summaryrefslogtreecommitdiff
path: root/vendor
diff options
context:
space:
mode:
authorhwajeong.son <hwajeong.son@samsung.com>2018-08-20 13:30:55 +0900
committerhwajeong.son <hwajeong.son@samsung.com>2018-08-20 13:30:55 +0900
commit0b51891e5977b87f986f4db2cbbe09295cfdbedc (patch)
treec35ac732cb1dffccee5a32131431f753481077c2 /vendor
parenteea0e89806b2cf59af3dccabc67014bd19b91b82 (diff)
downloaddocker-engine-0b51891e5977b87f986f4db2cbbe09295cfdbedc.tar.gz
docker-engine-0b51891e5977b87f986f4db2cbbe09295cfdbedc.tar.bz2
docker-engine-0b51891e5977b87f986f4db2cbbe09295cfdbedc.zip
Signed-off-by: hwajeong.son <hwajeong.son@samsung.com>
Diffstat (limited to 'vendor')
-rw-r--r--vendor/cloud.google.com/go/LICENSE202
-rw-r--r--vendor/cloud.google.com/go/README.md452
-rw-r--r--vendor/cloud.google.com/go/compute/metadata/metadata.go438
-rw-r--r--vendor/cloud.google.com/go/internal/cloud.go64
-rw-r--r--vendor/cloud.google.com/go/internal/retry.go55
-rw-r--r--vendor/cloud.google.com/go/logging/apiv2/README.md11
-rw-r--r--vendor/cloud.google.com/go/logging/apiv2/config_client.go300
-rw-r--r--vendor/cloud.google.com/go/logging/apiv2/doc.go26
-rw-r--r--vendor/cloud.google.com/go/logging/apiv2/logging_client.go359
-rw-r--r--vendor/cloud.google.com/go/logging/apiv2/metrics_client.go299
-rw-r--r--vendor/cloud.google.com/go/logging/doc.go89
-rw-r--r--vendor/cloud.google.com/go/logging/internal/common.go30
-rw-r--r--vendor/cloud.google.com/go/logging/logging.go674
-rw-r--r--vendor/github.com/Azure/go-ansiterm/LICENSE21
-rw-r--r--vendor/github.com/Azure/go-ansiterm/README.md9
-rw-r--r--vendor/github.com/Azure/go-ansiterm/constants.go188
-rw-r--r--vendor/github.com/Azure/go-ansiterm/context.go7
-rw-r--r--vendor/github.com/Azure/go-ansiterm/csi_entry_state.go49
-rw-r--r--vendor/github.com/Azure/go-ansiterm/csi_param_state.go38
-rw-r--r--vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go36
-rw-r--r--vendor/github.com/Azure/go-ansiterm/escape_state.go47
-rw-r--r--vendor/github.com/Azure/go-ansiterm/event_handler.go90
-rw-r--r--vendor/github.com/Azure/go-ansiterm/ground_state.go24
-rw-r--r--vendor/github.com/Azure/go-ansiterm/osc_string_state.go31
-rw-r--r--vendor/github.com/Azure/go-ansiterm/parser.go136
-rw-r--r--vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go103
-rw-r--r--vendor/github.com/Azure/go-ansiterm/parser_actions.go122
-rw-r--r--vendor/github.com/Azure/go-ansiterm/states.go71
-rw-r--r--vendor/github.com/Azure/go-ansiterm/utilities.go21
-rw-r--r--vendor/github.com/Azure/go-ansiterm/winterm/ansi.go182
-rw-r--r--vendor/github.com/Azure/go-ansiterm/winterm/api.go322
-rw-r--r--vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go100
-rw-r--r--vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go101
-rw-r--r--vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go84
-rw-r--r--vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go118
-rw-r--r--vendor/github.com/Azure/go-ansiterm/winterm/utilities.go9
-rw-r--r--vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go726
-rw-r--r--vendor/github.com/BurntSushi/toml/COPYING14
-rw-r--r--vendor/github.com/BurntSushi/toml/README.md220
-rw-r--r--vendor/github.com/BurntSushi/toml/decode.go492
-rw-r--r--vendor/github.com/BurntSushi/toml/decode_meta.go122
-rw-r--r--vendor/github.com/BurntSushi/toml/doc.go27
-rw-r--r--vendor/github.com/BurntSushi/toml/encode.go496
-rw-r--r--vendor/github.com/BurntSushi/toml/encoding_types.go19
-rw-r--r--vendor/github.com/BurntSushi/toml/encoding_types_1.1.go18
-rw-r--r--vendor/github.com/BurntSushi/toml/lex.go874
-rw-r--r--vendor/github.com/BurntSushi/toml/parse.go498
-rw-r--r--vendor/github.com/BurntSushi/toml/type_check.go91
-rw-r--r--vendor/github.com/BurntSushi/toml/type_fields.go241
-rw-r--r--vendor/github.com/Graylog2/go-gelf/LICENSE21
-rw-r--r--vendor/github.com/Graylog2/go-gelf/README.md76
-rw-r--r--vendor/github.com/Graylog2/go-gelf/gelf/reader.go140
-rw-r--r--vendor/github.com/Graylog2/go-gelf/gelf/writer.go418
-rw-r--r--vendor/github.com/Microsoft/go-winio/LICENSE22
-rw-r--r--vendor/github.com/Microsoft/go-winio/README.md22
-rw-r--r--vendor/github.com/Microsoft/go-winio/archive/tar/LICENSE27
-rw-r--r--vendor/github.com/Microsoft/go-winio/archive/tar/common.go344
-rw-r--r--vendor/github.com/Microsoft/go-winio/archive/tar/reader.go1002
-rw-r--r--vendor/github.com/Microsoft/go-winio/archive/tar/stat_atim.go20
-rw-r--r--vendor/github.com/Microsoft/go-winio/archive/tar/stat_atimespec.go20
-rw-r--r--vendor/github.com/Microsoft/go-winio/archive/tar/stat_unix.go32
-rw-r--r--vendor/github.com/Microsoft/go-winio/archive/tar/writer.go444
-rw-r--r--vendor/github.com/Microsoft/go-winio/backup.go270
-rw-r--r--vendor/github.com/Microsoft/go-winio/backuptar/noop.go4
-rw-r--r--vendor/github.com/Microsoft/go-winio/backuptar/tar.go353
-rw-r--r--vendor/github.com/Microsoft/go-winio/file.go295
-rw-r--r--vendor/github.com/Microsoft/go-winio/fileinfo.go60
-rw-r--r--vendor/github.com/Microsoft/go-winio/pipe.go404
-rw-r--r--vendor/github.com/Microsoft/go-winio/privilege.go202
-rw-r--r--vendor/github.com/Microsoft/go-winio/reparse.go128
-rw-r--r--vendor/github.com/Microsoft/go-winio/sd.go98
-rw-r--r--vendor/github.com/Microsoft/go-winio/syscall.go3
-rw-r--r--vendor/github.com/Microsoft/go-winio/zsyscall_windows.go528
-rw-r--r--vendor/github.com/Microsoft/hcsshim/LICENSE21
-rw-r--r--vendor/github.com/Microsoft/hcsshim/README.md12
-rw-r--r--vendor/github.com/Microsoft/hcsshim/activatelayer.go28
-rw-r--r--vendor/github.com/Microsoft/hcsshim/baselayer.go183
-rw-r--r--vendor/github.com/Microsoft/hcsshim/callback.go79
-rw-r--r--vendor/github.com/Microsoft/hcsshim/cgo.go7
-rw-r--r--vendor/github.com/Microsoft/hcsshim/container.go738
-rw-r--r--vendor/github.com/Microsoft/hcsshim/createlayer.go27
-rw-r--r--vendor/github.com/Microsoft/hcsshim/createsandboxlayer.go35
-rw-r--r--vendor/github.com/Microsoft/hcsshim/deactivatelayer.go26
-rw-r--r--vendor/github.com/Microsoft/hcsshim/destroylayer.go27
-rw-r--r--vendor/github.com/Microsoft/hcsshim/errors.go239
-rw-r--r--vendor/github.com/Microsoft/hcsshim/expandsandboxsize.go26
-rw-r--r--vendor/github.com/Microsoft/hcsshim/exportlayer.go156
-rw-r--r--vendor/github.com/Microsoft/hcsshim/getlayermountpath.go55
-rw-r--r--vendor/github.com/Microsoft/hcsshim/getsharedbaseimages.go22
-rw-r--r--vendor/github.com/Microsoft/hcsshim/guid.go19
-rw-r--r--vendor/github.com/Microsoft/hcsshim/hcsshim.go166
-rw-r--r--vendor/github.com/Microsoft/hcsshim/hnsfuncs.go271
-rw-r--r--vendor/github.com/Microsoft/hcsshim/importlayer.go212
-rw-r--r--vendor/github.com/Microsoft/hcsshim/interface.go174
-rw-r--r--vendor/github.com/Microsoft/hcsshim/layerexists.go30
-rw-r--r--vendor/github.com/Microsoft/hcsshim/layerutils.go111
-rw-r--r--vendor/github.com/Microsoft/hcsshim/legacy.go731
-rw-r--r--vendor/github.com/Microsoft/hcsshim/nametoguid.go20
-rw-r--r--vendor/github.com/Microsoft/hcsshim/preparelayer.go46
-rw-r--r--vendor/github.com/Microsoft/hcsshim/process.go384
-rw-r--r--vendor/github.com/Microsoft/hcsshim/processimage.go23
-rw-r--r--vendor/github.com/Microsoft/hcsshim/unpreparelayer.go27
-rw-r--r--vendor/github.com/Microsoft/hcsshim/utils.go33
-rw-r--r--vendor/github.com/Microsoft/hcsshim/version.go7
-rw-r--r--vendor/github.com/Microsoft/hcsshim/waithelper.go63
-rw-r--r--vendor/github.com/Microsoft/hcsshim/zhcsshim.go1042
-rw-r--r--vendor/github.com/Nvveen/Gotty/LICENSE26
-rw-r--r--vendor/github.com/Nvveen/Gotty/README5
-rw-r--r--vendor/github.com/Nvveen/Gotty/attributes.go514
-rw-r--r--vendor/github.com/Nvveen/Gotty/gotty.go244
-rw-r--r--vendor/github.com/Nvveen/Gotty/parser.go362
-rw-r--r--vendor/github.com/Nvveen/Gotty/types.go23
-rw-r--r--vendor/github.com/RackSec/srslog/LICENSE27
-rw-r--r--vendor/github.com/RackSec/srslog/README.md131
-rw-r--r--vendor/github.com/RackSec/srslog/constants.go68
-rw-r--r--vendor/github.com/RackSec/srslog/dialer.go87
-rw-r--r--vendor/github.com/RackSec/srslog/formatter.go48
-rw-r--r--vendor/github.com/RackSec/srslog/framer.go24
-rw-r--r--vendor/github.com/RackSec/srslog/net_conn.go30
-rw-r--r--vendor/github.com/RackSec/srslog/srslog.go97
-rw-r--r--vendor/github.com/RackSec/srslog/srslog_unix.go54
-rw-r--r--vendor/github.com/RackSec/srslog/writer.go185
-rw-r--r--vendor/github.com/Sirupsen/logrus/LICENSE21
-rw-r--r--vendor/github.com/Sirupsen/logrus/README.md425
-rw-r--r--vendor/github.com/Sirupsen/logrus/alt_exit.go64
-rw-r--r--vendor/github.com/Sirupsen/logrus/doc.go26
-rw-r--r--vendor/github.com/Sirupsen/logrus/entry.go275
-rw-r--r--vendor/github.com/Sirupsen/logrus/exported.go193
-rw-r--r--vendor/github.com/Sirupsen/logrus/formatter.go45
-rw-r--r--vendor/github.com/Sirupsen/logrus/hooks.go34
-rw-r--r--vendor/github.com/Sirupsen/logrus/json_formatter.go41
-rw-r--r--vendor/github.com/Sirupsen/logrus/logger.go308
-rw-r--r--vendor/github.com/Sirupsen/logrus/logrus.go143
-rw-r--r--vendor/github.com/Sirupsen/logrus/terminal_appengine.go8
-rw-r--r--vendor/github.com/Sirupsen/logrus/terminal_bsd.go10
-rw-r--r--vendor/github.com/Sirupsen/logrus/terminal_linux.go14
-rw-r--r--vendor/github.com/Sirupsen/logrus/terminal_notwindows.go22
-rw-r--r--vendor/github.com/Sirupsen/logrus/terminal_solaris.go15
-rw-r--r--vendor/github.com/Sirupsen/logrus/terminal_windows.go27
-rw-r--r--vendor/github.com/Sirupsen/logrus/text_formatter.go168
-rw-r--r--vendor/github.com/Sirupsen/logrus/writer.go53
-rw-r--r--vendor/github.com/agl/ed25519/LICENSE27
-rw-r--r--vendor/github.com/agl/ed25519/ed25519.go125
-rw-r--r--vendor/github.com/agl/ed25519/edwards25519/const.go1411
-rw-r--r--vendor/github.com/agl/ed25519/edwards25519/edwards25519.go2127
-rw-r--r--vendor/github.com/armon/go-metrics/LICENSE20
-rw-r--r--vendor/github.com/armon/go-metrics/README.md68
-rw-r--r--vendor/github.com/armon/go-metrics/const_unix.go12
-rw-r--r--vendor/github.com/armon/go-metrics/const_windows.go13
-rw-r--r--vendor/github.com/armon/go-metrics/inmem.go239
-rw-r--r--vendor/github.com/armon/go-metrics/inmem_signal.go100
-rwxr-xr-xvendor/github.com/armon/go-metrics/metrics.go115
-rwxr-xr-xvendor/github.com/armon/go-metrics/sink.go52
-rwxr-xr-xvendor/github.com/armon/go-metrics/start.go95
-rw-r--r--vendor/github.com/armon/go-metrics/statsd.go154
-rwxr-xr-xvendor/github.com/armon/go-metrics/statsite.go142
-rw-r--r--vendor/github.com/armon/go-radix/LICENSE20
-rw-r--r--vendor/github.com/armon/go-radix/README.md36
-rw-r--r--vendor/github.com/armon/go-radix/radix.go467
-rw-r--r--vendor/github.com/aws/aws-sdk-go/LICENSE.txt202
-rw-r--r--vendor/github.com/aws/aws-sdk-go/NOTICE.txt3
-rw-r--r--vendor/github.com/aws/aws-sdk-go/README.md116
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go145
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go194
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go108
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go27
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go222
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go107
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go89
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/client/client.go137
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go90
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go12
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/config.go419
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/convert_types.go369
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go182
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go17
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go100
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go223
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go178
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go191
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go77
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go151
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go57
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go161
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go130
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go162
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go124
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/errors.go17
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/logger.go112
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go187
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go24
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go58
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/request/request.go344
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go104
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go101
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/request/validation.go234
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/session/doc.go223
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go188
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/session/session.go393
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go295
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go82
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go24
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path_1_4.go24
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go713
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/types.go106
-rw-r--r--vendor/github.com/aws/aws-sdk-go/aws/version.go8
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/README.md4
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/endpoints/endpoints.go70
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/endpoints/endpoints_map.go95
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go75
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go254
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go213
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go111
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go36
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go230
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go35
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go66
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go256
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go45
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go198
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go21
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go293
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go260
-rw-r--r--vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go105
-rw-r--r--vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go4516
-rw-r--r--vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go117
-rw-r--r--vendor/github.com/aws/aws-sdk-go/service/sts/api.go1894
-rw-r--r--vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go12
-rw-r--r--vendor/github.com/aws/aws-sdk-go/service/sts/service.go130
-rw-r--r--vendor/github.com/beorn7/perks/LICENSE20
-rw-r--r--vendor/github.com/beorn7/perks/README.md31
-rw-r--r--vendor/github.com/beorn7/perks/quantile/stream.go292
-rw-r--r--vendor/github.com/boltdb/bolt/LICENSE20
-rw-r--r--vendor/github.com/boltdb/bolt/README.md857
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_386.go10
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_amd64.go10
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_arm.go28
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_arm64.go12
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_linux.go10
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_openbsd.go27
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_ppc.go9
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_ppc64.go9
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_ppc64le.go12
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_s390x.go12
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_unix.go89
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_unix_solaris.go90
-rw-r--r--vendor/github.com/boltdb/bolt/bolt_windows.go144
-rw-r--r--vendor/github.com/boltdb/bolt/boltsync_unix.go8
-rw-r--r--vendor/github.com/boltdb/bolt/bucket.go778
-rw-r--r--vendor/github.com/boltdb/bolt/cursor.go400
-rw-r--r--vendor/github.com/boltdb/bolt/db.go1036
-rw-r--r--vendor/github.com/boltdb/bolt/doc.go44
-rw-r--r--vendor/github.com/boltdb/bolt/errors.go71
-rw-r--r--vendor/github.com/boltdb/bolt/freelist.go248
-rw-r--r--vendor/github.com/boltdb/bolt/node.go604
-rw-r--r--vendor/github.com/boltdb/bolt/page.go178
-rw-r--r--vendor/github.com/boltdb/bolt/tx.go682
-rw-r--r--vendor/github.com/bsphere/le_go/LICENSE21
-rw-r--r--vendor/github.com/bsphere/le_go/README.md37
-rw-r--r--vendor/github.com/bsphere/le_go/le.go216
-rw-r--r--vendor/github.com/cloudflare/cfssl/LICENSE24
-rw-r--r--vendor/github.com/cloudflare/cfssl/README.md438
-rw-r--r--vendor/github.com/cloudflare/cfssl/api/api.go231
-rw-r--r--vendor/github.com/cloudflare/cfssl/auth/auth.go94
-rw-r--r--vendor/github.com/cloudflare/cfssl/certdb/README.md75
-rw-r--r--vendor/github.com/cloudflare/cfssl/certdb/certdb.go40
-rw-r--r--vendor/github.com/cloudflare/cfssl/config/config.go659
-rw-r--r--vendor/github.com/cloudflare/cfssl/crypto/pkcs7/pkcs7.go188
-rw-r--r--vendor/github.com/cloudflare/cfssl/csr/csr.go431
-rw-r--r--vendor/github.com/cloudflare/cfssl/errors/doc.go46
-rw-r--r--vendor/github.com/cloudflare/cfssl/errors/error.go424
-rw-r--r--vendor/github.com/cloudflare/cfssl/errors/http.go47
-rw-r--r--vendor/github.com/cloudflare/cfssl/helpers/derhelpers/derhelpers.go42
-rw-r--r--vendor/github.com/cloudflare/cfssl/helpers/helpers.go518
-rw-r--r--vendor/github.com/cloudflare/cfssl/info/info.go15
-rw-r--r--vendor/github.com/cloudflare/cfssl/initca/initca.go224
-rw-r--r--vendor/github.com/cloudflare/cfssl/log/log.go162
-rw-r--r--vendor/github.com/cloudflare/cfssl/ocsp/config/config.go13
-rw-r--r--vendor/github.com/cloudflare/cfssl/signer/local/local.go469
-rw-r--r--vendor/github.com/cloudflare/cfssl/signer/signer.go412
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/LICENSE201
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/NOTICE9
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/README.md22
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/concrete_sigar.go69
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/sigar_darwin.go467
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/sigar_format.go126
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/sigar_interface.go141
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/sigar_linux.go386
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/sigar_unix.go26
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/sigar_util.go22
-rw-r--r--vendor/github.com/cloudfoundry/gosigar/sigar_windows.go100
-rw-r--r--vendor/github.com/containerd/console/LICENSE24
-rw-r--r--vendor/github.com/containerd/console/README.md44
-rw-r--r--vendor/github.com/containerd/console/console.go52
-rw-r--r--vendor/github.com/containerd/console/console_unix.go133
-rw-r--r--vendor/github.com/containerd/console/console_windows.go199
-rw-r--r--vendor/github.com/containerd/console/tc_darwin.go51
-rw-r--r--vendor/github.com/containerd/console/tc_freebsd.go51
-rw-r--r--vendor/github.com/containerd/console/tc_linux.go51
-rw-r--r--vendor/github.com/containerd/containerd/LICENSE.code191
-rw-r--r--vendor/github.com/containerd/containerd/LICENSE.docs425
-rw-r--r--vendor/github.com/containerd/containerd/NOTICE16
-rw-r--r--vendor/github.com/containerd/containerd/README.md72
-rw-r--r--vendor/github.com/containerd/containerd/api/grpc/server/server.go494
-rw-r--r--vendor/github.com/containerd/containerd/api/grpc/server/server_linux.go66
-rw-r--r--vendor/github.com/containerd/containerd/api/grpc/server/server_solaris.go41
-rw-r--r--vendor/github.com/containerd/containerd/api/grpc/types/api.pb.go2584
-rw-r--r--vendor/github.com/containerd/containerd/api/grpc/types/api.proto344
-rw-r--r--vendor/github.com/containerd/containerd/api/http/pprof/pprof.go19
-rw-r--r--vendor/github.com/containerd/containerd/archutils/epoll.go22
-rw-r--r--vendor/github.com/containerd/containerd/archutils/epoll_arm64.go73
-rw-r--r--vendor/github.com/containerd/containerd/containerd-shim/console.go56
-rw-r--r--vendor/github.com/containerd/containerd/containerd-shim/console_solaris.go14
-rw-r--r--vendor/github.com/containerd/containerd/containerd-shim/main.go169
-rw-r--r--vendor/github.com/containerd/containerd/containerd-shim/process.go308
-rw-r--r--vendor/github.com/containerd/containerd/containerd-shim/process_linux.go190
-rw-r--r--vendor/github.com/containerd/containerd/containerd-shim/process_solaris.go74
-rw-r--r--vendor/github.com/containerd/containerd/containerd/main.go280
-rw-r--r--vendor/github.com/containerd/containerd/containerd/main_linux.go45
-rw-r--r--vendor/github.com/containerd/containerd/containerd/main_solaris.go4
-rw-r--r--vendor/github.com/containerd/containerd/ctr/checkpoint_linux.go165
-rw-r--r--vendor/github.com/containerd/containerd/ctr/checkpoint_solaris.go36
-rw-r--r--vendor/github.com/containerd/containerd/ctr/const.go12
-rw-r--r--vendor/github.com/containerd/containerd/ctr/container.go718
-rw-r--r--vendor/github.com/containerd/containerd/ctr/events.go63
-rw-r--r--vendor/github.com/containerd/containerd/ctr/main.go90
-rw-r--r--vendor/github.com/containerd/containerd/ctr/sort.go27
-rw-r--r--vendor/github.com/containerd/containerd/osutils/fds.go18
-rw-r--r--vendor/github.com/containerd/containerd/osutils/pdeathsig_linux.go15
-rw-r--r--vendor/github.com/containerd/containerd/osutils/pdeathsig_solaris.go8
-rw-r--r--vendor/github.com/containerd/containerd/osutils/prctl.go48
-rw-r--r--vendor/github.com/containerd/containerd/osutils/prctl_solaris.go19
-rw-r--r--vendor/github.com/containerd/containerd/osutils/reaper.go51
-rw-r--r--vendor/github.com/containerd/containerd/runtime/container.go748
-rw-r--r--vendor/github.com/containerd/containerd/runtime/container_linux.go190
-rw-r--r--vendor/github.com/containerd/containerd/runtime/container_solaris.go48
-rw-r--r--vendor/github.com/containerd/containerd/runtime/process.go476
-rw-r--r--vendor/github.com/containerd/containerd/runtime/process_linux.go22
-rw-r--r--vendor/github.com/containerd/containerd/runtime/process_solaris.go34
-rw-r--r--vendor/github.com/containerd/containerd/runtime/runtime.go132
-rw-r--r--vendor/github.com/containerd/containerd/runtime/stats.go87
-rw-r--r--vendor/github.com/containerd/containerd/specs/spec_linux.go12
-rw-r--r--vendor/github.com/containerd/containerd/specs/spec_solaris.go10
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/add_process.go53
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/checkpoint.go37
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/create.go71
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/create_solaris.go8
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/delete.go56
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/errors.go28
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/exit.go93
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/get_containers.go47
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/machine.go28
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/machine_solaris.go41
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/metrics.go42
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/monitor_linux.go147
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/monitor_solaris.go144
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/oom.go23
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/signal.go30
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/sort.go27
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/stats.go34
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/supervisor.go452
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/task.go34
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/types.go12
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/update.go95
-rw-r--r--vendor/github.com/containerd/containerd/supervisor/worker.go104
-rw-r--r--vendor/github.com/containerd/containerd/version.go20
-rw-r--r--vendor/github.com/containerd/go-runc/LICENSE24
-rw-r--r--vendor/github.com/containerd/go-runc/README.md42
-rw-r--r--vendor/github.com/containerd/go-runc/console.go98
-rw-r--r--vendor/github.com/containerd/go-runc/container.go14
-rw-r--r--vendor/github.com/containerd/go-runc/events.go84
-rw-r--r--vendor/github.com/containerd/go-runc/io.go165
-rw-r--r--vendor/github.com/containerd/go-runc/monitor.go50
-rw-r--r--vendor/github.com/containerd/go-runc/runc.go553
-rw-r--r--vendor/github.com/containerd/go-runc/utils.go28
-rw-r--r--vendor/github.com/coreos/etcd/LICENSE202
-rw-r--r--vendor/github.com/coreos/etcd/NOTICE5
-rw-r--r--vendor/github.com/coreos/etcd/README.md139
-rw-r--r--vendor/github.com/coreos/etcd/pkg/README.md2
-rw-r--r--vendor/github.com/coreos/etcd/pkg/crc/crc.go43
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/dir_unix.go22
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/dir_windows.go46
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/fileutil.go121
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/lock.go26
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/lock_flock.go49
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/lock_linux.go96
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/lock_plan9.go45
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/lock_solaris.go62
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/lock_unix.go29
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/lock_windows.go125
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/preallocate.go47
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_darwin.go43
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_unix.go49
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_unsupported.go25
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/purge.go78
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/sync.go29
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/sync_darwin.go40
-rw-r--r--vendor/github.com/coreos/etcd/pkg/fileutil/sync_linux.go34
-rw-r--r--vendor/github.com/coreos/etcd/pkg/idutil/id.go78
-rw-r--r--vendor/github.com/coreos/etcd/pkg/ioutil/pagewriter.go106
-rw-r--r--vendor/github.com/coreos/etcd/pkg/ioutil/readcloser.go66
-rw-r--r--vendor/github.com/coreos/etcd/pkg/ioutil/reader.go40
-rw-r--r--vendor/github.com/coreos/etcd/pkg/ioutil/util.go43
-rw-r--r--vendor/github.com/coreos/etcd/pkg/pbutil/pbutil.go60
-rw-r--r--vendor/github.com/coreos/etcd/raft/README.md247
-rw-r--r--vendor/github.com/coreos/etcd/raft/doc.go300
-rw-r--r--vendor/github.com/coreos/etcd/raft/log.go358
-rw-r--r--vendor/github.com/coreos/etcd/raft/log_unstable.go139
-rw-r--r--vendor/github.com/coreos/etcd/raft/logger.go126
-rw-r--r--vendor/github.com/coreos/etcd/raft/node.go521
-rw-r--r--vendor/github.com/coreos/etcd/raft/progress.go279
-rw-r--r--vendor/github.com/coreos/etcd/raft/raft.go1252
-rw-r--r--vendor/github.com/coreos/etcd/raft/raftpb/raft.pb.go1900
-rw-r--r--vendor/github.com/coreos/etcd/raft/raftpb/raft.proto93
-rw-r--r--vendor/github.com/coreos/etcd/raft/rawnode.go264
-rw-r--r--vendor/github.com/coreos/etcd/raft/read_only.go118
-rw-r--r--vendor/github.com/coreos/etcd/raft/status.go76
-rw-r--r--vendor/github.com/coreos/etcd/raft/storage.go271
-rw-r--r--vendor/github.com/coreos/etcd/raft/util.go129
-rw-r--r--vendor/github.com/coreos/etcd/snap/db.go74
-rw-r--r--vendor/github.com/coreos/etcd/snap/message.go64
-rw-r--r--vendor/github.com/coreos/etcd/snap/metrics.go41
-rw-r--r--vendor/github.com/coreos/etcd/snap/snappb/snap.pb.go353
-rw-r--r--vendor/github.com/coreos/etcd/snap/snappb/snap.proto14
-rw-r--r--vendor/github.com/coreos/etcd/snap/snapshotter.go204
-rw-r--r--vendor/github.com/coreos/etcd/wal/decoder.go185
-rw-r--r--vendor/github.com/coreos/etcd/wal/doc.go75
-rw-r--r--vendor/github.com/coreos/etcd/wal/encoder.go120
-rw-r--r--vendor/github.com/coreos/etcd/wal/file_pipeline.go97
-rw-r--r--vendor/github.com/coreos/etcd/wal/metrics.go31
-rw-r--r--vendor/github.com/coreos/etcd/wal/repair.go99
-rw-r--r--vendor/github.com/coreos/etcd/wal/util.go107
-rw-r--r--vendor/github.com/coreos/etcd/wal/wal.go637
-rw-r--r--vendor/github.com/coreos/etcd/wal/wal_unix.go44
-rw-r--r--vendor/github.com/coreos/etcd/wal/wal_windows.go41
-rw-r--r--vendor/github.com/coreos/etcd/wal/walpb/record.go29
-rw-r--r--vendor/github.com/coreos/etcd/wal/walpb/record.pb.go521
-rw-r--r--vendor/github.com/coreos/etcd/wal/walpb/record.proto20
-rw-r--r--vendor/github.com/coreos/go-systemd/LICENSE191
-rw-r--r--vendor/github.com/coreos/go-systemd/README.md54
-rw-r--r--vendor/github.com/coreos/go-systemd/activation/files.go52
-rw-r--r--vendor/github.com/coreos/go-systemd/activation/listeners.go60
-rw-r--r--vendor/github.com/coreos/go-systemd/activation/packetconns.go37
-rw-r--r--vendor/github.com/coreos/go-systemd/daemon/sdnotify.go63
-rw-r--r--vendor/github.com/coreos/go-systemd/daemon/watchdog.go72
-rw-r--r--vendor/github.com/coreos/go-systemd/dbus/dbus.go213
-rw-r--r--vendor/github.com/coreos/go-systemd/dbus/methods.go565
-rw-r--r--vendor/github.com/coreos/go-systemd/dbus/properties.go237
-rw-r--r--vendor/github.com/coreos/go-systemd/dbus/set.go47
-rw-r--r--vendor/github.com/coreos/go-systemd/dbus/subscription.go250
-rw-r--r--vendor/github.com/coreos/go-systemd/dbus/subscription_set.go57
-rw-r--r--vendor/github.com/coreos/go-systemd/journal/journal.go179
-rw-r--r--vendor/github.com/coreos/go-systemd/util/util.go90
-rw-r--r--vendor/github.com/coreos/go-systemd/util/util_cgo.go174
-rw-r--r--vendor/github.com/coreos/go-systemd/util/util_stub.go23
-rw-r--r--vendor/github.com/coreos/pkg/LICENSE202
-rw-r--r--vendor/github.com/coreos/pkg/NOTICE5
-rw-r--r--vendor/github.com/coreos/pkg/README.md4
-rw-r--r--vendor/github.com/coreos/pkg/capnslog/README.md39
-rw-r--r--vendor/github.com/coreos/pkg/capnslog/formatters.go157
-rw-r--r--vendor/github.com/coreos/pkg/capnslog/glog_formatter.go96
-rw-r--r--vendor/github.com/coreos/pkg/capnslog/init.go49
-rw-r--r--vendor/github.com/coreos/pkg/capnslog/init_windows.go25
-rw-r--r--vendor/github.com/coreos/pkg/capnslog/journald_formatter.go68
-rw-r--r--vendor/github.com/coreos/pkg/capnslog/log_hijack.go39
-rw-r--r--vendor/github.com/coreos/pkg/capnslog/logmap.go240
-rw-r--r--vendor/github.com/coreos/pkg/capnslog/pkg_logger.go177
-rw-r--r--vendor/github.com/coreos/pkg/capnslog/syslog_formatter.go65
-rw-r--r--vendor/github.com/coreos/pkg/dlopen/dlopen.go82
-rw-r--r--vendor/github.com/coreos/pkg/dlopen/dlopen_example.go56
-rw-r--r--vendor/github.com/cyberdelia/go-metrics-graphite/LICENSE22
-rw-r--r--vendor/github.com/cyberdelia/go-metrics-graphite/README.md19
-rw-r--r--vendor/github.com/cyberdelia/go-metrics-graphite/graphite.go113
-rw-r--r--vendor/github.com/davecgh/go-spew/LICENSE15
-rw-r--r--vendor/github.com/davecgh/go-spew/README.md205
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/bypass.go152
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/bypasssafe.go38
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/common.go341
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/config.go306
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/doc.go211
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/dump.go509
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/format.go419
-rw-r--r--vendor/github.com/davecgh/go-spew/spew/spew.go148
-rw-r--r--vendor/github.com/deckarep/golang-set/LICENSE22
-rw-r--r--vendor/github.com/deckarep/golang-set/README.md94
-rw-r--r--vendor/github.com/deckarep/golang-set/set.go168
-rw-r--r--vendor/github.com/deckarep/golang-set/threadsafe.go204
-rw-r--r--vendor/github.com/deckarep/golang-set/threadunsafe.go246
-rw-r--r--vendor/github.com/docker/cli/LICENSE191
-rw-r--r--vendor/github.com/docker/cli/NOTICE19
-rw-r--r--vendor/github.com/docker/cli/README.md63
-rw-r--r--vendor/github.com/docker/cli/VERSION1
-rw-r--r--vendor/github.com/docker/cli/cli/cobra.go150
-rw-r--r--vendor/github.com/docker/cli/cli/command/cli.go299
-rw-r--r--vendor/github.com/docker/cli/cli/command/commands/commands.go92
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/attach.go164
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/cmd.go46
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/commit.go75
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/cp.go305
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/create.go224
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/diff.go46
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/exec.go220
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/export.go58
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/hijack.go207
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/inspect.go46
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/kill.go56
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/list.go140
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/logs.go76
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/opts.go841
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/pause.go49
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/port.go78
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/prune.go78
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/rename.go51
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/restart.go62
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/rm.go73
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/run.go337
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/start.go195
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/stats.go243
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/stats_helpers.go238
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/stop.go67
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/top.go57
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/tty.go103
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/unpause.go50
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/update.go133
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/utils.go172
-rw-r--r--vendor/github.com/docker/cli/cli/command/container/wait.go53
-rw-r--r--vendor/github.com/docker/cli/cli/command/events_utils.go47
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/checkpoint.go52
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/config.go171
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/container.go345
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/custom.go35
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/diff.go72
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/disk_usage.go359
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/formatter.go119
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/history.go107
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/image.go272
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/network.go129
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/node.go330
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/plugin.go95
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/reflect.go66
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/secret.go162
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/service.go535
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/stack.go67
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/stats.go218
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/task.go150
-rw-r--r--vendor/github.com/docker/cli/cli/command/formatter/volume.go131
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/build.go503
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/build/context.go377
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/build/context_unix.go11
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/build/context_windows.go17
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/build/dockerignore.go39
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/cmd.go35
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/delta.go44
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/history.go64
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/import.go87
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/inspect.go44
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/list.go95
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/load.go77
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/prune.go95
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/pull.go85
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/push.go61
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/remove.go82
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/save.go56
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/tag.go41
-rw-r--r--vendor/github.com/docker/cli/cli/command/image/trust.go384
-rw-r--r--vendor/github.com/docker/cli/cli/command/in.go56
-rw-r--r--vendor/github.com/docker/cli/cli/command/inspect/inspector.go199
-rw-r--r--vendor/github.com/docker/cli/cli/command/network/cmd.go29
-rw-r--r--vendor/github.com/docker/cli/cli/command/network/connect.go62
-rw-r--r--vendor/github.com/docker/cli/cli/command/network/create.go248
-rw-r--r--vendor/github.com/docker/cli/cli/command/network/disconnect.go41
-rw-r--r--vendor/github.com/docker/cli/cli/command/network/inspect.go48
-rw-r--r--vendor/github.com/docker/cli/cli/command/network/list.go75
-rw-r--r--vendor/github.com/docker/cli/cli/command/network/prune.go76
-rw-r--r--vendor/github.com/docker/cli/cli/command/network/remove.go54
-rw-r--r--vendor/github.com/docker/cli/cli/command/out.go50
-rw-r--r--vendor/github.com/docker/cli/cli/command/prune/prune.go51
-rw-r--r--vendor/github.com/docker/cli/cli/command/registry.go189
-rw-r--r--vendor/github.com/docker/cli/cli/command/registry/login.go82
-rw-r--r--vendor/github.com/docker/cli/cli/command/registry/logout.go77
-rw-r--r--vendor/github.com/docker/cli/cli/command/registry/search.go125
-rw-r--r--vendor/github.com/docker/cli/cli/command/stream.go34
-rw-r--r--vendor/github.com/docker/cli/cli/command/system/cmd.go26
-rw-r--r--vendor/github.com/docker/cli/cli/command/system/df.go68
-rw-r--r--vendor/github.com/docker/cli/cli/command/system/events.go139
-rw-r--r--vendor/github.com/docker/cli/cli/command/system/info.go381
-rw-r--r--vendor/github.com/docker/cli/cli/command/system/inspect.go216
-rw-r--r--vendor/github.com/docker/cli/cli/command/system/prune.go103
-rw-r--r--vendor/github.com/docker/cli/cli/command/system/version.go130
-rw-r--r--vendor/github.com/docker/cli/cli/command/trust.go43
-rw-r--r--vendor/github.com/docker/cli/cli/command/utils.go119
-rw-r--r--vendor/github.com/docker/cli/cli/command/volume/cmd.go26
-rw-r--r--vendor/github.com/docker/cli/cli/command/volume/create.go69
-rw-r--r--vendor/github.com/docker/cli/cli/command/volume/inspect.go45
-rw-r--r--vendor/github.com/docker/cli/cli/command/volume/list.go73
-rw-r--r--vendor/github.com/docker/cli/cli/command/volume/prune.go78
-rw-r--r--vendor/github.com/docker/cli/cli/command/volume/remove.go69
-rw-r--r--vendor/github.com/docker/cli/cli/compose/interpolation/interpolation.go96
-rw-r--r--vendor/github.com/docker/cli/cli/compose/loader/loader.go714
-rw-r--r--vendor/github.com/docker/cli/cli/compose/loader/volume.go117
-rw-r--r--vendor/github.com/docker/cli/cli/compose/schema/bindata.go306
-rw-r--r--vendor/github.com/docker/cli/cli/compose/schema/schema.go168
-rw-r--r--vendor/github.com/docker/cli/cli/compose/template/template.go101
-rw-r--r--vendor/github.com/docker/cli/cli/compose/types/types.go337
-rw-r--r--vendor/github.com/docker/cli/cli/config/config.go120
-rw-r--r--vendor/github.com/docker/cli/cli/config/configfile/file.go233
-rw-r--r--vendor/github.com/docker/cli/cli/config/credentials/credentials.go17
-rw-r--r--vendor/github.com/docker/cli/cli/config/credentials/default_store.go22
-rw-r--r--vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go3
-rw-r--r--vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go3
-rw-r--r--vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go5
-rw-r--r--vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go3
-rw-r--r--vendor/github.com/docker/cli/cli/config/credentials/file_store.go53
-rw-r--r--vendor/github.com/docker/cli/cli/config/credentials/native_store.go144
-rw-r--r--vendor/github.com/docker/cli/cli/debug/debug.go26
-rw-r--r--vendor/github.com/docker/cli/cli/error.go33
-rw-r--r--vendor/github.com/docker/cli/cli/flags/client.go13
-rw-r--r--vendor/github.com/docker/cli/cli/flags/common.go117
-rw-r--r--vendor/github.com/docker/cli/cli/required.go96
-rw-r--r--vendor/github.com/docker/cli/cli/trust/trust.go232
-rw-r--r--vendor/github.com/docker/cli/cli/version.go9
-rw-r--r--vendor/github.com/docker/cli/cli/winresources/res_windows.go18
-rw-r--r--vendor/github.com/docker/cli/cmd/docker/daemon_none.go29
-rw-r--r--vendor/github.com/docker/cli/cmd/docker/daemon_unix.go79
-rw-r--r--vendor/github.com/docker/cli/cmd/docker/docker.go309
-rw-r--r--vendor/github.com/docker/cli/cmd/docker/docker_windows.go3
-rw-r--r--vendor/github.com/docker/cli/opts/config.go98
-rw-r--r--vendor/github.com/docker/cli/opts/duration.go64
-rw-r--r--vendor/github.com/docker/cli/opts/env.go46
-rw-r--r--vendor/github.com/docker/cli/opts/envfile.go81
-rw-r--r--vendor/github.com/docker/cli/opts/hosts.go165
-rw-r--r--vendor/github.com/docker/cli/opts/hosts_unix.go8
-rw-r--r--vendor/github.com/docker/cli/opts/hosts_windows.go6
-rw-r--r--vendor/github.com/docker/cli/opts/ip.go47
-rw-r--r--vendor/github.com/docker/cli/opts/mount.go174
-rw-r--r--vendor/github.com/docker/cli/opts/network.go106
-rw-r--r--vendor/github.com/docker/cli/opts/opts.go488
-rw-r--r--vendor/github.com/docker/cli/opts/opts_unix.go6
-rw-r--r--vendor/github.com/docker/cli/opts/opts_windows.go56
-rw-r--r--vendor/github.com/docker/cli/opts/parse.go87
-rw-r--r--vendor/github.com/docker/cli/opts/port.go163
-rw-r--r--vendor/github.com/docker/cli/opts/quotedstring.go37
-rw-r--r--vendor/github.com/docker/cli/opts/runtime.go79
-rw-r--r--vendor/github.com/docker/cli/opts/secret.go98
-rw-r--r--vendor/github.com/docker/cli/opts/throttledevice.go108
-rw-r--r--vendor/github.com/docker/cli/opts/ulimit.go57
-rw-r--r--vendor/github.com/docker/cli/opts/weightdevice.go84
-rwxr-xr-xvendor/github.com/docker/cli/vendor.conf51
-rw-r--r--vendor/github.com/docker/distribution/LICENSE202
-rw-r--r--vendor/github.com/docker/distribution/README.md131
-rw-r--r--vendor/github.com/docker/distribution/blobs.go257
-rw-r--r--vendor/github.com/docker/distribution/context/context.go85
-rw-r--r--vendor/github.com/docker/distribution/context/doc.go89
-rw-r--r--vendor/github.com/docker/distribution/context/http.go366
-rw-r--r--vendor/github.com/docker/distribution/context/logger.go116
-rw-r--r--vendor/github.com/docker/distribution/context/trace.go104
-rw-r--r--vendor/github.com/docker/distribution/context/util.go24
-rw-r--r--vendor/github.com/docker/distribution/context/version.go16
-rw-r--r--vendor/github.com/docker/distribution/digestset/set.go247
-rw-r--r--vendor/github.com/docker/distribution/doc.go7
-rw-r--r--vendor/github.com/docker/distribution/errors.go115
-rw-r--r--vendor/github.com/docker/distribution/manifest/doc.go1
-rw-r--r--vendor/github.com/docker/distribution/manifest/manifestlist/manifestlist.go155
-rw-r--r--vendor/github.com/docker/distribution/manifest/schema1/config_builder.go287
-rw-r--r--vendor/github.com/docker/distribution/manifest/schema1/manifest.go184
-rw-r--r--vendor/github.com/docker/distribution/manifest/schema1/reference_builder.go98
-rw-r--r--vendor/github.com/docker/distribution/manifest/schema1/sign.go68
-rw-r--r--vendor/github.com/docker/distribution/manifest/schema1/verify.go32
-rw-r--r--vendor/github.com/docker/distribution/manifest/schema2/builder.go84
-rw-r--r--vendor/github.com/docker/distribution/manifest/schema2/manifest.go138
-rw-r--r--vendor/github.com/docker/distribution/manifest/versioned.go12
-rw-r--r--vendor/github.com/docker/distribution/manifests.go125
-rw-r--r--vendor/github.com/docker/distribution/reference/helpers.go42
-rw-r--r--vendor/github.com/docker/distribution/reference/normalize.go170
-rw-r--r--vendor/github.com/docker/distribution/reference/reference.go433
-rw-r--r--vendor/github.com/docker/distribution/reference/regexp.go143
-rw-r--r--vendor/github.com/docker/distribution/registry.go97
-rw-r--r--vendor/github.com/docker/distribution/registry/api/errcode/errors.go267
-rw-r--r--vendor/github.com/docker/distribution/registry/api/errcode/handler.go44
-rw-r--r--vendor/github.com/docker/distribution/registry/api/errcode/register.go138
-rw-r--r--vendor/github.com/docker/distribution/registry/api/v2/descriptors.go1596
-rw-r--r--vendor/github.com/docker/distribution/registry/api/v2/doc.go9
-rw-r--r--vendor/github.com/docker/distribution/registry/api/v2/errors.go136
-rw-r--r--vendor/github.com/docker/distribution/registry/api/v2/headerparser.go161
-rw-r--r--vendor/github.com/docker/distribution/registry/api/v2/routes.go49
-rw-r--r--vendor/github.com/docker/distribution/registry/api/v2/urls.go314
-rw-r--r--vendor/github.com/docker/distribution/registry/client/auth/api_version.go58
-rw-r--r--vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go27
-rw-r--r--vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go237
-rw-r--r--vendor/github.com/docker/distribution/registry/client/auth/session.go505
-rw-r--r--vendor/github.com/docker/distribution/registry/client/blob_writer.go162
-rw-r--r--vendor/github.com/docker/distribution/registry/client/errors.go139
-rw-r--r--vendor/github.com/docker/distribution/registry/client/repository.go853
-rw-r--r--vendor/github.com/docker/distribution/registry/client/transport/http_reader.go251
-rw-r--r--vendor/github.com/docker/distribution/registry/client/transport/transport.go147
-rw-r--r--vendor/github.com/docker/distribution/registry/storage/cache/cache.go35
-rw-r--r--vendor/github.com/docker/distribution/registry/storage/cache/cachedblobdescriptorstore.go101
-rw-r--r--vendor/github.com/docker/distribution/registry/storage/cache/memory/memory.go179
-rw-r--r--vendor/github.com/docker/distribution/tags.go27
-rw-r--r--vendor/github.com/docker/distribution/uuid/uuid.go126
-rw-r--r--vendor/github.com/docker/distribution/vendor.conf41
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/LICENSE20
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/README.md76
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/client/client.go121
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/client/command.go44
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go177
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/credentials/error.go105
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/credentials/helper.go14
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.c228
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.go170
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.h14
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.c162
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.go115
-rw-r--r--vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.h13
-rw-r--r--vendor/github.com/docker/go-connections/LICENSE191
-rw-r--r--vendor/github.com/docker/go-connections/README.md13
-rw-r--r--vendor/github.com/docker/go-connections/nat/nat.go242
-rw-r--r--vendor/github.com/docker/go-connections/nat/parse.go57
-rw-r--r--vendor/github.com/docker/go-connections/nat/sort.go96
-rw-r--r--vendor/github.com/docker/go-connections/sockets/README.md0
-rw-r--r--vendor/github.com/docker/go-connections/sockets/inmem_socket.go81
-rw-r--r--vendor/github.com/docker/go-connections/sockets/proxy.go51
-rw-r--r--vendor/github.com/docker/go-connections/sockets/sockets.go38
-rw-r--r--vendor/github.com/docker/go-connections/sockets/sockets_unix.go35
-rw-r--r--vendor/github.com/docker/go-connections/sockets/sockets_windows.go27
-rw-r--r--vendor/github.com/docker/go-connections/sockets/tcp_socket.go22
-rw-r--r--vendor/github.com/docker/go-connections/sockets/unix_socket.go32
-rw-r--r--vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go18
-rw-r--r--vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go14
-rw-r--r--vendor/github.com/docker/go-connections/tlsconfig/config.go244
-rw-r--r--vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go17
-rw-r--r--vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go15
-rw-r--r--vendor/github.com/docker/go-events/LICENSE201
-rw-r--r--vendor/github.com/docker/go-events/README.md117
-rw-r--r--vendor/github.com/docker/go-events/broadcast.go178
-rw-r--r--vendor/github.com/docker/go-events/channel.go61
-rw-r--r--vendor/github.com/docker/go-events/errors.go10
-rw-r--r--vendor/github.com/docker/go-events/event.go15
-rw-r--r--vendor/github.com/docker/go-events/filter.go52
-rw-r--r--vendor/github.com/docker/go-events/queue.go111
-rw-r--r--vendor/github.com/docker/go-events/retry.go260
-rw-r--r--vendor/github.com/docker/go-metrics/LICENSE.code191
-rw-r--r--vendor/github.com/docker/go-metrics/LICENSE.docs425
-rw-r--r--vendor/github.com/docker/go-metrics/NOTICE16
-rw-r--r--vendor/github.com/docker/go-metrics/README.md79
-rw-r--r--vendor/github.com/docker/go-metrics/counter.go52
-rw-r--r--vendor/github.com/docker/go-metrics/docs.go3
-rw-r--r--vendor/github.com/docker/go-metrics/gauge.go72
-rw-r--r--vendor/github.com/docker/go-metrics/handler.go13
-rw-r--r--vendor/github.com/docker/go-metrics/helpers.go10
-rw-r--r--vendor/github.com/docker/go-metrics/namespace.go181
-rw-r--r--vendor/github.com/docker/go-metrics/register.go15
-rw-r--r--vendor/github.com/docker/go-metrics/timer.go68
-rw-r--r--vendor/github.com/docker/go-metrics/unit.go12
-rw-r--r--vendor/github.com/docker/go-units/LICENSE191
-rw-r--r--vendor/github.com/docker/go-units/README.md16
-rw-r--r--vendor/github.com/docker/go-units/duration.go35
-rw-r--r--vendor/github.com/docker/go-units/size.go108
-rw-r--r--vendor/github.com/docker/go-units/ulimit.go118
-rw-r--r--vendor/github.com/docker/go/LICENSE27
-rw-r--r--vendor/github.com/docker/go/README.md16
-rw-r--r--vendor/github.com/docker/go/canonical/json/decode.go1168
-rw-r--r--vendor/github.com/docker/go/canonical/json/encode.go1250
-rw-r--r--vendor/github.com/docker/go/canonical/json/fold.go143
-rw-r--r--vendor/github.com/docker/go/canonical/json/indent.go141
-rw-r--r--vendor/github.com/docker/go/canonical/json/scanner.go623
-rw-r--r--vendor/github.com/docker/go/canonical/json/stream.go487
-rw-r--r--vendor/github.com/docker/go/canonical/json/tags.go44
-rw-r--r--vendor/github.com/docker/libkv/LICENSE.code191
-rw-r--r--vendor/github.com/docker/libkv/LICENSE.docs425
-rw-r--r--vendor/github.com/docker/libkv/README.md107
-rw-r--r--vendor/github.com/docker/libkv/libkv.go40
-rw-r--r--vendor/github.com/docker/libkv/store/boltdb/boltdb.go474
-rw-r--r--vendor/github.com/docker/libkv/store/helpers.go47
-rw-r--r--vendor/github.com/docker/libkv/store/store.go132
-rw-r--r--vendor/github.com/docker/libnetwork/LICENSE202
-rw-r--r--vendor/github.com/docker/libnetwork/README.md89
-rw-r--r--vendor/github.com/docker/libnetwork/agent.go915
-rw-r--r--vendor/github.com/docker/libnetwork/agent.pb.go1003
-rw-r--r--vendor/github.com/docker/libnetwork/agent.proto72
-rw-r--r--vendor/github.com/docker/libnetwork/bitseq/sequence.go679
-rw-r--r--vendor/github.com/docker/libnetwork/bitseq/store.go141
-rw-r--r--vendor/github.com/docker/libnetwork/cluster/provider.go36
-rw-r--r--vendor/github.com/docker/libnetwork/cmd/proxy/main.go67
-rw-r--r--vendor/github.com/docker/libnetwork/cmd/proxy/proxy.go36
-rw-r--r--vendor/github.com/docker/libnetwork/cmd/proxy/stub_proxy.go31
-rw-r--r--vendor/github.com/docker/libnetwork/cmd/proxy/tcp_proxy.go89
-rw-r--r--vendor/github.com/docker/libnetwork/cmd/proxy/udp_proxy.go168
-rw-r--r--vendor/github.com/docker/libnetwork/common/setmatrix.go135
-rw-r--r--vendor/github.com/docker/libnetwork/config/config.go280
-rw-r--r--vendor/github.com/docker/libnetwork/controller.go1269
-rw-r--r--vendor/github.com/docker/libnetwork/datastore/cache.go178
-rw-r--r--vendor/github.com/docker/libnetwork/datastore/datastore.go660
-rw-r--r--vendor/github.com/docker/libnetwork/datastore/mock_store.go129
-rw-r--r--vendor/github.com/docker/libnetwork/default_gateway.go201
-rw-r--r--vendor/github.com/docker/libnetwork/default_gateway_freebsd.go13
-rw-r--r--vendor/github.com/docker/libnetwork/default_gateway_linux.go32
-rw-r--r--vendor/github.com/docker/libnetwork/default_gateway_solaris.go32
-rw-r--r--vendor/github.com/docker/libnetwork/default_gateway_windows.go22
-rw-r--r--vendor/github.com/docker/libnetwork/discoverapi/discoverapi.go60
-rw-r--r--vendor/github.com/docker/libnetwork/driverapi/driverapi.go213
-rw-r--r--vendor/github.com/docker/libnetwork/driverapi/errors.go56
-rw-r--r--vendor/github.com/docker/libnetwork/driverapi/ipamdata.go103
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/bridge.go1531
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/bridge_store.go388
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/brmanager/brmanager.go88
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/errors.go341
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/interface.go86
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/labels.go18
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/link.go85
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux.go131
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_armppc64.go7
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_notarm.go7
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_unsupported.go18
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/port_mapping.go128
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/setup.go26
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/setup_bridgenetfiltering.go163
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/setup_device.go68
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/setup_firewalld.go20
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_forwarding.go56
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_tables.go323
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv4.go80
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv6.go119
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/bridge/setup_verify.go73
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/host/host.go106
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan.go115
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_endpoint.go87
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_joinleave.go199
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_network.go250
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_setup.go205
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_state.go115
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_store.go349
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/ipvlan/ivmanager/ivmanager.go88
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/macvlan/mvmanager/mvmanager.go88
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/null/null.go105
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/overlay/ovmanager/ovmanager.go257
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/remote/api/api.go221
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/remote/driver.go409
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/bridge/bridge.go1263
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/bridge/bridge_store.go384
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/bridge/errors.go119
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/bridge/port_mapping.go225
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/overlay/encryption.go274
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/overlay/joinleave.go188
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_endpoint.go249
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_network.go786
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_serf.go233
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_utils.go61
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.go367
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.pb.go468
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.proto27
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/solaris/overlay/peerdb.go336
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/windows/labels.go39
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go107
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go216
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go380
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.pb.go468
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.proto27
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go159
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go120
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/windows/windows.go771
-rw-r--r--vendor/github.com/docker/libnetwork/drivers/windows/windows_store.go339
-rw-r--r--vendor/github.com/docker/libnetwork/drivers_experimental_linux.go9
-rw-r--r--vendor/github.com/docker/libnetwork/drivers_freebsd.go13
-rw-r--r--vendor/github.com/docker/libnetwork/drivers_ipam.go23
-rw-r--r--vendor/github.com/docker/libnetwork/drivers_linux.go22
-rw-r--r--vendor/github.com/docker/libnetwork/drivers_solaris.go15
-rw-r--r--vendor/github.com/docker/libnetwork/drivers_windows.go20
-rw-r--r--vendor/github.com/docker/libnetwork/drvregistry/drvregistry.go228
-rw-r--r--vendor/github.com/docker/libnetwork/endpoint.go1192
-rw-r--r--vendor/github.com/docker/libnetwork/endpoint_cnt.go178
-rw-r--r--vendor/github.com/docker/libnetwork/endpoint_info.go449
-rw-r--r--vendor/github.com/docker/libnetwork/endpoint_info_unix.go30
-rw-r--r--vendor/github.com/docker/libnetwork/endpoint_info_windows.go45
-rw-r--r--vendor/github.com/docker/libnetwork/error.go193
-rw-r--r--vendor/github.com/docker/libnetwork/etchosts/etchosts.go208
-rw-r--r--vendor/github.com/docker/libnetwork/firewall_linux.go29
-rw-r--r--vendor/github.com/docker/libnetwork/firewall_others.go6
-rw-r--r--vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery.go112
-rw-r--r--vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery_api.go22
-rw-r--r--vendor/github.com/docker/libnetwork/idm/idm.go76
-rw-r--r--vendor/github.com/docker/libnetwork/ipam/allocator.go601
-rw-r--r--vendor/github.com/docker/libnetwork/ipam/store.go136
-rw-r--r--vendor/github.com/docker/libnetwork/ipam/structures.go362
-rw-r--r--vendor/github.com/docker/libnetwork/ipam/utils.go81
-rw-r--r--vendor/github.com/docker/libnetwork/ipamapi/contract.go96
-rw-r--r--vendor/github.com/docker/libnetwork/ipams/builtin/builtin_unix.go43
-rw-r--r--vendor/github.com/docker/libnetwork/ipams/builtin/builtin_windows.go57
-rw-r--r--vendor/github.com/docker/libnetwork/ipams/null/null.go75
-rw-r--r--vendor/github.com/docker/libnetwork/ipams/remote/api/api.go94
-rw-r--r--vendor/github.com/docker/libnetwork/ipams/remote/remote.go155
-rw-r--r--vendor/github.com/docker/libnetwork/ipams/windowsipam/windowsipam.go107
-rw-r--r--vendor/github.com/docker/libnetwork/ipamutils/utils.go50
-rw-r--r--vendor/github.com/docker/libnetwork/iptables/conntrack.go59
-rw-r--r--vendor/github.com/docker/libnetwork/iptables/firewalld.go167
-rw-r--r--vendor/github.com/docker/libnetwork/iptables/iptables.go541
-rw-r--r--vendor/github.com/docker/libnetwork/ipvs/constants.go147
-rw-r--r--vendor/github.com/docker/libnetwork/ipvs/ipvs.go161
-rw-r--r--vendor/github.com/docker/libnetwork/ipvs/netlink.go546
-rw-r--r--vendor/github.com/docker/libnetwork/netlabel/labels.go129
-rw-r--r--vendor/github.com/docker/libnetwork/netutils/utils.go194
-rw-r--r--vendor/github.com/docker/libnetwork/netutils/utils_freebsd.go23
-rw-r--r--vendor/github.com/docker/libnetwork/netutils/utils_linux.go126
-rw-r--r--vendor/github.com/docker/libnetwork/netutils/utils_solaris.go104
-rw-r--r--vendor/github.com/docker/libnetwork/netutils/utils_windows.go25
-rw-r--r--vendor/github.com/docker/libnetwork/network.go2030
-rw-r--r--vendor/github.com/docker/libnetwork/network_unix.go14
-rw-r--r--vendor/github.com/docker/libnetwork/network_windows.go72
-rw-r--r--vendor/github.com/docker/libnetwork/networkdb/broadcast.go171
-rw-r--r--vendor/github.com/docker/libnetwork/networkdb/cluster.go663
-rw-r--r--vendor/github.com/docker/libnetwork/networkdb/delegate.go516
-rw-r--r--vendor/github.com/docker/libnetwork/networkdb/event_delegate.go68
-rw-r--r--vendor/github.com/docker/libnetwork/networkdb/message.go102
-rw-r--r--vendor/github.com/docker/libnetwork/networkdb/networkdb.go644
-rw-r--r--vendor/github.com/docker/libnetwork/networkdb/networkdb.pb.go2554
-rw-r--r--vendor/github.com/docker/libnetwork/networkdb/networkdb.proto183
-rw-r--r--vendor/github.com/docker/libnetwork/networkdb/watch.go110
-rw-r--r--vendor/github.com/docker/libnetwork/ns/init_linux.go140
-rw-r--r--vendor/github.com/docker/libnetwork/options/options.go88
-rw-r--r--vendor/github.com/docker/libnetwork/osl/interface_freebsd.go4
-rw-r--r--vendor/github.com/docker/libnetwork/osl/interface_linux.go469
-rw-r--r--vendor/github.com/docker/libnetwork/osl/interface_solaris.go4
-rw-r--r--vendor/github.com/docker/libnetwork/osl/interface_windows.go4
-rw-r--r--vendor/github.com/docker/libnetwork/osl/namespace_linux.go610
-rw-r--r--vendor/github.com/docker/libnetwork/osl/namespace_unsupported.go17
-rw-r--r--vendor/github.com/docker/libnetwork/osl/namespace_windows.go43
-rw-r--r--vendor/github.com/docker/libnetwork/osl/neigh_freebsd.go4
-rw-r--r--vendor/github.com/docker/libnetwork/osl/neigh_linux.go181
-rw-r--r--vendor/github.com/docker/libnetwork/osl/neigh_solaris.go4
-rw-r--r--vendor/github.com/docker/libnetwork/osl/neigh_windows.go4
-rw-r--r--vendor/github.com/docker/libnetwork/osl/options_linux.go79
-rw-r--r--vendor/github.com/docker/libnetwork/osl/route_linux.go203
-rw-r--r--vendor/github.com/docker/libnetwork/osl/sandbox.go171
-rw-r--r--vendor/github.com/docker/libnetwork/osl/sandbox_freebsd.go44
-rw-r--r--vendor/github.com/docker/libnetwork/osl/sandbox_solaris.go24
-rw-r--r--vendor/github.com/docker/libnetwork/osl/sandbox_unsupported.go22
-rw-r--r--vendor/github.com/docker/libnetwork/portallocator/portallocator.go248
-rw-r--r--vendor/github.com/docker/libnetwork/portallocator/portallocator_linux.go27
-rw-r--r--vendor/github.com/docker/libnetwork/portallocator/portallocator_solaris.go5
-rw-r--r--vendor/github.com/docker/libnetwork/portmapper/mapper.go241
-rw-r--r--vendor/github.com/docker/libnetwork/portmapper/mock_proxy.go18
-rw-r--r--vendor/github.com/docker/libnetwork/portmapper/proxy.go119
-rw-r--r--vendor/github.com/docker/libnetwork/portmapper/proxy_linux.go38
-rw-r--r--vendor/github.com/docker/libnetwork/portmapper/proxy_solaris.go34
-rw-r--r--vendor/github.com/docker/libnetwork/resolvconf/README.md1
-rw-r--r--vendor/github.com/docker/libnetwork/resolvconf/dns/resolvconf.go26
-rw-r--r--vendor/github.com/docker/libnetwork/resolvconf/resolvconf.go254
-rw-r--r--vendor/github.com/docker/libnetwork/resolver.go521
-rw-r--r--vendor/github.com/docker/libnetwork/resolver_unix.go101
-rw-r--r--vendor/github.com/docker/libnetwork/resolver_windows.go7
-rw-r--r--vendor/github.com/docker/libnetwork/sandbox.go1224
-rw-r--r--vendor/github.com/docker/libnetwork/sandbox_dns_unix.go407
-rw-r--r--vendor/github.com/docker/libnetwork/sandbox_dns_windows.go35
-rw-r--r--vendor/github.com/docker/libnetwork/sandbox_externalkey.go12
-rw-r--r--vendor/github.com/docker/libnetwork/sandbox_externalkey_solaris.go45
-rw-r--r--vendor/github.com/docker/libnetwork/sandbox_externalkey_unix.go177
-rw-r--r--vendor/github.com/docker/libnetwork/sandbox_externalkey_windows.go45
-rw-r--r--vendor/github.com/docker/libnetwork/sandbox_store.go307
-rw-r--r--vendor/github.com/docker/libnetwork/service.go92
-rw-r--r--vendor/github.com/docker/libnetwork/service_common.go381
-rw-r--r--vendor/github.com/docker/libnetwork/service_linux.go778
-rw-r--r--vendor/github.com/docker/libnetwork/service_unsupported.go25
-rw-r--r--vendor/github.com/docker/libnetwork/service_windows.go15
-rw-r--r--vendor/github.com/docker/libnetwork/store.go489
-rw-r--r--vendor/github.com/docker/libnetwork/types/types.go636
-rw-r--r--vendor/github.com/docker/libnetwork/vendor.conf44
-rw-r--r--vendor/github.com/docker/libtrust/LICENSE191
-rw-r--r--vendor/github.com/docker/libtrust/README.md18
-rw-r--r--vendor/github.com/docker/libtrust/certificates.go175
-rw-r--r--vendor/github.com/docker/libtrust/doc.go9
-rw-r--r--vendor/github.com/docker/libtrust/ec_key.go428
-rw-r--r--vendor/github.com/docker/libtrust/filter.go50
-rw-r--r--vendor/github.com/docker/libtrust/hash.go56
-rw-r--r--vendor/github.com/docker/libtrust/jsonsign.go657
-rw-r--r--vendor/github.com/docker/libtrust/key.go253
-rw-r--r--vendor/github.com/docker/libtrust/key_files.go255
-rw-r--r--vendor/github.com/docker/libtrust/key_manager.go175
-rw-r--r--vendor/github.com/docker/libtrust/rsa_key.go427
-rw-r--r--vendor/github.com/docker/libtrust/util.go363
-rw-r--r--vendor/github.com/docker/notary/LICENSE201
-rw-r--r--vendor/github.com/docker/notary/README.md100
-rw-r--r--vendor/github.com/docker/notary/client/changelist/change.go102
-rw-r--r--vendor/github.com/docker/notary/client/changelist/changelist.go77
-rw-r--r--vendor/github.com/docker/notary/client/changelist/file_changelist.go197
-rw-r--r--vendor/github.com/docker/notary/client/changelist/interface.go73
-rw-r--r--vendor/github.com/docker/notary/client/client.go1014
-rw-r--r--vendor/github.com/docker/notary/client/delegations.go299
-rw-r--r--vendor/github.com/docker/notary/client/helpers.go278
-rw-r--r--vendor/github.com/docker/notary/client/repo.go29
-rw-r--r--vendor/github.com/docker/notary/client/repo_pkcs11.go34
-rw-r--r--vendor/github.com/docker/notary/client/tufclient.go239
-rw-r--r--vendor/github.com/docker/notary/client/witness.go69
-rw-r--r--vendor/github.com/docker/notary/const.go70
-rw-r--r--vendor/github.com/docker/notary/const_nowindows.go16
-rw-r--r--vendor/github.com/docker/notary/const_windows.go8
-rw-r--r--vendor/github.com/docker/notary/cryptoservice/certificate.go41
-rw-r--r--vendor/github.com/docker/notary/cryptoservice/crypto_service.go181
-rw-r--r--vendor/github.com/docker/notary/notary.go7
-rw-r--r--vendor/github.com/docker/notary/passphrase/passphrase.go205
-rw-r--r--vendor/github.com/docker/notary/storage/errors.go22
-rw-r--r--vendor/github.com/docker/notary/storage/filestore.go222
-rw-r--r--vendor/github.com/docker/notary/storage/httpstore.go339
-rw-r--r--vendor/github.com/docker/notary/storage/interfaces.go34
-rw-r--r--vendor/github.com/docker/notary/storage/memorystore.go124
-rw-r--r--vendor/github.com/docker/notary/storage/offlinestore.go54
-rw-r--r--vendor/github.com/docker/notary/trustmanager/interfaces.go82
-rw-r--r--vendor/github.com/docker/notary/trustmanager/keystore.go325
-rw-r--r--vendor/github.com/docker/notary/trustmanager/yubikey/import.go57
-rw-r--r--vendor/github.com/docker/notary/trustmanager/yubikey/non_pkcs11.go9
-rw-r--r--vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_darwin.go9
-rw-r--r--vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_interface.go40
-rw-r--r--vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_linux.go10
-rw-r--r--vendor/github.com/docker/notary/trustmanager/yubikey/yubikeystore.go914
-rw-r--r--vendor/github.com/docker/notary/trustpinning/certs.go291
-rw-r--r--vendor/github.com/docker/notary/trustpinning/trustpin.go121
-rw-r--r--vendor/github.com/docker/notary/tuf/LICENSE30
-rw-r--r--vendor/github.com/docker/notary/tuf/README.md6
-rw-r--r--vendor/github.com/docker/notary/tuf/builder.go710
-rw-r--r--vendor/github.com/docker/notary/tuf/data/errors.go53
-rw-r--r--vendor/github.com/docker/notary/tuf/data/keys.go528
-rw-r--r--vendor/github.com/docker/notary/tuf/data/roles.go338
-rw-r--r--vendor/github.com/docker/notary/tuf/data/root.go171
-rw-r--r--vendor/github.com/docker/notary/tuf/data/serializer.go36
-rw-r--r--vendor/github.com/docker/notary/tuf/data/snapshot.go169
-rw-r--r--vendor/github.com/docker/notary/tuf/data/targets.go201
-rw-r--r--vendor/github.com/docker/notary/tuf/data/timestamp.go136
-rw-r--r--vendor/github.com/docker/notary/tuf/data/types.go311
-rw-r--r--vendor/github.com/docker/notary/tuf/signed/ed25519.go111
-rw-r--r--vendor/github.com/docker/notary/tuf/signed/errors.go96
-rw-r--r--vendor/github.com/docker/notary/tuf/signed/interface.go49
-rw-r--r--vendor/github.com/docker/notary/tuf/signed/sign.go113
-rw-r--r--vendor/github.com/docker/notary/tuf/signed/verifiers.go283
-rw-r--r--vendor/github.com/docker/notary/tuf/signed/verify.go112
-rw-r--r--vendor/github.com/docker/notary/tuf/tuf.go1148
-rw-r--r--vendor/github.com/docker/notary/tuf/utils/role_sort.go31
-rw-r--r--vendor/github.com/docker/notary/tuf/utils/stack.go85
-rw-r--r--vendor/github.com/docker/notary/tuf/utils/utils.go152
-rw-r--r--vendor/github.com/docker/notary/tuf/utils/x509.go551
-rw-r--r--vendor/github.com/docker/notary/tuf/validation/errors.go126
-rw-r--r--vendor/github.com/docker/swarmkit/LICENSE201
-rw-r--r--vendor/github.com/docker/swarmkit/README.md327
-rw-r--r--vendor/github.com/docker/swarmkit/agent/agent.go595
-rw-r--r--vendor/github.com/docker/swarmkit/agent/config.go83
-rw-r--r--vendor/github.com/docker/swarmkit/agent/configs/configs.go88
-rw-r--r--vendor/github.com/docker/swarmkit/agent/dependency.go52
-rw-r--r--vendor/github.com/docker/swarmkit/agent/errors.go22
-rw-r--r--vendor/github.com/docker/swarmkit/agent/exec/controller.go358
-rw-r--r--vendor/github.com/docker/swarmkit/agent/exec/controller_stub.go75
-rw-r--r--vendor/github.com/docker/swarmkit/agent/exec/errors.go82
-rw-r--r--vendor/github.com/docker/swarmkit/agent/exec/executor.go81
-rw-r--r--vendor/github.com/docker/swarmkit/agent/helpers.go13
-rw-r--r--vendor/github.com/docker/swarmkit/agent/reporter.go129
-rw-r--r--vendor/github.com/docker/swarmkit/agent/resource.go69
-rw-r--r--vendor/github.com/docker/swarmkit/agent/secrets/secrets.go88
-rw-r--r--vendor/github.com/docker/swarmkit/agent/session.go423
-rw-r--r--vendor/github.com/docker/swarmkit/agent/storage.go216
-rw-r--r--vendor/github.com/docker/swarmkit/agent/task.go248
-rw-r--r--vendor/github.com/docker/swarmkit/agent/worker.go604
-rw-r--r--vendor/github.com/docker/swarmkit/api/README.md8
-rw-r--r--vendor/github.com/docker/swarmkit/api/ca.pb.go2116
-rw-r--r--vendor/github.com/docker/swarmkit/api/ca.proto72
-rw-r--r--vendor/github.com/docker/swarmkit/api/control.pb.go16092
-rw-r--r--vendor/github.com/docker/swarmkit/api/control.proto554
-rw-r--r--vendor/github.com/docker/swarmkit/api/deepcopy/copy.go53
-rw-r--r--vendor/github.com/docker/swarmkit/api/defaults/service.go99
-rw-r--r--vendor/github.com/docker/swarmkit/api/dispatcher.pb.go3847
-rw-r--r--vendor/github.com/docker/swarmkit/api/dispatcher.proto218
-rw-r--r--vendor/github.com/docker/swarmkit/api/equality/equality.go67
-rw-r--r--vendor/github.com/docker/swarmkit/api/gen.go3
-rw-r--r--vendor/github.com/docker/swarmkit/api/genericresource/helpers.go111
-rw-r--r--vendor/github.com/docker/swarmkit/api/genericresource/parse.go47
-rw-r--r--vendor/github.com/docker/swarmkit/api/genericresource/resource_management.go202
-rw-r--r--vendor/github.com/docker/swarmkit/api/genericresource/string.go54
-rw-r--r--vendor/github.com/docker/swarmkit/api/genericresource/validate.go84
-rw-r--r--vendor/github.com/docker/swarmkit/api/health.pb.go721
-rw-r--r--vendor/github.com/docker/swarmkit/api/health.proto34
-rw-r--r--vendor/github.com/docker/swarmkit/api/logbroker.pb.go3416
-rw-r--r--vendor/github.com/docker/swarmkit/api/logbroker.proto188
-rw-r--r--vendor/github.com/docker/swarmkit/api/naming/naming.go49
-rw-r--r--vendor/github.com/docker/swarmkit/api/objects.pb.go7787
-rw-r--r--vendor/github.com/docker/swarmkit/api/objects.proto452
-rw-r--r--vendor/github.com/docker/swarmkit/api/raft.pb.go3638
-rw-r--r--vendor/github.com/docker/swarmkit/api/raft.proto132
-rw-r--r--vendor/github.com/docker/swarmkit/api/resource.pb.go1091
-rw-r--r--vendor/github.com/docker/swarmkit/api/resource.proto34
-rw-r--r--vendor/github.com/docker/swarmkit/api/snapshot.pb.go1342
-rw-r--r--vendor/github.com/docker/swarmkit/api/snapshot.proto44
-rw-r--r--vendor/github.com/docker/swarmkit/api/specs.pb.go6277
-rw-r--r--vendor/github.com/docker/swarmkit/api/specs.proto413
-rw-r--r--vendor/github.com/docker/swarmkit/api/storeobject.go108
-rw-r--r--vendor/github.com/docker/swarmkit/api/types.pb.go17356
-rw-r--r--vendor/github.com/docker/swarmkit/api/types.proto1022
-rw-r--r--vendor/github.com/docker/swarmkit/api/watch.pb.go4599
-rw-r--r--vendor/github.com/docker/swarmkit/api/watch.proto154
-rw-r--r--vendor/github.com/docker/swarmkit/ca/auth.go247
-rw-r--r--vendor/github.com/docker/swarmkit/ca/certificates.go1008
-rw-r--r--vendor/github.com/docker/swarmkit/ca/config.go665
-rw-r--r--vendor/github.com/docker/swarmkit/ca/external.go228
-rw-r--r--vendor/github.com/docker/swarmkit/ca/forward.go77
-rw-r--r--vendor/github.com/docker/swarmkit/ca/keyreadwriter.go388
-rw-r--r--vendor/github.com/docker/swarmkit/ca/reconciler.go259
-rw-r--r--vendor/github.com/docker/swarmkit/ca/renewer.go168
-rw-r--r--vendor/github.com/docker/swarmkit/ca/server.go849
-rw-r--r--vendor/github.com/docker/swarmkit/ca/transport.go213
-rw-r--r--vendor/github.com/docker/swarmkit/connectionbroker/broker.go110
-rw-r--r--vendor/github.com/docker/swarmkit/identity/doc.go16
-rw-r--r--vendor/github.com/docker/swarmkit/identity/randomid.go53
-rw-r--r--vendor/github.com/docker/swarmkit/ioutils/ioutils.go40
-rw-r--r--vendor/github.com/docker/swarmkit/log/context.go96
-rw-r--r--vendor/github.com/docker/swarmkit/log/grpc.go13
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/allocator.go231
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_darwin.go17
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_ipam.go23
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_linux.go28
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_windows.go17
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_unsupported.go14
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/networkallocator.go961
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/portallocator.go410
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/doc.go18
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/network.go1193
-rw-r--r--vendor/github.com/docker/swarmkit/manager/allocator/networkallocator/networkallocator.go132
-rw-r--r--vendor/github.com/docker/swarmkit/manager/constraint/constraint.go207
-rw-r--r--vendor/github.com/docker/swarmkit/manager/controlapi/ca_rotation.go282
-rw-r--r--vendor/github.com/docker/swarmkit/manager/controlapi/cluster.go287
-rw-r--r--vendor/github.com/docker/swarmkit/manager/controlapi/common.go135
-rw-r--r--vendor/github.com/docker/swarmkit/manager/controlapi/config.go248
-rw-r--r--vendor/github.com/docker/swarmkit/manager/controlapi/network.go302
-rw-r--r--vendor/github.com/docker/swarmkit/manager/controlapi/node.go322
-rw-r--r--vendor/github.com/docker/swarmkit/manager/controlapi/secret.go253
-rw-r--r--vendor/github.com/docker/swarmkit/manager/controlapi/server.go36
-rw-r--r--vendor/github.com/docker/swarmkit/manager/controlapi/service.go933
-rw-r--r--vendor/github.com/docker/swarmkit/manager/controlapi/task.go170
-rw-r--r--vendor/github.com/docker/swarmkit/manager/deks.go269
-rw-r--r--vendor/github.com/docker/swarmkit/manager/dirty.go57
-rw-r--r--vendor/github.com/docker/swarmkit/manager/dispatcher/assignments.go247
-rw-r--r--vendor/github.com/docker/swarmkit/manager/dispatcher/dispatcher.go1250
-rw-r--r--vendor/github.com/docker/swarmkit/manager/dispatcher/heartbeat/heartbeat.go39
-rw-r--r--vendor/github.com/docker/swarmkit/manager/dispatcher/nodes.go198
-rw-r--r--vendor/github.com/docker/swarmkit/manager/dispatcher/period.go28
-rw-r--r--vendor/github.com/docker/swarmkit/manager/doc.go1
-rw-r--r--vendor/github.com/docker/swarmkit/manager/encryption/encryption.go132
-rw-r--r--vendor/github.com/docker/swarmkit/manager/encryption/nacl.go73
-rw-r--r--vendor/github.com/docker/swarmkit/manager/health/health.go58
-rw-r--r--vendor/github.com/docker/swarmkit/manager/keymanager/keymanager.go239
-rw-r--r--vendor/github.com/docker/swarmkit/manager/logbroker/broker.go427
-rw-r--r--vendor/github.com/docker/swarmkit/manager/logbroker/subscription.go248
-rw-r--r--vendor/github.com/docker/swarmkit/manager/manager.go1197
-rw-r--r--vendor/github.com/docker/swarmkit/manager/metrics/collector.go104
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/constraintenforcer/constraint_enforcer.go183
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/global/global.go592
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/replicated.go108
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/services.go229
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/slot.go55
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/tasks.go180
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/restart/restart.go447
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/service.go61
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/slot.go46
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/task.go79
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/taskinit/init.go103
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/taskreaper/task_reaper.go245
-rw-r--r--vendor/github.com/docker/swarmkit/manager/orchestrator/update/updater.go642
-rw-r--r--vendor/github.com/docker/swarmkit/manager/raftselector/raftselector.go20
-rw-r--r--vendor/github.com/docker/swarmkit/manager/resourceapi/allocator.go124
-rw-r--r--vendor/github.com/docker/swarmkit/manager/role_manager.go177
-rw-r--r--vendor/github.com/docker/swarmkit/manager/scheduler/decision_tree.go55
-rw-r--r--vendor/github.com/docker/swarmkit/manager/scheduler/filter.go350
-rw-r--r--vendor/github.com/docker/swarmkit/manager/scheduler/nodeheap.go31
-rw-r--r--vendor/github.com/docker/swarmkit/manager/scheduler/nodeinfo.go181
-rw-r--r--vendor/github.com/docker/swarmkit/manager/scheduler/nodeset.go124
-rw-r--r--vendor/github.com/docker/swarmkit/manager/scheduler/pipeline.go98
-rw-r--r--vendor/github.com/docker/swarmkit/manager/scheduler/scheduler.go737
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/proposer.go30
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/raft/membership/cluster.go213
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/raft/raft.go1974
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/raft/storage.go248
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/raft/storage/snapwrap.go158
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/raft/storage/storage.go375
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/raft/storage/walwrap.go255
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/raft/transport/peer.go291
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/raft/transport/transport.go398
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/raft/util.go86
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/raft/wait.go77
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/apply.go49
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/by.go214
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/clusters.go138
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/combinators.go14
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/configs.go132
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/doc.go32
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/extensions.go190
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/memory.go941
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/networks.go132
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/nodes.go176
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/object.go15
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/resources.go199
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/secrets.go132
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/services.go248
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/store/tasks.go341
-rw-r--r--vendor/github.com/docker/swarmkit/manager/state/watch.go74
-rw-r--r--vendor/github.com/docker/swarmkit/manager/watchapi/server.go17
-rw-r--r--vendor/github.com/docker/swarmkit/manager/watchapi/watch.go56
-rw-r--r--vendor/github.com/docker/swarmkit/node/node.go1100
-rw-r--r--vendor/github.com/docker/swarmkit/protobuf/plugin/gen.go3
-rw-r--r--vendor/github.com/docker/swarmkit/protobuf/plugin/helpers.go11
-rw-r--r--vendor/github.com/docker/swarmkit/protobuf/plugin/plugin.pb.go1185
-rw-r--r--vendor/github.com/docker/swarmkit/protobuf/plugin/plugin.proto53
-rw-r--r--vendor/github.com/docker/swarmkit/protobuf/ptypes/doc.go3
-rw-r--r--vendor/github.com/docker/swarmkit/protobuf/ptypes/timestamp.go17
-rw-r--r--vendor/github.com/docker/swarmkit/remotes/remotes.go203
-rw-r--r--vendor/github.com/docker/swarmkit/template/context.go192
-rw-r--r--vendor/github.com/docker/swarmkit/template/expand.go161
-rw-r--r--vendor/github.com/docker/swarmkit/template/getter.go98
-rw-r--r--vendor/github.com/docker/swarmkit/template/template.go22
-rw-r--r--vendor/github.com/docker/swarmkit/vendor.conf65
-rw-r--r--vendor/github.com/docker/swarmkit/watch/watch.go107
-rw-r--r--vendor/github.com/docker/swarmkit/xnet/xnet_unix.go20
-rw-r--r--vendor/github.com/docker/swarmkit/xnet/xnet_windows.go31
-rw-r--r--vendor/github.com/fluent/fluent-logger-golang/LICENSE202
-rw-r--r--vendor/github.com/fluent/fluent-logger-golang/README.md65
-rw-r--r--vendor/github.com/fluent/fluent-logger-golang/fluent/fluent.go309
-rw-r--r--vendor/github.com/fluent/fluent-logger-golang/fluent/proto.go24
-rw-r--r--vendor/github.com/fluent/fluent-logger-golang/fluent/proto_gen.go372
-rw-r--r--vendor/github.com/fluent/fluent-logger-golang/fluent/version.go3
-rw-r--r--vendor/github.com/fsnotify/fsnotify/LICENSE28
-rw-r--r--vendor/github.com/fsnotify/fsnotify/README.md46
-rw-r--r--vendor/github.com/fsnotify/fsnotify/fen.go37
-rw-r--r--vendor/github.com/fsnotify/fsnotify/fsnotify.go62
-rw-r--r--vendor/github.com/fsnotify/fsnotify/inotify.go324
-rw-r--r--vendor/github.com/fsnotify/fsnotify/inotify_poller.go186
-rw-r--r--vendor/github.com/fsnotify/fsnotify/kqueue.go502
-rw-r--r--vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go11
-rw-r--r--vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go12
-rw-r--r--vendor/github.com/fsnotify/fsnotify/windows.go561
-rw-r--r--vendor/github.com/go-check/check/LICENSE25
-rw-r--r--vendor/github.com/go-check/check/README.md10
-rw-r--r--vendor/github.com/go-check/check/benchmark.go187
-rw-r--r--vendor/github.com/go-check/check/check.go939
-rw-r--r--vendor/github.com/go-check/check/checkers.go458
-rw-r--r--vendor/github.com/go-check/check/helpers.go231
-rw-r--r--vendor/github.com/go-check/check/printer.go168
-rw-r--r--vendor/github.com/go-check/check/reporter.go88
-rw-r--r--vendor/github.com/go-check/check/run.go183
-rw-r--r--vendor/github.com/go-ini/ini/LICENSE191
-rw-r--r--vendor/github.com/go-ini/ini/README.md560
-rw-r--r--vendor/github.com/go-ini/ini/README_ZH.md547
-rw-r--r--vendor/github.com/go-ini/ini/ini.go1226
-rw-r--r--vendor/github.com/go-ini/ini/struct.go350
-rw-r--r--vendor/github.com/godbus/dbus/LICENSE25
-rw-r--r--vendor/github.com/godbus/dbus/README.markdown41
-rw-r--r--vendor/github.com/godbus/dbus/auth.go253
-rw-r--r--vendor/github.com/godbus/dbus/auth_external.go26
-rw-r--r--vendor/github.com/godbus/dbus/auth_sha1.go102
-rw-r--r--vendor/github.com/godbus/dbus/call.go36
-rw-r--r--vendor/github.com/godbus/dbus/conn.go625
-rw-r--r--vendor/github.com/godbus/dbus/conn_darwin.go21
-rw-r--r--vendor/github.com/godbus/dbus/conn_other.go27
-rw-r--r--vendor/github.com/godbus/dbus/dbus.go258
-rw-r--r--vendor/github.com/godbus/dbus/decoder.go228
-rw-r--r--vendor/github.com/godbus/dbus/doc.go63
-rw-r--r--vendor/github.com/godbus/dbus/encoder.go208
-rw-r--r--vendor/github.com/godbus/dbus/export.go411
-rw-r--r--vendor/github.com/godbus/dbus/homedir.go28
-rw-r--r--vendor/github.com/godbus/dbus/homedir_dynamic.go15
-rw-r--r--vendor/github.com/godbus/dbus/homedir_static.go45
-rw-r--r--vendor/github.com/godbus/dbus/message.go346
-rw-r--r--vendor/github.com/godbus/dbus/object.go126
-rw-r--r--vendor/github.com/godbus/dbus/sig.go257
-rw-r--r--vendor/github.com/godbus/dbus/transport_darwin.go6
-rw-r--r--vendor/github.com/godbus/dbus/transport_generic.go35
-rw-r--r--vendor/github.com/godbus/dbus/transport_unix.go196
-rw-r--r--vendor/github.com/godbus/dbus/transport_unixcred_dragonfly.go95
-rw-r--r--vendor/github.com/godbus/dbus/transport_unixcred_linux.go25
-rw-r--r--vendor/github.com/godbus/dbus/variant.go139
-rw-r--r--vendor/github.com/godbus/dbus/variant_lexer.go284
-rw-r--r--vendor/github.com/godbus/dbus/variant_parser.go817
-rw-r--r--vendor/github.com/gogo/protobuf/LICENSE36
-rw-r--r--vendor/github.com/gogo/protobuf/README258
-rw-r--r--vendor/github.com/gogo/protobuf/Readme.md117
-rw-r--r--vendor/github.com/gogo/protobuf/gogoproto/doc.go169
-rw-r--r--vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go804
-rw-r--r--vendor/github.com/gogo/protobuf/gogoproto/gogo.proto132
-rw-r--r--vendor/github.com/gogo/protobuf/gogoproto/helper.go357
-rw-r--r--vendor/github.com/gogo/protobuf/io/full.go102
-rw-r--r--vendor/github.com/gogo/protobuf/io/io.go70
-rw-r--r--vendor/github.com/gogo/protobuf/io/uint32.go126
-rw-r--r--vendor/github.com/gogo/protobuf/io/varint.go134
-rw-r--r--vendor/github.com/gogo/protobuf/proto/clone.go234
-rw-r--r--vendor/github.com/gogo/protobuf/proto/decode.go978
-rw-r--r--vendor/github.com/gogo/protobuf/proto/decode_gogo.go172
-rw-r--r--vendor/github.com/gogo/protobuf/proto/duration.go100
-rw-r--r--vendor/github.com/gogo/protobuf/proto/duration_gogo.go203
-rw-r--r--vendor/github.com/gogo/protobuf/proto/encode.go1362
-rw-r--r--vendor/github.com/gogo/protobuf/proto/encode_gogo.go350
-rw-r--r--vendor/github.com/gogo/protobuf/proto/equal.go300
-rw-r--r--vendor/github.com/gogo/protobuf/proto/extensions.go693
-rw-r--r--vendor/github.com/gogo/protobuf/proto/extensions_gogo.go294
-rw-r--r--vendor/github.com/gogo/protobuf/proto/lib.go898
-rw-r--r--vendor/github.com/gogo/protobuf/proto/lib_gogo.go42
-rw-r--r--vendor/github.com/gogo/protobuf/proto/message_set.go311
-rw-r--r--vendor/github.com/gogo/protobuf/proto/pointer_reflect.go484
-rw-r--r--vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go85
-rw-r--r--vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go270
-rw-r--r--vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go128
-rw-r--r--vendor/github.com/gogo/protobuf/proto/properties.go968
-rw-r--r--vendor/github.com/gogo/protobuf/proto/properties_gogo.go111
-rw-r--r--vendor/github.com/gogo/protobuf/proto/skip_gogo.go119
-rw-r--r--vendor/github.com/gogo/protobuf/proto/text.go928
-rw-r--r--vendor/github.com/gogo/protobuf/proto/text_gogo.go57
-rw-r--r--vendor/github.com/gogo/protobuf/proto/text_parser.go1013
-rw-r--r--vendor/github.com/gogo/protobuf/proto/timestamp.go113
-rw-r--r--vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go229
-rw-r--r--vendor/github.com/gogo/protobuf/protobuf/google/protobuf/any.proto140
-rw-r--r--vendor/github.com/gogo/protobuf/protobuf/google/protobuf/compiler/plugin.proto150
-rw-r--r--vendor/github.com/gogo/protobuf/protobuf/google/protobuf/descriptor.proto813
-rw-r--r--vendor/github.com/gogo/protobuf/protobuf/google/protobuf/duration.proto98
-rw-r--r--vendor/github.com/gogo/protobuf/protobuf/google/protobuf/empty.proto53
-rw-r--r--vendor/github.com/gogo/protobuf/protobuf/google/protobuf/field_mask.proto246
-rw-r--r--vendor/github.com/gogo/protobuf/protobuf/google/protobuf/struct.proto96
-rw-r--r--vendor/github.com/gogo/protobuf/protobuf/google/protobuf/timestamp.proto111
-rw-r--r--vendor/github.com/gogo/protobuf/protobuf/google/protobuf/wrappers.proto119
-rw-r--r--vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go118
-rw-r--r--vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go2088
-rw-r--r--vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go715
-rw-r--r--vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/helper.go390
-rw-r--r--vendor/github.com/gogo/protobuf/sortkeys/sortkeys.go101
-rw-r--r--vendor/github.com/gogo/protobuf/types/any.go135
-rw-r--r--vendor/github.com/gogo/protobuf/types/any.pb.go666
-rw-r--r--vendor/github.com/gogo/protobuf/types/doc.go35
-rw-r--r--vendor/github.com/gogo/protobuf/types/duration.go100
-rw-r--r--vendor/github.com/gogo/protobuf/types/duration.pb.go494
-rw-r--r--vendor/github.com/gogo/protobuf/types/duration_gogo.go100
-rw-r--r--vendor/github.com/gogo/protobuf/types/empty.pb.go457
-rw-r--r--vendor/github.com/gogo/protobuf/types/field_mask.pb.go738
-rw-r--r--vendor/github.com/gogo/protobuf/types/struct.pb.go1888
-rw-r--r--vendor/github.com/gogo/protobuf/types/timestamp.go123
-rw-r--r--vendor/github.com/gogo/protobuf/types/timestamp.pb.go506
-rw-r--r--vendor/github.com/gogo/protobuf/types/timestamp_gogo.go94
-rw-r--r--vendor/github.com/gogo/protobuf/types/wrappers.pb.go2259
-rw-r--r--vendor/github.com/golang/protobuf/LICENSE31
-rw-r--r--vendor/github.com/golang/protobuf/README.md241
-rw-r--r--vendor/github.com/golang/protobuf/proto/clone.go229
-rw-r--r--vendor/github.com/golang/protobuf/proto/decode.go970
-rw-r--r--vendor/github.com/golang/protobuf/proto/encode.go1362
-rw-r--r--vendor/github.com/golang/protobuf/proto/equal.go300
-rw-r--r--vendor/github.com/golang/protobuf/proto/extensions.go587
-rw-r--r--vendor/github.com/golang/protobuf/proto/lib.go898
-rw-r--r--vendor/github.com/golang/protobuf/proto/message_set.go311
-rw-r--r--vendor/github.com/golang/protobuf/proto/pointer_reflect.go484
-rw-r--r--vendor/github.com/golang/protobuf/proto/pointer_unsafe.go270
-rw-r--r--vendor/github.com/golang/protobuf/proto/properties.go872
-rw-r--r--vendor/github.com/golang/protobuf/proto/text.go854
-rw-r--r--vendor/github.com/golang/protobuf/proto/text_parser.go895
-rw-r--r--vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go2152
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/any.go136
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/any/any.pb.go168
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/any/any.proto139
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/doc.go35
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/duration.go102
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go146
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/duration/duration.proto117
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go68
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/empty/empty.proto52
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go382
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/struct/struct.proto96
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/timestamp.go125
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go162
-rw-r--r--vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto133
-rw-r--r--vendor/github.com/google/certificate-transparency/LICENSE202
-rw-r--r--vendor/github.com/google/certificate-transparency/README-MacOS.md55
-rw-r--r--vendor/github.com/google/certificate-transparency/README.md303
-rw-r--r--vendor/github.com/google/certificate-transparency/cpp/third_party/curl/hostcheck.c214
-rw-r--r--vendor/github.com/google/certificate-transparency/cpp/third_party/curl/hostcheck.h29
-rw-r--r--vendor/github.com/google/certificate-transparency/cpp/third_party/isec_partners/openssl_hostname_validation.c180
-rw-r--r--vendor/github.com/google/certificate-transparency/cpp/third_party/isec_partners/openssl_hostname_validation.h59
-rw-r--r--vendor/github.com/google/certificate-transparency/cpp/version.h12
-rw-r--r--vendor/github.com/google/certificate-transparency/go/README.md25
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/asn1/asn1.go956
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/asn1/common.go163
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/asn1/marshal.go581
-rw-r--r--vendor/github.com/google/certificate-transparency/go/client/getentries.go88
-rw-r--r--vendor/github.com/google/certificate-transparency/go/client/logclient.go412
-rw-r--r--vendor/github.com/google/certificate-transparency/go/serialization.go691
-rw-r--r--vendor/github.com/google/certificate-transparency/go/signatures.go131
-rw-r--r--vendor/github.com/google/certificate-transparency/go/types.go374
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/cert_pool.go116
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/pem_decrypt.go233
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/pkcs1.go124
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/pkcs8.go56
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/pkix/pkix.go173
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/root.go17
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/root_darwin.go83
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/root_plan9.go33
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/root_stub.go14
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/root_unix.go37
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/root_windows.go229
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/sec1.go85
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/verify.go476
-rwxr-xr-xvendor/github.com/google/certificate-transparency/go/x509/x509.go1622
-rw-r--r--vendor/github.com/google/certificate-transparency/proto/ct.proto320
-rw-r--r--vendor/github.com/googleapis/gax-go/LICENSE27
-rw-r--r--vendor/github.com/googleapis/gax-go/README.md24
-rw-r--r--vendor/github.com/googleapis/gax-go/call_option.go136
-rw-r--r--vendor/github.com/googleapis/gax-go/gax.go40
-rw-r--r--vendor/github.com/googleapis/gax-go/invoke.go90
-rw-r--r--vendor/github.com/googleapis/gax-go/path_template.go176
-rw-r--r--vendor/github.com/googleapis/gax-go/path_template_parser.go227
-rw-r--r--vendor/github.com/gorilla/context/LICENSE27
-rw-r--r--vendor/github.com/gorilla/context/README.md7
-rw-r--r--vendor/github.com/gorilla/context/context.go143
-rw-r--r--vendor/github.com/gorilla/context/doc.go82
-rw-r--r--vendor/github.com/gorilla/mux/LICENSE27
-rw-r--r--vendor/github.com/gorilla/mux/README.md242
-rw-r--r--vendor/github.com/gorilla/mux/doc.go206
-rw-r--r--vendor/github.com/gorilla/mux/mux.go481
-rw-r--r--vendor/github.com/gorilla/mux/regexp.go312
-rw-r--r--vendor/github.com/gorilla/mux/route.go627
-rw-r--r--vendor/github.com/grpc-ecosystem/go-grpc-prometheus/LICENSE201
-rw-r--r--vendor/github.com/grpc-ecosystem/go-grpc-prometheus/README.md245
-rw-r--r--vendor/github.com/grpc-ecosystem/go-grpc-prometheus/client.go72
-rw-r--r--vendor/github.com/grpc-ecosystem/go-grpc-prometheus/client_reporter.go111
-rw-r--r--vendor/github.com/grpc-ecosystem/go-grpc-prometheus/server.go74
-rw-r--r--vendor/github.com/grpc-ecosystem/go-grpc-prometheus/server_reporter.go157
-rw-r--r--vendor/github.com/grpc-ecosystem/go-grpc-prometheus/util.go27
-rw-r--r--vendor/github.com/hashicorp/go-immutable-radix/LICENSE363
-rw-r--r--vendor/github.com/hashicorp/go-immutable-radix/README.md41
-rw-r--r--vendor/github.com/hashicorp/go-immutable-radix/edges.go21
-rw-r--r--vendor/github.com/hashicorp/go-immutable-radix/iradix.go333
-rw-r--r--vendor/github.com/hashicorp/go-immutable-radix/iter.go81
-rw-r--r--vendor/github.com/hashicorp/go-immutable-radix/node.go289
-rw-r--r--vendor/github.com/hashicorp/go-memdb/LICENSE363
-rw-r--r--vendor/github.com/hashicorp/go-memdb/README.md93
-rw-r--r--vendor/github.com/hashicorp/go-memdb/index.go419
-rw-r--r--vendor/github.com/hashicorp/go-memdb/memdb.go89
-rw-r--r--vendor/github.com/hashicorp/go-memdb/schema.go85
-rw-r--r--vendor/github.com/hashicorp/go-memdb/txn.go521
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/LICENSE25
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/README.md14
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/0doc.go143
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/README.md174
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/binc.go786
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/decode.go1048
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/encode.go1001
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/helper.go589
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go127
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go816
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/rpc.go152
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/simple.go461
-rw-r--r--vendor/github.com/hashicorp/go-msgpack/codec/time.go193
-rw-r--r--vendor/github.com/hashicorp/go-multierror/LICENSE353
-rw-r--r--vendor/github.com/hashicorp/go-multierror/README.md91
-rw-r--r--vendor/github.com/hashicorp/go-multierror/append.go30
-rw-r--r--vendor/github.com/hashicorp/go-multierror/format.go23
-rw-r--r--vendor/github.com/hashicorp/go-multierror/multierror.go51
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/LICENSE373
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/README.md118
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/doc.go5
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ifaddr.go126
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go969
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ifattr.go65
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ipaddr.go169
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go98
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go515
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/ipv6addr.go591
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/rfc.go947
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/route_info.go19
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go36
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/route_info_default.go10
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go37
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go37
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go41
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/sockaddr.go178
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go193
-rw-r--r--vendor/github.com/hashicorp/go-sockaddr/unixsock.go135
-rw-r--r--vendor/github.com/hashicorp/golang-lru/LICENSE362
-rw-r--r--vendor/github.com/hashicorp/golang-lru/README.md25
-rw-r--r--vendor/github.com/hashicorp/golang-lru/simplelru/lru.go160
-rw-r--r--vendor/github.com/hashicorp/memberlist/LICENSE354
-rw-r--r--vendor/github.com/hashicorp/memberlist/README.md144
-rw-r--r--vendor/github.com/hashicorp/memberlist/alive_delegate.go14
-rw-r--r--vendor/github.com/hashicorp/memberlist/awareness.go69
-rw-r--r--vendor/github.com/hashicorp/memberlist/broadcast.go100
-rw-r--r--vendor/github.com/hashicorp/memberlist/config.go288
-rw-r--r--vendor/github.com/hashicorp/memberlist/conflict_delegate.go10
-rw-r--r--vendor/github.com/hashicorp/memberlist/delegate.go37
-rw-r--r--vendor/github.com/hashicorp/memberlist/event_delegate.go61
-rw-r--r--vendor/github.com/hashicorp/memberlist/keyring.go160
-rw-r--r--vendor/github.com/hashicorp/memberlist/logging.go22
-rw-r--r--vendor/github.com/hashicorp/memberlist/memberlist.go625
-rw-r--r--vendor/github.com/hashicorp/memberlist/merge_delegate.go14
-rw-r--r--vendor/github.com/hashicorp/memberlist/mock_transport.go121
-rw-r--r--vendor/github.com/hashicorp/memberlist/net.go1069
-rw-r--r--vendor/github.com/hashicorp/memberlist/net_transport.go289
-rw-r--r--vendor/github.com/hashicorp/memberlist/ping_delegate.go14
-rw-r--r--vendor/github.com/hashicorp/memberlist/queue.go167
-rw-r--r--vendor/github.com/hashicorp/memberlist/security.go198
-rw-r--r--vendor/github.com/hashicorp/memberlist/state.go1160
-rw-r--r--vendor/github.com/hashicorp/memberlist/suspicion.go130
-rw-r--r--vendor/github.com/hashicorp/memberlist/transport.go65
-rw-r--r--vendor/github.com/hashicorp/memberlist/util.go296
-rw-r--r--vendor/github.com/hashicorp/serf/LICENSE354
-rw-r--r--vendor/github.com/hashicorp/serf/README.md114
-rw-r--r--vendor/github.com/hashicorp/serf/coordinate/client.go180
-rw-r--r--vendor/github.com/hashicorp/serf/coordinate/config.go70
-rw-r--r--vendor/github.com/hashicorp/serf/coordinate/coordinate.go183
-rw-r--r--vendor/github.com/hashicorp/serf/coordinate/phantom.go187
-rw-r--r--vendor/github.com/hashicorp/serf/serf/broadcast.go27
-rw-r--r--vendor/github.com/hashicorp/serf/serf/coalesce.go80
-rw-r--r--vendor/github.com/hashicorp/serf/serf/coalesce_member.go68
-rw-r--r--vendor/github.com/hashicorp/serf/serf/coalesce_user.go52
-rw-r--r--vendor/github.com/hashicorp/serf/serf/config.go251
-rw-r--r--vendor/github.com/hashicorp/serf/serf/conflict_delegate.go13
-rw-r--r--vendor/github.com/hashicorp/serf/serf/delegate.go254
-rw-r--r--vendor/github.com/hashicorp/serf/serf/event.go168
-rw-r--r--vendor/github.com/hashicorp/serf/serf/event_delegate.go21
-rw-r--r--vendor/github.com/hashicorp/serf/serf/internal_query.go312
-rw-r--r--vendor/github.com/hashicorp/serf/serf/keymanager.go166
-rw-r--r--vendor/github.com/hashicorp/serf/serf/lamport.go45
-rw-r--r--vendor/github.com/hashicorp/serf/serf/merge_delegate.go44
-rw-r--r--vendor/github.com/hashicorp/serf/serf/messages.go147
-rw-r--r--vendor/github.com/hashicorp/serf/serf/ping_delegate.go89
-rw-r--r--vendor/github.com/hashicorp/serf/serf/query.go210
-rw-r--r--vendor/github.com/hashicorp/serf/serf/serf.go1692
-rw-r--r--vendor/github.com/hashicorp/serf/serf/snapshot.go560
-rw-r--r--vendor/github.com/imdario/mergo/LICENSE28
-rw-r--r--vendor/github.com/imdario/mergo/README.md122
-rw-r--r--vendor/github.com/imdario/mergo/doc.go44
-rw-r--r--vendor/github.com/imdario/mergo/map.go154
-rw-r--r--vendor/github.com/imdario/mergo/merge.go120
-rw-r--r--vendor/github.com/imdario/mergo/mergo.go90
-rw-r--r--vendor/github.com/inconshreveable/mousetrap/LICENSE13
-rw-r--r--vendor/github.com/inconshreveable/mousetrap/README.md23
-rw-r--r--vendor/github.com/inconshreveable/mousetrap/trap_others.go15
-rw-r--r--vendor/github.com/inconshreveable/mousetrap/trap_windows.go98
-rw-r--r--vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go46
-rw-r--r--vendor/github.com/jmespath/go-jmespath/LICENSE13
-rw-r--r--vendor/github.com/jmespath/go-jmespath/README.md7
-rw-r--r--vendor/github.com/jmespath/go-jmespath/api.go49
-rw-r--r--vendor/github.com/jmespath/go-jmespath/astnodetype_string.go16
-rw-r--r--vendor/github.com/jmespath/go-jmespath/functions.go842
-rw-r--r--vendor/github.com/jmespath/go-jmespath/interpreter.go418
-rw-r--r--vendor/github.com/jmespath/go-jmespath/lexer.go420
-rw-r--r--vendor/github.com/jmespath/go-jmespath/parser.go603
-rw-r--r--vendor/github.com/jmespath/go-jmespath/toktype_string.go16
-rw-r--r--vendor/github.com/jmespath/go-jmespath/util.go185
-rw-r--r--vendor/github.com/kr/pty/License23
-rw-r--r--vendor/github.com/kr/pty/README.md36
-rw-r--r--vendor/github.com/kr/pty/doc.go16
-rw-r--r--vendor/github.com/kr/pty/ioctl.go11
-rw-r--r--vendor/github.com/kr/pty/ioctl_bsd.go39
-rw-r--r--vendor/github.com/kr/pty/pty_darwin.go60
-rw-r--r--vendor/github.com/kr/pty/pty_freebsd.go73
-rw-r--r--vendor/github.com/kr/pty/pty_linux.go46
-rw-r--r--vendor/github.com/kr/pty/pty_unsupported.go11
-rw-r--r--vendor/github.com/kr/pty/run.go28
-rw-r--r--vendor/github.com/kr/pty/util.go35
-rw-r--r--vendor/github.com/kr/pty/ztypes_386.go9
-rw-r--r--vendor/github.com/kr/pty/ztypes_amd64.go9
-rw-r--r--vendor/github.com/kr/pty/ztypes_arm.go9
-rw-r--r--vendor/github.com/kr/pty/ztypes_arm64.go11
-rw-r--r--vendor/github.com/kr/pty/ztypes_freebsd_386.go13
-rw-r--r--vendor/github.com/kr/pty/ztypes_freebsd_amd64.go14
-rw-r--r--vendor/github.com/kr/pty/ztypes_freebsd_arm.go13
-rw-r--r--vendor/github.com/kr/pty/ztypes_ppc64.go11
-rw-r--r--vendor/github.com/kr/pty/ztypes_ppc64le.go11
-rw-r--r--vendor/github.com/kr/pty/ztypes_s390x.go11
-rw-r--r--vendor/github.com/mattn/go-shellwords/LICENSE21
-rw-r--r--vendor/github.com/mattn/go-shellwords/README.md47
-rw-r--r--vendor/github.com/mattn/go-shellwords/shellwords.go145
-rw-r--r--vendor/github.com/mattn/go-shellwords/util_posix.go19
-rw-r--r--vendor/github.com/mattn/go-shellwords/util_windows.go17
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE201
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE1
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/README.md20
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go75
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go16
-rw-r--r--vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go46
-rw-r--r--vendor/github.com/miekg/dns/LICENSE32
-rw-r--r--vendor/github.com/miekg/dns/README.md153
-rw-r--r--vendor/github.com/miekg/dns/client.go385
-rw-r--r--vendor/github.com/miekg/dns/clientconfig.go99
-rw-r--r--vendor/github.com/miekg/dns/defaults.go278
-rw-r--r--vendor/github.com/miekg/dns/dns.go100
-rw-r--r--vendor/github.com/miekg/dns/dnssec.go664
-rw-r--r--vendor/github.com/miekg/dns/dnssec_keygen.go156
-rw-r--r--vendor/github.com/miekg/dns/dnssec_keyscan.go249
-rw-r--r--vendor/github.com/miekg/dns/dnssec_privkey.go85
-rw-r--r--vendor/github.com/miekg/dns/doc.go251
-rw-r--r--vendor/github.com/miekg/dns/edns.go505
-rw-r--r--vendor/github.com/miekg/dns/format.go96
-rw-r--r--vendor/github.com/miekg/dns/labels.go162
-rw-r--r--vendor/github.com/miekg/dns/msg.go1945
-rw-r--r--vendor/github.com/miekg/dns/nsecx.go112
-rw-r--r--vendor/github.com/miekg/dns/privaterr.go117
-rw-r--r--vendor/github.com/miekg/dns/rawmsg.go95
-rw-r--r--vendor/github.com/miekg/dns/sanitize.go84
-rw-r--r--vendor/github.com/miekg/dns/scanner.go43
-rw-r--r--vendor/github.com/miekg/dns/server.go690
-rw-r--r--vendor/github.com/miekg/dns/sig0.go216
-rw-r--r--vendor/github.com/miekg/dns/singleinflight.go57
-rw-r--r--vendor/github.com/miekg/dns/tlsa.go86
-rw-r--r--vendor/github.com/miekg/dns/tsig.go320
-rw-r--r--vendor/github.com/miekg/dns/types.go1328
-rw-r--r--vendor/github.com/miekg/dns/udp.go58
-rw-r--r--vendor/github.com/miekg/dns/udp_linux.go73
-rw-r--r--vendor/github.com/miekg/dns/udp_other.go17
-rw-r--r--vendor/github.com/miekg/dns/udp_windows.go34
-rw-r--r--vendor/github.com/miekg/dns/update.go94
-rw-r--r--vendor/github.com/miekg/dns/xfr.go244
-rw-r--r--vendor/github.com/miekg/dns/zgenerate.go158
-rw-r--r--vendor/github.com/miekg/dns/zscan.go974
-rw-r--r--vendor/github.com/miekg/dns/zscan_rr.go2270
-rw-r--r--vendor/github.com/miekg/dns/ztypes.go842
-rw-r--r--vendor/github.com/mistifyio/go-zfs/LICENSE201
-rw-r--r--vendor/github.com/mistifyio/go-zfs/README.md54
-rw-r--r--vendor/github.com/mistifyio/go-zfs/error.go18
-rw-r--r--vendor/github.com/mistifyio/go-zfs/utils.go352
-rw-r--r--vendor/github.com/mistifyio/go-zfs/utils_notsolaris.go17
-rw-r--r--vendor/github.com/mistifyio/go-zfs/utils_solaris.go17
-rw-r--r--vendor/github.com/mistifyio/go-zfs/zfs.go451
-rw-r--r--vendor/github.com/mistifyio/go-zfs/zpool.go112
-rw-r--r--vendor/github.com/mitchellh/mapstructure/LICENSE21
-rw-r--r--vendor/github.com/mitchellh/mapstructure/README.md46
-rw-r--r--vendor/github.com/mitchellh/mapstructure/decode_hooks.go154
-rw-r--r--vendor/github.com/mitchellh/mapstructure/error.go50
-rw-r--r--vendor/github.com/mitchellh/mapstructure/mapstructure.go782
-rw-r--r--vendor/github.com/mrunalp/fileutils/LICENSE191
-rw-r--r--vendor/github.com/mrunalp/fileutils/README.md5
-rw-r--r--vendor/github.com/mrunalp/fileutils/fileutils.go161
-rw-r--r--vendor/github.com/mrunalp/fileutils/idtools.go49
-rw-r--r--vendor/github.com/opencontainers/go-digest/LICENSE.code191
-rw-r--r--vendor/github.com/opencontainers/go-digest/LICENSE.docs425
-rw-r--r--vendor/github.com/opencontainers/go-digest/README.md104
-rw-r--r--vendor/github.com/opencontainers/go-digest/algorithm.go144
-rw-r--r--vendor/github.com/opencontainers/go-digest/digest.go140
-rw-r--r--vendor/github.com/opencontainers/go-digest/digester.go25
-rw-r--r--vendor/github.com/opencontainers/go-digest/doc.go42
-rw-r--r--vendor/github.com/opencontainers/go-digest/verifiers.go31
-rw-r--r--vendor/github.com/opencontainers/image-spec/LICENSE191
-rw-r--r--vendor/github.com/opencontainers/image-spec/README.md167
-rw-r--r--vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go103
-rw-r--r--vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go68
-rw-r--r--vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go29
-rw-r--r--vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go28
-rw-r--r--vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go32
-rw-r--r--vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go48
-rw-r--r--vendor/github.com/opencontainers/image-spec/specs-go/version.go32
-rw-r--r--vendor/github.com/opencontainers/image-spec/specs-go/versioned.go23
-rw-r--r--vendor/github.com/opencontainers/runc/LICENSE191
-rw-r--r--vendor/github.com/opencontainers/runc/NOTICE17
-rw-r--r--vendor/github.com/opencontainers/runc/README.md222
-rw-r--r--vendor/github.com/opencontainers/runc/VERSION1
-rw-r--r--vendor/github.com/opencontainers/runc/checkpoint.go132
-rw-r--r--vendor/github.com/opencontainers/runc/create.go74
-rw-r--r--vendor/github.com/opencontainers/runc/delete.go84
-rw-r--r--vendor/github.com/opencontainers/runc/events.go260
-rw-r--r--vendor/github.com/opencontainers/runc/exec.go211
-rw-r--r--vendor/github.com/opencontainers/runc/kill.go115
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/README.md262
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor.go39
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor_disabled.go20
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/capabilities_linux.go114
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go64
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups_unsupported.go3
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go360
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/blkio.go237
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpu.go125
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuacct.go121
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go162
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go80
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/freezer.go61
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/fs_unsupported.go3
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/hugetlb.go71
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go305
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go40
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_cls.go43
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_prio.go41
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/perf_event.go35
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids.go73
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/utils.go78
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/rootless/rootless.go128
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go106
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_nosystemd.go55
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go555
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go447
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/compat_1.5_linux.go10
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/blkio_device.go61
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go124
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unsupported.go6
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_windows.go6
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/config.go343
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/config_unix.go63
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/device.go57
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/device_defaults.go111
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/hugepage_limit.go9
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/interface_priority_map.go14
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/mount.go39
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces.go5
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go31
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go13
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go127
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unsupported.go8
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/network.go72
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/validate/rootless.go117
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/configs/validate/validator.go195
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/console.go17
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/console_freebsd.go13
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/console_linux.go154
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/console_solaris.go11
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/console_windows.go30
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/container.go166
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/container_linux.go1573
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/container_solaris.go20
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/container_windows.go20
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go39
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/criu_opts_windows.go6
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go822
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto174
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unix.go106
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unsupported.go3
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/devices/number.go24
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/error.go70
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/factory.go44
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go344
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/generic_error.go92
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/init_linux.go500
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/keys/keyctl.go66
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/message_linux.go91
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/network_linux.go259
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/notify_linux.go89
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md44
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/nsenter/namespace.h32
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter.go12
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_gccgo.go25
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_unsupported.go5
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsexec.c863
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/process.go106
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/process_linux.go483
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/restored_process.go122
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go812
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/seccomp/config.go76
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go229
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_unsupported.go24
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/setgroups_linux.go11
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go63
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/specconv/example.go227
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/specconv/spec_linux.go805
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/stacktrace/capture.go27
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/stacktrace/frame.go38
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/stacktrace/stacktrace.go5
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go190
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/state_linux.go247
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/stats.go15
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/stats_freebsd.go5
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/stats_linux.go8
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/stats_solaris.go7
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/stats_windows.go5
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/sync.go107
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/system/linux.go143
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/system/proc.go43
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/system/setns_linux.go40
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_386.go25
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_64.go25
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_arm.go25
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig.go12
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig_notcgo.go15
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/system/unsupported.go9
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/system/xattrs_linux.go99
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go110
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go30
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go21
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/user/user.go441
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/utils/cmsg.go95
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go126
-rw-r--r--vendor/github.com/opencontainers/runc/libcontainer/utils/utils_unix.go43
-rw-r--r--vendor/github.com/opencontainers/runc/list.go175
-rw-r--r--vendor/github.com/opencontainers/runc/main.go149
-rw-r--r--vendor/github.com/opencontainers/runc/main_solaris.go21
-rw-r--r--vendor/github.com/opencontainers/runc/main_unix.go33
-rw-r--r--vendor/github.com/opencontainers/runc/main_unsupported.go13
-rw-r--r--vendor/github.com/opencontainers/runc/notify_socket.go108
-rw-r--r--vendor/github.com/opencontainers/runc/pause.go57
-rw-r--r--vendor/github.com/opencontainers/runc/ps.go109
-rw-r--r--vendor/github.com/opencontainers/runc/restore.go216
-rw-r--r--vendor/github.com/opencontainers/runc/rlimit_linux.go49
-rw-r--r--vendor/github.com/opencontainers/runc/run.go84
-rw-r--r--vendor/github.com/opencontainers/runc/signals.go135
-rw-r--r--vendor/github.com/opencontainers/runc/spec.go160
-rw-r--r--vendor/github.com/opencontainers/runc/start.go43
-rw-r--r--vendor/github.com/opencontainers/runc/state.go60
-rw-r--r--vendor/github.com/opencontainers/runc/tty.go134
-rw-r--r--vendor/github.com/opencontainers/runc/update.go259
-rw-r--r--vendor/github.com/opencontainers/runc/utils.go82
-rw-r--r--vendor/github.com/opencontainers/runc/utils_linux.go378
-rw-r--r--vendor/github.com/opencontainers/runc/vendor.conf21
-rw-r--r--vendor/github.com/opencontainers/runtime-spec/LICENSE191
-rw-r--r--vendor/github.com/opencontainers/runtime-spec/README.md164
-rw-r--r--vendor/github.com/opencontainers/runtime-spec/specs-go/config.go563
-rw-r--r--vendor/github.com/opencontainers/runtime-spec/specs-go/state.go17
-rw-r--r--vendor/github.com/opencontainers/runtime-spec/specs-go/version.go18
-rw-r--r--vendor/github.com/opencontainers/selinux/LICENSE201
-rw-r--r--vendor/github.com/opencontainers/selinux/README.md7
-rw-r--r--vendor/github.com/opencontainers/selinux/go-selinux/label/label.go84
-rw-r--r--vendor/github.com/opencontainers/selinux/go-selinux/label/label_selinux.go204
-rw-r--r--vendor/github.com/opencontainers/selinux/go-selinux/selinux.go593
-rw-r--r--vendor/github.com/opencontainers/selinux/go-selinux/xattrs.go78
-rw-r--r--vendor/github.com/pborman/uuid/LICENSE27
-rw-r--r--vendor/github.com/pborman/uuid/README.md13
-rwxr-xr-xvendor/github.com/pborman/uuid/dce.go84
-rwxr-xr-xvendor/github.com/pborman/uuid/doc.go8
-rw-r--r--vendor/github.com/pborman/uuid/hash.go53
-rw-r--r--vendor/github.com/pborman/uuid/json.go34
-rwxr-xr-xvendor/github.com/pborman/uuid/node.go117
-rw-r--r--vendor/github.com/pborman/uuid/sql.go58
-rwxr-xr-xvendor/github.com/pborman/uuid/time.go132
-rw-r--r--vendor/github.com/pborman/uuid/util.go43
-rw-r--r--vendor/github.com/pborman/uuid/uuid.go176
-rw-r--r--vendor/github.com/pborman/uuid/version1.go41
-rw-r--r--vendor/github.com/pborman/uuid/version4.go25
-rw-r--r--vendor/github.com/philhofer/fwd/LICENSE.md7
-rw-r--r--vendor/github.com/philhofer/fwd/README.md315
-rw-r--r--vendor/github.com/philhofer/fwd/reader.go379
-rw-r--r--vendor/github.com/philhofer/fwd/writer.go224
-rw-r--r--vendor/github.com/philhofer/fwd/writer_appengine.go5
-rw-r--r--vendor/github.com/philhofer/fwd/writer_unsafe.go18
-rw-r--r--vendor/github.com/pivotal-golang/clock/LICENSE202
-rw-r--r--vendor/github.com/pivotal-golang/clock/README.md1
-rw-r--r--vendor/github.com/pivotal-golang/clock/clock.go42
-rw-r--r--vendor/github.com/pivotal-golang/clock/ticker.go20
-rw-r--r--vendor/github.com/pivotal-golang/clock/timer.go25
-rw-r--r--vendor/github.com/pkg/errors/LICENSE23
-rw-r--r--vendor/github.com/pkg/errors/README.md52
-rw-r--r--vendor/github.com/pkg/errors/errors.go269
-rw-r--r--vendor/github.com/pkg/errors/stack.go178
-rw-r--r--vendor/github.com/pmezard/go-difflib/LICENSE27
-rw-r--r--vendor/github.com/pmezard/go-difflib/README.md50
-rw-r--r--vendor/github.com/pmezard/go-difflib/difflib/difflib.go772
-rw-r--r--vendor/github.com/prometheus/client_golang/LICENSE201
-rw-r--r--vendor/github.com/prometheus/client_golang/NOTICE28
-rw-r--r--vendor/github.com/prometheus/client_golang/README.md45
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/README.md53
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/collector.go75
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/counter.go173
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/desc.go192
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/doc.go111
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/expvar.go119
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/fnv.go29
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/gauge.go144
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/go_collector.go263
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/histogram.go448
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/http.go381
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/metric.go166
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/process_collector.go142
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/push.go65
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/registry.go741
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/summary.go538
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/untyped.go142
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/value.go234
-rw-r--r--vendor/github.com/prometheus/client_golang/prometheus/vec.go249
-rw-r--r--vendor/github.com/prometheus/client_model/LICENSE201
-rw-r--r--vendor/github.com/prometheus/client_model/NOTICE5
-rw-r--r--vendor/github.com/prometheus/client_model/README.md26
-rw-r--r--vendor/github.com/prometheus/client_model/go/metrics.pb.go364
-rw-r--r--vendor/github.com/prometheus/common/LICENSE201
-rw-r--r--vendor/github.com/prometheus/common/NOTICE5
-rw-r--r--vendor/github.com/prometheus/common/README.md12
-rw-r--r--vendor/github.com/prometheus/common/expfmt/decode.go412
-rw-r--r--vendor/github.com/prometheus/common/expfmt/encode.go88
-rw-r--r--vendor/github.com/prometheus/common/expfmt/expfmt.go40
-rw-r--r--vendor/github.com/prometheus/common/expfmt/fuzz.go36
-rw-r--r--vendor/github.com/prometheus/common/expfmt/text_create.go300
-rw-r--r--vendor/github.com/prometheus/common/expfmt/text_parse.go753
-rw-r--r--vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt67
-rw-r--r--vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go162
-rw-r--r--vendor/github.com/prometheus/common/model/alert.go136
-rw-r--r--vendor/github.com/prometheus/common/model/fingerprinting.go105
-rw-r--r--vendor/github.com/prometheus/common/model/fnv.go42
-rw-r--r--vendor/github.com/prometheus/common/model/labels.go206
-rw-r--r--vendor/github.com/prometheus/common/model/labelset.go169
-rw-r--r--vendor/github.com/prometheus/common/model/metric.go98
-rw-r--r--vendor/github.com/prometheus/common/model/model.go16
-rw-r--r--vendor/github.com/prometheus/common/model/signature.go144
-rw-r--r--vendor/github.com/prometheus/common/model/silence.go106
-rw-r--r--vendor/github.com/prometheus/common/model/time.go249
-rw-r--r--vendor/github.com/prometheus/common/model/value.go403
-rw-r--r--vendor/github.com/prometheus/procfs/LICENSE201
-rw-r--r--vendor/github.com/prometheus/procfs/NOTICE7
-rw-r--r--vendor/github.com/prometheus/procfs/README.md10
-rw-r--r--vendor/github.com/prometheus/procfs/doc.go45
-rw-r--r--vendor/github.com/prometheus/procfs/fs.go33
-rw-r--r--vendor/github.com/prometheus/procfs/ipvs.go224
-rw-r--r--vendor/github.com/prometheus/procfs/mdstat.go138
-rw-r--r--vendor/github.com/prometheus/procfs/proc.go212
-rw-r--r--vendor/github.com/prometheus/procfs/proc_io.go55
-rw-r--r--vendor/github.com/prometheus/procfs/proc_limits.go137
-rw-r--r--vendor/github.com/prometheus/procfs/proc_stat.go175
-rw-r--r--vendor/github.com/prometheus/procfs/stat.go56
-rw-r--r--vendor/github.com/rcrowley/go-metrics/LICENSE29
-rw-r--r--vendor/github.com/rcrowley/go-metrics/README.md139
-rw-r--r--vendor/github.com/rcrowley/go-metrics/counter.go112
-rw-r--r--vendor/github.com/rcrowley/go-metrics/debug.go76
-rw-r--r--vendor/github.com/rcrowley/go-metrics/ewma.go118
-rw-r--r--vendor/github.com/rcrowley/go-metrics/gauge.go84
-rw-r--r--vendor/github.com/rcrowley/go-metrics/gauge_float64.go91
-rw-r--r--vendor/github.com/rcrowley/go-metrics/graphite.go113
-rw-r--r--vendor/github.com/rcrowley/go-metrics/healthcheck.go61
-rw-r--r--vendor/github.com/rcrowley/go-metrics/histogram.go202
-rw-r--r--vendor/github.com/rcrowley/go-metrics/json.go83
-rw-r--r--vendor/github.com/rcrowley/go-metrics/log.go77
-rw-r--r--vendor/github.com/rcrowley/go-metrics/meter.go233
-rw-r--r--vendor/github.com/rcrowley/go-metrics/metrics.go13
-rw-r--r--vendor/github.com/rcrowley/go-metrics/opentsdb.go119
-rw-r--r--vendor/github.com/rcrowley/go-metrics/registry.go247
-rw-r--r--vendor/github.com/rcrowley/go-metrics/runtime.go212
-rw-r--r--vendor/github.com/rcrowley/go-metrics/runtime_cgo.go10
-rw-r--r--vendor/github.com/rcrowley/go-metrics/runtime_gccpufraction.go9
-rw-r--r--vendor/github.com/rcrowley/go-metrics/runtime_no_cgo.go7
-rw-r--r--vendor/github.com/rcrowley/go-metrics/runtime_no_gccpufraction.go9
-rw-r--r--vendor/github.com/rcrowley/go-metrics/sample.go609
-rw-r--r--vendor/github.com/rcrowley/go-metrics/syslog.go78
-rw-r--r--vendor/github.com/rcrowley/go-metrics/timer.go311
-rw-r--r--vendor/github.com/rcrowley/go-metrics/writer.go100
-rwxr-xr-xvendor/github.com/resin-os/circbuf/LICENSE20
-rw-r--r--vendor/github.com/resin-os/circbuf/README.md28
-rw-r--r--vendor/github.com/resin-os/circbuf/circbuf.go115
-rw-r--r--vendor/github.com/resin-os/librsync-go/LICENSE177
-rw-r--r--vendor/github.com/resin-os/librsync-go/README.md15
-rw-r--r--vendor/github.com/resin-os/librsync-go/delta.go83
-rw-r--r--vendor/github.com/resin-os/librsync-go/match.go151
-rw-r--r--vendor/github.com/resin-os/librsync-go/op.go539
-rw-r--r--vendor/github.com/resin-os/librsync-go/patch.go88
-rw-r--r--vendor/github.com/resin-os/librsync-go/rollsum.go67
-rw-r--r--vendor/github.com/resin-os/librsync-go/signature.go98
-rw-r--r--vendor/github.com/sean-/seed/LICENSE54
-rw-r--r--vendor/github.com/sean-/seed/README.md44
-rw-r--r--vendor/github.com/sean-/seed/init.go84
-rw-r--r--vendor/github.com/seccomp/libseccomp-golang/LICENSE22
-rw-r--r--vendor/github.com/seccomp/libseccomp-golang/README26
-rw-r--r--vendor/github.com/seccomp/libseccomp-golang/seccomp.go857
-rw-r--r--vendor/github.com/seccomp/libseccomp-golang/seccomp_internal.go506
-rw-r--r--vendor/github.com/spf13/cobra/LICENSE.txt174
-rw-r--r--vendor/github.com/spf13/cobra/README.md928
-rw-r--r--vendor/github.com/spf13/cobra/args.go98
-rw-r--r--vendor/github.com/spf13/cobra/bash_completions.go630
-rw-r--r--vendor/github.com/spf13/cobra/cobra.go175
-rw-r--r--vendor/github.com/spf13/cobra/command.go1359
-rw-r--r--vendor/github.com/spf13/cobra/command_notwin.go5
-rw-r--r--vendor/github.com/spf13/cobra/command_win.go26
-rw-r--r--vendor/github.com/spf13/pflag/LICENSE28
-rw-r--r--vendor/github.com/spf13/pflag/README.md277
-rw-r--r--vendor/github.com/spf13/pflag/bool.go94
-rw-r--r--vendor/github.com/spf13/pflag/bool_slice.go147
-rw-r--r--vendor/github.com/spf13/pflag/count.go94
-rw-r--r--vendor/github.com/spf13/pflag/duration.go86
-rw-r--r--vendor/github.com/spf13/pflag/flag.go1063
-rw-r--r--vendor/github.com/spf13/pflag/float32.go88
-rw-r--r--vendor/github.com/spf13/pflag/float64.go84
-rw-r--r--vendor/github.com/spf13/pflag/golangflag.go101
-rw-r--r--vendor/github.com/spf13/pflag/int.go84
-rw-r--r--vendor/github.com/spf13/pflag/int32.go88
-rw-r--r--vendor/github.com/spf13/pflag/int64.go84
-rw-r--r--vendor/github.com/spf13/pflag/int8.go88
-rw-r--r--vendor/github.com/spf13/pflag/int_slice.go128
-rw-r--r--vendor/github.com/spf13/pflag/ip.go94
-rw-r--r--vendor/github.com/spf13/pflag/ip_slice.go148
-rw-r--r--vendor/github.com/spf13/pflag/ipmask.go122
-rw-r--r--vendor/github.com/spf13/pflag/ipnet.go98
-rw-r--r--vendor/github.com/spf13/pflag/string.go80
-rw-r--r--vendor/github.com/spf13/pflag/string_array.go103
-rw-r--r--vendor/github.com/spf13/pflag/string_slice.go129
-rw-r--r--vendor/github.com/spf13/pflag/uint.go88
-rw-r--r--vendor/github.com/spf13/pflag/uint16.go88
-rw-r--r--vendor/github.com/spf13/pflag/uint32.go88
-rw-r--r--vendor/github.com/spf13/pflag/uint64.go88
-rw-r--r--vendor/github.com/spf13/pflag/uint8.go88
-rw-r--r--vendor/github.com/spf13/pflag/uint_slice.go126
-rw-r--r--vendor/github.com/stevvooe/continuity/LICENSE202
-rw-r--r--vendor/github.com/stevvooe/continuity/README.md19
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/asm.s10
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/chmod_darwin.go18
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/chmod_darwin_386.go25
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/chmod_darwin_amd64.go25
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/chmod_freebsd.go17
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/chmod_freebsd_amd64.go25
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/chmod_linux.go12
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/copy_linux.go9
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/copy_linux_386.go20
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/copy_linux_amd64.go20
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/copy_linux_arm.go20
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/copy_linux_arm64.go20
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/nodata_linux.go7
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/nodata_unix.go9
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/sys.go37
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_386.go7
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_amd64.go7
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_arm.go7
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_arm64.go7
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr.go67
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_darwin.go71
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_darwin_386.go111
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_darwin_amd64.go111
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_freebsd.go53
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_linux.go61
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_linux_386.go111
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_linux_amd64.go111
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_linux_arm.go111
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_linux_arm64.go111
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_linux_ppc64.go111
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_linux_ppc64le.go111
-rw-r--r--vendor/github.com/stevvooe/continuity/sysx/xattr_linux_s390x.go111
-rw-r--r--vendor/github.com/stretchr/testify/LICENSE22
-rw-r--r--vendor/github.com/stretchr/testify/README.md332
-rw-r--r--vendor/github.com/stretchr/testify/assert/assertion_forward.go352
-rw-r--r--vendor/github.com/stretchr/testify/assert/assertions.go1069
-rw-r--r--vendor/github.com/stretchr/testify/assert/doc.go45
-rw-r--r--vendor/github.com/stretchr/testify/assert/errors.go10
-rw-r--r--vendor/github.com/stretchr/testify/assert/forward_assertions.go16
-rw-r--r--vendor/github.com/stretchr/testify/assert/http_assertions.go106
-rw-r--r--vendor/github.com/stretchr/testify/require/doc.go28
-rw-r--r--vendor/github.com/stretchr/testify/require/forward_requirements.go16
-rw-r--r--vendor/github.com/stretchr/testify/require/require.go429
-rw-r--r--vendor/github.com/stretchr/testify/require/require_forward.go353
-rw-r--r--vendor/github.com/stretchr/testify/require/requirements.go9
-rw-r--r--vendor/github.com/syndtr/gocapability/LICENSE24
-rw-r--r--vendor/github.com/syndtr/gocapability/capability/capability.go72
-rw-r--r--vendor/github.com/syndtr/gocapability/capability/capability_linux.go650
-rw-r--r--vendor/github.com/syndtr/gocapability/capability/capability_noop.go19
-rw-r--r--vendor/github.com/syndtr/gocapability/capability/enum.go268
-rw-r--r--vendor/github.com/syndtr/gocapability/capability/enum_gen.go129
-rw-r--r--vendor/github.com/syndtr/gocapability/capability/syscall_linux.go154
-rw-r--r--vendor/github.com/tchap/go-patricia/LICENSE20
-rw-r--r--vendor/github.com/tchap/go-patricia/README.md123
-rw-r--r--vendor/github.com/tchap/go-patricia/patricia/children.go325
-rw-r--r--vendor/github.com/tchap/go-patricia/patricia/patricia.go594
-rw-r--r--vendor/github.com/tinylib/msgp/LICENSE8
-rw-r--r--vendor/github.com/tinylib/msgp/README.md104
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/circular.go38
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/defs.go142
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/edit.go241
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/elsize.go99
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/errors.go142
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/extension.go548
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/integers.go174
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/json.go542
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/json_bytes.go363
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/number.go140
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/number_appengine.go101
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/number_unsafe.go159
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/read.go1118
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/read_bytes.go1073
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/size.go38
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/write.go768
-rw-r--r--vendor/github.com/tinylib/msgp/msgp/write_bytes.go369
-rw-r--r--vendor/github.com/tonistiigi/fifo/LICENSE21
-rw-r--r--vendor/github.com/tonistiigi/fifo/fifo.go217
-rw-r--r--vendor/github.com/tonistiigi/fifo/handle_linux.go76
-rw-r--r--vendor/github.com/tonistiigi/fifo/handle_nolinux.go49
-rw-r--r--vendor/github.com/tonistiigi/fifo/readme.md30
-rw-r--r--vendor/github.com/tonistiigi/fsutil/LICENSE22
-rw-r--r--vendor/github.com/tonistiigi/fsutil/diff.go37
-rw-r--r--vendor/github.com/tonistiigi/fsutil/diff_containerd.go199
-rw-r--r--vendor/github.com/tonistiigi/fsutil/diff_containerd_linux.go37
-rw-r--r--vendor/github.com/tonistiigi/fsutil/diskwriter.go353
-rw-r--r--vendor/github.com/tonistiigi/fsutil/diskwriter_linux.go64
-rw-r--r--vendor/github.com/tonistiigi/fsutil/diskwriter_windows.go25
-rw-r--r--vendor/github.com/tonistiigi/fsutil/generate.go3
-rw-r--r--vendor/github.com/tonistiigi/fsutil/hardlinks.go46
-rw-r--r--vendor/github.com/tonistiigi/fsutil/readme.md45
-rw-r--r--vendor/github.com/tonistiigi/fsutil/receive.go210
-rw-r--r--vendor/github.com/tonistiigi/fsutil/receive_unsupported.go14
-rw-r--r--vendor/github.com/tonistiigi/fsutil/send.go201
-rw-r--r--vendor/github.com/tonistiigi/fsutil/stat.pb.go931
-rw-r--r--vendor/github.com/tonistiigi/fsutil/stat.proto17
-rw-r--r--vendor/github.com/tonistiigi/fsutil/validator.go88
-rw-r--r--vendor/github.com/tonistiigi/fsutil/walker.go170
-rw-r--r--vendor/github.com/tonistiigi/fsutil/walker_unix.go61
-rw-r--r--vendor/github.com/tonistiigi/fsutil/walker_windows.go14
-rw-r--r--vendor/github.com/tonistiigi/fsutil/wire.pb.go563
-rw-r--r--vendor/github.com/tonistiigi/fsutil/wire.proto18
-rw-r--r--vendor/github.com/urfave/cli/LICENSE21
-rw-r--r--vendor/github.com/urfave/cli/README.md1381
-rw-r--r--vendor/github.com/urfave/cli/app.go492
-rw-r--r--vendor/github.com/urfave/cli/category.go44
-rw-r--r--vendor/github.com/urfave/cli/cli.go21
-rw-r--r--vendor/github.com/urfave/cli/command.go299
-rw-r--r--vendor/github.com/urfave/cli/context.go276
-rw-r--r--vendor/github.com/urfave/cli/errors.go115
-rw-r--r--vendor/github.com/urfave/cli/flag.go799
-rw-r--r--vendor/github.com/urfave/cli/flag_generated.go627
-rw-r--r--vendor/github.com/urfave/cli/funcs.go28
-rw-r--r--vendor/github.com/urfave/cli/help.go294
-rw-r--r--vendor/github.com/vbatts/tar-split/LICENSE28
-rw-r--r--vendor/github.com/vbatts/tar-split/README.md137
-rw-r--r--vendor/github.com/vbatts/tar-split/archive/tar/common.go340
-rw-r--r--vendor/github.com/vbatts/tar-split/archive/tar/reader.go1064
-rw-r--r--vendor/github.com/vbatts/tar-split/archive/tar/stat_atim.go20
-rw-r--r--vendor/github.com/vbatts/tar-split/archive/tar/stat_atimespec.go20
-rw-r--r--vendor/github.com/vbatts/tar-split/archive/tar/stat_unix.go32
-rw-r--r--vendor/github.com/vbatts/tar-split/archive/tar/writer.go416
-rw-r--r--vendor/github.com/vbatts/tar-split/tar/asm/README.md44
-rw-r--r--vendor/github.com/vbatts/tar-split/tar/asm/assemble.go130
-rw-r--r--vendor/github.com/vbatts/tar-split/tar/asm/disassemble.go141
-rw-r--r--vendor/github.com/vbatts/tar-split/tar/asm/doc.go9
-rw-r--r--vendor/github.com/vbatts/tar-split/tar/storage/doc.go12
-rw-r--r--vendor/github.com/vbatts/tar-split/tar/storage/entry.go78
-rw-r--r--vendor/github.com/vbatts/tar-split/tar/storage/getter.go104
-rw-r--r--vendor/github.com/vbatts/tar-split/tar/storage/packer.go127
-rw-r--r--vendor/github.com/vdemeester/shakers/LICENSE191
-rw-r--r--vendor/github.com/vdemeester/shakers/README.md30
-rw-r--r--vendor/github.com/vdemeester/shakers/bool.go46
-rw-r--r--vendor/github.com/vdemeester/shakers/common.go310
-rw-r--r--vendor/github.com/vdemeester/shakers/string.go168
-rw-r--r--vendor/github.com/vdemeester/shakers/time.go234
-rw-r--r--vendor/github.com/vishvananda/netlink/LICENSE192
-rw-r--r--vendor/github.com/vishvananda/netlink/README.md89
-rw-r--r--vendor/github.com/vishvananda/netlink/addr.go56
-rw-r--r--vendor/github.com/vishvananda/netlink/addr_linux.go288
-rw-r--r--vendor/github.com/vishvananda/netlink/bpf_linux.go62
-rw-r--r--vendor/github.com/vishvananda/netlink/class.go78
-rw-r--r--vendor/github.com/vishvananda/netlink/class_linux.go254
-rw-r--r--vendor/github.com/vishvananda/netlink/conntrack_linux.go344
-rw-r--r--vendor/github.com/vishvananda/netlink/conntrack_unspecified.go53
-rw-r--r--vendor/github.com/vishvananda/netlink/filter.go283
-rw-r--r--vendor/github.com/vishvananda/netlink/filter_linux.go591
-rw-r--r--vendor/github.com/vishvananda/netlink/genetlink_linux.go167
-rw-r--r--vendor/github.com/vishvananda/netlink/genetlink_unspecified.go25
-rw-r--r--vendor/github.com/vishvananda/netlink/gtp_linux.go238
-rw-r--r--vendor/github.com/vishvananda/netlink/handle_linux.go111
-rw-r--r--vendor/github.com/vishvananda/netlink/handle_unspecified.go218
-rw-r--r--vendor/github.com/vishvananda/netlink/link.go773
-rw-r--r--vendor/github.com/vishvananda/netlink/link_linux.go1798
-rw-r--r--vendor/github.com/vishvananda/netlink/link_tuntap_linux.go14
-rw-r--r--vendor/github.com/vishvananda/netlink/neigh.go22
-rw-r--r--vendor/github.com/vishvananda/netlink/neigh_linux.go250
-rw-r--r--vendor/github.com/vishvananda/netlink/netlink.go39
-rw-r--r--vendor/github.com/vishvananda/netlink/netlink_linux.go11
-rw-r--r--vendor/github.com/vishvananda/netlink/netlink_unspecified.go221
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/addr_linux.go76
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/conntrack_linux.go189
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/genetlink_linux.go89
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/link_linux.go524
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/mpls_linux.go36
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/nl_linux.go718
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/nl_unspecified.go11
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/route_linux.go80
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/syscall.go68
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/tc_linux.go675
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/xfrm_linux.go296
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/xfrm_monitor_linux.go32
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go119
-rw-r--r--vendor/github.com/vishvananda/netlink/nl/xfrm_state_linux.go334
-rw-r--r--vendor/github.com/vishvananda/netlink/order.go32
-rw-r--r--vendor/github.com/vishvananda/netlink/protinfo.go58
-rw-r--r--vendor/github.com/vishvananda/netlink/protinfo_linux.go74
-rw-r--r--vendor/github.com/vishvananda/netlink/qdisc.go232
-rw-r--r--vendor/github.com/vishvananda/netlink/qdisc_linux.go527
-rw-r--r--vendor/github.com/vishvananda/netlink/route.go116
-rw-r--r--vendor/github.com/vishvananda/netlink/route_linux.go674
-rw-r--r--vendor/github.com/vishvananda/netlink/route_unspecified.go11
-rw-r--r--vendor/github.com/vishvananda/netlink/rule.go40
-rw-r--r--vendor/github.com/vishvananda/netlink/rule_linux.go221
-rw-r--r--vendor/github.com/vishvananda/netlink/socket.go27
-rw-r--r--vendor/github.com/vishvananda/netlink/socket_linux.go159
-rw-r--r--vendor/github.com/vishvananda/netlink/xfrm.go74
-rw-r--r--vendor/github.com/vishvananda/netlink/xfrm_monitor_linux.go98
-rw-r--r--vendor/github.com/vishvananda/netlink/xfrm_policy.go74
-rw-r--r--vendor/github.com/vishvananda/netlink/xfrm_policy_linux.go257
-rw-r--r--vendor/github.com/vishvananda/netlink/xfrm_state.go108
-rw-r--r--vendor/github.com/vishvananda/netlink/xfrm_state_linux.go444
-rw-r--r--vendor/github.com/vishvananda/netns/LICENSE192
-rw-r--r--vendor/github.com/vishvananda/netns/README.md49
-rw-r--r--vendor/github.com/vishvananda/netns/netns.go67
-rw-r--r--vendor/github.com/vishvananda/netns/netns_linux.go205
-rw-r--r--vendor/github.com/vishvananda/netns/netns_linux_386.go7
-rw-r--r--vendor/github.com/vishvananda/netns/netns_linux_amd64.go7
-rw-r--r--vendor/github.com/vishvananda/netns/netns_linux_arm.go7
-rw-r--r--vendor/github.com/vishvananda/netns/netns_linux_arm64.go7
-rw-r--r--vendor/github.com/vishvananda/netns/netns_linux_ppc64le.go7
-rw-r--r--vendor/github.com/vishvananda/netns/netns_linux_s390x.go7
-rw-r--r--vendor/github.com/vishvananda/netns/netns_unspecified.go35
-rw-r--r--vendor/github.com/xeipuuv/gojsonpointer/LICENSE-APACHE-2.0.txt202
-rw-r--r--vendor/github.com/xeipuuv/gojsonpointer/README.md8
-rw-r--r--vendor/github.com/xeipuuv/gojsonpointer/pointer.go217
-rw-r--r--vendor/github.com/xeipuuv/gojsonreference/LICENSE-APACHE-2.0.txt202
-rw-r--r--vendor/github.com/xeipuuv/gojsonreference/README.md10
-rw-r--r--vendor/github.com/xeipuuv/gojsonreference/reference.go141
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/LICENSE-APACHE-2.0.txt202
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/README.md236
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/errors.go242
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/format_checkers.go178
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/internalLog.go37
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/jsonContext.go72
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go286
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/locales.go275
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/result.go171
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/schema.go908
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/schemaPool.go107
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/schemaReferencePool.go67
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/schemaType.go83
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/subSchema.go227
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/types.go58
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/utils.go202
-rw-r--r--vendor/github.com/xeipuuv/gojsonschema/validation.go829
-rw-r--r--vendor/golang.org/x/crypto/LICENSE27
-rw-r--r--vendor/golang.org/x/crypto/PATENTS22
-rw-r--r--vendor/golang.org/x/crypto/README3
-rw-r--r--vendor/golang.org/x/crypto/blake2b/blake2b.go207
-rw-r--r--vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go43
-rw-r--r--vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s762
-rw-r--r--vendor/golang.org/x/crypto/blake2b/blake2b_amd64.go25
-rw-r--r--vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s290
-rw-r--r--vendor/golang.org/x/crypto/blake2b/blake2b_generic.go179
-rw-r--r--vendor/golang.org/x/crypto/blake2b/blake2b_ref.go11
-rw-r--r--vendor/golang.org/x/crypto/blake2b/blake2x.go177
-rw-r--r--vendor/golang.org/x/crypto/blake2b/register.go32
-rw-r--r--vendor/golang.org/x/crypto/curve25519/const_amd64.h8
-rw-r--r--vendor/golang.org/x/crypto/curve25519/const_amd64.s20
-rw-r--r--vendor/golang.org/x/crypto/curve25519/cswap_amd64.s65
-rw-r--r--vendor/golang.org/x/crypto/curve25519/curve25519.go834
-rw-r--r--vendor/golang.org/x/crypto/curve25519/doc.go23
-rw-r--r--vendor/golang.org/x/crypto/curve25519/freeze_amd64.s73
-rw-r--r--vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s1377
-rw-r--r--vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go240
-rw-r--r--vendor/golang.org/x/crypto/curve25519/mul_amd64.s169
-rw-r--r--vendor/golang.org/x/crypto/curve25519/square_amd64.s132
-rw-r--r--vendor/golang.org/x/crypto/md4/md4.go118
-rw-r--r--vendor/golang.org/x/crypto/md4/md4block.go89
-rw-r--r--vendor/golang.org/x/crypto/nacl/secretbox/secretbox.go149
-rw-r--r--vendor/golang.org/x/crypto/pkcs12/bmp-string.go50
-rw-r--r--vendor/golang.org/x/crypto/pkcs12/crypto.go131
-rw-r--r--vendor/golang.org/x/crypto/pkcs12/errors.go23
-rw-r--r--vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go274
-rw-r--r--vendor/golang.org/x/crypto/pkcs12/mac.go45
-rw-r--r--vendor/golang.org/x/crypto/pkcs12/pbkdf.go170
-rw-r--r--vendor/golang.org/x/crypto/pkcs12/pkcs12.go346
-rw-r--r--vendor/golang.org/x/crypto/pkcs12/safebags.go57
-rw-r--r--vendor/golang.org/x/crypto/poly1305/poly1305.go33
-rw-r--r--vendor/golang.org/x/crypto/poly1305/sum_amd64.go22
-rw-r--r--vendor/golang.org/x/crypto/poly1305/sum_amd64.s125
-rw-r--r--vendor/golang.org/x/crypto/poly1305/sum_arm.go22
-rw-r--r--vendor/golang.org/x/crypto/poly1305/sum_arm.s427
-rw-r--r--vendor/golang.org/x/crypto/poly1305/sum_ref.go141
-rw-r--r--vendor/golang.org/x/crypto/salsa20/salsa/hsalsa20.go144
-rw-r--r--vendor/golang.org/x/crypto/salsa20/salsa/salsa2020_amd64.s889
-rw-r--r--vendor/golang.org/x/crypto/salsa20/salsa/salsa208.go199
-rw-r--r--vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go23
-rw-r--r--vendor/golang.org/x/crypto/salsa20/salsa/salsa20_ref.go234
-rw-r--r--vendor/golang.org/x/net/LICENSE27
-rw-r--r--vendor/golang.org/x/net/PATENTS22
-rw-r--r--vendor/golang.org/x/net/README3
-rw-r--r--vendor/golang.org/x/net/context/context.go156
-rw-r--r--vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go74
-rw-r--r--vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go147
-rw-r--r--vendor/golang.org/x/net/context/go17.go72
-rw-r--r--vendor/golang.org/x/net/context/pre_go17.go300
-rw-r--r--vendor/golang.org/x/net/http2/README20
-rw-r--r--vendor/golang.org/x/net/http2/ciphers.go641
-rw-r--r--vendor/golang.org/x/net/http2/client_conn_pool.go256
-rw-r--r--vendor/golang.org/x/net/http2/configure_transport.go80
-rw-r--r--vendor/golang.org/x/net/http2/databuffer.go146
-rw-r--r--vendor/golang.org/x/net/http2/errors.go130
-rw-r--r--vendor/golang.org/x/net/http2/flow.go50
-rw-r--r--vendor/golang.org/x/net/http2/frame.go1579
-rw-r--r--vendor/golang.org/x/net/http2/go16.go16
-rw-r--r--vendor/golang.org/x/net/http2/go17.go106
-rw-r--r--vendor/golang.org/x/net/http2/go17_not18.go36
-rw-r--r--vendor/golang.org/x/net/http2/go18.go54
-rw-r--r--vendor/golang.org/x/net/http2/go19.go16
-rw-r--r--vendor/golang.org/x/net/http2/gotrack.go170
-rw-r--r--vendor/golang.org/x/net/http2/headermap.go78
-rw-r--r--vendor/golang.org/x/net/http2/hpack/encode.go240
-rw-r--r--vendor/golang.org/x/net/http2/hpack/hpack.go490
-rw-r--r--vendor/golang.org/x/net/http2/hpack/huffman.go212
-rw-r--r--vendor/golang.org/x/net/http2/hpack/tables.go479
-rw-r--r--vendor/golang.org/x/net/http2/http2.go387
-rw-r--r--vendor/golang.org/x/net/http2/not_go16.go21
-rw-r--r--vendor/golang.org/x/net/http2/not_go17.go87
-rw-r--r--vendor/golang.org/x/net/http2/not_go18.go27
-rw-r--r--vendor/golang.org/x/net/http2/not_go19.go16
-rw-r--r--vendor/golang.org/x/net/http2/pipe.go163
-rw-r--r--vendor/golang.org/x/net/http2/server.go2842
-rw-r--r--vendor/golang.org/x/net/http2/transport.go2123
-rw-r--r--vendor/golang.org/x/net/http2/write.go370
-rw-r--r--vendor/golang.org/x/net/http2/writesched.go242
-rw-r--r--vendor/golang.org/x/net/http2/writesched_priority.go452
-rw-r--r--vendor/golang.org/x/net/http2/writesched_random.go72
-rw-r--r--vendor/golang.org/x/net/idna/idna.go668
-rw-r--r--vendor/golang.org/x/net/idna/punycode.go203
-rw-r--r--vendor/golang.org/x/net/idna/tables.go4477
-rw-r--r--vendor/golang.org/x/net/idna/trie.go72
-rw-r--r--vendor/golang.org/x/net/idna/trieval.go114
-rw-r--r--vendor/golang.org/x/net/internal/timeseries/timeseries.go525
-rw-r--r--vendor/golang.org/x/net/lex/httplex/httplex.go351
-rw-r--r--vendor/golang.org/x/net/proxy/direct.go18
-rw-r--r--vendor/golang.org/x/net/proxy/per_host.go140
-rw-r--r--vendor/golang.org/x/net/proxy/proxy.go94
-rw-r--r--vendor/golang.org/x/net/proxy/socks5.go213
-rw-r--r--vendor/golang.org/x/net/trace/events.go532
-rw-r--r--vendor/golang.org/x/net/trace/histogram.go365
-rw-r--r--vendor/golang.org/x/net/trace/trace.go1066
-rw-r--r--vendor/golang.org/x/net/trace/trace_go16.go21
-rw-r--r--vendor/golang.org/x/net/trace/trace_go17.go21
-rw-r--r--vendor/golang.org/x/net/websocket/client.go106
-rw-r--r--vendor/golang.org/x/net/websocket/dial.go24
-rw-r--r--vendor/golang.org/x/net/websocket/hybi.go583
-rw-r--r--vendor/golang.org/x/net/websocket/server.go113
-rw-r--r--vendor/golang.org/x/net/websocket/websocket.go448
-rw-r--r--vendor/golang.org/x/oauth2/LICENSE27
-rw-r--r--vendor/golang.org/x/oauth2/README.md65
-rw-r--r--vendor/golang.org/x/oauth2/client_appengine.go25
-rw-r--r--vendor/golang.org/x/oauth2/google/appengine.go89
-rw-r--r--vendor/golang.org/x/oauth2/google/appengine_hook.go14
-rw-r--r--vendor/golang.org/x/oauth2/google/appenginevm_hook.go15
-rw-r--r--vendor/golang.org/x/oauth2/google/default.go130
-rw-r--r--vendor/golang.org/x/oauth2/google/google.go202
-rw-r--r--vendor/golang.org/x/oauth2/google/jwt.go74
-rw-r--r--vendor/golang.org/x/oauth2/google/sdk.go172
-rw-r--r--vendor/golang.org/x/oauth2/internal/oauth2.go76
-rw-r--r--vendor/golang.org/x/oauth2/internal/token.go227
-rw-r--r--vendor/golang.org/x/oauth2/internal/transport.go69
-rw-r--r--vendor/golang.org/x/oauth2/jws/jws.go182
-rw-r--r--vendor/golang.org/x/oauth2/jwt/jwt.go157
-rw-r--r--vendor/golang.org/x/oauth2/oauth2.go341
-rw-r--r--vendor/golang.org/x/oauth2/token.go158
-rw-r--r--vendor/golang.org/x/oauth2/transport.go132
-rw-r--r--vendor/golang.org/x/sync/LICENSE27
-rw-r--r--vendor/golang.org/x/sync/PATENTS22
-rw-r--r--vendor/golang.org/x/sync/README2
-rw-r--r--vendor/golang.org/x/sync/errgroup/errgroup.go67
-rw-r--r--vendor/golang.org/x/sync/singleflight/singleflight.go111
-rw-r--r--vendor/golang.org/x/sync/syncmap/map.go372
-rw-r--r--vendor/golang.org/x/sys/LICENSE27
-rw-r--r--vendor/golang.org/x/sys/PATENTS22
-rw-r--r--vendor/golang.org/x/sys/README3
-rw-r--r--vendor/golang.org/x/sys/unix/README.md173
-rw-r--r--vendor/golang.org/x/sys/unix/asm_darwin_386.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_darwin_amd64.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_darwin_arm.s30
-rw-r--r--vendor/golang.org/x/sys/unix/asm_darwin_arm64.s30
-rw-r--r--vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_freebsd_386.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_freebsd_arm.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_linux_386.s35
-rw-r--r--vendor/golang.org/x/sys/unix/asm_linux_amd64.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_linux_arm.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_linux_arm64.s24
-rw-r--r--vendor/golang.org/x/sys/unix/asm_linux_mips64x.s28
-rw-r--r--vendor/golang.org/x/sys/unix/asm_linux_mipsx.s31
-rw-r--r--vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s28
-rw-r--r--vendor/golang.org/x/sys/unix/asm_linux_s390x.s28
-rw-r--r--vendor/golang.org/x/sys/unix/asm_netbsd_386.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_netbsd_arm.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_openbsd_386.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_openbsd_arm.s29
-rw-r--r--vendor/golang.org/x/sys/unix/asm_solaris_amd64.s17
-rw-r--r--vendor/golang.org/x/sys/unix/bluetooth_linux.go35
-rw-r--r--vendor/golang.org/x/sys/unix/cap_freebsd.go195
-rw-r--r--vendor/golang.org/x/sys/unix/constants.go13
-rw-r--r--vendor/golang.org/x/sys/unix/dev_linux.go42
-rw-r--r--vendor/golang.org/x/sys/unix/dirent.go102
-rw-r--r--vendor/golang.org/x/sys/unix/endian_big.go9
-rw-r--r--vendor/golang.org/x/sys/unix/endian_little.go9
-rw-r--r--vendor/golang.org/x/sys/unix/env_unix.go27
-rw-r--r--vendor/golang.org/x/sys/unix/env_unset.go14
-rw-r--r--vendor/golang.org/x/sys/unix/errors_freebsd_386.go227
-rw-r--r--vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go227
-rw-r--r--vendor/golang.org/x/sys/unix/errors_freebsd_arm.go226
-rw-r--r--vendor/golang.org/x/sys/unix/file_unix.go27
-rw-r--r--vendor/golang.org/x/sys/unix/flock.go22
-rw-r--r--vendor/golang.org/x/sys/unix/flock_linux_32bit.go13
-rw-r--r--vendor/golang.org/x/sys/unix/gccgo.go46
-rw-r--r--vendor/golang.org/x/sys/unix/gccgo_c.c41
-rw-r--r--vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go20
-rw-r--r--vendor/golang.org/x/sys/unix/gccgo_linux_sparc64.go20
-rw-r--r--vendor/golang.org/x/sys/unix/openbsd_pledge.go38
-rw-r--r--vendor/golang.org/x/sys/unix/race.go30
-rw-r--r--vendor/golang.org/x/sys/unix/race0.go25
-rw-r--r--vendor/golang.org/x/sys/unix/sockcmsg_linux.go36
-rw-r--r--vendor/golang.org/x/sys/unix/sockcmsg_unix.go104
-rw-r--r--vendor/golang.org/x/sys/unix/str.go26
-rw-r--r--vendor/golang.org/x/sys/unix/syscall.go69
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_bsd.go635
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_darwin.go536
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_darwin_386.go77
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go77
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_darwin_arm.go71
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go77
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_dragonfly.go415
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go61
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_freebsd.go708
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_freebsd_386.go61
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go61
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go61
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux.go1459
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux_386.go399
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux_amd64.go152
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go13
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux_arm.go263
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux_arm64.go191
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go209
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go239
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go135
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux_s390x.go328
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go169
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_netbsd.go472
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_netbsd_386.go42
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go42
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go42
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_no_getwd.go11
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_openbsd.go282
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_openbsd_386.go42
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go42
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go44
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_solaris.go716
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go35
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_unix.go293
-rw-r--r--vendor/golang.org/x/sys/unix/syscall_unix_gc.go15
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_darwin_386.go1673
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go1673
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go1673
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go1673
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go1568
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go1706
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go1707
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go1715
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_386.go2187
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go2188
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_arm.go2192
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go2177
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_mips.go2196
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go2196
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go2196
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go2196
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go2250
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go2250
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go2249
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go2142
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go1712
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go1702
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go1691
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go1584
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go1583
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go1586
-rw-r--r--vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go1483
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go1609
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go1609
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go1609
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go1609
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go1440
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go1877
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go1877
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go1877
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_386.go1953
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go2146
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go2055
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go2039
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go2111
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go2105
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go2105
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go2111
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go2157
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go2157
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go1937
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go1833
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go1346
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go1346
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go1346
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go1404
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go1404
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go1404
-rw-r--r--vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go1600
-rw-r--r--vendor/golang.org/x/sys/unix/zsysctl_openbsd.go270
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_darwin_386.go398
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go398
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_darwin_arm.go426
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go426
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go315
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go353
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go353
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go353
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_386.go388
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go341
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go361
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go285
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go374
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go334
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go334
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go374
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go369
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go369
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go331
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go348
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go274
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go274
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go274
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go207
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go207
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go213
-rw-r--r--vendor/golang.org/x/sys/unix/zsysnum_solaris_amd64.go13
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_darwin_386.go462
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go472
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go463
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go471
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go448
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go521
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go524
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go524
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_386.go762
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go780
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_arm.go751
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go759
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_mips.go756
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go761
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go761
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go756
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go769
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go769
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go786
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go666
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go401
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go408
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go406
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go446
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go453
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go439
-rw-r--r--vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go442
-rw-r--r--vendor/golang.org/x/sys/windows/asm_windows_386.s13
-rw-r--r--vendor/golang.org/x/sys/windows/asm_windows_amd64.s13
-rw-r--r--vendor/golang.org/x/sys/windows/dll_windows.go377
-rw-r--r--vendor/golang.org/x/sys/windows/env_unset.go15
-rw-r--r--vendor/golang.org/x/sys/windows/env_windows.go25
-rw-r--r--vendor/golang.org/x/sys/windows/eventlog.go20
-rw-r--r--vendor/golang.org/x/sys/windows/exec_windows.go97
-rw-r--r--vendor/golang.org/x/sys/windows/memory_windows.go26
-rw-r--r--vendor/golang.org/x/sys/windows/mksyscall.go7
-rw-r--r--vendor/golang.org/x/sys/windows/race.go30
-rw-r--r--vendor/golang.org/x/sys/windows/race0.go25
-rw-r--r--vendor/golang.org/x/sys/windows/registry/key.go200
-rw-r--r--vendor/golang.org/x/sys/windows/registry/mksyscall.go7
-rw-r--r--vendor/golang.org/x/sys/windows/registry/syscall.go32
-rw-r--r--vendor/golang.org/x/sys/windows/registry/value.go384
-rw-r--r--vendor/golang.org/x/sys/windows/registry/zsyscall_windows.go120
-rw-r--r--vendor/golang.org/x/sys/windows/security_windows.go435
-rw-r--r--vendor/golang.org/x/sys/windows/service.go164
-rw-r--r--vendor/golang.org/x/sys/windows/str.go22
-rw-r--r--vendor/golang.org/x/sys/windows/svc/debug/log.go56
-rw-r--r--vendor/golang.org/x/sys/windows/svc/debug/service.go45
-rw-r--r--vendor/golang.org/x/sys/windows/svc/event.go48
-rw-r--r--vendor/golang.org/x/sys/windows/svc/eventlog/install.go80
-rw-r--r--vendor/golang.org/x/sys/windows/svc/eventlog/log.go70
-rw-r--r--vendor/golang.org/x/sys/windows/svc/go12.c24
-rw-r--r--vendor/golang.org/x/sys/windows/svc/go12.go11
-rw-r--r--vendor/golang.org/x/sys/windows/svc/go13.go31
-rw-r--r--vendor/golang.org/x/sys/windows/svc/mgr/config.go139
-rw-r--r--vendor/golang.org/x/sys/windows/svc/mgr/mgr.go162
-rw-r--r--vendor/golang.org/x/sys/windows/svc/mgr/service.go72
-rw-r--r--vendor/golang.org/x/sys/windows/svc/security.go62
-rw-r--r--vendor/golang.org/x/sys/windows/svc/service.go363
-rw-r--r--vendor/golang.org/x/sys/windows/svc/sys_386.s68
-rw-r--r--vendor/golang.org/x/sys/windows/svc/sys_amd64.s42
-rw-r--r--vendor/golang.org/x/sys/windows/syscall.go71
-rw-r--r--vendor/golang.org/x/sys/windows/syscall_windows.go1004
-rw-r--r--vendor/golang.org/x/sys/windows/types_windows.go1282
-rw-r--r--vendor/golang.org/x/sys/windows/types_windows_386.go22
-rw-r--r--vendor/golang.org/x/sys/windows/types_windows_amd64.go22
-rw-r--r--vendor/golang.org/x/sys/windows/zsyscall_windows.go2428
-rw-r--r--vendor/golang.org/x/text/LICENSE27
-rw-r--r--vendor/golang.org/x/text/PATENTS22
-rw-r--r--vendor/golang.org/x/text/README23
-rw-r--r--vendor/golang.org/x/text/secure/bidirule/bidirule.go342
-rw-r--r--vendor/golang.org/x/text/transform/transform.go705
-rw-r--r--vendor/golang.org/x/text/unicode/bidi/bidi.go198
-rw-r--r--vendor/golang.org/x/text/unicode/bidi/bracket.go335
-rw-r--r--vendor/golang.org/x/text/unicode/bidi/core.go1058
-rw-r--r--vendor/golang.org/x/text/unicode/bidi/prop.go206
-rw-r--r--vendor/golang.org/x/text/unicode/bidi/tables.go1779
-rw-r--r--vendor/golang.org/x/text/unicode/bidi/trieval.go60
-rw-r--r--vendor/golang.org/x/text/unicode/norm/composition.go514
-rw-r--r--vendor/golang.org/x/text/unicode/norm/forminfo.go256
-rw-r--r--vendor/golang.org/x/text/unicode/norm/input.go105
-rw-r--r--vendor/golang.org/x/text/unicode/norm/iter.go450
-rw-r--r--vendor/golang.org/x/text/unicode/norm/normalize.go608
-rw-r--r--vendor/golang.org/x/text/unicode/norm/readwriter.go125
-rw-r--r--vendor/golang.org/x/text/unicode/norm/tables.go7627
-rw-r--r--vendor/golang.org/x/text/unicode/norm/transform.go88
-rw-r--r--vendor/golang.org/x/text/unicode/norm/trie.go54
-rw-r--r--vendor/golang.org/x/time/LICENSE27
-rw-r--r--vendor/golang.org/x/time/PATENTS22
-rw-r--r--vendor/golang.org/x/time/README1
-rw-r--r--vendor/golang.org/x/time/rate/rate.go368
-rw-r--r--vendor/google.golang.org/api/LICENSE27
-rw-r--r--vendor/google.golang.org/api/README.md92
-rw-r--r--vendor/google.golang.org/api/googleapi/transport/apikey.go38
-rw-r--r--vendor/google.golang.org/api/internal/pool.go59
-rw-r--r--vendor/google.golang.org/api/internal/settings.go23
-rw-r--r--vendor/google.golang.org/api/iterator/iterator.go231
-rw-r--r--vendor/google.golang.org/api/option/option.go142
-rw-r--r--vendor/google.golang.org/api/support/bundler/bundler.go261
-rw-r--r--vendor/google.golang.org/api/transport/dial.go134
-rw-r--r--vendor/google.golang.org/api/transport/dial_appengine.go34
-rw-r--r--vendor/google.golang.org/genproto/LICENSE202
-rw-r--r--vendor/google.golang.org/genproto/README.md28
-rw-r--r--vendor/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go65
-rw-r--r--vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go567
-rw-r--r--vendor/google.golang.org/genproto/googleapis/api/distribution/distribution.pb.go507
-rw-r--r--vendor/google.golang.org/genproto/googleapis/api/label/label.pb.go120
-rw-r--r--vendor/google.golang.org/genproto/googleapis/api/metric/metric.pb.go359
-rw-r--r--vendor/google.golang.org/genproto/googleapis/api/monitoredres/monitored_resource.pb.go181
-rw-r--r--vendor/google.golang.org/genproto/googleapis/logging/type/http_request.pb.go224
-rw-r--r--vendor/google.golang.org/genproto/googleapis/logging/type/log_severity.pb.go111
-rw-r--r--vendor/google.golang.org/genproto/googleapis/logging/v2/log_entry.pb.go501
-rw-r--r--vendor/google.golang.org/genproto/googleapis/logging/v2/logging.pb.go762
-rw-r--r--vendor/google.golang.org/genproto/googleapis/logging/v2/logging_config.pb.go735
-rw-r--r--vendor/google.golang.org/genproto/googleapis/logging/v2/logging_metrics.pb.go565
-rw-r--r--vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go144
-rw-r--r--vendor/google.golang.org/grpc/LICENSE28
-rw-r--r--vendor/google.golang.org/grpc/PATENTS22
-rw-r--r--vendor/google.golang.org/grpc/README.md41
-rw-r--r--vendor/google.golang.org/grpc/backoff.go80
-rw-r--r--vendor/google.golang.org/grpc/balancer.go400
-rw-r--r--vendor/google.golang.org/grpc/call.go306
-rw-r--r--vendor/google.golang.org/grpc/clientconn.go1030
-rw-r--r--vendor/google.golang.org/grpc/codec.go118
-rw-r--r--vendor/google.golang.org/grpc/codes/code_string.go16
-rw-r--r--vendor/google.golang.org/grpc/codes/codes.go159
-rw-r--r--vendor/google.golang.org/grpc/credentials/credentials.go234
-rw-r--r--vendor/google.golang.org/grpc/credentials/credentials_util_go17.go75
-rw-r--r--vendor/google.golang.org/grpc/credentials/credentials_util_go18.go53
-rw-r--r--vendor/google.golang.org/grpc/credentials/credentials_util_pre_go17.go72
-rw-r--r--vendor/google.golang.org/grpc/credentials/oauth/oauth.go180
-rw-r--r--vendor/google.golang.org/grpc/doc.go6
-rw-r--r--vendor/google.golang.org/grpc/go16.go56
-rw-r--r--vendor/google.golang.org/grpc/go17.go55
-rw-r--r--vendor/google.golang.org/grpc/grpclb.go749
-rw-r--r--vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/grpclb.pb.go629
-rw-r--r--vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/grpclb.proto179
-rw-r--r--vendor/google.golang.org/grpc/grpclog/logger.go93
-rw-r--r--vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go176
-rw-r--r--vendor/google.golang.org/grpc/health/grpc_health_v1/health.proto20
-rw-r--r--vendor/google.golang.org/grpc/health/health.go52
-rw-r--r--vendor/google.golang.org/grpc/interceptor.go90
-rw-r--r--vendor/google.golang.org/grpc/internal/internal.go49
-rw-r--r--vendor/google.golang.org/grpc/keepalive/keepalive.go80
-rw-r--r--vendor/google.golang.org/grpc/metadata/metadata.go144
-rw-r--r--vendor/google.golang.org/grpc/naming/naming.go74
-rw-r--r--vendor/google.golang.org/grpc/peer/peer.go65
-rw-r--r--vendor/google.golang.org/grpc/proxy.go145
-rw-r--r--vendor/google.golang.org/grpc/rpc_util.go501
-rw-r--r--vendor/google.golang.org/grpc/server.go1108
-rw-r--r--vendor/google.golang.org/grpc/stats/handlers.go76
-rw-r--r--vendor/google.golang.org/grpc/stats/stats.go223
-rw-r--r--vendor/google.golang.org/grpc/status/status.go145
-rw-r--r--vendor/google.golang.org/grpc/stream.go633
-rw-r--r--vendor/google.golang.org/grpc/tap/tap.go54
-rw-r--r--vendor/google.golang.org/grpc/trace.go119
-rw-r--r--vendor/google.golang.org/grpc/transport/control.go207
-rw-r--r--vendor/google.golang.org/grpc/transport/go16.go46
-rw-r--r--vendor/google.golang.org/grpc/transport/go17.go46
-rw-r--r--vendor/google.golang.org/grpc/transport/handler_server.go406
-rw-r--r--vendor/google.golang.org/grpc/transport/http2_client.go1248
-rw-r--r--vendor/google.golang.org/grpc/transport/http2_server.go1070
-rw-r--r--vendor/google.golang.org/grpc/transport/http_util.go549
-rw-r--r--vendor/google.golang.org/grpc/transport/transport.go666
-rw-r--r--vendor/gopkg.in/yaml.v2/LICENSE13
-rw-r--r--vendor/gopkg.in/yaml.v2/LICENSE.libyaml31
-rw-r--r--vendor/gopkg.in/yaml.v2/README.md131
-rw-r--r--vendor/gopkg.in/yaml.v2/apic.go742
-rw-r--r--vendor/gopkg.in/yaml.v2/decode.go683
-rw-r--r--vendor/gopkg.in/yaml.v2/emitterc.go1685
-rw-r--r--vendor/gopkg.in/yaml.v2/encode.go306
-rw-r--r--vendor/gopkg.in/yaml.v2/parserc.go1096
-rw-r--r--vendor/gopkg.in/yaml.v2/readerc.go394
-rw-r--r--vendor/gopkg.in/yaml.v2/resolve.go208
-rw-r--r--vendor/gopkg.in/yaml.v2/scannerc.go2710
-rw-r--r--vendor/gopkg.in/yaml.v2/sorter.go104
-rw-r--r--vendor/gopkg.in/yaml.v2/writerc.go89
-rw-r--r--vendor/gopkg.in/yaml.v2/yaml.go346
-rw-r--r--vendor/gopkg.in/yaml.v2/yamlh.go716
-rw-r--r--vendor/gopkg.in/yaml.v2/yamlprivateh.go173
2680 files changed, 709985 insertions, 0 deletions
diff --git a/vendor/cloud.google.com/go/LICENSE b/vendor/cloud.google.com/go/LICENSE
new file mode 100644
index 0000000..a4c5efd
--- /dev/null
+++ b/vendor/cloud.google.com/go/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2014 Google Inc.
+
+ 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/cloud.google.com/go/README.md b/vendor/cloud.google.com/go/README.md
new file mode 100644
index 0000000..9b91f52
--- /dev/null
+++ b/vendor/cloud.google.com/go/README.md
@@ -0,0 +1,452 @@
+# Google Cloud for Go
+
+[![Build Status](https://travis-ci.org/GoogleCloudPlatform/google-cloud-go.svg?branch=master)](https://travis-ci.org/GoogleCloudPlatform/google-cloud-go)
+[![GoDoc](https://godoc.org/cloud.google.com/go?status.svg)](https://godoc.org/cloud.google.com/go)
+
+``` go
+import "cloud.google.com/go"
+```
+
+Go packages for Google Cloud Platform services.
+
+To install the packages on your system,
+
+```
+$ go get -u cloud.google.com/go/...
+```
+
+**NOTE:** These packages are under development, and may occasionally make
+backwards-incompatible changes.
+
+**NOTE:** Github repo is a mirror of [https://code.googlesource.com/gocloud](https://code.googlesource.com/gocloud).
+
+## News
+
+_December 5, 2016_
+
+More changes to BigQuery:
+
+* The `ValueList` type was removed. It is no longer necessary. Instead of
+ ```go
+ var v ValueList
+ ... it.Next(&v) ..
+ ```
+ use
+
+ ```go
+ var v []Value
+ ... it.Next(&v) ...
+ ```
+
+* Previously, repeatedly calling `RowIterator.Next` on the same `[]Value` or
+ `ValueList` would append to the slice. Now each call resets the size to zero first.
+
+* Schema inference will infer the SQL type BYTES for a struct field of
+ type []byte. Previously it inferred STRING.
+
+* The types `uint`, `uint64` and `uintptr` are no longer supported in schema
+ inference. BigQuery's integer type is INT64, and those types may hold values
+ that are not correctly represented in a 64-bit signed integer.
+
+* The SQL types DATE, TIME and DATETIME are now supported. They correspond to
+ the `Date`, `Time` and `DateTime` types in the new `cloud.google.com/go/civil`
+ package.
+
+_November 17, 2016_
+
+Change to BigQuery: values from INTEGER columns will now be returned as int64,
+not int. This will avoid errors arising from large values on 32-bit systems.
+
+_November 8, 2016_
+
+New datastore feature: datastore now encodes your nested Go structs as Entity values,
+instead of a flattened list of the embedded struct's fields.
+This means that you may now have twice-nested slices, eg.
+```go
+type State struct {
+ Cities []struct{
+ Populations []int
+ }
+}
+```
+
+See [the announcement](https://groups.google.com/forum/#!topic/google-api-go-announce/79jtrdeuJAg) for
+more details.
+
+_November 8, 2016_
+
+Breaking changes to datastore: contexts no longer hold namespaces; instead you
+must set a key's namespace explicitly. Also, key functions have been changed
+and renamed.
+
+* The WithNamespace function has been removed. To specify a namespace in a Query, use the Query.Namespace method:
+ ```go
+ q := datastore.NewQuery("Kind").Namespace("ns")
+ ```
+
+* All the fields of Key are exported. That means you can construct any Key with a struct literal:
+ ```go
+ k := &Key{Kind: "Kind", ID: 37, Namespace: "ns"}
+ ```
+
+* As a result of the above, the Key methods Kind, ID, d.Name, Parent, SetParent and Namespace have been removed.
+
+* `NewIncompleteKey` has been removed, replaced by `IncompleteKey`. Replace
+ ```go
+ NewIncompleteKey(ctx, kind, parent)
+ ```
+ with
+ ```go
+ IncompleteKey(kind, parent)
+ ```
+ and if you do use namespaces, make sure you set the namespace on the returned key.
+
+* `NewKey` has been removed, replaced by `NameKey` and `IDKey`. Replace
+ ```go
+ NewKey(ctx, kind, name, 0, parent)
+ NewKey(ctx, kind, "", id, parent)
+ ```
+ with
+ ```go
+ NameKey(kind, name, parent)
+ IDKey(kind, id, parent)
+ ```
+ and if you do use namespaces, make sure you set the namespace on the returned key.
+
+* The `Done` variable has been removed. Replace `datastore.Done` with `iterator.Done`, from the package `google.golang.org/api/iterator`.
+
+* The `Client.Close` method will have a return type of error. It will return the result of closing the underlying gRPC connection.
+
+See [the announcement](https://groups.google.com/forum/#!topic/google-api-go-announce/hqXtM_4Ix-0) for
+more details.
+
+_October 27, 2016_
+
+Breaking change to bigquery: `NewGCSReference` is now a function,
+not a method on `Client`.
+
+New bigquery feature: `Table.LoaderFrom` now accepts a `ReaderSource`, enabling
+loading data into a table from a file or any `io.Reader`.
+
+_October 21, 2016_
+
+Breaking change to pubsub: removed `pubsub.Done`.
+
+Use `iterator.Done` instead, where `iterator` is the package
+`google.golang.org/api/iterator`.
+
+
+[Older news](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/old-news.md)
+
+## Supported APIs
+
+Google API | Status | Package
+-------------------------------|--------------|-----------------------------------------------------------
+[Datastore][cloud-datastore] | beta | [`cloud.google.com/go/datastore`][cloud-datastore-ref]
+[Storage][cloud-storage] | beta | [`cloud.google.com/go/storage`][cloud-storage-ref]
+[Bigtable][cloud-bigtable] | beta | [`cloud.google.com/go/bigtable`][cloud-bigtable-ref]
+[BigQuery][cloud-bigquery] | beta | [`cloud.google.com/go/bigquery`][cloud-bigquery-ref]
+[Logging][cloud-logging] | beta | [`cloud.google.com/go/logging`][cloud-logging-ref]
+[Pub/Sub][cloud-pubsub] | experimental | [`cloud.google.com/go/pubsub`][cloud-pubsub-ref]
+[Vision][cloud-vision] | experimental | [`cloud.google.com/go/vision`][cloud-vision-ref]
+[Language][cloud-language] | experimental | [`cloud.google.com/go/language/apiv1beta1`][cloud-language-ref]
+[Speech][cloud-speech] | experimental | [`cloud.google.com/go/speech/apiv1beta`][cloud-speech-ref]
+
+
+> **Experimental status**: the API is still being actively developed. As a
+> result, it might change in backward-incompatible ways and is not recommended
+> for production use.
+>
+> **Beta status**: the API is largely complete, but still has outstanding
+> features and bugs to be addressed. There may be minor backwards-incompatible
+> changes where necessary.
+>
+> **Stable status**: the API is mature and ready for production use. We will
+> continue addressing bugs and feature requests.
+
+Documentation and examples are available at
+https://godoc.org/cloud.google.com/go
+
+Visit or join the
+[google-api-go-announce group](https://groups.google.com/forum/#!forum/google-api-go-announce)
+for updates on these packages.
+
+## Go Versions Supported
+
+We support the two most recent major versions of Go. If Google App Engine uses
+an older version, we support that as well. You can see which versions are
+currently supported by looking at the lines following `go:` in
+[`.travis.yml`](.travis.yml).
+
+## Authorization
+
+By default, each API will use [Google Application Default Credentials][default-creds]
+for authorization credentials used in calling the API endpoints. This will allow your
+application to run in many environments without requiring explicit configuration.
+
+To authorize using a
+[JSON key file](https://cloud.google.com/iam/docs/managing-service-account-keys),
+pass
+[`option.WithServiceAccountFile`](https://godoc.org/google.golang.org/api/option#WithServiceAccountFile)
+to the `NewClient` function of the desired package. For example:
+
+```go
+client, err := storage.NewClient(ctx, option.WithServiceAccountFile("path/to/keyfile.json"))
+```
+
+You can exert more control over authorization by using the
+[`golang.org/x/oauth2`](https://godoc.org/golang.org/x/oauth2) package to
+create an `oauth2.TokenSource`. Then pass
+[`option.WithTokenSource`](https://godoc.org/google.golang.org/api/option#WithTokenSource)
+to the `NewClient` function:
+```go
+tokenSource := ...
+client, err := storage.NewClient(ctx, option.WithTokenSource(tokenSource))
+```
+
+## Cloud Datastore [![GoDoc](https://godoc.org/cloud.google.com/go/datastore?status.svg)](https://godoc.org/cloud.google.com/go/datastore)
+
+- [About Cloud Datastore][cloud-datastore]
+- [Activating the API for your project][cloud-datastore-activation]
+- [API documentation][cloud-datastore-docs]
+- [Go client documentation](https://godoc.org/cloud.google.com/go/datastore)
+- [Complete sample program](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/datastore/tasks)
+
+### Example Usage
+
+First create a `datastore.Client` to use throughout your application:
+
+```go
+client, err := datastore.NewClient(ctx, "my-project-id")
+if err != nil {
+ log.Fatal(err)
+}
+```
+
+Then use that client to interact with the API:
+
+```go
+type Post struct {
+ Title string
+ Body string `datastore:",noindex"`
+ PublishedAt time.Time
+}
+keys := []*datastore.Key{
+ datastore.NewKey(ctx, "Post", "post1", 0, nil),
+ datastore.NewKey(ctx, "Post", "post2", 0, nil),
+}
+posts := []*Post{
+ {Title: "Post 1", Body: "...", PublishedAt: time.Now()},
+ {Title: "Post 2", Body: "...", PublishedAt: time.Now()},
+}
+if _, err := client.PutMulti(ctx, keys, posts); err != nil {
+ log.Fatal(err)
+}
+```
+
+## Cloud Storage [![GoDoc](https://godoc.org/cloud.google.com/go/storage?status.svg)](https://godoc.org/cloud.google.com/go/storage)
+
+- [About Cloud Storage][cloud-storage]
+- [API documentation][cloud-storage-docs]
+- [Go client documentation](https://godoc.org/cloud.google.com/go/storage)
+- [Complete sample programs](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/storage)
+
+### Example Usage
+
+First create a `storage.Client` to use throughout your application:
+
+```go
+client, err := storage.NewClient(ctx)
+if err != nil {
+ log.Fatal(err)
+}
+```
+
+```go
+// Read the object1 from bucket.
+rc, err := client.Bucket("bucket").Object("object1").NewReader(ctx)
+if err != nil {
+ log.Fatal(err)
+}
+defer rc.Close()
+body, err := ioutil.ReadAll(rc)
+if err != nil {
+ log.Fatal(err)
+}
+```
+
+## Cloud Pub/Sub [![GoDoc](https://godoc.org/cloud.google.com/go/pubsub?status.svg)](https://godoc.org/cloud.google.com/go/pubsub)
+
+- [About Cloud Pubsub][cloud-pubsub]
+- [API documentation][cloud-pubsub-docs]
+- [Go client documentation](https://godoc.org/cloud.google.com/go/pubsub)
+- [Complete sample programs](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/pubsub)
+
+### Example Usage
+
+First create a `pubsub.Client` to use throughout your application:
+
+```go
+client, err := pubsub.NewClient(ctx, "project-id")
+if err != nil {
+ log.Fatal(err)
+}
+```
+
+```go
+// Publish "hello world" on topic1.
+topic := client.Topic("topic1")
+msgIDs, err := topic.Publish(ctx, &pubsub.Message{
+ Data: []byte("hello world"),
+})
+if err != nil {
+ log.Fatal(err)
+}
+
+// Create an iterator to pull messages via subscription1.
+it, err := client.Subscription("subscription1").Pull(ctx)
+if err != nil {
+ log.Println(err)
+}
+defer it.Stop()
+
+// Consume N messages from the iterator.
+for i := 0; i < N; i++ {
+ msg, err := it.Next()
+ if err == iterator.Done {
+ break
+ }
+ if err != nil {
+ log.Fatalf("Failed to retrieve message: %v", err)
+ }
+
+ fmt.Printf("Message %d: %s\n", i, msg.Data)
+ msg.Done(true) // Acknowledge that we've consumed the message.
+}
+```
+
+## Cloud BigQuery [![GoDoc](https://godoc.org/cloud.google.com/go/bigquery?status.svg)](https://godoc.org/cloud.google.com/go/bigquery)
+
+- [About Cloud BigQuery][cloud-bigquery]
+- [API documentation][cloud-bigquery-docs]
+- [Go client documentation][cloud-bigquery-ref]
+- [Complete sample programs](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/bigquery)
+
+### Example Usage
+
+First create a `bigquery.Client` to use throughout your application:
+```go
+c, err := bigquery.NewClient(ctx, "my-project-ID")
+if err != nil {
+ // TODO: Handle error.
+}
+```
+Then use that client to interact with the API:
+```go
+// Construct a query.
+q := c.Query(`
+ SELECT year, SUM(number)
+ FROM [bigquery-public-data:usa_names.usa_1910_2013]
+ WHERE name = "William"
+ GROUP BY year
+ ORDER BY year
+`)
+// Execute the query.
+it, err := q.Read(ctx)
+if err != nil {
+ // TODO: Handle error.
+}
+// Iterate through the results.
+for {
+ var values bigquery.ValueList
+ err := it.Next(&values)
+ if err == iterator.Done {
+ break
+ }
+ if err != nil {
+ // TODO: Handle error.
+ }
+ fmt.Println(values)
+}
+```
+
+
+## Stackdriver Logging [![GoDoc](https://godoc.org/cloud.google.com/go/logging?status.svg)](https://godoc.org/cloud.google.com/go/logging)
+
+- [About Stackdriver Logging][cloud-logging]
+- [API documentation][cloud-logging-docs]
+- [Go client documentation][cloud-logging-ref]
+- [Complete sample programs](https://github.com/GoogleCloudPlatform/golang-samples/tree/master/logging)
+
+### Example Usage
+
+First create a `logging.Client` to use throughout your application:
+
+```go
+ctx := context.Background()
+client, err := logging.NewClient(ctx, "my-project")
+if err != nil {
+ // TODO: Handle error.
+}
+```
+Usually, you'll want to add log entries to a buffer to be periodically flushed
+(automatically and asynchronously) to the Stackdriver Logging service.
+```go
+logger := client.Logger("my-log")
+logger.Log(logging.Entry{Payload: "something happened!"})
+```
+Close your client before your program exits, to flush any buffered log entries.
+```go
+err = client.Close()
+if err != nil {
+ // TODO: Handle error.
+}
+```
+
+## Contributing
+
+Contributions are welcome. Please, see the
+[CONTRIBUTING](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/CONTRIBUTING.md)
+document for details. We're using Gerrit for our code reviews. Please don't open pull
+requests against this repo, new pull requests will be automatically closed.
+
+Please note that this project is released with a Contributor Code of Conduct.
+By participating in this project you agree to abide by its terms.
+See [Contributor Code of Conduct](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/CONTRIBUTING.md#contributor-code-of-conduct)
+for more information.
+
+[cloud-datastore]: https://cloud.google.com/datastore/
+[cloud-datastore-ref]: https://godoc.org/cloud.google.com/go/datastore
+[cloud-datastore-docs]: https://cloud.google.com/datastore/docs
+[cloud-datastore-activation]: https://cloud.google.com/datastore/docs/activate
+
+[cloud-pubsub]: https://cloud.google.com/pubsub/
+[cloud-pubsub-ref]: https://godoc.org/cloud.google.com/go/pubsub
+[cloud-pubsub-docs]: https://cloud.google.com/pubsub/docs
+
+[cloud-storage]: https://cloud.google.com/storage/
+[cloud-storage-ref]: https://godoc.org/cloud.google.com/go/storage
+[cloud-storage-docs]: https://cloud.google.com/storage/docs
+[cloud-storage-create-bucket]: https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets
+
+[cloud-bigtable]: https://cloud.google.com/bigtable/
+[cloud-bigtable-ref]: https://godoc.org/cloud.google.com/go/bigtable
+
+[cloud-bigquery]: https://cloud.google.com/bigquery/
+[cloud-bigquery-docs]: https://cloud.google.com/bigquery/docs
+[cloud-bigquery-ref]: https://godoc.org/cloud.google.com/go/bigquery
+
+[cloud-logging]: https://cloud.google.com/logging/
+[cloud-logging-docs]: https://cloud.google.com/logging/docs
+[cloud-logging-ref]: https://godoc.org/cloud.google.com/go/logging
+
+[cloud-vision]: https://cloud.google.com/vision/
+[cloud-vision-ref]: https://godoc.org/cloud.google.com/go/vision
+
+[cloud-language]: https://cloud.google.com/natural-language
+[cloud-language-ref]: https://godoc.org/cloud.google.com/go/language/apiv1beta1
+
+[cloud-speech]: https://cloud.google.com/speech
+[cloud-speech-ref]: https://godoc.org/cloud.google.com/go/speech/apiv1beta1
+
+[default-creds]: https://developers.google.com/identity/protocols/application-default-credentials
diff --git a/vendor/cloud.google.com/go/compute/metadata/metadata.go b/vendor/cloud.google.com/go/compute/metadata/metadata.go
new file mode 100644
index 0000000..f9d2bef
--- /dev/null
+++ b/vendor/cloud.google.com/go/compute/metadata/metadata.go
@@ -0,0 +1,438 @@
+// Copyright 2014 Google Inc. All Rights Reserved.
+//
+// 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 metadata provides access to Google Compute Engine (GCE)
+// metadata and API service accounts.
+//
+// This package is a wrapper around the GCE metadata service,
+// as documented at https://developers.google.com/compute/docs/metadata.
+package metadata // import "cloud.google.com/go/compute/metadata"
+
+import (
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "net"
+ "net/http"
+ "net/url"
+ "os"
+ "runtime"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/net/context/ctxhttp"
+
+ "cloud.google.com/go/internal"
+)
+
+const (
+ // metadataIP is the documented metadata server IP address.
+ metadataIP = "169.254.169.254"
+
+ // metadataHostEnv is the environment variable specifying the
+ // GCE metadata hostname. If empty, the default value of
+ // metadataIP ("169.254.169.254") is used instead.
+ // This is variable name is not defined by any spec, as far as
+ // I know; it was made up for the Go package.
+ metadataHostEnv = "GCE_METADATA_HOST"
+)
+
+type cachedValue struct {
+ k string
+ trim bool
+ mu sync.Mutex
+ v string
+}
+
+var (
+ projID = &cachedValue{k: "project/project-id", trim: true}
+ projNum = &cachedValue{k: "project/numeric-project-id", trim: true}
+ instID = &cachedValue{k: "instance/id", trim: true}
+)
+
+var (
+ metaClient = &http.Client{
+ Transport: &internal.Transport{
+ Base: &http.Transport{
+ Dial: (&net.Dialer{
+ Timeout: 2 * time.Second,
+ KeepAlive: 30 * time.Second,
+ }).Dial,
+ ResponseHeaderTimeout: 2 * time.Second,
+ },
+ },
+ }
+ subscribeClient = &http.Client{
+ Transport: &internal.Transport{
+ Base: &http.Transport{
+ Dial: (&net.Dialer{
+ Timeout: 2 * time.Second,
+ KeepAlive: 30 * time.Second,
+ }).Dial,
+ },
+ },
+ }
+)
+
+// NotDefinedError is returned when requested metadata is not defined.
+//
+// The underlying string is the suffix after "/computeMetadata/v1/".
+//
+// This error is not returned if the value is defined to be the empty
+// string.
+type NotDefinedError string
+
+func (suffix NotDefinedError) Error() string {
+ return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix))
+}
+
+// Get returns a value from the metadata service.
+// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/".
+//
+// If the GCE_METADATA_HOST environment variable is not defined, a default of
+// 169.254.169.254 will be used instead.
+//
+// If the requested metadata is not defined, the returned error will
+// be of type NotDefinedError.
+func Get(suffix string) (string, error) {
+ val, _, err := getETag(metaClient, suffix)
+ return val, err
+}
+
+// getETag returns a value from the metadata service as well as the associated
+// ETag using the provided client. This func is otherwise equivalent to Get.
+func getETag(client *http.Client, suffix string) (value, etag string, err error) {
+ // Using a fixed IP makes it very difficult to spoof the metadata service in
+ // a container, which is an important use-case for local testing of cloud
+ // deployments. To enable spoofing of the metadata service, the environment
+ // variable GCE_METADATA_HOST is first inspected to decide where metadata
+ // requests shall go.
+ host := os.Getenv(metadataHostEnv)
+ if host == "" {
+ // Using 169.254.169.254 instead of "metadata" here because Go
+ // binaries built with the "netgo" tag and without cgo won't
+ // know the search suffix for "metadata" is
+ // ".google.internal", and this IP address is documented as
+ // being stable anyway.
+ host = metadataIP
+ }
+ url := "http://" + host + "/computeMetadata/v1/" + suffix
+ req, _ := http.NewRequest("GET", url, nil)
+ req.Header.Set("Metadata-Flavor", "Google")
+ res, err := client.Do(req)
+ if err != nil {
+ return "", "", err
+ }
+ defer res.Body.Close()
+ if res.StatusCode == http.StatusNotFound {
+ return "", "", NotDefinedError(suffix)
+ }
+ if res.StatusCode != 200 {
+ return "", "", fmt.Errorf("status code %d trying to fetch %s", res.StatusCode, url)
+ }
+ all, err := ioutil.ReadAll(res.Body)
+ if err != nil {
+ return "", "", err
+ }
+ return string(all), res.Header.Get("Etag"), nil
+}
+
+func getTrimmed(suffix string) (s string, err error) {
+ s, err = Get(suffix)
+ s = strings.TrimSpace(s)
+ return
+}
+
+func (c *cachedValue) get() (v string, err error) {
+ defer c.mu.Unlock()
+ c.mu.Lock()
+ if c.v != "" {
+ return c.v, nil
+ }
+ if c.trim {
+ v, err = getTrimmed(c.k)
+ } else {
+ v, err = Get(c.k)
+ }
+ if err == nil {
+ c.v = v
+ }
+ return
+}
+
+var (
+ onGCEOnce sync.Once
+ onGCE bool
+)
+
+// OnGCE reports whether this process is running on Google Compute Engine.
+func OnGCE() bool {
+ onGCEOnce.Do(initOnGCE)
+ return onGCE
+}
+
+func initOnGCE() {
+ onGCE = testOnGCE()
+}
+
+func testOnGCE() bool {
+ // The user explicitly said they're on GCE, so trust them.
+ if os.Getenv(metadataHostEnv) != "" {
+ return true
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ resc := make(chan bool, 2)
+
+ // Try two strategies in parallel.
+ // See https://github.com/GoogleCloudPlatform/google-cloud-go/issues/194
+ go func() {
+ res, err := ctxhttp.Get(ctx, metaClient, "http://"+metadataIP)
+ if err != nil {
+ resc <- false
+ return
+ }
+ defer res.Body.Close()
+ resc <- res.Header.Get("Metadata-Flavor") == "Google"
+ }()
+
+ go func() {
+ addrs, err := net.LookupHost("metadata.google.internal")
+ if err != nil || len(addrs) == 0 {
+ resc <- false
+ return
+ }
+ resc <- strsContains(addrs, metadataIP)
+ }()
+
+ tryHarder := systemInfoSuggestsGCE()
+ if tryHarder {
+ res := <-resc
+ if res {
+ // The first strategy succeeded, so let's use it.
+ return true
+ }
+ // Wait for either the DNS or metadata server probe to
+ // contradict the other one and say we are running on
+ // GCE. Give it a lot of time to do so, since the system
+ // info already suggests we're running on a GCE BIOS.
+ timer := time.NewTimer(5 * time.Second)
+ defer timer.Stop()
+ select {
+ case res = <-resc:
+ return res
+ case <-timer.C:
+ // Too slow. Who knows what this system is.
+ return false
+ }
+ }
+
+ // There's no hint from the system info that we're running on
+ // GCE, so use the first probe's result as truth, whether it's
+ // true or false. The goal here is to optimize for speed for
+ // users who are NOT running on GCE. We can't assume that
+ // either a DNS lookup or an HTTP request to a blackholed IP
+ // address is fast. Worst case this should return when the
+ // metaClient's Transport.ResponseHeaderTimeout or
+ // Transport.Dial.Timeout fires (in two seconds).
+ return <-resc
+}
+
+// systemInfoSuggestsGCE reports whether the local system (without
+// doing network requests) suggests that we're running on GCE. If this
+// returns true, testOnGCE tries a bit harder to reach its metadata
+// server.
+func systemInfoSuggestsGCE() bool {
+ if runtime.GOOS != "linux" {
+ // We don't have any non-Linux clues available, at least yet.
+ return false
+ }
+ slurp, _ := ioutil.ReadFile("/sys/class/dmi/id/product_name")
+ name := strings.TrimSpace(string(slurp))
+ return name == "Google" || name == "Google Compute Engine"
+}
+
+// Subscribe subscribes to a value from the metadata service.
+// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/".
+// The suffix may contain query parameters.
+//
+// Subscribe calls fn with the latest metadata value indicated by the provided
+// suffix. If the metadata value is deleted, fn is called with the empty string
+// and ok false. Subscribe blocks until fn returns a non-nil error or the value
+// is deleted. Subscribe returns the error value returned from the last call to
+// fn, which may be nil when ok == false.
+func Subscribe(suffix string, fn func(v string, ok bool) error) error {
+ const failedSubscribeSleep = time.Second * 5
+
+ // First check to see if the metadata value exists at all.
+ val, lastETag, err := getETag(subscribeClient, suffix)
+ if err != nil {
+ return err
+ }
+
+ if err := fn(val, true); err != nil {
+ return err
+ }
+
+ ok := true
+ if strings.ContainsRune(suffix, '?') {
+ suffix += "&wait_for_change=true&last_etag="
+ } else {
+ suffix += "?wait_for_change=true&last_etag="
+ }
+ for {
+ val, etag, err := getETag(subscribeClient, suffix+url.QueryEscape(lastETag))
+ if err != nil {
+ if _, deleted := err.(NotDefinedError); !deleted {
+ time.Sleep(failedSubscribeSleep)
+ continue // Retry on other errors.
+ }
+ ok = false
+ }
+ lastETag = etag
+
+ if err := fn(val, ok); err != nil || !ok {
+ return err
+ }
+ }
+}
+
+// ProjectID returns the current instance's project ID string.
+func ProjectID() (string, error) { return projID.get() }
+
+// NumericProjectID returns the current instance's numeric project ID.
+func NumericProjectID() (string, error) { return projNum.get() }
+
+// InternalIP returns the instance's primary internal IP address.
+func InternalIP() (string, error) {
+ return getTrimmed("instance/network-interfaces/0/ip")
+}
+
+// ExternalIP returns the instance's primary external (public) IP address.
+func ExternalIP() (string, error) {
+ return getTrimmed("instance/network-interfaces/0/access-configs/0/external-ip")
+}
+
+// Hostname returns the instance's hostname. This will be of the form
+// "<instanceID>.c.<projID>.internal".
+func Hostname() (string, error) {
+ return getTrimmed("instance/hostname")
+}
+
+// InstanceTags returns the list of user-defined instance tags,
+// assigned when initially creating a GCE instance.
+func InstanceTags() ([]string, error) {
+ var s []string
+ j, err := Get("instance/tags")
+ if err != nil {
+ return nil, err
+ }
+ if err := json.NewDecoder(strings.NewReader(j)).Decode(&s); err != nil {
+ return nil, err
+ }
+ return s, nil
+}
+
+// InstanceID returns the current VM's numeric instance ID.
+func InstanceID() (string, error) {
+ return instID.get()
+}
+
+// InstanceName returns the current VM's instance ID string.
+func InstanceName() (string, error) {
+ host, err := Hostname()
+ if err != nil {
+ return "", err
+ }
+ return strings.Split(host, ".")[0], nil
+}
+
+// Zone returns the current VM's zone, such as "us-central1-b".
+func Zone() (string, error) {
+ zone, err := getTrimmed("instance/zone")
+ // zone is of the form "projects/<projNum>/zones/<zoneName>".
+ if err != nil {
+ return "", err
+ }
+ return zone[strings.LastIndex(zone, "/")+1:], nil
+}
+
+// InstanceAttributes returns the list of user-defined attributes,
+// assigned when initially creating a GCE VM instance. The value of an
+// attribute can be obtained with InstanceAttributeValue.
+func InstanceAttributes() ([]string, error) { return lines("instance/attributes/") }
+
+// ProjectAttributes returns the list of user-defined attributes
+// applying to the project as a whole, not just this VM. The value of
+// an attribute can be obtained with ProjectAttributeValue.
+func ProjectAttributes() ([]string, error) { return lines("project/attributes/") }
+
+func lines(suffix string) ([]string, error) {
+ j, err := Get(suffix)
+ if err != nil {
+ return nil, err
+ }
+ s := strings.Split(strings.TrimSpace(j), "\n")
+ for i := range s {
+ s[i] = strings.TrimSpace(s[i])
+ }
+ return s, nil
+}
+
+// InstanceAttributeValue returns the value of the provided VM
+// instance attribute.
+//
+// If the requested attribute is not defined, the returned error will
+// be of type NotDefinedError.
+//
+// InstanceAttributeValue may return ("", nil) if the attribute was
+// defined to be the empty string.
+func InstanceAttributeValue(attr string) (string, error) {
+ return Get("instance/attributes/" + attr)
+}
+
+// ProjectAttributeValue returns the value of the provided
+// project attribute.
+//
+// If the requested attribute is not defined, the returned error will
+// be of type NotDefinedError.
+//
+// ProjectAttributeValue may return ("", nil) if the attribute was
+// defined to be the empty string.
+func ProjectAttributeValue(attr string) (string, error) {
+ return Get("project/attributes/" + attr)
+}
+
+// Scopes returns the service account scopes for the given account.
+// The account may be empty or the string "default" to use the instance's
+// main account.
+func Scopes(serviceAccount string) ([]string, error) {
+ if serviceAccount == "" {
+ serviceAccount = "default"
+ }
+ return lines("instance/service-accounts/" + serviceAccount + "/scopes")
+}
+
+func strsContains(ss []string, s string) bool {
+ for _, v := range ss {
+ if v == s {
+ return true
+ }
+ }
+ return false
+}
diff --git a/vendor/cloud.google.com/go/internal/cloud.go b/vendor/cloud.google.com/go/internal/cloud.go
new file mode 100644
index 0000000..8e0c8f8
--- /dev/null
+++ b/vendor/cloud.google.com/go/internal/cloud.go
@@ -0,0 +1,64 @@
+// Copyright 2014 Google Inc. All Rights Reserved.
+//
+// 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 internal provides support for the cloud packages.
+//
+// Users should not import this package directly.
+package internal
+
+import (
+ "fmt"
+ "net/http"
+)
+
+const userAgent = "gcloud-golang/0.1"
+
+// Transport is an http.RoundTripper that appends Google Cloud client's
+// user-agent to the original request's user-agent header.
+type Transport struct {
+ // TODO(bradfitz): delete internal.Transport. It's too wrappy for what it does.
+ // Do User-Agent some other way.
+
+ // Base is the actual http.RoundTripper
+ // requests will use. It must not be nil.
+ Base http.RoundTripper
+}
+
+// RoundTrip appends a user-agent to the existing user-agent
+// header and delegates the request to the base http.RoundTripper.
+func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
+ req = cloneRequest(req)
+ ua := req.Header.Get("User-Agent")
+ if ua == "" {
+ ua = userAgent
+ } else {
+ ua = fmt.Sprintf("%s %s", ua, userAgent)
+ }
+ req.Header.Set("User-Agent", ua)
+ return t.Base.RoundTrip(req)
+}
+
+// cloneRequest returns a clone of the provided *http.Request.
+// The clone is a shallow copy of the struct and its Header map.
+func cloneRequest(r *http.Request) *http.Request {
+ // shallow copy of the struct
+ r2 := new(http.Request)
+ *r2 = *r
+ // deep copy of the Header
+ r2.Header = make(http.Header)
+ for k, s := range r.Header {
+ r2.Header[k] = s
+ }
+ return r2
+}
diff --git a/vendor/cloud.google.com/go/internal/retry.go b/vendor/cloud.google.com/go/internal/retry.go
new file mode 100644
index 0000000..79995be
--- /dev/null
+++ b/vendor/cloud.google.com/go/internal/retry.go
@@ -0,0 +1,55 @@
+// Copyright 2016 Google Inc. All Rights Reserved.
+//
+// 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 internal
+
+import (
+ "fmt"
+ "time"
+
+ gax "github.com/googleapis/gax-go"
+
+ "golang.org/x/net/context"
+)
+
+// Retry calls the supplied function f repeatedly according to the provided
+// backoff parameters. It returns when one of the following occurs:
+// When f's first return value is true, Retry immediately returns with f's second
+// return value.
+// When the provided context is done, Retry returns with ctx.Err().
+func Retry(ctx context.Context, bo gax.Backoff, f func() (stop bool, err error)) error {
+ return retry(ctx, bo, f, gax.Sleep)
+}
+
+func retry(ctx context.Context, bo gax.Backoff, f func() (stop bool, err error),
+ sleep func(context.Context, time.Duration) error) error {
+ var lastErr error
+ for {
+ stop, err := f()
+ if stop {
+ return err
+ }
+ // Remember the last "real" error from f.
+ if err != nil && err != context.Canceled && err != context.DeadlineExceeded {
+ lastErr = err
+ }
+ p := bo.Pause()
+ if cerr := sleep(ctx, p); cerr != nil {
+ if lastErr != nil {
+ return fmt.Errorf("%v; last function err: %v", cerr, lastErr)
+ }
+ return cerr
+ }
+ }
+}
diff --git a/vendor/cloud.google.com/go/logging/apiv2/README.md b/vendor/cloud.google.com/go/logging/apiv2/README.md
new file mode 100644
index 0000000..d2d9a17
--- /dev/null
+++ b/vendor/cloud.google.com/go/logging/apiv2/README.md
@@ -0,0 +1,11 @@
+Auto-generated logging v2 clients
+=================================
+
+This package includes auto-generated clients for the logging v2 API.
+
+Use the handwritten logging client (in the parent directory,
+cloud.google.com/go/logging) in preference to this.
+
+This code is EXPERIMENTAL and subject to CHANGE AT ANY TIME.
+
+
diff --git a/vendor/cloud.google.com/go/logging/apiv2/config_client.go b/vendor/cloud.google.com/go/logging/apiv2/config_client.go
new file mode 100644
index 0000000..d3091be
--- /dev/null
+++ b/vendor/cloud.google.com/go/logging/apiv2/config_client.go
@@ -0,0 +1,300 @@
+// Copyright 2016, Google Inc. All rights reserved.
+//
+// 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.
+
+// AUTO-GENERATED CODE. DO NOT EDIT.
+
+package logging
+
+import (
+ "fmt"
+ "math"
+ "runtime"
+ "strings"
+ "time"
+
+ gax "github.com/googleapis/gax-go"
+ "golang.org/x/net/context"
+ "google.golang.org/api/iterator"
+ "google.golang.org/api/option"
+ "google.golang.org/api/transport"
+ loggingpb "google.golang.org/genproto/googleapis/logging/v2"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/metadata"
+)
+
+var (
+ configParentPathTemplate = gax.MustCompilePathTemplate("projects/{project}")
+ configSinkPathTemplate = gax.MustCompilePathTemplate("projects/{project}/sinks/{sink}")
+)
+
+// ConfigCallOptions contains the retry settings for each method of ConfigClient.
+type ConfigCallOptions struct {
+ ListSinks []gax.CallOption
+ GetSink []gax.CallOption
+ CreateSink []gax.CallOption
+ UpdateSink []gax.CallOption
+ DeleteSink []gax.CallOption
+}
+
+func defaultConfigClientOptions() []option.ClientOption {
+ return []option.ClientOption{
+ option.WithEndpoint("logging.googleapis.com:443"),
+ option.WithScopes(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ "https://www.googleapis.com/auth/logging.admin",
+ "https://www.googleapis.com/auth/logging.read",
+ "https://www.googleapis.com/auth/logging.write",
+ ),
+ }
+}
+
+func defaultConfigCallOptions() *ConfigCallOptions {
+ retry := map[[2]string][]gax.CallOption{
+ {"default", "idempotent"}: {
+ gax.WithRetry(func() gax.Retryer {
+ return gax.OnCodes([]codes.Code{
+ codes.DeadlineExceeded,
+ codes.Unavailable,
+ }, gax.Backoff{
+ Initial: 100 * time.Millisecond,
+ Max: 1000 * time.Millisecond,
+ Multiplier: 1.2,
+ })
+ }),
+ },
+ }
+ return &ConfigCallOptions{
+ ListSinks: retry[[2]string{"default", "idempotent"}],
+ GetSink: retry[[2]string{"default", "idempotent"}],
+ CreateSink: retry[[2]string{"default", "non_idempotent"}],
+ UpdateSink: retry[[2]string{"default", "non_idempotent"}],
+ DeleteSink: retry[[2]string{"default", "idempotent"}],
+ }
+}
+
+// ConfigClient is a client for interacting with Stackdriver Logging API.
+type ConfigClient struct {
+ // The connection to the service.
+ conn *grpc.ClientConn
+
+ // The gRPC API client.
+ configClient loggingpb.ConfigServiceV2Client
+
+ // The call options for this service.
+ CallOptions *ConfigCallOptions
+
+ // The metadata to be sent with each request.
+ metadata metadata.MD
+}
+
+// NewConfigClient creates a new config service v2 client.
+//
+// Service for configuring sinks used to export log entries outside of
+// Stackdriver Logging.
+func NewConfigClient(ctx context.Context, opts ...option.ClientOption) (*ConfigClient, error) {
+ conn, err := transport.DialGRPC(ctx, append(defaultConfigClientOptions(), opts...)...)
+ if err != nil {
+ return nil, err
+ }
+ c := &ConfigClient{
+ conn: conn,
+ CallOptions: defaultConfigCallOptions(),
+
+ configClient: loggingpb.NewConfigServiceV2Client(conn),
+ }
+ c.SetGoogleClientInfo("gax", gax.Version)
+ return c, nil
+}
+
+// Connection returns the client's connection to the API service.
+func (c *ConfigClient) Connection() *grpc.ClientConn {
+ return c.conn
+}
+
+// Close closes the connection to the API service. The user should invoke this when
+// the client is no longer required.
+func (c *ConfigClient) Close() error {
+ return c.conn.Close()
+}
+
+// SetGoogleClientInfo sets the name and version of the application in
+// the `x-goog-api-client` header passed on each request. Intended for
+// use by Google-written clients.
+func (c *ConfigClient) SetGoogleClientInfo(name, version string) {
+ goVersion := strings.Replace(runtime.Version(), " ", "_", -1)
+ v := fmt.Sprintf("%s/%s %s gax/%s go/%s", name, version, gapicNameVersion, gax.Version, goVersion)
+ c.metadata = metadata.Pairs("x-goog-api-client", v)
+}
+
+// ConfigParentPath returns the path for the parent resource.
+func ConfigParentPath(project string) string {
+ path, err := configParentPathTemplate.Render(map[string]string{
+ "project": project,
+ })
+ if err != nil {
+ panic(err)
+ }
+ return path
+}
+
+// ConfigSinkPath returns the path for the sink resource.
+func ConfigSinkPath(project, sink string) string {
+ path, err := configSinkPathTemplate.Render(map[string]string{
+ "project": project,
+ "sink": sink,
+ })
+ if err != nil {
+ panic(err)
+ }
+ return path
+}
+
+// ListSinks lists sinks.
+func (c *ConfigClient) ListSinks(ctx context.Context, req *loggingpb.ListSinksRequest) *LogSinkIterator {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ it := &LogSinkIterator{}
+ it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogSink, string, error) {
+ var resp *loggingpb.ListSinksResponse
+ req.PageToken = pageToken
+ if pageSize > math.MaxInt32 {
+ req.PageSize = math.MaxInt32
+ } else {
+ req.PageSize = int32(pageSize)
+ }
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.configClient.ListSinks(ctx, req)
+ return err
+ }, c.CallOptions.ListSinks...)
+ if err != nil {
+ return nil, "", err
+ }
+ return resp.Sinks, resp.NextPageToken, nil
+ }
+ fetch := func(pageSize int, pageToken string) (string, error) {
+ items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
+ if err != nil {
+ return "", err
+ }
+ it.items = append(it.items, items...)
+ return nextPageToken, nil
+ }
+ it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
+ return it
+}
+
+// GetSink gets a sink.
+func (c *ConfigClient) GetSink(ctx context.Context, req *loggingpb.GetSinkRequest) (*loggingpb.LogSink, error) {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ var resp *loggingpb.LogSink
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.configClient.GetSink(ctx, req)
+ return err
+ }, c.CallOptions.GetSink...)
+ if err != nil {
+ return nil, err
+ }
+ return resp, nil
+}
+
+// CreateSink creates a sink.
+func (c *ConfigClient) CreateSink(ctx context.Context, req *loggingpb.CreateSinkRequest) (*loggingpb.LogSink, error) {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ var resp *loggingpb.LogSink
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.configClient.CreateSink(ctx, req)
+ return err
+ }, c.CallOptions.CreateSink...)
+ if err != nil {
+ return nil, err
+ }
+ return resp, nil
+}
+
+// UpdateSink updates or creates a sink.
+func (c *ConfigClient) UpdateSink(ctx context.Context, req *loggingpb.UpdateSinkRequest) (*loggingpb.LogSink, error) {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ var resp *loggingpb.LogSink
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.configClient.UpdateSink(ctx, req)
+ return err
+ }, c.CallOptions.UpdateSink...)
+ if err != nil {
+ return nil, err
+ }
+ return resp, nil
+}
+
+// DeleteSink deletes a sink.
+func (c *ConfigClient) DeleteSink(ctx context.Context, req *loggingpb.DeleteSinkRequest) error {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ _, err = c.configClient.DeleteSink(ctx, req)
+ return err
+ }, c.CallOptions.DeleteSink...)
+ return err
+}
+
+// LogSinkIterator manages a stream of *loggingpb.LogSink.
+type LogSinkIterator struct {
+ items []*loggingpb.LogSink
+ pageInfo *iterator.PageInfo
+ nextFunc func() error
+
+ // InternalFetch is for use by the Google Cloud Libraries only.
+ // It is not part of the stable interface of this package.
+ //
+ // InternalFetch returns results from a single call to the underlying RPC.
+ // The number of results is no greater than pageSize.
+ // If there are no more results, nextPageToken is empty and err is nil.
+ InternalFetch func(pageSize int, pageToken string) (results []*loggingpb.LogSink, nextPageToken string, err error)
+}
+
+// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
+func (it *LogSinkIterator) PageInfo() *iterator.PageInfo {
+ return it.pageInfo
+}
+
+// Next returns the next result. Its second return value is iterator.Done if there are no more
+// results. Once Next returns Done, all subsequent calls will return Done.
+func (it *LogSinkIterator) Next() (*loggingpb.LogSink, error) {
+ var item *loggingpb.LogSink
+ if err := it.nextFunc(); err != nil {
+ return item, err
+ }
+ item = it.items[0]
+ it.items = it.items[1:]
+ return item, nil
+}
+
+func (it *LogSinkIterator) bufLen() int {
+ return len(it.items)
+}
+
+func (it *LogSinkIterator) takeBuf() interface{} {
+ b := it.items
+ it.items = nil
+ return b
+}
diff --git a/vendor/cloud.google.com/go/logging/apiv2/doc.go b/vendor/cloud.google.com/go/logging/apiv2/doc.go
new file mode 100644
index 0000000..3a92278
--- /dev/null
+++ b/vendor/cloud.google.com/go/logging/apiv2/doc.go
@@ -0,0 +1,26 @@
+// Copyright 2016, Google Inc. All rights reserved.
+//
+// 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.
+
+// AUTO-GENERATED CODE. DO NOT EDIT.
+
+// Package logging is an experimental, auto-generated package for the
+// logging API.
+//
+// The Stackdriver Logging API lets you write log entries and manage your
+// logs, log sinks and logs-based metrics.
+//
+// Use the client at cloud.google.com/go/logging in preference to this.
+package logging // import "cloud.google.com/go/logging/apiv2"
+
+const gapicNameVersion = "gapic/0.1.0"
diff --git a/vendor/cloud.google.com/go/logging/apiv2/logging_client.go b/vendor/cloud.google.com/go/logging/apiv2/logging_client.go
new file mode 100644
index 0000000..321b1e2
--- /dev/null
+++ b/vendor/cloud.google.com/go/logging/apiv2/logging_client.go
@@ -0,0 +1,359 @@
+// Copyright 2016, Google Inc. All rights reserved.
+//
+// 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.
+
+// AUTO-GENERATED CODE. DO NOT EDIT.
+
+package logging
+
+import (
+ "fmt"
+ "math"
+ "runtime"
+ "strings"
+ "time"
+
+ gax "github.com/googleapis/gax-go"
+ "golang.org/x/net/context"
+ "google.golang.org/api/iterator"
+ "google.golang.org/api/option"
+ "google.golang.org/api/transport"
+ monitoredrespb "google.golang.org/genproto/googleapis/api/monitoredres"
+ loggingpb "google.golang.org/genproto/googleapis/logging/v2"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/metadata"
+)
+
+var (
+ loggingParentPathTemplate = gax.MustCompilePathTemplate("projects/{project}")
+ loggingLogPathTemplate = gax.MustCompilePathTemplate("projects/{project}/logs/{log}")
+)
+
+// CallOptions contains the retry settings for each method of Client.
+type CallOptions struct {
+ DeleteLog []gax.CallOption
+ WriteLogEntries []gax.CallOption
+ ListLogEntries []gax.CallOption
+ ListMonitoredResourceDescriptors []gax.CallOption
+}
+
+func defaultClientOptions() []option.ClientOption {
+ return []option.ClientOption{
+ option.WithEndpoint("logging.googleapis.com:443"),
+ option.WithScopes(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ "https://www.googleapis.com/auth/logging.admin",
+ "https://www.googleapis.com/auth/logging.read",
+ "https://www.googleapis.com/auth/logging.write",
+ ),
+ }
+}
+
+func defaultCallOptions() *CallOptions {
+ retry := map[[2]string][]gax.CallOption{
+ {"default", "idempotent"}: {
+ gax.WithRetry(func() gax.Retryer {
+ return gax.OnCodes([]codes.Code{
+ codes.DeadlineExceeded,
+ codes.Unavailable,
+ }, gax.Backoff{
+ Initial: 100 * time.Millisecond,
+ Max: 1000 * time.Millisecond,
+ Multiplier: 1.2,
+ })
+ }),
+ },
+ {"list", "idempotent"}: {
+ gax.WithRetry(func() gax.Retryer {
+ return gax.OnCodes([]codes.Code{
+ codes.DeadlineExceeded,
+ codes.Unavailable,
+ }, gax.Backoff{
+ Initial: 100 * time.Millisecond,
+ Max: 1000 * time.Millisecond,
+ Multiplier: 1.2,
+ })
+ }),
+ },
+ }
+ return &CallOptions{
+ DeleteLog: retry[[2]string{"default", "idempotent"}],
+ WriteLogEntries: retry[[2]string{"default", "non_idempotent"}],
+ ListLogEntries: retry[[2]string{"list", "idempotent"}],
+ ListMonitoredResourceDescriptors: retry[[2]string{"default", "idempotent"}],
+ }
+}
+
+// Client is a client for interacting with Stackdriver Logging API.
+type Client struct {
+ // The connection to the service.
+ conn *grpc.ClientConn
+
+ // The gRPC API client.
+ client loggingpb.LoggingServiceV2Client
+
+ // The call options for this service.
+ CallOptions *CallOptions
+
+ // The metadata to be sent with each request.
+ metadata metadata.MD
+}
+
+// NewClient creates a new logging service v2 client.
+//
+// Service for ingesting and querying logs.
+func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
+ conn, err := transport.DialGRPC(ctx, append(defaultClientOptions(), opts...)...)
+ if err != nil {
+ return nil, err
+ }
+ c := &Client{
+ conn: conn,
+ CallOptions: defaultCallOptions(),
+
+ client: loggingpb.NewLoggingServiceV2Client(conn),
+ }
+ c.SetGoogleClientInfo("gax", gax.Version)
+ return c, nil
+}
+
+// Connection returns the client's connection to the API service.
+func (c *Client) Connection() *grpc.ClientConn {
+ return c.conn
+}
+
+// Close closes the connection to the API service. The user should invoke this when
+// the client is no longer required.
+func (c *Client) Close() error {
+ return c.conn.Close()
+}
+
+// SetGoogleClientInfo sets the name and version of the application in
+// the `x-goog-api-client` header passed on each request. Intended for
+// use by Google-written clients.
+func (c *Client) SetGoogleClientInfo(name, version string) {
+ goVersion := strings.Replace(runtime.Version(), " ", "_", -1)
+ v := fmt.Sprintf("%s/%s %s gax/%s go/%s", name, version, gapicNameVersion, gax.Version, goVersion)
+ c.metadata = metadata.Pairs("x-goog-api-client", v)
+}
+
+// LoggingParentPath returns the path for the parent resource.
+func LoggingParentPath(project string) string {
+ path, err := loggingParentPathTemplate.Render(map[string]string{
+ "project": project,
+ })
+ if err != nil {
+ panic(err)
+ }
+ return path
+}
+
+// LoggingLogPath returns the path for the log resource.
+func LoggingLogPath(project, log string) string {
+ path, err := loggingLogPathTemplate.Render(map[string]string{
+ "project": project,
+ "log": log,
+ })
+ if err != nil {
+ panic(err)
+ }
+ return path
+}
+
+// DeleteLog deletes all the log entries in a log.
+// The log reappears if it receives new entries.
+func (c *Client) DeleteLog(ctx context.Context, req *loggingpb.DeleteLogRequest) error {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ _, err = c.client.DeleteLog(ctx, req)
+ return err
+ }, c.CallOptions.DeleteLog...)
+ return err
+}
+
+// WriteLogEntries writes log entries to Stackdriver Logging. All log entries are
+// written by this method.
+func (c *Client) WriteLogEntries(ctx context.Context, req *loggingpb.WriteLogEntriesRequest) (*loggingpb.WriteLogEntriesResponse, error) {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ var resp *loggingpb.WriteLogEntriesResponse
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.client.WriteLogEntries(ctx, req)
+ return err
+ }, c.CallOptions.WriteLogEntries...)
+ if err != nil {
+ return nil, err
+ }
+ return resp, nil
+}
+
+// ListLogEntries lists log entries. Use this method to retrieve log entries from Cloud
+// Logging. For ways to export log entries, see
+// [Exporting Logs](/logging/docs/export).
+func (c *Client) ListLogEntries(ctx context.Context, req *loggingpb.ListLogEntriesRequest) *LogEntryIterator {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ it := &LogEntryIterator{}
+ it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogEntry, string, error) {
+ var resp *loggingpb.ListLogEntriesResponse
+ req.PageToken = pageToken
+ if pageSize > math.MaxInt32 {
+ req.PageSize = math.MaxInt32
+ } else {
+ req.PageSize = int32(pageSize)
+ }
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.client.ListLogEntries(ctx, req)
+ return err
+ }, c.CallOptions.ListLogEntries...)
+ if err != nil {
+ return nil, "", err
+ }
+ return resp.Entries, resp.NextPageToken, nil
+ }
+ fetch := func(pageSize int, pageToken string) (string, error) {
+ items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
+ if err != nil {
+ return "", err
+ }
+ it.items = append(it.items, items...)
+ return nextPageToken, nil
+ }
+ it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
+ return it
+}
+
+// ListMonitoredResourceDescriptors lists the monitored resource descriptors used by Stackdriver Logging.
+func (c *Client) ListMonitoredResourceDescriptors(ctx context.Context, req *loggingpb.ListMonitoredResourceDescriptorsRequest) *MonitoredResourceDescriptorIterator {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ it := &MonitoredResourceDescriptorIterator{}
+ it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoredrespb.MonitoredResourceDescriptor, string, error) {
+ var resp *loggingpb.ListMonitoredResourceDescriptorsResponse
+ req.PageToken = pageToken
+ if pageSize > math.MaxInt32 {
+ req.PageSize = math.MaxInt32
+ } else {
+ req.PageSize = int32(pageSize)
+ }
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.client.ListMonitoredResourceDescriptors(ctx, req)
+ return err
+ }, c.CallOptions.ListMonitoredResourceDescriptors...)
+ if err != nil {
+ return nil, "", err
+ }
+ return resp.ResourceDescriptors, resp.NextPageToken, nil
+ }
+ fetch := func(pageSize int, pageToken string) (string, error) {
+ items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
+ if err != nil {
+ return "", err
+ }
+ it.items = append(it.items, items...)
+ return nextPageToken, nil
+ }
+ it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
+ return it
+}
+
+// LogEntryIterator manages a stream of *loggingpb.LogEntry.
+type LogEntryIterator struct {
+ items []*loggingpb.LogEntry
+ pageInfo *iterator.PageInfo
+ nextFunc func() error
+
+ // InternalFetch is for use by the Google Cloud Libraries only.
+ // It is not part of the stable interface of this package.
+ //
+ // InternalFetch returns results from a single call to the underlying RPC.
+ // The number of results is no greater than pageSize.
+ // If there are no more results, nextPageToken is empty and err is nil.
+ InternalFetch func(pageSize int, pageToken string) (results []*loggingpb.LogEntry, nextPageToken string, err error)
+}
+
+// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
+func (it *LogEntryIterator) PageInfo() *iterator.PageInfo {
+ return it.pageInfo
+}
+
+// Next returns the next result. Its second return value is iterator.Done if there are no more
+// results. Once Next returns Done, all subsequent calls will return Done.
+func (it *LogEntryIterator) Next() (*loggingpb.LogEntry, error) {
+ var item *loggingpb.LogEntry
+ if err := it.nextFunc(); err != nil {
+ return item, err
+ }
+ item = it.items[0]
+ it.items = it.items[1:]
+ return item, nil
+}
+
+func (it *LogEntryIterator) bufLen() int {
+ return len(it.items)
+}
+
+func (it *LogEntryIterator) takeBuf() interface{} {
+ b := it.items
+ it.items = nil
+ return b
+}
+
+// MonitoredResourceDescriptorIterator manages a stream of *monitoredrespb.MonitoredResourceDescriptor.
+type MonitoredResourceDescriptorIterator struct {
+ items []*monitoredrespb.MonitoredResourceDescriptor
+ pageInfo *iterator.PageInfo
+ nextFunc func() error
+
+ // InternalFetch is for use by the Google Cloud Libraries only.
+ // It is not part of the stable interface of this package.
+ //
+ // InternalFetch returns results from a single call to the underlying RPC.
+ // The number of results is no greater than pageSize.
+ // If there are no more results, nextPageToken is empty and err is nil.
+ InternalFetch func(pageSize int, pageToken string) (results []*monitoredrespb.MonitoredResourceDescriptor, nextPageToken string, err error)
+}
+
+// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
+func (it *MonitoredResourceDescriptorIterator) PageInfo() *iterator.PageInfo {
+ return it.pageInfo
+}
+
+// Next returns the next result. Its second return value is iterator.Done if there are no more
+// results. Once Next returns Done, all subsequent calls will return Done.
+func (it *MonitoredResourceDescriptorIterator) Next() (*monitoredrespb.MonitoredResourceDescriptor, error) {
+ var item *monitoredrespb.MonitoredResourceDescriptor
+ if err := it.nextFunc(); err != nil {
+ return item, err
+ }
+ item = it.items[0]
+ it.items = it.items[1:]
+ return item, nil
+}
+
+func (it *MonitoredResourceDescriptorIterator) bufLen() int {
+ return len(it.items)
+}
+
+func (it *MonitoredResourceDescriptorIterator) takeBuf() interface{} {
+ b := it.items
+ it.items = nil
+ return b
+}
diff --git a/vendor/cloud.google.com/go/logging/apiv2/metrics_client.go b/vendor/cloud.google.com/go/logging/apiv2/metrics_client.go
new file mode 100644
index 0000000..2345978
--- /dev/null
+++ b/vendor/cloud.google.com/go/logging/apiv2/metrics_client.go
@@ -0,0 +1,299 @@
+// Copyright 2016, Google Inc. All rights reserved.
+//
+// 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.
+
+// AUTO-GENERATED CODE. DO NOT EDIT.
+
+package logging
+
+import (
+ "fmt"
+ "math"
+ "runtime"
+ "strings"
+ "time"
+
+ gax "github.com/googleapis/gax-go"
+ "golang.org/x/net/context"
+ "google.golang.org/api/iterator"
+ "google.golang.org/api/option"
+ "google.golang.org/api/transport"
+ loggingpb "google.golang.org/genproto/googleapis/logging/v2"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/metadata"
+)
+
+var (
+ metricsParentPathTemplate = gax.MustCompilePathTemplate("projects/{project}")
+ metricsMetricPathTemplate = gax.MustCompilePathTemplate("projects/{project}/metrics/{metric}")
+)
+
+// MetricsCallOptions contains the retry settings for each method of MetricsClient.
+type MetricsCallOptions struct {
+ ListLogMetrics []gax.CallOption
+ GetLogMetric []gax.CallOption
+ CreateLogMetric []gax.CallOption
+ UpdateLogMetric []gax.CallOption
+ DeleteLogMetric []gax.CallOption
+}
+
+func defaultMetricsClientOptions() []option.ClientOption {
+ return []option.ClientOption{
+ option.WithEndpoint("logging.googleapis.com:443"),
+ option.WithScopes(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud-platform.read-only",
+ "https://www.googleapis.com/auth/logging.admin",
+ "https://www.googleapis.com/auth/logging.read",
+ "https://www.googleapis.com/auth/logging.write",
+ ),
+ }
+}
+
+func defaultMetricsCallOptions() *MetricsCallOptions {
+ retry := map[[2]string][]gax.CallOption{
+ {"default", "idempotent"}: {
+ gax.WithRetry(func() gax.Retryer {
+ return gax.OnCodes([]codes.Code{
+ codes.DeadlineExceeded,
+ codes.Unavailable,
+ }, gax.Backoff{
+ Initial: 100 * time.Millisecond,
+ Max: 1000 * time.Millisecond,
+ Multiplier: 1.2,
+ })
+ }),
+ },
+ }
+ return &MetricsCallOptions{
+ ListLogMetrics: retry[[2]string{"default", "idempotent"}],
+ GetLogMetric: retry[[2]string{"default", "idempotent"}],
+ CreateLogMetric: retry[[2]string{"default", "non_idempotent"}],
+ UpdateLogMetric: retry[[2]string{"default", "non_idempotent"}],
+ DeleteLogMetric: retry[[2]string{"default", "idempotent"}],
+ }
+}
+
+// MetricsClient is a client for interacting with Stackdriver Logging API.
+type MetricsClient struct {
+ // The connection to the service.
+ conn *grpc.ClientConn
+
+ // The gRPC API client.
+ metricsClient loggingpb.MetricsServiceV2Client
+
+ // The call options for this service.
+ CallOptions *MetricsCallOptions
+
+ // The metadata to be sent with each request.
+ metadata metadata.MD
+}
+
+// NewMetricsClient creates a new metrics service v2 client.
+//
+// Service for configuring logs-based metrics.
+func NewMetricsClient(ctx context.Context, opts ...option.ClientOption) (*MetricsClient, error) {
+ conn, err := transport.DialGRPC(ctx, append(defaultMetricsClientOptions(), opts...)...)
+ if err != nil {
+ return nil, err
+ }
+ c := &MetricsClient{
+ conn: conn,
+ CallOptions: defaultMetricsCallOptions(),
+
+ metricsClient: loggingpb.NewMetricsServiceV2Client(conn),
+ }
+ c.SetGoogleClientInfo("gax", gax.Version)
+ return c, nil
+}
+
+// Connection returns the client's connection to the API service.
+func (c *MetricsClient) Connection() *grpc.ClientConn {
+ return c.conn
+}
+
+// Close closes the connection to the API service. The user should invoke this when
+// the client is no longer required.
+func (c *MetricsClient) Close() error {
+ return c.conn.Close()
+}
+
+// SetGoogleClientInfo sets the name and version of the application in
+// the `x-goog-api-client` header passed on each request. Intended for
+// use by Google-written clients.
+func (c *MetricsClient) SetGoogleClientInfo(name, version string) {
+ goVersion := strings.Replace(runtime.Version(), " ", "_", -1)
+ v := fmt.Sprintf("%s/%s %s gax/%s go/%s", name, version, gapicNameVersion, gax.Version, goVersion)
+ c.metadata = metadata.Pairs("x-goog-api-client", v)
+}
+
+// MetricsParentPath returns the path for the parent resource.
+func MetricsParentPath(project string) string {
+ path, err := metricsParentPathTemplate.Render(map[string]string{
+ "project": project,
+ })
+ if err != nil {
+ panic(err)
+ }
+ return path
+}
+
+// MetricsMetricPath returns the path for the metric resource.
+func MetricsMetricPath(project, metric string) string {
+ path, err := metricsMetricPathTemplate.Render(map[string]string{
+ "project": project,
+ "metric": metric,
+ })
+ if err != nil {
+ panic(err)
+ }
+ return path
+}
+
+// ListLogMetrics lists logs-based metrics.
+func (c *MetricsClient) ListLogMetrics(ctx context.Context, req *loggingpb.ListLogMetricsRequest) *LogMetricIterator {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ it := &LogMetricIterator{}
+ it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogMetric, string, error) {
+ var resp *loggingpb.ListLogMetricsResponse
+ req.PageToken = pageToken
+ if pageSize > math.MaxInt32 {
+ req.PageSize = math.MaxInt32
+ } else {
+ req.PageSize = int32(pageSize)
+ }
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.metricsClient.ListLogMetrics(ctx, req)
+ return err
+ }, c.CallOptions.ListLogMetrics...)
+ if err != nil {
+ return nil, "", err
+ }
+ return resp.Metrics, resp.NextPageToken, nil
+ }
+ fetch := func(pageSize int, pageToken string) (string, error) {
+ items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
+ if err != nil {
+ return "", err
+ }
+ it.items = append(it.items, items...)
+ return nextPageToken, nil
+ }
+ it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
+ return it
+}
+
+// GetLogMetric gets a logs-based metric.
+func (c *MetricsClient) GetLogMetric(ctx context.Context, req *loggingpb.GetLogMetricRequest) (*loggingpb.LogMetric, error) {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ var resp *loggingpb.LogMetric
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.metricsClient.GetLogMetric(ctx, req)
+ return err
+ }, c.CallOptions.GetLogMetric...)
+ if err != nil {
+ return nil, err
+ }
+ return resp, nil
+}
+
+// CreateLogMetric creates a logs-based metric.
+func (c *MetricsClient) CreateLogMetric(ctx context.Context, req *loggingpb.CreateLogMetricRequest) (*loggingpb.LogMetric, error) {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ var resp *loggingpb.LogMetric
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.metricsClient.CreateLogMetric(ctx, req)
+ return err
+ }, c.CallOptions.CreateLogMetric...)
+ if err != nil {
+ return nil, err
+ }
+ return resp, nil
+}
+
+// UpdateLogMetric creates or updates a logs-based metric.
+func (c *MetricsClient) UpdateLogMetric(ctx context.Context, req *loggingpb.UpdateLogMetricRequest) (*loggingpb.LogMetric, error) {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ var resp *loggingpb.LogMetric
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ resp, err = c.metricsClient.UpdateLogMetric(ctx, req)
+ return err
+ }, c.CallOptions.UpdateLogMetric...)
+ if err != nil {
+ return nil, err
+ }
+ return resp, nil
+}
+
+// DeleteLogMetric deletes a logs-based metric.
+func (c *MetricsClient) DeleteLogMetric(ctx context.Context, req *loggingpb.DeleteLogMetricRequest) error {
+ md, _ := metadata.FromContext(ctx)
+ ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
+ err := gax.Invoke(ctx, func(ctx context.Context) error {
+ var err error
+ _, err = c.metricsClient.DeleteLogMetric(ctx, req)
+ return err
+ }, c.CallOptions.DeleteLogMetric...)
+ return err
+}
+
+// LogMetricIterator manages a stream of *loggingpb.LogMetric.
+type LogMetricIterator struct {
+ items []*loggingpb.LogMetric
+ pageInfo *iterator.PageInfo
+ nextFunc func() error
+
+ // InternalFetch is for use by the Google Cloud Libraries only.
+ // It is not part of the stable interface of this package.
+ //
+ // InternalFetch returns results from a single call to the underlying RPC.
+ // The number of results is no greater than pageSize.
+ // If there are no more results, nextPageToken is empty and err is nil.
+ InternalFetch func(pageSize int, pageToken string) (results []*loggingpb.LogMetric, nextPageToken string, err error)
+}
+
+// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
+func (it *LogMetricIterator) PageInfo() *iterator.PageInfo {
+ return it.pageInfo
+}
+
+// Next returns the next result. Its second return value is iterator.Done if there are no more
+// results. Once Next returns Done, all subsequent calls will return Done.
+func (it *LogMetricIterator) Next() (*loggingpb.LogMetric, error) {
+ var item *loggingpb.LogMetric
+ if err := it.nextFunc(); err != nil {
+ return item, err
+ }
+ item = it.items[0]
+ it.items = it.items[1:]
+ return item, nil
+}
+
+func (it *LogMetricIterator) bufLen() int {
+ return len(it.items)
+}
+
+func (it *LogMetricIterator) takeBuf() interface{} {
+ b := it.items
+ it.items = nil
+ return b
+}
diff --git a/vendor/cloud.google.com/go/logging/doc.go b/vendor/cloud.google.com/go/logging/doc.go
new file mode 100644
index 0000000..6da3adf
--- /dev/null
+++ b/vendor/cloud.google.com/go/logging/doc.go
@@ -0,0 +1,89 @@
+// Copyright 2016 Google Inc. All Rights Reserved.
+//
+// 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 logging contains a Stackdriver Logging client suitable for writing logs.
+For reading logs, and working with sinks, metrics and monitored resources,
+see package cloud.google.com/go/logging/logadmin.
+
+This client uses Logging API v2.
+See https://cloud.google.com/logging/docs/api/v2/ for an introduction to the API.
+
+This package is experimental and subject to API changes.
+
+
+Creating a Client
+
+Use a Client to interact with the Stackdriver Logging API.
+
+ // Create a Client
+ ctx := context.Background()
+ client, err := logging.NewClient(ctx, "my-project")
+ if err != nil {
+ // TODO: Handle error.
+ }
+
+
+Basic Usage
+
+For most use-cases, you'll want to add log entries to a buffer to be periodically
+flushed (automatically and asynchronously) to the Stackdriver Logging service.
+
+ // Initialize a logger
+ lg := client.Logger("my-log")
+
+ // Add entry to log buffer
+ lg.Log(logging.Entry{Payload: "something happened!"})
+
+
+Closing your Client
+
+You should call Client.Close before your program exits to flush any buffered log entries to the Stackdriver Logging service.
+
+ // Close the client when finished.
+ err = client.Close()
+ if err != nil {
+ // TODO: Handle error.
+ }
+
+
+Synchronous Logging
+
+For critical errors, you may want to send your log entries immediately.
+LogSync is slow and will block until the log entry has been sent, so it is
+not recommended for basic use.
+
+ lg.LogSync(ctx, logging.Entry{Payload: "ALERT! Something critical happened!"})
+
+
+The Standard Logger Interface
+
+You may want use a standard log.Logger in your program.
+
+ // stdlg implements log.Logger
+ stdlg := lg.StandardLogger(logging.Info)
+ stdlg.Println("some info")
+
+
+Log Levels
+
+An Entry may have one of a number of severity levels associated with it.
+
+ logging.Entry{
+ Payload: "something terrible happened!",
+ Severity: logging.Critical,
+ }
+
+*/
+package logging // import "cloud.google.com/go/logging"
diff --git a/vendor/cloud.google.com/go/logging/internal/common.go b/vendor/cloud.google.com/go/logging/internal/common.go
new file mode 100644
index 0000000..7d8ece0
--- /dev/null
+++ b/vendor/cloud.google.com/go/logging/internal/common.go
@@ -0,0 +1,30 @@
+// Copyright 2016 Google Inc. All Rights Reserved.
+//
+// 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 internal
+
+import (
+ "fmt"
+ "strings"
+)
+
+const (
+ ProdAddr = "logging.googleapis.com:443"
+ Version = "0.2.0"
+)
+
+func LogPath(parent, logID string) string {
+ logID = strings.Replace(logID, "/", "%2F", -1)
+ return fmt.Sprintf("%s/logs/%s", parent, logID)
+}
diff --git a/vendor/cloud.google.com/go/logging/logging.go b/vendor/cloud.google.com/go/logging/logging.go
new file mode 100644
index 0000000..8506800
--- /dev/null
+++ b/vendor/cloud.google.com/go/logging/logging.go
@@ -0,0 +1,674 @@
+// Copyright 2016 Google Inc. All Rights Reserved.
+//
+// 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.
+
+// API/gRPC features intentionally missing from this client:
+// - You cannot have the server pick the time of the entry. This client
+// always sends a time.
+// - There is no way to provide a protocol buffer payload.
+// - No support for the "partial success" feature when writing log entries.
+
+// TODO(jba): test whether forward-slash characters in the log ID must be URL-encoded.
+// These features are missing now, but will likely be added:
+// - There is no way to specify CallOptions.
+
+package logging
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "math"
+ "net/http"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ vkit "cloud.google.com/go/logging/apiv2"
+ "cloud.google.com/go/logging/internal"
+ "github.com/golang/protobuf/proto"
+ "github.com/golang/protobuf/ptypes"
+ structpb "github.com/golang/protobuf/ptypes/struct"
+ tspb "github.com/golang/protobuf/ptypes/timestamp"
+ "golang.org/x/net/context"
+ "google.golang.org/api/option"
+ "google.golang.org/api/support/bundler"
+ mrpb "google.golang.org/genproto/googleapis/api/monitoredres"
+ logtypepb "google.golang.org/genproto/googleapis/logging/type"
+ logpb "google.golang.org/genproto/googleapis/logging/v2"
+)
+
+const (
+ // Scope for reading from the logging service.
+ ReadScope = "https://www.googleapis.com/auth/logging.read"
+
+ // Scope for writing to the logging service.
+ WriteScope = "https://www.googleapis.com/auth/logging.write"
+
+ // Scope for administrative actions on the logging service.
+ AdminScope = "https://www.googleapis.com/auth/logging.admin"
+)
+
+const (
+ // defaultErrorCapacity is the capacity of the channel used to deliver
+ // errors to the OnError function.
+ defaultErrorCapacity = 10
+
+ // DefaultDelayThreshold is the default value for the DelayThreshold LoggerOption.
+ DefaultDelayThreshold = time.Second
+
+ // DefaultEntryCountThreshold is the default value for the EntryCountThreshold LoggerOption.
+ DefaultEntryCountThreshold = 1000
+
+ // DefaultEntryByteThreshold is the default value for the EntryByteThreshold LoggerOption.
+ DefaultEntryByteThreshold = 1 << 20 // 1MiB
+
+ // DefaultBufferedByteLimit is the default value for the BufferedByteLimit LoggerOption.
+ DefaultBufferedByteLimit = 1 << 30 // 1GiB
+)
+
+// For testing:
+var now = time.Now
+
+// ErrOverflow signals that the number of buffered entries for a Logger
+// exceeds its BufferLimit.
+var ErrOverflow = errors.New("logging: log entry overflowed buffer limits")
+
+// Client is a Logging client. A Client is associated with a single Cloud project.
+type Client struct {
+ client *vkit.Client // client for the logging service
+ projectID string
+ errc chan error // should be buffered to minimize dropped errors
+ donec chan struct{} // closed on Client.Close to close Logger bundlers
+ loggers sync.WaitGroup // so we can wait for loggers to close
+ closed bool
+
+ // OnError is called when an error occurs in a call to Log or Flush. The
+ // error may be due to an invalid Entry, an overflow because BufferLimit
+ // was reached (in which case the error will be ErrOverflow) or an error
+ // communicating with the logging service. OnError is called with errors
+ // from all Loggers. It is never called concurrently. OnError is expected
+ // to return quickly; if errors occur while OnError is running, some may
+ // not be reported. The default behavior is to call log.Printf.
+ //
+ // This field should be set only once, before any method of Client is called.
+ OnError func(err error)
+}
+
+// NewClient returns a new logging client associated with the provided project ID.
+//
+// By default NewClient uses WriteScope. To use a different scope, call
+// NewClient using a WithScopes option (see https://godoc.org/google.golang.org/api/option#WithScopes).
+func NewClient(ctx context.Context, projectID string, opts ...option.ClientOption) (*Client, error) {
+ // Check for '/' in project ID to reserve the ability to support various owning resources,
+ // in the form "{Collection}/{Name}", for instance "organizations/my-org".
+ if strings.ContainsRune(projectID, '/') {
+ return nil, errors.New("logging: project ID contains '/'")
+ }
+ opts = append([]option.ClientOption{
+ option.WithEndpoint(internal.ProdAddr),
+ option.WithScopes(WriteScope),
+ }, opts...)
+ c, err := vkit.NewClient(ctx, opts...)
+ if err != nil {
+ return nil, err
+ }
+ c.SetGoogleClientInfo("logging", internal.Version)
+ client := &Client{
+ client: c,
+ projectID: projectID,
+ errc: make(chan error, defaultErrorCapacity), // create a small buffer for errors
+ donec: make(chan struct{}),
+ OnError: func(e error) { log.Printf("logging client: %v", e) },
+ }
+ // Call the user's function synchronously, to make life easier for them.
+ go func() {
+ for err := range client.errc {
+ // This reference to OnError is memory-safe if the user sets OnError before
+ // calling any client methods. The reference happens before the first read from
+ // client.errc, which happens before the first write to client.errc, which
+ // happens before any call, which happens before the user sets OnError.
+ if fn := client.OnError; fn != nil {
+ fn(err)
+ } else {
+ log.Printf("logging (project ID %q): %v", projectID, err)
+ }
+ }
+ }()
+ return client, nil
+}
+
+// parent returns the string used in many RPCs to denote the parent resource of the log.
+func (c *Client) parent() string {
+ return "projects/" + c.projectID
+}
+
+var unixZeroTimestamp *tspb.Timestamp
+
+func init() {
+ var err error
+ unixZeroTimestamp, err = ptypes.TimestampProto(time.Unix(0, 0))
+ if err != nil {
+ panic(err)
+ }
+}
+
+// Ping reports whether the client's connection to the logging service and the
+// authentication configuration are valid. To accomplish this, Ping writes a
+// log entry "ping" to a log named "ping".
+func (c *Client) Ping(ctx context.Context) error {
+ ent := &logpb.LogEntry{
+ Payload: &logpb.LogEntry_TextPayload{"ping"},
+ Timestamp: unixZeroTimestamp, // Identical timestamps and insert IDs are both
+ InsertId: "ping", // necessary for the service to dedup these entries.
+ }
+ _, err := c.client.WriteLogEntries(ctx, &logpb.WriteLogEntriesRequest{
+ LogName: internal.LogPath(c.parent(), "ping"),
+ Resource: &mrpb.MonitoredResource{Type: "global"},
+ Entries: []*logpb.LogEntry{ent},
+ })
+ return err
+}
+
+// A Logger is used to write log messages to a single log. It can be configured
+// with a log ID, common monitored resource, and a set of common labels.
+type Logger struct {
+ client *Client
+ logName string // "projects/{projectID}/logs/{logID}"
+ stdLoggers map[Severity]*log.Logger
+ bundler *bundler.Bundler
+
+ // Options
+ commonResource *mrpb.MonitoredResource
+ commonLabels map[string]string
+}
+
+// A LoggerOption is a configuration option for a Logger.
+type LoggerOption interface {
+ set(*Logger)
+}
+
+// CommonResource sets the monitored resource associated with all log entries
+// written from a Logger. If not provided, a resource of type "global" is used.
+// This value can be overridden by setting an Entry's Resource field.
+func CommonResource(r *mrpb.MonitoredResource) LoggerOption { return commonResource{r} }
+
+type commonResource struct{ *mrpb.MonitoredResource }
+
+func (r commonResource) set(l *Logger) { l.commonResource = r.MonitoredResource }
+
+// CommonLabels are labels that apply to all log entries written from a Logger,
+// so that you don't have to repeat them in each log entry's Labels field. If
+// any of the log entries contains a (key, value) with the same key that is in
+// CommonLabels, then the entry's (key, value) overrides the one in
+// CommonLabels.
+func CommonLabels(m map[string]string) LoggerOption { return commonLabels(m) }
+
+type commonLabels map[string]string
+
+func (c commonLabels) set(l *Logger) { l.commonLabels = c }
+
+// DelayThreshold is the maximum amount of time that an entry should remain
+// buffered in memory before a call to the logging service is triggered. Larger
+// values of DelayThreshold will generally result in fewer calls to the logging
+// service, while increasing the risk that log entries will be lost if the
+// process crashes.
+// The default is DefaultDelayThreshold.
+func DelayThreshold(d time.Duration) LoggerOption { return delayThreshold(d) }
+
+type delayThreshold time.Duration
+
+func (d delayThreshold) set(l *Logger) { l.bundler.DelayThreshold = time.Duration(d) }
+
+// EntryCountThreshold is the maximum number of entries that will be buffered
+// in memory before a call to the logging service is triggered. Larger values
+// will generally result in fewer calls to the logging service, while
+// increasing both memory consumption and the risk that log entries will be
+// lost if the process crashes.
+// The default is DefaultEntryCountThreshold.
+func EntryCountThreshold(n int) LoggerOption { return entryCountThreshold(n) }
+
+type entryCountThreshold int
+
+func (e entryCountThreshold) set(l *Logger) { l.bundler.BundleCountThreshold = int(e) }
+
+// EntryByteThreshold is the maximum number of bytes of entries that will be
+// buffered in memory before a call to the logging service is triggered. See
+// EntryCountThreshold for a discussion of the tradeoffs involved in setting
+// this option.
+// The default is DefaultEntryByteThreshold.
+func EntryByteThreshold(n int) LoggerOption { return entryByteThreshold(n) }
+
+type entryByteThreshold int
+
+func (e entryByteThreshold) set(l *Logger) { l.bundler.BundleByteThreshold = int(e) }
+
+// EntryByteLimit is the maximum number of bytes of entries that will be sent
+// in a single call to the logging service. This option limits the size of a
+// single RPC payload, to account for network or service issues with large
+// RPCs. If EntryByteLimit is smaller than EntryByteThreshold, the latter has
+// no effect.
+// The default is zero, meaning there is no limit.
+func EntryByteLimit(n int) LoggerOption { return entryByteLimit(n) }
+
+type entryByteLimit int
+
+func (e entryByteLimit) set(l *Logger) { l.bundler.BundleByteLimit = int(e) }
+
+// BufferedByteLimit is the maximum number of bytes that the Logger will keep
+// in memory before returning ErrOverflow. This option limits the total memory
+// consumption of the Logger (but note that each Logger has its own, separate
+// limit). It is possible to reach BufferedByteLimit even if it is larger than
+// EntryByteThreshold or EntryByteLimit, because calls triggered by the latter
+// two options may be enqueued (and hence occupying memory) while new log
+// entries are being added.
+// The default is DefaultBufferedByteLimit.
+func BufferedByteLimit(n int) LoggerOption { return bufferedByteLimit(n) }
+
+type bufferedByteLimit int
+
+func (b bufferedByteLimit) set(l *Logger) { l.bundler.BufferedByteLimit = int(b) }
+
+// Logger returns a Logger that will write entries with the given log ID, such as
+// "syslog". A log ID must be less than 512 characters long and can only
+// include the following characters: upper and lower case alphanumeric
+// characters: [A-Za-z0-9]; and punctuation characters: forward-slash,
+// underscore, hyphen, and period.
+func (c *Client) Logger(logID string, opts ...LoggerOption) *Logger {
+ l := &Logger{
+ client: c,
+ logName: internal.LogPath(c.parent(), logID),
+ commonResource: &mrpb.MonitoredResource{Type: "global"},
+ }
+ // TODO(jba): determine the right context for the bundle handler.
+ ctx := context.TODO()
+ l.bundler = bundler.NewBundler(&logpb.LogEntry{}, func(entries interface{}) {
+ l.writeLogEntries(ctx, entries.([]*logpb.LogEntry))
+ })
+ l.bundler.DelayThreshold = DefaultDelayThreshold
+ l.bundler.BundleCountThreshold = DefaultEntryCountThreshold
+ l.bundler.BundleByteThreshold = DefaultEntryByteThreshold
+ l.bundler.BufferedByteLimit = DefaultBufferedByteLimit
+ for _, opt := range opts {
+ opt.set(l)
+ }
+
+ l.stdLoggers = map[Severity]*log.Logger{}
+ for s := range severityName {
+ l.stdLoggers[s] = log.New(severityWriter{l, s}, "", 0)
+ }
+ c.loggers.Add(1)
+ go func() {
+ defer c.loggers.Done()
+ <-c.donec
+ l.bundler.Close()
+ }()
+ return l
+}
+
+type severityWriter struct {
+ l *Logger
+ s Severity
+}
+
+func (w severityWriter) Write(p []byte) (n int, err error) {
+ w.l.Log(Entry{
+ Severity: w.s,
+ Payload: string(p),
+ })
+ return len(p), nil
+}
+
+// Close closes the client.
+func (c *Client) Close() error {
+ if c.closed {
+ return nil
+ }
+ close(c.donec) // close Logger bundlers
+ c.loggers.Wait() // wait for all bundlers to flush and close
+ // Now there can be no more errors.
+ close(c.errc) // terminate error goroutine
+ // Return only the first error. Since all clients share an underlying connection,
+ // Closes after the first always report a "connection is closing" error.
+ err := c.client.Close()
+ c.closed = true
+ return err
+}
+
+// Severity is the severity of the event described in a log entry. These
+// guideline severity levels are ordered, with numerically smaller levels
+// treated as less severe than numerically larger levels.
+type Severity int
+
+const (
+ // Default means the log entry has no assigned severity level.
+ Default = Severity(logtypepb.LogSeverity_DEFAULT)
+ // Debug means debug or trace information.
+ Debug = Severity(logtypepb.LogSeverity_DEBUG)
+ // Info means routine information, such as ongoing status or performance.
+ Info = Severity(logtypepb.LogSeverity_INFO)
+ // Notice means normal but significant events, such as start up, shut down, or configuration.
+ Notice = Severity(logtypepb.LogSeverity_NOTICE)
+ // Warning means events that might cause problems.
+ Warning = Severity(logtypepb.LogSeverity_WARNING)
+ // Error means events that are likely to cause problems.
+ Error = Severity(logtypepb.LogSeverity_ERROR)
+ // Critical means events that cause more severe problems or brief outages.
+ Critical = Severity(logtypepb.LogSeverity_CRITICAL)
+ // Alert means a person must take an action immediately.
+ Alert = Severity(logtypepb.LogSeverity_ALERT)
+ // Emergency means one or more systems are unusable.
+ Emergency = Severity(logtypepb.LogSeverity_EMERGENCY)
+)
+
+var severityName = map[Severity]string{
+ Default: "Default",
+ Debug: "Debug",
+ Info: "Info",
+ Notice: "Notice",
+ Warning: "Warning",
+ Error: "Error",
+ Critical: "Critical",
+ Alert: "Alert",
+ Emergency: "Emergency",
+}
+
+// String converts a severity level to a string.
+func (v Severity) String() string {
+ // same as proto.EnumName
+ s, ok := severityName[v]
+ if ok {
+ return s
+ }
+ return strconv.Itoa(int(v))
+}
+
+// ParseSeverity returns the Severity whose name equals s, ignoring case. It
+// returns Default if no Severity matches.
+func ParseSeverity(s string) Severity {
+ sl := strings.ToLower(s)
+ for sev, name := range severityName {
+ if strings.ToLower(name) == sl {
+ return sev
+ }
+ }
+ return Default
+}
+
+// Entry is a log entry.
+// See https://cloud.google.com/logging/docs/view/logs_index for more about entries.
+type Entry struct {
+ // Timestamp is the time of the entry. If zero, the current time is used.
+ Timestamp time.Time
+
+ // Severity is the entry's severity level.
+ // The zero value is Default.
+ Severity Severity
+
+ // Payload must be either a string or something that
+ // marshals via the encoding/json package to a JSON object
+ // (and not any other type of JSON value).
+ Payload interface{}
+
+ // Labels optionally specifies key/value labels for the log entry.
+ // The Logger.Log method takes ownership of this map. See Logger.CommonLabels
+ // for more about labels.
+ Labels map[string]string
+
+ // InsertID is a unique ID for the log entry. If you provide this field,
+ // the logging service considers other log entries in the same log with the
+ // same ID as duplicates which can be removed. If omitted, the logging
+ // service will generate a unique ID for this log entry. Note that because
+ // this client retries RPCs automatically, it is possible (though unlikely)
+ // that an Entry without an InsertID will be written more than once.
+ InsertID string
+
+ // HTTPRequest optionally specifies metadata about the HTTP request
+ // associated with this log entry, if applicable. It is optional.
+ HTTPRequest *HTTPRequest
+
+ // Operation optionally provides information about an operation associated
+ // with the log entry, if applicable.
+ Operation *logpb.LogEntryOperation
+
+ // LogName is the full log name, in the form
+ // "projects/{ProjectID}/logs/{LogID}". It is set by the client when
+ // reading entries. It is an error to set it when writing entries.
+ LogName string
+
+ // Resource is the monitored resource associated with the entry. It is set
+ // by the client when reading entries. It is an error to set it when
+ // writing entries.
+ Resource *mrpb.MonitoredResource
+}
+
+// HTTPRequest contains an http.Request as well as additional
+// information about the request and its response.
+type HTTPRequest struct {
+ // Request is the http.Request passed to the handler.
+ Request *http.Request
+
+ // RequestSize is the size of the HTTP request message in bytes, including
+ // the request headers and the request body.
+ RequestSize int64
+
+ // Status is the response code indicating the status of the response.
+ // Examples: 200, 404.
+ Status int
+
+ // ResponseSize is the size of the HTTP response message sent back to the client, in bytes,
+ // including the response headers and the response body.
+ ResponseSize int64
+
+ // Latency is the request processing latency on the server, from the time the request was
+ // received until the response was sent.
+ Latency time.Duration
+
+ // RemoteIP is the IP address (IPv4 or IPv6) of the client that issued the
+ // HTTP request. Examples: "192.168.1.1", "FE80::0202:B3FF:FE1E:8329".
+ RemoteIP string
+
+ // CacheHit reports whether an entity was served from cache (with or without
+ // validation).
+ CacheHit bool
+
+ // CacheValidatedWithOriginServer reports whether the response was
+ // validated with the origin server before being served from cache. This
+ // field is only meaningful if CacheHit is true.
+ CacheValidatedWithOriginServer bool
+}
+
+func fromHTTPRequest(r *HTTPRequest) *logtypepb.HttpRequest {
+ if r == nil {
+ return nil
+ }
+ if r.Request == nil {
+ panic("HTTPRequest must have a non-nil Request")
+ }
+ u := *r.Request.URL
+ u.Fragment = ""
+ return &logtypepb.HttpRequest{
+ RequestMethod: r.Request.Method,
+ RequestUrl: u.String(),
+ RequestSize: r.RequestSize,
+ Status: int32(r.Status),
+ ResponseSize: r.ResponseSize,
+ Latency: ptypes.DurationProto(r.Latency),
+ UserAgent: r.Request.UserAgent(),
+ RemoteIp: r.RemoteIP, // TODO(jba): attempt to parse http.Request.RemoteAddr?
+ Referer: r.Request.Referer(),
+ CacheHit: r.CacheHit,
+ CacheValidatedWithOriginServer: r.CacheValidatedWithOriginServer,
+ }
+}
+
+// toProtoStruct converts v, which must marshal into a JSON object,
+// into a Google Struct proto.
+func toProtoStruct(v interface{}) (*structpb.Struct, error) {
+ // Fast path: if v is already a *structpb.Struct, nothing to do.
+ if s, ok := v.(*structpb.Struct); ok {
+ return s, nil
+ }
+ // v is a Go struct that supports JSON marshalling. We want a Struct
+ // protobuf. Some day we may have a more direct way to get there, but right
+ // now the only way is to marshal the Go struct to JSON, unmarshal into a
+ // map, and then build the Struct proto from the map.
+ jb, err := json.Marshal(v)
+ if err != nil {
+ return nil, fmt.Errorf("logging: json.Marshal: %v", err)
+ }
+ var m map[string]interface{}
+ err = json.Unmarshal(jb, &m)
+ if err != nil {
+ return nil, fmt.Errorf("logging: json.Unmarshal: %v", err)
+ }
+ return jsonMapToProtoStruct(m), nil
+}
+
+func jsonMapToProtoStruct(m map[string]interface{}) *structpb.Struct {
+ fields := map[string]*structpb.Value{}
+ for k, v := range m {
+ fields[k] = jsonValueToStructValue(v)
+ }
+ return &structpb.Struct{Fields: fields}
+}
+
+func jsonValueToStructValue(v interface{}) *structpb.Value {
+ switch x := v.(type) {
+ case bool:
+ return &structpb.Value{Kind: &structpb.Value_BoolValue{x}}
+ case float64:
+ return &structpb.Value{Kind: &structpb.Value_NumberValue{x}}
+ case string:
+ return &structpb.Value{Kind: &structpb.Value_StringValue{x}}
+ case nil:
+ return &structpb.Value{Kind: &structpb.Value_NullValue{}}
+ case map[string]interface{}:
+ return &structpb.Value{Kind: &structpb.Value_StructValue{jsonMapToProtoStruct(x)}}
+ case []interface{}:
+ var vals []*structpb.Value
+ for _, e := range x {
+ vals = append(vals, jsonValueToStructValue(e))
+ }
+ return &structpb.Value{Kind: &structpb.Value_ListValue{&structpb.ListValue{vals}}}
+ default:
+ panic(fmt.Sprintf("bad type %T for JSON value", v))
+ }
+}
+
+// LogSync logs the Entry synchronously without any buffering. Because LogSync is slow
+// and will block, it is intended primarily for debugging or critical errors.
+// Prefer Log for most uses.
+// TODO(jba): come up with a better name (LogNow?) or eliminate.
+func (l *Logger) LogSync(ctx context.Context, e Entry) error {
+ ent, err := toLogEntry(e)
+ if err != nil {
+ return err
+ }
+ _, err = l.client.client.WriteLogEntries(ctx, &logpb.WriteLogEntriesRequest{
+ LogName: l.logName,
+ Resource: l.commonResource,
+ Labels: l.commonLabels,
+ Entries: []*logpb.LogEntry{ent},
+ })
+ return err
+}
+
+// Log buffers the Entry for output to the logging service. It never blocks.
+func (l *Logger) Log(e Entry) {
+ ent, err := toLogEntry(e)
+ if err != nil {
+ l.error(err)
+ return
+ }
+ if err := l.bundler.Add(ent, proto.Size(ent)); err != nil {
+ l.error(err)
+ }
+}
+
+// Flush blocks until all currently buffered log entries are sent.
+func (l *Logger) Flush() {
+ l.bundler.Flush()
+}
+
+func (l *Logger) writeLogEntries(ctx context.Context, entries []*logpb.LogEntry) {
+ req := &logpb.WriteLogEntriesRequest{
+ LogName: l.logName,
+ Resource: l.commonResource,
+ Labels: l.commonLabels,
+ Entries: entries,
+ }
+ _, err := l.client.client.WriteLogEntries(ctx, req)
+ if err != nil {
+ l.error(err)
+ }
+}
+
+// error puts the error on the client's error channel
+// without blocking.
+func (l *Logger) error(err error) {
+ select {
+ case l.client.errc <- err:
+ default:
+ }
+}
+
+// StandardLogger returns a *log.Logger for the provided severity.
+//
+// This method is cheap. A single log.Logger is pre-allocated for each
+// severity level in each Logger. Callers may mutate the returned log.Logger
+// (for example by calling SetFlags or SetPrefix).
+func (l *Logger) StandardLogger(s Severity) *log.Logger { return l.stdLoggers[s] }
+
+func trunc32(i int) int32 {
+ if i > math.MaxInt32 {
+ i = math.MaxInt32
+ }
+ return int32(i)
+}
+
+func toLogEntry(e Entry) (*logpb.LogEntry, error) {
+ if e.LogName != "" {
+ return nil, errors.New("logging: Entry.LogName should be not be set when writing")
+ }
+ t := e.Timestamp
+ if t.IsZero() {
+ t = now()
+ }
+ ts, err := ptypes.TimestampProto(t)
+ if err != nil {
+ return nil, err
+ }
+ ent := &logpb.LogEntry{
+ Timestamp: ts,
+ Severity: logtypepb.LogSeverity(e.Severity),
+ InsertId: e.InsertID,
+ HttpRequest: fromHTTPRequest(e.HTTPRequest),
+ Operation: e.Operation,
+ Labels: e.Labels,
+ }
+
+ switch p := e.Payload.(type) {
+ case string:
+ ent.Payload = &logpb.LogEntry_TextPayload{p}
+ default:
+ s, err := toProtoStruct(p)
+ if err != nil {
+ return nil, err
+ }
+ ent.Payload = &logpb.LogEntry_JsonPayload{s}
+ }
+ return ent, nil
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/LICENSE b/vendor/github.com/Azure/go-ansiterm/LICENSE
new file mode 100644
index 0000000..e3d9a64
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 Microsoft Corporation
+
+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/Azure/go-ansiterm/README.md b/vendor/github.com/Azure/go-ansiterm/README.md
new file mode 100644
index 0000000..e25e382
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/README.md
@@ -0,0 +1,9 @@
+# go-ansiterm
+
+This is a cross platform Ansi Terminal Emulation library. It reads a stream of Ansi characters and produces the appropriate function calls. The results of the function calls are platform dependent.
+
+For example the parser might receive "ESC, [, A" as a stream of three characters. This is the code for Cursor Up (http://www.vt100.net/docs/vt510-rm/CUU). The parser then calls the cursor up function (CUU()) on an event handler. The event handler determines what platform specific work must be done to cause the cursor to move up one position.
+
+The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go).
+
+See parser_test.go for examples exercising the state machine and generating appropriate function calls.
diff --git a/vendor/github.com/Azure/go-ansiterm/constants.go b/vendor/github.com/Azure/go-ansiterm/constants.go
new file mode 100644
index 0000000..96504a3
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/constants.go
@@ -0,0 +1,188 @@
+package ansiterm
+
+const LogEnv = "DEBUG_TERMINAL"
+
+// ANSI constants
+// References:
+// -- http://www.ecma-international.org/publications/standards/Ecma-048.htm
+// -- http://man7.org/linux/man-pages/man4/console_codes.4.html
+// -- http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html
+// -- http://en.wikipedia.org/wiki/ANSI_escape_code
+// -- http://vt100.net/emu/dec_ansi_parser
+// -- http://vt100.net/emu/vt500_parser.svg
+// -- http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
+// -- http://www.inwap.com/pdp10/ansicode.txt
+const (
+ // ECMA-48 Set Graphics Rendition
+ // Note:
+ // -- Constants leading with an underscore (e.g., _ANSI_xxx) are unsupported or reserved
+ // -- Fonts could possibly be supported via SetCurrentConsoleFontEx
+ // -- Windows does not expose the per-window cursor (i.e., caret) blink times
+ ANSI_SGR_RESET = 0
+ ANSI_SGR_BOLD = 1
+ ANSI_SGR_DIM = 2
+ _ANSI_SGR_ITALIC = 3
+ ANSI_SGR_UNDERLINE = 4
+ _ANSI_SGR_BLINKSLOW = 5
+ _ANSI_SGR_BLINKFAST = 6
+ ANSI_SGR_REVERSE = 7
+ _ANSI_SGR_INVISIBLE = 8
+ _ANSI_SGR_LINETHROUGH = 9
+ _ANSI_SGR_FONT_00 = 10
+ _ANSI_SGR_FONT_01 = 11
+ _ANSI_SGR_FONT_02 = 12
+ _ANSI_SGR_FONT_03 = 13
+ _ANSI_SGR_FONT_04 = 14
+ _ANSI_SGR_FONT_05 = 15
+ _ANSI_SGR_FONT_06 = 16
+ _ANSI_SGR_FONT_07 = 17
+ _ANSI_SGR_FONT_08 = 18
+ _ANSI_SGR_FONT_09 = 19
+ _ANSI_SGR_FONT_10 = 20
+ _ANSI_SGR_DOUBLEUNDERLINE = 21
+ ANSI_SGR_BOLD_DIM_OFF = 22
+ _ANSI_SGR_ITALIC_OFF = 23
+ ANSI_SGR_UNDERLINE_OFF = 24
+ _ANSI_SGR_BLINK_OFF = 25
+ _ANSI_SGR_RESERVED_00 = 26
+ ANSI_SGR_REVERSE_OFF = 27
+ _ANSI_SGR_INVISIBLE_OFF = 28
+ _ANSI_SGR_LINETHROUGH_OFF = 29
+ ANSI_SGR_FOREGROUND_BLACK = 30
+ ANSI_SGR_FOREGROUND_RED = 31
+ ANSI_SGR_FOREGROUND_GREEN = 32
+ ANSI_SGR_FOREGROUND_YELLOW = 33
+ ANSI_SGR_FOREGROUND_BLUE = 34
+ ANSI_SGR_FOREGROUND_MAGENTA = 35
+ ANSI_SGR_FOREGROUND_CYAN = 36
+ ANSI_SGR_FOREGROUND_WHITE = 37
+ _ANSI_SGR_RESERVED_01 = 38
+ ANSI_SGR_FOREGROUND_DEFAULT = 39
+ ANSI_SGR_BACKGROUND_BLACK = 40
+ ANSI_SGR_BACKGROUND_RED = 41
+ ANSI_SGR_BACKGROUND_GREEN = 42
+ ANSI_SGR_BACKGROUND_YELLOW = 43
+ ANSI_SGR_BACKGROUND_BLUE = 44
+ ANSI_SGR_BACKGROUND_MAGENTA = 45
+ ANSI_SGR_BACKGROUND_CYAN = 46
+ ANSI_SGR_BACKGROUND_WHITE = 47
+ _ANSI_SGR_RESERVED_02 = 48
+ ANSI_SGR_BACKGROUND_DEFAULT = 49
+ // 50 - 65: Unsupported
+
+ ANSI_MAX_CMD_LENGTH = 4096
+
+ MAX_INPUT_EVENTS = 128
+ DEFAULT_WIDTH = 80
+ DEFAULT_HEIGHT = 24
+
+ ANSI_BEL = 0x07
+ ANSI_BACKSPACE = 0x08
+ ANSI_TAB = 0x09
+ ANSI_LINE_FEED = 0x0A
+ ANSI_VERTICAL_TAB = 0x0B
+ ANSI_FORM_FEED = 0x0C
+ ANSI_CARRIAGE_RETURN = 0x0D
+ ANSI_ESCAPE_PRIMARY = 0x1B
+ ANSI_ESCAPE_SECONDARY = 0x5B
+ ANSI_OSC_STRING_ENTRY = 0x5D
+ ANSI_COMMAND_FIRST = 0x40
+ ANSI_COMMAND_LAST = 0x7E
+ DCS_ENTRY = 0x90
+ CSI_ENTRY = 0x9B
+ OSC_STRING = 0x9D
+ ANSI_PARAMETER_SEP = ";"
+ ANSI_CMD_G0 = '('
+ ANSI_CMD_G1 = ')'
+ ANSI_CMD_G2 = '*'
+ ANSI_CMD_G3 = '+'
+ ANSI_CMD_DECPNM = '>'
+ ANSI_CMD_DECPAM = '='
+ ANSI_CMD_OSC = ']'
+ ANSI_CMD_STR_TERM = '\\'
+
+ KEY_CONTROL_PARAM_2 = ";2"
+ KEY_CONTROL_PARAM_3 = ";3"
+ KEY_CONTROL_PARAM_4 = ";4"
+ KEY_CONTROL_PARAM_5 = ";5"
+ KEY_CONTROL_PARAM_6 = ";6"
+ KEY_CONTROL_PARAM_7 = ";7"
+ KEY_CONTROL_PARAM_8 = ";8"
+ KEY_ESC_CSI = "\x1B["
+ KEY_ESC_N = "\x1BN"
+ KEY_ESC_O = "\x1BO"
+
+ FILL_CHARACTER = ' '
+)
+
+func getByteRange(start byte, end byte) []byte {
+ bytes := make([]byte, 0, 32)
+ for i := start; i <= end; i++ {
+ bytes = append(bytes, byte(i))
+ }
+
+ return bytes
+}
+
+var toGroundBytes = getToGroundBytes()
+var executors = getExecuteBytes()
+
+// SPACE 20+A0 hex Always and everywhere a blank space
+// Intermediate 20-2F hex !"#$%&'()*+,-./
+var intermeds = getByteRange(0x20, 0x2F)
+
+// Parameters 30-3F hex 0123456789:;<=>?
+// CSI Parameters 30-39, 3B hex 0123456789;
+var csiParams = getByteRange(0x30, 0x3F)
+
+var csiCollectables = append(getByteRange(0x30, 0x39), getByteRange(0x3B, 0x3F)...)
+
+// Uppercase 40-5F hex @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
+var upperCase = getByteRange(0x40, 0x5F)
+
+// Lowercase 60-7E hex `abcdefghijlkmnopqrstuvwxyz{|}~
+var lowerCase = getByteRange(0x60, 0x7E)
+
+// Alphabetics 40-7E hex (all of upper and lower case)
+var alphabetics = append(upperCase, lowerCase...)
+
+var printables = getByteRange(0x20, 0x7F)
+
+var escapeIntermediateToGroundBytes = getByteRange(0x30, 0x7E)
+var escapeToGroundBytes = getEscapeToGroundBytes()
+
+// See http://www.vt100.net/emu/vt500_parser.png for description of the complex
+// byte ranges below
+
+func getEscapeToGroundBytes() []byte {
+ escapeToGroundBytes := getByteRange(0x30, 0x4F)
+ escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x51, 0x57)...)
+ escapeToGroundBytes = append(escapeToGroundBytes, 0x59)
+ escapeToGroundBytes = append(escapeToGroundBytes, 0x5A)
+ escapeToGroundBytes = append(escapeToGroundBytes, 0x5C)
+ escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x60, 0x7E)...)
+ return escapeToGroundBytes
+}
+
+func getExecuteBytes() []byte {
+ executeBytes := getByteRange(0x00, 0x17)
+ executeBytes = append(executeBytes, 0x19)
+ executeBytes = append(executeBytes, getByteRange(0x1C, 0x1F)...)
+ return executeBytes
+}
+
+func getToGroundBytes() []byte {
+ groundBytes := []byte{0x18}
+ groundBytes = append(groundBytes, 0x1A)
+ groundBytes = append(groundBytes, getByteRange(0x80, 0x8F)...)
+ groundBytes = append(groundBytes, getByteRange(0x91, 0x97)...)
+ groundBytes = append(groundBytes, 0x99)
+ groundBytes = append(groundBytes, 0x9A)
+ groundBytes = append(groundBytes, 0x9C)
+ return groundBytes
+}
+
+// Delete 7F hex Always and everywhere ignored
+// C1 Control 80-9F hex 32 additional control characters
+// G1 Displayable A1-FE hex 94 additional displayable characters
+// Special A0+FF hex Same as SPACE and DELETE
diff --git a/vendor/github.com/Azure/go-ansiterm/context.go b/vendor/github.com/Azure/go-ansiterm/context.go
new file mode 100644
index 0000000..8d66e77
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/context.go
@@ -0,0 +1,7 @@
+package ansiterm
+
+type ansiContext struct {
+ currentChar byte
+ paramBuffer []byte
+ interBuffer []byte
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go
new file mode 100644
index 0000000..1bd6057
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go
@@ -0,0 +1,49 @@
+package ansiterm
+
+type csiEntryState struct {
+ baseState
+}
+
+func (csiState csiEntryState) Handle(b byte) (s state, e error) {
+ logger.Infof("CsiEntry::Handle %#x", b)
+
+ nextState, err := csiState.baseState.Handle(b)
+ if nextState != nil || err != nil {
+ return nextState, err
+ }
+
+ switch {
+ case sliceContains(alphabetics, b):
+ return csiState.parser.ground, nil
+ case sliceContains(csiCollectables, b):
+ return csiState.parser.csiParam, nil
+ case sliceContains(executors, b):
+ return csiState, csiState.parser.execute()
+ }
+
+ return csiState, nil
+}
+
+func (csiState csiEntryState) Transition(s state) error {
+ logger.Infof("CsiEntry::Transition %s --> %s", csiState.Name(), s.Name())
+ csiState.baseState.Transition(s)
+
+ switch s {
+ case csiState.parser.ground:
+ return csiState.parser.csiDispatch()
+ case csiState.parser.csiParam:
+ switch {
+ case sliceContains(csiParams, csiState.parser.context.currentChar):
+ csiState.parser.collectParam()
+ case sliceContains(intermeds, csiState.parser.context.currentChar):
+ csiState.parser.collectInter()
+ }
+ }
+
+ return nil
+}
+
+func (csiState csiEntryState) Enter() error {
+ csiState.parser.clear()
+ return nil
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go
new file mode 100644
index 0000000..4be35c5
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go
@@ -0,0 +1,38 @@
+package ansiterm
+
+type csiParamState struct {
+ baseState
+}
+
+func (csiState csiParamState) Handle(b byte) (s state, e error) {
+ logger.Infof("CsiParam::Handle %#x", b)
+
+ nextState, err := csiState.baseState.Handle(b)
+ if nextState != nil || err != nil {
+ return nextState, err
+ }
+
+ switch {
+ case sliceContains(alphabetics, b):
+ return csiState.parser.ground, nil
+ case sliceContains(csiCollectables, b):
+ csiState.parser.collectParam()
+ return csiState, nil
+ case sliceContains(executors, b):
+ return csiState, csiState.parser.execute()
+ }
+
+ return csiState, nil
+}
+
+func (csiState csiParamState) Transition(s state) error {
+ logger.Infof("CsiParam::Transition %s --> %s", csiState.Name(), s.Name())
+ csiState.baseState.Transition(s)
+
+ switch s {
+ case csiState.parser.ground:
+ return csiState.parser.csiDispatch()
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go
new file mode 100644
index 0000000..2189eb6
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go
@@ -0,0 +1,36 @@
+package ansiterm
+
+type escapeIntermediateState struct {
+ baseState
+}
+
+func (escState escapeIntermediateState) Handle(b byte) (s state, e error) {
+ logger.Infof("escapeIntermediateState::Handle %#x", b)
+ nextState, err := escState.baseState.Handle(b)
+ if nextState != nil || err != nil {
+ return nextState, err
+ }
+
+ switch {
+ case sliceContains(intermeds, b):
+ return escState, escState.parser.collectInter()
+ case sliceContains(executors, b):
+ return escState, escState.parser.execute()
+ case sliceContains(escapeIntermediateToGroundBytes, b):
+ return escState.parser.ground, nil
+ }
+
+ return escState, nil
+}
+
+func (escState escapeIntermediateState) Transition(s state) error {
+ logger.Infof("escapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name())
+ escState.baseState.Transition(s)
+
+ switch s {
+ case escState.parser.ground:
+ return escState.parser.escDispatch()
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/escape_state.go b/vendor/github.com/Azure/go-ansiterm/escape_state.go
new file mode 100644
index 0000000..7b1b9ad
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/escape_state.go
@@ -0,0 +1,47 @@
+package ansiterm
+
+type escapeState struct {
+ baseState
+}
+
+func (escState escapeState) Handle(b byte) (s state, e error) {
+ logger.Infof("escapeState::Handle %#x", b)
+ nextState, err := escState.baseState.Handle(b)
+ if nextState != nil || err != nil {
+ return nextState, err
+ }
+
+ switch {
+ case b == ANSI_ESCAPE_SECONDARY:
+ return escState.parser.csiEntry, nil
+ case b == ANSI_OSC_STRING_ENTRY:
+ return escState.parser.oscString, nil
+ case sliceContains(executors, b):
+ return escState, escState.parser.execute()
+ case sliceContains(escapeToGroundBytes, b):
+ return escState.parser.ground, nil
+ case sliceContains(intermeds, b):
+ return escState.parser.escapeIntermediate, nil
+ }
+
+ return escState, nil
+}
+
+func (escState escapeState) Transition(s state) error {
+ logger.Infof("Escape::Transition %s --> %s", escState.Name(), s.Name())
+ escState.baseState.Transition(s)
+
+ switch s {
+ case escState.parser.ground:
+ return escState.parser.escDispatch()
+ case escState.parser.escapeIntermediate:
+ return escState.parser.collectInter()
+ }
+
+ return nil
+}
+
+func (escState escapeState) Enter() error {
+ escState.parser.clear()
+ return nil
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/event_handler.go b/vendor/github.com/Azure/go-ansiterm/event_handler.go
new file mode 100644
index 0000000..98087b3
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/event_handler.go
@@ -0,0 +1,90 @@
+package ansiterm
+
+type AnsiEventHandler interface {
+ // Print
+ Print(b byte) error
+
+ // Execute C0 commands
+ Execute(b byte) error
+
+ // CUrsor Up
+ CUU(int) error
+
+ // CUrsor Down
+ CUD(int) error
+
+ // CUrsor Forward
+ CUF(int) error
+
+ // CUrsor Backward
+ CUB(int) error
+
+ // Cursor to Next Line
+ CNL(int) error
+
+ // Cursor to Previous Line
+ CPL(int) error
+
+ // Cursor Horizontal position Absolute
+ CHA(int) error
+
+ // Vertical line Position Absolute
+ VPA(int) error
+
+ // CUrsor Position
+ CUP(int, int) error
+
+ // Horizontal and Vertical Position (depends on PUM)
+ HVP(int, int) error
+
+ // Text Cursor Enable Mode
+ DECTCEM(bool) error
+
+ // Origin Mode
+ DECOM(bool) error
+
+ // 132 Column Mode
+ DECCOLM(bool) error
+
+ // Erase in Display
+ ED(int) error
+
+ // Erase in Line
+ EL(int) error
+
+ // Insert Line
+ IL(int) error
+
+ // Delete Line
+ DL(int) error
+
+ // Insert Character
+ ICH(int) error
+
+ // Delete Character
+ DCH(int) error
+
+ // Set Graphics Rendition
+ SGR([]int) error
+
+ // Pan Down
+ SU(int) error
+
+ // Pan Up
+ SD(int) error
+
+ // Device Attributes
+ DA([]string) error
+
+ // Set Top and Bottom Margins
+ DECSTBM(int, int) error
+
+ // Index
+ IND() error
+
+ // Reverse Index
+ RI() error
+
+ // Flush updates from previous commands
+ Flush() error
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/ground_state.go b/vendor/github.com/Azure/go-ansiterm/ground_state.go
new file mode 100644
index 0000000..52451e9
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/ground_state.go
@@ -0,0 +1,24 @@
+package ansiterm
+
+type groundState struct {
+ baseState
+}
+
+func (gs groundState) Handle(b byte) (s state, e error) {
+ gs.parser.context.currentChar = b
+
+ nextState, err := gs.baseState.Handle(b)
+ if nextState != nil || err != nil {
+ return nextState, err
+ }
+
+ switch {
+ case sliceContains(printables, b):
+ return gs, gs.parser.print()
+
+ case sliceContains(executors, b):
+ return gs, gs.parser.execute()
+ }
+
+ return gs, nil
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go
new file mode 100644
index 0000000..24062d4
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go
@@ -0,0 +1,31 @@
+package ansiterm
+
+type oscStringState struct {
+ baseState
+}
+
+func (oscState oscStringState) Handle(b byte) (s state, e error) {
+ logger.Infof("OscString::Handle %#x", b)
+ nextState, err := oscState.baseState.Handle(b)
+ if nextState != nil || err != nil {
+ return nextState, err
+ }
+
+ switch {
+ case isOscStringTerminator(b):
+ return oscState.parser.ground, nil
+ }
+
+ return oscState, nil
+}
+
+// See below for OSC string terminators for linux
+// http://man7.org/linux/man-pages/man4/console_codes.4.html
+func isOscStringTerminator(b byte) bool {
+
+ if b == ANSI_BEL || b == 0x5C {
+ return true
+ }
+
+ return false
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/parser.go b/vendor/github.com/Azure/go-ansiterm/parser.go
new file mode 100644
index 0000000..169f68d
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/parser.go
@@ -0,0 +1,136 @@
+package ansiterm
+
+import (
+ "errors"
+ "io/ioutil"
+ "os"
+
+ "github.com/Sirupsen/logrus"
+)
+
+var logger *logrus.Logger
+
+type AnsiParser struct {
+ currState state
+ eventHandler AnsiEventHandler
+ context *ansiContext
+ csiEntry state
+ csiParam state
+ dcsEntry state
+ escape state
+ escapeIntermediate state
+ error state
+ ground state
+ oscString state
+ stateMap []state
+}
+
+func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser {
+ logFile := ioutil.Discard
+
+ if isDebugEnv := os.Getenv(LogEnv); isDebugEnv == "1" {
+ logFile, _ = os.Create("ansiParser.log")
+ }
+
+ logger = &logrus.Logger{
+ Out: logFile,
+ Formatter: new(logrus.TextFormatter),
+ Level: logrus.InfoLevel,
+ }
+
+ parser := &AnsiParser{
+ eventHandler: evtHandler,
+ context: &ansiContext{},
+ }
+
+ parser.csiEntry = csiEntryState{baseState{name: "CsiEntry", parser: parser}}
+ parser.csiParam = csiParamState{baseState{name: "CsiParam", parser: parser}}
+ parser.dcsEntry = dcsEntryState{baseState{name: "DcsEntry", parser: parser}}
+ parser.escape = escapeState{baseState{name: "Escape", parser: parser}}
+ parser.escapeIntermediate = escapeIntermediateState{baseState{name: "EscapeIntermediate", parser: parser}}
+ parser.error = errorState{baseState{name: "Error", parser: parser}}
+ parser.ground = groundState{baseState{name: "Ground", parser: parser}}
+ parser.oscString = oscStringState{baseState{name: "OscString", parser: parser}}
+
+ parser.stateMap = []state{
+ parser.csiEntry,
+ parser.csiParam,
+ parser.dcsEntry,
+ parser.escape,
+ parser.escapeIntermediate,
+ parser.error,
+ parser.ground,
+ parser.oscString,
+ }
+
+ parser.currState = getState(initialState, parser.stateMap)
+
+ logger.Infof("CreateParser: parser %p", parser)
+ return parser
+}
+
+func getState(name string, states []state) state {
+ for _, el := range states {
+ if el.Name() == name {
+ return el
+ }
+ }
+
+ return nil
+}
+
+func (ap *AnsiParser) Parse(bytes []byte) (int, error) {
+ for i, b := range bytes {
+ if err := ap.handle(b); err != nil {
+ return i, err
+ }
+ }
+
+ return len(bytes), ap.eventHandler.Flush()
+}
+
+func (ap *AnsiParser) handle(b byte) error {
+ ap.context.currentChar = b
+ newState, err := ap.currState.Handle(b)
+ if err != nil {
+ return err
+ }
+
+ if newState == nil {
+ logger.Warning("newState is nil")
+ return errors.New("New state of 'nil' is invalid.")
+ }
+
+ if newState != ap.currState {
+ if err := ap.changeState(newState); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (ap *AnsiParser) changeState(newState state) error {
+ logger.Infof("ChangeState %s --> %s", ap.currState.Name(), newState.Name())
+
+ // Exit old state
+ if err := ap.currState.Exit(); err != nil {
+ logger.Infof("Exit state '%s' failed with : '%v'", ap.currState.Name(), err)
+ return err
+ }
+
+ // Perform transition action
+ if err := ap.currState.Transition(newState); err != nil {
+ logger.Infof("Transition from '%s' to '%s' failed with: '%v'", ap.currState.Name(), newState.Name, err)
+ return err
+ }
+
+ // Enter new state
+ if err := newState.Enter(); err != nil {
+ logger.Infof("Enter state '%s' failed with: '%v'", newState.Name(), err)
+ return err
+ }
+
+ ap.currState = newState
+ return nil
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go
new file mode 100644
index 0000000..8b69a67
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go
@@ -0,0 +1,103 @@
+package ansiterm
+
+import (
+ "strconv"
+)
+
+func parseParams(bytes []byte) ([]string, error) {
+ paramBuff := make([]byte, 0, 0)
+ params := []string{}
+
+ for _, v := range bytes {
+ if v == ';' {
+ if len(paramBuff) > 0 {
+ // Completed parameter, append it to the list
+ s := string(paramBuff)
+ params = append(params, s)
+ paramBuff = make([]byte, 0, 0)
+ }
+ } else {
+ paramBuff = append(paramBuff, v)
+ }
+ }
+
+ // Last parameter may not be terminated with ';'
+ if len(paramBuff) > 0 {
+ s := string(paramBuff)
+ params = append(params, s)
+ }
+
+ logger.Infof("Parsed params: %v with length: %d", params, len(params))
+ return params, nil
+}
+
+func parseCmd(context ansiContext) (string, error) {
+ return string(context.currentChar), nil
+}
+
+func getInt(params []string, dflt int) int {
+ i := getInts(params, 1, dflt)[0]
+ logger.Infof("getInt: %v", i)
+ return i
+}
+
+func getInts(params []string, minCount int, dflt int) []int {
+ ints := []int{}
+
+ for _, v := range params {
+ i, _ := strconv.Atoi(v)
+ // Zero is mapped to the default value in VT100.
+ if i == 0 {
+ i = dflt
+ }
+ ints = append(ints, i)
+ }
+
+ if len(ints) < minCount {
+ remaining := minCount - len(ints)
+ for i := 0; i < remaining; i++ {
+ ints = append(ints, dflt)
+ }
+ }
+
+ logger.Infof("getInts: %v", ints)
+
+ return ints
+}
+
+func (ap *AnsiParser) modeDispatch(param string, set bool) error {
+ switch param {
+ case "?3":
+ return ap.eventHandler.DECCOLM(set)
+ case "?6":
+ return ap.eventHandler.DECOM(set)
+ case "?25":
+ return ap.eventHandler.DECTCEM(set)
+ }
+ return nil
+}
+
+func (ap *AnsiParser) hDispatch(params []string) error {
+ if len(params) == 1 {
+ return ap.modeDispatch(params[0], true)
+ }
+
+ return nil
+}
+
+func (ap *AnsiParser) lDispatch(params []string) error {
+ if len(params) == 1 {
+ return ap.modeDispatch(params[0], false)
+ }
+
+ return nil
+}
+
+func getEraseParam(params []string) int {
+ param := getInt(params, 0)
+ if param < 0 || 3 < param {
+ param = 0
+ }
+
+ return param
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/parser_actions.go b/vendor/github.com/Azure/go-ansiterm/parser_actions.go
new file mode 100644
index 0000000..58750a2
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/parser_actions.go
@@ -0,0 +1,122 @@
+package ansiterm
+
+import (
+ "fmt"
+)
+
+func (ap *AnsiParser) collectParam() error {
+ currChar := ap.context.currentChar
+ logger.Infof("collectParam %#x", currChar)
+ ap.context.paramBuffer = append(ap.context.paramBuffer, currChar)
+ return nil
+}
+
+func (ap *AnsiParser) collectInter() error {
+ currChar := ap.context.currentChar
+ logger.Infof("collectInter %#x", currChar)
+ ap.context.paramBuffer = append(ap.context.interBuffer, currChar)
+ return nil
+}
+
+func (ap *AnsiParser) escDispatch() error {
+ cmd, _ := parseCmd(*ap.context)
+ intermeds := ap.context.interBuffer
+ logger.Infof("escDispatch currentChar: %#x", ap.context.currentChar)
+ logger.Infof("escDispatch: %v(%v)", cmd, intermeds)
+
+ switch cmd {
+ case "D": // IND
+ return ap.eventHandler.IND()
+ case "E": // NEL, equivalent to CRLF
+ err := ap.eventHandler.Execute(ANSI_CARRIAGE_RETURN)
+ if err == nil {
+ err = ap.eventHandler.Execute(ANSI_LINE_FEED)
+ }
+ return err
+ case "M": // RI
+ return ap.eventHandler.RI()
+ }
+
+ return nil
+}
+
+func (ap *AnsiParser) csiDispatch() error {
+ cmd, _ := parseCmd(*ap.context)
+ params, _ := parseParams(ap.context.paramBuffer)
+
+ logger.Infof("csiDispatch: %v(%v)", cmd, params)
+
+ switch cmd {
+ case "@":
+ return ap.eventHandler.ICH(getInt(params, 1))
+ case "A":
+ return ap.eventHandler.CUU(getInt(params, 1))
+ case "B":
+ return ap.eventHandler.CUD(getInt(params, 1))
+ case "C":
+ return ap.eventHandler.CUF(getInt(params, 1))
+ case "D":
+ return ap.eventHandler.CUB(getInt(params, 1))
+ case "E":
+ return ap.eventHandler.CNL(getInt(params, 1))
+ case "F":
+ return ap.eventHandler.CPL(getInt(params, 1))
+ case "G":
+ return ap.eventHandler.CHA(getInt(params, 1))
+ case "H":
+ ints := getInts(params, 2, 1)
+ x, y := ints[0], ints[1]
+ return ap.eventHandler.CUP(x, y)
+ case "J":
+ param := getEraseParam(params)
+ return ap.eventHandler.ED(param)
+ case "K":
+ param := getEraseParam(params)
+ return ap.eventHandler.EL(param)
+ case "L":
+ return ap.eventHandler.IL(getInt(params, 1))
+ case "M":
+ return ap.eventHandler.DL(getInt(params, 1))
+ case "P":
+ return ap.eventHandler.DCH(getInt(params, 1))
+ case "S":
+ return ap.eventHandler.SU(getInt(params, 1))
+ case "T":
+ return ap.eventHandler.SD(getInt(params, 1))
+ case "c":
+ return ap.eventHandler.DA(params)
+ case "d":
+ return ap.eventHandler.VPA(getInt(params, 1))
+ case "f":
+ ints := getInts(params, 2, 1)
+ x, y := ints[0], ints[1]
+ return ap.eventHandler.HVP(x, y)
+ case "h":
+ return ap.hDispatch(params)
+ case "l":
+ return ap.lDispatch(params)
+ case "m":
+ return ap.eventHandler.SGR(getInts(params, 1, 0))
+ case "r":
+ ints := getInts(params, 2, 1)
+ top, bottom := ints[0], ints[1]
+ return ap.eventHandler.DECSTBM(top, bottom)
+ default:
+ logger.Errorf(fmt.Sprintf("Unsupported CSI command: '%s', with full context: %v", cmd, ap.context))
+ return nil
+ }
+
+}
+
+func (ap *AnsiParser) print() error {
+ return ap.eventHandler.Print(ap.context.currentChar)
+}
+
+func (ap *AnsiParser) clear() error {
+ ap.context = &ansiContext{}
+ return nil
+}
+
+func (ap *AnsiParser) execute() error {
+ return ap.eventHandler.Execute(ap.context.currentChar)
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/states.go b/vendor/github.com/Azure/go-ansiterm/states.go
new file mode 100644
index 0000000..f2ea1fc
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/states.go
@@ -0,0 +1,71 @@
+package ansiterm
+
+type stateID int
+
+type state interface {
+ Enter() error
+ Exit() error
+ Handle(byte) (state, error)
+ Name() string
+ Transition(state) error
+}
+
+type baseState struct {
+ name string
+ parser *AnsiParser
+}
+
+func (base baseState) Enter() error {
+ return nil
+}
+
+func (base baseState) Exit() error {
+ return nil
+}
+
+func (base baseState) Handle(b byte) (s state, e error) {
+
+ switch {
+ case b == CSI_ENTRY:
+ return base.parser.csiEntry, nil
+ case b == DCS_ENTRY:
+ return base.parser.dcsEntry, nil
+ case b == ANSI_ESCAPE_PRIMARY:
+ return base.parser.escape, nil
+ case b == OSC_STRING:
+ return base.parser.oscString, nil
+ case sliceContains(toGroundBytes, b):
+ return base.parser.ground, nil
+ }
+
+ return nil, nil
+}
+
+func (base baseState) Name() string {
+ return base.name
+}
+
+func (base baseState) Transition(s state) error {
+ if s == base.parser.ground {
+ execBytes := []byte{0x18}
+ execBytes = append(execBytes, 0x1A)
+ execBytes = append(execBytes, getByteRange(0x80, 0x8F)...)
+ execBytes = append(execBytes, getByteRange(0x91, 0x97)...)
+ execBytes = append(execBytes, 0x99)
+ execBytes = append(execBytes, 0x9A)
+
+ if sliceContains(execBytes, base.parser.context.currentChar) {
+ return base.parser.execute()
+ }
+ }
+
+ return nil
+}
+
+type dcsEntryState struct {
+ baseState
+}
+
+type errorState struct {
+ baseState
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/utilities.go
new file mode 100644
index 0000000..3921144
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/utilities.go
@@ -0,0 +1,21 @@
+package ansiterm
+
+import (
+ "strconv"
+)
+
+func sliceContains(bytes []byte, b byte) bool {
+ for _, v := range bytes {
+ if v == b {
+ return true
+ }
+ }
+
+ return false
+}
+
+func convertBytesToInteger(bytes []byte) int {
+ s := string(bytes)
+ i, _ := strconv.Atoi(s)
+ return i
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go
new file mode 100644
index 0000000..daf2f06
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go
@@ -0,0 +1,182 @@
+// +build windows
+
+package winterm
+
+import (
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+ "syscall"
+
+ "github.com/Azure/go-ansiterm"
+)
+
+// Windows keyboard constants
+// See https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx.
+const (
+ VK_PRIOR = 0x21 // PAGE UP key
+ VK_NEXT = 0x22 // PAGE DOWN key
+ VK_END = 0x23 // END key
+ VK_HOME = 0x24 // HOME key
+ VK_LEFT = 0x25 // LEFT ARROW key
+ VK_UP = 0x26 // UP ARROW key
+ VK_RIGHT = 0x27 // RIGHT ARROW key
+ VK_DOWN = 0x28 // DOWN ARROW key
+ VK_SELECT = 0x29 // SELECT key
+ VK_PRINT = 0x2A // PRINT key
+ VK_EXECUTE = 0x2B // EXECUTE key
+ VK_SNAPSHOT = 0x2C // PRINT SCREEN key
+ VK_INSERT = 0x2D // INS key
+ VK_DELETE = 0x2E // DEL key
+ VK_HELP = 0x2F // HELP key
+ VK_F1 = 0x70 // F1 key
+ VK_F2 = 0x71 // F2 key
+ VK_F3 = 0x72 // F3 key
+ VK_F4 = 0x73 // F4 key
+ VK_F5 = 0x74 // F5 key
+ VK_F6 = 0x75 // F6 key
+ VK_F7 = 0x76 // F7 key
+ VK_F8 = 0x77 // F8 key
+ VK_F9 = 0x78 // F9 key
+ VK_F10 = 0x79 // F10 key
+ VK_F11 = 0x7A // F11 key
+ VK_F12 = 0x7B // F12 key
+
+ RIGHT_ALT_PRESSED = 0x0001
+ LEFT_ALT_PRESSED = 0x0002
+ RIGHT_CTRL_PRESSED = 0x0004
+ LEFT_CTRL_PRESSED = 0x0008
+ SHIFT_PRESSED = 0x0010
+ NUMLOCK_ON = 0x0020
+ SCROLLLOCK_ON = 0x0040
+ CAPSLOCK_ON = 0x0080
+ ENHANCED_KEY = 0x0100
+)
+
+type ansiCommand struct {
+ CommandBytes []byte
+ Command string
+ Parameters []string
+ IsSpecial bool
+}
+
+func newAnsiCommand(command []byte) *ansiCommand {
+
+ if isCharacterSelectionCmdChar(command[1]) {
+ // Is Character Set Selection commands
+ return &ansiCommand{
+ CommandBytes: command,
+ Command: string(command),
+ IsSpecial: true,
+ }
+ }
+
+ // last char is command character
+ lastCharIndex := len(command) - 1
+
+ ac := &ansiCommand{
+ CommandBytes: command,
+ Command: string(command[lastCharIndex]),
+ IsSpecial: false,
+ }
+
+ // more than a single escape
+ if lastCharIndex != 0 {
+ start := 1
+ // skip if double char escape sequence
+ if command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_ESCAPE_SECONDARY {
+ start++
+ }
+ // convert this to GetNextParam method
+ ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ansiterm.ANSI_PARAMETER_SEP)
+ }
+
+ return ac
+}
+
+func (ac *ansiCommand) paramAsSHORT(index int, defaultValue int16) int16 {
+ if index < 0 || index >= len(ac.Parameters) {
+ return defaultValue
+ }
+
+ param, err := strconv.ParseInt(ac.Parameters[index], 10, 16)
+ if err != nil {
+ return defaultValue
+ }
+
+ return int16(param)
+}
+
+func (ac *ansiCommand) String() string {
+ return fmt.Sprintf("0x%v \"%v\" (\"%v\")",
+ bytesToHex(ac.CommandBytes),
+ ac.Command,
+ strings.Join(ac.Parameters, "\",\""))
+}
+
+// isAnsiCommandChar returns true if the passed byte falls within the range of ANSI commands.
+// See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html.
+func isAnsiCommandChar(b byte) bool {
+ switch {
+ case ansiterm.ANSI_COMMAND_FIRST <= b && b <= ansiterm.ANSI_COMMAND_LAST && b != ansiterm.ANSI_ESCAPE_SECONDARY:
+ return true
+ case b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_OSC || b == ansiterm.ANSI_CMD_DECPAM || b == ansiterm.ANSI_CMD_DECPNM:
+ // non-CSI escape sequence terminator
+ return true
+ case b == ansiterm.ANSI_CMD_STR_TERM || b == ansiterm.ANSI_BEL:
+ // String escape sequence terminator
+ return true
+ }
+ return false
+}
+
+func isXtermOscSequence(command []byte, current byte) bool {
+ return (len(command) >= 2 && command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_CMD_OSC && current != ansiterm.ANSI_BEL)
+}
+
+func isCharacterSelectionCmdChar(b byte) bool {
+ return (b == ansiterm.ANSI_CMD_G0 || b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_G2 || b == ansiterm.ANSI_CMD_G3)
+}
+
+// bytesToHex converts a slice of bytes to a human-readable string.
+func bytesToHex(b []byte) string {
+ hex := make([]string, len(b))
+ for i, ch := range b {
+ hex[i] = fmt.Sprintf("%X", ch)
+ }
+ return strings.Join(hex, "")
+}
+
+// ensureInRange adjusts the passed value, if necessary, to ensure it is within
+// the passed min / max range.
+func ensureInRange(n int16, min int16, max int16) int16 {
+ if n < min {
+ return min
+ } else if n > max {
+ return max
+ } else {
+ return n
+ }
+}
+
+func GetStdFile(nFile int) (*os.File, uintptr) {
+ var file *os.File
+ switch nFile {
+ case syscall.STD_INPUT_HANDLE:
+ file = os.Stdin
+ case syscall.STD_OUTPUT_HANDLE:
+ file = os.Stdout
+ case syscall.STD_ERROR_HANDLE:
+ file = os.Stderr
+ default:
+ panic(fmt.Errorf("Invalid standard handle identifier: %v", nFile))
+ }
+
+ fd, err := syscall.GetStdHandle(nFile)
+ if err != nil {
+ panic(fmt.Errorf("Invalid standard handle indentifier: %v -- %v", nFile, err))
+ }
+
+ return file, uintptr(fd)
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go
new file mode 100644
index 0000000..462d92f
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/winterm/api.go
@@ -0,0 +1,322 @@
+// +build windows
+
+package winterm
+
+import (
+ "fmt"
+ "syscall"
+ "unsafe"
+)
+
+//===========================================================================================================
+// IMPORTANT NOTE:
+//
+// The methods below make extensive use of the "unsafe" package to obtain the required pointers.
+// Beginning in Go 1.3, the garbage collector may release local variables (e.g., incoming arguments, stack
+// variables) the pointers reference *before* the API completes.
+//
+// As a result, in those cases, the code must hint that the variables remain in active by invoking the
+// dummy method "use" (see below). Newer versions of Go are planned to change the mechanism to no longer
+// require unsafe pointers.
+//
+// If you add or modify methods, ENSURE protection of local variables through the "use" builtin to inform
+// the garbage collector the variables remain in use if:
+//
+// -- The value is not a pointer (e.g., int32, struct)
+// -- The value is not referenced by the method after passing the pointer to Windows
+//
+// See http://golang.org/doc/go1.3.
+//===========================================================================================================
+
+var (
+ kernel32DLL = syscall.NewLazyDLL("kernel32.dll")
+
+ getConsoleCursorInfoProc = kernel32DLL.NewProc("GetConsoleCursorInfo")
+ setConsoleCursorInfoProc = kernel32DLL.NewProc("SetConsoleCursorInfo")
+ setConsoleCursorPositionProc = kernel32DLL.NewProc("SetConsoleCursorPosition")
+ setConsoleModeProc = kernel32DLL.NewProc("SetConsoleMode")
+ getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo")
+ setConsoleScreenBufferSizeProc = kernel32DLL.NewProc("SetConsoleScreenBufferSize")
+ scrollConsoleScreenBufferProc = kernel32DLL.NewProc("ScrollConsoleScreenBufferA")
+ setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute")
+ setConsoleWindowInfoProc = kernel32DLL.NewProc("SetConsoleWindowInfo")
+ writeConsoleOutputProc = kernel32DLL.NewProc("WriteConsoleOutputW")
+ readConsoleInputProc = kernel32DLL.NewProc("ReadConsoleInputW")
+ waitForSingleObjectProc = kernel32DLL.NewProc("WaitForSingleObject")
+)
+
+// Windows Console constants
+const (
+ // Console modes
+ // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx.
+ ENABLE_PROCESSED_INPUT = 0x0001
+ ENABLE_LINE_INPUT = 0x0002
+ ENABLE_ECHO_INPUT = 0x0004
+ ENABLE_WINDOW_INPUT = 0x0008
+ ENABLE_MOUSE_INPUT = 0x0010
+ ENABLE_INSERT_MODE = 0x0020
+ ENABLE_QUICK_EDIT_MODE = 0x0040
+ ENABLE_EXTENDED_FLAGS = 0x0080
+
+ ENABLE_PROCESSED_OUTPUT = 0x0001
+ ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002
+
+ // Character attributes
+ // Note:
+ // -- The attributes are combined to produce various colors (e.g., Blue + Green will create Cyan).
+ // Clearing all foreground or background colors results in black; setting all creates white.
+ // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes.
+ FOREGROUND_BLUE uint16 = 0x0001
+ FOREGROUND_GREEN uint16 = 0x0002
+ FOREGROUND_RED uint16 = 0x0004
+ FOREGROUND_INTENSITY uint16 = 0x0008
+ FOREGROUND_MASK uint16 = 0x000F
+
+ BACKGROUND_BLUE uint16 = 0x0010
+ BACKGROUND_GREEN uint16 = 0x0020
+ BACKGROUND_RED uint16 = 0x0040
+ BACKGROUND_INTENSITY uint16 = 0x0080
+ BACKGROUND_MASK uint16 = 0x00F0
+
+ COMMON_LVB_MASK uint16 = 0xFF00
+ COMMON_LVB_REVERSE_VIDEO uint16 = 0x4000
+ COMMON_LVB_UNDERSCORE uint16 = 0x8000
+
+ // Input event types
+ // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx.
+ KEY_EVENT = 0x0001
+ MOUSE_EVENT = 0x0002
+ WINDOW_BUFFER_SIZE_EVENT = 0x0004
+ MENU_EVENT = 0x0008
+ FOCUS_EVENT = 0x0010
+
+ // WaitForSingleObject return codes
+ WAIT_ABANDONED = 0x00000080
+ WAIT_FAILED = 0xFFFFFFFF
+ WAIT_SIGNALED = 0x0000000
+ WAIT_TIMEOUT = 0x00000102
+
+ // WaitForSingleObject wait duration
+ WAIT_INFINITE = 0xFFFFFFFF
+ WAIT_ONE_SECOND = 1000
+ WAIT_HALF_SECOND = 500
+ WAIT_QUARTER_SECOND = 250
+)
+
+// Windows API Console types
+// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682101(v=vs.85).aspx for Console specific types (e.g., COORD)
+// -- See https://msdn.microsoft.com/en-us/library/aa296569(v=vs.60).aspx for comments on alignment
+type (
+ CHAR_INFO struct {
+ UnicodeChar uint16
+ Attributes uint16
+ }
+
+ CONSOLE_CURSOR_INFO struct {
+ Size uint32
+ Visible int32
+ }
+
+ CONSOLE_SCREEN_BUFFER_INFO struct {
+ Size COORD
+ CursorPosition COORD
+ Attributes uint16
+ Window SMALL_RECT
+ MaximumWindowSize COORD
+ }
+
+ COORD struct {
+ X int16
+ Y int16
+ }
+
+ SMALL_RECT struct {
+ Left int16
+ Top int16
+ Right int16
+ Bottom int16
+ }
+
+ // INPUT_RECORD is a C/C++ union of which KEY_EVENT_RECORD is one case, it is also the largest
+ // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx.
+ INPUT_RECORD struct {
+ EventType uint16
+ KeyEvent KEY_EVENT_RECORD
+ }
+
+ KEY_EVENT_RECORD struct {
+ KeyDown int32
+ RepeatCount uint16
+ VirtualKeyCode uint16
+ VirtualScanCode uint16
+ UnicodeChar uint16
+ ControlKeyState uint32
+ }
+
+ WINDOW_BUFFER_SIZE struct {
+ Size COORD
+ }
+)
+
+// boolToBOOL converts a Go bool into a Windows int32.
+func boolToBOOL(f bool) int32 {
+ if f {
+ return int32(1)
+ } else {
+ return int32(0)
+ }
+}
+
+// GetConsoleCursorInfo retrieves information about the size and visiblity of the console cursor.
+// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683163(v=vs.85).aspx.
+func GetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error {
+ r1, r2, err := getConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0)
+ return checkError(r1, r2, err)
+}
+
+// SetConsoleCursorInfo sets the size and visiblity of the console cursor.
+// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686019(v=vs.85).aspx.
+func SetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error {
+ r1, r2, err := setConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0)
+ return checkError(r1, r2, err)
+}
+
+// SetConsoleCursorPosition location of the console cursor.
+// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx.
+func SetConsoleCursorPosition(handle uintptr, coord COORD) error {
+ r1, r2, err := setConsoleCursorPositionProc.Call(handle, coordToPointer(coord))
+ use(coord)
+ return checkError(r1, r2, err)
+}
+
+// GetConsoleMode gets the console mode for given file descriptor
+// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx.
+func GetConsoleMode(handle uintptr) (mode uint32, err error) {
+ err = syscall.GetConsoleMode(syscall.Handle(handle), &mode)
+ return mode, err
+}
+
+// SetConsoleMode sets the console mode for given file descriptor
+// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx.
+func SetConsoleMode(handle uintptr, mode uint32) error {
+ r1, r2, err := setConsoleModeProc.Call(handle, uintptr(mode), 0)
+ use(mode)
+ return checkError(r1, r2, err)
+}
+
+// GetConsoleScreenBufferInfo retrieves information about the specified console screen buffer.
+// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171(v=vs.85).aspx.
+func GetConsoleScreenBufferInfo(handle uintptr) (*CONSOLE_SCREEN_BUFFER_INFO, error) {
+ info := CONSOLE_SCREEN_BUFFER_INFO{}
+ err := checkError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0))
+ if err != nil {
+ return nil, err
+ }
+ return &info, nil
+}
+
+func ScrollConsoleScreenBuffer(handle uintptr, scrollRect SMALL_RECT, clipRect SMALL_RECT, destOrigin COORD, char CHAR_INFO) error {
+ r1, r2, err := scrollConsoleScreenBufferProc.Call(handle, uintptr(unsafe.Pointer(&scrollRect)), uintptr(unsafe.Pointer(&clipRect)), coordToPointer(destOrigin), uintptr(unsafe.Pointer(&char)))
+ use(scrollRect)
+ use(clipRect)
+ use(destOrigin)
+ use(char)
+ return checkError(r1, r2, err)
+}
+
+// SetConsoleScreenBufferSize sets the size of the console screen buffer.
+// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686044(v=vs.85).aspx.
+func SetConsoleScreenBufferSize(handle uintptr, coord COORD) error {
+ r1, r2, err := setConsoleScreenBufferSizeProc.Call(handle, coordToPointer(coord))
+ use(coord)
+ return checkError(r1, r2, err)
+}
+
+// SetConsoleTextAttribute sets the attributes of characters written to the
+// console screen buffer by the WriteFile or WriteConsole function.
+// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx.
+func SetConsoleTextAttribute(handle uintptr, attribute uint16) error {
+ r1, r2, err := setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0)
+ use(attribute)
+ return checkError(r1, r2, err)
+}
+
+// SetConsoleWindowInfo sets the size and position of the console screen buffer's window.
+// Note that the size and location must be within and no larger than the backing console screen buffer.
+// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686125(v=vs.85).aspx.
+func SetConsoleWindowInfo(handle uintptr, isAbsolute bool, rect SMALL_RECT) error {
+ r1, r2, err := setConsoleWindowInfoProc.Call(handle, uintptr(boolToBOOL(isAbsolute)), uintptr(unsafe.Pointer(&rect)))
+ use(isAbsolute)
+ use(rect)
+ return checkError(r1, r2, err)
+}
+
+// WriteConsoleOutput writes the CHAR_INFOs from the provided buffer to the active console buffer.
+// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687404(v=vs.85).aspx.
+func WriteConsoleOutput(handle uintptr, buffer []CHAR_INFO, bufferSize COORD, bufferCoord COORD, writeRegion *SMALL_RECT) error {
+ r1, r2, err := writeConsoleOutputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), coordToPointer(bufferSize), coordToPointer(bufferCoord), uintptr(unsafe.Pointer(writeRegion)))
+ use(buffer)
+ use(bufferSize)
+ use(bufferCoord)
+ return checkError(r1, r2, err)
+}
+
+// ReadConsoleInput reads (and removes) data from the console input buffer.
+// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx.
+func ReadConsoleInput(handle uintptr, buffer []INPUT_RECORD, count *uint32) error {
+ r1, r2, err := readConsoleInputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), uintptr(len(buffer)), uintptr(unsafe.Pointer(count)))
+ use(buffer)
+ return checkError(r1, r2, err)
+}
+
+// WaitForSingleObject waits for the passed handle to be signaled.
+// It returns true if the handle was signaled; false otherwise.
+// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx.
+func WaitForSingleObject(handle uintptr, msWait uint32) (bool, error) {
+ r1, _, err := waitForSingleObjectProc.Call(handle, uintptr(uint32(msWait)))
+ switch r1 {
+ case WAIT_ABANDONED, WAIT_TIMEOUT:
+ return false, nil
+ case WAIT_SIGNALED:
+ return true, nil
+ }
+ use(msWait)
+ return false, err
+}
+
+// String helpers
+func (info CONSOLE_SCREEN_BUFFER_INFO) String() string {
+ return fmt.Sprintf("Size(%v) Cursor(%v) Window(%v) Max(%v)", info.Size, info.CursorPosition, info.Window, info.MaximumWindowSize)
+}
+
+func (coord COORD) String() string {
+ return fmt.Sprintf("%v,%v", coord.X, coord.Y)
+}
+
+func (rect SMALL_RECT) String() string {
+ return fmt.Sprintf("(%v,%v),(%v,%v)", rect.Left, rect.Top, rect.Right, rect.Bottom)
+}
+
+// checkError evaluates the results of a Windows API call and returns the error if it failed.
+func checkError(r1, r2 uintptr, err error) error {
+ // Windows APIs return non-zero to indicate success
+ if r1 != 0 {
+ return nil
+ }
+
+ // Return the error if provided, otherwise default to EINVAL
+ if err != nil {
+ return err
+ }
+ return syscall.EINVAL
+}
+
+// coordToPointer converts a COORD into a uintptr (by fooling the type system).
+func coordToPointer(c COORD) uintptr {
+ // Note: This code assumes the two SHORTs are correctly laid out; the "cast" to uint32 is just to get a pointer to pass.
+ return uintptr(*((*uint32)(unsafe.Pointer(&c))))
+}
+
+// use is a no-op, but the compiler cannot see that it is.
+// Calling use(p) ensures that p is kept live until that point.
+func use(p interface{}) {}
diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go
new file mode 100644
index 0000000..cbec8f7
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go
@@ -0,0 +1,100 @@
+// +build windows
+
+package winterm
+
+import "github.com/Azure/go-ansiterm"
+
+const (
+ FOREGROUND_COLOR_MASK = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
+ BACKGROUND_COLOR_MASK = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
+)
+
+// collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the
+// request represented by the passed ANSI mode.
+func collectAnsiIntoWindowsAttributes(windowsMode uint16, inverted bool, baseMode uint16, ansiMode int16) (uint16, bool) {
+ switch ansiMode {
+
+ // Mode styles
+ case ansiterm.ANSI_SGR_BOLD:
+ windowsMode = windowsMode | FOREGROUND_INTENSITY
+
+ case ansiterm.ANSI_SGR_DIM, ansiterm.ANSI_SGR_BOLD_DIM_OFF:
+ windowsMode &^= FOREGROUND_INTENSITY
+
+ case ansiterm.ANSI_SGR_UNDERLINE:
+ windowsMode = windowsMode | COMMON_LVB_UNDERSCORE
+
+ case ansiterm.ANSI_SGR_REVERSE:
+ inverted = true
+
+ case ansiterm.ANSI_SGR_REVERSE_OFF:
+ inverted = false
+
+ case ansiterm.ANSI_SGR_UNDERLINE_OFF:
+ windowsMode &^= COMMON_LVB_UNDERSCORE
+
+ // Foreground colors
+ case ansiterm.ANSI_SGR_FOREGROUND_DEFAULT:
+ windowsMode = (windowsMode &^ FOREGROUND_MASK) | (baseMode & FOREGROUND_MASK)
+
+ case ansiterm.ANSI_SGR_FOREGROUND_BLACK:
+ windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK)
+
+ case ansiterm.ANSI_SGR_FOREGROUND_RED:
+ windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED
+
+ case ansiterm.ANSI_SGR_FOREGROUND_GREEN:
+ windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN
+
+ case ansiterm.ANSI_SGR_FOREGROUND_YELLOW:
+ windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN
+
+ case ansiterm.ANSI_SGR_FOREGROUND_BLUE:
+ windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_BLUE
+
+ case ansiterm.ANSI_SGR_FOREGROUND_MAGENTA:
+ windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_BLUE
+
+ case ansiterm.ANSI_SGR_FOREGROUND_CYAN:
+ windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN | FOREGROUND_BLUE
+
+ case ansiterm.ANSI_SGR_FOREGROUND_WHITE:
+ windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
+
+ // Background colors
+ case ansiterm.ANSI_SGR_BACKGROUND_DEFAULT:
+ // Black with no intensity
+ windowsMode = (windowsMode &^ BACKGROUND_MASK) | (baseMode & BACKGROUND_MASK)
+
+ case ansiterm.ANSI_SGR_BACKGROUND_BLACK:
+ windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK)
+
+ case ansiterm.ANSI_SGR_BACKGROUND_RED:
+ windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED
+
+ case ansiterm.ANSI_SGR_BACKGROUND_GREEN:
+ windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN
+
+ case ansiterm.ANSI_SGR_BACKGROUND_YELLOW:
+ windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN
+
+ case ansiterm.ANSI_SGR_BACKGROUND_BLUE:
+ windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_BLUE
+
+ case ansiterm.ANSI_SGR_BACKGROUND_MAGENTA:
+ windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_BLUE
+
+ case ansiterm.ANSI_SGR_BACKGROUND_CYAN:
+ windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN | BACKGROUND_BLUE
+
+ case ansiterm.ANSI_SGR_BACKGROUND_WHITE:
+ windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
+ }
+
+ return windowsMode, inverted
+}
+
+// invertAttributes inverts the foreground and background colors of a Windows attributes value
+func invertAttributes(windowsMode uint16) uint16 {
+ return (COMMON_LVB_MASK & windowsMode) | ((FOREGROUND_MASK & windowsMode) << 4) | ((BACKGROUND_MASK & windowsMode) >> 4)
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go
new file mode 100644
index 0000000..f015723
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go
@@ -0,0 +1,101 @@
+// +build windows
+
+package winterm
+
+const (
+ horizontal = iota
+ vertical
+)
+
+func (h *windowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_INFO) SMALL_RECT {
+ if h.originMode {
+ sr := h.effectiveSr(info.Window)
+ return SMALL_RECT{
+ Top: sr.top,
+ Bottom: sr.bottom,
+ Left: 0,
+ Right: info.Size.X - 1,
+ }
+ } else {
+ return SMALL_RECT{
+ Top: info.Window.Top,
+ Bottom: info.Window.Bottom,
+ Left: 0,
+ Right: info.Size.X - 1,
+ }
+ }
+}
+
+// setCursorPosition sets the cursor to the specified position, bounded to the screen size
+func (h *windowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error {
+ position.X = ensureInRange(position.X, window.Left, window.Right)
+ position.Y = ensureInRange(position.Y, window.Top, window.Bottom)
+ err := SetConsoleCursorPosition(h.fd, position)
+ if err != nil {
+ return err
+ }
+ logger.Infof("Cursor position set: (%d, %d)", position.X, position.Y)
+ return err
+}
+
+func (h *windowsAnsiEventHandler) moveCursorVertical(param int) error {
+ return h.moveCursor(vertical, param)
+}
+
+func (h *windowsAnsiEventHandler) moveCursorHorizontal(param int) error {
+ return h.moveCursor(horizontal, param)
+}
+
+func (h *windowsAnsiEventHandler) moveCursor(moveMode int, param int) error {
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+
+ position := info.CursorPosition
+ switch moveMode {
+ case horizontal:
+ position.X += int16(param)
+ case vertical:
+ position.Y += int16(param)
+ }
+
+ if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) moveCursorLine(param int) error {
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+
+ position := info.CursorPosition
+ position.X = 0
+ position.Y += int16(param)
+
+ if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) moveCursorColumn(param int) error {
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+
+ position := info.CursorPosition
+ position.X = int16(param) - 1
+
+ if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go
new file mode 100644
index 0000000..244b5fa
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go
@@ -0,0 +1,84 @@
+// +build windows
+
+package winterm
+
+import "github.com/Azure/go-ansiterm"
+
+func (h *windowsAnsiEventHandler) clearRange(attributes uint16, fromCoord COORD, toCoord COORD) error {
+ // Ignore an invalid (negative area) request
+ if toCoord.Y < fromCoord.Y {
+ return nil
+ }
+
+ var err error
+
+ var coordStart = COORD{}
+ var coordEnd = COORD{}
+
+ xCurrent, yCurrent := fromCoord.X, fromCoord.Y
+ xEnd, yEnd := toCoord.X, toCoord.Y
+
+ // Clear any partial initial line
+ if xCurrent > 0 {
+ coordStart.X, coordStart.Y = xCurrent, yCurrent
+ coordEnd.X, coordEnd.Y = xEnd, yCurrent
+
+ err = h.clearRect(attributes, coordStart, coordEnd)
+ if err != nil {
+ return err
+ }
+
+ xCurrent = 0
+ yCurrent += 1
+ }
+
+ // Clear intervening rectangular section
+ if yCurrent < yEnd {
+ coordStart.X, coordStart.Y = xCurrent, yCurrent
+ coordEnd.X, coordEnd.Y = xEnd, yEnd-1
+
+ err = h.clearRect(attributes, coordStart, coordEnd)
+ if err != nil {
+ return err
+ }
+
+ xCurrent = 0
+ yCurrent = yEnd
+ }
+
+ // Clear remaining partial ending line
+ coordStart.X, coordStart.Y = xCurrent, yCurrent
+ coordEnd.X, coordEnd.Y = xEnd, yEnd
+
+ err = h.clearRect(attributes, coordStart, coordEnd)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) clearRect(attributes uint16, fromCoord COORD, toCoord COORD) error {
+ region := SMALL_RECT{Top: fromCoord.Y, Left: fromCoord.X, Bottom: toCoord.Y, Right: toCoord.X}
+ width := toCoord.X - fromCoord.X + 1
+ height := toCoord.Y - fromCoord.Y + 1
+ size := uint32(width) * uint32(height)
+
+ if size <= 0 {
+ return nil
+ }
+
+ buffer := make([]CHAR_INFO, size)
+
+ char := CHAR_INFO{ansiterm.FILL_CHARACTER, attributes}
+ for i := 0; i < int(size); i++ {
+ buffer[i] = char
+ }
+
+ err := WriteConsoleOutput(h.fd, buffer, COORD{X: width, Y: height}, COORD{X: 0, Y: 0}, &region)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go
new file mode 100644
index 0000000..706d270
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go
@@ -0,0 +1,118 @@
+// +build windows
+
+package winterm
+
+// effectiveSr gets the current effective scroll region in buffer coordinates
+func (h *windowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion {
+ top := addInRange(window.Top, h.sr.top, window.Top, window.Bottom)
+ bottom := addInRange(window.Top, h.sr.bottom, window.Top, window.Bottom)
+ if top >= bottom {
+ top = window.Top
+ bottom = window.Bottom
+ }
+ return scrollRegion{top: top, bottom: bottom}
+}
+
+func (h *windowsAnsiEventHandler) scrollUp(param int) error {
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+
+ sr := h.effectiveSr(info.Window)
+ return h.scroll(param, sr, info)
+}
+
+func (h *windowsAnsiEventHandler) scrollDown(param int) error {
+ return h.scrollUp(-param)
+}
+
+func (h *windowsAnsiEventHandler) deleteLines(param int) error {
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+
+ start := info.CursorPosition.Y
+ sr := h.effectiveSr(info.Window)
+ // Lines cannot be inserted or deleted outside the scrolling region.
+ if start >= sr.top && start <= sr.bottom {
+ sr.top = start
+ return h.scroll(param, sr, info)
+ } else {
+ return nil
+ }
+}
+
+func (h *windowsAnsiEventHandler) insertLines(param int) error {
+ return h.deleteLines(-param)
+}
+
+// scroll scrolls the provided scroll region by param lines. The scroll region is in buffer coordinates.
+func (h *windowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error {
+ logger.Infof("scroll: scrollTop: %d, scrollBottom: %d", sr.top, sr.bottom)
+ logger.Infof("scroll: windowTop: %d, windowBottom: %d", info.Window.Top, info.Window.Bottom)
+
+ // Copy from and clip to the scroll region (full buffer width)
+ scrollRect := SMALL_RECT{
+ Top: sr.top,
+ Bottom: sr.bottom,
+ Left: 0,
+ Right: info.Size.X - 1,
+ }
+
+ // Origin to which area should be copied
+ destOrigin := COORD{
+ X: 0,
+ Y: sr.top - int16(param),
+ }
+
+ char := CHAR_INFO{
+ UnicodeChar: ' ',
+ Attributes: h.attributes,
+ }
+
+ if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) deleteCharacters(param int) error {
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+ return h.scrollLine(param, info.CursorPosition, info)
+}
+
+func (h *windowsAnsiEventHandler) insertCharacters(param int) error {
+ return h.deleteCharacters(-param)
+}
+
+// scrollLine scrolls a line horizontally starting at the provided position by a number of columns.
+func (h *windowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error {
+ // Copy from and clip to the scroll region (full buffer width)
+ scrollRect := SMALL_RECT{
+ Top: position.Y,
+ Bottom: position.Y,
+ Left: position.X,
+ Right: info.Size.X - 1,
+ }
+
+ // Origin to which area should be copied
+ destOrigin := COORD{
+ X: position.X - int16(columns),
+ Y: position.Y,
+ }
+
+ char := CHAR_INFO{
+ UnicodeChar: ' ',
+ Attributes: h.attributes,
+ }
+
+ if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go
new file mode 100644
index 0000000..afa7635
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go
@@ -0,0 +1,9 @@
+// +build windows
+
+package winterm
+
+// AddInRange increments a value by the passed quantity while ensuring the values
+// always remain within the supplied min / max range.
+func addInRange(n int16, increment int16, min int16, max int16) int16 {
+ return ensureInRange(n+increment, min, max)
+}
diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go
new file mode 100644
index 0000000..4d858ed
--- /dev/null
+++ b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go
@@ -0,0 +1,726 @@
+// +build windows
+
+package winterm
+
+import (
+ "bytes"
+ "io/ioutil"
+ "os"
+ "strconv"
+
+ "github.com/Azure/go-ansiterm"
+ "github.com/Sirupsen/logrus"
+)
+
+var logger *logrus.Logger
+
+type windowsAnsiEventHandler struct {
+ fd uintptr
+ file *os.File
+ infoReset *CONSOLE_SCREEN_BUFFER_INFO
+ sr scrollRegion
+ buffer bytes.Buffer
+ attributes uint16
+ inverted bool
+ wrapNext bool
+ drewMarginByte bool
+ originMode bool
+ marginByte byte
+ curInfo *CONSOLE_SCREEN_BUFFER_INFO
+ curPos COORD
+}
+
+func CreateWinEventHandler(fd uintptr, file *os.File) ansiterm.AnsiEventHandler {
+ logFile := ioutil.Discard
+
+ if isDebugEnv := os.Getenv(ansiterm.LogEnv); isDebugEnv == "1" {
+ logFile, _ = os.Create("winEventHandler.log")
+ }
+
+ logger = &logrus.Logger{
+ Out: logFile,
+ Formatter: new(logrus.TextFormatter),
+ Level: logrus.DebugLevel,
+ }
+
+ infoReset, err := GetConsoleScreenBufferInfo(fd)
+ if err != nil {
+ return nil
+ }
+
+ return &windowsAnsiEventHandler{
+ fd: fd,
+ file: file,
+ infoReset: infoReset,
+ attributes: infoReset.Attributes,
+ }
+}
+
+type scrollRegion struct {
+ top int16
+ bottom int16
+}
+
+// simulateLF simulates a LF or CR+LF by scrolling if necessary to handle the
+// current cursor position and scroll region settings, in which case it returns
+// true. If no special handling is necessary, then it does nothing and returns
+// false.
+//
+// In the false case, the caller should ensure that a carriage return
+// and line feed are inserted or that the text is otherwise wrapped.
+func (h *windowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) {
+ if h.wrapNext {
+ if err := h.Flush(); err != nil {
+ return false, err
+ }
+ h.clearWrap()
+ }
+ pos, info, err := h.getCurrentInfo()
+ if err != nil {
+ return false, err
+ }
+ sr := h.effectiveSr(info.Window)
+ if pos.Y == sr.bottom {
+ // Scrolling is necessary. Let Windows automatically scroll if the scrolling region
+ // is the full window.
+ if sr.top == info.Window.Top && sr.bottom == info.Window.Bottom {
+ if includeCR {
+ pos.X = 0
+ h.updatePos(pos)
+ }
+ return false, nil
+ }
+
+ // A custom scroll region is active. Scroll the window manually to simulate
+ // the LF.
+ if err := h.Flush(); err != nil {
+ return false, err
+ }
+ logger.Info("Simulating LF inside scroll region")
+ if err := h.scrollUp(1); err != nil {
+ return false, err
+ }
+ if includeCR {
+ pos.X = 0
+ if err := SetConsoleCursorPosition(h.fd, pos); err != nil {
+ return false, err
+ }
+ }
+ return true, nil
+
+ } else if pos.Y < info.Window.Bottom {
+ // Let Windows handle the LF.
+ pos.Y++
+ if includeCR {
+ pos.X = 0
+ }
+ h.updatePos(pos)
+ return false, nil
+ } else {
+ // The cursor is at the bottom of the screen but outside the scroll
+ // region. Skip the LF.
+ logger.Info("Simulating LF outside scroll region")
+ if includeCR {
+ if err := h.Flush(); err != nil {
+ return false, err
+ }
+ pos.X = 0
+ if err := SetConsoleCursorPosition(h.fd, pos); err != nil {
+ return false, err
+ }
+ }
+ return true, nil
+ }
+}
+
+// executeLF executes a LF without a CR.
+func (h *windowsAnsiEventHandler) executeLF() error {
+ handled, err := h.simulateLF(false)
+ if err != nil {
+ return err
+ }
+ if !handled {
+ // Windows LF will reset the cursor column position. Write the LF
+ // and restore the cursor position.
+ pos, _, err := h.getCurrentInfo()
+ if err != nil {
+ return err
+ }
+ h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED)
+ if pos.X != 0 {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Info("Resetting cursor position for LF without CR")
+ if err := SetConsoleCursorPosition(h.fd, pos); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) Print(b byte) error {
+ if h.wrapNext {
+ h.buffer.WriteByte(h.marginByte)
+ h.clearWrap()
+ if _, err := h.simulateLF(true); err != nil {
+ return err
+ }
+ }
+ pos, info, err := h.getCurrentInfo()
+ if err != nil {
+ return err
+ }
+ if pos.X == info.Size.X-1 {
+ h.wrapNext = true
+ h.marginByte = b
+ } else {
+ pos.X++
+ h.updatePos(pos)
+ h.buffer.WriteByte(b)
+ }
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) Execute(b byte) error {
+ switch b {
+ case ansiterm.ANSI_TAB:
+ logger.Info("Execute(TAB)")
+ // Move to the next tab stop, but preserve auto-wrap if already set.
+ if !h.wrapNext {
+ pos, info, err := h.getCurrentInfo()
+ if err != nil {
+ return err
+ }
+ pos.X = (pos.X + 8) - pos.X%8
+ if pos.X >= info.Size.X {
+ pos.X = info.Size.X - 1
+ }
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ if err := SetConsoleCursorPosition(h.fd, pos); err != nil {
+ return err
+ }
+ }
+ return nil
+
+ case ansiterm.ANSI_BEL:
+ h.buffer.WriteByte(ansiterm.ANSI_BEL)
+ return nil
+
+ case ansiterm.ANSI_BACKSPACE:
+ if h.wrapNext {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ h.clearWrap()
+ }
+ pos, _, err := h.getCurrentInfo()
+ if err != nil {
+ return err
+ }
+ if pos.X > 0 {
+ pos.X--
+ h.updatePos(pos)
+ h.buffer.WriteByte(ansiterm.ANSI_BACKSPACE)
+ }
+ return nil
+
+ case ansiterm.ANSI_VERTICAL_TAB, ansiterm.ANSI_FORM_FEED:
+ // Treat as true LF.
+ return h.executeLF()
+
+ case ansiterm.ANSI_LINE_FEED:
+ // Simulate a CR and LF for now since there is no way in go-ansiterm
+ // to tell if the LF should include CR (and more things break when it's
+ // missing than when it's incorrectly added).
+ handled, err := h.simulateLF(true)
+ if handled || err != nil {
+ return err
+ }
+ return h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED)
+
+ case ansiterm.ANSI_CARRIAGE_RETURN:
+ if h.wrapNext {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ h.clearWrap()
+ }
+ pos, _, err := h.getCurrentInfo()
+ if err != nil {
+ return err
+ }
+ if pos.X != 0 {
+ pos.X = 0
+ h.updatePos(pos)
+ h.buffer.WriteByte(ansiterm.ANSI_CARRIAGE_RETURN)
+ }
+ return nil
+
+ default:
+ return nil
+ }
+}
+
+func (h *windowsAnsiEventHandler) CUU(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("CUU: [%v]", []string{strconv.Itoa(param)})
+ h.clearWrap()
+ return h.moveCursorVertical(-param)
+}
+
+func (h *windowsAnsiEventHandler) CUD(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("CUD: [%v]", []string{strconv.Itoa(param)})
+ h.clearWrap()
+ return h.moveCursorVertical(param)
+}
+
+func (h *windowsAnsiEventHandler) CUF(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("CUF: [%v]", []string{strconv.Itoa(param)})
+ h.clearWrap()
+ return h.moveCursorHorizontal(param)
+}
+
+func (h *windowsAnsiEventHandler) CUB(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("CUB: [%v]", []string{strconv.Itoa(param)})
+ h.clearWrap()
+ return h.moveCursorHorizontal(-param)
+}
+
+func (h *windowsAnsiEventHandler) CNL(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("CNL: [%v]", []string{strconv.Itoa(param)})
+ h.clearWrap()
+ return h.moveCursorLine(param)
+}
+
+func (h *windowsAnsiEventHandler) CPL(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("CPL: [%v]", []string{strconv.Itoa(param)})
+ h.clearWrap()
+ return h.moveCursorLine(-param)
+}
+
+func (h *windowsAnsiEventHandler) CHA(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("CHA: [%v]", []string{strconv.Itoa(param)})
+ h.clearWrap()
+ return h.moveCursorColumn(param)
+}
+
+func (h *windowsAnsiEventHandler) VPA(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("VPA: [[%d]]", param)
+ h.clearWrap()
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+ window := h.getCursorWindow(info)
+ position := info.CursorPosition
+ position.Y = window.Top + int16(param) - 1
+ return h.setCursorPosition(position, window)
+}
+
+func (h *windowsAnsiEventHandler) CUP(row int, col int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("CUP: [[%d %d]]", row, col)
+ h.clearWrap()
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+
+ window := h.getCursorWindow(info)
+ position := COORD{window.Left + int16(col) - 1, window.Top + int16(row) - 1}
+ return h.setCursorPosition(position, window)
+}
+
+func (h *windowsAnsiEventHandler) HVP(row int, col int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("HVP: [[%d %d]]", row, col)
+ h.clearWrap()
+ return h.CUP(row, col)
+}
+
+func (h *windowsAnsiEventHandler) DECTCEM(visible bool) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("DECTCEM: [%v]", []string{strconv.FormatBool(visible)})
+ h.clearWrap()
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) DECOM(enable bool) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("DECOM: [%v]", []string{strconv.FormatBool(enable)})
+ h.clearWrap()
+ h.originMode = enable
+ return h.CUP(1, 1)
+}
+
+func (h *windowsAnsiEventHandler) DECCOLM(use132 bool) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("DECCOLM: [%v]", []string{strconv.FormatBool(use132)})
+ h.clearWrap()
+ if err := h.ED(2); err != nil {
+ return err
+ }
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+ targetWidth := int16(80)
+ if use132 {
+ targetWidth = 132
+ }
+ if info.Size.X < targetWidth {
+ if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil {
+ logger.Info("set buffer failed:", err)
+ return err
+ }
+ }
+ window := info.Window
+ window.Left = 0
+ window.Right = targetWidth - 1
+ if err := SetConsoleWindowInfo(h.fd, true, window); err != nil {
+ logger.Info("set window failed:", err)
+ return err
+ }
+ if info.Size.X > targetWidth {
+ if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil {
+ logger.Info("set buffer failed:", err)
+ return err
+ }
+ }
+ return SetConsoleCursorPosition(h.fd, COORD{0, 0})
+}
+
+func (h *windowsAnsiEventHandler) ED(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("ED: [%v]", []string{strconv.Itoa(param)})
+ h.clearWrap()
+
+ // [J -- Erases from the cursor to the end of the screen, including the cursor position.
+ // [1J -- Erases from the beginning of the screen to the cursor, including the cursor position.
+ // [2J -- Erases the complete display. The cursor does not move.
+ // Notes:
+ // -- Clearing the entire buffer, versus just the Window, works best for Windows Consoles
+
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+
+ var start COORD
+ var end COORD
+
+ switch param {
+ case 0:
+ start = info.CursorPosition
+ end = COORD{info.Size.X - 1, info.Size.Y - 1}
+
+ case 1:
+ start = COORD{0, 0}
+ end = info.CursorPosition
+
+ case 2:
+ start = COORD{0, 0}
+ end = COORD{info.Size.X - 1, info.Size.Y - 1}
+ }
+
+ err = h.clearRange(h.attributes, start, end)
+ if err != nil {
+ return err
+ }
+
+ // If the whole buffer was cleared, move the window to the top while preserving
+ // the window-relative cursor position.
+ if param == 2 {
+ pos := info.CursorPosition
+ window := info.Window
+ pos.Y -= window.Top
+ window.Bottom -= window.Top
+ window.Top = 0
+ if err := SetConsoleCursorPosition(h.fd, pos); err != nil {
+ return err
+ }
+ if err := SetConsoleWindowInfo(h.fd, true, window); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) EL(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("EL: [%v]", strconv.Itoa(param))
+ h.clearWrap()
+
+ // [K -- Erases from the cursor to the end of the line, including the cursor position.
+ // [1K -- Erases from the beginning of the line to the cursor, including the cursor position.
+ // [2K -- Erases the complete line.
+
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+
+ var start COORD
+ var end COORD
+
+ switch param {
+ case 0:
+ start = info.CursorPosition
+ end = COORD{info.Size.X, info.CursorPosition.Y}
+
+ case 1:
+ start = COORD{0, info.CursorPosition.Y}
+ end = info.CursorPosition
+
+ case 2:
+ start = COORD{0, info.CursorPosition.Y}
+ end = COORD{info.Size.X, info.CursorPosition.Y}
+ }
+
+ err = h.clearRange(h.attributes, start, end)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) IL(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("IL: [%v]", strconv.Itoa(param))
+ h.clearWrap()
+ return h.insertLines(param)
+}
+
+func (h *windowsAnsiEventHandler) DL(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("DL: [%v]", strconv.Itoa(param))
+ h.clearWrap()
+ return h.deleteLines(param)
+}
+
+func (h *windowsAnsiEventHandler) ICH(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("ICH: [%v]", strconv.Itoa(param))
+ h.clearWrap()
+ return h.insertCharacters(param)
+}
+
+func (h *windowsAnsiEventHandler) DCH(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("DCH: [%v]", strconv.Itoa(param))
+ h.clearWrap()
+ return h.deleteCharacters(param)
+}
+
+func (h *windowsAnsiEventHandler) SGR(params []int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ strings := []string{}
+ for _, v := range params {
+ strings = append(strings, strconv.Itoa(v))
+ }
+
+ logger.Infof("SGR: [%v]", strings)
+
+ if len(params) <= 0 {
+ h.attributes = h.infoReset.Attributes
+ h.inverted = false
+ } else {
+ for _, attr := range params {
+
+ if attr == ansiterm.ANSI_SGR_RESET {
+ h.attributes = h.infoReset.Attributes
+ h.inverted = false
+ continue
+ }
+
+ h.attributes, h.inverted = collectAnsiIntoWindowsAttributes(h.attributes, h.inverted, h.infoReset.Attributes, int16(attr))
+ }
+ }
+
+ attributes := h.attributes
+ if h.inverted {
+ attributes = invertAttributes(attributes)
+ }
+ err := SetConsoleTextAttribute(h.fd, attributes)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) SU(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("SU: [%v]", []string{strconv.Itoa(param)})
+ h.clearWrap()
+ return h.scrollUp(param)
+}
+
+func (h *windowsAnsiEventHandler) SD(param int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("SD: [%v]", []string{strconv.Itoa(param)})
+ h.clearWrap()
+ return h.scrollDown(param)
+}
+
+func (h *windowsAnsiEventHandler) DA(params []string) error {
+ logger.Infof("DA: [%v]", params)
+ // DA cannot be implemented because it must send data on the VT100 input stream,
+ // which is not available to go-ansiterm.
+ return nil
+}
+
+func (h *windowsAnsiEventHandler) DECSTBM(top int, bottom int) error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Infof("DECSTBM: [%d, %d]", top, bottom)
+
+ // Windows is 0 indexed, Linux is 1 indexed
+ h.sr.top = int16(top - 1)
+ h.sr.bottom = int16(bottom - 1)
+
+ // This command also moves the cursor to the origin.
+ h.clearWrap()
+ return h.CUP(1, 1)
+}
+
+func (h *windowsAnsiEventHandler) RI() error {
+ if err := h.Flush(); err != nil {
+ return err
+ }
+ logger.Info("RI: []")
+ h.clearWrap()
+
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+
+ sr := h.effectiveSr(info.Window)
+ if info.CursorPosition.Y == sr.top {
+ return h.scrollDown(1)
+ }
+
+ return h.moveCursorVertical(-1)
+}
+
+func (h *windowsAnsiEventHandler) IND() error {
+ logger.Info("IND: []")
+ return h.executeLF()
+}
+
+func (h *windowsAnsiEventHandler) Flush() error {
+ h.curInfo = nil
+ if h.buffer.Len() > 0 {
+ logger.Infof("Flush: [%s]", h.buffer.Bytes())
+ if _, err := h.buffer.WriteTo(h.file); err != nil {
+ return err
+ }
+ }
+
+ if h.wrapNext && !h.drewMarginByte {
+ logger.Infof("Flush: drawing margin byte '%c'", h.marginByte)
+
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return err
+ }
+
+ charInfo := []CHAR_INFO{{UnicodeChar: uint16(h.marginByte), Attributes: info.Attributes}}
+ size := COORD{1, 1}
+ position := COORD{0, 0}
+ region := SMALL_RECT{Left: info.CursorPosition.X, Top: info.CursorPosition.Y, Right: info.CursorPosition.X, Bottom: info.CursorPosition.Y}
+ if err := WriteConsoleOutput(h.fd, charInfo, size, position, &region); err != nil {
+ return err
+ }
+ h.drewMarginByte = true
+ }
+ return nil
+}
+
+// cacheConsoleInfo ensures that the current console screen information has been queried
+// since the last call to Flush(). It must be called before accessing h.curInfo or h.curPos.
+func (h *windowsAnsiEventHandler) getCurrentInfo() (COORD, *CONSOLE_SCREEN_BUFFER_INFO, error) {
+ if h.curInfo == nil {
+ info, err := GetConsoleScreenBufferInfo(h.fd)
+ if err != nil {
+ return COORD{}, nil, err
+ }
+ h.curInfo = info
+ h.curPos = info.CursorPosition
+ }
+ return h.curPos, h.curInfo, nil
+}
+
+func (h *windowsAnsiEventHandler) updatePos(pos COORD) {
+ if h.curInfo == nil {
+ panic("failed to call getCurrentInfo before calling updatePos")
+ }
+ h.curPos = pos
+}
+
+// clearWrap clears the state where the cursor is in the margin
+// waiting for the next character before wrapping the line. This must
+// be done before most operations that act on the cursor.
+func (h *windowsAnsiEventHandler) clearWrap() {
+ h.wrapNext = false
+ h.drewMarginByte = false
+}
diff --git a/vendor/github.com/BurntSushi/toml/COPYING b/vendor/github.com/BurntSushi/toml/COPYING
new file mode 100644
index 0000000..5a8e332
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/COPYING
@@ -0,0 +1,14 @@
+ DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
+ Version 2, December 2004
+
+ Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
+
+ Everyone is permitted to copy and distribute verbatim or modified
+ copies of this license document, and changing it is allowed as long
+ as the name is changed.
+
+ DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. You just DO WHAT THE FUCK YOU WANT TO.
+
diff --git a/vendor/github.com/BurntSushi/toml/README.md b/vendor/github.com/BurntSushi/toml/README.md
new file mode 100644
index 0000000..e861c0c
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/README.md
@@ -0,0 +1,220 @@
+## TOML parser and encoder for Go with reflection
+
+TOML stands for Tom's Obvious, Minimal Language. This Go package provides a
+reflection interface similar to Go's standard library `json` and `xml`
+packages. This package also supports the `encoding.TextUnmarshaler` and
+`encoding.TextMarshaler` interfaces so that you can define custom data
+representations. (There is an example of this below.)
+
+Spec: https://github.com/mojombo/toml
+
+Compatible with TOML version
+[v0.2.0](https://github.com/mojombo/toml/blob/master/versions/toml-v0.2.0.md)
+
+Documentation: http://godoc.org/github.com/BurntSushi/toml
+
+Installation:
+
+```bash
+go get github.com/BurntSushi/toml
+```
+
+Try the toml validator:
+
+```bash
+go get github.com/BurntSushi/toml/cmd/tomlv
+tomlv some-toml-file.toml
+```
+
+[![Build status](https://api.travis-ci.org/BurntSushi/toml.png)](https://travis-ci.org/BurntSushi/toml)
+
+
+### Testing
+
+This package passes all tests in
+[toml-test](https://github.com/BurntSushi/toml-test) for both the decoder
+and the encoder.
+
+### Examples
+
+This package works similarly to how the Go standard library handles `XML`
+and `JSON`. Namely, data is loaded into Go values via reflection.
+
+For the simplest example, consider some TOML file as just a list of keys
+and values:
+
+```toml
+Age = 25
+Cats = [ "Cauchy", "Plato" ]
+Pi = 3.14
+Perfection = [ 6, 28, 496, 8128 ]
+DOB = 1987-07-05T05:45:00Z
+```
+
+Which could be defined in Go as:
+
+```go
+type Config struct {
+ Age int
+ Cats []string
+ Pi float64
+ Perfection []int
+ DOB time.Time // requires `import time`
+}
+```
+
+And then decoded with:
+
+```go
+var conf Config
+if _, err := toml.Decode(tomlData, &conf); err != nil {
+ // handle error
+}
+```
+
+You can also use struct tags if your struct field name doesn't map to a TOML
+key value directly:
+
+```toml
+some_key_NAME = "wat"
+```
+
+```go
+type TOML struct {
+ ObscureKey string `toml:"some_key_NAME"`
+}
+```
+
+### Using the `encoding.TextUnmarshaler` interface
+
+Here's an example that automatically parses duration strings into
+`time.Duration` values:
+
+```toml
+[[song]]
+name = "Thunder Road"
+duration = "4m49s"
+
+[[song]]
+name = "Stairway to Heaven"
+duration = "8m03s"
+```
+
+Which can be decoded with:
+
+```go
+type song struct {
+ Name string
+ Duration duration
+}
+type songs struct {
+ Song []song
+}
+var favorites songs
+if _, err := toml.Decode(blob, &favorites); err != nil {
+ log.Fatal(err)
+}
+
+for _, s := range favorites.Song {
+ fmt.Printf("%s (%s)\n", s.Name, s.Duration)
+}
+```
+
+And you'll also need a `duration` type that satisfies the
+`encoding.TextUnmarshaler` interface:
+
+```go
+type duration struct {
+ time.Duration
+}
+
+func (d *duration) UnmarshalText(text []byte) error {
+ var err error
+ d.Duration, err = time.ParseDuration(string(text))
+ return err
+}
+```
+
+### More complex usage
+
+Here's an example of how to load the example from the official spec page:
+
+```toml
+# This is a TOML document. Boom.
+
+title = "TOML Example"
+
+[owner]
+name = "Tom Preston-Werner"
+organization = "GitHub"
+bio = "GitHub Cofounder & CEO\nLikes tater tots and beer."
+dob = 1979-05-27T07:32:00Z # First class dates? Why not?
+
+[database]
+server = "192.168.1.1"
+ports = [ 8001, 8001, 8002 ]
+connection_max = 5000
+enabled = true
+
+[servers]
+
+ # You can indent as you please. Tabs or spaces. TOML don't care.
+ [servers.alpha]
+ ip = "10.0.0.1"
+ dc = "eqdc10"
+
+ [servers.beta]
+ ip = "10.0.0.2"
+ dc = "eqdc10"
+
+[clients]
+data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it
+
+# Line breaks are OK when inside arrays
+hosts = [
+ "alpha",
+ "omega"
+]
+```
+
+And the corresponding Go types are:
+
+```go
+type tomlConfig struct {
+ Title string
+ Owner ownerInfo
+ DB database `toml:"database"`
+ Servers map[string]server
+ Clients clients
+}
+
+type ownerInfo struct {
+ Name string
+ Org string `toml:"organization"`
+ Bio string
+ DOB time.Time
+}
+
+type database struct {
+ Server string
+ Ports []int
+ ConnMax int `toml:"connection_max"`
+ Enabled bool
+}
+
+type server struct {
+ IP string
+ DC string
+}
+
+type clients struct {
+ Data [][]interface{}
+ Hosts []string
+}
+```
+
+Note that a case insensitive match will be tried if an exact match can't be
+found.
+
+A working example of the above can be found in `_examples/example.{go,toml}`.
+
diff --git a/vendor/github.com/BurntSushi/toml/decode.go b/vendor/github.com/BurntSushi/toml/decode.go
new file mode 100644
index 0000000..6c7d398
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/decode.go
@@ -0,0 +1,492 @@
+package toml
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "math"
+ "reflect"
+ "strings"
+ "time"
+)
+
+var e = fmt.Errorf
+
+// Unmarshaler is the interface implemented by objects that can unmarshal a
+// TOML description of themselves.
+type Unmarshaler interface {
+ UnmarshalTOML(interface{}) error
+}
+
+// Unmarshal decodes the contents of `p` in TOML format into a pointer `v`.
+func Unmarshal(p []byte, v interface{}) error {
+ _, err := Decode(string(p), v)
+ return err
+}
+
+// Primitive is a TOML value that hasn't been decoded into a Go value.
+// When using the various `Decode*` functions, the type `Primitive` may
+// be given to any value, and its decoding will be delayed.
+//
+// A `Primitive` value can be decoded using the `PrimitiveDecode` function.
+//
+// The underlying representation of a `Primitive` value is subject to change.
+// Do not rely on it.
+//
+// N.B. Primitive values are still parsed, so using them will only avoid
+// the overhead of reflection. They can be useful when you don't know the
+// exact type of TOML data until run time.
+type Primitive struct {
+ undecoded interface{}
+ context Key
+}
+
+// DEPRECATED!
+//
+// Use MetaData.PrimitiveDecode instead.
+func PrimitiveDecode(primValue Primitive, v interface{}) error {
+ md := MetaData{decoded: make(map[string]bool)}
+ return md.unify(primValue.undecoded, rvalue(v))
+}
+
+// PrimitiveDecode is just like the other `Decode*` functions, except it
+// decodes a TOML value that has already been parsed. Valid primitive values
+// can *only* be obtained from values filled by the decoder functions,
+// including this method. (i.e., `v` may contain more `Primitive`
+// values.)
+//
+// Meta data for primitive values is included in the meta data returned by
+// the `Decode*` functions with one exception: keys returned by the Undecoded
+// method will only reflect keys that were decoded. Namely, any keys hidden
+// behind a Primitive will be considered undecoded. Executing this method will
+// update the undecoded keys in the meta data. (See the example.)
+func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error {
+ md.context = primValue.context
+ defer func() { md.context = nil }()
+ return md.unify(primValue.undecoded, rvalue(v))
+}
+
+// Decode will decode the contents of `data` in TOML format into a pointer
+// `v`.
+//
+// TOML hashes correspond to Go structs or maps. (Dealer's choice. They can be
+// used interchangeably.)
+//
+// TOML arrays of tables correspond to either a slice of structs or a slice
+// of maps.
+//
+// TOML datetimes correspond to Go `time.Time` values.
+//
+// All other TOML types (float, string, int, bool and array) correspond
+// to the obvious Go types.
+//
+// An exception to the above rules is if a type implements the
+// encoding.TextUnmarshaler interface. In this case, any primitive TOML value
+// (floats, strings, integers, booleans and datetimes) will be converted to
+// a byte string and given to the value's UnmarshalText method. See the
+// Unmarshaler example for a demonstration with time duration strings.
+//
+// Key mapping
+//
+// TOML keys can map to either keys in a Go map or field names in a Go
+// struct. The special `toml` struct tag may be used to map TOML keys to
+// struct fields that don't match the key name exactly. (See the example.)
+// A case insensitive match to struct names will be tried if an exact match
+// can't be found.
+//
+// The mapping between TOML values and Go values is loose. That is, there
+// may exist TOML values that cannot be placed into your representation, and
+// there may be parts of your representation that do not correspond to
+// TOML values. This loose mapping can be made stricter by using the IsDefined
+// and/or Undecoded methods on the MetaData returned.
+//
+// This decoder will not handle cyclic types. If a cyclic type is passed,
+// `Decode` will not terminate.
+func Decode(data string, v interface{}) (MetaData, error) {
+ p, err := parse(data)
+ if err != nil {
+ return MetaData{}, err
+ }
+ md := MetaData{
+ p.mapping, p.types, p.ordered,
+ make(map[string]bool, len(p.ordered)), nil,
+ }
+ return md, md.unify(p.mapping, rvalue(v))
+}
+
+// DecodeFile is just like Decode, except it will automatically read the
+// contents of the file at `fpath` and decode it for you.
+func DecodeFile(fpath string, v interface{}) (MetaData, error) {
+ bs, err := ioutil.ReadFile(fpath)
+ if err != nil {
+ return MetaData{}, err
+ }
+ return Decode(string(bs), v)
+}
+
+// DecodeReader is just like Decode, except it will consume all bytes
+// from the reader and decode it for you.
+func DecodeReader(r io.Reader, v interface{}) (MetaData, error) {
+ bs, err := ioutil.ReadAll(r)
+ if err != nil {
+ return MetaData{}, err
+ }
+ return Decode(string(bs), v)
+}
+
+// unify performs a sort of type unification based on the structure of `rv`,
+// which is the client representation.
+//
+// Any type mismatch produces an error. Finding a type that we don't know
+// how to handle produces an unsupported type error.
+func (md *MetaData) unify(data interface{}, rv reflect.Value) error {
+
+ // Special case. Look for a `Primitive` value.
+ if rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() {
+ // Save the undecoded data and the key context into the primitive
+ // value.
+ context := make(Key, len(md.context))
+ copy(context, md.context)
+ rv.Set(reflect.ValueOf(Primitive{
+ undecoded: data,
+ context: context,
+ }))
+ return nil
+ }
+
+ // Special case. Unmarshaler Interface support.
+ if rv.CanAddr() {
+ if v, ok := rv.Addr().Interface().(Unmarshaler); ok {
+ return v.UnmarshalTOML(data)
+ }
+ }
+
+ // Special case. Handle time.Time values specifically.
+ // TODO: Remove this code when we decide to drop support for Go 1.1.
+ // This isn't necessary in Go 1.2 because time.Time satisfies the encoding
+ // interfaces.
+ if rv.Type().AssignableTo(rvalue(time.Time{}).Type()) {
+ return md.unifyDatetime(data, rv)
+ }
+
+ // Special case. Look for a value satisfying the TextUnmarshaler interface.
+ if v, ok := rv.Interface().(TextUnmarshaler); ok {
+ return md.unifyText(data, v)
+ }
+ // BUG(burntsushi)
+ // The behavior here is incorrect whenever a Go type satisfies the
+ // encoding.TextUnmarshaler interface but also corresponds to a TOML
+ // hash or array. In particular, the unmarshaler should only be applied
+ // to primitive TOML values. But at this point, it will be applied to
+ // all kinds of values and produce an incorrect error whenever those values
+ // are hashes or arrays (including arrays of tables).
+
+ k := rv.Kind()
+
+ // laziness
+ if k >= reflect.Int && k <= reflect.Uint64 {
+ return md.unifyInt(data, rv)
+ }
+ switch k {
+ case reflect.Ptr:
+ elem := reflect.New(rv.Type().Elem())
+ err := md.unify(data, reflect.Indirect(elem))
+ if err != nil {
+ return err
+ }
+ rv.Set(elem)
+ return nil
+ case reflect.Struct:
+ return md.unifyStruct(data, rv)
+ case reflect.Map:
+ return md.unifyMap(data, rv)
+ case reflect.Array:
+ return md.unifyArray(data, rv)
+ case reflect.Slice:
+ return md.unifySlice(data, rv)
+ case reflect.String:
+ return md.unifyString(data, rv)
+ case reflect.Bool:
+ return md.unifyBool(data, rv)
+ case reflect.Interface:
+ // we only support empty interfaces.
+ if rv.NumMethod() > 0 {
+ return e("Unsupported type '%s'.", rv.Kind())
+ }
+ return md.unifyAnything(data, rv)
+ case reflect.Float32:
+ fallthrough
+ case reflect.Float64:
+ return md.unifyFloat64(data, rv)
+ }
+ return e("Unsupported type '%s'.", rv.Kind())
+}
+
+func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error {
+ tmap, ok := mapping.(map[string]interface{})
+ if !ok {
+ return mismatch(rv, "map", mapping)
+ }
+
+ for key, datum := range tmap {
+ var f *field
+ fields := cachedTypeFields(rv.Type())
+ for i := range fields {
+ ff := &fields[i]
+ if ff.name == key {
+ f = ff
+ break
+ }
+ if f == nil && strings.EqualFold(ff.name, key) {
+ f = ff
+ }
+ }
+ if f != nil {
+ subv := rv
+ for _, i := range f.index {
+ subv = indirect(subv.Field(i))
+ }
+ if isUnifiable(subv) {
+ md.decoded[md.context.add(key).String()] = true
+ md.context = append(md.context, key)
+ if err := md.unify(datum, subv); err != nil {
+ return e("Type mismatch for '%s.%s': %s",
+ rv.Type().String(), f.name, err)
+ }
+ md.context = md.context[0 : len(md.context)-1]
+ } else if f.name != "" {
+ // Bad user! No soup for you!
+ return e("Field '%s.%s' is unexported, and therefore cannot "+
+ "be loaded with reflection.", rv.Type().String(), f.name)
+ }
+ }
+ }
+ return nil
+}
+
+func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error {
+ tmap, ok := mapping.(map[string]interface{})
+ if !ok {
+ return badtype("map", mapping)
+ }
+ if rv.IsNil() {
+ rv.Set(reflect.MakeMap(rv.Type()))
+ }
+ for k, v := range tmap {
+ md.decoded[md.context.add(k).String()] = true
+ md.context = append(md.context, k)
+
+ rvkey := indirect(reflect.New(rv.Type().Key()))
+ rvval := reflect.Indirect(reflect.New(rv.Type().Elem()))
+ if err := md.unify(v, rvval); err != nil {
+ return err
+ }
+ md.context = md.context[0 : len(md.context)-1]
+
+ rvkey.SetString(k)
+ rv.SetMapIndex(rvkey, rvval)
+ }
+ return nil
+}
+
+func (md *MetaData) unifyArray(data interface{}, rv reflect.Value) error {
+ datav := reflect.ValueOf(data)
+ if datav.Kind() != reflect.Slice {
+ return badtype("slice", data)
+ }
+ sliceLen := datav.Len()
+ if sliceLen != rv.Len() {
+ return e("expected array length %d; got TOML array of length %d",
+ rv.Len(), sliceLen)
+ }
+ return md.unifySliceArray(datav, rv)
+}
+
+func (md *MetaData) unifySlice(data interface{}, rv reflect.Value) error {
+ datav := reflect.ValueOf(data)
+ if datav.Kind() != reflect.Slice {
+ return badtype("slice", data)
+ }
+ sliceLen := datav.Len()
+ if rv.IsNil() {
+ rv.Set(reflect.MakeSlice(rv.Type(), sliceLen, sliceLen))
+ }
+ return md.unifySliceArray(datav, rv)
+}
+
+func (md *MetaData) unifySliceArray(data, rv reflect.Value) error {
+ sliceLen := data.Len()
+ for i := 0; i < sliceLen; i++ {
+ v := data.Index(i).Interface()
+ sliceval := indirect(rv.Index(i))
+ if err := md.unify(v, sliceval); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (md *MetaData) unifyDatetime(data interface{}, rv reflect.Value) error {
+ if _, ok := data.(time.Time); ok {
+ rv.Set(reflect.ValueOf(data))
+ return nil
+ }
+ return badtype("time.Time", data)
+}
+
+func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error {
+ if s, ok := data.(string); ok {
+ rv.SetString(s)
+ return nil
+ }
+ return badtype("string", data)
+}
+
+func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error {
+ if num, ok := data.(float64); ok {
+ switch rv.Kind() {
+ case reflect.Float32:
+ fallthrough
+ case reflect.Float64:
+ rv.SetFloat(num)
+ default:
+ panic("bug")
+ }
+ return nil
+ }
+ return badtype("float", data)
+}
+
+func (md *MetaData) unifyInt(data interface{}, rv reflect.Value) error {
+ if num, ok := data.(int64); ok {
+ if rv.Kind() >= reflect.Int && rv.Kind() <= reflect.Int64 {
+ switch rv.Kind() {
+ case reflect.Int, reflect.Int64:
+ // No bounds checking necessary.
+ case reflect.Int8:
+ if num < math.MinInt8 || num > math.MaxInt8 {
+ return e("Value '%d' is out of range for int8.", num)
+ }
+ case reflect.Int16:
+ if num < math.MinInt16 || num > math.MaxInt16 {
+ return e("Value '%d' is out of range for int16.", num)
+ }
+ case reflect.Int32:
+ if num < math.MinInt32 || num > math.MaxInt32 {
+ return e("Value '%d' is out of range for int32.", num)
+ }
+ }
+ rv.SetInt(num)
+ } else if rv.Kind() >= reflect.Uint && rv.Kind() <= reflect.Uint64 {
+ unum := uint64(num)
+ switch rv.Kind() {
+ case reflect.Uint, reflect.Uint64:
+ // No bounds checking necessary.
+ case reflect.Uint8:
+ if num < 0 || unum > math.MaxUint8 {
+ return e("Value '%d' is out of range for uint8.", num)
+ }
+ case reflect.Uint16:
+ if num < 0 || unum > math.MaxUint16 {
+ return e("Value '%d' is out of range for uint16.", num)
+ }
+ case reflect.Uint32:
+ if num < 0 || unum > math.MaxUint32 {
+ return e("Value '%d' is out of range for uint32.", num)
+ }
+ }
+ rv.SetUint(unum)
+ } else {
+ panic("unreachable")
+ }
+ return nil
+ }
+ return badtype("integer", data)
+}
+
+func (md *MetaData) unifyBool(data interface{}, rv reflect.Value) error {
+ if b, ok := data.(bool); ok {
+ rv.SetBool(b)
+ return nil
+ }
+ return badtype("boolean", data)
+}
+
+func (md *MetaData) unifyAnything(data interface{}, rv reflect.Value) error {
+ rv.Set(reflect.ValueOf(data))
+ return nil
+}
+
+func (md *MetaData) unifyText(data interface{}, v TextUnmarshaler) error {
+ var s string
+ switch sdata := data.(type) {
+ case TextMarshaler:
+ text, err := sdata.MarshalText()
+ if err != nil {
+ return err
+ }
+ s = string(text)
+ case fmt.Stringer:
+ s = sdata.String()
+ case string:
+ s = sdata
+ case bool:
+ s = fmt.Sprintf("%v", sdata)
+ case int64:
+ s = fmt.Sprintf("%d", sdata)
+ case float64:
+ s = fmt.Sprintf("%f", sdata)
+ default:
+ return badtype("primitive (string-like)", data)
+ }
+ if err := v.UnmarshalText([]byte(s)); err != nil {
+ return err
+ }
+ return nil
+}
+
+// rvalue returns a reflect.Value of `v`. All pointers are resolved.
+func rvalue(v interface{}) reflect.Value {
+ return indirect(reflect.ValueOf(v))
+}
+
+// indirect returns the value pointed to by a pointer.
+// Pointers are followed until the value is not a pointer.
+// New values are allocated for each nil pointer.
+//
+// An exception to this rule is if the value satisfies an interface of
+// interest to us (like encoding.TextUnmarshaler).
+func indirect(v reflect.Value) reflect.Value {
+ if v.Kind() != reflect.Ptr {
+ if v.CanAddr() {
+ pv := v.Addr()
+ if _, ok := pv.Interface().(TextUnmarshaler); ok {
+ return pv
+ }
+ }
+ return v
+ }
+ if v.IsNil() {
+ v.Set(reflect.New(v.Type().Elem()))
+ }
+ return indirect(reflect.Indirect(v))
+}
+
+func isUnifiable(rv reflect.Value) bool {
+ if rv.CanSet() {
+ return true
+ }
+ if _, ok := rv.Interface().(TextUnmarshaler); ok {
+ return true
+ }
+ return false
+}
+
+func badtype(expected string, data interface{}) error {
+ return e("Expected %s but found '%T'.", expected, data)
+}
+
+func mismatch(user reflect.Value, expected string, data interface{}) error {
+ return e("Type mismatch for %s. Expected %s but found '%T'.",
+ user.Type().String(), expected, data)
+}
diff --git a/vendor/github.com/BurntSushi/toml/decode_meta.go b/vendor/github.com/BurntSushi/toml/decode_meta.go
new file mode 100644
index 0000000..ef6f545
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/decode_meta.go
@@ -0,0 +1,122 @@
+package toml
+
+import "strings"
+
+// MetaData allows access to meta information about TOML data that may not
+// be inferrable via reflection. In particular, whether a key has been defined
+// and the TOML type of a key.
+type MetaData struct {
+ mapping map[string]interface{}
+ types map[string]tomlType
+ keys []Key
+ decoded map[string]bool
+ context Key // Used only during decoding.
+}
+
+// IsDefined returns true if the key given exists in the TOML data. The key
+// should be specified hierarchially. e.g.,
+//
+// // access the TOML key 'a.b.c'
+// IsDefined("a", "b", "c")
+//
+// IsDefined will return false if an empty key given. Keys are case sensitive.
+func (md *MetaData) IsDefined(key ...string) bool {
+ if len(key) == 0 {
+ return false
+ }
+
+ var hash map[string]interface{}
+ var ok bool
+ var hashOrVal interface{} = md.mapping
+ for _, k := range key {
+ if hash, ok = hashOrVal.(map[string]interface{}); !ok {
+ return false
+ }
+ if hashOrVal, ok = hash[k]; !ok {
+ return false
+ }
+ }
+ return true
+}
+
+// Type returns a string representation of the type of the key specified.
+//
+// Type will return the empty string if given an empty key or a key that
+// does not exist. Keys are case sensitive.
+func (md *MetaData) Type(key ...string) string {
+ fullkey := strings.Join(key, ".")
+ if typ, ok := md.types[fullkey]; ok {
+ return typ.typeString()
+ }
+ return ""
+}
+
+// Key is the type of any TOML key, including key groups. Use (MetaData).Keys
+// to get values of this type.
+type Key []string
+
+func (k Key) String() string {
+ return strings.Join(k, ".")
+}
+
+func (k Key) maybeQuotedAll() string {
+ var ss []string
+ for i := range k {
+ ss = append(ss, k.maybeQuoted(i))
+ }
+ return strings.Join(ss, ".")
+}
+
+func (k Key) maybeQuoted(i int) string {
+ quote := false
+ for _, c := range k[i] {
+ if !isBareKeyChar(c) {
+ quote = true
+ break
+ }
+ }
+ if quote {
+ return "\"" + strings.Replace(k[i], "\"", "\\\"", -1) + "\""
+ } else {
+ return k[i]
+ }
+}
+
+func (k Key) add(piece string) Key {
+ newKey := make(Key, len(k)+1)
+ copy(newKey, k)
+ newKey[len(k)] = piece
+ return newKey
+}
+
+// Keys returns a slice of every key in the TOML data, including key groups.
+// Each key is itself a slice, where the first element is the top of the
+// hierarchy and the last is the most specific.
+//
+// The list will have the same order as the keys appeared in the TOML data.
+//
+// All keys returned are non-empty.
+func (md *MetaData) Keys() []Key {
+ return md.keys
+}
+
+// Undecoded returns all keys that have not been decoded in the order in which
+// they appear in the original TOML document.
+//
+// This includes keys that haven't been decoded because of a Primitive value.
+// Once the Primitive value is decoded, the keys will be considered decoded.
+//
+// Also note that decoding into an empty interface will result in no decoding,
+// and so no keys will be considered decoded.
+//
+// In this sense, the Undecoded keys correspond to keys in the TOML document
+// that do not have a concrete type in your representation.
+func (md *MetaData) Undecoded() []Key {
+ undecoded := make([]Key, 0, len(md.keys))
+ for _, key := range md.keys {
+ if !md.decoded[key.String()] {
+ undecoded = append(undecoded, key)
+ }
+ }
+ return undecoded
+}
diff --git a/vendor/github.com/BurntSushi/toml/doc.go b/vendor/github.com/BurntSushi/toml/doc.go
new file mode 100644
index 0000000..fe26800
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/doc.go
@@ -0,0 +1,27 @@
+/*
+Package toml provides facilities for decoding and encoding TOML configuration
+files via reflection. There is also support for delaying decoding with
+the Primitive type, and querying the set of keys in a TOML document with the
+MetaData type.
+
+The specification implemented: https://github.com/mojombo/toml
+
+The sub-command github.com/BurntSushi/toml/cmd/tomlv can be used to verify
+whether a file is a valid TOML document. It can also be used to print the
+type of each key in a TOML document.
+
+Testing
+
+There are two important types of tests used for this package. The first is
+contained inside '*_test.go' files and uses the standard Go unit testing
+framework. These tests are primarily devoted to holistically testing the
+decoder and encoder.
+
+The second type of testing is used to verify the implementation's adherence
+to the TOML specification. These tests have been factored into their own
+project: https://github.com/BurntSushi/toml-test
+
+The reason the tests are in a separate project is so that they can be used by
+any implementation of TOML. Namely, it is language agnostic.
+*/
+package toml
diff --git a/vendor/github.com/BurntSushi/toml/encode.go b/vendor/github.com/BurntSushi/toml/encode.go
new file mode 100644
index 0000000..64e8c47
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/encode.go
@@ -0,0 +1,496 @@
+package toml
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+type tomlEncodeError struct{ error }
+
+var (
+ errArrayMixedElementTypes = errors.New(
+ "can't encode array with mixed element types")
+ errArrayNilElement = errors.New(
+ "can't encode array with nil element")
+ errNonString = errors.New(
+ "can't encode a map with non-string key type")
+ errAnonNonStruct = errors.New(
+ "can't encode an anonymous field that is not a struct")
+ errArrayNoTable = errors.New(
+ "TOML array element can't contain a table")
+ errNoKey = errors.New(
+ "top-level values must be a Go map or struct")
+ errAnything = errors.New("") // used in testing
+)
+
+var quotedReplacer = strings.NewReplacer(
+ "\t", "\\t",
+ "\n", "\\n",
+ "\r", "\\r",
+ "\"", "\\\"",
+ "\\", "\\\\",
+)
+
+// Encoder controls the encoding of Go values to a TOML document to some
+// io.Writer.
+//
+// The indentation level can be controlled with the Indent field.
+type Encoder struct {
+ // A single indentation level. By default it is two spaces.
+ Indent string
+
+ // hasWritten is whether we have written any output to w yet.
+ hasWritten bool
+ w *bufio.Writer
+}
+
+// NewEncoder returns a TOML encoder that encodes Go values to the io.Writer
+// given. By default, a single indentation level is 2 spaces.
+func NewEncoder(w io.Writer) *Encoder {
+ return &Encoder{
+ w: bufio.NewWriter(w),
+ Indent: " ",
+ }
+}
+
+// Encode writes a TOML representation of the Go value to the underlying
+// io.Writer. If the value given cannot be encoded to a valid TOML document,
+// then an error is returned.
+//
+// The mapping between Go values and TOML values should be precisely the same
+// as for the Decode* functions. Similarly, the TextMarshaler interface is
+// supported by encoding the resulting bytes as strings. (If you want to write
+// arbitrary binary data then you will need to use something like base64 since
+// TOML does not have any binary types.)
+//
+// When encoding TOML hashes (i.e., Go maps or structs), keys without any
+// sub-hashes are encoded first.
+//
+// If a Go map is encoded, then its keys are sorted alphabetically for
+// deterministic output. More control over this behavior may be provided if
+// there is demand for it.
+//
+// Encoding Go values without a corresponding TOML representation---like map
+// types with non-string keys---will cause an error to be returned. Similarly
+// for mixed arrays/slices, arrays/slices with nil elements, embedded
+// non-struct types and nested slices containing maps or structs.
+// (e.g., [][]map[string]string is not allowed but []map[string]string is OK
+// and so is []map[string][]string.)
+func (enc *Encoder) Encode(v interface{}) error {
+ rv := eindirect(reflect.ValueOf(v))
+ if err := enc.safeEncode(Key([]string{}), rv); err != nil {
+ return err
+ }
+ return enc.w.Flush()
+}
+
+func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ if terr, ok := r.(tomlEncodeError); ok {
+ err = terr.error
+ return
+ }
+ panic(r)
+ }
+ }()
+ enc.encode(key, rv)
+ return nil
+}
+
+func (enc *Encoder) encode(key Key, rv reflect.Value) {
+ // Special case. Time needs to be in ISO8601 format.
+ // Special case. If we can marshal the type to text, then we used that.
+ // Basically, this prevents the encoder for handling these types as
+ // generic structs (or whatever the underlying type of a TextMarshaler is).
+ switch rv.Interface().(type) {
+ case time.Time, TextMarshaler:
+ enc.keyEqElement(key, rv)
+ return
+ }
+
+ k := rv.Kind()
+ switch k {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
+ reflect.Int64,
+ reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
+ reflect.Uint64,
+ reflect.Float32, reflect.Float64, reflect.String, reflect.Bool:
+ enc.keyEqElement(key, rv)
+ case reflect.Array, reflect.Slice:
+ if typeEqual(tomlArrayHash, tomlTypeOfGo(rv)) {
+ enc.eArrayOfTables(key, rv)
+ } else {
+ enc.keyEqElement(key, rv)
+ }
+ case reflect.Interface:
+ if rv.IsNil() {
+ return
+ }
+ enc.encode(key, rv.Elem())
+ case reflect.Map:
+ if rv.IsNil() {
+ return
+ }
+ enc.eTable(key, rv)
+ case reflect.Ptr:
+ if rv.IsNil() {
+ return
+ }
+ enc.encode(key, rv.Elem())
+ case reflect.Struct:
+ enc.eTable(key, rv)
+ default:
+ panic(e("Unsupported type for key '%s': %s", key, k))
+ }
+}
+
+// eElement encodes any value that can be an array element (primitives and
+// arrays).
+func (enc *Encoder) eElement(rv reflect.Value) {
+ switch v := rv.Interface().(type) {
+ case time.Time:
+ // Special case time.Time as a primitive. Has to come before
+ // TextMarshaler below because time.Time implements
+ // encoding.TextMarshaler, but we need to always use UTC.
+ enc.wf(v.In(time.FixedZone("UTC", 0)).Format("2006-01-02T15:04:05Z"))
+ return
+ case TextMarshaler:
+ // Special case. Use text marshaler if it's available for this value.
+ if s, err := v.MarshalText(); err != nil {
+ encPanic(err)
+ } else {
+ enc.writeQuoted(string(s))
+ }
+ return
+ }
+ switch rv.Kind() {
+ case reflect.Bool:
+ enc.wf(strconv.FormatBool(rv.Bool()))
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
+ reflect.Int64:
+ enc.wf(strconv.FormatInt(rv.Int(), 10))
+ case reflect.Uint, reflect.Uint8, reflect.Uint16,
+ reflect.Uint32, reflect.Uint64:
+ enc.wf(strconv.FormatUint(rv.Uint(), 10))
+ case reflect.Float32:
+ enc.wf(floatAddDecimal(strconv.FormatFloat(rv.Float(), 'f', -1, 32)))
+ case reflect.Float64:
+ enc.wf(floatAddDecimal(strconv.FormatFloat(rv.Float(), 'f', -1, 64)))
+ case reflect.Array, reflect.Slice:
+ enc.eArrayOrSliceElement(rv)
+ case reflect.Interface:
+ enc.eElement(rv.Elem())
+ case reflect.String:
+ enc.writeQuoted(rv.String())
+ default:
+ panic(e("Unexpected primitive type: %s", rv.Kind()))
+ }
+}
+
+// By the TOML spec, all floats must have a decimal with at least one
+// number on either side.
+func floatAddDecimal(fstr string) string {
+ if !strings.Contains(fstr, ".") {
+ return fstr + ".0"
+ }
+ return fstr
+}
+
+func (enc *Encoder) writeQuoted(s string) {
+ enc.wf("\"%s\"", quotedReplacer.Replace(s))
+}
+
+func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) {
+ length := rv.Len()
+ enc.wf("[")
+ for i := 0; i < length; i++ {
+ elem := rv.Index(i)
+ enc.eElement(elem)
+ if i != length-1 {
+ enc.wf(", ")
+ }
+ }
+ enc.wf("]")
+}
+
+func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) {
+ if len(key) == 0 {
+ encPanic(errNoKey)
+ }
+ for i := 0; i < rv.Len(); i++ {
+ trv := rv.Index(i)
+ if isNil(trv) {
+ continue
+ }
+ panicIfInvalidKey(key)
+ enc.newline()
+ enc.wf("%s[[%s]]", enc.indentStr(key), key.maybeQuotedAll())
+ enc.newline()
+ enc.eMapOrStruct(key, trv)
+ }
+}
+
+func (enc *Encoder) eTable(key Key, rv reflect.Value) {
+ panicIfInvalidKey(key)
+ if len(key) == 1 {
+ // Output an extra new line between top-level tables.
+ // (The newline isn't written if nothing else has been written though.)
+ enc.newline()
+ }
+ if len(key) > 0 {
+ enc.wf("%s[%s]", enc.indentStr(key), key.maybeQuotedAll())
+ enc.newline()
+ }
+ enc.eMapOrStruct(key, rv)
+}
+
+func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value) {
+ switch rv := eindirect(rv); rv.Kind() {
+ case reflect.Map:
+ enc.eMap(key, rv)
+ case reflect.Struct:
+ enc.eStruct(key, rv)
+ default:
+ panic("eTable: unhandled reflect.Value Kind: " + rv.Kind().String())
+ }
+}
+
+func (enc *Encoder) eMap(key Key, rv reflect.Value) {
+ rt := rv.Type()
+ if rt.Key().Kind() != reflect.String {
+ encPanic(errNonString)
+ }
+
+ // Sort keys so that we have deterministic output. And write keys directly
+ // underneath this key first, before writing sub-structs or sub-maps.
+ var mapKeysDirect, mapKeysSub []string
+ for _, mapKey := range rv.MapKeys() {
+ k := mapKey.String()
+ if typeIsHash(tomlTypeOfGo(rv.MapIndex(mapKey))) {
+ mapKeysSub = append(mapKeysSub, k)
+ } else {
+ mapKeysDirect = append(mapKeysDirect, k)
+ }
+ }
+
+ var writeMapKeys = func(mapKeys []string) {
+ sort.Strings(mapKeys)
+ for _, mapKey := range mapKeys {
+ mrv := rv.MapIndex(reflect.ValueOf(mapKey))
+ if isNil(mrv) {
+ // Don't write anything for nil fields.
+ continue
+ }
+ enc.encode(key.add(mapKey), mrv)
+ }
+ }
+ writeMapKeys(mapKeysDirect)
+ writeMapKeys(mapKeysSub)
+}
+
+func (enc *Encoder) eStruct(key Key, rv reflect.Value) {
+ // Write keys for fields directly under this key first, because if we write
+ // a field that creates a new table, then all keys under it will be in that
+ // table (not the one we're writing here).
+ rt := rv.Type()
+ var fieldsDirect, fieldsSub [][]int
+ var addFields func(rt reflect.Type, rv reflect.Value, start []int)
+ addFields = func(rt reflect.Type, rv reflect.Value, start []int) {
+ for i := 0; i < rt.NumField(); i++ {
+ f := rt.Field(i)
+ // skip unexporded fields
+ if f.PkgPath != "" {
+ continue
+ }
+ frv := rv.Field(i)
+ if f.Anonymous {
+ frv := eindirect(frv)
+ t := frv.Type()
+ if t.Kind() != reflect.Struct {
+ encPanic(errAnonNonStruct)
+ }
+ addFields(t, frv, f.Index)
+ } else if typeIsHash(tomlTypeOfGo(frv)) {
+ fieldsSub = append(fieldsSub, append(start, f.Index...))
+ } else {
+ fieldsDirect = append(fieldsDirect, append(start, f.Index...))
+ }
+ }
+ }
+ addFields(rt, rv, nil)
+
+ var writeFields = func(fields [][]int) {
+ for _, fieldIndex := range fields {
+ sft := rt.FieldByIndex(fieldIndex)
+ sf := rv.FieldByIndex(fieldIndex)
+ if isNil(sf) {
+ // Don't write anything for nil fields.
+ continue
+ }
+
+ keyName := sft.Tag.Get("toml")
+ if keyName == "-" {
+ continue
+ }
+ if keyName == "" {
+ keyName = sft.Name
+ }
+ enc.encode(key.add(keyName), sf)
+ }
+ }
+ writeFields(fieldsDirect)
+ writeFields(fieldsSub)
+}
+
+// tomlTypeName returns the TOML type name of the Go value's type. It is
+// used to determine whether the types of array elements are mixed (which is
+// forbidden). If the Go value is nil, then it is illegal for it to be an array
+// element, and valueIsNil is returned as true.
+
+// Returns the TOML type of a Go value. The type may be `nil`, which means
+// no concrete TOML type could be found.
+func tomlTypeOfGo(rv reflect.Value) tomlType {
+ if isNil(rv) || !rv.IsValid() {
+ return nil
+ }
+ switch rv.Kind() {
+ case reflect.Bool:
+ return tomlBool
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
+ reflect.Int64,
+ reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
+ reflect.Uint64:
+ return tomlInteger
+ case reflect.Float32, reflect.Float64:
+ return tomlFloat
+ case reflect.Array, reflect.Slice:
+ if typeEqual(tomlHash, tomlArrayType(rv)) {
+ return tomlArrayHash
+ } else {
+ return tomlArray
+ }
+ case reflect.Ptr, reflect.Interface:
+ return tomlTypeOfGo(rv.Elem())
+ case reflect.String:
+ return tomlString
+ case reflect.Map:
+ return tomlHash
+ case reflect.Struct:
+ switch rv.Interface().(type) {
+ case time.Time:
+ return tomlDatetime
+ case TextMarshaler:
+ return tomlString
+ default:
+ return tomlHash
+ }
+ default:
+ panic("unexpected reflect.Kind: " + rv.Kind().String())
+ }
+}
+
+// tomlArrayType returns the element type of a TOML array. The type returned
+// may be nil if it cannot be determined (e.g., a nil slice or a zero length
+// slize). This function may also panic if it finds a type that cannot be
+// expressed in TOML (such as nil elements, heterogeneous arrays or directly
+// nested arrays of tables).
+func tomlArrayType(rv reflect.Value) tomlType {
+ if isNil(rv) || !rv.IsValid() || rv.Len() == 0 {
+ return nil
+ }
+ firstType := tomlTypeOfGo(rv.Index(0))
+ if firstType == nil {
+ encPanic(errArrayNilElement)
+ }
+
+ rvlen := rv.Len()
+ for i := 1; i < rvlen; i++ {
+ elem := rv.Index(i)
+ switch elemType := tomlTypeOfGo(elem); {
+ case elemType == nil:
+ encPanic(errArrayNilElement)
+ case !typeEqual(firstType, elemType):
+ encPanic(errArrayMixedElementTypes)
+ }
+ }
+ // If we have a nested array, then we must make sure that the nested
+ // array contains ONLY primitives.
+ // This checks arbitrarily nested arrays.
+ if typeEqual(firstType, tomlArray) || typeEqual(firstType, tomlArrayHash) {
+ nest := tomlArrayType(eindirect(rv.Index(0)))
+ if typeEqual(nest, tomlHash) || typeEqual(nest, tomlArrayHash) {
+ encPanic(errArrayNoTable)
+ }
+ }
+ return firstType
+}
+
+func (enc *Encoder) newline() {
+ if enc.hasWritten {
+ enc.wf("\n")
+ }
+}
+
+func (enc *Encoder) keyEqElement(key Key, val reflect.Value) {
+ if len(key) == 0 {
+ encPanic(errNoKey)
+ }
+ panicIfInvalidKey(key)
+ enc.wf("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1))
+ enc.eElement(val)
+ enc.newline()
+}
+
+func (enc *Encoder) wf(format string, v ...interface{}) {
+ if _, err := fmt.Fprintf(enc.w, format, v...); err != nil {
+ encPanic(err)
+ }
+ enc.hasWritten = true
+}
+
+func (enc *Encoder) indentStr(key Key) string {
+ return strings.Repeat(enc.Indent, len(key)-1)
+}
+
+func encPanic(err error) {
+ panic(tomlEncodeError{err})
+}
+
+func eindirect(v reflect.Value) reflect.Value {
+ switch v.Kind() {
+ case reflect.Ptr, reflect.Interface:
+ return eindirect(v.Elem())
+ default:
+ return v
+ }
+}
+
+func isNil(rv reflect.Value) bool {
+ switch rv.Kind() {
+ case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ return rv.IsNil()
+ default:
+ return false
+ }
+}
+
+func panicIfInvalidKey(key Key) {
+ for _, k := range key {
+ if len(k) == 0 {
+ encPanic(e("Key '%s' is not a valid table name. Key names "+
+ "cannot be empty.", key.maybeQuotedAll()))
+ }
+ }
+}
+
+func isValidKeyName(s string) bool {
+ return len(s) != 0
+}
diff --git a/vendor/github.com/BurntSushi/toml/encoding_types.go b/vendor/github.com/BurntSushi/toml/encoding_types.go
new file mode 100644
index 0000000..d36e1dd
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/encoding_types.go
@@ -0,0 +1,19 @@
+// +build go1.2
+
+package toml
+
+// In order to support Go 1.1, we define our own TextMarshaler and
+// TextUnmarshaler types. For Go 1.2+, we just alias them with the
+// standard library interfaces.
+
+import (
+ "encoding"
+)
+
+// TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here
+// so that Go 1.1 can be supported.
+type TextMarshaler encoding.TextMarshaler
+
+// TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined
+// here so that Go 1.1 can be supported.
+type TextUnmarshaler encoding.TextUnmarshaler
diff --git a/vendor/github.com/BurntSushi/toml/encoding_types_1.1.go b/vendor/github.com/BurntSushi/toml/encoding_types_1.1.go
new file mode 100644
index 0000000..e8d503d
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/encoding_types_1.1.go
@@ -0,0 +1,18 @@
+// +build !go1.2
+
+package toml
+
+// These interfaces were introduced in Go 1.2, so we add them manually when
+// compiling for Go 1.1.
+
+// TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here
+// so that Go 1.1 can be supported.
+type TextMarshaler interface {
+ MarshalText() (text []byte, err error)
+}
+
+// TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined
+// here so that Go 1.1 can be supported.
+type TextUnmarshaler interface {
+ UnmarshalText(text []byte) error
+}
diff --git a/vendor/github.com/BurntSushi/toml/lex.go b/vendor/github.com/BurntSushi/toml/lex.go
new file mode 100644
index 0000000..2191228
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/lex.go
@@ -0,0 +1,874 @@
+package toml
+
+import (
+ "fmt"
+ "strings"
+ "unicode/utf8"
+)
+
+type itemType int
+
+const (
+ itemError itemType = iota
+ itemNIL // used in the parser to indicate no type
+ itemEOF
+ itemText
+ itemString
+ itemRawString
+ itemMultilineString
+ itemRawMultilineString
+ itemBool
+ itemInteger
+ itemFloat
+ itemDatetime
+ itemArray // the start of an array
+ itemArrayEnd
+ itemTableStart
+ itemTableEnd
+ itemArrayTableStart
+ itemArrayTableEnd
+ itemKeyStart
+ itemCommentStart
+)
+
+const (
+ eof = 0
+ tableStart = '['
+ tableEnd = ']'
+ arrayTableStart = '['
+ arrayTableEnd = ']'
+ tableSep = '.'
+ keySep = '='
+ arrayStart = '['
+ arrayEnd = ']'
+ arrayValTerm = ','
+ commentStart = '#'
+ stringStart = '"'
+ stringEnd = '"'
+ rawStringStart = '\''
+ rawStringEnd = '\''
+)
+
+type stateFn func(lx *lexer) stateFn
+
+type lexer struct {
+ input string
+ start int
+ pos int
+ width int
+ line int
+ state stateFn
+ items chan item
+
+ // A stack of state functions used to maintain context.
+ // The idea is to reuse parts of the state machine in various places.
+ // For example, values can appear at the top level or within arbitrarily
+ // nested arrays. The last state on the stack is used after a value has
+ // been lexed. Similarly for comments.
+ stack []stateFn
+}
+
+type item struct {
+ typ itemType
+ val string
+ line int
+}
+
+func (lx *lexer) nextItem() item {
+ for {
+ select {
+ case item := <-lx.items:
+ return item
+ default:
+ lx.state = lx.state(lx)
+ }
+ }
+}
+
+func lex(input string) *lexer {
+ lx := &lexer{
+ input: input + "\n",
+ state: lexTop,
+ line: 1,
+ items: make(chan item, 10),
+ stack: make([]stateFn, 0, 10),
+ }
+ return lx
+}
+
+func (lx *lexer) push(state stateFn) {
+ lx.stack = append(lx.stack, state)
+}
+
+func (lx *lexer) pop() stateFn {
+ if len(lx.stack) == 0 {
+ return lx.errorf("BUG in lexer: no states to pop.")
+ }
+ last := lx.stack[len(lx.stack)-1]
+ lx.stack = lx.stack[0 : len(lx.stack)-1]
+ return last
+}
+
+func (lx *lexer) current() string {
+ return lx.input[lx.start:lx.pos]
+}
+
+func (lx *lexer) emit(typ itemType) {
+ lx.items <- item{typ, lx.current(), lx.line}
+ lx.start = lx.pos
+}
+
+func (lx *lexer) emitTrim(typ itemType) {
+ lx.items <- item{typ, strings.TrimSpace(lx.current()), lx.line}
+ lx.start = lx.pos
+}
+
+func (lx *lexer) next() (r rune) {
+ if lx.pos >= len(lx.input) {
+ lx.width = 0
+ return eof
+ }
+
+ if lx.input[lx.pos] == '\n' {
+ lx.line++
+ }
+ r, lx.width = utf8.DecodeRuneInString(lx.input[lx.pos:])
+ lx.pos += lx.width
+ return r
+}
+
+// ignore skips over the pending input before this point.
+func (lx *lexer) ignore() {
+ lx.start = lx.pos
+}
+
+// backup steps back one rune. Can be called only once per call of next.
+func (lx *lexer) backup() {
+ lx.pos -= lx.width
+ if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' {
+ lx.line--
+ }
+}
+
+// accept consumes the next rune if it's equal to `valid`.
+func (lx *lexer) accept(valid rune) bool {
+ if lx.next() == valid {
+ return true
+ }
+ lx.backup()
+ return false
+}
+
+// peek returns but does not consume the next rune in the input.
+func (lx *lexer) peek() rune {
+ r := lx.next()
+ lx.backup()
+ return r
+}
+
+// errorf stops all lexing by emitting an error and returning `nil`.
+// Note that any value that is a character is escaped if it's a special
+// character (new lines, tabs, etc.).
+func (lx *lexer) errorf(format string, values ...interface{}) stateFn {
+ lx.items <- item{
+ itemError,
+ fmt.Sprintf(format, values...),
+ lx.line,
+ }
+ return nil
+}
+
+// lexTop consumes elements at the top level of TOML data.
+func lexTop(lx *lexer) stateFn {
+ r := lx.next()
+ if isWhitespace(r) || isNL(r) {
+ return lexSkip(lx, lexTop)
+ }
+
+ switch r {
+ case commentStart:
+ lx.push(lexTop)
+ return lexCommentStart
+ case tableStart:
+ return lexTableStart
+ case eof:
+ if lx.pos > lx.start {
+ return lx.errorf("Unexpected EOF.")
+ }
+ lx.emit(itemEOF)
+ return nil
+ }
+
+ // At this point, the only valid item can be a key, so we back up
+ // and let the key lexer do the rest.
+ lx.backup()
+ lx.push(lexTopEnd)
+ return lexKeyStart
+}
+
+// lexTopEnd is entered whenever a top-level item has been consumed. (A value
+// or a table.) It must see only whitespace, and will turn back to lexTop
+// upon a new line. If it sees EOF, it will quit the lexer successfully.
+func lexTopEnd(lx *lexer) stateFn {
+ r := lx.next()
+ switch {
+ case r == commentStart:
+ // a comment will read to a new line for us.
+ lx.push(lexTop)
+ return lexCommentStart
+ case isWhitespace(r):
+ return lexTopEnd
+ case isNL(r):
+ lx.ignore()
+ return lexTop
+ case r == eof:
+ lx.ignore()
+ return lexTop
+ }
+ return lx.errorf("Expected a top-level item to end with a new line, "+
+ "comment or EOF, but got %q instead.", r)
+}
+
+// lexTable lexes the beginning of a table. Namely, it makes sure that
+// it starts with a character other than '.' and ']'.
+// It assumes that '[' has already been consumed.
+// It also handles the case that this is an item in an array of tables.
+// e.g., '[[name]]'.
+func lexTableStart(lx *lexer) stateFn {
+ if lx.peek() == arrayTableStart {
+ lx.next()
+ lx.emit(itemArrayTableStart)
+ lx.push(lexArrayTableEnd)
+ } else {
+ lx.emit(itemTableStart)
+ lx.push(lexTableEnd)
+ }
+ return lexTableNameStart
+}
+
+func lexTableEnd(lx *lexer) stateFn {
+ lx.emit(itemTableEnd)
+ return lexTopEnd
+}
+
+func lexArrayTableEnd(lx *lexer) stateFn {
+ if r := lx.next(); r != arrayTableEnd {
+ return lx.errorf("Expected end of table array name delimiter %q, "+
+ "but got %q instead.", arrayTableEnd, r)
+ }
+ lx.emit(itemArrayTableEnd)
+ return lexTopEnd
+}
+
+func lexTableNameStart(lx *lexer) stateFn {
+ switch r := lx.peek(); {
+ case r == tableEnd || r == eof:
+ return lx.errorf("Unexpected end of table name. (Table names cannot " +
+ "be empty.)")
+ case r == tableSep:
+ return lx.errorf("Unexpected table separator. (Table names cannot " +
+ "be empty.)")
+ case r == stringStart || r == rawStringStart:
+ lx.ignore()
+ lx.push(lexTableNameEnd)
+ return lexValue // reuse string lexing
+ case isWhitespace(r):
+ return lexTableNameStart
+ default:
+ return lexBareTableName
+ }
+}
+
+// lexTableName lexes the name of a table. It assumes that at least one
+// valid character for the table has already been read.
+func lexBareTableName(lx *lexer) stateFn {
+ switch r := lx.next(); {
+ case isBareKeyChar(r):
+ return lexBareTableName
+ case r == tableSep || r == tableEnd:
+ lx.backup()
+ lx.emitTrim(itemText)
+ return lexTableNameEnd
+ default:
+ return lx.errorf("Bare keys cannot contain %q.", r)
+ }
+}
+
+// lexTableNameEnd reads the end of a piece of a table name, optionally
+// consuming whitespace.
+func lexTableNameEnd(lx *lexer) stateFn {
+ switch r := lx.next(); {
+ case isWhitespace(r):
+ return lexTableNameEnd
+ case r == tableSep:
+ lx.ignore()
+ return lexTableNameStart
+ case r == tableEnd:
+ return lx.pop()
+ default:
+ return lx.errorf("Expected '.' or ']' to end table name, but got %q "+
+ "instead.", r)
+ }
+}
+
+// lexKeyStart consumes a key name up until the first non-whitespace character.
+// lexKeyStart will ignore whitespace.
+func lexKeyStart(lx *lexer) stateFn {
+ r := lx.peek()
+ switch {
+ case r == keySep:
+ return lx.errorf("Unexpected key separator %q.", keySep)
+ case isWhitespace(r) || isNL(r):
+ lx.next()
+ return lexSkip(lx, lexKeyStart)
+ case r == stringStart || r == rawStringStart:
+ lx.ignore()
+ lx.emit(itemKeyStart)
+ lx.push(lexKeyEnd)
+ return lexValue // reuse string lexing
+ default:
+ lx.ignore()
+ lx.emit(itemKeyStart)
+ return lexBareKey
+ }
+}
+
+// lexBareKey consumes the text of a bare key. Assumes that the first character
+// (which is not whitespace) has not yet been consumed.
+func lexBareKey(lx *lexer) stateFn {
+ switch r := lx.next(); {
+ case isBareKeyChar(r):
+ return lexBareKey
+ case isWhitespace(r):
+ lx.emitTrim(itemText)
+ return lexKeyEnd
+ case r == keySep:
+ lx.backup()
+ lx.emitTrim(itemText)
+ return lexKeyEnd
+ default:
+ return lx.errorf("Bare keys cannot contain %q.", r)
+ }
+}
+
+// lexKeyEnd consumes the end of a key and trims whitespace (up to the key
+// separator).
+func lexKeyEnd(lx *lexer) stateFn {
+ switch r := lx.next(); {
+ case r == keySep:
+ return lexSkip(lx, lexValue)
+ case isWhitespace(r):
+ return lexSkip(lx, lexKeyEnd)
+ default:
+ return lx.errorf("Expected key separator %q, but got %q instead.",
+ keySep, r)
+ }
+}
+
+// lexValue starts the consumption of a value anywhere a value is expected.
+// lexValue will ignore whitespace.
+// After a value is lexed, the last state on the next is popped and returned.
+func lexValue(lx *lexer) stateFn {
+ // We allow whitespace to precede a value, but NOT new lines.
+ // In array syntax, the array states are responsible for ignoring new
+ // lines.
+ r := lx.next()
+ if isWhitespace(r) {
+ return lexSkip(lx, lexValue)
+ }
+
+ switch {
+ case r == arrayStart:
+ lx.ignore()
+ lx.emit(itemArray)
+ return lexArrayValue
+ case r == stringStart:
+ if lx.accept(stringStart) {
+ if lx.accept(stringStart) {
+ lx.ignore() // Ignore """
+ return lexMultilineString
+ }
+ lx.backup()
+ }
+ lx.ignore() // ignore the '"'
+ return lexString
+ case r == rawStringStart:
+ if lx.accept(rawStringStart) {
+ if lx.accept(rawStringStart) {
+ lx.ignore() // Ignore """
+ return lexMultilineRawString
+ }
+ lx.backup()
+ }
+ lx.ignore() // ignore the "'"
+ return lexRawString
+ case r == 't':
+ return lexTrue
+ case r == 'f':
+ return lexFalse
+ case r == '-':
+ return lexNumberStart
+ case isDigit(r):
+ lx.backup() // avoid an extra state and use the same as above
+ return lexNumberOrDateStart
+ case r == '.': // special error case, be kind to users
+ return lx.errorf("Floats must start with a digit, not '.'.")
+ }
+ return lx.errorf("Expected value but found %q instead.", r)
+}
+
+// lexArrayValue consumes one value in an array. It assumes that '[' or ','
+// have already been consumed. All whitespace and new lines are ignored.
+func lexArrayValue(lx *lexer) stateFn {
+ r := lx.next()
+ switch {
+ case isWhitespace(r) || isNL(r):
+ return lexSkip(lx, lexArrayValue)
+ case r == commentStart:
+ lx.push(lexArrayValue)
+ return lexCommentStart
+ case r == arrayValTerm:
+ return lx.errorf("Unexpected array value terminator %q.",
+ arrayValTerm)
+ case r == arrayEnd:
+ return lexArrayEnd
+ }
+
+ lx.backup()
+ lx.push(lexArrayValueEnd)
+ return lexValue
+}
+
+// lexArrayValueEnd consumes the cruft between values of an array. Namely,
+// it ignores whitespace and expects either a ',' or a ']'.
+func lexArrayValueEnd(lx *lexer) stateFn {
+ r := lx.next()
+ switch {
+ case isWhitespace(r) || isNL(r):
+ return lexSkip(lx, lexArrayValueEnd)
+ case r == commentStart:
+ lx.push(lexArrayValueEnd)
+ return lexCommentStart
+ case r == arrayValTerm:
+ lx.ignore()
+ return lexArrayValue // move on to the next value
+ case r == arrayEnd:
+ return lexArrayEnd
+ }
+ return lx.errorf("Expected an array value terminator %q or an array "+
+ "terminator %q, but got %q instead.", arrayValTerm, arrayEnd, r)
+}
+
+// lexArrayEnd finishes the lexing of an array. It assumes that a ']' has
+// just been consumed.
+func lexArrayEnd(lx *lexer) stateFn {
+ lx.ignore()
+ lx.emit(itemArrayEnd)
+ return lx.pop()
+}
+
+// lexString consumes the inner contents of a string. It assumes that the
+// beginning '"' has already been consumed and ignored.
+func lexString(lx *lexer) stateFn {
+ r := lx.next()
+ switch {
+ case isNL(r):
+ return lx.errorf("Strings cannot contain new lines.")
+ case r == '\\':
+ lx.push(lexString)
+ return lexStringEscape
+ case r == stringEnd:
+ lx.backup()
+ lx.emit(itemString)
+ lx.next()
+ lx.ignore()
+ return lx.pop()
+ }
+ return lexString
+}
+
+// lexMultilineString consumes the inner contents of a string. It assumes that
+// the beginning '"""' has already been consumed and ignored.
+func lexMultilineString(lx *lexer) stateFn {
+ r := lx.next()
+ switch {
+ case r == '\\':
+ return lexMultilineStringEscape
+ case r == stringEnd:
+ if lx.accept(stringEnd) {
+ if lx.accept(stringEnd) {
+ lx.backup()
+ lx.backup()
+ lx.backup()
+ lx.emit(itemMultilineString)
+ lx.next()
+ lx.next()
+ lx.next()
+ lx.ignore()
+ return lx.pop()
+ }
+ lx.backup()
+ }
+ }
+ return lexMultilineString
+}
+
+// lexRawString consumes a raw string. Nothing can be escaped in such a string.
+// It assumes that the beginning "'" has already been consumed and ignored.
+func lexRawString(lx *lexer) stateFn {
+ r := lx.next()
+ switch {
+ case isNL(r):
+ return lx.errorf("Strings cannot contain new lines.")
+ case r == rawStringEnd:
+ lx.backup()
+ lx.emit(itemRawString)
+ lx.next()
+ lx.ignore()
+ return lx.pop()
+ }
+ return lexRawString
+}
+
+// lexMultilineRawString consumes a raw string. Nothing can be escaped in such
+// a string. It assumes that the beginning "'" has already been consumed and
+// ignored.
+func lexMultilineRawString(lx *lexer) stateFn {
+ r := lx.next()
+ switch {
+ case r == rawStringEnd:
+ if lx.accept(rawStringEnd) {
+ if lx.accept(rawStringEnd) {
+ lx.backup()
+ lx.backup()
+ lx.backup()
+ lx.emit(itemRawMultilineString)
+ lx.next()
+ lx.next()
+ lx.next()
+ lx.ignore()
+ return lx.pop()
+ }
+ lx.backup()
+ }
+ }
+ return lexMultilineRawString
+}
+
+// lexMultilineStringEscape consumes an escaped character. It assumes that the
+// preceding '\\' has already been consumed.
+func lexMultilineStringEscape(lx *lexer) stateFn {
+ // Handle the special case first:
+ if isNL(lx.next()) {
+ lx.next()
+ return lexMultilineString
+ } else {
+ lx.backup()
+ lx.push(lexMultilineString)
+ return lexStringEscape(lx)
+ }
+}
+
+func lexStringEscape(lx *lexer) stateFn {
+ r := lx.next()
+ switch r {
+ case 'b':
+ fallthrough
+ case 't':
+ fallthrough
+ case 'n':
+ fallthrough
+ case 'f':
+ fallthrough
+ case 'r':
+ fallthrough
+ case '"':
+ fallthrough
+ case '\\':
+ return lx.pop()
+ case 'u':
+ return lexShortUnicodeEscape
+ case 'U':
+ return lexLongUnicodeEscape
+ }
+ return lx.errorf("Invalid escape character %q. Only the following "+
+ "escape characters are allowed: "+
+ "\\b, \\t, \\n, \\f, \\r, \\\", \\/, \\\\, "+
+ "\\uXXXX and \\UXXXXXXXX.", r)
+}
+
+func lexShortUnicodeEscape(lx *lexer) stateFn {
+ var r rune
+ for i := 0; i < 4; i++ {
+ r = lx.next()
+ if !isHexadecimal(r) {
+ return lx.errorf("Expected four hexadecimal digits after '\\u', "+
+ "but got '%s' instead.", lx.current())
+ }
+ }
+ return lx.pop()
+}
+
+func lexLongUnicodeEscape(lx *lexer) stateFn {
+ var r rune
+ for i := 0; i < 8; i++ {
+ r = lx.next()
+ if !isHexadecimal(r) {
+ return lx.errorf("Expected eight hexadecimal digits after '\\U', "+
+ "but got '%s' instead.", lx.current())
+ }
+ }
+ return lx.pop()
+}
+
+// lexNumberOrDateStart consumes either a (positive) integer, float or
+// datetime. It assumes that NO negative sign has been consumed.
+func lexNumberOrDateStart(lx *lexer) stateFn {
+ r := lx.next()
+ if !isDigit(r) {
+ if r == '.' {
+ return lx.errorf("Floats must start with a digit, not '.'.")
+ } else {
+ return lx.errorf("Expected a digit but got %q.", r)
+ }
+ }
+ return lexNumberOrDate
+}
+
+// lexNumberOrDate consumes either a (positive) integer, float or datetime.
+func lexNumberOrDate(lx *lexer) stateFn {
+ r := lx.next()
+ switch {
+ case r == '-':
+ if lx.pos-lx.start != 5 {
+ return lx.errorf("All ISO8601 dates must be in full Zulu form.")
+ }
+ return lexDateAfterYear
+ case isDigit(r):
+ return lexNumberOrDate
+ case r == '.':
+ return lexFloatStart
+ }
+
+ lx.backup()
+ lx.emit(itemInteger)
+ return lx.pop()
+}
+
+// lexDateAfterYear consumes a full Zulu Datetime in ISO8601 format.
+// It assumes that "YYYY-" has already been consumed.
+func lexDateAfterYear(lx *lexer) stateFn {
+ formats := []rune{
+ // digits are '0'.
+ // everything else is direct equality.
+ '0', '0', '-', '0', '0',
+ 'T',
+ '0', '0', ':', '0', '0', ':', '0', '0',
+ 'Z',
+ }
+ for _, f := range formats {
+ r := lx.next()
+ if f == '0' {
+ if !isDigit(r) {
+ return lx.errorf("Expected digit in ISO8601 datetime, "+
+ "but found %q instead.", r)
+ }
+ } else if f != r {
+ return lx.errorf("Expected %q in ISO8601 datetime, "+
+ "but found %q instead.", f, r)
+ }
+ }
+ lx.emit(itemDatetime)
+ return lx.pop()
+}
+
+// lexNumberStart consumes either an integer or a float. It assumes that
+// a negative sign has already been read, but that *no* digits have been
+// consumed. lexNumberStart will move to the appropriate integer or float
+// states.
+func lexNumberStart(lx *lexer) stateFn {
+ // we MUST see a digit. Even floats have to start with a digit.
+ r := lx.next()
+ if !isDigit(r) {
+ if r == '.' {
+ return lx.errorf("Floats must start with a digit, not '.'.")
+ } else {
+ return lx.errorf("Expected a digit but got %q.", r)
+ }
+ }
+ return lexNumber
+}
+
+// lexNumber consumes an integer or a float after seeing the first digit.
+func lexNumber(lx *lexer) stateFn {
+ r := lx.next()
+ switch {
+ case isDigit(r):
+ return lexNumber
+ case r == '.':
+ return lexFloatStart
+ }
+
+ lx.backup()
+ lx.emit(itemInteger)
+ return lx.pop()
+}
+
+// lexFloatStart starts the consumption of digits of a float after a '.'.
+// Namely, at least one digit is required.
+func lexFloatStart(lx *lexer) stateFn {
+ r := lx.next()
+ if !isDigit(r) {
+ return lx.errorf("Floats must have a digit after the '.', but got "+
+ "%q instead.", r)
+ }
+ return lexFloat
+}
+
+// lexFloat consumes the digits of a float after a '.'.
+// Assumes that one digit has been consumed after a '.' already.
+func lexFloat(lx *lexer) stateFn {
+ r := lx.next()
+ if isDigit(r) {
+ return lexFloat
+ }
+
+ lx.backup()
+ lx.emit(itemFloat)
+ return lx.pop()
+}
+
+// lexConst consumes the s[1:] in s. It assumes that s[0] has already been
+// consumed.
+func lexConst(lx *lexer, s string) stateFn {
+ for i := range s[1:] {
+ if r := lx.next(); r != rune(s[i+1]) {
+ return lx.errorf("Expected %q, but found %q instead.", s[:i+1],
+ s[:i]+string(r))
+ }
+ }
+ return nil
+}
+
+// lexTrue consumes the "rue" in "true". It assumes that 't' has already
+// been consumed.
+func lexTrue(lx *lexer) stateFn {
+ if fn := lexConst(lx, "true"); fn != nil {
+ return fn
+ }
+ lx.emit(itemBool)
+ return lx.pop()
+}
+
+// lexFalse consumes the "alse" in "false". It assumes that 'f' has already
+// been consumed.
+func lexFalse(lx *lexer) stateFn {
+ if fn := lexConst(lx, "false"); fn != nil {
+ return fn
+ }
+ lx.emit(itemBool)
+ return lx.pop()
+}
+
+// lexCommentStart begins the lexing of a comment. It will emit
+// itemCommentStart and consume no characters, passing control to lexComment.
+func lexCommentStart(lx *lexer) stateFn {
+ lx.ignore()
+ lx.emit(itemCommentStart)
+ return lexComment
+}
+
+// lexComment lexes an entire comment. It assumes that '#' has been consumed.
+// It will consume *up to* the first new line character, and pass control
+// back to the last state on the stack.
+func lexComment(lx *lexer) stateFn {
+ r := lx.peek()
+ if isNL(r) || r == eof {
+ lx.emit(itemText)
+ return lx.pop()
+ }
+ lx.next()
+ return lexComment
+}
+
+// lexSkip ignores all slurped input and moves on to the next state.
+func lexSkip(lx *lexer, nextState stateFn) stateFn {
+ return func(lx *lexer) stateFn {
+ lx.ignore()
+ return nextState
+ }
+}
+
+// isWhitespace returns true if `r` is a whitespace character according
+// to the spec.
+func isWhitespace(r rune) bool {
+ return r == '\t' || r == ' '
+}
+
+func isNL(r rune) bool {
+ return r == '\n' || r == '\r'
+}
+
+func isDigit(r rune) bool {
+ return r >= '0' && r <= '9'
+}
+
+func isHexadecimal(r rune) bool {
+ return (r >= '0' && r <= '9') ||
+ (r >= 'a' && r <= 'f') ||
+ (r >= 'A' && r <= 'F')
+}
+
+func isBareKeyChar(r rune) bool {
+ return (r >= 'A' && r <= 'Z') ||
+ (r >= 'a' && r <= 'z') ||
+ (r >= '0' && r <= '9') ||
+ r == '_' ||
+ r == '-'
+}
+
+func (itype itemType) String() string {
+ switch itype {
+ case itemError:
+ return "Error"
+ case itemNIL:
+ return "NIL"
+ case itemEOF:
+ return "EOF"
+ case itemText:
+ return "Text"
+ case itemString:
+ return "String"
+ case itemRawString:
+ return "String"
+ case itemMultilineString:
+ return "String"
+ case itemRawMultilineString:
+ return "String"
+ case itemBool:
+ return "Bool"
+ case itemInteger:
+ return "Integer"
+ case itemFloat:
+ return "Float"
+ case itemDatetime:
+ return "DateTime"
+ case itemTableStart:
+ return "TableStart"
+ case itemTableEnd:
+ return "TableEnd"
+ case itemKeyStart:
+ return "KeyStart"
+ case itemArray:
+ return "Array"
+ case itemArrayEnd:
+ return "ArrayEnd"
+ case itemCommentStart:
+ return "CommentStart"
+ }
+ panic(fmt.Sprintf("BUG: Unknown type '%d'.", int(itype)))
+}
+
+func (item item) String() string {
+ return fmt.Sprintf("(%s, %s)", item.typ.String(), item.val)
+}
diff --git a/vendor/github.com/BurntSushi/toml/parse.go b/vendor/github.com/BurntSushi/toml/parse.go
new file mode 100644
index 0000000..c6069be
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/parse.go
@@ -0,0 +1,498 @@
+package toml
+
+import (
+ "fmt"
+ "log"
+ "strconv"
+ "strings"
+ "time"
+ "unicode"
+ "unicode/utf8"
+)
+
+type parser struct {
+ mapping map[string]interface{}
+ types map[string]tomlType
+ lx *lexer
+
+ // A list of keys in the order that they appear in the TOML data.
+ ordered []Key
+
+ // the full key for the current hash in scope
+ context Key
+
+ // the base key name for everything except hashes
+ currentKey string
+
+ // rough approximation of line number
+ approxLine int
+
+ // A map of 'key.group.names' to whether they were created implicitly.
+ implicits map[string]bool
+}
+
+type parseError string
+
+func (pe parseError) Error() string {
+ return string(pe)
+}
+
+func parse(data string) (p *parser, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ var ok bool
+ if err, ok = r.(parseError); ok {
+ return
+ }
+ panic(r)
+ }
+ }()
+
+ p = &parser{
+ mapping: make(map[string]interface{}),
+ types: make(map[string]tomlType),
+ lx: lex(data),
+ ordered: make([]Key, 0),
+ implicits: make(map[string]bool),
+ }
+ for {
+ item := p.next()
+ if item.typ == itemEOF {
+ break
+ }
+ p.topLevel(item)
+ }
+
+ return p, nil
+}
+
+func (p *parser) panicf(format string, v ...interface{}) {
+ msg := fmt.Sprintf("Near line %d (last key parsed '%s'): %s",
+ p.approxLine, p.current(), fmt.Sprintf(format, v...))
+ panic(parseError(msg))
+}
+
+func (p *parser) next() item {
+ it := p.lx.nextItem()
+ if it.typ == itemError {
+ p.panicf("%s", it.val)
+ }
+ return it
+}
+
+func (p *parser) bug(format string, v ...interface{}) {
+ log.Fatalf("BUG: %s\n\n", fmt.Sprintf(format, v...))
+}
+
+func (p *parser) expect(typ itemType) item {
+ it := p.next()
+ p.assertEqual(typ, it.typ)
+ return it
+}
+
+func (p *parser) assertEqual(expected, got itemType) {
+ if expected != got {
+ p.bug("Expected '%s' but got '%s'.", expected, got)
+ }
+}
+
+func (p *parser) topLevel(item item) {
+ switch item.typ {
+ case itemCommentStart:
+ p.approxLine = item.line
+ p.expect(itemText)
+ case itemTableStart:
+ kg := p.next()
+ p.approxLine = kg.line
+
+ var key Key
+ for ; kg.typ != itemTableEnd && kg.typ != itemEOF; kg = p.next() {
+ key = append(key, p.keyString(kg))
+ }
+ p.assertEqual(itemTableEnd, kg.typ)
+
+ p.establishContext(key, false)
+ p.setType("", tomlHash)
+ p.ordered = append(p.ordered, key)
+ case itemArrayTableStart:
+ kg := p.next()
+ p.approxLine = kg.line
+
+ var key Key
+ for ; kg.typ != itemArrayTableEnd && kg.typ != itemEOF; kg = p.next() {
+ key = append(key, p.keyString(kg))
+ }
+ p.assertEqual(itemArrayTableEnd, kg.typ)
+
+ p.establishContext(key, true)
+ p.setType("", tomlArrayHash)
+ p.ordered = append(p.ordered, key)
+ case itemKeyStart:
+ kname := p.next()
+ p.approxLine = kname.line
+ p.currentKey = p.keyString(kname)
+
+ val, typ := p.value(p.next())
+ p.setValue(p.currentKey, val)
+ p.setType(p.currentKey, typ)
+ p.ordered = append(p.ordered, p.context.add(p.currentKey))
+ p.currentKey = ""
+ default:
+ p.bug("Unexpected type at top level: %s", item.typ)
+ }
+}
+
+// Gets a string for a key (or part of a key in a table name).
+func (p *parser) keyString(it item) string {
+ switch it.typ {
+ case itemText:
+ return it.val
+ case itemString, itemMultilineString,
+ itemRawString, itemRawMultilineString:
+ s, _ := p.value(it)
+ return s.(string)
+ default:
+ p.bug("Unexpected key type: %s", it.typ)
+ panic("unreachable")
+ }
+}
+
+// value translates an expected value from the lexer into a Go value wrapped
+// as an empty interface.
+func (p *parser) value(it item) (interface{}, tomlType) {
+ switch it.typ {
+ case itemString:
+ return p.replaceEscapes(it.val), p.typeOfPrimitive(it)
+ case itemMultilineString:
+ trimmed := stripFirstNewline(stripEscapedWhitespace(it.val))
+ return p.replaceEscapes(trimmed), p.typeOfPrimitive(it)
+ case itemRawString:
+ return it.val, p.typeOfPrimitive(it)
+ case itemRawMultilineString:
+ return stripFirstNewline(it.val), p.typeOfPrimitive(it)
+ case itemBool:
+ switch it.val {
+ case "true":
+ return true, p.typeOfPrimitive(it)
+ case "false":
+ return false, p.typeOfPrimitive(it)
+ }
+ p.bug("Expected boolean value, but got '%s'.", it.val)
+ case itemInteger:
+ num, err := strconv.ParseInt(it.val, 10, 64)
+ if err != nil {
+ // See comment below for floats describing why we make a
+ // distinction between a bug and a user error.
+ if e, ok := err.(*strconv.NumError); ok &&
+ e.Err == strconv.ErrRange {
+
+ p.panicf("Integer '%s' is out of the range of 64-bit "+
+ "signed integers.", it.val)
+ } else {
+ p.bug("Expected integer value, but got '%s'.", it.val)
+ }
+ }
+ return num, p.typeOfPrimitive(it)
+ case itemFloat:
+ num, err := strconv.ParseFloat(it.val, 64)
+ if err != nil {
+ // Distinguish float values. Normally, it'd be a bug if the lexer
+ // provides an invalid float, but it's possible that the float is
+ // out of range of valid values (which the lexer cannot determine).
+ // So mark the former as a bug but the latter as a legitimate user
+ // error.
+ //
+ // This is also true for integers.
+ if e, ok := err.(*strconv.NumError); ok &&
+ e.Err == strconv.ErrRange {
+
+ p.panicf("Float '%s' is out of the range of 64-bit "+
+ "IEEE-754 floating-point numbers.", it.val)
+ } else {
+ p.bug("Expected float value, but got '%s'.", it.val)
+ }
+ }
+ return num, p.typeOfPrimitive(it)
+ case itemDatetime:
+ t, err := time.Parse("2006-01-02T15:04:05Z", it.val)
+ if err != nil {
+ p.bug("Expected Zulu formatted DateTime, but got '%s'.", it.val)
+ }
+ return t, p.typeOfPrimitive(it)
+ case itemArray:
+ array := make([]interface{}, 0)
+ types := make([]tomlType, 0)
+
+ for it = p.next(); it.typ != itemArrayEnd; it = p.next() {
+ if it.typ == itemCommentStart {
+ p.expect(itemText)
+ continue
+ }
+
+ val, typ := p.value(it)
+ array = append(array, val)
+ types = append(types, typ)
+ }
+ return array, p.typeOfArray(types)
+ }
+ p.bug("Unexpected value type: %s", it.typ)
+ panic("unreachable")
+}
+
+// establishContext sets the current context of the parser,
+// where the context is either a hash or an array of hashes. Which one is
+// set depends on the value of the `array` parameter.
+//
+// Establishing the context also makes sure that the key isn't a duplicate, and
+// will create implicit hashes automatically.
+func (p *parser) establishContext(key Key, array bool) {
+ var ok bool
+
+ // Always start at the top level and drill down for our context.
+ hashContext := p.mapping
+ keyContext := make(Key, 0)
+
+ // We only need implicit hashes for key[0:-1]
+ for _, k := range key[0 : len(key)-1] {
+ _, ok = hashContext[k]
+ keyContext = append(keyContext, k)
+
+ // No key? Make an implicit hash and move on.
+ if !ok {
+ p.addImplicit(keyContext)
+ hashContext[k] = make(map[string]interface{})
+ }
+
+ // If the hash context is actually an array of tables, then set
+ // the hash context to the last element in that array.
+ //
+ // Otherwise, it better be a table, since this MUST be a key group (by
+ // virtue of it not being the last element in a key).
+ switch t := hashContext[k].(type) {
+ case []map[string]interface{}:
+ hashContext = t[len(t)-1]
+ case map[string]interface{}:
+ hashContext = t
+ default:
+ p.panicf("Key '%s' was already created as a hash.", keyContext)
+ }
+ }
+
+ p.context = keyContext
+ if array {
+ // If this is the first element for this array, then allocate a new
+ // list of tables for it.
+ k := key[len(key)-1]
+ if _, ok := hashContext[k]; !ok {
+ hashContext[k] = make([]map[string]interface{}, 0, 5)
+ }
+
+ // Add a new table. But make sure the key hasn't already been used
+ // for something else.
+ if hash, ok := hashContext[k].([]map[string]interface{}); ok {
+ hashContext[k] = append(hash, make(map[string]interface{}))
+ } else {
+ p.panicf("Key '%s' was already created and cannot be used as "+
+ "an array.", keyContext)
+ }
+ } else {
+ p.setValue(key[len(key)-1], make(map[string]interface{}))
+ }
+ p.context = append(p.context, key[len(key)-1])
+}
+
+// setValue sets the given key to the given value in the current context.
+// It will make sure that the key hasn't already been defined, account for
+// implicit key groups.
+func (p *parser) setValue(key string, value interface{}) {
+ var tmpHash interface{}
+ var ok bool
+
+ hash := p.mapping
+ keyContext := make(Key, 0)
+ for _, k := range p.context {
+ keyContext = append(keyContext, k)
+ if tmpHash, ok = hash[k]; !ok {
+ p.bug("Context for key '%s' has not been established.", keyContext)
+ }
+ switch t := tmpHash.(type) {
+ case []map[string]interface{}:
+ // The context is a table of hashes. Pick the most recent table
+ // defined as the current hash.
+ hash = t[len(t)-1]
+ case map[string]interface{}:
+ hash = t
+ default:
+ p.bug("Expected hash to have type 'map[string]interface{}', but "+
+ "it has '%T' instead.", tmpHash)
+ }
+ }
+ keyContext = append(keyContext, key)
+
+ if _, ok := hash[key]; ok {
+ // Typically, if the given key has already been set, then we have
+ // to raise an error since duplicate keys are disallowed. However,
+ // it's possible that a key was previously defined implicitly. In this
+ // case, it is allowed to be redefined concretely. (See the
+ // `tests/valid/implicit-and-explicit-after.toml` test in `toml-test`.)
+ //
+ // But we have to make sure to stop marking it as an implicit. (So that
+ // another redefinition provokes an error.)
+ //
+ // Note that since it has already been defined (as a hash), we don't
+ // want to overwrite it. So our business is done.
+ if p.isImplicit(keyContext) {
+ p.removeImplicit(keyContext)
+ return
+ }
+
+ // Otherwise, we have a concrete key trying to override a previous
+ // key, which is *always* wrong.
+ p.panicf("Key '%s' has already been defined.", keyContext)
+ }
+ hash[key] = value
+}
+
+// setType sets the type of a particular value at a given key.
+// It should be called immediately AFTER setValue.
+//
+// Note that if `key` is empty, then the type given will be applied to the
+// current context (which is either a table or an array of tables).
+func (p *parser) setType(key string, typ tomlType) {
+ keyContext := make(Key, 0, len(p.context)+1)
+ for _, k := range p.context {
+ keyContext = append(keyContext, k)
+ }
+ if len(key) > 0 { // allow type setting for hashes
+ keyContext = append(keyContext, key)
+ }
+ p.types[keyContext.String()] = typ
+}
+
+// addImplicit sets the given Key as having been created implicitly.
+func (p *parser) addImplicit(key Key) {
+ p.implicits[key.String()] = true
+}
+
+// removeImplicit stops tagging the given key as having been implicitly
+// created.
+func (p *parser) removeImplicit(key Key) {
+ p.implicits[key.String()] = false
+}
+
+// isImplicit returns true if the key group pointed to by the key was created
+// implicitly.
+func (p *parser) isImplicit(key Key) bool {
+ return p.implicits[key.String()]
+}
+
+// current returns the full key name of the current context.
+func (p *parser) current() string {
+ if len(p.currentKey) == 0 {
+ return p.context.String()
+ }
+ if len(p.context) == 0 {
+ return p.currentKey
+ }
+ return fmt.Sprintf("%s.%s", p.context, p.currentKey)
+}
+
+func stripFirstNewline(s string) string {
+ if len(s) == 0 || s[0] != '\n' {
+ return s
+ }
+ return s[1:len(s)]
+}
+
+func stripEscapedWhitespace(s string) string {
+ esc := strings.Split(s, "\\\n")
+ if len(esc) > 1 {
+ for i := 1; i < len(esc); i++ {
+ esc[i] = strings.TrimLeftFunc(esc[i], unicode.IsSpace)
+ }
+ }
+ return strings.Join(esc, "")
+}
+
+func (p *parser) replaceEscapes(str string) string {
+ var replaced []rune
+ s := []byte(str)
+ r := 0
+ for r < len(s) {
+ if s[r] != '\\' {
+ c, size := utf8.DecodeRune(s[r:])
+ r += size
+ replaced = append(replaced, c)
+ continue
+ }
+ r += 1
+ if r >= len(s) {
+ p.bug("Escape sequence at end of string.")
+ return ""
+ }
+ switch s[r] {
+ default:
+ p.bug("Expected valid escape code after \\, but got %q.", s[r])
+ return ""
+ case 'b':
+ replaced = append(replaced, rune(0x0008))
+ r += 1
+ case 't':
+ replaced = append(replaced, rune(0x0009))
+ r += 1
+ case 'n':
+ replaced = append(replaced, rune(0x000A))
+ r += 1
+ case 'f':
+ replaced = append(replaced, rune(0x000C))
+ r += 1
+ case 'r':
+ replaced = append(replaced, rune(0x000D))
+ r += 1
+ case '"':
+ replaced = append(replaced, rune(0x0022))
+ r += 1
+ case '\\':
+ replaced = append(replaced, rune(0x005C))
+ r += 1
+ case 'u':
+ // At this point, we know we have a Unicode escape of the form
+ // `uXXXX` at [r, r+5). (Because the lexer guarantees this
+ // for us.)
+ escaped := p.asciiEscapeToUnicode(s[r+1 : r+5])
+ replaced = append(replaced, escaped)
+ r += 5
+ case 'U':
+ // At this point, we know we have a Unicode escape of the form
+ // `uXXXX` at [r, r+9). (Because the lexer guarantees this
+ // for us.)
+ escaped := p.asciiEscapeToUnicode(s[r+1 : r+9])
+ replaced = append(replaced, escaped)
+ r += 9
+ }
+ }
+ return string(replaced)
+}
+
+func (p *parser) asciiEscapeToUnicode(bs []byte) rune {
+ s := string(bs)
+ hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32)
+ if err != nil {
+ p.bug("Could not parse '%s' as a hexadecimal number, but the "+
+ "lexer claims it's OK: %s", s, err)
+ }
+
+ // BUG(burntsushi)
+ // I honestly don't understand how this works. I can't seem
+ // to find a way to make this fail. I figured this would fail on invalid
+ // UTF-8 characters like U+DCFF, but it doesn't.
+ if !utf8.ValidString(string(rune(hex))) {
+ p.panicf("Escaped character '\\u%s' is not valid UTF-8.", s)
+ }
+ return rune(hex)
+}
+
+func isStringType(ty itemType) bool {
+ return ty == itemString || ty == itemMultilineString ||
+ ty == itemRawString || ty == itemRawMultilineString
+}
diff --git a/vendor/github.com/BurntSushi/toml/type_check.go b/vendor/github.com/BurntSushi/toml/type_check.go
new file mode 100644
index 0000000..c73f8af
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/type_check.go
@@ -0,0 +1,91 @@
+package toml
+
+// tomlType represents any Go type that corresponds to a TOML type.
+// While the first draft of the TOML spec has a simplistic type system that
+// probably doesn't need this level of sophistication, we seem to be militating
+// toward adding real composite types.
+type tomlType interface {
+ typeString() string
+}
+
+// typeEqual accepts any two types and returns true if they are equal.
+func typeEqual(t1, t2 tomlType) bool {
+ if t1 == nil || t2 == nil {
+ return false
+ }
+ return t1.typeString() == t2.typeString()
+}
+
+func typeIsHash(t tomlType) bool {
+ return typeEqual(t, tomlHash) || typeEqual(t, tomlArrayHash)
+}
+
+type tomlBaseType string
+
+func (btype tomlBaseType) typeString() string {
+ return string(btype)
+}
+
+func (btype tomlBaseType) String() string {
+ return btype.typeString()
+}
+
+var (
+ tomlInteger tomlBaseType = "Integer"
+ tomlFloat tomlBaseType = "Float"
+ tomlDatetime tomlBaseType = "Datetime"
+ tomlString tomlBaseType = "String"
+ tomlBool tomlBaseType = "Bool"
+ tomlArray tomlBaseType = "Array"
+ tomlHash tomlBaseType = "Hash"
+ tomlArrayHash tomlBaseType = "ArrayHash"
+)
+
+// typeOfPrimitive returns a tomlType of any primitive value in TOML.
+// Primitive values are: Integer, Float, Datetime, String and Bool.
+//
+// Passing a lexer item other than the following will cause a BUG message
+// to occur: itemString, itemBool, itemInteger, itemFloat, itemDatetime.
+func (p *parser) typeOfPrimitive(lexItem item) tomlType {
+ switch lexItem.typ {
+ case itemInteger:
+ return tomlInteger
+ case itemFloat:
+ return tomlFloat
+ case itemDatetime:
+ return tomlDatetime
+ case itemString:
+ return tomlString
+ case itemMultilineString:
+ return tomlString
+ case itemRawString:
+ return tomlString
+ case itemRawMultilineString:
+ return tomlString
+ case itemBool:
+ return tomlBool
+ }
+ p.bug("Cannot infer primitive type of lex item '%s'.", lexItem)
+ panic("unreachable")
+}
+
+// typeOfArray returns a tomlType for an array given a list of types of its
+// values.
+//
+// In the current spec, if an array is homogeneous, then its type is always
+// "Array". If the array is not homogeneous, an error is generated.
+func (p *parser) typeOfArray(types []tomlType) tomlType {
+ // Empty arrays are cool.
+ if len(types) == 0 {
+ return tomlArray
+ }
+
+ theType := types[0]
+ for _, t := range types[1:] {
+ if !typeEqual(theType, t) {
+ p.panicf("Array contains values of type '%s' and '%s', but "+
+ "arrays must be homogeneous.", theType, t)
+ }
+ }
+ return tomlArray
+}
diff --git a/vendor/github.com/BurntSushi/toml/type_fields.go b/vendor/github.com/BurntSushi/toml/type_fields.go
new file mode 100644
index 0000000..7592f87
--- /dev/null
+++ b/vendor/github.com/BurntSushi/toml/type_fields.go
@@ -0,0 +1,241 @@
+package toml
+
+// Struct field handling is adapted from code in encoding/json:
+//
+// 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 Go distribution.
+
+import (
+ "reflect"
+ "sort"
+ "sync"
+)
+
+// A field represents a single field found in a struct.
+type field struct {
+ name string // the name of the field (`toml` tag included)
+ tag bool // whether field has a `toml` tag
+ index []int // represents the depth of an anonymous field
+ typ reflect.Type // the type of the field
+}
+
+// byName sorts field by name, breaking ties with depth,
+// then breaking ties with "name came from toml tag", then
+// breaking ties with index sequence.
+type byName []field
+
+func (x byName) Len() int { return len(x) }
+
+func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
+
+func (x byName) Less(i, j int) bool {
+ if x[i].name != x[j].name {
+ return x[i].name < x[j].name
+ }
+ if len(x[i].index) != len(x[j].index) {
+ return len(x[i].index) < len(x[j].index)
+ }
+ if x[i].tag != x[j].tag {
+ return x[i].tag
+ }
+ return byIndex(x).Less(i, j)
+}
+
+// byIndex sorts field by index sequence.
+type byIndex []field
+
+func (x byIndex) Len() int { return len(x) }
+
+func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
+
+func (x byIndex) Less(i, j int) bool {
+ for k, xik := range x[i].index {
+ if k >= len(x[j].index) {
+ return false
+ }
+ if xik != x[j].index[k] {
+ return xik < x[j].index[k]
+ }
+ }
+ return len(x[i].index) < len(x[j].index)
+}
+
+// typeFields returns a list of fields that TOML should recognize for the given
+// type. The algorithm is breadth-first search over the set of structs to
+// include - the top struct and then any reachable anonymous structs.
+func typeFields(t reflect.Type) []field {
+ // Anonymous fields to explore at the current level and the next.
+ current := []field{}
+ next := []field{{typ: t}}
+
+ // Count of queued names for current level and the next.
+ count := map[reflect.Type]int{}
+ nextCount := map[reflect.Type]int{}
+
+ // Types already visited at an earlier level.
+ visited := map[reflect.Type]bool{}
+
+ // Fields found.
+ var fields []field
+
+ for len(next) > 0 {
+ current, next = next, current[:0]
+ count, nextCount = nextCount, map[reflect.Type]int{}
+
+ for _, f := range current {
+ if visited[f.typ] {
+ continue
+ }
+ visited[f.typ] = true
+
+ // Scan f.typ for fields to include.
+ for i := 0; i < f.typ.NumField(); i++ {
+ sf := f.typ.Field(i)
+ if sf.PkgPath != "" { // unexported
+ continue
+ }
+ name := sf.Tag.Get("toml")
+ if name == "-" {
+ continue
+ }
+ index := make([]int, len(f.index)+1)
+ copy(index, f.index)
+ index[len(f.index)] = i
+
+ ft := sf.Type
+ if ft.Name() == "" && ft.Kind() == reflect.Ptr {
+ // Follow pointer.
+ ft = ft.Elem()
+ }
+
+ // Record found field and index sequence.
+ if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
+ tagged := name != ""
+ if name == "" {
+ name = sf.Name
+ }
+ fields = append(fields, field{name, tagged, index, ft})
+ if count[f.typ] > 1 {
+ // If there were multiple instances, add a second,
+ // so that the annihilation code will see a duplicate.
+ // It only cares about the distinction between 1 or 2,
+ // so don't bother generating any more copies.
+ fields = append(fields, fields[len(fields)-1])
+ }
+ continue
+ }
+
+ // Record new anonymous struct to explore in next round.
+ nextCount[ft]++
+ if nextCount[ft] == 1 {
+ f := field{name: ft.Name(), index: index, typ: ft}
+ next = append(next, f)
+ }
+ }
+ }
+ }
+
+ sort.Sort(byName(fields))
+
+ // Delete all fields that are hidden by the Go rules for embedded fields,
+ // except that fields with TOML tags are promoted.
+
+ // The fields are sorted in primary order of name, secondary order
+ // of field index length. Loop over names; for each name, delete
+ // hidden fields by choosing the one dominant field that survives.
+ out := fields[:0]
+ for advance, i := 0, 0; i < len(fields); i += advance {
+ // One iteration per name.
+ // Find the sequence of fields with the name of this first field.
+ fi := fields[i]
+ name := fi.name
+ for advance = 1; i+advance < len(fields); advance++ {
+ fj := fields[i+advance]
+ if fj.name != name {
+ break
+ }
+ }
+ if advance == 1 { // Only one field with this name
+ out = append(out, fi)
+ continue
+ }
+ dominant, ok := dominantField(fields[i : i+advance])
+ if ok {
+ out = append(out, dominant)
+ }
+ }
+
+ fields = out
+ sort.Sort(byIndex(fields))
+
+ return fields
+}
+
+// dominantField looks through the fields, all of which are known to
+// have the same name, to find the single field that dominates the
+// others using Go's embedding rules, modified by the presence of
+// TOML tags. If there are multiple top-level fields, the boolean
+// will be false: This condition is an error in Go and we skip all
+// the fields.
+func dominantField(fields []field) (field, bool) {
+ // The fields are sorted in increasing index-length order. The winner
+ // must therefore be one with the shortest index length. Drop all
+ // longer entries, which is easy: just truncate the slice.
+ length := len(fields[0].index)
+ tagged := -1 // Index of first tagged field.
+ for i, f := range fields {
+ if len(f.index) > length {
+ fields = fields[:i]
+ break
+ }
+ if f.tag {
+ if tagged >= 0 {
+ // Multiple tagged fields at the same level: conflict.
+ // Return no field.
+ return field{}, false
+ }
+ tagged = i
+ }
+ }
+ if tagged >= 0 {
+ return fields[tagged], true
+ }
+ // All remaining fields have the same length. If there's more than one,
+ // we have a conflict (two fields named "X" at the same level) and we
+ // return no field.
+ if len(fields) > 1 {
+ return field{}, false
+ }
+ return fields[0], true
+}
+
+var fieldCache struct {
+ sync.RWMutex
+ m map[reflect.Type][]field
+}
+
+// cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
+func cachedTypeFields(t reflect.Type) []field {
+ fieldCache.RLock()
+ f := fieldCache.m[t]
+ fieldCache.RUnlock()
+ if f != nil {
+ return f
+ }
+
+ // Compute fields without lock.
+ // Might duplicate effort but won't hold other computations back.
+ f = typeFields(t)
+ if f == nil {
+ f = []field{}
+ }
+
+ fieldCache.Lock()
+ if fieldCache.m == nil {
+ fieldCache.m = map[reflect.Type][]field{}
+ }
+ fieldCache.m[t] = f
+ fieldCache.Unlock()
+ return f
+}
diff --git a/vendor/github.com/Graylog2/go-gelf/LICENSE b/vendor/github.com/Graylog2/go-gelf/LICENSE
new file mode 100644
index 0000000..bc756ae
--- /dev/null
+++ b/vendor/github.com/Graylog2/go-gelf/LICENSE
@@ -0,0 +1,21 @@
+Copyright 2012 SocialCode
+
+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/Graylog2/go-gelf/README.md b/vendor/github.com/Graylog2/go-gelf/README.md
new file mode 100644
index 0000000..4900a35
--- /dev/null
+++ b/vendor/github.com/Graylog2/go-gelf/README.md
@@ -0,0 +1,76 @@
+go-gelf - GELF library and writer for Go
+========================================
+
+GELF is graylog2's UDP logging format. This library provides an API
+that applications can use to log messages directly to a graylog2
+server, along with an `io.Writer` that can be use to redirect the
+standard library's log messages (or `os.Stdout`), to a graylog2 server.
+
+Installing
+----------
+
+go-gelf is go get-able:
+
+ go get github.com/Graylog2/go-gelf/gelf
+
+Usage
+-----
+
+The easiest way to integrate graylog logging into your go app is by
+having your `main` function (or even `init`) call `log.SetOutput()`.
+By using an `io.MultiWriter`, we can log to both stdout and graylog -
+giving us both centralized and local logs. (Redundancy is nice).
+
+ package main
+
+ import (
+ "flag"
+ "github.com/Graylog2/go-gelf/gelf"
+ "io"
+ "log"
+ "os"
+ )
+
+ func main() {
+ var graylogAddr string
+
+ flag.StringVar(&graylogAddr, "graylog", "", "graylog server addr")
+ flag.Parse()
+
+ if graylogAddr != "" {
+ gelfWriter, err := gelf.NewWriter(graylogAddr)
+ if err != nil {
+ log.Fatalf("gelf.NewWriter: %s", err)
+ }
+ // log to both stderr and graylog2
+ log.SetOutput(io.MultiWriter(os.Stderr, gelfWriter))
+ log.Printf("logging to stderr & graylog2@'%s'", graylogAddr)
+ }
+
+ // From here on out, any calls to log.Print* functions
+ // will appear on stdout, and be sent over UDP to the
+ // specified Graylog2 server.
+
+ log.Printf("Hello gray World")
+
+ // ...
+ }
+
+The above program can be invoked as:
+
+ go run test.go -graylog=localhost:12201
+
+Because GELF messages are sent over UDP, graylog server availability
+doesn't impact application performance or response time. There is a
+small, fixed overhead per log call, regardless of whether the target
+server is reachable or not.
+
+To Do
+-----
+
+- WriteMessage example
+
+License
+-------
+
+go-gelf is offered under the MIT license, see LICENSE for details.
diff --git a/vendor/github.com/Graylog2/go-gelf/gelf/reader.go b/vendor/github.com/Graylog2/go-gelf/gelf/reader.go
new file mode 100644
index 0000000..ff719fc
--- /dev/null
+++ b/vendor/github.com/Graylog2/go-gelf/gelf/reader.go
@@ -0,0 +1,140 @@
+// Copyright 2012 SocialCode. All rights reserved.
+// Use of this source code is governed by the MIT
+// license that can be found in the LICENSE file.
+
+package gelf
+
+import (
+ "bytes"
+ "compress/gzip"
+ "compress/zlib"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "strings"
+ "sync"
+)
+
+type Reader struct {
+ mu sync.Mutex
+ conn net.Conn
+}
+
+func NewReader(addr string) (*Reader, error) {
+ var err error
+ udpAddr, err := net.ResolveUDPAddr("udp", addr)
+ if err != nil {
+ return nil, fmt.Errorf("ResolveUDPAddr('%s'): %s", addr, err)
+ }
+
+ conn, err := net.ListenUDP("udp", udpAddr)
+ if err != nil {
+ return nil, fmt.Errorf("ListenUDP: %s", err)
+ }
+
+ r := new(Reader)
+ r.conn = conn
+ return r, nil
+}
+
+func (r *Reader) Addr() string {
+ return r.conn.LocalAddr().String()
+}
+
+// FIXME: this will discard data if p isn't big enough to hold the
+// full message.
+func (r *Reader) Read(p []byte) (int, error) {
+ msg, err := r.ReadMessage()
+ if err != nil {
+ return -1, err
+ }
+
+ var data string
+
+ if msg.Full == "" {
+ data = msg.Short
+ } else {
+ data = msg.Full
+ }
+
+ return strings.NewReader(data).Read(p)
+}
+
+func (r *Reader) ReadMessage() (*Message, error) {
+ cBuf := make([]byte, ChunkSize)
+ var (
+ err error
+ n, length int
+ cid, ocid []byte
+ seq, total uint8
+ cHead []byte
+ cReader io.Reader
+ chunks [][]byte
+ )
+
+ for got := 0; got < 128 && (total == 0 || got < int(total)); got++ {
+ if n, err = r.conn.Read(cBuf); err != nil {
+ return nil, fmt.Errorf("Read: %s", err)
+ }
+ cHead, cBuf = cBuf[:2], cBuf[:n]
+
+ if bytes.Equal(cHead, magicChunked) {
+ //fmt.Printf("chunked %v\n", cBuf[:14])
+ cid, seq, total = cBuf[2:2+8], cBuf[2+8], cBuf[2+8+1]
+ if ocid != nil && !bytes.Equal(cid, ocid) {
+ return nil, fmt.Errorf("out-of-band message %v (awaited %v)", cid, ocid)
+ } else if ocid == nil {
+ ocid = cid
+ chunks = make([][]byte, total)
+ }
+ n = len(cBuf) - chunkedHeaderLen
+ //fmt.Printf("setting chunks[%d]: %d\n", seq, n)
+ chunks[seq] = append(make([]byte, 0, n), cBuf[chunkedHeaderLen:]...)
+ length += n
+ } else { //not chunked
+ if total > 0 {
+ return nil, fmt.Errorf("out-of-band message (not chunked)")
+ }
+ break
+ }
+ }
+ //fmt.Printf("\nchunks: %v\n", chunks)
+
+ if length > 0 {
+ if cap(cBuf) < length {
+ cBuf = append(cBuf, make([]byte, 0, length-cap(cBuf))...)
+ }
+ cBuf = cBuf[:0]
+ for i := range chunks {
+ //fmt.Printf("appending %d %v\n", i, chunks[i])
+ cBuf = append(cBuf, chunks[i]...)
+ }
+ cHead = cBuf[:2]
+ }
+
+ // the data we get from the wire is compressed
+ if bytes.Equal(cHead, magicGzip) {
+ cReader, err = gzip.NewReader(bytes.NewReader(cBuf))
+ } else if cHead[0] == magicZlib[0] &&
+ (int(cHead[0])*256+int(cHead[1]))%31 == 0 {
+ // zlib is slightly more complicated, but correct
+ cReader, err = zlib.NewReader(bytes.NewReader(cBuf))
+ } else {
+ // compliance with https://github.com/Graylog2/graylog2-server
+ // treating all messages as uncompressed if they are not gzip, zlib or
+ // chunked
+ cReader = bytes.NewReader(cBuf)
+ }
+
+ if err != nil {
+ return nil, fmt.Errorf("NewReader: %s", err)
+ }
+
+ msg := new(Message)
+ if err := json.NewDecoder(cReader).Decode(&msg); err != nil {
+ return nil, fmt.Errorf("json.Unmarshal: %s", err)
+ }
+
+ return msg, nil
+}
diff --git a/vendor/github.com/Graylog2/go-gelf/gelf/writer.go b/vendor/github.com/Graylog2/go-gelf/gelf/writer.go
new file mode 100644
index 0000000..38e6944
--- /dev/null
+++ b/vendor/github.com/Graylog2/go-gelf/gelf/writer.go
@@ -0,0 +1,418 @@
+// Copyright 2012 SocialCode. All rights reserved.
+// Use of this source code is governed by the MIT
+// license that can be found in the LICENSE file.
+
+package gelf
+
+import (
+ "bytes"
+ "compress/flate"
+ "compress/gzip"
+ "compress/zlib"
+ "crypto/rand"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "path"
+ "runtime"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Writer implements io.Writer and is used to send both discrete
+// messages to a graylog2 server, or data from a stream-oriented
+// interface (like the functions in log).
+type Writer struct {
+ mu sync.Mutex
+ conn net.Conn
+ hostname string
+ Facility string // defaults to current process name
+ CompressionLevel int // one of the consts from compress/flate
+ CompressionType CompressType
+}
+
+// What compression type the writer should use when sending messages
+// to the graylog2 server
+type CompressType int
+
+const (
+ CompressGzip CompressType = iota
+ CompressZlib
+ CompressNone
+)
+
+// Message represents the contents of the GELF message. It is gzipped
+// before sending.
+type Message struct {
+ Version string `json:"version"`
+ Host string `json:"host"`
+ Short string `json:"short_message"`
+ Full string `json:"full_message,omitempty"`
+ TimeUnix float64 `json:"timestamp"`
+ Level int32 `json:"level,omitempty"`
+ Facility string `json:"facility,omitempty"`
+ Extra map[string]interface{} `json:"-"`
+ RawExtra json.RawMessage `json:"-"`
+}
+
+// Used to control GELF chunking. Should be less than (MTU - len(UDP
+// header)).
+//
+// TODO: generate dynamically using Path MTU Discovery?
+const (
+ ChunkSize = 1420
+ chunkedHeaderLen = 12
+ chunkedDataLen = ChunkSize - chunkedHeaderLen
+)
+
+var (
+ magicChunked = []byte{0x1e, 0x0f}
+ magicZlib = []byte{0x78}
+ magicGzip = []byte{0x1f, 0x8b}
+)
+
+// Syslog severity levels
+const (
+ LOG_EMERG = int32(0)
+ LOG_ALERT = int32(1)
+ LOG_CRIT = int32(2)
+ LOG_ERR = int32(3)
+ LOG_WARNING = int32(4)
+ LOG_NOTICE = int32(5)
+ LOG_INFO = int32(6)
+ LOG_DEBUG = int32(7)
+)
+
+// numChunks returns the number of GELF chunks necessary to transmit
+// the given compressed buffer.
+func numChunks(b []byte) int {
+ lenB := len(b)
+ if lenB <= ChunkSize {
+ return 1
+ }
+ return len(b)/chunkedDataLen + 1
+}
+
+// New returns a new GELF Writer. This writer can be used to send the
+// output of the standard Go log functions to a central GELF server by
+// passing it to log.SetOutput()
+func NewWriter(addr string) (*Writer, error) {
+ var err error
+ w := new(Writer)
+ w.CompressionLevel = flate.BestSpeed
+
+ if w.conn, err = net.Dial("udp", addr); err != nil {
+ return nil, err
+ }
+ if w.hostname, err = os.Hostname(); err != nil {
+ return nil, err
+ }
+
+ w.Facility = path.Base(os.Args[0])
+
+ return w, nil
+}
+
+// writes the gzip compressed byte array to the connection as a series
+// of GELF chunked messages. The format is documented at
+// http://docs.graylog.org/en/2.1/pages/gelf.html as:
+//
+// 2-byte magic (0x1e 0x0f), 8 byte id, 1 byte sequence id, 1 byte
+// total, chunk-data
+func (w *Writer) writeChunked(zBytes []byte) (err error) {
+ b := make([]byte, 0, ChunkSize)
+ buf := bytes.NewBuffer(b)
+ nChunksI := numChunks(zBytes)
+ if nChunksI > 128 {
+ return fmt.Errorf("msg too large, would need %d chunks", nChunksI)
+ }
+ nChunks := uint8(nChunksI)
+ // use urandom to get a unique message id
+ msgId := make([]byte, 8)
+ n, err := io.ReadFull(rand.Reader, msgId)
+ if err != nil || n != 8 {
+ return fmt.Errorf("rand.Reader: %d/%s", n, err)
+ }
+
+ bytesLeft := len(zBytes)
+ for i := uint8(0); i < nChunks; i++ {
+ buf.Reset()
+ // manually write header. Don't care about
+ // host/network byte order, because the spec only
+ // deals in individual bytes.
+ buf.Write(magicChunked) //magic
+ buf.Write(msgId)
+ buf.WriteByte(i)
+ buf.WriteByte(nChunks)
+ // slice out our chunk from zBytes
+ chunkLen := chunkedDataLen
+ if chunkLen > bytesLeft {
+ chunkLen = bytesLeft
+ }
+ off := int(i) * chunkedDataLen
+ chunk := zBytes[off : off+chunkLen]
+ buf.Write(chunk)
+
+ // write this chunk, and make sure the write was good
+ n, err := w.conn.Write(buf.Bytes())
+ if err != nil {
+ return fmt.Errorf("Write (chunk %d/%d): %s", i,
+ nChunks, err)
+ }
+ if n != len(buf.Bytes()) {
+ return fmt.Errorf("Write len: (chunk %d/%d) (%d/%d)",
+ i, nChunks, n, len(buf.Bytes()))
+ }
+
+ bytesLeft -= chunkLen
+ }
+
+ if bytesLeft != 0 {
+ return fmt.Errorf("error: %d bytes left after sending", bytesLeft)
+ }
+ return nil
+}
+
+// 1k bytes buffer by default
+var bufPool = sync.Pool{
+ New: func() interface{} {
+ return bytes.NewBuffer(make([]byte, 0, 1024))
+ },
+}
+
+func newBuffer() *bytes.Buffer {
+ b := bufPool.Get().(*bytes.Buffer)
+ if b != nil {
+ b.Reset()
+ return b
+ }
+ return bytes.NewBuffer(nil)
+}
+
+// WriteMessage sends the specified message to the GELF server
+// specified in the call to New(). It assumes all the fields are
+// filled out appropriately. In general, clients will want to use
+// Write, rather than WriteMessage.
+func (w *Writer) WriteMessage(m *Message) (err error) {
+ mBuf := newBuffer()
+ defer bufPool.Put(mBuf)
+ if err = m.MarshalJSONBuf(mBuf); err != nil {
+ return err
+ }
+ mBytes := mBuf.Bytes()
+
+ var (
+ zBuf *bytes.Buffer
+ zBytes []byte
+ )
+
+ var zw io.WriteCloser
+ switch w.CompressionType {
+ case CompressGzip:
+ zBuf = newBuffer()
+ defer bufPool.Put(zBuf)
+ zw, err = gzip.NewWriterLevel(zBuf, w.CompressionLevel)
+ case CompressZlib:
+ zBuf = newBuffer()
+ defer bufPool.Put(zBuf)
+ zw, err = zlib.NewWriterLevel(zBuf, w.CompressionLevel)
+ case CompressNone:
+ zBytes = mBytes
+ default:
+ panic(fmt.Sprintf("unknown compression type %d",
+ w.CompressionType))
+ }
+ if zw != nil {
+ if err != nil {
+ return
+ }
+ if _, err = zw.Write(mBytes); err != nil {
+ zw.Close()
+ return
+ }
+ zw.Close()
+ zBytes = zBuf.Bytes()
+ }
+
+ if numChunks(zBytes) > 1 {
+ return w.writeChunked(zBytes)
+ }
+ n, err := w.conn.Write(zBytes)
+ if err != nil {
+ return
+ }
+ if n != len(zBytes) {
+ return fmt.Errorf("bad write (%d/%d)", n, len(zBytes))
+ }
+
+ return nil
+}
+
+// Close connection and interrupt blocked Read or Write operations
+func (w *Writer) Close() error {
+ return w.conn.Close()
+}
+
+/*
+func (w *Writer) Alert(m string) (err error)
+func (w *Writer) Close() error
+func (w *Writer) Crit(m string) (err error)
+func (w *Writer) Debug(m string) (err error)
+func (w *Writer) Emerg(m string) (err error)
+func (w *Writer) Err(m string) (err error)
+func (w *Writer) Info(m string) (err error)
+func (w *Writer) Notice(m string) (err error)
+func (w *Writer) Warning(m string) (err error)
+*/
+
+// getCaller returns the filename and the line info of a function
+// further down in the call stack. Passing 0 in as callDepth would
+// return info on the function calling getCallerIgnoringLog, 1 the
+// parent function, and so on. Any suffixes passed to getCaller are
+// path fragments like "/pkg/log/log.go", and functions in the call
+// stack from that file are ignored.
+func getCaller(callDepth int, suffixesToIgnore ...string) (file string, line int) {
+ // bump by 1 to ignore the getCaller (this) stackframe
+ callDepth++
+outer:
+ for {
+ var ok bool
+ _, file, line, ok = runtime.Caller(callDepth)
+ if !ok {
+ file = "???"
+ line = 0
+ break
+ }
+
+ for _, s := range suffixesToIgnore {
+ if strings.HasSuffix(file, s) {
+ callDepth++
+ continue outer
+ }
+ }
+ break
+ }
+ return
+}
+
+func getCallerIgnoringLogMulti(callDepth int) (string, int) {
+ // the +1 is to ignore this (getCallerIgnoringLogMulti) frame
+ return getCaller(callDepth+1, "/pkg/log/log.go", "/pkg/io/multi.go")
+}
+
+// Write encodes the given string in a GELF message and sends it to
+// the server specified in New().
+func (w *Writer) Write(p []byte) (n int, err error) {
+
+ // 1 for the function that called us.
+ file, line := getCallerIgnoringLogMulti(1)
+
+ // remove trailing and leading whitespace
+ p = bytes.TrimSpace(p)
+
+ // If there are newlines in the message, use the first line
+ // for the short message and set the full message to the
+ // original input. If the input has no newlines, stick the
+ // whole thing in Short.
+ short := p
+ full := []byte("")
+ if i := bytes.IndexRune(p, '\n'); i > 0 {
+ short = p[:i]
+ full = p
+ }
+
+ m := Message{
+ Version: "1.1",
+ Host: w.hostname,
+ Short: string(short),
+ Full: string(full),
+ TimeUnix: float64(time.Now().Unix()),
+ Level: 6, // info
+ Facility: w.Facility,
+ Extra: map[string]interface{}{
+ "_file": file,
+ "_line": line,
+ },
+ }
+
+ if err = w.WriteMessage(&m); err != nil {
+ return 0, err
+ }
+
+ return len(p), nil
+}
+
+func (m *Message) MarshalJSONBuf(buf *bytes.Buffer) error {
+ b, err := json.Marshal(m)
+ if err != nil {
+ return err
+ }
+ // write up until the final }
+ if _, err = buf.Write(b[:len(b)-1]); err != nil {
+ return err
+ }
+ if len(m.Extra) > 0 {
+ eb, err := json.Marshal(m.Extra)
+ if err != nil {
+ return err
+ }
+ // merge serialized message + serialized extra map
+ if err = buf.WriteByte(','); err != nil {
+ return err
+ }
+ // write serialized extra bytes, without enclosing quotes
+ if _, err = buf.Write(eb[1 : len(eb)-1]); err != nil {
+ return err
+ }
+ }
+
+ if len(m.RawExtra) > 0 {
+ if err := buf.WriteByte(','); err != nil {
+ return err
+ }
+
+ // write serialized extra bytes, without enclosing quotes
+ if _, err = buf.Write(m.RawExtra[1 : len(m.RawExtra)-1]); err != nil {
+ return err
+ }
+ }
+
+ // write final closing quotes
+ return buf.WriteByte('}')
+}
+
+func (m *Message) UnmarshalJSON(data []byte) error {
+ i := make(map[string]interface{}, 16)
+ if err := json.Unmarshal(data, &i); err != nil {
+ return err
+ }
+ for k, v := range i {
+ if k[0] == '_' {
+ if m.Extra == nil {
+ m.Extra = make(map[string]interface{}, 1)
+ }
+ m.Extra[k] = v
+ continue
+ }
+ switch k {
+ case "version":
+ m.Version = v.(string)
+ case "host":
+ m.Host = v.(string)
+ case "short_message":
+ m.Short = v.(string)
+ case "full_message":
+ m.Full = v.(string)
+ case "timestamp":
+ m.TimeUnix = v.(float64)
+ case "level":
+ m.Level = int32(v.(float64))
+ case "facility":
+ m.Facility = v.(string)
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/go-winio/LICENSE b/vendor/github.com/Microsoft/go-winio/LICENSE
new file mode 100644
index 0000000..b8b569d
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/LICENSE
@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 Microsoft
+
+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/Microsoft/go-winio/README.md b/vendor/github.com/Microsoft/go-winio/README.md
new file mode 100644
index 0000000..5680010
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/README.md
@@ -0,0 +1,22 @@
+# go-winio
+
+This repository contains utilities for efficiently performing Win32 IO operations in
+Go. Currently, this is focused on accessing named pipes and other file handles, and
+for using named pipes as a net transport.
+
+This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go
+to reuse the thread to schedule another goroutine. This limits support to Windows Vista and
+newer operating systems. This is similar to the implementation of network sockets in Go's net
+package.
+
+Please see the LICENSE file for licensing information.
+
+This project has adopted the [Microsoft Open Source Code of
+Conduct](https://opensource.microsoft.com/codeofconduct/). For more information
+see the [Code of Conduct
+FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact
+[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional
+questions or comments.
+
+Thanks to natefinch for the inspiration for this library. See https://github.com/natefinch/npipe
+for another named pipe implementation.
diff --git a/vendor/github.com/Microsoft/go-winio/archive/tar/LICENSE b/vendor/github.com/Microsoft/go-winio/archive/tar/LICENSE
new file mode 100644
index 0000000..7448756
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/archive/tar/LICENSE
@@ -0,0 +1,27 @@
+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/Microsoft/go-winio/archive/tar/common.go b/vendor/github.com/Microsoft/go-winio/archive/tar/common.go
new file mode 100644
index 0000000..0378401
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/archive/tar/common.go
@@ -0,0 +1,344 @@
+// Copyright 2009 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 tar implements access to tar archives.
+// It aims to cover most of the variations, including those produced
+// by GNU and BSD tars.
+//
+// References:
+// http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
+// http://www.gnu.org/software/tar/manual/html_node/Standard.html
+// http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html
+package tar
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "os"
+ "path"
+ "time"
+)
+
+const (
+ blockSize = 512
+
+ // Types
+ TypeReg = '0' // regular file
+ TypeRegA = '\x00' // regular file
+ TypeLink = '1' // hard link
+ TypeSymlink = '2' // symbolic link
+ TypeChar = '3' // character device node
+ TypeBlock = '4' // block device node
+ TypeDir = '5' // directory
+ TypeFifo = '6' // fifo node
+ TypeCont = '7' // reserved
+ TypeXHeader = 'x' // extended header
+ TypeXGlobalHeader = 'g' // global extended header
+ TypeGNULongName = 'L' // Next file has a long name
+ TypeGNULongLink = 'K' // Next file symlinks to a file w/ a long name
+ TypeGNUSparse = 'S' // sparse file
+)
+
+// A Header represents a single header in a tar archive.
+// Some fields may not be populated.
+type Header struct {
+ Name string // name of header file entry
+ Mode int64 // permission and mode bits
+ Uid int // user id of owner
+ Gid int // group id of owner
+ Size int64 // length in bytes
+ ModTime time.Time // modified time
+ Typeflag byte // type of header entry
+ Linkname string // target name of link
+ Uname string // user name of owner
+ Gname string // group name of owner
+ Devmajor int64 // major number of character or block device
+ Devminor int64 // minor number of character or block device
+ AccessTime time.Time // access time
+ ChangeTime time.Time // status change time
+ CreationTime time.Time // creation time
+ Xattrs map[string]string
+ Winheaders map[string]string
+}
+
+// File name constants from the tar spec.
+const (
+ fileNameSize = 100 // Maximum number of bytes in a standard tar name.
+ fileNamePrefixSize = 155 // Maximum number of ustar extension bytes.
+)
+
+// FileInfo returns an os.FileInfo for the Header.
+func (h *Header) FileInfo() os.FileInfo {
+ return headerFileInfo{h}
+}
+
+// headerFileInfo implements os.FileInfo.
+type headerFileInfo struct {
+ h *Header
+}
+
+func (fi headerFileInfo) Size() int64 { return fi.h.Size }
+func (fi headerFileInfo) IsDir() bool { return fi.Mode().IsDir() }
+func (fi headerFileInfo) ModTime() time.Time { return fi.h.ModTime }
+func (fi headerFileInfo) Sys() interface{} { return fi.h }
+
+// Name returns the base name of the file.
+func (fi headerFileInfo) Name() string {
+ if fi.IsDir() {
+ return path.Base(path.Clean(fi.h.Name))
+ }
+ return path.Base(fi.h.Name)
+}
+
+// Mode returns the permission and mode bits for the headerFileInfo.
+func (fi headerFileInfo) Mode() (mode os.FileMode) {
+ // Set file permission bits.
+ mode = os.FileMode(fi.h.Mode).Perm()
+
+ // Set setuid, setgid and sticky bits.
+ if fi.h.Mode&c_ISUID != 0 {
+ // setuid
+ mode |= os.ModeSetuid
+ }
+ if fi.h.Mode&c_ISGID != 0 {
+ // setgid
+ mode |= os.ModeSetgid
+ }
+ if fi.h.Mode&c_ISVTX != 0 {
+ // sticky
+ mode |= os.ModeSticky
+ }
+
+ // Set file mode bits.
+ // clear perm, setuid, setgid and sticky bits.
+ m := os.FileMode(fi.h.Mode) &^ 07777
+ if m == c_ISDIR {
+ // directory
+ mode |= os.ModeDir
+ }
+ if m == c_ISFIFO {
+ // named pipe (FIFO)
+ mode |= os.ModeNamedPipe
+ }
+ if m == c_ISLNK {
+ // symbolic link
+ mode |= os.ModeSymlink
+ }
+ if m == c_ISBLK {
+ // device file
+ mode |= os.ModeDevice
+ }
+ if m == c_ISCHR {
+ // Unix character device
+ mode |= os.ModeDevice
+ mode |= os.ModeCharDevice
+ }
+ if m == c_ISSOCK {
+ // Unix domain socket
+ mode |= os.ModeSocket
+ }
+
+ switch fi.h.Typeflag {
+ case TypeSymlink:
+ // symbolic link
+ mode |= os.ModeSymlink
+ case TypeChar:
+ // character device node
+ mode |= os.ModeDevice
+ mode |= os.ModeCharDevice
+ case TypeBlock:
+ // block device node
+ mode |= os.ModeDevice
+ case TypeDir:
+ // directory
+ mode |= os.ModeDir
+ case TypeFifo:
+ // fifo node
+ mode |= os.ModeNamedPipe
+ }
+
+ return mode
+}
+
+// sysStat, if non-nil, populates h from system-dependent fields of fi.
+var sysStat func(fi os.FileInfo, h *Header) error
+
+// Mode constants from the tar spec.
+const (
+ c_ISUID = 04000 // Set uid
+ c_ISGID = 02000 // Set gid
+ c_ISVTX = 01000 // Save text (sticky bit)
+ c_ISDIR = 040000 // Directory
+ c_ISFIFO = 010000 // FIFO
+ c_ISREG = 0100000 // Regular file
+ c_ISLNK = 0120000 // Symbolic link
+ c_ISBLK = 060000 // Block special file
+ c_ISCHR = 020000 // Character special file
+ c_ISSOCK = 0140000 // Socket
+)
+
+// Keywords for the PAX Extended Header
+const (
+ paxAtime = "atime"
+ paxCharset = "charset"
+ paxComment = "comment"
+ paxCtime = "ctime" // please note that ctime is not a valid pax header.
+ paxCreationTime = "LIBARCHIVE.creationtime"
+ paxGid = "gid"
+ paxGname = "gname"
+ paxLinkpath = "linkpath"
+ paxMtime = "mtime"
+ paxPath = "path"
+ paxSize = "size"
+ paxUid = "uid"
+ paxUname = "uname"
+ paxXattr = "SCHILY.xattr."
+ paxWindows = "MSWINDOWS."
+ paxNone = ""
+)
+
+// FileInfoHeader creates a partially-populated Header from fi.
+// If fi describes a symlink, FileInfoHeader records link as the link target.
+// If fi describes a directory, a slash is appended to the name.
+// Because os.FileInfo's Name method returns only the base name of
+// the file it describes, it may be necessary to modify the Name field
+// of the returned header to provide the full path name of the file.
+func FileInfoHeader(fi os.FileInfo, link string) (*Header, error) {
+ if fi == nil {
+ return nil, errors.New("tar: FileInfo is nil")
+ }
+ fm := fi.Mode()
+ h := &Header{
+ Name: fi.Name(),
+ ModTime: fi.ModTime(),
+ Mode: int64(fm.Perm()), // or'd with c_IS* constants later
+ }
+ switch {
+ case fm.IsRegular():
+ h.Mode |= c_ISREG
+ h.Typeflag = TypeReg
+ h.Size = fi.Size()
+ case fi.IsDir():
+ h.Typeflag = TypeDir
+ h.Mode |= c_ISDIR
+ h.Name += "/"
+ case fm&os.ModeSymlink != 0:
+ h.Typeflag = TypeSymlink
+ h.Mode |= c_ISLNK
+ h.Linkname = link
+ case fm&os.ModeDevice != 0:
+ if fm&os.ModeCharDevice != 0 {
+ h.Mode |= c_ISCHR
+ h.Typeflag = TypeChar
+ } else {
+ h.Mode |= c_ISBLK
+ h.Typeflag = TypeBlock
+ }
+ case fm&os.ModeNamedPipe != 0:
+ h.Typeflag = TypeFifo
+ h.Mode |= c_ISFIFO
+ case fm&os.ModeSocket != 0:
+ h.Mode |= c_ISSOCK
+ default:
+ return nil, fmt.Errorf("archive/tar: unknown file mode %v", fm)
+ }
+ if fm&os.ModeSetuid != 0 {
+ h.Mode |= c_ISUID
+ }
+ if fm&os.ModeSetgid != 0 {
+ h.Mode |= c_ISGID
+ }
+ if fm&os.ModeSticky != 0 {
+ h.Mode |= c_ISVTX
+ }
+ // If possible, populate additional fields from OS-specific
+ // FileInfo fields.
+ if sys, ok := fi.Sys().(*Header); ok {
+ // This FileInfo came from a Header (not the OS). Use the
+ // original Header to populate all remaining fields.
+ h.Uid = sys.Uid
+ h.Gid = sys.Gid
+ h.Uname = sys.Uname
+ h.Gname = sys.Gname
+ h.AccessTime = sys.AccessTime
+ h.ChangeTime = sys.ChangeTime
+ if sys.Xattrs != nil {
+ h.Xattrs = make(map[string]string)
+ for k, v := range sys.Xattrs {
+ h.Xattrs[k] = v
+ }
+ }
+ if sys.Typeflag == TypeLink {
+ // hard link
+ h.Typeflag = TypeLink
+ h.Size = 0
+ h.Linkname = sys.Linkname
+ }
+ }
+ if sysStat != nil {
+ return h, sysStat(fi, h)
+ }
+ return h, nil
+}
+
+var zeroBlock = make([]byte, blockSize)
+
+// POSIX specifies a sum of the unsigned byte values, but the Sun tar uses signed byte values.
+// We compute and return both.
+func checksum(header []byte) (unsigned int64, signed int64) {
+ for i := 0; i < len(header); i++ {
+ if i == 148 {
+ // The chksum field (header[148:156]) is special: it should be treated as space bytes.
+ unsigned += ' ' * 8
+ signed += ' ' * 8
+ i += 7
+ continue
+ }
+ unsigned += int64(header[i])
+ signed += int64(int8(header[i]))
+ }
+ return
+}
+
+type slicer []byte
+
+func (sp *slicer) next(n int) (b []byte) {
+ s := *sp
+ b, *sp = s[0:n], s[n:]
+ return
+}
+
+func isASCII(s string) bool {
+ for _, c := range s {
+ if c >= 0x80 {
+ return false
+ }
+ }
+ return true
+}
+
+func toASCII(s string) string {
+ if isASCII(s) {
+ return s
+ }
+ var buf bytes.Buffer
+ for _, c := range s {
+ if c < 0x80 {
+ buf.WriteByte(byte(c))
+ }
+ }
+ return buf.String()
+}
+
+// isHeaderOnlyType checks if the given type flag is of the type that has no
+// data section even if a size is specified.
+func isHeaderOnlyType(flag byte) bool {
+ switch flag {
+ case TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, TypeFifo:
+ return true
+ default:
+ return false
+ }
+}
diff --git a/vendor/github.com/Microsoft/go-winio/archive/tar/reader.go b/vendor/github.com/Microsoft/go-winio/archive/tar/reader.go
new file mode 100644
index 0000000..e210c61
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/archive/tar/reader.go
@@ -0,0 +1,1002 @@
+// Copyright 2009 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 tar
+
+// TODO(dsymonds):
+// - pax extensions
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "io/ioutil"
+ "math"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var (
+ ErrHeader = errors.New("archive/tar: invalid tar header")
+)
+
+const maxNanoSecondIntSize = 9
+
+// A Reader provides sequential access to the contents of a tar archive.
+// A tar archive consists of a sequence of files.
+// The Next method advances to the next file in the archive (including the first),
+// and then it can be treated as an io.Reader to access the file's data.
+type Reader struct {
+ r io.Reader
+ err error
+ pad int64 // amount of padding (ignored) after current file entry
+ curr numBytesReader // reader for current file entry
+ hdrBuff [blockSize]byte // buffer to use in readHeader
+}
+
+type parser struct {
+ err error // Last error seen
+}
+
+// A numBytesReader is an io.Reader with a numBytes method, returning the number
+// of bytes remaining in the underlying encoded data.
+type numBytesReader interface {
+ io.Reader
+ numBytes() int64
+}
+
+// A regFileReader is a numBytesReader for reading file data from a tar archive.
+type regFileReader struct {
+ r io.Reader // underlying reader
+ nb int64 // number of unread bytes for current file entry
+}
+
+// A sparseFileReader is a numBytesReader for reading sparse file data from a
+// tar archive.
+type sparseFileReader struct {
+ rfr numBytesReader // Reads the sparse-encoded file data
+ sp []sparseEntry // The sparse map for the file
+ pos int64 // Keeps track of file position
+ total int64 // Total size of the file
+}
+
+// A sparseEntry holds a single entry in a sparse file's sparse map.
+//
+// Sparse files are represented using a series of sparseEntrys.
+// Despite the name, a sparseEntry represents an actual data fragment that
+// references data found in the underlying archive stream. All regions not
+// covered by a sparseEntry are logically filled with zeros.
+//
+// For example, if the underlying raw file contains the 10-byte data:
+// var compactData = "abcdefgh"
+//
+// And the sparse map has the following entries:
+// var sp = []sparseEntry{
+// {offset: 2, numBytes: 5} // Data fragment for [2..7]
+// {offset: 18, numBytes: 3} // Data fragment for [18..21]
+// }
+//
+// Then the content of the resulting sparse file with a "real" size of 25 is:
+// var sparseData = "\x00"*2 + "abcde" + "\x00"*11 + "fgh" + "\x00"*4
+type sparseEntry struct {
+ offset int64 // Starting position of the fragment
+ numBytes int64 // Length of the fragment
+}
+
+// Keywords for GNU sparse files in a PAX extended header
+const (
+ paxGNUSparseNumBlocks = "GNU.sparse.numblocks"
+ paxGNUSparseOffset = "GNU.sparse.offset"
+ paxGNUSparseNumBytes = "GNU.sparse.numbytes"
+ paxGNUSparseMap = "GNU.sparse.map"
+ paxGNUSparseName = "GNU.sparse.name"
+ paxGNUSparseMajor = "GNU.sparse.major"
+ paxGNUSparseMinor = "GNU.sparse.minor"
+ paxGNUSparseSize = "GNU.sparse.size"
+ paxGNUSparseRealSize = "GNU.sparse.realsize"
+)
+
+// Keywords for old GNU sparse headers
+const (
+ oldGNUSparseMainHeaderOffset = 386
+ oldGNUSparseMainHeaderIsExtendedOffset = 482
+ oldGNUSparseMainHeaderNumEntries = 4
+ oldGNUSparseExtendedHeaderIsExtendedOffset = 504
+ oldGNUSparseExtendedHeaderNumEntries = 21
+ oldGNUSparseOffsetSize = 12
+ oldGNUSparseNumBytesSize = 12
+)
+
+// NewReader creates a new Reader reading from r.
+func NewReader(r io.Reader) *Reader { return &Reader{r: r} }
+
+// Next advances to the next entry in the tar archive.
+//
+// io.EOF is returned at the end of the input.
+func (tr *Reader) Next() (*Header, error) {
+ if tr.err != nil {
+ return nil, tr.err
+ }
+
+ var hdr *Header
+ var extHdrs map[string]string
+
+ // Externally, Next iterates through the tar archive as if it is a series of
+ // files. Internally, the tar format often uses fake "files" to add meta
+ // data that describes the next file. These meta data "files" should not
+ // normally be visible to the outside. As such, this loop iterates through
+ // one or more "header files" until it finds a "normal file".
+loop:
+ for {
+ tr.err = tr.skipUnread()
+ if tr.err != nil {
+ return nil, tr.err
+ }
+
+ hdr = tr.readHeader()
+ if tr.err != nil {
+ return nil, tr.err
+ }
+
+ // Check for PAX/GNU special headers and files.
+ switch hdr.Typeflag {
+ case TypeXHeader:
+ extHdrs, tr.err = parsePAX(tr)
+ if tr.err != nil {
+ return nil, tr.err
+ }
+ continue loop // This is a meta header affecting the next header
+ case TypeGNULongName, TypeGNULongLink:
+ var realname []byte
+ realname, tr.err = ioutil.ReadAll(tr)
+ if tr.err != nil {
+ return nil, tr.err
+ }
+
+ // Convert GNU extensions to use PAX headers.
+ if extHdrs == nil {
+ extHdrs = make(map[string]string)
+ }
+ var p parser
+ switch hdr.Typeflag {
+ case TypeGNULongName:
+ extHdrs[paxPath] = p.parseString(realname)
+ case TypeGNULongLink:
+ extHdrs[paxLinkpath] = p.parseString(realname)
+ }
+ if p.err != nil {
+ tr.err = p.err
+ return nil, tr.err
+ }
+ continue loop // This is a meta header affecting the next header
+ default:
+ mergePAX(hdr, extHdrs)
+
+ // Check for a PAX format sparse file
+ sp, err := tr.checkForGNUSparsePAXHeaders(hdr, extHdrs)
+ if err != nil {
+ tr.err = err
+ return nil, err
+ }
+ if sp != nil {
+ // Current file is a PAX format GNU sparse file.
+ // Set the current file reader to a sparse file reader.
+ tr.curr, tr.err = newSparseFileReader(tr.curr, sp, hdr.Size)
+ if tr.err != nil {
+ return nil, tr.err
+ }
+ }
+ break loop // This is a file, so stop
+ }
+ }
+ return hdr, nil
+}
+
+// checkForGNUSparsePAXHeaders checks the PAX headers for GNU sparse headers. If they are found, then
+// this function reads the sparse map and returns it. Unknown sparse formats are ignored, causing the file to
+// be treated as a regular file.
+func (tr *Reader) checkForGNUSparsePAXHeaders(hdr *Header, headers map[string]string) ([]sparseEntry, error) {
+ var sparseFormat string
+
+ // Check for sparse format indicators
+ major, majorOk := headers[paxGNUSparseMajor]
+ minor, minorOk := headers[paxGNUSparseMinor]
+ sparseName, sparseNameOk := headers[paxGNUSparseName]
+ _, sparseMapOk := headers[paxGNUSparseMap]
+ sparseSize, sparseSizeOk := headers[paxGNUSparseSize]
+ sparseRealSize, sparseRealSizeOk := headers[paxGNUSparseRealSize]
+
+ // Identify which, if any, sparse format applies from which PAX headers are set
+ if majorOk && minorOk {
+ sparseFormat = major + "." + minor
+ } else if sparseNameOk && sparseMapOk {
+ sparseFormat = "0.1"
+ } else if sparseSizeOk {
+ sparseFormat = "0.0"
+ } else {
+ // Not a PAX format GNU sparse file.
+ return nil, nil
+ }
+
+ // Check for unknown sparse format
+ if sparseFormat != "0.0" && sparseFormat != "0.1" && sparseFormat != "1.0" {
+ return nil, nil
+ }
+
+ // Update hdr from GNU sparse PAX headers
+ if sparseNameOk {
+ hdr.Name = sparseName
+ }
+ if sparseSizeOk {
+ realSize, err := strconv.ParseInt(sparseSize, 10, 0)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ hdr.Size = realSize
+ } else if sparseRealSizeOk {
+ realSize, err := strconv.ParseInt(sparseRealSize, 10, 0)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ hdr.Size = realSize
+ }
+
+ // Set up the sparse map, according to the particular sparse format in use
+ var sp []sparseEntry
+ var err error
+ switch sparseFormat {
+ case "0.0", "0.1":
+ sp, err = readGNUSparseMap0x1(headers)
+ case "1.0":
+ sp, err = readGNUSparseMap1x0(tr.curr)
+ }
+ return sp, err
+}
+
+// mergePAX merges well known headers according to PAX standard.
+// In general headers with the same name as those found
+// in the header struct overwrite those found in the header
+// struct with higher precision or longer values. Esp. useful
+// for name and linkname fields.
+func mergePAX(hdr *Header, headers map[string]string) error {
+ for k, v := range headers {
+ switch k {
+ case paxPath:
+ hdr.Name = v
+ case paxLinkpath:
+ hdr.Linkname = v
+ case paxGname:
+ hdr.Gname = v
+ case paxUname:
+ hdr.Uname = v
+ case paxUid:
+ uid, err := strconv.ParseInt(v, 10, 0)
+ if err != nil {
+ return err
+ }
+ hdr.Uid = int(uid)
+ case paxGid:
+ gid, err := strconv.ParseInt(v, 10, 0)
+ if err != nil {
+ return err
+ }
+ hdr.Gid = int(gid)
+ case paxAtime:
+ t, err := parsePAXTime(v)
+ if err != nil {
+ return err
+ }
+ hdr.AccessTime = t
+ case paxMtime:
+ t, err := parsePAXTime(v)
+ if err != nil {
+ return err
+ }
+ hdr.ModTime = t
+ case paxCtime:
+ t, err := parsePAXTime(v)
+ if err != nil {
+ return err
+ }
+ hdr.ChangeTime = t
+ case paxCreationTime:
+ t, err := parsePAXTime(v)
+ if err != nil {
+ return err
+ }
+ hdr.CreationTime = t
+ case paxSize:
+ size, err := strconv.ParseInt(v, 10, 0)
+ if err != nil {
+ return err
+ }
+ hdr.Size = int64(size)
+ default:
+ if strings.HasPrefix(k, paxXattr) {
+ if hdr.Xattrs == nil {
+ hdr.Xattrs = make(map[string]string)
+ }
+ hdr.Xattrs[k[len(paxXattr):]] = v
+ } else if strings.HasPrefix(k, paxWindows) {
+ if hdr.Winheaders == nil {
+ hdr.Winheaders = make(map[string]string)
+ }
+ hdr.Winheaders[k[len(paxWindows):]] = v
+ }
+ }
+ }
+ return nil
+}
+
+// parsePAXTime takes a string of the form %d.%d as described in
+// the PAX specification.
+func parsePAXTime(t string) (time.Time, error) {
+ buf := []byte(t)
+ pos := bytes.IndexByte(buf, '.')
+ var seconds, nanoseconds int64
+ var err error
+ if pos == -1 {
+ seconds, err = strconv.ParseInt(t, 10, 0)
+ if err != nil {
+ return time.Time{}, err
+ }
+ } else {
+ seconds, err = strconv.ParseInt(string(buf[:pos]), 10, 0)
+ if err != nil {
+ return time.Time{}, err
+ }
+ nano_buf := string(buf[pos+1:])
+ // Pad as needed before converting to a decimal.
+ // For example .030 -> .030000000 -> 30000000 nanoseconds
+ if len(nano_buf) < maxNanoSecondIntSize {
+ // Right pad
+ nano_buf += strings.Repeat("0", maxNanoSecondIntSize-len(nano_buf))
+ } else if len(nano_buf) > maxNanoSecondIntSize {
+ // Right truncate
+ nano_buf = nano_buf[:maxNanoSecondIntSize]
+ }
+ nanoseconds, err = strconv.ParseInt(string(nano_buf), 10, 0)
+ if err != nil {
+ return time.Time{}, err
+ }
+ }
+ ts := time.Unix(seconds, nanoseconds)
+ return ts, nil
+}
+
+// parsePAX parses PAX headers.
+// If an extended header (type 'x') is invalid, ErrHeader is returned
+func parsePAX(r io.Reader) (map[string]string, error) {
+ buf, err := ioutil.ReadAll(r)
+ if err != nil {
+ return nil, err
+ }
+ sbuf := string(buf)
+
+ // For GNU PAX sparse format 0.0 support.
+ // This function transforms the sparse format 0.0 headers into sparse format 0.1 headers.
+ var sparseMap bytes.Buffer
+
+ headers := make(map[string]string)
+ // Each record is constructed as
+ // "%d %s=%s\n", length, keyword, value
+ for len(sbuf) > 0 {
+ key, value, residual, err := parsePAXRecord(sbuf)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ sbuf = residual
+
+ keyStr := string(key)
+ if keyStr == paxGNUSparseOffset || keyStr == paxGNUSparseNumBytes {
+ // GNU sparse format 0.0 special key. Write to sparseMap instead of using the headers map.
+ sparseMap.WriteString(value)
+ sparseMap.Write([]byte{','})
+ } else {
+ // Normal key. Set the value in the headers map.
+ headers[keyStr] = string(value)
+ }
+ }
+ if sparseMap.Len() != 0 {
+ // Add sparse info to headers, chopping off the extra comma
+ sparseMap.Truncate(sparseMap.Len() - 1)
+ headers[paxGNUSparseMap] = sparseMap.String()
+ }
+ return headers, nil
+}
+
+// parsePAXRecord parses the input PAX record string into a key-value pair.
+// If parsing is successful, it will slice off the currently read record and
+// return the remainder as r.
+//
+// A PAX record is of the following form:
+// "%d %s=%s\n" % (size, key, value)
+func parsePAXRecord(s string) (k, v, r string, err error) {
+ // The size field ends at the first space.
+ sp := strings.IndexByte(s, ' ')
+ if sp == -1 {
+ return "", "", s, ErrHeader
+ }
+
+ // Parse the first token as a decimal integer.
+ n, perr := strconv.ParseInt(s[:sp], 10, 0) // Intentionally parse as native int
+ if perr != nil || n < 5 || int64(len(s)) < n {
+ return "", "", s, ErrHeader
+ }
+
+ // Extract everything between the space and the final newline.
+ rec, nl, rem := s[sp+1:n-1], s[n-1:n], s[n:]
+ if nl != "\n" {
+ return "", "", s, ErrHeader
+ }
+
+ // The first equals separates the key from the value.
+ eq := strings.IndexByte(rec, '=')
+ if eq == -1 {
+ return "", "", s, ErrHeader
+ }
+ return rec[:eq], rec[eq+1:], rem, nil
+}
+
+// parseString parses bytes as a NUL-terminated C-style string.
+// If a NUL byte is not found then the whole slice is returned as a string.
+func (*parser) parseString(b []byte) string {
+ n := 0
+ for n < len(b) && b[n] != 0 {
+ n++
+ }
+ return string(b[0:n])
+}
+
+// parseNumeric parses the input as being encoded in either base-256 or octal.
+// This function may return negative numbers.
+// If parsing fails or an integer overflow occurs, err will be set.
+func (p *parser) parseNumeric(b []byte) int64 {
+ // Check for base-256 (binary) format first.
+ // If the first bit is set, then all following bits constitute a two's
+ // complement encoded number in big-endian byte order.
+ if len(b) > 0 && b[0]&0x80 != 0 {
+ // Handling negative numbers relies on the following identity:
+ // -a-1 == ^a
+ //
+ // If the number is negative, we use an inversion mask to invert the
+ // data bytes and treat the value as an unsigned number.
+ var inv byte // 0x00 if positive or zero, 0xff if negative
+ if b[0]&0x40 != 0 {
+ inv = 0xff
+ }
+
+ var x uint64
+ for i, c := range b {
+ c ^= inv // Inverts c only if inv is 0xff, otherwise does nothing
+ if i == 0 {
+ c &= 0x7f // Ignore signal bit in first byte
+ }
+ if (x >> 56) > 0 {
+ p.err = ErrHeader // Integer overflow
+ return 0
+ }
+ x = x<<8 | uint64(c)
+ }
+ if (x >> 63) > 0 {
+ p.err = ErrHeader // Integer overflow
+ return 0
+ }
+ if inv == 0xff {
+ return ^int64(x)
+ }
+ return int64(x)
+ }
+
+ // Normal case is base-8 (octal) format.
+ return p.parseOctal(b)
+}
+
+func (p *parser) parseOctal(b []byte) int64 {
+ // Because unused fields are filled with NULs, we need
+ // to skip leading NULs. Fields may also be padded with
+ // spaces or NULs.
+ // So we remove leading and trailing NULs and spaces to
+ // be sure.
+ b = bytes.Trim(b, " \x00")
+
+ if len(b) == 0 {
+ return 0
+ }
+ x, perr := strconv.ParseUint(p.parseString(b), 8, 64)
+ if perr != nil {
+ p.err = ErrHeader
+ }
+ return int64(x)
+}
+
+// skipUnread skips any unread bytes in the existing file entry, as well as any
+// alignment padding. It returns io.ErrUnexpectedEOF if any io.EOF is
+// encountered in the data portion; it is okay to hit io.EOF in the padding.
+//
+// Note that this function still works properly even when sparse files are being
+// used since numBytes returns the bytes remaining in the underlying io.Reader.
+func (tr *Reader) skipUnread() error {
+ dataSkip := tr.numBytes() // Number of data bytes to skip
+ totalSkip := dataSkip + tr.pad // Total number of bytes to skip
+ tr.curr, tr.pad = nil, 0
+
+ // If possible, Seek to the last byte before the end of the data section.
+ // Do this because Seek is often lazy about reporting errors; this will mask
+ // the fact that the tar stream may be truncated. We can rely on the
+ // io.CopyN done shortly afterwards to trigger any IO errors.
+ var seekSkipped int64 // Number of bytes skipped via Seek
+ if sr, ok := tr.r.(io.Seeker); ok && dataSkip > 1 {
+ // Not all io.Seeker can actually Seek. For example, os.Stdin implements
+ // io.Seeker, but calling Seek always returns an error and performs
+ // no action. Thus, we try an innocent seek to the current position
+ // to see if Seek is really supported.
+ pos1, err := sr.Seek(0, os.SEEK_CUR)
+ if err == nil {
+ // Seek seems supported, so perform the real Seek.
+ pos2, err := sr.Seek(dataSkip-1, os.SEEK_CUR)
+ if err != nil {
+ tr.err = err
+ return tr.err
+ }
+ seekSkipped = pos2 - pos1
+ }
+ }
+
+ var copySkipped int64 // Number of bytes skipped via CopyN
+ copySkipped, tr.err = io.CopyN(ioutil.Discard, tr.r, totalSkip-seekSkipped)
+ if tr.err == io.EOF && seekSkipped+copySkipped < dataSkip {
+ tr.err = io.ErrUnexpectedEOF
+ }
+ return tr.err
+}
+
+func (tr *Reader) verifyChecksum(header []byte) bool {
+ if tr.err != nil {
+ return false
+ }
+
+ var p parser
+ given := p.parseOctal(header[148:156])
+ unsigned, signed := checksum(header)
+ return p.err == nil && (given == unsigned || given == signed)
+}
+
+// readHeader reads the next block header and assumes that the underlying reader
+// is already aligned to a block boundary.
+//
+// The err will be set to io.EOF only when one of the following occurs:
+// * Exactly 0 bytes are read and EOF is hit.
+// * Exactly 1 block of zeros is read and EOF is hit.
+// * At least 2 blocks of zeros are read.
+func (tr *Reader) readHeader() *Header {
+ header := tr.hdrBuff[:]
+ copy(header, zeroBlock)
+
+ if _, tr.err = io.ReadFull(tr.r, header); tr.err != nil {
+ return nil // io.EOF is okay here
+ }
+
+ // Two blocks of zero bytes marks the end of the archive.
+ if bytes.Equal(header, zeroBlock[0:blockSize]) {
+ if _, tr.err = io.ReadFull(tr.r, header); tr.err != nil {
+ return nil // io.EOF is okay here
+ }
+ if bytes.Equal(header, zeroBlock[0:blockSize]) {
+ tr.err = io.EOF
+ } else {
+ tr.err = ErrHeader // zero block and then non-zero block
+ }
+ return nil
+ }
+
+ if !tr.verifyChecksum(header) {
+ tr.err = ErrHeader
+ return nil
+ }
+
+ // Unpack
+ var p parser
+ hdr := new(Header)
+ s := slicer(header)
+
+ hdr.Name = p.parseString(s.next(100))
+ hdr.Mode = p.parseNumeric(s.next(8))
+ hdr.Uid = int(p.parseNumeric(s.next(8)))
+ hdr.Gid = int(p.parseNumeric(s.next(8)))
+ hdr.Size = p.parseNumeric(s.next(12))
+ hdr.ModTime = time.Unix(p.parseNumeric(s.next(12)), 0)
+ s.next(8) // chksum
+ hdr.Typeflag = s.next(1)[0]
+ hdr.Linkname = p.parseString(s.next(100))
+
+ // The remainder of the header depends on the value of magic.
+ // The original (v7) version of tar had no explicit magic field,
+ // so its magic bytes, like the rest of the block, are NULs.
+ magic := string(s.next(8)) // contains version field as well.
+ var format string
+ switch {
+ case magic[:6] == "ustar\x00": // POSIX tar (1003.1-1988)
+ if string(header[508:512]) == "tar\x00" {
+ format = "star"
+ } else {
+ format = "posix"
+ }
+ case magic == "ustar \x00": // old GNU tar
+ format = "gnu"
+ }
+
+ switch format {
+ case "posix", "gnu", "star":
+ hdr.Uname = p.parseString(s.next(32))
+ hdr.Gname = p.parseString(s.next(32))
+ devmajor := s.next(8)
+ devminor := s.next(8)
+ if hdr.Typeflag == TypeChar || hdr.Typeflag == TypeBlock {
+ hdr.Devmajor = p.parseNumeric(devmajor)
+ hdr.Devminor = p.parseNumeric(devminor)
+ }
+ var prefix string
+ switch format {
+ case "posix", "gnu":
+ prefix = p.parseString(s.next(155))
+ case "star":
+ prefix = p.parseString(s.next(131))
+ hdr.AccessTime = time.Unix(p.parseNumeric(s.next(12)), 0)
+ hdr.ChangeTime = time.Unix(p.parseNumeric(s.next(12)), 0)
+ }
+ if len(prefix) > 0 {
+ hdr.Name = prefix + "/" + hdr.Name
+ }
+ }
+
+ if p.err != nil {
+ tr.err = p.err
+ return nil
+ }
+
+ nb := hdr.Size
+ if isHeaderOnlyType(hdr.Typeflag) {
+ nb = 0
+ }
+ if nb < 0 {
+ tr.err = ErrHeader
+ return nil
+ }
+
+ // Set the current file reader.
+ tr.pad = -nb & (blockSize - 1) // blockSize is a power of two
+ tr.curr = &regFileReader{r: tr.r, nb: nb}
+
+ // Check for old GNU sparse format entry.
+ if hdr.Typeflag == TypeGNUSparse {
+ // Get the real size of the file.
+ hdr.Size = p.parseNumeric(header[483:495])
+ if p.err != nil {
+ tr.err = p.err
+ return nil
+ }
+
+ // Read the sparse map.
+ sp := tr.readOldGNUSparseMap(header)
+ if tr.err != nil {
+ return nil
+ }
+
+ // Current file is a GNU sparse file. Update the current file reader.
+ tr.curr, tr.err = newSparseFileReader(tr.curr, sp, hdr.Size)
+ if tr.err != nil {
+ return nil
+ }
+ }
+
+ return hdr
+}
+
+// readOldGNUSparseMap reads the sparse map as stored in the old GNU sparse format.
+// The sparse map is stored in the tar header if it's small enough. If it's larger than four entries,
+// then one or more extension headers are used to store the rest of the sparse map.
+func (tr *Reader) readOldGNUSparseMap(header []byte) []sparseEntry {
+ var p parser
+ isExtended := header[oldGNUSparseMainHeaderIsExtendedOffset] != 0
+ spCap := oldGNUSparseMainHeaderNumEntries
+ if isExtended {
+ spCap += oldGNUSparseExtendedHeaderNumEntries
+ }
+ sp := make([]sparseEntry, 0, spCap)
+ s := slicer(header[oldGNUSparseMainHeaderOffset:])
+
+ // Read the four entries from the main tar header
+ for i := 0; i < oldGNUSparseMainHeaderNumEntries; i++ {
+ offset := p.parseNumeric(s.next(oldGNUSparseOffsetSize))
+ numBytes := p.parseNumeric(s.next(oldGNUSparseNumBytesSize))
+ if p.err != nil {
+ tr.err = p.err
+ return nil
+ }
+ if offset == 0 && numBytes == 0 {
+ break
+ }
+ sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
+ }
+
+ for isExtended {
+ // There are more entries. Read an extension header and parse its entries.
+ sparseHeader := make([]byte, blockSize)
+ if _, tr.err = io.ReadFull(tr.r, sparseHeader); tr.err != nil {
+ return nil
+ }
+ isExtended = sparseHeader[oldGNUSparseExtendedHeaderIsExtendedOffset] != 0
+ s = slicer(sparseHeader)
+ for i := 0; i < oldGNUSparseExtendedHeaderNumEntries; i++ {
+ offset := p.parseNumeric(s.next(oldGNUSparseOffsetSize))
+ numBytes := p.parseNumeric(s.next(oldGNUSparseNumBytesSize))
+ if p.err != nil {
+ tr.err = p.err
+ return nil
+ }
+ if offset == 0 && numBytes == 0 {
+ break
+ }
+ sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
+ }
+ }
+ return sp
+}
+
+// readGNUSparseMap1x0 reads the sparse map as stored in GNU's PAX sparse format
+// version 1.0. The format of the sparse map consists of a series of
+// newline-terminated numeric fields. The first field is the number of entries
+// and is always present. Following this are the entries, consisting of two
+// fields (offset, numBytes). This function must stop reading at the end
+// boundary of the block containing the last newline.
+//
+// Note that the GNU manual says that numeric values should be encoded in octal
+// format. However, the GNU tar utility itself outputs these values in decimal.
+// As such, this library treats values as being encoded in decimal.
+func readGNUSparseMap1x0(r io.Reader) ([]sparseEntry, error) {
+ var cntNewline int64
+ var buf bytes.Buffer
+ var blk = make([]byte, blockSize)
+
+ // feedTokens copies data in numBlock chunks from r into buf until there are
+ // at least cnt newlines in buf. It will not read more blocks than needed.
+ var feedTokens = func(cnt int64) error {
+ for cntNewline < cnt {
+ if _, err := io.ReadFull(r, blk); err != nil {
+ if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ }
+ return err
+ }
+ buf.Write(blk)
+ for _, c := range blk {
+ if c == '\n' {
+ cntNewline++
+ }
+ }
+ }
+ return nil
+ }
+
+ // nextToken gets the next token delimited by a newline. This assumes that
+ // at least one newline exists in the buffer.
+ var nextToken = func() string {
+ cntNewline--
+ tok, _ := buf.ReadString('\n')
+ return tok[:len(tok)-1] // Cut off newline
+ }
+
+ // Parse for the number of entries.
+ // Use integer overflow resistant math to check this.
+ if err := feedTokens(1); err != nil {
+ return nil, err
+ }
+ numEntries, err := strconv.ParseInt(nextToken(), 10, 0) // Intentionally parse as native int
+ if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) {
+ return nil, ErrHeader
+ }
+
+ // Parse for all member entries.
+ // numEntries is trusted after this since a potential attacker must have
+ // committed resources proportional to what this library used.
+ if err := feedTokens(2 * numEntries); err != nil {
+ return nil, err
+ }
+ sp := make([]sparseEntry, 0, numEntries)
+ for i := int64(0); i < numEntries; i++ {
+ offset, err := strconv.ParseInt(nextToken(), 10, 64)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ numBytes, err := strconv.ParseInt(nextToken(), 10, 64)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
+ }
+ return sp, nil
+}
+
+// readGNUSparseMap0x1 reads the sparse map as stored in GNU's PAX sparse format
+// version 0.1. The sparse map is stored in the PAX headers.
+func readGNUSparseMap0x1(extHdrs map[string]string) ([]sparseEntry, error) {
+ // Get number of entries.
+ // Use integer overflow resistant math to check this.
+ numEntriesStr := extHdrs[paxGNUSparseNumBlocks]
+ numEntries, err := strconv.ParseInt(numEntriesStr, 10, 0) // Intentionally parse as native int
+ if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) {
+ return nil, ErrHeader
+ }
+
+ // There should be two numbers in sparseMap for each entry.
+ sparseMap := strings.Split(extHdrs[paxGNUSparseMap], ",")
+ if int64(len(sparseMap)) != 2*numEntries {
+ return nil, ErrHeader
+ }
+
+ // Loop through the entries in the sparse map.
+ // numEntries is trusted now.
+ sp := make([]sparseEntry, 0, numEntries)
+ for i := int64(0); i < numEntries; i++ {
+ offset, err := strconv.ParseInt(sparseMap[2*i], 10, 64)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ numBytes, err := strconv.ParseInt(sparseMap[2*i+1], 10, 64)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
+ }
+ return sp, nil
+}
+
+// numBytes returns the number of bytes left to read in the current file's entry
+// in the tar archive, or 0 if there is no current file.
+func (tr *Reader) numBytes() int64 {
+ if tr.curr == nil {
+ // No current file, so no bytes
+ return 0
+ }
+ return tr.curr.numBytes()
+}
+
+// Read reads from the current entry in the tar archive.
+// It returns 0, io.EOF when it reaches the end of that entry,
+// until Next is called to advance to the next entry.
+//
+// Calling Read on special types like TypeLink, TypeSymLink, TypeChar,
+// TypeBlock, TypeDir, and TypeFifo returns 0, io.EOF regardless of what
+// the Header.Size claims.
+func (tr *Reader) Read(b []byte) (n int, err error) {
+ if tr.err != nil {
+ return 0, tr.err
+ }
+ if tr.curr == nil {
+ return 0, io.EOF
+ }
+
+ n, err = tr.curr.Read(b)
+ if err != nil && err != io.EOF {
+ tr.err = err
+ }
+ return
+}
+
+func (rfr *regFileReader) Read(b []byte) (n int, err error) {
+ if rfr.nb == 0 {
+ // file consumed
+ return 0, io.EOF
+ }
+ if int64(len(b)) > rfr.nb {
+ b = b[0:rfr.nb]
+ }
+ n, err = rfr.r.Read(b)
+ rfr.nb -= int64(n)
+
+ if err == io.EOF && rfr.nb > 0 {
+ err = io.ErrUnexpectedEOF
+ }
+ return
+}
+
+// numBytes returns the number of bytes left to read in the file's data in the tar archive.
+func (rfr *regFileReader) numBytes() int64 {
+ return rfr.nb
+}
+
+// newSparseFileReader creates a new sparseFileReader, but validates all of the
+// sparse entries before doing so.
+func newSparseFileReader(rfr numBytesReader, sp []sparseEntry, total int64) (*sparseFileReader, error) {
+ if total < 0 {
+ return nil, ErrHeader // Total size cannot be negative
+ }
+
+ // Validate all sparse entries. These are the same checks as performed by
+ // the BSD tar utility.
+ for i, s := range sp {
+ switch {
+ case s.offset < 0 || s.numBytes < 0:
+ return nil, ErrHeader // Negative values are never okay
+ case s.offset > math.MaxInt64-s.numBytes:
+ return nil, ErrHeader // Integer overflow with large length
+ case s.offset+s.numBytes > total:
+ return nil, ErrHeader // Region extends beyond the "real" size
+ case i > 0 && sp[i-1].offset+sp[i-1].numBytes > s.offset:
+ return nil, ErrHeader // Regions can't overlap and must be in order
+ }
+ }
+ return &sparseFileReader{rfr: rfr, sp: sp, total: total}, nil
+}
+
+// readHole reads a sparse hole ending at endOffset.
+func (sfr *sparseFileReader) readHole(b []byte, endOffset int64) int {
+ n64 := endOffset - sfr.pos
+ if n64 > int64(len(b)) {
+ n64 = int64(len(b))
+ }
+ n := int(n64)
+ for i := 0; i < n; i++ {
+ b[i] = 0
+ }
+ sfr.pos += n64
+ return n
+}
+
+// Read reads the sparse file data in expanded form.
+func (sfr *sparseFileReader) Read(b []byte) (n int, err error) {
+ // Skip past all empty fragments.
+ for len(sfr.sp) > 0 && sfr.sp[0].numBytes == 0 {
+ sfr.sp = sfr.sp[1:]
+ }
+
+ // If there are no more fragments, then it is possible that there
+ // is one last sparse hole.
+ if len(sfr.sp) == 0 {
+ // This behavior matches the BSD tar utility.
+ // However, GNU tar stops returning data even if sfr.total is unmet.
+ if sfr.pos < sfr.total {
+ return sfr.readHole(b, sfr.total), nil
+ }
+ return 0, io.EOF
+ }
+
+ // In front of a data fragment, so read a hole.
+ if sfr.pos < sfr.sp[0].offset {
+ return sfr.readHole(b, sfr.sp[0].offset), nil
+ }
+
+ // In a data fragment, so read from it.
+ // This math is overflow free since we verify that offset and numBytes can
+ // be safely added when creating the sparseFileReader.
+ endPos := sfr.sp[0].offset + sfr.sp[0].numBytes // End offset of fragment
+ bytesLeft := endPos - sfr.pos // Bytes left in fragment
+ if int64(len(b)) > bytesLeft {
+ b = b[:bytesLeft]
+ }
+
+ n, err = sfr.rfr.Read(b)
+ sfr.pos += int64(n)
+ if err == io.EOF {
+ if sfr.pos < endPos {
+ err = io.ErrUnexpectedEOF // There was supposed to be more data
+ } else if sfr.pos < sfr.total {
+ err = nil // There is still an implicit sparse hole at the end
+ }
+ }
+
+ if sfr.pos == endPos {
+ sfr.sp = sfr.sp[1:] // We are done with this fragment, so pop it
+ }
+ return n, err
+}
+
+// numBytes returns the number of bytes left to read in the sparse file's
+// sparse-encoded data in the tar archive.
+func (sfr *sparseFileReader) numBytes() int64 {
+ return sfr.rfr.numBytes()
+}
diff --git a/vendor/github.com/Microsoft/go-winio/archive/tar/stat_atim.go b/vendor/github.com/Microsoft/go-winio/archive/tar/stat_atim.go
new file mode 100644
index 0000000..cf9cc79
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/archive/tar/stat_atim.go
@@ -0,0 +1,20 @@
+// 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 linux dragonfly openbsd solaris
+
+package tar
+
+import (
+ "syscall"
+ "time"
+)
+
+func statAtime(st *syscall.Stat_t) time.Time {
+ return time.Unix(st.Atim.Unix())
+}
+
+func statCtime(st *syscall.Stat_t) time.Time {
+ return time.Unix(st.Ctim.Unix())
+}
diff --git a/vendor/github.com/Microsoft/go-winio/archive/tar/stat_atimespec.go b/vendor/github.com/Microsoft/go-winio/archive/tar/stat_atimespec.go
new file mode 100644
index 0000000..6f17dbe
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/archive/tar/stat_atimespec.go
@@ -0,0 +1,20 @@
+// 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 darwin freebsd netbsd
+
+package tar
+
+import (
+ "syscall"
+ "time"
+)
+
+func statAtime(st *syscall.Stat_t) time.Time {
+ return time.Unix(st.Atimespec.Unix())
+}
+
+func statCtime(st *syscall.Stat_t) time.Time {
+ return time.Unix(st.Ctimespec.Unix())
+}
diff --git a/vendor/github.com/Microsoft/go-winio/archive/tar/stat_unix.go b/vendor/github.com/Microsoft/go-winio/archive/tar/stat_unix.go
new file mode 100644
index 0000000..cb843db
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/archive/tar/stat_unix.go
@@ -0,0 +1,32 @@
+// 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 linux darwin dragonfly freebsd openbsd netbsd solaris
+
+package tar
+
+import (
+ "os"
+ "syscall"
+)
+
+func init() {
+ sysStat = statUnix
+}
+
+func statUnix(fi os.FileInfo, h *Header) error {
+ sys, ok := fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return nil
+ }
+ h.Uid = int(sys.Uid)
+ h.Gid = int(sys.Gid)
+ // TODO(bradfitz): populate username & group. os/user
+ // doesn't cache LookupId lookups, and lacks group
+ // lookup functions.
+ h.AccessTime = statAtime(sys)
+ h.ChangeTime = statCtime(sys)
+ // TODO(bradfitz): major/minor device numbers?
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/go-winio/archive/tar/writer.go b/vendor/github.com/Microsoft/go-winio/archive/tar/writer.go
new file mode 100644
index 0000000..30d7e60
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/archive/tar/writer.go
@@ -0,0 +1,444 @@
+// Copyright 2009 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 tar
+
+// TODO(dsymonds):
+// - catch more errors (no first header, etc.)
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "path"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var (
+ ErrWriteTooLong = errors.New("archive/tar: write too long")
+ ErrFieldTooLong = errors.New("archive/tar: header field too long")
+ ErrWriteAfterClose = errors.New("archive/tar: write after close")
+ errInvalidHeader = errors.New("archive/tar: header field too long or contains invalid values")
+)
+
+// A Writer provides sequential writing of a tar archive in POSIX.1 format.
+// A tar archive consists of a sequence of files.
+// Call WriteHeader to begin a new file, and then call Write to supply that file's data,
+// writing at most hdr.Size bytes in total.
+type Writer struct {
+ w io.Writer
+ err error
+ nb int64 // number of unwritten bytes for current file entry
+ pad int64 // amount of padding to write after current file entry
+ closed bool
+ usedBinary bool // whether the binary numeric field extension was used
+ preferPax bool // use pax header instead of binary numeric header
+ hdrBuff [blockSize]byte // buffer to use in writeHeader when writing a regular header
+ paxHdrBuff [blockSize]byte // buffer to use in writeHeader when writing a pax header
+}
+
+type formatter struct {
+ err error // Last error seen
+}
+
+// NewWriter creates a new Writer writing to w.
+func NewWriter(w io.Writer) *Writer { return &Writer{w: w, preferPax: true} }
+
+// Flush finishes writing the current file (optional).
+func (tw *Writer) Flush() error {
+ if tw.nb > 0 {
+ tw.err = fmt.Errorf("archive/tar: missed writing %d bytes", tw.nb)
+ return tw.err
+ }
+
+ n := tw.nb + tw.pad
+ for n > 0 && tw.err == nil {
+ nr := n
+ if nr > blockSize {
+ nr = blockSize
+ }
+ var nw int
+ nw, tw.err = tw.w.Write(zeroBlock[0:nr])
+ n -= int64(nw)
+ }
+ tw.nb = 0
+ tw.pad = 0
+ return tw.err
+}
+
+// Write s into b, terminating it with a NUL if there is room.
+func (f *formatter) formatString(b []byte, s string) {
+ if len(s) > len(b) {
+ f.err = ErrFieldTooLong
+ return
+ }
+ ascii := toASCII(s)
+ copy(b, ascii)
+ if len(ascii) < len(b) {
+ b[len(ascii)] = 0
+ }
+}
+
+// Encode x as an octal ASCII string and write it into b with leading zeros.
+func (f *formatter) formatOctal(b []byte, x int64) {
+ s := strconv.FormatInt(x, 8)
+ // leading zeros, but leave room for a NUL.
+ for len(s)+1 < len(b) {
+ s = "0" + s
+ }
+ f.formatString(b, s)
+}
+
+// fitsInBase256 reports whether x can be encoded into n bytes using base-256
+// encoding. Unlike octal encoding, base-256 encoding does not require that the
+// string ends with a NUL character. Thus, all n bytes are available for output.
+//
+// If operating in binary mode, this assumes strict GNU binary mode; which means
+// that the first byte can only be either 0x80 or 0xff. Thus, the first byte is
+// equivalent to the sign bit in two's complement form.
+func fitsInBase256(n int, x int64) bool {
+ var binBits = uint(n-1) * 8
+ return n >= 9 || (x >= -1<<binBits && x < 1<<binBits)
+}
+
+// Write x into b, as binary (GNUtar/star extension).
+func (f *formatter) formatNumeric(b []byte, x int64) {
+ if fitsInBase256(len(b), x) {
+ for i := len(b) - 1; i >= 0; i-- {
+ b[i] = byte(x)
+ x >>= 8
+ }
+ b[0] |= 0x80 // Highest bit indicates binary format
+ return
+ }
+
+ f.formatOctal(b, 0) // Last resort, just write zero
+ f.err = ErrFieldTooLong
+}
+
+var (
+ minTime = time.Unix(0, 0)
+ // There is room for 11 octal digits (33 bits) of mtime.
+ maxTime = minTime.Add((1<<33 - 1) * time.Second)
+)
+
+// WriteHeader writes hdr and prepares to accept the file's contents.
+// WriteHeader calls Flush if it is not the first header.
+// Calling after a Close will return ErrWriteAfterClose.
+func (tw *Writer) WriteHeader(hdr *Header) error {
+ return tw.writeHeader(hdr, true)
+}
+
+// WriteHeader writes hdr and prepares to accept the file's contents.
+// WriteHeader calls Flush if it is not the first header.
+// Calling after a Close will return ErrWriteAfterClose.
+// As this method is called internally by writePax header to allow it to
+// suppress writing the pax header.
+func (tw *Writer) writeHeader(hdr *Header, allowPax bool) error {
+ if tw.closed {
+ return ErrWriteAfterClose
+ }
+ if tw.err == nil {
+ tw.Flush()
+ }
+ if tw.err != nil {
+ return tw.err
+ }
+
+ // a map to hold pax header records, if any are needed
+ paxHeaders := make(map[string]string)
+
+ // TODO(shanemhansen): we might want to use PAX headers for
+ // subsecond time resolution, but for now let's just capture
+ // too long fields or non ascii characters
+
+ var f formatter
+ var header []byte
+
+ // We need to select which scratch buffer to use carefully,
+ // since this method is called recursively to write PAX headers.
+ // If allowPax is true, this is the non-recursive call, and we will use hdrBuff.
+ // If allowPax is false, we are being called by writePAXHeader, and hdrBuff is
+ // already being used by the non-recursive call, so we must use paxHdrBuff.
+ header = tw.hdrBuff[:]
+ if !allowPax {
+ header = tw.paxHdrBuff[:]
+ }
+ copy(header, zeroBlock)
+ s := slicer(header)
+
+ // Wrappers around formatter that automatically sets paxHeaders if the
+ // argument extends beyond the capacity of the input byte slice.
+ var formatString = func(b []byte, s string, paxKeyword string) {
+ needsPaxHeader := paxKeyword != paxNone && len(s) > len(b) || !isASCII(s)
+ if needsPaxHeader {
+ paxHeaders[paxKeyword] = s
+ return
+ }
+ f.formatString(b, s)
+ }
+ var formatNumeric = func(b []byte, x int64, paxKeyword string) {
+ // Try octal first.
+ s := strconv.FormatInt(x, 8)
+ if len(s) < len(b) {
+ f.formatOctal(b, x)
+ return
+ }
+
+ // If it is too long for octal, and PAX is preferred, use a PAX header.
+ if paxKeyword != paxNone && tw.preferPax {
+ f.formatOctal(b, 0)
+ s := strconv.FormatInt(x, 10)
+ paxHeaders[paxKeyword] = s
+ return
+ }
+
+ tw.usedBinary = true
+ f.formatNumeric(b, x)
+ }
+ var formatTime = func(b []byte, t time.Time, paxKeyword string) {
+ var unixTime int64
+ if !t.Before(minTime) && !t.After(maxTime) {
+ unixTime = t.Unix()
+ }
+ formatNumeric(b, unixTime, paxNone)
+
+ // Write a PAX header if the time didn't fit precisely.
+ if paxKeyword != "" && tw.preferPax && allowPax && (t.Nanosecond() != 0 || !t.Before(minTime) || !t.After(maxTime)) {
+ paxHeaders[paxKeyword] = formatPAXTime(t)
+ }
+ }
+
+ // keep a reference to the filename to allow to overwrite it later if we detect that we can use ustar longnames instead of pax
+ pathHeaderBytes := s.next(fileNameSize)
+
+ formatString(pathHeaderBytes, hdr.Name, paxPath)
+
+ f.formatOctal(s.next(8), hdr.Mode) // 100:108
+ formatNumeric(s.next(8), int64(hdr.Uid), paxUid) // 108:116
+ formatNumeric(s.next(8), int64(hdr.Gid), paxGid) // 116:124
+ formatNumeric(s.next(12), hdr.Size, paxSize) // 124:136
+ formatTime(s.next(12), hdr.ModTime, paxMtime) // 136:148
+ s.next(8) // chksum (148:156)
+ s.next(1)[0] = hdr.Typeflag // 156:157
+
+ formatString(s.next(100), hdr.Linkname, paxLinkpath)
+
+ copy(s.next(8), []byte("ustar\x0000")) // 257:265
+ formatString(s.next(32), hdr.Uname, paxUname) // 265:297
+ formatString(s.next(32), hdr.Gname, paxGname) // 297:329
+ formatNumeric(s.next(8), hdr.Devmajor, paxNone) // 329:337
+ formatNumeric(s.next(8), hdr.Devminor, paxNone) // 337:345
+
+ // keep a reference to the prefix to allow to overwrite it later if we detect that we can use ustar longnames instead of pax
+ prefixHeaderBytes := s.next(155)
+ formatString(prefixHeaderBytes, "", paxNone) // 345:500 prefix
+
+ // Use the GNU magic instead of POSIX magic if we used any GNU extensions.
+ if tw.usedBinary {
+ copy(header[257:265], []byte("ustar \x00"))
+ }
+
+ _, paxPathUsed := paxHeaders[paxPath]
+ // try to use a ustar header when only the name is too long
+ if !tw.preferPax && len(paxHeaders) == 1 && paxPathUsed {
+ prefix, suffix, ok := splitUSTARPath(hdr.Name)
+ if ok {
+ // Since we can encode in USTAR format, disable PAX header.
+ delete(paxHeaders, paxPath)
+
+ // Update the path fields
+ formatString(pathHeaderBytes, suffix, paxNone)
+ formatString(prefixHeaderBytes, prefix, paxNone)
+ }
+ }
+
+ // The chksum field is terminated by a NUL and a space.
+ // This is different from the other octal fields.
+ chksum, _ := checksum(header)
+ f.formatOctal(header[148:155], chksum) // Never fails
+ header[155] = ' '
+
+ // Check if there were any formatting errors.
+ if f.err != nil {
+ tw.err = f.err
+ return tw.err
+ }
+
+ if allowPax {
+ if !hdr.AccessTime.IsZero() {
+ paxHeaders[paxAtime] = formatPAXTime(hdr.AccessTime)
+ }
+ if !hdr.ChangeTime.IsZero() {
+ paxHeaders[paxCtime] = formatPAXTime(hdr.ChangeTime)
+ }
+ if !hdr.CreationTime.IsZero() {
+ paxHeaders[paxCreationTime] = formatPAXTime(hdr.CreationTime)
+ }
+ for k, v := range hdr.Xattrs {
+ paxHeaders[paxXattr+k] = v
+ }
+ for k, v := range hdr.Winheaders {
+ paxHeaders[paxWindows+k] = v
+ }
+ }
+
+ if len(paxHeaders) > 0 {
+ if !allowPax {
+ return errInvalidHeader
+ }
+ if err := tw.writePAXHeader(hdr, paxHeaders); err != nil {
+ return err
+ }
+ }
+ tw.nb = int64(hdr.Size)
+ tw.pad = (blockSize - (tw.nb % blockSize)) % blockSize
+
+ _, tw.err = tw.w.Write(header)
+ return tw.err
+}
+
+func formatPAXTime(t time.Time) string {
+ sec := t.Unix()
+ usec := t.Nanosecond()
+ s := strconv.FormatInt(sec, 10)
+ if usec != 0 {
+ s = fmt.Sprintf("%s.%09d", s, usec)
+ }
+ return s
+}
+
+// splitUSTARPath splits a path according to USTAR prefix and suffix rules.
+// If the path is not splittable, then it will return ("", "", false).
+func splitUSTARPath(name string) (prefix, suffix string, ok bool) {
+ length := len(name)
+ if length <= fileNameSize || !isASCII(name) {
+ return "", "", false
+ } else if length > fileNamePrefixSize+1 {
+ length = fileNamePrefixSize + 1
+ } else if name[length-1] == '/' {
+ length--
+ }
+
+ i := strings.LastIndex(name[:length], "/")
+ nlen := len(name) - i - 1 // nlen is length of suffix
+ plen := i // plen is length of prefix
+ if i <= 0 || nlen > fileNameSize || nlen == 0 || plen > fileNamePrefixSize {
+ return "", "", false
+ }
+ return name[:i], name[i+1:], true
+}
+
+// writePaxHeader writes an extended pax header to the
+// archive.
+func (tw *Writer) writePAXHeader(hdr *Header, paxHeaders map[string]string) error {
+ // Prepare extended header
+ ext := new(Header)
+ ext.Typeflag = TypeXHeader
+ // Setting ModTime is required for reader parsing to
+ // succeed, and seems harmless enough.
+ ext.ModTime = hdr.ModTime
+ // The spec asks that we namespace our pseudo files
+ // with the current pid. However, this results in differing outputs
+ // for identical inputs. As such, the constant 0 is now used instead.
+ // golang.org/issue/12358
+ dir, file := path.Split(hdr.Name)
+ fullName := path.Join(dir, "PaxHeaders.0", file)
+
+ ascii := toASCII(fullName)
+ if len(ascii) > 100 {
+ ascii = ascii[:100]
+ }
+ ext.Name = ascii
+ // Construct the body
+ var buf bytes.Buffer
+
+ // Keys are sorted before writing to body to allow deterministic output.
+ var keys []string
+ for k := range paxHeaders {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+
+ for _, k := range keys {
+ fmt.Fprint(&buf, formatPAXRecord(k, paxHeaders[k]))
+ }
+
+ ext.Size = int64(len(buf.Bytes()))
+ if err := tw.writeHeader(ext, false); err != nil {
+ return err
+ }
+ if _, err := tw.Write(buf.Bytes()); err != nil {
+ return err
+ }
+ if err := tw.Flush(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// formatPAXRecord formats a single PAX record, prefixing it with the
+// appropriate length.
+func formatPAXRecord(k, v string) string {
+ const padding = 3 // Extra padding for ' ', '=', and '\n'
+ size := len(k) + len(v) + padding
+ size += len(strconv.Itoa(size))
+ record := fmt.Sprintf("%d %s=%s\n", size, k, v)
+
+ // Final adjustment if adding size field increased the record size.
+ if len(record) != size {
+ size = len(record)
+ record = fmt.Sprintf("%d %s=%s\n", size, k, v)
+ }
+ return record
+}
+
+// Write writes to the current entry in the tar archive.
+// Write returns the error ErrWriteTooLong if more than
+// hdr.Size bytes are written after WriteHeader.
+func (tw *Writer) Write(b []byte) (n int, err error) {
+ if tw.closed {
+ err = ErrWriteAfterClose
+ return
+ }
+ overwrite := false
+ if int64(len(b)) > tw.nb {
+ b = b[0:tw.nb]
+ overwrite = true
+ }
+ n, err = tw.w.Write(b)
+ tw.nb -= int64(n)
+ if err == nil && overwrite {
+ err = ErrWriteTooLong
+ return
+ }
+ tw.err = err
+ return
+}
+
+// Close closes the tar archive, flushing any unwritten
+// data to the underlying writer.
+func (tw *Writer) Close() error {
+ if tw.err != nil || tw.closed {
+ return tw.err
+ }
+ tw.Flush()
+ tw.closed = true
+ if tw.err != nil {
+ return tw.err
+ }
+
+ // trailer: two zero blocks
+ for i := 0; i < 2; i++ {
+ _, tw.err = tw.w.Write(zeroBlock)
+ if tw.err != nil {
+ break
+ }
+ }
+ return tw.err
+}
diff --git a/vendor/github.com/Microsoft/go-winio/backup.go b/vendor/github.com/Microsoft/go-winio/backup.go
new file mode 100644
index 0000000..27d6ace
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/backup.go
@@ -0,0 +1,270 @@
+// +build windows
+
+package winio
+
+import (
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "runtime"
+ "syscall"
+ "unicode/utf16"
+)
+
+//sys backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupRead
+//sys backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupWrite
+
+const (
+ BackupData = uint32(iota + 1)
+ BackupEaData
+ BackupSecurity
+ BackupAlternateData
+ BackupLink
+ BackupPropertyData
+ BackupObjectId
+ BackupReparseData
+ BackupSparseBlock
+ BackupTxfsData
+)
+
+const (
+ StreamSparseAttributes = uint32(8)
+)
+
+const (
+ WRITE_DAC = 0x40000
+ WRITE_OWNER = 0x80000
+ ACCESS_SYSTEM_SECURITY = 0x1000000
+)
+
+// BackupHeader represents a backup stream of a file.
+type BackupHeader struct {
+ Id uint32 // The backup stream ID
+ Attributes uint32 // Stream attributes
+ Size int64 // The size of the stream in bytes
+ Name string // The name of the stream (for BackupAlternateData only).
+ Offset int64 // The offset of the stream in the file (for BackupSparseBlock only).
+}
+
+type win32StreamId struct {
+ StreamId uint32
+ Attributes uint32
+ Size uint64
+ NameSize uint32
+}
+
+// BackupStreamReader reads from a stream produced by the BackupRead Win32 API and produces a series
+// of BackupHeader values.
+type BackupStreamReader struct {
+ r io.Reader
+ bytesLeft int64
+}
+
+// NewBackupStreamReader produces a BackupStreamReader from any io.Reader.
+func NewBackupStreamReader(r io.Reader) *BackupStreamReader {
+ return &BackupStreamReader{r, 0}
+}
+
+// Next returns the next backup stream and prepares for calls to Write(). It skips the remainder of the current stream if
+// it was not completely read.
+func (r *BackupStreamReader) Next() (*BackupHeader, error) {
+ if r.bytesLeft > 0 {
+ if _, err := io.Copy(ioutil.Discard, r); err != nil {
+ return nil, err
+ }
+ }
+ var wsi win32StreamId
+ if err := binary.Read(r.r, binary.LittleEndian, &wsi); err != nil {
+ return nil, err
+ }
+ hdr := &BackupHeader{
+ Id: wsi.StreamId,
+ Attributes: wsi.Attributes,
+ Size: int64(wsi.Size),
+ }
+ if wsi.NameSize != 0 {
+ name := make([]uint16, int(wsi.NameSize/2))
+ if err := binary.Read(r.r, binary.LittleEndian, name); err != nil {
+ return nil, err
+ }
+ hdr.Name = syscall.UTF16ToString(name)
+ }
+ if wsi.StreamId == BackupSparseBlock {
+ if err := binary.Read(r.r, binary.LittleEndian, &hdr.Offset); err != nil {
+ return nil, err
+ }
+ hdr.Size -= 8
+ }
+ r.bytesLeft = hdr.Size
+ return hdr, nil
+}
+
+// Read reads from the current backup stream.
+func (r *BackupStreamReader) Read(b []byte) (int, error) {
+ if r.bytesLeft == 0 {
+ return 0, io.EOF
+ }
+ if int64(len(b)) > r.bytesLeft {
+ b = b[:r.bytesLeft]
+ }
+ n, err := r.r.Read(b)
+ r.bytesLeft -= int64(n)
+ if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ } else if r.bytesLeft == 0 && err == nil {
+ err = io.EOF
+ }
+ return n, err
+}
+
+// BackupStreamWriter writes a stream compatible with the BackupWrite Win32 API.
+type BackupStreamWriter struct {
+ w io.Writer
+ bytesLeft int64
+}
+
+// NewBackupStreamWriter produces a BackupStreamWriter on top of an io.Writer.
+func NewBackupStreamWriter(w io.Writer) *BackupStreamWriter {
+ return &BackupStreamWriter{w, 0}
+}
+
+// WriteHeader writes the next backup stream header and prepares for calls to Write().
+func (w *BackupStreamWriter) WriteHeader(hdr *BackupHeader) error {
+ if w.bytesLeft != 0 {
+ return fmt.Errorf("missing %d bytes", w.bytesLeft)
+ }
+ name := utf16.Encode([]rune(hdr.Name))
+ wsi := win32StreamId{
+ StreamId: hdr.Id,
+ Attributes: hdr.Attributes,
+ Size: uint64(hdr.Size),
+ NameSize: uint32(len(name) * 2),
+ }
+ if hdr.Id == BackupSparseBlock {
+ // Include space for the int64 block offset
+ wsi.Size += 8
+ }
+ if err := binary.Write(w.w, binary.LittleEndian, &wsi); err != nil {
+ return err
+ }
+ if len(name) != 0 {
+ if err := binary.Write(w.w, binary.LittleEndian, name); err != nil {
+ return err
+ }
+ }
+ if hdr.Id == BackupSparseBlock {
+ if err := binary.Write(w.w, binary.LittleEndian, hdr.Offset); err != nil {
+ return err
+ }
+ }
+ w.bytesLeft = hdr.Size
+ return nil
+}
+
+// Write writes to the current backup stream.
+func (w *BackupStreamWriter) Write(b []byte) (int, error) {
+ if w.bytesLeft < int64(len(b)) {
+ return 0, fmt.Errorf("too many bytes by %d", int64(len(b))-w.bytesLeft)
+ }
+ n, err := w.w.Write(b)
+ w.bytesLeft -= int64(n)
+ return n, err
+}
+
+// BackupFileReader provides an io.ReadCloser interface on top of the BackupRead Win32 API.
+type BackupFileReader struct {
+ f *os.File
+ includeSecurity bool
+ ctx uintptr
+}
+
+// NewBackupFileReader returns a new BackupFileReader from a file handle. If includeSecurity is true,
+// Read will attempt to read the security descriptor of the file.
+func NewBackupFileReader(f *os.File, includeSecurity bool) *BackupFileReader {
+ r := &BackupFileReader{f, includeSecurity, 0}
+ return r
+}
+
+// Read reads a backup stream from the file by calling the Win32 API BackupRead().
+func (r *BackupFileReader) Read(b []byte) (int, error) {
+ var bytesRead uint32
+ err := backupRead(syscall.Handle(r.f.Fd()), b, &bytesRead, false, r.includeSecurity, &r.ctx)
+ if err != nil {
+ return 0, &os.PathError{"BackupRead", r.f.Name(), err}
+ }
+ runtime.KeepAlive(r.f)
+ if bytesRead == 0 {
+ return 0, io.EOF
+ }
+ return int(bytesRead), nil
+}
+
+// Close frees Win32 resources associated with the BackupFileReader. It does not close
+// the underlying file.
+func (r *BackupFileReader) Close() error {
+ if r.ctx != 0 {
+ backupRead(syscall.Handle(r.f.Fd()), nil, nil, true, false, &r.ctx)
+ runtime.KeepAlive(r.f)
+ r.ctx = 0
+ }
+ return nil
+}
+
+// BackupFileWriter provides an io.WriteCloser interface on top of the BackupWrite Win32 API.
+type BackupFileWriter struct {
+ f *os.File
+ includeSecurity bool
+ ctx uintptr
+}
+
+// NewBackupFileWrtier returns a new BackupFileWriter from a file handle. If includeSecurity is true,
+// Write() will attempt to restore the security descriptor from the stream.
+func NewBackupFileWriter(f *os.File, includeSecurity bool) *BackupFileWriter {
+ w := &BackupFileWriter{f, includeSecurity, 0}
+ return w
+}
+
+// Write restores a portion of the file using the provided backup stream.
+func (w *BackupFileWriter) Write(b []byte) (int, error) {
+ var bytesWritten uint32
+ err := backupWrite(syscall.Handle(w.f.Fd()), b, &bytesWritten, false, w.includeSecurity, &w.ctx)
+ if err != nil {
+ return 0, &os.PathError{"BackupWrite", w.f.Name(), err}
+ }
+ runtime.KeepAlive(w.f)
+ if int(bytesWritten) != len(b) {
+ return int(bytesWritten), errors.New("not all bytes could be written")
+ }
+ return len(b), nil
+}
+
+// Close frees Win32 resources associated with the BackupFileWriter. It does not
+// close the underlying file.
+func (w *BackupFileWriter) Close() error {
+ if w.ctx != 0 {
+ backupWrite(syscall.Handle(w.f.Fd()), nil, nil, true, false, &w.ctx)
+ runtime.KeepAlive(w.f)
+ w.ctx = 0
+ }
+ return nil
+}
+
+// OpenForBackup opens a file or directory, potentially skipping access checks if the backup
+// or restore privileges have been acquired.
+//
+// If the file opened was a directory, it cannot be used with Readdir().
+func OpenForBackup(path string, access uint32, share uint32, createmode uint32) (*os.File, error) {
+ winPath, err := syscall.UTF16FromString(path)
+ if err != nil {
+ return nil, err
+ }
+ h, err := syscall.CreateFile(&winPath[0], access, share, nil, createmode, syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, 0)
+ if err != nil {
+ err = &os.PathError{Op: "open", Path: path, Err: err}
+ return nil, err
+ }
+ return os.NewFile(uintptr(h), path), nil
+}
diff --git a/vendor/github.com/Microsoft/go-winio/backuptar/noop.go b/vendor/github.com/Microsoft/go-winio/backuptar/noop.go
new file mode 100644
index 0000000..d39eccf
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/backuptar/noop.go
@@ -0,0 +1,4 @@
+// +build !windows
+// This file only exists to allow go get on non-Windows platforms.
+
+package backuptar
diff --git a/vendor/github.com/Microsoft/go-winio/backuptar/tar.go b/vendor/github.com/Microsoft/go-winio/backuptar/tar.go
new file mode 100644
index 0000000..cfbcedf
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/backuptar/tar.go
@@ -0,0 +1,353 @@
+// +build windows
+
+package backuptar
+
+import (
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/Microsoft/go-winio"
+ "github.com/Microsoft/go-winio/archive/tar" // until archive/tar supports pax extensions in its interface
+)
+
+const (
+ c_ISUID = 04000 // Set uid
+ c_ISGID = 02000 // Set gid
+ c_ISVTX = 01000 // Save text (sticky bit)
+ c_ISDIR = 040000 // Directory
+ c_ISFIFO = 010000 // FIFO
+ c_ISREG = 0100000 // Regular file
+ c_ISLNK = 0120000 // Symbolic link
+ c_ISBLK = 060000 // Block special file
+ c_ISCHR = 020000 // Character special file
+ c_ISSOCK = 0140000 // Socket
+)
+
+const (
+ hdrFileAttributes = "fileattr"
+ hdrSecurityDescriptor = "sd"
+ hdrRawSecurityDescriptor = "rawsd"
+ hdrMountPoint = "mountpoint"
+)
+
+func writeZeroes(w io.Writer, count int64) error {
+ buf := make([]byte, 8192)
+ c := len(buf)
+ for i := int64(0); i < count; i += int64(c) {
+ if int64(c) > count-i {
+ c = int(count - i)
+ }
+ _, err := w.Write(buf[:c])
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func copySparse(t *tar.Writer, br *winio.BackupStreamReader) error {
+ curOffset := int64(0)
+ for {
+ bhdr, err := br.Next()
+ if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ }
+ if err != nil {
+ return err
+ }
+ if bhdr.Id != winio.BackupSparseBlock {
+ return fmt.Errorf("unexpected stream %d", bhdr.Id)
+ }
+
+ // archive/tar does not support writing sparse files
+ // so just write zeroes to catch up to the current offset.
+ err = writeZeroes(t, bhdr.Offset-curOffset)
+ if bhdr.Size == 0 {
+ break
+ }
+ n, err := io.Copy(t, br)
+ if err != nil {
+ return err
+ }
+ curOffset = bhdr.Offset + n
+ }
+ return nil
+}
+
+// BasicInfoHeader creates a tar header from basic file information.
+func BasicInfoHeader(name string, size int64, fileInfo *winio.FileBasicInfo) *tar.Header {
+ hdr := &tar.Header{
+ Name: filepath.ToSlash(name),
+ Size: size,
+ Typeflag: tar.TypeReg,
+ ModTime: time.Unix(0, fileInfo.LastWriteTime.Nanoseconds()),
+ ChangeTime: time.Unix(0, fileInfo.ChangeTime.Nanoseconds()),
+ AccessTime: time.Unix(0, fileInfo.LastAccessTime.Nanoseconds()),
+ CreationTime: time.Unix(0, fileInfo.CreationTime.Nanoseconds()),
+ Winheaders: make(map[string]string),
+ }
+ hdr.Winheaders[hdrFileAttributes] = fmt.Sprintf("%d", fileInfo.FileAttributes)
+
+ if (fileInfo.FileAttributes & syscall.FILE_ATTRIBUTE_DIRECTORY) != 0 {
+ hdr.Mode |= c_ISDIR
+ hdr.Size = 0
+ hdr.Typeflag = tar.TypeDir
+ }
+ return hdr
+}
+
+// WriteTarFileFromBackupStream writes a file to a tar writer using data from a Win32 backup stream.
+//
+// This encodes Win32 metadata as tar pax vendor extensions starting with MSWINDOWS.
+//
+// The additional Win32 metadata is:
+//
+// MSWINDOWS.fileattr: The Win32 file attributes, as a decimal value
+//
+// MSWINDOWS.rawsd: The Win32 security descriptor, in raw binary format
+//
+// MSWINDOWS.mountpoint: If present, this is a mount point and not a symlink, even though the type is '2' (symlink)
+func WriteTarFileFromBackupStream(t *tar.Writer, r io.Reader, name string, size int64, fileInfo *winio.FileBasicInfo) error {
+ name = filepath.ToSlash(name)
+ hdr := BasicInfoHeader(name, size, fileInfo)
+ br := winio.NewBackupStreamReader(r)
+ var dataHdr *winio.BackupHeader
+ for dataHdr == nil {
+ bhdr, err := br.Next()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+ switch bhdr.Id {
+ case winio.BackupData:
+ hdr.Mode |= c_ISREG
+ dataHdr = bhdr
+ case winio.BackupSecurity:
+ sd, err := ioutil.ReadAll(br)
+ if err != nil {
+ return err
+ }
+ hdr.Winheaders[hdrRawSecurityDescriptor] = base64.StdEncoding.EncodeToString(sd)
+
+ case winio.BackupReparseData:
+ hdr.Mode |= c_ISLNK
+ hdr.Typeflag = tar.TypeSymlink
+ reparseBuffer, err := ioutil.ReadAll(br)
+ rp, err := winio.DecodeReparsePoint(reparseBuffer)
+ if err != nil {
+ return err
+ }
+ if rp.IsMountPoint {
+ hdr.Winheaders[hdrMountPoint] = "1"
+ }
+ hdr.Linkname = rp.Target
+ case winio.BackupEaData, winio.BackupLink, winio.BackupPropertyData, winio.BackupObjectId, winio.BackupTxfsData:
+ // ignore these streams
+ default:
+ return fmt.Errorf("%s: unknown stream ID %d", name, bhdr.Id)
+ }
+ }
+
+ err := t.WriteHeader(hdr)
+ if err != nil {
+ return err
+ }
+
+ if dataHdr != nil {
+ // A data stream was found. Copy the data.
+ if (dataHdr.Attributes & winio.StreamSparseAttributes) == 0 {
+ if size != dataHdr.Size {
+ return fmt.Errorf("%s: mismatch between file size %d and header size %d", name, size, dataHdr.Size)
+ }
+ _, err = io.Copy(t, br)
+ if err != nil {
+ return err
+ }
+ } else {
+ err = copySparse(t, br)
+ if err != nil {
+ return err
+ }
+ }
+ }
+
+ // Look for streams after the data stream. The only ones we handle are alternate data streams.
+ // Other streams may have metadata that could be serialized, but the tar header has already
+ // been written. In practice, this means that we don't get EA or TXF metadata.
+ for {
+ bhdr, err := br.Next()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+ switch bhdr.Id {
+ case winio.BackupAlternateData:
+ altName := bhdr.Name
+ if strings.HasSuffix(altName, ":$DATA") {
+ altName = altName[:len(altName)-len(":$DATA")]
+ }
+ if (bhdr.Attributes & winio.StreamSparseAttributes) == 0 {
+ hdr = &tar.Header{
+ Name: name + altName,
+ Mode: hdr.Mode,
+ Typeflag: tar.TypeReg,
+ Size: bhdr.Size,
+ ModTime: hdr.ModTime,
+ AccessTime: hdr.AccessTime,
+ ChangeTime: hdr.ChangeTime,
+ }
+ err = t.WriteHeader(hdr)
+ if err != nil {
+ return err
+ }
+ _, err = io.Copy(t, br)
+ if err != nil {
+ return err
+ }
+
+ } else {
+ // Unsupported for now, since the size of the alternate stream is not present
+ // in the backup stream until after the data has been read.
+ return errors.New("tar of sparse alternate data streams is unsupported")
+ }
+ case winio.BackupEaData, winio.BackupLink, winio.BackupPropertyData, winio.BackupObjectId, winio.BackupTxfsData:
+ // ignore these streams
+ default:
+ return fmt.Errorf("%s: unknown stream ID %d after data", name, bhdr.Id)
+ }
+ }
+ return nil
+}
+
+// FileInfoFromHeader retrieves basic Win32 file information from a tar header, using the additional metadata written by
+// WriteTarFileFromBackupStream.
+func FileInfoFromHeader(hdr *tar.Header) (name string, size int64, fileInfo *winio.FileBasicInfo, err error) {
+ name = hdr.Name
+ if hdr.Typeflag == tar.TypeReg || hdr.Typeflag == tar.TypeRegA {
+ size = hdr.Size
+ }
+ fileInfo = &winio.FileBasicInfo{
+ LastAccessTime: syscall.NsecToFiletime(hdr.AccessTime.UnixNano()),
+ LastWriteTime: syscall.NsecToFiletime(hdr.ModTime.UnixNano()),
+ ChangeTime: syscall.NsecToFiletime(hdr.ChangeTime.UnixNano()),
+ CreationTime: syscall.NsecToFiletime(hdr.CreationTime.UnixNano()),
+ }
+ if attrStr, ok := hdr.Winheaders[hdrFileAttributes]; ok {
+ attr, err := strconv.ParseUint(attrStr, 10, 32)
+ if err != nil {
+ return "", 0, nil, err
+ }
+ fileInfo.FileAttributes = uintptr(attr)
+ } else {
+ if hdr.Typeflag == tar.TypeDir {
+ fileInfo.FileAttributes |= syscall.FILE_ATTRIBUTE_DIRECTORY
+ }
+ }
+ return
+}
+
+// WriteBackupStreamFromTarFile writes a Win32 backup stream from the current tar file. Since this function may process multiple
+// tar file entries in order to collect all the alternate data streams for the file, it returns the next
+// tar file that was not processed, or io.EOF is there are no more.
+func WriteBackupStreamFromTarFile(w io.Writer, t *tar.Reader, hdr *tar.Header) (*tar.Header, error) {
+ bw := winio.NewBackupStreamWriter(w)
+ var sd []byte
+ var err error
+ // Maintaining old SDDL-based behavior for backward compatibility. All new tar headers written
+ // by this library will have raw binary for the security descriptor.
+ if sddl, ok := hdr.Winheaders[hdrSecurityDescriptor]; ok {
+ sd, err = winio.SddlToSecurityDescriptor(sddl)
+ if err != nil {
+ return nil, err
+ }
+ }
+ if sdraw, ok := hdr.Winheaders[hdrRawSecurityDescriptor]; ok {
+ sd, err = base64.StdEncoding.DecodeString(sdraw)
+ if err != nil {
+ return nil, err
+ }
+ }
+ if len(sd) != 0 {
+ bhdr := winio.BackupHeader{
+ Id: winio.BackupSecurity,
+ Size: int64(len(sd)),
+ }
+ err := bw.WriteHeader(&bhdr)
+ if err != nil {
+ return nil, err
+ }
+ _, err = bw.Write(sd)
+ if err != nil {
+ return nil, err
+ }
+ }
+ if hdr.Typeflag == tar.TypeSymlink {
+ _, isMountPoint := hdr.Winheaders[hdrMountPoint]
+ rp := winio.ReparsePoint{
+ Target: filepath.FromSlash(hdr.Linkname),
+ IsMountPoint: isMountPoint,
+ }
+ reparse := winio.EncodeReparsePoint(&rp)
+ bhdr := winio.BackupHeader{
+ Id: winio.BackupReparseData,
+ Size: int64(len(reparse)),
+ }
+ err := bw.WriteHeader(&bhdr)
+ if err != nil {
+ return nil, err
+ }
+ _, err = bw.Write(reparse)
+ if err != nil {
+ return nil, err
+ }
+ }
+ if hdr.Typeflag == tar.TypeReg || hdr.Typeflag == tar.TypeRegA {
+ bhdr := winio.BackupHeader{
+ Id: winio.BackupData,
+ Size: hdr.Size,
+ }
+ err := bw.WriteHeader(&bhdr)
+ if err != nil {
+ return nil, err
+ }
+ _, err = io.Copy(bw, t)
+ if err != nil {
+ return nil, err
+ }
+ }
+ // Copy all the alternate data streams and return the next non-ADS header.
+ for {
+ ahdr, err := t.Next()
+ if err != nil {
+ return nil, err
+ }
+ if ahdr.Typeflag != tar.TypeReg || !strings.HasPrefix(ahdr.Name, hdr.Name+":") {
+ return ahdr, nil
+ }
+ bhdr := winio.BackupHeader{
+ Id: winio.BackupAlternateData,
+ Size: ahdr.Size,
+ Name: ahdr.Name[len(hdr.Name):] + ":$DATA",
+ }
+ err = bw.WriteHeader(&bhdr)
+ if err != nil {
+ return nil, err
+ }
+ _, err = io.Copy(bw, t)
+ if err != nil {
+ return nil, err
+ }
+ }
+}
diff --git a/vendor/github.com/Microsoft/go-winio/file.go b/vendor/github.com/Microsoft/go-winio/file.go
new file mode 100644
index 0000000..613f31b
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/file.go
@@ -0,0 +1,295 @@
+// +build windows
+
+package winio
+
+import (
+ "errors"
+ "io"
+ "runtime"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "time"
+)
+
+//sys cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) = CancelIoEx
+//sys createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) = CreateIoCompletionPort
+//sys getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) = GetQueuedCompletionStatus
+//sys setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) = SetFileCompletionNotificationModes
+//sys timeBeginPeriod(period uint32) (n int32) = winmm.timeBeginPeriod
+
+type atomicBool int32
+
+func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 }
+func (b *atomicBool) setFalse() { atomic.StoreInt32((*int32)(b), 0) }
+func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) }
+
+const (
+ cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1
+ cFILE_SKIP_SET_EVENT_ON_HANDLE = 2
+)
+
+var (
+ ErrFileClosed = errors.New("file has already been closed")
+ ErrTimeout = &timeoutError{}
+)
+
+type timeoutError struct{}
+
+func (e *timeoutError) Error() string { return "i/o timeout" }
+func (e *timeoutError) Timeout() bool { return true }
+func (e *timeoutError) Temporary() bool { return true }
+
+type timeoutChan chan struct{}
+
+var ioInitOnce sync.Once
+var ioCompletionPort syscall.Handle
+
+// ioResult contains the result of an asynchronous IO operation
+type ioResult struct {
+ bytes uint32
+ err error
+}
+
+// ioOperation represents an outstanding asynchronous Win32 IO
+type ioOperation struct {
+ o syscall.Overlapped
+ ch chan ioResult
+}
+
+func initIo() {
+ h, err := createIoCompletionPort(syscall.InvalidHandle, 0, 0, 0xffffffff)
+ if err != nil {
+ panic(err)
+ }
+ ioCompletionPort = h
+ go ioCompletionProcessor(h)
+}
+
+// win32File implements Reader, Writer, and Closer on a Win32 handle without blocking in a syscall.
+// It takes ownership of this handle and will close it if it is garbage collected.
+type win32File struct {
+ handle syscall.Handle
+ wg sync.WaitGroup
+ closing bool
+ readDeadline deadlineHandler
+ writeDeadline deadlineHandler
+}
+
+type deadlineHandler struct {
+ setLock sync.Mutex
+ channel timeoutChan
+ channelLock sync.RWMutex
+ timer *time.Timer
+ timedout atomicBool
+}
+
+// makeWin32File makes a new win32File from an existing file handle
+func makeWin32File(h syscall.Handle) (*win32File, error) {
+ f := &win32File{handle: h}
+ ioInitOnce.Do(initIo)
+ _, err := createIoCompletionPort(h, ioCompletionPort, 0, 0xffffffff)
+ if err != nil {
+ return nil, err
+ }
+ err = setFileCompletionNotificationModes(h, cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS|cFILE_SKIP_SET_EVENT_ON_HANDLE)
+ if err != nil {
+ return nil, err
+ }
+ f.readDeadline.channel = make(timeoutChan)
+ f.writeDeadline.channel = make(timeoutChan)
+ return f, nil
+}
+
+func MakeOpenFile(h syscall.Handle) (io.ReadWriteCloser, error) {
+ return makeWin32File(h)
+}
+
+// closeHandle closes the resources associated with a Win32 handle
+func (f *win32File) closeHandle() {
+ if !f.closing {
+ // cancel all IO and wait for it to complete
+ f.closing = true
+ cancelIoEx(f.handle, nil)
+ f.wg.Wait()
+ // at this point, no new IO can start
+ syscall.Close(f.handle)
+ f.handle = 0
+ }
+}
+
+// Close closes a win32File.
+func (f *win32File) Close() error {
+ f.closeHandle()
+ return nil
+}
+
+// prepareIo prepares for a new IO operation.
+// The caller must call f.wg.Done() when the IO is finished, prior to Close() returning.
+func (f *win32File) prepareIo() (*ioOperation, error) {
+ f.wg.Add(1)
+ if f.closing {
+ return nil, ErrFileClosed
+ }
+ c := &ioOperation{}
+ c.ch = make(chan ioResult)
+ return c, nil
+}
+
+// ioCompletionProcessor processes completed async IOs forever
+func ioCompletionProcessor(h syscall.Handle) {
+ // Set the timer resolution to 1. This fixes a performance regression in golang 1.6.
+ timeBeginPeriod(1)
+ for {
+ var bytes uint32
+ var key uintptr
+ var op *ioOperation
+ err := getQueuedCompletionStatus(h, &bytes, &key, &op, syscall.INFINITE)
+ if op == nil {
+ panic(err)
+ }
+ op.ch <- ioResult{bytes, err}
+ }
+}
+
+// asyncIo processes the return value from ReadFile or WriteFile, blocking until
+// the operation has actually completed.
+func (f *win32File) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, err error) (int, error) {
+ if err != syscall.ERROR_IO_PENDING {
+ return int(bytes), err
+ }
+
+ if f.closing {
+ cancelIoEx(f.handle, &c.o)
+ }
+
+ var timeout timeoutChan
+ if d != nil {
+ d.channelLock.Lock()
+ timeout = d.channel
+ d.channelLock.Unlock()
+ }
+
+ var r ioResult
+ select {
+ case r = <-c.ch:
+ err = r.err
+ if err == syscall.ERROR_OPERATION_ABORTED {
+ if f.closing {
+ err = ErrFileClosed
+ }
+ }
+ case <-timeout:
+ cancelIoEx(f.handle, &c.o)
+ r = <-c.ch
+ err = r.err
+ if err == syscall.ERROR_OPERATION_ABORTED {
+ err = ErrTimeout
+ }
+ }
+
+ // runtime.KeepAlive is needed, as c is passed via native
+ // code to ioCompletionProcessor, c must remain alive
+ // until the channel read is complete.
+ runtime.KeepAlive(c)
+ return int(r.bytes), err
+}
+
+// Read reads from a file handle.
+func (f *win32File) Read(b []byte) (int, error) {
+ c, err := f.prepareIo()
+ if err != nil {
+ return 0, err
+ }
+ defer f.wg.Done()
+
+ if f.readDeadline.timedout.isSet() {
+ return 0, ErrTimeout
+ }
+
+ var bytes uint32
+ err = syscall.ReadFile(f.handle, b, &bytes, &c.o)
+ n, err := f.asyncIo(c, &f.readDeadline, bytes, err)
+ runtime.KeepAlive(b)
+
+ // Handle EOF conditions.
+ if err == nil && n == 0 && len(b) != 0 {
+ return 0, io.EOF
+ } else if err == syscall.ERROR_BROKEN_PIPE {
+ return 0, io.EOF
+ } else {
+ return n, err
+ }
+}
+
+// Write writes to a file handle.
+func (f *win32File) Write(b []byte) (int, error) {
+ c, err := f.prepareIo()
+ if err != nil {
+ return 0, err
+ }
+ defer f.wg.Done()
+
+ if f.writeDeadline.timedout.isSet() {
+ return 0, ErrTimeout
+ }
+
+ var bytes uint32
+ err = syscall.WriteFile(f.handle, b, &bytes, &c.o)
+ n, err := f.asyncIo(c, &f.writeDeadline, bytes, err)
+ runtime.KeepAlive(b)
+ return n, err
+}
+
+func (f *win32File) SetReadDeadline(deadline time.Time) error {
+ return f.readDeadline.set(deadline)
+}
+
+func (f *win32File) SetWriteDeadline(deadline time.Time) error {
+ return f.writeDeadline.set(deadline)
+}
+
+func (f *win32File) Flush() error {
+ return syscall.FlushFileBuffers(f.handle)
+}
+
+func (d *deadlineHandler) set(deadline time.Time) error {
+ d.setLock.Lock()
+ defer d.setLock.Unlock()
+
+ if d.timer != nil {
+ if !d.timer.Stop() {
+ <-d.channel
+ }
+ d.timer = nil
+ }
+ d.timedout.setFalse()
+
+ select {
+ case <-d.channel:
+ d.channelLock.Lock()
+ d.channel = make(chan struct{})
+ d.channelLock.Unlock()
+ default:
+ }
+
+ if deadline.IsZero() {
+ return nil
+ }
+
+ timeoutIO := func() {
+ d.timedout.setTrue()
+ close(d.channel)
+ }
+
+ now := time.Now()
+ duration := deadline.Sub(now)
+ if deadline.After(now) {
+ // Deadline is in the future, set a timer to wait
+ d.timer = time.AfterFunc(duration, timeoutIO)
+ } else {
+ // Deadline is in the past. Cancel all pending IO now.
+ timeoutIO()
+ }
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/go-winio/fileinfo.go b/vendor/github.com/Microsoft/go-winio/fileinfo.go
new file mode 100644
index 0000000..b1d60ab
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/fileinfo.go
@@ -0,0 +1,60 @@
+// +build windows
+
+package winio
+
+import (
+ "os"
+ "runtime"
+ "syscall"
+ "unsafe"
+)
+
+//sys getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = GetFileInformationByHandleEx
+//sys setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = SetFileInformationByHandle
+
+const (
+ fileBasicInfo = 0
+ fileIDInfo = 0x12
+)
+
+// FileBasicInfo contains file access time and file attributes information.
+type FileBasicInfo struct {
+ CreationTime, LastAccessTime, LastWriteTime, ChangeTime syscall.Filetime
+ FileAttributes uintptr // includes padding
+}
+
+// GetFileBasicInfo retrieves times and attributes for a file.
+func GetFileBasicInfo(f *os.File) (*FileBasicInfo, error) {
+ bi := &FileBasicInfo{}
+ if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil {
+ return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err}
+ }
+ runtime.KeepAlive(f)
+ return bi, nil
+}
+
+// SetFileBasicInfo sets times and attributes for a file.
+func SetFileBasicInfo(f *os.File, bi *FileBasicInfo) error {
+ if err := setFileInformationByHandle(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil {
+ return &os.PathError{Op: "SetFileInformationByHandle", Path: f.Name(), Err: err}
+ }
+ runtime.KeepAlive(f)
+ return nil
+}
+
+// FileIDInfo contains the volume serial number and file ID for a file. This pair should be
+// unique on a system.
+type FileIDInfo struct {
+ VolumeSerialNumber uint64
+ FileID [16]byte
+}
+
+// GetFileID retrieves the unique (volume, file ID) pair for a file.
+func GetFileID(f *os.File) (*FileIDInfo, error) {
+ fileID := &FileIDInfo{}
+ if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileIDInfo, (*byte)(unsafe.Pointer(fileID)), uint32(unsafe.Sizeof(*fileID))); err != nil {
+ return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err}
+ }
+ runtime.KeepAlive(f)
+ return fileID, nil
+}
diff --git a/vendor/github.com/Microsoft/go-winio/pipe.go b/vendor/github.com/Microsoft/go-winio/pipe.go
new file mode 100644
index 0000000..da706cc
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/pipe.go
@@ -0,0 +1,404 @@
+// +build windows
+
+package winio
+
+import (
+ "errors"
+ "io"
+ "net"
+ "os"
+ "syscall"
+ "time"
+ "unsafe"
+)
+
+//sys connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) = ConnectNamedPipe
+//sys createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW
+//sys createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateFileW
+//sys waitNamedPipe(name string, timeout uint32) (err error) = WaitNamedPipeW
+//sys getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) = GetNamedPipeInfo
+//sys getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW
+//sys localAlloc(uFlags uint32, length uint32) (ptr uintptr) = LocalAlloc
+
+const (
+ cERROR_PIPE_BUSY = syscall.Errno(231)
+ cERROR_PIPE_CONNECTED = syscall.Errno(535)
+ cERROR_SEM_TIMEOUT = syscall.Errno(121)
+
+ cPIPE_ACCESS_DUPLEX = 0x3
+ cFILE_FLAG_FIRST_PIPE_INSTANCE = 0x80000
+ cSECURITY_SQOS_PRESENT = 0x100000
+ cSECURITY_ANONYMOUS = 0
+
+ cPIPE_REJECT_REMOTE_CLIENTS = 0x8
+
+ cPIPE_UNLIMITED_INSTANCES = 255
+
+ cNMPWAIT_USE_DEFAULT_WAIT = 0
+ cNMPWAIT_NOWAIT = 1
+
+ cPIPE_TYPE_MESSAGE = 4
+
+ cPIPE_READMODE_MESSAGE = 2
+)
+
+var (
+ // ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed.
+ // This error should match net.errClosing since docker takes a dependency on its text.
+ ErrPipeListenerClosed = errors.New("use of closed network connection")
+
+ errPipeWriteClosed = errors.New("pipe has been closed for write")
+)
+
+type win32Pipe struct {
+ *win32File
+ path string
+}
+
+type win32MessageBytePipe struct {
+ win32Pipe
+ writeClosed bool
+ readEOF bool
+}
+
+type pipeAddress string
+
+func (f *win32Pipe) LocalAddr() net.Addr {
+ return pipeAddress(f.path)
+}
+
+func (f *win32Pipe) RemoteAddr() net.Addr {
+ return pipeAddress(f.path)
+}
+
+func (f *win32Pipe) SetDeadline(t time.Time) error {
+ f.SetReadDeadline(t)
+ f.SetWriteDeadline(t)
+ return nil
+}
+
+// CloseWrite closes the write side of a message pipe in byte mode.
+func (f *win32MessageBytePipe) CloseWrite() error {
+ if f.writeClosed {
+ return errPipeWriteClosed
+ }
+ err := f.win32File.Flush()
+ if err != nil {
+ return err
+ }
+ _, err = f.win32File.Write(nil)
+ if err != nil {
+ return err
+ }
+ f.writeClosed = true
+ return nil
+}
+
+// Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since
+// they are used to implement CloseWrite().
+func (f *win32MessageBytePipe) Write(b []byte) (int, error) {
+ if f.writeClosed {
+ return 0, errPipeWriteClosed
+ }
+ if len(b) == 0 {
+ return 0, nil
+ }
+ return f.win32File.Write(b)
+}
+
+// Read reads bytes from a message pipe in byte mode. A read of a zero-byte message on a message
+// mode pipe will return io.EOF, as will all subsequent reads.
+func (f *win32MessageBytePipe) Read(b []byte) (int, error) {
+ if f.readEOF {
+ return 0, io.EOF
+ }
+ n, err := f.win32File.Read(b)
+ if err == io.EOF {
+ // If this was the result of a zero-byte read, then
+ // it is possible that the read was due to a zero-size
+ // message. Since we are simulating CloseWrite with a
+ // zero-byte message, ensure that all future Read() calls
+ // also return EOF.
+ f.readEOF = true
+ }
+ return n, err
+}
+
+func (s pipeAddress) Network() string {
+ return "pipe"
+}
+
+func (s pipeAddress) String() string {
+ return string(s)
+}
+
+// DialPipe connects to a named pipe by path, timing out if the connection
+// takes longer than the specified duration. If timeout is nil, then the timeout
+// is the default timeout established by the pipe server.
+func DialPipe(path string, timeout *time.Duration) (net.Conn, error) {
+ var absTimeout time.Time
+ if timeout != nil {
+ absTimeout = time.Now().Add(*timeout)
+ }
+ var err error
+ var h syscall.Handle
+ for {
+ h, err = createFile(path, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0)
+ if err != cERROR_PIPE_BUSY {
+ break
+ }
+ now := time.Now()
+ var ms uint32
+ if absTimeout.IsZero() {
+ ms = cNMPWAIT_USE_DEFAULT_WAIT
+ } else if now.After(absTimeout) {
+ ms = cNMPWAIT_NOWAIT
+ } else {
+ ms = uint32(absTimeout.Sub(now).Nanoseconds() / 1000 / 1000)
+ }
+ err = waitNamedPipe(path, ms)
+ if err != nil {
+ if err == cERROR_SEM_TIMEOUT {
+ return nil, ErrTimeout
+ }
+ break
+ }
+ }
+ if err != nil {
+ return nil, &os.PathError{Op: "open", Path: path, Err: err}
+ }
+
+ var flags uint32
+ err = getNamedPipeInfo(h, &flags, nil, nil, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ var state uint32
+ err = getNamedPipeHandleState(h, &state, nil, nil, nil, nil, 0)
+ if err != nil {
+ return nil, err
+ }
+
+ if state&cPIPE_READMODE_MESSAGE != 0 {
+ return nil, &os.PathError{Op: "open", Path: path, Err: errors.New("message readmode pipes not supported")}
+ }
+
+ f, err := makeWin32File(h)
+ if err != nil {
+ syscall.Close(h)
+ return nil, err
+ }
+
+ // If the pipe is in message mode, return a message byte pipe, which
+ // supports CloseWrite().
+ if flags&cPIPE_TYPE_MESSAGE != 0 {
+ return &win32MessageBytePipe{
+ win32Pipe: win32Pipe{win32File: f, path: path},
+ }, nil
+ }
+ return &win32Pipe{win32File: f, path: path}, nil
+}
+
+type acceptResponse struct {
+ f *win32File
+ err error
+}
+
+type win32PipeListener struct {
+ firstHandle syscall.Handle
+ path string
+ securityDescriptor []byte
+ config PipeConfig
+ acceptCh chan (chan acceptResponse)
+ closeCh chan int
+ doneCh chan int
+}
+
+func makeServerPipeHandle(path string, securityDescriptor []byte, c *PipeConfig, first bool) (syscall.Handle, error) {
+ var flags uint32 = cPIPE_ACCESS_DUPLEX | syscall.FILE_FLAG_OVERLAPPED
+ if first {
+ flags |= cFILE_FLAG_FIRST_PIPE_INSTANCE
+ }
+
+ var mode uint32 = cPIPE_REJECT_REMOTE_CLIENTS
+ if c.MessageMode {
+ mode |= cPIPE_TYPE_MESSAGE
+ }
+
+ sa := &syscall.SecurityAttributes{}
+ sa.Length = uint32(unsafe.Sizeof(*sa))
+ if securityDescriptor != nil {
+ len := uint32(len(securityDescriptor))
+ sa.SecurityDescriptor = localAlloc(0, len)
+ defer localFree(sa.SecurityDescriptor)
+ copy((*[0xffff]byte)(unsafe.Pointer(sa.SecurityDescriptor))[:], securityDescriptor)
+ }
+ h, err := createNamedPipe(path, flags, mode, cPIPE_UNLIMITED_INSTANCES, uint32(c.OutputBufferSize), uint32(c.InputBufferSize), 0, sa)
+ if err != nil {
+ return 0, &os.PathError{Op: "open", Path: path, Err: err}
+ }
+ return h, nil
+}
+
+func (l *win32PipeListener) makeServerPipe() (*win32File, error) {
+ h, err := makeServerPipeHandle(l.path, l.securityDescriptor, &l.config, false)
+ if err != nil {
+ return nil, err
+ }
+ f, err := makeWin32File(h)
+ if err != nil {
+ syscall.Close(h)
+ return nil, err
+ }
+ return f, nil
+}
+
+func (l *win32PipeListener) listenerRoutine() {
+ closed := false
+ for !closed {
+ select {
+ case <-l.closeCh:
+ closed = true
+ case responseCh := <-l.acceptCh:
+ p, err := l.makeServerPipe()
+ if err == nil {
+ // Wait for the client to connect.
+ ch := make(chan error)
+ go func() {
+ ch <- connectPipe(p)
+ }()
+ select {
+ case err = <-ch:
+ if err != nil {
+ p.Close()
+ p = nil
+ }
+ case <-l.closeCh:
+ // Abort the connect request by closing the handle.
+ p.Close()
+ p = nil
+ err = <-ch
+ if err == nil || err == ErrFileClosed {
+ err = ErrPipeListenerClosed
+ }
+ closed = true
+ }
+ }
+ responseCh <- acceptResponse{p, err}
+ }
+ }
+ syscall.Close(l.firstHandle)
+ l.firstHandle = 0
+ // Notify Close() and Accept() callers that the handle has been closed.
+ close(l.doneCh)
+}
+
+// PipeConfig contain configuration for the pipe listener.
+type PipeConfig struct {
+ // SecurityDescriptor contains a Windows security descriptor in SDDL format.
+ SecurityDescriptor string
+
+ // MessageMode determines whether the pipe is in byte or message mode. In either
+ // case the pipe is read in byte mode by default. The only practical difference in
+ // this implementation is that CloseWrite() is only supported for message mode pipes;
+ // CloseWrite() is implemented as a zero-byte write, but zero-byte writes are only
+ // transferred to the reader (and returned as io.EOF in this implementation)
+ // when the pipe is in message mode.
+ MessageMode bool
+
+ // InputBufferSize specifies the size the input buffer, in bytes.
+ InputBufferSize int32
+
+ // OutputBufferSize specifies the size the input buffer, in bytes.
+ OutputBufferSize int32
+}
+
+// ListenPipe creates a listener on a Windows named pipe path, e.g. \\.\pipe\mypipe.
+// The pipe must not already exist.
+func ListenPipe(path string, c *PipeConfig) (net.Listener, error) {
+ var (
+ sd []byte
+ err error
+ )
+ if c == nil {
+ c = &PipeConfig{}
+ }
+ if c.SecurityDescriptor != "" {
+ sd, err = SddlToSecurityDescriptor(c.SecurityDescriptor)
+ if err != nil {
+ return nil, err
+ }
+ }
+ h, err := makeServerPipeHandle(path, sd, c, true)
+ if err != nil {
+ return nil, err
+ }
+ // Immediately open and then close a client handle so that the named pipe is
+ // created but not currently accepting connections.
+ h2, err := createFile(path, 0, 0, nil, syscall.OPEN_EXISTING, cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0)
+ if err != nil {
+ syscall.Close(h)
+ return nil, err
+ }
+ syscall.Close(h2)
+ l := &win32PipeListener{
+ firstHandle: h,
+ path: path,
+ securityDescriptor: sd,
+ config: *c,
+ acceptCh: make(chan (chan acceptResponse)),
+ closeCh: make(chan int),
+ doneCh: make(chan int),
+ }
+ go l.listenerRoutine()
+ return l, nil
+}
+
+func connectPipe(p *win32File) error {
+ c, err := p.prepareIo()
+ if err != nil {
+ return err
+ }
+ defer p.wg.Done()
+
+ err = connectNamedPipe(p.handle, &c.o)
+ _, err = p.asyncIo(c, nil, 0, err)
+ if err != nil && err != cERROR_PIPE_CONNECTED {
+ return err
+ }
+ return nil
+}
+
+func (l *win32PipeListener) Accept() (net.Conn, error) {
+ ch := make(chan acceptResponse)
+ select {
+ case l.acceptCh <- ch:
+ response := <-ch
+ err := response.err
+ if err != nil {
+ return nil, err
+ }
+ if l.config.MessageMode {
+ return &win32MessageBytePipe{
+ win32Pipe: win32Pipe{win32File: response.f, path: l.path},
+ }, nil
+ }
+ return &win32Pipe{win32File: response.f, path: l.path}, nil
+ case <-l.doneCh:
+ return nil, ErrPipeListenerClosed
+ }
+}
+
+func (l *win32PipeListener) Close() error {
+ select {
+ case l.closeCh <- 1:
+ <-l.doneCh
+ case <-l.doneCh:
+ }
+ return nil
+}
+
+func (l *win32PipeListener) Addr() net.Addr {
+ return pipeAddress(l.path)
+}
diff --git a/vendor/github.com/Microsoft/go-winio/privilege.go b/vendor/github.com/Microsoft/go-winio/privilege.go
new file mode 100644
index 0000000..9c83d36
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/privilege.go
@@ -0,0 +1,202 @@
+// +build windows
+
+package winio
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "runtime"
+ "sync"
+ "syscall"
+ "unicode/utf16"
+
+ "golang.org/x/sys/windows"
+)
+
+//sys adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges
+//sys impersonateSelf(level uint32) (err error) = advapi32.ImpersonateSelf
+//sys revertToSelf() (err error) = advapi32.RevertToSelf
+//sys openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) = advapi32.OpenThreadToken
+//sys getCurrentThread() (h syscall.Handle) = GetCurrentThread
+//sys lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) = advapi32.LookupPrivilegeValueW
+//sys lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW
+//sys lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW
+
+const (
+ SE_PRIVILEGE_ENABLED = 2
+
+ ERROR_NOT_ALL_ASSIGNED syscall.Errno = 1300
+
+ SeBackupPrivilege = "SeBackupPrivilege"
+ SeRestorePrivilege = "SeRestorePrivilege"
+)
+
+const (
+ securityAnonymous = iota
+ securityIdentification
+ securityImpersonation
+ securityDelegation
+)
+
+var (
+ privNames = make(map[string]uint64)
+ privNameMutex sync.Mutex
+)
+
+// PrivilegeError represents an error enabling privileges.
+type PrivilegeError struct {
+ privileges []uint64
+}
+
+func (e *PrivilegeError) Error() string {
+ s := ""
+ if len(e.privileges) > 1 {
+ s = "Could not enable privileges "
+ } else {
+ s = "Could not enable privilege "
+ }
+ for i, p := range e.privileges {
+ if i != 0 {
+ s += ", "
+ }
+ s += `"`
+ s += getPrivilegeName(p)
+ s += `"`
+ }
+ return s
+}
+
+// RunWithPrivilege enables a single privilege for a function call.
+func RunWithPrivilege(name string, fn func() error) error {
+ return RunWithPrivileges([]string{name}, fn)
+}
+
+// RunWithPrivileges enables privileges for a function call.
+func RunWithPrivileges(names []string, fn func() error) error {
+ privileges, err := mapPrivileges(names)
+ if err != nil {
+ return err
+ }
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ token, err := newThreadToken()
+ if err != nil {
+ return err
+ }
+ defer releaseThreadToken(token)
+ err = adjustPrivileges(token, privileges, SE_PRIVILEGE_ENABLED)
+ if err != nil {
+ return err
+ }
+ return fn()
+}
+
+func mapPrivileges(names []string) ([]uint64, error) {
+ var privileges []uint64
+ privNameMutex.Lock()
+ defer privNameMutex.Unlock()
+ for _, name := range names {
+ p, ok := privNames[name]
+ if !ok {
+ err := lookupPrivilegeValue("", name, &p)
+ if err != nil {
+ return nil, err
+ }
+ privNames[name] = p
+ }
+ privileges = append(privileges, p)
+ }
+ return privileges, nil
+}
+
+// EnableProcessPrivileges enables privileges globally for the process.
+func EnableProcessPrivileges(names []string) error {
+ return enableDisableProcessPrivilege(names, SE_PRIVILEGE_ENABLED)
+}
+
+// DisableProcessPrivileges disables privileges globally for the process.
+func DisableProcessPrivileges(names []string) error {
+ return enableDisableProcessPrivilege(names, 0)
+}
+
+func enableDisableProcessPrivilege(names []string, action uint32) error {
+ privileges, err := mapPrivileges(names)
+ if err != nil {
+ return err
+ }
+
+ p, _ := windows.GetCurrentProcess()
+ var token windows.Token
+ err = windows.OpenProcessToken(p, windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, &token)
+ if err != nil {
+ return err
+ }
+
+ defer token.Close()
+ return adjustPrivileges(token, privileges, action)
+}
+
+func adjustPrivileges(token windows.Token, privileges []uint64, action uint32) error {
+ var b bytes.Buffer
+ binary.Write(&b, binary.LittleEndian, uint32(len(privileges)))
+ for _, p := range privileges {
+ binary.Write(&b, binary.LittleEndian, p)
+ binary.Write(&b, binary.LittleEndian, action)
+ }
+ prevState := make([]byte, b.Len())
+ reqSize := uint32(0)
+ success, err := adjustTokenPrivileges(token, false, &b.Bytes()[0], uint32(len(prevState)), &prevState[0], &reqSize)
+ if !success {
+ return err
+ }
+ if err == ERROR_NOT_ALL_ASSIGNED {
+ return &PrivilegeError{privileges}
+ }
+ return nil
+}
+
+func getPrivilegeName(luid uint64) string {
+ var nameBuffer [256]uint16
+ bufSize := uint32(len(nameBuffer))
+ err := lookupPrivilegeName("", &luid, &nameBuffer[0], &bufSize)
+ if err != nil {
+ return fmt.Sprintf("<unknown privilege %d>", luid)
+ }
+
+ var displayNameBuffer [256]uint16
+ displayBufSize := uint32(len(displayNameBuffer))
+ var langID uint32
+ err = lookupPrivilegeDisplayName("", &nameBuffer[0], &displayNameBuffer[0], &displayBufSize, &langID)
+ if err != nil {
+ return fmt.Sprintf("<unknown privilege %s>", string(utf16.Decode(nameBuffer[:bufSize])))
+ }
+
+ return string(utf16.Decode(displayNameBuffer[:displayBufSize]))
+}
+
+func newThreadToken() (windows.Token, error) {
+ err := impersonateSelf(securityImpersonation)
+ if err != nil {
+ return 0, err
+ }
+
+ var token windows.Token
+ err = openThreadToken(getCurrentThread(), syscall.TOKEN_ADJUST_PRIVILEGES|syscall.TOKEN_QUERY, false, &token)
+ if err != nil {
+ rerr := revertToSelf()
+ if rerr != nil {
+ panic(rerr)
+ }
+ return 0, err
+ }
+ return token, nil
+}
+
+func releaseThreadToken(h windows.Token) {
+ err := revertToSelf()
+ if err != nil {
+ panic(err)
+ }
+ h.Close()
+}
diff --git a/vendor/github.com/Microsoft/go-winio/reparse.go b/vendor/github.com/Microsoft/go-winio/reparse.go
new file mode 100644
index 0000000..fc1ee4d
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/reparse.go
@@ -0,0 +1,128 @@
+package winio
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "strings"
+ "unicode/utf16"
+ "unsafe"
+)
+
+const (
+ reparseTagMountPoint = 0xA0000003
+ reparseTagSymlink = 0xA000000C
+)
+
+type reparseDataBuffer struct {
+ ReparseTag uint32
+ ReparseDataLength uint16
+ Reserved uint16
+ SubstituteNameOffset uint16
+ SubstituteNameLength uint16
+ PrintNameOffset uint16
+ PrintNameLength uint16
+}
+
+// ReparsePoint describes a Win32 symlink or mount point.
+type ReparsePoint struct {
+ Target string
+ IsMountPoint bool
+}
+
+// UnsupportedReparsePointError is returned when trying to decode a non-symlink or
+// mount point reparse point.
+type UnsupportedReparsePointError struct {
+ Tag uint32
+}
+
+func (e *UnsupportedReparsePointError) Error() string {
+ return fmt.Sprintf("unsupported reparse point %x", e.Tag)
+}
+
+// DecodeReparsePoint decodes a Win32 REPARSE_DATA_BUFFER structure containing either a symlink
+// or a mount point.
+func DecodeReparsePoint(b []byte) (*ReparsePoint, error) {
+ tag := binary.LittleEndian.Uint32(b[0:4])
+ return DecodeReparsePointData(tag, b[8:])
+}
+
+func DecodeReparsePointData(tag uint32, b []byte) (*ReparsePoint, error) {
+ isMountPoint := false
+ switch tag {
+ case reparseTagMountPoint:
+ isMountPoint = true
+ case reparseTagSymlink:
+ default:
+ return nil, &UnsupportedReparsePointError{tag}
+ }
+ nameOffset := 8 + binary.LittleEndian.Uint16(b[4:6])
+ if !isMountPoint {
+ nameOffset += 4
+ }
+ nameLength := binary.LittleEndian.Uint16(b[6:8])
+ name := make([]uint16, nameLength/2)
+ err := binary.Read(bytes.NewReader(b[nameOffset:nameOffset+nameLength]), binary.LittleEndian, &name)
+ if err != nil {
+ return nil, err
+ }
+ return &ReparsePoint{string(utf16.Decode(name)), isMountPoint}, nil
+}
+
+func isDriveLetter(c byte) bool {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
+}
+
+// EncodeReparsePoint encodes a Win32 REPARSE_DATA_BUFFER structure describing a symlink or
+// mount point.
+func EncodeReparsePoint(rp *ReparsePoint) []byte {
+ // Generate an NT path and determine if this is a relative path.
+ var ntTarget string
+ relative := false
+ if strings.HasPrefix(rp.Target, `\\?\`) {
+ ntTarget = `\??\` + rp.Target[4:]
+ } else if strings.HasPrefix(rp.Target, `\\`) {
+ ntTarget = `\??\UNC\` + rp.Target[2:]
+ } else if len(rp.Target) >= 2 && isDriveLetter(rp.Target[0]) && rp.Target[1] == ':' {
+ ntTarget = `\??\` + rp.Target
+ } else {
+ ntTarget = rp.Target
+ relative = true
+ }
+
+ // The paths must be NUL-terminated even though they are counted strings.
+ target16 := utf16.Encode([]rune(rp.Target + "\x00"))
+ ntTarget16 := utf16.Encode([]rune(ntTarget + "\x00"))
+
+ size := int(unsafe.Sizeof(reparseDataBuffer{})) - 8
+ size += len(ntTarget16)*2 + len(target16)*2
+
+ tag := uint32(reparseTagMountPoint)
+ if !rp.IsMountPoint {
+ tag = reparseTagSymlink
+ size += 4 // Add room for symlink flags
+ }
+
+ data := reparseDataBuffer{
+ ReparseTag: tag,
+ ReparseDataLength: uint16(size),
+ SubstituteNameOffset: 0,
+ SubstituteNameLength: uint16((len(ntTarget16) - 1) * 2),
+ PrintNameOffset: uint16(len(ntTarget16) * 2),
+ PrintNameLength: uint16((len(target16) - 1) * 2),
+ }
+
+ var b bytes.Buffer
+ binary.Write(&b, binary.LittleEndian, &data)
+ if !rp.IsMountPoint {
+ flags := uint32(0)
+ if relative {
+ flags |= 1
+ }
+ binary.Write(&b, binary.LittleEndian, flags)
+ }
+
+ binary.Write(&b, binary.LittleEndian, ntTarget16)
+ binary.Write(&b, binary.LittleEndian, target16)
+ return b.Bytes()
+}
diff --git a/vendor/github.com/Microsoft/go-winio/sd.go b/vendor/github.com/Microsoft/go-winio/sd.go
new file mode 100644
index 0000000..db1b370
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/sd.go
@@ -0,0 +1,98 @@
+// +build windows
+
+package winio
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+//sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW
+//sys convertSidToStringSid(sid *byte, str **uint16) (err error) = advapi32.ConvertSidToStringSidW
+//sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW
+//sys convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW
+//sys localFree(mem uintptr) = LocalFree
+//sys getSecurityDescriptorLength(sd uintptr) (len uint32) = advapi32.GetSecurityDescriptorLength
+
+const (
+ cERROR_NONE_MAPPED = syscall.Errno(1332)
+)
+
+type AccountLookupError struct {
+ Name string
+ Err error
+}
+
+func (e *AccountLookupError) Error() string {
+ if e.Name == "" {
+ return "lookup account: empty account name specified"
+ }
+ var s string
+ switch e.Err {
+ case cERROR_NONE_MAPPED:
+ s = "not found"
+ default:
+ s = e.Err.Error()
+ }
+ return "lookup account " + e.Name + ": " + s
+}
+
+type SddlConversionError struct {
+ Sddl string
+ Err error
+}
+
+func (e *SddlConversionError) Error() string {
+ return "convert " + e.Sddl + ": " + e.Err.Error()
+}
+
+// LookupSidByName looks up the SID of an account by name
+func LookupSidByName(name string) (sid string, err error) {
+ if name == "" {
+ return "", &AccountLookupError{name, cERROR_NONE_MAPPED}
+ }
+
+ var sidSize, sidNameUse, refDomainSize uint32
+ err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse)
+ if err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER {
+ return "", &AccountLookupError{name, err}
+ }
+ sidBuffer := make([]byte, sidSize)
+ refDomainBuffer := make([]uint16, refDomainSize)
+ err = lookupAccountName(nil, name, &sidBuffer[0], &sidSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse)
+ if err != nil {
+ return "", &AccountLookupError{name, err}
+ }
+ var strBuffer *uint16
+ err = convertSidToStringSid(&sidBuffer[0], &strBuffer)
+ if err != nil {
+ return "", &AccountLookupError{name, err}
+ }
+ sid = syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(strBuffer))[:])
+ localFree(uintptr(unsafe.Pointer(strBuffer)))
+ return sid, nil
+}
+
+func SddlToSecurityDescriptor(sddl string) ([]byte, error) {
+ var sdBuffer uintptr
+ err := convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &sdBuffer, nil)
+ if err != nil {
+ return nil, &SddlConversionError{sddl, err}
+ }
+ defer localFree(sdBuffer)
+ sd := make([]byte, getSecurityDescriptorLength(sdBuffer))
+ copy(sd, (*[0xffff]byte)(unsafe.Pointer(sdBuffer))[:len(sd)])
+ return sd, nil
+}
+
+func SecurityDescriptorToSddl(sd []byte) (string, error) {
+ var sddl *uint16
+ // The returned string length seems to including an aribtrary number of terminating NULs.
+ // Don't use it.
+ err := convertSecurityDescriptorToStringSecurityDescriptor(&sd[0], 1, 0xff, &sddl, nil)
+ if err != nil {
+ return "", err
+ }
+ defer localFree(uintptr(unsafe.Pointer(sddl)))
+ return syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(sddl))[:]), nil
+}
diff --git a/vendor/github.com/Microsoft/go-winio/syscall.go b/vendor/github.com/Microsoft/go-winio/syscall.go
new file mode 100644
index 0000000..20d64cf
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/syscall.go
@@ -0,0 +1,3 @@
+package winio
+
+//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go file.go pipe.go sd.go fileinfo.go privilege.go backup.go
diff --git a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go
new file mode 100644
index 0000000..4f7a52e
--- /dev/null
+++ b/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go
@@ -0,0 +1,528 @@
+// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT
+
+package winio
+
+import (
+ "syscall"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+var _ unsafe.Pointer
+
+// Do the interface allocations only once for common
+// Errno values.
+const (
+ errnoERROR_IO_PENDING = 997
+)
+
+var (
+ errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
+)
+
+// errnoErr returns common boxed Errno values, to prevent
+// allocations at runtime.
+func errnoErr(e syscall.Errno) error {
+ switch e {
+ case 0:
+ return nil
+ case errnoERROR_IO_PENDING:
+ return errERROR_IO_PENDING
+ }
+ // TODO: add more here, after collecting data on the common
+ // error values see on Windows. (perhaps when running
+ // all.bat?)
+ return e
+}
+
+var (
+ modkernel32 = windows.NewLazySystemDLL("kernel32.dll")
+ modwinmm = windows.NewLazySystemDLL("winmm.dll")
+ modadvapi32 = windows.NewLazySystemDLL("advapi32.dll")
+
+ procCancelIoEx = modkernel32.NewProc("CancelIoEx")
+ procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort")
+ procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus")
+ procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes")
+ proctimeBeginPeriod = modwinmm.NewProc("timeBeginPeriod")
+ procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe")
+ procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW")
+ procCreateFileW = modkernel32.NewProc("CreateFileW")
+ procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW")
+ procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo")
+ procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW")
+ procLocalAlloc = modkernel32.NewProc("LocalAlloc")
+ procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW")
+ procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW")
+ procConvertStringSecurityDescriptorToSecurityDescriptorW = modadvapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW")
+ procConvertSecurityDescriptorToStringSecurityDescriptorW = modadvapi32.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW")
+ procLocalFree = modkernel32.NewProc("LocalFree")
+ procGetSecurityDescriptorLength = modadvapi32.NewProc("GetSecurityDescriptorLength")
+ procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx")
+ procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle")
+ procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
+ procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf")
+ procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
+ procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken")
+ procGetCurrentThread = modkernel32.NewProc("GetCurrentThread")
+ procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW")
+ procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW")
+ procLookupPrivilegeDisplayNameW = modadvapi32.NewProc("LookupPrivilegeDisplayNameW")
+ procBackupRead = modkernel32.NewProc("BackupRead")
+ procBackupWrite = modkernel32.NewProc("BackupWrite")
+)
+
+func cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) {
+ r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(file), uintptr(unsafe.Pointer(o)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) {
+ r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(file), uintptr(port), uintptr(key), uintptr(threadCount), 0, 0)
+ newport = syscall.Handle(r0)
+ if newport == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(port), uintptr(unsafe.Pointer(bytes)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(o)), uintptr(timeout), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetFileCompletionNotificationModes.Addr(), 2, uintptr(h), uintptr(flags), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func timeBeginPeriod(period uint32) (n int32) {
+ r0, _, _ := syscall.Syscall(proctimeBeginPeriod.Addr(), 1, uintptr(period), 0, 0)
+ n = int32(r0)
+ return
+}
+
+func connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) {
+ r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(o)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) {
+ var _p0 *uint16
+ _p0, err = syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return
+ }
+ return _createNamedPipe(_p0, flags, pipeMode, maxInstances, outSize, inSize, defaultTimeout, sa)
+}
+
+func _createNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) {
+ r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(pipeMode), uintptr(maxInstances), uintptr(outSize), uintptr(inSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0)
+ handle = syscall.Handle(r0)
+ if handle == syscall.InvalidHandle {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) {
+ var _p0 *uint16
+ _p0, err = syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return
+ }
+ return _createFile(_p0, access, mode, sa, createmode, attrs, templatefile)
+}
+
+func _createFile(name *uint16, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) {
+ r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0)
+ handle = syscall.Handle(r0)
+ if handle == syscall.InvalidHandle {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func waitNamedPipe(name string, timeout uint32) (err error) {
+ var _p0 *uint16
+ _p0, err = syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return
+ }
+ return _waitNamedPipe(_p0, timeout)
+}
+
+func _waitNamedPipe(name *uint16, timeout uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procGetNamedPipeInfo.Addr(), 5, uintptr(pipe), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(outSize)), uintptr(unsafe.Pointer(inSize)), uintptr(unsafe.Pointer(maxInstances)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) {
+ r1, _, e1 := syscall.Syscall9(procGetNamedPipeHandleStateW.Addr(), 7, uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func localAlloc(uFlags uint32, length uint32) (ptr uintptr) {
+ r0, _, _ := syscall.Syscall(procLocalAlloc.Addr(), 2, uintptr(uFlags), uintptr(length), 0)
+ ptr = uintptr(r0)
+ return
+}
+
+func lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) {
+ var _p0 *uint16
+ _p0, err = syscall.UTF16PtrFromString(accountName)
+ if err != nil {
+ return
+ }
+ return _lookupAccountName(systemName, _p0, sid, sidSize, refDomain, refDomainSize, sidNameUse)
+}
+
+func _lookupAccountName(systemName *uint16, accountName *uint16, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall9(procLookupAccountNameW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidSize)), uintptr(unsafe.Pointer(refDomain)), uintptr(unsafe.Pointer(refDomainSize)), uintptr(unsafe.Pointer(sidNameUse)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func convertSidToStringSid(sid *byte, str **uint16) (err error) {
+ r1, _, e1 := syscall.Syscall(procConvertSidToStringSidW.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(str)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) {
+ var _p0 *uint16
+ _p0, err = syscall.UTF16PtrFromString(str)
+ if err != nil {
+ return
+ }
+ return _convertStringSecurityDescriptorToSecurityDescriptor(_p0, revision, sd, size)
+}
+
+func _convertStringSecurityDescriptorToSecurityDescriptor(str *uint16, revision uint32, sd *uintptr, size *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procConvertStringSecurityDescriptorToSecurityDescriptorW.Addr(), 4, uintptr(unsafe.Pointer(str)), uintptr(revision), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(size)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procConvertSecurityDescriptorToStringSecurityDescriptorW.Addr(), 5, uintptr(unsafe.Pointer(sd)), uintptr(revision), uintptr(secInfo), uintptr(unsafe.Pointer(sddl)), uintptr(unsafe.Pointer(sddlSize)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func localFree(mem uintptr) {
+ syscall.Syscall(procLocalFree.Addr(), 1, uintptr(mem), 0, 0)
+ return
+}
+
+func getSecurityDescriptorLength(sd uintptr) (len uint32) {
+ r0, _, _ := syscall.Syscall(procGetSecurityDescriptorLength.Addr(), 1, uintptr(sd), 0, 0)
+ len = uint32(r0)
+ return
+}
+
+func getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), 4, uintptr(h), uintptr(class), uintptr(unsafe.Pointer(buffer)), uintptr(size), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procSetFileInformationByHandle.Addr(), 4, uintptr(h), uintptr(class), uintptr(unsafe.Pointer(buffer)), uintptr(size), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) {
+ var _p0 uint32
+ if releaseAll {
+ _p0 = 1
+ } else {
+ _p0 = 0
+ }
+ r0, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(input)), uintptr(outputSize), uintptr(unsafe.Pointer(output)), uintptr(unsafe.Pointer(requiredSize)))
+ success = r0 != 0
+ if true {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func impersonateSelf(level uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(level), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func revertToSelf() (err error) {
+ r1, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) {
+ var _p0 uint32
+ if openAsSelf {
+ _p0 = 1
+ } else {
+ _p0 = 0
+ }
+ r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(thread), uintptr(accessMask), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func getCurrentThread() (h syscall.Handle) {
+ r0, _, _ := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0)
+ h = syscall.Handle(r0)
+ return
+}
+
+func lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) {
+ var _p0 *uint16
+ _p0, err = syscall.UTF16PtrFromString(systemName)
+ if err != nil {
+ return
+ }
+ var _p1 *uint16
+ _p1, err = syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return
+ }
+ return _lookupPrivilegeValue(_p0, _p1, luid)
+}
+
+func _lookupPrivilegeValue(systemName *uint16, name *uint16, luid *uint64) (err error) {
+ r1, _, e1 := syscall.Syscall(procLookupPrivilegeValueW.Addr(), 3, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) {
+ var _p0 *uint16
+ _p0, err = syscall.UTF16PtrFromString(systemName)
+ if err != nil {
+ return
+ }
+ return _lookupPrivilegeName(_p0, luid, buffer, size)
+}
+
+func _lookupPrivilegeName(systemName *uint16, luid *uint64, buffer *uint16, size *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procLookupPrivilegeNameW.Addr(), 4, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(luid)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) {
+ var _p0 *uint16
+ _p0, err = syscall.UTF16PtrFromString(systemName)
+ if err != nil {
+ return
+ }
+ return _lookupPrivilegeDisplayName(_p0, name, buffer, size, languageId)
+}
+
+func _lookupPrivilegeDisplayName(systemName *uint16, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procLookupPrivilegeDisplayNameW.Addr(), 5, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), uintptr(unsafe.Pointer(languageId)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) {
+ var _p0 *byte
+ if len(b) > 0 {
+ _p0 = &b[0]
+ }
+ var _p1 uint32
+ if abort {
+ _p1 = 1
+ } else {
+ _p1 = 0
+ }
+ var _p2 uint32
+ if processSecurity {
+ _p2 = 1
+ } else {
+ _p2 = 0
+ }
+ r1, _, e1 := syscall.Syscall9(procBackupRead.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesRead)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) {
+ var _p0 *byte
+ if len(b) > 0 {
+ _p0 = &b[0]
+ }
+ var _p1 uint32
+ if abort {
+ _p1 = 1
+ } else {
+ _p1 = 0
+ }
+ var _p2 uint32
+ if processSecurity {
+ _p2 = 1
+ } else {
+ _p2 = 0
+ }
+ r1, _, e1 := syscall.Syscall9(procBackupWrite.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesWritten)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/LICENSE b/vendor/github.com/Microsoft/hcsshim/LICENSE
new file mode 100644
index 0000000..49d2166
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 Microsoft
+
+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/Microsoft/hcsshim/README.md b/vendor/github.com/Microsoft/hcsshim/README.md
new file mode 100644
index 0000000..30991a1
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/README.md
@@ -0,0 +1,12 @@
+# hcsshim
+
+This package supports launching Windows Server containers from Go. It is
+primarily used in the [Docker Engine](https://github.com/docker/docker) project,
+but it can be freely used by other projects as well.
+
+This project has adopted the [Microsoft Open Source Code of
+Conduct](https://opensource.microsoft.com/codeofconduct/). For more information
+see the [Code of Conduct
+FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact
+[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional
+questions or comments.
diff --git a/vendor/github.com/Microsoft/hcsshim/activatelayer.go b/vendor/github.com/Microsoft/hcsshim/activatelayer.go
new file mode 100644
index 0000000..efc4d80
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/activatelayer.go
@@ -0,0 +1,28 @@
+package hcsshim
+
+import "github.com/Sirupsen/logrus"
+
+// ActivateLayer will find the layer with the given id and mount it's filesystem.
+// For a read/write layer, the mounted filesystem will appear as a volume on the
+// host, while a read-only layer is generally expected to be a no-op.
+// An activated layer must later be deactivated via DeactivateLayer.
+func ActivateLayer(info DriverInfo, id string) error {
+ title := "hcsshim::ActivateLayer "
+ logrus.Debugf(title+"Flavour %d ID %s", info.Flavour, id)
+
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return err
+ }
+
+ err = activateLayer(&infop, id)
+ if err != nil {
+ err = makeErrorf(err, title, "id=%s flavour=%d", id, info.Flavour)
+ logrus.Error(err)
+ return err
+ }
+
+ logrus.Debugf(title+" - succeeded id=%s flavour=%d", id, info.Flavour)
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/baselayer.go b/vendor/github.com/Microsoft/hcsshim/baselayer.go
new file mode 100644
index 0000000..9babd4e
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/baselayer.go
@@ -0,0 +1,183 @@
+package hcsshim
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "syscall"
+
+ "github.com/Microsoft/go-winio"
+)
+
+type baseLayerWriter struct {
+ root string
+ f *os.File
+ bw *winio.BackupFileWriter
+ err error
+ hasUtilityVM bool
+ dirInfo []dirInfo
+}
+
+type dirInfo struct {
+ path string
+ fileInfo winio.FileBasicInfo
+}
+
+// reapplyDirectoryTimes reapplies directory modification, creation, etc. times
+// after processing of the directory tree has completed. The times are expected
+// to be ordered such that parent directories come before child directories.
+func reapplyDirectoryTimes(dis []dirInfo) error {
+ for i := range dis {
+ di := &dis[len(dis)-i-1] // reverse order: process child directories first
+ f, err := winio.OpenForBackup(di.path, syscall.GENERIC_READ|syscall.GENERIC_WRITE, syscall.FILE_SHARE_READ, syscall.OPEN_EXISTING)
+ if err != nil {
+ return err
+ }
+
+ err = winio.SetFileBasicInfo(f, &di.fileInfo)
+ f.Close()
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (w *baseLayerWriter) closeCurrentFile() error {
+ if w.f != nil {
+ err := w.bw.Close()
+ err2 := w.f.Close()
+ w.f = nil
+ w.bw = nil
+ if err != nil {
+ return err
+ }
+ if err2 != nil {
+ return err2
+ }
+ }
+ return nil
+}
+
+func (w *baseLayerWriter) Add(name string, fileInfo *winio.FileBasicInfo) (err error) {
+ defer func() {
+ if err != nil {
+ w.err = err
+ }
+ }()
+
+ err = w.closeCurrentFile()
+ if err != nil {
+ return err
+ }
+
+ if filepath.ToSlash(name) == `UtilityVM/Files` {
+ w.hasUtilityVM = true
+ }
+
+ path := filepath.Join(w.root, name)
+ path, err = makeLongAbsPath(path)
+ if err != nil {
+ return err
+ }
+
+ var f *os.File
+ defer func() {
+ if f != nil {
+ f.Close()
+ }
+ }()
+
+ createmode := uint32(syscall.CREATE_NEW)
+ if fileInfo.FileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 {
+ err := os.Mkdir(path, 0)
+ if err != nil && !os.IsExist(err) {
+ return err
+ }
+ createmode = syscall.OPEN_EXISTING
+ if fileInfo.FileAttributes&syscall.FILE_ATTRIBUTE_REPARSE_POINT == 0 {
+ w.dirInfo = append(w.dirInfo, dirInfo{path, *fileInfo})
+ }
+ }
+
+ mode := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE | winio.WRITE_DAC | winio.WRITE_OWNER | winio.ACCESS_SYSTEM_SECURITY)
+ f, err = winio.OpenForBackup(path, mode, syscall.FILE_SHARE_READ, createmode)
+ if err != nil {
+ return makeError(err, "Failed to OpenForBackup", path)
+ }
+
+ err = winio.SetFileBasicInfo(f, fileInfo)
+ if err != nil {
+ return makeError(err, "Failed to SetFileBasicInfo", path)
+ }
+
+ w.f = f
+ w.bw = winio.NewBackupFileWriter(f, true)
+ f = nil
+ return nil
+}
+
+func (w *baseLayerWriter) AddLink(name string, target string) (err error) {
+ defer func() {
+ if err != nil {
+ w.err = err
+ }
+ }()
+
+ err = w.closeCurrentFile()
+ if err != nil {
+ return err
+ }
+
+ linkpath, err := makeLongAbsPath(filepath.Join(w.root, name))
+ if err != nil {
+ return err
+ }
+
+ linktarget, err := makeLongAbsPath(filepath.Join(w.root, target))
+ if err != nil {
+ return err
+ }
+
+ return os.Link(linktarget, linkpath)
+}
+
+func (w *baseLayerWriter) Remove(name string) error {
+ return errors.New("base layer cannot have tombstones")
+}
+
+func (w *baseLayerWriter) Write(b []byte) (int, error) {
+ n, err := w.bw.Write(b)
+ if err != nil {
+ w.err = err
+ }
+ return n, err
+}
+
+func (w *baseLayerWriter) Close() error {
+ err := w.closeCurrentFile()
+ if err != nil {
+ return err
+ }
+ if w.err == nil {
+ // Restore the file times of all the directories, since they may have
+ // been modified by creating child directories.
+ err = reapplyDirectoryTimes(w.dirInfo)
+ if err != nil {
+ return err
+ }
+
+ err = ProcessBaseLayer(w.root)
+ if err != nil {
+ return err
+ }
+
+ if w.hasUtilityVM {
+ err = ProcessUtilityVMImage(filepath.Join(w.root, "UtilityVM"))
+ if err != nil {
+ return err
+ }
+ }
+ }
+ return w.err
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/callback.go b/vendor/github.com/Microsoft/hcsshim/callback.go
new file mode 100644
index 0000000..e8c2b00
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/callback.go
@@ -0,0 +1,79 @@
+package hcsshim
+
+import (
+ "sync"
+ "syscall"
+)
+
+var (
+ nextCallback uintptr
+ callbackMap = map[uintptr]*notifcationWatcherContext{}
+ callbackMapLock = sync.RWMutex{}
+
+ notificationWatcherCallback = syscall.NewCallback(notificationWatcher)
+
+ // Notifications for HCS_SYSTEM handles
+ hcsNotificationSystemExited hcsNotification = 0x00000001
+ hcsNotificationSystemCreateCompleted hcsNotification = 0x00000002
+ hcsNotificationSystemStartCompleted hcsNotification = 0x00000003
+ hcsNotificationSystemPauseCompleted hcsNotification = 0x00000004
+ hcsNotificationSystemResumeCompleted hcsNotification = 0x00000005
+
+ // Notifications for HCS_PROCESS handles
+ hcsNotificationProcessExited hcsNotification = 0x00010000
+
+ // Common notifications
+ hcsNotificationInvalid hcsNotification = 0x00000000
+ hcsNotificationServiceDisconnect hcsNotification = 0x01000000
+)
+
+type hcsNotification uint32
+type notificationChannel chan error
+
+type notifcationWatcherContext struct {
+ channels notificationChannels
+ handle hcsCallback
+}
+
+type notificationChannels map[hcsNotification]notificationChannel
+
+func newChannels() notificationChannels {
+ channels := make(notificationChannels)
+
+ channels[hcsNotificationSystemExited] = make(notificationChannel, 1)
+ channels[hcsNotificationSystemCreateCompleted] = make(notificationChannel, 1)
+ channels[hcsNotificationSystemStartCompleted] = make(notificationChannel, 1)
+ channels[hcsNotificationSystemPauseCompleted] = make(notificationChannel, 1)
+ channels[hcsNotificationSystemResumeCompleted] = make(notificationChannel, 1)
+ channels[hcsNotificationProcessExited] = make(notificationChannel, 1)
+ channels[hcsNotificationServiceDisconnect] = make(notificationChannel, 1)
+ return channels
+}
+func closeChannels(channels notificationChannels) {
+ close(channels[hcsNotificationSystemExited])
+ close(channels[hcsNotificationSystemCreateCompleted])
+ close(channels[hcsNotificationSystemStartCompleted])
+ close(channels[hcsNotificationSystemPauseCompleted])
+ close(channels[hcsNotificationSystemResumeCompleted])
+ close(channels[hcsNotificationProcessExited])
+ close(channels[hcsNotificationServiceDisconnect])
+}
+
+func notificationWatcher(notificationType hcsNotification, callbackNumber uintptr, notificationStatus uintptr, notificationData *uint16) uintptr {
+ var result error
+ if int32(notificationStatus) < 0 {
+ result = syscall.Errno(win32FromHresult(notificationStatus))
+ }
+
+ callbackMapLock.RLock()
+ context := callbackMap[callbackNumber]
+ callbackMapLock.RUnlock()
+
+ if context == nil {
+ return 0
+ }
+
+ context.channels[notificationType] <- result
+
+ return 0
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/cgo.go b/vendor/github.com/Microsoft/hcsshim/cgo.go
new file mode 100644
index 0000000..2003332
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/cgo.go
@@ -0,0 +1,7 @@
+package hcsshim
+
+import "C"
+
+// This import is needed to make the library compile as CGO because HCSSHIM
+// only works with CGO due to callbacks from HCS comming back from a C thread
+// which is not supported without CGO. See https://github.com/golang/go/issues/10973
diff --git a/vendor/github.com/Microsoft/hcsshim/container.go b/vendor/github.com/Microsoft/hcsshim/container.go
new file mode 100644
index 0000000..8bc7d6d
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/container.go
@@ -0,0 +1,738 @@
+package hcsshim
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+)
+
+var (
+ defaultTimeout = time.Minute * 4
+)
+
+const (
+ pendingUpdatesQuery = `{ "PropertyTypes" : ["PendingUpdates"]}`
+ statisticsQuery = `{ "PropertyTypes" : ["Statistics"]}`
+ processListQuery = `{ "PropertyTypes" : ["ProcessList"]}`
+)
+
+type container struct {
+ handleLock sync.RWMutex
+ handle hcsSystem
+ id string
+ callbackNumber uintptr
+}
+
+// ContainerProperties holds the properties for a container and the processes running in that container
+type ContainerProperties struct {
+ ID string `json:"Id"`
+ Name string
+ SystemType string
+ Owner string
+ SiloGUID string `json:"SiloGuid,omitempty"`
+ RuntimeID string `json:"RuntimeId,omitempty"`
+ IsRuntimeTemplate bool `json:",omitempty"`
+ RuntimeImagePath string `json:",omitempty"`
+ Stopped bool `json:",omitempty"`
+ ExitType string `json:",omitempty"`
+ AreUpdatesPending bool `json:",omitempty"`
+ ObRoot string `json:",omitempty"`
+ Statistics Statistics `json:",omitempty"`
+ ProcessList []ProcessListItem `json:",omitempty"`
+}
+
+// MemoryStats holds the memory statistics for a container
+type MemoryStats struct {
+ UsageCommitBytes uint64 `json:"MemoryUsageCommitBytes,omitempty"`
+ UsageCommitPeakBytes uint64 `json:"MemoryUsageCommitPeakBytes,omitempty"`
+ UsagePrivateWorkingSetBytes uint64 `json:"MemoryUsagePrivateWorkingSetBytes,omitempty"`
+}
+
+// ProcessorStats holds the processor statistics for a container
+type ProcessorStats struct {
+ TotalRuntime100ns uint64 `json:",omitempty"`
+ RuntimeUser100ns uint64 `json:",omitempty"`
+ RuntimeKernel100ns uint64 `json:",omitempty"`
+}
+
+// StorageStats holds the storage statistics for a container
+type StorageStats struct {
+ ReadCountNormalized uint64 `json:",omitempty"`
+ ReadSizeBytes uint64 `json:",omitempty"`
+ WriteCountNormalized uint64 `json:",omitempty"`
+ WriteSizeBytes uint64 `json:",omitempty"`
+}
+
+// NetworkStats holds the network statistics for a container
+type NetworkStats struct {
+ BytesReceived uint64 `json:",omitempty"`
+ BytesSent uint64 `json:",omitempty"`
+ PacketsReceived uint64 `json:",omitempty"`
+ PacketsSent uint64 `json:",omitempty"`
+ DroppedPacketsIncoming uint64 `json:",omitempty"`
+ DroppedPacketsOutgoing uint64 `json:",omitempty"`
+ EndpointId string `json:",omitempty"`
+ InstanceId string `json:",omitempty"`
+}
+
+// Statistics is the structure returned by a statistics call on a container
+type Statistics struct {
+ Timestamp time.Time `json:",omitempty"`
+ ContainerStartTime time.Time `json:",omitempty"`
+ Uptime100ns uint64 `json:",omitempty"`
+ Memory MemoryStats `json:",omitempty"`
+ Processor ProcessorStats `json:",omitempty"`
+ Storage StorageStats `json:",omitempty"`
+ Network []NetworkStats `json:",omitempty"`
+}
+
+// ProcessList is the structure of an item returned by a ProcessList call on a container
+type ProcessListItem struct {
+ CreateTimestamp time.Time `json:",omitempty"`
+ ImageName string `json:",omitempty"`
+ KernelTime100ns uint64 `json:",omitempty"`
+ MemoryCommitBytes uint64 `json:",omitempty"`
+ MemoryWorkingSetPrivateBytes uint64 `json:",omitempty"`
+ MemoryWorkingSetSharedBytes uint64 `json:",omitempty"`
+ ProcessId uint32 `json:",omitempty"`
+ UserTime100ns uint64 `json:",omitempty"`
+}
+
+// Type of Request Support in ModifySystem
+type RequestType string
+
+// Type of Resource Support in ModifySystem
+type ResourceType string
+
+// RequestType const
+const (
+ Add RequestType = "Add"
+ Remove RequestType = "Remove"
+ Network ResourceType = "Network"
+)
+
+// ResourceModificationRequestResponse is the structure used to send request to the container to modify the system
+// Supported resource types are Network and Request Types are Add/Remove
+type ResourceModificationRequestResponse struct {
+ Resource ResourceType `json:"ResourceType"`
+ Data interface{} `json:"Settings"`
+ Request RequestType `json:"RequestType,omitempty"`
+}
+
+// createContainerAdditionalJSON is read from the environment at initialisation
+// time. It allows an environment variable to define additional JSON which
+// is merged in the CreateContainer call to HCS.
+var createContainerAdditionalJSON string
+
+func init() {
+ createContainerAdditionalJSON = os.Getenv("HCSSHIM_CREATECONTAINER_ADDITIONALJSON")
+}
+
+// CreateContainer creates a new container with the given configuration but does not start it.
+func CreateContainer(id string, c *ContainerConfig) (Container, error) {
+ return createContainerWithJSON(id, c, "")
+}
+
+// CreateContainerWithJSON creates a new container with the given configuration but does not start it.
+// It is identical to CreateContainer except that optional additional JSON can be merged before passing to HCS.
+func CreateContainerWithJSON(id string, c *ContainerConfig, additionalJSON string) (Container, error) {
+ return createContainerWithJSON(id, c, additionalJSON)
+}
+
+func createContainerWithJSON(id string, c *ContainerConfig, additionalJSON string) (Container, error) {
+ operation := "CreateContainer"
+ title := "HCSShim::" + operation
+
+ container := &container{
+ id: id,
+ }
+
+ configurationb, err := json.Marshal(c)
+ if err != nil {
+ return nil, err
+ }
+
+ configuration := string(configurationb)
+ logrus.Debugf(title+" id=%s config=%s", id, configuration)
+
+ // Merge any additional JSON. Priority is given to what is passed in explicitly,
+ // falling back to what's set in the environment.
+ if additionalJSON == "" && createContainerAdditionalJSON != "" {
+ additionalJSON = createContainerAdditionalJSON
+ }
+ if additionalJSON != "" {
+ configurationMap := map[string]interface{}{}
+ if err := json.Unmarshal([]byte(configuration), &configurationMap); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal %s: %s", configuration, err)
+ }
+
+ additionalMap := map[string]interface{}{}
+ if err := json.Unmarshal([]byte(additionalJSON), &additionalMap); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal %s: %s", additionalJSON, err)
+ }
+
+ mergedMap := mergeMaps(additionalMap, configurationMap)
+ mergedJSON, err := json.Marshal(mergedMap)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal merged configuration map %+v: %s", mergedMap, err)
+ }
+
+ configuration = string(mergedJSON)
+ logrus.Debugf(title+" id=%s merged config=%s", id, configuration)
+ }
+
+ var (
+ resultp *uint16
+ identity syscall.Handle
+ )
+ createError := hcsCreateComputeSystem(id, configuration, identity, &container.handle, &resultp)
+
+ if createError == nil || IsPending(createError) {
+ if err := container.registerCallback(); err != nil {
+ return nil, makeContainerError(container, operation, "", err)
+ }
+ }
+
+ err = processAsyncHcsResult(createError, resultp, container.callbackNumber, hcsNotificationSystemCreateCompleted, &defaultTimeout)
+ if err != nil {
+ return nil, makeContainerError(container, operation, configuration, err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s handle=%d", id, container.handle)
+ return container, nil
+}
+
+// mergeMaps recursively merges map `fromMap` into map `ToMap`. Any pre-existing values
+// in ToMap are overwritten. Values in fromMap are added to ToMap.
+// From http://stackoverflow.com/questions/40491438/merging-two-json-strings-in-golang
+func mergeMaps(fromMap, ToMap interface{}) interface{} {
+ switch fromMap := fromMap.(type) {
+ case map[string]interface{}:
+ ToMap, ok := ToMap.(map[string]interface{})
+ if !ok {
+ return fromMap
+ }
+ for keyToMap, valueToMap := range ToMap {
+ if valueFromMap, ok := fromMap[keyToMap]; ok {
+ fromMap[keyToMap] = mergeMaps(valueFromMap, valueToMap)
+ } else {
+ fromMap[keyToMap] = valueToMap
+ }
+ }
+ case nil:
+ // merge(nil, map[string]interface{...}) -> map[string]interface{...}
+ ToMap, ok := ToMap.(map[string]interface{})
+ if ok {
+ return ToMap
+ }
+ }
+ return fromMap
+}
+
+// OpenContainer opens an existing container by ID.
+func OpenContainer(id string) (Container, error) {
+ operation := "OpenContainer"
+ title := "HCSShim::" + operation
+ logrus.Debugf(title+" id=%s", id)
+
+ container := &container{
+ id: id,
+ }
+
+ var (
+ handle hcsSystem
+ resultp *uint16
+ )
+ err := hcsOpenComputeSystem(id, &handle, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return nil, makeContainerError(container, operation, "", err)
+ }
+
+ container.handle = handle
+
+ if err := container.registerCallback(); err != nil {
+ return nil, makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s handle=%d", id, handle)
+ return container, nil
+}
+
+// GetContainers gets a list of the containers on the system that match the query
+func GetContainers(q ComputeSystemQuery) ([]ContainerProperties, error) {
+ operation := "GetContainers"
+ title := "HCSShim::" + operation
+
+ queryb, err := json.Marshal(q)
+ if err != nil {
+ return nil, err
+ }
+
+ query := string(queryb)
+ logrus.Debugf(title+" query=%s", query)
+
+ var (
+ resultp *uint16
+ computeSystemsp *uint16
+ )
+ err = hcsEnumerateComputeSystems(query, &computeSystemsp, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return nil, err
+ }
+
+ if computeSystemsp == nil {
+ return nil, ErrUnexpectedValue
+ }
+ computeSystemsRaw := convertAndFreeCoTaskMemBytes(computeSystemsp)
+ computeSystems := []ContainerProperties{}
+ if err := json.Unmarshal(computeSystemsRaw, &computeSystems); err != nil {
+ return nil, err
+ }
+
+ logrus.Debugf(title + " succeeded")
+ return computeSystems, nil
+}
+
+// Start synchronously starts the container.
+func (container *container) Start() error {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "Start"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ if container.handle == 0 {
+ return makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ var resultp *uint16
+ err := hcsStartComputeSystem(container.handle, "", &resultp)
+ err = processAsyncHcsResult(err, resultp, container.callbackNumber, hcsNotificationSystemStartCompleted, &defaultTimeout)
+ if err != nil {
+ return makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return nil
+}
+
+// Shutdown requests a container shutdown, if IsPending() on the error returned is true,
+// it may not actually be shut down until Wait() succeeds.
+func (container *container) Shutdown() error {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "Shutdown"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ if container.handle == 0 {
+ return makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ var resultp *uint16
+ err := hcsShutdownComputeSystem(container.handle, "", &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return nil
+}
+
+// Terminate requests a container terminate, if IsPending() on the error returned is true,
+// it may not actually be shut down until Wait() succeeds.
+func (container *container) Terminate() error {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "Terminate"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ if container.handle == 0 {
+ return makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ var resultp *uint16
+ err := hcsTerminateComputeSystem(container.handle, "", &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return nil
+}
+
+// Wait synchronously waits for the container to shutdown or terminate.
+func (container *container) Wait() error {
+ operation := "Wait"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ err := waitForNotification(container.callbackNumber, hcsNotificationSystemExited, nil)
+ if err != nil {
+ return makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return nil
+}
+
+// WaitTimeout synchronously waits for the container to terminate or the duration to elapse.
+// If the timeout expires, IsTimeout(err) == true
+func (container *container) WaitTimeout(timeout time.Duration) error {
+ operation := "WaitTimeout"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ err := waitForNotification(container.callbackNumber, hcsNotificationSystemExited, &timeout)
+ if err != nil {
+ return makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return nil
+}
+
+func (container *container) properties(query string) (*ContainerProperties, error) {
+ var (
+ resultp *uint16
+ propertiesp *uint16
+ )
+ err := hcsGetComputeSystemProperties(container.handle, query, &propertiesp, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return nil, err
+ }
+
+ if propertiesp == nil {
+ return nil, ErrUnexpectedValue
+ }
+ propertiesRaw := convertAndFreeCoTaskMemBytes(propertiesp)
+ properties := &ContainerProperties{}
+ if err := json.Unmarshal(propertiesRaw, properties); err != nil {
+ return nil, err
+ }
+ return properties, nil
+}
+
+// HasPendingUpdates returns true if the container has updates pending to install
+func (container *container) HasPendingUpdates() (bool, error) {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "HasPendingUpdates"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ if container.handle == 0 {
+ return false, makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ properties, err := container.properties(pendingUpdatesQuery)
+ if err != nil {
+ return false, makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return properties.AreUpdatesPending, nil
+}
+
+// Statistics returns statistics for the container
+func (container *container) Statistics() (Statistics, error) {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "Statistics"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ if container.handle == 0 {
+ return Statistics{}, makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ properties, err := container.properties(statisticsQuery)
+ if err != nil {
+ return Statistics{}, makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return properties.Statistics, nil
+}
+
+// ProcessList returns an array of ProcessListItems for the container
+func (container *container) ProcessList() ([]ProcessListItem, error) {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "ProcessList"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ if container.handle == 0 {
+ return nil, makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ properties, err := container.properties(processListQuery)
+ if err != nil {
+ return nil, makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return properties.ProcessList, nil
+}
+
+// Pause pauses the execution of the container. This feature is not enabled in TP5.
+func (container *container) Pause() error {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "Pause"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ if container.handle == 0 {
+ return makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ var resultp *uint16
+ err := hcsPauseComputeSystem(container.handle, "", &resultp)
+ err = processAsyncHcsResult(err, resultp, container.callbackNumber, hcsNotificationSystemPauseCompleted, &defaultTimeout)
+ if err != nil {
+ return makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return nil
+}
+
+// Resume resumes the execution of the container. This feature is not enabled in TP5.
+func (container *container) Resume() error {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "Resume"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ if container.handle == 0 {
+ return makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ var resultp *uint16
+ err := hcsResumeComputeSystem(container.handle, "", &resultp)
+ err = processAsyncHcsResult(err, resultp, container.callbackNumber, hcsNotificationSystemResumeCompleted, &defaultTimeout)
+ if err != nil {
+ return makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return nil
+}
+
+// CreateProcess launches a new process within the container.
+func (container *container) CreateProcess(c *ProcessConfig) (Process, error) {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "CreateProcess"
+ title := "HCSShim::Container::" + operation
+ var (
+ processInfo hcsProcessInformation
+ processHandle hcsProcess
+ resultp *uint16
+ )
+
+ if container.handle == 0 {
+ return nil, makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ // If we are not emulating a console, ignore any console size passed to us
+ if !c.EmulateConsole {
+ c.ConsoleSize[0] = 0
+ c.ConsoleSize[1] = 0
+ }
+
+ configurationb, err := json.Marshal(c)
+ if err != nil {
+ return nil, makeContainerError(container, operation, "", err)
+ }
+
+ configuration := string(configurationb)
+ logrus.Debugf(title+" id=%s config=%s", container.id, configuration)
+
+ err = hcsCreateProcess(container.handle, configuration, &processInfo, &processHandle, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return nil, makeContainerError(container, operation, configuration, err)
+ }
+
+ process := &process{
+ handle: processHandle,
+ processID: int(processInfo.ProcessId),
+ container: container,
+ cachedPipes: &cachedPipes{
+ stdIn: processInfo.StdInput,
+ stdOut: processInfo.StdOutput,
+ stdErr: processInfo.StdError,
+ },
+ }
+
+ if err := process.registerCallback(); err != nil {
+ return nil, makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s processid=%d", container.id, process.processID)
+ return process, nil
+}
+
+// OpenProcess gets an interface to an existing process within the container.
+func (container *container) OpenProcess(pid int) (Process, error) {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "OpenProcess"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s, processid=%d", container.id, pid)
+ var (
+ processHandle hcsProcess
+ resultp *uint16
+ )
+
+ if container.handle == 0 {
+ return nil, makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ err := hcsOpenProcess(container.handle, uint32(pid), &processHandle, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return nil, makeContainerError(container, operation, "", err)
+ }
+
+ process := &process{
+ handle: processHandle,
+ processID: pid,
+ container: container,
+ }
+
+ if err := process.registerCallback(); err != nil {
+ return nil, makeContainerError(container, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded id=%s processid=%s", container.id, process.processID)
+ return process, nil
+}
+
+// Close cleans up any state associated with the container but does not terminate or wait for it.
+func (container *container) Close() error {
+ container.handleLock.Lock()
+ defer container.handleLock.Unlock()
+ operation := "Close"
+ title := "HCSShim::Container::" + operation
+ logrus.Debugf(title+" id=%s", container.id)
+
+ // Don't double free this
+ if container.handle == 0 {
+ return nil
+ }
+
+ if err := container.unregisterCallback(); err != nil {
+ return makeContainerError(container, operation, "", err)
+ }
+
+ if err := hcsCloseComputeSystem(container.handle); err != nil {
+ return makeContainerError(container, operation, "", err)
+ }
+
+ container.handle = 0
+
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return nil
+}
+
+func (container *container) registerCallback() error {
+ context := &notifcationWatcherContext{
+ channels: newChannels(),
+ }
+
+ callbackMapLock.Lock()
+ callbackNumber := nextCallback
+ nextCallback++
+ callbackMap[callbackNumber] = context
+ callbackMapLock.Unlock()
+
+ var callbackHandle hcsCallback
+ err := hcsRegisterComputeSystemCallback(container.handle, notificationWatcherCallback, callbackNumber, &callbackHandle)
+ if err != nil {
+ return err
+ }
+ context.handle = callbackHandle
+ container.callbackNumber = callbackNumber
+
+ return nil
+}
+
+func (container *container) unregisterCallback() error {
+ callbackNumber := container.callbackNumber
+
+ callbackMapLock.RLock()
+ context := callbackMap[callbackNumber]
+ callbackMapLock.RUnlock()
+
+ if context == nil {
+ return nil
+ }
+
+ handle := context.handle
+
+ if handle == 0 {
+ return nil
+ }
+
+ // hcsUnregisterComputeSystemCallback has its own syncronization
+ // to wait for all callbacks to complete. We must NOT hold the callbackMapLock.
+ err := hcsUnregisterComputeSystemCallback(handle)
+ if err != nil {
+ return err
+ }
+
+ closeChannels(context.channels)
+
+ callbackMapLock.Lock()
+ callbackMap[callbackNumber] = nil
+ callbackMapLock.Unlock()
+
+ handle = 0
+
+ return nil
+}
+
+// Modifies the System by sending a request to HCS
+func (container *container) Modify(config *ResourceModificationRequestResponse) error {
+ container.handleLock.RLock()
+ defer container.handleLock.RUnlock()
+ operation := "Modify"
+ title := "HCSShim::Container::" + operation
+
+ if container.handle == 0 {
+ return makeContainerError(container, operation, "", ErrAlreadyClosed)
+ }
+
+ requestJSON, err := json.Marshal(config)
+ if err != nil {
+ return err
+ }
+
+ requestString := string(requestJSON)
+ logrus.Debugf(title+" id=%s request=%s", container.id, requestString)
+
+ var resultp *uint16
+ err = hcsModifyComputeSystem(container.handle, requestString, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return makeContainerError(container, operation, "", err)
+ }
+ logrus.Debugf(title+" succeeded id=%s", container.id)
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/createlayer.go b/vendor/github.com/Microsoft/hcsshim/createlayer.go
new file mode 100644
index 0000000..9ecffb1
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/createlayer.go
@@ -0,0 +1,27 @@
+package hcsshim
+
+import "github.com/Sirupsen/logrus"
+
+// CreateLayer creates a new, empty, read-only layer on the filesystem based on
+// the parent layer provided.
+func CreateLayer(info DriverInfo, id, parent string) error {
+ title := "hcsshim::CreateLayer "
+ logrus.Debugf(title+"Flavour %d ID %s parent %s", info.Flavour, id, parent)
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return err
+ }
+
+ err = createLayer(&infop, id, parent)
+ if err != nil {
+ err = makeErrorf(err, title, "id=%s parent=%s flavour=%d", id, parent, info.Flavour)
+ logrus.Error(err)
+ return err
+ }
+
+ logrus.Debugf(title+" - succeeded id=%s parent=%s flavour=%d", id, parent, info.Flavour)
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/createsandboxlayer.go b/vendor/github.com/Microsoft/hcsshim/createsandboxlayer.go
new file mode 100644
index 0000000..b69c3da
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/createsandboxlayer.go
@@ -0,0 +1,35 @@
+package hcsshim
+
+import "github.com/Sirupsen/logrus"
+
+// CreateSandboxLayer creates and populates new read-write layer for use by a container.
+// This requires both the id of the direct parent layer, as well as the full list
+// of paths to all parent layers up to the base (and including the direct parent
+// whose id was provided).
+func CreateSandboxLayer(info DriverInfo, layerId, parentId string, parentLayerPaths []string) error {
+ title := "hcsshim::CreateSandboxLayer "
+ logrus.Debugf(title+"layerId %s parentId %s", layerId, parentId)
+
+ // Generate layer descriptors
+ layers, err := layerPathsToDescriptors(parentLayerPaths)
+ if err != nil {
+ return err
+ }
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return err
+ }
+
+ err = createSandboxLayer(&infop, layerId, parentId, layers)
+ if err != nil {
+ err = makeErrorf(err, title, "layerId=%s parentId=%s", layerId, parentId)
+ logrus.Error(err)
+ return err
+ }
+
+ logrus.Debugf(title+"- succeeded layerId=%s parentId=%s", layerId, parentId)
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/deactivatelayer.go b/vendor/github.com/Microsoft/hcsshim/deactivatelayer.go
new file mode 100644
index 0000000..c02bcb3
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/deactivatelayer.go
@@ -0,0 +1,26 @@
+package hcsshim
+
+import "github.com/Sirupsen/logrus"
+
+// DeactivateLayer will dismount a layer that was mounted via ActivateLayer.
+func DeactivateLayer(info DriverInfo, id string) error {
+ title := "hcsshim::DeactivateLayer "
+ logrus.Debugf(title+"Flavour %d ID %s", info.Flavour, id)
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return err
+ }
+
+ err = deactivateLayer(&infop, id)
+ if err != nil {
+ err = makeErrorf(err, title, "id=%s flavour=%d", id, info.Flavour)
+ logrus.Error(err)
+ return err
+ }
+
+ logrus.Debugf(title+"succeeded flavour=%d id=%s", info.Flavour, id)
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/destroylayer.go b/vendor/github.com/Microsoft/hcsshim/destroylayer.go
new file mode 100644
index 0000000..91ed269
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/destroylayer.go
@@ -0,0 +1,27 @@
+package hcsshim
+
+import "github.com/Sirupsen/logrus"
+
+// DestroyLayer will remove the on-disk files representing the layer with the given
+// id, including that layer's containing folder, if any.
+func DestroyLayer(info DriverInfo, id string) error {
+ title := "hcsshim::DestroyLayer "
+ logrus.Debugf(title+"Flavour %d ID %s", info.Flavour, id)
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return err
+ }
+
+ err = destroyLayer(&infop, id)
+ if err != nil {
+ err = makeErrorf(err, title, "id=%s flavour=%d", id, info.Flavour)
+ logrus.Error(err)
+ return err
+ }
+
+ logrus.Debugf(title+"succeeded flavour=%d id=%s", info.Flavour, id)
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/errors.go b/vendor/github.com/Microsoft/hcsshim/errors.go
new file mode 100644
index 0000000..d2f9cc8
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/errors.go
@@ -0,0 +1,239 @@
+package hcsshim
+
+import (
+ "errors"
+ "fmt"
+ "syscall"
+)
+
+var (
+ // ErrComputeSystemDoesNotExist is an error encountered when the container being operated on no longer exists
+ ErrComputeSystemDoesNotExist = syscall.Errno(0xc037010e)
+
+ // ErrElementNotFound is an error encountered when the object being referenced does not exist
+ ErrElementNotFound = syscall.Errno(0x490)
+
+ // ErrElementNotFound is an error encountered when the object being referenced does not exist
+ ErrNotSupported = syscall.Errno(0x32)
+
+ // ErrInvalidData is an error encountered when the request being sent to hcs is invalid/unsupported
+ // decimal -2147024883 / hex 0x8007000d
+ ErrInvalidData = syscall.Errno(0xd)
+
+ // ErrHandleClose is an error encountered when the handle generating the notification being waited on has been closed
+ ErrHandleClose = errors.New("hcsshim: the handle generating this notification has been closed")
+
+ // ErrAlreadyClosed is an error encountered when using a handle that has been closed by the Close method
+ ErrAlreadyClosed = errors.New("hcsshim: the handle has already been closed")
+
+ // ErrInvalidNotificationType is an error encountered when an invalid notification type is used
+ ErrInvalidNotificationType = errors.New("hcsshim: invalid notification type")
+
+ // ErrInvalidProcessState is an error encountered when the process is not in a valid state for the requested operation
+ ErrInvalidProcessState = errors.New("the process is in an invalid state for the attempted operation")
+
+ // ErrTimeout is an error encountered when waiting on a notification times out
+ ErrTimeout = errors.New("hcsshim: timeout waiting for notification")
+
+ // ErrUnexpectedContainerExit is the error encountered when a container exits while waiting for
+ // a different expected notification
+ ErrUnexpectedContainerExit = errors.New("unexpected container exit")
+
+ // ErrUnexpectedProcessAbort is the error encountered when communication with the compute service
+ // is lost while waiting for a notification
+ ErrUnexpectedProcessAbort = errors.New("lost communication with compute service")
+
+ // ErrUnexpectedValue is an error encountered when hcs returns an invalid value
+ ErrUnexpectedValue = errors.New("unexpected value returned from hcs")
+
+ // ErrVmcomputeAlreadyStopped is an error encountered when a shutdown or terminate request is made on a stopped container
+ ErrVmcomputeAlreadyStopped = syscall.Errno(0xc0370110)
+
+ // ErrVmcomputeOperationPending is an error encountered when the operation is being completed asynchronously
+ ErrVmcomputeOperationPending = syscall.Errno(0xC0370103)
+
+ // ErrVmcomputeOperationInvalidState is an error encountered when the compute system is not in a valid state for the requested operation
+ ErrVmcomputeOperationInvalidState = syscall.Errno(0xc0370105)
+
+ // ErrProcNotFound is an error encountered when the the process cannot be found
+ ErrProcNotFound = syscall.Errno(0x7f)
+
+ // ErrVmcomputeOperationAccessIsDenied is an error which can be encountered when enumerating compute systems in RS1/RS2
+ // builds when the underlying silo might be in the process of terminating. HCS was fixed in RS3.
+ ErrVmcomputeOperationAccessIsDenied = syscall.Errno(0x5)
+
+ // ErrVmcomputeInvalidJSON is an error encountered when the compute system does not support/understand the messages sent by management
+ ErrVmcomputeInvalidJSON = syscall.Errno(0xc037010d)
+
+ // ErrVmcomputeUnknownMessage is an error encountered guest compute system doesn't support the message
+ ErrVmcomputeUnknownMessage = syscall.Errno(0xc037010b)
+
+ // ErrNotSupported is an error encountered when hcs doesn't support the request
+ ErrPlatformNotSupported = errors.New("unsupported platform request")
+)
+
+// ProcessError is an error encountered in HCS during an operation on a Process object
+type ProcessError struct {
+ Process *process
+ Operation string
+ ExtraInfo string
+ Err error
+}
+
+// ContainerError is an error encountered in HCS during an operation on a Container object
+type ContainerError struct {
+ Container *container
+ Operation string
+ ExtraInfo string
+ Err error
+}
+
+func (e *ContainerError) Error() string {
+ if e == nil {
+ return "<nil>"
+ }
+
+ if e.Container == nil {
+ return "unexpected nil container for error: " + e.Err.Error()
+ }
+
+ s := "container " + e.Container.id
+
+ if e.Operation != "" {
+ s += " encountered an error during " + e.Operation
+ }
+
+ switch e.Err.(type) {
+ case nil:
+ break
+ case syscall.Errno:
+ s += fmt.Sprintf(": failure in a Windows system call: %s (0x%x)", e.Err, win32FromError(e.Err))
+ default:
+ s += fmt.Sprintf(": %s", e.Err.Error())
+ }
+
+ if e.ExtraInfo != "" {
+ s += " extra info: " + e.ExtraInfo
+ }
+
+ return s
+}
+
+func makeContainerError(container *container, operation string, extraInfo string, err error) error {
+ // Don't double wrap errors
+ if _, ok := err.(*ContainerError); ok {
+ return err
+ }
+ containerError := &ContainerError{Container: container, Operation: operation, ExtraInfo: extraInfo, Err: err}
+ return containerError
+}
+
+func (e *ProcessError) Error() string {
+ if e == nil {
+ return "<nil>"
+ }
+
+ if e.Process == nil {
+ return "Unexpected nil process for error: " + e.Err.Error()
+ }
+
+ s := fmt.Sprintf("process %d", e.Process.processID)
+
+ if e.Process.container != nil {
+ s += " in container " + e.Process.container.id
+ }
+
+ if e.Operation != "" {
+ s += " encountered an error during " + e.Operation
+ }
+
+ switch e.Err.(type) {
+ case nil:
+ break
+ case syscall.Errno:
+ s += fmt.Sprintf(": failure in a Windows system call: %s (0x%x)", e.Err, win32FromError(e.Err))
+ default:
+ s += fmt.Sprintf(": %s", e.Err.Error())
+ }
+
+ return s
+}
+
+func makeProcessError(process *process, operation string, extraInfo string, err error) error {
+ // Don't double wrap errors
+ if _, ok := err.(*ProcessError); ok {
+ return err
+ }
+ processError := &ProcessError{Process: process, Operation: operation, ExtraInfo: extraInfo, Err: err}
+ return processError
+}
+
+// IsNotExist checks if an error is caused by the Container or Process not existing.
+// Note: Currently, ErrElementNotFound can mean that a Process has either
+// already exited, or does not exist. Both IsAlreadyStopped and IsNotExist
+// will currently return true when the error is ErrElementNotFound or ErrProcNotFound.
+func IsNotExist(err error) bool {
+ err = getInnerError(err)
+ return err == ErrComputeSystemDoesNotExist ||
+ err == ErrElementNotFound ||
+ err == ErrProcNotFound
+}
+
+// IsAlreadyClosed checks if an error is caused by the Container or Process having been
+// already closed by a call to the Close() method.
+func IsAlreadyClosed(err error) bool {
+ err = getInnerError(err)
+ return err == ErrAlreadyClosed
+}
+
+// IsPending returns a boolean indicating whether the error is that
+// the requested operation is being completed in the background.
+func IsPending(err error) bool {
+ err = getInnerError(err)
+ return err == ErrVmcomputeOperationPending
+}
+
+// IsTimeout returns a boolean indicating whether the error is caused by
+// a timeout waiting for the operation to complete.
+func IsTimeout(err error) bool {
+ err = getInnerError(err)
+ return err == ErrTimeout
+}
+
+// IsAlreadyStopped returns a boolean indicating whether the error is caused by
+// a Container or Process being already stopped.
+// Note: Currently, ErrElementNotFound can mean that a Process has either
+// already exited, or does not exist. Both IsAlreadyStopped and IsNotExist
+// will currently return true when the error is ErrElementNotFound or ErrProcNotFound.
+func IsAlreadyStopped(err error) bool {
+ err = getInnerError(err)
+ return err == ErrVmcomputeAlreadyStopped ||
+ err == ErrElementNotFound ||
+ err == ErrProcNotFound
+}
+
+// IsNotSupported returns a boolean indicating whether the error is caused by
+// unsupported platform requests
+// Note: Currently Unsupported platform requests can be mean either
+// ErrVmcomputeInvalidJSON, ErrInvalidData, ErrNotSupported or ErrVmcomputeUnknownMessage
+// is thrown from the Platform
+func IsNotSupported(err error) bool {
+ err = getInnerError(err)
+ // If Platform doesn't recognize or support the request sent, below errors are seen
+ return err == ErrVmcomputeInvalidJSON ||
+ err == ErrInvalidData ||
+ err == ErrNotSupported ||
+ err == ErrVmcomputeUnknownMessage
+}
+
+func getInnerError(err error) error {
+ switch pe := err.(type) {
+ case nil:
+ return nil
+ case *ContainerError:
+ err = pe.Err
+ case *ProcessError:
+ err = pe.Err
+ }
+ return err
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/expandsandboxsize.go b/vendor/github.com/Microsoft/hcsshim/expandsandboxsize.go
new file mode 100644
index 0000000..e168921
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/expandsandboxsize.go
@@ -0,0 +1,26 @@
+package hcsshim
+
+import "github.com/Sirupsen/logrus"
+
+// ExpandSandboxSize expands the size of a layer to at least size bytes.
+func ExpandSandboxSize(info DriverInfo, layerId string, size uint64) error {
+ title := "hcsshim::ExpandSandboxSize "
+ logrus.Debugf(title+"layerId=%s size=%d", layerId, size)
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return err
+ }
+
+ err = expandSandboxSize(&infop, layerId, size)
+ if err != nil {
+ err = makeErrorf(err, title, "layerId=%s size=%d", layerId, size)
+ logrus.Error(err)
+ return err
+ }
+
+ logrus.Debugf(title+"- succeeded layerId=%s size=%d", layerId, size)
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/exportlayer.go b/vendor/github.com/Microsoft/hcsshim/exportlayer.go
new file mode 100644
index 0000000..3c9b24e
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/exportlayer.go
@@ -0,0 +1,156 @@
+package hcsshim
+
+import (
+ "io"
+ "io/ioutil"
+ "os"
+ "syscall"
+
+ "github.com/Microsoft/go-winio"
+ "github.com/Sirupsen/logrus"
+)
+
+// ExportLayer will create a folder at exportFolderPath and fill that folder with
+// the transport format version of the layer identified by layerId. This transport
+// format includes any metadata required for later importing the layer (using
+// ImportLayer), and requires the full list of parent layer paths in order to
+// perform the export.
+func ExportLayer(info DriverInfo, layerId string, exportFolderPath string, parentLayerPaths []string) error {
+ title := "hcsshim::ExportLayer "
+ logrus.Debugf(title+"flavour %d layerId %s folder %s", info.Flavour, layerId, exportFolderPath)
+
+ // Generate layer descriptors
+ layers, err := layerPathsToDescriptors(parentLayerPaths)
+ if err != nil {
+ return err
+ }
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return err
+ }
+
+ err = exportLayer(&infop, layerId, exportFolderPath, layers)
+ if err != nil {
+ err = makeErrorf(err, title, "layerId=%s flavour=%d folder=%s", layerId, info.Flavour, exportFolderPath)
+ logrus.Error(err)
+ return err
+ }
+
+ logrus.Debugf(title+"succeeded flavour=%d layerId=%s folder=%s", info.Flavour, layerId, exportFolderPath)
+ return nil
+}
+
+type LayerReader interface {
+ Next() (string, int64, *winio.FileBasicInfo, error)
+ Read(b []byte) (int, error)
+ Close() error
+}
+
+// FilterLayerReader provides an interface for extracting the contents of an on-disk layer.
+type FilterLayerReader struct {
+ context uintptr
+}
+
+// Next reads the next available file from a layer, ensuring that parent directories are always read
+// before child files and directories.
+//
+// Next returns the file's relative path, size, and basic file metadata. Read() should be used to
+// extract a Win32 backup stream with the remainder of the metadata and the data.
+func (r *FilterLayerReader) Next() (string, int64, *winio.FileBasicInfo, error) {
+ var fileNamep *uint16
+ fileInfo := &winio.FileBasicInfo{}
+ var deleted uint32
+ var fileSize int64
+ err := exportLayerNext(r.context, &fileNamep, fileInfo, &fileSize, &deleted)
+ if err != nil {
+ if err == syscall.ERROR_NO_MORE_FILES {
+ err = io.EOF
+ } else {
+ err = makeError(err, "ExportLayerNext", "")
+ }
+ return "", 0, nil, err
+ }
+ fileName := convertAndFreeCoTaskMemString(fileNamep)
+ if deleted != 0 {
+ fileInfo = nil
+ }
+ if fileName[0] == '\\' {
+ fileName = fileName[1:]
+ }
+ return fileName, fileSize, fileInfo, nil
+}
+
+// Read reads from the current file's Win32 backup stream.
+func (r *FilterLayerReader) Read(b []byte) (int, error) {
+ var bytesRead uint32
+ err := exportLayerRead(r.context, b, &bytesRead)
+ if err != nil {
+ return 0, makeError(err, "ExportLayerRead", "")
+ }
+ if bytesRead == 0 {
+ return 0, io.EOF
+ }
+ return int(bytesRead), nil
+}
+
+// Close frees resources associated with the layer reader. It will return an
+// error if there was an error while reading the layer or of the layer was not
+// completely read.
+func (r *FilterLayerReader) Close() (err error) {
+ if r.context != 0 {
+ err = exportLayerEnd(r.context)
+ if err != nil {
+ err = makeError(err, "ExportLayerEnd", "")
+ }
+ r.context = 0
+ }
+ return
+}
+
+// NewLayerReader returns a new layer reader for reading the contents of an on-disk layer.
+// The caller must have taken the SeBackupPrivilege privilege
+// to call this and any methods on the resulting LayerReader.
+func NewLayerReader(info DriverInfo, layerID string, parentLayerPaths []string) (LayerReader, error) {
+ if procExportLayerBegin.Find() != nil {
+ // The new layer reader is not available on this Windows build. Fall back to the
+ // legacy export code path.
+ path, err := ioutil.TempDir("", "hcs")
+ if err != nil {
+ return nil, err
+ }
+ err = ExportLayer(info, layerID, path, parentLayerPaths)
+ if err != nil {
+ os.RemoveAll(path)
+ return nil, err
+ }
+ return &legacyLayerReaderWrapper{newLegacyLayerReader(path)}, nil
+ }
+
+ layers, err := layerPathsToDescriptors(parentLayerPaths)
+ if err != nil {
+ return nil, err
+ }
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ return nil, err
+ }
+ r := &FilterLayerReader{}
+ err = exportLayerBegin(&infop, layerID, layers, &r.context)
+ if err != nil {
+ return nil, makeError(err, "ExportLayerBegin", "")
+ }
+ return r, err
+}
+
+type legacyLayerReaderWrapper struct {
+ *legacyLayerReader
+}
+
+func (r *legacyLayerReaderWrapper) Close() error {
+ err := r.legacyLayerReader.Close()
+ os.RemoveAll(r.root)
+ return err
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/getlayermountpath.go b/vendor/github.com/Microsoft/hcsshim/getlayermountpath.go
new file mode 100644
index 0000000..41b5758
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/getlayermountpath.go
@@ -0,0 +1,55 @@
+package hcsshim
+
+import (
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// GetLayerMountPath will look for a mounted layer with the given id and return
+// the path at which that layer can be accessed. This path may be a volume path
+// if the layer is a mounted read-write layer, otherwise it is expected to be the
+// folder path at which the layer is stored.
+func GetLayerMountPath(info DriverInfo, id string) (string, error) {
+ title := "hcsshim::GetLayerMountPath "
+ logrus.Debugf(title+"Flavour %d ID %s", info.Flavour, id)
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return "", err
+ }
+
+ var mountPathLength uintptr
+ mountPathLength = 0
+
+ // Call the procedure itself.
+ logrus.Debugf("Calling proc (1)")
+ err = getLayerMountPath(&infop, id, &mountPathLength, nil)
+ if err != nil {
+ err = makeErrorf(err, title, "(first call) id=%s flavour=%d", id, info.Flavour)
+ logrus.Error(err)
+ return "", err
+ }
+
+ // Allocate a mount path of the returned length.
+ if mountPathLength == 0 {
+ return "", nil
+ }
+ mountPathp := make([]uint16, mountPathLength)
+ mountPathp[0] = 0
+
+ // Call the procedure again
+ logrus.Debugf("Calling proc (2)")
+ err = getLayerMountPath(&infop, id, &mountPathLength, &mountPathp[0])
+ if err != nil {
+ err = makeErrorf(err, title, "(second call) id=%s flavour=%d", id, info.Flavour)
+ logrus.Error(err)
+ return "", err
+ }
+
+ path := syscall.UTF16ToString(mountPathp[0:])
+ logrus.Debugf(title+"succeeded flavour=%d id=%s path=%s", info.Flavour, id, path)
+ return path, nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/getsharedbaseimages.go b/vendor/github.com/Microsoft/hcsshim/getsharedbaseimages.go
new file mode 100644
index 0000000..01ab4da
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/getsharedbaseimages.go
@@ -0,0 +1,22 @@
+package hcsshim
+
+import "github.com/Sirupsen/logrus"
+
+// GetSharedBaseImages will enumerate the images stored in the common central
+// image store and return descriptive info about those images for the purpose
+// of registering them with the graphdriver, graph, and tagstore.
+func GetSharedBaseImages() (imageData string, err error) {
+ title := "hcsshim::GetSharedBaseImages "
+
+ logrus.Debugf("Calling proc")
+ var buffer *uint16
+ err = getBaseImages(&buffer)
+ if err != nil {
+ err = makeError(err, title, "")
+ logrus.Error(err)
+ return
+ }
+ imageData = convertAndFreeCoTaskMemString(buffer)
+ logrus.Debugf(title+" - succeeded output=%s", imageData)
+ return
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/guid.go b/vendor/github.com/Microsoft/hcsshim/guid.go
new file mode 100644
index 0000000..620aba1
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/guid.go
@@ -0,0 +1,19 @@
+package hcsshim
+
+import (
+ "crypto/sha1"
+ "fmt"
+)
+
+type GUID [16]byte
+
+func NewGUID(source string) *GUID {
+ h := sha1.Sum([]byte(source))
+ var g GUID
+ copy(g[0:], h[0:16])
+ return &g
+}
+
+func (g *GUID) ToString() string {
+ return fmt.Sprintf("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x-%02x", g[3], g[2], g[1], g[0], g[5], g[4], g[7], g[6], g[8:10], g[10:])
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/hcsshim.go b/vendor/github.com/Microsoft/hcsshim/hcsshim.go
new file mode 100644
index 0000000..3cb3a29
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/hcsshim.go
@@ -0,0 +1,166 @@
+// Shim for the Host Compute Service (HCS) to manage Windows Server
+// containers and Hyper-V containers.
+
+package hcsshim
+
+import (
+ "fmt"
+ "syscall"
+ "unsafe"
+
+ "github.com/Sirupsen/logrus"
+)
+
+//go:generate go run mksyscall_windows.go -output zhcsshim.go hcsshim.go
+
+//sys coTaskMemFree(buffer unsafe.Pointer) = ole32.CoTaskMemFree
+//sys SetCurrentThreadCompartmentId(compartmentId uint32) (hr error) = iphlpapi.SetCurrentThreadCompartmentId
+
+//sys activateLayer(info *driverInfo, id string) (hr error) = vmcompute.ActivateLayer?
+//sys copyLayer(info *driverInfo, srcId string, dstId string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) = vmcompute.CopyLayer?
+//sys createLayer(info *driverInfo, id string, parent string) (hr error) = vmcompute.CreateLayer?
+//sys createSandboxLayer(info *driverInfo, id string, parent string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) = vmcompute.CreateSandboxLayer?
+//sys expandSandboxSize(info *driverInfo, id string, size uint64) (hr error) = vmcompute.ExpandSandboxSize?
+//sys deactivateLayer(info *driverInfo, id string) (hr error) = vmcompute.DeactivateLayer?
+//sys destroyLayer(info *driverInfo, id string) (hr error) = vmcompute.DestroyLayer?
+//sys exportLayer(info *driverInfo, id string, path string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) = vmcompute.ExportLayer?
+//sys getLayerMountPath(info *driverInfo, id string, length *uintptr, buffer *uint16) (hr error) = vmcompute.GetLayerMountPath?
+//sys getBaseImages(buffer **uint16) (hr error) = vmcompute.GetBaseImages?
+//sys importLayer(info *driverInfo, id string, path string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) = vmcompute.ImportLayer?
+//sys layerExists(info *driverInfo, id string, exists *uint32) (hr error) = vmcompute.LayerExists?
+//sys nameToGuid(name string, guid *GUID) (hr error) = vmcompute.NameToGuid?
+//sys prepareLayer(info *driverInfo, id string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) = vmcompute.PrepareLayer?
+//sys unprepareLayer(info *driverInfo, id string) (hr error) = vmcompute.UnprepareLayer?
+//sys processBaseImage(path string) (hr error) = vmcompute.ProcessBaseImage?
+//sys processUtilityImage(path string) (hr error) = vmcompute.ProcessUtilityImage?
+
+//sys importLayerBegin(info *driverInfo, id string, descriptors []WC_LAYER_DESCRIPTOR, context *uintptr) (hr error) = vmcompute.ImportLayerBegin?
+//sys importLayerNext(context uintptr, fileName string, fileInfo *winio.FileBasicInfo) (hr error) = vmcompute.ImportLayerNext?
+//sys importLayerWrite(context uintptr, buffer []byte) (hr error) = vmcompute.ImportLayerWrite?
+//sys importLayerEnd(context uintptr) (hr error) = vmcompute.ImportLayerEnd?
+
+//sys exportLayerBegin(info *driverInfo, id string, descriptors []WC_LAYER_DESCRIPTOR, context *uintptr) (hr error) = vmcompute.ExportLayerBegin?
+//sys exportLayerNext(context uintptr, fileName **uint16, fileInfo *winio.FileBasicInfo, fileSize *int64, deleted *uint32) (hr error) = vmcompute.ExportLayerNext?
+//sys exportLayerRead(context uintptr, buffer []byte, bytesRead *uint32) (hr error) = vmcompute.ExportLayerRead?
+//sys exportLayerEnd(context uintptr) (hr error) = vmcompute.ExportLayerEnd?
+
+//sys hcsEnumerateComputeSystems(query string, computeSystems **uint16, result **uint16) (hr error) = vmcompute.HcsEnumerateComputeSystems?
+//sys hcsCreateComputeSystem(id string, configuration string, identity syscall.Handle, computeSystem *hcsSystem, result **uint16) (hr error) = vmcompute.HcsCreateComputeSystem?
+//sys hcsOpenComputeSystem(id string, computeSystem *hcsSystem, result **uint16) (hr error) = vmcompute.HcsOpenComputeSystem?
+//sys hcsCloseComputeSystem(computeSystem hcsSystem) (hr error) = vmcompute.HcsCloseComputeSystem?
+//sys hcsStartComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsStartComputeSystem?
+//sys hcsShutdownComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsShutdownComputeSystem?
+//sys hcsTerminateComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsTerminateComputeSystem?
+//sys hcsPauseComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsPauseComputeSystem?
+//sys hcsResumeComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsResumeComputeSystem?
+//sys hcsGetComputeSystemProperties(computeSystem hcsSystem, propertyQuery string, properties **uint16, result **uint16) (hr error) = vmcompute.HcsGetComputeSystemProperties?
+//sys hcsModifyComputeSystem(computeSystem hcsSystem, configuration string, result **uint16) (hr error) = vmcompute.HcsModifyComputeSystem?
+//sys hcsRegisterComputeSystemCallback(computeSystem hcsSystem, callback uintptr, context uintptr, callbackHandle *hcsCallback) (hr error) = vmcompute.HcsRegisterComputeSystemCallback?
+//sys hcsUnregisterComputeSystemCallback(callbackHandle hcsCallback) (hr error) = vmcompute.HcsUnregisterComputeSystemCallback?
+
+//sys hcsCreateProcess(computeSystem hcsSystem, processParameters string, processInformation *hcsProcessInformation, process *hcsProcess, result **uint16) (hr error) = vmcompute.HcsCreateProcess?
+//sys hcsOpenProcess(computeSystem hcsSystem, pid uint32, process *hcsProcess, result **uint16) (hr error) = vmcompute.HcsOpenProcess?
+//sys hcsCloseProcess(process hcsProcess) (hr error) = vmcompute.HcsCloseProcess?
+//sys hcsTerminateProcess(process hcsProcess, result **uint16) (hr error) = vmcompute.HcsTerminateProcess?
+//sys hcsGetProcessInfo(process hcsProcess, processInformation *hcsProcessInformation, result **uint16) (hr error) = vmcompute.HcsGetProcessInfo?
+//sys hcsGetProcessProperties(process hcsProcess, processProperties **uint16, result **uint16) (hr error) = vmcompute.HcsGetProcessProperties?
+//sys hcsModifyProcess(process hcsProcess, settings string, result **uint16) (hr error) = vmcompute.HcsModifyProcess?
+//sys hcsGetServiceProperties(propertyQuery string, properties **uint16, result **uint16) (hr error) = vmcompute.HcsGetServiceProperties?
+//sys hcsRegisterProcessCallback(process hcsProcess, callback uintptr, context uintptr, callbackHandle *hcsCallback) (hr error) = vmcompute.HcsRegisterProcessCallback?
+//sys hcsUnregisterProcessCallback(callbackHandle hcsCallback) (hr error) = vmcompute.HcsUnregisterProcessCallback?
+
+//sys hcsModifyServiceSettings(settings string, result **uint16) (hr error) = vmcompute.HcsModifyServiceSettings?
+
+//sys _hnsCall(method string, path string, object string, response **uint16) (hr error) = vmcompute.HNSCall?
+
+const (
+ // Specific user-visible exit codes
+ WaitErrExecFailed = 32767
+
+ ERROR_GEN_FAILURE = syscall.Errno(31)
+ ERROR_SHUTDOWN_IN_PROGRESS = syscall.Errno(1115)
+ WSAEINVAL = syscall.Errno(10022)
+
+ // Timeout on wait calls
+ TimeoutInfinite = 0xFFFFFFFF
+)
+
+type HcsError struct {
+ title string
+ rest string
+ Err error
+}
+
+type hcsSystem syscall.Handle
+type hcsProcess syscall.Handle
+type hcsCallback syscall.Handle
+
+type hcsProcessInformation struct {
+ ProcessId uint32
+ Reserved uint32
+ StdInput syscall.Handle
+ StdOutput syscall.Handle
+ StdError syscall.Handle
+}
+
+func makeError(err error, title, rest string) error {
+ // Pass through DLL errors directly since they do not originate from HCS.
+ if _, ok := err.(*syscall.DLLError); ok {
+ return err
+ }
+ return &HcsError{title, rest, err}
+}
+
+func makeErrorf(err error, title, format string, a ...interface{}) error {
+ return makeError(err, title, fmt.Sprintf(format, a...))
+}
+
+func win32FromError(err error) uint32 {
+ if herr, ok := err.(*HcsError); ok {
+ return win32FromError(herr.Err)
+ }
+ if code, ok := err.(syscall.Errno); ok {
+ return uint32(code)
+ }
+ return uint32(ERROR_GEN_FAILURE)
+}
+
+func win32FromHresult(hr uintptr) uintptr {
+ if hr&0x1fff0000 == 0x00070000 {
+ return hr & 0xffff
+ }
+ return hr
+}
+
+func (e *HcsError) Error() string {
+ s := e.title
+ if len(s) > 0 && s[len(s)-1] != ' ' {
+ s += " "
+ }
+ s += fmt.Sprintf("failed in Win32: %s (0x%x)", e.Err, win32FromError(e.Err))
+ if e.rest != "" {
+ if e.rest[0] != ' ' {
+ s += " "
+ }
+ s += e.rest
+ }
+ return s
+}
+
+func convertAndFreeCoTaskMemString(buffer *uint16) string {
+ str := syscall.UTF16ToString((*[1 << 30]uint16)(unsafe.Pointer(buffer))[:])
+ coTaskMemFree(unsafe.Pointer(buffer))
+ return str
+}
+
+func convertAndFreeCoTaskMemBytes(buffer *uint16) []byte {
+ return []byte(convertAndFreeCoTaskMemString(buffer))
+}
+
+func processHcsResult(err error, resultp *uint16) error {
+ if resultp != nil {
+ result := convertAndFreeCoTaskMemString(resultp)
+ logrus.Debugf("Result: %s", result)
+ }
+ return err
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/hnsfuncs.go b/vendor/github.com/Microsoft/hcsshim/hnsfuncs.go
new file mode 100644
index 0000000..97ec2e8
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/hnsfuncs.go
@@ -0,0 +1,271 @@
+package hcsshim
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+)
+
+type NatPolicy struct {
+ Type string
+ Protocol string
+ InternalPort uint16
+ ExternalPort uint16
+}
+
+type QosPolicy struct {
+ Type string
+ MaximumOutgoingBandwidthInBytes uint64
+}
+
+type VlanPolicy struct {
+ Type string
+ VLAN uint
+}
+
+type VsidPolicy struct {
+ Type string
+ VSID uint
+}
+
+type PaPolicy struct {
+ Type string
+ PA string
+}
+
+// Subnet is assoicated with a network and represents a list
+// of subnets available to the network
+type Subnet struct {
+ AddressPrefix string `json:",omitempty"`
+ GatewayAddress string `json:",omitempty"`
+ Policies []json.RawMessage `json:",omitempty"`
+}
+
+// MacPool is assoicated with a network and represents a list
+// of macaddresses available to the network
+type MacPool struct {
+ StartMacAddress string `json:",omitempty"`
+ EndMacAddress string `json:",omitempty"`
+}
+
+// HNSNetwork represents a network in HNS
+type HNSNetwork struct {
+ Id string `json:"ID,omitempty"`
+ Name string `json:",omitempty"`
+ Type string `json:",omitempty"`
+ NetworkAdapterName string `json:",omitempty"`
+ SourceMac string `json:",omitempty"`
+ Policies []json.RawMessage `json:",omitempty"`
+ MacPools []MacPool `json:",omitempty"`
+ Subnets []Subnet `json:",omitempty"`
+ DNSSuffix string `json:",omitempty"`
+ DNSServerList string `json:",omitempty"`
+ DNSServerCompartment uint32 `json:",omitempty"`
+ ManagementIP string `json:",omitempty"`
+}
+
+// HNSEndpoint represents a network endpoint in HNS
+type HNSEndpoint struct {
+ Id string `json:"ID,omitempty"`
+ Name string `json:",omitempty"`
+ VirtualNetwork string `json:",omitempty"`
+ VirtualNetworkName string `json:",omitempty"`
+ Policies []json.RawMessage `json:",omitempty"`
+ MacAddress string `json:",omitempty"`
+ IPAddress net.IP `json:",omitempty"`
+ DNSSuffix string `json:",omitempty"`
+ DNSServerList string `json:",omitempty"`
+ GatewayAddress string `json:",omitempty"`
+ EnableInternalDNS bool `json:",omitempty"`
+ DisableICC bool `json:",omitempty"`
+ PrefixLength uint8 `json:",omitempty"`
+ IsRemoteEndpoint bool `json:",omitempty"`
+}
+
+type hnsNetworkResponse struct {
+ Success bool
+ Error string
+ Output HNSNetwork
+}
+
+type hnsResponse struct {
+ Success bool
+ Error string
+ Output json.RawMessage
+}
+
+func hnsCall(method, path, request string, returnResponse interface{}) error {
+ var responseBuffer *uint16
+ logrus.Debugf("[%s]=>[%s] Request : %s", method, path, request)
+
+ err := _hnsCall(method, path, request, &responseBuffer)
+ if err != nil {
+ return makeError(err, "hnsCall ", "")
+ }
+ response := convertAndFreeCoTaskMemString(responseBuffer)
+
+ hnsresponse := &hnsResponse{}
+ if err = json.Unmarshal([]byte(response), &hnsresponse); err != nil {
+ return err
+ }
+
+ if !hnsresponse.Success {
+ return fmt.Errorf("HNS failed with error : %s", hnsresponse.Error)
+ }
+
+ if len(hnsresponse.Output) == 0 {
+ return nil
+ }
+
+ logrus.Debugf("Network Response : %s", hnsresponse.Output)
+ err = json.Unmarshal(hnsresponse.Output, returnResponse)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// HNSNetworkRequest makes a call into HNS to update/query a single network
+func HNSNetworkRequest(method, path, request string) (*HNSNetwork, error) {
+ var network HNSNetwork
+ err := hnsCall(method, "/networks/"+path, request, &network)
+ if err != nil {
+ return nil, err
+ }
+
+ return &network, nil
+}
+
+// HNSListNetworkRequest makes a HNS call to query the list of available networks
+func HNSListNetworkRequest(method, path, request string) ([]HNSNetwork, error) {
+ var network []HNSNetwork
+ err := hnsCall(method, "/networks/"+path, request, &network)
+ if err != nil {
+ return nil, err
+ }
+
+ return network, nil
+}
+
+// HNSEndpointRequest makes a HNS call to modify/query a network endpoint
+func HNSEndpointRequest(method, path, request string) (*HNSEndpoint, error) {
+ endpoint := &HNSEndpoint{}
+ err := hnsCall(method, "/endpoints/"+path, request, &endpoint)
+ if err != nil {
+ return nil, err
+ }
+
+ return endpoint, nil
+}
+
+// HNSListEndpointRequest makes a HNS call to query the list of available endpoints
+func HNSListEndpointRequest() ([]HNSEndpoint, error) {
+ var endpoint []HNSEndpoint
+ err := hnsCall("GET", "/endpoints/", "", &endpoint)
+ if err != nil {
+ return nil, err
+ }
+
+ return endpoint, nil
+}
+
+// HotAttachEndpoint makes a HCS Call to attach the endpoint to the container
+func HotAttachEndpoint(containerID string, endpointID string) error {
+ return modifyNetworkEndpoint(containerID, endpointID, Add)
+}
+
+// HotDetachEndpoint makes a HCS Call to detach the endpoint from the container
+func HotDetachEndpoint(containerID string, endpointID string) error {
+ return modifyNetworkEndpoint(containerID, endpointID, Remove)
+}
+
+// ModifyContainer corresponding to the container id, by sending a request
+func modifyContainer(id string, request *ResourceModificationRequestResponse) error {
+ container, err := OpenContainer(id)
+ if err != nil {
+ if IsNotExist(err) {
+ return ErrComputeSystemDoesNotExist
+ }
+ return getInnerError(err)
+ }
+ defer container.Close()
+ err = container.Modify(request)
+ if err != nil {
+ if IsNotSupported(err) {
+ return ErrPlatformNotSupported
+ }
+ return getInnerError(err)
+ }
+
+ return nil
+}
+
+func modifyNetworkEndpoint(containerID string, endpointID string, request RequestType) error {
+ requestMessage := &ResourceModificationRequestResponse{
+ Resource: Network,
+ Request: request,
+ Data: endpointID,
+ }
+ err := modifyContainer(containerID, requestMessage)
+
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// GetHNSNetworkByID
+func GetHNSNetworkByID(networkID string) (*HNSNetwork, error) {
+ return HNSNetworkRequest("GET", networkID, "")
+}
+
+// GetHNSNetworkName filtered by Name
+func GetHNSNetworkByName(networkName string) (*HNSNetwork, error) {
+ hsnnetworks, err := HNSListNetworkRequest("GET", "", "")
+ if err != nil {
+ return nil, err
+ }
+ for _, hnsnetwork := range hsnnetworks {
+ if hnsnetwork.Name == networkName {
+ return &hnsnetwork, nil
+ }
+ }
+ return nil, fmt.Errorf("Network %v not found", networkName)
+}
+
+// Create Endpoint by sending EndpointRequest to HNS. TODO: Create a separate HNS interface to place all these methods
+func (endpoint *HNSEndpoint) Create() (*HNSEndpoint, error) {
+ jsonString, err := json.Marshal(endpoint)
+ if err != nil {
+ return nil, err
+ }
+ return HNSEndpointRequest("POST", "", string(jsonString))
+}
+
+// Create Endpoint by sending EndpointRequest to HNS
+func (endpoint *HNSEndpoint) Delete() (*HNSEndpoint, error) {
+ return HNSEndpointRequest("DELETE", endpoint.Id, "")
+}
+
+// GetHNSEndpointByID
+func GetHNSEndpointByID(endpointID string) (*HNSEndpoint, error) {
+ return HNSEndpointRequest("GET", endpointID, "")
+}
+
+// GetHNSNetworkName filtered by Name
+func GetHNSEndpointByName(endpointName string) (*HNSEndpoint, error) {
+ hnsResponse, err := HNSListEndpointRequest()
+ if err != nil {
+ return nil, err
+ }
+ for _, hnsEndpoint := range hnsResponse {
+ if hnsEndpoint.Name == endpointName {
+ return &hnsEndpoint, nil
+ }
+ }
+ return nil, fmt.Errorf("Endpoint %v not found", endpointName)
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/importlayer.go b/vendor/github.com/Microsoft/hcsshim/importlayer.go
new file mode 100644
index 0000000..75dcd94
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/importlayer.go
@@ -0,0 +1,212 @@
+package hcsshim
+
+import (
+ "errors"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+
+ "github.com/Microsoft/go-winio"
+ "github.com/Sirupsen/logrus"
+)
+
+// ImportLayer will take the contents of the folder at importFolderPath and import
+// that into a layer with the id layerId. Note that in order to correctly populate
+// the layer and interperet the transport format, all parent layers must already
+// be present on the system at the paths provided in parentLayerPaths.
+func ImportLayer(info DriverInfo, layerID string, importFolderPath string, parentLayerPaths []string) error {
+ title := "hcsshim::ImportLayer "
+ logrus.Debugf(title+"flavour %d layerId %s folder %s", info.Flavour, layerID, importFolderPath)
+
+ // Generate layer descriptors
+ layers, err := layerPathsToDescriptors(parentLayerPaths)
+ if err != nil {
+ return err
+ }
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return err
+ }
+
+ err = importLayer(&infop, layerID, importFolderPath, layers)
+ if err != nil {
+ err = makeErrorf(err, title, "layerId=%s flavour=%d folder=%s", layerID, info.Flavour, importFolderPath)
+ logrus.Error(err)
+ return err
+ }
+
+ logrus.Debugf(title+"succeeded flavour=%d layerId=%s folder=%s", info.Flavour, layerID, importFolderPath)
+ return nil
+}
+
+// LayerWriter is an interface that supports writing a new container image layer.
+type LayerWriter interface {
+ // Add adds a file to the layer with given metadata.
+ Add(name string, fileInfo *winio.FileBasicInfo) error
+ // AddLink adds a hard link to the layer. The target must already have been added.
+ AddLink(name string, target string) error
+ // Remove removes a file that was present in a parent layer from the layer.
+ Remove(name string) error
+ // Write writes data to the current file. The data must be in the format of a Win32
+ // backup stream.
+ Write(b []byte) (int, error)
+ // Close finishes the layer writing process and releases any resources.
+ Close() error
+}
+
+// FilterLayerWriter provides an interface to write the contents of a layer to the file system.
+type FilterLayerWriter struct {
+ context uintptr
+}
+
+// Add adds a file or directory to the layer. The file's parent directory must have already been added.
+//
+// name contains the file's relative path. fileInfo contains file times and file attributes; the rest
+// of the file metadata and the file data must be written as a Win32 backup stream to the Write() method.
+// winio.BackupStreamWriter can be used to facilitate this.
+func (w *FilterLayerWriter) Add(name string, fileInfo *winio.FileBasicInfo) error {
+ if name[0] != '\\' {
+ name = `\` + name
+ }
+ err := importLayerNext(w.context, name, fileInfo)
+ if err != nil {
+ return makeError(err, "ImportLayerNext", "")
+ }
+ return nil
+}
+
+// AddLink adds a hard link to the layer. The target of the link must have already been added.
+func (w *FilterLayerWriter) AddLink(name string, target string) error {
+ return errors.New("hard links not yet supported")
+}
+
+// Remove removes a file from the layer. The file must have been present in the parent layer.
+//
+// name contains the file's relative path.
+func (w *FilterLayerWriter) Remove(name string) error {
+ if name[0] != '\\' {
+ name = `\` + name
+ }
+ err := importLayerNext(w.context, name, nil)
+ if err != nil {
+ return makeError(err, "ImportLayerNext", "")
+ }
+ return nil
+}
+
+// Write writes more backup stream data to the current file.
+func (w *FilterLayerWriter) Write(b []byte) (int, error) {
+ err := importLayerWrite(w.context, b)
+ if err != nil {
+ err = makeError(err, "ImportLayerWrite", "")
+ return 0, err
+ }
+ return len(b), err
+}
+
+// Close completes the layer write operation. The error must be checked to ensure that the
+// operation was successful.
+func (w *FilterLayerWriter) Close() (err error) {
+ if w.context != 0 {
+ err = importLayerEnd(w.context)
+ if err != nil {
+ err = makeError(err, "ImportLayerEnd", "")
+ }
+ w.context = 0
+ }
+ return
+}
+
+type legacyLayerWriterWrapper struct {
+ *legacyLayerWriter
+ info DriverInfo
+ layerID string
+ path string
+ parentLayerPaths []string
+}
+
+func (r *legacyLayerWriterWrapper) Close() error {
+ defer os.RemoveAll(r.root)
+ err := r.legacyLayerWriter.Close()
+ if err != nil {
+ return err
+ }
+
+ // Use the original path here because ImportLayer does not support long paths for the source in TP5.
+ // But do use a long path for the destination to work around another bug with directories
+ // with MAX_PATH - 12 < length < MAX_PATH.
+ info := r.info
+ fullPath, err := makeLongAbsPath(filepath.Join(info.HomeDir, r.layerID))
+ if err != nil {
+ return err
+ }
+
+ info.HomeDir = ""
+ if err = ImportLayer(info, fullPath, r.path, r.parentLayerPaths); err != nil {
+ return err
+ }
+ // Add any hard links that were collected.
+ for _, lnk := range r.PendingLinks {
+ if err = os.Remove(lnk.Path); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ if err = os.Link(lnk.Target, lnk.Path); err != nil {
+ return err
+ }
+ }
+ // Prepare the utility VM for use if one is present in the layer.
+ if r.HasUtilityVM {
+ err = ProcessUtilityVMImage(filepath.Join(fullPath, "UtilityVM"))
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// NewLayerWriter returns a new layer writer for creating a layer on disk.
+// The caller must have taken the SeBackupPrivilege and SeRestorePrivilege privileges
+// to call this and any methods on the resulting LayerWriter.
+func NewLayerWriter(info DriverInfo, layerID string, parentLayerPaths []string) (LayerWriter, error) {
+ if len(parentLayerPaths) == 0 {
+ // This is a base layer. It gets imported differently.
+ return &baseLayerWriter{
+ root: filepath.Join(info.HomeDir, layerID),
+ }, nil
+ }
+
+ if procImportLayerBegin.Find() != nil {
+ // The new layer reader is not available on this Windows build. Fall back to the
+ // legacy export code path.
+ path, err := ioutil.TempDir("", "hcs")
+ if err != nil {
+ return nil, err
+ }
+ return &legacyLayerWriterWrapper{
+ legacyLayerWriter: newLegacyLayerWriter(path, parentLayerPaths, filepath.Join(info.HomeDir, layerID)),
+ info: info,
+ layerID: layerID,
+ path: path,
+ parentLayerPaths: parentLayerPaths,
+ }, nil
+ }
+ layers, err := layerPathsToDescriptors(parentLayerPaths)
+ if err != nil {
+ return nil, err
+ }
+
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ return nil, err
+ }
+
+ w := &FilterLayerWriter{}
+ err = importLayerBegin(&infop, layerID, layers, &w.context)
+ if err != nil {
+ return nil, makeError(err, "ImportLayerStart", "")
+ }
+ return w, nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/interface.go b/vendor/github.com/Microsoft/hcsshim/interface.go
new file mode 100644
index 0000000..5238a64
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/interface.go
@@ -0,0 +1,174 @@
+package hcsshim
+
+import (
+ "encoding/json"
+ "io"
+ "time"
+)
+
+// ProcessConfig is used as both the input of Container.CreateProcess
+// and to convert the parameters to JSON for passing onto the HCS
+type ProcessConfig struct {
+ ApplicationName string `json:",omitempty"`
+ CommandLine string `json:",omitempty"`
+ CommandArgs []string `json:",omitempty"` // Used by Linux Containers on Windows
+ User string `json:",omitempty"`
+ WorkingDirectory string `json:",omitempty"`
+ Environment map[string]string `json:",omitempty"`
+ EmulateConsole bool `json:",omitempty"`
+ CreateStdInPipe bool `json:",omitempty"`
+ CreateStdOutPipe bool `json:",omitempty"`
+ CreateStdErrPipe bool `json:",omitempty"`
+ ConsoleSize [2]uint `json:",omitempty"`
+ CreateInUtilityVm bool `json:",omitempty"` // Used by Linux Containers on Windows
+ OCISpecification *json.RawMessage `json:",omitempty"` // Used by Linux Containers on Windows
+}
+
+type Layer struct {
+ ID string
+ Path string
+}
+
+type MappedDir struct {
+ HostPath string
+ ContainerPath string
+ ReadOnly bool
+ BandwidthMaximum uint64
+ IOPSMaximum uint64
+}
+
+type HvRuntime struct {
+ ImagePath string `json:",omitempty"`
+ SkipTemplate bool `json:",omitempty"`
+ LinuxInitrdFile string `json:",omitempty"` // File under ImagePath on host containing an initrd image for starting a Linux utility VM
+ LinuxKernelFile string `json:",omitempty"` // File under ImagePath on host containing a kernel for starting a Linux utility VM
+}
+
+type MappedVirtualDisk struct {
+ HostPath string `json:",omitempty"` // Path to VHD on the host
+ ContainerPath string // Platform-specific mount point path in the container
+ CreateInUtilityVM bool `json:",omitempty"`
+ ReadOnly bool `json:",omitempty"`
+ Cache string `json:",omitempty"` // "" (Unspecified); "Disabled"; "Enabled"; "Private"; "PrivateAllowSharing"
+}
+
+// ContainerConfig is used as both the input of CreateContainer
+// and to convert the parameters to JSON for passing onto the HCS
+type ContainerConfig struct {
+ SystemType string // HCS requires this to be hard-coded to "Container"
+ Name string // Name of the container. We use the docker ID.
+ Owner string `json:",omitempty"` // The management platform that created this container
+ VolumePath string `json:",omitempty"` // Windows volume path for scratch space. Used by Windows Server Containers only. Format \\?\\Volume{GUID}
+ IgnoreFlushesDuringBoot bool `json:",omitempty"` // Optimization hint for container startup in Windows
+ LayerFolderPath string `json:",omitempty"` // Where the layer folders are located. Used by Windows Server Containers only. Format %root%\windowsfilter\containerID
+ Layers []Layer // List of storage layers. Required for Windows Server and Hyper-V Containers. Format ID=GUID;Path=%root%\windowsfilter\layerID
+ Credentials string `json:",omitempty"` // Credentials information
+ ProcessorCount uint32 `json:",omitempty"` // Number of processors to assign to the container.
+ ProcessorWeight uint64 `json:",omitempty"` // CPU Shares 0..10000 on Windows; where 0 will be omitted and HCS will default.
+ ProcessorMaximum int64 `json:",omitempty"` // CPU maximum usage percent 1..100
+ StorageIOPSMaximum uint64 `json:",omitempty"` // Maximum Storage IOPS
+ StorageBandwidthMaximum uint64 `json:",omitempty"` // Maximum Storage Bandwidth in bytes per second
+ StorageSandboxSize uint64 `json:",omitempty"` // Size in bytes that the container system drive should be expanded to if smaller
+ MemoryMaximumInMB int64 `json:",omitempty"` // Maximum memory available to the container in Megabytes
+ HostName string `json:",omitempty"` // Hostname
+ MappedDirectories []MappedDir `json:",omitempty"` // List of mapped directories (volumes/mounts)
+ HvPartition bool // True if it a Hyper-V Container
+ NetworkSharedContainerName string `json:",omitempty"` // Name (ID) of the container that we will share the network stack with.
+ EndpointList []string `json:",omitempty"` // List of networking endpoints to be attached to container
+ HvRuntime *HvRuntime `json:",omitempty"` // Hyper-V container settings. Used by Hyper-V containers only. Format ImagePath=%root%\BaseLayerID\UtilityVM
+ Servicing bool `json:",omitempty"` // True if this container is for servicing
+ AllowUnqualifiedDNSQuery bool `json:",omitempty"` // True to allow unqualified DNS name resolution
+ DNSSearchList string `json:",omitempty"` // Comma seperated list of DNS suffixes to use for name resolution
+ ContainerType string `json:",omitempty"` // "Linux" for Linux containers on Windows. Omitted otherwise.
+ TerminateOnLastHandleClosed bool `json:",omitempty"` // Should HCS terminate the container once all handles have been closed
+ MappedVirtualDisks []MappedVirtualDisk `json:",omitempty"` // Array of virtual disks to mount at start
+}
+
+type ComputeSystemQuery struct {
+ IDs []string `json:"Ids,omitempty"`
+ Types []string `json:",omitempty"`
+ Names []string `json:",omitempty"`
+ Owners []string `json:",omitempty"`
+}
+
+// Container represents a created (but not necessarily running) container.
+type Container interface {
+ // Start synchronously starts the container.
+ Start() error
+
+ // Shutdown requests a container shutdown, but it may not actually be shutdown until Wait() succeeds.
+ Shutdown() error
+
+ // Terminate requests a container terminate, but it may not actually be terminated until Wait() succeeds.
+ Terminate() error
+
+ // Waits synchronously waits for the container to shutdown or terminate.
+ Wait() error
+
+ // WaitTimeout synchronously waits for the container to terminate or the duration to elapse. It
+ // returns false if timeout occurs.
+ WaitTimeout(time.Duration) error
+
+ // Pause pauses the execution of a container.
+ Pause() error
+
+ // Resume resumes the execution of a container.
+ Resume() error
+
+ // HasPendingUpdates returns true if the container has updates pending to install.
+ HasPendingUpdates() (bool, error)
+
+ // Statistics returns statistics for a container.
+ Statistics() (Statistics, error)
+
+ // ProcessList returns details for the processes in a container.
+ ProcessList() ([]ProcessListItem, error)
+
+ // CreateProcess launches a new process within the container.
+ CreateProcess(c *ProcessConfig) (Process, error)
+
+ // OpenProcess gets an interface to an existing process within the container.
+ OpenProcess(pid int) (Process, error)
+
+ // Close cleans up any state associated with the container but does not terminate or wait for it.
+ Close() error
+
+ // Modify the System
+ Modify(config *ResourceModificationRequestResponse) error
+}
+
+// Process represents a running or exited process.
+type Process interface {
+ // Pid returns the process ID of the process within the container.
+ Pid() int
+
+ // Kill signals the process to terminate but does not wait for it to finish terminating.
+ Kill() error
+
+ // Wait waits for the process to exit.
+ Wait() error
+
+ // WaitTimeout waits for the process to exit or the duration to elapse. It returns
+ // false if timeout occurs.
+ WaitTimeout(time.Duration) error
+
+ // ExitCode returns the exit code of the process. The process must have
+ // already terminated.
+ ExitCode() (int, error)
+
+ // ResizeConsole resizes the console of the process.
+ ResizeConsole(width, height uint16) error
+
+ // Stdio returns the stdin, stdout, and stderr pipes, respectively. Closing
+ // these pipes does not close the underlying pipes; it should be possible to
+ // call this multiple times to get multiple interfaces.
+ Stdio() (io.WriteCloser, io.ReadCloser, io.ReadCloser, error)
+
+ // CloseStdin closes the write side of the stdin pipe so that the process is
+ // notified on the read side that there is no more data in stdin.
+ CloseStdin() error
+
+ // Close cleans up any state associated with the process but does not kill
+ // or wait on it.
+ Close() error
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/layerexists.go b/vendor/github.com/Microsoft/hcsshim/layerexists.go
new file mode 100644
index 0000000..522d95c
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/layerexists.go
@@ -0,0 +1,30 @@
+package hcsshim
+
+import "github.com/Sirupsen/logrus"
+
+// LayerExists will return true if a layer with the given id exists and is known
+// to the system.
+func LayerExists(info DriverInfo, id string) (bool, error) {
+ title := "hcsshim::LayerExists "
+ logrus.Debugf(title+"Flavour %d ID %s", info.Flavour, id)
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return false, err
+ }
+
+ // Call the procedure itself.
+ var exists uint32
+
+ err = layerExists(&infop, id, &exists)
+ if err != nil {
+ err = makeErrorf(err, title, "id=%s flavour=%d", id, info.Flavour)
+ logrus.Error(err)
+ return false, err
+ }
+
+ logrus.Debugf(title+"succeeded flavour=%d id=%s exists=%d", info.Flavour, id, exists)
+ return exists != 0, nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/layerutils.go b/vendor/github.com/Microsoft/hcsshim/layerutils.go
new file mode 100644
index 0000000..47229d2
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/layerutils.go
@@ -0,0 +1,111 @@
+package hcsshim
+
+// This file contains utility functions to support storage (graph) related
+// functionality.
+
+import (
+ "path/filepath"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+)
+
+/* To pass into syscall, we need a struct matching the following:
+enum GraphDriverType
+{
+ DiffDriver,
+ FilterDriver
+};
+
+struct DriverInfo {
+ GraphDriverType Flavour;
+ LPCWSTR HomeDir;
+};
+*/
+type DriverInfo struct {
+ Flavour int
+ HomeDir string
+}
+
+type driverInfo struct {
+ Flavour int
+ HomeDirp *uint16
+}
+
+func convertDriverInfo(info DriverInfo) (driverInfo, error) {
+ homedirp, err := syscall.UTF16PtrFromString(info.HomeDir)
+ if err != nil {
+ logrus.Debugf("Failed conversion of home to pointer for driver info: %s", err.Error())
+ return driverInfo{}, err
+ }
+
+ return driverInfo{
+ Flavour: info.Flavour,
+ HomeDirp: homedirp,
+ }, nil
+}
+
+/* To pass into syscall, we need a struct matching the following:
+typedef struct _WC_LAYER_DESCRIPTOR {
+
+ //
+ // The ID of the layer
+ //
+
+ GUID LayerId;
+
+ //
+ // Additional flags
+ //
+
+ union {
+ struct {
+ ULONG Reserved : 31;
+ ULONG Dirty : 1; // Created from sandbox as a result of snapshot
+ };
+ ULONG Value;
+ } Flags;
+
+ //
+ // Path to the layer root directory, null-terminated
+ //
+
+ PCWSTR Path;
+
+} WC_LAYER_DESCRIPTOR, *PWC_LAYER_DESCRIPTOR;
+*/
+type WC_LAYER_DESCRIPTOR struct {
+ LayerId GUID
+ Flags uint32
+ Pathp *uint16
+}
+
+func layerPathsToDescriptors(parentLayerPaths []string) ([]WC_LAYER_DESCRIPTOR, error) {
+ // Array of descriptors that gets constructed.
+ var layers []WC_LAYER_DESCRIPTOR
+
+ for i := 0; i < len(parentLayerPaths); i++ {
+ // Create a layer descriptor, using the folder name
+ // as the source for a GUID LayerId
+ _, folderName := filepath.Split(parentLayerPaths[i])
+ g, err := NameToGuid(folderName)
+ if err != nil {
+ logrus.Debugf("Failed to convert name to guid %s", err)
+ return nil, err
+ }
+
+ p, err := syscall.UTF16PtrFromString(parentLayerPaths[i])
+ if err != nil {
+ logrus.Debugf("Failed conversion of parentLayerPath to pointer %s", err)
+ return nil, err
+ }
+
+ layers = append(layers, WC_LAYER_DESCRIPTOR{
+ LayerId: g,
+ Flags: 0,
+ Pathp: p,
+ })
+ }
+
+ return layers, nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/legacy.go b/vendor/github.com/Microsoft/hcsshim/legacy.go
new file mode 100644
index 0000000..8576157
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/legacy.go
@@ -0,0 +1,731 @@
+package hcsshim
+
+import (
+ "bufio"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+
+ "github.com/Microsoft/go-winio"
+)
+
+var errorIterationCanceled = errors.New("")
+
+var mutatedUtilityVMFiles = map[string]bool{
+ `EFI\Microsoft\Boot\BCD`: true,
+ `EFI\Microsoft\Boot\BCD.LOG`: true,
+ `EFI\Microsoft\Boot\BCD.LOG1`: true,
+ `EFI\Microsoft\Boot\BCD.LOG2`: true,
+}
+
+const (
+ filesPath = `Files`
+ hivesPath = `Hives`
+ utilityVMPath = `UtilityVM`
+ utilityVMFilesPath = `UtilityVM\Files`
+)
+
+func openFileOrDir(path string, mode uint32, createDisposition uint32) (file *os.File, err error) {
+ return winio.OpenForBackup(path, mode, syscall.FILE_SHARE_READ, createDisposition)
+}
+
+func makeLongAbsPath(path string) (string, error) {
+ if strings.HasPrefix(path, `\\?\`) || strings.HasPrefix(path, `\\.\`) {
+ return path, nil
+ }
+ if !filepath.IsAbs(path) {
+ absPath, err := filepath.Abs(path)
+ if err != nil {
+ return "", err
+ }
+ path = absPath
+ }
+ if strings.HasPrefix(path, `\\`) {
+ return `\\?\UNC\` + path[2:], nil
+ }
+ return `\\?\` + path, nil
+}
+
+func hasPathPrefix(p, prefix string) bool {
+ return strings.HasPrefix(p, prefix) && len(p) > len(prefix) && p[len(prefix)] == '\\'
+}
+
+type fileEntry struct {
+ path string
+ fi os.FileInfo
+ err error
+}
+
+type legacyLayerReader struct {
+ root string
+ result chan *fileEntry
+ proceed chan bool
+ currentFile *os.File
+ backupReader *winio.BackupFileReader
+}
+
+// newLegacyLayerReader returns a new LayerReader that can read the Windows
+// container layer transport format from disk.
+func newLegacyLayerReader(root string) *legacyLayerReader {
+ r := &legacyLayerReader{
+ root: root,
+ result: make(chan *fileEntry),
+ proceed: make(chan bool),
+ }
+ go r.walk()
+ return r
+}
+
+func readTombstones(path string) (map[string]([]string), error) {
+ tf, err := os.Open(filepath.Join(path, "tombstones.txt"))
+ if err != nil {
+ return nil, err
+ }
+ defer tf.Close()
+ s := bufio.NewScanner(tf)
+ if !s.Scan() || s.Text() != "\xef\xbb\xbfVersion 1.0" {
+ return nil, errors.New("Invalid tombstones file")
+ }
+
+ ts := make(map[string]([]string))
+ for s.Scan() {
+ t := filepath.Join(filesPath, s.Text()[1:]) // skip leading `\`
+ dir := filepath.Dir(t)
+ ts[dir] = append(ts[dir], t)
+ }
+ if err = s.Err(); err != nil {
+ return nil, err
+ }
+
+ return ts, nil
+}
+
+func (r *legacyLayerReader) walkUntilCancelled() error {
+ root, err := makeLongAbsPath(r.root)
+ if err != nil {
+ return err
+ }
+
+ r.root = root
+ ts, err := readTombstones(r.root)
+ if err != nil {
+ return err
+ }
+
+ err = filepath.Walk(r.root, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ if path == r.root || path == filepath.Join(r.root, "tombstones.txt") || strings.HasSuffix(path, ".$wcidirs$") {
+ return nil
+ }
+
+ r.result <- &fileEntry{path, info, nil}
+ if !<-r.proceed {
+ return errorIterationCanceled
+ }
+
+ // List all the tombstones.
+ if info.IsDir() {
+ relPath, err := filepath.Rel(r.root, path)
+ if err != nil {
+ return err
+ }
+ if dts, ok := ts[relPath]; ok {
+ for _, t := range dts {
+ r.result <- &fileEntry{filepath.Join(r.root, t), nil, nil}
+ if !<-r.proceed {
+ return errorIterationCanceled
+ }
+ }
+ }
+ }
+ return nil
+ })
+ if err == errorIterationCanceled {
+ return nil
+ }
+ if err == nil {
+ return io.EOF
+ }
+ return err
+}
+
+func (r *legacyLayerReader) walk() {
+ defer close(r.result)
+ if !<-r.proceed {
+ return
+ }
+
+ err := r.walkUntilCancelled()
+ if err != nil {
+ for {
+ r.result <- &fileEntry{err: err}
+ if !<-r.proceed {
+ return
+ }
+ }
+ }
+}
+
+func (r *legacyLayerReader) reset() {
+ if r.backupReader != nil {
+ r.backupReader.Close()
+ r.backupReader = nil
+ }
+ if r.currentFile != nil {
+ r.currentFile.Close()
+ r.currentFile = nil
+ }
+}
+
+func findBackupStreamSize(r io.Reader) (int64, error) {
+ br := winio.NewBackupStreamReader(r)
+ for {
+ hdr, err := br.Next()
+ if err != nil {
+ if err == io.EOF {
+ err = nil
+ }
+ return 0, err
+ }
+ if hdr.Id == winio.BackupData {
+ return hdr.Size, nil
+ }
+ }
+}
+
+func (r *legacyLayerReader) Next() (path string, size int64, fileInfo *winio.FileBasicInfo, err error) {
+ r.reset()
+ r.proceed <- true
+ fe := <-r.result
+ if fe == nil {
+ err = errors.New("LegacyLayerReader closed")
+ return
+ }
+ if fe.err != nil {
+ err = fe.err
+ return
+ }
+
+ path, err = filepath.Rel(r.root, fe.path)
+ if err != nil {
+ return
+ }
+
+ if fe.fi == nil {
+ // This is a tombstone. Return a nil fileInfo.
+ return
+ }
+
+ if fe.fi.IsDir() && hasPathPrefix(path, filesPath) {
+ fe.path += ".$wcidirs$"
+ }
+
+ f, err := openFileOrDir(fe.path, syscall.GENERIC_READ, syscall.OPEN_EXISTING)
+ if err != nil {
+ return
+ }
+ defer func() {
+ if f != nil {
+ f.Close()
+ }
+ }()
+
+ fileInfo, err = winio.GetFileBasicInfo(f)
+ if err != nil {
+ return
+ }
+
+ if !hasPathPrefix(path, filesPath) {
+ size = fe.fi.Size()
+ r.backupReader = winio.NewBackupFileReader(f, false)
+ if path == hivesPath || path == filesPath {
+ // The Hives directory has a non-deterministic file time because of the
+ // nature of the import process. Use the times from System_Delta.
+ var g *os.File
+ g, err = os.Open(filepath.Join(r.root, hivesPath, `System_Delta`))
+ if err != nil {
+ return
+ }
+ attr := fileInfo.FileAttributes
+ fileInfo, err = winio.GetFileBasicInfo(g)
+ g.Close()
+ if err != nil {
+ return
+ }
+ fileInfo.FileAttributes = attr
+ }
+
+ // The creation time and access time get reset for files outside of the Files path.
+ fileInfo.CreationTime = fileInfo.LastWriteTime
+ fileInfo.LastAccessTime = fileInfo.LastWriteTime
+
+ } else {
+ // The file attributes are written before the backup stream.
+ var attr uint32
+ err = binary.Read(f, binary.LittleEndian, &attr)
+ if err != nil {
+ return
+ }
+ fileInfo.FileAttributes = uintptr(attr)
+ beginning := int64(4)
+
+ // Find the accurate file size.
+ if !fe.fi.IsDir() {
+ size, err = findBackupStreamSize(f)
+ if err != nil {
+ err = &os.PathError{Op: "findBackupStreamSize", Path: fe.path, Err: err}
+ return
+ }
+ }
+
+ // Return back to the beginning of the backup stream.
+ _, err = f.Seek(beginning, 0)
+ if err != nil {
+ return
+ }
+ }
+
+ r.currentFile = f
+ f = nil
+ return
+}
+
+func (r *legacyLayerReader) Read(b []byte) (int, error) {
+ if r.backupReader == nil {
+ if r.currentFile == nil {
+ return 0, io.EOF
+ }
+ return r.currentFile.Read(b)
+ }
+ return r.backupReader.Read(b)
+}
+
+func (r *legacyLayerReader) Close() error {
+ r.proceed <- false
+ <-r.result
+ r.reset()
+ return nil
+}
+
+type pendingLink struct {
+ Path, Target string
+}
+
+type legacyLayerWriter struct {
+ root string
+ parentRoots []string
+ destRoot string
+ currentFile *os.File
+ backupWriter *winio.BackupFileWriter
+ tombstones []string
+ pathFixed bool
+ HasUtilityVM bool
+ uvmDi []dirInfo
+ addedFiles map[string]bool
+ PendingLinks []pendingLink
+}
+
+// newLegacyLayerWriter returns a LayerWriter that can write the contaler layer
+// transport format to disk.
+func newLegacyLayerWriter(root string, parentRoots []string, destRoot string) *legacyLayerWriter {
+ return &legacyLayerWriter{
+ root: root,
+ parentRoots: parentRoots,
+ destRoot: destRoot,
+ addedFiles: make(map[string]bool),
+ }
+}
+
+func (w *legacyLayerWriter) init() error {
+ if !w.pathFixed {
+ path, err := makeLongAbsPath(w.root)
+ if err != nil {
+ return err
+ }
+ for i, p := range w.parentRoots {
+ w.parentRoots[i], err = makeLongAbsPath(p)
+ if err != nil {
+ return err
+ }
+ }
+ destPath, err := makeLongAbsPath(w.destRoot)
+ if err != nil {
+ return err
+ }
+ w.root = path
+ w.destRoot = destPath
+ w.pathFixed = true
+ }
+ return nil
+}
+
+func (w *legacyLayerWriter) initUtilityVM() error {
+ if !w.HasUtilityVM {
+ err := os.Mkdir(filepath.Join(w.destRoot, utilityVMPath), 0)
+ if err != nil {
+ return err
+ }
+ // Server 2016 does not support multiple layers for the utility VM, so
+ // clone the utility VM from the parent layer into this layer. Use hard
+ // links to avoid unnecessary copying, since most of the files are
+ // immutable.
+ err = cloneTree(filepath.Join(w.parentRoots[0], utilityVMFilesPath), filepath.Join(w.destRoot, utilityVMFilesPath), mutatedUtilityVMFiles)
+ if err != nil {
+ return fmt.Errorf("cloning the parent utility VM image failed: %s", err)
+ }
+ w.HasUtilityVM = true
+ }
+ return nil
+}
+
+func (w *legacyLayerWriter) reset() {
+ if w.backupWriter != nil {
+ w.backupWriter.Close()
+ w.backupWriter = nil
+ }
+ if w.currentFile != nil {
+ w.currentFile.Close()
+ w.currentFile = nil
+ }
+}
+
+// copyFileWithMetadata copies a file using the backup/restore APIs in order to preserve metadata
+func copyFileWithMetadata(srcPath, destPath string, isDir bool) (fileInfo *winio.FileBasicInfo, err error) {
+ createDisposition := uint32(syscall.CREATE_NEW)
+ if isDir {
+ err = os.Mkdir(destPath, 0)
+ if err != nil {
+ return nil, err
+ }
+ createDisposition = syscall.OPEN_EXISTING
+ }
+
+ src, err := openFileOrDir(srcPath, syscall.GENERIC_READ|winio.ACCESS_SYSTEM_SECURITY, syscall.OPEN_EXISTING)
+ if err != nil {
+ return nil, err
+ }
+ defer src.Close()
+ srcr := winio.NewBackupFileReader(src, true)
+ defer srcr.Close()
+
+ fileInfo, err = winio.GetFileBasicInfo(src)
+ if err != nil {
+ return nil, err
+ }
+
+ dest, err := openFileOrDir(destPath, syscall.GENERIC_READ|syscall.GENERIC_WRITE|winio.WRITE_DAC|winio.WRITE_OWNER|winio.ACCESS_SYSTEM_SECURITY, createDisposition)
+ if err != nil {
+ return nil, err
+ }
+ defer dest.Close()
+
+ err = winio.SetFileBasicInfo(dest, fileInfo)
+ if err != nil {
+ return nil, err
+ }
+
+ destw := winio.NewBackupFileWriter(dest, true)
+ defer func() {
+ cerr := destw.Close()
+ if err == nil {
+ err = cerr
+ }
+ }()
+
+ _, err = io.Copy(destw, srcr)
+ if err != nil {
+ return nil, err
+ }
+
+ return fileInfo, nil
+}
+
+// cloneTree clones a directory tree using hard links. It skips hard links for
+// the file names in the provided map and just copies those files.
+func cloneTree(srcPath, destPath string, mutatedFiles map[string]bool) error {
+ var di []dirInfo
+ err := filepath.Walk(srcPath, func(srcFilePath string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+
+ relPath, err := filepath.Rel(srcPath, srcFilePath)
+ if err != nil {
+ return err
+ }
+ destFilePath := filepath.Join(destPath, relPath)
+
+ // Directories, reparse points, and files that will be mutated during
+ // utility VM import must be copied. All other files can be hard linked.
+ isReparsePoint := info.Sys().(*syscall.Win32FileAttributeData).FileAttributes&syscall.FILE_ATTRIBUTE_REPARSE_POINT != 0
+ if info.IsDir() || isReparsePoint || mutatedFiles[relPath] {
+ fi, err := copyFileWithMetadata(srcFilePath, destFilePath, info.IsDir())
+ if err != nil {
+ return err
+ }
+ if info.IsDir() && !isReparsePoint {
+ di = append(di, dirInfo{path: destFilePath, fileInfo: *fi})
+ }
+ } else {
+ err = os.Link(srcFilePath, destFilePath)
+ if err != nil {
+ return err
+ }
+ }
+
+ // Don't recurse on reparse points.
+ if info.IsDir() && isReparsePoint {
+ return filepath.SkipDir
+ }
+
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ return reapplyDirectoryTimes(di)
+}
+
+func (w *legacyLayerWriter) Add(name string, fileInfo *winio.FileBasicInfo) error {
+ w.reset()
+ err := w.init()
+ if err != nil {
+ return err
+ }
+
+ if name == utilityVMPath {
+ return w.initUtilityVM()
+ }
+
+ if hasPathPrefix(name, utilityVMPath) {
+ if !w.HasUtilityVM {
+ return errors.New("missing UtilityVM directory")
+ }
+ if !hasPathPrefix(name, utilityVMFilesPath) && name != utilityVMFilesPath {
+ return errors.New("invalid UtilityVM layer")
+ }
+ path := filepath.Join(w.destRoot, name)
+ createDisposition := uint32(syscall.OPEN_EXISTING)
+ if (fileInfo.FileAttributes & syscall.FILE_ATTRIBUTE_DIRECTORY) != 0 {
+ st, err := os.Lstat(path)
+ if err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ if st != nil {
+ // Delete the existing file/directory if it is not the same type as this directory.
+ existingAttr := st.Sys().(*syscall.Win32FileAttributeData).FileAttributes
+ if (uint32(fileInfo.FileAttributes)^existingAttr)&(syscall.FILE_ATTRIBUTE_DIRECTORY|syscall.FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
+ if err = os.RemoveAll(path); err != nil {
+ return err
+ }
+ st = nil
+ }
+ }
+ if st == nil {
+ if err = os.Mkdir(path, 0); err != nil {
+ return err
+ }
+ }
+ if fileInfo.FileAttributes&syscall.FILE_ATTRIBUTE_REPARSE_POINT == 0 {
+ w.uvmDi = append(w.uvmDi, dirInfo{path: path, fileInfo: *fileInfo})
+ }
+ } else {
+ // Overwrite any existing hard link.
+ err = os.Remove(path)
+ if err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ createDisposition = syscall.CREATE_NEW
+ }
+
+ f, err := openFileOrDir(path, syscall.GENERIC_READ|syscall.GENERIC_WRITE|winio.WRITE_DAC|winio.WRITE_OWNER|winio.ACCESS_SYSTEM_SECURITY, createDisposition)
+ if err != nil {
+ return err
+ }
+ defer func() {
+ if f != nil {
+ f.Close()
+ os.Remove(path)
+ }
+ }()
+
+ err = winio.SetFileBasicInfo(f, fileInfo)
+ if err != nil {
+ return err
+ }
+
+ w.backupWriter = winio.NewBackupFileWriter(f, true)
+ w.currentFile = f
+ w.addedFiles[name] = true
+ f = nil
+ return nil
+ }
+
+ path := filepath.Join(w.root, name)
+ if (fileInfo.FileAttributes & syscall.FILE_ATTRIBUTE_DIRECTORY) != 0 {
+ err := os.Mkdir(path, 0)
+ if err != nil {
+ return err
+ }
+ path += ".$wcidirs$"
+ }
+
+ f, err := openFileOrDir(path, syscall.GENERIC_READ|syscall.GENERIC_WRITE, syscall.CREATE_NEW)
+ if err != nil {
+ return err
+ }
+ defer func() {
+ if f != nil {
+ f.Close()
+ os.Remove(path)
+ }
+ }()
+
+ strippedFi := *fileInfo
+ strippedFi.FileAttributes = 0
+ err = winio.SetFileBasicInfo(f, &strippedFi)
+ if err != nil {
+ return err
+ }
+
+ if hasPathPrefix(name, hivesPath) {
+ w.backupWriter = winio.NewBackupFileWriter(f, false)
+ } else {
+ // The file attributes are written before the stream.
+ err = binary.Write(f, binary.LittleEndian, uint32(fileInfo.FileAttributes))
+ if err != nil {
+ return err
+ }
+ }
+
+ w.currentFile = f
+ w.addedFiles[name] = true
+ f = nil
+ return nil
+}
+
+func (w *legacyLayerWriter) AddLink(name string, target string) error {
+ w.reset()
+ err := w.init()
+ if err != nil {
+ return err
+ }
+
+ var roots []string
+ if hasPathPrefix(target, filesPath) {
+ // Look for cross-layer hard link targets in the parent layers, since
+ // nothing is in the destination path yet.
+ roots = w.parentRoots
+ } else if hasPathPrefix(target, utilityVMFilesPath) {
+ // Since the utility VM is fully cloned into the destination path
+ // already, look for cross-layer hard link targets directly in the
+ // destination path.
+ roots = []string{w.destRoot}
+ }
+
+ if roots == nil || (!hasPathPrefix(name, filesPath) && !hasPathPrefix(name, utilityVMFilesPath)) {
+ return errors.New("invalid hard link in layer")
+ }
+
+ // Find to try the target of the link in a previously added file. If that
+ // fails, search in parent layers.
+ var selectedRoot string
+ if _, ok := w.addedFiles[target]; ok {
+ selectedRoot = w.destRoot
+ } else {
+ for _, r := range roots {
+ if _, err = os.Lstat(filepath.Join(r, target)); err != nil {
+ if !os.IsNotExist(err) {
+ return err
+ }
+ } else {
+ selectedRoot = r
+ break
+ }
+ }
+ if selectedRoot == "" {
+ return fmt.Errorf("failed to find link target for '%s' -> '%s'", name, target)
+ }
+ }
+ // The link can't be written until after the ImportLayer call.
+ w.PendingLinks = append(w.PendingLinks, pendingLink{
+ Path: filepath.Join(w.destRoot, name),
+ Target: filepath.Join(selectedRoot, target),
+ })
+ w.addedFiles[name] = true
+ return nil
+}
+
+func (w *legacyLayerWriter) Remove(name string) error {
+ if hasPathPrefix(name, filesPath) {
+ w.tombstones = append(w.tombstones, name[len(filesPath)+1:])
+ } else if hasPathPrefix(name, utilityVMFilesPath) {
+ err := w.initUtilityVM()
+ if err != nil {
+ return err
+ }
+ // Make sure the path exists; os.RemoveAll will not fail if the file is
+ // already gone, and this needs to be a fatal error for diagnostics
+ // purposes.
+ path := filepath.Join(w.destRoot, name)
+ if _, err := os.Lstat(path); err != nil {
+ return err
+ }
+ err = os.RemoveAll(path)
+ if err != nil {
+ return err
+ }
+ } else {
+ return fmt.Errorf("invalid tombstone %s", name)
+ }
+
+ return nil
+}
+
+func (w *legacyLayerWriter) Write(b []byte) (int, error) {
+ if w.backupWriter == nil {
+ if w.currentFile == nil {
+ return 0, errors.New("closed")
+ }
+ return w.currentFile.Write(b)
+ }
+ return w.backupWriter.Write(b)
+}
+
+func (w *legacyLayerWriter) Close() error {
+ w.reset()
+ err := w.init()
+ if err != nil {
+ return err
+ }
+ tf, err := os.Create(filepath.Join(w.root, "tombstones.txt"))
+ if err != nil {
+ return err
+ }
+ defer tf.Close()
+ _, err = tf.Write([]byte("\xef\xbb\xbfVersion 1.0\n"))
+ if err != nil {
+ return err
+ }
+ for _, t := range w.tombstones {
+ _, err = tf.Write([]byte(filepath.Join(`\`, t) + "\n"))
+ if err != nil {
+ return err
+ }
+ }
+ if w.HasUtilityVM {
+ err = reapplyDirectoryTimes(w.uvmDi)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/nametoguid.go b/vendor/github.com/Microsoft/hcsshim/nametoguid.go
new file mode 100644
index 0000000..1a522f9
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/nametoguid.go
@@ -0,0 +1,20 @@
+package hcsshim
+
+import "github.com/Sirupsen/logrus"
+
+// NameToGuid converts the given string into a GUID using the algorithm in the
+// Host Compute Service, ensuring GUIDs generated with the same string are common
+// across all clients.
+func NameToGuid(name string) (id GUID, err error) {
+ title := "hcsshim::NameToGuid "
+ logrus.Debugf(title+"Name %s", name)
+
+ err = nameToGuid(name, &id)
+ if err != nil {
+ err = makeErrorf(err, title, "name=%s", name)
+ logrus.Error(err)
+ return
+ }
+
+ return
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/preparelayer.go b/vendor/github.com/Microsoft/hcsshim/preparelayer.go
new file mode 100644
index 0000000..2791683
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/preparelayer.go
@@ -0,0 +1,46 @@
+package hcsshim
+
+import (
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+)
+
+var prepareLayerLock sync.Mutex
+
+// PrepareLayer finds a mounted read-write layer matching layerId and enables the
+// the filesystem filter for use on that layer. This requires the paths to all
+// parent layers, and is necessary in order to view or interact with the layer
+// as an actual filesystem (reading and writing files, creating directories, etc).
+// Disabling the filter must be done via UnprepareLayer.
+func PrepareLayer(info DriverInfo, layerId string, parentLayerPaths []string) error {
+ title := "hcsshim::PrepareLayer "
+ logrus.Debugf(title+"flavour %d layerId %s", info.Flavour, layerId)
+
+ // Generate layer descriptors
+ layers, err := layerPathsToDescriptors(parentLayerPaths)
+ if err != nil {
+ return err
+ }
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return err
+ }
+
+ // This lock is a temporary workaround for a Windows bug. Only allowing one
+ // call to prepareLayer at a time vastly reduces the chance of a timeout.
+ prepareLayerLock.Lock()
+ defer prepareLayerLock.Unlock()
+ err = prepareLayer(&infop, layerId, layers)
+ if err != nil {
+ err = makeErrorf(err, title, "layerId=%s flavour=%d", layerId, info.Flavour)
+ logrus.Error(err)
+ return err
+ }
+
+ logrus.Debugf(title+"succeeded flavour=%d layerId=%s", info.Flavour, layerId)
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/process.go b/vendor/github.com/Microsoft/hcsshim/process.go
new file mode 100644
index 0000000..4ef0ed3
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/process.go
@@ -0,0 +1,384 @@
+package hcsshim
+
+import (
+ "encoding/json"
+ "io"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// ContainerError is an error encountered in HCS
+type process struct {
+ handleLock sync.RWMutex
+ handle hcsProcess
+ processID int
+ container *container
+ cachedPipes *cachedPipes
+ callbackNumber uintptr
+}
+
+type cachedPipes struct {
+ stdIn syscall.Handle
+ stdOut syscall.Handle
+ stdErr syscall.Handle
+}
+
+type processModifyRequest struct {
+ Operation string
+ ConsoleSize *consoleSize `json:",omitempty"`
+ CloseHandle *closeHandle `json:",omitempty"`
+}
+
+type consoleSize struct {
+ Height uint16
+ Width uint16
+}
+
+type closeHandle struct {
+ Handle string
+}
+
+type processStatus struct {
+ ProcessID uint32
+ Exited bool
+ ExitCode uint32
+ LastWaitResult int32
+}
+
+const (
+ stdIn string = "StdIn"
+ stdOut string = "StdOut"
+ stdErr string = "StdErr"
+)
+
+const (
+ modifyConsoleSize string = "ConsoleSize"
+ modifyCloseHandle string = "CloseHandle"
+)
+
+// Pid returns the process ID of the process within the container.
+func (process *process) Pid() int {
+ return process.processID
+}
+
+// Kill signals the process to terminate but does not wait for it to finish terminating.
+func (process *process) Kill() error {
+ process.handleLock.RLock()
+ defer process.handleLock.RUnlock()
+ operation := "Kill"
+ title := "HCSShim::Process::" + operation
+ logrus.Debugf(title+" processid=%d", process.processID)
+
+ if process.handle == 0 {
+ return makeProcessError(process, operation, "", ErrAlreadyClosed)
+ }
+
+ var resultp *uint16
+ err := hcsTerminateProcess(process.handle, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return makeProcessError(process, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded processid=%d", process.processID)
+ return nil
+}
+
+// Wait waits for the process to exit.
+func (process *process) Wait() error {
+ operation := "Wait"
+ title := "HCSShim::Process::" + operation
+ logrus.Debugf(title+" processid=%d", process.processID)
+
+ err := waitForNotification(process.callbackNumber, hcsNotificationProcessExited, nil)
+ if err != nil {
+ return makeProcessError(process, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded processid=%d", process.processID)
+ return nil
+}
+
+// WaitTimeout waits for the process to exit or the duration to elapse. It returns
+// false if timeout occurs.
+func (process *process) WaitTimeout(timeout time.Duration) error {
+ operation := "WaitTimeout"
+ title := "HCSShim::Process::" + operation
+ logrus.Debugf(title+" processid=%d", process.processID)
+
+ err := waitForNotification(process.callbackNumber, hcsNotificationProcessExited, &timeout)
+ if err != nil {
+ return makeProcessError(process, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded processid=%d", process.processID)
+ return nil
+}
+
+// ExitCode returns the exit code of the process. The process must have
+// already terminated.
+func (process *process) ExitCode() (int, error) {
+ process.handleLock.RLock()
+ defer process.handleLock.RUnlock()
+ operation := "ExitCode"
+ title := "HCSShim::Process::" + operation
+ logrus.Debugf(title+" processid=%d", process.processID)
+
+ if process.handle == 0 {
+ return 0, makeProcessError(process, operation, "", ErrAlreadyClosed)
+ }
+
+ properties, err := process.properties()
+ if err != nil {
+ return 0, makeProcessError(process, operation, "", err)
+ }
+
+ if properties.Exited == false {
+ return 0, makeProcessError(process, operation, "", ErrInvalidProcessState)
+ }
+
+ if properties.LastWaitResult != 0 {
+ return 0, makeProcessError(process, operation, "", syscall.Errno(properties.LastWaitResult))
+ }
+
+ logrus.Debugf(title+" succeeded processid=%d exitCode=%d", process.processID, properties.ExitCode)
+ return int(properties.ExitCode), nil
+}
+
+// ResizeConsole resizes the console of the process.
+func (process *process) ResizeConsole(width, height uint16) error {
+ process.handleLock.RLock()
+ defer process.handleLock.RUnlock()
+ operation := "ResizeConsole"
+ title := "HCSShim::Process::" + operation
+ logrus.Debugf(title+" processid=%d", process.processID)
+
+ if process.handle == 0 {
+ return makeProcessError(process, operation, "", ErrAlreadyClosed)
+ }
+
+ modifyRequest := processModifyRequest{
+ Operation: modifyConsoleSize,
+ ConsoleSize: &consoleSize{
+ Height: height,
+ Width: width,
+ },
+ }
+
+ modifyRequestb, err := json.Marshal(modifyRequest)
+ if err != nil {
+ return err
+ }
+
+ modifyRequestStr := string(modifyRequestb)
+
+ var resultp *uint16
+ err = hcsModifyProcess(process.handle, modifyRequestStr, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return makeProcessError(process, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded processid=%d", process.processID)
+ return nil
+}
+
+func (process *process) properties() (*processStatus, error) {
+ operation := "properties"
+ title := "HCSShim::Process::" + operation
+ logrus.Debugf(title+" processid=%d", process.processID)
+
+ var (
+ resultp *uint16
+ propertiesp *uint16
+ )
+ err := hcsGetProcessProperties(process.handle, &propertiesp, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return nil, err
+ }
+
+ if propertiesp == nil {
+ return nil, ErrUnexpectedValue
+ }
+ propertiesRaw := convertAndFreeCoTaskMemBytes(propertiesp)
+
+ properties := &processStatus{}
+ if err := json.Unmarshal(propertiesRaw, properties); err != nil {
+ return nil, err
+ }
+
+ logrus.Debugf(title+" succeeded processid=%d, properties=%s", process.processID, propertiesRaw)
+ return properties, nil
+}
+
+// Stdio returns the stdin, stdout, and stderr pipes, respectively. Closing
+// these pipes does not close the underlying pipes; it should be possible to
+// call this multiple times to get multiple interfaces.
+func (process *process) Stdio() (io.WriteCloser, io.ReadCloser, io.ReadCloser, error) {
+ process.handleLock.RLock()
+ defer process.handleLock.RUnlock()
+ operation := "Stdio"
+ title := "HCSShim::Process::" + operation
+ logrus.Debugf(title+" processid=%d", process.processID)
+
+ if process.handle == 0 {
+ return nil, nil, nil, makeProcessError(process, operation, "", ErrAlreadyClosed)
+ }
+
+ var stdIn, stdOut, stdErr syscall.Handle
+
+ if process.cachedPipes == nil {
+ var (
+ processInfo hcsProcessInformation
+ resultp *uint16
+ )
+ err := hcsGetProcessInfo(process.handle, &processInfo, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return nil, nil, nil, makeProcessError(process, operation, "", err)
+ }
+
+ stdIn, stdOut, stdErr = processInfo.StdInput, processInfo.StdOutput, processInfo.StdError
+ } else {
+ // Use cached pipes
+ stdIn, stdOut, stdErr = process.cachedPipes.stdIn, process.cachedPipes.stdOut, process.cachedPipes.stdErr
+
+ // Invalidate the cache
+ process.cachedPipes = nil
+ }
+
+ pipes, err := makeOpenFiles([]syscall.Handle{stdIn, stdOut, stdErr})
+ if err != nil {
+ return nil, nil, nil, makeProcessError(process, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded processid=%d", process.processID)
+ return pipes[0], pipes[1], pipes[2], nil
+}
+
+// CloseStdin closes the write side of the stdin pipe so that the process is
+// notified on the read side that there is no more data in stdin.
+func (process *process) CloseStdin() error {
+ process.handleLock.RLock()
+ defer process.handleLock.RUnlock()
+ operation := "CloseStdin"
+ title := "HCSShim::Process::" + operation
+ logrus.Debugf(title+" processid=%d", process.processID)
+
+ if process.handle == 0 {
+ return makeProcessError(process, operation, "", ErrAlreadyClosed)
+ }
+
+ modifyRequest := processModifyRequest{
+ Operation: modifyCloseHandle,
+ CloseHandle: &closeHandle{
+ Handle: stdIn,
+ },
+ }
+
+ modifyRequestb, err := json.Marshal(modifyRequest)
+ if err != nil {
+ return err
+ }
+
+ modifyRequestStr := string(modifyRequestb)
+
+ var resultp *uint16
+ err = hcsModifyProcess(process.handle, modifyRequestStr, &resultp)
+ err = processHcsResult(err, resultp)
+ if err != nil {
+ return makeProcessError(process, operation, "", err)
+ }
+
+ logrus.Debugf(title+" succeeded processid=%d", process.processID)
+ return nil
+}
+
+// Close cleans up any state associated with the process but does not kill
+// or wait on it.
+func (process *process) Close() error {
+ process.handleLock.Lock()
+ defer process.handleLock.Unlock()
+ operation := "Close"
+ title := "HCSShim::Process::" + operation
+ logrus.Debugf(title+" processid=%d", process.processID)
+
+ // Don't double free this
+ if process.handle == 0 {
+ return nil
+ }
+
+ if err := process.unregisterCallback(); err != nil {
+ return makeProcessError(process, operation, "", err)
+ }
+
+ if err := hcsCloseProcess(process.handle); err != nil {
+ return makeProcessError(process, operation, "", err)
+ }
+
+ process.handle = 0
+
+ logrus.Debugf(title+" succeeded processid=%d", process.processID)
+ return nil
+}
+
+func (process *process) registerCallback() error {
+ context := &notifcationWatcherContext{
+ channels: newChannels(),
+ }
+
+ callbackMapLock.Lock()
+ callbackNumber := nextCallback
+ nextCallback++
+ callbackMap[callbackNumber] = context
+ callbackMapLock.Unlock()
+
+ var callbackHandle hcsCallback
+ err := hcsRegisterProcessCallback(process.handle, notificationWatcherCallback, callbackNumber, &callbackHandle)
+ if err != nil {
+ return err
+ }
+ context.handle = callbackHandle
+ process.callbackNumber = callbackNumber
+
+ return nil
+}
+
+func (process *process) unregisterCallback() error {
+ callbackNumber := process.callbackNumber
+
+ callbackMapLock.RLock()
+ context := callbackMap[callbackNumber]
+ callbackMapLock.RUnlock()
+
+ if context == nil {
+ return nil
+ }
+
+ handle := context.handle
+
+ if handle == 0 {
+ return nil
+ }
+
+ // hcsUnregisterProcessCallback has its own syncronization
+ // to wait for all callbacks to complete. We must NOT hold the callbackMapLock.
+ err := hcsUnregisterProcessCallback(handle)
+ if err != nil {
+ return err
+ }
+
+ closeChannels(context.channels)
+
+ callbackMapLock.Lock()
+ callbackMap[callbackNumber] = nil
+ callbackMapLock.Unlock()
+
+ handle = 0
+
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/processimage.go b/vendor/github.com/Microsoft/hcsshim/processimage.go
new file mode 100644
index 0000000..fadb1b9
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/processimage.go
@@ -0,0 +1,23 @@
+package hcsshim
+
+import "os"
+
+// ProcessBaseLayer post-processes a base layer that has had its files extracted.
+// The files should have been extracted to <path>\Files.
+func ProcessBaseLayer(path string) error {
+ err := processBaseImage(path)
+ if err != nil {
+ return &os.PathError{Op: "ProcessBaseLayer", Path: path, Err: err}
+ }
+ return nil
+}
+
+// ProcessUtilityVMImage post-processes a utility VM image that has had its files extracted.
+// The files should have been extracted to <path>\Files.
+func ProcessUtilityVMImage(path string) error {
+ err := processUtilityImage(path)
+ if err != nil {
+ return &os.PathError{Op: "ProcessUtilityVMImage", Path: path, Err: err}
+ }
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/unpreparelayer.go b/vendor/github.com/Microsoft/hcsshim/unpreparelayer.go
new file mode 100644
index 0000000..d0ead0b
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/unpreparelayer.go
@@ -0,0 +1,27 @@
+package hcsshim
+
+import "github.com/Sirupsen/logrus"
+
+// UnprepareLayer disables the filesystem filter for the read-write layer with
+// the given id.
+func UnprepareLayer(info DriverInfo, layerId string) error {
+ title := "hcsshim::UnprepareLayer "
+ logrus.Debugf(title+"flavour %d layerId %s", info.Flavour, layerId)
+
+ // Convert info to API calling convention
+ infop, err := convertDriverInfo(info)
+ if err != nil {
+ logrus.Error(err)
+ return err
+ }
+
+ err = unprepareLayer(&infop, layerId)
+ if err != nil {
+ err = makeErrorf(err, title, "layerId=%s flavour=%d", layerId, info.Flavour)
+ logrus.Error(err)
+ return err
+ }
+
+ logrus.Debugf(title+"succeeded flavour %d layerId=%s", info.Flavour, layerId)
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/utils.go b/vendor/github.com/Microsoft/hcsshim/utils.go
new file mode 100644
index 0000000..bd6e2d9
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/utils.go
@@ -0,0 +1,33 @@
+package hcsshim
+
+import (
+ "io"
+ "syscall"
+
+ "github.com/Microsoft/go-winio"
+)
+
+// makeOpenFiles calls winio.MakeOpenFile for each handle in a slice but closes all the handles
+// if there is an error.
+func makeOpenFiles(hs []syscall.Handle) (_ []io.ReadWriteCloser, err error) {
+ fs := make([]io.ReadWriteCloser, len(hs))
+ for i, h := range hs {
+ if h != syscall.Handle(0) {
+ if err == nil {
+ fs[i], err = winio.MakeOpenFile(h)
+ }
+ if err != nil {
+ syscall.Close(h)
+ }
+ }
+ }
+ if err != nil {
+ for _, f := range fs {
+ if f != nil {
+ f.Close()
+ }
+ }
+ return nil, err
+ }
+ return fs, nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/version.go b/vendor/github.com/Microsoft/hcsshim/version.go
new file mode 100644
index 0000000..ae10c23
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/version.go
@@ -0,0 +1,7 @@
+package hcsshim
+
+// IsTP4 returns whether the currently running Windows build is at least TP4.
+func IsTP4() bool {
+ // HNSCall was not present in TP4
+ return procHNSCall.Find() != nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/waithelper.go b/vendor/github.com/Microsoft/hcsshim/waithelper.go
new file mode 100644
index 0000000..828d148
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/waithelper.go
@@ -0,0 +1,63 @@
+package hcsshim
+
+import (
+ "time"
+
+ "github.com/Sirupsen/logrus"
+)
+
+func processAsyncHcsResult(err error, resultp *uint16, callbackNumber uintptr, expectedNotification hcsNotification, timeout *time.Duration) error {
+ err = processHcsResult(err, resultp)
+ if IsPending(err) {
+ return waitForNotification(callbackNumber, expectedNotification, timeout)
+ }
+
+ return err
+}
+
+func waitForNotification(callbackNumber uintptr, expectedNotification hcsNotification, timeout *time.Duration) error {
+ callbackMapLock.RLock()
+ channels := callbackMap[callbackNumber].channels
+ callbackMapLock.RUnlock()
+
+ expectedChannel := channels[expectedNotification]
+ if expectedChannel == nil {
+ logrus.Errorf("unknown notification type in waitForNotification %x", expectedNotification)
+ return ErrInvalidNotificationType
+ }
+
+ var c <-chan time.Time
+ if timeout != nil {
+ timer := time.NewTimer(*timeout)
+ c = timer.C
+ defer timer.Stop()
+ }
+
+ select {
+ case err, ok := <-expectedChannel:
+ if !ok {
+ return ErrHandleClose
+ }
+ return err
+ case err, ok := <-channels[hcsNotificationSystemExited]:
+ if !ok {
+ return ErrHandleClose
+ }
+ // If the expected notification is hcsNotificationSystemExited which of the two selects
+ // chosen is random. Return the raw error if hcsNotificationSystemExited is expected
+ if channels[hcsNotificationSystemExited] == expectedChannel {
+ return err
+ }
+ return ErrUnexpectedContainerExit
+ case _, ok := <-channels[hcsNotificationServiceDisconnect]:
+ if !ok {
+ return ErrHandleClose
+ }
+ // hcsNotificationServiceDisconnect should never be an expected notification
+ // it does not need the same handling as hcsNotificationSystemExited
+ return ErrUnexpectedProcessAbort
+ case <-c:
+ return ErrTimeout
+ }
+ return nil
+}
diff --git a/vendor/github.com/Microsoft/hcsshim/zhcsshim.go b/vendor/github.com/Microsoft/hcsshim/zhcsshim.go
new file mode 100644
index 0000000..5d1a851
--- /dev/null
+++ b/vendor/github.com/Microsoft/hcsshim/zhcsshim.go
@@ -0,0 +1,1042 @@
+// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT
+
+package hcsshim
+
+import (
+ "syscall"
+ "unsafe"
+
+ "github.com/Microsoft/go-winio"
+ "golang.org/x/sys/windows"
+)
+
+var _ unsafe.Pointer
+
+// Do the interface allocations only once for common
+// Errno values.
+const (
+ errnoERROR_IO_PENDING = 997
+)
+
+var (
+ errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
+)
+
+// errnoErr returns common boxed Errno values, to prevent
+// allocations at runtime.
+func errnoErr(e syscall.Errno) error {
+ switch e {
+ case 0:
+ return nil
+ case errnoERROR_IO_PENDING:
+ return errERROR_IO_PENDING
+ }
+ // TODO: add more here, after collecting data on the common
+ // error values see on Windows. (perhaps when running
+ // all.bat?)
+ return e
+}
+
+var (
+ modole32 = windows.NewLazySystemDLL("ole32.dll")
+ modiphlpapi = windows.NewLazySystemDLL("iphlpapi.dll")
+ modvmcompute = windows.NewLazySystemDLL("vmcompute.dll")
+
+ procCoTaskMemFree = modole32.NewProc("CoTaskMemFree")
+ procSetCurrentThreadCompartmentId = modiphlpapi.NewProc("SetCurrentThreadCompartmentId")
+ procActivateLayer = modvmcompute.NewProc("ActivateLayer")
+ procCopyLayer = modvmcompute.NewProc("CopyLayer")
+ procCreateLayer = modvmcompute.NewProc("CreateLayer")
+ procCreateSandboxLayer = modvmcompute.NewProc("CreateSandboxLayer")
+ procExpandSandboxSize = modvmcompute.NewProc("ExpandSandboxSize")
+ procDeactivateLayer = modvmcompute.NewProc("DeactivateLayer")
+ procDestroyLayer = modvmcompute.NewProc("DestroyLayer")
+ procExportLayer = modvmcompute.NewProc("ExportLayer")
+ procGetLayerMountPath = modvmcompute.NewProc("GetLayerMountPath")
+ procGetBaseImages = modvmcompute.NewProc("GetBaseImages")
+ procImportLayer = modvmcompute.NewProc("ImportLayer")
+ procLayerExists = modvmcompute.NewProc("LayerExists")
+ procNameToGuid = modvmcompute.NewProc("NameToGuid")
+ procPrepareLayer = modvmcompute.NewProc("PrepareLayer")
+ procUnprepareLayer = modvmcompute.NewProc("UnprepareLayer")
+ procProcessBaseImage = modvmcompute.NewProc("ProcessBaseImage")
+ procProcessUtilityImage = modvmcompute.NewProc("ProcessUtilityImage")
+ procImportLayerBegin = modvmcompute.NewProc("ImportLayerBegin")
+ procImportLayerNext = modvmcompute.NewProc("ImportLayerNext")
+ procImportLayerWrite = modvmcompute.NewProc("ImportLayerWrite")
+ procImportLayerEnd = modvmcompute.NewProc("ImportLayerEnd")
+ procExportLayerBegin = modvmcompute.NewProc("ExportLayerBegin")
+ procExportLayerNext = modvmcompute.NewProc("ExportLayerNext")
+ procExportLayerRead = modvmcompute.NewProc("ExportLayerRead")
+ procExportLayerEnd = modvmcompute.NewProc("ExportLayerEnd")
+ procHcsEnumerateComputeSystems = modvmcompute.NewProc("HcsEnumerateComputeSystems")
+ procHcsCreateComputeSystem = modvmcompute.NewProc("HcsCreateComputeSystem")
+ procHcsOpenComputeSystem = modvmcompute.NewProc("HcsOpenComputeSystem")
+ procHcsCloseComputeSystem = modvmcompute.NewProc("HcsCloseComputeSystem")
+ procHcsStartComputeSystem = modvmcompute.NewProc("HcsStartComputeSystem")
+ procHcsShutdownComputeSystem = modvmcompute.NewProc("HcsShutdownComputeSystem")
+ procHcsTerminateComputeSystem = modvmcompute.NewProc("HcsTerminateComputeSystem")
+ procHcsPauseComputeSystem = modvmcompute.NewProc("HcsPauseComputeSystem")
+ procHcsResumeComputeSystem = modvmcompute.NewProc("HcsResumeComputeSystem")
+ procHcsGetComputeSystemProperties = modvmcompute.NewProc("HcsGetComputeSystemProperties")
+ procHcsModifyComputeSystem = modvmcompute.NewProc("HcsModifyComputeSystem")
+ procHcsRegisterComputeSystemCallback = modvmcompute.NewProc("HcsRegisterComputeSystemCallback")
+ procHcsUnregisterComputeSystemCallback = modvmcompute.NewProc("HcsUnregisterComputeSystemCallback")
+ procHcsCreateProcess = modvmcompute.NewProc("HcsCreateProcess")
+ procHcsOpenProcess = modvmcompute.NewProc("HcsOpenProcess")
+ procHcsCloseProcess = modvmcompute.NewProc("HcsCloseProcess")
+ procHcsTerminateProcess = modvmcompute.NewProc("HcsTerminateProcess")
+ procHcsGetProcessInfo = modvmcompute.NewProc("HcsGetProcessInfo")
+ procHcsGetProcessProperties = modvmcompute.NewProc("HcsGetProcessProperties")
+ procHcsModifyProcess = modvmcompute.NewProc("HcsModifyProcess")
+ procHcsGetServiceProperties = modvmcompute.NewProc("HcsGetServiceProperties")
+ procHcsRegisterProcessCallback = modvmcompute.NewProc("HcsRegisterProcessCallback")
+ procHcsUnregisterProcessCallback = modvmcompute.NewProc("HcsUnregisterProcessCallback")
+ procHcsModifyServiceSettings = modvmcompute.NewProc("HcsModifyServiceSettings")
+ procHNSCall = modvmcompute.NewProc("HNSCall")
+)
+
+func coTaskMemFree(buffer unsafe.Pointer) {
+ syscall.Syscall(procCoTaskMemFree.Addr(), 1, uintptr(buffer), 0, 0)
+ return
+}
+
+func SetCurrentThreadCompartmentId(compartmentId uint32) (hr error) {
+ r0, _, _ := syscall.Syscall(procSetCurrentThreadCompartmentId.Addr(), 1, uintptr(compartmentId), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func activateLayer(info *driverInfo, id string) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _activateLayer(info, _p0)
+}
+
+func _activateLayer(info *driverInfo, id *uint16) (hr error) {
+ if hr = procActivateLayer.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procActivateLayer.Addr(), 2, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func copyLayer(info *driverInfo, srcId string, dstId string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(srcId)
+ if hr != nil {
+ return
+ }
+ var _p1 *uint16
+ _p1, hr = syscall.UTF16PtrFromString(dstId)
+ if hr != nil {
+ return
+ }
+ return _copyLayer(info, _p0, _p1, descriptors)
+}
+
+func _copyLayer(info *driverInfo, srcId *uint16, dstId *uint16, descriptors []WC_LAYER_DESCRIPTOR) (hr error) {
+ var _p2 *WC_LAYER_DESCRIPTOR
+ if len(descriptors) > 0 {
+ _p2 = &descriptors[0]
+ }
+ if hr = procCopyLayer.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procCopyLayer.Addr(), 5, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(srcId)), uintptr(unsafe.Pointer(dstId)), uintptr(unsafe.Pointer(_p2)), uintptr(len(descriptors)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func createLayer(info *driverInfo, id string, parent string) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ var _p1 *uint16
+ _p1, hr = syscall.UTF16PtrFromString(parent)
+ if hr != nil {
+ return
+ }
+ return _createLayer(info, _p0, _p1)
+}
+
+func _createLayer(info *driverInfo, id *uint16, parent *uint16) (hr error) {
+ if hr = procCreateLayer.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procCreateLayer.Addr(), 3, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(parent)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func createSandboxLayer(info *driverInfo, id string, parent string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ var _p1 *uint16
+ _p1, hr = syscall.UTF16PtrFromString(parent)
+ if hr != nil {
+ return
+ }
+ return _createSandboxLayer(info, _p0, _p1, descriptors)
+}
+
+func _createSandboxLayer(info *driverInfo, id *uint16, parent *uint16, descriptors []WC_LAYER_DESCRIPTOR) (hr error) {
+ var _p2 *WC_LAYER_DESCRIPTOR
+ if len(descriptors) > 0 {
+ _p2 = &descriptors[0]
+ }
+ if hr = procCreateSandboxLayer.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procCreateSandboxLayer.Addr(), 5, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(parent)), uintptr(unsafe.Pointer(_p2)), uintptr(len(descriptors)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func expandSandboxSize(info *driverInfo, id string, size uint64) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _expandSandboxSize(info, _p0, size)
+}
+
+func _expandSandboxSize(info *driverInfo, id *uint16, size uint64) (hr error) {
+ if hr = procExpandSandboxSize.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procExpandSandboxSize.Addr(), 3, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(size))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func deactivateLayer(info *driverInfo, id string) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _deactivateLayer(info, _p0)
+}
+
+func _deactivateLayer(info *driverInfo, id *uint16) (hr error) {
+ if hr = procDeactivateLayer.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procDeactivateLayer.Addr(), 2, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func destroyLayer(info *driverInfo, id string) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _destroyLayer(info, _p0)
+}
+
+func _destroyLayer(info *driverInfo, id *uint16) (hr error) {
+ if hr = procDestroyLayer.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procDestroyLayer.Addr(), 2, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func exportLayer(info *driverInfo, id string, path string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ var _p1 *uint16
+ _p1, hr = syscall.UTF16PtrFromString(path)
+ if hr != nil {
+ return
+ }
+ return _exportLayer(info, _p0, _p1, descriptors)
+}
+
+func _exportLayer(info *driverInfo, id *uint16, path *uint16, descriptors []WC_LAYER_DESCRIPTOR) (hr error) {
+ var _p2 *WC_LAYER_DESCRIPTOR
+ if len(descriptors) > 0 {
+ _p2 = &descriptors[0]
+ }
+ if hr = procExportLayer.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procExportLayer.Addr(), 5, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(_p2)), uintptr(len(descriptors)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func getLayerMountPath(info *driverInfo, id string, length *uintptr, buffer *uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _getLayerMountPath(info, _p0, length, buffer)
+}
+
+func _getLayerMountPath(info *driverInfo, id *uint16, length *uintptr, buffer *uint16) (hr error) {
+ if hr = procGetLayerMountPath.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procGetLayerMountPath.Addr(), 4, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(length)), uintptr(unsafe.Pointer(buffer)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func getBaseImages(buffer **uint16) (hr error) {
+ if hr = procGetBaseImages.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procGetBaseImages.Addr(), 1, uintptr(unsafe.Pointer(buffer)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func importLayer(info *driverInfo, id string, path string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ var _p1 *uint16
+ _p1, hr = syscall.UTF16PtrFromString(path)
+ if hr != nil {
+ return
+ }
+ return _importLayer(info, _p0, _p1, descriptors)
+}
+
+func _importLayer(info *driverInfo, id *uint16, path *uint16, descriptors []WC_LAYER_DESCRIPTOR) (hr error) {
+ var _p2 *WC_LAYER_DESCRIPTOR
+ if len(descriptors) > 0 {
+ _p2 = &descriptors[0]
+ }
+ if hr = procImportLayer.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procImportLayer.Addr(), 5, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(_p2)), uintptr(len(descriptors)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func layerExists(info *driverInfo, id string, exists *uint32) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _layerExists(info, _p0, exists)
+}
+
+func _layerExists(info *driverInfo, id *uint16, exists *uint32) (hr error) {
+ if hr = procLayerExists.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procLayerExists.Addr(), 3, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(exists)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func nameToGuid(name string, guid *GUID) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(name)
+ if hr != nil {
+ return
+ }
+ return _nameToGuid(_p0, guid)
+}
+
+func _nameToGuid(name *uint16, guid *GUID) (hr error) {
+ if hr = procNameToGuid.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procNameToGuid.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(guid)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func prepareLayer(info *driverInfo, id string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _prepareLayer(info, _p0, descriptors)
+}
+
+func _prepareLayer(info *driverInfo, id *uint16, descriptors []WC_LAYER_DESCRIPTOR) (hr error) {
+ var _p1 *WC_LAYER_DESCRIPTOR
+ if len(descriptors) > 0 {
+ _p1 = &descriptors[0]
+ }
+ if hr = procPrepareLayer.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procPrepareLayer.Addr(), 4, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(_p1)), uintptr(len(descriptors)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func unprepareLayer(info *driverInfo, id string) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _unprepareLayer(info, _p0)
+}
+
+func _unprepareLayer(info *driverInfo, id *uint16) (hr error) {
+ if hr = procUnprepareLayer.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procUnprepareLayer.Addr(), 2, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func processBaseImage(path string) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(path)
+ if hr != nil {
+ return
+ }
+ return _processBaseImage(_p0)
+}
+
+func _processBaseImage(path *uint16) (hr error) {
+ if hr = procProcessBaseImage.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procProcessBaseImage.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func processUtilityImage(path string) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(path)
+ if hr != nil {
+ return
+ }
+ return _processUtilityImage(_p0)
+}
+
+func _processUtilityImage(path *uint16) (hr error) {
+ if hr = procProcessUtilityImage.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procProcessUtilityImage.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func importLayerBegin(info *driverInfo, id string, descriptors []WC_LAYER_DESCRIPTOR, context *uintptr) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _importLayerBegin(info, _p0, descriptors, context)
+}
+
+func _importLayerBegin(info *driverInfo, id *uint16, descriptors []WC_LAYER_DESCRIPTOR, context *uintptr) (hr error) {
+ var _p1 *WC_LAYER_DESCRIPTOR
+ if len(descriptors) > 0 {
+ _p1 = &descriptors[0]
+ }
+ if hr = procImportLayerBegin.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procImportLayerBegin.Addr(), 5, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(_p1)), uintptr(len(descriptors)), uintptr(unsafe.Pointer(context)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func importLayerNext(context uintptr, fileName string, fileInfo *winio.FileBasicInfo) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(fileName)
+ if hr != nil {
+ return
+ }
+ return _importLayerNext(context, _p0, fileInfo)
+}
+
+func _importLayerNext(context uintptr, fileName *uint16, fileInfo *winio.FileBasicInfo) (hr error) {
+ if hr = procImportLayerNext.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procImportLayerNext.Addr(), 3, uintptr(context), uintptr(unsafe.Pointer(fileName)), uintptr(unsafe.Pointer(fileInfo)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func importLayerWrite(context uintptr, buffer []byte) (hr error) {
+ var _p0 *byte
+ if len(buffer) > 0 {
+ _p0 = &buffer[0]
+ }
+ if hr = procImportLayerWrite.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procImportLayerWrite.Addr(), 3, uintptr(context), uintptr(unsafe.Pointer(_p0)), uintptr(len(buffer)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func importLayerEnd(context uintptr) (hr error) {
+ if hr = procImportLayerEnd.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procImportLayerEnd.Addr(), 1, uintptr(context), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func exportLayerBegin(info *driverInfo, id string, descriptors []WC_LAYER_DESCRIPTOR, context *uintptr) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _exportLayerBegin(info, _p0, descriptors, context)
+}
+
+func _exportLayerBegin(info *driverInfo, id *uint16, descriptors []WC_LAYER_DESCRIPTOR, context *uintptr) (hr error) {
+ var _p1 *WC_LAYER_DESCRIPTOR
+ if len(descriptors) > 0 {
+ _p1 = &descriptors[0]
+ }
+ if hr = procExportLayerBegin.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procExportLayerBegin.Addr(), 5, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(_p1)), uintptr(len(descriptors)), uintptr(unsafe.Pointer(context)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func exportLayerNext(context uintptr, fileName **uint16, fileInfo *winio.FileBasicInfo, fileSize *int64, deleted *uint32) (hr error) {
+ if hr = procExportLayerNext.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procExportLayerNext.Addr(), 5, uintptr(context), uintptr(unsafe.Pointer(fileName)), uintptr(unsafe.Pointer(fileInfo)), uintptr(unsafe.Pointer(fileSize)), uintptr(unsafe.Pointer(deleted)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func exportLayerRead(context uintptr, buffer []byte, bytesRead *uint32) (hr error) {
+ var _p0 *byte
+ if len(buffer) > 0 {
+ _p0 = &buffer[0]
+ }
+ if hr = procExportLayerRead.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procExportLayerRead.Addr(), 4, uintptr(context), uintptr(unsafe.Pointer(_p0)), uintptr(len(buffer)), uintptr(unsafe.Pointer(bytesRead)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func exportLayerEnd(context uintptr) (hr error) {
+ if hr = procExportLayerEnd.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procExportLayerEnd.Addr(), 1, uintptr(context), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsEnumerateComputeSystems(query string, computeSystems **uint16, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(query)
+ if hr != nil {
+ return
+ }
+ return _hcsEnumerateComputeSystems(_p0, computeSystems, result)
+}
+
+func _hcsEnumerateComputeSystems(query *uint16, computeSystems **uint16, result **uint16) (hr error) {
+ if hr = procHcsEnumerateComputeSystems.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsEnumerateComputeSystems.Addr(), 3, uintptr(unsafe.Pointer(query)), uintptr(unsafe.Pointer(computeSystems)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsCreateComputeSystem(id string, configuration string, identity syscall.Handle, computeSystem *hcsSystem, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ var _p1 *uint16
+ _p1, hr = syscall.UTF16PtrFromString(configuration)
+ if hr != nil {
+ return
+ }
+ return _hcsCreateComputeSystem(_p0, _p1, identity, computeSystem, result)
+}
+
+func _hcsCreateComputeSystem(id *uint16, configuration *uint16, identity syscall.Handle, computeSystem *hcsSystem, result **uint16) (hr error) {
+ if hr = procHcsCreateComputeSystem.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procHcsCreateComputeSystem.Addr(), 5, uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(configuration)), uintptr(identity), uintptr(unsafe.Pointer(computeSystem)), uintptr(unsafe.Pointer(result)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsOpenComputeSystem(id string, computeSystem *hcsSystem, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(id)
+ if hr != nil {
+ return
+ }
+ return _hcsOpenComputeSystem(_p0, computeSystem, result)
+}
+
+func _hcsOpenComputeSystem(id *uint16, computeSystem *hcsSystem, result **uint16) (hr error) {
+ if hr = procHcsOpenComputeSystem.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsOpenComputeSystem.Addr(), 3, uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(computeSystem)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsCloseComputeSystem(computeSystem hcsSystem) (hr error) {
+ if hr = procHcsCloseComputeSystem.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsCloseComputeSystem.Addr(), 1, uintptr(computeSystem), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsStartComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(options)
+ if hr != nil {
+ return
+ }
+ return _hcsStartComputeSystem(computeSystem, _p0, result)
+}
+
+func _hcsStartComputeSystem(computeSystem hcsSystem, options *uint16, result **uint16) (hr error) {
+ if hr = procHcsStartComputeSystem.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsStartComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsShutdownComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(options)
+ if hr != nil {
+ return
+ }
+ return _hcsShutdownComputeSystem(computeSystem, _p0, result)
+}
+
+func _hcsShutdownComputeSystem(computeSystem hcsSystem, options *uint16, result **uint16) (hr error) {
+ if hr = procHcsShutdownComputeSystem.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsShutdownComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsTerminateComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(options)
+ if hr != nil {
+ return
+ }
+ return _hcsTerminateComputeSystem(computeSystem, _p0, result)
+}
+
+func _hcsTerminateComputeSystem(computeSystem hcsSystem, options *uint16, result **uint16) (hr error) {
+ if hr = procHcsTerminateComputeSystem.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsTerminateComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsPauseComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(options)
+ if hr != nil {
+ return
+ }
+ return _hcsPauseComputeSystem(computeSystem, _p0, result)
+}
+
+func _hcsPauseComputeSystem(computeSystem hcsSystem, options *uint16, result **uint16) (hr error) {
+ if hr = procHcsPauseComputeSystem.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsPauseComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsResumeComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(options)
+ if hr != nil {
+ return
+ }
+ return _hcsResumeComputeSystem(computeSystem, _p0, result)
+}
+
+func _hcsResumeComputeSystem(computeSystem hcsSystem, options *uint16, result **uint16) (hr error) {
+ if hr = procHcsResumeComputeSystem.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsResumeComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsGetComputeSystemProperties(computeSystem hcsSystem, propertyQuery string, properties **uint16, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(propertyQuery)
+ if hr != nil {
+ return
+ }
+ return _hcsGetComputeSystemProperties(computeSystem, _p0, properties, result)
+}
+
+func _hcsGetComputeSystemProperties(computeSystem hcsSystem, propertyQuery *uint16, properties **uint16, result **uint16) (hr error) {
+ if hr = procHcsGetComputeSystemProperties.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procHcsGetComputeSystemProperties.Addr(), 4, uintptr(computeSystem), uintptr(unsafe.Pointer(propertyQuery)), uintptr(unsafe.Pointer(properties)), uintptr(unsafe.Pointer(result)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsModifyComputeSystem(computeSystem hcsSystem, configuration string, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(configuration)
+ if hr != nil {
+ return
+ }
+ return _hcsModifyComputeSystem(computeSystem, _p0, result)
+}
+
+func _hcsModifyComputeSystem(computeSystem hcsSystem, configuration *uint16, result **uint16) (hr error) {
+ if hr = procHcsModifyComputeSystem.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsModifyComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(configuration)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsRegisterComputeSystemCallback(computeSystem hcsSystem, callback uintptr, context uintptr, callbackHandle *hcsCallback) (hr error) {
+ if hr = procHcsRegisterComputeSystemCallback.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procHcsRegisterComputeSystemCallback.Addr(), 4, uintptr(computeSystem), uintptr(callback), uintptr(context), uintptr(unsafe.Pointer(callbackHandle)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsUnregisterComputeSystemCallback(callbackHandle hcsCallback) (hr error) {
+ if hr = procHcsUnregisterComputeSystemCallback.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsUnregisterComputeSystemCallback.Addr(), 1, uintptr(callbackHandle), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsCreateProcess(computeSystem hcsSystem, processParameters string, processInformation *hcsProcessInformation, process *hcsProcess, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(processParameters)
+ if hr != nil {
+ return
+ }
+ return _hcsCreateProcess(computeSystem, _p0, processInformation, process, result)
+}
+
+func _hcsCreateProcess(computeSystem hcsSystem, processParameters *uint16, processInformation *hcsProcessInformation, process *hcsProcess, result **uint16) (hr error) {
+ if hr = procHcsCreateProcess.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procHcsCreateProcess.Addr(), 5, uintptr(computeSystem), uintptr(unsafe.Pointer(processParameters)), uintptr(unsafe.Pointer(processInformation)), uintptr(unsafe.Pointer(process)), uintptr(unsafe.Pointer(result)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsOpenProcess(computeSystem hcsSystem, pid uint32, process *hcsProcess, result **uint16) (hr error) {
+ if hr = procHcsOpenProcess.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procHcsOpenProcess.Addr(), 4, uintptr(computeSystem), uintptr(pid), uintptr(unsafe.Pointer(process)), uintptr(unsafe.Pointer(result)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsCloseProcess(process hcsProcess) (hr error) {
+ if hr = procHcsCloseProcess.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsCloseProcess.Addr(), 1, uintptr(process), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsTerminateProcess(process hcsProcess, result **uint16) (hr error) {
+ if hr = procHcsTerminateProcess.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsTerminateProcess.Addr(), 2, uintptr(process), uintptr(unsafe.Pointer(result)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsGetProcessInfo(process hcsProcess, processInformation *hcsProcessInformation, result **uint16) (hr error) {
+ if hr = procHcsGetProcessInfo.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsGetProcessInfo.Addr(), 3, uintptr(process), uintptr(unsafe.Pointer(processInformation)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsGetProcessProperties(process hcsProcess, processProperties **uint16, result **uint16) (hr error) {
+ if hr = procHcsGetProcessProperties.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsGetProcessProperties.Addr(), 3, uintptr(process), uintptr(unsafe.Pointer(processProperties)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsModifyProcess(process hcsProcess, settings string, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(settings)
+ if hr != nil {
+ return
+ }
+ return _hcsModifyProcess(process, _p0, result)
+}
+
+func _hcsModifyProcess(process hcsProcess, settings *uint16, result **uint16) (hr error) {
+ if hr = procHcsModifyProcess.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsModifyProcess.Addr(), 3, uintptr(process), uintptr(unsafe.Pointer(settings)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsGetServiceProperties(propertyQuery string, properties **uint16, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(propertyQuery)
+ if hr != nil {
+ return
+ }
+ return _hcsGetServiceProperties(_p0, properties, result)
+}
+
+func _hcsGetServiceProperties(propertyQuery *uint16, properties **uint16, result **uint16) (hr error) {
+ if hr = procHcsGetServiceProperties.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsGetServiceProperties.Addr(), 3, uintptr(unsafe.Pointer(propertyQuery)), uintptr(unsafe.Pointer(properties)), uintptr(unsafe.Pointer(result)))
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsRegisterProcessCallback(process hcsProcess, callback uintptr, context uintptr, callbackHandle *hcsCallback) (hr error) {
+ if hr = procHcsRegisterProcessCallback.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procHcsRegisterProcessCallback.Addr(), 4, uintptr(process), uintptr(callback), uintptr(context), uintptr(unsafe.Pointer(callbackHandle)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsUnregisterProcessCallback(callbackHandle hcsCallback) (hr error) {
+ if hr = procHcsUnregisterProcessCallback.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsUnregisterProcessCallback.Addr(), 1, uintptr(callbackHandle), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func hcsModifyServiceSettings(settings string, result **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(settings)
+ if hr != nil {
+ return
+ }
+ return _hcsModifyServiceSettings(_p0, result)
+}
+
+func _hcsModifyServiceSettings(settings *uint16, result **uint16) (hr error) {
+ if hr = procHcsModifyServiceSettings.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall(procHcsModifyServiceSettings.Addr(), 2, uintptr(unsafe.Pointer(settings)), uintptr(unsafe.Pointer(result)), 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
+
+func _hnsCall(method string, path string, object string, response **uint16) (hr error) {
+ var _p0 *uint16
+ _p0, hr = syscall.UTF16PtrFromString(method)
+ if hr != nil {
+ return
+ }
+ var _p1 *uint16
+ _p1, hr = syscall.UTF16PtrFromString(path)
+ if hr != nil {
+ return
+ }
+ var _p2 *uint16
+ _p2, hr = syscall.UTF16PtrFromString(object)
+ if hr != nil {
+ return
+ }
+ return __hnsCall(_p0, _p1, _p2, response)
+}
+
+func __hnsCall(method *uint16, path *uint16, object *uint16, response **uint16) (hr error) {
+ if hr = procHNSCall.Find(); hr != nil {
+ return
+ }
+ r0, _, _ := syscall.Syscall6(procHNSCall.Addr(), 4, uintptr(unsafe.Pointer(method)), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(object)), uintptr(unsafe.Pointer(response)), 0, 0)
+ if int32(r0) < 0 {
+ hr = syscall.Errno(win32FromHresult(r0))
+ }
+ return
+}
diff --git a/vendor/github.com/Nvveen/Gotty/LICENSE b/vendor/github.com/Nvveen/Gotty/LICENSE
new file mode 100644
index 0000000..0b71c97
--- /dev/null
+++ b/vendor/github.com/Nvveen/Gotty/LICENSE
@@ -0,0 +1,26 @@
+Copyright (c) 2012, Neal van Veen (nealvanveen@gmail.com)
+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.
+
+The views and conclusions contained in the software and documentation are those
+of the authors and should not be interpreted as representing official policies,
+either expressed or implied, of the FreeBSD Project.
diff --git a/vendor/github.com/Nvveen/Gotty/README b/vendor/github.com/Nvveen/Gotty/README
new file mode 100644
index 0000000..a6b0d9a
--- /dev/null
+++ b/vendor/github.com/Nvveen/Gotty/README
@@ -0,0 +1,5 @@
+Gotty is a library written in Go that determines and reads termcap database
+files to produce an interface for interacting with the capabilities of a
+terminal.
+See the godoc documentation or the source code for more information about
+function usage.
diff --git a/vendor/github.com/Nvveen/Gotty/attributes.go b/vendor/github.com/Nvveen/Gotty/attributes.go
new file mode 100644
index 0000000..a4c005f
--- /dev/null
+++ b/vendor/github.com/Nvveen/Gotty/attributes.go
@@ -0,0 +1,514 @@
+// Copyright 2012 Neal van Veen. All rights reserved.
+// Usage of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package gotty
+
+// Boolean capabilities
+var BoolAttr = [...]string{
+ "auto_left_margin", "bw",
+ "auto_right_margin", "am",
+ "no_esc_ctlc", "xsb",
+ "ceol_standout_glitch", "xhp",
+ "eat_newline_glitch", "xenl",
+ "erase_overstrike", "eo",
+ "generic_type", "gn",
+ "hard_copy", "hc",
+ "has_meta_key", "km",
+ "has_status_line", "hs",
+ "insert_null_glitch", "in",
+ "memory_above", "da",
+ "memory_below", "db",
+ "move_insert_mode", "mir",
+ "move_standout_mode", "msgr",
+ "over_strike", "os",
+ "status_line_esc_ok", "eslok",
+ "dest_tabs_magic_smso", "xt",
+ "tilde_glitch", "hz",
+ "transparent_underline", "ul",
+ "xon_xoff", "nxon",
+ "needs_xon_xoff", "nxon",
+ "prtr_silent", "mc5i",
+ "hard_cursor", "chts",
+ "non_rev_rmcup", "nrrmc",
+ "no_pad_char", "npc",
+ "non_dest_scroll_region", "ndscr",
+ "can_change", "ccc",
+ "back_color_erase", "bce",
+ "hue_lightness_saturation", "hls",
+ "col_addr_glitch", "xhpa",
+ "cr_cancels_micro_mode", "crxm",
+ "has_print_wheel", "daisy",
+ "row_addr_glitch", "xvpa",
+ "semi_auto_right_margin", "sam",
+ "cpi_changes_res", "cpix",
+ "lpi_changes_res", "lpix",
+ "backspaces_with_bs", "",
+ "crt_no_scrolling", "",
+ "no_correctly_working_cr", "",
+ "gnu_has_meta_key", "",
+ "linefeed_is_newline", "",
+ "has_hardware_tabs", "",
+ "return_does_clr_eol", "",
+}
+
+// Numerical capabilities
+var NumAttr = [...]string{
+ "columns", "cols",
+ "init_tabs", "it",
+ "lines", "lines",
+ "lines_of_memory", "lm",
+ "magic_cookie_glitch", "xmc",
+ "padding_baud_rate", "pb",
+ "virtual_terminal", "vt",
+ "width_status_line", "wsl",
+ "num_labels", "nlab",
+ "label_height", "lh",
+ "label_width", "lw",
+ "max_attributes", "ma",
+ "maximum_windows", "wnum",
+ "max_colors", "colors",
+ "max_pairs", "pairs",
+ "no_color_video", "ncv",
+ "buffer_capacity", "bufsz",
+ "dot_vert_spacing", "spinv",
+ "dot_horz_spacing", "spinh",
+ "max_micro_address", "maddr",
+ "max_micro_jump", "mjump",
+ "micro_col_size", "mcs",
+ "micro_line_size", "mls",
+ "number_of_pins", "npins",
+ "output_res_char", "orc",
+ "output_res_line", "orl",
+ "output_res_horz_inch", "orhi",
+ "output_res_vert_inch", "orvi",
+ "print_rate", "cps",
+ "wide_char_size", "widcs",
+ "buttons", "btns",
+ "bit_image_entwining", "bitwin",
+ "bit_image_type", "bitype",
+ "magic_cookie_glitch_ul", "",
+ "carriage_return_delay", "",
+ "new_line_delay", "",
+ "backspace_delay", "",
+ "horizontal_tab_delay", "",
+ "number_of_function_keys", "",
+}
+
+// String capabilities
+var StrAttr = [...]string{
+ "back_tab", "cbt",
+ "bell", "bel",
+ "carriage_return", "cr",
+ "change_scroll_region", "csr",
+ "clear_all_tabs", "tbc",
+ "clear_screen", "clear",
+ "clr_eol", "el",
+ "clr_eos", "ed",
+ "column_address", "hpa",
+ "command_character", "cmdch",
+ "cursor_address", "cup",
+ "cursor_down", "cud1",
+ "cursor_home", "home",
+ "cursor_invisible", "civis",
+ "cursor_left", "cub1",
+ "cursor_mem_address", "mrcup",
+ "cursor_normal", "cnorm",
+ "cursor_right", "cuf1",
+ "cursor_to_ll", "ll",
+ "cursor_up", "cuu1",
+ "cursor_visible", "cvvis",
+ "delete_character", "dch1",
+ "delete_line", "dl1",
+ "dis_status_line", "dsl",
+ "down_half_line", "hd",
+ "enter_alt_charset_mode", "smacs",
+ "enter_blink_mode", "blink",
+ "enter_bold_mode", "bold",
+ "enter_ca_mode", "smcup",
+ "enter_delete_mode", "smdc",
+ "enter_dim_mode", "dim",
+ "enter_insert_mode", "smir",
+ "enter_secure_mode", "invis",
+ "enter_protected_mode", "prot",
+ "enter_reverse_mode", "rev",
+ "enter_standout_mode", "smso",
+ "enter_underline_mode", "smul",
+ "erase_chars", "ech",
+ "exit_alt_charset_mode", "rmacs",
+ "exit_attribute_mode", "sgr0",
+ "exit_ca_mode", "rmcup",
+ "exit_delete_mode", "rmdc",
+ "exit_insert_mode", "rmir",
+ "exit_standout_mode", "rmso",
+ "exit_underline_mode", "rmul",
+ "flash_screen", "flash",
+ "form_feed", "ff",
+ "from_status_line", "fsl",
+ "init_1string", "is1",
+ "init_2string", "is2",
+ "init_3string", "is3",
+ "init_file", "if",
+ "insert_character", "ich1",
+ "insert_line", "il1",
+ "insert_padding", "ip",
+ "key_backspace", "kbs",
+ "key_catab", "ktbc",
+ "key_clear", "kclr",
+ "key_ctab", "kctab",
+ "key_dc", "kdch1",
+ "key_dl", "kdl1",
+ "key_down", "kcud1",
+ "key_eic", "krmir",
+ "key_eol", "kel",
+ "key_eos", "ked",
+ "key_f0", "kf0",
+ "key_f1", "kf1",
+ "key_f10", "kf10",
+ "key_f2", "kf2",
+ "key_f3", "kf3",
+ "key_f4", "kf4",
+ "key_f5", "kf5",
+ "key_f6", "kf6",
+ "key_f7", "kf7",
+ "key_f8", "kf8",
+ "key_f9", "kf9",
+ "key_home", "khome",
+ "key_ic", "kich1",
+ "key_il", "kil1",
+ "key_left", "kcub1",
+ "key_ll", "kll",
+ "key_npage", "knp",
+ "key_ppage", "kpp",
+ "key_right", "kcuf1",
+ "key_sf", "kind",
+ "key_sr", "kri",
+ "key_stab", "khts",
+ "key_up", "kcuu1",
+ "keypad_local", "rmkx",
+ "keypad_xmit", "smkx",
+ "lab_f0", "lf0",
+ "lab_f1", "lf1",
+ "lab_f10", "lf10",
+ "lab_f2", "lf2",
+ "lab_f3", "lf3",
+ "lab_f4", "lf4",
+ "lab_f5", "lf5",
+ "lab_f6", "lf6",
+ "lab_f7", "lf7",
+ "lab_f8", "lf8",
+ "lab_f9", "lf9",
+ "meta_off", "rmm",
+ "meta_on", "smm",
+ "newline", "_glitch",
+ "pad_char", "npc",
+ "parm_dch", "dch",
+ "parm_delete_line", "dl",
+ "parm_down_cursor", "cud",
+ "parm_ich", "ich",
+ "parm_index", "indn",
+ "parm_insert_line", "il",
+ "parm_left_cursor", "cub",
+ "parm_right_cursor", "cuf",
+ "parm_rindex", "rin",
+ "parm_up_cursor", "cuu",
+ "pkey_key", "pfkey",
+ "pkey_local", "pfloc",
+ "pkey_xmit", "pfx",
+ "print_screen", "mc0",
+ "prtr_off", "mc4",
+ "prtr_on", "mc5",
+ "repeat_char", "rep",
+ "reset_1string", "rs1",
+ "reset_2string", "rs2",
+ "reset_3string", "rs3",
+ "reset_file", "rf",
+ "restore_cursor", "rc",
+ "row_address", "mvpa",
+ "save_cursor", "row_address",
+ "scroll_forward", "ind",
+ "scroll_reverse", "ri",
+ "set_attributes", "sgr",
+ "set_tab", "hts",
+ "set_window", "wind",
+ "tab", "s_magic_smso",
+ "to_status_line", "tsl",
+ "underline_char", "uc",
+ "up_half_line", "hu",
+ "init_prog", "iprog",
+ "key_a1", "ka1",
+ "key_a3", "ka3",
+ "key_b2", "kb2",
+ "key_c1", "kc1",
+ "key_c3", "kc3",
+ "prtr_non", "mc5p",
+ "char_padding", "rmp",
+ "acs_chars", "acsc",
+ "plab_norm", "pln",
+ "key_btab", "kcbt",
+ "enter_xon_mode", "smxon",
+ "exit_xon_mode", "rmxon",
+ "enter_am_mode", "smam",
+ "exit_am_mode", "rmam",
+ "xon_character", "xonc",
+ "xoff_character", "xoffc",
+ "ena_acs", "enacs",
+ "label_on", "smln",
+ "label_off", "rmln",
+ "key_beg", "kbeg",
+ "key_cancel", "kcan",
+ "key_close", "kclo",
+ "key_command", "kcmd",
+ "key_copy", "kcpy",
+ "key_create", "kcrt",
+ "key_end", "kend",
+ "key_enter", "kent",
+ "key_exit", "kext",
+ "key_find", "kfnd",
+ "key_help", "khlp",
+ "key_mark", "kmrk",
+ "key_message", "kmsg",
+ "key_move", "kmov",
+ "key_next", "knxt",
+ "key_open", "kopn",
+ "key_options", "kopt",
+ "key_previous", "kprv",
+ "key_print", "kprt",
+ "key_redo", "krdo",
+ "key_reference", "kref",
+ "key_refresh", "krfr",
+ "key_replace", "krpl",
+ "key_restart", "krst",
+ "key_resume", "kres",
+ "key_save", "ksav",
+ "key_suspend", "kspd",
+ "key_undo", "kund",
+ "key_sbeg", "kBEG",
+ "key_scancel", "kCAN",
+ "key_scommand", "kCMD",
+ "key_scopy", "kCPY",
+ "key_screate", "kCRT",
+ "key_sdc", "kDC",
+ "key_sdl", "kDL",
+ "key_select", "kslt",
+ "key_send", "kEND",
+ "key_seol", "kEOL",
+ "key_sexit", "kEXT",
+ "key_sfind", "kFND",
+ "key_shelp", "kHLP",
+ "key_shome", "kHOM",
+ "key_sic", "kIC",
+ "key_sleft", "kLFT",
+ "key_smessage", "kMSG",
+ "key_smove", "kMOV",
+ "key_snext", "kNXT",
+ "key_soptions", "kOPT",
+ "key_sprevious", "kPRV",
+ "key_sprint", "kPRT",
+ "key_sredo", "kRDO",
+ "key_sreplace", "kRPL",
+ "key_sright", "kRIT",
+ "key_srsume", "kRES",
+ "key_ssave", "kSAV",
+ "key_ssuspend", "kSPD",
+ "key_sundo", "kUND",
+ "req_for_input", "rfi",
+ "key_f11", "kf11",
+ "key_f12", "kf12",
+ "key_f13", "kf13",
+ "key_f14", "kf14",
+ "key_f15", "kf15",
+ "key_f16", "kf16",
+ "key_f17", "kf17",
+ "key_f18", "kf18",
+ "key_f19", "kf19",
+ "key_f20", "kf20",
+ "key_f21", "kf21",
+ "key_f22", "kf22",
+ "key_f23", "kf23",
+ "key_f24", "kf24",
+ "key_f25", "kf25",
+ "key_f26", "kf26",
+ "key_f27", "kf27",
+ "key_f28", "kf28",
+ "key_f29", "kf29",
+ "key_f30", "kf30",
+ "key_f31", "kf31",
+ "key_f32", "kf32",
+ "key_f33", "kf33",
+ "key_f34", "kf34",
+ "key_f35", "kf35",
+ "key_f36", "kf36",
+ "key_f37", "kf37",
+ "key_f38", "kf38",
+ "key_f39", "kf39",
+ "key_f40", "kf40",
+ "key_f41", "kf41",
+ "key_f42", "kf42",
+ "key_f43", "kf43",
+ "key_f44", "kf44",
+ "key_f45", "kf45",
+ "key_f46", "kf46",
+ "key_f47", "kf47",
+ "key_f48", "kf48",
+ "key_f49", "kf49",
+ "key_f50", "kf50",
+ "key_f51", "kf51",
+ "key_f52", "kf52",
+ "key_f53", "kf53",
+ "key_f54", "kf54",
+ "key_f55", "kf55",
+ "key_f56", "kf56",
+ "key_f57", "kf57",
+ "key_f58", "kf58",
+ "key_f59", "kf59",
+ "key_f60", "kf60",
+ "key_f61", "kf61",
+ "key_f62", "kf62",
+ "key_f63", "kf63",
+ "clr_bol", "el1",
+ "clear_margins", "mgc",
+ "set_left_margin", "smgl",
+ "set_right_margin", "smgr",
+ "label_format", "fln",
+ "set_clock", "sclk",
+ "display_clock", "dclk",
+ "remove_clock", "rmclk",
+ "create_window", "cwin",
+ "goto_window", "wingo",
+ "hangup", "hup",
+ "dial_phone", "dial",
+ "quick_dial", "qdial",
+ "tone", "tone",
+ "pulse", "pulse",
+ "flash_hook", "hook",
+ "fixed_pause", "pause",
+ "wait_tone", "wait",
+ "user0", "u0",
+ "user1", "u1",
+ "user2", "u2",
+ "user3", "u3",
+ "user4", "u4",
+ "user5", "u5",
+ "user6", "u6",
+ "user7", "u7",
+ "user8", "u8",
+ "user9", "u9",
+ "orig_pair", "op",
+ "orig_colors", "oc",
+ "initialize_color", "initc",
+ "initialize_pair", "initp",
+ "set_color_pair", "scp",
+ "set_foreground", "setf",
+ "set_background", "setb",
+ "change_char_pitch", "cpi",
+ "change_line_pitch", "lpi",
+ "change_res_horz", "chr",
+ "change_res_vert", "cvr",
+ "define_char", "defc",
+ "enter_doublewide_mode", "swidm",
+ "enter_draft_quality", "sdrfq",
+ "enter_italics_mode", "sitm",
+ "enter_leftward_mode", "slm",
+ "enter_micro_mode", "smicm",
+ "enter_near_letter_quality", "snlq",
+ "enter_normal_quality", "snrmq",
+ "enter_shadow_mode", "sshm",
+ "enter_subscript_mode", "ssubm",
+ "enter_superscript_mode", "ssupm",
+ "enter_upward_mode", "sum",
+ "exit_doublewide_mode", "rwidm",
+ "exit_italics_mode", "ritm",
+ "exit_leftward_mode", "rlm",
+ "exit_micro_mode", "rmicm",
+ "exit_shadow_mode", "rshm",
+ "exit_subscript_mode", "rsubm",
+ "exit_superscript_mode", "rsupm",
+ "exit_upward_mode", "rum",
+ "micro_column_address", "mhpa",
+ "micro_down", "mcud1",
+ "micro_left", "mcub1",
+ "micro_right", "mcuf1",
+ "micro_row_address", "mvpa",
+ "micro_up", "mcuu1",
+ "order_of_pins", "porder",
+ "parm_down_micro", "mcud",
+ "parm_left_micro", "mcub",
+ "parm_right_micro", "mcuf",
+ "parm_up_micro", "mcuu",
+ "select_char_set", "scs",
+ "set_bottom_margin", "smgb",
+ "set_bottom_margin_parm", "smgbp",
+ "set_left_margin_parm", "smglp",
+ "set_right_margin_parm", "smgrp",
+ "set_top_margin", "smgt",
+ "set_top_margin_parm", "smgtp",
+ "start_bit_image", "sbim",
+ "start_char_set_def", "scsd",
+ "stop_bit_image", "rbim",
+ "stop_char_set_def", "rcsd",
+ "subscript_characters", "subcs",
+ "superscript_characters", "supcs",
+ "these_cause_cr", "docr",
+ "zero_motion", "zerom",
+ "char_set_names", "csnm",
+ "key_mouse", "kmous",
+ "mouse_info", "minfo",
+ "req_mouse_pos", "reqmp",
+ "get_mouse", "getm",
+ "set_a_foreground", "setaf",
+ "set_a_background", "setab",
+ "pkey_plab", "pfxl",
+ "device_type", "devt",
+ "code_set_init", "csin",
+ "set0_des_seq", "s0ds",
+ "set1_des_seq", "s1ds",
+ "set2_des_seq", "s2ds",
+ "set3_des_seq", "s3ds",
+ "set_lr_margin", "smglr",
+ "set_tb_margin", "smgtb",
+ "bit_image_repeat", "birep",
+ "bit_image_newline", "binel",
+ "bit_image_carriage_return", "bicr",
+ "color_names", "colornm",
+ "define_bit_image_region", "defbi",
+ "end_bit_image_region", "endbi",
+ "set_color_band", "setcolor",
+ "set_page_length", "slines",
+ "display_pc_char", "dispc",
+ "enter_pc_charset_mode", "smpch",
+ "exit_pc_charset_mode", "rmpch",
+ "enter_scancode_mode", "smsc",
+ "exit_scancode_mode", "rmsc",
+ "pc_term_options", "pctrm",
+ "scancode_escape", "scesc",
+ "alt_scancode_esc", "scesa",
+ "enter_horizontal_hl_mode", "ehhlm",
+ "enter_left_hl_mode", "elhlm",
+ "enter_low_hl_mode", "elohlm",
+ "enter_right_hl_mode", "erhlm",
+ "enter_top_hl_mode", "ethlm",
+ "enter_vertical_hl_mode", "evhlm",
+ "set_a_attributes", "sgr1",
+ "set_pglen_inch", "slength",
+ "termcap_init2", "",
+ "termcap_reset", "",
+ "linefeed_if_not_lf", "",
+ "backspace_if_not_bs", "",
+ "other_non_function_keys", "",
+ "arrow_key_map", "",
+ "acs_ulcorner", "",
+ "acs_llcorner", "",
+ "acs_urcorner", "",
+ "acs_lrcorner", "",
+ "acs_ltee", "",
+ "acs_rtee", "",
+ "acs_btee", "",
+ "acs_ttee", "",
+ "acs_hline", "",
+ "acs_vline", "",
+ "acs_plus", "",
+ "memory_lock", "",
+ "memory_unlock", "",
+ "box_chars_1", "",
+}
diff --git a/vendor/github.com/Nvveen/Gotty/gotty.go b/vendor/github.com/Nvveen/Gotty/gotty.go
new file mode 100644
index 0000000..c329778
--- /dev/null
+++ b/vendor/github.com/Nvveen/Gotty/gotty.go
@@ -0,0 +1,244 @@
+// Copyright 2012 Neal van Veen. All rights reserved.
+// Usage of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Gotty is a Go-package for reading and parsing the terminfo database
+package gotty
+
+// TODO add more concurrency to name lookup, look for more opportunities.
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "os"
+ "path"
+ "reflect"
+ "strings"
+ "sync"
+)
+
+// Open a terminfo file by the name given and construct a TermInfo object.
+// If something went wrong reading the terminfo database file, an error is
+// returned.
+func OpenTermInfo(termName string) (*TermInfo, error) {
+ if len(termName) == 0 {
+ return nil, errors.New("No termname given")
+ }
+ // Find the environment variables
+ if termloc := os.Getenv("TERMINFO"); len(termloc) > 0 {
+ return readTermInfo(path.Join(termloc, string(termName[0]), termName))
+ } else {
+ // Search like ncurses
+ locations := []string{}
+ if h := os.Getenv("HOME"); len(h) > 0 {
+ locations = append(locations, path.Join(h, ".terminfo"))
+ }
+ locations = append(locations,
+ "/etc/terminfo/",
+ "/lib/terminfo/",
+ "/usr/share/terminfo/")
+ for _, str := range locations {
+ term, err := readTermInfo(path.Join(str, string(termName[0]), termName))
+ if err == nil {
+ return term, nil
+ }
+ }
+ return nil, errors.New("No terminfo file(-location) found")
+ }
+}
+
+// Open a terminfo file from the environment variable containing the current
+// terminal name and construct a TermInfo object. If something went wrong
+// reading the terminfo database file, an error is returned.
+func OpenTermInfoEnv() (*TermInfo, error) {
+ termenv := os.Getenv("TERM")
+ return OpenTermInfo(termenv)
+}
+
+// Return an attribute by the name attr provided. If none can be found,
+// an error is returned.
+func (term *TermInfo) GetAttribute(attr string) (stacker, error) {
+ // Channel to store the main value in.
+ var value stacker
+ // Add a blocking WaitGroup
+ var block sync.WaitGroup
+ // Keep track of variable being written.
+ written := false
+ // Function to put into goroutine.
+ f := func(ats interface{}) {
+ var ok bool
+ var v stacker
+ // Switch on type of map to use and assign value to it.
+ switch reflect.TypeOf(ats).Elem().Kind() {
+ case reflect.Bool:
+ v, ok = ats.(map[string]bool)[attr]
+ case reflect.Int16:
+ v, ok = ats.(map[string]int16)[attr]
+ case reflect.String:
+ v, ok = ats.(map[string]string)[attr]
+ }
+ // If ok, a value is found, so we can write.
+ if ok {
+ value = v
+ written = true
+ }
+ // Goroutine is done
+ block.Done()
+ }
+ block.Add(3)
+ // Go for all 3 attribute lists.
+ go f(term.boolAttributes)
+ go f(term.numAttributes)
+ go f(term.strAttributes)
+ // Wait until every goroutine is done.
+ block.Wait()
+ // If a value has been written, return it.
+ if written {
+ return value, nil
+ }
+ // Otherwise, error.
+ return nil, fmt.Errorf("Erorr finding attribute")
+}
+
+// Return an attribute by the name attr provided. If none can be found,
+// an error is returned. A name is first converted to its termcap value.
+func (term *TermInfo) GetAttributeName(name string) (stacker, error) {
+ tc := GetTermcapName(name)
+ return term.GetAttribute(tc)
+}
+
+// A utility function that finds and returns the termcap equivalent of a
+// variable name.
+func GetTermcapName(name string) string {
+ // Termcap name
+ var tc string
+ // Blocking group
+ var wait sync.WaitGroup
+ // Function to put into a goroutine
+ f := func(attrs []string) {
+ // Find the string corresponding to the name
+ for i, s := range attrs {
+ if s == name {
+ tc = attrs[i+1]
+ }
+ }
+ // Goroutine is finished
+ wait.Done()
+ }
+ wait.Add(3)
+ // Go for all 3 attribute lists
+ go f(BoolAttr[:])
+ go f(NumAttr[:])
+ go f(StrAttr[:])
+ // Wait until every goroutine is done
+ wait.Wait()
+ // Return the termcap name
+ return tc
+}
+
+// This function takes a path to a terminfo file and reads it in binary
+// form to construct the actual TermInfo file.
+func readTermInfo(path string) (*TermInfo, error) {
+ // Open the terminfo file
+ file, err := os.Open(path)
+ defer file.Close()
+ if err != nil {
+ return nil, err
+ }
+
+ // magic, nameSize, boolSize, nrSNum, nrOffsetsStr, strSize
+ // Header is composed of the magic 0432 octal number, size of the name
+ // section, size of the boolean section, the amount of number values,
+ // the number of offsets of strings, and the size of the string section.
+ var header [6]int16
+ // Byte array is used to read in byte values
+ var byteArray []byte
+ // Short array is used to read in short values
+ var shArray []int16
+ // TermInfo object to store values
+ var term TermInfo
+
+ // Read in the header
+ err = binary.Read(file, binary.LittleEndian, &header)
+ if err != nil {
+ return nil, err
+ }
+ // If magic number isn't there or isn't correct, we have the wrong filetype
+ if header[0] != 0432 {
+ return nil, errors.New(fmt.Sprintf("Wrong filetype"))
+ }
+
+ // Read in the names
+ byteArray = make([]byte, header[1])
+ err = binary.Read(file, binary.LittleEndian, &byteArray)
+ if err != nil {
+ return nil, err
+ }
+ term.Names = strings.Split(string(byteArray), "|")
+
+ // Read in the booleans
+ byteArray = make([]byte, header[2])
+ err = binary.Read(file, binary.LittleEndian, &byteArray)
+ if err != nil {
+ return nil, err
+ }
+ term.boolAttributes = make(map[string]bool)
+ for i, b := range byteArray {
+ if b == 1 {
+ term.boolAttributes[BoolAttr[i*2+1]] = true
+ }
+ }
+ // If the number of bytes read is not even, a byte for alignment is added
+ // We know the header is an even number of bytes so only need to check the
+ // total of the names and booleans.
+ if (header[1]+header[2])%2 != 0 {
+ err = binary.Read(file, binary.LittleEndian, make([]byte, 1))
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ // Read in shorts
+ shArray = make([]int16, header[3])
+ err = binary.Read(file, binary.LittleEndian, &shArray)
+ if err != nil {
+ return nil, err
+ }
+ term.numAttributes = make(map[string]int16)
+ for i, n := range shArray {
+ if n != 0377 && n > -1 {
+ term.numAttributes[NumAttr[i*2+1]] = n
+ }
+ }
+
+ // Read the offsets into the short array
+ shArray = make([]int16, header[4])
+ err = binary.Read(file, binary.LittleEndian, &shArray)
+ if err != nil {
+ return nil, err
+ }
+ // Read the actual strings in the byte array
+ byteArray = make([]byte, header[5])
+ err = binary.Read(file, binary.LittleEndian, &byteArray)
+ if err != nil {
+ return nil, err
+ }
+ term.strAttributes = make(map[string]string)
+ // We get an offset, and then iterate until the string is null-terminated
+ for i, offset := range shArray {
+ if offset > -1 {
+ if int(offset) >= len(byteArray) {
+ return nil, errors.New("array out of bounds reading string section")
+ }
+ r := bytes.IndexByte(byteArray[offset:], 0)
+ if r == -1 {
+ return nil, errors.New("missing nul byte reading string section")
+ }
+ r += int(offset)
+ term.strAttributes[StrAttr[i*2+1]] = string(byteArray[offset:r])
+ }
+ }
+ return &term, nil
+}
diff --git a/vendor/github.com/Nvveen/Gotty/parser.go b/vendor/github.com/Nvveen/Gotty/parser.go
new file mode 100644
index 0000000..a9d5d23
--- /dev/null
+++ b/vendor/github.com/Nvveen/Gotty/parser.go
@@ -0,0 +1,362 @@
+// Copyright 2012 Neal van Veen. All rights reserved.
+// Usage of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package gotty
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+var exp = [...]string{
+ "%%",
+ "%c",
+ "%s",
+ "%p(\\d)",
+ "%P([A-z])",
+ "%g([A-z])",
+ "%'(.)'",
+ "%{([0-9]+)}",
+ "%l",
+ "%\\+|%-|%\\*|%/|%m",
+ "%&|%\\||%\\^",
+ "%=|%>|%<",
+ "%A|%O",
+ "%!|%~",
+ "%i",
+ "%(:[\\ #\\-\\+]{0,4})?(\\d+\\.\\d+|\\d+)?[doxXs]",
+ "%\\?(.*?);",
+}
+
+var regex *regexp.Regexp
+var staticVar map[byte]stacker
+
+// Parses the attribute that is received with name attr and parameters params.
+func (term *TermInfo) Parse(attr string, params ...interface{}) (string, error) {
+ // Get the attribute name first.
+ iface, err := term.GetAttribute(attr)
+ str, ok := iface.(string)
+ if err != nil {
+ return "", err
+ }
+ if !ok {
+ return str, errors.New("Only string capabilities can be parsed.")
+ }
+ // Construct the hidden parser struct so we can use a recursive stack based
+ // parser.
+ ps := &parser{}
+ // Dynamic variables only exist in this context.
+ ps.dynamicVar = make(map[byte]stacker, 26)
+ ps.parameters = make([]stacker, len(params))
+ // Convert the parameters to insert them into the parser struct.
+ for i, x := range params {
+ ps.parameters[i] = x
+ }
+ // Recursively walk and return.
+ result, err := ps.walk(str)
+ return result, err
+}
+
+// Parses the attribute that is received with name attr and parameters params.
+// Only works on full name of a capability that is given, which it uses to
+// search for the termcap name.
+func (term *TermInfo) ParseName(attr string, params ...interface{}) (string, error) {
+ tc := GetTermcapName(attr)
+ return term.Parse(tc, params)
+}
+
+// Identify each token in a stack based manner and do the actual parsing.
+func (ps *parser) walk(attr string) (string, error) {
+ // We use a buffer to get the modified string.
+ var buf bytes.Buffer
+ // Next, find and identify all tokens by their indices and strings.
+ tokens := regex.FindAllStringSubmatch(attr, -1)
+ if len(tokens) == 0 {
+ return attr, nil
+ }
+ indices := regex.FindAllStringIndex(attr, -1)
+ q := 0 // q counts the matches of one token
+ // Iterate through the string per character.
+ for i := 0; i < len(attr); i++ {
+ // If the current position is an identified token, execute the following
+ // steps.
+ if q < len(indices) && i >= indices[q][0] && i < indices[q][1] {
+ // Switch on token.
+ switch {
+ case tokens[q][0][:2] == "%%":
+ // Literal percentage character.
+ buf.WriteByte('%')
+ case tokens[q][0][:2] == "%c":
+ // Pop a character.
+ c, err := ps.st.pop()
+ if err != nil {
+ return buf.String(), err
+ }
+ buf.WriteByte(c.(byte))
+ case tokens[q][0][:2] == "%s":
+ // Pop a string.
+ str, err := ps.st.pop()
+ if err != nil {
+ return buf.String(), err
+ }
+ if _, ok := str.(string); !ok {
+ return buf.String(), errors.New("Stack head is not a string")
+ }
+ buf.WriteString(str.(string))
+ case tokens[q][0][:2] == "%p":
+ // Push a parameter on the stack.
+ index, err := strconv.ParseInt(tokens[q][1], 10, 8)
+ index--
+ if err != nil {
+ return buf.String(), err
+ }
+ if int(index) >= len(ps.parameters) {
+ return buf.String(), errors.New("Parameters index out of bound")
+ }
+ ps.st.push(ps.parameters[index])
+ case tokens[q][0][:2] == "%P":
+ // Pop a variable from the stack as a dynamic or static variable.
+ val, err := ps.st.pop()
+ if err != nil {
+ return buf.String(), err
+ }
+ index := tokens[q][2]
+ if len(index) > 1 {
+ errorStr := fmt.Sprintf("%s is not a valid dynamic variables index",
+ index)
+ return buf.String(), errors.New(errorStr)
+ }
+ // Specify either dynamic or static.
+ if index[0] >= 'a' && index[0] <= 'z' {
+ ps.dynamicVar[index[0]] = val
+ } else if index[0] >= 'A' && index[0] <= 'Z' {
+ staticVar[index[0]] = val
+ }
+ case tokens[q][0][:2] == "%g":
+ // Push a variable from the stack as a dynamic or static variable.
+ index := tokens[q][3]
+ if len(index) > 1 {
+ errorStr := fmt.Sprintf("%s is not a valid static variables index",
+ index)
+ return buf.String(), errors.New(errorStr)
+ }
+ var val stacker
+ if index[0] >= 'a' && index[0] <= 'z' {
+ val = ps.dynamicVar[index[0]]
+ } else if index[0] >= 'A' && index[0] <= 'Z' {
+ val = staticVar[index[0]]
+ }
+ ps.st.push(val)
+ case tokens[q][0][:2] == "%'":
+ // Push a character constant.
+ con := tokens[q][4]
+ if len(con) > 1 {
+ errorStr := fmt.Sprintf("%s is not a valid character constant", con)
+ return buf.String(), errors.New(errorStr)
+ }
+ ps.st.push(con[0])
+ case tokens[q][0][:2] == "%{":
+ // Push an integer constant.
+ con, err := strconv.ParseInt(tokens[q][5], 10, 32)
+ if err != nil {
+ return buf.String(), err
+ }
+ ps.st.push(con)
+ case tokens[q][0][:2] == "%l":
+ // Push the length of the string that is popped from the stack.
+ popStr, err := ps.st.pop()
+ if err != nil {
+ return buf.String(), err
+ }
+ if _, ok := popStr.(string); !ok {
+ errStr := fmt.Sprintf("Stack head is not a string")
+ return buf.String(), errors.New(errStr)
+ }
+ ps.st.push(len(popStr.(string)))
+ case tokens[q][0][:2] == "%?":
+ // If-then-else construct. First, the whole string is identified and
+ // then inside this substring, we can specify which parts to switch on.
+ ifReg, _ := regexp.Compile("%\\?(.*)%t(.*)%e(.*);|%\\?(.*)%t(.*);")
+ ifTokens := ifReg.FindStringSubmatch(tokens[q][0])
+ var (
+ ifStr string
+ err error
+ )
+ // Parse the if-part to determine if-else.
+ if len(ifTokens[1]) > 0 {
+ ifStr, err = ps.walk(ifTokens[1])
+ } else { // else
+ ifStr, err = ps.walk(ifTokens[4])
+ }
+ // Return any errors
+ if err != nil {
+ return buf.String(), err
+ } else if len(ifStr) > 0 {
+ // Self-defined limitation, not sure if this is correct, but didn't
+ // seem like it.
+ return buf.String(), errors.New("If-clause cannot print statements")
+ }
+ var thenStr string
+ // Pop the first value that is set by parsing the if-clause.
+ choose, err := ps.st.pop()
+ if err != nil {
+ return buf.String(), err
+ }
+ // Switch to if or else.
+ if choose.(int) == 0 && len(ifTokens[1]) > 0 {
+ thenStr, err = ps.walk(ifTokens[3])
+ } else if choose.(int) != 0 {
+ if len(ifTokens[1]) > 0 {
+ thenStr, err = ps.walk(ifTokens[2])
+ } else {
+ thenStr, err = ps.walk(ifTokens[5])
+ }
+ }
+ if err != nil {
+ return buf.String(), err
+ }
+ buf.WriteString(thenStr)
+ case tokens[q][0][len(tokens[q][0])-1] == 'd': // Fallthrough for printing
+ fallthrough
+ case tokens[q][0][len(tokens[q][0])-1] == 'o': // digits.
+ fallthrough
+ case tokens[q][0][len(tokens[q][0])-1] == 'x':
+ fallthrough
+ case tokens[q][0][len(tokens[q][0])-1] == 'X':
+ fallthrough
+ case tokens[q][0][len(tokens[q][0])-1] == 's':
+ token := tokens[q][0]
+ // Remove the : that comes before a flag.
+ if token[1] == ':' {
+ token = token[:1] + token[2:]
+ }
+ digit, err := ps.st.pop()
+ if err != nil {
+ return buf.String(), err
+ }
+ // The rest is determined like the normal formatted prints.
+ digitStr := fmt.Sprintf(token, digit.(int))
+ buf.WriteString(digitStr)
+ case tokens[q][0][:2] == "%i":
+ // Increment the parameters by one.
+ if len(ps.parameters) < 2 {
+ return buf.String(), errors.New("Not enough parameters to increment.")
+ }
+ val1, val2 := ps.parameters[0].(int), ps.parameters[1].(int)
+ val1++
+ val2++
+ ps.parameters[0], ps.parameters[1] = val1, val2
+ default:
+ // The rest of the tokens is a special case, where two values are
+ // popped and then operated on by the token that comes after them.
+ op1, err := ps.st.pop()
+ if err != nil {
+ return buf.String(), err
+ }
+ op2, err := ps.st.pop()
+ if err != nil {
+ return buf.String(), err
+ }
+ var result stacker
+ switch tokens[q][0][:2] {
+ case "%+":
+ // Addition
+ result = op2.(int) + op1.(int)
+ case "%-":
+ // Subtraction
+ result = op2.(int) - op1.(int)
+ case "%*":
+ // Multiplication
+ result = op2.(int) * op1.(int)
+ case "%/":
+ // Division
+ result = op2.(int) / op1.(int)
+ case "%m":
+ // Modulo
+ result = op2.(int) % op1.(int)
+ case "%&":
+ // Bitwise AND
+ result = op2.(int) & op1.(int)
+ case "%|":
+ // Bitwise OR
+ result = op2.(int) | op1.(int)
+ case "%^":
+ // Bitwise XOR
+ result = op2.(int) ^ op1.(int)
+ case "%=":
+ // Equals
+ result = op2 == op1
+ case "%>":
+ // Greater-than
+ result = op2.(int) > op1.(int)
+ case "%<":
+ // Lesser-than
+ result = op2.(int) < op1.(int)
+ case "%A":
+ // Logical AND
+ result = op2.(bool) && op1.(bool)
+ case "%O":
+ // Logical OR
+ result = op2.(bool) || op1.(bool)
+ case "%!":
+ // Logical complement
+ result = !op1.(bool)
+ case "%~":
+ // Bitwise complement
+ result = ^(op1.(int))
+ }
+ ps.st.push(result)
+ }
+
+ i = indices[q][1] - 1
+ q++
+ } else {
+ // We are not "inside" a token, so just skip until the end or the next
+ // token, and add all characters to the buffer.
+ j := i
+ if q != len(indices) {
+ for !(j >= indices[q][0] && j < indices[q][1]) {
+ j++
+ }
+ } else {
+ j = len(attr)
+ }
+ buf.WriteString(string(attr[i:j]))
+ i = j
+ }
+ }
+ // Return the buffer as a string.
+ return buf.String(), nil
+}
+
+// Push a stacker-value onto the stack.
+func (st *stack) push(s stacker) {
+ *st = append(*st, s)
+}
+
+// Pop a stacker-value from the stack.
+func (st *stack) pop() (stacker, error) {
+ if len(*st) == 0 {
+ return nil, errors.New("Stack is empty.")
+ }
+ newStack := make(stack, len(*st)-1)
+ val := (*st)[len(*st)-1]
+ copy(newStack, (*st)[:len(*st)-1])
+ *st = newStack
+ return val, nil
+}
+
+// Initialize regexes and the static vars (that don't get changed between
+// calls.
+func init() {
+ // Initialize the main regex.
+ expStr := strings.Join(exp[:], "|")
+ regex, _ = regexp.Compile(expStr)
+ // Initialize the static variables.
+ staticVar = make(map[byte]stacker, 26)
+}
diff --git a/vendor/github.com/Nvveen/Gotty/types.go b/vendor/github.com/Nvveen/Gotty/types.go
new file mode 100644
index 0000000..9bcc65e
--- /dev/null
+++ b/vendor/github.com/Nvveen/Gotty/types.go
@@ -0,0 +1,23 @@
+// Copyright 2012 Neal van Veen. All rights reserved.
+// Usage of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package gotty
+
+type TermInfo struct {
+ boolAttributes map[string]bool
+ numAttributes map[string]int16
+ strAttributes map[string]string
+ // The various names of the TermInfo file.
+ Names []string
+}
+
+type stacker interface {
+}
+type stack []stacker
+
+type parser struct {
+ st stack
+ parameters []stacker
+ dynamicVar map[byte]stacker
+}
diff --git a/vendor/github.com/RackSec/srslog/LICENSE b/vendor/github.com/RackSec/srslog/LICENSE
new file mode 100644
index 0000000..9269338
--- /dev/null
+++ b/vendor/github.com/RackSec/srslog/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2015 Rackspace. 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/RackSec/srslog/README.md b/vendor/github.com/RackSec/srslog/README.md
new file mode 100644
index 0000000..1ae1fd4
--- /dev/null
+++ b/vendor/github.com/RackSec/srslog/README.md
@@ -0,0 +1,131 @@
+[![Build Status](https://travis-ci.org/RackSec/srslog.svg?branch=master)](https://travis-ci.org/RackSec/srslog)
+
+# srslog
+
+Go has a `syslog` package in the standard library, but it has the following
+shortcomings:
+
+1. It doesn't have TLS support
+2. [According to bradfitz on the Go team, it is no longer being maintained.](https://github.com/golang/go/issues/13449#issuecomment-161204716)
+
+I agree that it doesn't need to be in the standard library. So, I've
+followed Brad's suggestion and have made a separate project to handle syslog.
+
+This code was taken directly from the Go project as a base to start from.
+
+However, this _does_ have TLS support.
+
+# Usage
+
+Basic usage retains the same interface as the original `syslog` package. We
+only added to the interface where required to support new functionality.
+
+Switch from the standard library:
+
+```
+import(
+ //"log/syslog"
+ syslog "github.com/RackSec/srslog"
+)
+```
+
+You can still use it for local syslog:
+
+```
+w, err := syslog.Dial("", "", syslog.LOG_ERR, "testtag")
+```
+
+Or to unencrypted UDP:
+
+```
+w, err := syslog.Dial("udp", "192.168.0.50:514", syslog.LOG_ERR, "testtag")
+```
+
+Or to unencrypted TCP:
+
+```
+w, err := syslog.Dial("tcp", "192.168.0.51:514", syslog.LOG_ERR, "testtag")
+```
+
+But now you can also send messages via TLS-encrypted TCP:
+
+```
+w, err := syslog.DialWithTLSCertPath("tcp+tls", "192.168.0.52:514", syslog.LOG_ERR, "testtag", "/path/to/servercert.pem")
+```
+
+And if you need more control over your TLS configuration :
+
+```
+pool := x509.NewCertPool()
+serverCert, err := ioutil.ReadFile("/path/to/servercert.pem")
+if err != nil {
+ return nil, err
+}
+pool.AppendCertsFromPEM(serverCert)
+config := tls.Config{
+ RootCAs: pool,
+}
+
+w, err := DialWithTLSConfig(network, raddr, priority, tag, &config)
+```
+
+(Note that in both TLS cases, this uses a self-signed certificate, where the
+remote syslog server has the keypair and the client has only the public key.)
+
+And then to write log messages, continue like so:
+
+```
+if err != nil {
+ log.Fatal("failed to connect to syslog:", err)
+}
+defer w.Close()
+
+w.Alert("this is an alert")
+w.Crit("this is critical")
+w.Err("this is an error")
+w.Warning("this is a warning")
+w.Notice("this is a notice")
+w.Info("this is info")
+w.Debug("this is debug")
+w.Write([]byte("these are some bytes"))
+```
+
+# Generating TLS Certificates
+
+We've provided a script that you can use to generate a self-signed keypair:
+
+```
+pip install cryptography
+python script/gen-certs.py
+```
+
+That outputs the public key and private key to standard out. Put those into
+`.pem` files. (And don't put them into any source control. The certificate in
+the `test` directory is used by the unit tests, and please do not actually use
+it anywhere else.)
+
+# Running Tests
+
+Run the tests as usual:
+
+```
+go test
+```
+
+But we've also provided a test coverage script that will show you which
+lines of code are not covered:
+
+```
+script/coverage --html
+```
+
+That will open a new browser tab showing coverage information.
+
+# License
+
+This project uses the New BSD License, the same as the Go project itself.
+
+# Code of Conduct
+
+Please note that this project is released with a Contributor Code of Conduct.
+By participating in this project you agree to abide by its terms.
diff --git a/vendor/github.com/RackSec/srslog/constants.go b/vendor/github.com/RackSec/srslog/constants.go
new file mode 100644
index 0000000..600801e
--- /dev/null
+++ b/vendor/github.com/RackSec/srslog/constants.go
@@ -0,0 +1,68 @@
+package srslog
+
+import (
+ "errors"
+)
+
+// Priority is a combination of the syslog facility and
+// severity. For example, LOG_ALERT | LOG_FTP sends an alert severity
+// message from the FTP facility. The default severity is LOG_EMERG;
+// the default facility is LOG_KERN.
+type Priority int
+
+const severityMask = 0x07
+const facilityMask = 0xf8
+
+const (
+ // Severity.
+
+ // From /usr/include/sys/syslog.h.
+ // These are the same on Linux, BSD, and OS X.
+ LOG_EMERG Priority = iota
+ LOG_ALERT
+ LOG_CRIT
+ LOG_ERR
+ LOG_WARNING
+ LOG_NOTICE
+ LOG_INFO
+ LOG_DEBUG
+)
+
+const (
+ // Facility.
+
+ // From /usr/include/sys/syslog.h.
+ // These are the same up to LOG_FTP on Linux, BSD, and OS X.
+ LOG_KERN Priority = iota << 3
+ LOG_USER
+ LOG_MAIL
+ LOG_DAEMON
+ LOG_AUTH
+ LOG_SYSLOG
+ LOG_LPR
+ LOG_NEWS
+ LOG_UUCP
+ LOG_CRON
+ LOG_AUTHPRIV
+ LOG_FTP
+ _ // unused
+ _ // unused
+ _ // unused
+ _ // unused
+ LOG_LOCAL0
+ LOG_LOCAL1
+ LOG_LOCAL2
+ LOG_LOCAL3
+ LOG_LOCAL4
+ LOG_LOCAL5
+ LOG_LOCAL6
+ LOG_LOCAL7
+)
+
+func validatePriority(p Priority) error {
+ if p < 0 || p > LOG_LOCAL7|LOG_DEBUG {
+ return errors.New("log/syslog: invalid priority")
+ } else {
+ return nil
+ }
+}
diff --git a/vendor/github.com/RackSec/srslog/dialer.go b/vendor/github.com/RackSec/srslog/dialer.go
new file mode 100644
index 0000000..47a7b2b
--- /dev/null
+++ b/vendor/github.com/RackSec/srslog/dialer.go
@@ -0,0 +1,87 @@
+package srslog
+
+import (
+ "crypto/tls"
+ "net"
+)
+
+// dialerFunctionWrapper is a simple object that consists of a dialer function
+// and its name. This is primarily for testing, so we can make sure that the
+// getDialer method returns the correct dialer function. However, if you ever
+// find that you need to check which dialer function you have, this would also
+// be useful for you without having to use reflection.
+type dialerFunctionWrapper struct {
+ Name string
+ Dialer func() (serverConn, string, error)
+}
+
+// Call the wrapped dialer function and return its return values.
+func (df dialerFunctionWrapper) Call() (serverConn, string, error) {
+ return df.Dialer()
+}
+
+// getDialer returns a "dialer" function that can be called to connect to a
+// syslog server.
+//
+// Each dialer function is responsible for dialing the remote host and returns
+// a serverConn, the hostname (or a default if the Writer has not specified a
+// hostname), and an error in case dialing fails.
+//
+// The reason for separate dialers is that different network types may need
+// to dial their connection differently, yet still provide a net.Conn interface
+// that you can use once they have dialed. Rather than an increasingly long
+// conditional, we have a map of network -> dialer function (with a sane default
+// value), and adding a new network type is as easy as writing the dialer
+// function and adding it to the map.
+func (w *Writer) getDialer() dialerFunctionWrapper {
+ dialers := map[string]dialerFunctionWrapper{
+ "": dialerFunctionWrapper{"unixDialer", w.unixDialer},
+ "tcp+tls": dialerFunctionWrapper{"tlsDialer", w.tlsDialer},
+ }
+ dialer, ok := dialers[w.network]
+ if !ok {
+ dialer = dialerFunctionWrapper{"basicDialer", w.basicDialer}
+ }
+ return dialer
+}
+
+// unixDialer uses the unixSyslog method to open a connection to the syslog
+// daemon running on the local machine.
+func (w *Writer) unixDialer() (serverConn, string, error) {
+ sc, err := unixSyslog()
+ hostname := w.hostname
+ if hostname == "" {
+ hostname = "localhost"
+ }
+ return sc, hostname, err
+}
+
+// tlsDialer connects to TLS over TCP, and is used for the "tcp+tls" network
+// type.
+func (w *Writer) tlsDialer() (serverConn, string, error) {
+ c, err := tls.Dial("tcp", w.raddr, w.tlsConfig)
+ var sc serverConn
+ hostname := w.hostname
+ if err == nil {
+ sc = &netConn{conn: c}
+ if hostname == "" {
+ hostname = c.LocalAddr().String()
+ }
+ }
+ return sc, hostname, err
+}
+
+// basicDialer is the most common dialer for syslog, and supports both TCP and
+// UDP connections.
+func (w *Writer) basicDialer() (serverConn, string, error) {
+ c, err := net.Dial(w.network, w.raddr)
+ var sc serverConn
+ hostname := w.hostname
+ if err == nil {
+ sc = &netConn{conn: c}
+ if hostname == "" {
+ hostname = c.LocalAddr().String()
+ }
+ }
+ return sc, hostname, err
+}
diff --git a/vendor/github.com/RackSec/srslog/formatter.go b/vendor/github.com/RackSec/srslog/formatter.go
new file mode 100644
index 0000000..7852ad3
--- /dev/null
+++ b/vendor/github.com/RackSec/srslog/formatter.go
@@ -0,0 +1,48 @@
+package srslog
+
+import (
+ "fmt"
+ "os"
+ "time"
+)
+
+// Formatter is a type of function that takes the consituent parts of a
+// syslog message and returns a formatted string. A different Formatter is
+// defined for each different syslog protocol we support.
+type Formatter func(p Priority, hostname, tag, content string) string
+
+// DefaultFormatter is the original format supported by the Go syslog package,
+// and is a non-compliant amalgamation of 3164 and 5424 that is intended to
+// maximize compatibility.
+func DefaultFormatter(p Priority, hostname, tag, content string) string {
+ timestamp := time.Now().Format(time.RFC3339)
+ msg := fmt.Sprintf("<%d> %s %s %s[%d]: %s",
+ p, timestamp, hostname, tag, os.Getpid(), content)
+ return msg
+}
+
+// UnixFormatter omits the hostname, because it is only used locally.
+func UnixFormatter(p Priority, hostname, tag, content string) string {
+ timestamp := time.Now().Format(time.Stamp)
+ msg := fmt.Sprintf("<%d>%s %s[%d]: %s",
+ p, timestamp, tag, os.Getpid(), content)
+ return msg
+}
+
+// RFC3164Formatter provides an RFC 3164 compliant message.
+func RFC3164Formatter(p Priority, hostname, tag, content string) string {
+ timestamp := time.Now().Format(time.Stamp)
+ msg := fmt.Sprintf("<%d>%s %s %s[%d]: %s",
+ p, timestamp, hostname, tag, os.Getpid(), content)
+ return msg
+}
+
+// RFC5424Formatter provides an RFC 5424 compliant message.
+func RFC5424Formatter(p Priority, hostname, tag, content string) string {
+ timestamp := time.Now().Format(time.RFC3339)
+ pid := os.Getpid()
+ appName := os.Args[0]
+ msg := fmt.Sprintf("<%d>%d %s %s %s %d %s %s",
+ p, 1, timestamp, hostname, appName, pid, tag, content)
+ return msg
+}
diff --git a/vendor/github.com/RackSec/srslog/framer.go b/vendor/github.com/RackSec/srslog/framer.go
new file mode 100644
index 0000000..ab46f0d
--- /dev/null
+++ b/vendor/github.com/RackSec/srslog/framer.go
@@ -0,0 +1,24 @@
+package srslog
+
+import (
+ "fmt"
+)
+
+// Framer is a type of function that takes an input string (typically an
+// already-formatted syslog message) and applies "message framing" to it. We
+// have different framers because different versions of the syslog protocol
+// and its transport requirements define different framing behavior.
+type Framer func(in string) string
+
+// DefaultFramer does nothing, since there is no framing to apply. This is
+// the original behavior of the Go syslog package, and is also typically used
+// for UDP syslog.
+func DefaultFramer(in string) string {
+ return in
+}
+
+// RFC5425MessageLengthFramer prepends the message length to the front of the
+// provided message, as defined in RFC 5425.
+func RFC5425MessageLengthFramer(in string) string {
+ return fmt.Sprintf("%d %s", len(in), in)
+}
diff --git a/vendor/github.com/RackSec/srslog/net_conn.go b/vendor/github.com/RackSec/srslog/net_conn.go
new file mode 100644
index 0000000..75e4c3c
--- /dev/null
+++ b/vendor/github.com/RackSec/srslog/net_conn.go
@@ -0,0 +1,30 @@
+package srslog
+
+import (
+ "net"
+)
+
+// netConn has an internal net.Conn and adheres to the serverConn interface,
+// allowing us to send syslog messages over the network.
+type netConn struct {
+ conn net.Conn
+}
+
+// writeString formats syslog messages using time.RFC3339 and includes the
+// hostname, and sends the message to the connection.
+func (n *netConn) writeString(framer Framer, formatter Formatter, p Priority, hostname, tag, msg string) error {
+ if framer == nil {
+ framer = DefaultFramer
+ }
+ if formatter == nil {
+ formatter = DefaultFormatter
+ }
+ formattedMessage := framer(formatter(p, hostname, tag, msg))
+ _, err := n.conn.Write([]byte(formattedMessage))
+ return err
+}
+
+// close the network connection
+func (n *netConn) close() error {
+ return n.conn.Close()
+}
diff --git a/vendor/github.com/RackSec/srslog/srslog.go b/vendor/github.com/RackSec/srslog/srslog.go
new file mode 100644
index 0000000..b404dff
--- /dev/null
+++ b/vendor/github.com/RackSec/srslog/srslog.go
@@ -0,0 +1,97 @@
+package srslog
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+// This interface allows us to work with both local and network connections,
+// and enables Solaris support (see syslog_unix.go).
+type serverConn interface {
+ writeString(framer Framer, formatter Formatter, p Priority, hostname, tag, s string) error
+ close() error
+}
+
+// New establishes a new connection to the system log daemon. Each
+// write to the returned Writer sends a log message with the given
+// priority and prefix.
+func New(priority Priority, tag string) (w *Writer, err error) {
+ return Dial("", "", priority, tag)
+}
+
+// Dial establishes a connection to a log daemon by connecting to
+// address raddr on the specified network. Each write to the returned
+// Writer sends a log message with the given facility, severity and
+// tag.
+// If network is empty, Dial will connect to the local syslog server.
+func Dial(network, raddr string, priority Priority, tag string) (*Writer, error) {
+ return DialWithTLSConfig(network, raddr, priority, tag, nil)
+}
+
+// DialWithTLSCertPath establishes a secure connection to a log daemon by connecting to
+// address raddr on the specified network. It uses certPath to load TLS certificates and configure
+// the secure connection.
+func DialWithTLSCertPath(network, raddr string, priority Priority, tag, certPath string) (*Writer, error) {
+ serverCert, err := ioutil.ReadFile(certPath)
+ if err != nil {
+ return nil, err
+ }
+
+ return DialWithTLSCert(network, raddr, priority, tag, serverCert)
+}
+
+// DialWIthTLSCert establishes a secure connection to a log daemon by connecting to
+// address raddr on the specified network. It uses serverCert to load a TLS certificate
+// and configure the secure connection.
+func DialWithTLSCert(network, raddr string, priority Priority, tag string, serverCert []byte) (*Writer, error) {
+ pool := x509.NewCertPool()
+ pool.AppendCertsFromPEM(serverCert)
+ config := tls.Config{
+ RootCAs: pool,
+ }
+
+ return DialWithTLSConfig(network, raddr, priority, tag, &config)
+}
+
+// DialWithTLSConfig establishes a secure connection to a log daemon by connecting to
+// address raddr on the specified network. It uses tlsConfig to configure the secure connection.
+func DialWithTLSConfig(network, raddr string, priority Priority, tag string, tlsConfig *tls.Config) (*Writer, error) {
+ if err := validatePriority(priority); err != nil {
+ return nil, err
+ }
+
+ if tag == "" {
+ tag = os.Args[0]
+ }
+ hostname, _ := os.Hostname()
+
+ w := &Writer{
+ priority: priority,
+ tag: tag,
+ hostname: hostname,
+ network: network,
+ raddr: raddr,
+ tlsConfig: tlsConfig,
+ }
+
+ _, err := w.connect()
+ if err != nil {
+ return nil, err
+ }
+ return w, err
+}
+
+// NewLogger creates a log.Logger whose output is written to
+// the system log service with the specified priority. The logFlag
+// argument is the flag set passed through to log.New to create
+// the Logger.
+func NewLogger(p Priority, logFlag int) (*log.Logger, error) {
+ s, err := New(p, "")
+ if err != nil {
+ return nil, err
+ }
+ return log.New(s, "", logFlag), nil
+}
diff --git a/vendor/github.com/RackSec/srslog/srslog_unix.go b/vendor/github.com/RackSec/srslog/srslog_unix.go
new file mode 100644
index 0000000..a04d939
--- /dev/null
+++ b/vendor/github.com/RackSec/srslog/srslog_unix.go
@@ -0,0 +1,54 @@
+package srslog
+
+import (
+ "errors"
+ "io"
+ "net"
+)
+
+// unixSyslog opens a connection to the syslog daemon running on the
+// local machine using a Unix domain socket. This function exists because of
+// Solaris support as implemented by gccgo. On Solaris you can not
+// simply open a TCP connection to the syslog daemon. The gccgo
+// sources have a syslog_solaris.go file that implements unixSyslog to
+// return a type that satisfies the serverConn interface and simply calls the C
+// library syslog function.
+func unixSyslog() (conn serverConn, err error) {
+ logTypes := []string{"unixgram", "unix"}
+ logPaths := []string{"/dev/log", "/var/run/syslog", "/var/run/log"}
+ for _, network := range logTypes {
+ for _, path := range logPaths {
+ conn, err := net.Dial(network, path)
+ if err != nil {
+ continue
+ } else {
+ return &localConn{conn: conn}, nil
+ }
+ }
+ }
+ return nil, errors.New("Unix syslog delivery error")
+}
+
+// localConn adheres to the serverConn interface, allowing us to send syslog
+// messages to the local syslog daemon over a Unix domain socket.
+type localConn struct {
+ conn io.WriteCloser
+}
+
+// writeString formats syslog messages using time.Stamp instead of time.RFC3339,
+// and omits the hostname (because it is expected to be used locally).
+func (n *localConn) writeString(framer Framer, formatter Formatter, p Priority, hostname, tag, msg string) error {
+ if framer == nil {
+ framer = DefaultFramer
+ }
+ if formatter == nil {
+ formatter = UnixFormatter
+ }
+ _, err := n.conn.Write([]byte(framer(formatter(p, hostname, tag, msg))))
+ return err
+}
+
+// close the (local) network connection
+func (n *localConn) close() error {
+ return n.conn.Close()
+}
diff --git a/vendor/github.com/RackSec/srslog/writer.go b/vendor/github.com/RackSec/srslog/writer.go
new file mode 100644
index 0000000..ce3d867
--- /dev/null
+++ b/vendor/github.com/RackSec/srslog/writer.go
@@ -0,0 +1,185 @@
+package srslog
+
+import (
+ "crypto/tls"
+ "strings"
+ "sync"
+)
+
+// A Writer is a connection to a syslog server.
+type Writer struct {
+ priority Priority
+ tag string
+ hostname string
+ network string
+ raddr string
+ tlsConfig *tls.Config
+ framer Framer
+ formatter Formatter
+
+ mu sync.RWMutex // guards conn
+ conn serverConn
+}
+
+// getConn provides access to the internal conn, protected by a mutex. The
+// conn is threadsafe, so it can be used while unlocked, but we want to avoid
+// race conditions on grabbing a reference to it.
+func (w *Writer) getConn() serverConn {
+ w.mu.RLock()
+ conn := w.conn
+ w.mu.RUnlock()
+ return conn
+}
+
+// setConn updates the internal conn, protected by a mutex.
+func (w *Writer) setConn(c serverConn) {
+ w.mu.Lock()
+ w.conn = c
+ w.mu.Unlock()
+}
+
+// connect makes a connection to the syslog server.
+func (w *Writer) connect() (serverConn, error) {
+ conn := w.getConn()
+ if conn != nil {
+ // ignore err from close, it makes sense to continue anyway
+ conn.close()
+ w.setConn(nil)
+ }
+
+ var hostname string
+ var err error
+ dialer := w.getDialer()
+ conn, hostname, err = dialer.Call()
+ if err == nil {
+ w.setConn(conn)
+ w.hostname = hostname
+
+ return conn, nil
+ } else {
+ return nil, err
+ }
+}
+
+// SetFormatter changes the formatter function for subsequent messages.
+func (w *Writer) SetFormatter(f Formatter) {
+ w.formatter = f
+}
+
+// SetFramer changes the framer function for subsequent messages.
+func (w *Writer) SetFramer(f Framer) {
+ w.framer = f
+}
+
+// Write sends a log message to the syslog daemon using the default priority
+// passed into `srslog.New` or the `srslog.Dial*` functions.
+func (w *Writer) Write(b []byte) (int, error) {
+ return w.writeAndRetry(w.priority, string(b))
+}
+
+// WriteWithPriority sends a log message with a custom priority
+func (w *Writer) WriteWithPriority(p Priority, b []byte) (int, error) {
+ return w.writeAndRetry(p, string(b))
+}
+
+// Close closes a connection to the syslog daemon.
+func (w *Writer) Close() error {
+ conn := w.getConn()
+ if conn != nil {
+ err := conn.close()
+ w.setConn(nil)
+ return err
+ }
+ return nil
+}
+
+// Emerg logs a message with severity LOG_EMERG; this overrides the default
+// priority passed to `srslog.New` and the `srslog.Dial*` functions.
+func (w *Writer) Emerg(m string) (err error) {
+ _, err = w.writeAndRetry(LOG_EMERG, m)
+ return err
+}
+
+// Alert logs a message with severity LOG_ALERT; this overrides the default
+// priority passed to `srslog.New` and the `srslog.Dial*` functions.
+func (w *Writer) Alert(m string) (err error) {
+ _, err = w.writeAndRetry(LOG_ALERT, m)
+ return err
+}
+
+// Crit logs a message with severity LOG_CRIT; this overrides the default
+// priority passed to `srslog.New` and the `srslog.Dial*` functions.
+func (w *Writer) Crit(m string) (err error) {
+ _, err = w.writeAndRetry(LOG_CRIT, m)
+ return err
+}
+
+// Err logs a message with severity LOG_ERR; this overrides the default
+// priority passed to `srslog.New` and the `srslog.Dial*` functions.
+func (w *Writer) Err(m string) (err error) {
+ _, err = w.writeAndRetry(LOG_ERR, m)
+ return err
+}
+
+// Warning logs a message with severity LOG_WARNING; this overrides the default
+// priority passed to `srslog.New` and the `srslog.Dial*` functions.
+func (w *Writer) Warning(m string) (err error) {
+ _, err = w.writeAndRetry(LOG_WARNING, m)
+ return err
+}
+
+// Notice logs a message with severity LOG_NOTICE; this overrides the default
+// priority passed to `srslog.New` and the `srslog.Dial*` functions.
+func (w *Writer) Notice(m string) (err error) {
+ _, err = w.writeAndRetry(LOG_NOTICE, m)
+ return err
+}
+
+// Info logs a message with severity LOG_INFO; this overrides the default
+// priority passed to `srslog.New` and the `srslog.Dial*` functions.
+func (w *Writer) Info(m string) (err error) {
+ _, err = w.writeAndRetry(LOG_INFO, m)
+ return err
+}
+
+// Debug logs a message with severity LOG_DEBUG; this overrides the default
+// priority passed to `srslog.New` and the `srslog.Dial*` functions.
+func (w *Writer) Debug(m string) (err error) {
+ _, err = w.writeAndRetry(LOG_DEBUG, m)
+ return err
+}
+
+func (w *Writer) writeAndRetry(p Priority, s string) (int, error) {
+ pr := (w.priority & facilityMask) | (p & severityMask)
+
+ conn := w.getConn()
+ if conn != nil {
+ if n, err := w.write(conn, pr, s); err == nil {
+ return n, err
+ }
+ }
+
+ var err error
+ if conn, err = w.connect(); err != nil {
+ return 0, err
+ }
+ return w.write(conn, pr, s)
+}
+
+// write generates and writes a syslog formatted string. It formats the
+// message based on the current Formatter and Framer.
+func (w *Writer) write(conn serverConn, p Priority, msg string) (int, error) {
+ // ensure it ends in a \n
+ if !strings.HasSuffix(msg, "\n") {
+ msg += "\n"
+ }
+
+ err := conn.writeString(w.framer, w.formatter, p, w.hostname, w.tag, msg)
+ if err != nil {
+ return 0, err
+ }
+ // Note: return the length of the input, not the number of
+ // bytes printed by Fprintf, because this must behave like
+ // an io.Writer.
+ return len(msg), nil
+}
diff --git a/vendor/github.com/Sirupsen/logrus/LICENSE b/vendor/github.com/Sirupsen/logrus/LICENSE
new file mode 100644
index 0000000..f090cb4
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Simon Eskildsen
+
+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/Sirupsen/logrus/README.md b/vendor/github.com/Sirupsen/logrus/README.md
new file mode 100644
index 0000000..126cd1f
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/README.md
@@ -0,0 +1,425 @@
+# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/>&nbsp;[![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus)&nbsp;[![GoDoc](https://godoc.org/github.com/Sirupsen/logrus?status.svg)](https://godoc.org/github.com/Sirupsen/logrus)
+
+Logrus is a structured logger for Go (golang), completely API compatible with
+the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not
+yet stable (pre 1.0). Logrus itself is completely stable and has been used in
+many large deployments. The core API is unlikely to change much but please
+version control your Logrus to make sure you aren't fetching latest `master` on
+every build.**
+
+Nicely color-coded in development (when a TTY is attached, otherwise just
+plain text):
+
+![Colored](http://i.imgur.com/PY7qMwd.png)
+
+With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
+or Splunk:
+
+```json
+{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
+ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
+
+{"level":"warning","msg":"The group's number increased tremendously!",
+"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
+
+{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
+"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
+
+{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
+"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
+
+{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
+"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
+```
+
+With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
+attached, the output is compatible with the
+[logfmt](http://godoc.org/github.com/kr/logfmt) format:
+
+```text
+time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
+time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
+time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
+time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
+time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
+time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
+exit status 1
+```
+
+#### Example
+
+The simplest way to use Logrus is simply the package-level exported logger:
+
+```go
+package main
+
+import (
+ log "github.com/Sirupsen/logrus"
+)
+
+func main() {
+ log.WithFields(log.Fields{
+ "animal": "walrus",
+ }).Info("A walrus appears")
+}
+```
+
+Note that it's completely api-compatible with the stdlib logger, so you can
+replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"`
+and you'll now have the flexibility of Logrus. You can customize it all you
+want:
+
+```go
+package main
+
+import (
+ "os"
+ log "github.com/Sirupsen/logrus"
+)
+
+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)
+
+ // Only log the warning severity or above.
+ log.SetLevel(log.WarnLevel)
+}
+
+func main() {
+ log.WithFields(log.Fields{
+ "animal": "walrus",
+ "size": 10,
+ }).Info("A group of walrus emerges from the ocean")
+
+ log.WithFields(log.Fields{
+ "omg": true,
+ "number": 122,
+ }).Warn("The group's number increased tremendously!")
+
+ log.WithFields(log.Fields{
+ "omg": true,
+ "number": 100,
+ }).Fatal("The ice breaks!")
+
+ // A common pattern is to re-use fields between logging statements by re-using
+ // the logrus.Entry returned from WithFields()
+ contextLogger := log.WithFields(log.Fields{
+ "common": "this is a common field",
+ "other": "I also should be logged always",
+ })
+
+ contextLogger.Info("I'll be logged with common and other field")
+ contextLogger.Info("Me too")
+}
+```
+
+For more advanced usage such as logging to multiple locations from the same
+application, you can also create an instance of the `logrus` Logger:
+
+```go
+package main
+
+import (
+ "github.com/Sirupsen/logrus"
+)
+
+// Create a new instance of the logger. You can have any number of instances.
+var log = logrus.New()
+
+func main() {
+ // The API for setting attributes is a little different than the package level
+ // exported logger. See Godoc.
+ log.Out = os.Stderr
+
+ log.WithFields(logrus.Fields{
+ "animal": "walrus",
+ "size": 10,
+ }).Info("A group of walrus emerges from the ocean")
+}
+```
+
+#### Fields
+
+Logrus encourages careful, structured logging though logging fields instead of
+long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
+to send event %s to topic %s with key %d")`, you should log the much more
+discoverable:
+
+```go
+log.WithFields(log.Fields{
+ "event": event,
+ "topic": topic,
+ "key": key,
+}).Fatal("Failed to send event")
+```
+
+We've found this API forces you to think about logging in a way that produces
+much more useful logging messages. We've been in countless situations where just
+a single added field to a log statement that was already there would've saved us
+hours. The `WithFields` call is optional.
+
+In general, with Logrus using any of the `printf`-family functions should be
+seen as a hint you should add a field, however, you can still use the
+`printf`-family functions with Logrus.
+
+#### Hooks
+
+You can add hooks for logging levels. For example to send errors to an exception
+tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
+multiple places simultaneously, e.g. syslog.
+
+Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
+`init`:
+
+```go
+import (
+ log "github.com/Sirupsen/logrus"
+ "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake"
+ logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
+ "log/syslog"
+)
+
+func init() {
+
+ // Use the Airbrake hook to report errors that have Error severity or above to
+ // an exception tracker. You can create custom hooks, see the Hooks section.
+ log.AddHook(airbrake.NewHook(123, "xyz", "production"))
+
+ hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
+ if err != nil {
+ log.Error("Unable to connect to local syslog daemon")
+ } else {
+ log.AddHook(hook)
+ }
+}
+```
+Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
+
+| Hook | Description |
+| ----- | ----------- |
+| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. |
+| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
+| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. |
+| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. |
+| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
+| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. |
+| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
+| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
+| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
+| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
+| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) |
+| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
+| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
+| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
+| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
+| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
+| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd |
+| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb |
+| [Influxus] (http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB] (http://influxdata.com/) |
+| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb |
+| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit |
+| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic |
+| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) |
+| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) |
+| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka |
+| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) |
+| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch|
+| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)|
+| [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)|
+| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) |
+| [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash |
+| [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) |
+
+
+#### Level logging
+
+Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
+
+```go
+log.Debug("Useful debugging information.")
+log.Info("Something noteworthy happened!")
+log.Warn("You should probably take a look at this.")
+log.Error("Something failed but I'm not quitting.")
+// Calls os.Exit(1) after logging
+log.Fatal("Bye.")
+// Calls panic() after logging
+log.Panic("I'm bailing.")
+```
+
+You can set the logging level on a `Logger`, then it will only log entries with
+that severity or anything above it:
+
+```go
+// Will log anything that is info or above (warn, error, fatal, panic). Default.
+log.SetLevel(log.InfoLevel)
+```
+
+It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
+environment if your application has that.
+
+#### Entries
+
+Besides the fields added with `WithField` or `WithFields` some fields are
+automatically added to all logging events:
+
+1. `time`. The timestamp when the entry was created.
+2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
+ the `AddFields` call. E.g. `Failed to send event.`
+3. `level`. The logging level. E.g. `info`.
+
+#### Environments
+
+Logrus has no notion of environment.
+
+If you wish for hooks and formatters to only be used in specific environments,
+you should handle that yourself. For example, if your application has a global
+variable `Environment`, which is a string representation of the environment you
+could do:
+
+```go
+import (
+ log "github.com/Sirupsen/logrus"
+)
+
+init() {
+ // do something here to set environment depending on an environment variable
+ // or command-line flag
+ if Environment == "production" {
+ log.SetFormatter(&log.JSONFormatter{})
+ } else {
+ // The TextFormatter is default, you don't actually have to do this.
+ log.SetFormatter(&log.TextFormatter{})
+ }
+}
+```
+
+This configuration is how `logrus` was intended to be used, but JSON in
+production is mostly only useful if you do log aggregation with tools like
+Splunk or Logstash.
+
+#### Formatters
+
+The built-in logging formatters are:
+
+* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
+ without colors.
+ * *Note:* to force colored output when there is no TTY, set the `ForceColors`
+ field to `true`. To force no colored output even if there is a TTY set the
+ `DisableColors` field to `true`
+* `logrus.JSONFormatter`. Logs fields as JSON.
+
+Third party logging formatters:
+
+* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
+* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
+* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
+
+You can define your formatter by implementing the `Formatter` interface,
+requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
+`Fields` type (`map[string]interface{}`) with all your fields as well as the
+default ones (see Entries section above):
+
+```go
+type MyJSONFormatter struct {
+}
+
+log.SetFormatter(new(MyJSONFormatter))
+
+func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
+ // Note this doesn't include Time, Level and Message which are available on
+ // the Entry. Consult `godoc` on information about those fields or read the
+ // source of the official loggers.
+ serialized, err := json.Marshal(entry.Data)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
+ }
+ return append(serialized, '\n'), nil
+}
+```
+
+#### Logger as an `io.Writer`
+
+Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
+
+```go
+w := logger.Writer()
+defer w.Close()
+
+srv := http.Server{
+ // create a stdlib log.Logger that writes to
+ // logrus.Logger.
+ ErrorLog: log.New(w, "", 0),
+}
+```
+
+Each line written to that writer will be printed the usual way, using formatters
+and hooks. The level for those entries is `info`.
+
+#### Rotation
+
+Log rotation is not provided with Logrus. Log rotation should be done by an
+external program (like `logrotate(8)`) that can compress and delete old log
+entries. It should not be a feature of the application-level logger.
+
+#### Tools
+
+| Tool | Description |
+| ---- | ----------- |
+|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.|
+|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper arround Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
+
+#### Testing
+
+Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
+
+* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
+* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
+
+```go
+logger, hook := NewNullLogger()
+logger.Error("Hello error")
+
+assert.Equal(1, len(hook.Entries))
+assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
+assert.Equal("Hello error", hook.LastEntry().Message)
+
+hook.Reset()
+assert.Nil(hook.LastEntry())
+```
+
+#### Fatal handlers
+
+Logrus can register one or more functions that will be called when any `fatal`
+level message is logged. The registered handlers will be executed before
+logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
+to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
+
+```
+...
+handler := func() {
+ // gracefully shutdown something...
+}
+logrus.RegisterExitHandler(handler)
+...
+```
+
+#### Thread safty
+
+By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs.
+If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
+
+Situation when locking is not needed includes:
+
+* You have no hooks registered, or hooks calling is already thread-safe.
+
+* Writing to logger.Out is already thread-safe, for example:
+
+ 1) logger.Out is protected by locks.
+
+ 2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing)
+
+ (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
diff --git a/vendor/github.com/Sirupsen/logrus/alt_exit.go b/vendor/github.com/Sirupsen/logrus/alt_exit.go
new file mode 100644
index 0000000..b4c9e84
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/alt_exit.go
@@ -0,0 +1,64 @@
+package logrus
+
+// The following code was sourced and modified from the
+// https://bitbucket.org/tebeka/atexit package governed by the following license:
+//
+// Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.
+//
+// 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.
+
+import (
+ "fmt"
+ "os"
+)
+
+var handlers = []func(){}
+
+func runHandler(handler func()) {
+ defer func() {
+ if err := recover(); err != nil {
+ fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
+ }
+ }()
+
+ handler()
+}
+
+func runHandlers() {
+ for _, handler := range handlers {
+ runHandler(handler)
+ }
+}
+
+// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
+func Exit(code int) {
+ runHandlers()
+ os.Exit(code)
+}
+
+// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
+// all handlers. The handlers will also be invoked when any Fatal log entry is
+// made.
+//
+// This method is useful when a caller wishes to use logrus to log a fatal
+// message but also needs to gracefully shutdown. An example usecase could be
+// closing database connections, or sending a alert that the application is
+// closing.
+func RegisterExitHandler(handler func()) {
+ handlers = append(handlers, handler)
+}
diff --git a/vendor/github.com/Sirupsen/logrus/doc.go b/vendor/github.com/Sirupsen/logrus/doc.go
new file mode 100644
index 0000000..dddd5f8
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/doc.go
@@ -0,0 +1,26 @@
+/*
+Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
+
+
+The simplest way to use Logrus is simply the package-level exported logger:
+
+ package main
+
+ import (
+ log "github.com/Sirupsen/logrus"
+ )
+
+ func main() {
+ log.WithFields(log.Fields{
+ "animal": "walrus",
+ "number": 1,
+ "size": 10,
+ }).Info("A walrus appears")
+ }
+
+Output:
+ time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
+
+For a full guide visit https://github.com/Sirupsen/logrus
+*/
+package logrus
diff --git a/vendor/github.com/Sirupsen/logrus/entry.go b/vendor/github.com/Sirupsen/logrus/entry.go
new file mode 100644
index 0000000..4edbe7a
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/entry.go
@@ -0,0 +1,275 @@
+package logrus
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "sync"
+ "time"
+)
+
+var bufferPool *sync.Pool
+
+func init() {
+ bufferPool = &sync.Pool{
+ New: func() interface{} {
+ return new(bytes.Buffer)
+ },
+ }
+}
+
+// Defines the key when adding errors using WithError.
+var ErrorKey = "error"
+
+// An entry is the final or intermediate Logrus logging entry. It contains all
+// the fields passed with WithField{,s}. It's finally logged when Debug, Info,
+// Warn, Error, Fatal or Panic is called on it. These objects can be reused and
+// passed around as much as you wish to avoid field duplication.
+type Entry struct {
+ Logger *Logger
+
+ // Contains all the fields set by the user.
+ Data Fields
+
+ // Time at which the log entry was created
+ Time time.Time
+
+ // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
+ Level Level
+
+ // Message passed to Debug, Info, Warn, Error, Fatal or Panic
+ Message string
+
+ // When formatter is called in entry.log(), an Buffer may be set to entry
+ Buffer *bytes.Buffer
+}
+
+func NewEntry(logger *Logger) *Entry {
+ return &Entry{
+ Logger: logger,
+ // Default is three fields, give a little extra room
+ Data: make(Fields, 5),
+ }
+}
+
+// Returns the string representation from the reader and ultimately the
+// formatter.
+func (entry *Entry) String() (string, error) {
+ serialized, err := entry.Logger.Formatter.Format(entry)
+ if err != nil {
+ return "", err
+ }
+ str := string(serialized)
+ return str, nil
+}
+
+// Add an error as single field (using the key defined in ErrorKey) to the Entry.
+func (entry *Entry) WithError(err error) *Entry {
+ return entry.WithField(ErrorKey, err)
+}
+
+// Add a single field to the Entry.
+func (entry *Entry) WithField(key string, value interface{}) *Entry {
+ return entry.WithFields(Fields{key: value})
+}
+
+// Add a map of fields to the Entry.
+func (entry *Entry) WithFields(fields Fields) *Entry {
+ data := make(Fields, len(entry.Data)+len(fields))
+ for k, v := range entry.Data {
+ data[k] = v
+ }
+ for k, v := range fields {
+ data[k] = v
+ }
+ return &Entry{Logger: entry.Logger, Data: data}
+}
+
+// This function is not declared with a pointer value because otherwise
+// race conditions will occur when using multiple goroutines
+func (entry Entry) log(level Level, msg string) {
+ var buffer *bytes.Buffer
+ entry.Time = time.Now()
+ entry.Level = level
+ entry.Message = msg
+
+ if err := entry.Logger.Hooks.Fire(level, &entry); err != nil {
+ entry.Logger.mu.Lock()
+ fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
+ entry.Logger.mu.Unlock()
+ }
+ buffer = bufferPool.Get().(*bytes.Buffer)
+ buffer.Reset()
+ defer bufferPool.Put(buffer)
+ entry.Buffer = buffer
+ serialized, err := entry.Logger.Formatter.Format(&entry)
+ entry.Buffer = nil
+ if err != nil {
+ entry.Logger.mu.Lock()
+ fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
+ entry.Logger.mu.Unlock()
+ } else {
+ entry.Logger.mu.Lock()
+ _, err = entry.Logger.Out.Write(serialized)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
+ }
+ entry.Logger.mu.Unlock()
+ }
+
+ // To avoid Entry#log() returning a value that only would make sense for
+ // panic() to use in Entry#Panic(), we avoid the allocation by checking
+ // directly here.
+ if level <= PanicLevel {
+ panic(&entry)
+ }
+}
+
+func (entry *Entry) Debug(args ...interface{}) {
+ if entry.Logger.Level >= DebugLevel {
+ entry.log(DebugLevel, fmt.Sprint(args...))
+ }
+}
+
+func (entry *Entry) Print(args ...interface{}) {
+ entry.Info(args...)
+}
+
+func (entry *Entry) Info(args ...interface{}) {
+ if entry.Logger.Level >= InfoLevel {
+ entry.log(InfoLevel, fmt.Sprint(args...))
+ }
+}
+
+func (entry *Entry) Warn(args ...interface{}) {
+ if entry.Logger.Level >= WarnLevel {
+ entry.log(WarnLevel, fmt.Sprint(args...))
+ }
+}
+
+func (entry *Entry) Warning(args ...interface{}) {
+ entry.Warn(args...)
+}
+
+func (entry *Entry) Error(args ...interface{}) {
+ if entry.Logger.Level >= ErrorLevel {
+ entry.log(ErrorLevel, fmt.Sprint(args...))
+ }
+}
+
+func (entry *Entry) Fatal(args ...interface{}) {
+ if entry.Logger.Level >= FatalLevel {
+ entry.log(FatalLevel, fmt.Sprint(args...))
+ }
+ Exit(1)
+}
+
+func (entry *Entry) Panic(args ...interface{}) {
+ if entry.Logger.Level >= PanicLevel {
+ entry.log(PanicLevel, fmt.Sprint(args...))
+ }
+ panic(fmt.Sprint(args...))
+}
+
+// Entry Printf family functions
+
+func (entry *Entry) Debugf(format string, args ...interface{}) {
+ if entry.Logger.Level >= DebugLevel {
+ entry.Debug(fmt.Sprintf(format, args...))
+ }
+}
+
+func (entry *Entry) Infof(format string, args ...interface{}) {
+ if entry.Logger.Level >= InfoLevel {
+ entry.Info(fmt.Sprintf(format, args...))
+ }
+}
+
+func (entry *Entry) Printf(format string, args ...interface{}) {
+ entry.Infof(format, args...)
+}
+
+func (entry *Entry) Warnf(format string, args ...interface{}) {
+ if entry.Logger.Level >= WarnLevel {
+ entry.Warn(fmt.Sprintf(format, args...))
+ }
+}
+
+func (entry *Entry) Warningf(format string, args ...interface{}) {
+ entry.Warnf(format, args...)
+}
+
+func (entry *Entry) Errorf(format string, args ...interface{}) {
+ if entry.Logger.Level >= ErrorLevel {
+ entry.Error(fmt.Sprintf(format, args...))
+ }
+}
+
+func (entry *Entry) Fatalf(format string, args ...interface{}) {
+ if entry.Logger.Level >= FatalLevel {
+ entry.Fatal(fmt.Sprintf(format, args...))
+ }
+ Exit(1)
+}
+
+func (entry *Entry) Panicf(format string, args ...interface{}) {
+ if entry.Logger.Level >= PanicLevel {
+ entry.Panic(fmt.Sprintf(format, args...))
+ }
+}
+
+// Entry Println family functions
+
+func (entry *Entry) Debugln(args ...interface{}) {
+ if entry.Logger.Level >= DebugLevel {
+ entry.Debug(entry.sprintlnn(args...))
+ }
+}
+
+func (entry *Entry) Infoln(args ...interface{}) {
+ if entry.Logger.Level >= InfoLevel {
+ entry.Info(entry.sprintlnn(args...))
+ }
+}
+
+func (entry *Entry) Println(args ...interface{}) {
+ entry.Infoln(args...)
+}
+
+func (entry *Entry) Warnln(args ...interface{}) {
+ if entry.Logger.Level >= WarnLevel {
+ entry.Warn(entry.sprintlnn(args...))
+ }
+}
+
+func (entry *Entry) Warningln(args ...interface{}) {
+ entry.Warnln(args...)
+}
+
+func (entry *Entry) Errorln(args ...interface{}) {
+ if entry.Logger.Level >= ErrorLevel {
+ entry.Error(entry.sprintlnn(args...))
+ }
+}
+
+func (entry *Entry) Fatalln(args ...interface{}) {
+ if entry.Logger.Level >= FatalLevel {
+ entry.Fatal(entry.sprintlnn(args...))
+ }
+ Exit(1)
+}
+
+func (entry *Entry) Panicln(args ...interface{}) {
+ if entry.Logger.Level >= PanicLevel {
+ entry.Panic(entry.sprintlnn(args...))
+ }
+}
+
+// Sprintlnn => Sprint no newline. This is to get the behavior of how
+// fmt.Sprintln where spaces are always added between operands, regardless of
+// their type. Instead of vendoring the Sprintln implementation to spare a
+// string allocation, we do the simplest thing.
+func (entry *Entry) sprintlnn(args ...interface{}) string {
+ msg := fmt.Sprintln(args...)
+ return msg[:len(msg)-1]
+}
diff --git a/vendor/github.com/Sirupsen/logrus/exported.go b/vendor/github.com/Sirupsen/logrus/exported.go
new file mode 100644
index 0000000..9a0120a
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/exported.go
@@ -0,0 +1,193 @@
+package logrus
+
+import (
+ "io"
+)
+
+var (
+ // std is the name of the standard logger in stdlib `log`
+ std = New()
+)
+
+func StandardLogger() *Logger {
+ return std
+}
+
+// SetOutput sets the standard logger output.
+func SetOutput(out io.Writer) {
+ std.mu.Lock()
+ defer std.mu.Unlock()
+ std.Out = out
+}
+
+// SetFormatter sets the standard logger formatter.
+func SetFormatter(formatter Formatter) {
+ std.mu.Lock()
+ defer std.mu.Unlock()
+ std.Formatter = formatter
+}
+
+// SetLevel sets the standard logger level.
+func SetLevel(level Level) {
+ std.mu.Lock()
+ defer std.mu.Unlock()
+ std.Level = level
+}
+
+// GetLevel returns the standard logger level.
+func GetLevel() Level {
+ std.mu.Lock()
+ defer std.mu.Unlock()
+ return std.Level
+}
+
+// AddHook adds a hook to the standard logger hooks.
+func AddHook(hook Hook) {
+ std.mu.Lock()
+ defer std.mu.Unlock()
+ std.Hooks.Add(hook)
+}
+
+// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
+func WithError(err error) *Entry {
+ return std.WithField(ErrorKey, err)
+}
+
+// WithField creates an entry from the standard logger and adds a field to
+// it. If you want multiple fields, use `WithFields`.
+//
+// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
+// or Panic on the Entry it returns.
+func WithField(key string, value interface{}) *Entry {
+ return std.WithField(key, value)
+}
+
+// WithFields creates an entry from the standard logger and adds multiple
+// fields to it. This is simply a helper for `WithField`, invoking it
+// once for each field.
+//
+// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
+// or Panic on the Entry it returns.
+func WithFields(fields Fields) *Entry {
+ return std.WithFields(fields)
+}
+
+// Debug logs a message at level Debug on the standard logger.
+func Debug(args ...interface{}) {
+ std.Debug(args...)
+}
+
+// Print logs a message at level Info on the standard logger.
+func Print(args ...interface{}) {
+ std.Print(args...)
+}
+
+// Info logs a message at level Info on the standard logger.
+func Info(args ...interface{}) {
+ std.Info(args...)
+}
+
+// Warn logs a message at level Warn on the standard logger.
+func Warn(args ...interface{}) {
+ std.Warn(args...)
+}
+
+// Warning logs a message at level Warn on the standard logger.
+func Warning(args ...interface{}) {
+ std.Warning(args...)
+}
+
+// Error logs a message at level Error on the standard logger.
+func Error(args ...interface{}) {
+ std.Error(args...)
+}
+
+// Panic logs a message at level Panic on the standard logger.
+func Panic(args ...interface{}) {
+ std.Panic(args...)
+}
+
+// Fatal logs a message at level Fatal on the standard logger.
+func Fatal(args ...interface{}) {
+ std.Fatal(args...)
+}
+
+// Debugf logs a message at level Debug on the standard logger.
+func Debugf(format string, args ...interface{}) {
+ std.Debugf(format, args...)
+}
+
+// Printf logs a message at level Info on the standard logger.
+func Printf(format string, args ...interface{}) {
+ std.Printf(format, args...)
+}
+
+// Infof logs a message at level Info on the standard logger.
+func Infof(format string, args ...interface{}) {
+ std.Infof(format, args...)
+}
+
+// Warnf logs a message at level Warn on the standard logger.
+func Warnf(format string, args ...interface{}) {
+ std.Warnf(format, args...)
+}
+
+// Warningf logs a message at level Warn on the standard logger.
+func Warningf(format string, args ...interface{}) {
+ std.Warningf(format, args...)
+}
+
+// Errorf logs a message at level Error on the standard logger.
+func Errorf(format string, args ...interface{}) {
+ std.Errorf(format, args...)
+}
+
+// Panicf logs a message at level Panic on the standard logger.
+func Panicf(format string, args ...interface{}) {
+ std.Panicf(format, args...)
+}
+
+// Fatalf logs a message at level Fatal on the standard logger.
+func Fatalf(format string, args ...interface{}) {
+ std.Fatalf(format, args...)
+}
+
+// Debugln logs a message at level Debug on the standard logger.
+func Debugln(args ...interface{}) {
+ std.Debugln(args...)
+}
+
+// Println logs a message at level Info on the standard logger.
+func Println(args ...interface{}) {
+ std.Println(args...)
+}
+
+// Infoln logs a message at level Info on the standard logger.
+func Infoln(args ...interface{}) {
+ std.Infoln(args...)
+}
+
+// Warnln logs a message at level Warn on the standard logger.
+func Warnln(args ...interface{}) {
+ std.Warnln(args...)
+}
+
+// Warningln logs a message at level Warn on the standard logger.
+func Warningln(args ...interface{}) {
+ std.Warningln(args...)
+}
+
+// Errorln logs a message at level Error on the standard logger.
+func Errorln(args ...interface{}) {
+ std.Errorln(args...)
+}
+
+// Panicln logs a message at level Panic on the standard logger.
+func Panicln(args ...interface{}) {
+ std.Panicln(args...)
+}
+
+// Fatalln logs a message at level Fatal on the standard logger.
+func Fatalln(args ...interface{}) {
+ std.Fatalln(args...)
+}
diff --git a/vendor/github.com/Sirupsen/logrus/formatter.go b/vendor/github.com/Sirupsen/logrus/formatter.go
new file mode 100644
index 0000000..b5fbe93
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/formatter.go
@@ -0,0 +1,45 @@
+package logrus
+
+import "time"
+
+const DefaultTimestampFormat = time.RFC3339
+
+// The Formatter interface is used to implement a custom Formatter. It takes an
+// `Entry`. It exposes all the fields, including the default ones:
+//
+// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
+// * `entry.Data["time"]`. The timestamp.
+// * `entry.Data["level"]. The level the entry was logged at.
+//
+// Any additional fields added with `WithField` or `WithFields` are also in
+// `entry.Data`. Format is expected to return an array of bytes which are then
+// logged to `logger.Out`.
+type Formatter interface {
+ Format(*Entry) ([]byte, error)
+}
+
+// This is to not silently overwrite `time`, `msg` and `level` fields when
+// dumping it. If this code wasn't there doing:
+//
+// logrus.WithField("level", 1).Info("hello")
+//
+// Would just silently drop the user provided level. Instead with this code
+// it'll logged as:
+//
+// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
+//
+// It's not exported because it's still using Data in an opinionated way. It's to
+// avoid code duplication between the two default formatters.
+func prefixFieldClashes(data Fields) {
+ if t, ok := data["time"]; ok {
+ data["fields.time"] = t
+ }
+
+ if m, ok := data["msg"]; ok {
+ data["fields.msg"] = m
+ }
+
+ if l, ok := data["level"]; ok {
+ data["fields.level"] = l
+ }
+}
diff --git a/vendor/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/Sirupsen/logrus/hooks.go
new file mode 100644
index 0000000..3f151cd
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/hooks.go
@@ -0,0 +1,34 @@
+package logrus
+
+// A hook to be fired when logging on the logging levels returned from
+// `Levels()` on your implementation of the interface. Note that this is not
+// fired in a goroutine or a channel with workers, you should handle such
+// functionality yourself if your call is non-blocking and you don't wish for
+// the logging calls for levels returned from `Levels()` to block.
+type Hook interface {
+ Levels() []Level
+ Fire(*Entry) error
+}
+
+// Internal type for storing the hooks on a logger instance.
+type LevelHooks map[Level][]Hook
+
+// Add a hook to an instance of logger. This is called with
+// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
+func (hooks LevelHooks) Add(hook Hook) {
+ for _, level := range hook.Levels() {
+ hooks[level] = append(hooks[level], hook)
+ }
+}
+
+// Fire all the hooks for the passed level. Used by `entry.log` to fire
+// appropriate hooks for a log entry.
+func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
+ for _, hook := range hooks[level] {
+ if err := hook.Fire(entry); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/Sirupsen/logrus/json_formatter.go b/vendor/github.com/Sirupsen/logrus/json_formatter.go
new file mode 100644
index 0000000..2ad6dc5
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/json_formatter.go
@@ -0,0 +1,41 @@
+package logrus
+
+import (
+ "encoding/json"
+ "fmt"
+)
+
+type JSONFormatter struct {
+ // TimestampFormat sets the format used for marshaling timestamps.
+ TimestampFormat string
+}
+
+func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
+ data := make(Fields, len(entry.Data)+3)
+ for k, v := range entry.Data {
+ switch v := v.(type) {
+ case error:
+ // Otherwise errors are ignored by `encoding/json`
+ // https://github.com/Sirupsen/logrus/issues/137
+ data[k] = v.Error()
+ default:
+ data[k] = v
+ }
+ }
+ prefixFieldClashes(data)
+
+ timestampFormat := f.TimestampFormat
+ if timestampFormat == "" {
+ timestampFormat = DefaultTimestampFormat
+ }
+
+ data["time"] = entry.Time.Format(timestampFormat)
+ data["msg"] = entry.Message
+ data["level"] = entry.Level.String()
+
+ serialized, err := json.Marshal(data)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
+ }
+ return append(serialized, '\n'), nil
+}
diff --git a/vendor/github.com/Sirupsen/logrus/logger.go b/vendor/github.com/Sirupsen/logrus/logger.go
new file mode 100644
index 0000000..b769f3d
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/logger.go
@@ -0,0 +1,308 @@
+package logrus
+
+import (
+ "io"
+ "os"
+ "sync"
+)
+
+type Logger struct {
+ // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
+ // file, or leave it default which is `os.Stderr`. You can also set this to
+ // something more adventorous, such as logging to Kafka.
+ Out io.Writer
+ // Hooks for the logger instance. These allow firing events based on logging
+ // levels and log entries. For example, to send errors to an error tracking
+ // service, log to StatsD or dump the core on fatal errors.
+ Hooks LevelHooks
+ // All log entries pass through the formatter before logged to Out. The
+ // included formatters are `TextFormatter` and `JSONFormatter` for which
+ // TextFormatter is the default. In development (when a TTY is attached) it
+ // logs with colors, but to a file it wouldn't. You can easily implement your
+ // own that implements the `Formatter` interface, see the `README` or included
+ // formatters for examples.
+ Formatter Formatter
+ // The logging level the logger should log at. This is typically (and defaults
+ // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
+ // logged. `logrus.Debug` is useful in
+ Level Level
+ // Used to sync writing to the log. Locking is enabled by Default
+ mu MutexWrap
+ // Reusable empty entry
+ entryPool sync.Pool
+}
+
+type MutexWrap struct {
+ lock sync.Mutex
+ disabled bool
+}
+
+func (mw *MutexWrap) Lock() {
+ if !mw.disabled {
+ mw.lock.Lock()
+ }
+}
+
+func (mw *MutexWrap) Unlock() {
+ if !mw.disabled {
+ mw.lock.Unlock()
+ }
+}
+
+func (mw *MutexWrap) Disable() {
+ mw.disabled = true
+}
+
+// Creates a new logger. Configuration should be set by changing `Formatter`,
+// `Out` and `Hooks` directly on the default logger instance. You can also just
+// instantiate your own:
+//
+// var log = &Logger{
+// Out: os.Stderr,
+// Formatter: new(JSONFormatter),
+// Hooks: make(LevelHooks),
+// Level: logrus.DebugLevel,
+// }
+//
+// It's recommended to make this a global instance called `log`.
+func New() *Logger {
+ return &Logger{
+ Out: os.Stderr,
+ Formatter: new(TextFormatter),
+ Hooks: make(LevelHooks),
+ Level: InfoLevel,
+ }
+}
+
+func (logger *Logger) newEntry() *Entry {
+ entry, ok := logger.entryPool.Get().(*Entry)
+ if ok {
+ return entry
+ }
+ return NewEntry(logger)
+}
+
+func (logger *Logger) releaseEntry(entry *Entry) {
+ logger.entryPool.Put(entry)
+}
+
+// Adds a field to the log entry, note that it doesn't log until you call
+// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.
+// If you want multiple fields, use `WithFields`.
+func (logger *Logger) WithField(key string, value interface{}) *Entry {
+ entry := logger.newEntry()
+ defer logger.releaseEntry(entry)
+ return entry.WithField(key, value)
+}
+
+// Adds a struct of fields to the log entry. All it does is call `WithField` for
+// each `Field`.
+func (logger *Logger) WithFields(fields Fields) *Entry {
+ entry := logger.newEntry()
+ defer logger.releaseEntry(entry)
+ return entry.WithFields(fields)
+}
+
+// Add an error as single field to the log entry. All it does is call
+// `WithError` for the given `error`.
+func (logger *Logger) WithError(err error) *Entry {
+ entry := logger.newEntry()
+ defer logger.releaseEntry(entry)
+ return entry.WithError(err)
+}
+
+func (logger *Logger) Debugf(format string, args ...interface{}) {
+ if logger.Level >= DebugLevel {
+ entry := logger.newEntry()
+ entry.Debugf(format, args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Infof(format string, args ...interface{}) {
+ if logger.Level >= InfoLevel {
+ entry := logger.newEntry()
+ entry.Infof(format, args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Printf(format string, args ...interface{}) {
+ entry := logger.newEntry()
+ entry.Printf(format, args...)
+ logger.releaseEntry(entry)
+}
+
+func (logger *Logger) Warnf(format string, args ...interface{}) {
+ if logger.Level >= WarnLevel {
+ entry := logger.newEntry()
+ entry.Warnf(format, args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Warningf(format string, args ...interface{}) {
+ if logger.Level >= WarnLevel {
+ entry := logger.newEntry()
+ entry.Warnf(format, args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Errorf(format string, args ...interface{}) {
+ if logger.Level >= ErrorLevel {
+ entry := logger.newEntry()
+ entry.Errorf(format, args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Fatalf(format string, args ...interface{}) {
+ if logger.Level >= FatalLevel {
+ entry := logger.newEntry()
+ entry.Fatalf(format, args...)
+ logger.releaseEntry(entry)
+ }
+ Exit(1)
+}
+
+func (logger *Logger) Panicf(format string, args ...interface{}) {
+ if logger.Level >= PanicLevel {
+ entry := logger.newEntry()
+ entry.Panicf(format, args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Debug(args ...interface{}) {
+ if logger.Level >= DebugLevel {
+ entry := logger.newEntry()
+ entry.Debug(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Info(args ...interface{}) {
+ if logger.Level >= InfoLevel {
+ entry := logger.newEntry()
+ entry.Info(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Print(args ...interface{}) {
+ entry := logger.newEntry()
+ entry.Info(args...)
+ logger.releaseEntry(entry)
+}
+
+func (logger *Logger) Warn(args ...interface{}) {
+ if logger.Level >= WarnLevel {
+ entry := logger.newEntry()
+ entry.Warn(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Warning(args ...interface{}) {
+ if logger.Level >= WarnLevel {
+ entry := logger.newEntry()
+ entry.Warn(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Error(args ...interface{}) {
+ if logger.Level >= ErrorLevel {
+ entry := logger.newEntry()
+ entry.Error(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Fatal(args ...interface{}) {
+ if logger.Level >= FatalLevel {
+ entry := logger.newEntry()
+ entry.Fatal(args...)
+ logger.releaseEntry(entry)
+ }
+ Exit(1)
+}
+
+func (logger *Logger) Panic(args ...interface{}) {
+ if logger.Level >= PanicLevel {
+ entry := logger.newEntry()
+ entry.Panic(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Debugln(args ...interface{}) {
+ if logger.Level >= DebugLevel {
+ entry := logger.newEntry()
+ entry.Debugln(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Infoln(args ...interface{}) {
+ if logger.Level >= InfoLevel {
+ entry := logger.newEntry()
+ entry.Infoln(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Println(args ...interface{}) {
+ entry := logger.newEntry()
+ entry.Println(args...)
+ logger.releaseEntry(entry)
+}
+
+func (logger *Logger) Warnln(args ...interface{}) {
+ if logger.Level >= WarnLevel {
+ entry := logger.newEntry()
+ entry.Warnln(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Warningln(args ...interface{}) {
+ if logger.Level >= WarnLevel {
+ entry := logger.newEntry()
+ entry.Warnln(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Errorln(args ...interface{}) {
+ if logger.Level >= ErrorLevel {
+ entry := logger.newEntry()
+ entry.Errorln(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+func (logger *Logger) Fatalln(args ...interface{}) {
+ if logger.Level >= FatalLevel {
+ entry := logger.newEntry()
+ entry.Fatalln(args...)
+ logger.releaseEntry(entry)
+ }
+ Exit(1)
+}
+
+func (logger *Logger) Panicln(args ...interface{}) {
+ if logger.Level >= PanicLevel {
+ entry := logger.newEntry()
+ entry.Panicln(args...)
+ logger.releaseEntry(entry)
+ }
+}
+
+//When file is opened with appending mode, it's safe to
+//write concurrently to a file (within 4k message on Linux).
+//In these cases user can choose to disable the lock.
+func (logger *Logger) SetNoLock() {
+ logger.mu.Disable()
+}
diff --git a/vendor/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/Sirupsen/logrus/logrus.go
new file mode 100644
index 0000000..e596691
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/logrus.go
@@ -0,0 +1,143 @@
+package logrus
+
+import (
+ "fmt"
+ "log"
+ "strings"
+)
+
+// Fields type, used to pass to `WithFields`.
+type Fields map[string]interface{}
+
+// Level type
+type Level uint8
+
+// Convert the Level to a string. E.g. PanicLevel becomes "panic".
+func (level Level) String() string {
+ switch level {
+ case DebugLevel:
+ return "debug"
+ case InfoLevel:
+ return "info"
+ case WarnLevel:
+ return "warning"
+ case ErrorLevel:
+ return "error"
+ case FatalLevel:
+ return "fatal"
+ case PanicLevel:
+ return "panic"
+ }
+
+ return "unknown"
+}
+
+// ParseLevel takes a string level and returns the Logrus log level constant.
+func ParseLevel(lvl string) (Level, error) {
+ switch strings.ToLower(lvl) {
+ case "panic":
+ return PanicLevel, nil
+ case "fatal":
+ return FatalLevel, nil
+ case "error":
+ return ErrorLevel, nil
+ case "warn", "warning":
+ return WarnLevel, nil
+ case "info":
+ return InfoLevel, nil
+ case "debug":
+ return DebugLevel, nil
+ }
+
+ var l Level
+ return l, fmt.Errorf("not a valid logrus Level: %q", lvl)
+}
+
+// A constant exposing all logging levels
+var AllLevels = []Level{
+ PanicLevel,
+ FatalLevel,
+ ErrorLevel,
+ WarnLevel,
+ InfoLevel,
+ DebugLevel,
+}
+
+// These are the different logging levels. You can set the logging level to log
+// on your instance of logger, obtained with `logrus.New()`.
+const (
+ // PanicLevel level, highest level of severity. Logs and then calls panic with the
+ // message passed to Debug, Info, ...
+ PanicLevel Level = iota
+ // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the
+ // logging level is set to Panic.
+ FatalLevel
+ // ErrorLevel level. Logs. Used for errors that should definitely be noted.
+ // Commonly used for hooks to send errors to an error tracking service.
+ ErrorLevel
+ // WarnLevel level. Non-critical entries that deserve eyes.
+ WarnLevel
+ // InfoLevel level. General operational entries about what's going on inside the
+ // application.
+ InfoLevel
+ // DebugLevel level. Usually only enabled when debugging. Very verbose logging.
+ DebugLevel
+)
+
+// Won't compile if StdLogger can't be realized by a log.Logger
+var (
+ _ StdLogger = &log.Logger{}
+ _ StdLogger = &Entry{}
+ _ StdLogger = &Logger{}
+)
+
+// StdLogger is what your logrus-enabled library should take, that way
+// it'll accept a stdlib logger and a logrus logger. There's no standard
+// interface, this is the closest we get, unfortunately.
+type StdLogger interface {
+ Print(...interface{})
+ Printf(string, ...interface{})
+ Println(...interface{})
+
+ Fatal(...interface{})
+ Fatalf(string, ...interface{})
+ Fatalln(...interface{})
+
+ Panic(...interface{})
+ Panicf(string, ...interface{})
+ Panicln(...interface{})
+}
+
+// The FieldLogger interface generalizes the Entry and Logger types
+type FieldLogger interface {
+ WithField(key string, value interface{}) *Entry
+ WithFields(fields Fields) *Entry
+ WithError(err error) *Entry
+
+ Debugf(format string, args ...interface{})
+ Infof(format string, args ...interface{})
+ Printf(format string, args ...interface{})
+ Warnf(format string, args ...interface{})
+ Warningf(format string, args ...interface{})
+ Errorf(format string, args ...interface{})
+ Fatalf(format string, args ...interface{})
+ Panicf(format string, args ...interface{})
+
+ Debug(args ...interface{})
+ Info(args ...interface{})
+ Print(args ...interface{})
+ Warn(args ...interface{})
+ Warning(args ...interface{})
+ Error(args ...interface{})
+ Fatal(args ...interface{})
+ Panic(args ...interface{})
+
+ Debugln(args ...interface{})
+ Infoln(args ...interface{})
+ Println(args ...interface{})
+ Warnln(args ...interface{})
+ Warningln(args ...interface{})
+ Errorln(args ...interface{})
+ Fatalln(args ...interface{})
+ Panicln(args ...interface{})
+}
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_appengine.go b/vendor/github.com/Sirupsen/logrus/terminal_appengine.go
new file mode 100644
index 0000000..1960169
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/terminal_appengine.go
@@ -0,0 +1,8 @@
+// +build appengine
+
+package logrus
+
+// IsTerminal returns true if stderr's file descriptor is a terminal.
+func IsTerminal() bool {
+ return true
+}
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go b/vendor/github.com/Sirupsen/logrus/terminal_bsd.go
new file mode 100644
index 0000000..5f6be4d
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/terminal_bsd.go
@@ -0,0 +1,10 @@
+// +build darwin freebsd openbsd netbsd dragonfly
+// +build !appengine
+
+package logrus
+
+import "syscall"
+
+const ioctlReadTermios = syscall.TIOCGETA
+
+type Termios syscall.Termios
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_linux.go b/vendor/github.com/Sirupsen/logrus/terminal_linux.go
new file mode 100644
index 0000000..308160c
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/terminal_linux.go
@@ -0,0 +1,14 @@
+// Based on ssh/terminal:
+// 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.
+
+// +build !appengine
+
+package logrus
+
+import "syscall"
+
+const ioctlReadTermios = syscall.TCGETS
+
+type Termios syscall.Termios
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go b/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
new file mode 100644
index 0000000..329038f
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
@@ -0,0 +1,22 @@
+// Based on ssh/terminal:
+// 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.
+
+// +build linux darwin freebsd openbsd netbsd dragonfly
+// +build !appengine
+
+package logrus
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// IsTerminal returns true if stderr's file descriptor is a terminal.
+func IsTerminal() bool {
+ fd := syscall.Stderr
+ var termios Termios
+ _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
+ return err == 0
+}
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_solaris.go b/vendor/github.com/Sirupsen/logrus/terminal_solaris.go
new file mode 100644
index 0000000..a3c6f6e
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/terminal_solaris.go
@@ -0,0 +1,15 @@
+// +build solaris,!appengine
+
+package logrus
+
+import (
+ "os"
+
+ "golang.org/x/sys/unix"
+)
+
+// IsTerminal returns true if the given file descriptor is a terminal.
+func IsTerminal() bool {
+ _, err := unix.IoctlGetTermios(int(os.Stdout.Fd()), unix.TCGETA)
+ return err == nil
+}
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_windows.go b/vendor/github.com/Sirupsen/logrus/terminal_windows.go
new file mode 100644
index 0000000..3727e8a
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/terminal_windows.go
@@ -0,0 +1,27 @@
+// Based on ssh/terminal:
+// 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.
+
+// +build windows,!appengine
+
+package logrus
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var kernel32 = syscall.NewLazyDLL("kernel32.dll")
+
+var (
+ procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
+)
+
+// IsTerminal returns true if stderr's file descriptor is a terminal.
+func IsTerminal() bool {
+ fd := syscall.Stderr
+ var st uint32
+ r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
+ return r != 0 && e == 0
+}
diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/Sirupsen/logrus/text_formatter.go
new file mode 100644
index 0000000..9114b3c
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/text_formatter.go
@@ -0,0 +1,168 @@
+package logrus
+
+import (
+ "bytes"
+ "fmt"
+ "runtime"
+ "sort"
+ "strings"
+ "time"
+)
+
+const (
+ nocolor = 0
+ red = 31
+ green = 32
+ yellow = 33
+ blue = 34
+ gray = 37
+)
+
+var (
+ baseTimestamp time.Time
+ isTerminal bool
+)
+
+func init() {
+ baseTimestamp = time.Now()
+ 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
+
+ // Force disabling colors.
+ DisableColors bool
+
+ // Disable timestamp logging. useful when output is redirected to logging
+ // system that already adds timestamps.
+ DisableTimestamp bool
+
+ // Enable logging the full timestamp when a TTY is attached instead of just
+ // the time passed since beginning of execution.
+ FullTimestamp bool
+
+ // TimestampFormat to use for display when a full timestamp is printed
+ TimestampFormat string
+
+ // The fields are sorted by default for a consistent output. For applications
+ // that log extremely frequently and don't use the JSON formatter this may not
+ // be desired.
+ DisableSorting bool
+}
+
+func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
+ var b *bytes.Buffer
+ var keys []string = make([]string, 0, len(entry.Data))
+ for k := range entry.Data {
+ keys = append(keys, k)
+ }
+
+ if !f.DisableSorting {
+ sort.Strings(keys)
+ }
+ if entry.Buffer != nil {
+ b = entry.Buffer
+ } else {
+ b = &bytes.Buffer{}
+ }
+
+ prefixFieldClashes(entry.Data)
+
+ isColorTerminal := isTerminal && (runtime.GOOS != "windows")
+ isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors
+
+ timestampFormat := f.TimestampFormat
+ if timestampFormat == "" {
+ timestampFormat = DefaultTimestampFormat
+ }
+ if isColored {
+ f.printColored(b, entry, keys, timestampFormat)
+ } else {
+ if !f.DisableTimestamp {
+ f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
+ }
+ f.appendKeyValue(b, "level", entry.Level.String())
+ if entry.Message != "" {
+ f.appendKeyValue(b, "msg", entry.Message)
+ }
+ for _, key := range keys {
+ f.appendKeyValue(b, key, entry.Data[key])
+ }
+ }
+
+ b.WriteByte('\n')
+ return b.Bytes(), nil
+}
+
+func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) {
+ var levelColor int
+ switch entry.Level {
+ case DebugLevel:
+ levelColor = gray
+ case WarnLevel:
+ levelColor = yellow
+ case ErrorLevel, FatalLevel, PanicLevel:
+ levelColor = red
+ default:
+ levelColor = blue
+ }
+
+ 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)
+ } else {
+ fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
+ }
+ for _, k := range keys {
+ v := entry.Data[k]
+ fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
+ f.appendValue(b, v)
+ }
+}
+
+func needsQuoting(text string) bool {
+ for _, ch := range text {
+ if !((ch >= 'a' && ch <= 'z') ||
+ (ch >= 'A' && ch <= 'Z') ||
+ (ch >= '0' && ch <= '9') ||
+ ch == '-' || ch == '.') {
+ return true
+ }
+ }
+ return false
+}
+
+func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
+
+ b.WriteString(key)
+ b.WriteByte('=')
+ f.appendValue(b, value)
+ b.WriteByte(' ')
+}
+
+func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
+ switch value := value.(type) {
+ case string:
+ if !needsQuoting(value) {
+ b.WriteString(value)
+ } else {
+ fmt.Fprintf(b, "%q", value)
+ }
+ case error:
+ errmsg := value.Error()
+ if !needsQuoting(errmsg) {
+ b.WriteString(errmsg)
+ } else {
+ fmt.Fprintf(b, "%q", errmsg)
+ }
+ default:
+ fmt.Fprint(b, value)
+ }
+}
diff --git a/vendor/github.com/Sirupsen/logrus/writer.go b/vendor/github.com/Sirupsen/logrus/writer.go
new file mode 100644
index 0000000..f74d2aa
--- /dev/null
+++ b/vendor/github.com/Sirupsen/logrus/writer.go
@@ -0,0 +1,53 @@
+package logrus
+
+import (
+ "bufio"
+ "io"
+ "runtime"
+)
+
+func (logger *Logger) Writer() *io.PipeWriter {
+ return logger.WriterLevel(InfoLevel)
+}
+
+func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
+ reader, writer := io.Pipe()
+
+ var printFunc func(args ...interface{})
+ switch level {
+ case DebugLevel:
+ printFunc = logger.Debug
+ case InfoLevel:
+ printFunc = logger.Info
+ case WarnLevel:
+ printFunc = logger.Warn
+ case ErrorLevel:
+ printFunc = logger.Error
+ case FatalLevel:
+ printFunc = logger.Fatal
+ case PanicLevel:
+ printFunc = logger.Panic
+ default:
+ printFunc = logger.Print
+ }
+
+ go logger.writerScanner(reader, printFunc)
+ runtime.SetFinalizer(writer, writerFinalizer)
+
+ return writer
+}
+
+func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
+ scanner := bufio.NewScanner(reader)
+ for scanner.Scan() {
+ printFunc(scanner.Text())
+ }
+ if err := scanner.Err(); err != nil {
+ logger.Errorf("Error while reading from Writer: %s", err)
+ }
+ reader.Close()
+}
+
+func writerFinalizer(writer *io.PipeWriter) {
+ writer.Close()
+}
diff --git a/vendor/github.com/agl/ed25519/LICENSE b/vendor/github.com/agl/ed25519/LICENSE
new file mode 100644
index 0000000..7448756
--- /dev/null
+++ b/vendor/github.com/agl/ed25519/LICENSE
@@ -0,0 +1,27 @@
+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/agl/ed25519/ed25519.go b/vendor/github.com/agl/ed25519/ed25519.go
new file mode 100644
index 0000000..700938d
--- /dev/null
+++ b/vendor/github.com/agl/ed25519/ed25519.go
@@ -0,0 +1,125 @@
+// 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 ed25519 implements the Ed25519 signature algorithm. See
+// http://ed25519.cr.yp.to/.
+package ed25519
+
+// This code is a port of the public domain, "ref10" implementation of ed25519
+// from SUPERCOP.
+
+import (
+ "crypto/sha512"
+ "crypto/subtle"
+ "io"
+
+ "github.com/agl/ed25519/edwards25519"
+)
+
+const (
+ PublicKeySize = 32
+ PrivateKeySize = 64
+ SignatureSize = 64
+)
+
+// GenerateKey generates a public/private key pair using randomness from rand.
+func GenerateKey(rand io.Reader) (publicKey *[PublicKeySize]byte, privateKey *[PrivateKeySize]byte, err error) {
+ privateKey = new([64]byte)
+ publicKey = new([32]byte)
+ _, err = io.ReadFull(rand, privateKey[:32])
+ if err != nil {
+ return nil, nil, err
+ }
+
+ h := sha512.New()
+ h.Write(privateKey[:32])
+ digest := h.Sum(nil)
+
+ digest[0] &= 248
+ digest[31] &= 127
+ digest[31] |= 64
+
+ var A edwards25519.ExtendedGroupElement
+ var hBytes [32]byte
+ copy(hBytes[:], digest)
+ edwards25519.GeScalarMultBase(&A, &hBytes)
+ A.ToBytes(publicKey)
+
+ copy(privateKey[32:], publicKey[:])
+ return
+}
+
+// Sign signs the message with privateKey and returns a signature.
+func Sign(privateKey *[PrivateKeySize]byte, message []byte) *[SignatureSize]byte {
+ 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 := new([64]byte)
+ copy(signature[:], encodedR[:])
+ copy(signature[32:], s[:])
+ return signature
+}
+
+// Verify returns true iff sig is a valid signature of message by publicKey.
+func Verify(publicKey *[PublicKeySize]byte, message []byte, sig *[SignatureSize]byte) bool {
+ if sig[63]&224 != 0 {
+ return false
+ }
+
+ var A edwards25519.ExtendedGroupElement
+ if !A.FromBytes(publicKey) {
+ return false
+ }
+
+ 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/github.com/agl/ed25519/edwards25519/const.go b/vendor/github.com/agl/ed25519/edwards25519/const.go
new file mode 100644
index 0000000..ea5b77a
--- /dev/null
+++ b/vendor/github.com/agl/ed25519/edwards25519/const.go
@@ -0,0 +1,1411 @@
+// 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 edwards25519
+
+var d = FieldElement{
+ -10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116,
+}
+
+var d2 = FieldElement{
+ -21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199,
+}
+
+var SqrtM1 = FieldElement{
+ -32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482,
+}
+
+var A = FieldElement{
+ 486662, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+}
+
+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},
+ },
+}
+
+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/github.com/agl/ed25519/edwards25519/edwards25519.go b/vendor/github.com/agl/ed25519/edwards25519/edwards25519.go
new file mode 100644
index 0000000..184b4a8
--- /dev/null
+++ b/vendor/github.com/agl/ed25519/edwards25519/edwards25519.go
@@ -0,0 +1,2127 @@
+// 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 edwards25519 implements operations in GF(2**255-19) and on an
+// Edwards curve that is isomorphic to curve25519. See
+// http://ed25519.cr.yp.to/.
+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
+
+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]
+ }
+}
+
+// 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) {
+ var x FieldElement
+ b = -b
+ for i := range x {
+ x[i] = b & (f[i] ^ g[i])
+ }
+
+ for i := range f {
+ f[i] ^= x[i]
+ }
+}
+
+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
+
+ 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<y<1.
+//
+// Write r=h-pq.
+// Have 0<=r<=p-1=2^255-20.
+// Thus 0<=r+19(2^-255)r<r+19(2^-255)2^255<=2^255-1.
+//
+// Write x=r+19(2^-255)r+y.
+// Then 0<x<2^255 so floor(2^(-255)x) = 0 so floor(q+2^(-255)x) = q.
+//
+// Have q+2^(-255)x = 2^(-255)(h + 19 2^(-25) h9 + 2^(-1))
+// so floor(2^(-255)(h + 19 2^(-25) h9 + 2^(-1))) = q.
+func FeToBytes(s *[32]byte, h *FieldElement) {
+ var carry [10]int32
+
+ q := (19*h[9] + (1 << 24)) >> 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) {
+ for i := range h {
+ h[i] = -f[i]
+ }
+}
+
+// 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)
+}
+
+// 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) {
+ 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.959375*2^30
+ f6_19 := 19 * f6 // 1.959375*2^30
+ f7_38 := 38 * f7 // 1.959375*2^30
+ f8_19 := 19 * f8 // 1.959375*2^30
+ f9_38 := 38 * f9 // 1.959375*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
+
+ h0 += h0
+ h1 += h1
+ h2 += h2
+ h3 += h3
+ h4 += h4
+ h5 += h5
+ h6 += h6
+ h7 += h7
+ h8 += h8
+ h9 += 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
+
+ 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)
+}
+
+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]<<uint(b)) <= 15 {
+ r[i] += r[i+b] << uint(b)
+ r[i+b] = 0
+ } else if r[i]-(r[i+b]<<uint(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.
+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/github.com/armon/go-metrics/LICENSE b/vendor/github.com/armon/go-metrics/LICENSE
new file mode 100644
index 0000000..106569e
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Armon Dadgar
+
+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/armon/go-metrics/README.md b/vendor/github.com/armon/go-metrics/README.md
new file mode 100644
index 0000000..d9f46e8
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/README.md
@@ -0,0 +1,68 @@
+go-metrics
+==========
+
+This library provides a `metrics` package which can be used to instrument code,
+expose application metrics, and profile runtime performance in a flexible manner.
+
+Sinks
+=====
+
+The `metrics` package makes use of a `MetricSink` interface to support delivery
+to any type of backend. Currently the following sinks are provided:
+
+* StatsiteSink : Sinks to a statsite instance (TCP)
+* StatsdSink: Sinks to a statsd / statsite instance (UDP)
+* InmemSink : Provides in-memory aggregation, can be used to export stats
+* FanoutSink : Sinks to multiple sinks. Enables writing to multiple statsite instances for example.
+* BlackholeSink : Sinks to nowhere
+
+In addition to the sinks, the `InmemSignal` can be used to catch a signal,
+and dump a formatted output of recent metrics. For example, when a process gets
+a SIGUSR1, it can dump to stderr recent performance metrics for debugging.
+
+Examples
+========
+
+Here is an example of using the package:
+
+ func SlowMethod() {
+ // Profiling the runtime of a method
+ defer metrics.MeasureSince([]string{"SlowMethod"}, time.Now())
+ }
+
+ // Configure a statsite sink as the global metrics sink
+ sink, _ := metrics.NewStatsiteSink("statsite:8125")
+ metrics.NewGlobal(metrics.DefaultConfig("service-name"), sink)
+
+ // Emit a Key/Value pair
+ metrics.EmitKey([]string{"questions", "meaning of life"}, 42)
+
+
+Here is an example of setting up an signal handler:
+
+ // Setup the inmem sink and signal handler
+ inm := NewInmemSink(10*time.Second, time.Minute)
+ sig := DefaultInmemSignal(inm)
+ metrics.NewGlobal(metrics.DefaultConfig("service-name"), inm)
+
+ // Run some code
+ inm.SetGauge([]string{"foo"}, 42)
+ inm.EmitKey([]string{"bar"}, 30)
+
+ inm.IncrCounter([]string{"baz"}, 42)
+ inm.IncrCounter([]string{"baz"}, 1)
+ inm.IncrCounter([]string{"baz"}, 80)
+
+ inm.AddSample([]string{"method", "wow"}, 42)
+ inm.AddSample([]string{"method", "wow"}, 100)
+ inm.AddSample([]string{"method", "wow"}, 22)
+
+ ....
+
+When a signal comes in, output like the following will be dumped to stderr:
+
+ [2014-01-28 14:57:33.04 -0800 PST][G] 'foo': 42.000
+ [2014-01-28 14:57:33.04 -0800 PST][P] 'bar': 30.000
+ [2014-01-28 14:57:33.04 -0800 PST][C] 'baz': Count: 3 Min: 1.000 Mean: 41.000 Max: 80.000 Stddev: 39.509
+ [2014-01-28 14:57:33.04 -0800 PST][S] 'method.wow': Count: 3 Min: 22.000 Mean: 54.667 Max: 100.000 Stddev: 40.513
+
diff --git a/vendor/github.com/armon/go-metrics/const_unix.go b/vendor/github.com/armon/go-metrics/const_unix.go
new file mode 100644
index 0000000..31098dd
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/const_unix.go
@@ -0,0 +1,12 @@
+// +build !windows
+
+package metrics
+
+import (
+ "syscall"
+)
+
+const (
+ // DefaultSignal is used with DefaultInmemSignal
+ DefaultSignal = syscall.SIGUSR1
+)
diff --git a/vendor/github.com/armon/go-metrics/const_windows.go b/vendor/github.com/armon/go-metrics/const_windows.go
new file mode 100644
index 0000000..38136af
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/const_windows.go
@@ -0,0 +1,13 @@
+// +build windows
+
+package metrics
+
+import (
+ "syscall"
+)
+
+const (
+ // DefaultSignal is used with DefaultInmemSignal
+ // Windows has no SIGUSR1, use SIGBREAK
+ DefaultSignal = syscall.Signal(21)
+)
diff --git a/vendor/github.com/armon/go-metrics/inmem.go b/vendor/github.com/armon/go-metrics/inmem.go
new file mode 100644
index 0000000..0749229
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/inmem.go
@@ -0,0 +1,239 @@
+package metrics
+
+import (
+ "fmt"
+ "math"
+ "strings"
+ "sync"
+ "time"
+)
+
+// InmemSink provides a MetricSink that does in-memory aggregation
+// without sending metrics over a network. It can be embedded within
+// an application to provide profiling information.
+type InmemSink struct {
+ // How long is each aggregation interval
+ interval time.Duration
+
+ // Retain controls how many metrics interval we keep
+ retain time.Duration
+
+ // maxIntervals is the maximum length of intervals.
+ // It is retain / interval.
+ maxIntervals int
+
+ // intervals is a slice of the retained intervals
+ intervals []*IntervalMetrics
+ intervalLock sync.RWMutex
+}
+
+// IntervalMetrics stores the aggregated metrics
+// for a specific interval
+type IntervalMetrics struct {
+ sync.RWMutex
+
+ // The start time of the interval
+ Interval time.Time
+
+ // Gauges maps the key to the last set value
+ Gauges map[string]float32
+
+ // Points maps the string to the list of emitted values
+ // from EmitKey
+ Points map[string][]float32
+
+ // Counters maps the string key to a sum of the counter
+ // values
+ Counters map[string]*AggregateSample
+
+ // Samples maps the key to an AggregateSample,
+ // which has the rolled up view of a sample
+ Samples map[string]*AggregateSample
+}
+
+// NewIntervalMetrics creates a new IntervalMetrics for a given interval
+func NewIntervalMetrics(intv time.Time) *IntervalMetrics {
+ return &IntervalMetrics{
+ Interval: intv,
+ Gauges: make(map[string]float32),
+ Points: make(map[string][]float32),
+ Counters: make(map[string]*AggregateSample),
+ Samples: make(map[string]*AggregateSample),
+ }
+}
+
+// AggregateSample is used to hold aggregate metrics
+// about a sample
+type AggregateSample struct {
+ Count int // The count of emitted pairs
+ Sum float64 // The sum of values
+ SumSq float64 // The sum of squared values
+ Min float64 // Minimum value
+ Max float64 // Maximum value
+}
+
+// Computes a Stddev of the values
+func (a *AggregateSample) Stddev() float64 {
+ num := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2)
+ div := float64(a.Count * (a.Count - 1))
+ if div == 0 {
+ return 0
+ }
+ return math.Sqrt(num / div)
+}
+
+// Computes a mean of the values
+func (a *AggregateSample) Mean() float64 {
+ if a.Count == 0 {
+ return 0
+ }
+ return a.Sum / float64(a.Count)
+}
+
+// Ingest is used to update a sample
+func (a *AggregateSample) Ingest(v float64) {
+ a.Count++
+ a.Sum += v
+ a.SumSq += (v * v)
+ if v < a.Min || a.Count == 1 {
+ a.Min = v
+ }
+ if v > a.Max || a.Count == 1 {
+ a.Max = v
+ }
+}
+
+func (a *AggregateSample) String() string {
+ if a.Count == 0 {
+ return "Count: 0"
+ } else if a.Stddev() == 0 {
+ return fmt.Sprintf("Count: %d Sum: %0.3f", a.Count, a.Sum)
+ } else {
+ return fmt.Sprintf("Count: %d Min: %0.3f Mean: %0.3f Max: %0.3f Stddev: %0.3f Sum: %0.3f",
+ a.Count, a.Min, a.Mean(), a.Max, a.Stddev(), a.Sum)
+ }
+}
+
+// NewInmemSink is used to construct a new in-memory sink.
+// Uses an aggregation interval and maximum retention period.
+func NewInmemSink(interval, retain time.Duration) *InmemSink {
+ i := &InmemSink{
+ interval: interval,
+ retain: retain,
+ maxIntervals: int(retain / interval),
+ }
+ i.intervals = make([]*IntervalMetrics, 0, i.maxIntervals)
+ return i
+}
+
+func (i *InmemSink) SetGauge(key []string, val float32) {
+ k := i.flattenKey(key)
+ intv := i.getInterval()
+
+ intv.Lock()
+ defer intv.Unlock()
+ intv.Gauges[k] = val
+}
+
+func (i *InmemSink) EmitKey(key []string, val float32) {
+ k := i.flattenKey(key)
+ intv := i.getInterval()
+
+ intv.Lock()
+ defer intv.Unlock()
+ vals := intv.Points[k]
+ intv.Points[k] = append(vals, val)
+}
+
+func (i *InmemSink) IncrCounter(key []string, val float32) {
+ k := i.flattenKey(key)
+ intv := i.getInterval()
+
+ intv.Lock()
+ defer intv.Unlock()
+
+ agg := intv.Counters[k]
+ if agg == nil {
+ agg = &AggregateSample{}
+ intv.Counters[k] = agg
+ }
+ agg.Ingest(float64(val))
+}
+
+func (i *InmemSink) AddSample(key []string, val float32) {
+ k := i.flattenKey(key)
+ intv := i.getInterval()
+
+ intv.Lock()
+ defer intv.Unlock()
+
+ agg := intv.Samples[k]
+ if agg == nil {
+ agg = &AggregateSample{}
+ intv.Samples[k] = agg
+ }
+ agg.Ingest(float64(val))
+}
+
+// Data is used to retrieve all the aggregated metrics
+// Intervals may be in use, and a read lock should be acquired
+func (i *InmemSink) Data() []*IntervalMetrics {
+ // Get the current interval, forces creation
+ i.getInterval()
+
+ i.intervalLock.RLock()
+ defer i.intervalLock.RUnlock()
+
+ intervals := make([]*IntervalMetrics, len(i.intervals))
+ copy(intervals, i.intervals)
+ return intervals
+}
+
+func (i *InmemSink) getExistingInterval(intv time.Time) *IntervalMetrics {
+ i.intervalLock.RLock()
+ defer i.intervalLock.RUnlock()
+
+ n := len(i.intervals)
+ if n > 0 && i.intervals[n-1].Interval == intv {
+ return i.intervals[n-1]
+ }
+ return nil
+}
+
+func (i *InmemSink) createInterval(intv time.Time) *IntervalMetrics {
+ i.intervalLock.Lock()
+ defer i.intervalLock.Unlock()
+
+ // Check for an existing interval
+ n := len(i.intervals)
+ if n > 0 && i.intervals[n-1].Interval == intv {
+ return i.intervals[n-1]
+ }
+
+ // Add the current interval
+ current := NewIntervalMetrics(intv)
+ i.intervals = append(i.intervals, current)
+ n++
+
+ // Truncate the intervals if they are too long
+ if n >= i.maxIntervals {
+ copy(i.intervals[0:], i.intervals[n-i.maxIntervals:])
+ i.intervals = i.intervals[:i.maxIntervals]
+ }
+ return current
+}
+
+// getInterval returns the current interval to write to
+func (i *InmemSink) getInterval() *IntervalMetrics {
+ intv := time.Now().Truncate(i.interval)
+ if m := i.getExistingInterval(intv); m != nil {
+ return m
+ }
+ return i.createInterval(intv)
+}
+
+// Flattens the key for formatting, removes spaces
+func (i *InmemSink) flattenKey(parts []string) string {
+ joined := strings.Join(parts, ".")
+ return strings.Replace(joined, " ", "_", -1)
+}
diff --git a/vendor/github.com/armon/go-metrics/inmem_signal.go b/vendor/github.com/armon/go-metrics/inmem_signal.go
new file mode 100644
index 0000000..95d08ee
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/inmem_signal.go
@@ -0,0 +1,100 @@
+package metrics
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "os"
+ "os/signal"
+ "sync"
+ "syscall"
+)
+
+// InmemSignal is used to listen for a given signal, and when received,
+// to dump the current metrics from the InmemSink to an io.Writer
+type InmemSignal struct {
+ signal syscall.Signal
+ inm *InmemSink
+ w io.Writer
+ sigCh chan os.Signal
+
+ stop bool
+ stopCh chan struct{}
+ stopLock sync.Mutex
+}
+
+// NewInmemSignal creates a new InmemSignal which listens for a given signal,
+// and dumps the current metrics out to a writer
+func NewInmemSignal(inmem *InmemSink, sig syscall.Signal, w io.Writer) *InmemSignal {
+ i := &InmemSignal{
+ signal: sig,
+ inm: inmem,
+ w: w,
+ sigCh: make(chan os.Signal, 1),
+ stopCh: make(chan struct{}),
+ }
+ signal.Notify(i.sigCh, sig)
+ go i.run()
+ return i
+}
+
+// DefaultInmemSignal returns a new InmemSignal that responds to SIGUSR1
+// and writes output to stderr. Windows uses SIGBREAK
+func DefaultInmemSignal(inmem *InmemSink) *InmemSignal {
+ return NewInmemSignal(inmem, DefaultSignal, os.Stderr)
+}
+
+// Stop is used to stop the InmemSignal from listening
+func (i *InmemSignal) Stop() {
+ i.stopLock.Lock()
+ defer i.stopLock.Unlock()
+
+ if i.stop {
+ return
+ }
+ i.stop = true
+ close(i.stopCh)
+ signal.Stop(i.sigCh)
+}
+
+// run is a long running routine that handles signals
+func (i *InmemSignal) run() {
+ for {
+ select {
+ case <-i.sigCh:
+ i.dumpStats()
+ case <-i.stopCh:
+ return
+ }
+ }
+}
+
+// dumpStats is used to dump the data to output writer
+func (i *InmemSignal) dumpStats() {
+ buf := bytes.NewBuffer(nil)
+
+ data := i.inm.Data()
+ // Skip the last period which is still being aggregated
+ for i := 0; i < len(data)-1; i++ {
+ intv := data[i]
+ intv.RLock()
+ for name, val := range intv.Gauges {
+ fmt.Fprintf(buf, "[%v][G] '%s': %0.3f\n", intv.Interval, name, val)
+ }
+ for name, vals := range intv.Points {
+ for _, val := range vals {
+ fmt.Fprintf(buf, "[%v][P] '%s': %0.3f\n", intv.Interval, name, val)
+ }
+ }
+ for name, agg := range intv.Counters {
+ fmt.Fprintf(buf, "[%v][C] '%s': %s\n", intv.Interval, name, agg)
+ }
+ for name, agg := range intv.Samples {
+ fmt.Fprintf(buf, "[%v][S] '%s': %s\n", intv.Interval, name, agg)
+ }
+ intv.RUnlock()
+ }
+
+ // Write out the bytes
+ i.w.Write(buf.Bytes())
+}
diff --git a/vendor/github.com/armon/go-metrics/metrics.go b/vendor/github.com/armon/go-metrics/metrics.go
new file mode 100755
index 0000000..b818e41
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/metrics.go
@@ -0,0 +1,115 @@
+package metrics
+
+import (
+ "runtime"
+ "time"
+)
+
+func (m *Metrics) SetGauge(key []string, val float32) {
+ if m.HostName != "" && m.EnableHostname {
+ key = insert(0, m.HostName, key)
+ }
+ if m.EnableTypePrefix {
+ key = insert(0, "gauge", key)
+ }
+ if m.ServiceName != "" {
+ key = insert(0, m.ServiceName, key)
+ }
+ m.sink.SetGauge(key, val)
+}
+
+func (m *Metrics) EmitKey(key []string, val float32) {
+ if m.EnableTypePrefix {
+ key = insert(0, "kv", key)
+ }
+ if m.ServiceName != "" {
+ key = insert(0, m.ServiceName, key)
+ }
+ m.sink.EmitKey(key, val)
+}
+
+func (m *Metrics) IncrCounter(key []string, val float32) {
+ if m.EnableTypePrefix {
+ key = insert(0, "counter", key)
+ }
+ if m.ServiceName != "" {
+ key = insert(0, m.ServiceName, key)
+ }
+ m.sink.IncrCounter(key, val)
+}
+
+func (m *Metrics) AddSample(key []string, val float32) {
+ if m.EnableTypePrefix {
+ key = insert(0, "sample", key)
+ }
+ if m.ServiceName != "" {
+ key = insert(0, m.ServiceName, key)
+ }
+ m.sink.AddSample(key, val)
+}
+
+func (m *Metrics) MeasureSince(key []string, start time.Time) {
+ if m.EnableTypePrefix {
+ key = insert(0, "timer", key)
+ }
+ if m.ServiceName != "" {
+ key = insert(0, m.ServiceName, key)
+ }
+ now := time.Now()
+ elapsed := now.Sub(start)
+ msec := float32(elapsed.Nanoseconds()) / float32(m.TimerGranularity)
+ m.sink.AddSample(key, msec)
+}
+
+// Periodically collects runtime stats to publish
+func (m *Metrics) collectStats() {
+ for {
+ time.Sleep(m.ProfileInterval)
+ m.emitRuntimeStats()
+ }
+}
+
+// Emits various runtime statsitics
+func (m *Metrics) emitRuntimeStats() {
+ // Export number of Goroutines
+ numRoutines := runtime.NumGoroutine()
+ m.SetGauge([]string{"runtime", "num_goroutines"}, float32(numRoutines))
+
+ // Export memory stats
+ var stats runtime.MemStats
+ runtime.ReadMemStats(&stats)
+ m.SetGauge([]string{"runtime", "alloc_bytes"}, float32(stats.Alloc))
+ m.SetGauge([]string{"runtime", "sys_bytes"}, float32(stats.Sys))
+ m.SetGauge([]string{"runtime", "malloc_count"}, float32(stats.Mallocs))
+ m.SetGauge([]string{"runtime", "free_count"}, float32(stats.Frees))
+ m.SetGauge([]string{"runtime", "heap_objects"}, float32(stats.HeapObjects))
+ m.SetGauge([]string{"runtime", "total_gc_pause_ns"}, float32(stats.PauseTotalNs))
+ m.SetGauge([]string{"runtime", "total_gc_runs"}, float32(stats.NumGC))
+
+ // Export info about the last few GC runs
+ num := stats.NumGC
+
+ // Handle wrap around
+ if num < m.lastNumGC {
+ m.lastNumGC = 0
+ }
+
+ // Ensure we don't scan more than 256
+ if num-m.lastNumGC >= 256 {
+ m.lastNumGC = num - 255
+ }
+
+ for i := m.lastNumGC; i < num; i++ {
+ pause := stats.PauseNs[i%256]
+ m.AddSample([]string{"runtime", "gc_pause_ns"}, float32(pause))
+ }
+ m.lastNumGC = num
+}
+
+// Inserts a string value at an index into the slice
+func insert(i int, v string, s []string) []string {
+ s = append(s, "")
+ copy(s[i+1:], s[i:])
+ s[i] = v
+ return s
+}
diff --git a/vendor/github.com/armon/go-metrics/sink.go b/vendor/github.com/armon/go-metrics/sink.go
new file mode 100755
index 0000000..0c240c2
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/sink.go
@@ -0,0 +1,52 @@
+package metrics
+
+// The MetricSink interface is used to transmit metrics information
+// to an external system
+type MetricSink interface {
+ // A Gauge should retain the last value it is set to
+ SetGauge(key []string, val float32)
+
+ // Should emit a Key/Value pair for each call
+ EmitKey(key []string, val float32)
+
+ // Counters should accumulate values
+ IncrCounter(key []string, val float32)
+
+ // Samples are for timing information, where quantiles are used
+ AddSample(key []string, val float32)
+}
+
+// BlackholeSink is used to just blackhole messages
+type BlackholeSink struct{}
+
+func (*BlackholeSink) SetGauge(key []string, val float32) {}
+func (*BlackholeSink) EmitKey(key []string, val float32) {}
+func (*BlackholeSink) IncrCounter(key []string, val float32) {}
+func (*BlackholeSink) AddSample(key []string, val float32) {}
+
+// FanoutSink is used to sink to fanout values to multiple sinks
+type FanoutSink []MetricSink
+
+func (fh FanoutSink) SetGauge(key []string, val float32) {
+ for _, s := range fh {
+ s.SetGauge(key, val)
+ }
+}
+
+func (fh FanoutSink) EmitKey(key []string, val float32) {
+ for _, s := range fh {
+ s.EmitKey(key, val)
+ }
+}
+
+func (fh FanoutSink) IncrCounter(key []string, val float32) {
+ for _, s := range fh {
+ s.IncrCounter(key, val)
+ }
+}
+
+func (fh FanoutSink) AddSample(key []string, val float32) {
+ for _, s := range fh {
+ s.AddSample(key, val)
+ }
+}
diff --git a/vendor/github.com/armon/go-metrics/start.go b/vendor/github.com/armon/go-metrics/start.go
new file mode 100755
index 0000000..44113f1
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/start.go
@@ -0,0 +1,95 @@
+package metrics
+
+import (
+ "os"
+ "time"
+)
+
+// Config is used to configure metrics settings
+type Config struct {
+ ServiceName string // Prefixed with keys to seperate services
+ HostName string // Hostname to use. If not provided and EnableHostname, it will be os.Hostname
+ EnableHostname bool // Enable prefixing gauge values with hostname
+ EnableRuntimeMetrics bool // Enables profiling of runtime metrics (GC, Goroutines, Memory)
+ EnableTypePrefix bool // Prefixes key with a type ("counter", "gauge", "timer")
+ TimerGranularity time.Duration // Granularity of timers.
+ ProfileInterval time.Duration // Interval to profile runtime metrics
+}
+
+// Metrics represents an instance of a metrics sink that can
+// be used to emit
+type Metrics struct {
+ Config
+ lastNumGC uint32
+ sink MetricSink
+}
+
+// Shared global metrics instance
+var globalMetrics *Metrics
+
+func init() {
+ // Initialize to a blackhole sink to avoid errors
+ globalMetrics = &Metrics{sink: &BlackholeSink{}}
+}
+
+// DefaultConfig provides a sane default configuration
+func DefaultConfig(serviceName string) *Config {
+ c := &Config{
+ ServiceName: serviceName, // Use client provided service
+ HostName: "",
+ EnableHostname: true, // Enable hostname prefix
+ EnableRuntimeMetrics: true, // Enable runtime profiling
+ EnableTypePrefix: false, // Disable type prefix
+ TimerGranularity: time.Millisecond, // Timers are in milliseconds
+ ProfileInterval: time.Second, // Poll runtime every second
+ }
+
+ // Try to get the hostname
+ name, _ := os.Hostname()
+ c.HostName = name
+ return c
+}
+
+// New is used to create a new instance of Metrics
+func New(conf *Config, sink MetricSink) (*Metrics, error) {
+ met := &Metrics{}
+ met.Config = *conf
+ met.sink = sink
+
+ // Start the runtime collector
+ if conf.EnableRuntimeMetrics {
+ go met.collectStats()
+ }
+ return met, nil
+}
+
+// NewGlobal is the same as New, but it assigns the metrics object to be
+// used globally as well as returning it.
+func NewGlobal(conf *Config, sink MetricSink) (*Metrics, error) {
+ metrics, err := New(conf, sink)
+ if err == nil {
+ globalMetrics = metrics
+ }
+ return metrics, err
+}
+
+// Proxy all the methods to the globalMetrics instance
+func SetGauge(key []string, val float32) {
+ globalMetrics.SetGauge(key, val)
+}
+
+func EmitKey(key []string, val float32) {
+ globalMetrics.EmitKey(key, val)
+}
+
+func IncrCounter(key []string, val float32) {
+ globalMetrics.IncrCounter(key, val)
+}
+
+func AddSample(key []string, val float32) {
+ globalMetrics.AddSample(key, val)
+}
+
+func MeasureSince(key []string, start time.Time) {
+ globalMetrics.MeasureSince(key, start)
+}
diff --git a/vendor/github.com/armon/go-metrics/statsd.go b/vendor/github.com/armon/go-metrics/statsd.go
new file mode 100644
index 0000000..65a5021
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/statsd.go
@@ -0,0 +1,154 @@
+package metrics
+
+import (
+ "bytes"
+ "fmt"
+ "log"
+ "net"
+ "strings"
+ "time"
+)
+
+const (
+ // statsdMaxLen is the maximum size of a packet
+ // to send to statsd
+ statsdMaxLen = 1400
+)
+
+// StatsdSink provides a MetricSink that can be used
+// with a statsite or statsd metrics server. It uses
+// only UDP packets, while StatsiteSink uses TCP.
+type StatsdSink struct {
+ addr string
+ metricQueue chan string
+}
+
+// NewStatsdSink is used to create a new StatsdSink
+func NewStatsdSink(addr string) (*StatsdSink, error) {
+ s := &StatsdSink{
+ addr: addr,
+ metricQueue: make(chan string, 4096),
+ }
+ go s.flushMetrics()
+ return s, nil
+}
+
+// Close is used to stop flushing to statsd
+func (s *StatsdSink) Shutdown() {
+ close(s.metricQueue)
+}
+
+func (s *StatsdSink) SetGauge(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val))
+}
+
+func (s *StatsdSink) EmitKey(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|kv\n", flatKey, val))
+}
+
+func (s *StatsdSink) IncrCounter(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val))
+}
+
+func (s *StatsdSink) AddSample(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val))
+}
+
+// Flattens the key for formatting, removes spaces
+func (s *StatsdSink) flattenKey(parts []string) string {
+ joined := strings.Join(parts, ".")
+ return strings.Map(func(r rune) rune {
+ switch r {
+ case ':':
+ fallthrough
+ case ' ':
+ return '_'
+ default:
+ return r
+ }
+ }, joined)
+}
+
+// Does a non-blocking push to the metrics queue
+func (s *StatsdSink) pushMetric(m string) {
+ select {
+ case s.metricQueue <- m:
+ default:
+ }
+}
+
+// Flushes metrics
+func (s *StatsdSink) flushMetrics() {
+ var sock net.Conn
+ var err error
+ var wait <-chan time.Time
+ ticker := time.NewTicker(flushInterval)
+ defer ticker.Stop()
+
+CONNECT:
+ // Create a buffer
+ buf := bytes.NewBuffer(nil)
+
+ // Attempt to connect
+ sock, err = net.Dial("udp", s.addr)
+ if err != nil {
+ log.Printf("[ERR] Error connecting to statsd! Err: %s", err)
+ goto WAIT
+ }
+
+ for {
+ select {
+ case metric, ok := <-s.metricQueue:
+ // Get a metric from the queue
+ if !ok {
+ goto QUIT
+ }
+
+ // Check if this would overflow the packet size
+ if len(metric)+buf.Len() > statsdMaxLen {
+ _, err := sock.Write(buf.Bytes())
+ buf.Reset()
+ if err != nil {
+ log.Printf("[ERR] Error writing to statsd! Err: %s", err)
+ goto WAIT
+ }
+ }
+
+ // Append to the buffer
+ buf.WriteString(metric)
+
+ case <-ticker.C:
+ if buf.Len() == 0 {
+ continue
+ }
+
+ _, err := sock.Write(buf.Bytes())
+ buf.Reset()
+ if err != nil {
+ log.Printf("[ERR] Error flushing to statsd! Err: %s", err)
+ goto WAIT
+ }
+ }
+ }
+
+WAIT:
+ // Wait for a while
+ wait = time.After(time.Duration(5) * time.Second)
+ for {
+ select {
+ // Dequeue the messages to avoid backlog
+ case _, ok := <-s.metricQueue:
+ if !ok {
+ goto QUIT
+ }
+ case <-wait:
+ goto CONNECT
+ }
+ }
+QUIT:
+ s.metricQueue = nil
+}
diff --git a/vendor/github.com/armon/go-metrics/statsite.go b/vendor/github.com/armon/go-metrics/statsite.go
new file mode 100755
index 0000000..6873013
--- /dev/null
+++ b/vendor/github.com/armon/go-metrics/statsite.go
@@ -0,0 +1,142 @@
+package metrics
+
+import (
+ "bufio"
+ "fmt"
+ "log"
+ "net"
+ "strings"
+ "time"
+)
+
+const (
+ // We force flush the statsite metrics after this period of
+ // inactivity. Prevents stats from getting stuck in a buffer
+ // forever.
+ flushInterval = 100 * time.Millisecond
+)
+
+// StatsiteSink provides a MetricSink that can be used with a
+// statsite metrics server
+type StatsiteSink struct {
+ addr string
+ metricQueue chan string
+}
+
+// NewStatsiteSink is used to create a new StatsiteSink
+func NewStatsiteSink(addr string) (*StatsiteSink, error) {
+ s := &StatsiteSink{
+ addr: addr,
+ metricQueue: make(chan string, 4096),
+ }
+ go s.flushMetrics()
+ return s, nil
+}
+
+// Close is used to stop flushing to statsite
+func (s *StatsiteSink) Shutdown() {
+ close(s.metricQueue)
+}
+
+func (s *StatsiteSink) SetGauge(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val))
+}
+
+func (s *StatsiteSink) EmitKey(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|kv\n", flatKey, val))
+}
+
+func (s *StatsiteSink) IncrCounter(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val))
+}
+
+func (s *StatsiteSink) AddSample(key []string, val float32) {
+ flatKey := s.flattenKey(key)
+ s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val))
+}
+
+// Flattens the key for formatting, removes spaces
+func (s *StatsiteSink) flattenKey(parts []string) string {
+ joined := strings.Join(parts, ".")
+ return strings.Map(func(r rune) rune {
+ switch r {
+ case ':':
+ fallthrough
+ case ' ':
+ return '_'
+ default:
+ return r
+ }
+ }, joined)
+}
+
+// Does a non-blocking push to the metrics queue
+func (s *StatsiteSink) pushMetric(m string) {
+ select {
+ case s.metricQueue <- m:
+ default:
+ }
+}
+
+// Flushes metrics
+func (s *StatsiteSink) flushMetrics() {
+ var sock net.Conn
+ var err error
+ var wait <-chan time.Time
+ var buffered *bufio.Writer
+ ticker := time.NewTicker(flushInterval)
+ defer ticker.Stop()
+
+CONNECT:
+ // Attempt to connect
+ sock, err = net.Dial("tcp", s.addr)
+ if err != nil {
+ log.Printf("[ERR] Error connecting to statsite! Err: %s", err)
+ goto WAIT
+ }
+
+ // Create a buffered writer
+ buffered = bufio.NewWriter(sock)
+
+ for {
+ select {
+ case metric, ok := <-s.metricQueue:
+ // Get a metric from the queue
+ if !ok {
+ goto QUIT
+ }
+
+ // Try to send to statsite
+ _, err := buffered.Write([]byte(metric))
+ if err != nil {
+ log.Printf("[ERR] Error writing to statsite! Err: %s", err)
+ goto WAIT
+ }
+ case <-ticker.C:
+ if err := buffered.Flush(); err != nil {
+ log.Printf("[ERR] Error flushing to statsite! Err: %s", err)
+ goto WAIT
+ }
+ }
+ }
+
+WAIT:
+ // Wait for a while
+ wait = time.After(time.Duration(5) * time.Second)
+ for {
+ select {
+ // Dequeue the messages to avoid backlog
+ case _, ok := <-s.metricQueue:
+ if !ok {
+ goto QUIT
+ }
+ case <-wait:
+ goto CONNECT
+ }
+ }
+QUIT:
+ s.metricQueue = nil
+}
diff --git a/vendor/github.com/armon/go-radix/LICENSE b/vendor/github.com/armon/go-radix/LICENSE
new file mode 100644
index 0000000..a5df10e
--- /dev/null
+++ b/vendor/github.com/armon/go-radix/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Armon Dadgar
+
+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/armon/go-radix/README.md b/vendor/github.com/armon/go-radix/README.md
new file mode 100644
index 0000000..c054fe8
--- /dev/null
+++ b/vendor/github.com/armon/go-radix/README.md
@@ -0,0 +1,36 @@
+go-radix [![Build Status](https://travis-ci.org/armon/go-radix.png)](https://travis-ci.org/armon/go-radix)
+=========
+
+Provides the `radix` package that implements a [radix tree](http://en.wikipedia.org/wiki/Radix_tree).
+The package only provides a single `Tree` implementation, optimized for sparse nodes.
+
+As a radix tree, it provides the following:
+ * O(k) operations. In many cases, this can be faster than a hash table since
+ the hash function is an O(k) operation, and hash tables have very poor cache locality.
+ * Minimum / Maximum value lookups
+ * Ordered iteration
+
+Documentation
+=============
+
+The full documentation is available on [Godoc](http://godoc.org/github.com/armon/go-radix).
+
+Example
+=======
+
+Below is a simple example of usage
+
+```go
+// Create a tree
+r := radix.New()
+r.Insert("foo", 1)
+r.Insert("bar", 2)
+r.Insert("foobar", 2)
+
+// Find the longest prefix match
+m, _, _ := r.LongestPrefix("foozip")
+if m != "foo" {
+ panic("should be foo")
+}
+```
+
diff --git a/vendor/github.com/armon/go-radix/radix.go b/vendor/github.com/armon/go-radix/radix.go
new file mode 100644
index 0000000..8c963c9
--- /dev/null
+++ b/vendor/github.com/armon/go-radix/radix.go
@@ -0,0 +1,467 @@
+package radix
+
+import (
+ "sort"
+ "strings"
+)
+
+// WalkFn is used when walking the tree. Takes a
+// key and value, returning if iteration should
+// be terminated.
+type WalkFn func(s string, v interface{}) bool
+
+// leafNode is used to represent a value
+type leafNode struct {
+ key string
+ val interface{}
+}
+
+// edge is used to represent an edge node
+type edge struct {
+ label byte
+ node *node
+}
+
+type node struct {
+ // leaf is used to store possible leaf
+ leaf *leafNode
+
+ // prefix is the common prefix we ignore
+ prefix string
+
+ // Edges should be stored in-order for iteration.
+ // We avoid a fully materialized slice to save memory,
+ // since in most cases we expect to be sparse
+ edges edges
+}
+
+func (n *node) isLeaf() bool {
+ return n.leaf != nil
+}
+
+func (n *node) addEdge(e edge) {
+ n.edges = append(n.edges, e)
+ n.edges.Sort()
+}
+
+func (n *node) replaceEdge(e edge) {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= e.label
+ })
+ if idx < num && n.edges[idx].label == e.label {
+ n.edges[idx].node = e.node
+ return
+ }
+ panic("replacing missing edge")
+}
+
+func (n *node) getEdge(label byte) *node {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= label
+ })
+ if idx < num && n.edges[idx].label == label {
+ return n.edges[idx].node
+ }
+ return nil
+}
+
+type edges []edge
+
+func (e edges) Len() int {
+ return len(e)
+}
+
+func (e edges) Less(i, j int) bool {
+ return e[i].label < e[j].label
+}
+
+func (e edges) Swap(i, j int) {
+ e[i], e[j] = e[j], e[i]
+}
+
+func (e edges) Sort() {
+ sort.Sort(e)
+}
+
+// Tree implements a radix tree. This can be treated as a
+// Dictionary abstract data type. The main advantage over
+// a standard hash map is prefix-based lookups and
+// ordered iteration,
+type Tree struct {
+ root *node
+ size int
+}
+
+// New returns an empty Tree
+func New() *Tree {
+ return NewFromMap(nil)
+}
+
+// NewFromMap returns a new tree containing the keys
+// from an existing map
+func NewFromMap(m map[string]interface{}) *Tree {
+ t := &Tree{root: &node{}}
+ for k, v := range m {
+ t.Insert(k, v)
+ }
+ return t
+}
+
+// Len is used to return the number of elements in the tree
+func (t *Tree) Len() int {
+ return t.size
+}
+
+// longestPrefix finds the length of the shared prefix
+// of two strings
+func longestPrefix(k1, k2 string) int {
+ max := len(k1)
+ if l := len(k2); l < max {
+ max = l
+ }
+ var i int
+ for i = 0; i < max; i++ {
+ if k1[i] != k2[i] {
+ break
+ }
+ }
+ return i
+}
+
+// Insert is used to add a newentry or update
+// an existing entry. Returns if updated.
+func (t *Tree) Insert(s string, v interface{}) (interface{}, bool) {
+ var parent *node
+ n := t.root
+ search := s
+ for {
+ // Handle key exhaution
+ if len(search) == 0 {
+ if n.isLeaf() {
+ old := n.leaf.val
+ n.leaf.val = v
+ return old, true
+ } else {
+ n.leaf = &leafNode{
+ key: s,
+ val: v,
+ }
+ t.size++
+ return nil, false
+ }
+ }
+
+ // Look for the edge
+ parent = n
+ n = n.getEdge(search[0])
+
+ // No edge, create one
+ if n == nil {
+ e := edge{
+ label: search[0],
+ node: &node{
+ leaf: &leafNode{
+ key: s,
+ val: v,
+ },
+ prefix: search,
+ },
+ }
+ parent.addEdge(e)
+ t.size++
+ return nil, false
+ }
+
+ // Determine longest prefix of the search key on match
+ commonPrefix := longestPrefix(search, n.prefix)
+ if commonPrefix == len(n.prefix) {
+ search = search[commonPrefix:]
+ continue
+ }
+
+ // Split the node
+ t.size++
+ child := &node{
+ prefix: search[:commonPrefix],
+ }
+ parent.replaceEdge(edge{
+ label: search[0],
+ node: child,
+ })
+
+ // Restore the existing node
+ child.addEdge(edge{
+ label: n.prefix[commonPrefix],
+ node: n,
+ })
+ n.prefix = n.prefix[commonPrefix:]
+
+ // Create a new leaf node
+ leaf := &leafNode{
+ key: s,
+ val: v,
+ }
+
+ // If the new key is a subset, add to to this node
+ search = search[commonPrefix:]
+ if len(search) == 0 {
+ child.leaf = leaf
+ return nil, false
+ }
+
+ // Create a new edge for the node
+ child.addEdge(edge{
+ label: search[0],
+ node: &node{
+ leaf: leaf,
+ prefix: search,
+ },
+ })
+ return nil, false
+ }
+ return nil, false
+}
+
+// Delete is used to delete a key, returning the previous
+// value and if it was deleted
+func (t *Tree) Delete(s string) (interface{}, bool) {
+ n := t.root
+ search := s
+ for {
+ // Check for key exhaution
+ if len(search) == 0 {
+ if !n.isLeaf() {
+ break
+ }
+ goto DELETE
+ }
+
+ // Look for an edge
+ n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Consume the search prefix
+ if strings.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+ } else {
+ break
+ }
+ }
+ return nil, false
+
+DELETE:
+ // Delete the leaf
+ leaf := n.leaf
+ n.leaf = nil
+ t.size--
+
+ // Check if we should merge this node
+ if len(n.edges) == 1 {
+ e := n.edges[0]
+ child := e.node
+ n.prefix = n.prefix + child.prefix
+ n.leaf = child.leaf
+ n.edges = child.edges
+ }
+ return leaf.val, true
+}
+
+// Get is used to lookup a specific key, returning
+// the value and if it was found
+func (t *Tree) Get(s string) (interface{}, bool) {
+ n := t.root
+ search := s
+ for {
+ // Check for key exhaution
+ if len(search) == 0 {
+ if n.isLeaf() {
+ return n.leaf.val, true
+ }
+ break
+ }
+
+ // Look for an edge
+ n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Consume the search prefix
+ if strings.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+ } else {
+ break
+ }
+ }
+ return nil, false
+}
+
+// LongestPrefix is like Get, but instead of an
+// exact match, it will return the longest prefix match.
+func (t *Tree) LongestPrefix(s string) (string, interface{}, bool) {
+ var last *leafNode
+ n := t.root
+ search := s
+ for {
+ // Look for a leaf node
+ if n.isLeaf() {
+ last = n.leaf
+ }
+
+ // Check for key exhaution
+ if len(search) == 0 {
+ break
+ }
+
+ // Look for an edge
+ n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Consume the search prefix
+ if strings.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+ } else {
+ break
+ }
+ }
+ if last != nil {
+ return last.key, last.val, true
+ }
+ return "", nil, false
+}
+
+// Minimum is used to return the minimum value in the tree
+func (t *Tree) Minimum() (string, interface{}, bool) {
+ n := t.root
+ for {
+ if n.isLeaf() {
+ return n.leaf.key, n.leaf.val, true
+ }
+ if len(n.edges) > 0 {
+ n = n.edges[0].node
+ } else {
+ break
+ }
+ }
+ return "", nil, false
+}
+
+// Maximum is used to return the maximum value in the tree
+func (t *Tree) Maximum() (string, interface{}, bool) {
+ n := t.root
+ for {
+ if num := len(n.edges); num > 0 {
+ n = n.edges[num-1].node
+ continue
+ }
+ if n.isLeaf() {
+ return n.leaf.key, n.leaf.val, true
+ } else {
+ break
+ }
+ }
+ return "", nil, false
+}
+
+// Walk is used to walk the tree
+func (t *Tree) Walk(fn WalkFn) {
+ recursiveWalk(t.root, fn)
+}
+
+// WalkPrefix is used to walk the tree under a prefix
+func (t *Tree) WalkPrefix(prefix string, fn WalkFn) {
+ n := t.root
+ search := prefix
+ for {
+ // Check for key exhaution
+ if len(search) == 0 {
+ recursiveWalk(n, fn)
+ return
+ }
+
+ // Look for an edge
+ n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Consume the search prefix
+ if strings.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+
+ } else if strings.HasPrefix(n.prefix, search) {
+ // Child may be under our search prefix
+ recursiveWalk(n, fn)
+ return
+ } else {
+ break
+ }
+ }
+
+}
+
+// WalkPath is used to walk the tree, but only visiting nodes
+// from the root down to a given leaf. Where WalkPrefix walks
+// all the entries *under* the given prefix, this walks the
+// entries *above* the given prefix.
+func (t *Tree) WalkPath(path string, fn WalkFn) {
+ n := t.root
+ search := path
+ for {
+ // Visit the leaf values if any
+ if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
+ return
+ }
+
+ // Check for key exhaution
+ if len(search) == 0 {
+ return
+ }
+
+ // Look for an edge
+ n = n.getEdge(search[0])
+ if n == nil {
+ return
+ }
+
+ // Consume the search prefix
+ if strings.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+ } else {
+ break
+ }
+ }
+}
+
+// recursiveWalk is used to do a pre-order walk of a node
+// recursively. Returns true if the walk should be aborted
+func recursiveWalk(n *node, fn WalkFn) bool {
+ // Visit the leaf values if any
+ if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
+ return true
+ }
+
+ // Recurse on the children
+ for _, e := range n.edges {
+ if recursiveWalk(e.node, fn) {
+ return true
+ }
+ }
+ return false
+}
+
+// ToMap is used to walk the tree and convert it into a map
+func (t *Tree) ToMap() map[string]interface{} {
+ out := make(map[string]interface{}, t.size)
+ t.Walk(func(k string, v interface{}) bool {
+ out[k] = v
+ return false
+ })
+ return out
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go/LICENSE.txt
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/aws/aws-sdk-go/NOTICE.txt b/vendor/github.com/aws/aws-sdk-go/NOTICE.txt
new file mode 100644
index 0000000..5f14d11
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/NOTICE.txt
@@ -0,0 +1,3 @@
+AWS SDK for Go
+Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+Copyright 2014-2015 Stripe, Inc.
diff --git a/vendor/github.com/aws/aws-sdk-go/README.md b/vendor/github.com/aws/aws-sdk-go/README.md
new file mode 100644
index 0000000..947643a
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/README.md
@@ -0,0 +1,116 @@
+# AWS SDK for Go
+
+<span style="display: inline-block;">
+[![API Reference](http://img.shields.io/badge/api-reference-blue.svg)](http://docs.aws.amazon.com/sdk-for-go/api)
+[![Join the chat at https://gitter.im/aws/aws-sdk-go](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/aws/aws-sdk-go?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+[![Build Status](https://img.shields.io/travis/aws/aws-sdk-go.svg)](https://travis-ci.org/aws/aws-sdk-go)
+[![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/aws/aws-sdk-go/blob/master/LICENSE.txt)
+</span>
+
+aws-sdk-go is the official AWS SDK for the Go programming language.
+
+Checkout our [release notes](https://github.com/aws/aws-sdk-go/releases) for information about the latest bug fixes, updates, and features added to the SDK.
+
+## Installing
+
+If you are using Go 1.5 with the `GO15VENDOREXPERIMENT=1` vendoring flag, or 1.6 and higher you can use the following command to retrieve the SDK. The SDK's non-testing dependencies will be included and are vendored in the `vendor` folder.
+
+ go get -u github.com/aws/aws-sdk-go
+
+Otherwise if your Go environment does not have vendoring support enabled, or you do not want to include the vendored SDK's dependencies you can use the following command to retrieve the SDK and its non-testing dependencies using `go get`.
+
+ go get -u github.com/aws/aws-sdk-go/aws/...
+ go get -u github.com/aws/aws-sdk-go/service/...
+
+If you're looking to retrieve just the SDK without any dependencies use the following command.
+
+ go get -d github.com/aws/aws-sdk-go/
+
+These two processes will still include the `vendor` folder and it should be deleted if its not going to be used by your environment.
+
+ rm -rf $GOPATH/src/github.com/aws/aws-sdk-go/vendor
+
+## Reference Documentation
+[`Getting Started Guide`](https://aws.amazon.com/sdk-for-go/) - This document is a general introduction how to configure and make requests with the SDK. If this is your first time using the SDK, this documentation and the API documentation will help you get started. This document focuses on the syntax and behavior of the SDK. The [Service Developer Guide](https://aws.amazon.com/documentation/) will help you get started using specific AWS services.
+
+[`SDK API Reference Documentation`](https://docs.aws.amazon.com/sdk-for-go/api/) - Use this document to look up all API operation input and output parameters for AWS services supported by the SDK. The API reference also includes documentation of the SDK, and examples how to using the SDK, service client API operations, and API operation require parameters.
+
+[`Service Developer Guide`](https://aws.amazon.com/documentation/) - Use this documentation to learn how to interface with an AWS service. These are great guides both, if you're getting started with a service, or looking for more information on a service. You should not need this document for coding, though in some cases, services may supply helpful samples that you might want to look out for.
+
+[`SDK Examples`](https://github.com/aws/aws-sdk-go/tree/master/example) - Included in the SDK's repo are a several hand crafted examples using the SDK features and AWS services.
+
+## Configuring Credentials
+
+Before using the SDK, ensure that you've configured credentials. The best
+way to configure credentials on a development machine is to use the
+`~/.aws/credentials` file, which might look like:
+
+```
+[default]
+aws_access_key_id = AKID1234567890
+aws_secret_access_key = MY-SECRET-KEY
+```
+
+You can learn more about the credentials file from this
+[blog post](http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs).
+
+Alternatively, you can set the following environment variables:
+
+```
+AWS_ACCESS_KEY_ID=AKID1234567890
+AWS_SECRET_ACCESS_KEY=MY-SECRET-KEY
+```
+
+### AWS shared config file (`~/.aws/config`)
+The AWS SDK for Go added support the shared config file in release [v1.3.0](https://github.com/aws/aws-sdk-go/releases/tag/v1.3.0). You can opt into enabling support for the shared config by setting the environment variable `AWS_SDK_LOAD_CONFIG` to a truthy value. See the [Session](https://github.com/aws/aws-sdk-go/wiki/sessions) wiki for more information about this feature.
+
+## Using the Go SDK
+
+To use a service in the SDK, create a service variable by calling the `New()`
+function. Once you have a service client, you can call API operations which each
+return response data and a possible error.
+
+To list a set of instance IDs from EC2, you could run:
+
+```go
+package main
+
+import (
+ "fmt"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/session"
+ "github.com/aws/aws-sdk-go/service/ec2"
+)
+
+func main() {
+ // Create an EC2 service object in the "us-west-2" region
+ // Note that you can also configure your region globally by
+ // exporting the AWS_REGION environment variable
+ svc := ec2.New(session.NewSession(), &aws.Config{Region: aws.String("us-west-2")})
+
+ // Call the DescribeInstances Operation
+ resp, err := svc.DescribeInstances(nil)
+ if err != nil {
+ panic(err)
+ }
+
+ // resp has all of the response data, pull out instance IDs:
+ fmt.Println("> Number of reservation sets: ", len(resp.Reservations))
+ for idx, res := range resp.Reservations {
+ fmt.Println(" > Number of instances: ", len(res.Instances))
+ for _, inst := range resp.Reservations[idx].Instances {
+ fmt.Println(" - Instance ID: ", *inst.InstanceId)
+ }
+ }
+}
+```
+
+You can find more information and operations in our
+[API documentation](http://docs.aws.amazon.com/sdk-for-go/api/).
+
+## License
+
+This SDK is distributed under the
+[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0),
+see LICENSE.txt and NOTICE.txt for more information.
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go b/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go
new file mode 100644
index 0000000..56fdfc2
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go
@@ -0,0 +1,145 @@
+// Package awserr represents API error interface accessors for the SDK.
+package awserr
+
+// An Error wraps lower level errors with code, message and an original error.
+// The underlying concrete error type may also satisfy other interfaces which
+// can be to used to obtain more specific information about the error.
+//
+// Calling Error() or String() will always include the full information about
+// an error based on its underlying type.
+//
+// Example:
+//
+// output, err := s3manage.Upload(svc, input, opts)
+// if err != nil {
+// if awsErr, ok := err.(awserr.Error); ok {
+// // Get error details
+// log.Println("Error:", awsErr.Code(), awsErr.Message())
+//
+// // Prints out full error message, including original error if there was one.
+// log.Println("Error:", awsErr.Error())
+//
+// // Get original error
+// if origErr := awsErr.OrigErr(); origErr != nil {
+// // operate on original error.
+// }
+// } else {
+// fmt.Println(err.Error())
+// }
+// }
+//
+type Error interface {
+ // Satisfy the generic error interface.
+ error
+
+ // Returns the short phrase depicting the classification of the error.
+ Code() string
+
+ // Returns the error details message.
+ Message() string
+
+ // Returns the original error if one was set. Nil is returned if not set.
+ OrigErr() error
+}
+
+// BatchError is a batch of errors which also wraps lower level errors with
+// code, message, and original errors. Calling Error() will include all errors
+// that occurred in the batch.
+//
+// Deprecated: Replaced with BatchedErrors. Only defined for backwards
+// compatibility.
+type BatchError interface {
+ // Satisfy the generic error interface.
+ error
+
+ // Returns the short phrase depicting the classification of the error.
+ Code() string
+
+ // Returns the error details message.
+ Message() string
+
+ // Returns the original error if one was set. Nil is returned if not set.
+ OrigErrs() []error
+}
+
+// BatchedErrors is a batch of errors which also wraps lower level errors with
+// code, message, and original errors. Calling Error() will include all errors
+// that occurred in the batch.
+//
+// Replaces BatchError
+type BatchedErrors interface {
+ // Satisfy the base Error interface.
+ Error
+
+ // Returns the original error if one was set. Nil is returned if not set.
+ OrigErrs() []error
+}
+
+// New returns an Error object described by the code, message, and origErr.
+//
+// If origErr satisfies the Error interface it will not be wrapped within a new
+// Error object and will instead be returned.
+func New(code, message string, origErr error) Error {
+ var errs []error
+ if origErr != nil {
+ errs = append(errs, origErr)
+ }
+ return newBaseError(code, message, errs)
+}
+
+// NewBatchError returns an BatchedErrors with a collection of errors as an
+// array of errors.
+func NewBatchError(code, message string, errs []error) BatchedErrors {
+ return newBaseError(code, message, errs)
+}
+
+// A RequestFailure is an interface to extract request failure information from
+// an Error such as the request ID of the failed request returned by a service.
+// RequestFailures may not always have a requestID value if the request failed
+// prior to reaching the service such as a connection error.
+//
+// Example:
+//
+// output, err := s3manage.Upload(svc, input, opts)
+// if err != nil {
+// if reqerr, ok := err.(RequestFailure); ok {
+// log.Println("Request failed", reqerr.Code(), reqerr.Message(), reqerr.RequestID())
+// } else {
+// log.Println("Error:", err.Error())
+// }
+// }
+//
+// Combined with awserr.Error:
+//
+// output, err := s3manage.Upload(svc, input, opts)
+// if err != nil {
+// if awsErr, ok := err.(awserr.Error); ok {
+// // Generic AWS Error with Code, Message, and original error (if any)
+// fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
+//
+// if reqErr, ok := err.(awserr.RequestFailure); ok {
+// // A service error occurred
+// fmt.Println(reqErr.StatusCode(), reqErr.RequestID())
+// }
+// } else {
+// fmt.Println(err.Error())
+// }
+// }
+//
+type RequestFailure interface {
+ Error
+
+ // The status code of the HTTP response.
+ StatusCode() int
+
+ // The request ID returned by the service for a request failure. This will
+ // be empty if no request ID is available such as the request failed due
+ // to a connection error.
+ RequestID() string
+}
+
+// NewRequestFailure returns a new request error wrapper for the given Error
+// provided.
+func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure {
+ return newRequestError(err, statusCode, reqID)
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go b/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go
new file mode 100644
index 0000000..0202a00
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go
@@ -0,0 +1,194 @@
+package awserr
+
+import "fmt"
+
+// SprintError returns a string of the formatted error code.
+//
+// Both extra and origErr are optional. If they are included their lines
+// will be added, but if they are not included their lines will be ignored.
+func SprintError(code, message, extra string, origErr error) string {
+ msg := fmt.Sprintf("%s: %s", code, message)
+ if extra != "" {
+ msg = fmt.Sprintf("%s\n\t%s", msg, extra)
+ }
+ if origErr != nil {
+ msg = fmt.Sprintf("%s\ncaused by: %s", msg, origErr.Error())
+ }
+ return msg
+}
+
+// A baseError wraps the code and message which defines an error. It also
+// can be used to wrap an original error object.
+//
+// Should be used as the root for errors satisfying the awserr.Error. Also
+// for any error which does not fit into a specific error wrapper type.
+type baseError struct {
+ // Classification of error
+ code string
+
+ // Detailed information about error
+ message string
+
+ // Optional original error this error is based off of. Allows building
+ // chained errors.
+ errs []error
+}
+
+// newBaseError returns an error object for the code, message, and errors.
+//
+// code is a short no whitespace phrase depicting the classification of
+// the error that is being created.
+//
+// message is the free flow string containing detailed information about the
+// error.
+//
+// origErrs is the error objects which will be nested under the new errors to
+// be returned.
+func newBaseError(code, message string, origErrs []error) *baseError {
+ b := &baseError{
+ code: code,
+ message: message,
+ errs: origErrs,
+ }
+
+ return b
+}
+
+// Error returns the string representation of the error.
+//
+// See ErrorWithExtra for formatting.
+//
+// Satisfies the error interface.
+func (b baseError) Error() string {
+ size := len(b.errs)
+ if size > 0 {
+ return SprintError(b.code, b.message, "", errorList(b.errs))
+ }
+
+ return SprintError(b.code, b.message, "", nil)
+}
+
+// String returns the string representation of the error.
+// Alias for Error to satisfy the stringer interface.
+func (b baseError) String() string {
+ return b.Error()
+}
+
+// Code returns the short phrase depicting the classification of the error.
+func (b baseError) Code() string {
+ return b.code
+}
+
+// Message returns the error details message.
+func (b baseError) Message() string {
+ return b.message
+}
+
+// OrigErr returns the original error if one was set. Nil is returned if no
+// error was set. This only returns the first element in the list. If the full
+// list is needed, use BatchedErrors.
+func (b baseError) OrigErr() error {
+ switch len(b.errs) {
+ case 0:
+ return nil
+ case 1:
+ return b.errs[0]
+ default:
+ if err, ok := b.errs[0].(Error); ok {
+ return NewBatchError(err.Code(), err.Message(), b.errs[1:])
+ }
+ return NewBatchError("BatchedErrors",
+ "multiple errors occurred", b.errs)
+ }
+}
+
+// OrigErrs returns the original errors if one was set. An empty slice is
+// returned if no error was set.
+func (b baseError) OrigErrs() []error {
+ return b.errs
+}
+
+// So that the Error interface type can be included as an anonymous field
+// in the requestError struct and not conflict with the error.Error() method.
+type awsError Error
+
+// A requestError wraps a request or service error.
+//
+// Composed of baseError for code, message, and original error.
+type requestError struct {
+ awsError
+ statusCode int
+ requestID string
+}
+
+// newRequestError returns a wrapped error with additional information for
+// request status code, and service requestID.
+//
+// Should be used to wrap all request which involve service requests. Even if
+// the request failed without a service response, but had an HTTP status code
+// that may be meaningful.
+//
+// Also wraps original errors via the baseError.
+func newRequestError(err Error, statusCode int, requestID string) *requestError {
+ return &requestError{
+ awsError: err,
+ statusCode: statusCode,
+ requestID: requestID,
+ }
+}
+
+// Error returns the string representation of the error.
+// Satisfies the error interface.
+func (r requestError) Error() string {
+ extra := fmt.Sprintf("status code: %d, request id: %s",
+ r.statusCode, r.requestID)
+ return SprintError(r.Code(), r.Message(), extra, r.OrigErr())
+}
+
+// String returns the string representation of the error.
+// Alias for Error to satisfy the stringer interface.
+func (r requestError) String() string {
+ return r.Error()
+}
+
+// StatusCode returns the wrapped status code for the error
+func (r requestError) StatusCode() int {
+ return r.statusCode
+}
+
+// RequestID returns the wrapped requestID
+func (r requestError) RequestID() string {
+ return r.requestID
+}
+
+// OrigErrs returns the original errors if one was set. An empty slice is
+// returned if no error was set.
+func (r requestError) OrigErrs() []error {
+ if b, ok := r.awsError.(BatchedErrors); ok {
+ return b.OrigErrs()
+ }
+ return []error{r.OrigErr()}
+}
+
+// An error list that satisfies the golang interface
+type errorList []error
+
+// Error returns the string representation of the error.
+//
+// Satisfies the error interface.
+func (e errorList) Error() string {
+ msg := ""
+ // How do we want to handle the array size being zero
+ if size := len(e); size > 0 {
+ for i := 0; i < size; i++ {
+ msg += fmt.Sprintf("%s", e[i].Error())
+ // We check the next index to see if it is within the slice.
+ // If it is, then we append a newline. We do this, because unit tests
+ // could be broken with the additional '\n'
+ if i+1 < size {
+ msg += "\n"
+ }
+ }
+ }
+ return msg
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go
new file mode 100644
index 0000000..1a3d106
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go
@@ -0,0 +1,108 @@
+package awsutil
+
+import (
+ "io"
+ "reflect"
+ "time"
+)
+
+// Copy deeply copies a src structure to dst. Useful for copying request and
+// response structures.
+//
+// Can copy between structs of different type, but will only copy fields which
+// are assignable, and exist in both structs. Fields which are not assignable,
+// or do not exist in both structs are ignored.
+func Copy(dst, src interface{}) {
+ dstval := reflect.ValueOf(dst)
+ if !dstval.IsValid() {
+ panic("Copy dst cannot be nil")
+ }
+
+ rcopy(dstval, reflect.ValueOf(src), true)
+}
+
+// CopyOf returns a copy of src while also allocating the memory for dst.
+// src must be a pointer type or this operation will fail.
+func CopyOf(src interface{}) (dst interface{}) {
+ dsti := reflect.New(reflect.TypeOf(src).Elem())
+ dst = dsti.Interface()
+ rcopy(dsti, reflect.ValueOf(src), true)
+ return
+}
+
+// rcopy performs a recursive copy of values from the source to destination.
+//
+// root is used to skip certain aspects of the copy which are not valid
+// for the root node of a object.
+func rcopy(dst, src reflect.Value, root bool) {
+ if !src.IsValid() {
+ return
+ }
+
+ switch src.Kind() {
+ case reflect.Ptr:
+ if _, ok := src.Interface().(io.Reader); ok {
+ if dst.Kind() == reflect.Ptr && dst.Elem().CanSet() {
+ dst.Elem().Set(src)
+ } else if dst.CanSet() {
+ dst.Set(src)
+ }
+ } else {
+ e := src.Type().Elem()
+ if dst.CanSet() && !src.IsNil() {
+ if _, ok := src.Interface().(*time.Time); !ok {
+ dst.Set(reflect.New(e))
+ } else {
+ tempValue := reflect.New(e)
+ tempValue.Elem().Set(src.Elem())
+ // Sets time.Time's unexported values
+ dst.Set(tempValue)
+ }
+ }
+ if src.Elem().IsValid() {
+ // Keep the current root state since the depth hasn't changed
+ rcopy(dst.Elem(), src.Elem(), root)
+ }
+ }
+ case reflect.Struct:
+ t := dst.Type()
+ for i := 0; i < t.NumField(); i++ {
+ name := t.Field(i).Name
+ srcVal := src.FieldByName(name)
+ dstVal := dst.FieldByName(name)
+ if srcVal.IsValid() && dstVal.CanSet() {
+ rcopy(dstVal, srcVal, false)
+ }
+ }
+ case reflect.Slice:
+ if src.IsNil() {
+ break
+ }
+
+ s := reflect.MakeSlice(src.Type(), src.Len(), src.Cap())
+ dst.Set(s)
+ for i := 0; i < src.Len(); i++ {
+ rcopy(dst.Index(i), src.Index(i), false)
+ }
+ case reflect.Map:
+ if src.IsNil() {
+ break
+ }
+
+ s := reflect.MakeMap(src.Type())
+ dst.Set(s)
+ for _, k := range src.MapKeys() {
+ v := src.MapIndex(k)
+ v2 := reflect.New(v.Type()).Elem()
+ rcopy(v2, v, false)
+ dst.SetMapIndex(k, v2)
+ }
+ default:
+ // Assign the value if possible. If its not assignable, the value would
+ // need to be converted and the impact of that may be unexpected, or is
+ // not compatible with the dst type.
+ if src.Type().AssignableTo(dst.Type()) {
+ dst.Set(src)
+ }
+ }
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go
new file mode 100644
index 0000000..59fa4a5
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go
@@ -0,0 +1,27 @@
+package awsutil
+
+import (
+ "reflect"
+)
+
+// DeepEqual returns if the two values are deeply equal like reflect.DeepEqual.
+// In addition to this, this method will also dereference the input values if
+// possible so the DeepEqual performed will not fail if one parameter is a
+// pointer and the other is not.
+//
+// DeepEqual will not perform indirection of nested values of the input parameters.
+func DeepEqual(a, b interface{}) bool {
+ ra := reflect.Indirect(reflect.ValueOf(a))
+ rb := reflect.Indirect(reflect.ValueOf(b))
+
+ if raValid, rbValid := ra.IsValid(), rb.IsValid(); !raValid && !rbValid {
+ // If the elements are both nil, and of the same type the are equal
+ // If they are of different types they are not equal
+ return reflect.TypeOf(a) == reflect.TypeOf(b)
+ } else if raValid != rbValid {
+ // Both values must be valid to be equal
+ return false
+ }
+
+ return reflect.DeepEqual(ra.Interface(), rb.Interface())
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go
new file mode 100644
index 0000000..11c52c3
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go
@@ -0,0 +1,222 @@
+package awsutil
+
+import (
+ "reflect"
+ "regexp"
+ "strconv"
+ "strings"
+
+ "github.com/jmespath/go-jmespath"
+)
+
+var indexRe = regexp.MustCompile(`(.+)\[(-?\d+)?\]$`)
+
+// rValuesAtPath returns a slice of values found in value v. The values
+// in v are explored recursively so all nested values are collected.
+func rValuesAtPath(v interface{}, path string, createPath, caseSensitive, nilTerm bool) []reflect.Value {
+ pathparts := strings.Split(path, "||")
+ if len(pathparts) > 1 {
+ for _, pathpart := range pathparts {
+ vals := rValuesAtPath(v, pathpart, createPath, caseSensitive, nilTerm)
+ if len(vals) > 0 {
+ return vals
+ }
+ }
+ return nil
+ }
+
+ values := []reflect.Value{reflect.Indirect(reflect.ValueOf(v))}
+ components := strings.Split(path, ".")
+ for len(values) > 0 && len(components) > 0 {
+ var index *int64
+ var indexStar bool
+ c := strings.TrimSpace(components[0])
+ if c == "" { // no actual component, illegal syntax
+ return nil
+ } else if caseSensitive && c != "*" && strings.ToLower(c[0:1]) == c[0:1] {
+ // TODO normalize case for user
+ return nil // don't support unexported fields
+ }
+
+ // parse this component
+ if m := indexRe.FindStringSubmatch(c); m != nil {
+ c = m[1]
+ if m[2] == "" {
+ index = nil
+ indexStar = true
+ } else {
+ i, _ := strconv.ParseInt(m[2], 10, 32)
+ index = &i
+ indexStar = false
+ }
+ }
+
+ nextvals := []reflect.Value{}
+ for _, value := range values {
+ // pull component name out of struct member
+ if value.Kind() != reflect.Struct {
+ continue
+ }
+
+ if c == "*" { // pull all members
+ for i := 0; i < value.NumField(); i++ {
+ if f := reflect.Indirect(value.Field(i)); f.IsValid() {
+ nextvals = append(nextvals, f)
+ }
+ }
+ continue
+ }
+
+ value = value.FieldByNameFunc(func(name string) bool {
+ if c == name {
+ return true
+ } else if !caseSensitive && strings.ToLower(name) == strings.ToLower(c) {
+ return true
+ }
+ return false
+ })
+
+ if nilTerm && value.Kind() == reflect.Ptr && len(components[1:]) == 0 {
+ if !value.IsNil() {
+ value.Set(reflect.Zero(value.Type()))
+ }
+ return []reflect.Value{value}
+ }
+
+ if createPath && value.Kind() == reflect.Ptr && value.IsNil() {
+ // TODO if the value is the terminus it should not be created
+ // if the value to be set to its position is nil.
+ value.Set(reflect.New(value.Type().Elem()))
+ value = value.Elem()
+ } else {
+ value = reflect.Indirect(value)
+ }
+
+ if value.Kind() == reflect.Slice || value.Kind() == reflect.Map {
+ if !createPath && value.IsNil() {
+ value = reflect.ValueOf(nil)
+ }
+ }
+
+ if value.IsValid() {
+ nextvals = append(nextvals, value)
+ }
+ }
+ values = nextvals
+
+ if indexStar || index != nil {
+ nextvals = []reflect.Value{}
+ for _, valItem := range values {
+ value := reflect.Indirect(valItem)
+ if value.Kind() != reflect.Slice {
+ continue
+ }
+
+ if indexStar { // grab all indices
+ for i := 0; i < value.Len(); i++ {
+ idx := reflect.Indirect(value.Index(i))
+ if idx.IsValid() {
+ nextvals = append(nextvals, idx)
+ }
+ }
+ continue
+ }
+
+ // pull out index
+ i := int(*index)
+ if i >= value.Len() { // check out of bounds
+ if createPath {
+ // TODO resize slice
+ } else {
+ continue
+ }
+ } else if i < 0 { // support negative indexing
+ i = value.Len() + i
+ }
+ value = reflect.Indirect(value.Index(i))
+
+ if value.Kind() == reflect.Slice || value.Kind() == reflect.Map {
+ if !createPath && value.IsNil() {
+ value = reflect.ValueOf(nil)
+ }
+ }
+
+ if value.IsValid() {
+ nextvals = append(nextvals, value)
+ }
+ }
+ values = nextvals
+ }
+
+ components = components[1:]
+ }
+ return values
+}
+
+// ValuesAtPath returns a list of values at the case insensitive lexical
+// path inside of a structure.
+func ValuesAtPath(i interface{}, path string) ([]interface{}, error) {
+ result, err := jmespath.Search(path, i)
+ if err != nil {
+ return nil, err
+ }
+
+ v := reflect.ValueOf(result)
+ if !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) {
+ return nil, nil
+ }
+ if s, ok := result.([]interface{}); ok {
+ return s, err
+ }
+ if v.Kind() == reflect.Map && v.Len() == 0 {
+ return nil, nil
+ }
+ if v.Kind() == reflect.Slice {
+ out := make([]interface{}, v.Len())
+ for i := 0; i < v.Len(); i++ {
+ out[i] = v.Index(i).Interface()
+ }
+ return out, nil
+ }
+
+ return []interface{}{result}, nil
+}
+
+// SetValueAtPath sets a value at the case insensitive lexical path inside
+// of a structure.
+func SetValueAtPath(i interface{}, path string, v interface{}) {
+ if rvals := rValuesAtPath(i, path, true, false, v == nil); rvals != nil {
+ for _, rval := range rvals {
+ if rval.Kind() == reflect.Ptr && rval.IsNil() {
+ continue
+ }
+ setValue(rval, v)
+ }
+ }
+}
+
+func setValue(dstVal reflect.Value, src interface{}) {
+ if dstVal.Kind() == reflect.Ptr {
+ dstVal = reflect.Indirect(dstVal)
+ }
+ srcVal := reflect.ValueOf(src)
+
+ if !srcVal.IsValid() { // src is literal nil
+ if dstVal.CanAddr() {
+ // Convert to pointer so that pointer's value can be nil'ed
+ // dstVal = dstVal.Addr()
+ }
+ dstVal.Set(reflect.Zero(dstVal.Type()))
+
+ } else if srcVal.Kind() == reflect.Ptr {
+ if srcVal.IsNil() {
+ srcVal = reflect.Zero(dstVal.Type())
+ } else {
+ srcVal = reflect.ValueOf(src).Elem()
+ }
+ dstVal.Set(srcVal)
+ } else {
+ dstVal.Set(srcVal)
+ }
+
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go
new file mode 100644
index 0000000..fc38172
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go
@@ -0,0 +1,107 @@
+package awsutil
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "reflect"
+ "strings"
+)
+
+// Prettify returns the string representation of a value.
+func Prettify(i interface{}) string {
+ var buf bytes.Buffer
+ prettify(reflect.ValueOf(i), 0, &buf)
+ return buf.String()
+}
+
+// prettify will recursively walk value v to build a textual
+// representation of the value.
+func prettify(v reflect.Value, indent int, buf *bytes.Buffer) {
+ for v.Kind() == reflect.Ptr {
+ v = v.Elem()
+ }
+
+ switch v.Kind() {
+ case reflect.Struct:
+ strtype := v.Type().String()
+ if strtype == "time.Time" {
+ fmt.Fprintf(buf, "%s", v.Interface())
+ break
+ } else if strings.HasPrefix(strtype, "io.") {
+ buf.WriteString("<buffer>")
+ break
+ }
+
+ buf.WriteString("{\n")
+
+ names := []string{}
+ for i := 0; i < v.Type().NumField(); i++ {
+ name := v.Type().Field(i).Name
+ f := v.Field(i)
+ if name[0:1] == strings.ToLower(name[0:1]) {
+ continue // ignore unexported fields
+ }
+ if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice || f.Kind() == reflect.Map) && f.IsNil() {
+ continue // ignore unset fields
+ }
+ names = append(names, name)
+ }
+
+ for i, n := range names {
+ val := v.FieldByName(n)
+ buf.WriteString(strings.Repeat(" ", indent+2))
+ buf.WriteString(n + ": ")
+ prettify(val, indent+2, buf)
+
+ if i < len(names)-1 {
+ buf.WriteString(",\n")
+ }
+ }
+
+ buf.WriteString("\n" + strings.Repeat(" ", indent) + "}")
+ case reflect.Slice:
+ nl, id, id2 := "", "", ""
+ if v.Len() > 3 {
+ nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2)
+ }
+ buf.WriteString("[" + nl)
+ for i := 0; i < v.Len(); i++ {
+ buf.WriteString(id2)
+ prettify(v.Index(i), indent+2, buf)
+
+ if i < v.Len()-1 {
+ buf.WriteString("," + nl)
+ }
+ }
+
+ buf.WriteString(nl + id + "]")
+ case reflect.Map:
+ buf.WriteString("{\n")
+
+ for i, k := range v.MapKeys() {
+ buf.WriteString(strings.Repeat(" ", indent+2))
+ buf.WriteString(k.String() + ": ")
+ prettify(v.MapIndex(k), indent+2, buf)
+
+ if i < v.Len()-1 {
+ buf.WriteString(",\n")
+ }
+ }
+
+ buf.WriteString("\n" + strings.Repeat(" ", indent) + "}")
+ default:
+ if !v.IsValid() {
+ fmt.Fprint(buf, "<invalid value>")
+ return
+ }
+ format := "%v"
+ switch v.Interface().(type) {
+ case string:
+ format = "%q"
+ case io.ReadSeeker, io.Reader:
+ format = "buffer(%p)"
+ }
+ fmt.Fprintf(buf, format, v.Interface())
+ }
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go
new file mode 100644
index 0000000..b6432f1
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go
@@ -0,0 +1,89 @@
+package awsutil
+
+import (
+ "bytes"
+ "fmt"
+ "reflect"
+ "strings"
+)
+
+// StringValue returns the string representation of a value.
+func StringValue(i interface{}) string {
+ var buf bytes.Buffer
+ stringValue(reflect.ValueOf(i), 0, &buf)
+ return buf.String()
+}
+
+func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) {
+ for v.Kind() == reflect.Ptr {
+ v = v.Elem()
+ }
+
+ switch v.Kind() {
+ case reflect.Struct:
+ buf.WriteString("{\n")
+
+ names := []string{}
+ for i := 0; i < v.Type().NumField(); i++ {
+ name := v.Type().Field(i).Name
+ f := v.Field(i)
+ if name[0:1] == strings.ToLower(name[0:1]) {
+ continue // ignore unexported fields
+ }
+ if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice) && f.IsNil() {
+ continue // ignore unset fields
+ }
+ names = append(names, name)
+ }
+
+ for i, n := range names {
+ val := v.FieldByName(n)
+ buf.WriteString(strings.Repeat(" ", indent+2))
+ buf.WriteString(n + ": ")
+ stringValue(val, indent+2, buf)
+
+ if i < len(names)-1 {
+ buf.WriteString(",\n")
+ }
+ }
+
+ buf.WriteString("\n" + strings.Repeat(" ", indent) + "}")
+ case reflect.Slice:
+ nl, id, id2 := "", "", ""
+ if v.Len() > 3 {
+ nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2)
+ }
+ buf.WriteString("[" + nl)
+ for i := 0; i < v.Len(); i++ {
+ buf.WriteString(id2)
+ stringValue(v.Index(i), indent+2, buf)
+
+ if i < v.Len()-1 {
+ buf.WriteString("," + nl)
+ }
+ }
+
+ buf.WriteString(nl + id + "]")
+ case reflect.Map:
+ buf.WriteString("{\n")
+
+ for i, k := range v.MapKeys() {
+ buf.WriteString(strings.Repeat(" ", indent+2))
+ buf.WriteString(k.String() + ": ")
+ stringValue(v.MapIndex(k), indent+2, buf)
+
+ if i < v.Len()-1 {
+ buf.WriteString(",\n")
+ }
+ }
+
+ buf.WriteString("\n" + strings.Repeat(" ", indent) + "}")
+ default:
+ format := "%v"
+ switch v.Interface().(type) {
+ case string:
+ format = "%q"
+ }
+ fmt.Fprintf(buf, format, v.Interface())
+ }
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go
new file mode 100644
index 0000000..7c0e7d9
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go
@@ -0,0 +1,137 @@
+package client
+
+import (
+ "fmt"
+ "net/http/httputil"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/client/metadata"
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+// A Config provides configuration to a service client instance.
+type Config struct {
+ Config *aws.Config
+ Handlers request.Handlers
+ Endpoint, SigningRegion string
+}
+
+// ConfigProvider provides a generic way for a service client to receive
+// the ClientConfig without circular dependencies.
+type ConfigProvider interface {
+ ClientConfig(serviceName string, cfgs ...*aws.Config) Config
+}
+
+// A Client implements the base client request and response handling
+// used by all service clients.
+type Client struct {
+ request.Retryer
+ metadata.ClientInfo
+
+ Config aws.Config
+ Handlers request.Handlers
+}
+
+// New will return a pointer to a new initialized service client.
+func New(cfg aws.Config, info metadata.ClientInfo, handlers request.Handlers, options ...func(*Client)) *Client {
+ svc := &Client{
+ Config: cfg,
+ ClientInfo: info,
+ Handlers: handlers,
+ }
+
+ switch retryer, ok := cfg.Retryer.(request.Retryer); {
+ case ok:
+ svc.Retryer = retryer
+ case cfg.Retryer != nil && cfg.Logger != nil:
+ s := fmt.Sprintf("WARNING: %T does not implement request.Retryer; using DefaultRetryer instead", cfg.Retryer)
+ cfg.Logger.Log(s)
+ fallthrough
+ default:
+ maxRetries := aws.IntValue(cfg.MaxRetries)
+ if cfg.MaxRetries == nil || maxRetries == aws.UseServiceDefaultRetries {
+ maxRetries = 3
+ }
+ svc.Retryer = DefaultRetryer{NumMaxRetries: maxRetries}
+ }
+
+ svc.AddDebugHandlers()
+
+ for _, option := range options {
+ option(svc)
+ }
+
+ return svc
+}
+
+// NewRequest returns a new Request pointer for the service API
+// operation and parameters.
+func (c *Client) NewRequest(operation *request.Operation, params interface{}, data interface{}) *request.Request {
+ return request.New(c.Config, c.ClientInfo, c.Handlers, c.Retryer, operation, params, data)
+}
+
+// AddDebugHandlers injects debug logging handlers into the service to log request
+// debug information.
+func (c *Client) AddDebugHandlers() {
+ if !c.Config.LogLevel.AtLeast(aws.LogDebug) {
+ return
+ }
+
+ c.Handlers.Send.PushFront(logRequest)
+ c.Handlers.Send.PushBack(logResponse)
+}
+
+const logReqMsg = `DEBUG: Request %s/%s Details:
+---[ REQUEST POST-SIGN ]-----------------------------
+%s
+-----------------------------------------------------`
+
+const logReqErrMsg = `DEBUG ERROR: Request %s/%s:
+---[ REQUEST DUMP ERROR ]-----------------------------
+%s
+-----------------------------------------------------`
+
+func logRequest(r *request.Request) {
+ logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody)
+ dumpedBody, err := httputil.DumpRequestOut(r.HTTPRequest, logBody)
+ if err != nil {
+ r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err))
+ return
+ }
+
+ if logBody {
+ // Reset the request body because dumpRequest will re-wrap the r.HTTPRequest's
+ // Body as a NoOpCloser and will not be reset after read by the HTTP
+ // client reader.
+ r.ResetBody()
+ }
+
+ r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.ClientInfo.ServiceName, r.Operation.Name, string(dumpedBody)))
+}
+
+const logRespMsg = `DEBUG: Response %s/%s Details:
+---[ RESPONSE ]--------------------------------------
+%s
+-----------------------------------------------------`
+
+const logRespErrMsg = `DEBUG ERROR: Response %s/%s:
+---[ RESPONSE DUMP ERROR ]-----------------------------
+%s
+-----------------------------------------------------`
+
+func logResponse(r *request.Request) {
+ var msg = "no response data"
+ if r.HTTPResponse != nil {
+ logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody)
+ dumpedBody, err := httputil.DumpResponse(r.HTTPResponse, logBody)
+ if err != nil {
+ r.Config.Logger.Log(fmt.Sprintf(logRespErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err))
+ return
+ }
+
+ msg = string(dumpedBody)
+ } else if r.Error != nil {
+ msg = r.Error.Error()
+ }
+ r.Config.Logger.Log(fmt.Sprintf(logRespMsg, r.ClientInfo.ServiceName, r.Operation.Name, msg))
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go
new file mode 100644
index 0000000..43a3676
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go
@@ -0,0 +1,90 @@
+package client
+
+import (
+ "math/rand"
+ "sync"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+// DefaultRetryer implements basic retry logic using exponential backoff for
+// most services. If you want to implement custom retry logic, implement the
+// request.Retryer interface or create a structure type that composes this
+// struct and override the specific methods. For example, to override only
+// the MaxRetries method:
+//
+// type retryer struct {
+// service.DefaultRetryer
+// }
+//
+// // This implementation always has 100 max retries
+// func (d retryer) MaxRetries() uint { return 100 }
+type DefaultRetryer struct {
+ NumMaxRetries int
+}
+
+// MaxRetries returns the number of maximum returns the service will use to make
+// an individual API request.
+func (d DefaultRetryer) MaxRetries() int {
+ return d.NumMaxRetries
+}
+
+var seededRand = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())})
+
+// RetryRules returns the delay duration before retrying this request again
+func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration {
+ // Set the upper limit of delay in retrying at ~five minutes
+ minTime := 30
+ throttle := d.shouldThrottle(r)
+ if throttle {
+ minTime = 500
+ }
+
+ retryCount := r.RetryCount
+ if retryCount > 13 {
+ retryCount = 13
+ } else if throttle && retryCount > 8 {
+ retryCount = 8
+ }
+
+ delay := (1 << uint(retryCount)) * (seededRand.Intn(minTime) + minTime)
+ return time.Duration(delay) * time.Millisecond
+}
+
+// ShouldRetry returns true if the request should be retried.
+func (d DefaultRetryer) ShouldRetry(r *request.Request) bool {
+ if r.HTTPResponse.StatusCode >= 500 {
+ return true
+ }
+ return r.IsErrorRetryable() || d.shouldThrottle(r)
+}
+
+// ShouldThrottle returns true if the request should be throttled.
+func (d DefaultRetryer) shouldThrottle(r *request.Request) bool {
+ if r.HTTPResponse.StatusCode == 502 ||
+ r.HTTPResponse.StatusCode == 503 ||
+ r.HTTPResponse.StatusCode == 504 {
+ return true
+ }
+ return r.IsErrorThrottle()
+}
+
+// lockedSource is a thread-safe implementation of rand.Source
+type lockedSource struct {
+ lk sync.Mutex
+ src rand.Source
+}
+
+func (r *lockedSource) Int63() (n int64) {
+ r.lk.Lock()
+ n = r.src.Int63()
+ r.lk.Unlock()
+ return
+}
+
+func (r *lockedSource) Seed(seed int64) {
+ r.lk.Lock()
+ r.src.Seed(seed)
+ r.lk.Unlock()
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go b/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go
new file mode 100644
index 0000000..4778056
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go
@@ -0,0 +1,12 @@
+package metadata
+
+// ClientInfo wraps immutable data from the client.Client structure.
+type ClientInfo struct {
+ ServiceName string
+ APIVersion string
+ Endpoint string
+ SigningName string
+ SigningRegion string
+ JSONVersion string
+ TargetPrefix string
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/config.go b/vendor/github.com/aws/aws-sdk-go/aws/config.go
new file mode 100644
index 0000000..34c2bab
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/config.go
@@ -0,0 +1,419 @@
+package aws
+
+import (
+ "net/http"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws/credentials"
+)
+
+// UseServiceDefaultRetries instructs the config to use the service's own
+// default number of retries. This will be the default action if
+// Config.MaxRetries is nil also.
+const UseServiceDefaultRetries = -1
+
+// RequestRetryer is an alias for a type that implements the request.Retryer
+// interface.
+type RequestRetryer interface{}
+
+// A Config provides service configuration for service clients. By default,
+// all clients will use the defaults.DefaultConfig tructure.
+//
+// // Create Session with MaxRetry configuration to be shared by multiple
+// // service clients.
+// sess, err := session.NewSession(&aws.Config{
+// MaxRetries: aws.Int(3),
+// })
+//
+// // Create S3 service client with a specific Region.
+// svc := s3.New(sess, &aws.Config{
+// Region: aws.String("us-west-2"),
+// })
+type Config struct {
+ // Enables verbose error printing of all credential chain errors.
+ // Should be used when wanting to see all errors while attempting to
+ // retrieve credentials.
+ CredentialsChainVerboseErrors *bool
+
+ // The credentials object to use when signing requests. Defaults to a
+ // chain of credential providers to search for credentials in environment
+ // variables, shared credential file, and EC2 Instance Roles.
+ Credentials *credentials.Credentials
+
+ // An optional endpoint URL (hostname only or fully qualified URI)
+ // that overrides the default generated endpoint for a client. Set this
+ // to `""` to use the default generated endpoint.
+ //
+ // @note You must still provide a `Region` value when specifying an
+ // endpoint for a client.
+ Endpoint *string
+
+ // The region to send requests to. This parameter is required and must
+ // be configured globally or on a per-client basis unless otherwise
+ // noted. A full list of regions is found in the "Regions and Endpoints"
+ // document.
+ //
+ // @see http://docs.aws.amazon.com/general/latest/gr/rande.html
+ // AWS Regions and Endpoints
+ Region *string
+
+ // Set this to `true` to disable SSL when sending requests. Defaults
+ // to `false`.
+ DisableSSL *bool
+
+ // The HTTP client to use when sending requests. Defaults to
+ // `http.DefaultClient`.
+ HTTPClient *http.Client
+
+ // An integer value representing the logging level. The default log level
+ // is zero (LogOff), which represents no logging. To enable logging set
+ // to a LogLevel Value.
+ LogLevel *LogLevelType
+
+ // The logger writer interface to write logging messages to. Defaults to
+ // standard out.
+ Logger Logger
+
+ // The maximum number of times that a request will be retried for failures.
+ // Defaults to -1, which defers the max retry setting to the service
+ // specific configuration.
+ MaxRetries *int
+
+ // Retryer guides how HTTP requests should be retried in case of
+ // recoverable failures.
+ //
+ // When nil or the value does not implement the request.Retryer interface,
+ // the request.DefaultRetryer will be used.
+ //
+ // When both Retryer and MaxRetries are non-nil, the former is used and
+ // the latter ignored.
+ //
+ // To set the Retryer field in a type-safe manner and with chaining, use
+ // the request.WithRetryer helper function:
+ //
+ // cfg := request.WithRetryer(aws.NewConfig(), myRetryer)
+ //
+ Retryer RequestRetryer
+
+ // Disables semantic parameter validation, which validates input for
+ // missing required fields and/or other semantic request input errors.
+ DisableParamValidation *bool
+
+ // Disables the computation of request and response checksums, e.g.,
+ // CRC32 checksums in Amazon DynamoDB.
+ DisableComputeChecksums *bool
+
+ // Set this to `true` to force the request to use path-style addressing,
+ // i.e., `http://s3.amazonaws.com/BUCKET/KEY`. By default, the S3 client
+ // will use virtual hosted bucket addressing when possible
+ // (`http://BUCKET.s3.amazonaws.com/KEY`).
+ //
+ // @note This configuration option is specific to the Amazon S3 service.
+ // @see http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html
+ // Amazon S3: Virtual Hosting of Buckets
+ S3ForcePathStyle *bool
+
+ // Set this to `true` to disable the SDK adding the `Expect: 100-Continue`
+ // header to PUT requests over 2MB of content. 100-Continue instructs the
+ // HTTP client not to send the body until the service responds with a
+ // `continue` status. This is useful to prevent sending the request body
+ // until after the request is authenticated, and validated.
+ //
+ // http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
+ //
+ // 100-Continue is only enabled for Go 1.6 and above. See `http.Transport`'s
+ // `ExpectContinueTimeout` for information on adjusting the continue wait
+ // timeout. https://golang.org/pkg/net/http/#Transport
+ //
+ // You should use this flag to disble 100-Continue if you experience issues
+ // with proxies or third party S3 compatible services.
+ S3Disable100Continue *bool
+
+ // Set this to `true` to enable S3 Accelerate feature. For all operations
+ // compatible with S3 Accelerate will use the accelerate endpoint for
+ // requests. Requests not compatible will fall back to normal S3 requests.
+ //
+ // The bucket must be enable for accelerate to be used with S3 client with
+ // accelerate enabled. If the bucket is not enabled for accelerate an error
+ // will be returned. The bucket name must be DNS compatible to also work
+ // with accelerate.
+ S3UseAccelerate *bool
+
+ // Set this to `true` to disable the EC2Metadata client from overriding the
+ // default http.Client's Timeout. This is helpful if you do not want the
+ // EC2Metadata client to create a new http.Client. This options is only
+ // meaningful if you're not already using a custom HTTP client with the
+ // SDK. Enabled by default.
+ //
+ // Must be set and provided to the session.NewSession() in order to disable
+ // the EC2Metadata overriding the timeout for default credentials chain.
+ //
+ // Example:
+ // sess, err := session.NewSession(aws.NewConfig().WithEC2MetadataDiableTimeoutOverride(true))
+ //
+ // svc := s3.New(sess)
+ //
+ EC2MetadataDisableTimeoutOverride *bool
+
+ // Instructs the endpiont to be generated for a service client to
+ // be the dual stack endpoint. The dual stack endpoint will support
+ // both IPv4 and IPv6 addressing.
+ //
+ // Setting this for a service which does not support dual stack will fail
+ // to make requets. It is not recommended to set this value on the session
+ // as it will apply to all service clients created with the session. Even
+ // services which don't support dual stack endpoints.
+ //
+ // If the Endpoint config value is also provided the UseDualStack flag
+ // will be ignored.
+ //
+ // Only supported with.
+ //
+ // sess, err := session.NewSession()
+ //
+ // svc := s3.New(sess, &aws.Config{
+ // UseDualStack: aws.Bool(true),
+ // })
+ UseDualStack *bool
+
+ // SleepDelay is an override for the func the SDK will call when sleeping
+ // during the lifecycle of a request. Specifically this will be used for
+ // request delays. This value should only be used for testing. To adjust
+ // the delay of a request see the aws/client.DefaultRetryer and
+ // aws/request.Retryer.
+ SleepDelay func(time.Duration)
+}
+
+// NewConfig returns a new Config pointer that can be chained with builder
+// methods to set multiple configuration values inline without using pointers.
+//
+// // Create Session with MaxRetry configuration to be shared by multiple
+// // service clients.
+// sess, err := session.NewSession(aws.NewConfig().
+// WithMaxRetries(3),
+// )
+//
+// // Create S3 service client with a specific Region.
+// svc := s3.New(sess, aws.NewConfig().
+// WithRegion("us-west-2"),
+// )
+func NewConfig() *Config {
+ return &Config{}
+}
+
+// WithCredentialsChainVerboseErrors sets a config verbose errors boolean and returning
+// a Config pointer.
+func (c *Config) WithCredentialsChainVerboseErrors(verboseErrs bool) *Config {
+ c.CredentialsChainVerboseErrors = &verboseErrs
+ return c
+}
+
+// WithCredentials sets a config Credentials value returning a Config pointer
+// for chaining.
+func (c *Config) WithCredentials(creds *credentials.Credentials) *Config {
+ c.Credentials = creds
+ return c
+}
+
+// WithEndpoint sets a config Endpoint value returning a Config pointer for
+// chaining.
+func (c *Config) WithEndpoint(endpoint string) *Config {
+ c.Endpoint = &endpoint
+ return c
+}
+
+// WithRegion sets a config Region value returning a Config pointer for
+// chaining.
+func (c *Config) WithRegion(region string) *Config {
+ c.Region = &region
+ return c
+}
+
+// WithDisableSSL sets a config DisableSSL value returning a Config pointer
+// for chaining.
+func (c *Config) WithDisableSSL(disable bool) *Config {
+ c.DisableSSL = &disable
+ return c
+}
+
+// WithHTTPClient sets a config HTTPClient value returning a Config pointer
+// for chaining.
+func (c *Config) WithHTTPClient(client *http.Client) *Config {
+ c.HTTPClient = client
+ return c
+}
+
+// WithMaxRetries sets a config MaxRetries value returning a Config pointer
+// for chaining.
+func (c *Config) WithMaxRetries(max int) *Config {
+ c.MaxRetries = &max
+ return c
+}
+
+// WithDisableParamValidation sets a config DisableParamValidation value
+// returning a Config pointer for chaining.
+func (c *Config) WithDisableParamValidation(disable bool) *Config {
+ c.DisableParamValidation = &disable
+ return c
+}
+
+// WithDisableComputeChecksums sets a config DisableComputeChecksums value
+// returning a Config pointer for chaining.
+func (c *Config) WithDisableComputeChecksums(disable bool) *Config {
+ c.DisableComputeChecksums = &disable
+ return c
+}
+
+// WithLogLevel sets a config LogLevel value returning a Config pointer for
+// chaining.
+func (c *Config) WithLogLevel(level LogLevelType) *Config {
+ c.LogLevel = &level
+ return c
+}
+
+// WithLogger sets a config Logger value returning a Config pointer for
+// chaining.
+func (c *Config) WithLogger(logger Logger) *Config {
+ c.Logger = logger
+ return c
+}
+
+// WithS3ForcePathStyle sets a config S3ForcePathStyle value returning a Config
+// pointer for chaining.
+func (c *Config) WithS3ForcePathStyle(force bool) *Config {
+ c.S3ForcePathStyle = &force
+ return c
+}
+
+// WithS3Disable100Continue sets a config S3Disable100Continue value returning
+// a Config pointer for chaining.
+func (c *Config) WithS3Disable100Continue(disable bool) *Config {
+ c.S3Disable100Continue = &disable
+ return c
+}
+
+// WithS3UseAccelerate sets a config S3UseAccelerate value returning a Config
+// pointer for chaining.
+func (c *Config) WithS3UseAccelerate(enable bool) *Config {
+ c.S3UseAccelerate = &enable
+ return c
+}
+
+// WithUseDualStack sets a config UseDualStack value returning a Config
+// pointer for chaining.
+func (c *Config) WithUseDualStack(enable bool) *Config {
+ c.UseDualStack = &enable
+ return c
+}
+
+// WithEC2MetadataDisableTimeoutOverride sets a config EC2MetadataDisableTimeoutOverride value
+// returning a Config pointer for chaining.
+func (c *Config) WithEC2MetadataDisableTimeoutOverride(enable bool) *Config {
+ c.EC2MetadataDisableTimeoutOverride = &enable
+ return c
+}
+
+// WithSleepDelay overrides the function used to sleep while waiting for the
+// next retry. Defaults to time.Sleep.
+func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config {
+ c.SleepDelay = fn
+ return c
+}
+
+// MergeIn merges the passed in configs into the existing config object.
+func (c *Config) MergeIn(cfgs ...*Config) {
+ for _, other := range cfgs {
+ mergeInConfig(c, other)
+ }
+}
+
+func mergeInConfig(dst *Config, other *Config) {
+ if other == nil {
+ return
+ }
+
+ if other.CredentialsChainVerboseErrors != nil {
+ dst.CredentialsChainVerboseErrors = other.CredentialsChainVerboseErrors
+ }
+
+ if other.Credentials != nil {
+ dst.Credentials = other.Credentials
+ }
+
+ if other.Endpoint != nil {
+ dst.Endpoint = other.Endpoint
+ }
+
+ if other.Region != nil {
+ dst.Region = other.Region
+ }
+
+ if other.DisableSSL != nil {
+ dst.DisableSSL = other.DisableSSL
+ }
+
+ if other.HTTPClient != nil {
+ dst.HTTPClient = other.HTTPClient
+ }
+
+ if other.LogLevel != nil {
+ dst.LogLevel = other.LogLevel
+ }
+
+ if other.Logger != nil {
+ dst.Logger = other.Logger
+ }
+
+ if other.MaxRetries != nil {
+ dst.MaxRetries = other.MaxRetries
+ }
+
+ if other.Retryer != nil {
+ dst.Retryer = other.Retryer
+ }
+
+ if other.DisableParamValidation != nil {
+ dst.DisableParamValidation = other.DisableParamValidation
+ }
+
+ if other.DisableComputeChecksums != nil {
+ dst.DisableComputeChecksums = other.DisableComputeChecksums
+ }
+
+ if other.S3ForcePathStyle != nil {
+ dst.S3ForcePathStyle = other.S3ForcePathStyle
+ }
+
+ if other.S3Disable100Continue != nil {
+ dst.S3Disable100Continue = other.S3Disable100Continue
+ }
+
+ if other.S3UseAccelerate != nil {
+ dst.S3UseAccelerate = other.S3UseAccelerate
+ }
+
+ if other.UseDualStack != nil {
+ dst.UseDualStack = other.UseDualStack
+ }
+
+ if other.EC2MetadataDisableTimeoutOverride != nil {
+ dst.EC2MetadataDisableTimeoutOverride = other.EC2MetadataDisableTimeoutOverride
+ }
+
+ if other.SleepDelay != nil {
+ dst.SleepDelay = other.SleepDelay
+ }
+}
+
+// Copy will return a shallow copy of the Config object. If any additional
+// configurations are provided they will be merged into the new config returned.
+func (c *Config) Copy(cfgs ...*Config) *Config {
+ dst := &Config{}
+ dst.MergeIn(c)
+
+ for _, cfg := range cfgs {
+ dst.MergeIn(cfg)
+ }
+
+ return dst
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go b/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go
new file mode 100644
index 0000000..3b73a7d
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go
@@ -0,0 +1,369 @@
+package aws
+
+import "time"
+
+// String returns a pointer to the string value passed in.
+func String(v string) *string {
+ return &v
+}
+
+// StringValue returns the value of the string pointer passed in or
+// "" if the pointer is nil.
+func StringValue(v *string) string {
+ if v != nil {
+ return *v
+ }
+ return ""
+}
+
+// StringSlice converts a slice of string values into a slice of
+// string pointers
+func StringSlice(src []string) []*string {
+ dst := make([]*string, len(src))
+ for i := 0; i < len(src); i++ {
+ dst[i] = &(src[i])
+ }
+ return dst
+}
+
+// StringValueSlice converts a slice of string pointers into a slice of
+// string values
+func StringValueSlice(src []*string) []string {
+ dst := make([]string, len(src))
+ for i := 0; i < len(src); i++ {
+ if src[i] != nil {
+ dst[i] = *(src[i])
+ }
+ }
+ return dst
+}
+
+// StringMap converts a string map of string values into a string
+// map of string pointers
+func StringMap(src map[string]string) map[string]*string {
+ dst := make(map[string]*string)
+ for k, val := range src {
+ v := val
+ dst[k] = &v
+ }
+ return dst
+}
+
+// StringValueMap converts a string map of string pointers into a string
+// map of string values
+func StringValueMap(src map[string]*string) map[string]string {
+ dst := make(map[string]string)
+ for k, val := range src {
+ if val != nil {
+ dst[k] = *val
+ }
+ }
+ return dst
+}
+
+// Bool returns a pointer to the bool value passed in.
+func Bool(v bool) *bool {
+ return &v
+}
+
+// BoolValue returns the value of the bool pointer passed in or
+// false if the pointer is nil.
+func BoolValue(v *bool) bool {
+ if v != nil {
+ return *v
+ }
+ return false
+}
+
+// BoolSlice converts a slice of bool values into a slice of
+// bool pointers
+func BoolSlice(src []bool) []*bool {
+ dst := make([]*bool, len(src))
+ for i := 0; i < len(src); i++ {
+ dst[i] = &(src[i])
+ }
+ return dst
+}
+
+// BoolValueSlice converts a slice of bool pointers into a slice of
+// bool values
+func BoolValueSlice(src []*bool) []bool {
+ dst := make([]bool, len(src))
+ for i := 0; i < len(src); i++ {
+ if src[i] != nil {
+ dst[i] = *(src[i])
+ }
+ }
+ return dst
+}
+
+// BoolMap converts a string map of bool values into a string
+// map of bool pointers
+func BoolMap(src map[string]bool) map[string]*bool {
+ dst := make(map[string]*bool)
+ for k, val := range src {
+ v := val
+ dst[k] = &v
+ }
+ return dst
+}
+
+// BoolValueMap converts a string map of bool pointers into a string
+// map of bool values
+func BoolValueMap(src map[string]*bool) map[string]bool {
+ dst := make(map[string]bool)
+ for k, val := range src {
+ if val != nil {
+ dst[k] = *val
+ }
+ }
+ return dst
+}
+
+// Int returns a pointer to the int value passed in.
+func Int(v int) *int {
+ return &v
+}
+
+// IntValue returns the value of the int pointer passed in or
+// 0 if the pointer is nil.
+func IntValue(v *int) int {
+ if v != nil {
+ return *v
+ }
+ return 0
+}
+
+// IntSlice converts a slice of int values into a slice of
+// int pointers
+func IntSlice(src []int) []*int {
+ dst := make([]*int, len(src))
+ for i := 0; i < len(src); i++ {
+ dst[i] = &(src[i])
+ }
+ return dst
+}
+
+// IntValueSlice converts a slice of int pointers into a slice of
+// int values
+func IntValueSlice(src []*int) []int {
+ dst := make([]int, len(src))
+ for i := 0; i < len(src); i++ {
+ if src[i] != nil {
+ dst[i] = *(src[i])
+ }
+ }
+ return dst
+}
+
+// IntMap converts a string map of int values into a string
+// map of int pointers
+func IntMap(src map[string]int) map[string]*int {
+ dst := make(map[string]*int)
+ for k, val := range src {
+ v := val
+ dst[k] = &v
+ }
+ return dst
+}
+
+// IntValueMap converts a string map of int pointers into a string
+// map of int values
+func IntValueMap(src map[string]*int) map[string]int {
+ dst := make(map[string]int)
+ for k, val := range src {
+ if val != nil {
+ dst[k] = *val
+ }
+ }
+ return dst
+}
+
+// Int64 returns a pointer to the int64 value passed in.
+func Int64(v int64) *int64 {
+ return &v
+}
+
+// Int64Value returns the value of the int64 pointer passed in or
+// 0 if the pointer is nil.
+func Int64Value(v *int64) int64 {
+ if v != nil {
+ return *v
+ }
+ return 0
+}
+
+// Int64Slice converts a slice of int64 values into a slice of
+// int64 pointers
+func Int64Slice(src []int64) []*int64 {
+ dst := make([]*int64, len(src))
+ for i := 0; i < len(src); i++ {
+ dst[i] = &(src[i])
+ }
+ return dst
+}
+
+// Int64ValueSlice converts a slice of int64 pointers into a slice of
+// int64 values
+func Int64ValueSlice(src []*int64) []int64 {
+ dst := make([]int64, len(src))
+ for i := 0; i < len(src); i++ {
+ if src[i] != nil {
+ dst[i] = *(src[i])
+ }
+ }
+ return dst
+}
+
+// Int64Map converts a string map of int64 values into a string
+// map of int64 pointers
+func Int64Map(src map[string]int64) map[string]*int64 {
+ dst := make(map[string]*int64)
+ for k, val := range src {
+ v := val
+ dst[k] = &v
+ }
+ return dst
+}
+
+// Int64ValueMap converts a string map of int64 pointers into a string
+// map of int64 values
+func Int64ValueMap(src map[string]*int64) map[string]int64 {
+ dst := make(map[string]int64)
+ for k, val := range src {
+ if val != nil {
+ dst[k] = *val
+ }
+ }
+ return dst
+}
+
+// Float64 returns a pointer to the float64 value passed in.
+func Float64(v float64) *float64 {
+ return &v
+}
+
+// Float64Value returns the value of the float64 pointer passed in or
+// 0 if the pointer is nil.
+func Float64Value(v *float64) float64 {
+ if v != nil {
+ return *v
+ }
+ return 0
+}
+
+// Float64Slice converts a slice of float64 values into a slice of
+// float64 pointers
+func Float64Slice(src []float64) []*float64 {
+ dst := make([]*float64, len(src))
+ for i := 0; i < len(src); i++ {
+ dst[i] = &(src[i])
+ }
+ return dst
+}
+
+// Float64ValueSlice converts a slice of float64 pointers into a slice of
+// float64 values
+func Float64ValueSlice(src []*float64) []float64 {
+ dst := make([]float64, len(src))
+ for i := 0; i < len(src); i++ {
+ if src[i] != nil {
+ dst[i] = *(src[i])
+ }
+ }
+ return dst
+}
+
+// Float64Map converts a string map of float64 values into a string
+// map of float64 pointers
+func Float64Map(src map[string]float64) map[string]*float64 {
+ dst := make(map[string]*float64)
+ for k, val := range src {
+ v := val
+ dst[k] = &v
+ }
+ return dst
+}
+
+// Float64ValueMap converts a string map of float64 pointers into a string
+// map of float64 values
+func Float64ValueMap(src map[string]*float64) map[string]float64 {
+ dst := make(map[string]float64)
+ for k, val := range src {
+ if val != nil {
+ dst[k] = *val
+ }
+ }
+ return dst
+}
+
+// Time returns a pointer to the time.Time value passed in.
+func Time(v time.Time) *time.Time {
+ return &v
+}
+
+// TimeValue returns the value of the time.Time pointer passed in or
+// time.Time{} if the pointer is nil.
+func TimeValue(v *time.Time) time.Time {
+ if v != nil {
+ return *v
+ }
+ return time.Time{}
+}
+
+// TimeUnixMilli returns a Unix timestamp in milliseconds from "January 1, 1970 UTC".
+// The result is undefined if the Unix time cannot be represented by an int64.
+// Which includes calling TimeUnixMilli on a zero Time is undefined.
+//
+// This utility is useful for service API's such as CloudWatch Logs which require
+// their unix time values to be in milliseconds.
+//
+// See Go stdlib https://golang.org/pkg/time/#Time.UnixNano for more information.
+func TimeUnixMilli(t time.Time) int64 {
+ return t.UnixNano() / int64(time.Millisecond/time.Nanosecond)
+}
+
+// TimeSlice converts a slice of time.Time values into a slice of
+// time.Time pointers
+func TimeSlice(src []time.Time) []*time.Time {
+ dst := make([]*time.Time, len(src))
+ for i := 0; i < len(src); i++ {
+ dst[i] = &(src[i])
+ }
+ return dst
+}
+
+// TimeValueSlice converts a slice of time.Time pointers into a slice of
+// time.Time values
+func TimeValueSlice(src []*time.Time) []time.Time {
+ dst := make([]time.Time, len(src))
+ for i := 0; i < len(src); i++ {
+ if src[i] != nil {
+ dst[i] = *(src[i])
+ }
+ }
+ return dst
+}
+
+// TimeMap converts a string map of time.Time values into a string
+// map of time.Time pointers
+func TimeMap(src map[string]time.Time) map[string]*time.Time {
+ dst := make(map[string]*time.Time)
+ for k, val := range src {
+ v := val
+ dst[k] = &v
+ }
+ return dst
+}
+
+// TimeValueMap converts a string map of time.Time pointers into a string
+// map of time.Time values
+func TimeValueMap(src map[string]*time.Time) map[string]time.Time {
+ dst := make(map[string]time.Time)
+ for k, val := range src {
+ if val != nil {
+ dst[k] = *val
+ }
+ }
+ return dst
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go
new file mode 100644
index 0000000..8e12f82
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go
@@ -0,0 +1,182 @@
+package corehandlers
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "regexp"
+ "runtime"
+ "strconv"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/credentials"
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+// Interface for matching types which also have a Len method.
+type lener interface {
+ Len() int
+}
+
+// BuildContentLengthHandler builds the content length of a request based on the body,
+// or will use the HTTPRequest.Header's "Content-Length" if defined. If unable
+// to determine request body length and no "Content-Length" was specified it will panic.
+//
+// The Content-Length will only be aded to the request if the length of the body
+// is greater than 0. If the body is empty or the current `Content-Length`
+// header is <= 0, the header will also be stripped.
+var BuildContentLengthHandler = request.NamedHandler{Name: "core.BuildContentLengthHandler", Fn: func(r *request.Request) {
+ var length int64
+
+ if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" {
+ length, _ = strconv.ParseInt(slength, 10, 64)
+ } else {
+ switch body := r.Body.(type) {
+ case nil:
+ length = 0
+ case lener:
+ length = int64(body.Len())
+ case io.Seeker:
+ r.BodyStart, _ = body.Seek(0, 1)
+ end, _ := body.Seek(0, 2)
+ body.Seek(r.BodyStart, 0) // make sure to seek back to original location
+ length = end - r.BodyStart
+ default:
+ panic("Cannot get length of body, must provide `ContentLength`")
+ }
+ }
+
+ if length > 0 {
+ r.HTTPRequest.ContentLength = length
+ r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length))
+ } else {
+ r.HTTPRequest.ContentLength = 0
+ r.HTTPRequest.Header.Del("Content-Length")
+ }
+}}
+
+// SDKVersionUserAgentHandler is a request handler for adding the SDK Version to the user agent.
+var SDKVersionUserAgentHandler = request.NamedHandler{
+ Name: "core.SDKVersionUserAgentHandler",
+ Fn: request.MakeAddToUserAgentHandler(aws.SDKName, aws.SDKVersion,
+ runtime.Version(), runtime.GOOS, runtime.GOARCH),
+}
+
+var reStatusCode = regexp.MustCompile(`^(\d{3})`)
+
+// ValidateReqSigHandler is a request handler to ensure that the request's
+// signature doesn't expire before it is sent. This can happen when a request
+// is built and signed signficantly before it is sent. Or signficant delays
+// occur whne retrying requests that would cause the signature to expire.
+var ValidateReqSigHandler = request.NamedHandler{
+ Name: "core.ValidateReqSigHandler",
+ Fn: func(r *request.Request) {
+ // Unsigned requests are not signed
+ if r.Config.Credentials == credentials.AnonymousCredentials {
+ return
+ }
+
+ signedTime := r.Time
+ if !r.LastSignedAt.IsZero() {
+ signedTime = r.LastSignedAt
+ }
+
+ // 10 minutes to allow for some clock skew/delays in transmission.
+ // Would be improved with aws/aws-sdk-go#423
+ if signedTime.Add(10 * time.Minute).After(time.Now()) {
+ return
+ }
+
+ fmt.Println("request expired, resigning")
+ r.Sign()
+ },
+}
+
+// SendHandler is a request handler to send service request using HTTP client.
+var SendHandler = request.NamedHandler{Name: "core.SendHandler", Fn: func(r *request.Request) {
+ var err error
+ r.HTTPResponse, err = r.Config.HTTPClient.Do(r.HTTPRequest)
+ if err != nil {
+ // Prevent leaking if an HTTPResponse was returned. Clean up
+ // the body.
+ if r.HTTPResponse != nil {
+ r.HTTPResponse.Body.Close()
+ }
+ // Capture the case where url.Error is returned for error processing
+ // response. e.g. 301 without location header comes back as string
+ // error and r.HTTPResponse is nil. Other url redirect errors will
+ // comeback in a similar method.
+ if e, ok := err.(*url.Error); ok && e.Err != nil {
+ if s := reStatusCode.FindStringSubmatch(e.Err.Error()); s != nil {
+ code, _ := strconv.ParseInt(s[1], 10, 64)
+ r.HTTPResponse = &http.Response{
+ StatusCode: int(code),
+ Status: http.StatusText(int(code)),
+ Body: ioutil.NopCloser(bytes.NewReader([]byte{})),
+ }
+ return
+ }
+ }
+ if r.HTTPResponse == nil {
+ // Add a dummy request response object to ensure the HTTPResponse
+ // value is consistent.
+ r.HTTPResponse = &http.Response{
+ StatusCode: int(0),
+ Status: http.StatusText(int(0)),
+ Body: ioutil.NopCloser(bytes.NewReader([]byte{})),
+ }
+ }
+ // Catch all other request errors.
+ r.Error = awserr.New("RequestError", "send request failed", err)
+ r.Retryable = aws.Bool(true) // network errors are retryable
+ }
+}}
+
+// ValidateResponseHandler is a request handler to validate service response.
+var ValidateResponseHandler = request.NamedHandler{Name: "core.ValidateResponseHandler", Fn: func(r *request.Request) {
+ if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 {
+ // this may be replaced by an UnmarshalError handler
+ r.Error = awserr.New("UnknownError", "unknown error", nil)
+ }
+}}
+
+// AfterRetryHandler performs final checks to determine if the request should
+// be retried and how long to delay.
+var AfterRetryHandler = request.NamedHandler{Name: "core.AfterRetryHandler", Fn: func(r *request.Request) {
+ // If one of the other handlers already set the retry state
+ // we don't want to override it based on the service's state
+ if r.Retryable == nil {
+ r.Retryable = aws.Bool(r.ShouldRetry(r))
+ }
+
+ if r.WillRetry() {
+ r.RetryDelay = r.RetryRules(r)
+ r.Config.SleepDelay(r.RetryDelay)
+
+ // when the expired token exception occurs the credentials
+ // need to be expired locally so that the next request to
+ // get credentials will trigger a credentials refresh.
+ if r.IsErrorExpired() {
+ r.Config.Credentials.Expire()
+ }
+
+ r.RetryCount++
+ r.Error = nil
+ }
+}}
+
+// ValidateEndpointHandler is a request handler to validate a request had the
+// appropriate Region and Endpoint set. Will set r.Error if the endpoint or
+// region is not valid.
+var ValidateEndpointHandler = request.NamedHandler{Name: "core.ValidateEndpointHandler", Fn: func(r *request.Request) {
+ if r.ClientInfo.SigningRegion == "" && aws.StringValue(r.Config.Region) == "" {
+ r.Error = aws.ErrMissingRegion
+ } else if r.ClientInfo.Endpoint == "" {
+ r.Error = aws.ErrMissingEndpoint
+ }
+}}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go
new file mode 100644
index 0000000..7d50b15
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go
@@ -0,0 +1,17 @@
+package corehandlers
+
+import "github.com/aws/aws-sdk-go/aws/request"
+
+// ValidateParametersHandler is a request handler to validate the input parameters.
+// Validating parameters only has meaning if done prior to the request being sent.
+var ValidateParametersHandler = request.NamedHandler{Name: "core.ValidateParametersHandler", Fn: func(r *request.Request) {
+ if !r.ParamsFilled() {
+ return
+ }
+
+ if v, ok := r.Params.(request.Validator); ok {
+ if err := v.Validate(); err != nil {
+ r.Error = err
+ }
+ }
+}}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go
new file mode 100644
index 0000000..6efc77b
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go
@@ -0,0 +1,100 @@
+package credentials
+
+import (
+ "github.com/aws/aws-sdk-go/aws/awserr"
+)
+
+var (
+ // ErrNoValidProvidersFoundInChain Is returned when there are no valid
+ // providers in the ChainProvider.
+ //
+ // This has been deprecated. For verbose error messaging set
+ // aws.Config.CredentialsChainVerboseErrors to true
+ //
+ // @readonly
+ ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders",
+ `no valid providers in chain. Deprecated.
+ For verbose messaging see aws.Config.CredentialsChainVerboseErrors`,
+ nil)
+)
+
+// A ChainProvider will search for a provider which returns credentials
+// and cache that provider until Retrieve is called again.
+//
+// The ChainProvider provides a way of chaining multiple providers together
+// which will pick the first available using priority order of the Providers
+// in the list.
+//
+// If none of the Providers retrieve valid credentials Value, ChainProvider's
+// Retrieve() will return the error ErrNoValidProvidersFoundInChain.
+//
+// If a Provider is found which returns valid credentials Value ChainProvider
+// will cache that Provider for all calls to IsExpired(), until Retrieve is
+// called again.
+//
+// Example of ChainProvider to be used with an EnvProvider and EC2RoleProvider.
+// In this example EnvProvider will first check if any credentials are available
+// via the environment variables. If there are none ChainProvider will check
+// the next Provider in the list, EC2RoleProvider in this case. If EC2RoleProvider
+// does not return any credentials ChainProvider will return the error
+// ErrNoValidProvidersFoundInChain
+//
+// creds := NewChainCredentials(
+// []Provider{
+// &EnvProvider{},
+// &EC2RoleProvider{
+// Client: ec2metadata.New(sess),
+// },
+// })
+//
+// // Usage of ChainCredentials with aws.Config
+// svc := ec2.New(&aws.Config{Credentials: creds})
+//
+type ChainProvider struct {
+ Providers []Provider
+ curr Provider
+ VerboseErrors bool
+}
+
+// NewChainCredentials returns a pointer to a new Credentials object
+// wrapping a chain of providers.
+func NewChainCredentials(providers []Provider) *Credentials {
+ return NewCredentials(&ChainProvider{
+ Providers: append([]Provider{}, providers...),
+ })
+}
+
+// Retrieve returns the credentials value or error if no provider returned
+// without error.
+//
+// If a provider is found it will be cached and any calls to IsExpired()
+// will return the expired state of the cached provider.
+func (c *ChainProvider) Retrieve() (Value, error) {
+ var errs []error
+ for _, p := range c.Providers {
+ creds, err := p.Retrieve()
+ if err == nil {
+ c.curr = p
+ return creds, nil
+ }
+ errs = append(errs, err)
+ }
+ c.curr = nil
+
+ var err error
+ err = ErrNoValidProvidersFoundInChain
+ if c.VerboseErrors {
+ err = awserr.NewBatchError("NoCredentialProviders", "no valid providers in chain", errs)
+ }
+ return Value{}, err
+}
+
+// IsExpired will returned the expired state of the currently cached provider
+// if there is one. If there is no current provider, true will be returned.
+func (c *ChainProvider) IsExpired() bool {
+ if c.curr != nil {
+ return c.curr.IsExpired()
+ }
+
+ return true
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go
new file mode 100644
index 0000000..7b8ebf5
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go
@@ -0,0 +1,223 @@
+// Package credentials provides credential retrieval and management
+//
+// The Credentials is the primary method of getting access to and managing
+// credentials Values. Using dependency injection retrieval of the credential
+// values is handled by a object which satisfies the Provider interface.
+//
+// By default the Credentials.Get() will cache the successful result of a
+// Provider's Retrieve() until Provider.IsExpired() returns true. At which
+// point Credentials will call Provider's Retrieve() to get new credential Value.
+//
+// The Provider is responsible for determining when credentials Value have expired.
+// It is also important to note that Credentials will always call Retrieve the
+// first time Credentials.Get() is called.
+//
+// Example of using the environment variable credentials.
+//
+// creds := NewEnvCredentials()
+//
+// // Retrieve the credentials value
+// credValue, err := creds.Get()
+// if err != nil {
+// // handle error
+// }
+//
+// Example of forcing credentials to expire and be refreshed on the next Get().
+// This may be helpful to proactively expire credentials and refresh them sooner
+// than they would naturally expire on their own.
+//
+// creds := NewCredentials(&EC2RoleProvider{})
+// creds.Expire()
+// credsValue, err := creds.Get()
+// // New credentials will be retrieved instead of from cache.
+//
+//
+// Custom Provider
+//
+// Each Provider built into this package also provides a helper method to generate
+// a Credentials pointer setup with the provider. To use a custom Provider just
+// create a type which satisfies the Provider interface and pass it to the
+// NewCredentials method.
+//
+// type MyProvider struct{}
+// func (m *MyProvider) Retrieve() (Value, error) {...}
+// func (m *MyProvider) IsExpired() bool {...}
+//
+// creds := NewCredentials(&MyProvider{})
+// credValue, err := creds.Get()
+//
+package credentials
+
+import (
+ "sync"
+ "time"
+)
+
+// AnonymousCredentials is an empty Credential object that can be used as
+// dummy placeholder credentials for requests that do not need signed.
+//
+// This Credentials can be used to configure a service to not sign requests
+// when making service API calls. For example, when accessing public
+// s3 buckets.
+//
+// svc := s3.New(&aws.Config{Credentials: AnonymousCredentials})
+// // Access public S3 buckets.
+//
+// @readonly
+var AnonymousCredentials = NewStaticCredentials("", "", "")
+
+// A Value is the AWS credentials value for individual credential fields.
+type Value struct {
+ // AWS Access key ID
+ AccessKeyID string
+
+ // AWS Secret Access Key
+ SecretAccessKey string
+
+ // AWS Session Token
+ SessionToken string
+
+ // Provider used to get credentials
+ ProviderName string
+}
+
+// A Provider is the interface for any component which will provide credentials
+// Value. A provider is required to manage its own Expired state, and what to
+// be expired means.
+//
+// The Provider should not need to implement its own mutexes, because
+// that will be managed by Credentials.
+type Provider interface {
+ // Refresh returns nil if it successfully retrieved the value.
+ // Error is returned if the value were not obtainable, or empty.
+ Retrieve() (Value, error)
+
+ // IsExpired returns if the credentials are no longer valid, and need
+ // to be retrieved.
+ IsExpired() bool
+}
+
+// A Expiry provides shared expiration logic to be used by credentials
+// providers to implement expiry functionality.
+//
+// The best method to use this struct is as an anonymous field within the
+// provider's struct.
+//
+// Example:
+// type EC2RoleProvider struct {
+// Expiry
+// ...
+// }
+type Expiry struct {
+ // The date/time when to expire on
+ expiration time.Time
+
+ // If set will be used by IsExpired to determine the current time.
+ // Defaults to time.Now if CurrentTime is not set. Available for testing
+ // to be able to mock out the current time.
+ CurrentTime func() time.Time
+}
+
+// SetExpiration sets the expiration IsExpired will check when called.
+//
+// If window is greater than 0 the expiration time will be reduced by the
+// window value.
+//
+// Using a window is helpful to trigger credentials to expire sooner than
+// the expiration time given to ensure no requests are made with expired
+// tokens.
+func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) {
+ e.expiration = expiration
+ if window > 0 {
+ e.expiration = e.expiration.Add(-window)
+ }
+}
+
+// IsExpired returns if the credentials are expired.
+func (e *Expiry) IsExpired() bool {
+ if e.CurrentTime == nil {
+ e.CurrentTime = time.Now
+ }
+ return e.expiration.Before(e.CurrentTime())
+}
+
+// A Credentials provides synchronous safe retrieval of AWS credentials Value.
+// Credentials will cache the credentials value until they expire. Once the value
+// expires the next Get will attempt to retrieve valid credentials.
+//
+// Credentials is safe to use across multiple goroutines and will manage the
+// synchronous state so the Providers do not need to implement their own
+// synchronization.
+//
+// The first Credentials.Get() will always call Provider.Retrieve() to get the
+// first instance of the credentials Value. All calls to Get() after that
+// will return the cached credentials Value until IsExpired() returns true.
+type Credentials struct {
+ creds Value
+ forceRefresh bool
+ m sync.Mutex
+
+ provider Provider
+}
+
+// NewCredentials returns a pointer to a new Credentials with the provider set.
+func NewCredentials(provider Provider) *Credentials {
+ return &Credentials{
+ provider: provider,
+ forceRefresh: true,
+ }
+}
+
+// Get returns the credentials value, or error if the credentials Value failed
+// to be retrieved.
+//
+// Will return the cached credentials Value if it has not expired. If the
+// credentials Value has expired the Provider's Retrieve() will be called
+// to refresh the credentials.
+//
+// If Credentials.Expire() was called the credentials Value will be force
+// expired, and the next call to Get() will cause them to be refreshed.
+func (c *Credentials) Get() (Value, error) {
+ c.m.Lock()
+ defer c.m.Unlock()
+
+ if c.isExpired() {
+ creds, err := c.provider.Retrieve()
+ if err != nil {
+ return Value{}, err
+ }
+ c.creds = creds
+ c.forceRefresh = false
+ }
+
+ return c.creds, nil
+}
+
+// Expire expires the credentials and forces them to be retrieved on the
+// next call to Get().
+//
+// This will override the Provider's expired state, and force Credentials
+// to call the Provider's Retrieve().
+func (c *Credentials) Expire() {
+ c.m.Lock()
+ defer c.m.Unlock()
+
+ c.forceRefresh = true
+}
+
+// IsExpired returns if the credentials are no longer valid, and need
+// to be retrieved.
+//
+// If the Credentials were forced to be expired with Expire() this will
+// reflect that override.
+func (c *Credentials) IsExpired() bool {
+ c.m.Lock()
+ defer c.m.Unlock()
+
+ return c.isExpired()
+}
+
+// isExpired helper method wrapping the definition of expired credentials.
+func (c *Credentials) isExpired() bool {
+ return c.forceRefresh || c.provider.IsExpired()
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go
new file mode 100644
index 0000000..aa9d689
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go
@@ -0,0 +1,178 @@
+package ec2rolecreds
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "path"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/client"
+ "github.com/aws/aws-sdk-go/aws/credentials"
+ "github.com/aws/aws-sdk-go/aws/ec2metadata"
+)
+
+// ProviderName provides a name of EC2Role provider
+const ProviderName = "EC2RoleProvider"
+
+// A EC2RoleProvider retrieves credentials from the EC2 service, and keeps track if
+// those credentials are expired.
+//
+// Example how to configure the EC2RoleProvider with custom http Client, Endpoint
+// or ExpiryWindow
+//
+// p := &ec2rolecreds.EC2RoleProvider{
+// // Pass in a custom timeout to be used when requesting
+// // IAM EC2 Role credentials.
+// Client: ec2metadata.New(sess, aws.Config{
+// HTTPClient: &http.Client{Timeout: 10 * time.Second},
+// }),
+//
+// // Do not use early expiry of credentials. If a non zero value is
+// // specified the credentials will be expired early
+// ExpiryWindow: 0,
+// }
+type EC2RoleProvider struct {
+ credentials.Expiry
+
+ // Required EC2Metadata client to use when connecting to EC2 metadata service.
+ Client *ec2metadata.EC2Metadata
+
+ // ExpiryWindow will allow the credentials to trigger refreshing prior to
+ // the credentials actually expiring. This is beneficial so race conditions
+ // with expiring credentials do not cause request to fail unexpectedly
+ // due to ExpiredTokenException exceptions.
+ //
+ // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true
+ // 10 seconds before the credentials are actually expired.
+ //
+ // If ExpiryWindow is 0 or less it will be ignored.
+ ExpiryWindow time.Duration
+}
+
+// NewCredentials returns a pointer to a new Credentials object wrapping
+// the EC2RoleProvider. Takes a ConfigProvider to create a EC2Metadata client.
+// The ConfigProvider is satisfied by the session.Session type.
+func NewCredentials(c client.ConfigProvider, options ...func(*EC2RoleProvider)) *credentials.Credentials {
+ p := &EC2RoleProvider{
+ Client: ec2metadata.New(c),
+ }
+
+ for _, option := range options {
+ option(p)
+ }
+
+ return credentials.NewCredentials(p)
+}
+
+// NewCredentialsWithClient returns a pointer to a new Credentials object wrapping
+// the EC2RoleProvider. Takes a EC2Metadata client to use when connecting to EC2
+// metadata service.
+func NewCredentialsWithClient(client *ec2metadata.EC2Metadata, options ...func(*EC2RoleProvider)) *credentials.Credentials {
+ p := &EC2RoleProvider{
+ Client: client,
+ }
+
+ for _, option := range options {
+ option(p)
+ }
+
+ return credentials.NewCredentials(p)
+}
+
+// Retrieve retrieves credentials from the EC2 service.
+// Error will be returned if the request fails, or unable to extract
+// the desired credentials.
+func (m *EC2RoleProvider) Retrieve() (credentials.Value, error) {
+ credsList, err := requestCredList(m.Client)
+ if err != nil {
+ return credentials.Value{ProviderName: ProviderName}, err
+ }
+
+ if len(credsList) == 0 {
+ return credentials.Value{ProviderName: ProviderName}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil)
+ }
+ credsName := credsList[0]
+
+ roleCreds, err := requestCred(m.Client, credsName)
+ if err != nil {
+ return credentials.Value{ProviderName: ProviderName}, err
+ }
+
+ m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow)
+
+ return credentials.Value{
+ AccessKeyID: roleCreds.AccessKeyID,
+ SecretAccessKey: roleCreds.SecretAccessKey,
+ SessionToken: roleCreds.Token,
+ ProviderName: ProviderName,
+ }, nil
+}
+
+// A ec2RoleCredRespBody provides the shape for unmarshalling credential
+// request responses.
+type ec2RoleCredRespBody struct {
+ // Success State
+ Expiration time.Time
+ AccessKeyID string
+ SecretAccessKey string
+ Token string
+
+ // Error state
+ Code string
+ Message string
+}
+
+const iamSecurityCredsPath = "/iam/security-credentials"
+
+// requestCredList requests a list of credentials from the EC2 service.
+// If there are no credentials, or there is an error making or receiving the request
+func requestCredList(client *ec2metadata.EC2Metadata) ([]string, error) {
+ resp, err := client.GetMetadata(iamSecurityCredsPath)
+ if err != nil {
+ return nil, awserr.New("EC2RoleRequestError", "no EC2 instance role found", err)
+ }
+
+ credsList := []string{}
+ s := bufio.NewScanner(strings.NewReader(resp))
+ for s.Scan() {
+ credsList = append(credsList, s.Text())
+ }
+
+ if err := s.Err(); err != nil {
+ return nil, awserr.New("SerializationError", "failed to read EC2 instance role from metadata service", err)
+ }
+
+ return credsList, nil
+}
+
+// requestCred requests the credentials for a specific credentials from the EC2 service.
+//
+// If the credentials cannot be found, or there is an error reading the response
+// and error will be returned.
+func requestCred(client *ec2metadata.EC2Metadata, credsName string) (ec2RoleCredRespBody, error) {
+ resp, err := client.GetMetadata(path.Join(iamSecurityCredsPath, credsName))
+ if err != nil {
+ return ec2RoleCredRespBody{},
+ awserr.New("EC2RoleRequestError",
+ fmt.Sprintf("failed to get %s EC2 instance role credentials", credsName),
+ err)
+ }
+
+ respCreds := ec2RoleCredRespBody{}
+ if err := json.NewDecoder(strings.NewReader(resp)).Decode(&respCreds); err != nil {
+ return ec2RoleCredRespBody{},
+ awserr.New("SerializationError",
+ fmt.Sprintf("failed to decode %s EC2 instance role credentials", credsName),
+ err)
+ }
+
+ if respCreds.Code != "Success" {
+ // If an error code was returned something failed requesting the role.
+ return ec2RoleCredRespBody{}, awserr.New(respCreds.Code, respCreds.Message, nil)
+ }
+
+ return respCreds, nil
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go
new file mode 100644
index 0000000..a4cec5c
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go
@@ -0,0 +1,191 @@
+// Package endpointcreds provides support for retrieving credentials from an
+// arbitrary HTTP endpoint.
+//
+// The credentials endpoint Provider can receive both static and refreshable
+// credentials that will expire. Credentials are static when an "Expiration"
+// value is not provided in the endpoint's response.
+//
+// Static credentials will never expire once they have been retrieved. The format
+// of the static credentials response:
+// {
+// "AccessKeyId" : "MUA...",
+// "SecretAccessKey" : "/7PC5om....",
+// }
+//
+// Refreshable credentials will expire within the "ExpiryWindow" of the Expiration
+// value in the response. The format of the refreshable credentials response:
+// {
+// "AccessKeyId" : "MUA...",
+// "SecretAccessKey" : "/7PC5om....",
+// "Token" : "AQoDY....=",
+// "Expiration" : "2016-02-25T06:03:31Z"
+// }
+//
+// Errors should be returned in the following format and only returned with 400
+// or 500 HTTP status codes.
+// {
+// "code": "ErrorCode",
+// "message": "Helpful error message."
+// }
+package endpointcreds
+
+import (
+ "encoding/json"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/client"
+ "github.com/aws/aws-sdk-go/aws/client/metadata"
+ "github.com/aws/aws-sdk-go/aws/credentials"
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+// ProviderName is the name of the credentials provider.
+const ProviderName = `CredentialsEndpointProvider`
+
+// Provider satisfies the credentials.Provider interface, and is a client to
+// retrieve credentials from an arbitrary endpoint.
+type Provider struct {
+ staticCreds bool
+ credentials.Expiry
+
+ // Requires a AWS Client to make HTTP requests to the endpoint with.
+ // the Endpoint the request will be made to is provided by the aws.Config's
+ // Endpoint value.
+ Client *client.Client
+
+ // ExpiryWindow will allow the credentials to trigger refreshing prior to
+ // the credentials actually expiring. This is beneficial so race conditions
+ // with expiring credentials do not cause request to fail unexpectedly
+ // due to ExpiredTokenException exceptions.
+ //
+ // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true
+ // 10 seconds before the credentials are actually expired.
+ //
+ // If ExpiryWindow is 0 or less it will be ignored.
+ ExpiryWindow time.Duration
+}
+
+// NewProviderClient returns a credentials Provider for retrieving AWS credentials
+// from arbitrary endpoint.
+func NewProviderClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) credentials.Provider {
+ p := &Provider{
+ Client: client.New(
+ cfg,
+ metadata.ClientInfo{
+ ServiceName: "CredentialsEndpoint",
+ Endpoint: endpoint,
+ },
+ handlers,
+ ),
+ }
+
+ p.Client.Handlers.Unmarshal.PushBack(unmarshalHandler)
+ p.Client.Handlers.UnmarshalError.PushBack(unmarshalError)
+ p.Client.Handlers.Validate.Clear()
+ p.Client.Handlers.Validate.PushBack(validateEndpointHandler)
+
+ for _, option := range options {
+ option(p)
+ }
+
+ return p
+}
+
+// NewCredentialsClient returns a Credentials wrapper for retrieving credentials
+// from an arbitrary endpoint concurrently. The client will request the
+func NewCredentialsClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) *credentials.Credentials {
+ return credentials.NewCredentials(NewProviderClient(cfg, handlers, endpoint, options...))
+}
+
+// IsExpired returns true if the credentials retrieved are expired, or not yet
+// retrieved.
+func (p *Provider) IsExpired() bool {
+ if p.staticCreds {
+ return false
+ }
+ return p.Expiry.IsExpired()
+}
+
+// Retrieve will attempt to request the credentials from the endpoint the Provider
+// was configured for. And error will be returned if the retrieval fails.
+func (p *Provider) Retrieve() (credentials.Value, error) {
+ resp, err := p.getCredentials()
+ if err != nil {
+ return credentials.Value{ProviderName: ProviderName},
+ awserr.New("CredentialsEndpointError", "failed to load credentials", err)
+ }
+
+ if resp.Expiration != nil {
+ p.SetExpiration(*resp.Expiration, p.ExpiryWindow)
+ } else {
+ p.staticCreds = true
+ }
+
+ return credentials.Value{
+ AccessKeyID: resp.AccessKeyID,
+ SecretAccessKey: resp.SecretAccessKey,
+ SessionToken: resp.Token,
+ ProviderName: ProviderName,
+ }, nil
+}
+
+type getCredentialsOutput struct {
+ Expiration *time.Time
+ AccessKeyID string
+ SecretAccessKey string
+ Token string
+}
+
+type errorOutput struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+}
+
+func (p *Provider) getCredentials() (*getCredentialsOutput, error) {
+ op := &request.Operation{
+ Name: "GetCredentials",
+ HTTPMethod: "GET",
+ }
+
+ out := &getCredentialsOutput{}
+ req := p.Client.NewRequest(op, nil, out)
+ req.HTTPRequest.Header.Set("Accept", "application/json")
+
+ return out, req.Send()
+}
+
+func validateEndpointHandler(r *request.Request) {
+ if len(r.ClientInfo.Endpoint) == 0 {
+ r.Error = aws.ErrMissingEndpoint
+ }
+}
+
+func unmarshalHandler(r *request.Request) {
+ defer r.HTTPResponse.Body.Close()
+
+ out := r.Data.(*getCredentialsOutput)
+ if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&out); err != nil {
+ r.Error = awserr.New("SerializationError",
+ "failed to decode endpoint credentials",
+ err,
+ )
+ }
+}
+
+func unmarshalError(r *request.Request) {
+ defer r.HTTPResponse.Body.Close()
+
+ var errOut errorOutput
+ if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&errOut); err != nil {
+ r.Error = awserr.New("SerializationError",
+ "failed to decode endpoint credentials",
+ err,
+ )
+ }
+
+ // Response body format is not consistent between metadata endpoints.
+ // Grab the error message as a string and include that as the source error
+ r.Error = awserr.New(errOut.Code, errOut.Message, nil)
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go
new file mode 100644
index 0000000..96655bc
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go
@@ -0,0 +1,77 @@
+package credentials
+
+import (
+ "os"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+)
+
+// EnvProviderName provides a name of Env provider
+const EnvProviderName = "EnvProvider"
+
+var (
+ // ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be
+ // found in the process's environment.
+ //
+ // @readonly
+ ErrAccessKeyIDNotFound = awserr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil)
+
+ // ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key
+ // can't be found in the process's environment.
+ //
+ // @readonly
+ ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil)
+)
+
+// A EnvProvider retrieves credentials from the environment variables of the
+// running process. Environment credentials never expire.
+//
+// Environment variables used:
+//
+// * Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY
+// * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY
+type EnvProvider struct {
+ retrieved bool
+}
+
+// NewEnvCredentials returns a pointer to a new Credentials object
+// wrapping the environment variable provider.
+func NewEnvCredentials() *Credentials {
+ return NewCredentials(&EnvProvider{})
+}
+
+// Retrieve retrieves the keys from the environment.
+func (e *EnvProvider) Retrieve() (Value, error) {
+ e.retrieved = false
+
+ id := os.Getenv("AWS_ACCESS_KEY_ID")
+ if id == "" {
+ id = os.Getenv("AWS_ACCESS_KEY")
+ }
+
+ secret := os.Getenv("AWS_SECRET_ACCESS_KEY")
+ if secret == "" {
+ secret = os.Getenv("AWS_SECRET_KEY")
+ }
+
+ if id == "" {
+ return Value{ProviderName: EnvProviderName}, ErrAccessKeyIDNotFound
+ }
+
+ if secret == "" {
+ return Value{ProviderName: EnvProviderName}, ErrSecretAccessKeyNotFound
+ }
+
+ e.retrieved = true
+ return Value{
+ AccessKeyID: id,
+ SecretAccessKey: secret,
+ SessionToken: os.Getenv("AWS_SESSION_TOKEN"),
+ ProviderName: EnvProviderName,
+ }, nil
+}
+
+// IsExpired returns if the credentials have been retrieved.
+func (e *EnvProvider) IsExpired() bool {
+ return !e.retrieved
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go
new file mode 100644
index 0000000..7fb7cbf
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go
@@ -0,0 +1,151 @@
+package credentials
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/go-ini/ini"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+)
+
+// SharedCredsProviderName provides a name of SharedCreds provider
+const SharedCredsProviderName = "SharedCredentialsProvider"
+
+var (
+ // ErrSharedCredentialsHomeNotFound is emitted when the user directory cannot be found.
+ //
+ // @readonly
+ ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil)
+)
+
+// A SharedCredentialsProvider retrieves credentials from the current user's home
+// directory, and keeps track if those credentials are expired.
+//
+// Profile ini file example: $HOME/.aws/credentials
+type SharedCredentialsProvider struct {
+ // Path to the shared credentials file.
+ //
+ // If empty will look for "AWS_SHARED_CREDENTIALS_FILE" env variable. If the
+ // env value is empty will default to current user's home directory.
+ // Linux/OSX: "$HOME/.aws/credentials"
+ // Windows: "%USERPROFILE%\.aws\credentials"
+ Filename string
+
+ // AWS Profile to extract credentials from the shared credentials file. If empty
+ // will default to environment variable "AWS_PROFILE" or "default" if
+ // environment variable is also not set.
+ Profile string
+
+ // retrieved states if the credentials have been successfully retrieved.
+ retrieved bool
+}
+
+// NewSharedCredentials returns a pointer to a new Credentials object
+// wrapping the Profile file provider.
+func NewSharedCredentials(filename, profile string) *Credentials {
+ return NewCredentials(&SharedCredentialsProvider{
+ Filename: filename,
+ Profile: profile,
+ })
+}
+
+// Retrieve reads and extracts the shared credentials from the current
+// users home directory.
+func (p *SharedCredentialsProvider) Retrieve() (Value, error) {
+ p.retrieved = false
+
+ filename, err := p.filename()
+ if err != nil {
+ return Value{ProviderName: SharedCredsProviderName}, err
+ }
+
+ creds, err := loadProfile(filename, p.profile())
+ if err != nil {
+ return Value{ProviderName: SharedCredsProviderName}, err
+ }
+
+ p.retrieved = true
+ return creds, nil
+}
+
+// IsExpired returns if the shared credentials have expired.
+func (p *SharedCredentialsProvider) IsExpired() bool {
+ return !p.retrieved
+}
+
+// loadProfiles loads from the file pointed to by shared credentials filename for profile.
+// The credentials retrieved from the profile will be returned or error. Error will be
+// returned if it fails to read from the file, or the data is invalid.
+func loadProfile(filename, profile string) (Value, error) {
+ config, err := ini.Load(filename)
+ if err != nil {
+ return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err)
+ }
+ iniProfile, err := config.GetSection(profile)
+ if err != nil {
+ return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to get profile", err)
+ }
+
+ id, err := iniProfile.GetKey("aws_access_key_id")
+ if err != nil {
+ return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsAccessKey",
+ fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename),
+ err)
+ }
+
+ secret, err := iniProfile.GetKey("aws_secret_access_key")
+ if err != nil {
+ return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsSecret",
+ fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename),
+ nil)
+ }
+
+ // Default to empty string if not found
+ token := iniProfile.Key("aws_session_token")
+
+ return Value{
+ AccessKeyID: id.String(),
+ SecretAccessKey: secret.String(),
+ SessionToken: token.String(),
+ ProviderName: SharedCredsProviderName,
+ }, nil
+}
+
+// filename returns the filename to use to read AWS shared credentials.
+//
+// Will return an error if the user's home directory path cannot be found.
+func (p *SharedCredentialsProvider) filename() (string, error) {
+ if p.Filename == "" {
+ if p.Filename = os.Getenv("AWS_SHARED_CREDENTIALS_FILE"); p.Filename != "" {
+ return p.Filename, nil
+ }
+
+ homeDir := os.Getenv("HOME") // *nix
+ if homeDir == "" { // Windows
+ homeDir = os.Getenv("USERPROFILE")
+ }
+ if homeDir == "" {
+ return "", ErrSharedCredentialsHomeNotFound
+ }
+
+ p.Filename = filepath.Join(homeDir, ".aws", "credentials")
+ }
+
+ return p.Filename, nil
+}
+
+// profile returns the AWS shared credentials profile. If empty will read
+// environment variable "AWS_PROFILE". If that is not set profile will
+// return "default".
+func (p *SharedCredentialsProvider) profile() string {
+ if p.Profile == "" {
+ p.Profile = os.Getenv("AWS_PROFILE")
+ }
+ if p.Profile == "" {
+ p.Profile = "default"
+ }
+
+ return p.Profile
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go
new file mode 100644
index 0000000..4f5dab3
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go
@@ -0,0 +1,57 @@
+package credentials
+
+import (
+ "github.com/aws/aws-sdk-go/aws/awserr"
+)
+
+// StaticProviderName provides a name of Static provider
+const StaticProviderName = "StaticProvider"
+
+var (
+ // ErrStaticCredentialsEmpty is emitted when static credentials are empty.
+ //
+ // @readonly
+ ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil)
+)
+
+// A StaticProvider is a set of credentials which are set programmatically,
+// and will never expire.
+type StaticProvider struct {
+ Value
+}
+
+// NewStaticCredentials returns a pointer to a new Credentials object
+// wrapping a static credentials value provider.
+func NewStaticCredentials(id, secret, token string) *Credentials {
+ return NewCredentials(&StaticProvider{Value: Value{
+ AccessKeyID: id,
+ SecretAccessKey: secret,
+ SessionToken: token,
+ }})
+}
+
+// NewStaticCredentialsFromCreds returns a pointer to a new Credentials object
+// wrapping the static credentials value provide. Same as NewStaticCredentials
+// but takes the creds Value instead of individual fields
+func NewStaticCredentialsFromCreds(creds Value) *Credentials {
+ return NewCredentials(&StaticProvider{Value: creds})
+}
+
+// Retrieve returns the credentials or error if the credentials are invalid.
+func (s *StaticProvider) Retrieve() (Value, error) {
+ if s.AccessKeyID == "" || s.SecretAccessKey == "" {
+ return Value{ProviderName: StaticProviderName}, ErrStaticCredentialsEmpty
+ }
+
+ if len(s.Value.ProviderName) == 0 {
+ s.Value.ProviderName = StaticProviderName
+ }
+ return s.Value, nil
+}
+
+// IsExpired returns if the credentials are expired.
+//
+// For StaticProvider, the credentials never expired.
+func (s *StaticProvider) IsExpired() bool {
+ return false
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go
new file mode 100644
index 0000000..30c847a
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go
@@ -0,0 +1,161 @@
+// Package stscreds are credential Providers to retrieve STS AWS credentials.
+//
+// STS provides multiple ways to retrieve credentials which can be used when making
+// future AWS service API operation calls.
+package stscreds
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/client"
+ "github.com/aws/aws-sdk-go/aws/credentials"
+ "github.com/aws/aws-sdk-go/service/sts"
+)
+
+// ProviderName provides a name of AssumeRole provider
+const ProviderName = "AssumeRoleProvider"
+
+// AssumeRoler represents the minimal subset of the STS client API used by this provider.
+type AssumeRoler interface {
+ AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error)
+}
+
+// DefaultDuration is the default amount of time in minutes that the credentials
+// will be valid for.
+var DefaultDuration = time.Duration(15) * time.Minute
+
+// AssumeRoleProvider retrieves temporary credentials from the STS service, and
+// keeps track of their expiration time. This provider must be used explicitly,
+// as it is not included in the credentials chain.
+type AssumeRoleProvider struct {
+ credentials.Expiry
+
+ // STS client to make assume role request with.
+ Client AssumeRoler
+
+ // Role to be assumed.
+ RoleARN string
+
+ // Session name, if you wish to reuse the credentials elsewhere.
+ RoleSessionName string
+
+ // Expiry duration of the STS credentials. Defaults to 15 minutes if not set.
+ Duration time.Duration
+
+ // Optional ExternalID to pass along, defaults to nil if not set.
+ ExternalID *string
+
+ // The policy plain text must be 2048 bytes or shorter. However, an internal
+ // conversion compresses it into a packed binary format with a separate limit.
+ // The PackedPolicySize response element indicates by percentage how close to
+ // the upper size limit the policy is, with 100% equaling the maximum allowed
+ // size.
+ Policy *string
+
+ // The identification number of the MFA device that is associated with the user
+ // who is making the AssumeRole call. Specify this value if the trust policy
+ // of the role being assumed includes a condition that requires MFA authentication.
+ // The value is either the serial number for a hardware device (such as GAHT12345678)
+ // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user).
+ SerialNumber *string
+
+ // The value provided by the MFA device, if the trust policy of the role being
+ // assumed requires MFA (that is, if the policy includes a condition that tests
+ // for MFA). If the role being assumed requires MFA and if the TokenCode value
+ // is missing or expired, the AssumeRole call returns an "access denied" error.
+ TokenCode *string
+
+ // ExpiryWindow will allow the credentials to trigger refreshing prior to
+ // the credentials actually expiring. This is beneficial so race conditions
+ // with expiring credentials do not cause request to fail unexpectedly
+ // due to ExpiredTokenException exceptions.
+ //
+ // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true
+ // 10 seconds before the credentials are actually expired.
+ //
+ // If ExpiryWindow is 0 or less it will be ignored.
+ ExpiryWindow time.Duration
+}
+
+// NewCredentials returns a pointer to a new Credentials object wrapping the
+// AssumeRoleProvider. The credentials will expire every 15 minutes and the
+// role will be named after a nanosecond timestamp of this operation.
+//
+// Takes a Config provider to create the STS client. The ConfigProvider is
+// satisfied by the session.Session type.
+func NewCredentials(c client.ConfigProvider, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials {
+ p := &AssumeRoleProvider{
+ Client: sts.New(c),
+ RoleARN: roleARN,
+ Duration: DefaultDuration,
+ }
+
+ for _, option := range options {
+ option(p)
+ }
+
+ return credentials.NewCredentials(p)
+}
+
+// NewCredentialsWithClient returns a pointer to a new Credentials object wrapping the
+// AssumeRoleProvider. The credentials will expire every 15 minutes and the
+// role will be named after a nanosecond timestamp of this operation.
+//
+// Takes an AssumeRoler which can be satisfiede by the STS client.
+func NewCredentialsWithClient(svc AssumeRoler, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials {
+ p := &AssumeRoleProvider{
+ Client: svc,
+ RoleARN: roleARN,
+ Duration: DefaultDuration,
+ }
+
+ for _, option := range options {
+ option(p)
+ }
+
+ return credentials.NewCredentials(p)
+}
+
+// Retrieve generates a new set of temporary credentials using STS.
+func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) {
+
+ // Apply defaults where parameters are not set.
+ if p.RoleSessionName == "" {
+ // Try to work out a role name that will hopefully end up unique.
+ p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano())
+ }
+ if p.Duration == 0 {
+ // Expire as often as AWS permits.
+ p.Duration = DefaultDuration
+ }
+ input := &sts.AssumeRoleInput{
+ DurationSeconds: aws.Int64(int64(p.Duration / time.Second)),
+ RoleArn: aws.String(p.RoleARN),
+ RoleSessionName: aws.String(p.RoleSessionName),
+ ExternalId: p.ExternalID,
+ }
+ if p.Policy != nil {
+ input.Policy = p.Policy
+ }
+ if p.SerialNumber != nil && p.TokenCode != nil {
+ input.SerialNumber = p.SerialNumber
+ input.TokenCode = p.TokenCode
+ }
+ roleOutput, err := p.Client.AssumeRole(input)
+
+ if err != nil {
+ return credentials.Value{ProviderName: ProviderName}, err
+ }
+
+ // We will proactively generate new credentials before they expire.
+ p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow)
+
+ return credentials.Value{
+ AccessKeyID: *roleOutput.Credentials.AccessKeyId,
+ SecretAccessKey: *roleOutput.Credentials.SecretAccessKey,
+ SessionToken: *roleOutput.Credentials.SessionToken,
+ ProviderName: ProviderName,
+ }, nil
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go
new file mode 100644
index 0000000..8dbbf67
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go
@@ -0,0 +1,130 @@
+// Package defaults is a collection of helpers to retrieve the SDK's default
+// configuration and handlers.
+//
+// Generally this package shouldn't be used directly, but session.Session
+// instead. This package is useful when you need to reset the defaults
+// of a session or service client to the SDK defaults before setting
+// additional parameters.
+package defaults
+
+import (
+ "fmt"
+ "net/http"
+ "os"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/corehandlers"
+ "github.com/aws/aws-sdk-go/aws/credentials"
+ "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
+ "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds"
+ "github.com/aws/aws-sdk-go/aws/ec2metadata"
+ "github.com/aws/aws-sdk-go/aws/request"
+ "github.com/aws/aws-sdk-go/private/endpoints"
+)
+
+// A Defaults provides a collection of default values for SDK clients.
+type Defaults struct {
+ Config *aws.Config
+ Handlers request.Handlers
+}
+
+// Get returns the SDK's default values with Config and handlers pre-configured.
+func Get() Defaults {
+ cfg := Config()
+ handlers := Handlers()
+ cfg.Credentials = CredChain(cfg, handlers)
+
+ return Defaults{
+ Config: cfg,
+ Handlers: handlers,
+ }
+}
+
+// Config returns the default configuration without credentials.
+// To retrieve a config with credentials also included use
+// `defaults.Get().Config` instead.
+//
+// Generally you shouldn't need to use this method directly, but
+// is available if you need to reset the configuration of an
+// existing service client or session.
+func Config() *aws.Config {
+ return aws.NewConfig().
+ WithCredentials(credentials.AnonymousCredentials).
+ WithRegion(os.Getenv("AWS_REGION")).
+ WithHTTPClient(http.DefaultClient).
+ WithMaxRetries(aws.UseServiceDefaultRetries).
+ WithLogger(aws.NewDefaultLogger()).
+ WithLogLevel(aws.LogOff).
+ WithSleepDelay(time.Sleep)
+}
+
+// Handlers returns the default request handlers.
+//
+// Generally you shouldn't need to use this method directly, but
+// is available if you need to reset the request handlers of an
+// existing service client or session.
+func Handlers() request.Handlers {
+ var handlers request.Handlers
+
+ handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler)
+ handlers.Validate.AfterEachFn = request.HandlerListStopOnError
+ handlers.Build.PushBackNamed(corehandlers.SDKVersionUserAgentHandler)
+ handlers.Build.AfterEachFn = request.HandlerListStopOnError
+ handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler)
+ handlers.Send.PushBackNamed(corehandlers.ValidateReqSigHandler)
+ handlers.Send.PushBackNamed(corehandlers.SendHandler)
+ handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler)
+ handlers.ValidateResponse.PushBackNamed(corehandlers.ValidateResponseHandler)
+
+ return handlers
+}
+
+// CredChain returns the default credential chain.
+//
+// Generally you shouldn't need to use this method directly, but
+// is available if you need to reset the credentials of an
+// existing service client or session's Config.
+func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials {
+ return credentials.NewCredentials(&credentials.ChainProvider{
+ VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors),
+ Providers: []credentials.Provider{
+ &credentials.EnvProvider{},
+ &credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
+ RemoteCredProvider(*cfg, handlers),
+ },
+ })
+}
+
+// RemoteCredProvider returns a credenitials provider for the default remote
+// endpoints such as EC2 or ECS Roles.
+func RemoteCredProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider {
+ ecsCredURI := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
+
+ if len(ecsCredURI) > 0 {
+ return ecsCredProvider(cfg, handlers, ecsCredURI)
+ }
+
+ return ec2RoleProvider(cfg, handlers)
+}
+
+func ecsCredProvider(cfg aws.Config, handlers request.Handlers, uri string) credentials.Provider {
+ const host = `169.254.170.2`
+
+ return endpointcreds.NewProviderClient(cfg, handlers,
+ fmt.Sprintf("http://%s%s", host, uri),
+ func(p *endpointcreds.Provider) {
+ p.ExpiryWindow = 5 * time.Minute
+ },
+ )
+}
+
+func ec2RoleProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider {
+ endpoint, signingRegion := endpoints.EndpointForRegion(ec2metadata.ServiceName,
+ aws.StringValue(cfg.Region), true, false)
+
+ return &ec2rolecreds.EC2RoleProvider{
+ Client: ec2metadata.NewClient(cfg, handlers, endpoint, signingRegion),
+ ExpiryWindow: 5 * time.Minute,
+ }
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go
new file mode 100644
index 0000000..e5755d1
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go
@@ -0,0 +1,162 @@
+package ec2metadata
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "path"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+// GetMetadata uses the path provided to request information from the EC2
+// instance metdata service. The content will be returned as a string, or
+// error if the request failed.
+func (c *EC2Metadata) GetMetadata(p string) (string, error) {
+ op := &request.Operation{
+ Name: "GetMetadata",
+ HTTPMethod: "GET",
+ HTTPPath: path.Join("/", "meta-data", p),
+ }
+
+ output := &metadataOutput{}
+ req := c.NewRequest(op, nil, output)
+
+ return output.Content, req.Send()
+}
+
+// GetUserData returns the userdata that was configured for the service. If
+// there is no user-data setup for the EC2 instance a "NotFoundError" error
+// code will be returned.
+func (c *EC2Metadata) GetUserData() (string, error) {
+ op := &request.Operation{
+ Name: "GetUserData",
+ HTTPMethod: "GET",
+ HTTPPath: path.Join("/", "user-data"),
+ }
+
+ output := &metadataOutput{}
+ req := c.NewRequest(op, nil, output)
+ req.Handlers.UnmarshalError.PushBack(func(r *request.Request) {
+ if r.HTTPResponse.StatusCode == http.StatusNotFound {
+ r.Error = awserr.New("NotFoundError", "user-data not found", r.Error)
+ }
+ })
+
+ return output.Content, req.Send()
+}
+
+// GetDynamicData uses the path provided to request information from the EC2
+// instance metadata service for dynamic data. The content will be returned
+// as a string, or error if the request failed.
+func (c *EC2Metadata) GetDynamicData(p string) (string, error) {
+ op := &request.Operation{
+ Name: "GetDynamicData",
+ HTTPMethod: "GET",
+ HTTPPath: path.Join("/", "dynamic", p),
+ }
+
+ output := &metadataOutput{}
+ req := c.NewRequest(op, nil, output)
+
+ return output.Content, req.Send()
+}
+
+// GetInstanceIdentityDocument retrieves an identity document describing an
+// instance. Error is returned if the request fails or is unable to parse
+// the response.
+func (c *EC2Metadata) GetInstanceIdentityDocument() (EC2InstanceIdentityDocument, error) {
+ resp, err := c.GetDynamicData("instance-identity/document")
+ if err != nil {
+ return EC2InstanceIdentityDocument{},
+ awserr.New("EC2MetadataRequestError",
+ "failed to get EC2 instance identity document", err)
+ }
+
+ doc := EC2InstanceIdentityDocument{}
+ if err := json.NewDecoder(strings.NewReader(resp)).Decode(&doc); err != nil {
+ return EC2InstanceIdentityDocument{},
+ awserr.New("SerializationError",
+ "failed to decode EC2 instance identity document", err)
+ }
+
+ return doc, nil
+}
+
+// IAMInfo retrieves IAM info from the metadata API
+func (c *EC2Metadata) IAMInfo() (EC2IAMInfo, error) {
+ resp, err := c.GetMetadata("iam/info")
+ if err != nil {
+ return EC2IAMInfo{},
+ awserr.New("EC2MetadataRequestError",
+ "failed to get EC2 IAM info", err)
+ }
+
+ info := EC2IAMInfo{}
+ if err := json.NewDecoder(strings.NewReader(resp)).Decode(&info); err != nil {
+ return EC2IAMInfo{},
+ awserr.New("SerializationError",
+ "failed to decode EC2 IAM info", err)
+ }
+
+ if info.Code != "Success" {
+ errMsg := fmt.Sprintf("failed to get EC2 IAM Info (%s)", info.Code)
+ return EC2IAMInfo{},
+ awserr.New("EC2MetadataError", errMsg, nil)
+ }
+
+ return info, nil
+}
+
+// Region returns the region the instance is running in.
+func (c *EC2Metadata) Region() (string, error) {
+ resp, err := c.GetMetadata("placement/availability-zone")
+ if err != nil {
+ return "", err
+ }
+
+ // returns region without the suffix. Eg: us-west-2a becomes us-west-2
+ return resp[:len(resp)-1], nil
+}
+
+// Available returns if the application has access to the EC2 Metadata service.
+// Can be used to determine if application is running within an EC2 Instance and
+// the metadata service is available.
+func (c *EC2Metadata) Available() bool {
+ if _, err := c.GetMetadata("instance-id"); err != nil {
+ return false
+ }
+
+ return true
+}
+
+// An EC2IAMInfo provides the shape for unmarshalling
+// an IAM info from the metadata API
+type EC2IAMInfo struct {
+ Code string
+ LastUpdated time.Time
+ InstanceProfileArn string
+ InstanceProfileID string
+}
+
+// An EC2InstanceIdentityDocument provides the shape for unmarshalling
+// an instance identity document
+type EC2InstanceIdentityDocument struct {
+ DevpayProductCodes []string `json:"devpayProductCodes"`
+ AvailabilityZone string `json:"availabilityZone"`
+ PrivateIP string `json:"privateIp"`
+ Version string `json:"version"`
+ Region string `json:"region"`
+ InstanceID string `json:"instanceId"`
+ BillingProducts []string `json:"billingProducts"`
+ InstanceType string `json:"instanceType"`
+ AccountID string `json:"accountId"`
+ PendingTime time.Time `json:"pendingTime"`
+ ImageID string `json:"imageId"`
+ KernelID string `json:"kernelId"`
+ RamdiskID string `json:"ramdiskId"`
+ Architecture string `json:"architecture"`
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go
new file mode 100644
index 0000000..5b4379d
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go
@@ -0,0 +1,124 @@
+// Package ec2metadata provides the client for making API calls to the
+// EC2 Metadata service.
+package ec2metadata
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/client"
+ "github.com/aws/aws-sdk-go/aws/client/metadata"
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+// ServiceName is the name of the service.
+const ServiceName = "ec2metadata"
+
+// A EC2Metadata is an EC2 Metadata service Client.
+type EC2Metadata struct {
+ *client.Client
+}
+
+// New creates a new instance of the EC2Metadata client with a session.
+// This client is safe to use across multiple goroutines.
+//
+//
+// Example:
+// // Create a EC2Metadata client from just a session.
+// svc := ec2metadata.New(mySession)
+//
+// // Create a EC2Metadata client with additional configuration
+// svc := ec2metadata.New(mySession, aws.NewConfig().WithLogLevel(aws.LogDebugHTTPBody))
+func New(p client.ConfigProvider, cfgs ...*aws.Config) *EC2Metadata {
+ c := p.ClientConfig(ServiceName, cfgs...)
+ return NewClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
+}
+
+// NewClient returns a new EC2Metadata client. Should be used to create
+// a client when not using a session. Generally using just New with a session
+// is preferred.
+//
+// If an unmodified HTTP client is provided from the stdlib default, or no client
+// the EC2RoleProvider's EC2Metadata HTTP client's timeout will be shortened.
+// To disable this set Config.EC2MetadataDisableTimeoutOverride to false. Enabled by default.
+func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string, opts ...func(*client.Client)) *EC2Metadata {
+ if !aws.BoolValue(cfg.EC2MetadataDisableTimeoutOverride) && httpClientZero(cfg.HTTPClient) {
+ // If the http client is unmodified and this feature is not disabled
+ // set custom timeouts for EC2Metadata requests.
+ cfg.HTTPClient = &http.Client{
+ // use a shorter timeout than default because the metadata
+ // service is local if it is running, and to fail faster
+ // if not running on an ec2 instance.
+ Timeout: 5 * time.Second,
+ }
+ }
+
+ svc := &EC2Metadata{
+ Client: client.New(
+ cfg,
+ metadata.ClientInfo{
+ ServiceName: ServiceName,
+ Endpoint: endpoint,
+ APIVersion: "latest",
+ },
+ handlers,
+ ),
+ }
+
+ svc.Handlers.Unmarshal.PushBack(unmarshalHandler)
+ svc.Handlers.UnmarshalError.PushBack(unmarshalError)
+ svc.Handlers.Validate.Clear()
+ svc.Handlers.Validate.PushBack(validateEndpointHandler)
+
+ // Add additional options to the service config
+ for _, option := range opts {
+ option(svc.Client)
+ }
+
+ return svc
+}
+
+func httpClientZero(c *http.Client) bool {
+ return c == nil || (c.Transport == nil && c.CheckRedirect == nil && c.Jar == nil && c.Timeout == 0)
+}
+
+type metadataOutput struct {
+ Content string
+}
+
+func unmarshalHandler(r *request.Request) {
+ defer r.HTTPResponse.Body.Close()
+ b := &bytes.Buffer{}
+ if _, err := io.Copy(b, r.HTTPResponse.Body); err != nil {
+ r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata respose", err)
+ return
+ }
+
+ if data, ok := r.Data.(*metadataOutput); ok {
+ data.Content = b.String()
+ }
+}
+
+func unmarshalError(r *request.Request) {
+ defer r.HTTPResponse.Body.Close()
+ b := &bytes.Buffer{}
+ if _, err := io.Copy(b, r.HTTPResponse.Body); err != nil {
+ r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata error respose", err)
+ return
+ }
+
+ // Response body format is not consistent between metadata endpoints.
+ // Grab the error message as a string and include that as the source error
+ r.Error = awserr.New("EC2MetadataError", "failed to make EC2Metadata request", errors.New(b.String()))
+}
+
+func validateEndpointHandler(r *request.Request) {
+ if r.ClientInfo.Endpoint == "" {
+ r.Error = aws.ErrMissingEndpoint
+ }
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/errors.go b/vendor/github.com/aws/aws-sdk-go/aws/errors.go
new file mode 100644
index 0000000..5766361
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/errors.go
@@ -0,0 +1,17 @@
+package aws
+
+import "github.com/aws/aws-sdk-go/aws/awserr"
+
+var (
+ // ErrMissingRegion is an error that is returned if region configuration is
+ // not found.
+ //
+ // @readonly
+ ErrMissingRegion = awserr.New("MissingRegion", "could not find region configuration", nil)
+
+ // ErrMissingEndpoint is an error that is returned if an endpoint cannot be
+ // resolved for a service.
+ //
+ // @readonly
+ ErrMissingEndpoint = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil)
+)
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/logger.go b/vendor/github.com/aws/aws-sdk-go/aws/logger.go
new file mode 100644
index 0000000..db87188
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/logger.go
@@ -0,0 +1,112 @@
+package aws
+
+import (
+ "log"
+ "os"
+)
+
+// A LogLevelType defines the level logging should be performed at. Used to instruct
+// the SDK which statements should be logged.
+type LogLevelType uint
+
+// LogLevel returns the pointer to a LogLevel. Should be used to workaround
+// not being able to take the address of a non-composite literal.
+func LogLevel(l LogLevelType) *LogLevelType {
+ return &l
+}
+
+// Value returns the LogLevel value or the default value LogOff if the LogLevel
+// is nil. Safe to use on nil value LogLevelTypes.
+func (l *LogLevelType) Value() LogLevelType {
+ if l != nil {
+ return *l
+ }
+ return LogOff
+}
+
+// Matches returns true if the v LogLevel is enabled by this LogLevel. Should be
+// used with logging sub levels. Is safe to use on nil value LogLevelTypes. If
+// LogLevel is nill, will default to LogOff comparison.
+func (l *LogLevelType) Matches(v LogLevelType) bool {
+ c := l.Value()
+ return c&v == v
+}
+
+// AtLeast returns true if this LogLevel is at least high enough to satisfies v.
+// Is safe to use on nil value LogLevelTypes. If LogLevel is nill, will default
+// to LogOff comparison.
+func (l *LogLevelType) AtLeast(v LogLevelType) bool {
+ c := l.Value()
+ return c >= v
+}
+
+const (
+ // LogOff states that no logging should be performed by the SDK. This is the
+ // default state of the SDK, and should be use to disable all logging.
+ LogOff LogLevelType = iota * 0x1000
+
+ // LogDebug state that debug output should be logged by the SDK. This should
+ // be used to inspect request made and responses received.
+ LogDebug
+)
+
+// Debug Logging Sub Levels
+const (
+ // LogDebugWithSigning states that the SDK should log request signing and
+ // presigning events. This should be used to log the signing details of
+ // requests for debugging. Will also enable LogDebug.
+ LogDebugWithSigning LogLevelType = LogDebug | (1 << iota)
+
+ // LogDebugWithHTTPBody states the SDK should log HTTP request and response
+ // HTTP bodys in addition to the headers and path. This should be used to
+ // see the body content of requests and responses made while using the SDK
+ // Will also enable LogDebug.
+ LogDebugWithHTTPBody
+
+ // LogDebugWithRequestRetries states the SDK should log when service requests will
+ // be retried. This should be used to log when you want to log when service
+ // requests are being retried. Will also enable LogDebug.
+ LogDebugWithRequestRetries
+
+ // LogDebugWithRequestErrors states the SDK should log when service requests fail
+ // to build, send, validate, or unmarshal.
+ LogDebugWithRequestErrors
+)
+
+// A Logger is a minimalistic interface for the SDK to log messages to. Should
+// be used to provide custom logging writers for the SDK to use.
+type Logger interface {
+ Log(...interface{})
+}
+
+// A LoggerFunc is a convenience type to convert a function taking a variadic
+// list of arguments and wrap it so the Logger interface can be used.
+//
+// Example:
+// s3.New(sess, &aws.Config{Logger: aws.LoggerFunc(func(args ...interface{}) {
+// fmt.Fprintln(os.Stdout, args...)
+// })})
+type LoggerFunc func(...interface{})
+
+// Log calls the wrapped function with the arguments provided
+func (f LoggerFunc) Log(args ...interface{}) {
+ f(args...)
+}
+
+// NewDefaultLogger returns a Logger which will write log messages to stdout, and
+// use same formatting runes as the stdlib log.Logger
+func NewDefaultLogger() Logger {
+ return &defaultLogger{
+ logger: log.New(os.Stdout, "", log.LstdFlags),
+ }
+}
+
+// A defaultLogger provides a minimalistic logger satisfying the Logger interface.
+type defaultLogger struct {
+ logger *log.Logger
+}
+
+// Log logs the parameters to the stdlib logger. See log.Println.
+func (l defaultLogger) Log(args ...interface{}) {
+ l.logger.Println(args...)
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go
new file mode 100644
index 0000000..5279c19
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go
@@ -0,0 +1,187 @@
+package request
+
+import (
+ "fmt"
+ "strings"
+)
+
+// A Handlers provides a collection of request handlers for various
+// stages of handling requests.
+type Handlers struct {
+ Validate HandlerList
+ Build HandlerList
+ Sign HandlerList
+ Send HandlerList
+ ValidateResponse HandlerList
+ Unmarshal HandlerList
+ UnmarshalMeta HandlerList
+ UnmarshalError HandlerList
+ Retry HandlerList
+ AfterRetry HandlerList
+}
+
+// Copy returns of this handler's lists.
+func (h *Handlers) Copy() Handlers {
+ return Handlers{
+ Validate: h.Validate.copy(),
+ Build: h.Build.copy(),
+ Sign: h.Sign.copy(),
+ Send: h.Send.copy(),
+ ValidateResponse: h.ValidateResponse.copy(),
+ Unmarshal: h.Unmarshal.copy(),
+ UnmarshalError: h.UnmarshalError.copy(),
+ UnmarshalMeta: h.UnmarshalMeta.copy(),
+ Retry: h.Retry.copy(),
+ AfterRetry: h.AfterRetry.copy(),
+ }
+}
+
+// Clear removes callback functions for all handlers
+func (h *Handlers) Clear() {
+ h.Validate.Clear()
+ h.Build.Clear()
+ h.Send.Clear()
+ h.Sign.Clear()
+ h.Unmarshal.Clear()
+ h.UnmarshalMeta.Clear()
+ h.UnmarshalError.Clear()
+ h.ValidateResponse.Clear()
+ h.Retry.Clear()
+ h.AfterRetry.Clear()
+}
+
+// A HandlerListRunItem represents an entry in the HandlerList which
+// is being run.
+type HandlerListRunItem struct {
+ Index int
+ Handler NamedHandler
+ Request *Request
+}
+
+// A HandlerList manages zero or more handlers in a list.
+type HandlerList struct {
+ list []NamedHandler
+
+ // Called after each request handler in the list is called. If set
+ // and the func returns true the HandlerList will continue to iterate
+ // over the request handlers. If false is returned the HandlerList
+ // will stop iterating.
+ //
+ // Should be used if extra logic to be performed between each handler
+ // in the list. This can be used to terminate a list's iteration
+ // based on a condition such as error like, HandlerListStopOnError.
+ // Or for logging like HandlerListLogItem.
+ AfterEachFn func(item HandlerListRunItem) bool
+}
+
+// A NamedHandler is a struct that contains a name and function callback.
+type NamedHandler struct {
+ Name string
+ Fn func(*Request)
+}
+
+// copy creates a copy of the handler list.
+func (l *HandlerList) copy() HandlerList {
+ n := HandlerList{
+ AfterEachFn: l.AfterEachFn,
+ }
+ n.list = append([]NamedHandler{}, l.list...)
+ return n
+}
+
+// Clear clears the handler list.
+func (l *HandlerList) Clear() {
+ l.list = []NamedHandler{}
+}
+
+// Len returns the number of handlers in the list.
+func (l *HandlerList) Len() int {
+ return len(l.list)
+}
+
+// PushBack pushes handler f to the back of the handler list.
+func (l *HandlerList) PushBack(f func(*Request)) {
+ l.list = append(l.list, NamedHandler{"__anonymous", f})
+}
+
+// PushFront pushes handler f to the front of the handler list.
+func (l *HandlerList) PushFront(f func(*Request)) {
+ l.list = append([]NamedHandler{{"__anonymous", f}}, l.list...)
+}
+
+// PushBackNamed pushes named handler f to the back of the handler list.
+func (l *HandlerList) PushBackNamed(n NamedHandler) {
+ l.list = append(l.list, n)
+}
+
+// PushFrontNamed pushes named handler f to the front of the handler list.
+func (l *HandlerList) PushFrontNamed(n NamedHandler) {
+ l.list = append([]NamedHandler{n}, l.list...)
+}
+
+// Remove removes a NamedHandler n
+func (l *HandlerList) Remove(n NamedHandler) {
+ newlist := []NamedHandler{}
+ for _, m := range l.list {
+ if m.Name != n.Name {
+ newlist = append(newlist, m)
+ }
+ }
+ l.list = newlist
+}
+
+// Run executes all handlers in the list with a given request object.
+func (l *HandlerList) Run(r *Request) {
+ for i, h := range l.list {
+ h.Fn(r)
+ item := HandlerListRunItem{
+ Index: i, Handler: h, Request: r,
+ }
+ if l.AfterEachFn != nil && !l.AfterEachFn(item) {
+ return
+ }
+ }
+}
+
+// HandlerListLogItem logs the request handler and the state of the
+// request's Error value. Always returns true to continue iterating
+// request handlers in a HandlerList.
+func HandlerListLogItem(item HandlerListRunItem) bool {
+ if item.Request.Config.Logger == nil {
+ return true
+ }
+ item.Request.Config.Logger.Log("DEBUG: RequestHandler",
+ item.Index, item.Handler.Name, item.Request.Error)
+
+ return true
+}
+
+// HandlerListStopOnError returns false to stop the HandlerList iterating
+// over request handlers if Request.Error is not nil. True otherwise
+// to continue iterating.
+func HandlerListStopOnError(item HandlerListRunItem) bool {
+ return item.Request.Error == nil
+}
+
+// MakeAddToUserAgentHandler will add the name/version pair to the User-Agent request
+// header. If the extra parameters are provided they will be added as metadata to the
+// name/version pair resulting in the following format.
+// "name/version (extra0; extra1; ...)"
+// The user agent part will be concatenated with this current request's user agent string.
+func MakeAddToUserAgentHandler(name, version string, extra ...string) func(*Request) {
+ ua := fmt.Sprintf("%s/%s", name, version)
+ if len(extra) > 0 {
+ ua += fmt.Sprintf(" (%s)", strings.Join(extra, "; "))
+ }
+ return func(r *Request) {
+ AddToUserAgent(r, ua)
+ }
+}
+
+// MakeAddToUserAgentFreeFormHandler adds the input to the User-Agent request header.
+// The input string will be concatenated with the current request's user agent string.
+func MakeAddToUserAgentFreeFormHandler(s string) func(*Request) {
+ return func(r *Request) {
+ AddToUserAgent(r, s)
+ }
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go
new file mode 100644
index 0000000..79f7960
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go
@@ -0,0 +1,24 @@
+package request
+
+import (
+ "io"
+ "net/http"
+ "net/url"
+)
+
+func copyHTTPRequest(r *http.Request, body io.ReadCloser) *http.Request {
+ req := new(http.Request)
+ *req = *r
+ req.URL = &url.URL{}
+ *req.URL = *r.URL
+ req.Body = body
+
+ req.Header = http.Header{}
+ for k, v := range r.Header {
+ for _, vv := range v {
+ req.Header.Add(k, vv)
+ }
+ }
+
+ return req
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go b/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go
new file mode 100644
index 0000000..02f07f4
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go
@@ -0,0 +1,58 @@
+package request
+
+import (
+ "io"
+ "sync"
+)
+
+// offsetReader is a thread-safe io.ReadCloser to prevent racing
+// with retrying requests
+type offsetReader struct {
+ buf io.ReadSeeker
+ lock sync.Mutex
+ closed bool
+}
+
+func newOffsetReader(buf io.ReadSeeker, offset int64) *offsetReader {
+ reader := &offsetReader{}
+ buf.Seek(offset, 0)
+
+ reader.buf = buf
+ return reader
+}
+
+// Close will close the instance of the offset reader's access to
+// the underlying io.ReadSeeker.
+func (o *offsetReader) Close() error {
+ o.lock.Lock()
+ defer o.lock.Unlock()
+ o.closed = true
+ return nil
+}
+
+// Read is a thread-safe read of the underlying io.ReadSeeker
+func (o *offsetReader) Read(p []byte) (int, error) {
+ o.lock.Lock()
+ defer o.lock.Unlock()
+
+ if o.closed {
+ return 0, io.EOF
+ }
+
+ return o.buf.Read(p)
+}
+
+// Seek is a thread-safe seeking operation.
+func (o *offsetReader) Seek(offset int64, whence int) (int64, error) {
+ o.lock.Lock()
+ defer o.lock.Unlock()
+
+ return o.buf.Seek(offset, whence)
+}
+
+// CloseAndCopy will return a new offsetReader with a copy of the old buffer
+// and close the old buffer.
+func (o *offsetReader) CloseAndCopy(offset int64) *offsetReader {
+ o.Close()
+ return newOffsetReader(o.buf, offset)
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go
new file mode 100644
index 0000000..8ef9715
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go
@@ -0,0 +1,344 @@
+package request
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "reflect"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/client/metadata"
+)
+
+// A Request is the service request to be made.
+type Request struct {
+ Config aws.Config
+ ClientInfo metadata.ClientInfo
+ Handlers Handlers
+
+ Retryer
+ Time time.Time
+ ExpireTime time.Duration
+ Operation *Operation
+ HTTPRequest *http.Request
+ HTTPResponse *http.Response
+ Body io.ReadSeeker
+ BodyStart int64 // offset from beginning of Body that the request body starts
+ Params interface{}
+ Error error
+ Data interface{}
+ RequestID string
+ RetryCount int
+ Retryable *bool
+ RetryDelay time.Duration
+ NotHoist bool
+ SignedHeaderVals http.Header
+ LastSignedAt time.Time
+
+ built bool
+
+ // Need to persist an intermideant body betweend the input Body and HTTP
+ // request body because the HTTP Client's transport can maintain a reference
+ // to the HTTP request's body after the client has returned. This value is
+ // safe to use concurrently and rewraps the input Body for each HTTP request.
+ safeBody *offsetReader
+}
+
+// An Operation is the service API operation to be made.
+type Operation struct {
+ Name string
+ HTTPMethod string
+ HTTPPath string
+ *Paginator
+}
+
+// Paginator keeps track of pagination configuration for an API operation.
+type Paginator struct {
+ InputTokens []string
+ OutputTokens []string
+ LimitToken string
+ TruncationToken string
+}
+
+// New returns a new Request pointer for the service API
+// operation and parameters.
+//
+// Params is any value of input parameters to be the request payload.
+// Data is pointer value to an object which the request's response
+// payload will be deserialized to.
+func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers,
+ retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request {
+
+ method := operation.HTTPMethod
+ if method == "" {
+ method = "POST"
+ }
+
+ httpReq, _ := http.NewRequest(method, "", nil)
+
+ var err error
+ httpReq.URL, err = url.Parse(clientInfo.Endpoint + operation.HTTPPath)
+ if err != nil {
+ httpReq.URL = &url.URL{}
+ err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err)
+ }
+
+ r := &Request{
+ Config: cfg,
+ ClientInfo: clientInfo,
+ Handlers: handlers.Copy(),
+
+ Retryer: retryer,
+ Time: time.Now(),
+ ExpireTime: 0,
+ Operation: operation,
+ HTTPRequest: httpReq,
+ Body: nil,
+ Params: params,
+ Error: err,
+ Data: data,
+ }
+ r.SetBufferBody([]byte{})
+
+ return r
+}
+
+// WillRetry returns if the request's can be retried.
+func (r *Request) WillRetry() bool {
+ return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries()
+}
+
+// ParamsFilled returns if the request's parameters have been populated
+// and the parameters are valid. False is returned if no parameters are
+// provided or invalid.
+func (r *Request) ParamsFilled() bool {
+ return r.Params != nil && reflect.ValueOf(r.Params).Elem().IsValid()
+}
+
+// DataFilled returns true if the request's data for response deserialization
+// target has been set and is a valid. False is returned if data is not
+// set, or is invalid.
+func (r *Request) DataFilled() bool {
+ return r.Data != nil && reflect.ValueOf(r.Data).Elem().IsValid()
+}
+
+// SetBufferBody will set the request's body bytes that will be sent to
+// the service API.
+func (r *Request) SetBufferBody(buf []byte) {
+ r.SetReaderBody(bytes.NewReader(buf))
+}
+
+// SetStringBody sets the body of the request to be backed by a string.
+func (r *Request) SetStringBody(s string) {
+ r.SetReaderBody(strings.NewReader(s))
+}
+
+// SetReaderBody will set the request's body reader.
+func (r *Request) SetReaderBody(reader io.ReadSeeker) {
+ r.Body = reader
+ r.ResetBody()
+}
+
+// Presign returns the request's signed URL. Error will be returned
+// if the signing fails.
+func (r *Request) Presign(expireTime time.Duration) (string, error) {
+ r.ExpireTime = expireTime
+ r.NotHoist = false
+ r.Sign()
+ if r.Error != nil {
+ return "", r.Error
+ }
+ return r.HTTPRequest.URL.String(), nil
+}
+
+// PresignRequest behaves just like presign, but hoists all headers and signs them.
+// Also returns the signed hash back to the user
+func (r *Request) PresignRequest(expireTime time.Duration) (string, http.Header, error) {
+ r.ExpireTime = expireTime
+ r.NotHoist = true
+ r.Sign()
+ if r.Error != nil {
+ return "", nil, r.Error
+ }
+ return r.HTTPRequest.URL.String(), r.SignedHeaderVals, nil
+}
+
+func debugLogReqError(r *Request, stage string, retrying bool, err error) {
+ if !r.Config.LogLevel.Matches(aws.LogDebugWithRequestErrors) {
+ return
+ }
+
+ retryStr := "not retrying"
+ if retrying {
+ retryStr = "will retry"
+ }
+
+ r.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v",
+ stage, r.ClientInfo.ServiceName, r.Operation.Name, retryStr, err))
+}
+
+// Build will build the request's object so it can be signed and sent
+// to the service. Build will also validate all the request's parameters.
+// Anny additional build Handlers set on this request will be run
+// in the order they were set.
+//
+// The request will only be built once. Multiple calls to build will have
+// no effect.
+//
+// If any Validate or Build errors occur the build will stop and the error
+// which occurred will be returned.
+func (r *Request) Build() error {
+ if !r.built {
+ r.Handlers.Validate.Run(r)
+ if r.Error != nil {
+ debugLogReqError(r, "Validate Request", false, r.Error)
+ return r.Error
+ }
+ r.Handlers.Build.Run(r)
+ if r.Error != nil {
+ debugLogReqError(r, "Build Request", false, r.Error)
+ return r.Error
+ }
+ r.built = true
+ }
+
+ return r.Error
+}
+
+// Sign will sign the request returning error if errors are encountered.
+//
+// Send will build the request prior to signing. All Sign Handlers will
+// be executed in the order they were set.
+func (r *Request) Sign() error {
+ r.Build()
+ if r.Error != nil {
+ debugLogReqError(r, "Build Request", false, r.Error)
+ return r.Error
+ }
+
+ r.Handlers.Sign.Run(r)
+ return r.Error
+}
+
+// ResetBody rewinds the request body backto its starting position, and
+// set's the HTTP Request body reference. When the body is read prior
+// to being sent in the HTTP request it will need to be rewound.
+func (r *Request) ResetBody() {
+ if r.safeBody != nil {
+ r.safeBody.Close()
+ }
+
+ r.safeBody = newOffsetReader(r.Body, r.BodyStart)
+ r.HTTPRequest.Body = r.safeBody
+}
+
+// GetBody will return an io.ReadSeeker of the Request's underlying
+// input body with a concurrency safe wrapper.
+func (r *Request) GetBody() io.ReadSeeker {
+ return r.safeBody
+}
+
+// Send will send the request returning error if errors are encountered.
+//
+// Send will sign the request prior to sending. All Send Handlers will
+// be executed in the order they were set.
+//
+// Canceling a request is non-deterministic. If a request has been canceled,
+// then the transport will choose, randomly, one of the state channels during
+// reads or getting the connection.
+//
+// readLoop() and getConn(req *Request, cm connectMethod)
+// https://github.com/golang/go/blob/master/src/net/http/transport.go
+//
+// Send will not close the request.Request's body.
+func (r *Request) Send() error {
+ for {
+ if aws.BoolValue(r.Retryable) {
+ if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) {
+ r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d",
+ r.ClientInfo.ServiceName, r.Operation.Name, r.RetryCount))
+ }
+
+ // The previous http.Request will have a reference to the r.Body
+ // and the HTTP Client's Transport may still be reading from
+ // the request's body even though the Client's Do returned.
+ r.HTTPRequest = copyHTTPRequest(r.HTTPRequest, nil)
+ r.ResetBody()
+
+ // Closing response body to ensure that no response body is leaked
+ // between retry attempts.
+ if r.HTTPResponse != nil && r.HTTPResponse.Body != nil {
+ r.HTTPResponse.Body.Close()
+ }
+ }
+
+ r.Sign()
+ if r.Error != nil {
+ return r.Error
+ }
+
+ r.Retryable = nil
+
+ r.Handlers.Send.Run(r)
+ if r.Error != nil {
+ if strings.Contains(r.Error.Error(), "net/http: request canceled") {
+ return r.Error
+ }
+
+ err := r.Error
+ r.Handlers.Retry.Run(r)
+ r.Handlers.AfterRetry.Run(r)
+ if r.Error != nil {
+ debugLogReqError(r, "Send Request", false, r.Error)
+ return r.Error
+ }
+ debugLogReqError(r, "Send Request", true, err)
+ continue
+ }
+ r.Handlers.UnmarshalMeta.Run(r)
+ r.Handlers.ValidateResponse.Run(r)
+ if r.Error != nil {
+ err := r.Error
+ r.Handlers.UnmarshalError.Run(r)
+ r.Handlers.Retry.Run(r)
+ r.Handlers.AfterRetry.Run(r)
+ if r.Error != nil {
+ debugLogReqError(r, "Validate Response", false, r.Error)
+ return r.Error
+ }
+ debugLogReqError(r, "Validate Response", true, err)
+ continue
+ }
+
+ r.Handlers.Unmarshal.Run(r)
+ if r.Error != nil {
+ err := r.Error
+ r.Handlers.Retry.Run(r)
+ r.Handlers.AfterRetry.Run(r)
+ if r.Error != nil {
+ debugLogReqError(r, "Unmarshal Response", false, r.Error)
+ return r.Error
+ }
+ debugLogReqError(r, "Unmarshal Response", true, err)
+ continue
+ }
+
+ break
+ }
+
+ return nil
+}
+
+// AddToUserAgent adds the string to the end of the request's current user agent.
+func AddToUserAgent(r *Request, s string) {
+ curUA := r.HTTPRequest.Header.Get("User-Agent")
+ if len(curUA) > 0 {
+ s = curUA + " " + s
+ }
+ r.HTTPRequest.Header.Set("User-Agent", s)
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go
new file mode 100644
index 0000000..2939ec4
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go
@@ -0,0 +1,104 @@
+package request
+
+import (
+ "reflect"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/awsutil"
+)
+
+//type Paginater interface {
+// HasNextPage() bool
+// NextPage() *Request
+// EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error
+//}
+
+// HasNextPage returns true if this request has more pages of data available.
+func (r *Request) HasNextPage() bool {
+ return len(r.nextPageTokens()) > 0
+}
+
+// nextPageTokens returns the tokens to use when asking for the next page of
+// data.
+func (r *Request) nextPageTokens() []interface{} {
+ if r.Operation.Paginator == nil {
+ return nil
+ }
+
+ if r.Operation.TruncationToken != "" {
+ tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken)
+ if len(tr) == 0 {
+ return nil
+ }
+
+ switch v := tr[0].(type) {
+ case *bool:
+ if !aws.BoolValue(v) {
+ return nil
+ }
+ case bool:
+ if v == false {
+ return nil
+ }
+ }
+ }
+
+ tokens := []interface{}{}
+ tokenAdded := false
+ for _, outToken := range r.Operation.OutputTokens {
+ v, _ := awsutil.ValuesAtPath(r.Data, outToken)
+ if len(v) > 0 {
+ tokens = append(tokens, v[0])
+ tokenAdded = true
+ } else {
+ tokens = append(tokens, nil)
+ }
+ }
+ if !tokenAdded {
+ return nil
+ }
+
+ return tokens
+}
+
+// NextPage returns a new Request that can be executed to return the next
+// page of result data. Call .Send() on this request to execute it.
+func (r *Request) NextPage() *Request {
+ tokens := r.nextPageTokens()
+ if len(tokens) == 0 {
+ return nil
+ }
+
+ data := reflect.New(reflect.TypeOf(r.Data).Elem()).Interface()
+ nr := New(r.Config, r.ClientInfo, r.Handlers, r.Retryer, r.Operation, awsutil.CopyOf(r.Params), data)
+ for i, intok := range nr.Operation.InputTokens {
+ awsutil.SetValueAtPath(nr.Params, intok, tokens[i])
+ }
+ return nr
+}
+
+// EachPage iterates over each page of a paginated request object. The fn
+// parameter should be a function with the following sample signature:
+//
+// func(page *T, lastPage bool) bool {
+// return true // return false to stop iterating
+// }
+//
+// Where "T" is the structure type matching the output structure of the given
+// operation. For example, a request object generated by
+// DynamoDB.ListTablesRequest() would expect to see dynamodb.ListTablesOutput
+// as the structure "T". The lastPage value represents whether the page is
+// the last page of data or not. The return value of this function should
+// return true to keep iterating or false to stop.
+func (r *Request) EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error {
+ for page := r; page != nil; page = page.NextPage() {
+ if err := page.Send(); err != nil {
+ return err
+ }
+ if getNextPage := fn(page.Data, !page.HasNextPage()); !getNextPage {
+ return page.Error
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go
new file mode 100644
index 0000000..8cc8b01
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go
@@ -0,0 +1,101 @@
+package request
+
+import (
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/awserr"
+)
+
+// Retryer is an interface to control retry logic for a given service.
+// The default implementation used by most services is the service.DefaultRetryer
+// structure, which contains basic retry logic using exponential backoff.
+type Retryer interface {
+ RetryRules(*Request) time.Duration
+ ShouldRetry(*Request) bool
+ MaxRetries() int
+}
+
+// WithRetryer sets a config Retryer value to the given Config returning it
+// for chaining.
+func WithRetryer(cfg *aws.Config, retryer Retryer) *aws.Config {
+ cfg.Retryer = retryer
+ return cfg
+}
+
+// retryableCodes is a collection of service response codes which are retry-able
+// without any further action.
+var retryableCodes = map[string]struct{}{
+ "RequestError": {},
+ "RequestTimeout": {},
+}
+
+var throttleCodes = map[string]struct{}{
+ "ProvisionedThroughputExceededException": {},
+ "Throttling": {},
+ "ThrottlingException": {},
+ "RequestLimitExceeded": {},
+ "RequestThrottled": {},
+ "LimitExceededException": {}, // Deleting 10+ DynamoDb tables at once
+ "TooManyRequestsException": {}, // Lambda functions
+}
+
+// credsExpiredCodes is a collection of error codes which signify the credentials
+// need to be refreshed. Expired tokens require refreshing of credentials, and
+// resigning before the request can be retried.
+var credsExpiredCodes = map[string]struct{}{
+ "ExpiredToken": {},
+ "ExpiredTokenException": {},
+ "RequestExpired": {}, // EC2 Only
+}
+
+func isCodeThrottle(code string) bool {
+ _, ok := throttleCodes[code]
+ return ok
+}
+
+func isCodeRetryable(code string) bool {
+ if _, ok := retryableCodes[code]; ok {
+ return true
+ }
+
+ return isCodeExpiredCreds(code)
+}
+
+func isCodeExpiredCreds(code string) bool {
+ _, ok := credsExpiredCodes[code]
+ return ok
+}
+
+// IsErrorRetryable returns whether the error is retryable, based on its Code.
+// Returns false if the request has no Error set.
+func (r *Request) IsErrorRetryable() bool {
+ if r.Error != nil {
+ if err, ok := r.Error.(awserr.Error); ok {
+ return isCodeRetryable(err.Code())
+ }
+ }
+ return false
+}
+
+// IsErrorThrottle returns whether the error is to be throttled based on its code.
+// Returns false if the request has no Error set
+func (r *Request) IsErrorThrottle() bool {
+ if r.Error != nil {
+ if err, ok := r.Error.(awserr.Error); ok {
+ return isCodeThrottle(err.Code())
+ }
+ }
+ return false
+}
+
+// IsErrorExpired returns whether the error code is a credential expiry error.
+// Returns false if the request has no Error set.
+func (r *Request) IsErrorExpired() bool {
+ if r.Error != nil {
+ if err, ok := r.Error.(awserr.Error); ok {
+ return isCodeExpiredCreds(err.Code())
+ }
+ }
+ return false
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go b/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go
new file mode 100644
index 0000000..2520286
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go
@@ -0,0 +1,234 @@
+package request
+
+import (
+ "bytes"
+ "fmt"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+)
+
+const (
+ // InvalidParameterErrCode is the error code for invalid parameters errors
+ InvalidParameterErrCode = "InvalidParameter"
+ // ParamRequiredErrCode is the error code for required parameter errors
+ ParamRequiredErrCode = "ParamRequiredError"
+ // ParamMinValueErrCode is the error code for fields with too low of a
+ // number value.
+ ParamMinValueErrCode = "ParamMinValueError"
+ // ParamMinLenErrCode is the error code for fields without enough elements.
+ ParamMinLenErrCode = "ParamMinLenError"
+)
+
+// Validator provides a way for types to perform validation logic on their
+// input values that external code can use to determine if a type's values
+// are valid.
+type Validator interface {
+ Validate() error
+}
+
+// An ErrInvalidParams provides wrapping of invalid parameter errors found when
+// validating API operation input parameters.
+type ErrInvalidParams struct {
+ // Context is the base context of the invalid parameter group.
+ Context string
+ errs []ErrInvalidParam
+}
+
+// Add adds a new invalid parameter error to the collection of invalid
+// parameters. The context of the invalid parameter will be updated to reflect
+// this collection.
+func (e *ErrInvalidParams) Add(err ErrInvalidParam) {
+ err.SetContext(e.Context)
+ e.errs = append(e.errs, err)
+}
+
+// AddNested adds the invalid parameter errors from another ErrInvalidParams
+// value into this collection. The nested errors will have their nested context
+// updated and base context to reflect the merging.
+//
+// Use for nested validations errors.
+func (e *ErrInvalidParams) AddNested(nestedCtx string, nested ErrInvalidParams) {
+ for _, err := range nested.errs {
+ err.SetContext(e.Context)
+ err.AddNestedContext(nestedCtx)
+ e.errs = append(e.errs, err)
+ }
+}
+
+// Len returns the number of invalid parameter errors
+func (e ErrInvalidParams) Len() int {
+ return len(e.errs)
+}
+
+// Code returns the code of the error
+func (e ErrInvalidParams) Code() string {
+ return InvalidParameterErrCode
+}
+
+// Message returns the message of the error
+func (e ErrInvalidParams) Message() string {
+ return fmt.Sprintf("%d validation error(s) found.", len(e.errs))
+}
+
+// Error returns the string formatted form of the invalid parameters.
+func (e ErrInvalidParams) Error() string {
+ w := &bytes.Buffer{}
+ fmt.Fprintf(w, "%s: %s\n", e.Code(), e.Message())
+
+ for _, err := range e.errs {
+ fmt.Fprintf(w, "- %s\n", err.Message())
+ }
+
+ return w.String()
+}
+
+// OrigErr returns the invalid parameters as a awserr.BatchedErrors value
+func (e ErrInvalidParams) OrigErr() error {
+ return awserr.NewBatchError(
+ InvalidParameterErrCode, e.Message(), e.OrigErrs())
+}
+
+// OrigErrs returns a slice of the invalid parameters
+func (e ErrInvalidParams) OrigErrs() []error {
+ errs := make([]error, len(e.errs))
+ for i := 0; i < len(errs); i++ {
+ errs[i] = e.errs[i]
+ }
+
+ return errs
+}
+
+// An ErrInvalidParam represents an invalid parameter error type.
+type ErrInvalidParam interface {
+ awserr.Error
+
+ // Field name the error occurred on.
+ Field() string
+
+ // SetContext updates the context of the error.
+ SetContext(string)
+
+ // AddNestedContext updates the error's context to include a nested level.
+ AddNestedContext(string)
+}
+
+type errInvalidParam struct {
+ context string
+ nestedContext string
+ field string
+ code string
+ msg string
+}
+
+// Code returns the error code for the type of invalid parameter.
+func (e *errInvalidParam) Code() string {
+ return e.code
+}
+
+// Message returns the reason the parameter was invalid, and its context.
+func (e *errInvalidParam) Message() string {
+ return fmt.Sprintf("%s, %s.", e.msg, e.Field())
+}
+
+// Error returns the string version of the invalid parameter error.
+func (e *errInvalidParam) Error() string {
+ return fmt.Sprintf("%s: %s", e.code, e.Message())
+}
+
+// OrigErr returns nil, Implemented for awserr.Error interface.
+func (e *errInvalidParam) OrigErr() error {
+ return nil
+}
+
+// Field Returns the field and context the error occurred.
+func (e *errInvalidParam) Field() string {
+ field := e.context
+ if len(field) > 0 {
+ field += "."
+ }
+ if len(e.nestedContext) > 0 {
+ field += fmt.Sprintf("%s.", e.nestedContext)
+ }
+ field += e.field
+
+ return field
+}
+
+// SetContext updates the base context of the error.
+func (e *errInvalidParam) SetContext(ctx string) {
+ e.context = ctx
+}
+
+// AddNestedContext prepends a context to the field's path.
+func (e *errInvalidParam) AddNestedContext(ctx string) {
+ if len(e.nestedContext) == 0 {
+ e.nestedContext = ctx
+ } else {
+ e.nestedContext = fmt.Sprintf("%s.%s", ctx, e.nestedContext)
+ }
+
+}
+
+// An ErrParamRequired represents an required parameter error.
+type ErrParamRequired struct {
+ errInvalidParam
+}
+
+// NewErrParamRequired creates a new required parameter error.
+func NewErrParamRequired(field string) *ErrParamRequired {
+ return &ErrParamRequired{
+ errInvalidParam{
+ code: ParamRequiredErrCode,
+ field: field,
+ msg: fmt.Sprintf("missing required field"),
+ },
+ }
+}
+
+// An ErrParamMinValue represents a minimum value parameter error.
+type ErrParamMinValue struct {
+ errInvalidParam
+ min float64
+}
+
+// NewErrParamMinValue creates a new minimum value parameter error.
+func NewErrParamMinValue(field string, min float64) *ErrParamMinValue {
+ return &ErrParamMinValue{
+ errInvalidParam: errInvalidParam{
+ code: ParamMinValueErrCode,
+ field: field,
+ msg: fmt.Sprintf("minimum field value of %v", min),
+ },
+ min: min,
+ }
+}
+
+// MinValue returns the field's require minimum value.
+//
+// float64 is returned for both int and float min values.
+func (e *ErrParamMinValue) MinValue() float64 {
+ return e.min
+}
+
+// An ErrParamMinLen represents a minimum length parameter error.
+type ErrParamMinLen struct {
+ errInvalidParam
+ min int
+}
+
+// NewErrParamMinLen creates a new minimum length parameter error.
+func NewErrParamMinLen(field string, min int) *ErrParamMinLen {
+ return &ErrParamMinLen{
+ errInvalidParam: errInvalidParam{
+ code: ParamMinValueErrCode,
+ field: field,
+ msg: fmt.Sprintf("minimum field size of %v", min),
+ },
+ min: min,
+ }
+}
+
+// MinLen returns the field's required minimum length.
+func (e *ErrParamMinLen) MinLen() int {
+ return e.min
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go
new file mode 100644
index 0000000..d3dc840
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go
@@ -0,0 +1,223 @@
+/*
+Package session provides configuration for the SDK's service clients.
+
+Sessions can be shared across all service clients that share the same base
+configuration. The Session is built from the SDK's default configuration and
+request handlers.
+
+Sessions should be cached when possible, because creating a new Session will
+load all configuration values from the environment, and config files each time
+the Session is created. Sharing the Session value across all of your service
+clients will ensure the configuration is loaded the fewest number of times possible.
+
+Concurrency
+
+Sessions are safe to use concurrently as long as the Session is not being
+modified. The SDK will not modify the Session once the Session has been created.
+Creating service clients concurrently from a shared Session is safe.
+
+Sessions from Shared Config
+
+Sessions can be created using the method above that will only load the
+additional config if the AWS_SDK_LOAD_CONFIG environment variable is set.
+Alternatively you can explicitly create a Session with shared config enabled.
+To do this you can use NewSessionWithOptions to configure how the Session will
+be created. Using the NewSessionWithOptions with SharedConfigState set to
+SharedConfigEnabled will create the session as if the AWS_SDK_LOAD_CONFIG
+environment variable was set.
+
+Creating Sessions
+
+When creating Sessions optional aws.Config values can be passed in that will
+override the default, or loaded config values the Session is being created
+with. This allows you to provide additional, or case based, configuration
+as needed.
+
+By default NewSession will only load credentials from the shared credentials
+file (~/.aws/credentials). If the AWS_SDK_LOAD_CONFIG environment variable is
+set to a truthy value the Session will be created from the configuration
+values from the shared config (~/.aws/config) and shared credentials
+(~/.aws/credentials) files. See the section Sessions from Shared Config for
+more information.
+
+Create a Session with the default config and request handlers. With credentials
+region, and profile loaded from the environment and shared config automatically.
+Requires the AWS_PROFILE to be set, or "default" is used.
+
+ // Create Session
+ sess, err := session.NewSession()
+
+ // Create a Session with a custom region
+ sess, err := session.NewSession(&aws.Config{Region: aws.String("us-east-1")})
+
+ // Create a S3 client instance from a session
+ sess, err := session.NewSession()
+ if err != nil {
+ // Handle Session creation error
+ }
+ svc := s3.New(sess)
+
+Create Session With Option Overrides
+
+In addition to NewSession, Sessions can be created using NewSessionWithOptions.
+This func allows you to control and override how the Session will be created
+through code instead of being driven by environment variables only.
+
+Use NewSessionWithOptions when you want to provide the config profile, or
+override the shared config state (AWS_SDK_LOAD_CONFIG).
+
+ // Equivalent to session.NewSession()
+ sess, err := session.NewSessionWithOptions(session.Options{})
+
+ // Specify profile to load for the session's config
+ sess, err := session.NewSessionWithOptions(session.Options{
+ Profile: "profile_name",
+ })
+
+ // Specify profile for config and region for requests
+ sess, err := session.NewSessionWithOptions(session.Options{
+ Config: aws.Config{Region: aws.String("us-east-1")},
+ Profile: "profile_name",
+ })
+
+ // Force enable Shared Config support
+ sess, err := session.NewSessionWithOptions(session.Options{
+ SharedConfigState: SharedConfigEnable,
+ })
+
+Adding Handlers
+
+You can add handlers to a session for processing HTTP requests. All service
+clients that use the session inherit the handlers. For example, the following
+handler logs every request and its payload made by a service client:
+
+ // Create a session, and add additional handlers for all service
+ // clients created with the Session to inherit. Adds logging handler.
+ sess, err := session.NewSession()
+ sess.Handlers.Send.PushFront(func(r *request.Request) {
+ // Log every request made and its payload
+ logger.Println("Request: %s/%s, Payload: %s",
+ r.ClientInfo.ServiceName, r.Operation, r.Params)
+ })
+
+Deprecated "New" function
+
+The New session function has been deprecated because it does not provide good
+way to return errors that occur when loading the configuration files and values.
+Because of this, NewSession was created so errors can be retrieved when
+creating a session fails.
+
+Shared Config Fields
+
+By default the SDK will only load the shared credentials file's (~/.aws/credentials)
+credentials values, and all other config is provided by the environment variables,
+SDK defaults, and user provided aws.Config values.
+
+If the AWS_SDK_LOAD_CONFIG environment variable is set, or SharedConfigEnable
+option is used to create the Session the full shared config values will be
+loaded. This includes credentials, region, and support for assume role. In
+addition the Session will load its configuration from both the shared config
+file (~/.aws/config) and shared credentials file (~/.aws/credentials). Both
+files have the same format.
+
+If both config files are present the configuration from both files will be
+read. The Session will be created from configuration values from the shared
+credentials file (~/.aws/credentials) over those in the shared credentials
+file (~/.aws/config).
+
+Credentials are the values the SDK should use for authenticating requests with
+AWS Services. They arfrom a configuration file will need to include both
+aws_access_key_id and aws_secret_access_key must be provided together in the
+same file to be considered valid. The values will be ignored if not a complete
+group. aws_session_token is an optional field that can be provided if both of
+the other two fields are also provided.
+
+ aws_access_key_id = AKID
+ aws_secret_access_key = SECRET
+ aws_session_token = TOKEN
+
+Assume Role values allow you to configure the SDK to assume an IAM role using
+a set of credentials provided in a config file via the source_profile field.
+Both "role_arn" and "source_profile" are required. The SDK does not support
+assuming a role with MFA token Via the Session's constructor. You can use the
+stscreds.AssumeRoleProvider credentials provider to specify custom
+configuration and support for MFA.
+
+ role_arn = arn:aws:iam::<account_number>:role/<role_name>
+ source_profile = profile_with_creds
+ external_id = 1234
+ mfa_serial = not supported!
+ role_session_name = session_name
+
+Region is the region the SDK should use for looking up AWS service endpoints
+and signing requests.
+
+ region = us-east-1
+
+Environment Variables
+
+When a Session is created several environment variables can be set to adjust
+how the SDK functions, and what configuration data it loads when creating
+Sessions. All environment values are optional, but some values like credentials
+require multiple of the values to set or the partial values will be ignored.
+All environment variable values are strings unless otherwise noted.
+
+Environment configuration values. If set both Access Key ID and Secret Access
+Key must be provided. Session Token and optionally also be provided, but is
+not required.
+
+ # Access Key ID
+ AWS_ACCESS_KEY_ID=AKID
+ AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set.
+
+ # Secret Access Key
+ AWS_SECRET_ACCESS_KEY=SECRET
+ AWS_SECRET_KEY=SECRET=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set.
+
+ # Session Token
+ AWS_SESSION_TOKEN=TOKEN
+
+Region value will instruct the SDK where to make service API requests to. If is
+not provided in the environment the region must be provided before a service
+client request is made.
+
+ AWS_REGION=us-east-1
+
+ # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set,
+ # and AWS_REGION is not also set.
+ AWS_DEFAULT_REGION=us-east-1
+
+Profile name the SDK should load use when loading shared config from the
+configuration files. If not provided "default" will be used as the profile name.
+
+ AWS_PROFILE=my_profile
+
+ # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set,
+ # and AWS_PROFILE is not also set.
+ AWS_DEFAULT_PROFILE=my_profile
+
+SDK load config instructs the SDK to load the shared config in addition to
+shared credentials. This also expands the configuration loaded so the shared
+credentials will have parity with the shared config file. This also enables
+Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE
+env values as well.
+
+ AWS_SDK_LOAD_CONFIG=1
+
+Shared credentials file path can be set to instruct the SDK to use an alternative
+file for the shared credentials. If not set the file will be loaded from
+$HOME/.aws/credentials on Linux/Unix based systems, and
+%USERPROFILE%\.aws\credentials on Windows.
+
+ AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials
+
+Shared config file path can be set to instruct the SDK to use an alternative
+file for the shared config. If not set the file will be loaded from
+$HOME/.aws/config on Linux/Unix based systems, and
+%USERPROFILE%\.aws\config on Windows.
+
+ AWS_CONFIG_FILE=$HOME/my_shared_config
+
+
+*/
+package session
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go
new file mode 100644
index 0000000..d2f0c84
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go
@@ -0,0 +1,188 @@
+package session
+
+import (
+ "os"
+ "path/filepath"
+ "strconv"
+
+ "github.com/aws/aws-sdk-go/aws/credentials"
+)
+
+// envConfig is a collection of environment values the SDK will read
+// setup config from. All environment values are optional. But some values
+// such as credentials require multiple values to be complete or the values
+// will be ignored.
+type envConfig struct {
+ // Environment configuration values. If set both Access Key ID and Secret Access
+ // Key must be provided. Session Token and optionally also be provided, but is
+ // not required.
+ //
+ // # Access Key ID
+ // AWS_ACCESS_KEY_ID=AKID
+ // AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set.
+ //
+ // # Secret Access Key
+ // AWS_SECRET_ACCESS_KEY=SECRET
+ // AWS_SECRET_KEY=SECRET=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set.
+ //
+ // # Session Token
+ // AWS_SESSION_TOKEN=TOKEN
+ Creds credentials.Value
+
+ // Region value will instruct the SDK where to make service API requests to. If is
+ // not provided in the environment the region must be provided before a service
+ // client request is made.
+ //
+ // AWS_REGION=us-east-1
+ //
+ // # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set,
+ // # and AWS_REGION is not also set.
+ // AWS_DEFAULT_REGION=us-east-1
+ Region string
+
+ // Profile name the SDK should load use when loading shared configuration from the
+ // shared configuration files. If not provided "default" will be used as the
+ // profile name.
+ //
+ // AWS_PROFILE=my_profile
+ //
+ // # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set,
+ // # and AWS_PROFILE is not also set.
+ // AWS_DEFAULT_PROFILE=my_profile
+ Profile string
+
+ // SDK load config instructs the SDK to load the shared config in addition to
+ // shared credentials. This also expands the configuration loaded from the shared
+ // credentials to have parity with the shared config file. This also enables
+ // Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE
+ // env values as well.
+ //
+ // AWS_SDK_LOAD_CONFIG=1
+ EnableSharedConfig bool
+
+ // Shared credentials file path can be set to instruct the SDK to use an alternate
+ // file for the shared credentials. If not set the file will be loaded from
+ // $HOME/.aws/credentials on Linux/Unix based systems, and
+ // %USERPROFILE%\.aws\credentials on Windows.
+ //
+ // AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials
+ SharedCredentialsFile string
+
+ // Shared config file path can be set to instruct the SDK to use an alternate
+ // file for the shared config. If not set the file will be loaded from
+ // $HOME/.aws/config on Linux/Unix based systems, and
+ // %USERPROFILE%\.aws\config on Windows.
+ //
+ // AWS_CONFIG_FILE=$HOME/my_shared_config
+ SharedConfigFile string
+}
+
+var (
+ credAccessEnvKey = []string{
+ "AWS_ACCESS_KEY_ID",
+ "AWS_ACCESS_KEY",
+ }
+ credSecretEnvKey = []string{
+ "AWS_SECRET_ACCESS_KEY",
+ "AWS_SECRET_KEY",
+ }
+ credSessionEnvKey = []string{
+ "AWS_SESSION_TOKEN",
+ }
+
+ regionEnvKeys = []string{
+ "AWS_REGION",
+ "AWS_DEFAULT_REGION", // Only read if AWS_SDK_LOAD_CONFIG is also set
+ }
+ profileEnvKeys = []string{
+ "AWS_PROFILE",
+ "AWS_DEFAULT_PROFILE", // Only read if AWS_SDK_LOAD_CONFIG is also set
+ }
+)
+
+// loadEnvConfig retrieves the SDK's environment configuration.
+// See `envConfig` for the values that will be retrieved.
+//
+// If the environment variable `AWS_SDK_LOAD_CONFIG` is set to a truthy value
+// the shared SDK config will be loaded in addition to the SDK's specific
+// configuration values.
+func loadEnvConfig() envConfig {
+ enableSharedConfig, _ := strconv.ParseBool(os.Getenv("AWS_SDK_LOAD_CONFIG"))
+ return envConfigLoad(enableSharedConfig)
+}
+
+// loadEnvSharedConfig retrieves the SDK's environment configuration, and the
+// SDK shared config. See `envConfig` for the values that will be retrieved.
+//
+// Loads the shared configuration in addition to the SDK's specific configuration.
+// This will load the same values as `loadEnvConfig` if the `AWS_SDK_LOAD_CONFIG`
+// environment variable is set.
+func loadSharedEnvConfig() envConfig {
+ return envConfigLoad(true)
+}
+
+func envConfigLoad(enableSharedConfig bool) envConfig {
+ cfg := envConfig{}
+
+ cfg.EnableSharedConfig = enableSharedConfig
+
+ setFromEnvVal(&cfg.Creds.AccessKeyID, credAccessEnvKey)
+ setFromEnvVal(&cfg.Creds.SecretAccessKey, credSecretEnvKey)
+ setFromEnvVal(&cfg.Creds.SessionToken, credSessionEnvKey)
+
+ // Require logical grouping of credentials
+ if len(cfg.Creds.AccessKeyID) == 0 || len(cfg.Creds.SecretAccessKey) == 0 {
+ cfg.Creds = credentials.Value{}
+ } else {
+ cfg.Creds.ProviderName = "EnvConfigCredentials"
+ }
+
+ regionKeys := regionEnvKeys
+ profileKeys := profileEnvKeys
+ if !cfg.EnableSharedConfig {
+ regionKeys = regionKeys[:1]
+ profileKeys = profileKeys[:1]
+ }
+
+ setFromEnvVal(&cfg.Region, regionKeys)
+ setFromEnvVal(&cfg.Profile, profileKeys)
+
+ cfg.SharedCredentialsFile = sharedCredentialsFilename()
+ cfg.SharedConfigFile = sharedConfigFilename()
+
+ return cfg
+}
+
+func setFromEnvVal(dst *string, keys []string) {
+ for _, k := range keys {
+ if v := os.Getenv(k); len(v) > 0 {
+ *dst = v
+ break
+ }
+ }
+}
+
+func sharedCredentialsFilename() string {
+ if name := os.Getenv("AWS_SHARED_CREDENTIALS_FILE"); len(name) > 0 {
+ return name
+ }
+
+ return filepath.Join(userHomeDir(), ".aws", "credentials")
+}
+
+func sharedConfigFilename() string {
+ if name := os.Getenv("AWS_CONFIG_FILE"); len(name) > 0 {
+ return name
+ }
+
+ return filepath.Join(userHomeDir(), ".aws", "config")
+}
+
+func userHomeDir() string {
+ homeDir := os.Getenv("HOME") // *nix
+ if len(homeDir) == 0 { // windows
+ homeDir = os.Getenv("USERPROFILE")
+ }
+
+ return homeDir
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go
new file mode 100644
index 0000000..602f4e1
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go
@@ -0,0 +1,393 @@
+package session
+
+import (
+ "fmt"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/client"
+ "github.com/aws/aws-sdk-go/aws/corehandlers"
+ "github.com/aws/aws-sdk-go/aws/credentials"
+ "github.com/aws/aws-sdk-go/aws/credentials/stscreds"
+ "github.com/aws/aws-sdk-go/aws/defaults"
+ "github.com/aws/aws-sdk-go/aws/request"
+ "github.com/aws/aws-sdk-go/private/endpoints"
+)
+
+// A Session provides a central location to create service clients from and
+// store configurations and request handlers for those services.
+//
+// Sessions are safe to create service clients concurrently, but it is not safe
+// to mutate the Session concurrently.
+//
+// The Session satisfies the service client's client.ClientConfigProvider.
+type Session struct {
+ Config *aws.Config
+ Handlers request.Handlers
+}
+
+// New creates a new instance of the handlers merging in the provided configs
+// on top of the SDK's default configurations. Once the Session is created it
+// can be mutated to modify the Config or Handlers. The Session is safe to be
+// read concurrently, but it should not be written to concurrently.
+//
+// If the AWS_SDK_LOAD_CONFIG environment is set to a truthy value, the New
+// method could now encounter an error when loading the configuration. When
+// The environment variable is set, and an error occurs, New will return a
+// session that will fail all requests reporting the error that occured while
+// loading the session. Use NewSession to get the error when creating the
+// session.
+//
+// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
+// the shared config file (~/.aws/config) will also be loaded, in addition to
+// the shared credentials file (~/.aws/config). Values set in both the
+// shared config, and shared credentials will be taken from the shared
+// credentials file.
+//
+// Deprecated: Use NewSession functiions to create sessions instead. NewSession
+// has the same functionality as New except an error can be returned when the
+// func is called instead of waiting to receive an error until a request is made.
+func New(cfgs ...*aws.Config) *Session {
+ // load initial config from environment
+ envCfg := loadEnvConfig()
+
+ if envCfg.EnableSharedConfig {
+ s, err := newSession(envCfg, cfgs...)
+ if err != nil {
+ // Old session.New expected all errors to be discovered when
+ // a request is made, and would report the errors then. This
+ // needs to be replicated if an error occurs while creating
+ // the session.
+ msg := "failed to create session with AWS_SDK_LOAD_CONFIG enabled. " +
+ "Use session.NewSession to handle errors occuring during session creation."
+
+ // Session creation failed, need to report the error and prevent
+ // any requests from succeeding.
+ s = &Session{Config: defaults.Config()}
+ s.Config.MergeIn(cfgs...)
+ s.Config.Logger.Log("ERROR:", msg, "Error:", err)
+ s.Handlers.Validate.PushBack(func(r *request.Request) {
+ r.Error = err
+ })
+ }
+ return s
+ }
+
+ return oldNewSession(cfgs...)
+}
+
+// NewSession returns a new Session created from SDK defaults, config files,
+// environment, and user provided config files. Once the Session is created
+// it can be mutated to modify the Config or Handlers. The Session is safe to
+// be read concurrently, but it should not be written to concurrently.
+//
+// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
+// the shared config file (~/.aws/config) will also be loaded in addition to
+// the shared credentials file (~/.aws/config). Values set in both the
+// shared config, and shared credentials will be taken from the shared
+// credentials file. Enabling the Shared Config will also allow the Session
+// to be built with retrieving credentials with AssumeRole set in the config.
+//
+// See the NewSessionWithOptions func for information on how to override or
+// control through code how the Session will be created. Such as specifing the
+// config profile, and controlling if shared config is enabled or not.
+func NewSession(cfgs ...*aws.Config) (*Session, error) {
+ envCfg := loadEnvConfig()
+
+ return newSession(envCfg, cfgs...)
+}
+
+// SharedConfigState provides the ability to optionally override the state
+// of the session's creation based on the shared config being enabled or
+// disabled.
+type SharedConfigState int
+
+const (
+ // SharedConfigStateFromEnv does not override any state of the
+ // AWS_SDK_LOAD_CONFIG env var. It is the default value of the
+ // SharedConfigState type.
+ SharedConfigStateFromEnv SharedConfigState = iota
+
+ // SharedConfigDisable overrides the AWS_SDK_LOAD_CONFIG env var value
+ // and disables the shared config functionality.
+ SharedConfigDisable
+
+ // SharedConfigEnable overrides the AWS_SDK_LOAD_CONFIG env var value
+ // and enables the shared config functionality.
+ SharedConfigEnable
+)
+
+// Options provides the means to control how a Session is created and what
+// configuration values will be loaded.
+//
+type Options struct {
+ // Provides config values for the SDK to use when creating service clients
+ // and making API requests to services. Any value set in with this field
+ // will override the associated value provided by the SDK defaults,
+ // environment or config files where relevent.
+ //
+ // If not set, configuration values from from SDK defaults, environment,
+ // config will be used.
+ Config aws.Config
+
+ // Overrides the config profile the Session should be created from. If not
+ // set the value of the environment variable will be loaded (AWS_PROFILE,
+ // or AWS_DEFAULT_PROFILE if the Shared Config is enabled).
+ //
+ // If not set and environment variables are not set the "default"
+ // (DefaultSharedConfigProfile) will be used as the profile to load the
+ // session config from.
+ Profile string
+
+ // Instructs how the Session will be created based on the AWS_SDK_LOAD_CONFIG
+ // environment variable. By default a Session will be created using the
+ // value provided by the AWS_SDK_LOAD_CONFIG environment variable.
+ //
+ // Setting this value to SharedConfigEnable or SharedConfigDisable
+ // will allow you to override the AWS_SDK_LOAD_CONFIG environment variable
+ // and enable or disable the shared config functionality.
+ SharedConfigState SharedConfigState
+}
+
+// NewSessionWithOptions returns a new Session created from SDK defaults, config files,
+// environment, and user provided config files. This func uses the Options
+// values to configure how the Session is created.
+//
+// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
+// the shared config file (~/.aws/config) will also be loaded in addition to
+// the shared credentials file (~/.aws/config). Values set in both the
+// shared config, and shared credentials will be taken from the shared
+// credentials file. Enabling the Shared Config will also allow the Session
+// to be built with retrieving credentials with AssumeRole set in the config.
+//
+// // Equivalent to session.New
+// sess, err := session.NewSessionWithOptions(session.Options{})
+//
+// // Specify profile to load for the session's config
+// sess, err := session.NewSessionWithOptions(session.Options{
+// Profile: "profile_name",
+// })
+//
+// // Specify profile for config and region for requests
+// sess, err := session.NewSessionWithOptions(session.Options{
+// Config: aws.Config{Region: aws.String("us-east-1")},
+// Profile: "profile_name",
+// })
+//
+// // Force enable Shared Config support
+// sess, err := session.NewSessionWithOptions(session.Options{
+// SharedConfigState: SharedConfigEnable,
+// })
+func NewSessionWithOptions(opts Options) (*Session, error) {
+ var envCfg envConfig
+ if opts.SharedConfigState == SharedConfigEnable {
+ envCfg = loadSharedEnvConfig()
+ } else {
+ envCfg = loadEnvConfig()
+ }
+
+ if len(opts.Profile) > 0 {
+ envCfg.Profile = opts.Profile
+ }
+
+ switch opts.SharedConfigState {
+ case SharedConfigDisable:
+ envCfg.EnableSharedConfig = false
+ case SharedConfigEnable:
+ envCfg.EnableSharedConfig = true
+ }
+
+ return newSession(envCfg, &opts.Config)
+}
+
+// Must is a helper function to ensure the Session is valid and there was no
+// error when calling a NewSession function.
+//
+// This helper is intended to be used in variable initialization to load the
+// Session and configuration at startup. Such as:
+//
+// var sess = session.Must(session.NewSession())
+func Must(sess *Session, err error) *Session {
+ if err != nil {
+ panic(err)
+ }
+
+ return sess
+}
+
+func oldNewSession(cfgs ...*aws.Config) *Session {
+ cfg := defaults.Config()
+ handlers := defaults.Handlers()
+
+ // Apply the passed in configs so the configuration can be applied to the
+ // default credential chain
+ cfg.MergeIn(cfgs...)
+ cfg.Credentials = defaults.CredChain(cfg, handlers)
+
+ // Reapply any passed in configs to override credentials if set
+ cfg.MergeIn(cfgs...)
+
+ s := &Session{
+ Config: cfg,
+ Handlers: handlers,
+ }
+
+ initHandlers(s)
+
+ return s
+}
+
+func newSession(envCfg envConfig, cfgs ...*aws.Config) (*Session, error) {
+ cfg := defaults.Config()
+ handlers := defaults.Handlers()
+
+ // Get a merged version of the user provided config to determine if
+ // credentials were.
+ userCfg := &aws.Config{}
+ userCfg.MergeIn(cfgs...)
+
+ // Order config files will be loaded in with later files overwriting
+ // previous config file values.
+ cfgFiles := []string{envCfg.SharedConfigFile, envCfg.SharedCredentialsFile}
+ if !envCfg.EnableSharedConfig {
+ // The shared config file (~/.aws/config) is only loaded if instructed
+ // to load via the envConfig.EnableSharedConfig (AWS_SDK_LOAD_CONFIG).
+ cfgFiles = cfgFiles[1:]
+ }
+
+ // Load additional config from file(s)
+ sharedCfg, err := loadSharedConfig(envCfg.Profile, cfgFiles)
+ if err != nil {
+ return nil, err
+ }
+
+ mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers)
+
+ s := &Session{
+ Config: cfg,
+ Handlers: handlers,
+ }
+
+ initHandlers(s)
+
+ return s, nil
+}
+
+func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers) {
+ // Merge in user provided configuration
+ cfg.MergeIn(userCfg)
+
+ // Region if not already set by user
+ if len(aws.StringValue(cfg.Region)) == 0 {
+ if len(envCfg.Region) > 0 {
+ cfg.WithRegion(envCfg.Region)
+ } else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 {
+ cfg.WithRegion(sharedCfg.Region)
+ }
+ }
+
+ // Configure credentials if not already set
+ if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil {
+ if len(envCfg.Creds.AccessKeyID) > 0 {
+ cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
+ envCfg.Creds,
+ )
+ } else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil {
+ cfgCp := *cfg
+ cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds(
+ sharedCfg.AssumeRoleSource.Creds,
+ )
+ cfg.Credentials = stscreds.NewCredentials(
+ &Session{
+ Config: &cfgCp,
+ Handlers: handlers.Copy(),
+ },
+ sharedCfg.AssumeRole.RoleARN,
+ func(opt *stscreds.AssumeRoleProvider) {
+ opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName
+
+ if len(sharedCfg.AssumeRole.ExternalID) > 0 {
+ opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID)
+ }
+
+ // MFA not supported
+ },
+ )
+ } else if len(sharedCfg.Creds.AccessKeyID) > 0 {
+ cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
+ sharedCfg.Creds,
+ )
+ } else {
+ // Fallback to default credentials provider, include mock errors
+ // for the credential chain so user can identify why credentials
+ // failed to be retrieved.
+ cfg.Credentials = credentials.NewCredentials(&credentials.ChainProvider{
+ VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors),
+ Providers: []credentials.Provider{
+ &credProviderError{Err: awserr.New("EnvAccessKeyNotFound", "failed to find credentials in the environment.", nil)},
+ &credProviderError{Err: awserr.New("SharedCredsLoad", fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil)},
+ defaults.RemoteCredProvider(*cfg, handlers),
+ },
+ })
+ }
+ }
+}
+
+type credProviderError struct {
+ Err error
+}
+
+var emptyCreds = credentials.Value{}
+
+func (c credProviderError) Retrieve() (credentials.Value, error) {
+ return credentials.Value{}, c.Err
+}
+func (c credProviderError) IsExpired() bool {
+ return true
+}
+
+func initHandlers(s *Session) {
+ // Add the Validate parameter handler if it is not disabled.
+ s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler)
+ if !aws.BoolValue(s.Config.DisableParamValidation) {
+ s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler)
+ }
+}
+
+// Copy creates and returns a copy of the current Session, coping the config
+// and handlers. If any additional configs are provided they will be merged
+// on top of the Session's copied config.
+//
+// // Create a copy of the current Session, configured for the us-west-2 region.
+// sess.Copy(&aws.Config{Region: aws.String("us-west-2")})
+func (s *Session) Copy(cfgs ...*aws.Config) *Session {
+ newSession := &Session{
+ Config: s.Config.Copy(cfgs...),
+ Handlers: s.Handlers.Copy(),
+ }
+
+ initHandlers(newSession)
+
+ return newSession
+}
+
+// ClientConfig satisfies the client.ConfigProvider interface and is used to
+// configure the service client instances. Passing the Session to the service
+// client's constructor (New) will use this method to configure the client.
+func (s *Session) ClientConfig(serviceName string, cfgs ...*aws.Config) client.Config {
+ s = s.Copy(cfgs...)
+ endpoint, signingRegion := endpoints.NormalizeEndpoint(
+ aws.StringValue(s.Config.Endpoint),
+ serviceName,
+ aws.StringValue(s.Config.Region),
+ aws.BoolValue(s.Config.DisableSSL),
+ aws.BoolValue(s.Config.UseDualStack),
+ )
+
+ return client.Config{
+ Config: s.Config,
+ Handlers: s.Handlers,
+ Endpoint: endpoint,
+ SigningRegion: signingRegion,
+ }
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go
new file mode 100644
index 0000000..b58076f
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go
@@ -0,0 +1,295 @@
+package session
+
+import (
+ "fmt"
+ "io/ioutil"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/credentials"
+ "github.com/go-ini/ini"
+)
+
+const (
+ // Static Credentials group
+ accessKeyIDKey = `aws_access_key_id` // group required
+ secretAccessKey = `aws_secret_access_key` // group required
+ sessionTokenKey = `aws_session_token` // optional
+
+ // Assume Role Credentials group
+ roleArnKey = `role_arn` // group required
+ sourceProfileKey = `source_profile` // group required
+ externalIDKey = `external_id` // optional
+ mfaSerialKey = `mfa_serial` // optional
+ roleSessionNameKey = `role_session_name` // optional
+
+ // Additional Config fields
+ regionKey = `region`
+
+ // DefaultSharedConfigProfile is the default profile to be used when
+ // loading configuration from the config files if another profile name
+ // is not provided.
+ DefaultSharedConfigProfile = `default`
+)
+
+type assumeRoleConfig struct {
+ RoleARN string
+ SourceProfile string
+ ExternalID string
+ MFASerial string
+ RoleSessionName string
+}
+
+// sharedConfig represents the configuration fields of the SDK config files.
+type sharedConfig struct {
+ // Credentials values from the config file. Both aws_access_key_id
+ // and aws_secret_access_key must be provided together in the same file
+ // to be considered valid. The values will be ignored if not a complete group.
+ // aws_session_token is an optional field that can be provided if both of the
+ // other two fields are also provided.
+ //
+ // aws_access_key_id
+ // aws_secret_access_key
+ // aws_session_token
+ Creds credentials.Value
+
+ AssumeRole assumeRoleConfig
+ AssumeRoleSource *sharedConfig
+
+ // Region is the region the SDK should use for looking up AWS service endpoints
+ // and signing requests.
+ //
+ // region
+ Region string
+}
+
+type sharedConfigFile struct {
+ Filename string
+ IniData *ini.File
+}
+
+// loadSharedConfig retrieves the configuration from the list of files
+// using the profile provided. The order the files are listed will determine
+// precedence. Values in subsequent files will overwrite values defined in
+// earlier files.
+//
+// For example, given two files A and B. Both define credentials. If the order
+// of the files are A then B, B's credential values will be used instead of A's.
+//
+// See sharedConfig.setFromFile for information how the config files
+// will be loaded.
+func loadSharedConfig(profile string, filenames []string) (sharedConfig, error) {
+ if len(profile) == 0 {
+ profile = DefaultSharedConfigProfile
+ }
+
+ files, err := loadSharedConfigIniFiles(filenames)
+ if err != nil {
+ return sharedConfig{}, err
+ }
+
+ cfg := sharedConfig{}
+ if err = cfg.setFromIniFiles(profile, files); err != nil {
+ return sharedConfig{}, err
+ }
+
+ if len(cfg.AssumeRole.SourceProfile) > 0 {
+ if err := cfg.setAssumeRoleSource(profile, files); err != nil {
+ return sharedConfig{}, err
+ }
+ }
+
+ return cfg, nil
+}
+
+func loadSharedConfigIniFiles(filenames []string) ([]sharedConfigFile, error) {
+ files := make([]sharedConfigFile, 0, len(filenames))
+
+ for _, filename := range filenames {
+ b, err := ioutil.ReadFile(filename)
+ if err != nil {
+ // Skip files which can't be opened and read for whatever reason
+ continue
+ }
+
+ f, err := ini.Load(b)
+ if err != nil {
+ return nil, SharedConfigLoadError{Filename: filename}
+ }
+
+ files = append(files, sharedConfigFile{
+ Filename: filename, IniData: f,
+ })
+ }
+
+ return files, nil
+}
+
+func (cfg *sharedConfig) setAssumeRoleSource(origProfile string, files []sharedConfigFile) error {
+ var assumeRoleSrc sharedConfig
+
+ // Multiple level assume role chains are not support
+ if cfg.AssumeRole.SourceProfile == origProfile {
+ assumeRoleSrc = *cfg
+ assumeRoleSrc.AssumeRole = assumeRoleConfig{}
+ } else {
+ err := assumeRoleSrc.setFromIniFiles(cfg.AssumeRole.SourceProfile, files)
+ if err != nil {
+ return err
+ }
+ }
+
+ if len(assumeRoleSrc.Creds.AccessKeyID) == 0 {
+ return SharedConfigAssumeRoleError{RoleARN: cfg.AssumeRole.RoleARN}
+ }
+
+ cfg.AssumeRoleSource = &assumeRoleSrc
+
+ return nil
+}
+
+func (cfg *sharedConfig) setFromIniFiles(profile string, files []sharedConfigFile) error {
+ // Trim files from the list that don't exist.
+ for _, f := range files {
+ if err := cfg.setFromIniFile(profile, f); err != nil {
+ if _, ok := err.(SharedConfigProfileNotExistsError); ok {
+ // Ignore proviles missings
+ continue
+ }
+ return err
+ }
+ }
+
+ return nil
+}
+
+// setFromFile loads the configuration from the file using
+// the profile provided. A sharedConfig pointer type value is used so that
+// multiple config file loadings can be chained.
+//
+// Only loads complete logically grouped values, and will not set fields in cfg
+// for incomplete grouped values in the config. Such as credentials. For example
+// if a config file only includes aws_access_key_id but no aws_secret_access_key
+// the aws_access_key_id will be ignored.
+func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile) error {
+ section, err := file.IniData.GetSection(profile)
+ if err != nil {
+ // Fallback to to alternate profile name: profile <name>
+ section, err = file.IniData.GetSection(fmt.Sprintf("profile %s", profile))
+ if err != nil {
+ return SharedConfigProfileNotExistsError{Profile: profile, Err: err}
+ }
+ }
+
+ // Shared Credentials
+ akid := section.Key(accessKeyIDKey).String()
+ secret := section.Key(secretAccessKey).String()
+ if len(akid) > 0 && len(secret) > 0 {
+ cfg.Creds = credentials.Value{
+ AccessKeyID: akid,
+ SecretAccessKey: secret,
+ SessionToken: section.Key(sessionTokenKey).String(),
+ ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", file.Filename),
+ }
+ }
+
+ // Assume Role
+ roleArn := section.Key(roleArnKey).String()
+ srcProfile := section.Key(sourceProfileKey).String()
+ if len(roleArn) > 0 && len(srcProfile) > 0 {
+ cfg.AssumeRole = assumeRoleConfig{
+ RoleARN: roleArn,
+ SourceProfile: srcProfile,
+ ExternalID: section.Key(externalIDKey).String(),
+ MFASerial: section.Key(mfaSerialKey).String(),
+ RoleSessionName: section.Key(roleSessionNameKey).String(),
+ }
+ }
+
+ // Region
+ if v := section.Key(regionKey).String(); len(v) > 0 {
+ cfg.Region = v
+ }
+
+ return nil
+}
+
+// SharedConfigLoadError is an error for the shared config file failed to load.
+type SharedConfigLoadError struct {
+ Filename string
+ Err error
+}
+
+// Code is the short id of the error.
+func (e SharedConfigLoadError) Code() string {
+ return "SharedConfigLoadError"
+}
+
+// Message is the description of the error
+func (e SharedConfigLoadError) Message() string {
+ return fmt.Sprintf("failed to load config file, %s", e.Filename)
+}
+
+// OrigErr is the underlying error that caused the failure.
+func (e SharedConfigLoadError) OrigErr() error {
+ return e.Err
+}
+
+// Error satisfies the error interface.
+func (e SharedConfigLoadError) Error() string {
+ return awserr.SprintError(e.Code(), e.Message(), "", e.Err)
+}
+
+// SharedConfigProfileNotExistsError is an error for the shared config when
+// the profile was not find in the config file.
+type SharedConfigProfileNotExistsError struct {
+ Profile string
+ Err error
+}
+
+// Code is the short id of the error.
+func (e SharedConfigProfileNotExistsError) Code() string {
+ return "SharedConfigProfileNotExistsError"
+}
+
+// Message is the description of the error
+func (e SharedConfigProfileNotExistsError) Message() string {
+ return fmt.Sprintf("failed to get profile, %s", e.Profile)
+}
+
+// OrigErr is the underlying error that caused the failure.
+func (e SharedConfigProfileNotExistsError) OrigErr() error {
+ return e.Err
+}
+
+// Error satisfies the error interface.
+func (e SharedConfigProfileNotExistsError) Error() string {
+ return awserr.SprintError(e.Code(), e.Message(), "", e.Err)
+}
+
+// SharedConfigAssumeRoleError is an error for the shared config when the
+// profile contains assume role information, but that information is invalid
+// or not complete.
+type SharedConfigAssumeRoleError struct {
+ RoleARN string
+}
+
+// Code is the short id of the error.
+func (e SharedConfigAssumeRoleError) Code() string {
+ return "SharedConfigAssumeRoleError"
+}
+
+// Message is the description of the error
+func (e SharedConfigAssumeRoleError) Message() string {
+ return fmt.Sprintf("failed to load assume role for %s, source profile has no shared credentials",
+ e.RoleARN)
+}
+
+// OrigErr is the underlying error that caused the failure.
+func (e SharedConfigAssumeRoleError) OrigErr() error {
+ return nil
+}
+
+// Error satisfies the error interface.
+func (e SharedConfigAssumeRoleError) Error() string {
+ return awserr.SprintError(e.Code(), e.Message(), "", nil)
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go
new file mode 100644
index 0000000..244c86d
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go
@@ -0,0 +1,82 @@
+package v4
+
+import (
+ "net/http"
+ "strings"
+)
+
+// validator houses a set of rule needed for validation of a
+// string value
+type rules []rule
+
+// rule interface allows for more flexible rules and just simply
+// checks whether or not a value adheres to that rule
+type rule interface {
+ IsValid(value string) bool
+}
+
+// IsValid will iterate through all rules and see if any rules
+// apply to the value and supports nested rules
+func (r rules) IsValid(value string) bool {
+ for _, rule := range r {
+ if rule.IsValid(value) {
+ return true
+ }
+ }
+ return false
+}
+
+// mapRule generic rule for maps
+type mapRule map[string]struct{}
+
+// IsValid for the map rule satisfies whether it exists in the map
+func (m mapRule) IsValid(value string) bool {
+ _, ok := m[value]
+ return ok
+}
+
+// whitelist is a generic rule for whitelisting
+type whitelist struct {
+ rule
+}
+
+// IsValid for whitelist checks if the value is within the whitelist
+func (w whitelist) IsValid(value string) bool {
+ return w.rule.IsValid(value)
+}
+
+// blacklist is a generic rule for blacklisting
+type blacklist struct {
+ rule
+}
+
+// IsValid for whitelist checks if the value is within the whitelist
+func (b blacklist) IsValid(value string) bool {
+ return !b.rule.IsValid(value)
+}
+
+type patterns []string
+
+// IsValid for patterns checks each pattern and returns if a match has
+// been found
+func (p patterns) IsValid(value string) bool {
+ for _, pattern := range p {
+ if strings.HasPrefix(http.CanonicalHeaderKey(value), pattern) {
+ return true
+ }
+ }
+ return false
+}
+
+// inclusiveRules rules allow for rules to depend on one another
+type inclusiveRules []rule
+
+// IsValid will return true if all rules are true
+func (r inclusiveRules) IsValid(value string) bool {
+ for _, rule := range r {
+ if !rule.IsValid(value) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go
new file mode 100644
index 0000000..bd082e9
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go
@@ -0,0 +1,24 @@
+// +build go1.5
+
+package v4
+
+import (
+ "net/url"
+ "strings"
+)
+
+func getURIPath(u *url.URL) string {
+ var uri string
+
+ if len(u.Opaque) > 0 {
+ uri = "/" + strings.Join(strings.Split(u.Opaque, "/")[3:], "/")
+ } else {
+ uri = u.EscapedPath()
+ }
+
+ if len(uri) == 0 {
+ uri = "/"
+ }
+
+ return uri
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path_1_4.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path_1_4.go
new file mode 100644
index 0000000..7966041
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path_1_4.go
@@ -0,0 +1,24 @@
+// +build !go1.5
+
+package v4
+
+import (
+ "net/url"
+ "strings"
+)
+
+func getURIPath(u *url.URL) string {
+ var uri string
+
+ if len(u.Opaque) > 0 {
+ uri = "/" + strings.Join(strings.Split(u.Opaque, "/")[3:], "/")
+ } else {
+ uri = u.Path
+ }
+
+ if len(uri) == 0 {
+ uri = "/"
+ }
+
+ return uri
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go
new file mode 100644
index 0000000..986530b
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go
@@ -0,0 +1,713 @@
+// Package v4 implements signing for AWS V4 signer
+//
+// Provides request signing for request that need to be signed with
+// AWS V4 Signatures.
+//
+// Standalone Signer
+//
+// Generally using the signer outside of the SDK should not require any additional
+// logic when using Go v1.5 or higher. The signer does this by taking advantage
+// of the URL.EscapedPath method. If your request URI requires additional escaping
+// you many need to use the URL.Opaque to define what the raw URI should be sent
+// to the service as.
+//
+// The signer will first check the URL.Opaque field, and use its value if set.
+// The signer does require the URL.Opaque field to be set in the form of:
+//
+// "//<hostname>/<path>"
+//
+// // e.g.
+// "//example.com/some/path"
+//
+// The leading "//" and hostname are required or the URL.Opaque escaping will
+// not work correctly.
+//
+// If URL.Opaque is not set the signer will fallback to the URL.EscapedPath()
+// method and using the returned value. If you're using Go v1.4 you must set
+// URL.Opaque if the URI path needs escaping. If URL.Opaque is not set with
+// Go v1.5 the signer will fallback to URL.Path.
+//
+// AWS v4 signature validation requires that the canonical string's URI path
+// element must be the URI escaped form of the HTTP request's path.
+// http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
+//
+// The Go HTTP client will perform escaping automatically on the request. Some
+// of these escaping may cause signature validation errors because the HTTP
+// request differs from the URI path or query that the signature was generated.
+// https://golang.org/pkg/net/url/#URL.EscapedPath
+//
+// Because of this, it is recommended that when using the signer outside of the
+// SDK that explicitly escaping the request prior to being signed is preferable,
+// and will help prevent signature validation errors. This can be done by setting
+// the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then
+// call URL.EscapedPath() if Opaque is not set.
+//
+// Test `TestStandaloneSign` provides a complete example of using the signer
+// outside of the SDK and pre-escaping the URI path.
+package v4
+
+import (
+ "bytes"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/credentials"
+ "github.com/aws/aws-sdk-go/aws/request"
+ "github.com/aws/aws-sdk-go/private/protocol/rest"
+)
+
+const (
+ authHeaderPrefix = "AWS4-HMAC-SHA256"
+ timeFormat = "20060102T150405Z"
+ shortTimeFormat = "20060102"
+
+ // emptyStringSHA256 is a SHA256 of an empty string
+ emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`
+)
+
+var ignoredHeaders = rules{
+ blacklist{
+ mapRule{
+ "Authorization": struct{}{},
+ "User-Agent": struct{}{},
+ },
+ },
+}
+
+// requiredSignedHeaders is a whitelist for build canonical headers.
+var requiredSignedHeaders = rules{
+ whitelist{
+ mapRule{
+ "Cache-Control": struct{}{},
+ "Content-Disposition": struct{}{},
+ "Content-Encoding": struct{}{},
+ "Content-Language": struct{}{},
+ "Content-Md5": struct{}{},
+ "Content-Type": struct{}{},
+ "Expires": struct{}{},
+ "If-Match": struct{}{},
+ "If-Modified-Since": struct{}{},
+ "If-None-Match": struct{}{},
+ "If-Unmodified-Since": struct{}{},
+ "Range": struct{}{},
+ "X-Amz-Acl": struct{}{},
+ "X-Amz-Copy-Source": struct{}{},
+ "X-Amz-Copy-Source-If-Match": struct{}{},
+ "X-Amz-Copy-Source-If-Modified-Since": struct{}{},
+ "X-Amz-Copy-Source-If-None-Match": struct{}{},
+ "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{},
+ "X-Amz-Copy-Source-Range": struct{}{},
+ "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{},
+ "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{},
+ "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{},
+ "X-Amz-Grant-Full-control": struct{}{},
+ "X-Amz-Grant-Read": struct{}{},
+ "X-Amz-Grant-Read-Acp": struct{}{},
+ "X-Amz-Grant-Write": struct{}{},
+ "X-Amz-Grant-Write-Acp": struct{}{},
+ "X-Amz-Metadata-Directive": struct{}{},
+ "X-Amz-Mfa": struct{}{},
+ "X-Amz-Request-Payer": struct{}{},
+ "X-Amz-Server-Side-Encryption": struct{}{},
+ "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{},
+ "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{},
+ "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{},
+ "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{},
+ "X-Amz-Storage-Class": struct{}{},
+ "X-Amz-Website-Redirect-Location": struct{}{},
+ },
+ },
+ patterns{"X-Amz-Meta-"},
+}
+
+// allowedHoisting is a whitelist for build query headers. The boolean value
+// represents whether or not it is a pattern.
+var allowedQueryHoisting = inclusiveRules{
+ blacklist{requiredSignedHeaders},
+ patterns{"X-Amz-"},
+}
+
+// Signer applies AWS v4 signing to given request. Use this to sign requests
+// that need to be signed with AWS V4 Signatures.
+type Signer struct {
+ // The authentication credentials the request will be signed against.
+ // This value must be set to sign requests.
+ Credentials *credentials.Credentials
+
+ // Sets the log level the signer should use when reporting information to
+ // the logger. If the logger is nil nothing will be logged. See
+ // aws.LogLevelType for more information on available logging levels
+ //
+ // By default nothing will be logged.
+ Debug aws.LogLevelType
+
+ // The logger loging information will be written to. If there the logger
+ // is nil, nothing will be logged.
+ Logger aws.Logger
+
+ // Disables the Signer's moving HTTP header key/value pairs from the HTTP
+ // request header to the request's query string. This is most commonly used
+ // with pre-signed requests preventing headers from being added to the
+ // request's query string.
+ DisableHeaderHoisting bool
+
+ // Disables the automatic escaping of the URI path of the request for the
+ // siganture's canonical string's path. For services that do not need additional
+ // escaping then use this to disable the signer escaping the path.
+ //
+ // S3 is an example of a service that does not need additional escaping.
+ //
+ // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
+ DisableURIPathEscaping bool
+
+ // currentTimeFn returns the time value which represents the current time.
+ // This value should only be used for testing. If it is nil the default
+ // time.Now will be used.
+ currentTimeFn func() time.Time
+}
+
+// NewSigner returns a Signer pointer configured with the credentials and optional
+// option values provided. If not options are provided the Signer will use its
+// default configuration.
+func NewSigner(credentials *credentials.Credentials, options ...func(*Signer)) *Signer {
+ v4 := &Signer{
+ Credentials: credentials,
+ }
+
+ for _, option := range options {
+ option(v4)
+ }
+
+ return v4
+}
+
+type signingCtx struct {
+ ServiceName string
+ Region string
+ Request *http.Request
+ Body io.ReadSeeker
+ Query url.Values
+ Time time.Time
+ ExpireTime time.Duration
+ SignedHeaderVals http.Header
+
+ DisableURIPathEscaping bool
+
+ credValues credentials.Value
+ isPresign bool
+ formattedTime string
+ formattedShortTime string
+
+ bodyDigest string
+ signedHeaders string
+ canonicalHeaders string
+ canonicalString string
+ credentialString string
+ stringToSign string
+ signature string
+ authorization string
+}
+
+// Sign signs AWS v4 requests with the provided body, service name, region the
+// request is made to, and time the request is signed at. The signTime allows
+// you to specify that a request is signed for the future, and cannot be
+// used until then.
+//
+// Returns a list of HTTP headers that were included in the signature or an
+// error if signing the request failed. Generally for signed requests this value
+// is not needed as the full request context will be captured by the http.Request
+// value. It is included for reference though.
+//
+// Sign will set the request's Body to be the `body` parameter passed in. If
+// the body is not already an io.ReadCloser, it will be wrapped within one. If
+// a `nil` body parameter passed to Sign, the request's Body field will be
+// also set to nil. Its important to note that this functionality will not
+// change the request's ContentLength of the request.
+//
+// Sign differs from Presign in that it will sign the request using HTTP
+// header values. This type of signing is intended for http.Request values that
+// will not be shared, or are shared in a way the header values on the request
+// will not be lost.
+//
+// The requests body is an io.ReadSeeker so the SHA256 of the body can be
+// generated. To bypass the signer computing the hash you can set the
+// "X-Amz-Content-Sha256" header with a precomputed value. The signer will
+// only compute the hash if the request header value is empty.
+func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) {
+ return v4.signWithBody(r, body, service, region, 0, signTime)
+}
+
+// Presign signs AWS v4 requests with the provided body, service name, region
+// the request is made to, and time the request is signed at. The signTime
+// allows you to specify that a request is signed for the future, and cannot
+// be used until then.
+//
+// Returns a list of HTTP headers that were included in the signature or an
+// error if signing the request failed. For presigned requests these headers
+// and their values must be included on the HTTP request when it is made. This
+// is helpful to know what header values need to be shared with the party the
+// presigned request will be distributed to.
+//
+// Presign differs from Sign in that it will sign the request using query string
+// instead of header values. This allows you to share the Presigned Request's
+// URL with third parties, or distribute it throughout your system with minimal
+// dependencies.
+//
+// Presign also takes an exp value which is the duration the
+// signed request will be valid after the signing time. This is allows you to
+// set when the request will expire.
+//
+// The requests body is an io.ReadSeeker so the SHA256 of the body can be
+// generated. To bypass the signer computing the hash you can set the
+// "X-Amz-Content-Sha256" header with a precomputed value. The signer will
+// only compute the hash if the request header value is empty.
+//
+// Presigning a S3 request will not compute the body's SHA256 hash by default.
+// This is done due to the general use case for S3 presigned URLs is to share
+// PUT/GET capabilities. If you would like to include the body's SHA256 in the
+// presigned request's signature you can set the "X-Amz-Content-Sha256"
+// HTTP header and that will be included in the request's signature.
+func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) {
+ return v4.signWithBody(r, body, service, region, exp, signTime)
+}
+
+func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) {
+ currentTimeFn := v4.currentTimeFn
+ if currentTimeFn == nil {
+ currentTimeFn = time.Now
+ }
+
+ ctx := &signingCtx{
+ Request: r,
+ Body: body,
+ Query: r.URL.Query(),
+ Time: signTime,
+ ExpireTime: exp,
+ isPresign: exp != 0,
+ ServiceName: service,
+ Region: region,
+ DisableURIPathEscaping: v4.DisableURIPathEscaping,
+ }
+
+ if ctx.isRequestSigned() {
+ ctx.Time = currentTimeFn()
+ ctx.handlePresignRemoval()
+ }
+
+ var err error
+ ctx.credValues, err = v4.Credentials.Get()
+ if err != nil {
+ return http.Header{}, err
+ }
+
+ ctx.assignAmzQueryValues()
+ ctx.build(v4.DisableHeaderHoisting)
+
+ // If the request is not presigned the body should be attached to it. This
+ // prevents the confusion of wanting to send a signed request without
+ // the body the request was signed for attached.
+ if !ctx.isPresign {
+ var reader io.ReadCloser
+ if body != nil {
+ var ok bool
+ if reader, ok = body.(io.ReadCloser); !ok {
+ reader = ioutil.NopCloser(body)
+ }
+ }
+ r.Body = reader
+ }
+
+ if v4.Debug.Matches(aws.LogDebugWithSigning) {
+ v4.logSigningInfo(ctx)
+ }
+
+ return ctx.SignedHeaderVals, nil
+}
+
+func (ctx *signingCtx) handlePresignRemoval() {
+ if !ctx.isPresign {
+ return
+ }
+
+ // The credentials have expired for this request. The current signing
+ // is invalid, and needs to be request because the request will fail.
+ ctx.removePresign()
+
+ // Update the request's query string to ensure the values stays in
+ // sync in the case retrieving the new credentials fails.
+ ctx.Request.URL.RawQuery = ctx.Query.Encode()
+}
+
+func (ctx *signingCtx) assignAmzQueryValues() {
+ if ctx.isPresign {
+ ctx.Query.Set("X-Amz-Algorithm", authHeaderPrefix)
+ if ctx.credValues.SessionToken != "" {
+ ctx.Query.Set("X-Amz-Security-Token", ctx.credValues.SessionToken)
+ } else {
+ ctx.Query.Del("X-Amz-Security-Token")
+ }
+
+ return
+ }
+
+ if ctx.credValues.SessionToken != "" {
+ ctx.Request.Header.Set("X-Amz-Security-Token", ctx.credValues.SessionToken)
+ }
+}
+
+// SignRequestHandler is a named request handler the SDK will use to sign
+// service client request with using the V4 signature.
+var SignRequestHandler = request.NamedHandler{
+ Name: "v4.SignRequestHandler", Fn: SignSDKRequest,
+}
+
+// SignSDKRequest signs an AWS request with the V4 signature. This
+// request handler is bested used only with the SDK's built in service client's
+// API operation requests.
+//
+// This function should not be used on its on its own, but in conjunction with
+// an AWS service client's API operation call. To sign a standalone request
+// not created by a service client's API operation method use the "Sign" or
+// "Presign" functions of the "Signer" type.
+//
+// If the credentials of the request's config are set to
+// credentials.AnonymousCredentials the request will not be signed.
+func SignSDKRequest(req *request.Request) {
+ signSDKRequestWithCurrTime(req, time.Now)
+}
+func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time) {
+ // If the request does not need to be signed ignore the signing of the
+ // request if the AnonymousCredentials object is used.
+ if req.Config.Credentials == credentials.AnonymousCredentials {
+ return
+ }
+
+ region := req.ClientInfo.SigningRegion
+ if region == "" {
+ region = aws.StringValue(req.Config.Region)
+ }
+
+ name := req.ClientInfo.SigningName
+ if name == "" {
+ name = req.ClientInfo.ServiceName
+ }
+
+ v4 := NewSigner(req.Config.Credentials, func(v4 *Signer) {
+ v4.Debug = req.Config.LogLevel.Value()
+ v4.Logger = req.Config.Logger
+ v4.DisableHeaderHoisting = req.NotHoist
+ v4.currentTimeFn = curTimeFn
+ if name == "s3" {
+ // S3 service should not have any escaping applied
+ v4.DisableURIPathEscaping = true
+ }
+ })
+
+ signingTime := req.Time
+ if !req.LastSignedAt.IsZero() {
+ signingTime = req.LastSignedAt
+ }
+
+ signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(),
+ name, region, req.ExpireTime, signingTime,
+ )
+ if err != nil {
+ req.Error = err
+ req.SignedHeaderVals = nil
+ return
+ }
+
+ req.SignedHeaderVals = signedHeaders
+ req.LastSignedAt = curTimeFn()
+}
+
+const logSignInfoMsg = `DEBUG: Request Signature:
+---[ CANONICAL STRING ]-----------------------------
+%s
+---[ STRING TO SIGN ]--------------------------------
+%s%s
+-----------------------------------------------------`
+const logSignedURLMsg = `
+---[ SIGNED URL ]------------------------------------
+%s`
+
+func (v4 *Signer) logSigningInfo(ctx *signingCtx) {
+ signedURLMsg := ""
+ if ctx.isPresign {
+ signedURLMsg = fmt.Sprintf(logSignedURLMsg, ctx.Request.URL.String())
+ }
+ msg := fmt.Sprintf(logSignInfoMsg, ctx.canonicalString, ctx.stringToSign, signedURLMsg)
+ v4.Logger.Log(msg)
+}
+
+func (ctx *signingCtx) build(disableHeaderHoisting bool) {
+ ctx.buildTime() // no depends
+ ctx.buildCredentialString() // no depends
+
+ unsignedHeaders := ctx.Request.Header
+ if ctx.isPresign {
+ if !disableHeaderHoisting {
+ urlValues := url.Values{}
+ urlValues, unsignedHeaders = buildQuery(allowedQueryHoisting, unsignedHeaders) // no depends
+ for k := range urlValues {
+ ctx.Query[k] = urlValues[k]
+ }
+ }
+ }
+
+ ctx.buildBodyDigest()
+ ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders)
+ ctx.buildCanonicalString() // depends on canon headers / signed headers
+ ctx.buildStringToSign() // depends on canon string
+ ctx.buildSignature() // depends on string to sign
+
+ if ctx.isPresign {
+ ctx.Request.URL.RawQuery += "&X-Amz-Signature=" + ctx.signature
+ } else {
+ parts := []string{
+ authHeaderPrefix + " Credential=" + ctx.credValues.AccessKeyID + "/" + ctx.credentialString,
+ "SignedHeaders=" + ctx.signedHeaders,
+ "Signature=" + ctx.signature,
+ }
+ ctx.Request.Header.Set("Authorization", strings.Join(parts, ", "))
+ }
+}
+
+func (ctx *signingCtx) buildTime() {
+ ctx.formattedTime = ctx.Time.UTC().Format(timeFormat)
+ ctx.formattedShortTime = ctx.Time.UTC().Format(shortTimeFormat)
+
+ if ctx.isPresign {
+ duration := int64(ctx.ExpireTime / time.Second)
+ ctx.Query.Set("X-Amz-Date", ctx.formattedTime)
+ ctx.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10))
+ } else {
+ ctx.Request.Header.Set("X-Amz-Date", ctx.formattedTime)
+ }
+}
+
+func (ctx *signingCtx) buildCredentialString() {
+ ctx.credentialString = strings.Join([]string{
+ ctx.formattedShortTime,
+ ctx.Region,
+ ctx.ServiceName,
+ "aws4_request",
+ }, "/")
+
+ if ctx.isPresign {
+ ctx.Query.Set("X-Amz-Credential", ctx.credValues.AccessKeyID+"/"+ctx.credentialString)
+ }
+}
+
+func buildQuery(r rule, header http.Header) (url.Values, http.Header) {
+ query := url.Values{}
+ unsignedHeaders := http.Header{}
+ for k, h := range header {
+ if r.IsValid(k) {
+ query[k] = h
+ } else {
+ unsignedHeaders[k] = h
+ }
+ }
+
+ return query, unsignedHeaders
+}
+func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) {
+ var headers []string
+ headers = append(headers, "host")
+ for k, v := range header {
+ canonicalKey := http.CanonicalHeaderKey(k)
+ if !r.IsValid(canonicalKey) {
+ continue // ignored header
+ }
+ if ctx.SignedHeaderVals == nil {
+ ctx.SignedHeaderVals = make(http.Header)
+ }
+
+ lowerCaseKey := strings.ToLower(k)
+ if _, ok := ctx.SignedHeaderVals[lowerCaseKey]; ok {
+ // include additional values
+ ctx.SignedHeaderVals[lowerCaseKey] = append(ctx.SignedHeaderVals[lowerCaseKey], v...)
+ continue
+ }
+
+ headers = append(headers, lowerCaseKey)
+ ctx.SignedHeaderVals[lowerCaseKey] = v
+ }
+ sort.Strings(headers)
+
+ ctx.signedHeaders = strings.Join(headers, ";")
+
+ if ctx.isPresign {
+ ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders)
+ }
+
+ headerValues := make([]string, len(headers))
+ for i, k := range headers {
+ if k == "host" {
+ headerValues[i] = "host:" + ctx.Request.URL.Host
+ } else {
+ headerValues[i] = k + ":" +
+ strings.Join(ctx.SignedHeaderVals[k], ",")
+ }
+ }
+
+ ctx.canonicalHeaders = strings.Join(stripExcessSpaces(headerValues), "\n")
+}
+
+func (ctx *signingCtx) buildCanonicalString() {
+ ctx.Request.URL.RawQuery = strings.Replace(ctx.Query.Encode(), "+", "%20", -1)
+
+ uri := getURIPath(ctx.Request.URL)
+
+ if !ctx.DisableURIPathEscaping {
+ uri = rest.EscapePath(uri, false)
+ }
+
+ ctx.canonicalString = strings.Join([]string{
+ ctx.Request.Method,
+ uri,
+ ctx.Request.URL.RawQuery,
+ ctx.canonicalHeaders + "\n",
+ ctx.signedHeaders,
+ ctx.bodyDigest,
+ }, "\n")
+}
+
+func (ctx *signingCtx) buildStringToSign() {
+ ctx.stringToSign = strings.Join([]string{
+ authHeaderPrefix,
+ ctx.formattedTime,
+ ctx.credentialString,
+ hex.EncodeToString(makeSha256([]byte(ctx.canonicalString))),
+ }, "\n")
+}
+
+func (ctx *signingCtx) buildSignature() {
+ secret := ctx.credValues.SecretAccessKey
+ date := makeHmac([]byte("AWS4"+secret), []byte(ctx.formattedShortTime))
+ region := makeHmac(date, []byte(ctx.Region))
+ service := makeHmac(region, []byte(ctx.ServiceName))
+ credentials := makeHmac(service, []byte("aws4_request"))
+ signature := makeHmac(credentials, []byte(ctx.stringToSign))
+ ctx.signature = hex.EncodeToString(signature)
+}
+
+func (ctx *signingCtx) buildBodyDigest() {
+ hash := ctx.Request.Header.Get("X-Amz-Content-Sha256")
+ if hash == "" {
+ if ctx.isPresign && ctx.ServiceName == "s3" {
+ hash = "UNSIGNED-PAYLOAD"
+ } else if ctx.Body == nil {
+ hash = emptyStringSHA256
+ } else {
+ hash = hex.EncodeToString(makeSha256Reader(ctx.Body))
+ }
+ if ctx.ServiceName == "s3" || ctx.ServiceName == "glacier" {
+ ctx.Request.Header.Set("X-Amz-Content-Sha256", hash)
+ }
+ }
+ ctx.bodyDigest = hash
+}
+
+// isRequestSigned returns if the request is currently signed or presigned
+func (ctx *signingCtx) isRequestSigned() bool {
+ if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" {
+ return true
+ }
+ if ctx.Request.Header.Get("Authorization") != "" {
+ return true
+ }
+
+ return false
+}
+
+// unsign removes signing flags for both signed and presigned requests.
+func (ctx *signingCtx) removePresign() {
+ ctx.Query.Del("X-Amz-Algorithm")
+ ctx.Query.Del("X-Amz-Signature")
+ ctx.Query.Del("X-Amz-Security-Token")
+ ctx.Query.Del("X-Amz-Date")
+ ctx.Query.Del("X-Amz-Expires")
+ ctx.Query.Del("X-Amz-Credential")
+ ctx.Query.Del("X-Amz-SignedHeaders")
+}
+
+func makeHmac(key []byte, data []byte) []byte {
+ hash := hmac.New(sha256.New, key)
+ hash.Write(data)
+ return hash.Sum(nil)
+}
+
+func makeSha256(data []byte) []byte {
+ hash := sha256.New()
+ hash.Write(data)
+ return hash.Sum(nil)
+}
+
+func makeSha256Reader(reader io.ReadSeeker) []byte {
+ hash := sha256.New()
+ start, _ := reader.Seek(0, 1)
+ defer reader.Seek(start, 0)
+
+ io.Copy(hash, reader)
+ return hash.Sum(nil)
+}
+
+const doubleSpaces = " "
+
+var doubleSpaceBytes = []byte(doubleSpaces)
+
+func stripExcessSpaces(headerVals []string) []string {
+ vals := make([]string, len(headerVals))
+ for i, str := range headerVals {
+ // Trim leading and trailing spaces
+ trimmed := strings.TrimSpace(str)
+
+ idx := strings.Index(trimmed, doubleSpaces)
+ var buf []byte
+ for idx > -1 {
+ // Multiple adjacent spaces found
+ if buf == nil {
+ // first time create the buffer
+ buf = []byte(trimmed)
+ }
+
+ stripToIdx := -1
+ for j := idx + 1; j < len(buf); j++ {
+ if buf[j] != ' ' {
+ buf = append(buf[:idx+1], buf[j:]...)
+ stripToIdx = j
+ break
+ }
+ }
+
+ if stripToIdx >= 0 {
+ idx = bytes.Index(buf[stripToIdx:], doubleSpaceBytes)
+ if idx >= 0 {
+ idx += stripToIdx
+ }
+ } else {
+ idx = -1
+ }
+ }
+
+ if buf != nil {
+ vals[i] = string(buf)
+ } else {
+ vals[i] = trimmed
+ }
+ }
+ return vals
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/types.go b/vendor/github.com/aws/aws-sdk-go/aws/types.go
new file mode 100644
index 0000000..fa014b4
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/types.go
@@ -0,0 +1,106 @@
+package aws
+
+import (
+ "io"
+ "sync"
+)
+
+// ReadSeekCloser wraps a io.Reader returning a ReaderSeekerCloser
+func ReadSeekCloser(r io.Reader) ReaderSeekerCloser {
+ return ReaderSeekerCloser{r}
+}
+
+// ReaderSeekerCloser represents a reader that can also delegate io.Seeker and
+// io.Closer interfaces to the underlying object if they are available.
+type ReaderSeekerCloser struct {
+ r io.Reader
+}
+
+// Read reads from the reader up to size of p. The number of bytes read, and
+// error if it occurred will be returned.
+//
+// If the reader is not an io.Reader zero bytes read, and nil error will be returned.
+//
+// Performs the same functionality as io.Reader Read
+func (r ReaderSeekerCloser) Read(p []byte) (int, error) {
+ switch t := r.r.(type) {
+ case io.Reader:
+ return t.Read(p)
+ }
+ return 0, nil
+}
+
+// Seek sets the offset for the next Read 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. Seek returns the new offset
+// and an error, if any.
+//
+// If the ReaderSeekerCloser is not an io.Seeker nothing will be done.
+func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) {
+ switch t := r.r.(type) {
+ case io.Seeker:
+ return t.Seek(offset, whence)
+ }
+ return int64(0), nil
+}
+
+// Close closes the ReaderSeekerCloser.
+//
+// If the ReaderSeekerCloser is not an io.Closer nothing will be done.
+func (r ReaderSeekerCloser) Close() error {
+ switch t := r.r.(type) {
+ case io.Closer:
+ return t.Close()
+ }
+ return nil
+}
+
+// A WriteAtBuffer provides a in memory buffer supporting the io.WriterAt interface
+// Can be used with the s3manager.Downloader to download content to a buffer
+// in memory. Safe to use concurrently.
+type WriteAtBuffer struct {
+ buf []byte
+ m sync.Mutex
+
+ // GrowthCoeff defines the growth rate of the internal buffer. By
+ // default, the growth rate is 1, where expanding the internal
+ // buffer will allocate only enough capacity to fit the new expected
+ // length.
+ GrowthCoeff float64
+}
+
+// NewWriteAtBuffer creates a WriteAtBuffer with an internal buffer
+// provided by buf.
+func NewWriteAtBuffer(buf []byte) *WriteAtBuffer {
+ return &WriteAtBuffer{buf: buf}
+}
+
+// WriteAt writes a slice of bytes to a buffer starting at the position provided
+// The number of bytes written will be returned, or error. Can overwrite previous
+// written slices if the write ats overlap.
+func (b *WriteAtBuffer) WriteAt(p []byte, pos int64) (n int, err error) {
+ pLen := len(p)
+ expLen := pos + int64(pLen)
+ b.m.Lock()
+ defer b.m.Unlock()
+ if int64(len(b.buf)) < expLen {
+ if int64(cap(b.buf)) < expLen {
+ if b.GrowthCoeff < 1 {
+ b.GrowthCoeff = 1
+ }
+ newBuf := make([]byte, expLen, int64(b.GrowthCoeff*float64(expLen)))
+ copy(newBuf, b.buf)
+ b.buf = newBuf
+ }
+ b.buf = b.buf[:expLen]
+ }
+ copy(b.buf[pos:], p)
+ return pLen, nil
+}
+
+// Bytes returns a slice of bytes written to the buffer.
+func (b *WriteAtBuffer) Bytes() []byte {
+ b.m.Lock()
+ defer b.m.Unlock()
+ return b.buf[:len(b.buf):len(b.buf)]
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go
new file mode 100644
index 0000000..b01cd70
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/aws/version.go
@@ -0,0 +1,8 @@
+// Package aws provides core functionality for making requests to AWS services.
+package aws
+
+// SDKName is the name of this AWS SDK
+const SDKName = "aws-sdk-go"
+
+// SDKVersion is the version of this SDK
+const SDKVersion = "1.4.22"
diff --git a/vendor/github.com/aws/aws-sdk-go/private/README.md b/vendor/github.com/aws/aws-sdk-go/private/README.md
new file mode 100644
index 0000000..5bdb4c5
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/README.md
@@ -0,0 +1,4 @@
+## AWS SDK for Go Private packages ##
+`private` is a collection of packages used internally by the SDK, and is subject to have breaking changes. This package is not `internal` so that if you really need to use its functionality, and understand breaking changes will be made, you are able to.
+
+These packages will be refactored in the future so that the API generator and model parsers are exposed cleanly on their own. Making it easier for you to generate your own code based on the API models.
diff --git a/vendor/github.com/aws/aws-sdk-go/private/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go/private/endpoints/endpoints.go
new file mode 100644
index 0000000..19d9756
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/endpoints/endpoints.go
@@ -0,0 +1,70 @@
+// Package endpoints validates regional endpoints for services.
+package endpoints
+
+//go:generate go run -tags codegen ../model/cli/gen-endpoints/main.go endpoints.json endpoints_map.go
+//go:generate gofmt -s -w endpoints_map.go
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+)
+
+// NormalizeEndpoint takes and endpoint and service API information to return a
+// normalized endpoint and signing region. If the endpoint is not an empty string
+// the service name and region will be used to look up the service's API endpoint.
+// If the endpoint is provided the scheme will be added if it is not present.
+func NormalizeEndpoint(endpoint, serviceName, region string, disableSSL, useDualStack bool) (normEndpoint, signingRegion string) {
+ if endpoint == "" {
+ return EndpointForRegion(serviceName, region, disableSSL, useDualStack)
+ }
+
+ return AddScheme(endpoint, disableSSL), ""
+}
+
+// EndpointForRegion returns an endpoint and its signing region for a service and region.
+// if the service and region pair are not found endpoint and signingRegion will be empty.
+func EndpointForRegion(svcName, region string, disableSSL, useDualStack bool) (endpoint, signingRegion string) {
+ dualStackField := ""
+ if useDualStack {
+ dualStackField = "/dualstack"
+ }
+
+ derivedKeys := []string{
+ region + "/" + svcName + dualStackField,
+ region + "/*" + dualStackField,
+ "*/" + svcName + dualStackField,
+ "*/*" + dualStackField,
+ }
+
+ for _, key := range derivedKeys {
+ if val, ok := endpointsMap.Endpoints[key]; ok {
+ ep := val.Endpoint
+ ep = strings.Replace(ep, "{region}", region, -1)
+ ep = strings.Replace(ep, "{service}", svcName, -1)
+
+ endpoint = ep
+ signingRegion = val.SigningRegion
+ break
+ }
+ }
+
+ return AddScheme(endpoint, disableSSL), signingRegion
+}
+
+// Regular expression to determine if the endpoint string is prefixed with a scheme.
+var schemeRE = regexp.MustCompile("^([^:]+)://")
+
+// AddScheme adds the HTTP or HTTPS schemes to a endpoint URL if there is no
+// scheme. If disableSSL is true HTTP will be added instead of the default HTTPS.
+func AddScheme(endpoint string, disableSSL bool) string {
+ if endpoint != "" && !schemeRE.MatchString(endpoint) {
+ scheme := "https"
+ if disableSSL {
+ scheme = "http"
+ }
+ endpoint = fmt.Sprintf("%s://%s", scheme, endpoint)
+ }
+
+ return endpoint
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/endpoints/endpoints_map.go b/vendor/github.com/aws/aws-sdk-go/private/endpoints/endpoints_map.go
new file mode 100644
index 0000000..e79e678
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/endpoints/endpoints_map.go
@@ -0,0 +1,95 @@
+package endpoints
+
+// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
+
+type endpointStruct struct {
+ Version int
+ Endpoints map[string]endpointEntry
+}
+
+type endpointEntry struct {
+ Endpoint string
+ SigningRegion string
+}
+
+var endpointsMap = endpointStruct{
+ Version: 2,
+ Endpoints: map[string]endpointEntry{
+ "*/*": {
+ Endpoint: "{service}.{region}.amazonaws.com",
+ },
+ "*/budgets": {
+ Endpoint: "budgets.amazonaws.com",
+ SigningRegion: "us-east-1",
+ },
+ "*/cloudfront": {
+ Endpoint: "cloudfront.amazonaws.com",
+ SigningRegion: "us-east-1",
+ },
+ "*/cloudsearchdomain": {
+ Endpoint: "",
+ SigningRegion: "us-east-1",
+ },
+ "*/data.iot": {
+ Endpoint: "",
+ SigningRegion: "us-east-1",
+ },
+ "*/ec2metadata": {
+ Endpoint: "http://169.254.169.254/latest",
+ },
+ "*/iam": {
+ Endpoint: "iam.amazonaws.com",
+ SigningRegion: "us-east-1",
+ },
+ "*/importexport": {
+ Endpoint: "importexport.amazonaws.com",
+ SigningRegion: "us-east-1",
+ },
+ "*/route53": {
+ Endpoint: "route53.amazonaws.com",
+ SigningRegion: "us-east-1",
+ },
+ "*/s3": {
+ Endpoint: "s3-{region}.amazonaws.com",
+ },
+ "*/s3/dualstack": {
+ Endpoint: "s3.dualstack.{region}.amazonaws.com",
+ },
+ "*/sts": {
+ Endpoint: "sts.amazonaws.com",
+ SigningRegion: "us-east-1",
+ },
+ "*/waf": {
+ Endpoint: "waf.amazonaws.com",
+ SigningRegion: "us-east-1",
+ },
+ "cn-north-1/*": {
+ Endpoint: "{service}.{region}.amazonaws.com.cn",
+ },
+ "cn-north-1/ec2metadata": {
+ Endpoint: "http://169.254.169.254/latest",
+ },
+ "eu-central-1/s3": {
+ Endpoint: "{service}.{region}.amazonaws.com",
+ },
+ "us-east-1/s3": {
+ Endpoint: "s3.amazonaws.com",
+ },
+ "us-east-1/sdb": {
+ Endpoint: "sdb.amazonaws.com",
+ SigningRegion: "us-east-1",
+ },
+ "us-gov-west-1/ec2metadata": {
+ Endpoint: "http://169.254.169.254/latest",
+ },
+ "us-gov-west-1/iam": {
+ Endpoint: "iam.us-gov.amazonaws.com",
+ },
+ "us-gov-west-1/s3": {
+ Endpoint: "s3-{region}.amazonaws.com",
+ },
+ "us-gov-west-1/sts": {
+ Endpoint: "sts.us-gov-west-1.amazonaws.com",
+ },
+ },
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go
new file mode 100644
index 0000000..53831df
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go
@@ -0,0 +1,75 @@
+package protocol
+
+import (
+ "crypto/rand"
+ "fmt"
+ "reflect"
+)
+
+// RandReader is the random reader the protocol package will use to read
+// random bytes from. This is exported for testing, and should not be used.
+var RandReader = rand.Reader
+
+const idempotencyTokenFillTag = `idempotencyToken`
+
+// CanSetIdempotencyToken returns true if the struct field should be
+// automatically populated with a Idempotency token.
+//
+// Only *string and string type fields that are tagged with idempotencyToken
+// which are not already set can be auto filled.
+func CanSetIdempotencyToken(v reflect.Value, f reflect.StructField) bool {
+ switch u := v.Interface().(type) {
+ // To auto fill an Idempotency token the field must be a string,
+ // tagged for auto fill, and have a zero value.
+ case *string:
+ return u == nil && len(f.Tag.Get(idempotencyTokenFillTag)) != 0
+ case string:
+ return len(u) == 0 && len(f.Tag.Get(idempotencyTokenFillTag)) != 0
+ }
+
+ return false
+}
+
+// GetIdempotencyToken returns a randomly generated idempotency token.
+func GetIdempotencyToken() string {
+ b := make([]byte, 16)
+ RandReader.Read(b)
+
+ return UUIDVersion4(b)
+}
+
+// SetIdempotencyToken will set the value provided with a Idempotency Token.
+// Given that the value can be set. Will panic if value is not setable.
+func SetIdempotencyToken(v reflect.Value) {
+ if v.Kind() == reflect.Ptr {
+ if v.IsNil() && v.CanSet() {
+ v.Set(reflect.New(v.Type().Elem()))
+ }
+ v = v.Elem()
+ }
+ v = reflect.Indirect(v)
+
+ if !v.CanSet() {
+ panic(fmt.Sprintf("unable to set idempotnecy token %v", v))
+ }
+
+ b := make([]byte, 16)
+ _, err := rand.Read(b)
+ if err != nil {
+ // TODO handle error
+ return
+ }
+
+ v.Set(reflect.ValueOf(UUIDVersion4(b)))
+}
+
+// UUIDVersion4 returns a Version 4 random UUID from the byte slice provided
+func UUIDVersion4(u []byte) string {
+ // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
+ // 13th character is "4"
+ u[6] = (u[6] | 0x40) & 0x4F
+ // 17th character is "8", "9", "a", or "b"
+ u[8] = (u[8] | 0x80) & 0xBF
+
+ return fmt.Sprintf(`%X-%X-%X-%X-%X`, u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go
new file mode 100644
index 0000000..4504efe
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go
@@ -0,0 +1,254 @@
+// Package jsonutil provides JSON serialization of AWS requests and responses.
+package jsonutil
+
+import (
+ "bytes"
+ "encoding/base64"
+ "fmt"
+ "reflect"
+ "sort"
+ "strconv"
+ "time"
+
+ "github.com/aws/aws-sdk-go/private/protocol"
+)
+
+var timeType = reflect.ValueOf(time.Time{}).Type()
+var byteSliceType = reflect.ValueOf([]byte{}).Type()
+
+// BuildJSON builds a JSON string for a given object v.
+func BuildJSON(v interface{}) ([]byte, error) {
+ var buf bytes.Buffer
+
+ err := buildAny(reflect.ValueOf(v), &buf, "")
+ return buf.Bytes(), err
+}
+
+func buildAny(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error {
+ value = reflect.Indirect(value)
+ if !value.IsValid() {
+ return nil
+ }
+
+ vtype := value.Type()
+
+ t := tag.Get("type")
+ if t == "" {
+ switch vtype.Kind() {
+ case reflect.Struct:
+ // also it can't be a time object
+ if value.Type() != timeType {
+ t = "structure"
+ }
+ case reflect.Slice:
+ // also it can't be a byte slice
+ if _, ok := value.Interface().([]byte); !ok {
+ t = "list"
+ }
+ case reflect.Map:
+ t = "map"
+ }
+ }
+
+ switch t {
+ case "structure":
+ if field, ok := vtype.FieldByName("_"); ok {
+ tag = field.Tag
+ }
+ return buildStruct(value, buf, tag)
+ case "list":
+ return buildList(value, buf, tag)
+ case "map":
+ return buildMap(value, buf, tag)
+ default:
+ return buildScalar(value, buf, tag)
+ }
+}
+
+func buildStruct(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error {
+ if !value.IsValid() {
+ return nil
+ }
+
+ // unwrap payloads
+ if payload := tag.Get("payload"); payload != "" {
+ field, _ := value.Type().FieldByName(payload)
+ tag = field.Tag
+ value = elemOf(value.FieldByName(payload))
+
+ if !value.IsValid() {
+ return nil
+ }
+ }
+
+ buf.WriteByte('{')
+
+ t := value.Type()
+ first := true
+ for i := 0; i < t.NumField(); i++ {
+ member := value.Field(i)
+ field := t.Field(i)
+
+ if field.PkgPath != "" {
+ continue // ignore unexported fields
+ }
+ if field.Tag.Get("json") == "-" {
+ continue
+ }
+ if field.Tag.Get("location") != "" {
+ continue // ignore non-body elements
+ }
+
+ if protocol.CanSetIdempotencyToken(member, field) {
+ token := protocol.GetIdempotencyToken()
+ member = reflect.ValueOf(&token)
+ }
+
+ if (member.Kind() == reflect.Ptr || member.Kind() == reflect.Slice || member.Kind() == reflect.Map) && member.IsNil() {
+ continue // ignore unset fields
+ }
+
+ if first {
+ first = false
+ } else {
+ buf.WriteByte(',')
+ }
+
+ // figure out what this field is called
+ name := field.Name
+ if locName := field.Tag.Get("locationName"); locName != "" {
+ name = locName
+ }
+
+ writeString(name, buf)
+ buf.WriteString(`:`)
+
+ err := buildAny(member, buf, field.Tag)
+ if err != nil {
+ return err
+ }
+
+ }
+
+ buf.WriteString("}")
+
+ return nil
+}
+
+func buildList(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error {
+ buf.WriteString("[")
+
+ for i := 0; i < value.Len(); i++ {
+ buildAny(value.Index(i), buf, "")
+
+ if i < value.Len()-1 {
+ buf.WriteString(",")
+ }
+ }
+
+ buf.WriteString("]")
+
+ return nil
+}
+
+type sortedValues []reflect.Value
+
+func (sv sortedValues) Len() int { return len(sv) }
+func (sv sortedValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
+func (sv sortedValues) Less(i, j int) bool { return sv[i].String() < sv[j].String() }
+
+func buildMap(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error {
+ buf.WriteString("{")
+
+ sv := sortedValues(value.MapKeys())
+ sort.Sort(sv)
+
+ for i, k := range sv {
+ if i > 0 {
+ buf.WriteByte(',')
+ }
+
+ writeString(k.String(), buf)
+ buf.WriteString(`:`)
+
+ buildAny(value.MapIndex(k), buf, "")
+ }
+
+ buf.WriteString("}")
+
+ return nil
+}
+
+func buildScalar(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error {
+ switch value.Kind() {
+ case reflect.String:
+ writeString(value.String(), buf)
+ case reflect.Bool:
+ buf.WriteString(strconv.FormatBool(value.Bool()))
+ case reflect.Int64:
+ buf.WriteString(strconv.FormatInt(value.Int(), 10))
+ case reflect.Float64:
+ buf.WriteString(strconv.FormatFloat(value.Float(), 'f', -1, 64))
+ default:
+ switch value.Type() {
+ case timeType:
+ converted := value.Interface().(time.Time)
+ buf.WriteString(strconv.FormatInt(converted.UTC().Unix(), 10))
+ case byteSliceType:
+ if !value.IsNil() {
+ converted := value.Interface().([]byte)
+ buf.WriteByte('"')
+ if len(converted) < 1024 {
+ // for small buffers, using Encode directly is much faster.
+ dst := make([]byte, base64.StdEncoding.EncodedLen(len(converted)))
+ base64.StdEncoding.Encode(dst, converted)
+ buf.Write(dst)
+ } else {
+ // for large buffers, avoid unnecessary extra temporary
+ // buffer space.
+ enc := base64.NewEncoder(base64.StdEncoding, buf)
+ enc.Write(converted)
+ enc.Close()
+ }
+ buf.WriteByte('"')
+ }
+ default:
+ return fmt.Errorf("unsupported JSON value %v (%s)", value.Interface(), value.Type())
+ }
+ }
+ return nil
+}
+
+func writeString(s string, buf *bytes.Buffer) {
+ buf.WriteByte('"')
+ for _, r := range s {
+ if r == '"' {
+ buf.WriteString(`\"`)
+ } else if r == '\\' {
+ buf.WriteString(`\\`)
+ } else if r == '\b' {
+ buf.WriteString(`\b`)
+ } else if r == '\f' {
+ buf.WriteString(`\f`)
+ } else if r == '\r' {
+ buf.WriteString(`\r`)
+ } else if r == '\t' {
+ buf.WriteString(`\t`)
+ } else if r == '\n' {
+ buf.WriteString(`\n`)
+ } else if r < 32 {
+ fmt.Fprintf(buf, "\\u%0.4x", r)
+ } else {
+ buf.WriteRune(r)
+ }
+ }
+ buf.WriteByte('"')
+}
+
+// Returns the reflection element of a value, if it is a pointer.
+func elemOf(value reflect.Value) reflect.Value {
+ for value.Kind() == reflect.Ptr {
+ value = value.Elem()
+ }
+ return value
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go
new file mode 100644
index 0000000..fea5356
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go
@@ -0,0 +1,213 @@
+package jsonutil
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "reflect"
+ "time"
+)
+
+// UnmarshalJSON reads a stream and unmarshals the results in object v.
+func UnmarshalJSON(v interface{}, stream io.Reader) error {
+ var out interface{}
+
+ b, err := ioutil.ReadAll(stream)
+ if err != nil {
+ return err
+ }
+
+ if len(b) == 0 {
+ return nil
+ }
+
+ if err := json.Unmarshal(b, &out); err != nil {
+ return err
+ }
+
+ return unmarshalAny(reflect.ValueOf(v), out, "")
+}
+
+func unmarshalAny(value reflect.Value, data interface{}, tag reflect.StructTag) error {
+ vtype := value.Type()
+ if vtype.Kind() == reflect.Ptr {
+ vtype = vtype.Elem() // check kind of actual element type
+ }
+
+ t := tag.Get("type")
+ if t == "" {
+ switch vtype.Kind() {
+ case reflect.Struct:
+ // also it can't be a time object
+ if _, ok := value.Interface().(*time.Time); !ok {
+ t = "structure"
+ }
+ case reflect.Slice:
+ // also it can't be a byte slice
+ if _, ok := value.Interface().([]byte); !ok {
+ t = "list"
+ }
+ case reflect.Map:
+ t = "map"
+ }
+ }
+
+ switch t {
+ case "structure":
+ if field, ok := vtype.FieldByName("_"); ok {
+ tag = field.Tag
+ }
+ return unmarshalStruct(value, data, tag)
+ case "list":
+ return unmarshalList(value, data, tag)
+ case "map":
+ return unmarshalMap(value, data, tag)
+ default:
+ return unmarshalScalar(value, data, tag)
+ }
+}
+
+func unmarshalStruct(value reflect.Value, data interface{}, tag reflect.StructTag) error {
+ if data == nil {
+ return nil
+ }
+ mapData, ok := data.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("JSON value is not a structure (%#v)", data)
+ }
+
+ t := value.Type()
+ if value.Kind() == reflect.Ptr {
+ if value.IsNil() { // create the structure if it's nil
+ s := reflect.New(value.Type().Elem())
+ value.Set(s)
+ value = s
+ }
+
+ value = value.Elem()
+ t = t.Elem()
+ }
+
+ // unwrap any payloads
+ if payload := tag.Get("payload"); payload != "" {
+ field, _ := t.FieldByName(payload)
+ return unmarshalAny(value.FieldByName(payload), data, field.Tag)
+ }
+
+ for i := 0; i < t.NumField(); i++ {
+ field := t.Field(i)
+ if field.PkgPath != "" {
+ continue // ignore unexported fields
+ }
+
+ // figure out what this field is called
+ name := field.Name
+ if locName := field.Tag.Get("locationName"); locName != "" {
+ name = locName
+ }
+
+ member := value.FieldByIndex(field.Index)
+ err := unmarshalAny(member, mapData[name], field.Tag)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func unmarshalList(value reflect.Value, data interface{}, tag reflect.StructTag) error {
+ if data == nil {
+ return nil
+ }
+ listData, ok := data.([]interface{})
+ if !ok {
+ return fmt.Errorf("JSON value is not a list (%#v)", data)
+ }
+
+ if value.IsNil() {
+ l := len(listData)
+ value.Set(reflect.MakeSlice(value.Type(), l, l))
+ }
+
+ for i, c := range listData {
+ err := unmarshalAny(value.Index(i), c, "")
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func unmarshalMap(value reflect.Value, data interface{}, tag reflect.StructTag) error {
+ if data == nil {
+ return nil
+ }
+ mapData, ok := data.(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("JSON value is not a map (%#v)", data)
+ }
+
+ if value.IsNil() {
+ value.Set(reflect.MakeMap(value.Type()))
+ }
+
+ for k, v := range mapData {
+ kvalue := reflect.ValueOf(k)
+ vvalue := reflect.New(value.Type().Elem()).Elem()
+
+ unmarshalAny(vvalue, v, "")
+ value.SetMapIndex(kvalue, vvalue)
+ }
+
+ return nil
+}
+
+func unmarshalScalar(value reflect.Value, data interface{}, tag reflect.StructTag) error {
+ errf := func() error {
+ return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type())
+ }
+
+ switch d := data.(type) {
+ case nil:
+ return nil // nothing to do here
+ case string:
+ switch value.Interface().(type) {
+ case *string:
+ value.Set(reflect.ValueOf(&d))
+ case []byte:
+ b, err := base64.StdEncoding.DecodeString(d)
+ if err != nil {
+ return err
+ }
+ value.Set(reflect.ValueOf(b))
+ default:
+ return errf()
+ }
+ case float64:
+ switch value.Interface().(type) {
+ case *int64:
+ di := int64(d)
+ value.Set(reflect.ValueOf(&di))
+ case *float64:
+ value.Set(reflect.ValueOf(&d))
+ case *time.Time:
+ t := time.Unix(int64(d), 0).UTC()
+ value.Set(reflect.ValueOf(&t))
+ default:
+ return errf()
+ }
+ case bool:
+ switch value.Interface().(type) {
+ case *bool:
+ value.Set(reflect.ValueOf(&d))
+ default:
+ return errf()
+ }
+ default:
+ return fmt.Errorf("unsupported JSON value (%v)", data)
+ }
+ return nil
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go
new file mode 100644
index 0000000..56af4dc
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go
@@ -0,0 +1,111 @@
+// Package jsonrpc provides JSON RPC utilities for serialization of AWS
+// requests and responses.
+package jsonrpc
+
+//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/json.json build_test.go
+//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/json.json unmarshal_test.go
+
+import (
+ "encoding/json"
+ "io/ioutil"
+ "strings"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/request"
+ "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
+ "github.com/aws/aws-sdk-go/private/protocol/rest"
+)
+
+var emptyJSON = []byte("{}")
+
+// BuildHandler is a named request handler for building jsonrpc protocol requests
+var BuildHandler = request.NamedHandler{Name: "awssdk.jsonrpc.Build", Fn: Build}
+
+// UnmarshalHandler is a named request handler for unmarshaling jsonrpc protocol requests
+var UnmarshalHandler = request.NamedHandler{Name: "awssdk.jsonrpc.Unmarshal", Fn: Unmarshal}
+
+// UnmarshalMetaHandler is a named request handler for unmarshaling jsonrpc protocol request metadata
+var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.jsonrpc.UnmarshalMeta", Fn: UnmarshalMeta}
+
+// UnmarshalErrorHandler is a named request handler for unmarshaling jsonrpc protocol request errors
+var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.jsonrpc.UnmarshalError", Fn: UnmarshalError}
+
+// Build builds a JSON payload for a JSON RPC request.
+func Build(req *request.Request) {
+ var buf []byte
+ var err error
+ if req.ParamsFilled() {
+ buf, err = jsonutil.BuildJSON(req.Params)
+ if err != nil {
+ req.Error = awserr.New("SerializationError", "failed encoding JSON RPC request", err)
+ return
+ }
+ } else {
+ buf = emptyJSON
+ }
+
+ if req.ClientInfo.TargetPrefix != "" || string(buf) != "{}" {
+ req.SetBufferBody(buf)
+ }
+
+ if req.ClientInfo.TargetPrefix != "" {
+ target := req.ClientInfo.TargetPrefix + "." + req.Operation.Name
+ req.HTTPRequest.Header.Add("X-Amz-Target", target)
+ }
+ if req.ClientInfo.JSONVersion != "" {
+ jsonVersion := req.ClientInfo.JSONVersion
+ req.HTTPRequest.Header.Add("Content-Type", "application/x-amz-json-"+jsonVersion)
+ }
+}
+
+// Unmarshal unmarshals a response for a JSON RPC service.
+func Unmarshal(req *request.Request) {
+ defer req.HTTPResponse.Body.Close()
+ if req.DataFilled() {
+ err := jsonutil.UnmarshalJSON(req.Data, req.HTTPResponse.Body)
+ if err != nil {
+ req.Error = awserr.New("SerializationError", "failed decoding JSON RPC response", err)
+ }
+ }
+ return
+}
+
+// UnmarshalMeta unmarshals headers from a response for a JSON RPC service.
+func UnmarshalMeta(req *request.Request) {
+ rest.UnmarshalMeta(req)
+}
+
+// UnmarshalError unmarshals an error response for a JSON RPC service.
+func UnmarshalError(req *request.Request) {
+ defer req.HTTPResponse.Body.Close()
+ bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body)
+ if err != nil {
+ req.Error = awserr.New("SerializationError", "failed reading JSON RPC error response", err)
+ return
+ }
+ if len(bodyBytes) == 0 {
+ req.Error = awserr.NewRequestFailure(
+ awserr.New("SerializationError", req.HTTPResponse.Status, nil),
+ req.HTTPResponse.StatusCode,
+ "",
+ )
+ return
+ }
+ var jsonErr jsonErrorResponse
+ if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil {
+ req.Error = awserr.New("SerializationError", "failed decoding JSON RPC error response", err)
+ return
+ }
+
+ codes := strings.SplitN(jsonErr.Code, "#", 2)
+ req.Error = awserr.NewRequestFailure(
+ awserr.New(codes[len(codes)-1], jsonErr.Message, nil),
+ req.HTTPResponse.StatusCode,
+ req.RequestID,
+ )
+}
+
+type jsonErrorResponse struct {
+ Code string `json:"__type"`
+ Message string `json:"message"`
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go
new file mode 100644
index 0000000..18169f0
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go
@@ -0,0 +1,36 @@
+// Package query provides serialization of AWS query requests, and responses.
+package query
+
+//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/query.json build_test.go
+
+import (
+ "net/url"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/request"
+ "github.com/aws/aws-sdk-go/private/protocol/query/queryutil"
+)
+
+// BuildHandler is a named request handler for building query protocol requests
+var BuildHandler = request.NamedHandler{Name: "awssdk.query.Build", Fn: Build}
+
+// Build builds a request for an AWS Query service.
+func Build(r *request.Request) {
+ body := url.Values{
+ "Action": {r.Operation.Name},
+ "Version": {r.ClientInfo.APIVersion},
+ }
+ if err := queryutil.Parse(body, r.Params, false); err != nil {
+ r.Error = awserr.New("SerializationError", "failed encoding Query request", err)
+ return
+ }
+
+ if r.ExpireTime == 0 {
+ r.HTTPRequest.Method = "POST"
+ r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
+ r.SetBufferBody([]byte(body.Encode()))
+ } else { // This is a pre-signed request
+ r.HTTPRequest.Method = "GET"
+ r.HTTPRequest.URL.RawQuery = body.Encode()
+ }
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go
new file mode 100644
index 0000000..60ea0bd
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go
@@ -0,0 +1,230 @@
+package queryutil
+
+import (
+ "encoding/base64"
+ "fmt"
+ "net/url"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go/private/protocol"
+)
+
+// Parse parses an object i and fills a url.Values object. The isEC2 flag
+// indicates if this is the EC2 Query sub-protocol.
+func Parse(body url.Values, i interface{}, isEC2 bool) error {
+ q := queryParser{isEC2: isEC2}
+ return q.parseValue(body, reflect.ValueOf(i), "", "")
+}
+
+func elemOf(value reflect.Value) reflect.Value {
+ for value.Kind() == reflect.Ptr {
+ value = value.Elem()
+ }
+ return value
+}
+
+type queryParser struct {
+ isEC2 bool
+}
+
+func (q *queryParser) parseValue(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error {
+ value = elemOf(value)
+
+ // no need to handle zero values
+ if !value.IsValid() {
+ return nil
+ }
+
+ t := tag.Get("type")
+ if t == "" {
+ switch value.Kind() {
+ case reflect.Struct:
+ t = "structure"
+ case reflect.Slice:
+ t = "list"
+ case reflect.Map:
+ t = "map"
+ }
+ }
+
+ switch t {
+ case "structure":
+ return q.parseStruct(v, value, prefix)
+ case "list":
+ return q.parseList(v, value, prefix, tag)
+ case "map":
+ return q.parseMap(v, value, prefix, tag)
+ default:
+ return q.parseScalar(v, value, prefix, tag)
+ }
+}
+
+func (q *queryParser) parseStruct(v url.Values, value reflect.Value, prefix string) error {
+ if !value.IsValid() {
+ return nil
+ }
+
+ t := value.Type()
+ for i := 0; i < value.NumField(); i++ {
+ elemValue := elemOf(value.Field(i))
+ field := t.Field(i)
+
+ if field.PkgPath != "" {
+ continue // ignore unexported fields
+ }
+
+ if protocol.CanSetIdempotencyToken(value.Field(i), field) {
+ token := protocol.GetIdempotencyToken()
+ elemValue = reflect.ValueOf(token)
+ }
+
+ var name string
+ if q.isEC2 {
+ name = field.Tag.Get("queryName")
+ }
+ if name == "" {
+ if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" {
+ name = field.Tag.Get("locationNameList")
+ } else if locName := field.Tag.Get("locationName"); locName != "" {
+ name = locName
+ }
+ if name != "" && q.isEC2 {
+ name = strings.ToUpper(name[0:1]) + name[1:]
+ }
+ }
+ if name == "" {
+ name = field.Name
+ }
+
+ if prefix != "" {
+ name = prefix + "." + name
+ }
+
+ if err := q.parseValue(v, elemValue, name, field.Tag); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error {
+ // If it's empty, generate an empty value
+ if !value.IsNil() && value.Len() == 0 {
+ v.Set(prefix, "")
+ return nil
+ }
+
+ // check for unflattened list member
+ if !q.isEC2 && tag.Get("flattened") == "" {
+ prefix += ".member"
+ }
+
+ for i := 0; i < value.Len(); i++ {
+ slicePrefix := prefix
+ if slicePrefix == "" {
+ slicePrefix = strconv.Itoa(i + 1)
+ } else {
+ slicePrefix = slicePrefix + "." + strconv.Itoa(i+1)
+ }
+ if err := q.parseValue(v, value.Index(i), slicePrefix, ""); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (q *queryParser) parseMap(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error {
+ // If it's empty, generate an empty value
+ if !value.IsNil() && value.Len() == 0 {
+ v.Set(prefix, "")
+ return nil
+ }
+
+ // check for unflattened list member
+ if !q.isEC2 && tag.Get("flattened") == "" {
+ prefix += ".entry"
+ }
+
+ // sort keys for improved serialization consistency.
+ // this is not strictly necessary for protocol support.
+ mapKeyValues := value.MapKeys()
+ mapKeys := map[string]reflect.Value{}
+ mapKeyNames := make([]string, len(mapKeyValues))
+ for i, mapKey := range mapKeyValues {
+ name := mapKey.String()
+ mapKeys[name] = mapKey
+ mapKeyNames[i] = name
+ }
+ sort.Strings(mapKeyNames)
+
+ for i, mapKeyName := range mapKeyNames {
+ mapKey := mapKeys[mapKeyName]
+ mapValue := value.MapIndex(mapKey)
+
+ kname := tag.Get("locationNameKey")
+ if kname == "" {
+ kname = "key"
+ }
+ vname := tag.Get("locationNameValue")
+ if vname == "" {
+ vname = "value"
+ }
+
+ // serialize key
+ var keyName string
+ if prefix == "" {
+ keyName = strconv.Itoa(i+1) + "." + kname
+ } else {
+ keyName = prefix + "." + strconv.Itoa(i+1) + "." + kname
+ }
+
+ if err := q.parseValue(v, mapKey, keyName, ""); err != nil {
+ return err
+ }
+
+ // serialize value
+ var valueName string
+ if prefix == "" {
+ valueName = strconv.Itoa(i+1) + "." + vname
+ } else {
+ valueName = prefix + "." + strconv.Itoa(i+1) + "." + vname
+ }
+
+ if err := q.parseValue(v, mapValue, valueName, ""); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error {
+ switch value := r.Interface().(type) {
+ case string:
+ v.Set(name, value)
+ case []byte:
+ if !r.IsNil() {
+ v.Set(name, base64.StdEncoding.EncodeToString(value))
+ }
+ case bool:
+ v.Set(name, strconv.FormatBool(value))
+ case int64:
+ v.Set(name, strconv.FormatInt(value, 10))
+ case int:
+ v.Set(name, strconv.Itoa(value))
+ case float64:
+ v.Set(name, strconv.FormatFloat(value, 'f', -1, 64))
+ case float32:
+ v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32))
+ case time.Time:
+ const ISO8601UTC = "2006-01-02T15:04:05Z"
+ v.Set(name, value.UTC().Format(ISO8601UTC))
+ default:
+ return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name())
+ }
+ return nil
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go
new file mode 100644
index 0000000..e0f4d5a
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go
@@ -0,0 +1,35 @@
+package query
+
+//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/query.json unmarshal_test.go
+
+import (
+ "encoding/xml"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/request"
+ "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
+)
+
+// UnmarshalHandler is a named request handler for unmarshaling query protocol requests
+var UnmarshalHandler = request.NamedHandler{Name: "awssdk.query.Unmarshal", Fn: Unmarshal}
+
+// UnmarshalMetaHandler is a named request handler for unmarshaling query protocol request metadata
+var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.query.UnmarshalMeta", Fn: UnmarshalMeta}
+
+// Unmarshal unmarshals a response for an AWS Query service.
+func Unmarshal(r *request.Request) {
+ defer r.HTTPResponse.Body.Close()
+ if r.DataFilled() {
+ decoder := xml.NewDecoder(r.HTTPResponse.Body)
+ err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result")
+ if err != nil {
+ r.Error = awserr.New("SerializationError", "failed decoding Query response", err)
+ return
+ }
+ }
+}
+
+// UnmarshalMeta unmarshals header response values for an AWS Query service.
+func UnmarshalMeta(r *request.Request) {
+ r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid")
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go
new file mode 100644
index 0000000..f214296
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go
@@ -0,0 +1,66 @@
+package query
+
+import (
+ "encoding/xml"
+ "io/ioutil"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+type xmlErrorResponse struct {
+ XMLName xml.Name `xml:"ErrorResponse"`
+ Code string `xml:"Error>Code"`
+ Message string `xml:"Error>Message"`
+ RequestID string `xml:"RequestId"`
+}
+
+type xmlServiceUnavailableResponse struct {
+ XMLName xml.Name `xml:"ServiceUnavailableException"`
+}
+
+// UnmarshalErrorHandler is a name request handler to unmarshal request errors
+var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.query.UnmarshalError", Fn: UnmarshalError}
+
+// UnmarshalError unmarshals an error response for an AWS Query service.
+func UnmarshalError(r *request.Request) {
+ defer r.HTTPResponse.Body.Close()
+
+ bodyBytes, err := ioutil.ReadAll(r.HTTPResponse.Body)
+ if err != nil {
+ r.Error = awserr.New("SerializationError", "failed to read from query HTTP response body", err)
+ return
+ }
+
+ // First check for specific error
+ resp := xmlErrorResponse{}
+ decodeErr := xml.Unmarshal(bodyBytes, &resp)
+ if decodeErr == nil {
+ reqID := resp.RequestID
+ if reqID == "" {
+ reqID = r.RequestID
+ }
+ r.Error = awserr.NewRequestFailure(
+ awserr.New(resp.Code, resp.Message, nil),
+ r.HTTPResponse.StatusCode,
+ reqID,
+ )
+ return
+ }
+
+ // Check for unhandled error
+ servUnavailResp := xmlServiceUnavailableResponse{}
+ unavailErr := xml.Unmarshal(bodyBytes, &servUnavailResp)
+ if unavailErr == nil {
+ r.Error = awserr.NewRequestFailure(
+ awserr.New("ServiceUnavailableException", "service is unavailable", nil),
+ r.HTTPResponse.StatusCode,
+ r.RequestID,
+ )
+ return
+ }
+
+ // Failed to retrieve any error message from the response body
+ r.Error = awserr.New("SerializationError",
+ "failed to decode query XML error response", decodeErr)
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go
new file mode 100644
index 0000000..5f41251
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go
@@ -0,0 +1,256 @@
+// Package rest provides RESTful serialization of AWS requests and responses.
+package rest
+
+import (
+ "bytes"
+ "encoding/base64"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "path"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+// RFC822 returns an RFC822 formatted timestamp for AWS protocols
+const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT"
+
+// Whether the byte value can be sent without escaping in AWS URLs
+var noEscape [256]bool
+
+var errValueNotSet = fmt.Errorf("value not set")
+
+func init() {
+ for i := 0; i < len(noEscape); i++ {
+ // AWS expects every character except these to be escaped
+ noEscape[i] = (i >= 'A' && i <= 'Z') ||
+ (i >= 'a' && i <= 'z') ||
+ (i >= '0' && i <= '9') ||
+ i == '-' ||
+ i == '.' ||
+ i == '_' ||
+ i == '~'
+ }
+}
+
+// BuildHandler is a named request handler for building rest protocol requests
+var BuildHandler = request.NamedHandler{Name: "awssdk.rest.Build", Fn: Build}
+
+// Build builds the REST component of a service request.
+func Build(r *request.Request) {
+ if r.ParamsFilled() {
+ v := reflect.ValueOf(r.Params).Elem()
+ buildLocationElements(r, v)
+ buildBody(r, v)
+ }
+}
+
+func buildLocationElements(r *request.Request, v reflect.Value) {
+ query := r.HTTPRequest.URL.Query()
+
+ for i := 0; i < v.NumField(); i++ {
+ m := v.Field(i)
+ if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) {
+ continue
+ }
+
+ if m.IsValid() {
+ field := v.Type().Field(i)
+ name := field.Tag.Get("locationName")
+ if name == "" {
+ name = field.Name
+ }
+ if m.Kind() == reflect.Ptr {
+ m = m.Elem()
+ }
+ if !m.IsValid() {
+ continue
+ }
+
+ var err error
+ switch field.Tag.Get("location") {
+ case "headers": // header maps
+ err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag.Get("locationName"))
+ case "header":
+ err = buildHeader(&r.HTTPRequest.Header, m, name)
+ case "uri":
+ err = buildURI(r.HTTPRequest.URL, m, name)
+ case "querystring":
+ err = buildQueryString(query, m, name)
+ }
+ r.Error = err
+ }
+ if r.Error != nil {
+ return
+ }
+ }
+
+ r.HTTPRequest.URL.RawQuery = query.Encode()
+ updatePath(r.HTTPRequest.URL, r.HTTPRequest.URL.Path)
+}
+
+func buildBody(r *request.Request, v reflect.Value) {
+ if field, ok := v.Type().FieldByName("_"); ok {
+ if payloadName := field.Tag.Get("payload"); payloadName != "" {
+ pfield, _ := v.Type().FieldByName(payloadName)
+ if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" {
+ payload := reflect.Indirect(v.FieldByName(payloadName))
+ if payload.IsValid() && payload.Interface() != nil {
+ switch reader := payload.Interface().(type) {
+ case io.ReadSeeker:
+ r.SetReaderBody(reader)
+ case []byte:
+ r.SetBufferBody(reader)
+ case string:
+ r.SetStringBody(reader)
+ default:
+ r.Error = awserr.New("SerializationError",
+ "failed to encode REST request",
+ fmt.Errorf("unknown payload type %s", payload.Type()))
+ }
+ }
+ }
+ }
+ }
+}
+
+func buildHeader(header *http.Header, v reflect.Value, name string) error {
+ str, err := convertType(v)
+ if err == errValueNotSet {
+ return nil
+ } else if err != nil {
+ return awserr.New("SerializationError", "failed to encode REST request", err)
+ }
+
+ header.Add(name, str)
+
+ return nil
+}
+
+func buildHeaderMap(header *http.Header, v reflect.Value, prefix string) error {
+ for _, key := range v.MapKeys() {
+ str, err := convertType(v.MapIndex(key))
+ if err == errValueNotSet {
+ continue
+ } else if err != nil {
+ return awserr.New("SerializationError", "failed to encode REST request", err)
+
+ }
+
+ header.Add(prefix+key.String(), str)
+ }
+ return nil
+}
+
+func buildURI(u *url.URL, v reflect.Value, name string) error {
+ value, err := convertType(v)
+ if err == errValueNotSet {
+ return nil
+ } else if err != nil {
+ return awserr.New("SerializationError", "failed to encode REST request", err)
+ }
+
+ uri := u.Path
+ uri = strings.Replace(uri, "{"+name+"}", EscapePath(value, true), -1)
+ uri = strings.Replace(uri, "{"+name+"+}", EscapePath(value, false), -1)
+ u.Path = uri
+
+ return nil
+}
+
+func buildQueryString(query url.Values, v reflect.Value, name string) error {
+ switch value := v.Interface().(type) {
+ case []*string:
+ for _, item := range value {
+ query.Add(name, *item)
+ }
+ case map[string]*string:
+ for key, item := range value {
+ query.Add(key, *item)
+ }
+ case map[string][]*string:
+ for key, items := range value {
+ for _, item := range items {
+ query.Add(key, *item)
+ }
+ }
+ default:
+ str, err := convertType(v)
+ if err == errValueNotSet {
+ return nil
+ } else if err != nil {
+ return awserr.New("SerializationError", "failed to encode REST request", err)
+ }
+ query.Set(name, str)
+ }
+
+ return nil
+}
+
+func updatePath(url *url.URL, urlPath string) {
+ scheme, query := url.Scheme, url.RawQuery
+
+ hasSlash := strings.HasSuffix(urlPath, "/")
+
+ // clean up path
+ urlPath = path.Clean(urlPath)
+ if hasSlash && !strings.HasSuffix(urlPath, "/") {
+ urlPath += "/"
+ }
+
+ // get formatted URL minus scheme so we can build this into Opaque
+ url.Scheme, url.Path, url.RawQuery = "", "", ""
+ s := url.String()
+ url.Scheme = scheme
+ url.RawQuery = query
+
+ // build opaque URI
+ url.Opaque = s + urlPath
+}
+
+// EscapePath escapes part of a URL path in Amazon style
+func EscapePath(path string, encodeSep bool) string {
+ var buf bytes.Buffer
+ for i := 0; i < len(path); i++ {
+ c := path[i]
+ if noEscape[c] || (c == '/' && !encodeSep) {
+ buf.WriteByte(c)
+ } else {
+ fmt.Fprintf(&buf, "%%%02X", c)
+ }
+ }
+ return buf.String()
+}
+
+func convertType(v reflect.Value) (string, error) {
+ v = reflect.Indirect(v)
+ if !v.IsValid() {
+ return "", errValueNotSet
+ }
+
+ var str string
+ switch value := v.Interface().(type) {
+ case string:
+ str = value
+ case []byte:
+ str = base64.StdEncoding.EncodeToString(value)
+ case bool:
+ str = strconv.FormatBool(value)
+ case int64:
+ str = strconv.FormatInt(value, 10)
+ case float64:
+ str = strconv.FormatFloat(value, 'f', -1, 64)
+ case time.Time:
+ str = value.UTC().Format(RFC822)
+ default:
+ err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type())
+ return "", err
+ }
+ return str, nil
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go
new file mode 100644
index 0000000..4366de2
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go
@@ -0,0 +1,45 @@
+package rest
+
+import "reflect"
+
+// PayloadMember returns the payload field member of i if there is one, or nil.
+func PayloadMember(i interface{}) interface{} {
+ if i == nil {
+ return nil
+ }
+
+ v := reflect.ValueOf(i).Elem()
+ if !v.IsValid() {
+ return nil
+ }
+ if field, ok := v.Type().FieldByName("_"); ok {
+ if payloadName := field.Tag.Get("payload"); payloadName != "" {
+ field, _ := v.Type().FieldByName(payloadName)
+ if field.Tag.Get("type") != "structure" {
+ return nil
+ }
+
+ payload := v.FieldByName(payloadName)
+ if payload.IsValid() || (payload.Kind() == reflect.Ptr && !payload.IsNil()) {
+ return payload.Interface()
+ }
+ }
+ }
+ return nil
+}
+
+// PayloadType returns the type of a payload field member of i if there is one, or "".
+func PayloadType(i interface{}) string {
+ v := reflect.Indirect(reflect.ValueOf(i))
+ if !v.IsValid() {
+ return ""
+ }
+ if field, ok := v.Type().FieldByName("_"); ok {
+ if payloadName := field.Tag.Get("payload"); payloadName != "" {
+ if member, ok := v.Type().FieldByName(payloadName); ok {
+ return member.Tag.Get("type")
+ }
+ }
+ }
+ return ""
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go
new file mode 100644
index 0000000..2cba1d9
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go
@@ -0,0 +1,198 @@
+package rest
+
+import (
+ "encoding/base64"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net/http"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/awserr"
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+// UnmarshalHandler is a named request handler for unmarshaling rest protocol requests
+var UnmarshalHandler = request.NamedHandler{Name: "awssdk.rest.Unmarshal", Fn: Unmarshal}
+
+// UnmarshalMetaHandler is a named request handler for unmarshaling rest protocol request metadata
+var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.rest.UnmarshalMeta", Fn: UnmarshalMeta}
+
+// Unmarshal unmarshals the REST component of a response in a REST service.
+func Unmarshal(r *request.Request) {
+ if r.DataFilled() {
+ v := reflect.Indirect(reflect.ValueOf(r.Data))
+ unmarshalBody(r, v)
+ }
+}
+
+// UnmarshalMeta unmarshals the REST metadata of a response in a REST service
+func UnmarshalMeta(r *request.Request) {
+ r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid")
+ if r.RequestID == "" {
+ // Alternative version of request id in the header
+ r.RequestID = r.HTTPResponse.Header.Get("X-Amz-Request-Id")
+ }
+ if r.DataFilled() {
+ v := reflect.Indirect(reflect.ValueOf(r.Data))
+ unmarshalLocationElements(r, v)
+ }
+}
+
+func unmarshalBody(r *request.Request, v reflect.Value) {
+ if field, ok := v.Type().FieldByName("_"); ok {
+ if payloadName := field.Tag.Get("payload"); payloadName != "" {
+ pfield, _ := v.Type().FieldByName(payloadName)
+ if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" {
+ payload := v.FieldByName(payloadName)
+ if payload.IsValid() {
+ switch payload.Interface().(type) {
+ case []byte:
+ defer r.HTTPResponse.Body.Close()
+ b, err := ioutil.ReadAll(r.HTTPResponse.Body)
+ if err != nil {
+ r.Error = awserr.New("SerializationError", "failed to decode REST response", err)
+ } else {
+ payload.Set(reflect.ValueOf(b))
+ }
+ case *string:
+ defer r.HTTPResponse.Body.Close()
+ b, err := ioutil.ReadAll(r.HTTPResponse.Body)
+ if err != nil {
+ r.Error = awserr.New("SerializationError", "failed to decode REST response", err)
+ } else {
+ str := string(b)
+ payload.Set(reflect.ValueOf(&str))
+ }
+ default:
+ switch payload.Type().String() {
+ case "io.ReadSeeker":
+ payload.Set(reflect.ValueOf(aws.ReadSeekCloser(r.HTTPResponse.Body)))
+ case "aws.ReadSeekCloser", "io.ReadCloser":
+ payload.Set(reflect.ValueOf(r.HTTPResponse.Body))
+ default:
+ io.Copy(ioutil.Discard, r.HTTPResponse.Body)
+ defer r.HTTPResponse.Body.Close()
+ r.Error = awserr.New("SerializationError",
+ "failed to decode REST response",
+ fmt.Errorf("unknown payload type %s", payload.Type()))
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+func unmarshalLocationElements(r *request.Request, v reflect.Value) {
+ for i := 0; i < v.NumField(); i++ {
+ m, field := v.Field(i), v.Type().Field(i)
+ if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) {
+ continue
+ }
+
+ if m.IsValid() {
+ name := field.Tag.Get("locationName")
+ if name == "" {
+ name = field.Name
+ }
+
+ switch field.Tag.Get("location") {
+ case "statusCode":
+ unmarshalStatusCode(m, r.HTTPResponse.StatusCode)
+ case "header":
+ err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name))
+ if err != nil {
+ r.Error = awserr.New("SerializationError", "failed to decode REST response", err)
+ break
+ }
+ case "headers":
+ prefix := field.Tag.Get("locationName")
+ err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix)
+ if err != nil {
+ r.Error = awserr.New("SerializationError", "failed to decode REST response", err)
+ break
+ }
+ }
+ }
+ if r.Error != nil {
+ return
+ }
+ }
+}
+
+func unmarshalStatusCode(v reflect.Value, statusCode int) {
+ if !v.IsValid() {
+ return
+ }
+
+ switch v.Interface().(type) {
+ case *int64:
+ s := int64(statusCode)
+ v.Set(reflect.ValueOf(&s))
+ }
+}
+
+func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string) error {
+ switch r.Interface().(type) {
+ case map[string]*string: // we only support string map value types
+ out := map[string]*string{}
+ for k, v := range headers {
+ k = http.CanonicalHeaderKey(k)
+ if strings.HasPrefix(strings.ToLower(k), strings.ToLower(prefix)) {
+ out[k[len(prefix):]] = &v[0]
+ }
+ }
+ r.Set(reflect.ValueOf(out))
+ }
+ return nil
+}
+
+func unmarshalHeader(v reflect.Value, header string) error {
+ if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) {
+ return nil
+ }
+
+ switch v.Interface().(type) {
+ case *string:
+ v.Set(reflect.ValueOf(&header))
+ case []byte:
+ b, err := base64.StdEncoding.DecodeString(header)
+ if err != nil {
+ return err
+ }
+ v.Set(reflect.ValueOf(&b))
+ case *bool:
+ b, err := strconv.ParseBool(header)
+ if err != nil {
+ return err
+ }
+ v.Set(reflect.ValueOf(&b))
+ case *int64:
+ i, err := strconv.ParseInt(header, 10, 64)
+ if err != nil {
+ return err
+ }
+ v.Set(reflect.ValueOf(&i))
+ case *float64:
+ f, err := strconv.ParseFloat(header, 64)
+ if err != nil {
+ return err
+ }
+ v.Set(reflect.ValueOf(&f))
+ case *time.Time:
+ t, err := time.Parse(RFC822, header)
+ if err != nil {
+ return err
+ }
+ v.Set(reflect.ValueOf(&t))
+ default:
+ err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type())
+ return err
+ }
+ return nil
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go
new file mode 100644
index 0000000..da1a681
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go
@@ -0,0 +1,21 @@
+package protocol
+
+import (
+ "io"
+ "io/ioutil"
+
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+// UnmarshalDiscardBodyHandler is a named request handler to empty and close a response's body
+var UnmarshalDiscardBodyHandler = request.NamedHandler{Name: "awssdk.shared.UnmarshalDiscardBody", Fn: UnmarshalDiscardBody}
+
+// UnmarshalDiscardBody is a request handler to empty a response's body and closing it.
+func UnmarshalDiscardBody(r *request.Request) {
+ if r.HTTPResponse == nil || r.HTTPResponse.Body == nil {
+ return
+ }
+
+ io.Copy(ioutil.Discard, r.HTTPResponse.Body)
+ r.HTTPResponse.Body.Close()
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go
new file mode 100644
index 0000000..221029b
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go
@@ -0,0 +1,293 @@
+// Package xmlutil provides XML serialization of AWS requests and responses.
+package xmlutil
+
+import (
+ "encoding/base64"
+ "encoding/xml"
+ "fmt"
+ "reflect"
+ "sort"
+ "strconv"
+ "time"
+
+ "github.com/aws/aws-sdk-go/private/protocol"
+)
+
+// BuildXML will serialize params into an xml.Encoder.
+// Error will be returned if the serialization of any of the params or nested values fails.
+func BuildXML(params interface{}, e *xml.Encoder) error {
+ b := xmlBuilder{encoder: e, namespaces: map[string]string{}}
+ root := NewXMLElement(xml.Name{})
+ if err := b.buildValue(reflect.ValueOf(params), root, ""); err != nil {
+ return err
+ }
+ for _, c := range root.Children {
+ for _, v := range c {
+ return StructToXML(e, v, false)
+ }
+ }
+ return nil
+}
+
+// Returns the reflection element of a value, if it is a pointer.
+func elemOf(value reflect.Value) reflect.Value {
+ for value.Kind() == reflect.Ptr {
+ value = value.Elem()
+ }
+ return value
+}
+
+// A xmlBuilder serializes values from Go code to XML
+type xmlBuilder struct {
+ encoder *xml.Encoder
+ namespaces map[string]string
+}
+
+// buildValue generic XMLNode builder for any type. Will build value for their specific type
+// struct, list, map, scalar.
+//
+// Also takes a "type" tag value to set what type a value should be converted to XMLNode as. If
+// type is not provided reflect will be used to determine the value's type.
+func (b *xmlBuilder) buildValue(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
+ value = elemOf(value)
+ if !value.IsValid() { // no need to handle zero values
+ return nil
+ } else if tag.Get("location") != "" { // don't handle non-body location values
+ return nil
+ }
+
+ t := tag.Get("type")
+ if t == "" {
+ switch value.Kind() {
+ case reflect.Struct:
+ t = "structure"
+ case reflect.Slice:
+ t = "list"
+ case reflect.Map:
+ t = "map"
+ }
+ }
+
+ switch t {
+ case "structure":
+ if field, ok := value.Type().FieldByName("_"); ok {
+ tag = tag + reflect.StructTag(" ") + field.Tag
+ }
+ return b.buildStruct(value, current, tag)
+ case "list":
+ return b.buildList(value, current, tag)
+ case "map":
+ return b.buildMap(value, current, tag)
+ default:
+ return b.buildScalar(value, current, tag)
+ }
+}
+
+// buildStruct adds a struct and its fields to the current XMLNode. All fields any any nested
+// types are converted to XMLNodes also.
+func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
+ if !value.IsValid() {
+ return nil
+ }
+
+ fieldAdded := false
+
+ // unwrap payloads
+ if payload := tag.Get("payload"); payload != "" {
+ field, _ := value.Type().FieldByName(payload)
+ tag = field.Tag
+ value = elemOf(value.FieldByName(payload))
+
+ if !value.IsValid() {
+ return nil
+ }
+ }
+
+ child := NewXMLElement(xml.Name{Local: tag.Get("locationName")})
+
+ // there is an xmlNamespace associated with this struct
+ if prefix, uri := tag.Get("xmlPrefix"), tag.Get("xmlURI"); uri != "" {
+ ns := xml.Attr{
+ Name: xml.Name{Local: "xmlns"},
+ Value: uri,
+ }
+ if prefix != "" {
+ b.namespaces[prefix] = uri // register the namespace
+ ns.Name.Local = "xmlns:" + prefix
+ }
+
+ child.Attr = append(child.Attr, ns)
+ }
+
+ t := value.Type()
+ for i := 0; i < value.NumField(); i++ {
+ member := elemOf(value.Field(i))
+ field := t.Field(i)
+
+ if field.PkgPath != "" {
+ continue // ignore unexported fields
+ }
+
+ mTag := field.Tag
+ if mTag.Get("location") != "" { // skip non-body members
+ continue
+ }
+
+ if protocol.CanSetIdempotencyToken(value.Field(i), field) {
+ token := protocol.GetIdempotencyToken()
+ member = reflect.ValueOf(token)
+ }
+
+ memberName := mTag.Get("locationName")
+ if memberName == "" {
+ memberName = field.Name
+ mTag = reflect.StructTag(string(mTag) + ` locationName:"` + memberName + `"`)
+ }
+ if err := b.buildValue(member, child, mTag); err != nil {
+ return err
+ }
+
+ fieldAdded = true
+ }
+
+ if fieldAdded { // only append this child if we have one ore more valid members
+ current.AddChild(child)
+ }
+
+ return nil
+}
+
+// buildList adds the value's list items to the current XMLNode as children nodes. All
+// nested values in the list are converted to XMLNodes also.
+func (b *xmlBuilder) buildList(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
+ if value.IsNil() { // don't build omitted lists
+ return nil
+ }
+
+ // check for unflattened list member
+ flattened := tag.Get("flattened") != ""
+
+ xname := xml.Name{Local: tag.Get("locationName")}
+ if flattened {
+ for i := 0; i < value.Len(); i++ {
+ child := NewXMLElement(xname)
+ current.AddChild(child)
+ if err := b.buildValue(value.Index(i), child, ""); err != nil {
+ return err
+ }
+ }
+ } else {
+ list := NewXMLElement(xname)
+ current.AddChild(list)
+
+ for i := 0; i < value.Len(); i++ {
+ iname := tag.Get("locationNameList")
+ if iname == "" {
+ iname = "member"
+ }
+
+ child := NewXMLElement(xml.Name{Local: iname})
+ list.AddChild(child)
+ if err := b.buildValue(value.Index(i), child, ""); err != nil {
+ return err
+ }
+ }
+ }
+
+ return nil
+}
+
+// buildMap adds the value's key/value pairs to the current XMLNode as children nodes. All
+// nested values in the map are converted to XMLNodes also.
+//
+// Error will be returned if it is unable to build the map's values into XMLNodes
+func (b *xmlBuilder) buildMap(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
+ if value.IsNil() { // don't build omitted maps
+ return nil
+ }
+
+ maproot := NewXMLElement(xml.Name{Local: tag.Get("locationName")})
+ current.AddChild(maproot)
+ current = maproot
+
+ kname, vname := "key", "value"
+ if n := tag.Get("locationNameKey"); n != "" {
+ kname = n
+ }
+ if n := tag.Get("locationNameValue"); n != "" {
+ vname = n
+ }
+
+ // sorting is not required for compliance, but it makes testing easier
+ keys := make([]string, value.Len())
+ for i, k := range value.MapKeys() {
+ keys[i] = k.String()
+ }
+ sort.Strings(keys)
+
+ for _, k := range keys {
+ v := value.MapIndex(reflect.ValueOf(k))
+
+ mapcur := current
+ if tag.Get("flattened") == "" { // add "entry" tag to non-flat maps
+ child := NewXMLElement(xml.Name{Local: "entry"})
+ mapcur.AddChild(child)
+ mapcur = child
+ }
+
+ kchild := NewXMLElement(xml.Name{Local: kname})
+ kchild.Text = k
+ vchild := NewXMLElement(xml.Name{Local: vname})
+ mapcur.AddChild(kchild)
+ mapcur.AddChild(vchild)
+
+ if err := b.buildValue(v, vchild, ""); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+// buildScalar will convert the value into a string and append it as a attribute or child
+// of the current XMLNode.
+//
+// The value will be added as an attribute if tag contains a "xmlAttribute" attribute value.
+//
+// Error will be returned if the value type is unsupported.
+func (b *xmlBuilder) buildScalar(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
+ var str string
+ switch converted := value.Interface().(type) {
+ case string:
+ str = converted
+ case []byte:
+ if !value.IsNil() {
+ str = base64.StdEncoding.EncodeToString(converted)
+ }
+ case bool:
+ str = strconv.FormatBool(converted)
+ case int64:
+ str = strconv.FormatInt(converted, 10)
+ case int:
+ str = strconv.Itoa(converted)
+ case float64:
+ str = strconv.FormatFloat(converted, 'f', -1, 64)
+ case float32:
+ str = strconv.FormatFloat(float64(converted), 'f', -1, 32)
+ case time.Time:
+ const ISO8601UTC = "2006-01-02T15:04:05Z"
+ str = converted.UTC().Format(ISO8601UTC)
+ default:
+ return fmt.Errorf("unsupported value for param %s: %v (%s)",
+ tag.Get("locationName"), value.Interface(), value.Type().Name())
+ }
+
+ xname := xml.Name{Local: tag.Get("locationName")}
+ if tag.Get("xmlAttribute") != "" { // put into current node's attribute list
+ attr := xml.Attr{Name: xname, Value: str}
+ current.Attr = append(current.Attr, attr)
+ } else { // regular text node
+ current.AddChild(&XMLNode{Name: xname, Text: str})
+ }
+ return nil
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go
new file mode 100644
index 0000000..49f291a
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go
@@ -0,0 +1,260 @@
+package xmlutil
+
+import (
+ "encoding/base64"
+ "encoding/xml"
+ "fmt"
+ "io"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// UnmarshalXML deserializes an xml.Decoder into the container v. V
+// needs to match the shape of the XML expected to be decoded.
+// If the shape doesn't match unmarshaling will fail.
+func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error {
+ n, _ := XMLToStruct(d, nil)
+ if n.Children != nil {
+ for _, root := range n.Children {
+ for _, c := range root {
+ if wrappedChild, ok := c.Children[wrapper]; ok {
+ c = wrappedChild[0] // pull out wrapped element
+ }
+
+ err := parse(reflect.ValueOf(v), c, "")
+ if err != nil {
+ if err == io.EOF {
+ return nil
+ }
+ return err
+ }
+ }
+ }
+ return nil
+ }
+ return nil
+}
+
+// parse deserializes any value from the XMLNode. The type tag is used to infer the type, or reflect
+// will be used to determine the type from r.
+func parse(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
+ rtype := r.Type()
+ if rtype.Kind() == reflect.Ptr {
+ rtype = rtype.Elem() // check kind of actual element type
+ }
+
+ t := tag.Get("type")
+ if t == "" {
+ switch rtype.Kind() {
+ case reflect.Struct:
+ t = "structure"
+ case reflect.Slice:
+ t = "list"
+ case reflect.Map:
+ t = "map"
+ }
+ }
+
+ switch t {
+ case "structure":
+ if field, ok := rtype.FieldByName("_"); ok {
+ tag = field.Tag
+ }
+ return parseStruct(r, node, tag)
+ case "list":
+ return parseList(r, node, tag)
+ case "map":
+ return parseMap(r, node, tag)
+ default:
+ return parseScalar(r, node, tag)
+ }
+}
+
+// parseStruct deserializes a structure and its fields from an XMLNode. Any nested
+// types in the structure will also be deserialized.
+func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
+ t := r.Type()
+ if r.Kind() == reflect.Ptr {
+ if r.IsNil() { // create the structure if it's nil
+ s := reflect.New(r.Type().Elem())
+ r.Set(s)
+ r = s
+ }
+
+ r = r.Elem()
+ t = t.Elem()
+ }
+
+ // unwrap any payloads
+ if payload := tag.Get("payload"); payload != "" {
+ field, _ := t.FieldByName(payload)
+ return parseStruct(r.FieldByName(payload), node, field.Tag)
+ }
+
+ for i := 0; i < t.NumField(); i++ {
+ field := t.Field(i)
+ if c := field.Name[0:1]; strings.ToLower(c) == c {
+ continue // ignore unexported fields
+ }
+
+ // figure out what this field is called
+ name := field.Name
+ if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" {
+ name = field.Tag.Get("locationNameList")
+ } else if locName := field.Tag.Get("locationName"); locName != "" {
+ name = locName
+ }
+
+ // try to find the field by name in elements
+ elems := node.Children[name]
+
+ if elems == nil { // try to find the field in attributes
+ for _, a := range node.Attr {
+ if name == a.Name.Local {
+ // turn this into a text node for de-serializing
+ elems = []*XMLNode{{Text: a.Value}}
+ }
+ }
+ }
+
+ member := r.FieldByName(field.Name)
+ for _, elem := range elems {
+ err := parse(member, elem, field.Tag)
+ if err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// parseList deserializes a list of values from an XML node. Each list entry
+// will also be deserialized.
+func parseList(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
+ t := r.Type()
+
+ if tag.Get("flattened") == "" { // look at all item entries
+ mname := "member"
+ if name := tag.Get("locationNameList"); name != "" {
+ mname = name
+ }
+
+ if Children, ok := node.Children[mname]; ok {
+ if r.IsNil() {
+ r.Set(reflect.MakeSlice(t, len(Children), len(Children)))
+ }
+
+ for i, c := range Children {
+ err := parse(r.Index(i), c, "")
+ if err != nil {
+ return err
+ }
+ }
+ }
+ } else { // flattened list means this is a single element
+ if r.IsNil() {
+ r.Set(reflect.MakeSlice(t, 0, 0))
+ }
+
+ childR := reflect.Zero(t.Elem())
+ r.Set(reflect.Append(r, childR))
+ err := parse(r.Index(r.Len()-1), node, "")
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+// parseMap deserializes a map from an XMLNode. The direct children of the XMLNode
+// will also be deserialized as map entries.
+func parseMap(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
+ if r.IsNil() {
+ r.Set(reflect.MakeMap(r.Type()))
+ }
+
+ if tag.Get("flattened") == "" { // look at all child entries
+ for _, entry := range node.Children["entry"] {
+ parseMapEntry(r, entry, tag)
+ }
+ } else { // this element is itself an entry
+ parseMapEntry(r, node, tag)
+ }
+
+ return nil
+}
+
+// parseMapEntry deserializes a map entry from a XML node.
+func parseMapEntry(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
+ kname, vname := "key", "value"
+ if n := tag.Get("locationNameKey"); n != "" {
+ kname = n
+ }
+ if n := tag.Get("locationNameValue"); n != "" {
+ vname = n
+ }
+
+ keys, ok := node.Children[kname]
+ values := node.Children[vname]
+ if ok {
+ for i, key := range keys {
+ keyR := reflect.ValueOf(key.Text)
+ value := values[i]
+ valueR := reflect.New(r.Type().Elem()).Elem()
+
+ parse(valueR, value, "")
+ r.SetMapIndex(keyR, valueR)
+ }
+ }
+ return nil
+}
+
+// parseScaller deserializes an XMLNode value into a concrete type based on the
+// interface type of r.
+//
+// Error is returned if the deserialization fails due to invalid type conversion,
+// or unsupported interface type.
+func parseScalar(r reflect.Value, node *XMLNode, tag reflect.StructTag) error {
+ switch r.Interface().(type) {
+ case *string:
+ r.Set(reflect.ValueOf(&node.Text))
+ return nil
+ case []byte:
+ b, err := base64.StdEncoding.DecodeString(node.Text)
+ if err != nil {
+ return err
+ }
+ r.Set(reflect.ValueOf(b))
+ case *bool:
+ v, err := strconv.ParseBool(node.Text)
+ if err != nil {
+ return err
+ }
+ r.Set(reflect.ValueOf(&v))
+ case *int64:
+ v, err := strconv.ParseInt(node.Text, 10, 64)
+ if err != nil {
+ return err
+ }
+ r.Set(reflect.ValueOf(&v))
+ case *float64:
+ v, err := strconv.ParseFloat(node.Text, 64)
+ if err != nil {
+ return err
+ }
+ r.Set(reflect.ValueOf(&v))
+ case *time.Time:
+ const ISO8601UTC = "2006-01-02T15:04:05Z"
+ t, err := time.Parse(ISO8601UTC, node.Text)
+ if err != nil {
+ return err
+ }
+ r.Set(reflect.ValueOf(&t))
+ default:
+ return fmt.Errorf("unsupported value: %v (%s)", r.Interface(), r.Type())
+ }
+ return nil
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go
new file mode 100644
index 0000000..72c198a
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go
@@ -0,0 +1,105 @@
+package xmlutil
+
+import (
+ "encoding/xml"
+ "io"
+ "sort"
+)
+
+// A XMLNode contains the values to be encoded or decoded.
+type XMLNode struct {
+ Name xml.Name `json:",omitempty"`
+ Children map[string][]*XMLNode `json:",omitempty"`
+ Text string `json:",omitempty"`
+ Attr []xml.Attr `json:",omitempty"`
+}
+
+// NewXMLElement returns a pointer to a new XMLNode initialized to default values.
+func NewXMLElement(name xml.Name) *XMLNode {
+ return &XMLNode{
+ Name: name,
+ Children: map[string][]*XMLNode{},
+ Attr: []xml.Attr{},
+ }
+}
+
+// AddChild adds child to the XMLNode.
+func (n *XMLNode) AddChild(child *XMLNode) {
+ if _, ok := n.Children[child.Name.Local]; !ok {
+ n.Children[child.Name.Local] = []*XMLNode{}
+ }
+ n.Children[child.Name.Local] = append(n.Children[child.Name.Local], child)
+}
+
+// XMLToStruct converts a xml.Decoder stream to XMLNode with nested values.
+func XMLToStruct(d *xml.Decoder, s *xml.StartElement) (*XMLNode, error) {
+ out := &XMLNode{}
+ for {
+ tok, err := d.Token()
+ if tok == nil || err == io.EOF {
+ break
+ }
+ if err != nil {
+ return out, err
+ }
+
+ switch typed := tok.(type) {
+ case xml.CharData:
+ out.Text = string(typed.Copy())
+ case xml.StartElement:
+ el := typed.Copy()
+ out.Attr = el.Attr
+ if out.Children == nil {
+ out.Children = map[string][]*XMLNode{}
+ }
+
+ name := typed.Name.Local
+ slice := out.Children[name]
+ if slice == nil {
+ slice = []*XMLNode{}
+ }
+ node, e := XMLToStruct(d, &el)
+ if e != nil {
+ return out, e
+ }
+ node.Name = typed.Name
+ slice = append(slice, node)
+ out.Children[name] = slice
+ case xml.EndElement:
+ if s != nil && s.Name.Local == typed.Name.Local { // matching end token
+ return out, nil
+ }
+ }
+ }
+ return out, nil
+}
+
+// StructToXML writes an XMLNode to a xml.Encoder as tokens.
+func StructToXML(e *xml.Encoder, node *XMLNode, sorted bool) error {
+ e.EncodeToken(xml.StartElement{Name: node.Name, Attr: node.Attr})
+
+ if node.Text != "" {
+ e.EncodeToken(xml.CharData([]byte(node.Text)))
+ } else if sorted {
+ sortedNames := []string{}
+ for k := range node.Children {
+ sortedNames = append(sortedNames, k)
+ }
+ sort.Strings(sortedNames)
+
+ for _, k := range sortedNames {
+ for _, v := range node.Children[k] {
+ StructToXML(e, v, sorted)
+ }
+ }
+ } else {
+ for _, c := range node.Children {
+ for _, v := range c {
+ StructToXML(e, v, sorted)
+ }
+ }
+ }
+
+ e.EncodeToken(xml.EndElement{Name: node.Name})
+ return e.Flush()
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go
new file mode 100644
index 0000000..ba48157
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go
@@ -0,0 +1,4516 @@
+// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
+
+// Package cloudwatchlogs provides a client for Amazon CloudWatch Logs.
+package cloudwatchlogs
+
+import (
+ "fmt"
+
+ "github.com/aws/aws-sdk-go/aws/awsutil"
+ "github.com/aws/aws-sdk-go/aws/request"
+ "github.com/aws/aws-sdk-go/private/protocol"
+ "github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
+)
+
+const opCancelExportTask = "CancelExportTask"
+
+// CancelExportTaskRequest generates a "aws/request.Request" representing the
+// client's request for the CancelExportTask operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See CancelExportTask for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the CancelExportTask method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the CancelExportTaskRequest method.
+// req, resp := client.CancelExportTaskRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) CancelExportTaskRequest(input *CancelExportTaskInput) (req *request.Request, output *CancelExportTaskOutput) {
+ op := &request.Operation{
+ Name: opCancelExportTask,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &CancelExportTaskInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &CancelExportTaskOutput{}
+ req.Data = output
+ return
+}
+
+// CancelExportTask API operation for Amazon CloudWatch Logs.
+//
+// Cancels an export task if it is in PENDING or RUNNING state.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation CancelExportTask for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * InvalidOperationException
+// Returned if the operation is not valid on the specified resource
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) CancelExportTask(input *CancelExportTaskInput) (*CancelExportTaskOutput, error) {
+ req, out := c.CancelExportTaskRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opCreateExportTask = "CreateExportTask"
+
+// CreateExportTaskRequest generates a "aws/request.Request" representing the
+// client's request for the CreateExportTask operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See CreateExportTask for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the CreateExportTask method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the CreateExportTaskRequest method.
+// req, resp := client.CreateExportTaskRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) CreateExportTaskRequest(input *CreateExportTaskInput) (req *request.Request, output *CreateExportTaskOutput) {
+ op := &request.Operation{
+ Name: opCreateExportTask,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &CreateExportTaskInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &CreateExportTaskOutput{}
+ req.Data = output
+ return
+}
+
+// CreateExportTask API operation for Amazon CloudWatch Logs.
+//
+// Creates an ExportTask which allows you to efficiently export data from a
+// Log Group to your Amazon S3 bucket.
+//
+// This is an asynchronous call. If all the required information is provided,
+// this API will initiate an export task and respond with the task Id. Once
+// started, DescribeExportTasks can be used to get the status of an export task.
+// You can only have one active (RUNNING or PENDING) export task at a time,
+// per account.
+//
+// You can export logs from multiple log groups or multiple time ranges to the
+// same Amazon S3 bucket. To separate out log data for each export task, you
+// can specify a prefix that will be used as the Amazon S3 key prefix for all
+// exported objects.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation CreateExportTask for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * LimitExceededException
+// Returned if you have reached the maximum number of resources that can be
+// created.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * ResourceAlreadyExistsException
+// Returned if the specified resource already exists.
+//
+func (c *CloudWatchLogs) CreateExportTask(input *CreateExportTaskInput) (*CreateExportTaskOutput, error) {
+ req, out := c.CreateExportTaskRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opCreateLogGroup = "CreateLogGroup"
+
+// CreateLogGroupRequest generates a "aws/request.Request" representing the
+// client's request for the CreateLogGroup operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See CreateLogGroup for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the CreateLogGroup method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the CreateLogGroupRequest method.
+// req, resp := client.CreateLogGroupRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) CreateLogGroupRequest(input *CreateLogGroupInput) (req *request.Request, output *CreateLogGroupOutput) {
+ op := &request.Operation{
+ Name: opCreateLogGroup,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &CreateLogGroupInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &CreateLogGroupOutput{}
+ req.Data = output
+ return
+}
+
+// CreateLogGroup API operation for Amazon CloudWatch Logs.
+//
+// Creates a new log group with the specified name. The name of the log group
+// must be unique within a region for an AWS account. You can create up to 500
+// log groups per account.
+//
+// You must use the following guidelines when naming a log group:
+//
+// * Log group names can be between 1 and 512 characters long.
+//
+// * Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (hyphen),
+// '/' (forward slash), and '.' (period).
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation CreateLogGroup for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceAlreadyExistsException
+// Returned if the specified resource already exists.
+//
+// * LimitExceededException
+// Returned if you have reached the maximum number of resources that can be
+// created.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) CreateLogGroup(input *CreateLogGroupInput) (*CreateLogGroupOutput, error) {
+ req, out := c.CreateLogGroupRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opCreateLogStream = "CreateLogStream"
+
+// CreateLogStreamRequest generates a "aws/request.Request" representing the
+// client's request for the CreateLogStream operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See CreateLogStream for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the CreateLogStream method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the CreateLogStreamRequest method.
+// req, resp := client.CreateLogStreamRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) CreateLogStreamRequest(input *CreateLogStreamInput) (req *request.Request, output *CreateLogStreamOutput) {
+ op := &request.Operation{
+ Name: opCreateLogStream,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &CreateLogStreamInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &CreateLogStreamOutput{}
+ req.Data = output
+ return
+}
+
+// CreateLogStream API operation for Amazon CloudWatch Logs.
+//
+// Creates a new log stream in the specified log group. The name of the log
+// stream must be unique within the log group. There is no limit on the number
+// of log streams that can exist in a log group.
+//
+// You must use the following guidelines when naming a log stream:
+//
+// * Log stream names can be between 1 and 512 characters long.
+//
+// * The ':' colon character is not allowed.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation CreateLogStream for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceAlreadyExistsException
+// Returned if the specified resource already exists.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) CreateLogStream(input *CreateLogStreamInput) (*CreateLogStreamOutput, error) {
+ req, out := c.CreateLogStreamRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opDeleteDestination = "DeleteDestination"
+
+// DeleteDestinationRequest generates a "aws/request.Request" representing the
+// client's request for the DeleteDestination operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DeleteDestination for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DeleteDestination method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DeleteDestinationRequest method.
+// req, resp := client.DeleteDestinationRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DeleteDestinationRequest(input *DeleteDestinationInput) (req *request.Request, output *DeleteDestinationOutput) {
+ op := &request.Operation{
+ Name: opDeleteDestination,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &DeleteDestinationInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &DeleteDestinationOutput{}
+ req.Data = output
+ return
+}
+
+// DeleteDestination API operation for Amazon CloudWatch Logs.
+//
+// Deletes the destination with the specified name and eventually disables all
+// the subscription filters that publish to it. This will not delete the physical
+// resource encapsulated by the destination.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DeleteDestination for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DeleteDestination(input *DeleteDestinationInput) (*DeleteDestinationOutput, error) {
+ req, out := c.DeleteDestinationRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opDeleteLogGroup = "DeleteLogGroup"
+
+// DeleteLogGroupRequest generates a "aws/request.Request" representing the
+// client's request for the DeleteLogGroup operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DeleteLogGroup for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DeleteLogGroup method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DeleteLogGroupRequest method.
+// req, resp := client.DeleteLogGroupRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DeleteLogGroupRequest(input *DeleteLogGroupInput) (req *request.Request, output *DeleteLogGroupOutput) {
+ op := &request.Operation{
+ Name: opDeleteLogGroup,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &DeleteLogGroupInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &DeleteLogGroupOutput{}
+ req.Data = output
+ return
+}
+
+// DeleteLogGroup API operation for Amazon CloudWatch Logs.
+//
+// Deletes the log group with the specified name and permanently deletes all
+// the archived log events associated with it.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DeleteLogGroup for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DeleteLogGroup(input *DeleteLogGroupInput) (*DeleteLogGroupOutput, error) {
+ req, out := c.DeleteLogGroupRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opDeleteLogStream = "DeleteLogStream"
+
+// DeleteLogStreamRequest generates a "aws/request.Request" representing the
+// client's request for the DeleteLogStream operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DeleteLogStream for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DeleteLogStream method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DeleteLogStreamRequest method.
+// req, resp := client.DeleteLogStreamRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DeleteLogStreamRequest(input *DeleteLogStreamInput) (req *request.Request, output *DeleteLogStreamOutput) {
+ op := &request.Operation{
+ Name: opDeleteLogStream,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &DeleteLogStreamInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &DeleteLogStreamOutput{}
+ req.Data = output
+ return
+}
+
+// DeleteLogStream API operation for Amazon CloudWatch Logs.
+//
+// Deletes a log stream and permanently deletes all the archived log events
+// associated with it.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DeleteLogStream for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DeleteLogStream(input *DeleteLogStreamInput) (*DeleteLogStreamOutput, error) {
+ req, out := c.DeleteLogStreamRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opDeleteMetricFilter = "DeleteMetricFilter"
+
+// DeleteMetricFilterRequest generates a "aws/request.Request" representing the
+// client's request for the DeleteMetricFilter operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DeleteMetricFilter for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DeleteMetricFilter method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DeleteMetricFilterRequest method.
+// req, resp := client.DeleteMetricFilterRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DeleteMetricFilterRequest(input *DeleteMetricFilterInput) (req *request.Request, output *DeleteMetricFilterOutput) {
+ op := &request.Operation{
+ Name: opDeleteMetricFilter,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &DeleteMetricFilterInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &DeleteMetricFilterOutput{}
+ req.Data = output
+ return
+}
+
+// DeleteMetricFilter API operation for Amazon CloudWatch Logs.
+//
+// Deletes a metric filter associated with the specified log group.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DeleteMetricFilter for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DeleteMetricFilter(input *DeleteMetricFilterInput) (*DeleteMetricFilterOutput, error) {
+ req, out := c.DeleteMetricFilterRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opDeleteRetentionPolicy = "DeleteRetentionPolicy"
+
+// DeleteRetentionPolicyRequest generates a "aws/request.Request" representing the
+// client's request for the DeleteRetentionPolicy operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DeleteRetentionPolicy for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DeleteRetentionPolicy method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DeleteRetentionPolicyRequest method.
+// req, resp := client.DeleteRetentionPolicyRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DeleteRetentionPolicyRequest(input *DeleteRetentionPolicyInput) (req *request.Request, output *DeleteRetentionPolicyOutput) {
+ op := &request.Operation{
+ Name: opDeleteRetentionPolicy,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &DeleteRetentionPolicyInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &DeleteRetentionPolicyOutput{}
+ req.Data = output
+ return
+}
+
+// DeleteRetentionPolicy API operation for Amazon CloudWatch Logs.
+//
+// Deletes the retention policy of the specified log group. Log events would
+// not expire if they belong to log groups without a retention policy.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DeleteRetentionPolicy for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DeleteRetentionPolicy(input *DeleteRetentionPolicyInput) (*DeleteRetentionPolicyOutput, error) {
+ req, out := c.DeleteRetentionPolicyRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opDeleteSubscriptionFilter = "DeleteSubscriptionFilter"
+
+// DeleteSubscriptionFilterRequest generates a "aws/request.Request" representing the
+// client's request for the DeleteSubscriptionFilter operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DeleteSubscriptionFilter for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DeleteSubscriptionFilter method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DeleteSubscriptionFilterRequest method.
+// req, resp := client.DeleteSubscriptionFilterRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DeleteSubscriptionFilterRequest(input *DeleteSubscriptionFilterInput) (req *request.Request, output *DeleteSubscriptionFilterOutput) {
+ op := &request.Operation{
+ Name: opDeleteSubscriptionFilter,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &DeleteSubscriptionFilterInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &DeleteSubscriptionFilterOutput{}
+ req.Data = output
+ return
+}
+
+// DeleteSubscriptionFilter API operation for Amazon CloudWatch Logs.
+//
+// Deletes a subscription filter associated with the specified log group.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DeleteSubscriptionFilter for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DeleteSubscriptionFilter(input *DeleteSubscriptionFilterInput) (*DeleteSubscriptionFilterOutput, error) {
+ req, out := c.DeleteSubscriptionFilterRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opDescribeDestinations = "DescribeDestinations"
+
+// DescribeDestinationsRequest generates a "aws/request.Request" representing the
+// client's request for the DescribeDestinations operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DescribeDestinations for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DescribeDestinations method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DescribeDestinationsRequest method.
+// req, resp := client.DescribeDestinationsRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DescribeDestinationsRequest(input *DescribeDestinationsInput) (req *request.Request, output *DescribeDestinationsOutput) {
+ op := &request.Operation{
+ Name: opDescribeDestinations,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ Paginator: &request.Paginator{
+ InputTokens: []string{"nextToken"},
+ OutputTokens: []string{"nextToken"},
+ LimitToken: "limit",
+ TruncationToken: "",
+ },
+ }
+
+ if input == nil {
+ input = &DescribeDestinationsInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &DescribeDestinationsOutput{}
+ req.Data = output
+ return
+}
+
+// DescribeDestinations API operation for Amazon CloudWatch Logs.
+//
+// Returns all the destinations that are associated with the AWS account making
+// the request. The list returned in the response is ASCII-sorted by destination
+// name.
+//
+// By default, this operation returns up to 50 destinations. If there are more
+// destinations to list, the response would contain a nextToken value in the
+// response body. You can also limit the number of destinations returned in
+// the response by specifying the limit parameter in the request.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DescribeDestinations for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DescribeDestinations(input *DescribeDestinationsInput) (*DescribeDestinationsOutput, error) {
+ req, out := c.DescribeDestinationsRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+// DescribeDestinationsPages iterates over the pages of a DescribeDestinations operation,
+// calling the "fn" function with the response data for each page. To stop
+// iterating, return false from the fn function.
+//
+// See DescribeDestinations method for more information on how to use this operation.
+//
+// Note: This operation can generate multiple requests to a service.
+//
+// // Example iterating over at most 3 pages of a DescribeDestinations operation.
+// pageNum := 0
+// err := client.DescribeDestinationsPages(params,
+// func(page *DescribeDestinationsOutput, lastPage bool) bool {
+// pageNum++
+// fmt.Println(page)
+// return pageNum <= 3
+// })
+//
+func (c *CloudWatchLogs) DescribeDestinationsPages(input *DescribeDestinationsInput, fn func(p *DescribeDestinationsOutput, lastPage bool) (shouldContinue bool)) error {
+ page, _ := c.DescribeDestinationsRequest(input)
+ page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator"))
+ return page.EachPage(func(p interface{}, lastPage bool) bool {
+ return fn(p.(*DescribeDestinationsOutput), lastPage)
+ })
+}
+
+const opDescribeExportTasks = "DescribeExportTasks"
+
+// DescribeExportTasksRequest generates a "aws/request.Request" representing the
+// client's request for the DescribeExportTasks operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DescribeExportTasks for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DescribeExportTasks method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DescribeExportTasksRequest method.
+// req, resp := client.DescribeExportTasksRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DescribeExportTasksRequest(input *DescribeExportTasksInput) (req *request.Request, output *DescribeExportTasksOutput) {
+ op := &request.Operation{
+ Name: opDescribeExportTasks,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &DescribeExportTasksInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &DescribeExportTasksOutput{}
+ req.Data = output
+ return
+}
+
+// DescribeExportTasks API operation for Amazon CloudWatch Logs.
+//
+// Returns all the export tasks that are associated with the AWS account making
+// the request. The export tasks can be filtered based on TaskId or TaskStatus.
+//
+// By default, this operation returns up to 50 export tasks that satisfy the
+// specified filters. If there are more export tasks to list, the response would
+// contain a nextToken value in the response body. You can also limit the number
+// of export tasks returned in the response by specifying the limit parameter
+// in the request.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DescribeExportTasks for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DescribeExportTasks(input *DescribeExportTasksInput) (*DescribeExportTasksOutput, error) {
+ req, out := c.DescribeExportTasksRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opDescribeLogGroups = "DescribeLogGroups"
+
+// DescribeLogGroupsRequest generates a "aws/request.Request" representing the
+// client's request for the DescribeLogGroups operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DescribeLogGroups for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DescribeLogGroups method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DescribeLogGroupsRequest method.
+// req, resp := client.DescribeLogGroupsRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DescribeLogGroupsRequest(input *DescribeLogGroupsInput) (req *request.Request, output *DescribeLogGroupsOutput) {
+ op := &request.Operation{
+ Name: opDescribeLogGroups,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ Paginator: &request.Paginator{
+ InputTokens: []string{"nextToken"},
+ OutputTokens: []string{"nextToken"},
+ LimitToken: "limit",
+ TruncationToken: "",
+ },
+ }
+
+ if input == nil {
+ input = &DescribeLogGroupsInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &DescribeLogGroupsOutput{}
+ req.Data = output
+ return
+}
+
+// DescribeLogGroups API operation for Amazon CloudWatch Logs.
+//
+// Returns all the log groups that are associated with the AWS account making
+// the request. The list returned in the response is ASCII-sorted by log group
+// name.
+//
+// By default, this operation returns up to 50 log groups. If there are more
+// log groups to list, the response would contain a nextToken value in the response
+// body. You can also limit the number of log groups returned in the response
+// by specifying the limit parameter in the request.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DescribeLogGroups for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DescribeLogGroups(input *DescribeLogGroupsInput) (*DescribeLogGroupsOutput, error) {
+ req, out := c.DescribeLogGroupsRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+// DescribeLogGroupsPages iterates over the pages of a DescribeLogGroups operation,
+// calling the "fn" function with the response data for each page. To stop
+// iterating, return false from the fn function.
+//
+// See DescribeLogGroups method for more information on how to use this operation.
+//
+// Note: This operation can generate multiple requests to a service.
+//
+// // Example iterating over at most 3 pages of a DescribeLogGroups operation.
+// pageNum := 0
+// err := client.DescribeLogGroupsPages(params,
+// func(page *DescribeLogGroupsOutput, lastPage bool) bool {
+// pageNum++
+// fmt.Println(page)
+// return pageNum <= 3
+// })
+//
+func (c *CloudWatchLogs) DescribeLogGroupsPages(input *DescribeLogGroupsInput, fn func(p *DescribeLogGroupsOutput, lastPage bool) (shouldContinue bool)) error {
+ page, _ := c.DescribeLogGroupsRequest(input)
+ page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator"))
+ return page.EachPage(func(p interface{}, lastPage bool) bool {
+ return fn(p.(*DescribeLogGroupsOutput), lastPage)
+ })
+}
+
+const opDescribeLogStreams = "DescribeLogStreams"
+
+// DescribeLogStreamsRequest generates a "aws/request.Request" representing the
+// client's request for the DescribeLogStreams operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DescribeLogStreams for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DescribeLogStreams method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DescribeLogStreamsRequest method.
+// req, resp := client.DescribeLogStreamsRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DescribeLogStreamsRequest(input *DescribeLogStreamsInput) (req *request.Request, output *DescribeLogStreamsOutput) {
+ op := &request.Operation{
+ Name: opDescribeLogStreams,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ Paginator: &request.Paginator{
+ InputTokens: []string{"nextToken"},
+ OutputTokens: []string{"nextToken"},
+ LimitToken: "limit",
+ TruncationToken: "",
+ },
+ }
+
+ if input == nil {
+ input = &DescribeLogStreamsInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &DescribeLogStreamsOutput{}
+ req.Data = output
+ return
+}
+
+// DescribeLogStreams API operation for Amazon CloudWatch Logs.
+//
+// Returns all the log streams that are associated with the specified log group.
+// The list returned in the response is ASCII-sorted by log stream name.
+//
+// By default, this operation returns up to 50 log streams. If there are more
+// log streams to list, the response would contain a nextToken value in the
+// response body. You can also limit the number of log streams returned in the
+// response by specifying the limit parameter in the request. This operation
+// has a limit of five transactions per second, after which transactions are
+// throttled.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DescribeLogStreams for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DescribeLogStreams(input *DescribeLogStreamsInput) (*DescribeLogStreamsOutput, error) {
+ req, out := c.DescribeLogStreamsRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+// DescribeLogStreamsPages iterates over the pages of a DescribeLogStreams operation,
+// calling the "fn" function with the response data for each page. To stop
+// iterating, return false from the fn function.
+//
+// See DescribeLogStreams method for more information on how to use this operation.
+//
+// Note: This operation can generate multiple requests to a service.
+//
+// // Example iterating over at most 3 pages of a DescribeLogStreams operation.
+// pageNum := 0
+// err := client.DescribeLogStreamsPages(params,
+// func(page *DescribeLogStreamsOutput, lastPage bool) bool {
+// pageNum++
+// fmt.Println(page)
+// return pageNum <= 3
+// })
+//
+func (c *CloudWatchLogs) DescribeLogStreamsPages(input *DescribeLogStreamsInput, fn func(p *DescribeLogStreamsOutput, lastPage bool) (shouldContinue bool)) error {
+ page, _ := c.DescribeLogStreamsRequest(input)
+ page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator"))
+ return page.EachPage(func(p interface{}, lastPage bool) bool {
+ return fn(p.(*DescribeLogStreamsOutput), lastPage)
+ })
+}
+
+const opDescribeMetricFilters = "DescribeMetricFilters"
+
+// DescribeMetricFiltersRequest generates a "aws/request.Request" representing the
+// client's request for the DescribeMetricFilters operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DescribeMetricFilters for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DescribeMetricFilters method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DescribeMetricFiltersRequest method.
+// req, resp := client.DescribeMetricFiltersRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DescribeMetricFiltersRequest(input *DescribeMetricFiltersInput) (req *request.Request, output *DescribeMetricFiltersOutput) {
+ op := &request.Operation{
+ Name: opDescribeMetricFilters,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ Paginator: &request.Paginator{
+ InputTokens: []string{"nextToken"},
+ OutputTokens: []string{"nextToken"},
+ LimitToken: "limit",
+ TruncationToken: "",
+ },
+ }
+
+ if input == nil {
+ input = &DescribeMetricFiltersInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &DescribeMetricFiltersOutput{}
+ req.Data = output
+ return
+}
+
+// DescribeMetricFilters API operation for Amazon CloudWatch Logs.
+//
+// Returns all the metrics filters associated with the specified log group.
+// The list returned in the response is ASCII-sorted by filter name.
+//
+// By default, this operation returns up to 50 metric filters. If there are
+// more metric filters to list, the response would contain a nextToken value
+// in the response body. You can also limit the number of metric filters returned
+// in the response by specifying the limit parameter in the request.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DescribeMetricFilters for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DescribeMetricFilters(input *DescribeMetricFiltersInput) (*DescribeMetricFiltersOutput, error) {
+ req, out := c.DescribeMetricFiltersRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+// DescribeMetricFiltersPages iterates over the pages of a DescribeMetricFilters operation,
+// calling the "fn" function with the response data for each page. To stop
+// iterating, return false from the fn function.
+//
+// See DescribeMetricFilters method for more information on how to use this operation.
+//
+// Note: This operation can generate multiple requests to a service.
+//
+// // Example iterating over at most 3 pages of a DescribeMetricFilters operation.
+// pageNum := 0
+// err := client.DescribeMetricFiltersPages(params,
+// func(page *DescribeMetricFiltersOutput, lastPage bool) bool {
+// pageNum++
+// fmt.Println(page)
+// return pageNum <= 3
+// })
+//
+func (c *CloudWatchLogs) DescribeMetricFiltersPages(input *DescribeMetricFiltersInput, fn func(p *DescribeMetricFiltersOutput, lastPage bool) (shouldContinue bool)) error {
+ page, _ := c.DescribeMetricFiltersRequest(input)
+ page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator"))
+ return page.EachPage(func(p interface{}, lastPage bool) bool {
+ return fn(p.(*DescribeMetricFiltersOutput), lastPage)
+ })
+}
+
+const opDescribeSubscriptionFilters = "DescribeSubscriptionFilters"
+
+// DescribeSubscriptionFiltersRequest generates a "aws/request.Request" representing the
+// client's request for the DescribeSubscriptionFilters operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DescribeSubscriptionFilters for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DescribeSubscriptionFilters method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DescribeSubscriptionFiltersRequest method.
+// req, resp := client.DescribeSubscriptionFiltersRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) DescribeSubscriptionFiltersRequest(input *DescribeSubscriptionFiltersInput) (req *request.Request, output *DescribeSubscriptionFiltersOutput) {
+ op := &request.Operation{
+ Name: opDescribeSubscriptionFilters,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ Paginator: &request.Paginator{
+ InputTokens: []string{"nextToken"},
+ OutputTokens: []string{"nextToken"},
+ LimitToken: "limit",
+ TruncationToken: "",
+ },
+ }
+
+ if input == nil {
+ input = &DescribeSubscriptionFiltersInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &DescribeSubscriptionFiltersOutput{}
+ req.Data = output
+ return
+}
+
+// DescribeSubscriptionFilters API operation for Amazon CloudWatch Logs.
+//
+// Returns all the subscription filters associated with the specified log group.
+// The list returned in the response is ASCII-sorted by filter name.
+//
+// By default, this operation returns up to 50 subscription filters. If there
+// are more subscription filters to list, the response would contain a nextToken
+// value in the response body. You can also limit the number of subscription
+// filters returned in the response by specifying the limit parameter in the
+// request.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation DescribeSubscriptionFilters for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) DescribeSubscriptionFilters(input *DescribeSubscriptionFiltersInput) (*DescribeSubscriptionFiltersOutput, error) {
+ req, out := c.DescribeSubscriptionFiltersRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+// DescribeSubscriptionFiltersPages iterates over the pages of a DescribeSubscriptionFilters operation,
+// calling the "fn" function with the response data for each page. To stop
+// iterating, return false from the fn function.
+//
+// See DescribeSubscriptionFilters method for more information on how to use this operation.
+//
+// Note: This operation can generate multiple requests to a service.
+//
+// // Example iterating over at most 3 pages of a DescribeSubscriptionFilters operation.
+// pageNum := 0
+// err := client.DescribeSubscriptionFiltersPages(params,
+// func(page *DescribeSubscriptionFiltersOutput, lastPage bool) bool {
+// pageNum++
+// fmt.Println(page)
+// return pageNum <= 3
+// })
+//
+func (c *CloudWatchLogs) DescribeSubscriptionFiltersPages(input *DescribeSubscriptionFiltersInput, fn func(p *DescribeSubscriptionFiltersOutput, lastPage bool) (shouldContinue bool)) error {
+ page, _ := c.DescribeSubscriptionFiltersRequest(input)
+ page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator"))
+ return page.EachPage(func(p interface{}, lastPage bool) bool {
+ return fn(p.(*DescribeSubscriptionFiltersOutput), lastPage)
+ })
+}
+
+const opFilterLogEvents = "FilterLogEvents"
+
+// FilterLogEventsRequest generates a "aws/request.Request" representing the
+// client's request for the FilterLogEvents operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See FilterLogEvents for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the FilterLogEvents method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the FilterLogEventsRequest method.
+// req, resp := client.FilterLogEventsRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) FilterLogEventsRequest(input *FilterLogEventsInput) (req *request.Request, output *FilterLogEventsOutput) {
+ op := &request.Operation{
+ Name: opFilterLogEvents,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ Paginator: &request.Paginator{
+ InputTokens: []string{"nextToken"},
+ OutputTokens: []string{"nextToken"},
+ LimitToken: "limit",
+ TruncationToken: "",
+ },
+ }
+
+ if input == nil {
+ input = &FilterLogEventsInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &FilterLogEventsOutput{}
+ req.Data = output
+ return
+}
+
+// FilterLogEvents API operation for Amazon CloudWatch Logs.
+//
+// Retrieves log events, optionally filtered by a filter pattern from the specified
+// log group. You can provide an optional time range to filter the results on
+// the event timestamp. You can limit the streams searched to an explicit list
+// of logStreamNames.
+//
+// By default, this operation returns as much matching log events as can fit
+// in a response size of 1MB, up to 10,000 log events, or all the events found
+// within a time-bounded scan window. If the response includes a nextToken,
+// then there is more data to search, and the search can be resumed with a new
+// request providing the nextToken. The response will contain a list of searchedLogStreams
+// that contains information about which streams were searched in the request
+// and whether they have been searched completely or require further pagination.
+// The limit parameter in the request can be used to specify the maximum number
+// of events to return in a page.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation FilterLogEvents for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) FilterLogEvents(input *FilterLogEventsInput) (*FilterLogEventsOutput, error) {
+ req, out := c.FilterLogEventsRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+// FilterLogEventsPages iterates over the pages of a FilterLogEvents operation,
+// calling the "fn" function with the response data for each page. To stop
+// iterating, return false from the fn function.
+//
+// See FilterLogEvents method for more information on how to use this operation.
+//
+// Note: This operation can generate multiple requests to a service.
+//
+// // Example iterating over at most 3 pages of a FilterLogEvents operation.
+// pageNum := 0
+// err := client.FilterLogEventsPages(params,
+// func(page *FilterLogEventsOutput, lastPage bool) bool {
+// pageNum++
+// fmt.Println(page)
+// return pageNum <= 3
+// })
+//
+func (c *CloudWatchLogs) FilterLogEventsPages(input *FilterLogEventsInput, fn func(p *FilterLogEventsOutput, lastPage bool) (shouldContinue bool)) error {
+ page, _ := c.FilterLogEventsRequest(input)
+ page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator"))
+ return page.EachPage(func(p interface{}, lastPage bool) bool {
+ return fn(p.(*FilterLogEventsOutput), lastPage)
+ })
+}
+
+const opGetLogEvents = "GetLogEvents"
+
+// GetLogEventsRequest generates a "aws/request.Request" representing the
+// client's request for the GetLogEvents operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See GetLogEvents for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the GetLogEvents method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the GetLogEventsRequest method.
+// req, resp := client.GetLogEventsRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) GetLogEventsRequest(input *GetLogEventsInput) (req *request.Request, output *GetLogEventsOutput) {
+ op := &request.Operation{
+ Name: opGetLogEvents,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ Paginator: &request.Paginator{
+ InputTokens: []string{"nextToken"},
+ OutputTokens: []string{"nextForwardToken"},
+ LimitToken: "limit",
+ TruncationToken: "",
+ },
+ }
+
+ if input == nil {
+ input = &GetLogEventsInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &GetLogEventsOutput{}
+ req.Data = output
+ return
+}
+
+// GetLogEvents API operation for Amazon CloudWatch Logs.
+//
+// Retrieves log events from the specified log stream. You can provide an optional
+// time range to filter the results on the event timestamp.
+//
+// By default, this operation returns as much log events as can fit in a response
+// size of 1MB, up to 10,000 log events. The response will always include a
+// nextForwardToken and a nextBackwardToken in the response body. You can use
+// any of these tokens in subsequent GetLogEvents requests to paginate through
+// events in either forward or backward direction. You can also limit the number
+// of log events returned in the response by specifying the limit parameter
+// in the request.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation GetLogEvents for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) GetLogEvents(input *GetLogEventsInput) (*GetLogEventsOutput, error) {
+ req, out := c.GetLogEventsRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+// GetLogEventsPages iterates over the pages of a GetLogEvents operation,
+// calling the "fn" function with the response data for each page. To stop
+// iterating, return false from the fn function.
+//
+// See GetLogEvents method for more information on how to use this operation.
+//
+// Note: This operation can generate multiple requests to a service.
+//
+// // Example iterating over at most 3 pages of a GetLogEvents operation.
+// pageNum := 0
+// err := client.GetLogEventsPages(params,
+// func(page *GetLogEventsOutput, lastPage bool) bool {
+// pageNum++
+// fmt.Println(page)
+// return pageNum <= 3
+// })
+//
+func (c *CloudWatchLogs) GetLogEventsPages(input *GetLogEventsInput, fn func(p *GetLogEventsOutput, lastPage bool) (shouldContinue bool)) error {
+ page, _ := c.GetLogEventsRequest(input)
+ page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator"))
+ return page.EachPage(func(p interface{}, lastPage bool) bool {
+ return fn(p.(*GetLogEventsOutput), lastPage)
+ })
+}
+
+const opPutDestination = "PutDestination"
+
+// PutDestinationRequest generates a "aws/request.Request" representing the
+// client's request for the PutDestination operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See PutDestination for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the PutDestination method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the PutDestinationRequest method.
+// req, resp := client.PutDestinationRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) PutDestinationRequest(input *PutDestinationInput) (req *request.Request, output *PutDestinationOutput) {
+ op := &request.Operation{
+ Name: opPutDestination,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &PutDestinationInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &PutDestinationOutput{}
+ req.Data = output
+ return
+}
+
+// PutDestination API operation for Amazon CloudWatch Logs.
+//
+// Creates or updates a Destination. A destination encapsulates a physical resource
+// (such as a Kinesis stream) and allows you to subscribe to a real-time stream
+// of log events of a different account, ingested through PutLogEvents requests.
+// Currently, the only supported physical resource is a Amazon Kinesis stream
+// belonging to the same account as the destination.
+//
+// A destination controls what is written to its Amazon Kinesis stream through
+// an access policy. By default, PutDestination does not set any access policy
+// with the destination, which means a cross-account user will not be able to
+// call PutSubscriptionFilter against this destination. To enable that, the
+// destination owner must call PutDestinationPolicy after PutDestination.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation PutDestination for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) PutDestination(input *PutDestinationInput) (*PutDestinationOutput, error) {
+ req, out := c.PutDestinationRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opPutDestinationPolicy = "PutDestinationPolicy"
+
+// PutDestinationPolicyRequest generates a "aws/request.Request" representing the
+// client's request for the PutDestinationPolicy operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See PutDestinationPolicy for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the PutDestinationPolicy method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the PutDestinationPolicyRequest method.
+// req, resp := client.PutDestinationPolicyRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) PutDestinationPolicyRequest(input *PutDestinationPolicyInput) (req *request.Request, output *PutDestinationPolicyOutput) {
+ op := &request.Operation{
+ Name: opPutDestinationPolicy,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &PutDestinationPolicyInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &PutDestinationPolicyOutput{}
+ req.Data = output
+ return
+}
+
+// PutDestinationPolicy API operation for Amazon CloudWatch Logs.
+//
+// Creates or updates an access policy associated with an existing Destination.
+// An access policy is an IAM policy document (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies_overview.html)
+// that is used to authorize claims to register a subscription filter against
+// a given destination.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation PutDestinationPolicy for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) PutDestinationPolicy(input *PutDestinationPolicyInput) (*PutDestinationPolicyOutput, error) {
+ req, out := c.PutDestinationPolicyRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opPutLogEvents = "PutLogEvents"
+
+// PutLogEventsRequest generates a "aws/request.Request" representing the
+// client's request for the PutLogEvents operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See PutLogEvents for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the PutLogEvents method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the PutLogEventsRequest method.
+// req, resp := client.PutLogEventsRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) PutLogEventsRequest(input *PutLogEventsInput) (req *request.Request, output *PutLogEventsOutput) {
+ op := &request.Operation{
+ Name: opPutLogEvents,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &PutLogEventsInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &PutLogEventsOutput{}
+ req.Data = output
+ return
+}
+
+// PutLogEvents API operation for Amazon CloudWatch Logs.
+//
+// Uploads a batch of log events to the specified log stream.
+//
+// Every PutLogEvents request must include the sequenceToken obtained from the
+// response of the previous request. An upload in a newly created log stream
+// does not require a sequenceToken. You can also get the sequenceToken using
+// DescribeLogStreams.
+//
+// The batch of events must satisfy the following constraints:
+//
+// * The maximum batch size is 1,048,576 bytes, and this size is calculated
+// as the sum of all event messages in UTF-8, plus 26 bytes for each log
+// event.
+//
+// * None of the log events in the batch can be more than 2 hours in the
+// future.
+//
+// * None of the log events in the batch can be older than 14 days or the
+// retention period of the log group.
+//
+// * The log events in the batch must be in chronological ordered by their
+// timestamp.
+//
+// * The maximum number of log events in a batch is 10,000.
+//
+// * A batch of log events in a single PutLogEvents request cannot span more
+// than 24 hours. Otherwise, the PutLogEvents operation will fail.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation PutLogEvents for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * InvalidSequenceTokenException
+
+//
+// * DataAlreadyAcceptedException
+
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) PutLogEvents(input *PutLogEventsInput) (*PutLogEventsOutput, error) {
+ req, out := c.PutLogEventsRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opPutMetricFilter = "PutMetricFilter"
+
+// PutMetricFilterRequest generates a "aws/request.Request" representing the
+// client's request for the PutMetricFilter operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See PutMetricFilter for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the PutMetricFilter method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the PutMetricFilterRequest method.
+// req, resp := client.PutMetricFilterRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) PutMetricFilterRequest(input *PutMetricFilterInput) (req *request.Request, output *PutMetricFilterOutput) {
+ op := &request.Operation{
+ Name: opPutMetricFilter,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &PutMetricFilterInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &PutMetricFilterOutput{}
+ req.Data = output
+ return
+}
+
+// PutMetricFilter API operation for Amazon CloudWatch Logs.
+//
+// Creates or updates a metric filter and associates it with the specified log
+// group. Metric filters allow you to configure rules to extract metric data
+// from log events ingested through PutLogEvents requests.
+//
+// The maximum number of metric filters that can be associated with a log group
+// is 100.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation PutMetricFilter for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * LimitExceededException
+// Returned if you have reached the maximum number of resources that can be
+// created.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) PutMetricFilter(input *PutMetricFilterInput) (*PutMetricFilterOutput, error) {
+ req, out := c.PutMetricFilterRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opPutRetentionPolicy = "PutRetentionPolicy"
+
+// PutRetentionPolicyRequest generates a "aws/request.Request" representing the
+// client's request for the PutRetentionPolicy operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See PutRetentionPolicy for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the PutRetentionPolicy method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the PutRetentionPolicyRequest method.
+// req, resp := client.PutRetentionPolicyRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) PutRetentionPolicyRequest(input *PutRetentionPolicyInput) (req *request.Request, output *PutRetentionPolicyOutput) {
+ op := &request.Operation{
+ Name: opPutRetentionPolicy,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &PutRetentionPolicyInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &PutRetentionPolicyOutput{}
+ req.Data = output
+ return
+}
+
+// PutRetentionPolicy API operation for Amazon CloudWatch Logs.
+//
+// Sets the retention of the specified log group. A retention policy allows
+// you to configure the number of days you want to retain log events in the
+// specified log group.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation PutRetentionPolicy for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) PutRetentionPolicy(input *PutRetentionPolicyInput) (*PutRetentionPolicyOutput, error) {
+ req, out := c.PutRetentionPolicyRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opPutSubscriptionFilter = "PutSubscriptionFilter"
+
+// PutSubscriptionFilterRequest generates a "aws/request.Request" representing the
+// client's request for the PutSubscriptionFilter operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See PutSubscriptionFilter for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the PutSubscriptionFilter method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the PutSubscriptionFilterRequest method.
+// req, resp := client.PutSubscriptionFilterRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) PutSubscriptionFilterRequest(input *PutSubscriptionFilterInput) (req *request.Request, output *PutSubscriptionFilterOutput) {
+ op := &request.Operation{
+ Name: opPutSubscriptionFilter,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &PutSubscriptionFilterInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)
+ req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
+ output = &PutSubscriptionFilterOutput{}
+ req.Data = output
+ return
+}
+
+// PutSubscriptionFilter API operation for Amazon CloudWatch Logs.
+//
+// Creates or updates a subscription filter and associates it with the specified
+// log group. Subscription filters allow you to subscribe to a real-time stream
+// of log events ingested through PutLogEvents requests and have them delivered
+// to a specific destination. Currently, the supported destinations are:
+//
+// * An Amazon Kinesis stream belonging to the same account as the subscription
+// filter, for same-account delivery.
+//
+// * A logical destination (used via an ARN of Destination) belonging to
+// a different account, for cross-account delivery.
+//
+// * An Amazon Kinesis Firehose stream belonging to the same account as the
+// subscription filter, for same-account delivery.
+//
+// * An AWS Lambda function belonging to the same account as the subscription
+// filter, for same-account delivery.
+//
+// Currently there can only be one subscription filter associated with a log
+// group.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation PutSubscriptionFilter for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ResourceNotFoundException
+// Returned if the specified resource does not exist.
+//
+// * OperationAbortedException
+// Returned if multiple requests to update the same resource were in conflict.
+//
+// * LimitExceededException
+// Returned if you have reached the maximum number of resources that can be
+// created.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) PutSubscriptionFilter(input *PutSubscriptionFilterInput) (*PutSubscriptionFilterOutput, error) {
+ req, out := c.PutSubscriptionFilterRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opTestMetricFilter = "TestMetricFilter"
+
+// TestMetricFilterRequest generates a "aws/request.Request" representing the
+// client's request for the TestMetricFilter operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See TestMetricFilter for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the TestMetricFilter method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the TestMetricFilterRequest method.
+// req, resp := client.TestMetricFilterRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *CloudWatchLogs) TestMetricFilterRequest(input *TestMetricFilterInput) (req *request.Request, output *TestMetricFilterOutput) {
+ op := &request.Operation{
+ Name: opTestMetricFilter,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &TestMetricFilterInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &TestMetricFilterOutput{}
+ req.Data = output
+ return
+}
+
+// TestMetricFilter API operation for Amazon CloudWatch Logs.
+//
+// Tests the filter pattern of a metric filter against a sample of log event
+// messages. You can use this operation to validate the correctness of a metric
+// filter pattern.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for Amazon CloudWatch Logs's
+// API operation TestMetricFilter for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidParameterException
+// Returned if a parameter of the request is incorrectly specified.
+//
+// * ServiceUnavailableException
+// Returned if the service cannot complete the request.
+//
+func (c *CloudWatchLogs) TestMetricFilter(input *TestMetricFilterInput) (*TestMetricFilterOutput, error) {
+ req, out := c.TestMetricFilterRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+type CancelExportTaskInput struct {
+ _ struct{} `type:"structure"`
+
+ // Id of the export task to cancel.
+ //
+ // TaskId is a required field
+ TaskId *string `locationName:"taskId" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s CancelExportTaskInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s CancelExportTaskInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *CancelExportTaskInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "CancelExportTaskInput"}
+ if s.TaskId == nil {
+ invalidParams.Add(request.NewErrParamRequired("TaskId"))
+ }
+ if s.TaskId != nil && len(*s.TaskId) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("TaskId", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type CancelExportTaskOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s CancelExportTaskOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s CancelExportTaskOutput) GoString() string {
+ return s.String()
+}
+
+type CreateExportTaskInput struct {
+ _ struct{} `type:"structure"`
+
+ // Name of Amazon S3 bucket to which the log data will be exported.
+ //
+ // Note: Only buckets in the same AWS region are supported.
+ //
+ // Destination is a required field
+ Destination *string `locationName:"destination" min:"1" type:"string" required:"true"`
+
+ // Prefix that will be used as the start of Amazon S3 key for every object exported.
+ // If not specified, this defaults to 'exportedlogs'.
+ DestinationPrefix *string `locationName:"destinationPrefix" type:"string"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC. It indicates the start time of the range for the request. Events
+ // with a timestamp prior to this time will not be exported.
+ //
+ // From is a required field
+ From *int64 `locationName:"from" type:"long" required:"true"`
+
+ // The name of the log group to export.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // Will only export log streams that match the provided logStreamNamePrefix.
+ // If you don't specify a value, no prefix filter is applied.
+ LogStreamNamePrefix *string `locationName:"logStreamNamePrefix" min:"1" type:"string"`
+
+ // The name of the export task.
+ TaskName *string `locationName:"taskName" min:"1" type:"string"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC. It indicates the end time of the range for the request. Events
+ // with a timestamp later than this time will not be exported.
+ //
+ // To is a required field
+ To *int64 `locationName:"to" type:"long" required:"true"`
+}
+
+// String returns the string representation
+func (s CreateExportTaskInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s CreateExportTaskInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *CreateExportTaskInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "CreateExportTaskInput"}
+ if s.Destination == nil {
+ invalidParams.Add(request.NewErrParamRequired("Destination"))
+ }
+ if s.Destination != nil && len(*s.Destination) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("Destination", 1))
+ }
+ if s.From == nil {
+ invalidParams.Add(request.NewErrParamRequired("From"))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.LogStreamNamePrefix != nil && len(*s.LogStreamNamePrefix) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogStreamNamePrefix", 1))
+ }
+ if s.TaskName != nil && len(*s.TaskName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("TaskName", 1))
+ }
+ if s.To == nil {
+ invalidParams.Add(request.NewErrParamRequired("To"))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type CreateExportTaskOutput struct {
+ _ struct{} `type:"structure"`
+
+ // Id of the export task that got created.
+ TaskId *string `locationName:"taskId" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s CreateExportTaskOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s CreateExportTaskOutput) GoString() string {
+ return s.String()
+}
+
+type CreateLogGroupInput struct {
+ _ struct{} `type:"structure"`
+
+ // The name of the log group to create.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s CreateLogGroupInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s CreateLogGroupInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *CreateLogGroupInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "CreateLogGroupInput"}
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type CreateLogGroupOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s CreateLogGroupOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s CreateLogGroupOutput) GoString() string {
+ return s.String()
+}
+
+type CreateLogStreamInput struct {
+ _ struct{} `type:"structure"`
+
+ // The name of the log group under which the log stream is to be created.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // The name of the log stream to create.
+ //
+ // LogStreamName is a required field
+ LogStreamName *string `locationName:"logStreamName" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s CreateLogStreamInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s CreateLogStreamInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *CreateLogStreamInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "CreateLogStreamInput"}
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.LogStreamName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogStreamName"))
+ }
+ if s.LogStreamName != nil && len(*s.LogStreamName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogStreamName", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type CreateLogStreamOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s CreateLogStreamOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s CreateLogStreamOutput) GoString() string {
+ return s.String()
+}
+
+type DeleteDestinationInput struct {
+ _ struct{} `type:"structure"`
+
+ // The name of destination to delete.
+ //
+ // DestinationName is a required field
+ DestinationName *string `locationName:"destinationName" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s DeleteDestinationInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteDestinationInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DeleteDestinationInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DeleteDestinationInput"}
+ if s.DestinationName == nil {
+ invalidParams.Add(request.NewErrParamRequired("DestinationName"))
+ }
+ if s.DestinationName != nil && len(*s.DestinationName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("DestinationName", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DeleteDestinationOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s DeleteDestinationOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteDestinationOutput) GoString() string {
+ return s.String()
+}
+
+type DeleteLogGroupInput struct {
+ _ struct{} `type:"structure"`
+
+ // The name of the log group to delete.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s DeleteLogGroupInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteLogGroupInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DeleteLogGroupInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DeleteLogGroupInput"}
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DeleteLogGroupOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s DeleteLogGroupOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteLogGroupOutput) GoString() string {
+ return s.String()
+}
+
+type DeleteLogStreamInput struct {
+ _ struct{} `type:"structure"`
+
+ // The name of the log group under which the log stream to delete belongs.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // The name of the log stream to delete.
+ //
+ // LogStreamName is a required field
+ LogStreamName *string `locationName:"logStreamName" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s DeleteLogStreamInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteLogStreamInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DeleteLogStreamInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DeleteLogStreamInput"}
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.LogStreamName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogStreamName"))
+ }
+ if s.LogStreamName != nil && len(*s.LogStreamName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogStreamName", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DeleteLogStreamOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s DeleteLogStreamOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteLogStreamOutput) GoString() string {
+ return s.String()
+}
+
+type DeleteMetricFilterInput struct {
+ _ struct{} `type:"structure"`
+
+ // The name of the metric filter to delete.
+ //
+ // FilterName is a required field
+ FilterName *string `locationName:"filterName" min:"1" type:"string" required:"true"`
+
+ // The name of the log group that is associated with the metric filter to delete.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s DeleteMetricFilterInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteMetricFilterInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DeleteMetricFilterInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DeleteMetricFilterInput"}
+ if s.FilterName == nil {
+ invalidParams.Add(request.NewErrParamRequired("FilterName"))
+ }
+ if s.FilterName != nil && len(*s.FilterName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("FilterName", 1))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DeleteMetricFilterOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s DeleteMetricFilterOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteMetricFilterOutput) GoString() string {
+ return s.String()
+}
+
+type DeleteRetentionPolicyInput struct {
+ _ struct{} `type:"structure"`
+
+ // The name of the log group that is associated with the retention policy to
+ // delete.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s DeleteRetentionPolicyInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteRetentionPolicyInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DeleteRetentionPolicyInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DeleteRetentionPolicyInput"}
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DeleteRetentionPolicyOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s DeleteRetentionPolicyOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteRetentionPolicyOutput) GoString() string {
+ return s.String()
+}
+
+type DeleteSubscriptionFilterInput struct {
+ _ struct{} `type:"structure"`
+
+ // The name of the subscription filter to delete.
+ //
+ // FilterName is a required field
+ FilterName *string `locationName:"filterName" min:"1" type:"string" required:"true"`
+
+ // The name of the log group that is associated with the subscription filter
+ // to delete.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s DeleteSubscriptionFilterInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteSubscriptionFilterInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DeleteSubscriptionFilterInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DeleteSubscriptionFilterInput"}
+ if s.FilterName == nil {
+ invalidParams.Add(request.NewErrParamRequired("FilterName"))
+ }
+ if s.FilterName != nil && len(*s.FilterName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("FilterName", 1))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DeleteSubscriptionFilterOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s DeleteSubscriptionFilterOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DeleteSubscriptionFilterOutput) GoString() string {
+ return s.String()
+}
+
+type DescribeDestinationsInput struct {
+ _ struct{} `type:"structure"`
+
+ // Will only return destinations that match the provided destinationNamePrefix.
+ // If you don't specify a value, no prefix is applied.
+ DestinationNamePrefix *string `min:"1" type:"string"`
+
+ // The maximum number of results to return.
+ Limit *int64 `locationName:"limit" min:"1" type:"integer"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous request. The
+ // token expires after 24 hours.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s DescribeDestinationsInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeDestinationsInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DescribeDestinationsInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DescribeDestinationsInput"}
+ if s.DestinationNamePrefix != nil && len(*s.DestinationNamePrefix) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("DestinationNamePrefix", 1))
+ }
+ if s.Limit != nil && *s.Limit < 1 {
+ invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
+ }
+ if s.NextToken != nil && len(*s.NextToken) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("NextToken", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DescribeDestinationsOutput struct {
+ _ struct{} `type:"structure"`
+
+ Destinations []*Destination `locationName:"destinations" type:"list"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous request. The
+ // token expires after 24 hours.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s DescribeDestinationsOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeDestinationsOutput) GoString() string {
+ return s.String()
+}
+
+type DescribeExportTasksInput struct {
+ _ struct{} `type:"structure"`
+
+ // The maximum number of items returned in the response. If you don't specify
+ // a value, the request would return up to 50 items.
+ Limit *int64 `locationName:"limit" min:"1" type:"integer"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous DescribeExportTasks
+ // request.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+
+ // All export tasks that matches the specified status code will be returned.
+ // This can return zero or more export tasks.
+ StatusCode *string `locationName:"statusCode" type:"string" enum:"ExportTaskStatusCode"`
+
+ // Export task that matches the specified task Id will be returned. This can
+ // result in zero or one export task.
+ TaskId *string `locationName:"taskId" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s DescribeExportTasksInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeExportTasksInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DescribeExportTasksInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DescribeExportTasksInput"}
+ if s.Limit != nil && *s.Limit < 1 {
+ invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
+ }
+ if s.NextToken != nil && len(*s.NextToken) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("NextToken", 1))
+ }
+ if s.TaskId != nil && len(*s.TaskId) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("TaskId", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DescribeExportTasksOutput struct {
+ _ struct{} `type:"structure"`
+
+ // A list of export tasks.
+ ExportTasks []*ExportTask `locationName:"exportTasks" type:"list"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous request. The
+ // token expires after 24 hours.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s DescribeExportTasksOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeExportTasksOutput) GoString() string {
+ return s.String()
+}
+
+type DescribeLogGroupsInput struct {
+ _ struct{} `type:"structure"`
+
+ // The maximum number of items returned in the response. If you don't specify
+ // a value, the request would return up to 50 items.
+ Limit *int64 `locationName:"limit" min:"1" type:"integer"`
+
+ // Will only return log groups that match the provided logGroupNamePrefix. If
+ // you don't specify a value, no prefix filter is applied.
+ LogGroupNamePrefix *string `locationName:"logGroupNamePrefix" min:"1" type:"string"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous DescribeLogGroups
+ // request.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s DescribeLogGroupsInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeLogGroupsInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DescribeLogGroupsInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DescribeLogGroupsInput"}
+ if s.Limit != nil && *s.Limit < 1 {
+ invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
+ }
+ if s.LogGroupNamePrefix != nil && len(*s.LogGroupNamePrefix) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupNamePrefix", 1))
+ }
+ if s.NextToken != nil && len(*s.NextToken) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("NextToken", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DescribeLogGroupsOutput struct {
+ _ struct{} `type:"structure"`
+
+ // A list of log groups.
+ LogGroups []*LogGroup `locationName:"logGroups" type:"list"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous request. The
+ // token expires after 24 hours.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s DescribeLogGroupsOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeLogGroupsOutput) GoString() string {
+ return s.String()
+}
+
+type DescribeLogStreamsInput struct {
+ _ struct{} `type:"structure"`
+
+ // If set to true, results are returned in descending order. If you don't specify
+ // a value or set it to false, results are returned in ascending order.
+ Descending *bool `locationName:"descending" type:"boolean"`
+
+ // The maximum number of items returned in the response. If you don't specify
+ // a value, the request would return up to 50 items.
+ Limit *int64 `locationName:"limit" min:"1" type:"integer"`
+
+ // The log group name for which log streams are to be listed.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // Will only return log streams that match the provided logStreamNamePrefix.
+ // If you don't specify a value, no prefix filter is applied.
+ LogStreamNamePrefix *string `locationName:"logStreamNamePrefix" min:"1" type:"string"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous DescribeLogStreams
+ // request.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+
+ // Specifies what to order the returned log streams by. Valid arguments are
+ // 'LogStreamName' or 'LastEventTime'. If you don't specify a value, results
+ // are ordered by LogStreamName. If 'LastEventTime' is chosen, the request cannot
+ // also contain a logStreamNamePrefix.
+ OrderBy *string `locationName:"orderBy" type:"string" enum:"OrderBy"`
+}
+
+// String returns the string representation
+func (s DescribeLogStreamsInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeLogStreamsInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DescribeLogStreamsInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DescribeLogStreamsInput"}
+ if s.Limit != nil && *s.Limit < 1 {
+ invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.LogStreamNamePrefix != nil && len(*s.LogStreamNamePrefix) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogStreamNamePrefix", 1))
+ }
+ if s.NextToken != nil && len(*s.NextToken) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("NextToken", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DescribeLogStreamsOutput struct {
+ _ struct{} `type:"structure"`
+
+ // A list of log streams.
+ LogStreams []*LogStream `locationName:"logStreams" type:"list"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous request. The
+ // token expires after 24 hours.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s DescribeLogStreamsOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeLogStreamsOutput) GoString() string {
+ return s.String()
+}
+
+type DescribeMetricFiltersInput struct {
+ _ struct{} `type:"structure"`
+
+ // Will only return metric filters that match the provided filterNamePrefix.
+ // If you don't specify a value, no prefix filter is applied.
+ FilterNamePrefix *string `locationName:"filterNamePrefix" min:"1" type:"string"`
+
+ // The maximum number of items returned in the response. If you don't specify
+ // a value, the request would return up to 50 items.
+ Limit *int64 `locationName:"limit" min:"1" type:"integer"`
+
+ // The log group name for which metric filters are to be listed.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous DescribeMetricFilters
+ // request.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s DescribeMetricFiltersInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeMetricFiltersInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DescribeMetricFiltersInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DescribeMetricFiltersInput"}
+ if s.FilterNamePrefix != nil && len(*s.FilterNamePrefix) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("FilterNamePrefix", 1))
+ }
+ if s.Limit != nil && *s.Limit < 1 {
+ invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.NextToken != nil && len(*s.NextToken) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("NextToken", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DescribeMetricFiltersOutput struct {
+ _ struct{} `type:"structure"`
+
+ MetricFilters []*MetricFilter `locationName:"metricFilters" type:"list"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous request. The
+ // token expires after 24 hours.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s DescribeMetricFiltersOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeMetricFiltersOutput) GoString() string {
+ return s.String()
+}
+
+type DescribeSubscriptionFiltersInput struct {
+ _ struct{} `type:"structure"`
+
+ // Will only return subscription filters that match the provided filterNamePrefix.
+ // If you don't specify a value, no prefix filter is applied.
+ FilterNamePrefix *string `locationName:"filterNamePrefix" min:"1" type:"string"`
+
+ // The maximum number of results to return.
+ Limit *int64 `locationName:"limit" min:"1" type:"integer"`
+
+ // The log group name for which subscription filters are to be listed.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous request. The
+ // token expires after 24 hours.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s DescribeSubscriptionFiltersInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeSubscriptionFiltersInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DescribeSubscriptionFiltersInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DescribeSubscriptionFiltersInput"}
+ if s.FilterNamePrefix != nil && len(*s.FilterNamePrefix) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("FilterNamePrefix", 1))
+ }
+ if s.Limit != nil && *s.Limit < 1 {
+ invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.NextToken != nil && len(*s.NextToken) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("NextToken", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type DescribeSubscriptionFiltersOutput struct {
+ _ struct{} `type:"structure"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous request. The
+ // token expires after 24 hours.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+
+ SubscriptionFilters []*SubscriptionFilter `locationName:"subscriptionFilters" type:"list"`
+}
+
+// String returns the string representation
+func (s DescribeSubscriptionFiltersOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DescribeSubscriptionFiltersOutput) GoString() string {
+ return s.String()
+}
+
+// A cross account destination that is the recipient of subscription log events.
+type Destination struct {
+ _ struct{} `type:"structure"`
+
+ // An IAM policy document that governs which AWS accounts can create subscription
+ // filters against this destination.
+ AccessPolicy *string `locationName:"accessPolicy" min:"1" type:"string"`
+
+ // ARN of this destination.
+ Arn *string `locationName:"arn" type:"string"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC specifying when this destination was created.
+ CreationTime *int64 `locationName:"creationTime" type:"long"`
+
+ // Name of the destination.
+ DestinationName *string `locationName:"destinationName" min:"1" type:"string"`
+
+ // A role for impersonation for delivering log events to the target.
+ RoleArn *string `locationName:"roleArn" min:"1" type:"string"`
+
+ // ARN of the physical target where the log events will be delivered (eg. ARN
+ // of a Kinesis stream).
+ TargetArn *string `locationName:"targetArn" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s Destination) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s Destination) GoString() string {
+ return s.String()
+}
+
+// Represents an export task.
+type ExportTask struct {
+ _ struct{} `type:"structure"`
+
+ // Name of Amazon S3 bucket to which the log data was exported.
+ Destination *string `locationName:"destination" min:"1" type:"string"`
+
+ // Prefix that was used as the start of Amazon S3 key for every object exported.
+ DestinationPrefix *string `locationName:"destinationPrefix" type:"string"`
+
+ // Execution info about the export task.
+ ExecutionInfo *ExportTaskExecutionInfo `locationName:"executionInfo" type:"structure"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC. Events with a timestamp prior to this time are not exported.
+ From *int64 `locationName:"from" type:"long"`
+
+ // The name of the log group from which logs data was exported.
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"`
+
+ // Status of the export task.
+ Status *ExportTaskStatus `locationName:"status" type:"structure"`
+
+ // Id of the export task.
+ TaskId *string `locationName:"taskId" min:"1" type:"string"`
+
+ // The name of the export task.
+ TaskName *string `locationName:"taskName" min:"1" type:"string"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC. Events with a timestamp later than this time are not exported.
+ To *int64 `locationName:"to" type:"long"`
+}
+
+// String returns the string representation
+func (s ExportTask) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s ExportTask) GoString() string {
+ return s.String()
+}
+
+// Represents the status of an export task.
+type ExportTaskExecutionInfo struct {
+ _ struct{} `type:"structure"`
+
+ // A point in time when the export task got completed.
+ CompletionTime *int64 `locationName:"completionTime" type:"long"`
+
+ // A point in time when the export task got created.
+ CreationTime *int64 `locationName:"creationTime" type:"long"`
+}
+
+// String returns the string representation
+func (s ExportTaskExecutionInfo) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s ExportTaskExecutionInfo) GoString() string {
+ return s.String()
+}
+
+// Represents the status of an export task.
+type ExportTaskStatus struct {
+ _ struct{} `type:"structure"`
+
+ // Status code of the export task.
+ Code *string `locationName:"code" type:"string" enum:"ExportTaskStatusCode"`
+
+ // Status message related to the code.
+ Message *string `locationName:"message" type:"string"`
+}
+
+// String returns the string representation
+func (s ExportTaskStatus) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s ExportTaskStatus) GoString() string {
+ return s.String()
+}
+
+type FilterLogEventsInput struct {
+ _ struct{} `type:"structure"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC. If provided, events with a timestamp later than this time are
+ // not returned.
+ EndTime *int64 `locationName:"endTime" type:"long"`
+
+ // A valid CloudWatch Logs filter pattern to use for filtering the response.
+ // If not provided, all the events are matched.
+ FilterPattern *string `locationName:"filterPattern" type:"string"`
+
+ // If provided, the API will make a best effort to provide responses that contain
+ // events from multiple log streams within the log group interleaved in a single
+ // response. If not provided, all the matched log events in the first log stream
+ // will be searched first, then those in the next log stream, etc.
+ Interleaved *bool `locationName:"interleaved" type:"boolean"`
+
+ // The maximum number of events to return in a page of results. Default is 10,000
+ // events.
+ Limit *int64 `locationName:"limit" min:"1" type:"integer"`
+
+ // The name of the log group to query.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // Optional list of log stream names within the specified log group to search.
+ // Defaults to all the log streams in the log group.
+ LogStreamNames []*string `locationName:"logStreamNames" min:"1" type:"list"`
+
+ // A pagination token obtained from a FilterLogEvents response to continue paginating
+ // the FilterLogEvents results. This token is omitted from the response when
+ // there are no other events to display.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC. If provided, events with a timestamp prior to this time are
+ // not returned.
+ StartTime *int64 `locationName:"startTime" type:"long"`
+}
+
+// String returns the string representation
+func (s FilterLogEventsInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s FilterLogEventsInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *FilterLogEventsInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "FilterLogEventsInput"}
+ if s.Limit != nil && *s.Limit < 1 {
+ invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.LogStreamNames != nil && len(s.LogStreamNames) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogStreamNames", 1))
+ }
+ if s.NextToken != nil && len(*s.NextToken) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("NextToken", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type FilterLogEventsOutput struct {
+ _ struct{} `type:"structure"`
+
+ // A list of FilteredLogEvent objects representing the matched events from the
+ // request.
+ Events []*FilteredLogEvent `locationName:"events" type:"list"`
+
+ // A pagination token obtained from a FilterLogEvents response to continue paginating
+ // the FilterLogEvents results. This token is omitted from the response when
+ // there are no other events to display.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+
+ // A list of SearchedLogStream objects indicating which log streams have been
+ // searched in this request and whether each has been searched completely or
+ // still has more to be paginated.
+ SearchedLogStreams []*SearchedLogStream `locationName:"searchedLogStreams" type:"list"`
+}
+
+// String returns the string representation
+func (s FilterLogEventsOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s FilterLogEventsOutput) GoString() string {
+ return s.String()
+}
+
+// Represents a matched event from a FilterLogEvents request.
+type FilteredLogEvent struct {
+ _ struct{} `type:"structure"`
+
+ // A unique identifier for this event.
+ EventId *string `locationName:"eventId" type:"string"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ IngestionTime *int64 `locationName:"ingestionTime" type:"long"`
+
+ // The name of the log stream this event belongs to.
+ LogStreamName *string `locationName:"logStreamName" min:"1" type:"string"`
+
+ // The data contained in the log event.
+ Message *string `locationName:"message" min:"1" type:"string"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ Timestamp *int64 `locationName:"timestamp" type:"long"`
+}
+
+// String returns the string representation
+func (s FilteredLogEvent) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s FilteredLogEvent) GoString() string {
+ return s.String()
+}
+
+type GetLogEventsInput struct {
+ _ struct{} `type:"structure"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ EndTime *int64 `locationName:"endTime" type:"long"`
+
+ // The maximum number of log events returned in the response. If you don't specify
+ // a value, the request would return as many log events as can fit in a response
+ // size of 1MB, up to 10,000 log events.
+ Limit *int64 `locationName:"limit" min:"1" type:"integer"`
+
+ // The name of the log group to query.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // The name of the log stream to query.
+ //
+ // LogStreamName is a required field
+ LogStreamName *string `locationName:"logStreamName" min:"1" type:"string" required:"true"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the nextForwardToken or nextBackwardToken
+ // fields in the response of the previous GetLogEvents request.
+ NextToken *string `locationName:"nextToken" min:"1" type:"string"`
+
+ // If set to true, the earliest log events would be returned first. The default
+ // is false (the latest log events are returned first).
+ StartFromHead *bool `locationName:"startFromHead" type:"boolean"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ StartTime *int64 `locationName:"startTime" type:"long"`
+}
+
+// String returns the string representation
+func (s GetLogEventsInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s GetLogEventsInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *GetLogEventsInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "GetLogEventsInput"}
+ if s.Limit != nil && *s.Limit < 1 {
+ invalidParams.Add(request.NewErrParamMinValue("Limit", 1))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.LogStreamName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogStreamName"))
+ }
+ if s.LogStreamName != nil && len(*s.LogStreamName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogStreamName", 1))
+ }
+ if s.NextToken != nil && len(*s.NextToken) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("NextToken", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type GetLogEventsOutput struct {
+ _ struct{} `type:"structure"`
+
+ Events []*OutputLogEvent `locationName:"events" type:"list"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous request. The
+ // token expires after 24 hours.
+ NextBackwardToken *string `locationName:"nextBackwardToken" min:"1" type:"string"`
+
+ // A string token used for pagination that points to the next page of results.
+ // It must be a value obtained from the response of the previous request. The
+ // token expires after 24 hours.
+ NextForwardToken *string `locationName:"nextForwardToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s GetLogEventsOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s GetLogEventsOutput) GoString() string {
+ return s.String()
+}
+
+// A log event is a record of some activity that was recorded by the application
+// or resource being monitored. The log event record that CloudWatch Logs understands
+// contains two properties: the timestamp of when the event occurred, and the
+// raw event message.
+type InputLogEvent struct {
+ _ struct{} `type:"structure"`
+
+ // Message is a required field
+ Message *string `locationName:"message" min:"1" type:"string" required:"true"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ //
+ // Timestamp is a required field
+ Timestamp *int64 `locationName:"timestamp" type:"long" required:"true"`
+}
+
+// String returns the string representation
+func (s InputLogEvent) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s InputLogEvent) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *InputLogEvent) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "InputLogEvent"}
+ if s.Message == nil {
+ invalidParams.Add(request.NewErrParamRequired("Message"))
+ }
+ if s.Message != nil && len(*s.Message) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("Message", 1))
+ }
+ if s.Timestamp == nil {
+ invalidParams.Add(request.NewErrParamRequired("Timestamp"))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type LogGroup struct {
+ _ struct{} `type:"structure"`
+
+ Arn *string `locationName:"arn" type:"string"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ CreationTime *int64 `locationName:"creationTime" type:"long"`
+
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"`
+
+ // The number of metric filters associated with the log group.
+ MetricFilterCount *int64 `locationName:"metricFilterCount" type:"integer"`
+
+ // Specifies the number of days you want to retain log events in the specified
+ // log group. Possible values are: 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180,
+ // 365, 400, 545, 731, 1827, 3653.
+ RetentionInDays *int64 `locationName:"retentionInDays" type:"integer"`
+
+ StoredBytes *int64 `locationName:"storedBytes" type:"long"`
+}
+
+// String returns the string representation
+func (s LogGroup) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s LogGroup) GoString() string {
+ return s.String()
+}
+
+// A log stream is sequence of log events from a single emitter of logs.
+type LogStream struct {
+ _ struct{} `type:"structure"`
+
+ Arn *string `locationName:"arn" type:"string"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ CreationTime *int64 `locationName:"creationTime" type:"long"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ FirstEventTimestamp *int64 `locationName:"firstEventTimestamp" type:"long"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ LastEventTimestamp *int64 `locationName:"lastEventTimestamp" type:"long"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ LastIngestionTime *int64 `locationName:"lastIngestionTime" type:"long"`
+
+ LogStreamName *string `locationName:"logStreamName" min:"1" type:"string"`
+
+ StoredBytes *int64 `locationName:"storedBytes" type:"long"`
+
+ // A string token used for making PutLogEvents requests. A sequenceToken can
+ // only be used once, and PutLogEvents requests must include the sequenceToken
+ // obtained from the response of the previous request.
+ UploadSequenceToken *string `locationName:"uploadSequenceToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s LogStream) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s LogStream) GoString() string {
+ return s.String()
+}
+
+// Metric filters can be used to express how CloudWatch Logs would extract metric
+// observations from ingested log events and transform them to metric data in
+// a CloudWatch metric.
+type MetricFilter struct {
+ _ struct{} `type:"structure"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ CreationTime *int64 `locationName:"creationTime" type:"long"`
+
+ // A name for a metric or subscription filter.
+ FilterName *string `locationName:"filterName" min:"1" type:"string"`
+
+ // A symbolic description of how CloudWatch Logs should interpret the data in
+ // each log event. For example, a log event may contain timestamps, IP addresses,
+ // strings, and so on. You use the filter pattern to specify what to look for
+ // in the log event message.
+ FilterPattern *string `locationName:"filterPattern" type:"string"`
+
+ MetricTransformations []*MetricTransformation `locationName:"metricTransformations" min:"1" type:"list"`
+}
+
+// String returns the string representation
+func (s MetricFilter) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s MetricFilter) GoString() string {
+ return s.String()
+}
+
+type MetricFilterMatchRecord struct {
+ _ struct{} `type:"structure"`
+
+ EventMessage *string `locationName:"eventMessage" min:"1" type:"string"`
+
+ EventNumber *int64 `locationName:"eventNumber" type:"long"`
+
+ ExtractedValues map[string]*string `locationName:"extractedValues" type:"map"`
+}
+
+// String returns the string representation
+func (s MetricFilterMatchRecord) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s MetricFilterMatchRecord) GoString() string {
+ return s.String()
+}
+
+type MetricTransformation struct {
+ _ struct{} `type:"structure"`
+
+ // (Optional) A default value to emit when a filter pattern does not match a
+ // log event. Can be null.
+ DefaultValue *float64 `locationName:"defaultValue" type:"double"`
+
+ // Name of the metric.
+ //
+ // MetricName is a required field
+ MetricName *string `locationName:"metricName" type:"string" required:"true"`
+
+ // Namespace to which the metric belongs.
+ //
+ // MetricNamespace is a required field
+ MetricNamespace *string `locationName:"metricNamespace" type:"string" required:"true"`
+
+ // A string representing a value to publish to this metric when a filter pattern
+ // matches a log event.
+ //
+ // MetricValue is a required field
+ MetricValue *string `locationName:"metricValue" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s MetricTransformation) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s MetricTransformation) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *MetricTransformation) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "MetricTransformation"}
+ if s.MetricName == nil {
+ invalidParams.Add(request.NewErrParamRequired("MetricName"))
+ }
+ if s.MetricNamespace == nil {
+ invalidParams.Add(request.NewErrParamRequired("MetricNamespace"))
+ }
+ if s.MetricValue == nil {
+ invalidParams.Add(request.NewErrParamRequired("MetricValue"))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type OutputLogEvent struct {
+ _ struct{} `type:"structure"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ IngestionTime *int64 `locationName:"ingestionTime" type:"long"`
+
+ Message *string `locationName:"message" min:"1" type:"string"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ Timestamp *int64 `locationName:"timestamp" type:"long"`
+}
+
+// String returns the string representation
+func (s OutputLogEvent) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s OutputLogEvent) GoString() string {
+ return s.String()
+}
+
+type PutDestinationInput struct {
+ _ struct{} `type:"structure"`
+
+ // A name for the destination.
+ //
+ // DestinationName is a required field
+ DestinationName *string `locationName:"destinationName" min:"1" type:"string" required:"true"`
+
+ // The ARN of an IAM role that grants CloudWatch Logs permissions to do Amazon
+ // Kinesis PutRecord requests on the destination stream.
+ //
+ // RoleArn is a required field
+ RoleArn *string `locationName:"roleArn" min:"1" type:"string" required:"true"`
+
+ // The ARN of an Amazon Kinesis stream to deliver matching log events to.
+ //
+ // TargetArn is a required field
+ TargetArn *string `locationName:"targetArn" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s PutDestinationInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutDestinationInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *PutDestinationInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "PutDestinationInput"}
+ if s.DestinationName == nil {
+ invalidParams.Add(request.NewErrParamRequired("DestinationName"))
+ }
+ if s.DestinationName != nil && len(*s.DestinationName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("DestinationName", 1))
+ }
+ if s.RoleArn == nil {
+ invalidParams.Add(request.NewErrParamRequired("RoleArn"))
+ }
+ if s.RoleArn != nil && len(*s.RoleArn) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("RoleArn", 1))
+ }
+ if s.TargetArn == nil {
+ invalidParams.Add(request.NewErrParamRequired("TargetArn"))
+ }
+ if s.TargetArn != nil && len(*s.TargetArn) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("TargetArn", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type PutDestinationOutput struct {
+ _ struct{} `type:"structure"`
+
+ // A cross account destination that is the recipient of subscription log events.
+ Destination *Destination `locationName:"destination" type:"structure"`
+}
+
+// String returns the string representation
+func (s PutDestinationOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutDestinationOutput) GoString() string {
+ return s.String()
+}
+
+type PutDestinationPolicyInput struct {
+ _ struct{} `type:"structure"`
+
+ // An IAM policy document that authorizes cross-account users to deliver their
+ // log events to associated destination.
+ //
+ // AccessPolicy is a required field
+ AccessPolicy *string `locationName:"accessPolicy" min:"1" type:"string" required:"true"`
+
+ // A name for an existing destination.
+ //
+ // DestinationName is a required field
+ DestinationName *string `locationName:"destinationName" min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s PutDestinationPolicyInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutDestinationPolicyInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *PutDestinationPolicyInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "PutDestinationPolicyInput"}
+ if s.AccessPolicy == nil {
+ invalidParams.Add(request.NewErrParamRequired("AccessPolicy"))
+ }
+ if s.AccessPolicy != nil && len(*s.AccessPolicy) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("AccessPolicy", 1))
+ }
+ if s.DestinationName == nil {
+ invalidParams.Add(request.NewErrParamRequired("DestinationName"))
+ }
+ if s.DestinationName != nil && len(*s.DestinationName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("DestinationName", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type PutDestinationPolicyOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s PutDestinationPolicyOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutDestinationPolicyOutput) GoString() string {
+ return s.String()
+}
+
+type PutLogEventsInput struct {
+ _ struct{} `type:"structure"`
+
+ // A list of log events belonging to a log stream.
+ //
+ // LogEvents is a required field
+ LogEvents []*InputLogEvent `locationName:"logEvents" min:"1" type:"list" required:"true"`
+
+ // The name of the log group to put log events to.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // The name of the log stream to put log events to.
+ //
+ // LogStreamName is a required field
+ LogStreamName *string `locationName:"logStreamName" min:"1" type:"string" required:"true"`
+
+ // A string token that must be obtained from the response of the previous PutLogEvents
+ // request.
+ SequenceToken *string `locationName:"sequenceToken" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s PutLogEventsInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutLogEventsInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *PutLogEventsInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "PutLogEventsInput"}
+ if s.LogEvents == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogEvents"))
+ }
+ if s.LogEvents != nil && len(s.LogEvents) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogEvents", 1))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.LogStreamName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogStreamName"))
+ }
+ if s.LogStreamName != nil && len(*s.LogStreamName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogStreamName", 1))
+ }
+ if s.SequenceToken != nil && len(*s.SequenceToken) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("SequenceToken", 1))
+ }
+ if s.LogEvents != nil {
+ for i, v := range s.LogEvents {
+ if v == nil {
+ continue
+ }
+ if err := v.Validate(); err != nil {
+ invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LogEvents", i), err.(request.ErrInvalidParams))
+ }
+ }
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type PutLogEventsOutput struct {
+ _ struct{} `type:"structure"`
+
+ // A string token used for making PutLogEvents requests. A sequenceToken can
+ // only be used once, and PutLogEvents requests must include the sequenceToken
+ // obtained from the response of the previous request.
+ NextSequenceToken *string `locationName:"nextSequenceToken" min:"1" type:"string"`
+
+ RejectedLogEventsInfo *RejectedLogEventsInfo `locationName:"rejectedLogEventsInfo" type:"structure"`
+}
+
+// String returns the string representation
+func (s PutLogEventsOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutLogEventsOutput) GoString() string {
+ return s.String()
+}
+
+type PutMetricFilterInput struct {
+ _ struct{} `type:"structure"`
+
+ // A name for the metric filter.
+ //
+ // FilterName is a required field
+ FilterName *string `locationName:"filterName" min:"1" type:"string" required:"true"`
+
+ // A valid CloudWatch Logs filter pattern for extracting metric data out of
+ // ingested log events.
+ //
+ // FilterPattern is a required field
+ FilterPattern *string `locationName:"filterPattern" type:"string" required:"true"`
+
+ // The name of the log group to associate the metric filter with.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // A collection of information needed to define how metric data gets emitted.
+ //
+ // MetricTransformations is a required field
+ MetricTransformations []*MetricTransformation `locationName:"metricTransformations" min:"1" type:"list" required:"true"`
+}
+
+// String returns the string representation
+func (s PutMetricFilterInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutMetricFilterInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *PutMetricFilterInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "PutMetricFilterInput"}
+ if s.FilterName == nil {
+ invalidParams.Add(request.NewErrParamRequired("FilterName"))
+ }
+ if s.FilterName != nil && len(*s.FilterName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("FilterName", 1))
+ }
+ if s.FilterPattern == nil {
+ invalidParams.Add(request.NewErrParamRequired("FilterPattern"))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.MetricTransformations == nil {
+ invalidParams.Add(request.NewErrParamRequired("MetricTransformations"))
+ }
+ if s.MetricTransformations != nil && len(s.MetricTransformations) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("MetricTransformations", 1))
+ }
+ if s.MetricTransformations != nil {
+ for i, v := range s.MetricTransformations {
+ if v == nil {
+ continue
+ }
+ if err := v.Validate(); err != nil {
+ invalidParams.AddNested(fmt.Sprintf("%s[%v]", "MetricTransformations", i), err.(request.ErrInvalidParams))
+ }
+ }
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type PutMetricFilterOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s PutMetricFilterOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutMetricFilterOutput) GoString() string {
+ return s.String()
+}
+
+type PutRetentionPolicyInput struct {
+ _ struct{} `type:"structure"`
+
+ // The name of the log group to associate the retention policy with.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // Specifies the number of days you want to retain log events in the specified
+ // log group. Possible values are: 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180,
+ // 365, 400, 545, 731, 1827, 3653.
+ //
+ // RetentionInDays is a required field
+ RetentionInDays *int64 `locationName:"retentionInDays" type:"integer" required:"true"`
+}
+
+// String returns the string representation
+func (s PutRetentionPolicyInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutRetentionPolicyInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *PutRetentionPolicyInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "PutRetentionPolicyInput"}
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.RetentionInDays == nil {
+ invalidParams.Add(request.NewErrParamRequired("RetentionInDays"))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type PutRetentionPolicyOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s PutRetentionPolicyOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutRetentionPolicyOutput) GoString() string {
+ return s.String()
+}
+
+type PutSubscriptionFilterInput struct {
+ _ struct{} `type:"structure"`
+
+ // The ARN of the destination to deliver matching log events to. Currently,
+ // the supported destinations are:
+ //
+ // * An Amazon Kinesis stream belonging to the same account as the subscription
+ // filter, for same-account delivery.
+ //
+ // * A logical destination (used via an ARN of Destination) belonging to
+ // a different account, for cross-account delivery.
+ //
+ // * An Amazon Kinesis Firehose stream belonging to the same account as the
+ // subscription filter, for same-account delivery.
+ //
+ // * An AWS Lambda function belonging to the same account as the subscription
+ // filter, for same-account delivery.
+ //
+ // DestinationArn is a required field
+ DestinationArn *string `locationName:"destinationArn" min:"1" type:"string" required:"true"`
+
+ // A name for the subscription filter.
+ //
+ // FilterName is a required field
+ FilterName *string `locationName:"filterName" min:"1" type:"string" required:"true"`
+
+ // A valid CloudWatch Logs filter pattern for subscribing to a filtered stream
+ // of log events.
+ //
+ // FilterPattern is a required field
+ FilterPattern *string `locationName:"filterPattern" type:"string" required:"true"`
+
+ // The name of the log group to associate the subscription filter with.
+ //
+ // LogGroupName is a required field
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"`
+
+ // The ARN of an IAM role that grants CloudWatch Logs permissions to deliver
+ // ingested log events to the destination stream. You don't need to provide
+ // the ARN when you are working with a logical destination (used via an ARN
+ // of Destination) for cross-account delivery.
+ RoleArn *string `locationName:"roleArn" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s PutSubscriptionFilterInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutSubscriptionFilterInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *PutSubscriptionFilterInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "PutSubscriptionFilterInput"}
+ if s.DestinationArn == nil {
+ invalidParams.Add(request.NewErrParamRequired("DestinationArn"))
+ }
+ if s.DestinationArn != nil && len(*s.DestinationArn) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("DestinationArn", 1))
+ }
+ if s.FilterName == nil {
+ invalidParams.Add(request.NewErrParamRequired("FilterName"))
+ }
+ if s.FilterName != nil && len(*s.FilterName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("FilterName", 1))
+ }
+ if s.FilterPattern == nil {
+ invalidParams.Add(request.NewErrParamRequired("FilterPattern"))
+ }
+ if s.LogGroupName == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogGroupName"))
+ }
+ if s.LogGroupName != nil && len(*s.LogGroupName) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1))
+ }
+ if s.RoleArn != nil && len(*s.RoleArn) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("RoleArn", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type PutSubscriptionFilterOutput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s PutSubscriptionFilterOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s PutSubscriptionFilterOutput) GoString() string {
+ return s.String()
+}
+
+type RejectedLogEventsInfo struct {
+ _ struct{} `type:"structure"`
+
+ ExpiredLogEventEndIndex *int64 `locationName:"expiredLogEventEndIndex" type:"integer"`
+
+ TooNewLogEventStartIndex *int64 `locationName:"tooNewLogEventStartIndex" type:"integer"`
+
+ TooOldLogEventEndIndex *int64 `locationName:"tooOldLogEventEndIndex" type:"integer"`
+}
+
+// String returns the string representation
+func (s RejectedLogEventsInfo) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s RejectedLogEventsInfo) GoString() string {
+ return s.String()
+}
+
+// An object indicating the search status of a log stream in a FilterLogEvents
+// request.
+type SearchedLogStream struct {
+ _ struct{} `type:"structure"`
+
+ // The name of the log stream.
+ LogStreamName *string `locationName:"logStreamName" min:"1" type:"string"`
+
+ // Indicates whether all the events in this log stream were searched or more
+ // data exists to search by paginating further.
+ SearchedCompletely *bool `locationName:"searchedCompletely" type:"boolean"`
+}
+
+// String returns the string representation
+func (s SearchedLogStream) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s SearchedLogStream) GoString() string {
+ return s.String()
+}
+
+type SubscriptionFilter struct {
+ _ struct{} `type:"structure"`
+
+ // A point in time expressed as the number of milliseconds since Jan 1, 1970
+ // 00:00:00 UTC.
+ CreationTime *int64 `locationName:"creationTime" type:"long"`
+
+ DestinationArn *string `locationName:"destinationArn" min:"1" type:"string"`
+
+ // A name for a metric or subscription filter.
+ FilterName *string `locationName:"filterName" min:"1" type:"string"`
+
+ // A symbolic description of how CloudWatch Logs should interpret the data in
+ // each log event. For example, a log event may contain timestamps, IP addresses,
+ // strings, and so on. You use the filter pattern to specify what to look for
+ // in the log event message.
+ FilterPattern *string `locationName:"filterPattern" type:"string"`
+
+ LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"`
+
+ RoleArn *string `locationName:"roleArn" min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s SubscriptionFilter) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s SubscriptionFilter) GoString() string {
+ return s.String()
+}
+
+type TestMetricFilterInput struct {
+ _ struct{} `type:"structure"`
+
+ // A symbolic description of how CloudWatch Logs should interpret the data in
+ // each log event. For example, a log event may contain timestamps, IP addresses,
+ // strings, and so on. You use the filter pattern to specify what to look for
+ // in the log event message.
+ //
+ // FilterPattern is a required field
+ FilterPattern *string `locationName:"filterPattern" type:"string" required:"true"`
+
+ // A list of log event messages to test.
+ //
+ // LogEventMessages is a required field
+ LogEventMessages []*string `locationName:"logEventMessages" min:"1" type:"list" required:"true"`
+}
+
+// String returns the string representation
+func (s TestMetricFilterInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s TestMetricFilterInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *TestMetricFilterInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "TestMetricFilterInput"}
+ if s.FilterPattern == nil {
+ invalidParams.Add(request.NewErrParamRequired("FilterPattern"))
+ }
+ if s.LogEventMessages == nil {
+ invalidParams.Add(request.NewErrParamRequired("LogEventMessages"))
+ }
+ if s.LogEventMessages != nil && len(s.LogEventMessages) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("LogEventMessages", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+type TestMetricFilterOutput struct {
+ _ struct{} `type:"structure"`
+
+ Matches []*MetricFilterMatchRecord `locationName:"matches" type:"list"`
+}
+
+// String returns the string representation
+func (s TestMetricFilterOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s TestMetricFilterOutput) GoString() string {
+ return s.String()
+}
+
+const (
+ // ExportTaskStatusCodeCancelled is a ExportTaskStatusCode enum value
+ ExportTaskStatusCodeCancelled = "CANCELLED"
+
+ // ExportTaskStatusCodeCompleted is a ExportTaskStatusCode enum value
+ ExportTaskStatusCodeCompleted = "COMPLETED"
+
+ // ExportTaskStatusCodeFailed is a ExportTaskStatusCode enum value
+ ExportTaskStatusCodeFailed = "FAILED"
+
+ // ExportTaskStatusCodePending is a ExportTaskStatusCode enum value
+ ExportTaskStatusCodePending = "PENDING"
+
+ // ExportTaskStatusCodePendingCancel is a ExportTaskStatusCode enum value
+ ExportTaskStatusCodePendingCancel = "PENDING_CANCEL"
+
+ // ExportTaskStatusCodeRunning is a ExportTaskStatusCode enum value
+ ExportTaskStatusCodeRunning = "RUNNING"
+)
+
+const (
+ // OrderByLogStreamName is a OrderBy enum value
+ OrderByLogStreamName = "LogStreamName"
+
+ // OrderByLastEventTime is a OrderBy enum value
+ OrderByLastEventTime = "LastEventTime"
+)
diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go
new file mode 100644
index 0000000..0c7563a
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go
@@ -0,0 +1,117 @@
+// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
+
+package cloudwatchlogs
+
+import (
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/client"
+ "github.com/aws/aws-sdk-go/aws/client/metadata"
+ "github.com/aws/aws-sdk-go/aws/request"
+ "github.com/aws/aws-sdk-go/aws/signer/v4"
+ "github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
+)
+
+// You can use Amazon CloudWatch Logs to monitor, store, and access your log
+// files from Amazon Elastic Compute Cloud (Amazon EC2) instances, Amazon CloudTrail,
+// or other sources. You can then retrieve the associated log data from CloudWatch
+// Logs using the Amazon CloudWatch console, the CloudWatch Logs commands in
+// the AWS CLI, the CloudWatch Logs API, or the CloudWatch Logs SDK.
+//
+// You can use CloudWatch Logs to:
+//
+// * Monitor Logs from Amazon EC2 Instances in Real-time: You can use CloudWatch
+// Logs to monitor applications and systems using log data. For example,
+// CloudWatch Logs can track the number of errors that occur in your application
+// logs and send you a notification whenever the rate of errors exceeds a
+// threshold you specify. CloudWatch Logs uses your log data for monitoring;
+// so, no code changes are required. For example, you can monitor application
+// logs for specific literal terms (such as "NullReferenceException") or
+// count the number of occurrences of a literal term at a particular position
+// in log data (such as "404" status codes in an Apache access log). When
+// the term you are searching for is found, CloudWatch Logs reports the data
+// to a Amazon CloudWatch metric that you specify.
+//
+// * Monitor Amazon CloudTrail Logged Events: You can create alarms in Amazon
+// CloudWatch and receive notifications of particular API activity as captured
+// by CloudTrail and use the notification to perform troubleshooting.
+//
+// * Archive Log Data: You can use CloudWatch Logs to store your log data
+// in highly durable storage. You can change the log retention setting so
+// that any log events older than this setting are automatically deleted.
+// The CloudWatch Logs agent makes it easy to quickly send both rotated and
+// non-rotated log data off of a host and into the log service. You can then
+// access the raw log data when you need it.
+//The service client's operations are safe to be used concurrently.
+// It is not safe to mutate any of the client's properties though.
+type CloudWatchLogs struct {
+ *client.Client
+}
+
+// Used for custom client initialization logic
+var initClient func(*client.Client)
+
+// Used for custom request initialization logic
+var initRequest func(*request.Request)
+
+// A ServiceName is the name of the service the client will make API calls to.
+const ServiceName = "logs"
+
+// New creates a new instance of the CloudWatchLogs client with a session.
+// If additional configuration is needed for the client instance use the optional
+// aws.Config parameter to add your extra config.
+//
+// Example:
+// // Create a CloudWatchLogs client from just a session.
+// svc := cloudwatchlogs.New(mySession)
+//
+// // Create a CloudWatchLogs client with additional configuration
+// svc := cloudwatchlogs.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
+func New(p client.ConfigProvider, cfgs ...*aws.Config) *CloudWatchLogs {
+ c := p.ClientConfig(ServiceName, cfgs...)
+ return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
+}
+
+// newClient creates, initializes and returns a new service client instance.
+func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *CloudWatchLogs {
+ svc := &CloudWatchLogs{
+ Client: client.New(
+ cfg,
+ metadata.ClientInfo{
+ ServiceName: ServiceName,
+ SigningRegion: signingRegion,
+ Endpoint: endpoint,
+ APIVersion: "2014-03-28",
+ JSONVersion: "1.1",
+ TargetPrefix: "Logs_20140328",
+ },
+ handlers,
+ ),
+ }
+
+ // Handlers
+ svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
+ svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
+ svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
+ svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
+ svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)
+
+ // Run custom client initialization if present
+ if initClient != nil {
+ initClient(svc.Client)
+ }
+
+ return svc
+}
+
+// newRequest creates a new request for a CloudWatchLogs operation and runs any
+// custom request initialization.
+func (c *CloudWatchLogs) newRequest(op *request.Operation, params, data interface{}) *request.Request {
+ req := c.NewRequest(op, params, data)
+
+ // Run custom request initialization if present
+ if initRequest != nil {
+ initRequest(req)
+ }
+
+ return req
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go
new file mode 100644
index 0000000..e10ca8f
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go
@@ -0,0 +1,1894 @@
+// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
+
+// Package sts provides a client for AWS Security Token Service.
+package sts
+
+import (
+ "time"
+
+ "github.com/aws/aws-sdk-go/aws/awsutil"
+ "github.com/aws/aws-sdk-go/aws/request"
+)
+
+const opAssumeRole = "AssumeRole"
+
+// AssumeRoleRequest generates a "aws/request.Request" representing the
+// client's request for the AssumeRole operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See AssumeRole for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the AssumeRole method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the AssumeRoleRequest method.
+// req, resp := client.AssumeRoleRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, output *AssumeRoleOutput) {
+ op := &request.Operation{
+ Name: opAssumeRole,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &AssumeRoleInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &AssumeRoleOutput{}
+ req.Data = output
+ return
+}
+
+// AssumeRole API operation for AWS Security Token Service.
+//
+// Returns a set of temporary security credentials (consisting of an access
+// key ID, a secret access key, and a security token) that you can use to access
+// AWS resources that you might not normally have access to. Typically, you
+// use AssumeRole for cross-account access or federation. For a comparison of
+// AssumeRole with the other APIs that produce temporary credentials, see Requesting
+// Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html)
+// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison)
+// in the IAM User Guide.
+//
+// Important: You cannot call AssumeRole by using AWS root account credentials;
+// access is denied. You must use credentials for an IAM user or an IAM role
+// to call AssumeRole.
+//
+// For cross-account access, imagine that you own multiple accounts and need
+// to access resources in each account. You could create long-term credentials
+// in each account to access those resources. However, managing all those credentials
+// and remembering which one can access which account can be time consuming.
+// Instead, you can create one set of long-term credentials in one account and
+// then use temporary security credentials to access all the other accounts
+// by assuming roles in those accounts. For more information about roles, see
+// IAM Roles (Delegation and Federation) (http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html)
+// in the IAM User Guide.
+//
+// For federation, you can, for example, grant single sign-on access to the
+// AWS Management Console. If you already have an identity and authentication
+// system in your corporate network, you don't have to recreate user identities
+// in AWS in order to grant those user identities access to AWS. Instead, after
+// a user has been authenticated, you call AssumeRole (and specify the role
+// with the appropriate permissions) to get temporary security credentials for
+// that user. With those temporary security credentials, you construct a sign-in
+// URL that users can use to access the console. For more information, see Common
+// Scenarios for Temporary Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html#sts-introduction)
+// in the IAM User Guide.
+//
+// The temporary security credentials are valid for the duration that you specified
+// when calling AssumeRole, which can be from 900 seconds (15 minutes) to a
+// maximum of 3600 seconds (1 hour). The default is 1 hour.
+//
+// The temporary security credentials created by AssumeRole can be used to make
+// API calls to any AWS service with the following exception: you cannot call
+// the STS service's GetFederationToken or GetSessionToken APIs.
+//
+// Optionally, you can pass an IAM access policy to this operation. If you choose
+// not to pass a policy, the temporary security credentials that are returned
+// by the operation have the permissions that are defined in the access policy
+// of the role that is being assumed. If you pass a policy to this operation,
+// the temporary security credentials that are returned by the operation have
+// the permissions that are allowed by both the access policy of the role that
+// is being assumed, and the policy that you pass. This gives you a way to further
+// restrict the permissions for the resulting temporary security credentials.
+// You cannot use the passed policy to grant permissions that are in excess
+// of those allowed by the access policy of the role that is being assumed.
+// For more information, see Permissions for AssumeRole, AssumeRoleWithSAML,
+// and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html)
+// in the IAM User Guide.
+//
+// To assume a role, your AWS account must be trusted by the role. The trust
+// relationship is defined in the role's trust policy when the role is created.
+// That trust policy states which accounts are allowed to delegate access to
+// this account's role.
+//
+// The user who wants to access the role must also have permissions delegated
+// from the role's administrator. If the user is in a different account than
+// the role, then the user's administrator must attach a policy that allows
+// the user to call AssumeRole on the ARN of the role in the other account.
+// If the user is in the same account as the role, then you can either attach
+// a policy to the user (identical to the previous different account user),
+// or you can add the user as a principal directly in the role's trust policy
+//
+// Using MFA with AssumeRole
+//
+// You can optionally include multi-factor authentication (MFA) information
+// when you call AssumeRole. This is useful for cross-account scenarios in which
+// you want to make sure that the user who is assuming the role has been authenticated
+// using an AWS MFA device. In that scenario, the trust policy of the role being
+// assumed includes a condition that tests for MFA authentication; if the caller
+// does not include valid MFA information, the request to assume the role is
+// denied. The condition in a trust policy that tests for MFA authentication
+// might look like the following example.
+//
+// "Condition": {"Bool": {"aws:MultiFactorAuthPresent": true}}
+//
+// For more information, see Configuring MFA-Protected API Access (http://docs.aws.amazon.com/IAM/latest/UserGuide/MFAProtectedAPI.html)
+// in the IAM User Guide guide.
+//
+// To use MFA with AssumeRole, you pass values for the SerialNumber and TokenCode
+// parameters. The SerialNumber value identifies the user's hardware or virtual
+// MFA device. The TokenCode is the time-based one-time password (TOTP) that
+// the MFA devices produces.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for AWS Security Token Service's
+// API operation AssumeRole for usage and error information.
+//
+// Returned Error Codes:
+// * MalformedPolicyDocument
+// The request was rejected because the policy document was malformed. The error
+// message describes the specific error.
+//
+// * PackedPolicyTooLarge
+// The request was rejected because the policy document was too large. The error
+// message describes how big the policy document is, in packed form, as a percentage
+// of what the API allows.
+//
+// * RegionDisabledException
+// STS is not activated in the requested region for the account that is being
+// asked to generate credentials. The account administrator must use the IAM
+// console to activate STS in that region. For more information, see Activating
+// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html)
+// in the IAM User Guide.
+//
+func (c *STS) AssumeRole(input *AssumeRoleInput) (*AssumeRoleOutput, error) {
+ req, out := c.AssumeRoleRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opAssumeRoleWithSAML = "AssumeRoleWithSAML"
+
+// AssumeRoleWithSAMLRequest generates a "aws/request.Request" representing the
+// client's request for the AssumeRoleWithSAML operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See AssumeRoleWithSAML for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the AssumeRoleWithSAML method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the AssumeRoleWithSAMLRequest method.
+// req, resp := client.AssumeRoleWithSAMLRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *request.Request, output *AssumeRoleWithSAMLOutput) {
+ op := &request.Operation{
+ Name: opAssumeRoleWithSAML,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &AssumeRoleWithSAMLInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &AssumeRoleWithSAMLOutput{}
+ req.Data = output
+ return
+}
+
+// AssumeRoleWithSAML API operation for AWS Security Token Service.
+//
+// Returns a set of temporary security credentials for users who have been authenticated
+// via a SAML authentication response. This operation provides a mechanism for
+// tying an enterprise identity store or directory to role-based AWS access
+// without user-specific credentials or configuration. For a comparison of AssumeRoleWithSAML
+// with the other APIs that produce temporary credentials, see Requesting Temporary
+// Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html)
+// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison)
+// in the IAM User Guide.
+//
+// The temporary security credentials returned by this operation consist of
+// an access key ID, a secret access key, and a security token. Applications
+// can use these temporary security credentials to sign calls to AWS services.
+//
+// The temporary security credentials are valid for the duration that you specified
+// when calling AssumeRole, or until the time specified in the SAML authentication
+// response's SessionNotOnOrAfter value, whichever is shorter. The duration
+// can be from 900 seconds (15 minutes) to a maximum of 3600 seconds (1 hour).
+// The default is 1 hour.
+//
+// The temporary security credentials created by AssumeRoleWithSAML can be used
+// to make API calls to any AWS service with the following exception: you cannot
+// call the STS service's GetFederationToken or GetSessionToken APIs.
+//
+// Optionally, you can pass an IAM access policy to this operation. If you choose
+// not to pass a policy, the temporary security credentials that are returned
+// by the operation have the permissions that are defined in the access policy
+// of the role that is being assumed. If you pass a policy to this operation,
+// the temporary security credentials that are returned by the operation have
+// the permissions that are allowed by the intersection of both the access policy
+// of the role that is being assumed, and the policy that you pass. This means
+// that both policies must grant the permission for the action to be allowed.
+// This gives you a way to further restrict the permissions for the resulting
+// temporary security credentials. You cannot use the passed policy to grant
+// permissions that are in excess of those allowed by the access policy of the
+// role that is being assumed. For more information, see Permissions for AssumeRole,
+// AssumeRoleWithSAML, and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html)
+// in the IAM User Guide.
+//
+// Before your application can call AssumeRoleWithSAML, you must configure your
+// SAML identity provider (IdP) to issue the claims required by AWS. Additionally,
+// you must use AWS Identity and Access Management (IAM) to create a SAML provider
+// entity in your AWS account that represents your identity provider, and create
+// an IAM role that specifies this SAML provider in its trust policy.
+//
+// Calling AssumeRoleWithSAML does not require the use of AWS security credentials.
+// The identity of the caller is validated by using keys in the metadata document
+// that is uploaded for the SAML provider entity for your identity provider.
+//
+// Calling AssumeRoleWithSAML can result in an entry in your AWS CloudTrail
+// logs. The entry includes the value in the NameID element of the SAML assertion.
+// We recommend that you use a NameIDType that is not associated with any personally
+// identifiable information (PII). For example, you could instead use the Persistent
+// Identifier (urn:oasis:names:tc:SAML:2.0:nameid-format:persistent).
+//
+// For more information, see the following resources:
+//
+// * About SAML 2.0-based Federation (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html)
+// in the IAM User Guide.
+//
+// * Creating SAML Identity Providers (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)
+// in the IAM User Guide.
+//
+// * Configuring a Relying Party and Claims (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html)
+// in the IAM User Guide.
+//
+// * Creating a Role for SAML 2.0 Federation (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_saml.html)
+// in the IAM User Guide.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for AWS Security Token Service's
+// API operation AssumeRoleWithSAML for usage and error information.
+//
+// Returned Error Codes:
+// * MalformedPolicyDocument
+// The request was rejected because the policy document was malformed. The error
+// message describes the specific error.
+//
+// * PackedPolicyTooLarge
+// The request was rejected because the policy document was too large. The error
+// message describes how big the policy document is, in packed form, as a percentage
+// of what the API allows.
+//
+// * IDPRejectedClaim
+// The identity provider (IdP) reported that authentication failed. This might
+// be because the claim is invalid.
+//
+// If this error is returned for the AssumeRoleWithWebIdentity operation, it
+// can also mean that the claim has expired or has been explicitly revoked.
+//
+// * InvalidIdentityToken
+// The web identity token that was passed could not be validated by AWS. Get
+// a new identity token from the identity provider and then retry the request.
+//
+// * ExpiredTokenException
+// The web identity token that was passed is expired or is not valid. Get a
+// new identity token from the identity provider and then retry the request.
+//
+// * RegionDisabledException
+// STS is not activated in the requested region for the account that is being
+// asked to generate credentials. The account administrator must use the IAM
+// console to activate STS in that region. For more information, see Activating
+// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html)
+// in the IAM User Guide.
+//
+func (c *STS) AssumeRoleWithSAML(input *AssumeRoleWithSAMLInput) (*AssumeRoleWithSAMLOutput, error) {
+ req, out := c.AssumeRoleWithSAMLRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opAssumeRoleWithWebIdentity = "AssumeRoleWithWebIdentity"
+
+// AssumeRoleWithWebIdentityRequest generates a "aws/request.Request" representing the
+// client's request for the AssumeRoleWithWebIdentity operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See AssumeRoleWithWebIdentity for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the AssumeRoleWithWebIdentity method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the AssumeRoleWithWebIdentityRequest method.
+// req, resp := client.AssumeRoleWithWebIdentityRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityInput) (req *request.Request, output *AssumeRoleWithWebIdentityOutput) {
+ op := &request.Operation{
+ Name: opAssumeRoleWithWebIdentity,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &AssumeRoleWithWebIdentityInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &AssumeRoleWithWebIdentityOutput{}
+ req.Data = output
+ return
+}
+
+// AssumeRoleWithWebIdentity API operation for AWS Security Token Service.
+//
+// Returns a set of temporary security credentials for users who have been authenticated
+// in a mobile or web application with a web identity provider, such as Amazon
+// Cognito, Login with Amazon, Facebook, Google, or any OpenID Connect-compatible
+// identity provider.
+//
+// For mobile applications, we recommend that you use Amazon Cognito. You can
+// use Amazon Cognito with the AWS SDK for iOS (http://aws.amazon.com/sdkforios/)
+// and the AWS SDK for Android (http://aws.amazon.com/sdkforandroid/) to uniquely
+// identify a user and supply the user with a consistent identity throughout
+// the lifetime of an application.
+//
+// To learn more about Amazon Cognito, see Amazon Cognito Overview (http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-auth.html#d0e840)
+// in the AWS SDK for Android Developer Guide guide and Amazon Cognito Overview
+// (http://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-auth.html#d0e664)
+// in the AWS SDK for iOS Developer Guide.
+//
+// Calling AssumeRoleWithWebIdentity does not require the use of AWS security
+// credentials. Therefore, you can distribute an application (for example, on
+// mobile devices) that requests temporary security credentials without including
+// long-term AWS credentials in the application, and without deploying server-based
+// proxy services that use long-term AWS credentials. Instead, the identity
+// of the caller is validated by using a token from the web identity provider.
+// For a comparison of AssumeRoleWithWebIdentity with the other APIs that produce
+// temporary credentials, see Requesting Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html)
+// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison)
+// in the IAM User Guide.
+//
+// The temporary security credentials returned by this API consist of an access
+// key ID, a secret access key, and a security token. Applications can use these
+// temporary security credentials to sign calls to AWS service APIs.
+//
+// The credentials are valid for the duration that you specified when calling
+// AssumeRoleWithWebIdentity, which can be from 900 seconds (15 minutes) to
+// a maximum of 3600 seconds (1 hour). The default is 1 hour.
+//
+// The temporary security credentials created by AssumeRoleWithWebIdentity can
+// be used to make API calls to any AWS service with the following exception:
+// you cannot call the STS service's GetFederationToken or GetSessionToken APIs.
+//
+// Optionally, you can pass an IAM access policy to this operation. If you choose
+// not to pass a policy, the temporary security credentials that are returned
+// by the operation have the permissions that are defined in the access policy
+// of the role that is being assumed. If you pass a policy to this operation,
+// the temporary security credentials that are returned by the operation have
+// the permissions that are allowed by both the access policy of the role that
+// is being assumed, and the policy that you pass. This gives you a way to further
+// restrict the permissions for the resulting temporary security credentials.
+// You cannot use the passed policy to grant permissions that are in excess
+// of those allowed by the access policy of the role that is being assumed.
+// For more information, see Permissions for AssumeRole, AssumeRoleWithSAML,
+// and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html)
+// in the IAM User Guide.
+//
+// Before your application can call AssumeRoleWithWebIdentity, you must have
+// an identity token from a supported identity provider and create a role that
+// the application can assume. The role that your application assumes must trust
+// the identity provider that is associated with the identity token. In other
+// words, the identity provider must be specified in the role's trust policy.
+//
+// Calling AssumeRoleWithWebIdentity can result in an entry in your AWS CloudTrail
+// logs. The entry includes the Subject (http://openid.net/specs/openid-connect-core-1_0.html#Claims)
+// of the provided Web Identity Token. We recommend that you avoid using any
+// personally identifiable information (PII) in this field. For example, you
+// could instead use a GUID or a pairwise identifier, as suggested in the OIDC
+// specification (http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes).
+//
+// For more information about how to use web identity federation and the AssumeRoleWithWebIdentity
+// API, see the following resources:
+//
+// * Using Web Identity Federation APIs for Mobile Apps (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual)
+// and Federation Through a Web-based Identity Provider (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity).
+//
+//
+// * Web Identity Federation Playground (https://web-identity-federation-playground.s3.amazonaws.com/index.html).
+// This interactive website lets you walk through the process of authenticating
+// via Login with Amazon, Facebook, or Google, getting temporary security
+// credentials, and then using those credentials to make a request to AWS.
+//
+//
+// * AWS SDK for iOS (http://aws.amazon.com/sdkforios/) and AWS SDK for Android
+// (http://aws.amazon.com/sdkforandroid/). These toolkits contain sample
+// apps that show how to invoke the identity providers, and then how to use
+// the information from these providers to get and use temporary security
+// credentials.
+//
+// * Web Identity Federation with Mobile Applications (http://aws.amazon.com/articles/4617974389850313).
+// This article discusses web identity federation and shows an example of
+// how to use web identity federation to get access to content in Amazon
+// S3.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for AWS Security Token Service's
+// API operation AssumeRoleWithWebIdentity for usage and error information.
+//
+// Returned Error Codes:
+// * MalformedPolicyDocument
+// The request was rejected because the policy document was malformed. The error
+// message describes the specific error.
+//
+// * PackedPolicyTooLarge
+// The request was rejected because the policy document was too large. The error
+// message describes how big the policy document is, in packed form, as a percentage
+// of what the API allows.
+//
+// * IDPRejectedClaim
+// The identity provider (IdP) reported that authentication failed. This might
+// be because the claim is invalid.
+//
+// If this error is returned for the AssumeRoleWithWebIdentity operation, it
+// can also mean that the claim has expired or has been explicitly revoked.
+//
+// * IDPCommunicationError
+// The request could not be fulfilled because the non-AWS identity provider
+// (IDP) that was asked to verify the incoming identity token could not be reached.
+// This is often a transient error caused by network conditions. Retry the request
+// a limited number of times so that you don't exceed the request rate. If the
+// error persists, the non-AWS identity provider might be down or not responding.
+//
+// * InvalidIdentityToken
+// The web identity token that was passed could not be validated by AWS. Get
+// a new identity token from the identity provider and then retry the request.
+//
+// * ExpiredTokenException
+// The web identity token that was passed is expired or is not valid. Get a
+// new identity token from the identity provider and then retry the request.
+//
+// * RegionDisabledException
+// STS is not activated in the requested region for the account that is being
+// asked to generate credentials. The account administrator must use the IAM
+// console to activate STS in that region. For more information, see Activating
+// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html)
+// in the IAM User Guide.
+//
+func (c *STS) AssumeRoleWithWebIdentity(input *AssumeRoleWithWebIdentityInput) (*AssumeRoleWithWebIdentityOutput, error) {
+ req, out := c.AssumeRoleWithWebIdentityRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opDecodeAuthorizationMessage = "DecodeAuthorizationMessage"
+
+// DecodeAuthorizationMessageRequest generates a "aws/request.Request" representing the
+// client's request for the DecodeAuthorizationMessage operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See DecodeAuthorizationMessage for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the DecodeAuthorizationMessage method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the DecodeAuthorizationMessageRequest method.
+// req, resp := client.DecodeAuthorizationMessageRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessageInput) (req *request.Request, output *DecodeAuthorizationMessageOutput) {
+ op := &request.Operation{
+ Name: opDecodeAuthorizationMessage,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &DecodeAuthorizationMessageInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &DecodeAuthorizationMessageOutput{}
+ req.Data = output
+ return
+}
+
+// DecodeAuthorizationMessage API operation for AWS Security Token Service.
+//
+// Decodes additional information about the authorization status of a request
+// from an encoded message returned in response to an AWS request.
+//
+// For example, if a user is not authorized to perform an action that he or
+// she has requested, the request returns a Client.UnauthorizedOperation response
+// (an HTTP 403 response). Some AWS actions additionally return an encoded message
+// that can provide details about this authorization failure.
+//
+// Only certain AWS actions return an encoded authorization message. The documentation
+// for an individual action indicates whether that action returns an encoded
+// message in addition to returning an HTTP code.
+//
+// The message is encoded because the details of the authorization status can
+// constitute privileged information that the user who requested the action
+// should not see. To decode an authorization status message, a user must be
+// granted permissions via an IAM policy to request the DecodeAuthorizationMessage
+// (sts:DecodeAuthorizationMessage) action.
+//
+// The decoded message includes the following type of information:
+//
+// * Whether the request was denied due to an explicit deny or due to the
+// absence of an explicit allow. For more information, see Determining Whether
+// a Request is Allowed or Denied (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow)
+// in the IAM User Guide.
+//
+// * The principal who made the request.
+//
+// * The requested action.
+//
+// * The requested resource.
+//
+// * The values of condition keys in the context of the user's request.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for AWS Security Token Service's
+// API operation DecodeAuthorizationMessage for usage and error information.
+//
+// Returned Error Codes:
+// * InvalidAuthorizationMessageException
+// The error returned if the message passed to DecodeAuthorizationMessage was
+// invalid. This can happen if the token contains invalid characters, such as
+// linebreaks.
+//
+func (c *STS) DecodeAuthorizationMessage(input *DecodeAuthorizationMessageInput) (*DecodeAuthorizationMessageOutput, error) {
+ req, out := c.DecodeAuthorizationMessageRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opGetCallerIdentity = "GetCallerIdentity"
+
+// GetCallerIdentityRequest generates a "aws/request.Request" representing the
+// client's request for the GetCallerIdentity operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See GetCallerIdentity for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the GetCallerIdentity method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the GetCallerIdentityRequest method.
+// req, resp := client.GetCallerIdentityRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *request.Request, output *GetCallerIdentityOutput) {
+ op := &request.Operation{
+ Name: opGetCallerIdentity,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &GetCallerIdentityInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &GetCallerIdentityOutput{}
+ req.Data = output
+ return
+}
+
+// GetCallerIdentity API operation for AWS Security Token Service.
+//
+// Returns details about the IAM identity whose credentials are used to call
+// the API.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for AWS Security Token Service's
+// API operation GetCallerIdentity for usage and error information.
+func (c *STS) GetCallerIdentity(input *GetCallerIdentityInput) (*GetCallerIdentityOutput, error) {
+ req, out := c.GetCallerIdentityRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opGetFederationToken = "GetFederationToken"
+
+// GetFederationTokenRequest generates a "aws/request.Request" representing the
+// client's request for the GetFederationToken operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See GetFederationToken for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the GetFederationToken method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the GetFederationTokenRequest method.
+// req, resp := client.GetFederationTokenRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *request.Request, output *GetFederationTokenOutput) {
+ op := &request.Operation{
+ Name: opGetFederationToken,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &GetFederationTokenInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &GetFederationTokenOutput{}
+ req.Data = output
+ return
+}
+
+// GetFederationToken API operation for AWS Security Token Service.
+//
+// Returns a set of temporary security credentials (consisting of an access
+// key ID, a secret access key, and a security token) for a federated user.
+// A typical use is in a proxy application that gets temporary security credentials
+// on behalf of distributed applications inside a corporate network. Because
+// you must call the GetFederationToken action using the long-term security
+// credentials of an IAM user, this call is appropriate in contexts where those
+// credentials can be safely stored, usually in a server-based application.
+// For a comparison of GetFederationToken with the other APIs that produce temporary
+// credentials, see Requesting Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html)
+// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison)
+// in the IAM User Guide.
+//
+// If you are creating a mobile-based or browser-based app that can authenticate
+// users using a web identity provider like Login with Amazon, Facebook, Google,
+// or an OpenID Connect-compatible identity provider, we recommend that you
+// use Amazon Cognito (http://aws.amazon.com/cognito/) or AssumeRoleWithWebIdentity.
+// For more information, see Federation Through a Web-based Identity Provider
+// (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity).
+//
+// The GetFederationToken action must be called by using the long-term AWS security
+// credentials of an IAM user. You can also call GetFederationToken using the
+// security credentials of an AWS root account, but we do not recommended it.
+// Instead, we recommend that you create an IAM user for the purpose of the
+// proxy application and then attach a policy to the IAM user that limits federated
+// users to only the actions and resources that they need access to. For more
+// information, see IAM Best Practices (http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)
+// in the IAM User Guide.
+//
+// The temporary security credentials that are obtained by using the long-term
+// credentials of an IAM user are valid for the specified duration, from 900
+// seconds (15 minutes) up to a maximium of 129600 seconds (36 hours). The default
+// is 43200 seconds (12 hours). Temporary credentials that are obtained by using
+// AWS root account credentials have a maximum duration of 3600 seconds (1 hour).
+//
+// The temporary security credentials created by GetFederationToken can be used
+// to make API calls to any AWS service with the following exceptions:
+//
+// * You cannot use these credentials to call any IAM APIs.
+//
+// * You cannot call any STS APIs.
+//
+// Permissions
+//
+// The permissions for the temporary security credentials returned by GetFederationToken
+// are determined by a combination of the following:
+//
+// * The policy or policies that are attached to the IAM user whose credentials
+// are used to call GetFederationToken.
+//
+// * The policy that is passed as a parameter in the call.
+//
+// The passed policy is attached to the temporary security credentials that
+// result from the GetFederationToken API call--that is, to the federated user.
+// When the federated user makes an AWS request, AWS evaluates the policy attached
+// to the federated user in combination with the policy or policies attached
+// to the IAM user whose credentials were used to call GetFederationToken. AWS
+// allows the federated user's request only when both the federated user and
+// the IAM user are explicitly allowed to perform the requested action. The
+// passed policy cannot grant more permissions than those that are defined in
+// the IAM user policy.
+//
+// A typical use case is that the permissions of the IAM user whose credentials
+// are used to call GetFederationToken are designed to allow access to all the
+// actions and resources that any federated user will need. Then, for individual
+// users, you pass a policy to the operation that scopes down the permissions
+// to a level that's appropriate to that individual user, using a policy that
+// allows only a subset of permissions that are granted to the IAM user.
+//
+// If you do not pass a policy, the resulting temporary security credentials
+// have no effective permissions. The only exception is when the temporary security
+// credentials are used to access a resource that has a resource-based policy
+// that specifically allows the federated user to access the resource.
+//
+// For more information about how permissions work, see Permissions for GetFederationToken
+// (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getfederationtoken.html).
+// For information about using GetFederationToken to create temporary security
+// credentials, see GetFederationToken—Federation Through a Custom Identity
+// Broker (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getfederationtoken).
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for AWS Security Token Service's
+// API operation GetFederationToken for usage and error information.
+//
+// Returned Error Codes:
+// * MalformedPolicyDocument
+// The request was rejected because the policy document was malformed. The error
+// message describes the specific error.
+//
+// * PackedPolicyTooLarge
+// The request was rejected because the policy document was too large. The error
+// message describes how big the policy document is, in packed form, as a percentage
+// of what the API allows.
+//
+// * RegionDisabledException
+// STS is not activated in the requested region for the account that is being
+// asked to generate credentials. The account administrator must use the IAM
+// console to activate STS in that region. For more information, see Activating
+// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html)
+// in the IAM User Guide.
+//
+func (c *STS) GetFederationToken(input *GetFederationTokenInput) (*GetFederationTokenOutput, error) {
+ req, out := c.GetFederationTokenRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+const opGetSessionToken = "GetSessionToken"
+
+// GetSessionTokenRequest generates a "aws/request.Request" representing the
+// client's request for the GetSessionToken operation. The "output" return
+// value can be used to capture response data after the request's "Send" method
+// is called.
+//
+// See GetSessionToken for usage and error information.
+//
+// Creating a request object using this method should be used when you want to inject
+// custom logic into the request's lifecycle using a custom handler, or if you want to
+// access properties on the request object before or after sending the request. If
+// you just want the service response, call the GetSessionToken method directly
+// instead.
+//
+// Note: You must call the "Send" method on the returned request object in order
+// to execute the request.
+//
+// // Example sending a request using the GetSessionTokenRequest method.
+// req, resp := client.GetSessionTokenRequest(params)
+//
+// err := req.Send()
+// if err == nil { // resp is now filled
+// fmt.Println(resp)
+// }
+//
+func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request.Request, output *GetSessionTokenOutput) {
+ op := &request.Operation{
+ Name: opGetSessionToken,
+ HTTPMethod: "POST",
+ HTTPPath: "/",
+ }
+
+ if input == nil {
+ input = &GetSessionTokenInput{}
+ }
+
+ req = c.newRequest(op, input, output)
+ output = &GetSessionTokenOutput{}
+ req.Data = output
+ return
+}
+
+// GetSessionToken API operation for AWS Security Token Service.
+//
+// Returns a set of temporary credentials for an AWS account or IAM user. The
+// credentials consist of an access key ID, a secret access key, and a security
+// token. Typically, you use GetSessionToken if you want to use MFA to protect
+// programmatic calls to specific AWS APIs like Amazon EC2 StopInstances. MFA-enabled
+// IAM users would need to call GetSessionToken and submit an MFA code that
+// is associated with their MFA device. Using the temporary security credentials
+// that are returned from the call, IAM users can then make programmatic calls
+// to APIs that require MFA authentication. If you do not supply a correct MFA
+// code, then the API returns an access denied error. For a comparison of GetSessionToken
+// with the other APIs that produce temporary credentials, see Requesting Temporary
+// Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html)
+// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison)
+// in the IAM User Guide.
+//
+// The GetSessionToken action must be called by using the long-term AWS security
+// credentials of the AWS account or an IAM user. Credentials that are created
+// by IAM users are valid for the duration that you specify, from 900 seconds
+// (15 minutes) up to a maximum of 129600 seconds (36 hours), with a default
+// of 43200 seconds (12 hours); credentials that are created by using account
+// credentials can range from 900 seconds (15 minutes) up to a maximum of 3600
+// seconds (1 hour), with a default of 1 hour.
+//
+// The temporary security credentials created by GetSessionToken can be used
+// to make API calls to any AWS service with the following exceptions:
+//
+// * You cannot call any IAM APIs unless MFA authentication information is
+// included in the request.
+//
+// * You cannot call any STS API exceptAssumeRole.
+//
+// We recommend that you do not call GetSessionToken with root account credentials.
+// Instead, follow our best practices (http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#create-iam-users)
+// by creating one or more IAM users, giving them the necessary permissions,
+// and using IAM users for everyday interaction with AWS.
+//
+// The permissions associated with the temporary security credentials returned
+// by GetSessionToken are based on the permissions associated with account or
+// IAM user whose credentials are used to call the action. If GetSessionToken
+// is called using root account credentials, the temporary credentials have
+// root account permissions. Similarly, if GetSessionToken is called using the
+// credentials of an IAM user, the temporary credentials have the same permissions
+// as the IAM user.
+//
+// For more information about using GetSessionToken to create temporary credentials,
+// go to Temporary Credentials for Users in Untrusted Environments (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken)
+// in the IAM User Guide.
+//
+// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
+// with awserr.Error's Code and Message methods to get detailed information about
+// the error.
+//
+// See the AWS API reference guide for AWS Security Token Service's
+// API operation GetSessionToken for usage and error information.
+//
+// Returned Error Codes:
+// * RegionDisabledException
+// STS is not activated in the requested region for the account that is being
+// asked to generate credentials. The account administrator must use the IAM
+// console to activate STS in that region. For more information, see Activating
+// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html)
+// in the IAM User Guide.
+//
+func (c *STS) GetSessionToken(input *GetSessionTokenInput) (*GetSessionTokenOutput, error) {
+ req, out := c.GetSessionTokenRequest(input)
+ err := req.Send()
+ return out, err
+}
+
+type AssumeRoleInput struct {
+ _ struct{} `type:"structure"`
+
+ // The duration, in seconds, of the role session. The value can range from 900
+ // seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set
+ // to 3600 seconds.
+ //
+ // This is separate from the duration of a console session that you might request
+ // using the returned credentials. The request to the federation endpoint for
+ // a console sign-in token takes a SessionDuration parameter that specifies
+ // the maximum length of the console session, separately from the DurationSeconds
+ // parameter on this API. For more information, see Creating a URL that Enables
+ // Federated Users to Access the AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html)
+ // in the IAM User Guide.
+ DurationSeconds *int64 `min:"900" type:"integer"`
+
+ // A unique identifier that is used by third parties when assuming roles in
+ // their customers' accounts. For each role that the third party can assume,
+ // they should instruct their customers to ensure the role's trust policy checks
+ // for the external ID that the third party generated. Each time the third party
+ // assumes the role, they should pass the customer's external ID. The external
+ // ID is useful in order to help third parties bind a role to the customer who
+ // created it. For more information about the external ID, see How to Use an
+ // External ID When Granting Access to Your AWS Resources to a Third Party (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html)
+ // in the IAM User Guide.
+ //
+ // The format for this parameter, as described by its regex pattern, is a string
+ // of characters consisting of upper- and lower-case alphanumeric characters
+ // with no spaces. You can also include underscores or any of the following
+ // characters: =,.@:\/-
+ ExternalId *string `min:"2" type:"string"`
+
+ // An IAM policy in JSON format.
+ //
+ // This parameter is optional. If you pass a policy, the temporary security
+ // credentials that are returned by the operation have the permissions that
+ // are allowed by both (the intersection of) the access policy of the role that
+ // is being assumed, and the policy that you pass. This gives you a way to further
+ // restrict the permissions for the resulting temporary security credentials.
+ // You cannot use the passed policy to grant permissions that are in excess
+ // of those allowed by the access policy of the role that is being assumed.
+ // For more information, see Permissions for AssumeRole, AssumeRoleWithSAML,
+ // and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html)
+ // in the IAM User Guide.
+ //
+ // The format for this parameter, as described by its regex pattern, is a string
+ // of characters up to 2048 characters in length. The characters can be any
+ // ASCII character from the space character to the end of the valid character
+ // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A),
+ // and carriage return (\u000D) characters.
+ //
+ // The policy plain text must be 2048 bytes or shorter. However, an internal
+ // conversion compresses it into a packed binary format with a separate limit.
+ // The PackedPolicySize response element indicates by percentage how close to
+ // the upper size limit the policy is, with 100% equaling the maximum allowed
+ // size.
+ Policy *string `min:"1" type:"string"`
+
+ // The Amazon Resource Name (ARN) of the role to assume.
+ //
+ // RoleArn is a required field
+ RoleArn *string `min:"20" type:"string" required:"true"`
+
+ // An identifier for the assumed role session.
+ //
+ // Use the role session name to uniquely identify a session when the same role
+ // is assumed by different principals or for different reasons. In cross-account
+ // scenarios, the role session name is visible to, and can be logged by the
+ // account that owns the role. The role session name is also used in the ARN
+ // of the assumed role principal. This means that subsequent cross-account API
+ // requests using the temporary security credentials will expose the role session
+ // name to the external account in their CloudTrail logs.
+ //
+ // The format for this parameter, as described by its regex pattern, is a string
+ // of characters consisting of upper- and lower-case alphanumeric characters
+ // with no spaces. You can also include underscores or any of the following
+ // characters: =,.@-
+ //
+ // RoleSessionName is a required field
+ RoleSessionName *string `min:"2" type:"string" required:"true"`
+
+ // The identification number of the MFA device that is associated with the user
+ // who is making the AssumeRole call. Specify this value if the trust policy
+ // of the role being assumed includes a condition that requires MFA authentication.
+ // The value is either the serial number for a hardware device (such as GAHT12345678)
+ // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user).
+ //
+ // The format for this parameter, as described by its regex pattern, is a string
+ // of characters consisting of upper- and lower-case alphanumeric characters
+ // with no spaces. You can also include underscores or any of the following
+ // characters: =,.@-
+ SerialNumber *string `min:"9" type:"string"`
+
+ // The value provided by the MFA device, if the trust policy of the role being
+ // assumed requires MFA (that is, if the policy includes a condition that tests
+ // for MFA). If the role being assumed requires MFA and if the TokenCode value
+ // is missing or expired, the AssumeRole call returns an "access denied" error.
+ //
+ // The format for this parameter, as described by its regex pattern, is a sequence
+ // of six numeric digits.
+ TokenCode *string `min:"6" type:"string"`
+}
+
+// String returns the string representation
+func (s AssumeRoleInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s AssumeRoleInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *AssumeRoleInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "AssumeRoleInput"}
+ if s.DurationSeconds != nil && *s.DurationSeconds < 900 {
+ invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900))
+ }
+ if s.ExternalId != nil && len(*s.ExternalId) < 2 {
+ invalidParams.Add(request.NewErrParamMinLen("ExternalId", 2))
+ }
+ if s.Policy != nil && len(*s.Policy) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("Policy", 1))
+ }
+ if s.RoleArn == nil {
+ invalidParams.Add(request.NewErrParamRequired("RoleArn"))
+ }
+ if s.RoleArn != nil && len(*s.RoleArn) < 20 {
+ invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20))
+ }
+ if s.RoleSessionName == nil {
+ invalidParams.Add(request.NewErrParamRequired("RoleSessionName"))
+ }
+ if s.RoleSessionName != nil && len(*s.RoleSessionName) < 2 {
+ invalidParams.Add(request.NewErrParamMinLen("RoleSessionName", 2))
+ }
+ if s.SerialNumber != nil && len(*s.SerialNumber) < 9 {
+ invalidParams.Add(request.NewErrParamMinLen("SerialNumber", 9))
+ }
+ if s.TokenCode != nil && len(*s.TokenCode) < 6 {
+ invalidParams.Add(request.NewErrParamMinLen("TokenCode", 6))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+// Contains the response to a successful AssumeRole request, including temporary
+// AWS credentials that can be used to make AWS requests.
+type AssumeRoleOutput struct {
+ _ struct{} `type:"structure"`
+
+ // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers
+ // that you can use to refer to the resulting temporary security credentials.
+ // For example, you can reference these credentials as a principal in a resource-based
+ // policy by using the ARN or assumed role ID. The ARN and ID include the RoleSessionName
+ // that you specified when you called AssumeRole.
+ AssumedRoleUser *AssumedRoleUser `type:"structure"`
+
+ // The temporary security credentials, which include an access key ID, a secret
+ // access key, and a security (or session) token.
+ //
+ // Note: The size of the security token that STS APIs return is not fixed. We
+ // strongly recommend that you make no assumptions about the maximum size. As
+ // of this writing, the typical size is less than 4096 bytes, but that can vary.
+ // Also, future updates to AWS might require larger sizes.
+ Credentials *Credentials `type:"structure"`
+
+ // A percentage value that indicates the size of the policy in packed form.
+ // The service rejects any policy with a packed size greater than 100 percent,
+ // which means the policy exceeded the allowed space.
+ PackedPolicySize *int64 `type:"integer"`
+}
+
+// String returns the string representation
+func (s AssumeRoleOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s AssumeRoleOutput) GoString() string {
+ return s.String()
+}
+
+type AssumeRoleWithSAMLInput struct {
+ _ struct{} `type:"structure"`
+
+ // The duration, in seconds, of the role session. The value can range from 900
+ // seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set
+ // to 3600 seconds. An expiration can also be specified in the SAML authentication
+ // response's SessionNotOnOrAfter value. The actual expiration time is whichever
+ // value is shorter.
+ //
+ // This is separate from the duration of a console session that you might request
+ // using the returned credentials. The request to the federation endpoint for
+ // a console sign-in token takes a SessionDuration parameter that specifies
+ // the maximum length of the console session, separately from the DurationSeconds
+ // parameter on this API. For more information, see Enabling SAML 2.0 Federated
+ // Users to Access the AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html)
+ // in the IAM User Guide.
+ DurationSeconds *int64 `min:"900" type:"integer"`
+
+ // An IAM policy in JSON format.
+ //
+ // The policy parameter is optional. If you pass a policy, the temporary security
+ // credentials that are returned by the operation have the permissions that
+ // are allowed by both the access policy of the role that is being assumed,
+ // and the policy that you pass. This gives you a way to further restrict the
+ // permissions for the resulting temporary security credentials. You cannot
+ // use the passed policy to grant permissions that are in excess of those allowed
+ // by the access policy of the role that is being assumed. For more information,
+ // Permissions for AssumeRole, AssumeRoleWithSAML, and AssumeRoleWithWebIdentity
+ // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html)
+ // in the IAM User Guide.
+ //
+ // The format for this parameter, as described by its regex pattern, is a string
+ // of characters up to 2048 characters in length. The characters can be any
+ // ASCII character from the space character to the end of the valid character
+ // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A),
+ // and carriage return (\u000D) characters.
+ //
+ // The policy plain text must be 2048 bytes or shorter. However, an internal
+ // conversion compresses it into a packed binary format with a separate limit.
+ // The PackedPolicySize response element indicates by percentage how close to
+ // the upper size limit the policy is, with 100% equaling the maximum allowed
+ // size.
+ Policy *string `min:"1" type:"string"`
+
+ // The Amazon Resource Name (ARN) of the SAML provider in IAM that describes
+ // the IdP.
+ //
+ // PrincipalArn is a required field
+ PrincipalArn *string `min:"20" type:"string" required:"true"`
+
+ // The Amazon Resource Name (ARN) of the role that the caller is assuming.
+ //
+ // RoleArn is a required field
+ RoleArn *string `min:"20" type:"string" required:"true"`
+
+ // The base-64 encoded SAML authentication response provided by the IdP.
+ //
+ // For more information, see Configuring a Relying Party and Adding Claims (http://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html)
+ // in the Using IAM guide.
+ //
+ // SAMLAssertion is a required field
+ SAMLAssertion *string `min:"4" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s AssumeRoleWithSAMLInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s AssumeRoleWithSAMLInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *AssumeRoleWithSAMLInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "AssumeRoleWithSAMLInput"}
+ if s.DurationSeconds != nil && *s.DurationSeconds < 900 {
+ invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900))
+ }
+ if s.Policy != nil && len(*s.Policy) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("Policy", 1))
+ }
+ if s.PrincipalArn == nil {
+ invalidParams.Add(request.NewErrParamRequired("PrincipalArn"))
+ }
+ if s.PrincipalArn != nil && len(*s.PrincipalArn) < 20 {
+ invalidParams.Add(request.NewErrParamMinLen("PrincipalArn", 20))
+ }
+ if s.RoleArn == nil {
+ invalidParams.Add(request.NewErrParamRequired("RoleArn"))
+ }
+ if s.RoleArn != nil && len(*s.RoleArn) < 20 {
+ invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20))
+ }
+ if s.SAMLAssertion == nil {
+ invalidParams.Add(request.NewErrParamRequired("SAMLAssertion"))
+ }
+ if s.SAMLAssertion != nil && len(*s.SAMLAssertion) < 4 {
+ invalidParams.Add(request.NewErrParamMinLen("SAMLAssertion", 4))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+// Contains the response to a successful AssumeRoleWithSAML request, including
+// temporary AWS credentials that can be used to make AWS requests.
+type AssumeRoleWithSAMLOutput struct {
+ _ struct{} `type:"structure"`
+
+ // The identifiers for the temporary security credentials that the operation
+ // returns.
+ AssumedRoleUser *AssumedRoleUser `type:"structure"`
+
+ // The value of the Recipient attribute of the SubjectConfirmationData element
+ // of the SAML assertion.
+ Audience *string `type:"string"`
+
+ // The temporary security credentials, which include an access key ID, a secret
+ // access key, and a security (or session) token.
+ //
+ // Note: The size of the security token that STS APIs return is not fixed. We
+ // strongly recommend that you make no assumptions about the maximum size. As
+ // of this writing, the typical size is less than 4096 bytes, but that can vary.
+ // Also, future updates to AWS might require larger sizes.
+ Credentials *Credentials `type:"structure"`
+
+ // The value of the Issuer element of the SAML assertion.
+ Issuer *string `type:"string"`
+
+ // A hash value based on the concatenation of the Issuer response value, the
+ // AWS account ID, and the friendly name (the last part of the ARN) of the SAML
+ // provider in IAM. The combination of NameQualifier and Subject can be used
+ // to uniquely identify a federated user.
+ //
+ // The following pseudocode shows how the hash value is calculated:
+ //
+ // BASE64 ( SHA1 ( "https://example.com/saml" + "123456789012" + "/MySAMLIdP"
+ // ) )
+ NameQualifier *string `type:"string"`
+
+ // A percentage value that indicates the size of the policy in packed form.
+ // The service rejects any policy with a packed size greater than 100 percent,
+ // which means the policy exceeded the allowed space.
+ PackedPolicySize *int64 `type:"integer"`
+
+ // The value of the NameID element in the Subject element of the SAML assertion.
+ Subject *string `type:"string"`
+
+ // The format of the name ID, as defined by the Format attribute in the NameID
+ // element of the SAML assertion. Typical examples of the format are transient
+ // or persistent.
+ //
+ // If the format includes the prefix urn:oasis:names:tc:SAML:2.0:nameid-format,
+ // that prefix is removed. For example, urn:oasis:names:tc:SAML:2.0:nameid-format:transient
+ // is returned as transient. If the format includes any other prefix, the format
+ // is returned with no modifications.
+ SubjectType *string `type:"string"`
+}
+
+// String returns the string representation
+func (s AssumeRoleWithSAMLOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s AssumeRoleWithSAMLOutput) GoString() string {
+ return s.String()
+}
+
+type AssumeRoleWithWebIdentityInput struct {
+ _ struct{} `type:"structure"`
+
+ // The duration, in seconds, of the role session. The value can range from 900
+ // seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set
+ // to 3600 seconds.
+ //
+ // This is separate from the duration of a console session that you might request
+ // using the returned credentials. The request to the federation endpoint for
+ // a console sign-in token takes a SessionDuration parameter that specifies
+ // the maximum length of the console session, separately from the DurationSeconds
+ // parameter on this API. For more information, see Creating a URL that Enables
+ // Federated Users to Access the AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html)
+ // in the IAM User Guide.
+ DurationSeconds *int64 `min:"900" type:"integer"`
+
+ // An IAM policy in JSON format.
+ //
+ // The policy parameter is optional. If you pass a policy, the temporary security
+ // credentials that are returned by the operation have the permissions that
+ // are allowed by both the access policy of the role that is being assumed,
+ // and the policy that you pass. This gives you a way to further restrict the
+ // permissions for the resulting temporary security credentials. You cannot
+ // use the passed policy to grant permissions that are in excess of those allowed
+ // by the access policy of the role that is being assumed. For more information,
+ // see Permissions for AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html)
+ // in the IAM User Guide.
+ //
+ // The format for this parameter, as described by its regex pattern, is a string
+ // of characters up to 2048 characters in length. The characters can be any
+ // ASCII character from the space character to the end of the valid character
+ // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A),
+ // and carriage return (\u000D) characters.
+ //
+ // The policy plain text must be 2048 bytes or shorter. However, an internal
+ // conversion compresses it into a packed binary format with a separate limit.
+ // The PackedPolicySize response element indicates by percentage how close to
+ // the upper size limit the policy is, with 100% equaling the maximum allowed
+ // size.
+ Policy *string `min:"1" type:"string"`
+
+ // The fully qualified host component of the domain name of the identity provider.
+ //
+ // Specify this value only for OAuth 2.0 access tokens. Currently www.amazon.com
+ // and graph.facebook.com are the only supported identity providers for OAuth
+ // 2.0 access tokens. Do not include URL schemes and port numbers.
+ //
+ // Do not specify this value for OpenID Connect ID tokens.
+ ProviderId *string `min:"4" type:"string"`
+
+ // The Amazon Resource Name (ARN) of the role that the caller is assuming.
+ //
+ // RoleArn is a required field
+ RoleArn *string `min:"20" type:"string" required:"true"`
+
+ // An identifier for the assumed role session. Typically, you pass the name
+ // or identifier that is associated with the user who is using your application.
+ // That way, the temporary security credentials that your application will use
+ // are associated with that user. This session name is included as part of the
+ // ARN and assumed role ID in the AssumedRoleUser response element.
+ //
+ // The format for this parameter, as described by its regex pattern, is a string
+ // of characters consisting of upper- and lower-case alphanumeric characters
+ // with no spaces. You can also include underscores or any of the following
+ // characters: =,.@-
+ //
+ // RoleSessionName is a required field
+ RoleSessionName *string `min:"2" type:"string" required:"true"`
+
+ // The OAuth 2.0 access token or OpenID Connect ID token that is provided by
+ // the identity provider. Your application must get this token by authenticating
+ // the user who is using your application with a web identity provider before
+ // the application makes an AssumeRoleWithWebIdentity call.
+ //
+ // WebIdentityToken is a required field
+ WebIdentityToken *string `min:"4" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s AssumeRoleWithWebIdentityInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s AssumeRoleWithWebIdentityInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *AssumeRoleWithWebIdentityInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "AssumeRoleWithWebIdentityInput"}
+ if s.DurationSeconds != nil && *s.DurationSeconds < 900 {
+ invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900))
+ }
+ if s.Policy != nil && len(*s.Policy) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("Policy", 1))
+ }
+ if s.ProviderId != nil && len(*s.ProviderId) < 4 {
+ invalidParams.Add(request.NewErrParamMinLen("ProviderId", 4))
+ }
+ if s.RoleArn == nil {
+ invalidParams.Add(request.NewErrParamRequired("RoleArn"))
+ }
+ if s.RoleArn != nil && len(*s.RoleArn) < 20 {
+ invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20))
+ }
+ if s.RoleSessionName == nil {
+ invalidParams.Add(request.NewErrParamRequired("RoleSessionName"))
+ }
+ if s.RoleSessionName != nil && len(*s.RoleSessionName) < 2 {
+ invalidParams.Add(request.NewErrParamMinLen("RoleSessionName", 2))
+ }
+ if s.WebIdentityToken == nil {
+ invalidParams.Add(request.NewErrParamRequired("WebIdentityToken"))
+ }
+ if s.WebIdentityToken != nil && len(*s.WebIdentityToken) < 4 {
+ invalidParams.Add(request.NewErrParamMinLen("WebIdentityToken", 4))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+// Contains the response to a successful AssumeRoleWithWebIdentity request,
+// including temporary AWS credentials that can be used to make AWS requests.
+type AssumeRoleWithWebIdentityOutput struct {
+ _ struct{} `type:"structure"`
+
+ // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers
+ // that you can use to refer to the resulting temporary security credentials.
+ // For example, you can reference these credentials as a principal in a resource-based
+ // policy by using the ARN or assumed role ID. The ARN and ID include the RoleSessionName
+ // that you specified when you called AssumeRole.
+ AssumedRoleUser *AssumedRoleUser `type:"structure"`
+
+ // The intended audience (also known as client ID) of the web identity token.
+ // This is traditionally the client identifier issued to the application that
+ // requested the web identity token.
+ Audience *string `type:"string"`
+
+ // The temporary security credentials, which include an access key ID, a secret
+ // access key, and a security token.
+ //
+ // Note: The size of the security token that STS APIs return is not fixed. We
+ // strongly recommend that you make no assumptions about the maximum size. As
+ // of this writing, the typical size is less than 4096 bytes, but that can vary.
+ // Also, future updates to AWS might require larger sizes.
+ Credentials *Credentials `type:"structure"`
+
+ // A percentage value that indicates the size of the policy in packed form.
+ // The service rejects any policy with a packed size greater than 100 percent,
+ // which means the policy exceeded the allowed space.
+ PackedPolicySize *int64 `type:"integer"`
+
+ // The issuing authority of the web identity token presented. For OpenID Connect
+ // ID Tokens this contains the value of the iss field. For OAuth 2.0 access
+ // tokens, this contains the value of the ProviderId parameter that was passed
+ // in the AssumeRoleWithWebIdentity request.
+ Provider *string `type:"string"`
+
+ // The unique user identifier that is returned by the identity provider. This
+ // identifier is associated with the WebIdentityToken that was submitted with
+ // the AssumeRoleWithWebIdentity call. The identifier is typically unique to
+ // the user and the application that acquired the WebIdentityToken (pairwise
+ // identifier). For OpenID Connect ID tokens, this field contains the value
+ // returned by the identity provider as the token's sub (Subject) claim.
+ SubjectFromWebIdentityToken *string `min:"6" type:"string"`
+}
+
+// String returns the string representation
+func (s AssumeRoleWithWebIdentityOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s AssumeRoleWithWebIdentityOutput) GoString() string {
+ return s.String()
+}
+
+// The identifiers for the temporary security credentials that the operation
+// returns.
+type AssumedRoleUser struct {
+ _ struct{} `type:"structure"`
+
+ // The ARN of the temporary security credentials that are returned from the
+ // AssumeRole action. For more information about ARNs and how to use them in
+ // policies, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html)
+ // in Using IAM.
+ //
+ // Arn is a required field
+ Arn *string `min:"20" type:"string" required:"true"`
+
+ // A unique identifier that contains the role ID and the role session name of
+ // the role that is being assumed. The role ID is generated by AWS when the
+ // role is created.
+ //
+ // AssumedRoleId is a required field
+ AssumedRoleId *string `min:"2" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s AssumedRoleUser) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s AssumedRoleUser) GoString() string {
+ return s.String()
+}
+
+// AWS credentials for API authentication.
+type Credentials struct {
+ _ struct{} `type:"structure"`
+
+ // The access key ID that identifies the temporary security credentials.
+ //
+ // AccessKeyId is a required field
+ AccessKeyId *string `min:"16" type:"string" required:"true"`
+
+ // The date on which the current credentials expire.
+ //
+ // Expiration is a required field
+ Expiration *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"`
+
+ // The secret access key that can be used to sign requests.
+ //
+ // SecretAccessKey is a required field
+ SecretAccessKey *string `type:"string" required:"true"`
+
+ // The token that users must pass to the service API to use the temporary credentials.
+ //
+ // SessionToken is a required field
+ SessionToken *string `type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s Credentials) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s Credentials) GoString() string {
+ return s.String()
+}
+
+type DecodeAuthorizationMessageInput struct {
+ _ struct{} `type:"structure"`
+
+ // The encoded message that was returned with the response.
+ //
+ // EncodedMessage is a required field
+ EncodedMessage *string `min:"1" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s DecodeAuthorizationMessageInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DecodeAuthorizationMessageInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *DecodeAuthorizationMessageInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "DecodeAuthorizationMessageInput"}
+ if s.EncodedMessage == nil {
+ invalidParams.Add(request.NewErrParamRequired("EncodedMessage"))
+ }
+ if s.EncodedMessage != nil && len(*s.EncodedMessage) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("EncodedMessage", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+// A document that contains additional information about the authorization status
+// of a request from an encoded message that is returned in response to an AWS
+// request.
+type DecodeAuthorizationMessageOutput struct {
+ _ struct{} `type:"structure"`
+
+ // An XML document that contains the decoded message.
+ DecodedMessage *string `type:"string"`
+}
+
+// String returns the string representation
+func (s DecodeAuthorizationMessageOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s DecodeAuthorizationMessageOutput) GoString() string {
+ return s.String()
+}
+
+// Identifiers for the federated user that is associated with the credentials.
+type FederatedUser struct {
+ _ struct{} `type:"structure"`
+
+ // The ARN that specifies the federated user that is associated with the credentials.
+ // For more information about ARNs and how to use them in policies, see IAM
+ // Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html)
+ // in Using IAM.
+ //
+ // Arn is a required field
+ Arn *string `min:"20" type:"string" required:"true"`
+
+ // The string that identifies the federated user associated with the credentials,
+ // similar to the unique ID of an IAM user.
+ //
+ // FederatedUserId is a required field
+ FederatedUserId *string `min:"2" type:"string" required:"true"`
+}
+
+// String returns the string representation
+func (s FederatedUser) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s FederatedUser) GoString() string {
+ return s.String()
+}
+
+type GetCallerIdentityInput struct {
+ _ struct{} `type:"structure"`
+}
+
+// String returns the string representation
+func (s GetCallerIdentityInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s GetCallerIdentityInput) GoString() string {
+ return s.String()
+}
+
+// Contains the response to a successful GetCallerIdentity request, including
+// information about the entity making the request.
+type GetCallerIdentityOutput struct {
+ _ struct{} `type:"structure"`
+
+ // The AWS account ID number of the account that owns or contains the calling
+ // entity.
+ Account *string `type:"string"`
+
+ // The AWS ARN associated with the calling entity.
+ Arn *string `min:"20" type:"string"`
+
+ // The unique identifier of the calling entity. The exact value depends on the
+ // type of entity making the call. The values returned are those listed in the
+ // aws:userid column in the Principal table (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html#principaltable)
+ // found on the Policy Variables reference page in the IAM User Guide.
+ UserId *string `type:"string"`
+}
+
+// String returns the string representation
+func (s GetCallerIdentityOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s GetCallerIdentityOutput) GoString() string {
+ return s.String()
+}
+
+type GetFederationTokenInput struct {
+ _ struct{} `type:"structure"`
+
+ // The duration, in seconds, that the session should last. Acceptable durations
+ // for federation sessions range from 900 seconds (15 minutes) to 129600 seconds
+ // (36 hours), with 43200 seconds (12 hours) as the default. Sessions obtained
+ // using AWS account (root) credentials are restricted to a maximum of 3600
+ // seconds (one hour). If the specified duration is longer than one hour, the
+ // session obtained by using AWS account (root) credentials defaults to one
+ // hour.
+ DurationSeconds *int64 `min:"900" type:"integer"`
+
+ // The name of the federated user. The name is used as an identifier for the
+ // temporary security credentials (such as Bob). For example, you can reference
+ // the federated user name in a resource-based policy, such as in an Amazon
+ // S3 bucket policy.
+ //
+ // The format for this parameter, as described by its regex pattern, is a string
+ // of characters consisting of upper- and lower-case alphanumeric characters
+ // with no spaces. You can also include underscores or any of the following
+ // characters: =,.@-
+ //
+ // Name is a required field
+ Name *string `min:"2" type:"string" required:"true"`
+
+ // An IAM policy in JSON format that is passed with the GetFederationToken call
+ // and evaluated along with the policy or policies that are attached to the
+ // IAM user whose credentials are used to call GetFederationToken. The passed
+ // policy is used to scope down the permissions that are available to the IAM
+ // user, by allowing only a subset of the permissions that are granted to the
+ // IAM user. The passed policy cannot grant more permissions than those granted
+ // to the IAM user. The final permissions for the federated user are the most
+ // restrictive set based on the intersection of the passed policy and the IAM
+ // user policy.
+ //
+ // If you do not pass a policy, the resulting temporary security credentials
+ // have no effective permissions. The only exception is when the temporary security
+ // credentials are used to access a resource that has a resource-based policy
+ // that specifically allows the federated user to access the resource.
+ //
+ // The format for this parameter, as described by its regex pattern, is a string
+ // of characters up to 2048 characters in length. The characters can be any
+ // ASCII character from the space character to the end of the valid character
+ // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A),
+ // and carriage return (\u000D) characters.
+ //
+ // The policy plain text must be 2048 bytes or shorter. However, an internal
+ // conversion compresses it into a packed binary format with a separate limit.
+ // The PackedPolicySize response element indicates by percentage how close to
+ // the upper size limit the policy is, with 100% equaling the maximum allowed
+ // size.
+ //
+ // For more information about how permissions work, see Permissions for GetFederationToken
+ // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getfederationtoken.html).
+ Policy *string `min:"1" type:"string"`
+}
+
+// String returns the string representation
+func (s GetFederationTokenInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s GetFederationTokenInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *GetFederationTokenInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "GetFederationTokenInput"}
+ if s.DurationSeconds != nil && *s.DurationSeconds < 900 {
+ invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900))
+ }
+ if s.Name == nil {
+ invalidParams.Add(request.NewErrParamRequired("Name"))
+ }
+ if s.Name != nil && len(*s.Name) < 2 {
+ invalidParams.Add(request.NewErrParamMinLen("Name", 2))
+ }
+ if s.Policy != nil && len(*s.Policy) < 1 {
+ invalidParams.Add(request.NewErrParamMinLen("Policy", 1))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+// Contains the response to a successful GetFederationToken request, including
+// temporary AWS credentials that can be used to make AWS requests.
+type GetFederationTokenOutput struct {
+ _ struct{} `type:"structure"`
+
+ // The temporary security credentials, which include an access key ID, a secret
+ // access key, and a security (or session) token.
+ //
+ // Note: The size of the security token that STS APIs return is not fixed. We
+ // strongly recommend that you make no assumptions about the maximum size. As
+ // of this writing, the typical size is less than 4096 bytes, but that can vary.
+ // Also, future updates to AWS might require larger sizes.
+ Credentials *Credentials `type:"structure"`
+
+ // Identifiers for the federated user associated with the credentials (such
+ // as arn:aws:sts::123456789012:federated-user/Bob or 123456789012:Bob). You
+ // can use the federated user's ARN in your resource-based policies, such as
+ // an Amazon S3 bucket policy.
+ FederatedUser *FederatedUser `type:"structure"`
+
+ // A percentage value indicating the size of the policy in packed form. The
+ // service rejects policies for which the packed size is greater than 100 percent
+ // of the allowed value.
+ PackedPolicySize *int64 `type:"integer"`
+}
+
+// String returns the string representation
+func (s GetFederationTokenOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s GetFederationTokenOutput) GoString() string {
+ return s.String()
+}
+
+type GetSessionTokenInput struct {
+ _ struct{} `type:"structure"`
+
+ // The duration, in seconds, that the credentials should remain valid. Acceptable
+ // durations for IAM user sessions range from 900 seconds (15 minutes) to 129600
+ // seconds (36 hours), with 43200 seconds (12 hours) as the default. Sessions
+ // for AWS account owners are restricted to a maximum of 3600 seconds (one hour).
+ // If the duration is longer than one hour, the session for AWS account owners
+ // defaults to one hour.
+ DurationSeconds *int64 `min:"900" type:"integer"`
+
+ // The identification number of the MFA device that is associated with the IAM
+ // user who is making the GetSessionToken call. Specify this value if the IAM
+ // user has a policy that requires MFA authentication. The value is either the
+ // serial number for a hardware device (such as GAHT12345678) or an Amazon Resource
+ // Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user).
+ // You can find the device for an IAM user by going to the AWS Management Console
+ // and viewing the user's security credentials.
+ //
+ // The format for this parameter, as described by its regex pattern, is a string
+ // of characters consisting of upper- and lower-case alphanumeric characters
+ // with no spaces. You can also include underscores or any of the following
+ // characters: =,.@-
+ SerialNumber *string `min:"9" type:"string"`
+
+ // The value provided by the MFA device, if MFA is required. If any policy requires
+ // the IAM user to submit an MFA code, specify this value. If MFA authentication
+ // is required, and the user does not provide a code when requesting a set of
+ // temporary security credentials, the user will receive an "access denied"
+ // response when requesting resources that require MFA authentication.
+ //
+ // The format for this parameter, as described by its regex pattern, is a sequence
+ // of six numeric digits.
+ TokenCode *string `min:"6" type:"string"`
+}
+
+// String returns the string representation
+func (s GetSessionTokenInput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s GetSessionTokenInput) GoString() string {
+ return s.String()
+}
+
+// Validate inspects the fields of the type to determine if they are valid.
+func (s *GetSessionTokenInput) Validate() error {
+ invalidParams := request.ErrInvalidParams{Context: "GetSessionTokenInput"}
+ if s.DurationSeconds != nil && *s.DurationSeconds < 900 {
+ invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900))
+ }
+ if s.SerialNumber != nil && len(*s.SerialNumber) < 9 {
+ invalidParams.Add(request.NewErrParamMinLen("SerialNumber", 9))
+ }
+ if s.TokenCode != nil && len(*s.TokenCode) < 6 {
+ invalidParams.Add(request.NewErrParamMinLen("TokenCode", 6))
+ }
+
+ if invalidParams.Len() > 0 {
+ return invalidParams
+ }
+ return nil
+}
+
+// Contains the response to a successful GetSessionToken request, including
+// temporary AWS credentials that can be used to make AWS requests.
+type GetSessionTokenOutput struct {
+ _ struct{} `type:"structure"`
+
+ // The temporary security credentials, which include an access key ID, a secret
+ // access key, and a security (or session) token.
+ //
+ // Note: The size of the security token that STS APIs return is not fixed. We
+ // strongly recommend that you make no assumptions about the maximum size. As
+ // of this writing, the typical size is less than 4096 bytes, but that can vary.
+ // Also, future updates to AWS might require larger sizes.
+ Credentials *Credentials `type:"structure"`
+}
+
+// String returns the string representation
+func (s GetSessionTokenOutput) String() string {
+ return awsutil.Prettify(s)
+}
+
+// GoString returns the string representation
+func (s GetSessionTokenOutput) GoString() string {
+ return s.String()
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go
new file mode 100644
index 0000000..4010cc7
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go
@@ -0,0 +1,12 @@
+package sts
+
+import "github.com/aws/aws-sdk-go/aws/request"
+
+func init() {
+ initRequest = func(r *request.Request) {
+ switch r.Operation.Name {
+ case opAssumeRoleWithSAML, opAssumeRoleWithWebIdentity:
+ r.Handlers.Sign.Clear() // these operations are unsigned
+ }
+ }
+}
diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go
new file mode 100644
index 0000000..a9b9b32
--- /dev/null
+++ b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go
@@ -0,0 +1,130 @@
+// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.
+
+package sts
+
+import (
+ "github.com/aws/aws-sdk-go/aws"
+ "github.com/aws/aws-sdk-go/aws/client"
+ "github.com/aws/aws-sdk-go/aws/client/metadata"
+ "github.com/aws/aws-sdk-go/aws/request"
+ "github.com/aws/aws-sdk-go/aws/signer/v4"
+ "github.com/aws/aws-sdk-go/private/protocol/query"
+)
+
+// The AWS Security Token Service (STS) is a web service that enables you to
+// request temporary, limited-privilege credentials for AWS Identity and Access
+// Management (IAM) users or for users that you authenticate (federated users).
+// This guide provides descriptions of the STS API. For more detailed information
+// about using this service, go to Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html).
+//
+// As an alternative to using the API, you can use one of the AWS SDKs, which
+// consist of libraries and sample code for various programming languages and
+// platforms (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient
+// way to create programmatic access to STS. For example, the SDKs take care
+// of cryptographically signing requests, managing errors, and retrying requests
+// automatically. For information about the AWS SDKs, including how to download
+// and install them, see the Tools for Amazon Web Services page (http://aws.amazon.com/tools/).
+//
+// For information about setting up signatures and authorization through the
+// API, go to Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html)
+// in the AWS General Reference. For general information about the Query API,
+// go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html)
+// in Using IAM. For information about using security tokens with other AWS
+// products, go to AWS Services That Work with IAM (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html)
+// in the IAM User Guide.
+//
+// If you're new to AWS and need additional technical information about a specific
+// AWS product, you can find the product's technical documentation at http://aws.amazon.com/documentation/
+// (http://aws.amazon.com/documentation/).
+//
+// Endpoints
+//
+// The AWS Security Token Service (STS) has a default endpoint of https://sts.amazonaws.com
+// that maps to the US East (N. Virginia) region. Additional regions are available
+// and are activated by default. For more information, see Activating and Deactivating
+// AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html)
+// in the IAM User Guide.
+//
+// For information about STS endpoints, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region)
+// in the AWS General Reference.
+//
+// Recording API requests
+//
+// STS supports AWS CloudTrail, which is a service that records AWS calls for
+// your AWS account and delivers log files to an Amazon S3 bucket. By using
+// information collected by CloudTrail, you can determine what requests were
+// successfully made to STS, who made the request, when it was made, and so
+// on. To learn more about CloudTrail, including how to turn it on and find
+// your log files, see the AWS CloudTrail User Guide (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html).
+//The service client's operations are safe to be used concurrently.
+// It is not safe to mutate any of the client's properties though.
+type STS struct {
+ *client.Client
+}
+
+// Used for custom client initialization logic
+var initClient func(*client.Client)
+
+// Used for custom request initialization logic
+var initRequest func(*request.Request)
+
+// A ServiceName is the name of the service the client will make API calls to.
+const ServiceName = "sts"
+
+// New creates a new instance of the STS client with a session.
+// If additional configuration is needed for the client instance use the optional
+// aws.Config parameter to add your extra config.
+//
+// Example:
+// // Create a STS client from just a session.
+// svc := sts.New(mySession)
+//
+// // Create a STS client with additional configuration
+// svc := sts.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
+func New(p client.ConfigProvider, cfgs ...*aws.Config) *STS {
+ c := p.ClientConfig(ServiceName, cfgs...)
+ return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
+}
+
+// newClient creates, initializes and returns a new service client instance.
+func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *STS {
+ svc := &STS{
+ Client: client.New(
+ cfg,
+ metadata.ClientInfo{
+ ServiceName: ServiceName,
+ SigningRegion: signingRegion,
+ Endpoint: endpoint,
+ APIVersion: "2011-06-15",
+ },
+ handlers,
+ ),
+ }
+
+ // Handlers
+ svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
+ svc.Handlers.Build.PushBackNamed(query.BuildHandler)
+ svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler)
+ svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler)
+ svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler)
+
+ // Run custom client initialization if present
+ if initClient != nil {
+ initClient(svc.Client)
+ }
+
+ return svc
+}
+
+// newRequest creates a new request for a STS operation and runs any
+// custom request initialization.
+func (c *STS) newRequest(op *request.Operation, params, data interface{}) *request.Request {
+ req := c.NewRequest(op, params, data)
+
+ // Run custom request initialization if present
+ if initRequest != nil {
+ initRequest(req)
+ }
+
+ return req
+}
diff --git a/vendor/github.com/beorn7/perks/LICENSE b/vendor/github.com/beorn7/perks/LICENSE
new file mode 100644
index 0000000..339177b
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/LICENSE
@@ -0,0 +1,20 @@
+Copyright (C) 2013 Blake Mizerany
+
+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/beorn7/perks/README.md b/vendor/github.com/beorn7/perks/README.md
new file mode 100644
index 0000000..fc05777
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/README.md
@@ -0,0 +1,31 @@
+# Perks for Go (golang.org)
+
+Perks contains the Go package quantile that computes approximate quantiles over
+an unbounded data stream within low memory and CPU bounds.
+
+For more information and examples, see:
+http://godoc.org/github.com/bmizerany/perks
+
+A very special thank you and shout out to Graham Cormode (Rutgers University),
+Flip Korn (AT&T Labs–Research), S. Muthukrishnan (Rutgers University), and
+Divesh Srivastava (AT&T Labs–Research) for their research and publication of
+[Effective Computation of Biased Quantiles over Data Streams](http://www.cs.rutgers.edu/~muthu/bquant.pdf)
+
+Thank you, also:
+* Armon Dadgar (@armon)
+* Andrew Gerrand (@nf)
+* Brad Fitzpatrick (@bradfitz)
+* Keith Rarick (@kr)
+
+FAQ:
+
+Q: Why not move the quantile package into the project root?
+A: I want to add more packages to perks later.
+
+Copyright (C) 2013 Blake Mizerany
+
+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/beorn7/perks/quantile/stream.go b/vendor/github.com/beorn7/perks/quantile/stream.go
new file mode 100644
index 0000000..f4cabd6
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/quantile/stream.go
@@ -0,0 +1,292 @@
+// Package quantile computes approximate quantiles over an unbounded data
+// stream within low memory and CPU bounds.
+//
+// A small amount of accuracy is traded to achieve the above properties.
+//
+// Multiple streams can be merged before calling Query to generate a single set
+// of results. This is meaningful when the streams represent the same type of
+// data. See Merge and Samples.
+//
+// For more detailed information about the algorithm used, see:
+//
+// Effective Computation of Biased Quantiles over Data Streams
+//
+// http://www.cs.rutgers.edu/~muthu/bquant.pdf
+package quantile
+
+import (
+ "math"
+ "sort"
+)
+
+// Sample holds an observed value and meta information for compression. JSON
+// tags have been added for convenience.
+type Sample struct {
+ Value float64 `json:",string"`
+ Width float64 `json:",string"`
+ Delta float64 `json:",string"`
+}
+
+// Samples represents a slice of samples. It implements sort.Interface.
+type Samples []Sample
+
+func (a Samples) Len() int { return len(a) }
+func (a Samples) Less(i, j int) bool { return a[i].Value < a[j].Value }
+func (a Samples) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
+
+type invariant func(s *stream, r float64) float64
+
+// NewLowBiased returns an initialized Stream for low-biased quantiles
+// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but
+// error guarantees can still be given even for the lower ranks of the data
+// distribution.
+//
+// The provided epsilon is a relative error, i.e. the true quantile of a value
+// returned by a query is guaranteed to be within (1±Epsilon)*Quantile.
+//
+// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error
+// properties.
+func NewLowBiased(epsilon float64) *Stream {
+ ƒ := func(s *stream, r float64) float64 {
+ return 2 * epsilon * r
+ }
+ return newStream(ƒ)
+}
+
+// NewHighBiased returns an initialized Stream for high-biased quantiles
+// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but
+// error guarantees can still be given even for the higher ranks of the data
+// distribution.
+//
+// The provided epsilon is a relative error, i.e. the true quantile of a value
+// returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile).
+//
+// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error
+// properties.
+func NewHighBiased(epsilon float64) *Stream {
+ ƒ := func(s *stream, r float64) float64 {
+ return 2 * epsilon * (s.n - r)
+ }
+ return newStream(ƒ)
+}
+
+// NewTargeted returns an initialized Stream concerned with a particular set of
+// quantile values that are supplied a priori. Knowing these a priori reduces
+// space and computation time. The targets map maps the desired quantiles to
+// their absolute errors, i.e. the true quantile of a value returned by a query
+// is guaranteed to be within (Quantile±Epsilon).
+//
+// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties.
+func NewTargeted(targets map[float64]float64) *Stream {
+ ƒ := func(s *stream, r float64) float64 {
+ var m = math.MaxFloat64
+ var f float64
+ for quantile, epsilon := range targets {
+ if quantile*s.n <= r {
+ f = (2 * epsilon * r) / quantile
+ } else {
+ f = (2 * epsilon * (s.n - r)) / (1 - quantile)
+ }
+ if f < m {
+ m = f
+ }
+ }
+ return m
+ }
+ return newStream(ƒ)
+}
+
+// Stream computes quantiles for a stream of float64s. It is not thread-safe by
+// design. Take care when using across multiple goroutines.
+type Stream struct {
+ *stream
+ b Samples
+ sorted bool
+}
+
+func newStream(ƒ invariant) *Stream {
+ x := &stream{ƒ: ƒ}
+ return &Stream{x, make(Samples, 0, 500), true}
+}
+
+// Insert inserts v into the stream.
+func (s *Stream) Insert(v float64) {
+ s.insert(Sample{Value: v, Width: 1})
+}
+
+func (s *Stream) insert(sample Sample) {
+ s.b = append(s.b, sample)
+ s.sorted = false
+ if len(s.b) == cap(s.b) {
+ s.flush()
+ }
+}
+
+// Query returns the computed qth percentiles value. If s was created with
+// NewTargeted, and q is not in the set of quantiles provided a priori, Query
+// will return an unspecified result.
+func (s *Stream) Query(q float64) float64 {
+ if !s.flushed() {
+ // Fast path when there hasn't been enough data for a flush;
+ // this also yields better accuracy for small sets of data.
+ l := len(s.b)
+ if l == 0 {
+ return 0
+ }
+ i := int(math.Ceil(float64(l) * q))
+ if i > 0 {
+ i -= 1
+ }
+ s.maybeSort()
+ return s.b[i].Value
+ }
+ s.flush()
+ return s.stream.query(q)
+}
+
+// Merge merges samples into the underlying streams samples. This is handy when
+// merging multiple streams from separate threads, database shards, etc.
+//
+// ATTENTION: This method is broken and does not yield correct results. The
+// underlying algorithm is not capable of merging streams correctly.
+func (s *Stream) Merge(samples Samples) {
+ sort.Sort(samples)
+ s.stream.merge(samples)
+}
+
+// Reset reinitializes and clears the list reusing the samples buffer memory.
+func (s *Stream) Reset() {
+ s.stream.reset()
+ s.b = s.b[:0]
+}
+
+// Samples returns stream samples held by s.
+func (s *Stream) Samples() Samples {
+ if !s.flushed() {
+ return s.b
+ }
+ s.flush()
+ return s.stream.samples()
+}
+
+// Count returns the total number of samples observed in the stream
+// since initialization.
+func (s *Stream) Count() int {
+ return len(s.b) + s.stream.count()
+}
+
+func (s *Stream) flush() {
+ s.maybeSort()
+ s.stream.merge(s.b)
+ s.b = s.b[:0]
+}
+
+func (s *Stream) maybeSort() {
+ if !s.sorted {
+ s.sorted = true
+ sort.Sort(s.b)
+ }
+}
+
+func (s *Stream) flushed() bool {
+ return len(s.stream.l) > 0
+}
+
+type stream struct {
+ n float64
+ l []Sample
+ ƒ invariant
+}
+
+func (s *stream) reset() {
+ s.l = s.l[:0]
+ s.n = 0
+}
+
+func (s *stream) insert(v float64) {
+ s.merge(Samples{{v, 1, 0}})
+}
+
+func (s *stream) merge(samples Samples) {
+ // TODO(beorn7): This tries to merge not only individual samples, but
+ // whole summaries. The paper doesn't mention merging summaries at
+ // all. Unittests show that the merging is inaccurate. Find out how to
+ // do merges properly.
+ var r float64
+ i := 0
+ for _, sample := range samples {
+ for ; i < len(s.l); i++ {
+ c := s.l[i]
+ if c.Value > sample.Value {
+ // Insert at position i.
+ s.l = append(s.l, Sample{})
+ copy(s.l[i+1:], s.l[i:])
+ s.l[i] = Sample{
+ sample.Value,
+ sample.Width,
+ math.Max(sample.Delta, math.Floor(s.ƒ(s, r))-1),
+ // TODO(beorn7): How to calculate delta correctly?
+ }
+ i++
+ goto inserted
+ }
+ r += c.Width
+ }
+ s.l = append(s.l, Sample{sample.Value, sample.Width, 0})
+ i++
+ inserted:
+ s.n += sample.Width
+ r += sample.Width
+ }
+ s.compress()
+}
+
+func (s *stream) count() int {
+ return int(s.n)
+}
+
+func (s *stream) query(q float64) float64 {
+ t := math.Ceil(q * s.n)
+ t += math.Ceil(s.ƒ(s, t) / 2)
+ p := s.l[0]
+ var r float64
+ for _, c := range s.l[1:] {
+ r += p.Width
+ if r+c.Width+c.Delta > t {
+ return p.Value
+ }
+ p = c
+ }
+ return p.Value
+}
+
+func (s *stream) compress() {
+ if len(s.l) < 2 {
+ return
+ }
+ x := s.l[len(s.l)-1]
+ xi := len(s.l) - 1
+ r := s.n - 1 - x.Width
+
+ for i := len(s.l) - 2; i >= 0; i-- {
+ c := s.l[i]
+ if c.Width+x.Width+x.Delta <= s.ƒ(s, r) {
+ x.Width += c.Width
+ s.l[xi] = x
+ // Remove element at i.
+ copy(s.l[i:], s.l[i+1:])
+ s.l = s.l[:len(s.l)-1]
+ xi -= 1
+ } else {
+ x = c
+ xi = i
+ }
+ r -= c.Width
+ }
+}
+
+func (s *stream) samples() Samples {
+ samples := make(Samples, len(s.l))
+ copy(samples, s.l)
+ return samples
+}
diff --git a/vendor/github.com/boltdb/bolt/LICENSE b/vendor/github.com/boltdb/bolt/LICENSE
new file mode 100644
index 0000000..004e77f
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Ben Johnson
+
+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/boltdb/bolt/README.md b/vendor/github.com/boltdb/bolt/README.md
new file mode 100644
index 0000000..2a69d95
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/README.md
@@ -0,0 +1,857 @@
+Bolt [![Coverage Status](https://coveralls.io/repos/boltdb/bolt/badge.svg?branch=master)](https://coveralls.io/r/boltdb/bolt?branch=master) [![GoDoc](https://godoc.org/github.com/boltdb/bolt?status.svg)](https://godoc.org/github.com/boltdb/bolt) ![Version](https://img.shields.io/badge/version-1.2.1-green.svg)
+====
+
+Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas]
+[LMDB project][lmdb]. The goal of the project is to provide a simple,
+fast, and reliable database for projects that don't require a full database
+server such as Postgres or MySQL.
+
+Since Bolt is meant to be used as such a low-level piece of functionality,
+simplicity is key. The API will be small and only focus on getting values
+and setting values. That's it.
+
+[hyc_symas]: https://twitter.com/hyc_symas
+[lmdb]: http://symas.com/mdb/
+
+## Project Status
+
+Bolt is stable, the API is fixed, and the file format is fixed. Full unit
+test coverage and randomized black box testing are used to ensure database
+consistency and thread safety. Bolt is currently in high-load production
+environments serving databases as large as 1TB. Many companies such as
+Shopify and Heroku use Bolt-backed services every day.
+
+## Table of Contents
+
+- [Getting Started](#getting-started)
+ - [Installing](#installing)
+ - [Opening a database](#opening-a-database)
+ - [Transactions](#transactions)
+ - [Read-write transactions](#read-write-transactions)
+ - [Read-only transactions](#read-only-transactions)
+ - [Batch read-write transactions](#batch-read-write-transactions)
+ - [Managing transactions manually](#managing-transactions-manually)
+ - [Using buckets](#using-buckets)
+ - [Using key/value pairs](#using-keyvalue-pairs)
+ - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket)
+ - [Iterating over keys](#iterating-over-keys)
+ - [Prefix scans](#prefix-scans)
+ - [Range scans](#range-scans)
+ - [ForEach()](#foreach)
+ - [Nested buckets](#nested-buckets)
+ - [Database backups](#database-backups)
+ - [Statistics](#statistics)
+ - [Read-Only Mode](#read-only-mode)
+ - [Mobile Use (iOS/Android)](#mobile-use-iosandroid)
+- [Resources](#resources)
+- [Comparison with other databases](#comparison-with-other-databases)
+ - [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases)
+ - [LevelDB, RocksDB](#leveldb-rocksdb)
+ - [LMDB](#lmdb)
+- [Caveats & Limitations](#caveats--limitations)
+- [Reading the Source](#reading-the-source)
+- [Other Projects Using Bolt](#other-projects-using-bolt)
+
+## Getting Started
+
+### Installing
+
+To start using Bolt, install Go and run `go get`:
+
+```sh
+$ go get github.com/boltdb/bolt/...
+```
+
+This will retrieve the library and install the `bolt` command line utility into
+your `$GOBIN` path.
+
+
+### Opening a database
+
+The top-level object in Bolt is a `DB`. It is represented as a single file on
+your disk and represents a consistent snapshot of your data.
+
+To open your database, simply use the `bolt.Open()` function:
+
+```go
+package main
+
+import (
+ "log"
+
+ "github.com/boltdb/bolt"
+)
+
+func main() {
+ // Open the my.db data file in your current directory.
+ // It will be created if it doesn't exist.
+ db, err := bolt.Open("my.db", 0600, nil)
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer db.Close()
+
+ ...
+}
+```
+
+Please note that Bolt obtains a file lock on the data file so multiple processes
+cannot open the same database at the same time. Opening an already open Bolt
+database will cause it to hang until the other process closes it. To prevent
+an indefinite wait you can pass a timeout option to the `Open()` function:
+
+```go
+db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
+```
+
+
+### Transactions
+
+Bolt allows only one read-write transaction at a time but allows as many
+read-only transactions as you want at a time. Each transaction has a consistent
+view of the data as it existed when the transaction started.
+
+Individual transactions and all objects created from them (e.g. buckets, keys)
+are not thread safe. To work with data in multiple goroutines you must start
+a transaction for each one or use locking to ensure only one goroutine accesses
+a transaction at a time. Creating transaction from the `DB` is thread safe.
+
+Read-only transactions and read-write transactions should not depend on one
+another and generally shouldn't be opened simultaneously in the same goroutine.
+This can cause a deadlock as the read-write transaction needs to periodically
+re-map the data file but it cannot do so while a read-only transaction is open.
+
+
+#### Read-write transactions
+
+To start a read-write transaction, you can use the `DB.Update()` function:
+
+```go
+err := db.Update(func(tx *bolt.Tx) error {
+ ...
+ return nil
+})
+```
+
+Inside the closure, you have a consistent view of the database. You commit the
+transaction by returning `nil` at the end. You can also rollback the transaction
+at any point by returning an error. All database operations are allowed inside
+a read-write transaction.
+
+Always check the return error as it will report any disk failures that can cause
+your transaction to not complete. If you return an error within your closure
+it will be passed through.
+
+
+#### Read-only transactions
+
+To start a read-only transaction, you can use the `DB.View()` function:
+
+```go
+err := db.View(func(tx *bolt.Tx) error {
+ ...
+ return nil
+})
+```
+
+You also get a consistent view of the database within this closure, however,
+no mutating operations are allowed within a read-only transaction. You can only
+retrieve buckets, retrieve values, and copy the database within a read-only
+transaction.
+
+
+#### Batch read-write transactions
+
+Each `DB.Update()` waits for disk to commit the writes. This overhead
+can be minimized by combining multiple updates with the `DB.Batch()`
+function:
+
+```go
+err := db.Batch(func(tx *bolt.Tx) error {
+ ...
+ return nil
+})
+```
+
+Concurrent Batch calls are opportunistically combined into larger
+transactions. Batch is only useful when there are multiple goroutines
+calling it.
+
+The trade-off is that `Batch` can call the given
+function multiple times, if parts of the transaction fail. The
+function must be idempotent and side effects must take effect only
+after a successful return from `DB.Batch()`.
+
+For example: don't display messages from inside the function, instead
+set variables in the enclosing scope:
+
+```go
+var id uint64
+err := db.Batch(func(tx *bolt.Tx) error {
+ // Find last key in bucket, decode as bigendian uint64, increment
+ // by one, encode back to []byte, and add new key.
+ ...
+ id = newValue
+ return nil
+})
+if err != nil {
+ return ...
+}
+fmt.Println("Allocated ID %d", id)
+```
+
+
+#### Managing transactions manually
+
+The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()`
+function. These helper functions will start the transaction, execute a function,
+and then safely close your transaction if an error is returned. This is the
+recommended way to use Bolt transactions.
+
+However, sometimes you may want to manually start and end your transactions.
+You can use the `DB.Begin()` function directly but **please** be sure to close
+the transaction.
+
+```go
+// Start a writable transaction.
+tx, err := db.Begin(true)
+if err != nil {
+ return err
+}
+defer tx.Rollback()
+
+// Use the transaction...
+_, err := tx.CreateBucket([]byte("MyBucket"))
+if err != nil {
+ return err
+}
+
+// Commit the transaction and check for error.
+if err := tx.Commit(); err != nil {
+ return err
+}
+```
+
+The first argument to `DB.Begin()` is a boolean stating if the transaction
+should be writable.
+
+
+### Using buckets
+
+Buckets are collections of key/value pairs within the database. All keys in a
+bucket must be unique. You can create a bucket using the `DB.CreateBucket()`
+function:
+
+```go
+db.Update(func(tx *bolt.Tx) error {
+ b, err := tx.CreateBucket([]byte("MyBucket"))
+ if err != nil {
+ return fmt.Errorf("create bucket: %s", err)
+ }
+ return nil
+})
+```
+
+You can also create a bucket only if it doesn't exist by using the
+`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this
+function for all your top-level buckets after you open your database so you can
+guarantee that they exist for future transactions.
+
+To delete a bucket, simply call the `Tx.DeleteBucket()` function.
+
+
+### Using key/value pairs
+
+To save a key/value pair to a bucket, use the `Bucket.Put()` function:
+
+```go
+db.Update(func(tx *bolt.Tx) error {
+ b := tx.Bucket([]byte("MyBucket"))
+ err := b.Put([]byte("answer"), []byte("42"))
+ return err
+})
+```
+
+This will set the value of the `"answer"` key to `"42"` in the `MyBucket`
+bucket. To retrieve this value, we can use the `Bucket.Get()` function:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+ b := tx.Bucket([]byte("MyBucket"))
+ v := b.Get([]byte("answer"))
+ fmt.Printf("The answer is: %s\n", v)
+ return nil
+})
+```
+
+The `Get()` function does not return an error because its operation is
+guaranteed to work (unless there is some kind of system failure). If the key
+exists then it will return its byte slice value. If it doesn't exist then it
+will return `nil`. It's important to note that you can have a zero-length value
+set to a key which is different than the key not existing.
+
+Use the `Bucket.Delete()` function to delete a key from the bucket.
+
+Please note that values returned from `Get()` are only valid while the
+transaction is open. If you need to use a value outside of the transaction
+then you must use `copy()` to copy it to another byte slice.
+
+
+### Autoincrementing integer for the bucket
+By using the `NextSequence()` function, you can let Bolt determine a sequence
+which can be used as the unique identifier for your key/value pairs. See the
+example below.
+
+```go
+// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
+func (s *Store) CreateUser(u *User) error {
+ return s.db.Update(func(tx *bolt.Tx) error {
+ // Retrieve the users bucket.
+ // This should be created when the DB is first opened.
+ b := tx.Bucket([]byte("users"))
+
+ // Generate ID for the user.
+ // This returns an error only if the Tx is closed or not writeable.
+ // That can't happen in an Update() call so I ignore the error check.
+ id, _ := b.NextSequence()
+ u.ID = int(id)
+
+ // Marshal user data into bytes.
+ buf, err := json.Marshal(u)
+ if err != nil {
+ return err
+ }
+
+ // Persist bytes to users bucket.
+ return b.Put(itob(u.ID), buf)
+ })
+}
+
+// itob returns an 8-byte big endian representation of v.
+func itob(v int) []byte {
+ b := make([]byte, 8)
+ binary.BigEndian.PutUint64(b, uint64(v))
+ return b
+}
+
+type User struct {
+ ID int
+ ...
+}
+```
+
+### Iterating over keys
+
+Bolt stores its keys in byte-sorted order within a bucket. This makes sequential
+iteration over these keys extremely fast. To iterate over keys we'll use a
+`Cursor`:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+ // Assume bucket exists and has keys
+ b := tx.Bucket([]byte("MyBucket"))
+
+ c := b.Cursor()
+
+ for k, v := c.First(); k != nil; k, v = c.Next() {
+ fmt.Printf("key=%s, value=%s\n", k, v)
+ }
+
+ return nil
+})
+```
+
+The cursor allows you to move to a specific point in the list of keys and move
+forward or backward through the keys one at a time.
+
+The following functions are available on the cursor:
+
+```
+First() Move to the first key.
+Last() Move to the last key.
+Seek() Move to a specific key.
+Next() Move to the next key.
+Prev() Move to the previous key.
+```
+
+Each of those functions has a return signature of `(key []byte, value []byte)`.
+When you have iterated to the end of the cursor then `Next()` will return a
+`nil` key. You must seek to a position using `First()`, `Last()`, or `Seek()`
+before calling `Next()` or `Prev()`. If you do not seek to a position then
+these functions will return a `nil` key.
+
+During iteration, if the key is non-`nil` but the value is `nil`, that means
+the key refers to a bucket rather than a value. Use `Bucket.Bucket()` to
+access the sub-bucket.
+
+
+#### Prefix scans
+
+To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+ // Assume bucket exists and has keys
+ c := tx.Bucket([]byte("MyBucket")).Cursor()
+
+ prefix := []byte("1234")
+ for k, v := c.Seek(prefix); bytes.HasPrefix(k, prefix); k, v = c.Next() {
+ fmt.Printf("key=%s, value=%s\n", k, v)
+ }
+
+ return nil
+})
+```
+
+#### Range scans
+
+Another common use case is scanning over a range such as a time range. If you
+use a sortable time encoding such as RFC3339 then you can query a specific
+date range like this:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+ // Assume our events bucket exists and has RFC3339 encoded time keys.
+ c := tx.Bucket([]byte("Events")).Cursor()
+
+ // Our time range spans the 90's decade.
+ min := []byte("1990-01-01T00:00:00Z")
+ max := []byte("2000-01-01T00:00:00Z")
+
+ // Iterate over the 90's.
+ for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() {
+ fmt.Printf("%s: %s\n", k, v)
+ }
+
+ return nil
+})
+```
+
+Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable.
+
+
+#### ForEach()
+
+You can also use the function `ForEach()` if you know you'll be iterating over
+all the keys in a bucket:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+ // Assume bucket exists and has keys
+ b := tx.Bucket([]byte("MyBucket"))
+
+ b.ForEach(func(k, v []byte) error {
+ fmt.Printf("key=%s, value=%s\n", k, v)
+ return nil
+ })
+ return nil
+})
+```
+
+Please note that keys and values in `ForEach()` are only valid while
+the transaction is open. If you need to use a key or value outside of
+the transaction, you must use `copy()` to copy it to another byte
+slice.
+
+### Nested buckets
+
+You can also store a bucket in a key to create nested buckets. The API is the
+same as the bucket management API on the `DB` object:
+
+```go
+func (*Bucket) CreateBucket(key []byte) (*Bucket, error)
+func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)
+func (*Bucket) DeleteBucket(key []byte) error
+```
+
+
+### Database backups
+
+Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()`
+function to write a consistent view of the database to a writer. If you call
+this from a read-only transaction, it will perform a hot backup and not block
+your other database reads and writes.
+
+By default, it will use a regular file handle which will utilize the operating
+system's page cache. See the [`Tx`](https://godoc.org/github.com/boltdb/bolt#Tx)
+documentation for information about optimizing for larger-than-RAM datasets.
+
+One common use case is to backup over HTTP so you can use tools like `cURL` to
+do database backups:
+
+```go
+func BackupHandleFunc(w http.ResponseWriter, req *http.Request) {
+ err := db.View(func(tx *bolt.Tx) error {
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Disposition", `attachment; filename="my.db"`)
+ w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
+ _, err := tx.WriteTo(w)
+ return err
+ })
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+}
+```
+
+Then you can backup using this command:
+
+```sh
+$ curl http://localhost/backup > my.db
+```
+
+Or you can open your browser to `http://localhost/backup` and it will download
+automatically.
+
+If you want to backup to another file you can use the `Tx.CopyFile()` helper
+function.
+
+
+### Statistics
+
+The database keeps a running count of many of the internal operations it
+performs so you can better understand what's going on. By grabbing a snapshot
+of these stats at two points in time we can see what operations were performed
+in that time range.
+
+For example, we could start a goroutine to log stats every 10 seconds:
+
+```go
+go func() {
+ // Grab the initial stats.
+ prev := db.Stats()
+
+ for {
+ // Wait for 10s.
+ time.Sleep(10 * time.Second)
+
+ // Grab the current stats and diff them.
+ stats := db.Stats()
+ diff := stats.Sub(&prev)
+
+ // Encode stats to JSON and print to STDERR.
+ json.NewEncoder(os.Stderr).Encode(diff)
+
+ // Save stats for the next loop.
+ prev = stats
+ }
+}()
+```
+
+It's also useful to pipe these stats to a service such as statsd for monitoring
+or to provide an HTTP endpoint that will perform a fixed-length sample.
+
+
+### Read-Only Mode
+
+Sometimes it is useful to create a shared, read-only Bolt database. To this,
+set the `Options.ReadOnly` flag when opening your database. Read-only mode
+uses a shared lock to allow multiple processes to read from the database but
+it will block any processes from opening the database in read-write mode.
+
+```go
+db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true})
+if err != nil {
+ log.Fatal(err)
+}
+```
+
+### Mobile Use (iOS/Android)
+
+Bolt is able to run on mobile devices by leveraging the binding feature of the
+[gomobile](https://github.com/golang/mobile) tool. Create a struct that will
+contain your database logic and a reference to a `*bolt.DB` with a initializing
+constructor that takes in a filepath where the database file will be stored.
+Neither Android nor iOS require extra permissions or cleanup from using this method.
+
+```go
+func NewBoltDB(filepath string) *BoltDB {
+ db, err := bolt.Open(filepath+"/demo.db", 0600, nil)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ return &BoltDB{db}
+}
+
+type BoltDB struct {
+ db *bolt.DB
+ ...
+}
+
+func (b *BoltDB) Path() string {
+ return b.db.Path()
+}
+
+func (b *BoltDB) Close() {
+ b.db.Close()
+}
+```
+
+Database logic should be defined as methods on this wrapper struct.
+
+To initialize this struct from the native language (both platforms now sync
+their local storage to the cloud. These snippets disable that functionality for the
+database file):
+
+#### Android
+
+```java
+String path;
+if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){
+ path = getNoBackupFilesDir().getAbsolutePath();
+} else{
+ path = getFilesDir().getAbsolutePath();
+}
+Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path)
+```
+
+#### iOS
+
+```objc
+- (void)demo {
+ NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
+ NSUserDomainMask,
+ YES) objectAtIndex:0];
+ GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path);
+ [self addSkipBackupAttributeToItemAtPath:demo.path];
+ //Some DB Logic would go here
+ [demo close];
+}
+
+- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
+{
+ NSURL* URL= [NSURL fileURLWithPath: filePathString];
+ assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
+
+ NSError *error = nil;
+ BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
+ forKey: NSURLIsExcludedFromBackupKey error: &error];
+ if(!success){
+ NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
+ }
+ return success;
+}
+
+```
+
+## Resources
+
+For more information on getting started with Bolt, check out the following articles:
+
+* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch).
+* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville
+
+
+## Comparison with other databases
+
+### Postgres, MySQL, & other relational databases
+
+Relational databases structure data into rows and are only accessible through
+the use of SQL. This approach provides flexibility in how you store and query
+your data but also incurs overhead in parsing and planning SQL statements. Bolt
+accesses all data by a byte slice key. This makes Bolt fast to read and write
+data by key but provides no built-in support for joining values together.
+
+Most relational databases (with the exception of SQLite) are standalone servers
+that run separately from your application. This gives your systems
+flexibility to connect multiple application servers to a single database
+server but also adds overhead in serializing and transporting data over the
+network. Bolt runs as a library included in your application so all data access
+has to go through your application's process. This brings data closer to your
+application but limits multi-process access to the data.
+
+
+### LevelDB, RocksDB
+
+LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that
+they are libraries bundled into the application, however, their underlying
+structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes
+random writes by using a write ahead log and multi-tiered, sorted files called
+SSTables. Bolt uses a B+tree internally and only a single file. Both approaches
+have trade-offs.
+
+If you require a high random write throughput (>10,000 w/sec) or you need to use
+spinning disks then LevelDB could be a good choice. If your application is
+read-heavy or does a lot of range scans then Bolt could be a good choice.
+
+One other important consideration is that LevelDB does not have transactions.
+It supports batch writing of key/values pairs and it supports read snapshots
+but it will not give you the ability to do a compare-and-swap operation safely.
+Bolt supports fully serializable ACID transactions.
+
+
+### LMDB
+
+Bolt was originally a port of LMDB so it is architecturally similar. Both use
+a B+tree, have ACID semantics with fully serializable transactions, and support
+lock-free MVCC using a single writer and multiple readers.
+
+The two projects have somewhat diverged. LMDB heavily focuses on raw performance
+while Bolt has focused on simplicity and ease of use. For example, LMDB allows
+several unsafe actions such as direct writes for the sake of performance. Bolt
+opts to disallow actions which can leave the database in a corrupted state. The
+only exception to this in Bolt is `DB.NoSync`.
+
+There are also a few differences in API. LMDB requires a maximum mmap size when
+opening an `mdb_env` whereas Bolt will handle incremental mmap resizing
+automatically. LMDB overloads the getter and setter functions with multiple
+flags whereas Bolt splits these specialized cases into their own functions.
+
+
+## Caveats & Limitations
+
+It's important to pick the right tool for the job and Bolt is no exception.
+Here are a few things to note when evaluating and using Bolt:
+
+* Bolt is good for read intensive workloads. Sequential write performance is
+ also fast but random writes can be slow. You can use `DB.Batch()` or add a
+ write-ahead log to help mitigate this issue.
+
+* Bolt uses a B+tree internally so there can be a lot of random page access.
+ SSDs provide a significant performance boost over spinning disks.
+
+* Try to avoid long running read transactions. Bolt uses copy-on-write so
+ old pages cannot be reclaimed while an old transaction is using them.
+
+* Byte slices returned from Bolt are only valid during a transaction. Once the
+ transaction has been committed or rolled back then the memory they point to
+ can be reused by a new page or can be unmapped from virtual memory and you'll
+ see an `unexpected fault address` panic when accessing it.
+
+* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for
+ buckets that have random inserts will cause your database to have very poor
+ page utilization.
+
+* Use larger buckets in general. Smaller buckets causes poor page utilization
+ once they become larger than the page size (typically 4KB).
+
+* Bulk loading a lot of random writes into a new bucket can be slow as the
+ page will not split until the transaction is committed. Randomly inserting
+ more than 100,000 key/value pairs into a single new bucket in a single
+ transaction is not advised.
+
+* Bolt uses a memory-mapped file so the underlying operating system handles the
+ caching of the data. Typically, the OS will cache as much of the file as it
+ can in memory and will release memory as needed to other processes. This means
+ that Bolt can show very high memory usage when working with large databases.
+ However, this is expected and the OS will release memory as needed. Bolt can
+ handle databases much larger than the available physical RAM, provided its
+ memory-map fits in the process virtual address space. It may be problematic
+ on 32-bits systems.
+
+* The data structures in the Bolt database are memory mapped so the data file
+ will be endian specific. This means that you cannot copy a Bolt file from a
+ little endian machine to a big endian machine and have it work. For most
+ users this is not a concern since most modern CPUs are little endian.
+
+* Because of the way pages are laid out on disk, Bolt cannot truncate data files
+ and return free pages back to the disk. Instead, Bolt maintains a free list
+ of unused pages within its data file. These free pages can be reused by later
+ transactions. This works well for many use cases as databases generally tend
+ to grow. However, it's important to note that deleting large chunks of data
+ will not allow you to reclaim that space on disk.
+
+ For more information on page allocation, [see this comment][page-allocation].
+
+[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638
+
+
+## Reading the Source
+
+Bolt is a relatively small code base (<3KLOC) for an embedded, serializable,
+transactional key/value database so it can be a good starting point for people
+interested in how databases work.
+
+The best places to start are the main entry points into Bolt:
+
+- `Open()` - Initializes the reference to the database. It's responsible for
+ creating the database if it doesn't exist, obtaining an exclusive lock on the
+ file, reading the meta pages, & memory-mapping the file.
+
+- `DB.Begin()` - Starts a read-only or read-write transaction depending on the
+ value of the `writable` argument. This requires briefly obtaining the "meta"
+ lock to keep track of open transactions. Only one read-write transaction can
+ exist at a time so the "rwlock" is acquired during the life of a read-write
+ transaction.
+
+- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the
+ arguments, a cursor is used to traverse the B+tree to the page and position
+ where they key & value will be written. Once the position is found, the bucket
+ materializes the underlying page and the page's parent pages into memory as
+ "nodes". These nodes are where mutations occur during read-write transactions.
+ These changes get flushed to disk during commit.
+
+- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor
+ to move to the page & position of a key/value pair. During a read-only
+ transaction, the key and value data is returned as a direct reference to the
+ underlying mmap file so there's no allocation overhead. For read-write
+ transactions, this data may reference the mmap file or one of the in-memory
+ node values.
+
+- `Cursor` - This object is simply for traversing the B+tree of on-disk pages
+ or in-memory nodes. It can seek to a specific key, move to the first or last
+ value, or it can move forward or backward. The cursor handles the movement up
+ and down the B+tree transparently to the end user.
+
+- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages
+ into pages to be written to disk. Writing to disk then occurs in two phases.
+ First, the dirty pages are written to disk and an `fsync()` occurs. Second, a
+ new meta page with an incremented transaction ID is written and another
+ `fsync()` occurs. This two phase write ensures that partially written data
+ pages are ignored in the event of a crash since the meta page pointing to them
+ is never written. Partially written meta pages are invalidated because they
+ are written with a checksum.
+
+If you have additional notes that could be helpful for others, please submit
+them via pull request.
+
+
+## Other Projects Using Bolt
+
+Below is a list of public, open source projects that use Bolt:
+
+* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files.
+* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard.
+* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside.
+* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb.
+* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics.
+* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects.
+* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday.
+* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations.
+* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite.
+* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin".
+* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka.
+* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed.
+* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt.
+* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site.
+* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage.
+* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters.
+* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend.
+* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend.
+* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server.
+* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read.
+* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics.
+* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data.
+* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system.
+* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware.
+* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs.
+* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems.
+* [stow](https://github.com/djherbis/stow) - a persistence manager for objects
+ backed by boltdb.
+* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining
+ simple tx and key scans.
+* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets.
+* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service
+* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service.
+* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners.
+* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores.
+* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB.
+* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB.
+* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings.
+* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend.
+* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files.
+* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter.
+* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development.
+
+If you are using Bolt in a project please send a pull request to add it to the list.
diff --git a/vendor/github.com/boltdb/bolt/bolt_386.go b/vendor/github.com/boltdb/bolt/bolt_386.go
new file mode 100644
index 0000000..820d533
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_386.go
@@ -0,0 +1,10 @@
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x7FFFFFFF // 2GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0xFFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/vendor/github.com/boltdb/bolt/bolt_amd64.go b/vendor/github.com/boltdb/bolt/bolt_amd64.go
new file mode 100644
index 0000000..98fafdb
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_amd64.go
@@ -0,0 +1,10 @@
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/vendor/github.com/boltdb/bolt/bolt_arm.go b/vendor/github.com/boltdb/bolt/bolt_arm.go
new file mode 100644
index 0000000..7e5cb4b
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_arm.go
@@ -0,0 +1,28 @@
+package bolt
+
+import "unsafe"
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x7FFFFFFF // 2GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0xFFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned bool
+
+func init() {
+ // Simple check to see whether this arch handles unaligned load/stores
+ // correctly.
+
+ // ARM9 and older devices require load/stores to be from/to aligned
+ // addresses. If not, the lower 2 bits are cleared and that address is
+ // read in a jumbled up order.
+
+ // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka15414.html
+
+ raw := [6]byte{0xfe, 0xef, 0x11, 0x22, 0x22, 0x11}
+ val := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&raw)) + 2))
+
+ brokenUnaligned = val != 0x11222211
+}
diff --git a/vendor/github.com/boltdb/bolt/bolt_arm64.go b/vendor/github.com/boltdb/bolt/bolt_arm64.go
new file mode 100644
index 0000000..b26d84f
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_arm64.go
@@ -0,0 +1,12 @@
+// +build arm64
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/vendor/github.com/boltdb/bolt/bolt_linux.go b/vendor/github.com/boltdb/bolt/bolt_linux.go
new file mode 100644
index 0000000..2b67666
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_linux.go
@@ -0,0 +1,10 @@
+package bolt
+
+import (
+ "syscall"
+)
+
+// fdatasync flushes written data to a file descriptor.
+func fdatasync(db *DB) error {
+ return syscall.Fdatasync(int(db.file.Fd()))
+}
diff --git a/vendor/github.com/boltdb/bolt/bolt_openbsd.go b/vendor/github.com/boltdb/bolt/bolt_openbsd.go
new file mode 100644
index 0000000..7058c3d
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_openbsd.go
@@ -0,0 +1,27 @@
+package bolt
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+const (
+ msAsync = 1 << iota // perform asynchronous writes
+ msSync // perform synchronous writes
+ msInvalidate // invalidate cached data
+)
+
+func msync(db *DB) error {
+ _, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(db.data)), uintptr(db.datasz), msInvalidate)
+ if errno != 0 {
+ return errno
+ }
+ return nil
+}
+
+func fdatasync(db *DB) error {
+ if db.data != nil {
+ return msync(db)
+ }
+ return db.file.Sync()
+}
diff --git a/vendor/github.com/boltdb/bolt/bolt_ppc.go b/vendor/github.com/boltdb/bolt/bolt_ppc.go
new file mode 100644
index 0000000..645ddc3
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_ppc.go
@@ -0,0 +1,9 @@
+// +build ppc
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x7FFFFFFF // 2GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0xFFFFFFF
diff --git a/vendor/github.com/boltdb/bolt/bolt_ppc64.go b/vendor/github.com/boltdb/bolt/bolt_ppc64.go
new file mode 100644
index 0000000..2dc6be0
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_ppc64.go
@@ -0,0 +1,9 @@
+// +build ppc64
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
diff --git a/vendor/github.com/boltdb/bolt/bolt_ppc64le.go b/vendor/github.com/boltdb/bolt/bolt_ppc64le.go
new file mode 100644
index 0000000..8c143bc
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_ppc64le.go
@@ -0,0 +1,12 @@
+// +build ppc64le
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/vendor/github.com/boltdb/bolt/bolt_s390x.go b/vendor/github.com/boltdb/bolt/bolt_s390x.go
new file mode 100644
index 0000000..d7c39af
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_s390x.go
@@ -0,0 +1,12 @@
+// +build s390x
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/vendor/github.com/boltdb/bolt/bolt_unix.go b/vendor/github.com/boltdb/bolt/bolt_unix.go
new file mode 100644
index 0000000..cad62dd
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_unix.go
@@ -0,0 +1,89 @@
+// +build !windows,!plan9,!solaris
+
+package bolt
+
+import (
+ "fmt"
+ "os"
+ "syscall"
+ "time"
+ "unsafe"
+)
+
+// flock acquires an advisory lock on a file descriptor.
+func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
+ var t time.Time
+ for {
+ // If we're beyond our timeout then return an error.
+ // This can only occur after we've attempted a flock once.
+ if t.IsZero() {
+ t = time.Now()
+ } else if timeout > 0 && time.Since(t) > timeout {
+ return ErrTimeout
+ }
+ flag := syscall.LOCK_SH
+ if exclusive {
+ flag = syscall.LOCK_EX
+ }
+
+ // Otherwise attempt to obtain an exclusive lock.
+ err := syscall.Flock(int(db.file.Fd()), flag|syscall.LOCK_NB)
+ if err == nil {
+ return nil
+ } else if err != syscall.EWOULDBLOCK {
+ return err
+ }
+
+ // Wait for a bit and try again.
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+// funlock releases an advisory lock on a file descriptor.
+func funlock(db *DB) error {
+ return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN)
+}
+
+// mmap memory maps a DB's data file.
+func mmap(db *DB, sz int) error {
+ // Map the data file to memory.
+ b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
+ if err != nil {
+ return err
+ }
+
+ // Advise the kernel that the mmap is accessed randomly.
+ if err := madvise(b, syscall.MADV_RANDOM); err != nil {
+ return fmt.Errorf("madvise: %s", err)
+ }
+
+ // Save the original byte slice and convert to a byte array pointer.
+ db.dataref = b
+ db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
+ db.datasz = sz
+ return nil
+}
+
+// munmap unmaps a DB's data file from memory.
+func munmap(db *DB) error {
+ // Ignore the unmap if we have no mapped data.
+ if db.dataref == nil {
+ return nil
+ }
+
+ // Unmap using the original byte slice.
+ err := syscall.Munmap(db.dataref)
+ db.dataref = nil
+ db.data = nil
+ db.datasz = 0
+ return err
+}
+
+// NOTE: This function is copied from stdlib because it is not available on darwin.
+func madvise(b []byte, advice int) (err error) {
+ _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice))
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
diff --git a/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go b/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go
new file mode 100644
index 0000000..307bf2b
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go
@@ -0,0 +1,90 @@
+package bolt
+
+import (
+ "fmt"
+ "os"
+ "syscall"
+ "time"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+// flock acquires an advisory lock on a file descriptor.
+func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
+ var t time.Time
+ for {
+ // If we're beyond our timeout then return an error.
+ // This can only occur after we've attempted a flock once.
+ if t.IsZero() {
+ t = time.Now()
+ } else if timeout > 0 && time.Since(t) > timeout {
+ return ErrTimeout
+ }
+ var lock syscall.Flock_t
+ lock.Start = 0
+ lock.Len = 0
+ lock.Pid = 0
+ lock.Whence = 0
+ lock.Pid = 0
+ if exclusive {
+ lock.Type = syscall.F_WRLCK
+ } else {
+ lock.Type = syscall.F_RDLCK
+ }
+ err := syscall.FcntlFlock(db.file.Fd(), syscall.F_SETLK, &lock)
+ if err == nil {
+ return nil
+ } else if err != syscall.EAGAIN {
+ return err
+ }
+
+ // Wait for a bit and try again.
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+// funlock releases an advisory lock on a file descriptor.
+func funlock(db *DB) error {
+ var lock syscall.Flock_t
+ lock.Start = 0
+ lock.Len = 0
+ lock.Type = syscall.F_UNLCK
+ lock.Whence = 0
+ return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock)
+}
+
+// mmap memory maps a DB's data file.
+func mmap(db *DB, sz int) error {
+ // Map the data file to memory.
+ b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
+ if err != nil {
+ return err
+ }
+
+ // Advise the kernel that the mmap is accessed randomly.
+ if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil {
+ return fmt.Errorf("madvise: %s", err)
+ }
+
+ // Save the original byte slice and convert to a byte array pointer.
+ db.dataref = b
+ db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
+ db.datasz = sz
+ return nil
+}
+
+// munmap unmaps a DB's data file from memory.
+func munmap(db *DB) error {
+ // Ignore the unmap if we have no mapped data.
+ if db.dataref == nil {
+ return nil
+ }
+
+ // Unmap using the original byte slice.
+ err := unix.Munmap(db.dataref)
+ db.dataref = nil
+ db.data = nil
+ db.datasz = 0
+ return err
+}
diff --git a/vendor/github.com/boltdb/bolt/bolt_windows.go b/vendor/github.com/boltdb/bolt/bolt_windows.go
new file mode 100644
index 0000000..d538e6a
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bolt_windows.go
@@ -0,0 +1,144 @@
+package bolt
+
+import (
+ "fmt"
+ "os"
+ "syscall"
+ "time"
+ "unsafe"
+)
+
+// LockFileEx code derived from golang build filemutex_windows.go @ v1.5.1
+var (
+ modkernel32 = syscall.NewLazyDLL("kernel32.dll")
+ procLockFileEx = modkernel32.NewProc("LockFileEx")
+ procUnlockFileEx = modkernel32.NewProc("UnlockFileEx")
+)
+
+const (
+ lockExt = ".lock"
+
+ // see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
+ flagLockExclusive = 2
+ flagLockFailImmediately = 1
+
+ // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx
+ errLockViolation syscall.Errno = 0x21
+)
+
+func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
+ r, _, err := procLockFileEx.Call(uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)))
+ if r == 0 {
+ return err
+ }
+ return nil
+}
+
+func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
+ r, _, err := procUnlockFileEx.Call(uintptr(h), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)), 0)
+ if r == 0 {
+ return err
+ }
+ return nil
+}
+
+// fdatasync flushes written data to a file descriptor.
+func fdatasync(db *DB) error {
+ return db.file.Sync()
+}
+
+// flock acquires an advisory lock on a file descriptor.
+func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
+ // Create a separate lock file on windows because a process
+ // cannot share an exclusive lock on the same file. This is
+ // needed during Tx.WriteTo().
+ f, err := os.OpenFile(db.path+lockExt, os.O_CREATE, mode)
+ if err != nil {
+ return err
+ }
+ db.lockfile = f
+
+ var t time.Time
+ for {
+ // If we're beyond our timeout then return an error.
+ // This can only occur after we've attempted a flock once.
+ if t.IsZero() {
+ t = time.Now()
+ } else if timeout > 0 && time.Since(t) > timeout {
+ return ErrTimeout
+ }
+
+ var flag uint32 = flagLockFailImmediately
+ if exclusive {
+ flag |= flagLockExclusive
+ }
+
+ err := lockFileEx(syscall.Handle(db.lockfile.Fd()), flag, 0, 1, 0, &syscall.Overlapped{})
+ if err == nil {
+ return nil
+ } else if err != errLockViolation {
+ return err
+ }
+
+ // Wait for a bit and try again.
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+// funlock releases an advisory lock on a file descriptor.
+func funlock(db *DB) error {
+ err := unlockFileEx(syscall.Handle(db.lockfile.Fd()), 0, 1, 0, &syscall.Overlapped{})
+ db.lockfile.Close()
+ os.Remove(db.path+lockExt)
+ return err
+}
+
+// mmap memory maps a DB's data file.
+// Based on: https://github.com/edsrzf/mmap-go
+func mmap(db *DB, sz int) error {
+ if !db.readOnly {
+ // Truncate the database to the size of the mmap.
+ if err := db.file.Truncate(int64(sz)); err != nil {
+ return fmt.Errorf("truncate: %s", err)
+ }
+ }
+
+ // Open a file mapping handle.
+ sizelo := uint32(sz >> 32)
+ sizehi := uint32(sz) & 0xffffffff
+ h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil)
+ if h == 0 {
+ return os.NewSyscallError("CreateFileMapping", errno)
+ }
+
+ // Create the memory map.
+ addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz))
+ if addr == 0 {
+ return os.NewSyscallError("MapViewOfFile", errno)
+ }
+
+ // Close mapping handle.
+ if err := syscall.CloseHandle(syscall.Handle(h)); err != nil {
+ return os.NewSyscallError("CloseHandle", err)
+ }
+
+ // Convert to a byte array.
+ db.data = ((*[maxMapSize]byte)(unsafe.Pointer(addr)))
+ db.datasz = sz
+
+ return nil
+}
+
+// munmap unmaps a pointer from a file.
+// Based on: https://github.com/edsrzf/mmap-go
+func munmap(db *DB) error {
+ if db.data == nil {
+ return nil
+ }
+
+ addr := (uintptr)(unsafe.Pointer(&db.data[0]))
+ if err := syscall.UnmapViewOfFile(addr); err != nil {
+ return os.NewSyscallError("UnmapViewOfFile", err)
+ }
+ return nil
+}
diff --git a/vendor/github.com/boltdb/bolt/boltsync_unix.go b/vendor/github.com/boltdb/bolt/boltsync_unix.go
new file mode 100644
index 0000000..f504425
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/boltsync_unix.go
@@ -0,0 +1,8 @@
+// +build !windows,!plan9,!linux,!openbsd
+
+package bolt
+
+// fdatasync flushes written data to a file descriptor.
+func fdatasync(db *DB) error {
+ return db.file.Sync()
+}
diff --git a/vendor/github.com/boltdb/bolt/bucket.go b/vendor/github.com/boltdb/bolt/bucket.go
new file mode 100644
index 0000000..511ce72
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/bucket.go
@@ -0,0 +1,778 @@
+package bolt
+
+import (
+ "bytes"
+ "fmt"
+ "unsafe"
+)
+
+const (
+ // MaxKeySize is the maximum length of a key, in bytes.
+ MaxKeySize = 32768
+
+ // MaxValueSize is the maximum length of a value, in bytes.
+ MaxValueSize = (1 << 31) - 2
+)
+
+const (
+ maxUint = ^uint(0)
+ minUint = 0
+ maxInt = int(^uint(0) >> 1)
+ minInt = -maxInt - 1
+)
+
+const bucketHeaderSize = int(unsafe.Sizeof(bucket{}))
+
+const (
+ minFillPercent = 0.1
+ maxFillPercent = 1.0
+)
+
+// DefaultFillPercent is the percentage that split pages are filled.
+// This value can be changed by setting Bucket.FillPercent.
+const DefaultFillPercent = 0.5
+
+// Bucket represents a collection of key/value pairs inside the database.
+type Bucket struct {
+ *bucket
+ tx *Tx // the associated transaction
+ buckets map[string]*Bucket // subbucket cache
+ page *page // inline page reference
+ rootNode *node // materialized node for the root page.
+ nodes map[pgid]*node // node cache
+
+ // Sets the threshold for filling nodes when they split. By default,
+ // the bucket will fill to 50% but it can be useful to increase this
+ // amount if you know that your write workloads are mostly append-only.
+ //
+ // This is non-persisted across transactions so it must be set in every Tx.
+ FillPercent float64
+}
+
+// bucket represents the on-file representation of a bucket.
+// This is stored as the "value" of a bucket key. If the bucket is small enough,
+// then its root page can be stored inline in the "value", after the bucket
+// header. In the case of inline buckets, the "root" will be 0.
+type bucket struct {
+ root pgid // page id of the bucket's root-level page
+ sequence uint64 // monotonically incrementing, used by NextSequence()
+}
+
+// newBucket returns a new bucket associated with a transaction.
+func newBucket(tx *Tx) Bucket {
+ var b = Bucket{tx: tx, FillPercent: DefaultFillPercent}
+ if tx.writable {
+ b.buckets = make(map[string]*Bucket)
+ b.nodes = make(map[pgid]*node)
+ }
+ return b
+}
+
+// Tx returns the tx of the bucket.
+func (b *Bucket) Tx() *Tx {
+ return b.tx
+}
+
+// Root returns the root of the bucket.
+func (b *Bucket) Root() pgid {
+ return b.root
+}
+
+// Writable returns whether the bucket is writable.
+func (b *Bucket) Writable() bool {
+ return b.tx.writable
+}
+
+// Cursor creates a cursor associated with the bucket.
+// The cursor is only valid as long as the transaction is open.
+// Do not use a cursor after the transaction is closed.
+func (b *Bucket) Cursor() *Cursor {
+ // Update transaction statistics.
+ b.tx.stats.CursorCount++
+
+ // Allocate and return a cursor.
+ return &Cursor{
+ bucket: b,
+ stack: make([]elemRef, 0),
+ }
+}
+
+// Bucket retrieves a nested bucket by name.
+// Returns nil if the bucket does not exist.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (b *Bucket) Bucket(name []byte) *Bucket {
+ if b.buckets != nil {
+ if child := b.buckets[string(name)]; child != nil {
+ return child
+ }
+ }
+
+ // Move cursor to key.
+ c := b.Cursor()
+ k, v, flags := c.seek(name)
+
+ // Return nil if the key doesn't exist or it is not a bucket.
+ if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 {
+ return nil
+ }
+
+ // Otherwise create a bucket and cache it.
+ var child = b.openBucket(v)
+ if b.buckets != nil {
+ b.buckets[string(name)] = child
+ }
+
+ return child
+}
+
+// Helper method that re-interprets a sub-bucket value
+// from a parent into a Bucket
+func (b *Bucket) openBucket(value []byte) *Bucket {
+ var child = newBucket(b.tx)
+
+ // If unaligned load/stores are broken on this arch and value is
+ // unaligned simply clone to an aligned byte array.
+ unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0
+
+ if unaligned {
+ value = cloneBytes(value)
+ }
+
+ // If this is a writable transaction then we need to copy the bucket entry.
+ // Read-only transactions can point directly at the mmap entry.
+ if b.tx.writable && !unaligned {
+ child.bucket = &bucket{}
+ *child.bucket = *(*bucket)(unsafe.Pointer(&value[0]))
+ } else {
+ child.bucket = (*bucket)(unsafe.Pointer(&value[0]))
+ }
+
+ // Save a reference to the inline page if the bucket is inline.
+ if child.root == 0 {
+ child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
+ }
+
+ return &child
+}
+
+// CreateBucket creates a new bucket at the given key and returns the new bucket.
+// Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) {
+ if b.tx.db == nil {
+ return nil, ErrTxClosed
+ } else if !b.tx.writable {
+ return nil, ErrTxNotWritable
+ } else if len(key) == 0 {
+ return nil, ErrBucketNameRequired
+ }
+
+ // Move cursor to correct position.
+ c := b.Cursor()
+ k, _, flags := c.seek(key)
+
+ // Return an error if there is an existing key.
+ if bytes.Equal(key, k) {
+ if (flags & bucketLeafFlag) != 0 {
+ return nil, ErrBucketExists
+ } else {
+ return nil, ErrIncompatibleValue
+ }
+ }
+
+ // Create empty, inline bucket.
+ var bucket = Bucket{
+ bucket: &bucket{},
+ rootNode: &node{isLeaf: true},
+ FillPercent: DefaultFillPercent,
+ }
+ var value = bucket.write()
+
+ // Insert into node.
+ key = cloneBytes(key)
+ c.node().put(key, key, value, 0, bucketLeafFlag)
+
+ // Since subbuckets are not allowed on inline buckets, we need to
+ // dereference the inline page, if it exists. This will cause the bucket
+ // to be treated as a regular, non-inline bucket for the rest of the tx.
+ b.page = nil
+
+ return b.Bucket(key), nil
+}
+
+// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it.
+// Returns an error if the bucket name is blank, or if the bucket name is too long.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
+ child, err := b.CreateBucket(key)
+ if err == ErrBucketExists {
+ return b.Bucket(key), nil
+ } else if err != nil {
+ return nil, err
+ }
+ return child, nil
+}
+
+// DeleteBucket deletes a bucket at the given key.
+// Returns an error if the bucket does not exists, or if the key represents a non-bucket value.
+func (b *Bucket) DeleteBucket(key []byte) error {
+ if b.tx.db == nil {
+ return ErrTxClosed
+ } else if !b.Writable() {
+ return ErrTxNotWritable
+ }
+
+ // Move cursor to correct position.
+ c := b.Cursor()
+ k, _, flags := c.seek(key)
+
+ // Return an error if bucket doesn't exist or is not a bucket.
+ if !bytes.Equal(key, k) {
+ return ErrBucketNotFound
+ } else if (flags & bucketLeafFlag) == 0 {
+ return ErrIncompatibleValue
+ }
+
+ // Recursively delete all child buckets.
+ child := b.Bucket(key)
+ err := child.ForEach(func(k, v []byte) error {
+ if v == nil {
+ if err := child.DeleteBucket(k); err != nil {
+ return fmt.Errorf("delete bucket: %s", err)
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ // Remove cached copy.
+ delete(b.buckets, string(key))
+
+ // Release all bucket pages to freelist.
+ child.nodes = nil
+ child.rootNode = nil
+ child.free()
+
+ // Delete the node if we have a matching key.
+ c.node().del(key)
+
+ return nil
+}
+
+// Get retrieves the value for a key in the bucket.
+// Returns a nil value if the key does not exist or if the key is a nested bucket.
+// The returned value is only valid for the life of the transaction.
+func (b *Bucket) Get(key []byte) []byte {
+ k, v, flags := b.Cursor().seek(key)
+
+ // Return nil if this is a bucket.
+ if (flags & bucketLeafFlag) != 0 {
+ return nil
+ }
+
+ // If our target node isn't the same key as what's passed in then return nil.
+ if !bytes.Equal(key, k) {
+ return nil
+ }
+ return v
+}
+
+// Put sets the value for a key in the bucket.
+// If the key exist then its previous value will be overwritten.
+// Supplied value must remain valid for the life of the transaction.
+// Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large.
+func (b *Bucket) Put(key []byte, value []byte) error {
+ if b.tx.db == nil {
+ return ErrTxClosed
+ } else if !b.Writable() {
+ return ErrTxNotWritable
+ } else if len(key) == 0 {
+ return ErrKeyRequired
+ } else if len(key) > MaxKeySize {
+ return ErrKeyTooLarge
+ } else if int64(len(value)) > MaxValueSize {
+ return ErrValueTooLarge
+ }
+
+ // Move cursor to correct position.
+ c := b.Cursor()
+ k, _, flags := c.seek(key)
+
+ // Return an error if there is an existing key with a bucket value.
+ if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 {
+ return ErrIncompatibleValue
+ }
+
+ // Insert into node.
+ key = cloneBytes(key)
+ c.node().put(key, key, value, 0, 0)
+
+ return nil
+}
+
+// Delete removes a key from the bucket.
+// If the key does not exist then nothing is done and a nil error is returned.
+// Returns an error if the bucket was created from a read-only transaction.
+func (b *Bucket) Delete(key []byte) error {
+ if b.tx.db == nil {
+ return ErrTxClosed
+ } else if !b.Writable() {
+ return ErrTxNotWritable
+ }
+
+ // Move cursor to correct position.
+ c := b.Cursor()
+ _, _, flags := c.seek(key)
+
+ // Return an error if there is already existing bucket value.
+ if (flags & bucketLeafFlag) != 0 {
+ return ErrIncompatibleValue
+ }
+
+ // Delete the node if we have a matching key.
+ c.node().del(key)
+
+ return nil
+}
+
+// Sequence returns the current integer for the bucket without incrementing it.
+func (b *Bucket) Sequence() uint64 { return b.bucket.sequence }
+
+// SetSequence updates the sequence number for the bucket.
+func (b *Bucket) SetSequence(v uint64) error {
+ if b.tx.db == nil {
+ return ErrTxClosed
+ } else if !b.Writable() {
+ return ErrTxNotWritable
+ }
+
+ // Materialize the root node if it hasn't been already so that the
+ // bucket will be saved during commit.
+ if b.rootNode == nil {
+ _ = b.node(b.root, nil)
+ }
+
+ // Increment and return the sequence.
+ b.bucket.sequence = v
+ return nil
+}
+
+// NextSequence returns an autoincrementing integer for the bucket.
+func (b *Bucket) NextSequence() (uint64, error) {
+ if b.tx.db == nil {
+ return 0, ErrTxClosed
+ } else if !b.Writable() {
+ return 0, ErrTxNotWritable
+ }
+
+ // Materialize the root node if it hasn't been already so that the
+ // bucket will be saved during commit.
+ if b.rootNode == nil {
+ _ = b.node(b.root, nil)
+ }
+
+ // Increment and return the sequence.
+ b.bucket.sequence++
+ return b.bucket.sequence, nil
+}
+
+// ForEach executes a function for each key/value pair in a bucket.
+// If the provided function returns an error then the iteration is stopped and
+// the error is returned to the caller. The provided function must not modify
+// the bucket; this will result in undefined behavior.
+func (b *Bucket) ForEach(fn func(k, v []byte) error) error {
+ if b.tx.db == nil {
+ return ErrTxClosed
+ }
+ c := b.Cursor()
+ for k, v := c.First(); k != nil; k, v = c.Next() {
+ if err := fn(k, v); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Stat returns stats on a bucket.
+func (b *Bucket) Stats() BucketStats {
+ var s, subStats BucketStats
+ pageSize := b.tx.db.pageSize
+ s.BucketN += 1
+ if b.root == 0 {
+ s.InlineBucketN += 1
+ }
+ b.forEachPage(func(p *page, depth int) {
+ if (p.flags & leafPageFlag) != 0 {
+ s.KeyN += int(p.count)
+
+ // used totals the used bytes for the page
+ used := pageHeaderSize
+
+ if p.count != 0 {
+ // If page has any elements, add all element headers.
+ used += leafPageElementSize * int(p.count-1)
+
+ // Add all element key, value sizes.
+ // The computation takes advantage of the fact that the position
+ // of the last element's key/value equals to the total of the sizes
+ // of all previous elements' keys and values.
+ // It also includes the last element's header.
+ lastElement := p.leafPageElement(p.count - 1)
+ used += int(lastElement.pos + lastElement.ksize + lastElement.vsize)
+ }
+
+ if b.root == 0 {
+ // For inlined bucket just update the inline stats
+ s.InlineBucketInuse += used
+ } else {
+ // For non-inlined bucket update all the leaf stats
+ s.LeafPageN++
+ s.LeafInuse += used
+ s.LeafOverflowN += int(p.overflow)
+
+ // Collect stats from sub-buckets.
+ // Do that by iterating over all element headers
+ // looking for the ones with the bucketLeafFlag.
+ for i := uint16(0); i < p.count; i++ {
+ e := p.leafPageElement(i)
+ if (e.flags & bucketLeafFlag) != 0 {
+ // For any bucket element, open the element value
+ // and recursively call Stats on the contained bucket.
+ subStats.Add(b.openBucket(e.value()).Stats())
+ }
+ }
+ }
+ } else if (p.flags & branchPageFlag) != 0 {
+ s.BranchPageN++
+ lastElement := p.branchPageElement(p.count - 1)
+
+ // used totals the used bytes for the page
+ // Add header and all element headers.
+ used := pageHeaderSize + (branchPageElementSize * int(p.count-1))
+
+ // Add size of all keys and values.
+ // Again, use the fact that last element's position equals to
+ // the total of key, value sizes of all previous elements.
+ used += int(lastElement.pos + lastElement.ksize)
+ s.BranchInuse += used
+ s.BranchOverflowN += int(p.overflow)
+ }
+
+ // Keep track of maximum page depth.
+ if depth+1 > s.Depth {
+ s.Depth = (depth + 1)
+ }
+ })
+
+ // Alloc stats can be computed from page counts and pageSize.
+ s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize
+ s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize
+
+ // Add the max depth of sub-buckets to get total nested depth.
+ s.Depth += subStats.Depth
+ // Add the stats for all sub-buckets
+ s.Add(subStats)
+ return s
+}
+
+// forEachPage iterates over every page in a bucket, including inline pages.
+func (b *Bucket) forEachPage(fn func(*page, int)) {
+ // If we have an inline page then just use that.
+ if b.page != nil {
+ fn(b.page, 0)
+ return
+ }
+
+ // Otherwise traverse the page hierarchy.
+ b.tx.forEachPage(b.root, 0, fn)
+}
+
+// forEachPageNode iterates over every page (or node) in a bucket.
+// This also includes inline pages.
+func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) {
+ // If we have an inline page or root node then just use that.
+ if b.page != nil {
+ fn(b.page, nil, 0)
+ return
+ }
+ b._forEachPageNode(b.root, 0, fn)
+}
+
+func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) {
+ var p, n = b.pageNode(pgid)
+
+ // Execute function.
+ fn(p, n, depth)
+
+ // Recursively loop over children.
+ if p != nil {
+ if (p.flags & branchPageFlag) != 0 {
+ for i := 0; i < int(p.count); i++ {
+ elem := p.branchPageElement(uint16(i))
+ b._forEachPageNode(elem.pgid, depth+1, fn)
+ }
+ }
+ } else {
+ if !n.isLeaf {
+ for _, inode := range n.inodes {
+ b._forEachPageNode(inode.pgid, depth+1, fn)
+ }
+ }
+ }
+}
+
+// spill writes all the nodes for this bucket to dirty pages.
+func (b *Bucket) spill() error {
+ // Spill all child buckets first.
+ for name, child := range b.buckets {
+ // If the child bucket is small enough and it has no child buckets then
+ // write it inline into the parent bucket's page. Otherwise spill it
+ // like a normal bucket and make the parent value a pointer to the page.
+ var value []byte
+ if child.inlineable() {
+ child.free()
+ value = child.write()
+ } else {
+ if err := child.spill(); err != nil {
+ return err
+ }
+
+ // Update the child bucket header in this bucket.
+ value = make([]byte, unsafe.Sizeof(bucket{}))
+ var bucket = (*bucket)(unsafe.Pointer(&value[0]))
+ *bucket = *child.bucket
+ }
+
+ // Skip writing the bucket if there are no materialized nodes.
+ if child.rootNode == nil {
+ continue
+ }
+
+ // Update parent node.
+ var c = b.Cursor()
+ k, _, flags := c.seek([]byte(name))
+ if !bytes.Equal([]byte(name), k) {
+ panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k))
+ }
+ if flags&bucketLeafFlag == 0 {
+ panic(fmt.Sprintf("unexpected bucket header flag: %x", flags))
+ }
+ c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag)
+ }
+
+ // Ignore if there's not a materialized root node.
+ if b.rootNode == nil {
+ return nil
+ }
+
+ // Spill nodes.
+ if err := b.rootNode.spill(); err != nil {
+ return err
+ }
+ b.rootNode = b.rootNode.root()
+
+ // Update the root node for this bucket.
+ if b.rootNode.pgid >= b.tx.meta.pgid {
+ panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid))
+ }
+ b.root = b.rootNode.pgid
+
+ return nil
+}
+
+// inlineable returns true if a bucket is small enough to be written inline
+// and if it contains no subbuckets. Otherwise returns false.
+func (b *Bucket) inlineable() bool {
+ var n = b.rootNode
+
+ // Bucket must only contain a single leaf node.
+ if n == nil || !n.isLeaf {
+ return false
+ }
+
+ // Bucket is not inlineable if it contains subbuckets or if it goes beyond
+ // our threshold for inline bucket size.
+ var size = pageHeaderSize
+ for _, inode := range n.inodes {
+ size += leafPageElementSize + len(inode.key) + len(inode.value)
+
+ if inode.flags&bucketLeafFlag != 0 {
+ return false
+ } else if size > b.maxInlineBucketSize() {
+ return false
+ }
+ }
+
+ return true
+}
+
+// Returns the maximum total size of a bucket to make it a candidate for inlining.
+func (b *Bucket) maxInlineBucketSize() int {
+ return b.tx.db.pageSize / 4
+}
+
+// write allocates and writes a bucket to a byte slice.
+func (b *Bucket) write() []byte {
+ // Allocate the appropriate size.
+ var n = b.rootNode
+ var value = make([]byte, bucketHeaderSize+n.size())
+
+ // Write a bucket header.
+ var bucket = (*bucket)(unsafe.Pointer(&value[0]))
+ *bucket = *b.bucket
+
+ // Convert byte slice to a fake page and write the root node.
+ var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
+ n.write(p)
+
+ return value
+}
+
+// rebalance attempts to balance all nodes.
+func (b *Bucket) rebalance() {
+ for _, n := range b.nodes {
+ n.rebalance()
+ }
+ for _, child := range b.buckets {
+ child.rebalance()
+ }
+}
+
+// node creates a node from a page and associates it with a given parent.
+func (b *Bucket) node(pgid pgid, parent *node) *node {
+ _assert(b.nodes != nil, "nodes map expected")
+
+ // Retrieve node if it's already been created.
+ if n := b.nodes[pgid]; n != nil {
+ return n
+ }
+
+ // Otherwise create a node and cache it.
+ n := &node{bucket: b, parent: parent}
+ if parent == nil {
+ b.rootNode = n
+ } else {
+ parent.children = append(parent.children, n)
+ }
+
+ // Use the inline page if this is an inline bucket.
+ var p = b.page
+ if p == nil {
+ p = b.tx.page(pgid)
+ }
+
+ // Read the page into the node and cache it.
+ n.read(p)
+ b.nodes[pgid] = n
+
+ // Update statistics.
+ b.tx.stats.NodeCount++
+
+ return n
+}
+
+// free recursively frees all pages in the bucket.
+func (b *Bucket) free() {
+ if b.root == 0 {
+ return
+ }
+
+ var tx = b.tx
+ b.forEachPageNode(func(p *page, n *node, _ int) {
+ if p != nil {
+ tx.db.freelist.free(tx.meta.txid, p)
+ } else {
+ n.free()
+ }
+ })
+ b.root = 0
+}
+
+// dereference removes all references to the old mmap.
+func (b *Bucket) dereference() {
+ if b.rootNode != nil {
+ b.rootNode.root().dereference()
+ }
+
+ for _, child := range b.buckets {
+ child.dereference()
+ }
+}
+
+// pageNode returns the in-memory node, if it exists.
+// Otherwise returns the underlying page.
+func (b *Bucket) pageNode(id pgid) (*page, *node) {
+ // Inline buckets have a fake page embedded in their value so treat them
+ // differently. We'll return the rootNode (if available) or the fake page.
+ if b.root == 0 {
+ if id != 0 {
+ panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id))
+ }
+ if b.rootNode != nil {
+ return nil, b.rootNode
+ }
+ return b.page, nil
+ }
+
+ // Check the node cache for non-inline buckets.
+ if b.nodes != nil {
+ if n := b.nodes[id]; n != nil {
+ return nil, n
+ }
+ }
+
+ // Finally lookup the page from the transaction if no node is materialized.
+ return b.tx.page(id), nil
+}
+
+// BucketStats records statistics about resources used by a bucket.
+type BucketStats struct {
+ // Page count statistics.
+ BranchPageN int // number of logical branch pages
+ BranchOverflowN int // number of physical branch overflow pages
+ LeafPageN int // number of logical leaf pages
+ LeafOverflowN int // number of physical leaf overflow pages
+
+ // Tree statistics.
+ KeyN int // number of keys/value pairs
+ Depth int // number of levels in B+tree
+
+ // Page size utilization.
+ BranchAlloc int // bytes allocated for physical branch pages
+ BranchInuse int // bytes actually used for branch data
+ LeafAlloc int // bytes allocated for physical leaf pages
+ LeafInuse int // bytes actually used for leaf data
+
+ // Bucket statistics
+ BucketN int // total number of buckets including the top bucket
+ InlineBucketN int // total number on inlined buckets
+ InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse)
+}
+
+func (s *BucketStats) Add(other BucketStats) {
+ s.BranchPageN += other.BranchPageN
+ s.BranchOverflowN += other.BranchOverflowN
+ s.LeafPageN += other.LeafPageN
+ s.LeafOverflowN += other.LeafOverflowN
+ s.KeyN += other.KeyN
+ if s.Depth < other.Depth {
+ s.Depth = other.Depth
+ }
+ s.BranchAlloc += other.BranchAlloc
+ s.BranchInuse += other.BranchInuse
+ s.LeafAlloc += other.LeafAlloc
+ s.LeafInuse += other.LeafInuse
+
+ s.BucketN += other.BucketN
+ s.InlineBucketN += other.InlineBucketN
+ s.InlineBucketInuse += other.InlineBucketInuse
+}
+
+// cloneBytes returns a copy of a given slice.
+func cloneBytes(v []byte) []byte {
+ var clone = make([]byte, len(v))
+ copy(clone, v)
+ return clone
+}
diff --git a/vendor/github.com/boltdb/bolt/cursor.go b/vendor/github.com/boltdb/bolt/cursor.go
new file mode 100644
index 0000000..1be9f35
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/cursor.go
@@ -0,0 +1,400 @@
+package bolt
+
+import (
+ "bytes"
+ "fmt"
+ "sort"
+)
+
+// Cursor represents an iterator that can traverse over all key/value pairs in a bucket in sorted order.
+// Cursors see nested buckets with value == nil.
+// Cursors can be obtained from a transaction and are valid as long as the transaction is open.
+//
+// Keys and values returned from the cursor are only valid for the life of the transaction.
+//
+// Changing data while traversing with a cursor may cause it to be invalidated
+// and return unexpected keys and/or values. You must reposition your cursor
+// after mutating data.
+type Cursor struct {
+ bucket *Bucket
+ stack []elemRef
+}
+
+// Bucket returns the bucket that this cursor was created from.
+func (c *Cursor) Bucket() *Bucket {
+ return c.bucket
+}
+
+// First moves the cursor to the first item in the bucket and returns its key and value.
+// If the bucket is empty then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) First() (key []byte, value []byte) {
+ _assert(c.bucket.tx.db != nil, "tx closed")
+ c.stack = c.stack[:0]
+ p, n := c.bucket.pageNode(c.bucket.root)
+ c.stack = append(c.stack, elemRef{page: p, node: n, index: 0})
+ c.first()
+
+ // If we land on an empty page then move to the next value.
+ // https://github.com/boltdb/bolt/issues/450
+ if c.stack[len(c.stack)-1].count() == 0 {
+ c.next()
+ }
+
+ k, v, flags := c.keyValue()
+ if (flags & uint32(bucketLeafFlag)) != 0 {
+ return k, nil
+ }
+ return k, v
+
+}
+
+// Last moves the cursor to the last item in the bucket and returns its key and value.
+// If the bucket is empty then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Last() (key []byte, value []byte) {
+ _assert(c.bucket.tx.db != nil, "tx closed")
+ c.stack = c.stack[:0]
+ p, n := c.bucket.pageNode(c.bucket.root)
+ ref := elemRef{page: p, node: n}
+ ref.index = ref.count() - 1
+ c.stack = append(c.stack, ref)
+ c.last()
+ k, v, flags := c.keyValue()
+ if (flags & uint32(bucketLeafFlag)) != 0 {
+ return k, nil
+ }
+ return k, v
+}
+
+// Next moves the cursor to the next item in the bucket and returns its key and value.
+// If the cursor is at the end of the bucket then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Next() (key []byte, value []byte) {
+ _assert(c.bucket.tx.db != nil, "tx closed")
+ k, v, flags := c.next()
+ if (flags & uint32(bucketLeafFlag)) != 0 {
+ return k, nil
+ }
+ return k, v
+}
+
+// Prev moves the cursor to the previous item in the bucket and returns its key and value.
+// If the cursor is at the beginning of the bucket then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Prev() (key []byte, value []byte) {
+ _assert(c.bucket.tx.db != nil, "tx closed")
+
+ // Attempt to move back one element until we're successful.
+ // Move up the stack as we hit the beginning of each page in our stack.
+ for i := len(c.stack) - 1; i >= 0; i-- {
+ elem := &c.stack[i]
+ if elem.index > 0 {
+ elem.index--
+ break
+ }
+ c.stack = c.stack[:i]
+ }
+
+ // If we've hit the end then return nil.
+ if len(c.stack) == 0 {
+ return nil, nil
+ }
+
+ // Move down the stack to find the last element of the last leaf under this branch.
+ c.last()
+ k, v, flags := c.keyValue()
+ if (flags & uint32(bucketLeafFlag)) != 0 {
+ return k, nil
+ }
+ return k, v
+}
+
+// Seek moves the cursor to a given key and returns it.
+// If the key does not exist then the next key is used. If no keys
+// follow, a nil key is returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) {
+ k, v, flags := c.seek(seek)
+
+ // If we ended up after the last element of a page then move to the next one.
+ if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() {
+ k, v, flags = c.next()
+ }
+
+ if k == nil {
+ return nil, nil
+ } else if (flags & uint32(bucketLeafFlag)) != 0 {
+ return k, nil
+ }
+ return k, v
+}
+
+// Delete removes the current key/value under the cursor from the bucket.
+// Delete fails if current key/value is a bucket or if the transaction is not writable.
+func (c *Cursor) Delete() error {
+ if c.bucket.tx.db == nil {
+ return ErrTxClosed
+ } else if !c.bucket.Writable() {
+ return ErrTxNotWritable
+ }
+
+ key, _, flags := c.keyValue()
+ // Return an error if current value is a bucket.
+ if (flags & bucketLeafFlag) != 0 {
+ return ErrIncompatibleValue
+ }
+ c.node().del(key)
+
+ return nil
+}
+
+// seek moves the cursor to a given key and returns it.
+// If the key does not exist then the next key is used.
+func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) {
+ _assert(c.bucket.tx.db != nil, "tx closed")
+
+ // Start from root page/node and traverse to correct page.
+ c.stack = c.stack[:0]
+ c.search(seek, c.bucket.root)
+ ref := &c.stack[len(c.stack)-1]
+
+ // If the cursor is pointing to the end of page/node then return nil.
+ if ref.index >= ref.count() {
+ return nil, nil, 0
+ }
+
+ // If this is a bucket then return a nil value.
+ return c.keyValue()
+}
+
+// first moves the cursor to the first leaf element under the last page in the stack.
+func (c *Cursor) first() {
+ for {
+ // Exit when we hit a leaf page.
+ var ref = &c.stack[len(c.stack)-1]
+ if ref.isLeaf() {
+ break
+ }
+
+ // Keep adding pages pointing to the first element to the stack.
+ var pgid pgid
+ if ref.node != nil {
+ pgid = ref.node.inodes[ref.index].pgid
+ } else {
+ pgid = ref.page.branchPageElement(uint16(ref.index)).pgid
+ }
+ p, n := c.bucket.pageNode(pgid)
+ c.stack = append(c.stack, elemRef{page: p, node: n, index: 0})
+ }
+}
+
+// last moves the cursor to the last leaf element under the last page in the stack.
+func (c *Cursor) last() {
+ for {
+ // Exit when we hit a leaf page.
+ ref := &c.stack[len(c.stack)-1]
+ if ref.isLeaf() {
+ break
+ }
+
+ // Keep adding pages pointing to the last element in the stack.
+ var pgid pgid
+ if ref.node != nil {
+ pgid = ref.node.inodes[ref.index].pgid
+ } else {
+ pgid = ref.page.branchPageElement(uint16(ref.index)).pgid
+ }
+ p, n := c.bucket.pageNode(pgid)
+
+ var nextRef = elemRef{page: p, node: n}
+ nextRef.index = nextRef.count() - 1
+ c.stack = append(c.stack, nextRef)
+ }
+}
+
+// next moves to the next leaf element and returns the key and value.
+// If the cursor is at the last leaf element then it stays there and returns nil.
+func (c *Cursor) next() (key []byte, value []byte, flags uint32) {
+ for {
+ // Attempt to move over one element until we're successful.
+ // Move up the stack as we hit the end of each page in our stack.
+ var i int
+ for i = len(c.stack) - 1; i >= 0; i-- {
+ elem := &c.stack[i]
+ if elem.index < elem.count()-1 {
+ elem.index++
+ break
+ }
+ }
+
+ // If we've hit the root page then stop and return. This will leave the
+ // cursor on the last element of the last page.
+ if i == -1 {
+ return nil, nil, 0
+ }
+
+ // Otherwise start from where we left off in the stack and find the
+ // first element of the first leaf page.
+ c.stack = c.stack[:i+1]
+ c.first()
+
+ // If this is an empty page then restart and move back up the stack.
+ // https://github.com/boltdb/bolt/issues/450
+ if c.stack[len(c.stack)-1].count() == 0 {
+ continue
+ }
+
+ return c.keyValue()
+ }
+}
+
+// search recursively performs a binary search against a given page/node until it finds a given key.
+func (c *Cursor) search(key []byte, pgid pgid) {
+ p, n := c.bucket.pageNode(pgid)
+ if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 {
+ panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags))
+ }
+ e := elemRef{page: p, node: n}
+ c.stack = append(c.stack, e)
+
+ // If we're on a leaf page/node then find the specific node.
+ if e.isLeaf() {
+ c.nsearch(key)
+ return
+ }
+
+ if n != nil {
+ c.searchNode(key, n)
+ return
+ }
+ c.searchPage(key, p)
+}
+
+func (c *Cursor) searchNode(key []byte, n *node) {
+ var exact bool
+ index := sort.Search(len(n.inodes), func(i int) bool {
+ // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now.
+ // sort.Search() finds the lowest index where f() != -1 but we need the highest index.
+ ret := bytes.Compare(n.inodes[i].key, key)
+ if ret == 0 {
+ exact = true
+ }
+ return ret != -1
+ })
+ if !exact && index > 0 {
+ index--
+ }
+ c.stack[len(c.stack)-1].index = index
+
+ // Recursively search to the next page.
+ c.search(key, n.inodes[index].pgid)
+}
+
+func (c *Cursor) searchPage(key []byte, p *page) {
+ // Binary search for the correct range.
+ inodes := p.branchPageElements()
+
+ var exact bool
+ index := sort.Search(int(p.count), func(i int) bool {
+ // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now.
+ // sort.Search() finds the lowest index where f() != -1 but we need the highest index.
+ ret := bytes.Compare(inodes[i].key(), key)
+ if ret == 0 {
+ exact = true
+ }
+ return ret != -1
+ })
+ if !exact && index > 0 {
+ index--
+ }
+ c.stack[len(c.stack)-1].index = index
+
+ // Recursively search to the next page.
+ c.search(key, inodes[index].pgid)
+}
+
+// nsearch searches the leaf node on the top of the stack for a key.
+func (c *Cursor) nsearch(key []byte) {
+ e := &c.stack[len(c.stack)-1]
+ p, n := e.page, e.node
+
+ // If we have a node then search its inodes.
+ if n != nil {
+ index := sort.Search(len(n.inodes), func(i int) bool {
+ return bytes.Compare(n.inodes[i].key, key) != -1
+ })
+ e.index = index
+ return
+ }
+
+ // If we have a page then search its leaf elements.
+ inodes := p.leafPageElements()
+ index := sort.Search(int(p.count), func(i int) bool {
+ return bytes.Compare(inodes[i].key(), key) != -1
+ })
+ e.index = index
+}
+
+// keyValue returns the key and value of the current leaf element.
+func (c *Cursor) keyValue() ([]byte, []byte, uint32) {
+ ref := &c.stack[len(c.stack)-1]
+ if ref.count() == 0 || ref.index >= ref.count() {
+ return nil, nil, 0
+ }
+
+ // Retrieve value from node.
+ if ref.node != nil {
+ inode := &ref.node.inodes[ref.index]
+ return inode.key, inode.value, inode.flags
+ }
+
+ // Or retrieve value from page.
+ elem := ref.page.leafPageElement(uint16(ref.index))
+ return elem.key(), elem.value(), elem.flags
+}
+
+// node returns the node that the cursor is currently positioned on.
+func (c *Cursor) node() *node {
+ _assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack")
+
+ // If the top of the stack is a leaf node then just return it.
+ if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() {
+ return ref.node
+ }
+
+ // Start from root and traverse down the hierarchy.
+ var n = c.stack[0].node
+ if n == nil {
+ n = c.bucket.node(c.stack[0].page.id, nil)
+ }
+ for _, ref := range c.stack[:len(c.stack)-1] {
+ _assert(!n.isLeaf, "expected branch node")
+ n = n.childAt(int(ref.index))
+ }
+ _assert(n.isLeaf, "expected leaf node")
+ return n
+}
+
+// elemRef represents a reference to an element on a given page/node.
+type elemRef struct {
+ page *page
+ node *node
+ index int
+}
+
+// isLeaf returns whether the ref is pointing at a leaf page/node.
+func (r *elemRef) isLeaf() bool {
+ if r.node != nil {
+ return r.node.isLeaf
+ }
+ return (r.page.flags & leafPageFlag) != 0
+}
+
+// count returns the number of inodes or page elements.
+func (r *elemRef) count() int {
+ if r.node != nil {
+ return len(r.node.inodes)
+ }
+ return int(r.page.count)
+}
diff --git a/vendor/github.com/boltdb/bolt/db.go b/vendor/github.com/boltdb/bolt/db.go
new file mode 100644
index 0000000..1223493
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/db.go
@@ -0,0 +1,1036 @@
+package bolt
+
+import (
+ "errors"
+ "fmt"
+ "hash/fnv"
+ "log"
+ "os"
+ "runtime"
+ "runtime/debug"
+ "strings"
+ "sync"
+ "time"
+ "unsafe"
+)
+
+// The largest step that can be taken when remapping the mmap.
+const maxMmapStep = 1 << 30 // 1GB
+
+// The data file format version.
+const version = 2
+
+// Represents a marker value to indicate that a file is a Bolt DB.
+const magic uint32 = 0xED0CDAED
+
+// IgnoreNoSync specifies whether the NoSync field of a DB is ignored when
+// syncing changes to a file. This is required as some operating systems,
+// such as OpenBSD, do not have a unified buffer cache (UBC) and writes
+// must be synchronized using the msync(2) syscall.
+const IgnoreNoSync = runtime.GOOS == "openbsd"
+
+// Default values if not set in a DB instance.
+const (
+ DefaultMaxBatchSize int = 1000
+ DefaultMaxBatchDelay = 10 * time.Millisecond
+ DefaultAllocSize = 16 * 1024 * 1024
+)
+
+// default page size for db is set to the OS page size.
+var defaultPageSize = os.Getpagesize()
+
+// DB represents a collection of buckets persisted to a file on disk.
+// All data access is performed through transactions which can be obtained through the DB.
+// All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called.
+type DB struct {
+ // When enabled, the database will perform a Check() after every commit.
+ // A panic is issued if the database is in an inconsistent state. This
+ // flag has a large performance impact so it should only be used for
+ // debugging purposes.
+ StrictMode bool
+
+ // Setting the NoSync flag will cause the database to skip fsync()
+ // calls after each commit. This can be useful when bulk loading data
+ // into a database and you can restart the bulk load in the event of
+ // a system failure or database corruption. Do not set this flag for
+ // normal use.
+ //
+ // If the package global IgnoreNoSync constant is true, this value is
+ // ignored. See the comment on that constant for more details.
+ //
+ // THIS IS UNSAFE. PLEASE USE WITH CAUTION.
+ NoSync bool
+
+ // When true, skips the truncate call when growing the database.
+ // Setting this to true is only safe on non-ext3/ext4 systems.
+ // Skipping truncation avoids preallocation of hard drive space and
+ // bypasses a truncate() and fsync() syscall on remapping.
+ //
+ // https://github.com/boltdb/bolt/issues/284
+ NoGrowSync bool
+
+ // If you want to read the entire database fast, you can set MmapFlag to
+ // syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead.
+ MmapFlags int
+
+ // MaxBatchSize is the maximum size of a batch. Default value is
+ // copied from DefaultMaxBatchSize in Open.
+ //
+ // If <=0, disables batching.
+ //
+ // Do not change concurrently with calls to Batch.
+ MaxBatchSize int
+
+ // MaxBatchDelay is the maximum delay before a batch starts.
+ // Default value is copied from DefaultMaxBatchDelay in Open.
+ //
+ // If <=0, effectively disables batching.
+ //
+ // Do not change concurrently with calls to Batch.
+ MaxBatchDelay time.Duration
+
+ // AllocSize is the amount of space allocated when the database
+ // needs to create new pages. This is done to amortize the cost
+ // of truncate() and fsync() when growing the data file.
+ AllocSize int
+
+ path string
+ file *os.File
+ lockfile *os.File // windows only
+ dataref []byte // mmap'ed readonly, write throws SEGV
+ data *[maxMapSize]byte
+ datasz int
+ filesz int // current on disk file size
+ meta0 *meta
+ meta1 *meta
+ pageSize int
+ opened bool
+ rwtx *Tx
+ txs []*Tx
+ freelist *freelist
+ stats Stats
+
+ pagePool sync.Pool
+
+ batchMu sync.Mutex
+ batch *batch
+
+ rwlock sync.Mutex // Allows only one writer at a time.
+ metalock sync.Mutex // Protects meta page access.
+ mmaplock sync.RWMutex // Protects mmap access during remapping.
+ statlock sync.RWMutex // Protects stats access.
+
+ ops struct {
+ writeAt func(b []byte, off int64) (n int, err error)
+ }
+
+ // Read only mode.
+ // When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately.
+ readOnly bool
+}
+
+// Path returns the path to currently open database file.
+func (db *DB) Path() string {
+ return db.path
+}
+
+// GoString returns the Go string representation of the database.
+func (db *DB) GoString() string {
+ return fmt.Sprintf("bolt.DB{path:%q}", db.path)
+}
+
+// String returns the string representation of the database.
+func (db *DB) String() string {
+ return fmt.Sprintf("DB<%q>", db.path)
+}
+
+// Open creates and opens a database at the given path.
+// If the file does not exist then it will be created automatically.
+// Passing in nil options will cause Bolt to open the database with the default options.
+func Open(path string, mode os.FileMode, options *Options) (*DB, error) {
+ var db = &DB{opened: true}
+
+ // Set default options if no options are provided.
+ if options == nil {
+ options = DefaultOptions
+ }
+ db.NoGrowSync = options.NoGrowSync
+ db.MmapFlags = options.MmapFlags
+
+ // Set default values for later DB operations.
+ db.MaxBatchSize = DefaultMaxBatchSize
+ db.MaxBatchDelay = DefaultMaxBatchDelay
+ db.AllocSize = DefaultAllocSize
+
+ flag := os.O_RDWR
+ if options.ReadOnly {
+ flag = os.O_RDONLY
+ db.readOnly = true
+ }
+
+ // Open data file and separate sync handler for metadata writes.
+ db.path = path
+ var err error
+ if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil {
+ _ = db.close()
+ return nil, err
+ }
+
+ // Lock file so that other processes using Bolt in read-write mode cannot
+ // use the database at the same time. This would cause corruption since
+ // the two processes would write meta pages and free pages separately.
+ // The database file is locked exclusively (only one process can grab the lock)
+ // if !options.ReadOnly.
+ // The database file is locked using the shared lock (more than one process may
+ // hold a lock at the same time) otherwise (options.ReadOnly is set).
+ if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil {
+ _ = db.close()
+ return nil, err
+ }
+
+ // Default values for test hooks
+ db.ops.writeAt = db.file.WriteAt
+
+ // Initialize the database if it doesn't exist.
+ if info, err := db.file.Stat(); err != nil {
+ return nil, err
+ } else if info.Size() == 0 {
+ // Initialize new files with meta pages.
+ if err := db.init(); err != nil {
+ return nil, err
+ }
+ } else {
+ // Read the first meta page to determine the page size.
+ var buf [0x1000]byte
+ if _, err := db.file.ReadAt(buf[:], 0); err == nil {
+ m := db.pageInBuffer(buf[:], 0).meta()
+ if err := m.validate(); err != nil {
+ // If we can't read the page size, we can assume it's the same
+ // as the OS -- since that's how the page size was chosen in the
+ // first place.
+ //
+ // If the first page is invalid and this OS uses a different
+ // page size than what the database was created with then we
+ // are out of luck and cannot access the database.
+ db.pageSize = os.Getpagesize()
+ } else {
+ db.pageSize = int(m.pageSize)
+ }
+ }
+ }
+
+ // Initialize page pool.
+ db.pagePool = sync.Pool{
+ New: func() interface{} {
+ return make([]byte, db.pageSize)
+ },
+ }
+
+ // Memory map the data file.
+ if err := db.mmap(options.InitialMmapSize); err != nil {
+ _ = db.close()
+ return nil, err
+ }
+
+ // Read in the freelist.
+ db.freelist = newFreelist()
+ db.freelist.read(db.page(db.meta().freelist))
+
+ // Mark the database as opened and return.
+ return db, nil
+}
+
+// mmap opens the underlying memory-mapped file and initializes the meta references.
+// minsz is the minimum size that the new mmap can be.
+func (db *DB) mmap(minsz int) error {
+ db.mmaplock.Lock()
+ defer db.mmaplock.Unlock()
+
+ info, err := db.file.Stat()
+ if err != nil {
+ return fmt.Errorf("mmap stat error: %s", err)
+ } else if int(info.Size()) < db.pageSize*2 {
+ return fmt.Errorf("file size too small")
+ }
+
+ // Ensure the size is at least the minimum size.
+ var size = int(info.Size())
+ if size < minsz {
+ size = minsz
+ }
+ size, err = db.mmapSize(size)
+ if err != nil {
+ return err
+ }
+
+ // Dereference all mmap references before unmapping.
+ if db.rwtx != nil {
+ db.rwtx.root.dereference()
+ }
+
+ // Unmap existing data before continuing.
+ if err := db.munmap(); err != nil {
+ return err
+ }
+
+ // Memory-map the data file as a byte slice.
+ if err := mmap(db, size); err != nil {
+ return err
+ }
+
+ // Save references to the meta pages.
+ db.meta0 = db.page(0).meta()
+ db.meta1 = db.page(1).meta()
+
+ // Validate the meta pages. We only return an error if both meta pages fail
+ // validation, since meta0 failing validation means that it wasn't saved
+ // properly -- but we can recover using meta1. And vice-versa.
+ err0 := db.meta0.validate()
+ err1 := db.meta1.validate()
+ if err0 != nil && err1 != nil {
+ return err0
+ }
+
+ return nil
+}
+
+// munmap unmaps the data file from memory.
+func (db *DB) munmap() error {
+ if err := munmap(db); err != nil {
+ return fmt.Errorf("unmap error: " + err.Error())
+ }
+ return nil
+}
+
+// mmapSize determines the appropriate size for the mmap given the current size
+// of the database. The minimum size is 32KB and doubles until it reaches 1GB.
+// Returns an error if the new mmap size is greater than the max allowed.
+func (db *DB) mmapSize(size int) (int, error) {
+ // Double the size from 32KB until 1GB.
+ for i := uint(15); i <= 30; i++ {
+ if size <= 1<<i {
+ return 1 << i, nil
+ }
+ }
+
+ // Verify the requested size is not above the maximum allowed.
+ if size > maxMapSize {
+ return 0, fmt.Errorf("mmap too large")
+ }
+
+ // If larger than 1GB then grow by 1GB at a time.
+ sz := int64(size)
+ if remainder := sz % int64(maxMmapStep); remainder > 0 {
+ sz += int64(maxMmapStep) - remainder
+ }
+
+ // Ensure that the mmap size is a multiple of the page size.
+ // This should always be true since we're incrementing in MBs.
+ pageSize := int64(db.pageSize)
+ if (sz % pageSize) != 0 {
+ sz = ((sz / pageSize) + 1) * pageSize
+ }
+
+ // If we've exceeded the max size then only grow up to the max size.
+ if sz > maxMapSize {
+ sz = maxMapSize
+ }
+
+ return int(sz), nil
+}
+
+// init creates a new database file and initializes its meta pages.
+func (db *DB) init() error {
+ // Set the page size to the OS page size.
+ db.pageSize = os.Getpagesize()
+
+ // Create two meta pages on a buffer.
+ buf := make([]byte, db.pageSize*4)
+ for i := 0; i < 2; i++ {
+ p := db.pageInBuffer(buf[:], pgid(i))
+ p.id = pgid(i)
+ p.flags = metaPageFlag
+
+ // Initialize the meta page.
+ m := p.meta()
+ m.magic = magic
+ m.version = version
+ m.pageSize = uint32(db.pageSize)
+ m.freelist = 2
+ m.root = bucket{root: 3}
+ m.pgid = 4
+ m.txid = txid(i)
+ m.checksum = m.sum64()
+ }
+
+ // Write an empty freelist at page 3.
+ p := db.pageInBuffer(buf[:], pgid(2))
+ p.id = pgid(2)
+ p.flags = freelistPageFlag
+ p.count = 0
+
+ // Write an empty leaf page at page 4.
+ p = db.pageInBuffer(buf[:], pgid(3))
+ p.id = pgid(3)
+ p.flags = leafPageFlag
+ p.count = 0
+
+ // Write the buffer to our data file.
+ if _, err := db.ops.writeAt(buf, 0); err != nil {
+ return err
+ }
+ if err := fdatasync(db); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Close releases all database resources.
+// All transactions must be closed before closing the database.
+func (db *DB) Close() error {
+ db.rwlock.Lock()
+ defer db.rwlock.Unlock()
+
+ db.metalock.Lock()
+ defer db.metalock.Unlock()
+
+ db.mmaplock.RLock()
+ defer db.mmaplock.RUnlock()
+
+ return db.close()
+}
+
+func (db *DB) close() error {
+ if !db.opened {
+ return nil
+ }
+
+ db.opened = false
+
+ db.freelist = nil
+
+ // Clear ops.
+ db.ops.writeAt = nil
+
+ // Close the mmap.
+ if err := db.munmap(); err != nil {
+ return err
+ }
+
+ // Close file handles.
+ if db.file != nil {
+ // No need to unlock read-only file.
+ if !db.readOnly {
+ // Unlock the file.
+ if err := funlock(db); err != nil {
+ log.Printf("bolt.Close(): funlock error: %s", err)
+ }
+ }
+
+ // Close the file descriptor.
+ if err := db.file.Close(); err != nil {
+ return fmt.Errorf("db file close: %s", err)
+ }
+ db.file = nil
+ }
+
+ db.path = ""
+ return nil
+}
+
+// Begin starts a new transaction.
+// Multiple read-only transactions can be used concurrently but only one
+// write transaction can be used at a time. Starting multiple write transactions
+// will cause the calls to block and be serialized until the current write
+// transaction finishes.
+//
+// Transactions should not be dependent on one another. Opening a read
+// transaction and a write transaction in the same goroutine can cause the
+// writer to deadlock because the database periodically needs to re-mmap itself
+// as it grows and it cannot do that while a read transaction is open.
+//
+// If a long running read transaction (for example, a snapshot transaction) is
+// needed, you might want to set DB.InitialMmapSize to a large enough value
+// to avoid potential blocking of write transaction.
+//
+// IMPORTANT: You must close read-only transactions after you are finished or
+// else the database will not reclaim old pages.
+func (db *DB) Begin(writable bool) (*Tx, error) {
+ if writable {
+ return db.beginRWTx()
+ }
+ return db.beginTx()
+}
+
+func (db *DB) beginTx() (*Tx, error) {
+ // Lock the meta pages while we initialize the transaction. We obtain
+ // the meta lock before the mmap lock because that's the order that the
+ // write transaction will obtain them.
+ db.metalock.Lock()
+
+ // Obtain a read-only lock on the mmap. When the mmap is remapped it will
+ // obtain a write lock so all transactions must finish before it can be
+ // remapped.
+ db.mmaplock.RLock()
+
+ // Exit if the database is not open yet.
+ if !db.opened {
+ db.mmaplock.RUnlock()
+ db.metalock.Unlock()
+ return nil, ErrDatabaseNotOpen
+ }
+
+ // Create a transaction associated with the database.
+ t := &Tx{}
+ t.init(db)
+
+ // Keep track of transaction until it closes.
+ db.txs = append(db.txs, t)
+ n := len(db.txs)
+
+ // Unlock the meta pages.
+ db.metalock.Unlock()
+
+ // Update the transaction stats.
+ db.statlock.Lock()
+ db.stats.TxN++
+ db.stats.OpenTxN = n
+ db.statlock.Unlock()
+
+ return t, nil
+}
+
+func (db *DB) beginRWTx() (*Tx, error) {
+ // If the database was opened with Options.ReadOnly, return an error.
+ if db.readOnly {
+ return nil, ErrDatabaseReadOnly
+ }
+
+ // Obtain writer lock. This is released by the transaction when it closes.
+ // This enforces only one writer transaction at a time.
+ db.rwlock.Lock()
+
+ // Once we have the writer lock then we can lock the meta pages so that
+ // we can set up the transaction.
+ db.metalock.Lock()
+ defer db.metalock.Unlock()
+
+ // Exit if the database is not open yet.
+ if !db.opened {
+ db.rwlock.Unlock()
+ return nil, ErrDatabaseNotOpen
+ }
+
+ // Create a transaction associated with the database.
+ t := &Tx{writable: true}
+ t.init(db)
+ db.rwtx = t
+
+ // Free any pages associated with closed read-only transactions.
+ var minid txid = 0xFFFFFFFFFFFFFFFF
+ for _, t := range db.txs {
+ if t.meta.txid < minid {
+ minid = t.meta.txid
+ }
+ }
+ if minid > 0 {
+ db.freelist.release(minid - 1)
+ }
+
+ return t, nil
+}
+
+// removeTx removes a transaction from the database.
+func (db *DB) removeTx(tx *Tx) {
+ // Release the read lock on the mmap.
+ db.mmaplock.RUnlock()
+
+ // Use the meta lock to restrict access to the DB object.
+ db.metalock.Lock()
+
+ // Remove the transaction.
+ for i, t := range db.txs {
+ if t == tx {
+ db.txs = append(db.txs[:i], db.txs[i+1:]...)
+ break
+ }
+ }
+ n := len(db.txs)
+
+ // Unlock the meta pages.
+ db.metalock.Unlock()
+
+ // Merge statistics.
+ db.statlock.Lock()
+ db.stats.OpenTxN = n
+ db.stats.TxStats.add(&tx.stats)
+ db.statlock.Unlock()
+}
+
+// Update executes a function within the context of a read-write managed transaction.
+// If no error is returned from the function then the transaction is committed.
+// If an error is returned then the entire transaction is rolled back.
+// Any error that is returned from the function or returned from the commit is
+// returned from the Update() method.
+//
+// Attempting to manually commit or rollback within the function will cause a panic.
+func (db *DB) Update(fn func(*Tx) error) error {
+ t, err := db.Begin(true)
+ if err != nil {
+ return err
+ }
+
+ // Make sure the transaction rolls back in the event of a panic.
+ defer func() {
+ if t.db != nil {
+ t.rollback()
+ }
+ }()
+
+ // Mark as a managed tx so that the inner function cannot manually commit.
+ t.managed = true
+
+ // If an error is returned from the function then rollback and return error.
+ err = fn(t)
+ t.managed = false
+ if err != nil {
+ _ = t.Rollback()
+ return err
+ }
+
+ return t.Commit()
+}
+
+// View executes a function within the context of a managed read-only transaction.
+// Any error that is returned from the function is returned from the View() method.
+//
+// Attempting to manually rollback within the function will cause a panic.
+func (db *DB) View(fn func(*Tx) error) error {
+ t, err := db.Begin(false)
+ if err != nil {
+ return err
+ }
+
+ // Make sure the transaction rolls back in the event of a panic.
+ defer func() {
+ if t.db != nil {
+ t.rollback()
+ }
+ }()
+
+ // Mark as a managed tx so that the inner function cannot manually rollback.
+ t.managed = true
+
+ // If an error is returned from the function then pass it through.
+ err = fn(t)
+ t.managed = false
+ if err != nil {
+ _ = t.Rollback()
+ return err
+ }
+
+ if err := t.Rollback(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Batch calls fn as part of a batch. It behaves similar to Update,
+// except:
+//
+// 1. concurrent Batch calls can be combined into a single Bolt
+// transaction.
+//
+// 2. the function passed to Batch may be called multiple times,
+// regardless of whether it returns error or not.
+//
+// This means that Batch function side effects must be idempotent and
+// take permanent effect only after a successful return is seen in
+// caller.
+//
+// The maximum batch size and delay can be adjusted with DB.MaxBatchSize
+// and DB.MaxBatchDelay, respectively.
+//
+// Batch is only useful when there are multiple goroutines calling it.
+func (db *DB) Batch(fn func(*Tx) error) error {
+ errCh := make(chan error, 1)
+
+ db.batchMu.Lock()
+ if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) {
+ // There is no existing batch, or the existing batch is full; start a new one.
+ db.batch = &batch{
+ db: db,
+ }
+ db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger)
+ }
+ db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh})
+ if len(db.batch.calls) >= db.MaxBatchSize {
+ // wake up batch, it's ready to run
+ go db.batch.trigger()
+ }
+ db.batchMu.Unlock()
+
+ err := <-errCh
+ if err == trySolo {
+ err = db.Update(fn)
+ }
+ return err
+}
+
+type call struct {
+ fn func(*Tx) error
+ err chan<- error
+}
+
+type batch struct {
+ db *DB
+ timer *time.Timer
+ start sync.Once
+ calls []call
+}
+
+// trigger runs the batch if it hasn't already been run.
+func (b *batch) trigger() {
+ b.start.Do(b.run)
+}
+
+// run performs the transactions in the batch and communicates results
+// back to DB.Batch.
+func (b *batch) run() {
+ b.db.batchMu.Lock()
+ b.timer.Stop()
+ // Make sure no new work is added to this batch, but don't break
+ // other batches.
+ if b.db.batch == b {
+ b.db.batch = nil
+ }
+ b.db.batchMu.Unlock()
+
+retry:
+ for len(b.calls) > 0 {
+ var failIdx = -1
+ err := b.db.Update(func(tx *Tx) error {
+ for i, c := range b.calls {
+ if err := safelyCall(c.fn, tx); err != nil {
+ failIdx = i
+ return err
+ }
+ }
+ return nil
+ })
+
+ if failIdx >= 0 {
+ // take the failing transaction out of the batch. it's
+ // safe to shorten b.calls here because db.batch no longer
+ // points to us, and we hold the mutex anyway.
+ c := b.calls[failIdx]
+ b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1]
+ // tell the submitter re-run it solo, continue with the rest of the batch
+ c.err <- trySolo
+ continue retry
+ }
+
+ // pass success, or bolt internal errors, to all callers
+ for _, c := range b.calls {
+ if c.err != nil {
+ c.err <- err
+ }
+ }
+ break retry
+ }
+}
+
+// trySolo is a special sentinel error value used for signaling that a
+// transaction function should be re-run. It should never be seen by
+// callers.
+var trySolo = errors.New("batch function returned an error and should be re-run solo")
+
+type panicked struct {
+ reason interface{}
+}
+
+func (p panicked) Error() string {
+ if err, ok := p.reason.(error); ok {
+ return err.Error()
+ }
+ return fmt.Sprintf("panic: %v", p.reason)
+}
+
+func safelyCall(fn func(*Tx) error, tx *Tx) (err error) {
+ defer func() {
+ if p := recover(); p != nil {
+ err = panicked{p}
+ }
+ }()
+ return fn(tx)
+}
+
+// Sync executes fdatasync() against the database file handle.
+//
+// This is not necessary under normal operation, however, if you use NoSync
+// then it allows you to force the database file to sync against the disk.
+func (db *DB) Sync() error { return fdatasync(db) }
+
+// Stats retrieves ongoing performance stats for the database.
+// This is only updated when a transaction closes.
+func (db *DB) Stats() Stats {
+ db.statlock.RLock()
+ defer db.statlock.RUnlock()
+ return db.stats
+}
+
+// This is for internal access to the raw data bytes from the C cursor, use
+// carefully, or not at all.
+func (db *DB) Info() *Info {
+ return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize}
+}
+
+// page retrieves a page reference from the mmap based on the current page size.
+func (db *DB) page(id pgid) *page {
+ pos := id * pgid(db.pageSize)
+ return (*page)(unsafe.Pointer(&db.data[pos]))
+}
+
+// pageInBuffer retrieves a page reference from a given byte array based on the current page size.
+func (db *DB) pageInBuffer(b []byte, id pgid) *page {
+ return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)]))
+}
+
+// meta retrieves the current meta page reference.
+func (db *DB) meta() *meta {
+ // We have to return the meta with the highest txid which doesn't fail
+ // validation. Otherwise, we can cause errors when in fact the database is
+ // in a consistent state. metaA is the one with the higher txid.
+ metaA := db.meta0
+ metaB := db.meta1
+ if db.meta1.txid > db.meta0.txid {
+ metaA = db.meta1
+ metaB = db.meta0
+ }
+
+ // Use higher meta page if valid. Otherwise fallback to previous, if valid.
+ if err := metaA.validate(); err == nil {
+ return metaA
+ } else if err := metaB.validate(); err == nil {
+ return metaB
+ }
+
+ // This should never be reached, because both meta1 and meta0 were validated
+ // on mmap() and we do fsync() on every write.
+ panic("bolt.DB.meta(): invalid meta pages")
+}
+
+// allocate returns a contiguous block of memory starting at a given page.
+func (db *DB) allocate(count int) (*page, error) {
+ // Allocate a temporary buffer for the page.
+ var buf []byte
+ if count == 1 {
+ buf = db.pagePool.Get().([]byte)
+ } else {
+ buf = make([]byte, count*db.pageSize)
+ }
+ p := (*page)(unsafe.Pointer(&buf[0]))
+ p.overflow = uint32(count - 1)
+
+ // Use pages from the freelist if they are available.
+ if p.id = db.freelist.allocate(count); p.id != 0 {
+ return p, nil
+ }
+
+ // Resize mmap() if we're at the end.
+ p.id = db.rwtx.meta.pgid
+ var minsz = int((p.id+pgid(count))+1) * db.pageSize
+ if minsz >= db.datasz {
+ if err := db.mmap(minsz); err != nil {
+ return nil, fmt.Errorf("mmap allocate error: %s", err)
+ }
+ }
+
+ // Move the page id high water mark.
+ db.rwtx.meta.pgid += pgid(count)
+
+ return p, nil
+}
+
+// grow grows the size of the database to the given sz.
+func (db *DB) grow(sz int) error {
+ // Ignore if the new size is less than available file size.
+ if sz <= db.filesz {
+ return nil
+ }
+
+ // If the data is smaller than the alloc size then only allocate what's needed.
+ // Once it goes over the allocation size then allocate in chunks.
+ if db.datasz < db.AllocSize {
+ sz = db.datasz
+ } else {
+ sz += db.AllocSize
+ }
+
+ // Truncate and fsync to ensure file size metadata is flushed.
+ // https://github.com/boltdb/bolt/issues/284
+ if !db.NoGrowSync && !db.readOnly {
+ if runtime.GOOS != "windows" {
+ if err := db.file.Truncate(int64(sz)); err != nil {
+ return fmt.Errorf("file resize error: %s", err)
+ }
+ }
+ if err := db.file.Sync(); err != nil {
+ return fmt.Errorf("file sync error: %s", err)
+ }
+ }
+
+ db.filesz = sz
+ return nil
+}
+
+func (db *DB) IsReadOnly() bool {
+ return db.readOnly
+}
+
+// Options represents the options that can be set when opening a database.
+type Options struct {
+ // Timeout is the amount of time to wait to obtain a file lock.
+ // When set to zero it will wait indefinitely. This option is only
+ // available on Darwin and Linux.
+ Timeout time.Duration
+
+ // Sets the DB.NoGrowSync flag before memory mapping the file.
+ NoGrowSync bool
+
+ // Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to
+ // grab a shared lock (UNIX).
+ ReadOnly bool
+
+ // Sets the DB.MmapFlags flag before memory mapping the file.
+ MmapFlags int
+
+ // InitialMmapSize is the initial mmap size of the database
+ // in bytes. Read transactions won't block write transaction
+ // if the InitialMmapSize is large enough to hold database mmap
+ // size. (See DB.Begin for more information)
+ //
+ // If <=0, the initial map size is 0.
+ // If initialMmapSize is smaller than the previous database size,
+ // it takes no effect.
+ InitialMmapSize int
+}
+
+// DefaultOptions represent the options used if nil options are passed into Open().
+// No timeout is used which will cause Bolt to wait indefinitely for a lock.
+var DefaultOptions = &Options{
+ Timeout: 0,
+ NoGrowSync: false,
+}
+
+// Stats represents statistics about the database.
+type Stats struct {
+ // Freelist stats
+ FreePageN int // total number of free pages on the freelist
+ PendingPageN int // total number of pending pages on the freelist
+ FreeAlloc int // total bytes allocated in free pages
+ FreelistInuse int // total bytes used by the freelist
+
+ // Transaction stats
+ TxN int // total number of started read transactions
+ OpenTxN int // number of currently open read transactions
+
+ TxStats TxStats // global, ongoing stats.
+}
+
+// Sub calculates and returns the difference between two sets of database stats.
+// This is useful when obtaining stats at two different points and time and
+// you need the performance counters that occurred within that time span.
+func (s *Stats) Sub(other *Stats) Stats {
+ if other == nil {
+ return *s
+ }
+ var diff Stats
+ diff.FreePageN = s.FreePageN
+ diff.PendingPageN = s.PendingPageN
+ diff.FreeAlloc = s.FreeAlloc
+ diff.FreelistInuse = s.FreelistInuse
+ diff.TxN = other.TxN - s.TxN
+ diff.TxStats = s.TxStats.Sub(&other.TxStats)
+ return diff
+}
+
+func (s *Stats) add(other *Stats) {
+ s.TxStats.add(&other.TxStats)
+}
+
+type Info struct {
+ Data uintptr
+ PageSize int
+}
+
+type meta struct {
+ magic uint32
+ version uint32
+ pageSize uint32
+ flags uint32
+ root bucket
+ freelist pgid
+ pgid pgid
+ txid txid
+ checksum uint64
+}
+
+// validate checks the marker bytes and version of the meta page to ensure it matches this binary.
+func (m *meta) validate() error {
+ if m.magic != magic {
+ return ErrInvalid
+ } else if m.version != version {
+ return ErrVersionMismatch
+ } else if m.checksum != 0 && m.checksum != m.sum64() {
+ return ErrChecksum
+ }
+ return nil
+}
+
+// copy copies one meta object to another.
+func (m *meta) copy(dest *meta) {
+ *dest = *m
+}
+
+// write writes the meta onto a page.
+func (m *meta) write(p *page) {
+ if m.root.root >= m.pgid {
+ panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid))
+ } else if m.freelist >= m.pgid {
+ panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid))
+ }
+
+ // Page id is either going to be 0 or 1 which we can determine by the transaction ID.
+ p.id = pgid(m.txid % 2)
+ p.flags |= metaPageFlag
+
+ // Calculate the checksum.
+ m.checksum = m.sum64()
+
+ m.copy(p.meta())
+}
+
+// generates the checksum for the meta.
+func (m *meta) sum64() uint64 {
+ var h = fnv.New64a()
+ _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:])
+ return h.Sum64()
+}
+
+// _assert will panic with a given formatted message if the given condition is false.
+func _assert(condition bool, msg string, v ...interface{}) {
+ if !condition {
+ panic(fmt.Sprintf("assertion failed: "+msg, v...))
+ }
+}
+
+func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) }
+func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) }
+
+func printstack() {
+ stack := strings.Join(strings.Split(string(debug.Stack()), "\n")[2:], "\n")
+ fmt.Fprintln(os.Stderr, stack)
+}
diff --git a/vendor/github.com/boltdb/bolt/doc.go b/vendor/github.com/boltdb/bolt/doc.go
new file mode 100644
index 0000000..cc93784
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/doc.go
@@ -0,0 +1,44 @@
+/*
+Package bolt implements a low-level key/value store in pure Go. It supports
+fully serializable transactions, ACID semantics, and lock-free MVCC with
+multiple readers and a single writer. Bolt can be used for projects that
+want a simple data store without the need to add large dependencies such as
+Postgres or MySQL.
+
+Bolt is a single-level, zero-copy, B+tree data store. This means that Bolt is
+optimized for fast read access and does not require recovery in the event of a
+system crash. Transactions which have not finished committing will simply be
+rolled back in the event of a crash.
+
+The design of Bolt is based on Howard Chu's LMDB database project.
+
+Bolt currently works on Windows, Mac OS X, and Linux.
+
+
+Basics
+
+There are only a few types in Bolt: DB, Bucket, Tx, and Cursor. The DB is
+a collection of buckets and is represented by a single file on disk. A bucket is
+a collection of unique keys that are associated with values.
+
+Transactions provide either read-only or read-write access to the database.
+Read-only transactions can retrieve key/value pairs and can use Cursors to
+iterate over the dataset sequentially. Read-write transactions can create and
+delete buckets and can insert and remove keys. Only one read-write transaction
+is allowed at a time.
+
+
+Caveats
+
+The database uses a read-only, memory-mapped data file to ensure that
+applications cannot corrupt the database, however, this means that keys and
+values returned from Bolt cannot be changed. Writing to a read-only byte slice
+will cause Go to panic.
+
+Keys and values retrieved from the database are only valid for the life of
+the transaction. When used outside the transaction, these byte slices can
+point to different data or can point to invalid memory which will cause a panic.
+
+
+*/
+package bolt
diff --git a/vendor/github.com/boltdb/bolt/errors.go b/vendor/github.com/boltdb/bolt/errors.go
new file mode 100644
index 0000000..a3620a3
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/errors.go
@@ -0,0 +1,71 @@
+package bolt
+
+import "errors"
+
+// These errors can be returned when opening or calling methods on a DB.
+var (
+ // ErrDatabaseNotOpen is returned when a DB instance is accessed before it
+ // is opened or after it is closed.
+ ErrDatabaseNotOpen = errors.New("database not open")
+
+ // ErrDatabaseOpen is returned when opening a database that is
+ // already open.
+ ErrDatabaseOpen = errors.New("database already open")
+
+ // ErrInvalid is returned when both meta pages on a database are invalid.
+ // This typically occurs when a file is not a bolt database.
+ ErrInvalid = errors.New("invalid database")
+
+ // ErrVersionMismatch is returned when the data file was created with a
+ // different version of Bolt.
+ ErrVersionMismatch = errors.New("version mismatch")
+
+ // ErrChecksum is returned when either meta page checksum does not match.
+ ErrChecksum = errors.New("checksum error")
+
+ // ErrTimeout is returned when a database cannot obtain an exclusive lock
+ // on the data file after the timeout passed to Open().
+ ErrTimeout = errors.New("timeout")
+)
+
+// These errors can occur when beginning or committing a Tx.
+var (
+ // ErrTxNotWritable is returned when performing a write operation on a
+ // read-only transaction.
+ ErrTxNotWritable = errors.New("tx not writable")
+
+ // ErrTxClosed is returned when committing or rolling back a transaction
+ // that has already been committed or rolled back.
+ ErrTxClosed = errors.New("tx closed")
+
+ // ErrDatabaseReadOnly is returned when a mutating transaction is started on a
+ // read-only database.
+ ErrDatabaseReadOnly = errors.New("database is in read-only mode")
+)
+
+// These errors can occur when putting or deleting a value or a bucket.
+var (
+ // ErrBucketNotFound is returned when trying to access a bucket that has
+ // not been created yet.
+ ErrBucketNotFound = errors.New("bucket not found")
+
+ // ErrBucketExists is returned when creating a bucket that already exists.
+ ErrBucketExists = errors.New("bucket already exists")
+
+ // ErrBucketNameRequired is returned when creating a bucket with a blank name.
+ ErrBucketNameRequired = errors.New("bucket name required")
+
+ // ErrKeyRequired is returned when inserting a zero-length key.
+ ErrKeyRequired = errors.New("key required")
+
+ // ErrKeyTooLarge is returned when inserting a key that is larger than MaxKeySize.
+ ErrKeyTooLarge = errors.New("key too large")
+
+ // ErrValueTooLarge is returned when inserting a value that is larger than MaxValueSize.
+ ErrValueTooLarge = errors.New("value too large")
+
+ // ErrIncompatibleValue is returned when trying create or delete a bucket
+ // on an existing non-bucket key or when trying to create or delete a
+ // non-bucket key on an existing bucket key.
+ ErrIncompatibleValue = errors.New("incompatible value")
+)
diff --git a/vendor/github.com/boltdb/bolt/freelist.go b/vendor/github.com/boltdb/bolt/freelist.go
new file mode 100644
index 0000000..d32f6cd
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/freelist.go
@@ -0,0 +1,248 @@
+package bolt
+
+import (
+ "fmt"
+ "sort"
+ "unsafe"
+)
+
+// freelist represents a list of all pages that are available for allocation.
+// It also tracks pages that have been freed but are still in use by open transactions.
+type freelist struct {
+ ids []pgid // all free and available free page ids.
+ pending map[txid][]pgid // mapping of soon-to-be free page ids by tx.
+ cache map[pgid]bool // fast lookup of all free and pending page ids.
+}
+
+// newFreelist returns an empty, initialized freelist.
+func newFreelist() *freelist {
+ return &freelist{
+ pending: make(map[txid][]pgid),
+ cache: make(map[pgid]bool),
+ }
+}
+
+// size returns the size of the page after serialization.
+func (f *freelist) size() int {
+ return pageHeaderSize + (int(unsafe.Sizeof(pgid(0))) * f.count())
+}
+
+// count returns count of pages on the freelist
+func (f *freelist) count() int {
+ return f.free_count() + f.pending_count()
+}
+
+// free_count returns count of free pages
+func (f *freelist) free_count() int {
+ return len(f.ids)
+}
+
+// pending_count returns count of pending pages
+func (f *freelist) pending_count() int {
+ var count int
+ for _, list := range f.pending {
+ count += len(list)
+ }
+ return count
+}
+
+// all returns a list of all free ids and all pending ids in one sorted list.
+func (f *freelist) all() []pgid {
+ m := make(pgids, 0)
+
+ for _, list := range f.pending {
+ m = append(m, list...)
+ }
+
+ sort.Sort(m)
+ return pgids(f.ids).merge(m)
+}
+
+// allocate returns the starting page id of a contiguous list of pages of a given size.
+// If a contiguous block cannot be found then 0 is returned.
+func (f *freelist) allocate(n int) pgid {
+ if len(f.ids) == 0 {
+ return 0
+ }
+
+ var initial, previd pgid
+ for i, id := range f.ids {
+ if id <= 1 {
+ panic(fmt.Sprintf("invalid page allocation: %d", id))
+ }
+
+ // Reset initial page if this is not contiguous.
+ if previd == 0 || id-previd != 1 {
+ initial = id
+ }
+
+ // If we found a contiguous block then remove it and return it.
+ if (id-initial)+1 == pgid(n) {
+ // If we're allocating off the beginning then take the fast path
+ // and just adjust the existing slice. This will use extra memory
+ // temporarily but the append() in free() will realloc the slice
+ // as is necessary.
+ if (i + 1) == n {
+ f.ids = f.ids[i+1:]
+ } else {
+ copy(f.ids[i-n+1:], f.ids[i+1:])
+ f.ids = f.ids[:len(f.ids)-n]
+ }
+
+ // Remove from the free cache.
+ for i := pgid(0); i < pgid(n); i++ {
+ delete(f.cache, initial+i)
+ }
+
+ return initial
+ }
+
+ previd = id
+ }
+ return 0
+}
+
+// free releases a page and its overflow for a given transaction id.
+// If the page is already free then a panic will occur.
+func (f *freelist) free(txid txid, p *page) {
+ if p.id <= 1 {
+ panic(fmt.Sprintf("cannot free page 0 or 1: %d", p.id))
+ }
+
+ // Free page and all its overflow pages.
+ var ids = f.pending[txid]
+ for id := p.id; id <= p.id+pgid(p.overflow); id++ {
+ // Verify that page is not already free.
+ if f.cache[id] {
+ panic(fmt.Sprintf("page %d already freed", id))
+ }
+
+ // Add to the freelist and cache.
+ ids = append(ids, id)
+ f.cache[id] = true
+ }
+ f.pending[txid] = ids
+}
+
+// release moves all page ids for a transaction id (or older) to the freelist.
+func (f *freelist) release(txid txid) {
+ m := make(pgids, 0)
+ for tid, ids := range f.pending {
+ if tid <= txid {
+ // Move transaction's pending pages to the available freelist.
+ // Don't remove from the cache since the page is still free.
+ m = append(m, ids...)
+ delete(f.pending, tid)
+ }
+ }
+ sort.Sort(m)
+ f.ids = pgids(f.ids).merge(m)
+}
+
+// rollback removes the pages from a given pending tx.
+func (f *freelist) rollback(txid txid) {
+ // Remove page ids from cache.
+ for _, id := range f.pending[txid] {
+ delete(f.cache, id)
+ }
+
+ // Remove pages from pending list.
+ delete(f.pending, txid)
+}
+
+// freed returns whether a given page is in the free list.
+func (f *freelist) freed(pgid pgid) bool {
+ return f.cache[pgid]
+}
+
+// read initializes the freelist from a freelist page.
+func (f *freelist) read(p *page) {
+ // If the page.count is at the max uint16 value (64k) then it's considered
+ // an overflow and the size of the freelist is stored as the first element.
+ idx, count := 0, int(p.count)
+ if count == 0xFFFF {
+ idx = 1
+ count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0])
+ }
+
+ // Copy the list of page ids from the freelist.
+ if count == 0 {
+ f.ids = nil
+ } else {
+ ids := ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[idx:count]
+ f.ids = make([]pgid, len(ids))
+ copy(f.ids, ids)
+
+ // Make sure they're sorted.
+ sort.Sort(pgids(f.ids))
+ }
+
+ // Rebuild the page cache.
+ f.reindex()
+}
+
+// write writes the page ids onto a freelist page. All free and pending ids are
+// saved to disk since in the event of a program crash, all pending ids will
+// become free.
+func (f *freelist) write(p *page) error {
+ // Combine the old free pgids and pgids waiting on an open transaction.
+ ids := f.all()
+
+ // Update the header flag.
+ p.flags |= freelistPageFlag
+
+ // The page.count can only hold up to 64k elements so if we overflow that
+ // number then we handle it by putting the size in the first element.
+ if len(ids) == 0 {
+ p.count = uint16(len(ids))
+ } else if len(ids) < 0xFFFF {
+ p.count = uint16(len(ids))
+ copy(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[:], ids)
+ } else {
+ p.count = 0xFFFF
+ ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0] = pgid(len(ids))
+ copy(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[1:], ids)
+ }
+
+ return nil
+}
+
+// reload reads the freelist from a page and filters out pending items.
+func (f *freelist) reload(p *page) {
+ f.read(p)
+
+ // Build a cache of only pending pages.
+ pcache := make(map[pgid]bool)
+ for _, pendingIDs := range f.pending {
+ for _, pendingID := range pendingIDs {
+ pcache[pendingID] = true
+ }
+ }
+
+ // Check each page in the freelist and build a new available freelist
+ // with any pages not in the pending lists.
+ var a []pgid
+ for _, id := range f.ids {
+ if !pcache[id] {
+ a = append(a, id)
+ }
+ }
+ f.ids = a
+
+ // Once the available list is rebuilt then rebuild the free cache so that
+ // it includes the available and pending free pages.
+ f.reindex()
+}
+
+// reindex rebuilds the free cache based on available and pending free lists.
+func (f *freelist) reindex() {
+ f.cache = make(map[pgid]bool, len(f.ids))
+ for _, id := range f.ids {
+ f.cache[id] = true
+ }
+ for _, pendingIDs := range f.pending {
+ for _, pendingID := range pendingIDs {
+ f.cache[pendingID] = true
+ }
+ }
+}
diff --git a/vendor/github.com/boltdb/bolt/node.go b/vendor/github.com/boltdb/bolt/node.go
new file mode 100644
index 0000000..159318b
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/node.go
@@ -0,0 +1,604 @@
+package bolt
+
+import (
+ "bytes"
+ "fmt"
+ "sort"
+ "unsafe"
+)
+
+// node represents an in-memory, deserialized page.
+type node struct {
+ bucket *Bucket
+ isLeaf bool
+ unbalanced bool
+ spilled bool
+ key []byte
+ pgid pgid
+ parent *node
+ children nodes
+ inodes inodes
+}
+
+// root returns the top-level node this node is attached to.
+func (n *node) root() *node {
+ if n.parent == nil {
+ return n
+ }
+ return n.parent.root()
+}
+
+// minKeys returns the minimum number of inodes this node should have.
+func (n *node) minKeys() int {
+ if n.isLeaf {
+ return 1
+ }
+ return 2
+}
+
+// size returns the size of the node after serialization.
+func (n *node) size() int {
+ sz, elsz := pageHeaderSize, n.pageElementSize()
+ for i := 0; i < len(n.inodes); i++ {
+ item := &n.inodes[i]
+ sz += elsz + len(item.key) + len(item.value)
+ }
+ return sz
+}
+
+// sizeLessThan returns true if the node is less than a given size.
+// This is an optimization to avoid calculating a large node when we only need
+// to know if it fits inside a certain page size.
+func (n *node) sizeLessThan(v int) bool {
+ sz, elsz := pageHeaderSize, n.pageElementSize()
+ for i := 0; i < len(n.inodes); i++ {
+ item := &n.inodes[i]
+ sz += elsz + len(item.key) + len(item.value)
+ if sz >= v {
+ return false
+ }
+ }
+ return true
+}
+
+// pageElementSize returns the size of each page element based on the type of node.
+func (n *node) pageElementSize() int {
+ if n.isLeaf {
+ return leafPageElementSize
+ }
+ return branchPageElementSize
+}
+
+// childAt returns the child node at a given index.
+func (n *node) childAt(index int) *node {
+ if n.isLeaf {
+ panic(fmt.Sprintf("invalid childAt(%d) on a leaf node", index))
+ }
+ return n.bucket.node(n.inodes[index].pgid, n)
+}
+
+// childIndex returns the index of a given child node.
+func (n *node) childIndex(child *node) int {
+ index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, child.key) != -1 })
+ return index
+}
+
+// numChildren returns the number of children.
+func (n *node) numChildren() int {
+ return len(n.inodes)
+}
+
+// nextSibling returns the next node with the same parent.
+func (n *node) nextSibling() *node {
+ if n.parent == nil {
+ return nil
+ }
+ index := n.parent.childIndex(n)
+ if index >= n.parent.numChildren()-1 {
+ return nil
+ }
+ return n.parent.childAt(index + 1)
+}
+
+// prevSibling returns the previous node with the same parent.
+func (n *node) prevSibling() *node {
+ if n.parent == nil {
+ return nil
+ }
+ index := n.parent.childIndex(n)
+ if index == 0 {
+ return nil
+ }
+ return n.parent.childAt(index - 1)
+}
+
+// put inserts a key/value.
+func (n *node) put(oldKey, newKey, value []byte, pgid pgid, flags uint32) {
+ if pgid >= n.bucket.tx.meta.pgid {
+ panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", pgid, n.bucket.tx.meta.pgid))
+ } else if len(oldKey) <= 0 {
+ panic("put: zero-length old key")
+ } else if len(newKey) <= 0 {
+ panic("put: zero-length new key")
+ }
+
+ // Find insertion index.
+ index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, oldKey) != -1 })
+
+ // Add capacity and shift nodes if we don't have an exact match and need to insert.
+ exact := (len(n.inodes) > 0 && index < len(n.inodes) && bytes.Equal(n.inodes[index].key, oldKey))
+ if !exact {
+ n.inodes = append(n.inodes, inode{})
+ copy(n.inodes[index+1:], n.inodes[index:])
+ }
+
+ inode := &n.inodes[index]
+ inode.flags = flags
+ inode.key = newKey
+ inode.value = value
+ inode.pgid = pgid
+ _assert(len(inode.key) > 0, "put: zero-length inode key")
+}
+
+// del removes a key from the node.
+func (n *node) del(key []byte) {
+ // Find index of key.
+ index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 })
+
+ // Exit if the key isn't found.
+ if index >= len(n.inodes) || !bytes.Equal(n.inodes[index].key, key) {
+ return
+ }
+
+ // Delete inode from the node.
+ n.inodes = append(n.inodes[:index], n.inodes[index+1:]...)
+
+ // Mark the node as needing rebalancing.
+ n.unbalanced = true
+}
+
+// read initializes the node from a page.
+func (n *node) read(p *page) {
+ n.pgid = p.id
+ n.isLeaf = ((p.flags & leafPageFlag) != 0)
+ n.inodes = make(inodes, int(p.count))
+
+ for i := 0; i < int(p.count); i++ {
+ inode := &n.inodes[i]
+ if n.isLeaf {
+ elem := p.leafPageElement(uint16(i))
+ inode.flags = elem.flags
+ inode.key = elem.key()
+ inode.value = elem.value()
+ } else {
+ elem := p.branchPageElement(uint16(i))
+ inode.pgid = elem.pgid
+ inode.key = elem.key()
+ }
+ _assert(len(inode.key) > 0, "read: zero-length inode key")
+ }
+
+ // Save first key so we can find the node in the parent when we spill.
+ if len(n.inodes) > 0 {
+ n.key = n.inodes[0].key
+ _assert(len(n.key) > 0, "read: zero-length node key")
+ } else {
+ n.key = nil
+ }
+}
+
+// write writes the items onto one or more pages.
+func (n *node) write(p *page) {
+ // Initialize page.
+ if n.isLeaf {
+ p.flags |= leafPageFlag
+ } else {
+ p.flags |= branchPageFlag
+ }
+
+ if len(n.inodes) >= 0xFFFF {
+ panic(fmt.Sprintf("inode overflow: %d (pgid=%d)", len(n.inodes), p.id))
+ }
+ p.count = uint16(len(n.inodes))
+
+ // Stop here if there are no items to write.
+ if p.count == 0 {
+ return
+ }
+
+ // Loop over each item and write it to the page.
+ b := (*[maxAllocSize]byte)(unsafe.Pointer(&p.ptr))[n.pageElementSize()*len(n.inodes):]
+ for i, item := range n.inodes {
+ _assert(len(item.key) > 0, "write: zero-length inode key")
+
+ // Write the page element.
+ if n.isLeaf {
+ elem := p.leafPageElement(uint16(i))
+ elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem)))
+ elem.flags = item.flags
+ elem.ksize = uint32(len(item.key))
+ elem.vsize = uint32(len(item.value))
+ } else {
+ elem := p.branchPageElement(uint16(i))
+ elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem)))
+ elem.ksize = uint32(len(item.key))
+ elem.pgid = item.pgid
+ _assert(elem.pgid != p.id, "write: circular dependency occurred")
+ }
+
+ // If the length of key+value is larger than the max allocation size
+ // then we need to reallocate the byte array pointer.
+ //
+ // See: https://github.com/boltdb/bolt/pull/335
+ klen, vlen := len(item.key), len(item.value)
+ if len(b) < klen+vlen {
+ b = (*[maxAllocSize]byte)(unsafe.Pointer(&b[0]))[:]
+ }
+
+ // Write data for the element to the end of the page.
+ copy(b[0:], item.key)
+ b = b[klen:]
+ copy(b[0:], item.value)
+ b = b[vlen:]
+ }
+
+ // DEBUG ONLY: n.dump()
+}
+
+// split breaks up a node into multiple smaller nodes, if appropriate.
+// This should only be called from the spill() function.
+func (n *node) split(pageSize int) []*node {
+ var nodes []*node
+
+ node := n
+ for {
+ // Split node into two.
+ a, b := node.splitTwo(pageSize)
+ nodes = append(nodes, a)
+
+ // If we can't split then exit the loop.
+ if b == nil {
+ break
+ }
+
+ // Set node to b so it gets split on the next iteration.
+ node = b
+ }
+
+ return nodes
+}
+
+// splitTwo breaks up a node into two smaller nodes, if appropriate.
+// This should only be called from the split() function.
+func (n *node) splitTwo(pageSize int) (*node, *node) {
+ // Ignore the split if the page doesn't have at least enough nodes for
+ // two pages or if the nodes can fit in a single page.
+ if len(n.inodes) <= (minKeysPerPage*2) || n.sizeLessThan(pageSize) {
+ return n, nil
+ }
+
+ // Determine the threshold before starting a new node.
+ var fillPercent = n.bucket.FillPercent
+ if fillPercent < minFillPercent {
+ fillPercent = minFillPercent
+ } else if fillPercent > maxFillPercent {
+ fillPercent = maxFillPercent
+ }
+ threshold := int(float64(pageSize) * fillPercent)
+
+ // Determine split position and sizes of the two pages.
+ splitIndex, _ := n.splitIndex(threshold)
+
+ // Split node into two separate nodes.
+ // If there's no parent then we'll need to create one.
+ if n.parent == nil {
+ n.parent = &node{bucket: n.bucket, children: []*node{n}}
+ }
+
+ // Create a new node and add it to the parent.
+ next := &node{bucket: n.bucket, isLeaf: n.isLeaf, parent: n.parent}
+ n.parent.children = append(n.parent.children, next)
+
+ // Split inodes across two nodes.
+ next.inodes = n.inodes[splitIndex:]
+ n.inodes = n.inodes[:splitIndex]
+
+ // Update the statistics.
+ n.bucket.tx.stats.Split++
+
+ return n, next
+}
+
+// splitIndex finds the position where a page will fill a given threshold.
+// It returns the index as well as the size of the first page.
+// This is only be called from split().
+func (n *node) splitIndex(threshold int) (index, sz int) {
+ sz = pageHeaderSize
+
+ // Loop until we only have the minimum number of keys required for the second page.
+ for i := 0; i < len(n.inodes)-minKeysPerPage; i++ {
+ index = i
+ inode := n.inodes[i]
+ elsize := n.pageElementSize() + len(inode.key) + len(inode.value)
+
+ // If we have at least the minimum number of keys and adding another
+ // node would put us over the threshold then exit and return.
+ if i >= minKeysPerPage && sz+elsize > threshold {
+ break
+ }
+
+ // Add the element size to the total size.
+ sz += elsize
+ }
+
+ return
+}
+
+// spill writes the nodes to dirty pages and splits nodes as it goes.
+// Returns an error if dirty pages cannot be allocated.
+func (n *node) spill() error {
+ var tx = n.bucket.tx
+ if n.spilled {
+ return nil
+ }
+
+ // Spill child nodes first. Child nodes can materialize sibling nodes in
+ // the case of split-merge so we cannot use a range loop. We have to check
+ // the children size on every loop iteration.
+ sort.Sort(n.children)
+ for i := 0; i < len(n.children); i++ {
+ if err := n.children[i].spill(); err != nil {
+ return err
+ }
+ }
+
+ // We no longer need the child list because it's only used for spill tracking.
+ n.children = nil
+
+ // Split nodes into appropriate sizes. The first node will always be n.
+ var nodes = n.split(tx.db.pageSize)
+ for _, node := range nodes {
+ // Add node's page to the freelist if it's not new.
+ if node.pgid > 0 {
+ tx.db.freelist.free(tx.meta.txid, tx.page(node.pgid))
+ node.pgid = 0
+ }
+
+ // Allocate contiguous space for the node.
+ p, err := tx.allocate((node.size() / tx.db.pageSize) + 1)
+ if err != nil {
+ return err
+ }
+
+ // Write the node.
+ if p.id >= tx.meta.pgid {
+ panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", p.id, tx.meta.pgid))
+ }
+ node.pgid = p.id
+ node.write(p)
+ node.spilled = true
+
+ // Insert into parent inodes.
+ if node.parent != nil {
+ var key = node.key
+ if key == nil {
+ key = node.inodes[0].key
+ }
+
+ node.parent.put(key, node.inodes[0].key, nil, node.pgid, 0)
+ node.key = node.inodes[0].key
+ _assert(len(node.key) > 0, "spill: zero-length node key")
+ }
+
+ // Update the statistics.
+ tx.stats.Spill++
+ }
+
+ // If the root node split and created a new root then we need to spill that
+ // as well. We'll clear out the children to make sure it doesn't try to respill.
+ if n.parent != nil && n.parent.pgid == 0 {
+ n.children = nil
+ return n.parent.spill()
+ }
+
+ return nil
+}
+
+// rebalance attempts to combine the node with sibling nodes if the node fill
+// size is below a threshold or if there are not enough keys.
+func (n *node) rebalance() {
+ if !n.unbalanced {
+ return
+ }
+ n.unbalanced = false
+
+ // Update statistics.
+ n.bucket.tx.stats.Rebalance++
+
+ // Ignore if node is above threshold (25%) and has enough keys.
+ var threshold = n.bucket.tx.db.pageSize / 4
+ if n.size() > threshold && len(n.inodes) > n.minKeys() {
+ return
+ }
+
+ // Root node has special handling.
+ if n.parent == nil {
+ // If root node is a branch and only has one node then collapse it.
+ if !n.isLeaf && len(n.inodes) == 1 {
+ // Move root's child up.
+ child := n.bucket.node(n.inodes[0].pgid, n)
+ n.isLeaf = child.isLeaf
+ n.inodes = child.inodes[:]
+ n.children = child.children
+
+ // Reparent all child nodes being moved.
+ for _, inode := range n.inodes {
+ if child, ok := n.bucket.nodes[inode.pgid]; ok {
+ child.parent = n
+ }
+ }
+
+ // Remove old child.
+ child.parent = nil
+ delete(n.bucket.nodes, child.pgid)
+ child.free()
+ }
+
+ return
+ }
+
+ // If node has no keys then just remove it.
+ if n.numChildren() == 0 {
+ n.parent.del(n.key)
+ n.parent.removeChild(n)
+ delete(n.bucket.nodes, n.pgid)
+ n.free()
+ n.parent.rebalance()
+ return
+ }
+
+ _assert(n.parent.numChildren() > 1, "parent must have at least 2 children")
+
+ // Destination node is right sibling if idx == 0, otherwise left sibling.
+ var target *node
+ var useNextSibling = (n.parent.childIndex(n) == 0)
+ if useNextSibling {
+ target = n.nextSibling()
+ } else {
+ target = n.prevSibling()
+ }
+
+ // If both this node and the target node are too small then merge them.
+ if useNextSibling {
+ // Reparent all child nodes being moved.
+ for _, inode := range target.inodes {
+ if child, ok := n.bucket.nodes[inode.pgid]; ok {
+ child.parent.removeChild(child)
+ child.parent = n
+ child.parent.children = append(child.parent.children, child)
+ }
+ }
+
+ // Copy over inodes from target and remove target.
+ n.inodes = append(n.inodes, target.inodes...)
+ n.parent.del(target.key)
+ n.parent.removeChild(target)
+ delete(n.bucket.nodes, target.pgid)
+ target.free()
+ } else {
+ // Reparent all child nodes being moved.
+ for _, inode := range n.inodes {
+ if child, ok := n.bucket.nodes[inode.pgid]; ok {
+ child.parent.removeChild(child)
+ child.parent = target
+ child.parent.children = append(child.parent.children, child)
+ }
+ }
+
+ // Copy over inodes to target and remove node.
+ target.inodes = append(target.inodes, n.inodes...)
+ n.parent.del(n.key)
+ n.parent.removeChild(n)
+ delete(n.bucket.nodes, n.pgid)
+ n.free()
+ }
+
+ // Either this node or the target node was deleted from the parent so rebalance it.
+ n.parent.rebalance()
+}
+
+// removes a node from the list of in-memory children.
+// This does not affect the inodes.
+func (n *node) removeChild(target *node) {
+ for i, child := range n.children {
+ if child == target {
+ n.children = append(n.children[:i], n.children[i+1:]...)
+ return
+ }
+ }
+}
+
+// dereference causes the node to copy all its inode key/value references to heap memory.
+// This is required when the mmap is reallocated so inodes are not pointing to stale data.
+func (n *node) dereference() {
+ if n.key != nil {
+ key := make([]byte, len(n.key))
+ copy(key, n.key)
+ n.key = key
+ _assert(n.pgid == 0 || len(n.key) > 0, "dereference: zero-length node key on existing node")
+ }
+
+ for i := range n.inodes {
+ inode := &n.inodes[i]
+
+ key := make([]byte, len(inode.key))
+ copy(key, inode.key)
+ inode.key = key
+ _assert(len(inode.key) > 0, "dereference: zero-length inode key")
+
+ value := make([]byte, len(inode.value))
+ copy(value, inode.value)
+ inode.value = value
+ }
+
+ // Recursively dereference children.
+ for _, child := range n.children {
+ child.dereference()
+ }
+
+ // Update statistics.
+ n.bucket.tx.stats.NodeDeref++
+}
+
+// free adds the node's underlying page to the freelist.
+func (n *node) free() {
+ if n.pgid != 0 {
+ n.bucket.tx.db.freelist.free(n.bucket.tx.meta.txid, n.bucket.tx.page(n.pgid))
+ n.pgid = 0
+ }
+}
+
+// dump writes the contents of the node to STDERR for debugging purposes.
+/*
+func (n *node) dump() {
+ // Write node header.
+ var typ = "branch"
+ if n.isLeaf {
+ typ = "leaf"
+ }
+ warnf("[NODE %d {type=%s count=%d}]", n.pgid, typ, len(n.inodes))
+
+ // Write out abbreviated version of each item.
+ for _, item := range n.inodes {
+ if n.isLeaf {
+ if item.flags&bucketLeafFlag != 0 {
+ bucket := (*bucket)(unsafe.Pointer(&item.value[0]))
+ warnf("+L %08x -> (bucket root=%d)", trunc(item.key, 4), bucket.root)
+ } else {
+ warnf("+L %08x -> %08x", trunc(item.key, 4), trunc(item.value, 4))
+ }
+ } else {
+ warnf("+B %08x -> pgid=%d", trunc(item.key, 4), item.pgid)
+ }
+ }
+ warn("")
+}
+*/
+
+type nodes []*node
+
+func (s nodes) Len() int { return len(s) }
+func (s nodes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+func (s nodes) Less(i, j int) bool { return bytes.Compare(s[i].inodes[0].key, s[j].inodes[0].key) == -1 }
+
+// inode represents an internal node inside of a node.
+// It can be used to point to elements in a page or point
+// to an element which hasn't been added to a page yet.
+type inode struct {
+ flags uint32
+ pgid pgid
+ key []byte
+ value []byte
+}
+
+type inodes []inode
diff --git a/vendor/github.com/boltdb/bolt/page.go b/vendor/github.com/boltdb/bolt/page.go
new file mode 100644
index 0000000..7651a6b
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/page.go
@@ -0,0 +1,178 @@
+package bolt
+
+import (
+ "fmt"
+ "os"
+ "sort"
+ "unsafe"
+)
+
+const pageHeaderSize = int(unsafe.Offsetof(((*page)(nil)).ptr))
+
+const minKeysPerPage = 2
+
+const branchPageElementSize = int(unsafe.Sizeof(branchPageElement{}))
+const leafPageElementSize = int(unsafe.Sizeof(leafPageElement{}))
+
+const (
+ branchPageFlag = 0x01
+ leafPageFlag = 0x02
+ metaPageFlag = 0x04
+ freelistPageFlag = 0x10
+)
+
+const (
+ bucketLeafFlag = 0x01
+)
+
+type pgid uint64
+
+type page struct {
+ id pgid
+ flags uint16
+ count uint16
+ overflow uint32
+ ptr uintptr
+}
+
+// typ returns a human readable page type string used for debugging.
+func (p *page) typ() string {
+ if (p.flags & branchPageFlag) != 0 {
+ return "branch"
+ } else if (p.flags & leafPageFlag) != 0 {
+ return "leaf"
+ } else if (p.flags & metaPageFlag) != 0 {
+ return "meta"
+ } else if (p.flags & freelistPageFlag) != 0 {
+ return "freelist"
+ }
+ return fmt.Sprintf("unknown<%02x>", p.flags)
+}
+
+// meta returns a pointer to the metadata section of the page.
+func (p *page) meta() *meta {
+ return (*meta)(unsafe.Pointer(&p.ptr))
+}
+
+// leafPageElement retrieves the leaf node by index
+func (p *page) leafPageElement(index uint16) *leafPageElement {
+ n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index]
+ return n
+}
+
+// leafPageElements retrieves a list of leaf nodes.
+func (p *page) leafPageElements() []leafPageElement {
+ if p.count == 0 {
+ return nil
+ }
+ return ((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[:]
+}
+
+// branchPageElement retrieves the branch node by index
+func (p *page) branchPageElement(index uint16) *branchPageElement {
+ return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index]
+}
+
+// branchPageElements retrieves a list of branch nodes.
+func (p *page) branchPageElements() []branchPageElement {
+ if p.count == 0 {
+ return nil
+ }
+ return ((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[:]
+}
+
+// dump writes n bytes of the page to STDERR as hex output.
+func (p *page) hexdump(n int) {
+ buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:n]
+ fmt.Fprintf(os.Stderr, "%x\n", buf)
+}
+
+type pages []*page
+
+func (s pages) Len() int { return len(s) }
+func (s pages) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+func (s pages) Less(i, j int) bool { return s[i].id < s[j].id }
+
+// branchPageElement represents a node on a branch page.
+type branchPageElement struct {
+ pos uint32
+ ksize uint32
+ pgid pgid
+}
+
+// key returns a byte slice of the node key.
+func (n *branchPageElement) key() []byte {
+ buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
+ return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize]
+}
+
+// leafPageElement represents a node on a leaf page.
+type leafPageElement struct {
+ flags uint32
+ pos uint32
+ ksize uint32
+ vsize uint32
+}
+
+// key returns a byte slice of the node key.
+func (n *leafPageElement) key() []byte {
+ buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
+ return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize:n.ksize]
+}
+
+// value returns a byte slice of the node value.
+func (n *leafPageElement) value() []byte {
+ buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
+ return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos+n.ksize]))[:n.vsize:n.vsize]
+}
+
+// PageInfo represents human readable information about a page.
+type PageInfo struct {
+ ID int
+ Type string
+ Count int
+ OverflowCount int
+}
+
+type pgids []pgid
+
+func (s pgids) Len() int { return len(s) }
+func (s pgids) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+func (s pgids) Less(i, j int) bool { return s[i] < s[j] }
+
+// merge returns the sorted union of a and b.
+func (a pgids) merge(b pgids) pgids {
+ // Return the opposite slice if one is nil.
+ if len(a) == 0 {
+ return b
+ } else if len(b) == 0 {
+ return a
+ }
+
+ // Create a list to hold all elements from both lists.
+ merged := make(pgids, 0, len(a)+len(b))
+
+ // Assign lead to the slice with a lower starting value, follow to the higher value.
+ lead, follow := a, b
+ if b[0] < a[0] {
+ lead, follow = b, a
+ }
+
+ // Continue while there are elements in the lead.
+ for len(lead) > 0 {
+ // Merge largest prefix of lead that is ahead of follow[0].
+ n := sort.Search(len(lead), func(i int) bool { return lead[i] > follow[0] })
+ merged = append(merged, lead[:n]...)
+ if n >= len(lead) {
+ break
+ }
+
+ // Swap lead and follow.
+ lead, follow = follow, lead[n:]
+ }
+
+ // Append what's left in follow.
+ merged = append(merged, follow...)
+
+ return merged
+}
diff --git a/vendor/github.com/boltdb/bolt/tx.go b/vendor/github.com/boltdb/bolt/tx.go
new file mode 100644
index 0000000..1cfb4cd
--- /dev/null
+++ b/vendor/github.com/boltdb/bolt/tx.go
@@ -0,0 +1,682 @@
+package bolt
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "sort"
+ "strings"
+ "time"
+ "unsafe"
+)
+
+// txid represents the internal transaction identifier.
+type txid uint64
+
+// Tx represents a read-only or read/write transaction on the database.
+// Read-only transactions can be used for retrieving values for keys and creating cursors.
+// Read/write transactions can create and remove buckets and create and remove keys.
+//
+// IMPORTANT: You must commit or rollback transactions when you are done with
+// them. Pages can not be reclaimed by the writer until no more transactions
+// are using them. A long running read transaction can cause the database to
+// quickly grow.
+type Tx struct {
+ writable bool
+ managed bool
+ db *DB
+ meta *meta
+ root Bucket
+ pages map[pgid]*page
+ stats TxStats
+ commitHandlers []func()
+
+ // WriteFlag specifies the flag for write-related methods like WriteTo().
+ // Tx opens the database file with the specified flag to copy the data.
+ //
+ // By default, the flag is unset, which works well for mostly in-memory
+ // workloads. For databases that are much larger than available RAM,
+ // set the flag to syscall.O_DIRECT to avoid trashing the page cache.
+ WriteFlag int
+}
+
+// init initializes the transaction.
+func (tx *Tx) init(db *DB) {
+ tx.db = db
+ tx.pages = nil
+
+ // Copy the meta page since it can be changed by the writer.
+ tx.meta = &meta{}
+ db.meta().copy(tx.meta)
+
+ // Copy over the root bucket.
+ tx.root = newBucket(tx)
+ tx.root.bucket = &bucket{}
+ *tx.root.bucket = tx.meta.root
+
+ // Increment the transaction id and add a page cache for writable transactions.
+ if tx.writable {
+ tx.pages = make(map[pgid]*page)
+ tx.meta.txid += txid(1)
+ }
+}
+
+// ID returns the transaction id.
+func (tx *Tx) ID() int {
+ return int(tx.meta.txid)
+}
+
+// DB returns a reference to the database that created the transaction.
+func (tx *Tx) DB() *DB {
+ return tx.db
+}
+
+// Size returns current database size in bytes as seen by this transaction.
+func (tx *Tx) Size() int64 {
+ return int64(tx.meta.pgid) * int64(tx.db.pageSize)
+}
+
+// Writable returns whether the transaction can perform write operations.
+func (tx *Tx) Writable() bool {
+ return tx.writable
+}
+
+// Cursor creates a cursor associated with the root bucket.
+// All items in the cursor will return a nil value because all root bucket keys point to buckets.
+// The cursor is only valid as long as the transaction is open.
+// Do not use a cursor after the transaction is closed.
+func (tx *Tx) Cursor() *Cursor {
+ return tx.root.Cursor()
+}
+
+// Stats retrieves a copy of the current transaction statistics.
+func (tx *Tx) Stats() TxStats {
+ return tx.stats
+}
+
+// Bucket retrieves a bucket by name.
+// Returns nil if the bucket does not exist.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (tx *Tx) Bucket(name []byte) *Bucket {
+ return tx.root.Bucket(name)
+}
+
+// CreateBucket creates a new bucket.
+// Returns an error if the bucket already exists, if the bucket name is blank, or if the bucket name is too long.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) {
+ return tx.root.CreateBucket(name)
+}
+
+// CreateBucketIfNotExists creates a new bucket if it doesn't already exist.
+// Returns an error if the bucket name is blank, or if the bucket name is too long.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) {
+ return tx.root.CreateBucketIfNotExists(name)
+}
+
+// DeleteBucket deletes a bucket.
+// Returns an error if the bucket cannot be found or if the key represents a non-bucket value.
+func (tx *Tx) DeleteBucket(name []byte) error {
+ return tx.root.DeleteBucket(name)
+}
+
+// ForEach executes a function for each bucket in the root.
+// If the provided function returns an error then the iteration is stopped and
+// the error is returned to the caller.
+func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error {
+ return tx.root.ForEach(func(k, v []byte) error {
+ if err := fn(k, tx.root.Bucket(k)); err != nil {
+ return err
+ }
+ return nil
+ })
+}
+
+// OnCommit adds a handler function to be executed after the transaction successfully commits.
+func (tx *Tx) OnCommit(fn func()) {
+ tx.commitHandlers = append(tx.commitHandlers, fn)
+}
+
+// Commit writes all changes to disk and updates the meta page.
+// Returns an error if a disk write error occurs, or if Commit is
+// called on a read-only transaction.
+func (tx *Tx) Commit() error {
+ _assert(!tx.managed, "managed tx commit not allowed")
+ if tx.db == nil {
+ return ErrTxClosed
+ } else if !tx.writable {
+ return ErrTxNotWritable
+ }
+
+ // TODO(benbjohnson): Use vectorized I/O to write out dirty pages.
+
+ // Rebalance nodes which have had deletions.
+ var startTime = time.Now()
+ tx.root.rebalance()
+ if tx.stats.Rebalance > 0 {
+ tx.stats.RebalanceTime += time.Since(startTime)
+ }
+
+ // spill data onto dirty pages.
+ startTime = time.Now()
+ if err := tx.root.spill(); err != nil {
+ tx.rollback()
+ return err
+ }
+ tx.stats.SpillTime += time.Since(startTime)
+
+ // Free the old root bucket.
+ tx.meta.root.root = tx.root.root
+
+ opgid := tx.meta.pgid
+
+ // Free the freelist and allocate new pages for it. This will overestimate
+ // the size of the freelist but not underestimate the size (which would be bad).
+ tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist))
+ p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1)
+ if err != nil {
+ tx.rollback()
+ return err
+ }
+ if err := tx.db.freelist.write(p); err != nil {
+ tx.rollback()
+ return err
+ }
+ tx.meta.freelist = p.id
+
+ // If the high water mark has moved up then attempt to grow the database.
+ if tx.meta.pgid > opgid {
+ if err := tx.db.grow(int(tx.meta.pgid+1) * tx.db.pageSize); err != nil {
+ tx.rollback()
+ return err
+ }
+ }
+
+ // Write dirty pages to disk.
+ startTime = time.Now()
+ if err := tx.write(); err != nil {
+ tx.rollback()
+ return err
+ }
+
+ // If strict mode is enabled then perform a consistency check.
+ // Only the first consistency error is reported in the panic.
+ if tx.db.StrictMode {
+ ch := tx.Check()
+ var errs []string
+ for {
+ err, ok := <-ch
+ if !ok {
+ break
+ }
+ errs = append(errs, err.Error())
+ }
+ if len(errs) > 0 {
+ panic("check fail: " + strings.Join(errs, "\n"))
+ }
+ }
+
+ // Write meta to disk.
+ if err := tx.writeMeta(); err != nil {
+ tx.rollback()
+ return err
+ }
+ tx.stats.WriteTime += time.Since(startTime)
+
+ // Finalize the transaction.
+ tx.close()
+
+ // Execute commit handlers now that the locks have been removed.
+ for _, fn := range tx.commitHandlers {
+ fn()
+ }
+
+ return nil
+}
+
+// Rollback closes the transaction and ignores all previous updates. Read-only
+// transactions must be rolled back and not committed.
+func (tx *Tx) Rollback() error {
+ _assert(!tx.managed, "managed tx rollback not allowed")
+ if tx.db == nil {
+ return ErrTxClosed
+ }
+ tx.rollback()
+ return nil
+}
+
+func (tx *Tx) rollback() {
+ if tx.db == nil {
+ return
+ }
+ if tx.writable {
+ tx.db.freelist.rollback(tx.meta.txid)
+ tx.db.freelist.reload(tx.db.page(tx.db.meta().freelist))
+ }
+ tx.close()
+}
+
+func (tx *Tx) close() {
+ if tx.db == nil {
+ return
+ }
+ if tx.writable {
+ // Grab freelist stats.
+ var freelistFreeN = tx.db.freelist.free_count()
+ var freelistPendingN = tx.db.freelist.pending_count()
+ var freelistAlloc = tx.db.freelist.size()
+
+ // Remove transaction ref & writer lock.
+ tx.db.rwtx = nil
+ tx.db.rwlock.Unlock()
+
+ // Merge statistics.
+ tx.db.statlock.Lock()
+ tx.db.stats.FreePageN = freelistFreeN
+ tx.db.stats.PendingPageN = freelistPendingN
+ tx.db.stats.FreeAlloc = (freelistFreeN + freelistPendingN) * tx.db.pageSize
+ tx.db.stats.FreelistInuse = freelistAlloc
+ tx.db.stats.TxStats.add(&tx.stats)
+ tx.db.statlock.Unlock()
+ } else {
+ tx.db.removeTx(tx)
+ }
+
+ // Clear all references.
+ tx.db = nil
+ tx.meta = nil
+ tx.root = Bucket{tx: tx}
+ tx.pages = nil
+}
+
+// Copy writes the entire database to a writer.
+// This function exists for backwards compatibility. Use WriteTo() instead.
+func (tx *Tx) Copy(w io.Writer) error {
+ _, err := tx.WriteTo(w)
+ return err
+}
+
+// WriteTo writes the entire database to a writer.
+// If err == nil then exactly tx.Size() bytes will be written into the writer.
+func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) {
+ // Attempt to open reader with WriteFlag
+ f, err := os.OpenFile(tx.db.path, os.O_RDONLY|tx.WriteFlag, 0)
+ if err != nil {
+ return 0, err
+ }
+ defer func() { _ = f.Close() }()
+
+ // Generate a meta page. We use the same page data for both meta pages.
+ buf := make([]byte, tx.db.pageSize)
+ page := (*page)(unsafe.Pointer(&buf[0]))
+ page.flags = metaPageFlag
+ *page.meta() = *tx.meta
+
+ // Write meta 0.
+ page.id = 0
+ page.meta().checksum = page.meta().sum64()
+ nn, err := w.Write(buf)
+ n += int64(nn)
+ if err != nil {
+ return n, fmt.Errorf("meta 0 copy: %s", err)
+ }
+
+ // Write meta 1 with a lower transaction id.
+ page.id = 1
+ page.meta().txid -= 1
+ page.meta().checksum = page.meta().sum64()
+ nn, err = w.Write(buf)
+ n += int64(nn)
+ if err != nil {
+ return n, fmt.Errorf("meta 1 copy: %s", err)
+ }
+
+ // Move past the meta pages in the file.
+ if _, err := f.Seek(int64(tx.db.pageSize*2), os.SEEK_SET); err != nil {
+ return n, fmt.Errorf("seek: %s", err)
+ }
+
+ // Copy data pages.
+ wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2))
+ n += wn
+ if err != nil {
+ return n, err
+ }
+
+ return n, f.Close()
+}
+
+// CopyFile copies the entire database to file at the given path.
+// A reader transaction is maintained during the copy so it is safe to continue
+// using the database while a copy is in progress.
+func (tx *Tx) CopyFile(path string, mode os.FileMode) error {
+ f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
+ if err != nil {
+ return err
+ }
+
+ err = tx.Copy(f)
+ if err != nil {
+ _ = f.Close()
+ return err
+ }
+ return f.Close()
+}
+
+// Check performs several consistency checks on the database for this transaction.
+// An error is returned if any inconsistency is found.
+//
+// It can be safely run concurrently on a writable transaction. However, this
+// incurs a high cost for large databases and databases with a lot of subbuckets
+// because of caching. This overhead can be removed if running on a read-only
+// transaction, however, it is not safe to execute other writer transactions at
+// the same time.
+func (tx *Tx) Check() <-chan error {
+ ch := make(chan error)
+ go tx.check(ch)
+ return ch
+}
+
+func (tx *Tx) check(ch chan error) {
+ // Check if any pages are double freed.
+ freed := make(map[pgid]bool)
+ for _, id := range tx.db.freelist.all() {
+ if freed[id] {
+ ch <- fmt.Errorf("page %d: already freed", id)
+ }
+ freed[id] = true
+ }
+
+ // Track every reachable page.
+ reachable := make(map[pgid]*page)
+ reachable[0] = tx.page(0) // meta0
+ reachable[1] = tx.page(1) // meta1
+ for i := uint32(0); i <= tx.page(tx.meta.freelist).overflow; i++ {
+ reachable[tx.meta.freelist+pgid(i)] = tx.page(tx.meta.freelist)
+ }
+
+ // Recursively check buckets.
+ tx.checkBucket(&tx.root, reachable, freed, ch)
+
+ // Ensure all pages below high water mark are either reachable or freed.
+ for i := pgid(0); i < tx.meta.pgid; i++ {
+ _, isReachable := reachable[i]
+ if !isReachable && !freed[i] {
+ ch <- fmt.Errorf("page %d: unreachable unfreed", int(i))
+ }
+ }
+
+ // Close the channel to signal completion.
+ close(ch)
+}
+
+func (tx *Tx) checkBucket(b *Bucket, reachable map[pgid]*page, freed map[pgid]bool, ch chan error) {
+ // Ignore inline buckets.
+ if b.root == 0 {
+ return
+ }
+
+ // Check every page used by this bucket.
+ b.tx.forEachPage(b.root, 0, func(p *page, _ int) {
+ if p.id > tx.meta.pgid {
+ ch <- fmt.Errorf("page %d: out of bounds: %d", int(p.id), int(b.tx.meta.pgid))
+ }
+
+ // Ensure each page is only referenced once.
+ for i := pgid(0); i <= pgid(p.overflow); i++ {
+ var id = p.id + i
+ if _, ok := reachable[id]; ok {
+ ch <- fmt.Errorf("page %d: multiple references", int(id))
+ }
+ reachable[id] = p
+ }
+
+ // We should only encounter un-freed leaf and branch pages.
+ if freed[p.id] {
+ ch <- fmt.Errorf("page %d: reachable freed", int(p.id))
+ } else if (p.flags&branchPageFlag) == 0 && (p.flags&leafPageFlag) == 0 {
+ ch <- fmt.Errorf("page %d: invalid type: %s", int(p.id), p.typ())
+ }
+ })
+
+ // Check each bucket within this bucket.
+ _ = b.ForEach(func(k, v []byte) error {
+ if child := b.Bucket(k); child != nil {
+ tx.checkBucket(child, reachable, freed, ch)
+ }
+ return nil
+ })
+}
+
+// allocate returns a contiguous block of memory starting at a given page.
+func (tx *Tx) allocate(count int) (*page, error) {
+ p, err := tx.db.allocate(count)
+ if err != nil {
+ return nil, err
+ }
+
+ // Save to our page cache.
+ tx.pages[p.id] = p
+
+ // Update statistics.
+ tx.stats.PageCount++
+ tx.stats.PageAlloc += count * tx.db.pageSize
+
+ return p, nil
+}
+
+// write writes any dirty pages to disk.
+func (tx *Tx) write() error {
+ // Sort pages by id.
+ pages := make(pages, 0, len(tx.pages))
+ for _, p := range tx.pages {
+ pages = append(pages, p)
+ }
+ // Clear out page cache early.
+ tx.pages = make(map[pgid]*page)
+ sort.Sort(pages)
+
+ // Write pages to disk in order.
+ for _, p := range pages {
+ size := (int(p.overflow) + 1) * tx.db.pageSize
+ offset := int64(p.id) * int64(tx.db.pageSize)
+
+ // Write out page in "max allocation" sized chunks.
+ ptr := (*[maxAllocSize]byte)(unsafe.Pointer(p))
+ for {
+ // Limit our write to our max allocation size.
+ sz := size
+ if sz > maxAllocSize-1 {
+ sz = maxAllocSize - 1
+ }
+
+ // Write chunk to disk.
+ buf := ptr[:sz]
+ if _, err := tx.db.ops.writeAt(buf, offset); err != nil {
+ return err
+ }
+
+ // Update statistics.
+ tx.stats.Write++
+
+ // Exit inner for loop if we've written all the chunks.
+ size -= sz
+ if size == 0 {
+ break
+ }
+
+ // Otherwise move offset forward and move pointer to next chunk.
+ offset += int64(sz)
+ ptr = (*[maxAllocSize]byte)(unsafe.Pointer(&ptr[sz]))
+ }
+ }
+
+ // Ignore file sync if flag is set on DB.
+ if !tx.db.NoSync || IgnoreNoSync {
+ if err := fdatasync(tx.db); err != nil {
+ return err
+ }
+ }
+
+ // Put small pages back to page pool.
+ for _, p := range pages {
+ // Ignore page sizes over 1 page.
+ // These are allocated using make() instead of the page pool.
+ if int(p.overflow) != 0 {
+ continue
+ }
+
+ buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:tx.db.pageSize]
+
+ // See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1
+ for i := range buf {
+ buf[i] = 0
+ }
+ tx.db.pagePool.Put(buf)
+ }
+
+ return nil
+}
+
+// writeMeta writes the meta to the disk.
+func (tx *Tx) writeMeta() error {
+ // Create a temporary buffer for the meta page.
+ buf := make([]byte, tx.db.pageSize)
+ p := tx.db.pageInBuffer(buf, 0)
+ tx.meta.write(p)
+
+ // Write the meta page to file.
+ if _, err := tx.db.ops.writeAt(buf, int64(p.id)*int64(tx.db.pageSize)); err != nil {
+ return err
+ }
+ if !tx.db.NoSync || IgnoreNoSync {
+ if err := fdatasync(tx.db); err != nil {
+ return err
+ }
+ }
+
+ // Update statistics.
+ tx.stats.Write++
+
+ return nil
+}
+
+// page returns a reference to the page with a given id.
+// If page has been written to then a temporary buffered page is returned.
+func (tx *Tx) page(id pgid) *page {
+ // Check the dirty pages first.
+ if tx.pages != nil {
+ if p, ok := tx.pages[id]; ok {
+ return p
+ }
+ }
+
+ // Otherwise return directly from the mmap.
+ return tx.db.page(id)
+}
+
+// forEachPage iterates over every page within a given page and executes a function.
+func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) {
+ p := tx.page(pgid)
+
+ // Execute function.
+ fn(p, depth)
+
+ // Recursively loop over children.
+ if (p.flags & branchPageFlag) != 0 {
+ for i := 0; i < int(p.count); i++ {
+ elem := p.branchPageElement(uint16(i))
+ tx.forEachPage(elem.pgid, depth+1, fn)
+ }
+ }
+}
+
+// Page returns page information for a given page number.
+// This is only safe for concurrent use when used by a writable transaction.
+func (tx *Tx) Page(id int) (*PageInfo, error) {
+ if tx.db == nil {
+ return nil, ErrTxClosed
+ } else if pgid(id) >= tx.meta.pgid {
+ return nil, nil
+ }
+
+ // Build the page info.
+ p := tx.db.page(pgid(id))
+ info := &PageInfo{
+ ID: id,
+ Count: int(p.count),
+ OverflowCount: int(p.overflow),
+ }
+
+ // Determine the type (or if it's free).
+ if tx.db.freelist.freed(pgid(id)) {
+ info.Type = "free"
+ } else {
+ info.Type = p.typ()
+ }
+
+ return info, nil
+}
+
+// TxStats represents statistics about the actions performed by the transaction.
+type TxStats struct {
+ // Page statistics.
+ PageCount int // number of page allocations
+ PageAlloc int // total bytes allocated
+
+ // Cursor statistics.
+ CursorCount int // number of cursors created
+
+ // Node statistics
+ NodeCount int // number of node allocations
+ NodeDeref int // number of node dereferences
+
+ // Rebalance statistics.
+ Rebalance int // number of node rebalances
+ RebalanceTime time.Duration // total time spent rebalancing
+
+ // Split/Spill statistics.
+ Split int // number of nodes split
+ Spill int // number of nodes spilled
+ SpillTime time.Duration // total time spent spilling
+
+ // Write statistics.
+ Write int // number of writes performed
+ WriteTime time.Duration // total time spent writing to disk
+}
+
+func (s *TxStats) add(other *TxStats) {
+ s.PageCount += other.PageCount
+ s.PageAlloc += other.PageAlloc
+ s.CursorCount += other.CursorCount
+ s.NodeCount += other.NodeCount
+ s.NodeDeref += other.NodeDeref
+ s.Rebalance += other.Rebalance
+ s.RebalanceTime += other.RebalanceTime
+ s.Split += other.Split
+ s.Spill += other.Spill
+ s.SpillTime += other.SpillTime
+ s.Write += other.Write
+ s.WriteTime += other.WriteTime
+}
+
+// Sub calculates and returns the difference between two sets of transaction stats.
+// This is useful when obtaining stats at two different points and time and
+// you need the performance counters that occurred within that time span.
+func (s *TxStats) Sub(other *TxStats) TxStats {
+ var diff TxStats
+ diff.PageCount = s.PageCount - other.PageCount
+ diff.PageAlloc = s.PageAlloc - other.PageAlloc
+ diff.CursorCount = s.CursorCount - other.CursorCount
+ diff.NodeCount = s.NodeCount - other.NodeCount
+ diff.NodeDeref = s.NodeDeref - other.NodeDeref
+ diff.Rebalance = s.Rebalance - other.Rebalance
+ diff.RebalanceTime = s.RebalanceTime - other.RebalanceTime
+ diff.Split = s.Split - other.Split
+ diff.Spill = s.Spill - other.Spill
+ diff.SpillTime = s.SpillTime - other.SpillTime
+ diff.Write = s.Write - other.Write
+ diff.WriteTime = s.WriteTime - other.WriteTime
+ return diff
+}
diff --git a/vendor/github.com/bsphere/le_go/LICENSE b/vendor/github.com/bsphere/le_go/LICENSE
new file mode 100644
index 0000000..03f6677
--- /dev/null
+++ b/vendor/github.com/bsphere/le_go/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2017 Gal Ben-Haim
+
+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/bsphere/le_go/README.md b/vendor/github.com/bsphere/le_go/README.md
new file mode 100644
index 0000000..9d2ca9a
--- /dev/null
+++ b/vendor/github.com/bsphere/le_go/README.md
@@ -0,0 +1,37 @@
+le_go
+=====
+
+Golang client library for logentries.com
+
+It is compatible with http://golang.org/pkg/log/#Logger
+and also implements http://golang.org/pkg/io/#Writer
+
+[![GoDoc](https://godoc.org/github.com/bsphere/le_go?status.png)](https://godoc.org/github.com/bsphere/le_go)
+
+[![Build Status](https://travis-ci.org/bsphere/le_go.svg)](https://travis-ci.org/bsphere/le_go)
+
+Usage
+-----
+Add a new manual TCP token log at [logentries.com](https://logentries.com/quick-start/) and copy the [token](https://logentries.com/doc/input-token/).
+
+Installation: `go get github.com/bsphere/le_go`
+
+**Note:** The Logger is blocking, it can be easily run in a goroutine by calling `go le.Println(...)`
+
+```go
+package main
+
+import "github.com/bsphere/le_go"
+
+func main() {
+ le, err := le_go.Connect("XXXX-XXXX-XXXX-XXXX") // replace with token
+ if err != nil {
+ panic(err)
+ }
+
+ defer le.Close()
+
+ le.Println("another test message")
+}
+```
+
diff --git a/vendor/github.com/bsphere/le_go/le.go b/vendor/github.com/bsphere/le_go/le.go
new file mode 100644
index 0000000..553e4c7
--- /dev/null
+++ b/vendor/github.com/bsphere/le_go/le.go
@@ -0,0 +1,216 @@
+// Package le_go provides a Golang client library for logging to
+// logentries.com over a TCP connection.
+//
+// it uses an access token for sending log events.
+package le_go
+
+import (
+ "crypto/tls"
+ "fmt"
+ "net"
+ "os"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Logger represents a Logentries logger,
+// it holds the open TCP connection, access token, prefix and flags.
+//
+// all Logger operations are thread safe and blocking,
+// log operations can be invoked in a non-blocking way by calling them from
+// a goroutine.
+type Logger struct {
+ conn net.Conn
+ flag int
+ mu sync.Mutex
+ prefix string
+ token string
+ buf []byte
+}
+
+const lineSep = "\n"
+
+// Connect creates a new Logger instance and opens a TCP connection to
+// logentries.com,
+// The token can be generated at logentries.com by adding a new log,
+// choosing manual configuration and token based TCP connection.
+func Connect(token string) (*Logger, error) {
+ logger := Logger{
+ token: token,
+ }
+
+ if err := logger.openConnection(); err != nil {
+ return nil, err
+ }
+
+ return &logger, nil
+}
+
+// Close closes the TCP connection to logentries.com
+func (logger *Logger) Close() error {
+ if logger.conn != nil {
+ return logger.conn.Close()
+ }
+
+ return nil
+}
+
+// Opens a TCP connection to logentries.com
+func (logger *Logger) openConnection() error {
+ conn, err := tls.Dial("tcp", "data.logentries.com:443", &tls.Config{})
+ if err != nil {
+ return err
+ }
+ logger.conn = conn
+ return nil
+}
+
+// It returns if the TCP connection to logentries.com is open
+func (logger *Logger) isOpenConnection() bool {
+ if logger.conn == nil {
+ return false
+ }
+
+ buf := make([]byte, 1)
+
+ logger.conn.SetReadDeadline(time.Now())
+
+ _, err := logger.conn.Read(buf)
+
+ switch err.(type) {
+ case net.Error:
+ if err.(net.Error).Timeout() == true {
+ logger.conn.SetReadDeadline(time.Time{})
+
+ return true
+ }
+ }
+
+ return false
+}
+
+// It ensures that the TCP connection to logentries.com is open.
+// If the connection is closed, a new one is opened.
+func (logger *Logger) ensureOpenConnection() error {
+ if !logger.isOpenConnection() {
+ if err := logger.openConnection(); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+// Fatal is same as Print() but calls to os.Exit(1)
+func (logger *Logger) Fatal(v ...interface{}) {
+ logger.Output(2, fmt.Sprint(v...))
+ os.Exit(1)
+}
+
+// Fatalf is same as Printf() but calls to os.Exit(1)
+func (logger *Logger) Fatalf(format string, v ...interface{}) {
+ logger.Output(2, fmt.Sprintf(format, v...))
+ os.Exit(1)
+}
+
+// Fatalln is same as Println() but calls to os.Exit(1)
+func (logger *Logger) Fatalln(v ...interface{}) {
+ logger.Output(2, fmt.Sprintln(v...))
+ os.Exit(1)
+}
+
+// Flags returns the logger flags
+func (logger *Logger) Flags() int {
+ return logger.flag
+}
+
+// Output does the actual writing to the TCP connection
+func (logger *Logger) Output(calldepth int, s string) error {
+ _, err := logger.Write([]byte(s))
+
+ return err
+}
+
+// Panic is same as Print() but calls to panic
+func (logger *Logger) Panic(v ...interface{}) {
+ s := fmt.Sprint(v...)
+ logger.Output(2, s)
+ panic(s)
+}
+
+// Panicf is same as Printf() but calls to panic
+func (logger *Logger) Panicf(format string, v ...interface{}) {
+ s := fmt.Sprintf(format, v...)
+ logger.Output(2, s)
+ panic(s)
+}
+
+// Panicln is same as Println() but calls to panic
+func (logger *Logger) Panicln(v ...interface{}) {
+ s := fmt.Sprintln(v...)
+ logger.Output(2, s)
+ panic(s)
+}
+
+// Prefix returns the logger prefix
+func (logger *Logger) Prefix() string {
+ return logger.prefix
+}
+
+// Print logs a message
+func (logger *Logger) Print(v ...interface{}) {
+ logger.Output(2, fmt.Sprint(v...))
+}
+
+// Printf logs a formatted message
+func (logger *Logger) Printf(format string, v ...interface{}) {
+ logger.Output(2, fmt.Sprintf(format, v...))
+}
+
+// Println logs a message with a linebreak
+func (logger *Logger) Println(v ...interface{}) {
+ logger.Output(2, fmt.Sprintln(v...))
+}
+
+// SetFlags sets the logger flags
+func (logger *Logger) SetFlags(flag int) {
+ logger.flag = flag
+}
+
+// SetPrefix sets the logger prefix
+func (logger *Logger) SetPrefix(prefix string) {
+ logger.prefix = prefix
+}
+
+// Write writes a bytes array to the Logentries TCP connection,
+// it adds the access token and prefix and also replaces
+// line breaks with the unicode \u2028 character
+func (logger *Logger) Write(p []byte) (n int, err error) {
+ if err := logger.ensureOpenConnection(); err != nil {
+ return 0, err
+ }
+
+ logger.mu.Lock()
+ defer logger.mu.Unlock()
+
+ logger.makeBuf(p)
+
+ return logger.conn.Write(logger.buf)
+}
+
+// makeBuf constructs the logger buffer
+// it is not safe to be used from within multiple concurrent goroutines
+func (logger *Logger) makeBuf(p []byte) {
+ count := strings.Count(string(p), lineSep)
+ p = []byte(strings.Replace(string(p), lineSep, "\u2028", count-1))
+
+ logger.buf = logger.buf[:0]
+ logger.buf = append(logger.buf, (logger.token + " ")...)
+ logger.buf = append(logger.buf, (logger.prefix + " ")...)
+ logger.buf = append(logger.buf, p...)
+
+ if !strings.HasSuffix(string(logger.buf), lineSep) {
+ logger.buf = append(logger.buf, (lineSep)...)
+ }
+}
diff --git a/vendor/github.com/cloudflare/cfssl/LICENSE b/vendor/github.com/cloudflare/cfssl/LICENSE
new file mode 100644
index 0000000..bc5841f
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/LICENSE
@@ -0,0 +1,24 @@
+Copyright (c) 2014 CloudFlare Inc.
+
+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/cloudflare/cfssl/README.md b/vendor/github.com/cloudflare/cfssl/README.md
new file mode 100644
index 0000000..7285eee
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/README.md
@@ -0,0 +1,438 @@
+# CFSSL
+
+[![Build Status](https://travis-ci.org/cloudflare/cfssl.svg?branch=master)](https://travis-ci.org/cloudflare/cfssl)
+[![Coverage Status](http://codecov.io/github/cloudflare/cfssl/coverage.svg?branch=master)](http://codecov.io/github/cloudflare/cfssl?branch=master)
+[![GoDoc](https://godoc.org/github.com/cloudflare/cfssl?status.svg)](https://godoc.org/github.com/cloudflare/cfssl)
+
+## CloudFlare's PKI/TLS toolkit
+
+CFSSL is CloudFlare's PKI/TLS swiss army knife. It is both a command line
+tool and an HTTP API server for signing, verifying, and bundling TLS
+certificates. It requires Go 1.5+ to build.
+
+Note that certain linux distributions have certain algorithms removed
+(RHEL-based distributions in particular), so the golang from the
+official repositories will not work. Users of these distributions should
+[install go manually](//golang.org/dl) to install CFSSL.
+
+CFSSL consists of:
+
+* a set of packages useful for building custom TLS PKI tools
+* the `cfssl` program, which is the canonical command line utility
+ using the CFSSL packages.
+* the `multirootca` program, which is a certificate authority server
+ that can use multiple signing keys.
+* the `mkbundle` program is used to build certificate pool bundles.
+* the `cfssljson` program, which takes the JSON output from the
+ `cfssl` and `multirootca` programs and writes certificates, keys,
+ CSRs, and bundles to disk.
+
+### Building
+
+See [BUILDING](BUILDING.md)
+
+### Installation
+
+Installation requires a
+[working Go 1.5+ installation](http://golang.org/doc/install) and a
+properly set `GOPATH`.
+
+```
+$ go get -u github.com/cloudflare/cfssl/cmd/cfssl
+```
+
+will download and build the CFSSL tool, installing it in
+`$GOPATH/bin/cfssl`. To install the other utility programs that are in
+this repo:
+
+```
+$ go get -u github.com/cloudflare/cfssl/cmd/...
+```
+
+This will download, build, and install `cfssl`, `cfssljson`, and
+`mkbundle` into `$GOPATH/bin/`.
+
+Note that CFSSL makes use of vendored packages; in Go 1.5, the
+`GO15VENDOREXPERIMENT` environment variable will need to be set, e.g.
+
+```
+export GO15VENDOREXPERIMENT=1
+```
+
+In Go 1.6, this works out of the box.
+
+#### Installing pre-Go 1.5
+With a Go 1.4 or earlier installation, you won't be able to install the latest version of CFSSL. However, you can checkout the `1.1.0` release and build that.
+
+```
+git clone -b 1.1.0 https://github.com/cloudflare/cfssl.git $GOPATH/src/github.com/cloudflare/cfssl
+go get github.com/cloudflare/cfssl/cmd/cfssl
+```
+
+### Using the Command Line Tool
+
+The `cfssl` command line tool takes a command to specify what
+operation it should carry out:
+
+ sign signs a certificate
+ bundle build a certificate bundle
+ genkey generate a private key and a certificate request
+ gencert generate a private key and a certificate
+ serve start the API server
+ version prints out the current version
+ selfsign generates a self-signed certificate
+ print-defaults print default configurations
+
+Use "cfssl [command] -help" to find out more about a command.
+The version command takes no arguments.
+
+#### Signing
+
+```
+cfssl sign [-ca cert] [-ca-key key] [-hostname comma,separated,hostnames] csr [subject]
+```
+
+The csr is the client's certificate request. The `-ca` and `-ca-key`
+flags are the CA's certificate and private key, respectively. By
+default, they are "ca.pem" and "ca_key.pem". The `-hostname` is
+a comma separated hostname list that overrides the DNS names and
+IP address in the certificate SAN extension.
+For example, assuming the CA's private key is in
+`/etc/ssl/private/cfssl_key.pem` and the CA's certificate is in
+`/etc/ssl/certs/cfssl.pem`, to sign the `cloudflare.pem` certificate
+for cloudflare.com:
+
+```
+cfssl sign -ca /etc/ssl/certs/cfssl.pem \
+ -ca-key /etc/ssl/private/cfssl_key.pem \
+ -hostname cloudflare.com ./cloudflare.pem
+```
+
+It is also possible to specify csr through '-csr' flag. By doing so,
+flag values take precedence and will overwrite the argument.
+
+The subject is an optional file that contains subject information that
+should be used in place of the information from the CSR. It should be
+a JSON file with the type:
+
+```json
+{
+ "CN": "example.com",
+ "names": [
+ {
+ "C": "US",
+ "L": "San Francisco",
+ "O": "Internet Widgets, Inc.",
+ "OU": "WWW",
+ "ST": "California"
+ }
+ ]
+}
+```
+
+#### Bundling
+
+```
+cfssl bundle [-ca-bundle bundle] [-int-bundle bundle] \
+ [-metadata metadata_file] [-flavor bundle_flavor] \
+ -cert certificate_file [-key key_file]
+```
+
+The bundles are used for the root and intermediate certificate
+pools. In addition, platform metadata is specified through '-metadata'
+The bundle files, metadata file (and auxiliary files) can be
+found at [cfssl_trust](https://github.com/cloudflare/cfssl_trust)
+
+
+Specify PEM-encoded client certificate and key through '-cert' and
+'-key' respectively. If key is specified, the bundle will be built
+and verified with the key. Otherwise the bundle will be built
+without a private key. Instead of file path, use '-' for reading
+certificate PEM from stdin. It is also acceptable the certificate
+file contains a (partial) certificate bundle.
+
+Specify bundling flavor through '-flavor'. There are three flavors:
+'optimal' to generate a bundle of shortest chain and most advanced
+cryptographic algorithms, 'ubiquitous' to generate a bundle of most
+widely acceptance across different browsers and OS platforms, and
+'force' to find an acceptable bundle which is identical to the
+content of the input certificate file.
+
+Alternatively, the client certificate can be pulled directly from
+a domain. It is also possible to connect to the remote address
+through '-ip'.
+
+```
+cfssl bundle [-ca-bundle bundle] [-int-bundle bundle] \
+ [-metadata metadata_file] [-flavor bundle_flavor] \
+ -domain domain_name [-ip ip_address]
+```
+
+The bundle output form should follow the example
+
+```json
+{
+ "bundle": "CERT_BUNDLE_IN_PEM",
+ "crt": "LEAF_CERT_IN_PEM",
+ "crl_support": true,
+ "expires": "2015-12-31T23:59:59Z",
+ "hostnames": ["example.com"],
+ "issuer": "ISSUER CERT SUBJECT",
+ "key": "KEY_IN_PEM",
+ "key_size": 2048,
+ "key_type": "2048-bit RSA",
+ "ocsp": ["http://ocsp.example-ca.com"],
+ "ocsp_support": true,
+ "root": "ROOT_CA_CERT_IN_PEM",
+ "signature": "SHA1WithRSA",
+ "subject": "LEAF CERT SUBJECT",
+ "status": {
+ "rebundled": false,
+ "expiring_SKIs": [],
+ "untrusted_root_stores": [],
+ "messages": [],
+ "code": 0
+ }
+}
+```
+
+
+#### Generating certificate signing request and private key
+
+```
+cfssl genkey csr.json
+```
+
+To generate a private key and corresponding certificate request, specify
+the key request as a JSON file. This file should follow the form
+
+```json
+{
+ "hosts": [
+ "example.com",
+ "www.example.com"
+ ],
+ "key": {
+ "algo": "rsa",
+ "size": 2048
+ },
+ "names": [
+ {
+ "C": "US",
+ "L": "San Francisco",
+ "O": "Internet Widgets, Inc.",
+ "OU": "WWW",
+ "ST": "California"
+ }
+ ]
+}
+```
+
+#### Generating self-signed root CA certificate and private key
+
+```
+cfssl genkey -initca csr.json | cfssljson -bare ca
+```
+
+To generate a self-signed root CA certificate, specify the key request as
+the JSON file in the same format as in 'genkey'. Three PEM-encoded entities
+will appear in the output: the private key, the csr, and the self-signed
+certificate.
+
+#### Generating a remote-issued certificate and private key.
+
+```
+cfssl gencert -remote=remote_server [-hostname=comma,separated,hostnames] csr.json
+```
+
+This is calls genkey, but has a remote CFSSL server sign and issue
+a certificate. You may use `-hostname` to override certificate SANs.
+
+#### Generating a local-issued certificate and private key.
+
+```
+cfssl gencert -ca cert -ca-key key [-hostname=comma,separated,hostnames] csr.json
+```
+
+This is generates and issues a certificate and private key from a local CA
+via a JSON request. You may use `-hostname` to override certificate SANs.
+
+
+#### Updating a OCSP responses file with a newly issued certificate
+
+```
+cfssl ocspsign -ca cert -responder key -responder-key key -cert cert \
+ | cfssljson -bare -stdout >> responses
+```
+
+This will generate a OCSP response for the `cert` and add it to the
+`responses` file. You can then pass `responses` to `ocspserve` to start a
+OCSP server.
+
+### Starting the API Server
+
+CFSSL comes with an HTTP-based API server; the endpoints are
+documented in `doc/api.txt`. The server is started with the "serve"
+command:
+
+```
+cfssl serve [-address address] [-ca cert] [-ca-bundle bundle] \
+ [-ca-key key] [-int-bundle bundle] [-int-dir dir] [-port port] \
+ [-metadata file] [-remote remote_host] [-config config] \
+ [-responder cert] [-responder-key key] [-db-config db-config]
+```
+
+Address and port default to "127.0.0.1:8888". The `-ca` and `-ca-key`
+arguments should be the PEM-encoded certificate and private key to use
+for signing; by default, they are "ca.pem" and "ca_key.pem". The
+`-ca-bundle` and `-int-bundle` should be the certificate bundles used
+for the root and intermediate certificate pools, respectively. These
+default to "ca-bundle.crt" and "int-bundle." If the "remote" option is
+provided, all signature operations will be forwarded to the remote CFSSL.
+
+'-int-dir' specifies intermediates directory. '-metadata' is a file for
+root certificate presence. The content of the file is a json dictionary
+(k,v): each key k is SHA-1 digest of a root certificate while value v
+is a list of key store filenames. '-config' specifies path to configuration
+file. '-responder' and '-responder-key' are Certificate for OCSP responder
+and private key for OCSP responder certificate, respectively.
+
+The amount of logging can be controlled with the `-loglevel` option. This
+comes *after* the serve command:
+
+```
+cfssl serve -loglevel 2
+```
+
+The levels are:
+
+* 0. DEBUG
+* 1. INFO (this is the default level)
+* 2. WARNING
+* 3. ERROR
+* 4. CRITICAL
+
+### The multirootca
+
+The `cfssl` program can act as an online certificate authority, but it
+only uses a single key. If multiple signing keys are needed, the
+`multirootca` program can be used. It only provides the sign,
+authsign, and info endpoints. The documentation contains instructions
+for configuring and running the CA.
+
+### The mkbundle Utility
+
+`mkbundle` is used to build the root and intermediate bundles used in
+verifying certificates. It can be installed with
+
+```
+go get -u github.com/cloudflare/cfssl/cmd/mkbundle
+```
+
+It takes a collection of certificates, checks for CRL revocation (OCSP
+support is planned for the next release) and expired certificates, and
+bundles them into one file. It takes directories of certificates and
+certificate files (which may contain multiple certificates). For example,
+if the directory `intermediates` contains a number of intermediate
+certificates,
+
+```
+mkbundle -f int-bundle.crt intermediates
+```
+
+will check those certificates and combine valid ones into a single
+`int-bundle.crt` file.
+
+The `-f` flag specifies an output name; `-loglevel` specifies the verbosity
+of the logging (using the same loglevels above), and `-nw` controls the
+number of revocation-checking workers.
+
+### The cfssljson Utility
+
+Most of the output from `cfssl` is in JSON. The `cfssljson` will take
+this output and split it out into separate key, certificate, CSR, and
+bundle files as appropriate. The tool takes a single flag, `-f`, that
+specifies the input file, and an argument that specifies the base name for
+the files produced. If the input filename is "-" (which is the default),
+`cfssljson` reads from standard input. It maps keys in the JSON file to
+filenames in the following way:
+
+* if there is a "cert" (or if not, if there's a "certificate") field, the
+ file "basename.pem" will be produced.
+* if there is a "key" (or if not, if there's a "private_key") field, the
+ file "basename-key.pem" will be produced.
+* if there is a "csr" (or if not, if there's a "certificate_request") field,
+ the file "basename.csr" will be produced.
+* if there is a "bundle" field, the file "basename-bundle.pem" will
+ be produced.
+* if there is a "ocspResponse" field, the file "basename-response.der" will
+ be produced.
+
+Instead of saving to a file, you can pass `-stdout` to output the encoded
+contents.
+
+### Static Builds
+
+By default, the web assets are accessed from disk, based on their
+relative locations. If you’re wishing to distribute a single,
+statically-linked, cfssl binary, you’ll want to embed these resources
+before building. This can by done with the
+[go.rice](https://github.com/GeertJohan/go.rice) tool.
+
+```
+pushd cli/serve && rice embed-go && popd
+```
+
+Then building with `go build` will use the embedded resources.
+
+### Using a PKCS#11 hardware token / HSM
+
+For better security, you may want to store your private key in an HSM or
+smartcard. The interface to both of these categories of device is described by
+the PKCS#11 spec. If you need to do approximately one signing operation per
+second or fewer, the Yubikey NEO and NEO-n are inexpensive smartcard options:
+https://www.yubico.com/products/yubikey-hardware/yubikey-neo/. In general you
+are looking for a product that supports PIV (personal identity verification). If
+your signing needs are in the hundreds of signatures per second, you will need
+to purchase an expensive HSM (in the thousands to many thousands of USD).
+
+If you want to try out the PKCS#11 signing modes without a hardware token, you
+can use the [SoftHSM](https://github.com/opendnssec/SoftHSMv1#softhsm)
+implementation. Please note that using SoftHSM simply stores your private key in
+a file on disk and does not increase security.
+
+To get started with your PKCS#11 token you will need to initialize it with a
+private key, PIN, and token label. The instructions to do this will be specific
+to each hardware device, and you should follow the instructions provided by your
+vendor. You will also need to find the path to your 'module', a shared object
+file (.so). Having initialized your device, you can query it to check your token
+label with:
+
+ pkcs11-tool --module <module path> --list-token-slots
+
+You'll also want to check the label of the private key you imported (or
+generated). Run the following command and look for a 'Private Key Object':
+
+ pkcs11-tool --module <module path> --pin <pin> \
+ --list-token-slots --login --list-objects
+
+You now have all the information you need to use your PKCS#11 token with CFSSL.
+CFSSL supports PKCS#11 for certificate signing and OCSP signing. To create a
+Signer (for certificate signing), import `signer/universal` and call NewSigner
+with a Root object containing the module, pin, token label and private label
+from above, plus a path to your certificate. The structure of the Root object is
+documented in universal.go.
+
+Alternately, you can construct a pkcs11key.Key or pkcs11key.Pool yourself, and
+pass it to ocsp.NewSigner (for OCSP) or local.NewSigner (for certificate
+signing). This will be necessary, for example, if you are using a single-session
+token like the Yubikey and need both OCSP signing and certificate signing at the
+same time.
+
+### Additional Documentation
+
+Additional documentation can be found in the "doc/" directory:
+
+* `api.txt`: documents the API endpoints
+* `bootstrap.txt`: a walkthrough from building the package to getting
+ up and running
diff --git a/vendor/github.com/cloudflare/cfssl/api/api.go b/vendor/github.com/cloudflare/cfssl/api/api.go
new file mode 100644
index 0000000..f1040ca
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/api/api.go
@@ -0,0 +1,231 @@
+// Package api implements an HTTP-based API and server for CFSSL.
+package api
+
+import (
+ "encoding/json"
+ "io/ioutil"
+ "net/http"
+
+ "github.com/cloudflare/cfssl/errors"
+ "github.com/cloudflare/cfssl/log"
+)
+
+// Handler is an interface providing a generic mechanism for handling HTTP requests.
+type Handler interface {
+ Handle(w http.ResponseWriter, r *http.Request) error
+}
+
+// HTTPHandler is a wrapper that encapsulates Handler interface as http.Handler.
+// HTTPHandler also enforces that the Handler only responds to requests with registered HTTP methods.
+type HTTPHandler struct {
+ Handler // CFSSL handler
+ Methods []string // The associated HTTP methods
+}
+
+// HandlerFunc is similar to the http.HandlerFunc type; it serves as
+// an adapter allowing the use of ordinary functions as Handlers. If
+// f is a function with the appropriate signature, HandlerFunc(f) is a
+// Handler object that calls f.
+type HandlerFunc func(http.ResponseWriter, *http.Request) error
+
+// Handle calls f(w, r)
+func (f HandlerFunc) Handle(w http.ResponseWriter, r *http.Request) error {
+ w.Header().Set("Content-Type", "application/json")
+ return f(w, r)
+}
+
+// handleError is the centralised error handling and reporting.
+func handleError(w http.ResponseWriter, err error) (code int) {
+ if err == nil {
+ return http.StatusOK
+ }
+ msg := err.Error()
+ httpCode := http.StatusInternalServerError
+
+ // If it is recognized as HttpError emitted from cfssl,
+ // we rewrite the status code accordingly. If it is a
+ // cfssl error, set the http status to StatusBadRequest
+ switch err := err.(type) {
+ case *errors.HTTPError:
+ httpCode = err.StatusCode
+ code = err.StatusCode
+ case *errors.Error:
+ httpCode = http.StatusBadRequest
+ code = err.ErrorCode
+ msg = err.Message
+ }
+
+ response := NewErrorResponse(msg, code)
+ jsonMessage, err := json.Marshal(response)
+ if err != nil {
+ log.Errorf("Failed to marshal JSON: %v", err)
+ } else {
+ msg = string(jsonMessage)
+ }
+ http.Error(w, msg, httpCode)
+ return code
+}
+
+// ServeHTTP encapsulates the call to underlying Handler to handle the request
+// and return the response with proper HTTP status code
+func (h HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ var err error
+ var match bool
+ // Throw 405 when requested with an unsupported verb.
+ for _, m := range h.Methods {
+ if m == r.Method {
+ match = true
+ }
+ }
+ if match {
+ err = h.Handle(w, r)
+ } else {
+ err = errors.NewMethodNotAllowed(r.Method)
+ }
+ status := handleError(w, err)
+ log.Infof("%s - \"%s %s\" %d", r.RemoteAddr, r.Method, r.URL, status)
+}
+
+// readRequestBlob takes a JSON-blob-encoded response body in the form
+// map[string]string and returns it, the list of keywords presented,
+// and any error that occurred.
+func readRequestBlob(r *http.Request) (map[string]string, error) {
+ var blob map[string]string
+
+ body, err := ioutil.ReadAll(r.Body)
+ if err != nil {
+ return nil, err
+ }
+ r.Body.Close()
+
+ err = json.Unmarshal(body, &blob)
+ if err != nil {
+ return nil, err
+ }
+ return blob, nil
+}
+
+// ProcessRequestOneOf reads a JSON blob for the request and makes
+// sure it contains one of a set of keywords. For example, a request
+// might have the ('foo' && 'bar') keys, OR it might have the 'baz'
+// key. In either case, we want to accept the request; however, if
+// none of these sets shows up, the request is a bad request, and it
+// should be returned.
+func ProcessRequestOneOf(r *http.Request, keywordSets [][]string) (map[string]string, []string, error) {
+ blob, err := readRequestBlob(r)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ var matched []string
+ for _, set := range keywordSets {
+ if matchKeywords(blob, set) {
+ if matched != nil {
+ return nil, nil, errors.NewBadRequestString("mismatched parameters")
+ }
+ matched = set
+ }
+ }
+ if matched == nil {
+ return nil, nil, errors.NewBadRequestString("no valid parameter sets found")
+ }
+ return blob, matched, nil
+}
+
+// ProcessRequestFirstMatchOf reads a JSON blob for the request and returns
+// the first match of a set of keywords. For example, a request
+// might have one of the following combinations: (foo=1, bar=2), (foo=1), and (bar=2)
+// By giving a specific ordering of those combinations, we could decide how to accept
+// the request.
+func ProcessRequestFirstMatchOf(r *http.Request, keywordSets [][]string) (map[string]string, []string, error) {
+ blob, err := readRequestBlob(r)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ for _, set := range keywordSets {
+ if matchKeywords(blob, set) {
+ return blob, set, nil
+ }
+ }
+ return nil, nil, errors.NewBadRequestString("no valid parameter sets found")
+}
+
+func matchKeywords(blob map[string]string, keywords []string) bool {
+ for _, keyword := range keywords {
+ if _, ok := blob[keyword]; !ok {
+ return false
+ }
+ }
+ return true
+}
+
+// ResponseMessage implements the standard for response errors and
+// messages. A message has a code and a string message.
+type ResponseMessage struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+}
+
+// Response implements the CloudFlare standard for API
+// responses.
+type Response struct {
+ Success bool `json:"success"`
+ Result interface{} `json:"result"`
+ Errors []ResponseMessage `json:"errors"`
+ Messages []ResponseMessage `json:"messages"`
+}
+
+// NewSuccessResponse is a shortcut for creating new successul API
+// responses.
+func NewSuccessResponse(result interface{}) Response {
+ return Response{
+ Success: true,
+ Result: result,
+ Errors: []ResponseMessage{},
+ Messages: []ResponseMessage{},
+ }
+}
+
+// NewSuccessResponseWithMessage is a shortcut for creating new successul API
+// responses that includes a message.
+func NewSuccessResponseWithMessage(result interface{}, message string, code int) Response {
+ return Response{
+ Success: true,
+ Result: result,
+ Errors: []ResponseMessage{},
+ Messages: []ResponseMessage{{code, message}},
+ }
+}
+
+// NewErrorResponse is a shortcut for creating an error response for a
+// single error.
+func NewErrorResponse(message string, code int) Response {
+ return Response{
+ Success: false,
+ Result: nil,
+ Errors: []ResponseMessage{{code, message}},
+ Messages: []ResponseMessage{},
+ }
+}
+
+// SendResponse builds a response from the result, sets the JSON
+// header, and writes to the http.ResponseWriter.
+func SendResponse(w http.ResponseWriter, result interface{}) error {
+ response := NewSuccessResponse(result)
+ w.Header().Set("Content-Type", "application/json")
+ enc := json.NewEncoder(w)
+ err := enc.Encode(response)
+ return err
+}
+
+// SendResponseWithMessage builds a response from the result and the
+// provided message, sets the JSON header, and writes to the
+// http.ResponseWriter.
+func SendResponseWithMessage(w http.ResponseWriter, result interface{}, message string, code int) error {
+ response := NewSuccessResponseWithMessage(result, message, code)
+ w.Header().Set("Content-Type", "application/json")
+ enc := json.NewEncoder(w)
+ err := enc.Encode(response)
+ return err
+}
diff --git a/vendor/github.com/cloudflare/cfssl/auth/auth.go b/vendor/github.com/cloudflare/cfssl/auth/auth.go
new file mode 100644
index 0000000..ecd5e5f
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/auth/auth.go
@@ -0,0 +1,94 @@
+// Package auth implements an interface for providing CFSSL
+// authentication. This is meant to authenticate a client CFSSL to a
+// remote CFSSL in order to prevent unauthorised use of the signature
+// capabilities. This package provides both the interface and a
+// standard HMAC-based implementation.
+package auth
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "strings"
+)
+
+// An AuthenticatedRequest contains a request and authentication
+// token. The Provider may determine whether to validate the timestamp
+// and remote address.
+type AuthenticatedRequest struct {
+ // An Authenticator decides whether to use this field.
+ Timestamp int64 `json:"timestamp,omitempty"`
+ RemoteAddress []byte `json:"remote_address,omitempty"`
+ Token []byte `json:"token"`
+ Request []byte `json:"request"`
+}
+
+// A Provider can generate tokens from a request and verify a
+// request. The handling of additional authentication data (such as
+// the IP address) is handled by the concrete type, as is any
+// serialisation and state-keeping.
+type Provider interface {
+ Token(req []byte) (token []byte, err error)
+ Verify(aReq *AuthenticatedRequest) bool
+}
+
+// Standard implements an HMAC-SHA-256 authentication provider. It may
+// be supplied additional data at creation time that will be used as
+// request || additional-data with the HMAC.
+type Standard struct {
+ key []byte
+ ad []byte
+}
+
+// New generates a new standard authentication provider from the key
+// and additional data. The additional data will be used when
+// generating a new token.
+func New(key string, ad []byte) (*Standard, error) {
+ if splitKey := strings.SplitN(key, ":", 2); len(splitKey) == 2 {
+ switch splitKey[0] {
+ case "env":
+ key = os.Getenv(splitKey[1])
+ case "file":
+ data, err := ioutil.ReadFile(splitKey[1])
+ if err != nil {
+ return nil, err
+ }
+ key = string(data)
+ default:
+ return nil, fmt.Errorf("unknown key prefix: %s", splitKey[0])
+ }
+ }
+
+ keyBytes, err := hex.DecodeString(key)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Standard{keyBytes, ad}, nil
+}
+
+// Token generates a new authentication token from the request.
+func (p Standard) Token(req []byte) (token []byte, err error) {
+ h := hmac.New(sha256.New, p.key)
+ h.Write(req)
+ h.Write(p.ad)
+ return h.Sum(nil), nil
+}
+
+// Verify determines whether an authenticated request is valid.
+func (p Standard) Verify(ad *AuthenticatedRequest) bool {
+ if ad == nil {
+ return false
+ }
+
+ // Standard token generation returns no error.
+ token, _ := p.Token(ad.Request)
+ if len(ad.Token) != len(token) {
+ return false
+ }
+
+ return hmac.Equal(token, ad.Token)
+}
diff --git a/vendor/github.com/cloudflare/cfssl/certdb/README.md b/vendor/github.com/cloudflare/cfssl/certdb/README.md
new file mode 100644
index 0000000..fbd941e
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/certdb/README.md
@@ -0,0 +1,75 @@
+# certdb usage
+
+Using a database enables additional functionality for existing commands when a
+db config is provided:
+
+ - `sign` and `gencert` add a certificate to the certdb after signing it
+ - `serve` enables database functionality for the sign and revoke endpoints
+
+A database is required for the following:
+
+ - `revoke` marks certificates revoked in the database with an optional reason
+ - `ocsprefresh` refreshes the table of cached OCSP responses
+ - `ocspdump` outputs cached OCSP responses in a concatenated base64-encoded format
+
+## Setup/Migration
+
+This directory stores [goose](https://bitbucket.org/liamstask/goose/) db migration scripts for various DB backends.
+Currently supported:
+ - MySQL in mysql
+ - PostgreSQL in pg
+ - SQLite in sqlite
+
+### Get goose
+
+ go get bitbucket.org/liamstask/goose/cmd/goose
+
+### Use goose to start and terminate a MySQL DB
+To start a MySQL using goose:
+
+ goose -path $GOPATH/src/github.com/cloudflare/cfssl/certdb/mysql up
+
+To tear down a MySQL DB using goose
+
+ goose -path $GOPATH/src/github.com/cloudflare/cfssl/certdb/mysql down
+
+Note: the administration of MySQL DB is not included. We assume
+the databases being connected to are already created and access control
+is properly handled.
+
+### Use goose to start and terminate a PostgreSQL DB
+To start a PostgreSQL using goose:
+
+ goose -path $GOPATH/src/github.com/cloudflare/cfssl/certdb/pg up
+
+To tear down a PostgreSQL DB using goose
+
+ goose -path $GOPATH/src/github.com/cloudflare/cfssl/certdb/pg down
+
+Note: the administration of PostgreSQL DB is not included. We assume
+the databases being connected to are already created and access control
+is properly handled.
+
+### Use goose to start and terminate a SQLite DB
+To start a SQLite DB using goose:
+
+ goose -path $GOPATH/src/github.com/cloudflare/cfssl/certdb/sqlite up
+
+To tear down a SQLite DB using goose
+
+ goose -path $GOPATH/src/github.com/cloudflare/cfssl/certdb/sqlite down
+
+## CFSSL Configuration
+
+Several cfssl commands take a -db-config flag. Create a file with a
+JSON dictionary:
+
+ {"driver":"sqlite3","data_source":"certs.db"}
+
+or
+
+ {"driver":"postgres","data_source":"postgres://user:password@host/db"}
+
+or
+
+ {"driver":"mysql","data_source":"user:password@tcp(hostname:3306)/db?parseTime=true"}
diff --git a/vendor/github.com/cloudflare/cfssl/certdb/certdb.go b/vendor/github.com/cloudflare/cfssl/certdb/certdb.go
new file mode 100644
index 0000000..96694f7
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/certdb/certdb.go
@@ -0,0 +1,40 @@
+package certdb
+
+import (
+ "time"
+)
+
+// CertificateRecord encodes a certificate and its metadata
+// that will be recorded in a database.
+type CertificateRecord struct {
+ Serial string `db:"serial_number"`
+ AKI string `db:"authority_key_identifier"`
+ CALabel string `db:"ca_label"`
+ Status string `db:"status"`
+ Reason int `db:"reason"`
+ Expiry time.Time `db:"expiry"`
+ RevokedAt time.Time `db:"revoked_at"`
+ PEM string `db:"pem"`
+}
+
+// OCSPRecord encodes a OCSP response body and its metadata
+// that will be recorded in a database.
+type OCSPRecord struct {
+ Serial string `db:"serial_number"`
+ AKI string `db:"authority_key_identifier"`
+ Body string `db:"body"`
+ Expiry time.Time `db:"expiry"`
+}
+
+// Accessor abstracts the CRUD of certdb objects from a DB.
+type Accessor interface {
+ InsertCertificate(cr CertificateRecord) error
+ GetCertificate(serial, aki string) ([]CertificateRecord, error)
+ GetUnexpiredCertificates() ([]CertificateRecord, error)
+ RevokeCertificate(serial, aki string, reasonCode int) error
+ InsertOCSP(rr OCSPRecord) error
+ GetOCSP(serial, aki string) ([]OCSPRecord, error)
+ GetUnexpiredOCSPs() ([]OCSPRecord, error)
+ UpdateOCSP(serial, aki, body string, expiry time.Time) error
+ UpsertOCSP(serial, aki, body string, expiry time.Time) error
+}
diff --git a/vendor/github.com/cloudflare/cfssl/config/config.go b/vendor/github.com/cloudflare/cfssl/config/config.go
new file mode 100644
index 0000000..d5eb7c3
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/config/config.go
@@ -0,0 +1,659 @@
+// Package config contains the configuration logic for CFSSL.
+package config
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/asn1"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/cloudflare/cfssl/auth"
+ cferr "github.com/cloudflare/cfssl/errors"
+ "github.com/cloudflare/cfssl/helpers"
+ "github.com/cloudflare/cfssl/log"
+ ocspConfig "github.com/cloudflare/cfssl/ocsp/config"
+)
+
+// A CSRWhitelist stores booleans for fields in the CSR. If a CSRWhitelist is
+// not present in a SigningProfile, all of these fields may be copied from the
+// CSR into the signed certificate. If a CSRWhitelist *is* present in a
+// SigningProfile, only those fields with a `true` value in the CSRWhitelist may
+// be copied from the CSR to the signed certificate. Note that some of these
+// fields, like Subject, can be provided or partially provided through the API.
+// Since API clients are expected to be trusted, but CSRs are not, fields
+// provided through the API are not subject to whitelisting through this
+// mechanism.
+type CSRWhitelist struct {
+ Subject, PublicKeyAlgorithm, PublicKey, SignatureAlgorithm bool
+ DNSNames, IPAddresses, EmailAddresses bool
+}
+
+// OID is our own version of asn1's ObjectIdentifier, so we can define a custom
+// JSON marshal / unmarshal.
+type OID asn1.ObjectIdentifier
+
+// CertificatePolicy represents the ASN.1 PolicyInformation structure from
+// https://tools.ietf.org/html/rfc3280.html#page-106.
+// Valid values of Type are "id-qt-unotice" and "id-qt-cps"
+type CertificatePolicy struct {
+ ID OID
+ Qualifiers []CertificatePolicyQualifier
+}
+
+// CertificatePolicyQualifier represents a single qualifier from an ASN.1
+// PolicyInformation structure.
+type CertificatePolicyQualifier struct {
+ Type string
+ Value string
+}
+
+// AuthRemote is an authenticated remote signer.
+type AuthRemote struct {
+ RemoteName string `json:"remote"`
+ AuthKeyName string `json:"auth_key"`
+}
+
+// CAConstraint specifies various CA constraints on the signed certificate.
+// CAConstraint would verify against (and override) the CA
+// extensions in the given CSR.
+type CAConstraint struct {
+ IsCA bool `json:"is_ca"`
+ MaxPathLen int `json:"max_path_len"`
+ MaxPathLenZero bool `json:"max_path_len_zero"`
+}
+
+// A SigningProfile stores information that the CA needs to store
+// signature policy.
+type SigningProfile struct {
+ Usage []string `json:"usages"`
+ IssuerURL []string `json:"issuer_urls"`
+ OCSP string `json:"ocsp_url"`
+ CRL string `json:"crl_url"`
+ CAConstraint CAConstraint `json:"ca_constraint"`
+ OCSPNoCheck bool `json:"ocsp_no_check"`
+ ExpiryString string `json:"expiry"`
+ BackdateString string `json:"backdate"`
+ AuthKeyName string `json:"auth_key"`
+ RemoteName string `json:"remote"`
+ NotBefore time.Time `json:"not_before"`
+ NotAfter time.Time `json:"not_after"`
+ NameWhitelistString string `json:"name_whitelist"`
+ AuthRemote AuthRemote `json:"auth_remote"`
+ CTLogServers []string `json:"ct_log_servers"`
+ AllowedExtensions []OID `json:"allowed_extensions"`
+ CertStore string `json:"cert_store"`
+
+ Policies []CertificatePolicy
+ Expiry time.Duration
+ Backdate time.Duration
+ Provider auth.Provider
+ RemoteProvider auth.Provider
+ RemoteServer string
+ RemoteCAs *x509.CertPool
+ ClientCert *tls.Certificate
+ CSRWhitelist *CSRWhitelist
+ NameWhitelist *regexp.Regexp
+ ExtensionWhitelist map[string]bool
+ ClientProvidesSerialNumbers bool
+}
+
+// UnmarshalJSON unmarshals a JSON string into an OID.
+func (oid *OID) UnmarshalJSON(data []byte) (err error) {
+ if data[0] != '"' || data[len(data)-1] != '"' {
+ return errors.New("OID JSON string not wrapped in quotes." + string(data))
+ }
+ data = data[1 : len(data)-1]
+ parsedOid, err := parseObjectIdentifier(string(data))
+ if err != nil {
+ return err
+ }
+ *oid = OID(parsedOid)
+ return
+}
+
+// MarshalJSON marshals an oid into a JSON string.
+func (oid OID) MarshalJSON() ([]byte, error) {
+ return []byte(fmt.Sprintf(`"%v"`, asn1.ObjectIdentifier(oid))), nil
+}
+
+func parseObjectIdentifier(oidString string) (oid asn1.ObjectIdentifier, err error) {
+ validOID, err := regexp.MatchString("\\d(\\.\\d+)*", oidString)
+ if err != nil {
+ return
+ }
+ if !validOID {
+ err = errors.New("Invalid OID")
+ return
+ }
+
+ segments := strings.Split(oidString, ".")
+ oid = make(asn1.ObjectIdentifier, len(segments))
+ for i, intString := range segments {
+ oid[i], err = strconv.Atoi(intString)
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+const timeFormat = "2006-01-02T15:04:05"
+
+// populate is used to fill in the fields that are not in JSON
+//
+// First, the ExpiryString parameter is needed to parse
+// expiration timestamps from JSON. The JSON decoder is not able to
+// decode a string time duration to a time.Duration, so this is called
+// when loading the configuration to properly parse and fill out the
+// Expiry parameter.
+// This function is also used to create references to the auth key
+// and default remote for the profile.
+// It returns true if ExpiryString is a valid representation of a
+// time.Duration, and the AuthKeyString and RemoteName point to
+// valid objects. It returns false otherwise.
+func (p *SigningProfile) populate(cfg *Config) error {
+ if p == nil {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("can't parse nil profile"))
+ }
+
+ var err error
+ if p.RemoteName == "" && p.AuthRemote.RemoteName == "" {
+ log.Debugf("parse expiry in profile")
+ if p.ExpiryString == "" {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("empty expiry string"))
+ }
+
+ dur, err := time.ParseDuration(p.ExpiryString)
+ if err != nil {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, err)
+ }
+
+ log.Debugf("expiry is valid")
+ p.Expiry = dur
+
+ if p.BackdateString != "" {
+ dur, err = time.ParseDuration(p.BackdateString)
+ if err != nil {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, err)
+ }
+
+ p.Backdate = dur
+ }
+
+ if !p.NotBefore.IsZero() && !p.NotAfter.IsZero() && p.NotAfter.Before(p.NotBefore) {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, err)
+ }
+
+ if len(p.Policies) > 0 {
+ for _, policy := range p.Policies {
+ for _, qualifier := range policy.Qualifiers {
+ if qualifier.Type != "" && qualifier.Type != "id-qt-unotice" && qualifier.Type != "id-qt-cps" {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("invalid policy qualifier type"))
+ }
+ }
+ }
+ }
+ } else if p.RemoteName != "" {
+ log.Debug("match remote in profile to remotes section")
+ if p.AuthRemote.RemoteName != "" {
+ log.Error("profile has both a remote and an auth remote specified")
+ return cferr.New(cferr.PolicyError, cferr.InvalidPolicy)
+ }
+ if remote := cfg.Remotes[p.RemoteName]; remote != "" {
+ if err := p.updateRemote(remote); err != nil {
+ return err
+ }
+ } else {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("failed to find remote in remotes section"))
+ }
+ } else {
+ log.Debug("match auth remote in profile to remotes section")
+ if remote := cfg.Remotes[p.AuthRemote.RemoteName]; remote != "" {
+ if err := p.updateRemote(remote); err != nil {
+ return err
+ }
+ } else {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("failed to find remote in remotes section"))
+ }
+ }
+
+ if p.AuthKeyName != "" {
+ log.Debug("match auth key in profile to auth_keys section")
+ if key, ok := cfg.AuthKeys[p.AuthKeyName]; ok == true {
+ if key.Type == "standard" {
+ p.Provider, err = auth.New(key.Key, nil)
+ if err != nil {
+ log.Debugf("failed to create new standard auth provider: %v", err)
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("failed to create new standard auth provider"))
+ }
+ } else {
+ log.Debugf("unknown authentication type %v", key.Type)
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("unknown authentication type"))
+ }
+ } else {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("failed to find auth_key in auth_keys section"))
+ }
+ }
+
+ if p.AuthRemote.AuthKeyName != "" {
+ log.Debug("match auth remote key in profile to auth_keys section")
+ if key, ok := cfg.AuthKeys[p.AuthRemote.AuthKeyName]; ok == true {
+ if key.Type == "standard" {
+ p.RemoteProvider, err = auth.New(key.Key, nil)
+ if err != nil {
+ log.Debugf("failed to create new standard auth provider: %v", err)
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("failed to create new standard auth provider"))
+ }
+ } else {
+ log.Debugf("unknown authentication type %v", key.Type)
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("unknown authentication type"))
+ }
+ } else {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("failed to find auth_remote's auth_key in auth_keys section"))
+ }
+ }
+
+ if p.NameWhitelistString != "" {
+ log.Debug("compiling whitelist regular expression")
+ rule, err := regexp.Compile(p.NameWhitelistString)
+ if err != nil {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("failed to compile name whitelist section"))
+ }
+ p.NameWhitelist = rule
+ }
+
+ p.ExtensionWhitelist = map[string]bool{}
+ for _, oid := range p.AllowedExtensions {
+ p.ExtensionWhitelist[asn1.ObjectIdentifier(oid).String()] = true
+ }
+
+ return nil
+}
+
+// updateRemote takes a signing profile and initializes the remote server object
+// to the hostname:port combination sent by remote.
+func (p *SigningProfile) updateRemote(remote string) error {
+ if remote != "" {
+ p.RemoteServer = remote
+ }
+ return nil
+}
+
+// OverrideRemotes takes a signing configuration and updates the remote server object
+// to the hostname:port combination sent by remote
+func (p *Signing) OverrideRemotes(remote string) error {
+ if remote != "" {
+ var err error
+ for _, profile := range p.Profiles {
+ err = profile.updateRemote(remote)
+ if err != nil {
+ return err
+ }
+ }
+ err = p.Default.updateRemote(remote)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// SetClientCertKeyPairFromFile updates the properties to set client certificates for mutual
+// authenticated TLS remote requests
+func (p *Signing) SetClientCertKeyPairFromFile(certFile string, keyFile string) error {
+ if certFile != "" && keyFile != "" {
+ cert, err := helpers.LoadClientCertificate(certFile, keyFile)
+ if err != nil {
+ return err
+ }
+ for _, profile := range p.Profiles {
+ profile.ClientCert = cert
+ }
+ p.Default.ClientCert = cert
+ }
+ return nil
+}
+
+// SetRemoteCAsFromFile reads root CAs from file and updates the properties to set remote CAs for TLS
+// remote requests
+func (p *Signing) SetRemoteCAsFromFile(caFile string) error {
+ if caFile != "" {
+ remoteCAs, err := helpers.LoadPEMCertPool(caFile)
+ if err != nil {
+ return err
+ }
+ p.SetRemoteCAs(remoteCAs)
+ }
+ return nil
+}
+
+// SetRemoteCAs updates the properties to set remote CAs for TLS
+// remote requests
+func (p *Signing) SetRemoteCAs(remoteCAs *x509.CertPool) {
+ for _, profile := range p.Profiles {
+ profile.RemoteCAs = remoteCAs
+ }
+ p.Default.RemoteCAs = remoteCAs
+}
+
+// NeedsRemoteSigner returns true if one of the profiles has a remote set
+func (p *Signing) NeedsRemoteSigner() bool {
+ for _, profile := range p.Profiles {
+ if profile.RemoteServer != "" {
+ return true
+ }
+ }
+
+ if p.Default.RemoteServer != "" {
+ return true
+ }
+
+ return false
+}
+
+// NeedsLocalSigner returns true if one of the profiles doe not have a remote set
+func (p *Signing) NeedsLocalSigner() bool {
+ for _, profile := range p.Profiles {
+ if profile.RemoteServer == "" {
+ return true
+ }
+ }
+
+ if p.Default.RemoteServer == "" {
+ return true
+ }
+
+ return false
+}
+
+// Usages parses the list of key uses in the profile, translating them
+// to a list of X.509 key usages and extended key usages. The unknown
+// uses are collected into a slice that is also returned.
+func (p *SigningProfile) Usages() (ku x509.KeyUsage, eku []x509.ExtKeyUsage, unk []string) {
+ for _, keyUse := range p.Usage {
+ if kuse, ok := KeyUsage[keyUse]; ok {
+ ku |= kuse
+ } else if ekuse, ok := ExtKeyUsage[keyUse]; ok {
+ eku = append(eku, ekuse)
+ } else {
+ unk = append(unk, keyUse)
+ }
+ }
+ return
+}
+
+// A valid profile must be a valid local profile or a valid remote profile.
+// A valid local profile has defined at least key usages to be used, and a
+// valid local default profile has defined at least a default expiration.
+// A valid remote profile (default or not) has remote signer initialized.
+// In addition, a remote profile must has a valid auth provider if auth
+// key defined.
+func (p *SigningProfile) validProfile(isDefault bool) bool {
+ if p == nil {
+ return false
+ }
+
+ if p.AuthRemote.RemoteName == "" && p.AuthRemote.AuthKeyName != "" {
+ log.Debugf("invalid auth remote profile: no remote signer specified")
+ return false
+ }
+
+ if p.RemoteName != "" {
+ log.Debugf("validate remote profile")
+
+ if p.RemoteServer == "" {
+ log.Debugf("invalid remote profile: no remote signer specified")
+ return false
+ }
+
+ if p.AuthKeyName != "" && p.Provider == nil {
+ log.Debugf("invalid remote profile: auth key name is defined but no auth provider is set")
+ return false
+ }
+
+ if p.AuthRemote.RemoteName != "" {
+ log.Debugf("invalid remote profile: auth remote is also specified")
+ return false
+ }
+ } else if p.AuthRemote.RemoteName != "" {
+ log.Debugf("validate auth remote profile")
+ if p.RemoteServer == "" {
+ log.Debugf("invalid auth remote profile: no remote signer specified")
+ return false
+ }
+
+ if p.AuthRemote.AuthKeyName == "" || p.RemoteProvider == nil {
+ log.Debugf("invalid auth remote profile: no auth key is defined")
+ return false
+ }
+ } else {
+ log.Debugf("validate local profile")
+ if !isDefault {
+ if len(p.Usage) == 0 {
+ log.Debugf("invalid local profile: no usages specified")
+ return false
+ } else if _, _, unk := p.Usages(); len(unk) == len(p.Usage) {
+ log.Debugf("invalid local profile: no valid usages")
+ return false
+ }
+ } else {
+ if p.Expiry == 0 {
+ log.Debugf("invalid local profile: no expiry set")
+ return false
+ }
+ }
+ }
+
+ log.Debugf("profile is valid")
+ return true
+}
+
+// This checks if the SigningProfile object contains configurations that are only effective with a local signer
+// which has access to CA private key.
+func (p *SigningProfile) hasLocalConfig() bool {
+ if p.Usage != nil ||
+ p.IssuerURL != nil ||
+ p.OCSP != "" ||
+ p.ExpiryString != "" ||
+ p.BackdateString != "" ||
+ p.CAConstraint.IsCA != false ||
+ !p.NotBefore.IsZero() ||
+ !p.NotAfter.IsZero() ||
+ p.NameWhitelistString != "" ||
+ len(p.CTLogServers) != 0 {
+ return true
+ }
+ return false
+}
+
+// warnSkippedSettings prints a log warning message about skipped settings
+// in a SigningProfile, usually due to remote signer.
+func (p *Signing) warnSkippedSettings() {
+ const warningMessage = `The configuration value by "usages", "issuer_urls", "ocsp_url", "crl_url", "ca_constraint", "expiry", "backdate", "not_before", "not_after", "cert_store" and "ct_log_servers" are skipped`
+ if p == nil {
+ return
+ }
+
+ if (p.Default.RemoteName != "" || p.Default.AuthRemote.RemoteName != "") && p.Default.hasLocalConfig() {
+ log.Warning("default profile points to a remote signer: ", warningMessage)
+ }
+
+ for name, profile := range p.Profiles {
+ if (profile.RemoteName != "" || profile.AuthRemote.RemoteName != "") && profile.hasLocalConfig() {
+ log.Warningf("Profiles[%s] points to a remote signer: %s", name, warningMessage)
+ }
+ }
+}
+
+// Signing codifies the signature configuration policy for a CA.
+type Signing struct {
+ Profiles map[string]*SigningProfile `json:"profiles"`
+ Default *SigningProfile `json:"default"`
+}
+
+// Config stores configuration information for the CA.
+type Config struct {
+ Signing *Signing `json:"signing"`
+ OCSP *ocspConfig.Config `json:"ocsp"`
+ AuthKeys map[string]AuthKey `json:"auth_keys,omitempty"`
+ Remotes map[string]string `json:"remotes,omitempty"`
+}
+
+// Valid ensures that Config is a valid configuration. It should be
+// called immediately after parsing a configuration file.
+func (c *Config) Valid() bool {
+ return c.Signing.Valid()
+}
+
+// Valid checks the signature policies, ensuring they are valid
+// policies. A policy is valid if it has defined at least key usages
+// to be used, and a valid default profile has defined at least a
+// default expiration.
+func (p *Signing) Valid() bool {
+ if p == nil {
+ return false
+ }
+
+ log.Debugf("validating configuration")
+ if !p.Default.validProfile(true) {
+ log.Debugf("default profile is invalid")
+ return false
+ }
+
+ for _, sp := range p.Profiles {
+ if !sp.validProfile(false) {
+ log.Debugf("invalid profile")
+ return false
+ }
+ }
+
+ p.warnSkippedSettings()
+
+ return true
+}
+
+// KeyUsage contains a mapping of string names to key usages.
+var KeyUsage = map[string]x509.KeyUsage{
+ "signing": x509.KeyUsageDigitalSignature,
+ "digital signature": x509.KeyUsageDigitalSignature,
+ "content committment": x509.KeyUsageContentCommitment,
+ "key encipherment": x509.KeyUsageKeyEncipherment,
+ "key agreement": x509.KeyUsageKeyAgreement,
+ "data encipherment": x509.KeyUsageDataEncipherment,
+ "cert sign": x509.KeyUsageCertSign,
+ "crl sign": x509.KeyUsageCRLSign,
+ "encipher only": x509.KeyUsageEncipherOnly,
+ "decipher only": x509.KeyUsageDecipherOnly,
+}
+
+// ExtKeyUsage contains a mapping of string names to extended key
+// usages.
+var ExtKeyUsage = map[string]x509.ExtKeyUsage{
+ "any": x509.ExtKeyUsageAny,
+ "server auth": x509.ExtKeyUsageServerAuth,
+ "client auth": x509.ExtKeyUsageClientAuth,
+ "code signing": x509.ExtKeyUsageCodeSigning,
+ "email protection": x509.ExtKeyUsageEmailProtection,
+ "s/mime": x509.ExtKeyUsageEmailProtection,
+ "ipsec end system": x509.ExtKeyUsageIPSECEndSystem,
+ "ipsec tunnel": x509.ExtKeyUsageIPSECTunnel,
+ "ipsec user": x509.ExtKeyUsageIPSECUser,
+ "timestamping": x509.ExtKeyUsageTimeStamping,
+ "ocsp signing": x509.ExtKeyUsageOCSPSigning,
+ "microsoft sgc": x509.ExtKeyUsageMicrosoftServerGatedCrypto,
+ "netscape sgc": x509.ExtKeyUsageNetscapeServerGatedCrypto,
+}
+
+// An AuthKey contains an entry for a key used for authentication.
+type AuthKey struct {
+ // Type contains information needed to select the appropriate
+ // constructor. For example, "standard" for HMAC-SHA-256,
+ // "standard-ip" for HMAC-SHA-256 incorporating the client's
+ // IP.
+ Type string `json:"type"`
+ // Key contains the key information, such as a hex-encoded
+ // HMAC key.
+ Key string `json:"key"`
+}
+
+// DefaultConfig returns a default configuration specifying basic key
+// usage and a 1 year expiration time. The key usages chosen are
+// signing, key encipherment, client auth and server auth.
+func DefaultConfig() *SigningProfile {
+ d := helpers.OneYear
+ return &SigningProfile{
+ Usage: []string{"signing", "key encipherment", "server auth", "client auth"},
+ Expiry: d,
+ ExpiryString: "8760h",
+ }
+}
+
+// LoadFile attempts to load the configuration file stored at the path
+// and returns the configuration. On error, it returns nil.
+func LoadFile(path string) (*Config, error) {
+ log.Debugf("loading configuration file from %s", path)
+ if path == "" {
+ return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid path"))
+ }
+
+ body, err := ioutil.ReadFile(path)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("could not read configuration file"))
+ }
+
+ return LoadConfig(body)
+}
+
+// LoadConfig attempts to load the configuration from a byte slice.
+// On error, it returns nil.
+func LoadConfig(config []byte) (*Config, error) {
+ var cfg = &Config{}
+ err := json.Unmarshal(config, &cfg)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy,
+ errors.New("failed to unmarshal configuration: "+err.Error()))
+ }
+
+ if cfg.Signing == nil {
+ return nil, errors.New("No \"signing\" field present")
+ }
+
+ if cfg.Signing.Default == nil {
+ log.Debugf("no default given: using default config")
+ cfg.Signing.Default = DefaultConfig()
+ } else {
+ if err := cfg.Signing.Default.populate(cfg); err != nil {
+ return nil, err
+ }
+ }
+
+ for k := range cfg.Signing.Profiles {
+ if err := cfg.Signing.Profiles[k].populate(cfg); err != nil {
+ return nil, err
+ }
+ }
+
+ if !cfg.Valid() {
+ return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, errors.New("invalid configuration"))
+ }
+
+ log.Debugf("configuration ok")
+ return cfg, nil
+}
diff --git a/vendor/github.com/cloudflare/cfssl/crypto/pkcs7/pkcs7.go b/vendor/github.com/cloudflare/cfssl/crypto/pkcs7/pkcs7.go
new file mode 100644
index 0000000..8db547f
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/crypto/pkcs7/pkcs7.go
@@ -0,0 +1,188 @@
+// Package pkcs7 implements the subset of the CMS PKCS #7 datatype that is typically
+// used to package certificates and CRLs. Using openssl, every certificate converted
+// to PKCS #7 format from another encoding such as PEM conforms to this implementation.
+// reference: https://www.openssl.org/docs/apps/crl2pkcs7.html
+//
+// PKCS #7 Data type, reference: https://tools.ietf.org/html/rfc2315
+//
+// The full pkcs#7 cryptographic message syntax allows for cryptographic enhancements,
+// for example data can be encrypted and signed and then packaged through pkcs#7 to be
+// sent over a network and then verified and decrypted. It is asn1, and the type of
+// PKCS #7 ContentInfo, which comprises the PKCS #7 structure, is:
+//
+// ContentInfo ::= SEQUENCE {
+// contentType ContentType,
+// content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
+// }
+//
+// There are 6 possible ContentTypes, data, signedData, envelopedData,
+// signedAndEnvelopedData, digestedData, and encryptedData. Here signedData, Data, and encrypted
+// Data are implemented, as the degenerate case of signedData without a signature is the typical
+// format for transferring certificates and CRLS, and Data and encryptedData are used in PKCS #12
+// formats.
+// The ContentType signedData has the form:
+//
+//
+// signedData ::= SEQUENCE {
+// version Version,
+// digestAlgorithms DigestAlgorithmIdentifiers,
+// contentInfo ContentInfo,
+// certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL
+// crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
+// signerInfos SignerInfos
+// }
+//
+// As of yet signerInfos and digestAlgorithms are not parsed, as they are not relevant to
+// this system's use of PKCS #7 data. Version is an integer type, note that PKCS #7 is
+// recursive, this second layer of ContentInfo is similar ignored for our degenerate
+// usage. The ExtendedCertificatesAndCertificates type consists of a sequence of choices
+// between PKCS #6 extended certificates and x509 certificates. Any sequence consisting
+// of any number of extended certificates is not yet supported in this implementation.
+//
+// The ContentType Data is simply a raw octet string and is parsed directly into a Go []byte slice.
+//
+// The ContentType encryptedData is the most complicated and its form can be gathered by
+// the go type below. It essentially contains a raw octet string of encrypted data and an
+// algorithm identifier for use in decrypting this data.
+package pkcs7
+
+import (
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/asn1"
+ "errors"
+
+ cferr "github.com/cloudflare/cfssl/errors"
+)
+
+// Types used for asn1 Unmarshaling.
+
+type signedData struct {
+ Version int
+ DigestAlgorithms asn1.RawValue
+ ContentInfo asn1.RawValue
+ Certificates asn1.RawValue `asn1:"optional" asn1:"tag:0"`
+ Crls asn1.RawValue `asn1:"optional"`
+ SignerInfos asn1.RawValue
+}
+
+type initPKCS7 struct {
+ Raw asn1.RawContent
+ ContentType asn1.ObjectIdentifier
+ Content asn1.RawValue `asn1:"tag:0,explicit,optional"`
+}
+
+// Object identifier strings of the three implemented PKCS7 types.
+const (
+ ObjIDData = "1.2.840.113549.1.7.1"
+ ObjIDSignedData = "1.2.840.113549.1.7.2"
+ ObjIDEncryptedData = "1.2.840.113549.1.7.6"
+)
+
+// PKCS7 represents the ASN1 PKCS #7 Content type. It contains one of three
+// possible types of Content objects, as denoted by the object identifier in
+// the ContentInfo field, the other two being nil. SignedData
+// is the degenerate SignedData Content info without signature used
+// to hold certificates and crls. Data is raw bytes, and EncryptedData
+// is as defined in PKCS #7 standard.
+type PKCS7 struct {
+ Raw asn1.RawContent
+ ContentInfo string
+ Content Content
+}
+
+// Content implements three of the six possible PKCS7 data types. Only one is non-nil.
+type Content struct {
+ Data []byte
+ SignedData SignedData
+ EncryptedData EncryptedData
+}
+
+// SignedData defines the typical carrier of certificates and crls.
+type SignedData struct {
+ Raw asn1.RawContent
+ Version int
+ Certificates []*x509.Certificate
+ Crl *pkix.CertificateList
+}
+
+// Data contains raw bytes. Used as a subtype in PKCS12.
+type Data struct {
+ Bytes []byte
+}
+
+// EncryptedData contains encrypted data. Used as a subtype in PKCS12.
+type EncryptedData struct {
+ Raw asn1.RawContent
+ Version int
+ EncryptedContentInfo EncryptedContentInfo
+}
+
+// EncryptedContentInfo is a subtype of PKCS7EncryptedData.
+type EncryptedContentInfo struct {
+ Raw asn1.RawContent
+ ContentType asn1.ObjectIdentifier
+ ContentEncryptionAlgorithm pkix.AlgorithmIdentifier
+ EncryptedContent []byte `asn1:"tag:0,optional"`
+}
+
+// ParsePKCS7 attempts to parse the DER encoded bytes of a
+// PKCS7 structure.
+func ParsePKCS7(raw []byte) (msg *PKCS7, err error) {
+
+ var pkcs7 initPKCS7
+ _, err = asn1.Unmarshal(raw, &pkcs7)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
+ }
+
+ msg = new(PKCS7)
+ msg.Raw = pkcs7.Raw
+ msg.ContentInfo = pkcs7.ContentType.String()
+ switch {
+ case msg.ContentInfo == ObjIDData:
+ msg.ContentInfo = "Data"
+ _, err = asn1.Unmarshal(pkcs7.Content.Bytes, &msg.Content.Data)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
+ }
+ case msg.ContentInfo == ObjIDSignedData:
+ msg.ContentInfo = "SignedData"
+ var signedData signedData
+ _, err = asn1.Unmarshal(pkcs7.Content.Bytes, &signedData)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
+ }
+ if len(signedData.Certificates.Bytes) != 0 {
+ msg.Content.SignedData.Certificates, err = x509.ParseCertificates(signedData.Certificates.Bytes)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
+ }
+ }
+ if len(signedData.Crls.Bytes) != 0 {
+ msg.Content.SignedData.Crl, err = x509.ParseDERCRL(signedData.Crls.Bytes)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
+ }
+ }
+ msg.Content.SignedData.Version = signedData.Version
+ msg.Content.SignedData.Raw = pkcs7.Content.Bytes
+ case msg.ContentInfo == ObjIDEncryptedData:
+ msg.ContentInfo = "EncryptedData"
+ var encryptedData EncryptedData
+ _, err = asn1.Unmarshal(pkcs7.Content.Bytes, &encryptedData)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
+ }
+ if encryptedData.Version != 0 {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("Only support for PKCS #7 encryptedData version 0"))
+ }
+ msg.Content.EncryptedData = encryptedData
+
+ default:
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("Attempt to parse PKCS# 7 Content not of type data, signed data or encrypted data"))
+ }
+
+ return msg, nil
+
+}
diff --git a/vendor/github.com/cloudflare/cfssl/csr/csr.go b/vendor/github.com/cloudflare/cfssl/csr/csr.go
new file mode 100644
index 0000000..4329b79
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/csr/csr.go
@@ -0,0 +1,431 @@
+// Package csr implements certificate requests for CFSSL.
+package csr
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/asn1"
+ "encoding/pem"
+ "errors"
+ "net"
+ "net/mail"
+ "strings"
+
+ cferr "github.com/cloudflare/cfssl/errors"
+ "github.com/cloudflare/cfssl/helpers"
+ "github.com/cloudflare/cfssl/log"
+)
+
+const (
+ curveP256 = 256
+ curveP384 = 384
+ curveP521 = 521
+)
+
+// A Name contains the SubjectInfo fields.
+type Name struct {
+ C string // Country
+ ST string // State
+ L string // Locality
+ O string // OrganisationName
+ OU string // OrganisationalUnitName
+ SerialNumber string
+}
+
+// A KeyRequest is a generic request for a new key.
+type KeyRequest interface {
+ Algo() string
+ Size() int
+ Generate() (crypto.PrivateKey, error)
+ SigAlgo() x509.SignatureAlgorithm
+}
+
+// A BasicKeyRequest contains the algorithm and key size for a new private key.
+type BasicKeyRequest struct {
+ A string `json:"algo"`
+ S int `json:"size"`
+}
+
+// NewBasicKeyRequest returns a default BasicKeyRequest.
+func NewBasicKeyRequest() *BasicKeyRequest {
+ return &BasicKeyRequest{"ecdsa", curveP256}
+}
+
+// Algo returns the requested key algorithm represented as a string.
+func (kr *BasicKeyRequest) Algo() string {
+ return kr.A
+}
+
+// Size returns the requested key size.
+func (kr *BasicKeyRequest) Size() int {
+ return kr.S
+}
+
+// Generate generates a key as specified in the request. Currently,
+// only ECDSA and RSA are supported.
+func (kr *BasicKeyRequest) Generate() (crypto.PrivateKey, error) {
+ log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo(), kr.Size())
+ switch kr.Algo() {
+ case "rsa":
+ if kr.Size() < 2048 {
+ return nil, errors.New("RSA key is too weak")
+ }
+ if kr.Size() > 8192 {
+ return nil, errors.New("RSA key size too large")
+ }
+ return rsa.GenerateKey(rand.Reader, kr.Size())
+ case "ecdsa":
+ var curve elliptic.Curve
+ switch kr.Size() {
+ case curveP256:
+ curve = elliptic.P256()
+ case curveP384:
+ curve = elliptic.P384()
+ case curveP521:
+ curve = elliptic.P521()
+ default:
+ return nil, errors.New("invalid curve")
+ }
+ return ecdsa.GenerateKey(curve, rand.Reader)
+ default:
+ return nil, errors.New("invalid algorithm")
+ }
+}
+
+// SigAlgo returns an appropriate X.509 signature algorithm given the
+// key request's type and size.
+func (kr *BasicKeyRequest) SigAlgo() x509.SignatureAlgorithm {
+ switch kr.Algo() {
+ case "rsa":
+ switch {
+ case kr.Size() >= 4096:
+ return x509.SHA512WithRSA
+ case kr.Size() >= 3072:
+ return x509.SHA384WithRSA
+ case kr.Size() >= 2048:
+ return x509.SHA256WithRSA
+ default:
+ return x509.SHA1WithRSA
+ }
+ case "ecdsa":
+ switch kr.Size() {
+ case curveP521:
+ return x509.ECDSAWithSHA512
+ case curveP384:
+ return x509.ECDSAWithSHA384
+ case curveP256:
+ return x509.ECDSAWithSHA256
+ default:
+ return x509.ECDSAWithSHA1
+ }
+ default:
+ return x509.UnknownSignatureAlgorithm
+ }
+}
+
+// CAConfig is a section used in the requests initialising a new CA.
+type CAConfig struct {
+ PathLength int `json:"pathlen"`
+ PathLenZero bool `json:"pathlenzero"`
+ Expiry string `json:"expiry"`
+}
+
+// A CertificateRequest encapsulates the API interface to the
+// certificate request functionality.
+type CertificateRequest struct {
+ CN string
+ Names []Name `json:"names"`
+ Hosts []string `json:"hosts"`
+ KeyRequest KeyRequest `json:"key,omitempty"`
+ CA *CAConfig `json:"ca,omitempty"`
+ SerialNumber string `json:"serialnumber,omitempty"`
+}
+
+// New returns a new, empty CertificateRequest with a
+// BasicKeyRequest.
+func New() *CertificateRequest {
+ return &CertificateRequest{
+ KeyRequest: NewBasicKeyRequest(),
+ }
+}
+
+// appendIf appends to a if s is not an empty string.
+func appendIf(s string, a *[]string) {
+ if s != "" {
+ *a = append(*a, s)
+ }
+}
+
+// Name returns the PKIX name for the request.
+func (cr *CertificateRequest) Name() pkix.Name {
+ var name pkix.Name
+ name.CommonName = cr.CN
+
+ for _, n := range cr.Names {
+ appendIf(n.C, &name.Country)
+ appendIf(n.ST, &name.Province)
+ appendIf(n.L, &name.Locality)
+ appendIf(n.O, &name.Organization)
+ appendIf(n.OU, &name.OrganizationalUnit)
+ }
+ name.SerialNumber = cr.SerialNumber
+ return name
+}
+
+// BasicConstraints CSR information RFC 5280, 4.2.1.9
+type BasicConstraints struct {
+ IsCA bool `asn1:"optional"`
+ MaxPathLen int `asn1:"optional,default:-1"`
+}
+
+// ParseRequest takes a certificate request and generates a key and
+// CSR from it. It does no validation -- caveat emptor. It will,
+// however, fail if the key request is not valid (i.e., an unsupported
+// curve or RSA key size). The lack of validation was specifically
+// chosen to allow the end user to define a policy and validate the
+// request appropriately before calling this function.
+func ParseRequest(req *CertificateRequest) (csr, key []byte, err error) {
+ log.Info("received CSR")
+ if req.KeyRequest == nil {
+ req.KeyRequest = NewBasicKeyRequest()
+ }
+
+ log.Infof("generating key: %s-%d", req.KeyRequest.Algo(), req.KeyRequest.Size())
+ priv, err := req.KeyRequest.Generate()
+ if err != nil {
+ err = cferr.Wrap(cferr.PrivateKeyError, cferr.GenerationFailed, err)
+ return
+ }
+
+ switch priv := priv.(type) {
+ case *rsa.PrivateKey:
+ key = x509.MarshalPKCS1PrivateKey(priv)
+ block := pem.Block{
+ Type: "RSA PRIVATE KEY",
+ Bytes: key,
+ }
+ key = pem.EncodeToMemory(&block)
+ case *ecdsa.PrivateKey:
+ key, err = x509.MarshalECPrivateKey(priv)
+ if err != nil {
+ err = cferr.Wrap(cferr.PrivateKeyError, cferr.Unknown, err)
+ return
+ }
+ block := pem.Block{
+ Type: "EC PRIVATE KEY",
+ Bytes: key,
+ }
+ key = pem.EncodeToMemory(&block)
+ default:
+ panic("Generate should have failed to produce a valid key.")
+ }
+
+ csr, err = Generate(priv.(crypto.Signer), req)
+ if err != nil {
+ log.Errorf("failed to generate a CSR: %v", err)
+ err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err)
+ }
+ return
+}
+
+// ExtractCertificateRequest extracts a CertificateRequest from
+// x509.Certificate. It is aimed to used for generating a new certificate
+// from an existing certificate. For a root certificate, the CA expiry
+// length is calculated as the duration between cert.NotAfter and cert.NotBefore.
+func ExtractCertificateRequest(cert *x509.Certificate) *CertificateRequest {
+ req := New()
+ req.CN = cert.Subject.CommonName
+ req.Names = getNames(cert.Subject)
+ req.Hosts = getHosts(cert)
+ req.SerialNumber = cert.Subject.SerialNumber
+
+ if cert.IsCA {
+ req.CA = new(CAConfig)
+ // CA expiry length is calculated based on the input cert
+ // issue date and expiry date.
+ req.CA.Expiry = cert.NotAfter.Sub(cert.NotBefore).String()
+ req.CA.PathLength = cert.MaxPathLen
+ req.CA.PathLenZero = cert.MaxPathLenZero
+ }
+
+ return req
+}
+
+func getHosts(cert *x509.Certificate) []string {
+ var hosts []string
+ for _, ip := range cert.IPAddresses {
+ hosts = append(hosts, ip.String())
+ }
+ for _, dns := range cert.DNSNames {
+ hosts = append(hosts, dns)
+ }
+ for _, email := range cert.EmailAddresses {
+ hosts = append(hosts, email)
+ }
+
+ return hosts
+}
+
+// getNames returns an array of Names from the certificate
+// It onnly cares about Country, Organization, OrganizationalUnit, Locality, Province
+func getNames(sub pkix.Name) []Name {
+ // anonymous func for finding the max of a list of interger
+ max := func(v1 int, vn ...int) (max int) {
+ max = v1
+ for i := 0; i < len(vn); i++ {
+ if vn[i] > max {
+ max = vn[i]
+ }
+ }
+ return max
+ }
+
+ nc := len(sub.Country)
+ norg := len(sub.Organization)
+ nou := len(sub.OrganizationalUnit)
+ nl := len(sub.Locality)
+ np := len(sub.Province)
+
+ n := max(nc, norg, nou, nl, np)
+
+ names := make([]Name, n)
+ for i := range names {
+ if i < nc {
+ names[i].C = sub.Country[i]
+ }
+ if i < norg {
+ names[i].O = sub.Organization[i]
+ }
+ if i < nou {
+ names[i].OU = sub.OrganizationalUnit[i]
+ }
+ if i < nl {
+ names[i].L = sub.Locality[i]
+ }
+ if i < np {
+ names[i].ST = sub.Province[i]
+ }
+ }
+ return names
+}
+
+// A Generator is responsible for validating certificate requests.
+type Generator struct {
+ Validator func(*CertificateRequest) error
+}
+
+// ProcessRequest validates and processes the incoming request. It is
+// a wrapper around a validator and the ParseRequest function.
+func (g *Generator) ProcessRequest(req *CertificateRequest) (csr, key []byte, err error) {
+
+ log.Info("generate received request")
+ err = g.Validator(req)
+ if err != nil {
+ log.Warningf("invalid request: %v", err)
+ return
+ }
+
+ csr, key, err = ParseRequest(req)
+ if err != nil {
+ return nil, nil, err
+ }
+ return
+}
+
+// IsNameEmpty returns true if the name has no identifying information in it.
+func IsNameEmpty(n Name) bool {
+ empty := func(s string) bool { return strings.TrimSpace(s) == "" }
+
+ if empty(n.C) && empty(n.ST) && empty(n.L) && empty(n.O) && empty(n.OU) {
+ return true
+ }
+ return false
+}
+
+// Regenerate uses the provided CSR as a template for signing a new
+// CSR using priv.
+func Regenerate(priv crypto.Signer, csr []byte) ([]byte, error) {
+ req, extra, err := helpers.ParseCSR(csr)
+ if err != nil {
+ return nil, err
+ } else if len(extra) > 0 {
+ return nil, errors.New("csr: trailing data in certificate request")
+ }
+
+ return x509.CreateCertificateRequest(rand.Reader, req, priv)
+}
+
+// Generate creates a new CSR from a CertificateRequest structure and
+// an existing key. The KeyRequest field is ignored.
+func Generate(priv crypto.Signer, req *CertificateRequest) (csr []byte, err error) {
+ sigAlgo := helpers.SignerAlgo(priv)
+ if sigAlgo == x509.UnknownSignatureAlgorithm {
+ return nil, cferr.New(cferr.PrivateKeyError, cferr.Unavailable)
+ }
+
+ var tpl = x509.CertificateRequest{
+ Subject: req.Name(),
+ SignatureAlgorithm: sigAlgo,
+ }
+
+ for i := range req.Hosts {
+ if ip := net.ParseIP(req.Hosts[i]); ip != nil {
+ tpl.IPAddresses = append(tpl.IPAddresses, ip)
+ } else if email, err := mail.ParseAddress(req.Hosts[i]); err == nil && email != nil {
+ tpl.EmailAddresses = append(tpl.EmailAddresses, email.Address)
+ } else {
+ tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i])
+ }
+ }
+
+ if req.CA != nil {
+ err = appendCAInfoToCSR(req.CA, &tpl)
+ if err != nil {
+ err = cferr.Wrap(cferr.CSRError, cferr.GenerationFailed, err)
+ return
+ }
+ }
+
+ csr, err = x509.CreateCertificateRequest(rand.Reader, &tpl, priv)
+ if err != nil {
+ log.Errorf("failed to generate a CSR: %v", err)
+ err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err)
+ return
+ }
+ block := pem.Block{
+ Type: "CERTIFICATE REQUEST",
+ Bytes: csr,
+ }
+
+ log.Info("encoded CSR")
+ csr = pem.EncodeToMemory(&block)
+ return
+}
+
+// appendCAInfoToCSR appends CAConfig BasicConstraint extension to a CSR
+func appendCAInfoToCSR(reqConf *CAConfig, csr *x509.CertificateRequest) error {
+ pathlen := reqConf.PathLength
+ if pathlen == 0 && !reqConf.PathLenZero {
+ pathlen = -1
+ }
+ val, err := asn1.Marshal(BasicConstraints{true, pathlen})
+
+ if err != nil {
+ return err
+ }
+
+ csr.ExtraExtensions = []pkix.Extension{
+ {
+ Id: asn1.ObjectIdentifier{2, 5, 29, 19},
+ Value: val,
+ Critical: true,
+ },
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/cloudflare/cfssl/errors/doc.go b/vendor/github.com/cloudflare/cfssl/errors/doc.go
new file mode 100644
index 0000000..1910e26
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/errors/doc.go
@@ -0,0 +1,46 @@
+/*
+Package errors provides error types returned in CF SSL.
+
+1. Type Error is intended for errors produced by CF SSL packages.
+It formats to a json object that consists of an error message and a 4-digit code for error reasoning.
+
+Example: {"code":1002, "message": "Failed to decode certificate"}
+
+The index of codes are listed below:
+ 1XXX: CertificateError
+ 1000: Unknown
+ 1001: ReadFailed
+ 1002: DecodeFailed
+ 1003: ParseFailed
+ 1100: SelfSigned
+ 12XX: VerifyFailed
+ 121X: CertificateInvalid
+ 1210: NotAuthorizedToSign
+ 1211: Expired
+ 1212: CANotAuthorizedForThisName
+ 1213: TooManyIntermediates
+ 1214: IncompatibleUsage
+ 1220: UnknownAuthority
+ 2XXX: PrivatekeyError
+ 2000: Unknown
+ 2001: ReadFailed
+ 2002: DecodeFailed
+ 2003: ParseFailed
+ 2100: Encrypted
+ 2200: NotRSA
+ 2300: KeyMismatch
+ 2400: GenerationFailed
+ 2500: Unavailable
+ 3XXX: IntermediatesError
+ 4XXX: RootError
+ 5XXX: PolicyError
+ 5100: NoKeyUsages
+ 5200: InvalidPolicy
+ 5300: InvalidRequest
+ 5400: UnknownProfile
+ 6XXX: DialError
+
+2. Type HttpError is intended for CF SSL API to consume. It contains a HTTP status code that will be read and returned
+by the API server.
+*/
+package errors
diff --git a/vendor/github.com/cloudflare/cfssl/errors/error.go b/vendor/github.com/cloudflare/cfssl/errors/error.go
new file mode 100644
index 0000000..9913a84
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/errors/error.go
@@ -0,0 +1,424 @@
+package errors
+
+import (
+ "crypto/x509"
+ "encoding/json"
+ "fmt"
+)
+
+// Error is the error type usually returned by functions in CF SSL package.
+// It contains a 4-digit error code where the most significant digit
+// describes the category where the error occurred and the rest 3 digits
+// describe the specific error reason.
+type Error struct {
+ ErrorCode int `json:"code"`
+ Message string `json:"message"`
+}
+
+// Category is the most significant digit of the error code.
+type Category int
+
+// Reason is the last 3 digits of the error code.
+type Reason int
+
+const (
+ // Success indicates no error occurred.
+ Success Category = 1000 * iota // 0XXX
+
+ // CertificateError indicates a fault in a certificate.
+ CertificateError // 1XXX
+
+ // PrivateKeyError indicates a fault in a private key.
+ PrivateKeyError // 2XXX
+
+ // IntermediatesError indicates a fault in an intermediate.
+ IntermediatesError // 3XXX
+
+ // RootError indicates a fault in a root.
+ RootError // 4XXX
+
+ // PolicyError indicates an error arising from a malformed or
+ // non-existent policy, or a breach of policy.
+ PolicyError // 5XXX
+
+ // DialError indicates a network fault.
+ DialError // 6XXX
+
+ // APIClientError indicates a problem with the API client.
+ APIClientError // 7XXX
+
+ // OCSPError indicates a problem with OCSP signing
+ OCSPError // 8XXX
+
+ // CSRError indicates a problem with CSR parsing
+ CSRError // 9XXX
+
+ // CTError indicates a problem with the certificate transparency process
+ CTError // 10XXX
+
+ // CertStoreError indicates a problem with the certificate store
+ CertStoreError // 11XXX
+)
+
+// None is a non-specified error.
+const (
+ None Reason = iota
+)
+
+// Warning code for a success
+const (
+ BundleExpiringBit int = 1 << iota // 0x01
+ BundleNotUbiquitousBit // 0x02
+)
+
+// Parsing errors
+const (
+ Unknown Reason = iota // X000
+ ReadFailed // X001
+ DecodeFailed // X002
+ ParseFailed // X003
+)
+
+// The following represent certificate non-parsing errors, and must be
+// specified along with CertificateError.
+const (
+ // SelfSigned indicates that a certificate is self-signed and
+ // cannot be used in the manner being attempted.
+ SelfSigned Reason = 100 * (iota + 1) // Code 11XX
+
+ // VerifyFailed is an X.509 verification failure. The least two
+ // significant digits of 12XX is determined as the actual x509
+ // error is examined.
+ VerifyFailed // Code 12XX
+
+ // BadRequest indicates that the certificate request is invalid.
+ BadRequest // Code 13XX
+
+ // MissingSerial indicates that the profile specified
+ // 'ClientProvidesSerialNumbers', but the SignRequest did not include a serial
+ // number.
+ MissingSerial // Code 14XX
+)
+
+const (
+ certificateInvalid = 10 * (iota + 1) //121X
+ unknownAuthority //122x
+)
+
+// The following represent private-key non-parsing errors, and must be
+// specified with PrivateKeyError.
+const (
+ // Encrypted indicates that the private key is a PKCS #8 encrypted
+ // private key. At this time, CFSSL does not support decrypting
+ // these keys.
+ Encrypted Reason = 100 * (iota + 1) //21XX
+
+ // NotRSAOrECC indicates that they key is not an RSA or ECC
+ // private key; these are the only two private key types supported
+ // at this time by CFSSL.
+ NotRSAOrECC //22XX
+
+ // KeyMismatch indicates that the private key does not match
+ // the public key or certificate being presented with the key.
+ KeyMismatch //23XX
+
+ // GenerationFailed indicates that a private key could not
+ // be generated.
+ GenerationFailed //24XX
+
+ // Unavailable indicates that a private key mechanism (such as
+ // PKCS #11) was requested but support for that mechanism is
+ // not available.
+ Unavailable
+)
+
+// The following are policy-related non-parsing errors, and must be
+// specified along with PolicyError.
+const (
+ // NoKeyUsages indicates that the profile does not permit any
+ // key usages for the certificate.
+ NoKeyUsages Reason = 100 * (iota + 1) // 51XX
+
+ // InvalidPolicy indicates that policy being requested is not
+ // a valid policy or does not exist.
+ InvalidPolicy // 52XX
+
+ // InvalidRequest indicates a certificate request violated the
+ // constraints of the policy being applied to the request.
+ InvalidRequest // 53XX
+
+ // UnknownProfile indicates that the profile does not exist.
+ UnknownProfile // 54XX
+
+ UnmatchedWhitelist // 55xx
+)
+
+// The following are API client related errors, and should be
+// specified with APIClientError.
+const (
+ // AuthenticationFailure occurs when the client is unable
+ // to obtain an authentication token for the request.
+ AuthenticationFailure Reason = 100 * (iota + 1)
+
+ // JSONError wraps an encoding/json error.
+ JSONError
+
+ // IOError wraps an io/ioutil error.
+ IOError
+
+ // ClientHTTPError wraps a net/http error.
+ ClientHTTPError
+
+ // ServerRequestFailed covers any other failures from the API
+ // client.
+ ServerRequestFailed
+)
+
+// The following are OCSP related errors, and should be
+// specified with OCSPError
+const (
+ // IssuerMismatch ocurs when the certificate in the OCSP signing
+ // request was not issued by the CA that this responder responds for.
+ IssuerMismatch Reason = 100 * (iota + 1) // 81XX
+
+ // InvalidStatus occurs when the OCSP signing requests includes an
+ // invalid value for the certificate status.
+ InvalidStatus
+)
+
+// Certificate transparency related errors specified with CTError
+const (
+ // PrecertSubmissionFailed occurs when submitting a precertificate to
+ // a log server fails
+ PrecertSubmissionFailed = 100 * (iota + 1)
+)
+
+// Certificate persistence related errors specified with CertStoreError
+const (
+ // InsertionFailed occurs when a SQL insert query failes to complete.
+ InsertionFailed = 100 * (iota + 1)
+ // RecordNotFound occurs when a SQL query targeting on one unique
+ // record failes to update the specified row in the table.
+ RecordNotFound
+)
+
+// The error interface implementation, which formats to a JSON object string.
+func (e *Error) Error() string {
+ marshaled, err := json.Marshal(e)
+ if err != nil {
+ panic(err)
+ }
+ return string(marshaled)
+
+}
+
+// New returns an error that contains an error code and message derived from
+// the given category, reason. Currently, to avoid confusion, it is not
+// allowed to create an error of category Success
+func New(category Category, reason Reason) *Error {
+ errorCode := int(category) + int(reason)
+ var msg string
+ switch category {
+ case OCSPError:
+ switch reason {
+ case ReadFailed:
+ msg = "No certificate provided"
+ case IssuerMismatch:
+ msg = "Certificate not issued by this issuer"
+ case InvalidStatus:
+ msg = "Invalid revocation status"
+ }
+ case CertificateError:
+ switch reason {
+ case Unknown:
+ msg = "Unknown certificate error"
+ case ReadFailed:
+ msg = "Failed to read certificate"
+ case DecodeFailed:
+ msg = "Failed to decode certificate"
+ case ParseFailed:
+ msg = "Failed to parse certificate"
+ case SelfSigned:
+ msg = "Certificate is self signed"
+ case VerifyFailed:
+ msg = "Unable to verify certificate"
+ case BadRequest:
+ msg = "Invalid certificate request"
+ case MissingSerial:
+ msg = "Missing serial number in request"
+ default:
+ panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category CertificateError.",
+ reason))
+
+ }
+ case PrivateKeyError:
+ switch reason {
+ case Unknown:
+ msg = "Unknown private key error"
+ case ReadFailed:
+ msg = "Failed to read private key"
+ case DecodeFailed:
+ msg = "Failed to decode private key"
+ case ParseFailed:
+ msg = "Failed to parse private key"
+ case Encrypted:
+ msg = "Private key is encrypted."
+ case NotRSAOrECC:
+ msg = "Private key algorithm is not RSA or ECC"
+ case KeyMismatch:
+ msg = "Private key does not match public key"
+ case GenerationFailed:
+ msg = "Failed to new private key"
+ case Unavailable:
+ msg = "Private key is unavailable"
+ default:
+ panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category PrivateKeyError.",
+ reason))
+ }
+ case IntermediatesError:
+ switch reason {
+ case Unknown:
+ msg = "Unknown intermediate certificate error"
+ case ReadFailed:
+ msg = "Failed to read intermediate certificate"
+ case DecodeFailed:
+ msg = "Failed to decode intermediate certificate"
+ case ParseFailed:
+ msg = "Failed to parse intermediate certificate"
+ default:
+ panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category IntermediatesError.",
+ reason))
+ }
+ case RootError:
+ switch reason {
+ case Unknown:
+ msg = "Unknown root certificate error"
+ case ReadFailed:
+ msg = "Failed to read root certificate"
+ case DecodeFailed:
+ msg = "Failed to decode root certificate"
+ case ParseFailed:
+ msg = "Failed to parse root certificate"
+ default:
+ panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category RootError.",
+ reason))
+ }
+ case PolicyError:
+ switch reason {
+ case Unknown:
+ msg = "Unknown policy error"
+ case NoKeyUsages:
+ msg = "Invalid policy: no key usage available"
+ case InvalidPolicy:
+ msg = "Invalid or unknown policy"
+ case InvalidRequest:
+ msg = "Policy violation request"
+ case UnknownProfile:
+ msg = "Unknown policy profile"
+ case UnmatchedWhitelist:
+ msg = "Request does not match policy whitelist"
+ default:
+ panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category PolicyError.",
+ reason))
+ }
+ case DialError:
+ switch reason {
+ case Unknown:
+ msg = "Failed to dial remote server"
+ default:
+ panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category DialError.",
+ reason))
+ }
+ case APIClientError:
+ switch reason {
+ case AuthenticationFailure:
+ msg = "API client authentication failure"
+ case JSONError:
+ msg = "API client JSON config error"
+ case ClientHTTPError:
+ msg = "API client HTTP error"
+ case IOError:
+ msg = "API client IO error"
+ case ServerRequestFailed:
+ msg = "API client error: Server request failed"
+ default:
+ panic(fmt.Sprintf("Unsupported CFSSL error reason %d under category APIClientError.",
+ reason))
+ }
+ case CSRError:
+ switch reason {
+ case Unknown:
+ msg = "CSR parsing failed due to unknown error"
+ case ReadFailed:
+ msg = "CSR file read failed"
+ case ParseFailed:
+ msg = "CSR Parsing failed"
+ case DecodeFailed:
+ msg = "CSR Decode failed"
+ case BadRequest:
+ msg = "CSR Bad request"
+ default:
+ panic(fmt.Sprintf("Unsupported CF-SSL error reason %d under category APIClientError.", reason))
+ }
+ case CTError:
+ switch reason {
+ case Unknown:
+ msg = "Certificate transparency parsing failed due to unknown error"
+ case PrecertSubmissionFailed:
+ msg = "Certificate transparency precertificate submission failed"
+ default:
+ panic(fmt.Sprintf("Unsupported CF-SSL error reason %d under category CTError.", reason))
+ }
+ case CertStoreError:
+ switch reason {
+ case Unknown:
+ msg = "Certificate store action failed due to unknown error"
+ default:
+ panic(fmt.Sprintf("Unsupported CF-SSL error reason %d under category CertStoreError.", reason))
+ }
+
+ default:
+ panic(fmt.Sprintf("Unsupported CFSSL error type: %d.",
+ category))
+ }
+ return &Error{ErrorCode: errorCode, Message: msg}
+}
+
+// Wrap returns an error that contains the given error and an error code derived from
+// the given category, reason and the error. Currently, to avoid confusion, it is not
+// allowed to create an error of category Success
+func Wrap(category Category, reason Reason, err error) *Error {
+ errorCode := int(category) + int(reason)
+ if err == nil {
+ panic("Wrap needs a supplied error to initialize.")
+ }
+
+ // do not double wrap a error
+ switch err.(type) {
+ case *Error:
+ panic("Unable to wrap a wrapped error.")
+ }
+
+ switch category {
+ case CertificateError:
+ // given VerifyFailed , report the status with more detailed status code
+ // for some certificate errors we care.
+ if reason == VerifyFailed {
+ switch errorType := err.(type) {
+ case x509.CertificateInvalidError:
+ errorCode += certificateInvalid + int(errorType.Reason)
+ case x509.UnknownAuthorityError:
+ errorCode += unknownAuthority
+ }
+ }
+ case PrivateKeyError, IntermediatesError, RootError, PolicyError, DialError,
+ APIClientError, CSRError, CTError, CertStoreError:
+ // no-op, just use the error
+ default:
+ panic(fmt.Sprintf("Unsupported CFSSL error type: %d.",
+ category))
+ }
+
+ return &Error{ErrorCode: errorCode, Message: err.Error()}
+
+}
diff --git a/vendor/github.com/cloudflare/cfssl/errors/http.go b/vendor/github.com/cloudflare/cfssl/errors/http.go
new file mode 100644
index 0000000..c9c0a39
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/errors/http.go
@@ -0,0 +1,47 @@
+package errors
+
+import (
+ "errors"
+ "net/http"
+)
+
+// HTTPError is an augmented error with a HTTP status code.
+type HTTPError struct {
+ StatusCode int
+ error
+}
+
+// Error implements the error interface.
+func (e *HTTPError) Error() string {
+ return e.error.Error()
+}
+
+// NewMethodNotAllowed returns an appropriate error in the case that
+// an HTTP client uses an invalid method (i.e. a GET in place of a POST)
+// on an API endpoint.
+func NewMethodNotAllowed(method string) *HTTPError {
+ return &HTTPError{http.StatusMethodNotAllowed, errors.New(`Method is not allowed:"` + method + `"`)}
+}
+
+// NewBadRequest creates a HttpError with the given error and error code 400.
+func NewBadRequest(err error) *HTTPError {
+ return &HTTPError{http.StatusBadRequest, err}
+}
+
+// NewBadRequestString returns a HttpError with the supplied message
+// and error code 400.
+func NewBadRequestString(s string) *HTTPError {
+ return NewBadRequest(errors.New(s))
+}
+
+// NewBadRequestMissingParameter returns a 400 HttpError as a required
+// parameter is missing in the HTTP request.
+func NewBadRequestMissingParameter(s string) *HTTPError {
+ return NewBadRequestString(`Missing parameter "` + s + `"`)
+}
+
+// NewBadRequestUnwantedParameter returns a 400 HttpError as a unnecessary
+// parameter is present in the HTTP request.
+func NewBadRequestUnwantedParameter(s string) *HTTPError {
+ return NewBadRequestString(`Unwanted parameter "` + s + `"`)
+}
diff --git a/vendor/github.com/cloudflare/cfssl/helpers/derhelpers/derhelpers.go b/vendor/github.com/cloudflare/cfssl/helpers/derhelpers/derhelpers.go
new file mode 100644
index 0000000..bcc7418
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/helpers/derhelpers/derhelpers.go
@@ -0,0 +1,42 @@
+// Package derhelpers implements common functionality
+// on DER encoded data
+package derhelpers
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/rsa"
+ "crypto/x509"
+
+ cferr "github.com/cloudflare/cfssl/errors"
+)
+
+// ParsePrivateKeyDER parses a PKCS #1, PKCS #8, or elliptic curve
+// DER-encoded private key. The key must not be in PEM format.
+func ParsePrivateKeyDER(keyDER []byte) (key crypto.Signer, err error) {
+ generalKey, err := x509.ParsePKCS8PrivateKey(keyDER)
+ if err != nil {
+ generalKey, err = x509.ParsePKCS1PrivateKey(keyDER)
+ if err != nil {
+ generalKey, err = x509.ParseECPrivateKey(keyDER)
+ if err != nil {
+ // We don't include the actual error into
+ // the final error. The reason might be
+ // we don't want to leak any info about
+ // the private key.
+ return nil, cferr.New(cferr.PrivateKeyError,
+ cferr.ParseFailed)
+ }
+ }
+ }
+
+ switch generalKey.(type) {
+ case *rsa.PrivateKey:
+ return generalKey.(*rsa.PrivateKey), nil
+ case *ecdsa.PrivateKey:
+ return generalKey.(*ecdsa.PrivateKey), nil
+ }
+
+ // should never reach here
+ return nil, cferr.New(cferr.PrivateKeyError, cferr.ParseFailed)
+}
diff --git a/vendor/github.com/cloudflare/cfssl/helpers/helpers.go b/vendor/github.com/cloudflare/cfssl/helpers/helpers.go
new file mode 100644
index 0000000..48d096a
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/helpers/helpers.go
@@ -0,0 +1,518 @@
+// Package helpers implements utility functionality common to many
+// CFSSL packages.
+package helpers
+
+import (
+ "bytes"
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rsa"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/asn1"
+ "encoding/pem"
+ "errors"
+ "io/ioutil"
+ "math/big"
+
+ "strings"
+ "time"
+
+ "github.com/cloudflare/cfssl/crypto/pkcs7"
+ cferr "github.com/cloudflare/cfssl/errors"
+ "github.com/cloudflare/cfssl/helpers/derhelpers"
+ "github.com/cloudflare/cfssl/log"
+ "golang.org/x/crypto/pkcs12"
+)
+
+// OneYear is a time.Duration representing a year's worth of seconds.
+const OneYear = 8760 * time.Hour
+
+// OneDay is a time.Duration representing a day's worth of seconds.
+const OneDay = 24 * time.Hour
+
+// InclusiveDate returns the time.Time representation of a date - 1
+// nanosecond. This allows time.After to be used inclusively.
+func InclusiveDate(year int, month time.Month, day int) time.Time {
+ return time.Date(year, month, day, 0, 0, 0, 0, time.UTC).Add(-1 * time.Nanosecond)
+}
+
+// Jul2012 is the July 2012 CAB Forum deadline for when CAs must stop
+// issuing certificates valid for more than 5 years.
+var Jul2012 = InclusiveDate(2012, time.July, 01)
+
+// Apr2015 is the April 2015 CAB Forum deadline for when CAs must stop
+// issuing certificates valid for more than 39 months.
+var Apr2015 = InclusiveDate(2015, time.April, 01)
+
+// KeyLength returns the bit size of ECDSA or RSA PublicKey
+func KeyLength(key interface{}) int {
+ if key == nil {
+ return 0
+ }
+ if ecdsaKey, ok := key.(*ecdsa.PublicKey); ok {
+ return ecdsaKey.Curve.Params().BitSize
+ } else if rsaKey, ok := key.(*rsa.PublicKey); ok {
+ return rsaKey.N.BitLen()
+ }
+
+ return 0
+}
+
+// ExpiryTime returns the time when the certificate chain is expired.
+func ExpiryTime(chain []*x509.Certificate) (notAfter time.Time) {
+ if len(chain) == 0 {
+ return
+ }
+
+ notAfter = chain[0].NotAfter
+ for _, cert := range chain {
+ if notAfter.After(cert.NotAfter) {
+ notAfter = cert.NotAfter
+ }
+ }
+ return
+}
+
+// MonthsValid returns the number of months for which a certificate is valid.
+func MonthsValid(c *x509.Certificate) int {
+ issued := c.NotBefore
+ expiry := c.NotAfter
+ years := (expiry.Year() - issued.Year())
+ months := years*12 + int(expiry.Month()) - int(issued.Month())
+
+ // Round up if valid for less than a full month
+ if expiry.Day() > issued.Day() {
+ months++
+ }
+ return months
+}
+
+// ValidExpiry determines if a certificate is valid for an acceptable
+// length of time per the CA/Browser Forum baseline requirements.
+// See https://cabforum.org/wp-content/uploads/CAB-Forum-BR-1.3.0.pdf
+func ValidExpiry(c *x509.Certificate) bool {
+ issued := c.NotBefore
+
+ var maxMonths int
+ switch {
+ case issued.After(Apr2015):
+ maxMonths = 39
+ case issued.After(Jul2012):
+ maxMonths = 60
+ case issued.Before(Jul2012):
+ maxMonths = 120
+ }
+
+ if MonthsValid(c) > maxMonths {
+ return false
+ }
+ return true
+}
+
+// SignatureString returns the TLS signature string corresponding to
+// an X509 signature algorithm.
+func SignatureString(alg x509.SignatureAlgorithm) string {
+ switch alg {
+ case x509.MD2WithRSA:
+ return "MD2WithRSA"
+ case x509.MD5WithRSA:
+ return "MD5WithRSA"
+ case x509.SHA1WithRSA:
+ return "SHA1WithRSA"
+ case x509.SHA256WithRSA:
+ return "SHA256WithRSA"
+ case x509.SHA384WithRSA:
+ return "SHA384WithRSA"
+ case x509.SHA512WithRSA:
+ return "SHA512WithRSA"
+ case x509.DSAWithSHA1:
+ return "DSAWithSHA1"
+ case x509.DSAWithSHA256:
+ return "DSAWithSHA256"
+ case x509.ECDSAWithSHA1:
+ return "ECDSAWithSHA1"
+ case x509.ECDSAWithSHA256:
+ return "ECDSAWithSHA256"
+ case x509.ECDSAWithSHA384:
+ return "ECDSAWithSHA384"
+ case x509.ECDSAWithSHA512:
+ return "ECDSAWithSHA512"
+ default:
+ return "Unknown Signature"
+ }
+}
+
+// HashAlgoString returns the hash algorithm name contains in the signature
+// method.
+func HashAlgoString(alg x509.SignatureAlgorithm) string {
+ switch alg {
+ case x509.MD2WithRSA:
+ return "MD2"
+ case x509.MD5WithRSA:
+ return "MD5"
+ case x509.SHA1WithRSA:
+ return "SHA1"
+ case x509.SHA256WithRSA:
+ return "SHA256"
+ case x509.SHA384WithRSA:
+ return "SHA384"
+ case x509.SHA512WithRSA:
+ return "SHA512"
+ case x509.DSAWithSHA1:
+ return "SHA1"
+ case x509.DSAWithSHA256:
+ return "SHA256"
+ case x509.ECDSAWithSHA1:
+ return "SHA1"
+ case x509.ECDSAWithSHA256:
+ return "SHA256"
+ case x509.ECDSAWithSHA384:
+ return "SHA384"
+ case x509.ECDSAWithSHA512:
+ return "SHA512"
+ default:
+ return "Unknown Hash Algorithm"
+ }
+}
+
+// EncodeCertificatesPEM encodes a number of x509 certficates to PEM
+func EncodeCertificatesPEM(certs []*x509.Certificate) []byte {
+ var buffer bytes.Buffer
+ for _, cert := range certs {
+ pem.Encode(&buffer, &pem.Block{
+ Type: "CERTIFICATE",
+ Bytes: cert.Raw,
+ })
+ }
+
+ return buffer.Bytes()
+}
+
+// EncodeCertificatePEM encodes a single x509 certficates to PEM
+func EncodeCertificatePEM(cert *x509.Certificate) []byte {
+ return EncodeCertificatesPEM([]*x509.Certificate{cert})
+}
+
+// ParseCertificatesPEM parses a sequence of PEM-encoded certificate and returns them,
+// can handle PEM encoded PKCS #7 structures.
+func ParseCertificatesPEM(certsPEM []byte) ([]*x509.Certificate, error) {
+ var certs []*x509.Certificate
+ var err error
+ certsPEM = bytes.TrimSpace(certsPEM)
+ for len(certsPEM) > 0 {
+ var cert []*x509.Certificate
+ cert, certsPEM, err = ParseOneCertificateFromPEM(certsPEM)
+ if err != nil {
+
+ return nil, cferr.New(cferr.CertificateError, cferr.ParseFailed)
+ } else if cert == nil {
+ break
+ }
+
+ certs = append(certs, cert...)
+ }
+ if len(certsPEM) > 0 {
+ return nil, cferr.New(cferr.CertificateError, cferr.DecodeFailed)
+ }
+ return certs, nil
+}
+
+// ParseCertificatesDER parses a DER encoding of a certificate object and possibly private key,
+// either PKCS #7, PKCS #12, or raw x509.
+func ParseCertificatesDER(certsDER []byte, password string) (certs []*x509.Certificate, key crypto.Signer, err error) {
+ certsDER = bytes.TrimSpace(certsDER)
+ pkcs7data, err := pkcs7.ParsePKCS7(certsDER)
+ if err != nil {
+ var pkcs12data interface{}
+ certs = make([]*x509.Certificate, 1)
+ pkcs12data, certs[0], err = pkcs12.Decode(certsDER, password)
+ if err != nil {
+ certs, err = x509.ParseCertificates(certsDER)
+ if err != nil {
+ return nil, nil, cferr.New(cferr.CertificateError, cferr.DecodeFailed)
+ }
+ } else {
+ key = pkcs12data.(crypto.Signer)
+ }
+ } else {
+ if pkcs7data.ContentInfo != "SignedData" {
+ return nil, nil, cferr.Wrap(cferr.CertificateError, cferr.DecodeFailed, errors.New("can only extract certificates from signed data content info"))
+ }
+ certs = pkcs7data.Content.SignedData.Certificates
+ }
+ if certs == nil {
+ return nil, key, cferr.New(cferr.CertificateError, cferr.DecodeFailed)
+ }
+ return certs, key, nil
+}
+
+// ParseSelfSignedCertificatePEM parses a PEM-encoded certificate and check if it is self-signed.
+func ParseSelfSignedCertificatePEM(certPEM []byte) (*x509.Certificate, error) {
+ cert, err := ParseCertificatePEM(certPEM)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature); err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.VerifyFailed, err)
+ }
+ return cert, nil
+}
+
+// ParseCertificatePEM parses and returns a PEM-encoded certificate,
+// can handle PEM encoded PKCS #7 structures.
+func ParseCertificatePEM(certPEM []byte) (*x509.Certificate, error) {
+ certPEM = bytes.TrimSpace(certPEM)
+ cert, rest, err := ParseOneCertificateFromPEM(certPEM)
+ if err != nil {
+ // Log the actual parsing error but throw a default parse error message.
+ log.Debugf("Certificate parsing error: %v", err)
+ return nil, cferr.New(cferr.CertificateError, cferr.ParseFailed)
+ } else if cert == nil {
+ return nil, cferr.New(cferr.CertificateError, cferr.DecodeFailed)
+ } else if len(rest) > 0 {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("the PEM file should contain only one object"))
+ } else if len(cert) > 1 {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New("the PKCS7 object in the PEM file should contain only one certificate"))
+ }
+ return cert[0], nil
+}
+
+// ParseOneCertificateFromPEM attempts to parse one PEM encoded certificate object,
+// either a raw x509 certificate or a PKCS #7 structure possibly containing
+// multiple certificates, from the top of certsPEM, which itself may
+// contain multiple PEM encoded certificate objects.
+func ParseOneCertificateFromPEM(certsPEM []byte) ([]*x509.Certificate, []byte, error) {
+
+ block, rest := pem.Decode(certsPEM)
+ if block == nil {
+ return nil, rest, nil
+ }
+
+ cert, err := x509.ParseCertificate(block.Bytes)
+ if err != nil {
+ pkcs7data, err := pkcs7.ParsePKCS7(block.Bytes)
+ if err != nil {
+ return nil, rest, err
+ }
+ if pkcs7data.ContentInfo != "SignedData" {
+ return nil, rest, errors.New("only PKCS #7 Signed Data Content Info supported for certificate parsing")
+ }
+ certs := pkcs7data.Content.SignedData.Certificates
+ if certs == nil {
+ return nil, rest, errors.New("PKCS #7 structure contains no certificates")
+ }
+ return certs, rest, nil
+ }
+ var certs = []*x509.Certificate{cert}
+ return certs, rest, nil
+}
+
+// LoadPEMCertPool loads a pool of PEM certificates from file.
+func LoadPEMCertPool(certsFile string) (*x509.CertPool, error) {
+ if certsFile == "" {
+ return nil, nil
+ }
+ pemCerts, err := ioutil.ReadFile(certsFile)
+ if err != nil {
+ return nil, err
+ }
+
+ return PEMToCertPool(pemCerts)
+}
+
+// PEMToCertPool concerts PEM certificates to a CertPool.
+func PEMToCertPool(pemCerts []byte) (*x509.CertPool, error) {
+ if len(pemCerts) == 0 {
+ return nil, nil
+ }
+
+ certPool := x509.NewCertPool()
+ if !certPool.AppendCertsFromPEM(pemCerts) {
+ return nil, errors.New("failed to load cert pool")
+ }
+
+ return certPool, nil
+}
+
+// ParsePrivateKeyPEM parses and returns a PEM-encoded private
+// key. The private key may be either an unencrypted PKCS#8, PKCS#1,
+// or elliptic private key.
+func ParsePrivateKeyPEM(keyPEM []byte) (key crypto.Signer, err error) {
+ return ParsePrivateKeyPEMWithPassword(keyPEM, nil)
+}
+
+// ParsePrivateKeyPEMWithPassword parses and returns a PEM-encoded private
+// key. The private key may be a potentially encrypted PKCS#8, PKCS#1,
+// or elliptic private key.
+func ParsePrivateKeyPEMWithPassword(keyPEM []byte, password []byte) (key crypto.Signer, err error) {
+ keyDER, err := GetKeyDERFromPEM(keyPEM, password)
+ if err != nil {
+ return nil, err
+ }
+
+ return derhelpers.ParsePrivateKeyDER(keyDER)
+}
+
+// GetKeyDERFromPEM parses a PEM-encoded private key and returns DER-format key bytes.
+func GetKeyDERFromPEM(in []byte, password []byte) ([]byte, error) {
+ keyDER, _ := pem.Decode(in)
+ if keyDER != nil {
+ if procType, ok := keyDER.Headers["Proc-Type"]; ok {
+ if strings.Contains(procType, "ENCRYPTED") {
+ if password != nil {
+ return x509.DecryptPEMBlock(keyDER, password)
+ }
+ return nil, cferr.New(cferr.PrivateKeyError, cferr.Encrypted)
+ }
+ }
+ return keyDER.Bytes, nil
+ }
+
+ return nil, cferr.New(cferr.PrivateKeyError, cferr.DecodeFailed)
+}
+
+// CheckSignature verifies a signature made by the key on a CSR, such
+// as on the CSR itself.
+func CheckSignature(csr *x509.CertificateRequest, algo x509.SignatureAlgorithm, signed, signature []byte) error {
+ var hashType crypto.Hash
+
+ switch algo {
+ case x509.SHA1WithRSA, x509.ECDSAWithSHA1:
+ hashType = crypto.SHA1
+ case x509.SHA256WithRSA, x509.ECDSAWithSHA256:
+ hashType = crypto.SHA256
+ case x509.SHA384WithRSA, x509.ECDSAWithSHA384:
+ hashType = crypto.SHA384
+ case x509.SHA512WithRSA, x509.ECDSAWithSHA512:
+ hashType = crypto.SHA512
+ default:
+ return x509.ErrUnsupportedAlgorithm
+ }
+
+ if !hashType.Available() {
+ return x509.ErrUnsupportedAlgorithm
+ }
+ h := hashType.New()
+
+ h.Write(signed)
+ digest := h.Sum(nil)
+
+ switch pub := csr.PublicKey.(type) {
+ case *rsa.PublicKey:
+ return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
+ case *ecdsa.PublicKey:
+ ecdsaSig := new(struct{ R, S *big.Int })
+ if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
+ return err
+ }
+ if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
+ return errors.New("x509: ECDSA signature contained zero or negative values")
+ }
+ if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
+ return errors.New("x509: ECDSA verification failure")
+ }
+ return nil
+ }
+ return x509.ErrUnsupportedAlgorithm
+}
+
+// ParseCSR parses a PEM- or DER-encoded PKCS #10 certificate signing request.
+func ParseCSR(in []byte) (csr *x509.CertificateRequest, rest []byte, err error) {
+ in = bytes.TrimSpace(in)
+ p, rest := pem.Decode(in)
+ if p != nil {
+ if p.Type != "NEW CERTIFICATE REQUEST" && p.Type != "CERTIFICATE REQUEST" {
+ return nil, rest, cferr.New(cferr.CSRError, cferr.BadRequest)
+ }
+
+ csr, err = x509.ParseCertificateRequest(p.Bytes)
+ } else {
+ csr, err = x509.ParseCertificateRequest(in)
+ }
+
+ if err != nil {
+ return nil, rest, err
+ }
+
+ err = CheckSignature(csr, csr.SignatureAlgorithm, csr.RawTBSCertificateRequest, csr.Signature)
+ if err != nil {
+ return nil, rest, err
+ }
+
+ return csr, rest, nil
+}
+
+// ParseCSRPEM parses a PEM-encoded certificiate signing request.
+// It does not check the signature. This is useful for dumping data from a CSR
+// locally.
+func ParseCSRPEM(csrPEM []byte) (*x509.CertificateRequest, error) {
+ block, _ := pem.Decode([]byte(csrPEM))
+ der := block.Bytes
+ csrObject, err := x509.ParseCertificateRequest(der)
+
+ if err != nil {
+ return nil, err
+ }
+
+ return csrObject, nil
+}
+
+// SignerAlgo returns an X.509 signature algorithm from a crypto.Signer.
+func SignerAlgo(priv crypto.Signer) x509.SignatureAlgorithm {
+ switch pub := priv.Public().(type) {
+ case *rsa.PublicKey:
+ bitLength := pub.N.BitLen()
+ switch {
+ case bitLength >= 4096:
+ return x509.SHA512WithRSA
+ case bitLength >= 3072:
+ return x509.SHA384WithRSA
+ case bitLength >= 2048:
+ return x509.SHA256WithRSA
+ default:
+ return x509.SHA1WithRSA
+ }
+ case *ecdsa.PublicKey:
+ switch pub.Curve {
+ case elliptic.P521():
+ return x509.ECDSAWithSHA512
+ case elliptic.P384():
+ return x509.ECDSAWithSHA384
+ case elliptic.P256():
+ return x509.ECDSAWithSHA256
+ default:
+ return x509.ECDSAWithSHA1
+ }
+ default:
+ return x509.UnknownSignatureAlgorithm
+ }
+}
+
+// LoadClientCertificate load key/certificate from pem files
+func LoadClientCertificate(certFile string, keyFile string) (*tls.Certificate, error) {
+ if certFile != "" && keyFile != "" {
+ cert, err := tls.LoadX509KeyPair(certFile, keyFile)
+ if err != nil {
+ log.Critical("Unable to read client certificate from file: %s or key from file: %s", certFile, keyFile)
+ return nil, err
+ }
+ log.Debug("Client certificate loaded ")
+ return &cert, nil
+ }
+ return nil, nil
+}
+
+// CreateTLSConfig creates a tls.Config object from certs and roots
+func CreateTLSConfig(remoteCAs *x509.CertPool, cert *tls.Certificate) *tls.Config {
+ var certs []tls.Certificate
+ if cert != nil {
+ certs = []tls.Certificate{*cert}
+ }
+ return &tls.Config{
+ Certificates: certs,
+ RootCAs: remoteCAs,
+ }
+}
diff --git a/vendor/github.com/cloudflare/cfssl/info/info.go b/vendor/github.com/cloudflare/cfssl/info/info.go
new file mode 100644
index 0000000..926a411
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/info/info.go
@@ -0,0 +1,15 @@
+// Package info contains the definitions for the info endpoint
+package info
+
+// Req is the request struct for an info API request.
+type Req struct {
+ Label string `json:"label"`
+ Profile string `json:"profile"`
+}
+
+// Resp is the response for an Info API request.
+type Resp struct {
+ Certificate string `json:"certificate"`
+ Usage []string `json:"usages"`
+ ExpiryString string `json:"expiry"`
+}
diff --git a/vendor/github.com/cloudflare/cfssl/initca/initca.go b/vendor/github.com/cloudflare/cfssl/initca/initca.go
new file mode 100644
index 0000000..c9ab3bb
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/initca/initca.go
@@ -0,0 +1,224 @@
+// Package initca contains code to initialise a certificate authority,
+// generating a new root key and certificate.
+package initca
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/rsa"
+ "crypto/x509"
+ "errors"
+ "io/ioutil"
+ "time"
+
+ "github.com/cloudflare/cfssl/config"
+ "github.com/cloudflare/cfssl/csr"
+ cferr "github.com/cloudflare/cfssl/errors"
+ "github.com/cloudflare/cfssl/helpers"
+ "github.com/cloudflare/cfssl/log"
+ "github.com/cloudflare/cfssl/signer"
+ "github.com/cloudflare/cfssl/signer/local"
+)
+
+// validator contains the default validation logic for certificate
+// authority certificates. The only requirement here is that the
+// certificate have a non-empty subject field.
+func validator(req *csr.CertificateRequest) error {
+ if req.CN != "" {
+ return nil
+ }
+
+ if len(req.Names) == 0 {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidRequest, errors.New("missing subject information"))
+ }
+
+ for i := range req.Names {
+ if csr.IsNameEmpty(req.Names[i]) {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidRequest, errors.New("missing subject information"))
+ }
+ }
+
+ return nil
+}
+
+// New creates a new root certificate from the certificate request.
+func New(req *csr.CertificateRequest) (cert, csrPEM, key []byte, err error) {
+ policy := CAPolicy()
+ if req.CA != nil {
+ if req.CA.Expiry != "" {
+ policy.Default.ExpiryString = req.CA.Expiry
+ policy.Default.Expiry, err = time.ParseDuration(req.CA.Expiry)
+ if err != nil {
+ return
+ }
+ }
+
+ policy.Default.CAConstraint.MaxPathLen = req.CA.PathLength
+ if req.CA.PathLength != 0 && req.CA.PathLenZero == true {
+ log.Infof("ignore invalid 'pathlenzero' value")
+ } else {
+ policy.Default.CAConstraint.MaxPathLenZero = req.CA.PathLenZero
+ }
+ }
+
+ g := &csr.Generator{Validator: validator}
+ csrPEM, key, err = g.ProcessRequest(req)
+ if err != nil {
+ log.Errorf("failed to process request: %v", err)
+ key = nil
+ return
+ }
+
+ priv, err := helpers.ParsePrivateKeyPEM(key)
+ if err != nil {
+ log.Errorf("failed to parse private key: %v", err)
+ return
+ }
+
+ s, err := local.NewSigner(priv, nil, signer.DefaultSigAlgo(priv), policy)
+ if err != nil {
+ log.Errorf("failed to create signer: %v", err)
+ return
+ }
+
+ signReq := signer.SignRequest{Hosts: req.Hosts, Request: string(csrPEM)}
+ cert, err = s.Sign(signReq)
+
+ return
+
+}
+
+// NewFromPEM creates a new root certificate from the key file passed in.
+func NewFromPEM(req *csr.CertificateRequest, keyFile string) (cert, csrPEM []byte, err error) {
+ privData, err := ioutil.ReadFile(keyFile)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ priv, err := helpers.ParsePrivateKeyPEM(privData)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ return NewFromSigner(req, priv)
+}
+
+// RenewFromPEM re-creates a root certificate from the CA cert and key
+// files. The resulting root certificate will have the input CA certificate
+// as the template and have the same expiry length. E.g. the exsiting CA
+// is valid for a year from Jan 01 2015 to Jan 01 2016, the renewed certificate
+// will be valid from now and expire in one year as well.
+func RenewFromPEM(caFile, keyFile string) ([]byte, error) {
+ caBytes, err := ioutil.ReadFile(caFile)
+ if err != nil {
+ return nil, err
+ }
+
+ ca, err := helpers.ParseCertificatePEM(caBytes)
+ if err != nil {
+ return nil, err
+ }
+
+ keyBytes, err := ioutil.ReadFile(keyFile)
+ if err != nil {
+ return nil, err
+ }
+
+ key, err := helpers.ParsePrivateKeyPEM(keyBytes)
+ if err != nil {
+ return nil, err
+ }
+
+ return RenewFromSigner(ca, key)
+
+}
+
+// NewFromSigner creates a new root certificate from a crypto.Signer.
+func NewFromSigner(req *csr.CertificateRequest, priv crypto.Signer) (cert, csrPEM []byte, err error) {
+ policy := CAPolicy()
+ if req.CA != nil {
+ if req.CA.Expiry != "" {
+ policy.Default.ExpiryString = req.CA.Expiry
+ policy.Default.Expiry, err = time.ParseDuration(req.CA.Expiry)
+ if err != nil {
+ return nil, nil, err
+ }
+ }
+
+ policy.Default.CAConstraint.MaxPathLen = req.CA.PathLength
+ if req.CA.PathLength != 0 && req.CA.PathLenZero == true {
+ log.Infof("ignore invalid 'pathlenzero' value")
+ } else {
+ policy.Default.CAConstraint.MaxPathLenZero = req.CA.PathLenZero
+ }
+ }
+
+ csrPEM, err = csr.Generate(priv, req)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ s, err := local.NewSigner(priv, nil, signer.DefaultSigAlgo(priv), policy)
+ if err != nil {
+ log.Errorf("failed to create signer: %v", err)
+ return
+ }
+
+ signReq := signer.SignRequest{Request: string(csrPEM)}
+ cert, err = s.Sign(signReq)
+ return
+}
+
+// RenewFromSigner re-creates a root certificate from the CA cert and crypto.Signer.
+// The resulting root certificate will have ca certificate
+// as the template and have the same expiry length. E.g. the exsiting CA
+// is valid for a year from Jan 01 2015 to Jan 01 2016, the renewed certificate
+// will be valid from now and expire in one year as well.
+func RenewFromSigner(ca *x509.Certificate, priv crypto.Signer) ([]byte, error) {
+ if !ca.IsCA {
+ return nil, errors.New("input certificate is not a CA cert")
+ }
+
+ // matching certificate public key vs private key
+ switch {
+ case ca.PublicKeyAlgorithm == x509.RSA:
+
+ var rsaPublicKey *rsa.PublicKey
+ var ok bool
+ if rsaPublicKey, ok = priv.Public().(*rsa.PublicKey); !ok {
+ return nil, cferr.New(cferr.PrivateKeyError, cferr.KeyMismatch)
+ }
+ if ca.PublicKey.(*rsa.PublicKey).N.Cmp(rsaPublicKey.N) != 0 {
+ return nil, cferr.New(cferr.PrivateKeyError, cferr.KeyMismatch)
+ }
+ case ca.PublicKeyAlgorithm == x509.ECDSA:
+ var ecdsaPublicKey *ecdsa.PublicKey
+ var ok bool
+ if ecdsaPublicKey, ok = priv.Public().(*ecdsa.PublicKey); !ok {
+ return nil, cferr.New(cferr.PrivateKeyError, cferr.KeyMismatch)
+ }
+ if ca.PublicKey.(*ecdsa.PublicKey).X.Cmp(ecdsaPublicKey.X) != 0 {
+ return nil, cferr.New(cferr.PrivateKeyError, cferr.KeyMismatch)
+ }
+ default:
+ return nil, cferr.New(cferr.PrivateKeyError, cferr.NotRSAOrECC)
+ }
+
+ req := csr.ExtractCertificateRequest(ca)
+
+ cert, _, err := NewFromSigner(req, priv)
+ return cert, err
+
+}
+
+// CAPolicy contains the CA issuing policy as default policy.
+var CAPolicy = func() *config.Signing {
+ return &config.Signing{
+ Default: &config.SigningProfile{
+ Usage: []string{"cert sign", "crl sign"},
+ ExpiryString: "43800h",
+ Expiry: 5 * helpers.OneYear,
+ CAConstraint: config.CAConstraint{IsCA: true},
+ },
+ }
+}
diff --git a/vendor/github.com/cloudflare/cfssl/log/log.go b/vendor/github.com/cloudflare/cfssl/log/log.go
new file mode 100644
index 0000000..956c9d4
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/log/log.go
@@ -0,0 +1,162 @@
+// Package log implements a wrapper around the Go standard library's
+// logging package. Clients should set the current log level; only
+// messages below that level will actually be logged. For example, if
+// Level is set to LevelWarning, only log messages at the Warning,
+// Error, and Critical levels will be logged.
+package log
+
+import (
+ "fmt"
+ "log"
+ "os"
+)
+
+// The following constants represent logging levels in increasing levels of seriousness.
+const (
+ // LevelDebug is the log level for Debug statements.
+ LevelDebug = iota
+ // LevelInfo is the log level for Info statements.
+ LevelInfo
+ // LevelWarning is the log level for Warning statements.
+ LevelWarning
+ // LevelError is the log level for Error statements.
+ LevelError
+ // LevelCritical is the log level for Critical statements.
+ LevelCritical
+ // LevelFatal is the log level for Fatal statements.
+ LevelFatal
+)
+
+var levelPrefix = [...]string{
+ LevelDebug: "DEBUG",
+ LevelInfo: "INFO",
+ LevelWarning: "WARNING",
+ LevelError: "ERROR",
+ LevelCritical: "CRITICAL",
+ LevelFatal: "FATAL",
+}
+
+// Level stores the current logging level.
+var Level = LevelInfo
+
+// SyslogWriter specifies the necessary methods for an alternate output
+// destination passed in via SetLogger.
+//
+// SyslogWriter is satisfied by *syslog.Writer.
+type SyslogWriter interface {
+ Debug(string)
+ Info(string)
+ Warning(string)
+ Err(string)
+ Crit(string)
+ Emerg(string)
+}
+
+// syslogWriter stores the SetLogger() parameter.
+var syslogWriter SyslogWriter
+
+// SetLogger sets the output used for output by this package.
+// A *syslog.Writer is a good choice for the logger parameter.
+// Call with a nil parameter to revert to default behavior.
+func SetLogger(logger SyslogWriter) {
+ syslogWriter = logger
+}
+
+func print(l int, msg string) {
+ if l >= Level {
+ if syslogWriter != nil {
+ switch l {
+ case LevelDebug:
+ syslogWriter.Debug(msg)
+ case LevelInfo:
+ syslogWriter.Info(msg)
+ case LevelWarning:
+ syslogWriter.Warning(msg)
+ case LevelError:
+ syslogWriter.Err(msg)
+ case LevelCritical:
+ syslogWriter.Crit(msg)
+ case LevelFatal:
+ syslogWriter.Emerg(msg)
+ }
+ } else {
+ log.Printf("[%s] %s", levelPrefix[l], msg)
+ }
+ }
+}
+
+func outputf(l int, format string, v []interface{}) {
+ print(l, fmt.Sprintf(format, v...))
+}
+
+func output(l int, v []interface{}) {
+ print(l, fmt.Sprint(v...))
+}
+
+// Fatalf logs a formatted message at the "fatal" level and then exits. The
+// arguments are handled in the same manner as fmt.Printf.
+func Fatalf(format string, v ...interface{}) {
+ outputf(LevelFatal, format, v)
+ os.Exit(1)
+}
+
+// Fatal logs its arguments at the "fatal" level and then exits.
+func Fatal(v ...interface{}) {
+ output(LevelFatal, v)
+ os.Exit(1)
+}
+
+// Criticalf logs a formatted message at the "critical" level. The
+// arguments are handled in the same manner as fmt.Printf.
+func Criticalf(format string, v ...interface{}) {
+ outputf(LevelCritical, format, v)
+}
+
+// Critical logs its arguments at the "critical" level.
+func Critical(v ...interface{}) {
+ output(LevelCritical, v)
+}
+
+// Errorf logs a formatted message at the "error" level. The arguments
+// are handled in the same manner as fmt.Printf.
+func Errorf(format string, v ...interface{}) {
+ outputf(LevelError, format, v)
+}
+
+// Error logs its arguments at the "error" level.
+func Error(v ...interface{}) {
+ output(LevelError, v)
+}
+
+// Warningf logs a formatted message at the "warning" level. The
+// arguments are handled in the same manner as fmt.Printf.
+func Warningf(format string, v ...interface{}) {
+ outputf(LevelWarning, format, v)
+}
+
+// Warning logs its arguments at the "warning" level.
+func Warning(v ...interface{}) {
+ output(LevelWarning, v)
+}
+
+// Infof logs a formatted message at the "info" level. The arguments
+// are handled in the same manner as fmt.Printf.
+func Infof(format string, v ...interface{}) {
+ outputf(LevelInfo, format, v)
+}
+
+// Info logs its arguments at the "info" level.
+func Info(v ...interface{}) {
+ output(LevelInfo, v)
+}
+
+// Debugf logs a formatted message at the "debug" level. The arguments
+// are handled in the same manner as fmt.Printf.
+func Debugf(format string, v ...interface{}) {
+ outputf(LevelDebug, format, v)
+}
+
+// Debug logs its arguments at the "debug" level.
+func Debug(v ...interface{}) {
+ output(LevelDebug, v)
+}
diff --git a/vendor/github.com/cloudflare/cfssl/ocsp/config/config.go b/vendor/github.com/cloudflare/cfssl/ocsp/config/config.go
new file mode 100644
index 0000000..a19b113
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/ocsp/config/config.go
@@ -0,0 +1,13 @@
+// Package config in the ocsp directory provides configuration data for an OCSP
+// signer.
+package config
+
+import "time"
+
+// Config contains configuration information required to set up an OCSP signer.
+type Config struct {
+ CACertFile string
+ ResponderCertFile string
+ KeyFile string
+ Interval time.Duration
+}
diff --git a/vendor/github.com/cloudflare/cfssl/signer/local/local.go b/vendor/github.com/cloudflare/cfssl/signer/local/local.go
new file mode 100644
index 0000000..6f2b5e5
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/signer/local/local.go
@@ -0,0 +1,469 @@
+// Package local implements certificate signature functionality for CFSSL.
+package local
+
+import (
+ "bytes"
+ "crypto"
+ "crypto/rand"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/asn1"
+ "encoding/binary"
+ "encoding/hex"
+ "encoding/pem"
+ "errors"
+ "io"
+ "io/ioutil"
+ "math/big"
+ "net"
+ "net/mail"
+ "os"
+
+ "github.com/cloudflare/cfssl/certdb"
+ "github.com/cloudflare/cfssl/config"
+ cferr "github.com/cloudflare/cfssl/errors"
+ "github.com/cloudflare/cfssl/helpers"
+ "github.com/cloudflare/cfssl/info"
+ "github.com/cloudflare/cfssl/log"
+ "github.com/cloudflare/cfssl/signer"
+ "github.com/google/certificate-transparency/go"
+ "github.com/google/certificate-transparency/go/client"
+)
+
+// Signer contains a signer that uses the standard library to
+// support both ECDSA and RSA CA keys.
+type Signer struct {
+ ca *x509.Certificate
+ priv crypto.Signer
+ policy *config.Signing
+ sigAlgo x509.SignatureAlgorithm
+ dbAccessor certdb.Accessor
+}
+
+// NewSigner creates a new Signer directly from a
+// private key and certificate, with optional policy.
+func NewSigner(priv crypto.Signer, cert *x509.Certificate, sigAlgo x509.SignatureAlgorithm, policy *config.Signing) (*Signer, error) {
+ if policy == nil {
+ policy = &config.Signing{
+ Profiles: map[string]*config.SigningProfile{},
+ Default: config.DefaultConfig()}
+ }
+
+ if !policy.Valid() {
+ return nil, cferr.New(cferr.PolicyError, cferr.InvalidPolicy)
+ }
+
+ return &Signer{
+ ca: cert,
+ priv: priv,
+ sigAlgo: sigAlgo,
+ policy: policy,
+ }, nil
+}
+
+// NewSignerFromFile generates a new local signer from a caFile
+// and a caKey file, both PEM encoded.
+func NewSignerFromFile(caFile, caKeyFile string, policy *config.Signing) (*Signer, error) {
+ log.Debug("Loading CA: ", caFile)
+ ca, err := ioutil.ReadFile(caFile)
+ if err != nil {
+ return nil, err
+ }
+ log.Debug("Loading CA key: ", caKeyFile)
+ cakey, err := ioutil.ReadFile(caKeyFile)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ReadFailed, err)
+ }
+
+ parsedCa, err := helpers.ParseCertificatePEM(ca)
+ if err != nil {
+ return nil, err
+ }
+
+ strPassword := os.Getenv("CFSSL_CA_PK_PASSWORD")
+ password := []byte(strPassword)
+ if strPassword == "" {
+ password = nil
+ }
+
+ priv, err := helpers.ParsePrivateKeyPEMWithPassword(cakey, password)
+ if err != nil {
+ log.Debug("Malformed private key %v", err)
+ return nil, err
+ }
+
+ return NewSigner(priv, parsedCa, signer.DefaultSigAlgo(priv), policy)
+}
+
+func (s *Signer) sign(template *x509.Certificate, profile *config.SigningProfile) (cert []byte, err error) {
+ var distPoints = template.CRLDistributionPoints
+ err = signer.FillTemplate(template, s.policy.Default, profile)
+ if distPoints != nil && len(distPoints) > 0 {
+ template.CRLDistributionPoints = distPoints
+ }
+ if err != nil {
+ return
+ }
+
+ var initRoot bool
+ if s.ca == nil {
+ if !template.IsCA {
+ err = cferr.New(cferr.PolicyError, cferr.InvalidRequest)
+ return
+ }
+ template.DNSNames = nil
+ template.EmailAddresses = nil
+ s.ca = template
+ initRoot = true
+ }
+
+ derBytes, err := x509.CreateCertificate(rand.Reader, template, s.ca, template.PublicKey, s.priv)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.Unknown, err)
+ }
+ if initRoot {
+ s.ca, err = x509.ParseCertificate(derBytes)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)
+ }
+ }
+
+ cert = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
+ log.Infof("signed certificate with serial number %d", template.SerialNumber)
+ return
+}
+
+// replaceSliceIfEmpty replaces the contents of replaced with newContents if
+// the slice referenced by replaced is empty
+func replaceSliceIfEmpty(replaced, newContents *[]string) {
+ if len(*replaced) == 0 {
+ *replaced = *newContents
+ }
+}
+
+// PopulateSubjectFromCSR has functionality similar to Name, except
+// it fills the fields of the resulting pkix.Name with req's if the
+// subject's corresponding fields are empty
+func PopulateSubjectFromCSR(s *signer.Subject, req pkix.Name) pkix.Name {
+ // if no subject, use req
+ if s == nil {
+ return req
+ }
+
+ name := s.Name()
+
+ if name.CommonName == "" {
+ name.CommonName = req.CommonName
+ }
+
+ replaceSliceIfEmpty(&name.Country, &req.Country)
+ replaceSliceIfEmpty(&name.Province, &req.Province)
+ replaceSliceIfEmpty(&name.Locality, &req.Locality)
+ replaceSliceIfEmpty(&name.Organization, &req.Organization)
+ replaceSliceIfEmpty(&name.OrganizationalUnit, &req.OrganizationalUnit)
+ if name.SerialNumber == "" {
+ name.SerialNumber = req.SerialNumber
+ }
+ return name
+}
+
+// OverrideHosts fills template's IPAddresses, EmailAddresses, and DNSNames with the
+// content of hosts, if it is not nil.
+func OverrideHosts(template *x509.Certificate, hosts []string) {
+ if hosts != nil {
+ template.IPAddresses = []net.IP{}
+ template.EmailAddresses = []string{}
+ template.DNSNames = []string{}
+ }
+
+ for i := range hosts {
+ if ip := net.ParseIP(hosts[i]); ip != nil {
+ template.IPAddresses = append(template.IPAddresses, ip)
+ } else if email, err := mail.ParseAddress(hosts[i]); err == nil && email != nil {
+ template.EmailAddresses = append(template.EmailAddresses, email.Address)
+ } else {
+ template.DNSNames = append(template.DNSNames, hosts[i])
+ }
+ }
+
+}
+
+// Sign signs a new certificate based on the PEM-encoded client
+// certificate or certificate request with the signing profile,
+// specified by profileName.
+func (s *Signer) Sign(req signer.SignRequest) (cert []byte, err error) {
+ profile, err := signer.Profile(s, req.Profile)
+ if err != nil {
+ return
+ }
+
+ block, _ := pem.Decode([]byte(req.Request))
+ if block == nil {
+ return nil, cferr.New(cferr.CSRError, cferr.DecodeFailed)
+ }
+
+ if block.Type != "NEW CERTIFICATE REQUEST" && block.Type != "CERTIFICATE REQUEST" {
+ return nil, cferr.Wrap(cferr.CSRError,
+ cferr.BadRequest, errors.New("not a certificate or csr"))
+ }
+
+ csrTemplate, err := signer.ParseCertificateRequest(s, block.Bytes)
+ if err != nil {
+ return nil, err
+ }
+
+ // Copy out only the fields from the CSR authorized by policy.
+ safeTemplate := x509.Certificate{}
+ // If the profile contains no explicit whitelist, assume that all fields
+ // should be copied from the CSR.
+ if profile.CSRWhitelist == nil {
+ safeTemplate = *csrTemplate
+ } else {
+ if profile.CSRWhitelist.Subject {
+ safeTemplate.Subject = csrTemplate.Subject
+ }
+ if profile.CSRWhitelist.PublicKeyAlgorithm {
+ safeTemplate.PublicKeyAlgorithm = csrTemplate.PublicKeyAlgorithm
+ }
+ if profile.CSRWhitelist.PublicKey {
+ safeTemplate.PublicKey = csrTemplate.PublicKey
+ }
+ if profile.CSRWhitelist.SignatureAlgorithm {
+ safeTemplate.SignatureAlgorithm = csrTemplate.SignatureAlgorithm
+ }
+ if profile.CSRWhitelist.DNSNames {
+ safeTemplate.DNSNames = csrTemplate.DNSNames
+ }
+ if profile.CSRWhitelist.IPAddresses {
+ safeTemplate.IPAddresses = csrTemplate.IPAddresses
+ }
+ if profile.CSRWhitelist.EmailAddresses {
+ safeTemplate.EmailAddresses = csrTemplate.EmailAddresses
+ }
+ }
+
+ if req.CRLOverride != "" {
+ safeTemplate.CRLDistributionPoints = []string{req.CRLOverride}
+ }
+
+ if safeTemplate.IsCA {
+ if !profile.CAConstraint.IsCA {
+ log.Error("local signer policy disallows issuing CA certificate")
+ return nil, cferr.New(cferr.PolicyError, cferr.InvalidRequest)
+ }
+
+ if s.ca != nil && s.ca.MaxPathLen > 0 {
+ if safeTemplate.MaxPathLen >= s.ca.MaxPathLen {
+ log.Error("local signer certificate disallows CA MaxPathLen extending")
+ // do not sign a cert with pathlen > current
+ return nil, cferr.New(cferr.PolicyError, cferr.InvalidRequest)
+ }
+ } else if s.ca != nil && s.ca.MaxPathLen == 0 && s.ca.MaxPathLenZero {
+ log.Error("local signer certificate disallows issuing CA certificate")
+ // signer has pathlen of 0, do not sign more intermediate CAs
+ return nil, cferr.New(cferr.PolicyError, cferr.InvalidRequest)
+ }
+ }
+
+ OverrideHosts(&safeTemplate, req.Hosts)
+ safeTemplate.Subject = PopulateSubjectFromCSR(req.Subject, safeTemplate.Subject)
+
+ // If there is a whitelist, ensure that both the Common Name and SAN DNSNames match
+ if profile.NameWhitelist != nil {
+ if safeTemplate.Subject.CommonName != "" {
+ if profile.NameWhitelist.Find([]byte(safeTemplate.Subject.CommonName)) == nil {
+ return nil, cferr.New(cferr.PolicyError, cferr.UnmatchedWhitelist)
+ }
+ }
+ for _, name := range safeTemplate.DNSNames {
+ if profile.NameWhitelist.Find([]byte(name)) == nil {
+ return nil, cferr.New(cferr.PolicyError, cferr.UnmatchedWhitelist)
+ }
+ }
+ for _, name := range safeTemplate.EmailAddresses {
+ if profile.NameWhitelist.Find([]byte(name)) == nil {
+ return nil, cferr.New(cferr.PolicyError, cferr.UnmatchedWhitelist)
+ }
+ }
+ }
+
+ if profile.ClientProvidesSerialNumbers {
+ if req.Serial == nil {
+ return nil, cferr.New(cferr.CertificateError, cferr.MissingSerial)
+ }
+ safeTemplate.SerialNumber = req.Serial
+ } else {
+ // RFC 5280 4.1.2.2:
+ // Certificate users MUST be able to handle serialNumber
+ // values up to 20 octets. Conforming CAs MUST NOT use
+ // serialNumber values longer than 20 octets.
+ //
+ // If CFSSL is providing the serial numbers, it makes
+ // sense to use the max supported size.
+ serialNumber := make([]byte, 20)
+ _, err = io.ReadFull(rand.Reader, serialNumber)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.Unknown, err)
+ }
+
+ // SetBytes interprets buf as the bytes of a big-endian
+ // unsigned integer. The leading byte should be masked
+ // off to ensure it isn't negative.
+ serialNumber[0] &= 0x7F
+
+ safeTemplate.SerialNumber = new(big.Int).SetBytes(serialNumber)
+ }
+
+ if len(req.Extensions) > 0 {
+ for _, ext := range req.Extensions {
+ oid := asn1.ObjectIdentifier(ext.ID)
+ if !profile.ExtensionWhitelist[oid.String()] {
+ return nil, cferr.New(cferr.CertificateError, cferr.InvalidRequest)
+ }
+
+ rawValue, err := hex.DecodeString(ext.Value)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CertificateError, cferr.InvalidRequest, err)
+ }
+
+ safeTemplate.ExtraExtensions = append(safeTemplate.ExtraExtensions, pkix.Extension{
+ Id: oid,
+ Critical: ext.Critical,
+ Value: rawValue,
+ })
+ }
+ }
+
+ var certTBS = safeTemplate
+
+ if len(profile.CTLogServers) > 0 {
+ // Add a poison extension which prevents validation
+ var poisonExtension = pkix.Extension{Id: signer.CTPoisonOID, Critical: true, Value: []byte{0x05, 0x00}}
+ var poisonedPreCert = certTBS
+ poisonedPreCert.ExtraExtensions = append(safeTemplate.ExtraExtensions, poisonExtension)
+ cert, err = s.sign(&poisonedPreCert, profile)
+ if err != nil {
+ return
+ }
+
+ derCert, _ := pem.Decode(cert)
+ prechain := []ct.ASN1Cert{derCert.Bytes, s.ca.Raw}
+ var sctList []ct.SignedCertificateTimestamp
+
+ for _, server := range profile.CTLogServers {
+ log.Infof("submitting poisoned precertificate to %s", server)
+ var ctclient = client.New(server, nil)
+ var resp *ct.SignedCertificateTimestamp
+ resp, err = ctclient.AddPreChain(prechain)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CTError, cferr.PrecertSubmissionFailed, err)
+ }
+ sctList = append(sctList, *resp)
+ }
+
+ var serializedSCTList []byte
+ serializedSCTList, err = serializeSCTList(sctList)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err)
+ }
+
+ // Serialize again as an octet string before embedding
+ serializedSCTList, err = asn1.Marshal(serializedSCTList)
+ if err != nil {
+ return nil, cferr.Wrap(cferr.CTError, cferr.Unknown, err)
+ }
+
+ var SCTListExtension = pkix.Extension{Id: signer.SCTListOID, Critical: false, Value: serializedSCTList}
+ certTBS.ExtraExtensions = append(certTBS.ExtraExtensions, SCTListExtension)
+ }
+ var signedCert []byte
+ signedCert, err = s.sign(&certTBS, profile)
+ if err != nil {
+ return nil, err
+ }
+
+ if s.dbAccessor != nil {
+ var certRecord = certdb.CertificateRecord{
+ Serial: certTBS.SerialNumber.String(),
+ // this relies on the specific behavior of x509.CreateCertificate
+ // which updates certTBS AuthorityKeyId from the signer's SubjectKeyId
+ AKI: hex.EncodeToString(certTBS.AuthorityKeyId),
+ CALabel: req.Label,
+ Status: "good",
+ Expiry: certTBS.NotAfter,
+ PEM: string(signedCert),
+ }
+
+ err = s.dbAccessor.InsertCertificate(certRecord)
+ if err != nil {
+ return nil, err
+ }
+ log.Debug("saved certificate with serial number ", certTBS.SerialNumber)
+ }
+
+ return signedCert, nil
+}
+
+func serializeSCTList(sctList []ct.SignedCertificateTimestamp) ([]byte, error) {
+ var buf bytes.Buffer
+ for _, sct := range sctList {
+ sct, err := ct.SerializeSCT(sct)
+ if err != nil {
+ return nil, err
+ }
+ binary.Write(&buf, binary.BigEndian, uint16(len(sct)))
+ buf.Write(sct)
+ }
+
+ var sctListLengthField = make([]byte, 2)
+ binary.BigEndian.PutUint16(sctListLengthField, uint16(buf.Len()))
+ return bytes.Join([][]byte{sctListLengthField, buf.Bytes()}, nil), nil
+}
+
+// Info return a populated info.Resp struct or an error.
+func (s *Signer) Info(req info.Req) (resp *info.Resp, err error) {
+ cert, err := s.Certificate(req.Label, req.Profile)
+ if err != nil {
+ return
+ }
+
+ profile, err := signer.Profile(s, req.Profile)
+ if err != nil {
+ return
+ }
+
+ resp = new(info.Resp)
+ if cert.Raw != nil {
+ resp.Certificate = string(bytes.TrimSpace(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})))
+ }
+ resp.Usage = profile.Usage
+ resp.ExpiryString = profile.ExpiryString
+
+ return
+}
+
+// SigAlgo returns the RSA signer's signature algorithm.
+func (s *Signer) SigAlgo() x509.SignatureAlgorithm {
+ return s.sigAlgo
+}
+
+// Certificate returns the signer's certificate.
+func (s *Signer) Certificate(label, profile string) (*x509.Certificate, error) {
+ cert := *s.ca
+ return &cert, nil
+}
+
+// SetPolicy sets the signer's signature policy.
+func (s *Signer) SetPolicy(policy *config.Signing) {
+ s.policy = policy
+}
+
+// SetDBAccessor sets the signers' cert db accessor
+func (s *Signer) SetDBAccessor(dba certdb.Accessor) {
+ s.dbAccessor = dba
+}
+
+// Policy returns the signer's policy.
+func (s *Signer) Policy() *config.Signing {
+ return s.policy
+}
diff --git a/vendor/github.com/cloudflare/cfssl/signer/signer.go b/vendor/github.com/cloudflare/cfssl/signer/signer.go
new file mode 100644
index 0000000..a34fa45
--- /dev/null
+++ b/vendor/github.com/cloudflare/cfssl/signer/signer.go
@@ -0,0 +1,412 @@
+// Package signer implements certificate signature functionality for CFSSL.
+package signer
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rsa"
+ "crypto/sha1"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/asn1"
+ "errors"
+ "math/big"
+ "strings"
+ "time"
+
+ "github.com/cloudflare/cfssl/certdb"
+ "github.com/cloudflare/cfssl/config"
+ "github.com/cloudflare/cfssl/csr"
+ cferr "github.com/cloudflare/cfssl/errors"
+ "github.com/cloudflare/cfssl/helpers"
+ "github.com/cloudflare/cfssl/info"
+)
+
+// Subject contains the information that should be used to override the
+// subject information when signing a certificate.
+type Subject struct {
+ CN string
+ Names []csr.Name `json:"names"`
+ SerialNumber string
+}
+
+// Extension represents a raw extension to be included in the certificate. The
+// "value" field must be hex encoded.
+type Extension struct {
+ ID config.OID `json:"id"`
+ Critical bool `json:"critical"`
+ Value string `json:"value"`
+}
+
+// SignRequest stores a signature request, which contains the hostname,
+// the CSR, optional subject information, and the signature profile.
+//
+// Extensions provided in the signRequest are copied into the certificate, as
+// long as they are in the ExtensionWhitelist for the signer's policy.
+// Extensions requested in the CSR are ignored, except for those processed by
+// ParseCertificateRequest (mainly subjectAltName).
+type SignRequest struct {
+ Hosts []string `json:"hosts"`
+ Request string `json:"certificate_request"`
+ Subject *Subject `json:"subject,omitempty"`
+ Profile string `json:"profile"`
+ CRLOverride string `json:"crl_override"`
+ Label string `json:"label"`
+ Serial *big.Int `json:"serial,omitempty"`
+ Extensions []Extension `json:"extensions,omitempty"`
+}
+
+// appendIf appends to a if s is not an empty string.
+func appendIf(s string, a *[]string) {
+ if s != "" {
+ *a = append(*a, s)
+ }
+}
+
+// Name returns the PKIX name for the subject.
+func (s *Subject) Name() pkix.Name {
+ var name pkix.Name
+ name.CommonName = s.CN
+
+ for _, n := range s.Names {
+ appendIf(n.C, &name.Country)
+ appendIf(n.ST, &name.Province)
+ appendIf(n.L, &name.Locality)
+ appendIf(n.O, &name.Organization)
+ appendIf(n.OU, &name.OrganizationalUnit)
+ }
+ name.SerialNumber = s.SerialNumber
+ return name
+}
+
+// SplitHosts takes a comma-spearated list of hosts and returns a slice
+// with the hosts split
+func SplitHosts(hostList string) []string {
+ if hostList == "" {
+ return nil
+ }
+
+ return strings.Split(hostList, ",")
+}
+
+// A Signer contains a CA's certificate and private key for signing
+// certificates, a Signing policy to refer to and a SignatureAlgorithm.
+type Signer interface {
+ Info(info.Req) (*info.Resp, error)
+ Policy() *config.Signing
+ SetDBAccessor(certdb.Accessor)
+ SetPolicy(*config.Signing)
+ SigAlgo() x509.SignatureAlgorithm
+ Sign(req SignRequest) (cert []byte, err error)
+}
+
+// Profile gets the specific profile from the signer
+func Profile(s Signer, profile string) (*config.SigningProfile, error) {
+ var p *config.SigningProfile
+ policy := s.Policy()
+ if policy != nil && policy.Profiles != nil && profile != "" {
+ p = policy.Profiles[profile]
+ }
+
+ if p == nil && policy != nil {
+ p = policy.Default
+ }
+
+ if p == nil {
+ return nil, cferr.Wrap(cferr.APIClientError, cferr.ClientHTTPError, errors.New("profile must not be nil"))
+ }
+ return p, nil
+}
+
+// DefaultSigAlgo returns an appropriate X.509 signature algorithm given
+// the CA's private key.
+func DefaultSigAlgo(priv crypto.Signer) x509.SignatureAlgorithm {
+ pub := priv.Public()
+ switch pub := pub.(type) {
+ case *rsa.PublicKey:
+ keySize := pub.N.BitLen()
+ switch {
+ case keySize >= 4096:
+ return x509.SHA512WithRSA
+ case keySize >= 3072:
+ return x509.SHA384WithRSA
+ case keySize >= 2048:
+ return x509.SHA256WithRSA
+ default:
+ return x509.SHA1WithRSA
+ }
+ case *ecdsa.PublicKey:
+ switch pub.Curve {
+ case elliptic.P256():
+ return x509.ECDSAWithSHA256
+ case elliptic.P384():
+ return x509.ECDSAWithSHA384
+ case elliptic.P521():
+ return x509.ECDSAWithSHA512
+ default:
+ return x509.ECDSAWithSHA1
+ }
+ default:
+ return x509.UnknownSignatureAlgorithm
+ }
+}
+
+// ParseCertificateRequest takes an incoming certificate request and
+// builds a certificate template from it.
+func ParseCertificateRequest(s Signer, csrBytes []byte) (template *x509.Certificate, err error) {
+ csrv, err := x509.ParseCertificateRequest(csrBytes)
+ if err != nil {
+ err = cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err)
+ return
+ }
+
+ err = helpers.CheckSignature(csrv, csrv.SignatureAlgorithm, csrv.RawTBSCertificateRequest, csrv.Signature)
+ if err != nil {
+ err = cferr.Wrap(cferr.CSRError, cferr.KeyMismatch, err)
+ return
+ }
+
+ template = &x509.Certificate{
+ Subject: csrv.Subject,
+ PublicKeyAlgorithm: csrv.PublicKeyAlgorithm,
+ PublicKey: csrv.PublicKey,
+ SignatureAlgorithm: s.SigAlgo(),
+ DNSNames: csrv.DNSNames,
+ IPAddresses: csrv.IPAddresses,
+ EmailAddresses: csrv.EmailAddresses,
+ }
+
+ for _, val := range csrv.Extensions {
+ // Check the CSR for the X.509 BasicConstraints (RFC 5280, 4.2.1.9)
+ // extension and append to template if necessary
+ if val.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 19}) {
+ var constraints csr.BasicConstraints
+ var rest []byte
+
+ if rest, err = asn1.Unmarshal(val.Value, &constraints); err != nil {
+ return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err)
+ } else if len(rest) != 0 {
+ return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, errors.New("x509: trailing data after X.509 BasicConstraints"))
+ }
+
+ template.BasicConstraintsValid = true
+ template.IsCA = constraints.IsCA
+ template.MaxPathLen = constraints.MaxPathLen
+ template.MaxPathLenZero = template.MaxPathLen == 0
+ }
+ }
+
+ return
+}
+
+type subjectPublicKeyInfo struct {
+ Algorithm pkix.AlgorithmIdentifier
+ SubjectPublicKey asn1.BitString
+}
+
+// ComputeSKI derives an SKI from the certificate's public key in a
+// standard manner. This is done by computing the SHA-1 digest of the
+// SubjectPublicKeyInfo component of the certificate.
+func ComputeSKI(template *x509.Certificate) ([]byte, error) {
+ pub := template.PublicKey
+ encodedPub, err := x509.MarshalPKIXPublicKey(pub)
+ if err != nil {
+ return nil, err
+ }
+
+ var subPKI subjectPublicKeyInfo
+ _, err = asn1.Unmarshal(encodedPub, &subPKI)
+ if err != nil {
+ return nil, err
+ }
+
+ pubHash := sha1.Sum(subPKI.SubjectPublicKey.Bytes)
+ return pubHash[:], nil
+}
+
+// FillTemplate is a utility function that tries to load as much of
+// the certificate template as possible from the profiles and current
+// template. It fills in the key uses, expiration, revocation URLs
+// and SKI.
+func FillTemplate(template *x509.Certificate, defaultProfile, profile *config.SigningProfile) error {
+ ski, err := ComputeSKI(template)
+
+ var (
+ eku []x509.ExtKeyUsage
+ ku x509.KeyUsage
+ backdate time.Duration
+ expiry time.Duration
+ notBefore time.Time
+ notAfter time.Time
+ crlURL, ocspURL string
+ issuerURL = profile.IssuerURL
+ )
+
+ // The third value returned from Usages is a list of unknown key usages.
+ // This should be used when validating the profile at load, and isn't used
+ // here.
+ ku, eku, _ = profile.Usages()
+ if profile.IssuerURL == nil {
+ issuerURL = defaultProfile.IssuerURL
+ }
+
+ if ku == 0 && len(eku) == 0 {
+ return cferr.New(cferr.PolicyError, cferr.NoKeyUsages)
+ }
+
+ if expiry = profile.Expiry; expiry == 0 {
+ expiry = defaultProfile.Expiry
+ }
+
+ if crlURL = profile.CRL; crlURL == "" {
+ crlURL = defaultProfile.CRL
+ }
+ if ocspURL = profile.OCSP; ocspURL == "" {
+ ocspURL = defaultProfile.OCSP
+ }
+ if backdate = profile.Backdate; backdate == 0 {
+ backdate = -5 * time.Minute
+ } else {
+ backdate = -1 * profile.Backdate
+ }
+
+ if !profile.NotBefore.IsZero() {
+ notBefore = profile.NotBefore.UTC()
+ } else {
+ notBefore = time.Now().Round(time.Minute).Add(backdate).UTC()
+ }
+
+ if !profile.NotAfter.IsZero() {
+ notAfter = profile.NotAfter.UTC()
+ } else {
+ notAfter = notBefore.Add(expiry).UTC()
+ }
+
+ template.NotBefore = notBefore
+ template.NotAfter = notAfter
+ template.KeyUsage = ku
+ template.ExtKeyUsage = eku
+ template.BasicConstraintsValid = true
+ template.IsCA = profile.CAConstraint.IsCA
+ if template.IsCA {
+ template.MaxPathLen = profile.CAConstraint.MaxPathLen
+ if template.MaxPathLen == 0 {
+ template.MaxPathLenZero = profile.CAConstraint.MaxPathLenZero
+ }
+ template.DNSNames = nil
+ template.EmailAddresses = nil
+ }
+ template.SubjectKeyId = ski
+
+ if ocspURL != "" {
+ template.OCSPServer = []string{ocspURL}
+ }
+ if crlURL != "" {
+ template.CRLDistributionPoints = []string{crlURL}
+ }
+
+ if len(issuerURL) != 0 {
+ template.IssuingCertificateURL = issuerURL
+ }
+ if len(profile.Policies) != 0 {
+ err = addPolicies(template, profile.Policies)
+ if err != nil {
+ return cferr.Wrap(cferr.PolicyError, cferr.InvalidPolicy, err)
+ }
+ }
+ if profile.OCSPNoCheck {
+ ocspNoCheckExtension := pkix.Extension{
+ Id: asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1, 5},
+ Critical: false,
+ Value: []byte{0x05, 0x00},
+ }
+ template.ExtraExtensions = append(template.ExtraExtensions, ocspNoCheckExtension)
+ }
+
+ return nil
+}
+
+type policyInformation struct {
+ PolicyIdentifier asn1.ObjectIdentifier
+ Qualifiers []interface{} `asn1:"tag:optional,omitempty"`
+}
+
+type cpsPolicyQualifier struct {
+ PolicyQualifierID asn1.ObjectIdentifier
+ Qualifier string `asn1:"tag:optional,ia5"`
+}
+
+type userNotice struct {
+ ExplicitText string `asn1:"tag:optional,utf8"`
+}
+type userNoticePolicyQualifier struct {
+ PolicyQualifierID asn1.ObjectIdentifier
+ Qualifier userNotice
+}
+
+var (
+ // Per https://tools.ietf.org/html/rfc3280.html#page-106, this represents:
+ // iso(1) identified-organization(3) dod(6) internet(1) security(5)
+ // mechanisms(5) pkix(7) id-qt(2) id-qt-cps(1)
+ iDQTCertificationPracticeStatement = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 1}
+ // iso(1) identified-organization(3) dod(6) internet(1) security(5)
+ // mechanisms(5) pkix(7) id-qt(2) id-qt-unotice(2)
+ iDQTUserNotice = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 2}
+
+ // CTPoisonOID is the object ID of the critical poison extension for precertificates
+ // https://tools.ietf.org/html/rfc6962#page-9
+ CTPoisonOID = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3}
+
+ // SCTListOID is the object ID for the Signed Certificate Timestamp certificate extension
+ // https://tools.ietf.org/html/rfc6962#page-14
+ SCTListOID = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2}
+)
+
+// addPolicies adds Certificate Policies and optional Policy Qualifiers to a
+// certificate, based on the input config. Go's x509 library allows setting
+// Certificate Policies easily, but does not support nested Policy Qualifiers
+// under those policies. So we need to construct the ASN.1 structure ourselves.
+func addPolicies(template *x509.Certificate, policies []config.CertificatePolicy) error {
+ asn1PolicyList := []policyInformation{}
+
+ for _, policy := range policies {
+ pi := policyInformation{
+ // The PolicyIdentifier is an OID assigned to a given issuer.
+ PolicyIdentifier: asn1.ObjectIdentifier(policy.ID),
+ }
+ for _, qualifier := range policy.Qualifiers {
+ switch qualifier.Type {
+ case "id-qt-unotice":
+ pi.Qualifiers = append(pi.Qualifiers,
+ userNoticePolicyQualifier{
+ PolicyQualifierID: iDQTUserNotice,
+ Qualifier: userNotice{
+ ExplicitText: qualifier.Value,
+ },
+ })
+ case "id-qt-cps":
+ pi.Qualifiers = append(pi.Qualifiers,
+ cpsPolicyQualifier{
+ PolicyQualifierID: iDQTCertificationPracticeStatement,
+ Qualifier: qualifier.Value,
+ })
+ default:
+ return errors.New("Invalid qualifier type in Policies " + qualifier.Type)
+ }
+ }
+ asn1PolicyList = append(asn1PolicyList, pi)
+ }
+
+ asn1Bytes, err := asn1.Marshal(asn1PolicyList)
+ if err != nil {
+ return err
+ }
+
+ template.ExtraExtensions = append(template.ExtraExtensions, pkix.Extension{
+ Id: asn1.ObjectIdentifier{2, 5, 29, 32},
+ Critical: false,
+ Value: asn1Bytes,
+ })
+ return nil
+}
diff --git a/vendor/github.com/cloudfoundry/gosigar/LICENSE b/vendor/github.com/cloudfoundry/gosigar/LICENSE
new file mode 100644
index 0000000..11069ed
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/vendor/github.com/cloudfoundry/gosigar/NOTICE b/vendor/github.com/cloudfoundry/gosigar/NOTICE
new file mode 100644
index 0000000..fda553b
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/NOTICE
@@ -0,0 +1,9 @@
+Copyright (c) [2009-2011] VMware, Inc. All Rights Reserved.
+
+This product is licensed to you under the Apache License, Version 2.0 (the "License").
+You may not use this product except in compliance with the License.
+
+This product includes a number of subcomponents with
+separate copyright notices and license terms. Your use of these
+subcomponents is subject to the terms and conditions of the
+subcomponent's license, as noted in the LICENSE file. \ No newline at end of file
diff --git a/vendor/github.com/cloudfoundry/gosigar/README.md b/vendor/github.com/cloudfoundry/gosigar/README.md
new file mode 100644
index 0000000..90d51f9
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/README.md
@@ -0,0 +1,22 @@
+# Go sigar
+
+## Overview
+
+Go sigar is a golang implementation of the
+[sigar API](https://github.com/hyperic/sigar). The Go version of
+sigar has a very similar interface, but is being written from scratch
+in pure go/cgo, rather than cgo bindings for libsigar.
+
+## Test drive
+
+ $ go get github.com/cloudfoundry/gosigar
+ $ cd $GOPATH/src/github.com/cloudfoundry/gosigar/examples
+ $ go run uptime.go
+
+## Supported platforms
+
+Currently targeting modern flavors of darwin and linux.
+
+## License
+
+Apache 2.0
diff --git a/vendor/github.com/cloudfoundry/gosigar/concrete_sigar.go b/vendor/github.com/cloudfoundry/gosigar/concrete_sigar.go
new file mode 100644
index 0000000..0e80aa4
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/concrete_sigar.go
@@ -0,0 +1,69 @@
+package sigar
+
+import (
+ "time"
+)
+
+type ConcreteSigar struct{}
+
+func (c *ConcreteSigar) CollectCpuStats(collectionInterval time.Duration) (<-chan Cpu, chan<- struct{}) {
+ // samplesCh is buffered to 1 value to immediately return first CPU sample
+ samplesCh := make(chan Cpu, 1)
+
+ stopCh := make(chan struct{})
+
+ go func() {
+ var cpuUsage Cpu
+
+ // Immediately provide non-delta value.
+ // samplesCh is buffered to 1 value, so it will not block.
+ cpuUsage.Get()
+ samplesCh <- cpuUsage
+
+ ticker := time.NewTicker(collectionInterval)
+
+ for {
+ select {
+ case <-ticker.C:
+ previousCpuUsage := cpuUsage
+
+ cpuUsage.Get()
+
+ select {
+ case samplesCh <- cpuUsage.Delta(previousCpuUsage):
+ default:
+ // Include default to avoid channel blocking
+ }
+
+ case <-stopCh:
+ return
+ }
+ }
+ }()
+
+ return samplesCh, stopCh
+}
+
+func (c *ConcreteSigar) GetLoadAverage() (LoadAverage, error) {
+ l := LoadAverage{}
+ err := l.Get()
+ return l, err
+}
+
+func (c *ConcreteSigar) GetMem() (Mem, error) {
+ m := Mem{}
+ err := m.Get()
+ return m, err
+}
+
+func (c *ConcreteSigar) GetSwap() (Swap, error) {
+ s := Swap{}
+ err := s.Get()
+ return s, err
+}
+
+func (c *ConcreteSigar) GetFileSystemUsage(path string) (FileSystemUsage, error) {
+ f := FileSystemUsage{}
+ err := f.Get(path)
+ return f, err
+}
diff --git a/vendor/github.com/cloudfoundry/gosigar/sigar_darwin.go b/vendor/github.com/cloudfoundry/gosigar/sigar_darwin.go
new file mode 100644
index 0000000..e3a8c4b
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/sigar_darwin.go
@@ -0,0 +1,467 @@
+// Copyright (c) 2012 VMware, Inc.
+
+package sigar
+
+/*
+#include <stdlib.h>
+#include <sys/sysctl.h>
+#include <sys/mount.h>
+#include <mach/mach_init.h>
+#include <mach/mach_host.h>
+#include <mach/host_info.h>
+#include <libproc.h>
+#include <mach/processor_info.h>
+#include <mach/vm_map.h>
+*/
+import "C"
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "syscall"
+ "time"
+ "unsafe"
+)
+
+func (self *LoadAverage) Get() error {
+ avg := []C.double{0, 0, 0}
+
+ C.getloadavg(&avg[0], C.int(len(avg)))
+
+ self.One = float64(avg[0])
+ self.Five = float64(avg[1])
+ self.Fifteen = float64(avg[2])
+
+ return nil
+}
+
+func (self *Uptime) Get() error {
+ tv := syscall.Timeval32{}
+
+ if err := sysctlbyname("kern.boottime", &tv); err != nil {
+ return err
+ }
+
+ self.Length = time.Since(time.Unix(int64(tv.Sec), int64(tv.Usec)*1000)).Seconds()
+
+ return nil
+}
+
+func (self *Mem) Get() error {
+ var vmstat C.vm_statistics_data_t
+
+ if err := sysctlbyname("hw.memsize", &self.Total); err != nil {
+ return err
+ }
+
+ if err := vm_info(&vmstat); err != nil {
+ return err
+ }
+
+ kern := uint64(vmstat.inactive_count) << 12
+ self.Free = uint64(vmstat.free_count) << 12
+
+ self.Used = self.Total - self.Free
+ self.ActualFree = self.Free + kern
+ self.ActualUsed = self.Used - kern
+
+ return nil
+}
+
+type xsw_usage struct {
+ Total, Avail, Used uint64
+}
+
+func (self *Swap) Get() error {
+ sw_usage := xsw_usage{}
+
+ if err := sysctlbyname("vm.swapusage", &sw_usage); err != nil {
+ return err
+ }
+
+ self.Total = sw_usage.Total
+ self.Used = sw_usage.Used
+ self.Free = sw_usage.Avail
+
+ return nil
+}
+
+func (self *Cpu) Get() error {
+ var count C.mach_msg_type_number_t = C.HOST_CPU_LOAD_INFO_COUNT
+ var cpuload C.host_cpu_load_info_data_t
+
+ status := C.host_statistics(C.host_t(C.mach_host_self()),
+ C.HOST_CPU_LOAD_INFO,
+ C.host_info_t(unsafe.Pointer(&cpuload)),
+ &count)
+
+ if status != C.KERN_SUCCESS {
+ return fmt.Errorf("host_statistics error=%d", status)
+ }
+
+ self.User = uint64(cpuload.cpu_ticks[C.CPU_STATE_USER])
+ self.Sys = uint64(cpuload.cpu_ticks[C.CPU_STATE_SYSTEM])
+ self.Idle = uint64(cpuload.cpu_ticks[C.CPU_STATE_IDLE])
+ self.Nice = uint64(cpuload.cpu_ticks[C.CPU_STATE_NICE])
+
+ return nil
+}
+
+func (self *CpuList) Get() error {
+ var count C.mach_msg_type_number_t
+ var cpuload *C.processor_cpu_load_info_data_t
+ var ncpu C.natural_t
+
+ status := C.host_processor_info(C.host_t(C.mach_host_self()),
+ C.PROCESSOR_CPU_LOAD_INFO,
+ &ncpu,
+ (*C.processor_info_array_t)(unsafe.Pointer(&cpuload)),
+ &count)
+
+ if status != C.KERN_SUCCESS {
+ return fmt.Errorf("host_processor_info error=%d", status)
+ }
+
+ // jump through some cgo casting hoops and ensure we properly free
+ // the memory that cpuload points to
+ target := C.vm_map_t(C.mach_task_self_)
+ address := C.vm_address_t(uintptr(unsafe.Pointer(cpuload)))
+ defer C.vm_deallocate(target, address, C.vm_size_t(ncpu))
+
+ // the body of struct processor_cpu_load_info
+ // aka processor_cpu_load_info_data_t
+ var cpu_ticks [C.CPU_STATE_MAX]uint32
+
+ // copy the cpuload array to a []byte buffer
+ // where we can binary.Read the data
+ size := int(ncpu) * binary.Size(cpu_ticks)
+ buf := C.GoBytes(unsafe.Pointer(cpuload), C.int(size))
+
+ bbuf := bytes.NewBuffer(buf)
+
+ self.List = make([]Cpu, 0, ncpu)
+
+ for i := 0; i < int(ncpu); i++ {
+ cpu := Cpu{}
+
+ err := binary.Read(bbuf, binary.LittleEndian, &cpu_ticks)
+ if err != nil {
+ return err
+ }
+
+ cpu.User = uint64(cpu_ticks[C.CPU_STATE_USER])
+ cpu.Sys = uint64(cpu_ticks[C.CPU_STATE_SYSTEM])
+ cpu.Idle = uint64(cpu_ticks[C.CPU_STATE_IDLE])
+ cpu.Nice = uint64(cpu_ticks[C.CPU_STATE_NICE])
+
+ self.List = append(self.List, cpu)
+ }
+
+ return nil
+}
+
+func (self *FileSystemList) Get() error {
+ num, err := getfsstat(nil, C.MNT_NOWAIT)
+ if num < 0 {
+ return err
+ }
+
+ buf := make([]syscall.Statfs_t, num)
+
+ num, err = getfsstat(buf, C.MNT_NOWAIT)
+ if err != nil {
+ return err
+ }
+
+ fslist := make([]FileSystem, 0, num)
+
+ for i := 0; i < num; i++ {
+ fs := FileSystem{}
+
+ fs.DirName = bytePtrToString(&buf[i].Mntonname[0])
+ fs.DevName = bytePtrToString(&buf[i].Mntfromname[0])
+ fs.SysTypeName = bytePtrToString(&buf[i].Fstypename[0])
+
+ fslist = append(fslist, fs)
+ }
+
+ self.List = fslist
+
+ return err
+}
+
+func (self *ProcList) Get() error {
+ n := C.proc_listpids(C.PROC_ALL_PIDS, 0, nil, 0)
+ if n <= 0 {
+ return syscall.EINVAL
+ }
+ buf := make([]byte, n)
+ n = C.proc_listpids(C.PROC_ALL_PIDS, 0, unsafe.Pointer(&buf[0]), n)
+ if n <= 0 {
+ return syscall.ENOMEM
+ }
+
+ var pid int32
+ num := int(n) / binary.Size(pid)
+ list := make([]int, 0, num)
+ bbuf := bytes.NewBuffer(buf)
+
+ for i := 0; i < num; i++ {
+ if err := binary.Read(bbuf, binary.LittleEndian, &pid); err != nil {
+ return err
+ }
+ if pid == 0 {
+ continue
+ }
+
+ list = append(list, int(pid))
+ }
+
+ self.List = list
+
+ return nil
+}
+
+func (self *ProcState) Get(pid int) error {
+ info := C.struct_proc_taskallinfo{}
+
+ if err := task_info(pid, &info); err != nil {
+ return err
+ }
+
+ self.Name = C.GoString(&info.pbsd.pbi_comm[0])
+
+ switch info.pbsd.pbi_status {
+ case C.SIDL:
+ self.State = RunStateIdle
+ case C.SRUN:
+ self.State = RunStateRun
+ case C.SSLEEP:
+ self.State = RunStateSleep
+ case C.SSTOP:
+ self.State = RunStateStop
+ case C.SZOMB:
+ self.State = RunStateZombie
+ default:
+ self.State = RunStateUnknown
+ }
+
+ self.Ppid = int(info.pbsd.pbi_ppid)
+
+ self.Tty = int(info.pbsd.e_tdev)
+
+ self.Priority = int(info.ptinfo.pti_priority)
+
+ self.Nice = int(info.pbsd.pbi_nice)
+
+ return nil
+}
+
+func (self *ProcMem) Get(pid int) error {
+ info := C.struct_proc_taskallinfo{}
+
+ if err := task_info(pid, &info); err != nil {
+ return err
+ }
+
+ self.Size = uint64(info.ptinfo.pti_virtual_size)
+ self.Resident = uint64(info.ptinfo.pti_resident_size)
+ self.PageFaults = uint64(info.ptinfo.pti_faults)
+
+ return nil
+}
+
+func (self *ProcTime) Get(pid int) error {
+ info := C.struct_proc_taskallinfo{}
+
+ if err := task_info(pid, &info); err != nil {
+ return err
+ }
+
+ self.User =
+ uint64(info.ptinfo.pti_total_user) / uint64(time.Millisecond)
+
+ self.Sys =
+ uint64(info.ptinfo.pti_total_system) / uint64(time.Millisecond)
+
+ self.Total = self.User + self.Sys
+
+ self.StartTime = (uint64(info.pbsd.pbi_start_tvsec) * 1000) +
+ (uint64(info.pbsd.pbi_start_tvusec) / 1000)
+
+ return nil
+}
+
+func (self *ProcArgs) Get(pid int) error {
+ var args []string
+
+ argv := func(arg string) {
+ args = append(args, arg)
+ }
+
+ err := kern_procargs(pid, nil, argv, nil)
+
+ self.List = args
+
+ return err
+}
+
+func (self *ProcExe) Get(pid int) error {
+ exe := func(arg string) {
+ self.Name = arg
+ }
+
+ return kern_procargs(pid, exe, nil, nil)
+}
+
+// wrapper around sysctl KERN_PROCARGS2
+// callbacks params are optional,
+// up to the caller as to which pieces of data they want
+func kern_procargs(pid int,
+ exe func(string),
+ argv func(string),
+ env func(string, string)) error {
+
+ mib := []C.int{C.CTL_KERN, C.KERN_PROCARGS2, C.int(pid)}
+ argmax := uintptr(C.ARG_MAX)
+ buf := make([]byte, argmax)
+ err := sysctl(mib, &buf[0], &argmax, nil, 0)
+ if err != nil {
+ return nil
+ }
+
+ bbuf := bytes.NewBuffer(buf)
+ bbuf.Truncate(int(argmax))
+
+ var argc int32
+ binary.Read(bbuf, binary.LittleEndian, &argc)
+
+ path, err := bbuf.ReadBytes(0)
+ if exe != nil {
+ exe(string(chop(path)))
+ }
+
+ // skip trailing \0's
+ for {
+ c, _ := bbuf.ReadByte()
+ if c != 0 {
+ bbuf.UnreadByte()
+ break // start of argv[0]
+ }
+ }
+
+ for i := 0; i < int(argc); i++ {
+ arg, err := bbuf.ReadBytes(0)
+ if err == io.EOF {
+ break
+ }
+ if argv != nil {
+ argv(string(chop(arg)))
+ }
+ }
+
+ if env == nil {
+ return nil
+ }
+
+ delim := []byte{61} // "="
+
+ for {
+ line, err := bbuf.ReadBytes(0)
+ if err == io.EOF || line[0] == 0 {
+ break
+ }
+ pair := bytes.SplitN(chop(line), delim, 2)
+ env(string(pair[0]), string(pair[1]))
+ }
+
+ return nil
+}
+
+// XXX copied from zsyscall_darwin_amd64.go
+func sysctl(mib []C.int, old *byte, oldlen *uintptr,
+ new *byte, newlen uintptr) (err error) {
+ var p0 unsafe.Pointer
+ p0 = unsafe.Pointer(&mib[0])
+ _, _, e1 := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(p0),
+ uintptr(len(mib)),
+ uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)),
+ uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func vm_info(vmstat *C.vm_statistics_data_t) error {
+ var count C.mach_msg_type_number_t = C.HOST_VM_INFO_COUNT
+
+ status := C.host_statistics(
+ C.host_t(C.mach_host_self()),
+ C.HOST_VM_INFO,
+ C.host_info_t(unsafe.Pointer(vmstat)),
+ &count)
+
+ if status != C.KERN_SUCCESS {
+ return fmt.Errorf("host_statistics=%d", status)
+ }
+
+ return nil
+}
+
+// generic Sysctl buffer unmarshalling
+func sysctlbyname(name string, data interface{}) (err error) {
+ val, err := syscall.Sysctl(name)
+ if err != nil {
+ return err
+ }
+
+ buf := []byte(val)
+
+ switch v := data.(type) {
+ case *uint64:
+ *v = *(*uint64)(unsafe.Pointer(&buf[0]))
+ return
+ }
+
+ bbuf := bytes.NewBuffer([]byte(val))
+ return binary.Read(bbuf, binary.LittleEndian, data)
+}
+
+// syscall.Getfsstat() wrapper is broken, roll our own to workaround.
+func getfsstat(buf []syscall.Statfs_t, flags int) (n int, err error) {
+ var ptr uintptr
+ var size uintptr
+
+ if len(buf) > 0 {
+ ptr = uintptr(unsafe.Pointer(&buf[0]))
+ size = unsafe.Sizeof(buf[0]) * uintptr(len(buf))
+ } else {
+ ptr = uintptr(0)
+ size = uintptr(0)
+ }
+
+ trap := uintptr(syscall.SYS_GETFSSTAT64)
+ ret, _, errno := syscall.Syscall(trap, ptr, size, uintptr(flags))
+
+ n = int(ret)
+ if errno != 0 {
+ err = errno
+ }
+
+ return
+}
+
+func task_info(pid int, info *C.struct_proc_taskallinfo) error {
+ size := C.int(unsafe.Sizeof(*info))
+ ptr := unsafe.Pointer(info)
+
+ n := C.proc_pidinfo(C.int(pid), C.PROC_PIDTASKALLINFO, 0, ptr, size)
+ if n != size {
+ return syscall.ENOMEM
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/cloudfoundry/gosigar/sigar_format.go b/vendor/github.com/cloudfoundry/gosigar/sigar_format.go
new file mode 100644
index 0000000..d80a64e
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/sigar_format.go
@@ -0,0 +1,126 @@
+// Copyright (c) 2012 VMware, Inc.
+
+package sigar
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "strconv"
+ "time"
+)
+
+// Go version of apr_strfsize
+func FormatSize(size uint64) string {
+ ord := []string{"K", "M", "G", "T", "P", "E"}
+ o := 0
+ buf := new(bytes.Buffer)
+ w := bufio.NewWriter(buf)
+
+ if size < 973 {
+ fmt.Fprintf(w, "%3d ", size)
+ w.Flush()
+ return buf.String()
+ }
+
+ for {
+ remain := size & 1023
+ size >>= 10
+
+ if size >= 973 {
+ o++
+ continue
+ }
+
+ if size < 9 || (size == 9 && remain < 973) {
+ remain = ((remain * 5) + 256) / 512
+ if remain >= 10 {
+ size++
+ remain = 0
+ }
+
+ fmt.Fprintf(w, "%d.%d%s", size, remain, ord[o])
+ break
+ }
+
+ if remain >= 512 {
+ size++
+ }
+
+ fmt.Fprintf(w, "%3d%s", size, ord[o])
+ break
+ }
+
+ w.Flush()
+ return buf.String()
+}
+
+func FormatPercent(percent float64) string {
+ return strconv.FormatFloat(percent, 'f', -1, 64) + "%"
+}
+
+func (self *FileSystemUsage) UsePercent() float64 {
+ b_used := (self.Total - self.Free) / 1024
+ b_avail := self.Avail / 1024
+ utotal := b_used + b_avail
+ used := b_used
+
+ if utotal != 0 {
+ u100 := used * 100
+ pct := u100 / utotal
+ if u100%utotal != 0 {
+ pct += 1
+ }
+ return (float64(pct) / float64(100)) * 100.0
+ }
+
+ return 0.0
+}
+
+func (self *Uptime) Format() string {
+ buf := new(bytes.Buffer)
+ w := bufio.NewWriter(buf)
+ uptime := uint64(self.Length)
+
+ days := uptime / (60 * 60 * 24)
+
+ if days != 0 {
+ s := ""
+ if days > 1 {
+ s = "s"
+ }
+ fmt.Fprintf(w, "%d day%s, ", days, s)
+ }
+
+ minutes := uptime / 60
+ hours := minutes / 60
+ hours %= 24
+ minutes %= 60
+
+ fmt.Fprintf(w, "%2d:%02d", hours, minutes)
+
+ w.Flush()
+ return buf.String()
+}
+
+func (self *ProcTime) FormatStartTime() string {
+ if self.StartTime == 0 {
+ return "00:00"
+ }
+ start := time.Unix(int64(self.StartTime)/1000, 0)
+ format := "Jan02"
+ if time.Since(start).Seconds() < (60 * 60 * 24) {
+ format = "15:04"
+ }
+ return start.Format(format)
+}
+
+func (self *ProcTime) FormatTotal() string {
+ t := self.Total / 1000
+ ss := t % 60
+ t /= 60
+ mm := t % 60
+ t /= 60
+ hh := t % 24
+ return fmt.Sprintf("%02d:%02d:%02d", hh, mm, ss)
+}
diff --git a/vendor/github.com/cloudfoundry/gosigar/sigar_interface.go b/vendor/github.com/cloudfoundry/gosigar/sigar_interface.go
new file mode 100644
index 0000000..dd72a76
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/sigar_interface.go
@@ -0,0 +1,141 @@
+package sigar
+
+import (
+ "time"
+)
+
+type Sigar interface {
+ CollectCpuStats(collectionInterval time.Duration) (<-chan Cpu, chan<- struct{})
+ GetLoadAverage() (LoadAverage, error)
+ GetMem() (Mem, error)
+ GetSwap() (Swap, error)
+ GetFileSystemUsage(string) (FileSystemUsage, error)
+}
+
+type Cpu struct {
+ User uint64
+ Nice uint64
+ Sys uint64
+ Idle uint64
+ Wait uint64
+ Irq uint64
+ SoftIrq uint64
+ Stolen uint64
+}
+
+func (cpu *Cpu) Total() uint64 {
+ return cpu.User + cpu.Nice + cpu.Sys + cpu.Idle +
+ cpu.Wait + cpu.Irq + cpu.SoftIrq + cpu.Stolen
+}
+
+func (cpu Cpu) Delta(other Cpu) Cpu {
+ return Cpu{
+ User: cpu.User - other.User,
+ Nice: cpu.Nice - other.Nice,
+ Sys: cpu.Sys - other.Sys,
+ Idle: cpu.Idle - other.Idle,
+ Wait: cpu.Wait - other.Wait,
+ Irq: cpu.Irq - other.Irq,
+ SoftIrq: cpu.SoftIrq - other.SoftIrq,
+ Stolen: cpu.Stolen - other.Stolen,
+ }
+}
+
+type LoadAverage struct {
+ One, Five, Fifteen float64
+}
+
+type Uptime struct {
+ Length float64
+}
+
+type Mem struct {
+ Total uint64
+ Used uint64
+ Free uint64
+ ActualFree uint64
+ ActualUsed uint64
+}
+
+type Swap struct {
+ Total uint64
+ Used uint64
+ Free uint64
+}
+
+type CpuList struct {
+ List []Cpu
+}
+
+type FileSystem struct {
+ DirName string
+ DevName string
+ TypeName string
+ SysTypeName string
+ Options string
+ Flags uint32
+}
+
+type FileSystemList struct {
+ List []FileSystem
+}
+
+type FileSystemUsage struct {
+ Total uint64
+ Used uint64
+ Free uint64
+ Avail uint64
+ Files uint64
+ FreeFiles uint64
+}
+
+type ProcList struct {
+ List []int
+}
+
+type RunState byte
+
+const (
+ RunStateSleep = 'S'
+ RunStateRun = 'R'
+ RunStateStop = 'T'
+ RunStateZombie = 'Z'
+ RunStateIdle = 'D'
+ RunStateUnknown = '?'
+)
+
+type ProcState struct {
+ Name string
+ State RunState
+ Ppid int
+ Tty int
+ Priority int
+ Nice int
+ Processor int
+}
+
+type ProcMem struct {
+ Size uint64
+ Resident uint64
+ Share uint64
+ MinorFaults uint64
+ MajorFaults uint64
+ PageFaults uint64
+}
+
+type ProcTime struct {
+ StartTime uint64
+ User uint64
+ Sys uint64
+ Total uint64
+}
+
+type ProcArgs struct {
+ List []string
+}
+
+type ProcExe struct {
+ Name string
+ Cwd string
+ Root string
+}
diff --git a/vendor/github.com/cloudfoundry/gosigar/sigar_linux.go b/vendor/github.com/cloudfoundry/gosigar/sigar_linux.go
new file mode 100644
index 0000000..68ffb0f
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/sigar_linux.go
@@ -0,0 +1,386 @@
+// Copyright (c) 2012 VMware, Inc.
+
+package sigar
+
+import (
+ "bufio"
+ "bytes"
+ "io"
+ "io/ioutil"
+ "os"
+ "strconv"
+ "strings"
+ "syscall"
+)
+
+var system struct {
+ ticks uint64
+ btime uint64
+}
+
+var Procd string
+
+func init() {
+ system.ticks = 100 // C.sysconf(C._SC_CLK_TCK)
+
+ Procd = "/proc"
+
+ // grab system boot time
+ readFile(Procd+"/stat", func(line string) bool {
+ if strings.HasPrefix(line, "btime") {
+ system.btime, _ = strtoull(line[6:])
+ return false // stop reading
+ }
+ return true
+ })
+}
+
+func (self *LoadAverage) Get() error {
+ line, err := ioutil.ReadFile(Procd + "/loadavg")
+ if err != nil {
+ return nil
+ }
+
+ fields := strings.Fields(string(line))
+
+ self.One, _ = strconv.ParseFloat(fields[0], 64)
+ self.Five, _ = strconv.ParseFloat(fields[1], 64)
+ self.Fifteen, _ = strconv.ParseFloat(fields[2], 64)
+
+ return nil
+}
+
+func (self *Uptime) Get() error {
+ sysinfo := syscall.Sysinfo_t{}
+
+ if err := syscall.Sysinfo(&sysinfo); err != nil {
+ return err
+ }
+
+ self.Length = float64(sysinfo.Uptime)
+
+ return nil
+}
+
+func (self *Mem) Get() error {
+ var buffers, cached uint64
+ table := map[string]*uint64{
+ "MemTotal": &self.Total,
+ "MemFree": &self.Free,
+ "Buffers": &buffers,
+ "Cached": &cached,
+ }
+
+ if err := parseMeminfo(table); err != nil {
+ return err
+ }
+
+ self.Used = self.Total - self.Free
+ kern := buffers + cached
+ self.ActualFree = self.Free + kern
+ self.ActualUsed = self.Used - kern
+
+ return nil
+}
+
+func (self *Swap) Get() error {
+ table := map[string]*uint64{
+ "SwapTotal": &self.Total,
+ "SwapFree": &self.Free,
+ }
+
+ if err := parseMeminfo(table); err != nil {
+ return err
+ }
+
+ self.Used = self.Total - self.Free
+ return nil
+}
+
+func (self *Cpu) Get() error {
+ return readFile(Procd+"/stat", func(line string) bool {
+ if len(line) > 4 && line[0:4] == "cpu " {
+ parseCpuStat(self, line)
+ return false
+ }
+ return true
+
+ })
+}
+
+func (self *CpuList) Get() error {
+ capacity := len(self.List)
+ if capacity == 0 {
+ capacity = 4
+ }
+ list := make([]Cpu, 0, capacity)
+
+ err := readFile(Procd+"/stat", func(line string) bool {
+ if len(line) > 3 && line[0:3] == "cpu" && line[3] != ' ' {
+ cpu := Cpu{}
+ parseCpuStat(&cpu, line)
+ list = append(list, cpu)
+ }
+ return true
+ })
+
+ self.List = list
+
+ return err
+}
+
+func (self *FileSystemList) Get() error {
+ capacity := len(self.List)
+ if capacity == 0 {
+ capacity = 10
+ }
+ fslist := make([]FileSystem, 0, capacity)
+
+ err := readFile("/etc/mtab", func(line string) bool {
+ fields := strings.Fields(line)
+
+ fs := FileSystem{}
+ fs.DevName = fields[0]
+ fs.DirName = fields[1]
+ fs.SysTypeName = fields[2]
+ fs.Options = fields[3]
+
+ fslist = append(fslist, fs)
+
+ return true
+ })
+
+ self.List = fslist
+
+ return err
+}
+
+func (self *ProcList) Get() error {
+ dir, err := os.Open(Procd)
+ if err != nil {
+ return err
+ }
+ defer dir.Close()
+
+ const readAllDirnames = -1 // see os.File.Readdirnames doc
+
+ names, err := dir.Readdirnames(readAllDirnames)
+ if err != nil {
+ return err
+ }
+
+ capacity := len(names)
+ list := make([]int, 0, capacity)
+
+ for _, name := range names {
+ if name[0] < '0' || name[0] > '9' {
+ continue
+ }
+ pid, err := strconv.Atoi(name)
+ if err == nil {
+ list = append(list, pid)
+ }
+ }
+
+ self.List = list
+
+ return nil
+}
+
+func (self *ProcState) Get(pid int) error {
+ contents, err := readProcFile(pid, "stat")
+ if err != nil {
+ return err
+ }
+
+ fields := strings.Fields(string(contents))
+
+ self.Name = fields[1][1 : len(fields[1])-1] // strip ()'s
+
+ self.State = RunState(fields[2][0])
+
+ self.Ppid, _ = strconv.Atoi(fields[3])
+
+ self.Tty, _ = strconv.Atoi(fields[6])
+
+ self.Priority, _ = strconv.Atoi(fields[17])
+
+ self.Nice, _ = strconv.Atoi(fields[18])
+
+ self.Processor, _ = strconv.Atoi(fields[38])
+
+ return nil
+}
+
+func (self *ProcMem) Get(pid int) error {
+ contents, err := readProcFile(pid, "statm")
+ if err != nil {
+ return err
+ }
+
+ fields := strings.Fields(string(contents))
+
+ size, _ := strtoull(fields[0])
+ self.Size = size << 12
+
+ rss, _ := strtoull(fields[1])
+ self.Resident = rss << 12
+
+ share, _ := strtoull(fields[2])
+ self.Share = share << 12
+
+ contents, err = readProcFile(pid, "stat")
+ if err != nil {
+ return err
+ }
+
+ fields = strings.Fields(string(contents))
+
+ self.MinorFaults, _ = strtoull(fields[10])
+ self.MajorFaults, _ = strtoull(fields[12])
+ self.PageFaults = self.MinorFaults + self.MajorFaults
+
+ return nil
+}
+
+func (self *ProcTime) Get(pid int) error {
+ contents, err := readProcFile(pid, "stat")
+ if err != nil {
+ return err
+ }
+
+ fields := strings.Fields(string(contents))
+
+ user, _ := strtoull(fields[13])
+ sys, _ := strtoull(fields[14])
+ // convert to millis
+ self.User = user * (1000 / system.ticks)
+ self.Sys = sys * (1000 / system.ticks)
+ self.Total = self.User + self.Sys
+
+ // convert to millis
+ self.StartTime, _ = strtoull(fields[21])
+ self.StartTime /= system.ticks
+ self.StartTime += system.btime
+ self.StartTime *= 1000
+
+ return nil
+}
+
+func (self *ProcArgs) Get(pid int) error {
+ contents, err := readProcFile(pid, "cmdline")
+ if err != nil {
+ return err
+ }
+
+ bbuf := bytes.NewBuffer(contents)
+
+ var args []string
+
+ for {
+ arg, err := bbuf.ReadBytes(0)
+ if err == io.EOF {
+ break
+ }
+ args = append(args, string(chop(arg)))
+ }
+
+ self.List = args
+
+ return nil
+}
+
+func (self *ProcExe) Get(pid int) error {
+ fields := map[string]*string{
+ "exe": &self.Name,
+ "cwd": &self.Cwd,
+ "root": &self.Root,
+ }
+
+ for name, field := range fields {
+ val, err := os.Readlink(procFileName(pid, name))
+
+ if err != nil {
+ return err
+ }
+
+ *field = val
+ }
+
+ return nil
+}
+
+func parseMeminfo(table map[string]*uint64) error {
+ return readFile(Procd+"/meminfo", func(line string) bool {
+ fields := strings.Split(line, ":")
+
+ if ptr := table[fields[0]]; ptr != nil {
+ num := strings.TrimLeft(fields[1], " ")
+ val, err := strtoull(strings.Fields(num)[0])
+ if err == nil {
+ *ptr = val * 1024
+ }
+ }
+
+ return true
+ })
+}
+
+func parseCpuStat(self *Cpu, line string) error {
+ fields := strings.Fields(line)
+
+ self.User, _ = strtoull(fields[1])
+ self.Nice, _ = strtoull(fields[2])
+ self.Sys, _ = strtoull(fields[3])
+ self.Idle, _ = strtoull(fields[4])
+ self.Wait, _ = strtoull(fields[5])
+ self.Irq, _ = strtoull(fields[6])
+ self.SoftIrq, _ = strtoull(fields[7])
+ self.Stolen, _ = strtoull(fields[8])
+
+ return nil
+}
+
+func readFile(file string, handler func(string) bool) error {
+ contents, err := ioutil.ReadFile(file)
+ if err != nil {
+ return err
+ }
+
+ reader := bufio.NewReader(bytes.NewBuffer(contents))
+
+ for {
+ line, _, err := reader.ReadLine()
+ if err == io.EOF {
+ break
+ }
+ if !handler(string(line)) {
+ break
+ }
+ }
+
+ return nil
+}
+
+func strtoull(val string) (uint64, error) {
+ return strconv.ParseUint(val, 10, 64)
+}
+
+func procFileName(pid int, name string) string {
+ return Procd + "/" + strconv.Itoa(pid) + "/" + name
+}
+
+func readProcFile(pid int, name string) ([]byte, error) {
+ path := procFileName(pid, name)
+ contents, err := ioutil.ReadFile(path)
+
+ if err != nil {
+ if perr, ok := err.(*os.PathError); ok {
+ if perr.Err == syscall.ENOENT {
+ return nil, syscall.ESRCH
+ }
+ }
+ }
+
+ return contents, err
+}
diff --git a/vendor/github.com/cloudfoundry/gosigar/sigar_unix.go b/vendor/github.com/cloudfoundry/gosigar/sigar_unix.go
new file mode 100644
index 0000000..39f1878
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/sigar_unix.go
@@ -0,0 +1,26 @@
+// Copyright (c) 2012 VMware, Inc.
+
+// +build darwin freebsd linux netbsd openbsd
+
+package sigar
+
+import "syscall"
+
+func (self *FileSystemUsage) Get(path string) error {
+ stat := syscall.Statfs_t{}
+ err := syscall.Statfs(path, &stat)
+ if err != nil {
+ return err
+ }
+
+ bsize := stat.Bsize / 512
+
+ self.Total = (uint64(stat.Blocks) * uint64(bsize)) >> 1
+ self.Free = (uint64(stat.Bfree) * uint64(bsize)) >> 1
+ self.Avail = (uint64(stat.Bavail) * uint64(bsize)) >> 1
+ self.Used = self.Total - self.Free
+ self.Files = stat.Files
+ self.FreeFiles = stat.Ffree
+
+ return nil
+}
diff --git a/vendor/github.com/cloudfoundry/gosigar/sigar_util.go b/vendor/github.com/cloudfoundry/gosigar/sigar_util.go
new file mode 100644
index 0000000..a02df94
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/sigar_util.go
@@ -0,0 +1,22 @@
+// Copyright (c) 2012 VMware, Inc.
+
+package sigar
+
+import (
+ "unsafe"
+)
+
+func bytePtrToString(ptr *int8) string {
+ bytes := (*[10000]byte)(unsafe.Pointer(ptr))
+
+ n := 0
+ for bytes[n] != 0 {
+ n++
+ }
+
+ return string(bytes[0:n])
+}
+
+func chop(buf []byte) []byte {
+ return buf[0 : len(buf)-1]
+}
diff --git a/vendor/github.com/cloudfoundry/gosigar/sigar_windows.go b/vendor/github.com/cloudfoundry/gosigar/sigar_windows.go
new file mode 100644
index 0000000..0c779d7
--- /dev/null
+++ b/vendor/github.com/cloudfoundry/gosigar/sigar_windows.go
@@ -0,0 +1,100 @@
+// Copyright (c) 2012 VMware, Inc.
+
+package sigar
+
+// #include <stdlib.h>
+// #include <windows.h>
+import "C"
+
+import (
+ "fmt"
+ "unsafe"
+)
+
+func init() {
+}
+
+func (self *LoadAverage) Get() error {
+ return nil
+}
+
+func (self *Uptime) Get() error {
+ return nil
+}
+
+func (self *Mem) Get() error {
+ var statex C.MEMORYSTATUSEX
+ statex.dwLength = C.DWORD(unsafe.Sizeof(statex))
+
+ succeeded := C.GlobalMemoryStatusEx(&statex)
+ if succeeded == C.FALSE {
+ lastError := C.GetLastError()
+ return fmt.Errorf("GlobalMemoryStatusEx failed with error: %d", int(lastError))
+ }
+
+ self.Total = uint64(statex.ullTotalPhys)
+ return nil
+}
+
+func (self *Swap) Get() error {
+ return notImplemented()
+}
+
+func (self *Cpu) Get() error {
+ return notImplemented()
+}
+
+func (self *CpuList) Get() error {
+ return notImplemented()
+}
+
+func (self *FileSystemList) Get() error {
+ return notImplemented()
+}
+
+func (self *ProcList) Get() error {
+ return notImplemented()
+}
+
+func (self *ProcState) Get(pid int) error {
+ return notImplemented()
+}
+
+func (self *ProcMem) Get(pid int) error {
+ return notImplemented()
+}
+
+func (self *ProcTime) Get(pid int) error {
+ return notImplemented()
+}
+
+func (self *ProcArgs) Get(pid int) error {
+ return notImplemented()
+}
+
+func (self *ProcExe) Get(pid int) error {
+ return notImplemented()
+}
+
+func (self *FileSystemUsage) Get(path string) error {
+ var availableBytes C.ULARGE_INTEGER
+ var totalBytes C.ULARGE_INTEGER
+ var totalFreeBytes C.ULARGE_INTEGER
+
+ pathChars := C.CString(path)
+ defer C.free(unsafe.Pointer(pathChars))
+
+ succeeded := C.GetDiskFreeSpaceEx((*C.CHAR)(pathChars), &availableBytes, &totalBytes, &totalFreeBytes)
+ if succeeded == C.FALSE {
+ lastError := C.GetLastError()
+ return fmt.Errorf("GetDiskFreeSpaceEx failed with error: %d", int(lastError))
+ }
+
+ self.Total = *(*uint64)(unsafe.Pointer(&totalBytes))
+ return nil
+}
+
+func notImplemented() error {
+ panic("Not Implemented")
+ return nil
+}
diff --git a/vendor/github.com/containerd/console/LICENSE b/vendor/github.com/containerd/console/LICENSE
new file mode 100644
index 0000000..109b6bd
--- /dev/null
+++ b/vendor/github.com/containerd/console/LICENSE
@@ -0,0 +1,24 @@
+Copyright (c) 2017-infinity Michael Crosby. crosbymichael@gmail.com
+
+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/containerd/console/README.md b/vendor/github.com/containerd/console/README.md
new file mode 100644
index 0000000..3881cd4
--- /dev/null
+++ b/vendor/github.com/containerd/console/README.md
@@ -0,0 +1,44 @@
+# console
+
+[![Build Status](https://travis-ci.org/containerd/console.svg?branch=master)](https://travis-ci.org/containerd/console)
+
+Golang package for dealing with consoles. Light on deps and a simple API.
+
+## Modifying the current process
+
+```go
+current := console.Current()
+defer current.Reset()
+
+if err := current.SetRaw(); err != nil {
+}
+ws, err := current.Size()
+current.Resize(ws)
+```
+
+## License - MIT
+
+Copyright (c) 2017-infinity Michael Crosby. crosbymichael@gmail.com
+
+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/containerd/console/console.go b/vendor/github.com/containerd/console/console.go
new file mode 100644
index 0000000..08d255d
--- /dev/null
+++ b/vendor/github.com/containerd/console/console.go
@@ -0,0 +1,52 @@
+package console
+
+import (
+ "errors"
+ "io"
+ "os"
+)
+
+var ErrNotAConsole = errors.New("provided file is not a console")
+
+type Console interface {
+ io.Reader
+ io.Writer
+ io.Closer
+
+ // Resize resizes the console to the provided window size
+ Resize(WinSize) error
+ // ResizeFrom resizes the calling console to the size of the
+ // provided console
+ ResizeFrom(Console) error
+ // SetRaw sets the console in raw mode
+ SetRaw() error
+ // DisableEcho disables echo on the console
+ DisableEcho() error
+ // Reset restores the console to its orignal state
+ Reset() error
+ // Size returns the window size of the console
+ Size() (WinSize, error)
+}
+
+// WinSize specifies the window size of the console
+type WinSize struct {
+ // Height of the console
+ Height uint16
+ // Width of the console
+ Width uint16
+ x uint16
+ y uint16
+}
+
+// Current returns the current processes console
+func Current() Console {
+ return newMaster(os.Stdin)
+}
+
+// ConsoleFromFile returns a console using the provided file
+func ConsoleFromFile(f *os.File) (Console, error) {
+ if err := checkConsole(f); err != nil {
+ return nil, err
+ }
+ return newMaster(f), nil
+}
diff --git a/vendor/github.com/containerd/console/console_unix.go b/vendor/github.com/containerd/console/console_unix.go
new file mode 100644
index 0000000..fb27011
--- /dev/null
+++ b/vendor/github.com/containerd/console/console_unix.go
@@ -0,0 +1,133 @@
+// +build darwin freebsd linux
+
+package console
+
+// #include <termios.h>
+import "C"
+
+import (
+ "os"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+// NewPty creates a new pty pair
+// The master is returned as the first console and a string
+// with the path to the pty slave is returned as the second
+func NewPty() (Console, string, error) {
+ f, err := os.OpenFile("/dev/ptmx", unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, "", err
+ }
+ if err := saneTerminal(f); err != nil {
+ return nil, "", err
+ }
+ slave, err := ptsname(f)
+ if err != nil {
+ return nil, "", err
+ }
+ if err := unlockpt(f); err != nil {
+ return nil, "", err
+ }
+ return &master{
+ f: f,
+ }, slave, nil
+}
+
+type master struct {
+ f *os.File
+ original *unix.Termios
+}
+
+func (m *master) Read(b []byte) (int, error) {
+ return m.f.Read(b)
+}
+
+func (m *master) Write(b []byte) (int, error) {
+ return m.f.Write(b)
+}
+
+func (m *master) Close() error {
+ return m.f.Close()
+}
+
+func (m *master) Resize(ws WinSize) error {
+ return ioctl(
+ m.f.Fd(),
+ uintptr(unix.TIOCSWINSZ),
+ uintptr(unsafe.Pointer(&ws)),
+ )
+}
+
+func (m *master) ResizeFrom(c Console) error {
+ ws, err := c.Size()
+ if err != nil {
+ return err
+ }
+ return m.Resize(ws)
+}
+
+func (m *master) Reset() error {
+ if m.original == nil {
+ return nil
+ }
+ return tcset(m.f.Fd(), m.original)
+}
+
+func (m *master) getCurrent() (unix.Termios, error) {
+ var termios unix.Termios
+ if err := tcget(m.f.Fd(), &termios); err != nil {
+ return unix.Termios{}, err
+ }
+ if m.original == nil {
+ m.original = &termios
+ }
+ return termios, nil
+}
+
+func (m *master) SetRaw() error {
+ rawState, err := m.getCurrent()
+ if err != nil {
+ return err
+ }
+ C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&rawState)))
+ rawState.Oflag = rawState.Oflag | C.OPOST
+ return tcset(m.f.Fd(), &rawState)
+}
+
+func (m *master) DisableEcho() error {
+ rawState, err := m.getCurrent()
+ if err != nil {
+ return err
+ }
+ rawState.Lflag = rawState.Lflag &^ unix.ECHO
+ return tcset(m.f.Fd(), &rawState)
+}
+
+func (m *master) Size() (WinSize, error) {
+ var ws WinSize
+ if err := ioctl(
+ m.f.Fd(),
+ uintptr(unix.TIOCGWINSZ),
+ uintptr(unsafe.Pointer(&ws)),
+ ); err != nil {
+ return ws, err
+ }
+ return ws, nil
+}
+
+// checkConsole checks if the provided file is a console
+func checkConsole(f *os.File) error {
+ var termios unix.Termios
+ if tcget(f.Fd(), &termios) != nil {
+ return ErrNotAConsole
+ }
+ return nil
+}
+
+func newMaster(f *os.File) Console {
+ return &master{
+ f: f,
+ }
+}
diff --git a/vendor/github.com/containerd/console/console_windows.go b/vendor/github.com/containerd/console/console_windows.go
new file mode 100644
index 0000000..8d133ea
--- /dev/null
+++ b/vendor/github.com/containerd/console/console_windows.go
@@ -0,0 +1,199 @@
+package console
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/Azure/go-ansiterm/winterm"
+ "github.com/pkg/errors"
+)
+
+const (
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx
+ enableVirtualTerminalInput = 0x0200
+ enableVirtualTerminalProcessing = 0x0004
+ disableNewlineAutoReturn = 0x0008
+)
+
+var (
+ vtInputSupported bool
+ ErrNotImplemented = errors.New("not implemented")
+)
+
+func (m *master) initStdios() {
+ m.in = os.Stdin.Fd()
+ if mode, err := winterm.GetConsoleMode(m.in); err == nil {
+ m.inMode = mode
+ // Validate that enableVirtualTerminalInput is supported, but do not set it.
+ if err = winterm.SetConsoleMode(m.in, mode|enableVirtualTerminalInput); err == nil {
+ vtInputSupported = true
+ }
+ // Unconditionally set the console mode back even on failure because SetConsoleMode
+ // remembers invalid bits on input handles.
+ winterm.SetConsoleMode(m.in, mode)
+ } else {
+ fmt.Printf("failed to get console mode for stdin: %v\n", err)
+ }
+
+ m.out = os.Stdout.Fd()
+ if mode, err := winterm.GetConsoleMode(m.out); err == nil {
+ m.outMode = mode
+ if err := winterm.SetConsoleMode(m.out, mode|enableVirtualTerminalProcessing); err == nil {
+ m.outMode |= enableVirtualTerminalProcessing
+ } else {
+ winterm.SetConsoleMode(m.out, m.outMode)
+ }
+ } else {
+ fmt.Printf("failed to get console mode for stdout: %v\n", err)
+ }
+
+ m.err = os.Stderr.Fd()
+ if mode, err := winterm.GetConsoleMode(m.err); err == nil {
+ m.errMode = mode
+ if err := winterm.SetConsoleMode(m.err, mode|enableVirtualTerminalProcessing); err == nil {
+ m.errMode |= enableVirtualTerminalProcessing
+ } else {
+ winterm.SetConsoleMode(m.err, m.errMode)
+ }
+ } else {
+ fmt.Printf("failed to get console mode for stderr: %v\n", err)
+ }
+}
+
+type master struct {
+ in uintptr
+ inMode uint32
+
+ out uintptr
+ outMode uint32
+
+ err uintptr
+ errMode uint32
+}
+
+func (m *master) SetRaw() error {
+ if err := makeInputRaw(m.in, m.inMode); err != nil {
+ return err
+ }
+
+ // Set StdOut and StdErr to raw mode, we ignore failures since
+ // disableNewlineAutoReturn might not be supported on this version of
+ // Windows.
+
+ winterm.SetConsoleMode(m.out, m.outMode|disableNewlineAutoReturn)
+
+ winterm.SetConsoleMode(m.err, m.errMode|disableNewlineAutoReturn)
+
+ return nil
+}
+
+func (m *master) Reset() error {
+ for _, s := range []struct {
+ fd uintptr
+ mode uint32
+ }{
+ {m.in, m.inMode},
+ {m.out, m.outMode},
+ {m.err, m.errMode},
+ } {
+ if err := winterm.SetConsoleMode(s.fd, s.mode); err != nil {
+ return errors.Wrap(err, "unable to restore console mode")
+ }
+ }
+
+ return nil
+}
+
+func (m *master) Size() (WinSize, error) {
+ info, err := winterm.GetConsoleScreenBufferInfo(m.out)
+ if err != nil {
+ return WinSize{}, errors.Wrap(err, "unable to get console info")
+ }
+
+ winsize := WinSize{
+ Width: uint16(info.Window.Right - info.Window.Left + 1),
+ Height: uint16(info.Window.Bottom - info.Window.Top + 1),
+ }
+
+ return winsize, nil
+}
+
+func (m *master) Resize(ws WinSize) error {
+ return ErrNotImplemented
+}
+
+func (m *master) ResizeFrom(c Console) error {
+ return ErrNotImplemented
+}
+
+func (m *master) DisableEcho() error {
+ mode := m.inMode &^ winterm.ENABLE_ECHO_INPUT
+ mode |= winterm.ENABLE_PROCESSED_INPUT
+ mode |= winterm.ENABLE_LINE_INPUT
+
+ if err := winterm.SetConsoleMode(m.in, mode); err != nil {
+ return errors.Wrap(err, "unable to set console to disable echo")
+ }
+
+ return nil
+}
+
+func (m *master) Close() error {
+ return nil
+}
+
+func (m *master) Read(b []byte) (int, error) {
+ panic("not implemented on windows")
+}
+
+func (m *master) Write(b []byte) (int, error) {
+ panic("not implemented on windows")
+}
+
+// makeInputRaw puts the terminal (Windows Console) connected to the given
+// file descriptor into raw mode
+func makeInputRaw(fd uintptr, mode uint32) error {
+ // See
+ // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx
+ // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx
+
+ // Disable these modes
+ mode &^= winterm.ENABLE_ECHO_INPUT
+ mode &^= winterm.ENABLE_LINE_INPUT
+ mode &^= winterm.ENABLE_MOUSE_INPUT
+ mode &^= winterm.ENABLE_WINDOW_INPUT
+ mode &^= winterm.ENABLE_PROCESSED_INPUT
+
+ // Enable these modes
+ mode |= winterm.ENABLE_EXTENDED_FLAGS
+ mode |= winterm.ENABLE_INSERT_MODE
+ mode |= winterm.ENABLE_QUICK_EDIT_MODE
+
+ if vtInputSupported {
+ mode |= enableVirtualTerminalInput
+ }
+
+ if err := winterm.SetConsoleMode(fd, mode); err != nil {
+ return errors.Wrap(err, "unable to set console to raw mode")
+ }
+
+ return nil
+}
+
+func checkConsole(f *os.File) error {
+ if _, err := winterm.GetConsoleMode(f.Fd()); err != nil {
+ return err
+ }
+ return nil
+}
+
+func newMaster(f *os.File) Console {
+ if f != os.Stdin && f != os.Stdout && f != os.Stderr {
+ panic("creating a console from a file is not supported on windows")
+ }
+
+ m := &master{}
+ m.initStdios()
+
+ return m
+}
diff --git a/vendor/github.com/containerd/console/tc_darwin.go b/vendor/github.com/containerd/console/tc_darwin.go
new file mode 100644
index 0000000..d86c315
--- /dev/null
+++ b/vendor/github.com/containerd/console/tc_darwin.go
@@ -0,0 +1,51 @@
+package console
+
+import (
+ "fmt"
+ "os"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+func tcget(fd uintptr, p *unix.Termios) error {
+ return ioctl(fd, unix.TIOCGETA, uintptr(unsafe.Pointer(p)))
+}
+
+func tcset(fd uintptr, p *unix.Termios) error {
+ return ioctl(fd, unix.TIOCSETA, uintptr(unsafe.Pointer(p)))
+}
+
+func ioctl(fd, flag, data uintptr) error {
+ if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, flag, data); err != 0 {
+ return err
+ }
+ return nil
+}
+
+// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.
+// unlockpt should be called before opening the slave side of a pty.
+func unlockpt(f *os.File) error {
+ var u int32
+ return ioctl(f.Fd(), unix.TIOCPTYUNLK, uintptr(unsafe.Pointer(&u)))
+}
+
+// ptsname retrieves the name of the first available pts for the given master.
+func ptsname(f *os.File) (string, error) {
+ var n int32
+ if err := ioctl(f.Fd(), unix.TIOCPTYGNAME, uintptr(unsafe.Pointer(&n))); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("/dev/pts/%d", n), nil
+}
+
+func saneTerminal(f *os.File) error {
+ // Go doesn't have a wrapper for any of the termios ioctls.
+ var termios unix.Termios
+ if err := tcget(f.Fd(), &termios); err != nil {
+ return err
+ }
+ // Set -onlcr so we don't have to deal with \r.
+ termios.Oflag &^= unix.ONLCR
+ return tcset(f.Fd(), &termios)
+}
diff --git a/vendor/github.com/containerd/console/tc_freebsd.go b/vendor/github.com/containerd/console/tc_freebsd.go
new file mode 100644
index 0000000..478f60a
--- /dev/null
+++ b/vendor/github.com/containerd/console/tc_freebsd.go
@@ -0,0 +1,51 @@
+package console
+
+import (
+ "fmt"
+ "os"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+func tcget(fd uintptr, p *unix.Termios) error {
+ return ioctl(fd, unix.TIOCGETA, uintptr(unsafe.Pointer(p)))
+}
+
+func tcset(fd uintptr, p *unix.Termios) error {
+ return ioctl(fd, unix.TIOCSETA, uintptr(unsafe.Pointer(p)))
+}
+
+func ioctl(fd, flag, data uintptr) error {
+ if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, flag, data); err != 0 {
+ return err
+ }
+ return nil
+}
+
+// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.
+// unlockpt should be called before opening the slave side of a pty.
+// This does not exist on FreeBSD, it does not allocate controlling terminals on open
+func unlockpt(f *os.File) error {
+ return nil
+}
+
+// ptsname retrieves the name of the first available pts for the given master.
+func ptsname(f *os.File) (string, error) {
+ var n int32
+ if err := ioctl(f.Fd(), unix.TIOCGPTN, uintptr(unsafe.Pointer(&n))); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("/dev/pts/%d", n), nil
+}
+
+func saneTerminal(f *os.File) error {
+ // Go doesn't have a wrapper for any of the termios ioctls.
+ var termios unix.Termios
+ if err := tcget(f.Fd(), &termios); err != nil {
+ return err
+ }
+ // Set -onlcr so we don't have to deal with \r.
+ termios.Oflag &^= unix.ONLCR
+ return tcset(f.Fd(), &termios)
+}
diff --git a/vendor/github.com/containerd/console/tc_linux.go b/vendor/github.com/containerd/console/tc_linux.go
new file mode 100644
index 0000000..67c89f0
--- /dev/null
+++ b/vendor/github.com/containerd/console/tc_linux.go
@@ -0,0 +1,51 @@
+package console
+
+import (
+ "fmt"
+ "os"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+func tcget(fd uintptr, p *unix.Termios) error {
+ return ioctl(fd, unix.TCGETS, uintptr(unsafe.Pointer(p)))
+}
+
+func tcset(fd uintptr, p *unix.Termios) error {
+ return ioctl(fd, unix.TCSETS, uintptr(unsafe.Pointer(p)))
+}
+
+func ioctl(fd, flag, data uintptr) error {
+ if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, flag, data); err != 0 {
+ return err
+ }
+ return nil
+}
+
+// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.
+// unlockpt should be called before opening the slave side of a pty.
+func unlockpt(f *os.File) error {
+ var u int32
+ return ioctl(f.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))
+}
+
+// ptsname retrieves the name of the first available pts for the given master.
+func ptsname(f *os.File) (string, error) {
+ var n int32
+ if err := ioctl(f.Fd(), unix.TIOCGPTN, uintptr(unsafe.Pointer(&n))); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("/dev/pts/%d", n), nil
+}
+
+func saneTerminal(f *os.File) error {
+ // Go doesn't have a wrapper for any of the termios ioctls.
+ var termios unix.Termios
+ if err := tcget(f.Fd(), &termios); err != nil {
+ return err
+ }
+ // Set -onlcr so we don't have to deal with \r.
+ termios.Oflag &^= unix.ONLCR
+ return tcset(f.Fd(), &termios)
+}
diff --git a/vendor/github.com/containerd/containerd/LICENSE.code b/vendor/github.com/containerd/containerd/LICENSE.code
new file mode 100644
index 0000000..8f3fee6
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/LICENSE.code
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2013-2016 Docker, Inc.
+
+ 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
+
+ https://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/containerd/containerd/LICENSE.docs b/vendor/github.com/containerd/containerd/LICENSE.docs
new file mode 100644
index 0000000..e26cd4f
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/LICENSE.docs
@@ -0,0 +1,425 @@
+Attribution-ShareAlike 4.0 International
+
+=======================================================================
+
+Creative Commons Corporation ("Creative Commons") is not a law firm and
+does not provide legal services or legal advice. Distribution of
+Creative Commons public licenses does not create a lawyer-client or
+other relationship. Creative Commons makes its licenses and related
+information available on an "as-is" basis. Creative Commons gives no
+warranties regarding its licenses, any material licensed under their
+terms and conditions, or any related information. Creative Commons
+disclaims all liability for damages resulting from their use to the
+fullest extent possible.
+
+Using Creative Commons Public Licenses
+
+Creative Commons public licenses provide a standard set of terms and
+conditions that creators and other rights holders may use to share
+original works of authorship and other material subject to copyright
+and certain other rights specified in the public license below. The
+following considerations are for informational purposes only, are not
+exhaustive, and do not form part of our licenses.
+
+ Considerations for licensors: Our public licenses are
+ intended for use by those authorized to give the public
+ permission to use material in ways otherwise restricted by
+ copyright and certain other rights. Our licenses are
+ irrevocable. Licensors should read and understand the terms
+ and conditions of the license they choose before applying it.
+ Licensors should also secure all rights necessary before
+ applying our licenses so that the public can reuse the
+ material as expected. Licensors should clearly mark any
+ material not subject to the license. This includes other CC-
+ licensed material, or material used under an exception or
+ limitation to copyright. More considerations for licensors:
+ wiki.creativecommons.org/Considerations_for_licensors
+
+ Considerations for the public: By using one of our public
+ licenses, a licensor grants the public permission to use the
+ licensed material under specified terms and conditions. If
+ the licensor's permission is not necessary for any reason--for
+ example, because of any applicable exception or limitation to
+ copyright--then that use is not regulated by the license. Our
+ licenses grant only permissions under copyright and certain
+ other rights that a licensor has authority to grant. Use of
+ the licensed material may still be restricted for other
+ reasons, including because others have copyright or other
+ rights in the material. A licensor may make special requests,
+ such as asking that all changes be marked or described.
+ Although not required by our licenses, you are encouraged to
+ respect those requests where reasonable. More_considerations
+ for the public:
+ wiki.creativecommons.org/Considerations_for_licensees
+
+=======================================================================
+
+Creative Commons Attribution-ShareAlike 4.0 International Public
+License
+
+By exercising the Licensed Rights (defined below), You accept and agree
+to be bound by the terms and conditions of this Creative Commons
+Attribution-ShareAlike 4.0 International Public License ("Public
+License"). To the extent this Public License may be interpreted as a
+contract, You are granted the Licensed Rights in consideration of Your
+acceptance of these terms and conditions, and the Licensor grants You
+such rights in consideration of benefits the Licensor receives from
+making the Licensed Material available under these terms and
+conditions.
+
+
+Section 1 -- Definitions.
+
+ a. Adapted Material means material subject to Copyright and Similar
+ Rights that is derived from or based upon the Licensed Material
+ and in which the Licensed Material is translated, altered,
+ arranged, transformed, or otherwise modified in a manner requiring
+ permission under the Copyright and Similar Rights held by the
+ Licensor. For purposes of this Public License, where the Licensed
+ Material is a musical work, performance, or sound recording,
+ Adapted Material is always produced where the Licensed Material is
+ synched in timed relation with a moving image.
+
+ b. Adapter's License means the license You apply to Your Copyright
+ and Similar Rights in Your contributions to Adapted Material in
+ accordance with the terms and conditions of this Public License.
+
+ c. BY-SA Compatible License means a license listed at
+ creativecommons.org/compatiblelicenses, approved by Creative
+ Commons as essentially the equivalent of this Public License.
+
+ d. Copyright and Similar Rights means copyright and/or similar rights
+ closely related to copyright including, without limitation,
+ performance, broadcast, sound recording, and Sui Generis Database
+ Rights, without regard to how the rights are labeled or
+ categorized. For purposes of this Public License, the rights
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
+ Rights.
+
+ e. Effective Technological Measures means those measures that, in the
+ absence of proper authority, may not be circumvented under laws
+ fulfilling obligations under Article 11 of the WIPO Copyright
+ Treaty adopted on December 20, 1996, and/or similar international
+ agreements.
+
+ f. Exceptions and Limitations means fair use, fair dealing, and/or
+ any other exception or limitation to Copyright and Similar Rights
+ that applies to Your use of the Licensed Material.
+
+ g. License Elements means the license attributes listed in the name
+ of a Creative Commons Public License. The License Elements of this
+ Public License are Attribution and ShareAlike.
+
+ h. Licensed Material means the artistic or literary work, database,
+ or other material to which the Licensor applied this Public
+ License.
+
+ i. Licensed Rights means the rights granted to You subject to the
+ terms and conditions of this Public License, which are limited to
+ all Copyright and Similar Rights that apply to Your use of the
+ Licensed Material and that the Licensor has authority to license.
+
+ j. Licensor means the individual(s) or entity(ies) granting rights
+ under this Public License.
+
+ k. Share means to provide material to the public by any means or
+ process that requires permission under the Licensed Rights, such
+ as reproduction, public display, public performance, distribution,
+ dissemination, communication, or importation, and to make material
+ available to the public including in ways that members of the
+ public may access the material from a place and at a time
+ individually chosen by them.
+
+ l. Sui Generis Database Rights means rights other than copyright
+ resulting from Directive 96/9/EC of the European Parliament and of
+ the Council of 11 March 1996 on the legal protection of databases,
+ as amended and/or succeeded, as well as other essentially
+ equivalent rights anywhere in the world.
+
+ m. You means the individual or entity exercising the Licensed Rights
+ under this Public License. Your has a corresponding meaning.
+
+
+Section 2 -- Scope.
+
+ a. License grant.
+
+ 1. Subject to the terms and conditions of this Public License,
+ the Licensor hereby grants You a worldwide, royalty-free,
+ non-sublicensable, non-exclusive, irrevocable license to
+ exercise the Licensed Rights in the Licensed Material to:
+
+ a. reproduce and Share the Licensed Material, in whole or
+ in part; and
+
+ b. produce, reproduce, and Share Adapted Material.
+
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
+ Exceptions and Limitations apply to Your use, this Public
+ License does not apply, and You do not need to comply with
+ its terms and conditions.
+
+ 3. Term. The term of this Public License is specified in Section
+ 6(a).
+
+ 4. Media and formats; technical modifications allowed. The
+ Licensor authorizes You to exercise the Licensed Rights in
+ all media and formats whether now known or hereafter created,
+ and to make technical modifications necessary to do so. The
+ Licensor waives and/or agrees not to assert any right or
+ authority to forbid You from making technical modifications
+ necessary to exercise the Licensed Rights, including
+ technical modifications necessary to circumvent Effective
+ Technological Measures. For purposes of this Public License,
+ simply making modifications authorized by this Section 2(a)
+ (4) never produces Adapted Material.
+
+ 5. Downstream recipients.
+
+ a. Offer from the Licensor -- Licensed Material. Every
+ recipient of the Licensed Material automatically
+ receives an offer from the Licensor to exercise the
+ Licensed Rights under the terms and conditions of this
+ Public License.
+
+ b. Additional offer from the Licensor -- Adapted Material.
+ Every recipient of Adapted Material from You
+ automatically receives an offer from the Licensor to
+ exercise the Licensed Rights in the Adapted Material
+ under the conditions of the Adapter's License You apply.
+
+ c. No downstream restrictions. You may not offer or impose
+ any additional or different terms or conditions on, or
+ apply any Effective Technological Measures to, the
+ Licensed Material if doing so restricts exercise of the
+ Licensed Rights by any recipient of the Licensed
+ Material.
+
+ 6. No endorsement. Nothing in this Public License constitutes or
+ may be construed as permission to assert or imply that You
+ are, or that Your use of the Licensed Material is, connected
+ with, or sponsored, endorsed, or granted official status by,
+ the Licensor or others designated to receive attribution as
+ provided in Section 3(a)(1)(A)(i).
+
+ b. Other rights.
+
+ 1. Moral rights, such as the right of integrity, are not
+ licensed under this Public License, nor are publicity,
+ privacy, and/or other similar personality rights; however, to
+ the extent possible, the Licensor waives and/or agrees not to
+ assert any such rights held by the Licensor to the limited
+ extent necessary to allow You to exercise the Licensed
+ Rights, but not otherwise.
+
+ 2. Patent and trademark rights are not licensed under this
+ Public License.
+
+ 3. To the extent possible, the Licensor waives any right to
+ collect royalties from You for the exercise of the Licensed
+ Rights, whether directly or through a collecting society
+ under any voluntary or waivable statutory or compulsory
+ licensing scheme. In all other cases the Licensor expressly
+ reserves any right to collect such royalties.
+
+
+Section 3 -- License Conditions.
+
+Your exercise of the Licensed Rights is expressly made subject to the
+following conditions.
+
+ a. Attribution.
+
+ 1. If You Share the Licensed Material (including in modified
+ form), You must:
+
+ a. retain the following if it is supplied by the Licensor
+ with the Licensed Material:
+
+ i. identification of the creator(s) of the Licensed
+ Material and any others designated to receive
+ attribution, in any reasonable manner requested by
+ the Licensor (including by pseudonym if
+ designated);
+
+ ii. a copyright notice;
+
+ iii. a notice that refers to this Public License;
+
+ iv. a notice that refers to the disclaimer of
+ warranties;
+
+ v. a URI or hyperlink to the Licensed Material to the
+ extent reasonably practicable;
+
+ b. indicate if You modified the Licensed Material and
+ retain an indication of any previous modifications; and
+
+ c. indicate the Licensed Material is licensed under this
+ Public License, and include the text of, or the URI or
+ hyperlink to, this Public License.
+
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
+ reasonable manner based on the medium, means, and context in
+ which You Share the Licensed Material. For example, it may be
+ reasonable to satisfy the conditions by providing a URI or
+ hyperlink to a resource that includes the required
+ information.
+
+ 3. If requested by the Licensor, You must remove any of the
+ information required by Section 3(a)(1)(A) to the extent
+ reasonably practicable.
+
+ b. ShareAlike.
+
+ In addition to the conditions in Section 3(a), if You Share
+ Adapted Material You produce, the following conditions also apply.
+
+ 1. The Adapter's License You apply must be a Creative Commons
+ license with the same License Elements, this version or
+ later, or a BY-SA Compatible License.
+
+ 2. You must include the text of, or the URI or hyperlink to, the
+ Adapter's License You apply. You may satisfy this condition
+ in any reasonable manner based on the medium, means, and
+ context in which You Share Adapted Material.
+
+ 3. You may not offer or impose any additional or different terms
+ or conditions on, or apply any Effective Technological
+ Measures to, Adapted Material that restrict exercise of the
+ rights granted under the Adapter's License You apply.
+
+
+Section 4 -- Sui Generis Database Rights.
+
+Where the Licensed Rights include Sui Generis Database Rights that
+apply to Your use of the Licensed Material:
+
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
+ to extract, reuse, reproduce, and Share all or a substantial
+ portion of the contents of the database;
+
+ b. if You include all or a substantial portion of the database
+ contents in a database in which You have Sui Generis Database
+ Rights, then the database in which You have Sui Generis Database
+ Rights (but not its individual contents) is Adapted Material,
+
+ including for purposes of Section 3(b); and
+ c. You must comply with the conditions in Section 3(a) if You Share
+ all or a substantial portion of the contents of the database.
+
+For the avoidance of doubt, this Section 4 supplements and does not
+replace Your obligations under this Public License where the Licensed
+Rights include other Copyright and Similar Rights.
+
+
+Section 5 -- Disclaimer of Warranties and Limitation of Liability.
+
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
+
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
+
+ c. The disclaimer of warranties and limitation of liability provided
+ above shall be interpreted in a manner that, to the extent
+ possible, most closely approximates an absolute disclaimer and
+ waiver of all liability.
+
+
+Section 6 -- Term and Termination.
+
+ a. This Public License applies for the term of the Copyright and
+ Similar Rights licensed here. However, if You fail to comply with
+ this Public License, then Your rights under this Public License
+ terminate automatically.
+
+ b. Where Your right to use the Licensed Material has terminated under
+ Section 6(a), it reinstates:
+
+ 1. automatically as of the date the violation is cured, provided
+ it is cured within 30 days of Your discovery of the
+ violation; or
+
+ 2. upon express reinstatement by the Licensor.
+
+ For the avoidance of doubt, this Section 6(b) does not affect any
+ right the Licensor may have to seek remedies for Your violations
+ of this Public License.
+
+ c. For the avoidance of doubt, the Licensor may also offer the
+ Licensed Material under separate terms or conditions or stop
+ distributing the Licensed Material at any time; however, doing so
+ will not terminate this Public License.
+
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
+ License.
+
+
+Section 7 -- Other Terms and Conditions.
+
+ a. The Licensor shall not be bound by any additional or different
+ terms or conditions communicated by You unless expressly agreed.
+
+ b. Any arrangements, understandings, or agreements regarding the
+ Licensed Material not stated herein are separate from and
+ independent of the terms and conditions of this Public License.
+
+
+Section 8 -- Interpretation.
+
+ a. For the avoidance of doubt, this Public License does not, and
+ shall not be interpreted to, reduce, limit, restrict, or impose
+ conditions on any use of the Licensed Material that could lawfully
+ be made without permission under this Public License.
+
+ b. To the extent possible, if any provision of this Public License is
+ deemed unenforceable, it shall be automatically reformed to the
+ minimum extent necessary to make it enforceable. If the provision
+ cannot be reformed, it shall be severed from this Public License
+ without affecting the enforceability of the remaining terms and
+ conditions.
+
+ c. No term or condition of this Public License will be waived and no
+ failure to comply consented to unless expressly agreed to by the
+ Licensor.
+
+ d. Nothing in this Public License constitutes or may be interpreted
+ as a limitation upon, or waiver of, any privileges and immunities
+ that apply to the Licensor or You, including from the legal
+ processes of any jurisdiction or authority.
+
+
+=======================================================================
+
+Creative Commons is not a party to its public licenses.
+Notwithstanding, Creative Commons may elect to apply one of its public
+licenses to material it publishes and in those instances will be
+considered the "Licensor." Except for the limited purpose of indicating
+that material is shared under a Creative Commons public license or as
+otherwise permitted by the Creative Commons policies published at
+creativecommons.org/policies, Creative Commons does not authorize the
+use of the trademark "Creative Commons" or any other trademark or logo
+of Creative Commons without its prior written consent including,
+without limitation, in connection with any unauthorized modifications
+to any of its public licenses or any other arrangements,
+understandings, or agreements concerning use of licensed material. For
+the avoidance of doubt, this paragraph does not form part of the public
+licenses.
+
+Creative Commons may be contacted at creativecommons.org.
diff --git a/vendor/github.com/containerd/containerd/NOTICE b/vendor/github.com/containerd/containerd/NOTICE
new file mode 100644
index 0000000..8915f02
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/NOTICE
@@ -0,0 +1,16 @@
+Docker
+Copyright 2012-2015 Docker, Inc.
+
+This product includes software developed at Docker, Inc. (https://www.docker.com).
+
+The following is courtesy of our legal counsel:
+
+
+Use and transfer of Docker may be subject to certain restrictions by the
+United States and other governments.
+It is your responsibility to ensure that your use and/or transfer does not
+violate applicable laws.
+
+For more information, please see https://www.bis.doc.gov
+
+See also https://www.apache.org/dev/crypto.html and/or seek legal counsel.
diff --git a/vendor/github.com/containerd/containerd/README.md b/vendor/github.com/containerd/containerd/README.md
new file mode 100644
index 0000000..6741966
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/README.md
@@ -0,0 +1,72 @@
+# containerd
+
+containerd is a daemon to control runC, built for performance and density.
+containerd leverages runC's advanced features such as seccomp and user namespace support as well
+as checkpoint and restore for cloning and live migration of containers.
+
+## Getting started
+
+The easiest way to start using containerd is to download binaries from the [releases page](https://github.com/containerd/containerd/releases).
+
+The included `ctr` command-line tool allows you interact with the containerd daemon:
+
+```
+$ sudo ctr containers start redis /containers/redis
+$ sudo ctr containers list
+ID PATH STATUS PROCESSES
+redis /containers/redis running 14063
+```
+
+`/containers/redis` is the path to an OCI bundle. [See the docs for more information.](docs/bundle.md)
+
+## Docs
+
+ * [Client CLI reference (`ctr`)](docs/cli.md)
+ * [Daemon CLI reference (`containerd`)](docs/daemon.md)
+ * [Creating OCI bundles](docs/bundle.md)
+ * [containerd changes to the bundle](docs/bundle-changes.md)
+ * [Attaching to STDIO or TTY](docs/attach.md)
+ * [Telemetry and metrics](docs/telemetry.md)
+
+All documentation is contained in the `/docs` directory in this repository.
+
+## Building
+
+You will need to make sure that you have Go installed on your system and the containerd repository is cloned
+in your `$GOPATH`. You will also need to make sure that you have all the dependencies cloned as well.
+Currently, contributing to containerd is not for the first time devs as many dependencies are not vendored and
+work is being completed at a high rate.
+
+After that just run `make` and the binaries for the daemon and client will be localed in the `bin/` directory.
+
+## Performance
+
+Starting 1000 containers concurrently runs at 126-140 containers per second.
+
+Overall start times:
+
+```
+[containerd] 2015/12/04 15:00:54 count: 1000
+[containerd] 2015/12/04 14:59:54 min: 23ms
+[containerd] 2015/12/04 14:59:54 max: 355ms
+[containerd] 2015/12/04 14:59:54 mean: 78ms
+[containerd] 2015/12/04 14:59:54 stddev: 34ms
+[containerd] 2015/12/04 14:59:54 median: 73ms
+[containerd] 2015/12/04 14:59:54 75%: 91ms
+[containerd] 2015/12/04 14:59:54 95%: 123ms
+[containerd] 2015/12/04 14:59:54 99%: 287ms
+[containerd] 2015/12/04 14:59:54 99.9%: 355ms
+```
+
+## Roadmap
+
+The current roadmap and milestones for alpha and beta completion are in the github issues on this repository. Please refer to these issues for what is being worked on and completed for the various stages of development.
+
+## Copyright and license
+
+Copyright © 2016 Docker, Inc. All rights reserved, except as follows. Code
+is released under the Apache 2.0 license. The README.md file, and files in the
+"docs" folder are licensed under the Creative Commons Attribution 4.0
+International License under the terms and conditions set forth in the file
+"LICENSE.docs". You may obtain a duplicate copy of the same license, titled
+CC-BY-SA-4.0, at http://creativecommons.org/licenses/by/4.0/.
diff --git a/vendor/github.com/containerd/containerd/api/grpc/server/server.go b/vendor/github.com/containerd/containerd/api/grpc/server/server.go
new file mode 100644
index 0000000..89ba87c
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/api/grpc/server/server.go
@@ -0,0 +1,494 @@
+package server
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+
+ "github.com/containerd/containerd"
+ "github.com/containerd/containerd/api/grpc/types"
+ "github.com/containerd/containerd/runtime"
+ "github.com/containerd/containerd/supervisor"
+ "github.com/golang/protobuf/ptypes"
+ "golang.org/x/net/context"
+)
+
+type apiServer struct {
+ sv *supervisor.Supervisor
+}
+
+// NewServer returns grpc server instance
+func NewServer(sv *supervisor.Supervisor) types.APIServer {
+ return &apiServer{
+ sv: sv,
+ }
+}
+
+func (s *apiServer) GetServerVersion(ctx context.Context, c *types.GetServerVersionRequest) (*types.GetServerVersionResponse, error) {
+ return &types.GetServerVersionResponse{
+ Major: containerd.VersionMajor,
+ Minor: containerd.VersionMinor,
+ Patch: containerd.VersionPatch,
+ Revision: containerd.GitCommit,
+ }, nil
+}
+
+func (s *apiServer) CreateContainer(ctx context.Context, c *types.CreateContainerRequest) (*types.CreateContainerResponse, error) {
+ if c.BundlePath == "" {
+ return nil, errors.New("empty bundle path")
+ }
+ e := &supervisor.StartTask{}
+ e.ID = c.Id
+ e.BundlePath = c.BundlePath
+ e.Stdin = c.Stdin
+ e.Stdout = c.Stdout
+ e.Stderr = c.Stderr
+ e.Labels = c.Labels
+ e.NoPivotRoot = c.NoPivotRoot
+ e.Runtime = c.Runtime
+ e.RuntimeArgs = c.RuntimeArgs
+ e.StartResponse = make(chan supervisor.StartResponse, 1)
+ e.Ctx = ctx
+ if c.Checkpoint != "" {
+ e.CheckpointDir = c.CheckpointDir
+ e.Checkpoint = &runtime.Checkpoint{
+ Name: c.Checkpoint,
+ }
+ }
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ r := <-e.StartResponse
+ apiC, err := createAPIContainer(r.Container, false)
+ if err != nil {
+ return nil, err
+ }
+ return &types.CreateContainerResponse{
+ Container: apiC,
+ }, nil
+}
+
+func (s *apiServer) CreateCheckpoint(ctx context.Context, r *types.CreateCheckpointRequest) (*types.CreateCheckpointResponse, error) {
+ e := &supervisor.CreateCheckpointTask{}
+ e.ID = r.Id
+ e.CheckpointDir = r.CheckpointDir
+ e.Checkpoint = &runtime.Checkpoint{
+ Name: r.Checkpoint.Name,
+ Exit: r.Checkpoint.Exit,
+ TCP: r.Checkpoint.Tcp,
+ UnixSockets: r.Checkpoint.UnixSockets,
+ Shell: r.Checkpoint.Shell,
+ EmptyNS: r.Checkpoint.EmptyNS,
+ }
+
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ return &types.CreateCheckpointResponse{}, nil
+}
+
+func (s *apiServer) DeleteCheckpoint(ctx context.Context, r *types.DeleteCheckpointRequest) (*types.DeleteCheckpointResponse, error) {
+ if r.Name == "" {
+ return nil, errors.New("checkpoint name cannot be empty")
+ }
+ e := &supervisor.DeleteCheckpointTask{}
+ e.ID = r.Id
+ e.CheckpointDir = r.CheckpointDir
+ e.Checkpoint = &runtime.Checkpoint{
+ Name: r.Name,
+ }
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ return &types.DeleteCheckpointResponse{}, nil
+}
+
+func (s *apiServer) ListCheckpoint(ctx context.Context, r *types.ListCheckpointRequest) (*types.ListCheckpointResponse, error) {
+ e := &supervisor.GetContainersTask{}
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ var container runtime.Container
+ for _, c := range e.Containers {
+ if c.ID() == r.Id {
+ container = c
+ break
+ }
+ }
+ if container == nil {
+ return nil, grpc.Errorf(codes.NotFound, "no such containers")
+ }
+ var out []*types.Checkpoint
+ checkpoints, err := container.Checkpoints(r.CheckpointDir)
+ if err != nil {
+ return nil, err
+ }
+ for _, c := range checkpoints {
+ out = append(out, &types.Checkpoint{
+ Name: c.Name,
+ Tcp: c.TCP,
+ Shell: c.Shell,
+ UnixSockets: c.UnixSockets,
+ // TODO: figure out timestamp
+ //Timestamp: c.Timestamp,
+ })
+ }
+ return &types.ListCheckpointResponse{Checkpoints: out}, nil
+}
+
+func (s *apiServer) Signal(ctx context.Context, r *types.SignalRequest) (*types.SignalResponse, error) {
+ e := &supervisor.SignalTask{}
+ e.ID = r.Id
+ e.PID = r.Pid
+ e.Signal = syscall.Signal(int(r.Signal))
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ return &types.SignalResponse{}, nil
+}
+
+func (s *apiServer) State(ctx context.Context, r *types.StateRequest) (*types.StateResponse, error) {
+
+ getState := func(c runtime.Container) (interface{}, error) {
+ return createAPIContainer(c, true)
+ }
+
+ e := &supervisor.GetContainersTask{}
+ e.ID = r.Id
+ e.GetState = getState
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ m := s.sv.Machine()
+ state := &types.StateResponse{
+ Machine: &types.Machine{
+ Cpus: uint32(m.Cpus),
+ Memory: uint64(m.Memory),
+ },
+ }
+ for idx := range e.Containers {
+ state.Containers = append(state.Containers, e.States[idx].(*types.Container))
+ }
+ return state, nil
+}
+
+func createAPIContainer(c runtime.Container, getPids bool) (*types.Container, error) {
+ processes, err := c.Processes()
+ if err != nil {
+ return nil, grpc.Errorf(codes.Internal, "get processes for container: "+err.Error())
+ }
+ var procs []*types.Process
+ for _, p := range processes {
+ oldProc := p.Spec()
+ stdio := p.Stdio()
+ proc := &types.Process{
+ Pid: p.ID(),
+ SystemPid: uint32(p.SystemPid()),
+ Terminal: oldProc.Terminal,
+ Args: oldProc.Args,
+ Env: oldProc.Env,
+ Cwd: oldProc.Cwd,
+ Stdin: stdio.Stdin,
+ Stdout: stdio.Stdout,
+ Stderr: stdio.Stderr,
+ }
+ proc.User = &types.User{
+ Uid: oldProc.User.UID,
+ Gid: oldProc.User.GID,
+ AdditionalGids: oldProc.User.AdditionalGids,
+ }
+ // FIXME: trying to mimic api compat with only using one field
+ proc.Capabilities = oldProc.Capabilities.Effective
+ proc.ApparmorProfile = oldProc.ApparmorProfile
+ proc.SelinuxLabel = oldProc.SelinuxLabel
+ proc.NoNewPrivileges = oldProc.NoNewPrivileges
+ for _, rl := range oldProc.Rlimits {
+ proc.Rlimits = append(proc.Rlimits, &types.Rlimit{
+ Type: rl.Type,
+ Soft: rl.Soft,
+ Hard: rl.Hard,
+ })
+ }
+ procs = append(procs, proc)
+ }
+ var pids []int
+ state := c.State()
+ if getPids && (state == runtime.Running || state == runtime.Paused) {
+ if pids, err = c.Pids(); err != nil {
+ return nil, grpc.Errorf(codes.Internal, "get all pids for container: "+err.Error())
+ }
+ }
+ return &types.Container{
+ Id: c.ID(),
+ BundlePath: c.Path(),
+ Processes: procs,
+ Labels: c.Labels(),
+ Status: string(state),
+ Pids: toUint32(pids),
+ Runtime: c.Runtime(),
+ }, nil
+}
+
+func toUint32(its []int) []uint32 {
+ o := []uint32{}
+ for _, i := range its {
+ o = append(o, uint32(i))
+ }
+ return o
+}
+
+func (s *apiServer) UpdateContainer(ctx context.Context, r *types.UpdateContainerRequest) (*types.UpdateContainerResponse, error) {
+ e := &supervisor.UpdateTask{}
+ e.ID = r.Id
+ e.State = runtime.State(r.Status)
+ if r.Resources != nil {
+ rs := r.Resources
+ e.Resources = &runtime.Resource{}
+ if rs.CpuShares != 0 {
+ e.Resources.CPUShares = int64(rs.CpuShares)
+ }
+ if rs.BlkioWeight != 0 {
+ e.Resources.BlkioWeight = uint16(rs.BlkioWeight)
+ }
+ if rs.CpuPeriod != 0 {
+ e.Resources.CPUPeriod = int64(rs.CpuPeriod)
+ }
+ if rs.CpuQuota != 0 {
+ e.Resources.CPUQuota = int64(rs.CpuQuota)
+ }
+ if rs.CpusetCpus != "" {
+ e.Resources.CpusetCpus = rs.CpusetCpus
+ }
+ if rs.CpusetMems != "" {
+ e.Resources.CpusetMems = rs.CpusetMems
+ }
+ if rs.KernelMemoryLimit != 0 {
+ e.Resources.KernelMemory = int64(rs.KernelMemoryLimit)
+ }
+ if rs.KernelTCPMemoryLimit != 0 {
+ e.Resources.KernelTCPMemory = int64(rs.KernelTCPMemoryLimit)
+ }
+ if rs.MemoryLimit != 0 {
+ e.Resources.Memory = int64(rs.MemoryLimit)
+ }
+ if rs.MemoryReservation != 0 {
+ e.Resources.MemoryReservation = int64(rs.MemoryReservation)
+ }
+ if rs.MemorySwap != 0 {
+ e.Resources.MemorySwap = int64(rs.MemorySwap)
+ }
+ if rs.PidsLimit != 0 {
+ e.Resources.PidsLimit = int64(rs.PidsLimit)
+ }
+ }
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ return &types.UpdateContainerResponse{}, nil
+}
+
+func (s *apiServer) UpdateProcess(ctx context.Context, r *types.UpdateProcessRequest) (*types.UpdateProcessResponse, error) {
+ e := &supervisor.UpdateProcessTask{}
+ e.ID = r.Id
+ e.PID = r.Pid
+ e.Height = int(r.Height)
+ e.Width = int(r.Width)
+ e.CloseStdin = r.CloseStdin
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ return &types.UpdateProcessResponse{}, nil
+}
+
+func (s *apiServer) Events(r *types.EventsRequest, stream types.API_EventsServer) error {
+ t := time.Time{}
+ if r.Timestamp != nil {
+ from, err := ptypes.Timestamp(r.Timestamp)
+ if err != nil {
+ return err
+ }
+ t = from
+ }
+ if r.StoredOnly && t.IsZero() {
+ return fmt.Errorf("invalid parameter: StoredOnly cannot be specified without setting a valid Timestamp")
+ }
+ events := s.sv.Events(t, r.StoredOnly, r.Id)
+ defer s.sv.Unsubscribe(events)
+ for e := range events {
+ tsp, err := ptypes.TimestampProto(e.Timestamp)
+ if err != nil {
+ return err
+ }
+ if r.Id == "" || e.ID == r.Id {
+ if err := stream.Send(&types.Event{
+ Id: e.ID,
+ Type: e.Type,
+ Timestamp: tsp,
+ Pid: e.PID,
+ Status: uint32(e.Status),
+ }); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func convertToPb(st *runtime.Stat) *types.StatsResponse {
+ tsp, _ := ptypes.TimestampProto(st.Timestamp)
+ pbSt := &types.StatsResponse{
+ Timestamp: tsp,
+ CgroupStats: &types.CgroupStats{},
+ }
+ systemUsage, _ := getSystemCPUUsage()
+ pbSt.CgroupStats.CpuStats = &types.CpuStats{
+ CpuUsage: &types.CpuUsage{
+ TotalUsage: st.CPU.Usage.Total,
+ PercpuUsage: st.CPU.Usage.Percpu,
+ UsageInKernelmode: st.CPU.Usage.Kernel,
+ UsageInUsermode: st.CPU.Usage.User,
+ },
+ ThrottlingData: &types.ThrottlingData{
+ Periods: st.CPU.Throttling.Periods,
+ ThrottledPeriods: st.CPU.Throttling.ThrottledPeriods,
+ ThrottledTime: st.CPU.Throttling.ThrottledTime,
+ },
+ SystemUsage: systemUsage,
+ }
+ pbSt.CgroupStats.MemoryStats = &types.MemoryStats{
+ Cache: st.Memory.Cache,
+ Usage: &types.MemoryData{
+ Usage: st.Memory.Usage.Usage,
+ MaxUsage: st.Memory.Usage.Max,
+ Failcnt: st.Memory.Usage.Failcnt,
+ Limit: st.Memory.Usage.Limit,
+ },
+ SwapUsage: &types.MemoryData{
+ Usage: st.Memory.Swap.Usage,
+ MaxUsage: st.Memory.Swap.Max,
+ Failcnt: st.Memory.Swap.Failcnt,
+ Limit: st.Memory.Swap.Limit,
+ },
+ KernelUsage: &types.MemoryData{
+ Usage: st.Memory.Kernel.Usage,
+ MaxUsage: st.Memory.Kernel.Max,
+ Failcnt: st.Memory.Kernel.Failcnt,
+ Limit: st.Memory.Kernel.Limit,
+ },
+ Stats: st.Memory.Raw,
+ }
+ pbSt.CgroupStats.BlkioStats = &types.BlkioStats{
+ IoServiceBytesRecursive: convertBlkioEntryToPb(st.Blkio.IoServiceBytesRecursive),
+ IoServicedRecursive: convertBlkioEntryToPb(st.Blkio.IoServicedRecursive),
+ IoQueuedRecursive: convertBlkioEntryToPb(st.Blkio.IoQueuedRecursive),
+ IoServiceTimeRecursive: convertBlkioEntryToPb(st.Blkio.IoServiceTimeRecursive),
+ IoWaitTimeRecursive: convertBlkioEntryToPb(st.Blkio.IoWaitTimeRecursive),
+ IoMergedRecursive: convertBlkioEntryToPb(st.Blkio.IoMergedRecursive),
+ IoTimeRecursive: convertBlkioEntryToPb(st.Blkio.IoTimeRecursive),
+ SectorsRecursive: convertBlkioEntryToPb(st.Blkio.SectorsRecursive),
+ }
+ pbSt.CgroupStats.HugetlbStats = make(map[string]*types.HugetlbStats)
+ for k, st := range st.Hugetlb {
+ pbSt.CgroupStats.HugetlbStats[k] = &types.HugetlbStats{
+ Usage: st.Usage,
+ MaxUsage: st.Max,
+ Failcnt: st.Failcnt,
+ }
+ }
+ pbSt.CgroupStats.PidsStats = &types.PidsStats{
+ Current: st.Pids.Current,
+ Limit: st.Pids.Limit,
+ }
+ return pbSt
+}
+
+func convertBlkioEntryToPb(b []runtime.BlkioEntry) []*types.BlkioStatsEntry {
+ var pbEs []*types.BlkioStatsEntry
+ for _, e := range b {
+ pbEs = append(pbEs, &types.BlkioStatsEntry{
+ Major: e.Major,
+ Minor: e.Minor,
+ Op: e.Op,
+ Value: e.Value,
+ })
+ }
+ return pbEs
+}
+
+const nanoSecondsPerSecond = 1e9
+
+// getSystemCPUUsage returns the host system's cpu usage in
+// nanoseconds. An error is returned if the format of the underlying
+// file does not match.
+//
+// Uses /proc/stat defined by POSIX. Looks for the cpu
+// statistics line and then sums up the first seven fields
+// provided. See `man 5 proc` for details on specific field
+// information.
+func getSystemCPUUsage() (uint64, error) {
+ var line string
+ f, err := os.Open("/proc/stat")
+ if err != nil {
+ return 0, err
+ }
+ bufReader := bufio.NewReaderSize(nil, 128)
+ defer func() {
+ bufReader.Reset(nil)
+ f.Close()
+ }()
+ bufReader.Reset(f)
+ err = nil
+ for err == nil {
+ line, err = bufReader.ReadString('\n')
+ if err != nil {
+ break
+ }
+ parts := strings.Fields(line)
+ switch parts[0] {
+ case "cpu":
+ if len(parts) < 8 {
+ return 0, fmt.Errorf("bad format of cpu stats")
+ }
+ var totalClockTicks uint64
+ for _, i := range parts[1:8] {
+ v, err := strconv.ParseUint(i, 10, 64)
+ if err != nil {
+ return 0, fmt.Errorf("error parsing cpu stats")
+ }
+ totalClockTicks += v
+ }
+ return (totalClockTicks * nanoSecondsPerSecond) /
+ clockTicksPerSecond, nil
+ }
+ }
+ return 0, fmt.Errorf("bad stats format")
+}
+
+func (s *apiServer) Stats(ctx context.Context, r *types.StatsRequest) (*types.StatsResponse, error) {
+ e := &supervisor.StatsTask{}
+ e.ID = r.Id
+ e.Stat = make(chan *runtime.Stat, 1)
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ stats := <-e.Stat
+ t := convertToPb(stats)
+ return t, nil
+}
diff --git a/vendor/github.com/containerd/containerd/api/grpc/server/server_linux.go b/vendor/github.com/containerd/containerd/api/grpc/server/server_linux.go
new file mode 100644
index 0000000..92baf39
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/api/grpc/server/server_linux.go
@@ -0,0 +1,66 @@
+package server
+
+import (
+ "fmt"
+
+ "github.com/containerd/containerd/api/grpc/types"
+ "github.com/containerd/containerd/specs"
+ "github.com/containerd/containerd/supervisor"
+ "github.com/opencontainers/runc/libcontainer/system"
+ ocs "github.com/opencontainers/runtime-spec/specs-go"
+ "golang.org/x/net/context"
+)
+
+var clockTicksPerSecond = uint64(system.GetClockTicks())
+
+func (s *apiServer) AddProcess(ctx context.Context, r *types.AddProcessRequest) (*types.AddProcessResponse, error) {
+ process := &specs.ProcessSpec{
+ Terminal: r.Terminal,
+ Args: r.Args,
+ Env: r.Env,
+ Cwd: r.Cwd,
+ }
+ process.User = ocs.User{
+ UID: r.User.Uid,
+ GID: r.User.Gid,
+ AdditionalGids: r.User.AdditionalGids,
+ }
+ // for backwards compat in the API set eibp
+ process.Capabilities = &ocs.LinuxCapabilities{
+ Bounding: r.Capabilities,
+ Effective: r.Capabilities,
+ Inheritable: r.Capabilities,
+ Permitted: r.Capabilities,
+ }
+ process.ApparmorProfile = r.ApparmorProfile
+ process.SelinuxLabel = r.SelinuxLabel
+ process.NoNewPrivileges = r.NoNewPrivileges
+ for _, rl := range r.Rlimits {
+ process.Rlimits = append(process.Rlimits, ocs.LinuxRlimit{
+ Type: rl.Type,
+ Soft: rl.Soft,
+ Hard: rl.Hard,
+ })
+ }
+ if r.Id == "" {
+ return nil, fmt.Errorf("container id cannot be empty")
+ }
+ if r.Pid == "" {
+ return nil, fmt.Errorf("process id cannot be empty")
+ }
+ e := &supervisor.AddProcessTask{}
+ e.ID = r.Id
+ e.PID = r.Pid
+ e.ProcessSpec = process
+ e.Stdin = r.Stdin
+ e.Stdout = r.Stdout
+ e.Stderr = r.Stderr
+ e.StartResponse = make(chan supervisor.StartResponse, 1)
+ e.Ctx = ctx
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ sr := <-e.StartResponse
+ return &types.AddProcessResponse{SystemPid: uint32(sr.ExecPid)}, nil
+}
diff --git a/vendor/github.com/containerd/containerd/api/grpc/server/server_solaris.go b/vendor/github.com/containerd/containerd/api/grpc/server/server_solaris.go
new file mode 100644
index 0000000..5ad2734
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/api/grpc/server/server_solaris.go
@@ -0,0 +1,41 @@
+package server
+
+import (
+ "fmt"
+
+ "github.com/containerd/containerd/api/grpc/types"
+ "github.com/containerd/containerd/specs"
+ "github.com/containerd/containerd/supervisor"
+ "golang.org/x/net/context"
+)
+
+var clockTicksPerSecond uint64
+
+func (s *apiServer) AddProcess(ctx context.Context, r *types.AddProcessRequest) (*types.AddProcessResponse, error) {
+ process := &specs.ProcessSpec{
+ Terminal: r.Terminal,
+ Args: r.Args,
+ Env: r.Env,
+ Cwd: r.Cwd,
+ }
+ if r.Id == "" {
+ return nil, fmt.Errorf("container id cannot be empty")
+ }
+ if r.Pid == "" {
+ return nil, fmt.Errorf("process id cannot be empty")
+ }
+ e := &supervisor.AddProcessTask{}
+ e.ID = r.Id
+ e.PID = r.Pid
+ e.ProcessSpec = process
+ e.Stdin = r.Stdin
+ e.Stdout = r.Stdout
+ e.Stderr = r.Stderr
+ e.StartResponse = make(chan supervisor.StartResponse, 1)
+ s.sv.SendTask(e)
+ if err := <-e.ErrorCh(); err != nil {
+ return nil, err
+ }
+ <-e.StartResponse
+ return &types.AddProcessResponse{}, nil
+}
diff --git a/vendor/github.com/containerd/containerd/api/grpc/types/api.pb.go b/vendor/github.com/containerd/containerd/api/grpc/types/api.pb.go
new file mode 100644
index 0000000..e6ef556
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/api/grpc/types/api.pb.go
@@ -0,0 +1,2584 @@
+// Code generated by protoc-gen-go.
+// source: api.proto
+// DO NOT EDIT!
+
+/*
+Package types is a generated protocol buffer package.
+
+It is generated from these files:
+ api.proto
+
+It has these top-level messages:
+ GetServerVersionRequest
+ GetServerVersionResponse
+ UpdateProcessRequest
+ UpdateProcessResponse
+ CreateContainerRequest
+ CreateContainerResponse
+ SignalRequest
+ SignalResponse
+ AddProcessRequest
+ Rlimit
+ User
+ AddProcessResponse
+ CreateCheckpointRequest
+ CreateCheckpointResponse
+ DeleteCheckpointRequest
+ DeleteCheckpointResponse
+ ListCheckpointRequest
+ Checkpoint
+ ListCheckpointResponse
+ StateRequest
+ ContainerState
+ Process
+ Container
+ Machine
+ StateResponse
+ UpdateContainerRequest
+ UpdateResource
+ BlockIODevice
+ WeightDevice
+ ThrottleDevice
+ UpdateContainerResponse
+ EventsRequest
+ Event
+ NetworkStats
+ CpuUsage
+ ThrottlingData
+ CpuStats
+ PidsStats
+ MemoryData
+ MemoryStats
+ BlkioStatsEntry
+ BlkioStats
+ HugetlbStats
+ CgroupStats
+ StatsResponse
+ StatsRequest
+*/
+package types
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_protobuf "github.com/golang/protobuf/ptypes/timestamp"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+type GetServerVersionRequest struct {
+}
+
+func (m *GetServerVersionRequest) Reset() { *m = GetServerVersionRequest{} }
+func (m *GetServerVersionRequest) String() string { return proto.CompactTextString(m) }
+func (*GetServerVersionRequest) ProtoMessage() {}
+func (*GetServerVersionRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+type GetServerVersionResponse struct {
+ Major uint32 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"`
+ Minor uint32 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"`
+ Patch uint32 `protobuf:"varint,3,opt,name=patch" json:"patch,omitempty"`
+ Revision string `protobuf:"bytes,4,opt,name=revision" json:"revision,omitempty"`
+}
+
+func (m *GetServerVersionResponse) Reset() { *m = GetServerVersionResponse{} }
+func (m *GetServerVersionResponse) String() string { return proto.CompactTextString(m) }
+func (*GetServerVersionResponse) ProtoMessage() {}
+func (*GetServerVersionResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *GetServerVersionResponse) GetMajor() uint32 {
+ if m != nil {
+ return m.Major
+ }
+ return 0
+}
+
+func (m *GetServerVersionResponse) GetMinor() uint32 {
+ if m != nil {
+ return m.Minor
+ }
+ return 0
+}
+
+func (m *GetServerVersionResponse) GetPatch() uint32 {
+ if m != nil {
+ return m.Patch
+ }
+ return 0
+}
+
+func (m *GetServerVersionResponse) GetRevision() string {
+ if m != nil {
+ return m.Revision
+ }
+ return ""
+}
+
+type UpdateProcessRequest struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+ Pid string `protobuf:"bytes,2,opt,name=pid" json:"pid,omitempty"`
+ CloseStdin bool `protobuf:"varint,3,opt,name=closeStdin" json:"closeStdin,omitempty"`
+ Width uint32 `protobuf:"varint,4,opt,name=width" json:"width,omitempty"`
+ Height uint32 `protobuf:"varint,5,opt,name=height" json:"height,omitempty"`
+}
+
+func (m *UpdateProcessRequest) Reset() { *m = UpdateProcessRequest{} }
+func (m *UpdateProcessRequest) String() string { return proto.CompactTextString(m) }
+func (*UpdateProcessRequest) ProtoMessage() {}
+func (*UpdateProcessRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+
+func (m *UpdateProcessRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *UpdateProcessRequest) GetPid() string {
+ if m != nil {
+ return m.Pid
+ }
+ return ""
+}
+
+func (m *UpdateProcessRequest) GetCloseStdin() bool {
+ if m != nil {
+ return m.CloseStdin
+ }
+ return false
+}
+
+func (m *UpdateProcessRequest) GetWidth() uint32 {
+ if m != nil {
+ return m.Width
+ }
+ return 0
+}
+
+func (m *UpdateProcessRequest) GetHeight() uint32 {
+ if m != nil {
+ return m.Height
+ }
+ return 0
+}
+
+type UpdateProcessResponse struct {
+}
+
+func (m *UpdateProcessResponse) Reset() { *m = UpdateProcessResponse{} }
+func (m *UpdateProcessResponse) String() string { return proto.CompactTextString(m) }
+func (*UpdateProcessResponse) ProtoMessage() {}
+func (*UpdateProcessResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
+
+type CreateContainerRequest struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+ BundlePath string `protobuf:"bytes,2,opt,name=bundlePath" json:"bundlePath,omitempty"`
+ Checkpoint string `protobuf:"bytes,3,opt,name=checkpoint" json:"checkpoint,omitempty"`
+ Stdin string `protobuf:"bytes,4,opt,name=stdin" json:"stdin,omitempty"`
+ Stdout string `protobuf:"bytes,5,opt,name=stdout" json:"stdout,omitempty"`
+ Stderr string `protobuf:"bytes,6,opt,name=stderr" json:"stderr,omitempty"`
+ Labels []string `protobuf:"bytes,7,rep,name=labels" json:"labels,omitempty"`
+ NoPivotRoot bool `protobuf:"varint,8,opt,name=noPivotRoot" json:"noPivotRoot,omitempty"`
+ Runtime string `protobuf:"bytes,9,opt,name=runtime" json:"runtime,omitempty"`
+ RuntimeArgs []string `protobuf:"bytes,10,rep,name=runtimeArgs" json:"runtimeArgs,omitempty"`
+ CheckpointDir string `protobuf:"bytes,11,opt,name=checkpointDir" json:"checkpointDir,omitempty"`
+}
+
+func (m *CreateContainerRequest) Reset() { *m = CreateContainerRequest{} }
+func (m *CreateContainerRequest) String() string { return proto.CompactTextString(m) }
+func (*CreateContainerRequest) ProtoMessage() {}
+func (*CreateContainerRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
+
+func (m *CreateContainerRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *CreateContainerRequest) GetBundlePath() string {
+ if m != nil {
+ return m.BundlePath
+ }
+ return ""
+}
+
+func (m *CreateContainerRequest) GetCheckpoint() string {
+ if m != nil {
+ return m.Checkpoint
+ }
+ return ""
+}
+
+func (m *CreateContainerRequest) GetStdin() string {
+ if m != nil {
+ return m.Stdin
+ }
+ return ""
+}
+
+func (m *CreateContainerRequest) GetStdout() string {
+ if m != nil {
+ return m.Stdout
+ }
+ return ""
+}
+
+func (m *CreateContainerRequest) GetStderr() string {
+ if m != nil {
+ return m.Stderr
+ }
+ return ""
+}
+
+func (m *CreateContainerRequest) GetLabels() []string {
+ if m != nil {
+ return m.Labels
+ }
+ return nil
+}
+
+func (m *CreateContainerRequest) GetNoPivotRoot() bool {
+ if m != nil {
+ return m.NoPivotRoot
+ }
+ return false
+}
+
+func (m *CreateContainerRequest) GetRuntime() string {
+ if m != nil {
+ return m.Runtime
+ }
+ return ""
+}
+
+func (m *CreateContainerRequest) GetRuntimeArgs() []string {
+ if m != nil {
+ return m.RuntimeArgs
+ }
+ return nil
+}
+
+func (m *CreateContainerRequest) GetCheckpointDir() string {
+ if m != nil {
+ return m.CheckpointDir
+ }
+ return ""
+}
+
+type CreateContainerResponse struct {
+ Container *Container `protobuf:"bytes,1,opt,name=container" json:"container,omitempty"`
+}
+
+func (m *CreateContainerResponse) Reset() { *m = CreateContainerResponse{} }
+func (m *CreateContainerResponse) String() string { return proto.CompactTextString(m) }
+func (*CreateContainerResponse) ProtoMessage() {}
+func (*CreateContainerResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
+
+func (m *CreateContainerResponse) GetContainer() *Container {
+ if m != nil {
+ return m.Container
+ }
+ return nil
+}
+
+type SignalRequest struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+ Pid string `protobuf:"bytes,2,opt,name=pid" json:"pid,omitempty"`
+ Signal uint32 `protobuf:"varint,3,opt,name=signal" json:"signal,omitempty"`
+}
+
+func (m *SignalRequest) Reset() { *m = SignalRequest{} }
+func (m *SignalRequest) String() string { return proto.CompactTextString(m) }
+func (*SignalRequest) ProtoMessage() {}
+func (*SignalRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
+
+func (m *SignalRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *SignalRequest) GetPid() string {
+ if m != nil {
+ return m.Pid
+ }
+ return ""
+}
+
+func (m *SignalRequest) GetSignal() uint32 {
+ if m != nil {
+ return m.Signal
+ }
+ return 0
+}
+
+type SignalResponse struct {
+}
+
+func (m *SignalResponse) Reset() { *m = SignalResponse{} }
+func (m *SignalResponse) String() string { return proto.CompactTextString(m) }
+func (*SignalResponse) ProtoMessage() {}
+func (*SignalResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
+
+type AddProcessRequest struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+ Terminal bool `protobuf:"varint,2,opt,name=terminal" json:"terminal,omitempty"`
+ User *User `protobuf:"bytes,3,opt,name=user" json:"user,omitempty"`
+ Args []string `protobuf:"bytes,4,rep,name=args" json:"args,omitempty"`
+ Env []string `protobuf:"bytes,5,rep,name=env" json:"env,omitempty"`
+ Cwd string `protobuf:"bytes,6,opt,name=cwd" json:"cwd,omitempty"`
+ Pid string `protobuf:"bytes,7,opt,name=pid" json:"pid,omitempty"`
+ Stdin string `protobuf:"bytes,8,opt,name=stdin" json:"stdin,omitempty"`
+ Stdout string `protobuf:"bytes,9,opt,name=stdout" json:"stdout,omitempty"`
+ Stderr string `protobuf:"bytes,10,opt,name=stderr" json:"stderr,omitempty"`
+ Capabilities []string `protobuf:"bytes,11,rep,name=capabilities" json:"capabilities,omitempty"`
+ ApparmorProfile string `protobuf:"bytes,12,opt,name=apparmorProfile" json:"apparmorProfile,omitempty"`
+ SelinuxLabel string `protobuf:"bytes,13,opt,name=selinuxLabel" json:"selinuxLabel,omitempty"`
+ NoNewPrivileges bool `protobuf:"varint,14,opt,name=noNewPrivileges" json:"noNewPrivileges,omitempty"`
+ Rlimits []*Rlimit `protobuf:"bytes,15,rep,name=rlimits" json:"rlimits,omitempty"`
+}
+
+func (m *AddProcessRequest) Reset() { *m = AddProcessRequest{} }
+func (m *AddProcessRequest) String() string { return proto.CompactTextString(m) }
+func (*AddProcessRequest) ProtoMessage() {}
+func (*AddProcessRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
+
+func (m *AddProcessRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *AddProcessRequest) GetTerminal() bool {
+ if m != nil {
+ return m.Terminal
+ }
+ return false
+}
+
+func (m *AddProcessRequest) GetUser() *User {
+ if m != nil {
+ return m.User
+ }
+ return nil
+}
+
+func (m *AddProcessRequest) GetArgs() []string {
+ if m != nil {
+ return m.Args
+ }
+ return nil
+}
+
+func (m *AddProcessRequest) GetEnv() []string {
+ if m != nil {
+ return m.Env
+ }
+ return nil
+}
+
+func (m *AddProcessRequest) GetCwd() string {
+ if m != nil {
+ return m.Cwd
+ }
+ return ""
+}
+
+func (m *AddProcessRequest) GetPid() string {
+ if m != nil {
+ return m.Pid
+ }
+ return ""
+}
+
+func (m *AddProcessRequest) GetStdin() string {
+ if m != nil {
+ return m.Stdin
+ }
+ return ""
+}
+
+func (m *AddProcessRequest) GetStdout() string {
+ if m != nil {
+ return m.Stdout
+ }
+ return ""
+}
+
+func (m *AddProcessRequest) GetStderr() string {
+ if m != nil {
+ return m.Stderr
+ }
+ return ""
+}
+
+func (m *AddProcessRequest) GetCapabilities() []string {
+ if m != nil {
+ return m.Capabilities
+ }
+ return nil
+}
+
+func (m *AddProcessRequest) GetApparmorProfile() string {
+ if m != nil {
+ return m.ApparmorProfile
+ }
+ return ""
+}
+
+func (m *AddProcessRequest) GetSelinuxLabel() string {
+ if m != nil {
+ return m.SelinuxLabel
+ }
+ return ""
+}
+
+func (m *AddProcessRequest) GetNoNewPrivileges() bool {
+ if m != nil {
+ return m.NoNewPrivileges
+ }
+ return false
+}
+
+func (m *AddProcessRequest) GetRlimits() []*Rlimit {
+ if m != nil {
+ return m.Rlimits
+ }
+ return nil
+}
+
+type Rlimit struct {
+ Type string `protobuf:"bytes,1,opt,name=type" json:"type,omitempty"`
+ Soft uint64 `protobuf:"varint,2,opt,name=soft" json:"soft,omitempty"`
+ Hard uint64 `protobuf:"varint,3,opt,name=hard" json:"hard,omitempty"`
+}
+
+func (m *Rlimit) Reset() { *m = Rlimit{} }
+func (m *Rlimit) String() string { return proto.CompactTextString(m) }
+func (*Rlimit) ProtoMessage() {}
+func (*Rlimit) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} }
+
+func (m *Rlimit) GetType() string {
+ if m != nil {
+ return m.Type
+ }
+ return ""
+}
+
+func (m *Rlimit) GetSoft() uint64 {
+ if m != nil {
+ return m.Soft
+ }
+ return 0
+}
+
+func (m *Rlimit) GetHard() uint64 {
+ if m != nil {
+ return m.Hard
+ }
+ return 0
+}
+
+type User struct {
+ Uid uint32 `protobuf:"varint,1,opt,name=uid" json:"uid,omitempty"`
+ Gid uint32 `protobuf:"varint,2,opt,name=gid" json:"gid,omitempty"`
+ AdditionalGids []uint32 `protobuf:"varint,3,rep,packed,name=additionalGids" json:"additionalGids,omitempty"`
+}
+
+func (m *User) Reset() { *m = User{} }
+func (m *User) String() string { return proto.CompactTextString(m) }
+func (*User) ProtoMessage() {}
+func (*User) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} }
+
+func (m *User) GetUid() uint32 {
+ if m != nil {
+ return m.Uid
+ }
+ return 0
+}
+
+func (m *User) GetGid() uint32 {
+ if m != nil {
+ return m.Gid
+ }
+ return 0
+}
+
+func (m *User) GetAdditionalGids() []uint32 {
+ if m != nil {
+ return m.AdditionalGids
+ }
+ return nil
+}
+
+type AddProcessResponse struct {
+ SystemPid uint32 `protobuf:"varint,1,opt,name=systemPid" json:"systemPid,omitempty"`
+}
+
+func (m *AddProcessResponse) Reset() { *m = AddProcessResponse{} }
+func (m *AddProcessResponse) String() string { return proto.CompactTextString(m) }
+func (*AddProcessResponse) ProtoMessage() {}
+func (*AddProcessResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} }
+
+func (m *AddProcessResponse) GetSystemPid() uint32 {
+ if m != nil {
+ return m.SystemPid
+ }
+ return 0
+}
+
+type CreateCheckpointRequest struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+ Checkpoint *Checkpoint `protobuf:"bytes,2,opt,name=checkpoint" json:"checkpoint,omitempty"`
+ CheckpointDir string `protobuf:"bytes,3,opt,name=checkpointDir" json:"checkpointDir,omitempty"`
+}
+
+func (m *CreateCheckpointRequest) Reset() { *m = CreateCheckpointRequest{} }
+func (m *CreateCheckpointRequest) String() string { return proto.CompactTextString(m) }
+func (*CreateCheckpointRequest) ProtoMessage() {}
+func (*CreateCheckpointRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} }
+
+func (m *CreateCheckpointRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *CreateCheckpointRequest) GetCheckpoint() *Checkpoint {
+ if m != nil {
+ return m.Checkpoint
+ }
+ return nil
+}
+
+func (m *CreateCheckpointRequest) GetCheckpointDir() string {
+ if m != nil {
+ return m.CheckpointDir
+ }
+ return ""
+}
+
+type CreateCheckpointResponse struct {
+}
+
+func (m *CreateCheckpointResponse) Reset() { *m = CreateCheckpointResponse{} }
+func (m *CreateCheckpointResponse) String() string { return proto.CompactTextString(m) }
+func (*CreateCheckpointResponse) ProtoMessage() {}
+func (*CreateCheckpointResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} }
+
+type DeleteCheckpointRequest struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+ Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"`
+ CheckpointDir string `protobuf:"bytes,3,opt,name=checkpointDir" json:"checkpointDir,omitempty"`
+}
+
+func (m *DeleteCheckpointRequest) Reset() { *m = DeleteCheckpointRequest{} }
+func (m *DeleteCheckpointRequest) String() string { return proto.CompactTextString(m) }
+func (*DeleteCheckpointRequest) ProtoMessage() {}
+func (*DeleteCheckpointRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} }
+
+func (m *DeleteCheckpointRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *DeleteCheckpointRequest) GetName() string {
+ if m != nil {
+ return m.Name
+ }
+ return ""
+}
+
+func (m *DeleteCheckpointRequest) GetCheckpointDir() string {
+ if m != nil {
+ return m.CheckpointDir
+ }
+ return ""
+}
+
+type DeleteCheckpointResponse struct {
+}
+
+func (m *DeleteCheckpointResponse) Reset() { *m = DeleteCheckpointResponse{} }
+func (m *DeleteCheckpointResponse) String() string { return proto.CompactTextString(m) }
+func (*DeleteCheckpointResponse) ProtoMessage() {}
+func (*DeleteCheckpointResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} }
+
+type ListCheckpointRequest struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+ CheckpointDir string `protobuf:"bytes,2,opt,name=checkpointDir" json:"checkpointDir,omitempty"`
+}
+
+func (m *ListCheckpointRequest) Reset() { *m = ListCheckpointRequest{} }
+func (m *ListCheckpointRequest) String() string { return proto.CompactTextString(m) }
+func (*ListCheckpointRequest) ProtoMessage() {}
+func (*ListCheckpointRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} }
+
+func (m *ListCheckpointRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *ListCheckpointRequest) GetCheckpointDir() string {
+ if m != nil {
+ return m.CheckpointDir
+ }
+ return ""
+}
+
+type Checkpoint struct {
+ Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Exit bool `protobuf:"varint,2,opt,name=exit" json:"exit,omitempty"`
+ Tcp bool `protobuf:"varint,3,opt,name=tcp" json:"tcp,omitempty"`
+ UnixSockets bool `protobuf:"varint,4,opt,name=unixSockets" json:"unixSockets,omitempty"`
+ Shell bool `protobuf:"varint,5,opt,name=shell" json:"shell,omitempty"`
+ EmptyNS []string `protobuf:"bytes,6,rep,name=emptyNS" json:"emptyNS,omitempty"`
+}
+
+func (m *Checkpoint) Reset() { *m = Checkpoint{} }
+func (m *Checkpoint) String() string { return proto.CompactTextString(m) }
+func (*Checkpoint) ProtoMessage() {}
+func (*Checkpoint) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} }
+
+func (m *Checkpoint) GetName() string {
+ if m != nil {
+ return m.Name
+ }
+ return ""
+}
+
+func (m *Checkpoint) GetExit() bool {
+ if m != nil {
+ return m.Exit
+ }
+ return false
+}
+
+func (m *Checkpoint) GetTcp() bool {
+ if m != nil {
+ return m.Tcp
+ }
+ return false
+}
+
+func (m *Checkpoint) GetUnixSockets() bool {
+ if m != nil {
+ return m.UnixSockets
+ }
+ return false
+}
+
+func (m *Checkpoint) GetShell() bool {
+ if m != nil {
+ return m.Shell
+ }
+ return false
+}
+
+func (m *Checkpoint) GetEmptyNS() []string {
+ if m != nil {
+ return m.EmptyNS
+ }
+ return nil
+}
+
+type ListCheckpointResponse struct {
+ Checkpoints []*Checkpoint `protobuf:"bytes,1,rep,name=checkpoints" json:"checkpoints,omitempty"`
+}
+
+func (m *ListCheckpointResponse) Reset() { *m = ListCheckpointResponse{} }
+func (m *ListCheckpointResponse) String() string { return proto.CompactTextString(m) }
+func (*ListCheckpointResponse) ProtoMessage() {}
+func (*ListCheckpointResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} }
+
+func (m *ListCheckpointResponse) GetCheckpoints() []*Checkpoint {
+ if m != nil {
+ return m.Checkpoints
+ }
+ return nil
+}
+
+type StateRequest struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+}
+
+func (m *StateRequest) Reset() { *m = StateRequest{} }
+func (m *StateRequest) String() string { return proto.CompactTextString(m) }
+func (*StateRequest) ProtoMessage() {}
+func (*StateRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} }
+
+func (m *StateRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+type ContainerState struct {
+ Status string `protobuf:"bytes,1,opt,name=status" json:"status,omitempty"`
+}
+
+func (m *ContainerState) Reset() { *m = ContainerState{} }
+func (m *ContainerState) String() string { return proto.CompactTextString(m) }
+func (*ContainerState) ProtoMessage() {}
+func (*ContainerState) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} }
+
+func (m *ContainerState) GetStatus() string {
+ if m != nil {
+ return m.Status
+ }
+ return ""
+}
+
+type Process struct {
+ Pid string `protobuf:"bytes,1,opt,name=pid" json:"pid,omitempty"`
+ Terminal bool `protobuf:"varint,2,opt,name=terminal" json:"terminal,omitempty"`
+ User *User `protobuf:"bytes,3,opt,name=user" json:"user,omitempty"`
+ Args []string `protobuf:"bytes,4,rep,name=args" json:"args,omitempty"`
+ Env []string `protobuf:"bytes,5,rep,name=env" json:"env,omitempty"`
+ Cwd string `protobuf:"bytes,6,opt,name=cwd" json:"cwd,omitempty"`
+ SystemPid uint32 `protobuf:"varint,7,opt,name=systemPid" json:"systemPid,omitempty"`
+ Stdin string `protobuf:"bytes,8,opt,name=stdin" json:"stdin,omitempty"`
+ Stdout string `protobuf:"bytes,9,opt,name=stdout" json:"stdout,omitempty"`
+ Stderr string `protobuf:"bytes,10,opt,name=stderr" json:"stderr,omitempty"`
+ Capabilities []string `protobuf:"bytes,11,rep,name=capabilities" json:"capabilities,omitempty"`
+ ApparmorProfile string `protobuf:"bytes,12,opt,name=apparmorProfile" json:"apparmorProfile,omitempty"`
+ SelinuxLabel string `protobuf:"bytes,13,opt,name=selinuxLabel" json:"selinuxLabel,omitempty"`
+ NoNewPrivileges bool `protobuf:"varint,14,opt,name=noNewPrivileges" json:"noNewPrivileges,omitempty"`
+ Rlimits []*Rlimit `protobuf:"bytes,15,rep,name=rlimits" json:"rlimits,omitempty"`
+}
+
+func (m *Process) Reset() { *m = Process{} }
+func (m *Process) String() string { return proto.CompactTextString(m) }
+func (*Process) ProtoMessage() {}
+func (*Process) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{21} }
+
+func (m *Process) GetPid() string {
+ if m != nil {
+ return m.Pid
+ }
+ return ""
+}
+
+func (m *Process) GetTerminal() bool {
+ if m != nil {
+ return m.Terminal
+ }
+ return false
+}
+
+func (m *Process) GetUser() *User {
+ if m != nil {
+ return m.User
+ }
+ return nil
+}
+
+func (m *Process) GetArgs() []string {
+ if m != nil {
+ return m.Args
+ }
+ return nil
+}
+
+func (m *Process) GetEnv() []string {
+ if m != nil {
+ return m.Env
+ }
+ return nil
+}
+
+func (m *Process) GetCwd() string {
+ if m != nil {
+ return m.Cwd
+ }
+ return ""
+}
+
+func (m *Process) GetSystemPid() uint32 {
+ if m != nil {
+ return m.SystemPid
+ }
+ return 0
+}
+
+func (m *Process) GetStdin() string {
+ if m != nil {
+ return m.Stdin
+ }
+ return ""
+}
+
+func (m *Process) GetStdout() string {
+ if m != nil {
+ return m.Stdout
+ }
+ return ""
+}
+
+func (m *Process) GetStderr() string {
+ if m != nil {
+ return m.Stderr
+ }
+ return ""
+}
+
+func (m *Process) GetCapabilities() []string {
+ if m != nil {
+ return m.Capabilities
+ }
+ return nil
+}
+
+func (m *Process) GetApparmorProfile() string {
+ if m != nil {
+ return m.ApparmorProfile
+ }
+ return ""
+}
+
+func (m *Process) GetSelinuxLabel() string {
+ if m != nil {
+ return m.SelinuxLabel
+ }
+ return ""
+}
+
+func (m *Process) GetNoNewPrivileges() bool {
+ if m != nil {
+ return m.NoNewPrivileges
+ }
+ return false
+}
+
+func (m *Process) GetRlimits() []*Rlimit {
+ if m != nil {
+ return m.Rlimits
+ }
+ return nil
+}
+
+type Container struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+ BundlePath string `protobuf:"bytes,2,opt,name=bundlePath" json:"bundlePath,omitempty"`
+ Processes []*Process `protobuf:"bytes,3,rep,name=processes" json:"processes,omitempty"`
+ Status string `protobuf:"bytes,4,opt,name=status" json:"status,omitempty"`
+ Labels []string `protobuf:"bytes,5,rep,name=labels" json:"labels,omitempty"`
+ Pids []uint32 `protobuf:"varint,6,rep,packed,name=pids" json:"pids,omitempty"`
+ Runtime string `protobuf:"bytes,7,opt,name=runtime" json:"runtime,omitempty"`
+}
+
+func (m *Container) Reset() { *m = Container{} }
+func (m *Container) String() string { return proto.CompactTextString(m) }
+func (*Container) ProtoMessage() {}
+func (*Container) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{22} }
+
+func (m *Container) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *Container) GetBundlePath() string {
+ if m != nil {
+ return m.BundlePath
+ }
+ return ""
+}
+
+func (m *Container) GetProcesses() []*Process {
+ if m != nil {
+ return m.Processes
+ }
+ return nil
+}
+
+func (m *Container) GetStatus() string {
+ if m != nil {
+ return m.Status
+ }
+ return ""
+}
+
+func (m *Container) GetLabels() []string {
+ if m != nil {
+ return m.Labels
+ }
+ return nil
+}
+
+func (m *Container) GetPids() []uint32 {
+ if m != nil {
+ return m.Pids
+ }
+ return nil
+}
+
+func (m *Container) GetRuntime() string {
+ if m != nil {
+ return m.Runtime
+ }
+ return ""
+}
+
+// Machine is information about machine on which containerd is run
+type Machine struct {
+ Cpus uint32 `protobuf:"varint,1,opt,name=cpus" json:"cpus,omitempty"`
+ Memory uint64 `protobuf:"varint,2,opt,name=memory" json:"memory,omitempty"`
+}
+
+func (m *Machine) Reset() { *m = Machine{} }
+func (m *Machine) String() string { return proto.CompactTextString(m) }
+func (*Machine) ProtoMessage() {}
+func (*Machine) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{23} }
+
+func (m *Machine) GetCpus() uint32 {
+ if m != nil {
+ return m.Cpus
+ }
+ return 0
+}
+
+func (m *Machine) GetMemory() uint64 {
+ if m != nil {
+ return m.Memory
+ }
+ return 0
+}
+
+// StateResponse is information about containerd daemon
+type StateResponse struct {
+ Containers []*Container `protobuf:"bytes,1,rep,name=containers" json:"containers,omitempty"`
+ Machine *Machine `protobuf:"bytes,2,opt,name=machine" json:"machine,omitempty"`
+}
+
+func (m *StateResponse) Reset() { *m = StateResponse{} }
+func (m *StateResponse) String() string { return proto.CompactTextString(m) }
+func (*StateResponse) ProtoMessage() {}
+func (*StateResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{24} }
+
+func (m *StateResponse) GetContainers() []*Container {
+ if m != nil {
+ return m.Containers
+ }
+ return nil
+}
+
+func (m *StateResponse) GetMachine() *Machine {
+ if m != nil {
+ return m.Machine
+ }
+ return nil
+}
+
+type UpdateContainerRequest struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+ Pid string `protobuf:"bytes,2,opt,name=pid" json:"pid,omitempty"`
+ Status string `protobuf:"bytes,3,opt,name=status" json:"status,omitempty"`
+ Resources *UpdateResource `protobuf:"bytes,4,opt,name=resources" json:"resources,omitempty"`
+}
+
+func (m *UpdateContainerRequest) Reset() { *m = UpdateContainerRequest{} }
+func (m *UpdateContainerRequest) String() string { return proto.CompactTextString(m) }
+func (*UpdateContainerRequest) ProtoMessage() {}
+func (*UpdateContainerRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25} }
+
+func (m *UpdateContainerRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *UpdateContainerRequest) GetPid() string {
+ if m != nil {
+ return m.Pid
+ }
+ return ""
+}
+
+func (m *UpdateContainerRequest) GetStatus() string {
+ if m != nil {
+ return m.Status
+ }
+ return ""
+}
+
+func (m *UpdateContainerRequest) GetResources() *UpdateResource {
+ if m != nil {
+ return m.Resources
+ }
+ return nil
+}
+
+type UpdateResource struct {
+ BlkioWeight uint64 `protobuf:"varint,1,opt,name=blkioWeight" json:"blkioWeight,omitempty"`
+ CpuShares uint64 `protobuf:"varint,2,opt,name=cpuShares" json:"cpuShares,omitempty"`
+ CpuPeriod uint64 `protobuf:"varint,3,opt,name=cpuPeriod" json:"cpuPeriod,omitempty"`
+ CpuQuota uint64 `protobuf:"varint,4,opt,name=cpuQuota" json:"cpuQuota,omitempty"`
+ CpusetCpus string `protobuf:"bytes,5,opt,name=cpusetCpus" json:"cpusetCpus,omitempty"`
+ CpusetMems string `protobuf:"bytes,6,opt,name=cpusetMems" json:"cpusetMems,omitempty"`
+ MemoryLimit uint64 `protobuf:"varint,7,opt,name=memoryLimit" json:"memoryLimit,omitempty"`
+ MemorySwap uint64 `protobuf:"varint,8,opt,name=memorySwap" json:"memorySwap,omitempty"`
+ MemoryReservation uint64 `protobuf:"varint,9,opt,name=memoryReservation" json:"memoryReservation,omitempty"`
+ KernelMemoryLimit uint64 `protobuf:"varint,10,opt,name=kernelMemoryLimit" json:"kernelMemoryLimit,omitempty"`
+ KernelTCPMemoryLimit uint64 `protobuf:"varint,11,opt,name=kernelTCPMemoryLimit" json:"kernelTCPMemoryLimit,omitempty"`
+ BlkioLeafWeight uint64 `protobuf:"varint,12,opt,name=blkioLeafWeight" json:"blkioLeafWeight,omitempty"`
+ BlkioWeightDevice []*WeightDevice `protobuf:"bytes,13,rep,name=blkioWeightDevice" json:"blkioWeightDevice,omitempty"`
+ BlkioThrottleReadBpsDevice []*ThrottleDevice `protobuf:"bytes,14,rep,name=blkioThrottleReadBpsDevice" json:"blkioThrottleReadBpsDevice,omitempty"`
+ BlkioThrottleWriteBpsDevice []*ThrottleDevice `protobuf:"bytes,15,rep,name=blkioThrottleWriteBpsDevice" json:"blkioThrottleWriteBpsDevice,omitempty"`
+ BlkioThrottleReadIopsDevice []*ThrottleDevice `protobuf:"bytes,16,rep,name=blkioThrottleReadIopsDevice" json:"blkioThrottleReadIopsDevice,omitempty"`
+ BlkioThrottleWriteIopsDevice []*ThrottleDevice `protobuf:"bytes,17,rep,name=blkioThrottleWriteIopsDevice" json:"blkioThrottleWriteIopsDevice,omitempty"`
+ PidsLimit uint64 `protobuf:"varint,18,opt,name=pidsLimit" json:"pidsLimit,omitempty"`
+}
+
+func (m *UpdateResource) Reset() { *m = UpdateResource{} }
+func (m *UpdateResource) String() string { return proto.CompactTextString(m) }
+func (*UpdateResource) ProtoMessage() {}
+func (*UpdateResource) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26} }
+
+func (m *UpdateResource) GetBlkioWeight() uint64 {
+ if m != nil {
+ return m.BlkioWeight
+ }
+ return 0
+}
+
+func (m *UpdateResource) GetCpuShares() uint64 {
+ if m != nil {
+ return m.CpuShares
+ }
+ return 0
+}
+
+func (m *UpdateResource) GetCpuPeriod() uint64 {
+ if m != nil {
+ return m.CpuPeriod
+ }
+ return 0
+}
+
+func (m *UpdateResource) GetCpuQuota() uint64 {
+ if m != nil {
+ return m.CpuQuota
+ }
+ return 0
+}
+
+func (m *UpdateResource) GetCpusetCpus() string {
+ if m != nil {
+ return m.CpusetCpus
+ }
+ return ""
+}
+
+func (m *UpdateResource) GetCpusetMems() string {
+ if m != nil {
+ return m.CpusetMems
+ }
+ return ""
+}
+
+func (m *UpdateResource) GetMemoryLimit() uint64 {
+ if m != nil {
+ return m.MemoryLimit
+ }
+ return 0
+}
+
+func (m *UpdateResource) GetMemorySwap() uint64 {
+ if m != nil {
+ return m.MemorySwap
+ }
+ return 0
+}
+
+func (m *UpdateResource) GetMemoryReservation() uint64 {
+ if m != nil {
+ return m.MemoryReservation
+ }
+ return 0
+}
+
+func (m *UpdateResource) GetKernelMemoryLimit() uint64 {
+ if m != nil {
+ return m.KernelMemoryLimit
+ }
+ return 0
+}
+
+func (m *UpdateResource) GetKernelTCPMemoryLimit() uint64 {
+ if m != nil {
+ return m.KernelTCPMemoryLimit
+ }
+ return 0
+}
+
+func (m *UpdateResource) GetBlkioLeafWeight() uint64 {
+ if m != nil {
+ return m.BlkioLeafWeight
+ }
+ return 0
+}
+
+func (m *UpdateResource) GetBlkioWeightDevice() []*WeightDevice {
+ if m != nil {
+ return m.BlkioWeightDevice
+ }
+ return nil
+}
+
+func (m *UpdateResource) GetBlkioThrottleReadBpsDevice() []*ThrottleDevice {
+ if m != nil {
+ return m.BlkioThrottleReadBpsDevice
+ }
+ return nil
+}
+
+func (m *UpdateResource) GetBlkioThrottleWriteBpsDevice() []*ThrottleDevice {
+ if m != nil {
+ return m.BlkioThrottleWriteBpsDevice
+ }
+ return nil
+}
+
+func (m *UpdateResource) GetBlkioThrottleReadIopsDevice() []*ThrottleDevice {
+ if m != nil {
+ return m.BlkioThrottleReadIopsDevice
+ }
+ return nil
+}
+
+func (m *UpdateResource) GetBlkioThrottleWriteIopsDevice() []*ThrottleDevice {
+ if m != nil {
+ return m.BlkioThrottleWriteIopsDevice
+ }
+ return nil
+}
+
+func (m *UpdateResource) GetPidsLimit() uint64 {
+ if m != nil {
+ return m.PidsLimit
+ }
+ return 0
+}
+
+type BlockIODevice struct {
+ Major int64 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"`
+ Minor int64 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"`
+}
+
+func (m *BlockIODevice) Reset() { *m = BlockIODevice{} }
+func (m *BlockIODevice) String() string { return proto.CompactTextString(m) }
+func (*BlockIODevice) ProtoMessage() {}
+func (*BlockIODevice) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{27} }
+
+func (m *BlockIODevice) GetMajor() int64 {
+ if m != nil {
+ return m.Major
+ }
+ return 0
+}
+
+func (m *BlockIODevice) GetMinor() int64 {
+ if m != nil {
+ return m.Minor
+ }
+ return 0
+}
+
+type WeightDevice struct {
+ BlkIODevice *BlockIODevice `protobuf:"bytes,1,opt,name=blkIODevice" json:"blkIODevice,omitempty"`
+ Weight uint32 `protobuf:"varint,2,opt,name=weight" json:"weight,omitempty"`
+ LeafWeight uint32 `protobuf:"varint,3,opt,name=leafWeight" json:"leafWeight,omitempty"`
+}
+
+func (m *WeightDevice) Reset() { *m = WeightDevice{} }
+func (m *WeightDevice) String() string { return proto.CompactTextString(m) }
+func (*WeightDevice) ProtoMessage() {}
+func (*WeightDevice) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{28} }
+
+func (m *WeightDevice) GetBlkIODevice() *BlockIODevice {
+ if m != nil {
+ return m.BlkIODevice
+ }
+ return nil
+}
+
+func (m *WeightDevice) GetWeight() uint32 {
+ if m != nil {
+ return m.Weight
+ }
+ return 0
+}
+
+func (m *WeightDevice) GetLeafWeight() uint32 {
+ if m != nil {
+ return m.LeafWeight
+ }
+ return 0
+}
+
+type ThrottleDevice struct {
+ BlkIODevice *BlockIODevice `protobuf:"bytes,1,opt,name=blkIODevice" json:"blkIODevice,omitempty"`
+ Rate uint64 `protobuf:"varint,2,opt,name=rate" json:"rate,omitempty"`
+}
+
+func (m *ThrottleDevice) Reset() { *m = ThrottleDevice{} }
+func (m *ThrottleDevice) String() string { return proto.CompactTextString(m) }
+func (*ThrottleDevice) ProtoMessage() {}
+func (*ThrottleDevice) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29} }
+
+func (m *ThrottleDevice) GetBlkIODevice() *BlockIODevice {
+ if m != nil {
+ return m.BlkIODevice
+ }
+ return nil
+}
+
+func (m *ThrottleDevice) GetRate() uint64 {
+ if m != nil {
+ return m.Rate
+ }
+ return 0
+}
+
+type UpdateContainerResponse struct {
+}
+
+func (m *UpdateContainerResponse) Reset() { *m = UpdateContainerResponse{} }
+func (m *UpdateContainerResponse) String() string { return proto.CompactTextString(m) }
+func (*UpdateContainerResponse) ProtoMessage() {}
+func (*UpdateContainerResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{30} }
+
+type EventsRequest struct {
+ // Tag 1 is deprecated (old uint64 timestamp)
+ Timestamp *google_protobuf.Timestamp `protobuf:"bytes,2,opt,name=timestamp" json:"timestamp,omitempty"`
+ StoredOnly bool `protobuf:"varint,3,opt,name=storedOnly" json:"storedOnly,omitempty"`
+ Id string `protobuf:"bytes,4,opt,name=id" json:"id,omitempty"`
+}
+
+func (m *EventsRequest) Reset() { *m = EventsRequest{} }
+func (m *EventsRequest) String() string { return proto.CompactTextString(m) }
+func (*EventsRequest) ProtoMessage() {}
+func (*EventsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{31} }
+
+func (m *EventsRequest) GetTimestamp() *google_protobuf.Timestamp {
+ if m != nil {
+ return m.Timestamp
+ }
+ return nil
+}
+
+func (m *EventsRequest) GetStoredOnly() bool {
+ if m != nil {
+ return m.StoredOnly
+ }
+ return false
+}
+
+func (m *EventsRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+type Event struct {
+ Type string `protobuf:"bytes,1,opt,name=type" json:"type,omitempty"`
+ Id string `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"`
+ Status uint32 `protobuf:"varint,3,opt,name=status" json:"status,omitempty"`
+ Pid string `protobuf:"bytes,4,opt,name=pid" json:"pid,omitempty"`
+ // Tag 5 is deprecated (old uint64 timestamp)
+ Timestamp *google_protobuf.Timestamp `protobuf:"bytes,6,opt,name=timestamp" json:"timestamp,omitempty"`
+}
+
+func (m *Event) Reset() { *m = Event{} }
+func (m *Event) String() string { return proto.CompactTextString(m) }
+func (*Event) ProtoMessage() {}
+func (*Event) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{32} }
+
+func (m *Event) GetType() string {
+ if m != nil {
+ return m.Type
+ }
+ return ""
+}
+
+func (m *Event) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *Event) GetStatus() uint32 {
+ if m != nil {
+ return m.Status
+ }
+ return 0
+}
+
+func (m *Event) GetPid() string {
+ if m != nil {
+ return m.Pid
+ }
+ return ""
+}
+
+func (m *Event) GetTimestamp() *google_protobuf.Timestamp {
+ if m != nil {
+ return m.Timestamp
+ }
+ return nil
+}
+
+type NetworkStats struct {
+ Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ RxBytes uint64 `protobuf:"varint,2,opt,name=rx_bytes,json=rxBytes" json:"rx_bytes,omitempty"`
+ Rx_Packets uint64 `protobuf:"varint,3,opt,name=rx_Packets,json=rxPackets" json:"rx_Packets,omitempty"`
+ RxErrors uint64 `protobuf:"varint,4,opt,name=Rx_errors,json=RxErrors" json:"Rx_errors,omitempty"`
+ RxDropped uint64 `protobuf:"varint,5,opt,name=Rx_dropped,json=RxDropped" json:"Rx_dropped,omitempty"`
+ TxBytes uint64 `protobuf:"varint,6,opt,name=Tx_bytes,json=TxBytes" json:"Tx_bytes,omitempty"`
+ TxPackets uint64 `protobuf:"varint,7,opt,name=Tx_packets,json=TxPackets" json:"Tx_packets,omitempty"`
+ TxErrors uint64 `protobuf:"varint,8,opt,name=Tx_errors,json=TxErrors" json:"Tx_errors,omitempty"`
+ TxDropped uint64 `protobuf:"varint,9,opt,name=Tx_dropped,json=TxDropped" json:"Tx_dropped,omitempty"`
+}
+
+func (m *NetworkStats) Reset() { *m = NetworkStats{} }
+func (m *NetworkStats) String() string { return proto.CompactTextString(m) }
+func (*NetworkStats) ProtoMessage() {}
+func (*NetworkStats) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{33} }
+
+func (m *NetworkStats) GetName() string {
+ if m != nil {
+ return m.Name
+ }
+ return ""
+}
+
+func (m *NetworkStats) GetRxBytes() uint64 {
+ if m != nil {
+ return m.RxBytes
+ }
+ return 0
+}
+
+func (m *NetworkStats) GetRx_Packets() uint64 {
+ if m != nil {
+ return m.Rx_Packets
+ }
+ return 0
+}
+
+func (m *NetworkStats) GetRxErrors() uint64 {
+ if m != nil {
+ return m.RxErrors
+ }
+ return 0
+}
+
+func (m *NetworkStats) GetRxDropped() uint64 {
+ if m != nil {
+ return m.RxDropped
+ }
+ return 0
+}
+
+func (m *NetworkStats) GetTxBytes() uint64 {
+ if m != nil {
+ return m.TxBytes
+ }
+ return 0
+}
+
+func (m *NetworkStats) GetTxPackets() uint64 {
+ if m != nil {
+ return m.TxPackets
+ }
+ return 0
+}
+
+func (m *NetworkStats) GetTxErrors() uint64 {
+ if m != nil {
+ return m.TxErrors
+ }
+ return 0
+}
+
+func (m *NetworkStats) GetTxDropped() uint64 {
+ if m != nil {
+ return m.TxDropped
+ }
+ return 0
+}
+
+type CpuUsage struct {
+ TotalUsage uint64 `protobuf:"varint,1,opt,name=total_usage,json=totalUsage" json:"total_usage,omitempty"`
+ PercpuUsage []uint64 `protobuf:"varint,2,rep,packed,name=percpu_usage,json=percpuUsage" json:"percpu_usage,omitempty"`
+ UsageInKernelmode uint64 `protobuf:"varint,3,opt,name=usage_in_kernelmode,json=usageInKernelmode" json:"usage_in_kernelmode,omitempty"`
+ UsageInUsermode uint64 `protobuf:"varint,4,opt,name=usage_in_usermode,json=usageInUsermode" json:"usage_in_usermode,omitempty"`
+}
+
+func (m *CpuUsage) Reset() { *m = CpuUsage{} }
+func (m *CpuUsage) String() string { return proto.CompactTextString(m) }
+func (*CpuUsage) ProtoMessage() {}
+func (*CpuUsage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{34} }
+
+func (m *CpuUsage) GetTotalUsage() uint64 {
+ if m != nil {
+ return m.TotalUsage
+ }
+ return 0
+}
+
+func (m *CpuUsage) GetPercpuUsage() []uint64 {
+ if m != nil {
+ return m.PercpuUsage
+ }
+ return nil
+}
+
+func (m *CpuUsage) GetUsageInKernelmode() uint64 {
+ if m != nil {
+ return m.UsageInKernelmode
+ }
+ return 0
+}
+
+func (m *CpuUsage) GetUsageInUsermode() uint64 {
+ if m != nil {
+ return m.UsageInUsermode
+ }
+ return 0
+}
+
+type ThrottlingData struct {
+ Periods uint64 `protobuf:"varint,1,opt,name=periods" json:"periods,omitempty"`
+ ThrottledPeriods uint64 `protobuf:"varint,2,opt,name=throttled_periods,json=throttledPeriods" json:"throttled_periods,omitempty"`
+ ThrottledTime uint64 `protobuf:"varint,3,opt,name=throttled_time,json=throttledTime" json:"throttled_time,omitempty"`
+}
+
+func (m *ThrottlingData) Reset() { *m = ThrottlingData{} }
+func (m *ThrottlingData) String() string { return proto.CompactTextString(m) }
+func (*ThrottlingData) ProtoMessage() {}
+func (*ThrottlingData) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{35} }
+
+func (m *ThrottlingData) GetPeriods() uint64 {
+ if m != nil {
+ return m.Periods
+ }
+ return 0
+}
+
+func (m *ThrottlingData) GetThrottledPeriods() uint64 {
+ if m != nil {
+ return m.ThrottledPeriods
+ }
+ return 0
+}
+
+func (m *ThrottlingData) GetThrottledTime() uint64 {
+ if m != nil {
+ return m.ThrottledTime
+ }
+ return 0
+}
+
+type CpuStats struct {
+ CpuUsage *CpuUsage `protobuf:"bytes,1,opt,name=cpu_usage,json=cpuUsage" json:"cpu_usage,omitempty"`
+ ThrottlingData *ThrottlingData `protobuf:"bytes,2,opt,name=throttling_data,json=throttlingData" json:"throttling_data,omitempty"`
+ SystemUsage uint64 `protobuf:"varint,3,opt,name=system_usage,json=systemUsage" json:"system_usage,omitempty"`
+}
+
+func (m *CpuStats) Reset() { *m = CpuStats{} }
+func (m *CpuStats) String() string { return proto.CompactTextString(m) }
+func (*CpuStats) ProtoMessage() {}
+func (*CpuStats) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{36} }
+
+func (m *CpuStats) GetCpuUsage() *CpuUsage {
+ if m != nil {
+ return m.CpuUsage
+ }
+ return nil
+}
+
+func (m *CpuStats) GetThrottlingData() *ThrottlingData {
+ if m != nil {
+ return m.ThrottlingData
+ }
+ return nil
+}
+
+func (m *CpuStats) GetSystemUsage() uint64 {
+ if m != nil {
+ return m.SystemUsage
+ }
+ return 0
+}
+
+type PidsStats struct {
+ Current uint64 `protobuf:"varint,1,opt,name=current" json:"current,omitempty"`
+ Limit uint64 `protobuf:"varint,2,opt,name=limit" json:"limit,omitempty"`
+}
+
+func (m *PidsStats) Reset() { *m = PidsStats{} }
+func (m *PidsStats) String() string { return proto.CompactTextString(m) }
+func (*PidsStats) ProtoMessage() {}
+func (*PidsStats) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{37} }
+
+func (m *PidsStats) GetCurrent() uint64 {
+ if m != nil {
+ return m.Current
+ }
+ return 0
+}
+
+func (m *PidsStats) GetLimit() uint64 {
+ if m != nil {
+ return m.Limit
+ }
+ return 0
+}
+
+type MemoryData struct {
+ Usage uint64 `protobuf:"varint,1,opt,name=usage" json:"usage,omitempty"`
+ MaxUsage uint64 `protobuf:"varint,2,opt,name=max_usage,json=maxUsage" json:"max_usage,omitempty"`
+ Failcnt uint64 `protobuf:"varint,3,opt,name=failcnt" json:"failcnt,omitempty"`
+ Limit uint64 `protobuf:"varint,4,opt,name=limit" json:"limit,omitempty"`
+}
+
+func (m *MemoryData) Reset() { *m = MemoryData{} }
+func (m *MemoryData) String() string { return proto.CompactTextString(m) }
+func (*MemoryData) ProtoMessage() {}
+func (*MemoryData) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{38} }
+
+func (m *MemoryData) GetUsage() uint64 {
+ if m != nil {
+ return m.Usage
+ }
+ return 0
+}
+
+func (m *MemoryData) GetMaxUsage() uint64 {
+ if m != nil {
+ return m.MaxUsage
+ }
+ return 0
+}
+
+func (m *MemoryData) GetFailcnt() uint64 {
+ if m != nil {
+ return m.Failcnt
+ }
+ return 0
+}
+
+func (m *MemoryData) GetLimit() uint64 {
+ if m != nil {
+ return m.Limit
+ }
+ return 0
+}
+
+type MemoryStats struct {
+ Cache uint64 `protobuf:"varint,1,opt,name=cache" json:"cache,omitempty"`
+ Usage *MemoryData `protobuf:"bytes,2,opt,name=usage" json:"usage,omitempty"`
+ SwapUsage *MemoryData `protobuf:"bytes,3,opt,name=swap_usage,json=swapUsage" json:"swap_usage,omitempty"`
+ KernelUsage *MemoryData `protobuf:"bytes,4,opt,name=kernel_usage,json=kernelUsage" json:"kernel_usage,omitempty"`
+ Stats map[string]uint64 `protobuf:"bytes,5,rep,name=stats" json:"stats,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+}
+
+func (m *MemoryStats) Reset() { *m = MemoryStats{} }
+func (m *MemoryStats) String() string { return proto.CompactTextString(m) }
+func (*MemoryStats) ProtoMessage() {}
+func (*MemoryStats) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{39} }
+
+func (m *MemoryStats) GetCache() uint64 {
+ if m != nil {
+ return m.Cache
+ }
+ return 0
+}
+
+func (m *MemoryStats) GetUsage() *MemoryData {
+ if m != nil {
+ return m.Usage
+ }
+ return nil
+}
+
+func (m *MemoryStats) GetSwapUsage() *MemoryData {
+ if m != nil {
+ return m.SwapUsage
+ }
+ return nil
+}
+
+func (m *MemoryStats) GetKernelUsage() *MemoryData {
+ if m != nil {
+ return m.KernelUsage
+ }
+ return nil
+}
+
+func (m *MemoryStats) GetStats() map[string]uint64 {
+ if m != nil {
+ return m.Stats
+ }
+ return nil
+}
+
+type BlkioStatsEntry struct {
+ Major uint64 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"`
+ Minor uint64 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"`
+ Op string `protobuf:"bytes,3,opt,name=op" json:"op,omitempty"`
+ Value uint64 `protobuf:"varint,4,opt,name=value" json:"value,omitempty"`
+}
+
+func (m *BlkioStatsEntry) Reset() { *m = BlkioStatsEntry{} }
+func (m *BlkioStatsEntry) String() string { return proto.CompactTextString(m) }
+func (*BlkioStatsEntry) ProtoMessage() {}
+func (*BlkioStatsEntry) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{40} }
+
+func (m *BlkioStatsEntry) GetMajor() uint64 {
+ if m != nil {
+ return m.Major
+ }
+ return 0
+}
+
+func (m *BlkioStatsEntry) GetMinor() uint64 {
+ if m != nil {
+ return m.Minor
+ }
+ return 0
+}
+
+func (m *BlkioStatsEntry) GetOp() string {
+ if m != nil {
+ return m.Op
+ }
+ return ""
+}
+
+func (m *BlkioStatsEntry) GetValue() uint64 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+type BlkioStats struct {
+ IoServiceBytesRecursive []*BlkioStatsEntry `protobuf:"bytes,1,rep,name=io_service_bytes_recursive,json=ioServiceBytesRecursive" json:"io_service_bytes_recursive,omitempty"`
+ IoServicedRecursive []*BlkioStatsEntry `protobuf:"bytes,2,rep,name=io_serviced_recursive,json=ioServicedRecursive" json:"io_serviced_recursive,omitempty"`
+ IoQueuedRecursive []*BlkioStatsEntry `protobuf:"bytes,3,rep,name=io_queued_recursive,json=ioQueuedRecursive" json:"io_queued_recursive,omitempty"`
+ IoServiceTimeRecursive []*BlkioStatsEntry `protobuf:"bytes,4,rep,name=io_service_time_recursive,json=ioServiceTimeRecursive" json:"io_service_time_recursive,omitempty"`
+ IoWaitTimeRecursive []*BlkioStatsEntry `protobuf:"bytes,5,rep,name=io_wait_time_recursive,json=ioWaitTimeRecursive" json:"io_wait_time_recursive,omitempty"`
+ IoMergedRecursive []*BlkioStatsEntry `protobuf:"bytes,6,rep,name=io_merged_recursive,json=ioMergedRecursive" json:"io_merged_recursive,omitempty"`
+ IoTimeRecursive []*BlkioStatsEntry `protobuf:"bytes,7,rep,name=io_time_recursive,json=ioTimeRecursive" json:"io_time_recursive,omitempty"`
+ SectorsRecursive []*BlkioStatsEntry `protobuf:"bytes,8,rep,name=sectors_recursive,json=sectorsRecursive" json:"sectors_recursive,omitempty"`
+}
+
+func (m *BlkioStats) Reset() { *m = BlkioStats{} }
+func (m *BlkioStats) String() string { return proto.CompactTextString(m) }
+func (*BlkioStats) ProtoMessage() {}
+func (*BlkioStats) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{41} }
+
+func (m *BlkioStats) GetIoServiceBytesRecursive() []*BlkioStatsEntry {
+ if m != nil {
+ return m.IoServiceBytesRecursive
+ }
+ return nil
+}
+
+func (m *BlkioStats) GetIoServicedRecursive() []*BlkioStatsEntry {
+ if m != nil {
+ return m.IoServicedRecursive
+ }
+ return nil
+}
+
+func (m *BlkioStats) GetIoQueuedRecursive() []*BlkioStatsEntry {
+ if m != nil {
+ return m.IoQueuedRecursive
+ }
+ return nil
+}
+
+func (m *BlkioStats) GetIoServiceTimeRecursive() []*BlkioStatsEntry {
+ if m != nil {
+ return m.IoServiceTimeRecursive
+ }
+ return nil
+}
+
+func (m *BlkioStats) GetIoWaitTimeRecursive() []*BlkioStatsEntry {
+ if m != nil {
+ return m.IoWaitTimeRecursive
+ }
+ return nil
+}
+
+func (m *BlkioStats) GetIoMergedRecursive() []*BlkioStatsEntry {
+ if m != nil {
+ return m.IoMergedRecursive
+ }
+ return nil
+}
+
+func (m *BlkioStats) GetIoTimeRecursive() []*BlkioStatsEntry {
+ if m != nil {
+ return m.IoTimeRecursive
+ }
+ return nil
+}
+
+func (m *BlkioStats) GetSectorsRecursive() []*BlkioStatsEntry {
+ if m != nil {
+ return m.SectorsRecursive
+ }
+ return nil
+}
+
+type HugetlbStats struct {
+ Usage uint64 `protobuf:"varint,1,opt,name=usage" json:"usage,omitempty"`
+ MaxUsage uint64 `protobuf:"varint,2,opt,name=max_usage,json=maxUsage" json:"max_usage,omitempty"`
+ Failcnt uint64 `protobuf:"varint,3,opt,name=failcnt" json:"failcnt,omitempty"`
+ Limit uint64 `protobuf:"varint,4,opt,name=limit" json:"limit,omitempty"`
+}
+
+func (m *HugetlbStats) Reset() { *m = HugetlbStats{} }
+func (m *HugetlbStats) String() string { return proto.CompactTextString(m) }
+func (*HugetlbStats) ProtoMessage() {}
+func (*HugetlbStats) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{42} }
+
+func (m *HugetlbStats) GetUsage() uint64 {
+ if m != nil {
+ return m.Usage
+ }
+ return 0
+}
+
+func (m *HugetlbStats) GetMaxUsage() uint64 {
+ if m != nil {
+ return m.MaxUsage
+ }
+ return 0
+}
+
+func (m *HugetlbStats) GetFailcnt() uint64 {
+ if m != nil {
+ return m.Failcnt
+ }
+ return 0
+}
+
+func (m *HugetlbStats) GetLimit() uint64 {
+ if m != nil {
+ return m.Limit
+ }
+ return 0
+}
+
+type CgroupStats struct {
+ CpuStats *CpuStats `protobuf:"bytes,1,opt,name=cpu_stats,json=cpuStats" json:"cpu_stats,omitempty"`
+ MemoryStats *MemoryStats `protobuf:"bytes,2,opt,name=memory_stats,json=memoryStats" json:"memory_stats,omitempty"`
+ BlkioStats *BlkioStats `protobuf:"bytes,3,opt,name=blkio_stats,json=blkioStats" json:"blkio_stats,omitempty"`
+ HugetlbStats map[string]*HugetlbStats `protobuf:"bytes,4,rep,name=hugetlb_stats,json=hugetlbStats" json:"hugetlb_stats,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ PidsStats *PidsStats `protobuf:"bytes,5,opt,name=pids_stats,json=pidsStats" json:"pids_stats,omitempty"`
+}
+
+func (m *CgroupStats) Reset() { *m = CgroupStats{} }
+func (m *CgroupStats) String() string { return proto.CompactTextString(m) }
+func (*CgroupStats) ProtoMessage() {}
+func (*CgroupStats) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{43} }
+
+func (m *CgroupStats) GetCpuStats() *CpuStats {
+ if m != nil {
+ return m.CpuStats
+ }
+ return nil
+}
+
+func (m *CgroupStats) GetMemoryStats() *MemoryStats {
+ if m != nil {
+ return m.MemoryStats
+ }
+ return nil
+}
+
+func (m *CgroupStats) GetBlkioStats() *BlkioStats {
+ if m != nil {
+ return m.BlkioStats
+ }
+ return nil
+}
+
+func (m *CgroupStats) GetHugetlbStats() map[string]*HugetlbStats {
+ if m != nil {
+ return m.HugetlbStats
+ }
+ return nil
+}
+
+func (m *CgroupStats) GetPidsStats() *PidsStats {
+ if m != nil {
+ return m.PidsStats
+ }
+ return nil
+}
+
+type StatsResponse struct {
+ NetworkStats []*NetworkStats `protobuf:"bytes,1,rep,name=network_stats,json=networkStats" json:"network_stats,omitempty"`
+ CgroupStats *CgroupStats `protobuf:"bytes,2,opt,name=cgroup_stats,json=cgroupStats" json:"cgroup_stats,omitempty"`
+ // Tag 3 is deprecated (old uint64 timestamp)
+ Timestamp *google_protobuf.Timestamp `protobuf:"bytes,4,opt,name=timestamp" json:"timestamp,omitempty"`
+}
+
+func (m *StatsResponse) Reset() { *m = StatsResponse{} }
+func (m *StatsResponse) String() string { return proto.CompactTextString(m) }
+func (*StatsResponse) ProtoMessage() {}
+func (*StatsResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{44} }
+
+func (m *StatsResponse) GetNetworkStats() []*NetworkStats {
+ if m != nil {
+ return m.NetworkStats
+ }
+ return nil
+}
+
+func (m *StatsResponse) GetCgroupStats() *CgroupStats {
+ if m != nil {
+ return m.CgroupStats
+ }
+ return nil
+}
+
+func (m *StatsResponse) GetTimestamp() *google_protobuf.Timestamp {
+ if m != nil {
+ return m.Timestamp
+ }
+ return nil
+}
+
+type StatsRequest struct {
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+}
+
+func (m *StatsRequest) Reset() { *m = StatsRequest{} }
+func (m *StatsRequest) String() string { return proto.CompactTextString(m) }
+func (*StatsRequest) ProtoMessage() {}
+func (*StatsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{45} }
+
+func (m *StatsRequest) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func init() {
+ proto.RegisterType((*GetServerVersionRequest)(nil), "types.GetServerVersionRequest")
+ proto.RegisterType((*GetServerVersionResponse)(nil), "types.GetServerVersionResponse")
+ proto.RegisterType((*UpdateProcessRequest)(nil), "types.UpdateProcessRequest")
+ proto.RegisterType((*UpdateProcessResponse)(nil), "types.UpdateProcessResponse")
+ proto.RegisterType((*CreateContainerRequest)(nil), "types.CreateContainerRequest")
+ proto.RegisterType((*CreateContainerResponse)(nil), "types.CreateContainerResponse")
+ proto.RegisterType((*SignalRequest)(nil), "types.SignalRequest")
+ proto.RegisterType((*SignalResponse)(nil), "types.SignalResponse")
+ proto.RegisterType((*AddProcessRequest)(nil), "types.AddProcessRequest")
+ proto.RegisterType((*Rlimit)(nil), "types.Rlimit")
+ proto.RegisterType((*User)(nil), "types.User")
+ proto.RegisterType((*AddProcessResponse)(nil), "types.AddProcessResponse")
+ proto.RegisterType((*CreateCheckpointRequest)(nil), "types.CreateCheckpointRequest")
+ proto.RegisterType((*CreateCheckpointResponse)(nil), "types.CreateCheckpointResponse")
+ proto.RegisterType((*DeleteCheckpointRequest)(nil), "types.DeleteCheckpointRequest")
+ proto.RegisterType((*DeleteCheckpointResponse)(nil), "types.DeleteCheckpointResponse")
+ proto.RegisterType((*ListCheckpointRequest)(nil), "types.ListCheckpointRequest")
+ proto.RegisterType((*Checkpoint)(nil), "types.Checkpoint")
+ proto.RegisterType((*ListCheckpointResponse)(nil), "types.ListCheckpointResponse")
+ proto.RegisterType((*StateRequest)(nil), "types.StateRequest")
+ proto.RegisterType((*ContainerState)(nil), "types.ContainerState")
+ proto.RegisterType((*Process)(nil), "types.Process")
+ proto.RegisterType((*Container)(nil), "types.Container")
+ proto.RegisterType((*Machine)(nil), "types.Machine")
+ proto.RegisterType((*StateResponse)(nil), "types.StateResponse")
+ proto.RegisterType((*UpdateContainerRequest)(nil), "types.UpdateContainerRequest")
+ proto.RegisterType((*UpdateResource)(nil), "types.UpdateResource")
+ proto.RegisterType((*BlockIODevice)(nil), "types.BlockIODevice")
+ proto.RegisterType((*WeightDevice)(nil), "types.WeightDevice")
+ proto.RegisterType((*ThrottleDevice)(nil), "types.ThrottleDevice")
+ proto.RegisterType((*UpdateContainerResponse)(nil), "types.UpdateContainerResponse")
+ proto.RegisterType((*EventsRequest)(nil), "types.EventsRequest")
+ proto.RegisterType((*Event)(nil), "types.Event")
+ proto.RegisterType((*NetworkStats)(nil), "types.NetworkStats")
+ proto.RegisterType((*CpuUsage)(nil), "types.CpuUsage")
+ proto.RegisterType((*ThrottlingData)(nil), "types.ThrottlingData")
+ proto.RegisterType((*CpuStats)(nil), "types.CpuStats")
+ proto.RegisterType((*PidsStats)(nil), "types.PidsStats")
+ proto.RegisterType((*MemoryData)(nil), "types.MemoryData")
+ proto.RegisterType((*MemoryStats)(nil), "types.MemoryStats")
+ proto.RegisterType((*BlkioStatsEntry)(nil), "types.BlkioStatsEntry")
+ proto.RegisterType((*BlkioStats)(nil), "types.BlkioStats")
+ proto.RegisterType((*HugetlbStats)(nil), "types.HugetlbStats")
+ proto.RegisterType((*CgroupStats)(nil), "types.CgroupStats")
+ proto.RegisterType((*StatsResponse)(nil), "types.StatsResponse")
+ proto.RegisterType((*StatsRequest)(nil), "types.StatsRequest")
+}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for API service
+
+type APIClient interface {
+ GetServerVersion(ctx context.Context, in *GetServerVersionRequest, opts ...grpc.CallOption) (*GetServerVersionResponse, error)
+ CreateContainer(ctx context.Context, in *CreateContainerRequest, opts ...grpc.CallOption) (*CreateContainerResponse, error)
+ UpdateContainer(ctx context.Context, in *UpdateContainerRequest, opts ...grpc.CallOption) (*UpdateContainerResponse, error)
+ Signal(ctx context.Context, in *SignalRequest, opts ...grpc.CallOption) (*SignalResponse, error)
+ UpdateProcess(ctx context.Context, in *UpdateProcessRequest, opts ...grpc.CallOption) (*UpdateProcessResponse, error)
+ AddProcess(ctx context.Context, in *AddProcessRequest, opts ...grpc.CallOption) (*AddProcessResponse, error)
+ CreateCheckpoint(ctx context.Context, in *CreateCheckpointRequest, opts ...grpc.CallOption) (*CreateCheckpointResponse, error)
+ DeleteCheckpoint(ctx context.Context, in *DeleteCheckpointRequest, opts ...grpc.CallOption) (*DeleteCheckpointResponse, error)
+ ListCheckpoint(ctx context.Context, in *ListCheckpointRequest, opts ...grpc.CallOption) (*ListCheckpointResponse, error)
+ State(ctx context.Context, in *StateRequest, opts ...grpc.CallOption) (*StateResponse, error)
+ Events(ctx context.Context, in *EventsRequest, opts ...grpc.CallOption) (API_EventsClient, error)
+ Stats(ctx context.Context, in *StatsRequest, opts ...grpc.CallOption) (*StatsResponse, error)
+}
+
+type aPIClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewAPIClient(cc *grpc.ClientConn) APIClient {
+ return &aPIClient{cc}
+}
+
+func (c *aPIClient) GetServerVersion(ctx context.Context, in *GetServerVersionRequest, opts ...grpc.CallOption) (*GetServerVersionResponse, error) {
+ out := new(GetServerVersionResponse)
+ err := grpc.Invoke(ctx, "/types.API/GetServerVersion", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *aPIClient) CreateContainer(ctx context.Context, in *CreateContainerRequest, opts ...grpc.CallOption) (*CreateContainerResponse, error) {
+ out := new(CreateContainerResponse)
+ err := grpc.Invoke(ctx, "/types.API/CreateContainer", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *aPIClient) UpdateContainer(ctx context.Context, in *UpdateContainerRequest, opts ...grpc.CallOption) (*UpdateContainerResponse, error) {
+ out := new(UpdateContainerResponse)
+ err := grpc.Invoke(ctx, "/types.API/UpdateContainer", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *aPIClient) Signal(ctx context.Context, in *SignalRequest, opts ...grpc.CallOption) (*SignalResponse, error) {
+ out := new(SignalResponse)
+ err := grpc.Invoke(ctx, "/types.API/Signal", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *aPIClient) UpdateProcess(ctx context.Context, in *UpdateProcessRequest, opts ...grpc.CallOption) (*UpdateProcessResponse, error) {
+ out := new(UpdateProcessResponse)
+ err := grpc.Invoke(ctx, "/types.API/UpdateProcess", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *aPIClient) AddProcess(ctx context.Context, in *AddProcessRequest, opts ...grpc.CallOption) (*AddProcessResponse, error) {
+ out := new(AddProcessResponse)
+ err := grpc.Invoke(ctx, "/types.API/AddProcess", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *aPIClient) CreateCheckpoint(ctx context.Context, in *CreateCheckpointRequest, opts ...grpc.CallOption) (*CreateCheckpointResponse, error) {
+ out := new(CreateCheckpointResponse)
+ err := grpc.Invoke(ctx, "/types.API/CreateCheckpoint", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *aPIClient) DeleteCheckpoint(ctx context.Context, in *DeleteCheckpointRequest, opts ...grpc.CallOption) (*DeleteCheckpointResponse, error) {
+ out := new(DeleteCheckpointResponse)
+ err := grpc.Invoke(ctx, "/types.API/DeleteCheckpoint", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *aPIClient) ListCheckpoint(ctx context.Context, in *ListCheckpointRequest, opts ...grpc.CallOption) (*ListCheckpointResponse, error) {
+ out := new(ListCheckpointResponse)
+ err := grpc.Invoke(ctx, "/types.API/ListCheckpoint", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *aPIClient) State(ctx context.Context, in *StateRequest, opts ...grpc.CallOption) (*StateResponse, error) {
+ out := new(StateResponse)
+ err := grpc.Invoke(ctx, "/types.API/State", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *aPIClient) Events(ctx context.Context, in *EventsRequest, opts ...grpc.CallOption) (API_EventsClient, error) {
+ stream, err := grpc.NewClientStream(ctx, &_API_serviceDesc.Streams[0], c.cc, "/types.API/Events", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &aPIEventsClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type API_EventsClient interface {
+ Recv() (*Event, error)
+ grpc.ClientStream
+}
+
+type aPIEventsClient struct {
+ grpc.ClientStream
+}
+
+func (x *aPIEventsClient) Recv() (*Event, error) {
+ m := new(Event)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+func (c *aPIClient) Stats(ctx context.Context, in *StatsRequest, opts ...grpc.CallOption) (*StatsResponse, error) {
+ out := new(StatsResponse)
+ err := grpc.Invoke(ctx, "/types.API/Stats", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for API service
+
+type APIServer interface {
+ GetServerVersion(context.Context, *GetServerVersionRequest) (*GetServerVersionResponse, error)
+ CreateContainer(context.Context, *CreateContainerRequest) (*CreateContainerResponse, error)
+ UpdateContainer(context.Context, *UpdateContainerRequest) (*UpdateContainerResponse, error)
+ Signal(context.Context, *SignalRequest) (*SignalResponse, error)
+ UpdateProcess(context.Context, *UpdateProcessRequest) (*UpdateProcessResponse, error)
+ AddProcess(context.Context, *AddProcessRequest) (*AddProcessResponse, error)
+ CreateCheckpoint(context.Context, *CreateCheckpointRequest) (*CreateCheckpointResponse, error)
+ DeleteCheckpoint(context.Context, *DeleteCheckpointRequest) (*DeleteCheckpointResponse, error)
+ ListCheckpoint(context.Context, *ListCheckpointRequest) (*ListCheckpointResponse, error)
+ State(context.Context, *StateRequest) (*StateResponse, error)
+ Events(*EventsRequest, API_EventsServer) error
+ Stats(context.Context, *StatsRequest) (*StatsResponse, error)
+}
+
+func RegisterAPIServer(s *grpc.Server, srv APIServer) {
+ s.RegisterService(&_API_serviceDesc, srv)
+}
+
+func _API_GetServerVersion_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetServerVersionRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).GetServerVersion(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/GetServerVersion",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).GetServerVersion(ctx, req.(*GetServerVersionRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _API_CreateContainer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreateContainerRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).CreateContainer(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/CreateContainer",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).CreateContainer(ctx, req.(*CreateContainerRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _API_UpdateContainer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateContainerRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).UpdateContainer(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/UpdateContainer",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).UpdateContainer(ctx, req.(*UpdateContainerRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _API_Signal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(SignalRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).Signal(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/Signal",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).Signal(ctx, req.(*SignalRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _API_UpdateProcess_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateProcessRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).UpdateProcess(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/UpdateProcess",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).UpdateProcess(ctx, req.(*UpdateProcessRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _API_AddProcess_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(AddProcessRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).AddProcess(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/AddProcess",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).AddProcess(ctx, req.(*AddProcessRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _API_CreateCheckpoint_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreateCheckpointRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).CreateCheckpoint(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/CreateCheckpoint",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).CreateCheckpoint(ctx, req.(*CreateCheckpointRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _API_DeleteCheckpoint_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(DeleteCheckpointRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).DeleteCheckpoint(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/DeleteCheckpoint",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).DeleteCheckpoint(ctx, req.(*DeleteCheckpointRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _API_ListCheckpoint_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListCheckpointRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).ListCheckpoint(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/ListCheckpoint",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).ListCheckpoint(ctx, req.(*ListCheckpointRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _API_State_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(StateRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).State(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/State",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).State(ctx, req.(*StateRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _API_Events_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(EventsRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(APIServer).Events(m, &aPIEventsServer{stream})
+}
+
+type API_EventsServer interface {
+ Send(*Event) error
+ grpc.ServerStream
+}
+
+type aPIEventsServer struct {
+ grpc.ServerStream
+}
+
+func (x *aPIEventsServer) Send(m *Event) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+func _API_Stats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(StatsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(APIServer).Stats(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/types.API/Stats",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(APIServer).Stats(ctx, req.(*StatsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _API_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "types.API",
+ HandlerType: (*APIServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "GetServerVersion",
+ Handler: _API_GetServerVersion_Handler,
+ },
+ {
+ MethodName: "CreateContainer",
+ Handler: _API_CreateContainer_Handler,
+ },
+ {
+ MethodName: "UpdateContainer",
+ Handler: _API_UpdateContainer_Handler,
+ },
+ {
+ MethodName: "Signal",
+ Handler: _API_Signal_Handler,
+ },
+ {
+ MethodName: "UpdateProcess",
+ Handler: _API_UpdateProcess_Handler,
+ },
+ {
+ MethodName: "AddProcess",
+ Handler: _API_AddProcess_Handler,
+ },
+ {
+ MethodName: "CreateCheckpoint",
+ Handler: _API_CreateCheckpoint_Handler,
+ },
+ {
+ MethodName: "DeleteCheckpoint",
+ Handler: _API_DeleteCheckpoint_Handler,
+ },
+ {
+ MethodName: "ListCheckpoint",
+ Handler: _API_ListCheckpoint_Handler,
+ },
+ {
+ MethodName: "State",
+ Handler: _API_State_Handler,
+ },
+ {
+ MethodName: "Stats",
+ Handler: _API_Stats_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "Events",
+ Handler: _API_Events_Handler,
+ ServerStreams: true,
+ },
+ },
+ Metadata: "api.proto",
+}
+
+func init() { proto.RegisterFile("api.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 2632 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x19, 0x4d, 0x6f, 0x24, 0x47,
+ 0x75, 0x67, 0xa6, 0xed, 0xf1, 0xbc, 0xf9, 0xb0, 0xa7, 0xd6, 0xeb, 0xed, 0x9d, 0x24, 0xbb, 0x4e,
+ 0x2b, 0x10, 0x03, 0x91, 0xb3, 0x78, 0x13, 0x58, 0x11, 0x09, 0x69, 0xd7, 0x1b, 0x82, 0xc9, 0x3a,
+ 0x99, 0xb4, 0x6d, 0x56, 0x48, 0x48, 0xa3, 0x76, 0x77, 0xed, 0x4c, 0xe1, 0x9e, 0xae, 0x4e, 0x75,
+ 0xb5, 0x3d, 0xbe, 0xe4, 0xc0, 0x01, 0x0e, 0x48, 0x70, 0x45, 0xe2, 0xc8, 0x8d, 0x3b, 0x07, 0xf8,
+ 0x03, 0x48, 0xfc, 0x10, 0x6e, 0xdc, 0x39, 0xa2, 0xfa, 0xe8, 0xea, 0xea, 0xf9, 0xf0, 0x6e, 0x90,
+ 0x10, 0x17, 0x2e, 0xad, 0x7a, 0xaf, 0xde, 0x57, 0xbd, 0x7a, 0xef, 0xd5, 0xab, 0x6a, 0x68, 0x05,
+ 0x29, 0xd9, 0x4f, 0x19, 0xe5, 0x14, 0xad, 0xf1, 0xeb, 0x14, 0x67, 0x83, 0x07, 0x63, 0x4a, 0xc7,
+ 0x31, 0x7e, 0x5f, 0x22, 0xcf, 0xf3, 0x97, 0xef, 0x73, 0x32, 0xc5, 0x19, 0x0f, 0xa6, 0xa9, 0xa2,
+ 0xf3, 0xee, 0xc1, 0xdd, 0x4f, 0x30, 0x3f, 0xc1, 0xec, 0x12, 0xb3, 0x9f, 0x62, 0x96, 0x11, 0x9a,
+ 0xf8, 0xf8, 0xcb, 0x1c, 0x67, 0xdc, 0x9b, 0x81, 0xbb, 0x38, 0x95, 0xa5, 0x34, 0xc9, 0x30, 0xda,
+ 0x86, 0xb5, 0x69, 0xf0, 0x0b, 0xca, 0xdc, 0xda, 0x6e, 0x6d, 0xaf, 0xeb, 0x2b, 0x40, 0x62, 0x49,
+ 0x42, 0x99, 0x5b, 0xd7, 0x58, 0x01, 0x08, 0x6c, 0x1a, 0xf0, 0x70, 0xe2, 0x36, 0x14, 0x56, 0x02,
+ 0x68, 0x00, 0x1b, 0x0c, 0x5f, 0x12, 0x21, 0xd5, 0x75, 0x76, 0x6b, 0x7b, 0x2d, 0xdf, 0xc0, 0xde,
+ 0xaf, 0x6a, 0xb0, 0x7d, 0x96, 0x46, 0x01, 0xc7, 0x43, 0x46, 0x43, 0x9c, 0x65, 0xda, 0x24, 0xd4,
+ 0x83, 0x3a, 0x89, 0xa4, 0xce, 0x96, 0x5f, 0x27, 0x11, 0xda, 0x82, 0x46, 0x4a, 0x22, 0xa9, 0xae,
+ 0xe5, 0x8b, 0x21, 0xba, 0x0f, 0x10, 0xc6, 0x34, 0xc3, 0x27, 0x3c, 0x22, 0x89, 0xd4, 0xb8, 0xe1,
+ 0x5b, 0x18, 0x61, 0xcc, 0x15, 0x89, 0xf8, 0x44, 0xea, 0xec, 0xfa, 0x0a, 0x40, 0x3b, 0xb0, 0x3e,
+ 0xc1, 0x64, 0x3c, 0xe1, 0xee, 0x9a, 0x44, 0x6b, 0xc8, 0xbb, 0x0b, 0x77, 0xe6, 0xec, 0x50, 0xeb,
+ 0xf7, 0xfe, 0x5e, 0x87, 0x9d, 0x43, 0x86, 0x03, 0x8e, 0x0f, 0x69, 0xc2, 0x03, 0x92, 0x60, 0xb6,
+ 0xca, 0xc6, 0xfb, 0x00, 0xe7, 0x79, 0x12, 0xc5, 0x78, 0x18, 0xf0, 0x89, 0x36, 0xd5, 0xc2, 0x48,
+ 0x8b, 0x27, 0x38, 0xbc, 0x48, 0x29, 0x49, 0xb8, 0xb4, 0xb8, 0xe5, 0x5b, 0x18, 0x61, 0x71, 0x26,
+ 0x17, 0xa3, 0xbc, 0xa4, 0x00, 0x61, 0x71, 0xc6, 0x23, 0x9a, 0x2b, 0x8b, 0x5b, 0xbe, 0x86, 0x34,
+ 0x1e, 0x33, 0xe6, 0xae, 0x1b, 0x3c, 0x66, 0x4c, 0xe0, 0xe3, 0xe0, 0x1c, 0xc7, 0x99, 0xdb, 0xdc,
+ 0x6d, 0x08, 0xbc, 0x82, 0xd0, 0x2e, 0xb4, 0x13, 0x3a, 0x24, 0x97, 0x94, 0xfb, 0x94, 0x72, 0x77,
+ 0x43, 0x3a, 0xcc, 0x46, 0x21, 0x17, 0x9a, 0x2c, 0x4f, 0x44, 0xdc, 0xb8, 0x2d, 0x29, 0xb2, 0x00,
+ 0x05, 0xaf, 0x1e, 0x3e, 0x61, 0xe3, 0xcc, 0x05, 0x29, 0xd8, 0x46, 0xa1, 0x77, 0xa0, 0x5b, 0xae,
+ 0xe4, 0x19, 0x61, 0x6e, 0x5b, 0x4a, 0xa8, 0x22, 0xbd, 0x23, 0xb8, 0xbb, 0xe0, 0x4b, 0x1d, 0x67,
+ 0xfb, 0xd0, 0x0a, 0x0b, 0xa4, 0xf4, 0x69, 0xfb, 0x60, 0x6b, 0x5f, 0x86, 0xf6, 0x7e, 0x49, 0x5c,
+ 0x92, 0x78, 0x47, 0xd0, 0x3d, 0x21, 0xe3, 0x24, 0x88, 0x5f, 0x3f, 0x62, 0x84, 0xc7, 0x24, 0x8b,
+ 0x8e, 0x4f, 0x0d, 0x79, 0x5b, 0xd0, 0x2b, 0x44, 0xe9, 0x4d, 0xff, 0x73, 0x03, 0xfa, 0x4f, 0xa2,
+ 0xe8, 0x15, 0x31, 0x39, 0x80, 0x0d, 0x8e, 0xd9, 0x94, 0x08, 0x89, 0x75, 0xe9, 0x4e, 0x03, 0xa3,
+ 0x07, 0xe0, 0xe4, 0x19, 0x66, 0x52, 0x53, 0xfb, 0xa0, 0xad, 0x57, 0x72, 0x96, 0x61, 0xe6, 0xcb,
+ 0x09, 0x84, 0xc0, 0x09, 0x84, 0x2f, 0x1d, 0xe9, 0x4b, 0x39, 0x16, 0x26, 0xe3, 0xe4, 0xd2, 0x5d,
+ 0x93, 0x28, 0x31, 0x14, 0x98, 0xf0, 0x2a, 0xd2, 0x3b, 0x2c, 0x86, 0xc5, 0xb2, 0x9a, 0xe5, 0xb2,
+ 0x4c, 0xd8, 0x6c, 0x2c, 0x0f, 0x9b, 0xd6, 0x8a, 0xb0, 0x81, 0x4a, 0xd8, 0x78, 0xd0, 0x09, 0x83,
+ 0x34, 0x38, 0x27, 0x31, 0xe1, 0x04, 0x67, 0x6e, 0x5b, 0x1a, 0x51, 0xc1, 0xa1, 0x3d, 0xd8, 0x0c,
+ 0xd2, 0x34, 0x60, 0x53, 0xca, 0x86, 0x8c, 0xbe, 0x24, 0x31, 0x76, 0x3b, 0x52, 0xc8, 0x3c, 0x5a,
+ 0x48, 0xcb, 0x70, 0x4c, 0x92, 0x7c, 0xf6, 0x5c, 0x44, 0x9f, 0xdb, 0x95, 0x64, 0x15, 0x9c, 0x90,
+ 0x96, 0xd0, 0xcf, 0xf0, 0xd5, 0x90, 0x91, 0x4b, 0x12, 0xe3, 0x31, 0xce, 0xdc, 0x9e, 0xf4, 0xe2,
+ 0x3c, 0x1a, 0xbd, 0x0b, 0x4d, 0x16, 0x93, 0x29, 0xe1, 0x99, 0xbb, 0xb9, 0xdb, 0xd8, 0x6b, 0x1f,
+ 0x74, 0xb5, 0x3f, 0x7d, 0x89, 0xf5, 0x8b, 0x59, 0xef, 0x19, 0xac, 0x2b, 0x94, 0x70, 0xaf, 0x20,
+ 0xd1, 0xbb, 0x25, 0xc7, 0x02, 0x97, 0xd1, 0x97, 0x5c, 0xee, 0x95, 0xe3, 0xcb, 0xb1, 0xc0, 0x4d,
+ 0x02, 0x16, 0xc9, 0x7d, 0x72, 0x7c, 0x39, 0xf6, 0x7c, 0x70, 0xc4, 0x46, 0x09, 0x57, 0xe7, 0x7a,
+ 0xc3, 0xbb, 0xbe, 0x18, 0x0a, 0xcc, 0x58, 0xc7, 0x54, 0xd7, 0x17, 0x43, 0xf4, 0x4d, 0xe8, 0x05,
+ 0x51, 0x44, 0x38, 0xa1, 0x49, 0x10, 0x7f, 0x42, 0xa2, 0xcc, 0x6d, 0xec, 0x36, 0xf6, 0xba, 0xfe,
+ 0x1c, 0xd6, 0x3b, 0x00, 0x64, 0x07, 0x94, 0x0e, 0xfa, 0x37, 0xa1, 0x95, 0x5d, 0x67, 0x1c, 0x4f,
+ 0x87, 0x46, 0x4f, 0x89, 0xf0, 0x7e, 0x59, 0x33, 0xe9, 0x62, 0xb2, 0x68, 0x55, 0x2c, 0x7e, 0xb7,
+ 0x52, 0x5b, 0xea, 0x32, 0xea, 0xfa, 0x45, 0xfe, 0x94, 0xdc, 0x76, 0xb9, 0x59, 0x48, 0xd9, 0xc6,
+ 0xb2, 0x94, 0x1d, 0x80, 0xbb, 0x68, 0x83, 0x4e, 0x93, 0x10, 0xee, 0x3e, 0xc3, 0x31, 0x7e, 0x1d,
+ 0xfb, 0x10, 0x38, 0x49, 0x30, 0xc5, 0x3a, 0x1d, 0xe5, 0xf8, 0xf5, 0x0d, 0x58, 0x54, 0xa2, 0x0d,
+ 0x38, 0x86, 0x3b, 0xcf, 0x49, 0xc6, 0x5f, 0xad, 0x7e, 0x41, 0x55, 0x7d, 0x99, 0xaa, 0xdf, 0xd7,
+ 0x00, 0x4a, 0x59, 0xc6, 0xe6, 0x9a, 0x65, 0x33, 0x02, 0x07, 0xcf, 0x08, 0xd7, 0xf9, 0x2e, 0xc7,
+ 0x22, 0x2a, 0x78, 0x98, 0xea, 0x23, 0x48, 0x0c, 0x45, 0xbd, 0xcc, 0x13, 0x32, 0x3b, 0xa1, 0xe1,
+ 0x05, 0xe6, 0x99, 0xac, 0xe7, 0x1b, 0xbe, 0x8d, 0x92, 0x49, 0x3b, 0xc1, 0x71, 0x2c, 0x8b, 0xfa,
+ 0x86, 0xaf, 0x00, 0x51, 0x81, 0xf1, 0x34, 0xe5, 0xd7, 0x9f, 0x9d, 0xb8, 0xeb, 0x32, 0xff, 0x0a,
+ 0xd0, 0x3b, 0x86, 0x9d, 0xf9, 0x95, 0xea, 0x18, 0x7a, 0x04, 0xed, 0x72, 0x15, 0x99, 0x5b, 0x93,
+ 0x09, 0xb2, 0x64, 0xeb, 0x6d, 0x2a, 0xef, 0x3e, 0x74, 0x4e, 0x78, 0xc0, 0xf1, 0x0a, 0x7f, 0x79,
+ 0x7b, 0xd0, 0x33, 0x55, 0x57, 0x12, 0xaa, 0xba, 0x11, 0xf0, 0x3c, 0xd3, 0x54, 0x1a, 0xf2, 0xfe,
+ 0xd2, 0x80, 0xa6, 0x0e, 0xeb, 0xa2, 0x36, 0xd5, 0xca, 0xda, 0xf4, 0x3f, 0x29, 0x91, 0x95, 0xac,
+ 0x6a, 0xce, 0x65, 0xd5, 0xff, 0xcb, 0x65, 0x59, 0x2e, 0xff, 0x56, 0x83, 0x96, 0xd9, 0xe6, 0xaf,
+ 0xdd, 0xce, 0xbc, 0x07, 0xad, 0x54, 0x6d, 0x3c, 0x56, 0x55, 0xaf, 0x7d, 0xd0, 0xd3, 0x8a, 0x8a,
+ 0x3a, 0x57, 0x12, 0x58, 0xf1, 0xe3, 0xd8, 0xf1, 0x63, 0xb5, 0x2b, 0x6b, 0x95, 0x76, 0x05, 0x81,
+ 0x93, 0x8a, 0x72, 0xba, 0x2e, 0xcb, 0xa9, 0x1c, 0xdb, 0x0d, 0x4a, 0xb3, 0xd2, 0xa0, 0x78, 0x1f,
+ 0x42, 0xf3, 0x38, 0x08, 0x27, 0x24, 0x91, 0x19, 0x1a, 0xa6, 0x3a, 0x4c, 0xbb, 0xbe, 0x1c, 0x0b,
+ 0x25, 0x53, 0x3c, 0xa5, 0xec, 0x5a, 0xd7, 0x7e, 0x0d, 0x79, 0x17, 0xd0, 0xd5, 0x69, 0xa0, 0x93,
+ 0xe9, 0x21, 0x80, 0x69, 0x31, 0x8a, 0x5c, 0x5a, 0x6c, 0x43, 0x2c, 0x1a, 0xb4, 0x07, 0xcd, 0xa9,
+ 0xd2, 0xac, 0xab, 0x6e, 0xe1, 0x03, 0x6d, 0x8f, 0x5f, 0x4c, 0x7b, 0xbf, 0xae, 0xc1, 0x8e, 0xea,
+ 0x31, 0x5f, 0xd9, 0x49, 0x2e, 0xef, 0x5d, 0x94, 0xfb, 0x1a, 0x15, 0xf7, 0x3d, 0x82, 0x16, 0xc3,
+ 0x19, 0xcd, 0x59, 0x88, 0x95, 0x67, 0xdb, 0x07, 0x77, 0x8a, 0x4c, 0x92, 0xba, 0x7c, 0x3d, 0xeb,
+ 0x97, 0x74, 0xde, 0x6f, 0x9a, 0xd0, 0xab, 0xce, 0x8a, 0x8a, 0x75, 0x1e, 0x5f, 0x10, 0xfa, 0x42,
+ 0x35, 0xc7, 0x35, 0xe9, 0x26, 0x1b, 0x25, 0xb2, 0x2a, 0x4c, 0xf3, 0x93, 0x49, 0xc0, 0x70, 0xa6,
+ 0xdd, 0x58, 0x22, 0xf4, 0xec, 0x10, 0x33, 0x42, 0x8b, 0xc3, 0xb4, 0x44, 0x88, 0x32, 0x10, 0xa6,
+ 0xf9, 0x17, 0x39, 0xe5, 0x81, 0x34, 0xd2, 0xf1, 0x0d, 0x2c, 0xbb, 0xe2, 0x34, 0xcf, 0x30, 0x3f,
+ 0x14, 0xbb, 0xb6, 0xa6, 0xbb, 0x62, 0x83, 0x29, 0xe7, 0x8f, 0xf1, 0x34, 0xd3, 0x69, 0x6e, 0x61,
+ 0x84, 0xe5, 0x6a, 0x37, 0x9f, 0x8b, 0xa0, 0x96, 0x81, 0xe1, 0xf8, 0x36, 0x4a, 0x48, 0x50, 0xe0,
+ 0xc9, 0x55, 0x90, 0xca, 0xb4, 0x77, 0x7c, 0x0b, 0x83, 0xde, 0x83, 0xbe, 0x82, 0x7c, 0x9c, 0x61,
+ 0x76, 0x19, 0x88, 0x63, 0x5b, 0x96, 0x01, 0xc7, 0x5f, 0x9c, 0x10, 0xd4, 0x17, 0x98, 0x25, 0x38,
+ 0x3e, 0xb6, 0xb4, 0x82, 0xa2, 0x5e, 0x98, 0x40, 0x07, 0xb0, 0xad, 0x90, 0xa7, 0x87, 0x43, 0x9b,
+ 0xa1, 0x2d, 0x19, 0x96, 0xce, 0x89, 0x4c, 0x97, 0x8e, 0x7f, 0x8e, 0x83, 0x97, 0x7a, 0x3f, 0x3a,
+ 0x92, 0x7c, 0x1e, 0x8d, 0x9e, 0x40, 0xdf, 0xda, 0xa2, 0x67, 0xf8, 0x92, 0x84, 0xd8, 0xed, 0xca,
+ 0xa8, 0xbd, 0xad, 0xa3, 0xc0, 0x9e, 0xf2, 0x17, 0xa9, 0xd1, 0x19, 0x0c, 0x24, 0xf2, 0x74, 0xc2,
+ 0x28, 0xe7, 0x31, 0xf6, 0x71, 0x10, 0x3d, 0x4d, 0x33, 0x2d, 0xab, 0x27, 0x65, 0x15, 0x11, 0x55,
+ 0xd0, 0x68, 0x69, 0x37, 0x30, 0xa2, 0x17, 0xf0, 0x46, 0x65, 0xf6, 0x05, 0x23, 0x1c, 0x97, 0x72,
+ 0x37, 0x6f, 0x92, 0x7b, 0x13, 0xe7, 0x82, 0x60, 0xa1, 0xf6, 0x88, 0x1a, 0xc1, 0x5b, 0xaf, 0x2f,
+ 0xb8, 0xca, 0x89, 0x7e, 0x06, 0x6f, 0x2e, 0xea, 0xb5, 0x24, 0xf7, 0x6f, 0x92, 0x7c, 0x23, 0xab,
+ 0x48, 0x0e, 0x51, 0xbf, 0xd4, 0xce, 0x23, 0x95, 0x1c, 0x06, 0xe1, 0x7d, 0x04, 0xdd, 0xa7, 0x31,
+ 0x0d, 0x2f, 0x8e, 0x3e, 0xd7, 0xe4, 0x95, 0x2b, 0x77, 0x63, 0xe9, 0x95, 0xbb, 0xa1, 0xaf, 0xdc,
+ 0xde, 0x57, 0xd0, 0xa9, 0x6c, 0xe7, 0xf7, 0x64, 0x1e, 0x17, 0xa2, 0xf4, 0x45, 0x6a, 0x5b, 0x1b,
+ 0x5d, 0x51, 0xe3, 0xdb, 0x84, 0xa2, 0xbe, 0x5c, 0xa9, 0x50, 0x53, 0xcd, 0xad, 0x86, 0x44, 0xee,
+ 0xc4, 0x65, 0x18, 0xaa, 0x7b, 0x93, 0x85, 0xf1, 0x7e, 0x0e, 0xbd, 0xaa, 0x2b, 0xfe, 0x63, 0x0b,
+ 0x10, 0x38, 0x2c, 0xe0, 0xb8, 0xe8, 0xce, 0xc5, 0xd8, 0xbb, 0x07, 0x77, 0x17, 0x2a, 0xa6, 0x6e,
+ 0xfd, 0xae, 0xa1, 0xfb, 0xf1, 0x25, 0x4e, 0xb8, 0xb9, 0x9d, 0x3d, 0x86, 0x96, 0x79, 0xf2, 0xd0,
+ 0xa5, 0x78, 0xb0, 0xaf, 0x1e, 0x45, 0xf6, 0x8b, 0x47, 0x91, 0xfd, 0xd3, 0x82, 0xc2, 0x2f, 0x89,
+ 0xc5, 0x1a, 0x33, 0x4e, 0x19, 0x8e, 0x3e, 0x4f, 0xe2, 0xeb, 0xe2, 0x25, 0xa1, 0xc4, 0xe8, 0xea,
+ 0xec, 0x98, 0xe6, 0xe8, 0x77, 0x35, 0x58, 0x93, 0xba, 0x97, 0xde, 0x32, 0x14, 0x75, 0xdd, 0xd4,
+ 0xf2, 0x6a, 0xe5, 0xee, 0x9a, 0xca, 0xad, 0x6b, 0xbc, 0x53, 0xd6, 0xf8, 0xca, 0x0a, 0xd6, 0xbf,
+ 0xc6, 0x0a, 0xbc, 0xdf, 0xd6, 0xa1, 0xf3, 0x19, 0xe6, 0x57, 0x94, 0x5d, 0x88, 0xf3, 0x2c, 0x5b,
+ 0xda, 0xba, 0xde, 0x83, 0x0d, 0x36, 0x1b, 0x9d, 0x5f, 0x73, 0x53, 0xbf, 0x9b, 0x6c, 0xf6, 0x54,
+ 0x80, 0xe8, 0x2d, 0x00, 0x36, 0x1b, 0x0d, 0x03, 0xd5, 0xae, 0xea, 0xf2, 0xcd, 0x66, 0x1a, 0x81,
+ 0xde, 0x80, 0x96, 0x3f, 0x1b, 0x61, 0xc6, 0x28, 0xcb, 0x8a, 0xfa, 0xed, 0xcf, 0x3e, 0x96, 0xb0,
+ 0xe0, 0xf5, 0x67, 0xa3, 0x88, 0xd1, 0x34, 0xc5, 0x91, 0xac, 0xdf, 0x8e, 0xdf, 0xf2, 0x67, 0xcf,
+ 0x14, 0x42, 0x68, 0x3d, 0x2d, 0xb4, 0xae, 0x2b, 0xad, 0xa7, 0xa5, 0xd6, 0xd3, 0xd9, 0x28, 0xd5,
+ 0x5a, 0x55, 0xe1, 0x6e, 0x9d, 0xda, 0x5a, 0x4f, 0x8d, 0x56, 0x55, 0xb5, 0x37, 0x4e, 0x2d, 0xad,
+ 0xa7, 0xa5, 0xd6, 0x56, 0xc1, 0xab, 0xb5, 0x7a, 0x7f, 0xaa, 0xc1, 0xc6, 0x61, 0x9a, 0x9f, 0x65,
+ 0xc1, 0x18, 0xa3, 0x07, 0xd0, 0xe6, 0x94, 0x07, 0xf1, 0x28, 0x17, 0xa0, 0x3e, 0xdb, 0x40, 0xa2,
+ 0x14, 0xc1, 0xdb, 0xd0, 0x49, 0x31, 0x0b, 0xd3, 0x5c, 0x53, 0xd4, 0x77, 0x1b, 0xe2, 0x0c, 0x51,
+ 0x38, 0x45, 0xb2, 0x0f, 0xb7, 0xe5, 0xdc, 0x88, 0x24, 0x23, 0x55, 0xb4, 0xa7, 0x34, 0xc2, 0xda,
+ 0x55, 0x7d, 0x39, 0x75, 0x94, 0x7c, 0x6a, 0x26, 0xd0, 0xb7, 0xa1, 0x6f, 0xe8, 0x45, 0x33, 0x2b,
+ 0xa9, 0x95, 0xeb, 0x36, 0x35, 0xf5, 0x99, 0x46, 0x7b, 0x5f, 0x99, 0x1c, 0x22, 0xc9, 0xf8, 0x59,
+ 0xc0, 0x03, 0xd1, 0xe8, 0xa4, 0xf2, 0xe4, 0xcc, 0xb4, 0xb5, 0x05, 0x88, 0xbe, 0x03, 0x7d, 0xae,
+ 0xf3, 0x2d, 0x1a, 0x15, 0x34, 0x6a, 0x37, 0xb7, 0xcc, 0xc4, 0x50, 0x13, 0x7f, 0x03, 0x7a, 0x25,
+ 0xb1, 0x6c, 0x9b, 0x94, 0xbd, 0x5d, 0x83, 0x15, 0xd1, 0xe4, 0xfd, 0x41, 0x39, 0x4b, 0x45, 0xce,
+ 0x7b, 0xf2, 0x20, 0xb7, 0x5c, 0xd5, 0x3e, 0xd8, 0x2c, 0x1a, 0x20, 0xed, 0x0c, 0x79, 0x78, 0x2b,
+ 0xb7, 0xfc, 0x10, 0x36, 0xb9, 0x31, 0x7d, 0x14, 0x05, 0x3c, 0xd0, 0xa9, 0x37, 0x57, 0x27, 0xf5,
+ 0xc2, 0xfc, 0x1e, 0xaf, 0x2e, 0xf4, 0x6d, 0xe8, 0xa8, 0xce, 0x5c, 0x2b, 0x54, 0xf6, 0xb5, 0x15,
+ 0x4e, 0xaa, 0xf0, 0x3e, 0x82, 0xd6, 0x90, 0x44, 0x99, 0xb2, 0xce, 0x85, 0x66, 0x98, 0x33, 0x86,
+ 0x93, 0xa2, 0x45, 0x29, 0x40, 0x51, 0x1e, 0x65, 0x57, 0xab, 0x9d, 0xa1, 0x00, 0x8f, 0x02, 0xa8,
+ 0x93, 0x55, 0x6a, 0xdb, 0x86, 0x35, 0x3b, 0x04, 0x14, 0x20, 0xe2, 0x6c, 0x1a, 0xcc, 0xcc, 0xd6,
+ 0xcb, 0x38, 0x9b, 0x06, 0x33, 0xb5, 0x40, 0x17, 0x9a, 0x2f, 0x03, 0x12, 0x87, 0xfa, 0xc1, 0xce,
+ 0xf1, 0x0b, 0xb0, 0x54, 0xe8, 0xd8, 0x0a, 0xff, 0x58, 0x87, 0xb6, 0xd2, 0xa8, 0x0c, 0xde, 0x86,
+ 0xb5, 0x30, 0x08, 0x27, 0x46, 0xa5, 0x04, 0xd0, 0xbb, 0x85, 0x21, 0xd5, 0x8b, 0x7a, 0x69, 0x6a,
+ 0x61, 0xdb, 0x43, 0x80, 0xec, 0x2a, 0x48, 0x2d, 0xef, 0x2c, 0xa5, 0x6e, 0x09, 0x22, 0x65, 0xf0,
+ 0x07, 0xd0, 0x51, 0xf1, 0xa9, 0x79, 0x9c, 0x55, 0x3c, 0x6d, 0x45, 0xa6, 0xb8, 0x1e, 0x89, 0x4b,
+ 0x51, 0xc0, 0x55, 0x13, 0xde, 0x3e, 0x78, 0xab, 0x42, 0x2e, 0x57, 0xb2, 0x2f, 0xbf, 0x1f, 0x27,
+ 0x9c, 0x5d, 0xfb, 0x8a, 0x76, 0xf0, 0x18, 0xa0, 0x44, 0x8a, 0x7a, 0x76, 0x81, 0xaf, 0x8b, 0xcb,
+ 0xdf, 0x05, 0xbe, 0x16, 0x6b, 0xbf, 0x0c, 0xe2, 0xbc, 0x70, 0xaa, 0x02, 0x7e, 0x50, 0x7f, 0x5c,
+ 0xf3, 0x42, 0xd8, 0x7c, 0x2a, 0x0e, 0x4c, 0x8b, 0xbd, 0x72, 0xe8, 0x39, 0x4b, 0x0f, 0x3d, 0xa7,
+ 0x78, 0x67, 0xee, 0x41, 0x9d, 0xa6, 0xba, 0x11, 0xae, 0xd3, 0xb4, 0x54, 0xe4, 0x58, 0x8a, 0xbc,
+ 0x7f, 0x38, 0x00, 0xa5, 0x16, 0x74, 0x02, 0x03, 0x42, 0x47, 0xa2, 0x8f, 0x23, 0x21, 0x56, 0x05,
+ 0x69, 0xc4, 0x70, 0x98, 0xb3, 0x8c, 0x5c, 0x62, 0xdd, 0xea, 0xef, 0x98, 0x63, 0xaa, 0x62, 0x9c,
+ 0x7f, 0x97, 0xd0, 0x13, 0xc5, 0x28, 0x2b, 0x97, 0x5f, 0xb0, 0xa1, 0x9f, 0xc0, 0x9d, 0x52, 0x68,
+ 0x64, 0xc9, 0xab, 0xdf, 0x28, 0xef, 0xb6, 0x91, 0x17, 0x95, 0xb2, 0x7e, 0x04, 0xb7, 0x09, 0x1d,
+ 0x7d, 0x99, 0xe3, 0xbc, 0x22, 0xa9, 0x71, 0xa3, 0xa4, 0x3e, 0xa1, 0x5f, 0x48, 0x8e, 0x52, 0xce,
+ 0x17, 0x70, 0xcf, 0x5a, 0xa8, 0x48, 0x7b, 0x4b, 0x9a, 0x73, 0xa3, 0xb4, 0x1d, 0x63, 0x97, 0x28,
+ 0x0c, 0xa5, 0xc8, 0x4f, 0x61, 0x87, 0xd0, 0xd1, 0x55, 0x40, 0xf8, 0xbc, 0xbc, 0xb5, 0x57, 0xad,
+ 0xf3, 0x45, 0x40, 0x78, 0x55, 0x98, 0x5a, 0xe7, 0x14, 0xb3, 0x71, 0x65, 0x9d, 0xeb, 0xaf, 0x5a,
+ 0xe7, 0xb1, 0xe4, 0x28, 0xe5, 0x3c, 0x85, 0x3e, 0xa1, 0xf3, 0xf6, 0x34, 0x6f, 0x94, 0xb2, 0x49,
+ 0x68, 0xd5, 0x96, 0x43, 0xe8, 0x67, 0x38, 0xe4, 0x94, 0xd9, 0xb1, 0xb0, 0x71, 0xa3, 0x8c, 0x2d,
+ 0xcd, 0x60, 0x84, 0x78, 0x5f, 0x42, 0xe7, 0xc7, 0xf9, 0x18, 0xf3, 0xf8, 0xdc, 0xe4, 0xfc, 0x7f,
+ 0xbb, 0xcc, 0xfc, 0xab, 0x0e, 0xed, 0xc3, 0x31, 0xa3, 0x79, 0x5a, 0xa9, 0xda, 0x2a, 0x87, 0x17,
+ 0xaa, 0xb6, 0xa4, 0x91, 0x55, 0x5b, 0x51, 0x7f, 0x08, 0x1d, 0x75, 0xaf, 0xd1, 0x0c, 0xaa, 0x0a,
+ 0xa1, 0xc5, 0xa4, 0x2f, 0xee, 0x51, 0x8a, 0xed, 0x40, 0xdf, 0x11, 0x35, 0x57, 0xb5, 0x1a, 0x95,
+ 0x6e, 0xf2, 0xe1, 0xbc, 0xcc, 0xba, 0x23, 0xe8, 0x4e, 0x94, 0x6f, 0x34, 0x97, 0x0a, 0xc0, 0x77,
+ 0x0a, 0xe3, 0xca, 0x35, 0xec, 0xdb, 0x3e, 0x54, 0xae, 0xee, 0x4c, 0x6c, 0xb7, 0xbe, 0x0f, 0x20,
+ 0x9a, 0xe6, 0x51, 0x51, 0xa8, 0xec, 0x5f, 0x04, 0xe6, 0x84, 0x50, 0x8d, 0xb5, 0x1c, 0x0e, 0x4e,
+ 0xa1, 0xbf, 0x20, 0x73, 0x49, 0x99, 0xfa, 0x96, 0x5d, 0xa6, 0xca, 0x8b, 0x93, 0xcd, 0x6a, 0xd7,
+ 0xae, 0xbf, 0xd6, 0xd4, 0xa3, 0x41, 0xf9, 0x8a, 0xfb, 0x18, 0xba, 0x89, 0x6a, 0xbe, 0xcc, 0x06,
+ 0xd8, 0x37, 0x30, 0xbb, 0x31, 0xf3, 0x3b, 0x89, 0xdd, 0xa6, 0x7d, 0x08, 0x9d, 0x50, 0x7a, 0x60,
+ 0xe9, 0x46, 0x58, 0xce, 0xf1, 0xdb, 0xa1, 0xb5, 0xdb, 0x95, 0x46, 0xd1, 0xf9, 0x3a, 0x8d, 0xa2,
+ 0x7e, 0xf7, 0x5b, 0xf5, 0x4b, 0xe3, 0xe0, 0x9f, 0xeb, 0xd0, 0x78, 0x32, 0x3c, 0x42, 0x67, 0xb0,
+ 0x35, 0xff, 0x47, 0x10, 0xdd, 0xd7, 0x66, 0xad, 0xf8, 0x8b, 0x38, 0x78, 0xb0, 0x72, 0x5e, 0xb7,
+ 0xec, 0xb7, 0x90, 0x0f, 0x9b, 0x73, 0xff, 0x7f, 0x50, 0x71, 0xd4, 0x2c, 0xff, 0xc7, 0x36, 0xb8,
+ 0xbf, 0x6a, 0xda, 0x96, 0x39, 0x77, 0x47, 0x30, 0x32, 0x97, 0xbf, 0xb6, 0x18, 0x99, 0xab, 0xae,
+ 0x16, 0xb7, 0xd0, 0xf7, 0x61, 0x5d, 0xfd, 0x11, 0x42, 0xc5, 0xc5, 0xa5, 0xf2, 0xaf, 0x69, 0x70,
+ 0x67, 0x0e, 0x6b, 0x18, 0x9f, 0x43, 0xb7, 0xf2, 0x1b, 0x11, 0xbd, 0x51, 0xd1, 0x55, 0xfd, 0xa1,
+ 0x34, 0x78, 0x73, 0xf9, 0xa4, 0x91, 0x76, 0x08, 0x50, 0xfe, 0x34, 0x40, 0xae, 0xa6, 0x5e, 0xf8,
+ 0x31, 0x35, 0xb8, 0xb7, 0x64, 0xc6, 0x08, 0x39, 0x83, 0xad, 0xf9, 0x07, 0x7c, 0x34, 0xe7, 0xd5,
+ 0xf9, 0xe7, 0x73, 0xb3, 0x95, 0x2b, 0x5f, 0xfe, 0xa5, 0xd8, 0xf9, 0x67, 0x79, 0x23, 0x76, 0xc5,
+ 0x4f, 0x01, 0x23, 0x76, 0xe5, 0x7b, 0xfe, 0x2d, 0xf4, 0x39, 0xf4, 0xaa, 0xef, 0xdc, 0xa8, 0x70,
+ 0xd2, 0xd2, 0x87, 0xfe, 0xc1, 0x5b, 0x2b, 0x66, 0x8d, 0xc0, 0x0f, 0x60, 0x4d, 0x3d, 0x60, 0x17,
+ 0xe9, 0x68, 0xbf, 0x7b, 0x0f, 0xb6, 0xab, 0x48, 0xc3, 0xf5, 0x10, 0xd6, 0xd5, 0xed, 0xd2, 0x04,
+ 0x40, 0xe5, 0xb2, 0x39, 0xe8, 0xd8, 0x58, 0xef, 0xd6, 0xc3, 0x5a, 0xa1, 0x27, 0xab, 0xe8, 0xc9,
+ 0x96, 0xe9, 0xb1, 0x36, 0xe7, 0x7c, 0x5d, 0xa6, 0xeb, 0xa3, 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff,
+ 0x4c, 0xa9, 0xa8, 0x4d, 0xd0, 0x1f, 0x00, 0x00,
+}
diff --git a/vendor/github.com/containerd/containerd/api/grpc/types/api.proto b/vendor/github.com/containerd/containerd/api/grpc/types/api.proto
new file mode 100644
index 0000000..902f6c1
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/api/grpc/types/api.proto
@@ -0,0 +1,344 @@
+syntax = "proto3";
+
+package types;
+
+import "google/protobuf/timestamp.proto";
+
+service API {
+ rpc GetServerVersion(GetServerVersionRequest) returns (GetServerVersionResponse) {}
+ rpc CreateContainer(CreateContainerRequest) returns (CreateContainerResponse) {}
+ rpc UpdateContainer(UpdateContainerRequest) returns (UpdateContainerResponse) {}
+ rpc Signal(SignalRequest) returns (SignalResponse) {}
+ rpc UpdateProcess(UpdateProcessRequest) returns (UpdateProcessResponse) {}
+ rpc AddProcess(AddProcessRequest) returns (AddProcessResponse) {}
+ rpc CreateCheckpoint(CreateCheckpointRequest) returns (CreateCheckpointResponse) {}
+ rpc DeleteCheckpoint(DeleteCheckpointRequest) returns (DeleteCheckpointResponse) {}
+ rpc ListCheckpoint(ListCheckpointRequest) returns (ListCheckpointResponse) {}
+ rpc State(StateRequest) returns (StateResponse) {}
+ rpc Events(EventsRequest) returns (stream Event) {}
+ rpc Stats(StatsRequest) returns (StatsResponse) {}
+}
+
+message GetServerVersionRequest {
+}
+
+message GetServerVersionResponse {
+ uint32 major = 1;
+ uint32 minor = 2;
+ uint32 patch = 3;
+ string revision = 4;
+}
+
+message UpdateProcessRequest {
+ string id = 1;
+ string pid = 2;
+ bool closeStdin = 3; // Close stdin of the container
+ uint32 width = 4;
+ uint32 height = 5;
+}
+
+message UpdateProcessResponse {
+}
+
+message CreateContainerRequest {
+ string id = 1; // ID of container
+ string bundlePath = 2; // path to OCI bundle
+ string checkpoint = 3; // checkpoint name if you want to create immediate checkpoint (optional)
+ string stdin = 4; // path to the file where stdin will be read (optional)
+ string stdout = 5; // path to file where stdout will be written (optional)
+ string stderr = 6; // path to file where stderr will be written (optional)
+ repeated string labels = 7;
+ bool noPivotRoot = 8;
+ string runtime = 9;
+ repeated string runtimeArgs = 10;
+ string checkpointDir = 11; // Directory where checkpoints are stored
+}
+
+message CreateContainerResponse {
+ Container container = 1;
+}
+
+message SignalRequest {
+ string id = 1; // ID of container
+ string pid = 2; // PID of process inside container
+ uint32 signal = 3; // Signal which will be sent, you can find value in "man 7 signal"
+}
+
+message SignalResponse {
+}
+
+message AddProcessRequest {
+ string id = 1; // ID of container
+ bool terminal = 2; // Use tty for container stdio
+ User user = 3; // User under which process will be run
+ repeated string args = 4; // Arguments for process, first is binary path itself
+ repeated string env = 5; // List of environment variables for process
+ string cwd = 6; // Working directory of process
+ string pid = 7; // Process ID
+ string stdin = 8; // path to the file where stdin will be read (optional)
+ string stdout = 9; // path to file where stdout will be written (optional)
+ string stderr = 10; // path to file where stderr will be written (optional)
+ repeated string capabilities = 11;
+ string apparmorProfile = 12;
+ string selinuxLabel = 13;
+ bool noNewPrivileges = 14;
+ repeated Rlimit rlimits = 15;
+}
+
+message Rlimit {
+ string type = 1;
+ uint64 soft = 2;
+ uint64 hard = 3;
+}
+
+message User {
+ uint32 uid = 1; // UID of user
+ uint32 gid = 2; // GID of user
+ repeated uint32 additionalGids = 3; // Additional groups to which user will be added
+}
+
+message AddProcessResponse {
+ uint32 systemPid = 1;
+}
+
+message CreateCheckpointRequest {
+ string id = 1; // ID of container
+ Checkpoint checkpoint = 2; // Checkpoint configuration
+ string checkpointDir = 3; // Directory where checkpoints are stored
+}
+
+message CreateCheckpointResponse {
+}
+
+message DeleteCheckpointRequest {
+ string id = 1; // ID of container
+ string name = 2; // Name of checkpoint
+ string checkpointDir = 3; // Directory where checkpoints are stored
+}
+
+message DeleteCheckpointResponse {
+}
+
+message ListCheckpointRequest {
+ string id = 1; // ID of container
+ string checkpointDir = 2; // Directory where checkpoints are stored
+}
+
+message Checkpoint {
+ string name = 1; // Name of checkpoint
+ bool exit = 2; // checkpoint configuration: should container exit on checkpoint or not
+ bool tcp = 3; // allow open tcp connections
+ bool unixSockets = 4; // allow external unix sockets
+ bool shell = 5; // allow shell-jobs
+ repeated string emptyNS = 6;
+}
+
+message ListCheckpointResponse {
+ repeated Checkpoint checkpoints = 1; // List of checkpoints
+}
+
+message StateRequest {
+ string id = 1; // container id for a single container
+}
+
+message ContainerState {
+ string status = 1;
+}
+
+message Process {
+ string pid = 1;
+ bool terminal = 2; // Use tty for container stdio
+ User user = 3; // User under which process will be run
+ repeated string args = 4; // Arguments for process, first is binary path itself
+ repeated string env = 5; // List of environment variables for process
+ string cwd = 6; // Working directory of process
+ uint32 systemPid = 7;
+ string stdin = 8; // path to the file where stdin will be read (optional)
+ string stdout = 9; // path to file where stdout will be written (optional)
+ string stderr = 10; // path to file where stderr will be written (optional)
+ repeated string capabilities = 11;
+ string apparmorProfile = 12;
+ string selinuxLabel = 13;
+ bool noNewPrivileges = 14;
+ repeated Rlimit rlimits = 15;
+}
+
+message Container {
+ string id = 1; // ID of container
+ string bundlePath = 2; // Path to OCI bundle
+ repeated Process processes = 3; // List of processes which run in container
+ string status = 4; // Container status ("running", "paused", etc.)
+ repeated string labels = 5;
+ repeated uint32 pids = 6;
+ string runtime = 7; // runtime used to execute the container
+}
+
+// Machine is information about machine on which containerd is run
+message Machine {
+ uint32 cpus = 1; // number of cpus
+ uint64 memory = 2; // amount of memory
+}
+
+// StateResponse is information about containerd daemon
+message StateResponse {
+ repeated Container containers = 1;
+ Machine machine = 2;
+}
+
+message UpdateContainerRequest {
+ string id = 1; // ID of container
+ string pid = 2;
+ string status = 3; // Status to which containerd will try to change
+ UpdateResource resources =4;
+}
+
+message UpdateResource {
+ uint64 blkioWeight = 1;
+ uint64 cpuShares = 2;
+ uint64 cpuPeriod = 3;
+ uint64 cpuQuota = 4;
+ string cpusetCpus = 5;
+ string cpusetMems = 6;
+ uint64 memoryLimit = 7;
+ uint64 memorySwap = 8;
+ uint64 memoryReservation = 9;
+ uint64 kernelMemoryLimit = 10;
+ uint64 kernelTCPMemoryLimit = 11;
+ uint64 blkioLeafWeight = 12;
+ repeated WeightDevice blkioWeightDevice = 13;
+ repeated ThrottleDevice blkioThrottleReadBpsDevice = 14;
+ repeated ThrottleDevice blkioThrottleWriteBpsDevice = 15;
+ repeated ThrottleDevice blkioThrottleReadIopsDevice = 16;
+ repeated ThrottleDevice blkioThrottleWriteIopsDevice = 17;
+ uint64 pidsLimit = 18;
+}
+
+message BlockIODevice {
+ int64 major = 1;
+ int64 minor = 2;
+}
+
+message WeightDevice {
+ BlockIODevice blkIODevice = 1;
+ uint32 weight = 2;
+ uint32 leafWeight = 3;
+}
+
+message ThrottleDevice {
+ BlockIODevice blkIODevice = 1;
+ uint64 rate = 2;
+}
+
+message UpdateContainerResponse {
+}
+
+message EventsRequest {
+ // Tag 1 is deprecated (old uint64 timestamp)
+ google.protobuf.Timestamp timestamp = 2;
+ bool storedOnly = 3;
+ string id = 4;
+}
+
+message Event {
+ string type = 1;
+ string id = 2;
+ uint32 status = 3;
+ string pid = 4;
+ // Tag 5 is deprecated (old uint64 timestamp)
+ google.protobuf.Timestamp timestamp = 6;
+}
+
+message NetworkStats {
+ string name = 1; // name of network interface
+ uint64 rx_bytes = 2;
+ uint64 rx_Packets = 3;
+ uint64 Rx_errors = 4;
+ uint64 Rx_dropped = 5;
+ uint64 Tx_bytes = 6;
+ uint64 Tx_packets = 7;
+ uint64 Tx_errors = 8;
+ uint64 Tx_dropped = 9;
+}
+
+message CpuUsage {
+ uint64 total_usage = 1;
+ repeated uint64 percpu_usage = 2;
+ uint64 usage_in_kernelmode = 3;
+ uint64 usage_in_usermode = 4;
+}
+
+message ThrottlingData {
+ uint64 periods = 1;
+ uint64 throttled_periods = 2;
+ uint64 throttled_time = 3;
+}
+
+message CpuStats {
+ CpuUsage cpu_usage = 1;
+ ThrottlingData throttling_data = 2;
+ uint64 system_usage = 3;
+}
+
+message PidsStats {
+ uint64 current = 1;
+ uint64 limit = 2;
+}
+
+message MemoryData {
+ uint64 usage = 1;
+ uint64 max_usage = 2;
+ uint64 failcnt = 3;
+ uint64 limit = 4;
+}
+
+message MemoryStats {
+ uint64 cache = 1;
+ MemoryData usage = 2;
+ MemoryData swap_usage = 3;
+ MemoryData kernel_usage = 4;
+ map<string, uint64> stats = 5;
+}
+
+message BlkioStatsEntry {
+ uint64 major = 1;
+ uint64 minor = 2;
+ string op = 3;
+ uint64 value = 4;
+}
+
+message BlkioStats {
+ repeated BlkioStatsEntry io_service_bytes_recursive = 1; // number of bytes transferred to and from the block device
+ repeated BlkioStatsEntry io_serviced_recursive = 2;
+ repeated BlkioStatsEntry io_queued_recursive = 3;
+ repeated BlkioStatsEntry io_service_time_recursive = 4;
+ repeated BlkioStatsEntry io_wait_time_recursive = 5;
+ repeated BlkioStatsEntry io_merged_recursive = 6;
+ repeated BlkioStatsEntry io_time_recursive = 7;
+ repeated BlkioStatsEntry sectors_recursive = 8;
+}
+
+message HugetlbStats {
+ uint64 usage = 1;
+ uint64 max_usage = 2;
+ uint64 failcnt = 3;
+ uint64 limit = 4;
+}
+
+message CgroupStats {
+ CpuStats cpu_stats = 1;
+ MemoryStats memory_stats = 2;
+ BlkioStats blkio_stats = 3;
+ map<string, HugetlbStats> hugetlb_stats = 4; // the map is in the format "size of hugepage: stats of the hugepage"
+ PidsStats pids_stats = 5;
+}
+
+message StatsResponse {
+ repeated NetworkStats network_stats = 1;
+ CgroupStats cgroup_stats = 2;
+ // Tag 3 is deprecated (old uint64 timestamp)
+ google.protobuf.Timestamp timestamp = 4;
+};
+
+message StatsRequest {
+ string id = 1;
+}
diff --git a/vendor/github.com/containerd/containerd/api/http/pprof/pprof.go b/vendor/github.com/containerd/containerd/api/http/pprof/pprof.go
new file mode 100644
index 0000000..5a61e16
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/api/http/pprof/pprof.go
@@ -0,0 +1,19 @@
+package pprof
+
+import (
+ // expvar init routine adds the "/debug/vars" handler
+ _ "expvar"
+ "net/http"
+ // net/http/pprof installs the "/debug/pprof/{block,heap,goroutine,threadcreate}" handler
+ _ "net/http/pprof"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// Enable registers the "/debug/pprof" handler
+func Enable(address string) {
+ http.Handle("/", http.RedirectHandler("/debug/pprof", http.StatusMovedPermanently))
+
+ go http.ListenAndServe(address, nil)
+ logrus.Debug("pprof listening in address %s", address)
+}
diff --git a/vendor/github.com/containerd/containerd/archutils/epoll.go b/vendor/github.com/containerd/containerd/archutils/epoll.go
new file mode 100644
index 0000000..3f08d8f
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/archutils/epoll.go
@@ -0,0 +1,22 @@
+// +build linux,!arm64
+
+package archutils
+
+import (
+ "syscall"
+)
+
+// EpollCreate1 directly calls syscall.EpollCreate1
+func EpollCreate1(flag int) (int, error) {
+ return syscall.EpollCreate1(flag)
+}
+
+// EpollCtl directly calls syscall.EpollCtl
+func EpollCtl(epfd int, op int, fd int, event *syscall.EpollEvent) error {
+ return syscall.EpollCtl(epfd, op, fd, event)
+}
+
+// EpollWait directly calls syscall.EpollWait
+func EpollWait(epfd int, events []syscall.EpollEvent, msec int) (int, error) {
+ return syscall.EpollWait(epfd, events, msec)
+}
diff --git a/vendor/github.com/containerd/containerd/archutils/epoll_arm64.go b/vendor/github.com/containerd/containerd/archutils/epoll_arm64.go
new file mode 100644
index 0000000..3c6e63d
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/archutils/epoll_arm64.go
@@ -0,0 +1,73 @@
+// +build linux,arm64
+
+package archutils
+
+// #include <sys/epoll.h>
+/*
+int EpollCreate1(int flag) {
+ return epoll_create1(flag);
+}
+
+int EpollCtl(int efd, int op,int sfd, int events, int fd) {
+ struct epoll_event event;
+ event.events = events;
+ event.data.fd = fd;
+
+ return epoll_ctl(efd, op, sfd, &event);
+}
+
+struct event_t {
+ uint32_t events;
+ int fd;
+};
+
+struct epoll_event events[128];
+int run_epoll_wait(int fd, struct event_t *event) {
+ int n, i;
+ n = epoll_wait(fd, events, 128, -1);
+ for (i = 0; i < n; i++) {
+ event[i].events = events[i].events;
+ event[i].fd = events[i].data.fd;
+ }
+ return n;
+}
+*/
+import "C"
+
+import (
+ "fmt"
+ "syscall"
+ "unsafe"
+)
+
+// EpollCreate1 calls a C implementation
+func EpollCreate1(flag int) (int, error) {
+ fd := int(C.EpollCreate1(C.int(flag)))
+ if fd < 0 {
+ return fd, fmt.Errorf("failed to create epoll, errno is %d", fd)
+ }
+ return fd, nil
+}
+
+// EpollCtl calls a C implementation
+func EpollCtl(epfd int, op int, fd int, event *syscall.EpollEvent) error {
+ errno := C.EpollCtl(C.int(epfd), C.int(syscall.EPOLL_CTL_ADD), C.int(fd), C.int(event.Events), C.int(event.Fd))
+ if errno < 0 {
+ return fmt.Errorf("Failed to ctl epoll")
+ }
+ return nil
+}
+
+// EpollWait calls a C implementation
+func EpollWait(epfd int, events []syscall.EpollEvent, msec int) (int, error) {
+ var c_events [128]C.struct_event_t
+ n := int(C.run_epoll_wait(C.int(epfd), (*C.struct_event_t)(unsafe.Pointer(&c_events))))
+ if n < 0 {
+ return int(n), fmt.Errorf("Failed to wait epoll")
+ }
+ for i := 0; i < n; i++ {
+ events[i].Fd = int32(c_events[i].fd)
+ events[i].Events = uint32(c_events[i].events)
+ }
+ return int(n), nil
+}
diff --git a/vendor/github.com/containerd/containerd/containerd-shim/console.go b/vendor/github.com/containerd/containerd/containerd-shim/console.go
new file mode 100644
index 0000000..d2615ce
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/containerd-shim/console.go
@@ -0,0 +1,56 @@
+// +build !solaris
+
+package containerdShim
+
+import (
+ "fmt"
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+// NewConsole returns an initialized console that can be used within a container by copying bytes
+// from the master side to the slave that is attached as the tty for the container's init process.
+func newConsole(uid, gid int) (*os.File, string, error) {
+ master, err := os.OpenFile("/dev/ptmx", syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, "", err
+ }
+ console, err := ptsname(master)
+ if err != nil {
+ return nil, "", err
+ }
+ if err := unlockpt(master); err != nil {
+ return nil, "", err
+ }
+ if err := os.Chmod(console, 0600); err != nil {
+ return nil, "", err
+ }
+ if err := os.Chown(console, uid, gid); err != nil {
+ return nil, "", err
+ }
+ return master, console, nil
+}
+
+func ioctl(fd uintptr, flag, data uintptr) error {
+ if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, flag, data); err != 0 {
+ return err
+ }
+ return nil
+}
+
+// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.
+// unlockpt should be called before opening the slave side of a pty.
+func unlockpt(f *os.File) error {
+ var u int32
+ return ioctl(f.Fd(), syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))
+}
+
+// ptsname retrieves the name of the first available pts for the given master.
+func ptsname(f *os.File) (string, error) {
+ var n int32
+ if err := ioctl(f.Fd(), syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n))); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("/dev/pts/%d", n), nil
+}
diff --git a/vendor/github.com/containerd/containerd/containerd-shim/console_solaris.go b/vendor/github.com/containerd/containerd/containerd-shim/console_solaris.go
new file mode 100644
index 0000000..746e60d
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/containerd-shim/console_solaris.go
@@ -0,0 +1,14 @@
+// +build solaris
+
+package containerdShim
+
+import (
+ "errors"
+ "os"
+)
+
+// NewConsole returns an initalized console that can be used within a container by copying bytes
+// from the master side to the slave that is attached as the tty for the container's init process.
+func newConsole(uid, gid int) (*os.File, string, error) {
+ return nil, "", errors.New("newConsole not implemented on Solaris")
+}
diff --git a/vendor/github.com/containerd/containerd/containerd-shim/main.go b/vendor/github.com/containerd/containerd/containerd-shim/main.go
new file mode 100644
index 0000000..6d2388c
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/containerd-shim/main.go
@@ -0,0 +1,169 @@
+package containerdShim
+
+import (
+ "flag"
+ "fmt"
+ "os"
+ "os/signal"
+ "path/filepath"
+ "runtime"
+ "syscall"
+
+ "github.com/containerd/containerd/osutils"
+ "github.com/containerd/console"
+)
+
+func writeMessage(f *os.File, level string, err error) {
+ fmt.Fprintf(f, `{"level": "%s","msg": "%s"}`, level, err)
+}
+
+type controlMessage struct {
+ Type int
+ Width int
+ Height int
+}
+
+// containerd-shim is a small shim that sits in front of a runtime implementation
+// that allows it to be repartented to init and handle reattach from the caller.
+//
+// the cwd of the shim should be the path to the state directory where the shim
+// can locate fifos and other information.
+// Arg0: id of the container
+// Arg1: bundle path
+// Arg2: runtime binary
+func Main() {
+ flag.Parse()
+ cwd, err := os.Getwd()
+ if err != nil {
+ panic(err)
+ }
+ f, err := os.OpenFile(filepath.Join(cwd, "shim-log.json"), os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_SYNC, 0666)
+ if err != nil {
+ panic(err)
+ }
+ if err := start(f); err != nil {
+ // this means that the runtime failed starting the container and will have the
+ // proper error messages in the runtime log so we should to treat this as a
+ // shim failure because the sim executed properly
+ if err == errRuntime {
+ f.Close()
+ return
+ }
+ // log the error instead of writing to stderr because the shim will have
+ // /dev/null as it's stdio because it is supposed to be reparented to system
+ // init and will not have anyone to read from it
+ writeMessage(f, "error", err)
+ f.Close()
+ os.Exit(1)
+ }
+}
+
+func start(log *os.File) error {
+ // start handling signals as soon as possible so that things are properly reaped
+ // or if runtime exits before we hit the handler
+ signals := make(chan os.Signal, 2048)
+ signal.Notify(signals)
+ // set the shim as the subreaper for all orphaned processes created by the container
+ if err := osutils.SetSubreaper(1); err != nil {
+ return err
+ }
+ // open the exit pipe
+ f, err := os.OpenFile("exit", syscall.O_WRONLY, 0)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ control, err := os.OpenFile("control", syscall.O_RDWR, 0)
+ if err != nil {
+ return err
+ }
+ defer control.Close()
+ p, err := newProcess(flag.Arg(0), flag.Arg(1), flag.Arg(2))
+ if err != nil {
+ return err
+ }
+ if err := p.openIO(); err != nil {
+ return err
+ }
+ defer func() {
+ if err := p.Close(); err != nil {
+ writeMessage(log, "warn", err)
+ }
+ }()
+ if err := p.create(); err != nil {
+ p.delete()
+ return err
+ }
+ if err := <-p.consoleErrCh; err != nil {
+ p.delete()
+ return err
+ }
+ msgC := make(chan controlMessage, 32)
+ go func() {
+ for {
+ var m controlMessage
+ if _, err := fmt.Fscanf(control, "%d %d %d\n", &m.Type, &m.Width, &m.Height); err != nil {
+ continue
+ }
+ msgC <- m
+ }
+ }()
+ if runtime.GOOS == "solaris" {
+ return nil
+ }
+ var exitShim bool
+ for {
+ select {
+ case s := <-signals:
+ switch s {
+ case syscall.SIGCHLD:
+ exits, _ := osutils.Reap(false)
+ for _, e := range exits {
+ // check to see if runtime is one of the processes that has exited
+ if e.Pid == p.pid() {
+ exitShim = true
+ writeInt("exitStatus", e.Status)
+ }
+ }
+ }
+ // runtime has exited so the shim can also exit
+ if exitShim {
+ // kill all processes in the container incase it was not running in
+ // its own PID namespace
+ p.killAll()
+ // wait for all the processes and IO to finish
+ p.Wait()
+ // delete the container from the runtime
+ p.delete()
+ // the close of the exit fifo will happen when the shim exits
+ return nil
+ }
+ case msg := <-msgC:
+ switch msg.Type {
+ case 0:
+ // close stdin
+ if p.stdinCloser != nil {
+ p.stdinCloser.Close()
+ }
+ case 1:
+ if p.console == nil {
+ continue
+ }
+ p.console.Resize(console.WinSize{
+ Width: uint16(msg.Width),
+ Height: uint16(msg.Height),
+ })
+ }
+ }
+ }
+}
+
+func writeInt(path string, i int) error {
+ f, err := os.Create(path)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ _, err = fmt.Fprintf(f, "%d", i)
+ return err
+}
diff --git a/vendor/github.com/containerd/containerd/containerd-shim/process.go b/vendor/github.com/containerd/containerd/containerd-shim/process.go
new file mode 100644
index 0000000..2cb362d
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/containerd-shim/process.go
@@ -0,0 +1,308 @@
+package containerdShim
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/containerd/containerd/osutils"
+ "github.com/containerd/containerd/specs"
+ "github.com/containerd/console"
+ runc "github.com/containerd/go-runc"
+)
+
+var errRuntime = errors.New("shim: runtime execution error")
+
+type checkpoint struct {
+ // Timestamp is the time that checkpoint happened
+ Created time.Time `json:"created"`
+ // Name is the name of the checkpoint
+ Name string `json:"name"`
+ // TCP checkpoints open tcp connections
+ TCP bool `json:"tcp"`
+ // UnixSockets persists unix sockets in the checkpoint
+ UnixSockets bool `json:"unixSockets"`
+ // Shell persists tty sessions in the checkpoint
+ Shell bool `json:"shell"`
+ // Exit exits the container after the checkpoint is finished
+ Exit bool `json:"exit"`
+ // EmptyNS tells CRIU not to restore a particular namespace
+ EmptyNS []string `json:"emptyNS,omitempty"`
+}
+
+type processState struct {
+ specs.ProcessSpec
+ Exec bool `json:"exec"`
+ Stdin string `json:"containerdStdin"`
+ Stdout string `json:"containerdStdout"`
+ Stderr string `json:"containerdStderr"`
+ RuntimeArgs []string `json:"runtimeArgs"`
+ NoPivotRoot bool `json:"noPivotRoot"`
+ CheckpointPath string `json:"checkpoint"`
+ RootUID int `json:"rootUID"`
+ RootGID int `json:"rootGID"`
+}
+
+type process struct {
+ sync.WaitGroup
+ id string
+ bundle string
+ stdio *stdio
+ containerPid int
+ checkpoint *checkpoint
+ checkpointPath string
+ shimIO *IO
+ stdinCloser io.Closer
+ state *processState
+ runtime string
+ ioCleanupFn func()
+
+ socket *runc.Socket
+ console console.Console
+ consoleErrCh chan error
+}
+
+func newProcess(id, bundle, runtimeName string) (*process, error) {
+ p := &process{
+ id: id,
+ bundle: bundle,
+ runtime: runtimeName,
+ consoleErrCh: make(chan error, 1),
+ }
+ s, err := loadProcess()
+ if err != nil {
+ return nil, err
+ }
+ p.state = s
+ if s.CheckpointPath != "" {
+ cpt, err := loadCheckpoint(s.CheckpointPath)
+ if err != nil {
+ return nil, err
+ }
+ p.checkpoint = cpt
+ p.checkpointPath = s.CheckpointPath
+ }
+ return p, nil
+}
+
+func loadProcess() (*processState, error) {
+ f, err := os.Open("process.json")
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ var s processState
+ if err := json.NewDecoder(f).Decode(&s); err != nil {
+ return nil, err
+ }
+ return &s, nil
+}
+
+func loadCheckpoint(checkpointPath string) (*checkpoint, error) {
+ f, err := os.Open(filepath.Join(checkpointPath, "config.json"))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ var cpt checkpoint
+ if err := json.NewDecoder(f).Decode(&cpt); err != nil {
+ return nil, err
+ }
+ return &cpt, nil
+}
+
+func (p *process) create() error {
+ cwd, err := os.Getwd()
+ if err != nil {
+ return err
+ }
+ logPath := filepath.Join(cwd, "log.json")
+ args := append([]string{
+ "--log", logPath,
+ "--log-format", "json",
+ }, p.state.RuntimeArgs...)
+ if p.state.Exec {
+ args = append(args, "exec",
+ "-d",
+ "--process", filepath.Join(cwd, "process.json"),
+ )
+ if p.socket != nil {
+ args = append(args, "--console-socket", p.socket.Path())
+ }
+
+ } else if p.checkpoint != nil {
+ args = append(args, "restore",
+ "-d",
+ "--image-path", p.checkpointPath,
+ "--work-path", filepath.Join(p.checkpointPath, "criu.work", "restore-"+time.Now().Format(time.RFC3339Nano)),
+ )
+ add := func(flags ...string) {
+ args = append(args, flags...)
+ }
+ if p.checkpoint.Shell {
+ add("--shell-job")
+ }
+ if p.checkpoint.TCP {
+ add("--tcp-established")
+ }
+ if p.checkpoint.UnixSockets {
+ add("--ext-unix-sk")
+ }
+ if p.state.NoPivotRoot {
+ add("--no-pivot")
+ }
+ for _, ns := range p.checkpoint.EmptyNS {
+ add("--empty-ns", ns)
+ }
+
+ } else {
+ args = append(args, "create",
+ "--bundle", p.bundle,
+ )
+ if p.socket != nil {
+ args = append(args, "--console-socket", p.socket.Path())
+ }
+ if p.state.NoPivotRoot {
+ args = append(args, "--no-pivot")
+ }
+ }
+ args = append(args,
+ "--pid-file", filepath.Join(cwd, "pid"),
+ p.id,
+ )
+ cmd := exec.Command(p.runtime, args...)
+ cmd.Dir = p.bundle
+ cmd.Stdin = p.stdio.stdin
+ cmd.Stdout = p.stdio.stdout
+ cmd.Stderr = p.stdio.stderr
+ // Call out to SetPDeathSig to set SysProcAttr as elements are platform specific
+ cmd.SysProcAttr = osutils.SetPDeathSig()
+
+ if err := cmd.Start(); err != nil {
+ if exErr, ok := err.(*exec.Error); ok {
+ if exErr.Err == exec.ErrNotFound || exErr.Err == os.ErrNotExist {
+ return fmt.Errorf("%s not installed on system", p.runtime)
+ }
+ }
+ return err
+ }
+ if runtime.GOOS != "solaris" {
+ // Since current logic dictates that we need a pid at the end of p.create
+ // we need to call runtime start as well on Solaris hence we need the
+ // pipes to stay open.
+ p.stdio.stdout.Close()
+ p.stdio.stderr.Close()
+ }
+ if err := cmd.Wait(); err != nil {
+ if _, ok := err.(*exec.ExitError); ok {
+ return errRuntime
+ }
+ return err
+ }
+ data, err := ioutil.ReadFile("pid")
+ if err != nil {
+ return err
+ }
+ pid, err := strconv.Atoi(string(data))
+ if err != nil {
+ return err
+ }
+ p.containerPid = pid
+ return nil
+}
+
+func (p *process) pid() int {
+ return p.containerPid
+}
+
+func (p *process) delete() error {
+ if !p.state.Exec {
+ cmd := exec.Command(p.runtime, append(p.state.RuntimeArgs, "delete", p.id)...)
+ cmd.SysProcAttr = osutils.SetPDeathSig()
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s: %v", out, err)
+ }
+ }
+ return nil
+}
+
+// IO holds all 3 standard io Reader/Writer (stdin,stdout,stderr)
+type IO struct {
+ Stdin io.WriteCloser
+ Stdout io.ReadCloser
+ Stderr io.ReadCloser
+}
+
+func (p *process) initializeIO(rootuid, rootgid int) (i *IO, err error) {
+ var fds []uintptr
+ i = &IO{}
+ // cleanup in case of an error
+ defer func() {
+ if err != nil {
+ for _, fd := range fds {
+ syscall.Close(int(fd))
+ }
+ }
+ }()
+ // STDIN
+ r, w, err := os.Pipe()
+ if err != nil {
+ return nil, err
+ }
+ fds = append(fds, r.Fd(), w.Fd())
+ p.stdio.stdin, i.Stdin = r, w
+ // STDOUT
+ if r, w, err = os.Pipe(); err != nil {
+ return nil, err
+ }
+ fds = append(fds, r.Fd(), w.Fd())
+ p.stdio.stdout, i.Stdout = w, r
+ // STDERR
+ if r, w, err = os.Pipe(); err != nil {
+ return nil, err
+ }
+ fds = append(fds, r.Fd(), w.Fd())
+ p.stdio.stderr, i.Stderr = w, r
+ // change ownership of the pipes in case we are in a user namespace
+ for _, fd := range fds {
+ if err := syscall.Fchown(int(fd), rootuid, rootgid); err != nil {
+ return nil, err
+ }
+ }
+ return i, nil
+}
+func (p *process) Close() error {
+ err := p.stdio.Close()
+ if p.socket != nil {
+ p.socket.Close()
+ }
+ return err
+}
+
+type stdio struct {
+ stdin *os.File
+ stdout *os.File
+ stderr *os.File
+}
+
+func (s *stdio) Close() error {
+ err := s.stdin.Close()
+ if oerr := s.stdout.Close(); err == nil {
+ err = oerr
+ }
+ if oerr := s.stderr.Close(); err == nil {
+ err = oerr
+ }
+ return err
+}
diff --git a/vendor/github.com/containerd/containerd/containerd-shim/process_linux.go b/vendor/github.com/containerd/containerd/containerd-shim/process_linux.go
new file mode 100644
index 0000000..69dc7fa
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/containerd-shim/process_linux.go
@@ -0,0 +1,190 @@
+// +build !solaris
+
+package containerdShim
+
+import (
+ "fmt"
+ "io"
+ "os/exec"
+ "syscall"
+ "time"
+
+ "github.com/containerd/containerd/osutils"
+ "github.com/containerd/console"
+ runc "github.com/containerd/go-runc"
+ "github.com/tonistiigi/fifo"
+ "golang.org/x/net/context"
+)
+
+// openIO opens the pre-created fifo's for use with the container
+// in RDWR so that they remain open if the other side stops listening
+func (p *process) openIO() error {
+ p.stdio = &stdio{}
+ var (
+ uid = p.state.RootUID
+ gid = p.state.RootGID
+ )
+
+ ctx, _ := context.WithTimeout(context.Background(), 15*time.Second)
+
+ stdinCloser, err := fifo.OpenFifo(ctx, p.state.Stdin, syscall.O_WRONLY|syscall.O_NONBLOCK, 0)
+ if err != nil {
+ return err
+ }
+ p.stdinCloser = stdinCloser
+
+ if p.state.Terminal {
+ socket, err := runc.NewTempConsoleSocket()
+ if err != nil {
+ return err
+ }
+ p.socket = socket
+ consoleCh := p.waitConsole(socket)
+
+ stdin, err := fifo.OpenFifo(ctx, p.state.Stdin, syscall.O_RDONLY, 0)
+ if err != nil {
+ return err
+ }
+ stdoutw, err := fifo.OpenFifo(ctx, p.state.Stdout, syscall.O_WRONLY, 0)
+ if err != nil {
+ return err
+ }
+ stdoutr, err := fifo.OpenFifo(ctx, p.state.Stdout, syscall.O_RDONLY, 0)
+ if err != nil {
+ return err
+ }
+ // open the fifos but wait until we receive the console before we start
+ // copying data back and forth between the two
+ go p.setConsole(consoleCh, stdin, stdoutw)
+
+ p.Add(1)
+ p.ioCleanupFn = func() {
+ stdoutr.Close()
+ stdoutw.Close()
+ }
+ return nil
+ }
+ close(p.consoleErrCh)
+ i, err := p.initializeIO(uid, gid)
+ if err != nil {
+ return err
+ }
+ p.shimIO = i
+ // non-tty
+ ioClosers := []io.Closer{}
+ for _, pair := range []struct {
+ name string
+ dest func(wc io.WriteCloser, rc io.Closer)
+ }{
+ {
+ p.state.Stdout,
+ func(wc io.WriteCloser, rc io.Closer) {
+ p.Add(1)
+ go func() {
+ io.Copy(wc, i.Stdout)
+ p.Done()
+ }()
+ },
+ },
+ {
+ p.state.Stderr,
+ func(wc io.WriteCloser, rc io.Closer) {
+ p.Add(1)
+ go func() {
+ io.Copy(wc, i.Stderr)
+ p.Done()
+ }()
+ },
+ },
+ } {
+ fw, err := fifo.OpenFifo(ctx, pair.name, syscall.O_WRONLY, 0)
+ if err != nil {
+ return fmt.Errorf("containerd-shim: opening %s failed: %s", pair.name, err)
+ }
+ fr, err := fifo.OpenFifo(ctx, pair.name, syscall.O_RDONLY, 0)
+ if err != nil {
+ return fmt.Errorf("containerd-shim: opening %s failed: %s", pair.name, err)
+ }
+ pair.dest(fw, fr)
+ ioClosers = append(ioClosers, fw, fr)
+ }
+
+ f, err := fifo.OpenFifo(ctx, p.state.Stdin, syscall.O_RDONLY, 0)
+ if err != nil {
+ return fmt.Errorf("containerd-shim: opening %s failed: %s", p.state.Stdin, err)
+ }
+ p.ioCleanupFn = func() {
+ for _, c := range ioClosers {
+ c.Close()
+ }
+ }
+ go func() {
+ io.Copy(i.Stdin, f)
+ i.Stdin.Close()
+ f.Close()
+ }()
+
+ return nil
+}
+
+func (p *process) Wait() {
+ p.WaitGroup.Wait()
+ if p.ioCleanupFn != nil {
+ p.ioCleanupFn()
+ }
+ if p.console != nil {
+ p.console.Close()
+ }
+}
+
+func (p *process) killAll() error {
+ if !p.state.Exec {
+ cmd := exec.Command(p.runtime, append(p.state.RuntimeArgs, "kill", "--all", p.id, "SIGKILL")...)
+ cmd.SysProcAttr = osutils.SetPDeathSig()
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s: %v", out, err)
+ }
+ }
+ return nil
+}
+
+func (p *process) setConsole(c <-chan *consoleR, stdin io.Reader, stdout io.Writer) {
+ r := <-c
+ if r.err != nil {
+ p.consoleErrCh <- r.err
+ return
+ }
+ close(p.consoleErrCh)
+ p.console = r.c
+ // copy from the console into the provided fifos
+ go io.Copy(r.c, stdin)
+ go func() {
+ io.Copy(stdout, r.c)
+ p.Done()
+ }()
+}
+
+type consoleR struct {
+ c console.Console
+ err error
+}
+
+func (p *process) waitConsole(socket *runc.Socket) <-chan *consoleR {
+ c := make(chan *consoleR, 1)
+ go func() {
+ master, err := socket.ReceiveMaster()
+ socket.Close()
+ if err != nil {
+ c <- &consoleR{
+ err: err,
+ }
+ return
+ }
+ c <- &consoleR{
+ c: master,
+ }
+ }()
+ return c
+
+}
diff --git a/vendor/github.com/containerd/containerd/containerd-shim/process_solaris.go b/vendor/github.com/containerd/containerd/containerd-shim/process_solaris.go
new file mode 100644
index 0000000..15465c3
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/containerd-shim/process_solaris.go
@@ -0,0 +1,74 @@
+// +build solaris
+
+package containerdShim
+
+import (
+ "io"
+ "os"
+ "syscall"
+)
+
+// TODO: Update to using fifo's package in openIO. Need to
+// 1. Merge and vendor changes in the package to use sys/unix.
+// 2. Figure out why context.Background is timing out.
+// openIO opens the pre-created fifo's for use with the container
+// in RDWR so that they remain open if the other side stops listening
+func (p *process) openIO() error {
+ p.stdio = &stdio{}
+ var (
+ uid = p.state.RootUID
+ )
+ i, err := p.initializeIO(uid)
+ if err != nil {
+ return err
+ }
+ p.shimIO = i
+ // Both tty and non-tty mode are handled by the runtime using
+ // the following pipes
+ for _, pair := range []struct {
+ name string
+ dest func(f *os.File)
+ }{
+ {
+ p.state.Stdout,
+ func(f *os.File) {
+ p.Add(1)
+ go func() {
+ io.Copy(f, i.Stdout)
+ p.Done()
+ }()
+ },
+ },
+ {
+ p.state.Stderr,
+ func(f *os.File) {
+ p.Add(1)
+ go func() {
+ io.Copy(f, i.Stderr)
+ p.Done()
+ }()
+ },
+ },
+ } {
+ f, err := os.OpenFile(pair.name, syscall.O_RDWR, 0)
+ if err != nil {
+ return err
+ }
+ pair.dest(f)
+ }
+
+ f, err := os.OpenFile(p.state.Stdin, syscall.O_RDONLY, 0)
+ if err != nil {
+ return err
+ }
+ go func() {
+ io.Copy(i.Stdin, f)
+ i.Stdin.Close()
+ }()
+
+ return nil
+}
+
+func (p *process) killAll() error {
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/containerd/main.go b/vendor/github.com/containerd/containerd/containerd/main.go
new file mode 100644
index 0000000..913cbf6
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/containerd/main.go
@@ -0,0 +1,280 @@
+package containerd
+
+import (
+ "fmt"
+ "log"
+ "net"
+ "os"
+ "os/signal"
+ "runtime"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/health"
+ "google.golang.org/grpc/health/grpc_health_v1"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/urfave/cli"
+ "github.com/cyberdelia/go-metrics-graphite"
+ "github.com/containerd/containerd"
+ grpcserver "github.com/containerd/containerd/api/grpc/server"
+ "github.com/containerd/containerd/api/grpc/types"
+ "github.com/containerd/containerd/api/http/pprof"
+ "github.com/containerd/containerd/supervisor"
+ "github.com/docker/docker/pkg/listeners"
+ "github.com/rcrowley/go-metrics"
+)
+
+const (
+ usage = `High performance container daemon`
+ minRlimit = 1024
+ defaultStateDir = "/run/containerd"
+ defaultGRPCEndpoint = "unix:///run/containerd/containerd.sock"
+)
+
+var daemonFlags = []cli.Flag{
+ cli.BoolFlag{
+ Name: "debug",
+ Usage: "enable debug output in the logs",
+ },
+ cli.StringFlag{
+ Name: "log-level",
+ Usage: "Set the logging level [debug, info, warn, error, fatal, panic]",
+ },
+ cli.StringFlag{
+ Name: "state-dir",
+ Value: defaultStateDir,
+ Usage: "runtime state directory",
+ },
+ cli.DurationFlag{
+ Name: "metrics-interval",
+ Value: 5 * time.Minute,
+ Usage: "interval for flushing metrics to the store",
+ },
+ cli.StringFlag{
+ Name: "listen,l",
+ Value: defaultGRPCEndpoint,
+ Usage: "proto://address on which the GRPC API will listen",
+ },
+ cli.StringFlag{
+ Name: "runtime,r",
+ Value: "runc",
+ Usage: "name or path of the OCI compliant runtime to use when executing containers",
+ },
+ cli.StringSliceFlag{
+ Name: "runtime-args",
+ Value: &cli.StringSlice{},
+ Usage: "specify additional runtime args",
+ },
+ cli.StringFlag{
+ Name: "shim",
+ Value: "containerd-shim",
+ Usage: "Name or path of shim",
+ },
+ cli.StringFlag{
+ Name: "pprof-address",
+ Usage: "http address to listen for pprof events",
+ },
+ cli.DurationFlag{
+ Name: "start-timeout",
+ Value: 30 * time.Second,
+ Usage: "timeout duration for waiting on a container to start before it is killed",
+ },
+ cli.IntFlag{
+ Name: "retain-count",
+ Value: 500,
+ Usage: "number of past events to keep in the event log",
+ },
+ cli.StringFlag{
+ Name: "graphite-address",
+ Usage: "Address of graphite server",
+ },
+}
+
+// DumpStacks dumps the runtime stack.
+func dumpStacks() {
+ var (
+ buf []byte
+ stackSize int
+ )
+ bufferLen := 16384
+ for stackSize == len(buf) {
+ buf = make([]byte, bufferLen)
+ stackSize = runtime.Stack(buf, true)
+ bufferLen *= 2
+ }
+ buf = buf[:stackSize]
+ logrus.Infof("=== BEGIN goroutine stack dump ===\n%s\n=== END goroutine stack dump ===", buf)
+}
+
+func setupDumpStacksTrap() {
+ c := make(chan os.Signal, 1)
+ signal.Notify(c, syscall.SIGUSR1)
+ go func() {
+ for range c {
+ dumpStacks()
+ }
+ }()
+}
+
+func Main() {
+ logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: time.RFC3339Nano})
+ app := cli.NewApp()
+ app.Name = "containerd"
+ if containerd.GitCommit != "" {
+ app.Version = fmt.Sprintf("%s commit: %s", containerd.Version, containerd.GitCommit)
+ } else {
+ app.Version = containerd.Version
+ }
+ app.Usage = usage
+ app.Flags = daemonFlags
+ app.Before = func(context *cli.Context) error {
+ setupDumpStacksTrap()
+ if context.GlobalBool("debug") {
+ logrus.SetLevel(logrus.DebugLevel)
+ if context.GlobalDuration("metrics-interval") > 0 {
+ if err := debugMetrics(context.GlobalDuration("metrics-interval"), context.GlobalString("graphite-address")); err != nil {
+ return err
+ }
+ }
+ }
+ if logLevel := context.GlobalString("log-level"); logLevel != "" {
+ lvl, err := logrus.ParseLevel(logLevel)
+ if err != nil {
+ lvl = logrus.InfoLevel
+ fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n, and being defaulted to info", logLevel)
+ }
+ logrus.SetLevel(lvl)
+ }
+ if p := context.GlobalString("pprof-address"); len(p) > 0 {
+ pprof.Enable(p)
+ }
+ if err := checkLimits(); err != nil {
+ return err
+ }
+ return nil
+ }
+
+ app.Action = func(context *cli.Context) {
+ if err := daemon(context); err != nil {
+ logrus.Fatal(err)
+ }
+ }
+ if err := app.Run(os.Args); err != nil {
+ logrus.Fatal(err)
+ }
+}
+
+func daemon(context *cli.Context) error {
+ stateDir := context.String("state-dir")
+ if err := os.MkdirAll(stateDir, 0755); err != nil {
+ return err
+ }
+ s := make(chan os.Signal, 2048)
+ signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)
+ // Split the listen string of the form proto://addr
+ listenSpec := context.String("listen")
+ listenParts := strings.SplitN(listenSpec, "://", 2)
+ if len(listenParts) != 2 {
+ return fmt.Errorf("bad listen address format %s, expected proto://address", listenSpec)
+ }
+ // Register server early to allow healthcheck to be done
+ server, err := startServer(listenParts[0], listenParts[1])
+ if err != nil {
+ return err
+ }
+ sv, err := supervisor.New(
+ stateDir,
+ context.String("runtime"),
+ context.String("shim"),
+ context.StringSlice("runtime-args"),
+ context.Duration("start-timeout"),
+ context.Int("retain-count"))
+ if err != nil {
+ return err
+ }
+ types.RegisterAPIServer(server, grpcserver.NewServer(sv))
+ wg := &sync.WaitGroup{}
+ for i := 0; i < 10; i++ {
+ wg.Add(1)
+ w := supervisor.NewWorker(sv, wg)
+ go w.Start()
+ }
+ if err := sv.Start(); err != nil {
+ return err
+ }
+ for ss := range s {
+ switch ss {
+ case syscall.SIGPIPE:
+ continue
+ default:
+ logrus.Infof("stopping containerd after receiving %s", ss)
+ server.Stop()
+ os.Exit(0)
+ }
+ }
+ return nil
+}
+
+func startServer(protocol, address string) (*grpc.Server, error) {
+ // TODO: We should use TLS.
+ // TODO: Add an option for the SocketGroup.
+ sockets, err := listeners.Init(protocol, address, "", nil)
+ if err != nil {
+ return nil, err
+ }
+ if len(sockets) != 1 {
+ return nil, fmt.Errorf("incorrect number of listeners")
+ }
+ l := sockets[0]
+ s := grpc.NewServer()
+ healthServer := health.NewServer()
+ grpc_health_v1.RegisterHealthServer(s, healthServer)
+
+ go func() {
+ logrus.Debugf("containerd: grpc api on %s", address)
+ if err := s.Serve(l); err != nil {
+ logrus.WithField("error", err).Fatal("containerd: serve grpc")
+ }
+ }()
+ return s, nil
+}
+
+func checkLimits() error {
+ var l syscall.Rlimit
+ if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l); err != nil {
+ return err
+ }
+ if l.Cur <= minRlimit {
+ logrus.WithFields(logrus.Fields{
+ "current": l.Cur,
+ "max": l.Max,
+ }).Warn("containerd: low RLIMIT_NOFILE changing to max")
+ l.Cur = l.Max
+ return syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l)
+ }
+ return nil
+}
+
+func debugMetrics(interval time.Duration, graphiteAddr string) error {
+ for name, m := range supervisor.Metrics() {
+ if err := metrics.DefaultRegistry.Register(name, m); err != nil {
+ return err
+ }
+ }
+ processMetrics()
+ if graphiteAddr != "" {
+ addr, err := net.ResolveTCPAddr("tcp", graphiteAddr)
+ if err != nil {
+ return err
+ }
+ go graphite.Graphite(metrics.DefaultRegistry, 10e9, "metrics", addr)
+ } else {
+ l := log.New(os.Stdout, "[containerd] ", log.LstdFlags)
+ go metrics.Log(metrics.DefaultRegistry, interval, l)
+ }
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/containerd/main_linux.go b/vendor/github.com/containerd/containerd/containerd/main_linux.go
new file mode 100644
index 0000000..6b48e53
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/containerd/main_linux.go
@@ -0,0 +1,45 @@
+package containerd
+
+import (
+ "os"
+ "runtime"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/cloudfoundry/gosigar"
+ "github.com/containerd/containerd/osutils"
+ "github.com/rcrowley/go-metrics"
+)
+
+func processMetrics() {
+ var (
+ g = metrics.NewGauge()
+ fg = metrics.NewGauge()
+ memg = metrics.NewGauge()
+ )
+ metrics.DefaultRegistry.Register("goroutines", g)
+ metrics.DefaultRegistry.Register("fds", fg)
+ metrics.DefaultRegistry.Register("memory-used", memg)
+ collect := func() {
+ // update number of goroutines
+ g.Update(int64(runtime.NumGoroutine()))
+ // collect the number of open fds
+ fds, err := osutils.GetOpenFds(os.Getpid())
+ if err != nil {
+ logrus.WithField("error", err).Error("containerd: get open fd count")
+ }
+ fg.Update(int64(fds))
+ // get the memory used
+ m := sigar.ProcMem{}
+ if err := m.Get(os.Getpid()); err != nil {
+ logrus.WithField("error", err).Error("containerd: get pid memory information")
+ }
+ memg.Update(int64(m.Size))
+ }
+ go func() {
+ collect()
+ for range time.Tick(30 * time.Second) {
+ collect()
+ }
+ }()
+}
diff --git a/vendor/github.com/containerd/containerd/containerd/main_solaris.go b/vendor/github.com/containerd/containerd/containerd/main_solaris.go
new file mode 100644
index 0000000..fdcfc34
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/containerd/main_solaris.go
@@ -0,0 +1,4 @@
+package containerd
+
+func processMetrics() {
+}
diff --git a/vendor/github.com/containerd/containerd/ctr/checkpoint_linux.go b/vendor/github.com/containerd/containerd/ctr/checkpoint_linux.go
new file mode 100644
index 0000000..3f1922e
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/ctr/checkpoint_linux.go
@@ -0,0 +1,165 @@
+package ctr
+
+import (
+ "fmt"
+ "os"
+ "text/tabwriter"
+
+ "github.com/urfave/cli"
+ "github.com/containerd/containerd/api/grpc/types"
+ netcontext "golang.org/x/net/context"
+)
+
+var checkpointSubCmds = []cli.Command{
+ listCheckpointCommand,
+ createCheckpointCommand,
+ deleteCheckpointCommand,
+}
+
+var checkpointCommand = cli.Command{
+ Name: "checkpoints",
+ Usage: "list all checkpoints",
+ ArgsUsage: "COMMAND [arguments...]",
+ Subcommands: checkpointSubCmds,
+ Description: func() string {
+ desc := "\n COMMAND:\n"
+ for _, command := range checkpointSubCmds {
+ desc += fmt.Sprintf(" %-10.10s%s\n", command.Name, command.Usage)
+ }
+ return desc
+ }(),
+ Action: listCheckpoints,
+}
+
+var listCheckpointCommand = cli.Command{
+ Name: "list",
+ Usage: "list all checkpoints for a container",
+ Action: listCheckpoints,
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "checkpoint-dir",
+ Value: "",
+ Usage: "path to checkpoint directory",
+ },
+ },
+}
+
+func listCheckpoints(context *cli.Context) {
+ var (
+ c = getClient(context)
+ id = context.Args().First()
+ )
+ if id == "" {
+ fatal("container id cannot be empty", ExitStatusMissingArg)
+ }
+ resp, err := c.ListCheckpoint(netcontext.Background(), &types.ListCheckpointRequest{
+ Id: id,
+ CheckpointDir: context.String("checkpoint-dir"),
+ })
+ if err != nil {
+ fatal(err.Error(), 1)
+ }
+ w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
+ fmt.Fprint(w, "NAME\tTCP\tUNIX SOCKETS\tSHELL\n")
+ for _, c := range resp.Checkpoints {
+ fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", c.Name, c.Tcp, c.UnixSockets, c.Shell)
+ }
+ if err := w.Flush(); err != nil {
+ fatal(err.Error(), 1)
+ }
+}
+
+var createCheckpointCommand = cli.Command{
+ Name: "create",
+ Usage: "create a new checkpoint for the container",
+ Flags: []cli.Flag{
+ cli.BoolFlag{
+ Name: "tcp",
+ Usage: "persist open tcp connections",
+ },
+ cli.BoolFlag{
+ Name: "unix-sockets",
+ Usage: "persist unix sockets",
+ },
+ cli.BoolFlag{
+ Name: "exit",
+ Usage: "exit the container after the checkpoint completes successfully",
+ },
+ cli.BoolFlag{
+ Name: "shell",
+ Usage: "checkpoint shell jobs",
+ },
+ cli.StringFlag{
+ Name: "checkpoint-dir",
+ Value: "",
+ Usage: "directory to store checkpoints",
+ },
+ cli.StringSliceFlag{
+ Name: "empty-ns",
+ Usage: "create a namespace, but don't restore its properties",
+ },
+ },
+ Action: func(context *cli.Context) {
+ var (
+ containerID = context.Args().Get(0)
+ name = context.Args().Get(1)
+ )
+ if containerID == "" {
+ fatal("container id at cannot be empty", ExitStatusMissingArg)
+ }
+ if name == "" {
+ fatal("checkpoint name cannot be empty", ExitStatusMissingArg)
+ }
+ c := getClient(context)
+ checkpoint := types.Checkpoint{
+ Name: name,
+ Exit: context.Bool("exit"),
+ Tcp: context.Bool("tcp"),
+ Shell: context.Bool("shell"),
+ UnixSockets: context.Bool("unix-sockets"),
+ }
+
+ emptyNSes := context.StringSlice("empty-ns")
+ checkpoint.EmptyNS = append(checkpoint.EmptyNS, emptyNSes...)
+
+ if _, err := c.CreateCheckpoint(netcontext.Background(), &types.CreateCheckpointRequest{
+ Id: containerID,
+ CheckpointDir: context.String("checkpoint-dir"),
+ Checkpoint: &checkpoint,
+ }); err != nil {
+ fatal(err.Error(), 1)
+ }
+ },
+}
+
+var deleteCheckpointCommand = cli.Command{
+ Name: "delete",
+ Usage: "delete a container's checkpoint",
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "checkpoint-dir",
+ Value: "",
+ Usage: "path to checkpoint directory",
+ },
+ },
+ Action: func(context *cli.Context) {
+ var (
+ containerID = context.Args().Get(0)
+ name = context.Args().Get(1)
+ )
+ if containerID == "" {
+ fatal("container id at cannot be empty", ExitStatusMissingArg)
+ }
+ if name == "" {
+ fatal("checkpoint name cannot be empty", ExitStatusMissingArg)
+ }
+ c := getClient(context)
+ if _, err := c.DeleteCheckpoint(netcontext.Background(), &types.DeleteCheckpointRequest{
+ Id: containerID,
+ Name: name,
+ CheckpointDir: context.String("checkpoint-dir"),
+ }); err != nil {
+ fatal(err.Error(), 1)
+ }
+ },
+}
diff --git a/vendor/github.com/containerd/containerd/ctr/checkpoint_solaris.go b/vendor/github.com/containerd/containerd/ctr/checkpoint_solaris.go
new file mode 100644
index 0000000..0bed786
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/ctr/checkpoint_solaris.go
@@ -0,0 +1,36 @@
+package ctr
+
+import (
+ "fmt"
+
+ "github.com/urfave/cli"
+)
+
+var checkpointSubCmds = []cli.Command{
+ listCheckpointCommand,
+}
+
+var checkpointCommand = cli.Command{
+ Name: "checkpoints",
+ Usage: "list all checkpoints",
+ ArgsUsage: "COMMAND [arguments...]",
+ Subcommands: checkpointSubCmds,
+ Description: func() string {
+ desc := "\n COMMAND:\n"
+ for _, command := range checkpointSubCmds {
+ desc += fmt.Sprintf(" %-10.10s%s\n", command.Name, command.Usage)
+ }
+ return desc
+ }(),
+ Action: listCheckpoints,
+}
+
+var listCheckpointCommand = cli.Command{
+ Name: "list",
+ Usage: "list all checkpoints for a container",
+ Action: listCheckpoints,
+}
+
+func listCheckpoints(context *cli.Context) {
+ fatal("checkpoint command is not supported on Solaris", ExitStatusUnsupported)
+}
diff --git a/vendor/github.com/containerd/containerd/ctr/const.go b/vendor/github.com/containerd/containerd/ctr/const.go
new file mode 100644
index 0000000..3f962d3
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/ctr/const.go
@@ -0,0 +1,12 @@
+package ctr
+
+// ctr wide constants
+const (
+ // ExitStatusOK indicates successful completion
+ ExitStatusOK = 0
+
+ // ExitStatusMissingArg indicates failure due to missing argument(s)
+ ExitStatusMissingArg = 1
+ // ExitStatusUnsupported indicates failure due to unsupported subcommand(s)
+ ExitStatusUnsupported = 2
+)
diff --git a/vendor/github.com/containerd/containerd/ctr/container.go b/vendor/github.com/containerd/containerd/ctr/container.go
new file mode 100644
index 0000000..f57f866
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/ctr/container.go
@@ -0,0 +1,718 @@
+package ctr
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "log"
+ "net"
+ "os"
+ "os/signal"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "text/tabwriter"
+ "time"
+
+ "github.com/containerd/containerd/api/grpc/types"
+ "github.com/containerd/containerd/specs"
+ "github.com/containerd/console"
+ "github.com/golang/protobuf/ptypes"
+ "github.com/urfave/cli"
+ netcontext "golang.org/x/net/context"
+ "golang.org/x/sys/unix"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/grpclog"
+ "google.golang.org/grpc/transport"
+)
+
+// TODO: parse flags and pass opts
+func getClient(ctx *cli.Context) types.APIClient {
+ // Parse proto://address form addresses.
+ bindSpec := ctx.GlobalString("address")
+ bindParts := strings.SplitN(bindSpec, "://", 2)
+ if len(bindParts) != 2 {
+ fatal(fmt.Sprintf("bad bind address format %s, expected proto://address", bindSpec), 1)
+ }
+
+ // reset the logger for grpc to log to dev/null so that it does not mess with our stdio
+ grpclog.SetLogger(log.New(ioutil.Discard, "", log.LstdFlags))
+ dialOpts := []grpc.DialOption{grpc.WithInsecure(), grpc.WithTimeout(ctx.GlobalDuration("conn-timeout"))}
+ dialOpts = append(dialOpts,
+ grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
+ return net.DialTimeout(bindParts[0], bindParts[1], timeout)
+ },
+ ))
+ conn, err := grpc.Dial(bindSpec, dialOpts...)
+ if err != nil {
+ fatal(err.Error(), 1)
+ }
+ return types.NewAPIClient(conn)
+}
+
+var contSubCmds = []cli.Command{
+ execCommand,
+ killCommand,
+ listCommand,
+ pauseCommand,
+ resumeCommand,
+ startCommand,
+ stateCommand,
+ statsCommand,
+ watchCommand,
+ updateCommand,
+}
+
+var containersCommand = cli.Command{
+ Name: "containers",
+ Usage: "interact with running containers",
+ ArgsUsage: "COMMAND [arguments...]",
+ Subcommands: contSubCmds,
+ Description: func() string {
+ desc := "\n COMMAND:\n"
+ for _, command := range contSubCmds {
+ desc += fmt.Sprintf(" %-10.10s%s\n", command.Name, command.Usage)
+ }
+ return desc
+ }(),
+ Action: listContainers,
+}
+
+var stateCommand = cli.Command{
+ Name: "state",
+ Usage: "get a raw dump of the containerd state",
+ Action: func(context *cli.Context) error {
+ c := getClient(context)
+ resp, err := c.State(netcontext.Background(), &types.StateRequest{
+ Id: context.Args().First(),
+ })
+ if err != nil {
+ return err
+ }
+ data, err := json.Marshal(resp)
+ if err != nil {
+ return err
+ }
+ fmt.Print(string(data))
+ return nil
+ },
+}
+
+var listCommand = cli.Command{
+ Name: "list",
+ Usage: "list all running containers",
+ Action: listContainers,
+}
+
+func listContainers(context *cli.Context) error {
+ c := getClient(context)
+ resp, err := c.State(netcontext.Background(), &types.StateRequest{
+ Id: context.Args().First(),
+ })
+ if err != nil {
+ return err
+ }
+ w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
+ fmt.Fprint(w, "ID\tPATH\tSTATUS\tPROCESSES\n")
+ sortContainers(resp.Containers)
+ for _, c := range resp.Containers {
+ procs := []string{}
+ for _, p := range c.Processes {
+ procs = append(procs, p.Pid)
+ }
+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", c.Id, c.BundlePath, c.Status, strings.Join(procs, ","))
+ }
+ return w.Flush()
+}
+
+var startCommand = cli.Command{
+ Name: "start",
+ Usage: "start a container",
+ ArgsUsage: "ID BundlePath",
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "checkpoint,c",
+ Value: "",
+ Usage: "checkpoint to start the container from",
+ },
+ cli.StringFlag{
+ Name: "checkpoint-dir",
+ Value: "",
+ Usage: "path to checkpoint directory",
+ },
+ cli.BoolFlag{
+ Name: "attach,a",
+ Usage: "connect to the stdio of the container",
+ },
+ cli.StringSliceFlag{
+ Name: "label,l",
+ Value: &cli.StringSlice{},
+ Usage: "set labels for the container",
+ },
+ cli.BoolFlag{
+ Name: "no-pivot",
+ Usage: "do not use pivot root",
+ },
+ cli.StringFlag{
+ Name: "runtime,r",
+ Value: "runc",
+ Usage: "name or path of the OCI compliant runtime to use when executing containers",
+ },
+ cli.StringSliceFlag{
+ Name: "runtime-args",
+ Value: &cli.StringSlice{},
+ Usage: "specify additional runtime args",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ var (
+ id = context.Args().Get(0)
+ path = context.Args().Get(1)
+ )
+ if path == "" {
+ fatal("bundle path cannot be empty", ExitStatusMissingArg)
+ }
+ if id == "" {
+ fatal("container id cannot be empty", ExitStatusMissingArg)
+ }
+ bpath, err := filepath.Abs(path)
+ if err != nil {
+ return fmt.Errorf("cannot get the absolute path of the bundle: %v", err)
+ }
+ s, tmpDir, err := createStdio()
+ defer func() {
+ if tmpDir != "" {
+ os.RemoveAll(tmpDir)
+ }
+ }()
+ if err != nil {
+ return err
+ }
+ var (
+ con console.Console
+ tty bool
+ c = getClient(context)
+ r = &types.CreateContainerRequest{
+ Id: id,
+ BundlePath: bpath,
+ Checkpoint: context.String("checkpoint"),
+ CheckpointDir: context.String("checkpoint-dir"),
+ Stdin: s.stdin,
+ Stdout: s.stdout,
+ Stderr: s.stderr,
+ Labels: context.StringSlice("label"),
+ NoPivotRoot: context.Bool("no-pivot"),
+ Runtime: context.String("runtime"),
+ RuntimeArgs: context.StringSlice("runtime-args"),
+ }
+ )
+ if context.Bool("attach") {
+ mkterm, err := readTermSetting(bpath)
+ if err != nil {
+ return err
+ }
+ tty = mkterm
+ if mkterm {
+ con = console.Current()
+ defer func() {
+ con.Reset()
+ con.Close()
+ }()
+ if err := con.SetRaw(); err != nil {
+ return err
+ }
+ }
+ if err := attachStdio(s); err != nil {
+ return err
+ }
+ }
+ events, err := c.Events(netcontext.Background(), &types.EventsRequest{})
+ if err != nil {
+ return err
+ }
+ if _, err := c.CreateContainer(netcontext.Background(), r); err != nil {
+ return err
+ }
+ if context.Bool("attach") {
+ go func() {
+ io.Copy(stdin, os.Stdin)
+ if _, err := c.UpdateProcess(netcontext.Background(), &types.UpdateProcessRequest{
+ Id: id,
+ Pid: "init",
+ CloseStdin: true,
+ }); err != nil {
+ fatal(err.Error(), 1)
+ }
+ con.Reset()
+ con.Close()
+ }()
+ if tty {
+ resize(id, "init", c, con)
+ go func() {
+ s := make(chan os.Signal, 64)
+ signal.Notify(s, syscall.SIGWINCH)
+ for range s {
+ if err := resize(id, "init", c, con); err != nil {
+ log.Println(err)
+ }
+ }
+ }()
+ }
+ time.Sleep(2 * time.Second)
+ log.Println("closing stdin now")
+ if _, err := c.UpdateProcess(netcontext.Background(), &types.UpdateProcessRequest{
+ Id: id,
+ Pid: "init",
+ CloseStdin: true,
+ }); err != nil {
+ fatal(err.Error(), 1)
+ }
+
+ waitForExit(c, events, id, "init", con)
+ }
+ return nil
+ },
+}
+
+func resize(id, pid string, c types.APIClient, con console.Console) error {
+ ws, err := con.Size()
+ if err != nil {
+ return err
+ }
+ if _, err := c.UpdateProcess(netcontext.Background(), &types.UpdateProcessRequest{
+ Id: id,
+ Pid: "init",
+ Width: uint32(ws.Width),
+ Height: uint32(ws.Height),
+ }); err != nil {
+ return err
+ }
+ return nil
+}
+
+var (
+ stdin io.WriteCloser
+)
+
+// readTermSetting reads the Terminal option out of the specs configuration
+// to know if ctr should allocate a pty
+func readTermSetting(path string) (bool, error) {
+ f, err := os.Open(filepath.Join(path, "config.json"))
+ if err != nil {
+ return false, err
+ }
+ defer f.Close()
+ var spec specs.Spec
+ if err := json.NewDecoder(f).Decode(&spec); err != nil {
+ return false, err
+ }
+ return spec.Process.Terminal, nil
+}
+
+func attachStdio(s stdio) error {
+ stdinf, err := os.OpenFile(s.stdin, syscall.O_RDWR, 0)
+ if err != nil {
+ return err
+ }
+ // FIXME: assign to global
+ stdin = stdinf
+ stdoutf, err := os.OpenFile(s.stdout, syscall.O_RDWR, 0)
+ if err != nil {
+ return err
+ }
+ go io.Copy(os.Stdout, stdoutf)
+ stderrf, err := os.OpenFile(s.stderr, syscall.O_RDWR, 0)
+ if err != nil {
+ return err
+ }
+ go io.Copy(os.Stderr, stderrf)
+ return nil
+}
+
+var watchCommand = cli.Command{
+ Name: "watch",
+ Usage: "print container events",
+ Action: func(context *cli.Context) error {
+ c := getClient(context)
+ id := context.Args().First()
+ if id != "" {
+ resp, err := c.State(netcontext.Background(), &types.StateRequest{Id: id})
+ if err != nil {
+ return err
+ }
+ for _, c := range resp.Containers {
+ if c.Id == id {
+ break
+ }
+ }
+ if id == "" {
+ fatal("Invalid container id", 1)
+ }
+ }
+ events, reqErr := c.Events(netcontext.Background(), &types.EventsRequest{})
+ if reqErr != nil {
+ return reqErr
+ }
+
+ for {
+ e, err := events.Recv()
+ if err != nil {
+ return err
+ }
+
+ if id == "" || e.Id == id {
+ fmt.Printf("%#v\n", e)
+ }
+ return nil
+ }
+ },
+}
+
+var pauseCommand = cli.Command{
+ Name: "pause",
+ Usage: "pause a container",
+ Action: func(context *cli.Context) error {
+ id := context.Args().First()
+ if id == "" {
+ fatal("container id cannot be empty", ExitStatusMissingArg)
+ }
+ c := getClient(context)
+ _, err := c.UpdateContainer(netcontext.Background(), &types.UpdateContainerRequest{
+ Id: id,
+ Pid: "init",
+ Status: "paused",
+ })
+ return err
+ },
+}
+
+var resumeCommand = cli.Command{
+ Name: "resume",
+ Usage: "resume a paused container",
+ Action: func(context *cli.Context) error {
+ id := context.Args().First()
+ if id == "" {
+ fatal("container id cannot be empty", ExitStatusMissingArg)
+ }
+ c := getClient(context)
+ _, err := c.UpdateContainer(netcontext.Background(), &types.UpdateContainerRequest{
+ Id: id,
+ Pid: "init",
+ Status: "running",
+ })
+ return err
+ },
+}
+
+var killCommand = cli.Command{
+ Name: "kill",
+ Usage: "send a signal to a container or its processes",
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "pid,p",
+ Value: "init",
+ Usage: "pid of the process to signal within the container",
+ },
+ cli.IntFlag{
+ Name: "signal,s",
+ Value: 15,
+ Usage: "signal to send to the container",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ id := context.Args().First()
+ if id == "" {
+ fatal("container id cannot be empty", ExitStatusMissingArg)
+ }
+ c := getClient(context)
+ _, err := c.Signal(netcontext.Background(), &types.SignalRequest{
+ Id: id,
+ Pid: context.String("pid"),
+ Signal: uint32(context.Int("signal")),
+ })
+ return err
+ },
+}
+
+var execCommand = cli.Command{
+ Name: "exec",
+ Usage: "exec another process in an existing container",
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "id",
+ Usage: "container id to add the process to",
+ },
+ cli.StringFlag{
+ Name: "pid",
+ Usage: "process id for the new process",
+ },
+ cli.BoolFlag{
+ Name: "attach,a",
+ Usage: "connect to the stdio of the container",
+ },
+ cli.StringFlag{
+ Name: "cwd",
+ Usage: "current working directory for the process",
+ Value: "/",
+ },
+ cli.BoolFlag{
+ Name: "tty,t",
+ Usage: "create a terminal for the process",
+ },
+ cli.StringSliceFlag{
+ Name: "env,e",
+ Value: &cli.StringSlice{},
+ Usage: "environment variables for the process",
+ },
+ cli.IntFlag{
+ Name: "uid,u",
+ Usage: "user id of the user for the process",
+ },
+ cli.IntFlag{
+ Name: "gid,g",
+ Usage: "group id of the user for the process",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ p := &types.AddProcessRequest{
+ Id: context.String("id"),
+ Pid: context.String("pid"),
+ Args: context.Args(),
+ Cwd: context.String("cwd"),
+ Terminal: context.Bool("tty"),
+ Env: context.StringSlice("env"),
+ User: &types.User{
+ Uid: uint32(context.Int("uid")),
+ Gid: uint32(context.Int("gid")),
+ },
+ }
+ s, tmpDir, err := createStdio()
+ defer func() {
+ if tmpDir != "" {
+ os.RemoveAll(tmpDir)
+ }
+ }()
+ if err != nil {
+ return err
+ }
+ p.Stdin = s.stdin
+ p.Stdout = s.stdout
+ p.Stderr = s.stderr
+
+ var con console.Console
+ if context.Bool("attach") {
+ if context.Bool("tty") {
+ con = console.Current()
+ defer func() {
+ con.Reset()
+ con.Close()
+ }()
+ if err := con.SetRaw(); err != nil {
+ return err
+ }
+ }
+ if err := attachStdio(s); err != nil {
+ return err
+ }
+ }
+ c := getClient(context)
+ events, err := c.Events(netcontext.Background(), &types.EventsRequest{})
+ if err != nil {
+ return err
+ }
+ if _, err := c.AddProcess(netcontext.Background(), p); err != nil {
+ return err
+ }
+ if context.Bool("attach") {
+ go func() {
+ io.Copy(stdin, os.Stdin)
+ if _, err := c.UpdateProcess(netcontext.Background(), &types.UpdateProcessRequest{
+ Id: p.Id,
+ Pid: p.Pid,
+ CloseStdin: true,
+ }); err != nil {
+ log.Println(err)
+ }
+ con.Reset()
+ con.Close()
+ }()
+ if context.Bool("tty") {
+ resize(p.Id, p.Pid, c, con)
+ go func() {
+ s := make(chan os.Signal, 64)
+ signal.Notify(s, syscall.SIGWINCH)
+ for range s {
+ if err := resize(p.Id, p.Pid, c, con); err != nil {
+ log.Println(err)
+ }
+ }
+ }()
+ }
+ waitForExit(c, events, context.String("id"), context.String("pid"), con)
+ }
+ return nil
+ },
+}
+
+var statsCommand = cli.Command{
+ Name: "stats",
+ Usage: "get stats for running container",
+ Action: func(context *cli.Context) error {
+ req := &types.StatsRequest{
+ Id: context.Args().First(),
+ }
+ c := getClient(context)
+ stats, err := c.Stats(netcontext.Background(), req)
+ if err != nil {
+ return err
+ }
+ data, err := json.Marshal(stats)
+ if err != nil {
+ return err
+ }
+ fmt.Print(string(data))
+ return nil
+ },
+}
+
+func getUpdateCommandInt64Flag(context *cli.Context, name string) uint64 {
+ str := context.String(name)
+ if str == "" {
+ return 0
+ }
+
+ val, err := strconv.ParseUint(str, 0, 64)
+ if err != nil {
+ fatal(err.Error(), 1)
+ }
+
+ return val
+}
+
+var updateCommand = cli.Command{
+ Name: "update",
+ Usage: "update a containers resources",
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "memory-limit",
+ },
+ cli.StringFlag{
+ Name: "memory-reservation",
+ },
+ cli.StringFlag{
+ Name: "memory-swap",
+ },
+ cli.StringFlag{
+ Name: "cpu-quota",
+ },
+ cli.StringFlag{
+ Name: "cpu-period",
+ },
+ cli.StringFlag{
+ Name: "kernel-limit",
+ },
+ cli.StringFlag{
+ Name: "kernel-tcp-limit",
+ },
+ cli.StringFlag{
+ Name: "blkio-weight",
+ },
+ cli.StringFlag{
+ Name: "cpuset-cpus",
+ },
+ cli.StringFlag{
+ Name: "cpuset-mems",
+ },
+ cli.StringFlag{
+ Name: "pids-limit",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ req := &types.UpdateContainerRequest{
+ Id: context.Args().First(),
+ }
+ req.Resources = &types.UpdateResource{}
+ req.Resources.MemoryLimit = getUpdateCommandInt64Flag(context, "memory-limit")
+ req.Resources.MemoryReservation = getUpdateCommandInt64Flag(context, "memory-reservation")
+ req.Resources.MemorySwap = getUpdateCommandInt64Flag(context, "memory-swap")
+ req.Resources.BlkioWeight = getUpdateCommandInt64Flag(context, "blkio-weight")
+ req.Resources.CpuPeriod = getUpdateCommandInt64Flag(context, "cpu-period")
+ req.Resources.CpuQuota = getUpdateCommandInt64Flag(context, "cpu-quota")
+ req.Resources.CpuShares = getUpdateCommandInt64Flag(context, "cpu-shares")
+ req.Resources.CpusetCpus = context.String("cpuset-cpus")
+ req.Resources.CpusetMems = context.String("cpuset-mems")
+ req.Resources.KernelMemoryLimit = getUpdateCommandInt64Flag(context, "kernel-limit")
+ req.Resources.KernelTCPMemoryLimit = getUpdateCommandInt64Flag(context, "kernel-tcp-limit")
+ req.Resources.PidsLimit = getUpdateCommandInt64Flag(context, "pids-limit")
+ c := getClient(context)
+ _, err := c.UpdateContainer(netcontext.Background(), req)
+ return err
+ },
+}
+
+func waitForExit(c types.APIClient, events types.API_EventsClient, id, pid string, con console.Console) {
+ timestamp := time.Now()
+ for {
+ e, err := events.Recv()
+ if err != nil {
+ if grpc.ErrorDesc(err) == transport.ErrConnClosing.Desc {
+ if con != nil {
+ con.Reset()
+ con.Close()
+ }
+ os.Exit(128 + int(syscall.SIGHUP))
+ }
+ time.Sleep(1 * time.Second)
+ tsp, err := ptypes.TimestampProto(timestamp)
+ if err != nil {
+ if con != nil {
+ con.Reset()
+ con.Close()
+ }
+ fmt.Fprintf(os.Stderr, "%s", err.Error())
+ os.Exit(1)
+ }
+ events, _ = c.Events(netcontext.Background(), &types.EventsRequest{Timestamp: tsp})
+ continue
+ }
+ timestamp, err = ptypes.Timestamp(e.Timestamp)
+ if e.Id == id && e.Type == "exit" && e.Pid == pid {
+ if con != nil {
+ con.Reset()
+ con.Close()
+ }
+ os.Exit(int(e.Status))
+ }
+ }
+}
+
+type stdio struct {
+ stdin string
+ stdout string
+ stderr string
+}
+
+func createStdio() (s stdio, tmp string, err error) {
+ tmp, err = ioutil.TempDir("", "ctr-")
+ if err != nil {
+ return s, tmp, err
+ }
+ // create fifo's for the process
+ for _, pair := range []struct {
+ name string
+ fd *string
+ }{
+ {"stdin", &s.stdin},
+ {"stdout", &s.stdout},
+ {"stderr", &s.stderr},
+ } {
+ path := filepath.Join(tmp, pair.name)
+ if err := unix.Mkfifo(path, 0755); err != nil && !os.IsExist(err) {
+ return s, tmp, err
+ }
+ *pair.fd = path
+ }
+ return s, tmp, nil
+}
diff --git a/vendor/github.com/containerd/containerd/ctr/events.go b/vendor/github.com/containerd/containerd/ctr/events.go
new file mode 100644
index 0000000..03696f4
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/ctr/events.go
@@ -0,0 +1,63 @@
+package ctr
+
+import (
+ "fmt"
+ "os"
+ "text/tabwriter"
+ "time"
+
+ "github.com/urfave/cli"
+ "github.com/containerd/containerd/api/grpc/types"
+ "github.com/golang/protobuf/ptypes"
+ netcontext "golang.org/x/net/context"
+)
+
+var eventsCommand = cli.Command{
+ Name: "events",
+ Usage: "receive events from the containerd daemon",
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "timestamp,t",
+ Usage: "get events from a specific time stamp in RFC3339Nano format",
+ },
+ },
+ Action: func(context *cli.Context) {
+ var (
+ t = time.Time{}
+ c = getClient(context)
+ )
+ if ts := context.String("timestamp"); ts != "" {
+ from, err := time.Parse(time.RFC3339Nano, ts)
+ if err != nil {
+ fatal(err.Error(), 1)
+ }
+ t = from
+ }
+ tsp, err := ptypes.TimestampProto(t)
+ if err != nil {
+ fatal(err.Error(), 1)
+ }
+ events, err := c.Events(netcontext.Background(), &types.EventsRequest{
+ Timestamp: tsp,
+ })
+ if err != nil {
+ fatal(err.Error(), 1)
+ }
+ w := tabwriter.NewWriter(os.Stdout, 31, 1, 1, ' ', 0)
+ fmt.Fprint(w, "TIME\tTYPE\tID\tPID\tSTATUS\n")
+ w.Flush()
+ for {
+ e, err := events.Recv()
+ if err != nil {
+ fatal(err.Error(), 1)
+ }
+ t, err := ptypes.Timestamp(e.Timestamp)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Unable to convert timestamp")
+ t = time.Time{}
+ }
+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%d\n", t.Format(time.RFC3339Nano), e.Type, e.Id, e.Pid, e.Status)
+ w.Flush()
+ }
+ },
+}
diff --git a/vendor/github.com/containerd/containerd/ctr/main.go b/vendor/github.com/containerd/containerd/ctr/main.go
new file mode 100644
index 0000000..d0d8e5c
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/ctr/main.go
@@ -0,0 +1,90 @@
+package ctr
+
+import (
+ "fmt"
+ "os"
+ "time"
+
+ netcontext "golang.org/x/net/context"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/urfave/cli"
+ "github.com/containerd/containerd"
+ "github.com/containerd/containerd/api/grpc/types"
+)
+
+const usage = `High performance container daemon cli`
+
+type exit struct {
+ Code int
+}
+
+func Main() {
+ // We want our defer functions to be run when calling fatal()
+ defer func() {
+ if e := recover(); e != nil {
+ if ex, ok := e.(exit); ok == true {
+ os.Exit(ex.Code)
+ }
+ panic(e)
+ }
+ }()
+ app := cli.NewApp()
+ app.Name = "ctr"
+ if containerd.GitCommit != "" {
+ app.Version = fmt.Sprintf("%s commit: %s", containerd.Version, containerd.GitCommit)
+ } else {
+ app.Version = containerd.Version
+ }
+ app.Usage = usage
+ app.Flags = []cli.Flag{
+ cli.BoolFlag{
+ Name: "debug",
+ Usage: "enable debug output in the logs",
+ },
+ cli.StringFlag{
+ Name: "address",
+ Value: "unix:///run/containerd/containerd.sock",
+ Usage: "proto://address of GRPC API",
+ },
+ cli.DurationFlag{
+ Name: "conn-timeout",
+ Value: 1 * time.Second,
+ Usage: "GRPC connection timeout",
+ },
+ }
+ app.Commands = []cli.Command{
+ checkpointCommand,
+ containersCommand,
+ eventsCommand,
+ stateCommand,
+ versionCommand,
+ }
+ app.Before = func(context *cli.Context) error {
+ if context.GlobalBool("debug") {
+ logrus.SetLevel(logrus.DebugLevel)
+ }
+ return nil
+ }
+ if err := app.Run(os.Args); err != nil {
+ logrus.Fatal(err)
+ }
+}
+
+var versionCommand = cli.Command{
+ Name: "version",
+ Usage: "return the daemon version",
+ Action: func(context *cli.Context) {
+ c := getClient(context)
+ resp, err := c.GetServerVersion(netcontext.Background(), &types.GetServerVersionRequest{})
+ if err != nil {
+ fatal(err.Error(), 1)
+ }
+ fmt.Printf("daemon version %d.%d.%d commit: %s\n", resp.Major, resp.Minor, resp.Patch, resp.Revision)
+ },
+}
+
+func fatal(err string, code int) {
+ fmt.Fprintf(os.Stderr, "[ctr] %s\n", err)
+ panic(exit{code})
+}
diff --git a/vendor/github.com/containerd/containerd/ctr/sort.go b/vendor/github.com/containerd/containerd/ctr/sort.go
new file mode 100644
index 0000000..461583d
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/ctr/sort.go
@@ -0,0 +1,27 @@
+package ctr
+
+import (
+ "sort"
+
+ "github.com/containerd/containerd/api/grpc/types"
+)
+
+func sortContainers(c []*types.Container) {
+ sort.Sort(&containerSorter{c})
+}
+
+type containerSorter struct {
+ c []*types.Container
+}
+
+func (s *containerSorter) Len() int {
+ return len(s.c)
+}
+
+func (s *containerSorter) Swap(i, j int) {
+ s.c[i], s.c[j] = s.c[j], s.c[i]
+}
+
+func (s *containerSorter) Less(i, j int) bool {
+ return s.c[i].Id < s.c[j].Id
+}
diff --git a/vendor/github.com/containerd/containerd/osutils/fds.go b/vendor/github.com/containerd/containerd/osutils/fds.go
new file mode 100644
index 0000000..98fc930
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/osutils/fds.go
@@ -0,0 +1,18 @@
+// +build !windows,!darwin
+
+package osutils
+
+import (
+ "io/ioutil"
+ "path/filepath"
+ "strconv"
+)
+
+// GetOpenFds returns the number of open fds for the process provided by pid
+func GetOpenFds(pid int) (int, error) {
+ dirs, err := ioutil.ReadDir(filepath.Join("/proc", strconv.Itoa(pid), "fd"))
+ if err != nil {
+ return -1, err
+ }
+ return len(dirs), nil
+}
diff --git a/vendor/github.com/containerd/containerd/osutils/pdeathsig_linux.go b/vendor/github.com/containerd/containerd/osutils/pdeathsig_linux.go
new file mode 100644
index 0000000..5310f2e
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/osutils/pdeathsig_linux.go
@@ -0,0 +1,15 @@
+// +build !solaris
+
+package osutils
+
+import (
+ "syscall"
+)
+
+// SetPDeathSig sets the parent death signal to SIGKILL so that if the
+// shim dies the container process also dies.
+func SetPDeathSig() *syscall.SysProcAttr {
+ return &syscall.SysProcAttr{
+ Pdeathsig: syscall.SIGKILL,
+ }
+}
diff --git a/vendor/github.com/containerd/containerd/osutils/pdeathsig_solaris.go b/vendor/github.com/containerd/containerd/osutils/pdeathsig_solaris.go
new file mode 100644
index 0000000..512e24b
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/osutils/pdeathsig_solaris.go
@@ -0,0 +1,8 @@
+// +build solaris
+
+package osutils
+
+// SetPDeathSig is a no-op on Solaris as Pdeathsig is not defined.
+func SetPDeathSig() *syscall.SysProcAttr {
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/osutils/prctl.go b/vendor/github.com/containerd/containerd/osutils/prctl.go
new file mode 100644
index 0000000..1d6e251
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/osutils/prctl.go
@@ -0,0 +1,48 @@
+// +build linux
+
+// Package osutils provide access to the Get Child and Set Child prctl
+// flags.
+// See http://man7.org/linux/man-pages/man2/prctl.2.html
+package osutils
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// PR_SET_CHILD_SUBREAPER allows setting the child subreaper.
+// If arg2 is nonzero, set the "child subreaper" attribute of the
+// calling process; if arg2 is zero, unset the attribute. When a
+// process is marked as a child subreaper, all of the children
+// that it creates, and their descendants, will be marked as
+// having a subreaper. In effect, a subreaper fulfills the role
+// of init(1) for its descendant processes. Upon termination of
+// a process that is orphaned (i.e., its immediate parent has
+// already terminated) and marked as having a subreaper, the
+// nearest still living ancestor subreaper will receive a SIGCHLD
+// signal and be able to wait(2) on the process to discover its
+// termination status.
+const prSetChildSubreaper = 36
+
+// PR_GET_CHILD_SUBREAPER allows retrieving the current child
+// subreaper.
+// Return the "child subreaper" setting of the caller, in the
+// location pointed to by (int *) arg2.
+const prGetChildSubreaper = 37
+
+// GetSubreaper returns the subreaper setting for the calling process
+func GetSubreaper() (int, error) {
+ var i uintptr
+ if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, prGetChildSubreaper, uintptr(unsafe.Pointer(&i)), 0); err != 0 {
+ return -1, err
+ }
+ return int(i), nil
+}
+
+// SetSubreaper sets the value i as the subreaper setting for the calling process
+func SetSubreaper(i int) error {
+ if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, prSetChildSubreaper, uintptr(i), 0); err != 0 {
+ return err
+ }
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/osutils/prctl_solaris.go b/vendor/github.com/containerd/containerd/osutils/prctl_solaris.go
new file mode 100644
index 0000000..84da5f9
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/osutils/prctl_solaris.go
@@ -0,0 +1,19 @@
+// +build solaris
+
+package osutils
+
+import (
+ "errors"
+)
+
+//Solaris TODO
+
+// GetSubreaper returns the subreaper setting for the calling process
+func GetSubreaper() (int, error) {
+ return 0, errors.New("osutils GetSubreaper not implemented on Solaris")
+}
+
+// SetSubreaper sets the value i as the subreaper setting for the calling process
+func SetSubreaper(i int) error {
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/osutils/reaper.go b/vendor/github.com/containerd/containerd/osutils/reaper.go
new file mode 100644
index 0000000..6a80335
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/osutils/reaper.go
@@ -0,0 +1,51 @@
+// +build !windows
+
+package osutils
+
+import "syscall"
+
+// Exit is the wait4 information from an exited process
+type Exit struct {
+ Pid int
+ Status int
+}
+
+// Reap reaps all child processes for the calling process and returns their
+// exit information
+func Reap(wait bool) (exits []Exit, err error) {
+ var (
+ ws syscall.WaitStatus
+ rus syscall.Rusage
+ )
+ flag := syscall.WNOHANG
+ if wait {
+ flag = 0
+ }
+ for {
+ pid, err := syscall.Wait4(-1, &ws, flag, &rus)
+ if err != nil {
+ if err == syscall.ECHILD {
+ return exits, nil
+ }
+ return exits, err
+ }
+ if pid <= 0 {
+ return exits, nil
+ }
+ exits = append(exits, Exit{
+ Pid: pid,
+ Status: exitStatus(ws),
+ })
+ }
+}
+
+const exitSignalOffset = 128
+
+// exitStatus returns the correct exit status for a process based on if it
+// was signaled or exited cleanly
+func exitStatus(status syscall.WaitStatus) int {
+ if status.Signaled() {
+ return exitSignalOffset + int(status.Signal())
+ }
+ return status.ExitStatus()
+}
diff --git a/vendor/github.com/containerd/containerd/runtime/container.go b/vendor/github.com/containerd/containerd/runtime/container.go
new file mode 100644
index 0000000..a9677c4
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/runtime/container.go
@@ -0,0 +1,748 @@
+package runtime
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/containerd/containerd/specs"
+ ocs "github.com/opencontainers/runtime-spec/specs-go"
+ "golang.org/x/net/context"
+ "golang.org/x/sys/unix"
+)
+
+// Container defines the operations allowed on a container
+type Container interface {
+ // ID returns the container ID
+ ID() string
+ // Path returns the path to the bundle
+ Path() string
+ // Start starts the init process of the container
+ Start(ctx context.Context, checkpointPath string, s Stdio) (Process, error)
+ // Exec starts another process in an existing container
+ Exec(context.Context, string, specs.ProcessSpec, Stdio) (Process, error)
+ // Delete removes the container's state and any resources
+ Delete() error
+ // Processes returns all the containers processes that have been added
+ Processes() ([]Process, error)
+ // State returns the containers runtime state
+ State() State
+ // Resume resumes a paused container
+ Resume() error
+ // Pause pauses a running container
+ Pause() error
+ // RemoveProcess removes the specified process from the container
+ RemoveProcess(string) error
+ // Checkpoints returns all the checkpoints for a container
+ Checkpoints(checkpointDir string) ([]Checkpoint, error)
+ // Checkpoint creates a new checkpoint
+ Checkpoint(checkpoint Checkpoint, checkpointDir string) error
+ // DeleteCheckpoint deletes the checkpoint for the provided name
+ DeleteCheckpoint(name string, checkpointDir string) error
+ // Labels are user provided labels for the container
+ Labels() []string
+ // Pids returns all pids inside the container
+ Pids() ([]int, error)
+ // Stats returns realtime container stats and resource information
+ Stats() (*Stat, error)
+ // Name or path of the OCI compliant runtime used to execute the container
+ Runtime() string
+ // OOM signals the channel if the container received an OOM notification
+ OOM() (OOM, error)
+ // UpdateResource updates the containers resources to new values
+ UpdateResources(*Resource) error
+
+ // Status return the current status of the container.
+ Status() (State, error)
+}
+
+// OOM wraps a container OOM.
+type OOM interface {
+ io.Closer
+ FD() int
+ ContainerID() string
+ Flush()
+ Removed() bool
+}
+
+// Stdio holds the path to the 3 pipes used for the standard ios.
+type Stdio struct {
+ Stdin string
+ Stdout string
+ Stderr string
+}
+
+// NewStdio wraps the given standard io path into an Stdio struct.
+// If a given parameter is the empty string, it is replaced by "/dev/null"
+func NewStdio(stdin, stdout, stderr string) Stdio {
+ for _, s := range []*string{
+ &stdin, &stdout, &stderr,
+ } {
+ if *s == "" {
+ *s = "/dev/null"
+ }
+ }
+ return Stdio{
+ Stdin: stdin,
+ Stdout: stdout,
+ Stderr: stderr,
+ }
+}
+
+// ContainerOpts keeps the options passed at container creation
+type ContainerOpts struct {
+ Root string
+ ID string
+ Bundle string
+ Runtime string
+ RuntimeArgs []string
+ Shim string
+ Labels []string
+ NoPivotRoot bool
+ Timeout time.Duration
+}
+
+// New returns a new container
+func New(opts ContainerOpts) (Container, error) {
+ c := &container{
+ root: opts.Root,
+ id: opts.ID,
+ bundle: opts.Bundle,
+ labels: opts.Labels,
+ processes: make(map[string]*process),
+ runtime: opts.Runtime,
+ runtimeArgs: opts.RuntimeArgs,
+ shim: opts.Shim,
+ noPivotRoot: opts.NoPivotRoot,
+ timeout: opts.Timeout,
+ }
+ if err := os.Mkdir(filepath.Join(c.root, c.id), 0755); err != nil {
+ return nil, err
+ }
+ f, err := os.Create(filepath.Join(c.root, c.id, StateFile))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ if err := json.NewEncoder(f).Encode(state{
+ Bundle: c.bundle,
+ Labels: c.labels,
+ Runtime: c.runtime,
+ RuntimeArgs: c.runtimeArgs,
+ Shim: c.shim,
+ NoPivotRoot: opts.NoPivotRoot,
+ }); err != nil {
+ return nil, err
+ }
+ return c, nil
+}
+
+// Load return a new container from the matchin state file on disk.
+func Load(root, id, shimName string, timeout time.Duration) (Container, error) {
+ var s state
+ f, err := os.Open(filepath.Join(root, id, StateFile))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ if err := json.NewDecoder(f).Decode(&s); err != nil {
+ return nil, err
+ }
+ c := &container{
+ root: root,
+ id: id,
+ bundle: s.Bundle,
+ labels: s.Labels,
+ runtime: s.Runtime,
+ runtimeArgs: s.RuntimeArgs,
+ shim: s.Shim,
+ noPivotRoot: s.NoPivotRoot,
+ processes: make(map[string]*process),
+ timeout: timeout,
+ }
+
+ if c.shim == "" {
+ c.shim = shimName
+ }
+
+ dirs, err := ioutil.ReadDir(filepath.Join(root, id))
+ if err != nil {
+ return nil, err
+ }
+ for _, d := range dirs {
+ if !d.IsDir() {
+ continue
+ }
+ pid := d.Name()
+ s, err := readProcessState(filepath.Join(root, id, pid))
+ if err != nil {
+ return nil, err
+ }
+ p, err := loadProcess(filepath.Join(root, id, pid), pid, c, s)
+ if err != nil {
+ logrus.WithField("id", id).WithField("pid", pid).Debugf("containerd: error loading process %s", err)
+ continue
+ }
+ c.processes[pid] = p
+ }
+
+ _, err = os.Stat(c.bundle)
+ if err != nil && !os.IsExist(err) {
+ for key, p := range c.processes {
+ if key == InitProcessID {
+ p.Delete()
+ break
+ }
+ }
+ return nil, fmt.Errorf("bundle dir %s don't exist", c.bundle)
+ }
+ return c, nil
+}
+
+func readProcessState(dir string) (*ProcessState, error) {
+ f, err := os.Open(filepath.Join(dir, "process.json"))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ var s ProcessState
+ if err := json.NewDecoder(f).Decode(&s); err != nil {
+ return nil, err
+ }
+ return &s, nil
+}
+
+type container struct {
+ // path to store runtime state information
+ root string
+ id string
+ bundle string
+ runtime string
+ runtimeArgs []string
+ shim string
+ processes map[string]*process
+ labels []string
+ oomFds []int
+ noPivotRoot bool
+ timeout time.Duration
+}
+
+func (c *container) ID() string {
+ return c.id
+}
+
+func (c *container) Path() string {
+ return c.bundle
+}
+
+func (c *container) Labels() []string {
+ return c.labels
+}
+
+func (c *container) readSpec() (*specs.Spec, error) {
+ var spec specs.Spec
+ f, err := os.Open(filepath.Join(c.bundle, "config.json"))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ if err := json.NewDecoder(f).Decode(&spec); err != nil {
+ return nil, err
+ }
+ return &spec, nil
+}
+
+func (c *container) Delete() error {
+ var err error
+ args := append(c.runtimeArgs, "delete", c.id)
+ if b, derr := exec.Command(c.runtime, args...).CombinedOutput(); derr != nil && !strings.Contains(string(b), "does not exist") {
+ err = fmt.Errorf("%s: %q", derr, string(b))
+ }
+ if rerr := os.RemoveAll(filepath.Join(c.root, c.id)); rerr != nil {
+ if err != nil {
+ err = fmt.Errorf("%s; failed to remove %s: %s", err, filepath.Join(c.root, c.id), rerr)
+ } else {
+ err = rerr
+ }
+ }
+ return err
+}
+
+func (c *container) Processes() ([]Process, error) {
+ out := []Process{}
+ for _, p := range c.processes {
+ out = append(out, p)
+ }
+ return out, nil
+}
+
+func (c *container) RemoveProcess(pid string) error {
+ delete(c.processes, pid)
+ return os.RemoveAll(filepath.Join(c.root, c.id, pid))
+}
+
+func (c *container) State() State {
+ proc := c.processes[InitProcessID]
+ if proc == nil {
+ return Stopped
+ }
+ return proc.State()
+}
+
+func (c *container) Runtime() string {
+ return c.runtime
+}
+
+func (c *container) Pause() error {
+ args := c.runtimeArgs
+ args = append(args, "pause", c.id)
+ b, err := exec.Command(c.runtime, args...).CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s: %q", err.Error(), string(b))
+ }
+ return nil
+}
+
+func (c *container) Resume() error {
+ args := c.runtimeArgs
+ args = append(args, "resume", c.id)
+ b, err := exec.Command(c.runtime, args...).CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s: %q", err.Error(), string(b))
+ }
+ return nil
+}
+
+func (c *container) Checkpoints(checkpointDir string) ([]Checkpoint, error) {
+ if checkpointDir == "" {
+ checkpointDir = filepath.Join(c.bundle, "checkpoints")
+ }
+
+ dirs, err := ioutil.ReadDir(checkpointDir)
+ if err != nil {
+ return nil, err
+ }
+ var out []Checkpoint
+ for _, d := range dirs {
+ if !d.IsDir() {
+ continue
+ }
+ path := filepath.Join(checkpointDir, d.Name(), "config.json")
+ data, err := ioutil.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ var cpt Checkpoint
+ if err := json.Unmarshal(data, &cpt); err != nil {
+ return nil, err
+ }
+ out = append(out, cpt)
+ }
+ return out, nil
+}
+
+func (c *container) Checkpoint(cpt Checkpoint, checkpointDir string) error {
+ if checkpointDir == "" {
+ checkpointDir = filepath.Join(c.bundle, "checkpoints")
+ }
+
+ if err := os.MkdirAll(checkpointDir, 0755); err != nil {
+ return err
+ }
+
+ path := filepath.Join(checkpointDir, cpt.Name)
+ if err := os.Mkdir(path, 0755); err != nil {
+ return err
+ }
+ f, err := os.Create(filepath.Join(path, "config.json"))
+ if err != nil {
+ return err
+ }
+ cpt.Created = time.Now()
+ err = json.NewEncoder(f).Encode(cpt)
+ f.Close()
+ if err != nil {
+ return err
+ }
+ args := []string{
+ "checkpoint",
+ "--image-path", path,
+ "--work-path", filepath.Join(path, "criu.work"),
+ }
+ add := func(flags ...string) {
+ args = append(args, flags...)
+ }
+ add(c.runtimeArgs...)
+ if !cpt.Exit {
+ add("--leave-running")
+ }
+ if cpt.Shell {
+ add("--shell-job")
+ }
+ if cpt.TCP {
+ add("--tcp-established")
+ }
+ if cpt.UnixSockets {
+ add("--ext-unix-sk")
+ }
+ for _, ns := range cpt.EmptyNS {
+ add("--empty-ns", ns)
+ }
+ add(c.id)
+ out, err := exec.Command(c.runtime, args...).CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s: %q", err.Error(), string(out))
+ }
+ return err
+}
+
+func (c *container) DeleteCheckpoint(name string, checkpointDir string) error {
+ if checkpointDir == "" {
+ checkpointDir = filepath.Join(c.bundle, "checkpoints")
+ }
+ return os.RemoveAll(filepath.Join(checkpointDir, name))
+}
+
+func (c *container) Start(ctx context.Context, checkpointPath string, s Stdio) (Process, error) {
+ processRoot := filepath.Join(c.root, c.id, InitProcessID)
+ if err := os.Mkdir(processRoot, 0755); err != nil {
+ return nil, err
+ }
+ cmd := exec.Command(c.shim,
+ c.id, c.bundle, c.runtime,
+ )
+ cmd.Dir = processRoot
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ Setpgid: true,
+ }
+ spec, err := c.readSpec()
+ if err != nil {
+ return nil, err
+ }
+ config := &processConfig{
+ checkpoint: checkpointPath,
+ root: processRoot,
+ id: InitProcessID,
+ c: c,
+ stdio: s,
+ spec: spec,
+ processSpec: specs.ProcessSpec(spec.Process),
+ }
+ p, err := newProcess(config)
+ if err != nil {
+ return nil, err
+ }
+ if err := c.createCmd(ctx, InitProcessID, cmd, p); err != nil {
+ return nil, err
+ }
+ return p, nil
+}
+
+func (c *container) Exec(ctx context.Context, pid string, pspec specs.ProcessSpec, s Stdio) (pp Process, err error) {
+ processRoot := filepath.Join(c.root, c.id, pid)
+ if err := os.Mkdir(processRoot, 0755); err != nil {
+ return nil, err
+ }
+ defer func() {
+ if err != nil {
+ c.RemoveProcess(pid)
+ }
+ }()
+ cmd := exec.Command(c.shim,
+ c.id, c.bundle, c.runtime,
+ )
+ cmd.Dir = processRoot
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ Setpgid: true,
+ }
+ spec, err := c.readSpec()
+ if err != nil {
+ return nil, err
+ }
+ config := &processConfig{
+ exec: true,
+ id: pid,
+ root: processRoot,
+ c: c,
+ processSpec: pspec,
+ spec: spec,
+ stdio: s,
+ }
+ p, err := newProcess(config)
+ if err != nil {
+ return nil, err
+ }
+ if err := c.createCmd(ctx, pid, cmd, p); err != nil {
+ return nil, err
+ }
+ return p, nil
+}
+
+func (c *container) createCmd(ctx context.Context, pid string, cmd *exec.Cmd, p *process) error {
+ p.cmd = cmd
+ if err := cmd.Start(); err != nil {
+ close(p.cmdDoneCh)
+ if exErr, ok := err.(*exec.Error); ok {
+ if exErr.Err == exec.ErrNotFound || exErr.Err == os.ErrNotExist {
+ return fmt.Errorf("%s not installed on system", c.shim)
+ }
+ }
+ return err
+ }
+ // We need the pid file to have been written to run
+ defer func() {
+ go func() {
+ err := p.cmd.Wait()
+ if err == nil {
+ p.cmdSuccess = true
+ }
+
+ if same, err := p.isSameProcess(); same && p.pid > 0 {
+ // The process changed its PR_SET_PDEATHSIG, so force
+ // kill it
+ logrus.Infof("containerd: %s:%s (pid %v) has become an orphan, killing it", p.container.id, p.id, p.pid)
+ err = unix.Kill(p.pid, syscall.SIGKILL)
+ if err != nil && err != syscall.ESRCH {
+ logrus.Errorf("containerd: unable to SIGKILL %s:%s (pid %v): %v", p.container.id, p.id, p.pid, err)
+ } else {
+ for {
+ err = unix.Kill(p.pid, 0)
+ if err != nil {
+ break
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ }
+ }
+ close(p.cmdDoneCh)
+ }()
+ }()
+
+ ch := make(chan error)
+ go func() {
+ if err := c.waitForCreate(p, cmd); err != nil {
+ ch <- err
+ return
+ }
+ c.processes[pid] = p
+ ch <- nil
+ }()
+ select {
+ case <-ctx.Done():
+ cmd.Process.Kill()
+ cmd.Wait()
+ <-ch
+ return ctx.Err()
+ case err := <-ch:
+ return err
+ }
+}
+
+func hostIDFromMap(id uint32, mp []ocs.LinuxIDMapping) int {
+ for _, m := range mp {
+ if (id >= m.ContainerID) && (id <= (m.ContainerID + m.Size - 1)) {
+ return int(m.HostID + (id - m.ContainerID))
+ }
+ }
+ return 0
+}
+
+func (c *container) Stats() (*Stat, error) {
+ now := time.Now()
+ args := c.runtimeArgs
+ args = append(args, "events", "--stats", c.id)
+ out, err := exec.Command(c.runtime, args...).CombinedOutput()
+ if err != nil {
+ return nil, fmt.Errorf("%s: %q", err.Error(), out)
+ }
+ s := struct {
+ Data *Stat `json:"data"`
+ }{}
+ if err := json.Unmarshal(out, &s); err != nil {
+ return nil, err
+ }
+ s.Data.Timestamp = now
+ return s.Data, nil
+}
+
+// Status implements the runtime Container interface.
+func (c *container) Status() (State, error) {
+ args := c.runtimeArgs
+ args = append(args, "state", c.id)
+
+ out, err := exec.Command(c.runtime, args...).CombinedOutput()
+ if err != nil {
+ return "", fmt.Errorf("%s: %q", err.Error(), out)
+ }
+
+ // We only require the runtime json output to have a top level Status field.
+ var s struct {
+ Status State `json:"status"`
+ }
+ if err := json.Unmarshal(out, &s); err != nil {
+ return "", err
+ }
+ return s.Status, nil
+}
+
+func (c *container) writeEventFD(root string, cfd, efd int) error {
+ f, err := os.OpenFile(filepath.Join(root, "cgroup.event_control"), os.O_WRONLY, 0)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ _, err = f.WriteString(fmt.Sprintf("%d %d", efd, cfd))
+ return err
+}
+
+type waitArgs struct {
+ pid int
+ err error
+}
+
+func (c *container) waitForCreate(p *process, cmd *exec.Cmd) error {
+ wc := make(chan error, 1)
+ go func() {
+ for {
+ if _, err := p.getPidFromFile(); err != nil {
+ if os.IsNotExist(err) || err == errInvalidPidInt || err == errContainerNotFound {
+ alive, err := isAlive(cmd)
+ if err != nil {
+ wc <- err
+ return
+ }
+ if !alive {
+ // runc could have failed to run the container so lets get the error
+ // out of the logs or the shim could have encountered an error
+ messages, err := readLogMessages(filepath.Join(p.root, "shim-log.json"))
+ if err != nil {
+ wc <- err
+ return
+ }
+ for _, m := range messages {
+ if m.Level == "error" {
+ wc <- fmt.Errorf("shim error: %v", m.Msg)
+ return
+ }
+ }
+ // no errors reported back from shim, check for runc/runtime errors
+ messages, err = readLogMessages(filepath.Join(p.root, "log.json"))
+ if err != nil {
+ if os.IsNotExist(err) {
+ err = ErrContainerNotStarted
+ }
+ wc <- err
+ return
+ }
+ for _, m := range messages {
+ if m.Level == "error" {
+ wc <- fmt.Errorf("oci runtime error: %v", m.Msg)
+ return
+ }
+ }
+ wc <- ErrContainerNotStarted
+ return
+ }
+ time.Sleep(15 * time.Millisecond)
+ continue
+ }
+ wc <- err
+ return
+ }
+ // the pid file was read successfully
+ wc <- nil
+ return
+ }
+ }()
+ select {
+ case err := <-wc:
+ if err != nil {
+ return err
+ }
+ err = p.saveStartTime()
+ if err != nil && !os.IsNotExist(err) {
+ logrus.Warnf("containerd: unable to save %s:%s starttime: %v", p.container.id, p.id, err)
+ }
+ return nil
+ case <-time.After(c.timeout):
+ cmd.Process.Kill()
+ cmd.Wait()
+ return ErrContainerStartTimeout
+ }
+}
+
+// isAlive checks if the shim that launched the container is still alive
+func isAlive(cmd *exec.Cmd) (bool, error) {
+ if _, err := syscall.Wait4(cmd.Process.Pid, nil, syscall.WNOHANG, nil); err == nil {
+ return true, nil
+ }
+ if err := syscall.Kill(cmd.Process.Pid, 0); err != nil {
+ if err == syscall.ESRCH {
+ return false, nil
+ }
+ return false, err
+ }
+ return true, nil
+}
+
+type oom struct {
+ id string
+ root string
+ eventfd int
+}
+
+func (o *oom) ContainerID() string {
+ return o.id
+}
+
+func (o *oom) FD() int {
+ return o.eventfd
+}
+
+func (o *oom) Flush() {
+ buf := make([]byte, 8)
+ syscall.Read(o.eventfd, buf)
+}
+
+func (o *oom) Removed() bool {
+ _, err := os.Lstat(filepath.Join(o.root, "cgroup.event_control"))
+ return os.IsNotExist(err)
+}
+
+func (o *oom) Close() error {
+ return syscall.Close(o.eventfd)
+}
+
+type message struct {
+ Level string `json:"level"`
+ Msg string `json:"msg"`
+}
+
+func readLogMessages(path string) ([]message, error) {
+ var out []message
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ dec := json.NewDecoder(f)
+ for {
+ var m message
+ if err := dec.Decode(&m); err != nil {
+ if err == io.EOF {
+ break
+ }
+ return nil, err
+ }
+ out = append(out, m)
+ }
+ return out, nil
+}
diff --git a/vendor/github.com/containerd/containerd/runtime/container_linux.go b/vendor/github.com/containerd/containerd/runtime/container_linux.go
new file mode 100644
index 0000000..9f3526a
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/runtime/container_linux.go
@@ -0,0 +1,190 @@
+package runtime
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "syscall"
+
+ "github.com/containerd/containerd/specs"
+ ocs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+func findCgroupMountpointAndRoot(pid int, subsystem string) (string, string, error) {
+ f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid))
+ if err != nil {
+ return "", "", err
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ txt := scanner.Text()
+ fields := strings.Split(txt, " ")
+ for _, opt := range strings.Split(fields[len(fields)-1], ",") {
+ if opt == subsystem {
+ return fields[4], fields[3], nil
+ }
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ return "", "", err
+ }
+
+ return "", "", fmt.Errorf("cgroup path for %s not found", subsystem)
+}
+
+func parseCgroupFile(path string) (map[string]string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ s := bufio.NewScanner(f)
+ cgroups := make(map[string]string)
+
+ for s.Scan() {
+ if err := s.Err(); err != nil {
+ return nil, err
+ }
+
+ text := s.Text()
+ parts := strings.Split(text, ":")
+
+ for _, subs := range strings.Split(parts[1], ",") {
+ cgroups[subs] = parts[2]
+ }
+ }
+ return cgroups, nil
+}
+
+func (c *container) OOM() (OOM, error) {
+ p := c.processes[InitProcessID]
+ if p == nil {
+ return nil, fmt.Errorf("no init process found")
+ }
+
+ mountpoint, hostRoot, err := findCgroupMountpointAndRoot(os.Getpid(), "memory")
+ if err != nil {
+ return nil, err
+ }
+
+ cgroups, err := parseCgroupFile(fmt.Sprintf("/proc/%d/cgroup", p.pid))
+ if err != nil {
+ return nil, err
+ }
+
+ root, ok := cgroups["memory"]
+ if !ok {
+ return nil, fmt.Errorf("no memory cgroup for container %s", c.ID())
+ }
+
+ // Take care of the case were we're running inside a container
+ // ourself
+ root = strings.TrimPrefix(root, hostRoot)
+
+ return c.getMemoryEventFD(filepath.Join(mountpoint, root))
+}
+
+func (c *container) Pids() ([]int, error) {
+ var pids []int
+ args := c.runtimeArgs
+ args = append(args, "ps", "--format=json", c.id)
+ out, err := exec.Command(c.runtime, args...).CombinedOutput()
+ if err != nil {
+ return nil, fmt.Errorf("%s: %q", err.Error(), out)
+ }
+ if err := json.Unmarshal(out, &pids); err != nil {
+ return nil, err
+ }
+ return pids, nil
+}
+
+func u64Ptr(i uint64) *uint64 { return &i }
+func i64Ptr(i int64) *int64 { return &i }
+
+func (c *container) UpdateResources(r *Resource) error {
+ sr := ocs.LinuxResources{
+ Memory: &ocs.LinuxMemory{
+ Limit: u64Ptr(uint64(r.Memory)),
+ Reservation: u64Ptr(uint64(r.MemoryReservation)),
+ Swap: u64Ptr(uint64(r.MemorySwap)),
+ Kernel: u64Ptr(uint64(r.KernelMemory)),
+ KernelTCP: u64Ptr(uint64(r.KernelTCPMemory)),
+ },
+ CPU: &ocs.LinuxCPU{
+ Shares: u64Ptr(uint64(r.CPUShares)),
+ Quota: i64Ptr(int64(r.CPUQuota)),
+ Period: u64Ptr(uint64(r.CPUPeriod)),
+ Cpus: r.CpusetCpus,
+ Mems: r.CpusetMems,
+ },
+ BlockIO: &ocs.LinuxBlockIO{
+ Weight: &r.BlkioWeight,
+ },
+ Pids: &ocs.LinuxPids{
+ Limit: r.PidsLimit,
+ },
+ }
+
+ srStr := bytes.NewBuffer(nil)
+ if err := json.NewEncoder(srStr).Encode(&sr); err != nil {
+ return err
+ }
+
+ args := c.runtimeArgs
+ args = append(args, "update", "-r", "-", c.id)
+ cmd := exec.Command(c.runtime, args...)
+ cmd.Stdin = srStr
+ b, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf(string(b))
+ }
+ return nil
+}
+
+func getRootIDs(s *specs.Spec) (int, int, error) {
+ if s == nil {
+ return 0, 0, nil
+ }
+ var hasUserns bool
+ for _, ns := range s.Linux.Namespaces {
+ if ns.Type == ocs.UserNamespace {
+ hasUserns = true
+ break
+ }
+ }
+ if !hasUserns {
+ return 0, 0, nil
+ }
+ uid := hostIDFromMap(0, s.Linux.UIDMappings)
+ gid := hostIDFromMap(0, s.Linux.GIDMappings)
+ return uid, gid, nil
+}
+
+func (c *container) getMemoryEventFD(root string) (*oom, error) {
+ f, err := os.Open(filepath.Join(root, "memory.oom_control"))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ fd, _, serr := syscall.RawSyscall(syscall.SYS_EVENTFD2, 0, syscall.FD_CLOEXEC, 0)
+ if serr != 0 {
+ return nil, serr
+ }
+ if err := c.writeEventFD(root, int(f.Fd()), int(fd)); err != nil {
+ syscall.Close(int(fd))
+ return nil, err
+ }
+ return &oom{
+ root: root,
+ id: c.id,
+ eventfd: int(fd),
+ }, nil
+}
diff --git a/vendor/github.com/containerd/containerd/runtime/container_solaris.go b/vendor/github.com/containerd/containerd/runtime/container_solaris.go
new file mode 100644
index 0000000..7d9c538
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/runtime/container_solaris.go
@@ -0,0 +1,48 @@
+package runtime
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "os/exec"
+ "strings"
+
+ "github.com/containerd/containerd/specs"
+ ocs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+func getRootIDs(s *specs.Spec) (int, int, error) {
+ return 0, 0, nil
+}
+
+func (c *container) OOM() (OOM, error) {
+ return nil, nil
+}
+
+func (c *container) Pids() ([]int, error) {
+ var pids []int
+
+ // TODO: This could be racy. Needs more investigation.
+ //we get this information from runz state
+ cmd := exec.Command(c.runtime, "state", c.id)
+ outBuf, errBuf := new(bytes.Buffer), new(bytes.Buffer)
+ cmd.Stdout, cmd.Stderr = outBuf, errBuf
+
+ if err := cmd.Run(); err != nil {
+ if strings.Contains(errBuf.String(), "Container not found") {
+ return nil, errContainerNotFound
+ }
+ return nil, fmt.Errorf("Error is: %+v\n", err)
+ }
+ response := ocs.State{}
+ decoder := json.NewDecoder(outBuf)
+ if err := decoder.Decode(&response); err != nil {
+ return nil, fmt.Errorf("unable to decode json response: %+v", err)
+ }
+ pids = append(pids, response.Pid)
+ return pids, nil
+}
+
+func (c *container) UpdateResources(r *Resource) error {
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/runtime/process.go b/vendor/github.com/containerd/containerd/runtime/process.go
new file mode 100644
index 0000000..2df67d9
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/runtime/process.go
@@ -0,0 +1,476 @@
+package runtime
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/containerd/containerd/osutils"
+ "github.com/containerd/containerd/specs"
+ "golang.org/x/sys/unix"
+)
+
+// Process holds the operation allowed on a container's process
+type Process interface {
+ io.Closer
+
+ // ID of the process.
+ // This is either "init" when it is the container's init process or
+ // it is a user provided id for the process similar to the container id
+ ID() string
+ // Start unblocks the associated container init process.
+ // This should only be called on the process with ID "init"
+ Start() error
+ CloseStdin() error
+ Resize(int, int) error
+ // ExitFD returns the fd the provides an event when the process exits
+ ExitFD() int
+ // ExitStatus returns the exit status of the process or an error if it
+ // has not exited
+ ExitStatus() (uint32, error)
+ // Spec returns the process spec that created the process
+ Spec() specs.ProcessSpec
+ // Signal sends the provided signal to the process
+ Signal(os.Signal) error
+ // Container returns the container that the process belongs to
+ Container() Container
+ // Stdio of the container
+ Stdio() Stdio
+ // SystemPid is the pid on the system
+ SystemPid() int
+ // State returns if the process is running or not
+ State() State
+ // Wait reaps the shim process if avaliable
+ Wait()
+}
+
+type processConfig struct {
+ id string
+ root string
+ processSpec specs.ProcessSpec
+ spec *specs.Spec
+ c *container
+ stdio Stdio
+ exec bool
+ checkpoint string
+}
+
+func newProcess(config *processConfig) (*process, error) {
+ p := &process{
+ root: config.root,
+ id: config.id,
+ container: config.c,
+ spec: config.processSpec,
+ stdio: config.stdio,
+ cmdDoneCh: make(chan struct{}),
+ state: Running,
+ }
+ uid, gid, err := getRootIDs(config.spec)
+ if err != nil {
+ return nil, err
+ }
+ f, err := os.Create(filepath.Join(config.root, "process.json"))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ ps := ProcessState{
+ ProcessSpec: config.processSpec,
+ Exec: config.exec,
+ PlatformProcessState: PlatformProcessState{
+ Checkpoint: config.checkpoint,
+ RootUID: uid,
+ RootGID: gid,
+ },
+ Stdin: config.stdio.Stdin,
+ Stdout: config.stdio.Stdout,
+ Stderr: config.stdio.Stderr,
+ RuntimeArgs: config.c.runtimeArgs,
+ NoPivotRoot: config.c.noPivotRoot,
+ }
+
+ if err := json.NewEncoder(f).Encode(ps); err != nil {
+ return nil, err
+ }
+ exit, err := getExitPipe(filepath.Join(config.root, ExitFile))
+ if err != nil {
+ return nil, err
+ }
+ control, err := getControlPipe(filepath.Join(config.root, ControlFile))
+ if err != nil {
+ return nil, err
+ }
+ p.exitPipe = exit
+ p.controlPipe = control
+ return p, nil
+}
+
+func loadProcess(root, id string, c *container, s *ProcessState) (*process, error) {
+ p := &process{
+ root: root,
+ id: id,
+ container: c,
+ spec: s.ProcessSpec,
+ stdio: Stdio{
+ Stdin: s.Stdin,
+ Stdout: s.Stdout,
+ Stderr: s.Stderr,
+ },
+ state: Stopped,
+ }
+
+ startTime, err := ioutil.ReadFile(filepath.Join(p.root, StartTimeFile))
+ if err != nil && !os.IsNotExist(err) {
+ return nil, err
+ }
+ p.startTime = string(startTime)
+
+ if _, err := p.getPidFromFile(); err != nil {
+ return nil, err
+ }
+ if _, err := p.ExitStatus(); err != nil {
+ if err == ErrProcessNotExited {
+ exit, err := getExitPipe(filepath.Join(root, ExitFile))
+ if err != nil {
+ return nil, err
+ }
+ p.exitPipe = exit
+
+ control, err := getControlPipe(filepath.Join(root, ControlFile))
+ if err != nil {
+ return nil, err
+ }
+ p.controlPipe = control
+
+ p.state = Running
+ return p, nil
+ }
+ return nil, err
+ }
+ return p, nil
+}
+
+func readProcStatField(pid int, field int) (string, error) {
+ data, err := ioutil.ReadFile(filepath.Join(string(filepath.Separator), "proc", strconv.Itoa(pid), "stat"))
+ if err != nil {
+ return "", err
+ }
+
+ if field > 2 {
+ // First, split out the name since he could contains spaces.
+ parts := strings.Split(string(data), ") ")
+ // Now split out the rest, we end up with 2 fields less
+ parts = strings.Split(parts[1], " ")
+ return parts[field-2-1], nil // field count start at 1 in manual
+ }
+
+ parts := strings.Split(string(data), " (")
+
+ if field == 1 {
+ return parts[0], nil
+ }
+
+ parts = strings.Split(parts[1], ") ")
+ return parts[0], nil
+}
+
+type process struct {
+ root string
+ id string
+ pid int
+ exitPipe *os.File
+ controlPipe *os.File
+ container *container
+ spec specs.ProcessSpec
+ stdio Stdio
+ cmd *exec.Cmd
+ cmdSuccess bool
+ cmdDoneCh chan struct{}
+ state State
+ stateLock sync.Mutex
+ startTime string
+}
+
+func (p *process) ID() string {
+ return p.id
+}
+
+func (p *process) Container() Container {
+ return p.container
+}
+
+func (p *process) SystemPid() int {
+ return p.pid
+}
+
+// ExitFD returns the fd of the exit pipe
+func (p *process) ExitFD() int {
+ return int(p.exitPipe.Fd())
+}
+
+func (p *process) CloseStdin() error {
+ _, err := fmt.Fprintf(p.controlPipe, "%d %d %d\n", 0, 0, 0)
+ return err
+}
+
+func (p *process) Resize(w, h int) error {
+ _, err := fmt.Fprintf(p.controlPipe, "%d %d %d\n", 1, w, h)
+ return err
+}
+
+func (p *process) updateExitStatusFile(status uint32) (uint32, error) {
+ p.stateLock.Lock()
+ p.state = Stopped
+ p.stateLock.Unlock()
+ err := ioutil.WriteFile(filepath.Join(p.root, ExitStatusFile), []byte(fmt.Sprintf("%d", status)), 0644)
+ return status, err
+}
+
+func (p *process) handleSigkilledShim(rst uint32, rerr error) (uint32, error) {
+ if p.cmd == nil || p.cmd.Process == nil {
+ e := unix.Kill(p.pid, 0)
+ if e == syscall.ESRCH {
+ logrus.Warnf("containerd: %s:%s (pid %d) does not exist", p.container.id, p.id, p.pid)
+ // The process died while containerd was down (probably of
+ // SIGKILL, but no way to be sure)
+ return p.updateExitStatusFile(UnknownStatus)
+ }
+
+ // If it's not the same process, just mark it stopped and set
+ // the status to the UnknownStatus value (i.e. 255)
+ if same, err := p.isSameProcess(); !same {
+ logrus.Warnf("containerd: %s:%s (pid %d) is not the same process anymore (%v)", p.container.id, p.id, p.pid, err)
+ // Create the file so we get the exit event generated once monitor kicks in
+ // without having to go through all this process again
+ return p.updateExitStatusFile(UnknownStatus)
+ }
+
+ ppid, err := readProcStatField(p.pid, 4)
+ if err != nil {
+ return rst, fmt.Errorf("could not check process ppid: %v (%v)", err, rerr)
+ }
+ if ppid == "1" {
+ logrus.Warnf("containerd: %s:%s shim died, killing associated process", p.container.id, p.id)
+ unix.Kill(p.pid, syscall.SIGKILL)
+ if err != nil && err != syscall.ESRCH {
+ return UnknownStatus, fmt.Errorf("containerd: unable to SIGKILL %s:%s (pid %v): %v", p.container.id, p.id, p.pid, err)
+ }
+
+ // wait for the process to die
+ for {
+ e := unix.Kill(p.pid, 0)
+ if e == syscall.ESRCH {
+ break
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ // Create the file so we get the exit event generated once monitor kicks in
+ // without having to go through all this process again
+ return p.updateExitStatusFile(128 + uint32(syscall.SIGKILL))
+ }
+
+ return rst, rerr
+ }
+
+ // Possible that the shim was SIGKILLED
+ e := unix.Kill(p.cmd.Process.Pid, 0)
+ if e != syscall.ESRCH {
+ return rst, rerr
+ }
+
+ // Ensure we got the shim ProcessState
+ <-p.cmdDoneCh
+
+ shimStatus := p.cmd.ProcessState.Sys().(syscall.WaitStatus)
+ if shimStatus.Signaled() && shimStatus.Signal() == syscall.SIGKILL {
+ logrus.Debugf("containerd: ExitStatus(container: %s, process: %s): shim was SIGKILL'ed reaping its child with pid %d", p.container.id, p.id, p.pid)
+
+ rerr = nil
+ rst = 128 + uint32(shimStatus.Signal())
+
+ p.stateLock.Lock()
+ p.state = Stopped
+ p.stateLock.Unlock()
+ }
+
+ return rst, rerr
+}
+
+func (p *process) ExitStatus() (rst uint32, rerr error) {
+ data, err := ioutil.ReadFile(filepath.Join(p.root, ExitStatusFile))
+ defer func() {
+ if rerr != nil {
+ rst, rerr = p.handleSigkilledShim(rst, rerr)
+ }
+ }()
+ if err != nil {
+ if os.IsNotExist(err) {
+ return UnknownStatus, ErrProcessNotExited
+ }
+ return UnknownStatus, err
+ }
+ if len(data) == 0 {
+ return UnknownStatus, ErrProcessNotExited
+ }
+ p.stateLock.Lock()
+ p.state = Stopped
+ p.stateLock.Unlock()
+
+ i, err := strconv.ParseUint(string(data), 10, 32)
+ return uint32(i), err
+}
+
+func (p *process) Spec() specs.ProcessSpec {
+ return p.spec
+}
+
+func (p *process) Stdio() Stdio {
+ return p.stdio
+}
+
+// Close closes any open files and/or resouces on the process
+func (p *process) Close() error {
+ err := p.exitPipe.Close()
+ if cerr := p.controlPipe.Close(); err == nil {
+ err = cerr
+ }
+ return err
+}
+
+func (p *process) State() State {
+ p.stateLock.Lock()
+ defer p.stateLock.Unlock()
+ return p.state
+}
+
+func (p *process) readStartTime() (string, error) {
+ return readProcStatField(p.pid, 22)
+}
+
+func (p *process) saveStartTime() error {
+ startTime, err := p.readStartTime()
+ if err != nil {
+ return err
+ }
+
+ p.startTime = startTime
+ return ioutil.WriteFile(filepath.Join(p.root, StartTimeFile), []byte(startTime), 0644)
+}
+
+func (p *process) isSameProcess() (bool, error) {
+ if p.pid == 0 {
+ _, err := p.getPidFromFile()
+ if err != nil {
+ return false, err
+ }
+ }
+
+ // for backward compat assume it's the same if startTime wasn't set
+ if p.startTime == "" {
+ // Sometimes the process dies before we can get the starttime,
+ // check that the process actually exists
+ if err := unix.Kill(p.pid, 0); err != syscall.ESRCH {
+ return true, nil
+ }
+ return false, nil
+ }
+
+ startTime, err := p.readStartTime()
+ if err != nil {
+ return false, err
+ }
+
+ return startTime == p.startTime, nil
+}
+
+// Wait will reap the shim process
+func (p *process) Wait() {
+ if p.cmdDoneCh != nil {
+ <-p.cmdDoneCh
+ }
+}
+
+func getExitPipe(path string) (*os.File, error) {
+ if err := unix.Mkfifo(path, 0755); err != nil && !os.IsExist(err) {
+ return nil, err
+ }
+ // add NONBLOCK in case the other side has already closed or else
+ // this function would never return
+ return os.OpenFile(path, syscall.O_RDONLY|syscall.O_NONBLOCK, 0)
+}
+
+func getControlPipe(path string) (*os.File, error) {
+ if err := unix.Mkfifo(path, 0755); err != nil && !os.IsExist(err) {
+ return nil, err
+ }
+ return os.OpenFile(path, syscall.O_RDWR|syscall.O_NONBLOCK, 0)
+}
+
+// Signal sends the provided signal to the process
+func (p *process) Signal(s os.Signal) error {
+ return syscall.Kill(p.pid, s.(syscall.Signal))
+}
+
+// Start unblocks the associated container init process.
+// This should only be called on the process with ID "init"
+func (p *process) Start() error {
+ if p.ID() == InitProcessID {
+ var (
+ errC = make(chan error, 1)
+ args = append(p.container.runtimeArgs, "start", p.container.id)
+ cmd = exec.Command(p.container.runtime, args...)
+ )
+ go func() {
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ errC <- fmt.Errorf("%s: %q", err.Error(), out)
+ }
+ errC <- nil
+ }()
+ select {
+ case err := <-errC:
+ if err != nil {
+ return err
+ }
+ case <-p.cmdDoneCh:
+ if !p.cmdSuccess {
+ if cmd.Process != nil {
+ cmd.Process.Kill()
+ }
+ cmd.Wait()
+ return ErrShimExited
+ }
+ err := <-errC
+ if err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// Delete delete any resources held by the container
+func (p *process) Delete() error {
+ var (
+ args = append(p.container.runtimeArgs, "delete", "-f", p.container.id)
+ cmd = exec.Command(p.container.runtime, args...)
+ )
+
+ cmd.SysProcAttr = osutils.SetPDeathSig()
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s: %v", out, err)
+ }
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/runtime/process_linux.go b/vendor/github.com/containerd/containerd/runtime/process_linux.go
new file mode 100644
index 0000000..d14c4d8
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/runtime/process_linux.go
@@ -0,0 +1,22 @@
+// +build linux
+
+package runtime
+
+import (
+ "io/ioutil"
+ "path/filepath"
+ "strconv"
+)
+
+func (p *process) getPidFromFile() (int, error) {
+ data, err := ioutil.ReadFile(filepath.Join(p.root, "pid"))
+ if err != nil {
+ return -1, err
+ }
+ i, err := strconv.Atoi(string(data))
+ if err != nil {
+ return -1, errInvalidPidInt
+ }
+ p.pid = i
+ return i, nil
+}
diff --git a/vendor/github.com/containerd/containerd/runtime/process_solaris.go b/vendor/github.com/containerd/containerd/runtime/process_solaris.go
new file mode 100644
index 0000000..8159f30
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/runtime/process_solaris.go
@@ -0,0 +1,34 @@
+// +build solaris
+
+package runtime
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "os/exec"
+
+ runtimespec "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+// On Solaris we already have a state file maintained by the framework.
+// This is read by runz state. We just call that instead of maintaining
+// a separate file.
+func (p *process) getPidFromFile() (int, error) {
+ //we get this information from runz state
+ cmd := exec.Command("runc", "state", p.container.ID())
+ outBuf, errBuf := new(bytes.Buffer), new(bytes.Buffer)
+ cmd.Stdout, cmd.Stderr = outBuf, errBuf
+
+ if err := cmd.Run(); err != nil {
+ // TODO: Improve logic
+ return -1, errContainerNotFound
+ }
+ response := runtimespec.State{}
+ decoder := json.NewDecoder(outBuf)
+ if err := decoder.Decode(&response); err != nil {
+ return -1, fmt.Errorf("unable to decode json response: %+v", err)
+ }
+ p.pid = response.Pid
+ return p.pid, nil
+}
diff --git a/vendor/github.com/containerd/containerd/runtime/runtime.go b/vendor/github.com/containerd/containerd/runtime/runtime.go
new file mode 100644
index 0000000..eaba452
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/runtime/runtime.go
@@ -0,0 +1,132 @@
+package runtime
+
+import (
+ "errors"
+ "time"
+
+ "github.com/containerd/containerd/specs"
+)
+
+var (
+ // ErrContainerExited is returned when access to an exited
+ // container is attempted
+ ErrContainerExited = errors.New("containerd: container has exited")
+ // ErrProcessNotExited is returned when trying to retrieve the exit
+ // status of an alive process
+ ErrProcessNotExited = errors.New("containerd: process has not exited")
+ // ErrContainerNotStarted is returned when a container fails to
+ // start without error from the shim or the OCI runtime
+ ErrContainerNotStarted = errors.New("containerd: container not started")
+ // ErrContainerStartTimeout is returned if a container takes too
+ // long to start
+ ErrContainerStartTimeout = errors.New("containerd: container did not start before the specified timeout")
+ // ErrShimExited is returned if the shim or the contianer's init process
+ // exits before completing
+ ErrShimExited = errors.New("containerd: shim exited before container process was started")
+
+ errNoPidFile = errors.New("containerd: no process pid file found")
+ errInvalidPidInt = errors.New("containerd: process pid is invalid")
+ errContainerNotFound = errors.New("containerd: container not found")
+ errNotImplemented = errors.New("containerd: not implemented")
+)
+
+const (
+ // ExitFile holds the name of the pipe used to monitor process
+ // exit
+ ExitFile = "exit"
+ // ExitStatusFile holds the name of the file where the container
+ // exit code is to be written
+ ExitStatusFile = "exitStatus"
+ // StateFile holds the name of the file where the container state
+ // is written
+ StateFile = "state.json"
+ // ControlFile holds the name of the pipe used to control the shim
+ ControlFile = "control"
+ // InitProcessID holds the special ID used for the very first
+ // container's process
+ InitProcessID = "init"
+ // StartTimeFile holds the name of the file in which the process
+ // start time is saved
+ StartTimeFile = "starttime"
+
+ // UnknownStatus is the value returned when a process exit
+ // status cannot be determined
+ UnknownStatus = 255
+)
+
+// Checkpoint holds information regarding a container checkpoint
+type Checkpoint struct {
+ // Timestamp is the time that checkpoint happened
+ Created time.Time `json:"created"`
+ // Name is the name of the checkpoint
+ Name string `json:"name"`
+ // TCP checkpoints open tcp connections
+ TCP bool `json:"tcp"`
+ // UnixSockets persists unix sockets in the checkpoint
+ UnixSockets bool `json:"unixSockets"`
+ // Shell persists tty sessions in the checkpoint
+ Shell bool `json:"shell"`
+ // Exit exits the container after the checkpoint is finished
+ Exit bool `json:"exit"`
+ // EmptyNS tells CRIU to omit a specified namespace
+ EmptyNS []string `json:"emptyNS,omitempty"`
+}
+
+// PlatformProcessState container platform-specific fields in the ProcessState structure
+type PlatformProcessState struct {
+ Checkpoint string `json:"checkpoint"`
+ RootUID int `json:"rootUID"`
+ RootGID int `json:"rootGID"`
+}
+
+// State represents a container state
+type State string
+
+// Resource regroups the various container limits that can be updated
+type Resource struct {
+ CPUShares int64
+ BlkioWeight uint16
+ CPUPeriod int64
+ CPUQuota int64
+ CpusetCpus string
+ CpusetMems string
+ KernelMemory int64
+ KernelTCPMemory int64
+ Memory int64
+ MemoryReservation int64
+ MemorySwap int64
+ PidsLimit int64
+}
+
+// Possible container states
+const (
+ Paused = State("paused")
+ Stopped = State("stopped")
+ Running = State("running")
+)
+
+type state struct {
+ Bundle string `json:"bundle"`
+ Labels []string `json:"labels"`
+ Stdin string `json:"stdin"`
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ Runtime string `json:"runtime"`
+ RuntimeArgs []string `json:"runtimeArgs"`
+ Shim string `json:"shim"`
+ NoPivotRoot bool `json:"noPivotRoot"`
+}
+
+// ProcessState holds the process OCI specs along with various fields
+// required by containerd
+type ProcessState struct {
+ specs.ProcessSpec
+ Exec bool `json:"exec"`
+ Stdin string `json:"containerdStdin"`
+ Stdout string `json:"containerdStdout"`
+ Stderr string `json:"containerdStderr"`
+ RuntimeArgs []string `json:"runtimeArgs"`
+ NoPivotRoot bool `json:"noPivotRoot"`
+
+ PlatformProcessState
+}
diff --git a/vendor/github.com/containerd/containerd/runtime/stats.go b/vendor/github.com/containerd/containerd/runtime/stats.go
new file mode 100644
index 0000000..4cfa9e9
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/runtime/stats.go
@@ -0,0 +1,87 @@
+package runtime
+
+import "time"
+
+// Stat holds a container statistics
+type Stat struct {
+ // Timestamp is the time that the statistics where collected
+ Timestamp time.Time
+ CPU CPU `json:"cpu"`
+ Memory Memory `json:"memory"`
+ Pids Pids `json:"pids"`
+ Blkio Blkio `json:"blkio"`
+ Hugetlb map[string]Hugetlb `json:"hugetlb"`
+}
+
+// Hugetlb holds information regarding a container huge tlb usage
+type Hugetlb struct {
+ Usage uint64 `json:"usage,omitempty"`
+ Max uint64 `json:"max,omitempty"`
+ Failcnt uint64 `json:"failcnt"`
+}
+
+// BlkioEntry represents a single record for a Blkio stat
+type BlkioEntry struct {
+ Major uint64 `json:"major,omitempty"`
+ Minor uint64 `json:"minor,omitempty"`
+ Op string `json:"op,omitempty"`
+ Value uint64 `json:"value,omitempty"`
+}
+
+// Blkio regroups all the Blkio related stats
+type Blkio struct {
+ IoServiceBytesRecursive []BlkioEntry `json:"ioServiceBytesRecursive,omitempty"`
+ IoServicedRecursive []BlkioEntry `json:"ioServicedRecursive,omitempty"`
+ IoQueuedRecursive []BlkioEntry `json:"ioQueueRecursive,omitempty"`
+ IoServiceTimeRecursive []BlkioEntry `json:"ioServiceTimeRecursive,omitempty"`
+ IoWaitTimeRecursive []BlkioEntry `json:"ioWaitTimeRecursive,omitempty"`
+ IoMergedRecursive []BlkioEntry `json:"ioMergedRecursive,omitempty"`
+ IoTimeRecursive []BlkioEntry `json:"ioTimeRecursive,omitempty"`
+ SectorsRecursive []BlkioEntry `json:"sectorsRecursive,omitempty"`
+}
+
+// Pids holds the stat of the pid usage of the machine
+type Pids struct {
+ Current uint64 `json:"current,omitempty"`
+ Limit uint64 `json:"limit,omitempty"`
+}
+
+// Throttling holds a cpu throttling information
+type Throttling struct {
+ Periods uint64 `json:"periods,omitempty"`
+ ThrottledPeriods uint64 `json:"throttledPeriods,omitempty"`
+ ThrottledTime uint64 `json:"throttledTime,omitempty"`
+}
+
+// CPUUsage holds information regarding cpu usage
+type CPUUsage struct {
+ // Units: nanoseconds.
+ Total uint64 `json:"total,omitempty"`
+ Percpu []uint64 `json:"percpu,omitempty"`
+ Kernel uint64 `json:"kernel"`
+ User uint64 `json:"user"`
+}
+
+// CPU regroups both a CPU usage and throttling information
+type CPU struct {
+ Usage CPUUsage `json:"usage,omitempty"`
+ Throttling Throttling `json:"throttling,omitempty"`
+}
+
+// MemoryEntry regroups statistic about a given type of memory
+type MemoryEntry struct {
+ Limit uint64 `json:"limit"`
+ Usage uint64 `json:"usage,omitempty"`
+ Max uint64 `json:"max,omitempty"`
+ Failcnt uint64 `json:"failcnt"`
+}
+
+// Memory holds information regarding the different type of memories available
+type Memory struct {
+ Cache uint64 `json:"cache,omitempty"`
+ Usage MemoryEntry `json:"usage,omitempty"`
+ Swap MemoryEntry `json:"swap,omitempty"`
+ Kernel MemoryEntry `json:"kernel,omitempty"`
+ KernelTCP MemoryEntry `json:"kernelTCP,omitempty"`
+ Raw map[string]uint64 `json:"raw,omitempty"`
+}
diff --git a/vendor/github.com/containerd/containerd/specs/spec_linux.go b/vendor/github.com/containerd/containerd/specs/spec_linux.go
new file mode 100644
index 0000000..0b31604
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/specs/spec_linux.go
@@ -0,0 +1,12 @@
+package specs
+
+import oci "github.com/opencontainers/runtime-spec/specs-go"
+
+type (
+ // ProcessSpec aliases the platform process specs
+ ProcessSpec oci.Process
+ // Spec aliases the platform oci spec
+ Spec oci.Spec
+ // Rlimit aliases the platform resource limit
+ Rlimit oci.LinuxRlimit
+)
diff --git a/vendor/github.com/containerd/containerd/specs/spec_solaris.go b/vendor/github.com/containerd/containerd/specs/spec_solaris.go
new file mode 100644
index 0000000..1b60d3d
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/specs/spec_solaris.go
@@ -0,0 +1,10 @@
+package specs
+
+import ocs "github.com/opencontainers/runtime-spec/specs-go"
+
+type (
+ // ProcessSpec aliases the platform process specs
+ ProcessSpec ocs.Process
+ // Spec aliases the platform oci spec
+ Spec ocs.Spec
+)
diff --git a/vendor/github.com/containerd/containerd/supervisor/add_process.go b/vendor/github.com/containerd/containerd/supervisor/add_process.go
new file mode 100644
index 0000000..6c56b82
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/add_process.go
@@ -0,0 +1,53 @@
+package supervisor
+
+import (
+ "os"
+ "time"
+
+ "github.com/containerd/containerd/runtime"
+ "github.com/containerd/containerd/specs"
+ "golang.org/x/net/context"
+)
+
+// AddProcessTask holds everything necessary to add a process to a
+// container
+type AddProcessTask struct {
+ baseTask
+ ID string
+ PID string
+ Stdout string
+ Stderr string
+ Stdin string
+ ProcessSpec *specs.ProcessSpec
+ StartResponse chan StartResponse
+ Ctx context.Context
+}
+
+func (s *Supervisor) addProcess(t *AddProcessTask) error {
+ start := time.Now()
+ ci, ok := s.containers[t.ID]
+ if !ok {
+ return ErrContainerNotFound
+ }
+ process, err := ci.container.Exec(t.Ctx, t.PID, *t.ProcessSpec, runtime.NewStdio(t.Stdin, t.Stdout, t.Stderr))
+ if err != nil {
+ return err
+ }
+ s.newExecSyncChannel(t.ID, t.PID)
+ if err := s.monitorProcess(process); err != nil {
+ s.deleteExecSyncChannel(t.ID, t.PID)
+ // Kill process
+ process.Signal(os.Kill)
+ ci.container.RemoveProcess(t.PID)
+ return err
+ }
+ ExecProcessTimer.UpdateSince(start)
+ t.StartResponse <- StartResponse{ExecPid: process.SystemPid()}
+ s.notifySubscribers(Event{
+ Timestamp: time.Now(),
+ Type: StateStartProcess,
+ PID: t.PID,
+ ID: t.ID,
+ })
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/checkpoint.go b/vendor/github.com/containerd/containerd/supervisor/checkpoint.go
new file mode 100644
index 0000000..ce05aea
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/checkpoint.go
@@ -0,0 +1,37 @@
+// +build !windows
+
+package supervisor
+
+import "github.com/containerd/containerd/runtime"
+
+// CreateCheckpointTask holds needed parameters to create a new checkpoint
+type CreateCheckpointTask struct {
+ baseTask
+ ID string
+ CheckpointDir string
+ Checkpoint *runtime.Checkpoint
+}
+
+func (s *Supervisor) createCheckpoint(t *CreateCheckpointTask) error {
+ i, ok := s.containers[t.ID]
+ if !ok {
+ return ErrContainerNotFound
+ }
+ return i.container.Checkpoint(*t.Checkpoint, t.CheckpointDir)
+}
+
+// DeleteCheckpointTask holds needed parameters to delete a checkpoint
+type DeleteCheckpointTask struct {
+ baseTask
+ ID string
+ CheckpointDir string
+ Checkpoint *runtime.Checkpoint
+}
+
+func (s *Supervisor) deleteCheckpoint(t *DeleteCheckpointTask) error {
+ i, ok := s.containers[t.ID]
+ if !ok {
+ return ErrContainerNotFound
+ }
+ return i.container.DeleteCheckpoint(t.Checkpoint.Name, t.CheckpointDir)
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/create.go b/vendor/github.com/containerd/containerd/supervisor/create.go
new file mode 100644
index 0000000..3e782c6
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/create.go
@@ -0,0 +1,71 @@
+package supervisor
+
+import (
+ "path/filepath"
+ "time"
+
+ "github.com/containerd/containerd/runtime"
+ "golang.org/x/net/context"
+)
+
+// StartTask holds needed parameters to create a new container
+type StartTask struct {
+ baseTask
+ ID string
+ BundlePath string
+ Stdout string
+ Stderr string
+ Stdin string
+ StartResponse chan StartResponse
+ Labels []string
+ NoPivotRoot bool
+ Checkpoint *runtime.Checkpoint
+ CheckpointDir string
+ Runtime string
+ RuntimeArgs []string
+ Ctx context.Context
+}
+
+func (s *Supervisor) start(t *StartTask) error {
+ start := time.Now()
+ rt := s.runtime
+ rtArgs := s.runtimeArgs
+ if t.Runtime != "" {
+ rt = t.Runtime
+ rtArgs = t.RuntimeArgs
+ }
+ container, err := runtime.New(runtime.ContainerOpts{
+ Root: s.stateDir,
+ ID: t.ID,
+ Bundle: t.BundlePath,
+ Runtime: rt,
+ RuntimeArgs: rtArgs,
+ Shim: s.shim,
+ Labels: t.Labels,
+ NoPivotRoot: t.NoPivotRoot,
+ Timeout: s.timeout,
+ })
+ if err != nil {
+ return err
+ }
+ s.containers[t.ID] = &containerInfo{
+ container: container,
+ }
+ ContainersCounter.Inc(1)
+ task := &startTask{
+ Err: t.ErrorCh(),
+ Container: container,
+ StartResponse: t.StartResponse,
+ Stdin: t.Stdin,
+ Stdout: t.Stdout,
+ Stderr: t.Stderr,
+ Ctx: t.Ctx,
+ }
+ if t.Checkpoint != nil {
+ task.CheckpointPath = filepath.Join(t.CheckpointDir, t.Checkpoint.Name)
+ }
+
+ s.startTasks <- task
+ ContainerCreateTimer.UpdateSince(start)
+ return errDeferredResponse
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/create_solaris.go b/vendor/github.com/containerd/containerd/supervisor/create_solaris.go
new file mode 100644
index 0000000..444e55b
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/create_solaris.go
@@ -0,0 +1,8 @@
+package supervisor
+
+type platformStartTask struct {
+}
+
+// Checkpoint not supported on Solaris
+func (task *startTask) setTaskCheckpoint(t *StartTask) {
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/delete.go b/vendor/github.com/containerd/containerd/supervisor/delete.go
new file mode 100644
index 0000000..3f5f6d8
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/delete.go
@@ -0,0 +1,56 @@
+package supervisor
+
+import (
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/containerd/containerd/runtime"
+)
+
+// DeleteTask holds needed parameters to remove a container
+type DeleteTask struct {
+ baseTask
+ ID string
+ Status uint32
+ PID string
+ NoEvent bool
+ Process runtime.Process
+}
+
+func (s *Supervisor) delete(t *DeleteTask) error {
+ if i, ok := s.containers[t.ID]; ok {
+ start := time.Now()
+ if err := s.deleteContainer(i.container); err != nil {
+ logrus.WithField("error", err).Error("containerd: deleting container")
+ }
+ if t.Process != nil {
+ t.Process.Wait()
+ }
+ if !t.NoEvent {
+ execMap := s.getExecSyncMap(t.ID)
+ go func() {
+ // Wait for all exec processe events to be sent (we seem
+ // to sometimes receive them after the init event)
+ for _, ch := range execMap {
+ <-ch
+ }
+ s.deleteExecSyncMap(t.ID)
+ s.notifySubscribers(Event{
+ Type: StateExit,
+ Timestamp: time.Now(),
+ ID: t.ID,
+ Status: t.Status,
+ PID: t.PID,
+ })
+ }()
+ }
+ ContainersCounter.Dec(1)
+ ContainerDeleteTimer.UpdateSince(start)
+ }
+ return nil
+}
+
+func (s *Supervisor) deleteContainer(container runtime.Container) error {
+ delete(s.containers, container.ID())
+ return container.Delete()
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/errors.go b/vendor/github.com/containerd/containerd/supervisor/errors.go
new file mode 100644
index 0000000..930807d
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/errors.go
@@ -0,0 +1,28 @@
+package supervisor
+
+import "errors"
+
+var (
+ // ErrContainerNotFound is returned when the container ID passed
+ // for a given operation is invalid
+ ErrContainerNotFound = errors.New("containerd: container not found")
+ // ErrProcessNotFound is returned when the process ID passed for
+ // a given operation is invalid
+ ErrProcessNotFound = errors.New("containerd: process not found for container")
+ // ErrUnknownContainerStatus is returned when the container status
+ // cannot be determined
+ ErrUnknownContainerStatus = errors.New("containerd: unknown container status ")
+ // ErrUnknownTask is returned when an unknown Task type is
+ // scheduled (should never happen).
+ ErrUnknownTask = errors.New("containerd: unknown task type")
+
+ // Internal errors
+ errShutdown = errors.New("containerd: supervisor is shutdown")
+ errRootNotAbs = errors.New("containerd: rootfs path is not an absolute path")
+ errNoContainerForPid = errors.New("containerd: pid not registered for any container")
+ // internal error where the handler will defer to another for the final response
+ //
+ // TODO: we could probably do a typed error with another error channel for this to make it
+ // less like magic
+ errDeferredResponse = errors.New("containerd: deferred response")
+)
diff --git a/vendor/github.com/containerd/containerd/supervisor/exit.go b/vendor/github.com/containerd/containerd/supervisor/exit.go
new file mode 100644
index 0000000..9977c18
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/exit.go
@@ -0,0 +1,93 @@
+package supervisor
+
+import (
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/containerd/containerd/runtime"
+)
+
+// ExitTask holds needed parameters to execute the exit task
+type ExitTask struct {
+ baseTask
+ Process runtime.Process
+}
+
+func (s *Supervisor) exit(t *ExitTask) error {
+ start := time.Now()
+ proc := t.Process
+ status, err := proc.ExitStatus()
+ if err != nil {
+ logrus.WithFields(logrus.Fields{
+ "error": err,
+ "pid": proc.ID(),
+ "id": proc.Container().ID(),
+ "systemPid": proc.SystemPid(),
+ }).Error("containerd: get exit status")
+ }
+ logrus.WithFields(logrus.Fields{
+ "pid": proc.ID(),
+ "status": status,
+ "id": proc.Container().ID(),
+ "systemPid": proc.SystemPid(),
+ }).Debug("containerd: process exited")
+
+ // if the process is the the init process of the container then
+ // fire a separate event for this process
+ if proc.ID() != runtime.InitProcessID {
+ ne := &ExecExitTask{
+ ID: proc.Container().ID(),
+ PID: proc.ID(),
+ Status: status,
+ Process: proc,
+ }
+ s.execExit(ne)
+ return nil
+ }
+ container := proc.Container()
+ ne := &DeleteTask{
+ ID: container.ID(),
+ Status: status,
+ PID: proc.ID(),
+ Process: proc,
+ }
+ s.delete(ne)
+
+ ExitProcessTimer.UpdateSince(start)
+
+ return nil
+}
+
+// ExecExitTask holds needed parameters to execute the exec exit task
+type ExecExitTask struct {
+ baseTask
+ ID string
+ PID string
+ Status uint32
+ Process runtime.Process
+}
+
+func (s *Supervisor) execExit(t *ExecExitTask) error {
+ container := t.Process.Container()
+ // exec process: we remove this process without notifying the main event loop
+ if err := container.RemoveProcess(t.PID); err != nil {
+ logrus.WithField("error", err).Error("containerd: find container for pid")
+ }
+ synCh := s.getExecSyncChannel(t.ID, t.PID)
+ // If the exec spawned children which are still using its IO
+ // waiting here will block until they die or close their IO
+ // descriptors.
+ // Hence, we use a go routine to avoid blocking all other operations
+ go func() {
+ t.Process.Wait()
+ s.notifySubscribers(Event{
+ Timestamp: time.Now(),
+ ID: t.ID,
+ Type: StateExit,
+ PID: t.PID,
+ Status: t.Status,
+ })
+ close(synCh)
+ }()
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/get_containers.go b/vendor/github.com/containerd/containerd/supervisor/get_containers.go
new file mode 100644
index 0000000..528c02f
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/get_containers.go
@@ -0,0 +1,47 @@
+package supervisor
+
+import "github.com/containerd/containerd/runtime"
+
+// GetContainersTask holds needed parameters to retrieve a list of
+// containers
+type GetContainersTask struct {
+ baseTask
+ ID string
+ GetState func(c runtime.Container) (interface{}, error)
+
+ Containers []runtime.Container
+ States []interface{}
+}
+
+func (s *Supervisor) getContainers(t *GetContainersTask) error {
+
+ if t.ID != "" {
+ ci, ok := s.containers[t.ID]
+ if !ok {
+ return ErrContainerNotFound
+ }
+ t.Containers = append(t.Containers, ci.container)
+ if t.GetState != nil {
+ st, err := t.GetState(ci.container)
+ if err != nil {
+ return err
+ }
+ t.States = append(t.States, st)
+ }
+
+ return nil
+ }
+
+ for _, ci := range s.containers {
+ t.Containers = append(t.Containers, ci.container)
+ if t.GetState != nil {
+ st, err := t.GetState(ci.container)
+ if err != nil {
+ return err
+ }
+ t.States = append(t.States, st)
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/machine.go b/vendor/github.com/containerd/containerd/supervisor/machine.go
new file mode 100644
index 0000000..387c73a
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/machine.go
@@ -0,0 +1,28 @@
+// +build !solaris
+
+package supervisor
+
+import "github.com/cloudfoundry/gosigar"
+
+// Machine holds the current machine cpu count and ram size
+type Machine struct {
+ Cpus int
+ Memory int64
+}
+
+// CollectMachineInformation returns information regarding the current
+// machine (e.g. CPU count, RAM amount)
+func CollectMachineInformation() (Machine, error) {
+ m := Machine{}
+ cpu := sigar.CpuList{}
+ if err := cpu.Get(); err != nil {
+ return m, err
+ }
+ m.Cpus = len(cpu.List)
+ mem := sigar.Mem{}
+ if err := mem.Get(); err != nil {
+ return m, err
+ }
+ m.Memory = int64(mem.Total / 1024 / 1024)
+ return m, nil
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/machine_solaris.go b/vendor/github.com/containerd/containerd/supervisor/machine_solaris.go
new file mode 100644
index 0000000..3320394
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/machine_solaris.go
@@ -0,0 +1,41 @@
+package supervisor
+
+/*
+#include <unistd.h>
+*/
+import "C"
+
+import (
+ "errors"
+)
+
+// Machine holds the current machine cpu count and ram size
+type Machine struct {
+ Cpus int
+ Memory int64
+}
+
+// CollectMachineInformation returns information regarding the current
+// machine (e.g. CPU count, RAM amount)
+func CollectMachineInformation() (Machine, error) {
+ m := Machine{}
+ ncpus := C.sysconf(C._SC_NPROCESSORS_ONLN)
+ if ncpus <= 0 {
+ return m, errors.New("Unable to get number of cpus")
+ }
+ m.Cpus = int(ncpus)
+
+ memTotal := getTotalMem()
+ if memTotal < 0 {
+ return m, errors.New("Unable to get total memory")
+ }
+ m.Memory = int64(memTotal / 1024 / 1024)
+ return m, nil
+}
+
+// Get the system memory info using sysconf same as prtconf
+func getTotalMem() int64 {
+ pagesize := C.sysconf(C._SC_PAGESIZE)
+ npages := C.sysconf(C._SC_PHYS_PAGES)
+ return int64(pagesize * npages)
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/metrics.go b/vendor/github.com/containerd/containerd/supervisor/metrics.go
new file mode 100644
index 0000000..e49170d
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/metrics.go
@@ -0,0 +1,42 @@
+package supervisor
+
+import "github.com/rcrowley/go-metrics"
+
+var (
+ // ContainerCreateTimer holds the metrics timer associated with container creation
+ ContainerCreateTimer = metrics.NewTimer()
+ // ContainerDeleteTimer holds the metrics timer associated with container deletion
+ ContainerDeleteTimer = metrics.NewTimer()
+ // ContainerStartTimer holds the metrics timer associated with container start duration
+ ContainerStartTimer = metrics.NewTimer()
+ // ContainerStatsTimer holds the metrics timer associated with container stats generation
+ ContainerStatsTimer = metrics.NewTimer()
+ // ContainersCounter keeps track of the number of active containers
+ ContainersCounter = metrics.NewCounter()
+ // EventSubscriberCounter keeps track of the number of active event subscribers
+ EventSubscriberCounter = metrics.NewCounter()
+ // TasksCounter keeps track of the number of active supervisor tasks
+ TasksCounter = metrics.NewCounter()
+ // ExecProcessTimer holds the metrics timer associated with container exec
+ ExecProcessTimer = metrics.NewTimer()
+ // ExitProcessTimer holds the metrics timer associated with reporting container exit status
+ ExitProcessTimer = metrics.NewTimer()
+ // EpollFdCounter keeps trac of how many process are being monitored
+ EpollFdCounter = metrics.NewCounter()
+)
+
+// Metrics return the list of all available metrics
+func Metrics() map[string]interface{} {
+ return map[string]interface{}{
+ "container-create-time": ContainerCreateTimer,
+ "container-delete-time": ContainerDeleteTimer,
+ "container-start-time": ContainerStartTimer,
+ "container-stats-time": ContainerStatsTimer,
+ "containers": ContainersCounter,
+ "event-subscribers": EventSubscriberCounter,
+ "tasks": TasksCounter,
+ "exec-process-time": ExecProcessTimer,
+ "exit-process-time": ExitProcessTimer,
+ "epoll-fds": EpollFdCounter,
+ }
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/monitor_linux.go b/vendor/github.com/containerd/containerd/supervisor/monitor_linux.go
new file mode 100644
index 0000000..b643b88
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/monitor_linux.go
@@ -0,0 +1,147 @@
+package supervisor
+
+import (
+ "sync"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/containerd/containerd/archutils"
+ "github.com/containerd/containerd/runtime"
+)
+
+// NewMonitor starts a new process monitor and returns it
+func NewMonitor() (*Monitor, error) {
+ m := &Monitor{
+ receivers: make(map[int]interface{}),
+ exits: make(chan runtime.Process, 1024),
+ ooms: make(chan string, 1024),
+ }
+ fd, err := archutils.EpollCreate1(syscall.EPOLL_CLOEXEC)
+ if err != nil {
+ return nil, err
+ }
+ m.epollFd = fd
+ go m.start()
+ return m, nil
+}
+
+// Monitor represents a runtime.Process monitor
+type Monitor struct {
+ m sync.Mutex
+ receivers map[int]interface{}
+ exits chan runtime.Process
+ ooms chan string
+ epollFd int
+}
+
+// Exits returns the channel used to notify of a process exit
+func (m *Monitor) Exits() chan runtime.Process {
+ return m.exits
+}
+
+// OOMs returns the channel used to notify of a container exit due to OOM
+func (m *Monitor) OOMs() chan string {
+ return m.ooms
+}
+
+// Monitor adds a process to the list of the one being monitored
+func (m *Monitor) Monitor(p runtime.Process) error {
+ m.m.Lock()
+ defer m.m.Unlock()
+ fd := p.ExitFD()
+ event := syscall.EpollEvent{
+ Fd: int32(fd),
+ Events: syscall.EPOLLHUP,
+ }
+ if err := archutils.EpollCtl(m.epollFd, syscall.EPOLL_CTL_ADD, fd, &event); err != nil {
+ return err
+ }
+ EpollFdCounter.Inc(1)
+ m.receivers[fd] = p
+ return nil
+}
+
+// MonitorOOM adds a container to the list of the ones monitored for OOM
+func (m *Monitor) MonitorOOM(c runtime.Container) error {
+ m.m.Lock()
+ defer m.m.Unlock()
+ o, err := c.OOM()
+ if err != nil {
+ return err
+ }
+ fd := o.FD()
+ event := syscall.EpollEvent{
+ Fd: int32(fd),
+ Events: syscall.EPOLLHUP | syscall.EPOLLIN,
+ }
+ if err := archutils.EpollCtl(m.epollFd, syscall.EPOLL_CTL_ADD, fd, &event); err != nil {
+ return err
+ }
+ EpollFdCounter.Inc(1)
+ m.receivers[fd] = o
+ return nil
+}
+
+// Close cleans up resources allocated by NewMonitor()
+func (m *Monitor) Close() error {
+ return syscall.Close(m.epollFd)
+}
+
+func (m *Monitor) processEvent(fd int, event uint32) {
+ m.m.Lock()
+ r := m.receivers[fd]
+ switch t := r.(type) {
+ case runtime.Process:
+ if event == syscall.EPOLLHUP {
+ delete(m.receivers, fd)
+ if err := syscall.EpollCtl(m.epollFd, syscall.EPOLL_CTL_DEL, fd, &syscall.EpollEvent{
+ Events: syscall.EPOLLHUP,
+ Fd: int32(fd),
+ }); err != nil {
+ logrus.WithField("error", err).Error("containerd: epoll remove fd")
+ }
+ if err := t.Close(); err != nil {
+ logrus.WithField("error", err).Error("containerd: close process IO")
+ }
+ EpollFdCounter.Dec(1)
+ // defer until lock is released
+ defer func() {
+ m.exits <- t
+ }()
+ }
+ case runtime.OOM:
+ // always flush the event fd
+ t.Flush()
+ if t.Removed() {
+ delete(m.receivers, fd)
+ // epoll will remove the fd from its set after it has been closed
+ t.Close()
+ EpollFdCounter.Dec(1)
+ } else {
+ // defer until lock is released
+ defer func() {
+ m.ooms <- t.ContainerID()
+ }()
+ }
+ }
+ // This cannot be a defer to avoid a deadlock in case the channels
+ // above get full
+ m.m.Unlock()
+}
+
+func (m *Monitor) start() {
+ var events [128]syscall.EpollEvent
+ for {
+ n, err := archutils.EpollWait(m.epollFd, events[:], -1)
+ if err != nil {
+ if err == syscall.EINTR {
+ continue
+ }
+ logrus.WithField("error", err).Fatal("containerd: epoll wait")
+ }
+ // process events
+ for i := 0; i < n; i++ {
+ m.processEvent(int(events[i].Fd), events[i].Events)
+ }
+ }
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/monitor_solaris.go b/vendor/github.com/containerd/containerd/supervisor/monitor_solaris.go
new file mode 100644
index 0000000..5b6b18e
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/monitor_solaris.go
@@ -0,0 +1,144 @@
+// +build solaris,cgo
+
+package supervisor
+
+/*
+#include <port.h>
+#include <poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+int portAssociate(int port, int fd) {
+ if (port_associate(port, PORT_SOURCE_FD, fd, POLLIN | POLLHUP, NULL) < 0) {
+ return 1;
+ }
+}
+
+port_event_t* getEvent(int e_fd) {
+ port_event_t *ev;
+ ev = (port_event_t *)malloc(sizeof(port_event_t));
+ if (port_get(e_fd, ev, NULL) < 0) {
+ return NULL;
+ }
+ return ev;
+}
+
+int getFd(uintptr_t x) {
+ return *(int *)x;
+}
+
+void freeEvent( port_event_t *ev){
+ free(ev);
+}
+*/
+import "C"
+import (
+ "sync"
+ "unsafe"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/containerd/containerd/runtime"
+)
+
+// NewMonitor starts a new process monitor and returns it
+func NewMonitor() (*Monitor, error) {
+ m := &Monitor{
+ receivers: make(map[int]interface{}),
+ exits: make(chan runtime.Process, 1024),
+ ooms: make(chan string, 1024),
+ }
+ fd, err := C.port_create()
+ if err != nil {
+ return nil, err
+ }
+
+ m.epollFd = int(fd)
+ go m.start()
+ return m, nil
+}
+
+// Monitor represents a runtime.Process monitor
+type Monitor struct {
+ m sync.Mutex
+ receivers map[int]interface{}
+ exits chan runtime.Process
+ ooms chan string
+ epollFd int
+}
+
+// Exits returns the channel used to notify of a process exit
+func (m *Monitor) Exits() chan runtime.Process {
+ return m.exits
+}
+
+// OOMs returns the channel used to notify of a container exit due to OOM
+func (m *Monitor) OOMs() chan string {
+ return m.ooms
+}
+
+// Monitor adds a process to the list of the one being monitored
+func (m *Monitor) Monitor(p runtime.Process) error {
+ m.m.Lock()
+ defer m.m.Unlock()
+ fd := p.ExitFD()
+ if _, err := C.port_associate(C.int(m.epollFd), C.PORT_SOURCE_FD, C.uintptr_t(fd), C.POLLIN|C.POLLHUP, unsafe.Pointer(&fd)); err != nil {
+ return err
+ }
+ EpollFdCounter.Inc(1)
+ m.receivers[fd] = p
+ return nil
+}
+
+// MonitorOOM adds a container to the list of the ones monitored for OOM
+// There is no OOM-Killer on Solaris therefore nothing to setup
+func (m *Monitor) MonitorOOM(c runtime.Container) error {
+ return nil
+}
+
+// Close cleans up resources allocated by NewMonitor()
+func (m *Monitor) Close() error {
+ _, err := C.close(C.int(m.epollFd))
+ return err
+}
+
+func (m *Monitor) start() {
+ for {
+ ev := C.getEvent(C.int(m.epollFd))
+ if ev == nil {
+ continue
+ }
+ fd := int(C.getFd(C.uintptr_t(uintptr((ev.portev_user)))))
+
+ if fd < 0 {
+ logrus.Warnf("containerd: epoll wait")
+ }
+
+ m.m.Lock()
+ r := m.receivers[fd]
+ switch t := r.(type) {
+ case runtime.Process:
+ if ev.portev_events == C.POLLHUP {
+ delete(m.receivers, fd)
+ if err := t.Close(); err != nil {
+ logrus.Warnf("containerd: close process IO")
+ }
+ EpollFdCounter.Dec(1)
+ m.exits <- t
+ }
+ case runtime.OOM:
+ // always flush the event fd
+ t.Flush()
+ if t.Removed() {
+ delete(m.receivers, fd)
+ // epoll will remove the fd from its set after it has been closed
+ t.Close()
+ EpollFdCounter.Dec(1)
+ } else {
+ m.ooms <- t.ContainerID()
+ }
+ }
+ m.m.Unlock()
+ C.freeEvent(ev)
+ }
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/oom.go b/vendor/github.com/containerd/containerd/supervisor/oom.go
new file mode 100644
index 0000000..9d8c23d
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/oom.go
@@ -0,0 +1,23 @@
+package supervisor
+
+import (
+ "time"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// OOMTask holds needed parameters to report a container OOM
+type OOMTask struct {
+ baseTask
+ ID string
+}
+
+func (s *Supervisor) oom(t *OOMTask) error {
+ logrus.WithField("id", t.ID).Debug("containerd: container oom")
+ s.notifySubscribers(Event{
+ Timestamp: time.Now(),
+ ID: t.ID,
+ Type: StateOOM,
+ })
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/signal.go b/vendor/github.com/containerd/containerd/supervisor/signal.go
new file mode 100644
index 0000000..55dfa79
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/signal.go
@@ -0,0 +1,30 @@
+package supervisor
+
+import (
+ "os"
+)
+
+// SignalTask holds needed parameters to signal a container
+type SignalTask struct {
+ baseTask
+ ID string
+ PID string
+ Signal os.Signal
+}
+
+func (s *Supervisor) signal(t *SignalTask) error {
+ i, ok := s.containers[t.ID]
+ if !ok {
+ return ErrContainerNotFound
+ }
+ processes, err := i.container.Processes()
+ if err != nil {
+ return err
+ }
+ for _, p := range processes {
+ if p.ID() == t.PID {
+ return p.Signal(t.Signal)
+ }
+ }
+ return ErrProcessNotFound
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/sort.go b/vendor/github.com/containerd/containerd/supervisor/sort.go
new file mode 100644
index 0000000..35ccce1
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/sort.go
@@ -0,0 +1,27 @@
+package supervisor
+
+import (
+ "sort"
+
+ "github.com/containerd/containerd/runtime"
+)
+
+func sortProcesses(p []runtime.Process) {
+ sort.Sort(&processSorter{p})
+}
+
+type processSorter struct {
+ processes []runtime.Process
+}
+
+func (s *processSorter) Len() int {
+ return len(s.processes)
+}
+
+func (s *processSorter) Swap(i, j int) {
+ s.processes[i], s.processes[j] = s.processes[j], s.processes[i]
+}
+
+func (s *processSorter) Less(i, j int) bool {
+ return s.processes[j].ID() == runtime.InitProcessID
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/stats.go b/vendor/github.com/containerd/containerd/supervisor/stats.go
new file mode 100644
index 0000000..baeae25
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/stats.go
@@ -0,0 +1,34 @@
+package supervisor
+
+import (
+ "time"
+
+ "github.com/containerd/containerd/runtime"
+)
+
+// StatsTask holds needed parameters to retrieve a container statistics
+type StatsTask struct {
+ baseTask
+ ID string
+ Stat chan *runtime.Stat
+}
+
+func (s *Supervisor) stats(t *StatsTask) error {
+ start := time.Now()
+ i, ok := s.containers[t.ID]
+ if !ok {
+ return ErrContainerNotFound
+ }
+ // TODO: use workers for this
+ go func() {
+ s, err := i.container.Stats()
+ if err != nil {
+ t.ErrorCh() <- err
+ return
+ }
+ t.ErrorCh() <- nil
+ t.Stat <- s
+ ContainerStatsTimer.UpdateSince(start)
+ }()
+ return errDeferredResponse
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/supervisor.go b/vendor/github.com/containerd/containerd/supervisor/supervisor.go
new file mode 100644
index 0000000..41539b1
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/supervisor.go
@@ -0,0 +1,452 @@
+package supervisor
+
+import (
+ "encoding/json"
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/containerd/containerd/runtime"
+)
+
+const (
+ defaultBufferSize = 2048 // size of queue in eventloop
+)
+
+// New returns an initialized Process supervisor.
+func New(stateDir string, runtimeName, shimName string, runtimeArgs []string, timeout time.Duration, retainCount int) (*Supervisor, error) {
+ startTasks := make(chan *startTask, 10)
+ machine, err := CollectMachineInformation()
+ if err != nil {
+ return nil, err
+ }
+ monitor, err := NewMonitor()
+ if err != nil {
+ return nil, err
+ }
+ s := &Supervisor{
+ stateDir: stateDir,
+ containers: make(map[string]*containerInfo),
+ startTasks: startTasks,
+ machine: machine,
+ subscribers: make(map[chan Event]struct{}),
+ tasks: make(chan Task, defaultBufferSize),
+ monitor: monitor,
+ runtime: runtimeName,
+ runtimeArgs: runtimeArgs,
+ shim: shimName,
+ timeout: timeout,
+ containerExecSync: make(map[string]map[string]chan struct{}),
+ }
+ if err := setupEventLog(s, retainCount); err != nil {
+ return nil, err
+ }
+ go s.exitHandler()
+ go s.oomHandler()
+ if err := s.restore(); err != nil {
+ return nil, err
+ }
+ return s, nil
+}
+
+type containerInfo struct {
+ container runtime.Container
+}
+
+func setupEventLog(s *Supervisor, retainCount int) error {
+ if err := readEventLog(s); err != nil {
+ return err
+ }
+ logrus.WithField("count", len(s.eventLog)).Debug("containerd: read past events")
+ events := s.Events(time.Time{}, false, "")
+ return eventLogger(s, filepath.Join(s.stateDir, "events.log"), events, retainCount)
+}
+
+func eventLogger(s *Supervisor, path string, events chan Event, retainCount int) error {
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND|os.O_TRUNC, 0755)
+ if err != nil {
+ return err
+ }
+ go func() {
+ var (
+ count = len(s.eventLog)
+ enc = json.NewEncoder(f)
+ )
+ for e := range events {
+ // if we have a specified retain count make sure the truncate the event
+ // log if it grows past the specified number of events to keep.
+ if retainCount > 0 {
+ if count > retainCount {
+ logrus.Debug("truncating event log")
+ // close the log file
+ if f != nil {
+ f.Close()
+ }
+ slice := retainCount - 1
+ l := len(s.eventLog)
+ if slice >= l {
+ slice = l
+ }
+ s.eventLock.Lock()
+ s.eventLog = s.eventLog[len(s.eventLog)-slice:]
+ s.eventLock.Unlock()
+ if f, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND|os.O_TRUNC, 0755); err != nil {
+ logrus.WithField("error", err).Error("containerd: open event to journal")
+ continue
+ }
+ enc = json.NewEncoder(f)
+ count = 0
+ for _, le := range s.eventLog {
+ if err := enc.Encode(le); err != nil {
+ logrus.WithField("error", err).Error("containerd: write event to journal")
+ }
+ }
+ }
+ }
+ s.eventLock.Lock()
+ s.eventLog = append(s.eventLog, e)
+ s.eventLock.Unlock()
+ count++
+ if err := enc.Encode(e); err != nil {
+ logrus.WithField("error", err).Error("containerd: write event to journal")
+ }
+ }
+ }()
+ return nil
+}
+
+func readEventLog(s *Supervisor) error {
+ f, err := os.Open(filepath.Join(s.stateDir, "events.log"))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+ }
+ defer f.Close()
+ dec := json.NewDecoder(f)
+ for {
+ var e eventV1
+ if err := dec.Decode(&e); err != nil {
+ if err == io.EOF {
+ break
+ }
+ return err
+ }
+
+ // We need to take care of -1 Status for backward compatibility
+ ev := e.Event
+ ev.Status = uint32(e.Status)
+ if ev.Status > runtime.UnknownStatus {
+ ev.Status = runtime.UnknownStatus
+ }
+ s.eventLog = append(s.eventLog, ev)
+ }
+ return nil
+}
+
+// Supervisor represents a container supervisor
+type Supervisor struct {
+ // stateDir is the directory on the system to store container runtime state information.
+ stateDir string
+ // name of the OCI compatible runtime used to execute containers
+ runtime string
+ runtimeArgs []string
+ shim string
+ containers map[string]*containerInfo
+ startTasks chan *startTask
+ // we need a lock around the subscribers map only because additions and deletions from
+ // the map are via the API so we cannot really control the concurrency
+ subscriberLock sync.RWMutex
+ subscribers map[chan Event]struct{}
+ machine Machine
+ tasks chan Task
+ monitor *Monitor
+ eventLog []Event
+ eventLock sync.Mutex
+ timeout time.Duration
+ // This is used to ensure that exec process death events are sent
+ // before the init process death
+ containerExecSyncLock sync.Mutex
+ containerExecSync map[string]map[string]chan struct{}
+}
+
+// Stop closes all startTasks and sends a SIGTERM to each container's pid1 then waits for they to
+// terminate. After it has handled all the SIGCHILD events it will close the signals chan
+// and exit. Stop is a non-blocking call and will return after the containers have been signaled
+func (s *Supervisor) Stop() {
+ // Close the startTasks channel so that no new containers get started
+ close(s.startTasks)
+}
+
+// Close closes any open files in the supervisor but expects that Stop has been
+// callsed so that no more containers are started.
+func (s *Supervisor) Close() error {
+ return nil
+}
+
+// Event represents a container event
+type Event struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+ Timestamp time.Time `json:"timestamp"`
+ PID string `json:"pid,omitempty"`
+ Status uint32 `json:"status,omitempty"`
+}
+
+type eventV1 struct {
+ Event
+ Status int `json:"status,omitempty"`
+}
+
+// Events returns an event channel that external consumers can use to receive updates
+// on container events
+func (s *Supervisor) Events(from time.Time, storedOnly bool, id string) chan Event {
+ c := make(chan Event, defaultBufferSize)
+ if storedOnly {
+ defer s.Unsubscribe(c)
+ }
+ s.subscriberLock.Lock()
+ defer s.subscriberLock.Unlock()
+ if !from.IsZero() {
+ // replay old event
+ s.eventLock.Lock()
+ past := s.eventLog[:]
+ s.eventLock.Unlock()
+ for _, e := range past {
+ if e.Timestamp.After(from) {
+ if id == "" || e.ID == id {
+ c <- e
+ }
+ }
+ }
+ }
+ if storedOnly {
+ close(c)
+ } else {
+ EventSubscriberCounter.Inc(1)
+ s.subscribers[c] = struct{}{}
+ }
+ return c
+}
+
+// Unsubscribe removes the provided channel from receiving any more events
+func (s *Supervisor) Unsubscribe(sub chan Event) {
+ s.subscriberLock.Lock()
+ defer s.subscriberLock.Unlock()
+ if _, ok := s.subscribers[sub]; ok {
+ delete(s.subscribers, sub)
+ close(sub)
+ EventSubscriberCounter.Dec(1)
+ }
+}
+
+// notifySubscribers will send the provided event to the external subscribers
+// of the events channel
+func (s *Supervisor) notifySubscribers(e Event) {
+ s.subscriberLock.RLock()
+ defer s.subscriberLock.RUnlock()
+ for sub := range s.subscribers {
+ // do a non-blocking send for the channel
+ select {
+ case sub <- e:
+ default:
+ logrus.WithField("event", e.Type).Warn("containerd: event not sent to subscriber")
+ }
+ }
+}
+
+// Start is a non-blocking call that runs the supervisor for monitoring contianer processes and
+// executing new containers.
+//
+// This event loop is the only thing that is allowed to modify state of containers and processes
+// therefore it is save to do operations in the handlers that modify state of the system or
+// state of the Supervisor
+func (s *Supervisor) Start() error {
+ logrus.WithFields(logrus.Fields{
+ "stateDir": s.stateDir,
+ "runtime": s.runtime,
+ "runtimeArgs": s.runtimeArgs,
+ "memory": s.machine.Memory,
+ "cpus": s.machine.Cpus,
+ }).Debug("containerd: supervisor running")
+ go func() {
+ for i := range s.tasks {
+ s.handleTask(i)
+ }
+ }()
+ return nil
+}
+
+// Machine returns the machine information for which the
+// supervisor is executing on.
+func (s *Supervisor) Machine() Machine {
+ return s.machine
+}
+
+// SendTask sends the provided event the the supervisors main event loop
+func (s *Supervisor) SendTask(evt Task) {
+ TasksCounter.Inc(1)
+ s.tasks <- evt
+}
+
+func (s *Supervisor) exitHandler() {
+ for p := range s.monitor.Exits() {
+ e := &ExitTask{
+ Process: p,
+ }
+ s.SendTask(e)
+ }
+}
+
+func (s *Supervisor) oomHandler() {
+ for id := range s.monitor.OOMs() {
+ e := &OOMTask{
+ ID: id,
+ }
+ s.SendTask(e)
+ }
+}
+
+func (s *Supervisor) monitorProcess(p runtime.Process) error {
+ return s.monitor.Monitor(p)
+}
+
+func (s *Supervisor) restore() error {
+ dirs, err := ioutil.ReadDir(s.stateDir)
+ if err != nil {
+ return err
+ }
+ for _, d := range dirs {
+ if !d.IsDir() {
+ continue
+ }
+ id := d.Name()
+ container, err := runtime.Load(s.stateDir, id, s.shim, s.timeout)
+ if err != nil {
+ logrus.WithFields(logrus.Fields{"error": err, "id": id}).Warnf("containerd: failed to load container,removing state directory.")
+ os.RemoveAll(filepath.Join(s.stateDir, id))
+ continue
+ }
+ processes, err := container.Processes()
+ if err != nil || len(processes) == 0 {
+ logrus.WithFields(logrus.Fields{"error": err, "id": id}).Warnf("containerd: container has no process running,removing state directory.")
+ os.RemoveAll(filepath.Join(s.stateDir, id))
+ continue
+ }
+
+ ContainersCounter.Inc(1)
+ s.containers[id] = &containerInfo{
+ container: container,
+ }
+ if err := s.monitor.MonitorOOM(container); err != nil && err != runtime.ErrContainerExited {
+ logrus.WithField("error", err).Error("containerd: notify OOM events")
+ }
+
+ s.newExecSyncMap(container.ID())
+
+ logrus.WithField("id", id).Debug("containerd: container restored")
+ var exitedProcesses []runtime.Process
+ for _, p := range processes {
+ if p.State() == runtime.Running {
+ if err := s.monitorProcess(p); err != nil {
+ return err
+ }
+ } else {
+ exitedProcesses = append(exitedProcesses, p)
+ }
+ if p.ID() != runtime.InitProcessID {
+ s.newExecSyncChannel(container.ID(), p.ID())
+ }
+ }
+ if len(exitedProcesses) > 0 {
+ // sort processes so that init is fired last because that is how the kernel sends the
+ // exit events
+ sortProcesses(exitedProcesses)
+ for _, p := range exitedProcesses {
+ e := &ExitTask{
+ Process: p,
+ }
+ s.SendTask(e)
+ }
+ }
+ }
+ return nil
+}
+
+func (s *Supervisor) handleTask(i Task) {
+ var err error
+ switch t := i.(type) {
+ case *AddProcessTask:
+ err = s.addProcess(t)
+ case *CreateCheckpointTask:
+ err = s.createCheckpoint(t)
+ case *DeleteCheckpointTask:
+ err = s.deleteCheckpoint(t)
+ case *StartTask:
+ err = s.start(t)
+ case *DeleteTask:
+ err = s.delete(t)
+ case *ExitTask:
+ err = s.exit(t)
+ case *GetContainersTask:
+ err = s.getContainers(t)
+ case *SignalTask:
+ err = s.signal(t)
+ case *StatsTask:
+ err = s.stats(t)
+ case *UpdateTask:
+ err = s.updateContainer(t)
+ case *UpdateProcessTask:
+ err = s.updateProcess(t)
+ case *OOMTask:
+ err = s.oom(t)
+ default:
+ err = ErrUnknownTask
+ }
+ if err != errDeferredResponse {
+ i.ErrorCh() <- err
+ close(i.ErrorCh())
+ }
+}
+
+func (s *Supervisor) newExecSyncMap(containerID string) {
+ s.containerExecSyncLock.Lock()
+ s.containerExecSync[containerID] = make(map[string]chan struct{})
+ s.containerExecSyncLock.Unlock()
+}
+
+func (s *Supervisor) newExecSyncChannel(containerID, pid string) {
+ s.containerExecSyncLock.Lock()
+ s.containerExecSync[containerID][pid] = make(chan struct{})
+ s.containerExecSyncLock.Unlock()
+}
+
+func (s *Supervisor) deleteExecSyncChannel(containerID, pid string) {
+ s.containerExecSyncLock.Lock()
+ delete(s.containerExecSync[containerID], pid)
+ s.containerExecSyncLock.Unlock()
+}
+
+func (s *Supervisor) getExecSyncChannel(containerID, pid string) chan struct{} {
+ s.containerExecSyncLock.Lock()
+ ch := s.containerExecSync[containerID][pid]
+ s.containerExecSyncLock.Unlock()
+ return ch
+}
+
+func (s *Supervisor) getExecSyncMap(containerID string) map[string]chan struct{} {
+ s.containerExecSyncLock.Lock()
+ defer s.containerExecSyncLock.Unlock()
+ return s.containerExecSync[containerID]
+}
+
+func (s *Supervisor) deleteExecSyncMap(containerID string) {
+ s.containerExecSyncLock.Lock()
+ defer s.containerExecSyncLock.Unlock()
+ delete(s.containerExecSync, containerID)
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/task.go b/vendor/github.com/containerd/containerd/supervisor/task.go
new file mode 100644
index 0000000..4980a35
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/task.go
@@ -0,0 +1,34 @@
+package supervisor
+
+import (
+ "sync"
+
+ "github.com/containerd/containerd/runtime"
+)
+
+// StartResponse is the response containing a started container
+type StartResponse struct {
+ ExecPid int
+ Container runtime.Container
+}
+
+// Task executes an action returning an error chan with either nil or
+// the error from executing the task
+type Task interface {
+ // ErrorCh returns a channel used to report and error from an async task
+ ErrorCh() chan error
+}
+
+type baseTask struct {
+ errCh chan error
+ mu sync.Mutex
+}
+
+func (t *baseTask) ErrorCh() chan error {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.errCh == nil {
+ t.errCh = make(chan error, 1)
+ }
+ return t.errCh
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/types.go b/vendor/github.com/containerd/containerd/supervisor/types.go
new file mode 100644
index 0000000..2e36fce
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/types.go
@@ -0,0 +1,12 @@
+package supervisor
+
+// State constants used in Event types
+const (
+ StateStart = "start-container"
+ StatePause = "pause"
+ StateResume = "resume"
+ StateExit = "exit"
+ StateStartProcess = "start-process"
+ StateOOM = "oom"
+ StateLive = "live"
+)
diff --git a/vendor/github.com/containerd/containerd/supervisor/update.go b/vendor/github.com/containerd/containerd/supervisor/update.go
new file mode 100644
index 0000000..6ee4ff7
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/update.go
@@ -0,0 +1,95 @@
+package supervisor
+
+import (
+ "time"
+
+ "github.com/containerd/containerd/runtime"
+)
+
+// UpdateTask holds needed parameters to update a container resource constraints
+type UpdateTask struct {
+ baseTask
+ ID string
+ State runtime.State
+ Resources *runtime.Resource
+}
+
+func (s *Supervisor) updateContainer(t *UpdateTask) error {
+ i, ok := s.containers[t.ID]
+ if !ok {
+ return ErrContainerNotFound
+ }
+ container := i.container
+ if t.State != "" {
+ switch t.State {
+ case runtime.Running:
+ if err := container.Resume(); err != nil {
+ return err
+ }
+ s.notifySubscribers(Event{
+ ID: t.ID,
+ Type: StateResume,
+ Timestamp: time.Now(),
+ })
+ case runtime.Paused:
+ if err := container.Pause(); err != nil {
+ return err
+ }
+ s.notifySubscribers(Event{
+ ID: t.ID,
+ Type: StatePause,
+ Timestamp: time.Now(),
+ })
+ default:
+ return ErrUnknownContainerStatus
+ }
+ return nil
+ }
+ if t.Resources != nil {
+ return container.UpdateResources(t.Resources)
+ }
+ return nil
+}
+
+// UpdateProcessTask holds needed parameters to update a container
+// process terminal size or close its stdin
+type UpdateProcessTask struct {
+ baseTask
+ ID string
+ PID string
+ CloseStdin bool
+ Width int
+ Height int
+}
+
+func (s *Supervisor) updateProcess(t *UpdateProcessTask) error {
+ i, ok := s.containers[t.ID]
+ if !ok {
+ return ErrContainerNotFound
+ }
+ processes, err := i.container.Processes()
+ if err != nil {
+ return err
+ }
+ var process runtime.Process
+ for _, p := range processes {
+ if p.ID() == t.PID {
+ process = p
+ break
+ }
+ }
+ if process == nil {
+ return ErrProcessNotFound
+ }
+ if t.CloseStdin {
+ if err := process.CloseStdin(); err != nil {
+ return err
+ }
+ }
+ if t.Width > 0 || t.Height > 0 {
+ if err := process.Resize(t.Width, t.Height); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/containerd/containerd/supervisor/worker.go b/vendor/github.com/containerd/containerd/supervisor/worker.go
new file mode 100644
index 0000000..652cd62
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/supervisor/worker.go
@@ -0,0 +1,104 @@
+package supervisor
+
+import (
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/containerd/containerd/runtime"
+ "golang.org/x/net/context"
+)
+
+// Worker interface
+type Worker interface {
+ Start()
+}
+
+type startTask struct {
+ Container runtime.Container
+ CheckpointPath string
+ Stdin string
+ Stdout string
+ Stderr string
+ Err chan error
+ StartResponse chan StartResponse
+ Ctx context.Context
+}
+
+// NewWorker return a new initialized worker
+func NewWorker(s *Supervisor, wg *sync.WaitGroup) Worker {
+ return &worker{
+ s: s,
+ wg: wg,
+ }
+}
+
+type worker struct {
+ wg *sync.WaitGroup
+ s *Supervisor
+}
+
+// Start runs a loop in charge of starting new containers
+func (w *worker) Start() {
+ defer w.wg.Done()
+ for t := range w.s.startTasks {
+ started := time.Now()
+ process, err := t.Container.Start(t.Ctx, t.CheckpointPath, runtime.NewStdio(t.Stdin, t.Stdout, t.Stderr))
+ if err != nil {
+ logrus.WithFields(logrus.Fields{
+ "error": err,
+ "id": t.Container.ID(),
+ }).Error("containerd: start container")
+ t.Err <- err
+ evt := &DeleteTask{
+ ID: t.Container.ID(),
+ NoEvent: true,
+ Process: process,
+ }
+ w.s.SendTask(evt)
+ continue
+ }
+ if err := w.s.monitor.MonitorOOM(t.Container); err != nil && err != runtime.ErrContainerExited {
+ if process.State() != runtime.Stopped {
+ logrus.WithField("error", err).Error("containerd: notify OOM events")
+ }
+ }
+ if err := w.s.monitorProcess(process); err != nil {
+ logrus.WithField("error", err).Error("containerd: add process to monitor")
+ t.Err <- err
+ evt := &DeleteTask{
+ ID: t.Container.ID(),
+ NoEvent: true,
+ Process: process,
+ }
+ w.s.SendTask(evt)
+ continue
+ }
+ // only call process start if we aren't restoring from a checkpoint
+ // if we have restored from a checkpoint then the process is already started
+ if t.CheckpointPath == "" {
+ if err := process.Start(); err != nil {
+ logrus.WithField("error", err).Error("containerd: start init process")
+ t.Err <- err
+ evt := &DeleteTask{
+ ID: t.Container.ID(),
+ NoEvent: true,
+ Process: process,
+ }
+ w.s.SendTask(evt)
+ continue
+ }
+ }
+ ContainerStartTimer.UpdateSince(started)
+ w.s.newExecSyncMap(t.Container.ID())
+ t.Err <- nil
+ t.StartResponse <- StartResponse{
+ Container: t.Container,
+ }
+ w.s.notifySubscribers(Event{
+ Timestamp: time.Now(),
+ ID: t.Container.ID(),
+ Type: StateStart,
+ })
+ }
+}
diff --git a/vendor/github.com/containerd/containerd/version.go b/vendor/github.com/containerd/containerd/version.go
new file mode 100644
index 0000000..7a34f84
--- /dev/null
+++ b/vendor/github.com/containerd/containerd/version.go
@@ -0,0 +1,20 @@
+package containerd
+
+import "fmt"
+
+// VersionMajor holds the release major number
+const VersionMajor = 0
+
+// VersionMinor holds the release minor number
+const VersionMinor = 2
+
+// VersionPatch holds the release patch number
+const VersionPatch = 3
+
+// Version holds the combination of major minor and patch as a string
+// of format Major.Minor.Patch
+var Version = fmt.Sprintf("%d.%d.%d", VersionMajor, VersionMinor, VersionPatch)
+
+// GitCommit is filled with the Git revision being used to build the
+// program at linking time
+var GitCommit = ""
diff --git a/vendor/github.com/containerd/go-runc/LICENSE b/vendor/github.com/containerd/go-runc/LICENSE
new file mode 100644
index 0000000..2abe416
--- /dev/null
+++ b/vendor/github.com/containerd/go-runc/LICENSE
@@ -0,0 +1,24 @@
+Copyright (c) 2016 Michael Crosby. crosbymichael@gmail.com
+
+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/containerd/go-runc/README.md b/vendor/github.com/containerd/go-runc/README.md
new file mode 100644
index 0000000..2629773
--- /dev/null
+++ b/vendor/github.com/containerd/go-runc/README.md
@@ -0,0 +1,42 @@
+# go-runc
+
+[![Build Status](https://travis-ci.org/containerd/go-runc.svg?branch=master)](https://travis-ci.org/containerd/go-runc)
+
+
+This is a package for consuming the [runc](https://github.com/opencontainers/runc) binary in your Go applications.
+It tries to expose all the settings and features of the runc CLI. If there is something missing then add it, its opensource!
+
+This needs runc @ [a9610f2c0](https://github.com/opencontainers/runc/commit/a9610f2c0237d2636d05a031ec8659a70e75ffeb)
+or greater.
+
+## Docs
+
+Docs can be found at [godoc.org](https://godoc.org/github.com/containerd/go-runc).
+
+
+## LICENSE - MIT
+
+Copyright (c) 2016 Michael Crosby. crosbymichael@gmail.com
+
+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/containerd/go-runc/console.go b/vendor/github.com/containerd/go-runc/console.go
new file mode 100644
index 0000000..d84bd9f
--- /dev/null
+++ b/vendor/github.com/containerd/go-runc/console.go
@@ -0,0 +1,98 @@
+// +build cgo
+
+package runc
+
+import (
+ "fmt"
+ "io/ioutil"
+ "net"
+ "os"
+ "path/filepath"
+
+ "github.com/containerd/console"
+ "github.com/opencontainers/runc/libcontainer/utils"
+)
+
+// NewConsoleSocket creates a new unix socket at the provided path to accept a
+// pty master created by runc for use by the container
+func NewConsoleSocket(path string) (*Socket, error) {
+ abs, err := filepath.Abs(path)
+ if err != nil {
+ return nil, err
+ }
+ l, err := net.Listen("unix", abs)
+ if err != nil {
+ return nil, err
+ }
+ return &Socket{
+ l: l,
+ path: abs,
+ }, nil
+}
+
+// NewTempConsoleSocket returns a temp console socket for use with a container
+// On Close(), the socket is deleted
+func NewTempConsoleSocket() (*Socket, error) {
+ dir, err := ioutil.TempDir("", "pty")
+ if err != nil {
+ return nil, err
+ }
+ abs, err := filepath.Abs(filepath.Join(dir, "pty.sock"))
+ if err != nil {
+ return nil, err
+ }
+ l, err := net.Listen("unix", abs)
+ if err != nil {
+ return nil, err
+ }
+ return &Socket{
+ l: l,
+ rmdir: true,
+ path: abs,
+ }, nil
+}
+
+// Socket is a unix socket that accepts the pty master created by runc
+type Socket struct {
+ path string
+ rmdir bool
+ l net.Listener
+}
+
+// Path returns the path to the unix socket on disk
+func (c *Socket) Path() string {
+ return c.path
+}
+
+// ReceiveMaster blocks until the socket receives the pty master
+func (c *Socket) ReceiveMaster() (console.Console, error) {
+ conn, err := c.l.Accept()
+ if err != nil {
+ return nil, err
+ }
+ defer conn.Close()
+ unix, ok := conn.(*net.UnixConn)
+ if !ok {
+ return nil, fmt.Errorf("received connection which was not a unix socket")
+ }
+ sock, err := unix.File()
+ if err != nil {
+ return nil, err
+ }
+ f, err := utils.RecvFd(sock)
+ if err != nil {
+ return nil, err
+ }
+ return console.ConsoleFromFile(f)
+}
+
+// Close closes the unix socket
+func (c *Socket) Close() error {
+ err := c.l.Close()
+ if c.rmdir {
+ if rerr := os.RemoveAll(filepath.Dir(c.path)); err == nil {
+ err = rerr
+ }
+ }
+ return err
+}
diff --git a/vendor/github.com/containerd/go-runc/container.go b/vendor/github.com/containerd/go-runc/container.go
new file mode 100644
index 0000000..7981aac
--- /dev/null
+++ b/vendor/github.com/containerd/go-runc/container.go
@@ -0,0 +1,14 @@
+package runc
+
+import "time"
+
+// Container hold information for a runc container
+type Container struct {
+ ID string `json:"id"`
+ Pid int `json:"pid"`
+ Status string `json:"status"`
+ Bundle string `json:"bundle"`
+ Rootfs string `json:"rootfs"`
+ Created time.Time `json:"created"`
+ Annotations map[string]string `json:"annotations"`
+}
diff --git a/vendor/github.com/containerd/go-runc/events.go b/vendor/github.com/containerd/go-runc/events.go
new file mode 100644
index 0000000..ca0e048
--- /dev/null
+++ b/vendor/github.com/containerd/go-runc/events.go
@@ -0,0 +1,84 @@
+package runc
+
+type Event struct {
+ // Type are the event type generated by runc
+ // If the type is "error" then check the Err field on the event for
+ // the actual error
+ Type string `json:"type"`
+ ID string `json:"id"`
+ Stats *Stats `json:"data,omitempty"`
+ // Err has a read error if we were unable to decode the event from runc
+ Err error `json:"-"`
+}
+
+type Stats struct {
+ Cpu Cpu `json:"cpu"`
+ Memory Memory `json:"memory"`
+ Pids Pids `json:"pids"`
+ Blkio Blkio `json:"blkio"`
+ Hugetlb map[string]Hugetlb `json:"hugetlb"`
+}
+
+type Hugetlb struct {
+ Usage uint64 `json:"usage,omitempty"`
+ Max uint64 `json:"max,omitempty"`
+ Failcnt uint64 `json:"failcnt"`
+}
+
+type BlkioEntry struct {
+ Major uint64 `json:"major,omitempty"`
+ Minor uint64 `json:"minor,omitempty"`
+ Op string `json:"op,omitempty"`
+ Value uint64 `json:"value,omitempty"`
+}
+
+type Blkio struct {
+ IoServiceBytesRecursive []BlkioEntry `json:"ioServiceBytesRecursive,omitempty"`
+ IoServicedRecursive []BlkioEntry `json:"ioServicedRecursive,omitempty"`
+ IoQueuedRecursive []BlkioEntry `json:"ioQueueRecursive,omitempty"`
+ IoServiceTimeRecursive []BlkioEntry `json:"ioServiceTimeRecursive,omitempty"`
+ IoWaitTimeRecursive []BlkioEntry `json:"ioWaitTimeRecursive,omitempty"`
+ IoMergedRecursive []BlkioEntry `json:"ioMergedRecursive,omitempty"`
+ IoTimeRecursive []BlkioEntry `json:"ioTimeRecursive,omitempty"`
+ SectorsRecursive []BlkioEntry `json:"sectorsRecursive,omitempty"`
+}
+
+type Pids struct {
+ Current uint64 `json:"current,omitempty"`
+ Limit uint64 `json:"limit,omitempty"`
+}
+
+type Throttling struct {
+ Periods uint64 `json:"periods,omitempty"`
+ ThrottledPeriods uint64 `json:"throttledPeriods,omitempty"`
+ ThrottledTime uint64 `json:"throttledTime,omitempty"`
+}
+
+type CpuUsage struct {
+ // Units: nanoseconds.
+ Total uint64 `json:"total,omitempty"`
+ Percpu []uint64 `json:"percpu,omitempty"`
+ Kernel uint64 `json:"kernel"`
+ User uint64 `json:"user"`
+}
+
+type Cpu struct {
+ Usage CpuUsage `json:"usage,omitempty"`
+ Throttling Throttling `json:"throttling,omitempty"`
+}
+
+type MemoryEntry struct {
+ Limit uint64 `json:"limit"`
+ Usage uint64 `json:"usage,omitempty"`
+ Max uint64 `json:"max,omitempty"`
+ Failcnt uint64 `json:"failcnt"`
+}
+
+type Memory struct {
+ Cache uint64 `json:"cache,omitempty"`
+ Usage MemoryEntry `json:"usage,omitempty"`
+ Swap MemoryEntry `json:"swap,omitempty"`
+ Kernel MemoryEntry `json:"kernel,omitempty"`
+ KernelTCP MemoryEntry `json:"kernelTCP,omitempty"`
+ Raw map[string]uint64 `json:"raw,omitempty"`
+}
diff --git a/vendor/github.com/containerd/go-runc/io.go b/vendor/github.com/containerd/go-runc/io.go
new file mode 100644
index 0000000..f6f7d2d
--- /dev/null
+++ b/vendor/github.com/containerd/go-runc/io.go
@@ -0,0 +1,165 @@
+package runc
+
+import (
+ "io"
+ "os"
+ "os/exec"
+
+ "golang.org/x/sys/unix"
+)
+
+type IO interface {
+ io.Closer
+ Stdin() io.WriteCloser
+ Stdout() io.ReadCloser
+ Stderr() io.ReadCloser
+ Set(*exec.Cmd)
+}
+
+type StartCloser interface {
+ CloseAfterStart() error
+}
+
+// NewPipeIO creates pipe pairs to be used with runc
+func NewPipeIO(uid, gid int) (i IO, err error) {
+ var pipes []*pipe
+ // cleanup in case of an error
+ defer func() {
+ if err != nil {
+ for _, p := range pipes {
+ p.Close()
+ }
+ }
+ }()
+ stdin, err := newPipe(uid, gid)
+ if err != nil {
+ return nil, err
+ }
+ pipes = append(pipes, stdin)
+
+ stdout, err := newPipe(uid, gid)
+ if err != nil {
+ return nil, err
+ }
+ pipes = append(pipes, stdout)
+
+ stderr, err := newPipe(uid, gid)
+ if err != nil {
+ return nil, err
+ }
+ pipes = append(pipes, stderr)
+
+ return &pipeIO{
+ in: stdin,
+ out: stdout,
+ err: stderr,
+ }, nil
+}
+
+func newPipe(uid, gid int) (*pipe, error) {
+ r, w, err := os.Pipe()
+ if err != nil {
+ return nil, err
+ }
+ if err := unix.Fchown(int(r.Fd()), uid, gid); err != nil {
+ return nil, err
+ }
+ if err := unix.Fchown(int(w.Fd()), uid, gid); err != nil {
+ return nil, err
+ }
+ return &pipe{
+ r: r,
+ w: w,
+ }, nil
+}
+
+type pipe struct {
+ r *os.File
+ w *os.File
+}
+
+func (p *pipe) Close() error {
+ err := p.r.Close()
+ if werr := p.w.Close(); err == nil {
+ err = werr
+ }
+ return err
+}
+
+type pipeIO struct {
+ in *pipe
+ out *pipe
+ err *pipe
+}
+
+func (i *pipeIO) Stdin() io.WriteCloser {
+ return i.in.w
+}
+
+func (i *pipeIO) Stdout() io.ReadCloser {
+ return i.out.r
+}
+
+func (i *pipeIO) Stderr() io.ReadCloser {
+ return i.err.r
+}
+
+func (i *pipeIO) Close() error {
+ var err error
+ for _, v := range []*pipe{
+ i.in,
+ i.out,
+ i.err,
+ } {
+ if cerr := v.Close(); err == nil {
+ err = cerr
+ }
+ }
+ return err
+}
+
+func (i *pipeIO) CloseAfterStart() error {
+ for _, f := range []*os.File{
+ i.out.w,
+ i.err.w,
+ } {
+ f.Close()
+ }
+ return nil
+}
+
+// Set sets the io to the exec.Cmd
+func (i *pipeIO) Set(cmd *exec.Cmd) {
+ cmd.Stdin = i.in.r
+ cmd.Stdout = i.out.w
+ cmd.Stderr = i.err.w
+}
+
+func NewSTDIO() (IO, error) {
+ return &stdio{}, nil
+}
+
+type stdio struct {
+}
+
+func (s *stdio) Close() error {
+ return nil
+}
+
+func (s *stdio) Set(cmd *exec.Cmd) {
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+}
+
+func (s *stdio) Stdin() io.WriteCloser {
+ return os.Stdin
+}
+
+func (s *stdio) Stdout() io.ReadCloser {
+ return os.Stdout
+}
+
+func (s *stdio) Stderr() io.ReadCloser {
+ return os.Stderr
+}
diff --git a/vendor/github.com/containerd/go-runc/monitor.go b/vendor/github.com/containerd/go-runc/monitor.go
new file mode 100644
index 0000000..83eebb0
--- /dev/null
+++ b/vendor/github.com/containerd/go-runc/monitor.go
@@ -0,0 +1,50 @@
+package runc
+
+import (
+ "os/exec"
+ "syscall"
+)
+
+var Monitor ProcessMonitor = &defaultMonitor{}
+
+// ProcessMonitor is an interface for process monitoring
+//
+// It allows daemons using go-runc to have a SIGCHLD handler
+// to handle exits without introducing races between the handler
+// and go's exec.Cmd
+// These methods should match the methods exposed by exec.Cmd to provide
+// a consistent experience for the caller
+type ProcessMonitor interface {
+ Output(*exec.Cmd) ([]byte, error)
+ CombinedOutput(*exec.Cmd) ([]byte, error)
+ Run(*exec.Cmd) error
+ Start(*exec.Cmd) error
+ Wait(*exec.Cmd) (int, error)
+}
+
+type defaultMonitor struct {
+}
+
+func (m *defaultMonitor) Output(c *exec.Cmd) ([]byte, error) {
+ return c.Output()
+}
+
+func (m *defaultMonitor) CombinedOutput(c *exec.Cmd) ([]byte, error) {
+ return c.CombinedOutput()
+}
+
+func (m *defaultMonitor) Run(c *exec.Cmd) error {
+ return c.Run()
+}
+
+func (m *defaultMonitor) Start(c *exec.Cmd) error {
+ return c.Start()
+}
+
+func (m *defaultMonitor) Wait(c *exec.Cmd) (int, error) {
+ status, err := c.Process.Wait()
+ if err != nil {
+ return -1, err
+ }
+ return status.Sys().(syscall.WaitStatus).ExitStatus(), nil
+}
diff --git a/vendor/github.com/containerd/go-runc/runc.go b/vendor/github.com/containerd/go-runc/runc.go
new file mode 100644
index 0000000..9515deb
--- /dev/null
+++ b/vendor/github.com/containerd/go-runc/runc.go
@@ -0,0 +1,553 @@
+package runc
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "syscall"
+ "time"
+
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+// Format is the type of log formatting options avaliable
+type Format string
+
+const (
+ none Format = ""
+ JSON Format = "json"
+ Text Format = "text"
+ // DefaultCommand is the default command for Runc
+ DefaultCommand = "runc"
+)
+
+// Runc is the client to the runc cli
+type Runc struct {
+ //If command is empty, DefaultCommand is used
+ Command string
+ Root string
+ Debug bool
+ Log string
+ LogFormat Format
+ PdeathSignal syscall.Signal
+ Criu string
+}
+
+// List returns all containers created inside the provided runc root directory
+func (r *Runc) List(context context.Context) ([]*Container, error) {
+ data, err := Monitor.Output(r.command(context, "list", "--format=json"))
+ if err != nil {
+ return nil, err
+ }
+ var out []*Container
+ if err := json.Unmarshal(data, &out); err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// State returns the state for the container provided by id
+func (r *Runc) State(context context.Context, id string) (*Container, error) {
+ data, err := Monitor.CombinedOutput(r.command(context, "state", id))
+ if err != nil {
+ return nil, fmt.Errorf("%s: %s", err, data)
+ }
+ var c Container
+ if err := json.Unmarshal(data, &c); err != nil {
+ return nil, err
+ }
+ return &c, nil
+}
+
+type ConsoleSocket interface {
+ Path() string
+}
+
+type CreateOpts struct {
+ IO
+ // PidFile is a path to where a pid file should be created
+ PidFile string
+ ConsoleSocket ConsoleSocket
+ Detach bool
+ NoPivot bool
+ NoNewKeyring bool
+ ExtraFiles []*os.File
+}
+
+func (o *CreateOpts) args() (out []string, err error) {
+ if o.PidFile != "" {
+ abs, err := filepath.Abs(o.PidFile)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, "--pid-file", abs)
+ }
+ if o.ConsoleSocket != nil {
+ out = append(out, "--console-socket", o.ConsoleSocket.Path())
+ }
+ if o.NoPivot {
+ out = append(out, "--no-pivot")
+ }
+ if o.NoNewKeyring {
+ out = append(out, "--no-new-keyring")
+ }
+ if o.Detach {
+ out = append(out, "--detach")
+ }
+ if o.ExtraFiles != nil {
+ out = append(out, "--preserve-fds", strconv.Itoa(len(o.ExtraFiles)))
+ }
+ return out, nil
+}
+
+// Create creates a new container and returns its pid if it was created successfully
+func (r *Runc) Create(context context.Context, id, bundle string, opts *CreateOpts) error {
+ args := []string{"create", "--bundle", bundle}
+ if opts != nil {
+ oargs, err := opts.args()
+ if err != nil {
+ return err
+ }
+ args = append(args, oargs...)
+ }
+ cmd := r.command(context, append(args, id)...)
+ if opts != nil && opts.IO != nil {
+ opts.Set(cmd)
+ }
+ cmd.ExtraFiles = opts.ExtraFiles
+
+ if cmd.Stdout == nil && cmd.Stderr == nil {
+ data, err := Monitor.CombinedOutput(cmd)
+ if err != nil {
+ return fmt.Errorf("%s: %s", err, data)
+ }
+ return nil
+ }
+ if err := Monitor.Start(cmd); err != nil {
+ return err
+ }
+ if opts != nil && opts.IO != nil {
+ if c, ok := opts.IO.(StartCloser); ok {
+ if err := c.CloseAfterStart(); err != nil {
+ return err
+ }
+ }
+ }
+ _, err := Monitor.Wait(cmd)
+ return err
+}
+
+// Start will start an already created container
+func (r *Runc) Start(context context.Context, id string) error {
+ return r.runOrError(r.command(context, "start", id))
+}
+
+type ExecOpts struct {
+ IO
+ PidFile string
+ ConsoleSocket ConsoleSocket
+ Detach bool
+}
+
+func (o *ExecOpts) args() (out []string, err error) {
+ if o.ConsoleSocket != nil {
+ out = append(out, "--console-socket", o.ConsoleSocket.Path())
+ }
+ if o.Detach {
+ out = append(out, "--detach")
+ }
+ if o.PidFile != "" {
+ abs, err := filepath.Abs(o.PidFile)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, "--pid-file", abs)
+ }
+ return out, nil
+}
+
+// Exec executres and additional process inside the container based on a full
+// OCI Process specification
+func (r *Runc) Exec(context context.Context, id string, spec specs.Process, opts *ExecOpts) error {
+ f, err := ioutil.TempFile("", "runc-process")
+ if err != nil {
+ return err
+ }
+ defer os.Remove(f.Name())
+ err = json.NewEncoder(f).Encode(spec)
+ f.Close()
+ if err != nil {
+ return err
+ }
+ args := []string{"exec", "--process", f.Name()}
+ if opts != nil {
+ oargs, err := opts.args()
+ if err != nil {
+ return err
+ }
+ args = append(args, oargs...)
+ }
+ cmd := r.command(context, append(args, id)...)
+ if opts != nil && opts.IO != nil {
+ opts.Set(cmd)
+ }
+ if cmd.Stdout == nil && cmd.Stderr == nil {
+ data, err := Monitor.CombinedOutput(cmd)
+ if err != nil {
+ return fmt.Errorf("%s: %s", err, data)
+ }
+ return nil
+ }
+ if err := Monitor.Start(cmd); err != nil {
+ return err
+ }
+ if opts != nil && opts.IO != nil {
+ if c, ok := opts.IO.(StartCloser); ok {
+ if err := c.CloseAfterStart(); err != nil {
+ return err
+ }
+ }
+ }
+ _, err = Monitor.Wait(cmd)
+ return err
+}
+
+// Run runs the create, start, delete lifecycle of the container
+// and returns its exit status after it has exited
+func (r *Runc) Run(context context.Context, id, bundle string, opts *CreateOpts) (int, error) {
+ args := []string{"run", "--bundle", bundle}
+ if opts != nil {
+ oargs, err := opts.args()
+ if err != nil {
+ return -1, err
+ }
+ args = append(args, oargs...)
+ }
+ cmd := r.command(context, append(args, id)...)
+ if opts != nil {
+ opts.Set(cmd)
+ }
+ if err := Monitor.Start(cmd); err != nil {
+ return -1, err
+ }
+ return Monitor.Wait(cmd)
+}
+
+// Delete deletes the container
+func (r *Runc) Delete(context context.Context, id string) error {
+ return r.runOrError(r.command(context, "delete", id))
+}
+
+// KillOpts specifies options for killing a container and its processes
+type KillOpts struct {
+ All bool
+}
+
+func (o *KillOpts) args() (out []string) {
+ if o.All {
+ out = append(out, "--all")
+ }
+ return out
+}
+
+// Kill sends the specified signal to the container
+func (r *Runc) Kill(context context.Context, id string, sig int, opts *KillOpts) error {
+ args := []string{
+ "kill",
+ }
+ if opts != nil {
+ args = append(args, opts.args()...)
+ }
+ return r.runOrError(r.command(context, append(args, id, strconv.Itoa(sig))...))
+}
+
+// Stats return the stats for a container like cpu, memory, and io
+func (r *Runc) Stats(context context.Context, id string) (*Stats, error) {
+ cmd := r.command(context, "events", "--stats", id)
+ rd, err := cmd.StdoutPipe()
+ if err != nil {
+ return nil, err
+ }
+ defer func() {
+ rd.Close()
+ Monitor.Wait(cmd)
+ }()
+ if err := Monitor.Start(cmd); err != nil {
+ return nil, err
+ }
+ var e Event
+ if err := json.NewDecoder(rd).Decode(&e); err != nil {
+ return nil, err
+ }
+ return e.Stats, nil
+}
+
+// Events returns an event stream from runc for a container with stats and OOM notifications
+func (r *Runc) Events(context context.Context, id string, interval time.Duration) (chan *Event, error) {
+ cmd := r.command(context, "events", fmt.Sprintf("--interval=%ds", int(interval.Seconds())), id)
+ rd, err := cmd.StdoutPipe()
+ if err != nil {
+ return nil, err
+ }
+ if err := Monitor.Start(cmd); err != nil {
+ rd.Close()
+ return nil, err
+ }
+ var (
+ dec = json.NewDecoder(rd)
+ c = make(chan *Event, 128)
+ )
+ go func() {
+ defer func() {
+ close(c)
+ rd.Close()
+ Monitor.Wait(cmd)
+ }()
+ for {
+ var e Event
+ if err := dec.Decode(&e); err != nil {
+ if err == io.EOF {
+ return
+ }
+ e = Event{
+ Type: "error",
+ Err: err,
+ }
+ }
+ c <- &e
+ }
+ }()
+ return c, nil
+}
+
+// Pause the container with the provided id
+func (r *Runc) Pause(context context.Context, id string) error {
+ return r.runOrError(r.command(context, "pause", id))
+}
+
+// Resume the container with the provided id
+func (r *Runc) Resume(context context.Context, id string) error {
+ return r.runOrError(r.command(context, "resume", id))
+}
+
+// Ps lists all the processes inside the container returning their pids
+func (r *Runc) Ps(context context.Context, id string) ([]int, error) {
+ data, err := Monitor.CombinedOutput(r.command(context, "ps", "--format", "json", id))
+ if err != nil {
+ return nil, fmt.Errorf("%s: %s", err, data)
+ }
+ var pids []int
+ if err := json.Unmarshal(data, &pids); err != nil {
+ return nil, err
+ }
+ return pids, nil
+}
+
+type CheckpointOpts struct {
+ // ImagePath is the path for saving the criu image file
+ ImagePath string
+ // WorkDir is the working directory for criu
+ WorkDir string
+ // ParentPath is the path for previous image files from a pre-dump
+ ParentPath string
+ // AllowOpenTCP allows open tcp connections to be checkpointed
+ AllowOpenTCP bool
+ // AllowExternalUnixSockets allows external unix sockets to be checkpointed
+ AllowExternalUnixSockets bool
+ // AllowTerminal allows the terminal(pty) to be checkpointed with a container
+ AllowTerminal bool
+ // CriuPageServer is the address:port for the criu page server
+ CriuPageServer string
+ // FileLocks handle file locks held by the container
+ FileLocks bool
+ // Cgroups is the cgroup mode for how to handle the checkpoint of a container's cgroups
+ Cgroups CgroupMode
+ // EmptyNamespaces creates a namespace for the container but does not save its properties
+ // Provide the namespaces you wish to be checkpointed without their settings on restore
+ EmptyNamespaces []string
+}
+
+type CgroupMode string
+
+const (
+ Soft CgroupMode = "soft"
+ Full CgroupMode = "full"
+ Strict CgroupMode = "strict"
+)
+
+func (o *CheckpointOpts) args() (out []string) {
+ if o.ImagePath != "" {
+ out = append(out, "--image-path", o.ImagePath)
+ }
+ if o.WorkDir != "" {
+ out = append(out, "--work-path", o.WorkDir)
+ }
+ if o.ParentPath != "" {
+ out = append(out, "--parent-path", o.ParentPath)
+ }
+ if o.AllowOpenTCP {
+ out = append(out, "--tcp-established")
+ }
+ if o.AllowExternalUnixSockets {
+ out = append(out, "--ext-unix-sk")
+ }
+ if o.AllowTerminal {
+ out = append(out, "--shell-job")
+ }
+ if o.CriuPageServer != "" {
+ out = append(out, "--page-server", o.CriuPageServer)
+ }
+ if o.FileLocks {
+ out = append(out, "--file-locks")
+ }
+ if string(o.Cgroups) != "" {
+ out = append(out, "--manage-cgroups-mode", string(o.Cgroups))
+ }
+ for _, ns := range o.EmptyNamespaces {
+ out = append(out, "--empty-ns", ns)
+ }
+ return out
+}
+
+type CheckpointAction func([]string) []string
+
+// LeaveRunning keeps the container running after the checkpoint has been completed
+func LeaveRunning(args []string) []string {
+ return append(args, "--leave-running")
+}
+
+// PreDump allows a pre-dump of the checkpoint to be made and completed later
+func PreDump(args []string) []string {
+ return append(args, "--pre-dump")
+}
+
+// Checkpoint allows you to checkpoint a container using criu
+func (r *Runc) Checkpoint(context context.Context, id string, opts *CheckpointOpts, actions ...CheckpointAction) error {
+ args := []string{"checkpoint"}
+ if opts != nil {
+ args = append(args, opts.args()...)
+ }
+ for _, a := range actions {
+ args = a(args)
+ }
+ return r.runOrError(r.command(context, append(args, id)...))
+}
+
+type RestoreOpts struct {
+ CheckpointOpts
+ IO
+
+ Detach bool
+ PidFile string
+ NoSubreaper bool
+ NoPivot bool
+}
+
+func (o *RestoreOpts) args() ([]string, error) {
+ out := o.CheckpointOpts.args()
+ if o.Detach {
+ out = append(out, "--detach")
+ }
+ if o.PidFile != "" {
+ abs, err := filepath.Abs(o.PidFile)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, "--pid-file", abs)
+ }
+ if o.NoPivot {
+ out = append(out, "--no-pivot")
+ }
+ if o.NoSubreaper {
+ out = append(out, "-no-subreaper")
+ }
+ return out, nil
+}
+
+// Restore restores a container with the provide id from an existing checkpoint
+func (r *Runc) Restore(context context.Context, id, bundle string, opts *RestoreOpts) (int, error) {
+ args := []string{"restore"}
+ if opts != nil {
+ oargs, err := opts.args()
+ if err != nil {
+ return -1, err
+ }
+ args = append(args, oargs...)
+ }
+ args = append(args, "--bundle", bundle)
+ cmd := r.command(context, append(args, id)...)
+ if opts != nil {
+ opts.Set(cmd)
+ }
+ if err := Monitor.Start(cmd); err != nil {
+ return -1, err
+ }
+ return Monitor.Wait(cmd)
+}
+
+// Update updates the current container with the provided resource spec
+func (r *Runc) Update(context context.Context, id string, resources *specs.LinuxResources) error {
+ buf := bytes.NewBuffer(nil)
+ if err := json.NewEncoder(buf).Encode(resources); err != nil {
+ return err
+ }
+ args := []string{"update", "--resources", "-", id}
+ cmd := r.command(context, args...)
+ cmd.Stdin = buf
+ return r.runOrError(cmd)
+}
+
+func (r *Runc) args() (out []string) {
+ if r.Root != "" {
+ out = append(out, "--root", r.Root)
+ }
+ if r.Debug {
+ out = append(out, "--debug")
+ }
+ if r.Log != "" {
+ out = append(out, "--log", r.Log)
+ }
+ if r.LogFormat != none {
+ out = append(out, "--log-format", string(r.LogFormat))
+ }
+ if r.Criu != "" {
+ out = append(out, "--criu", r.Criu)
+ }
+ return out
+}
+
+func (r *Runc) command(context context.Context, args ...string) *exec.Cmd {
+ command := r.Command
+ if command == "" {
+ command = DefaultCommand
+ }
+ cmd := exec.CommandContext(context, command, append(r.args(), args...)...)
+ if r.PdeathSignal != 0 {
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ Pdeathsig: r.PdeathSignal,
+ }
+ }
+ return cmd
+}
+
+// runOrError will run the provided command. If an error is
+// encountered and neither Stdout or Stderr was set the error and the
+// stderr of the command will be returned in the format of <error>:
+// <stderr>
+func (r *Runc) runOrError(cmd *exec.Cmd) error {
+ if cmd.Stdout != nil || cmd.Stderr != nil {
+ return Monitor.Run(cmd)
+ }
+ data, err := Monitor.CombinedOutput(cmd)
+ if err != nil {
+ return fmt.Errorf("%s: %s", err, data)
+ }
+ return nil
+}
diff --git a/vendor/github.com/containerd/go-runc/utils.go b/vendor/github.com/containerd/go-runc/utils.go
new file mode 100644
index 0000000..81fcd3f
--- /dev/null
+++ b/vendor/github.com/containerd/go-runc/utils.go
@@ -0,0 +1,28 @@
+package runc
+
+import (
+ "io/ioutil"
+ "strconv"
+ "syscall"
+)
+
+// ReadPidFile reads the pid file at the provided path and returns
+// the pid or an error if the read and conversion is unsuccessful
+func ReadPidFile(path string) (int, error) {
+ data, err := ioutil.ReadFile(path)
+ if err != nil {
+ return -1, err
+ }
+ return strconv.Atoi(string(data))
+}
+
+const exitSignalOffset = 128
+
+// exitStatus returns the correct exit status for a process based on if it
+// was signaled or exited cleanly
+func exitStatus(status syscall.WaitStatus) int {
+ if status.Signaled() {
+ return exitSignalOffset + int(status.Signal())
+ }
+ return status.ExitStatus()
+}
diff --git a/vendor/github.com/coreos/etcd/LICENSE b/vendor/github.com/coreos/etcd/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/coreos/etcd/NOTICE b/vendor/github.com/coreos/etcd/NOTICE
new file mode 100644
index 0000000..b39ddfa
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/NOTICE
@@ -0,0 +1,5 @@
+CoreOS Project
+Copyright 2014 CoreOS, Inc
+
+This product includes software developed at CoreOS, Inc.
+(http://www.coreos.com/).
diff --git a/vendor/github.com/coreos/etcd/README.md b/vendor/github.com/coreos/etcd/README.md
new file mode 100644
index 0000000..e7d4e23
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/README.md
@@ -0,0 +1,139 @@
+# etcd
+
+[![Go Report Card](https://goreportcard.com/badge/github.com/coreos/etcd)](https://goreportcard.com/report/github.com/coreos/etcd)
+[![Build Status](https://travis-ci.org/coreos/etcd.svg?branch=master)](https://travis-ci.org/coreos/etcd)
+[![Build Status](https://semaphoreci.com/api/v1/coreos/etcd/branches/master/shields_badge.svg)](https://semaphoreci.com/coreos/etcd)
+[![Docker Repository on Quay.io](https://quay.io/repository/coreos/etcd-git/status "Docker Repository on Quay.io")](https://quay.io/repository/coreos/etcd-git)
+
+**Note**: The `master` branch may be in an *unstable or even broken state* during development. Please use [releases][github-release] instead of the `master` branch in order to get stable binaries.
+
+*the etcd v2 [documentation](Documentation/v2/README.md) has moved*
+
+![etcd Logo](logos/etcd-horizontal-color.png)
+
+etcd is a distributed, consistent key-value store for shared configuration and service discovery, with a focus on being:
+
+* *Simple*: well-defined, user-facing API (gRPC)
+* *Secure*: automatic TLS with optional client cert authentication
+* *Fast*: benchmarked 10,000 writes/sec
+* *Reliable*: properly distributed using Raft
+
+etcd is written in Go and uses the [Raft][raft] consensus algorithm to manage a highly-available replicated log.
+
+etcd is used [in production by many companies](./Documentation/production-users.md), and the development team stands behind it in critical deployment scenarios, where etcd is frequently teamed with applications such as [Kubernetes][k8s], [fleet][fleet], [locksmith][locksmith], [vulcand][vulcand], [Doorman][doorman], and many others. Reliability is further ensured by rigorous [testing][etcd-tests].
+
+See [etcdctl][etcdctl] for a simple command line client.
+
+[raft]: https://raft.github.io/
+[k8s]: http://kubernetes.io/
+[doorman]: https://github.com/youtube/doorman
+[fleet]: https://github.com/coreos/fleet
+[locksmith]: https://github.com/coreos/locksmith
+[vulcand]: https://github.com/vulcand/vulcand
+[etcdctl]: https://github.com/coreos/etcd/tree/master/etcdctl
+[etcd-tests]: http://dash.etcd.io
+
+## Getting started
+
+### Getting etcd
+
+The easiest way to get etcd is to use one of the pre-built release binaries which are available for OSX, Linux, Windows, AppC (ACI), and Docker. Instructions for using these binaries are on the [GitHub releases page][github-release].
+
+For those wanting to try the very latest version, you can [build the latest version of etcd][dl-build] from the `master` branch.
+You will first need [*Go*](https://golang.org/) installed on your machine (version 1.6+ is required).
+All development occurs on `master`, including new features and bug fixes.
+Bug fixes are first targeted at `master` and subsequently ported to release branches, as described in the [branch management][branch-management] guide.
+
+[github-release]: https://github.com/coreos/etcd/releases/
+[branch-management]: ./Documentation/branch_management.md
+[dl-build]: ./Documentation/dl_build.md#build-the-latest-version
+
+### Running etcd
+
+First start a single-member cluster of etcd:
+
+```sh
+./bin/etcd
+```
+
+This will bring up etcd listening on port 2379 for client communication and on port 2380 for server-to-server communication.
+
+Next, let's set a single key, and then retrieve it:
+
+```
+ETCDCTL_API=3 etcdctl put mykey "this is awesome"
+ETCDCTL_API=3 etcdctl get mykey
+```
+
+That's it! etcd is now running and serving client requests. For more
+
+- [Animated quick demo][demo-gif]
+- [Interactive etcd playground][etcd-play]
+
+[demo-gif]: ./Documentation/demo.md
+[etcd-play]: http://play.etcd.io/
+
+### etcd TCP ports
+
+The [official etcd ports][iana-ports] are 2379 for client requests, and 2380 for peer communication.
+
+[iana-ports]: https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=etcd
+
+### Running a local etcd cluster
+
+First install [goreman](https://github.com/mattn/goreman), which manages Procfile-based applications.
+
+Our [Procfile script](./Procfile) will set up a local example cluster. Start it with:
+
+```sh
+goreman start
+```
+
+This will bring up 3 etcd members `infra1`, `infra2` and `infra3` and etcd proxy `proxy`, which runs locally and composes a cluster.
+
+Every cluster member and proxy accepts key value reads and key value writes.
+
+### Running etcd on Kubernetes
+
+If you want to run etcd cluster on Kubernetes, try [etcd operator](https://github.com/coreos/etcd-operator).
+
+### Next steps
+
+Now it's time to dig into the full etcd API and other guides.
+
+- Read the full [documentation][fulldoc].
+- Explore the full gRPC [API][api].
+- Set up a [multi-machine cluster][clustering].
+- Learn the [config format, env variables and flags][configuration].
+- Find [language bindings and tools][libraries-and-tools].
+- Use TLS to [secure an etcd cluster][security].
+- [Tune etcd][tuning].
+
+[fulldoc]: ./Documentation/docs.md
+[api]: ./Documentation/dev-guide/api_reference_v3.md
+[clustering]: ./Documentation/op-guide/clustering.md
+[configuration]: ./Documentation/op-guide/configuration.md
+[libraries-and-tools]: ./Documentation/libraries-and-tools.md
+[security]: ./Documentation/op-guide/security.md
+[tuning]: ./Documentation/tuning.md
+
+## Contact
+
+- Mailing list: [etcd-dev](https://groups.google.com/forum/?hl=en#!forum/etcd-dev)
+- IRC: #[etcd](irc://irc.freenode.org:6667/#etcd) on freenode.org
+- Planning/Roadmap: [milestones](https://github.com/coreos/etcd/milestones), [roadmap](./ROADMAP.md)
+- Bugs: [issues](https://github.com/coreos/etcd/issues)
+
+## Contributing
+
+See [CONTRIBUTING](CONTRIBUTING.md) for details on submitting patches and the contribution workflow.
+
+## Reporting bugs
+
+See [reporting bugs](Documentation/reporting_bugs.md) for details about reporting any issue you may encounter.
+
+### License
+
+etcd is under the Apache 2.0 license. See the [LICENSE](LICENSE) file for details.
+
+
diff --git a/vendor/github.com/coreos/etcd/pkg/README.md b/vendor/github.com/coreos/etcd/pkg/README.md
new file mode 100644
index 0000000..d7de4d3
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/README.md
@@ -0,0 +1,2 @@
+pkg/ is a collection of utility packages used by etcd without being specific to etcd itself. A package belongs here
+only if it could possibly be moved out into its own repository in the future.
diff --git a/vendor/github.com/coreos/etcd/pkg/crc/crc.go b/vendor/github.com/coreos/etcd/pkg/crc/crc.go
new file mode 100644
index 0000000..4b998a4
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/crc/crc.go
@@ -0,0 +1,43 @@
+// Copyright 2009 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 crc provides utility function for cyclic redundancy check
+// algorithms.
+package crc
+
+import (
+ "hash"
+ "hash/crc32"
+)
+
+// The size of a CRC-32 checksum in bytes.
+const Size = 4
+
+type digest struct {
+ crc uint32
+ tab *crc32.Table
+}
+
+// New creates a new hash.Hash32 computing the CRC-32 checksum
+// using the polynomial represented by the Table.
+// Modified by xiangli to take a prevcrc.
+func New(prev uint32, tab *crc32.Table) hash.Hash32 { return &digest{prev, tab} }
+
+func (d *digest) Size() int { return Size }
+
+func (d *digest) BlockSize() int { return 1 }
+
+func (d *digest) Reset() { d.crc = 0 }
+
+func (d *digest) Write(p []byte) (n int, err error) {
+ d.crc = crc32.Update(d.crc, d.tab, p)
+ return len(p), nil
+}
+
+func (d *digest) Sum32() uint32 { return d.crc }
+
+func (d *digest) Sum(in []byte) []byte {
+ s := d.Sum32()
+ return append(in, byte(s>>24), byte(s>>16), byte(s>>8), byte(s))
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/dir_unix.go b/vendor/github.com/coreos/etcd/pkg/fileutil/dir_unix.go
new file mode 100644
index 0000000..58a77df
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/dir_unix.go
@@ -0,0 +1,22 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build !windows
+
+package fileutil
+
+import "os"
+
+// OpenDir opens a directory for syncing.
+func OpenDir(path string) (*os.File, error) { return os.Open(path) }
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/dir_windows.go b/vendor/github.com/coreos/etcd/pkg/fileutil/dir_windows.go
new file mode 100644
index 0000000..c123395
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/dir_windows.go
@@ -0,0 +1,46 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build windows
+
+package fileutil
+
+import (
+ "os"
+ "syscall"
+)
+
+// OpenDir opens a directory in windows with write access for syncing.
+func OpenDir(path string) (*os.File, error) {
+ fd, err := openDir(path)
+ if err != nil {
+ return nil, err
+ }
+ return os.NewFile(uintptr(fd), path), nil
+}
+
+func openDir(path string) (fd syscall.Handle, err error) {
+ if len(path) == 0 {
+ return syscall.InvalidHandle, syscall.ERROR_FILE_NOT_FOUND
+ }
+ pathp, err := syscall.UTF16PtrFromString(path)
+ if err != nil {
+ return syscall.InvalidHandle, err
+ }
+ access := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE)
+ sharemode := uint32(syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE)
+ createmode := uint32(syscall.OPEN_EXISTING)
+ fl := uint32(syscall.FILE_FLAG_BACKUP_SEMANTICS)
+ return syscall.CreateFile(pathp, access, sharemode, nil, createmode, fl, 0)
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/fileutil.go b/vendor/github.com/coreos/etcd/pkg/fileutil/fileutil.go
new file mode 100644
index 0000000..9585ed5
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/fileutil.go
@@ -0,0 +1,121 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package fileutil implements utility functions related to files and paths.
+package fileutil
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path"
+ "sort"
+
+ "github.com/coreos/pkg/capnslog"
+)
+
+const (
+ // PrivateFileMode grants owner to read/write a file.
+ PrivateFileMode = 0600
+ // PrivateDirMode grants owner to make/remove files inside the directory.
+ PrivateDirMode = 0700
+)
+
+var (
+ plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "pkg/fileutil")
+)
+
+// IsDirWriteable checks if dir is writable by writing and removing a file
+// to dir. It returns nil if dir is writable.
+func IsDirWriteable(dir string) error {
+ f := path.Join(dir, ".touch")
+ if err := ioutil.WriteFile(f, []byte(""), PrivateFileMode); err != nil {
+ return err
+ }
+ return os.Remove(f)
+}
+
+// ReadDir returns the filenames in the given directory in sorted order.
+func ReadDir(dirpath string) ([]string, error) {
+ dir, err := os.Open(dirpath)
+ if err != nil {
+ return nil, err
+ }
+ defer dir.Close()
+ names, err := dir.Readdirnames(-1)
+ if err != nil {
+ return nil, err
+ }
+ sort.Strings(names)
+ return names, nil
+}
+
+// TouchDirAll is similar to os.MkdirAll. It creates directories with 0700 permission if any directory
+// does not exists. TouchDirAll also ensures the given directory is writable.
+func TouchDirAll(dir string) error {
+ // If path is already a directory, MkdirAll does nothing
+ // and returns nil.
+ err := os.MkdirAll(dir, PrivateDirMode)
+ if err != nil {
+ // if mkdirAll("a/text") and "text" is not
+ // a directory, this will return syscall.ENOTDIR
+ return err
+ }
+ return IsDirWriteable(dir)
+}
+
+// CreateDirAll is similar to TouchDirAll but returns error
+// if the deepest directory was not empty.
+func CreateDirAll(dir string) error {
+ err := TouchDirAll(dir)
+ if err == nil {
+ var ns []string
+ ns, err = ReadDir(dir)
+ if err != nil {
+ return err
+ }
+ if len(ns) != 0 {
+ err = fmt.Errorf("expected %q to be empty, got %q", dir, ns)
+ }
+ }
+ return err
+}
+
+func Exist(name string) bool {
+ _, err := os.Stat(name)
+ return err == nil
+}
+
+// ZeroToEnd zeros a file starting from SEEK_CUR to its SEEK_END. May temporarily
+// shorten the length of the file.
+func ZeroToEnd(f *os.File) error {
+ // TODO: support FALLOC_FL_ZERO_RANGE
+ off, err := f.Seek(0, os.SEEK_CUR)
+ if err != nil {
+ return err
+ }
+ lenf, lerr := f.Seek(0, os.SEEK_END)
+ if lerr != nil {
+ return lerr
+ }
+ if err = f.Truncate(off); err != nil {
+ return err
+ }
+ // make sure blocks remain allocated
+ if err = Preallocate(f, lenf, true); err != nil {
+ return err
+ }
+ _, err = f.Seek(off, os.SEEK_SET)
+ return err
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/lock.go b/vendor/github.com/coreos/etcd/pkg/fileutil/lock.go
new file mode 100644
index 0000000..338627f
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/lock.go
@@ -0,0 +1,26 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package fileutil
+
+import (
+ "errors"
+ "os"
+)
+
+var (
+ ErrLocked = errors.New("fileutil: file already locked")
+)
+
+type LockedFile struct{ *os.File }
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/lock_flock.go b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_flock.go
new file mode 100644
index 0000000..542550b
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_flock.go
@@ -0,0 +1,49 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build !windows,!plan9,!solaris
+
+package fileutil
+
+import (
+ "os"
+ "syscall"
+)
+
+func flockTryLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ f, err := os.OpenFile(path, flag, perm)
+ if err != nil {
+ return nil, err
+ }
+ if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
+ f.Close()
+ if err == syscall.EWOULDBLOCK {
+ err = ErrLocked
+ }
+ return nil, err
+ }
+ return &LockedFile{f}, nil
+}
+
+func flockLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ f, err := os.OpenFile(path, flag, perm)
+ if err != nil {
+ return nil, err
+ }
+ if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
+ f.Close()
+ return nil, err
+ }
+ return &LockedFile{f}, err
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/lock_linux.go b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_linux.go
new file mode 100644
index 0000000..dec25a1
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_linux.go
@@ -0,0 +1,96 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build linux
+
+package fileutil
+
+import (
+ "os"
+ "syscall"
+)
+
+// This used to call syscall.Flock() but that call fails with EBADF on NFS.
+// An alternative is lockf() which works on NFS but that call lets a process lock
+// the same file twice. Instead, use Linux's non-standard open file descriptor
+// locks which will block if the process already holds the file lock.
+//
+// constants from /usr/include/bits/fcntl-linux.h
+const (
+ F_OFD_GETLK = 37
+ F_OFD_SETLK = 37
+ F_OFD_SETLKW = 38
+)
+
+var (
+ wrlck = syscall.Flock_t{
+ Type: syscall.F_WRLCK,
+ Whence: int16(os.SEEK_SET),
+ Start: 0,
+ Len: 0,
+ }
+
+ linuxTryLockFile = flockTryLockFile
+ linuxLockFile = flockLockFile
+)
+
+func init() {
+ // use open file descriptor locks if the system supports it
+ getlk := syscall.Flock_t{Type: syscall.F_RDLCK}
+ if err := syscall.FcntlFlock(0, F_OFD_GETLK, &getlk); err == nil {
+ linuxTryLockFile = ofdTryLockFile
+ linuxLockFile = ofdLockFile
+ }
+}
+
+func TryLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ return linuxTryLockFile(path, flag, perm)
+}
+
+func ofdTryLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ f, err := os.OpenFile(path, flag, perm)
+ if err != nil {
+ return nil, err
+ }
+
+ flock := wrlck
+ if err = syscall.FcntlFlock(f.Fd(), F_OFD_SETLK, &flock); err != nil {
+ f.Close()
+ if err == syscall.EWOULDBLOCK {
+ err = ErrLocked
+ }
+ return nil, err
+ }
+ return &LockedFile{f}, nil
+}
+
+func LockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ return linuxLockFile(path, flag, perm)
+}
+
+func ofdLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ f, err := os.OpenFile(path, flag, perm)
+ if err != nil {
+ return nil, err
+ }
+
+ flock := wrlck
+ err = syscall.FcntlFlock(f.Fd(), F_OFD_SETLKW, &flock)
+
+ if err != nil {
+ f.Close()
+ return nil, err
+ }
+ return &LockedFile{f}, err
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/lock_plan9.go b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_plan9.go
new file mode 100644
index 0000000..fee6a7c
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_plan9.go
@@ -0,0 +1,45 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package fileutil
+
+import (
+ "os"
+ "syscall"
+ "time"
+)
+
+func TryLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ if err := os.Chmod(path, syscall.DMEXCL|PrivateFileMode); err != nil {
+ return nil, err
+ }
+ f, err := os.Open(path, flag, perm)
+ if err != nil {
+ return nil, ErrLocked
+ }
+ return &LockedFile{f}, nil
+}
+
+func LockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ if err := os.Chmod(path, syscall.DMEXCL|PrivateFileMode); err != nil {
+ return nil, err
+ }
+ for {
+ f, err := os.OpenFile(path, flag, perm)
+ if err == nil {
+ return &LockedFile{f}, nil
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/lock_solaris.go b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_solaris.go
new file mode 100644
index 0000000..352ca55
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_solaris.go
@@ -0,0 +1,62 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build solaris
+
+package fileutil
+
+import (
+ "os"
+ "syscall"
+)
+
+func TryLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ var lock syscall.Flock_t
+ lock.Start = 0
+ lock.Len = 0
+ lock.Pid = 0
+ lock.Type = syscall.F_WRLCK
+ lock.Whence = 0
+ lock.Pid = 0
+ f, err := os.OpenFile(path, flag, perm)
+ if err != nil {
+ return nil, err
+ }
+ if err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &lock); err != nil {
+ f.Close()
+ if err == syscall.EAGAIN {
+ err = ErrLocked
+ }
+ return nil, err
+ }
+ return &LockedFile{f}, nil
+}
+
+func LockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ var lock syscall.Flock_t
+ lock.Start = 0
+ lock.Len = 0
+ lock.Pid = 0
+ lock.Type = syscall.F_WRLCK
+ lock.Whence = 0
+ f, err := os.OpenFile(path, flag, perm)
+ if err != nil {
+ return nil, err
+ }
+ if err = syscall.FcntlFlock(f.Fd(), syscall.F_SETLKW, &lock); err != nil {
+ f.Close()
+ return nil, err
+ }
+ return &LockedFile{f}, nil
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/lock_unix.go b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_unix.go
new file mode 100644
index 0000000..ed01164
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_unix.go
@@ -0,0 +1,29 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build !windows,!plan9,!solaris,!linux
+
+package fileutil
+
+import (
+ "os"
+)
+
+func TryLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ return flockTryLockFile(path, flag, perm)
+}
+
+func LockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ return flockLockFile(path, flag, perm)
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/lock_windows.go b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_windows.go
new file mode 100644
index 0000000..8698f4a
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/lock_windows.go
@@ -0,0 +1,125 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build windows
+
+package fileutil
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+var (
+ modkernel32 = syscall.NewLazyDLL("kernel32.dll")
+ procLockFileEx = modkernel32.NewProc("LockFileEx")
+
+ errLocked = errors.New("The process cannot access the file because another process has locked a portion of the file.")
+)
+
+const (
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
+ LOCKFILE_EXCLUSIVE_LOCK = 2
+ LOCKFILE_FAIL_IMMEDIATELY = 1
+
+ // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx
+ errLockViolation syscall.Errno = 0x21
+)
+
+func TryLockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ f, err := open(path, flag, perm)
+ if err != nil {
+ return nil, err
+ }
+ if err := lockFile(syscall.Handle(f.Fd()), LOCKFILE_FAIL_IMMEDIATELY); err != nil {
+ f.Close()
+ return nil, err
+ }
+ return &LockedFile{f}, nil
+}
+
+func LockFile(path string, flag int, perm os.FileMode) (*LockedFile, error) {
+ f, err := open(path, flag, perm)
+ if err != nil {
+ return nil, err
+ }
+ if err := lockFile(syscall.Handle(f.Fd()), 0); err != nil {
+ f.Close()
+ return nil, err
+ }
+ return &LockedFile{f}, nil
+}
+
+func open(path string, flag int, perm os.FileMode) (*os.File, error) {
+ if path == "" {
+ return nil, fmt.Errorf("cannot open empty filename")
+ }
+ var access uint32
+ switch flag {
+ case syscall.O_RDONLY:
+ access = syscall.GENERIC_READ
+ case syscall.O_WRONLY:
+ access = syscall.GENERIC_WRITE
+ case syscall.O_RDWR:
+ access = syscall.GENERIC_READ | syscall.GENERIC_WRITE
+ case syscall.O_WRONLY | syscall.O_CREAT:
+ access = syscall.GENERIC_ALL
+ default:
+ panic(fmt.Errorf("flag %v is not supported", flag))
+ }
+ fd, err := syscall.CreateFile(&(syscall.StringToUTF16(path)[0]),
+ access,
+ syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
+ nil,
+ syscall.OPEN_ALWAYS,
+ syscall.FILE_ATTRIBUTE_NORMAL,
+ 0)
+ if err != nil {
+ return nil, err
+ }
+ return os.NewFile(uintptr(fd), path), nil
+}
+
+func lockFile(fd syscall.Handle, flags uint32) error {
+ var flag uint32 = LOCKFILE_EXCLUSIVE_LOCK
+ flag |= flags
+ if fd == syscall.InvalidHandle {
+ return nil
+ }
+ err := lockFileEx(fd, flag, 1, 0, &syscall.Overlapped{})
+ if err == nil {
+ return nil
+ } else if err.Error() == errLocked.Error() {
+ return ErrLocked
+ } else if err != errLockViolation {
+ return err
+ }
+ return nil
+}
+
+func lockFileEx(h syscall.Handle, flags, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
+ var reserved uint32 = 0
+ r1, _, e1 := syscall.Syscall6(procLockFileEx.Addr(), 6, uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = error(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate.go b/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate.go
new file mode 100644
index 0000000..bb7f028
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate.go
@@ -0,0 +1,47 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package fileutil
+
+import "os"
+
+// Preallocate tries to allocate the space for given
+// file. This operation is only supported on linux by a
+// few filesystems (btrfs, ext4, etc.).
+// If the operation is unsupported, no error will be returned.
+// Otherwise, the error encountered will be returned.
+func Preallocate(f *os.File, sizeInBytes int64, extendFile bool) error {
+ if extendFile {
+ return preallocExtend(f, sizeInBytes)
+ }
+ return preallocFixed(f, sizeInBytes)
+}
+
+func preallocExtendTrunc(f *os.File, sizeInBytes int64) error {
+ curOff, err := f.Seek(0, os.SEEK_CUR)
+ if err != nil {
+ return err
+ }
+ size, err := f.Seek(sizeInBytes, os.SEEK_END)
+ if err != nil {
+ return err
+ }
+ if _, err = f.Seek(curOff, os.SEEK_SET); err != nil {
+ return err
+ }
+ if sizeInBytes > size {
+ return nil
+ }
+ return f.Truncate(sizeInBytes)
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_darwin.go b/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_darwin.go
new file mode 100644
index 0000000..1ed09c5
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_darwin.go
@@ -0,0 +1,43 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build darwin
+
+package fileutil
+
+import (
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+func preallocExtend(f *os.File, sizeInBytes int64) error {
+ if err := preallocFixed(f, sizeInBytes); err != nil {
+ return err
+ }
+ return preallocExtendTrunc(f, sizeInBytes)
+}
+
+func preallocFixed(f *os.File, sizeInBytes int64) error {
+ fstore := &syscall.Fstore_t{
+ Flags: syscall.F_ALLOCATEALL,
+ Posmode: syscall.F_PEOFPOSMODE,
+ Length: sizeInBytes}
+ p := unsafe.Pointer(fstore)
+ _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, f.Fd(), uintptr(syscall.F_PREALLOCATE), uintptr(p))
+ if errno == 0 || errno == syscall.ENOTSUP {
+ return nil
+ }
+ return errno
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_unix.go b/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_unix.go
new file mode 100644
index 0000000..50bd84f
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_unix.go
@@ -0,0 +1,49 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build linux
+
+package fileutil
+
+import (
+ "os"
+ "syscall"
+)
+
+func preallocExtend(f *os.File, sizeInBytes int64) error {
+ // use mode = 0 to change size
+ err := syscall.Fallocate(int(f.Fd()), 0, 0, sizeInBytes)
+ if err != nil {
+ errno, ok := err.(syscall.Errno)
+ // not supported; fallback
+ // fallocate EINTRs frequently in some environments; fallback
+ if ok && (errno == syscall.ENOTSUP || errno == syscall.EINTR) {
+ return preallocExtendTrunc(f, sizeInBytes)
+ }
+ }
+ return err
+}
+
+func preallocFixed(f *os.File, sizeInBytes int64) error {
+ // use mode = 1 to keep size; see FALLOC_FL_KEEP_SIZE
+ err := syscall.Fallocate(int(f.Fd()), 1, 0, sizeInBytes)
+ if err != nil {
+ errno, ok := err.(syscall.Errno)
+ // treat not supported as nil error
+ if ok && errno == syscall.ENOTSUP {
+ return nil
+ }
+ }
+ return err
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_unsupported.go b/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_unsupported.go
new file mode 100644
index 0000000..162fbc5
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/preallocate_unsupported.go
@@ -0,0 +1,25 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build !linux,!darwin
+
+package fileutil
+
+import "os"
+
+func preallocExtend(f *os.File, sizeInBytes int64) error {
+ return preallocExtendTrunc(f, sizeInBytes)
+}
+
+func preallocFixed(f *os.File, sizeInBytes int64) error { return nil }
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/purge.go b/vendor/github.com/coreos/etcd/pkg/fileutil/purge.go
new file mode 100644
index 0000000..53bda0c
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/purge.go
@@ -0,0 +1,78 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package fileutil
+
+import (
+ "os"
+ "path"
+ "sort"
+ "strings"
+ "time"
+)
+
+func PurgeFile(dirname string, suffix string, max uint, interval time.Duration, stop <-chan struct{}) <-chan error {
+ return purgeFile(dirname, suffix, max, interval, stop, nil)
+}
+
+// purgeFile is the internal implementation for PurgeFile which can post purged files to purgec if non-nil.
+func purgeFile(dirname string, suffix string, max uint, interval time.Duration, stop <-chan struct{}, purgec chan<- string) <-chan error {
+ errC := make(chan error, 1)
+ go func() {
+ for {
+ fnames, err := ReadDir(dirname)
+ if err != nil {
+ errC <- err
+ return
+ }
+ newfnames := make([]string, 0)
+ for _, fname := range fnames {
+ if strings.HasSuffix(fname, suffix) {
+ newfnames = append(newfnames, fname)
+ }
+ }
+ sort.Strings(newfnames)
+ fnames = newfnames
+ for len(newfnames) > int(max) {
+ f := path.Join(dirname, newfnames[0])
+ l, err := TryLockFile(f, os.O_WRONLY, PrivateFileMode)
+ if err != nil {
+ break
+ }
+ if err = os.Remove(f); err != nil {
+ errC <- err
+ return
+ }
+ if err = l.Close(); err != nil {
+ plog.Errorf("error unlocking %s when purging file (%v)", l.Name(), err)
+ errC <- err
+ return
+ }
+ plog.Infof("purged file %s successfully", f)
+ newfnames = newfnames[1:]
+ }
+ if purgec != nil {
+ for i := 0; i < len(fnames)-len(newfnames); i++ {
+ purgec <- fnames[i]
+ }
+ }
+ select {
+ case <-time.After(interval):
+ case <-stop:
+ return
+ }
+ }
+ }()
+ return errC
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/sync.go b/vendor/github.com/coreos/etcd/pkg/fileutil/sync.go
new file mode 100644
index 0000000..54dd41f
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/sync.go
@@ -0,0 +1,29 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build !linux,!darwin
+
+package fileutil
+
+import "os"
+
+// Fsync is a wrapper around file.Sync(). Special handling is needed on darwin platform.
+func Fsync(f *os.File) error {
+ return f.Sync()
+}
+
+// Fdatasync is a wrapper around file.Sync(). Special handling is needed on linux platform.
+func Fdatasync(f *os.File) error {
+ return f.Sync()
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/sync_darwin.go b/vendor/github.com/coreos/etcd/pkg/fileutil/sync_darwin.go
new file mode 100644
index 0000000..c2f39bf
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/sync_darwin.go
@@ -0,0 +1,40 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build darwin
+
+package fileutil
+
+import (
+ "os"
+ "syscall"
+)
+
+// Fsync on HFS/OSX flushes the data on to the physical drive but the drive
+// may not write it to the persistent media for quite sometime and it may be
+// written in out-of-order sequence. Using F_FULLFSYNC ensures that the
+// physical drive's buffer will also get flushed to the media.
+func Fsync(f *os.File) error {
+ _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, f.Fd(), uintptr(syscall.F_FULLFSYNC), uintptr(0))
+ if errno == 0 {
+ return nil
+ }
+ return errno
+}
+
+// Fdatasync on darwin platform invokes fcntl(F_FULLFSYNC) for actual persistence
+// on physical drive media.
+func Fdatasync(f *os.File) error {
+ return Fsync(f)
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/fileutil/sync_linux.go b/vendor/github.com/coreos/etcd/pkg/fileutil/sync_linux.go
new file mode 100644
index 0000000..1bbced9
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/fileutil/sync_linux.go
@@ -0,0 +1,34 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build linux
+
+package fileutil
+
+import (
+ "os"
+ "syscall"
+)
+
+// Fsync is a wrapper around file.Sync(). Special handling is needed on darwin platform.
+func Fsync(f *os.File) error {
+ return f.Sync()
+}
+
+// Fdatasync is similar to fsync(), but does not flush modified metadata
+// unless that metadata is needed in order to allow a subsequent data retrieval
+// to be correctly handled.
+func Fdatasync(f *os.File) error {
+ return syscall.Fdatasync(int(f.Fd()))
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/idutil/id.go b/vendor/github.com/coreos/etcd/pkg/idutil/id.go
new file mode 100644
index 0000000..931beb2
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/idutil/id.go
@@ -0,0 +1,78 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package idutil implements utility functions for generating unique,
+// randomized ids.
+package idutil
+
+import (
+ "math"
+ "sync"
+ "time"
+)
+
+const (
+ tsLen = 5 * 8
+ cntLen = 8
+ suffixLen = tsLen + cntLen
+)
+
+// Generator generates unique identifiers based on counters, timestamps, and
+// a node member ID.
+//
+// The initial id is in this format:
+// High order byte is memberID, next 5 bytes are from timestamp,
+// and low order 2 bytes are 0s.
+// | prefix | suffix |
+// | 2 bytes | 5 bytes | 1 byte |
+// | memberID | timestamp | cnt |
+//
+// The timestamp 5 bytes is different when the machine is restart
+// after 1 ms and before 35 years.
+//
+// It increases suffix to generate the next id.
+// The count field may overflow to timestamp field, which is intentional.
+// It helps to extend the event window to 2^56. This doesn't break that
+// id generated after restart is unique because etcd throughput is <<
+// 256req/ms(250k reqs/second).
+type Generator struct {
+ mu sync.Mutex
+ // high order 2 bytes
+ prefix uint64
+ // low order 6 bytes
+ suffix uint64
+}
+
+func NewGenerator(memberID uint16, now time.Time) *Generator {
+ prefix := uint64(memberID) << suffixLen
+ unixMilli := uint64(now.UnixNano()) / uint64(time.Millisecond/time.Nanosecond)
+ suffix := lowbit(unixMilli, tsLen) << cntLen
+ return &Generator{
+ prefix: prefix,
+ suffix: suffix,
+ }
+}
+
+// Next generates a id that is unique.
+func (g *Generator) Next() uint64 {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.suffix++
+ id := g.prefix | lowbit(g.suffix, suffixLen)
+ return id
+}
+
+func lowbit(x uint64, n uint) uint64 {
+ return x & (math.MaxUint64 >> (64 - n))
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/ioutil/pagewriter.go b/vendor/github.com/coreos/etcd/pkg/ioutil/pagewriter.go
new file mode 100644
index 0000000..72de159
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/ioutil/pagewriter.go
@@ -0,0 +1,106 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package ioutil
+
+import (
+ "io"
+)
+
+var defaultBufferBytes = 128 * 1024
+
+// PageWriter implements the io.Writer interface so that writes will
+// either be in page chunks or from flushing.
+type PageWriter struct {
+ w io.Writer
+ // pageOffset tracks the page offset of the base of the buffer
+ pageOffset int
+ // pageBytes is the number of bytes per page
+ pageBytes int
+ // bufferedBytes counts the number of bytes pending for write in the buffer
+ bufferedBytes int
+ // buf holds the write buffer
+ buf []byte
+ // bufWatermarkBytes is the number of bytes the buffer can hold before it needs
+ // to be flushed. It is less than len(buf) so there is space for slack writes
+ // to bring the writer to page alignment.
+ bufWatermarkBytes int
+}
+
+// NewPageWriter creates a new PageWriter. pageBytes is the number of bytes
+// to write per page. pageOffset is the starting offset of io.Writer.
+func NewPageWriter(w io.Writer, pageBytes, pageOffset int) *PageWriter {
+ return &PageWriter{
+ w: w,
+ pageOffset: pageOffset,
+ pageBytes: pageBytes,
+ buf: make([]byte, defaultBufferBytes+pageBytes),
+ bufWatermarkBytes: defaultBufferBytes,
+ }
+}
+
+func (pw *PageWriter) Write(p []byte) (n int, err error) {
+ if len(p)+pw.bufferedBytes <= pw.bufWatermarkBytes {
+ // no overflow
+ copy(pw.buf[pw.bufferedBytes:], p)
+ pw.bufferedBytes += len(p)
+ return len(p), nil
+ }
+ // complete the slack page in the buffer if unaligned
+ slack := pw.pageBytes - ((pw.pageOffset + pw.bufferedBytes) % pw.pageBytes)
+ if slack != pw.pageBytes {
+ partial := slack > len(p)
+ if partial {
+ // not enough data to complete the slack page
+ slack = len(p)
+ }
+ // special case: writing to slack page in buffer
+ copy(pw.buf[pw.bufferedBytes:], p[:slack])
+ pw.bufferedBytes += slack
+ n = slack
+ p = p[slack:]
+ if partial {
+ // avoid forcing an unaligned flush
+ return n, nil
+ }
+ }
+ // buffer contents are now page-aligned; clear out
+ if err = pw.Flush(); err != nil {
+ return n, err
+ }
+ // directly write all complete pages without copying
+ if len(p) > pw.pageBytes {
+ pages := len(p) / pw.pageBytes
+ c, werr := pw.w.Write(p[:pages*pw.pageBytes])
+ n += c
+ if werr != nil {
+ return n, werr
+ }
+ p = p[pages*pw.pageBytes:]
+ }
+ // write remaining tail to buffer
+ c, werr := pw.Write(p)
+ n += c
+ return n, werr
+}
+
+func (pw *PageWriter) Flush() error {
+ if pw.bufferedBytes == 0 {
+ return nil
+ }
+ _, err := pw.w.Write(pw.buf[:pw.bufferedBytes])
+ pw.pageOffset = (pw.pageOffset + pw.bufferedBytes) % pw.pageBytes
+ pw.bufferedBytes = 0
+ return err
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/ioutil/readcloser.go b/vendor/github.com/coreos/etcd/pkg/ioutil/readcloser.go
new file mode 100644
index 0000000..d3efcfe
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/ioutil/readcloser.go
@@ -0,0 +1,66 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package ioutil
+
+import (
+ "fmt"
+ "io"
+)
+
+// ReaderAndCloser implements io.ReadCloser interface by combining
+// reader and closer together.
+type ReaderAndCloser struct {
+ io.Reader
+ io.Closer
+}
+
+var (
+ ErrShortRead = fmt.Errorf("ioutil: short read")
+ ErrExpectEOF = fmt.Errorf("ioutil: expect EOF")
+)
+
+// NewExactReadCloser returns a ReadCloser that returns errors if the underlying
+// reader does not read back exactly the requested number of bytes.
+func NewExactReadCloser(rc io.ReadCloser, totalBytes int64) io.ReadCloser {
+ return &exactReadCloser{rc: rc, totalBytes: totalBytes}
+}
+
+type exactReadCloser struct {
+ rc io.ReadCloser
+ br int64
+ totalBytes int64
+}
+
+func (e *exactReadCloser) Read(p []byte) (int, error) {
+ n, err := e.rc.Read(p)
+ e.br += int64(n)
+ if e.br > e.totalBytes {
+ return 0, ErrExpectEOF
+ }
+ if e.br < e.totalBytes && n == 0 {
+ return 0, ErrShortRead
+ }
+ return n, err
+}
+
+func (e *exactReadCloser) Close() error {
+ if err := e.rc.Close(); err != nil {
+ return err
+ }
+ if e.br < e.totalBytes {
+ return ErrShortRead
+ }
+ return nil
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/ioutil/reader.go b/vendor/github.com/coreos/etcd/pkg/ioutil/reader.go
new file mode 100644
index 0000000..0703ed4
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/ioutil/reader.go
@@ -0,0 +1,40 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package ioutil implements I/O utility functions.
+package ioutil
+
+import "io"
+
+// NewLimitedBufferReader returns a reader that reads from the given reader
+// but limits the amount of data returned to at most n bytes.
+func NewLimitedBufferReader(r io.Reader, n int) io.Reader {
+ return &limitedBufferReader{
+ r: r,
+ n: n,
+ }
+}
+
+type limitedBufferReader struct {
+ r io.Reader
+ n int
+}
+
+func (r *limitedBufferReader) Read(p []byte) (n int, err error) {
+ np := p
+ if len(np) > r.n {
+ np = np[:r.n]
+ }
+ return r.r.Read(np)
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/ioutil/util.go b/vendor/github.com/coreos/etcd/pkg/ioutil/util.go
new file mode 100644
index 0000000..192ad88
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/ioutil/util.go
@@ -0,0 +1,43 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package ioutil
+
+import (
+ "io"
+ "os"
+
+ "github.com/coreos/etcd/pkg/fileutil"
+)
+
+// WriteAndSyncFile behaves just like ioutil.WriteFile in the standard library,
+// but calls Sync before closing the file. WriteAndSyncFile guarantees the data
+// is synced if there is no error returned.
+func WriteAndSyncFile(filename string, data []byte, perm os.FileMode) error {
+ f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
+ if err != nil {
+ return err
+ }
+ n, err := f.Write(data)
+ if err == nil && n < len(data) {
+ err = io.ErrShortWrite
+ }
+ if err == nil {
+ err = fileutil.Fsync(f)
+ }
+ if err1 := f.Close(); err == nil {
+ err = err1
+ }
+ return err
+}
diff --git a/vendor/github.com/coreos/etcd/pkg/pbutil/pbutil.go b/vendor/github.com/coreos/etcd/pkg/pbutil/pbutil.go
new file mode 100644
index 0000000..d70f98d
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/pkg/pbutil/pbutil.go
@@ -0,0 +1,60 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package pbutil defines interfaces for handling Protocol Buffer objects.
+package pbutil
+
+import "github.com/coreos/pkg/capnslog"
+
+var (
+ plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "pkg/pbutil")
+)
+
+type Marshaler interface {
+ Marshal() (data []byte, err error)
+}
+
+type Unmarshaler interface {
+ Unmarshal(data []byte) error
+}
+
+func MustMarshal(m Marshaler) []byte {
+ d, err := m.Marshal()
+ if err != nil {
+ plog.Panicf("marshal should never fail (%v)", err)
+ }
+ return d
+}
+
+func MustUnmarshal(um Unmarshaler, data []byte) {
+ if err := um.Unmarshal(data); err != nil {
+ plog.Panicf("unmarshal should never fail (%v)", err)
+ }
+}
+
+func MaybeUnmarshal(um Unmarshaler, data []byte) bool {
+ if err := um.Unmarshal(data); err != nil {
+ return false
+ }
+ return true
+}
+
+func GetBool(v *bool) (vv bool, set bool) {
+ if v == nil {
+ return false, false
+ }
+ return *v, true
+}
+
+func Boolp(b bool) *bool { return &b }
diff --git a/vendor/github.com/coreos/etcd/raft/README.md b/vendor/github.com/coreos/etcd/raft/README.md
new file mode 100644
index 0000000..a724b95
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/README.md
@@ -0,0 +1,247 @@
+# Raft library
+
+Raft is a protocol with which a cluster of nodes can maintain a replicated state machine.
+The state machine is kept in sync through the use of a replicated log.
+For more details on Raft, see "In Search of an Understandable Consensus Algorithm"
+(https://ramcloud.stanford.edu/raft.pdf) by Diego Ongaro and John Ousterhout.
+
+This Raft library is stable and feature complete. As of 2016, it is **the most widely used** Raft library in production, serving tens of thousands clusters each day. It powers distributed systems such as etcd, Kubernetes, Docker Swarm, Cloud Foundry Diego, CockroachDB, TiDB, Project Calico, Flannel, and more.
+
+Most Raft implementations have a monolithic design, including storage handling, messaging serialization, and network transport. This library instead follows a minimalistic design philosophy by only implementing the core raft algorithm. This minimalism buys flexibility, determinism, and performance.
+
+To keep the codebase small as well as provide flexibility, the library only implements the Raft algorithm; both network and disk IO are left to the user. Library users must implement their own transportation layer for message passing between Raft peers over the wire. Similarly, users must implement their own storage layer to persist the Raft log and state.
+
+In order to easily test the Raft library, its behavior should be deterministic. To achieve this determinism, the library models Raft as a state machine. The state machine takes a `Message` as input. A message can either be a local timer update or a network message sent from a remote peer. The state machine's output is a 3-tuple `{[]Messages, []LogEntries, NextState}` consisting of an array of `Messages`, `log entries`, and `Raft state changes`. For state machines with the same state, the same state machine input should always generate the same state machine output.
+
+A simple example application, _raftexample_, is also available to help illustrate
+how to use this package in practice:
+https://github.com/coreos/etcd/tree/master/contrib/raftexample
+
+# Features
+
+This raft implementation is a full feature implementation of Raft protocol. Features includes:
+
+- Leader election
+- Log replication
+- Log compaction
+- Membership changes
+- Leadership transfer extension
+- Efficient linearizable read-only queries served by both the leader and followers
+ - leader checks with quorum and bypasses Raft log before processing read-only queries
+ - followers asks leader to get a safe read index before processing read-only queries
+- More efficient lease-based linearizable read-only queries served by both the leader and followers
+ - leader bypasses Raft log and processing read-only queries locally
+ - followers asks leader to get a safe read index before processing read-only queries
+ - this approach relies on the clock of the all the machines in raft group
+
+This raft implementation also includes a few optional enhancements:
+
+- Optimistic pipelining to reduce log replication latency
+- Flow control for log replication
+- Batching Raft messages to reduce synchronized network I/O calls
+- Batching log entries to reduce disk synchronized I/O
+- Writing to leader's disk in parallel
+- Internal proposal redirection from followers to leader
+- Automatic stepping down when the leader loses quorum
+
+## Notable Users
+
+- [cockroachdb](https://github.com/cockroachdb/cockroach) A Scalable, Survivable, Strongly-Consistent SQL Database
+- [dgraph](https://github.com/dgraph-io/dgraph) A Scalable, Distributed, Low Latency, High Throughput Graph Database
+- [etcd](https://github.com/coreos/etcd) A distributed reliable key-value store
+- [tikv](https://github.com/pingcap/tikv) A Distributed transactional key value database powered by Rust and Raft
+- [swarmkit](https://github.com/docker/swarmkit) A toolkit for orchestrating distributed systems at any scale.
+
+## Usage
+
+The primary object in raft is a Node. You either start a Node from scratch
+using raft.StartNode or start a Node from some initial state using raft.RestartNode.
+
+To start a three-node cluster
+```go
+ storage := raft.NewMemoryStorage()
+ c := &Config{
+ ID: 0x01,
+ ElectionTick: 10,
+ HeartbeatTick: 1,
+ Storage: storage,
+ MaxSizePerMsg: 4096,
+ MaxInflightMsgs: 256,
+ }
+ // Set peer list to the other nodes in the cluster.
+ // Note that they need to be started separately as well.
+ n := raft.StartNode(c, []raft.Peer{{ID: 0x02}, {ID: 0x03}})
+```
+
+You can start a single node cluster, like so:
+```go
+ // Create storage and config as shown above.
+ // Set peer list to itself, so this node can become the leader of this single-node cluster.
+ peers := []raft.Peer{{ID: 0x01}}
+ n := raft.StartNode(c, peers)
+```
+
+To allow a new node to join this cluster, do not pass in any peers. First, you need add the node to the existing cluster by calling `ProposeConfChange` on any existing node inside the cluster. Then, you can start the node with empty peer list, like so:
+```go
+ // Create storage and config as shown above.
+ n := raft.StartNode(c, nil)
+```
+
+To restart a node from previous state:
+```go
+ storage := raft.NewMemoryStorage()
+
+ // Recover the in-memory storage from persistent snapshot, state and entries.
+ storage.ApplySnapshot(snapshot)
+ storage.SetHardState(state)
+ storage.Append(entries)
+
+ c := &Config{
+ ID: 0x01,
+ ElectionTick: 10,
+ HeartbeatTick: 1,
+ Storage: storage,
+ MaxSizePerMsg: 4096,
+ MaxInflightMsgs: 256,
+ }
+
+ // Restart raft without peer information.
+ // Peer information is already included in the storage.
+ n := raft.RestartNode(c)
+```
+
+Now that you are holding onto a Node you have a few responsibilities:
+
+First, you must read from the Node.Ready() channel and process the updates
+it contains. These steps may be performed in parallel, except as noted in step
+2.
+
+1. Write HardState, Entries, and Snapshot to persistent storage if they are
+not empty. Note that when writing an Entry with Index i, any
+previously-persisted entries with Index >= i must be discarded.
+
+2. Send all Messages to the nodes named in the To field. It is important that
+no messages be sent until the latest HardState has been persisted to disk,
+and all Entries written by any previous Ready batch (Messages may be sent while
+entries from the same batch are being persisted). To reduce the I/O latency, an
+optimization can be applied to make leader write to disk in parallel with its
+followers (as explained at section 10.2.1 in Raft thesis). If any Message has type
+MsgSnap, call Node.ReportSnapshot() after it has been sent (these messages may be
+large). Note: Marshalling messages is not thread-safe; it is important that you
+make sure that no new entries are persisted while marshalling.
+The easiest way to achieve this is to serialise the messages directly inside
+your main raft loop.
+
+3. Apply Snapshot (if any) and CommittedEntries to the state machine.
+If any committed Entry has Type EntryConfChange, call Node.ApplyConfChange()
+to apply it to the node. The configuration change may be cancelled at this point
+by setting the NodeID field to zero before calling ApplyConfChange
+(but ApplyConfChange must be called one way or the other, and the decision to cancel
+must be based solely on the state machine and not external information such as
+the observed health of the node).
+
+4. Call Node.Advance() to signal readiness for the next batch of updates.
+This may be done at any time after step 1, although all updates must be processed
+in the order they were returned by Ready.
+
+Second, all persisted log entries must be made available via an
+implementation of the Storage interface. The provided MemoryStorage
+type can be used for this (if you repopulate its state upon a
+restart), or you can supply your own disk-backed implementation.
+
+Third, when you receive a message from another node, pass it to Node.Step:
+
+```go
+ func recvRaftRPC(ctx context.Context, m raftpb.Message) {
+ n.Step(ctx, m)
+ }
+```
+
+Finally, you need to call `Node.Tick()` at regular intervals (probably
+via a `time.Ticker`). Raft has two important timeouts: heartbeat and the
+election timeout. However, internally to the raft package time is
+represented by an abstract "tick".
+
+The total state machine handling loop will look something like this:
+
+```go
+ for {
+ select {
+ case <-s.Ticker:
+ n.Tick()
+ case rd := <-s.Node.Ready():
+ saveToStorage(rd.State, rd.Entries, rd.Snapshot)
+ send(rd.Messages)
+ if !raft.IsEmptySnap(rd.Snapshot) {
+ processSnapshot(rd.Snapshot)
+ }
+ for _, entry := range rd.CommittedEntries {
+ process(entry)
+ if entry.Type == raftpb.EntryConfChange {
+ var cc raftpb.ConfChange
+ cc.Unmarshal(entry.Data)
+ s.Node.ApplyConfChange(cc)
+ }
+ }
+ s.Node.Advance()
+ case <-s.done:
+ return
+ }
+ }
+```
+
+To propose changes to the state machine from your node take your application
+data, serialize it into a byte slice and call:
+
+```go
+ n.Propose(ctx, data)
+```
+
+If the proposal is committed, data will appear in committed entries with type
+raftpb.EntryNormal. There is no guarantee that a proposed command will be
+committed; you may have to re-propose after a timeout.
+
+To add or remove node in a cluster, build ConfChange struct 'cc' and call:
+
+```go
+ n.ProposeConfChange(ctx, cc)
+```
+
+After config change is committed, some committed entry with type
+raftpb.EntryConfChange will be returned. You must apply it to node through:
+
+```go
+ var cc raftpb.ConfChange
+ cc.Unmarshal(data)
+ n.ApplyConfChange(cc)
+```
+
+Note: An ID represents a unique node in a cluster for all time. A
+given ID MUST be used only once even if the old node has been removed.
+This means that for example IP addresses make poor node IDs since they
+may be reused. Node IDs must be non-zero.
+
+## Implementation notes
+
+This implementation is up to date with the final Raft thesis
+(https://ramcloud.stanford.edu/~ongaro/thesis.pdf), although our
+implementation of the membership change protocol differs somewhat from
+that described in chapter 4. The key invariant that membership changes
+happen one node at a time is preserved, but in our implementation the
+membership change takes effect when its entry is applied, not when it
+is added to the log (so the entry is committed under the old
+membership instead of the new). This is equivalent in terms of safety,
+since the old and new configurations are guaranteed to overlap.
+
+To ensure that we do not attempt to commit two membership changes at
+once by matching log positions (which would be unsafe since they
+should have different quorum requirements), we simply disallow any
+proposed membership change while any uncommitted change appears in
+the leader's log.
+
+This approach introduces a problem when you try to remove a member
+from a two-member cluster: If one of the members dies before the
+other one receives the commit of the confchange entry, then the member
+cannot be removed any more since the cluster cannot make progress.
+For this reason it is highly recommended to use three or more nodes in
+every cluster.
diff --git a/vendor/github.com/coreos/etcd/raft/doc.go b/vendor/github.com/coreos/etcd/raft/doc.go
new file mode 100644
index 0000000..b55c591
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/doc.go
@@ -0,0 +1,300 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/*
+Package raft sends and receives messages in the Protocol Buffer format
+defined in the raftpb package.
+
+Raft is a protocol with which a cluster of nodes can maintain a replicated state machine.
+The state machine is kept in sync through the use of a replicated log.
+For more details on Raft, see "In Search of an Understandable Consensus Algorithm"
+(https://ramcloud.stanford.edu/raft.pdf) by Diego Ongaro and John Ousterhout.
+
+A simple example application, _raftexample_, is also available to help illustrate
+how to use this package in practice:
+https://github.com/coreos/etcd/tree/master/contrib/raftexample
+
+Usage
+
+The primary object in raft is a Node. You either start a Node from scratch
+using raft.StartNode or start a Node from some initial state using raft.RestartNode.
+
+To start a node from scratch:
+
+ storage := raft.NewMemoryStorage()
+ c := &Config{
+ ID: 0x01,
+ ElectionTick: 10,
+ HeartbeatTick: 1,
+ Storage: storage,
+ MaxSizePerMsg: 4096,
+ MaxInflightMsgs: 256,
+ }
+ n := raft.StartNode(c, []raft.Peer{{ID: 0x02}, {ID: 0x03}})
+
+To restart a node from previous state:
+
+ storage := raft.NewMemoryStorage()
+
+ // recover the in-memory storage from persistent
+ // snapshot, state and entries.
+ storage.ApplySnapshot(snapshot)
+ storage.SetHardState(state)
+ storage.Append(entries)
+
+ c := &Config{
+ ID: 0x01,
+ ElectionTick: 10,
+ HeartbeatTick: 1,
+ Storage: storage,
+ MaxSizePerMsg: 4096,
+ MaxInflightMsgs: 256,
+ }
+
+ // restart raft without peer information.
+ // peer information is already included in the storage.
+ n := raft.RestartNode(c)
+
+Now that you are holding onto a Node you have a few responsibilities:
+
+First, you must read from the Node.Ready() channel and process the updates
+it contains. These steps may be performed in parallel, except as noted in step
+2.
+
+1. Write HardState, Entries, and Snapshot to persistent storage if they are
+not empty. Note that when writing an Entry with Index i, any
+previously-persisted entries with Index >= i must be discarded.
+
+2. Send all Messages to the nodes named in the To field. It is important that
+no messages be sent until the latest HardState has been persisted to disk,
+and all Entries written by any previous Ready batch (Messages may be sent while
+entries from the same batch are being persisted). To reduce the I/O latency, an
+optimization can be applied to make leader write to disk in parallel with its
+followers (as explained at section 10.2.1 in Raft thesis). If any Message has type
+MsgSnap, call Node.ReportSnapshot() after it has been sent (these messages may be
+large).
+
+Note: Marshalling messages is not thread-safe; it is important that you
+make sure that no new entries are persisted while marshalling.
+The easiest way to achieve this is to serialise the messages directly inside
+your main raft loop.
+
+3. Apply Snapshot (if any) and CommittedEntries to the state machine.
+If any committed Entry has Type EntryConfChange, call Node.ApplyConfChange()
+to apply it to the node. The configuration change may be cancelled at this point
+by setting the NodeID field to zero before calling ApplyConfChange
+(but ApplyConfChange must be called one way or the other, and the decision to cancel
+must be based solely on the state machine and not external information such as
+the observed health of the node).
+
+4. Call Node.Advance() to signal readiness for the next batch of updates.
+This may be done at any time after step 1, although all updates must be processed
+in the order they were returned by Ready.
+
+Second, all persisted log entries must be made available via an
+implementation of the Storage interface. The provided MemoryStorage
+type can be used for this (if you repopulate its state upon a
+restart), or you can supply your own disk-backed implementation.
+
+Third, when you receive a message from another node, pass it to Node.Step:
+
+ func recvRaftRPC(ctx context.Context, m raftpb.Message) {
+ n.Step(ctx, m)
+ }
+
+Finally, you need to call Node.Tick() at regular intervals (probably
+via a time.Ticker). Raft has two important timeouts: heartbeat and the
+election timeout. However, internally to the raft package time is
+represented by an abstract "tick".
+
+The total state machine handling loop will look something like this:
+
+ for {
+ select {
+ case <-s.Ticker:
+ n.Tick()
+ case rd := <-s.Node.Ready():
+ saveToStorage(rd.State, rd.Entries, rd.Snapshot)
+ send(rd.Messages)
+ if !raft.IsEmptySnap(rd.Snapshot) {
+ processSnapshot(rd.Snapshot)
+ }
+ for _, entry := range rd.CommittedEntries {
+ process(entry)
+ if entry.Type == raftpb.EntryConfChange {
+ var cc raftpb.ConfChange
+ cc.Unmarshal(entry.Data)
+ s.Node.ApplyConfChange(cc)
+ }
+ }
+ s.Node.Advance()
+ case <-s.done:
+ return
+ }
+ }
+
+To propose changes to the state machine from your node take your application
+data, serialize it into a byte slice and call:
+
+ n.Propose(ctx, data)
+
+If the proposal is committed, data will appear in committed entries with type
+raftpb.EntryNormal. There is no guarantee that a proposed command will be
+committed; you may have to re-propose after a timeout.
+
+To add or remove node in a cluster, build ConfChange struct 'cc' and call:
+
+ n.ProposeConfChange(ctx, cc)
+
+After config change is committed, some committed entry with type
+raftpb.EntryConfChange will be returned. You must apply it to node through:
+
+ var cc raftpb.ConfChange
+ cc.Unmarshal(data)
+ n.ApplyConfChange(cc)
+
+Note: An ID represents a unique node in a cluster for all time. A
+given ID MUST be used only once even if the old node has been removed.
+This means that for example IP addresses make poor node IDs since they
+may be reused. Node IDs must be non-zero.
+
+Implementation notes
+
+This implementation is up to date with the final Raft thesis
+(https://ramcloud.stanford.edu/~ongaro/thesis.pdf), although our
+implementation of the membership change protocol differs somewhat from
+that described in chapter 4. The key invariant that membership changes
+happen one node at a time is preserved, but in our implementation the
+membership change takes effect when its entry is applied, not when it
+is added to the log (so the entry is committed under the old
+membership instead of the new). This is equivalent in terms of safety,
+since the old and new configurations are guaranteed to overlap.
+
+To ensure that we do not attempt to commit two membership changes at
+once by matching log positions (which would be unsafe since they
+should have different quorum requirements), we simply disallow any
+proposed membership change while any uncommitted change appears in
+the leader's log.
+
+This approach introduces a problem when you try to remove a member
+from a two-member cluster: If one of the members dies before the
+other one receives the commit of the confchange entry, then the member
+cannot be removed any more since the cluster cannot make progress.
+For this reason it is highly recommended to use three or more nodes in
+every cluster.
+
+MessageType
+
+Package raft sends and receives message in Protocol Buffer format (defined
+in raftpb package). Each state (follower, candidate, leader) implements its
+own 'step' method ('stepFollower', 'stepCandidate', 'stepLeader') when
+advancing with the given raftpb.Message. Each step is determined by its
+raftpb.MessageType. Note that every step is checked by one common method
+'Step' that safety-checks the terms of node and incoming message to prevent
+stale log entries:
+
+ 'MsgHup' is used for election. If a node is a follower or candidate, the
+ 'tick' function in 'raft' struct is set as 'tickElection'. If a follower or
+ candidate has not received any heartbeat before the election timeout, it
+ passes 'MsgHup' to its Step method and becomes (or remains) a candidate to
+ start a new election.
+
+ 'MsgBeat' is an internal type that signals the leader to send a heartbeat of
+ the 'MsgHeartbeat' type. If a node is a leader, the 'tick' function in
+ the 'raft' struct is set as 'tickHeartbeat', and triggers the leader to
+ send periodic 'MsgHeartbeat' messages to its followers.
+
+ 'MsgProp' proposes to append data to its log entries. This is a special
+ type to redirect proposals to leader. Therefore, send method overwrites
+ raftpb.Message's term with its HardState's term to avoid attaching its
+ local term to 'MsgProp'. When 'MsgProp' is passed to the leader's 'Step'
+ method, the leader first calls the 'appendEntry' method to append entries
+ to its log, and then calls 'bcastAppend' method to send those entries to
+ its peers. When passed to candidate, 'MsgProp' is dropped. When passed to
+ follower, 'MsgProp' is stored in follower's mailbox(msgs) by the send
+ method. It is stored with sender's ID and later forwarded to leader by
+ rafthttp package.
+
+ 'MsgApp' contains log entries to replicate. A leader calls bcastAppend,
+ which calls sendAppend, which sends soon-to-be-replicated logs in 'MsgApp'
+ type. When 'MsgApp' is passed to candidate's Step method, candidate reverts
+ back to follower, because it indicates that there is a valid leader sending
+ 'MsgApp' messages. Candidate and follower respond to this message in
+ 'MsgAppResp' type.
+
+ 'MsgAppResp' is response to log replication request('MsgApp'). When
+ 'MsgApp' is passed to candidate or follower's Step method, it responds by
+ calling 'handleAppendEntries' method, which sends 'MsgAppResp' to raft
+ mailbox.
+
+ 'MsgVote' requests votes for election. When a node is a follower or
+ candidate and 'MsgHup' is passed to its Step method, then the node calls
+ 'campaign' method to campaign itself to become a leader. Once 'campaign'
+ method is called, the node becomes candidate and sends 'MsgVote' to peers
+ in cluster to request votes. When passed to leader or candidate's Step
+ method and the message's Term is lower than leader's or candidate's,
+ 'MsgVote' will be rejected ('MsgVoteResp' is returned with Reject true).
+ If leader or candidate receives 'MsgVote' with higher term, it will revert
+ back to follower. When 'MsgVote' is passed to follower, it votes for the
+ sender only when sender's last term is greater than MsgVote's term or
+ sender's last term is equal to MsgVote's term but sender's last committed
+ index is greater than or equal to follower's.
+
+ 'MsgVoteResp' contains responses from voting request. When 'MsgVoteResp' is
+ passed to candidate, the candidate calculates how many votes it has won. If
+ it's more than majority (quorum), it becomes leader and calls 'bcastAppend'.
+ If candidate receives majority of votes of denials, it reverts back to
+ follower.
+
+ 'MsgPreVote' and 'MsgPreVoteResp' are used in an optional two-phase election
+ protocol. When Config.PreVote is true, a pre-election is carried out first
+ (using the same rules as a regular election), and no node increases its term
+ number unless the pre-election indicates that the campaigining node would win.
+ This minimizes disruption when a partitioned node rejoins the cluster.
+
+ 'MsgSnap' requests to install a snapshot message. When a node has just
+ become a leader or the leader receives 'MsgProp' message, it calls
+ 'bcastAppend' method, which then calls 'sendAppend' method to each
+ follower. In 'sendAppend', if a leader fails to get term or entries,
+ the leader requests snapshot by sending 'MsgSnap' type message.
+
+ 'MsgSnapStatus' tells the result of snapshot install message. When a
+ follower rejected 'MsgSnap', it indicates the snapshot request with
+ 'MsgSnap' had failed from network issues which causes the network layer
+ to fail to send out snapshots to its followers. Then leader considers
+ follower's progress as probe. When 'MsgSnap' were not rejected, it
+ indicates that the snapshot succeeded and the leader sets follower's
+ progress to probe and resumes its log replication.
+
+ 'MsgHeartbeat' sends heartbeat from leader. When 'MsgHeartbeat' is passed
+ to candidate and message's term is higher than candidate's, the candidate
+ reverts back to follower and updates its committed index from the one in
+ this heartbeat. And it sends the message to its mailbox. When
+ 'MsgHeartbeat' is passed to follower's Step method and message's term is
+ higher than follower's, the follower updates its leaderID with the ID
+ from the message.
+
+ 'MsgHeartbeatResp' is a response to 'MsgHeartbeat'. When 'MsgHeartbeatResp'
+ is passed to leader's Step method, the leader knows which follower
+ responded. And only when the leader's last committed index is greater than
+ follower's Match index, the leader runs 'sendAppend` method.
+
+ 'MsgUnreachable' tells that request(message) wasn't delivered. When
+ 'MsgUnreachable' is passed to leader's Step method, the leader discovers
+ that the follower that sent this 'MsgUnreachable' is not reachable, often
+ indicating 'MsgApp' is lost. When follower's progress state is replicate,
+ the leader sets it back to probe.
+
+*/
+package raft
diff --git a/vendor/github.com/coreos/etcd/raft/log.go b/vendor/github.com/coreos/etcd/raft/log.go
new file mode 100644
index 0000000..c3036d3
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/log.go
@@ -0,0 +1,358 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import (
+ "fmt"
+ "log"
+
+ pb "github.com/coreos/etcd/raft/raftpb"
+)
+
+type raftLog struct {
+ // storage contains all stable entries since the last snapshot.
+ storage Storage
+
+ // unstable contains all unstable entries and snapshot.
+ // they will be saved into storage.
+ unstable unstable
+
+ // committed is the highest log position that is known to be in
+ // stable storage on a quorum of nodes.
+ committed uint64
+ // applied is the highest log position that the application has
+ // been instructed to apply to its state machine.
+ // Invariant: applied <= committed
+ applied uint64
+
+ logger Logger
+}
+
+// newLog returns log using the given storage. It recovers the log to the state
+// that it just commits and applies the latest snapshot.
+func newLog(storage Storage, logger Logger) *raftLog {
+ if storage == nil {
+ log.Panic("storage must not be nil")
+ }
+ log := &raftLog{
+ storage: storage,
+ logger: logger,
+ }
+ firstIndex, err := storage.FirstIndex()
+ if err != nil {
+ panic(err) // TODO(bdarnell)
+ }
+ lastIndex, err := storage.LastIndex()
+ if err != nil {
+ panic(err) // TODO(bdarnell)
+ }
+ log.unstable.offset = lastIndex + 1
+ log.unstable.logger = logger
+ // Initialize our committed and applied pointers to the time of the last compaction.
+ log.committed = firstIndex - 1
+ log.applied = firstIndex - 1
+
+ return log
+}
+
+func (l *raftLog) String() string {
+ return fmt.Sprintf("committed=%d, applied=%d, unstable.offset=%d, len(unstable.Entries)=%d", l.committed, l.applied, l.unstable.offset, len(l.unstable.entries))
+}
+
+// maybeAppend returns (0, false) if the entries cannot be appended. Otherwise,
+// it returns (last index of new entries, true).
+func (l *raftLog) maybeAppend(index, logTerm, committed uint64, ents ...pb.Entry) (lastnewi uint64, ok bool) {
+ if l.matchTerm(index, logTerm) {
+ lastnewi = index + uint64(len(ents))
+ ci := l.findConflict(ents)
+ switch {
+ case ci == 0:
+ case ci <= l.committed:
+ l.logger.Panicf("entry %d conflict with committed entry [committed(%d)]", ci, l.committed)
+ default:
+ offset := index + 1
+ l.append(ents[ci-offset:]...)
+ }
+ l.commitTo(min(committed, lastnewi))
+ return lastnewi, true
+ }
+ return 0, false
+}
+
+func (l *raftLog) append(ents ...pb.Entry) uint64 {
+ if len(ents) == 0 {
+ return l.lastIndex()
+ }
+ if after := ents[0].Index - 1; after < l.committed {
+ l.logger.Panicf("after(%d) is out of range [committed(%d)]", after, l.committed)
+ }
+ l.unstable.truncateAndAppend(ents)
+ return l.lastIndex()
+}
+
+// findConflict finds the index of the conflict.
+// It returns the first pair of conflicting entries between the existing
+// entries and the given entries, if there are any.
+// If there is no conflicting entries, and the existing entries contains
+// all the given entries, zero will be returned.
+// If there is no conflicting entries, but the given entries contains new
+// entries, the index of the first new entry will be returned.
+// An entry is considered to be conflicting if it has the same index but
+// a different term.
+// The first entry MUST have an index equal to the argument 'from'.
+// The index of the given entries MUST be continuously increasing.
+func (l *raftLog) findConflict(ents []pb.Entry) uint64 {
+ for _, ne := range ents {
+ if !l.matchTerm(ne.Index, ne.Term) {
+ if ne.Index <= l.lastIndex() {
+ l.logger.Infof("found conflict at index %d [existing term: %d, conflicting term: %d]",
+ ne.Index, l.zeroTermOnErrCompacted(l.term(ne.Index)), ne.Term)
+ }
+ return ne.Index
+ }
+ }
+ return 0
+}
+
+func (l *raftLog) unstableEntries() []pb.Entry {
+ if len(l.unstable.entries) == 0 {
+ return nil
+ }
+ return l.unstable.entries
+}
+
+// nextEnts returns all the available entries for execution.
+// If applied is smaller than the index of snapshot, it returns all committed
+// entries after the index of snapshot.
+func (l *raftLog) nextEnts() (ents []pb.Entry) {
+ off := max(l.applied+1, l.firstIndex())
+ if l.committed+1 > off {
+ ents, err := l.slice(off, l.committed+1, noLimit)
+ if err != nil {
+ l.logger.Panicf("unexpected error when getting unapplied entries (%v)", err)
+ }
+ return ents
+ }
+ return nil
+}
+
+// hasNextEnts returns if there is any available entries for execution. This
+// is a fast check without heavy raftLog.slice() in raftLog.nextEnts().
+func (l *raftLog) hasNextEnts() bool {
+ off := max(l.applied+1, l.firstIndex())
+ return l.committed+1 > off
+}
+
+func (l *raftLog) snapshot() (pb.Snapshot, error) {
+ if l.unstable.snapshot != nil {
+ return *l.unstable.snapshot, nil
+ }
+ return l.storage.Snapshot()
+}
+
+func (l *raftLog) firstIndex() uint64 {
+ if i, ok := l.unstable.maybeFirstIndex(); ok {
+ return i
+ }
+ index, err := l.storage.FirstIndex()
+ if err != nil {
+ panic(err) // TODO(bdarnell)
+ }
+ return index
+}
+
+func (l *raftLog) lastIndex() uint64 {
+ if i, ok := l.unstable.maybeLastIndex(); ok {
+ return i
+ }
+ i, err := l.storage.LastIndex()
+ if err != nil {
+ panic(err) // TODO(bdarnell)
+ }
+ return i
+}
+
+func (l *raftLog) commitTo(tocommit uint64) {
+ // never decrease commit
+ if l.committed < tocommit {
+ if l.lastIndex() < tocommit {
+ l.logger.Panicf("tocommit(%d) is out of range [lastIndex(%d)]. Was the raft log corrupted, truncated, or lost?", tocommit, l.lastIndex())
+ }
+ l.committed = tocommit
+ }
+}
+
+func (l *raftLog) appliedTo(i uint64) {
+ if i == 0 {
+ return
+ }
+ if l.committed < i || i < l.applied {
+ l.logger.Panicf("applied(%d) is out of range [prevApplied(%d), committed(%d)]", i, l.applied, l.committed)
+ }
+ l.applied = i
+}
+
+func (l *raftLog) stableTo(i, t uint64) { l.unstable.stableTo(i, t) }
+
+func (l *raftLog) stableSnapTo(i uint64) { l.unstable.stableSnapTo(i) }
+
+func (l *raftLog) lastTerm() uint64 {
+ t, err := l.term(l.lastIndex())
+ if err != nil {
+ l.logger.Panicf("unexpected error when getting the last term (%v)", err)
+ }
+ return t
+}
+
+func (l *raftLog) term(i uint64) (uint64, error) {
+ // the valid term range is [index of dummy entry, last index]
+ dummyIndex := l.firstIndex() - 1
+ if i < dummyIndex || i > l.lastIndex() {
+ // TODO: return an error instead?
+ return 0, nil
+ }
+
+ if t, ok := l.unstable.maybeTerm(i); ok {
+ return t, nil
+ }
+
+ t, err := l.storage.Term(i)
+ if err == nil {
+ return t, nil
+ }
+ if err == ErrCompacted || err == ErrUnavailable {
+ return 0, err
+ }
+ panic(err) // TODO(bdarnell)
+}
+
+func (l *raftLog) entries(i, maxsize uint64) ([]pb.Entry, error) {
+ if i > l.lastIndex() {
+ return nil, nil
+ }
+ return l.slice(i, l.lastIndex()+1, maxsize)
+}
+
+// allEntries returns all entries in the log.
+func (l *raftLog) allEntries() []pb.Entry {
+ ents, err := l.entries(l.firstIndex(), noLimit)
+ if err == nil {
+ return ents
+ }
+ if err == ErrCompacted { // try again if there was a racing compaction
+ return l.allEntries()
+ }
+ // TODO (xiangli): handle error?
+ panic(err)
+}
+
+// isUpToDate determines if the given (lastIndex,term) log is more up-to-date
+// by comparing the index and term of the last entries in the existing logs.
+// If the logs have last entries with different terms, then the log with the
+// later term is more up-to-date. If the logs end with the same term, then
+// whichever log has the larger lastIndex is more up-to-date. If the logs are
+// the same, the given log is up-to-date.
+func (l *raftLog) isUpToDate(lasti, term uint64) bool {
+ return term > l.lastTerm() || (term == l.lastTerm() && lasti >= l.lastIndex())
+}
+
+func (l *raftLog) matchTerm(i, term uint64) bool {
+ t, err := l.term(i)
+ if err != nil {
+ return false
+ }
+ return t == term
+}
+
+func (l *raftLog) maybeCommit(maxIndex, term uint64) bool {
+ if maxIndex > l.committed && l.zeroTermOnErrCompacted(l.term(maxIndex)) == term {
+ l.commitTo(maxIndex)
+ return true
+ }
+ return false
+}
+
+func (l *raftLog) restore(s pb.Snapshot) {
+ l.logger.Infof("log [%s] starts to restore snapshot [index: %d, term: %d]", l, s.Metadata.Index, s.Metadata.Term)
+ l.committed = s.Metadata.Index
+ l.unstable.restore(s)
+}
+
+// slice returns a slice of log entries from lo through hi-1, inclusive.
+func (l *raftLog) slice(lo, hi, maxSize uint64) ([]pb.Entry, error) {
+ err := l.mustCheckOutOfBounds(lo, hi)
+ if err != nil {
+ return nil, err
+ }
+ if lo == hi {
+ return nil, nil
+ }
+ var ents []pb.Entry
+ if lo < l.unstable.offset {
+ storedEnts, err := l.storage.Entries(lo, min(hi, l.unstable.offset), maxSize)
+ if err == ErrCompacted {
+ return nil, err
+ } else if err == ErrUnavailable {
+ l.logger.Panicf("entries[%d:%d) is unavailable from storage", lo, min(hi, l.unstable.offset))
+ } else if err != nil {
+ panic(err) // TODO(bdarnell)
+ }
+
+ // check if ents has reached the size limitation
+ if uint64(len(storedEnts)) < min(hi, l.unstable.offset)-lo {
+ return storedEnts, nil
+ }
+
+ ents = storedEnts
+ }
+ if hi > l.unstable.offset {
+ unstable := l.unstable.slice(max(lo, l.unstable.offset), hi)
+ if len(ents) > 0 {
+ ents = append([]pb.Entry{}, ents...)
+ ents = append(ents, unstable...)
+ } else {
+ ents = unstable
+ }
+ }
+ return limitSize(ents, maxSize), nil
+}
+
+// l.firstIndex <= lo <= hi <= l.firstIndex + len(l.entries)
+func (l *raftLog) mustCheckOutOfBounds(lo, hi uint64) error {
+ if lo > hi {
+ l.logger.Panicf("invalid slice %d > %d", lo, hi)
+ }
+ fi := l.firstIndex()
+ if lo < fi {
+ return ErrCompacted
+ }
+
+ length := l.lastIndex() + 1 - fi
+ if lo < fi || hi > fi+length {
+ l.logger.Panicf("slice[%d,%d) out of bound [%d,%d]", lo, hi, fi, l.lastIndex())
+ }
+ return nil
+}
+
+func (l *raftLog) zeroTermOnErrCompacted(t uint64, err error) uint64 {
+ if err == nil {
+ return t
+ }
+ if err == ErrCompacted {
+ return 0
+ }
+ l.logger.Panicf("unexpected error (%v)", err)
+ return 0
+}
diff --git a/vendor/github.com/coreos/etcd/raft/log_unstable.go b/vendor/github.com/coreos/etcd/raft/log_unstable.go
new file mode 100644
index 0000000..8ae301c
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/log_unstable.go
@@ -0,0 +1,139 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import pb "github.com/coreos/etcd/raft/raftpb"
+
+// unstable.entries[i] has raft log position i+unstable.offset.
+// Note that unstable.offset may be less than the highest log
+// position in storage; this means that the next write to storage
+// might need to truncate the log before persisting unstable.entries.
+type unstable struct {
+ // the incoming unstable snapshot, if any.
+ snapshot *pb.Snapshot
+ // all entries that have not yet been written to storage.
+ entries []pb.Entry
+ offset uint64
+
+ logger Logger
+}
+
+// maybeFirstIndex returns the index of the first possible entry in entries
+// if it has a snapshot.
+func (u *unstable) maybeFirstIndex() (uint64, bool) {
+ if u.snapshot != nil {
+ return u.snapshot.Metadata.Index + 1, true
+ }
+ return 0, false
+}
+
+// maybeLastIndex returns the last index if it has at least one
+// unstable entry or snapshot.
+func (u *unstable) maybeLastIndex() (uint64, bool) {
+ if l := len(u.entries); l != 0 {
+ return u.offset + uint64(l) - 1, true
+ }
+ if u.snapshot != nil {
+ return u.snapshot.Metadata.Index, true
+ }
+ return 0, false
+}
+
+// maybeTerm returns the term of the entry at index i, if there
+// is any.
+func (u *unstable) maybeTerm(i uint64) (uint64, bool) {
+ if i < u.offset {
+ if u.snapshot == nil {
+ return 0, false
+ }
+ if u.snapshot.Metadata.Index == i {
+ return u.snapshot.Metadata.Term, true
+ }
+ return 0, false
+ }
+
+ last, ok := u.maybeLastIndex()
+ if !ok {
+ return 0, false
+ }
+ if i > last {
+ return 0, false
+ }
+ return u.entries[i-u.offset].Term, true
+}
+
+func (u *unstable) stableTo(i, t uint64) {
+ gt, ok := u.maybeTerm(i)
+ if !ok {
+ return
+ }
+ // if i < offset, term is matched with the snapshot
+ // only update the unstable entries if term is matched with
+ // an unstable entry.
+ if gt == t && i >= u.offset {
+ u.entries = u.entries[i+1-u.offset:]
+ u.offset = i + 1
+ }
+}
+
+func (u *unstable) stableSnapTo(i uint64) {
+ if u.snapshot != nil && u.snapshot.Metadata.Index == i {
+ u.snapshot = nil
+ }
+}
+
+func (u *unstable) restore(s pb.Snapshot) {
+ u.offset = s.Metadata.Index + 1
+ u.entries = nil
+ u.snapshot = &s
+}
+
+func (u *unstable) truncateAndAppend(ents []pb.Entry) {
+ after := ents[0].Index
+ switch {
+ case after == u.offset+uint64(len(u.entries)):
+ // after is the next index in the u.entries
+ // directly append
+ u.entries = append(u.entries, ents...)
+ case after <= u.offset:
+ u.logger.Infof("replace the unstable entries from index %d", after)
+ // The log is being truncated to before our current offset
+ // portion, so set the offset and replace the entries
+ u.offset = after
+ u.entries = ents
+ default:
+ // truncate to after and copy to u.entries
+ // then append
+ u.logger.Infof("truncate the unstable entries before index %d", after)
+ u.entries = append([]pb.Entry{}, u.slice(u.offset, after)...)
+ u.entries = append(u.entries, ents...)
+ }
+}
+
+func (u *unstable) slice(lo uint64, hi uint64) []pb.Entry {
+ u.mustCheckOutOfBounds(lo, hi)
+ return u.entries[lo-u.offset : hi-u.offset]
+}
+
+// u.offset <= lo <= hi <= u.offset+len(u.offset)
+func (u *unstable) mustCheckOutOfBounds(lo, hi uint64) {
+ if lo > hi {
+ u.logger.Panicf("invalid unstable.slice %d > %d", lo, hi)
+ }
+ upper := u.offset + uint64(len(u.entries))
+ if lo < u.offset || hi > upper {
+ u.logger.Panicf("unstable.slice[%d,%d) out of bound [%d,%d]", lo, hi, u.offset, upper)
+ }
+}
diff --git a/vendor/github.com/coreos/etcd/raft/logger.go b/vendor/github.com/coreos/etcd/raft/logger.go
new file mode 100644
index 0000000..92e55b3
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/logger.go
@@ -0,0 +1,126 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "os"
+)
+
+type Logger interface {
+ Debug(v ...interface{})
+ Debugf(format string, v ...interface{})
+
+ Error(v ...interface{})
+ Errorf(format string, v ...interface{})
+
+ Info(v ...interface{})
+ Infof(format string, v ...interface{})
+
+ Warning(v ...interface{})
+ Warningf(format string, v ...interface{})
+
+ Fatal(v ...interface{})
+ Fatalf(format string, v ...interface{})
+
+ Panic(v ...interface{})
+ Panicf(format string, v ...interface{})
+}
+
+func SetLogger(l Logger) { raftLogger = l }
+
+var (
+ defaultLogger = &DefaultLogger{Logger: log.New(os.Stderr, "raft", log.LstdFlags)}
+ discardLogger = &DefaultLogger{Logger: log.New(ioutil.Discard, "", 0)}
+ raftLogger = Logger(defaultLogger)
+)
+
+const (
+ calldepth = 2
+)
+
+// DefaultLogger is a default implementation of the Logger interface.
+type DefaultLogger struct {
+ *log.Logger
+ debug bool
+}
+
+func (l *DefaultLogger) EnableTimestamps() {
+ l.SetFlags(l.Flags() | log.Ldate | log.Ltime)
+}
+
+func (l *DefaultLogger) EnableDebug() {
+ l.debug = true
+}
+
+func (l *DefaultLogger) Debug(v ...interface{}) {
+ if l.debug {
+ l.Output(calldepth, header("DEBUG", fmt.Sprint(v...)))
+ }
+}
+
+func (l *DefaultLogger) Debugf(format string, v ...interface{}) {
+ if l.debug {
+ l.Output(calldepth, header("DEBUG", fmt.Sprintf(format, v...)))
+ }
+}
+
+func (l *DefaultLogger) Info(v ...interface{}) {
+ l.Output(calldepth, header("INFO", fmt.Sprint(v...)))
+}
+
+func (l *DefaultLogger) Infof(format string, v ...interface{}) {
+ l.Output(calldepth, header("INFO", fmt.Sprintf(format, v...)))
+}
+
+func (l *DefaultLogger) Error(v ...interface{}) {
+ l.Output(calldepth, header("ERROR", fmt.Sprint(v...)))
+}
+
+func (l *DefaultLogger) Errorf(format string, v ...interface{}) {
+ l.Output(calldepth, header("ERROR", fmt.Sprintf(format, v...)))
+}
+
+func (l *DefaultLogger) Warning(v ...interface{}) {
+ l.Output(calldepth, header("WARN", fmt.Sprint(v...)))
+}
+
+func (l *DefaultLogger) Warningf(format string, v ...interface{}) {
+ l.Output(calldepth, header("WARN", fmt.Sprintf(format, v...)))
+}
+
+func (l *DefaultLogger) Fatal(v ...interface{}) {
+ l.Output(calldepth, header("FATAL", fmt.Sprint(v...)))
+ os.Exit(1)
+}
+
+func (l *DefaultLogger) Fatalf(format string, v ...interface{}) {
+ l.Output(calldepth, header("FATAL", fmt.Sprintf(format, v...)))
+ os.Exit(1)
+}
+
+func (l *DefaultLogger) Panic(v ...interface{}) {
+ l.Logger.Panic(v)
+}
+
+func (l *DefaultLogger) Panicf(format string, v ...interface{}) {
+ l.Logger.Panicf(format, v...)
+}
+
+func header(lvl, msg string) string {
+ return fmt.Sprintf("%s: %s", lvl, msg)
+}
diff --git a/vendor/github.com/coreos/etcd/raft/node.go b/vendor/github.com/coreos/etcd/raft/node.go
new file mode 100644
index 0000000..c8410fd
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/node.go
@@ -0,0 +1,521 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import (
+ "errors"
+
+ pb "github.com/coreos/etcd/raft/raftpb"
+ "golang.org/x/net/context"
+)
+
+type SnapshotStatus int
+
+const (
+ SnapshotFinish SnapshotStatus = 1
+ SnapshotFailure SnapshotStatus = 2
+)
+
+var (
+ emptyState = pb.HardState{}
+
+ // ErrStopped is returned by methods on Nodes that have been stopped.
+ ErrStopped = errors.New("raft: stopped")
+)
+
+// SoftState provides state that is useful for logging and debugging.
+// The state is volatile and does not need to be persisted to the WAL.
+type SoftState struct {
+ Lead uint64 // must use atomic operations to access; keep 64-bit aligned.
+ RaftState StateType
+}
+
+func (a *SoftState) equal(b *SoftState) bool {
+ return a.Lead == b.Lead && a.RaftState == b.RaftState
+}
+
+// Ready encapsulates the entries and messages that are ready to read,
+// be saved to stable storage, committed or sent to other peers.
+// All fields in Ready are read-only.
+type Ready struct {
+ // The current volatile state of a Node.
+ // SoftState will be nil if there is no update.
+ // It is not required to consume or store SoftState.
+ *SoftState
+
+ // The current state of a Node to be saved to stable storage BEFORE
+ // Messages are sent.
+ // HardState will be equal to empty state if there is no update.
+ pb.HardState
+
+ // ReadStates can be used for node to serve linearizable read requests locally
+ // when its applied index is greater than the index in ReadState.
+ // Note that the readState will be returned when raft receives msgReadIndex.
+ // The returned is only valid for the request that requested to read.
+ ReadStates []ReadState
+
+ // Entries specifies entries to be saved to stable storage BEFORE
+ // Messages are sent.
+ Entries []pb.Entry
+
+ // Snapshot specifies the snapshot to be saved to stable storage.
+ Snapshot pb.Snapshot
+
+ // CommittedEntries specifies entries to be committed to a
+ // store/state-machine. These have previously been committed to stable
+ // store.
+ CommittedEntries []pb.Entry
+
+ // Messages specifies outbound messages to be sent AFTER Entries are
+ // committed to stable storage.
+ // If it contains a MsgSnap message, the application MUST report back to raft
+ // when the snapshot has been received or has failed by calling ReportSnapshot.
+ Messages []pb.Message
+}
+
+func isHardStateEqual(a, b pb.HardState) bool {
+ return a.Term == b.Term && a.Vote == b.Vote && a.Commit == b.Commit
+}
+
+// IsEmptyHardState returns true if the given HardState is empty.
+func IsEmptyHardState(st pb.HardState) bool {
+ return isHardStateEqual(st, emptyState)
+}
+
+// IsEmptySnap returns true if the given Snapshot is empty.
+func IsEmptySnap(sp pb.Snapshot) bool {
+ return sp.Metadata.Index == 0
+}
+
+func (rd Ready) containsUpdates() bool {
+ return rd.SoftState != nil || !IsEmptyHardState(rd.HardState) ||
+ !IsEmptySnap(rd.Snapshot) || len(rd.Entries) > 0 ||
+ len(rd.CommittedEntries) > 0 || len(rd.Messages) > 0 || len(rd.ReadStates) != 0
+}
+
+// Node represents a node in a raft cluster.
+type Node interface {
+ // Tick increments the internal logical clock for the Node by a single tick. Election
+ // timeouts and heartbeat timeouts are in units of ticks.
+ Tick()
+ // Campaign causes the Node to transition to candidate state and start campaigning to become leader.
+ Campaign(ctx context.Context) error
+ // Propose proposes that data be appended to the log.
+ Propose(ctx context.Context, data []byte) error
+ // ProposeConfChange proposes config change.
+ // At most one ConfChange can be in the process of going through consensus.
+ // Application needs to call ApplyConfChange when applying EntryConfChange type entry.
+ ProposeConfChange(ctx context.Context, cc pb.ConfChange) error
+ // Step advances the state machine using the given message. ctx.Err() will be returned, if any.
+ Step(ctx context.Context, msg pb.Message) error
+
+ // Ready returns a channel that returns the current point-in-time state.
+ // Users of the Node must call Advance after retrieving the state returned by Ready.
+ //
+ // NOTE: No committed entries from the next Ready may be applied until all committed entries
+ // and snapshots from the previous one have finished.
+ Ready() <-chan Ready
+
+ // Advance notifies the Node that the application has saved progress up to the last Ready.
+ // It prepares the node to return the next available Ready.
+ //
+ // The application should generally call Advance after it applies the entries in last Ready.
+ //
+ // However, as an optimization, the application may call Advance while it is applying the
+ // commands. For example. when the last Ready contains a snapshot, the application might take
+ // a long time to apply the snapshot data. To continue receiving Ready without blocking raft
+ // progress, it can call Advance before finishing applying the last ready.
+ Advance()
+ // ApplyConfChange applies config change to the local node.
+ // Returns an opaque ConfState protobuf which must be recorded
+ // in snapshots. Will never return nil; it returns a pointer only
+ // to match MemoryStorage.Compact.
+ ApplyConfChange(cc pb.ConfChange) *pb.ConfState
+
+ // TransferLeadership attempts to transfer leadership to the given transferee.
+ TransferLeadership(ctx context.Context, lead, transferee uint64)
+
+ // ReadIndex request a read state. The read state will be set in the ready.
+ // Read state has a read index. Once the application advances further than the read
+ // index, any linearizable read requests issued before the read request can be
+ // processed safely. The read state will have the same rctx attached.
+ ReadIndex(ctx context.Context, rctx []byte) error
+
+ // Status returns the current status of the raft state machine.
+ Status() Status
+ // ReportUnreachable reports the given node is not reachable for the last send.
+ ReportUnreachable(id uint64)
+ // ReportSnapshot reports the status of the sent snapshot.
+ ReportSnapshot(id uint64, status SnapshotStatus)
+ // Stop performs any necessary termination of the Node.
+ Stop()
+}
+
+type Peer struct {
+ ID uint64
+ Context []byte
+}
+
+// StartNode returns a new Node given configuration and a list of raft peers.
+// It appends a ConfChangeAddNode entry for each given peer to the initial log.
+func StartNode(c *Config, peers []Peer) Node {
+ r := newRaft(c)
+ // become the follower at term 1 and apply initial configuration
+ // entries of term 1
+ r.becomeFollower(1, None)
+ for _, peer := range peers {
+ cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context}
+ d, err := cc.Marshal()
+ if err != nil {
+ panic("unexpected marshal error")
+ }
+ e := pb.Entry{Type: pb.EntryConfChange, Term: 1, Index: r.raftLog.lastIndex() + 1, Data: d}
+ r.raftLog.append(e)
+ }
+ // Mark these initial entries as committed.
+ // TODO(bdarnell): These entries are still unstable; do we need to preserve
+ // the invariant that committed < unstable?
+ r.raftLog.committed = r.raftLog.lastIndex()
+ // Now apply them, mainly so that the application can call Campaign
+ // immediately after StartNode in tests. Note that these nodes will
+ // be added to raft twice: here and when the application's Ready
+ // loop calls ApplyConfChange. The calls to addNode must come after
+ // all calls to raftLog.append so progress.next is set after these
+ // bootstrapping entries (it is an error if we try to append these
+ // entries since they have already been committed).
+ // We do not set raftLog.applied so the application will be able
+ // to observe all conf changes via Ready.CommittedEntries.
+ for _, peer := range peers {
+ r.addNode(peer.ID)
+ }
+
+ n := newNode()
+ n.logger = c.Logger
+ go n.run(r)
+ return &n
+}
+
+// RestartNode is similar to StartNode but does not take a list of peers.
+// The current membership of the cluster will be restored from the Storage.
+// If the caller has an existing state machine, pass in the last log index that
+// has been applied to it; otherwise use zero.
+func RestartNode(c *Config) Node {
+ r := newRaft(c)
+
+ n := newNode()
+ n.logger = c.Logger
+ go n.run(r)
+ return &n
+}
+
+// node is the canonical implementation of the Node interface
+type node struct {
+ propc chan pb.Message
+ recvc chan pb.Message
+ confc chan pb.ConfChange
+ confstatec chan pb.ConfState
+ readyc chan Ready
+ advancec chan struct{}
+ tickc chan struct{}
+ done chan struct{}
+ stop chan struct{}
+ status chan chan Status
+
+ logger Logger
+}
+
+func newNode() node {
+ return node{
+ propc: make(chan pb.Message),
+ recvc: make(chan pb.Message),
+ confc: make(chan pb.ConfChange),
+ confstatec: make(chan pb.ConfState),
+ readyc: make(chan Ready),
+ advancec: make(chan struct{}),
+ // make tickc a buffered chan, so raft node can buffer some ticks when the node
+ // is busy processing raft messages. Raft node will resume process buffered
+ // ticks when it becomes idle.
+ tickc: make(chan struct{}, 128),
+ done: make(chan struct{}),
+ stop: make(chan struct{}),
+ status: make(chan chan Status),
+ }
+}
+
+func (n *node) Stop() {
+ select {
+ case n.stop <- struct{}{}:
+ // Not already stopped, so trigger it
+ case <-n.done:
+ // Node has already been stopped - no need to do anything
+ return
+ }
+ // Block until the stop has been acknowledged by run()
+ <-n.done
+}
+
+func (n *node) run(r *raft) {
+ var propc chan pb.Message
+ var readyc chan Ready
+ var advancec chan struct{}
+ var prevLastUnstablei, prevLastUnstablet uint64
+ var havePrevLastUnstablei bool
+ var prevSnapi uint64
+ var rd Ready
+
+ lead := None
+ prevSoftSt := r.softState()
+ prevHardSt := emptyState
+
+ for {
+ if advancec != nil {
+ readyc = nil
+ } else {
+ rd = newReady(r, prevSoftSt, prevHardSt)
+ if rd.containsUpdates() {
+ readyc = n.readyc
+ } else {
+ readyc = nil
+ }
+ }
+
+ if lead != r.lead {
+ if r.hasLeader() {
+ if lead == None {
+ r.logger.Infof("raft.node: %x elected leader %x at term %d", r.id, r.lead, r.Term)
+ } else {
+ r.logger.Infof("raft.node: %x changed leader from %x to %x at term %d", r.id, lead, r.lead, r.Term)
+ }
+ propc = n.propc
+ } else {
+ r.logger.Infof("raft.node: %x lost leader %x at term %d", r.id, lead, r.Term)
+ propc = nil
+ }
+ lead = r.lead
+ }
+
+ select {
+ // TODO: maybe buffer the config propose if there exists one (the way
+ // described in raft dissertation)
+ // Currently it is dropped in Step silently.
+ case m := <-propc:
+ m.From = r.id
+ r.Step(m)
+ case m := <-n.recvc:
+ // filter out response message from unknown From.
+ if _, ok := r.prs[m.From]; ok || !IsResponseMsg(m.Type) {
+ r.Step(m) // raft never returns an error
+ }
+ case cc := <-n.confc:
+ if cc.NodeID == None {
+ r.resetPendingConf()
+ select {
+ case n.confstatec <- pb.ConfState{Nodes: r.nodes()}:
+ case <-n.done:
+ }
+ break
+ }
+ switch cc.Type {
+ case pb.ConfChangeAddNode:
+ r.addNode(cc.NodeID)
+ case pb.ConfChangeRemoveNode:
+ // block incoming proposal when local node is
+ // removed
+ if cc.NodeID == r.id {
+ propc = nil
+ }
+ r.removeNode(cc.NodeID)
+ case pb.ConfChangeUpdateNode:
+ r.resetPendingConf()
+ default:
+ panic("unexpected conf type")
+ }
+ select {
+ case n.confstatec <- pb.ConfState{Nodes: r.nodes()}:
+ case <-n.done:
+ }
+ case <-n.tickc:
+ r.tick()
+ case readyc <- rd:
+ if rd.SoftState != nil {
+ prevSoftSt = rd.SoftState
+ }
+ if len(rd.Entries) > 0 {
+ prevLastUnstablei = rd.Entries[len(rd.Entries)-1].Index
+ prevLastUnstablet = rd.Entries[len(rd.Entries)-1].Term
+ havePrevLastUnstablei = true
+ }
+ if !IsEmptyHardState(rd.HardState) {
+ prevHardSt = rd.HardState
+ }
+ if !IsEmptySnap(rd.Snapshot) {
+ prevSnapi = rd.Snapshot.Metadata.Index
+ }
+
+ r.msgs = nil
+ r.readStates = nil
+ advancec = n.advancec
+ case <-advancec:
+ if prevHardSt.Commit != 0 {
+ r.raftLog.appliedTo(prevHardSt.Commit)
+ }
+ if havePrevLastUnstablei {
+ r.raftLog.stableTo(prevLastUnstablei, prevLastUnstablet)
+ havePrevLastUnstablei = false
+ }
+ r.raftLog.stableSnapTo(prevSnapi)
+ advancec = nil
+ case c := <-n.status:
+ c <- getStatus(r)
+ case <-n.stop:
+ close(n.done)
+ return
+ }
+ }
+}
+
+// Tick increments the internal logical clock for this Node. Election timeouts
+// and heartbeat timeouts are in units of ticks.
+func (n *node) Tick() {
+ select {
+ case n.tickc <- struct{}{}:
+ case <-n.done:
+ default:
+ n.logger.Warningf("A tick missed to fire. Node blocks too long!")
+ }
+}
+
+func (n *node) Campaign(ctx context.Context) error { return n.step(ctx, pb.Message{Type: pb.MsgHup}) }
+
+func (n *node) Propose(ctx context.Context, data []byte) error {
+ return n.step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
+}
+
+func (n *node) Step(ctx context.Context, m pb.Message) error {
+ // ignore unexpected local messages receiving over network
+ if IsLocalMsg(m.Type) {
+ // TODO: return an error?
+ return nil
+ }
+ return n.step(ctx, m)
+}
+
+func (n *node) ProposeConfChange(ctx context.Context, cc pb.ConfChange) error {
+ data, err := cc.Marshal()
+ if err != nil {
+ return err
+ }
+ return n.Step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange, Data: data}}})
+}
+
+// Step advances the state machine using msgs. The ctx.Err() will be returned,
+// if any.
+func (n *node) step(ctx context.Context, m pb.Message) error {
+ ch := n.recvc
+ if m.Type == pb.MsgProp {
+ ch = n.propc
+ }
+
+ select {
+ case ch <- m:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-n.done:
+ return ErrStopped
+ }
+}
+
+func (n *node) Ready() <-chan Ready { return n.readyc }
+
+func (n *node) Advance() {
+ select {
+ case n.advancec <- struct{}{}:
+ case <-n.done:
+ }
+}
+
+func (n *node) ApplyConfChange(cc pb.ConfChange) *pb.ConfState {
+ var cs pb.ConfState
+ select {
+ case n.confc <- cc:
+ case <-n.done:
+ }
+ select {
+ case cs = <-n.confstatec:
+ case <-n.done:
+ }
+ return &cs
+}
+
+func (n *node) Status() Status {
+ c := make(chan Status)
+ select {
+ case n.status <- c:
+ return <-c
+ case <-n.done:
+ return Status{}
+ }
+}
+
+func (n *node) ReportUnreachable(id uint64) {
+ select {
+ case n.recvc <- pb.Message{Type: pb.MsgUnreachable, From: id}:
+ case <-n.done:
+ }
+}
+
+func (n *node) ReportSnapshot(id uint64, status SnapshotStatus) {
+ rej := status == SnapshotFailure
+
+ select {
+ case n.recvc <- pb.Message{Type: pb.MsgSnapStatus, From: id, Reject: rej}:
+ case <-n.done:
+ }
+}
+
+func (n *node) TransferLeadership(ctx context.Context, lead, transferee uint64) {
+ select {
+ // manually set 'from' and 'to', so that leader can voluntarily transfers its leadership
+ case n.recvc <- pb.Message{Type: pb.MsgTransferLeader, From: transferee, To: lead}:
+ case <-n.done:
+ case <-ctx.Done():
+ }
+}
+
+func (n *node) ReadIndex(ctx context.Context, rctx []byte) error {
+ return n.step(ctx, pb.Message{Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: rctx}}})
+}
+
+func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState) Ready {
+ rd := Ready{
+ Entries: r.raftLog.unstableEntries(),
+ CommittedEntries: r.raftLog.nextEnts(),
+ Messages: r.msgs,
+ }
+ if softSt := r.softState(); !softSt.equal(prevSoftSt) {
+ rd.SoftState = softSt
+ }
+ if hardSt := r.hardState(); !isHardStateEqual(hardSt, prevHardSt) {
+ rd.HardState = hardSt
+ }
+ if r.raftLog.unstable.snapshot != nil {
+ rd.Snapshot = *r.raftLog.unstable.snapshot
+ }
+ if len(r.readStates) != 0 {
+ rd.ReadStates = r.readStates
+ }
+ return rd
+}
diff --git a/vendor/github.com/coreos/etcd/raft/progress.go b/vendor/github.com/coreos/etcd/raft/progress.go
new file mode 100644
index 0000000..77c7b52
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/progress.go
@@ -0,0 +1,279 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import "fmt"
+
+const (
+ ProgressStateProbe ProgressStateType = iota
+ ProgressStateReplicate
+ ProgressStateSnapshot
+)
+
+type ProgressStateType uint64
+
+var prstmap = [...]string{
+ "ProgressStateProbe",
+ "ProgressStateReplicate",
+ "ProgressStateSnapshot",
+}
+
+func (st ProgressStateType) String() string { return prstmap[uint64(st)] }
+
+// Progress represents a follower’s progress in the view of the leader. Leader maintains
+// progresses of all followers, and sends entries to the follower based on its progress.
+type Progress struct {
+ Match, Next uint64
+ // State defines how the leader should interact with the follower.
+ //
+ // When in ProgressStateProbe, leader sends at most one replication message
+ // per heartbeat interval. It also probes actual progress of the follower.
+ //
+ // When in ProgressStateReplicate, leader optimistically increases next
+ // to the latest entry sent after sending replication message. This is
+ // an optimized state for fast replicating log entries to the follower.
+ //
+ // When in ProgressStateSnapshot, leader should have sent out snapshot
+ // before and stops sending any replication message.
+ State ProgressStateType
+ // Paused is used in ProgressStateProbe.
+ // When Paused is true, raft should pause sending replication message to this peer.
+ Paused bool
+ // PendingSnapshot is used in ProgressStateSnapshot.
+ // If there is a pending snapshot, the pendingSnapshot will be set to the
+ // index of the snapshot. If pendingSnapshot is set, the replication process of
+ // this Progress will be paused. raft will not resend snapshot until the pending one
+ // is reported to be failed.
+ PendingSnapshot uint64
+
+ // RecentActive is true if the progress is recently active. Receiving any messages
+ // from the corresponding follower indicates the progress is active.
+ // RecentActive can be reset to false after an election timeout.
+ RecentActive bool
+
+ // inflights is a sliding window for the inflight messages.
+ // Each inflight message contains one or more log entries.
+ // The max number of entries per message is defined in raft config as MaxSizePerMsg.
+ // Thus inflight effectively limits both the number of inflight messages
+ // and the bandwidth each Progress can use.
+ // When inflights is full, no more message should be sent.
+ // When a leader sends out a message, the index of the last
+ // entry should be added to inflights. The index MUST be added
+ // into inflights in order.
+ // When a leader receives a reply, the previous inflights should
+ // be freed by calling inflights.freeTo with the index of the last
+ // received entry.
+ ins *inflights
+}
+
+func (pr *Progress) resetState(state ProgressStateType) {
+ pr.Paused = false
+ pr.PendingSnapshot = 0
+ pr.State = state
+ pr.ins.reset()
+}
+
+func (pr *Progress) becomeProbe() {
+ // If the original state is ProgressStateSnapshot, progress knows that
+ // the pending snapshot has been sent to this peer successfully, then
+ // probes from pendingSnapshot + 1.
+ if pr.State == ProgressStateSnapshot {
+ pendingSnapshot := pr.PendingSnapshot
+ pr.resetState(ProgressStateProbe)
+ pr.Next = max(pr.Match+1, pendingSnapshot+1)
+ } else {
+ pr.resetState(ProgressStateProbe)
+ pr.Next = pr.Match + 1
+ }
+}
+
+func (pr *Progress) becomeReplicate() {
+ pr.resetState(ProgressStateReplicate)
+ pr.Next = pr.Match + 1
+}
+
+func (pr *Progress) becomeSnapshot(snapshoti uint64) {
+ pr.resetState(ProgressStateSnapshot)
+ pr.PendingSnapshot = snapshoti
+}
+
+// maybeUpdate returns false if the given n index comes from an outdated message.
+// Otherwise it updates the progress and returns true.
+func (pr *Progress) maybeUpdate(n uint64) bool {
+ var updated bool
+ if pr.Match < n {
+ pr.Match = n
+ updated = true
+ pr.resume()
+ }
+ if pr.Next < n+1 {
+ pr.Next = n + 1
+ }
+ return updated
+}
+
+func (pr *Progress) optimisticUpdate(n uint64) { pr.Next = n + 1 }
+
+// maybeDecrTo returns false if the given to index comes from an out of order message.
+// Otherwise it decreases the progress next index to min(rejected, last) and returns true.
+func (pr *Progress) maybeDecrTo(rejected, last uint64) bool {
+ if pr.State == ProgressStateReplicate {
+ // the rejection must be stale if the progress has matched and "rejected"
+ // is smaller than "match".
+ if rejected <= pr.Match {
+ return false
+ }
+ // directly decrease next to match + 1
+ pr.Next = pr.Match + 1
+ return true
+ }
+
+ // the rejection must be stale if "rejected" does not match next - 1
+ if pr.Next-1 != rejected {
+ return false
+ }
+
+ if pr.Next = min(rejected, last+1); pr.Next < 1 {
+ pr.Next = 1
+ }
+ pr.resume()
+ return true
+}
+
+func (pr *Progress) pause() { pr.Paused = true }
+func (pr *Progress) resume() { pr.Paused = false }
+
+// IsPaused returns whether sending log entries to this node has been
+// paused. A node may be paused because it has rejected recent
+// MsgApps, is currently waiting for a snapshot, or has reached the
+// MaxInflightMsgs limit.
+func (pr *Progress) IsPaused() bool {
+ switch pr.State {
+ case ProgressStateProbe:
+ return pr.Paused
+ case ProgressStateReplicate:
+ return pr.ins.full()
+ case ProgressStateSnapshot:
+ return true
+ default:
+ panic("unexpected state")
+ }
+}
+
+func (pr *Progress) snapshotFailure() { pr.PendingSnapshot = 0 }
+
+// needSnapshotAbort returns true if snapshot progress's Match
+// is equal or higher than the pendingSnapshot.
+func (pr *Progress) needSnapshotAbort() bool {
+ return pr.State == ProgressStateSnapshot && pr.Match >= pr.PendingSnapshot
+}
+
+func (pr *Progress) String() string {
+ return fmt.Sprintf("next = %d, match = %d, state = %s, waiting = %v, pendingSnapshot = %d", pr.Next, pr.Match, pr.State, pr.IsPaused(), pr.PendingSnapshot)
+}
+
+type inflights struct {
+ // the starting index in the buffer
+ start int
+ // number of inflights in the buffer
+ count int
+
+ // the size of the buffer
+ size int
+
+ // buffer contains the index of the last entry
+ // inside one message.
+ buffer []uint64
+}
+
+func newInflights(size int) *inflights {
+ return &inflights{
+ size: size,
+ }
+}
+
+// add adds an inflight into inflights
+func (in *inflights) add(inflight uint64) {
+ if in.full() {
+ panic("cannot add into a full inflights")
+ }
+ next := in.start + in.count
+ size := in.size
+ if next >= size {
+ next -= size
+ }
+ if next >= len(in.buffer) {
+ in.growBuf()
+ }
+ in.buffer[next] = inflight
+ in.count++
+}
+
+// grow the inflight buffer by doubling up to inflights.size. We grow on demand
+// instead of preallocating to inflights.size to handle systems which have
+// thousands of Raft groups per process.
+func (in *inflights) growBuf() {
+ newSize := len(in.buffer) * 2
+ if newSize == 0 {
+ newSize = 1
+ } else if newSize > in.size {
+ newSize = in.size
+ }
+ newBuffer := make([]uint64, newSize)
+ copy(newBuffer, in.buffer)
+ in.buffer = newBuffer
+}
+
+// freeTo frees the inflights smaller or equal to the given `to` flight.
+func (in *inflights) freeTo(to uint64) {
+ if in.count == 0 || to < in.buffer[in.start] {
+ // out of the left side of the window
+ return
+ }
+
+ i, idx := 0, in.start
+ for i = 0; i < in.count; i++ {
+ if to < in.buffer[idx] { // found the first large inflight
+ break
+ }
+
+ // increase index and maybe rotate
+ size := in.size
+ if idx++; idx >= size {
+ idx -= size
+ }
+ }
+ // free i inflights and set new start index
+ in.count -= i
+ in.start = idx
+ if in.count == 0 {
+ // inflights is empty, reset the start index so that we don't grow the
+ // buffer unnecessarily.
+ in.start = 0
+ }
+}
+
+func (in *inflights) freeFirstOne() { in.freeTo(in.buffer[in.start]) }
+
+// full returns true if the inflights is full.
+func (in *inflights) full() bool {
+ return in.count == in.size
+}
+
+// resets frees all inflights.
+func (in *inflights) reset() {
+ in.count = 0
+ in.start = 0
+}
diff --git a/vendor/github.com/coreos/etcd/raft/raft.go b/vendor/github.com/coreos/etcd/raft/raft.go
new file mode 100644
index 0000000..633cc14
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/raft.go
@@ -0,0 +1,1252 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "math"
+ "math/rand"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ pb "github.com/coreos/etcd/raft/raftpb"
+)
+
+// None is a placeholder node ID used when there is no leader.
+const None uint64 = 0
+const noLimit = math.MaxUint64
+
+// Possible values for StateType.
+const (
+ StateFollower StateType = iota
+ StateCandidate
+ StateLeader
+ StatePreCandidate
+ numStates
+)
+
+type ReadOnlyOption int
+
+const (
+ // ReadOnlySafe guarantees the linearizability of the read only request by
+ // communicating with the quorum. It is the default and suggested option.
+ ReadOnlySafe ReadOnlyOption = iota
+ // ReadOnlyLeaseBased ensures linearizability of the read only request by
+ // relying on the leader lease. It can be affected by clock drift.
+ // If the clock drift is unbounded, leader might keep the lease longer than it
+ // should (clock can move backward/pause without any bound). ReadIndex is not safe
+ // in that case.
+ ReadOnlyLeaseBased
+)
+
+// Possible values for CampaignType
+const (
+ // campaignPreElection represents the first phase of a normal election when
+ // Config.PreVote is true.
+ campaignPreElection CampaignType = "CampaignPreElection"
+ // campaignElection represents a normal (time-based) election (the second phase
+ // of the election when Config.PreVote is true).
+ campaignElection CampaignType = "CampaignElection"
+ // campaignTransfer represents the type of leader transfer
+ campaignTransfer CampaignType = "CampaignTransfer"
+)
+
+// lockedRand is a small wrapper around rand.Rand to provide
+// synchronization. Only the methods needed by the code are exposed
+// (e.g. Intn).
+type lockedRand struct {
+ mu sync.Mutex
+ rand *rand.Rand
+}
+
+func (r *lockedRand) Intn(n int) int {
+ r.mu.Lock()
+ v := r.rand.Intn(n)
+ r.mu.Unlock()
+ return v
+}
+
+var globalRand = &lockedRand{
+ rand: rand.New(rand.NewSource(time.Now().UnixNano())),
+}
+
+// CampaignType represents the type of campaigning
+// the reason we use the type of string instead of uint64
+// is because it's simpler to compare and fill in raft entries
+type CampaignType string
+
+// StateType represents the role of a node in a cluster.
+type StateType uint64
+
+var stmap = [...]string{
+ "StateFollower",
+ "StateCandidate",
+ "StateLeader",
+ "StatePreCandidate",
+}
+
+func (st StateType) String() string {
+ return stmap[uint64(st)]
+}
+
+// Config contains the parameters to start a raft.
+type Config struct {
+ // ID is the identity of the local raft. ID cannot be 0.
+ ID uint64
+
+ // peers contains the IDs of all nodes (including self) in the raft cluster. It
+ // should only be set when starting a new raft cluster. Restarting raft from
+ // previous configuration will panic if peers is set. peer is private and only
+ // used for testing right now.
+ peers []uint64
+
+ // ElectionTick is the number of Node.Tick invocations that must pass between
+ // elections. That is, if a follower does not receive any message from the
+ // leader of current term before ElectionTick has elapsed, it will become
+ // candidate and start an election. ElectionTick must be greater than
+ // HeartbeatTick. We suggest ElectionTick = 10 * HeartbeatTick to avoid
+ // unnecessary leader switching.
+ ElectionTick int
+ // HeartbeatTick is the number of Node.Tick invocations that must pass between
+ // heartbeats. That is, a leader sends heartbeat messages to maintain its
+ // leadership every HeartbeatTick ticks.
+ HeartbeatTick int
+
+ // Storage is the storage for raft. raft generates entries and states to be
+ // stored in storage. raft reads the persisted entries and states out of
+ // Storage when it needs. raft reads out the previous state and configuration
+ // out of storage when restarting.
+ Storage Storage
+ // Applied is the last applied index. It should only be set when restarting
+ // raft. raft will not return entries to the application smaller or equal to
+ // Applied. If Applied is unset when restarting, raft might return previous
+ // applied entries. This is a very application dependent configuration.
+ Applied uint64
+
+ // MaxSizePerMsg limits the max size of each append message. Smaller value
+ // lowers the raft recovery cost(initial probing and message lost during normal
+ // operation). On the other side, it might affect the throughput during normal
+ // replication. Note: math.MaxUint64 for unlimited, 0 for at most one entry per
+ // message.
+ MaxSizePerMsg uint64
+ // MaxInflightMsgs limits the max number of in-flight append messages during
+ // optimistic replication phase. The application transportation layer usually
+ // has its own sending buffer over TCP/UDP. Setting MaxInflightMsgs to avoid
+ // overflowing that sending buffer. TODO (xiangli): feedback to application to
+ // limit the proposal rate?
+ MaxInflightMsgs int
+
+ // CheckQuorum specifies if the leader should check quorum activity. Leader
+ // steps down when quorum is not active for an electionTimeout.
+ CheckQuorum bool
+
+ // PreVote enables the Pre-Vote algorithm described in raft thesis section
+ // 9.6. This prevents disruption when a node that has been partitioned away
+ // rejoins the cluster.
+ PreVote bool
+
+ // ReadOnlyOption specifies how the read only request is processed.
+ //
+ // ReadOnlySafe guarantees the linearizability of the read only request by
+ // communicating with the quorum. It is the default and suggested option.
+ //
+ // ReadOnlyLeaseBased ensures linearizability of the read only request by
+ // relying on the leader lease. It can be affected by clock drift.
+ // If the clock drift is unbounded, leader might keep the lease longer than it
+ // should (clock can move backward/pause without any bound). ReadIndex is not safe
+ // in that case.
+ ReadOnlyOption ReadOnlyOption
+
+ // Logger is the logger used for raft log. For multinode which can host
+ // multiple raft group, each raft group can have its own logger
+ Logger Logger
+}
+
+func (c *Config) validate() error {
+ if c.ID == None {
+ return errors.New("cannot use none as id")
+ }
+
+ if c.HeartbeatTick <= 0 {
+ return errors.New("heartbeat tick must be greater than 0")
+ }
+
+ if c.ElectionTick <= c.HeartbeatTick {
+ return errors.New("election tick must be greater than heartbeat tick")
+ }
+
+ if c.Storage == nil {
+ return errors.New("storage cannot be nil")
+ }
+
+ if c.MaxInflightMsgs <= 0 {
+ return errors.New("max inflight messages must be greater than 0")
+ }
+
+ if c.Logger == nil {
+ c.Logger = raftLogger
+ }
+
+ return nil
+}
+
+type raft struct {
+ id uint64
+
+ Term uint64
+ Vote uint64
+
+ readStates []ReadState
+
+ // the log
+ raftLog *raftLog
+
+ maxInflight int
+ maxMsgSize uint64
+ prs map[uint64]*Progress
+
+ state StateType
+
+ votes map[uint64]bool
+
+ msgs []pb.Message
+
+ // the leader id
+ lead uint64
+ // leadTransferee is id of the leader transfer target when its value is not zero.
+ // Follow the procedure defined in raft thesis 3.10.
+ leadTransferee uint64
+ // New configuration is ignored if there exists unapplied configuration.
+ pendingConf bool
+
+ readOnly *readOnly
+
+ // number of ticks since it reached last electionTimeout when it is leader
+ // or candidate.
+ // number of ticks since it reached last electionTimeout or received a
+ // valid message from current leader when it is a follower.
+ electionElapsed int
+
+ // number of ticks since it reached last heartbeatTimeout.
+ // only leader keeps heartbeatElapsed.
+ heartbeatElapsed int
+
+ checkQuorum bool
+ preVote bool
+
+ heartbeatTimeout int
+ electionTimeout int
+ // randomizedElectionTimeout is a random number between
+ // [electiontimeout, 2 * electiontimeout - 1]. It gets reset
+ // when raft changes its state to follower or candidate.
+ randomizedElectionTimeout int
+
+ tick func()
+ step stepFunc
+
+ logger Logger
+}
+
+func newRaft(c *Config) *raft {
+ if err := c.validate(); err != nil {
+ panic(err.Error())
+ }
+ raftlog := newLog(c.Storage, c.Logger)
+ hs, cs, err := c.Storage.InitialState()
+ if err != nil {
+ panic(err) // TODO(bdarnell)
+ }
+ peers := c.peers
+ if len(cs.Nodes) > 0 {
+ if len(peers) > 0 {
+ // TODO(bdarnell): the peers argument is always nil except in
+ // tests; the argument should be removed and these tests should be
+ // updated to specify their nodes through a snapshot.
+ panic("cannot specify both newRaft(peers) and ConfState.Nodes)")
+ }
+ peers = cs.Nodes
+ }
+ r := &raft{
+ id: c.ID,
+ lead: None,
+ raftLog: raftlog,
+ maxMsgSize: c.MaxSizePerMsg,
+ maxInflight: c.MaxInflightMsgs,
+ prs: make(map[uint64]*Progress),
+ electionTimeout: c.ElectionTick,
+ heartbeatTimeout: c.HeartbeatTick,
+ logger: c.Logger,
+ checkQuorum: c.CheckQuorum,
+ preVote: c.PreVote,
+ readOnly: newReadOnly(c.ReadOnlyOption),
+ }
+ for _, p := range peers {
+ r.prs[p] = &Progress{Next: 1, ins: newInflights(r.maxInflight)}
+ }
+ if !isHardStateEqual(hs, emptyState) {
+ r.loadState(hs)
+ }
+ if c.Applied > 0 {
+ raftlog.appliedTo(c.Applied)
+ }
+ r.becomeFollower(r.Term, None)
+
+ var nodesStrs []string
+ for _, n := range r.nodes() {
+ nodesStrs = append(nodesStrs, fmt.Sprintf("%x", n))
+ }
+
+ r.logger.Infof("newRaft %x [peers: [%s], term: %d, commit: %d, applied: %d, lastindex: %d, lastterm: %d]",
+ r.id, strings.Join(nodesStrs, ","), r.Term, r.raftLog.committed, r.raftLog.applied, r.raftLog.lastIndex(), r.raftLog.lastTerm())
+ return r
+}
+
+func (r *raft) hasLeader() bool { return r.lead != None }
+
+func (r *raft) softState() *SoftState { return &SoftState{Lead: r.lead, RaftState: r.state} }
+
+func (r *raft) hardState() pb.HardState {
+ return pb.HardState{
+ Term: r.Term,
+ Vote: r.Vote,
+ Commit: r.raftLog.committed,
+ }
+}
+
+func (r *raft) quorum() int { return len(r.prs)/2 + 1 }
+
+func (r *raft) nodes() []uint64 {
+ nodes := make([]uint64, 0, len(r.prs))
+ for id := range r.prs {
+ nodes = append(nodes, id)
+ }
+ sort.Sort(uint64Slice(nodes))
+ return nodes
+}
+
+// send persists state to stable storage and then sends to its mailbox.
+func (r *raft) send(m pb.Message) {
+ m.From = r.id
+ if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
+ if m.Term == 0 {
+ // PreVote RPCs are sent at a term other than our actual term, so the code
+ // that sends these messages is responsible for setting the term.
+ panic(fmt.Sprintf("term should be set when sending %s", m.Type))
+ }
+ } else {
+ if m.Term != 0 {
+ panic(fmt.Sprintf("term should not be set when sending %s (was %d)", m.Type, m.Term))
+ }
+ // do not attach term to MsgProp, MsgReadIndex
+ // proposals are a way to forward to the leader and
+ // should be treated as local message.
+ // MsgReadIndex is also forwarded to leader.
+ if m.Type != pb.MsgProp && m.Type != pb.MsgReadIndex {
+ m.Term = r.Term
+ }
+ }
+ r.msgs = append(r.msgs, m)
+}
+
+// sendAppend sends RPC, with entries to the given peer.
+func (r *raft) sendAppend(to uint64) {
+ pr := r.prs[to]
+ if pr.IsPaused() {
+ return
+ }
+ m := pb.Message{}
+ m.To = to
+
+ term, errt := r.raftLog.term(pr.Next - 1)
+ ents, erre := r.raftLog.entries(pr.Next, r.maxMsgSize)
+
+ if errt != nil || erre != nil { // send snapshot if we failed to get term or entries
+ if !pr.RecentActive {
+ r.logger.Debugf("ignore sending snapshot to %x since it is not recently active", to)
+ return
+ }
+
+ m.Type = pb.MsgSnap
+ snapshot, err := r.raftLog.snapshot()
+ if err != nil {
+ if err == ErrSnapshotTemporarilyUnavailable {
+ r.logger.Debugf("%x failed to send snapshot to %x because snapshot is temporarily unavailable", r.id, to)
+ return
+ }
+ panic(err) // TODO(bdarnell)
+ }
+ if IsEmptySnap(snapshot) {
+ panic("need non-empty snapshot")
+ }
+ m.Snapshot = snapshot
+ sindex, sterm := snapshot.Metadata.Index, snapshot.Metadata.Term
+ r.logger.Debugf("%x [firstindex: %d, commit: %d] sent snapshot[index: %d, term: %d] to %x [%s]",
+ r.id, r.raftLog.firstIndex(), r.raftLog.committed, sindex, sterm, to, pr)
+ pr.becomeSnapshot(sindex)
+ r.logger.Debugf("%x paused sending replication messages to %x [%s]", r.id, to, pr)
+ } else {
+ m.Type = pb.MsgApp
+ m.Index = pr.Next - 1
+ m.LogTerm = term
+ m.Entries = ents
+ m.Commit = r.raftLog.committed
+ if n := len(m.Entries); n != 0 {
+ switch pr.State {
+ // optimistically increase the next when in ProgressStateReplicate
+ case ProgressStateReplicate:
+ last := m.Entries[n-1].Index
+ pr.optimisticUpdate(last)
+ pr.ins.add(last)
+ case ProgressStateProbe:
+ pr.pause()
+ default:
+ r.logger.Panicf("%x is sending append in unhandled state %s", r.id, pr.State)
+ }
+ }
+ }
+ r.send(m)
+}
+
+// sendHeartbeat sends an empty MsgApp
+func (r *raft) sendHeartbeat(to uint64, ctx []byte) {
+ // Attach the commit as min(to.matched, r.committed).
+ // When the leader sends out heartbeat message,
+ // the receiver(follower) might not be matched with the leader
+ // or it might not have all the committed entries.
+ // The leader MUST NOT forward the follower's commit to
+ // an unmatched index.
+ commit := min(r.prs[to].Match, r.raftLog.committed)
+ m := pb.Message{
+ To: to,
+ Type: pb.MsgHeartbeat,
+ Commit: commit,
+ Context: ctx,
+ }
+
+ r.send(m)
+}
+
+// bcastAppend sends RPC, with entries to all peers that are not up-to-date
+// according to the progress recorded in r.prs.
+func (r *raft) bcastAppend() {
+ for id := range r.prs {
+ if id == r.id {
+ continue
+ }
+ r.sendAppend(id)
+ }
+}
+
+// bcastHeartbeat sends RPC, without entries to all the peers.
+func (r *raft) bcastHeartbeat() {
+ lastCtx := r.readOnly.lastPendingRequestCtx()
+ if len(lastCtx) == 0 {
+ r.bcastHeartbeatWithCtx(nil)
+ } else {
+ r.bcastHeartbeatWithCtx([]byte(lastCtx))
+ }
+}
+
+func (r *raft) bcastHeartbeatWithCtx(ctx []byte) {
+ for id := range r.prs {
+ if id == r.id {
+ continue
+ }
+ r.sendHeartbeat(id, ctx)
+ }
+}
+
+// maybeCommit attempts to advance the commit index. Returns true if
+// the commit index changed (in which case the caller should call
+// r.bcastAppend).
+func (r *raft) maybeCommit() bool {
+ // TODO(bmizerany): optimize.. Currently naive
+ mis := make(uint64Slice, 0, len(r.prs))
+ for id := range r.prs {
+ mis = append(mis, r.prs[id].Match)
+ }
+ sort.Sort(sort.Reverse(mis))
+ mci := mis[r.quorum()-1]
+ return r.raftLog.maybeCommit(mci, r.Term)
+}
+
+func (r *raft) reset(term uint64) {
+ if r.Term != term {
+ r.Term = term
+ r.Vote = None
+ }
+ r.lead = None
+
+ r.electionElapsed = 0
+ r.heartbeatElapsed = 0
+ r.resetRandomizedElectionTimeout()
+
+ r.abortLeaderTransfer()
+
+ r.votes = make(map[uint64]bool)
+ for id := range r.prs {
+ r.prs[id] = &Progress{Next: r.raftLog.lastIndex() + 1, ins: newInflights(r.maxInflight)}
+ if id == r.id {
+ r.prs[id].Match = r.raftLog.lastIndex()
+ }
+ }
+ r.pendingConf = false
+ r.readOnly = newReadOnly(r.readOnly.option)
+}
+
+func (r *raft) appendEntry(es ...pb.Entry) {
+ li := r.raftLog.lastIndex()
+ for i := range es {
+ es[i].Term = r.Term
+ es[i].Index = li + 1 + uint64(i)
+ }
+ r.raftLog.append(es...)
+ r.prs[r.id].maybeUpdate(r.raftLog.lastIndex())
+ // Regardless of maybeCommit's return, our caller will call bcastAppend.
+ r.maybeCommit()
+}
+
+// tickElection is run by followers and candidates after r.electionTimeout.
+func (r *raft) tickElection() {
+ r.electionElapsed++
+
+ if r.promotable() && r.pastElectionTimeout() {
+ r.electionElapsed = 0
+ r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
+ }
+}
+
+// tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout.
+func (r *raft) tickHeartbeat() {
+ r.heartbeatElapsed++
+ r.electionElapsed++
+
+ if r.electionElapsed >= r.electionTimeout {
+ r.electionElapsed = 0
+ if r.checkQuorum {
+ r.Step(pb.Message{From: r.id, Type: pb.MsgCheckQuorum})
+ }
+ // If current leader cannot transfer leadership in electionTimeout, it becomes leader again.
+ if r.state == StateLeader && r.leadTransferee != None {
+ r.abortLeaderTransfer()
+ }
+ }
+
+ if r.state != StateLeader {
+ return
+ }
+
+ if r.heartbeatElapsed >= r.heartbeatTimeout {
+ r.heartbeatElapsed = 0
+ r.Step(pb.Message{From: r.id, Type: pb.MsgBeat})
+ }
+}
+
+func (r *raft) becomeFollower(term uint64, lead uint64) {
+ r.step = stepFollower
+ r.reset(term)
+ r.tick = r.tickElection
+ r.lead = lead
+ r.state = StateFollower
+ r.logger.Infof("%x became follower at term %d", r.id, r.Term)
+}
+
+func (r *raft) becomeCandidate() {
+ // TODO(xiangli) remove the panic when the raft implementation is stable
+ if r.state == StateLeader {
+ panic("invalid transition [leader -> candidate]")
+ }
+ r.step = stepCandidate
+ r.reset(r.Term + 1)
+ r.tick = r.tickElection
+ r.Vote = r.id
+ r.state = StateCandidate
+ r.logger.Infof("%x became candidate at term %d", r.id, r.Term)
+}
+
+func (r *raft) becomePreCandidate() {
+ // TODO(xiangli) remove the panic when the raft implementation is stable
+ if r.state == StateLeader {
+ panic("invalid transition [leader -> pre-candidate]")
+ }
+ // Becoming a pre-candidate changes our step functions and state,
+ // but doesn't change anything else. In particular it does not increase
+ // r.Term or change r.Vote.
+ r.step = stepCandidate
+ r.tick = r.tickElection
+ r.state = StatePreCandidate
+ r.logger.Infof("%x became pre-candidate at term %d", r.id, r.Term)
+}
+
+func (r *raft) becomeLeader() {
+ // TODO(xiangli) remove the panic when the raft implementation is stable
+ if r.state == StateFollower {
+ panic("invalid transition [follower -> leader]")
+ }
+ r.step = stepLeader
+ r.reset(r.Term)
+ r.tick = r.tickHeartbeat
+ r.lead = r.id
+ r.state = StateLeader
+ ents, err := r.raftLog.entries(r.raftLog.committed+1, noLimit)
+ if err != nil {
+ r.logger.Panicf("unexpected error getting uncommitted entries (%v)", err)
+ }
+
+ nconf := numOfPendingConf(ents)
+ if nconf > 1 {
+ panic("unexpected multiple uncommitted config entry")
+ }
+ if nconf == 1 {
+ r.pendingConf = true
+ }
+
+ r.appendEntry(pb.Entry{Data: nil})
+ r.logger.Infof("%x became leader at term %d", r.id, r.Term)
+}
+
+func (r *raft) campaign(t CampaignType) {
+ var term uint64
+ var voteMsg pb.MessageType
+ if t == campaignPreElection {
+ r.becomePreCandidate()
+ voteMsg = pb.MsgPreVote
+ // PreVote RPCs are sent for the next term before we've incremented r.Term.
+ term = r.Term + 1
+ } else {
+ r.becomeCandidate()
+ voteMsg = pb.MsgVote
+ term = r.Term
+ }
+ if r.quorum() == r.poll(r.id, voteRespMsgType(voteMsg), true) {
+ // We won the election after voting for ourselves (which must mean that
+ // this is a single-node cluster). Advance to the next state.
+ if t == campaignPreElection {
+ r.campaign(campaignElection)
+ } else {
+ r.becomeLeader()
+ }
+ return
+ }
+ for id := range r.prs {
+ if id == r.id {
+ continue
+ }
+ r.logger.Infof("%x [logterm: %d, index: %d] sent %s request to %x at term %d",
+ r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), voteMsg, id, r.Term)
+
+ var ctx []byte
+ if t == campaignTransfer {
+ ctx = []byte(t)
+ }
+ r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx})
+ }
+}
+
+func (r *raft) poll(id uint64, t pb.MessageType, v bool) (granted int) {
+ if v {
+ r.logger.Infof("%x received %s from %x at term %d", r.id, t, id, r.Term)
+ } else {
+ r.logger.Infof("%x received %s rejection from %x at term %d", r.id, t, id, r.Term)
+ }
+ if _, ok := r.votes[id]; !ok {
+ r.votes[id] = v
+ }
+ for _, vv := range r.votes {
+ if vv {
+ granted++
+ }
+ }
+ return granted
+}
+
+func (r *raft) Step(m pb.Message) error {
+ // Handle the message term, which may result in our stepping down to a follower.
+ switch {
+ case m.Term == 0:
+ // local message
+ case m.Term > r.Term:
+ lead := m.From
+ if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
+ force := bytes.Equal(m.Context, []byte(campaignTransfer))
+ inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
+ if !force && inLease {
+ // If a server receives a RequestVote request within the minimum election timeout
+ // of hearing from a current leader, it does not update its term or grant its vote
+ r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] ignored %s from %x [logterm: %d, index: %d] at term %d: lease is not expired (remaining ticks: %d)",
+ r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed)
+ return nil
+ }
+ lead = None
+ }
+ switch {
+ case m.Type == pb.MsgPreVote:
+ // Never change our term in response to a PreVote
+ case m.Type == pb.MsgPreVoteResp && !m.Reject:
+ // We send pre-vote requests with a term in our future. If the
+ // pre-vote is granted, we will increment our term when we get a
+ // quorum. If it is not, the term comes from the node that
+ // rejected our vote so we should become a follower at the new
+ // term.
+ default:
+ r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
+ r.id, r.Term, m.Type, m.From, m.Term)
+ r.becomeFollower(m.Term, lead)
+ }
+
+ case m.Term < r.Term:
+ if r.checkQuorum && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) {
+ // We have received messages from a leader at a lower term. It is possible
+ // that these messages were simply delayed in the network, but this could
+ // also mean that this node has advanced its term number during a network
+ // partition, and it is now unable to either win an election or to rejoin
+ // the majority on the old term. If checkQuorum is false, this will be
+ // handled by incrementing term numbers in response to MsgVote with a
+ // higher term, but if checkQuorum is true we may not advance the term on
+ // MsgVote and must generate other messages to advance the term. The net
+ // result of these two features is to minimize the disruption caused by
+ // nodes that have been removed from the cluster's configuration: a
+ // removed node will send MsgVotes (or MsgPreVotes) which will be ignored,
+ // but it will not receive MsgApp or MsgHeartbeat, so it will not create
+ // disruptive term increases
+ r.send(pb.Message{To: m.From, Type: pb.MsgAppResp})
+ } else {
+ // ignore other cases
+ r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
+ r.id, r.Term, m.Type, m.From, m.Term)
+ }
+ return nil
+ }
+
+ switch m.Type {
+ case pb.MsgHup:
+ if r.state != StateLeader {
+ ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit)
+ if err != nil {
+ r.logger.Panicf("unexpected error getting unapplied entries (%v)", err)
+ }
+ if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied {
+ r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n)
+ return nil
+ }
+
+ r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
+ if r.preVote {
+ r.campaign(campaignPreElection)
+ } else {
+ r.campaign(campaignElection)
+ }
+ } else {
+ r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
+ }
+
+ case pb.MsgVote, pb.MsgPreVote:
+ // The m.Term > r.Term clause is for MsgPreVote. For MsgVote m.Term should
+ // always equal r.Term.
+ if (r.Vote == None || m.Term > r.Term || r.Vote == m.From) && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
+ r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] cast %s for %x [logterm: %d, index: %d] at term %d",
+ r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
+ r.send(pb.Message{To: m.From, Type: voteRespMsgType(m.Type)})
+ if m.Type == pb.MsgVote {
+ // Only record real votes.
+ r.electionElapsed = 0
+ r.Vote = m.From
+ }
+ } else {
+ r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
+ r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
+ r.send(pb.Message{To: m.From, Type: voteRespMsgType(m.Type), Reject: true})
+ }
+
+ default:
+ r.step(r, m)
+ }
+ return nil
+}
+
+type stepFunc func(r *raft, m pb.Message)
+
+func stepLeader(r *raft, m pb.Message) {
+ // These message types do not require any progress for m.From.
+ switch m.Type {
+ case pb.MsgBeat:
+ r.bcastHeartbeat()
+ return
+ case pb.MsgCheckQuorum:
+ if !r.checkQuorumActive() {
+ r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id)
+ r.becomeFollower(r.Term, None)
+ }
+ return
+ case pb.MsgProp:
+ if len(m.Entries) == 0 {
+ r.logger.Panicf("%x stepped empty MsgProp", r.id)
+ }
+ if _, ok := r.prs[r.id]; !ok {
+ // If we are not currently a member of the range (i.e. this node
+ // was removed from the configuration while serving as leader),
+ // drop any new proposals.
+ return
+ }
+ if r.leadTransferee != None {
+ r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee)
+ return
+ }
+
+ for i, e := range m.Entries {
+ if e.Type == pb.EntryConfChange {
+ if r.pendingConf {
+ r.logger.Infof("propose conf %s ignored since pending unapplied configuration", e.String())
+ m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
+ }
+ r.pendingConf = true
+ }
+ }
+ r.appendEntry(m.Entries...)
+ r.bcastAppend()
+ return
+ case pb.MsgReadIndex:
+ if r.quorum() > 1 {
+ // thinking: use an interally defined context instead of the user given context.
+ // We can express this in terms of the term and index instead of a user-supplied value.
+ // This would allow multiple reads to piggyback on the same message.
+ switch r.readOnly.option {
+ case ReadOnlySafe:
+ r.readOnly.addRequest(r.raftLog.committed, m)
+ r.bcastHeartbeatWithCtx(m.Entries[0].Data)
+ case ReadOnlyLeaseBased:
+ var ri uint64
+ if r.checkQuorum {
+ ri = r.raftLog.committed
+ }
+ if m.From == None || m.From == r.id { // from local member
+ r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
+ } else {
+ r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
+ }
+ }
+ } else {
+ r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
+ }
+
+ return
+ }
+
+ // All other message types require a progress for m.From (pr).
+ pr, prOk := r.prs[m.From]
+ if !prOk {
+ r.logger.Debugf("%x no progress available for %x", r.id, m.From)
+ return
+ }
+ switch m.Type {
+ case pb.MsgAppResp:
+ pr.RecentActive = true
+
+ if m.Reject {
+ r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
+ r.id, m.RejectHint, m.From, m.Index)
+ if pr.maybeDecrTo(m.Index, m.RejectHint) {
+ r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
+ if pr.State == ProgressStateReplicate {
+ pr.becomeProbe()
+ }
+ r.sendAppend(m.From)
+ }
+ } else {
+ oldPaused := pr.IsPaused()
+ if pr.maybeUpdate(m.Index) {
+ switch {
+ case pr.State == ProgressStateProbe:
+ pr.becomeReplicate()
+ case pr.State == ProgressStateSnapshot && pr.needSnapshotAbort():
+ r.logger.Debugf("%x snapshot aborted, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
+ pr.becomeProbe()
+ case pr.State == ProgressStateReplicate:
+ pr.ins.freeTo(m.Index)
+ }
+
+ if r.maybeCommit() {
+ r.bcastAppend()
+ } else if oldPaused {
+ // update() reset the wait state on this node. If we had delayed sending
+ // an update before, send it now.
+ r.sendAppend(m.From)
+ }
+ // Transfer leadership is in progress.
+ if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
+ r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
+ r.sendTimeoutNow(m.From)
+ }
+ }
+ }
+ case pb.MsgHeartbeatResp:
+ pr.RecentActive = true
+ pr.resume()
+
+ // free one slot for the full inflights window to allow progress.
+ if pr.State == ProgressStateReplicate && pr.ins.full() {
+ pr.ins.freeFirstOne()
+ }
+ if pr.Match < r.raftLog.lastIndex() {
+ r.sendAppend(m.From)
+ }
+
+ if r.readOnly.option != ReadOnlySafe || len(m.Context) == 0 {
+ return
+ }
+
+ ackCount := r.readOnly.recvAck(m)
+ if ackCount < r.quorum() {
+ return
+ }
+
+ rss := r.readOnly.advance(m)
+ for _, rs := range rss {
+ req := rs.req
+ if req.From == None || req.From == r.id { // from local member
+ r.readStates = append(r.readStates, ReadState{Index: rs.index, RequestCtx: req.Entries[0].Data})
+ } else {
+ r.send(pb.Message{To: req.From, Type: pb.MsgReadIndexResp, Index: rs.index, Entries: req.Entries})
+ }
+ }
+ case pb.MsgSnapStatus:
+ if pr.State != ProgressStateSnapshot {
+ return
+ }
+ if !m.Reject {
+ pr.becomeProbe()
+ r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
+ } else {
+ pr.snapshotFailure()
+ pr.becomeProbe()
+ r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
+ }
+ // If snapshot finish, wait for the msgAppResp from the remote node before sending
+ // out the next msgApp.
+ // If snapshot failure, wait for a heartbeat interval before next try
+ pr.pause()
+ case pb.MsgUnreachable:
+ // During optimistic replication, if the remote becomes unreachable,
+ // there is huge probability that a MsgApp is lost.
+ if pr.State == ProgressStateReplicate {
+ pr.becomeProbe()
+ }
+ r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
+ case pb.MsgTransferLeader:
+ leadTransferee := m.From
+ lastLeadTransferee := r.leadTransferee
+ if lastLeadTransferee != None {
+ if lastLeadTransferee == leadTransferee {
+ r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
+ r.id, r.Term, leadTransferee, leadTransferee)
+ return
+ }
+ r.abortLeaderTransfer()
+ r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
+ }
+ if leadTransferee == r.id {
+ r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
+ return
+ }
+ // Transfer leadership to third party.
+ r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
+ // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
+ r.electionElapsed = 0
+ r.leadTransferee = leadTransferee
+ if pr.Match == r.raftLog.lastIndex() {
+ r.sendTimeoutNow(leadTransferee)
+ r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
+ } else {
+ r.sendAppend(leadTransferee)
+ }
+ }
+}
+
+// stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
+// whether they respond to MsgVoteResp or MsgPreVoteResp.
+func stepCandidate(r *raft, m pb.Message) {
+ // Only handle vote responses corresponding to our candidacy (while in
+ // StateCandidate, we may get stale MsgPreVoteResp messages in this term from
+ // our pre-candidate state).
+ var myVoteRespType pb.MessageType
+ if r.state == StatePreCandidate {
+ myVoteRespType = pb.MsgPreVoteResp
+ } else {
+ myVoteRespType = pb.MsgVoteResp
+ }
+ switch m.Type {
+ case pb.MsgProp:
+ r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
+ return
+ case pb.MsgApp:
+ r.becomeFollower(r.Term, m.From)
+ r.handleAppendEntries(m)
+ case pb.MsgHeartbeat:
+ r.becomeFollower(r.Term, m.From)
+ r.handleHeartbeat(m)
+ case pb.MsgSnap:
+ r.becomeFollower(m.Term, m.From)
+ r.handleSnapshot(m)
+ case myVoteRespType:
+ gr := r.poll(m.From, m.Type, !m.Reject)
+ r.logger.Infof("%x [quorum:%d] has received %d %s votes and %d vote rejections", r.id, r.quorum(), gr, m.Type, len(r.votes)-gr)
+ switch r.quorum() {
+ case gr:
+ if r.state == StatePreCandidate {
+ r.campaign(campaignElection)
+ } else {
+ r.becomeLeader()
+ r.bcastAppend()
+ }
+ case len(r.votes) - gr:
+ r.becomeFollower(r.Term, None)
+ }
+ case pb.MsgTimeoutNow:
+ r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
+ }
+}
+
+func stepFollower(r *raft, m pb.Message) {
+ switch m.Type {
+ case pb.MsgProp:
+ if r.lead == None {
+ r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
+ return
+ }
+ m.To = r.lead
+ r.send(m)
+ case pb.MsgApp:
+ r.electionElapsed = 0
+ r.lead = m.From
+ r.handleAppendEntries(m)
+ case pb.MsgHeartbeat:
+ r.electionElapsed = 0
+ r.lead = m.From
+ r.handleHeartbeat(m)
+ case pb.MsgSnap:
+ r.electionElapsed = 0
+ r.lead = m.From
+ r.handleSnapshot(m)
+ case pb.MsgTransferLeader:
+ if r.lead == None {
+ r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term)
+ return
+ }
+ m.To = r.lead
+ r.send(m)
+ case pb.MsgTimeoutNow:
+ if r.promotable() {
+ r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
+ // Leadership transfers never use pre-vote even if r.preVote is true; we
+ // know we are not recovering from a partition so there is no need for the
+ // extra round trip.
+ r.campaign(campaignTransfer)
+ } else {
+ r.logger.Infof("%x received MsgTimeoutNow from %x but is not promotable", r.id, m.From)
+ }
+ case pb.MsgReadIndex:
+ if r.lead == None {
+ r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
+ return
+ }
+ m.To = r.lead
+ r.send(m)
+ case pb.MsgReadIndexResp:
+ if len(m.Entries) != 1 {
+ r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
+ return
+ }
+ r.readStates = append(r.readStates, ReadState{Index: m.Index, RequestCtx: m.Entries[0].Data})
+ }
+}
+
+func (r *raft) handleAppendEntries(m pb.Message) {
+ if m.Index < r.raftLog.committed {
+ r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
+ return
+ }
+
+ if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
+ r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
+ } else {
+ r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
+ r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
+ r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
+ }
+}
+
+func (r *raft) handleHeartbeat(m pb.Message) {
+ r.raftLog.commitTo(m.Commit)
+ r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp, Context: m.Context})
+}
+
+func (r *raft) handleSnapshot(m pb.Message) {
+ sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
+ if r.restore(m.Snapshot) {
+ r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
+ r.id, r.raftLog.committed, sindex, sterm)
+ r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
+ } else {
+ r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
+ r.id, r.raftLog.committed, sindex, sterm)
+ r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
+ }
+}
+
+// restore recovers the state machine from a snapshot. It restores the log and the
+// configuration of state machine.
+func (r *raft) restore(s pb.Snapshot) bool {
+ if s.Metadata.Index <= r.raftLog.committed {
+ return false
+ }
+ if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
+ r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
+ r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
+ r.raftLog.commitTo(s.Metadata.Index)
+ return false
+ }
+
+ r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
+ r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
+
+ r.raftLog.restore(s)
+ r.prs = make(map[uint64]*Progress)
+ for _, n := range s.Metadata.ConfState.Nodes {
+ match, next := uint64(0), r.raftLog.lastIndex()+1
+ if n == r.id {
+ match = next - 1
+ }
+ r.setProgress(n, match, next)
+ r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.prs[n])
+ }
+ return true
+}
+
+// promotable indicates whether state machine can be promoted to leader,
+// which is true when its own id is in progress list.
+func (r *raft) promotable() bool {
+ _, ok := r.prs[r.id]
+ return ok
+}
+
+func (r *raft) addNode(id uint64) {
+ r.pendingConf = false
+ if _, ok := r.prs[id]; ok {
+ // Ignore any redundant addNode calls (which can happen because the
+ // initial bootstrapping entries are applied twice).
+ return
+ }
+
+ r.setProgress(id, 0, r.raftLog.lastIndex()+1)
+ // When a node is first added, we should mark it as recently active.
+ // Otherwise, CheckQuorum may cause us to step down if it is invoked
+ // before the added node has a chance to communicate with us.
+ r.prs[id].RecentActive = true
+}
+
+func (r *raft) removeNode(id uint64) {
+ r.delProgress(id)
+ r.pendingConf = false
+
+ // do not try to commit or abort transferring if there is no nodes in the cluster.
+ if len(r.prs) == 0 {
+ return
+ }
+
+ // The quorum size is now smaller, so see if any pending entries can
+ // be committed.
+ if r.maybeCommit() {
+ r.bcastAppend()
+ }
+ // If the removed node is the leadTransferee, then abort the leadership transferring.
+ if r.state == StateLeader && r.leadTransferee == id {
+ r.abortLeaderTransfer()
+ }
+}
+
+func (r *raft) resetPendingConf() { r.pendingConf = false }
+
+func (r *raft) setProgress(id, match, next uint64) {
+ r.prs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight)}
+}
+
+func (r *raft) delProgress(id uint64) {
+ delete(r.prs, id)
+}
+
+func (r *raft) loadState(state pb.HardState) {
+ if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
+ r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
+ }
+ r.raftLog.committed = state.Commit
+ r.Term = state.Term
+ r.Vote = state.Vote
+}
+
+// pastElectionTimeout returns true iff r.electionElapsed is greater
+// than or equal to the randomized election timeout in
+// [electiontimeout, 2 * electiontimeout - 1].
+func (r *raft) pastElectionTimeout() bool {
+ return r.electionElapsed >= r.randomizedElectionTimeout
+}
+
+func (r *raft) resetRandomizedElectionTimeout() {
+ r.randomizedElectionTimeout = r.electionTimeout + globalRand.Intn(r.electionTimeout)
+}
+
+// checkQuorumActive returns true if the quorum is active from
+// the view of the local raft state machine. Otherwise, it returns
+// false.
+// checkQuorumActive also resets all RecentActive to false.
+func (r *raft) checkQuorumActive() bool {
+ var act int
+
+ for id := range r.prs {
+ if id == r.id { // self is always active
+ act++
+ continue
+ }
+
+ if r.prs[id].RecentActive {
+ act++
+ }
+
+ r.prs[id].RecentActive = false
+ }
+
+ return act >= r.quorum()
+}
+
+func (r *raft) sendTimeoutNow(to uint64) {
+ r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
+}
+
+func (r *raft) abortLeaderTransfer() {
+ r.leadTransferee = None
+}
+
+func numOfPendingConf(ents []pb.Entry) int {
+ n := 0
+ for i := range ents {
+ if ents[i].Type == pb.EntryConfChange {
+ n++
+ }
+ }
+ return n
+}
diff --git a/vendor/github.com/coreos/etcd/raft/raftpb/raft.pb.go b/vendor/github.com/coreos/etcd/raft/raftpb/raft.pb.go
new file mode 100644
index 0000000..86ad312
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/raftpb/raft.pb.go
@@ -0,0 +1,1900 @@
+// Code generated by protoc-gen-gogo.
+// source: raft.proto
+// DO NOT EDIT!
+
+/*
+ Package raftpb is a generated protocol buffer package.
+
+ It is generated from these files:
+ raft.proto
+
+ It has these top-level messages:
+ Entry
+ SnapshotMetadata
+ Snapshot
+ Message
+ HardState
+ ConfState
+ ConfChange
+*/
+package raftpb
+
+import (
+ "fmt"
+
+ proto "github.com/golang/protobuf/proto"
+
+ math "math"
+
+ io "io"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+type EntryType int32
+
+const (
+ EntryNormal EntryType = 0
+ EntryConfChange EntryType = 1
+)
+
+var EntryType_name = map[int32]string{
+ 0: "EntryNormal",
+ 1: "EntryConfChange",
+}
+var EntryType_value = map[string]int32{
+ "EntryNormal": 0,
+ "EntryConfChange": 1,
+}
+
+func (x EntryType) Enum() *EntryType {
+ p := new(EntryType)
+ *p = x
+ return p
+}
+func (x EntryType) String() string {
+ return proto.EnumName(EntryType_name, int32(x))
+}
+func (x *EntryType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(EntryType_value, data, "EntryType")
+ if err != nil {
+ return err
+ }
+ *x = EntryType(value)
+ return nil
+}
+func (EntryType) EnumDescriptor() ([]byte, []int) { return fileDescriptorRaft, []int{0} }
+
+type MessageType int32
+
+const (
+ MsgHup MessageType = 0
+ MsgBeat MessageType = 1
+ MsgProp MessageType = 2
+ MsgApp MessageType = 3
+ MsgAppResp MessageType = 4
+ MsgVote MessageType = 5
+ MsgVoteResp MessageType = 6
+ MsgSnap MessageType = 7
+ MsgHeartbeat MessageType = 8
+ MsgHeartbeatResp MessageType = 9
+ MsgUnreachable MessageType = 10
+ MsgSnapStatus MessageType = 11
+ MsgCheckQuorum MessageType = 12
+ MsgTransferLeader MessageType = 13
+ MsgTimeoutNow MessageType = 14
+ MsgReadIndex MessageType = 15
+ MsgReadIndexResp MessageType = 16
+ MsgPreVote MessageType = 17
+ MsgPreVoteResp MessageType = 18
+)
+
+var MessageType_name = map[int32]string{
+ 0: "MsgHup",
+ 1: "MsgBeat",
+ 2: "MsgProp",
+ 3: "MsgApp",
+ 4: "MsgAppResp",
+ 5: "MsgVote",
+ 6: "MsgVoteResp",
+ 7: "MsgSnap",
+ 8: "MsgHeartbeat",
+ 9: "MsgHeartbeatResp",
+ 10: "MsgUnreachable",
+ 11: "MsgSnapStatus",
+ 12: "MsgCheckQuorum",
+ 13: "MsgTransferLeader",
+ 14: "MsgTimeoutNow",
+ 15: "MsgReadIndex",
+ 16: "MsgReadIndexResp",
+ 17: "MsgPreVote",
+ 18: "MsgPreVoteResp",
+}
+var MessageType_value = map[string]int32{
+ "MsgHup": 0,
+ "MsgBeat": 1,
+ "MsgProp": 2,
+ "MsgApp": 3,
+ "MsgAppResp": 4,
+ "MsgVote": 5,
+ "MsgVoteResp": 6,
+ "MsgSnap": 7,
+ "MsgHeartbeat": 8,
+ "MsgHeartbeatResp": 9,
+ "MsgUnreachable": 10,
+ "MsgSnapStatus": 11,
+ "MsgCheckQuorum": 12,
+ "MsgTransferLeader": 13,
+ "MsgTimeoutNow": 14,
+ "MsgReadIndex": 15,
+ "MsgReadIndexResp": 16,
+ "MsgPreVote": 17,
+ "MsgPreVoteResp": 18,
+}
+
+func (x MessageType) Enum() *MessageType {
+ p := new(MessageType)
+ *p = x
+ return p
+}
+func (x MessageType) String() string {
+ return proto.EnumName(MessageType_name, int32(x))
+}
+func (x *MessageType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(MessageType_value, data, "MessageType")
+ if err != nil {
+ return err
+ }
+ *x = MessageType(value)
+ return nil
+}
+func (MessageType) EnumDescriptor() ([]byte, []int) { return fileDescriptorRaft, []int{1} }
+
+type ConfChangeType int32
+
+const (
+ ConfChangeAddNode ConfChangeType = 0
+ ConfChangeRemoveNode ConfChangeType = 1
+ ConfChangeUpdateNode ConfChangeType = 2
+)
+
+var ConfChangeType_name = map[int32]string{
+ 0: "ConfChangeAddNode",
+ 1: "ConfChangeRemoveNode",
+ 2: "ConfChangeUpdateNode",
+}
+var ConfChangeType_value = map[string]int32{
+ "ConfChangeAddNode": 0,
+ "ConfChangeRemoveNode": 1,
+ "ConfChangeUpdateNode": 2,
+}
+
+func (x ConfChangeType) Enum() *ConfChangeType {
+ p := new(ConfChangeType)
+ *p = x
+ return p
+}
+func (x ConfChangeType) String() string {
+ return proto.EnumName(ConfChangeType_name, int32(x))
+}
+func (x *ConfChangeType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(ConfChangeType_value, data, "ConfChangeType")
+ if err != nil {
+ return err
+ }
+ *x = ConfChangeType(value)
+ return nil
+}
+func (ConfChangeType) EnumDescriptor() ([]byte, []int) { return fileDescriptorRaft, []int{2} }
+
+type Entry struct {
+ Term uint64 `protobuf:"varint,2,opt,name=Term" json:"Term"`
+ Index uint64 `protobuf:"varint,3,opt,name=Index" json:"Index"`
+ Type EntryType `protobuf:"varint,1,opt,name=Type,enum=raftpb.EntryType" json:"Type"`
+ Data []byte `protobuf:"bytes,4,opt,name=Data" json:"Data,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Entry) Reset() { *m = Entry{} }
+func (m *Entry) String() string { return proto.CompactTextString(m) }
+func (*Entry) ProtoMessage() {}
+func (*Entry) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{0} }
+
+type SnapshotMetadata struct {
+ ConfState ConfState `protobuf:"bytes,1,opt,name=conf_state,json=confState" json:"conf_state"`
+ Index uint64 `protobuf:"varint,2,opt,name=index" json:"index"`
+ Term uint64 `protobuf:"varint,3,opt,name=term" json:"term"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *SnapshotMetadata) Reset() { *m = SnapshotMetadata{} }
+func (m *SnapshotMetadata) String() string { return proto.CompactTextString(m) }
+func (*SnapshotMetadata) ProtoMessage() {}
+func (*SnapshotMetadata) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{1} }
+
+type Snapshot struct {
+ Data []byte `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"`
+ Metadata SnapshotMetadata `protobuf:"bytes,2,opt,name=metadata" json:"metadata"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Snapshot) Reset() { *m = Snapshot{} }
+func (m *Snapshot) String() string { return proto.CompactTextString(m) }
+func (*Snapshot) ProtoMessage() {}
+func (*Snapshot) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{2} }
+
+type Message struct {
+ Type MessageType `protobuf:"varint,1,opt,name=type,enum=raftpb.MessageType" json:"type"`
+ To uint64 `protobuf:"varint,2,opt,name=to" json:"to"`
+ From uint64 `protobuf:"varint,3,opt,name=from" json:"from"`
+ Term uint64 `protobuf:"varint,4,opt,name=term" json:"term"`
+ LogTerm uint64 `protobuf:"varint,5,opt,name=logTerm" json:"logTerm"`
+ Index uint64 `protobuf:"varint,6,opt,name=index" json:"index"`
+ Entries []Entry `protobuf:"bytes,7,rep,name=entries" json:"entries"`
+ Commit uint64 `protobuf:"varint,8,opt,name=commit" json:"commit"`
+ Snapshot Snapshot `protobuf:"bytes,9,opt,name=snapshot" json:"snapshot"`
+ Reject bool `protobuf:"varint,10,opt,name=reject" json:"reject"`
+ RejectHint uint64 `protobuf:"varint,11,opt,name=rejectHint" json:"rejectHint"`
+ Context []byte `protobuf:"bytes,12,opt,name=context" json:"context,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Message) Reset() { *m = Message{} }
+func (m *Message) String() string { return proto.CompactTextString(m) }
+func (*Message) ProtoMessage() {}
+func (*Message) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{3} }
+
+type HardState struct {
+ Term uint64 `protobuf:"varint,1,opt,name=term" json:"term"`
+ Vote uint64 `protobuf:"varint,2,opt,name=vote" json:"vote"`
+ Commit uint64 `protobuf:"varint,3,opt,name=commit" json:"commit"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *HardState) Reset() { *m = HardState{} }
+func (m *HardState) String() string { return proto.CompactTextString(m) }
+func (*HardState) ProtoMessage() {}
+func (*HardState) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{4} }
+
+type ConfState struct {
+ Nodes []uint64 `protobuf:"varint,1,rep,name=nodes" json:"nodes,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ConfState) Reset() { *m = ConfState{} }
+func (m *ConfState) String() string { return proto.CompactTextString(m) }
+func (*ConfState) ProtoMessage() {}
+func (*ConfState) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{5} }
+
+type ConfChange struct {
+ ID uint64 `protobuf:"varint,1,opt,name=ID" json:"ID"`
+ Type ConfChangeType `protobuf:"varint,2,opt,name=Type,enum=raftpb.ConfChangeType" json:"Type"`
+ NodeID uint64 `protobuf:"varint,3,opt,name=NodeID" json:"NodeID"`
+ Context []byte `protobuf:"bytes,4,opt,name=Context" json:"Context,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ConfChange) Reset() { *m = ConfChange{} }
+func (m *ConfChange) String() string { return proto.CompactTextString(m) }
+func (*ConfChange) ProtoMessage() {}
+func (*ConfChange) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{6} }
+
+func init() {
+ proto.RegisterType((*Entry)(nil), "raftpb.Entry")
+ proto.RegisterType((*SnapshotMetadata)(nil), "raftpb.SnapshotMetadata")
+ proto.RegisterType((*Snapshot)(nil), "raftpb.Snapshot")
+ proto.RegisterType((*Message)(nil), "raftpb.Message")
+ proto.RegisterType((*HardState)(nil), "raftpb.HardState")
+ proto.RegisterType((*ConfState)(nil), "raftpb.ConfState")
+ proto.RegisterType((*ConfChange)(nil), "raftpb.ConfChange")
+ proto.RegisterEnum("raftpb.EntryType", EntryType_name, EntryType_value)
+ proto.RegisterEnum("raftpb.MessageType", MessageType_name, MessageType_value)
+ proto.RegisterEnum("raftpb.ConfChangeType", ConfChangeType_name, ConfChangeType_value)
+}
+func (m *Entry) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Entry) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Type))
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Term))
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Index))
+ if m.Data != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(len(m.Data)))
+ i += copy(dAtA[i:], m.Data)
+ }
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func (m *SnapshotMetadata) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SnapshotMetadata) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.ConfState.Size()))
+ n1, err := m.ConfState.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Index))
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Term))
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func (m *Snapshot) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Snapshot) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Data != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(len(m.Data)))
+ i += copy(dAtA[i:], m.Data)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Metadata.Size()))
+ n2, err := m.Metadata.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func (m *Message) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Message) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Type))
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.To))
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.From))
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Term))
+ dAtA[i] = 0x28
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.LogTerm))
+ dAtA[i] = 0x30
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Index))
+ if len(m.Entries) > 0 {
+ for _, msg := range m.Entries {
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ dAtA[i] = 0x40
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Commit))
+ dAtA[i] = 0x4a
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Snapshot.Size()))
+ n3, err := m.Snapshot.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ dAtA[i] = 0x50
+ i++
+ if m.Reject {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ dAtA[i] = 0x58
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.RejectHint))
+ if m.Context != nil {
+ dAtA[i] = 0x62
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(len(m.Context)))
+ i += copy(dAtA[i:], m.Context)
+ }
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func (m *HardState) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *HardState) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Term))
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Vote))
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Commit))
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func (m *ConfState) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ConfState) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Nodes) > 0 {
+ for _, num := range m.Nodes {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(num))
+ }
+ }
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func (m *ConfChange) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ConfChange) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.ID))
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Type))
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.NodeID))
+ if m.Context != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(len(m.Context)))
+ i += copy(dAtA[i:], m.Context)
+ }
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func encodeFixed64Raft(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Raft(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintRaft(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func (m *Entry) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovRaft(uint64(m.Type))
+ n += 1 + sovRaft(uint64(m.Term))
+ n += 1 + sovRaft(uint64(m.Index))
+ if m.Data != nil {
+ l = len(m.Data)
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *SnapshotMetadata) Size() (n int) {
+ var l int
+ _ = l
+ l = m.ConfState.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ n += 1 + sovRaft(uint64(m.Index))
+ n += 1 + sovRaft(uint64(m.Term))
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *Snapshot) Size() (n int) {
+ var l int
+ _ = l
+ if m.Data != nil {
+ l = len(m.Data)
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ l = m.Metadata.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *Message) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovRaft(uint64(m.Type))
+ n += 1 + sovRaft(uint64(m.To))
+ n += 1 + sovRaft(uint64(m.From))
+ n += 1 + sovRaft(uint64(m.Term))
+ n += 1 + sovRaft(uint64(m.LogTerm))
+ n += 1 + sovRaft(uint64(m.Index))
+ if len(m.Entries) > 0 {
+ for _, e := range m.Entries {
+ l = e.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ }
+ n += 1 + sovRaft(uint64(m.Commit))
+ l = m.Snapshot.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ n += 2
+ n += 1 + sovRaft(uint64(m.RejectHint))
+ if m.Context != nil {
+ l = len(m.Context)
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *HardState) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovRaft(uint64(m.Term))
+ n += 1 + sovRaft(uint64(m.Vote))
+ n += 1 + sovRaft(uint64(m.Commit))
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *ConfState) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Nodes) > 0 {
+ for _, e := range m.Nodes {
+ n += 1 + sovRaft(uint64(e))
+ }
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *ConfChange) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovRaft(uint64(m.ID))
+ n += 1 + sovRaft(uint64(m.Type))
+ n += 1 + sovRaft(uint64(m.NodeID))
+ if m.Context != nil {
+ l = len(m.Context)
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func sovRaft(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozRaft(x uint64) (n int) {
+ return sovRaft(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (m *Entry) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Entry: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Entry: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Type |= (EntryType(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Term", wireType)
+ }
+ m.Term = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Term |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
+ }
+ m.Index = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Index |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SnapshotMetadata) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SnapshotMetadata: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SnapshotMetadata: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ConfState", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.ConfState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
+ }
+ m.Index = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Index |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Term", wireType)
+ }
+ m.Term = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Term |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Snapshot) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Snapshot: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Snapshot: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Metadata", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Metadata.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Message) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Message: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Type |= (MessageType(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field To", wireType)
+ }
+ m.To = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.To |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field From", wireType)
+ }
+ m.From = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.From |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Term", wireType)
+ }
+ m.Term = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Term |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LogTerm", wireType)
+ }
+ m.LogTerm = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.LogTerm |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
+ }
+ m.Index = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Index |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Entries", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Entries = append(m.Entries, Entry{})
+ if err := m.Entries[len(m.Entries)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 8:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Commit", wireType)
+ }
+ m.Commit = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Commit |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Snapshot", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Snapshot.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 10:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Reject", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Reject = bool(v != 0)
+ case 11:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RejectHint", wireType)
+ }
+ m.RejectHint = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RejectHint |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 12:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Context", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Context = append(m.Context[:0], dAtA[iNdEx:postIndex]...)
+ if m.Context == nil {
+ m.Context = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *HardState) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: HardState: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: HardState: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Term", wireType)
+ }
+ m.Term = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Term |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Vote", wireType)
+ }
+ m.Vote = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Vote |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Commit", wireType)
+ }
+ m.Commit = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Commit |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ConfState) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ConfState: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ConfState: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Nodes", wireType)
+ }
+ var v uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Nodes = append(m.Nodes, v)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ConfChange) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ConfChange: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ConfChange: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ m.ID = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ID |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Type |= (ConfChangeType(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ m.NodeID = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.NodeID |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Context", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Context = append(m.Context[:0], dAtA[iNdEx:postIndex]...)
+ if m.Context == nil {
+ m.Context = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipRaft(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthRaft
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipRaft(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthRaft = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowRaft = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("raft.proto", fileDescriptorRaft) }
+
+var fileDescriptorRaft = []byte{
+ // 790 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x64, 0x54, 0xcd, 0x6e, 0xdb, 0x46,
+ 0x10, 0x16, 0x29, 0xea, 0x6f, 0x28, 0xcb, 0xab, 0xb5, 0x5a, 0x2c, 0x0c, 0x43, 0x55, 0x85, 0x1e,
+ 0x04, 0x17, 0x76, 0x5b, 0x1d, 0x7a, 0xe8, 0xcd, 0x96, 0x0a, 0x58, 0x40, 0x65, 0xb8, 0xb2, 0xdc,
+ 0x43, 0x83, 0x20, 0x58, 0x8b, 0x2b, 0x4a, 0x89, 0xc9, 0x25, 0x96, 0x2b, 0xc7, 0xbe, 0x04, 0x79,
+ 0x80, 0x3c, 0x40, 0x2e, 0x79, 0x1f, 0x1f, 0x0d, 0xe4, 0x1e, 0xc4, 0xce, 0x8b, 0x04, 0xbb, 0x5c,
+ 0x4a, 0x94, 0x74, 0xdb, 0xf9, 0xbe, 0xe1, 0xcc, 0x37, 0xdf, 0xce, 0x12, 0x40, 0xd0, 0xa9, 0x3c,
+ 0x8e, 0x04, 0x97, 0x1c, 0x17, 0xd5, 0x39, 0xba, 0xde, 0x6f, 0xf8, 0xdc, 0xe7, 0x1a, 0xfa, 0x4d,
+ 0x9d, 0x12, 0xb6, 0xfd, 0x0e, 0x0a, 0x7f, 0x87, 0x52, 0xdc, 0xe3, 0x5f, 0xc1, 0x19, 0xdf, 0x47,
+ 0x8c, 0x58, 0x2d, 0xab, 0x53, 0xeb, 0xd6, 0x8f, 0x93, 0xaf, 0x8e, 0x35, 0xa9, 0x88, 0x53, 0xe7,
+ 0xe1, 0xcb, 0x4f, 0xb9, 0x91, 0x4e, 0xc2, 0x04, 0x9c, 0x31, 0x13, 0x01, 0xb1, 0x5b, 0x56, 0xc7,
+ 0x59, 0x32, 0x4c, 0x04, 0x78, 0x1f, 0x0a, 0x83, 0xd0, 0x63, 0x77, 0x24, 0x9f, 0xa1, 0x12, 0x08,
+ 0x63, 0x70, 0xfa, 0x54, 0x52, 0xe2, 0xb4, 0xac, 0x4e, 0x75, 0xa4, 0xcf, 0xed, 0xf7, 0x16, 0xa0,
+ 0xcb, 0x90, 0x46, 0xf1, 0x8c, 0xcb, 0x21, 0x93, 0xd4, 0xa3, 0x92, 0xe2, 0x3f, 0x01, 0x26, 0x3c,
+ 0x9c, 0xbe, 0x8a, 0x25, 0x95, 0x89, 0x22, 0x77, 0xa5, 0xa8, 0xc7, 0xc3, 0xe9, 0xa5, 0x22, 0x4c,
+ 0xf1, 0xca, 0x24, 0x05, 0x54, 0xf3, 0xb9, 0x6e, 0x9e, 0xd5, 0x95, 0x40, 0x4a, 0xb2, 0x54, 0x92,
+ 0xb3, 0xba, 0x34, 0xd2, 0xfe, 0x1f, 0xca, 0xa9, 0x02, 0x25, 0x51, 0x29, 0xd0, 0x3d, 0xab, 0x23,
+ 0x7d, 0xc6, 0x7f, 0x41, 0x39, 0x30, 0xca, 0x74, 0x61, 0xb7, 0x4b, 0x52, 0x2d, 0x9b, 0xca, 0x4d,
+ 0xdd, 0x65, 0x7e, 0xfb, 0x53, 0x1e, 0x4a, 0x43, 0x16, 0xc7, 0xd4, 0x67, 0xf8, 0x08, 0x1c, 0xb9,
+ 0x72, 0x78, 0x2f, 0xad, 0x61, 0xe8, 0xac, 0xc7, 0x2a, 0x0d, 0x37, 0xc0, 0x96, 0x7c, 0x6d, 0x12,
+ 0x5b, 0x72, 0x35, 0xc6, 0x54, 0xf0, 0x8d, 0x31, 0x14, 0xb2, 0x1c, 0xd0, 0xd9, 0x1c, 0x10, 0x37,
+ 0xa1, 0x74, 0xc3, 0x7d, 0x7d, 0x61, 0x85, 0x0c, 0x99, 0x82, 0x2b, 0xdb, 0x8a, 0xdb, 0xb6, 0x1d,
+ 0x41, 0x89, 0x85, 0x52, 0xcc, 0x59, 0x4c, 0x4a, 0xad, 0x7c, 0xc7, 0xed, 0xee, 0xac, 0x6d, 0x46,
+ 0x5a, 0xca, 0xe4, 0xe0, 0x03, 0x28, 0x4e, 0x78, 0x10, 0xcc, 0x25, 0x29, 0x67, 0x6a, 0x19, 0x0c,
+ 0x77, 0xa1, 0x1c, 0x1b, 0xc7, 0x48, 0x45, 0x3b, 0x89, 0x36, 0x9d, 0x4c, 0x1d, 0x4c, 0xf3, 0x54,
+ 0x45, 0xc1, 0x5e, 0xb3, 0x89, 0x24, 0xd0, 0xb2, 0x3a, 0xe5, 0xb4, 0x62, 0x82, 0xe1, 0x5f, 0x00,
+ 0x92, 0xd3, 0xd9, 0x3c, 0x94, 0xc4, 0xcd, 0xf4, 0xcc, 0xe0, 0x98, 0x40, 0x69, 0xc2, 0x43, 0xc9,
+ 0xee, 0x24, 0xa9, 0xea, 0x8b, 0x4d, 0xc3, 0xf6, 0x4b, 0xa8, 0x9c, 0x51, 0xe1, 0x25, 0xeb, 0x93,
+ 0x3a, 0x68, 0x6d, 0x39, 0x48, 0xc0, 0xb9, 0xe5, 0x92, 0xad, 0xef, 0xbb, 0x42, 0x32, 0x03, 0xe7,
+ 0xb7, 0x07, 0x6e, 0xff, 0x0c, 0x95, 0xe5, 0xba, 0xe2, 0x06, 0x14, 0x42, 0xee, 0xb1, 0x98, 0x58,
+ 0xad, 0x7c, 0xc7, 0x19, 0x25, 0x41, 0xfb, 0x83, 0x05, 0xa0, 0x72, 0x7a, 0x33, 0x1a, 0xfa, 0xfa,
+ 0xd6, 0x07, 0xfd, 0x35, 0x05, 0xf6, 0xa0, 0x8f, 0x7f, 0x37, 0x8f, 0xd3, 0xd6, 0xab, 0xf3, 0x63,
+ 0xf6, 0x29, 0x24, 0xdf, 0x6d, 0xbd, 0xd0, 0x03, 0x28, 0x9e, 0x73, 0x8f, 0x0d, 0xfa, 0xeb, 0xba,
+ 0x12, 0x4c, 0x19, 0xd2, 0x33, 0x86, 0x24, 0x8f, 0x31, 0x0d, 0x0f, 0xff, 0x80, 0xca, 0xf2, 0xc9,
+ 0xe3, 0x5d, 0x70, 0x75, 0x70, 0xce, 0x45, 0x40, 0x6f, 0x50, 0x0e, 0xef, 0xc1, 0xae, 0x06, 0x56,
+ 0x8d, 0x91, 0x75, 0xf8, 0xd9, 0x06, 0x37, 0xb3, 0xc4, 0x18, 0xa0, 0x38, 0x8c, 0xfd, 0xb3, 0x45,
+ 0x84, 0x72, 0xd8, 0x85, 0xd2, 0x30, 0xf6, 0x4f, 0x19, 0x95, 0xc8, 0x32, 0xc1, 0x85, 0xe0, 0x11,
+ 0xb2, 0x4d, 0xd6, 0x49, 0x14, 0xa1, 0x3c, 0xae, 0x01, 0x24, 0xe7, 0x11, 0x8b, 0x23, 0xe4, 0x98,
+ 0xc4, 0xff, 0xb8, 0x64, 0xa8, 0xa0, 0x44, 0x98, 0x40, 0xb3, 0x45, 0xc3, 0xaa, 0x85, 0x41, 0x25,
+ 0x8c, 0xa0, 0xaa, 0x9a, 0x31, 0x2a, 0xe4, 0xb5, 0xea, 0x52, 0xc6, 0x0d, 0x40, 0x59, 0x44, 0x7f,
+ 0x54, 0xc1, 0x18, 0x6a, 0xc3, 0xd8, 0xbf, 0x0a, 0x05, 0xa3, 0x93, 0x19, 0xbd, 0xbe, 0x61, 0x08,
+ 0x70, 0x1d, 0x76, 0x4c, 0x21, 0x75, 0x41, 0x8b, 0x18, 0xb9, 0x26, 0xad, 0x37, 0x63, 0x93, 0x37,
+ 0xff, 0x2e, 0xb8, 0x58, 0x04, 0xa8, 0x8a, 0x7f, 0x80, 0xfa, 0x30, 0xf6, 0xc7, 0x82, 0x86, 0xf1,
+ 0x94, 0x89, 0x7f, 0x18, 0xf5, 0x98, 0x40, 0x3b, 0xe6, 0xeb, 0xf1, 0x3c, 0x60, 0x7c, 0x21, 0xcf,
+ 0xf9, 0x5b, 0x54, 0x33, 0x62, 0x46, 0x8c, 0x7a, 0xfa, 0x87, 0x87, 0x76, 0x8d, 0x98, 0x25, 0xa2,
+ 0xc5, 0x20, 0x33, 0xef, 0x85, 0x60, 0x7a, 0xc4, 0xba, 0xe9, 0x6a, 0x62, 0x9d, 0x83, 0x0f, 0x5f,
+ 0x40, 0x6d, 0xfd, 0x7a, 0x95, 0x8e, 0x15, 0x72, 0xe2, 0x79, 0xea, 0x2e, 0x51, 0x0e, 0x13, 0x68,
+ 0xac, 0xe0, 0x11, 0x0b, 0xf8, 0x2d, 0xd3, 0x8c, 0xb5, 0xce, 0x5c, 0x45, 0x1e, 0x95, 0x09, 0x63,
+ 0x9f, 0x92, 0x87, 0xa7, 0x66, 0xee, 0xf1, 0xa9, 0x99, 0x7b, 0x78, 0x6e, 0x5a, 0x8f, 0xcf, 0x4d,
+ 0xeb, 0xeb, 0x73, 0xd3, 0xfa, 0xf8, 0xad, 0x99, 0xfb, 0x1e, 0x00, 0x00, 0xff, 0xff, 0xcf, 0x30,
+ 0x01, 0x41, 0x3a, 0x06, 0x00, 0x00,
+}
diff --git a/vendor/github.com/coreos/etcd/raft/raftpb/raft.proto b/vendor/github.com/coreos/etcd/raft/raftpb/raft.proto
new file mode 100644
index 0000000..806a436
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/raftpb/raft.proto
@@ -0,0 +1,93 @@
+syntax = "proto2";
+package raftpb;
+
+import "gogoproto/gogo.proto";
+
+option (gogoproto.marshaler_all) = true;
+option (gogoproto.sizer_all) = true;
+option (gogoproto.unmarshaler_all) = true;
+option (gogoproto.goproto_getters_all) = false;
+option (gogoproto.goproto_enum_prefix_all) = false;
+
+enum EntryType {
+ EntryNormal = 0;
+ EntryConfChange = 1;
+}
+
+message Entry {
+ optional uint64 Term = 2 [(gogoproto.nullable) = false]; // must be 64-bit aligned for atomic operations
+ optional uint64 Index = 3 [(gogoproto.nullable) = false]; // must be 64-bit aligned for atomic operations
+ optional EntryType Type = 1 [(gogoproto.nullable) = false];
+ optional bytes Data = 4;
+}
+
+message SnapshotMetadata {
+ optional ConfState conf_state = 1 [(gogoproto.nullable) = false];
+ optional uint64 index = 2 [(gogoproto.nullable) = false];
+ optional uint64 term = 3 [(gogoproto.nullable) = false];
+}
+
+message Snapshot {
+ optional bytes data = 1;
+ optional SnapshotMetadata metadata = 2 [(gogoproto.nullable) = false];
+}
+
+enum MessageType {
+ MsgHup = 0;
+ MsgBeat = 1;
+ MsgProp = 2;
+ MsgApp = 3;
+ MsgAppResp = 4;
+ MsgVote = 5;
+ MsgVoteResp = 6;
+ MsgSnap = 7;
+ MsgHeartbeat = 8;
+ MsgHeartbeatResp = 9;
+ MsgUnreachable = 10;
+ MsgSnapStatus = 11;
+ MsgCheckQuorum = 12;
+ MsgTransferLeader = 13;
+ MsgTimeoutNow = 14;
+ MsgReadIndex = 15;
+ MsgReadIndexResp = 16;
+ MsgPreVote = 17;
+ MsgPreVoteResp = 18;
+}
+
+message Message {
+ optional MessageType type = 1 [(gogoproto.nullable) = false];
+ optional uint64 to = 2 [(gogoproto.nullable) = false];
+ optional uint64 from = 3 [(gogoproto.nullable) = false];
+ optional uint64 term = 4 [(gogoproto.nullable) = false];
+ optional uint64 logTerm = 5 [(gogoproto.nullable) = false];
+ optional uint64 index = 6 [(gogoproto.nullable) = false];
+ repeated Entry entries = 7 [(gogoproto.nullable) = false];
+ optional uint64 commit = 8 [(gogoproto.nullable) = false];
+ optional Snapshot snapshot = 9 [(gogoproto.nullable) = false];
+ optional bool reject = 10 [(gogoproto.nullable) = false];
+ optional uint64 rejectHint = 11 [(gogoproto.nullable) = false];
+ optional bytes context = 12;
+}
+
+message HardState {
+ optional uint64 term = 1 [(gogoproto.nullable) = false];
+ optional uint64 vote = 2 [(gogoproto.nullable) = false];
+ optional uint64 commit = 3 [(gogoproto.nullable) = false];
+}
+
+message ConfState {
+ repeated uint64 nodes = 1;
+}
+
+enum ConfChangeType {
+ ConfChangeAddNode = 0;
+ ConfChangeRemoveNode = 1;
+ ConfChangeUpdateNode = 2;
+}
+
+message ConfChange {
+ optional uint64 ID = 1 [(gogoproto.nullable) = false];
+ optional ConfChangeType Type = 2 [(gogoproto.nullable) = false];
+ optional uint64 NodeID = 3 [(gogoproto.nullable) = false];
+ optional bytes Context = 4;
+}
diff --git a/vendor/github.com/coreos/etcd/raft/rawnode.go b/vendor/github.com/coreos/etcd/raft/rawnode.go
new file mode 100644
index 0000000..b950d51
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/rawnode.go
@@ -0,0 +1,264 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import (
+ "errors"
+
+ pb "github.com/coreos/etcd/raft/raftpb"
+)
+
+// ErrStepLocalMsg is returned when try to step a local raft message
+var ErrStepLocalMsg = errors.New("raft: cannot step raft local message")
+
+// ErrStepPeerNotFound is returned when try to step a response message
+// but there is no peer found in raft.prs for that node.
+var ErrStepPeerNotFound = errors.New("raft: cannot step as peer not found")
+
+// RawNode is a thread-unsafe Node.
+// The methods of this struct correspond to the methods of Node and are described
+// more fully there.
+type RawNode struct {
+ raft *raft
+ prevSoftSt *SoftState
+ prevHardSt pb.HardState
+}
+
+func (rn *RawNode) newReady() Ready {
+ return newReady(rn.raft, rn.prevSoftSt, rn.prevHardSt)
+}
+
+func (rn *RawNode) commitReady(rd Ready) {
+ if rd.SoftState != nil {
+ rn.prevSoftSt = rd.SoftState
+ }
+ if !IsEmptyHardState(rd.HardState) {
+ rn.prevHardSt = rd.HardState
+ }
+ if rn.prevHardSt.Commit != 0 {
+ // In most cases, prevHardSt and rd.HardState will be the same
+ // because when there are new entries to apply we just sent a
+ // HardState with an updated Commit value. However, on initial
+ // startup the two are different because we don't send a HardState
+ // until something changes, but we do send any un-applied but
+ // committed entries (and previously-committed entries may be
+ // incorporated into the snapshot, even if rd.CommittedEntries is
+ // empty). Therefore we mark all committed entries as applied
+ // whether they were included in rd.HardState or not.
+ rn.raft.raftLog.appliedTo(rn.prevHardSt.Commit)
+ }
+ if len(rd.Entries) > 0 {
+ e := rd.Entries[len(rd.Entries)-1]
+ rn.raft.raftLog.stableTo(e.Index, e.Term)
+ }
+ if !IsEmptySnap(rd.Snapshot) {
+ rn.raft.raftLog.stableSnapTo(rd.Snapshot.Metadata.Index)
+ }
+ if len(rd.ReadStates) != 0 {
+ rn.raft.readStates = nil
+ }
+}
+
+// NewRawNode returns a new RawNode given configuration and a list of raft peers.
+func NewRawNode(config *Config, peers []Peer) (*RawNode, error) {
+ if config.ID == 0 {
+ panic("config.ID must not be zero")
+ }
+ r := newRaft(config)
+ rn := &RawNode{
+ raft: r,
+ }
+ lastIndex, err := config.Storage.LastIndex()
+ if err != nil {
+ panic(err) // TODO(bdarnell)
+ }
+ // If the log is empty, this is a new RawNode (like StartNode); otherwise it's
+ // restoring an existing RawNode (like RestartNode).
+ // TODO(bdarnell): rethink RawNode initialization and whether the application needs
+ // to be able to tell us when it expects the RawNode to exist.
+ if lastIndex == 0 {
+ r.becomeFollower(1, None)
+ ents := make([]pb.Entry, len(peers))
+ for i, peer := range peers {
+ cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context}
+ data, err := cc.Marshal()
+ if err != nil {
+ panic("unexpected marshal error")
+ }
+
+ ents[i] = pb.Entry{Type: pb.EntryConfChange, Term: 1, Index: uint64(i + 1), Data: data}
+ }
+ r.raftLog.append(ents...)
+ r.raftLog.committed = uint64(len(ents))
+ for _, peer := range peers {
+ r.addNode(peer.ID)
+ }
+ }
+
+ // Set the initial hard and soft states after performing all initialization.
+ rn.prevSoftSt = r.softState()
+ if lastIndex == 0 {
+ rn.prevHardSt = emptyState
+ } else {
+ rn.prevHardSt = r.hardState()
+ }
+
+ return rn, nil
+}
+
+// Tick advances the internal logical clock by a single tick.
+func (rn *RawNode) Tick() {
+ rn.raft.tick()
+}
+
+// TickQuiesced advances the internal logical clock by a single tick without
+// performing any other state machine processing. It allows the caller to avoid
+// periodic heartbeats and elections when all of the peers in a Raft group are
+// known to be at the same state. Expected usage is to periodically invoke Tick
+// or TickQuiesced depending on whether the group is "active" or "quiesced".
+//
+// WARNING: Be very careful about using this method as it subverts the Raft
+// state machine. You should probably be using Tick instead.
+func (rn *RawNode) TickQuiesced() {
+ rn.raft.electionElapsed++
+}
+
+// Campaign causes this RawNode to transition to candidate state.
+func (rn *RawNode) Campaign() error {
+ return rn.raft.Step(pb.Message{
+ Type: pb.MsgHup,
+ })
+}
+
+// Propose proposes data be appended to the raft log.
+func (rn *RawNode) Propose(data []byte) error {
+ return rn.raft.Step(pb.Message{
+ Type: pb.MsgProp,
+ From: rn.raft.id,
+ Entries: []pb.Entry{
+ {Data: data},
+ }})
+}
+
+// ProposeConfChange proposes a config change.
+func (rn *RawNode) ProposeConfChange(cc pb.ConfChange) error {
+ data, err := cc.Marshal()
+ if err != nil {
+ return err
+ }
+ return rn.raft.Step(pb.Message{
+ Type: pb.MsgProp,
+ Entries: []pb.Entry{
+ {Type: pb.EntryConfChange, Data: data},
+ },
+ })
+}
+
+// ApplyConfChange applies a config change to the local node.
+func (rn *RawNode) ApplyConfChange(cc pb.ConfChange) *pb.ConfState {
+ if cc.NodeID == None {
+ rn.raft.resetPendingConf()
+ return &pb.ConfState{Nodes: rn.raft.nodes()}
+ }
+ switch cc.Type {
+ case pb.ConfChangeAddNode:
+ rn.raft.addNode(cc.NodeID)
+ case pb.ConfChangeRemoveNode:
+ rn.raft.removeNode(cc.NodeID)
+ case pb.ConfChangeUpdateNode:
+ rn.raft.resetPendingConf()
+ default:
+ panic("unexpected conf type")
+ }
+ return &pb.ConfState{Nodes: rn.raft.nodes()}
+}
+
+// Step advances the state machine using the given message.
+func (rn *RawNode) Step(m pb.Message) error {
+ // ignore unexpected local messages receiving over network
+ if IsLocalMsg(m.Type) {
+ return ErrStepLocalMsg
+ }
+ if _, ok := rn.raft.prs[m.From]; ok || !IsResponseMsg(m.Type) {
+ return rn.raft.Step(m)
+ }
+ return ErrStepPeerNotFound
+}
+
+// Ready returns the current point-in-time state of this RawNode.
+func (rn *RawNode) Ready() Ready {
+ rd := rn.newReady()
+ rn.raft.msgs = nil
+ return rd
+}
+
+// HasReady called when RawNode user need to check if any Ready pending.
+// Checking logic in this method should be consistent with Ready.containsUpdates().
+func (rn *RawNode) HasReady() bool {
+ r := rn.raft
+ if !r.softState().equal(rn.prevSoftSt) {
+ return true
+ }
+ if hardSt := r.hardState(); !IsEmptyHardState(hardSt) && !isHardStateEqual(hardSt, rn.prevHardSt) {
+ return true
+ }
+ if r.raftLog.unstable.snapshot != nil && !IsEmptySnap(*r.raftLog.unstable.snapshot) {
+ return true
+ }
+ if len(r.msgs) > 0 || len(r.raftLog.unstableEntries()) > 0 || r.raftLog.hasNextEnts() {
+ return true
+ }
+ if len(r.readStates) != 0 {
+ return true
+ }
+ return false
+}
+
+// Advance notifies the RawNode that the application has applied and saved progress in the
+// last Ready results.
+func (rn *RawNode) Advance(rd Ready) {
+ rn.commitReady(rd)
+}
+
+// Status returns the current status of the given group.
+func (rn *RawNode) Status() *Status {
+ status := getStatus(rn.raft)
+ return &status
+}
+
+// ReportUnreachable reports the given node is not reachable for the last send.
+func (rn *RawNode) ReportUnreachable(id uint64) {
+ _ = rn.raft.Step(pb.Message{Type: pb.MsgUnreachable, From: id})
+}
+
+// ReportSnapshot reports the status of the sent snapshot.
+func (rn *RawNode) ReportSnapshot(id uint64, status SnapshotStatus) {
+ rej := status == SnapshotFailure
+
+ _ = rn.raft.Step(pb.Message{Type: pb.MsgSnapStatus, From: id, Reject: rej})
+}
+
+// TransferLeader tries to transfer leadership to the given transferee.
+func (rn *RawNode) TransferLeader(transferee uint64) {
+ _ = rn.raft.Step(pb.Message{Type: pb.MsgTransferLeader, From: transferee})
+}
+
+// ReadIndex requests a read state. The read state will be set in ready.
+// Read State has a read index. Once the application advances further than the read
+// index, any linearizable read requests issued before the read request can be
+// processed safely. The read state will have the same rctx attached.
+func (rn *RawNode) ReadIndex(rctx []byte) {
+ _ = rn.raft.Step(pb.Message{Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: rctx}}})
+}
diff --git a/vendor/github.com/coreos/etcd/raft/read_only.go b/vendor/github.com/coreos/etcd/raft/read_only.go
new file mode 100644
index 0000000..05a21da
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/read_only.go
@@ -0,0 +1,118 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import pb "github.com/coreos/etcd/raft/raftpb"
+
+// ReadState provides state for read only query.
+// It's caller's responsibility to call ReadIndex first before getting
+// this state from ready, It's also caller's duty to differentiate if this
+// state is what it requests through RequestCtx, eg. given a unique id as
+// RequestCtx
+type ReadState struct {
+ Index uint64
+ RequestCtx []byte
+}
+
+type readIndexStatus struct {
+ req pb.Message
+ index uint64
+ acks map[uint64]struct{}
+}
+
+type readOnly struct {
+ option ReadOnlyOption
+ pendingReadIndex map[string]*readIndexStatus
+ readIndexQueue []string
+}
+
+func newReadOnly(option ReadOnlyOption) *readOnly {
+ return &readOnly{
+ option: option,
+ pendingReadIndex: make(map[string]*readIndexStatus),
+ }
+}
+
+// addRequest adds a read only reuqest into readonly struct.
+// `index` is the commit index of the raft state machine when it received
+// the read only request.
+// `m` is the original read only request message from the local or remote node.
+func (ro *readOnly) addRequest(index uint64, m pb.Message) {
+ ctx := string(m.Entries[0].Data)
+ if _, ok := ro.pendingReadIndex[ctx]; ok {
+ return
+ }
+ ro.pendingReadIndex[ctx] = &readIndexStatus{index: index, req: m, acks: make(map[uint64]struct{})}
+ ro.readIndexQueue = append(ro.readIndexQueue, ctx)
+}
+
+// recvAck notifies the readonly struct that the raft state machine received
+// an acknowledgment of the heartbeat that attached with the read only request
+// context.
+func (ro *readOnly) recvAck(m pb.Message) int {
+ rs, ok := ro.pendingReadIndex[string(m.Context)]
+ if !ok {
+ return 0
+ }
+
+ rs.acks[m.From] = struct{}{}
+ // add one to include an ack from local node
+ return len(rs.acks) + 1
+}
+
+// advance advances the read only request queue kept by the readonly struct.
+// It dequeues the requests until it finds the read only request that has
+// the same context as the given `m`.
+func (ro *readOnly) advance(m pb.Message) []*readIndexStatus {
+ var (
+ i int
+ found bool
+ )
+
+ ctx := string(m.Context)
+ rss := []*readIndexStatus{}
+
+ for _, okctx := range ro.readIndexQueue {
+ i++
+ rs, ok := ro.pendingReadIndex[okctx]
+ if !ok {
+ panic("cannot find corresponding read state from pending map")
+ }
+ rss = append(rss, rs)
+ if okctx == ctx {
+ found = true
+ break
+ }
+ }
+
+ if found {
+ ro.readIndexQueue = ro.readIndexQueue[i:]
+ for _, rs := range rss {
+ delete(ro.pendingReadIndex, string(rs.req.Context))
+ }
+ return rss
+ }
+
+ return nil
+}
+
+// lastPendingRequestCtx returns the context of the last pending read only
+// request in readonly struct.
+func (ro *readOnly) lastPendingRequestCtx() string {
+ if len(ro.readIndexQueue) == 0 {
+ return ""
+ }
+ return ro.readIndexQueue[len(ro.readIndexQueue)-1]
+}
diff --git a/vendor/github.com/coreos/etcd/raft/status.go b/vendor/github.com/coreos/etcd/raft/status.go
new file mode 100644
index 0000000..b690fa5
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/status.go
@@ -0,0 +1,76 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import (
+ "fmt"
+
+ pb "github.com/coreos/etcd/raft/raftpb"
+)
+
+type Status struct {
+ ID uint64
+
+ pb.HardState
+ SoftState
+
+ Applied uint64
+ Progress map[uint64]Progress
+}
+
+// getStatus gets a copy of the current raft status.
+func getStatus(r *raft) Status {
+ s := Status{ID: r.id}
+ s.HardState = r.hardState()
+ s.SoftState = *r.softState()
+
+ s.Applied = r.raftLog.applied
+
+ if s.RaftState == StateLeader {
+ s.Progress = make(map[uint64]Progress)
+ for id, p := range r.prs {
+ s.Progress[id] = *p
+ }
+ }
+
+ return s
+}
+
+// MarshalJSON translates the raft status into JSON.
+// TODO: try to simplify this by introducing ID type into raft
+func (s Status) MarshalJSON() ([]byte, error) {
+ j := fmt.Sprintf(`{"id":"%x","term":%d,"vote":"%x","commit":%d,"lead":"%x","raftState":%q,"progress":{`,
+ s.ID, s.Term, s.Vote, s.Commit, s.Lead, s.RaftState)
+
+ if len(s.Progress) == 0 {
+ j += "}}"
+ } else {
+ for k, v := range s.Progress {
+ subj := fmt.Sprintf(`"%x":{"match":%d,"next":%d,"state":%q},`, k, v.Match, v.Next, v.State)
+ j += subj
+ }
+ // remove the trailing ","
+ j = j[:len(j)-1] + "}}"
+ }
+ return []byte(j), nil
+}
+
+func (s Status) String() string {
+ b, err := s.MarshalJSON()
+ if err != nil {
+ raftLogger.Panicf("unexpected error: %v", err)
+ }
+ return string(b)
+}
diff --git a/vendor/github.com/coreos/etcd/raft/storage.go b/vendor/github.com/coreos/etcd/raft/storage.go
new file mode 100644
index 0000000..69c3a7d
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/storage.go
@@ -0,0 +1,271 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import (
+ "errors"
+ "sync"
+
+ pb "github.com/coreos/etcd/raft/raftpb"
+)
+
+// ErrCompacted is returned by Storage.Entries/Compact when a requested
+// index is unavailable because it predates the last snapshot.
+var ErrCompacted = errors.New("requested index is unavailable due to compaction")
+
+// ErrSnapOutOfDate is returned by Storage.CreateSnapshot when a requested
+// index is older than the existing snapshot.
+var ErrSnapOutOfDate = errors.New("requested index is older than the existing snapshot")
+
+// ErrUnavailable is returned by Storage interface when the requested log entries
+// are unavailable.
+var ErrUnavailable = errors.New("requested entry at index is unavailable")
+
+// ErrSnapshotTemporarilyUnavailable is returned by the Storage interface when the required
+// snapshot is temporarily unavailable.
+var ErrSnapshotTemporarilyUnavailable = errors.New("snapshot is temporarily unavailable")
+
+// Storage is an interface that may be implemented by the application
+// to retrieve log entries from storage.
+//
+// If any Storage method returns an error, the raft instance will
+// become inoperable and refuse to participate in elections; the
+// application is responsible for cleanup and recovery in this case.
+type Storage interface {
+ // InitialState returns the saved HardState and ConfState information.
+ InitialState() (pb.HardState, pb.ConfState, error)
+ // Entries returns a slice of log entries in the range [lo,hi).
+ // MaxSize limits the total size of the log entries returned, but
+ // Entries returns at least one entry if any.
+ Entries(lo, hi, maxSize uint64) ([]pb.Entry, error)
+ // Term returns the term of entry i, which must be in the range
+ // [FirstIndex()-1, LastIndex()]. The term of the entry before
+ // FirstIndex is retained for matching purposes even though the
+ // rest of that entry may not be available.
+ Term(i uint64) (uint64, error)
+ // LastIndex returns the index of the last entry in the log.
+ LastIndex() (uint64, error)
+ // FirstIndex returns the index of the first log entry that is
+ // possibly available via Entries (older entries have been incorporated
+ // into the latest Snapshot; if storage only contains the dummy entry the
+ // first log entry is not available).
+ FirstIndex() (uint64, error)
+ // Snapshot returns the most recent snapshot.
+ // If snapshot is temporarily unavailable, it should return ErrSnapshotTemporarilyUnavailable,
+ // so raft state machine could know that Storage needs some time to prepare
+ // snapshot and call Snapshot later.
+ Snapshot() (pb.Snapshot, error)
+}
+
+// MemoryStorage implements the Storage interface backed by an
+// in-memory array.
+type MemoryStorage struct {
+ // Protects access to all fields. Most methods of MemoryStorage are
+ // run on the raft goroutine, but Append() is run on an application
+ // goroutine.
+ sync.Mutex
+
+ hardState pb.HardState
+ snapshot pb.Snapshot
+ // ents[i] has raft log position i+snapshot.Metadata.Index
+ ents []pb.Entry
+}
+
+// NewMemoryStorage creates an empty MemoryStorage.
+func NewMemoryStorage() *MemoryStorage {
+ return &MemoryStorage{
+ // When starting from scratch populate the list with a dummy entry at term zero.
+ ents: make([]pb.Entry, 1),
+ }
+}
+
+// InitialState implements the Storage interface.
+func (ms *MemoryStorage) InitialState() (pb.HardState, pb.ConfState, error) {
+ return ms.hardState, ms.snapshot.Metadata.ConfState, nil
+}
+
+// SetHardState saves the current HardState.
+func (ms *MemoryStorage) SetHardState(st pb.HardState) error {
+ ms.Lock()
+ defer ms.Unlock()
+ ms.hardState = st
+ return nil
+}
+
+// Entries implements the Storage interface.
+func (ms *MemoryStorage) Entries(lo, hi, maxSize uint64) ([]pb.Entry, error) {
+ ms.Lock()
+ defer ms.Unlock()
+ offset := ms.ents[0].Index
+ if lo <= offset {
+ return nil, ErrCompacted
+ }
+ if hi > ms.lastIndex()+1 {
+ raftLogger.Panicf("entries' hi(%d) is out of bound lastindex(%d)", hi, ms.lastIndex())
+ }
+ // only contains dummy entries.
+ if len(ms.ents) == 1 {
+ return nil, ErrUnavailable
+ }
+
+ ents := ms.ents[lo-offset : hi-offset]
+ return limitSize(ents, maxSize), nil
+}
+
+// Term implements the Storage interface.
+func (ms *MemoryStorage) Term(i uint64) (uint64, error) {
+ ms.Lock()
+ defer ms.Unlock()
+ offset := ms.ents[0].Index
+ if i < offset {
+ return 0, ErrCompacted
+ }
+ if int(i-offset) >= len(ms.ents) {
+ return 0, ErrUnavailable
+ }
+ return ms.ents[i-offset].Term, nil
+}
+
+// LastIndex implements the Storage interface.
+func (ms *MemoryStorage) LastIndex() (uint64, error) {
+ ms.Lock()
+ defer ms.Unlock()
+ return ms.lastIndex(), nil
+}
+
+func (ms *MemoryStorage) lastIndex() uint64 {
+ return ms.ents[0].Index + uint64(len(ms.ents)) - 1
+}
+
+// FirstIndex implements the Storage interface.
+func (ms *MemoryStorage) FirstIndex() (uint64, error) {
+ ms.Lock()
+ defer ms.Unlock()
+ return ms.firstIndex(), nil
+}
+
+func (ms *MemoryStorage) firstIndex() uint64 {
+ return ms.ents[0].Index + 1
+}
+
+// Snapshot implements the Storage interface.
+func (ms *MemoryStorage) Snapshot() (pb.Snapshot, error) {
+ ms.Lock()
+ defer ms.Unlock()
+ return ms.snapshot, nil
+}
+
+// ApplySnapshot overwrites the contents of this Storage object with
+// those of the given snapshot.
+func (ms *MemoryStorage) ApplySnapshot(snap pb.Snapshot) error {
+ ms.Lock()
+ defer ms.Unlock()
+
+ //handle check for old snapshot being applied
+ msIndex := ms.snapshot.Metadata.Index
+ snapIndex := snap.Metadata.Index
+ if msIndex >= snapIndex {
+ return ErrSnapOutOfDate
+ }
+
+ ms.snapshot = snap
+ ms.ents = []pb.Entry{{Term: snap.Metadata.Term, Index: snap.Metadata.Index}}
+ return nil
+}
+
+// CreateSnapshot makes a snapshot which can be retrieved with Snapshot() and
+// can be used to reconstruct the state at that point.
+// If any configuration changes have been made since the last compaction,
+// the result of the last ApplyConfChange must be passed in.
+func (ms *MemoryStorage) CreateSnapshot(i uint64, cs *pb.ConfState, data []byte) (pb.Snapshot, error) {
+ ms.Lock()
+ defer ms.Unlock()
+ if i <= ms.snapshot.Metadata.Index {
+ return pb.Snapshot{}, ErrSnapOutOfDate
+ }
+
+ offset := ms.ents[0].Index
+ if i > ms.lastIndex() {
+ raftLogger.Panicf("snapshot %d is out of bound lastindex(%d)", i, ms.lastIndex())
+ }
+
+ ms.snapshot.Metadata.Index = i
+ ms.snapshot.Metadata.Term = ms.ents[i-offset].Term
+ if cs != nil {
+ ms.snapshot.Metadata.ConfState = *cs
+ }
+ ms.snapshot.Data = data
+ return ms.snapshot, nil
+}
+
+// Compact discards all log entries prior to compactIndex.
+// It is the application's responsibility to not attempt to compact an index
+// greater than raftLog.applied.
+func (ms *MemoryStorage) Compact(compactIndex uint64) error {
+ ms.Lock()
+ defer ms.Unlock()
+ offset := ms.ents[0].Index
+ if compactIndex <= offset {
+ return ErrCompacted
+ }
+ if compactIndex > ms.lastIndex() {
+ raftLogger.Panicf("compact %d is out of bound lastindex(%d)", compactIndex, ms.lastIndex())
+ }
+
+ i := compactIndex - offset
+ ents := make([]pb.Entry, 1, 1+uint64(len(ms.ents))-i)
+ ents[0].Index = ms.ents[i].Index
+ ents[0].Term = ms.ents[i].Term
+ ents = append(ents, ms.ents[i+1:]...)
+ ms.ents = ents
+ return nil
+}
+
+// Append the new entries to storage.
+// TODO (xiangli): ensure the entries are continuous and
+// entries[0].Index > ms.entries[0].Index
+func (ms *MemoryStorage) Append(entries []pb.Entry) error {
+ if len(entries) == 0 {
+ return nil
+ }
+
+ ms.Lock()
+ defer ms.Unlock()
+
+ first := ms.firstIndex()
+ last := entries[0].Index + uint64(len(entries)) - 1
+
+ // shortcut if there is no new entry.
+ if last < first {
+ return nil
+ }
+ // truncate compacted entries
+ if first > entries[0].Index {
+ entries = entries[first-entries[0].Index:]
+ }
+
+ offset := entries[0].Index - ms.ents[0].Index
+ switch {
+ case uint64(len(ms.ents)) > offset:
+ ms.ents = append([]pb.Entry{}, ms.ents[:offset]...)
+ ms.ents = append(ms.ents, entries...)
+ case uint64(len(ms.ents)) == offset:
+ ms.ents = append(ms.ents, entries...)
+ default:
+ raftLogger.Panicf("missing log entry [last: %d, append at: %d]",
+ ms.lastIndex(), entries[0].Index)
+ }
+ return nil
+}
diff --git a/vendor/github.com/coreos/etcd/raft/util.go b/vendor/github.com/coreos/etcd/raft/util.go
new file mode 100644
index 0000000..f4141fe
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/raft/util.go
@@ -0,0 +1,129 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package raft
+
+import (
+ "bytes"
+ "fmt"
+
+ pb "github.com/coreos/etcd/raft/raftpb"
+)
+
+func (st StateType) MarshalJSON() ([]byte, error) {
+ return []byte(fmt.Sprintf("%q", st.String())), nil
+}
+
+// uint64Slice implements sort interface
+type uint64Slice []uint64
+
+func (p uint64Slice) Len() int { return len(p) }
+func (p uint64Slice) Less(i, j int) bool { return p[i] < p[j] }
+func (p uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+
+func min(a, b uint64) uint64 {
+ if a > b {
+ return b
+ }
+ return a
+}
+
+func max(a, b uint64) uint64 {
+ if a > b {
+ return a
+ }
+ return b
+}
+
+func IsLocalMsg(msgt pb.MessageType) bool {
+ return msgt == pb.MsgHup || msgt == pb.MsgBeat || msgt == pb.MsgUnreachable ||
+ msgt == pb.MsgSnapStatus || msgt == pb.MsgCheckQuorum
+}
+
+func IsResponseMsg(msgt pb.MessageType) bool {
+ return msgt == pb.MsgAppResp || msgt == pb.MsgVoteResp || msgt == pb.MsgHeartbeatResp || msgt == pb.MsgUnreachable || msgt == pb.MsgPreVoteResp
+}
+
+// voteResponseType maps vote and prevote message types to their corresponding responses.
+func voteRespMsgType(msgt pb.MessageType) pb.MessageType {
+ switch msgt {
+ case pb.MsgVote:
+ return pb.MsgVoteResp
+ case pb.MsgPreVote:
+ return pb.MsgPreVoteResp
+ default:
+ panic(fmt.Sprintf("not a vote message: %s", msgt))
+ }
+}
+
+// EntryFormatter can be implemented by the application to provide human-readable formatting
+// of entry data. Nil is a valid EntryFormatter and will use a default format.
+type EntryFormatter func([]byte) string
+
+// DescribeMessage returns a concise human-readable description of a
+// Message for debugging.
+func DescribeMessage(m pb.Message, f EntryFormatter) string {
+ var buf bytes.Buffer
+ fmt.Fprintf(&buf, "%x->%x %v Term:%d Log:%d/%d", m.From, m.To, m.Type, m.Term, m.LogTerm, m.Index)
+ if m.Reject {
+ fmt.Fprintf(&buf, " Rejected")
+ if m.RejectHint != 0 {
+ fmt.Fprintf(&buf, "(Hint:%d)", m.RejectHint)
+ }
+ }
+ if m.Commit != 0 {
+ fmt.Fprintf(&buf, " Commit:%d", m.Commit)
+ }
+ if len(m.Entries) > 0 {
+ fmt.Fprintf(&buf, " Entries:[")
+ for i, e := range m.Entries {
+ if i != 0 {
+ buf.WriteString(", ")
+ }
+ buf.WriteString(DescribeEntry(e, f))
+ }
+ fmt.Fprintf(&buf, "]")
+ }
+ if !IsEmptySnap(m.Snapshot) {
+ fmt.Fprintf(&buf, " Snapshot:%v", m.Snapshot)
+ }
+ return buf.String()
+}
+
+// DescribeEntry returns a concise human-readable description of an
+// Entry for debugging.
+func DescribeEntry(e pb.Entry, f EntryFormatter) string {
+ var formatted string
+ if e.Type == pb.EntryNormal && f != nil {
+ formatted = f(e.Data)
+ } else {
+ formatted = fmt.Sprintf("%q", e.Data)
+ }
+ return fmt.Sprintf("%d/%d %s %s", e.Term, e.Index, e.Type, formatted)
+}
+
+func limitSize(ents []pb.Entry, maxSize uint64) []pb.Entry {
+ if len(ents) == 0 {
+ return ents
+ }
+ size := ents[0].Size()
+ var limit int
+ for limit = 1; limit < len(ents); limit++ {
+ size += ents[limit].Size()
+ if uint64(size) > maxSize {
+ break
+ }
+ }
+ return ents[:limit]
+}
diff --git a/vendor/github.com/coreos/etcd/snap/db.go b/vendor/github.com/coreos/etcd/snap/db.go
new file mode 100644
index 0000000..743deac
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/snap/db.go
@@ -0,0 +1,74 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package snap
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "path"
+
+ "github.com/coreos/etcd/pkg/fileutil"
+)
+
+// SaveDBFrom saves snapshot of the database from the given reader. It
+// guarantees the save operation is atomic.
+func (s *Snapshotter) SaveDBFrom(r io.Reader, id uint64) (int64, error) {
+ f, err := ioutil.TempFile(s.dir, "tmp")
+ if err != nil {
+ return 0, err
+ }
+ var n int64
+ n, err = io.Copy(f, r)
+ if err == nil {
+ err = fileutil.Fsync(f)
+ }
+ f.Close()
+ if err != nil {
+ os.Remove(f.Name())
+ return n, err
+ }
+ fn := path.Join(s.dir, fmt.Sprintf("%016x.snap.db", id))
+ if fileutil.Exist(fn) {
+ os.Remove(f.Name())
+ return n, nil
+ }
+ err = os.Rename(f.Name(), fn)
+ if err != nil {
+ os.Remove(f.Name())
+ return n, err
+ }
+
+ plog.Infof("saved database snapshot to disk [total bytes: %d]", n)
+
+ return n, nil
+}
+
+// DBFilePath returns the file path for the snapshot of the database with
+// given id. If the snapshot does not exist, it returns error.
+func (s *Snapshotter) DBFilePath(id uint64) (string, error) {
+ fns, err := fileutil.ReadDir(s.dir)
+ if err != nil {
+ return "", err
+ }
+ wfn := fmt.Sprintf("%016x.snap.db", id)
+ for _, fn := range fns {
+ if fn == wfn {
+ return path.Join(s.dir, fn), nil
+ }
+ }
+ return "", fmt.Errorf("snap: snapshot file doesn't exist")
+}
diff --git a/vendor/github.com/coreos/etcd/snap/message.go b/vendor/github.com/coreos/etcd/snap/message.go
new file mode 100644
index 0000000..d73713f
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/snap/message.go
@@ -0,0 +1,64 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package snap
+
+import (
+ "io"
+
+ "github.com/coreos/etcd/pkg/ioutil"
+ "github.com/coreos/etcd/raft/raftpb"
+)
+
+// Message is a struct that contains a raft Message and a ReadCloser. The type
+// of raft message MUST be MsgSnap, which contains the raft meta-data and an
+// additional data []byte field that contains the snapshot of the actual state
+// machine.
+// Message contains the ReadCloser field for handling large snapshot. This avoid
+// copying the entire snapshot into a byte array, which consumes a lot of memory.
+//
+// User of Message should close the Message after sending it.
+type Message struct {
+ raftpb.Message
+ ReadCloser io.ReadCloser
+ TotalSize int64
+ closeC chan bool
+}
+
+func NewMessage(rs raftpb.Message, rc io.ReadCloser, rcSize int64) *Message {
+ return &Message{
+ Message: rs,
+ ReadCloser: ioutil.NewExactReadCloser(rc, rcSize),
+ TotalSize: int64(rs.Size()) + rcSize,
+ closeC: make(chan bool, 1),
+ }
+}
+
+// CloseNotify returns a channel that receives a single value
+// when the message sent is finished. true indicates the sent
+// is successful.
+func (m Message) CloseNotify() <-chan bool {
+ return m.closeC
+}
+
+func (m Message) CloseWithError(err error) {
+ if cerr := m.ReadCloser.Close(); cerr != nil {
+ err = cerr
+ }
+ if err == nil {
+ m.closeC <- true
+ } else {
+ m.closeC <- false
+ }
+}
diff --git a/vendor/github.com/coreos/etcd/snap/metrics.go b/vendor/github.com/coreos/etcd/snap/metrics.go
new file mode 100644
index 0000000..433ef09
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/snap/metrics.go
@@ -0,0 +1,41 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package snap
+
+import "github.com/prometheus/client_golang/prometheus"
+
+var (
+ // TODO: save_fsync latency?
+ saveDurations = prometheus.NewHistogram(prometheus.HistogramOpts{
+ Namespace: "etcd_debugging",
+ Subsystem: "snap",
+ Name: "save_total_duration_seconds",
+ Help: "The total latency distributions of save called by snapshot.",
+ Buckets: prometheus.ExponentialBuckets(0.001, 2, 14),
+ })
+
+ marshallingDurations = prometheus.NewHistogram(prometheus.HistogramOpts{
+ Namespace: "etcd_debugging",
+ Subsystem: "snap",
+ Name: "save_marshalling_duration_seconds",
+ Help: "The marshalling cost distributions of save called by snapshot.",
+ Buckets: prometheus.ExponentialBuckets(0.001, 2, 14),
+ })
+)
+
+func init() {
+ prometheus.MustRegister(saveDurations)
+ prometheus.MustRegister(marshallingDurations)
+}
diff --git a/vendor/github.com/coreos/etcd/snap/snappb/snap.pb.go b/vendor/github.com/coreos/etcd/snap/snappb/snap.pb.go
new file mode 100644
index 0000000..130e227
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/snap/snappb/snap.pb.go
@@ -0,0 +1,353 @@
+// Code generated by protoc-gen-gogo.
+// source: snap.proto
+// DO NOT EDIT!
+
+/*
+ Package snappb is a generated protocol buffer package.
+
+ It is generated from these files:
+ snap.proto
+
+ It has these top-level messages:
+ Snapshot
+*/
+package snappb
+
+import (
+ "fmt"
+
+ proto "github.com/golang/protobuf/proto"
+
+ math "math"
+
+ io "io"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+type Snapshot struct {
+ Crc uint32 `protobuf:"varint,1,opt,name=crc" json:"crc"`
+ Data []byte `protobuf:"bytes,2,opt,name=data" json:"data,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Snapshot) Reset() { *m = Snapshot{} }
+func (m *Snapshot) String() string { return proto.CompactTextString(m) }
+func (*Snapshot) ProtoMessage() {}
+func (*Snapshot) Descriptor() ([]byte, []int) { return fileDescriptorSnap, []int{0} }
+
+func init() {
+ proto.RegisterType((*Snapshot)(nil), "snappb.snapshot")
+}
+func (m *Snapshot) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Snapshot) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintSnap(dAtA, i, uint64(m.Crc))
+ if m.Data != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSnap(dAtA, i, uint64(len(m.Data)))
+ i += copy(dAtA[i:], m.Data)
+ }
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func encodeFixed64Snap(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Snap(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintSnap(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func (m *Snapshot) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovSnap(uint64(m.Crc))
+ if m.Data != nil {
+ l = len(m.Data)
+ n += 1 + l + sovSnap(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func sovSnap(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozSnap(x uint64) (n int) {
+ return sovSnap(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (m *Snapshot) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnap
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: snapshot: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: snapshot: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Crc", wireType)
+ }
+ m.Crc = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnap
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Crc |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnap
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthSnap
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSnap(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSnap
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipSnap(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSnap
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSnap
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSnap
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthSnap
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSnap
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipSnap(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthSnap = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowSnap = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("snap.proto", fileDescriptorSnap) }
+
+var fileDescriptorSnap = []byte{
+ // 126 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x2a, 0xce, 0x4b, 0x2c,
+ 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0xb1, 0x0b, 0x92, 0xa4, 0x44, 0xd2, 0xf3,
+ 0xd3, 0xf3, 0xc1, 0x42, 0xfa, 0x20, 0x16, 0x44, 0x56, 0xc9, 0x8c, 0x8b, 0x03, 0x24, 0x5f, 0x9c,
+ 0x91, 0x5f, 0x22, 0x24, 0xc6, 0xc5, 0x9c, 0x5c, 0x94, 0x2c, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0xeb,
+ 0xc4, 0x72, 0xe2, 0x9e, 0x3c, 0x43, 0x10, 0x48, 0x40, 0x48, 0x88, 0x8b, 0x25, 0x25, 0xb1, 0x24,
+ 0x51, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xcc, 0x76, 0x12, 0x39, 0xf1, 0x50, 0x8e, 0xe1,
+ 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf1, 0x58, 0x8e,
+ 0x01, 0x10, 0x00, 0x00, 0xff, 0xff, 0xd8, 0x0f, 0x32, 0xb2, 0x78, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/coreos/etcd/snap/snappb/snap.proto b/vendor/github.com/coreos/etcd/snap/snappb/snap.proto
new file mode 100644
index 0000000..cd3d21d
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/snap/snappb/snap.proto
@@ -0,0 +1,14 @@
+syntax = "proto2";
+package snappb;
+
+import "gogoproto/gogo.proto";
+
+option (gogoproto.marshaler_all) = true;
+option (gogoproto.sizer_all) = true;
+option (gogoproto.unmarshaler_all) = true;
+option (gogoproto.goproto_getters_all) = false;
+
+message snapshot {
+ optional uint32 crc = 1 [(gogoproto.nullable) = false];
+ optional bytes data = 2;
+}
diff --git a/vendor/github.com/coreos/etcd/snap/snapshotter.go b/vendor/github.com/coreos/etcd/snap/snapshotter.go
new file mode 100644
index 0000000..50d09dd
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/snap/snapshotter.go
@@ -0,0 +1,204 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package snap stores raft nodes' states with snapshots.
+package snap
+
+import (
+ "errors"
+ "fmt"
+ "hash/crc32"
+ "io/ioutil"
+ "os"
+ "path"
+ "sort"
+ "strings"
+ "time"
+
+ pioutil "github.com/coreos/etcd/pkg/ioutil"
+ "github.com/coreos/etcd/pkg/pbutil"
+ "github.com/coreos/etcd/raft"
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/coreos/etcd/snap/snappb"
+
+ "github.com/coreos/pkg/capnslog"
+)
+
+const (
+ snapSuffix = ".snap"
+)
+
+var (
+ plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "snap")
+
+ ErrNoSnapshot = errors.New("snap: no available snapshot")
+ ErrEmptySnapshot = errors.New("snap: empty snapshot")
+ ErrCRCMismatch = errors.New("snap: crc mismatch")
+ crcTable = crc32.MakeTable(crc32.Castagnoli)
+
+ // A map of valid files that can be present in the snap folder.
+ validFiles = map[string]bool{
+ "db": true,
+ }
+)
+
+type Snapshotter struct {
+ dir string
+}
+
+func New(dir string) *Snapshotter {
+ return &Snapshotter{
+ dir: dir,
+ }
+}
+
+func (s *Snapshotter) SaveSnap(snapshot raftpb.Snapshot) error {
+ if raft.IsEmptySnap(snapshot) {
+ return nil
+ }
+ return s.save(&snapshot)
+}
+
+func (s *Snapshotter) save(snapshot *raftpb.Snapshot) error {
+ start := time.Now()
+
+ fname := fmt.Sprintf("%016x-%016x%s", snapshot.Metadata.Term, snapshot.Metadata.Index, snapSuffix)
+ b := pbutil.MustMarshal(snapshot)
+ crc := crc32.Update(0, crcTable, b)
+ snap := snappb.Snapshot{Crc: crc, Data: b}
+ d, err := snap.Marshal()
+ if err != nil {
+ return err
+ } else {
+ marshallingDurations.Observe(float64(time.Since(start)) / float64(time.Second))
+ }
+
+ err = pioutil.WriteAndSyncFile(path.Join(s.dir, fname), d, 0666)
+ if err == nil {
+ saveDurations.Observe(float64(time.Since(start)) / float64(time.Second))
+ } else {
+ err1 := os.Remove(path.Join(s.dir, fname))
+ if err1 != nil {
+ plog.Errorf("failed to remove broken snapshot file %s", path.Join(s.dir, fname))
+ }
+ }
+ return err
+}
+
+func (s *Snapshotter) Load() (*raftpb.Snapshot, error) {
+ names, err := s.snapNames()
+ if err != nil {
+ return nil, err
+ }
+ var snap *raftpb.Snapshot
+ for _, name := range names {
+ if snap, err = loadSnap(s.dir, name); err == nil {
+ break
+ }
+ }
+ if err != nil {
+ return nil, ErrNoSnapshot
+ }
+ return snap, nil
+}
+
+func loadSnap(dir, name string) (*raftpb.Snapshot, error) {
+ fpath := path.Join(dir, name)
+ snap, err := Read(fpath)
+ if err != nil {
+ renameBroken(fpath)
+ }
+ return snap, err
+}
+
+// Read reads the snapshot named by snapname and returns the snapshot.
+func Read(snapname string) (*raftpb.Snapshot, error) {
+ b, err := ioutil.ReadFile(snapname)
+ if err != nil {
+ plog.Errorf("cannot read file %v: %v", snapname, err)
+ return nil, err
+ }
+
+ if len(b) == 0 {
+ plog.Errorf("unexpected empty snapshot")
+ return nil, ErrEmptySnapshot
+ }
+
+ var serializedSnap snappb.Snapshot
+ if err = serializedSnap.Unmarshal(b); err != nil {
+ plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
+ return nil, err
+ }
+
+ if len(serializedSnap.Data) == 0 || serializedSnap.Crc == 0 {
+ plog.Errorf("unexpected empty snapshot")
+ return nil, ErrEmptySnapshot
+ }
+
+ crc := crc32.Update(0, crcTable, serializedSnap.Data)
+ if crc != serializedSnap.Crc {
+ plog.Errorf("corrupted snapshot file %v: crc mismatch", snapname)
+ return nil, ErrCRCMismatch
+ }
+
+ var snap raftpb.Snapshot
+ if err = snap.Unmarshal(serializedSnap.Data); err != nil {
+ plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
+ return nil, err
+ }
+ return &snap, nil
+}
+
+// snapNames returns the filename of the snapshots in logical time order (from newest to oldest).
+// If there is no available snapshots, an ErrNoSnapshot will be returned.
+func (s *Snapshotter) snapNames() ([]string, error) {
+ dir, err := os.Open(s.dir)
+ if err != nil {
+ return nil, err
+ }
+ defer dir.Close()
+ names, err := dir.Readdirnames(-1)
+ if err != nil {
+ return nil, err
+ }
+ snaps := checkSuffix(names)
+ if len(snaps) == 0 {
+ return nil, ErrNoSnapshot
+ }
+ sort.Sort(sort.Reverse(sort.StringSlice(snaps)))
+ return snaps, nil
+}
+
+func checkSuffix(names []string) []string {
+ snaps := []string{}
+ for i := range names {
+ if strings.HasSuffix(names[i], snapSuffix) {
+ snaps = append(snaps, names[i])
+ } else {
+ // If we find a file which is not a snapshot then check if it's
+ // a vaild file. If not throw out a warning.
+ if _, ok := validFiles[names[i]]; !ok {
+ plog.Warningf("skipped unexpected non snapshot file %v", names[i])
+ }
+ }
+ }
+ return snaps
+}
+
+func renameBroken(path string) {
+ brokenPath := path + ".broken"
+ if err := os.Rename(path, brokenPath); err != nil {
+ plog.Warningf("cannot rename broken snapshot file %v to %v: %v", path, brokenPath, err)
+ }
+}
diff --git a/vendor/github.com/coreos/etcd/wal/decoder.go b/vendor/github.com/coreos/etcd/wal/decoder.go
new file mode 100644
index 0000000..0d9b442
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/decoder.go
@@ -0,0 +1,185 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package wal
+
+import (
+ "bufio"
+ "encoding/binary"
+ "hash"
+ "io"
+ "sync"
+
+ "github.com/coreos/etcd/pkg/crc"
+ "github.com/coreos/etcd/pkg/pbutil"
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/coreos/etcd/wal/walpb"
+)
+
+const minSectorSize = 512
+
+type decoder struct {
+ mu sync.Mutex
+ brs []*bufio.Reader
+
+ // lastValidOff file offset following the last valid decoded record
+ lastValidOff int64
+ crc hash.Hash32
+}
+
+func newDecoder(r ...io.Reader) *decoder {
+ readers := make([]*bufio.Reader, len(r))
+ for i := range r {
+ readers[i] = bufio.NewReader(r[i])
+ }
+ return &decoder{
+ brs: readers,
+ crc: crc.New(0, crcTable),
+ }
+}
+
+func (d *decoder) decode(rec *walpb.Record) error {
+ rec.Reset()
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.decodeRecord(rec)
+}
+
+func (d *decoder) decodeRecord(rec *walpb.Record) error {
+ if len(d.brs) == 0 {
+ return io.EOF
+ }
+
+ l, err := readInt64(d.brs[0])
+ if err == io.EOF || (err == nil && l == 0) {
+ // hit end of file or preallocated space
+ d.brs = d.brs[1:]
+ if len(d.brs) == 0 {
+ return io.EOF
+ }
+ d.lastValidOff = 0
+ return d.decodeRecord(rec)
+ }
+ if err != nil {
+ return err
+ }
+
+ recBytes, padBytes := decodeFrameSize(l)
+
+ data := make([]byte, recBytes+padBytes)
+ if _, err = io.ReadFull(d.brs[0], data); err != nil {
+ // ReadFull returns io.EOF only if no bytes were read
+ // the decoder should treat this as an ErrUnexpectedEOF instead.
+ if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ }
+ return err
+ }
+ if err := rec.Unmarshal(data[:recBytes]); err != nil {
+ if d.isTornEntry(data) {
+ return io.ErrUnexpectedEOF
+ }
+ return err
+ }
+
+ // skip crc checking if the record type is crcType
+ if rec.Type != crcType {
+ d.crc.Write(rec.Data)
+ if err := rec.Validate(d.crc.Sum32()); err != nil {
+ if d.isTornEntry(data) {
+ return io.ErrUnexpectedEOF
+ }
+ return err
+ }
+ }
+ // record decoded as valid; point last valid offset to end of record
+ d.lastValidOff += recBytes + padBytes + 8
+ return nil
+}
+
+func decodeFrameSize(lenField int64) (recBytes int64, padBytes int64) {
+ // the record size is stored in the lower 56 bits of the 64-bit length
+ recBytes = int64(uint64(lenField) & ^(uint64(0xff) << 56))
+ // non-zero padding is indicated by set MSb / a negative length
+ if lenField < 0 {
+ // padding is stored in lower 3 bits of length MSB
+ padBytes = int64((uint64(lenField) >> 56) & 0x7)
+ }
+ return
+}
+
+// isTornEntry determines whether the last entry of the WAL was partially written
+// and corrupted because of a torn write.
+func (d *decoder) isTornEntry(data []byte) bool {
+ if len(d.brs) != 1 {
+ return false
+ }
+
+ fileOff := d.lastValidOff + 8
+ curOff := 0
+ chunks := [][]byte{}
+ // split data on sector boundaries
+ for curOff < len(data) {
+ chunkLen := int(minSectorSize - (fileOff % minSectorSize))
+ if chunkLen > len(data)-curOff {
+ chunkLen = len(data) - curOff
+ }
+ chunks = append(chunks, data[curOff:curOff+chunkLen])
+ fileOff += int64(chunkLen)
+ curOff += chunkLen
+ }
+
+ // if any data for a sector chunk is all 0, it's a torn write
+ for _, sect := range chunks {
+ isZero := true
+ for _, v := range sect {
+ if v != 0 {
+ isZero = false
+ break
+ }
+ }
+ if isZero {
+ return true
+ }
+ }
+ return false
+}
+
+func (d *decoder) updateCRC(prevCrc uint32) {
+ d.crc = crc.New(prevCrc, crcTable)
+}
+
+func (d *decoder) lastCRC() uint32 {
+ return d.crc.Sum32()
+}
+
+func (d *decoder) lastOffset() int64 { return d.lastValidOff }
+
+func mustUnmarshalEntry(d []byte) raftpb.Entry {
+ var e raftpb.Entry
+ pbutil.MustUnmarshal(&e, d)
+ return e
+}
+
+func mustUnmarshalState(d []byte) raftpb.HardState {
+ var s raftpb.HardState
+ pbutil.MustUnmarshal(&s, d)
+ return s
+}
+
+func readInt64(r io.Reader) (int64, error) {
+ var n int64
+ err := binary.Read(r, binary.LittleEndian, &n)
+ return n, err
+}
diff --git a/vendor/github.com/coreos/etcd/wal/doc.go b/vendor/github.com/coreos/etcd/wal/doc.go
new file mode 100644
index 0000000..a3abd69
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/doc.go
@@ -0,0 +1,75 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/*
+Package wal provides an implementation of a write ahead log that is used by
+etcd.
+
+A WAL is created at a particular directory and is made up of a number of
+segmented WAL files. Inside of each file the raft state and entries are appended
+to it with the Save method:
+
+ metadata := []byte{}
+ w, err := wal.Create("/var/lib/etcd", metadata)
+ ...
+ err := w.Save(s, ents)
+
+After saving a raft snapshot to disk, SaveSnapshot method should be called to
+record it. So WAL can match with the saved snapshot when restarting.
+
+ err := w.SaveSnapshot(walpb.Snapshot{Index: 10, Term: 2})
+
+When a user has finished using a WAL it must be closed:
+
+ w.Close()
+
+Each WAL file is a stream of WAL records. A WAL record is a length field and a wal record
+protobuf. The record protobuf contains a CRC, a type, and a data payload. The length field is a
+64-bit packed structure holding the length of the remaining logical record data in its lower
+56 bits and its physical padding in the first three bits of the most significant byte. Each
+record is 8-byte aligned so that the length field is never torn. The CRC contains the CRC32
+value of all record protobufs preceding the current record.
+
+WAL files are placed inside of the directory in the following format:
+$seq-$index.wal
+
+The first WAL file to be created will be 0000000000000000-0000000000000000.wal
+indicating an initial sequence of 0 and an initial raft index of 0. The first
+entry written to WAL MUST have raft index 0.
+
+WAL will cut its current tail wal file if its size exceeds 64MB. This will increment an internal
+sequence number and cause a new file to be created. If the last raft index saved
+was 0x20 and this is the first time cut has been called on this WAL then the sequence will
+increment from 0x0 to 0x1. The new file will be: 0000000000000001-0000000000000021.wal.
+If a second cut issues 0x10 entries with incremental index later then the file will be called:
+0000000000000002-0000000000000031.wal.
+
+At a later time a WAL can be opened at a particular snapshot. If there is no
+snapshot, an empty snapshot should be passed in.
+
+ w, err := wal.Open("/var/lib/etcd", walpb.Snapshot{Index: 10, Term: 2})
+ ...
+
+The snapshot must have been written to the WAL.
+
+Additional items cannot be Saved to this WAL until all of the items from the given
+snapshot to the end of the WAL are read first:
+
+ metadata, state, ents, err := w.ReadAll()
+
+This will give you the metadata, the last raft.State and the slice of
+raft.Entry items in the log.
+
+*/
+package wal
diff --git a/vendor/github.com/coreos/etcd/wal/encoder.go b/vendor/github.com/coreos/etcd/wal/encoder.go
new file mode 100644
index 0000000..efe5892
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/encoder.go
@@ -0,0 +1,120 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package wal
+
+import (
+ "encoding/binary"
+ "hash"
+ "io"
+ "os"
+ "sync"
+
+ "github.com/coreos/etcd/pkg/crc"
+ "github.com/coreos/etcd/pkg/ioutil"
+ "github.com/coreos/etcd/wal/walpb"
+)
+
+// walPageBytes is the alignment for flushing records to the backing Writer.
+// It should be a multiple of the minimum sector size so that WAL can safely
+// distinguish between torn writes and ordinary data corruption.
+const walPageBytes = 8 * minSectorSize
+
+type encoder struct {
+ mu sync.Mutex
+ bw *ioutil.PageWriter
+
+ crc hash.Hash32
+ buf []byte
+ uint64buf []byte
+}
+
+func newEncoder(w io.Writer, prevCrc uint32, pageOffset int) *encoder {
+ return &encoder{
+ bw: ioutil.NewPageWriter(w, walPageBytes, pageOffset),
+ crc: crc.New(prevCrc, crcTable),
+ // 1MB buffer
+ buf: make([]byte, 1024*1024),
+ uint64buf: make([]byte, 8),
+ }
+}
+
+// newFileEncoder creates a new encoder with current file offset for the page writer.
+func newFileEncoder(f *os.File, prevCrc uint32) (*encoder, error) {
+ offset, err := f.Seek(0, os.SEEK_CUR)
+ if err != nil {
+ return nil, err
+ }
+ return newEncoder(f, prevCrc, int(offset)), nil
+}
+
+func (e *encoder) encode(rec *walpb.Record) error {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+
+ e.crc.Write(rec.Data)
+ rec.Crc = e.crc.Sum32()
+ var (
+ data []byte
+ err error
+ n int
+ )
+
+ if rec.Size() > len(e.buf) {
+ data, err = rec.Marshal()
+ if err != nil {
+ return err
+ }
+ } else {
+ n, err = rec.MarshalTo(e.buf)
+ if err != nil {
+ return err
+ }
+ data = e.buf[:n]
+ }
+
+ lenField, padBytes := encodeFrameSize(len(data))
+ if err = writeUint64(e.bw, lenField, e.uint64buf); err != nil {
+ return err
+ }
+
+ if padBytes != 0 {
+ data = append(data, make([]byte, padBytes)...)
+ }
+ _, err = e.bw.Write(data)
+ return err
+}
+
+func encodeFrameSize(dataBytes int) (lenField uint64, padBytes int) {
+ lenField = uint64(dataBytes)
+ // force 8 byte alignment so length never gets a torn write
+ padBytes = (8 - (dataBytes % 8)) % 8
+ if padBytes != 0 {
+ lenField |= uint64(0x80|padBytes) << 56
+ }
+ return
+}
+
+func (e *encoder) flush() error {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ return e.bw.Flush()
+}
+
+func writeUint64(w io.Writer, n uint64, buf []byte) error {
+ // http://golang.org/src/encoding/binary/binary.go
+ binary.LittleEndian.PutUint64(buf, n)
+ _, err := w.Write(buf)
+ return err
+}
diff --git a/vendor/github.com/coreos/etcd/wal/file_pipeline.go b/vendor/github.com/coreos/etcd/wal/file_pipeline.go
new file mode 100644
index 0000000..3412210
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/file_pipeline.go
@@ -0,0 +1,97 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package wal
+
+import (
+ "fmt"
+ "os"
+ "path"
+
+ "github.com/coreos/etcd/pkg/fileutil"
+)
+
+// filePipeline pipelines allocating disk space
+type filePipeline struct {
+ // dir to put files
+ dir string
+ // size of files to make, in bytes
+ size int64
+ // count number of files generated
+ count int
+
+ filec chan *fileutil.LockedFile
+ errc chan error
+ donec chan struct{}
+}
+
+func newFilePipeline(dir string, fileSize int64) *filePipeline {
+ fp := &filePipeline{
+ dir: dir,
+ size: fileSize,
+ filec: make(chan *fileutil.LockedFile),
+ errc: make(chan error, 1),
+ donec: make(chan struct{}),
+ }
+ go fp.run()
+ return fp
+}
+
+// Open returns a fresh file for writing. Rename the file before calling
+// Open again or there will be file collisions.
+func (fp *filePipeline) Open() (f *fileutil.LockedFile, err error) {
+ select {
+ case f = <-fp.filec:
+ case err = <-fp.errc:
+ }
+ return
+}
+
+func (fp *filePipeline) Close() error {
+ close(fp.donec)
+ return <-fp.errc
+}
+
+func (fp *filePipeline) alloc() (f *fileutil.LockedFile, err error) {
+ // count % 2 so this file isn't the same as the one last published
+ fpath := path.Join(fp.dir, fmt.Sprintf("%d.tmp", fp.count%2))
+ if f, err = fileutil.LockFile(fpath, os.O_CREATE|os.O_WRONLY, fileutil.PrivateFileMode); err != nil {
+ return nil, err
+ }
+ if err = fileutil.Preallocate(f.File, fp.size, true); err != nil {
+ plog.Errorf("failed to allocate space when creating new wal file (%v)", err)
+ f.Close()
+ return nil, err
+ }
+ fp.count++
+ return f, nil
+}
+
+func (fp *filePipeline) run() {
+ defer close(fp.errc)
+ for {
+ f, err := fp.alloc()
+ if err != nil {
+ fp.errc <- err
+ return
+ }
+ select {
+ case fp.filec <- f:
+ case <-fp.donec:
+ os.Remove(f.Name())
+ f.Close()
+ return
+ }
+ }
+}
diff --git a/vendor/github.com/coreos/etcd/wal/metrics.go b/vendor/github.com/coreos/etcd/wal/metrics.go
new file mode 100644
index 0000000..9e089d3
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/metrics.go
@@ -0,0 +1,31 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package wal
+
+import "github.com/prometheus/client_golang/prometheus"
+
+var (
+ syncDurations = prometheus.NewHistogram(prometheus.HistogramOpts{
+ Namespace: "etcd",
+ Subsystem: "disk",
+ Name: "wal_fsync_duration_seconds",
+ Help: "The latency distributions of fsync called by wal.",
+ Buckets: prometheus.ExponentialBuckets(0.001, 2, 14),
+ })
+)
+
+func init() {
+ prometheus.MustRegister(syncDurations)
+}
diff --git a/vendor/github.com/coreos/etcd/wal/repair.go b/vendor/github.com/coreos/etcd/wal/repair.go
new file mode 100644
index 0000000..0a920e2
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/repair.go
@@ -0,0 +1,99 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package wal
+
+import (
+ "io"
+ "os"
+ "path"
+
+ "github.com/coreos/etcd/pkg/fileutil"
+ "github.com/coreos/etcd/wal/walpb"
+)
+
+// Repair tries to repair ErrUnexpectedEOF in the
+// last wal file by truncating.
+func Repair(dirpath string) bool {
+ f, err := openLast(dirpath)
+ if err != nil {
+ return false
+ }
+ defer f.Close()
+
+ rec := &walpb.Record{}
+ decoder := newDecoder(f)
+ for {
+ lastOffset := decoder.lastOffset()
+ err := decoder.decode(rec)
+ switch err {
+ case nil:
+ // update crc of the decoder when necessary
+ switch rec.Type {
+ case crcType:
+ crc := decoder.crc.Sum32()
+ // current crc of decoder must match the crc of the record.
+ // do no need to match 0 crc, since the decoder is a new one at this case.
+ if crc != 0 && rec.Validate(crc) != nil {
+ return false
+ }
+ decoder.updateCRC(rec.Crc)
+ }
+ continue
+ case io.EOF:
+ return true
+ case io.ErrUnexpectedEOF:
+ plog.Noticef("repairing %v", f.Name())
+ bf, bferr := os.Create(f.Name() + ".broken")
+ if bferr != nil {
+ plog.Errorf("could not repair %v, failed to create backup file", f.Name())
+ return false
+ }
+ defer bf.Close()
+
+ if _, err = f.Seek(0, os.SEEK_SET); err != nil {
+ plog.Errorf("could not repair %v, failed to read file", f.Name())
+ return false
+ }
+
+ if _, err = io.Copy(bf, f); err != nil {
+ plog.Errorf("could not repair %v, failed to copy file", f.Name())
+ return false
+ }
+
+ if err = f.Truncate(int64(lastOffset)); err != nil {
+ plog.Errorf("could not repair %v, failed to truncate file", f.Name())
+ return false
+ }
+ if err = fileutil.Fsync(f.File); err != nil {
+ plog.Errorf("could not repair %v, failed to sync file", f.Name())
+ return false
+ }
+ return true
+ default:
+ plog.Errorf("could not repair error (%v)", err)
+ return false
+ }
+ }
+}
+
+// openLast opens the last wal file for read and write.
+func openLast(dirpath string) (*fileutil.LockedFile, error) {
+ names, err := readWalNames(dirpath)
+ if err != nil {
+ return nil, err
+ }
+ last := path.Join(dirpath, names[len(names)-1])
+ return fileutil.LockFile(last, os.O_RDWR, fileutil.PrivateFileMode)
+}
diff --git a/vendor/github.com/coreos/etcd/wal/util.go b/vendor/github.com/coreos/etcd/wal/util.go
new file mode 100644
index 0000000..5c56e22
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/util.go
@@ -0,0 +1,107 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package wal
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/coreos/etcd/pkg/fileutil"
+)
+
+var (
+ badWalName = errors.New("bad wal name")
+)
+
+func Exist(dirpath string) bool {
+ names, err := fileutil.ReadDir(dirpath)
+ if err != nil {
+ return false
+ }
+ return len(names) != 0
+}
+
+// searchIndex returns the last array index of names whose raft index section is
+// equal to or smaller than the given index.
+// The given names MUST be sorted.
+func searchIndex(names []string, index uint64) (int, bool) {
+ for i := len(names) - 1; i >= 0; i-- {
+ name := names[i]
+ _, curIndex, err := parseWalName(name)
+ if err != nil {
+ plog.Panicf("parse correct name should never fail: %v", err)
+ }
+ if index >= curIndex {
+ return i, true
+ }
+ }
+ return -1, false
+}
+
+// names should have been sorted based on sequence number.
+// isValidSeq checks whether seq increases continuously.
+func isValidSeq(names []string) bool {
+ var lastSeq uint64
+ for _, name := range names {
+ curSeq, _, err := parseWalName(name)
+ if err != nil {
+ plog.Panicf("parse correct name should never fail: %v", err)
+ }
+ if lastSeq != 0 && lastSeq != curSeq-1 {
+ return false
+ }
+ lastSeq = curSeq
+ }
+ return true
+}
+func readWalNames(dirpath string) ([]string, error) {
+ names, err := fileutil.ReadDir(dirpath)
+ if err != nil {
+ return nil, err
+ }
+ wnames := checkWalNames(names)
+ if len(wnames) == 0 {
+ return nil, ErrFileNotFound
+ }
+ return wnames, nil
+}
+
+func checkWalNames(names []string) []string {
+ wnames := make([]string, 0)
+ for _, name := range names {
+ if _, _, err := parseWalName(name); err != nil {
+ // don't complain about left over tmp files
+ if !strings.HasSuffix(name, ".tmp") {
+ plog.Warningf("ignored file %v in wal", name)
+ }
+ continue
+ }
+ wnames = append(wnames, name)
+ }
+ return wnames
+}
+
+func parseWalName(str string) (seq, index uint64, err error) {
+ if !strings.HasSuffix(str, ".wal") {
+ return 0, 0, badWalName
+ }
+ _, err = fmt.Sscanf(str, "%016x-%016x.wal", &seq, &index)
+ return seq, index, err
+}
+
+func walName(seq, index uint64) string {
+ return fmt.Sprintf("%016x-%016x.wal", seq, index)
+}
diff --git a/vendor/github.com/coreos/etcd/wal/wal.go b/vendor/github.com/coreos/etcd/wal/wal.go
new file mode 100644
index 0000000..69ed6b2
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/wal.go
@@ -0,0 +1,637 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package wal
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "os"
+ "path"
+ "sync"
+ "time"
+
+ "github.com/coreos/etcd/pkg/fileutil"
+ "github.com/coreos/etcd/pkg/pbutil"
+ "github.com/coreos/etcd/raft"
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/coreos/etcd/wal/walpb"
+
+ "github.com/coreos/pkg/capnslog"
+)
+
+const (
+ metadataType int64 = iota + 1
+ entryType
+ stateType
+ crcType
+ snapshotType
+
+ // warnSyncDuration is the amount of time allotted to an fsync before
+ // logging a warning
+ warnSyncDuration = time.Second
+)
+
+var (
+ // SegmentSizeBytes is the preallocated size of each wal segment file.
+ // The actual size might be larger than this. In general, the default
+ // value should be used, but this is defined as an exported variable
+ // so that tests can set a different segment size.
+ SegmentSizeBytes int64 = 64 * 1000 * 1000 // 64MB
+
+ plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "wal")
+
+ ErrMetadataConflict = errors.New("wal: conflicting metadata found")
+ ErrFileNotFound = errors.New("wal: file not found")
+ ErrCRCMismatch = errors.New("wal: crc mismatch")
+ ErrSnapshotMismatch = errors.New("wal: snapshot mismatch")
+ ErrSnapshotNotFound = errors.New("wal: snapshot not found")
+ crcTable = crc32.MakeTable(crc32.Castagnoli)
+)
+
+// WAL is a logical representation of the stable storage.
+// WAL is either in read mode or append mode but not both.
+// A newly created WAL is in append mode, and ready for appending records.
+// A just opened WAL is in read mode, and ready for reading records.
+// The WAL will be ready for appending after reading out all the previous records.
+type WAL struct {
+ dir string // the living directory of the underlay files
+
+ // dirFile is a fd for the wal directory for syncing on Rename
+ dirFile *os.File
+
+ metadata []byte // metadata recorded at the head of each WAL
+ state raftpb.HardState // hardstate recorded at the head of WAL
+
+ start walpb.Snapshot // snapshot to start reading
+ decoder *decoder // decoder to decode records
+ readClose func() error // closer for decode reader
+
+ mu sync.Mutex
+ enti uint64 // index of the last entry saved to the wal
+ encoder *encoder // encoder to encode records
+
+ locks []*fileutil.LockedFile // the locked files the WAL holds (the name is increasing)
+ fp *filePipeline
+}
+
+// Create creates a WAL ready for appending records. The given metadata is
+// recorded at the head of each WAL file, and can be retrieved with ReadAll.
+func Create(dirpath string, metadata []byte) (*WAL, error) {
+ if Exist(dirpath) {
+ return nil, os.ErrExist
+ }
+
+ // keep temporary wal directory so WAL initialization appears atomic
+ tmpdirpath := path.Clean(dirpath) + ".tmp"
+ if fileutil.Exist(tmpdirpath) {
+ if err := os.RemoveAll(tmpdirpath); err != nil {
+ return nil, err
+ }
+ }
+ if err := fileutil.CreateDirAll(tmpdirpath); err != nil {
+ return nil, err
+ }
+
+ p := path.Join(tmpdirpath, walName(0, 0))
+ f, err := fileutil.LockFile(p, os.O_WRONLY|os.O_CREATE, fileutil.PrivateFileMode)
+ if err != nil {
+ return nil, err
+ }
+ if _, err = f.Seek(0, os.SEEK_END); err != nil {
+ return nil, err
+ }
+ if err = fileutil.Preallocate(f.File, SegmentSizeBytes, true); err != nil {
+ return nil, err
+ }
+
+ w := &WAL{
+ dir: dirpath,
+ metadata: metadata,
+ }
+ w.encoder, err = newFileEncoder(f.File, 0)
+ if err != nil {
+ return nil, err
+ }
+ w.locks = append(w.locks, f)
+ if err = w.saveCrc(0); err != nil {
+ return nil, err
+ }
+ if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil {
+ return nil, err
+ }
+ if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil {
+ return nil, err
+ }
+
+ if w, err = w.renameWal(tmpdirpath); err != nil {
+ return nil, err
+ }
+
+ // directory was renamed; sync parent dir to persist rename
+ pdir, perr := fileutil.OpenDir(path.Dir(w.dir))
+ if perr != nil {
+ return nil, perr
+ }
+ if perr = fileutil.Fsync(pdir); perr != nil {
+ return nil, perr
+ }
+ if perr = pdir.Close(); err != nil {
+ return nil, perr
+ }
+
+ return w, nil
+}
+
+// Open opens the WAL at the given snap.
+// The snap SHOULD have been previously saved to the WAL, or the following
+// ReadAll will fail.
+// The returned WAL is ready to read and the first record will be the one after
+// the given snap. The WAL cannot be appended to before reading out all of its
+// previous records.
+func Open(dirpath string, snap walpb.Snapshot) (*WAL, error) {
+ w, err := openAtIndex(dirpath, snap, true)
+ if err != nil {
+ return nil, err
+ }
+ if w.dirFile, err = fileutil.OpenDir(w.dir); err != nil {
+ return nil, err
+ }
+ return w, nil
+}
+
+// OpenForRead only opens the wal files for read.
+// Write on a read only wal panics.
+func OpenForRead(dirpath string, snap walpb.Snapshot) (*WAL, error) {
+ return openAtIndex(dirpath, snap, false)
+}
+
+func openAtIndex(dirpath string, snap walpb.Snapshot, write bool) (*WAL, error) {
+ names, err := readWalNames(dirpath)
+ if err != nil {
+ return nil, err
+ }
+
+ nameIndex, ok := searchIndex(names, snap.Index)
+ if !ok || !isValidSeq(names[nameIndex:]) {
+ return nil, ErrFileNotFound
+ }
+
+ // open the wal files
+ rcs := make([]io.ReadCloser, 0)
+ rs := make([]io.Reader, 0)
+ ls := make([]*fileutil.LockedFile, 0)
+ for _, name := range names[nameIndex:] {
+ p := path.Join(dirpath, name)
+ if write {
+ l, err := fileutil.TryLockFile(p, os.O_RDWR, fileutil.PrivateFileMode)
+ if err != nil {
+ closeAll(rcs...)
+ return nil, err
+ }
+ ls = append(ls, l)
+ rcs = append(rcs, l)
+ } else {
+ rf, err := os.OpenFile(p, os.O_RDONLY, fileutil.PrivateFileMode)
+ if err != nil {
+ closeAll(rcs...)
+ return nil, err
+ }
+ ls = append(ls, nil)
+ rcs = append(rcs, rf)
+ }
+ rs = append(rs, rcs[len(rcs)-1])
+ }
+
+ closer := func() error { return closeAll(rcs...) }
+
+ // create a WAL ready for reading
+ w := &WAL{
+ dir: dirpath,
+ start: snap,
+ decoder: newDecoder(rs...),
+ readClose: closer,
+ locks: ls,
+ }
+
+ if write {
+ // write reuses the file descriptors from read; don't close so
+ // WAL can append without dropping the file lock
+ w.readClose = nil
+ if _, _, err := parseWalName(path.Base(w.tail().Name())); err != nil {
+ closer()
+ return nil, err
+ }
+ w.fp = newFilePipeline(w.dir, SegmentSizeBytes)
+ }
+
+ return w, nil
+}
+
+// ReadAll reads out records of the current WAL.
+// If opened in write mode, it must read out all records until EOF. Or an error
+// will be returned.
+// If opened in read mode, it will try to read all records if possible.
+// If it cannot read out the expected snap, it will return ErrSnapshotNotFound.
+// If loaded snap doesn't match with the expected one, it will return
+// all the records and error ErrSnapshotMismatch.
+// TODO: detect not-last-snap error.
+// TODO: maybe loose the checking of match.
+// After ReadAll, the WAL will be ready for appending new records.
+func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ rec := &walpb.Record{}
+ decoder := w.decoder
+
+ var match bool
+ for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
+ switch rec.Type {
+ case entryType:
+ e := mustUnmarshalEntry(rec.Data)
+ if e.Index > w.start.Index {
+ ents = append(ents[:e.Index-w.start.Index-1], e)
+ }
+ w.enti = e.Index
+ case stateType:
+ state = mustUnmarshalState(rec.Data)
+ case metadataType:
+ if metadata != nil && !bytes.Equal(metadata, rec.Data) {
+ state.Reset()
+ return nil, state, nil, ErrMetadataConflict
+ }
+ metadata = rec.Data
+ case crcType:
+ crc := decoder.crc.Sum32()
+ // current crc of decoder must match the crc of the record.
+ // do no need to match 0 crc, since the decoder is a new one at this case.
+ if crc != 0 && rec.Validate(crc) != nil {
+ state.Reset()
+ return nil, state, nil, ErrCRCMismatch
+ }
+ decoder.updateCRC(rec.Crc)
+ case snapshotType:
+ var snap walpb.Snapshot
+ pbutil.MustUnmarshal(&snap, rec.Data)
+ if snap.Index == w.start.Index {
+ if snap.Term != w.start.Term {
+ state.Reset()
+ return nil, state, nil, ErrSnapshotMismatch
+ }
+ match = true
+ }
+ default:
+ state.Reset()
+ return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
+ }
+ }
+
+ switch w.tail() {
+ case nil:
+ // We do not have to read out all entries in read mode.
+ // The last record maybe a partial written one, so
+ // ErrunexpectedEOF might be returned.
+ if err != io.EOF && err != io.ErrUnexpectedEOF {
+ state.Reset()
+ return nil, state, nil, err
+ }
+ default:
+ // We must read all of the entries if WAL is opened in write mode.
+ if err != io.EOF {
+ state.Reset()
+ return nil, state, nil, err
+ }
+ // decodeRecord() will return io.EOF if it detects a zero record,
+ // but this zero record may be followed by non-zero records from
+ // a torn write. Overwriting some of these non-zero records, but
+ // not all, will cause CRC errors on WAL open. Since the records
+ // were never fully synced to disk in the first place, it's safe
+ // to zero them out to avoid any CRC errors from new writes.
+ if _, err = w.tail().Seek(w.decoder.lastOffset(), os.SEEK_SET); err != nil {
+ return nil, state, nil, err
+ }
+ if err = fileutil.ZeroToEnd(w.tail().File); err != nil {
+ return nil, state, nil, err
+ }
+ }
+
+ err = nil
+ if !match {
+ err = ErrSnapshotNotFound
+ }
+
+ // close decoder, disable reading
+ if w.readClose != nil {
+ w.readClose()
+ w.readClose = nil
+ }
+ w.start = walpb.Snapshot{}
+
+ w.metadata = metadata
+
+ if w.tail() != nil {
+ // create encoder (chain crc with the decoder), enable appending
+ w.encoder, err = newFileEncoder(w.tail().File, w.decoder.lastCRC())
+ if err != nil {
+ return
+ }
+ }
+ w.decoder = nil
+
+ return metadata, state, ents, err
+}
+
+// cut closes current file written and creates a new one ready to append.
+// cut first creates a temp wal file and writes necessary headers into it.
+// Then cut atomically rename temp wal file to a wal file.
+func (w *WAL) cut() error {
+ // close old wal file; truncate to avoid wasting space if an early cut
+ off, serr := w.tail().Seek(0, os.SEEK_CUR)
+ if serr != nil {
+ return serr
+ }
+ if err := w.tail().Truncate(off); err != nil {
+ return err
+ }
+ if err := w.sync(); err != nil {
+ return err
+ }
+
+ fpath := path.Join(w.dir, walName(w.seq()+1, w.enti+1))
+
+ // create a temp wal file with name sequence + 1, or truncate the existing one
+ newTail, err := w.fp.Open()
+ if err != nil {
+ return err
+ }
+
+ // update writer and save the previous crc
+ w.locks = append(w.locks, newTail)
+ prevCrc := w.encoder.crc.Sum32()
+ w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
+ if err != nil {
+ return err
+ }
+ if err = w.saveCrc(prevCrc); err != nil {
+ return err
+ }
+ if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
+ return err
+ }
+ if err = w.saveState(&w.state); err != nil {
+ return err
+ }
+ // atomically move temp wal file to wal file
+ if err = w.sync(); err != nil {
+ return err
+ }
+
+ off, err = w.tail().Seek(0, os.SEEK_CUR)
+ if err != nil {
+ return err
+ }
+
+ if err = os.Rename(newTail.Name(), fpath); err != nil {
+ return err
+ }
+ if err = fileutil.Fsync(w.dirFile); err != nil {
+ return err
+ }
+
+ newTail.Close()
+
+ if newTail, err = fileutil.LockFile(fpath, os.O_WRONLY, fileutil.PrivateFileMode); err != nil {
+ return err
+ }
+ if _, err = newTail.Seek(off, os.SEEK_SET); err != nil {
+ return err
+ }
+
+ w.locks[len(w.locks)-1] = newTail
+
+ prevCrc = w.encoder.crc.Sum32()
+ w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
+ if err != nil {
+ return err
+ }
+
+ plog.Infof("segmented wal file %v is created", fpath)
+ return nil
+}
+
+func (w *WAL) sync() error {
+ if w.encoder != nil {
+ if err := w.encoder.flush(); err != nil {
+ return err
+ }
+ }
+ start := time.Now()
+ err := fileutil.Fdatasync(w.tail().File)
+
+ duration := time.Since(start)
+ if duration > warnSyncDuration {
+ plog.Warningf("sync duration of %v, expected less than %v", duration, warnSyncDuration)
+ }
+ syncDurations.Observe(duration.Seconds())
+
+ return err
+}
+
+// ReleaseLockTo releases the locks, which has smaller index than the given index
+// except the largest one among them.
+// For example, if WAL is holding lock 1,2,3,4,5,6, ReleaseLockTo(4) will release
+// lock 1,2 but keep 3. ReleaseLockTo(5) will release 1,2,3 but keep 4.
+func (w *WAL) ReleaseLockTo(index uint64) error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ var smaller int
+ found := false
+
+ for i, l := range w.locks {
+ _, lockIndex, err := parseWalName(path.Base(l.Name()))
+ if err != nil {
+ return err
+ }
+ if lockIndex >= index {
+ smaller = i - 1
+ found = true
+ break
+ }
+ }
+
+ // if no lock index is greater than the release index, we can
+ // release lock up to the last one(excluding).
+ if !found && len(w.locks) != 0 {
+ smaller = len(w.locks) - 1
+ }
+
+ if smaller <= 0 {
+ return nil
+ }
+
+ for i := 0; i < smaller; i++ {
+ if w.locks[i] == nil {
+ continue
+ }
+ w.locks[i].Close()
+ }
+ w.locks = w.locks[smaller:]
+
+ return nil
+}
+
+func (w *WAL) Close() error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ if w.fp != nil {
+ w.fp.Close()
+ w.fp = nil
+ }
+
+ if w.tail() != nil {
+ if err := w.sync(); err != nil {
+ return err
+ }
+ }
+ for _, l := range w.locks {
+ if l == nil {
+ continue
+ }
+ if err := l.Close(); err != nil {
+ plog.Errorf("failed to unlock during closing wal: %s", err)
+ }
+ }
+
+ return w.dirFile.Close()
+}
+
+func (w *WAL) saveEntry(e *raftpb.Entry) error {
+ // TODO: add MustMarshalTo to reduce one allocation.
+ b := pbutil.MustMarshal(e)
+ rec := &walpb.Record{Type: entryType, Data: b}
+ if err := w.encoder.encode(rec); err != nil {
+ return err
+ }
+ w.enti = e.Index
+ return nil
+}
+
+func (w *WAL) saveState(s *raftpb.HardState) error {
+ if raft.IsEmptyHardState(*s) {
+ return nil
+ }
+ w.state = *s
+ b := pbutil.MustMarshal(s)
+ rec := &walpb.Record{Type: stateType, Data: b}
+ return w.encoder.encode(rec)
+}
+
+func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ // short cut, do not call sync
+ if raft.IsEmptyHardState(st) && len(ents) == 0 {
+ return nil
+ }
+
+ mustSync := mustSync(st, w.state, len(ents))
+
+ // TODO(xiangli): no more reference operator
+ for i := range ents {
+ if err := w.saveEntry(&ents[i]); err != nil {
+ return err
+ }
+ }
+ if err := w.saveState(&st); err != nil {
+ return err
+ }
+
+ curOff, err := w.tail().Seek(0, os.SEEK_CUR)
+ if err != nil {
+ return err
+ }
+ if curOff < SegmentSizeBytes {
+ if mustSync {
+ return w.sync()
+ }
+ return nil
+ }
+
+ return w.cut()
+}
+
+func (w *WAL) SaveSnapshot(e walpb.Snapshot) error {
+ b := pbutil.MustMarshal(&e)
+
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ rec := &walpb.Record{Type: snapshotType, Data: b}
+ if err := w.encoder.encode(rec); err != nil {
+ return err
+ }
+ // update enti only when snapshot is ahead of last index
+ if w.enti < e.Index {
+ w.enti = e.Index
+ }
+ return w.sync()
+}
+
+func (w *WAL) saveCrc(prevCrc uint32) error {
+ return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
+}
+
+func (w *WAL) tail() *fileutil.LockedFile {
+ if len(w.locks) > 0 {
+ return w.locks[len(w.locks)-1]
+ }
+ return nil
+}
+
+func (w *WAL) seq() uint64 {
+ t := w.tail()
+ if t == nil {
+ return 0
+ }
+ seq, _, err := parseWalName(path.Base(t.Name()))
+ if err != nil {
+ plog.Fatalf("bad wal name %s (%v)", t.Name(), err)
+ }
+ return seq
+}
+
+func mustSync(st, prevst raftpb.HardState, entsnum int) bool {
+ // Persistent state on all servers:
+ // (Updated on stable storage before responding to RPCs)
+ // currentTerm
+ // votedFor
+ // log entries[]
+ return entsnum != 0 || st.Vote != prevst.Vote || st.Term != prevst.Term
+}
+
+func closeAll(rcs ...io.ReadCloser) error {
+ for _, f := range rcs {
+ if err := f.Close(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/coreos/etcd/wal/wal_unix.go b/vendor/github.com/coreos/etcd/wal/wal_unix.go
new file mode 100644
index 0000000..82fd6a1
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/wal_unix.go
@@ -0,0 +1,44 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build !windows
+
+package wal
+
+import (
+ "os"
+
+ "github.com/coreos/etcd/pkg/fileutil"
+)
+
+func (w *WAL) renameWal(tmpdirpath string) (*WAL, error) {
+ // On non-Windows platforms, hold the lock while renaming. Releasing
+ // the lock and trying to reacquire it quickly can be flaky because
+ // it's possible the process will fork to spawn a process while this is
+ // happening. The fds are set up as close-on-exec by the Go runtime,
+ // but there is a window between the fork and the exec where another
+ // process holds the lock.
+
+ if err := os.RemoveAll(w.dir); err != nil {
+ return nil, err
+ }
+ if err := os.Rename(tmpdirpath, w.dir); err != nil {
+ return nil, err
+ }
+
+ w.fp = newFilePipeline(w.dir, SegmentSizeBytes)
+ df, err := fileutil.OpenDir(w.dir)
+ w.dirFile = df
+ return w, err
+}
diff --git a/vendor/github.com/coreos/etcd/wal/wal_windows.go b/vendor/github.com/coreos/etcd/wal/wal_windows.go
new file mode 100644
index 0000000..0b9e434
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/wal_windows.go
@@ -0,0 +1,41 @@
+// Copyright 2016 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package wal
+
+import (
+ "os"
+
+ "github.com/coreos/etcd/wal/walpb"
+)
+
+func (w *WAL) renameWal(tmpdirpath string) (*WAL, error) {
+ // rename of directory with locked files doesn't work on
+ // windows; close the WAL to release the locks so the directory
+ // can be renamed
+ w.Close()
+ if err := os.Rename(tmpdirpath, w.dir); err != nil {
+ return nil, err
+ }
+ // reopen and relock
+ newWAL, oerr := Open(w.dir, walpb.Snapshot{})
+ if oerr != nil {
+ return nil, oerr
+ }
+ if _, _, _, err := newWAL.ReadAll(); err != nil {
+ newWAL.Close()
+ return nil, err
+ }
+ return newWAL, nil
+}
diff --git a/vendor/github.com/coreos/etcd/wal/walpb/record.go b/vendor/github.com/coreos/etcd/wal/walpb/record.go
new file mode 100644
index 0000000..30a05e0
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/walpb/record.go
@@ -0,0 +1,29 @@
+// Copyright 2015 The etcd Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package walpb
+
+import "errors"
+
+var (
+ ErrCRCMismatch = errors.New("walpb: crc mismatch")
+)
+
+func (rec *Record) Validate(crc uint32) error {
+ if rec.Crc == crc {
+ return nil
+ }
+ rec.Reset()
+ return ErrCRCMismatch
+}
diff --git a/vendor/github.com/coreos/etcd/wal/walpb/record.pb.go b/vendor/github.com/coreos/etcd/wal/walpb/record.pb.go
new file mode 100644
index 0000000..e1a77d5
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/walpb/record.pb.go
@@ -0,0 +1,521 @@
+// Code generated by protoc-gen-gogo.
+// source: record.proto
+// DO NOT EDIT!
+
+/*
+ Package walpb is a generated protocol buffer package.
+
+ It is generated from these files:
+ record.proto
+
+ It has these top-level messages:
+ Record
+ Snapshot
+*/
+package walpb
+
+import (
+ "fmt"
+
+ proto "github.com/golang/protobuf/proto"
+
+ math "math"
+
+ io "io"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+type Record struct {
+ Type int64 `protobuf:"varint,1,opt,name=type" json:"type"`
+ Crc uint32 `protobuf:"varint,2,opt,name=crc" json:"crc"`
+ Data []byte `protobuf:"bytes,3,opt,name=data" json:"data,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Record) Reset() { *m = Record{} }
+func (m *Record) String() string { return proto.CompactTextString(m) }
+func (*Record) ProtoMessage() {}
+func (*Record) Descriptor() ([]byte, []int) { return fileDescriptorRecord, []int{0} }
+
+type Snapshot struct {
+ Index uint64 `protobuf:"varint,1,opt,name=index" json:"index"`
+ Term uint64 `protobuf:"varint,2,opt,name=term" json:"term"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Snapshot) Reset() { *m = Snapshot{} }
+func (m *Snapshot) String() string { return proto.CompactTextString(m) }
+func (*Snapshot) ProtoMessage() {}
+func (*Snapshot) Descriptor() ([]byte, []int) { return fileDescriptorRecord, []int{1} }
+
+func init() {
+ proto.RegisterType((*Record)(nil), "walpb.Record")
+ proto.RegisterType((*Snapshot)(nil), "walpb.Snapshot")
+}
+func (m *Record) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Record) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRecord(dAtA, i, uint64(m.Type))
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintRecord(dAtA, i, uint64(m.Crc))
+ if m.Data != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintRecord(dAtA, i, uint64(len(m.Data)))
+ i += copy(dAtA[i:], m.Data)
+ }
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func (m *Snapshot) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Snapshot) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRecord(dAtA, i, uint64(m.Index))
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintRecord(dAtA, i, uint64(m.Term))
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func encodeFixed64Record(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Record(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintRecord(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func (m *Record) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovRecord(uint64(m.Type))
+ n += 1 + sovRecord(uint64(m.Crc))
+ if m.Data != nil {
+ l = len(m.Data)
+ n += 1 + l + sovRecord(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *Snapshot) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovRecord(uint64(m.Index))
+ n += 1 + sovRecord(uint64(m.Term))
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func sovRecord(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozRecord(x uint64) (n int) {
+ return sovRecord(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (m *Record) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Record: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Record: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Type |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Crc", wireType)
+ }
+ m.Crc = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Crc |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthRecord
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRecord(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRecord
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Snapshot) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Snapshot: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Snapshot: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
+ }
+ m.Index = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Index |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Term", wireType)
+ }
+ m.Term = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Term |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRecord(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRecord
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipRecord(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthRecord
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRecord
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipRecord(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthRecord = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowRecord = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("record.proto", fileDescriptorRecord) }
+
+var fileDescriptorRecord = []byte{
+ // 186 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0x4a, 0x4d, 0xce,
+ 0x2f, 0x4a, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2d, 0x4f, 0xcc, 0x29, 0x48, 0x92,
+ 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x8b, 0xe8, 0x83, 0x58, 0x10, 0x49, 0x25, 0x3f, 0x2e, 0xb6,
+ 0x20, 0xb0, 0x62, 0x21, 0x09, 0x2e, 0x96, 0x92, 0xca, 0x82, 0x54, 0x09, 0x46, 0x05, 0x46, 0x0d,
+ 0x66, 0x27, 0x96, 0x13, 0xf7, 0xe4, 0x19, 0x82, 0xc0, 0x22, 0x42, 0x62, 0x5c, 0xcc, 0xc9, 0x45,
+ 0xc9, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xbc, 0x50, 0x09, 0x90, 0x80, 0x90, 0x10, 0x17, 0x4b, 0x4a,
+ 0x62, 0x49, 0xa2, 0x04, 0xb3, 0x02, 0xa3, 0x06, 0x4f, 0x10, 0x98, 0xad, 0xe4, 0xc0, 0xc5, 0x11,
+ 0x9c, 0x97, 0x58, 0x50, 0x9c, 0x91, 0x5f, 0x22, 0x24, 0xc5, 0xc5, 0x9a, 0x99, 0x97, 0x92, 0x5a,
+ 0x01, 0x36, 0x92, 0x05, 0xaa, 0x13, 0x22, 0x04, 0xb6, 0x2d, 0xb5, 0x28, 0x17, 0x6c, 0x28, 0x0b,
+ 0xdc, 0xb6, 0xd4, 0xa2, 0x5c, 0x27, 0x91, 0x13, 0x0f, 0xe5, 0x18, 0x4e, 0x3c, 0x92, 0x63, 0xbc,
+ 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x19, 0x8f, 0xe5, 0x18, 0x00, 0x01, 0x00, 0x00,
+ 0xff, 0xff, 0x7f, 0x5e, 0x5c, 0x46, 0xd3, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/coreos/etcd/wal/walpb/record.proto b/vendor/github.com/coreos/etcd/wal/walpb/record.proto
new file mode 100644
index 0000000..b694cb2
--- /dev/null
+++ b/vendor/github.com/coreos/etcd/wal/walpb/record.proto
@@ -0,0 +1,20 @@
+syntax = "proto2";
+package walpb;
+
+import "gogoproto/gogo.proto";
+
+option (gogoproto.marshaler_all) = true;
+option (gogoproto.sizer_all) = true;
+option (gogoproto.unmarshaler_all) = true;
+option (gogoproto.goproto_getters_all) = false;
+
+message Record {
+ optional int64 type = 1 [(gogoproto.nullable) = false];
+ optional uint32 crc = 2 [(gogoproto.nullable) = false];
+ optional bytes data = 3;
+}
+
+message Snapshot {
+ optional uint64 index = 1 [(gogoproto.nullable) = false];
+ optional uint64 term = 2 [(gogoproto.nullable) = false];
+}
diff --git a/vendor/github.com/coreos/go-systemd/LICENSE b/vendor/github.com/coreos/go-systemd/LICENSE
new file mode 100644
index 0000000..37ec93a
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/LICENSE
@@ -0,0 +1,191 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and
+distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright
+owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities
+that control, are controlled by, or are under common control with that entity.
+For the purposes of this definition, "control" means (i) the power, direct or
+indirect, to cause the direction or management of such entity, whether by
+contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
+outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising
+permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including
+but not limited to software source code, documentation source, and configuration
+files.
+
+"Object" form shall mean any form resulting from mechanical transformation or
+translation of a Source form, including but not limited to compiled object code,
+generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made
+available under the License, as indicated by a copyright notice that is included
+in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that
+is based on (or derived from) the Work and for which the editorial revisions,
+annotations, elaborations, or other modifications represent, as a whole, an
+original work of authorship. For the purposes of this License, Derivative Works
+shall not include works that remain separable from, or merely link (or bind by
+name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version
+of the Work and any modifications or additions to that Work or Derivative Works
+thereof, that is intentionally submitted to Licensor for inclusion in the Work
+by the copyright owner or by an individual or Legal Entity authorized to submit
+on behalf of the copyright owner. For the purposes of this definition,
+"submitted" means any form of electronic, verbal, or written communication sent
+to the Licensor or its representatives, including but not limited to
+communication on electronic mailing lists, source code control systems, and
+issue tracking systems that are managed by, or on behalf of, the Licensor for
+the purpose of discussing and improving the Work, but excluding communication
+that is conspicuously marked or otherwise designated in writing by the copyright
+owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
+of whom a Contribution has been received by Licensor and subsequently
+incorporated within the Work.
+
+2. Grant of Copyright License.
+
+Subject to the terms and conditions of this License, each Contributor hereby
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+irrevocable copyright license to reproduce, prepare Derivative Works of,
+publicly display, publicly perform, sublicense, and distribute the Work and such
+Derivative Works in Source or Object form.
+
+3. Grant of Patent License.
+
+Subject to the terms and conditions of this License, each Contributor hereby
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+irrevocable (except as stated in this section) patent license to make, have
+made, use, offer to sell, sell, import, and otherwise transfer the Work, where
+such license applies only to those patent claims licensable by such Contributor
+that are necessarily infringed by their Contribution(s) alone or by combination
+of their Contribution(s) with the Work to which such Contribution(s) was
+submitted. If You institute patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Work or a
+Contribution incorporated within the Work constitutes direct or contributory
+patent infringement, then any patent licenses granted to You under this License
+for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution.
+
+You may reproduce and distribute copies of the Work or Derivative Works thereof
+in any medium, with or without modifications, and in Source or Object form,
+provided that You meet the following conditions:
+
+You must give any other recipients of the Work or Derivative Works a copy of
+this License; and
+You must cause any modified files to carry prominent notices stating that You
+changed the files; and
+You must retain, in the Source form of any Derivative Works that You distribute,
+all copyright, patent, trademark, and attribution notices from the Source form
+of the Work, excluding those notices that do not pertain to any part of the
+Derivative Works; and
+If the Work includes a "NOTICE" text file as part of its distribution, then any
+Derivative Works that You distribute must include a readable copy of the
+attribution notices contained within such NOTICE file, excluding those notices
+that do not pertain to any part of the Derivative Works, in at least one of the
+following places: within a NOTICE text file distributed as part of the
+Derivative Works; within the Source form or documentation, if provided along
+with the Derivative Works; or, within a display generated by the Derivative
+Works, if and wherever such third-party notices normally appear. The contents of
+the NOTICE file are for informational purposes only and do not modify the
+License. You may add Your own attribution notices within Derivative Works that
+You distribute, alongside or as an addendum to the NOTICE text from the Work,
+provided that such additional attribution notices cannot be construed as
+modifying the License.
+You may add Your own copyright statement to Your modifications and may provide
+additional or different license terms and conditions for use, reproduction, or
+distribution of Your modifications, or for any such Derivative Works as a whole,
+provided Your use, reproduction, and distribution of the Work otherwise complies
+with the conditions stated in this License.
+
+5. Submission of Contributions.
+
+Unless You explicitly state otherwise, any Contribution intentionally submitted
+for inclusion in the Work by You to the Licensor shall be under the terms and
+conditions of this License, without any additional terms or conditions.
+Notwithstanding the above, nothing herein shall supersede or modify the terms of
+any separate license agreement you may have executed with Licensor regarding
+such Contributions.
+
+6. Trademarks.
+
+This License does not grant permission to use the trade names, trademarks,
+service marks, or product names of the Licensor, except as required for
+reasonable and customary use in describing the origin of the Work and
+reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty.
+
+Unless required by applicable law or agreed to in writing, Licensor provides the
+Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
+including, without limitation, any warranties or conditions of TITLE,
+NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
+solely responsible for determining the appropriateness of using or
+redistributing the Work and assume any risks associated with Your exercise of
+permissions under this License.
+
+8. Limitation of Liability.
+
+In no event and under no legal theory, whether in tort (including negligence),
+contract, or otherwise, unless required by applicable law (such as deliberate
+and grossly negligent acts) or agreed to in writing, shall any Contributor be
+liable to You for damages, including any direct, indirect, special, incidental,
+or consequential damages of any character arising as a result of this License or
+out of the use or inability to use the Work (including but not limited to
+damages for loss of goodwill, work stoppage, computer failure or malfunction, or
+any and all other commercial damages or losses), even if such Contributor has
+been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability.
+
+While redistributing the Work or Derivative Works thereof, You may choose to
+offer, and charge a fee for, acceptance of support, warranty, indemnity, or
+other liability obligations and/or rights consistent with this License. However,
+in accepting such obligations, You may act only on Your own behalf and on Your
+sole responsibility, not on behalf of any other Contributor, and only if You
+agree to indemnify, defend, and hold each Contributor harmless for any liability
+incurred by, or claims asserted against, such Contributor by reason of your
+accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work
+
+To apply the Apache License to your work, attach the following boilerplate
+notice, with the fields enclosed by brackets "[]" replaced with your own
+identifying information. (Don't include the brackets!) The text should be
+enclosed in the appropriate comment syntax for the file format. We also
+recommend that a file or class name and description of purpose be included on
+the same "printed page" as the copyright notice for easier identification within
+third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/coreos/go-systemd/README.md b/vendor/github.com/coreos/go-systemd/README.md
new file mode 100644
index 0000000..cb87a11
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/README.md
@@ -0,0 +1,54 @@
+# go-systemd
+
+[![Build Status](https://travis-ci.org/coreos/go-systemd.png?branch=master)](https://travis-ci.org/coreos/go-systemd)
+[![godoc](https://godoc.org/github.com/coreos/go-systemd?status.svg)](http://godoc.org/github.com/coreos/go-systemd)
+
+Go bindings to systemd. The project has several packages:
+
+- `activation` - for writing and using socket activation from Go
+- `dbus` - for starting/stopping/inspecting running services and units
+- `journal` - for writing to systemd's logging service, journald
+- `sdjournal` - for reading from journald by wrapping its C API
+- `machine1` - for registering machines/containers with systemd
+- `unit` - for (de)serialization and comparison of unit files
+
+## Socket Activation
+
+An example HTTP server using socket activation can be quickly set up by following this README on a Linux machine running systemd:
+
+https://github.com/coreos/go-systemd/tree/master/examples/activation/httpserver
+
+## Journal
+
+Using the pure-Go `journal` package you can submit journal entries directly to systemd's journal, taking advantage of features like indexed key/value pairs for each log entry.
+The `sdjournal` package provides read access to the journal by wrapping around journald's native C API; consequently it requires cgo and the journal headers to be available.
+
+## D-Bus
+
+The `dbus` package connects to the [systemd D-Bus API](http://www.freedesktop.org/wiki/Software/systemd/dbus/) and lets you start, stop and introspect systemd units. The API docs are here:
+
+http://godoc.org/github.com/coreos/go-systemd/dbus
+
+### Debugging
+
+Create `/etc/dbus-1/system-local.conf` that looks like this:
+
+```
+<!DOCTYPE busconfig PUBLIC
+"-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
+"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+<busconfig>
+ <policy user="root">
+ <allow eavesdrop="true"/>
+ <allow eavesdrop="true" send_destination="*"/>
+ </policy>
+</busconfig>
+```
+
+## machined
+
+The `machine1` package allows interaction with the [systemd machined D-Bus API](http://www.freedesktop.org/wiki/Software/systemd/machined/).
+
+## Units
+
+The `unit` package provides various functions for working with [systemd unit files](http://www.freedesktop.org/software/systemd/man/systemd.unit.html).
diff --git a/vendor/github.com/coreos/go-systemd/activation/files.go b/vendor/github.com/coreos/go-systemd/activation/files.go
new file mode 100644
index 0000000..c8e85fc
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/activation/files.go
@@ -0,0 +1,52 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 activation implements primitives for systemd socket activation.
+package activation
+
+import (
+ "os"
+ "strconv"
+ "syscall"
+)
+
+// based on: https://gist.github.com/alberts/4640792
+const (
+ listenFdsStart = 3
+)
+
+func Files(unsetEnv bool) []*os.File {
+ if unsetEnv {
+ defer os.Unsetenv("LISTEN_PID")
+ defer os.Unsetenv("LISTEN_FDS")
+ }
+
+ pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
+ if err != nil || pid != os.Getpid() {
+ return nil
+ }
+
+ nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
+ if err != nil || nfds == 0 {
+ return nil
+ }
+
+ files := make([]*os.File, 0, nfds)
+ for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ {
+ syscall.CloseOnExec(fd)
+ files = append(files, os.NewFile(uintptr(fd), "LISTEN_FD_"+strconv.Itoa(fd)))
+ }
+
+ return files
+}
diff --git a/vendor/github.com/coreos/go-systemd/activation/listeners.go b/vendor/github.com/coreos/go-systemd/activation/listeners.go
new file mode 100644
index 0000000..fd5dfc7
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/activation/listeners.go
@@ -0,0 +1,60 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 activation
+
+import (
+ "crypto/tls"
+ "net"
+)
+
+// Listeners returns a slice containing a net.Listener for each matching socket type
+// passed to this process.
+//
+// The order of the file descriptors is preserved in the returned slice.
+// Nil values are used to fill any gaps. For example if systemd were to return file descriptors
+// corresponding with "udp, tcp, tcp", then the slice would contain {nil, net.Listener, net.Listener}
+func Listeners(unsetEnv bool) ([]net.Listener, error) {
+ files := Files(unsetEnv)
+ listeners := make([]net.Listener, len(files))
+
+ for i, f := range files {
+ if pc, err := net.FileListener(f); err == nil {
+ listeners[i] = pc
+ }
+ }
+ return listeners, nil
+}
+
+// TLSListeners returns a slice containing a net.listener for each matching TCP socket type
+// passed to this process.
+// It uses default Listeners func and forces TCP sockets handlers to use TLS based on tlsConfig.
+func TLSListeners(unsetEnv bool, tlsConfig *tls.Config) ([]net.Listener, error) {
+ listeners, err := Listeners(unsetEnv)
+
+ if listeners == nil || err != nil {
+ return nil, err
+ }
+
+ if tlsConfig != nil && err == nil {
+ for i, l := range listeners {
+ // Activate TLS only for TCP sockets
+ if l.Addr().Network() == "tcp" {
+ listeners[i] = tls.NewListener(l, tlsConfig)
+ }
+ }
+ }
+
+ return listeners, err
+}
diff --git a/vendor/github.com/coreos/go-systemd/activation/packetconns.go b/vendor/github.com/coreos/go-systemd/activation/packetconns.go
new file mode 100644
index 0000000..48b2ca0
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/activation/packetconns.go
@@ -0,0 +1,37 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 activation
+
+import (
+ "net"
+)
+
+// PacketConns returns a slice containing a net.PacketConn for each matching socket type
+// passed to this process.
+//
+// The order of the file descriptors is preserved in the returned slice.
+// Nil values are used to fill any gaps. For example if systemd were to return file descriptors
+// corresponding with "udp, tcp, udp", then the slice would contain {net.PacketConn, nil, net.PacketConn}
+func PacketConns(unsetEnv bool) ([]net.PacketConn, error) {
+ files := Files(unsetEnv)
+ conns := make([]net.PacketConn, len(files))
+
+ for i, f := range files {
+ if pc, err := net.FilePacketConn(f); err == nil {
+ conns[i] = pc
+ }
+ }
+ return conns, nil
+}
diff --git a/vendor/github.com/coreos/go-systemd/daemon/sdnotify.go b/vendor/github.com/coreos/go-systemd/daemon/sdnotify.go
new file mode 100644
index 0000000..ba6d41d
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/daemon/sdnotify.go
@@ -0,0 +1,63 @@
+// Copyright 2014 Docker, Inc.
+//
+// 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.
+//
+
+// Code forked from Docker project
+package daemon
+
+import (
+ "net"
+ "os"
+)
+
+// SdNotify sends a message to the init daemon. It is common to ignore the error.
+// If `unsetEnvironment` is true, the environment variable `NOTIFY_SOCKET`
+// will be unconditionally unset.
+//
+// It returns one of the following:
+// (false, nil) - notification not supported (i.e. NOTIFY_SOCKET is unset)
+// (false, err) - notification supported, but failure happened (e.g. error connecting to NOTIFY_SOCKET or while sending data)
+// (true, nil) - notification supported, data has been sent
+func SdNotify(unsetEnvironment bool, state string) (sent bool, err error) {
+ socketAddr := &net.UnixAddr{
+ Name: os.Getenv("NOTIFY_SOCKET"),
+ Net: "unixgram",
+ }
+
+ // NOTIFY_SOCKET not set
+ if socketAddr.Name == "" {
+ return false, nil
+ }
+
+ if unsetEnvironment {
+ err = os.Unsetenv("NOTIFY_SOCKET")
+ }
+ if err != nil {
+ return false, err
+ }
+
+ conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
+ // Error connecting to NOTIFY_SOCKET
+ if err != nil {
+ return false, err
+ }
+ defer conn.Close()
+
+ _, err = conn.Write([]byte(state))
+ // Error sending the message
+ if err != nil {
+ return false, err
+ }
+ return true, nil
+}
diff --git a/vendor/github.com/coreos/go-systemd/daemon/watchdog.go b/vendor/github.com/coreos/go-systemd/daemon/watchdog.go
new file mode 100644
index 0000000..35a92e6
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/daemon/watchdog.go
@@ -0,0 +1,72 @@
+// Copyright 2016 CoreOS, Inc.
+//
+// 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 daemon
+
+import (
+ "fmt"
+ "os"
+ "strconv"
+ "time"
+)
+
+// SdWatchdogEnabled return watchdog information for a service.
+// Process should send daemon.SdNotify("WATCHDOG=1") every time / 2.
+// If `unsetEnvironment` is true, the environment variables `WATCHDOG_USEC`
+// and `WATCHDOG_PID` will be unconditionally unset.
+//
+// It returns one of the following:
+// (0, nil) - watchdog isn't enabled or we aren't the watched PID.
+// (0, err) - an error happened (e.g. error converting time).
+// (time, nil) - watchdog is enabled and we can send ping.
+// time is delay before inactive service will be killed.
+func SdWatchdogEnabled(unsetEnvironment bool) (time.Duration, error) {
+ wusec := os.Getenv("WATCHDOG_USEC")
+ wpid := os.Getenv("WATCHDOG_PID")
+ if unsetEnvironment {
+ wusecErr := os.Unsetenv("WATCHDOG_USEC")
+ wpidErr := os.Unsetenv("WATCHDOG_PID")
+ if wusecErr != nil {
+ return 0, wusecErr
+ }
+ if wpidErr != nil {
+ return 0, wpidErr
+ }
+ }
+
+ if wusec == "" {
+ return 0, nil
+ }
+ s, err := strconv.Atoi(wusec)
+ if err != nil {
+ return 0, fmt.Errorf("error converting WATCHDOG_USEC: %s", err)
+ }
+ if s <= 0 {
+ return 0, fmt.Errorf("error WATCHDOG_USEC must be a positive number")
+ }
+ interval := time.Duration(s) * time.Microsecond
+
+ if wpid == "" {
+ return interval, nil
+ }
+ p, err := strconv.Atoi(wpid)
+ if err != nil {
+ return 0, fmt.Errorf("error converting WATCHDOG_PID: %s", err)
+ }
+ if os.Getpid() != p {
+ return 0, nil
+ }
+
+ return interval, nil
+}
diff --git a/vendor/github.com/coreos/go-systemd/dbus/dbus.go b/vendor/github.com/coreos/go-systemd/dbus/dbus.go
new file mode 100644
index 0000000..c1694fb
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/dbus/dbus.go
@@ -0,0 +1,213 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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.
+
+// Integration with the systemd D-Bus API. See http://www.freedesktop.org/wiki/Software/systemd/dbus/
+package dbus
+
+import (
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/godbus/dbus"
+)
+
+const (
+ alpha = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`
+ num = `0123456789`
+ alphanum = alpha + num
+ signalBuffer = 100
+)
+
+// needsEscape checks whether a byte in a potential dbus ObjectPath needs to be escaped
+func needsEscape(i int, b byte) bool {
+ // Escape everything that is not a-z-A-Z-0-9
+ // Also escape 0-9 if it's the first character
+ return strings.IndexByte(alphanum, b) == -1 ||
+ (i == 0 && strings.IndexByte(num, b) != -1)
+}
+
+// PathBusEscape sanitizes a constituent string of a dbus ObjectPath using the
+// rules that systemd uses for serializing special characters.
+func PathBusEscape(path string) string {
+ // Special case the empty string
+ if len(path) == 0 {
+ return "_"
+ }
+ n := []byte{}
+ for i := 0; i < len(path); i++ {
+ c := path[i]
+ if needsEscape(i, c) {
+ e := fmt.Sprintf("_%x", c)
+ n = append(n, []byte(e)...)
+ } else {
+ n = append(n, c)
+ }
+ }
+ return string(n)
+}
+
+// Conn is a connection to systemd's dbus endpoint.
+type Conn struct {
+ // sysconn/sysobj are only used to call dbus methods
+ sysconn *dbus.Conn
+ sysobj dbus.BusObject
+
+ // sigconn/sigobj are only used to receive dbus signals
+ sigconn *dbus.Conn
+ sigobj dbus.BusObject
+
+ jobListener struct {
+ jobs map[dbus.ObjectPath]chan<- string
+ sync.Mutex
+ }
+ subscriber struct {
+ updateCh chan<- *SubStateUpdate
+ errCh chan<- error
+ sync.Mutex
+ ignore map[dbus.ObjectPath]int64
+ cleanIgnore int64
+ }
+}
+
+// New establishes a connection to any available bus and authenticates.
+// Callers should call Close() when done with the connection.
+func New() (*Conn, error) {
+ conn, err := NewSystemConnection()
+ if err != nil && os.Geteuid() == 0 {
+ return NewSystemdConnection()
+ }
+ return conn, err
+}
+
+// NewSystemConnection establishes a connection to the system bus and authenticates.
+// Callers should call Close() when done with the connection
+func NewSystemConnection() (*Conn, error) {
+ return NewConnection(func() (*dbus.Conn, error) {
+ return dbusAuthHelloConnection(dbus.SystemBusPrivate)
+ })
+}
+
+// NewUserConnection establishes a connection to the session bus and
+// authenticates. This can be used to connect to systemd user instances.
+// Callers should call Close() when done with the connection.
+func NewUserConnection() (*Conn, error) {
+ return NewConnection(func() (*dbus.Conn, error) {
+ return dbusAuthHelloConnection(dbus.SessionBusPrivate)
+ })
+}
+
+// NewSystemdConnection establishes a private, direct connection to systemd.
+// This can be used for communicating with systemd without a dbus daemon.
+// Callers should call Close() when done with the connection.
+func NewSystemdConnection() (*Conn, error) {
+ return NewConnection(func() (*dbus.Conn, error) {
+ // We skip Hello when talking directly to systemd.
+ return dbusAuthConnection(func() (*dbus.Conn, error) {
+ return dbus.Dial("unix:path=/run/systemd/private")
+ })
+ })
+}
+
+// Close closes an established connection
+func (c *Conn) Close() {
+ c.sysconn.Close()
+ c.sigconn.Close()
+}
+
+// NewConnection establishes a connection to a bus using a caller-supplied function.
+// This allows connecting to remote buses through a user-supplied mechanism.
+// The supplied function may be called multiple times, and should return independent connections.
+// The returned connection must be fully initialised: the org.freedesktop.DBus.Hello call must have succeeded,
+// and any authentication should be handled by the function.
+func NewConnection(dialBus func() (*dbus.Conn, error)) (*Conn, error) {
+ sysconn, err := dialBus()
+ if err != nil {
+ return nil, err
+ }
+
+ sigconn, err := dialBus()
+ if err != nil {
+ sysconn.Close()
+ return nil, err
+ }
+
+ c := &Conn{
+ sysconn: sysconn,
+ sysobj: systemdObject(sysconn),
+ sigconn: sigconn,
+ sigobj: systemdObject(sigconn),
+ }
+
+ c.subscriber.ignore = make(map[dbus.ObjectPath]int64)
+ c.jobListener.jobs = make(map[dbus.ObjectPath]chan<- string)
+
+ // Setup the listeners on jobs so that we can get completions
+ c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
+ "type='signal', interface='org.freedesktop.systemd1.Manager', member='JobRemoved'")
+
+ c.dispatch()
+ return c, nil
+}
+
+// GetManagerProperty returns the value of a property on the org.freedesktop.systemd1.Manager
+// interface. The value is returned in its string representation, as defined at
+// https://developer.gnome.org/glib/unstable/gvariant-text.html
+func (c *Conn) GetManagerProperty(prop string) (string, error) {
+ variant, err := c.sysobj.GetProperty("org.freedesktop.systemd1.Manager." + prop)
+ if err != nil {
+ return "", err
+ }
+ return variant.String(), nil
+}
+
+func dbusAuthConnection(createBus func() (*dbus.Conn, error)) (*dbus.Conn, error) {
+ conn, err := createBus()
+ if err != nil {
+ return nil, err
+ }
+
+ // Only use EXTERNAL method, and hardcode the uid (not username)
+ // to avoid a username lookup (which requires a dynamically linked
+ // libc)
+ methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}
+
+ err = conn.Auth(methods)
+ if err != nil {
+ conn.Close()
+ return nil, err
+ }
+
+ return conn, nil
+}
+
+func dbusAuthHelloConnection(createBus func() (*dbus.Conn, error)) (*dbus.Conn, error) {
+ conn, err := dbusAuthConnection(createBus)
+ if err != nil {
+ return nil, err
+ }
+
+ if err = conn.Hello(); err != nil {
+ conn.Close()
+ return nil, err
+ }
+
+ return conn, nil
+}
+
+func systemdObject(conn *dbus.Conn) dbus.BusObject {
+ return conn.Object("org.freedesktop.systemd1", dbus.ObjectPath("/org/freedesktop/systemd1"))
+}
diff --git a/vendor/github.com/coreos/go-systemd/dbus/methods.go b/vendor/github.com/coreos/go-systemd/dbus/methods.go
new file mode 100644
index 0000000..ab17f7c
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/dbus/methods.go
@@ -0,0 +1,565 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 dbus
+
+import (
+ "errors"
+ "path"
+ "strconv"
+
+ "github.com/godbus/dbus"
+)
+
+func (c *Conn) jobComplete(signal *dbus.Signal) {
+ var id uint32
+ var job dbus.ObjectPath
+ var unit string
+ var result string
+ dbus.Store(signal.Body, &id, &job, &unit, &result)
+ c.jobListener.Lock()
+ out, ok := c.jobListener.jobs[job]
+ if ok {
+ out <- result
+ delete(c.jobListener.jobs, job)
+ }
+ c.jobListener.Unlock()
+}
+
+func (c *Conn) startJob(ch chan<- string, job string, args ...interface{}) (int, error) {
+ if ch != nil {
+ c.jobListener.Lock()
+ defer c.jobListener.Unlock()
+ }
+
+ var p dbus.ObjectPath
+ err := c.sysobj.Call(job, 0, args...).Store(&p)
+ if err != nil {
+ return 0, err
+ }
+
+ if ch != nil {
+ c.jobListener.jobs[p] = ch
+ }
+
+ // ignore error since 0 is fine if conversion fails
+ jobID, _ := strconv.Atoi(path.Base(string(p)))
+
+ return jobID, nil
+}
+
+// StartUnit enqueues a start job and depending jobs, if any (unless otherwise
+// specified by the mode string).
+//
+// Takes the unit to activate, plus a mode string. The mode needs to be one of
+// replace, fail, isolate, ignore-dependencies, ignore-requirements. If
+// "replace" the call will start the unit and its dependencies, possibly
+// replacing already queued jobs that conflict with this. If "fail" the call
+// will start the unit and its dependencies, but will fail if this would change
+// an already queued job. If "isolate" the call will start the unit in question
+// and terminate all units that aren't dependencies of it. If
+// "ignore-dependencies" it will start a unit but ignore all its dependencies.
+// If "ignore-requirements" it will start a unit but only ignore the
+// requirement dependencies. It is not recommended to make use of the latter
+// two options.
+//
+// If the provided channel is non-nil, a result string will be sent to it upon
+// job completion: one of done, canceled, timeout, failed, dependency, skipped.
+// done indicates successful execution of a job. canceled indicates that a job
+// has been canceled before it finished execution. timeout indicates that the
+// job timeout was reached. failed indicates that the job failed. dependency
+// indicates that a job this job has been depending on failed and the job hence
+// has been removed too. skipped indicates that a job was skipped because it
+// didn't apply to the units current state.
+//
+// If no error occurs, the ID of the underlying systemd job will be returned. There
+// does exist the possibility for no error to be returned, but for the returned job
+// ID to be 0. In this case, the actual underlying ID is not 0 and this datapoint
+// should not be considered authoritative.
+//
+// If an error does occur, it will be returned to the user alongside a job ID of 0.
+func (c *Conn) StartUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ch, "org.freedesktop.systemd1.Manager.StartUnit", name, mode)
+}
+
+// StopUnit is similar to StartUnit but stops the specified unit rather
+// than starting it.
+func (c *Conn) StopUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ch, "org.freedesktop.systemd1.Manager.StopUnit", name, mode)
+}
+
+// ReloadUnit reloads a unit. Reloading is done only if the unit is already running and fails otherwise.
+func (c *Conn) ReloadUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadUnit", name, mode)
+}
+
+// RestartUnit restarts a service. If a service is restarted that isn't
+// running it will be started.
+func (c *Conn) RestartUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ch, "org.freedesktop.systemd1.Manager.RestartUnit", name, mode)
+}
+
+// TryRestartUnit is like RestartUnit, except that a service that isn't running
+// is not affected by the restart.
+func (c *Conn) TryRestartUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ch, "org.freedesktop.systemd1.Manager.TryRestartUnit", name, mode)
+}
+
+// ReloadOrRestart attempts a reload if the unit supports it and use a restart
+// otherwise.
+func (c *Conn) ReloadOrRestartUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadOrRestartUnit", name, mode)
+}
+
+// ReloadOrTryRestart attempts a reload if the unit supports it and use a "Try"
+// flavored restart otherwise.
+func (c *Conn) ReloadOrTryRestartUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadOrTryRestartUnit", name, mode)
+}
+
+// StartTransientUnit() may be used to create and start a transient unit, which
+// will be released as soon as it is not running or referenced anymore or the
+// system is rebooted. name is the unit name including suffix, and must be
+// unique. mode is the same as in StartUnit(), properties contains properties
+// of the unit.
+func (c *Conn) StartTransientUnit(name string, mode string, properties []Property, ch chan<- string) (int, error) {
+ return c.startJob(ch, "org.freedesktop.systemd1.Manager.StartTransientUnit", name, mode, properties, make([]PropertyCollection, 0))
+}
+
+// KillUnit takes the unit name and a UNIX signal number to send. All of the unit's
+// processes are killed.
+func (c *Conn) KillUnit(name string, signal int32) {
+ c.sysobj.Call("org.freedesktop.systemd1.Manager.KillUnit", 0, name, "all", signal).Store()
+}
+
+// ResetFailedUnit resets the "failed" state of a specific unit.
+func (c *Conn) ResetFailedUnit(name string) error {
+ return c.sysobj.Call("org.freedesktop.systemd1.Manager.ResetFailedUnit", 0, name).Store()
+}
+
+// getProperties takes the unit name and returns all of its dbus object properties, for the given dbus interface
+func (c *Conn) getProperties(unit string, dbusInterface string) (map[string]interface{}, error) {
+ var err error
+ var props map[string]dbus.Variant
+
+ path := unitPath(unit)
+ if !path.IsValid() {
+ return nil, errors.New("invalid unit name: " + unit)
+ }
+
+ obj := c.sysconn.Object("org.freedesktop.systemd1", path)
+ err = obj.Call("org.freedesktop.DBus.Properties.GetAll", 0, dbusInterface).Store(&props)
+ if err != nil {
+ return nil, err
+ }
+
+ out := make(map[string]interface{}, len(props))
+ for k, v := range props {
+ out[k] = v.Value()
+ }
+
+ return out, nil
+}
+
+// GetUnitProperties takes the unit name and returns all of its dbus object properties.
+func (c *Conn) GetUnitProperties(unit string) (map[string]interface{}, error) {
+ return c.getProperties(unit, "org.freedesktop.systemd1.Unit")
+}
+
+func (c *Conn) getProperty(unit string, dbusInterface string, propertyName string) (*Property, error) {
+ var err error
+ var prop dbus.Variant
+
+ path := unitPath(unit)
+ if !path.IsValid() {
+ return nil, errors.New("invalid unit name: " + unit)
+ }
+
+ obj := c.sysconn.Object("org.freedesktop.systemd1", path)
+ err = obj.Call("org.freedesktop.DBus.Properties.Get", 0, dbusInterface, propertyName).Store(&prop)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Property{Name: propertyName, Value: prop}, nil
+}
+
+func (c *Conn) GetUnitProperty(unit string, propertyName string) (*Property, error) {
+ return c.getProperty(unit, "org.freedesktop.systemd1.Unit", propertyName)
+}
+
+// GetServiceProperty returns property for given service name and property name
+func (c *Conn) GetServiceProperty(service string, propertyName string) (*Property, error) {
+ return c.getProperty(service, "org.freedesktop.systemd1.Service", propertyName)
+}
+
+// GetUnitTypeProperties returns the extra properties for a unit, specific to the unit type.
+// Valid values for unitType: Service, Socket, Target, Device, Mount, Automount, Snapshot, Timer, Swap, Path, Slice, Scope
+// return "dbus.Error: Unknown interface" if the unitType is not the correct type of the unit
+func (c *Conn) GetUnitTypeProperties(unit string, unitType string) (map[string]interface{}, error) {
+ return c.getProperties(unit, "org.freedesktop.systemd1."+unitType)
+}
+
+// SetUnitProperties() may be used to modify certain unit properties at runtime.
+// Not all properties may be changed at runtime, but many resource management
+// settings (primarily those in systemd.cgroup(5)) may. The changes are applied
+// instantly, and stored on disk for future boots, unless runtime is true, in which
+// case the settings only apply until the next reboot. name is the name of the unit
+// to modify. properties are the settings to set, encoded as an array of property
+// name and value pairs.
+func (c *Conn) SetUnitProperties(name string, runtime bool, properties ...Property) error {
+ return c.sysobj.Call("org.freedesktop.systemd1.Manager.SetUnitProperties", 0, name, runtime, properties).Store()
+}
+
+func (c *Conn) GetUnitTypeProperty(unit string, unitType string, propertyName string) (*Property, error) {
+ return c.getProperty(unit, "org.freedesktop.systemd1."+unitType, propertyName)
+}
+
+type UnitStatus struct {
+ Name string // The primary unit name as string
+ Description string // The human readable description string
+ LoadState string // The load state (i.e. whether the unit file has been loaded successfully)
+ ActiveState string // The active state (i.e. whether the unit is currently started or not)
+ SubState string // The sub state (a more fine-grained version of the active state that is specific to the unit type, which the active state is not)
+ Followed string // A unit that is being followed in its state by this unit, if there is any, otherwise the empty string.
+ Path dbus.ObjectPath // The unit object path
+ JobId uint32 // If there is a job queued for the job unit the numeric job id, 0 otherwise
+ JobType string // The job type as string
+ JobPath dbus.ObjectPath // The job object path
+}
+
+type storeFunc func(retvalues ...interface{}) error
+
+func (c *Conn) listUnitsInternal(f storeFunc) ([]UnitStatus, error) {
+ result := make([][]interface{}, 0)
+ err := f(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ status := make([]UnitStatus, len(result))
+ statusInterface := make([]interface{}, len(status))
+ for i := range status {
+ statusInterface[i] = &status[i]
+ }
+
+ err = dbus.Store(resultInterface, statusInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return status, nil
+}
+
+// ListUnits returns an array with all currently loaded units. Note that
+// units may be known by multiple names at the same time, and hence there might
+// be more unit names loaded than actual units behind them.
+func (c *Conn) ListUnits() ([]UnitStatus, error) {
+ return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnits", 0).Store)
+}
+
+// ListUnitsFiltered returns an array with units filtered by state.
+// It takes a list of units' statuses to filter.
+func (c *Conn) ListUnitsFiltered(states []string) ([]UnitStatus, error) {
+ return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitsFiltered", 0, states).Store)
+}
+
+// ListUnitsByPatterns returns an array with units.
+// It takes a list of units' statuses and names to filter.
+// Note that units may be known by multiple names at the same time,
+// and hence there might be more unit names loaded than actual units behind them.
+func (c *Conn) ListUnitsByPatterns(states []string, patterns []string) ([]UnitStatus, error) {
+ return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitsByPatterns", 0, states, patterns).Store)
+}
+
+// ListUnitsByNames returns an array with units. It takes a list of units'
+// names and returns an UnitStatus array. Comparing to ListUnitsByPatterns
+// method, this method returns statuses even for inactive or non-existing
+// units. Input array should contain exact unit names, but not patterns.
+func (c *Conn) ListUnitsByNames(units []string) ([]UnitStatus, error) {
+ return c.listUnitsInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitsByNames", 0, units).Store)
+}
+
+type UnitFile struct {
+ Path string
+ Type string
+}
+
+func (c *Conn) listUnitFilesInternal(f storeFunc) ([]UnitFile, error) {
+ result := make([][]interface{}, 0)
+ err := f(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ files := make([]UnitFile, len(result))
+ fileInterface := make([]interface{}, len(files))
+ for i := range files {
+ fileInterface[i] = &files[i]
+ }
+
+ err = dbus.Store(resultInterface, fileInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return files, nil
+}
+
+// ListUnitFiles returns an array of all available units on disk.
+func (c *Conn) ListUnitFiles() ([]UnitFile, error) {
+ return c.listUnitFilesInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitFiles", 0).Store)
+}
+
+// ListUnitFilesByPatterns returns an array of all available units on disk matched the patterns.
+func (c *Conn) ListUnitFilesByPatterns(states []string, patterns []string) ([]UnitFile, error) {
+ return c.listUnitFilesInternal(c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnitFilesByPatterns", 0, states, patterns).Store)
+}
+
+type LinkUnitFileChange EnableUnitFileChange
+
+// LinkUnitFiles() links unit files (that are located outside of the
+// usual unit search paths) into the unit search path.
+//
+// It takes a list of absolute paths to unit files to link and two
+// booleans. The first boolean controls whether the unit shall be
+// enabled for runtime only (true, /run), or persistently (false,
+// /etc).
+// The second controls whether symlinks pointing to other units shall
+// be replaced if necessary.
+//
+// This call returns a list of the changes made. The list consists of
+// structures with three strings: the type of the change (one of symlink
+// or unlink), the file name of the symlink and the destination of the
+// symlink.
+func (c *Conn) LinkUnitFiles(files []string, runtime bool, force bool) ([]LinkUnitFileChange, error) {
+ result := make([][]interface{}, 0)
+ err := c.sysobj.Call("org.freedesktop.systemd1.Manager.LinkUnitFiles", 0, files, runtime, force).Store(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ changes := make([]LinkUnitFileChange, len(result))
+ changesInterface := make([]interface{}, len(changes))
+ for i := range changes {
+ changesInterface[i] = &changes[i]
+ }
+
+ err = dbus.Store(resultInterface, changesInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return changes, nil
+}
+
+// EnableUnitFiles() may be used to enable one or more units in the system (by
+// creating symlinks to them in /etc or /run).
+//
+// It takes a list of unit files to enable (either just file names or full
+// absolute paths if the unit files are residing outside the usual unit
+// search paths), and two booleans: the first controls whether the unit shall
+// be enabled for runtime only (true, /run), or persistently (false, /etc).
+// The second one controls whether symlinks pointing to other units shall
+// be replaced if necessary.
+//
+// This call returns one boolean and an array with the changes made. The
+// boolean signals whether the unit files contained any enablement
+// information (i.e. an [Install]) section. The changes list consists of
+// structures with three strings: the type of the change (one of symlink
+// or unlink), the file name of the symlink and the destination of the
+// symlink.
+func (c *Conn) EnableUnitFiles(files []string, runtime bool, force bool) (bool, []EnableUnitFileChange, error) {
+ var carries_install_info bool
+
+ result := make([][]interface{}, 0)
+ err := c.sysobj.Call("org.freedesktop.systemd1.Manager.EnableUnitFiles", 0, files, runtime, force).Store(&carries_install_info, &result)
+ if err != nil {
+ return false, nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ changes := make([]EnableUnitFileChange, len(result))
+ changesInterface := make([]interface{}, len(changes))
+ for i := range changes {
+ changesInterface[i] = &changes[i]
+ }
+
+ err = dbus.Store(resultInterface, changesInterface...)
+ if err != nil {
+ return false, nil, err
+ }
+
+ return carries_install_info, changes, nil
+}
+
+type EnableUnitFileChange struct {
+ Type string // Type of the change (one of symlink or unlink)
+ Filename string // File name of the symlink
+ Destination string // Destination of the symlink
+}
+
+// DisableUnitFiles() may be used to disable one or more units in the system (by
+// removing symlinks to them from /etc or /run).
+//
+// It takes a list of unit files to disable (either just file names or full
+// absolute paths if the unit files are residing outside the usual unit
+// search paths), and one boolean: whether the unit was enabled for runtime
+// only (true, /run), or persistently (false, /etc).
+//
+// This call returns an array with the changes made. The changes list
+// consists of structures with three strings: the type of the change (one of
+// symlink or unlink), the file name of the symlink and the destination of the
+// symlink.
+func (c *Conn) DisableUnitFiles(files []string, runtime bool) ([]DisableUnitFileChange, error) {
+ result := make([][]interface{}, 0)
+ err := c.sysobj.Call("org.freedesktop.systemd1.Manager.DisableUnitFiles", 0, files, runtime).Store(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ changes := make([]DisableUnitFileChange, len(result))
+ changesInterface := make([]interface{}, len(changes))
+ for i := range changes {
+ changesInterface[i] = &changes[i]
+ }
+
+ err = dbus.Store(resultInterface, changesInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return changes, nil
+}
+
+type DisableUnitFileChange struct {
+ Type string // Type of the change (one of symlink or unlink)
+ Filename string // File name of the symlink
+ Destination string // Destination of the symlink
+}
+
+// MaskUnitFiles masks one or more units in the system
+//
+// It takes three arguments:
+// * list of units to mask (either just file names or full
+// absolute paths if the unit files are residing outside
+// the usual unit search paths)
+// * runtime to specify whether the unit was enabled for runtime
+// only (true, /run/systemd/..), or persistently (false, /etc/systemd/..)
+// * force flag
+func (c *Conn) MaskUnitFiles(files []string, runtime bool, force bool) ([]MaskUnitFileChange, error) {
+ result := make([][]interface{}, 0)
+ err := c.sysobj.Call("org.freedesktop.systemd1.Manager.MaskUnitFiles", 0, files, runtime, force).Store(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ changes := make([]MaskUnitFileChange, len(result))
+ changesInterface := make([]interface{}, len(changes))
+ for i := range changes {
+ changesInterface[i] = &changes[i]
+ }
+
+ err = dbus.Store(resultInterface, changesInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return changes, nil
+}
+
+type MaskUnitFileChange struct {
+ Type string // Type of the change (one of symlink or unlink)
+ Filename string // File name of the symlink
+ Destination string // Destination of the symlink
+}
+
+// UnmaskUnitFiles unmasks one or more units in the system
+//
+// It takes two arguments:
+// * list of unit files to mask (either just file names or full
+// absolute paths if the unit files are residing outside
+// the usual unit search paths)
+// * runtime to specify whether the unit was enabled for runtime
+// only (true, /run/systemd/..), or persistently (false, /etc/systemd/..)
+func (c *Conn) UnmaskUnitFiles(files []string, runtime bool) ([]UnmaskUnitFileChange, error) {
+ result := make([][]interface{}, 0)
+ err := c.sysobj.Call("org.freedesktop.systemd1.Manager.UnmaskUnitFiles", 0, files, runtime).Store(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ changes := make([]UnmaskUnitFileChange, len(result))
+ changesInterface := make([]interface{}, len(changes))
+ for i := range changes {
+ changesInterface[i] = &changes[i]
+ }
+
+ err = dbus.Store(resultInterface, changesInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return changes, nil
+}
+
+type UnmaskUnitFileChange struct {
+ Type string // Type of the change (one of symlink or unlink)
+ Filename string // File name of the symlink
+ Destination string // Destination of the symlink
+}
+
+// Reload instructs systemd to scan for and reload unit files. This is
+// equivalent to a 'systemctl daemon-reload'.
+func (c *Conn) Reload() error {
+ return c.sysobj.Call("org.freedesktop.systemd1.Manager.Reload", 0).Store()
+}
+
+func unitPath(name string) dbus.ObjectPath {
+ return dbus.ObjectPath("/org/freedesktop/systemd1/unit/" + PathBusEscape(name))
+}
diff --git a/vendor/github.com/coreos/go-systemd/dbus/properties.go b/vendor/github.com/coreos/go-systemd/dbus/properties.go
new file mode 100644
index 0000000..6c81895
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/dbus/properties.go
@@ -0,0 +1,237 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 dbus
+
+import (
+ "github.com/godbus/dbus"
+)
+
+// From the systemd docs:
+//
+// The properties array of StartTransientUnit() may take many of the settings
+// that may also be configured in unit files. Not all parameters are currently
+// accepted though, but we plan to cover more properties with future release.
+// Currently you may set the Description, Slice and all dependency types of
+// units, as well as RemainAfterExit, ExecStart for service units,
+// TimeoutStopUSec and PIDs for scope units, and CPUAccounting, CPUShares,
+// BlockIOAccounting, BlockIOWeight, BlockIOReadBandwidth,
+// BlockIOWriteBandwidth, BlockIODeviceWeight, MemoryAccounting, MemoryLimit,
+// DevicePolicy, DeviceAllow for services/scopes/slices. These fields map
+// directly to their counterparts in unit files and as normal D-Bus object
+// properties. The exception here is the PIDs field of scope units which is
+// used for construction of the scope only and specifies the initial PIDs to
+// add to the scope object.
+
+type Property struct {
+ Name string
+ Value dbus.Variant
+}
+
+type PropertyCollection struct {
+ Name string
+ Properties []Property
+}
+
+type execStart struct {
+ Path string // the binary path to execute
+ Args []string // an array with all arguments to pass to the executed command, starting with argument 0
+ UncleanIsFailure bool // a boolean whether it should be considered a failure if the process exits uncleanly
+}
+
+// PropExecStart sets the ExecStart service property. The first argument is a
+// slice with the binary path to execute followed by the arguments to pass to
+// the executed command. See
+// http://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecStart=
+func PropExecStart(command []string, uncleanIsFailure bool) Property {
+ execStarts := []execStart{
+ execStart{
+ Path: command[0],
+ Args: command,
+ UncleanIsFailure: uncleanIsFailure,
+ },
+ }
+
+ return Property{
+ Name: "ExecStart",
+ Value: dbus.MakeVariant(execStarts),
+ }
+}
+
+// PropRemainAfterExit sets the RemainAfterExit service property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.service.html#RemainAfterExit=
+func PropRemainAfterExit(b bool) Property {
+ return Property{
+ Name: "RemainAfterExit",
+ Value: dbus.MakeVariant(b),
+ }
+}
+
+// PropType sets the Type service property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.service.html#Type=
+func PropType(t string) Property {
+ return Property{
+ Name: "Type",
+ Value: dbus.MakeVariant(t),
+ }
+}
+
+// PropDescription sets the Description unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit#Description=
+func PropDescription(desc string) Property {
+ return Property{
+ Name: "Description",
+ Value: dbus.MakeVariant(desc),
+ }
+}
+
+func propDependency(name string, units []string) Property {
+ return Property{
+ Name: name,
+ Value: dbus.MakeVariant(units),
+ }
+}
+
+// PropRequires sets the Requires unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Requires=
+func PropRequires(units ...string) Property {
+ return propDependency("Requires", units)
+}
+
+// PropRequiresOverridable sets the RequiresOverridable unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiresOverridable=
+func PropRequiresOverridable(units ...string) Property {
+ return propDependency("RequiresOverridable", units)
+}
+
+// PropRequisite sets the Requisite unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Requisite=
+func PropRequisite(units ...string) Property {
+ return propDependency("Requisite", units)
+}
+
+// PropRequisiteOverridable sets the RequisiteOverridable unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequisiteOverridable=
+func PropRequisiteOverridable(units ...string) Property {
+ return propDependency("RequisiteOverridable", units)
+}
+
+// PropWants sets the Wants unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Wants=
+func PropWants(units ...string) Property {
+ return propDependency("Wants", units)
+}
+
+// PropBindsTo sets the BindsTo unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#BindsTo=
+func PropBindsTo(units ...string) Property {
+ return propDependency("BindsTo", units)
+}
+
+// PropRequiredBy sets the RequiredBy unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiredBy=
+func PropRequiredBy(units ...string) Property {
+ return propDependency("RequiredBy", units)
+}
+
+// PropRequiredByOverridable sets the RequiredByOverridable unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiredByOverridable=
+func PropRequiredByOverridable(units ...string) Property {
+ return propDependency("RequiredByOverridable", units)
+}
+
+// PropWantedBy sets the WantedBy unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#WantedBy=
+func PropWantedBy(units ...string) Property {
+ return propDependency("WantedBy", units)
+}
+
+// PropBoundBy sets the BoundBy unit property. See
+// http://www.freedesktop.org/software/systemd/main/systemd.unit.html#BoundBy=
+func PropBoundBy(units ...string) Property {
+ return propDependency("BoundBy", units)
+}
+
+// PropConflicts sets the Conflicts unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Conflicts=
+func PropConflicts(units ...string) Property {
+ return propDependency("Conflicts", units)
+}
+
+// PropConflictedBy sets the ConflictedBy unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#ConflictedBy=
+func PropConflictedBy(units ...string) Property {
+ return propDependency("ConflictedBy", units)
+}
+
+// PropBefore sets the Before unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Before=
+func PropBefore(units ...string) Property {
+ return propDependency("Before", units)
+}
+
+// PropAfter sets the After unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#After=
+func PropAfter(units ...string) Property {
+ return propDependency("After", units)
+}
+
+// PropOnFailure sets the OnFailure unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#OnFailure=
+func PropOnFailure(units ...string) Property {
+ return propDependency("OnFailure", units)
+}
+
+// PropTriggers sets the Triggers unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Triggers=
+func PropTriggers(units ...string) Property {
+ return propDependency("Triggers", units)
+}
+
+// PropTriggeredBy sets the TriggeredBy unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#TriggeredBy=
+func PropTriggeredBy(units ...string) Property {
+ return propDependency("TriggeredBy", units)
+}
+
+// PropPropagatesReloadTo sets the PropagatesReloadTo unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#PropagatesReloadTo=
+func PropPropagatesReloadTo(units ...string) Property {
+ return propDependency("PropagatesReloadTo", units)
+}
+
+// PropRequiresMountsFor sets the RequiresMountsFor unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiresMountsFor=
+func PropRequiresMountsFor(units ...string) Property {
+ return propDependency("RequiresMountsFor", units)
+}
+
+// PropSlice sets the Slice unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.resource-control.html#Slice=
+func PropSlice(slice string) Property {
+ return Property{
+ Name: "Slice",
+ Value: dbus.MakeVariant(slice),
+ }
+}
+
+// PropPids sets the PIDs field of scope units used in the initial construction
+// of the scope only and specifies the initial PIDs to add to the scope object.
+// See https://www.freedesktop.org/wiki/Software/systemd/ControlGroupInterface/#properties
+func PropPids(pids ...uint32) Property {
+ return Property{
+ Name: "PIDs",
+ Value: dbus.MakeVariant(pids),
+ }
+}
diff --git a/vendor/github.com/coreos/go-systemd/dbus/set.go b/vendor/github.com/coreos/go-systemd/dbus/set.go
new file mode 100644
index 0000000..f92e6fb
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/dbus/set.go
@@ -0,0 +1,47 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 dbus
+
+type set struct {
+ data map[string]bool
+}
+
+func (s *set) Add(value string) {
+ s.data[value] = true
+}
+
+func (s *set) Remove(value string) {
+ delete(s.data, value)
+}
+
+func (s *set) Contains(value string) (exists bool) {
+ _, exists = s.data[value]
+ return
+}
+
+func (s *set) Length() int {
+ return len(s.data)
+}
+
+func (s *set) Values() (values []string) {
+ for val, _ := range s.data {
+ values = append(values, val)
+ }
+ return
+}
+
+func newSet() *set {
+ return &set{make(map[string]bool)}
+}
diff --git a/vendor/github.com/coreos/go-systemd/dbus/subscription.go b/vendor/github.com/coreos/go-systemd/dbus/subscription.go
new file mode 100644
index 0000000..9964514
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/dbus/subscription.go
@@ -0,0 +1,250 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 dbus
+
+import (
+ "errors"
+ "time"
+
+ "github.com/godbus/dbus"
+)
+
+const (
+ cleanIgnoreInterval = int64(10 * time.Second)
+ ignoreInterval = int64(30 * time.Millisecond)
+)
+
+// Subscribe sets up this connection to subscribe to all systemd dbus events.
+// This is required before calling SubscribeUnits. When the connection closes
+// systemd will automatically stop sending signals so there is no need to
+// explicitly call Unsubscribe().
+func (c *Conn) Subscribe() error {
+ c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
+ "type='signal',interface='org.freedesktop.systemd1.Manager',member='UnitNew'")
+ c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
+ "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'")
+
+ err := c.sigobj.Call("org.freedesktop.systemd1.Manager.Subscribe", 0).Store()
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Unsubscribe this connection from systemd dbus events.
+func (c *Conn) Unsubscribe() error {
+ err := c.sigobj.Call("org.freedesktop.systemd1.Manager.Unsubscribe", 0).Store()
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (c *Conn) dispatch() {
+ ch := make(chan *dbus.Signal, signalBuffer)
+
+ c.sigconn.Signal(ch)
+
+ go func() {
+ for {
+ signal, ok := <-ch
+ if !ok {
+ return
+ }
+
+ if signal.Name == "org.freedesktop.systemd1.Manager.JobRemoved" {
+ c.jobComplete(signal)
+ }
+
+ if c.subscriber.updateCh == nil {
+ continue
+ }
+
+ var unitPath dbus.ObjectPath
+ switch signal.Name {
+ case "org.freedesktop.systemd1.Manager.JobRemoved":
+ unitName := signal.Body[2].(string)
+ c.sysobj.Call("org.freedesktop.systemd1.Manager.GetUnit", 0, unitName).Store(&unitPath)
+ case "org.freedesktop.systemd1.Manager.UnitNew":
+ unitPath = signal.Body[1].(dbus.ObjectPath)
+ case "org.freedesktop.DBus.Properties.PropertiesChanged":
+ if signal.Body[0].(string) == "org.freedesktop.systemd1.Unit" {
+ unitPath = signal.Path
+ }
+ }
+
+ if unitPath == dbus.ObjectPath("") {
+ continue
+ }
+
+ c.sendSubStateUpdate(unitPath)
+ }
+ }()
+}
+
+// Returns two unbuffered channels which will receive all changed units every
+// interval. Deleted units are sent as nil.
+func (c *Conn) SubscribeUnits(interval time.Duration) (<-chan map[string]*UnitStatus, <-chan error) {
+ return c.SubscribeUnitsCustom(interval, 0, func(u1, u2 *UnitStatus) bool { return *u1 != *u2 }, nil)
+}
+
+// SubscribeUnitsCustom is like SubscribeUnits but lets you specify the buffer
+// size of the channels, the comparison function for detecting changes and a filter
+// function for cutting down on the noise that your channel receives.
+func (c *Conn) SubscribeUnitsCustom(interval time.Duration, buffer int, isChanged func(*UnitStatus, *UnitStatus) bool, filterUnit func(string) bool) (<-chan map[string]*UnitStatus, <-chan error) {
+ old := make(map[string]*UnitStatus)
+ statusChan := make(chan map[string]*UnitStatus, buffer)
+ errChan := make(chan error, buffer)
+
+ go func() {
+ for {
+ timerChan := time.After(interval)
+
+ units, err := c.ListUnits()
+ if err == nil {
+ cur := make(map[string]*UnitStatus)
+ for i := range units {
+ if filterUnit != nil && filterUnit(units[i].Name) {
+ continue
+ }
+ cur[units[i].Name] = &units[i]
+ }
+
+ // add all new or changed units
+ changed := make(map[string]*UnitStatus)
+ for n, u := range cur {
+ if oldU, ok := old[n]; !ok || isChanged(oldU, u) {
+ changed[n] = u
+ }
+ delete(old, n)
+ }
+
+ // add all deleted units
+ for oldN := range old {
+ changed[oldN] = nil
+ }
+
+ old = cur
+
+ if len(changed) != 0 {
+ statusChan <- changed
+ }
+ } else {
+ errChan <- err
+ }
+
+ <-timerChan
+ }
+ }()
+
+ return statusChan, errChan
+}
+
+type SubStateUpdate struct {
+ UnitName string
+ SubState string
+}
+
+// SetSubStateSubscriber writes to updateCh when any unit's substate changes.
+// Although this writes to updateCh on every state change, the reported state
+// may be more recent than the change that generated it (due to an unavoidable
+// race in the systemd dbus interface). That is, this method provides a good
+// way to keep a current view of all units' states, but is not guaranteed to
+// show every state transition they go through. Furthermore, state changes
+// will only be written to the channel with non-blocking writes. If updateCh
+// is full, it attempts to write an error to errCh; if errCh is full, the error
+// passes silently.
+func (c *Conn) SetSubStateSubscriber(updateCh chan<- *SubStateUpdate, errCh chan<- error) {
+ c.subscriber.Lock()
+ defer c.subscriber.Unlock()
+ c.subscriber.updateCh = updateCh
+ c.subscriber.errCh = errCh
+}
+
+func (c *Conn) sendSubStateUpdate(path dbus.ObjectPath) {
+ c.subscriber.Lock()
+ defer c.subscriber.Unlock()
+
+ if c.shouldIgnore(path) {
+ return
+ }
+
+ info, err := c.GetUnitProperties(string(path))
+ if err != nil {
+ select {
+ case c.subscriber.errCh <- err:
+ default:
+ }
+ }
+
+ name := info["Id"].(string)
+ substate := info["SubState"].(string)
+
+ update := &SubStateUpdate{name, substate}
+ select {
+ case c.subscriber.updateCh <- update:
+ default:
+ select {
+ case c.subscriber.errCh <- errors.New("update channel full!"):
+ default:
+ }
+ }
+
+ c.updateIgnore(path, info)
+}
+
+// The ignore functions work around a wart in the systemd dbus interface.
+// Requesting the properties of an unloaded unit will cause systemd to send a
+// pair of UnitNew/UnitRemoved signals. Because we need to get a unit's
+// properties on UnitNew (as that's the only indication of a new unit coming up
+// for the first time), we would enter an infinite loop if we did not attempt
+// to detect and ignore these spurious signals. The signal themselves are
+// indistinguishable from relevant ones, so we (somewhat hackishly) ignore an
+// unloaded unit's signals for a short time after requesting its properties.
+// This means that we will miss e.g. a transient unit being restarted
+// *immediately* upon failure and also a transient unit being started
+// immediately after requesting its status (with systemctl status, for example,
+// because this causes a UnitNew signal to be sent which then causes us to fetch
+// the properties).
+
+func (c *Conn) shouldIgnore(path dbus.ObjectPath) bool {
+ t, ok := c.subscriber.ignore[path]
+ return ok && t >= time.Now().UnixNano()
+}
+
+func (c *Conn) updateIgnore(path dbus.ObjectPath, info map[string]interface{}) {
+ c.cleanIgnore()
+
+ // unit is unloaded - it will trigger bad systemd dbus behavior
+ if info["LoadState"].(string) == "not-found" {
+ c.subscriber.ignore[path] = time.Now().UnixNano() + ignoreInterval
+ }
+}
+
+// without this, ignore would grow unboundedly over time
+func (c *Conn) cleanIgnore() {
+ now := time.Now().UnixNano()
+ if c.subscriber.cleanIgnore < now {
+ c.subscriber.cleanIgnore = now + cleanIgnoreInterval
+
+ for p, t := range c.subscriber.ignore {
+ if t < now {
+ delete(c.subscriber.ignore, p)
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/coreos/go-systemd/dbus/subscription_set.go b/vendor/github.com/coreos/go-systemd/dbus/subscription_set.go
new file mode 100644
index 0000000..5b408d5
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/dbus/subscription_set.go
@@ -0,0 +1,57 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 dbus
+
+import (
+ "time"
+)
+
+// SubscriptionSet returns a subscription set which is like conn.Subscribe but
+// can filter to only return events for a set of units.
+type SubscriptionSet struct {
+ *set
+ conn *Conn
+}
+
+func (s *SubscriptionSet) filter(unit string) bool {
+ return !s.Contains(unit)
+}
+
+// Subscribe starts listening for dbus events for all of the units in the set.
+// Returns channels identical to conn.SubscribeUnits.
+func (s *SubscriptionSet) Subscribe() (<-chan map[string]*UnitStatus, <-chan error) {
+ // TODO: Make fully evented by using systemd 209 with properties changed values
+ return s.conn.SubscribeUnitsCustom(time.Second, 0,
+ mismatchUnitStatus,
+ func(unit string) bool { return s.filter(unit) },
+ )
+}
+
+// NewSubscriptionSet returns a new subscription set.
+func (conn *Conn) NewSubscriptionSet() *SubscriptionSet {
+ return &SubscriptionSet{newSet(), conn}
+}
+
+// mismatchUnitStatus returns true if the provided UnitStatus objects
+// are not equivalent. false is returned if the objects are equivalent.
+// Only the Name, Description and state-related fields are used in
+// the comparison.
+func mismatchUnitStatus(u1, u2 *UnitStatus) bool {
+ return u1.Name != u2.Name ||
+ u1.Description != u2.Description ||
+ u1.LoadState != u2.LoadState ||
+ u1.ActiveState != u2.ActiveState ||
+ u1.SubState != u2.SubState
+}
diff --git a/vendor/github.com/coreos/go-systemd/journal/journal.go b/vendor/github.com/coreos/go-systemd/journal/journal.go
new file mode 100644
index 0000000..7f43499
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/journal/journal.go
@@ -0,0 +1,179 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 journal provides write bindings to the local systemd journal.
+// It is implemented in pure Go and connects to the journal directly over its
+// unix socket.
+//
+// To read from the journal, see the "sdjournal" package, which wraps the
+// sd-journal a C API.
+//
+// http://www.freedesktop.org/software/systemd/man/systemd-journald.service.html
+package journal
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net"
+ "os"
+ "strconv"
+ "strings"
+ "syscall"
+)
+
+// Priority of a journal message
+type Priority int
+
+const (
+ PriEmerg Priority = iota
+ PriAlert
+ PriCrit
+ PriErr
+ PriWarning
+ PriNotice
+ PriInfo
+ PriDebug
+)
+
+var conn net.Conn
+
+func init() {
+ var err error
+ conn, err = net.Dial("unixgram", "/run/systemd/journal/socket")
+ if err != nil {
+ conn = nil
+ }
+}
+
+// Enabled returns true if the local systemd journal is available for logging
+func Enabled() bool {
+ return conn != nil
+}
+
+// Send a message to the local systemd journal. vars is a map of journald
+// fields to values. Fields must be composed of uppercase letters, numbers,
+// and underscores, but must not start with an underscore. Within these
+// restrictions, any arbitrary field name may be used. Some names have special
+// significance: see the journalctl documentation
+// (http://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
+// for more details. vars may be nil.
+func Send(message string, priority Priority, vars map[string]string) error {
+ if conn == nil {
+ return journalError("could not connect to journald socket")
+ }
+
+ data := new(bytes.Buffer)
+ appendVariable(data, "PRIORITY", strconv.Itoa(int(priority)))
+ appendVariable(data, "MESSAGE", message)
+ for k, v := range vars {
+ appendVariable(data, k, v)
+ }
+
+ _, err := io.Copy(conn, data)
+ if err != nil && isSocketSpaceError(err) {
+ file, err := tempFd()
+ if err != nil {
+ return journalError(err.Error())
+ }
+ defer file.Close()
+ _, err = io.Copy(file, data)
+ if err != nil {
+ return journalError(err.Error())
+ }
+
+ rights := syscall.UnixRights(int(file.Fd()))
+
+ /* this connection should always be a UnixConn, but better safe than sorry */
+ unixConn, ok := conn.(*net.UnixConn)
+ if !ok {
+ return journalError("can't send file through non-Unix connection")
+ }
+ unixConn.WriteMsgUnix([]byte{}, rights, nil)
+ } else if err != nil {
+ return journalError(err.Error())
+ }
+ return nil
+}
+
+// Print prints a message to the local systemd journal using Send().
+func Print(priority Priority, format string, a ...interface{}) error {
+ return Send(fmt.Sprintf(format, a...), priority, nil)
+}
+
+func appendVariable(w io.Writer, name, value string) {
+ if !validVarName(name) {
+ journalError("variable name contains invalid character, ignoring")
+ }
+ if strings.ContainsRune(value, '\n') {
+ /* When the value contains a newline, we write:
+ * - the variable name, followed by a newline
+ * - the size (in 64bit little endian format)
+ * - the data, followed by a newline
+ */
+ fmt.Fprintln(w, name)
+ binary.Write(w, binary.LittleEndian, uint64(len(value)))
+ fmt.Fprintln(w, value)
+ } else {
+ /* just write the variable and value all on one line */
+ fmt.Fprintf(w, "%s=%s\n", name, value)
+ }
+}
+
+func validVarName(name string) bool {
+ /* The variable name must be in uppercase and consist only of characters,
+ * numbers and underscores, and may not begin with an underscore. (from the docs)
+ */
+
+ valid := name[0] != '_'
+ for _, c := range name {
+ valid = valid && ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '_'
+ }
+ return valid
+}
+
+func isSocketSpaceError(err error) bool {
+ opErr, ok := err.(*net.OpError)
+ if !ok {
+ return false
+ }
+
+ sysErr, ok := opErr.Err.(syscall.Errno)
+ if !ok {
+ return false
+ }
+
+ return sysErr == syscall.EMSGSIZE || sysErr == syscall.ENOBUFS
+}
+
+func tempFd() (*os.File, error) {
+ file, err := ioutil.TempFile("/dev/shm/", "journal.XXXXX")
+ if err != nil {
+ return nil, err
+ }
+ syscall.Unlink(file.Name())
+ if err != nil {
+ return nil, err
+ }
+ return file, nil
+}
+
+func journalError(s string) error {
+ s = "journal error: " + s
+ fmt.Fprintln(os.Stderr, s)
+ return errors.New(s)
+}
diff --git a/vendor/github.com/coreos/go-systemd/util/util.go b/vendor/github.com/coreos/go-systemd/util/util.go
new file mode 100644
index 0000000..7828ce6
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/util/util.go
@@ -0,0 +1,90 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 util contains utility functions related to systemd that applications
+// can use to check things like whether systemd is running. Note that some of
+// these functions attempt to manually load systemd libraries at runtime rather
+// than linking against them.
+package util
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "strings"
+)
+
+var (
+ ErrNoCGO = fmt.Errorf("go-systemd built with CGO disabled")
+)
+
+// GetRunningSlice attempts to retrieve the name of the systemd slice in which
+// the current process is running.
+// This function is a wrapper around the libsystemd C library; if it cannot be
+// opened, an error is returned.
+func GetRunningSlice() (string, error) {
+ return getRunningSlice()
+}
+
+// RunningFromSystemService tries to detect whether the current process has
+// been invoked from a system service. The condition for this is whether the
+// process is _not_ a user process. User processes are those running in session
+// scopes or under per-user `systemd --user` instances.
+//
+// To avoid false positives on systems without `pam_systemd` (which is
+// responsible for creating user sessions), this function also uses a heuristic
+// to detect whether it's being invoked from a session leader process. This is
+// the case if the current process is executed directly from a service file
+// (e.g. with `ExecStart=/this/cmd`). Note that this heuristic will fail if the
+// command is instead launched in a subshell or similar so that it is not
+// session leader (e.g. `ExecStart=/bin/bash -c "/this/cmd"`)
+//
+// This function is a wrapper around the libsystemd C library; if this is
+// unable to successfully open a handle to the library for any reason (e.g. it
+// cannot be found), an error will be returned.
+func RunningFromSystemService() (bool, error) {
+ return runningFromSystemService()
+}
+
+// CurrentUnitName attempts to retrieve the name of the systemd system unit
+// from which the calling process has been invoked. It wraps the systemd
+// `sd_pid_get_unit` call, with the same caveat: for processes not part of a
+// systemd system unit, this function will return an error.
+func CurrentUnitName() (string, error) {
+ return currentUnitName()
+}
+
+// IsRunningSystemd checks whether the host was booted with systemd as its init
+// system. This functions similarly to systemd's `sd_booted(3)`: internally, it
+// checks whether /run/systemd/system/ exists and is a directory.
+// http://www.freedesktop.org/software/systemd/man/sd_booted.html
+func IsRunningSystemd() bool {
+ fi, err := os.Lstat("/run/systemd/system")
+ if err != nil {
+ return false
+ }
+ return fi.IsDir()
+}
+
+// GetMachineID returns a host's 128-bit machine ID as a string. This functions
+// similarly to systemd's `sd_id128_get_machine`: internally, it simply reads
+// the contents of /etc/machine-id
+// http://www.freedesktop.org/software/systemd/man/sd_id128_get_machine.html
+func GetMachineID() (string, error) {
+ machineID, err := ioutil.ReadFile("/etc/machine-id")
+ if err != nil {
+ return "", fmt.Errorf("failed to read /etc/machine-id: %v", err)
+ }
+ return strings.TrimSpace(string(machineID)), nil
+}
diff --git a/vendor/github.com/coreos/go-systemd/util/util_cgo.go b/vendor/github.com/coreos/go-systemd/util/util_cgo.go
new file mode 100644
index 0000000..22c0d60
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/util/util_cgo.go
@@ -0,0 +1,174 @@
+// Copyright 2016 CoreOS, Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build cgo
+
+package util
+
+// #include <stdlib.h>
+// #include <sys/types.h>
+// #include <unistd.h>
+//
+// int
+// my_sd_pid_get_owner_uid(void *f, pid_t pid, uid_t *uid)
+// {
+// int (*sd_pid_get_owner_uid)(pid_t, uid_t *);
+//
+// sd_pid_get_owner_uid = (int (*)(pid_t, uid_t *))f;
+// return sd_pid_get_owner_uid(pid, uid);
+// }
+//
+// int
+// my_sd_pid_get_unit(void *f, pid_t pid, char **unit)
+// {
+// int (*sd_pid_get_unit)(pid_t, char **);
+//
+// sd_pid_get_unit = (int (*)(pid_t, char **))f;
+// return sd_pid_get_unit(pid, unit);
+// }
+//
+// int
+// my_sd_pid_get_slice(void *f, pid_t pid, char **slice)
+// {
+// int (*sd_pid_get_slice)(pid_t, char **);
+//
+// sd_pid_get_slice = (int (*)(pid_t, char **))f;
+// return sd_pid_get_slice(pid, slice);
+// }
+//
+// int
+// am_session_leader()
+// {
+// return (getsid(0) == getpid());
+// }
+import "C"
+import (
+ "fmt"
+ "syscall"
+ "unsafe"
+
+ "github.com/coreos/pkg/dlopen"
+)
+
+var libsystemdNames = []string{
+ // systemd < 209
+ "libsystemd-login.so.0",
+ "libsystemd-login.so",
+
+ // systemd >= 209 merged libsystemd-login into libsystemd proper
+ "libsystemd.so.0",
+ "libsystemd.so",
+}
+
+func getRunningSlice() (slice string, err error) {
+ var h *dlopen.LibHandle
+ h, err = dlopen.GetHandle(libsystemdNames)
+ if err != nil {
+ return
+ }
+ defer func() {
+ if err1 := h.Close(); err1 != nil {
+ err = err1
+ }
+ }()
+
+ sd_pid_get_slice, err := h.GetSymbolPointer("sd_pid_get_slice")
+ if err != nil {
+ return
+ }
+
+ var s string
+ sl := C.CString(s)
+ defer C.free(unsafe.Pointer(sl))
+
+ ret := C.my_sd_pid_get_slice(sd_pid_get_slice, 0, &sl)
+ if ret < 0 {
+ err = fmt.Errorf("error calling sd_pid_get_slice: %v", syscall.Errno(-ret))
+ return
+ }
+
+ return C.GoString(sl), nil
+}
+
+func runningFromSystemService() (ret bool, err error) {
+ var h *dlopen.LibHandle
+ h, err = dlopen.GetHandle(libsystemdNames)
+ if err != nil {
+ return
+ }
+ defer func() {
+ if err1 := h.Close(); err1 != nil {
+ err = err1
+ }
+ }()
+
+ sd_pid_get_owner_uid, err := h.GetSymbolPointer("sd_pid_get_owner_uid")
+ if err != nil {
+ return
+ }
+
+ var uid C.uid_t
+ errno := C.my_sd_pid_get_owner_uid(sd_pid_get_owner_uid, 0, &uid)
+ serrno := syscall.Errno(-errno)
+ // when we're running from a unit file, sd_pid_get_owner_uid returns
+ // ENOENT (systemd <220) or ENXIO (systemd >=220)
+ switch {
+ case errno >= 0:
+ ret = false
+ case serrno == syscall.ENOENT, serrno == syscall.ENXIO:
+ // Since the implementation of sessions in systemd relies on
+ // the `pam_systemd` module, using the sd_pid_get_owner_uid
+ // heuristic alone can result in false positives if that module
+ // (or PAM itself) is not present or properly configured on the
+ // system. As such, we also check if we're the session leader,
+ // which should be the case if we're invoked from a unit file,
+ // but not if e.g. we're invoked from the command line from a
+ // user's login session
+ ret = C.am_session_leader() == 1
+ default:
+ err = fmt.Errorf("error calling sd_pid_get_owner_uid: %v", syscall.Errno(-errno))
+ }
+ return
+}
+
+func currentUnitName() (unit string, err error) {
+ var h *dlopen.LibHandle
+ h, err = dlopen.GetHandle(libsystemdNames)
+ if err != nil {
+ return
+ }
+ defer func() {
+ if err1 := h.Close(); err1 != nil {
+ err = err1
+ }
+ }()
+
+ sd_pid_get_unit, err := h.GetSymbolPointer("sd_pid_get_unit")
+ if err != nil {
+ return
+ }
+
+ var s string
+ u := C.CString(s)
+ defer C.free(unsafe.Pointer(u))
+
+ ret := C.my_sd_pid_get_unit(sd_pid_get_unit, 0, &u)
+ if ret < 0 {
+ err = fmt.Errorf("error calling sd_pid_get_unit: %v", syscall.Errno(-ret))
+ return
+ }
+
+ unit = C.GoString(u)
+ return
+}
diff --git a/vendor/github.com/coreos/go-systemd/util/util_stub.go b/vendor/github.com/coreos/go-systemd/util/util_stub.go
new file mode 100644
index 0000000..477589e
--- /dev/null
+++ b/vendor/github.com/coreos/go-systemd/util/util_stub.go
@@ -0,0 +1,23 @@
+// Copyright 2016 CoreOS, Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build !cgo
+
+package util
+
+func getRunningSlice() (string, error) { return "", ErrNoCGO }
+
+func runningFromSystemService() (bool, error) { return false, ErrNoCGO }
+
+func currentUnitName() (string, error) { return "", ErrNoCGO }
diff --git a/vendor/github.com/coreos/pkg/LICENSE b/vendor/github.com/coreos/pkg/LICENSE
new file mode 100644
index 0000000..e06d208
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/LICENSE
@@ -0,0 +1,202 @@
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/vendor/github.com/coreos/pkg/NOTICE b/vendor/github.com/coreos/pkg/NOTICE
new file mode 100644
index 0000000..b39ddfa
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/NOTICE
@@ -0,0 +1,5 @@
+CoreOS Project
+Copyright 2014 CoreOS, Inc
+
+This product includes software developed at CoreOS, Inc.
+(http://www.coreos.com/).
diff --git a/vendor/github.com/coreos/pkg/README.md b/vendor/github.com/coreos/pkg/README.md
new file mode 100644
index 0000000..ca68a07
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/README.md
@@ -0,0 +1,4 @@
+a collection of go utility packages
+
+[![Build Status](https://travis-ci.org/coreos/pkg.png?branch=master)](https://travis-ci.org/coreos/pkg)
+[![Godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/coreos/pkg)
diff --git a/vendor/github.com/coreos/pkg/capnslog/README.md b/vendor/github.com/coreos/pkg/capnslog/README.md
new file mode 100644
index 0000000..81efb1f
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/capnslog/README.md
@@ -0,0 +1,39 @@
+# capnslog, the CoreOS logging package
+
+There are far too many logging packages out there, with varying degrees of licenses, far too many features (colorization, all sorts of log frameworks) or are just a pain to use (lack of `Fatalln()`?).
+capnslog provides a simple but consistent logging interface suitable for all kinds of projects.
+
+### Design Principles
+
+##### `package main` is the place where logging gets turned on and routed
+
+A library should not touch log options, only generate log entries. Libraries are silent until main lets them speak.
+
+##### All log options are runtime-configurable.
+
+Still the job of `main` to expose these configurations. `main` may delegate this to, say, a configuration webhook, but does so explicitly.
+
+##### There is one log object per package. It is registered under its repository and package name.
+
+`main` activates logging for its repository and any dependency repositories it would also like to have output in its logstream. `main` also dictates at which level each subpackage logs.
+
+##### There is *one* output stream, and it is an `io.Writer` composed with a formatter.
+
+Splitting streams is probably not the job of your program, but rather, your log aggregation framework. If you must split output streams, again, `main` configures this and you can write a very simple two-output struct that satisfies io.Writer.
+
+Fancy colorful formatting and JSON output are beyond the scope of a basic logging framework -- they're application/log-collector dependant. These are, at best, provided as options, but more likely, provided by your application.
+
+##### Log objects are an interface
+
+An object knows best how to print itself. Log objects can collect more interesting metadata if they wish, however, because text isn't going away anytime soon, they must all be marshalable to text. The simplest log object is a string, which returns itself. If you wish to do more fancy tricks for printing your log objects, see also JSON output -- introspect and write a formatter which can handle your advanced log interface. Making strings is the only thing guaranteed.
+
+##### Log levels have specific meanings:
+
+ * Critical: Unrecoverable. Must fail.
+ * Error: Data has been lost, a request has failed for a bad reason, or a required resource has been lost
+ * Warning: (Hopefully) Temporary conditions that may cause errors, but may work fine. A replica disappearing (that may reconnect) is a warning.
+ * Notice: Normal, but important (uncommon) log information.
+ * Info: Normal, working log information, everything is fine, but helpful notices for auditing or common operations.
+ * Debug: Everything is still fine, but even common operations may be logged, and less helpful but more quantity of notices.
+ * Trace: Anything goes, from logging every function call as part of a common operation, to tracing execution of a query.
+
diff --git a/vendor/github.com/coreos/pkg/capnslog/formatters.go b/vendor/github.com/coreos/pkg/capnslog/formatters.go
new file mode 100644
index 0000000..b305a84
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/capnslog/formatters.go
@@ -0,0 +1,157 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 capnslog
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "log"
+ "runtime"
+ "strings"
+ "time"
+)
+
+type Formatter interface {
+ Format(pkg string, level LogLevel, depth int, entries ...interface{})
+ Flush()
+}
+
+func NewStringFormatter(w io.Writer) Formatter {
+ return &StringFormatter{
+ w: bufio.NewWriter(w),
+ }
+}
+
+type StringFormatter struct {
+ w *bufio.Writer
+}
+
+func (s *StringFormatter) Format(pkg string, l LogLevel, i int, entries ...interface{}) {
+ now := time.Now().UTC()
+ s.w.WriteString(now.Format(time.RFC3339))
+ s.w.WriteByte(' ')
+ writeEntries(s.w, pkg, l, i, entries...)
+ s.Flush()
+}
+
+func writeEntries(w *bufio.Writer, pkg string, _ LogLevel, _ int, entries ...interface{}) {
+ if pkg != "" {
+ w.WriteString(pkg + ": ")
+ }
+ str := fmt.Sprint(entries...)
+ endsInNL := strings.HasSuffix(str, "\n")
+ w.WriteString(str)
+ if !endsInNL {
+ w.WriteString("\n")
+ }
+}
+
+func (s *StringFormatter) Flush() {
+ s.w.Flush()
+}
+
+func NewPrettyFormatter(w io.Writer, debug bool) Formatter {
+ return &PrettyFormatter{
+ w: bufio.NewWriter(w),
+ debug: debug,
+ }
+}
+
+type PrettyFormatter struct {
+ w *bufio.Writer
+ debug bool
+}
+
+func (c *PrettyFormatter) Format(pkg string, l LogLevel, depth int, entries ...interface{}) {
+ now := time.Now()
+ ts := now.Format("2006-01-02 15:04:05")
+ c.w.WriteString(ts)
+ ms := now.Nanosecond() / 1000
+ c.w.WriteString(fmt.Sprintf(".%06d", ms))
+ if c.debug {
+ _, file, line, ok := runtime.Caller(depth) // It's always the same number of frames to the user's call.
+ if !ok {
+ file = "???"
+ line = 1
+ } else {
+ slash := strings.LastIndex(file, "/")
+ if slash >= 0 {
+ file = file[slash+1:]
+ }
+ }
+ if line < 0 {
+ line = 0 // not a real line number
+ }
+ c.w.WriteString(fmt.Sprintf(" [%s:%d]", file, line))
+ }
+ c.w.WriteString(fmt.Sprint(" ", l.Char(), " | "))
+ writeEntries(c.w, pkg, l, depth, entries...)
+ c.Flush()
+}
+
+func (c *PrettyFormatter) Flush() {
+ c.w.Flush()
+}
+
+// LogFormatter emulates the form of the traditional built-in logger.
+type LogFormatter struct {
+ logger *log.Logger
+ prefix string
+}
+
+// NewLogFormatter is a helper to produce a new LogFormatter struct. It uses the
+// golang log package to actually do the logging work so that logs look similar.
+func NewLogFormatter(w io.Writer, prefix string, flag int) Formatter {
+ return &LogFormatter{
+ logger: log.New(w, "", flag), // don't use prefix here
+ prefix: prefix, // save it instead
+ }
+}
+
+// Format builds a log message for the LogFormatter. The LogLevel is ignored.
+func (lf *LogFormatter) Format(pkg string, _ LogLevel, _ int, entries ...interface{}) {
+ str := fmt.Sprint(entries...)
+ prefix := lf.prefix
+ if pkg != "" {
+ prefix = fmt.Sprintf("%s%s: ", prefix, pkg)
+ }
+ lf.logger.Output(5, fmt.Sprintf("%s%v", prefix, str)) // call depth is 5
+}
+
+// Flush is included so that the interface is complete, but is a no-op.
+func (lf *LogFormatter) Flush() {
+ // noop
+}
+
+// NilFormatter is a no-op log formatter that does nothing.
+type NilFormatter struct {
+}
+
+// NewNilFormatter is a helper to produce a new LogFormatter struct. It logs no
+// messages so that you can cause part of your logging to be silent.
+func NewNilFormatter() Formatter {
+ return &NilFormatter{}
+}
+
+// Format does nothing.
+func (_ *NilFormatter) Format(_ string, _ LogLevel, _ int, _ ...interface{}) {
+ // noop
+}
+
+// Flush is included so that the interface is complete, but is a no-op.
+func (_ *NilFormatter) Flush() {
+ // noop
+}
diff --git a/vendor/github.com/coreos/pkg/capnslog/glog_formatter.go b/vendor/github.com/coreos/pkg/capnslog/glog_formatter.go
new file mode 100644
index 0000000..426603e
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/capnslog/glog_formatter.go
@@ -0,0 +1,96 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 capnslog
+
+import (
+ "bufio"
+ "bytes"
+ "io"
+ "os"
+ "runtime"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var pid = os.Getpid()
+
+type GlogFormatter struct {
+ StringFormatter
+}
+
+func NewGlogFormatter(w io.Writer) *GlogFormatter {
+ g := &GlogFormatter{}
+ g.w = bufio.NewWriter(w)
+ return g
+}
+
+func (g GlogFormatter) Format(pkg string, level LogLevel, depth int, entries ...interface{}) {
+ g.w.Write(GlogHeader(level, depth+1))
+ g.StringFormatter.Format(pkg, level, depth+1, entries...)
+}
+
+func GlogHeader(level LogLevel, depth int) []byte {
+ // Lmmdd hh:mm:ss.uuuuuu threadid file:line]
+ now := time.Now().UTC()
+ _, file, line, ok := runtime.Caller(depth) // It's always the same number of frames to the user's call.
+ if !ok {
+ file = "???"
+ line = 1
+ } else {
+ slash := strings.LastIndex(file, "/")
+ if slash >= 0 {
+ file = file[slash+1:]
+ }
+ }
+ if line < 0 {
+ line = 0 // not a real line number
+ }
+ buf := &bytes.Buffer{}
+ buf.Grow(30)
+ _, month, day := now.Date()
+ hour, minute, second := now.Clock()
+ buf.WriteString(level.Char())
+ twoDigits(buf, int(month))
+ twoDigits(buf, day)
+ buf.WriteByte(' ')
+ twoDigits(buf, hour)
+ buf.WriteByte(':')
+ twoDigits(buf, minute)
+ buf.WriteByte(':')
+ twoDigits(buf, second)
+ buf.WriteByte('.')
+ buf.WriteString(strconv.Itoa(now.Nanosecond() / 1000))
+ buf.WriteByte('Z')
+ buf.WriteByte(' ')
+ buf.WriteString(strconv.Itoa(pid))
+ buf.WriteByte(' ')
+ buf.WriteString(file)
+ buf.WriteByte(':')
+ buf.WriteString(strconv.Itoa(line))
+ buf.WriteByte(']')
+ buf.WriteByte(' ')
+ return buf.Bytes()
+}
+
+const digits = "0123456789"
+
+func twoDigits(b *bytes.Buffer, d int) {
+ c2 := digits[d%10]
+ d /= 10
+ c1 := digits[d%10]
+ b.WriteByte(c1)
+ b.WriteByte(c2)
+}
diff --git a/vendor/github.com/coreos/pkg/capnslog/init.go b/vendor/github.com/coreos/pkg/capnslog/init.go
new file mode 100644
index 0000000..44b8cd3
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/capnslog/init.go
@@ -0,0 +1,49 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// +build !windows
+
+package capnslog
+
+import (
+ "io"
+ "os"
+ "syscall"
+)
+
+// Here's where the opinionation comes in. We need some sensible defaults,
+// especially after taking over the log package. Your project (whatever it may
+// be) may see things differently. That's okay; there should be no defaults in
+// the main package that cannot be controlled or overridden programatically,
+// otherwise it's a bug. Doing so is creating your own init_log.go file much
+// like this one.
+
+func init() {
+ initHijack()
+
+ // Go `log` pacakge uses os.Stderr.
+ SetFormatter(NewDefaultFormatter(os.Stderr))
+ SetGlobalLogLevel(INFO)
+}
+
+func NewDefaultFormatter(out io.Writer) Formatter {
+ if syscall.Getppid() == 1 {
+ // We're running under init, which may be systemd.
+ f, err := NewJournaldFormatter()
+ if err == nil {
+ return f
+ }
+ }
+ return NewPrettyFormatter(out, false)
+}
diff --git a/vendor/github.com/coreos/pkg/capnslog/init_windows.go b/vendor/github.com/coreos/pkg/capnslog/init_windows.go
new file mode 100644
index 0000000..4553050
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/capnslog/init_windows.go
@@ -0,0 +1,25 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 capnslog
+
+import "os"
+
+func init() {
+ initHijack()
+
+ // Go `log` package uses os.Stderr.
+ SetFormatter(NewPrettyFormatter(os.Stderr, false))
+ SetGlobalLogLevel(INFO)
+}
diff --git a/vendor/github.com/coreos/pkg/capnslog/journald_formatter.go b/vendor/github.com/coreos/pkg/capnslog/journald_formatter.go
new file mode 100644
index 0000000..72e0520
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/capnslog/journald_formatter.go
@@ -0,0 +1,68 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// +build !windows
+
+package capnslog
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/coreos/go-systemd/journal"
+)
+
+func NewJournaldFormatter() (Formatter, error) {
+ if !journal.Enabled() {
+ return nil, errors.New("No systemd detected")
+ }
+ return &journaldFormatter{}, nil
+}
+
+type journaldFormatter struct{}
+
+func (j *journaldFormatter) Format(pkg string, l LogLevel, _ int, entries ...interface{}) {
+ var pri journal.Priority
+ switch l {
+ case CRITICAL:
+ pri = journal.PriCrit
+ case ERROR:
+ pri = journal.PriErr
+ case WARNING:
+ pri = journal.PriWarning
+ case NOTICE:
+ pri = journal.PriNotice
+ case INFO:
+ pri = journal.PriInfo
+ case DEBUG:
+ pri = journal.PriDebug
+ case TRACE:
+ pri = journal.PriDebug
+ default:
+ panic("Unhandled loglevel")
+ }
+ msg := fmt.Sprint(entries...)
+ tags := map[string]string{
+ "PACKAGE": pkg,
+ "SYSLOG_IDENTIFIER": filepath.Base(os.Args[0]),
+ }
+ err := journal.Send(msg, pri, tags)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ }
+}
+
+func (j *journaldFormatter) Flush() {}
diff --git a/vendor/github.com/coreos/pkg/capnslog/log_hijack.go b/vendor/github.com/coreos/pkg/capnslog/log_hijack.go
new file mode 100644
index 0000000..970086b
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/capnslog/log_hijack.go
@@ -0,0 +1,39 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 capnslog
+
+import (
+ "log"
+)
+
+func initHijack() {
+ pkg := NewPackageLogger("log", "")
+ w := packageWriter{pkg}
+ log.SetFlags(0)
+ log.SetPrefix("")
+ log.SetOutput(w)
+}
+
+type packageWriter struct {
+ pl *PackageLogger
+}
+
+func (p packageWriter) Write(b []byte) (int, error) {
+ if p.pl.level < INFO {
+ return 0, nil
+ }
+ p.pl.internalLog(calldepth+2, INFO, string(b))
+ return len(b), nil
+}
diff --git a/vendor/github.com/coreos/pkg/capnslog/logmap.go b/vendor/github.com/coreos/pkg/capnslog/logmap.go
new file mode 100644
index 0000000..8495448
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/capnslog/logmap.go
@@ -0,0 +1,240 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 capnslog
+
+import (
+ "errors"
+ "strings"
+ "sync"
+)
+
+// LogLevel is the set of all log levels.
+type LogLevel int8
+
+const (
+ // CRITICAL is the lowest log level; only errors which will end the program will be propagated.
+ CRITICAL LogLevel = iota - 1
+ // ERROR is for errors that are not fatal but lead to troubling behavior.
+ ERROR
+ // WARNING is for errors which are not fatal and not errors, but are unusual. Often sourced from misconfigurations.
+ WARNING
+ // NOTICE is for normal but significant conditions.
+ NOTICE
+ // INFO is a log level for common, everyday log updates.
+ INFO
+ // DEBUG is the default hidden level for more verbose updates about internal processes.
+ DEBUG
+ // TRACE is for (potentially) call by call tracing of programs.
+ TRACE
+)
+
+// Char returns a single-character representation of the log level.
+func (l LogLevel) Char() string {
+ switch l {
+ case CRITICAL:
+ return "C"
+ case ERROR:
+ return "E"
+ case WARNING:
+ return "W"
+ case NOTICE:
+ return "N"
+ case INFO:
+ return "I"
+ case DEBUG:
+ return "D"
+ case TRACE:
+ return "T"
+ default:
+ panic("Unhandled loglevel")
+ }
+}
+
+// String returns a multi-character representation of the log level.
+func (l LogLevel) String() string {
+ switch l {
+ case CRITICAL:
+ return "CRITICAL"
+ case ERROR:
+ return "ERROR"
+ case WARNING:
+ return "WARNING"
+ case NOTICE:
+ return "NOTICE"
+ case INFO:
+ return "INFO"
+ case DEBUG:
+ return "DEBUG"
+ case TRACE:
+ return "TRACE"
+ default:
+ panic("Unhandled loglevel")
+ }
+}
+
+// Update using the given string value. Fulfills the flag.Value interface.
+func (l *LogLevel) Set(s string) error {
+ value, err := ParseLevel(s)
+ if err != nil {
+ return err
+ }
+
+ *l = value
+ return nil
+}
+
+// ParseLevel translates some potential loglevel strings into their corresponding levels.
+func ParseLevel(s string) (LogLevel, error) {
+ switch s {
+ case "CRITICAL", "C":
+ return CRITICAL, nil
+ case "ERROR", "0", "E":
+ return ERROR, nil
+ case "WARNING", "1", "W":
+ return WARNING, nil
+ case "NOTICE", "2", "N":
+ return NOTICE, nil
+ case "INFO", "3", "I":
+ return INFO, nil
+ case "DEBUG", "4", "D":
+ return DEBUG, nil
+ case "TRACE", "5", "T":
+ return TRACE, nil
+ }
+ return CRITICAL, errors.New("couldn't parse log level " + s)
+}
+
+type RepoLogger map[string]*PackageLogger
+
+type loggerStruct struct {
+ sync.Mutex
+ repoMap map[string]RepoLogger
+ formatter Formatter
+}
+
+// logger is the global logger
+var logger = new(loggerStruct)
+
+// SetGlobalLogLevel sets the log level for all packages in all repositories
+// registered with capnslog.
+func SetGlobalLogLevel(l LogLevel) {
+ logger.Lock()
+ defer logger.Unlock()
+ for _, r := range logger.repoMap {
+ r.setRepoLogLevelInternal(l)
+ }
+}
+
+// GetRepoLogger may return the handle to the repository's set of packages' loggers.
+func GetRepoLogger(repo string) (RepoLogger, error) {
+ logger.Lock()
+ defer logger.Unlock()
+ r, ok := logger.repoMap[repo]
+ if !ok {
+ return nil, errors.New("no packages registered for repo " + repo)
+ }
+ return r, nil
+}
+
+// MustRepoLogger returns the handle to the repository's packages' loggers.
+func MustRepoLogger(repo string) RepoLogger {
+ r, err := GetRepoLogger(repo)
+ if err != nil {
+ panic(err)
+ }
+ return r
+}
+
+// SetRepoLogLevel sets the log level for all packages in the repository.
+func (r RepoLogger) SetRepoLogLevel(l LogLevel) {
+ logger.Lock()
+ defer logger.Unlock()
+ r.setRepoLogLevelInternal(l)
+}
+
+func (r RepoLogger) setRepoLogLevelInternal(l LogLevel) {
+ for _, v := range r {
+ v.level = l
+ }
+}
+
+// ParseLogLevelConfig parses a comma-separated string of "package=loglevel", in
+// order, and returns a map of the results, for use in SetLogLevel.
+func (r RepoLogger) ParseLogLevelConfig(conf string) (map[string]LogLevel, error) {
+ setlist := strings.Split(conf, ",")
+ out := make(map[string]LogLevel)
+ for _, setstring := range setlist {
+ setting := strings.Split(setstring, "=")
+ if len(setting) != 2 {
+ return nil, errors.New("oddly structured `pkg=level` option: " + setstring)
+ }
+ l, err := ParseLevel(setting[1])
+ if err != nil {
+ return nil, err
+ }
+ out[setting[0]] = l
+ }
+ return out, nil
+}
+
+// SetLogLevel takes a map of package names within a repository to their desired
+// loglevel, and sets the levels appropriately. Unknown packages are ignored.
+// "*" is a special package name that corresponds to all packages, and will be
+// processed first.
+func (r RepoLogger) SetLogLevel(m map[string]LogLevel) {
+ logger.Lock()
+ defer logger.Unlock()
+ if l, ok := m["*"]; ok {
+ r.setRepoLogLevelInternal(l)
+ }
+ for k, v := range m {
+ l, ok := r[k]
+ if !ok {
+ continue
+ }
+ l.level = v
+ }
+}
+
+// SetFormatter sets the formatting function for all logs.
+func SetFormatter(f Formatter) {
+ logger.Lock()
+ defer logger.Unlock()
+ logger.formatter = f
+}
+
+// NewPackageLogger creates a package logger object.
+// This should be defined as a global var in your package, referencing your repo.
+func NewPackageLogger(repo string, pkg string) (p *PackageLogger) {
+ logger.Lock()
+ defer logger.Unlock()
+ if logger.repoMap == nil {
+ logger.repoMap = make(map[string]RepoLogger)
+ }
+ r, rok := logger.repoMap[repo]
+ if !rok {
+ logger.repoMap[repo] = make(RepoLogger)
+ r = logger.repoMap[repo]
+ }
+ p, pok := r[pkg]
+ if !pok {
+ r[pkg] = &PackageLogger{
+ pkg: pkg,
+ level: INFO,
+ }
+ p = r[pkg]
+ }
+ return
+}
diff --git a/vendor/github.com/coreos/pkg/capnslog/pkg_logger.go b/vendor/github.com/coreos/pkg/capnslog/pkg_logger.go
new file mode 100644
index 0000000..612d55c
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/capnslog/pkg_logger.go
@@ -0,0 +1,177 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 capnslog
+
+import (
+ "fmt"
+ "os"
+)
+
+type PackageLogger struct {
+ pkg string
+ level LogLevel
+}
+
+const calldepth = 2
+
+func (p *PackageLogger) internalLog(depth int, inLevel LogLevel, entries ...interface{}) {
+ logger.Lock()
+ defer logger.Unlock()
+ if inLevel != CRITICAL && p.level < inLevel {
+ return
+ }
+ if logger.formatter != nil {
+ logger.formatter.Format(p.pkg, inLevel, depth+1, entries...)
+ }
+}
+
+func (p *PackageLogger) LevelAt(l LogLevel) bool {
+ logger.Lock()
+ defer logger.Unlock()
+ return p.level >= l
+}
+
+// Log a formatted string at any level between ERROR and TRACE
+func (p *PackageLogger) Logf(l LogLevel, format string, args ...interface{}) {
+ p.internalLog(calldepth, l, fmt.Sprintf(format, args...))
+}
+
+// Log a message at any level between ERROR and TRACE
+func (p *PackageLogger) Log(l LogLevel, args ...interface{}) {
+ p.internalLog(calldepth, l, fmt.Sprint(args...))
+}
+
+// log stdlib compatibility
+
+func (p *PackageLogger) Println(args ...interface{}) {
+ p.internalLog(calldepth, INFO, fmt.Sprintln(args...))
+}
+
+func (p *PackageLogger) Printf(format string, args ...interface{}) {
+ p.Logf(INFO, format, args...)
+}
+
+func (p *PackageLogger) Print(args ...interface{}) {
+ p.internalLog(calldepth, INFO, fmt.Sprint(args...))
+}
+
+// Panic and fatal
+
+func (p *PackageLogger) Panicf(format string, args ...interface{}) {
+ s := fmt.Sprintf(format, args...)
+ p.internalLog(calldepth, CRITICAL, s)
+ panic(s)
+}
+
+func (p *PackageLogger) Panic(args ...interface{}) {
+ s := fmt.Sprint(args...)
+ p.internalLog(calldepth, CRITICAL, s)
+ panic(s)
+}
+
+func (p *PackageLogger) Fatalf(format string, args ...interface{}) {
+ p.Logf(CRITICAL, format, args...)
+ os.Exit(1)
+}
+
+func (p *PackageLogger) Fatal(args ...interface{}) {
+ s := fmt.Sprint(args...)
+ p.internalLog(calldepth, CRITICAL, s)
+ os.Exit(1)
+}
+
+func (p *PackageLogger) Fatalln(args ...interface{}) {
+ s := fmt.Sprintln(args...)
+ p.internalLog(calldepth, CRITICAL, s)
+ os.Exit(1)
+}
+
+// Error Functions
+
+func (p *PackageLogger) Errorf(format string, args ...interface{}) {
+ p.Logf(ERROR, format, args...)
+}
+
+func (p *PackageLogger) Error(entries ...interface{}) {
+ p.internalLog(calldepth, ERROR, entries...)
+}
+
+// Warning Functions
+
+func (p *PackageLogger) Warningf(format string, args ...interface{}) {
+ p.Logf(WARNING, format, args...)
+}
+
+func (p *PackageLogger) Warning(entries ...interface{}) {
+ p.internalLog(calldepth, WARNING, entries...)
+}
+
+// Notice Functions
+
+func (p *PackageLogger) Noticef(format string, args ...interface{}) {
+ p.Logf(NOTICE, format, args...)
+}
+
+func (p *PackageLogger) Notice(entries ...interface{}) {
+ p.internalLog(calldepth, NOTICE, entries...)
+}
+
+// Info Functions
+
+func (p *PackageLogger) Infof(format string, args ...interface{}) {
+ p.Logf(INFO, format, args...)
+}
+
+func (p *PackageLogger) Info(entries ...interface{}) {
+ p.internalLog(calldepth, INFO, entries...)
+}
+
+// Debug Functions
+
+func (p *PackageLogger) Debugf(format string, args ...interface{}) {
+ if p.level < DEBUG {
+ return
+ }
+ p.Logf(DEBUG, format, args...)
+}
+
+func (p *PackageLogger) Debug(entries ...interface{}) {
+ if p.level < DEBUG {
+ return
+ }
+ p.internalLog(calldepth, DEBUG, entries...)
+}
+
+// Trace Functions
+
+func (p *PackageLogger) Tracef(format string, args ...interface{}) {
+ if p.level < TRACE {
+ return
+ }
+ p.Logf(TRACE, format, args...)
+}
+
+func (p *PackageLogger) Trace(entries ...interface{}) {
+ if p.level < TRACE {
+ return
+ }
+ p.internalLog(calldepth, TRACE, entries...)
+}
+
+func (p *PackageLogger) Flush() {
+ logger.Lock()
+ defer logger.Unlock()
+ logger.formatter.Flush()
+}
diff --git a/vendor/github.com/coreos/pkg/capnslog/syslog_formatter.go b/vendor/github.com/coreos/pkg/capnslog/syslog_formatter.go
new file mode 100644
index 0000000..4be5a1f
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/capnslog/syslog_formatter.go
@@ -0,0 +1,65 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// +build !windows
+
+package capnslog
+
+import (
+ "fmt"
+ "log/syslog"
+)
+
+func NewSyslogFormatter(w *syslog.Writer) Formatter {
+ return &syslogFormatter{w}
+}
+
+func NewDefaultSyslogFormatter(tag string) (Formatter, error) {
+ w, err := syslog.New(syslog.LOG_DEBUG, tag)
+ if err != nil {
+ return nil, err
+ }
+ return NewSyslogFormatter(w), nil
+}
+
+type syslogFormatter struct {
+ w *syslog.Writer
+}
+
+func (s *syslogFormatter) Format(pkg string, l LogLevel, _ int, entries ...interface{}) {
+ for _, entry := range entries {
+ str := fmt.Sprint(entry)
+ switch l {
+ case CRITICAL:
+ s.w.Crit(str)
+ case ERROR:
+ s.w.Err(str)
+ case WARNING:
+ s.w.Warning(str)
+ case NOTICE:
+ s.w.Notice(str)
+ case INFO:
+ s.w.Info(str)
+ case DEBUG:
+ s.w.Debug(str)
+ case TRACE:
+ s.w.Debug(str)
+ default:
+ panic("Unhandled loglevel")
+ }
+ }
+}
+
+func (s *syslogFormatter) Flush() {
+}
diff --git a/vendor/github.com/coreos/pkg/dlopen/dlopen.go b/vendor/github.com/coreos/pkg/dlopen/dlopen.go
new file mode 100644
index 0000000..23774f6
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/dlopen/dlopen.go
@@ -0,0 +1,82 @@
+// Copyright 2016 CoreOS, Inc.
+//
+// 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 dlopen provides some convenience functions to dlopen a library and
+// get its symbols.
+package dlopen
+
+// #cgo LDFLAGS: -ldl
+// #include <stdlib.h>
+// #include <dlfcn.h>
+import "C"
+import (
+ "errors"
+ "fmt"
+ "unsafe"
+)
+
+var ErrSoNotFound = errors.New("unable to open a handle to the library")
+
+// LibHandle represents an open handle to a library (.so)
+type LibHandle struct {
+ Handle unsafe.Pointer
+ Libname string
+}
+
+// GetHandle tries to get a handle to a library (.so), attempting to access it
+// by the names specified in libs and returning the first that is successfully
+// opened. Callers are responsible for closing the handler. If no library can
+// be successfully opened, an error is returned.
+func GetHandle(libs []string) (*LibHandle, error) {
+ for _, name := range libs {
+ libname := C.CString(name)
+ defer C.free(unsafe.Pointer(libname))
+ handle := C.dlopen(libname, C.RTLD_LAZY)
+ if handle != nil {
+ h := &LibHandle{
+ Handle: handle,
+ Libname: name,
+ }
+ return h, nil
+ }
+ }
+ return nil, ErrSoNotFound
+}
+
+// GetSymbolPointer takes a symbol name and returns a pointer to the symbol.
+func (l *LibHandle) GetSymbolPointer(symbol string) (unsafe.Pointer, error) {
+ sym := C.CString(symbol)
+ defer C.free(unsafe.Pointer(sym))
+
+ C.dlerror()
+ p := C.dlsym(l.Handle, sym)
+ e := C.dlerror()
+ if e != nil {
+ return nil, fmt.Errorf("error resolving symbol %q: %v", symbol, errors.New(C.GoString(e)))
+ }
+
+ return p, nil
+}
+
+// Close closes a LibHandle.
+func (l *LibHandle) Close() error {
+ C.dlerror()
+ C.dlclose(l.Handle)
+ e := C.dlerror()
+ if e != nil {
+ return fmt.Errorf("error closing %v: %v", l.Libname, errors.New(C.GoString(e)))
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/coreos/pkg/dlopen/dlopen_example.go b/vendor/github.com/coreos/pkg/dlopen/dlopen_example.go
new file mode 100644
index 0000000..48a6601
--- /dev/null
+++ b/vendor/github.com/coreos/pkg/dlopen/dlopen_example.go
@@ -0,0 +1,56 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// +build linux
+
+package dlopen
+
+// #include <string.h>
+// #include <stdlib.h>
+//
+// int
+// my_strlen(void *f, const char *s)
+// {
+// size_t (*strlen)(const char *);
+//
+// strlen = (size_t (*)(const char *))f;
+// return strlen(s);
+// }
+import "C"
+
+import (
+ "fmt"
+ "unsafe"
+)
+
+func strlen(libs []string, s string) (int, error) {
+ h, err := GetHandle(libs)
+ if err != nil {
+ return -1, fmt.Errorf(`couldn't get a handle to the library: %v`, err)
+ }
+ defer h.Close()
+
+ f := "strlen"
+ cs := C.CString(s)
+ defer C.free(unsafe.Pointer(cs))
+
+ strlen, err := h.GetSymbolPointer(f)
+ if err != nil {
+ return -1, fmt.Errorf(`couldn't get symbol %q: %v`, f, err)
+ }
+
+ len := C.my_strlen(strlen, cs)
+
+ return int(len), nil
+}
diff --git a/vendor/github.com/cyberdelia/go-metrics-graphite/LICENSE b/vendor/github.com/cyberdelia/go-metrics-graphite/LICENSE
new file mode 100644
index 0000000..fdfc8ab
--- /dev/null
+++ b/vendor/github.com/cyberdelia/go-metrics-graphite/LICENSE
@@ -0,0 +1,22 @@
+Copyright 2015 Timothée Peignier. 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 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/cyberdelia/go-metrics-graphite/README.md b/vendor/github.com/cyberdelia/go-metrics-graphite/README.md
new file mode 100644
index 0000000..e43f4df
--- /dev/null
+++ b/vendor/github.com/cyberdelia/go-metrics-graphite/README.md
@@ -0,0 +1,19 @@
+This is a reporter for the [go-metrics](https://github.com/rcrowley/go-metrics)
+library which will post the metrics to Graphite. It was originally part of the
+`go-metrics` library itself, but has been split off to make maintenance of
+both the core library and the client easier.
+
+### Usage
+
+```go
+import "github.com/cyberdelia/go-metrics-graphite"
+
+
+go graphite.Graphite(metrics.DefaultRegistry,
+ 1*time.Second, "some.prefix", addr)
+```
+
+### Migrating from `rcrowley/go-metrics` implementation
+
+Simply modify the import from `"github.com/rcrowley/go-metrics/librato"` to
+`"github.com/cyberdelia/go-metrics-graphite"` and it should Just Work.
diff --git a/vendor/github.com/cyberdelia/go-metrics-graphite/graphite.go b/vendor/github.com/cyberdelia/go-metrics-graphite/graphite.go
new file mode 100644
index 0000000..ffc309b
--- /dev/null
+++ b/vendor/github.com/cyberdelia/go-metrics-graphite/graphite.go
@@ -0,0 +1,113 @@
+package graphite
+
+import (
+ "bufio"
+ "fmt"
+ "log"
+ "net"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/rcrowley/go-metrics"
+)
+
+// GraphiteConfig provides a container with configuration parameters for
+// the Graphite exporter
+type GraphiteConfig struct {
+ Addr *net.TCPAddr // Network address to connect to
+ Registry metrics.Registry // Registry to be exported
+ FlushInterval time.Duration // Flush interval
+ DurationUnit time.Duration // Time conversion unit for durations
+ Prefix string // Prefix to be prepended to metric names
+ Percentiles []float64 // Percentiles to export from timers and histograms
+}
+
+// Graphite is a blocking exporter function which reports metrics in r
+// to a graphite server located at addr, flushing them every d duration
+// and prepending metric names with prefix.
+func Graphite(r metrics.Registry, d time.Duration, prefix string, addr *net.TCPAddr) {
+ GraphiteWithConfig(GraphiteConfig{
+ Addr: addr,
+ Registry: r,
+ FlushInterval: d,
+ DurationUnit: time.Nanosecond,
+ Prefix: prefix,
+ Percentiles: []float64{0.5, 0.75, 0.95, 0.99, 0.999},
+ })
+}
+
+// GraphiteWithConfig is a blocking exporter function just like Graphite,
+// but it takes a GraphiteConfig instead.
+func GraphiteWithConfig(c GraphiteConfig) {
+ for _ = range time.Tick(c.FlushInterval) {
+ if err := graphite(&c); nil != err {
+ log.Println(err)
+ }
+ }
+}
+
+// GraphiteOnce performs a single submission to Graphite, returning a
+// non-nil error on failed connections. This can be used in a loop
+// similar to GraphiteWithConfig for custom error handling.
+func GraphiteOnce(c GraphiteConfig) error {
+ return graphite(&c)
+}
+
+func graphite(c *GraphiteConfig) error {
+ now := time.Now().Unix()
+ du := float64(c.DurationUnit)
+ conn, err := net.DialTCP("tcp", nil, c.Addr)
+ if nil != err {
+ return err
+ }
+ defer conn.Close()
+ w := bufio.NewWriter(conn)
+ c.Registry.Each(func(name string, i interface{}) {
+ switch metric := i.(type) {
+ case metrics.Counter:
+ fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, metric.Count(), now)
+ case metrics.Gauge:
+ fmt.Fprintf(w, "%s.%s.value %d %d\n", c.Prefix, name, metric.Value(), now)
+ case metrics.GaugeFloat64:
+ fmt.Fprintf(w, "%s.%s.value %f %d\n", c.Prefix, name, metric.Value(), now)
+ case metrics.Histogram:
+ h := metric.Snapshot()
+ ps := h.Percentiles(c.Percentiles)
+ fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, h.Count(), now)
+ fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, h.Min(), now)
+ fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, h.Max(), now)
+ fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, h.Mean(), now)
+ fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, h.StdDev(), now)
+ for psIdx, psKey := range c.Percentiles {
+ key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1)
+ fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx], now)
+ }
+ case metrics.Meter:
+ m := metric.Snapshot()
+ fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, m.Count(), now)
+ fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, m.Rate1(), now)
+ fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, m.Rate5(), now)
+ fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, m.Rate15(), now)
+ fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, m.RateMean(), now)
+ case metrics.Timer:
+ t := metric.Snapshot()
+ ps := t.Percentiles(c.Percentiles)
+ fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, t.Count(), now)
+ fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, t.Min()/int64(du), now)
+ fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, t.Max()/int64(du), now)
+ fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, t.Mean()/du, now)
+ fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, t.StdDev()/du, now)
+ for psIdx, psKey := range c.Percentiles {
+ key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1)
+ fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx]/du, now)
+ }
+ fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, t.Rate1(), now)
+ fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, t.Rate5(), now)
+ fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, t.Rate15(), now)
+ fmt.Fprintf(w, "%s.%s.mean-rate %.2f %d\n", c.Prefix, name, t.RateMean(), now)
+ }
+ w.Flush()
+ })
+ return nil
+}
diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE
new file mode 100644
index 0000000..c836416
--- /dev/null
+++ b/vendor/github.com/davecgh/go-spew/LICENSE
@@ -0,0 +1,15 @@
+ISC License
+
+Copyright (c) 2012-2016 Dave Collins <dave@davec.name>
+
+Permission to use, copy, modify, and distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/vendor/github.com/davecgh/go-spew/README.md b/vendor/github.com/davecgh/go-spew/README.md
new file mode 100644
index 0000000..2624304
--- /dev/null
+++ b/vendor/github.com/davecgh/go-spew/README.md
@@ -0,0 +1,205 @@
+go-spew
+=======
+
+[![Build Status](https://img.shields.io/travis/davecgh/go-spew.svg)]
+(https://travis-ci.org/davecgh/go-spew) [![ISC License]
+(http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) [![Coverage Status]
+(https://img.shields.io/coveralls/davecgh/go-spew.svg)]
+(https://coveralls.io/r/davecgh/go-spew?branch=master)
+
+
+Go-spew implements a deep pretty printer for Go data structures to aid in
+debugging. A comprehensive suite of tests with 100% test coverage is provided
+to ensure proper functionality. See `test_coverage.txt` for the gocov coverage
+report. Go-spew is licensed under the liberal ISC license, so it may be used in
+open source or commercial projects.
+
+If you're interested in reading about how this package came to life and some
+of the challenges involved in providing a deep pretty printer, there is a blog
+post about it
+[here](https://web.archive.org/web/20160304013555/https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/).
+
+## Documentation
+
+[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)]
+(http://godoc.org/github.com/davecgh/go-spew/spew)
+
+Full `go doc` style documentation for the project can be viewed online without
+installing this package by using the excellent GoDoc site here:
+http://godoc.org/github.com/davecgh/go-spew/spew
+
+You can also view the documentation locally once the package is installed with
+the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to
+http://localhost:6060/pkg/github.com/davecgh/go-spew/spew
+
+## Installation
+
+```bash
+$ go get -u github.com/davecgh/go-spew/spew
+```
+
+## Quick Start
+
+Add this import line to the file you're working in:
+
+```Go
+import "github.com/davecgh/go-spew/spew"
+```
+
+To dump a variable with full newlines, indentation, type, and pointer
+information use Dump, Fdump, or Sdump:
+
+```Go
+spew.Dump(myVar1, myVar2, ...)
+spew.Fdump(someWriter, myVar1, myVar2, ...)
+str := spew.Sdump(myVar1, myVar2, ...)
+```
+
+Alternatively, if you would prefer to use format strings with a compacted inline
+printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most
+compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types
+and pointer addresses):
+
+```Go
+spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
+spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
+spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
+spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
+```
+
+## Debugging a Web Application Example
+
+Here is an example of how you can use `spew.Sdump()` to help debug a web application. Please be sure to wrap your output using the `html.EscapeString()` function for safety reasons. You should also only use this debugging technique in a development environment, never in production.
+
+```Go
+package main
+
+import (
+ "fmt"
+ "html"
+ "net/http"
+
+ "github.com/davecgh/go-spew/spew"
+)
+
+func handler(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/html")
+ fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:])
+ fmt.Fprintf(w, "<!--\n" + html.EscapeString(spew.Sdump(w)) + "\n-->")
+}
+
+func main() {
+ http.HandleFunc("/", handler)
+ http.ListenAndServe(":8080", nil)
+}
+```
+
+## Sample Dump Output
+
+```
+(main.Foo) {
+ unexportedField: (*main.Bar)(0xf84002e210)({
+ flag: (main.Flag) flagTwo,
+ data: (uintptr) <nil>
+ }),
+ ExportedField: (map[interface {}]interface {}) {
+ (string) "one": (bool) true
+ }
+}
+([]uint8) {
+ 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
+ 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
+ 00000020 31 32 |12|
+}
+```
+
+## Sample Formatter Output
+
+Double pointer to a uint8:
+```
+ %v: <**>5
+ %+v: <**>(0xf8400420d0->0xf8400420c8)5
+ %#v: (**uint8)5
+ %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5
+```
+
+Pointer to circular struct with a uint8 field and a pointer to itself:
+```
+ %v: <*>{1 <*><shown>}
+ %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>}
+ %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>}
+ %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)<shown>}
+```
+
+## Configuration Options
+
+Configuration of spew is handled by fields in the ConfigState type. For
+convenience, all of the top-level functions use a global state available via the
+spew.Config global.
+
+It is also possible to create a ConfigState instance that provides methods
+equivalent to the top-level functions. This allows concurrent configuration
+options. See the ConfigState documentation for more details.
+
+```
+* Indent
+ String to use for each indentation level for Dump functions.
+ It is a single space by default. A popular alternative is "\t".
+
+* MaxDepth
+ Maximum number of levels to descend into nested data structures.
+ There is no limit by default.
+
+* DisableMethods
+ Disables invocation of error and Stringer interface methods.
+ Method invocation is enabled by default.
+
+* DisablePointerMethods
+ Disables invocation of error and Stringer interface methods on types
+ which only accept pointer receivers from non-pointer variables. This option
+ relies on access to the unsafe package, so it will not have any effect when
+ running in environments without access to the unsafe package such as Google
+ App Engine or with the "safe" build tag specified.
+ Pointer method invocation is enabled by default.
+
+* DisablePointerAddresses
+ DisablePointerAddresses specifies whether to disable the printing of
+ pointer addresses. This is useful when diffing data structures in tests.
+
+* DisableCapacities
+ DisableCapacities specifies whether to disable the printing of capacities
+ for arrays, slices, maps and channels. This is useful when diffing data
+ structures in tests.
+
+* ContinueOnMethod
+ Enables recursion into types after invoking error and Stringer interface
+ methods. Recursion after method invocation is disabled by default.
+
+* SortKeys
+ Specifies map keys should be sorted before being printed. Use
+ this to have a more deterministic, diffable output. Note that
+ only native types (bool, int, uint, floats, uintptr and string)
+ and types which implement error or Stringer interfaces are supported,
+ with other types sorted according to the reflect.Value.String() output
+ which guarantees display stability. Natural map order is used by
+ default.
+
+* SpewKeys
+ SpewKeys specifies that, as a last resort attempt, map keys should be
+ spewed to strings and sorted by those strings. This is only considered
+ if SortKeys is true.
+
+```
+
+## Unsafe Package Dependency
+
+This package relies on the unsafe package to perform some of the more advanced
+features, however it also supports a "limited" mode which allows it to work in
+environments where the unsafe package is not available. By default, it will
+operate in this mode on Google App Engine and when compiled with GopherJS. The
+"safe" build tag may also be specified to force the package to build without
+using the unsafe package.
+
+## License
+
+Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License.
diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go
new file mode 100644
index 0000000..8a4a658
--- /dev/null
+++ b/vendor/github.com/davecgh/go-spew/spew/bypass.go
@@ -0,0 +1,152 @@
+// Copyright (c) 2015-2016 Dave Collins <dave@davec.name>
+//
+// Permission to use, copy, modify, and distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+// NOTE: Due to the following build constraints, this file will only be compiled
+// when the code is not running on Google App Engine, compiled by GopherJS, and
+// "-tags safe" is not added to the go build command line. The "disableunsafe"
+// tag is deprecated and thus should not be used.
+// +build !js,!appengine,!safe,!disableunsafe
+
+package spew
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+const (
+ // UnsafeDisabled is a build-time constant which specifies whether or
+ // not access to the unsafe package is available.
+ UnsafeDisabled = false
+
+ // ptrSize is the size of a pointer on the current arch.
+ ptrSize = unsafe.Sizeof((*byte)(nil))
+)
+
+var (
+ // offsetPtr, offsetScalar, and offsetFlag are the offsets for the
+ // internal reflect.Value fields. These values are valid before golang
+ // commit ecccf07e7f9d which changed the format. The are also valid
+ // after commit 82f48826c6c7 which changed the format again to mirror
+ // the original format. Code in the init function updates these offsets
+ // as necessary.
+ offsetPtr = uintptr(ptrSize)
+ offsetScalar = uintptr(0)
+ offsetFlag = uintptr(ptrSize * 2)
+
+ // flagKindWidth and flagKindShift indicate various bits that the
+ // reflect package uses internally to track kind information.
+ //
+ // flagRO indicates whether or not the value field of a reflect.Value is
+ // read-only.
+ //
+ // flagIndir indicates whether the value field of a reflect.Value is
+ // the actual data or a pointer to the data.
+ //
+ // These values are valid before golang commit 90a7c3c86944 which
+ // changed their positions. Code in the init function updates these
+ // flags as necessary.
+ flagKindWidth = uintptr(5)
+ flagKindShift = uintptr(flagKindWidth - 1)
+ flagRO = uintptr(1 << 0)
+ flagIndir = uintptr(1 << 1)
+)
+
+func init() {
+ // Older versions of reflect.Value stored small integers directly in the
+ // ptr field (which is named val in the older versions). Versions
+ // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named
+ // scalar for this purpose which unfortunately came before the flag
+ // field, so the offset of the flag field is different for those
+ // versions.
+ //
+ // This code constructs a new reflect.Value from a known small integer
+ // and checks if the size of the reflect.Value struct indicates it has
+ // the scalar field. When it does, the offsets are updated accordingly.
+ vv := reflect.ValueOf(0xf00)
+ if unsafe.Sizeof(vv) == (ptrSize * 4) {
+ offsetScalar = ptrSize * 2
+ offsetFlag = ptrSize * 3
+ }
+
+ // Commit 90a7c3c86944 changed the flag positions such that the low
+ // order bits are the kind. This code extracts the kind from the flags
+ // field and ensures it's the correct type. When it's not, the flag
+ // order has been changed to the newer format, so the flags are updated
+ // accordingly.
+ upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag)
+ upfv := *(*uintptr)(upf)
+ flagKindMask := uintptr((1<<flagKindWidth - 1) << flagKindShift)
+ if (upfv&flagKindMask)>>flagKindShift != uintptr(reflect.Int) {
+ flagKindShift = 0
+ flagRO = 1 << 5
+ flagIndir = 1 << 6
+
+ // Commit adf9b30e5594 modified the flags to separate the
+ // flagRO flag into two bits which specifies whether or not the
+ // field is embedded. This causes flagIndir to move over a bit
+ // and means that flagRO is the combination of either of the
+ // original flagRO bit and the new bit.
+ //
+ // This code detects the change by extracting what used to be
+ // the indirect bit to ensure it's set. When it's not, the flag
+ // order has been changed to the newer format, so the flags are
+ // updated accordingly.
+ if upfv&flagIndir == 0 {
+ flagRO = 3 << 5
+ flagIndir = 1 << 7
+ }
+ }
+}
+
+// unsafeReflectValue converts the passed reflect.Value into a one that bypasses
+// the typical safety restrictions preventing access to unaddressable and
+// unexported data. It works by digging the raw pointer to the underlying
+// value out of the protected value and generating a new unprotected (unsafe)
+// reflect.Value to it.
+//
+// This allows us to check for implementations of the Stringer and error
+// interfaces to be used for pretty printing ordinarily unaddressable and
+// inaccessible values such as unexported struct fields.
+func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
+ indirects := 1
+ vt := v.Type()
+ upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)
+ rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))
+ if rvf&flagIndir != 0 {
+ vt = reflect.PtrTo(v.Type())
+ indirects++
+ } else if offsetScalar != 0 {
+ // The value is in the scalar field when it's not one of the
+ // reference types.
+ switch vt.Kind() {
+ case reflect.Uintptr:
+ case reflect.Chan:
+ case reflect.Func:
+ case reflect.Map:
+ case reflect.Ptr:
+ case reflect.UnsafePointer:
+ default:
+ upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) +
+ offsetScalar)
+ }
+ }
+
+ pv := reflect.NewAt(vt, upv)
+ rv = pv
+ for i := 0; i < indirects; i++ {
+ rv = rv.Elem()
+ }
+ return rv
+}
diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go
new file mode 100644
index 0000000..1fe3cf3
--- /dev/null
+++ b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go
@@ -0,0 +1,38 @@
+// Copyright (c) 2015-2016 Dave Collins <dave@davec.name>
+//
+// Permission to use, copy, modify, and distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+// NOTE: Due to the following build constraints, this file will only be compiled
+// when the code is running on Google App Engine, compiled by GopherJS, or
+// "-tags safe" is added to the go build command line. The "disableunsafe"
+// tag is deprecated and thus should not be used.
+// +build js appengine safe disableunsafe
+
+package spew
+
+import "reflect"
+
+const (
+ // UnsafeDisabled is a build-time constant which specifies whether or
+ // not access to the unsafe package is available.
+ UnsafeDisabled = true
+)
+
+// unsafeReflectValue typically converts the passed reflect.Value into a one
+// that bypasses the typical safety restrictions preventing access to
+// unaddressable and unexported data. However, doing this relies on access to
+// the unsafe package. This is a stub version which simply returns the passed
+// reflect.Value when the unsafe package is not available.
+func unsafeReflectValue(v reflect.Value) reflect.Value {
+ return v
+}
diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go
new file mode 100644
index 0000000..7c519ff
--- /dev/null
+++ b/vendor/github.com/davecgh/go-spew/spew/common.go
@@ -0,0 +1,341 @@
+/*
+ * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+package spew
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "reflect"
+ "sort"
+ "strconv"
+)
+
+// Some constants in the form of bytes to avoid string overhead. This mirrors
+// the technique used in the fmt package.
+var (
+ panicBytes = []byte("(PANIC=")
+ plusBytes = []byte("+")
+ iBytes = []byte("i")
+ trueBytes = []byte("true")
+ falseBytes = []byte("false")
+ interfaceBytes = []byte("(interface {})")
+ commaNewlineBytes = []byte(",\n")
+ newlineBytes = []byte("\n")
+ openBraceBytes = []byte("{")
+ openBraceNewlineBytes = []byte("{\n")
+ closeBraceBytes = []byte("}")
+ asteriskBytes = []byte("*")
+ colonBytes = []byte(":")
+ colonSpaceBytes = []byte(": ")
+ openParenBytes = []byte("(")
+ closeParenBytes = []byte(")")
+ spaceBytes = []byte(" ")
+ pointerChainBytes = []byte("->")
+ nilAngleBytes = []byte("<nil>")
+ maxNewlineBytes = []byte("<max depth reached>\n")
+ maxShortBytes = []byte("<max>")
+ circularBytes = []byte("<already shown>")
+ circularShortBytes = []byte("<shown>")
+ invalidAngleBytes = []byte("<invalid>")
+ openBracketBytes = []byte("[")
+ closeBracketBytes = []byte("]")
+ percentBytes = []byte("%")
+ precisionBytes = []byte(".")
+ openAngleBytes = []byte("<")
+ closeAngleBytes = []byte(">")
+ openMapBytes = []byte("map[")
+ closeMapBytes = []byte("]")
+ lenEqualsBytes = []byte("len=")
+ capEqualsBytes = []byte("cap=")
+)
+
+// hexDigits is used to map a decimal value to a hex digit.
+var hexDigits = "0123456789abcdef"
+
+// catchPanic handles any panics that might occur during the handleMethods
+// calls.
+func catchPanic(w io.Writer, v reflect.Value) {
+ if err := recover(); err != nil {
+ w.Write(panicBytes)
+ fmt.Fprintf(w, "%v", err)
+ w.Write(closeParenBytes)
+ }
+}
+
+// handleMethods attempts to call the Error and String methods on the underlying
+// type the passed reflect.Value represents and outputes the result to Writer w.
+//
+// It handles panics in any called methods by catching and displaying the error
+// as the formatted value.
+func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
+ // We need an interface to check if the type implements the error or
+ // Stringer interface. However, the reflect package won't give us an
+ // interface on certain things like unexported struct fields in order
+ // to enforce visibility rules. We use unsafe, when it's available,
+ // to bypass these restrictions since this package does not mutate the
+ // values.
+ if !v.CanInterface() {
+ if UnsafeDisabled {
+ return false
+ }
+
+ v = unsafeReflectValue(v)
+ }
+
+ // Choose whether or not to do error and Stringer interface lookups against
+ // the base type or a pointer to the base type depending on settings.
+ // Technically calling one of these methods with a pointer receiver can
+ // mutate the value, however, types which choose to satisify an error or
+ // Stringer interface with a pointer receiver should not be mutating their
+ // state inside these interface methods.
+ if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() {
+ v = unsafeReflectValue(v)
+ }
+ if v.CanAddr() {
+ v = v.Addr()
+ }
+
+ // Is it an error or Stringer?
+ switch iface := v.Interface().(type) {
+ case error:
+ defer catchPanic(w, v)
+ if cs.ContinueOnMethod {
+ w.Write(openParenBytes)
+ w.Write([]byte(iface.Error()))
+ w.Write(closeParenBytes)
+ w.Write(spaceBytes)
+ return false
+ }
+
+ w.Write([]byte(iface.Error()))
+ return true
+
+ case fmt.Stringer:
+ defer catchPanic(w, v)
+ if cs.ContinueOnMethod {
+ w.Write(openParenBytes)
+ w.Write([]byte(iface.String()))
+ w.Write(closeParenBytes)
+ w.Write(spaceBytes)
+ return false
+ }
+ w.Write([]byte(iface.String()))
+ return true
+ }
+ return false
+}
+
+// printBool outputs a boolean value as true or false to Writer w.
+func printBool(w io.Writer, val bool) {
+ if val {
+ w.Write(trueBytes)
+ } else {
+ w.Write(falseBytes)
+ }
+}
+
+// printInt outputs a signed integer value to Writer w.
+func printInt(w io.Writer, val int64, base int) {
+ w.Write([]byte(strconv.FormatInt(val, base)))
+}
+
+// printUint outputs an unsigned integer value to Writer w.
+func printUint(w io.Writer, val uint64, base int) {
+ w.Write([]byte(strconv.FormatUint(val, base)))
+}
+
+// printFloat outputs a floating point value using the specified precision,
+// which is expected to be 32 or 64bit, to Writer w.
+func printFloat(w io.Writer, val float64, precision int) {
+ w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
+}
+
+// printComplex outputs a complex value using the specified float precision
+// for the real and imaginary parts to Writer w.
+func printComplex(w io.Writer, c complex128, floatPrecision int) {
+ r := real(c)
+ w.Write(openParenBytes)
+ w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
+ i := imag(c)
+ if i >= 0 {
+ w.Write(plusBytes)
+ }
+ w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
+ w.Write(iBytes)
+ w.Write(closeParenBytes)
+}
+
+// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
+// prefix to Writer w.
+func printHexPtr(w io.Writer, p uintptr) {
+ // Null pointer.
+ num := uint64(p)
+ if num == 0 {
+ w.Write(nilAngleBytes)
+ return
+ }
+
+ // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
+ buf := make([]byte, 18)
+
+ // It's simpler to construct the hex string right to left.
+ base := uint64(16)
+ i := len(buf) - 1
+ for num >= base {
+ buf[i] = hexDigits[num%base]
+ num /= base
+ i--
+ }
+ buf[i] = hexDigits[num]
+
+ // Add '0x' prefix.
+ i--
+ buf[i] = 'x'
+ i--
+ buf[i] = '0'
+
+ // Strip unused leading bytes.
+ buf = buf[i:]
+ w.Write(buf)
+}
+
+// valuesSorter implements sort.Interface to allow a slice of reflect.Value
+// elements to be sorted.
+type valuesSorter struct {
+ values []reflect.Value
+ strings []string // either nil or same len and values
+ cs *ConfigState
+}
+
+// newValuesSorter initializes a valuesSorter instance, which holds a set of
+// surrogate keys on which the data should be sorted. It uses flags in
+// ConfigState to decide if and how to populate those surrogate keys.
+func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface {
+ vs := &valuesSorter{values: values, cs: cs}
+ if canSortSimply(vs.values[0].Kind()) {
+ return vs
+ }
+ if !cs.DisableMethods {
+ vs.strings = make([]string, len(values))
+ for i := range vs.values {
+ b := bytes.Buffer{}
+ if !handleMethods(cs, &b, vs.values[i]) {
+ vs.strings = nil
+ break
+ }
+ vs.strings[i] = b.String()
+ }
+ }
+ if vs.strings == nil && cs.SpewKeys {
+ vs.strings = make([]string, len(values))
+ for i := range vs.values {
+ vs.strings[i] = Sprintf("%#v", vs.values[i].Interface())
+ }
+ }
+ return vs
+}
+
+// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted
+// directly, or whether it should be considered for sorting by surrogate keys
+// (if the ConfigState allows it).
+func canSortSimply(kind reflect.Kind) bool {
+ // This switch parallels valueSortLess, except for the default case.
+ switch kind {
+ case reflect.Bool:
+ return true
+ case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
+ return true
+ case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
+ return true
+ case reflect.Float32, reflect.Float64:
+ return true
+ case reflect.String:
+ return true
+ case reflect.Uintptr:
+ return true
+ case reflect.Array:
+ return true
+ }
+ return false
+}
+
+// Len returns the number of values in the slice. It is part of the
+// sort.Interface implementation.
+func (s *valuesSorter) Len() int {
+ return len(s.values)
+}
+
+// Swap swaps the values at the passed indices. It is part of the
+// sort.Interface implementation.
+func (s *valuesSorter) Swap(i, j int) {
+ s.values[i], s.values[j] = s.values[j], s.values[i]
+ if s.strings != nil {
+ s.strings[i], s.strings[j] = s.strings[j], s.strings[i]
+ }
+}
+
+// valueSortLess returns whether the first value should sort before the second
+// value. It is used by valueSorter.Less as part of the sort.Interface
+// implementation.
+func valueSortLess(a, b reflect.Value) bool {
+ switch a.Kind() {
+ case reflect.Bool:
+ return !a.Bool() && b.Bool()
+ case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
+ return a.Int() < b.Int()
+ case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
+ return a.Uint() < b.Uint()
+ case reflect.Float32, reflect.Float64:
+ return a.Float() < b.Float()
+ case reflect.String:
+ return a.String() < b.String()
+ case reflect.Uintptr:
+ return a.Uint() < b.Uint()
+ case reflect.Array:
+ // Compare the contents of both arrays.
+ l := a.Len()
+ for i := 0; i < l; i++ {
+ av := a.Index(i)
+ bv := b.Index(i)
+ if av.Interface() == bv.Interface() {
+ continue
+ }
+ return valueSortLess(av, bv)
+ }
+ }
+ return a.String() < b.String()
+}
+
+// Less returns whether the value at index i should sort before the
+// value at index j. It is part of the sort.Interface implementation.
+func (s *valuesSorter) Less(i, j int) bool {
+ if s.strings == nil {
+ return valueSortLess(s.values[i], s.values[j])
+ }
+ return s.strings[i] < s.strings[j]
+}
+
+// sortValues is a sort function that handles both native types and any type that
+// can be converted to error or Stringer. Other inputs are sorted according to
+// their Value.String() value to ensure display stability.
+func sortValues(values []reflect.Value, cs *ConfigState) {
+ if len(values) == 0 {
+ return
+ }
+ sort.Sort(newValuesSorter(values, cs))
+}
diff --git a/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go
new file mode 100644
index 0000000..2e3d22f
--- /dev/null
+++ b/vendor/github.com/davecgh/go-spew/spew/config.go
@@ -0,0 +1,306 @@
+/*
+ * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+package spew
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "os"
+)
+
+// ConfigState houses the configuration options used by spew to format and
+// display values. There is a global instance, Config, that is used to control
+// all top-level Formatter and Dump functionality. Each ConfigState instance
+// provides methods equivalent to the top-level functions.
+//
+// The zero value for ConfigState provides no indentation. You would typically
+// want to set it to a space or a tab.
+//
+// Alternatively, you can use NewDefaultConfig to get a ConfigState instance
+// with default settings. See the documentation of NewDefaultConfig for default
+// values.
+type ConfigState struct {
+ // Indent specifies the string to use for each indentation level. The
+ // global config instance that all top-level functions use set this to a
+ // single space by default. If you would like more indentation, you might
+ // set this to a tab with "\t" or perhaps two spaces with " ".
+ Indent string
+
+ // MaxDepth controls the maximum number of levels to descend into nested
+ // data structures. The default, 0, means there is no limit.
+ //
+ // NOTE: Circular data structures are properly detected, so it is not
+ // necessary to set this value unless you specifically want to limit deeply
+ // nested data structures.
+ MaxDepth int
+
+ // DisableMethods specifies whether or not error and Stringer interfaces are
+ // invoked for types that implement them.
+ DisableMethods bool
+
+ // DisablePointerMethods specifies whether or not to check for and invoke
+ // error and Stringer interfaces on types which only accept a pointer
+ // receiver when the current type is not a pointer.
+ //
+ // NOTE: This might be an unsafe action since calling one of these methods
+ // with a pointer receiver could technically mutate the value, however,
+ // in practice, types which choose to satisify an error or Stringer
+ // interface with a pointer receiver should not be mutating their state
+ // inside these interface methods. As a result, this option relies on
+ // access to the unsafe package, so it will not have any effect when
+ // running in environments without access to the unsafe package such as
+ // Google App Engine or with the "safe" build tag specified.
+ DisablePointerMethods bool
+
+ // DisablePointerAddresses specifies whether to disable the printing of
+ // pointer addresses. This is useful when diffing data structures in tests.
+ DisablePointerAddresses bool
+
+ // DisableCapacities specifies whether to disable the printing of capacities
+ // for arrays, slices, maps and channels. This is useful when diffing
+ // data structures in tests.
+ DisableCapacities bool
+
+ // ContinueOnMethod specifies whether or not recursion should continue once
+ // a custom error or Stringer interface is invoked. The default, false,
+ // means it will print the results of invoking the custom error or Stringer
+ // interface and return immediately instead of continuing to recurse into
+ // the internals of the data type.
+ //
+ // NOTE: This flag does not have any effect if method invocation is disabled
+ // via the DisableMethods or DisablePointerMethods options.
+ ContinueOnMethod bool
+
+ // SortKeys specifies map keys should be sorted before being printed. Use
+ // this to have a more deterministic, diffable output. Note that only
+ // native types (bool, int, uint, floats, uintptr and string) and types
+ // that support the error or Stringer interfaces (if methods are
+ // enabled) are supported, with other types sorted according to the
+ // reflect.Value.String() output which guarantees display stability.
+ SortKeys bool
+
+ // SpewKeys specifies that, as a last resort attempt, map keys should
+ // be spewed to strings and sorted by those strings. This is only
+ // considered if SortKeys is true.
+ SpewKeys bool
+}
+
+// Config is the active configuration of the top-level functions.
+// The configuration can be changed by modifying the contents of spew.Config.
+var Config = ConfigState{Indent: " "}
+
+// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were
+// passed with a Formatter interface returned by c.NewFormatter. It returns
+// the formatted string as a value that satisfies error. See NewFormatter
+// for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b))
+func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) {
+ return fmt.Errorf(format, c.convertArgs(a)...)
+}
+
+// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were
+// passed with a Formatter interface returned by c.NewFormatter. It returns
+// the number of bytes written and any write error encountered. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b))
+func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
+ return fmt.Fprint(w, c.convertArgs(a)...)
+}
+
+// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were
+// passed with a Formatter interface returned by c.NewFormatter. It returns
+// the number of bytes written and any write error encountered. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b))
+func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
+ return fmt.Fprintf(w, format, c.convertArgs(a)...)
+}
+
+// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it
+// passed with a Formatter interface returned by c.NewFormatter. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b))
+func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
+ return fmt.Fprintln(w, c.convertArgs(a)...)
+}
+
+// Print is a wrapper for fmt.Print that treats each argument as if it were
+// passed with a Formatter interface returned by c.NewFormatter. It returns
+// the number of bytes written and any write error encountered. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Print(c.NewFormatter(a), c.NewFormatter(b))
+func (c *ConfigState) Print(a ...interface{}) (n int, err error) {
+ return fmt.Print(c.convertArgs(a)...)
+}
+
+// Printf is a wrapper for fmt.Printf that treats each argument as if it were
+// passed with a Formatter interface returned by c.NewFormatter. It returns
+// the number of bytes written and any write error encountered. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b))
+func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) {
+ return fmt.Printf(format, c.convertArgs(a)...)
+}
+
+// Println is a wrapper for fmt.Println that treats each argument as if it were
+// passed with a Formatter interface returned by c.NewFormatter. It returns
+// the number of bytes written and any write error encountered. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Println(c.NewFormatter(a), c.NewFormatter(b))
+func (c *ConfigState) Println(a ...interface{}) (n int, err error) {
+ return fmt.Println(c.convertArgs(a)...)
+}
+
+// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were
+// passed with a Formatter interface returned by c.NewFormatter. It returns
+// the resulting string. See NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b))
+func (c *ConfigState) Sprint(a ...interface{}) string {
+ return fmt.Sprint(c.convertArgs(a)...)
+}
+
+// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were
+// passed with a Formatter interface returned by c.NewFormatter. It returns
+// the resulting string. See NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b))
+func (c *ConfigState) Sprintf(format string, a ...interface{}) string {
+ return fmt.Sprintf(format, c.convertArgs(a)...)
+}
+
+// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it
+// were passed with a Formatter interface returned by c.NewFormatter. It
+// returns the resulting string. See NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b))
+func (c *ConfigState) Sprintln(a ...interface{}) string {
+ return fmt.Sprintln(c.convertArgs(a)...)
+}
+
+/*
+NewFormatter returns a custom formatter that satisfies the fmt.Formatter
+interface. As a result, it integrates cleanly with standard fmt package
+printing functions. The formatter is useful for inline printing of smaller data
+types similar to the standard %v format specifier.
+
+The custom formatter only responds to the %v (most compact), %+v (adds pointer
+addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb
+combinations. Any other verbs such as %x and %q will be sent to the the
+standard fmt package for formatting. In addition, the custom formatter ignores
+the width and precision arguments (however they will still work on the format
+specifiers not handled by the custom formatter).
+
+Typically this function shouldn't be called directly. It is much easier to make
+use of the custom formatter by calling one of the convenience functions such as
+c.Printf, c.Println, or c.Printf.
+*/
+func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter {
+ return newFormatter(c, v)
+}
+
+// Fdump formats and displays the passed arguments to io.Writer w. It formats
+// exactly the same as Dump.
+func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) {
+ fdump(c, w, a...)
+}
+
+/*
+Dump displays the passed parameters to standard out with newlines, customizable
+indentation, and additional debug information such as complete types and all
+pointer addresses used to indirect to the final value. It provides the
+following features over the built-in printing facilities provided by the fmt
+package:
+
+ * Pointers are dereferenced and followed
+ * Circular data structures are detected and handled properly
+ * Custom Stringer/error interfaces are optionally invoked, including
+ on unexported types
+ * Custom types which only implement the Stringer/error interfaces via
+ a pointer receiver are optionally invoked when passing non-pointer
+ variables
+ * Byte arrays and slices are dumped like the hexdump -C command which
+ includes offsets, byte values in hex, and ASCII output
+
+The configuration options are controlled by modifying the public members
+of c. See ConfigState for options documentation.
+
+See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
+get the formatted result as a string.
+*/
+func (c *ConfigState) Dump(a ...interface{}) {
+ fdump(c, os.Stdout, a...)
+}
+
+// Sdump returns a string with the passed arguments formatted exactly the same
+// as Dump.
+func (c *ConfigState) Sdump(a ...interface{}) string {
+ var buf bytes.Buffer
+ fdump(c, &buf, a...)
+ return buf.String()
+}
+
+// convertArgs accepts a slice of arguments and returns a slice of the same
+// length with each argument converted to a spew Formatter interface using
+// the ConfigState associated with s.
+func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) {
+ formatters = make([]interface{}, len(args))
+ for index, arg := range args {
+ formatters[index] = newFormatter(c, arg)
+ }
+ return formatters
+}
+
+// NewDefaultConfig returns a ConfigState with the following default settings.
+//
+// Indent: " "
+// MaxDepth: 0
+// DisableMethods: false
+// DisablePointerMethods: false
+// ContinueOnMethod: false
+// SortKeys: false
+func NewDefaultConfig() *ConfigState {
+ return &ConfigState{Indent: " "}
+}
diff --git a/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/davecgh/go-spew/spew/doc.go
new file mode 100644
index 0000000..aacaac6
--- /dev/null
+++ b/vendor/github.com/davecgh/go-spew/spew/doc.go
@@ -0,0 +1,211 @@
+/*
+ * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+/*
+Package spew implements a deep pretty printer for Go data structures to aid in
+debugging.
+
+A quick overview of the additional features spew provides over the built-in
+printing facilities for Go data types are as follows:
+
+ * Pointers are dereferenced and followed
+ * Circular data structures are detected and handled properly
+ * Custom Stringer/error interfaces are optionally invoked, including
+ on unexported types
+ * Custom types which only implement the Stringer/error interfaces via
+ a pointer receiver are optionally invoked when passing non-pointer
+ variables
+ * Byte arrays and slices are dumped like the hexdump -C command which
+ includes offsets, byte values in hex, and ASCII output (only when using
+ Dump style)
+
+There are two different approaches spew allows for dumping Go data structures:
+
+ * Dump style which prints with newlines, customizable indentation,
+ and additional debug information such as types and all pointer addresses
+ used to indirect to the final value
+ * A custom Formatter interface that integrates cleanly with the standard fmt
+ package and replaces %v, %+v, %#v, and %#+v to provide inline printing
+ similar to the default %v while providing the additional functionality
+ outlined above and passing unsupported format verbs such as %x and %q
+ along to fmt
+
+Quick Start
+
+This section demonstrates how to quickly get started with spew. See the
+sections below for further details on formatting and configuration options.
+
+To dump a variable with full newlines, indentation, type, and pointer
+information use Dump, Fdump, or Sdump:
+ spew.Dump(myVar1, myVar2, ...)
+ spew.Fdump(someWriter, myVar1, myVar2, ...)
+ str := spew.Sdump(myVar1, myVar2, ...)
+
+Alternatively, if you would prefer to use format strings with a compacted inline
+printing style, use the convenience wrappers Printf, Fprintf, etc with
+%v (most compact), %+v (adds pointer addresses), %#v (adds types), or
+%#+v (adds types and pointer addresses):
+ spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
+ spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
+ spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
+ spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
+
+Configuration Options
+
+Configuration of spew is handled by fields in the ConfigState type. For
+convenience, all of the top-level functions use a global state available
+via the spew.Config global.
+
+It is also possible to create a ConfigState instance that provides methods
+equivalent to the top-level functions. This allows concurrent configuration
+options. See the ConfigState documentation for more details.
+
+The following configuration options are available:
+ * Indent
+ String to use for each indentation level for Dump functions.
+ It is a single space by default. A popular alternative is "\t".
+
+ * MaxDepth
+ Maximum number of levels to descend into nested data structures.
+ There is no limit by default.
+
+ * DisableMethods
+ Disables invocation of error and Stringer interface methods.
+ Method invocation is enabled by default.
+
+ * DisablePointerMethods
+ Disables invocation of error and Stringer interface methods on types
+ which only accept pointer receivers from non-pointer variables.
+ Pointer method invocation is enabled by default.
+
+ * DisablePointerAddresses
+ DisablePointerAddresses specifies whether to disable the printing of
+ pointer addresses. This is useful when diffing data structures in tests.
+
+ * DisableCapacities
+ DisableCapacities specifies whether to disable the printing of
+ capacities for arrays, slices, maps and channels. This is useful when
+ diffing data structures in tests.
+
+ * ContinueOnMethod
+ Enables recursion into types after invoking error and Stringer interface
+ methods. Recursion after method invocation is disabled by default.
+
+ * SortKeys
+ Specifies map keys should be sorted before being printed. Use
+ this to have a more deterministic, diffable output. Note that
+ only native types (bool, int, uint, floats, uintptr and string)
+ and types which implement error or Stringer interfaces are
+ supported with other types sorted according to the
+ reflect.Value.String() output which guarantees display
+ stability. Natural map order is used by default.
+
+ * SpewKeys
+ Specifies that, as a last resort attempt, map keys should be
+ spewed to strings and sorted by those strings. This is only
+ considered if SortKeys is true.
+
+Dump Usage
+
+Simply call spew.Dump with a list of variables you want to dump:
+
+ spew.Dump(myVar1, myVar2, ...)
+
+You may also call spew.Fdump if you would prefer to output to an arbitrary
+io.Writer. For example, to dump to standard error:
+
+ spew.Fdump(os.Stderr, myVar1, myVar2, ...)
+
+A third option is to call spew.Sdump to get the formatted output as a string:
+
+ str := spew.Sdump(myVar1, myVar2, ...)
+
+Sample Dump Output
+
+See the Dump example for details on the setup of the types and variables being
+shown here.
+
+ (main.Foo) {
+ unexportedField: (*main.Bar)(0xf84002e210)({
+ flag: (main.Flag) flagTwo,
+ data: (uintptr) <nil>
+ }),
+ ExportedField: (map[interface {}]interface {}) (len=1) {
+ (string) (len=3) "one": (bool) true
+ }
+ }
+
+Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C
+command as shown.
+ ([]uint8) (len=32 cap=32) {
+ 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
+ 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
+ 00000020 31 32 |12|
+ }
+
+Custom Formatter
+
+Spew provides a custom formatter that implements the fmt.Formatter interface
+so that it integrates cleanly with standard fmt package printing functions. The
+formatter is useful for inline printing of smaller data types similar to the
+standard %v format specifier.
+
+The custom formatter only responds to the %v (most compact), %+v (adds pointer
+addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb
+combinations. Any other verbs such as %x and %q will be sent to the the
+standard fmt package for formatting. In addition, the custom formatter ignores
+the width and precision arguments (however they will still work on the format
+specifiers not handled by the custom formatter).
+
+Custom Formatter Usage
+
+The simplest way to make use of the spew custom formatter is to call one of the
+convenience functions such as spew.Printf, spew.Println, or spew.Printf. The
+functions have syntax you are most likely already familiar with:
+
+ spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
+ spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
+ spew.Println(myVar, myVar2)
+ spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
+ spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
+
+See the Index for the full list convenience functions.
+
+Sample Formatter Output
+
+Double pointer to a uint8:
+ %v: <**>5
+ %+v: <**>(0xf8400420d0->0xf8400420c8)5
+ %#v: (**uint8)5
+ %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5
+
+Pointer to circular struct with a uint8 field and a pointer to itself:
+ %v: <*>{1 <*><shown>}
+ %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>}
+ %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>}
+ %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)<shown>}
+
+See the Printf example for details on the setup of variables being shown
+here.
+
+Errors
+
+Since it is possible for custom Stringer/error interfaces to panic, spew
+detects them and handles them internally by printing the panic information
+inline with the output. Since spew is intended to provide deep pretty printing
+capabilities on structures, it intentionally does not return any errors.
+*/
+package spew
diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go
new file mode 100644
index 0000000..df1d582
--- /dev/null
+++ b/vendor/github.com/davecgh/go-spew/spew/dump.go
@@ -0,0 +1,509 @@
+/*
+ * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+package spew
+
+import (
+ "bytes"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "os"
+ "reflect"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+var (
+ // uint8Type is a reflect.Type representing a uint8. It is used to
+ // convert cgo types to uint8 slices for hexdumping.
+ uint8Type = reflect.TypeOf(uint8(0))
+
+ // cCharRE is a regular expression that matches a cgo char.
+ // It is used to detect character arrays to hexdump them.
+ cCharRE = regexp.MustCompile("^.*\\._Ctype_char$")
+
+ // cUnsignedCharRE is a regular expression that matches a cgo unsigned
+ // char. It is used to detect unsigned character arrays to hexdump
+ // them.
+ cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$")
+
+ // cUint8tCharRE is a regular expression that matches a cgo uint8_t.
+ // It is used to detect uint8_t arrays to hexdump them.
+ cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$")
+)
+
+// dumpState contains information about the state of a dump operation.
+type dumpState struct {
+ w io.Writer
+ depth int
+ pointers map[uintptr]int
+ ignoreNextType bool
+ ignoreNextIndent bool
+ cs *ConfigState
+}
+
+// indent performs indentation according to the depth level and cs.Indent
+// option.
+func (d *dumpState) indent() {
+ if d.ignoreNextIndent {
+ d.ignoreNextIndent = false
+ return
+ }
+ d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth))
+}
+
+// unpackValue returns values inside of non-nil interfaces when possible.
+// This is useful for data types like structs, arrays, slices, and maps which
+// can contain varying types packed inside an interface.
+func (d *dumpState) unpackValue(v reflect.Value) reflect.Value {
+ if v.Kind() == reflect.Interface && !v.IsNil() {
+ v = v.Elem()
+ }
+ return v
+}
+
+// dumpPtr handles formatting of pointers by indirecting them as necessary.
+func (d *dumpState) dumpPtr(v reflect.Value) {
+ // Remove pointers at or below the current depth from map used to detect
+ // circular refs.
+ for k, depth := range d.pointers {
+ if depth >= d.depth {
+ delete(d.pointers, k)
+ }
+ }
+
+ // Keep list of all dereferenced pointers to show later.
+ pointerChain := make([]uintptr, 0)
+
+ // Figure out how many levels of indirection there are by dereferencing
+ // pointers and unpacking interfaces down the chain while detecting circular
+ // references.
+ nilFound := false
+ cycleFound := false
+ indirects := 0
+ ve := v
+ for ve.Kind() == reflect.Ptr {
+ if ve.IsNil() {
+ nilFound = true
+ break
+ }
+ indirects++
+ addr := ve.Pointer()
+ pointerChain = append(pointerChain, addr)
+ if pd, ok := d.pointers[addr]; ok && pd < d.depth {
+ cycleFound = true
+ indirects--
+ break
+ }
+ d.pointers[addr] = d.depth
+
+ ve = ve.Elem()
+ if ve.Kind() == reflect.Interface {
+ if ve.IsNil() {
+ nilFound = true
+ break
+ }
+ ve = ve.Elem()
+ }
+ }
+
+ // Display type information.
+ d.w.Write(openParenBytes)
+ d.w.Write(bytes.Repeat(asteriskBytes, indirects))
+ d.w.Write([]byte(ve.Type().String()))
+ d.w.Write(closeParenBytes)
+
+ // Display pointer information.
+ if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 {
+ d.w.Write(openParenBytes)
+ for i, addr := range pointerChain {
+ if i > 0 {
+ d.w.Write(pointerChainBytes)
+ }
+ printHexPtr(d.w, addr)
+ }
+ d.w.Write(closeParenBytes)
+ }
+
+ // Display dereferenced value.
+ d.w.Write(openParenBytes)
+ switch {
+ case nilFound == true:
+ d.w.Write(nilAngleBytes)
+
+ case cycleFound == true:
+ d.w.Write(circularBytes)
+
+ default:
+ d.ignoreNextType = true
+ d.dump(ve)
+ }
+ d.w.Write(closeParenBytes)
+}
+
+// dumpSlice handles formatting of arrays and slices. Byte (uint8 under
+// reflection) arrays and slices are dumped in hexdump -C fashion.
+func (d *dumpState) dumpSlice(v reflect.Value) {
+ // Determine whether this type should be hex dumped or not. Also,
+ // for types which should be hexdumped, try to use the underlying data
+ // first, then fall back to trying to convert them to a uint8 slice.
+ var buf []uint8
+ doConvert := false
+ doHexDump := false
+ numEntries := v.Len()
+ if numEntries > 0 {
+ vt := v.Index(0).Type()
+ vts := vt.String()
+ switch {
+ // C types that need to be converted.
+ case cCharRE.MatchString(vts):
+ fallthrough
+ case cUnsignedCharRE.MatchString(vts):
+ fallthrough
+ case cUint8tCharRE.MatchString(vts):
+ doConvert = true
+
+ // Try to use existing uint8 slices and fall back to converting
+ // and copying if that fails.
+ case vt.Kind() == reflect.Uint8:
+ // We need an addressable interface to convert the type
+ // to a byte slice. However, the reflect package won't
+ // give us an interface on certain things like
+ // unexported struct fields in order to enforce
+ // visibility rules. We use unsafe, when available, to
+ // bypass these restrictions since this package does not
+ // mutate the values.
+ vs := v
+ if !vs.CanInterface() || !vs.CanAddr() {
+ vs = unsafeReflectValue(vs)
+ }
+ if !UnsafeDisabled {
+ vs = vs.Slice(0, numEntries)
+
+ // Use the existing uint8 slice if it can be
+ // type asserted.
+ iface := vs.Interface()
+ if slice, ok := iface.([]uint8); ok {
+ buf = slice
+ doHexDump = true
+ break
+ }
+ }
+
+ // The underlying data needs to be converted if it can't
+ // be type asserted to a uint8 slice.
+ doConvert = true
+ }
+
+ // Copy and convert the underlying type if needed.
+ if doConvert && vt.ConvertibleTo(uint8Type) {
+ // Convert and copy each element into a uint8 byte
+ // slice.
+ buf = make([]uint8, numEntries)
+ for i := 0; i < numEntries; i++ {
+ vv := v.Index(i)
+ buf[i] = uint8(vv.Convert(uint8Type).Uint())
+ }
+ doHexDump = true
+ }
+ }
+
+ // Hexdump the entire slice as needed.
+ if doHexDump {
+ indent := strings.Repeat(d.cs.Indent, d.depth)
+ str := indent + hex.Dump(buf)
+ str = strings.Replace(str, "\n", "\n"+indent, -1)
+ str = strings.TrimRight(str, d.cs.Indent)
+ d.w.Write([]byte(str))
+ return
+ }
+
+ // Recursively call dump for each item.
+ for i := 0; i < numEntries; i++ {
+ d.dump(d.unpackValue(v.Index(i)))
+ if i < (numEntries - 1) {
+ d.w.Write(commaNewlineBytes)
+ } else {
+ d.w.Write(newlineBytes)
+ }
+ }
+}
+
+// dump is the main workhorse for dumping a value. It uses the passed reflect
+// value to figure out what kind of object we are dealing with and formats it
+// appropriately. It is a recursive function, however circular data structures
+// are detected and handled properly.
+func (d *dumpState) dump(v reflect.Value) {
+ // Handle invalid reflect values immediately.
+ kind := v.Kind()
+ if kind == reflect.Invalid {
+ d.w.Write(invalidAngleBytes)
+ return
+ }
+
+ // Handle pointers specially.
+ if kind == reflect.Ptr {
+ d.indent()
+ d.dumpPtr(v)
+ return
+ }
+
+ // Print type information unless already handled elsewhere.
+ if !d.ignoreNextType {
+ d.indent()
+ d.w.Write(openParenBytes)
+ d.w.Write([]byte(v.Type().String()))
+ d.w.Write(closeParenBytes)
+ d.w.Write(spaceBytes)
+ }
+ d.ignoreNextType = false
+
+ // Display length and capacity if the built-in len and cap functions
+ // work with the value's kind and the len/cap itself is non-zero.
+ valueLen, valueCap := 0, 0
+ switch v.Kind() {
+ case reflect.Array, reflect.Slice, reflect.Chan:
+ valueLen, valueCap = v.Len(), v.Cap()
+ case reflect.Map, reflect.String:
+ valueLen = v.Len()
+ }
+ if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 {
+ d.w.Write(openParenBytes)
+ if valueLen != 0 {
+ d.w.Write(lenEqualsBytes)
+ printInt(d.w, int64(valueLen), 10)
+ }
+ if !d.cs.DisableCapacities && valueCap != 0 {
+ if valueLen != 0 {
+ d.w.Write(spaceBytes)
+ }
+ d.w.Write(capEqualsBytes)
+ printInt(d.w, int64(valueCap), 10)
+ }
+ d.w.Write(closeParenBytes)
+ d.w.Write(spaceBytes)
+ }
+
+ // Call Stringer/error interfaces if they exist and the handle methods flag
+ // is enabled
+ if !d.cs.DisableMethods {
+ if (kind != reflect.Invalid) && (kind != reflect.Interface) {
+ if handled := handleMethods(d.cs, d.w, v); handled {
+ return
+ }
+ }
+ }
+
+ switch kind {
+ case reflect.Invalid:
+ // Do nothing. We should never get here since invalid has already
+ // been handled above.
+
+ case reflect.Bool:
+ printBool(d.w, v.Bool())
+
+ case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
+ printInt(d.w, v.Int(), 10)
+
+ case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
+ printUint(d.w, v.Uint(), 10)
+
+ case reflect.Float32:
+ printFloat(d.w, v.Float(), 32)
+
+ case reflect.Float64:
+ printFloat(d.w, v.Float(), 64)
+
+ case reflect.Complex64:
+ printComplex(d.w, v.Complex(), 32)
+
+ case reflect.Complex128:
+ printComplex(d.w, v.Complex(), 64)
+
+ case reflect.Slice:
+ if v.IsNil() {
+ d.w.Write(nilAngleBytes)
+ break
+ }
+ fallthrough
+
+ case reflect.Array:
+ d.w.Write(openBraceNewlineBytes)
+ d.depth++
+ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
+ d.indent()
+ d.w.Write(maxNewlineBytes)
+ } else {
+ d.dumpSlice(v)
+ }
+ d.depth--
+ d.indent()
+ d.w.Write(closeBraceBytes)
+
+ case reflect.String:
+ d.w.Write([]byte(strconv.Quote(v.String())))
+
+ case reflect.Interface:
+ // The only time we should get here is for nil interfaces due to
+ // unpackValue calls.
+ if v.IsNil() {
+ d.w.Write(nilAngleBytes)
+ }
+
+ case reflect.Ptr:
+ // Do nothing. We should never get here since pointers have already
+ // been handled above.
+
+ case reflect.Map:
+ // nil maps should be indicated as different than empty maps
+ if v.IsNil() {
+ d.w.Write(nilAngleBytes)
+ break
+ }
+
+ d.w.Write(openBraceNewlineBytes)
+ d.depth++
+ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
+ d.indent()
+ d.w.Write(maxNewlineBytes)
+ } else {
+ numEntries := v.Len()
+ keys := v.MapKeys()
+ if d.cs.SortKeys {
+ sortValues(keys, d.cs)
+ }
+ for i, key := range keys {
+ d.dump(d.unpackValue(key))
+ d.w.Write(colonSpaceBytes)
+ d.ignoreNextIndent = true
+ d.dump(d.unpackValue(v.MapIndex(key)))
+ if i < (numEntries - 1) {
+ d.w.Write(commaNewlineBytes)
+ } else {
+ d.w.Write(newlineBytes)
+ }
+ }
+ }
+ d.depth--
+ d.indent()
+ d.w.Write(closeBraceBytes)
+
+ case reflect.Struct:
+ d.w.Write(openBraceNewlineBytes)
+ d.depth++
+ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
+ d.indent()
+ d.w.Write(maxNewlineBytes)
+ } else {
+ vt := v.Type()
+ numFields := v.NumField()
+ for i := 0; i < numFields; i++ {
+ d.indent()
+ vtf := vt.Field(i)
+ d.w.Write([]byte(vtf.Name))
+ d.w.Write(colonSpaceBytes)
+ d.ignoreNextIndent = true
+ d.dump(d.unpackValue(v.Field(i)))
+ if i < (numFields - 1) {
+ d.w.Write(commaNewlineBytes)
+ } else {
+ d.w.Write(newlineBytes)
+ }
+ }
+ }
+ d.depth--
+ d.indent()
+ d.w.Write(closeBraceBytes)
+
+ case reflect.Uintptr:
+ printHexPtr(d.w, uintptr(v.Uint()))
+
+ case reflect.UnsafePointer, reflect.Chan, reflect.Func:
+ printHexPtr(d.w, v.Pointer())
+
+ // There were not any other types at the time this code was written, but
+ // fall back to letting the default fmt package handle it in case any new
+ // types are added.
+ default:
+ if v.CanInterface() {
+ fmt.Fprintf(d.w, "%v", v.Interface())
+ } else {
+ fmt.Fprintf(d.w, "%v", v.String())
+ }
+ }
+}
+
+// fdump is a helper function to consolidate the logic from the various public
+// methods which take varying writers and config states.
+func fdump(cs *ConfigState, w io.Writer, a ...interface{}) {
+ for _, arg := range a {
+ if arg == nil {
+ w.Write(interfaceBytes)
+ w.Write(spaceBytes)
+ w.Write(nilAngleBytes)
+ w.Write(newlineBytes)
+ continue
+ }
+
+ d := dumpState{w: w, cs: cs}
+ d.pointers = make(map[uintptr]int)
+ d.dump(reflect.ValueOf(arg))
+ d.w.Write(newlineBytes)
+ }
+}
+
+// Fdump formats and displays the passed arguments to io.Writer w. It formats
+// exactly the same as Dump.
+func Fdump(w io.Writer, a ...interface{}) {
+ fdump(&Config, w, a...)
+}
+
+// Sdump returns a string with the passed arguments formatted exactly the same
+// as Dump.
+func Sdump(a ...interface{}) string {
+ var buf bytes.Buffer
+ fdump(&Config, &buf, a...)
+ return buf.String()
+}
+
+/*
+Dump displays the passed parameters to standard out with newlines, customizable
+indentation, and additional debug information such as complete types and all
+pointer addresses used to indirect to the final value. It provides the
+following features over the built-in printing facilities provided by the fmt
+package:
+
+ * Pointers are dereferenced and followed
+ * Circular data structures are detected and handled properly
+ * Custom Stringer/error interfaces are optionally invoked, including
+ on unexported types
+ * Custom types which only implement the Stringer/error interfaces via
+ a pointer receiver are optionally invoked when passing non-pointer
+ variables
+ * Byte arrays and slices are dumped like the hexdump -C command which
+ includes offsets, byte values in hex, and ASCII output
+
+The configuration options are controlled by an exported package global,
+spew.Config. See ConfigState for options documentation.
+
+See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
+get the formatted result as a string.
+*/
+func Dump(a ...interface{}) {
+ fdump(&Config, os.Stdout, a...)
+}
diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go
new file mode 100644
index 0000000..c49875b
--- /dev/null
+++ b/vendor/github.com/davecgh/go-spew/spew/format.go
@@ -0,0 +1,419 @@
+/*
+ * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+package spew
+
+import (
+ "bytes"
+ "fmt"
+ "reflect"
+ "strconv"
+ "strings"
+)
+
+// supportedFlags is a list of all the character flags supported by fmt package.
+const supportedFlags = "0-+# "
+
+// formatState implements the fmt.Formatter interface and contains information
+// about the state of a formatting operation. The NewFormatter function can
+// be used to get a new Formatter which can be used directly as arguments
+// in standard fmt package printing calls.
+type formatState struct {
+ value interface{}
+ fs fmt.State
+ depth int
+ pointers map[uintptr]int
+ ignoreNextType bool
+ cs *ConfigState
+}
+
+// buildDefaultFormat recreates the original format string without precision
+// and width information to pass in to fmt.Sprintf in the case of an
+// unrecognized type. Unless new types are added to the language, this
+// function won't ever be called.
+func (f *formatState) buildDefaultFormat() (format string) {
+ buf := bytes.NewBuffer(percentBytes)
+
+ for _, flag := range supportedFlags {
+ if f.fs.Flag(int(flag)) {
+ buf.WriteRune(flag)
+ }
+ }
+
+ buf.WriteRune('v')
+
+ format = buf.String()
+ return format
+}
+
+// constructOrigFormat recreates the original format string including precision
+// and width information to pass along to the standard fmt package. This allows
+// automatic deferral of all format strings this package doesn't support.
+func (f *formatState) constructOrigFormat(verb rune) (format string) {
+ buf := bytes.NewBuffer(percentBytes)
+
+ for _, flag := range supportedFlags {
+ if f.fs.Flag(int(flag)) {
+ buf.WriteRune(flag)
+ }
+ }
+
+ if width, ok := f.fs.Width(); ok {
+ buf.WriteString(strconv.Itoa(width))
+ }
+
+ if precision, ok := f.fs.Precision(); ok {
+ buf.Write(precisionBytes)
+ buf.WriteString(strconv.Itoa(precision))
+ }
+
+ buf.WriteRune(verb)
+
+ format = buf.String()
+ return format
+}
+
+// unpackValue returns values inside of non-nil interfaces when possible and
+// ensures that types for values which have been unpacked from an interface
+// are displayed when the show types flag is also set.
+// This is useful for data types like structs, arrays, slices, and maps which
+// can contain varying types packed inside an interface.
+func (f *formatState) unpackValue(v reflect.Value) reflect.Value {
+ if v.Kind() == reflect.Interface {
+ f.ignoreNextType = false
+ if !v.IsNil() {
+ v = v.Elem()
+ }
+ }
+ return v
+}
+
+// formatPtr handles formatting of pointers by indirecting them as necessary.
+func (f *formatState) formatPtr(v reflect.Value) {
+ // Display nil if top level pointer is nil.
+ showTypes := f.fs.Flag('#')
+ if v.IsNil() && (!showTypes || f.ignoreNextType) {
+ f.fs.Write(nilAngleBytes)
+ return
+ }
+
+ // Remove pointers at or below the current depth from map used to detect
+ // circular refs.
+ for k, depth := range f.pointers {
+ if depth >= f.depth {
+ delete(f.pointers, k)
+ }
+ }
+
+ // Keep list of all dereferenced pointers to possibly show later.
+ pointerChain := make([]uintptr, 0)
+
+ // Figure out how many levels of indirection there are by derferencing
+ // pointers and unpacking interfaces down the chain while detecting circular
+ // references.
+ nilFound := false
+ cycleFound := false
+ indirects := 0
+ ve := v
+ for ve.Kind() == reflect.Ptr {
+ if ve.IsNil() {
+ nilFound = true
+ break
+ }
+ indirects++
+ addr := ve.Pointer()
+ pointerChain = append(pointerChain, addr)
+ if pd, ok := f.pointers[addr]; ok && pd < f.depth {
+ cycleFound = true
+ indirects--
+ break
+ }
+ f.pointers[addr] = f.depth
+
+ ve = ve.Elem()
+ if ve.Kind() == reflect.Interface {
+ if ve.IsNil() {
+ nilFound = true
+ break
+ }
+ ve = ve.Elem()
+ }
+ }
+
+ // Display type or indirection level depending on flags.
+ if showTypes && !f.ignoreNextType {
+ f.fs.Write(openParenBytes)
+ f.fs.Write(bytes.Repeat(asteriskBytes, indirects))
+ f.fs.Write([]byte(ve.Type().String()))
+ f.fs.Write(closeParenBytes)
+ } else {
+ if nilFound || cycleFound {
+ indirects += strings.Count(ve.Type().String(), "*")
+ }
+ f.fs.Write(openAngleBytes)
+ f.fs.Write([]byte(strings.Repeat("*", indirects)))
+ f.fs.Write(closeAngleBytes)
+ }
+
+ // Display pointer information depending on flags.
+ if f.fs.Flag('+') && (len(pointerChain) > 0) {
+ f.fs.Write(openParenBytes)
+ for i, addr := range pointerChain {
+ if i > 0 {
+ f.fs.Write(pointerChainBytes)
+ }
+ printHexPtr(f.fs, addr)
+ }
+ f.fs.Write(closeParenBytes)
+ }
+
+ // Display dereferenced value.
+ switch {
+ case nilFound == true:
+ f.fs.Write(nilAngleBytes)
+
+ case cycleFound == true:
+ f.fs.Write(circularShortBytes)
+
+ default:
+ f.ignoreNextType = true
+ f.format(ve)
+ }
+}
+
+// format is the main workhorse for providing the Formatter interface. It
+// uses the passed reflect value to figure out what kind of object we are
+// dealing with and formats it appropriately. It is a recursive function,
+// however circular data structures are detected and handled properly.
+func (f *formatState) format(v reflect.Value) {
+ // Handle invalid reflect values immediately.
+ kind := v.Kind()
+ if kind == reflect.Invalid {
+ f.fs.Write(invalidAngleBytes)
+ return
+ }
+
+ // Handle pointers specially.
+ if kind == reflect.Ptr {
+ f.formatPtr(v)
+ return
+ }
+
+ // Print type information unless already handled elsewhere.
+ if !f.ignoreNextType && f.fs.Flag('#') {
+ f.fs.Write(openParenBytes)
+ f.fs.Write([]byte(v.Type().String()))
+ f.fs.Write(closeParenBytes)
+ }
+ f.ignoreNextType = false
+
+ // Call Stringer/error interfaces if they exist and the handle methods
+ // flag is enabled.
+ if !f.cs.DisableMethods {
+ if (kind != reflect.Invalid) && (kind != reflect.Interface) {
+ if handled := handleMethods(f.cs, f.fs, v); handled {
+ return
+ }
+ }
+ }
+
+ switch kind {
+ case reflect.Invalid:
+ // Do nothing. We should never get here since invalid has already
+ // been handled above.
+
+ case reflect.Bool:
+ printBool(f.fs, v.Bool())
+
+ case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
+ printInt(f.fs, v.Int(), 10)
+
+ case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
+ printUint(f.fs, v.Uint(), 10)
+
+ case reflect.Float32:
+ printFloat(f.fs, v.Float(), 32)
+
+ case reflect.Float64:
+ printFloat(f.fs, v.Float(), 64)
+
+ case reflect.Complex64:
+ printComplex(f.fs, v.Complex(), 32)
+
+ case reflect.Complex128:
+ printComplex(f.fs, v.Complex(), 64)
+
+ case reflect.Slice:
+ if v.IsNil() {
+ f.fs.Write(nilAngleBytes)
+ break
+ }
+ fallthrough
+
+ case reflect.Array:
+ f.fs.Write(openBracketBytes)
+ f.depth++
+ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
+ f.fs.Write(maxShortBytes)
+ } else {
+ numEntries := v.Len()
+ for i := 0; i < numEntries; i++ {
+ if i > 0 {
+ f.fs.Write(spaceBytes)
+ }
+ f.ignoreNextType = true
+ f.format(f.unpackValue(v.Index(i)))
+ }
+ }
+ f.depth--
+ f.fs.Write(closeBracketBytes)
+
+ case reflect.String:
+ f.fs.Write([]byte(v.String()))
+
+ case reflect.Interface:
+ // The only time we should get here is for nil interfaces due to
+ // unpackValue calls.
+ if v.IsNil() {
+ f.fs.Write(nilAngleBytes)
+ }
+
+ case reflect.Ptr:
+ // Do nothing. We should never get here since pointers have already
+ // been handled above.
+
+ case reflect.Map:
+ // nil maps should be indicated as different than empty maps
+ if v.IsNil() {
+ f.fs.Write(nilAngleBytes)
+ break
+ }
+
+ f.fs.Write(openMapBytes)
+ f.depth++
+ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
+ f.fs.Write(maxShortBytes)
+ } else {
+ keys := v.MapKeys()
+ if f.cs.SortKeys {
+ sortValues(keys, f.cs)
+ }
+ for i, key := range keys {
+ if i > 0 {
+ f.fs.Write(spaceBytes)
+ }
+ f.ignoreNextType = true
+ f.format(f.unpackValue(key))
+ f.fs.Write(colonBytes)
+ f.ignoreNextType = true
+ f.format(f.unpackValue(v.MapIndex(key)))
+ }
+ }
+ f.depth--
+ f.fs.Write(closeMapBytes)
+
+ case reflect.Struct:
+ numFields := v.NumField()
+ f.fs.Write(openBraceBytes)
+ f.depth++
+ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
+ f.fs.Write(maxShortBytes)
+ } else {
+ vt := v.Type()
+ for i := 0; i < numFields; i++ {
+ if i > 0 {
+ f.fs.Write(spaceBytes)
+ }
+ vtf := vt.Field(i)
+ if f.fs.Flag('+') || f.fs.Flag('#') {
+ f.fs.Write([]byte(vtf.Name))
+ f.fs.Write(colonBytes)
+ }
+ f.format(f.unpackValue(v.Field(i)))
+ }
+ }
+ f.depth--
+ f.fs.Write(closeBraceBytes)
+
+ case reflect.Uintptr:
+ printHexPtr(f.fs, uintptr(v.Uint()))
+
+ case reflect.UnsafePointer, reflect.Chan, reflect.Func:
+ printHexPtr(f.fs, v.Pointer())
+
+ // There were not any other types at the time this code was written, but
+ // fall back to letting the default fmt package handle it if any get added.
+ default:
+ format := f.buildDefaultFormat()
+ if v.CanInterface() {
+ fmt.Fprintf(f.fs, format, v.Interface())
+ } else {
+ fmt.Fprintf(f.fs, format, v.String())
+ }
+ }
+}
+
+// Format satisfies the fmt.Formatter interface. See NewFormatter for usage
+// details.
+func (f *formatState) Format(fs fmt.State, verb rune) {
+ f.fs = fs
+
+ // Use standard formatting for verbs that are not v.
+ if verb != 'v' {
+ format := f.constructOrigFormat(verb)
+ fmt.Fprintf(fs, format, f.value)
+ return
+ }
+
+ if f.value == nil {
+ if fs.Flag('#') {
+ fs.Write(interfaceBytes)
+ }
+ fs.Write(nilAngleBytes)
+ return
+ }
+
+ f.format(reflect.ValueOf(f.value))
+}
+
+// newFormatter is a helper function to consolidate the logic from the various
+// public methods which take varying config states.
+func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter {
+ fs := &formatState{value: v, cs: cs}
+ fs.pointers = make(map[uintptr]int)
+ return fs
+}
+
+/*
+NewFormatter returns a custom formatter that satisfies the fmt.Formatter
+interface. As a result, it integrates cleanly with standard fmt package
+printing functions. The formatter is useful for inline printing of smaller data
+types similar to the standard %v format specifier.
+
+The custom formatter only responds to the %v (most compact), %+v (adds pointer
+addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb
+combinations. Any other verbs such as %x and %q will be sent to the the
+standard fmt package for formatting. In addition, the custom formatter ignores
+the width and precision arguments (however they will still work on the format
+specifiers not handled by the custom formatter).
+
+Typically this function shouldn't be called directly. It is much easier to make
+use of the custom formatter by calling one of the convenience functions such as
+Printf, Println, or Fprintf.
+*/
+func NewFormatter(v interface{}) fmt.Formatter {
+ return newFormatter(&Config, v)
+}
diff --git a/vendor/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/davecgh/go-spew/spew/spew.go
new file mode 100644
index 0000000..32c0e33
--- /dev/null
+++ b/vendor/github.com/davecgh/go-spew/spew/spew.go
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+package spew
+
+import (
+ "fmt"
+ "io"
+)
+
+// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were
+// passed with a default Formatter interface returned by NewFormatter. It
+// returns the formatted string as a value that satisfies error. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b))
+func Errorf(format string, a ...interface{}) (err error) {
+ return fmt.Errorf(format, convertArgs(a)...)
+}
+
+// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were
+// passed with a default Formatter interface returned by NewFormatter. It
+// returns the number of bytes written and any write error encountered. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b))
+func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
+ return fmt.Fprint(w, convertArgs(a)...)
+}
+
+// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were
+// passed with a default Formatter interface returned by NewFormatter. It
+// returns the number of bytes written and any write error encountered. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b))
+func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
+ return fmt.Fprintf(w, format, convertArgs(a)...)
+}
+
+// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it
+// passed with a default Formatter interface returned by NewFormatter. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b))
+func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
+ return fmt.Fprintln(w, convertArgs(a)...)
+}
+
+// Print is a wrapper for fmt.Print that treats each argument as if it were
+// passed with a default Formatter interface returned by NewFormatter. It
+// returns the number of bytes written and any write error encountered. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b))
+func Print(a ...interface{}) (n int, err error) {
+ return fmt.Print(convertArgs(a)...)
+}
+
+// Printf is a wrapper for fmt.Printf that treats each argument as if it were
+// passed with a default Formatter interface returned by NewFormatter. It
+// returns the number of bytes written and any write error encountered. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b))
+func Printf(format string, a ...interface{}) (n int, err error) {
+ return fmt.Printf(format, convertArgs(a)...)
+}
+
+// Println is a wrapper for fmt.Println that treats each argument as if it were
+// passed with a default Formatter interface returned by NewFormatter. It
+// returns the number of bytes written and any write error encountered. See
+// NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b))
+func Println(a ...interface{}) (n int, err error) {
+ return fmt.Println(convertArgs(a)...)
+}
+
+// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were
+// passed with a default Formatter interface returned by NewFormatter. It
+// returns the resulting string. See NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b))
+func Sprint(a ...interface{}) string {
+ return fmt.Sprint(convertArgs(a)...)
+}
+
+// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were
+// passed with a default Formatter interface returned by NewFormatter. It
+// returns the resulting string. See NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b))
+func Sprintf(format string, a ...interface{}) string {
+ return fmt.Sprintf(format, convertArgs(a)...)
+}
+
+// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it
+// were passed with a default Formatter interface returned by NewFormatter. It
+// returns the resulting string. See NewFormatter for formatting details.
+//
+// This function is shorthand for the following syntax:
+//
+// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b))
+func Sprintln(a ...interface{}) string {
+ return fmt.Sprintln(convertArgs(a)...)
+}
+
+// convertArgs accepts a slice of arguments and returns a slice of the same
+// length with each argument converted to a default spew Formatter interface.
+func convertArgs(args []interface{}) (formatters []interface{}) {
+ formatters = make([]interface{}, len(args))
+ for index, arg := range args {
+ formatters[index] = NewFormatter(arg)
+ }
+ return formatters
+}
diff --git a/vendor/github.com/deckarep/golang-set/LICENSE b/vendor/github.com/deckarep/golang-set/LICENSE
new file mode 100644
index 0000000..b5768f8
--- /dev/null
+++ b/vendor/github.com/deckarep/golang-set/LICENSE
@@ -0,0 +1,22 @@
+Open Source Initiative OSI - The MIT License (MIT):Licensing
+
+The MIT License (MIT)
+Copyright (c) 2013 Ralph Caraveo (deckarep@gmail.com)
+
+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/deckarep/golang-set/README.md b/vendor/github.com/deckarep/golang-set/README.md
new file mode 100644
index 0000000..744b184
--- /dev/null
+++ b/vendor/github.com/deckarep/golang-set/README.md
@@ -0,0 +1,94 @@
+[![Build Status](https://travis-ci.org/deckarep/golang-set.png?branch=master)](https://travis-ci.org/deckarep/golang-set)
+[![GoDoc](https://godoc.org/github.com/deckarep/golang-set?status.png)](http://godoc.org/github.com/deckarep/golang-set)
+
+## golang-set
+
+
+The missing set collection for the Go language. Until Go has sets built-in...use this.
+
+Coming from Python one of the things I miss is the superbly wonderful set collection. This is my attempt to mimic the primary features of the set from Python.
+You can of course argue that there is no need for a set in Go, otherwise the creators would have added one to the standard library. To those I say simply ignore this repository
+and carry-on and to the rest that find this useful please contribute in helping me make it better by:
+
+* Helping to make more idiomatic improvements to the code.
+* Helping to increase the performance of it. ~~(So far, no attempt has been made, but since it uses a map internally, I expect it to be mostly performant.)~~
+* Helping to make the unit-tests more robust and kick-ass.
+* Helping to fill in the [documentation.](http://godoc.org/github.com/deckarep/golang-set)
+* Simply offering feedback and suggestions. (Positive, constructive feedback is appreciated.)
+
+I have to give some credit for helping seed the idea with this post on [stackoverflow.](http://programmers.stackexchange.com/questions/177428/sets-data-structure-in-golang)
+
+*Update* - as of 3/9/2014, you can use a compile-time generic version of this package in the [gen](http://clipperhouse.github.io/gen/) framework. This framework allows you to use the golang-set in a completely generic and type-safe way by allowing you to generate a supporting .go file based on your custom types.
+
+## Features (as of 9/22/2014)
+
+* a CartesionProduct() method has been added with unit-tests: [Read more about the cartesion product](http://en.wikipedia.org/wiki/Cartesian_product)
+
+## Features (as of 9/15/2014)
+
+* a PowerSet() method has been added with unit-tests: [Read more about the Power set](http://en.wikipedia.org/wiki/Power_set)
+
+## Features (as of 4/22/2014)
+
+* One common interface to both implementations
+* Two set implementations to choose from
+ * a thread-safe implementation designed for concurrent use
+ * a non-thread-safe implementation designed for performance
+* 75 benchmarks for both implementations
+* 35 unit tests for both implementations
+* 14 concurrent tests for the thread-safe implementation
+
+
+
+Please see the unit test file for additional usage examples. The Python set documentation will also do a better job than I can of explaining how a set typically [works.](http://docs.python.org/2/library/sets.html) Please keep in mind
+however that the Python set is a built-in type and supports additional features and syntax that make it awesome.
+
+## Examples but not exhaustive:
+
+```go
+requiredClasses := mapset.NewSet()
+requiredClasses.Add("Cooking")
+requiredClasses.Add("English")
+requiredClasses.Add("Math")
+requiredClasses.Add("Biology")
+
+scienceSlice := []interface{}{"Biology", "Chemistry"}
+scienceClasses := mapset.NewSetFromSlice(scienceSlice)
+
+electiveClasses := mapset.NewSet()
+electiveClasses.Add("Welding")
+electiveClasses.Add("Music")
+electiveClasses.Add("Automotive")
+
+bonusClasses := mapset.NewSet()
+bonusClasses.Add("Go Programming")
+bonusClasses.Add("Python Programming")
+
+//Show me all the available classes I can take
+allClasses := requiredClasses.Union(scienceClasses).Union(electiveClasses).Union(bonusClasses)
+fmt.Println(allClasses) //Set{Cooking, English, Math, Chemistry, Welding, Biology, Music, Automotive, Go Programming, Python Programming}
+
+
+//Is cooking considered a science class?
+fmt.Println(scienceClasses.Contains("Cooking")) //false
+
+//Show me all classes that are not science classes, since I hate science.
+fmt.Println(allClasses.Difference(scienceClasses)) //Set{Music, Automotive, Go Programming, Python Programming, Cooking, English, Math, Welding}
+
+//Which science classes are also required classes?
+fmt.Println(scienceClasses.Intersect(requiredClasses)) //Set{Biology}
+
+//How many bonus classes do you offer?
+fmt.Println(bonusClasses.Cardinality()) //2
+
+//Do you have the following classes? Welding, Automotive and English?
+fmt.Println(allClasses.IsSuperset(mapset.NewSetFromSlice([]interface{}{"Welding", "Automotive", "English"}))) //true
+```
+
+Thanks!
+
+-Ralph
+
+[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/deckarep/golang-set/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
+
+[![Analytics](https://ga-beacon.appspot.com/UA-42584447-2/deckarep/golang-set)](https://github.com/igrigorik/ga-beacon)
diff --git a/vendor/github.com/deckarep/golang-set/set.go b/vendor/github.com/deckarep/golang-set/set.go
new file mode 100644
index 0000000..eccba70
--- /dev/null
+++ b/vendor/github.com/deckarep/golang-set/set.go
@@ -0,0 +1,168 @@
+/*
+Open Source Initiative OSI - The MIT License (MIT):Licensing
+
+The MIT License (MIT)
+Copyright (c) 2013 Ralph Caraveo (deckarep@gmail.com)
+
+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.
+*/
+
+// Package mapset implements a simple and generic set collection.
+// Items stored within it are unordered and unique. It supports
+// typical set operations: membership testing, intersection, union,
+// difference, symmetric difference and cloning.
+//
+// Package mapset provides two implementations. The default
+// implementation is safe for concurrent access. There is a non-threadsafe
+// implementation which is slightly more performant.
+package mapset
+
+type Set interface {
+ // Adds an element to the set. Returns whether
+ // the item was added.
+ Add(i interface{}) bool
+
+ // Returns the number of elements in the set.
+ Cardinality() int
+
+ // Removes all elements from the set, leaving
+ // the emtpy set.
+ Clear()
+
+ // Returns a clone of the set using the same
+ // implementation, duplicating all keys.
+ Clone() Set
+
+ // Returns whether the given items
+ // are all in the set.
+ Contains(i ...interface{}) bool
+
+ // Returns the difference between this set
+ // and other. The returned set will contain
+ // all elements of this set that are not also
+ // elements of other.
+ //
+ // Note that the argument to Difference
+ // must be of the same type as the receiver
+ // of the method. Otherwise, Difference will
+ // panic.
+ Difference(other Set) Set
+
+ // Determines if two sets are equal to each
+ // other. If they have the same cardinality
+ // and contain the same elements, they are
+ // considered equal. The order in which
+ // the elements were added is irrelevant.
+ //
+ // Note that the argument to Equal must be
+ // of the same type as the receiver of the
+ // method. Otherwise, Equal will panic.
+ Equal(other Set) bool
+
+ // Returns a new set containing only the elements
+ // that exist only in both sets.
+ //
+ // Note that the argument to Intersect
+ // must be of the same type as the receiver
+ // of the method. Otherwise, Intersect will
+ // panic.
+ Intersect(other Set) Set
+
+ // Determines if every element in the other set
+ // is in this set.
+ //
+ // Note that the argument to IsSubset
+ // must be of the same type as the receiver
+ // of the method. Otherwise, IsSubset will
+ // panic.
+ IsSubset(other Set) bool
+
+ // Determines if every element in this set is in
+ // the other set.
+ //
+ // Note that the argument to IsSuperset
+ // must be of the same type as the receiver
+ // of the method. Otherwise, IsSuperset will
+ // panic.
+ IsSuperset(other Set) bool
+
+ // Returns a channel of elements that you can
+ // range over.
+ Iter() <-chan interface{}
+
+ // Remove a single element from the set.
+ Remove(i interface{})
+
+ // Provides a convenient string representation
+ // of the current state of the set.
+ String() string
+
+ // Returns a new set with all elements which are
+ // in either this set or the other set but not in both.
+ //
+ // Note that the argument to SymmetricDifference
+ // must be of the same type as the receiver
+ // of the method. Otherwise, SymmetricDifference
+ // will panic.
+ SymmetricDifference(other Set) Set
+
+ // Returns a new set with all elements in both sets.
+ //
+ // Note that the argument to Union must be of the
+ // same type as the receiver of the method.
+ // Otherwise, IsSuperset will panic.
+ Union(other Set) Set
+
+ // Returns all subsets of a given set (Power Set).
+ PowerSet() Set
+
+ // Returns the Cartesian Product of two sets.
+ CartesianProduct(other Set) Set
+
+ // Returns the members of the set as a slice.
+ ToSlice() []interface{}
+}
+
+// Creates and returns a reference to an empty set.
+func NewSet() Set {
+ set := newThreadSafeSet()
+ return &set
+}
+
+// Creates and returns a reference to a set from an existing slice
+func NewSetFromSlice(s []interface{}) Set {
+ a := NewSet()
+ for _, item := range s {
+ a.Add(item)
+ }
+ return a
+}
+
+func NewThreadUnsafeSet() Set {
+ set := newThreadUnsafeSet()
+ return &set
+}
+
+func NewThreadUnsafeSetFromSlice(s []interface{}) Set {
+ a := NewThreadUnsafeSet()
+ for _, item := range s {
+ a.Add(item)
+ }
+ return a
+}
diff --git a/vendor/github.com/deckarep/golang-set/threadsafe.go b/vendor/github.com/deckarep/golang-set/threadsafe.go
new file mode 100644
index 0000000..9dca94a
--- /dev/null
+++ b/vendor/github.com/deckarep/golang-set/threadsafe.go
@@ -0,0 +1,204 @@
+/*
+Open Source Initiative OSI - The MIT License (MIT):Licensing
+
+The MIT License (MIT)
+Copyright (c) 2013 Ralph Caraveo (deckarep@gmail.com)
+
+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.
+*/
+
+package mapset
+
+import "sync"
+
+type threadSafeSet struct {
+ s threadUnsafeSet
+ sync.RWMutex
+}
+
+func newThreadSafeSet() threadSafeSet {
+ return threadSafeSet{s: newThreadUnsafeSet()}
+}
+
+func (set *threadSafeSet) Add(i interface{}) bool {
+ set.Lock()
+ ret := set.s.Add(i)
+ set.Unlock()
+ return ret
+}
+
+func (set *threadSafeSet) Contains(i ...interface{}) bool {
+ set.RLock()
+ ret := set.s.Contains(i...)
+ set.RUnlock()
+ return ret
+}
+
+func (set *threadSafeSet) IsSubset(other Set) bool {
+ o := other.(*threadSafeSet)
+
+ set.RLock()
+ o.RLock()
+
+ ret := set.s.IsSubset(&o.s)
+ set.RUnlock()
+ o.RUnlock()
+ return ret
+}
+
+func (set *threadSafeSet) IsSuperset(other Set) bool {
+ return other.IsSubset(set)
+}
+
+func (set *threadSafeSet) Union(other Set) Set {
+ o := other.(*threadSafeSet)
+
+ set.RLock()
+ o.RLock()
+
+ unsafeUnion := set.s.Union(&o.s).(*threadUnsafeSet)
+ ret := &threadSafeSet{s: *unsafeUnion}
+ set.RUnlock()
+ o.RUnlock()
+ return ret
+}
+
+func (set *threadSafeSet) Intersect(other Set) Set {
+ o := other.(*threadSafeSet)
+
+ set.RLock()
+ o.RLock()
+
+ unsafeIntersection := set.s.Intersect(&o.s).(*threadUnsafeSet)
+ ret := &threadSafeSet{s: *unsafeIntersection}
+ set.RUnlock()
+ o.RUnlock()
+ return ret
+}
+
+func (set *threadSafeSet) Difference(other Set) Set {
+ o := other.(*threadSafeSet)
+
+ set.RLock()
+ o.RLock()
+
+ unsafeDifference := set.s.Difference(&o.s).(*threadUnsafeSet)
+ ret := &threadSafeSet{s: *unsafeDifference}
+ set.RUnlock()
+ o.RUnlock()
+ return ret
+}
+
+func (set *threadSafeSet) SymmetricDifference(other Set) Set {
+ o := other.(*threadSafeSet)
+
+ unsafeDifference := set.s.SymmetricDifference(&o.s).(*threadUnsafeSet)
+ return &threadSafeSet{s: *unsafeDifference}
+}
+
+func (set *threadSafeSet) Clear() {
+ set.Lock()
+ set.s = newThreadUnsafeSet()
+ set.Unlock()
+}
+
+func (set *threadSafeSet) Remove(i interface{}) {
+ set.Lock()
+ delete(set.s, i)
+ set.Unlock()
+}
+
+func (set *threadSafeSet) Cardinality() int {
+ set.RLock()
+ defer set.RUnlock()
+ return len(set.s)
+}
+
+func (set *threadSafeSet) Iter() <-chan interface{} {
+ ch := make(chan interface{})
+ go func() {
+ set.RLock()
+
+ for elem := range set.s {
+ ch <- elem
+ }
+ close(ch)
+ set.RUnlock()
+ }()
+
+ return ch
+}
+
+func (set *threadSafeSet) Equal(other Set) bool {
+ o := other.(*threadSafeSet)
+
+ set.RLock()
+ o.RLock()
+
+ ret := set.s.Equal(&o.s)
+ set.RUnlock()
+ o.RUnlock()
+ return ret
+}
+
+func (set *threadSafeSet) Clone() Set {
+ set.RLock()
+
+ unsafeClone := set.s.Clone().(*threadUnsafeSet)
+ ret := &threadSafeSet{s: *unsafeClone}
+ set.RUnlock()
+ return ret
+}
+
+func (set *threadSafeSet) String() string {
+ set.RLock()
+ ret := set.s.String()
+ set.RUnlock()
+ return ret
+}
+
+func (set *threadSafeSet) PowerSet() Set {
+ set.RLock()
+ ret := set.s.PowerSet()
+ set.RUnlock()
+ return ret
+}
+
+func (set *threadSafeSet) CartesianProduct(other Set) Set {
+ o := other.(*threadSafeSet)
+
+ set.RLock()
+ o.RLock()
+
+ unsafeCartProduct := set.s.CartesianProduct(&o.s).(*threadUnsafeSet)
+ ret := &threadSafeSet{s: *unsafeCartProduct}
+ set.RUnlock()
+ o.RUnlock()
+ return ret
+}
+
+func (set *threadSafeSet) ToSlice() []interface{} {
+ set.RLock()
+ keys := make([]interface{}, 0, set.Cardinality())
+ for elem := range set.s {
+ keys = append(keys, elem)
+ }
+ set.RUnlock()
+ return keys
+}
diff --git a/vendor/github.com/deckarep/golang-set/threadunsafe.go b/vendor/github.com/deckarep/golang-set/threadunsafe.go
new file mode 100644
index 0000000..124521e
--- /dev/null
+++ b/vendor/github.com/deckarep/golang-set/threadunsafe.go
@@ -0,0 +1,246 @@
+/*
+Open Source Initiative OSI - The MIT License (MIT):Licensing
+
+The MIT License (MIT)
+Copyright (c) 2013 Ralph Caraveo (deckarep@gmail.com)
+
+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.
+*/
+
+package mapset
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+)
+
+type threadUnsafeSet map[interface{}]struct{}
+
+type orderedPair struct {
+ first interface{}
+ second interface{}
+}
+
+func newThreadUnsafeSet() threadUnsafeSet {
+ return make(threadUnsafeSet)
+}
+
+func (pair *orderedPair) Equal(other orderedPair) bool {
+ if pair.first == other.first &&
+ pair.second == other.second {
+ return true
+ }
+
+ return false
+}
+
+func (set *threadUnsafeSet) Add(i interface{}) bool {
+ _, found := (*set)[i]
+ (*set)[i] = struct{}{}
+ return !found //False if it existed already
+}
+
+func (set *threadUnsafeSet) Contains(i ...interface{}) bool {
+ for _, val := range i {
+ if _, ok := (*set)[val]; !ok {
+ return false
+ }
+ }
+ return true
+}
+
+func (set *threadUnsafeSet) IsSubset(other Set) bool {
+ _ = other.(*threadUnsafeSet)
+ for elem := range *set {
+ if !other.Contains(elem) {
+ return false
+ }
+ }
+ return true
+}
+
+func (set *threadUnsafeSet) IsSuperset(other Set) bool {
+ return other.IsSubset(set)
+}
+
+func (set *threadUnsafeSet) Union(other Set) Set {
+ o := other.(*threadUnsafeSet)
+
+ unionedSet := newThreadUnsafeSet()
+
+ for elem := range *set {
+ unionedSet.Add(elem)
+ }
+ for elem := range *o {
+ unionedSet.Add(elem)
+ }
+ return &unionedSet
+}
+
+func (set *threadUnsafeSet) Intersect(other Set) Set {
+ o := other.(*threadUnsafeSet)
+
+ intersection := newThreadUnsafeSet()
+ // loop over smaller set
+ if set.Cardinality() < other.Cardinality() {
+ for elem := range *set {
+ if other.Contains(elem) {
+ intersection.Add(elem)
+ }
+ }
+ } else {
+ for elem := range *o {
+ if set.Contains(elem) {
+ intersection.Add(elem)
+ }
+ }
+ }
+ return &intersection
+}
+
+func (set *threadUnsafeSet) Difference(other Set) Set {
+ _ = other.(*threadUnsafeSet)
+
+ difference := newThreadUnsafeSet()
+ for elem := range *set {
+ if !other.Contains(elem) {
+ difference.Add(elem)
+ }
+ }
+ return &difference
+}
+
+func (set *threadUnsafeSet) SymmetricDifference(other Set) Set {
+ _ = other.(*threadUnsafeSet)
+
+ aDiff := set.Difference(other)
+ bDiff := other.Difference(set)
+ return aDiff.Union(bDiff)
+}
+
+func (set *threadUnsafeSet) Clear() {
+ *set = newThreadUnsafeSet()
+}
+
+func (set *threadUnsafeSet) Remove(i interface{}) {
+ delete(*set, i)
+}
+
+func (set *threadUnsafeSet) Cardinality() int {
+ return len(*set)
+}
+
+func (set *threadUnsafeSet) Iter() <-chan interface{} {
+ ch := make(chan interface{})
+ go func() {
+ for elem := range *set {
+ ch <- elem
+ }
+ close(ch)
+ }()
+
+ return ch
+}
+
+func (set *threadUnsafeSet) Equal(other Set) bool {
+ _ = other.(*threadUnsafeSet)
+
+ if set.Cardinality() != other.Cardinality() {
+ return false
+ }
+ for elem := range *set {
+ if !other.Contains(elem) {
+ return false
+ }
+ }
+ return true
+}
+
+func (set *threadUnsafeSet) Clone() Set {
+ clonedSet := newThreadUnsafeSet()
+ for elem := range *set {
+ clonedSet.Add(elem)
+ }
+ return &clonedSet
+}
+
+func (set *threadUnsafeSet) String() string {
+ items := make([]string, 0, len(*set))
+
+ for elem := range *set {
+ items = append(items, fmt.Sprintf("%v", elem))
+ }
+ return fmt.Sprintf("Set{%s}", strings.Join(items, ", "))
+}
+
+func (pair orderedPair) String() string {
+ return fmt.Sprintf("(%v, %v)", pair.first, pair.second)
+}
+
+func (set *threadUnsafeSet) PowerSet() Set {
+ powSet := NewThreadUnsafeSet()
+ nullset := newThreadUnsafeSet()
+ powSet.Add(&nullset)
+
+ for es := range *set {
+ u := newThreadUnsafeSet()
+ j := powSet.Iter()
+ for er := range j {
+ p := newThreadUnsafeSet()
+ if reflect.TypeOf(er).Name() == "" {
+ k := er.(*threadUnsafeSet)
+ for ek := range *(k) {
+ p.Add(ek)
+ }
+ } else {
+ p.Add(er)
+ }
+ p.Add(es)
+ u.Add(&p)
+ }
+
+ powSet = powSet.Union(&u)
+ }
+
+ return powSet
+}
+
+func (set *threadUnsafeSet) CartesianProduct(other Set) Set {
+ o := other.(*threadUnsafeSet)
+ cartProduct := NewThreadUnsafeSet()
+
+ for i := range *set {
+ for j := range *o {
+ elem := orderedPair{first: i, second: j}
+ cartProduct.Add(elem)
+ }
+ }
+
+ return cartProduct
+}
+
+func (set *threadUnsafeSet) ToSlice() []interface{} {
+ keys := make([]interface{}, 0, set.Cardinality())
+ for elem := range *set {
+ keys = append(keys, elem)
+ }
+
+ return keys
+}
diff --git a/vendor/github.com/docker/cli/LICENSE b/vendor/github.com/docker/cli/LICENSE
new file mode 100644
index 0000000..9c8e20a
--- /dev/null
+++ b/vendor/github.com/docker/cli/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2013-2017 Docker, Inc.
+
+ 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
+
+ https://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/docker/cli/NOTICE b/vendor/github.com/docker/cli/NOTICE
new file mode 100644
index 0000000..0c74e15
--- /dev/null
+++ b/vendor/github.com/docker/cli/NOTICE
@@ -0,0 +1,19 @@
+Docker
+Copyright 2012-2017 Docker, Inc.
+
+This product includes software developed at Docker, Inc. (https://www.docker.com).
+
+This product contains software (https://github.com/kr/pty) developed
+by Keith Rarick, licensed under the MIT License.
+
+The following is courtesy of our legal counsel:
+
+
+Use and transfer of Docker may be subject to certain restrictions by the
+United States and other governments.
+It is your responsibility to ensure that your use and/or transfer does not
+violate applicable laws.
+
+For more information, please see https://www.bis.doc.gov
+
+See also https://www.apache.org/dev/crypto.html and/or seek legal counsel.
diff --git a/vendor/github.com/docker/cli/README.md b/vendor/github.com/docker/cli/README.md
new file mode 100644
index 0000000..340556d
--- /dev/null
+++ b/vendor/github.com/docker/cli/README.md
@@ -0,0 +1,63 @@
+[![build status](https://circleci.com/gh/docker/cli.svg?style=shield)](https://circleci.com/gh/docker/cli/tree/master)
+
+docker/cli
+==========
+
+This repository is the home of the cli used in the Docker CE and
+Docker EE products.
+
+Development
+===========
+
+`docker/cli` is developed using Docker.
+
+Build a linux binary:
+
+```
+$ make -f docker.Makefile binary
+```
+
+Build binaries for all supported platforms:
+
+```
+$ make -f docker.Makefile cross
+```
+
+Run all linting:
+
+```
+$ make -f docker.Makefile lint
+```
+
+### In-container development environment
+
+Start an interactive development environment:
+
+```
+$ make -f docker.Makefile shell
+```
+
+In the development environment you can run many tasks, including build binaries:
+
+```
+$ make binary
+```
+
+Legal
+=====
+*Brought to you courtesy of our legal counsel. For more context,
+please see the [NOTICE](https://github.com/docker/cli/blob/master/NOTICE) document in this repo.*
+
+Use and transfer of Docker may be subject to certain restrictions by the
+United States and other governments.
+
+It is your responsibility to ensure that your use and/or transfer does not
+violate applicable laws.
+
+For more information, please see https://www.bis.doc.gov
+
+Licensing
+=========
+docker/cli is licensed under the Apache License, Version 2.0. See
+[LICENSE](https://github.com/docker/docker/blob/master/LICENSE) for the full
+license text.
diff --git a/vendor/github.com/docker/cli/VERSION b/vendor/github.com/docker/cli/VERSION
new file mode 100644
index 0000000..3e9257a
--- /dev/null
+++ b/vendor/github.com/docker/cli/VERSION
@@ -0,0 +1 @@
+17.07.0-dev
diff --git a/vendor/github.com/docker/cli/cli/cobra.go b/vendor/github.com/docker/cli/cli/cobra.go
new file mode 100644
index 0000000..114f1b7
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/cobra.go
@@ -0,0 +1,150 @@
+package cli
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/docker/pkg/term"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+)
+
+// SetupRootCommand sets default usage, help, and error handling for the
+// root command.
+func SetupRootCommand(rootCmd *cobra.Command) {
+ cobra.AddTemplateFunc("hasSubCommands", hasSubCommands)
+ cobra.AddTemplateFunc("hasManagementSubCommands", hasManagementSubCommands)
+ cobra.AddTemplateFunc("operationSubCommands", operationSubCommands)
+ cobra.AddTemplateFunc("managementSubCommands", managementSubCommands)
+ cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages)
+
+ rootCmd.SetUsageTemplate(usageTemplate)
+ rootCmd.SetHelpTemplate(helpTemplate)
+ rootCmd.SetFlagErrorFunc(FlagErrorFunc)
+ rootCmd.SetHelpCommand(helpCommand)
+
+ rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
+ rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help")
+}
+
+// FlagErrorFunc prints an error message which matches the format of the
+// docker/cli/cli error messages
+func FlagErrorFunc(cmd *cobra.Command, err error) error {
+ if err == nil {
+ return nil
+ }
+
+ usage := ""
+ if cmd.HasSubCommands() {
+ usage = "\n\n" + cmd.UsageString()
+ }
+ return StatusError{
+ Status: fmt.Sprintf("%s\nSee '%s --help'.%s", err, cmd.CommandPath(), usage),
+ StatusCode: 125,
+ }
+}
+
+var helpCommand = &cobra.Command{
+ Use: "help [command]",
+ Short: "Help about the command",
+ PersistentPreRun: func(cmd *cobra.Command, args []string) {},
+ PersistentPostRun: func(cmd *cobra.Command, args []string) {},
+ RunE: func(c *cobra.Command, args []string) error {
+ cmd, args, e := c.Root().Find(args)
+ if cmd == nil || e != nil || len(args) > 0 {
+ return errors.Errorf("unknown help topic: %v", strings.Join(args, " "))
+ }
+
+ helpFunc := cmd.HelpFunc()
+ helpFunc(cmd, args)
+ return nil
+ },
+}
+
+func hasSubCommands(cmd *cobra.Command) bool {
+ return len(operationSubCommands(cmd)) > 0
+}
+
+func hasManagementSubCommands(cmd *cobra.Command) bool {
+ return len(managementSubCommands(cmd)) > 0
+}
+
+func operationSubCommands(cmd *cobra.Command) []*cobra.Command {
+ cmds := []*cobra.Command{}
+ for _, sub := range cmd.Commands() {
+ if sub.IsAvailableCommand() && !sub.HasSubCommands() {
+ cmds = append(cmds, sub)
+ }
+ }
+ return cmds
+}
+
+func wrappedFlagUsages(cmd *cobra.Command) string {
+ width := 80
+ if ws, err := term.GetWinsize(0); err == nil {
+ width = int(ws.Width)
+ }
+ return cmd.Flags().FlagUsagesWrapped(width - 1)
+}
+
+func managementSubCommands(cmd *cobra.Command) []*cobra.Command {
+ cmds := []*cobra.Command{}
+ for _, sub := range cmd.Commands() {
+ if sub.IsAvailableCommand() && sub.HasSubCommands() {
+ cmds = append(cmds, sub)
+ }
+ }
+ return cmds
+}
+
+var usageTemplate = `Usage:
+
+{{- if not .HasSubCommands}} {{.UseLine}}{{end}}
+{{- if .HasSubCommands}} {{ .CommandPath}} COMMAND{{end}}
+
+{{ .Short | trim }}
+
+{{- if gt .Aliases 0}}
+
+Aliases:
+ {{.NameAndAliases}}
+
+{{- end}}
+{{- if .HasExample}}
+
+Examples:
+{{ .Example }}
+
+{{- end}}
+{{- if .HasFlags}}
+
+Options:
+{{ wrappedFlagUsages . | trimRightSpace}}
+
+{{- end}}
+{{- if hasManagementSubCommands . }}
+
+Management Commands:
+
+{{- range managementSubCommands . }}
+ {{rpad .Name .NamePadding }} {{.Short}}
+{{- end}}
+
+{{- end}}
+{{- if hasSubCommands .}}
+
+Commands:
+
+{{- range operationSubCommands . }}
+ {{rpad .Name .NamePadding }} {{.Short}}
+{{- end}}
+{{- end}}
+
+{{- if .HasSubCommands }}
+
+Run '{{.CommandPath}} COMMAND --help' for more information on a command.
+{{- end}}
+`
+
+var helpTemplate = `
+{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
diff --git a/vendor/github.com/docker/cli/cli/command/cli.go b/vendor/github.com/docker/cli/cli/command/cli.go
new file mode 100644
index 0000000..e56c7a7
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/cli.go
@@ -0,0 +1,299 @@
+package command
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "runtime"
+
+ "github.com/docker/cli/cli"
+ cliconfig "github.com/docker/cli/cli/config"
+ "github.com/docker/cli/cli/config/configfile"
+ "github.com/docker/cli/cli/config/credentials"
+ cliflags "github.com/docker/cli/cli/flags"
+ dopts "github.com/docker/cli/opts"
+ "github.com/docker/docker/api"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/client"
+ "github.com/docker/go-connections/sockets"
+ "github.com/docker/go-connections/tlsconfig"
+ "github.com/docker/notary/passphrase"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+// Streams is an interface which exposes the standard input and output streams
+type Streams interface {
+ In() *InStream
+ Out() *OutStream
+ Err() io.Writer
+}
+
+// Cli represents the docker command line client.
+type Cli interface {
+ Client() client.APIClient
+ Out() *OutStream
+ Err() io.Writer
+ In() *InStream
+ SetIn(in *InStream)
+ ConfigFile() *configfile.ConfigFile
+ CredentialsStore(serverAddress string) credentials.Store
+}
+
+// DockerCli is an instance the docker command line client.
+// Instances of the client can be returned from NewDockerCli.
+type DockerCli struct {
+ configFile *configfile.ConfigFile
+ in *InStream
+ out *OutStream
+ err io.Writer
+ client client.APIClient
+ defaultVersion string
+ server ServerInfo
+}
+
+// DefaultVersion returns api.defaultVersion or DOCKER_API_VERSION if specified.
+func (cli *DockerCli) DefaultVersion() string {
+ return cli.defaultVersion
+}
+
+// Client returns the APIClient
+func (cli *DockerCli) Client() client.APIClient {
+ return cli.client
+}
+
+// Out returns the writer used for stdout
+func (cli *DockerCli) Out() *OutStream {
+ return cli.out
+}
+
+// Err returns the writer used for stderr
+func (cli *DockerCli) Err() io.Writer {
+ return cli.err
+}
+
+// SetIn sets the reader used for stdin
+func (cli *DockerCli) SetIn(in *InStream) {
+ cli.in = in
+}
+
+// In returns the reader used for stdin
+func (cli *DockerCli) In() *InStream {
+ return cli.in
+}
+
+// ShowHelp shows the command help.
+func ShowHelp(err io.Writer) func(*cobra.Command, []string) error {
+ return func(cmd *cobra.Command, args []string) error {
+ cmd.SetOutput(err)
+ cmd.HelpFunc()(cmd, args)
+ return nil
+ }
+}
+
+// ConfigFile returns the ConfigFile
+func (cli *DockerCli) ConfigFile() *configfile.ConfigFile {
+ return cli.configFile
+}
+
+// ServerInfo returns the server version details for the host this client is
+// connected to
+func (cli *DockerCli) ServerInfo() ServerInfo {
+ return cli.server
+}
+
+// GetAllCredentials returns all of the credentials stored in all of the
+// configured credential stores.
+func (cli *DockerCli) GetAllCredentials() (map[string]types.AuthConfig, error) {
+ auths := make(map[string]types.AuthConfig)
+ for registry := range cli.configFile.CredentialHelpers {
+ helper := cli.CredentialsStore(registry)
+ newAuths, err := helper.GetAll()
+ if err != nil {
+ return nil, err
+ }
+ addAll(auths, newAuths)
+ }
+ defaultStore := cli.CredentialsStore("")
+ newAuths, err := defaultStore.GetAll()
+ if err != nil {
+ return nil, err
+ }
+ addAll(auths, newAuths)
+ return auths, nil
+}
+
+func addAll(to, from map[string]types.AuthConfig) {
+ for reg, ac := range from {
+ to[reg] = ac
+ }
+}
+
+// CredentialsStore returns a new credentials store based
+// on the settings provided in the configuration file. Empty string returns
+// the default credential store.
+func (cli *DockerCli) CredentialsStore(serverAddress string) credentials.Store {
+ if helper := getConfiguredCredentialStore(cli.configFile, serverAddress); helper != "" {
+ return credentials.NewNativeStore(cli.configFile, helper)
+ }
+ return credentials.NewFileStore(cli.configFile)
+}
+
+// getConfiguredCredentialStore returns the credential helper configured for the
+// given registry, the default credsStore, or the empty string if neither are
+// configured.
+func getConfiguredCredentialStore(c *configfile.ConfigFile, serverAddress string) string {
+ if c.CredentialHelpers != nil && serverAddress != "" {
+ if helper, exists := c.CredentialHelpers[serverAddress]; exists {
+ return helper
+ }
+ }
+ return c.CredentialsStore
+}
+
+// Initialize the dockerCli runs initialization that must happen after command
+// line flags are parsed.
+func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions) error {
+ cli.configFile = LoadDefaultConfigFile(cli.err)
+
+ var err error
+ cli.client, err = NewAPIClientFromFlags(opts.Common, cli.configFile)
+ if tlsconfig.IsErrEncryptedKey(err) {
+ var (
+ passwd string
+ giveup bool
+ )
+ passRetriever := passphrase.PromptRetrieverWithInOut(cli.In(), cli.Out(), nil)
+
+ for attempts := 0; tlsconfig.IsErrEncryptedKey(err); attempts++ {
+ // some code and comments borrowed from notary/trustmanager/keystore.go
+ passwd, giveup, err = passRetriever("private", "encrypted TLS private", false, attempts)
+ // Check if the passphrase retriever got an error or if it is telling us to give up
+ if giveup || err != nil {
+ return errors.Wrap(err, "private key is encrypted, but could not get passphrase")
+ }
+
+ opts.Common.TLSOptions.Passphrase = passwd
+ cli.client, err = NewAPIClientFromFlags(opts.Common, cli.configFile)
+ }
+ }
+
+ if err != nil {
+ return err
+ }
+
+ cli.defaultVersion = cli.client.ClientVersion()
+
+ if ping, err := cli.client.Ping(context.Background()); err == nil {
+ cli.server = ServerInfo{
+ HasExperimental: ping.Experimental,
+ OSType: ping.OSType,
+ }
+
+ cli.client.NegotiateAPIVersionPing(ping)
+ } else {
+ // Default to true if we fail to connect to daemon
+ cli.server = ServerInfo{HasExperimental: true}
+ }
+
+ return nil
+}
+
+// ServerInfo stores details about the supported features and platform of the
+// server
+type ServerInfo struct {
+ HasExperimental bool
+ OSType string
+}
+
+// NewDockerCli returns a DockerCli instance with IO output and error streams set by in, out and err.
+func NewDockerCli(in io.ReadCloser, out, err io.Writer) *DockerCli {
+ return &DockerCli{in: NewInStream(in), out: NewOutStream(out), err: err}
+}
+
+// LoadDefaultConfigFile attempts to load the default config file and returns
+// an initialized ConfigFile struct if none is found.
+func LoadDefaultConfigFile(err io.Writer) *configfile.ConfigFile {
+ configFile, e := cliconfig.Load(cliconfig.Dir())
+ if e != nil {
+ fmt.Fprintf(err, "WARNING: Error loading config file:%v\n", e)
+ }
+ if !configFile.ContainsAuth() {
+ credentials.DetectDefaultStore(configFile)
+ }
+ return configFile
+}
+
+// NewAPIClientFromFlags creates a new APIClient from command line flags
+func NewAPIClientFromFlags(opts *cliflags.CommonOptions, configFile *configfile.ConfigFile) (client.APIClient, error) {
+ host, err := getServerHost(opts.Hosts, opts.TLSOptions)
+ if err != nil {
+ return &client.Client{}, err
+ }
+
+ customHeaders := configFile.HTTPHeaders
+ if customHeaders == nil {
+ customHeaders = map[string]string{}
+ }
+ customHeaders["User-Agent"] = UserAgent()
+
+ verStr := api.DefaultVersion
+ if tmpStr := os.Getenv("DOCKER_API_VERSION"); tmpStr != "" {
+ verStr = tmpStr
+ }
+
+ httpClient, err := newHTTPClient(host, opts.TLSOptions)
+ if err != nil {
+ return &client.Client{}, err
+ }
+
+ return client.NewClient(host, verStr, httpClient, customHeaders)
+}
+
+func getServerHost(hosts []string, tlsOptions *tlsconfig.Options) (host string, err error) {
+ switch len(hosts) {
+ case 0:
+ host = os.Getenv("DOCKER_HOST")
+ case 1:
+ host = hosts[0]
+ default:
+ return "", errors.New("Please specify only one -H")
+ }
+
+ host, err = dopts.ParseHost(tlsOptions != nil, host)
+ return
+}
+
+func newHTTPClient(host string, tlsOptions *tlsconfig.Options) (*http.Client, error) {
+ if tlsOptions == nil {
+ // let the api client configure the default transport.
+ return nil, nil
+ }
+ opts := *tlsOptions
+ opts.ExclusiveRootPools = true
+ config, err := tlsconfig.Client(opts)
+ if err != nil {
+ return nil, err
+ }
+ tr := &http.Transport{
+ TLSClientConfig: config,
+ }
+ proto, addr, _, err := client.ParseHost(host)
+ if err != nil {
+ return nil, err
+ }
+
+ sockets.ConfigureTransport(tr, proto, addr)
+
+ return &http.Client{
+ Transport: tr,
+ CheckRedirect: client.CheckRedirect,
+ }, nil
+}
+
+// UserAgent returns the user agent string used for making API requests
+func UserAgent() string {
+ return "Docker-Client/" + cli.Version + " (" + runtime.GOOS + ")"
+}
diff --git a/vendor/github.com/docker/cli/cli/command/commands/commands.go b/vendor/github.com/docker/cli/cli/command/commands/commands.go
new file mode 100644
index 0000000..9f29dac
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/commands/commands.go
@@ -0,0 +1,92 @@
+package commands
+
+import (
+ "os"
+
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/container"
+ "github.com/docker/cli/cli/command/image"
+ "github.com/docker/cli/cli/command/network"
+ "github.com/docker/cli/cli/command/registry"
+ "github.com/docker/cli/cli/command/system"
+ "github.com/docker/cli/cli/command/volume"
+ "github.com/spf13/cobra"
+)
+
+// AddCommands adds all the commands from cli/command to the root command
+func AddCommands(cmd *cobra.Command, dockerCli *command.DockerCli) {
+ cmd.AddCommand(
+ // container
+ container.NewContainerCommand(dockerCli),
+ container.NewRunCommand(dockerCli),
+
+ // image
+ image.NewImageCommand(dockerCli),
+ image.NewBuildCommand(dockerCli),
+
+ // network
+ network.NewNetworkCommand(dockerCli),
+
+ // registry
+ registry.NewLoginCommand(dockerCli),
+ registry.NewLogoutCommand(dockerCli),
+ registry.NewSearchCommand(dockerCli),
+
+ // system
+ system.NewSystemCommand(dockerCli),
+ system.NewVersionCommand(dockerCli),
+
+ // volume
+ volume.NewVolumeCommand(dockerCli),
+
+ // legacy commands may be hidden
+ hide(system.NewEventsCommand(dockerCli)),
+ hide(system.NewInfoCommand(dockerCli)),
+ hide(system.NewInspectCommand(dockerCli)),
+ hide(container.NewAttachCommand(dockerCli)),
+ hide(container.NewCommitCommand(dockerCli)),
+ hide(container.NewCopyCommand(dockerCli)),
+ hide(container.NewCreateCommand(dockerCli)),
+ hide(container.NewDiffCommand(dockerCli)),
+ hide(container.NewExecCommand(dockerCli)),
+ hide(container.NewExportCommand(dockerCli)),
+ hide(container.NewKillCommand(dockerCli)),
+ hide(container.NewLogsCommand(dockerCli)),
+ hide(container.NewPauseCommand(dockerCli)),
+ hide(container.NewPortCommand(dockerCli)),
+ hide(container.NewPsCommand(dockerCli)),
+ hide(container.NewRenameCommand(dockerCli)),
+ hide(container.NewRestartCommand(dockerCli)),
+ hide(container.NewRmCommand(dockerCli)),
+ hide(container.NewStartCommand(dockerCli)),
+ hide(container.NewStatsCommand(dockerCli)),
+ hide(container.NewStopCommand(dockerCli)),
+ hide(container.NewTopCommand(dockerCli)),
+ hide(container.NewUnpauseCommand(dockerCli)),
+ hide(container.NewUpdateCommand(dockerCli)),
+ hide(container.NewWaitCommand(dockerCli)),
+ hide(image.NewHistoryCommand(dockerCli)),
+ hide(image.NewImagesCommand(dockerCli)),
+ hide(image.NewImportCommand(dockerCli)),
+ hide(image.NewLoadCommand(dockerCli)),
+ hide(image.NewPullCommand(dockerCli)),
+ hide(image.NewPushCommand(dockerCli)),
+ hide(image.NewRemoveCommand(dockerCli)),
+ hide(image.NewSaveCommand(dockerCli)),
+ hide(image.NewTagCommand(dockerCli)),
+ )
+
+}
+
+func hide(cmd *cobra.Command) *cobra.Command {
+ // If the environment variable with name "DOCKER_HIDE_LEGACY_COMMANDS" is not empty,
+ // these legacy commands (such as `docker ps`, `docker exec`, etc)
+ // will not be shown in output console.
+ if os.Getenv("DOCKER_HIDE_LEGACY_COMMANDS") == "" {
+ return cmd
+ }
+ cmdCopy := *cmd
+ cmdCopy.Hidden = true
+ cmdCopy.Aliases = []string{}
+ return &cmdCopy
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/attach.go b/vendor/github.com/docker/cli/cli/command/container/attach.go
new file mode 100644
index 0000000..dce6432
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/attach.go
@@ -0,0 +1,164 @@
+package container
+
+import (
+ "io"
+ "net/http/httputil"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/client"
+ "github.com/docker/docker/pkg/signal"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type attachOptions struct {
+ noStdin bool
+ proxy bool
+ detachKeys string
+
+ container string
+}
+
+func inspectContainerAndCheckState(ctx context.Context, cli client.APIClient, args string) (*types.ContainerJSON, error) {
+ c, err := cli.ContainerInspect(ctx, args)
+ if err != nil {
+ return nil, err
+ }
+ if !c.State.Running {
+ return nil, errors.New("You cannot attach to a stopped container, start it first")
+ }
+ if c.State.Paused {
+ return nil, errors.New("You cannot attach to a paused container, unpause it first")
+ }
+ if c.State.Restarting {
+ return nil, errors.New("You cannot attach to a restarting container, wait until it is running")
+ }
+
+ return &c, nil
+}
+
+// NewAttachCommand creates a new cobra.Command for `docker attach`
+func NewAttachCommand(dockerCli command.Cli) *cobra.Command {
+ var opts attachOptions
+
+ cmd := &cobra.Command{
+ Use: "attach [OPTIONS] CONTAINER",
+ Short: "Attach local standard input, output, and error streams to a running container",
+ Args: cli.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.container = args[0]
+ return runAttach(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVar(&opts.noStdin, "no-stdin", false, "Do not attach STDIN")
+ flags.BoolVar(&opts.proxy, "sig-proxy", true, "Proxy all received signals to the process")
+ flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container")
+ return cmd
+}
+
+func runAttach(dockerCli command.Cli, opts *attachOptions) error {
+ ctx := context.Background()
+ client := dockerCli.Client()
+
+ c, err := inspectContainerAndCheckState(ctx, client, opts.container)
+ if err != nil {
+ return err
+ }
+
+ if err := dockerCli.In().CheckTty(!opts.noStdin, c.Config.Tty); err != nil {
+ return err
+ }
+
+ if opts.detachKeys != "" {
+ dockerCli.ConfigFile().DetachKeys = opts.detachKeys
+ }
+
+ options := types.ContainerAttachOptions{
+ Stream: true,
+ Stdin: !opts.noStdin && c.Config.OpenStdin,
+ Stdout: true,
+ Stderr: true,
+ DetachKeys: dockerCli.ConfigFile().DetachKeys,
+ }
+
+ var in io.ReadCloser
+ if options.Stdin {
+ in = dockerCli.In()
+ }
+
+ if opts.proxy && !c.Config.Tty {
+ sigc := ForwardAllSignals(ctx, dockerCli, opts.container)
+ defer signal.StopCatch(sigc)
+ }
+
+ resp, errAttach := client.ContainerAttach(ctx, opts.container, options)
+ if errAttach != nil && errAttach != httputil.ErrPersistEOF {
+ // ContainerAttach returns an ErrPersistEOF (connection closed)
+ // means server met an error and put it in Hijacked connection
+ // keep the error and read detailed error message from hijacked connection later
+ return errAttach
+ }
+ defer resp.Close()
+
+ // If use docker attach command to attach to a stop container, it will return
+ // "You cannot attach to a stopped container" error, it's ok, but when
+ // attach to a running container, it(docker attach) use inspect to check
+ // the container's state, if it pass the state check on the client side,
+ // and then the container is stopped, docker attach command still attach to
+ // the container and not exit.
+ //
+ // Recheck the container's state to avoid attach block.
+ _, err = inspectContainerAndCheckState(ctx, client, opts.container)
+ if err != nil {
+ return err
+ }
+
+ if c.Config.Tty && dockerCli.Out().IsTerminal() {
+ height, width := dockerCli.Out().GetTtySize()
+ // To handle the case where a user repeatedly attaches/detaches without resizing their
+ // terminal, the only way to get the shell prompt to display for attaches 2+ is to artificially
+ // resize it, then go back to normal. Without this, every attach after the first will
+ // require the user to manually resize or hit enter.
+ resizeTtyTo(ctx, client, opts.container, height+1, width+1, false)
+
+ // After the above resizing occurs, the call to MonitorTtySize below will handle resetting back
+ // to the actual size.
+ if err := MonitorTtySize(ctx, dockerCli, opts.container, false); err != nil {
+ logrus.Debugf("Error monitoring TTY size: %s", err)
+ }
+ }
+
+ streamer := hijackedIOStreamer{
+ streams: dockerCli,
+ inputStream: in,
+ outputStream: dockerCli.Out(),
+ errorStream: dockerCli.Err(),
+ resp: resp,
+ tty: c.Config.Tty,
+ detachKeys: options.DetachKeys,
+ }
+
+ if err := streamer.stream(ctx); err != nil {
+ return err
+ }
+
+ if errAttach != nil {
+ return errAttach
+ }
+
+ _, status, err := getExitCode(ctx, dockerCli, opts.container)
+ if err != nil {
+ return err
+ }
+ if status != 0 {
+ return cli.StatusError{StatusCode: status}
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/cmd.go b/vendor/github.com/docker/cli/cli/command/container/cmd.go
new file mode 100644
index 0000000..82500be
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/cmd.go
@@ -0,0 +1,46 @@
+package container
+
+import (
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/spf13/cobra"
+)
+
+// NewContainerCommand returns a cobra command for `container` subcommands
+// nolint: interfacer
+func NewContainerCommand(dockerCli *command.DockerCli) *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "container",
+ Short: "Manage containers",
+ Args: cli.NoArgs,
+ RunE: command.ShowHelp(dockerCli.Err()),
+ }
+ cmd.AddCommand(
+ NewAttachCommand(dockerCli),
+ NewCommitCommand(dockerCli),
+ NewCopyCommand(dockerCli),
+ NewCreateCommand(dockerCli),
+ NewDiffCommand(dockerCli),
+ NewExecCommand(dockerCli),
+ NewExportCommand(dockerCli),
+ NewKillCommand(dockerCli),
+ NewLogsCommand(dockerCli),
+ NewPauseCommand(dockerCli),
+ NewPortCommand(dockerCli),
+ NewRenameCommand(dockerCli),
+ NewRestartCommand(dockerCli),
+ NewRmCommand(dockerCli),
+ NewRunCommand(dockerCli),
+ NewStartCommand(dockerCli),
+ NewStatsCommand(dockerCli),
+ NewStopCommand(dockerCli),
+ NewTopCommand(dockerCli),
+ NewUnpauseCommand(dockerCli),
+ NewUpdateCommand(dockerCli),
+ NewWaitCommand(dockerCli),
+ newListCommand(dockerCli),
+ newInspectCommand(dockerCli),
+ NewPruneCommand(dockerCli),
+ )
+ return cmd
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/commit.go b/vendor/github.com/docker/cli/cli/command/container/commit.go
new file mode 100644
index 0000000..689918e
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/commit.go
@@ -0,0 +1,75 @@
+package container
+
+import (
+ "fmt"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type commitOptions struct {
+ container string
+ reference string
+
+ pause bool
+ comment string
+ author string
+ changes opts.ListOpts
+}
+
+// NewCommitCommand creates a new cobra.Command for `docker commit`
+func NewCommitCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var options commitOptions
+
+ cmd := &cobra.Command{
+ Use: "commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]",
+ Short: "Create a new image from a container's changes",
+ Args: cli.RequiresRangeArgs(1, 2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ options.container = args[0]
+ if len(args) > 1 {
+ options.reference = args[1]
+ }
+ return runCommit(dockerCli, &options)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.SetInterspersed(false)
+
+ flags.BoolVarP(&options.pause, "pause", "p", true, "Pause container during commit")
+ flags.StringVarP(&options.comment, "message", "m", "", "Commit message")
+ flags.StringVarP(&options.author, "author", "a", "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")")
+
+ options.changes = opts.NewListOpts(nil)
+ flags.VarP(&options.changes, "change", "c", "Apply Dockerfile instruction to the created image")
+
+ return cmd
+}
+
+func runCommit(dockerCli *command.DockerCli, options *commitOptions) error {
+ ctx := context.Background()
+
+ name := options.container
+ reference := options.reference
+
+ commitOptions := types.ContainerCommitOptions{
+ Reference: reference,
+ Comment: options.comment,
+ Author: options.author,
+ Changes: options.changes.GetAll(),
+ Pause: options.pause,
+ }
+
+ response, err := dockerCli.Client().ContainerCommit(ctx, name, commitOptions)
+ if err != nil {
+ return err
+ }
+
+ fmt.Fprintln(dockerCli.Out(), response.ID)
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/cp.go b/vendor/github.com/docker/cli/cli/command/container/cp.go
new file mode 100644
index 0000000..17a4030
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/cp.go
@@ -0,0 +1,305 @@
+package container
+
+import (
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/archive"
+ "github.com/docker/docker/pkg/system"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type copyOptions struct {
+ source string
+ destination string
+ followLink bool
+ copyUIDGID bool
+}
+
+type copyDirection int
+
+const (
+ fromContainer copyDirection = (1 << iota)
+ toContainer
+ acrossContainers = fromContainer | toContainer
+)
+
+type cpConfig struct {
+ followLink bool
+}
+
+// NewCopyCommand creates a new `docker cp` command
+func NewCopyCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts copyOptions
+
+ cmd := &cobra.Command{
+ Use: `cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
+ docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH`,
+ Short: "Copy files/folders between a container and the local filesystem",
+ Long: strings.Join([]string{
+ "Copy files/folders between a container and the local filesystem\n",
+ "\nUse '-' as the source to read a tar archive from stdin\n",
+ "and extract it to a directory destination in a container.\n",
+ "Use '-' as the destination to stream a tar archive of a\n",
+ "container source to stdout.",
+ }, ""),
+ Args: cli.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if args[0] == "" {
+ return errors.New("source can not be empty")
+ }
+ if args[1] == "" {
+ return errors.New("destination can not be empty")
+ }
+ opts.source = args[0]
+ opts.destination = args[1]
+ return runCopy(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.BoolVarP(&opts.followLink, "follow-link", "L", false, "Always follow symbol link in SRC_PATH")
+ flags.BoolVarP(&opts.copyUIDGID, "archive", "a", false, "Archive mode (copy all uid/gid information)")
+
+ return cmd
+}
+
+func runCopy(dockerCli *command.DockerCli, opts copyOptions) error {
+ srcContainer, srcPath := splitCpArg(opts.source)
+ dstContainer, dstPath := splitCpArg(opts.destination)
+
+ var direction copyDirection
+ if srcContainer != "" {
+ direction |= fromContainer
+ }
+ if dstContainer != "" {
+ direction |= toContainer
+ }
+
+ cpParam := &cpConfig{
+ followLink: opts.followLink,
+ }
+
+ ctx := context.Background()
+
+ switch direction {
+ case fromContainer:
+ return copyFromContainer(ctx, dockerCli, srcContainer, srcPath, dstPath, cpParam)
+ case toContainer:
+ return copyToContainer(ctx, dockerCli, srcPath, dstContainer, dstPath, cpParam, opts.copyUIDGID)
+ case acrossContainers:
+ // Copying between containers isn't supported.
+ return errors.New("copying between containers is not supported")
+ default:
+ // User didn't specify any container.
+ return errors.New("must specify at least one container source")
+ }
+}
+
+func statContainerPath(ctx context.Context, dockerCli *command.DockerCli, containerName, path string) (types.ContainerPathStat, error) {
+ return dockerCli.Client().ContainerStatPath(ctx, containerName, path)
+}
+
+func resolveLocalPath(localPath string) (absPath string, err error) {
+ if absPath, err = filepath.Abs(localPath); err != nil {
+ return
+ }
+
+ return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil
+}
+
+func copyFromContainer(ctx context.Context, dockerCli *command.DockerCli, srcContainer, srcPath, dstPath string, cpParam *cpConfig) (err error) {
+ if dstPath != "-" {
+ // Get an absolute destination path.
+ dstPath, err = resolveLocalPath(dstPath)
+ if err != nil {
+ return err
+ }
+ }
+
+ // if client requests to follow symbol link, then must decide target file to be copied
+ var rebaseName string
+ if cpParam.followLink {
+ srcStat, err := statContainerPath(ctx, dockerCli, srcContainer, srcPath)
+
+ // If the destination is a symbolic link, we should follow it.
+ if err == nil && srcStat.Mode&os.ModeSymlink != 0 {
+ linkTarget := srcStat.LinkTarget
+ if !system.IsAbs(linkTarget) {
+ // Join with the parent directory.
+ srcParent, _ := archive.SplitPathDirEntry(srcPath)
+ linkTarget = filepath.Join(srcParent, linkTarget)
+ }
+
+ linkTarget, rebaseName = archive.GetRebaseName(srcPath, linkTarget)
+ srcPath = linkTarget
+ }
+
+ }
+
+ content, stat, err := dockerCli.Client().CopyFromContainer(ctx, srcContainer, srcPath)
+ if err != nil {
+ return err
+ }
+ defer content.Close()
+
+ if dstPath == "-" {
+ // Send the response to STDOUT.
+ _, err = io.Copy(os.Stdout, content)
+
+ return err
+ }
+
+ // Prepare source copy info.
+ srcInfo := archive.CopyInfo{
+ Path: srcPath,
+ Exists: true,
+ IsDir: stat.Mode.IsDir(),
+ RebaseName: rebaseName,
+ }
+
+ preArchive := content
+ if len(srcInfo.RebaseName) != 0 {
+ _, srcBase := archive.SplitPathDirEntry(srcInfo.Path)
+ preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName)
+ }
+ // See comments in the implementation of `archive.CopyTo` for exactly what
+ // goes into deciding how and whether the source archive needs to be
+ // altered for the correct copy behavior.
+ return archive.CopyTo(preArchive, srcInfo, dstPath)
+}
+
+func copyToContainer(ctx context.Context, dockerCli *command.DockerCli, srcPath, dstContainer, dstPath string, cpParam *cpConfig, copyUIDGID bool) (err error) {
+ if srcPath != "-" {
+ // Get an absolute source path.
+ srcPath, err = resolveLocalPath(srcPath)
+ if err != nil {
+ return err
+ }
+ }
+
+ // In order to get the copy behavior right, we need to know information
+ // about both the source and destination. The API is a simple tar
+ // archive/extract API but we can use the stat info header about the
+ // destination to be more informed about exactly what the destination is.
+
+ // Prepare destination copy info by stat-ing the container path.
+ dstInfo := archive.CopyInfo{Path: dstPath}
+ dstStat, err := statContainerPath(ctx, dockerCli, dstContainer, dstPath)
+
+ // If the destination is a symbolic link, we should evaluate it.
+ if err == nil && dstStat.Mode&os.ModeSymlink != 0 {
+ linkTarget := dstStat.LinkTarget
+ if !system.IsAbs(linkTarget) {
+ // Join with the parent directory.
+ dstParent, _ := archive.SplitPathDirEntry(dstPath)
+ linkTarget = filepath.Join(dstParent, linkTarget)
+ }
+
+ dstInfo.Path = linkTarget
+ dstStat, err = statContainerPath(ctx, dockerCli, dstContainer, linkTarget)
+ }
+
+ // Ignore any error and assume that the parent directory of the destination
+ // path exists, in which case the copy may still succeed. If there is any
+ // type of conflict (e.g., non-directory overwriting an existing directory
+ // or vice versa) the extraction will fail. If the destination simply did
+ // not exist, but the parent directory does, the extraction will still
+ // succeed.
+ if err == nil {
+ dstInfo.Exists, dstInfo.IsDir = true, dstStat.Mode.IsDir()
+ }
+
+ var (
+ content io.Reader
+ resolvedDstPath string
+ )
+
+ if srcPath == "-" {
+ // Use STDIN.
+ content = os.Stdin
+ resolvedDstPath = dstInfo.Path
+ if !dstInfo.IsDir {
+ return errors.Errorf("destination \"%s:%s\" must be a directory", dstContainer, dstPath)
+ }
+ } else {
+ // Prepare source copy info.
+ srcInfo, err := archive.CopyInfoSourcePath(srcPath, cpParam.followLink)
+ if err != nil {
+ return err
+ }
+
+ srcArchive, err := archive.TarResource(srcInfo)
+ if err != nil {
+ return err
+ }
+ defer srcArchive.Close()
+
+ // With the stat info about the local source as well as the
+ // destination, we have enough information to know whether we need to
+ // alter the archive that we upload so that when the server extracts
+ // it to the specified directory in the container we get the desired
+ // copy behavior.
+
+ // See comments in the implementation of `archive.PrepareArchiveCopy`
+ // for exactly what goes into deciding how and whether the source
+ // archive needs to be altered for the correct copy behavior when it is
+ // extracted. This function also infers from the source and destination
+ // info which directory to extract to, which may be the parent of the
+ // destination that the user specified.
+ dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo)
+ if err != nil {
+ return err
+ }
+ defer preparedArchive.Close()
+
+ resolvedDstPath = dstDir
+ content = preparedArchive
+ }
+
+ options := types.CopyToContainerOptions{
+ AllowOverwriteDirWithFile: false,
+ CopyUIDGID: copyUIDGID,
+ }
+
+ return dockerCli.Client().CopyToContainer(ctx, dstContainer, resolvedDstPath, content, options)
+}
+
+// We use `:` as a delimiter between CONTAINER and PATH, but `:` could also be
+// in a valid LOCALPATH, like `file:name.txt`. We can resolve this ambiguity by
+// requiring a LOCALPATH with a `:` to be made explicit with a relative or
+// absolute path:
+// `/path/to/file:name.txt` or `./file:name.txt`
+//
+// This is apparently how `scp` handles this as well:
+// http://www.cyberciti.biz/faq/rsync-scp-file-name-with-colon-punctuation-in-it/
+//
+// We can't simply check for a filepath separator because container names may
+// have a separator, e.g., "host0/cname1" if container is in a Docker cluster,
+// so we have to check for a `/` or `.` prefix. Also, in the case of a Windows
+// client, a `:` could be part of an absolute Windows path, in which case it
+// is immediately proceeded by a backslash.
+func splitCpArg(arg string) (container, path string) {
+ if system.IsAbs(arg) {
+ // Explicit local absolute path, e.g., `C:\foo` or `/foo`.
+ return "", arg
+ }
+
+ parts := strings.SplitN(arg, ":", 2)
+
+ if len(parts) == 1 || strings.HasPrefix(parts[0], ".") {
+ // Either there's no `:` in the arg
+ // OR it's an explicit local relative path like `./file:name.txt`.
+ return "", arg
+ }
+
+ return parts[0], parts[1]
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/create.go b/vendor/github.com/docker/cli/cli/command/container/create.go
new file mode 100644
index 0000000..2795e4f
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/create.go
@@ -0,0 +1,224 @@
+package container
+
+import (
+ "fmt"
+ "io"
+ "os"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/image"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/api/types/container"
+ apiclient "github.com/docker/docker/client"
+ "github.com/docker/docker/pkg/jsonmessage"
+ "github.com/docker/docker/registry"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "github.com/spf13/pflag"
+ "golang.org/x/net/context"
+)
+
+type createOptions struct {
+ name string
+}
+
+// NewCreateCommand creates a new cobra.Command for `docker create`
+func NewCreateCommand(dockerCli command.Cli) *cobra.Command {
+ var opts createOptions
+ var copts *containerOptions
+
+ cmd := &cobra.Command{
+ Use: "create [OPTIONS] IMAGE [COMMAND] [ARG...]",
+ Short: "Create a new container",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ copts.Image = args[0]
+ if len(args) > 1 {
+ copts.Args = args[1:]
+ }
+ return runCreate(dockerCli, cmd.Flags(), &opts, copts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.SetInterspersed(false)
+
+ flags.StringVar(&opts.name, "name", "", "Assign a name to the container")
+
+ // Add an explicit help that doesn't have a `-h` to prevent the conflict
+ // with hostname
+ flags.Bool("help", false, "Print usage")
+
+ command.AddTrustVerificationFlags(flags)
+ copts = addFlags(flags)
+ return cmd
+}
+
+func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, opts *createOptions, copts *containerOptions) error {
+ containerConfig, err := parse(flags, copts)
+ if err != nil {
+ reportError(dockerCli.Err(), "create", err.Error(), true)
+ return cli.StatusError{StatusCode: 125}
+ }
+ response, err := createContainer(context.Background(), dockerCli, containerConfig, opts.name)
+ if err != nil {
+ return err
+ }
+ fmt.Fprintln(dockerCli.Out(), response.ID)
+ return nil
+}
+
+func pullImage(ctx context.Context, dockerCli command.Cli, image string, out io.Writer) error {
+ ref, err := reference.ParseNormalizedNamed(image)
+ if err != nil {
+ return err
+ }
+
+ // Resolve the Repository name from fqn to RepositoryInfo
+ repoInfo, err := registry.ParseRepositoryInfo(ref)
+ if err != nil {
+ return err
+ }
+
+ authConfig := command.ResolveAuthConfig(ctx, dockerCli, repoInfo.Index)
+ encodedAuth, err := command.EncodeAuthToBase64(authConfig)
+ if err != nil {
+ return err
+ }
+
+ options := types.ImageCreateOptions{
+ RegistryAuth: encodedAuth,
+ }
+
+ responseBody, err := dockerCli.Client().ImageCreate(ctx, image, options)
+ if err != nil {
+ return err
+ }
+ defer responseBody.Close()
+
+ return jsonmessage.DisplayJSONMessagesStream(
+ responseBody,
+ out,
+ dockerCli.Out().FD(),
+ dockerCli.Out().IsTerminal(),
+ nil)
+}
+
+type cidFile struct {
+ path string
+ file *os.File
+ written bool
+}
+
+func (cid *cidFile) Close() error {
+ cid.file.Close()
+
+ if cid.written {
+ return nil
+ }
+ if err := os.Remove(cid.path); err != nil {
+ return errors.Errorf("failed to remove the CID file '%s': %s \n", cid.path, err)
+ }
+
+ return nil
+}
+
+func (cid *cidFile) Write(id string) error {
+ if _, err := cid.file.Write([]byte(id)); err != nil {
+ return errors.Errorf("Failed to write the container ID to the file: %s", err)
+ }
+ cid.written = true
+ return nil
+}
+
+func newCIDFile(path string) (*cidFile, error) {
+ if _, err := os.Stat(path); err == nil {
+ return nil, errors.Errorf("Container ID file found, make sure the other container isn't running or delete %s", path)
+ }
+
+ f, err := os.Create(path)
+ if err != nil {
+ return nil, errors.Errorf("Failed to create the container ID file: %s", err)
+ }
+
+ return &cidFile{path: path, file: f}, nil
+}
+
+func createContainer(ctx context.Context, dockerCli command.Cli, containerConfig *containerConfig, name string) (*container.ContainerCreateCreatedBody, error) {
+ config := containerConfig.Config
+ hostConfig := containerConfig.HostConfig
+ networkingConfig := containerConfig.NetworkingConfig
+ stderr := dockerCli.Err()
+
+ var (
+ containerIDFile *cidFile
+ trustedRef reference.Canonical
+ namedRef reference.Named
+ )
+
+ cidfile := hostConfig.ContainerIDFile
+ if cidfile != "" {
+ var err error
+ if containerIDFile, err = newCIDFile(cidfile); err != nil {
+ return nil, err
+ }
+ defer containerIDFile.Close()
+ }
+
+ ref, err := reference.ParseAnyReference(config.Image)
+ if err != nil {
+ return nil, err
+ }
+ if named, ok := ref.(reference.Named); ok {
+ namedRef = reference.TagNameOnly(named)
+
+ if taggedRef, ok := namedRef.(reference.NamedTagged); ok && command.IsTrusted() {
+ var err error
+ trustedRef, err = image.TrustedReference(ctx, dockerCli, taggedRef, nil)
+ if err != nil {
+ return nil, err
+ }
+ config.Image = reference.FamiliarString(trustedRef)
+ }
+ }
+
+ //create the container
+ response, err := dockerCli.Client().ContainerCreate(ctx, config, hostConfig, networkingConfig, name)
+
+ //if image not found try to pull it
+ if err != nil {
+ if apiclient.IsErrImageNotFound(err) && namedRef != nil {
+ fmt.Fprintf(stderr, "Unable to find image '%s' locally\n", reference.FamiliarString(namedRef))
+
+ // we don't want to write to stdout anything apart from container.ID
+ if err = pullImage(ctx, dockerCli, config.Image, stderr); err != nil {
+ return nil, err
+ }
+ if taggedRef, ok := namedRef.(reference.NamedTagged); ok && trustedRef != nil {
+ if err := image.TagTrusted(ctx, dockerCli, trustedRef, taggedRef); err != nil {
+ return nil, err
+ }
+ }
+ // Retry
+ var retryErr error
+ response, retryErr = dockerCli.Client().ContainerCreate(ctx, config, hostConfig, networkingConfig, name)
+ if retryErr != nil {
+ return nil, retryErr
+ }
+ } else {
+ return nil, err
+ }
+ }
+
+ for _, warning := range response.Warnings {
+ fmt.Fprintf(stderr, "WARNING: %s\n", warning)
+ }
+ if containerIDFile != nil {
+ if err = containerIDFile.Write(response.ID); err != nil {
+ return nil, err
+ }
+ }
+ return &response, nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/diff.go b/vendor/github.com/docker/cli/cli/command/container/diff.go
new file mode 100644
index 0000000..5f646aa
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/diff.go
@@ -0,0 +1,46 @@
+package container
+
+import (
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/formatter"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type diffOptions struct {
+ container string
+}
+
+// NewDiffCommand creates a new cobra.Command for `docker diff`
+func NewDiffCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts diffOptions
+
+ return &cobra.Command{
+ Use: "diff CONTAINER",
+ Short: "Inspect changes to files or directories on a container's filesystem",
+ Args: cli.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.container = args[0]
+ return runDiff(dockerCli, &opts)
+ },
+ }
+}
+
+func runDiff(dockerCli *command.DockerCli, opts *diffOptions) error {
+ if opts.container == "" {
+ return errors.New("Container name cannot be empty")
+ }
+ ctx := context.Background()
+
+ changes, err := dockerCli.Client().ContainerDiff(ctx, opts.container)
+ if err != nil {
+ return err
+ }
+ diffCtx := formatter.Context{
+ Output: dockerCli.Out(),
+ Format: formatter.NewDiffFormat("{{.Type}} {{.Path}}"),
+ }
+ return formatter.DiffWrite(diffCtx, changes)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/exec.go b/vendor/github.com/docker/cli/cli/command/container/exec.go
new file mode 100644
index 0000000..bbcd34a
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/exec.go
@@ -0,0 +1,220 @@
+package container
+
+import (
+ "fmt"
+ "io"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ apiclient "github.com/docker/docker/client"
+ "github.com/docker/docker/pkg/promise"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type execOptions struct {
+ detachKeys string
+ interactive bool
+ tty bool
+ detach bool
+ user string
+ privileged bool
+ env *opts.ListOpts
+}
+
+func newExecOptions() *execOptions {
+ var values []string
+ return &execOptions{
+ env: opts.NewListOptsRef(&values, opts.ValidateEnv),
+ }
+}
+
+// NewExecCommand creates a new cobra.Command for `docker exec`
+func NewExecCommand(dockerCli command.Cli) *cobra.Command {
+ options := newExecOptions()
+
+ cmd := &cobra.Command{
+ Use: "exec [OPTIONS] CONTAINER COMMAND [ARG...]",
+ Short: "Run a command in a running container",
+ Args: cli.RequiresMinArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ container := args[0]
+ execCmd := args[1:]
+ return runExec(dockerCli, options, container, execCmd)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.SetInterspersed(false)
+
+ flags.StringVarP(&options.detachKeys, "detach-keys", "", "", "Override the key sequence for detaching a container")
+ flags.BoolVarP(&options.interactive, "interactive", "i", false, "Keep STDIN open even if not attached")
+ flags.BoolVarP(&options.tty, "tty", "t", false, "Allocate a pseudo-TTY")
+ flags.BoolVarP(&options.detach, "detach", "d", false, "Detached mode: run command in the background")
+ flags.StringVarP(&options.user, "user", "u", "", "Username or UID (format: <name|uid>[:<group|gid>])")
+ flags.BoolVarP(&options.privileged, "privileged", "", false, "Give extended privileges to the command")
+ flags.VarP(options.env, "env", "e", "Set environment variables")
+ flags.SetAnnotation("env", "version", []string{"1.25"})
+
+ return cmd
+}
+
+// nolint: gocyclo
+func runExec(dockerCli command.Cli, options *execOptions, container string, execCmd []string) error {
+ execConfig, err := parseExec(options, execCmd)
+ // just in case the ParseExec does not exit
+ if container == "" || err != nil {
+ return cli.StatusError{StatusCode: 1}
+ }
+
+ if options.detachKeys != "" {
+ dockerCli.ConfigFile().DetachKeys = options.detachKeys
+ }
+
+ // Send client escape keys
+ execConfig.DetachKeys = dockerCli.ConfigFile().DetachKeys
+
+ ctx := context.Background()
+ client := dockerCli.Client()
+
+ // We need to check the tty _before_ we do the ContainerExecCreate, because
+ // otherwise if we error out we will leak execIDs on the server (and
+ // there's no easy way to clean those up). But also in order to make "not
+ // exist" errors take precedence we do a dummy inspect first.
+ if _, err := client.ContainerInspect(ctx, container); err != nil {
+ return err
+ }
+ if !execConfig.Detach {
+ if err := dockerCli.In().CheckTty(execConfig.AttachStdin, execConfig.Tty); err != nil {
+ return err
+ }
+ }
+
+ response, err := client.ContainerExecCreate(ctx, container, *execConfig)
+ if err != nil {
+ return err
+ }
+
+ execID := response.ID
+ if execID == "" {
+ fmt.Fprintln(dockerCli.Out(), "exec ID empty")
+ return nil
+ }
+
+ // Temp struct for execStart so that we don't need to transfer all the execConfig.
+ if execConfig.Detach {
+ execStartCheck := types.ExecStartCheck{
+ Detach: execConfig.Detach,
+ Tty: execConfig.Tty,
+ }
+
+ return client.ContainerExecStart(ctx, execID, execStartCheck)
+ }
+
+ // Interactive exec requested.
+ var (
+ out, stderr io.Writer
+ in io.ReadCloser
+ errCh chan error
+ )
+
+ if execConfig.AttachStdin {
+ in = dockerCli.In()
+ }
+ if execConfig.AttachStdout {
+ out = dockerCli.Out()
+ }
+ if execConfig.AttachStderr {
+ if execConfig.Tty {
+ stderr = dockerCli.Out()
+ } else {
+ stderr = dockerCli.Err()
+ }
+ }
+
+ resp, err := client.ContainerExecAttach(ctx, execID, *execConfig)
+ if err != nil {
+ return err
+ }
+ defer resp.Close()
+ errCh = promise.Go(func() error {
+ streamer := hijackedIOStreamer{
+ streams: dockerCli,
+ inputStream: in,
+ outputStream: out,
+ errorStream: stderr,
+ resp: resp,
+ tty: execConfig.Tty,
+ detachKeys: execConfig.DetachKeys,
+ }
+
+ return streamer.stream(ctx)
+ })
+
+ if execConfig.Tty && dockerCli.In().IsTerminal() {
+ if err := MonitorTtySize(ctx, dockerCli, execID, true); err != nil {
+ fmt.Fprintln(dockerCli.Err(), "Error monitoring TTY size:", err)
+ }
+ }
+
+ if err := <-errCh; err != nil {
+ logrus.Debugf("Error hijack: %s", err)
+ return err
+ }
+
+ var status int
+ if _, status, err = getExecExitCode(ctx, client, execID); err != nil {
+ return err
+ }
+
+ if status != 0 {
+ return cli.StatusError{StatusCode: status}
+ }
+
+ return nil
+}
+
+// getExecExitCode perform an inspect on the exec command. It returns
+// the running state and the exit code.
+func getExecExitCode(ctx context.Context, client apiclient.ContainerAPIClient, execID string) (bool, int, error) {
+ resp, err := client.ContainerExecInspect(ctx, execID)
+ if err != nil {
+ // If we can't connect, then the daemon probably died.
+ if !apiclient.IsErrConnectionFailed(err) {
+ return false, -1, err
+ }
+ return false, -1, nil
+ }
+
+ return resp.Running, resp.ExitCode, nil
+}
+
+// parseExec parses the specified args for the specified command and generates
+// an ExecConfig from it.
+func parseExec(opts *execOptions, execCmd []string) (*types.ExecConfig, error) {
+ execConfig := &types.ExecConfig{
+ User: opts.user,
+ Privileged: opts.privileged,
+ Tty: opts.tty,
+ Cmd: execCmd,
+ Detach: opts.detach,
+ }
+
+ // If -d is not set, attach to everything by default
+ if !opts.detach {
+ execConfig.AttachStdout = true
+ execConfig.AttachStderr = true
+ if opts.interactive {
+ execConfig.AttachStdin = true
+ }
+ }
+
+ if opts.env != nil {
+ execConfig.Env = opts.env.GetAll()
+ }
+
+ return execConfig, nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/export.go b/vendor/github.com/docker/cli/cli/command/container/export.go
new file mode 100644
index 0000000..700f557
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/export.go
@@ -0,0 +1,58 @@
+package container
+
+import (
+ "io"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type exportOptions struct {
+ container string
+ output string
+}
+
+// NewExportCommand creates a new `docker export` command
+func NewExportCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts exportOptions
+
+ cmd := &cobra.Command{
+ Use: "export [OPTIONS] CONTAINER",
+ Short: "Export a container's filesystem as a tar archive",
+ Args: cli.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.container = args[0]
+ return runExport(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT")
+
+ return cmd
+}
+
+func runExport(dockerCli *command.DockerCli, opts exportOptions) error {
+ if opts.output == "" && dockerCli.Out().IsTerminal() {
+ return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect")
+ }
+
+ clnt := dockerCli.Client()
+
+ responseBody, err := clnt.ContainerExport(context.Background(), opts.container)
+ if err != nil {
+ return err
+ }
+ defer responseBody.Close()
+
+ if opts.output == "" {
+ _, err := io.Copy(dockerCli.Out(), responseBody)
+ return err
+ }
+
+ return command.CopyToFile(opts.output, responseBody)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/hijack.go b/vendor/github.com/docker/cli/cli/command/container/hijack.go
new file mode 100644
index 0000000..b6d467d
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/hijack.go
@@ -0,0 +1,207 @@
+package container
+
+import (
+ "fmt"
+ "io"
+ "runtime"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/ioutils"
+ "github.com/docker/docker/pkg/stdcopy"
+ "github.com/docker/docker/pkg/term"
+ "golang.org/x/net/context"
+)
+
+// The default escape key sequence: ctrl-p, ctrl-q
+// TODO: This could be moved to `pkg/term`.
+var defaultEscapeKeys = []byte{16, 17}
+
+// A hijackedIOStreamer handles copying input to and output from streams to the
+// connection.
+type hijackedIOStreamer struct {
+ streams command.Streams
+ inputStream io.ReadCloser
+ outputStream io.Writer
+ errorStream io.Writer
+
+ resp types.HijackedResponse
+
+ tty bool
+ detachKeys string
+}
+
+// stream handles setting up the IO and then begins streaming stdin/stdout
+// to/from the hijacked connection, blocking until it is either done reading
+// output, the user inputs the detach key sequence when in TTY mode, or when
+// the given context is cancelled.
+func (h *hijackedIOStreamer) stream(ctx context.Context) error {
+ restoreInput, err := h.setupInput()
+ if err != nil {
+ return fmt.Errorf("unable to setup input stream: %s", err)
+ }
+
+ defer restoreInput()
+
+ outputDone := h.beginOutputStream(restoreInput)
+ inputDone, detached := h.beginInputStream(restoreInput)
+
+ select {
+ case err := <-outputDone:
+ return err
+ case <-inputDone:
+ // Input stream has closed.
+ if h.outputStream != nil || h.errorStream != nil {
+ // Wait for output to complete streaming.
+ select {
+ case err := <-outputDone:
+ return err
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+ return nil
+ case err := <-detached:
+ // Got a detach key sequence.
+ return err
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+func (h *hijackedIOStreamer) setupInput() (restore func(), err error) {
+ if h.inputStream == nil || !h.tty {
+ // No need to setup input TTY.
+ // The restore func is a nop.
+ return func() {}, nil
+ }
+
+ if err := setRawTerminal(h.streams); err != nil {
+ return nil, fmt.Errorf("unable to set IO streams as raw terminal: %s", err)
+ }
+
+ // Use sync.Once so we may call restore multiple times but ensure we
+ // only restore the terminal once.
+ var restoreOnce sync.Once
+ restore = func() {
+ restoreOnce.Do(func() {
+ restoreTerminal(h.streams, h.inputStream)
+ })
+ }
+
+ // Wrap the input to detect detach escape sequence.
+ // Use default escape keys if an invalid sequence is given.
+ escapeKeys := defaultEscapeKeys
+ if h.detachKeys != "" {
+ customEscapeKeys, err := term.ToBytes(h.detachKeys)
+ if err != nil {
+ logrus.Warnf("invalid detach escape keys, using default: %s", err)
+ } else {
+ escapeKeys = customEscapeKeys
+ }
+ }
+
+ h.inputStream = ioutils.NewReadCloserWrapper(term.NewEscapeProxy(h.inputStream, escapeKeys), h.inputStream.Close)
+
+ return restore, nil
+}
+
+func (h *hijackedIOStreamer) beginOutputStream(restoreInput func()) <-chan error {
+ if h.outputStream == nil && h.errorStream == nil {
+ // There is no need to copy output.
+ return nil
+ }
+
+ outputDone := make(chan error)
+ go func() {
+ var err error
+
+ // When TTY is ON, use regular copy
+ if h.outputStream != nil && h.tty {
+ _, err = io.Copy(h.outputStream, h.resp.Reader)
+ // We should restore the terminal as soon as possible
+ // once the connection ends so any following print
+ // messages will be in normal type.
+ restoreInput()
+ } else {
+ _, err = stdcopy.StdCopy(h.outputStream, h.errorStream, h.resp.Reader)
+ }
+
+ logrus.Debug("[hijack] End of stdout")
+
+ if err != nil {
+ logrus.Debugf("Error receiveStdout: %s", err)
+ }
+
+ outputDone <- err
+ }()
+
+ return outputDone
+}
+
+func (h *hijackedIOStreamer) beginInputStream(restoreInput func()) (doneC <-chan struct{}, detachedC <-chan error) {
+ inputDone := make(chan struct{})
+ detached := make(chan error)
+
+ go func() {
+ if h.inputStream != nil {
+ _, err := io.Copy(h.resp.Conn, h.inputStream)
+ // We should restore the terminal as soon as possible
+ // once the connection ends so any following print
+ // messages will be in normal type.
+ restoreInput()
+
+ logrus.Debug("[hijack] End of stdin")
+
+ if _, ok := err.(term.EscapeError); ok {
+ detached <- err
+ return
+ }
+
+ if err != nil {
+ // This error will also occur on the receive
+ // side (from stdout) where it will be
+ // propagated back to the caller.
+ logrus.Debugf("Error sendStdin: %s", err)
+ }
+ }
+
+ if err := h.resp.CloseWrite(); err != nil {
+ logrus.Debugf("Couldn't send EOF: %s", err)
+ }
+
+ close(inputDone)
+ }()
+
+ return inputDone, detached
+}
+
+func setRawTerminal(streams command.Streams) error {
+ if err := streams.In().SetRawTerminal(); err != nil {
+ return err
+ }
+ return streams.Out().SetRawTerminal()
+}
+
+func restoreTerminal(streams command.Streams, in io.Closer) error {
+ streams.In().RestoreTerminal()
+ streams.Out().RestoreTerminal()
+ // WARNING: DO NOT REMOVE THE OS CHECKS !!!
+ // For some reason this Close call blocks on darwin..
+ // As the client exits right after, simply discard the close
+ // until we find a better solution.
+ //
+ // This can also cause the client on Windows to get stuck in Win32 CloseHandle()
+ // in some cases. See https://github.com/docker/docker/issues/28267#issuecomment-288237442
+ // Tracked internally at Microsoft by VSO #11352156. In the
+ // Windows case, you hit this if you are using the native/v2 console,
+ // not the "legacy" console, and you start the client in a new window. eg
+ // `start docker run --rm -it microsoft/nanoserver cmd /s /c echo foobar`
+ // will hang. Remove start, and it won't repro.
+ if in != nil && runtime.GOOS != "darwin" && runtime.GOOS != "windows" {
+ return in.Close()
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/inspect.go b/vendor/github.com/docker/cli/cli/command/container/inspect.go
new file mode 100644
index 0000000..7e0e710
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/inspect.go
@@ -0,0 +1,46 @@
+package container
+
+import (
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/inspect"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type inspectOptions struct {
+ format string
+ size bool
+ refs []string
+}
+
+// newInspectCommand creates a new cobra.Command for `docker container inspect`
+func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts inspectOptions
+
+ cmd := &cobra.Command{
+ Use: "inspect [OPTIONS] CONTAINER [CONTAINER...]",
+ Short: "Display detailed information on one or more containers",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.refs = args
+ return runInspect(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
+ flags.BoolVarP(&opts.size, "size", "s", false, "Display total file sizes")
+
+ return cmd
+}
+
+func runInspect(dockerCli *command.DockerCli, opts inspectOptions) error {
+ client := dockerCli.Client()
+ ctx := context.Background()
+
+ getRefFunc := func(ref string) (interface{}, []byte, error) {
+ return client.ContainerInspectWithRaw(ctx, ref, opts.size)
+ }
+ return inspect.Inspect(dockerCli.Out(), opts.refs, opts.format, getRefFunc)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/kill.go b/vendor/github.com/docker/cli/cli/command/container/kill.go
new file mode 100644
index 0000000..650f957
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/kill.go
@@ -0,0 +1,56 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type killOptions struct {
+ signal string
+
+ containers []string
+}
+
+// NewKillCommand creates a new cobra.Command for `docker kill`
+func NewKillCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts killOptions
+
+ cmd := &cobra.Command{
+ Use: "kill [OPTIONS] CONTAINER [CONTAINER...]",
+ Short: "Kill one or more running containers",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.containers = args
+ return runKill(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.StringVarP(&opts.signal, "signal", "s", "KILL", "Signal to send to the container")
+ return cmd
+}
+
+func runKill(dockerCli *command.DockerCli, opts *killOptions) error {
+ var errs []string
+ ctx := context.Background()
+ errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error {
+ return dockerCli.Client().ContainerKill(ctx, container, opts.signal)
+ })
+ for _, name := range opts.containers {
+ if err := <-errChan; err != nil {
+ errs = append(errs, err.Error())
+ } else {
+ fmt.Fprintln(dockerCli.Out(), name)
+ }
+ }
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, "\n"))
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/list.go b/vendor/github.com/docker/cli/cli/command/container/list.go
new file mode 100644
index 0000000..844ef57
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/list.go
@@ -0,0 +1,140 @@
+package container
+
+import (
+ "io/ioutil"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/formatter"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/templates"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type psOptions struct {
+ quiet bool
+ size bool
+ all bool
+ noTrunc bool
+ nLatest bool
+ last int
+ format string
+ filter opts.FilterOpt
+}
+
+// NewPsCommand creates a new cobra.Command for `docker ps`
+func NewPsCommand(dockerCli *command.DockerCli) *cobra.Command {
+ options := psOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "ps [OPTIONS]",
+ Short: "List containers",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runPs(dockerCli, &options)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only display numeric IDs")
+ flags.BoolVarP(&options.size, "size", "s", false, "Display total file sizes")
+ flags.BoolVarP(&options.all, "all", "a", false, "Show all containers (default shows just running)")
+ flags.BoolVar(&options.noTrunc, "no-trunc", false, "Don't truncate output")
+ flags.BoolVarP(&options.nLatest, "latest", "l", false, "Show the latest created container (includes all states)")
+ flags.IntVarP(&options.last, "last", "n", -1, "Show n last created containers (includes all states)")
+ flags.StringVarP(&options.format, "format", "", "", "Pretty-print containers using a Go template")
+ flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided")
+
+ return cmd
+}
+
+func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
+ cmd := *NewPsCommand(dockerCli)
+ cmd.Aliases = []string{"ps", "list"}
+ cmd.Use = "ls [OPTIONS]"
+ return &cmd
+}
+
+// listOptionsProcessor is used to set any container list options which may only
+// be embedded in the format template.
+// This is passed directly into tmpl.Execute in order to allow the preprocessor
+// to set any list options that were not provided by flags (e.g. `.Size`).
+// It is using a `map[string]bool` so that unknown fields passed into the
+// template format do not cause errors. These errors will get picked up when
+// running through the actual template processor.
+type listOptionsProcessor map[string]bool
+
+// Size sets the size of the map when called by a template execution.
+func (o listOptionsProcessor) Size() bool {
+ o["size"] = true
+ return true
+}
+
+// Label is needed here as it allows the correct pre-processing
+// because Label() is a method with arguments
+func (o listOptionsProcessor) Label(name string) string {
+ return ""
+}
+
+func buildContainerListOptions(opts *psOptions) (*types.ContainerListOptions, error) {
+ options := &types.ContainerListOptions{
+ All: opts.all,
+ Limit: opts.last,
+ Size: opts.size,
+ Filters: opts.filter.Value(),
+ }
+
+ if opts.nLatest && opts.last == -1 {
+ options.Limit = 1
+ }
+
+ tmpl, err := templates.Parse(opts.format)
+
+ if err != nil {
+ return nil, err
+ }
+
+ optionsProcessor := listOptionsProcessor{}
+ // This shouldn't error out but swallowing the error makes it harder
+ // to track down if preProcessor issues come up. Ref #24696
+ if err := tmpl.Execute(ioutil.Discard, optionsProcessor); err != nil {
+ return nil, err
+ }
+ // At the moment all we need is to capture .Size for preprocessor
+ options.Size = opts.size || optionsProcessor["size"]
+
+ return options, nil
+}
+
+func runPs(dockerCli *command.DockerCli, options *psOptions) error {
+ ctx := context.Background()
+
+ listOptions, err := buildContainerListOptions(options)
+ if err != nil {
+ return err
+ }
+
+ containers, err := dockerCli.Client().ContainerList(ctx, *listOptions)
+ if err != nil {
+ return err
+ }
+
+ format := options.format
+ if len(format) == 0 {
+ if len(dockerCli.ConfigFile().PsFormat) > 0 && !options.quiet {
+ format = dockerCli.ConfigFile().PsFormat
+ } else {
+ format = formatter.TableFormatKey
+ }
+ }
+
+ containerCtx := formatter.Context{
+ Output: dockerCli.Out(),
+ Format: formatter.NewContainerFormat(format, options.quiet, listOptions.Size),
+ Trunc: !options.noTrunc,
+ }
+ return formatter.ContainerWrite(containerCtx, containers)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/logs.go b/vendor/github.com/docker/cli/cli/command/container/logs.go
new file mode 100644
index 0000000..209e749
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/logs.go
@@ -0,0 +1,76 @@
+package container
+
+import (
+ "io"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/stdcopy"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type logsOptions struct {
+ follow bool
+ since string
+ timestamps bool
+ details bool
+ tail string
+
+ container string
+}
+
+// NewLogsCommand creates a new cobra.Command for `docker logs`
+func NewLogsCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts logsOptions
+
+ cmd := &cobra.Command{
+ Use: "logs [OPTIONS] CONTAINER",
+ Short: "Fetch the logs of a container",
+ Args: cli.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.container = args[0]
+ return runLogs(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&opts.follow, "follow", "f", false, "Follow log output")
+ flags.StringVar(&opts.since, "since", "", "Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)")
+ flags.BoolVarP(&opts.timestamps, "timestamps", "t", false, "Show timestamps")
+ flags.BoolVar(&opts.details, "details", false, "Show extra details provided to logs")
+ flags.StringVar(&opts.tail, "tail", "all", "Number of lines to show from the end of the logs")
+ return cmd
+}
+
+func runLogs(dockerCli *command.DockerCli, opts *logsOptions) error {
+ ctx := context.Background()
+
+ options := types.ContainerLogsOptions{
+ ShowStdout: true,
+ ShowStderr: true,
+ Since: opts.since,
+ Timestamps: opts.timestamps,
+ Follow: opts.follow,
+ Tail: opts.tail,
+ Details: opts.details,
+ }
+ responseBody, err := dockerCli.Client().ContainerLogs(ctx, opts.container, options)
+ if err != nil {
+ return err
+ }
+ defer responseBody.Close()
+
+ c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
+ if err != nil {
+ return err
+ }
+
+ if c.Config.Tty {
+ _, err = io.Copy(dockerCli.Out(), responseBody)
+ } else {
+ _, err = stdcopy.StdCopy(dockerCli.Out(), dockerCli.Err(), responseBody)
+ }
+ return err
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/opts.go b/vendor/github.com/docker/cli/cli/command/container/opts.go
new file mode 100644
index 0000000..cf1f931
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/opts.go
@@ -0,0 +1,841 @@
+package container
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "path"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli/compose/loader"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types/container"
+ networktypes "github.com/docker/docker/api/types/network"
+ "github.com/docker/docker/api/types/strslice"
+ "github.com/docker/docker/pkg/signal"
+ "github.com/docker/go-connections/nat"
+ "github.com/pkg/errors"
+ "github.com/spf13/pflag"
+)
+
+var (
+ deviceCgroupRuleRegexp = regexp.MustCompile(`^[acb] ([0-9]+|\*):([0-9]+|\*) [rwm]{1,3}$`)
+)
+
+// containerOptions is a data object with all the options for creating a container
+type containerOptions struct {
+ attach opts.ListOpts
+ volumes opts.ListOpts
+ tmpfs opts.ListOpts
+ mounts opts.MountOpt
+ blkioWeightDevice opts.WeightdeviceOpt
+ deviceReadBps opts.ThrottledeviceOpt
+ deviceWriteBps opts.ThrottledeviceOpt
+ links opts.ListOpts
+ aliases opts.ListOpts
+ linkLocalIPs opts.ListOpts
+ deviceReadIOps opts.ThrottledeviceOpt
+ deviceWriteIOps opts.ThrottledeviceOpt
+ env opts.ListOpts
+ labels opts.ListOpts
+ deviceCgroupRules opts.ListOpts
+ devices opts.ListOpts
+ ulimits *opts.UlimitOpt
+ sysctls *opts.MapOpts
+ publish opts.ListOpts
+ expose opts.ListOpts
+ dns opts.ListOpts
+ dnsSearch opts.ListOpts
+ dnsOptions opts.ListOpts
+ extraHosts opts.ListOpts
+ volumesFrom opts.ListOpts
+ envFile opts.ListOpts
+ capAdd opts.ListOpts
+ capDrop opts.ListOpts
+ groupAdd opts.ListOpts
+ securityOpt opts.ListOpts
+ storageOpt opts.ListOpts
+ labelsFile opts.ListOpts
+ loggingOpts opts.ListOpts
+ privileged bool
+ pidMode string
+ utsMode string
+ usernsMode string
+ publishAll bool
+ stdin bool
+ tty bool
+ oomKillDisable bool
+ oomScoreAdj int
+ containerIDFile string
+ entrypoint string
+ hostname string
+ memory opts.MemBytes
+ memoryReservation opts.MemBytes
+ memorySwap opts.MemSwapBytes
+ kernelMemory opts.MemBytes
+ user string
+ workingDir string
+ cpuCount int64
+ cpuShares int64
+ cpuPercent int64
+ cpuPeriod int64
+ cpuRealtimePeriod int64
+ cpuRealtimeRuntime int64
+ cpuQuota int64
+ cpus opts.NanoCPUs
+ cpusetCpus string
+ cpusetMems string
+ blkioWeight uint16
+ ioMaxBandwidth opts.MemBytes
+ ioMaxIOps uint64
+ swappiness int64
+ netMode string
+ macAddress string
+ ipv4Address string
+ ipv6Address string
+ ipcMode string
+ pidsLimit int64
+ restartPolicy string
+ readonlyRootfs bool
+ loggingDriver string
+ cgroupParent string
+ volumeDriver string
+ stopSignal string
+ stopTimeout int
+ isolation string
+ shmSize opts.MemBytes
+ noHealthcheck bool
+ healthCmd string
+ healthInterval time.Duration
+ healthTimeout time.Duration
+ healthStartPeriod time.Duration
+ healthRetries int
+ runtime string
+ autoRemove bool
+ init bool
+
+ Image string
+ Args []string
+}
+
+// addFlags adds all command line flags that will be used by parse to the FlagSet
+func addFlags(flags *pflag.FlagSet) *containerOptions {
+ copts := &containerOptions{
+ aliases: opts.NewListOpts(nil),
+ attach: opts.NewListOpts(validateAttach),
+ blkioWeightDevice: opts.NewWeightdeviceOpt(opts.ValidateWeightDevice),
+ capAdd: opts.NewListOpts(nil),
+ capDrop: opts.NewListOpts(nil),
+ dns: opts.NewListOpts(opts.ValidateIPAddress),
+ dnsOptions: opts.NewListOpts(nil),
+ dnsSearch: opts.NewListOpts(opts.ValidateDNSSearch),
+ deviceCgroupRules: opts.NewListOpts(validateDeviceCgroupRule),
+ deviceReadBps: opts.NewThrottledeviceOpt(opts.ValidateThrottleBpsDevice),
+ deviceReadIOps: opts.NewThrottledeviceOpt(opts.ValidateThrottleIOpsDevice),
+ deviceWriteBps: opts.NewThrottledeviceOpt(opts.ValidateThrottleBpsDevice),
+ deviceWriteIOps: opts.NewThrottledeviceOpt(opts.ValidateThrottleIOpsDevice),
+ devices: opts.NewListOpts(validateDevice),
+ env: opts.NewListOpts(opts.ValidateEnv),
+ envFile: opts.NewListOpts(nil),
+ expose: opts.NewListOpts(nil),
+ extraHosts: opts.NewListOpts(opts.ValidateExtraHost),
+ groupAdd: opts.NewListOpts(nil),
+ labels: opts.NewListOpts(opts.ValidateEnv),
+ labelsFile: opts.NewListOpts(nil),
+ linkLocalIPs: opts.NewListOpts(nil),
+ links: opts.NewListOpts(opts.ValidateLink),
+ loggingOpts: opts.NewListOpts(nil),
+ publish: opts.NewListOpts(nil),
+ securityOpt: opts.NewListOpts(nil),
+ storageOpt: opts.NewListOpts(nil),
+ sysctls: opts.NewMapOpts(nil, opts.ValidateSysctl),
+ tmpfs: opts.NewListOpts(nil),
+ ulimits: opts.NewUlimitOpt(nil),
+ volumes: opts.NewListOpts(nil),
+ volumesFrom: opts.NewListOpts(nil),
+ }
+
+ // General purpose flags
+ flags.VarP(&copts.attach, "attach", "a", "Attach to STDIN, STDOUT or STDERR")
+ flags.Var(&copts.deviceCgroupRules, "device-cgroup-rule", "Add a rule to the cgroup allowed devices list")
+ flags.Var(&copts.devices, "device", "Add a host device to the container")
+ flags.VarP(&copts.env, "env", "e", "Set environment variables")
+ flags.Var(&copts.envFile, "env-file", "Read in a file of environment variables")
+ flags.StringVar(&copts.entrypoint, "entrypoint", "", "Overwrite the default ENTRYPOINT of the image")
+ flags.Var(&copts.groupAdd, "group-add", "Add additional groups to join")
+ flags.StringVarP(&copts.hostname, "hostname", "h", "", "Container host name")
+ flags.BoolVarP(&copts.stdin, "interactive", "i", false, "Keep STDIN open even if not attached")
+ flags.VarP(&copts.labels, "label", "l", "Set meta data on a container")
+ flags.Var(&copts.labelsFile, "label-file", "Read in a line delimited file of labels")
+ flags.BoolVar(&copts.readonlyRootfs, "read-only", false, "Mount the container's root filesystem as read only")
+ flags.StringVar(&copts.restartPolicy, "restart", "no", "Restart policy to apply when a container exits")
+ flags.StringVar(&copts.stopSignal, "stop-signal", signal.DefaultStopSignal, "Signal to stop a container")
+ flags.IntVar(&copts.stopTimeout, "stop-timeout", 0, "Timeout (in seconds) to stop a container")
+ flags.SetAnnotation("stop-timeout", "version", []string{"1.25"})
+ flags.Var(copts.sysctls, "sysctl", "Sysctl options")
+ flags.BoolVarP(&copts.tty, "tty", "t", false, "Allocate a pseudo-TTY")
+ flags.Var(copts.ulimits, "ulimit", "Ulimit options")
+ flags.StringVarP(&copts.user, "user", "u", "", "Username or UID (format: <name|uid>[:<group|gid>])")
+ flags.StringVarP(&copts.workingDir, "workdir", "w", "", "Working directory inside the container")
+ flags.BoolVar(&copts.autoRemove, "rm", false, "Automatically remove the container when it exits")
+
+ // Security
+ flags.Var(&copts.capAdd, "cap-add", "Add Linux capabilities")
+ flags.Var(&copts.capDrop, "cap-drop", "Drop Linux capabilities")
+ flags.BoolVar(&copts.privileged, "privileged", false, "Give extended privileges to this container")
+ flags.Var(&copts.securityOpt, "security-opt", "Security Options")
+ flags.StringVar(&copts.usernsMode, "userns", "", "User namespace to use")
+
+ // Network and port publishing flag
+ flags.Var(&copts.extraHosts, "add-host", "Add a custom host-to-IP mapping (host:ip)")
+ flags.Var(&copts.dns, "dns", "Set custom DNS servers")
+ // We allow for both "--dns-opt" and "--dns-option", although the latter is the recommended way.
+ // This is to be consistent with service create/update
+ flags.Var(&copts.dnsOptions, "dns-opt", "Set DNS options")
+ flags.Var(&copts.dnsOptions, "dns-option", "Set DNS options")
+ flags.MarkHidden("dns-opt")
+ flags.Var(&copts.dnsSearch, "dns-search", "Set custom DNS search domains")
+ flags.Var(&copts.expose, "expose", "Expose a port or a range of ports")
+ flags.StringVar(&copts.ipv4Address, "ip", "", "IPv4 address (e.g., 172.30.100.104)")
+ flags.StringVar(&copts.ipv6Address, "ip6", "", "IPv6 address (e.g., 2001:db8::33)")
+ flags.Var(&copts.links, "link", "Add link to another container")
+ flags.Var(&copts.linkLocalIPs, "link-local-ip", "Container IPv4/IPv6 link-local addresses")
+ flags.StringVar(&copts.macAddress, "mac-address", "", "Container MAC address (e.g., 92:d0:c6:0a:29:33)")
+ flags.VarP(&copts.publish, "publish", "p", "Publish a container's port(s) to the host")
+ flags.BoolVarP(&copts.publishAll, "publish-all", "P", false, "Publish all exposed ports to random ports")
+ // We allow for both "--net" and "--network", although the latter is the recommended way.
+ flags.StringVar(&copts.netMode, "net", "default", "Connect a container to a network")
+ flags.StringVar(&copts.netMode, "network", "default", "Connect a container to a network")
+ flags.MarkHidden("net")
+ // We allow for both "--net-alias" and "--network-alias", although the latter is the recommended way.
+ flags.Var(&copts.aliases, "net-alias", "Add network-scoped alias for the container")
+ flags.Var(&copts.aliases, "network-alias", "Add network-scoped alias for the container")
+ flags.MarkHidden("net-alias")
+
+ // Logging and storage
+ flags.StringVar(&copts.loggingDriver, "log-driver", "", "Logging driver for the container")
+ flags.StringVar(&copts.volumeDriver, "volume-driver", "", "Optional volume driver for the container")
+ flags.Var(&copts.loggingOpts, "log-opt", "Log driver options")
+ flags.Var(&copts.storageOpt, "storage-opt", "Storage driver options for the container")
+ flags.Var(&copts.tmpfs, "tmpfs", "Mount a tmpfs directory")
+ flags.Var(&copts.volumesFrom, "volumes-from", "Mount volumes from the specified container(s)")
+ flags.VarP(&copts.volumes, "volume", "v", "Bind mount a volume")
+ flags.Var(&copts.mounts, "mount", "Attach a filesystem mount to the container")
+
+ // Health-checking
+ flags.StringVar(&copts.healthCmd, "health-cmd", "", "Command to run to check health")
+ flags.DurationVar(&copts.healthInterval, "health-interval", 0, "Time between running the check (ms|s|m|h) (default 0s)")
+ flags.IntVar(&copts.healthRetries, "health-retries", 0, "Consecutive failures needed to report unhealthy")
+ flags.DurationVar(&copts.healthTimeout, "health-timeout", 0, "Maximum time to allow one check to run (ms|s|m|h) (default 0s)")
+ flags.DurationVar(&copts.healthStartPeriod, "health-start-period", 0, "Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)")
+ flags.SetAnnotation("health-start-period", "version", []string{"1.29"})
+ flags.BoolVar(&copts.noHealthcheck, "no-healthcheck", false, "Disable any container-specified HEALTHCHECK")
+
+ // Resource management
+ flags.Uint16Var(&copts.blkioWeight, "blkio-weight", 0, "Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)")
+ flags.Var(&copts.blkioWeightDevice, "blkio-weight-device", "Block IO weight (relative device weight)")
+ flags.StringVar(&copts.containerIDFile, "cidfile", "", "Write the container ID to the file")
+ flags.StringVar(&copts.cpusetCpus, "cpuset-cpus", "", "CPUs in which to allow execution (0-3, 0,1)")
+ flags.StringVar(&copts.cpusetMems, "cpuset-mems", "", "MEMs in which to allow execution (0-3, 0,1)")
+ flags.Int64Var(&copts.cpuCount, "cpu-count", 0, "CPU count (Windows only)")
+ flags.SetAnnotation("cpu-count", "ostype", []string{"windows"})
+ flags.Int64Var(&copts.cpuPercent, "cpu-percent", 0, "CPU percent (Windows only)")
+ flags.SetAnnotation("cpu-percent", "ostype", []string{"windows"})
+ flags.Int64Var(&copts.cpuPeriod, "cpu-period", 0, "Limit CPU CFS (Completely Fair Scheduler) period")
+ flags.Int64Var(&copts.cpuQuota, "cpu-quota", 0, "Limit CPU CFS (Completely Fair Scheduler) quota")
+ flags.Int64Var(&copts.cpuRealtimePeriod, "cpu-rt-period", 0, "Limit CPU real-time period in microseconds")
+ flags.SetAnnotation("cpu-rt-period", "version", []string{"1.25"})
+ flags.Int64Var(&copts.cpuRealtimeRuntime, "cpu-rt-runtime", 0, "Limit CPU real-time runtime in microseconds")
+ flags.SetAnnotation("cpu-rt-runtime", "version", []string{"1.25"})
+ flags.Int64VarP(&copts.cpuShares, "cpu-shares", "c", 0, "CPU shares (relative weight)")
+ flags.Var(&copts.cpus, "cpus", "Number of CPUs")
+ flags.SetAnnotation("cpus", "version", []string{"1.25"})
+ flags.Var(&copts.deviceReadBps, "device-read-bps", "Limit read rate (bytes per second) from a device")
+ flags.Var(&copts.deviceReadIOps, "device-read-iops", "Limit read rate (IO per second) from a device")
+ flags.Var(&copts.deviceWriteBps, "device-write-bps", "Limit write rate (bytes per second) to a device")
+ flags.Var(&copts.deviceWriteIOps, "device-write-iops", "Limit write rate (IO per second) to a device")
+ flags.Var(&copts.ioMaxBandwidth, "io-maxbandwidth", "Maximum IO bandwidth limit for the system drive (Windows only)")
+ flags.SetAnnotation("io-maxbandwidth", "ostype", []string{"windows"})
+ flags.Uint64Var(&copts.ioMaxIOps, "io-maxiops", 0, "Maximum IOps limit for the system drive (Windows only)")
+ flags.SetAnnotation("io-maxiops", "ostype", []string{"windows"})
+ flags.Var(&copts.kernelMemory, "kernel-memory", "Kernel memory limit")
+ flags.VarP(&copts.memory, "memory", "m", "Memory limit")
+ flags.Var(&copts.memoryReservation, "memory-reservation", "Memory soft limit")
+ flags.Var(&copts.memorySwap, "memory-swap", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap")
+ flags.Int64Var(&copts.swappiness, "memory-swappiness", -1, "Tune container memory swappiness (0 to 100)")
+ flags.BoolVar(&copts.oomKillDisable, "oom-kill-disable", false, "Disable OOM Killer")
+ flags.IntVar(&copts.oomScoreAdj, "oom-score-adj", 0, "Tune host's OOM preferences (-1000 to 1000)")
+ flags.Int64Var(&copts.pidsLimit, "pids-limit", 0, "Tune container pids limit (set -1 for unlimited)")
+
+ // Low-level execution (cgroups, namespaces, ...)
+ flags.StringVar(&copts.cgroupParent, "cgroup-parent", "", "Optional parent cgroup for the container")
+ flags.StringVar(&copts.ipcMode, "ipc", "", "IPC namespace to use")
+ flags.StringVar(&copts.isolation, "isolation", "", "Container isolation technology")
+ flags.StringVar(&copts.pidMode, "pid", "", "PID namespace to use")
+ flags.Var(&copts.shmSize, "shm-size", "Size of /dev/shm")
+ flags.StringVar(&copts.utsMode, "uts", "", "UTS namespace to use")
+ flags.StringVar(&copts.runtime, "runtime", "", "Runtime to use for this container")
+
+ flags.BoolVar(&copts.init, "init", false, "Run an init inside the container that forwards signals and reaps processes")
+ flags.SetAnnotation("init", "version", []string{"1.25"})
+ return copts
+}
+
+type containerConfig struct {
+ Config *container.Config
+ HostConfig *container.HostConfig
+ NetworkingConfig *networktypes.NetworkingConfig
+}
+
+// parse parses the args for the specified command and generates a Config,
+// a HostConfig and returns them with the specified command.
+// If the specified args are not valid, it will return an error.
+// nolint: gocyclo
+func parse(flags *pflag.FlagSet, copts *containerOptions) (*containerConfig, error) {
+ var (
+ attachStdin = copts.attach.Get("stdin")
+ attachStdout = copts.attach.Get("stdout")
+ attachStderr = copts.attach.Get("stderr")
+ )
+
+ // Validate the input mac address
+ if copts.macAddress != "" {
+ if _, err := opts.ValidateMACAddress(copts.macAddress); err != nil {
+ return nil, errors.Errorf("%s is not a valid mac address", copts.macAddress)
+ }
+ }
+ if copts.stdin {
+ attachStdin = true
+ }
+ // If -a is not set, attach to stdout and stderr
+ if copts.attach.Len() == 0 {
+ attachStdout = true
+ attachStderr = true
+ }
+
+ var err error
+
+ swappiness := copts.swappiness
+ if swappiness != -1 && (swappiness < 0 || swappiness > 100) {
+ return nil, errors.Errorf("invalid value: %d. Valid memory swappiness range is 0-100", swappiness)
+ }
+
+ mounts := copts.mounts.Value()
+ if len(mounts) > 0 && copts.volumeDriver != "" {
+ logrus.Warn("`--volume-driver` is ignored for volumes specified via `--mount`. Use `--mount type=volume,volume-driver=...` instead.")
+ }
+ var binds []string
+ volumes := copts.volumes.GetMap()
+ // add any bind targets to the list of container volumes
+ for bind := range copts.volumes.GetMap() {
+ parsed, _ := loader.ParseVolume(bind)
+ if parsed.Source != "" {
+ // after creating the bind mount we want to delete it from the copts.volumes values because
+ // we do not want bind mounts being committed to image configs
+ binds = append(binds, bind)
+ // We should delete from the map (`volumes`) here, as deleting from copts.volumes will not work if
+ // there are duplicates entries.
+ delete(volumes, bind)
+ }
+ }
+
+ // Can't evaluate options passed into --tmpfs until we actually mount
+ tmpfs := make(map[string]string)
+ for _, t := range copts.tmpfs.GetAll() {
+ if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
+ tmpfs[arr[0]] = arr[1]
+ } else {
+ tmpfs[arr[0]] = ""
+ }
+ }
+
+ var (
+ runCmd strslice.StrSlice
+ entrypoint strslice.StrSlice
+ )
+
+ if len(copts.Args) > 0 {
+ runCmd = strslice.StrSlice(copts.Args)
+ }
+
+ if copts.entrypoint != "" {
+ entrypoint = strslice.StrSlice{copts.entrypoint}
+ } else if flags.Changed("entrypoint") {
+ // if `--entrypoint=` is parsed then Entrypoint is reset
+ entrypoint = []string{""}
+ }
+
+ ports, portBindings, err := nat.ParsePortSpecs(copts.publish.GetAll())
+ if err != nil {
+ return nil, err
+ }
+
+ // Merge in exposed ports to the map of published ports
+ for _, e := range copts.expose.GetAll() {
+ if strings.Contains(e, ":") {
+ return nil, errors.Errorf("invalid port format for --expose: %s", e)
+ }
+ //support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>]
+ proto, port := nat.SplitProtoPort(e)
+ //parse the start and end port and create a sequence of ports to expose
+ //if expose a port, the start and end port are the same
+ start, end, err := nat.ParsePortRange(port)
+ if err != nil {
+ return nil, errors.Errorf("invalid range format for --expose: %s, error: %s", e, err)
+ }
+ for i := start; i <= end; i++ {
+ p, err := nat.NewPort(proto, strconv.FormatUint(i, 10))
+ if err != nil {
+ return nil, err
+ }
+ if _, exists := ports[p]; !exists {
+ ports[p] = struct{}{}
+ }
+ }
+ }
+
+ // parse device mappings
+ deviceMappings := []container.DeviceMapping{}
+ for _, device := range copts.devices.GetAll() {
+ deviceMapping, err := parseDevice(device)
+ if err != nil {
+ return nil, err
+ }
+ deviceMappings = append(deviceMappings, deviceMapping)
+ }
+
+ // collect all the environment variables for the container
+ envVariables, err := opts.ReadKVStrings(copts.envFile.GetAll(), copts.env.GetAll())
+ if err != nil {
+ return nil, err
+ }
+
+ // collect all the labels for the container
+ labels, err := opts.ReadKVStrings(copts.labelsFile.GetAll(), copts.labels.GetAll())
+ if err != nil {
+ return nil, err
+ }
+
+ ipcMode := container.IpcMode(copts.ipcMode)
+ if !ipcMode.Valid() {
+ return nil, errors.Errorf("--ipc: invalid IPC mode")
+ }
+
+ pidMode := container.PidMode(copts.pidMode)
+ if !pidMode.Valid() {
+ return nil, errors.Errorf("--pid: invalid PID mode")
+ }
+
+ utsMode := container.UTSMode(copts.utsMode)
+ if !utsMode.Valid() {
+ return nil, errors.Errorf("--uts: invalid UTS mode")
+ }
+
+ usernsMode := container.UsernsMode(copts.usernsMode)
+ if !usernsMode.Valid() {
+ return nil, errors.Errorf("--userns: invalid USER mode")
+ }
+
+ restartPolicy, err := opts.ParseRestartPolicy(copts.restartPolicy)
+ if err != nil {
+ return nil, err
+ }
+
+ loggingOpts, err := parseLoggingOpts(copts.loggingDriver, copts.loggingOpts.GetAll())
+ if err != nil {
+ return nil, err
+ }
+
+ securityOpts, err := parseSecurityOpts(copts.securityOpt.GetAll())
+ if err != nil {
+ return nil, err
+ }
+
+ storageOpts, err := parseStorageOpts(copts.storageOpt.GetAll())
+ if err != nil {
+ return nil, err
+ }
+
+ // Healthcheck
+ var healthConfig *container.HealthConfig
+ haveHealthSettings := copts.healthCmd != "" ||
+ copts.healthInterval != 0 ||
+ copts.healthTimeout != 0 ||
+ copts.healthStartPeriod != 0 ||
+ copts.healthRetries != 0
+ if copts.noHealthcheck {
+ if haveHealthSettings {
+ return nil, errors.Errorf("--no-healthcheck conflicts with --health-* options")
+ }
+ test := strslice.StrSlice{"NONE"}
+ healthConfig = &container.HealthConfig{Test: test}
+ } else if haveHealthSettings {
+ var probe strslice.StrSlice
+ if copts.healthCmd != "" {
+ args := []string{"CMD-SHELL", copts.healthCmd}
+ probe = strslice.StrSlice(args)
+ }
+ if copts.healthInterval < 0 {
+ return nil, errors.Errorf("--health-interval cannot be negative")
+ }
+ if copts.healthTimeout < 0 {
+ return nil, errors.Errorf("--health-timeout cannot be negative")
+ }
+ if copts.healthRetries < 0 {
+ return nil, errors.Errorf("--health-retries cannot be negative")
+ }
+ if copts.healthStartPeriod < 0 {
+ return nil, fmt.Errorf("--health-start-period cannot be negative")
+ }
+
+ healthConfig = &container.HealthConfig{
+ Test: probe,
+ Interval: copts.healthInterval,
+ Timeout: copts.healthTimeout,
+ StartPeriod: copts.healthStartPeriod,
+ Retries: copts.healthRetries,
+ }
+ }
+
+ resources := container.Resources{
+ CgroupParent: copts.cgroupParent,
+ Memory: copts.memory.Value(),
+ MemoryReservation: copts.memoryReservation.Value(),
+ MemorySwap: copts.memorySwap.Value(),
+ MemorySwappiness: &copts.swappiness,
+ KernelMemory: copts.kernelMemory.Value(),
+ OomKillDisable: &copts.oomKillDisable,
+ NanoCPUs: copts.cpus.Value(),
+ CPUCount: copts.cpuCount,
+ CPUPercent: copts.cpuPercent,
+ CPUShares: copts.cpuShares,
+ CPUPeriod: copts.cpuPeriod,
+ CpusetCpus: copts.cpusetCpus,
+ CpusetMems: copts.cpusetMems,
+ CPUQuota: copts.cpuQuota,
+ CPURealtimePeriod: copts.cpuRealtimePeriod,
+ CPURealtimeRuntime: copts.cpuRealtimeRuntime,
+ PidsLimit: copts.pidsLimit,
+ BlkioWeight: copts.blkioWeight,
+ BlkioWeightDevice: copts.blkioWeightDevice.GetList(),
+ BlkioDeviceReadBps: copts.deviceReadBps.GetList(),
+ BlkioDeviceWriteBps: copts.deviceWriteBps.GetList(),
+ BlkioDeviceReadIOps: copts.deviceReadIOps.GetList(),
+ BlkioDeviceWriteIOps: copts.deviceWriteIOps.GetList(),
+ IOMaximumIOps: copts.ioMaxIOps,
+ IOMaximumBandwidth: uint64(copts.ioMaxBandwidth),
+ Ulimits: copts.ulimits.GetList(),
+ DeviceCgroupRules: copts.deviceCgroupRules.GetAll(),
+ Devices: deviceMappings,
+ }
+
+ config := &container.Config{
+ Hostname: copts.hostname,
+ ExposedPorts: ports,
+ User: copts.user,
+ Tty: copts.tty,
+ // TODO: deprecated, it comes from -n, --networking
+ // it's still needed internally to set the network to disabled
+ // if e.g. bridge is none in daemon opts, and in inspect
+ NetworkDisabled: false,
+ OpenStdin: copts.stdin,
+ AttachStdin: attachStdin,
+ AttachStdout: attachStdout,
+ AttachStderr: attachStderr,
+ Env: envVariables,
+ Cmd: runCmd,
+ Image: copts.Image,
+ Volumes: volumes,
+ MacAddress: copts.macAddress,
+ Entrypoint: entrypoint,
+ WorkingDir: copts.workingDir,
+ Labels: opts.ConvertKVStringsToMap(labels),
+ Healthcheck: healthConfig,
+ }
+ if flags.Changed("stop-signal") {
+ config.StopSignal = copts.stopSignal
+ }
+ if flags.Changed("stop-timeout") {
+ config.StopTimeout = &copts.stopTimeout
+ }
+
+ hostConfig := &container.HostConfig{
+ Binds: binds,
+ ContainerIDFile: copts.containerIDFile,
+ OomScoreAdj: copts.oomScoreAdj,
+ AutoRemove: copts.autoRemove,
+ Privileged: copts.privileged,
+ PortBindings: portBindings,
+ Links: copts.links.GetAll(),
+ PublishAllPorts: copts.publishAll,
+ // Make sure the dns fields are never nil.
+ // New containers don't ever have those fields nil,
+ // but pre created containers can still have those nil values.
+ // See https://github.com/docker/docker/pull/17779
+ // for a more detailed explanation on why we don't want that.
+ DNS: copts.dns.GetAllOrEmpty(),
+ DNSSearch: copts.dnsSearch.GetAllOrEmpty(),
+ DNSOptions: copts.dnsOptions.GetAllOrEmpty(),
+ ExtraHosts: copts.extraHosts.GetAll(),
+ VolumesFrom: copts.volumesFrom.GetAll(),
+ NetworkMode: container.NetworkMode(copts.netMode),
+ IpcMode: ipcMode,
+ PidMode: pidMode,
+ UTSMode: utsMode,
+ UsernsMode: usernsMode,
+ CapAdd: strslice.StrSlice(copts.capAdd.GetAll()),
+ CapDrop: strslice.StrSlice(copts.capDrop.GetAll()),
+ GroupAdd: copts.groupAdd.GetAll(),
+ RestartPolicy: restartPolicy,
+ SecurityOpt: securityOpts,
+ StorageOpt: storageOpts,
+ ReadonlyRootfs: copts.readonlyRootfs,
+ LogConfig: container.LogConfig{Type: copts.loggingDriver, Config: loggingOpts},
+ VolumeDriver: copts.volumeDriver,
+ Isolation: container.Isolation(copts.isolation),
+ ShmSize: copts.shmSize.Value(),
+ Resources: resources,
+ Tmpfs: tmpfs,
+ Sysctls: copts.sysctls.GetAll(),
+ Runtime: copts.runtime,
+ Mounts: mounts,
+ }
+
+ if copts.autoRemove && !hostConfig.RestartPolicy.IsNone() {
+ return nil, errors.Errorf("Conflicting options: --restart and --rm")
+ }
+
+ // only set this value if the user provided the flag, else it should default to nil
+ if flags.Changed("init") {
+ hostConfig.Init = &copts.init
+ }
+
+ // When allocating stdin in attached mode, close stdin at client disconnect
+ if config.OpenStdin && config.AttachStdin {
+ config.StdinOnce = true
+ }
+
+ networkingConfig := &networktypes.NetworkingConfig{
+ EndpointsConfig: make(map[string]*networktypes.EndpointSettings),
+ }
+
+ if copts.ipv4Address != "" || copts.ipv6Address != "" || copts.linkLocalIPs.Len() > 0 {
+ epConfig := &networktypes.EndpointSettings{}
+ networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] = epConfig
+
+ epConfig.IPAMConfig = &networktypes.EndpointIPAMConfig{
+ IPv4Address: copts.ipv4Address,
+ IPv6Address: copts.ipv6Address,
+ }
+
+ if copts.linkLocalIPs.Len() > 0 {
+ epConfig.IPAMConfig.LinkLocalIPs = make([]string, copts.linkLocalIPs.Len())
+ copy(epConfig.IPAMConfig.LinkLocalIPs, copts.linkLocalIPs.GetAll())
+ }
+ }
+
+ if hostConfig.NetworkMode.IsUserDefined() && len(hostConfig.Links) > 0 {
+ epConfig := networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)]
+ if epConfig == nil {
+ epConfig = &networktypes.EndpointSettings{}
+ }
+ epConfig.Links = make([]string, len(hostConfig.Links))
+ copy(epConfig.Links, hostConfig.Links)
+ networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] = epConfig
+ }
+
+ if copts.aliases.Len() > 0 {
+ epConfig := networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)]
+ if epConfig == nil {
+ epConfig = &networktypes.EndpointSettings{}
+ }
+ epConfig.Aliases = make([]string, copts.aliases.Len())
+ copy(epConfig.Aliases, copts.aliases.GetAll())
+ networkingConfig.EndpointsConfig[string(hostConfig.NetworkMode)] = epConfig
+ }
+
+ return &containerConfig{
+ Config: config,
+ HostConfig: hostConfig,
+ NetworkingConfig: networkingConfig,
+ }, nil
+}
+
+func parseLoggingOpts(loggingDriver string, loggingOpts []string) (map[string]string, error) {
+ loggingOptsMap := opts.ConvertKVStringsToMap(loggingOpts)
+ if loggingDriver == "none" && len(loggingOpts) > 0 {
+ return map[string]string{}, errors.Errorf("invalid logging opts for driver %s", loggingDriver)
+ }
+ return loggingOptsMap, nil
+}
+
+// takes a local seccomp daemon, reads the file contents for sending to the daemon
+func parseSecurityOpts(securityOpts []string) ([]string, error) {
+ for key, opt := range securityOpts {
+ con := strings.SplitN(opt, "=", 2)
+ if len(con) == 1 && con[0] != "no-new-privileges" {
+ if strings.Contains(opt, ":") {
+ con = strings.SplitN(opt, ":", 2)
+ } else {
+ return securityOpts, errors.Errorf("Invalid --security-opt: %q", opt)
+ }
+ }
+ if con[0] == "seccomp" && con[1] != "unconfined" {
+ f, err := ioutil.ReadFile(con[1])
+ if err != nil {
+ return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", con[1], err)
+ }
+ b := bytes.NewBuffer(nil)
+ if err := json.Compact(b, f); err != nil {
+ return securityOpts, errors.Errorf("compacting json for seccomp profile (%s) failed: %v", con[1], err)
+ }
+ securityOpts[key] = fmt.Sprintf("seccomp=%s", b.Bytes())
+ }
+ }
+
+ return securityOpts, nil
+}
+
+// parses storage options per container into a map
+func parseStorageOpts(storageOpts []string) (map[string]string, error) {
+ m := make(map[string]string)
+ for _, option := range storageOpts {
+ if strings.Contains(option, "=") {
+ opt := strings.SplitN(option, "=", 2)
+ m[opt[0]] = opt[1]
+ } else {
+ return nil, errors.Errorf("invalid storage option")
+ }
+ }
+ return m, nil
+}
+
+// parseDevice parses a device mapping string to a container.DeviceMapping struct
+func parseDevice(device string) (container.DeviceMapping, error) {
+ src := ""
+ dst := ""
+ permissions := "rwm"
+ arr := strings.Split(device, ":")
+ switch len(arr) {
+ case 3:
+ permissions = arr[2]
+ fallthrough
+ case 2:
+ if validDeviceMode(arr[1]) {
+ permissions = arr[1]
+ } else {
+ dst = arr[1]
+ }
+ fallthrough
+ case 1:
+ src = arr[0]
+ default:
+ return container.DeviceMapping{}, errors.Errorf("invalid device specification: %s", device)
+ }
+
+ if dst == "" {
+ dst = src
+ }
+
+ deviceMapping := container.DeviceMapping{
+ PathOnHost: src,
+ PathInContainer: dst,
+ CgroupPermissions: permissions,
+ }
+ return deviceMapping, nil
+}
+
+// validateDeviceCgroupRule validates a device cgroup rule string format
+// It will make sure 'val' is in the form:
+// 'type major:minor mode'
+func validateDeviceCgroupRule(val string) (string, error) {
+ if deviceCgroupRuleRegexp.MatchString(val) {
+ return val, nil
+ }
+
+ return val, errors.Errorf("invalid device cgroup format '%s'", val)
+}
+
+// validDeviceMode checks if the mode for device is valid or not.
+// Valid mode is a composition of r (read), w (write), and m (mknod).
+func validDeviceMode(mode string) bool {
+ var legalDeviceMode = map[rune]bool{
+ 'r': true,
+ 'w': true,
+ 'm': true,
+ }
+ if mode == "" {
+ return false
+ }
+ for _, c := range mode {
+ if !legalDeviceMode[c] {
+ return false
+ }
+ legalDeviceMode[c] = false
+ }
+ return true
+}
+
+// validateDevice validates a path for devices
+// It will make sure 'val' is in the form:
+// [host-dir:]container-path[:mode]
+// It also validates the device mode.
+func validateDevice(val string) (string, error) {
+ return validatePath(val, validDeviceMode)
+}
+
+func validatePath(val string, validator func(string) bool) (string, error) {
+ var containerPath string
+ var mode string
+
+ if strings.Count(val, ":") > 2 {
+ return val, errors.Errorf("bad format for path: %s", val)
+ }
+
+ split := strings.SplitN(val, ":", 3)
+ if split[0] == "" {
+ return val, errors.Errorf("bad format for path: %s", val)
+ }
+ switch len(split) {
+ case 1:
+ containerPath = split[0]
+ val = path.Clean(containerPath)
+ case 2:
+ if isValid := validator(split[1]); isValid {
+ containerPath = split[0]
+ mode = split[1]
+ val = fmt.Sprintf("%s:%s", path.Clean(containerPath), mode)
+ } else {
+ containerPath = split[1]
+ val = fmt.Sprintf("%s:%s", split[0], path.Clean(containerPath))
+ }
+ case 3:
+ containerPath = split[1]
+ mode = split[2]
+ if isValid := validator(split[2]); !isValid {
+ return val, errors.Errorf("bad mode specified: %s", mode)
+ }
+ val = fmt.Sprintf("%s:%s:%s", split[0], containerPath, mode)
+ }
+
+ if !path.IsAbs(containerPath) {
+ return val, errors.Errorf("%s is not an absolute path", containerPath)
+ }
+ return val, nil
+}
+
+// validateAttach validates that the specified string is a valid attach option.
+func validateAttach(val string) (string, error) {
+ s := strings.ToLower(val)
+ for _, str := range []string{"stdin", "stdout", "stderr"} {
+ if s == str {
+ return s, nil
+ }
+ }
+ return val, errors.Errorf("valid streams are STDIN, STDOUT and STDERR")
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/pause.go b/vendor/github.com/docker/cli/cli/command/container/pause.go
new file mode 100644
index 0000000..9dc404d
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/pause.go
@@ -0,0 +1,49 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type pauseOptions struct {
+ containers []string
+}
+
+// NewPauseCommand creates a new cobra.Command for `docker pause`
+func NewPauseCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts pauseOptions
+
+ return &cobra.Command{
+ Use: "pause CONTAINER [CONTAINER...]",
+ Short: "Pause all processes within one or more containers",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.containers = args
+ return runPause(dockerCli, &opts)
+ },
+ }
+}
+
+func runPause(dockerCli *command.DockerCli, opts *pauseOptions) error {
+ ctx := context.Background()
+
+ var errs []string
+ errChan := parallelOperation(ctx, opts.containers, dockerCli.Client().ContainerPause)
+ for _, container := range opts.containers {
+ if err := <-errChan; err != nil {
+ errs = append(errs, err.Error())
+ continue
+ }
+ fmt.Fprintln(dockerCli.Out(), container)
+ }
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, "\n"))
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/port.go b/vendor/github.com/docker/cli/cli/command/container/port.go
new file mode 100644
index 0000000..13a1ae4
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/port.go
@@ -0,0 +1,78 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/go-connections/nat"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type portOptions struct {
+ container string
+
+ port string
+}
+
+// NewPortCommand creates a new cobra.Command for `docker port`
+func NewPortCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts portOptions
+
+ cmd := &cobra.Command{
+ Use: "port CONTAINER [PRIVATE_PORT[/PROTO]]",
+ Short: "List port mappings or a specific mapping for the container",
+ Args: cli.RequiresRangeArgs(1, 2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.container = args[0]
+ if len(args) > 1 {
+ opts.port = args[1]
+ }
+ return runPort(dockerCli, &opts)
+ },
+ }
+ return cmd
+}
+
+func runPort(dockerCli *command.DockerCli, opts *portOptions) error {
+ ctx := context.Background()
+
+ c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
+ if err != nil {
+ return err
+ }
+
+ if opts.port != "" {
+ port := opts.port
+ proto := "tcp"
+ parts := strings.SplitN(port, "/", 2)
+
+ if len(parts) == 2 && len(parts[1]) != 0 {
+ port = parts[0]
+ proto = parts[1]
+ }
+ natPort := port + "/" + proto
+ newP, err := nat.NewPort(proto, port)
+ if err != nil {
+ return err
+ }
+ if frontends, exists := c.NetworkSettings.Ports[newP]; exists && frontends != nil {
+ for _, frontend := range frontends {
+ fmt.Fprintf(dockerCli.Out(), "%s:%s\n", frontend.HostIP, frontend.HostPort)
+ }
+ return nil
+ }
+ return errors.Errorf("Error: No public port '%s' published for %s", natPort, opts.container)
+ }
+
+ for from, frontends := range c.NetworkSettings.Ports {
+ for _, frontend := range frontends {
+ fmt.Fprintf(dockerCli.Out(), "%s -> %s:%s\n", from, frontend.HostIP, frontend.HostPort)
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/prune.go b/vendor/github.com/docker/cli/cli/command/container/prune.go
new file mode 100644
index 0000000..38ac647
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/prune.go
@@ -0,0 +1,78 @@
+package container
+
+import (
+ "fmt"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ units "github.com/docker/go-units"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type pruneOptions struct {
+ force bool
+ filter opts.FilterOpt
+}
+
+// NewPruneCommand returns a new cobra prune command for containers
+func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
+ options := pruneOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "prune [OPTIONS]",
+ Short: "Remove all stopped containers",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ spaceReclaimed, output, err := runPrune(dockerCli, options)
+ if err != nil {
+ return err
+ }
+ if output != "" {
+ fmt.Fprintln(dockerCli.Out(), output)
+ }
+ fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
+ return nil
+ },
+ Tags: map[string]string{"version": "1.25"},
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&options.force, "force", "f", false, "Do not prompt for confirmation")
+ flags.Var(&options.filter, "filter", "Provide filter values (e.g. 'until=<timestamp>')")
+
+ return cmd
+}
+
+const warning = `WARNING! This will remove all stopped containers.
+Are you sure you want to continue?`
+
+func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) {
+ pruneFilters := command.PruneFilters(dockerCli, options.filter.Value())
+
+ if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
+ return
+ }
+
+ report, err := dockerCli.Client().ContainersPrune(context.Background(), pruneFilters)
+ if err != nil {
+ return
+ }
+
+ if len(report.ContainersDeleted) > 0 {
+ output = "Deleted Containers:\n"
+ for _, id := range report.ContainersDeleted {
+ output += id + "\n"
+ }
+ spaceReclaimed = report.SpaceReclaimed
+ }
+
+ return
+}
+
+// RunPrune calls the Container Prune API
+// This returns the amount of space reclaimed and a detailed output string
+func RunPrune(dockerCli command.Cli, filter opts.FilterOpt) (uint64, string, error) {
+ return runPrune(dockerCli, pruneOptions{force: true, filter: filter})
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/rename.go b/vendor/github.com/docker/cli/cli/command/container/rename.go
new file mode 100644
index 0000000..ad60bda
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/rename.go
@@ -0,0 +1,51 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type renameOptions struct {
+ oldName string
+ newName string
+}
+
+// NewRenameCommand creates a new cobra.Command for `docker rename`
+func NewRenameCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts renameOptions
+
+ cmd := &cobra.Command{
+ Use: "rename CONTAINER NEW_NAME",
+ Short: "Rename a container",
+ Args: cli.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.oldName = args[0]
+ opts.newName = args[1]
+ return runRename(dockerCli, &opts)
+ },
+ }
+ return cmd
+}
+
+func runRename(dockerCli *command.DockerCli, opts *renameOptions) error {
+ ctx := context.Background()
+
+ oldName := strings.TrimSpace(opts.oldName)
+ newName := strings.TrimSpace(opts.newName)
+
+ if oldName == "" || newName == "" {
+ return errors.New("Error: Neither old nor new names may be empty")
+ }
+
+ if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil {
+ fmt.Fprintln(dockerCli.Err(), err)
+ return errors.Errorf("Error: failed to rename container named %s", oldName)
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/restart.go b/vendor/github.com/docker/cli/cli/command/container/restart.go
new file mode 100644
index 0000000..6e13603
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/restart.go
@@ -0,0 +1,62 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type restartOptions struct {
+ nSeconds int
+ nSecondsChanged bool
+
+ containers []string
+}
+
+// NewRestartCommand creates a new cobra.Command for `docker restart`
+func NewRestartCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts restartOptions
+
+ cmd := &cobra.Command{
+ Use: "restart [OPTIONS] CONTAINER [CONTAINER...]",
+ Short: "Restart one or more containers",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.containers = args
+ opts.nSecondsChanged = cmd.Flags().Changed("time")
+ return runRestart(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.IntVarP(&opts.nSeconds, "time", "t", 10, "Seconds to wait for stop before killing the container")
+ return cmd
+}
+
+func runRestart(dockerCli *command.DockerCli, opts *restartOptions) error {
+ ctx := context.Background()
+ var errs []string
+ var timeout *time.Duration
+ if opts.nSecondsChanged {
+ timeoutValue := time.Duration(opts.nSeconds) * time.Second
+ timeout = &timeoutValue
+ }
+
+ for _, name := range opts.containers {
+ if err := dockerCli.Client().ContainerRestart(ctx, name, timeout); err != nil {
+ errs = append(errs, err.Error())
+ continue
+ }
+ fmt.Fprintln(dockerCli.Out(), name)
+ }
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, "\n"))
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/rm.go b/vendor/github.com/docker/cli/cli/command/container/rm.go
new file mode 100644
index 0000000..a7106ac
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/rm.go
@@ -0,0 +1,73 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type rmOptions struct {
+ rmVolumes bool
+ rmLink bool
+ force bool
+
+ containers []string
+}
+
+// NewRmCommand creates a new cobra.Command for `docker rm`
+func NewRmCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts rmOptions
+
+ cmd := &cobra.Command{
+ Use: "rm [OPTIONS] CONTAINER [CONTAINER...]",
+ Short: "Remove one or more containers",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.containers = args
+ return runRm(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&opts.rmVolumes, "volumes", "v", false, "Remove the volumes associated with the container")
+ flags.BoolVarP(&opts.rmLink, "link", "l", false, "Remove the specified link")
+ flags.BoolVarP(&opts.force, "force", "f", false, "Force the removal of a running container (uses SIGKILL)")
+ return cmd
+}
+
+func runRm(dockerCli *command.DockerCli, opts *rmOptions) error {
+ ctx := context.Background()
+
+ var errs []string
+ options := types.ContainerRemoveOptions{
+ RemoveVolumes: opts.rmVolumes,
+ RemoveLinks: opts.rmLink,
+ Force: opts.force,
+ }
+
+ errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error {
+ container = strings.Trim(container, "/")
+ if container == "" {
+ return errors.New("Container name cannot be empty")
+ }
+ return dockerCli.Client().ContainerRemove(ctx, container, options)
+ })
+
+ for _, name := range opts.containers {
+ if err := <-errChan; err != nil {
+ errs = append(errs, err.Error())
+ continue
+ }
+ fmt.Fprintln(dockerCli.Out(), name)
+ }
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, "\n"))
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/run.go b/vendor/github.com/docker/cli/cli/command/container/run.go
new file mode 100644
index 0000000..56f0d0d
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/run.go
@@ -0,0 +1,337 @@
+package container
+
+import (
+ "fmt"
+ "io"
+ "net/http/httputil"
+ "os"
+ "regexp"
+ "runtime"
+ "strings"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/pkg/promise"
+ "github.com/docker/docker/pkg/signal"
+ "github.com/docker/docker/pkg/term"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "github.com/spf13/pflag"
+ "golang.org/x/net/context"
+)
+
+type runOptions struct {
+ detach bool
+ sigProxy bool
+ name string
+ detachKeys string
+}
+
+// NewRunCommand create a new `docker run` command
+func NewRunCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts runOptions
+ var copts *containerOptions
+
+ cmd := &cobra.Command{
+ Use: "run [OPTIONS] IMAGE [COMMAND] [ARG...]",
+ Short: "Run a command in a new container",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ copts.Image = args[0]
+ if len(args) > 1 {
+ copts.Args = args[1:]
+ }
+ return runRun(dockerCli, cmd.Flags(), &opts, copts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.SetInterspersed(false)
+
+ // These are flags not stored in Config/HostConfig
+ flags.BoolVarP(&opts.detach, "detach", "d", false, "Run container in background and print container ID")
+ flags.BoolVar(&opts.sigProxy, "sig-proxy", true, "Proxy received signals to the process")
+ flags.StringVar(&opts.name, "name", "", "Assign a name to the container")
+ flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container")
+
+ // Add an explicit help that doesn't have a `-h` to prevent the conflict
+ // with hostname
+ flags.Bool("help", false, "Print usage")
+
+ command.AddTrustVerificationFlags(flags)
+ copts = addFlags(flags)
+ return cmd
+}
+
+func warnOnOomKillDisable(hostConfig container.HostConfig, stderr io.Writer) {
+ if hostConfig.OomKillDisable != nil && *hostConfig.OomKillDisable && hostConfig.Memory == 0 {
+ fmt.Fprintln(stderr, "WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.")
+ }
+}
+
+// check the DNS settings passed via --dns against localhost regexp to warn if
+// they are trying to set a DNS to a localhost address
+func warnOnLocalhostDNS(hostConfig container.HostConfig, stderr io.Writer) {
+ for _, dnsIP := range hostConfig.DNS {
+ if isLocalhost(dnsIP) {
+ fmt.Fprintf(stderr, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP)
+ return
+ }
+ }
+}
+
+// IPLocalhost is a regex pattern for IPv4 or IPv6 loopback range.
+const ipLocalhost = `((127\.([0-9]{1,3}\.){2}[0-9]{1,3})|(::1)$)`
+
+var localhostIPRegexp = regexp.MustCompile(ipLocalhost)
+
+// IsLocalhost returns true if ip matches the localhost IP regular expression.
+// Used for determining if nameserver settings are being passed which are
+// localhost addresses
+func isLocalhost(ip string) bool {
+ return localhostIPRegexp.MatchString(ip)
+}
+
+func runRun(dockerCli *command.DockerCli, flags *pflag.FlagSet, ropts *runOptions, copts *containerOptions) error {
+ proxyConfig := dockerCli.ConfigFile().ParseProxyConfig(dockerCli.Client().DaemonHost(), copts.env.GetAll())
+ newEnv := []string{}
+ for k, v := range proxyConfig {
+ if v == nil {
+ newEnv = append(newEnv, k)
+ } else {
+ newEnv = append(newEnv, fmt.Sprintf("%s=%s", k, *v))
+ }
+ }
+ copts.env = *opts.NewListOptsRef(&newEnv, nil)
+ containerConfig, err := parse(flags, copts)
+ // just in case the parse does not exit
+ if err != nil {
+ reportError(dockerCli.Err(), "run", err.Error(), true)
+ return cli.StatusError{StatusCode: 125}
+ }
+ return runContainer(dockerCli, ropts, copts, containerConfig)
+}
+
+// nolint: gocyclo
+func runContainer(dockerCli *command.DockerCli, opts *runOptions, copts *containerOptions, containerConfig *containerConfig) error {
+ config := containerConfig.Config
+ hostConfig := containerConfig.HostConfig
+ stdout, stderr := dockerCli.Out(), dockerCli.Err()
+ client := dockerCli.Client()
+
+ // TODO: pass this as an argument
+ cmdPath := "run"
+
+ warnOnOomKillDisable(*hostConfig, stderr)
+ warnOnLocalhostDNS(*hostConfig, stderr)
+
+ config.ArgsEscaped = false
+
+ if !opts.detach {
+ if err := dockerCli.In().CheckTty(config.AttachStdin, config.Tty); err != nil {
+ return err
+ }
+ } else {
+ if copts.attach.Len() != 0 {
+ return errors.New("Conflicting options: -a and -d")
+ }
+
+ config.AttachStdin = false
+ config.AttachStdout = false
+ config.AttachStderr = false
+ config.StdinOnce = false
+ }
+
+ // Disable sigProxy when in TTY mode
+ if config.Tty {
+ opts.sigProxy = false
+ }
+
+ // Telling the Windows daemon the initial size of the tty during start makes
+ // a far better user experience rather than relying on subsequent resizes
+ // to cause things to catch up.
+ if runtime.GOOS == "windows" {
+ hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = dockerCli.Out().GetTtySize()
+ }
+
+ ctx, cancelFun := context.WithCancel(context.Background())
+
+ createResponse, err := createContainer(ctx, dockerCli, containerConfig, opts.name)
+ if err != nil {
+ reportError(stderr, cmdPath, err.Error(), true)
+ return runStartContainerErr(err)
+ }
+ if opts.sigProxy {
+ sigc := ForwardAllSignals(ctx, dockerCli, createResponse.ID)
+ defer signal.StopCatch(sigc)
+ }
+
+ var (
+ waitDisplayID chan struct{}
+ errCh chan error
+ )
+ if !config.AttachStdout && !config.AttachStderr {
+ // Make this asynchronous to allow the client to write to stdin before having to read the ID
+ waitDisplayID = make(chan struct{})
+ go func() {
+ defer close(waitDisplayID)
+ fmt.Fprintln(stdout, createResponse.ID)
+ }()
+ }
+ attach := config.AttachStdin || config.AttachStdout || config.AttachStderr
+ if attach {
+ if opts.detachKeys != "" {
+ dockerCli.ConfigFile().DetachKeys = opts.detachKeys
+ }
+
+ close, err := attachContainer(ctx, dockerCli, &errCh, config, createResponse.ID)
+ defer close()
+ if err != nil {
+ return err
+ }
+ }
+
+ statusChan := waitExitOrRemoved(ctx, dockerCli, createResponse.ID, copts.autoRemove)
+
+ //start the container
+ if err := client.ContainerStart(ctx, createResponse.ID, types.ContainerStartOptions{}); err != nil {
+ // If we have hijackedIOStreamer, we should notify
+ // hijackedIOStreamer we are going to exit and wait
+ // to avoid the terminal are not restored.
+ if attach {
+ cancelFun()
+ <-errCh
+ }
+
+ reportError(stderr, cmdPath, err.Error(), false)
+ if copts.autoRemove {
+ // wait container to be removed
+ <-statusChan
+ }
+ return runStartContainerErr(err)
+ }
+
+ if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && dockerCli.Out().IsTerminal() {
+ if err := MonitorTtySize(ctx, dockerCli, createResponse.ID, false); err != nil {
+ fmt.Fprintln(stderr, "Error monitoring TTY size:", err)
+ }
+ }
+
+ if errCh != nil {
+ if err := <-errCh; err != nil {
+ if _, ok := err.(term.EscapeError); ok {
+ // The user entered the detach escape sequence.
+ return nil
+ }
+
+ logrus.Debugf("Error hijack: %s", err)
+ return err
+ }
+ }
+
+ // Detached mode: wait for the id to be displayed and return.
+ if !config.AttachStdout && !config.AttachStderr {
+ // Detached mode
+ <-waitDisplayID
+ return nil
+ }
+
+ status := <-statusChan
+ if status != 0 {
+ return cli.StatusError{StatusCode: status}
+ }
+ return nil
+}
+
+func attachContainer(
+ ctx context.Context,
+ dockerCli command.Cli,
+ errCh *chan error,
+ config *container.Config,
+ containerID string,
+) (func(), error) {
+ stdout, stderr := dockerCli.Out(), dockerCli.Err()
+ var (
+ out, cerr io.Writer
+ in io.ReadCloser
+ )
+ if config.AttachStdin {
+ in = dockerCli.In()
+ }
+ if config.AttachStdout {
+ out = stdout
+ }
+ if config.AttachStderr {
+ if config.Tty {
+ cerr = stdout
+ } else {
+ cerr = stderr
+ }
+ }
+
+ options := types.ContainerAttachOptions{
+ Stream: true,
+ Stdin: config.AttachStdin,
+ Stdout: config.AttachStdout,
+ Stderr: config.AttachStderr,
+ DetachKeys: dockerCli.ConfigFile().DetachKeys,
+ }
+
+ resp, errAttach := dockerCli.Client().ContainerAttach(ctx, containerID, options)
+ if errAttach != nil && errAttach != httputil.ErrPersistEOF {
+ // ContainerAttach returns an ErrPersistEOF (connection closed)
+ // means server met an error and put it in Hijacked connection
+ // keep the error and read detailed error message from hijacked connection later
+ return nil, errAttach
+ }
+
+ *errCh = promise.Go(func() error {
+ streamer := hijackedIOStreamer{
+ streams: dockerCli,
+ inputStream: in,
+ outputStream: out,
+ errorStream: cerr,
+ resp: resp,
+ tty: config.Tty,
+ detachKeys: options.DetachKeys,
+ }
+
+ if errHijack := streamer.stream(ctx); errHijack != nil {
+ return errHijack
+ }
+ return errAttach
+ })
+ return resp.Close, nil
+}
+
+// reportError is a utility method that prints a user-friendly message
+// containing the error that occurred during parsing and a suggestion to get help
+func reportError(stderr io.Writer, name string, str string, withHelp bool) {
+ str = strings.TrimSuffix(str, ".") + "."
+ if withHelp {
+ str += "\nSee '" + os.Args[0] + " " + name + " --help'."
+ }
+ fmt.Fprintf(stderr, "%s: %s\n", os.Args[0], str)
+}
+
+// if container start fails with 'not found'/'no such' error, return 127
+// if container start fails with 'permission denied' error, return 126
+// return 125 for generic docker daemon failures
+func runStartContainerErr(err error) error {
+ trimmedErr := strings.TrimPrefix(err.Error(), "Error response from daemon: ")
+ statusError := cli.StatusError{StatusCode: 125}
+ if strings.Contains(trimmedErr, "executable file not found") ||
+ strings.Contains(trimmedErr, "no such file or directory") ||
+ strings.Contains(trimmedErr, "system cannot find the file specified") {
+ statusError = cli.StatusError{StatusCode: 127}
+ } else if strings.Contains(trimmedErr, syscall.EACCES.Error()) {
+ statusError = cli.StatusError{StatusCode: 126}
+ }
+
+ return statusError
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/start.go b/vendor/github.com/docker/cli/cli/command/container/start.go
new file mode 100644
index 0000000..6cd4751
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/start.go
@@ -0,0 +1,195 @@
+package container
+
+import (
+ "fmt"
+ "io"
+ "net/http/httputil"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/promise"
+ "github.com/docker/docker/pkg/signal"
+ "github.com/docker/docker/pkg/term"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type startOptions struct {
+ attach bool
+ openStdin bool
+ detachKeys string
+ checkpoint string
+ checkpointDir string
+
+ containers []string
+}
+
+// NewStartCommand creates a new cobra.Command for `docker start`
+func NewStartCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts startOptions
+
+ cmd := &cobra.Command{
+ Use: "start [OPTIONS] CONTAINER [CONTAINER...]",
+ Short: "Start one or more stopped containers",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.containers = args
+ return runStart(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&opts.attach, "attach", "a", false, "Attach STDOUT/STDERR and forward signals")
+ flags.BoolVarP(&opts.openStdin, "interactive", "i", false, "Attach container's STDIN")
+ flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container")
+
+ flags.StringVar(&opts.checkpoint, "checkpoint", "", "Restore from this checkpoint")
+ flags.SetAnnotation("checkpoint", "experimental", nil)
+ flags.StringVar(&opts.checkpointDir, "checkpoint-dir", "", "Use a custom checkpoint storage directory")
+ flags.SetAnnotation("checkpoint-dir", "experimental", nil)
+ return cmd
+}
+
+// nolint: gocyclo
+func runStart(dockerCli *command.DockerCli, opts *startOptions) error {
+ ctx, cancelFun := context.WithCancel(context.Background())
+
+ if opts.attach || opts.openStdin {
+ // We're going to attach to a container.
+ // 1. Ensure we only have one container.
+ if len(opts.containers) > 1 {
+ return errors.New("you cannot start and attach multiple containers at once")
+ }
+
+ // 2. Attach to the container.
+ container := opts.containers[0]
+ c, err := dockerCli.Client().ContainerInspect(ctx, container)
+ if err != nil {
+ return err
+ }
+
+ // We always use c.ID instead of container to maintain consistency during `docker start`
+ if !c.Config.Tty {
+ sigc := ForwardAllSignals(ctx, dockerCli, c.ID)
+ defer signal.StopCatch(sigc)
+ }
+
+ if opts.detachKeys != "" {
+ dockerCli.ConfigFile().DetachKeys = opts.detachKeys
+ }
+
+ options := types.ContainerAttachOptions{
+ Stream: true,
+ Stdin: opts.openStdin && c.Config.OpenStdin,
+ Stdout: true,
+ Stderr: true,
+ DetachKeys: dockerCli.ConfigFile().DetachKeys,
+ }
+
+ var in io.ReadCloser
+
+ if options.Stdin {
+ in = dockerCli.In()
+ }
+
+ resp, errAttach := dockerCli.Client().ContainerAttach(ctx, c.ID, options)
+ if errAttach != nil && errAttach != httputil.ErrPersistEOF {
+ // ContainerAttach return an ErrPersistEOF (connection closed)
+ // means server met an error and already put it in Hijacked connection,
+ // we would keep the error and read the detailed error message from hijacked connection
+ return errAttach
+ }
+ defer resp.Close()
+ cErr := promise.Go(func() error {
+ streamer := hijackedIOStreamer{
+ streams: dockerCli,
+ inputStream: in,
+ outputStream: dockerCli.Out(),
+ errorStream: dockerCli.Err(),
+ resp: resp,
+ tty: c.Config.Tty,
+ detachKeys: options.DetachKeys,
+ }
+
+ errHijack := streamer.stream(ctx)
+ if errHijack == nil {
+ return errAttach
+ }
+ return errHijack
+ })
+
+ // 3. We should open a channel for receiving status code of the container
+ // no matter it's detached, removed on daemon side(--rm) or exit normally.
+ statusChan := waitExitOrRemoved(ctx, dockerCli, c.ID, c.HostConfig.AutoRemove)
+ startOptions := types.ContainerStartOptions{
+ CheckpointID: opts.checkpoint,
+ CheckpointDir: opts.checkpointDir,
+ }
+
+ // 4. Start the container.
+ if err := dockerCli.Client().ContainerStart(ctx, c.ID, startOptions); err != nil {
+ cancelFun()
+ <-cErr
+ if c.HostConfig.AutoRemove {
+ // wait container to be removed
+ <-statusChan
+ }
+ return err
+ }
+
+ // 5. Wait for attachment to break.
+ if c.Config.Tty && dockerCli.Out().IsTerminal() {
+ if err := MonitorTtySize(ctx, dockerCli, c.ID, false); err != nil {
+ fmt.Fprintln(dockerCli.Err(), "Error monitoring TTY size:", err)
+ }
+ }
+ if attachErr := <-cErr; attachErr != nil {
+ if _, ok := err.(term.EscapeError); ok {
+ // The user entered the detach escape sequence.
+ return nil
+ }
+ return attachErr
+ }
+
+ if status := <-statusChan; status != 0 {
+ return cli.StatusError{StatusCode: status}
+ }
+ } else if opts.checkpoint != "" {
+ if len(opts.containers) > 1 {
+ return errors.New("you cannot restore multiple containers at once")
+ }
+ container := opts.containers[0]
+ startOptions := types.ContainerStartOptions{
+ CheckpointID: opts.checkpoint,
+ CheckpointDir: opts.checkpointDir,
+ }
+ return dockerCli.Client().ContainerStart(ctx, container, startOptions)
+
+ } else {
+ // We're not going to attach to anything.
+ // Start as many containers as we want.
+ return startContainersWithoutAttachments(ctx, dockerCli, opts.containers)
+ }
+
+ return nil
+}
+
+func startContainersWithoutAttachments(ctx context.Context, dockerCli *command.DockerCli, containers []string) error {
+ var failedContainers []string
+ for _, container := range containers {
+ if err := dockerCli.Client().ContainerStart(ctx, container, types.ContainerStartOptions{}); err != nil {
+ fmt.Fprintln(dockerCli.Err(), err)
+ failedContainers = append(failedContainers, container)
+ continue
+ }
+ fmt.Fprintln(dockerCli.Out(), container)
+ }
+
+ if len(failedContainers) > 0 {
+ return errors.Errorf("Error: failed to start containers: %s", strings.Join(failedContainers, ", "))
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/stats.go b/vendor/github.com/docker/cli/cli/command/container/stats.go
new file mode 100644
index 0000000..50495f0
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/stats.go
@@ -0,0 +1,243 @@
+package container
+
+import (
+ "fmt"
+ "io"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/formatter"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/api/types/events"
+ "github.com/docker/docker/api/types/filters"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type statsOptions struct {
+ all bool
+ noStream bool
+ format string
+ containers []string
+}
+
+// NewStatsCommand creates a new cobra.Command for `docker stats`
+func NewStatsCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts statsOptions
+
+ cmd := &cobra.Command{
+ Use: "stats [OPTIONS] [CONTAINER...]",
+ Short: "Display a live stream of container(s) resource usage statistics",
+ Args: cli.RequiresMinArgs(0),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.containers = args
+ return runStats(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&opts.all, "all", "a", false, "Show all containers (default shows just running)")
+ flags.BoolVar(&opts.noStream, "no-stream", false, "Disable streaming stats and only pull the first result")
+ flags.StringVar(&opts.format, "format", "", "Pretty-print images using a Go template")
+ return cmd
+}
+
+// runStats displays a live stream of resource usage statistics for one or more containers.
+// This shows real-time information on CPU usage, memory usage, and network I/O.
+// nolint: gocyclo
+func runStats(dockerCli *command.DockerCli, opts *statsOptions) error {
+ showAll := len(opts.containers) == 0
+ closeChan := make(chan error)
+
+ ctx := context.Background()
+
+ // monitorContainerEvents watches for container creation and removal (only
+ // used when calling `docker stats` without arguments).
+ monitorContainerEvents := func(started chan<- struct{}, c chan events.Message) {
+ f := filters.NewArgs()
+ f.Add("type", "container")
+ options := types.EventsOptions{
+ Filters: f,
+ }
+
+ eventq, errq := dockerCli.Client().Events(ctx, options)
+
+ // Whether we successfully subscribed to eventq or not, we can now
+ // unblock the main goroutine.
+ close(started)
+
+ for {
+ select {
+ case event := <-eventq:
+ c <- event
+ case err := <-errq:
+ closeChan <- err
+ return
+ }
+ }
+ }
+
+ // Get the daemonOSType if not set already
+ if daemonOSType == "" {
+ svctx := context.Background()
+ sv, err := dockerCli.Client().ServerVersion(svctx)
+ if err != nil {
+ return err
+ }
+ daemonOSType = sv.Os
+ }
+
+ // waitFirst is a WaitGroup to wait first stat data's reach for each container
+ waitFirst := &sync.WaitGroup{}
+
+ cStats := stats{}
+ // getContainerList simulates creation event for all previously existing
+ // containers (only used when calling `docker stats` without arguments).
+ getContainerList := func() {
+ options := types.ContainerListOptions{
+ All: opts.all,
+ }
+ cs, err := dockerCli.Client().ContainerList(ctx, options)
+ if err != nil {
+ closeChan <- err
+ }
+ for _, container := range cs {
+ s := formatter.NewContainerStats(container.ID[:12])
+ if cStats.add(s) {
+ waitFirst.Add(1)
+ go collect(ctx, s, dockerCli.Client(), !opts.noStream, waitFirst)
+ }
+ }
+ }
+
+ if showAll {
+ // If no names were specified, start a long running goroutine which
+ // monitors container events. We make sure we're subscribed before
+ // retrieving the list of running containers to avoid a race where we
+ // would "miss" a creation.
+ started := make(chan struct{})
+ eh := command.InitEventHandler()
+ eh.Handle("create", func(e events.Message) {
+ if opts.all {
+ s := formatter.NewContainerStats(e.ID[:12])
+ if cStats.add(s) {
+ waitFirst.Add(1)
+ go collect(ctx, s, dockerCli.Client(), !opts.noStream, waitFirst)
+ }
+ }
+ })
+
+ eh.Handle("start", func(e events.Message) {
+ s := formatter.NewContainerStats(e.ID[:12])
+ if cStats.add(s) {
+ waitFirst.Add(1)
+ go collect(ctx, s, dockerCli.Client(), !opts.noStream, waitFirst)
+ }
+ })
+
+ eh.Handle("die", func(e events.Message) {
+ if !opts.all {
+ cStats.remove(e.ID[:12])
+ }
+ })
+
+ eventChan := make(chan events.Message)
+ go eh.Watch(eventChan)
+ go monitorContainerEvents(started, eventChan)
+ defer close(eventChan)
+ <-started
+
+ // Start a short-lived goroutine to retrieve the initial list of
+ // containers.
+ getContainerList()
+ } else {
+ // Artificially send creation events for the containers we were asked to
+ // monitor (same code path than we use when monitoring all containers).
+ for _, name := range opts.containers {
+ s := formatter.NewContainerStats(name)
+ if cStats.add(s) {
+ waitFirst.Add(1)
+ go collect(ctx, s, dockerCli.Client(), !opts.noStream, waitFirst)
+ }
+ }
+
+ // We don't expect any asynchronous errors: closeChan can be closed.
+ close(closeChan)
+
+ // Do a quick pause to detect any error with the provided list of
+ // container names.
+ time.Sleep(1500 * time.Millisecond)
+ var errs []string
+ cStats.mu.Lock()
+ for _, c := range cStats.cs {
+ if err := c.GetError(); err != nil {
+ errs = append(errs, err.Error())
+ }
+ }
+ cStats.mu.Unlock()
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, "\n"))
+ }
+ }
+
+ // before print to screen, make sure each container get at least one valid stat data
+ waitFirst.Wait()
+ format := opts.format
+ if len(format) == 0 {
+ if len(dockerCli.ConfigFile().StatsFormat) > 0 {
+ format = dockerCli.ConfigFile().StatsFormat
+ } else {
+ format = formatter.TableFormatKey
+ }
+ }
+ statsCtx := formatter.Context{
+ Output: dockerCli.Out(),
+ Format: formatter.NewStatsFormat(format, daemonOSType),
+ }
+ cleanScreen := func() {
+ if !opts.noStream {
+ fmt.Fprint(dockerCli.Out(), "\033[2J")
+ fmt.Fprint(dockerCli.Out(), "\033[H")
+ }
+ }
+
+ var err error
+ for range time.Tick(500 * time.Millisecond) {
+ cleanScreen()
+ ccstats := []formatter.StatsEntry{}
+ cStats.mu.Lock()
+ for _, c := range cStats.cs {
+ ccstats = append(ccstats, c.GetStatistics())
+ }
+ cStats.mu.Unlock()
+ if err = formatter.ContainerStatsWrite(statsCtx, ccstats, daemonOSType); err != nil {
+ break
+ }
+ if len(cStats.cs) == 0 && !showAll {
+ break
+ }
+ if opts.noStream {
+ break
+ }
+ select {
+ case err, ok := <-closeChan:
+ if ok {
+ if err != nil {
+ // this is suppressing "unexpected EOF" in the cli when the
+ // daemon restarts so it shutdowns cleanly
+ if err == io.ErrUnexpectedEOF {
+ return nil
+ }
+ return err
+ }
+ }
+ default:
+ // just skip
+ }
+ }
+ return err
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/stats_helpers.go b/vendor/github.com/docker/cli/cli/command/container/stats_helpers.go
new file mode 100644
index 0000000..eb12cd0
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/stats_helpers.go
@@ -0,0 +1,238 @@
+package container
+
+import (
+ "encoding/json"
+ "io"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli/command/formatter"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/client"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+type stats struct {
+ mu sync.Mutex
+ cs []*formatter.ContainerStats
+}
+
+// daemonOSType is set once we have at least one stat for a container
+// from the daemon. It is used to ensure we print the right header based
+// on the daemon platform.
+var daemonOSType string
+
+func (s *stats) add(cs *formatter.ContainerStats) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if _, exists := s.isKnownContainer(cs.Container); !exists {
+ s.cs = append(s.cs, cs)
+ return true
+ }
+ return false
+}
+
+func (s *stats) remove(id string) {
+ s.mu.Lock()
+ if i, exists := s.isKnownContainer(id); exists {
+ s.cs = append(s.cs[:i], s.cs[i+1:]...)
+ }
+ s.mu.Unlock()
+}
+
+func (s *stats) isKnownContainer(cid string) (int, bool) {
+ for i, c := range s.cs {
+ if c.Container == cid {
+ return i, true
+ }
+ }
+ return -1, false
+}
+
+func collect(ctx context.Context, s *formatter.ContainerStats, cli client.APIClient, streamStats bool, waitFirst *sync.WaitGroup) {
+ logrus.Debugf("collecting stats for %s", s.Container)
+ var (
+ getFirst bool
+ previousCPU uint64
+ previousSystem uint64
+ u = make(chan error, 1)
+ )
+
+ defer func() {
+ // if error happens and we get nothing of stats, release wait group whatever
+ if !getFirst {
+ getFirst = true
+ waitFirst.Done()
+ }
+ }()
+
+ response, err := cli.ContainerStats(ctx, s.Container, streamStats)
+ if err != nil {
+ s.SetError(err)
+ return
+ }
+ defer response.Body.Close()
+
+ dec := json.NewDecoder(response.Body)
+ go func() {
+ for {
+ var (
+ v *types.StatsJSON
+ memPercent, cpuPercent float64
+ blkRead, blkWrite uint64 // Only used on Linux
+ mem, memLimit float64
+ pidsStatsCurrent uint64
+ )
+
+ if err := dec.Decode(&v); err != nil {
+ dec = json.NewDecoder(io.MultiReader(dec.Buffered(), response.Body))
+ u <- err
+ if err == io.EOF {
+ break
+ }
+ time.Sleep(100 * time.Millisecond)
+ continue
+ }
+
+ daemonOSType = response.OSType
+
+ if daemonOSType != "windows" {
+ previousCPU = v.PreCPUStats.CPUUsage.TotalUsage
+ previousSystem = v.PreCPUStats.SystemUsage
+ cpuPercent = calculateCPUPercentUnix(previousCPU, previousSystem, v)
+ blkRead, blkWrite = calculateBlockIO(v.BlkioStats)
+ mem = calculateMemUsageUnixNoCache(v.MemoryStats)
+ memLimit = float64(v.MemoryStats.Limit)
+ memPercent = calculateMemPercentUnixNoCache(memLimit, mem)
+ pidsStatsCurrent = v.PidsStats.Current
+ } else {
+ cpuPercent = calculateCPUPercentWindows(v)
+ blkRead = v.StorageStats.ReadSizeBytes
+ blkWrite = v.StorageStats.WriteSizeBytes
+ mem = float64(v.MemoryStats.PrivateWorkingSet)
+ }
+ netRx, netTx := calculateNetwork(v.Networks)
+ s.SetStatistics(formatter.StatsEntry{
+ Name: v.Name,
+ ID: v.ID,
+ CPUPercentage: cpuPercent,
+ Memory: mem,
+ MemoryPercentage: memPercent,
+ MemoryLimit: memLimit,
+ NetworkRx: netRx,
+ NetworkTx: netTx,
+ BlockRead: float64(blkRead),
+ BlockWrite: float64(blkWrite),
+ PidsCurrent: pidsStatsCurrent,
+ })
+ u <- nil
+ if !streamStats {
+ return
+ }
+ }
+ }()
+ for {
+ select {
+ case <-time.After(2 * time.Second):
+ // zero out the values if we have not received an update within
+ // the specified duration.
+ s.SetErrorAndReset(errors.New("timeout waiting for stats"))
+ // if this is the first stat you get, release WaitGroup
+ if !getFirst {
+ getFirst = true
+ waitFirst.Done()
+ }
+ case err := <-u:
+ s.SetError(err)
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ continue
+ }
+ // if this is the first stat you get, release WaitGroup
+ if !getFirst {
+ getFirst = true
+ waitFirst.Done()
+ }
+ }
+ if !streamStats {
+ return
+ }
+ }
+}
+
+func calculateCPUPercentUnix(previousCPU, previousSystem uint64, v *types.StatsJSON) float64 {
+ var (
+ cpuPercent = 0.0
+ // calculate the change for the cpu usage of the container in between readings
+ cpuDelta = float64(v.CPUStats.CPUUsage.TotalUsage) - float64(previousCPU)
+ // calculate the change for the entire system between readings
+ systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem)
+ onlineCPUs = float64(v.CPUStats.OnlineCPUs)
+ )
+
+ if onlineCPUs == 0.0 {
+ onlineCPUs = float64(len(v.CPUStats.CPUUsage.PercpuUsage))
+ }
+ if systemDelta > 0.0 && cpuDelta > 0.0 {
+ cpuPercent = (cpuDelta / systemDelta) * onlineCPUs * 100.0
+ }
+ return cpuPercent
+}
+
+func calculateCPUPercentWindows(v *types.StatsJSON) float64 {
+ // Max number of 100ns intervals between the previous time read and now
+ possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) // Start with number of ns intervals
+ possIntervals /= 100 // Convert to number of 100ns intervals
+ possIntervals *= uint64(v.NumProcs) // Multiple by the number of processors
+
+ // Intervals used
+ intervalsUsed := v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage
+
+ // Percentage avoiding divide-by-zero
+ if possIntervals > 0 {
+ return float64(intervalsUsed) / float64(possIntervals) * 100.0
+ }
+ return 0.00
+}
+
+func calculateBlockIO(blkio types.BlkioStats) (blkRead uint64, blkWrite uint64) {
+ for _, bioEntry := range blkio.IoServiceBytesRecursive {
+ switch strings.ToLower(bioEntry.Op) {
+ case "read":
+ blkRead = blkRead + bioEntry.Value
+ case "write":
+ blkWrite = blkWrite + bioEntry.Value
+ }
+ }
+ return
+}
+
+func calculateNetwork(network map[string]types.NetworkStats) (float64, float64) {
+ var rx, tx float64
+
+ for _, v := range network {
+ rx += float64(v.RxBytes)
+ tx += float64(v.TxBytes)
+ }
+ return rx, tx
+}
+
+// calculateMemUsageUnixNoCache calculate memory usage of the container.
+// Page cache is intentionally excluded to avoid misinterpretation of the output.
+func calculateMemUsageUnixNoCache(mem types.MemoryStats) float64 {
+ return float64(mem.Usage - mem.Stats["cache"])
+}
+
+func calculateMemPercentUnixNoCache(limit float64, usedNoCache float64) float64 {
+ // MemoryStats.Limit will never be 0 unless the container is not running and we haven't
+ // got any data from cgroup
+ if limit != 0 {
+ return usedNoCache / limit * 100.0
+ }
+ return 0
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/stop.go b/vendor/github.com/docker/cli/cli/command/container/stop.go
new file mode 100644
index 0000000..59d6d0b
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/stop.go
@@ -0,0 +1,67 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type stopOptions struct {
+ time int
+ timeChanged bool
+
+ containers []string
+}
+
+// NewStopCommand creates a new cobra.Command for `docker stop`
+func NewStopCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts stopOptions
+
+ cmd := &cobra.Command{
+ Use: "stop [OPTIONS] CONTAINER [CONTAINER...]",
+ Short: "Stop one or more running containers",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.containers = args
+ opts.timeChanged = cmd.Flags().Changed("time")
+ return runStop(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.IntVarP(&opts.time, "time", "t", 10, "Seconds to wait for stop before killing it")
+ return cmd
+}
+
+func runStop(dockerCli *command.DockerCli, opts *stopOptions) error {
+ ctx := context.Background()
+
+ var timeout *time.Duration
+ if opts.timeChanged {
+ timeoutValue := time.Duration(opts.time) * time.Second
+ timeout = &timeoutValue
+ }
+
+ var errs []string
+
+ errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, id string) error {
+ return dockerCli.Client().ContainerStop(ctx, id, timeout)
+ })
+ for _, container := range opts.containers {
+ if err := <-errChan; err != nil {
+ errs = append(errs, err.Error())
+ continue
+ }
+ fmt.Fprintln(dockerCli.Out(), container)
+ }
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, "\n"))
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/top.go b/vendor/github.com/docker/cli/cli/command/container/top.go
new file mode 100644
index 0000000..428ee27
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/top.go
@@ -0,0 +1,57 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+ "text/tabwriter"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type topOptions struct {
+ container string
+
+ args []string
+}
+
+// NewTopCommand creates a new cobra.Command for `docker top`
+func NewTopCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts topOptions
+
+ cmd := &cobra.Command{
+ Use: "top CONTAINER [ps OPTIONS]",
+ Short: "Display the running processes of a container",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.container = args[0]
+ opts.args = args[1:]
+ return runTop(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.SetInterspersed(false)
+
+ return cmd
+}
+
+func runTop(dockerCli *command.DockerCli, opts *topOptions) error {
+ ctx := context.Background()
+
+ procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args)
+ if err != nil {
+ return err
+ }
+
+ w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0)
+ fmt.Fprintln(w, strings.Join(procList.Titles, "\t"))
+
+ for _, proc := range procList.Processes {
+ fmt.Fprintln(w, strings.Join(proc, "\t"))
+ }
+ w.Flush()
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/tty.go b/vendor/github.com/docker/cli/cli/command/container/tty.go
new file mode 100644
index 0000000..fe123eb
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/tty.go
@@ -0,0 +1,103 @@
+package container
+
+import (
+ "fmt"
+ "os"
+ gosignal "os/signal"
+ "runtime"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/client"
+ "github.com/docker/docker/pkg/signal"
+ "golang.org/x/net/context"
+)
+
+// resizeTtyTo resizes tty to specific height and width
+func resizeTtyTo(ctx context.Context, client client.ContainerAPIClient, id string, height, width uint, isExec bool) {
+ if height == 0 && width == 0 {
+ return
+ }
+
+ options := types.ResizeOptions{
+ Height: height,
+ Width: width,
+ }
+
+ var err error
+ if isExec {
+ err = client.ContainerExecResize(ctx, id, options)
+ } else {
+ err = client.ContainerResize(ctx, id, options)
+ }
+
+ if err != nil {
+ logrus.Debugf("Error resize: %s", err)
+ }
+}
+
+// MonitorTtySize updates the container tty size when the terminal tty changes size
+func MonitorTtySize(ctx context.Context, cli command.Cli, id string, isExec bool) error {
+ resizeTty := func() {
+ height, width := cli.Out().GetTtySize()
+ resizeTtyTo(ctx, cli.Client(), id, height, width, isExec)
+ }
+
+ resizeTty()
+
+ if runtime.GOOS == "windows" {
+ go func() {
+ prevH, prevW := cli.Out().GetTtySize()
+ for {
+ time.Sleep(time.Millisecond * 250)
+ h, w := cli.Out().GetTtySize()
+
+ if prevW != w || prevH != h {
+ resizeTty()
+ }
+ prevH = h
+ prevW = w
+ }
+ }()
+ } else {
+ sigchan := make(chan os.Signal, 1)
+ gosignal.Notify(sigchan, signal.SIGWINCH)
+ go func() {
+ for range sigchan {
+ resizeTty()
+ }
+ }()
+ }
+ return nil
+}
+
+// ForwardAllSignals forwards signals to the container
+func ForwardAllSignals(ctx context.Context, cli command.Cli, cid string) chan os.Signal {
+ sigc := make(chan os.Signal, 128)
+ signal.CatchAll(sigc)
+ go func() {
+ for s := range sigc {
+ if s == signal.SIGCHLD || s == signal.SIGPIPE {
+ continue
+ }
+ var sig string
+ for sigStr, sigN := range signal.SignalMap {
+ if sigN == s {
+ sig = sigStr
+ break
+ }
+ }
+ if sig == "" {
+ fmt.Fprintf(cli.Err(), "Unsupported signal: %v. Discarding.\n", s)
+ continue
+ }
+
+ if err := cli.Client().ContainerKill(ctx, cid, sig); err != nil {
+ logrus.Debugf("Error sending signal: %s", err)
+ }
+ }
+ }()
+ return sigc
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/unpause.go b/vendor/github.com/docker/cli/cli/command/container/unpause.go
new file mode 100644
index 0000000..b6d5e23
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/unpause.go
@@ -0,0 +1,50 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type unpauseOptions struct {
+ containers []string
+}
+
+// NewUnpauseCommand creates a new cobra.Command for `docker unpause`
+func NewUnpauseCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts unpauseOptions
+
+ cmd := &cobra.Command{
+ Use: "unpause CONTAINER [CONTAINER...]",
+ Short: "Unpause all processes within one or more containers",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.containers = args
+ return runUnpause(dockerCli, &opts)
+ },
+ }
+ return cmd
+}
+
+func runUnpause(dockerCli *command.DockerCli, opts *unpauseOptions) error {
+ ctx := context.Background()
+
+ var errs []string
+ errChan := parallelOperation(ctx, opts.containers, dockerCli.Client().ContainerUnpause)
+ for _, container := range opts.containers {
+ if err := <-errChan; err != nil {
+ errs = append(errs, err.Error())
+ continue
+ }
+ fmt.Fprintln(dockerCli.Out(), container)
+ }
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, "\n"))
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/update.go b/vendor/github.com/docker/cli/cli/command/container/update.go
new file mode 100644
index 0000000..9cb74ae
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/update.go
@@ -0,0 +1,133 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ containertypes "github.com/docker/docker/api/types/container"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type updateOptions struct {
+ blkioWeight uint16
+ cpuPeriod int64
+ cpuQuota int64
+ cpuRealtimePeriod int64
+ cpuRealtimeRuntime int64
+ cpusetCpus string
+ cpusetMems string
+ cpuShares int64
+ memory opts.MemBytes
+ memoryReservation opts.MemBytes
+ memorySwap opts.MemSwapBytes
+ kernelMemory opts.MemBytes
+ restartPolicy string
+ cpus opts.NanoCPUs
+
+ nFlag int
+
+ containers []string
+}
+
+// NewUpdateCommand creates a new cobra.Command for `docker update`
+func NewUpdateCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var options updateOptions
+
+ cmd := &cobra.Command{
+ Use: "update [OPTIONS] CONTAINER [CONTAINER...]",
+ Short: "Update configuration of one or more containers",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ options.containers = args
+ options.nFlag = cmd.Flags().NFlag()
+ return runUpdate(dockerCli, &options)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.Uint16Var(&options.blkioWeight, "blkio-weight", 0, "Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)")
+ flags.Int64Var(&options.cpuPeriod, "cpu-period", 0, "Limit CPU CFS (Completely Fair Scheduler) period")
+ flags.Int64Var(&options.cpuQuota, "cpu-quota", 0, "Limit CPU CFS (Completely Fair Scheduler) quota")
+ flags.Int64Var(&options.cpuRealtimePeriod, "cpu-rt-period", 0, "Limit the CPU real-time period in microseconds")
+ flags.SetAnnotation("cpu-rt-period", "version", []string{"1.25"})
+ flags.Int64Var(&options.cpuRealtimeRuntime, "cpu-rt-runtime", 0, "Limit the CPU real-time runtime in microseconds")
+ flags.SetAnnotation("cpu-rt-runtime", "version", []string{"1.25"})
+ flags.StringVar(&options.cpusetCpus, "cpuset-cpus", "", "CPUs in which to allow execution (0-3, 0,1)")
+ flags.StringVar(&options.cpusetMems, "cpuset-mems", "", "MEMs in which to allow execution (0-3, 0,1)")
+ flags.Int64VarP(&options.cpuShares, "cpu-shares", "c", 0, "CPU shares (relative weight)")
+ flags.VarP(&options.memory, "memory", "m", "Memory limit")
+ flags.Var(&options.memoryReservation, "memory-reservation", "Memory soft limit")
+ flags.Var(&options.memorySwap, "memory-swap", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap")
+ flags.Var(&options.kernelMemory, "kernel-memory", "Kernel memory limit")
+ flags.StringVar(&options.restartPolicy, "restart", "", "Restart policy to apply when a container exits")
+
+ flags.Var(&options.cpus, "cpus", "Number of CPUs")
+ flags.SetAnnotation("cpus", "version", []string{"1.29"})
+
+ return cmd
+}
+
+func runUpdate(dockerCli *command.DockerCli, options *updateOptions) error {
+ var err error
+
+ if options.nFlag == 0 {
+ return errors.New("you must provide one or more flags when using this command")
+ }
+
+ var restartPolicy containertypes.RestartPolicy
+ if options.restartPolicy != "" {
+ restartPolicy, err = opts.ParseRestartPolicy(options.restartPolicy)
+ if err != nil {
+ return err
+ }
+ }
+
+ resources := containertypes.Resources{
+ BlkioWeight: options.blkioWeight,
+ CpusetCpus: options.cpusetCpus,
+ CpusetMems: options.cpusetMems,
+ CPUShares: options.cpuShares,
+ Memory: options.memory.Value(),
+ MemoryReservation: options.memoryReservation.Value(),
+ MemorySwap: options.memorySwap.Value(),
+ KernelMemory: options.kernelMemory.Value(),
+ CPUPeriod: options.cpuPeriod,
+ CPUQuota: options.cpuQuota,
+ CPURealtimePeriod: options.cpuRealtimePeriod,
+ CPURealtimeRuntime: options.cpuRealtimeRuntime,
+ NanoCPUs: options.cpus.Value(),
+ }
+
+ updateConfig := containertypes.UpdateConfig{
+ Resources: resources,
+ RestartPolicy: restartPolicy,
+ }
+
+ ctx := context.Background()
+
+ var (
+ warns []string
+ errs []string
+ )
+ for _, container := range options.containers {
+ r, err := dockerCli.Client().ContainerUpdate(ctx, container, updateConfig)
+ if err != nil {
+ errs = append(errs, err.Error())
+ } else {
+ fmt.Fprintln(dockerCli.Out(), container)
+ }
+ warns = append(warns, r.Warnings...)
+ }
+ if len(warns) > 0 {
+ fmt.Fprintln(dockerCli.Out(), strings.Join(warns, "\n"))
+ }
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, "\n"))
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/utils.go b/vendor/github.com/docker/cli/cli/command/container/utils.go
new file mode 100644
index 0000000..d9afe24
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/utils.go
@@ -0,0 +1,172 @@
+package container
+
+import (
+ "strconv"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/api/types/events"
+ "github.com/docker/docker/api/types/filters"
+ "github.com/docker/docker/api/types/versions"
+ clientapi "github.com/docker/docker/client"
+ "golang.org/x/net/context"
+)
+
+func waitExitOrRemoved(ctx context.Context, dockerCli *command.DockerCli, containerID string, waitRemove bool) <-chan int {
+ if len(containerID) == 0 {
+ // containerID can never be empty
+ panic("Internal Error: waitExitOrRemoved needs a containerID as parameter")
+ }
+
+ // Older versions used the Events API, and even older versions did not
+ // support server-side removal. This legacyWaitExitOrRemoved method
+ // preserves that old behavior and any issues it may have.
+ if versions.LessThan(dockerCli.Client().ClientVersion(), "1.30") {
+ return legacyWaitExitOrRemoved(ctx, dockerCli, containerID, waitRemove)
+ }
+
+ condition := container.WaitConditionNextExit
+ if waitRemove {
+ condition = container.WaitConditionRemoved
+ }
+
+ resultC, errC := dockerCli.Client().ContainerWait(ctx, containerID, condition)
+
+ statusC := make(chan int)
+ go func() {
+ select {
+ case result := <-resultC:
+ statusC <- int(result.StatusCode)
+ case err := <-errC:
+ logrus.Errorf("error waiting for container: %v", err)
+ statusC <- 125
+ }
+ }()
+
+ return statusC
+}
+
+func legacyWaitExitOrRemoved(ctx context.Context, dockerCli *command.DockerCli, containerID string, waitRemove bool) <-chan int {
+ var removeErr error
+ statusChan := make(chan int)
+ exitCode := 125
+
+ // Get events via Events API
+ f := filters.NewArgs()
+ f.Add("type", "container")
+ f.Add("container", containerID)
+ options := types.EventsOptions{
+ Filters: f,
+ }
+ eventCtx, cancel := context.WithCancel(ctx)
+ eventq, errq := dockerCli.Client().Events(eventCtx, options)
+
+ eventProcessor := func(e events.Message) bool {
+ stopProcessing := false
+ switch e.Status {
+ case "die":
+ if v, ok := e.Actor.Attributes["exitCode"]; ok {
+ code, cerr := strconv.Atoi(v)
+ if cerr != nil {
+ logrus.Errorf("failed to convert exitcode '%q' to int: %v", v, cerr)
+ } else {
+ exitCode = code
+ }
+ }
+ if !waitRemove {
+ stopProcessing = true
+ } else {
+ // If we are talking to an older daemon, `AutoRemove` is not supported.
+ // We need to fall back to the old behavior, which is client-side removal
+ if versions.LessThan(dockerCli.Client().ClientVersion(), "1.25") {
+ go func() {
+ removeErr = dockerCli.Client().ContainerRemove(ctx, containerID, types.ContainerRemoveOptions{RemoveVolumes: true})
+ if removeErr != nil {
+ logrus.Errorf("error removing container: %v", removeErr)
+ cancel() // cancel the event Q
+ }
+ }()
+ }
+ }
+ case "detach":
+ exitCode = 0
+ stopProcessing = true
+ case "destroy":
+ stopProcessing = true
+ }
+ return stopProcessing
+ }
+
+ go func() {
+ defer func() {
+ statusChan <- exitCode // must always send an exit code or the caller will block
+ cancel()
+ }()
+
+ for {
+ select {
+ case <-eventCtx.Done():
+ if removeErr != nil {
+ return
+ }
+ case evt := <-eventq:
+ if eventProcessor(evt) {
+ return
+ }
+ case err := <-errq:
+ logrus.Errorf("error getting events from daemon: %v", err)
+ return
+ }
+ }
+ }()
+
+ return statusChan
+}
+
+// getExitCode performs an inspect on the container. It returns
+// the running state and the exit code.
+func getExitCode(ctx context.Context, dockerCli command.Cli, containerID string) (bool, int, error) {
+ c, err := dockerCli.Client().ContainerInspect(ctx, containerID)
+ if err != nil {
+ // If we can't connect, then the daemon probably died.
+ if !clientapi.IsErrConnectionFailed(err) {
+ return false, -1, err
+ }
+ return false, -1, nil
+ }
+ return c.State.Running, c.State.ExitCode, nil
+}
+
+func parallelOperation(ctx context.Context, containers []string, op func(ctx context.Context, container string) error) chan error {
+ if len(containers) == 0 {
+ return nil
+ }
+ const defaultParallel int = 50
+ sem := make(chan struct{}, defaultParallel)
+ errChan := make(chan error)
+
+ // make sure result is printed in correct order
+ output := map[string]chan error{}
+ for _, c := range containers {
+ output[c] = make(chan error, 1)
+ }
+ go func() {
+ for _, c := range containers {
+ err := <-output[c]
+ errChan <- err
+ }
+ }()
+
+ go func() {
+ for _, c := range containers {
+ sem <- struct{}{} // Wait for active queue sem to drain.
+ go func(container string) {
+ output[container] <- op(ctx, container)
+ <-sem
+ }(c)
+ }
+ }()
+ return errChan
+}
diff --git a/vendor/github.com/docker/cli/cli/command/container/wait.go b/vendor/github.com/docker/cli/cli/command/container/wait.go
new file mode 100644
index 0000000..f582469
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/container/wait.go
@@ -0,0 +1,53 @@
+package container
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type waitOptions struct {
+ containers []string
+}
+
+// NewWaitCommand creates a new cobra.Command for `docker wait`
+func NewWaitCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts waitOptions
+
+ cmd := &cobra.Command{
+ Use: "wait CONTAINER [CONTAINER...]",
+ Short: "Block until one or more containers stop, then print their exit codes",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.containers = args
+ return runWait(dockerCli, &opts)
+ },
+ }
+
+ return cmd
+}
+
+func runWait(dockerCli *command.DockerCli, opts *waitOptions) error {
+ ctx := context.Background()
+
+ var errs []string
+ for _, container := range opts.containers {
+ resultC, errC := dockerCli.Client().ContainerWait(ctx, container, "")
+
+ select {
+ case result := <-resultC:
+ fmt.Fprintf(dockerCli.Out(), "%d\n", result.StatusCode)
+ case err := <-errC:
+ errs = append(errs, err.Error())
+ }
+ }
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, "\n"))
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/events_utils.go b/vendor/github.com/docker/cli/cli/command/events_utils.go
new file mode 100644
index 0000000..c271b20
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/events_utils.go
@@ -0,0 +1,47 @@
+package command
+
+import (
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ eventtypes "github.com/docker/docker/api/types/events"
+)
+
+// EventHandler is abstract interface for user to customize
+// own handle functions of each type of events
+type EventHandler interface {
+ Handle(action string, h func(eventtypes.Message))
+ Watch(c <-chan eventtypes.Message)
+}
+
+// InitEventHandler initializes and returns an EventHandler
+func InitEventHandler() EventHandler {
+ return &eventHandler{handlers: make(map[string]func(eventtypes.Message))}
+}
+
+type eventHandler struct {
+ handlers map[string]func(eventtypes.Message)
+ mu sync.Mutex
+}
+
+func (w *eventHandler) Handle(action string, h func(eventtypes.Message)) {
+ w.mu.Lock()
+ w.handlers[action] = h
+ w.mu.Unlock()
+}
+
+// Watch ranges over the passed in event chan and processes the events based on the
+// handlers created for a given action.
+// To stop watching, close the event chan.
+func (w *eventHandler) Watch(c <-chan eventtypes.Message) {
+ for e := range c {
+ w.mu.Lock()
+ h, exists := w.handlers[e.Action]
+ w.mu.Unlock()
+ if !exists {
+ continue
+ }
+ logrus.Debugf("event handler: received event: %v", e)
+ go h(e)
+ }
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/checkpoint.go b/vendor/github.com/docker/cli/cli/command/formatter/checkpoint.go
new file mode 100644
index 0000000..041fcaf
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/checkpoint.go
@@ -0,0 +1,52 @@
+package formatter
+
+import "github.com/docker/docker/api/types"
+
+const (
+ defaultCheckpointFormat = "table {{.Name}}"
+
+ checkpointNameHeader = "CHECKPOINT NAME"
+)
+
+// NewCheckpointFormat returns a format for use with a checkpoint Context
+func NewCheckpointFormat(source string) Format {
+ switch source {
+ case TableFormatKey:
+ return defaultCheckpointFormat
+ }
+ return Format(source)
+}
+
+// CheckpointWrite writes formatted checkpoints using the Context
+func CheckpointWrite(ctx Context, checkpoints []types.Checkpoint) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, checkpoint := range checkpoints {
+ if err := format(&checkpointContext{c: checkpoint}); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(newCheckpointContext(), render)
+}
+
+type checkpointContext struct {
+ HeaderContext
+ c types.Checkpoint
+}
+
+func newCheckpointContext() *checkpointContext {
+ cpCtx := checkpointContext{}
+ cpCtx.header = volumeHeaderContext{
+ "Name": checkpointNameHeader,
+ }
+ return &cpCtx
+}
+
+func (c *checkpointContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *checkpointContext) Name() string {
+ return c.c.Name
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/config.go b/vendor/github.com/docker/cli/cli/command/formatter/config.go
new file mode 100644
index 0000000..72203f3
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/config.go
@@ -0,0 +1,171 @@
+package formatter
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/inspect"
+ "github.com/docker/docker/api/types/swarm"
+ units "github.com/docker/go-units"
+)
+
+const (
+ defaultConfigTableFormat = "table {{.ID}}\t{{.Name}}\t{{.CreatedAt}}\t{{.UpdatedAt}}"
+ configIDHeader = "ID"
+ configCreatedHeader = "CREATED"
+ configUpdatedHeader = "UPDATED"
+ configInspectPrettyTemplate Format = `ID: {{.ID}}
+Name: {{.Name}}
+{{- if .Labels }}
+Labels:
+{{- range $k, $v := .Labels }}
+ - {{ $k }}{{if $v }}={{ $v }}{{ end }}
+{{- end }}{{ end }}
+Created at: {{.CreatedAt}}
+Updated at: {{.UpdatedAt}}
+Data:
+{{.Data}}`
+)
+
+// NewConfigFormat returns a Format for rendering using a config Context
+func NewConfigFormat(source string, quiet bool) Format {
+ switch source {
+ case PrettyFormatKey:
+ return configInspectPrettyTemplate
+ case TableFormatKey:
+ if quiet {
+ return defaultQuietFormat
+ }
+ return defaultConfigTableFormat
+ }
+ return Format(source)
+}
+
+// ConfigWrite writes the context
+func ConfigWrite(ctx Context, configs []swarm.Config) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, config := range configs {
+ configCtx := &configContext{c: config}
+ if err := format(configCtx); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(newConfigContext(), render)
+}
+
+func newConfigContext() *configContext {
+ cCtx := &configContext{}
+
+ cCtx.header = map[string]string{
+ "ID": configIDHeader,
+ "Name": nameHeader,
+ "CreatedAt": configCreatedHeader,
+ "UpdatedAt": configUpdatedHeader,
+ "Labels": labelsHeader,
+ }
+ return cCtx
+}
+
+type configContext struct {
+ HeaderContext
+ c swarm.Config
+}
+
+func (c *configContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *configContext) ID() string {
+ return c.c.ID
+}
+
+func (c *configContext) Name() string {
+ return c.c.Spec.Annotations.Name
+}
+
+func (c *configContext) CreatedAt() string {
+ return units.HumanDuration(time.Now().UTC().Sub(c.c.Meta.CreatedAt)) + " ago"
+}
+
+func (c *configContext) UpdatedAt() string {
+ return units.HumanDuration(time.Now().UTC().Sub(c.c.Meta.UpdatedAt)) + " ago"
+}
+
+func (c *configContext) Labels() string {
+ mapLabels := c.c.Spec.Annotations.Labels
+ if mapLabels == nil {
+ return ""
+ }
+ var joinLabels []string
+ for k, v := range mapLabels {
+ joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v))
+ }
+ return strings.Join(joinLabels, ",")
+}
+
+func (c *configContext) Label(name string) string {
+ if c.c.Spec.Annotations.Labels == nil {
+ return ""
+ }
+ return c.c.Spec.Annotations.Labels[name]
+}
+
+// ConfigInspectWrite renders the context for a list of configs
+func ConfigInspectWrite(ctx Context, refs []string, getRef inspect.GetRefFunc) error {
+ if ctx.Format != configInspectPrettyTemplate {
+ return inspect.Inspect(ctx.Output, refs, string(ctx.Format), getRef)
+ }
+ render := func(format func(subContext subContext) error) error {
+ for _, ref := range refs {
+ configI, _, err := getRef(ref)
+ if err != nil {
+ return err
+ }
+ config, ok := configI.(swarm.Config)
+ if !ok {
+ return fmt.Errorf("got wrong object to inspect :%v", ok)
+ }
+ if err := format(&configInspectContext{Config: config}); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(&configInspectContext{}, render)
+}
+
+type configInspectContext struct {
+ swarm.Config
+ subContext
+}
+
+func (ctx *configInspectContext) ID() string {
+ return ctx.Config.ID
+}
+
+func (ctx *configInspectContext) Name() string {
+ return ctx.Config.Spec.Name
+}
+
+func (ctx *configInspectContext) Labels() map[string]string {
+ return ctx.Config.Spec.Labels
+}
+
+func (ctx *configInspectContext) CreatedAt() string {
+ return command.PrettyPrint(ctx.Config.CreatedAt)
+}
+
+func (ctx *configInspectContext) UpdatedAt() string {
+ return command.PrettyPrint(ctx.Config.UpdatedAt)
+}
+
+func (ctx *configInspectContext) Data() string {
+ if ctx.Config.Spec.Data == nil {
+ return ""
+ }
+ return string(ctx.Config.Spec.Data)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/container.go b/vendor/github.com/docker/cli/cli/command/formatter/container.go
new file mode 100644
index 0000000..5ee1309
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/container.go
@@ -0,0 +1,345 @@
+package formatter
+
+import (
+ "fmt"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/stringid"
+ "github.com/docker/docker/pkg/stringutils"
+ "github.com/docker/go-units"
+)
+
+const (
+ defaultContainerTableFormat = "table {{.ID}}\t{{.Image}}\t{{.Command}}\t{{.RunningFor}}\t{{.Status}}\t{{.Ports}}\t{{.Names}}"
+
+ containerIDHeader = "CONTAINER ID"
+ namesHeader = "NAMES"
+ commandHeader = "COMMAND"
+ runningForHeader = "CREATED"
+ statusHeader = "STATUS"
+ portsHeader = "PORTS"
+ mountsHeader = "MOUNTS"
+ localVolumes = "LOCAL VOLUMES"
+ networksHeader = "NETWORKS"
+)
+
+// NewContainerFormat returns a Format for rendering using a Context
+func NewContainerFormat(source string, quiet bool, size bool) Format {
+ switch source {
+ case TableFormatKey:
+ if quiet {
+ return defaultQuietFormat
+ }
+ format := defaultContainerTableFormat
+ if size {
+ format += `\t{{.Size}}`
+ }
+ return Format(format)
+ case RawFormatKey:
+ if quiet {
+ return `container_id: {{.ID}}`
+ }
+ format := `container_id: {{.ID}}
+image: {{.Image}}
+command: {{.Command}}
+created_at: {{.CreatedAt}}
+status: {{- pad .Status 1 0}}
+names: {{.Names}}
+labels: {{- pad .Labels 1 0}}
+ports: {{- pad .Ports 1 0}}
+`
+ if size {
+ format += `size: {{.Size}}\n`
+ }
+ return Format(format)
+ }
+ return Format(source)
+}
+
+// ContainerWrite renders the context for a list of containers
+func ContainerWrite(ctx Context, containers []types.Container) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, container := range containers {
+ err := format(&containerContext{trunc: ctx.Trunc, c: container})
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(newContainerContext(), render)
+}
+
+type containerHeaderContext map[string]string
+
+func (c containerHeaderContext) Label(name string) string {
+ n := strings.Split(name, ".")
+ r := strings.NewReplacer("-", " ", "_", " ")
+ h := r.Replace(n[len(n)-1])
+
+ return h
+}
+
+type containerContext struct {
+ HeaderContext
+ trunc bool
+ c types.Container
+}
+
+func newContainerContext() *containerContext {
+ containerCtx := containerContext{}
+ containerCtx.header = containerHeaderContext{
+ "ID": containerIDHeader,
+ "Names": namesHeader,
+ "Image": imageHeader,
+ "Command": commandHeader,
+ "CreatedAt": createdAtHeader,
+ "RunningFor": runningForHeader,
+ "Ports": portsHeader,
+ "Status": statusHeader,
+ "Size": sizeHeader,
+ "Labels": labelsHeader,
+ "Mounts": mountsHeader,
+ "LocalVolumes": localVolumes,
+ "Networks": networksHeader,
+ }
+ return &containerCtx
+}
+
+func (c *containerContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *containerContext) ID() string {
+ if c.trunc {
+ return stringid.TruncateID(c.c.ID)
+ }
+ return c.c.ID
+}
+
+func (c *containerContext) Names() string {
+ names := stripNamePrefix(c.c.Names)
+ if c.trunc {
+ for _, name := range names {
+ if len(strings.Split(name, "/")) == 1 {
+ names = []string{name}
+ break
+ }
+ }
+ }
+ return strings.Join(names, ",")
+}
+
+func (c *containerContext) Image() string {
+ if c.c.Image == "" {
+ return "<no image>"
+ }
+ if c.trunc {
+ if trunc := stringid.TruncateID(c.c.ImageID); trunc == stringid.TruncateID(c.c.Image) {
+ return trunc
+ }
+ // truncate digest if no-trunc option was not selected
+ ref, err := reference.ParseNormalizedNamed(c.c.Image)
+ if err == nil {
+ if nt, ok := ref.(reference.NamedTagged); ok {
+ // case for when a tag is provided
+ if namedTagged, err := reference.WithTag(reference.TrimNamed(nt), nt.Tag()); err == nil {
+ return reference.FamiliarString(namedTagged)
+ }
+ } else {
+ // case for when a tag is not provided
+ named := reference.TrimNamed(ref)
+ return reference.FamiliarString(named)
+ }
+ }
+ }
+
+ return c.c.Image
+}
+
+func (c *containerContext) Command() string {
+ command := c.c.Command
+ if c.trunc {
+ command = stringutils.Ellipsis(command, 20)
+ }
+ return strconv.Quote(command)
+}
+
+func (c *containerContext) CreatedAt() string {
+ return time.Unix(c.c.Created, 0).String()
+}
+
+func (c *containerContext) RunningFor() string {
+ createdAt := time.Unix(c.c.Created, 0)
+ return units.HumanDuration(time.Now().UTC().Sub(createdAt)) + " ago"
+}
+
+func (c *containerContext) Ports() string {
+ return DisplayablePorts(c.c.Ports)
+}
+
+func (c *containerContext) Status() string {
+ return c.c.Status
+}
+
+func (c *containerContext) Size() string {
+ srw := units.HumanSizeWithPrecision(float64(c.c.SizeRw), 3)
+ sv := units.HumanSizeWithPrecision(float64(c.c.SizeRootFs), 3)
+
+ sf := srw
+ if c.c.SizeRootFs > 0 {
+ sf = fmt.Sprintf("%s (virtual %s)", srw, sv)
+ }
+ return sf
+}
+
+func (c *containerContext) Labels() string {
+ if c.c.Labels == nil {
+ return ""
+ }
+
+ var joinLabels []string
+ for k, v := range c.c.Labels {
+ joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v))
+ }
+ return strings.Join(joinLabels, ",")
+}
+
+func (c *containerContext) Label(name string) string {
+ if c.c.Labels == nil {
+ return ""
+ }
+ return c.c.Labels[name]
+}
+
+func (c *containerContext) Mounts() string {
+ var name string
+ var mounts []string
+ for _, m := range c.c.Mounts {
+ if m.Name == "" {
+ name = m.Source
+ } else {
+ name = m.Name
+ }
+ if c.trunc {
+ name = stringutils.Ellipsis(name, 15)
+ }
+ mounts = append(mounts, name)
+ }
+ return strings.Join(mounts, ",")
+}
+
+func (c *containerContext) LocalVolumes() string {
+ count := 0
+ for _, m := range c.c.Mounts {
+ if m.Driver == "local" {
+ count++
+ }
+ }
+
+ return fmt.Sprintf("%d", count)
+}
+
+func (c *containerContext) Networks() string {
+ if c.c.NetworkSettings == nil {
+ return ""
+ }
+
+ networks := []string{}
+ for k := range c.c.NetworkSettings.Networks {
+ networks = append(networks, k)
+ }
+
+ return strings.Join(networks, ",")
+}
+
+// DisplayablePorts returns formatted string representing open ports of container
+// e.g. "0.0.0.0:80->9090/tcp, 9988/tcp"
+// it's used by command 'docker ps'
+func DisplayablePorts(ports []types.Port) string {
+ type portGroup struct {
+ first uint16
+ last uint16
+ }
+ groupMap := make(map[string]*portGroup)
+ var result []string
+ var hostMappings []string
+ var groupMapKeys []string
+ sort.Sort(byPortInfo(ports))
+ for _, port := range ports {
+ current := port.PrivatePort
+ portKey := port.Type
+ if port.IP != "" {
+ if port.PublicPort != current {
+ hostMappings = append(hostMappings, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type))
+ continue
+ }
+ portKey = fmt.Sprintf("%s/%s", port.IP, port.Type)
+ }
+ group := groupMap[portKey]
+
+ if group == nil {
+ groupMap[portKey] = &portGroup{first: current, last: current}
+ // record order that groupMap keys are created
+ groupMapKeys = append(groupMapKeys, portKey)
+ continue
+ }
+ if current == (group.last + 1) {
+ group.last = current
+ continue
+ }
+
+ result = append(result, formGroup(portKey, group.first, group.last))
+ groupMap[portKey] = &portGroup{first: current, last: current}
+ }
+ for _, portKey := range groupMapKeys {
+ g := groupMap[portKey]
+ result = append(result, formGroup(portKey, g.first, g.last))
+ }
+ result = append(result, hostMappings...)
+ return strings.Join(result, ", ")
+}
+
+func formGroup(key string, start, last uint16) string {
+ parts := strings.Split(key, "/")
+ groupType := parts[0]
+ var ip string
+ if len(parts) > 1 {
+ ip = parts[0]
+ groupType = parts[1]
+ }
+ group := strconv.Itoa(int(start))
+ if start != last {
+ group = fmt.Sprintf("%s-%d", group, last)
+ }
+ if ip != "" {
+ group = fmt.Sprintf("%s:%s->%s", ip, group, group)
+ }
+ return fmt.Sprintf("%s/%s", group, groupType)
+}
+
+// byPortInfo is a temporary type used to sort types.Port by its fields
+type byPortInfo []types.Port
+
+func (r byPortInfo) Len() int { return len(r) }
+func (r byPortInfo) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
+func (r byPortInfo) Less(i, j int) bool {
+ if r[i].PrivatePort != r[j].PrivatePort {
+ return r[i].PrivatePort < r[j].PrivatePort
+ }
+
+ if r[i].IP != r[j].IP {
+ return r[i].IP < r[j].IP
+ }
+
+ if r[i].PublicPort != r[j].PublicPort {
+ return r[i].PublicPort < r[j].PublicPort
+ }
+
+ return r[i].Type < r[j].Type
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/custom.go b/vendor/github.com/docker/cli/cli/command/formatter/custom.go
new file mode 100644
index 0000000..73487f6
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/custom.go
@@ -0,0 +1,35 @@
+package formatter
+
+const (
+ imageHeader = "IMAGE"
+ createdSinceHeader = "CREATED"
+ createdAtHeader = "CREATED AT"
+ sizeHeader = "SIZE"
+ labelsHeader = "LABELS"
+ nameHeader = "NAME"
+ driverHeader = "DRIVER"
+ scopeHeader = "SCOPE"
+)
+
+type subContext interface {
+ FullHeader() interface{}
+}
+
+// HeaderContext provides the subContext interface for managing headers
+type HeaderContext struct {
+ header interface{}
+}
+
+// FullHeader returns the header as an interface
+func (c *HeaderContext) FullHeader() interface{} {
+ return c.header
+}
+
+func stripNamePrefix(ss []string) []string {
+ sss := make([]string, len(ss))
+ for i, s := range ss {
+ sss[i] = s[1:]
+ }
+
+ return sss
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/diff.go b/vendor/github.com/docker/cli/cli/command/formatter/diff.go
new file mode 100644
index 0000000..9b46819
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/diff.go
@@ -0,0 +1,72 @@
+package formatter
+
+import (
+ "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/pkg/archive"
+)
+
+const (
+ defaultDiffTableFormat = "table {{.Type}}\t{{.Path}}"
+
+ changeTypeHeader = "CHANGE TYPE"
+ pathHeader = "PATH"
+)
+
+// NewDiffFormat returns a format for use with a diff Context
+func NewDiffFormat(source string) Format {
+ switch source {
+ case TableFormatKey:
+ return defaultDiffTableFormat
+ }
+ return Format(source)
+}
+
+// DiffWrite writes formatted diff using the Context
+func DiffWrite(ctx Context, changes []container.ContainerChangeResponseItem) error {
+
+ render := func(format func(subContext subContext) error) error {
+ for _, change := range changes {
+ if err := format(&diffContext{c: change}); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(newDiffContext(), render)
+}
+
+type diffContext struct {
+ HeaderContext
+ c container.ContainerChangeResponseItem
+}
+
+func newDiffContext() *diffContext {
+ diffCtx := diffContext{}
+ diffCtx.header = map[string]string{
+ "Type": changeTypeHeader,
+ "Path": pathHeader,
+ }
+ return &diffCtx
+}
+
+func (d *diffContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(d)
+}
+
+func (d *diffContext) Type() string {
+ var kind string
+ switch d.c.Kind {
+ case archive.ChangeModify:
+ kind = "C"
+ case archive.ChangeAdd:
+ kind = "A"
+ case archive.ChangeDelete:
+ kind = "D"
+ }
+ return kind
+
+}
+
+func (d *diffContext) Path() string {
+ return d.c.Path
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/disk_usage.go b/vendor/github.com/docker/cli/cli/command/formatter/disk_usage.go
new file mode 100644
index 0000000..1713a9c
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/disk_usage.go
@@ -0,0 +1,359 @@
+package formatter
+
+import (
+ "bytes"
+ "fmt"
+ "strings"
+ "text/template"
+
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/api/types"
+ units "github.com/docker/go-units"
+)
+
+const (
+ defaultDiskUsageImageTableFormat = "table {{.Repository}}\t{{.Tag}}\t{{.ID}}\t{{.CreatedSince}} ago\t{{.VirtualSize}}\t{{.SharedSize}}\t{{.UniqueSize}}\t{{.Containers}}"
+ defaultDiskUsageContainerTableFormat = "table {{.ID}}\t{{.Image}}\t{{.Command}}\t{{.LocalVolumes}}\t{{.Size}}\t{{.RunningFor}} ago\t{{.Status}}\t{{.Names}}"
+ defaultDiskUsageVolumeTableFormat = "table {{.Name}}\t{{.Links}}\t{{.Size}}"
+ defaultDiskUsageTableFormat = "table {{.Type}}\t{{.TotalCount}}\t{{.Active}}\t{{.Size}}\t{{.Reclaimable}}"
+
+ typeHeader = "TYPE"
+ totalHeader = "TOTAL"
+ activeHeader = "ACTIVE"
+ reclaimableHeader = "RECLAIMABLE"
+ containersHeader = "CONTAINERS"
+ sharedSizeHeader = "SHARED SIZE"
+ uniqueSizeHeader = "UNIQUE SiZE"
+)
+
+// DiskUsageContext contains disk usage specific information required by the formatter, encapsulate a Context struct.
+type DiskUsageContext struct {
+ Context
+ Verbose bool
+ LayersSize int64
+ Images []*types.ImageSummary
+ Containers []*types.Container
+ Volumes []*types.Volume
+}
+
+func (ctx *DiskUsageContext) startSubsection(format string) (*template.Template, error) {
+ ctx.buffer = bytes.NewBufferString("")
+ ctx.header = ""
+ ctx.Format = Format(format)
+ ctx.preFormat()
+
+ return ctx.parseFormat()
+}
+
+//
+// NewDiskUsageFormat returns a format for rendering an DiskUsageContext
+func NewDiskUsageFormat(source string) Format {
+ switch source {
+ case TableFormatKey:
+ format := defaultDiskUsageTableFormat
+ return Format(format)
+ case RawFormatKey:
+ format := `type: {{.Type}}
+total: {{.TotalCount}}
+active: {{.Active}}
+size: {{.Size}}
+reclaimable: {{.Reclaimable}}
+`
+ return Format(format)
+ }
+ return Format(source)
+}
+
+func (ctx *DiskUsageContext) Write() (err error) {
+ if ctx.Verbose {
+ return ctx.verboseWrite()
+ }
+ ctx.buffer = bytes.NewBufferString("")
+ ctx.preFormat()
+
+ tmpl, err := ctx.parseFormat()
+ if err != nil {
+ return err
+ }
+
+ err = ctx.contextFormat(tmpl, &diskUsageImagesContext{
+ totalSize: ctx.LayersSize,
+ images: ctx.Images,
+ })
+ if err != nil {
+ return err
+ }
+ err = ctx.contextFormat(tmpl, &diskUsageContainersContext{
+ containers: ctx.Containers,
+ })
+ if err != nil {
+ return err
+ }
+
+ err = ctx.contextFormat(tmpl, &diskUsageVolumesContext{
+ volumes: ctx.Volumes,
+ })
+ if err != nil {
+ return err
+ }
+
+ diskUsageContainersCtx := diskUsageContainersContext{containers: []*types.Container{}}
+ diskUsageContainersCtx.header = map[string]string{
+ "Type": typeHeader,
+ "TotalCount": totalHeader,
+ "Active": activeHeader,
+ "Size": sizeHeader,
+ "Reclaimable": reclaimableHeader,
+ }
+ ctx.postFormat(tmpl, &diskUsageContainersCtx)
+
+ return err
+}
+
+func (ctx *DiskUsageContext) verboseWrite() (err error) {
+ // First images
+ tmpl, err := ctx.startSubsection(defaultDiskUsageImageTableFormat)
+ if err != nil {
+ return
+ }
+
+ ctx.Output.Write([]byte("Images space usage:\n\n"))
+ for _, i := range ctx.Images {
+ repo := "<none>"
+ tag := "<none>"
+ if len(i.RepoTags) > 0 && !isDangling(*i) {
+ // Only show the first tag
+ ref, err := reference.ParseNormalizedNamed(i.RepoTags[0])
+ if err != nil {
+ continue
+ }
+ if nt, ok := ref.(reference.NamedTagged); ok {
+ repo = reference.FamiliarName(ref)
+ tag = nt.Tag()
+ }
+ }
+
+ err = ctx.contextFormat(tmpl, &imageContext{
+ repo: repo,
+ tag: tag,
+ trunc: true,
+ i: *i,
+ })
+ if err != nil {
+ return
+ }
+ }
+ ctx.postFormat(tmpl, newImageContext())
+
+ // Now containers
+ ctx.Output.Write([]byte("\nContainers space usage:\n\n"))
+ tmpl, err = ctx.startSubsection(defaultDiskUsageContainerTableFormat)
+ if err != nil {
+ return
+ }
+ for _, c := range ctx.Containers {
+ // Don't display the virtual size
+ c.SizeRootFs = 0
+ err = ctx.contextFormat(tmpl, &containerContext{
+ trunc: true,
+ c: *c,
+ })
+ if err != nil {
+ return
+ }
+ }
+ ctx.postFormat(tmpl, newContainerContext())
+
+ // And volumes
+ ctx.Output.Write([]byte("\nLocal Volumes space usage:\n\n"))
+ tmpl, err = ctx.startSubsection(defaultDiskUsageVolumeTableFormat)
+ if err != nil {
+ return
+ }
+ for _, v := range ctx.Volumes {
+ err = ctx.contextFormat(tmpl, &volumeContext{
+ v: *v,
+ })
+ if err != nil {
+ return
+ }
+ }
+ ctx.postFormat(tmpl, newVolumeContext())
+ return
+}
+
+type diskUsageImagesContext struct {
+ HeaderContext
+ totalSize int64
+ images []*types.ImageSummary
+}
+
+func (c *diskUsageImagesContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *diskUsageImagesContext) Type() string {
+ return "Images"
+}
+
+func (c *diskUsageImagesContext) TotalCount() string {
+ return fmt.Sprintf("%d", len(c.images))
+}
+
+func (c *diskUsageImagesContext) Active() string {
+ used := 0
+ for _, i := range c.images {
+ if i.Containers > 0 {
+ used++
+ }
+ }
+
+ return fmt.Sprintf("%d", used)
+}
+
+func (c *diskUsageImagesContext) Size() string {
+ return units.HumanSize(float64(c.totalSize))
+
+}
+
+func (c *diskUsageImagesContext) Reclaimable() string {
+ var used int64
+
+ for _, i := range c.images {
+ if i.Containers != 0 {
+ if i.VirtualSize == -1 || i.SharedSize == -1 {
+ continue
+ }
+ used += i.VirtualSize - i.SharedSize
+ }
+ }
+
+ reclaimable := c.totalSize - used
+ if c.totalSize > 0 {
+ return fmt.Sprintf("%s (%v%%)", units.HumanSize(float64(reclaimable)), (reclaimable*100)/c.totalSize)
+ }
+ return fmt.Sprintf("%s", units.HumanSize(float64(reclaimable)))
+}
+
+type diskUsageContainersContext struct {
+ HeaderContext
+ containers []*types.Container
+}
+
+func (c *diskUsageContainersContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *diskUsageContainersContext) Type() string {
+ return "Containers"
+}
+
+func (c *diskUsageContainersContext) TotalCount() string {
+ return fmt.Sprintf("%d", len(c.containers))
+}
+
+func (c *diskUsageContainersContext) isActive(container types.Container) bool {
+ return strings.Contains(container.State, "running") ||
+ strings.Contains(container.State, "paused") ||
+ strings.Contains(container.State, "restarting")
+}
+
+func (c *diskUsageContainersContext) Active() string {
+ used := 0
+ for _, container := range c.containers {
+ if c.isActive(*container) {
+ used++
+ }
+ }
+
+ return fmt.Sprintf("%d", used)
+}
+
+func (c *diskUsageContainersContext) Size() string {
+ var size int64
+
+ for _, container := range c.containers {
+ size += container.SizeRw
+ }
+
+ return units.HumanSize(float64(size))
+}
+
+func (c *diskUsageContainersContext) Reclaimable() string {
+ var reclaimable int64
+ var totalSize int64
+
+ for _, container := range c.containers {
+ if !c.isActive(*container) {
+ reclaimable += container.SizeRw
+ }
+ totalSize += container.SizeRw
+ }
+
+ if totalSize > 0 {
+ return fmt.Sprintf("%s (%v%%)", units.HumanSize(float64(reclaimable)), (reclaimable*100)/totalSize)
+ }
+
+ return fmt.Sprintf("%s", units.HumanSize(float64(reclaimable)))
+}
+
+type diskUsageVolumesContext struct {
+ HeaderContext
+ volumes []*types.Volume
+}
+
+func (c *diskUsageVolumesContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *diskUsageVolumesContext) Type() string {
+ return "Local Volumes"
+}
+
+func (c *diskUsageVolumesContext) TotalCount() string {
+ return fmt.Sprintf("%d", len(c.volumes))
+}
+
+func (c *diskUsageVolumesContext) Active() string {
+
+ used := 0
+ for _, v := range c.volumes {
+ if v.UsageData.RefCount > 0 {
+ used++
+ }
+ }
+
+ return fmt.Sprintf("%d", used)
+}
+
+func (c *diskUsageVolumesContext) Size() string {
+ var size int64
+
+ for _, v := range c.volumes {
+ if v.UsageData.Size != -1 {
+ size += v.UsageData.Size
+ }
+ }
+
+ return units.HumanSize(float64(size))
+}
+
+func (c *diskUsageVolumesContext) Reclaimable() string {
+ var reclaimable int64
+ var totalSize int64
+
+ for _, v := range c.volumes {
+ if v.UsageData.Size != -1 {
+ if v.UsageData.RefCount == 0 {
+ reclaimable += v.UsageData.Size
+ }
+ totalSize += v.UsageData.Size
+ }
+ }
+
+ if totalSize > 0 {
+ return fmt.Sprintf("%s (%v%%)", units.HumanSize(float64(reclaimable)), (reclaimable*100)/totalSize)
+ }
+
+ return fmt.Sprintf("%s", units.HumanSize(float64(reclaimable)))
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/formatter.go b/vendor/github.com/docker/cli/cli/command/formatter/formatter.go
new file mode 100644
index 0000000..3f07aee
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/formatter.go
@@ -0,0 +1,119 @@
+package formatter
+
+import (
+ "bytes"
+ "io"
+ "strings"
+ "text/tabwriter"
+ "text/template"
+
+ "github.com/docker/docker/pkg/templates"
+ "github.com/pkg/errors"
+)
+
+// Format keys used to specify certain kinds of output formats
+const (
+ TableFormatKey = "table"
+ RawFormatKey = "raw"
+ PrettyFormatKey = "pretty"
+
+ defaultQuietFormat = "{{.ID}}"
+)
+
+// Format is the format string rendered using the Context
+type Format string
+
+// IsTable returns true if the format is a table-type format
+func (f Format) IsTable() bool {
+ return strings.HasPrefix(string(f), TableFormatKey)
+}
+
+// Contains returns true if the format contains the substring
+func (f Format) Contains(sub string) bool {
+ return strings.Contains(string(f), sub)
+}
+
+// Context contains information required by the formatter to print the output as desired.
+type Context struct {
+ // Output is the output stream to which the formatted string is written.
+ Output io.Writer
+ // Format is used to choose raw, table or custom format for the output.
+ Format Format
+ // Trunc when set to true will truncate the output of certain fields such as Container ID.
+ Trunc bool
+
+ // internal element
+ finalFormat string
+ header interface{}
+ buffer *bytes.Buffer
+}
+
+func (c *Context) preFormat() {
+ c.finalFormat = string(c.Format)
+
+ // TODO: handle this in the Format type
+ if c.Format.IsTable() {
+ c.finalFormat = c.finalFormat[len(TableFormatKey):]
+ }
+
+ c.finalFormat = strings.Trim(c.finalFormat, " ")
+ r := strings.NewReplacer(`\t`, "\t", `\n`, "\n")
+ c.finalFormat = r.Replace(c.finalFormat)
+}
+
+func (c *Context) parseFormat() (*template.Template, error) {
+ tmpl, err := templates.Parse(c.finalFormat)
+ if err != nil {
+ return tmpl, errors.Errorf("Template parsing error: %v\n", err)
+ }
+ return tmpl, err
+}
+
+func (c *Context) postFormat(tmpl *template.Template, subContext subContext) {
+ if c.Format.IsTable() {
+ t := tabwriter.NewWriter(c.Output, 20, 1, 3, ' ', 0)
+ buffer := bytes.NewBufferString("")
+ tmpl.Funcs(templates.HeaderFunctions).Execute(buffer, subContext.FullHeader())
+ buffer.WriteTo(t)
+ t.Write([]byte("\n"))
+ c.buffer.WriteTo(t)
+ t.Flush()
+ } else {
+ c.buffer.WriteTo(c.Output)
+ }
+}
+
+func (c *Context) contextFormat(tmpl *template.Template, subContext subContext) error {
+ if err := tmpl.Execute(c.buffer, subContext); err != nil {
+ return errors.Errorf("Template parsing error: %v\n", err)
+ }
+ if c.Format.IsTable() && c.header != nil {
+ c.header = subContext.FullHeader()
+ }
+ c.buffer.WriteString("\n")
+ return nil
+}
+
+// SubFormat is a function type accepted by Write()
+type SubFormat func(func(subContext) error) error
+
+// Write the template to the buffer using this Context
+func (c *Context) Write(sub subContext, f SubFormat) error {
+ c.buffer = bytes.NewBufferString("")
+ c.preFormat()
+
+ tmpl, err := c.parseFormat()
+ if err != nil {
+ return err
+ }
+
+ subFormat := func(subContext subContext) error {
+ return c.contextFormat(tmpl, subContext)
+ }
+ if err := f(subFormat); err != nil {
+ return err
+ }
+
+ c.postFormat(tmpl, sub)
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/history.go b/vendor/github.com/docker/cli/cli/command/formatter/history.go
new file mode 100644
index 0000000..161aaa4
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/history.go
@@ -0,0 +1,107 @@
+package formatter
+
+import (
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/docker/docker/api/types/image"
+ "github.com/docker/docker/pkg/stringid"
+ "github.com/docker/docker/pkg/stringutils"
+ units "github.com/docker/go-units"
+)
+
+const (
+ defaultHistoryTableFormat = "table {{.ID}}\t{{.CreatedSince}}\t{{.CreatedBy}}\t{{.Size}}\t{{.Comment}}"
+ nonHumanHistoryTableFormat = "table {{.ID}}\t{{.CreatedAt}}\t{{.CreatedBy}}\t{{.Size}}\t{{.Comment}}"
+
+ historyIDHeader = "IMAGE"
+ createdByHeader = "CREATED BY"
+ commentHeader = "COMMENT"
+)
+
+// NewHistoryFormat returns a format for rendering an HistoryContext
+func NewHistoryFormat(source string, quiet bool, human bool) Format {
+ switch source {
+ case TableFormatKey:
+ switch {
+ case quiet:
+ return defaultQuietFormat
+ case !human:
+ return nonHumanHistoryTableFormat
+ default:
+ return defaultHistoryTableFormat
+ }
+ }
+
+ return Format(source)
+}
+
+// HistoryWrite writes the context
+func HistoryWrite(ctx Context, human bool, histories []image.HistoryResponseItem) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, history := range histories {
+ historyCtx := &historyContext{trunc: ctx.Trunc, h: history, human: human}
+ if err := format(historyCtx); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ historyCtx := &historyContext{}
+ historyCtx.header = map[string]string{
+ "ID": historyIDHeader,
+ "CreatedSince": createdSinceHeader,
+ "CreatedAt": createdAtHeader,
+ "CreatedBy": createdByHeader,
+ "Size": sizeHeader,
+ "Comment": commentHeader,
+ }
+ return ctx.Write(historyCtx, render)
+}
+
+type historyContext struct {
+ HeaderContext
+ trunc bool
+ human bool
+ h image.HistoryResponseItem
+}
+
+func (c *historyContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *historyContext) ID() string {
+ if c.trunc {
+ return stringid.TruncateID(c.h.ID)
+ }
+ return c.h.ID
+}
+
+func (c *historyContext) CreatedAt() string {
+ return units.HumanDuration(time.Now().UTC().Sub(time.Unix(c.h.Created, 0)))
+}
+
+func (c *historyContext) CreatedSince() string {
+ created := units.HumanDuration(time.Now().UTC().Sub(time.Unix(c.h.Created, 0)))
+ return created + " ago"
+}
+
+func (c *historyContext) CreatedBy() string {
+ createdBy := strings.Replace(c.h.CreatedBy, "\t", " ", -1)
+ if c.trunc {
+ return stringutils.Ellipsis(createdBy, 45)
+ }
+ return createdBy
+}
+
+func (c *historyContext) Size() string {
+ if c.human {
+ return units.HumanSizeWithPrecision(float64(c.h.Size), 3)
+ }
+ return strconv.FormatInt(c.h.Size, 10)
+}
+
+func (c *historyContext) Comment() string {
+ return c.h.Comment
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/image.go b/vendor/github.com/docker/cli/cli/command/formatter/image.go
new file mode 100644
index 0000000..cbd3eda
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/image.go
@@ -0,0 +1,272 @@
+package formatter
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/stringid"
+ units "github.com/docker/go-units"
+)
+
+const (
+ defaultImageTableFormat = "table {{.Repository}}\t{{.Tag}}\t{{.ID}}\t{{.CreatedSince}}\t{{.Size}}"
+ defaultImageTableFormatWithDigest = "table {{.Repository}}\t{{.Tag}}\t{{.Digest}}\t{{.ID}}\t{{.CreatedSince}}\t{{.Size}}"
+
+ imageIDHeader = "IMAGE ID"
+ repositoryHeader = "REPOSITORY"
+ tagHeader = "TAG"
+ digestHeader = "DIGEST"
+)
+
+// ImageContext contains image specific information required by the formatter, encapsulate a Context struct.
+type ImageContext struct {
+ Context
+ Digest bool
+}
+
+func isDangling(image types.ImageSummary) bool {
+ return len(image.RepoTags) == 1 && image.RepoTags[0] == "<none>:<none>" && len(image.RepoDigests) == 1 && image.RepoDigests[0] == "<none>@<none>"
+}
+
+// NewImageFormat returns a format for rendering an ImageContext
+func NewImageFormat(source string, quiet bool, digest bool) Format {
+ switch source {
+ case TableFormatKey:
+ switch {
+ case quiet:
+ return defaultQuietFormat
+ case digest:
+ return defaultImageTableFormatWithDigest
+ default:
+ return defaultImageTableFormat
+ }
+ case RawFormatKey:
+ switch {
+ case quiet:
+ return `image_id: {{.ID}}`
+ case digest:
+ return `repository: {{ .Repository }}
+tag: {{.Tag}}
+digest: {{.Digest}}
+image_id: {{.ID}}
+created_at: {{.CreatedAt}}
+virtual_size: {{.Size}}
+`
+ default:
+ return `repository: {{ .Repository }}
+tag: {{.Tag}}
+image_id: {{.ID}}
+created_at: {{.CreatedAt}}
+virtual_size: {{.Size}}
+`
+ }
+ }
+
+ format := Format(source)
+ if format.IsTable() && digest && !format.Contains("{{.Digest}}") {
+ format += "\t{{.Digest}}"
+ }
+ return format
+}
+
+// ImageWrite writes the formatter images using the ImageContext
+func ImageWrite(ctx ImageContext, images []types.ImageSummary) error {
+ render := func(format func(subContext subContext) error) error {
+ return imageFormat(ctx, images, format)
+ }
+ return ctx.Write(newImageContext(), render)
+}
+
+func imageFormat(ctx ImageContext, images []types.ImageSummary, format func(subContext subContext) error) error {
+ for _, image := range images {
+ images := []*imageContext{}
+ if isDangling(image) {
+ images = append(images, &imageContext{
+ trunc: ctx.Trunc,
+ i: image,
+ repo: "<none>",
+ tag: "<none>",
+ digest: "<none>",
+ })
+ } else {
+ repoTags := map[string][]string{}
+ repoDigests := map[string][]string{}
+
+ for _, refString := range image.RepoTags {
+ ref, err := reference.ParseNormalizedNamed(refString)
+ if err != nil {
+ continue
+ }
+ if nt, ok := ref.(reference.NamedTagged); ok {
+ familiarRef := reference.FamiliarName(ref)
+ repoTags[familiarRef] = append(repoTags[familiarRef], nt.Tag())
+ }
+ }
+ for _, refString := range image.RepoDigests {
+ ref, err := reference.ParseNormalizedNamed(refString)
+ if err != nil {
+ continue
+ }
+ if c, ok := ref.(reference.Canonical); ok {
+ familiarRef := reference.FamiliarName(ref)
+ repoDigests[familiarRef] = append(repoDigests[familiarRef], c.Digest().String())
+ }
+ }
+
+ for repo, tags := range repoTags {
+ digests := repoDigests[repo]
+
+ // Do not display digests as their own row
+ delete(repoDigests, repo)
+
+ if !ctx.Digest {
+ // Ignore digest references, just show tag once
+ digests = nil
+ }
+
+ for _, tag := range tags {
+ if len(digests) == 0 {
+ images = append(images, &imageContext{
+ trunc: ctx.Trunc,
+ i: image,
+ repo: repo,
+ tag: tag,
+ digest: "<none>",
+ })
+ continue
+ }
+ // Display the digests for each tag
+ for _, dgst := range digests {
+ images = append(images, &imageContext{
+ trunc: ctx.Trunc,
+ i: image,
+ repo: repo,
+ tag: tag,
+ digest: dgst,
+ })
+ }
+
+ }
+ }
+
+ // Show rows for remaining digest only references
+ for repo, digests := range repoDigests {
+ // If digests are displayed, show row per digest
+ if ctx.Digest {
+ for _, dgst := range digests {
+ images = append(images, &imageContext{
+ trunc: ctx.Trunc,
+ i: image,
+ repo: repo,
+ tag: "<none>",
+ digest: dgst,
+ })
+ }
+ } else {
+ images = append(images, &imageContext{
+ trunc: ctx.Trunc,
+ i: image,
+ repo: repo,
+ tag: "<none>",
+ })
+ }
+ }
+ }
+ for _, imageCtx := range images {
+ if err := format(imageCtx); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+type imageContext struct {
+ HeaderContext
+ trunc bool
+ i types.ImageSummary
+ repo string
+ tag string
+ digest string
+}
+
+func newImageContext() *imageContext {
+ imageCtx := imageContext{}
+ imageCtx.header = map[string]string{
+ "ID": imageIDHeader,
+ "Repository": repositoryHeader,
+ "Tag": tagHeader,
+ "Digest": digestHeader,
+ "CreatedSince": createdSinceHeader,
+ "CreatedAt": createdAtHeader,
+ "Size": sizeHeader,
+ "Containers": containersHeader,
+ "VirtualSize": sizeHeader,
+ "SharedSize": sharedSizeHeader,
+ "UniqueSize": uniqueSizeHeader,
+ }
+ return &imageCtx
+}
+
+func (c *imageContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *imageContext) ID() string {
+ if c.trunc {
+ return stringid.TruncateID(c.i.ID)
+ }
+ return c.i.ID
+}
+
+func (c *imageContext) Repository() string {
+ return c.repo
+}
+
+func (c *imageContext) Tag() string {
+ return c.tag
+}
+
+func (c *imageContext) Digest() string {
+ return c.digest
+}
+
+func (c *imageContext) CreatedSince() string {
+ createdAt := time.Unix(c.i.Created, 0)
+ return units.HumanDuration(time.Now().UTC().Sub(createdAt)) + " ago"
+}
+
+func (c *imageContext) CreatedAt() string {
+ return time.Unix(c.i.Created, 0).String()
+}
+
+func (c *imageContext) Size() string {
+ return units.HumanSizeWithPrecision(float64(c.i.Size), 3)
+}
+
+func (c *imageContext) Containers() string {
+ if c.i.Containers == -1 {
+ return "N/A"
+ }
+ return fmt.Sprintf("%d", c.i.Containers)
+}
+
+func (c *imageContext) VirtualSize() string {
+ return units.HumanSize(float64(c.i.VirtualSize))
+}
+
+func (c *imageContext) SharedSize() string {
+ if c.i.SharedSize == -1 {
+ return "N/A"
+ }
+ return units.HumanSize(float64(c.i.SharedSize))
+}
+
+func (c *imageContext) UniqueSize() string {
+ if c.i.VirtualSize == -1 || c.i.SharedSize == -1 {
+ return "N/A"
+ }
+ return units.HumanSize(float64(c.i.VirtualSize - c.i.SharedSize))
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/network.go b/vendor/github.com/docker/cli/cli/command/formatter/network.go
new file mode 100644
index 0000000..4aeebd1
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/network.go
@@ -0,0 +1,129 @@
+package formatter
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/stringid"
+)
+
+const (
+ defaultNetworkTableFormat = "table {{.ID}}\t{{.Name}}\t{{.Driver}}\t{{.Scope}}"
+
+ networkIDHeader = "NETWORK ID"
+ ipv6Header = "IPV6"
+ internalHeader = "INTERNAL"
+)
+
+// NewNetworkFormat returns a Format for rendering using a network Context
+func NewNetworkFormat(source string, quiet bool) Format {
+ switch source {
+ case TableFormatKey:
+ if quiet {
+ return defaultQuietFormat
+ }
+ return defaultNetworkTableFormat
+ case RawFormatKey:
+ if quiet {
+ return `network_id: {{.ID}}`
+ }
+ return `network_id: {{.ID}}\nname: {{.Name}}\ndriver: {{.Driver}}\nscope: {{.Scope}}\n`
+ }
+ return Format(source)
+}
+
+// NetworkWrite writes the context
+func NetworkWrite(ctx Context, networks []types.NetworkResource) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, network := range networks {
+ networkCtx := &networkContext{trunc: ctx.Trunc, n: network}
+ if err := format(networkCtx); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ networkCtx := networkContext{}
+ networkCtx.header = networkHeaderContext{
+ "ID": networkIDHeader,
+ "Name": nameHeader,
+ "Driver": driverHeader,
+ "Scope": scopeHeader,
+ "IPv6": ipv6Header,
+ "Internal": internalHeader,
+ "Labels": labelsHeader,
+ "CreatedAt": createdAtHeader,
+ }
+ return ctx.Write(&networkCtx, render)
+}
+
+type networkHeaderContext map[string]string
+
+func (c networkHeaderContext) Label(name string) string {
+ n := strings.Split(name, ".")
+ r := strings.NewReplacer("-", " ", "_", " ")
+ h := r.Replace(n[len(n)-1])
+
+ return h
+}
+
+type networkContext struct {
+ HeaderContext
+ trunc bool
+ n types.NetworkResource
+}
+
+func (c *networkContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *networkContext) ID() string {
+ if c.trunc {
+ return stringid.TruncateID(c.n.ID)
+ }
+ return c.n.ID
+}
+
+func (c *networkContext) Name() string {
+ return c.n.Name
+}
+
+func (c *networkContext) Driver() string {
+ return c.n.Driver
+}
+
+func (c *networkContext) Scope() string {
+ return c.n.Scope
+}
+
+func (c *networkContext) IPv6() string {
+ return fmt.Sprintf("%v", c.n.EnableIPv6)
+}
+
+func (c *networkContext) Internal() string {
+ return fmt.Sprintf("%v", c.n.Internal)
+}
+
+func (c *networkContext) Labels() string {
+ if c.n.Labels == nil {
+ return ""
+ }
+
+ var joinLabels []string
+ for k, v := range c.n.Labels {
+ joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v))
+ }
+ return strings.Join(joinLabels, ",")
+}
+
+func (c *networkContext) Label(name string) string {
+ if c.n.Labels == nil {
+ return ""
+ }
+ return c.n.Labels[name]
+}
+
+func (c *networkContext) CreatedAt() string {
+ return c.n.Created.String()
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/node.go b/vendor/github.com/docker/cli/cli/command/formatter/node.go
new file mode 100644
index 0000000..09bcd3f
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/node.go
@@ -0,0 +1,330 @@
+package formatter
+
+import (
+ "encoding/base64"
+ "fmt"
+ "reflect"
+ "strings"
+
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/inspect"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/api/types/swarm"
+ units "github.com/docker/go-units"
+)
+
+const (
+ defaultNodeTableFormat = "table {{.ID}} {{if .Self}}*{{else}} {{ end }}\t{{.Hostname}}\t{{.Status}}\t{{.Availability}}\t{{.ManagerStatus}}"
+ nodeInspectPrettyTemplate Format = `ID: {{.ID}}
+{{- if .Name }}
+Name: {{.Name}}
+{{- end }}
+{{- if .Labels }}
+Labels:
+{{- range $k, $v := .Labels }}
+ - {{ $k }}{{if $v }}={{ $v }}{{ end }}
+{{- end }}{{ end }}
+Hostname: {{.Hostname}}
+Joined at: {{.CreatedAt}}
+Status:
+ State: {{.StatusState}}
+ {{- if .HasStatusMessage}}
+ Message: {{.StatusMessage}}
+ {{- end}}
+ Availability: {{.SpecAvailability}}
+ {{- if .Status.Addr}}
+ Address: {{.StatusAddr}}
+ {{- end}}
+{{- if .HasManagerStatus}}
+Manager Status:
+ Address: {{.ManagerStatusAddr}}
+ Raft Status: {{.ManagerStatusReachability}}
+ {{- if .IsManagerStatusLeader}}
+ Leader: Yes
+ {{- else}}
+ Leader: No
+ {{- end}}
+{{- end}}
+Platform:
+ Operating System: {{.PlatformOS}}
+ Architecture: {{.PlatformArchitecture}}
+Resources:
+ CPUs: {{.ResourceNanoCPUs}}
+ Memory: {{.ResourceMemory}}
+{{- if .HasEnginePlugins}}
+Plugins:
+{{- range $k, $v := .EnginePlugins }}
+ {{ $k }}:{{if $v }} {{ $v }}{{ end }}
+{{- end }}
+{{- end }}
+Engine Version: {{.EngineVersion}}
+{{- if .EngineLabels}}
+Engine Labels:
+{{- range $k, $v := .EngineLabels }}
+ - {{ $k }}{{if $v }}={{ $v }}{{ end }}
+{{- end }}{{- end }}
+{{- if .HasTLSInfo}}
+TLS Info:
+ TrustRoot:
+{{.TLSInfoTrustRoot}}
+ Issuer Subject: {{.TLSInfoCertIssuerSubject}}
+ Issuer Public Key: {{.TLSInfoCertIssuerPublicKey}}
+{{- end}}`
+ nodeIDHeader = "ID"
+ selfHeader = ""
+ hostnameHeader = "HOSTNAME"
+ availabilityHeader = "AVAILABILITY"
+ managerStatusHeader = "MANAGER STATUS"
+ tlsStatusHeader = "TLS STATUS"
+)
+
+// NewNodeFormat returns a Format for rendering using a node Context
+func NewNodeFormat(source string, quiet bool) Format {
+ switch source {
+ case PrettyFormatKey:
+ return nodeInspectPrettyTemplate
+ case TableFormatKey:
+ if quiet {
+ return defaultQuietFormat
+ }
+ return defaultNodeTableFormat
+ case RawFormatKey:
+ if quiet {
+ return `node_id: {{.ID}}`
+ }
+ return `node_id: {{.ID}}\nhostname: {{.Hostname}}\nstatus: {{.Status}}\navailability: {{.Availability}}\nmanager_status: {{.ManagerStatus}}\n`
+ }
+ return Format(source)
+}
+
+// NodeWrite writes the context
+func NodeWrite(ctx Context, nodes []swarm.Node, info types.Info) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, node := range nodes {
+ nodeCtx := &nodeContext{n: node, info: info}
+ if err := format(nodeCtx); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ header := nodeHeaderContext{
+ "ID": nodeIDHeader,
+ "Self": selfHeader,
+ "Hostname": hostnameHeader,
+ "Status": statusHeader,
+ "Availability": availabilityHeader,
+ "ManagerStatus": managerStatusHeader,
+ "TLSStatus": tlsStatusHeader,
+ }
+ nodeCtx := nodeContext{}
+ nodeCtx.header = header
+ return ctx.Write(&nodeCtx, render)
+}
+
+type nodeHeaderContext map[string]string
+
+type nodeContext struct {
+ HeaderContext
+ n swarm.Node
+ info types.Info
+}
+
+func (c *nodeContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *nodeContext) ID() string {
+ return c.n.ID
+}
+
+func (c *nodeContext) Self() bool {
+ return c.n.ID == c.info.Swarm.NodeID
+}
+
+func (c *nodeContext) Hostname() string {
+ return c.n.Description.Hostname
+}
+
+func (c *nodeContext) Status() string {
+ return command.PrettyPrint(string(c.n.Status.State))
+}
+
+func (c *nodeContext) Availability() string {
+ return command.PrettyPrint(string(c.n.Spec.Availability))
+}
+
+func (c *nodeContext) ManagerStatus() string {
+ reachability := ""
+ if c.n.ManagerStatus != nil {
+ if c.n.ManagerStatus.Leader {
+ reachability = "Leader"
+ } else {
+ reachability = string(c.n.ManagerStatus.Reachability)
+ }
+ }
+ return command.PrettyPrint(reachability)
+}
+
+func (c *nodeContext) TLSStatus() string {
+ if c.info.Swarm.Cluster == nil || reflect.DeepEqual(c.info.Swarm.Cluster.TLSInfo, swarm.TLSInfo{}) || reflect.DeepEqual(c.n.Description.TLSInfo, swarm.TLSInfo{}) {
+ return "Unknown"
+ }
+ if reflect.DeepEqual(c.n.Description.TLSInfo, c.info.Swarm.Cluster.TLSInfo) {
+ return "Ready"
+ }
+ return "Needs Rotation"
+}
+
+// NodeInspectWrite renders the context for a list of nodes
+func NodeInspectWrite(ctx Context, refs []string, getRef inspect.GetRefFunc) error {
+ if ctx.Format != nodeInspectPrettyTemplate {
+ return inspect.Inspect(ctx.Output, refs, string(ctx.Format), getRef)
+ }
+ render := func(format func(subContext subContext) error) error {
+ for _, ref := range refs {
+ nodeI, _, err := getRef(ref)
+ if err != nil {
+ return err
+ }
+ node, ok := nodeI.(swarm.Node)
+ if !ok {
+ return fmt.Errorf("got wrong object to inspect :%v", ok)
+ }
+ if err := format(&nodeInspectContext{Node: node}); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(&nodeInspectContext{}, render)
+}
+
+type nodeInspectContext struct {
+ swarm.Node
+ subContext
+}
+
+func (ctx *nodeInspectContext) ID() string {
+ return ctx.Node.ID
+}
+
+func (ctx *nodeInspectContext) Name() string {
+ return ctx.Node.Spec.Name
+}
+
+func (ctx *nodeInspectContext) Labels() map[string]string {
+ return ctx.Node.Spec.Labels
+}
+
+func (ctx *nodeInspectContext) Hostname() string {
+ return ctx.Node.Description.Hostname
+}
+
+func (ctx *nodeInspectContext) CreatedAt() string {
+ return command.PrettyPrint(ctx.Node.CreatedAt)
+}
+
+func (ctx *nodeInspectContext) StatusState() string {
+ return command.PrettyPrint(ctx.Node.Status.State)
+}
+
+func (ctx *nodeInspectContext) HasStatusMessage() bool {
+ return ctx.Node.Status.Message != ""
+}
+
+func (ctx *nodeInspectContext) StatusMessage() string {
+ return command.PrettyPrint(ctx.Node.Status.Message)
+}
+
+func (ctx *nodeInspectContext) SpecAvailability() string {
+ return command.PrettyPrint(ctx.Node.Spec.Availability)
+}
+
+func (ctx *nodeInspectContext) HasStatusAddr() bool {
+ return ctx.Node.Status.Addr != ""
+}
+
+func (ctx *nodeInspectContext) StatusAddr() string {
+ return ctx.Node.Status.Addr
+}
+
+func (ctx *nodeInspectContext) HasManagerStatus() bool {
+ return ctx.Node.ManagerStatus != nil
+}
+
+func (ctx *nodeInspectContext) ManagerStatusAddr() string {
+ return ctx.Node.ManagerStatus.Addr
+}
+
+func (ctx *nodeInspectContext) ManagerStatusReachability() string {
+ return command.PrettyPrint(ctx.Node.ManagerStatus.Reachability)
+}
+
+func (ctx *nodeInspectContext) IsManagerStatusLeader() bool {
+ return ctx.Node.ManagerStatus.Leader
+}
+
+func (ctx *nodeInspectContext) PlatformOS() string {
+ return ctx.Node.Description.Platform.OS
+}
+
+func (ctx *nodeInspectContext) PlatformArchitecture() string {
+ return ctx.Node.Description.Platform.Architecture
+}
+
+func (ctx *nodeInspectContext) ResourceNanoCPUs() int {
+ if ctx.Node.Description.Resources.NanoCPUs == 0 {
+ return int(0)
+ }
+ return int(ctx.Node.Description.Resources.NanoCPUs) / 1e9
+}
+
+func (ctx *nodeInspectContext) ResourceMemory() string {
+ if ctx.Node.Description.Resources.MemoryBytes == 0 {
+ return ""
+ }
+ return units.BytesSize(float64(ctx.Node.Description.Resources.MemoryBytes))
+}
+
+func (ctx *nodeInspectContext) HasEnginePlugins() bool {
+ return len(ctx.Node.Description.Engine.Plugins) > 0
+}
+
+func (ctx *nodeInspectContext) EnginePlugins() map[string]string {
+ pluginMap := map[string][]string{}
+ for _, p := range ctx.Node.Description.Engine.Plugins {
+ pluginMap[p.Type] = append(pluginMap[p.Type], p.Name)
+ }
+
+ pluginNamesByType := map[string]string{}
+ for k, v := range pluginMap {
+ pluginNamesByType[k] = strings.Join(v, ", ")
+ }
+ return pluginNamesByType
+}
+
+func (ctx *nodeInspectContext) EngineLabels() map[string]string {
+ return ctx.Node.Description.Engine.Labels
+}
+
+func (ctx *nodeInspectContext) EngineVersion() string {
+ return ctx.Node.Description.Engine.EngineVersion
+}
+
+func (ctx *nodeInspectContext) HasTLSInfo() bool {
+ tlsInfo := ctx.Node.Description.TLSInfo
+ return !reflect.DeepEqual(tlsInfo, swarm.TLSInfo{})
+}
+
+func (ctx *nodeInspectContext) TLSInfoTrustRoot() string {
+ return ctx.Node.Description.TLSInfo.TrustRoot
+}
+
+func (ctx *nodeInspectContext) TLSInfoCertIssuerPublicKey() string {
+ return base64.StdEncoding.EncodeToString(ctx.Node.Description.TLSInfo.CertIssuerPublicKey)
+}
+
+func (ctx *nodeInspectContext) TLSInfoCertIssuerSubject() string {
+ return base64.StdEncoding.EncodeToString(ctx.Node.Description.TLSInfo.CertIssuerSubject)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/plugin.go b/vendor/github.com/docker/cli/cli/command/formatter/plugin.go
new file mode 100644
index 0000000..2b71281
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/plugin.go
@@ -0,0 +1,95 @@
+package formatter
+
+import (
+ "strings"
+
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/stringid"
+ "github.com/docker/docker/pkg/stringutils"
+)
+
+const (
+ defaultPluginTableFormat = "table {{.ID}}\t{{.Name}}\t{{.Description}}\t{{.Enabled}}"
+
+ pluginIDHeader = "ID"
+ descriptionHeader = "DESCRIPTION"
+ enabledHeader = "ENABLED"
+)
+
+// NewPluginFormat returns a Format for rendering using a plugin Context
+func NewPluginFormat(source string, quiet bool) Format {
+ switch source {
+ case TableFormatKey:
+ if quiet {
+ return defaultQuietFormat
+ }
+ return defaultPluginTableFormat
+ case RawFormatKey:
+ if quiet {
+ return `plugin_id: {{.ID}}`
+ }
+ return `plugin_id: {{.ID}}\nname: {{.Name}}\ndescription: {{.Description}}\nenabled: {{.Enabled}}\n`
+ }
+ return Format(source)
+}
+
+// PluginWrite writes the context
+func PluginWrite(ctx Context, plugins []*types.Plugin) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, plugin := range plugins {
+ pluginCtx := &pluginContext{trunc: ctx.Trunc, p: *plugin}
+ if err := format(pluginCtx); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ pluginCtx := pluginContext{}
+ pluginCtx.header = map[string]string{
+ "ID": pluginIDHeader,
+ "Name": nameHeader,
+ "Description": descriptionHeader,
+ "Enabled": enabledHeader,
+ "PluginReference": imageHeader,
+ }
+ return ctx.Write(&pluginCtx, render)
+}
+
+type pluginContext struct {
+ HeaderContext
+ trunc bool
+ p types.Plugin
+}
+
+func (c *pluginContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *pluginContext) ID() string {
+ if c.trunc {
+ return stringid.TruncateID(c.p.ID)
+ }
+ return c.p.ID
+}
+
+func (c *pluginContext) Name() string {
+ return c.p.Name
+}
+
+func (c *pluginContext) Description() string {
+ desc := strings.Replace(c.p.Config.Description, "\n", "", -1)
+ desc = strings.Replace(desc, "\r", "", -1)
+ if c.trunc {
+ desc = stringutils.Ellipsis(desc, 45)
+ }
+
+ return desc
+}
+
+func (c *pluginContext) Enabled() bool {
+ return c.p.Enabled
+}
+
+func (c *pluginContext) PluginReference() string {
+ return c.p.PluginReference
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/reflect.go b/vendor/github.com/docker/cli/cli/command/formatter/reflect.go
new file mode 100644
index 0000000..fd59404
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/reflect.go
@@ -0,0 +1,66 @@
+package formatter
+
+import (
+ "encoding/json"
+ "reflect"
+ "unicode"
+
+ "github.com/pkg/errors"
+)
+
+func marshalJSON(x interface{}) ([]byte, error) {
+ m, err := marshalMap(x)
+ if err != nil {
+ return nil, err
+ }
+ return json.Marshal(m)
+}
+
+// marshalMap marshals x to map[string]interface{}
+func marshalMap(x interface{}) (map[string]interface{}, error) {
+ val := reflect.ValueOf(x)
+ if val.Kind() != reflect.Ptr {
+ return nil, errors.Errorf("expected a pointer to a struct, got %v", val.Kind())
+ }
+ if val.IsNil() {
+ return nil, errors.Errorf("expected a pointer to a struct, got nil pointer")
+ }
+ valElem := val.Elem()
+ if valElem.Kind() != reflect.Struct {
+ return nil, errors.Errorf("expected a pointer to a struct, got a pointer to %v", valElem.Kind())
+ }
+ typ := val.Type()
+ m := make(map[string]interface{})
+ for i := 0; i < val.NumMethod(); i++ {
+ k, v, err := marshalForMethod(typ.Method(i), val.Method(i))
+ if err != nil {
+ return nil, err
+ }
+ if k != "" {
+ m[k] = v
+ }
+ }
+ return m, nil
+}
+
+var unmarshallableNames = map[string]struct{}{"FullHeader": {}}
+
+// marshalForMethod returns the map key and the map value for marshalling the method.
+// It returns ("", nil, nil) for valid but non-marshallable parameter. (e.g. "unexportedFunc()")
+func marshalForMethod(typ reflect.Method, val reflect.Value) (string, interface{}, error) {
+ if val.Kind() != reflect.Func {
+ return "", nil, errors.Errorf("expected func, got %v", val.Kind())
+ }
+ name, numIn, numOut := typ.Name, val.Type().NumIn(), val.Type().NumOut()
+ _, blackListed := unmarshallableNames[name]
+ // FIXME: In text/template, (numOut == 2) is marshallable,
+ // if the type of the second param is error.
+ marshallable := unicode.IsUpper(rune(name[0])) && !blackListed &&
+ numIn == 0 && numOut == 1
+ if !marshallable {
+ return "", nil, nil
+ }
+ result := val.Call(make([]reflect.Value, numIn))
+ intf := result[0].Interface()
+ return name, intf, nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/secret.go b/vendor/github.com/docker/cli/cli/command/formatter/secret.go
new file mode 100644
index 0000000..04bf944
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/secret.go
@@ -0,0 +1,162 @@
+package formatter
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/inspect"
+ "github.com/docker/docker/api/types/swarm"
+ units "github.com/docker/go-units"
+)
+
+const (
+ defaultSecretTableFormat = "table {{.ID}}\t{{.Name}}\t{{.CreatedAt}}\t{{.UpdatedAt}}"
+ secretIDHeader = "ID"
+ secretCreatedHeader = "CREATED"
+ secretUpdatedHeader = "UPDATED"
+ secretInspectPrettyTemplate Format = `ID: {{.ID}}
+Name: {{.Name}}
+{{- if .Labels }}
+Labels:
+{{- range $k, $v := .Labels }}
+ - {{ $k }}{{if $v }}={{ $v }}{{ end }}
+{{- end }}{{ end }}
+Created at: {{.CreatedAt}}
+Updated at: {{.UpdatedAt}}`
+)
+
+// NewSecretFormat returns a Format for rendering using a secret Context
+func NewSecretFormat(source string, quiet bool) Format {
+ switch source {
+ case PrettyFormatKey:
+ return secretInspectPrettyTemplate
+ case TableFormatKey:
+ if quiet {
+ return defaultQuietFormat
+ }
+ return defaultSecretTableFormat
+ }
+ return Format(source)
+}
+
+// SecretWrite writes the context
+func SecretWrite(ctx Context, secrets []swarm.Secret) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, secret := range secrets {
+ secretCtx := &secretContext{s: secret}
+ if err := format(secretCtx); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(newSecretContext(), render)
+}
+
+func newSecretContext() *secretContext {
+ sCtx := &secretContext{}
+
+ sCtx.header = map[string]string{
+ "ID": secretIDHeader,
+ "Name": nameHeader,
+ "CreatedAt": secretCreatedHeader,
+ "UpdatedAt": secretUpdatedHeader,
+ "Labels": labelsHeader,
+ }
+ return sCtx
+}
+
+type secretContext struct {
+ HeaderContext
+ s swarm.Secret
+}
+
+func (c *secretContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *secretContext) ID() string {
+ return c.s.ID
+}
+
+func (c *secretContext) Name() string {
+ return c.s.Spec.Annotations.Name
+}
+
+func (c *secretContext) CreatedAt() string {
+ return units.HumanDuration(time.Now().UTC().Sub(c.s.Meta.CreatedAt)) + " ago"
+}
+
+func (c *secretContext) UpdatedAt() string {
+ return units.HumanDuration(time.Now().UTC().Sub(c.s.Meta.UpdatedAt)) + " ago"
+}
+
+func (c *secretContext) Labels() string {
+ mapLabels := c.s.Spec.Annotations.Labels
+ if mapLabels == nil {
+ return ""
+ }
+ var joinLabels []string
+ for k, v := range mapLabels {
+ joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v))
+ }
+ return strings.Join(joinLabels, ",")
+}
+
+func (c *secretContext) Label(name string) string {
+ if c.s.Spec.Annotations.Labels == nil {
+ return ""
+ }
+ return c.s.Spec.Annotations.Labels[name]
+}
+
+// SecretInspectWrite renders the context for a list of secrets
+func SecretInspectWrite(ctx Context, refs []string, getRef inspect.GetRefFunc) error {
+ if ctx.Format != secretInspectPrettyTemplate {
+ return inspect.Inspect(ctx.Output, refs, string(ctx.Format), getRef)
+ }
+ render := func(format func(subContext subContext) error) error {
+ for _, ref := range refs {
+ secretI, _, err := getRef(ref)
+ if err != nil {
+ return err
+ }
+ secret, ok := secretI.(swarm.Secret)
+ if !ok {
+ return fmt.Errorf("got wrong object to inspect :%v", ok)
+ }
+ if err := format(&secretInspectContext{Secret: secret}); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(&secretInspectContext{}, render)
+}
+
+type secretInspectContext struct {
+ swarm.Secret
+ subContext
+}
+
+func (ctx *secretInspectContext) ID() string {
+ return ctx.Secret.ID
+}
+
+func (ctx *secretInspectContext) Name() string {
+ return ctx.Secret.Spec.Name
+}
+
+func (ctx *secretInspectContext) Labels() map[string]string {
+ return ctx.Secret.Spec.Labels
+}
+
+func (ctx *secretInspectContext) CreatedAt() string {
+ return command.PrettyPrint(ctx.Secret.CreatedAt)
+}
+
+func (ctx *secretInspectContext) UpdatedAt() string {
+ return command.PrettyPrint(ctx.Secret.UpdatedAt)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/service.go b/vendor/github.com/docker/cli/cli/command/formatter/service.go
new file mode 100644
index 0000000..27200b8
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/service.go
@@ -0,0 +1,535 @@
+package formatter
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/docker/cli/cli/command/inspect"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/api/types"
+ mounttypes "github.com/docker/docker/api/types/mount"
+ "github.com/docker/docker/api/types/swarm"
+ "github.com/docker/docker/pkg/stringid"
+ units "github.com/docker/go-units"
+ "github.com/pkg/errors"
+)
+
+const serviceInspectPrettyTemplate Format = `
+ID: {{.ID}}
+Name: {{.Name}}
+{{- if .Labels }}
+Labels:
+{{- range $k, $v := .Labels }}
+ {{ $k }}{{if $v }}={{ $v }}{{ end }}
+{{- end }}{{ end }}
+Service Mode:
+{{- if .IsModeGlobal }} Global
+{{- else if .IsModeReplicated }} Replicated
+{{- if .ModeReplicatedReplicas }}
+ Replicas: {{ .ModeReplicatedReplicas }}
+{{- end }}{{ end }}
+{{- if .HasUpdateStatus }}
+UpdateStatus:
+ State: {{ .UpdateStatusState }}
+{{- if .HasUpdateStatusStarted }}
+ Started: {{ .UpdateStatusStarted }}
+{{- end }}
+{{- if .UpdateIsCompleted }}
+ Completed: {{ .UpdateStatusCompleted }}
+{{- end }}
+ Message: {{ .UpdateStatusMessage }}
+{{- end }}
+Placement:
+{{- if .TaskPlacementConstraints }}
+ Constraints: {{ .TaskPlacementConstraints }}
+{{- end }}
+{{- if .TaskPlacementPreferences }}
+ Preferences: {{ .TaskPlacementPreferences }}
+{{- end }}
+{{- if .HasUpdateConfig }}
+UpdateConfig:
+ Parallelism: {{ .UpdateParallelism }}
+{{- if .HasUpdateDelay}}
+ Delay: {{ .UpdateDelay }}
+{{- end }}
+ On failure: {{ .UpdateOnFailure }}
+{{- if .HasUpdateMonitor}}
+ Monitoring Period: {{ .UpdateMonitor }}
+{{- end }}
+ Max failure ratio: {{ .UpdateMaxFailureRatio }}
+ Update order: {{ .UpdateOrder }}
+{{- end }}
+{{- if .HasRollbackConfig }}
+RollbackConfig:
+ Parallelism: {{ .RollbackParallelism }}
+{{- if .HasRollbackDelay}}
+ Delay: {{ .RollbackDelay }}
+{{- end }}
+ On failure: {{ .RollbackOnFailure }}
+{{- if .HasRollbackMonitor}}
+ Monitoring Period: {{ .RollbackMonitor }}
+{{- end }}
+ Max failure ratio: {{ .RollbackMaxFailureRatio }}
+ Rollback order: {{ .RollbackOrder }}
+{{- end }}
+ContainerSpec:
+ Image: {{ .ContainerImage }}
+{{- if .ContainerArgs }}
+ Args: {{ range $arg := .ContainerArgs }}{{ $arg }} {{ end }}
+{{- end -}}
+{{- if .ContainerEnv }}
+ Env: {{ range $env := .ContainerEnv }}{{ $env }} {{ end }}
+{{- end -}}
+{{- if .ContainerWorkDir }}
+ Dir: {{ .ContainerWorkDir }}
+{{- end -}}
+{{- if .ContainerUser }}
+ User: {{ .ContainerUser }}
+{{- end }}
+{{- if .ContainerMounts }}
+Mounts:
+{{- end }}
+{{- range $mount := .ContainerMounts }}
+ Target = {{ $mount.Target }}
+ Source = {{ $mount.Source }}
+ ReadOnly = {{ $mount.ReadOnly }}
+ Type = {{ $mount.Type }}
+{{- end -}}
+{{- if .HasResources }}
+Resources:
+{{- if .HasResourceReservations }}
+ Reservations:
+{{- if gt .ResourceReservationNanoCPUs 0.0 }}
+ CPU: {{ .ResourceReservationNanoCPUs }}
+{{- end }}
+{{- if .ResourceReservationMemory }}
+ Memory: {{ .ResourceReservationMemory }}
+{{- end }}{{ end }}
+{{- if .HasResourceLimits }}
+ Limits:
+{{- if gt .ResourceLimitsNanoCPUs 0.0 }}
+ CPU: {{ .ResourceLimitsNanoCPUs }}
+{{- end }}
+{{- if .ResourceLimitMemory }}
+ Memory: {{ .ResourceLimitMemory }}
+{{- end }}{{ end }}{{ end }}
+{{- if .Networks }}
+Networks:
+{{- range $network := .Networks }} {{ $network }}{{ end }} {{ end }}
+Endpoint Mode: {{ .EndpointMode }}
+{{- if .Ports }}
+Ports:
+{{- range $port := .Ports }}
+ PublishedPort = {{ $port.PublishedPort }}
+ Protocol = {{ $port.Protocol }}
+ TargetPort = {{ $port.TargetPort }}
+ PublishMode = {{ $port.PublishMode }}
+{{- end }} {{ end -}}
+`
+
+// NewServiceFormat returns a Format for rendering using a Context
+func NewServiceFormat(source string) Format {
+ switch source {
+ case PrettyFormatKey:
+ return serviceInspectPrettyTemplate
+ default:
+ return Format(strings.TrimPrefix(source, RawFormatKey))
+ }
+}
+
+func resolveNetworks(service swarm.Service, getNetwork inspect.GetRefFunc) map[string]string {
+ networkNames := make(map[string]string)
+ for _, network := range service.Spec.TaskTemplate.Networks {
+ if resolved, _, err := getNetwork(network.Target); err == nil {
+ if resolvedNetwork, ok := resolved.(types.NetworkResource); ok {
+ networkNames[resolvedNetwork.ID] = resolvedNetwork.Name
+ }
+ }
+ }
+ return networkNames
+}
+
+// ServiceInspectWrite renders the context for a list of services
+func ServiceInspectWrite(ctx Context, refs []string, getRef, getNetwork inspect.GetRefFunc) error {
+ if ctx.Format != serviceInspectPrettyTemplate {
+ return inspect.Inspect(ctx.Output, refs, string(ctx.Format), getRef)
+ }
+ render := func(format func(subContext subContext) error) error {
+ for _, ref := range refs {
+ serviceI, _, err := getRef(ref)
+ if err != nil {
+ return err
+ }
+ service, ok := serviceI.(swarm.Service)
+ if !ok {
+ return errors.Errorf("got wrong object to inspect")
+ }
+ if err := format(&serviceInspectContext{Service: service, networkNames: resolveNetworks(service, getNetwork)}); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(&serviceInspectContext{}, render)
+}
+
+type serviceInspectContext struct {
+ swarm.Service
+ subContext
+
+ // networkNames is a map from network IDs (as found in
+ // Networks[x].Target) to network names.
+ networkNames map[string]string
+}
+
+func (ctx *serviceInspectContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(ctx)
+}
+
+func (ctx *serviceInspectContext) ID() string {
+ return ctx.Service.ID
+}
+
+func (ctx *serviceInspectContext) Name() string {
+ return ctx.Service.Spec.Name
+}
+
+func (ctx *serviceInspectContext) Labels() map[string]string {
+ return ctx.Service.Spec.Labels
+}
+
+func (ctx *serviceInspectContext) IsModeGlobal() bool {
+ return ctx.Service.Spec.Mode.Global != nil
+}
+
+func (ctx *serviceInspectContext) IsModeReplicated() bool {
+ return ctx.Service.Spec.Mode.Replicated != nil
+}
+
+func (ctx *serviceInspectContext) ModeReplicatedReplicas() *uint64 {
+ return ctx.Service.Spec.Mode.Replicated.Replicas
+}
+
+func (ctx *serviceInspectContext) HasUpdateStatus() bool {
+ return ctx.Service.UpdateStatus != nil && ctx.Service.UpdateStatus.State != ""
+}
+
+func (ctx *serviceInspectContext) UpdateStatusState() swarm.UpdateState {
+ return ctx.Service.UpdateStatus.State
+}
+
+func (ctx *serviceInspectContext) HasUpdateStatusStarted() bool {
+ return ctx.Service.UpdateStatus.StartedAt != nil
+}
+
+func (ctx *serviceInspectContext) UpdateStatusStarted() string {
+ return units.HumanDuration(time.Since(*ctx.Service.UpdateStatus.StartedAt)) + " ago"
+}
+
+func (ctx *serviceInspectContext) UpdateIsCompleted() bool {
+ return ctx.Service.UpdateStatus.State == swarm.UpdateStateCompleted && ctx.Service.UpdateStatus.CompletedAt != nil
+}
+
+func (ctx *serviceInspectContext) UpdateStatusCompleted() string {
+ return units.HumanDuration(time.Since(*ctx.Service.UpdateStatus.CompletedAt)) + " ago"
+}
+
+func (ctx *serviceInspectContext) UpdateStatusMessage() string {
+ return ctx.Service.UpdateStatus.Message
+}
+
+func (ctx *serviceInspectContext) TaskPlacementConstraints() []string {
+ if ctx.Service.Spec.TaskTemplate.Placement != nil {
+ return ctx.Service.Spec.TaskTemplate.Placement.Constraints
+ }
+ return nil
+}
+
+func (ctx *serviceInspectContext) TaskPlacementPreferences() []string {
+ if ctx.Service.Spec.TaskTemplate.Placement == nil {
+ return nil
+ }
+ var strings []string
+ for _, pref := range ctx.Service.Spec.TaskTemplate.Placement.Preferences {
+ if pref.Spread != nil {
+ strings = append(strings, "spread="+pref.Spread.SpreadDescriptor)
+ }
+ }
+ return strings
+}
+
+func (ctx *serviceInspectContext) HasUpdateConfig() bool {
+ return ctx.Service.Spec.UpdateConfig != nil
+}
+
+func (ctx *serviceInspectContext) UpdateParallelism() uint64 {
+ return ctx.Service.Spec.UpdateConfig.Parallelism
+}
+
+func (ctx *serviceInspectContext) HasUpdateDelay() bool {
+ return ctx.Service.Spec.UpdateConfig.Delay.Nanoseconds() > 0
+}
+
+func (ctx *serviceInspectContext) UpdateDelay() time.Duration {
+ return ctx.Service.Spec.UpdateConfig.Delay
+}
+
+func (ctx *serviceInspectContext) UpdateOnFailure() string {
+ return ctx.Service.Spec.UpdateConfig.FailureAction
+}
+
+func (ctx *serviceInspectContext) UpdateOrder() string {
+ return ctx.Service.Spec.UpdateConfig.Order
+}
+
+func (ctx *serviceInspectContext) HasUpdateMonitor() bool {
+ return ctx.Service.Spec.UpdateConfig.Monitor.Nanoseconds() > 0
+}
+
+func (ctx *serviceInspectContext) UpdateMonitor() time.Duration {
+ return ctx.Service.Spec.UpdateConfig.Monitor
+}
+
+func (ctx *serviceInspectContext) UpdateMaxFailureRatio() float32 {
+ return ctx.Service.Spec.UpdateConfig.MaxFailureRatio
+}
+
+func (ctx *serviceInspectContext) HasRollbackConfig() bool {
+ return ctx.Service.Spec.RollbackConfig != nil
+}
+
+func (ctx *serviceInspectContext) RollbackParallelism() uint64 {
+ return ctx.Service.Spec.RollbackConfig.Parallelism
+}
+
+func (ctx *serviceInspectContext) HasRollbackDelay() bool {
+ return ctx.Service.Spec.RollbackConfig.Delay.Nanoseconds() > 0
+}
+
+func (ctx *serviceInspectContext) RollbackDelay() time.Duration {
+ return ctx.Service.Spec.RollbackConfig.Delay
+}
+
+func (ctx *serviceInspectContext) RollbackOnFailure() string {
+ return ctx.Service.Spec.RollbackConfig.FailureAction
+}
+
+func (ctx *serviceInspectContext) HasRollbackMonitor() bool {
+ return ctx.Service.Spec.RollbackConfig.Monitor.Nanoseconds() > 0
+}
+
+func (ctx *serviceInspectContext) RollbackMonitor() time.Duration {
+ return ctx.Service.Spec.RollbackConfig.Monitor
+}
+
+func (ctx *serviceInspectContext) RollbackMaxFailureRatio() float32 {
+ return ctx.Service.Spec.RollbackConfig.MaxFailureRatio
+}
+
+func (ctx *serviceInspectContext) RollbackOrder() string {
+ return ctx.Service.Spec.RollbackConfig.Order
+}
+
+func (ctx *serviceInspectContext) ContainerImage() string {
+ return ctx.Service.Spec.TaskTemplate.ContainerSpec.Image
+}
+
+func (ctx *serviceInspectContext) ContainerArgs() []string {
+ return ctx.Service.Spec.TaskTemplate.ContainerSpec.Args
+}
+
+func (ctx *serviceInspectContext) ContainerEnv() []string {
+ return ctx.Service.Spec.TaskTemplate.ContainerSpec.Env
+}
+
+func (ctx *serviceInspectContext) ContainerWorkDir() string {
+ return ctx.Service.Spec.TaskTemplate.ContainerSpec.Dir
+}
+
+func (ctx *serviceInspectContext) ContainerUser() string {
+ return ctx.Service.Spec.TaskTemplate.ContainerSpec.User
+}
+
+func (ctx *serviceInspectContext) ContainerMounts() []mounttypes.Mount {
+ return ctx.Service.Spec.TaskTemplate.ContainerSpec.Mounts
+}
+
+func (ctx *serviceInspectContext) HasResources() bool {
+ return ctx.Service.Spec.TaskTemplate.Resources != nil
+}
+
+func (ctx *serviceInspectContext) HasResourceReservations() bool {
+ if ctx.Service.Spec.TaskTemplate.Resources == nil || ctx.Service.Spec.TaskTemplate.Resources.Reservations == nil {
+ return false
+ }
+ return ctx.Service.Spec.TaskTemplate.Resources.Reservations.NanoCPUs > 0 || ctx.Service.Spec.TaskTemplate.Resources.Reservations.MemoryBytes > 0
+}
+
+func (ctx *serviceInspectContext) ResourceReservationNanoCPUs() float64 {
+ if ctx.Service.Spec.TaskTemplate.Resources.Reservations.NanoCPUs == 0 {
+ return float64(0)
+ }
+ return float64(ctx.Service.Spec.TaskTemplate.Resources.Reservations.NanoCPUs) / 1e9
+}
+
+func (ctx *serviceInspectContext) ResourceReservationMemory() string {
+ if ctx.Service.Spec.TaskTemplate.Resources.Reservations.MemoryBytes == 0 {
+ return ""
+ }
+ return units.BytesSize(float64(ctx.Service.Spec.TaskTemplate.Resources.Reservations.MemoryBytes))
+}
+
+func (ctx *serviceInspectContext) HasResourceLimits() bool {
+ if ctx.Service.Spec.TaskTemplate.Resources == nil || ctx.Service.Spec.TaskTemplate.Resources.Limits == nil {
+ return false
+ }
+ return ctx.Service.Spec.TaskTemplate.Resources.Limits.NanoCPUs > 0 || ctx.Service.Spec.TaskTemplate.Resources.Limits.MemoryBytes > 0
+}
+
+func (ctx *serviceInspectContext) ResourceLimitsNanoCPUs() float64 {
+ return float64(ctx.Service.Spec.TaskTemplate.Resources.Limits.NanoCPUs) / 1e9
+}
+
+func (ctx *serviceInspectContext) ResourceLimitMemory() string {
+ if ctx.Service.Spec.TaskTemplate.Resources.Limits.MemoryBytes == 0 {
+ return ""
+ }
+ return units.BytesSize(float64(ctx.Service.Spec.TaskTemplate.Resources.Limits.MemoryBytes))
+}
+
+func (ctx *serviceInspectContext) Networks() []string {
+ var out []string
+ for _, n := range ctx.Service.Spec.TaskTemplate.Networks {
+ if name, ok := ctx.networkNames[n.Target]; ok {
+ out = append(out, name)
+ } else {
+ out = append(out, n.Target)
+ }
+ }
+ return out
+}
+
+func (ctx *serviceInspectContext) EndpointMode() string {
+ if ctx.Service.Spec.EndpointSpec == nil {
+ return ""
+ }
+
+ return string(ctx.Service.Spec.EndpointSpec.Mode)
+}
+
+func (ctx *serviceInspectContext) Ports() []swarm.PortConfig {
+ return ctx.Service.Endpoint.Ports
+}
+
+const (
+ defaultServiceTableFormat = "table {{.ID}}\t{{.Name}}\t{{.Mode}}\t{{.Replicas}}\t{{.Image}}\t{{.Ports}}"
+
+ serviceIDHeader = "ID"
+ modeHeader = "MODE"
+ replicasHeader = "REPLICAS"
+)
+
+// NewServiceListFormat returns a Format for rendering using a service Context
+func NewServiceListFormat(source string, quiet bool) Format {
+ switch source {
+ case TableFormatKey:
+ if quiet {
+ return defaultQuietFormat
+ }
+ return defaultServiceTableFormat
+ case RawFormatKey:
+ if quiet {
+ return `id: {{.ID}}`
+ }
+ return `id: {{.ID}}\nname: {{.Name}}\nmode: {{.Mode}}\nreplicas: {{.Replicas}}\nimage: {{.Image}}\nports: {{.Ports}}\n`
+ }
+ return Format(source)
+}
+
+// ServiceListInfo stores the information about mode and replicas to be used by template
+type ServiceListInfo struct {
+ Mode string
+ Replicas string
+}
+
+// ServiceListWrite writes the context
+func ServiceListWrite(ctx Context, services []swarm.Service, info map[string]ServiceListInfo) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, service := range services {
+ serviceCtx := &serviceContext{service: service, mode: info[service.ID].Mode, replicas: info[service.ID].Replicas}
+ if err := format(serviceCtx); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ serviceCtx := serviceContext{}
+ serviceCtx.header = map[string]string{
+ "ID": serviceIDHeader,
+ "Name": nameHeader,
+ "Mode": modeHeader,
+ "Replicas": replicasHeader,
+ "Image": imageHeader,
+ "Ports": portsHeader,
+ }
+ return ctx.Write(&serviceCtx, render)
+}
+
+type serviceContext struct {
+ HeaderContext
+ service swarm.Service
+ mode string
+ replicas string
+}
+
+func (c *serviceContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *serviceContext) ID() string {
+ return stringid.TruncateID(c.service.ID)
+}
+
+func (c *serviceContext) Name() string {
+ return c.service.Spec.Name
+}
+
+func (c *serviceContext) Mode() string {
+ return c.mode
+}
+
+func (c *serviceContext) Replicas() string {
+ return c.replicas
+}
+
+func (c *serviceContext) Image() string {
+ image := c.service.Spec.TaskTemplate.ContainerSpec.Image
+ if ref, err := reference.ParseNormalizedNamed(image); err == nil {
+ // update image string for display, (strips any digest)
+ if nt, ok := ref.(reference.NamedTagged); ok {
+ if namedTagged, err := reference.WithTag(reference.TrimNamed(nt), nt.Tag()); err == nil {
+ image = reference.FamiliarString(namedTagged)
+ }
+ }
+ }
+
+ return image
+}
+
+func (c *serviceContext) Ports() string {
+ if c.service.Spec.EndpointSpec == nil || c.service.Spec.EndpointSpec.Ports == nil {
+ return ""
+ }
+ ports := []string{}
+ for _, pConfig := range c.service.Spec.EndpointSpec.Ports {
+ if pConfig.PublishMode == swarm.PortConfigPublishModeIngress {
+ ports = append(ports, fmt.Sprintf("*:%d->%d/%s",
+ pConfig.PublishedPort,
+ pConfig.TargetPort,
+ pConfig.Protocol,
+ ))
+ }
+ }
+ return strings.Join(ports, ",")
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/stack.go b/vendor/github.com/docker/cli/cli/command/formatter/stack.go
new file mode 100644
index 0000000..676bcc0
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/stack.go
@@ -0,0 +1,67 @@
+package formatter
+
+import (
+ "strconv"
+)
+
+const (
+ defaultStackTableFormat = "table {{.Name}}\t{{.Services}}"
+
+ stackServicesHeader = "SERVICES"
+)
+
+// Stack contains deployed stack information.
+type Stack struct {
+ // Name is the name of the stack
+ Name string
+ // Services is the number of the services
+ Services int
+}
+
+// NewStackFormat returns a format for use with a stack Context
+func NewStackFormat(source string) Format {
+ switch source {
+ case TableFormatKey:
+ return defaultStackTableFormat
+ }
+ return Format(source)
+}
+
+// StackWrite writes formatted stacks using the Context
+func StackWrite(ctx Context, stacks []*Stack) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, stack := range stacks {
+ if err := format(&stackContext{s: stack}); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(newStackContext(), render)
+}
+
+type stackContext struct {
+ HeaderContext
+ s *Stack
+}
+
+func newStackContext() *stackContext {
+ stackCtx := stackContext{}
+ stackCtx.header = map[string]string{
+ "Name": nameHeader,
+ "Services": stackServicesHeader,
+ }
+ return &stackCtx
+}
+
+func (s *stackContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(s)
+}
+
+func (s *stackContext) Name() string {
+ return s.s.Name
+}
+
+func (s *stackContext) Services() string {
+ return strconv.Itoa(s.s.Services)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/stats.go b/vendor/github.com/docker/cli/cli/command/formatter/stats.go
new file mode 100644
index 0000000..f53387e
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/stats.go
@@ -0,0 +1,218 @@
+package formatter
+
+import (
+ "fmt"
+ "sync"
+
+ units "github.com/docker/go-units"
+)
+
+const (
+ winOSType = "windows"
+ defaultStatsTableFormat = "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.NetIO}}\t{{.BlockIO}}\t{{.PIDs}}"
+ winDefaultStatsTableFormat = "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}"
+
+ containerHeader = "CONTAINER"
+ cpuPercHeader = "CPU %"
+ netIOHeader = "NET I/O"
+ blockIOHeader = "BLOCK I/O"
+ memPercHeader = "MEM %" // Used only on Linux
+ winMemUseHeader = "PRIV WORKING SET" // Used only on Windows
+ memUseHeader = "MEM USAGE / LIMIT" // Used only on Linux
+ pidsHeader = "PIDS" // Used only on Linux
+)
+
+// StatsEntry represents represents the statistics data collected from a container
+type StatsEntry struct {
+ Container string
+ Name string
+ ID string
+ CPUPercentage float64
+ Memory float64 // On Windows this is the private working set
+ MemoryLimit float64 // Not used on Windows
+ MemoryPercentage float64 // Not used on Windows
+ NetworkRx float64
+ NetworkTx float64
+ BlockRead float64
+ BlockWrite float64
+ PidsCurrent uint64 // Not used on Windows
+ IsInvalid bool
+}
+
+// ContainerStats represents an entity to store containers statistics synchronously
+type ContainerStats struct {
+ mutex sync.Mutex
+ StatsEntry
+ err error
+}
+
+// GetError returns the container statistics error.
+// This is used to determine whether the statistics are valid or not
+func (cs *ContainerStats) GetError() error {
+ cs.mutex.Lock()
+ defer cs.mutex.Unlock()
+ return cs.err
+}
+
+// SetErrorAndReset zeroes all the container statistics and store the error.
+// It is used when receiving time out error during statistics collecting to reduce lock overhead
+func (cs *ContainerStats) SetErrorAndReset(err error) {
+ cs.mutex.Lock()
+ defer cs.mutex.Unlock()
+ cs.CPUPercentage = 0
+ cs.Memory = 0
+ cs.MemoryPercentage = 0
+ cs.MemoryLimit = 0
+ cs.NetworkRx = 0
+ cs.NetworkTx = 0
+ cs.BlockRead = 0
+ cs.BlockWrite = 0
+ cs.PidsCurrent = 0
+ cs.err = err
+ cs.IsInvalid = true
+}
+
+// SetError sets container statistics error
+func (cs *ContainerStats) SetError(err error) {
+ cs.mutex.Lock()
+ defer cs.mutex.Unlock()
+ cs.err = err
+ if err != nil {
+ cs.IsInvalid = true
+ }
+}
+
+// SetStatistics set the container statistics
+func (cs *ContainerStats) SetStatistics(s StatsEntry) {
+ cs.mutex.Lock()
+ defer cs.mutex.Unlock()
+ s.Container = cs.Container
+ cs.StatsEntry = s
+}
+
+// GetStatistics returns container statistics with other meta data such as the container name
+func (cs *ContainerStats) GetStatistics() StatsEntry {
+ cs.mutex.Lock()
+ defer cs.mutex.Unlock()
+ return cs.StatsEntry
+}
+
+// NewStatsFormat returns a format for rendering an CStatsContext
+func NewStatsFormat(source, osType string) Format {
+ if source == TableFormatKey {
+ if osType == winOSType {
+ return Format(winDefaultStatsTableFormat)
+ }
+ return Format(defaultStatsTableFormat)
+ }
+ return Format(source)
+}
+
+// NewContainerStats returns a new ContainerStats entity and sets in it the given name
+func NewContainerStats(container string) *ContainerStats {
+ return &ContainerStats{StatsEntry: StatsEntry{Container: container}}
+}
+
+// ContainerStatsWrite renders the context for a list of containers statistics
+func ContainerStatsWrite(ctx Context, containerStats []StatsEntry, osType string) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, cstats := range containerStats {
+ containerStatsCtx := &containerStatsContext{
+ s: cstats,
+ os: osType,
+ }
+ if err := format(containerStatsCtx); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ memUsage := memUseHeader
+ if osType == winOSType {
+ memUsage = winMemUseHeader
+ }
+ containerStatsCtx := containerStatsContext{}
+ containerStatsCtx.header = map[string]string{
+ "Container": containerHeader,
+ "Name": nameHeader,
+ "ID": containerIDHeader,
+ "CPUPerc": cpuPercHeader,
+ "MemUsage": memUsage,
+ "MemPerc": memPercHeader,
+ "NetIO": netIOHeader,
+ "BlockIO": blockIOHeader,
+ "PIDs": pidsHeader,
+ }
+ containerStatsCtx.os = osType
+ return ctx.Write(&containerStatsCtx, render)
+}
+
+type containerStatsContext struct {
+ HeaderContext
+ s StatsEntry
+ os string
+}
+
+func (c *containerStatsContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *containerStatsContext) Container() string {
+ return c.s.Container
+}
+
+func (c *containerStatsContext) Name() string {
+ if len(c.s.Name) > 1 {
+ return c.s.Name[1:]
+ }
+ return "--"
+}
+
+func (c *containerStatsContext) ID() string {
+ return c.s.ID
+}
+
+func (c *containerStatsContext) CPUPerc() string {
+ if c.s.IsInvalid {
+ return fmt.Sprintf("--")
+ }
+ return fmt.Sprintf("%.2f%%", c.s.CPUPercentage)
+}
+
+func (c *containerStatsContext) MemUsage() string {
+ if c.s.IsInvalid {
+ return fmt.Sprintf("-- / --")
+ }
+ if c.os == winOSType {
+ return fmt.Sprintf("%s", units.BytesSize(c.s.Memory))
+ }
+ return fmt.Sprintf("%s / %s", units.BytesSize(c.s.Memory), units.BytesSize(c.s.MemoryLimit))
+}
+
+func (c *containerStatsContext) MemPerc() string {
+ if c.s.IsInvalid || c.os == winOSType {
+ return fmt.Sprintf("--")
+ }
+ return fmt.Sprintf("%.2f%%", c.s.MemoryPercentage)
+}
+
+func (c *containerStatsContext) NetIO() string {
+ if c.s.IsInvalid {
+ return fmt.Sprintf("--")
+ }
+ return fmt.Sprintf("%s / %s", units.HumanSizeWithPrecision(c.s.NetworkRx, 3), units.HumanSizeWithPrecision(c.s.NetworkTx, 3))
+}
+
+func (c *containerStatsContext) BlockIO() string {
+ if c.s.IsInvalid {
+ return fmt.Sprintf("--")
+ }
+ return fmt.Sprintf("%s / %s", units.HumanSizeWithPrecision(c.s.BlockRead, 3), units.HumanSizeWithPrecision(c.s.BlockWrite, 3))
+}
+
+func (c *containerStatsContext) PIDs() string {
+ if c.s.IsInvalid || c.os == winOSType {
+ return fmt.Sprintf("--")
+ }
+ return fmt.Sprintf("%d", c.s.PidsCurrent)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/task.go b/vendor/github.com/docker/cli/cli/command/formatter/task.go
new file mode 100644
index 0000000..6172b32
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/task.go
@@ -0,0 +1,150 @@
+package formatter
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/api/types/swarm"
+ "github.com/docker/docker/pkg/stringid"
+ "github.com/docker/go-units"
+)
+
+const (
+ defaultTaskTableFormat = "table {{.ID}}\t{{.Name}}\t{{.Image}}\t{{.Node}}\t{{.DesiredState}}\t{{.CurrentState}}\t{{.Error}}\t{{.Ports}}"
+
+ nodeHeader = "NODE"
+ taskIDHeader = "ID"
+ desiredStateHeader = "DESIRED STATE"
+ currentStateHeader = "CURRENT STATE"
+ errorHeader = "ERROR"
+
+ maxErrLength = 30
+)
+
+// NewTaskFormat returns a Format for rendering using a task Context
+func NewTaskFormat(source string, quiet bool) Format {
+ switch source {
+ case TableFormatKey:
+ if quiet {
+ return defaultQuietFormat
+ }
+ return defaultTaskTableFormat
+ case RawFormatKey:
+ if quiet {
+ return `id: {{.ID}}`
+ }
+ return `id: {{.ID}}\nname: {{.Name}}\nimage: {{.Image}}\nnode: {{.Node}}\ndesired_state: {{.DesiredState}}\ncurrent_state: {{.CurrentState}}\nerror: {{.Error}}\nports: {{.Ports}}\n`
+ }
+ return Format(source)
+}
+
+// TaskWrite writes the context
+func TaskWrite(ctx Context, tasks []swarm.Task, names map[string]string, nodes map[string]string) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, task := range tasks {
+ taskCtx := &taskContext{trunc: ctx.Trunc, task: task, name: names[task.ID], node: nodes[task.ID]}
+ if err := format(taskCtx); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ taskCtx := taskContext{}
+ taskCtx.header = taskHeaderContext{
+ "ID": taskIDHeader,
+ "Name": nameHeader,
+ "Image": imageHeader,
+ "Node": nodeHeader,
+ "DesiredState": desiredStateHeader,
+ "CurrentState": currentStateHeader,
+ "Error": errorHeader,
+ "Ports": portsHeader,
+ }
+ return ctx.Write(&taskCtx, render)
+}
+
+type taskHeaderContext map[string]string
+
+type taskContext struct {
+ HeaderContext
+ trunc bool
+ task swarm.Task
+ name string
+ node string
+}
+
+func (c *taskContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *taskContext) ID() string {
+ if c.trunc {
+ return stringid.TruncateID(c.task.ID)
+ }
+ return c.task.ID
+}
+
+func (c *taskContext) Name() string {
+ return c.name
+}
+
+func (c *taskContext) Image() string {
+ image := c.task.Spec.ContainerSpec.Image
+ if c.trunc {
+ ref, err := reference.ParseNormalizedNamed(image)
+ if err == nil {
+ // update image string for display, (strips any digest)
+ if nt, ok := ref.(reference.NamedTagged); ok {
+ if namedTagged, err := reference.WithTag(reference.TrimNamed(nt), nt.Tag()); err == nil {
+ image = reference.FamiliarString(namedTagged)
+ }
+ }
+ }
+ }
+ return image
+}
+
+func (c *taskContext) Node() string {
+ return c.node
+}
+
+func (c *taskContext) DesiredState() string {
+ return command.PrettyPrint(c.task.DesiredState)
+}
+
+func (c *taskContext) CurrentState() string {
+ return fmt.Sprintf("%s %s ago",
+ command.PrettyPrint(c.task.Status.State),
+ strings.ToLower(units.HumanDuration(time.Since(c.task.Status.Timestamp))),
+ )
+}
+
+func (c *taskContext) Error() string {
+ // Trim and quote the error message.
+ taskErr := c.task.Status.Err
+ if c.trunc && len(taskErr) > maxErrLength {
+ taskErr = fmt.Sprintf("%s…", taskErr[:maxErrLength-1])
+ }
+ if len(taskErr) > 0 {
+ taskErr = fmt.Sprintf("\"%s\"", taskErr)
+ }
+ return taskErr
+}
+
+func (c *taskContext) Ports() string {
+ if len(c.task.Status.PortStatus.Ports) == 0 {
+ return ""
+ }
+ ports := []string{}
+ for _, pConfig := range c.task.Status.PortStatus.Ports {
+ ports = append(ports, fmt.Sprintf("*:%d->%d/%s",
+ pConfig.PublishedPort,
+ pConfig.TargetPort,
+ pConfig.Protocol,
+ ))
+ }
+ return strings.Join(ports, ",")
+}
diff --git a/vendor/github.com/docker/cli/cli/command/formatter/volume.go b/vendor/github.com/docker/cli/cli/command/formatter/volume.go
new file mode 100644
index 0000000..342f2fb
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/formatter/volume.go
@@ -0,0 +1,131 @@
+package formatter
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/docker/api/types"
+ units "github.com/docker/go-units"
+)
+
+const (
+ defaultVolumeQuietFormat = "{{.Name}}"
+ defaultVolumeTableFormat = "table {{.Driver}}\t{{.Name}}"
+
+ volumeNameHeader = "VOLUME NAME"
+ mountpointHeader = "MOUNTPOINT"
+ linksHeader = "LINKS"
+ // Status header ?
+)
+
+// NewVolumeFormat returns a format for use with a volume Context
+func NewVolumeFormat(source string, quiet bool) Format {
+ switch source {
+ case TableFormatKey:
+ if quiet {
+ return defaultVolumeQuietFormat
+ }
+ return defaultVolumeTableFormat
+ case RawFormatKey:
+ if quiet {
+ return `name: {{.Name}}`
+ }
+ return `name: {{.Name}}\ndriver: {{.Driver}}\n`
+ }
+ return Format(source)
+}
+
+// VolumeWrite writes formatted volumes using the Context
+func VolumeWrite(ctx Context, volumes []*types.Volume) error {
+ render := func(format func(subContext subContext) error) error {
+ for _, volume := range volumes {
+ if err := format(&volumeContext{v: *volume}); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return ctx.Write(newVolumeContext(), render)
+}
+
+type volumeHeaderContext map[string]string
+
+func (c volumeHeaderContext) Label(name string) string {
+ n := strings.Split(name, ".")
+ r := strings.NewReplacer("-", " ", "_", " ")
+ h := r.Replace(n[len(n)-1])
+
+ return h
+}
+
+type volumeContext struct {
+ HeaderContext
+ v types.Volume
+}
+
+func newVolumeContext() *volumeContext {
+ volumeCtx := volumeContext{}
+ volumeCtx.header = volumeHeaderContext{
+ "Name": volumeNameHeader,
+ "Driver": driverHeader,
+ "Scope": scopeHeader,
+ "Mountpoint": mountpointHeader,
+ "Labels": labelsHeader,
+ "Links": linksHeader,
+ "Size": sizeHeader,
+ }
+ return &volumeCtx
+}
+
+func (c *volumeContext) MarshalJSON() ([]byte, error) {
+ return marshalJSON(c)
+}
+
+func (c *volumeContext) Name() string {
+ return c.v.Name
+}
+
+func (c *volumeContext) Driver() string {
+ return c.v.Driver
+}
+
+func (c *volumeContext) Scope() string {
+ return c.v.Scope
+}
+
+func (c *volumeContext) Mountpoint() string {
+ return c.v.Mountpoint
+}
+
+func (c *volumeContext) Labels() string {
+ if c.v.Labels == nil {
+ return ""
+ }
+
+ var joinLabels []string
+ for k, v := range c.v.Labels {
+ joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v))
+ }
+ return strings.Join(joinLabels, ",")
+}
+
+func (c *volumeContext) Label(name string) string {
+ if c.v.Labels == nil {
+ return ""
+ }
+ return c.v.Labels[name]
+}
+
+func (c *volumeContext) Links() string {
+ if c.v.UsageData == nil {
+ return "N/A"
+ }
+ return fmt.Sprintf("%d", c.v.UsageData.RefCount)
+}
+
+func (c *volumeContext) Size() string {
+ if c.v.UsageData == nil {
+ return "N/A"
+ }
+ return units.HumanSize(float64(c.v.UsageData.Size))
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/build.go b/vendor/github.com/docker/cli/cli/command/image/build.go
new file mode 100644
index 0000000..7397703
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/build.go
@@ -0,0 +1,503 @@
+package image
+
+import (
+ "archive/tar"
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "regexp"
+ "runtime"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/image/build"
+ "github.com/docker/cli/opts"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/api"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/pkg/archive"
+ "github.com/docker/docker/pkg/jsonmessage"
+ "github.com/docker/docker/pkg/progress"
+ "github.com/docker/docker/pkg/streamformatter"
+ "github.com/docker/docker/pkg/urlutil"
+ units "github.com/docker/go-units"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type buildOptions struct {
+ context string
+ dockerfileName string
+ tags opts.ListOpts
+ labels opts.ListOpts
+ buildArgs opts.ListOpts
+ extraHosts opts.ListOpts
+ ulimits *opts.UlimitOpt
+ memory opts.MemBytes
+ memorySwap opts.MemSwapBytes
+ shmSize opts.MemBytes
+ cpuShares int64
+ cpuPeriod int64
+ cpuQuota int64
+ cpuSetCpus string
+ cpuSetMems string
+ cgroupParent string
+ isolation string
+ quiet bool
+ noCache bool
+ rm bool
+ forceRm bool
+ pull bool
+ cacheFrom []string
+ compress bool
+ securityOpt []string
+ networkMode string
+ squash bool
+ target string
+ imageIDFile string
+ volumes opts.ListOpts
+}
+
+// dockerfileFromStdin returns true when the user specified that the Dockerfile
+// should be read from stdin instead of a file
+func (o buildOptions) dockerfileFromStdin() bool {
+ return o.dockerfileName == "-"
+}
+
+// contextFromStdin returns true when the user specified that the build context
+// should be read from stdin
+func (o buildOptions) contextFromStdin() bool {
+ return o.context == "-"
+}
+
+// NewBuildCommand creates a new `docker build` command
+func NewBuildCommand(dockerCli *command.DockerCli) *cobra.Command {
+ ulimits := make(map[string]*units.Ulimit)
+ options := buildOptions{
+ tags: opts.NewListOpts(validateTag),
+ buildArgs: opts.NewListOpts(opts.ValidateEnv),
+ ulimits: opts.NewUlimitOpt(&ulimits),
+ labels: opts.NewListOpts(opts.ValidateEnv),
+ extraHosts: opts.NewListOpts(opts.ValidateExtraHost),
+ volumes: opts.NewListOpts(nil),
+ }
+
+ cmd := &cobra.Command{
+ Use: "build [OPTIONS] PATH | URL | -",
+ Short: "Build an image from a Dockerfile",
+ Args: cli.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ options.context = args[0]
+ return runBuild(dockerCli, options)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.VarP(&options.tags, "tag", "t", "Name and optionally a tag in the 'name:tag' format")
+ flags.Var(&options.buildArgs, "build-arg", "Set build-time variables")
+ flags.Var(options.ulimits, "ulimit", "Ulimit options")
+ flags.StringVarP(&options.dockerfileName, "file", "f", "", "Name of the Dockerfile (Default is 'PATH/Dockerfile')")
+ flags.VarP(&options.memory, "memory", "m", "Memory limit")
+ flags.Var(&options.memorySwap, "memory-swap", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap")
+ flags.Var(&options.shmSize, "shm-size", "Size of /dev/shm")
+ flags.Int64VarP(&options.cpuShares, "cpu-shares", "c", 0, "CPU shares (relative weight)")
+ flags.Int64Var(&options.cpuPeriod, "cpu-period", 0, "Limit the CPU CFS (Completely Fair Scheduler) period")
+ flags.Int64Var(&options.cpuQuota, "cpu-quota", 0, "Limit the CPU CFS (Completely Fair Scheduler) quota")
+ flags.StringVar(&options.cpuSetCpus, "cpuset-cpus", "", "CPUs in which to allow execution (0-3, 0,1)")
+ flags.StringVar(&options.cpuSetMems, "cpuset-mems", "", "MEMs in which to allow execution (0-3, 0,1)")
+ flags.StringVar(&options.cgroupParent, "cgroup-parent", "", "Optional parent cgroup for the container")
+ flags.StringVar(&options.isolation, "isolation", "", "Container isolation technology")
+ flags.Var(&options.labels, "label", "Set metadata for an image")
+ flags.BoolVar(&options.noCache, "no-cache", false, "Do not use cache when building the image")
+ flags.BoolVar(&options.rm, "rm", true, "Remove intermediate containers after a successful build")
+ flags.BoolVar(&options.forceRm, "force-rm", false, "Always remove intermediate containers")
+ flags.BoolVarP(&options.quiet, "quiet", "q", false, "Suppress the build output and print image ID on success")
+ flags.BoolVar(&options.pull, "pull", false, "Always attempt to pull a newer version of the image")
+ flags.StringSliceVar(&options.cacheFrom, "cache-from", []string{}, "Images to consider as cache sources")
+ flags.BoolVar(&options.compress, "compress", false, "Compress the build context using gzip")
+ flags.StringSliceVar(&options.securityOpt, "security-opt", []string{}, "Security options")
+ flags.StringVar(&options.networkMode, "network", "default", "Set the networking mode for the RUN instructions during build")
+ flags.SetAnnotation("network", "version", []string{"1.25"})
+ flags.Var(&options.extraHosts, "add-host", "Add a custom host-to-IP mapping (host:ip)")
+ flags.StringVar(&options.target, "target", "", "Set the target build stage to build.")
+ flags.StringVar(&options.imageIDFile, "iidfile", "", "Write the image ID to the file")
+
+ command.AddTrustVerificationFlags(flags)
+
+ flags.BoolVar(&options.squash, "squash", false, "Squash newly built layers into a single new layer")
+ flags.SetAnnotation("squash", "experimental", nil)
+ flags.SetAnnotation("squash", "version", []string{"1.25"})
+ flags.VarP(&options.volumes, "volume", "v", "Bind mount a volume")
+
+ return cmd
+}
+
+// lastProgressOutput is the same as progress.Output except
+// that it only output with the last update. It is used in
+// non terminal scenarios to suppress verbose messages
+type lastProgressOutput struct {
+ output progress.Output
+}
+
+// WriteProgress formats progress information from a ProgressReader.
+func (out *lastProgressOutput) WriteProgress(prog progress.Progress) error {
+ if !prog.LastUpdate {
+ return nil
+ }
+
+ return out.output.WriteProgress(prog)
+}
+
+// nolint: gocyclo
+func runBuild(dockerCli *command.DockerCli, options buildOptions) error {
+ var (
+ buildCtx io.ReadCloser
+ dockerfileCtx io.ReadCloser
+ err error
+ contextDir string
+ tempDir string
+ relDockerfile string
+ progBuff io.Writer
+ buildBuff io.Writer
+ )
+
+ if options.dockerfileFromStdin() {
+ if options.contextFromStdin() {
+ return errors.New("invalid argument: can't use stdin for both build context and dockerfile")
+ }
+ dockerfileCtx = dockerCli.In()
+ }
+
+ specifiedContext := options.context
+ progBuff = dockerCli.Out()
+ buildBuff = dockerCli.Out()
+ if options.quiet {
+ progBuff = bytes.NewBuffer(nil)
+ buildBuff = bytes.NewBuffer(nil)
+ }
+ if options.imageIDFile != "" {
+ // Avoid leaving a stale file if we eventually fail
+ if err := os.Remove(options.imageIDFile); err != nil && !os.IsNotExist(err) {
+ return errors.Wrap(err, "Removing image ID file")
+ }
+ }
+
+ switch {
+ case options.contextFromStdin():
+ buildCtx, relDockerfile, err = build.GetContextFromReader(dockerCli.In(), options.dockerfileName)
+ case isLocalDir(specifiedContext):
+ contextDir, relDockerfile, err = build.GetContextFromLocalDir(specifiedContext, options.dockerfileName)
+ case urlutil.IsGitURL(specifiedContext):
+ tempDir, relDockerfile, err = build.GetContextFromGitURL(specifiedContext, options.dockerfileName)
+ case urlutil.IsURL(specifiedContext):
+ buildCtx, relDockerfile, err = build.GetContextFromURL(progBuff, specifiedContext, options.dockerfileName)
+ default:
+ return errors.Errorf("unable to prepare context: path %q not found", specifiedContext)
+ }
+
+ if err != nil {
+ if options.quiet && urlutil.IsURL(specifiedContext) {
+ fmt.Fprintln(dockerCli.Err(), progBuff)
+ }
+ return errors.Errorf("unable to prepare context: %s", err)
+ }
+
+ if tempDir != "" {
+ defer os.RemoveAll(tempDir)
+ contextDir = tempDir
+ }
+
+ if buildCtx == nil {
+ excludes, err := build.ReadDockerignore(contextDir)
+ if err != nil {
+ return err
+ }
+
+ if err := build.ValidateContextDirectory(contextDir, excludes); err != nil {
+ return errors.Errorf("error checking context: '%s'.", err)
+ }
+
+ // And canonicalize dockerfile name to a platform-independent one
+ relDockerfile, err = archive.CanonicalTarNameForPath(relDockerfile)
+ if err != nil {
+ return errors.Errorf("cannot canonicalize dockerfile path %s: %v", relDockerfile, err)
+ }
+
+ excludes = build.TrimBuildFilesFromExcludes(excludes, relDockerfile, options.dockerfileFromStdin())
+
+ compression := archive.Uncompressed
+ if options.compress {
+ compression = archive.Gzip
+ }
+ buildCtx, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
+ Compression: compression,
+ ExcludePatterns: excludes,
+ })
+ if err != nil {
+ return err
+ }
+ }
+
+ // replace Dockerfile if added dynamically
+ if dockerfileCtx != nil {
+ buildCtx, relDockerfile, err = build.AddDockerfileToBuildContext(dockerfileCtx, buildCtx)
+ if err != nil {
+ return err
+ }
+ }
+
+ ctx := context.Background()
+
+ var resolvedTags []*resolvedTag
+ if command.IsTrusted() {
+ translator := func(ctx context.Context, ref reference.NamedTagged) (reference.Canonical, error) {
+ return TrustedReference(ctx, dockerCli, ref, nil)
+ }
+ // Wrap the tar archive to replace the Dockerfile entry with the rewritten
+ // Dockerfile which uses trusted pulls.
+ buildCtx = replaceDockerfileTarWrapper(ctx, buildCtx, relDockerfile, translator, &resolvedTags)
+ }
+
+ // Setup an upload progress bar
+ progressOutput := streamformatter.NewProgressOutput(progBuff)
+ if !dockerCli.Out().IsTerminal() {
+ progressOutput = &lastProgressOutput{output: progressOutput}
+ }
+
+ var body io.Reader = progress.NewProgressReader(buildCtx, progressOutput, 0, "", "Sending build context to Docker daemon")
+
+ authConfigs, _ := dockerCli.GetAllCredentials()
+ buildOptions := types.ImageBuildOptions{
+ Memory: options.memory.Value(),
+ MemorySwap: options.memorySwap.Value(),
+ Tags: options.tags.GetAll(),
+ SuppressOutput: options.quiet,
+ NoCache: options.noCache,
+ Remove: options.rm,
+ ForceRemove: options.forceRm,
+ PullParent: options.pull,
+ Isolation: container.Isolation(options.isolation),
+ CPUSetCPUs: options.cpuSetCpus,
+ CPUSetMems: options.cpuSetMems,
+ CPUShares: options.cpuShares,
+ CPUQuota: options.cpuQuota,
+ CPUPeriod: options.cpuPeriod,
+ CgroupParent: options.cgroupParent,
+ Dockerfile: relDockerfile,
+ ShmSize: options.shmSize.Value(),
+ Ulimits: options.ulimits.GetList(),
+ BuildArgs: dockerCli.ConfigFile().ParseProxyConfig(dockerCli.Client().DaemonHost(), options.buildArgs.GetAll()),
+ AuthConfigs: authConfigs,
+ Labels: opts.ConvertKVStringsToMap(options.labels.GetAll()),
+ CacheFrom: options.cacheFrom,
+ SecurityOpt: options.securityOpt,
+ NetworkMode: options.networkMode,
+ Squash: options.squash,
+ ExtraHosts: options.extraHosts.GetAll(),
+ Target: options.target,
+ Volumes: options.volumes.GetAll(),
+ }
+
+ response, err := dockerCli.Client().ImageBuild(ctx, body, buildOptions)
+ if err != nil {
+ if options.quiet {
+ fmt.Fprintf(dockerCli.Err(), "%s", progBuff)
+ }
+ return err
+ }
+ defer response.Body.Close()
+
+ imageID := ""
+ aux := func(auxJSON *json.RawMessage) {
+ var result types.BuildResult
+ if err := json.Unmarshal(*auxJSON, &result); err != nil {
+ fmt.Fprintf(dockerCli.Err(), "Failed to parse aux message: %s", err)
+ } else {
+ imageID = result.ID
+ }
+ }
+
+ err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, dockerCli.Out().FD(), dockerCli.Out().IsTerminal(), aux)
+ if err != nil {
+ if jerr, ok := err.(*jsonmessage.JSONError); ok {
+ // If no error code is set, default to 1
+ if jerr.Code == 0 {
+ jerr.Code = 1
+ }
+ if options.quiet {
+ fmt.Fprintf(dockerCli.Err(), "%s%s", progBuff, buildBuff)
+ }
+ return cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
+ }
+ return err
+ }
+
+ // Windows: show error message about modified file permissions if the
+ // daemon isn't running Windows.
+ if response.OSType != "windows" && runtime.GOOS == "windows" && !options.quiet {
+ fmt.Fprintln(dockerCli.Out(), "SECURITY WARNING: You are building a Docker "+
+ "image from Windows against a non-Windows Docker host. All files and "+
+ "directories added to build context will have '-rwxr-xr-x' permissions. "+
+ "It is recommended to double check and reset permissions for sensitive "+
+ "files and directories.")
+ }
+
+ // Everything worked so if -q was provided the output from the daemon
+ // should be just the image ID and we'll print that to stdout.
+ if options.quiet {
+ imageID = fmt.Sprintf("%s", buildBuff)
+ fmt.Fprintf(dockerCli.Out(), imageID)
+ }
+
+ if options.imageIDFile != "" {
+ if imageID == "" {
+ return errors.Errorf("Server did not provide an image ID. Cannot write %s", options.imageIDFile)
+ }
+ if err := ioutil.WriteFile(options.imageIDFile, []byte(imageID), 0666); err != nil {
+ return err
+ }
+ }
+ if command.IsTrusted() {
+ // Since the build was successful, now we must tag any of the resolved
+ // images from the above Dockerfile rewrite.
+ for _, resolved := range resolvedTags {
+ if err := TagTrusted(ctx, dockerCli, resolved.digestRef, resolved.tagRef); err != nil {
+ return err
+ }
+ }
+ }
+
+ return nil
+}
+
+func isLocalDir(c string) bool {
+ _, err := os.Stat(c)
+ return err == nil
+}
+
+type translatorFunc func(context.Context, reference.NamedTagged) (reference.Canonical, error)
+
+// validateTag checks if the given image name can be resolved.
+func validateTag(rawRepo string) (string, error) {
+ _, err := reference.ParseNormalizedNamed(rawRepo)
+ if err != nil {
+ return "", err
+ }
+
+ return rawRepo, nil
+}
+
+var dockerfileFromLinePattern = regexp.MustCompile(`(?i)^[\s]*FROM[ \f\r\t\v]+(?P<image>[^ \f\r\t\v\n#]+)`)
+
+// resolvedTag records the repository, tag, and resolved digest reference
+// from a Dockerfile rewrite.
+type resolvedTag struct {
+ digestRef reference.Canonical
+ tagRef reference.NamedTagged
+}
+
+// rewriteDockerfileFrom rewrites the given Dockerfile by resolving images in
+// "FROM <image>" instructions to a digest reference. `translator` is a
+// function that takes a repository name and tag reference and returns a
+// trusted digest reference.
+func rewriteDockerfileFrom(ctx context.Context, dockerfile io.Reader, translator translatorFunc) (newDockerfile []byte, resolvedTags []*resolvedTag, err error) {
+ scanner := bufio.NewScanner(dockerfile)
+ buf := bytes.NewBuffer(nil)
+
+ // Scan the lines of the Dockerfile, looking for a "FROM" line.
+ for scanner.Scan() {
+ line := scanner.Text()
+
+ matches := dockerfileFromLinePattern.FindStringSubmatch(line)
+ if matches != nil && matches[1] != api.NoBaseImageSpecifier {
+ // Replace the line with a resolved "FROM repo@digest"
+ var ref reference.Named
+ ref, err = reference.ParseNormalizedNamed(matches[1])
+ if err != nil {
+ return nil, nil, err
+ }
+ ref = reference.TagNameOnly(ref)
+ if ref, ok := ref.(reference.NamedTagged); ok && command.IsTrusted() {
+ trustedRef, err := translator(ctx, ref)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", reference.FamiliarString(trustedRef)))
+ resolvedTags = append(resolvedTags, &resolvedTag{
+ digestRef: trustedRef,
+ tagRef: ref,
+ })
+ }
+ }
+
+ _, err := fmt.Fprintln(buf, line)
+ if err != nil {
+ return nil, nil, err
+ }
+ }
+
+ return buf.Bytes(), resolvedTags, scanner.Err()
+}
+
+// replaceDockerfileTarWrapper wraps the given input tar archive stream and
+// replaces the entry with the given Dockerfile name with the contents of the
+// new Dockerfile. Returns a new tar archive stream with the replaced
+// Dockerfile.
+func replaceDockerfileTarWrapper(ctx context.Context, inputTarStream io.ReadCloser, dockerfileName string, translator translatorFunc, resolvedTags *[]*resolvedTag) io.ReadCloser {
+ pipeReader, pipeWriter := io.Pipe()
+ go func() {
+ tarReader := tar.NewReader(inputTarStream)
+ tarWriter := tar.NewWriter(pipeWriter)
+
+ defer inputTarStream.Close()
+
+ for {
+ hdr, err := tarReader.Next()
+ if err == io.EOF {
+ // Signals end of archive.
+ tarWriter.Close()
+ pipeWriter.Close()
+ return
+ }
+ if err != nil {
+ pipeWriter.CloseWithError(err)
+ return
+ }
+
+ content := io.Reader(tarReader)
+ if hdr.Name == dockerfileName {
+ // This entry is the Dockerfile. Since the tar archive was
+ // generated from a directory on the local filesystem, the
+ // Dockerfile will only appear once in the archive.
+ var newDockerfile []byte
+ newDockerfile, *resolvedTags, err = rewriteDockerfileFrom(ctx, content, translator)
+ if err != nil {
+ pipeWriter.CloseWithError(err)
+ return
+ }
+ hdr.Size = int64(len(newDockerfile))
+ content = bytes.NewBuffer(newDockerfile)
+ }
+
+ if err := tarWriter.WriteHeader(hdr); err != nil {
+ pipeWriter.CloseWithError(err)
+ return
+ }
+
+ if _, err := io.Copy(tarWriter, content); err != nil {
+ pipeWriter.CloseWithError(err)
+ return
+ }
+ }
+ }()
+
+ return pipeReader
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/build/context.go b/vendor/github.com/docker/cli/cli/command/image/build/context.go
new file mode 100644
index 0000000..b1457bd
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/build/context.go
@@ -0,0 +1,377 @@
+package build
+
+import (
+ "archive/tar"
+ "bufio"
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/docker/docker/builder/remotecontext/git"
+ "github.com/docker/docker/pkg/archive"
+ "github.com/docker/docker/pkg/fileutils"
+ "github.com/docker/docker/pkg/ioutils"
+ "github.com/docker/docker/pkg/progress"
+ "github.com/docker/docker/pkg/streamformatter"
+ "github.com/docker/docker/pkg/stringid"
+ "github.com/pkg/errors"
+)
+
+const (
+ // DefaultDockerfileName is the Default filename with Docker commands, read by docker build
+ DefaultDockerfileName string = "Dockerfile"
+ // archiveHeaderSize is the number of bytes in an archive header
+ archiveHeaderSize = 512
+)
+
+// ValidateContextDirectory checks if all the contents of the directory
+// can be read and returns an error if some files can't be read
+// symlinks which point to non-existing files don't trigger an error
+func ValidateContextDirectory(srcPath string, excludes []string) error {
+ contextRoot, err := getContextRoot(srcPath)
+ if err != nil {
+ return err
+ }
+ return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error {
+ if err != nil {
+ if os.IsPermission(err) {
+ return errors.Errorf("can't stat '%s'", filePath)
+ }
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+ }
+
+ // skip this directory/file if it's not in the path, it won't get added to the context
+ if relFilePath, err := filepath.Rel(contextRoot, filePath); err != nil {
+ return err
+ } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
+ return err
+ } else if skip {
+ if f.IsDir() {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+
+ // skip checking if symlinks point to non-existing files, such symlinks can be useful
+ // also skip named pipes, because they hanging on open
+ if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
+ return nil
+ }
+
+ if !f.IsDir() {
+ currentFile, err := os.Open(filePath)
+ if err != nil && os.IsPermission(err) {
+ return errors.Errorf("no permission to read from '%s'", filePath)
+ }
+ currentFile.Close()
+ }
+ return nil
+ })
+}
+
+// GetContextFromReader will read the contents of the given reader as either a
+// Dockerfile or tar archive. Returns a tar archive used as a context and a
+// path to the Dockerfile inside the tar.
+func GetContextFromReader(r io.ReadCloser, dockerfileName string) (out io.ReadCloser, relDockerfile string, err error) {
+ buf := bufio.NewReader(r)
+
+ magic, err := buf.Peek(archiveHeaderSize)
+ if err != nil && err != io.EOF {
+ return nil, "", errors.Errorf("failed to peek context header from STDIN: %v", err)
+ }
+
+ if IsArchive(magic) {
+ return ioutils.NewReadCloserWrapper(buf, func() error { return r.Close() }), dockerfileName, nil
+ }
+
+ if dockerfileName == "-" {
+ return nil, "", errors.New("build context is not an archive")
+ }
+
+ // Input should be read as a Dockerfile.
+ tmpDir, err := ioutil.TempDir("", "docker-build-context-")
+ if err != nil {
+ return nil, "", errors.Errorf("unable to create temporary context directory: %v", err)
+ }
+
+ f, err := os.Create(filepath.Join(tmpDir, DefaultDockerfileName))
+ if err != nil {
+ return nil, "", err
+ }
+ _, err = io.Copy(f, buf)
+ if err != nil {
+ f.Close()
+ return nil, "", err
+ }
+
+ if err := f.Close(); err != nil {
+ return nil, "", err
+ }
+ if err := r.Close(); err != nil {
+ return nil, "", err
+ }
+
+ tar, err := archive.Tar(tmpDir, archive.Uncompressed)
+ if err != nil {
+ return nil, "", err
+ }
+
+ return ioutils.NewReadCloserWrapper(tar, func() error {
+ err := tar.Close()
+ os.RemoveAll(tmpDir)
+ return err
+ }), DefaultDockerfileName, nil
+
+}
+
+// IsArchive checks for the magic bytes of a tar or any supported compression
+// algorithm.
+func IsArchive(header []byte) bool {
+ compression := archive.DetectCompression(header)
+ if compression != archive.Uncompressed {
+ return true
+ }
+ r := tar.NewReader(bytes.NewBuffer(header))
+ _, err := r.Next()
+ return err == nil
+}
+
+// GetContextFromGitURL uses a Git URL as context for a `docker build`. The
+// git repo is cloned into a temporary directory used as the context directory.
+// Returns the absolute path to the temporary context directory, the relative
+// path of the dockerfile in that context directory, and a non-nil error on
+// success.
+func GetContextFromGitURL(gitURL, dockerfileName string) (string, string, error) {
+ if _, err := exec.LookPath("git"); err != nil {
+ return "", "", errors.Wrapf(err, "unable to find 'git'")
+ }
+ absContextDir, err := git.Clone(gitURL)
+ if err != nil {
+ return "", "", errors.Wrapf(err, "unable to 'git clone' to temporary context directory")
+ }
+
+ absContextDir, err = ResolveAndValidateContextPath(absContextDir)
+ if err != nil {
+ return "", "", err
+ }
+ relDockerfile, err := getDockerfileRelPath(absContextDir, dockerfileName)
+ return absContextDir, relDockerfile, err
+}
+
+// GetContextFromURL uses a remote URL as context for a `docker build`. The
+// remote resource is downloaded as either a Dockerfile or a tar archive.
+// Returns the tar archive used for the context and a path of the
+// dockerfile inside the tar.
+func GetContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.ReadCloser, string, error) {
+ response, err := getWithStatusError(remoteURL)
+ if err != nil {
+ return nil, "", errors.Errorf("unable to download remote context %s: %v", remoteURL, err)
+ }
+ progressOutput := streamformatter.NewProgressOutput(out)
+
+ // Pass the response body through a progress reader.
+ progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", fmt.Sprintf("Downloading build context from remote url: %s", remoteURL))
+
+ return GetContextFromReader(ioutils.NewReadCloserWrapper(progReader, func() error { return response.Body.Close() }), dockerfileName)
+}
+
+// getWithStatusError does an http.Get() and returns an error if the
+// status code is 4xx or 5xx.
+func getWithStatusError(url string) (resp *http.Response, err error) {
+ if resp, err = http.Get(url); err != nil {
+ return nil, err
+ }
+ if resp.StatusCode < 400 {
+ return resp, nil
+ }
+ msg := fmt.Sprintf("failed to GET %s with status %s", url, resp.Status)
+ body, err := ioutil.ReadAll(resp.Body)
+ resp.Body.Close()
+ if err != nil {
+ return nil, errors.Wrapf(err, msg+": error reading body")
+ }
+ return nil, errors.Errorf(msg+": %s", bytes.TrimSpace(body))
+}
+
+// GetContextFromLocalDir uses the given local directory as context for a
+// `docker build`. Returns the absolute path to the local context directory,
+// the relative path of the dockerfile in that context directory, and a non-nil
+// error on success.
+func GetContextFromLocalDir(localDir, dockerfileName string) (string, string, error) {
+ localDir, err := ResolveAndValidateContextPath(localDir)
+ if err != nil {
+ return "", "", err
+ }
+
+ // When using a local context directory, and the Dockerfile is specified
+ // with the `-f/--file` option then it is considered relative to the
+ // current directory and not the context directory.
+ if dockerfileName != "" && dockerfileName != "-" {
+ if dockerfileName, err = filepath.Abs(dockerfileName); err != nil {
+ return "", "", errors.Errorf("unable to get absolute path to Dockerfile: %v", err)
+ }
+ }
+
+ relDockerfile, err := getDockerfileRelPath(localDir, dockerfileName)
+ return localDir, relDockerfile, err
+}
+
+// ResolveAndValidateContextPath uses the given context directory for a `docker build`
+// and returns the absolute path to the context directory.
+func ResolveAndValidateContextPath(givenContextDir string) (string, error) {
+ absContextDir, err := filepath.Abs(givenContextDir)
+ if err != nil {
+ return "", errors.Errorf("unable to get absolute context directory of given context directory %q: %v", givenContextDir, err)
+ }
+
+ // The context dir might be a symbolic link, so follow it to the actual
+ // target directory.
+ //
+ // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
+ // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
+ // paths (those starting with \\). This hack means that when using links
+ // on UNC paths, they will not be followed.
+ if !isUNC(absContextDir) {
+ absContextDir, err = filepath.EvalSymlinks(absContextDir)
+ if err != nil {
+ return "", errors.Errorf("unable to evaluate symlinks in context path: %v", err)
+ }
+ }
+
+ stat, err := os.Lstat(absContextDir)
+ if err != nil {
+ return "", errors.Errorf("unable to stat context directory %q: %v", absContextDir, err)
+ }
+
+ if !stat.IsDir() {
+ return "", errors.Errorf("context must be a directory: %s", absContextDir)
+ }
+ return absContextDir, err
+}
+
+// getDockerfileRelPath returns the dockerfile path relative to the context
+// directory
+func getDockerfileRelPath(absContextDir, givenDockerfile string) (string, error) {
+ var err error
+
+ if givenDockerfile == "-" {
+ return givenDockerfile, nil
+ }
+
+ absDockerfile := givenDockerfile
+ if absDockerfile == "" {
+ // No -f/--file was specified so use the default relative to the
+ // context directory.
+ absDockerfile = filepath.Join(absContextDir, DefaultDockerfileName)
+
+ // Just to be nice ;-) look for 'dockerfile' too but only
+ // use it if we found it, otherwise ignore this check
+ if _, err = os.Lstat(absDockerfile); os.IsNotExist(err) {
+ altPath := filepath.Join(absContextDir, strings.ToLower(DefaultDockerfileName))
+ if _, err = os.Lstat(altPath); err == nil {
+ absDockerfile = altPath
+ }
+ }
+ }
+
+ // If not already an absolute path, the Dockerfile path should be joined to
+ // the base directory.
+ if !filepath.IsAbs(absDockerfile) {
+ absDockerfile = filepath.Join(absContextDir, absDockerfile)
+ }
+
+ // Evaluate symlinks in the path to the Dockerfile too.
+ //
+ // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
+ // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
+ // paths (those starting with \\). This hack means that when using links
+ // on UNC paths, they will not be followed.
+ if !isUNC(absDockerfile) {
+ absDockerfile, err = filepath.EvalSymlinks(absDockerfile)
+ if err != nil {
+ return "", errors.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err)
+
+ }
+ }
+
+ if _, err := os.Lstat(absDockerfile); err != nil {
+ if os.IsNotExist(err) {
+ return "", errors.Errorf("Cannot locate Dockerfile: %q", absDockerfile)
+ }
+ return "", errors.Errorf("unable to stat Dockerfile: %v", err)
+ }
+
+ relDockerfile, err := filepath.Rel(absContextDir, absDockerfile)
+ if err != nil {
+ return "", errors.Errorf("unable to get relative Dockerfile path: %v", err)
+ }
+
+ if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
+ return "", errors.Errorf("the Dockerfile (%s) must be within the build context", givenDockerfile)
+ }
+
+ return relDockerfile, nil
+}
+
+// isUNC returns true if the path is UNC (one starting \\). It always returns
+// false on Linux.
+func isUNC(path string) bool {
+ return runtime.GOOS == "windows" && strings.HasPrefix(path, `\\`)
+}
+
+// AddDockerfileToBuildContext from a ReadCloser, returns a new archive and
+// the relative path to the dockerfile in the context.
+func AddDockerfileToBuildContext(dockerfileCtx io.ReadCloser, buildCtx io.ReadCloser) (io.ReadCloser, string, error) {
+ file, err := ioutil.ReadAll(dockerfileCtx)
+ dockerfileCtx.Close()
+ if err != nil {
+ return nil, "", err
+ }
+ now := time.Now()
+ hdrTmpl := &tar.Header{
+ Mode: 0600,
+ Uid: 0,
+ Gid: 0,
+ ModTime: now,
+ Typeflag: tar.TypeReg,
+ AccessTime: now,
+ ChangeTime: now,
+ }
+ randomName := ".dockerfile." + stringid.GenerateRandomID()[:20]
+
+ buildCtx = archive.ReplaceFileTarWrapper(buildCtx, map[string]archive.TarModifierFunc{
+ // Add the dockerfile with a random filename
+ randomName: func(_ string, h *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
+ return hdrTmpl, file, nil
+ },
+ // Update .dockerignore to include the random filename
+ ".dockerignore": func(_ string, h *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
+ if h == nil {
+ h = hdrTmpl
+ }
+
+ b := &bytes.Buffer{}
+ if content != nil {
+ if _, err := b.ReadFrom(content); err != nil {
+ return nil, nil, err
+ }
+ } else {
+ b.WriteString(".dockerignore")
+ }
+ b.WriteString("\n" + randomName + "\n")
+ return h, b.Bytes(), nil
+ },
+ })
+ return buildCtx, randomName, nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/build/context_unix.go b/vendor/github.com/docker/cli/cli/command/image/build/context_unix.go
new file mode 100644
index 0000000..cb2634f
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/build/context_unix.go
@@ -0,0 +1,11 @@
+// +build !windows
+
+package build
+
+import (
+ "path/filepath"
+)
+
+func getContextRoot(srcPath string) (string, error) {
+ return filepath.Join(srcPath, "."), nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/build/context_windows.go b/vendor/github.com/docker/cli/cli/command/image/build/context_windows.go
new file mode 100644
index 0000000..c577cfa
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/build/context_windows.go
@@ -0,0 +1,17 @@
+// +build windows
+
+package build
+
+import (
+ "path/filepath"
+
+ "github.com/docker/docker/pkg/longpath"
+)
+
+func getContextRoot(srcPath string) (string, error) {
+ cr, err := filepath.Abs(srcPath)
+ if err != nil {
+ return "", err
+ }
+ return longpath.AddPrefix(cr), nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/build/dockerignore.go b/vendor/github.com/docker/cli/cli/command/image/build/dockerignore.go
new file mode 100644
index 0000000..497c3f2
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/build/dockerignore.go
@@ -0,0 +1,39 @@
+package build
+
+import (
+ "os"
+ "path/filepath"
+
+ "github.com/docker/docker/builder/dockerignore"
+ "github.com/docker/docker/pkg/fileutils"
+)
+
+// ReadDockerignore reads the .dockerignore file in the context directory and
+// returns the list of paths to exclude
+func ReadDockerignore(contextDir string) ([]string, error) {
+ var excludes []string
+
+ f, err := os.Open(filepath.Join(contextDir, ".dockerignore"))
+ switch {
+ case os.IsNotExist(err):
+ return excludes, nil
+ case err != nil:
+ return nil, err
+ }
+ defer f.Close()
+
+ return dockerignore.ReadAll(f)
+}
+
+// TrimBuildFilesFromExcludes removes the named Dockerfile and .dockerignore from
+// the list of excluded files. The daemon will remove them from the final context
+// but they must be in available in the context when passed to the API.
+func TrimBuildFilesFromExcludes(excludes []string, dockerfile string, dockerfileFromStdin bool) []string {
+ if keep, _ := fileutils.Matches(".dockerignore", excludes); keep {
+ excludes = append(excludes, "!.dockerignore")
+ }
+ if keep, _ := fileutils.Matches(dockerfile, excludes); keep && !dockerfileFromStdin {
+ excludes = append(excludes, "!"+dockerfile)
+ }
+ return excludes
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/cmd.go b/vendor/github.com/docker/cli/cli/command/image/cmd.go
new file mode 100644
index 0000000..0c68af1
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/cmd.go
@@ -0,0 +1,35 @@
+package image
+
+import (
+ "github.com/spf13/cobra"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+)
+
+// NewImageCommand returns a cobra command for `image` subcommands
+// nolint: interfacer
+func NewImageCommand(dockerCli *command.DockerCli) *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "image",
+ Short: "Manage images",
+ Args: cli.NoArgs,
+ RunE: command.ShowHelp(dockerCli.Err()),
+ }
+ cmd.AddCommand(
+ NewBuildCommand(dockerCli),
+ NewHistoryCommand(dockerCli),
+ NewDeltaCommand(dockerCli),
+ NewImportCommand(dockerCli),
+ NewLoadCommand(dockerCli),
+ NewPullCommand(dockerCli),
+ NewPushCommand(dockerCli),
+ NewSaveCommand(dockerCli),
+ NewTagCommand(dockerCli),
+ newListCommand(dockerCli),
+ newRemoveCommand(dockerCli),
+ newInspectCommand(dockerCli),
+ NewPruneCommand(dockerCli),
+ )
+ return cmd
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/delta.go b/vendor/github.com/docker/cli/cli/command/image/delta.go
new file mode 100644
index 0000000..a2e9b1b
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/delta.go
@@ -0,0 +1,44 @@
+package image
+
+import (
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/pkg/jsonmessage"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type deltaOptions struct {
+ src string
+ dest string
+}
+
+// NewDeltaCommand creates a new `docker delta` command
+func NewDeltaCommand(dockerCli command.Cli) *cobra.Command {
+ var options deltaOptions
+
+ cmd := &cobra.Command{
+ Use: "delta [OPTIONS] SRC_IMAGE DEST_IMAGE",
+ Short: "Create a binary delta between SRC_IMAGE and DEST_IMAGE",
+ Args: cli.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ options.src = args[0]
+ options.dest = args[1]
+ return runDelta(dockerCli, options)
+ },
+ }
+
+ return cmd
+}
+
+func runDelta(dockerCli command.Cli, options deltaOptions) error {
+ clnt := dockerCli.Client()
+
+ responseBody, err := clnt.ImageDelta(context.Background(), options.src, options.dest)
+ if err != nil {
+ return err
+ }
+ defer responseBody.Close()
+
+ return jsonmessage.DisplayJSONMessagesToStream(responseBody, dockerCli.Out(), nil)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/history.go b/vendor/github.com/docker/cli/cli/command/image/history.go
new file mode 100644
index 0000000..27782d1
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/history.go
@@ -0,0 +1,64 @@
+package image
+
+import (
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/formatter"
+ "github.com/spf13/cobra"
+)
+
+type historyOptions struct {
+ image string
+
+ human bool
+ quiet bool
+ noTrunc bool
+ format string
+}
+
+// NewHistoryCommand creates a new `docker history` command
+func NewHistoryCommand(dockerCli command.Cli) *cobra.Command {
+ var opts historyOptions
+
+ cmd := &cobra.Command{
+ Use: "history [OPTIONS] IMAGE",
+ Short: "Show the history of an image",
+ Args: cli.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.image = args[0]
+ return runHistory(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.BoolVarP(&opts.human, "human", "H", true, "Print sizes and dates in human readable format")
+ flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only show numeric IDs")
+ flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Don't truncate output")
+ flags.StringVar(&opts.format, "format", "", "Pretty-print images using a Go template")
+
+ return cmd
+}
+
+func runHistory(dockerCli command.Cli, opts historyOptions) error {
+ ctx := context.Background()
+
+ history, err := dockerCli.Client().ImageHistory(ctx, opts.image)
+ if err != nil {
+ return err
+ }
+
+ format := opts.format
+ if len(format) == 0 {
+ format = formatter.TableFormatKey
+ }
+
+ historyCtx := formatter.Context{
+ Output: dockerCli.Out(),
+ Format: formatter.NewHistoryFormat(format, opts.quiet, opts.human),
+ Trunc: !opts.noTrunc,
+ }
+ return formatter.HistoryWrite(historyCtx, opts.human, history)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/import.go b/vendor/github.com/docker/cli/cli/command/image/import.go
new file mode 100644
index 0000000..1f7189a
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/import.go
@@ -0,0 +1,87 @@
+package image
+
+import (
+ "io"
+ "os"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ dockeropts "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/jsonmessage"
+ "github.com/docker/docker/pkg/urlutil"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type importOptions struct {
+ source string
+ reference string
+ changes dockeropts.ListOpts
+ message string
+}
+
+// NewImportCommand creates a new `docker import` command
+func NewImportCommand(dockerCli command.Cli) *cobra.Command {
+ var options importOptions
+
+ cmd := &cobra.Command{
+ Use: "import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]",
+ Short: "Import the contents from a tarball to create a filesystem image",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ options.source = args[0]
+ if len(args) > 1 {
+ options.reference = args[1]
+ }
+ return runImport(dockerCli, options)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ options.changes = dockeropts.NewListOpts(nil)
+ flags.VarP(&options.changes, "change", "c", "Apply Dockerfile instruction to the created image")
+ flags.StringVarP(&options.message, "message", "m", "", "Set commit message for imported image")
+
+ return cmd
+}
+
+func runImport(dockerCli command.Cli, options importOptions) error {
+ var (
+ in io.Reader
+ srcName = options.source
+ )
+
+ if options.source == "-" {
+ in = dockerCli.In()
+ } else if !urlutil.IsURL(options.source) {
+ srcName = "-"
+ file, err := os.Open(options.source)
+ if err != nil {
+ return err
+ }
+ defer file.Close()
+ in = file
+ }
+
+ source := types.ImageImportSource{
+ Source: in,
+ SourceName: srcName,
+ }
+
+ importOptions := types.ImageImportOptions{
+ Message: options.message,
+ Changes: options.changes.GetAll(),
+ }
+
+ clnt := dockerCli.Client()
+
+ responseBody, err := clnt.ImageImport(context.Background(), source, options.reference, importOptions)
+ if err != nil {
+ return err
+ }
+ defer responseBody.Close()
+
+ return jsonmessage.DisplayJSONMessagesToStream(responseBody, dockerCli.Out(), nil)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/inspect.go b/vendor/github.com/docker/cli/cli/command/image/inspect.go
new file mode 100644
index 0000000..a510e30
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/inspect.go
@@ -0,0 +1,44 @@
+package image
+
+import (
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/inspect"
+ "github.com/spf13/cobra"
+)
+
+type inspectOptions struct {
+ format string
+ refs []string
+}
+
+// newInspectCommand creates a new cobra.Command for `docker image inspect`
+func newInspectCommand(dockerCli command.Cli) *cobra.Command {
+ var opts inspectOptions
+
+ cmd := &cobra.Command{
+ Use: "inspect [OPTIONS] IMAGE [IMAGE...]",
+ Short: "Display detailed information on one or more images",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.refs = args
+ return runInspect(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
+ return cmd
+}
+
+func runInspect(dockerCli command.Cli, opts inspectOptions) error {
+ client := dockerCli.Client()
+ ctx := context.Background()
+
+ getRefFunc := func(ref string) (interface{}, []byte, error) {
+ return client.ImageInspectWithRaw(ctx, ref)
+ }
+ return inspect.Inspect(dockerCli.Out(), opts.refs, opts.format, getRefFunc)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/list.go b/vendor/github.com/docker/cli/cli/command/image/list.go
new file mode 100644
index 0000000..6dada82
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/list.go
@@ -0,0 +1,95 @@
+package image
+
+import (
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/formatter"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type imagesOptions struct {
+ matchName string
+
+ quiet bool
+ all bool
+ noTrunc bool
+ showDigests bool
+ format string
+ filter opts.FilterOpt
+}
+
+// NewImagesCommand creates a new `docker images` command
+func NewImagesCommand(dockerCli command.Cli) *cobra.Command {
+ options := imagesOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "images [OPTIONS] [REPOSITORY[:TAG]]",
+ Short: "List images",
+ Args: cli.RequiresMaxArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if len(args) > 0 {
+ options.matchName = args[0]
+ }
+ return runImages(dockerCli, options)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only show numeric IDs")
+ flags.BoolVarP(&options.all, "all", "a", false, "Show all images (default hides intermediate images)")
+ flags.BoolVar(&options.noTrunc, "no-trunc", false, "Don't truncate output")
+ flags.BoolVar(&options.showDigests, "digests", false, "Show digests")
+ flags.StringVar(&options.format, "format", "", "Pretty-print images using a Go template")
+ flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided")
+
+ return cmd
+}
+
+func newListCommand(dockerCli command.Cli) *cobra.Command {
+ cmd := *NewImagesCommand(dockerCli)
+ cmd.Aliases = []string{"images", "list"}
+ cmd.Use = "ls [OPTIONS] [REPOSITORY[:TAG]]"
+ return &cmd
+}
+
+func runImages(dockerCli command.Cli, options imagesOptions) error {
+ ctx := context.Background()
+
+ filters := options.filter.Value()
+ if options.matchName != "" {
+ filters.Add("reference", options.matchName)
+ }
+
+ listOptions := types.ImageListOptions{
+ All: options.all,
+ Filters: filters,
+ }
+
+ images, err := dockerCli.Client().ImageList(ctx, listOptions)
+ if err != nil {
+ return err
+ }
+
+ format := options.format
+ if len(format) == 0 {
+ if len(dockerCli.ConfigFile().ImagesFormat) > 0 && !options.quiet {
+ format = dockerCli.ConfigFile().ImagesFormat
+ } else {
+ format = formatter.TableFormatKey
+ }
+ }
+
+ imageCtx := formatter.ImageContext{
+ Context: formatter.Context{
+ Output: dockerCli.Out(),
+ Format: formatter.NewImageFormat(format, options.quiet, options.showDigests),
+ Trunc: !options.noTrunc,
+ },
+ Digest: options.showDigests,
+ }
+ return formatter.ImageWrite(imageCtx, images)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/load.go b/vendor/github.com/docker/cli/cli/command/image/load.go
new file mode 100644
index 0000000..6708599
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/load.go
@@ -0,0 +1,77 @@
+package image
+
+import (
+ "io"
+
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/pkg/jsonmessage"
+ "github.com/docker/docker/pkg/system"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+)
+
+type loadOptions struct {
+ input string
+ quiet bool
+}
+
+// NewLoadCommand creates a new `docker load` command
+func NewLoadCommand(dockerCli command.Cli) *cobra.Command {
+ var opts loadOptions
+
+ cmd := &cobra.Command{
+ Use: "load [OPTIONS]",
+ Short: "Load an image from a tar archive or STDIN",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runLoad(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.StringVarP(&opts.input, "input", "i", "", "Read from tar archive file, instead of STDIN")
+ flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Suppress the load output")
+
+ return cmd
+}
+
+func runLoad(dockerCli command.Cli, opts loadOptions) error {
+
+ var input io.Reader = dockerCli.In()
+ if opts.input != "" {
+ // We use system.OpenSequential to use sequential file access on Windows, avoiding
+ // depleting the standby list un-necessarily. On Linux, this equates to a regular os.Open.
+ file, err := system.OpenSequential(opts.input)
+ if err != nil {
+ return err
+ }
+ defer file.Close()
+ input = file
+ }
+
+ // To avoid getting stuck, verify that a tar file is given either in
+ // the input flag or through stdin and if not display an error message and exit.
+ if opts.input == "" && dockerCli.In().IsTerminal() {
+ return errors.Errorf("requested load from stdin, but stdin is empty")
+ }
+
+ if !dockerCli.Out().IsTerminal() {
+ opts.quiet = true
+ }
+ response, err := dockerCli.Client().ImageLoad(context.Background(), input, opts.quiet)
+ if err != nil {
+ return err
+ }
+ defer response.Body.Close()
+
+ if response.Body != nil && response.JSON {
+ return jsonmessage.DisplayJSONMessagesToStream(response.Body, dockerCli.Out(), nil)
+ }
+
+ _, err = io.Copy(dockerCli.Out(), response.Body)
+ return err
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/prune.go b/vendor/github.com/docker/cli/cli/command/image/prune.go
new file mode 100644
index 0000000..8e521b6
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/prune.go
@@ -0,0 +1,95 @@
+package image
+
+import (
+ "fmt"
+
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ units "github.com/docker/go-units"
+ "github.com/spf13/cobra"
+)
+
+type pruneOptions struct {
+ force bool
+ all bool
+ filter opts.FilterOpt
+}
+
+// NewPruneCommand returns a new cobra prune command for images
+func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
+ options := pruneOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "prune [OPTIONS]",
+ Short: "Remove unused images",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ spaceReclaimed, output, err := runPrune(dockerCli, options)
+ if err != nil {
+ return err
+ }
+ if output != "" {
+ fmt.Fprintln(dockerCli.Out(), output)
+ }
+ fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
+ return nil
+ },
+ Tags: map[string]string{"version": "1.25"},
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&options.force, "force", "f", false, "Do not prompt for confirmation")
+ flags.BoolVarP(&options.all, "all", "a", false, "Remove all unused images, not just dangling ones")
+ flags.Var(&options.filter, "filter", "Provide filter values (e.g. 'until=<timestamp>')")
+
+ return cmd
+}
+
+const (
+ allImageWarning = `WARNING! This will remove all images without at least one container associated to them.
+Are you sure you want to continue?`
+ danglingWarning = `WARNING! This will remove all dangling images.
+Are you sure you want to continue?`
+)
+
+func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) {
+ pruneFilters := options.filter.Value()
+ pruneFilters.Add("dangling", fmt.Sprintf("%v", !options.all))
+ pruneFilters = command.PruneFilters(dockerCli, pruneFilters)
+
+ warning := danglingWarning
+ if options.all {
+ warning = allImageWarning
+ }
+ if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
+ return
+ }
+
+ report, err := dockerCli.Client().ImagesPrune(context.Background(), pruneFilters)
+ if err != nil {
+ return
+ }
+
+ if len(report.ImagesDeleted) > 0 {
+ output = "Deleted Images:\n"
+ for _, st := range report.ImagesDeleted {
+ if st.Untagged != "" {
+ output += fmt.Sprintln("untagged:", st.Untagged)
+ } else {
+ output += fmt.Sprintln("deleted:", st.Deleted)
+ }
+ }
+ spaceReclaimed = report.SpaceReclaimed
+ }
+
+ return
+}
+
+// RunPrune calls the Image Prune API
+// This returns the amount of space reclaimed and a detailed output string
+func RunPrune(dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) {
+ return runPrune(dockerCli, pruneOptions{force: true, all: all, filter: filter})
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/pull.go b/vendor/github.com/docker/cli/cli/command/image/pull.go
new file mode 100644
index 0000000..e60e5a4
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/pull.go
@@ -0,0 +1,85 @@
+package image
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/registry"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type pullOptions struct {
+ remote string
+ all bool
+}
+
+// NewPullCommand creates a new `docker pull` command
+func NewPullCommand(dockerCli command.Cli) *cobra.Command {
+ var opts pullOptions
+
+ cmd := &cobra.Command{
+ Use: "pull [OPTIONS] NAME[:TAG|@DIGEST]",
+ Short: "Pull an image or a repository from a registry",
+ Args: cli.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.remote = args[0]
+ return runPull(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.BoolVarP(&opts.all, "all-tags", "a", false, "Download all tagged images in the repository")
+ command.AddTrustVerificationFlags(flags)
+
+ return cmd
+}
+
+func runPull(dockerCli command.Cli, opts pullOptions) error {
+ distributionRef, err := reference.ParseNormalizedNamed(opts.remote)
+ if err != nil {
+ return err
+ }
+ if opts.all && !reference.IsNameOnly(distributionRef) {
+ return errors.New("tag can't be used with --all-tags/-a")
+ }
+
+ if !opts.all && reference.IsNameOnly(distributionRef) {
+ distributionRef = reference.TagNameOnly(distributionRef)
+ if tagged, ok := distributionRef.(reference.Tagged); ok {
+ fmt.Fprintf(dockerCli.Out(), "Using default tag: %s\n", tagged.Tag())
+ }
+ }
+
+ // Resolve the Repository name from fqn to RepositoryInfo
+ repoInfo, err := registry.ParseRepositoryInfo(distributionRef)
+ if err != nil {
+ return err
+ }
+
+ ctx := context.Background()
+
+ authConfig := command.ResolveAuthConfig(ctx, dockerCli, repoInfo.Index)
+ requestPrivilege := command.RegistryAuthenticationPrivilegedFunc(dockerCli, repoInfo.Index, "pull")
+
+ // Check if reference has a digest
+ _, isCanonical := distributionRef.(reference.Canonical)
+ if command.IsTrusted() && !isCanonical {
+ err = trustedPull(ctx, dockerCli, repoInfo, distributionRef, authConfig, requestPrivilege)
+ } else {
+ err = imagePullPrivileged(ctx, dockerCli, authConfig, reference.FamiliarString(distributionRef), requestPrivilege, opts.all)
+ }
+ if err != nil {
+ if strings.Contains(err.Error(), "when fetching 'plugin'") {
+ return errors.New(err.Error() + " - Use `docker plugin install`")
+ }
+ return err
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/push.go b/vendor/github.com/docker/cli/cli/command/image/push.go
new file mode 100644
index 0000000..cc95897
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/push.go
@@ -0,0 +1,61 @@
+package image
+
+import (
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/pkg/jsonmessage"
+ "github.com/docker/docker/registry"
+ "github.com/spf13/cobra"
+)
+
+// NewPushCommand creates a new `docker push` command
+func NewPushCommand(dockerCli command.Cli) *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "push [OPTIONS] NAME[:TAG]",
+ Short: "Push an image or a repository to a registry",
+ Args: cli.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runPush(dockerCli, args[0])
+ },
+ }
+
+ flags := cmd.Flags()
+
+ command.AddTrustSigningFlags(flags)
+
+ return cmd
+}
+
+func runPush(dockerCli command.Cli, remote string) error {
+ ref, err := reference.ParseNormalizedNamed(remote)
+ if err != nil {
+ return err
+ }
+
+ // Resolve the Repository name from fqn to RepositoryInfo
+ repoInfo, err := registry.ParseRepositoryInfo(ref)
+ if err != nil {
+ return err
+ }
+
+ ctx := context.Background()
+
+ // Resolve the Auth config relevant for this server
+ authConfig := command.ResolveAuthConfig(ctx, dockerCli, repoInfo.Index)
+ requestPrivilege := command.RegistryAuthenticationPrivilegedFunc(dockerCli, repoInfo.Index, "push")
+
+ if command.IsTrusted() {
+ return trustedPush(ctx, dockerCli, repoInfo, ref, authConfig, requestPrivilege)
+ }
+
+ responseBody, err := imagePushPrivileged(ctx, dockerCli, authConfig, ref, requestPrivilege)
+ if err != nil {
+ return err
+ }
+
+ defer responseBody.Close()
+ return jsonmessage.DisplayJSONMessagesToStream(responseBody, dockerCli.Out(), nil)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/remove.go b/vendor/github.com/docker/cli/cli/command/image/remove.go
new file mode 100644
index 0000000..894d305
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/remove.go
@@ -0,0 +1,82 @@
+package image
+
+import (
+ "fmt"
+ "strings"
+
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+)
+
+type removeOptions struct {
+ force bool
+ noPrune bool
+}
+
+// NewRemoveCommand creates a new `docker remove` command
+func NewRemoveCommand(dockerCli command.Cli) *cobra.Command {
+ var opts removeOptions
+
+ cmd := &cobra.Command{
+ Use: "rmi [OPTIONS] IMAGE [IMAGE...]",
+ Short: "Remove one or more images",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runRemove(dockerCli, opts, args)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.BoolVarP(&opts.force, "force", "f", false, "Force removal of the image")
+ flags.BoolVar(&opts.noPrune, "no-prune", false, "Do not delete untagged parents")
+
+ return cmd
+}
+
+func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
+ cmd := *NewRemoveCommand(dockerCli)
+ cmd.Aliases = []string{"rmi", "remove"}
+ cmd.Use = "rm [OPTIONS] IMAGE [IMAGE...]"
+ return &cmd
+}
+
+func runRemove(dockerCli command.Cli, opts removeOptions, images []string) error {
+ client := dockerCli.Client()
+ ctx := context.Background()
+
+ options := types.ImageRemoveOptions{
+ Force: opts.force,
+ PruneChildren: !opts.noPrune,
+ }
+
+ var errs []string
+ for _, img := range images {
+ dels, err := client.ImageRemove(ctx, img, options)
+ if err != nil {
+ errs = append(errs, err.Error())
+ } else {
+ for _, del := range dels {
+ if del.Deleted != "" {
+ fmt.Fprintf(dockerCli.Out(), "Deleted: %s\n", del.Deleted)
+ } else {
+ fmt.Fprintf(dockerCli.Out(), "Untagged: %s\n", del.Untagged)
+ }
+ }
+ }
+ }
+
+ if len(errs) > 0 {
+ msg := strings.Join(errs, "\n")
+ if !opts.force {
+ return errors.New(msg)
+ }
+ fmt.Fprintf(dockerCli.Err(), msg)
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/save.go b/vendor/github.com/docker/cli/cli/command/image/save.go
new file mode 100644
index 0000000..ba666d2
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/save.go
@@ -0,0 +1,56 @@
+package image
+
+import (
+ "io"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type saveOptions struct {
+ images []string
+ output string
+}
+
+// NewSaveCommand creates a new `docker save` command
+func NewSaveCommand(dockerCli command.Cli) *cobra.Command {
+ var opts saveOptions
+
+ cmd := &cobra.Command{
+ Use: "save [OPTIONS] IMAGE [IMAGE...]",
+ Short: "Save one or more images to a tar archive (streamed to STDOUT by default)",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.images = args
+ return runSave(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT")
+
+ return cmd
+}
+
+func runSave(dockerCli command.Cli, opts saveOptions) error {
+ if opts.output == "" && dockerCli.Out().IsTerminal() {
+ return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect")
+ }
+
+ responseBody, err := dockerCli.Client().ImageSave(context.Background(), opts.images)
+ if err != nil {
+ return err
+ }
+ defer responseBody.Close()
+
+ if opts.output == "" {
+ _, err := io.Copy(dockerCli.Out(), responseBody)
+ return err
+ }
+
+ return command.CopyToFile(opts.output, responseBody)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/tag.go b/vendor/github.com/docker/cli/cli/command/image/tag.go
new file mode 100644
index 0000000..2a50c12
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/tag.go
@@ -0,0 +1,41 @@
+package image
+
+import (
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/spf13/cobra"
+)
+
+type tagOptions struct {
+ image string
+ name string
+}
+
+// NewTagCommand creates a new `docker tag` command
+func NewTagCommand(dockerCli command.Cli) *cobra.Command {
+ var opts tagOptions
+
+ cmd := &cobra.Command{
+ Use: "tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]",
+ Short: "Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE",
+ Args: cli.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.image = args[0]
+ opts.name = args[1]
+ return runTag(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.SetInterspersed(false)
+
+ return cmd
+}
+
+func runTag(dockerCli command.Cli, opts tagOptions) error {
+ ctx := context.Background()
+
+ return dockerCli.Client().ImageTag(ctx, opts.image, opts.name)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/image/trust.go b/vendor/github.com/docker/cli/cli/command/image/trust.go
new file mode 100644
index 0000000..dd0d12c
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/image/trust.go
@@ -0,0 +1,384 @@
+package image
+
+import (
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "path"
+ "sort"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/trust"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/jsonmessage"
+ "github.com/docker/docker/registry"
+ "github.com/docker/notary/client"
+ "github.com/docker/notary/tuf/data"
+ "github.com/opencontainers/go-digest"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+type target struct {
+ name string
+ digest digest.Digest
+ size int64
+}
+
+// trustedPush handles content trust pushing of an image
+func trustedPush(ctx context.Context, cli command.Cli, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, requestPrivilege types.RequestPrivilegeFunc) error {
+ responseBody, err := imagePushPrivileged(ctx, cli, authConfig, ref, requestPrivilege)
+ if err != nil {
+ return err
+ }
+
+ defer responseBody.Close()
+
+ return PushTrustedReference(cli, repoInfo, ref, authConfig, responseBody)
+}
+
+// PushTrustedReference pushes a canonical reference to the trust server.
+// nolint: gocyclo
+func PushTrustedReference(streams command.Streams, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, in io.Reader) error {
+ // If it is a trusted push we would like to find the target entry which match the
+ // tag provided in the function and then do an AddTarget later.
+ target := &client.Target{}
+ // Count the times of calling for handleTarget,
+ // if it is called more that once, that should be considered an error in a trusted push.
+ cnt := 0
+ handleTarget := func(aux *json.RawMessage) {
+ cnt++
+ if cnt > 1 {
+ // handleTarget should only be called one. This will be treated as an error.
+ return
+ }
+
+ var pushResult types.PushResult
+ err := json.Unmarshal(*aux, &pushResult)
+ if err == nil && pushResult.Tag != "" {
+ if dgst, err := digest.Parse(pushResult.Digest); err == nil {
+ h, err := hex.DecodeString(dgst.Hex())
+ if err != nil {
+ target = nil
+ return
+ }
+ target.Name = pushResult.Tag
+ target.Hashes = data.Hashes{string(dgst.Algorithm()): h}
+ target.Length = int64(pushResult.Size)
+ }
+ }
+ }
+
+ var tag string
+ switch x := ref.(type) {
+ case reference.Canonical:
+ return errors.New("cannot push a digest reference")
+ case reference.NamedTagged:
+ tag = x.Tag()
+ default:
+ // We want trust signatures to always take an explicit tag,
+ // otherwise it will act as an untrusted push.
+ if err := jsonmessage.DisplayJSONMessagesToStream(in, streams.Out(), nil); err != nil {
+ return err
+ }
+ fmt.Fprintln(streams.Out(), "No tag specified, skipping trust metadata push")
+ return nil
+ }
+
+ if err := jsonmessage.DisplayJSONMessagesToStream(in, streams.Out(), handleTarget); err != nil {
+ return err
+ }
+
+ if cnt > 1 {
+ return errors.Errorf("internal error: only one call to handleTarget expected")
+ }
+
+ if target == nil {
+ fmt.Fprintln(streams.Out(), "No targets found, please provide a specific tag in order to sign it")
+ return nil
+ }
+
+ fmt.Fprintln(streams.Out(), "Signing and pushing trust metadata")
+
+ repo, err := trust.GetNotaryRepository(streams, repoInfo, authConfig, "push", "pull")
+ if err != nil {
+ fmt.Fprintf(streams.Out(), "Error establishing connection to notary repository: %s\n", err)
+ return err
+ }
+
+ // get the latest repository metadata so we can figure out which roles to sign
+ err = repo.Update(false)
+
+ switch err.(type) {
+ case client.ErrRepoNotInitialized, client.ErrRepositoryNotExist:
+ keys := repo.CryptoService.ListKeys(data.CanonicalRootRole)
+ var rootKeyID string
+ // always select the first root key
+ if len(keys) > 0 {
+ sort.Strings(keys)
+ rootKeyID = keys[0]
+ } else {
+ rootPublicKey, err := repo.CryptoService.Create(data.CanonicalRootRole, "", data.ECDSAKey)
+ if err != nil {
+ return err
+ }
+ rootKeyID = rootPublicKey.ID()
+ }
+
+ // Initialize the notary repository with a remotely managed snapshot key
+ if err := repo.Initialize([]string{rootKeyID}, data.CanonicalSnapshotRole); err != nil {
+ return trust.NotaryError(repoInfo.Name.Name(), err)
+ }
+ fmt.Fprintf(streams.Out(), "Finished initializing %q\n", repoInfo.Name.Name())
+ err = repo.AddTarget(target, data.CanonicalTargetsRole)
+ case nil:
+ // already initialized and we have successfully downloaded the latest metadata
+ err = addTargetToAllSignableRoles(repo, target)
+ default:
+ return trust.NotaryError(repoInfo.Name.Name(), err)
+ }
+
+ if err == nil {
+ err = repo.Publish()
+ }
+
+ if err != nil {
+ fmt.Fprintf(streams.Out(), "Failed to sign %q:%s - %s\n", repoInfo.Name.Name(), tag, err.Error())
+ return trust.NotaryError(repoInfo.Name.Name(), err)
+ }
+
+ fmt.Fprintf(streams.Out(), "Successfully signed %q:%s\n", repoInfo.Name.Name(), tag)
+ return nil
+}
+
+// Attempt to add the image target to all the top level delegation roles we can
+// (based on whether we have the signing key and whether the role's path allows
+// us to).
+// If there are no delegation roles, we add to the targets role.
+func addTargetToAllSignableRoles(repo *client.NotaryRepository, target *client.Target) error {
+ var signableRoles []string
+
+ // translate the full key names, which includes the GUN, into just the key IDs
+ allCanonicalKeyIDs := make(map[string]struct{})
+ for fullKeyID := range repo.CryptoService.ListAllKeys() {
+ allCanonicalKeyIDs[path.Base(fullKeyID)] = struct{}{}
+ }
+
+ allDelegationRoles, err := repo.GetDelegationRoles()
+ if err != nil {
+ return err
+ }
+
+ // if there are no delegation roles, then just try to sign it into the targets role
+ if len(allDelegationRoles) == 0 {
+ return repo.AddTarget(target, data.CanonicalTargetsRole)
+ }
+
+ // there are delegation roles, find every delegation role we have a key for, and
+ // attempt to sign into into all those roles.
+ for _, delegationRole := range allDelegationRoles {
+ // We do not support signing any delegation role that isn't a direct child of the targets role.
+ // Also don't bother checking the keys if we can't add the target
+ // to this role due to path restrictions
+ if path.Dir(delegationRole.Name) != data.CanonicalTargetsRole || !delegationRole.CheckPaths(target.Name) {
+ continue
+ }
+
+ for _, canonicalKeyID := range delegationRole.KeyIDs {
+ if _, ok := allCanonicalKeyIDs[canonicalKeyID]; ok {
+ signableRoles = append(signableRoles, delegationRole.Name)
+ break
+ }
+ }
+ }
+
+ if len(signableRoles) == 0 {
+ return errors.Errorf("no valid signing keys for delegation roles")
+ }
+
+ return repo.AddTarget(target, signableRoles...)
+}
+
+// imagePushPrivileged push the image
+func imagePushPrivileged(ctx context.Context, cli command.Cli, authConfig types.AuthConfig, ref reference.Reference, requestPrivilege types.RequestPrivilegeFunc) (io.ReadCloser, error) {
+ encodedAuth, err := command.EncodeAuthToBase64(authConfig)
+ if err != nil {
+ return nil, err
+ }
+ options := types.ImagePushOptions{
+ RegistryAuth: encodedAuth,
+ PrivilegeFunc: requestPrivilege,
+ }
+
+ return cli.Client().ImagePush(ctx, reference.FamiliarString(ref), options)
+}
+
+// trustedPull handles content trust pulling of an image
+func trustedPull(ctx context.Context, cli command.Cli, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, requestPrivilege types.RequestPrivilegeFunc) error {
+ var refs []target
+
+ notaryRepo, err := trust.GetNotaryRepository(cli, repoInfo, authConfig, "pull")
+ if err != nil {
+ fmt.Fprintf(cli.Out(), "Error establishing connection to trust repository: %s\n", err)
+ return err
+ }
+
+ if tagged, isTagged := ref.(reference.NamedTagged); !isTagged {
+ // List all targets
+ targets, err := notaryRepo.ListTargets(trust.ReleasesRole, data.CanonicalTargetsRole)
+ if err != nil {
+ return trust.NotaryError(ref.Name(), err)
+ }
+ for _, tgt := range targets {
+ t, err := convertTarget(tgt.Target)
+ if err != nil {
+ fmt.Fprintf(cli.Out(), "Skipping target for %q\n", reference.FamiliarName(ref))
+ continue
+ }
+ // Only list tags in the top level targets role or the releases delegation role - ignore
+ // all other delegation roles
+ if tgt.Role != trust.ReleasesRole && tgt.Role != data.CanonicalTargetsRole {
+ continue
+ }
+ refs = append(refs, t)
+ }
+ if len(refs) == 0 {
+ return trust.NotaryError(ref.Name(), errors.Errorf("No trusted tags for %s", ref.Name()))
+ }
+ } else {
+ t, err := notaryRepo.GetTargetByName(tagged.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole)
+ if err != nil {
+ return trust.NotaryError(ref.Name(), err)
+ }
+ // Only get the tag if it's in the top level targets role or the releases delegation role
+ // ignore it if it's in any other delegation roles
+ if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
+ return trust.NotaryError(ref.Name(), errors.Errorf("No trust data for %s", tagged.Tag()))
+ }
+
+ logrus.Debugf("retrieving target for %s role\n", t.Role)
+ r, err := convertTarget(t.Target)
+ if err != nil {
+ return err
+
+ }
+ refs = append(refs, r)
+ }
+
+ for i, r := range refs {
+ displayTag := r.name
+ if displayTag != "" {
+ displayTag = ":" + displayTag
+ }
+ fmt.Fprintf(cli.Out(), "Pull (%d of %d): %s%s@%s\n", i+1, len(refs), reference.FamiliarName(ref), displayTag, r.digest)
+
+ trustedRef, err := reference.WithDigest(reference.TrimNamed(ref), r.digest)
+ if err != nil {
+ return err
+ }
+ if err := imagePullPrivileged(ctx, cli, authConfig, reference.FamiliarString(trustedRef), requestPrivilege, false); err != nil {
+ return err
+ }
+
+ tagged, err := reference.WithTag(reference.TrimNamed(ref), r.name)
+ if err != nil {
+ return err
+ }
+
+ if err := TagTrusted(ctx, cli, trustedRef, tagged); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// imagePullPrivileged pulls the image and displays it to the output
+func imagePullPrivileged(ctx context.Context, cli command.Cli, authConfig types.AuthConfig, ref string, requestPrivilege types.RequestPrivilegeFunc, all bool) error {
+
+ encodedAuth, err := command.EncodeAuthToBase64(authConfig)
+ if err != nil {
+ return err
+ }
+ options := types.ImagePullOptions{
+ RegistryAuth: encodedAuth,
+ PrivilegeFunc: requestPrivilege,
+ All: all,
+ }
+
+ responseBody, err := cli.Client().ImagePull(ctx, ref, options)
+ if err != nil {
+ return err
+ }
+ defer responseBody.Close()
+
+ return jsonmessage.DisplayJSONMessagesToStream(responseBody, cli.Out(), nil)
+}
+
+// TrustedReference returns the canonical trusted reference for an image reference
+func TrustedReference(ctx context.Context, cli command.Cli, ref reference.NamedTagged, rs registry.Service) (reference.Canonical, error) {
+ var (
+ repoInfo *registry.RepositoryInfo
+ err error
+ )
+ if rs != nil {
+ repoInfo, err = rs.ResolveRepository(ref)
+ } else {
+ repoInfo, err = registry.ParseRepositoryInfo(ref)
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ // Resolve the Auth config relevant for this server
+ authConfig := command.ResolveAuthConfig(ctx, cli, repoInfo.Index)
+
+ notaryRepo, err := trust.GetNotaryRepository(cli, repoInfo, authConfig, "pull")
+ if err != nil {
+ fmt.Fprintf(cli.Out(), "Error establishing connection to trust repository: %s\n", err)
+ return nil, err
+ }
+
+ t, err := notaryRepo.GetTargetByName(ref.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole)
+ if err != nil {
+ return nil, trust.NotaryError(repoInfo.Name.Name(), err)
+ }
+ // Only list tags in the top level targets role or the releases delegation role - ignore
+ // all other delegation roles
+ if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
+ return nil, trust.NotaryError(repoInfo.Name.Name(), errors.Errorf("No trust data for %s", ref.Tag()))
+ }
+ r, err := convertTarget(t.Target)
+ if err != nil {
+ return nil, err
+
+ }
+
+ return reference.WithDigest(reference.TrimNamed(ref), r.digest)
+}
+
+func convertTarget(t client.Target) (target, error) {
+ h, ok := t.Hashes["sha256"]
+ if !ok {
+ return target{}, errors.New("no valid hash, expecting sha256")
+ }
+ return target{
+ name: t.Name,
+ digest: digest.NewDigestFromHex("sha256", hex.EncodeToString(h)),
+ size: t.Length,
+ }, nil
+}
+
+// TagTrusted tags a trusted ref
+// nolint: interfacer
+func TagTrusted(ctx context.Context, cli command.Cli, trustedRef reference.Canonical, ref reference.NamedTagged) error {
+ // Use familiar references when interacting with client and output
+ familiarRef := reference.FamiliarString(ref)
+ trustedFamiliarRef := reference.FamiliarString(trustedRef)
+
+ fmt.Fprintf(cli.Out(), "Tagging %s as %s\n", trustedFamiliarRef, familiarRef)
+
+ return cli.Client().ImageTag(ctx, trustedFamiliarRef, familiarRef)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/in.go b/vendor/github.com/docker/cli/cli/command/in.go
new file mode 100644
index 0000000..54855c6
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/in.go
@@ -0,0 +1,56 @@
+package command
+
+import (
+ "errors"
+ "io"
+ "os"
+ "runtime"
+
+ "github.com/docker/docker/pkg/term"
+)
+
+// InStream is an input stream used by the DockerCli to read user input
+type InStream struct {
+ CommonStream
+ in io.ReadCloser
+}
+
+func (i *InStream) Read(p []byte) (int, error) {
+ return i.in.Read(p)
+}
+
+// Close implements the Closer interface
+func (i *InStream) Close() error {
+ return i.in.Close()
+}
+
+// SetRawTerminal sets raw mode on the input terminal
+func (i *InStream) SetRawTerminal() (err error) {
+ if os.Getenv("NORAW") != "" || !i.CommonStream.isTerminal {
+ return nil
+ }
+ i.CommonStream.state, err = term.SetRawTerminal(i.CommonStream.fd)
+ return err
+}
+
+// CheckTty checks if we are trying to attach to a container tty
+// from a non-tty client input stream, and if so, returns an error.
+func (i *InStream) CheckTty(attachStdin, ttyMode bool) error {
+ // In order to attach to a container tty, input stream for the client must
+ // be a tty itself: redirecting or piping the client standard input is
+ // incompatible with `docker run -t`, `docker exec -t` or `docker attach`.
+ if ttyMode && attachStdin && !i.isTerminal {
+ eText := "the input device is not a TTY"
+ if runtime.GOOS == "windows" {
+ return errors.New(eText + ". If you are using mintty, try prefixing the command with 'winpty'")
+ }
+ return errors.New(eText)
+ }
+ return nil
+}
+
+// NewInStream returns a new InStream object from a ReadCloser
+func NewInStream(in io.ReadCloser) *InStream {
+ fd, isTerminal := term.GetFdInfo(in)
+ return &InStream{CommonStream: CommonStream{fd: fd, isTerminal: isTerminal}, in: in}
+}
diff --git a/vendor/github.com/docker/cli/cli/command/inspect/inspector.go b/vendor/github.com/docker/cli/cli/command/inspect/inspector.go
new file mode 100644
index 0000000..054381f
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/inspect/inspector.go
@@ -0,0 +1,199 @@
+package inspect
+
+import (
+ "bytes"
+ "encoding/json"
+ "io"
+ "strings"
+ "text/template"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli"
+ "github.com/docker/docker/pkg/templates"
+ "github.com/pkg/errors"
+)
+
+// Inspector defines an interface to implement to process elements
+type Inspector interface {
+ Inspect(typedElement interface{}, rawElement []byte) error
+ Flush() error
+}
+
+// TemplateInspector uses a text template to inspect elements.
+type TemplateInspector struct {
+ outputStream io.Writer
+ buffer *bytes.Buffer
+ tmpl *template.Template
+}
+
+// NewTemplateInspector creates a new inspector with a template.
+func NewTemplateInspector(outputStream io.Writer, tmpl *template.Template) Inspector {
+ return &TemplateInspector{
+ outputStream: outputStream,
+ buffer: new(bytes.Buffer),
+ tmpl: tmpl,
+ }
+}
+
+// NewTemplateInspectorFromString creates a new TemplateInspector from a string
+// which is compiled into a template.
+func NewTemplateInspectorFromString(out io.Writer, tmplStr string) (Inspector, error) {
+ if tmplStr == "" {
+ return NewIndentedInspector(out), nil
+ }
+
+ tmpl, err := templates.Parse(tmplStr)
+ if err != nil {
+ return nil, errors.Errorf("Template parsing error: %s", err)
+ }
+ return NewTemplateInspector(out, tmpl), nil
+}
+
+// GetRefFunc is a function which used by Inspect to fetch an object from a
+// reference
+type GetRefFunc func(ref string) (interface{}, []byte, error)
+
+// Inspect fetches objects by reference using GetRefFunc and writes the json
+// representation to the output writer.
+func Inspect(out io.Writer, references []string, tmplStr string, getRef GetRefFunc) error {
+ inspector, err := NewTemplateInspectorFromString(out, tmplStr)
+ if err != nil {
+ return cli.StatusError{StatusCode: 64, Status: err.Error()}
+ }
+
+ var inspectErrs []string
+ for _, ref := range references {
+ element, raw, err := getRef(ref)
+ if err != nil {
+ inspectErrs = append(inspectErrs, err.Error())
+ continue
+ }
+
+ if err := inspector.Inspect(element, raw); err != nil {
+ inspectErrs = append(inspectErrs, err.Error())
+ }
+ }
+
+ if err := inspector.Flush(); err != nil {
+ logrus.Errorf("%s\n", err)
+ }
+
+ if len(inspectErrs) != 0 {
+ return cli.StatusError{
+ StatusCode: 1,
+ Status: strings.Join(inspectErrs, "\n"),
+ }
+ }
+ return nil
+}
+
+// Inspect executes the inspect template.
+// It decodes the raw element into a map if the initial execution fails.
+// This allows docker cli to parse inspect structs injected with Swarm fields.
+func (i *TemplateInspector) Inspect(typedElement interface{}, rawElement []byte) error {
+ buffer := new(bytes.Buffer)
+ if err := i.tmpl.Execute(buffer, typedElement); err != nil {
+ if rawElement == nil {
+ return errors.Errorf("Template parsing error: %v", err)
+ }
+ return i.tryRawInspectFallback(rawElement)
+ }
+ i.buffer.Write(buffer.Bytes())
+ i.buffer.WriteByte('\n')
+ return nil
+}
+
+// tryRawInspectFallback executes the inspect template with a raw interface.
+// This allows docker cli to parse inspect structs injected with Swarm fields.
+func (i *TemplateInspector) tryRawInspectFallback(rawElement []byte) error {
+ var raw interface{}
+ buffer := new(bytes.Buffer)
+ rdr := bytes.NewReader(rawElement)
+ dec := json.NewDecoder(rdr)
+ dec.UseNumber()
+
+ if rawErr := dec.Decode(&raw); rawErr != nil {
+ return errors.Errorf("unable to read inspect data: %v", rawErr)
+ }
+
+ tmplMissingKey := i.tmpl.Option("missingkey=error")
+ if rawErr := tmplMissingKey.Execute(buffer, raw); rawErr != nil {
+ return errors.Errorf("Template parsing error: %v", rawErr)
+ }
+
+ i.buffer.Write(buffer.Bytes())
+ i.buffer.WriteByte('\n')
+ return nil
+}
+
+// Flush writes the result of inspecting all elements into the output stream.
+func (i *TemplateInspector) Flush() error {
+ if i.buffer.Len() == 0 {
+ _, err := io.WriteString(i.outputStream, "\n")
+ return err
+ }
+ _, err := io.Copy(i.outputStream, i.buffer)
+ return err
+}
+
+// IndentedInspector uses a buffer to stop the indented representation of an element.
+type IndentedInspector struct {
+ outputStream io.Writer
+ elements []interface{}
+ rawElements [][]byte
+}
+
+// NewIndentedInspector generates a new IndentedInspector.
+func NewIndentedInspector(outputStream io.Writer) Inspector {
+ return &IndentedInspector{
+ outputStream: outputStream,
+ }
+}
+
+// Inspect writes the raw element with an indented json format.
+func (i *IndentedInspector) Inspect(typedElement interface{}, rawElement []byte) error {
+ if rawElement != nil {
+ i.rawElements = append(i.rawElements, rawElement)
+ } else {
+ i.elements = append(i.elements, typedElement)
+ }
+ return nil
+}
+
+// Flush writes the result of inspecting all elements into the output stream.
+func (i *IndentedInspector) Flush() error {
+ if len(i.elements) == 0 && len(i.rawElements) == 0 {
+ _, err := io.WriteString(i.outputStream, "[]\n")
+ return err
+ }
+
+ var buffer io.Reader
+ if len(i.rawElements) > 0 {
+ bytesBuffer := new(bytes.Buffer)
+ bytesBuffer.WriteString("[")
+ for idx, r := range i.rawElements {
+ bytesBuffer.Write(r)
+ if idx < len(i.rawElements)-1 {
+ bytesBuffer.WriteString(",")
+ }
+ }
+ bytesBuffer.WriteString("]")
+ indented := new(bytes.Buffer)
+ if err := json.Indent(indented, bytesBuffer.Bytes(), "", " "); err != nil {
+ return err
+ }
+ buffer = indented
+ } else {
+ b, err := json.MarshalIndent(i.elements, "", " ")
+ if err != nil {
+ return err
+ }
+ buffer = bytes.NewReader(b)
+ }
+
+ if _, err := io.Copy(i.outputStream, buffer); err != nil {
+ return err
+ }
+ _, err := io.WriteString(i.outputStream, "\n")
+ return err
+}
diff --git a/vendor/github.com/docker/cli/cli/command/network/cmd.go b/vendor/github.com/docker/cli/cli/command/network/cmd.go
new file mode 100644
index 0000000..97bcca2
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/network/cmd.go
@@ -0,0 +1,29 @@
+package network
+
+import (
+ "github.com/spf13/cobra"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+)
+
+// NewNetworkCommand returns a cobra command for `network` subcommands
+// nolint: interfacer
+func NewNetworkCommand(dockerCli *command.DockerCli) *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "network",
+ Short: "Manage networks",
+ Args: cli.NoArgs,
+ RunE: command.ShowHelp(dockerCli.Err()),
+ }
+ cmd.AddCommand(
+ newConnectCommand(dockerCli),
+ newCreateCommand(dockerCli),
+ newDisconnectCommand(dockerCli),
+ newInspectCommand(dockerCli),
+ newListCommand(dockerCli),
+ newRemoveCommand(dockerCli),
+ NewPruneCommand(dockerCli),
+ )
+ return cmd
+}
diff --git a/vendor/github.com/docker/cli/cli/command/network/connect.go b/vendor/github.com/docker/cli/cli/command/network/connect.go
new file mode 100644
index 0000000..19bd3c5
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/network/connect.go
@@ -0,0 +1,62 @@
+package network
+
+import (
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types/network"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type connectOptions struct {
+ network string
+ container string
+ ipaddress string
+ ipv6address string
+ links opts.ListOpts
+ aliases []string
+ linklocalips []string
+}
+
+func newConnectCommand(dockerCli *command.DockerCli) *cobra.Command {
+ options := connectOptions{
+ links: opts.NewListOpts(opts.ValidateLink),
+ }
+
+ cmd := &cobra.Command{
+ Use: "connect [OPTIONS] NETWORK CONTAINER",
+ Short: "Connect a container to a network",
+ Args: cli.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ options.network = args[0]
+ options.container = args[1]
+ return runConnect(dockerCli, options)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.StringVar(&options.ipaddress, "ip", "", "IPv4 address (e.g., 172.30.100.104)")
+ flags.StringVar(&options.ipv6address, "ip6", "", "IPv6 address (e.g., 2001:db8::33)")
+ flags.Var(&options.links, "link", "Add link to another container")
+ flags.StringSliceVar(&options.aliases, "alias", []string{}, "Add network-scoped alias for the container")
+ flags.StringSliceVar(&options.linklocalips, "link-local-ip", []string{}, "Add a link-local address for the container")
+
+ return cmd
+}
+
+func runConnect(dockerCli *command.DockerCli, options connectOptions) error {
+ client := dockerCli.Client()
+
+ epConfig := &network.EndpointSettings{
+ IPAMConfig: &network.EndpointIPAMConfig{
+ IPv4Address: options.ipaddress,
+ IPv6Address: options.ipv6address,
+ LinkLocalIPs: options.linklocalips,
+ },
+ Links: options.links.GetAll(),
+ Aliases: options.aliases,
+ }
+
+ return client.NetworkConnect(context.Background(), options.network, options.container, epConfig)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/network/create.go b/vendor/github.com/docker/cli/cli/command/network/create.go
new file mode 100644
index 0000000..ed6d2de
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/network/create.go
@@ -0,0 +1,248 @@
+package network
+
+import (
+ "fmt"
+ "net"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/api/types/network"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type createOptions struct {
+ name string
+ scope string
+ driver string
+ driverOpts opts.MapOpts
+ labels opts.ListOpts
+ internal bool
+ ipv6 bool
+ attachable bool
+ ingress bool
+ configOnly bool
+ configFrom string
+
+ ipamDriver string
+ ipamSubnet []string
+ ipamIPRange []string
+ ipamGateway []string
+ ipamAux opts.MapOpts
+ ipamOpt opts.MapOpts
+}
+
+func newCreateCommand(dockerCli *command.DockerCli) *cobra.Command {
+ options := createOptions{
+ driverOpts: *opts.NewMapOpts(nil, nil),
+ labels: opts.NewListOpts(opts.ValidateEnv),
+ ipamAux: *opts.NewMapOpts(nil, nil),
+ ipamOpt: *opts.NewMapOpts(nil, nil),
+ }
+
+ cmd := &cobra.Command{
+ Use: "create [OPTIONS] NETWORK",
+ Short: "Create a network",
+ Args: cli.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ options.name = args[0]
+ return runCreate(dockerCli, options)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.StringVarP(&options.driver, "driver", "d", "bridge", "Driver to manage the Network")
+ flags.VarP(&options.driverOpts, "opt", "o", "Set driver specific options")
+ flags.Var(&options.labels, "label", "Set metadata on a network")
+ flags.BoolVar(&options.internal, "internal", false, "Restrict external access to the network")
+ flags.BoolVar(&options.ipv6, "ipv6", false, "Enable IPv6 networking")
+ flags.BoolVar(&options.attachable, "attachable", false, "Enable manual container attachment")
+ flags.SetAnnotation("attachable", "version", []string{"1.25"})
+ flags.BoolVar(&options.ingress, "ingress", false, "Create swarm routing-mesh network")
+ flags.SetAnnotation("ingress", "version", []string{"1.29"})
+ flags.StringVar(&options.scope, "scope", "", "Control the network's scope")
+ flags.SetAnnotation("scope", "version", []string{"1.30"})
+ flags.BoolVar(&options.configOnly, "config-only", false, "Create a configuration only network")
+ flags.SetAnnotation("config-only", "version", []string{"1.30"})
+ flags.StringVar(&options.configFrom, "config-from", "", "The network from which copying the configuration")
+ flags.SetAnnotation("config-from", "version", []string{"1.30"})
+
+ flags.StringVar(&options.ipamDriver, "ipam-driver", "default", "IP Address Management Driver")
+ flags.StringSliceVar(&options.ipamSubnet, "subnet", []string{}, "Subnet in CIDR format that represents a network segment")
+ flags.StringSliceVar(&options.ipamIPRange, "ip-range", []string{}, "Allocate container ip from a sub-range")
+ flags.StringSliceVar(&options.ipamGateway, "gateway", []string{}, "IPv4 or IPv6 Gateway for the master subnet")
+
+ flags.Var(&options.ipamAux, "aux-address", "Auxiliary IPv4 or IPv6 addresses used by Network driver")
+ flags.Var(&options.ipamOpt, "ipam-opt", "Set IPAM driver specific options")
+
+ return cmd
+}
+
+func runCreate(dockerCli *command.DockerCli, options createOptions) error {
+ client := dockerCli.Client()
+
+ ipamCfg, err := consolidateIpam(options.ipamSubnet, options.ipamIPRange, options.ipamGateway, options.ipamAux.GetAll())
+ if err != nil {
+ return err
+ }
+
+ // Construct network create request body
+ nc := types.NetworkCreate{
+ Driver: options.driver,
+ Options: options.driverOpts.GetAll(),
+ IPAM: &network.IPAM{
+ Driver: options.ipamDriver,
+ Config: ipamCfg,
+ Options: options.ipamOpt.GetAll(),
+ },
+ CheckDuplicate: true,
+ Internal: options.internal,
+ EnableIPv6: options.ipv6,
+ Attachable: options.attachable,
+ Ingress: options.ingress,
+ Scope: options.scope,
+ ConfigOnly: options.configOnly,
+ Labels: opts.ConvertKVStringsToMap(options.labels.GetAll()),
+ }
+
+ if from := options.configFrom; from != "" {
+ nc.ConfigFrom = &network.ConfigReference{
+ Network: from,
+ }
+ }
+
+ resp, err := client.NetworkCreate(context.Background(), options.name, nc)
+ if err != nil {
+ return err
+ }
+ fmt.Fprintf(dockerCli.Out(), "%s\n", resp.ID)
+ return nil
+}
+
+// Consolidates the ipam configuration as a group from different related configurations
+// user can configure network with multiple non-overlapping subnets and hence it is
+// possible to correlate the various related parameters and consolidate them.
+// consolidateIpam consolidates subnets, ip-ranges, gateways and auxiliary addresses into
+// structured ipam data.
+// nolint: gocyclo
+func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]string) ([]network.IPAMConfig, error) {
+ if len(subnets) < len(ranges) || len(subnets) < len(gateways) {
+ return nil, errors.Errorf("every ip-range or gateway must have a corresponding subnet")
+ }
+ iData := map[string]*network.IPAMConfig{}
+
+ // Populate non-overlapping subnets into consolidation map
+ for _, s := range subnets {
+ for k := range iData {
+ ok1, err := subnetMatches(s, k)
+ if err != nil {
+ return nil, err
+ }
+ ok2, err := subnetMatches(k, s)
+ if err != nil {
+ return nil, err
+ }
+ if ok1 || ok2 {
+ return nil, errors.Errorf("multiple overlapping subnet configuration is not supported")
+ }
+ }
+ iData[s] = &network.IPAMConfig{Subnet: s, AuxAddress: map[string]string{}}
+ }
+
+ // Validate and add valid ip ranges
+ for _, r := range ranges {
+ match := false
+ for _, s := range subnets {
+ ok, err := subnetMatches(s, r)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ continue
+ }
+ if iData[s].IPRange != "" {
+ return nil, errors.Errorf("cannot configure multiple ranges (%s, %s) on the same subnet (%s)", r, iData[s].IPRange, s)
+ }
+ d := iData[s]
+ d.IPRange = r
+ match = true
+ }
+ if !match {
+ return nil, errors.Errorf("no matching subnet for range %s", r)
+ }
+ }
+
+ // Validate and add valid gateways
+ for _, g := range gateways {
+ match := false
+ for _, s := range subnets {
+ ok, err := subnetMatches(s, g)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ continue
+ }
+ if iData[s].Gateway != "" {
+ return nil, errors.Errorf("cannot configure multiple gateways (%s, %s) for the same subnet (%s)", g, iData[s].Gateway, s)
+ }
+ d := iData[s]
+ d.Gateway = g
+ match = true
+ }
+ if !match {
+ return nil, errors.Errorf("no matching subnet for gateway %s", g)
+ }
+ }
+
+ // Validate and add aux-addresses
+ for key, aa := range auxaddrs {
+ match := false
+ for _, s := range subnets {
+ ok, err := subnetMatches(s, aa)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ continue
+ }
+ iData[s].AuxAddress[key] = aa
+ match = true
+ }
+ if !match {
+ return nil, errors.Errorf("no matching subnet for aux-address %s", aa)
+ }
+ }
+
+ idl := []network.IPAMConfig{}
+ for _, v := range iData {
+ idl = append(idl, *v)
+ }
+ return idl, nil
+}
+
+func subnetMatches(subnet, data string) (bool, error) {
+ var (
+ ip net.IP
+ )
+
+ _, s, err := net.ParseCIDR(subnet)
+ if err != nil {
+ return false, errors.Errorf("Invalid subnet %s : %v", s, err)
+ }
+
+ if strings.Contains(data, "/") {
+ ip, _, err = net.ParseCIDR(data)
+ if err != nil {
+ return false, errors.Errorf("Invalid cidr %s : %v", data, err)
+ }
+ } else {
+ ip = net.ParseIP(data)
+ }
+
+ return s.Contains(ip), nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/network/disconnect.go b/vendor/github.com/docker/cli/cli/command/network/disconnect.go
new file mode 100644
index 0000000..0f7d7c2
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/network/disconnect.go
@@ -0,0 +1,41 @@
+package network
+
+import (
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/spf13/cobra"
+)
+
+type disconnectOptions struct {
+ network string
+ container string
+ force bool
+}
+
+func newDisconnectCommand(dockerCli *command.DockerCli) *cobra.Command {
+ opts := disconnectOptions{}
+
+ cmd := &cobra.Command{
+ Use: "disconnect [OPTIONS] NETWORK CONTAINER",
+ Short: "Disconnect a container from a network",
+ Args: cli.ExactArgs(2),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.network = args[0]
+ opts.container = args[1]
+ return runDisconnect(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&opts.force, "force", "f", false, "Force the container to disconnect from a network")
+
+ return cmd
+}
+
+func runDisconnect(dockerCli *command.DockerCli, opts disconnectOptions) error {
+ client := dockerCli.Client()
+
+ return client.NetworkDisconnect(context.Background(), opts.network, opts.container, opts.force)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/network/inspect.go b/vendor/github.com/docker/cli/cli/command/network/inspect.go
new file mode 100644
index 0000000..9856c04
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/network/inspect.go
@@ -0,0 +1,48 @@
+package network
+
+import (
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/inspect"
+ "github.com/docker/docker/api/types"
+ "github.com/spf13/cobra"
+)
+
+type inspectOptions struct {
+ format string
+ names []string
+ verbose bool
+}
+
+func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts inspectOptions
+
+ cmd := &cobra.Command{
+ Use: "inspect [OPTIONS] NETWORK [NETWORK...]",
+ Short: "Display detailed information on one or more networks",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.names = args
+ return runInspect(dockerCli, opts)
+ },
+ }
+
+ cmd.Flags().StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
+ cmd.Flags().BoolVarP(&opts.verbose, "verbose", "v", false, "Verbose output for diagnostics")
+
+ return cmd
+}
+
+func runInspect(dockerCli *command.DockerCli, opts inspectOptions) error {
+ client := dockerCli.Client()
+
+ ctx := context.Background()
+
+ getNetFunc := func(name string) (interface{}, []byte, error) {
+ return client.NetworkInspectWithRaw(ctx, name, types.NetworkInspectOptions{Verbose: opts.verbose})
+ }
+
+ return inspect.Inspect(dockerCli.Out(), opts.names, opts.format, getNetFunc)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/network/list.go b/vendor/github.com/docker/cli/cli/command/network/list.go
new file mode 100644
index 0000000..79a860f
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/network/list.go
@@ -0,0 +1,75 @@
+package network
+
+import (
+ "sort"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/formatter"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type byNetworkName []types.NetworkResource
+
+func (r byNetworkName) Len() int { return len(r) }
+func (r byNetworkName) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
+func (r byNetworkName) Less(i, j int) bool { return r[i].Name < r[j].Name }
+
+type listOptions struct {
+ quiet bool
+ noTrunc bool
+ format string
+ filter opts.FilterOpt
+}
+
+func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
+ options := listOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "ls [OPTIONS]",
+ Aliases: []string{"list"},
+ Short: "List networks",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runList(dockerCli, options)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only display network IDs")
+ flags.BoolVar(&options.noTrunc, "no-trunc", false, "Do not truncate the output")
+ flags.StringVar(&options.format, "format", "", "Pretty-print networks using a Go template")
+ flags.VarP(&options.filter, "filter", "f", "Provide filter values (e.g. 'driver=bridge')")
+
+ return cmd
+}
+
+func runList(dockerCli *command.DockerCli, options listOptions) error {
+ client := dockerCli.Client()
+ listOptions := types.NetworkListOptions{Filters: options.filter.Value()}
+ networkResources, err := client.NetworkList(context.Background(), listOptions)
+ if err != nil {
+ return err
+ }
+
+ format := options.format
+ if len(format) == 0 {
+ if len(dockerCli.ConfigFile().NetworksFormat) > 0 && !options.quiet {
+ format = dockerCli.ConfigFile().NetworksFormat
+ } else {
+ format = formatter.TableFormatKey
+ }
+ }
+
+ sort.Sort(byNetworkName(networkResources))
+
+ networksCtx := formatter.Context{
+ Output: dockerCli.Out(),
+ Format: formatter.NewNetworkFormat(format, options.quiet),
+ Trunc: !options.noTrunc,
+ }
+ return formatter.NetworkWrite(networksCtx, networkResources)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/network/prune.go b/vendor/github.com/docker/cli/cli/command/network/prune.go
new file mode 100644
index 0000000..b31db99
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/network/prune.go
@@ -0,0 +1,76 @@
+package network
+
+import (
+ "fmt"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type pruneOptions struct {
+ force bool
+ filter opts.FilterOpt
+}
+
+// NewPruneCommand returns a new cobra prune command for networks
+func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
+ options := pruneOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "prune [OPTIONS]",
+ Short: "Remove all unused networks",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ output, err := runPrune(dockerCli, options)
+ if err != nil {
+ return err
+ }
+ if output != "" {
+ fmt.Fprintln(dockerCli.Out(), output)
+ }
+ return nil
+ },
+ Tags: map[string]string{"version": "1.25"},
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&options.force, "force", "f", false, "Do not prompt for confirmation")
+ flags.Var(&options.filter, "filter", "Provide filter values (e.g. 'until=<timestamp>')")
+
+ return cmd
+}
+
+const warning = `WARNING! This will remove all networks not used by at least one container.
+Are you sure you want to continue?`
+
+func runPrune(dockerCli command.Cli, options pruneOptions) (output string, err error) {
+ pruneFilters := command.PruneFilters(dockerCli, options.filter.Value())
+
+ if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
+ return
+ }
+
+ report, err := dockerCli.Client().NetworksPrune(context.Background(), pruneFilters)
+ if err != nil {
+ return
+ }
+
+ if len(report.NetworksDeleted) > 0 {
+ output = "Deleted Networks:\n"
+ for _, id := range report.NetworksDeleted {
+ output += id + "\n"
+ }
+ }
+
+ return
+}
+
+// RunPrune calls the Network Prune API
+// This returns the amount of space reclaimed and a detailed output string
+func RunPrune(dockerCli command.Cli, filter opts.FilterOpt) (uint64, string, error) {
+ output, err := runPrune(dockerCli, pruneOptions{force: true, filter: filter})
+ return 0, output, err
+}
diff --git a/vendor/github.com/docker/cli/cli/command/network/remove.go b/vendor/github.com/docker/cli/cli/command/network/remove.go
new file mode 100644
index 0000000..7dfe8da
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/network/remove.go
@@ -0,0 +1,54 @@
+package network
+
+import (
+ "fmt"
+
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/spf13/cobra"
+)
+
+func newRemoveCommand(dockerCli *command.DockerCli) *cobra.Command {
+ return &cobra.Command{
+ Use: "rm NETWORK [NETWORK...]",
+ Aliases: []string{"remove"},
+ Short: "Remove one or more networks",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runRemove(dockerCli, args)
+ },
+ }
+}
+
+const ingressWarning = "WARNING! Before removing the routing-mesh network, " +
+ "make sure all the nodes in your swarm run the same docker engine version. " +
+ "Otherwise, removal may not be effective and functionality of newly create " +
+ "ingress networks will be impaired.\nAre you sure you want to continue?"
+
+func runRemove(dockerCli *command.DockerCli, networks []string) error {
+ client := dockerCli.Client()
+ ctx := context.Background()
+ status := 0
+
+ for _, name := range networks {
+ if nw, _, err := client.NetworkInspectWithRaw(ctx, name, types.NetworkInspectOptions{}); err == nil &&
+ nw.Ingress &&
+ !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), ingressWarning) {
+ continue
+ }
+ if err := client.NetworkRemove(ctx, name); err != nil {
+ fmt.Fprintf(dockerCli.Err(), "%s\n", err)
+ status = 1
+ continue
+ }
+ fmt.Fprintf(dockerCli.Out(), "%s\n", name)
+ }
+
+ if status != 0 {
+ return cli.StatusError{StatusCode: status}
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/out.go b/vendor/github.com/docker/cli/cli/command/out.go
new file mode 100644
index 0000000..27b44c2
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/out.go
@@ -0,0 +1,50 @@
+package command
+
+import (
+ "io"
+ "os"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/term"
+)
+
+// OutStream is an output stream used by the DockerCli to write normal program
+// output.
+type OutStream struct {
+ CommonStream
+ out io.Writer
+}
+
+func (o *OutStream) Write(p []byte) (int, error) {
+ return o.out.Write(p)
+}
+
+// SetRawTerminal sets raw mode on the input terminal
+func (o *OutStream) SetRawTerminal() (err error) {
+ if os.Getenv("NORAW") != "" || !o.CommonStream.isTerminal {
+ return nil
+ }
+ o.CommonStream.state, err = term.SetRawTerminalOutput(o.CommonStream.fd)
+ return err
+}
+
+// GetTtySize returns the height and width in characters of the tty
+func (o *OutStream) GetTtySize() (uint, uint) {
+ if !o.isTerminal {
+ return 0, 0
+ }
+ ws, err := term.GetWinsize(o.fd)
+ if err != nil {
+ logrus.Debugf("Error getting size: %s", err)
+ if ws == nil {
+ return 0, 0
+ }
+ }
+ return uint(ws.Height), uint(ws.Width)
+}
+
+// NewOutStream returns a new OutStream object from a Writer
+func NewOutStream(out io.Writer) *OutStream {
+ fd, isTerminal := term.GetFdInfo(out)
+ return &OutStream{CommonStream: CommonStream{fd: fd, isTerminal: isTerminal}, out: out}
+}
diff --git a/vendor/github.com/docker/cli/cli/command/prune/prune.go b/vendor/github.com/docker/cli/cli/command/prune/prune.go
new file mode 100644
index 0000000..e916a82
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/prune/prune.go
@@ -0,0 +1,51 @@
+package prune
+
+import (
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/container"
+ "github.com/docker/cli/cli/command/image"
+ "github.com/docker/cli/cli/command/network"
+ "github.com/docker/cli/cli/command/volume"
+ "github.com/docker/cli/opts"
+ "github.com/spf13/cobra"
+)
+
+// NewContainerPruneCommand returns a cobra prune command for containers
+func NewContainerPruneCommand(dockerCli command.Cli) *cobra.Command {
+ return container.NewPruneCommand(dockerCli)
+}
+
+// NewVolumePruneCommand returns a cobra prune command for volumes
+func NewVolumePruneCommand(dockerCli command.Cli) *cobra.Command {
+ return volume.NewPruneCommand(dockerCli)
+}
+
+// NewImagePruneCommand returns a cobra prune command for images
+func NewImagePruneCommand(dockerCli command.Cli) *cobra.Command {
+ return image.NewPruneCommand(dockerCli)
+}
+
+// NewNetworkPruneCommand returns a cobra prune command for Networks
+func NewNetworkPruneCommand(dockerCli command.Cli) *cobra.Command {
+ return network.NewPruneCommand(dockerCli)
+}
+
+// RunContainerPrune executes a prune command for containers
+func RunContainerPrune(dockerCli command.Cli, filter opts.FilterOpt) (uint64, string, error) {
+ return container.RunPrune(dockerCli, filter)
+}
+
+// RunVolumePrune executes a prune command for volumes
+func RunVolumePrune(dockerCli command.Cli, filter opts.FilterOpt) (uint64, string, error) {
+ return volume.RunPrune(dockerCli, filter)
+}
+
+// RunImagePrune executes a prune command for images
+func RunImagePrune(dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) {
+ return image.RunPrune(dockerCli, all, filter)
+}
+
+// RunNetworkPrune executes a prune command for networks
+func RunNetworkPrune(dockerCli command.Cli, filter opts.FilterOpt) (uint64, string, error) {
+ return network.RunPrune(dockerCli, filter)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/registry.go b/vendor/github.com/docker/cli/cli/command/registry.go
new file mode 100644
index 0000000..802b3a4
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/registry.go
@@ -0,0 +1,189 @@
+package command
+
+import (
+ "bufio"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "runtime"
+ "strings"
+
+ "golang.org/x/net/context"
+
+ "github.com/docker/distribution/reference"
+ "github.com/docker/docker/api/types"
+ registrytypes "github.com/docker/docker/api/types/registry"
+ "github.com/docker/docker/pkg/term"
+ "github.com/docker/docker/registry"
+ "github.com/pkg/errors"
+)
+
+// ElectAuthServer returns the default registry to use (by asking the daemon)
+func ElectAuthServer(ctx context.Context, cli Cli) string {
+ // The daemon `/info` endpoint informs us of the default registry being
+ // used. This is essential in cross-platforms environment, where for
+ // example a Linux client might be interacting with a Windows daemon, hence
+ // the default registry URL might be Windows specific.
+ serverAddress := registry.IndexServer
+ if info, err := cli.Client().Info(ctx); err != nil {
+ fmt.Fprintf(cli.Err(), "Warning: failed to get default registry endpoint from daemon (%v). Using system default: %s\n", err, serverAddress)
+ } else if info.IndexServerAddress == "" {
+ fmt.Fprintf(cli.Err(), "Warning: Empty registry endpoint from daemon. Using system default: %s\n", serverAddress)
+ } else {
+ serverAddress = info.IndexServerAddress
+ }
+ return serverAddress
+}
+
+// EncodeAuthToBase64 serializes the auth configuration as JSON base64 payload
+func EncodeAuthToBase64(authConfig types.AuthConfig) (string, error) {
+ buf, err := json.Marshal(authConfig)
+ if err != nil {
+ return "", err
+ }
+ return base64.URLEncoding.EncodeToString(buf), nil
+}
+
+// RegistryAuthenticationPrivilegedFunc returns a RequestPrivilegeFunc from the specified registry index info
+// for the given command.
+func RegistryAuthenticationPrivilegedFunc(cli Cli, index *registrytypes.IndexInfo, cmdName string) types.RequestPrivilegeFunc {
+ return func() (string, error) {
+ fmt.Fprintf(cli.Out(), "\nPlease login prior to %s:\n", cmdName)
+ indexServer := registry.GetAuthConfigKey(index)
+ isDefaultRegistry := indexServer == ElectAuthServer(context.Background(), cli)
+ authConfig, err := ConfigureAuth(cli, "", "", indexServer, isDefaultRegistry)
+ if err != nil {
+ return "", err
+ }
+ return EncodeAuthToBase64(authConfig)
+ }
+}
+
+// ResolveAuthConfig is like registry.ResolveAuthConfig, but if using the
+// default index, it uses the default index name for the daemon's platform,
+// not the client's platform.
+func ResolveAuthConfig(ctx context.Context, cli Cli, index *registrytypes.IndexInfo) types.AuthConfig {
+ configKey := index.Name
+ if index.Official {
+ configKey = ElectAuthServer(ctx, cli)
+ }
+
+ a, _ := cli.CredentialsStore(configKey).Get(configKey)
+ return a
+}
+
+// ConfigureAuth returns an AuthConfig from the specified user, password and server.
+func ConfigureAuth(cli Cli, flUser, flPassword, serverAddress string, isDefaultRegistry bool) (types.AuthConfig, error) {
+ // On Windows, force the use of the regular OS stdin stream. Fixes #14336/#14210
+ if runtime.GOOS == "windows" {
+ cli.SetIn(NewInStream(os.Stdin))
+ }
+
+ if !isDefaultRegistry {
+ serverAddress = registry.ConvertToHostname(serverAddress)
+ }
+
+ authconfig, err := cli.CredentialsStore(serverAddress).Get(serverAddress)
+ if err != nil {
+ return authconfig, err
+ }
+
+ // Some links documenting this:
+ // - https://code.google.com/archive/p/mintty/issues/56
+ // - https://github.com/docker/docker/issues/15272
+ // - https://mintty.github.io/ (compatibility)
+ // Linux will hit this if you attempt `cat | docker login`, and Windows
+ // will hit this if you attempt docker login from mintty where stdin
+ // is a pipe, not a character based console.
+ if flPassword == "" && !cli.In().IsTerminal() {
+ return authconfig, errors.Errorf("Error: Cannot perform an interactive login from a non TTY device")
+ }
+
+ authconfig.Username = strings.TrimSpace(authconfig.Username)
+
+ if flUser = strings.TrimSpace(flUser); flUser == "" {
+ if isDefaultRegistry {
+ // if this is a default registry (docker hub), then display the following message.
+ fmt.Fprintln(cli.Out(), "Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.")
+ }
+ promptWithDefault(cli.Out(), "Username", authconfig.Username)
+ flUser = readInput(cli.In(), cli.Out())
+ flUser = strings.TrimSpace(flUser)
+ if flUser == "" {
+ flUser = authconfig.Username
+ }
+ }
+ if flUser == "" {
+ return authconfig, errors.Errorf("Error: Non-null Username Required")
+ }
+ if flPassword == "" {
+ oldState, err := term.SaveState(cli.In().FD())
+ if err != nil {
+ return authconfig, err
+ }
+ fmt.Fprintf(cli.Out(), "Password: ")
+ term.DisableEcho(cli.In().FD(), oldState)
+
+ flPassword = readInput(cli.In(), cli.Out())
+ fmt.Fprint(cli.Out(), "\n")
+
+ term.RestoreTerminal(cli.In().FD(), oldState)
+ if flPassword == "" {
+ return authconfig, errors.Errorf("Error: Password Required")
+ }
+ }
+
+ authconfig.Username = flUser
+ authconfig.Password = flPassword
+ authconfig.ServerAddress = serverAddress
+ authconfig.IdentityToken = ""
+
+ return authconfig, nil
+}
+
+func readInput(in io.Reader, out io.Writer) string {
+ reader := bufio.NewReader(in)
+ line, _, err := reader.ReadLine()
+ if err != nil {
+ fmt.Fprintln(out, err.Error())
+ os.Exit(1)
+ }
+ return string(line)
+}
+
+func promptWithDefault(out io.Writer, prompt string, configDefault string) {
+ if configDefault == "" {
+ fmt.Fprintf(out, "%s: ", prompt)
+ } else {
+ fmt.Fprintf(out, "%s (%s): ", prompt, configDefault)
+ }
+}
+
+// RetrieveAuthTokenFromImage retrieves an encoded auth token given a complete image
+func RetrieveAuthTokenFromImage(ctx context.Context, cli Cli, image string) (string, error) {
+ // Retrieve encoded auth token from the image reference
+ authConfig, err := resolveAuthConfigFromImage(ctx, cli, image)
+ if err != nil {
+ return "", err
+ }
+ encodedAuth, err := EncodeAuthToBase64(authConfig)
+ if err != nil {
+ return "", err
+ }
+ return encodedAuth, nil
+}
+
+// resolveAuthConfigFromImage retrieves that AuthConfig using the image string
+func resolveAuthConfigFromImage(ctx context.Context, cli Cli, image string) (types.AuthConfig, error) {
+ registryRef, err := reference.ParseNormalizedNamed(image)
+ if err != nil {
+ return types.AuthConfig{}, err
+ }
+ repoInfo, err := registry.ParseRepositoryInfo(registryRef)
+ if err != nil {
+ return types.AuthConfig{}, err
+ }
+ return ResolveAuthConfig(ctx, cli, repoInfo.Index), nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/registry/login.go b/vendor/github.com/docker/cli/cli/command/registry/login.go
new file mode 100644
index 0000000..ba1b133
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/registry/login.go
@@ -0,0 +1,82 @@
+package registry
+
+import (
+ "fmt"
+
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/registry"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+)
+
+type loginOptions struct {
+ serverAddress string
+ user string
+ password string
+}
+
+// NewLoginCommand creates a new `docker login` command
+func NewLoginCommand(dockerCli command.Cli) *cobra.Command {
+ var opts loginOptions
+
+ cmd := &cobra.Command{
+ Use: "login [OPTIONS] [SERVER]",
+ Short: "Log in to a Docker registry",
+ Long: "Log in to a Docker registry.\nIf no server is specified, the default is defined by the daemon.",
+ Args: cli.RequiresMaxArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if len(args) > 0 {
+ opts.serverAddress = args[0]
+ }
+ return runLogin(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.StringVarP(&opts.user, "username", "u", "", "Username")
+ flags.StringVarP(&opts.password, "password", "p", "", "Password")
+
+ return cmd
+}
+
+func runLogin(dockerCli command.Cli, opts loginOptions) error {
+ ctx := context.Background()
+ clnt := dockerCli.Client()
+
+ var (
+ serverAddress string
+ authServer = command.ElectAuthServer(ctx, dockerCli)
+ )
+ if opts.serverAddress != "" && opts.serverAddress != registry.DefaultNamespace {
+ serverAddress = opts.serverAddress
+ } else {
+ serverAddress = authServer
+ }
+
+ isDefaultRegistry := serverAddress == authServer
+
+ authConfig, err := command.ConfigureAuth(dockerCli, opts.user, opts.password, serverAddress, isDefaultRegistry)
+ if err != nil {
+ return err
+ }
+ response, err := clnt.RegistryLogin(ctx, authConfig)
+ if err != nil {
+ return err
+ }
+ if response.IdentityToken != "" {
+ authConfig.Password = ""
+ authConfig.IdentityToken = response.IdentityToken
+ }
+ if err := dockerCli.CredentialsStore(serverAddress).Store(authConfig); err != nil {
+ return errors.Errorf("Error saving credentials: %v", err)
+ }
+
+ if response.Status != "" {
+ fmt.Fprintln(dockerCli.Out(), response.Status)
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/registry/logout.go b/vendor/github.com/docker/cli/cli/command/registry/logout.go
new file mode 100644
index 0000000..d241df4
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/registry/logout.go
@@ -0,0 +1,77 @@
+package registry
+
+import (
+ "fmt"
+
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/registry"
+ "github.com/spf13/cobra"
+)
+
+// NewLogoutCommand creates a new `docker logout` command
+func NewLogoutCommand(dockerCli command.Cli) *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "logout [SERVER]",
+ Short: "Log out from a Docker registry",
+ Long: "Log out from a Docker registry.\nIf no server is specified, the default is defined by the daemon.",
+ Args: cli.RequiresMaxArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ var serverAddress string
+ if len(args) > 0 {
+ serverAddress = args[0]
+ }
+ return runLogout(dockerCli, serverAddress)
+ },
+ }
+
+ return cmd
+}
+
+func runLogout(dockerCli command.Cli, serverAddress string) error {
+ ctx := context.Background()
+ var isDefaultRegistry bool
+
+ if serverAddress == "" {
+ serverAddress = command.ElectAuthServer(ctx, dockerCli)
+ isDefaultRegistry = true
+ }
+
+ var (
+ loggedIn bool
+ regsToLogout []string
+ hostnameAddress = serverAddress
+ regsToTry = []string{serverAddress}
+ )
+ if !isDefaultRegistry {
+ hostnameAddress = registry.ConvertToHostname(serverAddress)
+ // the tries below are kept for backward compatibility where a user could have
+ // saved the registry in one of the following format.
+ regsToTry = append(regsToTry, hostnameAddress, "http://"+hostnameAddress, "https://"+hostnameAddress)
+ }
+
+ // check if we're logged in based on the records in the config file
+ // which means it couldn't have user/pass cause they may be in the creds store
+ for _, s := range regsToTry {
+ if _, ok := dockerCli.ConfigFile().AuthConfigs[s]; ok {
+ loggedIn = true
+ regsToLogout = append(regsToLogout, s)
+ }
+ }
+
+ if !loggedIn {
+ fmt.Fprintf(dockerCli.Out(), "Not logged in to %s\n", hostnameAddress)
+ return nil
+ }
+
+ fmt.Fprintf(dockerCli.Out(), "Removing login credentials for %s\n", hostnameAddress)
+ for _, r := range regsToLogout {
+ if err := dockerCli.CredentialsStore(r).Erase(r); err != nil {
+ fmt.Fprintf(dockerCli.Err(), "WARNING: could not erase credentials: %v\n", err)
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/registry/search.go b/vendor/github.com/docker/cli/cli/command/registry/search.go
new file mode 100644
index 0000000..443c9a3
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/registry/search.go
@@ -0,0 +1,125 @@
+package registry
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+ "text/tabwriter"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ registrytypes "github.com/docker/docker/api/types/registry"
+ "github.com/docker/docker/pkg/stringutils"
+ "github.com/docker/docker/registry"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type searchOptions struct {
+ term string
+ noTrunc bool
+ limit int
+ filter opts.FilterOpt
+
+ // Deprecated
+ stars uint
+ automated bool
+}
+
+// NewSearchCommand creates a new `docker search` command
+func NewSearchCommand(dockerCli command.Cli) *cobra.Command {
+ options := searchOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "search [OPTIONS] TERM",
+ Short: "Search the Docker Hub for images",
+ Args: cli.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ options.term = args[0]
+ return runSearch(dockerCli, options)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.BoolVar(&options.noTrunc, "no-trunc", false, "Don't truncate output")
+ flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided")
+ flags.IntVar(&options.limit, "limit", registry.DefaultSearchLimit, "Max number of search results")
+
+ flags.BoolVar(&options.automated, "automated", false, "Only show automated builds")
+ flags.UintVarP(&options.stars, "stars", "s", 0, "Only displays with at least x stars")
+
+ flags.MarkDeprecated("automated", "use --filter=is-automated=true instead")
+ flags.MarkDeprecated("stars", "use --filter=stars=3 instead")
+
+ return cmd
+}
+
+func runSearch(dockerCli command.Cli, options searchOptions) error {
+ indexInfo, err := registry.ParseSearchIndexInfo(options.term)
+ if err != nil {
+ return err
+ }
+
+ ctx := context.Background()
+
+ authConfig := command.ResolveAuthConfig(ctx, dockerCli, indexInfo)
+ requestPrivilege := command.RegistryAuthenticationPrivilegedFunc(dockerCli, indexInfo, "search")
+
+ encodedAuth, err := command.EncodeAuthToBase64(authConfig)
+ if err != nil {
+ return err
+ }
+
+ searchOptions := types.ImageSearchOptions{
+ RegistryAuth: encodedAuth,
+ PrivilegeFunc: requestPrivilege,
+ Filters: options.filter.Value(),
+ Limit: options.limit,
+ }
+
+ clnt := dockerCli.Client()
+
+ unorderedResults, err := clnt.ImageSearch(ctx, options.term, searchOptions)
+ if err != nil {
+ return err
+ }
+
+ results := searchResultsByStars(unorderedResults)
+ sort.Sort(results)
+
+ w := tabwriter.NewWriter(dockerCli.Out(), 10, 1, 3, ' ', 0)
+ fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tAUTOMATED\n")
+ for _, res := range results {
+ // --automated and -s, --stars are deprecated since Docker 1.12
+ if (options.automated && !res.IsAutomated) || (int(options.stars) > res.StarCount) {
+ continue
+ }
+ desc := strings.Replace(res.Description, "\n", " ", -1)
+ desc = strings.Replace(desc, "\r", " ", -1)
+ if !options.noTrunc {
+ desc = stringutils.Ellipsis(desc, 45)
+ }
+ fmt.Fprintf(w, "%s\t%s\t%d\t", res.Name, desc, res.StarCount)
+ if res.IsOfficial {
+ fmt.Fprint(w, "[OK]")
+
+ }
+ fmt.Fprint(w, "\t")
+ if res.IsAutomated {
+ fmt.Fprint(w, "[OK]")
+ }
+ fmt.Fprint(w, "\n")
+ }
+ w.Flush()
+ return nil
+}
+
+// searchResultsByStars sorts search results in descending order by number of stars.
+type searchResultsByStars []registrytypes.SearchResult
+
+func (r searchResultsByStars) Len() int { return len(r) }
+func (r searchResultsByStars) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
+func (r searchResultsByStars) Less(i, j int) bool { return r[j].StarCount < r[i].StarCount }
diff --git a/vendor/github.com/docker/cli/cli/command/stream.go b/vendor/github.com/docker/cli/cli/command/stream.go
new file mode 100644
index 0000000..71a43fa
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/stream.go
@@ -0,0 +1,34 @@
+package command
+
+import (
+ "github.com/docker/docker/pkg/term"
+)
+
+// CommonStream is an input stream used by the DockerCli to read user input
+type CommonStream struct {
+ fd uintptr
+ isTerminal bool
+ state *term.State
+}
+
+// FD returns the file descriptor number for this stream
+func (s *CommonStream) FD() uintptr {
+ return s.fd
+}
+
+// IsTerminal returns true if this stream is connected to a terminal
+func (s *CommonStream) IsTerminal() bool {
+ return s.isTerminal
+}
+
+// RestoreTerminal restores normal mode to the terminal
+func (s *CommonStream) RestoreTerminal() {
+ if s.state != nil {
+ term.RestoreTerminal(s.fd, s.state)
+ }
+}
+
+// SetIsTerminal sets the boolean used for isTerminal
+func (s *CommonStream) SetIsTerminal(isTerminal bool) {
+ s.isTerminal = isTerminal
+}
diff --git a/vendor/github.com/docker/cli/cli/command/system/cmd.go b/vendor/github.com/docker/cli/cli/command/system/cmd.go
new file mode 100644
index 0000000..455387c
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/system/cmd.go
@@ -0,0 +1,26 @@
+package system
+
+import (
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/spf13/cobra"
+)
+
+// NewSystemCommand returns a cobra command for `system` subcommands
+// nolint: interfacer
+func NewSystemCommand(dockerCli *command.DockerCli) *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "system",
+ Short: "Manage Docker",
+ Args: cli.NoArgs,
+ RunE: command.ShowHelp(dockerCli.Err()),
+ }
+ cmd.AddCommand(
+ NewEventsCommand(dockerCli),
+ NewInfoCommand(dockerCli),
+ NewDiskUsageCommand(dockerCli),
+ NewPruneCommand(dockerCli),
+ )
+
+ return cmd
+}
diff --git a/vendor/github.com/docker/cli/cli/command/system/df.go b/vendor/github.com/docker/cli/cli/command/system/df.go
new file mode 100644
index 0000000..44c662e
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/system/df.go
@@ -0,0 +1,68 @@
+package system
+
+import (
+ "errors"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/formatter"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type diskUsageOptions struct {
+ verbose bool
+ format string
+}
+
+// NewDiskUsageCommand creates a new cobra.Command for `docker df`
+func NewDiskUsageCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts diskUsageOptions
+
+ cmd := &cobra.Command{
+ Use: "df [OPTIONS]",
+ Short: "Show docker disk usage",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runDiskUsage(dockerCli, opts)
+ },
+ Tags: map[string]string{"version": "1.25"},
+ }
+
+ flags := cmd.Flags()
+
+ flags.BoolVarP(&opts.verbose, "verbose", "v", false, "Show detailed information on space usage")
+ flags.StringVar(&opts.format, "format", "", "Pretty-print images using a Go template")
+
+ return cmd
+}
+
+func runDiskUsage(dockerCli *command.DockerCli, opts diskUsageOptions) error {
+ if opts.verbose && len(opts.format) != 0 {
+ return errors.New("the verbose and the format options conflict")
+ }
+
+ du, err := dockerCli.Client().DiskUsage(context.Background())
+ if err != nil {
+ return err
+ }
+
+ format := opts.format
+ if len(format) == 0 {
+ format = formatter.TableFormatKey
+ }
+
+ duCtx := formatter.DiskUsageContext{
+ Context: formatter.Context{
+ Output: dockerCli.Out(),
+ Format: formatter.NewDiskUsageFormat(format),
+ },
+ LayersSize: du.LayersSize,
+ Images: du.Images,
+ Containers: du.Containers,
+ Volumes: du.Volumes,
+ Verbose: opts.verbose,
+ }
+
+ return duCtx.Write()
+}
diff --git a/vendor/github.com/docker/cli/cli/command/system/events.go b/vendor/github.com/docker/cli/cli/command/system/events.go
new file mode 100644
index 0000000..ba83d26
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/system/events.go
@@ -0,0 +1,139 @@
+package system
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "sort"
+ "strings"
+ "text/template"
+ "time"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ eventtypes "github.com/docker/docker/api/types/events"
+ "github.com/docker/docker/pkg/jsonlog"
+ "github.com/docker/docker/pkg/templates"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type eventsOptions struct {
+ since string
+ until string
+ filter opts.FilterOpt
+ format string
+}
+
+// NewEventsCommand creates a new cobra.Command for `docker events`
+func NewEventsCommand(dockerCli *command.DockerCli) *cobra.Command {
+ options := eventsOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "events [OPTIONS]",
+ Short: "Get real time events from the server",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runEvents(dockerCli, &options)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.StringVar(&options.since, "since", "", "Show all events created since timestamp")
+ flags.StringVar(&options.until, "until", "", "Stream events until this timestamp")
+ flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided")
+ flags.StringVar(&options.format, "format", "", "Format the output using the given Go template")
+
+ return cmd
+}
+
+func runEvents(dockerCli *command.DockerCli, options *eventsOptions) error {
+ tmpl, err := makeTemplate(options.format)
+ if err != nil {
+ return cli.StatusError{
+ StatusCode: 64,
+ Status: "Error parsing format: " + err.Error()}
+ }
+ eventOptions := types.EventsOptions{
+ Since: options.since,
+ Until: options.until,
+ Filters: options.filter.Value(),
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ events, errs := dockerCli.Client().Events(ctx, eventOptions)
+ defer cancel()
+
+ out := dockerCli.Out()
+
+ for {
+ select {
+ case event := <-events:
+ if err := handleEvent(out, event, tmpl); err != nil {
+ return err
+ }
+ case err := <-errs:
+ if err == io.EOF {
+ return nil
+ }
+ return err
+ }
+ }
+}
+
+func handleEvent(out io.Writer, event eventtypes.Message, tmpl *template.Template) error {
+ if tmpl == nil {
+ return prettyPrintEvent(out, event)
+ }
+
+ return formatEvent(out, event, tmpl)
+}
+
+func makeTemplate(format string) (*template.Template, error) {
+ if format == "" {
+ return nil, nil
+ }
+ tmpl, err := templates.Parse(format)
+ if err != nil {
+ return tmpl, err
+ }
+ // we execute the template for an empty message, so as to validate
+ // a bad template like "{{.badFieldString}}"
+ return tmpl, tmpl.Execute(ioutil.Discard, &eventtypes.Message{})
+}
+
+// prettyPrintEvent prints all types of event information.
+// Each output includes the event type, actor id, name and action.
+// Actor attributes are printed at the end if the actor has any.
+func prettyPrintEvent(out io.Writer, event eventtypes.Message) error {
+ if event.TimeNano != 0 {
+ fmt.Fprintf(out, "%s ", time.Unix(0, event.TimeNano).Format(jsonlog.RFC3339NanoFixed))
+ } else if event.Time != 0 {
+ fmt.Fprintf(out, "%s ", time.Unix(event.Time, 0).Format(jsonlog.RFC3339NanoFixed))
+ }
+
+ fmt.Fprintf(out, "%s %s %s", event.Type, event.Action, event.Actor.ID)
+
+ if len(event.Actor.Attributes) > 0 {
+ var attrs []string
+ var keys []string
+ for k := range event.Actor.Attributes {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ v := event.Actor.Attributes[k]
+ attrs = append(attrs, fmt.Sprintf("%s=%s", k, v))
+ }
+ fmt.Fprintf(out, " (%s)", strings.Join(attrs, ", "))
+ }
+ fmt.Fprint(out, "\n")
+ return nil
+}
+
+func formatEvent(out io.Writer, event eventtypes.Message, tmpl *template.Template) error {
+ defer out.Write([]byte{'\n'})
+ return tmpl.Execute(out, event)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/system/info.go b/vendor/github.com/docker/cli/cli/command/system/info.go
new file mode 100644
index 0000000..f2a404e
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/system/info.go
@@ -0,0 +1,381 @@
+package system
+
+import (
+ "fmt"
+ "io"
+ "sort"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/debug"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/api/types/swarm"
+ "github.com/docker/docker/pkg/templates"
+ "github.com/docker/go-units"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type infoOptions struct {
+ format string
+}
+
+// NewInfoCommand creates a new cobra.Command for `docker info`
+func NewInfoCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts infoOptions
+
+ cmd := &cobra.Command{
+ Use: "info [OPTIONS]",
+ Short: "Display system-wide information",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runInfo(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
+
+ return cmd
+}
+
+func runInfo(dockerCli *command.DockerCli, opts *infoOptions) error {
+ ctx := context.Background()
+ info, err := dockerCli.Client().Info(ctx)
+ if err != nil {
+ return err
+ }
+ if opts.format == "" {
+ return prettyPrintInfo(dockerCli, info)
+ }
+ return formatInfo(dockerCli, info, opts.format)
+}
+
+// nolint: gocyclo
+func prettyPrintInfo(dockerCli *command.DockerCli, info types.Info) error {
+ fmt.Fprintf(dockerCli.Out(), "Containers: %d\n", info.Containers)
+ fmt.Fprintf(dockerCli.Out(), " Running: %d\n", info.ContainersRunning)
+ fmt.Fprintf(dockerCli.Out(), " Paused: %d\n", info.ContainersPaused)
+ fmt.Fprintf(dockerCli.Out(), " Stopped: %d\n", info.ContainersStopped)
+ fmt.Fprintf(dockerCli.Out(), "Images: %d\n", info.Images)
+ fprintfIfNotEmpty(dockerCli.Out(), "Server Version: %s\n", info.ServerVersion)
+ fprintfIfNotEmpty(dockerCli.Out(), "Storage Driver: %s\n", info.Driver)
+ if info.DriverStatus != nil {
+ for _, pair := range info.DriverStatus {
+ fmt.Fprintf(dockerCli.Out(), " %s: %s\n", pair[0], pair[1])
+ }
+
+ }
+ if info.SystemStatus != nil {
+ for _, pair := range info.SystemStatus {
+ fmt.Fprintf(dockerCli.Out(), "%s: %s\n", pair[0], pair[1])
+ }
+ }
+ fprintfIfNotEmpty(dockerCli.Out(), "Logging Driver: %s\n", info.LoggingDriver)
+ fprintfIfNotEmpty(dockerCli.Out(), "Cgroup Driver: %s\n", info.CgroupDriver)
+
+ fmt.Fprintf(dockerCli.Out(), "Plugins: \n")
+ fmt.Fprintf(dockerCli.Out(), " Volume:")
+ fmt.Fprintf(dockerCli.Out(), " %s", strings.Join(info.Plugins.Volume, " "))
+ fmt.Fprintf(dockerCli.Out(), "\n")
+ fmt.Fprintf(dockerCli.Out(), " Network:")
+ fmt.Fprintf(dockerCli.Out(), " %s", strings.Join(info.Plugins.Network, " "))
+ fmt.Fprintf(dockerCli.Out(), "\n")
+
+ if len(info.Plugins.Authorization) != 0 {
+ fmt.Fprintf(dockerCli.Out(), " Authorization:")
+ fmt.Fprintf(dockerCli.Out(), " %s", strings.Join(info.Plugins.Authorization, " "))
+ fmt.Fprintf(dockerCli.Out(), "\n")
+ }
+
+ fmt.Fprintf(dockerCli.Out(), " Log:")
+ fmt.Fprintf(dockerCli.Out(), " %s", strings.Join(info.Plugins.Log, " "))
+ fmt.Fprintf(dockerCli.Out(), "\n")
+
+ fmt.Fprintf(dockerCli.Out(), "Swarm: %v\n", info.Swarm.LocalNodeState)
+ if info.Swarm.LocalNodeState != swarm.LocalNodeStateInactive && info.Swarm.LocalNodeState != swarm.LocalNodeStateLocked {
+ fmt.Fprintf(dockerCli.Out(), " NodeID: %s\n", info.Swarm.NodeID)
+ if info.Swarm.Error != "" {
+ fmt.Fprintf(dockerCli.Out(), " Error: %v\n", info.Swarm.Error)
+ }
+ fmt.Fprintf(dockerCli.Out(), " Is Manager: %v\n", info.Swarm.ControlAvailable)
+ if info.Swarm.Cluster != nil && info.Swarm.ControlAvailable && info.Swarm.Error == "" && info.Swarm.LocalNodeState != swarm.LocalNodeStateError {
+ fmt.Fprintf(dockerCli.Out(), " ClusterID: %s\n", info.Swarm.Cluster.ID)
+ fmt.Fprintf(dockerCli.Out(), " Managers: %d\n", info.Swarm.Managers)
+ fmt.Fprintf(dockerCli.Out(), " Nodes: %d\n", info.Swarm.Nodes)
+ fmt.Fprintf(dockerCli.Out(), " Orchestration:\n")
+ taskHistoryRetentionLimit := int64(0)
+ if info.Swarm.Cluster.Spec.Orchestration.TaskHistoryRetentionLimit != nil {
+ taskHistoryRetentionLimit = *info.Swarm.Cluster.Spec.Orchestration.TaskHistoryRetentionLimit
+ }
+ fmt.Fprintf(dockerCli.Out(), " Task History Retention Limit: %d\n", taskHistoryRetentionLimit)
+ fmt.Fprintf(dockerCli.Out(), " Raft:\n")
+ fmt.Fprintf(dockerCli.Out(), " Snapshot Interval: %d\n", info.Swarm.Cluster.Spec.Raft.SnapshotInterval)
+ if info.Swarm.Cluster.Spec.Raft.KeepOldSnapshots != nil {
+ fmt.Fprintf(dockerCli.Out(), " Number of Old Snapshots to Retain: %d\n", *info.Swarm.Cluster.Spec.Raft.KeepOldSnapshots)
+ }
+ fmt.Fprintf(dockerCli.Out(), " Heartbeat Tick: %d\n", info.Swarm.Cluster.Spec.Raft.HeartbeatTick)
+ fmt.Fprintf(dockerCli.Out(), " Election Tick: %d\n", info.Swarm.Cluster.Spec.Raft.ElectionTick)
+ fmt.Fprintf(dockerCli.Out(), " Dispatcher:\n")
+ fmt.Fprintf(dockerCli.Out(), " Heartbeat Period: %s\n", units.HumanDuration(info.Swarm.Cluster.Spec.Dispatcher.HeartbeatPeriod))
+ fmt.Fprintf(dockerCli.Out(), " CA Configuration:\n")
+ fmt.Fprintf(dockerCli.Out(), " Expiry Duration: %s\n", units.HumanDuration(info.Swarm.Cluster.Spec.CAConfig.NodeCertExpiry))
+ fmt.Fprintf(dockerCli.Out(), " Force Rotate: %d\n", info.Swarm.Cluster.Spec.CAConfig.ForceRotate)
+ fprintfIfNotEmpty(dockerCli.Out(), " Signing CA Certificate: \n%s\n\n", strings.TrimSpace(info.Swarm.Cluster.Spec.CAConfig.SigningCACert))
+ if len(info.Swarm.Cluster.Spec.CAConfig.ExternalCAs) > 0 {
+ fmt.Fprintf(dockerCli.Out(), " External CAs:\n")
+ for _, entry := range info.Swarm.Cluster.Spec.CAConfig.ExternalCAs {
+ fmt.Fprintf(dockerCli.Out(), " %s: %s\n", entry.Protocol, entry.URL)
+ }
+ }
+ fmt.Fprintf(dockerCli.Out(), " Root Rotation In Progress: %v\n", info.Swarm.Cluster.RootRotationInProgress)
+ }
+ fmt.Fprintf(dockerCli.Out(), " Node Address: %s\n", info.Swarm.NodeAddr)
+ managers := []string{}
+ for _, entry := range info.Swarm.RemoteManagers {
+ managers = append(managers, entry.Addr)
+ }
+ if len(managers) > 0 {
+ sort.Strings(managers)
+ fmt.Fprintf(dockerCli.Out(), " Manager Addresses:\n")
+ for _, entry := range managers {
+ fmt.Fprintf(dockerCli.Out(), " %s\n", entry)
+ }
+ }
+ }
+
+ if len(info.Runtimes) > 0 {
+ fmt.Fprintf(dockerCli.Out(), "Runtimes:")
+ for name := range info.Runtimes {
+ fmt.Fprintf(dockerCli.Out(), " %s", name)
+ }
+ fmt.Fprint(dockerCli.Out(), "\n")
+ fmt.Fprintf(dockerCli.Out(), "Default Runtime: %s\n", info.DefaultRuntime)
+ }
+
+ if info.OSType == "linux" {
+ fmt.Fprintf(dockerCli.Out(), "Init Binary: %v\n", info.InitBinary)
+
+ for _, ci := range []struct {
+ Name string
+ Commit types.Commit
+ }{
+ {"containerd", info.ContainerdCommit},
+ {"runc", info.RuncCommit},
+ {"init", info.InitCommit},
+ } {
+ fmt.Fprintf(dockerCli.Out(), "%s version: %s", ci.Name, ci.Commit.ID)
+ if ci.Commit.ID != ci.Commit.Expected {
+ fmt.Fprintf(dockerCli.Out(), " (expected: %s)", ci.Commit.Expected)
+ }
+ fmt.Fprintf(dockerCli.Out(), "\n")
+ }
+ if len(info.SecurityOptions) != 0 {
+ kvs, err := types.DecodeSecurityOptions(info.SecurityOptions)
+ if err != nil {
+ return err
+ }
+ fmt.Fprintf(dockerCli.Out(), "Security Options:\n")
+ for _, so := range kvs {
+ fmt.Fprintf(dockerCli.Out(), " %s\n", so.Name)
+ for _, o := range so.Options {
+ switch o.Key {
+ case "profile":
+ if o.Value != "default" {
+ fmt.Fprintf(dockerCli.Err(), " WARNING: You're not using the default seccomp profile\n")
+ }
+ fmt.Fprintf(dockerCli.Out(), " Profile: %s\n", o.Value)
+ }
+ }
+ }
+ }
+ }
+
+ // Isolation only has meaning on a Windows daemon.
+ if info.OSType == "windows" {
+ fmt.Fprintf(dockerCli.Out(), "Default Isolation: %v\n", info.Isolation)
+ }
+
+ fprintfIfNotEmpty(dockerCli.Out(), "Kernel Version: %s\n", info.KernelVersion)
+ fprintfIfNotEmpty(dockerCli.Out(), "Operating System: %s\n", info.OperatingSystem)
+ fprintfIfNotEmpty(dockerCli.Out(), "OSType: %s\n", info.OSType)
+ fprintfIfNotEmpty(dockerCli.Out(), "Architecture: %s\n", info.Architecture)
+ fmt.Fprintf(dockerCli.Out(), "CPUs: %d\n", info.NCPU)
+ fmt.Fprintf(dockerCli.Out(), "Total Memory: %s\n", units.BytesSize(float64(info.MemTotal)))
+ fprintfIfNotEmpty(dockerCli.Out(), "Name: %s\n", info.Name)
+ fprintfIfNotEmpty(dockerCli.Out(), "ID: %s\n", info.ID)
+ fmt.Fprintf(dockerCli.Out(), "Docker Root Dir: %s\n", info.DockerRootDir)
+ fmt.Fprintf(dockerCli.Out(), "Debug Mode (client): %v\n", debug.IsEnabled())
+ fmt.Fprintf(dockerCli.Out(), "Debug Mode (server): %v\n", info.Debug)
+
+ if info.Debug {
+ fmt.Fprintf(dockerCli.Out(), " File Descriptors: %d\n", info.NFd)
+ fmt.Fprintf(dockerCli.Out(), " Goroutines: %d\n", info.NGoroutines)
+ fmt.Fprintf(dockerCli.Out(), " System Time: %s\n", info.SystemTime)
+ fmt.Fprintf(dockerCli.Out(), " EventsListeners: %d\n", info.NEventsListener)
+ }
+
+ fprintfIfNotEmpty(dockerCli.Out(), "Http Proxy: %s\n", info.HTTPProxy)
+ fprintfIfNotEmpty(dockerCli.Out(), "Https Proxy: %s\n", info.HTTPSProxy)
+ fprintfIfNotEmpty(dockerCli.Out(), "No Proxy: %s\n", info.NoProxy)
+
+ if info.IndexServerAddress != "" {
+ u := dockerCli.ConfigFile().AuthConfigs[info.IndexServerAddress].Username
+ if len(u) > 0 {
+ fmt.Fprintf(dockerCli.Out(), "Username: %v\n", u)
+ }
+ fmt.Fprintf(dockerCli.Out(), "Registry: %v\n", info.IndexServerAddress)
+ }
+
+ if info.Labels != nil {
+ fmt.Fprintln(dockerCli.Out(), "Labels:")
+ for _, attribute := range info.Labels {
+ fmt.Fprintf(dockerCli.Out(), " %s\n", attribute)
+ }
+ // TODO: Engine labels with duplicate keys has been deprecated in 1.13 and will be error out
+ // after 3 release cycles (17.12). For now, a WARNING will be generated. The following will
+ // be removed eventually.
+ labelMap := map[string]string{}
+ for _, label := range info.Labels {
+ stringSlice := strings.SplitN(label, "=", 2)
+ if len(stringSlice) > 1 {
+ // If there is a conflict we will throw out a warning
+ if v, ok := labelMap[stringSlice[0]]; ok && v != stringSlice[1] {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: labels with duplicate keys and conflicting values have been deprecated")
+ break
+ }
+ labelMap[stringSlice[0]] = stringSlice[1]
+ }
+ }
+ }
+
+ fmt.Fprintf(dockerCli.Out(), "Experimental: %v\n", info.ExperimentalBuild)
+ if info.ClusterStore != "" {
+ fmt.Fprintf(dockerCli.Out(), "Cluster Store: %s\n", info.ClusterStore)
+ }
+
+ if info.ClusterAdvertise != "" {
+ fmt.Fprintf(dockerCli.Out(), "Cluster Advertise: %s\n", info.ClusterAdvertise)
+ }
+
+ if info.RegistryConfig != nil && (len(info.RegistryConfig.InsecureRegistryCIDRs) > 0 || len(info.RegistryConfig.IndexConfigs) > 0) {
+ fmt.Fprintln(dockerCli.Out(), "Insecure Registries:")
+ for _, registry := range info.RegistryConfig.IndexConfigs {
+ if !registry.Secure {
+ fmt.Fprintf(dockerCli.Out(), " %s\n", registry.Name)
+ }
+ }
+
+ for _, registry := range info.RegistryConfig.InsecureRegistryCIDRs {
+ mask, _ := registry.Mask.Size()
+ fmt.Fprintf(dockerCli.Out(), " %s/%d\n", registry.IP.String(), mask)
+ }
+ }
+
+ if info.RegistryConfig != nil && len(info.RegistryConfig.Mirrors) > 0 {
+ fmt.Fprintln(dockerCli.Out(), "Registry Mirrors:")
+ for _, mirror := range info.RegistryConfig.Mirrors {
+ fmt.Fprintf(dockerCli.Out(), " %s\n", mirror)
+ }
+ }
+
+ fmt.Fprintf(dockerCli.Out(), "Live Restore Enabled: %v\n\n", info.LiveRestoreEnabled)
+
+ // Only output these warnings if the server does not support these features
+ if info.OSType != "windows" {
+ printStorageDriverWarnings(dockerCli, info)
+
+ if !info.MemoryLimit {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: No memory limit support")
+ }
+ if !info.SwapLimit {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: No swap limit support")
+ }
+ if !info.KernelMemory {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: No kernel memory limit support")
+ }
+ if !info.OomKillDisable {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: No oom kill disable support")
+ }
+ if !info.CPUCfsQuota {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: No cpu cfs quota support")
+ }
+ if !info.CPUCfsPeriod {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: No cpu cfs period support")
+ }
+ if !info.CPUShares {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: No cpu shares support")
+ }
+ if !info.CPUSet {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: No cpuset support")
+ }
+ if !info.IPv4Forwarding {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: IPv4 forwarding is disabled")
+ }
+ if !info.BridgeNfIptables {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: bridge-nf-call-iptables is disabled")
+ }
+ if !info.BridgeNfIP6tables {
+ fmt.Fprintln(dockerCli.Err(), "WARNING: bridge-nf-call-ip6tables is disabled")
+ }
+ }
+
+ return nil
+}
+
+func printStorageDriverWarnings(dockerCli *command.DockerCli, info types.Info) {
+ if info.DriverStatus == nil {
+ return
+ }
+
+ for _, pair := range info.DriverStatus {
+ if pair[0] == "Data loop file" {
+ fmt.Fprintf(dockerCli.Err(), "WARNING: %s: usage of loopback devices is "+
+ "strongly discouraged for production use.\n "+
+ "Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.\n", info.Driver)
+ }
+ if pair[0] == "Supports d_type" && pair[1] == "false" {
+ backingFs := getBackingFs(info)
+
+ msg := fmt.Sprintf("WARNING: %s: the backing %s filesystem is formatted without d_type support, which leads to incorrect behavior.\n", info.Driver, backingFs)
+ if backingFs == "xfs" {
+ msg += " Reformat the filesystem with ftype=1 to enable d_type support.\n"
+ }
+ msg += " Running without d_type support will not be supported in future releases."
+ fmt.Fprintln(dockerCli.Err(), msg)
+ }
+ }
+}
+
+func getBackingFs(info types.Info) string {
+ if info.DriverStatus == nil {
+ return ""
+ }
+
+ for _, pair := range info.DriverStatus {
+ if pair[0] == "Backing Filesystem" {
+ return pair[1]
+ }
+ }
+ return ""
+}
+
+func formatInfo(dockerCli *command.DockerCli, info types.Info, format string) error {
+ tmpl, err := templates.Parse(format)
+ if err != nil {
+ return cli.StatusError{StatusCode: 64,
+ Status: "Template parsing error: " + err.Error()}
+ }
+ err = tmpl.Execute(dockerCli.Out(), info)
+ dockerCli.Out().Write([]byte{'\n'})
+ return err
+}
+
+func fprintfIfNotEmpty(w io.Writer, format, value string) (int, error) {
+ if value != "" {
+ return fmt.Fprintf(w, format, value)
+ }
+ return 0, nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/system/inspect.go b/vendor/github.com/docker/cli/cli/command/system/inspect.go
new file mode 100644
index 0000000..6d079cd
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/system/inspect.go
@@ -0,0 +1,216 @@
+package system
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/inspect"
+ "github.com/docker/docker/api/types"
+ apiclient "github.com/docker/docker/client"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type inspectOptions struct {
+ format string
+ inspectType string
+ size bool
+ ids []string
+}
+
+// NewInspectCommand creates a new cobra.Command for `docker inspect`
+func NewInspectCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts inspectOptions
+
+ cmd := &cobra.Command{
+ Use: "inspect [OPTIONS] NAME|ID [NAME|ID...]",
+ Short: "Return low-level information on Docker objects",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.ids = args
+ return runInspect(dockerCli, opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
+ flags.StringVar(&opts.inspectType, "type", "", "Return JSON for specified type")
+ flags.BoolVarP(&opts.size, "size", "s", false, "Display total file sizes if the type is container")
+
+ return cmd
+}
+
+func runInspect(dockerCli *command.DockerCli, opts inspectOptions) error {
+ var elementSearcher inspect.GetRefFunc
+ switch opts.inspectType {
+ case "", "container", "image", "node", "network", "service", "volume", "task", "plugin", "secret":
+ elementSearcher = inspectAll(context.Background(), dockerCli, opts.size, opts.inspectType)
+ default:
+ return errors.Errorf("%q is not a valid value for --type", opts.inspectType)
+ }
+ return inspect.Inspect(dockerCli.Out(), opts.ids, opts.format, elementSearcher)
+}
+
+func inspectContainers(ctx context.Context, dockerCli *command.DockerCli, getSize bool) inspect.GetRefFunc {
+ return func(ref string) (interface{}, []byte, error) {
+ return dockerCli.Client().ContainerInspectWithRaw(ctx, ref, getSize)
+ }
+}
+
+func inspectImages(ctx context.Context, dockerCli *command.DockerCli) inspect.GetRefFunc {
+ return func(ref string) (interface{}, []byte, error) {
+ return dockerCli.Client().ImageInspectWithRaw(ctx, ref)
+ }
+}
+
+func inspectNetwork(ctx context.Context, dockerCli *command.DockerCli) inspect.GetRefFunc {
+ return func(ref string) (interface{}, []byte, error) {
+ return dockerCli.Client().NetworkInspectWithRaw(ctx, ref, types.NetworkInspectOptions{})
+ }
+}
+
+func inspectNode(ctx context.Context, dockerCli *command.DockerCli) inspect.GetRefFunc {
+ return func(ref string) (interface{}, []byte, error) {
+ return dockerCli.Client().NodeInspectWithRaw(ctx, ref)
+ }
+}
+
+func inspectService(ctx context.Context, dockerCli *command.DockerCli) inspect.GetRefFunc {
+ return func(ref string) (interface{}, []byte, error) {
+ // Service inspect shows defaults values in empty fields.
+ return dockerCli.Client().ServiceInspectWithRaw(ctx, ref, types.ServiceInspectOptions{InsertDefaults: true})
+ }
+}
+
+func inspectTasks(ctx context.Context, dockerCli *command.DockerCli) inspect.GetRefFunc {
+ return func(ref string) (interface{}, []byte, error) {
+ return dockerCli.Client().TaskInspectWithRaw(ctx, ref)
+ }
+}
+
+func inspectVolume(ctx context.Context, dockerCli *command.DockerCli) inspect.GetRefFunc {
+ return func(ref string) (interface{}, []byte, error) {
+ return dockerCli.Client().VolumeInspectWithRaw(ctx, ref)
+ }
+}
+
+func inspectPlugin(ctx context.Context, dockerCli *command.DockerCli) inspect.GetRefFunc {
+ return func(ref string) (interface{}, []byte, error) {
+ return dockerCli.Client().PluginInspectWithRaw(ctx, ref)
+ }
+}
+
+func inspectSecret(ctx context.Context, dockerCli *command.DockerCli) inspect.GetRefFunc {
+ return func(ref string) (interface{}, []byte, error) {
+ return dockerCli.Client().SecretInspectWithRaw(ctx, ref)
+ }
+}
+
+func inspectAll(ctx context.Context, dockerCli *command.DockerCli, getSize bool, typeConstraint string) inspect.GetRefFunc {
+ var inspectAutodetect = []struct {
+ objectType string
+ isSizeSupported bool
+ isSwarmObject bool
+ objectInspector func(string) (interface{}, []byte, error)
+ }{
+ {
+ objectType: "container",
+ isSizeSupported: true,
+ objectInspector: inspectContainers(ctx, dockerCli, getSize),
+ },
+ {
+ objectType: "image",
+ objectInspector: inspectImages(ctx, dockerCli),
+ },
+ {
+ objectType: "network",
+ objectInspector: inspectNetwork(ctx, dockerCli),
+ },
+ {
+ objectType: "volume",
+ objectInspector: inspectVolume(ctx, dockerCli),
+ },
+ {
+ objectType: "service",
+ isSwarmObject: true,
+ objectInspector: inspectService(ctx, dockerCli),
+ },
+ {
+ objectType: "task",
+ isSwarmObject: true,
+ objectInspector: inspectTasks(ctx, dockerCli),
+ },
+ {
+ objectType: "node",
+ isSwarmObject: true,
+ objectInspector: inspectNode(ctx, dockerCli),
+ },
+ {
+ objectType: "plugin",
+ objectInspector: inspectPlugin(ctx, dockerCli),
+ },
+ {
+ objectType: "secret",
+ isSwarmObject: true,
+ objectInspector: inspectSecret(ctx, dockerCli),
+ },
+ }
+
+ // isSwarmManager does an Info API call to verify that the daemon is
+ // a swarm manager.
+ isSwarmManager := func() bool {
+ info, err := dockerCli.Client().Info(ctx)
+ if err != nil {
+ fmt.Fprintln(dockerCli.Err(), err)
+ return false
+ }
+ return info.Swarm.ControlAvailable
+ }
+
+ isErrNotSupported := func(err error) bool {
+ return strings.Contains(err.Error(), "not supported")
+ }
+
+ return func(ref string) (interface{}, []byte, error) {
+ const (
+ swarmSupportUnknown = iota
+ swarmSupported
+ swarmUnsupported
+ )
+
+ isSwarmSupported := swarmSupportUnknown
+
+ for _, inspectData := range inspectAutodetect {
+ if typeConstraint != "" && inspectData.objectType != typeConstraint {
+ continue
+ }
+ if typeConstraint == "" && inspectData.isSwarmObject {
+ if isSwarmSupported == swarmSupportUnknown {
+ if isSwarmManager() {
+ isSwarmSupported = swarmSupported
+ } else {
+ isSwarmSupported = swarmUnsupported
+ }
+ }
+ if isSwarmSupported == swarmUnsupported {
+ continue
+ }
+ }
+ v, raw, err := inspectData.objectInspector(ref)
+ if err != nil {
+ if typeConstraint == "" && (apiclient.IsErrNotFound(err) || isErrNotSupported(err)) {
+ continue
+ }
+ return v, raw, err
+ }
+ if getSize && !inspectData.isSizeSupported {
+ fmt.Fprintf(dockerCli.Err(), "WARNING: --size ignored for %s\n", inspectData.objectType)
+ }
+ return v, raw, err
+ }
+ return nil, nil, errors.Errorf("Error: No such object: %s", ref)
+ }
+}
diff --git a/vendor/github.com/docker/cli/cli/command/system/prune.go b/vendor/github.com/docker/cli/cli/command/system/prune.go
new file mode 100644
index 0000000..fca9c98
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/system/prune.go
@@ -0,0 +1,103 @@
+package system
+
+import (
+ "fmt"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/prune"
+ "github.com/docker/cli/opts"
+ units "github.com/docker/go-units"
+ "github.com/spf13/cobra"
+)
+
+type pruneOptions struct {
+ force bool
+ all bool
+ pruneVolumes bool
+ filter opts.FilterOpt
+}
+
+// NewPruneCommand creates a new cobra.Command for `docker prune`
+func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
+ options := pruneOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "prune [OPTIONS]",
+ Short: "Remove unused data",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runPrune(dockerCli, options)
+ },
+ Tags: map[string]string{"version": "1.25"},
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&options.force, "force", "f", false, "Do not prompt for confirmation")
+ flags.BoolVarP(&options.all, "all", "a", false, "Remove all unused images not just dangling ones")
+ flags.BoolVar(&options.pruneVolumes, "volumes", false, "Prune volumes")
+ flags.Var(&options.filter, "filter", "Provide filter values (e.g. 'label=<key>=<value>')")
+ // "filter" flag is available in 1.28 (docker 17.04) and up
+ flags.SetAnnotation("filter", "version", []string{"1.28"})
+
+ return cmd
+}
+
+const (
+ warning = `WARNING! This will remove:
+ - all stopped containers
+ - all volumes not used by at least one container
+ - all networks not used by at least one container
+ %s
+Are you sure you want to continue?`
+
+ danglingImageDesc = "- all dangling images"
+ allImageDesc = `- all images without at least one container associated to them`
+)
+
+func runPrune(dockerCli command.Cli, options pruneOptions) error {
+ var message string
+
+ if options.all {
+ message = fmt.Sprintf(warning, allImageDesc)
+ } else {
+ message = fmt.Sprintf(warning, danglingImageDesc)
+ }
+
+ if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), message) {
+ return nil
+ }
+
+ var spaceReclaimed uint64
+ pruneFuncs := []func(dockerCli command.Cli, filter opts.FilterOpt) (uint64, string, error){
+ prune.RunContainerPrune,
+ prune.RunNetworkPrune,
+ }
+ if options.pruneVolumes {
+ pruneFuncs = append(pruneFuncs, prune.RunVolumePrune)
+ }
+
+ for _, pruneFn := range pruneFuncs {
+ spc, output, err := pruneFn(dockerCli, options.filter)
+ if err != nil {
+ return err
+ }
+ spaceReclaimed += spc
+ if output != "" {
+ fmt.Fprintln(dockerCli.Out(), output)
+ }
+ }
+
+ spc, output, err := prune.RunImagePrune(dockerCli, options.all, options.filter)
+ if err != nil {
+ return err
+ }
+ if spc > 0 {
+ spaceReclaimed += spc
+ fmt.Fprintln(dockerCli.Out(), output)
+ }
+
+ fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
+
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/system/version.go b/vendor/github.com/docker/cli/cli/command/system/version.go
new file mode 100644
index 0000000..21c5a6d
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/system/version.go
@@ -0,0 +1,130 @@
+package system
+
+import (
+ "runtime"
+ "time"
+
+ "golang.org/x/net/context"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/templates"
+ "github.com/spf13/cobra"
+)
+
+var versionTemplate = `Client:
+ Version: {{.Client.Version}}
+ API version: {{.Client.APIVersion}}{{if ne .Client.APIVersion .Client.DefaultAPIVersion}} (downgraded from {{.Client.DefaultAPIVersion}}){{end}}
+ Go version: {{.Client.GoVersion}}
+ Git commit: {{.Client.GitCommit}}
+ Built: {{.Client.BuildTime}}
+ OS/Arch: {{.Client.Os}}/{{.Client.Arch}}{{if .ServerOK}}
+
+Server:
+ Version: {{.Server.Version}}
+ API version: {{.Server.APIVersion}} (minimum version {{.Server.MinAPIVersion}})
+ Go version: {{.Server.GoVersion}}
+ Git commit: {{.Server.GitCommit}}
+ Built: {{.Server.BuildTime}}
+ OS/Arch: {{.Server.Os}}/{{.Server.Arch}}
+ Experimental: {{.Server.Experimental}}{{end}}`
+
+type versionOptions struct {
+ format string
+}
+
+// versionInfo contains version information of both the Client, and Server
+type versionInfo struct {
+ Client clientVersion
+ Server *types.Version
+}
+
+type clientVersion struct {
+ Version string
+ APIVersion string `json:"ApiVersion"`
+ DefaultAPIVersion string `json:"DefaultAPIVersion,omitempty"`
+ GitCommit string
+ GoVersion string
+ Os string
+ Arch string
+ BuildTime string `json:",omitempty"`
+}
+
+// ServerOK returns true when the client could connect to the docker server
+// and parse the information received. It returns false otherwise.
+func (v versionInfo) ServerOK() bool {
+ return v.Server != nil
+}
+
+// NewVersionCommand creates a new cobra.Command for `docker version`
+func NewVersionCommand(dockerCli *command.DockerCli) *cobra.Command {
+ var opts versionOptions
+
+ cmd := &cobra.Command{
+ Use: "version [OPTIONS]",
+ Short: "Show the Docker version information",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runVersion(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+
+ flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
+
+ return cmd
+}
+
+func runVersion(dockerCli *command.DockerCli, opts *versionOptions) error {
+ ctx := context.Background()
+
+ templateFormat := versionTemplate
+ if opts.format != "" {
+ templateFormat = opts.format
+ }
+
+ tmpl, err := templates.Parse(templateFormat)
+ if err != nil {
+ return cli.StatusError{StatusCode: 64,
+ Status: "Template parsing error: " + err.Error()}
+ }
+
+ vd := versionInfo{
+ Client: clientVersion{
+ Version: cli.Version,
+ APIVersion: dockerCli.Client().ClientVersion(),
+ DefaultAPIVersion: dockerCli.DefaultVersion(),
+ GoVersion: runtime.Version(),
+ GitCommit: cli.GitCommit,
+ BuildTime: cli.BuildTime,
+ Os: runtime.GOOS,
+ Arch: runtime.GOARCH,
+ },
+ }
+
+ serverVersion, err := dockerCli.Client().ServerVersion(ctx)
+ if err == nil {
+ vd.Server = &serverVersion
+ }
+
+ // first we need to make BuildTime more human friendly
+ t, errTime := time.Parse(time.RFC3339Nano, vd.Client.BuildTime)
+ if errTime == nil {
+ vd.Client.BuildTime = t.Format(time.ANSIC)
+ }
+
+ if vd.ServerOK() {
+ t, errTime = time.Parse(time.RFC3339Nano, vd.Server.BuildTime)
+ if errTime == nil {
+ vd.Server.BuildTime = t.Format(time.ANSIC)
+ }
+ }
+
+ if err2 := tmpl.Execute(dockerCli.Out(), vd); err2 != nil && err == nil {
+ err = err2
+ }
+ dockerCli.Out().Write([]byte{'\n'})
+ return err
+}
diff --git a/vendor/github.com/docker/cli/cli/command/trust.go b/vendor/github.com/docker/cli/cli/command/trust.go
new file mode 100644
index 0000000..c0742bc
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/trust.go
@@ -0,0 +1,43 @@
+package command
+
+import (
+ "os"
+ "strconv"
+
+ "github.com/spf13/pflag"
+)
+
+var (
+ // TODO: make this not global
+ untrusted bool
+)
+
+// AddTrustVerificationFlags adds content trust flags to the provided flagset
+func AddTrustVerificationFlags(fs *pflag.FlagSet) {
+ trusted := getDefaultTrustState()
+ fs.BoolVar(&untrusted, "disable-content-trust", !trusted, "Skip image verification")
+}
+
+// AddTrustSigningFlags adds "signing" flags to the provided flagset
+func AddTrustSigningFlags(fs *pflag.FlagSet) {
+ trusted := getDefaultTrustState()
+ fs.BoolVar(&untrusted, "disable-content-trust", !trusted, "Skip image signing")
+}
+
+// getDefaultTrustState returns true if content trust is enabled through the $DOCKER_CONTENT_TRUST environment variable.
+func getDefaultTrustState() bool {
+ var trusted bool
+ if e := os.Getenv("DOCKER_CONTENT_TRUST"); e != "" {
+ if t, err := strconv.ParseBool(e); t || err != nil {
+ // treat any other value as true
+ trusted = true
+ }
+ }
+ return trusted
+}
+
+// IsTrusted returns true if content trust is enabled, either through the $DOCKER_CONTENT_TRUST environment variable,
+// or through `--disabled-content-trust=false` on a command.
+func IsTrusted() bool {
+ return !untrusted
+}
diff --git a/vendor/github.com/docker/cli/cli/command/utils.go b/vendor/github.com/docker/cli/cli/command/utils.go
new file mode 100644
index 0000000..3f4acaa
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/utils.go
@@ -0,0 +1,119 @@
+package command
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+
+ "github.com/docker/docker/api/types/filters"
+ "github.com/docker/docker/pkg/system"
+)
+
+// CopyToFile writes the content of the reader to the specified file
+func CopyToFile(outfile string, r io.Reader) error {
+ // We use sequential file access here to avoid depleting the standby list
+ // on Windows. On Linux, this is a call directly to ioutil.TempFile
+ tmpFile, err := system.TempFileSequential(filepath.Dir(outfile), ".docker_temp_")
+ if err != nil {
+ return err
+ }
+
+ tmpPath := tmpFile.Name()
+
+ _, err = io.Copy(tmpFile, r)
+ tmpFile.Close()
+
+ if err != nil {
+ os.Remove(tmpPath)
+ return err
+ }
+
+ if err = os.Rename(tmpPath, outfile); err != nil {
+ os.Remove(tmpPath)
+ return err
+ }
+
+ return nil
+}
+
+// capitalizeFirst capitalizes the first character of string
+func capitalizeFirst(s string) string {
+ switch l := len(s); l {
+ case 0:
+ return s
+ case 1:
+ return strings.ToLower(s)
+ default:
+ return strings.ToUpper(string(s[0])) + strings.ToLower(s[1:])
+ }
+}
+
+// PrettyPrint outputs arbitrary data for human formatted output by uppercasing the first letter.
+func PrettyPrint(i interface{}) string {
+ switch t := i.(type) {
+ case nil:
+ return "None"
+ case string:
+ return capitalizeFirst(t)
+ default:
+ return capitalizeFirst(fmt.Sprintf("%s", t))
+ }
+}
+
+// PromptForConfirmation requests and checks confirmation from user.
+// This will display the provided message followed by ' [y/N] '. If
+// the user input 'y' or 'Y' it returns true other false. If no
+// message is provided "Are you sure you want to proceed? [y/N] "
+// will be used instead.
+func PromptForConfirmation(ins io.Reader, outs io.Writer, message string) bool {
+ if message == "" {
+ message = "Are you sure you want to proceed?"
+ }
+ message += " [y/N] "
+
+ fmt.Fprintf(outs, message)
+
+ // On Windows, force the use of the regular OS stdin stream.
+ if runtime.GOOS == "windows" {
+ ins = NewInStream(os.Stdin)
+ }
+
+ reader := bufio.NewReader(ins)
+ answer, _, _ := reader.ReadLine()
+ return strings.ToLower(string(answer)) == "y"
+}
+
+// PruneFilters returns consolidated prune filters obtained from config.json and cli
+func PruneFilters(dockerCli Cli, pruneFilters filters.Args) filters.Args {
+ if dockerCli.ConfigFile() == nil {
+ return pruneFilters
+ }
+ for _, f := range dockerCli.ConfigFile().PruneFilters {
+ parts := strings.SplitN(f, "=", 2)
+ if len(parts) != 2 {
+ continue
+ }
+ if parts[0] == "label" {
+ // CLI label filter supersede config.json.
+ // If CLI label filter conflict with config.json,
+ // skip adding label! filter in config.json.
+ if pruneFilters.Include("label!") && pruneFilters.ExactMatch("label!", parts[1]) {
+ continue
+ }
+ } else if parts[0] == "label!" {
+ // CLI label! filter supersede config.json.
+ // If CLI label! filter conflict with config.json,
+ // skip adding label filter in config.json.
+ if pruneFilters.Include("label") && pruneFilters.ExactMatch("label", parts[1]) {
+ continue
+ }
+ }
+ pruneFilters.Add(parts[0], parts[1])
+ }
+
+ return pruneFilters
+}
diff --git a/vendor/github.com/docker/cli/cli/command/volume/cmd.go b/vendor/github.com/docker/cli/cli/command/volume/cmd.go
new file mode 100644
index 0000000..cf6e61d
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/volume/cmd.go
@@ -0,0 +1,26 @@
+package volume
+
+import (
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/spf13/cobra"
+)
+
+// NewVolumeCommand returns a cobra command for `volume` subcommands
+func NewVolumeCommand(dockerCli command.Cli) *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "volume COMMAND",
+ Short: "Manage volumes",
+ Args: cli.NoArgs,
+ RunE: command.ShowHelp(dockerCli.Err()),
+ Tags: map[string]string{"version": "1.21"},
+ }
+ cmd.AddCommand(
+ newCreateCommand(dockerCli),
+ newInspectCommand(dockerCli),
+ newListCommand(dockerCli),
+ newRemoveCommand(dockerCli),
+ NewPruneCommand(dockerCli),
+ )
+ return cmd
+}
diff --git a/vendor/github.com/docker/cli/cli/command/volume/create.go b/vendor/github.com/docker/cli/cli/command/volume/create.go
new file mode 100644
index 0000000..5a10922
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/volume/create.go
@@ -0,0 +1,69 @@
+package volume
+
+import (
+ "fmt"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ volumetypes "github.com/docker/docker/api/types/volume"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type createOptions struct {
+ name string
+ driver string
+ driverOpts opts.MapOpts
+ labels opts.ListOpts
+}
+
+func newCreateCommand(dockerCli command.Cli) *cobra.Command {
+ options := createOptions{
+ driverOpts: *opts.NewMapOpts(nil, nil),
+ labels: opts.NewListOpts(opts.ValidateEnv),
+ }
+
+ cmd := &cobra.Command{
+ Use: "create [OPTIONS] [VOLUME]",
+ Short: "Create a volume",
+ Args: cli.RequiresMaxArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if len(args) == 1 {
+ if options.name != "" {
+ return errors.Errorf("Conflicting options: either specify --name or provide positional arg, not both\n")
+ }
+ options.name = args[0]
+ }
+ return runCreate(dockerCli, options)
+ },
+ }
+ flags := cmd.Flags()
+ flags.StringVarP(&options.driver, "driver", "d", "local", "Specify volume driver name")
+ flags.StringVar(&options.name, "name", "", "Specify volume name")
+ flags.Lookup("name").Hidden = true
+ flags.VarP(&options.driverOpts, "opt", "o", "Set driver specific options")
+ flags.Var(&options.labels, "label", "Set metadata for a volume")
+
+ return cmd
+}
+
+func runCreate(dockerCli command.Cli, options createOptions) error {
+ client := dockerCli.Client()
+
+ volReq := volumetypes.VolumesCreateBody{
+ Driver: options.driver,
+ DriverOpts: options.driverOpts.GetAll(),
+ Name: options.name,
+ Labels: opts.ConvertKVStringsToMap(options.labels.GetAll()),
+ }
+
+ vol, err := client.VolumeCreate(context.Background(), volReq)
+ if err != nil {
+ return err
+ }
+
+ fmt.Fprintf(dockerCli.Out(), "%s\n", vol.Name)
+ return nil
+}
diff --git a/vendor/github.com/docker/cli/cli/command/volume/inspect.go b/vendor/github.com/docker/cli/cli/command/volume/inspect.go
new file mode 100644
index 0000000..b8729e2
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/volume/inspect.go
@@ -0,0 +1,45 @@
+package volume
+
+import (
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/inspect"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type inspectOptions struct {
+ format string
+ names []string
+}
+
+func newInspectCommand(dockerCli command.Cli) *cobra.Command {
+ var opts inspectOptions
+
+ cmd := &cobra.Command{
+ Use: "inspect [OPTIONS] VOLUME [VOLUME...]",
+ Short: "Display detailed information on one or more volumes",
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.names = args
+ return runInspect(dockerCli, opts)
+ },
+ }
+
+ cmd.Flags().StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template")
+
+ return cmd
+}
+
+func runInspect(dockerCli command.Cli, opts inspectOptions) error {
+ client := dockerCli.Client()
+
+ ctx := context.Background()
+
+ getVolFunc := func(name string) (interface{}, []byte, error) {
+ i, err := client.VolumeInspect(ctx, name)
+ return i, nil, err
+ }
+
+ return inspect.Inspect(dockerCli.Out(), opts.names, opts.format, getVolFunc)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/volume/list.go b/vendor/github.com/docker/cli/cli/command/volume/list.go
new file mode 100644
index 0000000..d9b5ef8
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/volume/list.go
@@ -0,0 +1,73 @@
+package volume
+
+import (
+ "sort"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/formatter"
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type byVolumeName []*types.Volume
+
+func (r byVolumeName) Len() int { return len(r) }
+func (r byVolumeName) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
+func (r byVolumeName) Less(i, j int) bool {
+ return r[i].Name < r[j].Name
+}
+
+type listOptions struct {
+ quiet bool
+ format string
+ filter opts.FilterOpt
+}
+
+func newListCommand(dockerCli command.Cli) *cobra.Command {
+ options := listOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "ls [OPTIONS]",
+ Aliases: []string{"list"},
+ Short: "List volumes",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runList(dockerCli, options)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only display volume names")
+ flags.StringVar(&options.format, "format", "", "Pretty-print volumes using a Go template")
+ flags.VarP(&options.filter, "filter", "f", "Provide filter values (e.g. 'dangling=true')")
+
+ return cmd
+}
+
+func runList(dockerCli command.Cli, options listOptions) error {
+ client := dockerCli.Client()
+ volumes, err := client.VolumeList(context.Background(), options.filter.Value())
+ if err != nil {
+ return err
+ }
+
+ format := options.format
+ if len(format) == 0 {
+ if len(dockerCli.ConfigFile().VolumesFormat) > 0 && !options.quiet {
+ format = dockerCli.ConfigFile().VolumesFormat
+ } else {
+ format = formatter.TableFormatKey
+ }
+ }
+
+ sort.Sort(byVolumeName(volumes.Volumes))
+
+ volumeCtx := formatter.Context{
+ Output: dockerCli.Out(),
+ Format: formatter.NewVolumeFormat(format, options.quiet),
+ }
+ return formatter.VolumeWrite(volumeCtx, volumes.Volumes)
+}
diff --git a/vendor/github.com/docker/cli/cli/command/volume/prune.go b/vendor/github.com/docker/cli/cli/command/volume/prune.go
new file mode 100644
index 0000000..157f883
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/volume/prune.go
@@ -0,0 +1,78 @@
+package volume
+
+import (
+ "fmt"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/opts"
+ units "github.com/docker/go-units"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type pruneOptions struct {
+ force bool
+ filter opts.FilterOpt
+}
+
+// NewPruneCommand returns a new cobra prune command for volumes
+func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
+ options := pruneOptions{filter: opts.NewFilterOpt()}
+
+ cmd := &cobra.Command{
+ Use: "prune [OPTIONS]",
+ Short: "Remove all unused volumes",
+ Args: cli.NoArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ spaceReclaimed, output, err := runPrune(dockerCli, options)
+ if err != nil {
+ return err
+ }
+ if output != "" {
+ fmt.Fprintln(dockerCli.Out(), output)
+ }
+ fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
+ return nil
+ },
+ Tags: map[string]string{"version": "1.25"},
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&options.force, "force", "f", false, "Do not prompt for confirmation")
+ flags.Var(&options.filter, "filter", "Provide filter values (e.g. 'label=<label>')")
+
+ return cmd
+}
+
+const warning = `WARNING! This will remove all volumes not used by at least one container.
+Are you sure you want to continue?`
+
+func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) {
+ pruneFilters := command.PruneFilters(dockerCli, options.filter.Value())
+
+ if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
+ return
+ }
+
+ report, err := dockerCli.Client().VolumesPrune(context.Background(), pruneFilters)
+ if err != nil {
+ return
+ }
+
+ if len(report.VolumesDeleted) > 0 {
+ output = "Deleted Volumes:\n"
+ for _, id := range report.VolumesDeleted {
+ output += id + "\n"
+ }
+ spaceReclaimed = report.SpaceReclaimed
+ }
+
+ return
+}
+
+// RunPrune calls the Volume Prune API
+// This returns the amount of space reclaimed and a detailed output string
+func RunPrune(dockerCli command.Cli, filter opts.FilterOpt) (uint64, string, error) {
+ return runPrune(dockerCli, pruneOptions{force: true, filter: filter})
+}
diff --git a/vendor/github.com/docker/cli/cli/command/volume/remove.go b/vendor/github.com/docker/cli/cli/command/volume/remove.go
new file mode 100644
index 0000000..b9d455d
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/command/volume/remove.go
@@ -0,0 +1,69 @@
+package volume
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/net/context"
+)
+
+type removeOptions struct {
+ force bool
+
+ volumes []string
+}
+
+func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
+ var opts removeOptions
+
+ cmd := &cobra.Command{
+ Use: "rm [OPTIONS] VOLUME [VOLUME...]",
+ Aliases: []string{"remove"},
+ Short: "Remove one or more volumes",
+ Long: removeDescription,
+ Example: removeExample,
+ Args: cli.RequiresMinArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ opts.volumes = args
+ return runRemove(dockerCli, &opts)
+ },
+ }
+
+ flags := cmd.Flags()
+ flags.BoolVarP(&opts.force, "force", "f", false, "Force the removal of one or more volumes")
+ flags.SetAnnotation("force", "version", []string{"1.25"})
+ return cmd
+}
+
+func runRemove(dockerCli command.Cli, opts *removeOptions) error {
+ client := dockerCli.Client()
+ ctx := context.Background()
+
+ var errs []string
+
+ for _, name := range opts.volumes {
+ if err := client.VolumeRemove(ctx, name, opts.force); err != nil {
+ errs = append(errs, err.Error())
+ continue
+ }
+ fmt.Fprintf(dockerCli.Out(), "%s\n", name)
+ }
+
+ if len(errs) > 0 {
+ return errors.Errorf("%s", strings.Join(errs, "\n"))
+ }
+ return nil
+}
+
+var removeDescription = `
+Remove one or more volumes. You cannot remove a volume that is in use by a container.
+`
+
+var removeExample = `
+$ docker volume rm hello
+hello
+`
diff --git a/vendor/github.com/docker/cli/cli/compose/interpolation/interpolation.go b/vendor/github.com/docker/cli/cli/compose/interpolation/interpolation.go
new file mode 100644
index 0000000..38673c5
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/compose/interpolation/interpolation.go
@@ -0,0 +1,96 @@
+package interpolation
+
+import (
+ "github.com/docker/cli/cli/compose/template"
+ "github.com/pkg/errors"
+)
+
+// Interpolate replaces variables in a string with the values from a mapping
+func Interpolate(config map[string]interface{}, section string, mapping template.Mapping) (map[string]interface{}, error) {
+ out := map[string]interface{}{}
+
+ for name, item := range config {
+ if item == nil {
+ out[name] = nil
+ continue
+ }
+ mapItem, ok := item.(map[string]interface{})
+ if !ok {
+ return nil, errors.Errorf("Invalid type for %s : %T instead of %T", name, item, out)
+ }
+ interpolatedItem, err := interpolateSectionItem(name, mapItem, section, mapping)
+ if err != nil {
+ return nil, err
+ }
+ out[name] = interpolatedItem
+ }
+
+ return out, nil
+}
+
+func interpolateSectionItem(
+ name string,
+ item map[string]interface{},
+ section string,
+ mapping template.Mapping,
+) (map[string]interface{}, error) {
+
+ out := map[string]interface{}{}
+
+ for key, value := range item {
+ interpolatedValue, err := recursiveInterpolate(value, mapping)
+ switch err := err.(type) {
+ case nil:
+ case *template.InvalidTemplateError:
+ return nil, errors.Errorf(
+ "Invalid interpolation format for %#v option in %s %#v: %#v. You may need to escape any $ with another $.",
+ key, section, name, err.Template,
+ )
+ default:
+ return nil, errors.Wrapf(err, "error while interpolating %s in %s %s", key, section, name)
+ }
+ out[key] = interpolatedValue
+ }
+
+ return out, nil
+
+}
+
+func recursiveInterpolate(
+ value interface{},
+ mapping template.Mapping,
+) (interface{}, error) {
+
+ switch value := value.(type) {
+
+ case string:
+ return template.Substitute(value, mapping)
+
+ case map[string]interface{}:
+ out := map[string]interface{}{}
+ for key, elem := range value {
+ interpolatedElem, err := recursiveInterpolate(elem, mapping)
+ if err != nil {
+ return nil, err
+ }
+ out[key] = interpolatedElem
+ }
+ return out, nil
+
+ case []interface{}:
+ out := make([]interface{}, len(value))
+ for i, elem := range value {
+ interpolatedElem, err := recursiveInterpolate(elem, mapping)
+ if err != nil {
+ return nil, err
+ }
+ out[i] = interpolatedElem
+ }
+ return out, nil
+
+ default:
+ return value, nil
+
+ }
+
+}
diff --git a/vendor/github.com/docker/cli/cli/compose/loader/loader.go b/vendor/github.com/docker/cli/cli/compose/loader/loader.go
new file mode 100644
index 0000000..b456e18
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/compose/loader/loader.go
@@ -0,0 +1,714 @@
+package loader
+
+import (
+ "fmt"
+ "path"
+ "path/filepath"
+ "reflect"
+ "sort"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli/compose/interpolation"
+ "github.com/docker/cli/cli/compose/schema"
+ "github.com/docker/cli/cli/compose/template"
+ "github.com/docker/cli/cli/compose/types"
+ "github.com/docker/cli/opts"
+ "github.com/docker/go-connections/nat"
+ units "github.com/docker/go-units"
+ shellwords "github.com/mattn/go-shellwords"
+ "github.com/mitchellh/mapstructure"
+ "github.com/pkg/errors"
+ yaml "gopkg.in/yaml.v2"
+)
+
+// ParseYAML reads the bytes from a file, parses the bytes into a mapping
+// structure, and returns it.
+func ParseYAML(source []byte) (map[string]interface{}, error) {
+ var cfg interface{}
+ if err := yaml.Unmarshal(source, &cfg); err != nil {
+ return nil, err
+ }
+ cfgMap, ok := cfg.(map[interface{}]interface{})
+ if !ok {
+ return nil, errors.Errorf("Top-level object must be a mapping")
+ }
+ converted, err := convertToStringKeysRecursive(cfgMap, "")
+ if err != nil {
+ return nil, err
+ }
+ return converted.(map[string]interface{}), nil
+}
+
+// Load reads a ConfigDetails and returns a fully loaded configuration
+func Load(configDetails types.ConfigDetails) (*types.Config, error) {
+ if len(configDetails.ConfigFiles) < 1 {
+ return nil, errors.Errorf("No files specified")
+ }
+ if len(configDetails.ConfigFiles) > 1 {
+ return nil, errors.Errorf("Multiple files are not yet supported")
+ }
+
+ configDict := getConfigDict(configDetails)
+
+ if services, ok := configDict["services"]; ok {
+ if servicesDict, ok := services.(map[string]interface{}); ok {
+ forbidden := getProperties(servicesDict, types.ForbiddenProperties)
+
+ if len(forbidden) > 0 {
+ return nil, &ForbiddenPropertiesError{Properties: forbidden}
+ }
+ }
+ }
+
+ if err := schema.Validate(configDict, schema.Version(configDict)); err != nil {
+ return nil, err
+ }
+
+ cfg := types.Config{}
+
+ config, err := interpolateConfig(configDict, configDetails.LookupEnv)
+ if err != nil {
+ return nil, err
+ }
+
+ cfg.Services, err = LoadServices(config["services"], configDetails.WorkingDir, configDetails.LookupEnv)
+ if err != nil {
+ return nil, err
+ }
+
+ cfg.Networks, err = LoadNetworks(config["networks"])
+ if err != nil {
+ return nil, err
+ }
+
+ cfg.Volumes, err = LoadVolumes(config["volumes"])
+ if err != nil {
+ return nil, err
+ }
+
+ cfg.Secrets, err = LoadSecrets(config["secrets"], configDetails.WorkingDir)
+ if err != nil {
+ return nil, err
+ }
+
+ cfg.Configs, err = LoadConfigObjs(config["configs"], configDetails.WorkingDir)
+ if err != nil {
+ return nil, err
+ }
+
+ return &cfg, nil
+}
+
+func interpolateConfig(configDict map[string]interface{}, lookupEnv template.Mapping) (map[string]map[string]interface{}, error) {
+ config := make(map[string]map[string]interface{})
+
+ for _, key := range []string{"services", "networks", "volumes", "secrets", "configs"} {
+ section, ok := configDict[key]
+ if !ok {
+ config[key] = make(map[string]interface{})
+ continue
+ }
+ var err error
+ config[key], err = interpolation.Interpolate(section.(map[string]interface{}), key, lookupEnv)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return config, nil
+}
+
+// GetUnsupportedProperties returns the list of any unsupported properties that are
+// used in the Compose files.
+func GetUnsupportedProperties(configDetails types.ConfigDetails) []string {
+ unsupported := map[string]bool{}
+
+ for _, service := range getServices(getConfigDict(configDetails)) {
+ serviceDict := service.(map[string]interface{})
+ for _, property := range types.UnsupportedProperties {
+ if _, isSet := serviceDict[property]; isSet {
+ unsupported[property] = true
+ }
+ }
+ }
+
+ return sortedKeys(unsupported)
+}
+
+func sortedKeys(set map[string]bool) []string {
+ var keys []string
+ for key := range set {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ return keys
+}
+
+// GetDeprecatedProperties returns the list of any deprecated properties that
+// are used in the compose files.
+func GetDeprecatedProperties(configDetails types.ConfigDetails) map[string]string {
+ return getProperties(getServices(getConfigDict(configDetails)), types.DeprecatedProperties)
+}
+
+func getProperties(services map[string]interface{}, propertyMap map[string]string) map[string]string {
+ output := map[string]string{}
+
+ for _, service := range services {
+ if serviceDict, ok := service.(map[string]interface{}); ok {
+ for property, description := range propertyMap {
+ if _, isSet := serviceDict[property]; isSet {
+ output[property] = description
+ }
+ }
+ }
+ }
+
+ return output
+}
+
+// ForbiddenPropertiesError is returned when there are properties in the Compose
+// file that are forbidden.
+type ForbiddenPropertiesError struct {
+ Properties map[string]string
+}
+
+func (e *ForbiddenPropertiesError) Error() string {
+ return "Configuration contains forbidden properties"
+}
+
+// TODO: resolve multiple files into a single config
+func getConfigDict(configDetails types.ConfigDetails) map[string]interface{} {
+ return configDetails.ConfigFiles[0].Config
+}
+
+func getServices(configDict map[string]interface{}) map[string]interface{} {
+ if services, ok := configDict["services"]; ok {
+ if servicesDict, ok := services.(map[string]interface{}); ok {
+ return servicesDict
+ }
+ }
+
+ return map[string]interface{}{}
+}
+
+func transform(source map[string]interface{}, target interface{}) error {
+ data := mapstructure.Metadata{}
+ config := &mapstructure.DecoderConfig{
+ DecodeHook: mapstructure.ComposeDecodeHookFunc(
+ createTransformHook(),
+ mapstructure.StringToTimeDurationHookFunc()),
+ Result: target,
+ Metadata: &data,
+ }
+ decoder, err := mapstructure.NewDecoder(config)
+ if err != nil {
+ return err
+ }
+ return decoder.Decode(source)
+}
+
+func createTransformHook() mapstructure.DecodeHookFuncType {
+ transforms := map[reflect.Type]func(interface{}) (interface{}, error){
+ reflect.TypeOf(types.External{}): transformExternal,
+ reflect.TypeOf(types.HealthCheckTest{}): transformHealthCheckTest,
+ reflect.TypeOf(types.ShellCommand{}): transformShellCommand,
+ reflect.TypeOf(types.StringList{}): transformStringList,
+ reflect.TypeOf(map[string]string{}): transformMapStringString,
+ reflect.TypeOf(types.UlimitsConfig{}): transformUlimits,
+ reflect.TypeOf(types.UnitBytes(0)): transformSize,
+ reflect.TypeOf([]types.ServicePortConfig{}): transformServicePort,
+ reflect.TypeOf(types.ServiceSecretConfig{}): transformStringSourceMap,
+ reflect.TypeOf(types.ServiceConfigObjConfig{}): transformStringSourceMap,
+ reflect.TypeOf(types.StringOrNumberList{}): transformStringOrNumberList,
+ reflect.TypeOf(map[string]*types.ServiceNetworkConfig{}): transformServiceNetworkMap,
+ reflect.TypeOf(types.MappingWithEquals{}): transformMappingOrListFunc("=", true),
+ reflect.TypeOf(types.Labels{}): transformMappingOrListFunc("=", false),
+ reflect.TypeOf(types.MappingWithColon{}): transformMappingOrListFunc(":", false),
+ reflect.TypeOf(types.ServiceVolumeConfig{}): transformServiceVolumeConfig,
+ }
+
+ return func(_ reflect.Type, target reflect.Type, data interface{}) (interface{}, error) {
+ transform, ok := transforms[target]
+ if !ok {
+ return data, nil
+ }
+ return transform(data)
+ }
+}
+
+// keys needs to be converted to strings for jsonschema
+func convertToStringKeysRecursive(value interface{}, keyPrefix string) (interface{}, error) {
+ if mapping, ok := value.(map[interface{}]interface{}); ok {
+ dict := make(map[string]interface{})
+ for key, entry := range mapping {
+ str, ok := key.(string)
+ if !ok {
+ return nil, formatInvalidKeyError(keyPrefix, key)
+ }
+ var newKeyPrefix string
+ if keyPrefix == "" {
+ newKeyPrefix = str
+ } else {
+ newKeyPrefix = fmt.Sprintf("%s.%s", keyPrefix, str)
+ }
+ convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix)
+ if err != nil {
+ return nil, err
+ }
+ dict[str] = convertedEntry
+ }
+ return dict, nil
+ }
+ if list, ok := value.([]interface{}); ok {
+ var convertedList []interface{}
+ for index, entry := range list {
+ newKeyPrefix := fmt.Sprintf("%s[%d]", keyPrefix, index)
+ convertedEntry, err := convertToStringKeysRecursive(entry, newKeyPrefix)
+ if err != nil {
+ return nil, err
+ }
+ convertedList = append(convertedList, convertedEntry)
+ }
+ return convertedList, nil
+ }
+ return value, nil
+}
+
+func formatInvalidKeyError(keyPrefix string, key interface{}) error {
+ var location string
+ if keyPrefix == "" {
+ location = "at top level"
+ } else {
+ location = fmt.Sprintf("in %s", keyPrefix)
+ }
+ return errors.Errorf("Non-string key %s: %#v", location, key)
+}
+
+// LoadServices produces a ServiceConfig map from a compose file Dict
+// the servicesDict is not validated if directly used. Use Load() to enable validation
+func LoadServices(servicesDict map[string]interface{}, workingDir string, lookupEnv template.Mapping) ([]types.ServiceConfig, error) {
+ var services []types.ServiceConfig
+
+ for name, serviceDef := range servicesDict {
+ serviceConfig, err := LoadService(name, serviceDef.(map[string]interface{}), workingDir, lookupEnv)
+ if err != nil {
+ return nil, err
+ }
+ services = append(services, *serviceConfig)
+ }
+
+ return services, nil
+}
+
+// LoadService produces a single ServiceConfig from a compose file Dict
+// the serviceDict is not validated if directly used. Use Load() to enable validation
+func LoadService(name string, serviceDict map[string]interface{}, workingDir string, lookupEnv template.Mapping) (*types.ServiceConfig, error) {
+ serviceConfig := &types.ServiceConfig{}
+ if err := transform(serviceDict, serviceConfig); err != nil {
+ return nil, err
+ }
+ serviceConfig.Name = name
+
+ if err := resolveEnvironment(serviceConfig, workingDir, lookupEnv); err != nil {
+ return nil, err
+ }
+
+ resolveVolumePaths(serviceConfig.Volumes, workingDir, lookupEnv)
+ return serviceConfig, nil
+}
+
+func updateEnvironment(environment map[string]*string, vars map[string]*string, lookupEnv template.Mapping) {
+ for k, v := range vars {
+ interpolatedV, ok := lookupEnv(k)
+ if (v == nil || *v == "") && ok {
+ // lookupEnv is prioritized over vars
+ environment[k] = &interpolatedV
+ } else {
+ environment[k] = v
+ }
+ }
+}
+
+func resolveEnvironment(serviceConfig *types.ServiceConfig, workingDir string, lookupEnv template.Mapping) error {
+ environment := make(map[string]*string)
+
+ if len(serviceConfig.EnvFile) > 0 {
+ var envVars []string
+
+ for _, file := range serviceConfig.EnvFile {
+ filePath := absPath(workingDir, file)
+ fileVars, err := opts.ParseEnvFile(filePath)
+ if err != nil {
+ return err
+ }
+ envVars = append(envVars, fileVars...)
+ }
+ updateEnvironment(environment,
+ opts.ConvertKVStringsToMapWithNil(envVars), lookupEnv)
+ }
+
+ updateEnvironment(environment, serviceConfig.Environment, lookupEnv)
+ serviceConfig.Environment = environment
+ return nil
+}
+
+func resolveVolumePaths(volumes []types.ServiceVolumeConfig, workingDir string, lookupEnv template.Mapping) {
+ for i, volume := range volumes {
+ if volume.Type != "bind" {
+ continue
+ }
+
+ filePath := expandUser(volume.Source, lookupEnv)
+ // Check for a Unix absolute path first, to handle a Windows client
+ // with a Unix daemon. This handles a Windows client connecting to a
+ // Unix daemon. Note that this is not required for Docker for Windows
+ // when specifying a local Windows path, because Docker for Windows
+ // translates the Windows path into a valid path within the VM.
+ if !path.IsAbs(filePath) {
+ filePath = absPath(workingDir, filePath)
+ }
+ volume.Source = filePath
+ volumes[i] = volume
+ }
+}
+
+// TODO: make this more robust
+func expandUser(path string, lookupEnv template.Mapping) string {
+ if strings.HasPrefix(path, "~") {
+ home, ok := lookupEnv("HOME")
+ if !ok {
+ logrus.Warn("cannot expand '~', because the environment lacks HOME")
+ return path
+ }
+ return strings.Replace(path, "~", home, 1)
+ }
+ return path
+}
+
+func transformUlimits(data interface{}) (interface{}, error) {
+ switch value := data.(type) {
+ case int:
+ return types.UlimitsConfig{Single: value}, nil
+ case map[string]interface{}:
+ ulimit := types.UlimitsConfig{}
+ ulimit.Soft = value["soft"].(int)
+ ulimit.Hard = value["hard"].(int)
+ return ulimit, nil
+ default:
+ return data, errors.Errorf("invalid type %T for ulimits", value)
+ }
+}
+
+// LoadNetworks produces a NetworkConfig map from a compose file Dict
+// the source Dict is not validated if directly used. Use Load() to enable validation
+func LoadNetworks(source map[string]interface{}) (map[string]types.NetworkConfig, error) {
+ networks := make(map[string]types.NetworkConfig)
+ err := transform(source, &networks)
+ if err != nil {
+ return networks, err
+ }
+ for name, network := range networks {
+ if network.External.External && network.External.Name == "" {
+ network.External.Name = name
+ networks[name] = network
+ }
+ }
+ return networks, nil
+}
+
+func externalVolumeError(volume, key string) error {
+ return errors.Errorf(
+ "conflicting parameters \"external\" and %q specified for volume %q",
+ key, volume)
+}
+
+// LoadVolumes produces a VolumeConfig map from a compose file Dict
+// the source Dict is not validated if directly used. Use Load() to enable validation
+func LoadVolumes(source map[string]interface{}) (map[string]types.VolumeConfig, error) {
+ volumes := make(map[string]types.VolumeConfig)
+ err := transform(source, &volumes)
+ if err != nil {
+ return volumes, err
+ }
+ for name, volume := range volumes {
+ if volume.External.External {
+ if volume.Driver != "" {
+ return nil, externalVolumeError(name, "driver")
+ }
+ if len(volume.DriverOpts) > 0 {
+ return nil, externalVolumeError(name, "driver_opts")
+ }
+ if len(volume.Labels) > 0 {
+ return nil, externalVolumeError(name, "labels")
+ }
+ if volume.External.Name == "" {
+ volume.External.Name = name
+ volumes[name] = volume
+ }
+ }
+ }
+ return volumes, nil
+}
+
+// LoadSecrets produces a SecretConfig map from a compose file Dict
+// the source Dict is not validated if directly used. Use Load() to enable validation
+func LoadSecrets(source map[string]interface{}, workingDir string) (map[string]types.SecretConfig, error) {
+ secrets := make(map[string]types.SecretConfig)
+ if err := transform(source, &secrets); err != nil {
+ return secrets, err
+ }
+ for name, secret := range secrets {
+ if secret.External.External && secret.External.Name == "" {
+ secret.External.Name = name
+ secrets[name] = secret
+ }
+ if secret.File != "" {
+ secret.File = absPath(workingDir, secret.File)
+ }
+ }
+ return secrets, nil
+}
+
+// LoadConfigObjs produces a ConfigObjConfig map from a compose file Dict
+// the source Dict is not validated if directly used. Use Load() to enable validation
+func LoadConfigObjs(source map[string]interface{}, workingDir string) (map[string]types.ConfigObjConfig, error) {
+ configs := make(map[string]types.ConfigObjConfig)
+ if err := transform(source, &configs); err != nil {
+ return configs, err
+ }
+ for name, config := range configs {
+ if config.External.External && config.External.Name == "" {
+ config.External.Name = name
+ configs[name] = config
+ }
+ if config.File != "" {
+ config.File = absPath(workingDir, config.File)
+ }
+ }
+ return configs, nil
+}
+
+func absPath(workingDir string, filePath string) string {
+ if filepath.IsAbs(filePath) {
+ return filePath
+ }
+ return filepath.Join(workingDir, filePath)
+}
+
+func transformMapStringString(data interface{}) (interface{}, error) {
+ switch value := data.(type) {
+ case map[string]interface{}:
+ return toMapStringString(value, false), nil
+ case map[string]string:
+ return value, nil
+ default:
+ return data, errors.Errorf("invalid type %T for map[string]string", value)
+ }
+}
+
+func transformExternal(data interface{}) (interface{}, error) {
+ switch value := data.(type) {
+ case bool:
+ return map[string]interface{}{"external": value}, nil
+ case map[string]interface{}:
+ return map[string]interface{}{"external": true, "name": value["name"]}, nil
+ default:
+ return data, errors.Errorf("invalid type %T for external", value)
+ }
+}
+
+func transformServicePort(data interface{}) (interface{}, error) {
+ switch entries := data.(type) {
+ case []interface{}:
+ // We process the list instead of individual items here.
+ // The reason is that one entry might be mapped to multiple ServicePortConfig.
+ // Therefore we take an input of a list and return an output of a list.
+ ports := []interface{}{}
+ for _, entry := range entries {
+ switch value := entry.(type) {
+ case int:
+ v, err := toServicePortConfigs(fmt.Sprint(value))
+ if err != nil {
+ return data, err
+ }
+ ports = append(ports, v...)
+ case string:
+ v, err := toServicePortConfigs(value)
+ if err != nil {
+ return data, err
+ }
+ ports = append(ports, v...)
+ case map[string]interface{}:
+ ports = append(ports, value)
+ default:
+ return data, errors.Errorf("invalid type %T for port", value)
+ }
+ }
+ return ports, nil
+ default:
+ return data, errors.Errorf("invalid type %T for port", entries)
+ }
+}
+
+func transformStringSourceMap(data interface{}) (interface{}, error) {
+ switch value := data.(type) {
+ case string:
+ return map[string]interface{}{"source": value}, nil
+ case map[string]interface{}:
+ return data, nil
+ default:
+ return data, errors.Errorf("invalid type %T for secret", value)
+ }
+}
+
+func transformServiceVolumeConfig(data interface{}) (interface{}, error) {
+ switch value := data.(type) {
+ case string:
+ return ParseVolume(value)
+ case map[string]interface{}:
+ return data, nil
+ default:
+ return data, errors.Errorf("invalid type %T for service volume", value)
+ }
+
+}
+
+func transformServiceNetworkMap(value interface{}) (interface{}, error) {
+ if list, ok := value.([]interface{}); ok {
+ mapValue := map[interface{}]interface{}{}
+ for _, name := range list {
+ mapValue[name] = nil
+ }
+ return mapValue, nil
+ }
+ return value, nil
+}
+
+func transformStringOrNumberList(value interface{}) (interface{}, error) {
+ list := value.([]interface{})
+ result := make([]string, len(list))
+ for i, item := range list {
+ result[i] = fmt.Sprint(item)
+ }
+ return result, nil
+}
+
+func transformStringList(data interface{}) (interface{}, error) {
+ switch value := data.(type) {
+ case string:
+ return []string{value}, nil
+ case []interface{}:
+ return value, nil
+ default:
+ return data, errors.Errorf("invalid type %T for string list", value)
+ }
+}
+
+func transformMappingOrListFunc(sep string, allowNil bool) func(interface{}) (interface{}, error) {
+ return func(data interface{}) (interface{}, error) {
+ return transformMappingOrList(data, sep, allowNil), nil
+ }
+}
+
+func transformMappingOrList(mappingOrList interface{}, sep string, allowNil bool) interface{} {
+ switch value := mappingOrList.(type) {
+ case map[string]interface{}:
+ return toMapStringString(value, allowNil)
+ case ([]interface{}):
+ result := make(map[string]interface{})
+ for _, value := range value {
+ parts := strings.SplitN(value.(string), sep, 2)
+ key := parts[0]
+ switch {
+ case len(parts) == 1 && allowNil:
+ result[key] = nil
+ case len(parts) == 1 && !allowNil:
+ result[key] = ""
+ default:
+ result[key] = parts[1]
+ }
+ }
+ return result
+ }
+ panic(errors.Errorf("expected a map or a list, got %T: %#v", mappingOrList, mappingOrList))
+}
+
+func transformShellCommand(value interface{}) (interface{}, error) {
+ if str, ok := value.(string); ok {
+ return shellwords.Parse(str)
+ }
+ return value, nil
+}
+
+func transformHealthCheckTest(data interface{}) (interface{}, error) {
+ switch value := data.(type) {
+ case string:
+ return append([]string{"CMD-SHELL"}, value), nil
+ case []interface{}:
+ return value, nil
+ default:
+ return value, errors.Errorf("invalid type %T for healthcheck.test", value)
+ }
+}
+
+func transformSize(value interface{}) (interface{}, error) {
+ switch value := value.(type) {
+ case int:
+ return int64(value), nil
+ case string:
+ return units.RAMInBytes(value)
+ }
+ panic(errors.Errorf("invalid type for size %T", value))
+}
+
+func toServicePortConfigs(value string) ([]interface{}, error) {
+ var portConfigs []interface{}
+
+ ports, portBindings, err := nat.ParsePortSpecs([]string{value})
+ if err != nil {
+ return nil, err
+ }
+ // We need to sort the key of the ports to make sure it is consistent
+ keys := []string{}
+ for port := range ports {
+ keys = append(keys, string(port))
+ }
+ sort.Strings(keys)
+
+ for _, key := range keys {
+ // Reuse ConvertPortToPortConfig so that it is consistent
+ portConfig, err := opts.ConvertPortToPortConfig(nat.Port(key), portBindings)
+ if err != nil {
+ return nil, err
+ }
+ for _, p := range portConfig {
+ portConfigs = append(portConfigs, types.ServicePortConfig{
+ Protocol: string(p.Protocol),
+ Target: p.TargetPort,
+ Published: p.PublishedPort,
+ Mode: string(p.PublishMode),
+ })
+ }
+ }
+
+ return portConfigs, nil
+}
+
+func toMapStringString(value map[string]interface{}, allowNil bool) map[string]interface{} {
+ output := make(map[string]interface{})
+ for key, value := range value {
+ output[key] = toString(value, allowNil)
+ }
+ return output
+}
+
+func toString(value interface{}, allowNil bool) interface{} {
+ switch {
+ case value != nil:
+ return fmt.Sprint(value)
+ case allowNil:
+ return nil
+ default:
+ return ""
+ }
+}
diff --git a/vendor/github.com/docker/cli/cli/compose/loader/volume.go b/vendor/github.com/docker/cli/cli/compose/loader/volume.go
new file mode 100644
index 0000000..b026cf1
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/compose/loader/volume.go
@@ -0,0 +1,117 @@
+package loader
+
+import (
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/docker/cli/cli/compose/types"
+ "github.com/docker/docker/api/types/mount"
+ "github.com/pkg/errors"
+)
+
+const endOfSpec = rune(0)
+
+// ParseVolume parses a volume spec without any knowledge of the target platform
+func ParseVolume(spec string) (types.ServiceVolumeConfig, error) {
+ volume := types.ServiceVolumeConfig{}
+
+ switch len(spec) {
+ case 0:
+ return volume, errors.New("invalid empty volume spec")
+ case 1, 2:
+ volume.Target = spec
+ volume.Type = string(mount.TypeVolume)
+ return volume, nil
+ }
+
+ buffer := []rune{}
+ for _, char := range spec + string(endOfSpec) {
+ switch {
+ case isWindowsDrive(buffer, char):
+ buffer = append(buffer, char)
+ case char == ':' || char == endOfSpec:
+ if err := populateFieldFromBuffer(char, buffer, &volume); err != nil {
+ populateType(&volume)
+ return volume, errors.Wrapf(err, "invalid spec: %s", spec)
+ }
+ buffer = []rune{}
+ default:
+ buffer = append(buffer, char)
+ }
+ }
+
+ populateType(&volume)
+ return volume, nil
+}
+
+func isWindowsDrive(buffer []rune, char rune) bool {
+ return char == ':' && len(buffer) == 1 && unicode.IsLetter(buffer[0])
+}
+
+func populateFieldFromBuffer(char rune, buffer []rune, volume *types.ServiceVolumeConfig) error {
+ strBuffer := string(buffer)
+ switch {
+ case len(buffer) == 0:
+ return errors.New("empty section between colons")
+ // Anonymous volume
+ case volume.Source == "" && char == endOfSpec:
+ volume.Target = strBuffer
+ return nil
+ case volume.Source == "":
+ volume.Source = strBuffer
+ return nil
+ case volume.Target == "":
+ volume.Target = strBuffer
+ return nil
+ case char == ':':
+ return errors.New("too many colons")
+ }
+ for _, option := range strings.Split(strBuffer, ",") {
+ switch option {
+ case "ro":
+ volume.ReadOnly = true
+ case "rw":
+ volume.ReadOnly = false
+ case "nocopy":
+ volume.Volume = &types.ServiceVolumeVolume{NoCopy: true}
+ default:
+ if isBindOption(option) {
+ volume.Bind = &types.ServiceVolumeBind{Propagation: option}
+ }
+ // ignore unknown options
+ }
+ }
+ return nil
+}
+
+func isBindOption(option string) bool {
+ for _, propagation := range mount.Propagations {
+ if mount.Propagation(option) == propagation {
+ return true
+ }
+ }
+ return false
+}
+
+func populateType(volume *types.ServiceVolumeConfig) {
+ switch {
+ // Anonymous volume
+ case volume.Source == "":
+ volume.Type = string(mount.TypeVolume)
+ case isFilePath(volume.Source):
+ volume.Type = string(mount.TypeBind)
+ default:
+ volume.Type = string(mount.TypeVolume)
+ }
+}
+
+func isFilePath(source string) bool {
+ switch source[0] {
+ case '.', '/', '~':
+ return true
+ }
+
+ first, nextIndex := utf8.DecodeRuneInString(source)
+ return isWindowsDrive([]rune{first}, rune(source[nextIndex]))
+}
diff --git a/vendor/github.com/docker/cli/cli/compose/schema/bindata.go b/vendor/github.com/docker/cli/cli/compose/schema/bindata.go
new file mode 100644
index 0000000..06fcae3
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/compose/schema/bindata.go
@@ -0,0 +1,306 @@
+// Code generated by go-bindata.
+// sources:
+// data/config_schema_v3.0.json
+// data/config_schema_v3.1.json
+// data/config_schema_v3.2.json
+// data/config_schema_v3.3.json
+// DO NOT EDIT!
+
+package schema
+
+import (
+ "bytes"
+ "compress/gzip"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+func bindataRead(data []byte, name string) ([]byte, error) {
+ gz, err := gzip.NewReader(bytes.NewBuffer(data))
+ if err != nil {
+ return nil, fmt.Errorf("Read %q: %v", name, err)
+ }
+
+ var buf bytes.Buffer
+ _, err = io.Copy(&buf, gz)
+ clErr := gz.Close()
+
+ if err != nil {
+ return nil, fmt.Errorf("Read %q: %v", name, err)
+ }
+ if clErr != nil {
+ return nil, err
+ }
+
+ return buf.Bytes(), nil
+}
+
+type asset struct {
+ bytes []byte
+ info os.FileInfo
+}
+
+type bindataFileInfo struct {
+ name string
+ size int64
+ mode os.FileMode
+ modTime time.Time
+}
+
+func (fi bindataFileInfo) Name() string {
+ return fi.name
+}
+func (fi bindataFileInfo) Size() int64 {
+ return fi.size
+}
+func (fi bindataFileInfo) Mode() os.FileMode {
+ return fi.mode
+}
+func (fi bindataFileInfo) ModTime() time.Time {
+ return fi.modTime
+}
+func (fi bindataFileInfo) IsDir() bool {
+ return false
+}
+func (fi bindataFileInfo) Sys() interface{} {
+ return nil
+}
+
+var _dataConfig_schema_v30Json = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xec\x5a\x4b\x8f\xdb\x38\x12\xbe\xfb\x57\x08\x4a\x6e\x71\x77\x07\xd8\x60\x81\xcd\x6d\x8f\x7b\xda\x39\x4f\x43\x11\x68\xa9\x6c\x33\x4d\x91\x4c\x91\x72\xda\x09\xfc\xdf\x07\xd4\xcb\x14\x4d\x8a\xb2\xad\x3c\x30\x98\x53\xb7\xc5\xaa\x62\xbd\xf8\x55\xb1\xa4\xef\xab\x24\x49\xdf\xaa\x62\x0f\x15\x49\x3f\x26\xe9\x5e\x6b\xf9\xf1\xe9\xe9\xb3\x12\xfc\xa1\x7d\xfa\x28\x70\xf7\x54\x22\xd9\xea\x87\xf7\x1f\x9e\xda\x67\x6f\xd2\xb5\xe1\xa3\xa5\x61\x29\x04\xdf\xd2\x5d\xde\xae\xe4\x87\x7f\x3d\xbe\x7f\x34\xec\x2d\x89\x3e\x4a\x30\x44\x62\xf3\x19\x0a\xdd\x3e\x43\xf8\x52\x53\x04\xc3\xfc\x9c\x1e\x00\x15\x15\x3c\xcd\xd6\x2b\xb3\x26\x51\x48\x40\x4d\x41\xa5\x1f\x13\xa3\x5c\x92\x0c\x24\xfd\x03\x4b\xac\xd2\x48\xf9\x2e\x6d\x1e\x9f\x1a\x09\x49\x92\x2a\xc0\x03\x2d\x2c\x09\x83\xaa\x6f\x9e\xce\xf2\x9f\x06\xb2\xb5\x2b\xd5\x52\xb6\x79\x2e\x89\xd6\x80\xfc\x8f\x4b\xdd\x9a\xe5\x4f\xcf\xe4\xe1\xdb\x7f\x1f\xfe\x7c\xff\xf0\x9f\xc7\xfc\x21\x7b\xf7\x76\xb4\x6c\xfc\x8b\xb0\x6d\xb7\x2f\x61\x4b\x39\xd5\x54\xf0\x61\xff\x74\xa0\x3c\x75\xff\x9d\x86\x8d\x49\x59\x36\xc4\x84\x8d\xf6\xde\x12\xa6\x60\x6c\x33\x07\xfd\x55\xe0\x4b\xcc\xe6\x81\xec\x17\xd9\xdc\xed\xef\xb1\x79\x6c\xce\x41\xb0\xba\x8a\x46\xb0\xa7\xfa\x45\xc6\xb4\xdb\xdf\x17\xbf\x55\x6f\xf4\x24\x6d\x4b\x61\xed\xdd\x28\x38\xca\x76\x9f\xab\x7c\xd9\x16\xf6\xd5\xe0\xac\x80\x97\x4a\x90\x4c\x1c\xcd\xb3\x80\x3f\x5a\x82\x0a\xb8\x4e\x07\x17\x24\x49\xba\xa9\x29\x2b\x5d\x8f\x0a\x0e\xff\x37\x22\x9e\xad\x87\x49\xf2\xdd\x3d\xd8\x96\x9c\x66\x7d\xf4\x2b\x1c\xf0\x61\x3d\x60\xcb\xb0\x5e\x08\xae\xe1\x55\x37\x46\x4d\x6f\xdd\xba\x40\x14\x2f\x80\x5b\xca\x60\x2e\x07\xc1\x9d\x9a\x70\x19\xa3\x4a\xe7\x02\xf3\x92\x16\x3a\x3d\x39\xec\x17\xf2\xe2\xf9\x34\xb0\x5a\xbf\xb2\x95\x47\x60\x5a\x10\x99\x93\xb2\x1c\xd9\x41\x10\xc9\x31\x5d\x27\x29\xd5\x50\x29\xbf\x89\x49\x5a\x73\xfa\xa5\x86\xff\x75\x24\x1a\x6b\x70\xe5\x96\x28\xe4\xf2\x82\x77\x28\x6a\x99\x4b\x82\x26\xc1\xa6\xdd\x9f\x16\xa2\xaa\x08\x5f\x2a\xeb\xae\xb1\x63\x86\xe7\x05\xd7\x84\x72\xc0\x9c\x93\x2a\x96\x48\xe6\xd4\x01\x2f\x55\xde\xd6\xbf\xc9\x34\xda\xe6\x2d\xbf\x72\x04\x0c\xc5\x70\xd1\x78\x94\x7c\x2a\xb1\x5b\x31\x26\xb5\x8d\x6e\xa9\xc3\x98\x2b\x20\x58\xec\x6f\xe4\x17\x15\xa1\x7c\x8e\xef\x80\x6b\x3c\x4a\x41\xdb\x7c\xf9\xed\x12\x01\xf8\x21\x1f\xb0\xe4\x6a\x37\x00\x3f\x50\x14\xbc\xea\x4f\xc3\x1c\x80\x19\x40\xde\xf0\xbf\x4a\xa1\xc0\x75\x8c\x63\xa0\xbd\x34\x98\x3a\xf2\x49\xcf\xf1\xdc\x1b\xbe\x4e\x52\x5e\x57\x1b\x40\xd3\xd2\x8d\x28\xb7\x02\x2b\x62\x94\xed\xf7\xb6\x96\x47\x9e\xf6\x64\x9e\xed\x40\xdb\x06\x53\xd6\x09\xcb\x19\xe5\x2f\xcb\xa7\x38\xbc\x6a\x24\xf9\x5e\x28\x3d\x1f\xc3\x2d\xf6\x3d\x10\xa6\xf7\xc5\x1e\x8a\x97\x09\x76\x9b\x6a\xc4\x2d\x94\x9e\x93\xe4\xb4\x22\xbb\x38\x91\x2c\x62\x24\x8c\x6c\x80\xdd\x64\xe7\xa2\xce\xb7\xc4\x8a\xdd\xce\x90\x86\x32\xee\xa2\x73\xe9\x96\x63\x35\xbf\x44\x7a\x00\x9c\x5b\xc0\x85\x3c\x37\x5c\xee\x62\xbc\x01\x49\xe2\xdd\xe7\x88\xf4\xd3\x63\xdb\x7c\x4e\x9c\xaa\xe6\x3f\xc6\xd2\xcc\x6d\x17\x12\xa7\xee\xfb\x9e\x38\x16\xce\x6b\x28\x46\x51\xa9\x48\x61\xfa\x06\x04\x15\x88\xeb\x99\xb4\x6b\xf6\xf3\x4a\x94\xa1\x04\xbd\x20\x76\x7d\x13\x44\xea\xab\x0b\x61\x72\x53\xff\x38\x2b\x74\xd1\x0b\x44\xc4\x9a\x90\x7a\x73\xd5\x3c\xab\x1b\x4f\xb1\x86\x8e\x30\x4a\x14\xc4\x0f\x7b\xd0\x91\x23\x69\x54\x1e\x3e\xcc\xcc\x09\x1f\xef\xbf\x27\x79\x03\xac\x41\x99\xf3\x7b\xe4\x88\xa8\xb3\x2a\xcd\x71\xf3\x29\x92\x45\x4e\xdb\x0f\x6e\xe1\x25\x2d\xc3\x58\xd1\x20\x84\x7d\xc0\xa4\x40\x7d\x71\xba\x7e\x4e\xb9\x6f\xb7\xbe\xbb\xda\x4b\xa4\x07\xca\x60\x07\xe3\x5b\xcb\x46\x08\x06\x84\x8f\xa0\x07\x81\x94\xb9\xe0\xec\x38\x83\x52\x69\x82\xd1\x0b\x85\x82\xa2\x46\xaa\x8f\xb9\x90\x7a\xf1\x3e\x43\xed\xab\x5c\xd1\x6f\x30\x8e\xe6\x19\xef\x3b\x41\xd9\x88\xe7\xa8\x0a\x7d\x5b\xbd\x56\xba\xa4\x3c\x17\x12\x78\xd4\x3b\x4a\x0b\x99\xef\x90\x14\x90\x4b\x40\x2a\x4a\x9f\x81\x6b\x3b\xd6\x65\x8d\xc4\xec\x7f\x29\x46\xd1\x1d\x27\x2c\xe6\x68\x5d\xc9\xed\x8d\x17\x0b\xad\xe3\xe1\xae\x19\xad\x68\xf8\x1c\x78\x00\x76\x46\x0d\x68\xf1\xdf\x0f\xfb\x13\x90\x7f\xd6\x94\x72\x0d\x3b\x40\x1f\x52\x4e\x74\x1d\xd3\x4d\xc7\x8c\x6e\x63\x4f\x70\x1c\xd0\x09\x3d\x1a\x06\x25\xb6\xda\xcf\xe0\xeb\x45\xbc\x7a\x8d\x86\xbf\x8d\xbc\x75\xa7\x48\xe6\xa5\xbf\x0a\xce\x5d\x35\xb2\x20\xa2\x9e\xbc\x88\x5a\xab\x68\x63\xd8\xd0\x70\x35\xd5\xd4\x0c\xa4\xd6\x14\x73\x51\xbc\x30\x8d\x92\x39\x04\x25\xf5\x6b\xbb\x72\x2c\xbb\x62\x8e\xec\xdc\x59\x7a\x01\xbe\x89\xa2\x4d\x1a\x9d\xc0\x4e\x4f\x37\x3b\xa2\xe0\xe4\x91\x2a\xb2\x71\x66\x6e\xbe\xc3\x6d\xb2\x11\x0f\x71\x8c\x41\xd0\x48\x9d\xb8\x74\x68\x3b\xc2\x13\x50\xbf\xe7\xe0\x40\xd3\x0a\x44\xed\xaf\x59\x2b\x3b\xbf\x3b\xa6\xd4\x9a\xcc\x46\x82\x6a\x51\xba\x31\x7d\x1e\x82\xda\xf7\x17\xd1\xc0\xcd\x39\x24\x08\x92\xd1\x82\xa8\x18\x10\xdd\x71\x41\xad\x65\x49\x34\xe4\xed\x8b\xaa\xab\xa0\x7f\x02\xf3\x25\x41\xc2\x18\x30\xaa\xaa\x39\x18\x9a\x96\xc0\xc8\xf1\xa6\xf2\xd9\xb0\x6f\x09\x65\x35\x42\x4e\x0a\xdd\xbd\x0b\x8b\xe4\x5c\x5a\x09\x4e\xb5\xf0\x22\xc4\xbc\x2d\x2b\xf2\x9a\xf7\xdb\x36\x24\xde\x03\x13\x6c\xeb\xe6\xde\x2d\xad\x4c\x50\xa2\xc6\xe2\xc2\xd9\x37\x87\xe8\x5c\xeb\x03\x19\xd3\xef\x78\x61\x3a\x82\x32\x48\x32\x5c\xfd\xa3\xfc\xd1\xd2\xd2\xf5\x99\xb9\x14\x8c\x16\xc7\xa5\x2c\x2c\x04\x6f\x9d\x3c\x27\x21\xee\xcc\x40\x93\x0e\xa6\x15\xaa\xa4\x8e\x1e\xd6\x86\xe1\x2b\xe5\xa5\xf8\x7a\xc5\x86\xcb\xa5\x92\x64\xa4\x00\x07\xef\xee\x75\xb4\xd2\x48\x28\xd7\x57\x97\xf3\x7b\xcd\xba\xa3\x9a\x0f\xf9\x19\x41\xfd\x81\x2e\xfe\x26\x35\x80\xf4\x85\xac\xa3\xf3\xa0\x0a\x2a\x81\xde\x04\x5c\xe0\xcd\x77\xcc\xc4\x9e\x6c\x81\xaa\x36\x6b\x80\xd8\x51\x99\xfb\xe2\xe2\xb7\x8d\xf8\x90\x30\x8b\x03\x12\x95\xa4\x5a\xea\x74\xcc\x1e\xa9\xa6\xde\x1a\x9c\x4c\x8f\x22\x92\xf0\x38\x22\xa6\x75\x5c\xf7\x8e\x42\xd5\x1b\x0e\x93\x1d\x95\xe5\x4f\xdf\x7b\xde\xf9\xd7\x94\x53\xf8\x52\x72\x1f\xe8\xf5\x6f\x43\x02\x51\x7d\x1e\x7a\xe6\xf5\xe0\xab\x6c\x76\x88\x83\xaf\x22\x96\xd3\xbf\x69\xdf\xdd\x11\x81\xaf\xcf\xbf\xb2\x13\xbc\x03\x5c\xba\x4f\x3c\x22\xd8\xd2\x51\xfd\x03\x2d\x7f\x93\x44\xfc\x79\xf9\xe5\x4c\xb3\xac\x3c\xbb\xbc\x68\x4e\xa5\xc4\xec\x31\x7e\xc7\x91\x8d\xd5\x70\xc9\x3c\x5f\xda\x8d\x61\x79\x6a\x7a\xd1\x93\x04\xc6\xba\xce\xa6\x9d\x13\xa7\x2d\x5f\x30\xc3\x1f\xdf\x4d\x14\x9f\xa9\xd7\x6d\x3f\x08\xb5\x17\x98\x0c\xf9\x63\xea\x74\xac\xbd\x77\x2f\x3f\x17\x0b\x80\x9a\xc5\x7f\xf1\xf1\x98\xb1\x93\x1f\x2f\x06\x21\xdf\xc7\xd3\xbd\xf6\xc3\xaf\x6c\xe4\x1f\x87\xa4\x7d\x79\x6d\x41\x4a\x66\x37\xf1\xa1\x30\x7a\x3f\x29\x73\x67\x8b\xfd\xa7\x5d\x99\x1f\xae\x56\xf6\xdf\xe6\x33\xbc\xd5\x69\xf5\x57\x00\x00\x00\xff\xff\x78\x30\xec\x51\x0e\x2b\x00\x00")
+
+func dataConfig_schema_v30JsonBytes() ([]byte, error) {
+ return bindataRead(
+ _dataConfig_schema_v30Json,
+ "data/config_schema_v3.0.json",
+ )
+}
+
+func dataConfig_schema_v30Json() (*asset, error) {
+ bytes, err := dataConfig_schema_v30JsonBytes()
+ if err != nil {
+ return nil, err
+ }
+
+ info := bindataFileInfo{name: "data/config_schema_v3.0.json", size: 0, mode: os.FileMode(0), modTime: time.Unix(0, 0)}
+ a := &asset{bytes: bytes, info: info}
+ return a, nil
+}
+
+var _dataConfig_schema_v31Json = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xec\x1a\xcb\x8e\xdb\x36\xf0\xee\xaf\x10\x94\xdc\xe2\xdd\x4d\xd1\xa0\x40\x73\xeb\xb1\xa7\xf6\xdc\x85\x23\xd0\xd2\x58\x66\x96\x22\x19\x92\x72\xd6\x09\xfc\xef\x05\xf5\x32\x45\x91\x22\x6d\x2b\xd9\x45\xd1\xd3\xae\xc5\x99\xe1\xbc\x67\x38\xe4\xf7\x55\x92\xa4\x6f\x65\xbe\x87\x0a\xa5\x1f\x93\x74\xaf\x14\xff\xf8\xf0\xf0\x59\x32\x7a\xd7\x7e\xbd\x67\xa2\x7c\x28\x04\xda\xa9\xbb\xf7\x1f\x1e\xda\x6f\x6f\xd2\xb5\xc6\xc3\x85\x46\xc9\x19\xdd\xe1\x32\x6b\x57\xb2\xc3\xaf\xf7\xbf\xdc\x6b\xf4\x16\x44\x1d\x39\x68\x20\xb6\xfd\x0c\xb9\x6a\xbf\x09\xf8\x52\x63\x01\x1a\xf9\x31\x3d\x80\x90\x98\xd1\x74\xb3\x5e\xe9\x35\x2e\x18\x07\xa1\x30\xc8\xf4\x63\xa2\x99\x4b\x92\x01\xa4\xff\x60\x90\x95\x4a\x60\x5a\xa6\xcd\xe7\x53\x43\x21\x49\x52\x09\xe2\x80\x73\x83\xc2\xc0\xea\x9b\x87\x33\xfd\x87\x01\x6c\x6d\x53\x35\x98\x6d\xbe\x73\xa4\x14\x08\xfa\xf7\x94\xb7\x66\xf9\xd3\x23\xba\xfb\xf6\xc7\xdd\x3f\xef\xef\x7e\xbf\xcf\xee\x36\xef\xde\x8e\x96\xb5\x7e\x05\xec\xda\xed\x0b\xd8\x61\x8a\x15\x66\x74\xd8\x3f\x1d\x20\x4f\xdd\x7f\xa7\x61\x63\x54\x14\x0d\x30\x22\xa3\xbd\x77\x88\x48\x18\xcb\x4c\x41\x7d\x65\xe2\x29\x24\xf3\x00\xf6\x42\x32\x77\xfb\x3b\x64\x1e\x8b\x73\x60\xa4\xae\x82\x16\xec\xa1\x5e\x48\x98\x76\xfb\x65\xec\x27\x21\x17\xa0\xc2\x2e\xdb\x42\xbd\x98\xc7\xea\xed\x6f\x13\x78\xd5\x0b\x3d\x0b\xdb\x42\x18\x7b\x37\x0c\x8e\xc2\xdb\xa5\x2a\x57\x78\xf9\x75\x35\x28\xcb\xa3\xa5\x02\x38\x61\x47\xfd\xcd\xa3\x8f\x16\xa0\x02\xaa\xd2\x41\x05\x49\x92\x6e\x6b\x4c\x0a\x5b\xa3\x8c\xc2\x5f\x9a\xc4\xa3\xf1\x31\x49\xbe\xdb\x99\xcc\xa0\xd3\xac\x8f\x7e\xf9\x0d\x3e\xac\x7b\x64\x19\xd6\x73\x46\x15\x3c\xab\x46\xa8\xf9\xad\x5b\x15\xb0\xfc\x09\xc4\x0e\x13\x88\xc5\x40\xa2\x94\x33\x2a\x23\x58\xaa\x8c\x89\xac\xc0\xb9\x4a\x4f\x16\xfa\x84\x5e\xd8\x9f\x06\x54\xe3\xd7\x66\xe5\x20\x98\xe6\x88\x67\xa8\x28\x46\x72\x20\x21\xd0\x31\x5d\x27\x29\x56\x50\x49\xb7\x88\x49\x5a\x53\xfc\xa5\x86\x3f\x3b\x10\x25\x6a\xb0\xe9\x16\x82\xf1\xe5\x09\x97\x82\xd5\x3c\xe3\x48\x68\x07\x9b\x57\x7f\x9a\xb3\xaa\x42\x74\x29\xaf\xbb\x44\x8e\x08\xcd\x33\xaa\x10\xa6\x20\x32\x8a\xaa\x90\x23\xe9\xa8\x03\x5a\xc8\xac\x2d\xf8\xb3\x6e\xb4\xcb\x5a\x7c\x69\x11\x18\xaa\xff\xa2\xf6\x28\xe8\x9c\x63\xb7\x64\xb4\x6b\x6b\xde\x52\x0b\x31\x93\x80\x44\xbe\xbf\x12\x9f\x55\x08\xd3\x18\xdd\x01\x55\xe2\xc8\x19\x6e\xfd\xe5\xd5\x39\x02\xd0\x43\x36\xe4\x92\x8b\xd5\x00\xf4\x80\x05\xa3\x55\x1f\x0d\x31\x09\x66\x48\xf2\x1a\xff\x99\x33\x09\xb6\x62\x2c\x01\xcd\xa5\x41\xd4\x91\x4e\x7a\x8c\xc7\x5e\xf0\x75\x92\xd2\xba\xda\x82\xd0\x3d\xec\x08\x72\xc7\x44\x85\x34\xb3\xfd\xde\xc6\xf2\x48\xd3\x0e\xcf\x33\x15\x68\xca\xa0\xcb\x3a\x22\x19\xc1\xf4\x69\x79\x17\x87\x67\x25\x50\xb6\x67\x52\xc5\xe7\x70\x03\x7d\x0f\x88\xa8\x7d\xbe\x87\xfc\x69\x06\xdd\x84\x1a\x61\x33\xa9\x62\x9c\x1c\x57\xa8\x0c\x03\xf1\x3c\x04\x42\xd0\x16\xc8\x55\x72\x2e\xaa\x7c\x83\x2c\x2b\x4b\x0d\xea\xf3\xb8\x49\xe7\xd2\x2d\x87\x6a\x7e\x21\xf0\x01\x44\x6c\x01\x67\xfc\xdc\x70\xd9\x8b\xe1\x06\x24\x09\x77\x9f\x23\xd0\x4f\xf7\x6d\xf3\x39\x13\x55\xcd\x7f\x84\xa4\x1b\xbb\x5d\x48\xac\xba\xef\xfa\x62\x49\x18\xd7\x50\x8c\xac\x52\xa1\x5c\xf7\x0d\x02\xa4\xc7\xae\x67\xd0\xee\x74\x93\x55\xac\xf0\x39\xe8\x04\xd8\xd6\x8d\x37\x53\x5f\x5c\x08\x93\xab\xfa\xc7\x28\xd3\x05\x0f\x10\x01\x69\x7c\xec\xc5\xb2\x79\x66\x37\xec\x62\x0d\x1c\x22\x18\x49\x08\x07\xbb\x57\x91\x23\x6a\x98\x1f\x3e\x44\xfa\x84\x0b\xf7\xb7\x59\x5c\x0f\xaa\x97\x66\x7c\x8f\x1c\x20\x75\x66\xa5\x09\x37\x17\x23\x9b\x40\xb4\xfd\xe0\x16\x9e\xe3\xc2\x9f\x2b\x9a\x0c\x61\x06\x18\x67\x42\x4d\xa2\xeb\xe7\x94\xfb\x76\xeb\x9b\xab\x3d\x17\xf8\x80\x09\x94\x30\x3e\xb5\x6c\x19\x23\x80\xe8\x28\xf5\x08\x40\x45\xc6\x28\x39\x46\x40\x4a\x85\x44\xf0\x40\x21\x21\xaf\x05\x56\xc7\x8c\x71\xb5\x78\x9f\x21\xf7\x55\x26\xf1\x37\x18\x5b\xf3\x9c\xef\x3b\x42\x1b\x8b\x21\x6b\x42\x72\xa5\x41\x7d\x29\x29\x1c\xc6\x8e\x44\x18\x4c\x54\xe1\x14\x95\x4a\x56\x8b\x3c\xf6\x80\xad\xf7\x44\xa2\x84\xd8\x23\xbc\x76\xb7\x71\xd8\xcc\x03\x97\x97\x00\x4f\x0a\x5d\x67\xc2\x50\x55\xb6\x7f\x9b\x79\xe5\xe4\x0c\x7d\x79\x94\xb9\xba\xae\x5b\x93\xaa\xc0\x34\x63\x1c\x68\x30\x36\xa4\x62\x3c\x2b\x05\xca\x21\xe3\x20\x30\x73\xaa\x62\x6d\x46\x7a\x51\x0b\xa4\xf7\x9f\x92\x91\xb8\xa4\x88\x84\xc2\x4c\x55\x7c\x77\xe5\xb1\x52\xa9\x70\xb0\xd7\x04\x57\xd8\x1f\x34\x0e\xaf\x8d\xe8\x00\xda\xea\xef\x2e\xfa\x33\x05\xff\xcc\x29\xa6\x0a\x4a\xed\x26\x53\xa7\x9a\xe9\x39\xe7\x5b\xce\x88\x5e\x73\x8f\xc4\xd8\xa0\x33\x7c\x24\x6d\x60\xee\x94\x1b\xc1\xd5\x89\x3a\xf9\x1a\xdd\x75\x34\xf4\xd6\x1d\x23\x1b\x27\xfc\x45\xc5\xdc\x66\x63\xe3\xad\xa7\xee\xa0\xaa\x65\xf0\x58\xd0\xc0\x50\x39\xd7\xd2\x0e\xa0\xc6\xd0\x7e\xd1\x6a\xa1\xdb\x64\x1d\x04\x05\x76\x73\xbb\xb2\x24\xbb\x60\xec\x6e\x9d\x58\x7b\x02\xae\x79\xb2\x09\x1a\x9c\xbf\xcf\xcf\xb6\x3b\x20\xef\xdc\x19\x4b\xb4\xb5\x26\xae\xae\xe0\xd6\xde\x28\x0e\xe1\x1c\x23\x40\x09\x6c\xd9\xa5\x4f\xd4\x66\x3e\x01\xf9\x3a\xc7\x46\x0a\x57\xc0\x6a\x77\xc1\x5b\x99\xfe\xdd\x21\xa5\xc6\x5c\x3e\x60\x54\x03\xd2\xb6\xe9\xe3\x60\xd4\xbe\xbb\x0c\x1a\x2e\x26\x48\x04\x70\x82\x73\x24\x43\x89\xe8\x86\xf1\x44\xcd\x0b\xa4\x20\x6b\xef\x65\x2f\x4a\xfd\x33\x39\x9f\x23\x81\x08\x01\x82\x65\x15\x93\x43\xd3\x02\x08\x3a\x5e\x55\x3e\x1b\xf4\x1d\xc2\xa4\x16\x90\xa1\x5c\x75\x57\xbf\x01\x9f\x4b\x2b\x46\xb1\x62\xce\x0c\x11\xb7\x65\x85\x9e\xb3\x7e\xdb\x06\x24\xd4\xd9\x8c\x9b\xfa\xd8\xc9\x82\xe1\x09\x6d\xe3\x77\x59\x75\x9e\x31\xd1\xb9\xd6\x7b\x3c\xa6\xdf\x71\x22\xba\x00\xa9\x33\xc9\x30\xf8\x09\xe2\x07\x4b\x4b\x77\xca\xc8\x38\x23\x38\x3f\x2e\x25\x61\xce\x68\xab\xe4\x18\x87\xb8\xd1\x03\xb5\x3b\xe8\x56\xa8\xe2\x2a\x18\xac\x0d\xc2\x57\x4c\x0b\xf6\xf5\x82\x0d\x97\x73\x25\x4e\x50\x0e\x56\xbe\xbb\x55\xd1\x52\x09\x84\xa9\xba\xb8\x9c\xdf\x2a\xd6\x0d\xd5\x7c\xf0\xcf\x40\xd6\x1f\xe0\xc2\xf7\xe8\x9e\x4c\x9f\xf3\x3a\x38\x0d\xac\xa0\x62\xc2\xe9\x80\x0b\x3c\xf4\x08\x89\xd8\x83\x2d\x50\xd5\xa2\xc6\xc7\x1d\x54\xc6\xf8\xf2\xa7\x8d\xf0\x88\x78\x13\x4e\x48\x98\xa3\x6a\xa9\xe8\x88\x1e\xa8\xa7\xce\x1a\x9c\xcc\xcf\x2d\x12\xff\xec\x22\xc4\x75\x98\xf7\x0e\x42\xd6\x5b\xea\x19\x21\x4c\x4f\x19\xae\x5b\xfe\xf8\x63\xca\xc9\x7f\x28\xb9\x2d\xe9\xf5\x77\x61\x1e\xab\x3e\x0e\x3d\xf3\x7a\xd0\xd5\x26\xda\xc4\xde\x8b\xa8\xe5\xf8\x6f\xda\x77\x7b\x44\xe0\xea\xf3\x2f\xec\x04\x6f\x48\x2e\xdd\x8b\xa6\x40\x6e\xe9\xa0\xfe\x4f\x2d\xff\x11\x47\xfc\x79\xfe\xd5\x3d\x20\x0b\xbe\xdc\x6a\xa0\xae\x2e\xce\x11\xcf\x95\x5e\x81\xcd\x5e\xda\x14\xe3\xc1\xa2\x61\x92\xe9\x99\x7f\x4e\x93\xd1\xf7\x69\x1d\xc6\x66\xcc\x86\x0d\xe6\x78\xe3\x3b\xae\x90\x73\x83\xa4\x1e\xc4\x73\xbf\x62\x6d\xda\x29\x71\x5e\xf2\x05\x93\xcd\xfd\xbb\x99\x3e\x60\xee\xde\xfb\x07\x15\xd0\x05\x86\x74\x6e\x9b\x5a\x87\x87\x5e\xbb\xd3\x77\x9b\x9e\xf8\x37\xf0\x27\xaf\x38\xb5\x9c\xf4\x38\x99\x49\x7d\x1f\x0f\x5a\xdb\x17\x98\x9b\x91\x7e\x2c\x90\xf6\x15\x89\x91\xdd\x37\xe6\x79\xca\x67\x46\xe7\xdb\x4e\x7b\xcc\xdb\xbf\xb1\xf4\xdc\x6a\xac\xcc\xbf\xcd\x7b\xd8\xd5\x69\xf5\x6f\x00\x00\x00\xff\xff\xfc\xf3\x11\x6a\x88\x2f\x00\x00")
+
+func dataConfig_schema_v31JsonBytes() ([]byte, error) {
+ return bindataRead(
+ _dataConfig_schema_v31Json,
+ "data/config_schema_v3.1.json",
+ )
+}
+
+func dataConfig_schema_v31Json() (*asset, error) {
+ bytes, err := dataConfig_schema_v31JsonBytes()
+ if err != nil {
+ return nil, err
+ }
+
+ info := bindataFileInfo{name: "data/config_schema_v3.1.json", size: 0, mode: os.FileMode(0), modTime: time.Unix(0, 0)}
+ a := &asset{bytes: bytes, info: info}
+ return a, nil
+}
+
+var _dataConfig_schema_v32Json = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xec\x1b\x4d\x73\xdc\xa8\xf2\x3e\xbf\x42\xa5\xe4\x16\x7f\xa4\xde\x4b\xbd\xaa\x97\xdb\x3b\xbe\xd3\xee\x79\x5d\x13\x15\x83\x7a\x34\xc4\x12\x10\x40\x63\x4f\x52\xfe\xef\x5b\xfa\x1c\x40\x20\xd0\x8c\x1c\x67\xb7\xf6\x64\x5b\x74\x37\xf4\x77\x37\x8d\x7f\x6c\x92\x24\x7d\x2f\xf1\x01\x2a\x94\x7e\x4e\xd2\x83\x52\xfc\xf3\xfd\xfd\x57\xc9\xe8\x6d\xf7\xf5\x8e\x89\xe2\x3e\x17\x68\xaf\x6e\x3f\x7e\xba\xef\xbe\xbd\x4b\x6f\x1a\x3c\x92\x37\x28\x98\xd1\x3d\x29\xb2\x6e\x25\x3b\xfe\xfb\xee\x5f\x77\x0d\x7a\x07\xa2\x4e\x1c\x1a\x20\xb6\xfb\x0a\x58\x75\xdf\x04\x7c\xab\x89\x80\x06\xf9\x21\x3d\x82\x90\x84\xd1\x74\x7b\xb3\x69\xd6\xb8\x60\x1c\x84\x22\x20\xd3\xcf\x49\x73\xb8\x24\x19\x41\x86\x0f\x1a\x59\xa9\x04\xa1\x45\xda\x7e\x7e\x69\x29\x24\x49\x2a\x41\x1c\x09\xd6\x28\x8c\x47\x7d\x77\x7f\xa6\x7f\x3f\x82\xdd\xd8\x54\xb5\xc3\xb6\xdf\x39\x52\x0a\x04\xfd\x7d\x7a\xb6\x76\xf9\xcb\x03\xba\xfd\xfe\xbf\xdb\x3f\x3e\xde\xfe\xf7\x2e\xbb\xdd\x7e\x78\x6f\x2c\x37\xf2\x15\xb0\xef\xb6\xcf\x61\x4f\x28\x51\x84\xd1\x71\xff\x74\x84\x7c\xe9\x7f\x7b\x19\x37\x46\x79\xde\x02\xa3\xd2\xd8\x7b\x8f\x4a\x09\x26\xcf\x14\xd4\x13\x13\x8f\x21\x9e\x47\xb0\x37\xe2\xb9\xdf\xdf\xc1\xb3\xc9\xce\x91\x95\x75\x15\xd4\xe0\x00\xf5\x46\xcc\x74\xdb\xaf\xa3\x3f\x09\x58\x80\x0a\x9b\x6c\x07\xf5\x66\x16\xdb\x6c\x7f\x1d\xc3\x9b\x81\xe9\x59\xd8\x0e\x42\xdb\xbb\x3d\xa0\xe1\xde\x2e\x51\xb9\xdc\xcb\x2f\xab\x51\x58\x1e\x29\xe5\xc0\x4b\x76\x6a\xbe\x79\xe4\xd1\x01\x54\x40\x55\x3a\x8a\x20\x49\xd2\x5d\x4d\xca\xdc\x96\x28\xa3\xf0\x5b\x43\xe2\x41\xfb\x98\x24\x3f\xec\x48\xa6\xd1\x69\xd7\x8d\xbf\xfc\x0a\x1f\xd7\x3d\xbc\x8c\xeb\x98\x51\x05\xcf\xaa\x65\x6a\x7e\xeb\x4e\x04\x0c\x3f\x82\xd8\x93\x12\x62\x31\x90\x28\xe4\x8c\xc8\x4a\x22\x55\xc6\x44\x96\x13\xac\x9c\xf8\x18\xe1\x03\x64\x7b\xc1\xaa\x20\x95\x7d\xd6\x9d\x43\xa6\x2f\x16\x9d\x09\xe1\xb0\x61\x8e\xa8\xda\x5f\xdb\x8d\x83\x60\x8a\x11\xcf\x50\x9e\x1b\x02\x41\x42\xa0\x53\x7a\x93\xa4\x44\x41\x25\xdd\xb2\x4a\xd2\x9a\x92\x6f\x35\xfc\xbf\x07\x51\xa2\x06\x9b\x6e\x2e\x18\x5f\x9f\x70\x21\x58\xcd\x33\x8e\x44\x63\xa9\xf3\x7a\x4c\x31\xab\x2a\x44\xd7\x32\xdf\x25\x7c\x44\x48\x9e\x51\x85\x08\x05\x91\x51\x54\x85\x2c\xb2\x71\x5f\xa0\xb9\xcc\xba\xca\x21\xd6\x92\x0c\x02\x63\x19\xb1\xaa\x3e\x72\x3a\xe7\x21\x1d\x99\xc6\x47\x9a\xb3\xa5\x16\x62\x26\x01\x09\x7c\xb8\x10\x9f\x55\x88\xd0\x18\xd9\x01\x55\xe2\xc4\x19\xe9\xec\xe5\x97\x33\x04\xa0\xc7\x6c\x0c\x4a\x8b\xc5\x00\xf4\x48\x04\xa3\xd5\xe0\x0d\x71\x91\x4a\xc3\x7f\xe6\x4c\x82\x2d\x18\x8b\x41\x7d\x69\x64\xd5\x90\xc9\x80\xf1\x30\x30\x7e\x93\xa4\xb4\xae\x76\x20\x9a\x62\xd8\x80\xdc\x33\x51\xa1\xe6\xb0\xc3\xde\xda\xb2\x21\x69\x87\xe5\xe9\x02\xd4\x79\x68\xea\x03\x54\x66\x25\xa1\x8f\xeb\x9b\x38\x3c\x2b\x81\xb2\x03\x93\xea\x92\x64\x90\x1e\x00\x95\xea\x80\x0f\x80\x1f\x67\xd0\x75\x28\x03\x9b\x49\x15\x63\xe4\xa4\x42\x45\x18\x88\xe3\x10\x48\x89\x76\x50\x5e\xc4\xe7\xaa\xc2\xd7\xc8\xb2\xa2\x68\x40\x7d\x16\x37\x29\x81\xfa\xe5\x50\xf1\x90\x0b\x72\x04\x11\x5b\x09\x30\x7e\xae\xdc\xec\xc5\x70\x25\x93\x84\xcb\x58\x03\xf4\xcb\x5d\x57\xc5\xce\x78\x55\xfb\x5b\x59\xa6\x5b\xbb\x5c\x48\xac\xbc\xef\xfa\x62\x71\x18\x57\x50\x18\x5a\xa9\x10\x6e\xea\x06\x01\xd2\xa3\xd7\x33\x68\xdf\x26\x65\x15\xcb\x7d\x06\x3a\x01\xb6\x65\xe3\x8d\xd4\x8b\x13\x61\x72\x51\x21\x1a\xa5\xba\x60\x27\x12\xe0\xc6\x77\xbc\xd8\x63\x9e\x8f\x1b\x36\xb1\x16\x0e\x95\x04\x49\x08\x3b\xbb\x57\x90\x06\x35\xc2\x8f\x9f\x22\x6d\xc2\x85\xfb\x9f\x59\x5c\x0f\xaa\x97\x66\x7c\x8d\x1c\x20\x75\x3e\x4a\xeb\x6e\xae\x83\x6c\x03\xde\xf6\xca\x25\x3c\x27\xb9\x3f\x56\xb4\x11\x42\x77\x30\xce\x84\x9a\x78\xd7\xf2\x74\xef\xb3\x60\x5d\x5c\x43\x9c\x3a\x27\xfc\x6e\xf3\x89\x34\x26\xea\x8e\x42\x9a\xfa\x5f\xd0\x3f\xc2\x9e\x91\xce\x44\x29\x07\xb4\x42\xa2\x00\xb3\x0d\x21\x54\x41\x01\xc2\x83\xc0\xeb\x5d\x49\xe4\x01\xf2\x25\x38\x82\x29\x86\x59\x19\xe7\x18\xce\x3e\x36\xde\x19\x4c\x82\xdb\xab\x6b\x33\x2e\xc8\x91\x94\x50\x58\x1c\xef\x18\x2b\x01\x51\x23\x51\x08\x40\x79\xc6\x68\x79\x8a\x80\x94\x0a\x89\x60\xfb\x27\x01\xd7\x82\xa8\x53\xc6\xb8\x5a\xbd\x2a\x94\x87\x2a\x93\xe4\x3b\x98\xbe\x77\xb6\xfa\x9e\xd0\xd6\x3a\x90\x75\x31\x96\xbc\x96\xfb\xf9\xcc\xf6\x95\xdc\x46\xb2\x5a\xe0\xeb\x1c\x67\x16\xbe\x36\x83\xdc\x3c\x70\xb1\x04\x78\xe2\xf0\xbd\x0a\x43\x35\xd4\xac\xab\x38\x03\xb5\x3c\x49\xac\x2e\xab\xad\xa5\xca\x09\xcd\x18\x07\x1a\xf4\x0d\xa9\x18\xcf\x0a\x81\x30\x64\x1c\x04\x61\x4e\x51\x18\x01\x36\xaf\x05\x6a\xf6\x9f\x92\x91\xa4\xa0\xc8\x1d\x77\x34\x50\x55\xf1\xfd\x85\x97\x00\x4a\x85\x9d\xbd\x2e\x49\x45\xfc\x4e\xe3\xb0\xda\x88\x7a\xad\xab\xd5\xdc\x25\xda\x4c\x79\x16\x15\xb2\x67\x3a\x84\xf9\x06\x21\xa2\x33\x38\x20\xb1\x20\x75\xb4\x8e\xb9\xf7\xe4\x27\x57\xdf\xe0\x3c\x97\x31\xe2\x6a\xe9\xdd\xf4\x07\xd9\x3a\xe1\x17\x95\x5e\xf6\x31\xb6\xde\xea\xc7\xed\x54\xb5\x0c\x36\x71\x2d\x0c\x95\x73\x0d\xc8\x08\x3a\x9d\xd5\x24\x7f\x89\x08\x6d\xe8\xa8\x05\x77\xe8\x26\x22\x8e\xf7\x3b\x45\xc6\xce\xd7\x8e\xfa\xd1\x15\x81\x86\x83\x19\x95\x44\x2a\xa0\xf8\x14\xbf\xd1\x8e\x4c\x6e\x89\xa7\x42\x99\xef\xbb\xe2\xba\xae\x16\x0a\x15\x5d\xbc\x8d\x6e\x74\xe2\x7d\xb5\x1f\xe3\xfd\x14\x56\x28\xc3\x8c\x7b\x54\x13\xcf\xc6\xd2\x34\x6b\x5d\x5d\xcc\xd4\xa1\xbe\x90\xf1\xc4\xc4\x63\x93\x90\x72\xe2\x8e\x1c\x1b\x0b\x65\xc1\xe4\xd3\xba\xeb\x1b\x08\xb8\x46\x7a\x3a\x68\x70\x04\x3a\x3f\x5e\xec\x81\xbc\xa3\x3f\x22\xd1\xce\x1a\x7a\xb9\x12\x6d\x93\x19\xc4\x31\x9c\xef\x05\x28\x41\xac\x51\xc2\x50\x34\xe9\xb9\x1d\xe4\xaf\x79\xe1\xae\x48\x05\xac\x76\x87\xa1\x8d\x6e\x38\x3d\x52\xaa\x8d\x46\x03\x4a\xd5\x20\x6d\x9d\x3e\x8c\x4a\x1d\xfa\xf2\xa0\xe2\x62\x12\x16\xd0\xbc\x1d\x6d\x44\x65\x37\x01\xbc\x24\x18\xc9\x50\x05\x71\xc5\x2d\x70\xcd\x73\xa4\x20\xeb\xde\xd1\x2c\xaa\xd9\x66\x8a\x35\x8e\x04\x2a\x4b\x28\x89\xac\x62\x8a\x9f\x34\x87\x12\x39\xa3\x7f\xb0\xee\x6d\xd1\xf7\x88\x94\xb5\x80\x0c\x61\x6f\x98\xb6\x30\x2a\x46\x89\x62\xce\x70\x12\xb7\x65\x85\x9e\xb3\x61\xdb\x16\x24\xd4\x92\x98\xdd\x78\xec\x05\xae\x66\x09\x5d\xee\x5e\x56\x56\xcf\xa8\xe8\x5c\xa4\x7b\x2c\x66\xd8\x71\xc2\xba\x00\xd9\x84\x9d\xf1\x7e\x3d\x88\x1f\x0c\xf0\xfd\xf5\x40\xc6\x59\x49\xba\x2a\x60\x0d\x0e\x31\xa3\x9d\x90\x63\x0c\xe2\x4a\x0b\x6c\xcc\xa1\xe9\x61\x2a\xae\x82\xce\xda\x22\x3c\x11\x9a\xb3\xa7\x05\x1b\xae\x67\x4a\xbc\x44\x18\xac\xe0\x78\xad\xa0\xa5\x12\x88\x50\xb5\x78\x9c\x74\x2d\x5b\x57\xa4\xfe\xd1\x3e\x03\x29\x62\x84\x0b\x26\x7d\x5f\x5a\xc0\xbc\x0e\x0e\x5d\x2a\xa8\x98\x70\x17\xc0\x57\xf0\x38\xbc\x78\x0b\xb0\x38\x80\xad\x90\x02\xa3\xa6\x74\x3d\x54\xc6\xf8\xfa\xd7\x04\xe1\x49\xdc\x36\x1c\x90\x08\x47\xd5\x5a\xde\x11\x3d\xb7\x4c\x9d\x39\x38\x99\x6f\x67\x13\x7f\x4b\x1b\x3a\x75\xf8\xec\x3d\x84\xac\x77\xd4\xd3\x05\x4e\x9b\x81\x35\x6f\xb3\x57\x0c\x7a\xc3\x93\x03\x8f\x56\x1f\xc6\x02\xfb\x66\x94\xd5\x36\x5a\xc5\xde\x79\xff\x7a\xe7\x6f\x6b\x7d\xfb\x6e\xcf\xd5\x14\x20\xa5\x10\x3e\x44\xf5\x0f\x0b\x8b\xc6\x2b\xe2\xd0\xa4\xcb\x75\x86\xa1\x1e\xea\x9f\x28\xf4\x37\xb1\xd9\x9f\x67\x5f\xfd\xdb\xe0\xe0\xa3\xdc\x16\xea\xe2\x3c\x1e\xf1\x12\xf5\x17\xd0\xd9\x5b\xab\xc2\x1c\x1e\x68\x2a\x99\xde\x25\xcc\x49\x72\xe9\xeb\xdb\xad\x79\x0c\x1b\xcc\xf1\xef\x1b\x66\x32\x9d\x1b\x2d\x0e\x20\x9e\xbb\x2b\x6b\xd3\x5e\x88\xf3\x9c\xaf\x18\x6c\xee\x3e\xcc\x94\x0c\x73\x2f\x91\x5e\x29\xd7\xae\x30\xb6\x75\xeb\xd4\xea\x33\x06\xe9\x4e\x9f\xe4\x7b\xfc\x5f\xc3\x9f\x3c\xd0\x6f\xf8\xa4\xa7\xc9\x5d\xd7\x0f\xf3\xa2\xbe\x7b\x5c\xbf\x35\xe4\x63\x81\x74\xef\xfa\xb4\xe8\xbe\xd5\x5b\x2f\x9f\x1a\x9d\xcf\xf6\xed\x31\xc1\xf0\x7c\xde\x33\xb9\xdc\xe8\x3f\xdb\x7f\x75\xd8\xbc\x6c\xfe\x0c\x00\x00\xff\xff\xa9\x16\x7b\x3d\x63\x35\x00\x00")
+
+func dataConfig_schema_v32JsonBytes() ([]byte, error) {
+ return bindataRead(
+ _dataConfig_schema_v32Json,
+ "data/config_schema_v3.2.json",
+ )
+}
+
+func dataConfig_schema_v32Json() (*asset, error) {
+ bytes, err := dataConfig_schema_v32JsonBytes()
+ if err != nil {
+ return nil, err
+ }
+
+ info := bindataFileInfo{name: "data/config_schema_v3.2.json", size: 0, mode: os.FileMode(0), modTime: time.Unix(0, 0)}
+ a := &asset{bytes: bytes, info: info}
+ return a, nil
+}
+
+var _dataConfig_schema_v33Json = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xec\x5b\x4b\x93\xdb\x2a\x16\xde\xfb\x57\xa8\x74\xef\x2e\xfd\x48\x55\x52\x53\x35\xd9\xcd\x72\x56\x33\xeb\xe9\x72\x54\x18\x1d\xdb\xa4\x11\x10\x40\xee\x76\x52\xfd\xdf\xa7\xf4\x34\x20\x10\xd8\x56\xa7\x7b\xe6\x66\xd5\x6d\xe9\x3b\xc0\x79\x9f\x03\xe8\xe7\x2a\xcb\xf2\x3f\x15\xde\x43\x85\xf2\x2f\x59\xbe\xd7\x5a\x7c\xb9\xbf\xff\xa6\x38\xbb\xed\x9e\xde\x71\xb9\xbb\x2f\x25\xda\xea\xdb\x8f\x9f\xef\xbb\x67\x7f\xe4\x37\x0d\x1d\x29\x1b\x12\xcc\xd9\x96\xec\x8a\xee\x4d\x71\xf8\x74\xf7\xe9\xae\x21\xef\x20\xfa\x28\xa0\x01\xf1\xcd\x37\xc0\xba\x7b\x26\xe1\x7b\x4d\x24\x34\xc4\x0f\xf9\x01\xa4\x22\x9c\xe5\xeb\x9b\x55\xf3\x4e\x48\x2e\x40\x6a\x02\x2a\xff\x92\x35\x8b\xcb\xb2\x11\x32\x3c\x30\x86\x55\x5a\x12\xb6\xcb\xdb\xc7\x2f\xed\x08\x59\x96\x2b\x90\x07\x82\x8d\x11\xc6\xa5\xfe\x71\x7f\x1a\xff\x7e\x84\xdd\xb8\xa3\x1a\x8b\x6d\x9f\x0b\xa4\x35\x48\xf6\xef\xe9\xda\xda\xd7\x5f\x1f\xd0\xed\x8f\x7f\xdc\xfe\xe7\xe3\xed\xdf\xef\x8a\xdb\xf5\x87\x3f\xad\xd7\x8d\x7c\x25\x6c\xbb\xe9\x4b\xd8\x12\x46\x34\xe1\x6c\x9c\x3f\x1f\x91\x2f\xfd\x7f\x2f\xe3\xc4\xa8\x2c\x5b\x30\xa2\xd6\xdc\x5b\x44\x15\xd8\x3c\x33\xd0\x4f\x5c\x3e\xc6\x78\x1e\x61\x6f\xc4\x73\x3f\xbf\x87\x67\x9b\x9d\x03\xa7\x75\x15\xd5\xe0\x80\x7a\x23\x66\xba\xe9\x97\xd1\x9f\x02\x2c\x41\xc7\x4d\xb6\x43\xbd\x99\xc5\x36\xd3\x2f\xc3\x70\x17\x35\x62\x0c\x0f\xa8\x37\x62\xb8\x9b\xfe\x3a\x86\x57\x03\xd3\xb3\xd8\x0e\x61\xcc\xdd\x2e\xd0\x8a\x67\x3e\x51\xf9\xe2\x49\x58\x56\xa3\xb0\x02\x52\x2a\x41\x50\x7e\x6c\x9e\x05\xe4\xd1\x01\x2a\x60\x3a\x1f\x45\x90\x65\xf9\xa6\x26\xb4\x74\x25\xca\x19\xfc\xab\x19\xe2\xc1\x78\x98\x65\x3f\xdd\xd0\x6d\x8c\xd3\xbe\xb7\x7e\x85\x15\x3e\xbe\x0f\xf0\x32\xbe\xc7\x9c\x69\x78\xd6\x2d\x53\xf3\x53\x77\x22\xe0\xf8\x11\xe4\x96\x50\x48\xa5\x40\xb2\xb3\xe2\x80\xc8\x28\x51\xba\xe0\xb2\x28\x09\xd6\x5e\x7a\x8a\x36\x40\xaf\x1a\x01\x23\xbc\x87\x62\x2b\x79\x15\x1d\x65\x5b\x74\x9c\xa8\xfc\xc5\x19\x67\x32\x70\xdc\xb4\x47\x52\xe3\xd7\x7a\xe5\x19\x30\xc7\x48\x14\xa8\x2c\x2d\x91\x22\x29\xd1\x31\xbf\xc9\x72\xa2\xa1\x52\x7e\x69\x67\x79\xcd\xc8\xf7\x1a\xfe\xd9\x43\xb4\xac\xc1\x1d\xb7\x94\x5c\x2c\x3f\xf0\x4e\xf2\x5a\x14\x02\xc9\xc6\xd6\xe7\x2d\x21\xc7\xbc\xaa\x10\x5b\xca\x01\xce\xe1\x23\x41\xf2\x93\x30\x9b\x99\x5e\xd5\xcf\x61\xbe\x1a\x67\xb3\x96\x15\xe0\x26\xce\xcf\xd4\xa5\xe3\x4e\x1d\x77\xeb\x26\x2a\xf2\x5a\xe2\x54\x2f\x6d\xe6\x44\x72\x07\xa9\x71\x20\xcb\xf2\x9a\x94\xe9\xe0\xdd\x39\xe0\x8a\x97\xf6\xba\x59\x5d\x6d\x40\x4e\x5c\xd2\xf6\xac\xe9\xef\xf5\xca\xf7\xc6\xd1\xbe\x46\x84\x81\x2c\x18\xaa\x62\xb2\xca\xb1\x84\x12\x98\x26\x88\x16\x4a\x00\xb6\xe0\x83\xa6\x66\x34\x93\x27\x45\xcd\x5c\xc2\x8e\x28\x2d\x8f\x5e\xe4\x89\x0b\x73\x61\x25\x08\x60\xa5\x2a\xba\x1e\x20\x35\xc0\x59\x03\x8c\x0d\xc1\xa2\x61\xa2\x64\x73\x81\xbb\x1b\xa6\x09\xdd\xcd\xda\x72\x87\xb0\x50\x80\x24\xde\x5f\x48\xcf\x2b\x44\x58\x8a\x52\x81\x69\x79\x14\x9c\x74\x61\xec\xdd\xc5\x27\x60\x87\x62\xb4\x9b\xb3\xc5\x00\xec\x40\x24\x67\xd5\x10\xa4\xd3\x12\xa8\x41\xff\x2c\xb8\x82\xeb\x83\x63\x4f\xf1\x30\x30\x7e\x33\xfa\xf4\xda\x96\x5e\xbe\xe5\xb2\x42\xcd\x62\x87\xb9\x4d\x1f\xb6\xa6\x9a\x5a\x9e\x29\x40\x93\x87\xa6\xf0\x45\xb4\xa0\x84\x3d\x2e\x6f\xe2\xf0\xac\x25\x2a\xf6\x5c\xe9\x4b\x6a\x94\x7c\x0f\x88\xea\x3d\xde\x03\x7e\x9c\x21\x37\x51\x16\x35\x57\x3a\xc5\xc8\x49\x85\x76\x71\x90\xc0\x31\xc8\xc5\xb5\x58\xbe\xa8\xf0\x8d\x61\xf9\x6e\xd7\x40\x43\x16\x37\xa9\xed\xfb\xd7\xb1\xaa\xb8\x94\xe4\x00\x32\xb5\xc4\xe5\xe2\xd4\x92\xb8\x2f\x53\xb2\x79\xb4\x3f\xb3\xa0\x5f\xef\xba\xf6\x6c\xc6\xab\xda\xff\x28\xcd\xd7\xd3\x94\x39\x4d\x9a\xee\x13\x87\xc3\xb4\x3a\xd7\xd2\x4a\x85\x70\x53\xce\x4a\x50\x01\xbd\x9e\xa0\xfd\x86\x47\x31\xc9\xf9\x27\xec\x04\x3c\x49\xac\xa1\x48\x7d\x76\x22\xcc\x2e\xea\xb0\x92\x54\x17\x6d\xb1\x23\xdc\x84\x96\x97\xba\xcc\xd3\x72\xe3\x26\xd6\xe2\x10\x25\x48\x41\xdc\xd9\x83\x82\xb4\x46\x23\xe2\xf0\x39\xd1\x26\x7c\xb4\x7f\x9b\xa5\x0d\x90\x06\xc7\x4c\x6f\xdd\x22\x43\x99\x25\x2a\xa5\xde\x85\xac\xe3\x45\xeb\x6b\x76\x96\xc2\x2e\xbc\xed\x58\xd1\x46\x08\xd3\xc1\x04\x97\xfa\x97\xf4\x42\xa7\x38\x75\x4a\xf8\xdd\xe4\xd3\xf6\xc8\x55\x77\x12\xd1\xeb\xf4\x54\x33\x51\xca\x83\xf6\x74\x54\x84\x69\xd8\x35\xad\x8c\x3f\x09\xd4\x1b\x4a\xd4\x1e\xca\x73\x68\x24\xd7\x1c\x73\x9a\xe6\x18\xde\x0d\x9a\x74\x67\x98\xe9\xaf\x2e\xaa\xcd\x84\x24\x07\x42\x61\xe7\x70\xbc\xe1\x9c\x02\x62\x56\xa2\x90\x80\xca\x82\x33\x7a\x4c\x40\x2a\x8d\x64\x74\x57\x42\x01\xae\x25\xd1\xc7\x82\x0b\xbd\x78\x55\xa8\xf6\x55\xa1\xc8\x0f\xb0\x7d\xef\x64\xf5\xfd\x40\x6b\x67\x41\xce\x16\x77\xf6\x7b\x2b\xe2\x2f\xb3\x15\xa1\x8e\x0a\xeb\xcb\x6a\x6b\xa5\x4b\xc2\x0a\x2e\x80\x45\x7d\x43\x69\x2e\x8a\x9d\x44\x18\x0a\x01\x92\x70\xaf\x28\xac\x00\x5b\xd6\x12\x35\xf3\x4f\x87\x51\x64\xc7\x90\x3f\xee\x18\x50\x5d\x89\xed\x85\x9b\x00\x5a\xc7\x9d\xbd\xa6\xa4\x22\x61\xa7\xf1\x58\x6d\x42\xbd\xd6\xd5\x6a\xfe\x12\x6d\xa6\x3c\x4b\x0a\xd9\x33\x1d\xc2\x7c\x83\x90\xd0\x19\xec\x91\x3c\x23\x75\xb4\x8e\xb9\x0d\xe4\x27\x5f\xdf\xe0\x5d\x97\x75\x58\xdd\x8e\x77\xd3\x2f\x64\xed\xc5\x9f\x55\x7a\xb9\xcb\x58\x07\xab\x1f\xbf\x53\xd5\x2a\xda\xc4\xb5\x18\xa6\xe6\x1a\x90\x11\x3a\x3d\x75\xcd\xfe\x27\x22\xb4\xa5\xa3\x16\xee\xd1\x4d\x42\x1c\xef\x67\x4a\x8c\x9d\xaf\x1d\xf5\x93\x2b\x02\x83\x06\x73\xa6\x88\xd2\xc0\xb0\x7f\x7f\xd5\x4b\xb4\x21\x93\xc3\x8b\xa9\x50\xe6\xfb\xae\xb4\xae\xab\x45\xa1\x5d\x17\x6f\x93\x1b\x9d\x74\x5f\xed\x0f\xe4\x7f\x09\x2b\x8c\x63\x2e\x02\xaa\x49\x67\xe3\xdc\x34\xeb\x6c\x5d\xcc\xd4\xa1\xa1\x90\xf1\xc4\xe5\x63\x93\x90\x4a\xe2\x8f\x1c\x2b\x87\xe4\x8c\x23\x7d\x67\xaf\x6f\x18\xc0\x77\x56\x6d\x42\xa3\x67\xfb\xf3\xe7\xe6\x3d\x28\x78\xa6\x4d\x14\xda\x38\xe7\x12\xbe\x44\xdb\x64\x06\x79\x88\xe7\x7b\x09\x5a\x12\xe7\x28\x61\x28\x9a\xcc\xdc\x0e\xea\x7d\x6e\xb8\x6b\x52\x01\xaf\xfd\x61\x68\x65\x1a\x4e\x4f\x94\x1b\x67\xfe\x11\xa5\x1a\x48\x57\xa7\x0f\xc6\x01\x52\xd7\x97\x47\x15\x97\x92\xb0\x80\x95\xed\xd1\x46\x52\x76\x93\x20\x28\xc1\x48\xc5\x2a\x88\x2b\x76\x81\x6b\x51\x22\x0d\x45\x7f\x6d\xe4\x9c\x9a\x6d\xa6\x58\x13\x48\x22\x4a\x81\x12\x55\xa5\x14\x3f\x79\x09\x14\x79\xa3\x7f\xb4\xee\x6d\xc9\xb7\x88\xd0\x5a\x42\x81\x70\x30\x4c\x3b\x14\x15\x67\x44\x73\x6f\x38\x49\x9b\xb2\x42\xcf\xc5\x30\x6d\x0b\x89\xb5\x24\x76\x37\x9e\xba\x81\x6b\x58\x42\x97\xbb\xcf\x2b\xab\x67\x54\x74\x2a\xd2\x03\x16\x33\xcc\x38\x61\x5d\x82\x6a\xc2\xce\xb8\xbf\x1e\xa5\x8f\x06\xf8\x7e\x7b\xa0\x10\x9c\x92\xae\x0a\x58\x82\x43\xcc\x59\x27\xe4\x14\x83\xb8\xd2\x02\x1b\x73\x68\x7a\x98\x4a\xe8\xa8\xb3\xb6\x04\x4f\x84\x95\xfc\xe9\x8c\x09\x97\x33\x25\x41\x11\x06\x27\x38\x5e\x2b\x68\xa5\x25\x22\x4c\x9f\x7d\x9c\xe4\x8a\x45\x48\xd8\x82\x04\x36\x35\xf4\x6c\xbe\xac\xcf\xc2\xa5\x7d\x8c\xb7\x38\x87\x3d\x42\x89\xa6\xbe\x7d\x83\x5d\xbd\x6b\x95\x7f\x45\x81\x34\x7a\x71\x24\x91\x8e\xb8\x68\x69\x14\x4a\x9e\x58\xd4\xd1\xa3\xa9\x0a\x2a\x3e\x7f\x0d\xe3\x8a\x8b\xc8\x31\x16\x07\xd8\x02\x85\x42\xd2\x59\x66\x8f\x2a\xb8\x58\x7e\x33\x25\x7e\x5e\xb9\x8e\x87\x6d\x22\x50\xb5\x54\x0c\x49\x3e\xdd\xcd\xbd\x95\x4a\xf6\x0e\xa2\x43\xbd\x61\x81\x5e\xf9\x7d\x47\x07\xfb\xe6\x44\x7b\x31\x23\xa0\xd5\x87\xb1\x0d\xb9\x19\x65\xb5\x4e\x56\x71\xf0\x56\xc4\x72\xeb\x6f\x3b\x22\x77\x07\xd4\xd7\x3a\x21\xad\x11\xde\x27\x75\x59\x67\x96\xd6\x57\xc4\xa1\xc9\x5e\x80\x37\x0c\xf5\xa8\xdf\x51\xe8\xff\xc4\x66\x7f\x9d\x7d\xf5\xdf\x42\x44\xef\xe4\xb7\xa8\x8b\xf3\x78\xc2\x95\xca\x77\xa0\xb3\x37\x56\xc5\x24\x89\x79\x55\xd1\xa3\x7e\xab\xe2\x55\xbd\xc2\x3e\xed\x32\x54\x32\xdd\xfc\x9a\x93\xe4\xb9\x5f\x31\xac\xed\x65\xb8\x30\xcf\x97\x83\x76\x5d\x33\x77\x16\x3e\x40\x02\x9b\xad\xce\xa4\xbd\x10\xe7\x39\x5f\x30\xee\xdf\x7d\x98\xa9\xde\xe6\xae\xce\xbd\x52\xd9\xb3\xc0\x3d\x03\xbf\x4e\x9d\xc6\x78\x90\xee\xf4\xe3\xa8\xb0\xff\x0f\xf4\x93\x4f\xa5\x1a\x3e\xd9\x71\xb2\x39\xfb\xd3\x3e\x59\xea\x3e\x73\x5a\x5b\xf2\x71\x20\xdd\x45\x54\x23\xd1\xae\xcd\xbd\x82\xe0\xcd\x79\xdf\x07\x54\xee\xb9\xd6\xf0\x21\x53\xe0\xa8\x7d\x65\xfe\x6d\x3f\x3a\x5b\xbd\xac\xfe\x1b\x00\x00\xff\xff\x88\x06\xbb\x83\xde\x3b\x00\x00")
+
+func dataConfig_schema_v33JsonBytes() ([]byte, error) {
+ return bindataRead(
+ _dataConfig_schema_v33Json,
+ "data/config_schema_v3.3.json",
+ )
+}
+
+func dataConfig_schema_v33Json() (*asset, error) {
+ bytes, err := dataConfig_schema_v33JsonBytes()
+ if err != nil {
+ return nil, err
+ }
+
+ info := bindataFileInfo{name: "data/config_schema_v3.3.json", size: 0, mode: os.FileMode(0), modTime: time.Unix(0, 0)}
+ a := &asset{bytes: bytes, info: info}
+ return a, nil
+}
+
+// Asset loads and returns the asset for the given name.
+// It returns an error if the asset could not be found or
+// could not be loaded.
+func Asset(name string) ([]byte, error) {
+ cannonicalName := strings.Replace(name, "\\", "/", -1)
+ if f, ok := _bindata[cannonicalName]; ok {
+ a, err := f()
+ if err != nil {
+ return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err)
+ }
+ return a.bytes, nil
+ }
+ return nil, fmt.Errorf("Asset %s not found", name)
+}
+
+// MustAsset is like Asset but panics when Asset would return an error.
+// It simplifies safe initialization of global variables.
+func MustAsset(name string) []byte {
+ a, err := Asset(name)
+ if err != nil {
+ panic("asset: Asset(" + name + "): " + err.Error())
+ }
+
+ return a
+}
+
+// AssetInfo loads and returns the asset info for the given name.
+// It returns an error if the asset could not be found or
+// could not be loaded.
+func AssetInfo(name string) (os.FileInfo, error) {
+ cannonicalName := strings.Replace(name, "\\", "/", -1)
+ if f, ok := _bindata[cannonicalName]; ok {
+ a, err := f()
+ if err != nil {
+ return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err)
+ }
+ return a.info, nil
+ }
+ return nil, fmt.Errorf("AssetInfo %s not found", name)
+}
+
+// AssetNames returns the names of the assets.
+func AssetNames() []string {
+ names := make([]string, 0, len(_bindata))
+ for name := range _bindata {
+ names = append(names, name)
+ }
+ return names
+}
+
+// _bindata is a table, holding each asset generator, mapped to its name.
+var _bindata = map[string]func() (*asset, error){
+ "data/config_schema_v3.0.json": dataConfig_schema_v30Json,
+ "data/config_schema_v3.1.json": dataConfig_schema_v31Json,
+ "data/config_schema_v3.2.json": dataConfig_schema_v32Json,
+ "data/config_schema_v3.3.json": dataConfig_schema_v33Json,
+}
+
+// AssetDir returns the file names below a certain
+// directory embedded in the file by go-bindata.
+// For example if you run go-bindata on data/... and data contains the
+// following hierarchy:
+// data/
+// foo.txt
+// img/
+// a.png
+// b.png
+// then AssetDir("data") would return []string{"foo.txt", "img"}
+// AssetDir("data/img") would return []string{"a.png", "b.png"}
+// AssetDir("foo.txt") and AssetDir("notexist") would return an error
+// AssetDir("") will return []string{"data"}.
+func AssetDir(name string) ([]string, error) {
+ node := _bintree
+ if len(name) != 0 {
+ cannonicalName := strings.Replace(name, "\\", "/", -1)
+ pathList := strings.Split(cannonicalName, "/")
+ for _, p := range pathList {
+ node = node.Children[p]
+ if node == nil {
+ return nil, fmt.Errorf("Asset %s not found", name)
+ }
+ }
+ }
+ if node.Func != nil {
+ return nil, fmt.Errorf("Asset %s not found", name)
+ }
+ rv := make([]string, 0, len(node.Children))
+ for childName := range node.Children {
+ rv = append(rv, childName)
+ }
+ return rv, nil
+}
+
+type bintree struct {
+ Func func() (*asset, error)
+ Children map[string]*bintree
+}
+var _bintree = &bintree{nil, map[string]*bintree{
+ "data": &bintree{nil, map[string]*bintree{
+ "config_schema_v3.0.json": &bintree{dataConfig_schema_v30Json, map[string]*bintree{}},
+ "config_schema_v3.1.json": &bintree{dataConfig_schema_v31Json, map[string]*bintree{}},
+ "config_schema_v3.2.json": &bintree{dataConfig_schema_v32Json, map[string]*bintree{}},
+ "config_schema_v3.3.json": &bintree{dataConfig_schema_v33Json, map[string]*bintree{}},
+ }},
+}}
+
+// RestoreAsset restores an asset under the given directory
+func RestoreAsset(dir, name string) error {
+ data, err := Asset(name)
+ if err != nil {
+ return err
+ }
+ info, err := AssetInfo(name)
+ if err != nil {
+ return err
+ }
+ err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755))
+ if err != nil {
+ return err
+ }
+ err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())
+ if err != nil {
+ return err
+ }
+ err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+// RestoreAssets restores an asset under the given directory recursively
+func RestoreAssets(dir, name string) error {
+ children, err := AssetDir(name)
+ // File
+ if err != nil {
+ return RestoreAsset(dir, name)
+ }
+ // Dir
+ for _, child := range children {
+ err = RestoreAssets(dir, filepath.Join(name, child))
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func _filePath(dir, name string) string {
+ cannonicalName := strings.Replace(name, "\\", "/", -1)
+ return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...)
+}
+
diff --git a/vendor/github.com/docker/cli/cli/compose/schema/schema.go b/vendor/github.com/docker/cli/cli/compose/schema/schema.go
new file mode 100644
index 0000000..9a70dc2
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/compose/schema/schema.go
@@ -0,0 +1,168 @@
+package schema
+
+//go:generate go-bindata -pkg schema -nometadata data
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/pkg/errors"
+ "github.com/xeipuuv/gojsonschema"
+)
+
+const (
+ defaultVersion = "1.0"
+ versionField = "version"
+)
+
+type portsFormatChecker struct{}
+
+func (checker portsFormatChecker) IsFormat(input string) bool {
+ // TODO: implement this
+ return true
+}
+
+type durationFormatChecker struct{}
+
+func (checker durationFormatChecker) IsFormat(input string) bool {
+ _, err := time.ParseDuration(input)
+ return err == nil
+}
+
+func init() {
+ gojsonschema.FormatCheckers.Add("expose", portsFormatChecker{})
+ gojsonschema.FormatCheckers.Add("ports", portsFormatChecker{})
+ gojsonschema.FormatCheckers.Add("duration", durationFormatChecker{})
+}
+
+// Version returns the version of the config, defaulting to version 1.0
+func Version(config map[string]interface{}) string {
+ version, ok := config[versionField]
+ if !ok {
+ return defaultVersion
+ }
+ return normalizeVersion(fmt.Sprintf("%v", version))
+}
+
+func normalizeVersion(version string) string {
+ switch version {
+ case "3":
+ return "3.0"
+ default:
+ return version
+ }
+}
+
+// Validate uses the jsonschema to validate the configuration
+func Validate(config map[string]interface{}, version string) error {
+ schemaData, err := Asset(fmt.Sprintf("data/config_schema_v%s.json", version))
+ if err != nil {
+ return errors.Errorf("unsupported Compose file version: %s", version)
+ }
+
+ schemaLoader := gojsonschema.NewStringLoader(string(schemaData))
+ dataLoader := gojsonschema.NewGoLoader(config)
+
+ result, err := gojsonschema.Validate(schemaLoader, dataLoader)
+ if err != nil {
+ return err
+ }
+
+ if !result.Valid() {
+ return toError(result)
+ }
+
+ return nil
+}
+
+func toError(result *gojsonschema.Result) error {
+ err := getMostSpecificError(result.Errors())
+ return err
+}
+
+const (
+ jsonschemaOneOf = "number_one_of"
+ jsonschemaAnyOf = "number_any_of"
+)
+
+func getDescription(err validationError) string {
+ switch err.parent.Type() {
+ case "invalid_type":
+ if expectedType, ok := err.parent.Details()["expected"].(string); ok {
+ return fmt.Sprintf("must be a %s", humanReadableType(expectedType))
+ }
+ case jsonschemaOneOf, jsonschemaAnyOf:
+ if err.child == nil {
+ return err.parent.Description()
+ }
+ return err.child.Description()
+ }
+ return err.parent.Description()
+}
+
+func humanReadableType(definition string) string {
+ if definition[0:1] == "[" {
+ allTypes := strings.Split(definition[1:len(definition)-1], ",")
+ for i, t := range allTypes {
+ allTypes[i] = humanReadableType(t)
+ }
+ return fmt.Sprintf(
+ "%s or %s",
+ strings.Join(allTypes[0:len(allTypes)-1], ", "),
+ allTypes[len(allTypes)-1],
+ )
+ }
+ if definition == "object" {
+ return "mapping"
+ }
+ if definition == "array" {
+ return "list"
+ }
+ return definition
+}
+
+type validationError struct {
+ parent gojsonschema.ResultError
+ child gojsonschema.ResultError
+}
+
+func (err validationError) Error() string {
+ description := getDescription(err)
+ return fmt.Sprintf("%s %s", err.parent.Field(), description)
+}
+
+func getMostSpecificError(errors []gojsonschema.ResultError) validationError {
+ mostSpecificError := 0
+ for i, err := range errors {
+ if specificity(err) > specificity(errors[mostSpecificError]) {
+ mostSpecificError = i
+ continue
+ }
+
+ if specificity(err) == specificity(errors[mostSpecificError]) {
+ // Invalid type errors win in a tie-breaker for most specific field name
+ if err.Type() == "invalid_type" && errors[mostSpecificError].Type() != "invalid_type" {
+ mostSpecificError = i
+ }
+ }
+ }
+
+ if mostSpecificError+1 == len(errors) {
+ return validationError{parent: errors[mostSpecificError]}
+ }
+
+ switch errors[mostSpecificError].Type() {
+ case "number_one_of", "number_any_of":
+ return validationError{
+ parent: errors[mostSpecificError],
+ child: errors[mostSpecificError+1],
+ }
+ default:
+ return validationError{parent: errors[mostSpecificError]}
+ }
+}
+
+func specificity(err gojsonschema.ResultError) int {
+ return len(strings.Split(err.Field(), "."))
+}
diff --git a/vendor/github.com/docker/cli/cli/compose/template/template.go b/vendor/github.com/docker/cli/cli/compose/template/template.go
new file mode 100644
index 0000000..8426a23
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/compose/template/template.go
@@ -0,0 +1,101 @@
+package template
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+)
+
+var delimiter = "\\$"
+var substitution = "[_a-z][_a-z0-9]*(?::?-[^}]+)?"
+
+var patternString = fmt.Sprintf(
+ "%s(?i:(?P<escaped>%s)|(?P<named>%s)|{(?P<braced>%s)}|(?P<invalid>))",
+ delimiter, delimiter, substitution, substitution,
+)
+
+var pattern = regexp.MustCompile(patternString)
+
+// InvalidTemplateError is returned when a variable template is not in a valid
+// format
+type InvalidTemplateError struct {
+ Template string
+}
+
+func (e InvalidTemplateError) Error() string {
+ return fmt.Sprintf("Invalid template: %#v", e.Template)
+}
+
+// Mapping is a user-supplied function which maps from variable names to values.
+// Returns the value as a string and a bool indicating whether
+// the value is present, to distinguish between an empty string
+// and the absence of a value.
+type Mapping func(string) (string, bool)
+
+// Substitute variables in the string with their values
+func Substitute(template string, mapping Mapping) (string, error) {
+ var err error
+ result := pattern.ReplaceAllStringFunc(template, func(substring string) string {
+ matches := pattern.FindStringSubmatch(substring)
+ groups := make(map[string]string)
+ for i, name := range pattern.SubexpNames() {
+ if i != 0 {
+ groups[name] = matches[i]
+ }
+ }
+
+ substitution := groups["named"]
+ if substitution == "" {
+ substitution = groups["braced"]
+ }
+ if substitution != "" {
+ // Soft default (fall back if unset or empty)
+ if strings.Contains(substitution, ":-") {
+ name, defaultValue := partition(substitution, ":-")
+ value, ok := mapping(name)
+ if !ok || value == "" {
+ return defaultValue
+ }
+ return value
+ }
+
+ // Hard default (fall back if-and-only-if empty)
+ if strings.Contains(substitution, "-") {
+ name, defaultValue := partition(substitution, "-")
+ value, ok := mapping(name)
+ if !ok {
+ return defaultValue
+ }
+ return value
+ }
+
+ // No default (fall back to empty string)
+ value, ok := mapping(substitution)
+ if !ok {
+ return ""
+ }
+ return value
+ }
+
+ if escaped := groups["escaped"]; escaped != "" {
+ return escaped
+ }
+
+ err = &InvalidTemplateError{Template: template}
+ return ""
+ })
+
+ return result, err
+}
+
+// Split the string at the first occurrence of sep, and return the part before the separator,
+// and the part after the separator.
+//
+// If the separator is not found, return the string itself, followed by an empty string.
+func partition(s, sep string) (string, string) {
+ if strings.Contains(s, sep) {
+ parts := strings.SplitN(s, sep, 2)
+ return parts[0], parts[1]
+ }
+ return s, ""
+}
diff --git a/vendor/github.com/docker/cli/cli/compose/types/types.go b/vendor/github.com/docker/cli/cli/compose/types/types.go
new file mode 100644
index 0000000..1eecc12
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/compose/types/types.go
@@ -0,0 +1,337 @@
+package types
+
+import (
+ "time"
+)
+
+// UnsupportedProperties not yet supported by this implementation of the compose file
+var UnsupportedProperties = []string{
+ "build",
+ "cap_add",
+ "cap_drop",
+ "cgroup_parent",
+ "devices",
+ "domainname",
+ "external_links",
+ "ipc",
+ "links",
+ "mac_address",
+ "network_mode",
+ "privileged",
+ "restart",
+ "security_opt",
+ "shm_size",
+ "stop_signal",
+ "sysctls",
+ "tmpfs",
+ "userns_mode",
+}
+
+// DeprecatedProperties that were removed from the v3 format, but their
+// use should not impact the behaviour of the application.
+var DeprecatedProperties = map[string]string{
+ "container_name": "Setting the container name is not supported.",
+ "expose": "Exposing ports is unnecessary - services on the same network can access each other's containers on any port.",
+}
+
+// ForbiddenProperties that are not supported in this implementation of the
+// compose file.
+var ForbiddenProperties = map[string]string{
+ "extends": "Support for `extends` is not implemented yet.",
+ "volume_driver": "Instead of setting the volume driver on the service, define a volume using the top-level `volumes` option and specify the driver there.",
+ "volumes_from": "To share a volume between services, define it using the top-level `volumes` option and reference it from each service that shares it using the service-level `volumes` option.",
+ "cpu_quota": "Set resource limits using deploy.resources",
+ "cpu_shares": "Set resource limits using deploy.resources",
+ "cpuset": "Set resource limits using deploy.resources",
+ "mem_limit": "Set resource limits using deploy.resources",
+ "memswap_limit": "Set resource limits using deploy.resources",
+}
+
+// ConfigFile is a filename and the contents of the file as a Dict
+type ConfigFile struct {
+ Filename string
+ Config map[string]interface{}
+}
+
+// ConfigDetails are the details about a group of ConfigFiles
+type ConfigDetails struct {
+ WorkingDir string
+ ConfigFiles []ConfigFile
+ Environment map[string]string
+}
+
+// LookupEnv provides a lookup function for environment variables
+func (cd ConfigDetails) LookupEnv(key string) (string, bool) {
+ v, ok := cd.Environment[key]
+ return v, ok
+}
+
+// Config is a full compose file configuration
+type Config struct {
+ Services []ServiceConfig
+ Networks map[string]NetworkConfig
+ Volumes map[string]VolumeConfig
+ Secrets map[string]SecretConfig
+ Configs map[string]ConfigObjConfig
+}
+
+// ServiceConfig is the configuration of one service
+type ServiceConfig struct {
+ Name string
+
+ CapAdd []string `mapstructure:"cap_add"`
+ CapDrop []string `mapstructure:"cap_drop"`
+ CgroupParent string `mapstructure:"cgroup_parent"`
+ Command ShellCommand
+ Configs []ServiceConfigObjConfig
+ ContainerName string `mapstructure:"container_name"`
+ CredentialSpec CredentialSpecConfig `mapstructure:"credential_spec"`
+ DependsOn []string `mapstructure:"depends_on"`
+ Deploy DeployConfig
+ Devices []string
+ DNS StringList
+ DNSSearch StringList `mapstructure:"dns_search"`
+ DomainName string `mapstructure:"domainname"`
+ Entrypoint ShellCommand
+ Environment MappingWithEquals
+ EnvFile StringList `mapstructure:"env_file"`
+ Expose StringOrNumberList
+ ExternalLinks []string `mapstructure:"external_links"`
+ ExtraHosts MappingWithColon `mapstructure:"extra_hosts"`
+ Hostname string
+ HealthCheck *HealthCheckConfig
+ Image string
+ Ipc string
+ Labels Labels
+ Links []string
+ Logging *LoggingConfig
+ MacAddress string `mapstructure:"mac_address"`
+ NetworkMode string `mapstructure:"network_mode"`
+ Networks map[string]*ServiceNetworkConfig
+ Pid string
+ Ports []ServicePortConfig
+ Privileged bool
+ ReadOnly bool `mapstructure:"read_only"`
+ Restart string
+ Secrets []ServiceSecretConfig
+ SecurityOpt []string `mapstructure:"security_opt"`
+ StdinOpen bool `mapstructure:"stdin_open"`
+ StopGracePeriod *time.Duration `mapstructure:"stop_grace_period"`
+ StopSignal string `mapstructure:"stop_signal"`
+ Tmpfs StringList
+ Tty bool `mapstructure:"tty"`
+ Ulimits map[string]*UlimitsConfig
+ User string
+ Volumes []ServiceVolumeConfig
+ WorkingDir string `mapstructure:"working_dir"`
+}
+
+// ShellCommand is a string or list of string args
+type ShellCommand []string
+
+// StringList is a type for fields that can be a string or list of strings
+type StringList []string
+
+// StringOrNumberList is a type for fields that can be a list of strings or
+// numbers
+type StringOrNumberList []string
+
+// MappingWithEquals is a mapping type that can be converted from a list of
+// key[=value] strings.
+// For the key with an empty value (`key=`), the mapped value is set to a pointer to `""`.
+// For the key without value (`key`), the mapped value is set to nil.
+type MappingWithEquals map[string]*string
+
+// Labels is a mapping type for labels
+type Labels map[string]string
+
+// MappingWithColon is a mapping type that can be converted from a list of
+// 'key: value' strings
+type MappingWithColon map[string]string
+
+// LoggingConfig the logging configuration for a service
+type LoggingConfig struct {
+ Driver string
+ Options map[string]string
+}
+
+// DeployConfig the deployment configuration for a service
+type DeployConfig struct {
+ Mode string
+ Replicas *uint64
+ Labels Labels
+ UpdateConfig *UpdateConfig `mapstructure:"update_config"`
+ Resources Resources
+ RestartPolicy *RestartPolicy `mapstructure:"restart_policy"`
+ Placement Placement
+ EndpointMode string `mapstructure:"endpoint_mode"`
+}
+
+// HealthCheckConfig the healthcheck configuration for a service
+type HealthCheckConfig struct {
+ Test HealthCheckTest
+ Timeout string
+ Interval string
+ Retries *uint64
+ StartPeriod string
+ Disable bool
+}
+
+// HealthCheckTest is the command run to test the health of a service
+type HealthCheckTest []string
+
+// UpdateConfig the service update configuration
+type UpdateConfig struct {
+ Parallelism *uint64
+ Delay time.Duration
+ FailureAction string `mapstructure:"failure_action"`
+ Monitor time.Duration
+ MaxFailureRatio float32 `mapstructure:"max_failure_ratio"`
+}
+
+// Resources the resource limits and reservations
+type Resources struct {
+ Limits *Resource
+ Reservations *Resource
+}
+
+// Resource is a resource to be limited or reserved
+type Resource struct {
+ // TODO: types to convert from units and ratios
+ NanoCPUs string `mapstructure:"cpus"`
+ MemoryBytes UnitBytes `mapstructure:"memory"`
+}
+
+// UnitBytes is the bytes type
+type UnitBytes int64
+
+// RestartPolicy the service restart policy
+type RestartPolicy struct {
+ Condition string
+ Delay *time.Duration
+ MaxAttempts *uint64 `mapstructure:"max_attempts"`
+ Window *time.Duration
+}
+
+// Placement constraints for the service
+type Placement struct {
+ Constraints []string
+ Preferences []PlacementPreferences
+}
+
+// PlacementPreferences is the preferences for a service placement
+type PlacementPreferences struct {
+ Spread string
+}
+
+// ServiceNetworkConfig is the network configuration for a service
+type ServiceNetworkConfig struct {
+ Aliases []string
+ Ipv4Address string `mapstructure:"ipv4_address"`
+ Ipv6Address string `mapstructure:"ipv6_address"`
+}
+
+// ServicePortConfig is the port configuration for a service
+type ServicePortConfig struct {
+ Mode string
+ Target uint32
+ Published uint32
+ Protocol string
+}
+
+// ServiceVolumeConfig are references to a volume used by a service
+type ServiceVolumeConfig struct {
+ Type string
+ Source string
+ Target string
+ ReadOnly bool `mapstructure:"read_only"`
+ Consistency string
+ Bind *ServiceVolumeBind
+ Volume *ServiceVolumeVolume
+}
+
+// ServiceVolumeBind are options for a service volume of type bind
+type ServiceVolumeBind struct {
+ Propagation string
+}
+
+// ServiceVolumeVolume are options for a service volume of type volume
+type ServiceVolumeVolume struct {
+ NoCopy bool `mapstructure:"nocopy"`
+}
+
+type fileReferenceConfig struct {
+ Source string
+ Target string
+ UID string
+ GID string
+ Mode *uint32
+}
+
+// ServiceConfigObjConfig is the config obj configuration for a service
+type ServiceConfigObjConfig fileReferenceConfig
+
+// ServiceSecretConfig is the secret configuration for a service
+type ServiceSecretConfig fileReferenceConfig
+
+// UlimitsConfig the ulimit configuration
+type UlimitsConfig struct {
+ Single int
+ Soft int
+ Hard int
+}
+
+// NetworkConfig for a network
+type NetworkConfig struct {
+ Driver string
+ DriverOpts map[string]string `mapstructure:"driver_opts"`
+ Ipam IPAMConfig
+ External External
+ Internal bool
+ Attachable bool
+ Labels Labels
+}
+
+// IPAMConfig for a network
+type IPAMConfig struct {
+ Driver string
+ Config []*IPAMPool
+}
+
+// IPAMPool for a network
+type IPAMPool struct {
+ Subnet string
+}
+
+// VolumeConfig for a volume
+type VolumeConfig struct {
+ Driver string
+ DriverOpts map[string]string `mapstructure:"driver_opts"`
+ External External
+ Labels Labels
+}
+
+// External identifies a Volume or Network as a reference to a resource that is
+// not managed, and should already exist.
+type External struct {
+ Name string
+ External bool
+}
+
+// CredentialSpecConfig for credential spec on Windows
+type CredentialSpecConfig struct {
+ File string
+ Registry string
+}
+
+type fileObjectConfig struct {
+ File string
+ External External
+ Labels Labels
+}
+
+// SecretConfig for a secret
+type SecretConfig fileObjectConfig
+
+// ConfigObjConfig is the config for the swarm "Config" object
+type ConfigObjConfig fileObjectConfig
diff --git a/vendor/github.com/docker/cli/cli/config/config.go b/vendor/github.com/docker/cli/cli/config/config.go
new file mode 100644
index 0000000..58c83b6
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/config/config.go
@@ -0,0 +1,120 @@
+package config
+
+import (
+ "io"
+ "os"
+ "path/filepath"
+
+ "github.com/docker/cli/cli/config/configfile"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/pkg/homedir"
+ "github.com/pkg/errors"
+)
+
+const (
+ // ConfigFileName is the name of config file
+ ConfigFileName = "config.json"
+ configFileDir = ".docker"
+ oldConfigfile = ".dockercfg"
+)
+
+var (
+ configDir = os.Getenv("DOCKER_CONFIG")
+)
+
+func init() {
+ if configDir == "" {
+ configDir = filepath.Join(homedir.Get(), configFileDir)
+ }
+}
+
+// Dir returns the directory the configuration file is stored in
+func Dir() string {
+ return configDir
+}
+
+// SetDir sets the directory the configuration file is stored in
+func SetDir(dir string) {
+ configDir = dir
+}
+
+// NewConfigFile initializes an empty configuration file for the given filename 'fn'
+func NewConfigFile(fn string) *configfile.ConfigFile {
+ return &configfile.ConfigFile{
+ AuthConfigs: make(map[string]types.AuthConfig),
+ HTTPHeaders: make(map[string]string),
+ Filename: fn,
+ }
+}
+
+// LegacyLoadFromReader is a convenience function that creates a ConfigFile object from
+// a non-nested reader
+func LegacyLoadFromReader(configData io.Reader) (*configfile.ConfigFile, error) {
+ configFile := configfile.ConfigFile{
+ AuthConfigs: make(map[string]types.AuthConfig),
+ }
+ err := configFile.LegacyLoadFromReader(configData)
+ return &configFile, err
+}
+
+// LoadFromReader is a convenience function that creates a ConfigFile object from
+// a reader
+func LoadFromReader(configData io.Reader) (*configfile.ConfigFile, error) {
+ configFile := configfile.ConfigFile{
+ AuthConfigs: make(map[string]types.AuthConfig),
+ }
+ err := configFile.LoadFromReader(configData)
+ return &configFile, err
+}
+
+// Load reads the configuration files in the given directory, and sets up
+// the auth config information and returns values.
+// FIXME: use the internal golang config parser
+func Load(configDir string) (*configfile.ConfigFile, error) {
+ if configDir == "" {
+ configDir = Dir()
+ }
+
+ configFile := configfile.ConfigFile{
+ AuthConfigs: make(map[string]types.AuthConfig),
+ Filename: filepath.Join(configDir, ConfigFileName),
+ }
+
+ // Try happy path first - latest config file
+ if _, err := os.Stat(configFile.Filename); err == nil {
+ file, err := os.Open(configFile.Filename)
+ if err != nil {
+ return &configFile, errors.Errorf("%s - %v", configFile.Filename, err)
+ }
+ defer file.Close()
+ err = configFile.LoadFromReader(file)
+ if err != nil {
+ err = errors.Errorf("%s - %v", configFile.Filename, err)
+ }
+ return &configFile, err
+ } else if !os.IsNotExist(err) {
+ // if file is there but we can't stat it for any reason other
+ // than it doesn't exist then stop
+ return &configFile, errors.Errorf("%s - %v", configFile.Filename, err)
+ }
+
+ // Can't find latest config file so check for the old one
+ confFile := filepath.Join(homedir.Get(), oldConfigfile)
+ if _, err := os.Stat(confFile); err != nil {
+ return &configFile, nil //missing file is not an error
+ }
+ file, err := os.Open(confFile)
+ if err != nil {
+ return &configFile, errors.Errorf("%s - %v", confFile, err)
+ }
+ defer file.Close()
+ err = configFile.LegacyLoadFromReader(file)
+ if err != nil {
+ return &configFile, errors.Errorf("%s - %v", confFile, err)
+ }
+
+ if configFile.HTTPHeaders == nil {
+ configFile.HTTPHeaders = map[string]string{}
+ }
+ return &configFile, nil
+}
diff --git a/vendor/github.com/docker/cli/cli/config/configfile/file.go b/vendor/github.com/docker/cli/cli/config/configfile/file.go
new file mode 100644
index 0000000..9c2c4ee
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/config/configfile/file.go
@@ -0,0 +1,233 @@
+package configfile
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/docker/cli/opts"
+ "github.com/docker/docker/api/types"
+ "github.com/pkg/errors"
+)
+
+const (
+ // This constant is only used for really old config files when the
+ // URL wasn't saved as part of the config file and it was just
+ // assumed to be this value.
+ defaultIndexserver = "https://index.docker.io/v1/"
+)
+
+// ConfigFile ~/.docker/config.json file info
+type ConfigFile struct {
+ AuthConfigs map[string]types.AuthConfig `json:"auths"`
+ HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"`
+ PsFormat string `json:"psFormat,omitempty"`
+ ImagesFormat string `json:"imagesFormat,omitempty"`
+ NetworksFormat string `json:"networksFormat,omitempty"`
+ PluginsFormat string `json:"pluginsFormat,omitempty"`
+ VolumesFormat string `json:"volumesFormat,omitempty"`
+ StatsFormat string `json:"statsFormat,omitempty"`
+ DetachKeys string `json:"detachKeys,omitempty"`
+ CredentialsStore string `json:"credsStore,omitempty"`
+ CredentialHelpers map[string]string `json:"credHelpers,omitempty"`
+ Filename string `json:"-"` // Note: for internal use only
+ ServiceInspectFormat string `json:"serviceInspectFormat,omitempty"`
+ ServicesFormat string `json:"servicesFormat,omitempty"`
+ TasksFormat string `json:"tasksFormat,omitempty"`
+ SecretFormat string `json:"secretFormat,omitempty"`
+ ConfigFormat string `json:"configFormat,omitempty"`
+ NodesFormat string `json:"nodesFormat,omitempty"`
+ PruneFilters []string `json:"pruneFilters,omitempty"`
+ Proxies map[string]ProxyConfig `json:"proxies,omitempty"`
+}
+
+// ProxyConfig contains proxy configuration settings
+type ProxyConfig struct {
+ HTTPProxy string `json:"httpProxy,omitempty"`
+ HTTPSProxy string `json:"httpsProxy,omitempty"`
+ NoProxy string `json:"noProxy,omitempty"`
+ FTPProxy string `json:"ftpProxy,omitempty"`
+}
+
+// LegacyLoadFromReader reads the non-nested configuration data given and sets up the
+// auth config information with given directory and populates the receiver object
+func (configFile *ConfigFile) LegacyLoadFromReader(configData io.Reader) error {
+ b, err := ioutil.ReadAll(configData)
+ if err != nil {
+ return err
+ }
+
+ if err := json.Unmarshal(b, &configFile.AuthConfigs); err != nil {
+ arr := strings.Split(string(b), "\n")
+ if len(arr) < 2 {
+ return errors.Errorf("The Auth config file is empty")
+ }
+ authConfig := types.AuthConfig{}
+ origAuth := strings.Split(arr[0], " = ")
+ if len(origAuth) != 2 {
+ return errors.Errorf("Invalid Auth config file")
+ }
+ authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1])
+ if err != nil {
+ return err
+ }
+ authConfig.ServerAddress = defaultIndexserver
+ configFile.AuthConfigs[defaultIndexserver] = authConfig
+ } else {
+ for k, authConfig := range configFile.AuthConfigs {
+ authConfig.Username, authConfig.Password, err = decodeAuth(authConfig.Auth)
+ if err != nil {
+ return err
+ }
+ authConfig.Auth = ""
+ authConfig.ServerAddress = k
+ configFile.AuthConfigs[k] = authConfig
+ }
+ }
+ return nil
+}
+
+// LoadFromReader reads the configuration data given and sets up the auth config
+// information with given directory and populates the receiver object
+func (configFile *ConfigFile) LoadFromReader(configData io.Reader) error {
+ if err := json.NewDecoder(configData).Decode(&configFile); err != nil {
+ return err
+ }
+ var err error
+ for addr, ac := range configFile.AuthConfigs {
+ ac.Username, ac.Password, err = decodeAuth(ac.Auth)
+ if err != nil {
+ return err
+ }
+ ac.Auth = ""
+ ac.ServerAddress = addr
+ configFile.AuthConfigs[addr] = ac
+ }
+ return nil
+}
+
+// ContainsAuth returns whether there is authentication configured
+// in this file or not.
+func (configFile *ConfigFile) ContainsAuth() bool {
+ return configFile.CredentialsStore != "" ||
+ len(configFile.CredentialHelpers) > 0 ||
+ len(configFile.AuthConfigs) > 0
+}
+
+// SaveToWriter encodes and writes out all the authorization information to
+// the given writer
+func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error {
+ // Encode sensitive data into a new/temp struct
+ tmpAuthConfigs := make(map[string]types.AuthConfig, len(configFile.AuthConfigs))
+ for k, authConfig := range configFile.AuthConfigs {
+ authCopy := authConfig
+ // encode and save the authstring, while blanking out the original fields
+ authCopy.Auth = encodeAuth(&authCopy)
+ authCopy.Username = ""
+ authCopy.Password = ""
+ authCopy.ServerAddress = ""
+ tmpAuthConfigs[k] = authCopy
+ }
+
+ saveAuthConfigs := configFile.AuthConfigs
+ configFile.AuthConfigs = tmpAuthConfigs
+ defer func() { configFile.AuthConfigs = saveAuthConfigs }()
+
+ data, err := json.MarshalIndent(configFile, "", "\t")
+ if err != nil {
+ return err
+ }
+ _, err = writer.Write(data)
+ return err
+}
+
+// Save encodes and writes out all the authorization information
+func (configFile *ConfigFile) Save() error {
+ if configFile.Filename == "" {
+ return errors.Errorf("Can't save config with empty filename")
+ }
+
+ if err := os.MkdirAll(filepath.Dir(configFile.Filename), 0700); err != nil {
+ return err
+ }
+ f, err := os.OpenFile(configFile.Filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ return configFile.SaveToWriter(f)
+}
+
+// ParseProxyConfig computes proxy configuration by retreiving the config for the provided host and
+// then checking this against any environment variables provided to the container
+func (configFile *ConfigFile) ParseProxyConfig(host string, runOpts []string) map[string]*string {
+ var cfgKey string
+
+ if _, ok := configFile.Proxies[host]; !ok {
+ cfgKey = "default"
+ } else {
+ cfgKey = host
+ }
+
+ config := configFile.Proxies[cfgKey]
+ permitted := map[string]*string{
+ "HTTP_PROXY": &config.HTTPProxy,
+ "HTTPS_PROXY": &config.HTTPSProxy,
+ "NO_PROXY": &config.NoProxy,
+ "FTP_PROXY": &config.FTPProxy,
+ }
+ m := opts.ConvertKVStringsToMapWithNil(runOpts)
+ for k := range permitted {
+ if *permitted[k] == "" {
+ continue
+ }
+ if _, ok := m[k]; !ok {
+ m[k] = permitted[k]
+ }
+ if _, ok := m[strings.ToLower(k)]; !ok {
+ m[strings.ToLower(k)] = permitted[k]
+ }
+ }
+ return m
+}
+
+// encodeAuth creates a base64 encoded string to containing authorization information
+func encodeAuth(authConfig *types.AuthConfig) string {
+ if authConfig.Username == "" && authConfig.Password == "" {
+ return ""
+ }
+
+ authStr := authConfig.Username + ":" + authConfig.Password
+ msg := []byte(authStr)
+ encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
+ base64.StdEncoding.Encode(encoded, msg)
+ return string(encoded)
+}
+
+// decodeAuth decodes a base64 encoded string and returns username and password
+func decodeAuth(authStr string) (string, string, error) {
+ if authStr == "" {
+ return "", "", nil
+ }
+
+ decLen := base64.StdEncoding.DecodedLen(len(authStr))
+ decoded := make([]byte, decLen)
+ authByte := []byte(authStr)
+ n, err := base64.StdEncoding.Decode(decoded, authByte)
+ if err != nil {
+ return "", "", err
+ }
+ if n > decLen {
+ return "", "", errors.Errorf("Something went wrong decoding auth config")
+ }
+ arr := strings.SplitN(string(decoded), ":", 2)
+ if len(arr) != 2 {
+ return "", "", errors.Errorf("Invalid auth configuration file")
+ }
+ password := strings.Trim(arr[1], "\x00")
+ return arr[0], password, nil
+}
diff --git a/vendor/github.com/docker/cli/cli/config/credentials/credentials.go b/vendor/github.com/docker/cli/cli/config/credentials/credentials.go
new file mode 100644
index 0000000..ca874ca
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/config/credentials/credentials.go
@@ -0,0 +1,17 @@
+package credentials
+
+import (
+ "github.com/docker/docker/api/types"
+)
+
+// Store is the interface that any credentials store must implement.
+type Store interface {
+ // Erase removes credentials from the store for a given server.
+ Erase(serverAddress string) error
+ // Get retrieves credentials from the store for a given server.
+ Get(serverAddress string) (types.AuthConfig, error)
+ // GetAll retrieves all the credentials from the store.
+ GetAll() (map[string]types.AuthConfig, error)
+ // Store saves credentials in the store.
+ Store(authConfig types.AuthConfig) error
+}
diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store.go
new file mode 100644
index 0000000..dc080db
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/config/credentials/default_store.go
@@ -0,0 +1,22 @@
+package credentials
+
+import (
+ "os/exec"
+
+ "github.com/docker/cli/cli/config/configfile"
+)
+
+// DetectDefaultStore sets the default credentials store
+// if the host includes the default store helper program.
+func DetectDefaultStore(c *configfile.ConfigFile) {
+ if c.CredentialsStore != "" {
+ // user defined
+ return
+ }
+
+ if defaultCredentialsStore != "" {
+ if _, err := exec.LookPath(remoteCredentialsPrefix + defaultCredentialsStore); err == nil {
+ c.CredentialsStore = defaultCredentialsStore
+ }
+ }
+}
diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go
new file mode 100644
index 0000000..63e8ed4
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go
@@ -0,0 +1,3 @@
+package credentials
+
+const defaultCredentialsStore = "osxkeychain"
diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go
new file mode 100644
index 0000000..864c540
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go
@@ -0,0 +1,3 @@
+package credentials
+
+const defaultCredentialsStore = "secretservice"
diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go
new file mode 100644
index 0000000..519ef53
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go
@@ -0,0 +1,5 @@
+// +build !windows,!darwin,!linux
+
+package credentials
+
+const defaultCredentialsStore = ""
diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go
new file mode 100644
index 0000000..fb6a974
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go
@@ -0,0 +1,3 @@
+package credentials
+
+const defaultCredentialsStore = "wincred"
diff --git a/vendor/github.com/docker/cli/cli/config/credentials/file_store.go b/vendor/github.com/docker/cli/cli/config/credentials/file_store.go
new file mode 100644
index 0000000..4e3325c
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/config/credentials/file_store.go
@@ -0,0 +1,53 @@
+package credentials
+
+import (
+ "github.com/docker/cli/cli/config/configfile"
+ "github.com/docker/docker/api/types"
+ "github.com/docker/docker/registry"
+)
+
+// fileStore implements a credentials store using
+// the docker configuration file to keep the credentials in plain text.
+type fileStore struct {
+ file *configfile.ConfigFile
+}
+
+// NewFileStore creates a new file credentials store.
+func NewFileStore(file *configfile.ConfigFile) Store {
+ return &fileStore{
+ file: file,
+ }
+}
+
+// Erase removes the given credentials from the file store.
+func (c *fileStore) Erase(serverAddress string) error {
+ delete(c.file.AuthConfigs, serverAddress)
+ return c.file.Save()
+}
+
+// Get retrieves credentials for a specific server from the file store.
+func (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) {
+ authConfig, ok := c.file.AuthConfigs[serverAddress]
+ if !ok {
+ // Maybe they have a legacy config file, we will iterate the keys converting
+ // them to the new format and testing
+ for r, ac := range c.file.AuthConfigs {
+ if serverAddress == registry.ConvertToHostname(r) {
+ return ac, nil
+ }
+ }
+
+ authConfig = types.AuthConfig{}
+ }
+ return authConfig, nil
+}
+
+func (c *fileStore) GetAll() (map[string]types.AuthConfig, error) {
+ return c.file.AuthConfigs, nil
+}
+
+// Store saves the given credentials in the file store.
+func (c *fileStore) Store(authConfig types.AuthConfig) error {
+ c.file.AuthConfigs[authConfig.ServerAddress] = authConfig
+ return c.file.Save()
+}
diff --git a/vendor/github.com/docker/cli/cli/config/credentials/native_store.go b/vendor/github.com/docker/cli/cli/config/credentials/native_store.go
new file mode 100644
index 0000000..cef34db
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/config/credentials/native_store.go
@@ -0,0 +1,144 @@
+package credentials
+
+import (
+ "github.com/docker/cli/cli/config/configfile"
+ "github.com/docker/docker-credential-helpers/client"
+ "github.com/docker/docker-credential-helpers/credentials"
+ "github.com/docker/docker/api/types"
+)
+
+const (
+ remoteCredentialsPrefix = "docker-credential-"
+ tokenUsername = "<token>"
+)
+
+// nativeStore implements a credentials store
+// using native keychain to keep credentials secure.
+// It piggybacks into a file store to keep users' emails.
+type nativeStore struct {
+ programFunc client.ProgramFunc
+ fileStore Store
+}
+
+// NewNativeStore creates a new native store that
+// uses a remote helper program to manage credentials.
+func NewNativeStore(file *configfile.ConfigFile, helperSuffix string) Store {
+ name := remoteCredentialsPrefix + helperSuffix
+ return &nativeStore{
+ programFunc: client.NewShellProgramFunc(name),
+ fileStore: NewFileStore(file),
+ }
+}
+
+// Erase removes the given credentials from the native store.
+func (c *nativeStore) Erase(serverAddress string) error {
+ if err := client.Erase(c.programFunc, serverAddress); err != nil {
+ return err
+ }
+
+ // Fallback to plain text store to remove email
+ return c.fileStore.Erase(serverAddress)
+}
+
+// Get retrieves credentials for a specific server from the native store.
+func (c *nativeStore) Get(serverAddress string) (types.AuthConfig, error) {
+ // load user email if it exist or an empty auth config.
+ auth, _ := c.fileStore.Get(serverAddress)
+
+ creds, err := c.getCredentialsFromStore(serverAddress)
+ if err != nil {
+ return auth, err
+ }
+ auth.Username = creds.Username
+ auth.IdentityToken = creds.IdentityToken
+ auth.Password = creds.Password
+
+ return auth, nil
+}
+
+// GetAll retrieves all the credentials from the native store.
+func (c *nativeStore) GetAll() (map[string]types.AuthConfig, error) {
+ auths, err := c.listCredentialsInStore()
+ if err != nil {
+ return nil, err
+ }
+
+ // Emails are only stored in the file store.
+ // This call can be safely eliminated when emails are removed.
+ fileConfigs, _ := c.fileStore.GetAll()
+
+ authConfigs := make(map[string]types.AuthConfig)
+ for registry := range auths {
+ creds, err := c.getCredentialsFromStore(registry)
+ if err != nil {
+ return nil, err
+ }
+ ac := fileConfigs[registry] // might contain Email
+ ac.Username = creds.Username
+ ac.Password = creds.Password
+ ac.IdentityToken = creds.IdentityToken
+ authConfigs[registry] = ac
+ }
+
+ return authConfigs, nil
+}
+
+// Store saves the given credentials in the file store.
+func (c *nativeStore) Store(authConfig types.AuthConfig) error {
+ if err := c.storeCredentialsInStore(authConfig); err != nil {
+ return err
+ }
+ authConfig.Username = ""
+ authConfig.Password = ""
+ authConfig.IdentityToken = ""
+
+ // Fallback to old credential in plain text to save only the email
+ return c.fileStore.Store(authConfig)
+}
+
+// storeCredentialsInStore executes the command to store the credentials in the native store.
+func (c *nativeStore) storeCredentialsInStore(config types.AuthConfig) error {
+ creds := &credentials.Credentials{
+ ServerURL: config.ServerAddress,
+ Username: config.Username,
+ Secret: config.Password,
+ }
+
+ if config.IdentityToken != "" {
+ creds.Username = tokenUsername
+ creds.Secret = config.IdentityToken
+ }
+
+ return client.Store(c.programFunc, creds)
+}
+
+// getCredentialsFromStore executes the command to get the credentials from the native store.
+func (c *nativeStore) getCredentialsFromStore(serverAddress string) (types.AuthConfig, error) {
+ var ret types.AuthConfig
+
+ creds, err := client.Get(c.programFunc, serverAddress)
+ if err != nil {
+ if credentials.IsErrCredentialsNotFound(err) {
+ // do not return an error if the credentials are not
+ // in the keychain. Let docker ask for new credentials.
+ return ret, nil
+ }
+ return ret, err
+ }
+
+ if creds.Username == tokenUsername {
+ ret.IdentityToken = creds.Secret
+ } else {
+ ret.Password = creds.Secret
+ ret.Username = creds.Username
+ }
+
+ ret.ServerAddress = serverAddress
+ return ret, nil
+}
+
+// listCredentialsInStore returns a listing of stored credentials as a map of
+// URL -> username.
+func (c *nativeStore) listCredentialsInStore() (map[string]string, error) {
+ return client.List(c.programFunc)
+}
diff --git a/vendor/github.com/docker/cli/cli/debug/debug.go b/vendor/github.com/docker/cli/cli/debug/debug.go
new file mode 100644
index 0000000..51dfab2
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/debug/debug.go
@@ -0,0 +1,26 @@
+package debug
+
+import (
+ "os"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// Enable sets the DEBUG env var to true
+// and makes the logger to log at debug level.
+func Enable() {
+ os.Setenv("DEBUG", "1")
+ logrus.SetLevel(logrus.DebugLevel)
+}
+
+// Disable sets the DEBUG env var to false
+// and makes the logger to log at info level.
+func Disable() {
+ os.Setenv("DEBUG", "")
+ logrus.SetLevel(logrus.InfoLevel)
+}
+
+// IsEnabled checks whether the debug flag is set or not.
+func IsEnabled() bool {
+ return os.Getenv("DEBUG") != ""
+}
diff --git a/vendor/github.com/docker/cli/cli/error.go b/vendor/github.com/docker/cli/cli/error.go
new file mode 100644
index 0000000..62f6243
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/error.go
@@ -0,0 +1,33 @@
+package cli
+
+import (
+ "fmt"
+ "strings"
+)
+
+// Errors is a list of errors.
+// Useful in a loop if you don't want to return the error right away and you want to display after the loop,
+// all the errors that happened during the loop.
+type Errors []error
+
+func (errList Errors) Error() string {
+ if len(errList) < 1 {
+ return ""
+ }
+
+ out := make([]string, len(errList))
+ for i := range errList {
+ out[i] = errList[i].Error()
+ }
+ return strings.Join(out, ", ")
+}
+
+// StatusError reports an unsuccessful exit by a command.
+type StatusError struct {
+ Status string
+ StatusCode int
+}
+
+func (e StatusError) Error() string {
+ return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode)
+}
diff --git a/vendor/github.com/docker/cli/cli/flags/client.go b/vendor/github.com/docker/cli/cli/flags/client.go
new file mode 100644
index 0000000..9b6940f
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/flags/client.go
@@ -0,0 +1,13 @@
+package flags
+
+// ClientOptions are the options used to configure the client cli
+type ClientOptions struct {
+ Common *CommonOptions
+ ConfigDir string
+ Version bool
+}
+
+// NewClientOptions returns a new ClientOptions
+func NewClientOptions() *ClientOptions {
+ return &ClientOptions{Common: NewCommonOptions()}
+}
diff --git a/vendor/github.com/docker/cli/cli/flags/common.go b/vendor/github.com/docker/cli/cli/flags/common.go
new file mode 100644
index 0000000..ca402ef
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/flags/common.go
@@ -0,0 +1,117 @@
+package flags
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/Sirupsen/logrus"
+ cliconfig "github.com/docker/cli/cli/config"
+ "github.com/docker/cli/opts"
+ "github.com/docker/go-connections/tlsconfig"
+ "github.com/spf13/pflag"
+)
+
+const (
+ // DefaultCaFile is the default filename for the CA pem file
+ DefaultCaFile = "ca.pem"
+ // DefaultKeyFile is the default filename for the key pem file
+ DefaultKeyFile = "key.pem"
+ // DefaultCertFile is the default filename for the cert pem file
+ DefaultCertFile = "cert.pem"
+ // FlagTLSVerify is the flag name for the TLS verification option
+ FlagTLSVerify = "tlsverify"
+)
+
+var (
+ dockerCertPath = os.Getenv("DOCKER_CERT_PATH")
+ dockerTLSVerify = os.Getenv("DOCKER_TLS_VERIFY") != ""
+)
+
+// CommonOptions are options common to both the client and the daemon.
+type CommonOptions struct {
+ Debug bool
+ Hosts []string
+ LogLevel string
+ TLS bool
+ TLSVerify bool
+ TLSOptions *tlsconfig.Options
+}
+
+// NewCommonOptions returns a new CommonOptions
+func NewCommonOptions() *CommonOptions {
+ return &CommonOptions{}
+}
+
+// InstallFlags adds flags for the common options on the FlagSet
+func (commonOpts *CommonOptions) InstallFlags(flags *pflag.FlagSet) {
+ if dockerCertPath == "" {
+ dockerCertPath = cliconfig.Dir()
+ }
+
+ flags.BoolVarP(&commonOpts.Debug, "debug", "D", false, "Enable debug mode")
+ flags.StringVarP(&commonOpts.LogLevel, "log-level", "l", "info", `Set the logging level ("debug"|"info"|"warn"|"error"|"fatal")`)
+ flags.BoolVar(&commonOpts.TLS, "tls", false, "Use TLS; implied by --tlsverify")
+ flags.BoolVar(&commonOpts.TLSVerify, FlagTLSVerify, dockerTLSVerify, "Use TLS and verify the remote")
+
+ // TODO use flag flags.String("identity"}, "i", "", "Path to libtrust key file")
+
+ commonOpts.TLSOptions = &tlsconfig.Options{
+ CAFile: filepath.Join(dockerCertPath, DefaultCaFile),
+ CertFile: filepath.Join(dockerCertPath, DefaultCertFile),
+ KeyFile: filepath.Join(dockerCertPath, DefaultKeyFile),
+ }
+ tlsOptions := commonOpts.TLSOptions
+ flags.Var(opts.NewQuotedString(&tlsOptions.CAFile), "tlscacert", "Trust certs signed only by this CA")
+ flags.Var(opts.NewQuotedString(&tlsOptions.CertFile), "tlscert", "Path to TLS certificate file")
+ flags.Var(opts.NewQuotedString(&tlsOptions.KeyFile), "tlskey", "Path to TLS key file")
+
+ hostOpt := opts.NewNamedListOptsRef("hosts", &commonOpts.Hosts, opts.ValidateHost)
+ flags.VarP(hostOpt, "host", "H", "Daemon socket(s) to connect to")
+}
+
+// SetDefaultOptions sets default values for options after flag parsing is
+// complete
+func (commonOpts *CommonOptions) SetDefaultOptions(flags *pflag.FlagSet) {
+ // Regardless of whether the user sets it to true or false, if they
+ // specify --tlsverify at all then we need to turn on TLS
+ // TLSVerify can be true even if not set due to DOCKER_TLS_VERIFY env var, so we need
+ // to check that here as well
+ if flags.Changed(FlagTLSVerify) || commonOpts.TLSVerify {
+ commonOpts.TLS = true
+ }
+
+ if !commonOpts.TLS {
+ commonOpts.TLSOptions = nil
+ } else {
+ tlsOptions := commonOpts.TLSOptions
+ tlsOptions.InsecureSkipVerify = !commonOpts.TLSVerify
+
+ // Reset CertFile and KeyFile to empty string if the user did not specify
+ // the respective flags and the respective default files were not found.
+ if !flags.Changed("tlscert") {
+ if _, err := os.Stat(tlsOptions.CertFile); os.IsNotExist(err) {
+ tlsOptions.CertFile = ""
+ }
+ }
+ if !flags.Changed("tlskey") {
+ if _, err := os.Stat(tlsOptions.KeyFile); os.IsNotExist(err) {
+ tlsOptions.KeyFile = ""
+ }
+ }
+ }
+}
+
+// SetLogLevel sets the logrus logging level
+func SetLogLevel(logLevel string) {
+ if logLevel != "" {
+ lvl, err := logrus.ParseLevel(logLevel)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", logLevel)
+ os.Exit(1)
+ }
+ logrus.SetLevel(lvl)
+ } else {
+ logrus.SetLevel(logrus.InfoLevel)
+ }
+}
diff --git a/vendor/github.com/docker/cli/cli/required.go b/vendor/github.com/docker/cli/cli/required.go
new file mode 100644
index 0000000..d28af86
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/required.go
@@ -0,0 +1,96 @@
+package cli
+
+import (
+ "strings"
+
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+)
+
+// NoArgs validates args and returns an error if there are any args
+func NoArgs(cmd *cobra.Command, args []string) error {
+ if len(args) == 0 {
+ return nil
+ }
+
+ if cmd.HasSubCommands() {
+ return errors.Errorf("\n" + strings.TrimRight(cmd.UsageString(), "\n"))
+ }
+
+ return errors.Errorf(
+ "\"%s\" accepts no argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
+ cmd.CommandPath(),
+ cmd.CommandPath(),
+ cmd.UseLine(),
+ cmd.Short,
+ )
+}
+
+// RequiresMinArgs returns an error if there is not at least min args
+func RequiresMinArgs(min int) cobra.PositionalArgs {
+ return func(cmd *cobra.Command, args []string) error {
+ if len(args) >= min {
+ return nil
+ }
+ return errors.Errorf(
+ "\"%s\" requires at least %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
+ cmd.CommandPath(),
+ min,
+ cmd.CommandPath(),
+ cmd.UseLine(),
+ cmd.Short,
+ )
+ }
+}
+
+// RequiresMaxArgs returns an error if there is not at most max args
+func RequiresMaxArgs(max int) cobra.PositionalArgs {
+ return func(cmd *cobra.Command, args []string) error {
+ if len(args) <= max {
+ return nil
+ }
+ return errors.Errorf(
+ "\"%s\" requires at most %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
+ cmd.CommandPath(),
+ max,
+ cmd.CommandPath(),
+ cmd.UseLine(),
+ cmd.Short,
+ )
+ }
+}
+
+// RequiresRangeArgs returns an error if there is not at least min args and at most max args
+func RequiresRangeArgs(min int, max int) cobra.PositionalArgs {
+ return func(cmd *cobra.Command, args []string) error {
+ if len(args) >= min && len(args) <= max {
+ return nil
+ }
+ return errors.Errorf(
+ "\"%s\" requires at least %d and at most %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
+ cmd.CommandPath(),
+ min,
+ max,
+ cmd.CommandPath(),
+ cmd.UseLine(),
+ cmd.Short,
+ )
+ }
+}
+
+// ExactArgs returns an error if there is not the exact number of args
+func ExactArgs(number int) cobra.PositionalArgs {
+ return func(cmd *cobra.Command, args []string) error {
+ if len(args) == number {
+ return nil
+ }
+ return errors.Errorf(
+ "\"%s\" requires exactly %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
+ cmd.CommandPath(),
+ number,
+ cmd.CommandPath(),
+ cmd.UseLine(),
+ cmd.Short,
+ )
+ }
+}
diff --git a/vendor/github.com/docker/cli/cli/trust/trust.go b/vendor/github.com/docker/cli/cli/trust/trust.go
new file mode 100644
index 0000000..600a2ac
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/trust/trust.go
@@ -0,0 +1,232 @@
+package trust
+
+import (
+ "encoding/json"
+ "net"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "path/filepath"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli/command"
+ cliconfig "github.com/docker/cli/cli/config"
+ "github.com/docker/distribution/registry/client/auth"
+ "github.com/docker/distribution/registry/client/auth/challenge"
+ "github.com/docker/distribution/registry/client/transport"
+ "github.com/docker/docker/api/types"
+ registrytypes "github.com/docker/docker/api/types/registry"
+ "github.com/docker/docker/registry"
+ "github.com/docker/go-connections/tlsconfig"
+ "github.com/docker/notary"
+ "github.com/docker/notary/client"
+ "github.com/docker/notary/passphrase"
+ "github.com/docker/notary/storage"
+ "github.com/docker/notary/trustmanager"
+ "github.com/docker/notary/trustpinning"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/signed"
+ "github.com/pkg/errors"
+)
+
+var (
+ // ReleasesRole is the role named "releases"
+ ReleasesRole = path.Join(data.CanonicalTargetsRole, "releases")
+)
+
+func trustDirectory() string {
+ return filepath.Join(cliconfig.Dir(), "trust")
+}
+
+// certificateDirectory returns the directory containing
+// TLS certificates for the given server. An error is
+// returned if there was an error parsing the server string.
+func certificateDirectory(server string) (string, error) {
+ u, err := url.Parse(server)
+ if err != nil {
+ return "", err
+ }
+
+ return filepath.Join(cliconfig.Dir(), "tls", u.Host), nil
+}
+
+// Server returns the base URL for the trust server.
+func Server(index *registrytypes.IndexInfo) (string, error) {
+ if s := os.Getenv("DOCKER_CONTENT_TRUST_SERVER"); s != "" {
+ urlObj, err := url.Parse(s)
+ if err != nil || urlObj.Scheme != "https" {
+ return "", errors.Errorf("valid https URL required for trust server, got %s", s)
+ }
+
+ return s, nil
+ }
+ if index.Official {
+ return registry.NotaryServer, nil
+ }
+ return "https://" + index.Name, nil
+}
+
+type simpleCredentialStore struct {
+ auth types.AuthConfig
+}
+
+func (scs simpleCredentialStore) Basic(u *url.URL) (string, string) {
+ return scs.auth.Username, scs.auth.Password
+}
+
+func (scs simpleCredentialStore) RefreshToken(u *url.URL, service string) string {
+ return scs.auth.IdentityToken
+}
+
+func (scs simpleCredentialStore) SetRefreshToken(*url.URL, string, string) {
+}
+
+// GetNotaryRepository returns a NotaryRepository which stores all the
+// information needed to operate on a notary repository.
+// It creates an HTTP transport providing authentication support.
+func GetNotaryRepository(streams command.Streams, repoInfo *registry.RepositoryInfo, authConfig types.AuthConfig, actions ...string) (*client.NotaryRepository, error) {
+ server, err := Server(repoInfo.Index)
+ if err != nil {
+ return nil, err
+ }
+
+ var cfg = tlsconfig.ClientDefault()
+ cfg.InsecureSkipVerify = !repoInfo.Index.Secure
+
+ // Get certificate base directory
+ certDir, err := certificateDirectory(server)
+ if err != nil {
+ return nil, err
+ }
+ logrus.Debugf("reading certificate directory: %s", certDir)
+
+ if err := registry.ReadCertsDirectory(cfg, certDir); err != nil {
+ return nil, err
+ }
+
+ base := &http.Transport{
+ Proxy: http.ProxyFromEnvironment,
+ Dial: (&net.Dialer{
+ Timeout: 30 * time.Second,
+ KeepAlive: 30 * time.Second,
+ DualStack: true,
+ }).Dial,
+ TLSHandshakeTimeout: 10 * time.Second,
+ TLSClientConfig: cfg,
+ DisableKeepAlives: true,
+ }
+
+ // Skip configuration headers since request is not going to Docker daemon
+ modifiers := registry.DockerHeaders(command.UserAgent(), http.Header{})
+ authTransport := transport.NewTransport(base, modifiers...)
+ pingClient := &http.Client{
+ Transport: authTransport,
+ Timeout: 5 * time.Second,
+ }
+ endpointStr := server + "/v2/"
+ req, err := http.NewRequest("GET", endpointStr, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ challengeManager := challenge.NewSimpleManager()
+
+ resp, err := pingClient.Do(req)
+ if err != nil {
+ // Ignore error on ping to operate in offline mode
+ logrus.Debugf("Error pinging notary server %q: %s", endpointStr, err)
+ } else {
+ defer resp.Body.Close()
+
+ // Add response to the challenge manager to parse out
+ // authentication header and register authentication method
+ if err := challengeManager.AddResponse(resp); err != nil {
+ return nil, err
+ }
+ }
+
+ scope := auth.RepositoryScope{
+ Repository: repoInfo.Name.Name(),
+ Actions: actions,
+ Class: repoInfo.Class,
+ }
+ creds := simpleCredentialStore{auth: authConfig}
+ tokenHandlerOptions := auth.TokenHandlerOptions{
+ Transport: authTransport,
+ Credentials: creds,
+ Scopes: []auth.Scope{scope},
+ ClientID: registry.AuthClientID,
+ }
+ tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions)
+ basicHandler := auth.NewBasicHandler(creds)
+ modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler))
+ tr := transport.NewTransport(base, modifiers...)
+
+ return client.NewNotaryRepository(
+ trustDirectory(),
+ repoInfo.Name.Name(),
+ server,
+ tr,
+ getPassphraseRetriever(streams),
+ trustpinning.TrustPinConfig{})
+}
+
+func getPassphraseRetriever(streams command.Streams) notary.PassRetriever {
+ aliasMap := map[string]string{
+ "root": "root",
+ "snapshot": "repository",
+ "targets": "repository",
+ "default": "repository",
+ }
+ baseRetriever := passphrase.PromptRetrieverWithInOut(streams.In(), streams.Out(), aliasMap)
+ env := map[string]string{
+ "root": os.Getenv("DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE"),
+ "snapshot": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
+ "targets": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
+ "default": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
+ }
+
+ return func(keyName string, alias string, createNew bool, numAttempts int) (string, bool, error) {
+ if v := env[alias]; v != "" {
+ return v, numAttempts > 1, nil
+ }
+ // For non-root roles, we can also try the "default" alias if it is specified
+ if v := env["default"]; v != "" && alias != data.CanonicalRootRole {
+ return v, numAttempts > 1, nil
+ }
+ return baseRetriever(keyName, alias, createNew, numAttempts)
+ }
+}
+
+// NotaryError formats an error message received from the notary service
+func NotaryError(repoName string, err error) error {
+ switch err.(type) {
+ case *json.SyntaxError:
+ logrus.Debugf("Notary syntax error: %s", err)
+ return errors.Errorf("Error: no trust data available for remote repository %s. Try running notary server and setting DOCKER_CONTENT_TRUST_SERVER to its HTTPS address?", repoName)
+ case signed.ErrExpired:
+ return errors.Errorf("Error: remote repository %s out-of-date: %v", repoName, err)
+ case trustmanager.ErrKeyNotFound:
+ return errors.Errorf("Error: signing keys for remote repository %s not found: %v", repoName, err)
+ case storage.NetworkError:
+ return errors.Errorf("Error: error contacting notary server: %v", err)
+ case storage.ErrMetaNotFound:
+ return errors.Errorf("Error: trust data missing for remote repository %s or remote repository not found: %v", repoName, err)
+ case trustpinning.ErrRootRotationFail, trustpinning.ErrValidationFail, signed.ErrInvalidKeyType:
+ return errors.Errorf("Warning: potential malicious behavior - trust data mismatch for remote repository %s: %v", repoName, err)
+ case signed.ErrNoKeys:
+ return errors.Errorf("Error: could not find signing keys for remote repository %s, or could not decrypt signing key: %v", repoName, err)
+ case signed.ErrLowVersion:
+ return errors.Errorf("Warning: potential malicious behavior - trust data version is lower than expected for remote repository %s: %v", repoName, err)
+ case signed.ErrRoleThreshold:
+ return errors.Errorf("Warning: potential malicious behavior - trust data has insufficient signatures for remote repository %s: %v", repoName, err)
+ case client.ErrRepositoryNotExist:
+ return errors.Errorf("Error: remote trust data does not exist for %s: %v", repoName, err)
+ case signed.ErrInsufficientSignatures:
+ return errors.Errorf("Error: could not produce valid signature for %s. If Yubikey was used, was touch input provided?: %v", repoName, err)
+ }
+
+ return err
+}
diff --git a/vendor/github.com/docker/cli/cli/version.go b/vendor/github.com/docker/cli/cli/version.go
new file mode 100644
index 0000000..bff7ab4
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/version.go
@@ -0,0 +1,9 @@
+package cli
+
+// Default build-time variable.
+// These values are overriding via ldflags
+var (
+ Version = "unknown-version"
+ GitCommit = "unknown-commit"
+ BuildTime = "unknown-buildtime"
+)
diff --git a/vendor/github.com/docker/cli/cli/winresources/res_windows.go b/vendor/github.com/docker/cli/cli/winresources/res_windows.go
new file mode 100644
index 0000000..3f755cc
--- /dev/null
+++ b/vendor/github.com/docker/cli/cli/winresources/res_windows.go
@@ -0,0 +1,18 @@
+/*Package winresources is used to embed Windows resources into docker.exe.
+These resources are used to provide
+
+ * Version information
+ * An icon
+ * A Windows manifest declaring Windows version support
+
+The resource object files are generated with go generate.
+The resource source files are located in scripts/winresources.
+This occurs automatically when you run scripts/build/windows.
+
+These object files are picked up automatically by go build when this package
+is included.
+
+*/
+package winresources
+
+//go:generate ../../scripts/gen/windows-resources
diff --git a/vendor/github.com/docker/cli/cmd/docker/daemon_none.go b/vendor/github.com/docker/cli/cmd/docker/daemon_none.go
new file mode 100644
index 0000000..5004b39
--- /dev/null
+++ b/vendor/github.com/docker/cli/cmd/docker/daemon_none.go
@@ -0,0 +1,29 @@
+// +build !daemon
+
+package docker
+
+import (
+ "fmt"
+ "runtime"
+ "strings"
+
+ "github.com/spf13/cobra"
+)
+
+func newDaemonCommand() *cobra.Command {
+ return &cobra.Command{
+ Use: "daemon",
+ Hidden: true,
+ Args: cobra.ArbitraryArgs,
+ DisableFlagParsing: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runDaemon()
+ },
+ }
+}
+
+func runDaemon() error {
+ return fmt.Errorf(
+ "`docker daemon` is not supported on %s. Please run `dockerd` directly",
+ strings.Title(runtime.GOOS))
+}
diff --git a/vendor/github.com/docker/cli/cmd/docker/daemon_unix.go b/vendor/github.com/docker/cli/cmd/docker/daemon_unix.go
new file mode 100644
index 0000000..3122218
--- /dev/null
+++ b/vendor/github.com/docker/cli/cmd/docker/daemon_unix.go
@@ -0,0 +1,79 @@
+// +build daemon
+
+package docker
+
+import (
+ "fmt"
+
+ "os"
+ "os/exec"
+ "path/filepath"
+ "syscall"
+
+ "github.com/spf13/cobra"
+)
+
+const daemonBinary = "dockerd"
+
+func newDaemonCommand() *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "daemon",
+ Hidden: true,
+ Args: cobra.ArbitraryArgs,
+ DisableFlagParsing: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runDaemon()
+ },
+ Deprecated: "and will be removed. Please run `dockerd` directly.",
+ }
+ cmd.SetHelpFunc(helpFunc)
+ return cmd
+}
+
+// CmdDaemon execs dockerd with the same flags
+func runDaemon() error {
+ // Use os.Args[1:] so that "global" args are passed to dockerd
+ return execDaemon(stripDaemonArg(os.Args[1:]))
+}
+
+func execDaemon(args []string) error {
+ binaryPath, err := findDaemonBinary()
+ if err != nil {
+ return err
+ }
+
+ return syscall.Exec(
+ binaryPath,
+ append([]string{daemonBinary}, args...),
+ os.Environ())
+}
+
+func helpFunc(cmd *cobra.Command, args []string) {
+ if err := execDaemon([]string{"--help"}); err != nil {
+ fmt.Fprintf(os.Stderr, "%s\n", err.Error())
+ }
+}
+
+// findDaemonBinary looks for the path to the dockerd binary starting with
+// the directory of the current executable (if one exists) and followed by $PATH
+func findDaemonBinary() (string, error) {
+ execDirname := filepath.Dir(os.Args[0])
+ if execDirname != "" {
+ binaryPath := filepath.Join(execDirname, daemonBinary)
+ if _, err := os.Stat(binaryPath); err == nil {
+ return binaryPath, nil
+ }
+ }
+
+ return exec.LookPath(daemonBinary)
+}
+
+// stripDaemonArg removes the `daemon` argument from the list
+func stripDaemonArg(args []string) []string {
+ for i, arg := range args {
+ if arg == "daemon" {
+ return append(args[:i], args[i+1:]...)
+ }
+ }
+ return args
+}
diff --git a/vendor/github.com/docker/cli/cmd/docker/docker.go b/vendor/github.com/docker/cli/cmd/docker/docker.go
new file mode 100644
index 0000000..072b964
--- /dev/null
+++ b/vendor/github.com/docker/cli/cmd/docker/docker.go
@@ -0,0 +1,309 @@
+package docker
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/cli/cli"
+ "github.com/docker/cli/cli/command"
+ "github.com/docker/cli/cli/command/commands"
+ cliconfig "github.com/docker/cli/cli/config"
+ "github.com/docker/cli/cli/debug"
+ cliflags "github.com/docker/cli/cli/flags"
+ "github.com/docker/docker/api/types/versions"
+ "github.com/docker/docker/client"
+ "github.com/docker/docker/pkg/term"
+ "github.com/spf13/cobra"
+ "github.com/spf13/pflag"
+)
+
+func newDockerCommand(dockerCli *command.DockerCli) *cobra.Command {
+ opts := cliflags.NewClientOptions()
+ var flags *pflag.FlagSet
+
+ cmd := &cobra.Command{
+ Use: "docker [OPTIONS] COMMAND [ARG...]",
+ Short: "A self-sufficient runtime for containers",
+ SilenceUsage: true,
+ SilenceErrors: true,
+ TraverseChildren: true,
+ Args: noArgs,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if opts.Version {
+ showVersion()
+ return nil
+ }
+ return command.ShowHelp(dockerCli.Err())(cmd, args)
+ },
+ PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
+ // daemon command is special, we redirect directly to another binary
+ if cmd.Name() == "daemon" {
+ return nil
+ }
+ // flags must be the top-level command flags, not cmd.Flags()
+ opts.Common.SetDefaultOptions(flags)
+ dockerPreRun(opts)
+ if err := dockerCli.Initialize(opts); err != nil {
+ return err
+ }
+ return isSupported(cmd, dockerCli)
+ },
+ }
+ cli.SetupRootCommand(cmd)
+
+ flags = cmd.Flags()
+ flags.BoolVarP(&opts.Version, "version", "v", false, "Print version information and quit")
+ flags.StringVar(&opts.ConfigDir, "config", cliconfig.Dir(), "Location of client config files")
+ opts.Common.InstallFlags(flags)
+
+ setFlagErrorFunc(dockerCli, cmd, flags, opts)
+
+ setHelpFunc(dockerCli, cmd, flags, opts)
+
+ cmd.SetOutput(dockerCli.Out())
+ cmd.AddCommand(newDaemonCommand())
+ commands.AddCommands(cmd, dockerCli)
+
+ setValidateArgs(dockerCli, cmd, flags, opts)
+
+ return cmd
+}
+
+func setFlagErrorFunc(dockerCli *command.DockerCli, cmd *cobra.Command, flags *pflag.FlagSet, opts *cliflags.ClientOptions) {
+ // When invoking `docker stack --nonsense`, we need to make sure FlagErrorFunc return appropriate
+ // output if the feature is not supported.
+ // As above cli.SetupRootCommand(cmd) have already setup the FlagErrorFunc, we will add a pre-check before the FlagErrorFunc
+ // is called.
+ flagErrorFunc := cmd.FlagErrorFunc()
+ cmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
+ initializeDockerCli(dockerCli, flags, opts)
+ if err := isSupported(cmd, dockerCli); err != nil {
+ return err
+ }
+ return flagErrorFunc(cmd, err)
+ })
+}
+
+func setHelpFunc(dockerCli *command.DockerCli, cmd *cobra.Command, flags *pflag.FlagSet, opts *cliflags.ClientOptions) {
+ cmd.SetHelpFunc(func(ccmd *cobra.Command, args []string) {
+ initializeDockerCli(dockerCli, flags, opts)
+ if err := isSupported(ccmd, dockerCli); err != nil {
+ ccmd.Println(err)
+ return
+ }
+
+ hideUnsupportedFeatures(ccmd, dockerCli)
+
+ if err := ccmd.Help(); err != nil {
+ ccmd.Println(err)
+ }
+ })
+}
+
+func setValidateArgs(dockerCli *command.DockerCli, cmd *cobra.Command, flags *pflag.FlagSet, opts *cliflags.ClientOptions) {
+ // The Args is handled by ValidateArgs in cobra, which does not allows a pre-hook.
+ // As a result, here we replace the existing Args validation func to a wrapper,
+ // where the wrapper will check to see if the feature is supported or not.
+ // The Args validation error will only be returned if the feature is supported.
+ visitAll(cmd, func(ccmd *cobra.Command) {
+ // if there is no tags for a command or any of its parent,
+ // there is no need to wrap the Args validation.
+ if !hasTags(ccmd) {
+ return
+ }
+
+ if ccmd.Args == nil {
+ return
+ }
+
+ cmdArgs := ccmd.Args
+ ccmd.Args = func(cmd *cobra.Command, args []string) error {
+ initializeDockerCli(dockerCli, flags, opts)
+ if err := isSupported(cmd, dockerCli); err != nil {
+ return err
+ }
+ return cmdArgs(cmd, args)
+ }
+ })
+}
+
+func initializeDockerCli(dockerCli *command.DockerCli, flags *pflag.FlagSet, opts *cliflags.ClientOptions) {
+ if dockerCli.Client() == nil { // when using --help, PersistentPreRun is not called, so initialization is needed.
+ // flags must be the top-level command flags, not cmd.Flags()
+ opts.Common.SetDefaultOptions(flags)
+ dockerPreRun(opts)
+ dockerCli.Initialize(opts)
+ }
+}
+
+// visitAll will traverse all commands from the root.
+// This is different from the VisitAll of cobra.Command where only parents
+// are checked.
+func visitAll(root *cobra.Command, fn func(*cobra.Command)) {
+ for _, cmd := range root.Commands() {
+ visitAll(cmd, fn)
+ }
+ fn(root)
+}
+
+func noArgs(cmd *cobra.Command, args []string) error {
+ if len(args) == 0 {
+ return nil
+ }
+ return fmt.Errorf(
+ "docker: '%s' is not a docker command.\nSee 'docker --help'", args[0])
+}
+
+func Main() {
+ // Set terminal emulation based on platform as required.
+ stdin, stdout, stderr := term.StdStreams()
+ logrus.SetOutput(stderr)
+
+ dockerCli := command.NewDockerCli(stdin, stdout, stderr)
+ cmd := newDockerCommand(dockerCli)
+
+ if err := cmd.Execute(); err != nil {
+ if sterr, ok := err.(cli.StatusError); ok {
+ if sterr.Status != "" {
+ fmt.Fprintln(stderr, sterr.Status)
+ }
+ // StatusError should only be used for errors, and all errors should
+ // have a non-zero exit status, so never exit with 0
+ if sterr.StatusCode == 0 {
+ os.Exit(1)
+ }
+ os.Exit(sterr.StatusCode)
+ }
+ fmt.Fprintln(stderr, err)
+ os.Exit(1)
+ }
+}
+
+func showVersion() {
+ fmt.Printf("docker version %s, build %s\n", cli.Version, cli.GitCommit)
+}
+
+func dockerPreRun(opts *cliflags.ClientOptions) {
+ cliflags.SetLogLevel(opts.Common.LogLevel)
+
+ if opts.ConfigDir != "" {
+ cliconfig.SetDir(opts.ConfigDir)
+ }
+
+ if opts.Common.Debug {
+ debug.Enable()
+ }
+}
+
+type versionDetails interface {
+ Client() client.APIClient
+ ServerInfo() command.ServerInfo
+}
+
+func hideUnsupportedFeatures(cmd *cobra.Command, details versionDetails) {
+ clientVersion := details.Client().ClientVersion()
+ osType := details.ServerInfo().OSType
+ hasExperimental := details.ServerInfo().HasExperimental
+
+ cmd.Flags().VisitAll(func(f *pflag.Flag) {
+ // hide experimental flags
+ if !hasExperimental {
+ if _, ok := f.Annotations["experimental"]; ok {
+ f.Hidden = true
+ }
+ }
+
+ // hide flags not supported by the server
+ if !isOSTypeSupported(f, osType) || !isVersionSupported(f, clientVersion) {
+ f.Hidden = true
+ }
+ })
+
+ for _, subcmd := range cmd.Commands() {
+ // hide experimental subcommands
+ if !hasExperimental {
+ if _, ok := subcmd.Tags["experimental"]; ok {
+ subcmd.Hidden = true
+ }
+ }
+
+ // hide subcommands not supported by the server
+ if subcmdVersion, ok := subcmd.Tags["version"]; ok && versions.LessThan(clientVersion, subcmdVersion) {
+ subcmd.Hidden = true
+ }
+ }
+}
+
+func isSupported(cmd *cobra.Command, details versionDetails) error {
+ clientVersion := details.Client().ClientVersion()
+ osType := details.ServerInfo().OSType
+ hasExperimental := details.ServerInfo().HasExperimental
+
+ // Check recursively so that, e.g., `docker stack ls` returns the same output as `docker stack`
+ for curr := cmd; curr != nil; curr = curr.Parent() {
+ if cmdVersion, ok := curr.Tags["version"]; ok && versions.LessThan(clientVersion, cmdVersion) {
+ return fmt.Errorf("%s requires API version %s, but the docker daemon API version is %s", cmd.CommandPath(), cmdVersion, clientVersion)
+ }
+ if _, ok := curr.Tags["experimental"]; ok && !hasExperimental {
+ return fmt.Errorf("%s is only supported on a docker daemon with experimental features enabled", cmd.CommandPath())
+ }
+ }
+
+ errs := []string{}
+
+ cmd.Flags().VisitAll(func(f *pflag.Flag) {
+ if f.Changed {
+ if !isVersionSupported(f, clientVersion) {
+ errs = append(errs, fmt.Sprintf("\"--%s\" requires API version %s, but the docker daemon API version is %s", f.Name, getFlagAnnotation(f, "version"), clientVersion))
+ return
+ }
+ if !isOSTypeSupported(f, osType) {
+ errs = append(errs, fmt.Sprintf("\"--%s\" requires the docker daemon to run on %s, but the docker daemon is running on %s", f.Name, getFlagAnnotation(f, "ostype"), osType))
+ return
+ }
+ if _, ok := f.Annotations["experimental"]; ok && !hasExperimental {
+ errs = append(errs, fmt.Sprintf("\"--%s\" is only supported on a docker daemon with experimental features enabled", f.Name))
+ }
+ }
+ })
+ if len(errs) > 0 {
+ return errors.New(strings.Join(errs, "\n"))
+ }
+
+ return nil
+}
+
+func getFlagAnnotation(f *pflag.Flag, annotation string) string {
+ if value, ok := f.Annotations[annotation]; ok && len(value) == 1 {
+ return value[0]
+ }
+ return ""
+}
+
+func isVersionSupported(f *pflag.Flag, clientVersion string) bool {
+ if v := getFlagAnnotation(f, "version"); v != "" {
+ return versions.GreaterThanOrEqualTo(clientVersion, v)
+ }
+ return true
+}
+
+func isOSTypeSupported(f *pflag.Flag, osType string) bool {
+ if v := getFlagAnnotation(f, "ostype"); v != "" && osType != "" {
+ return osType == v
+ }
+ return true
+}
+
+// hasTags return true if any of the command's parents has tags
+func hasTags(cmd *cobra.Command) bool {
+ for curr := cmd; curr != nil; curr = curr.Parent() {
+ if len(curr.Tags) > 0 {
+ return true
+ }
+ }
+
+ return false
+}
diff --git a/vendor/github.com/docker/cli/cmd/docker/docker_windows.go b/vendor/github.com/docker/cli/cmd/docker/docker_windows.go
new file mode 100644
index 0000000..00c3f01
--- /dev/null
+++ b/vendor/github.com/docker/cli/cmd/docker/docker_windows.go
@@ -0,0 +1,3 @@
+package docker
+
+import _ "github.com/docker/cli/cli/winresources"
diff --git a/vendor/github.com/docker/cli/opts/config.go b/vendor/github.com/docker/cli/opts/config.go
new file mode 100644
index 0000000..82fd2bc
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/config.go
@@ -0,0 +1,98 @@
+package opts
+
+import (
+ "encoding/csv"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ swarmtypes "github.com/docker/docker/api/types/swarm"
+)
+
+// ConfigOpt is a Value type for parsing configs
+type ConfigOpt struct {
+ values []*swarmtypes.ConfigReference
+}
+
+// Set a new config value
+func (o *ConfigOpt) Set(value string) error {
+ csvReader := csv.NewReader(strings.NewReader(value))
+ fields, err := csvReader.Read()
+ if err != nil {
+ return err
+ }
+
+ options := &swarmtypes.ConfigReference{
+ File: &swarmtypes.ConfigReferenceFileTarget{
+ UID: "0",
+ GID: "0",
+ Mode: 0444,
+ },
+ }
+
+ // support a simple syntax of --config foo
+ if len(fields) == 1 {
+ options.File.Name = fields[0]
+ options.ConfigName = fields[0]
+ o.values = append(o.values, options)
+ return nil
+ }
+
+ for _, field := range fields {
+ parts := strings.SplitN(field, "=", 2)
+ key := strings.ToLower(parts[0])
+
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid field '%s' must be a key=value pair", field)
+ }
+
+ value := parts[1]
+ switch key {
+ case "source", "src":
+ options.ConfigName = value
+ case "target":
+ options.File.Name = value
+ case "uid":
+ options.File.UID = value
+ case "gid":
+ options.File.GID = value
+ case "mode":
+ m, err := strconv.ParseUint(value, 0, 32)
+ if err != nil {
+ return fmt.Errorf("invalid mode specified: %v", err)
+ }
+
+ options.File.Mode = os.FileMode(m)
+ default:
+ return fmt.Errorf("invalid field in config request: %s", key)
+ }
+ }
+
+ if options.ConfigName == "" {
+ return fmt.Errorf("source is required")
+ }
+
+ o.values = append(o.values, options)
+ return nil
+}
+
+// Type returns the type of this option
+func (o *ConfigOpt) Type() string {
+ return "config"
+}
+
+// String returns a string repr of this option
+func (o *ConfigOpt) String() string {
+ configs := []string{}
+ for _, config := range o.values {
+ repr := fmt.Sprintf("%s -> %s", config.ConfigName, config.File.Name)
+ configs = append(configs, repr)
+ }
+ return strings.Join(configs, ", ")
+}
+
+// Value returns the config requests
+func (o *ConfigOpt) Value() []*swarmtypes.ConfigReference {
+ return o.values
+}
diff --git a/vendor/github.com/docker/cli/opts/duration.go b/vendor/github.com/docker/cli/opts/duration.go
new file mode 100644
index 0000000..5dc6eea
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/duration.go
@@ -0,0 +1,64 @@
+package opts
+
+import (
+ "time"
+
+ "github.com/pkg/errors"
+)
+
+// PositiveDurationOpt is an option type for time.Duration that uses a pointer.
+// It behave similarly to DurationOpt but only allows positive duration values.
+type PositiveDurationOpt struct {
+ DurationOpt
+}
+
+// Set a new value on the option. Setting a negative duration value will cause
+// an error to be returned.
+func (d *PositiveDurationOpt) Set(s string) error {
+ err := d.DurationOpt.Set(s)
+ if err != nil {
+ return err
+ }
+ if *d.DurationOpt.value < 0 {
+ return errors.Errorf("duration cannot be negative")
+ }
+ return nil
+}
+
+// DurationOpt is an option type for time.Duration that uses a pointer. This
+// allows us to get nil values outside, instead of defaulting to 0
+type DurationOpt struct {
+ value *time.Duration
+}
+
+// NewDurationOpt creates a DurationOpt with the specified duration
+func NewDurationOpt(value *time.Duration) *DurationOpt {
+ return &DurationOpt{
+ value: value,
+ }
+}
+
+// Set a new value on the option
+func (d *DurationOpt) Set(s string) error {
+ v, err := time.ParseDuration(s)
+ d.value = &v
+ return err
+}
+
+// Type returns the type of this option, which will be displayed in `--help` output
+func (d *DurationOpt) Type() string {
+ return "duration"
+}
+
+// String returns a string repr of this option
+func (d *DurationOpt) String() string {
+ if d.value != nil {
+ return d.value.String()
+ }
+ return ""
+}
+
+// Value returns the time.Duration
+func (d *DurationOpt) Value() *time.Duration {
+ return d.value
+}
diff --git a/vendor/github.com/docker/cli/opts/env.go b/vendor/github.com/docker/cli/opts/env.go
new file mode 100644
index 0000000..e6ddd73
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/env.go
@@ -0,0 +1,46 @@
+package opts
+
+import (
+ "fmt"
+ "os"
+ "runtime"
+ "strings"
+)
+
+// ValidateEnv validates an environment variable and returns it.
+// If no value is specified, it returns the current value using os.Getenv.
+//
+// As on ParseEnvFile and related to #16585, environment variable names
+// are not validate what so ever, it's up to application inside docker
+// to validate them or not.
+//
+// The only validation here is to check if name is empty, per #25099
+func ValidateEnv(val string) (string, error) {
+ arr := strings.Split(val, "=")
+ if arr[0] == "" {
+ return "", fmt.Errorf("invalid environment variable: %s", val)
+ }
+ if len(arr) > 1 {
+ return val, nil
+ }
+ if !doesEnvExist(val) {
+ return val, nil
+ }
+ return fmt.Sprintf("%s=%s", val, os.Getenv(val)), nil
+}
+
+func doesEnvExist(name string) bool {
+ for _, entry := range os.Environ() {
+ parts := strings.SplitN(entry, "=", 2)
+ if runtime.GOOS == "windows" {
+ // Environment variable are case-insensitive on Windows. PaTh, path and PATH are equivalent.
+ if strings.EqualFold(parts[0], name) {
+ return true
+ }
+ }
+ if parts[0] == name {
+ return true
+ }
+ }
+ return false
+}
diff --git a/vendor/github.com/docker/cli/opts/envfile.go b/vendor/github.com/docker/cli/opts/envfile.go
new file mode 100644
index 0000000..f723799
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/envfile.go
@@ -0,0 +1,81 @@
+package opts
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "os"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+// ParseEnvFile reads a file with environment variables enumerated by lines
+//
+// ``Environment variable names used by the utilities in the Shell and
+// Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase
+// letters, digits, and the '_' (underscore) from the characters defined in
+// Portable Character Set and do not begin with a digit. *But*, other
+// characters may be permitted by an implementation; applications shall
+// tolerate the presence of such names.''
+// -- http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html
+//
+// As of #16585, it's up to application inside docker to validate or not
+// environment variables, that's why we just strip leading whitespace and
+// nothing more.
+func ParseEnvFile(filename string) ([]string, error) {
+ fh, err := os.Open(filename)
+ if err != nil {
+ return []string{}, err
+ }
+ defer fh.Close()
+
+ lines := []string{}
+ scanner := bufio.NewScanner(fh)
+ currentLine := 0
+ utf8bom := []byte{0xEF, 0xBB, 0xBF}
+ for scanner.Scan() {
+ scannedBytes := scanner.Bytes()
+ if !utf8.Valid(scannedBytes) {
+ return []string{}, fmt.Errorf("env file %s contains invalid utf8 bytes at line %d: %v", filename, currentLine+1, scannedBytes)
+ }
+ // We trim UTF8 BOM
+ if currentLine == 0 {
+ scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom)
+ }
+ // trim the line from all leading whitespace first
+ line := strings.TrimLeftFunc(string(scannedBytes), unicode.IsSpace)
+ currentLine++
+ // line is not empty, and not starting with '#'
+ if len(line) > 0 && !strings.HasPrefix(line, "#") {
+ data := strings.SplitN(line, "=", 2)
+
+ // trim the front of a variable, but nothing else
+ variable := strings.TrimLeft(data[0], whiteSpaces)
+ if strings.ContainsAny(variable, whiteSpaces) {
+ return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' has white spaces", variable)}
+ }
+
+ if len(data) > 1 {
+
+ // pass the value through, no trimming
+ lines = append(lines, fmt.Sprintf("%s=%s", variable, data[1]))
+ } else {
+ // if only a pass-through variable is given, clean it up.
+ lines = append(lines, fmt.Sprintf("%s=%s", strings.TrimSpace(line), os.Getenv(line)))
+ }
+ }
+ }
+ return lines, scanner.Err()
+}
+
+var whiteSpaces = " \t"
+
+// ErrBadEnvVariable typed error for bad environment variable
+type ErrBadEnvVariable struct {
+ msg string
+}
+
+func (e ErrBadEnvVariable) Error() string {
+ return fmt.Sprintf("poorly formatted environment: %s", e.msg)
+}
diff --git a/vendor/github.com/docker/cli/opts/hosts.go b/vendor/github.com/docker/cli/opts/hosts.go
new file mode 100644
index 0000000..594cccf
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/hosts.go
@@ -0,0 +1,165 @@
+package opts
+
+import (
+ "fmt"
+ "net"
+ "net/url"
+ "strconv"
+ "strings"
+)
+
+var (
+ // DefaultHTTPPort Default HTTP Port used if only the protocol is provided to -H flag e.g. dockerd -H tcp://
+ // These are the IANA registered port numbers for use with Docker
+ // see http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=docker
+ DefaultHTTPPort = 2375 // Default HTTP Port
+ // DefaultTLSHTTPPort Default HTTP Port used when TLS enabled
+ DefaultTLSHTTPPort = 2376 // Default TLS encrypted HTTP Port
+ // DefaultUnixSocket Path for the unix socket.
+ // Docker daemon by default always listens on the default unix socket
+ DefaultUnixSocket = "/var/run/docker.sock"
+ // DefaultTCPHost constant defines the default host string used by docker on Windows
+ DefaultTCPHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultHTTPPort)
+ // DefaultTLSHost constant defines the default host string used by docker for TLS sockets
+ DefaultTLSHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultTLSHTTPPort)
+ // DefaultNamedPipe defines the default named pipe used by docker on Windows
+ DefaultNamedPipe = `//./pipe/docker_engine`
+)
+
+// ValidateHost validates that the specified string is a valid host and returns it.
+func ValidateHost(val string) (string, error) {
+ host := strings.TrimSpace(val)
+ // The empty string means default and is not handled by parseDockerDaemonHost
+ if host != "" {
+ _, err := parseDockerDaemonHost(host)
+ if err != nil {
+ return val, err
+ }
+ }
+ // Note: unlike most flag validators, we don't return the mutated value here
+ // we need to know what the user entered later (using ParseHost) to adjust for TLS
+ return val, nil
+}
+
+// ParseHost and set defaults for a Daemon host string
+func ParseHost(defaultToTLS bool, val string) (string, error) {
+ host := strings.TrimSpace(val)
+ if host == "" {
+ if defaultToTLS {
+ host = DefaultTLSHost
+ } else {
+ host = DefaultHost
+ }
+ } else {
+ var err error
+ host, err = parseDockerDaemonHost(host)
+ if err != nil {
+ return val, err
+ }
+ }
+ return host, nil
+}
+
+// parseDockerDaemonHost parses the specified address and returns an address that will be used as the host.
+// Depending of the address specified, this may return one of the global Default* strings defined in hosts.go.
+func parseDockerDaemonHost(addr string) (string, error) {
+ addrParts := strings.SplitN(addr, "://", 2)
+ if len(addrParts) == 1 && addrParts[0] != "" {
+ addrParts = []string{"tcp", addrParts[0]}
+ }
+
+ switch addrParts[0] {
+ case "tcp":
+ return ParseTCPAddr(addrParts[1], DefaultTCPHost)
+ case "unix":
+ return parseSimpleProtoAddr("unix", addrParts[1], DefaultUnixSocket)
+ case "npipe":
+ return parseSimpleProtoAddr("npipe", addrParts[1], DefaultNamedPipe)
+ case "fd":
+ return addr, nil
+ default:
+ return "", fmt.Errorf("Invalid bind address format: %s", addr)
+ }
+}
+
+// parseSimpleProtoAddr parses and validates that the specified address is a valid
+// socket address for simple protocols like unix and npipe. It returns a formatted
+// socket address, either using the address parsed from addr, or the contents of
+// defaultAddr if addr is a blank string.
+func parseSimpleProtoAddr(proto, addr, defaultAddr string) (string, error) {
+ addr = strings.TrimPrefix(addr, proto+"://")
+ if strings.Contains(addr, "://") {
+ return "", fmt.Errorf("Invalid proto, expected %s: %s", proto, addr)
+ }
+ if addr == "" {
+ addr = defaultAddr
+ }
+ return fmt.Sprintf("%s://%s", proto, addr), nil
+}
+
+// ParseTCPAddr parses and validates that the specified address is a valid TCP
+// address. It returns a formatted TCP address, either using the address parsed
+// from tryAddr, or the contents of defaultAddr if tryAddr is a blank string.
+// tryAddr is expected to have already been Trim()'d
+// defaultAddr must be in the full `tcp://host:port` form
+func ParseTCPAddr(tryAddr string, defaultAddr string) (string, error) {
+ if tryAddr == "" || tryAddr == "tcp://" {
+ return defaultAddr, nil
+ }
+ addr := strings.TrimPrefix(tryAddr, "tcp://")
+ if strings.Contains(addr, "://") || addr == "" {
+ return "", fmt.Errorf("Invalid proto, expected tcp: %s", tryAddr)
+ }
+
+ defaultAddr = strings.TrimPrefix(defaultAddr, "tcp://")
+ defaultHost, defaultPort, err := net.SplitHostPort(defaultAddr)
+ if err != nil {
+ return "", err
+ }
+ // url.Parse fails for trailing colon on IPv6 brackets on Go 1.5, but
+ // not 1.4. See https://github.com/golang/go/issues/12200 and
+ // https://github.com/golang/go/issues/6530.
+ if strings.HasSuffix(addr, "]:") {
+ addr += defaultPort
+ }
+
+ u, err := url.Parse("tcp://" + addr)
+ if err != nil {
+ return "", err
+ }
+ host, port, err := net.SplitHostPort(u.Host)
+ if err != nil {
+ // try port addition once
+ host, port, err = net.SplitHostPort(net.JoinHostPort(u.Host, defaultPort))
+ }
+ if err != nil {
+ return "", fmt.Errorf("Invalid bind address format: %s", tryAddr)
+ }
+
+ if host == "" {
+ host = defaultHost
+ }
+ if port == "" {
+ port = defaultPort
+ }
+ p, err := strconv.Atoi(port)
+ if err != nil && p == 0 {
+ return "", fmt.Errorf("Invalid bind address format: %s", tryAddr)
+ }
+
+ return fmt.Sprintf("tcp://%s%s", net.JoinHostPort(host, port), u.Path), nil
+}
+
+// ValidateExtraHost validates that the specified string is a valid extrahost and returns it.
+// ExtraHost is in the form of name:ip where the ip has to be a valid ip (IPv4 or IPv6).
+func ValidateExtraHost(val string) (string, error) {
+ // allow for IPv6 addresses in extra hosts by only splitting on first ":"
+ arr := strings.SplitN(val, ":", 2)
+ if len(arr) != 2 || len(arr[0]) == 0 {
+ return "", fmt.Errorf("bad format for add-host: %q", val)
+ }
+ if _, err := ValidateIPAddress(arr[1]); err != nil {
+ return "", fmt.Errorf("invalid IP address in add-host: %q", arr[1])
+ }
+ return val, nil
+}
diff --git a/vendor/github.com/docker/cli/opts/hosts_unix.go b/vendor/github.com/docker/cli/opts/hosts_unix.go
new file mode 100644
index 0000000..611407a
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/hosts_unix.go
@@ -0,0 +1,8 @@
+// +build !windows
+
+package opts
+
+import "fmt"
+
+// DefaultHost constant defines the default host string used by docker on other hosts than Windows
+var DefaultHost = fmt.Sprintf("unix://%s", DefaultUnixSocket)
diff --git a/vendor/github.com/docker/cli/opts/hosts_windows.go b/vendor/github.com/docker/cli/opts/hosts_windows.go
new file mode 100644
index 0000000..7c239e0
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/hosts_windows.go
@@ -0,0 +1,6 @@
+// +build windows
+
+package opts
+
+// DefaultHost constant defines the default host string used by docker on Windows
+var DefaultHost = "npipe://" + DefaultNamedPipe
diff --git a/vendor/github.com/docker/cli/opts/ip.go b/vendor/github.com/docker/cli/opts/ip.go
new file mode 100644
index 0000000..fb03b50
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/ip.go
@@ -0,0 +1,47 @@
+package opts
+
+import (
+ "fmt"
+ "net"
+)
+
+// IPOpt holds an IP. It is used to store values from CLI flags.
+type IPOpt struct {
+ *net.IP
+}
+
+// NewIPOpt creates a new IPOpt from a reference net.IP and a
+// string representation of an IP. If the string is not a valid
+// IP it will fallback to the specified reference.
+func NewIPOpt(ref *net.IP, defaultVal string) *IPOpt {
+ o := &IPOpt{
+ IP: ref,
+ }
+ o.Set(defaultVal)
+ return o
+}
+
+// Set sets an IPv4 or IPv6 address from a given string. If the given
+// string is not parseable as an IP address it returns an error.
+func (o *IPOpt) Set(val string) error {
+ ip := net.ParseIP(val)
+ if ip == nil {
+ return fmt.Errorf("%s is not an ip address", val)
+ }
+ *o.IP = ip
+ return nil
+}
+
+// String returns the IP address stored in the IPOpt. If stored IP is a
+// nil pointer, it returns an empty string.
+func (o *IPOpt) String() string {
+ if *o.IP == nil {
+ return ""
+ }
+ return o.IP.String()
+}
+
+// Type returns the type of the option
+func (o *IPOpt) Type() string {
+ return "ip"
+}
diff --git a/vendor/github.com/docker/cli/opts/mount.go b/vendor/github.com/docker/cli/opts/mount.go
new file mode 100644
index 0000000..3aa9849
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/mount.go
@@ -0,0 +1,174 @@
+package opts
+
+import (
+ "encoding/csv"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ mounttypes "github.com/docker/docker/api/types/mount"
+ "github.com/docker/go-units"
+)
+
+// MountOpt is a Value type for parsing mounts
+type MountOpt struct {
+ values []mounttypes.Mount
+}
+
+// Set a new mount value
+// nolint: gocyclo
+func (m *MountOpt) Set(value string) error {
+ csvReader := csv.NewReader(strings.NewReader(value))
+ fields, err := csvReader.Read()
+ if err != nil {
+ return err
+ }
+
+ mount := mounttypes.Mount{}
+
+ volumeOptions := func() *mounttypes.VolumeOptions {
+ if mount.VolumeOptions == nil {
+ mount.VolumeOptions = &mounttypes.VolumeOptions{
+ Labels: make(map[string]string),
+ }
+ }
+ if mount.VolumeOptions.DriverConfig == nil {
+ mount.VolumeOptions.DriverConfig = &mounttypes.Driver{}
+ }
+ return mount.VolumeOptions
+ }
+
+ bindOptions := func() *mounttypes.BindOptions {
+ if mount.BindOptions == nil {
+ mount.BindOptions = new(mounttypes.BindOptions)
+ }
+ return mount.BindOptions
+ }
+
+ tmpfsOptions := func() *mounttypes.TmpfsOptions {
+ if mount.TmpfsOptions == nil {
+ mount.TmpfsOptions = new(mounttypes.TmpfsOptions)
+ }
+ return mount.TmpfsOptions
+ }
+
+ setValueOnMap := func(target map[string]string, value string) {
+ parts := strings.SplitN(value, "=", 2)
+ if len(parts) == 1 {
+ target[value] = ""
+ } else {
+ target[parts[0]] = parts[1]
+ }
+ }
+
+ mount.Type = mounttypes.TypeVolume // default to volume mounts
+ // Set writable as the default
+ for _, field := range fields {
+ parts := strings.SplitN(field, "=", 2)
+ key := strings.ToLower(parts[0])
+
+ if len(parts) == 1 {
+ switch key {
+ case "readonly", "ro":
+ mount.ReadOnly = true
+ continue
+ case "volume-nocopy":
+ volumeOptions().NoCopy = true
+ continue
+ }
+ }
+
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid field '%s' must be a key=value pair", field)
+ }
+
+ value := parts[1]
+ switch key {
+ case "type":
+ mount.Type = mounttypes.Type(strings.ToLower(value))
+ case "source", "src":
+ mount.Source = value
+ case "target", "dst", "destination":
+ mount.Target = value
+ case "readonly", "ro":
+ mount.ReadOnly, err = strconv.ParseBool(value)
+ if err != nil {
+ return fmt.Errorf("invalid value for %s: %s", key, value)
+ }
+ case "consistency":
+ mount.Consistency = mounttypes.Consistency(strings.ToLower(value))
+ case "bind-propagation":
+ bindOptions().Propagation = mounttypes.Propagation(strings.ToLower(value))
+ case "volume-nocopy":
+ volumeOptions().NoCopy, err = strconv.ParseBool(value)
+ if err != nil {
+ return fmt.Errorf("invalid value for volume-nocopy: %s", value)
+ }
+ case "volume-label":
+ setValueOnMap(volumeOptions().Labels, value)
+ case "volume-driver":
+ volumeOptions().DriverConfig.Name = value
+ case "volume-opt":
+ if volumeOptions().DriverConfig.Options == nil {
+ volumeOptions().DriverConfig.Options = make(map[string]string)
+ }
+ setValueOnMap(volumeOptions().DriverConfig.Options, value)
+ case "tmpfs-size":
+ sizeBytes, err := units.RAMInBytes(value)
+ if err != nil {
+ return fmt.Errorf("invalid value for %s: %s", key, value)
+ }
+ tmpfsOptions().SizeBytes = sizeBytes
+ case "tmpfs-mode":
+ ui64, err := strconv.ParseUint(value, 8, 32)
+ if err != nil {
+ return fmt.Errorf("invalid value for %s: %s", key, value)
+ }
+ tmpfsOptions().Mode = os.FileMode(ui64)
+ default:
+ return fmt.Errorf("unexpected key '%s' in '%s'", key, field)
+ }
+ }
+
+ if mount.Type == "" {
+ return fmt.Errorf("type is required")
+ }
+
+ if mount.Target == "" {
+ return fmt.Errorf("target is required")
+ }
+
+ if mount.VolumeOptions != nil && mount.Type != mounttypes.TypeVolume {
+ return fmt.Errorf("cannot mix 'volume-*' options with mount type '%s'", mount.Type)
+ }
+ if mount.BindOptions != nil && mount.Type != mounttypes.TypeBind {
+ return fmt.Errorf("cannot mix 'bind-*' options with mount type '%s'", mount.Type)
+ }
+ if mount.TmpfsOptions != nil && mount.Type != mounttypes.TypeTmpfs {
+ return fmt.Errorf("cannot mix 'tmpfs-*' options with mount type '%s'", mount.Type)
+ }
+
+ m.values = append(m.values, mount)
+ return nil
+}
+
+// Type returns the type of this option
+func (m *MountOpt) Type() string {
+ return "mount"
+}
+
+// String returns a string repr of this option
+func (m *MountOpt) String() string {
+ mounts := []string{}
+ for _, mount := range m.values {
+ repr := fmt.Sprintf("%s %s %s", mount.Type, mount.Source, mount.Target)
+ mounts = append(mounts, repr)
+ }
+ return strings.Join(mounts, ", ")
+}
+
+// Value returns the mounts
+func (m *MountOpt) Value() []mounttypes.Mount {
+ return m.values
+}
diff --git a/vendor/github.com/docker/cli/opts/network.go b/vendor/github.com/docker/cli/opts/network.go
new file mode 100644
index 0000000..317a7ac
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/network.go
@@ -0,0 +1,106 @@
+package opts
+
+import (
+ "encoding/csv"
+ "fmt"
+ "regexp"
+ "strings"
+)
+
+const (
+ networkOptName = "name"
+ networkOptAlias = "alias"
+ driverOpt = "driver-opt"
+)
+
+// NetworkAttachmentOpts represents the network options for endpoint creation
+type NetworkAttachmentOpts struct {
+ Target string
+ Aliases []string
+ DriverOpts map[string]string
+}
+
+// NetworkOpt represents a network config in swarm mode.
+type NetworkOpt struct {
+ options []NetworkAttachmentOpts
+}
+
+// Set networkopts value
+func (n *NetworkOpt) Set(value string) error {
+ longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value)
+ if err != nil {
+ return err
+ }
+
+ var netOpt NetworkAttachmentOpts
+ if longSyntax {
+ csvReader := csv.NewReader(strings.NewReader(value))
+ fields, err := csvReader.Read()
+ if err != nil {
+ return err
+ }
+
+ netOpt.Aliases = []string{}
+ for _, field := range fields {
+ parts := strings.SplitN(field, "=", 2)
+
+ if len(parts) < 2 {
+ return fmt.Errorf("invalid field %s", field)
+ }
+
+ key := strings.TrimSpace(strings.ToLower(parts[0]))
+ value := strings.TrimSpace(strings.ToLower(parts[1]))
+
+ switch key {
+ case networkOptName:
+ netOpt.Target = value
+ case networkOptAlias:
+ netOpt.Aliases = append(netOpt.Aliases, value)
+ case driverOpt:
+ key, value, err = parseDriverOpt(value)
+ if err == nil {
+ if netOpt.DriverOpts == nil {
+ netOpt.DriverOpts = make(map[string]string)
+ }
+ netOpt.DriverOpts[key] = value
+ } else {
+ return err
+ }
+ default:
+ return fmt.Errorf("invalid field key %s", key)
+ }
+ }
+ if len(netOpt.Target) == 0 {
+ return fmt.Errorf("network name/id is not specified")
+ }
+ } else {
+ netOpt.Target = value
+ }
+ n.options = append(n.options, netOpt)
+ return nil
+}
+
+// Type returns the type of this option
+func (n *NetworkOpt) Type() string {
+ return "network"
+}
+
+// Value returns the networkopts
+func (n *NetworkOpt) Value() []NetworkAttachmentOpts {
+ return n.options
+}
+
+// String returns the network opts as a string
+func (n *NetworkOpt) String() string {
+ return ""
+}
+
+func parseDriverOpt(driverOpt string) (key string, value string, err error) {
+ parts := strings.SplitN(driverOpt, "=", 2)
+ if len(parts) != 2 {
+ err = fmt.Errorf("invalid key value pair format in driver options")
+ }
+ key = strings.TrimSpace(strings.ToLower(parts[0]))
+ value = strings.TrimSpace(strings.ToLower(parts[1]))
+ return
+}
diff --git a/vendor/github.com/docker/cli/opts/opts.go b/vendor/github.com/docker/cli/opts/opts.go
new file mode 100644
index 0000000..d915ec2
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/opts.go
@@ -0,0 +1,488 @@
+package opts
+
+import (
+ "fmt"
+ "math/big"
+ "net"
+ "path"
+ "regexp"
+ "strings"
+
+ "github.com/docker/docker/api/types/filters"
+ units "github.com/docker/go-units"
+)
+
+var (
+ alphaRegexp = regexp.MustCompile(`[a-zA-Z]`)
+ domainRegexp = regexp.MustCompile(`^(:?(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]))(:?\.(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])))*)\.?\s*$`)
+)
+
+// ListOpts holds a list of values and a validation function.
+type ListOpts struct {
+ values *[]string
+ validator ValidatorFctType
+}
+
+// NewListOpts creates a new ListOpts with the specified validator.
+func NewListOpts(validator ValidatorFctType) ListOpts {
+ var values []string
+ return *NewListOptsRef(&values, validator)
+}
+
+// NewListOptsRef creates a new ListOpts with the specified values and validator.
+func NewListOptsRef(values *[]string, validator ValidatorFctType) *ListOpts {
+ return &ListOpts{
+ values: values,
+ validator: validator,
+ }
+}
+
+func (opts *ListOpts) String() string {
+ if len(*opts.values) == 0 {
+ return ""
+ }
+ return fmt.Sprintf("%v", *opts.values)
+}
+
+// Set validates if needed the input value and adds it to the
+// internal slice.
+func (opts *ListOpts) Set(value string) error {
+ if opts.validator != nil {
+ v, err := opts.validator(value)
+ if err != nil {
+ return err
+ }
+ value = v
+ }
+ (*opts.values) = append((*opts.values), value)
+ return nil
+}
+
+// Delete removes the specified element from the slice.
+func (opts *ListOpts) Delete(key string) {
+ for i, k := range *opts.values {
+ if k == key {
+ (*opts.values) = append((*opts.values)[:i], (*opts.values)[i+1:]...)
+ return
+ }
+ }
+}
+
+// GetMap returns the content of values in a map in order to avoid
+// duplicates.
+func (opts *ListOpts) GetMap() map[string]struct{} {
+ ret := make(map[string]struct{})
+ for _, k := range *opts.values {
+ ret[k] = struct{}{}
+ }
+ return ret
+}
+
+// GetAll returns the values of slice.
+func (opts *ListOpts) GetAll() []string {
+ return (*opts.values)
+}
+
+// GetAllOrEmpty returns the values of the slice
+// or an empty slice when there are no values.
+func (opts *ListOpts) GetAllOrEmpty() []string {
+ v := *opts.values
+ if v == nil {
+ return make([]string, 0)
+ }
+ return v
+}
+
+// Get checks the existence of the specified key.
+func (opts *ListOpts) Get(key string) bool {
+ for _, k := range *opts.values {
+ if k == key {
+ return true
+ }
+ }
+ return false
+}
+
+// Len returns the amount of element in the slice.
+func (opts *ListOpts) Len() int {
+ return len((*opts.values))
+}
+
+// Type returns a string name for this Option type
+func (opts *ListOpts) Type() string {
+ return "list"
+}
+
+// WithValidator returns the ListOpts with validator set.
+func (opts *ListOpts) WithValidator(validator ValidatorFctType) *ListOpts {
+ opts.validator = validator
+ return opts
+}
+
+// NamedOption is an interface that list and map options
+// with names implement.
+type NamedOption interface {
+ Name() string
+}
+
+// NamedListOpts is a ListOpts with a configuration name.
+// This struct is useful to keep reference to the assigned
+// field name in the internal configuration struct.
+type NamedListOpts struct {
+ name string
+ ListOpts
+}
+
+var _ NamedOption = &NamedListOpts{}
+
+// NewNamedListOptsRef creates a reference to a new NamedListOpts struct.
+func NewNamedListOptsRef(name string, values *[]string, validator ValidatorFctType) *NamedListOpts {
+ return &NamedListOpts{
+ name: name,
+ ListOpts: *NewListOptsRef(values, validator),
+ }
+}
+
+// Name returns the name of the NamedListOpts in the configuration.
+func (o *NamedListOpts) Name() string {
+ return o.name
+}
+
+// MapOpts holds a map of values and a validation function.
+type MapOpts struct {
+ values map[string]string
+ validator ValidatorFctType
+}
+
+// Set validates if needed the input value and add it to the
+// internal map, by splitting on '='.
+func (opts *MapOpts) Set(value string) error {
+ if opts.validator != nil {
+ v, err := opts.validator(value)
+ if err != nil {
+ return err
+ }
+ value = v
+ }
+ vals := strings.SplitN(value, "=", 2)
+ if len(vals) == 1 {
+ (opts.values)[vals[0]] = ""
+ } else {
+ (opts.values)[vals[0]] = vals[1]
+ }
+ return nil
+}
+
+// GetAll returns the values of MapOpts as a map.
+func (opts *MapOpts) GetAll() map[string]string {
+ return opts.values
+}
+
+func (opts *MapOpts) String() string {
+ return fmt.Sprintf("%v", opts.values)
+}
+
+// Type returns a string name for this Option type
+func (opts *MapOpts) Type() string {
+ return "map"
+}
+
+// NewMapOpts creates a new MapOpts with the specified map of values and a validator.
+func NewMapOpts(values map[string]string, validator ValidatorFctType) *MapOpts {
+ if values == nil {
+ values = make(map[string]string)
+ }
+ return &MapOpts{
+ values: values,
+ validator: validator,
+ }
+}
+
+// NamedMapOpts is a MapOpts struct with a configuration name.
+// This struct is useful to keep reference to the assigned
+// field name in the internal configuration struct.
+type NamedMapOpts struct {
+ name string
+ MapOpts
+}
+
+var _ NamedOption = &NamedMapOpts{}
+
+// NewNamedMapOpts creates a reference to a new NamedMapOpts struct.
+func NewNamedMapOpts(name string, values map[string]string, validator ValidatorFctType) *NamedMapOpts {
+ return &NamedMapOpts{
+ name: name,
+ MapOpts: *NewMapOpts(values, validator),
+ }
+}
+
+// Name returns the name of the NamedMapOpts in the configuration.
+func (o *NamedMapOpts) Name() string {
+ return o.name
+}
+
+// ValidatorFctType defines a validator function that returns a validated string and/or an error.
+type ValidatorFctType func(val string) (string, error)
+
+// ValidatorFctListType defines a validator function that returns a validated list of string and/or an error
+type ValidatorFctListType func(val string) ([]string, error)
+
+// ValidateIPAddress validates an Ip address.
+func ValidateIPAddress(val string) (string, error) {
+ var ip = net.ParseIP(strings.TrimSpace(val))
+ if ip != nil {
+ return ip.String(), nil
+ }
+ return "", fmt.Errorf("%s is not an ip address", val)
+}
+
+// ValidateMACAddress validates a MAC address.
+func ValidateMACAddress(val string) (string, error) {
+ _, err := net.ParseMAC(strings.TrimSpace(val))
+ if err != nil {
+ return "", err
+ }
+ return val, nil
+}
+
+// ValidateDNSSearch validates domain for resolvconf search configuration.
+// A zero length domain is represented by a dot (.).
+func ValidateDNSSearch(val string) (string, error) {
+ if val = strings.Trim(val, " "); val == "." {
+ return val, nil
+ }
+ return validateDomain(val)
+}
+
+func validateDomain(val string) (string, error) {
+ if alphaRegexp.FindString(val) == "" {
+ return "", fmt.Errorf("%s is not a valid domain", val)
+ }
+ ns := domainRegexp.FindSubmatch([]byte(val))
+ if len(ns) > 0 && len(ns[1]) < 255 {
+ return string(ns[1]), nil
+ }
+ return "", fmt.Errorf("%s is not a valid domain", val)
+}
+
+// ValidateLabel validates that the specified string is a valid label, and returns it.
+// Labels are in the form on key=value.
+func ValidateLabel(val string) (string, error) {
+ if strings.Count(val, "=") < 1 {
+ return "", fmt.Errorf("bad attribute format: %s", val)
+ }
+ return val, nil
+}
+
+// ValidateSysctl validates a sysctl and returns it.
+func ValidateSysctl(val string) (string, error) {
+ validSysctlMap := map[string]bool{
+ "kernel.msgmax": true,
+ "kernel.msgmnb": true,
+ "kernel.msgmni": true,
+ "kernel.sem": true,
+ "kernel.shmall": true,
+ "kernel.shmmax": true,
+ "kernel.shmmni": true,
+ "kernel.shm_rmid_forced": true,
+ }
+ validSysctlPrefixes := []string{
+ "net.",
+ "fs.mqueue.",
+ }
+ arr := strings.Split(val, "=")
+ if len(arr) < 2 {
+ return "", fmt.Errorf("sysctl '%s' is not whitelisted", val)
+ }
+ if validSysctlMap[arr[0]] {
+ return val, nil
+ }
+
+ for _, vp := range validSysctlPrefixes {
+ if strings.HasPrefix(arr[0], vp) {
+ return val, nil
+ }
+ }
+ return "", fmt.Errorf("sysctl '%s' is not whitelisted", val)
+}
+
+// FilterOpt is a flag type for validating filters
+type FilterOpt struct {
+ filter filters.Args
+}
+
+// NewFilterOpt returns a new FilterOpt
+func NewFilterOpt() FilterOpt {
+ return FilterOpt{filter: filters.NewArgs()}
+}
+
+func (o *FilterOpt) String() string {
+ repr, err := filters.ToParam(o.filter)
+ if err != nil {
+ return "invalid filters"
+ }
+ return repr
+}
+
+// Set sets the value of the opt by parsing the command line value
+func (o *FilterOpt) Set(value string) error {
+ var err error
+ o.filter, err = filters.ParseFlag(value, o.filter)
+ return err
+}
+
+// Type returns the option type
+func (o *FilterOpt) Type() string {
+ return "filter"
+}
+
+// Value returns the value of this option
+func (o *FilterOpt) Value() filters.Args {
+ return o.filter
+}
+
+// NanoCPUs is a type for fixed point fractional number.
+type NanoCPUs int64
+
+// String returns the string format of the number
+func (c *NanoCPUs) String() string {
+ if *c == 0 {
+ return ""
+ }
+ return big.NewRat(c.Value(), 1e9).FloatString(3)
+}
+
+// Set sets the value of the NanoCPU by passing a string
+func (c *NanoCPUs) Set(value string) error {
+ cpus, err := ParseCPUs(value)
+ *c = NanoCPUs(cpus)
+ return err
+}
+
+// Type returns the type
+func (c *NanoCPUs) Type() string {
+ return "decimal"
+}
+
+// Value returns the value in int64
+func (c *NanoCPUs) Value() int64 {
+ return int64(*c)
+}
+
+// ParseCPUs takes a string ratio and returns an integer value of nano cpus
+func ParseCPUs(value string) (int64, error) {
+ cpu, ok := new(big.Rat).SetString(value)
+ if !ok {
+ return 0, fmt.Errorf("failed to parse %v as a rational number", value)
+ }
+ nano := cpu.Mul(cpu, big.NewRat(1e9, 1))
+ if !nano.IsInt() {
+ return 0, fmt.Errorf("value is too precise")
+ }
+ return nano.Num().Int64(), nil
+}
+
+// ParseLink parses and validates the specified string as a link format (name:alias)
+func ParseLink(val string) (string, string, error) {
+ if val == "" {
+ return "", "", fmt.Errorf("empty string specified for links")
+ }
+ arr := strings.Split(val, ":")
+ if len(arr) > 2 {
+ return "", "", fmt.Errorf("bad format for links: %s", val)
+ }
+ if len(arr) == 1 {
+ return val, val, nil
+ }
+ // This is kept because we can actually get a HostConfig with links
+ // from an already created container and the format is not `foo:bar`
+ // but `/foo:/c1/bar`
+ if strings.HasPrefix(arr[0], "/") {
+ _, alias := path.Split(arr[1])
+ return arr[0][1:], alias, nil
+ }
+ return arr[0], arr[1], nil
+}
+
+// ValidateLink validates that the specified string has a valid link format (containerName:alias).
+func ValidateLink(val string) (string, error) {
+ _, _, err := ParseLink(val)
+ return val, err
+}
+
+// MemBytes is a type for human readable memory bytes (like 128M, 2g, etc)
+type MemBytes int64
+
+// String returns the string format of the human readable memory bytes
+func (m *MemBytes) String() string {
+ // NOTE: In spf13/pflag/flag.go, "0" is considered as "zero value" while "0 B" is not.
+ // We return "0" in case value is 0 here so that the default value is hidden.
+ // (Sometimes "default 0 B" is actually misleading)
+ if m.Value() != 0 {
+ return units.BytesSize(float64(m.Value()))
+ }
+ return "0"
+}
+
+// Set sets the value of the MemBytes by passing a string
+func (m *MemBytes) Set(value string) error {
+ val, err := units.RAMInBytes(value)
+ *m = MemBytes(val)
+ return err
+}
+
+// Type returns the type
+func (m *MemBytes) Type() string {
+ return "bytes"
+}
+
+// Value returns the value in int64
+func (m *MemBytes) Value() int64 {
+ return int64(*m)
+}
+
+// UnmarshalJSON is the customized unmarshaler for MemBytes
+func (m *MemBytes) UnmarshalJSON(s []byte) error {
+ if len(s) <= 2 || s[0] != '"' || s[len(s)-1] != '"' {
+ return fmt.Errorf("invalid size: %q", s)
+ }
+ val, err := units.RAMInBytes(string(s[1 : len(s)-1]))
+ *m = MemBytes(val)
+ return err
+}
+
+// MemSwapBytes is a type for human readable memory bytes (like 128M, 2g, etc).
+// It differs from MemBytes in that -1 is valid and the default.
+type MemSwapBytes int64
+
+// Set sets the value of the MemSwapBytes by passing a string
+func (m *MemSwapBytes) Set(value string) error {
+ if value == "-1" {
+ *m = MemSwapBytes(-1)
+ return nil
+ }
+ val, err := units.RAMInBytes(value)
+ *m = MemSwapBytes(val)
+ return err
+}
+
+// Type returns the type
+func (m *MemSwapBytes) Type() string {
+ return "bytes"
+}
+
+// Value returns the value in int64
+func (m *MemSwapBytes) Value() int64 {
+ return int64(*m)
+}
+
+func (m *MemSwapBytes) String() string {
+ b := MemBytes(*m)
+ return b.String()
+}
+
+// UnmarshalJSON is the customized unmarshaler for MemSwapBytes
+func (m *MemSwapBytes) UnmarshalJSON(s []byte) error {
+ b := MemBytes(*m)
+ return b.UnmarshalJSON(s)
+}
diff --git a/vendor/github.com/docker/cli/opts/opts_unix.go b/vendor/github.com/docker/cli/opts/opts_unix.go
new file mode 100644
index 0000000..2766a43
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/opts_unix.go
@@ -0,0 +1,6 @@
+// +build !windows
+
+package opts
+
+// DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080
+const DefaultHTTPHost = "localhost"
diff --git a/vendor/github.com/docker/cli/opts/opts_windows.go b/vendor/github.com/docker/cli/opts/opts_windows.go
new file mode 100644
index 0000000..98b7251
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/opts_windows.go
@@ -0,0 +1,56 @@
+package opts
+
+// TODO Windows. Identify bug in GOLang 1.5.1+ and/or Windows Server 2016 TP5.
+// @jhowardmsft, @swernli.
+//
+// On Windows, this mitigates a problem with the default options of running
+// a docker client against a local docker daemon on TP5.
+//
+// What was found that if the default host is "localhost", even if the client
+// (and daemon as this is local) is not physically on a network, and the DNS
+// cache is flushed (ipconfig /flushdns), then the client will pause for
+// exactly one second when connecting to the daemon for calls. For example
+// using docker run windowsservercore cmd, the CLI will send a create followed
+// by an attach. You see the delay between the attach finishing and the attach
+// being seen by the daemon.
+//
+// Here's some daemon debug logs with additional debug spew put in. The
+// AfterWriteJSON log is the very last thing the daemon does as part of the
+// create call. The POST /attach is the second CLI call. Notice the second
+// time gap.
+//
+// time="2015-11-06T13:38:37.259627400-08:00" level=debug msg="After createRootfs"
+// time="2015-11-06T13:38:37.263626300-08:00" level=debug msg="After setHostConfig"
+// time="2015-11-06T13:38:37.267631200-08:00" level=debug msg="before createContainerPl...."
+// time="2015-11-06T13:38:37.271629500-08:00" level=debug msg=ToDiskLocking....
+// time="2015-11-06T13:38:37.275643200-08:00" level=debug msg="loggin event...."
+// time="2015-11-06T13:38:37.277627600-08:00" level=debug msg="logged event...."
+// time="2015-11-06T13:38:37.279631800-08:00" level=debug msg="In defer func"
+// time="2015-11-06T13:38:37.282628100-08:00" level=debug msg="After daemon.create"
+// time="2015-11-06T13:38:37.286651700-08:00" level=debug msg="return 2"
+// time="2015-11-06T13:38:37.289629500-08:00" level=debug msg="Returned from daemon.ContainerCreate"
+// time="2015-11-06T13:38:37.311629100-08:00" level=debug msg="After WriteJSON"
+// ... 1 second gap here....
+// time="2015-11-06T13:38:38.317866200-08:00" level=debug msg="Calling POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach"
+// time="2015-11-06T13:38:38.326882500-08:00" level=info msg="POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach?stderr=1&stdin=1&stdout=1&stream=1"
+//
+// We suspect this is either a bug introduced in GOLang 1.5.1, or that a change
+// in GOLang 1.5.1 (from 1.4.3) is exposing a bug in Windows. In theory,
+// the Windows networking stack is supposed to resolve "localhost" internally,
+// without hitting DNS, or even reading the hosts file (which is why localhost
+// is commented out in the hosts file on Windows).
+//
+// We have validated that working around this using the actual IPv4 localhost
+// address does not cause the delay.
+//
+// This does not occur with the docker client built with 1.4.3 on the same
+// Windows build, regardless of whether the daemon is built using 1.5.1
+// or 1.4.3. It does not occur on Linux. We also verified we see the same thing
+// on a cross-compiled Windows binary (from Linux).
+//
+// Final note: This is a mitigation, not a 'real' fix. It is still susceptible
+// to the delay if a user were to do 'docker run -H=tcp://localhost:2375...'
+// explicitly.
+
+// DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080
+const DefaultHTTPHost = "127.0.0.1"
diff --git a/vendor/github.com/docker/cli/opts/parse.go b/vendor/github.com/docker/cli/opts/parse.go
new file mode 100644
index 0000000..a88ea13
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/parse.go
@@ -0,0 +1,87 @@
+package opts
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/docker/docker/api/types/container"
+)
+
+// ReadKVStrings reads a file of line terminated key=value pairs, and overrides any keys
+// present in the file with additional pairs specified in the override parameter
+func ReadKVStrings(files []string, override []string) ([]string, error) {
+ envVariables := []string{}
+ for _, ef := range files {
+ parsedVars, err := ParseEnvFile(ef)
+ if err != nil {
+ return nil, err
+ }
+ envVariables = append(envVariables, parsedVars...)
+ }
+ // parse the '-e' and '--env' after, to allow override
+ envVariables = append(envVariables, override...)
+
+ return envVariables, nil
+}
+
+// ConvertKVStringsToMap converts ["key=value"] to {"key":"value"}
+func ConvertKVStringsToMap(values []string) map[string]string {
+ result := make(map[string]string, len(values))
+ for _, value := range values {
+ kv := strings.SplitN(value, "=", 2)
+ if len(kv) == 1 {
+ result[kv[0]] = ""
+ } else {
+ result[kv[0]] = kv[1]
+ }
+ }
+
+ return result
+}
+
+// ConvertKVStringsToMapWithNil converts ["key=value"] to {"key":"value"}
+// but set unset keys to nil - meaning the ones with no "=" in them.
+// We use this in cases where we need to distinguish between
+// FOO= and FOO
+// where the latter case just means FOO was mentioned but not given a value
+func ConvertKVStringsToMapWithNil(values []string) map[string]*string {
+ result := make(map[string]*string, len(values))
+ for _, value := range values {
+ kv := strings.SplitN(value, "=", 2)
+ if len(kv) == 1 {
+ result[kv[0]] = nil
+ } else {
+ result[kv[0]] = &kv[1]
+ }
+ }
+
+ return result
+}
+
+// ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect
+func ParseRestartPolicy(policy string) (container.RestartPolicy, error) {
+ p := container.RestartPolicy{}
+
+ if policy == "" {
+ return p, nil
+ }
+
+ parts := strings.Split(policy, ":")
+
+ if len(parts) > 2 {
+ return p, fmt.Errorf("invalid restart policy format")
+ }
+ if len(parts) == 2 {
+ count, err := strconv.Atoi(parts[1])
+ if err != nil {
+ return p, fmt.Errorf("maximum retry count must be an integer")
+ }
+
+ p.MaximumRetryCount = count
+ }
+
+ p.Name = parts[0]
+
+ return p, nil
+}
diff --git a/vendor/github.com/docker/cli/opts/port.go b/vendor/github.com/docker/cli/opts/port.go
new file mode 100644
index 0000000..49ca7d0
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/port.go
@@ -0,0 +1,163 @@
+package opts
+
+import (
+ "encoding/csv"
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+
+ "github.com/docker/docker/api/types/swarm"
+ "github.com/docker/go-connections/nat"
+)
+
+const (
+ portOptTargetPort = "target"
+ portOptPublishedPort = "published"
+ portOptProtocol = "protocol"
+ portOptMode = "mode"
+)
+
+// PortOpt represents a port config in swarm mode.
+type PortOpt struct {
+ ports []swarm.PortConfig
+}
+
+// Set a new port value
+// nolint: gocyclo
+func (p *PortOpt) Set(value string) error {
+ longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value)
+ if err != nil {
+ return err
+ }
+ if longSyntax {
+ csvReader := csv.NewReader(strings.NewReader(value))
+ fields, err := csvReader.Read()
+ if err != nil {
+ return err
+ }
+
+ pConfig := swarm.PortConfig{}
+ for _, field := range fields {
+ parts := strings.SplitN(field, "=", 2)
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid field %s", field)
+ }
+
+ key := strings.ToLower(parts[0])
+ value := strings.ToLower(parts[1])
+
+ switch key {
+ case portOptProtocol:
+ if value != string(swarm.PortConfigProtocolTCP) && value != string(swarm.PortConfigProtocolUDP) {
+ return fmt.Errorf("invalid protocol value %s", value)
+ }
+
+ pConfig.Protocol = swarm.PortConfigProtocol(value)
+ case portOptMode:
+ if value != string(swarm.PortConfigPublishModeIngress) && value != string(swarm.PortConfigPublishModeHost) {
+ return fmt.Errorf("invalid publish mode value %s", value)
+ }
+
+ pConfig.PublishMode = swarm.PortConfigPublishMode(value)
+ case portOptTargetPort:
+ tPort, err := strconv.ParseUint(value, 10, 16)
+ if err != nil {
+ return err
+ }
+
+ pConfig.TargetPort = uint32(tPort)
+ case portOptPublishedPort:
+ pPort, err := strconv.ParseUint(value, 10, 16)
+ if err != nil {
+ return err
+ }
+
+ pConfig.PublishedPort = uint32(pPort)
+ default:
+ return fmt.Errorf("invalid field key %s", key)
+ }
+ }
+
+ if pConfig.TargetPort == 0 {
+ return fmt.Errorf("missing mandatory field %q", portOptTargetPort)
+ }
+
+ if pConfig.PublishMode == "" {
+ pConfig.PublishMode = swarm.PortConfigPublishModeIngress
+ }
+
+ if pConfig.Protocol == "" {
+ pConfig.Protocol = swarm.PortConfigProtocolTCP
+ }
+
+ p.ports = append(p.ports, pConfig)
+ } else {
+ // short syntax
+ portConfigs := []swarm.PortConfig{}
+ ports, portBindingMap, err := nat.ParsePortSpecs([]string{value})
+ if err != nil {
+ return err
+ }
+ for _, portBindings := range portBindingMap {
+ for _, portBinding := range portBindings {
+ if portBinding.HostIP != "" {
+ return fmt.Errorf("hostip is not supported")
+ }
+ }
+ }
+
+ for port := range ports {
+ portConfig, err := ConvertPortToPortConfig(port, portBindingMap)
+ if err != nil {
+ return err
+ }
+ portConfigs = append(portConfigs, portConfig...)
+ }
+ p.ports = append(p.ports, portConfigs...)
+ }
+ return nil
+}
+
+// Type returns the type of this option
+func (p *PortOpt) Type() string {
+ return "port"
+}
+
+// String returns a string repr of this option
+func (p *PortOpt) String() string {
+ ports := []string{}
+ for _, port := range p.ports {
+ repr := fmt.Sprintf("%v:%v/%s/%s", port.PublishedPort, port.TargetPort, port.Protocol, port.PublishMode)
+ ports = append(ports, repr)
+ }
+ return strings.Join(ports, ", ")
+}
+
+// Value returns the ports
+func (p *PortOpt) Value() []swarm.PortConfig {
+ return p.ports
+}
+
+// ConvertPortToPortConfig converts ports to the swarm type
+func ConvertPortToPortConfig(
+ port nat.Port,
+ portBindings map[nat.Port][]nat.PortBinding,
+) ([]swarm.PortConfig, error) {
+ ports := []swarm.PortConfig{}
+
+ for _, binding := range portBindings[port] {
+ hostPort, err := strconv.ParseUint(binding.HostPort, 10, 16)
+ if err != nil && binding.HostPort != "" {
+ return nil, fmt.Errorf("invalid hostport binding (%s) for port (%s)", binding.HostPort, port.Port())
+ }
+ ports = append(ports, swarm.PortConfig{
+ //TODO Name: ?
+ Protocol: swarm.PortConfigProtocol(strings.ToLower(port.Proto())),
+ TargetPort: uint32(port.Int()),
+ PublishedPort: uint32(hostPort),
+ PublishMode: swarm.PortConfigPublishModeIngress,
+ })
+ }
+ return ports, nil
+}
diff --git a/vendor/github.com/docker/cli/opts/quotedstring.go b/vendor/github.com/docker/cli/opts/quotedstring.go
new file mode 100644
index 0000000..09c68a5
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/quotedstring.go
@@ -0,0 +1,37 @@
+package opts
+
+// QuotedString is a string that may have extra quotes around the value. The
+// quotes are stripped from the value.
+type QuotedString struct {
+ value *string
+}
+
+// Set sets a new value
+func (s *QuotedString) Set(val string) error {
+ *s.value = trimQuotes(val)
+ return nil
+}
+
+// Type returns the type of the value
+func (s *QuotedString) Type() string {
+ return "string"
+}
+
+func (s *QuotedString) String() string {
+ return *s.value
+}
+
+func trimQuotes(value string) string {
+ lastIndex := len(value) - 1
+ for _, char := range []byte{'\'', '"'} {
+ if value[0] == char && value[lastIndex] == char {
+ return value[1:lastIndex]
+ }
+ }
+ return value
+}
+
+// NewQuotedString returns a new quoted string option
+func NewQuotedString(value *string) *QuotedString {
+ return &QuotedString{value: value}
+}
diff --git a/vendor/github.com/docker/cli/opts/runtime.go b/vendor/github.com/docker/cli/opts/runtime.go
new file mode 100644
index 0000000..4361b3c
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/runtime.go
@@ -0,0 +1,79 @@
+package opts
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/docker/api/types"
+)
+
+// RuntimeOpt defines a map of Runtimes
+type RuntimeOpt struct {
+ name string
+ stockRuntimeName string
+ values *map[string]types.Runtime
+}
+
+// NewNamedRuntimeOpt creates a new RuntimeOpt
+func NewNamedRuntimeOpt(name string, ref *map[string]types.Runtime, stockRuntime string) *RuntimeOpt {
+ if ref == nil {
+ ref = &map[string]types.Runtime{}
+ }
+ return &RuntimeOpt{name: name, values: ref, stockRuntimeName: stockRuntime}
+}
+
+// Name returns the name of the NamedListOpts in the configuration.
+func (o *RuntimeOpt) Name() string {
+ return o.name
+}
+
+// Set validates and updates the list of Runtimes
+func (o *RuntimeOpt) Set(val string) error {
+ parts := strings.SplitN(val, "=", 2)
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid runtime argument: %s", val)
+ }
+
+ parts[0] = strings.TrimSpace(parts[0])
+ parts[1] = strings.TrimSpace(parts[1])
+ if parts[0] == "" || parts[1] == "" {
+ return fmt.Errorf("invalid runtime argument: %s", val)
+ }
+
+ parts[0] = strings.ToLower(parts[0])
+ if parts[0] == o.stockRuntimeName {
+ return fmt.Errorf("runtime name '%s' is reserved", o.stockRuntimeName)
+ }
+
+ if _, ok := (*o.values)[parts[0]]; ok {
+ return fmt.Errorf("runtime '%s' was already defined", parts[0])
+ }
+
+ (*o.values)[parts[0]] = types.Runtime{Path: parts[1]}
+
+ return nil
+}
+
+// String returns Runtime values as a string.
+func (o *RuntimeOpt) String() string {
+ var out []string
+ for k := range *o.values {
+ out = append(out, k)
+ }
+
+ return fmt.Sprintf("%v", out)
+}
+
+// GetMap returns a map of Runtimes (name: path)
+func (o *RuntimeOpt) GetMap() map[string]types.Runtime {
+ if o.values != nil {
+ return *o.values
+ }
+
+ return map[string]types.Runtime{}
+}
+
+// Type returns the type of the option
+func (o *RuntimeOpt) Type() string {
+ return "runtime"
+}
diff --git a/vendor/github.com/docker/cli/opts/secret.go b/vendor/github.com/docker/cli/opts/secret.go
new file mode 100644
index 0000000..a1fde54
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/secret.go
@@ -0,0 +1,98 @@
+package opts
+
+import (
+ "encoding/csv"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ swarmtypes "github.com/docker/docker/api/types/swarm"
+)
+
+// SecretOpt is a Value type for parsing secrets
+type SecretOpt struct {
+ values []*swarmtypes.SecretReference
+}
+
+// Set a new secret value
+func (o *SecretOpt) Set(value string) error {
+ csvReader := csv.NewReader(strings.NewReader(value))
+ fields, err := csvReader.Read()
+ if err != nil {
+ return err
+ }
+
+ options := &swarmtypes.SecretReference{
+ File: &swarmtypes.SecretReferenceFileTarget{
+ UID: "0",
+ GID: "0",
+ Mode: 0444,
+ },
+ }
+
+ // support a simple syntax of --secret foo
+ if len(fields) == 1 {
+ options.File.Name = fields[0]
+ options.SecretName = fields[0]
+ o.values = append(o.values, options)
+ return nil
+ }
+
+ for _, field := range fields {
+ parts := strings.SplitN(field, "=", 2)
+ key := strings.ToLower(parts[0])
+
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid field '%s' must be a key=value pair", field)
+ }
+
+ value := parts[1]
+ switch key {
+ case "source", "src":
+ options.SecretName = value
+ case "target":
+ options.File.Name = value
+ case "uid":
+ options.File.UID = value
+ case "gid":
+ options.File.GID = value
+ case "mode":
+ m, err := strconv.ParseUint(value, 0, 32)
+ if err != nil {
+ return fmt.Errorf("invalid mode specified: %v", err)
+ }
+
+ options.File.Mode = os.FileMode(m)
+ default:
+ return fmt.Errorf("invalid field in secret request: %s", key)
+ }
+ }
+
+ if options.SecretName == "" {
+ return fmt.Errorf("source is required")
+ }
+
+ o.values = append(o.values, options)
+ return nil
+}
+
+// Type returns the type of this option
+func (o *SecretOpt) Type() string {
+ return "secret"
+}
+
+// String returns a string repr of this option
+func (o *SecretOpt) String() string {
+ secrets := []string{}
+ for _, secret := range o.values {
+ repr := fmt.Sprintf("%s -> %s", secret.SecretName, secret.File.Name)
+ secrets = append(secrets, repr)
+ }
+ return strings.Join(secrets, ", ")
+}
+
+// Value returns the secret requests
+func (o *SecretOpt) Value() []*swarmtypes.SecretReference {
+ return o.values
+}
diff --git a/vendor/github.com/docker/cli/opts/throttledevice.go b/vendor/github.com/docker/cli/opts/throttledevice.go
new file mode 100644
index 0000000..0959efa
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/throttledevice.go
@@ -0,0 +1,108 @@
+package opts
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/docker/docker/api/types/blkiodev"
+ "github.com/docker/go-units"
+)
+
+// ValidatorThrottleFctType defines a validator function that returns a validated struct and/or an error.
+type ValidatorThrottleFctType func(val string) (*blkiodev.ThrottleDevice, error)
+
+// ValidateThrottleBpsDevice validates that the specified string has a valid device-rate format.
+func ValidateThrottleBpsDevice(val string) (*blkiodev.ThrottleDevice, error) {
+ split := strings.SplitN(val, ":", 2)
+ if len(split) != 2 {
+ return nil, fmt.Errorf("bad format: %s", val)
+ }
+ if !strings.HasPrefix(split[0], "/dev/") {
+ return nil, fmt.Errorf("bad format for device path: %s", val)
+ }
+ rate, err := units.RAMInBytes(split[1])
+ if err != nil {
+ return nil, fmt.Errorf("invalid rate for device: %s. The correct format is <device-path>:<number>[<unit>]. Number must be a positive integer. Unit is optional and can be kb, mb, or gb", val)
+ }
+ if rate < 0 {
+ return nil, fmt.Errorf("invalid rate for device: %s. The correct format is <device-path>:<number>[<unit>]. Number must be a positive integer. Unit is optional and can be kb, mb, or gb", val)
+ }
+
+ return &blkiodev.ThrottleDevice{
+ Path: split[0],
+ Rate: uint64(rate),
+ }, nil
+}
+
+// ValidateThrottleIOpsDevice validates that the specified string has a valid device-rate format.
+func ValidateThrottleIOpsDevice(val string) (*blkiodev.ThrottleDevice, error) {
+ split := strings.SplitN(val, ":", 2)
+ if len(split) != 2 {
+ return nil, fmt.Errorf("bad format: %s", val)
+ }
+ if !strings.HasPrefix(split[0], "/dev/") {
+ return nil, fmt.Errorf("bad format for device path: %s", val)
+ }
+ rate, err := strconv.ParseUint(split[1], 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("invalid rate for device: %s. The correct format is <device-path>:<number>. Number must be a positive integer", val)
+ }
+ if rate < 0 {
+ return nil, fmt.Errorf("invalid rate for device: %s. The correct format is <device-path>:<number>. Number must be a positive integer", val)
+ }
+
+ return &blkiodev.ThrottleDevice{Path: split[0], Rate: rate}, nil
+}
+
+// ThrottledeviceOpt defines a map of ThrottleDevices
+type ThrottledeviceOpt struct {
+ values []*blkiodev.ThrottleDevice
+ validator ValidatorThrottleFctType
+}
+
+// NewThrottledeviceOpt creates a new ThrottledeviceOpt
+func NewThrottledeviceOpt(validator ValidatorThrottleFctType) ThrottledeviceOpt {
+ values := []*blkiodev.ThrottleDevice{}
+ return ThrottledeviceOpt{
+ values: values,
+ validator: validator,
+ }
+}
+
+// Set validates a ThrottleDevice and sets its name as a key in ThrottledeviceOpt
+func (opt *ThrottledeviceOpt) Set(val string) error {
+ var value *blkiodev.ThrottleDevice
+ if opt.validator != nil {
+ v, err := opt.validator(val)
+ if err != nil {
+ return err
+ }
+ value = v
+ }
+ (opt.values) = append((opt.values), value)
+ return nil
+}
+
+// String returns ThrottledeviceOpt values as a string.
+func (opt *ThrottledeviceOpt) String() string {
+ var out []string
+ for _, v := range opt.values {
+ out = append(out, v.String())
+ }
+
+ return fmt.Sprintf("%v", out)
+}
+
+// GetList returns a slice of pointers to ThrottleDevices.
+func (opt *ThrottledeviceOpt) GetList() []*blkiodev.ThrottleDevice {
+ var throttledevice []*blkiodev.ThrottleDevice
+ throttledevice = append(throttledevice, opt.values...)
+
+ return throttledevice
+}
+
+// Type returns the option type
+func (opt *ThrottledeviceOpt) Type() string {
+ return "list"
+}
diff --git a/vendor/github.com/docker/cli/opts/ulimit.go b/vendor/github.com/docker/cli/opts/ulimit.go
new file mode 100644
index 0000000..5adfe30
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/ulimit.go
@@ -0,0 +1,57 @@
+package opts
+
+import (
+ "fmt"
+
+ "github.com/docker/go-units"
+)
+
+// UlimitOpt defines a map of Ulimits
+type UlimitOpt struct {
+ values *map[string]*units.Ulimit
+}
+
+// NewUlimitOpt creates a new UlimitOpt
+func NewUlimitOpt(ref *map[string]*units.Ulimit) *UlimitOpt {
+ if ref == nil {
+ ref = &map[string]*units.Ulimit{}
+ }
+ return &UlimitOpt{ref}
+}
+
+// Set validates a Ulimit and sets its name as a key in UlimitOpt
+func (o *UlimitOpt) Set(val string) error {
+ l, err := units.ParseUlimit(val)
+ if err != nil {
+ return err
+ }
+
+ (*o.values)[l.Name] = l
+
+ return nil
+}
+
+// String returns Ulimit values as a string.
+func (o *UlimitOpt) String() string {
+ var out []string
+ for _, v := range *o.values {
+ out = append(out, v.String())
+ }
+
+ return fmt.Sprintf("%v", out)
+}
+
+// GetList returns a slice of pointers to Ulimits.
+func (o *UlimitOpt) GetList() []*units.Ulimit {
+ var ulimits []*units.Ulimit
+ for _, v := range *o.values {
+ ulimits = append(ulimits, v)
+ }
+
+ return ulimits
+}
+
+// Type returns the option type
+func (o *UlimitOpt) Type() string {
+ return "ulimit"
+}
diff --git a/vendor/github.com/docker/cli/opts/weightdevice.go b/vendor/github.com/docker/cli/opts/weightdevice.go
new file mode 100644
index 0000000..46ce9b6
--- /dev/null
+++ b/vendor/github.com/docker/cli/opts/weightdevice.go
@@ -0,0 +1,84 @@
+package opts
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/docker/docker/api/types/blkiodev"
+)
+
+// ValidatorWeightFctType defines a validator function that returns a validated struct and/or an error.
+type ValidatorWeightFctType func(val string) (*blkiodev.WeightDevice, error)
+
+// ValidateWeightDevice validates that the specified string has a valid device-weight format.
+func ValidateWeightDevice(val string) (*blkiodev.WeightDevice, error) {
+ split := strings.SplitN(val, ":", 2)
+ if len(split) != 2 {
+ return nil, fmt.Errorf("bad format: %s", val)
+ }
+ if !strings.HasPrefix(split[0], "/dev/") {
+ return nil, fmt.Errorf("bad format for device path: %s", val)
+ }
+ weight, err := strconv.ParseUint(split[1], 10, 0)
+ if err != nil {
+ return nil, fmt.Errorf("invalid weight for device: %s", val)
+ }
+ if weight > 0 && (weight < 10 || weight > 1000) {
+ return nil, fmt.Errorf("invalid weight for device: %s", val)
+ }
+
+ return &blkiodev.WeightDevice{
+ Path: split[0],
+ Weight: uint16(weight),
+ }, nil
+}
+
+// WeightdeviceOpt defines a map of WeightDevices
+type WeightdeviceOpt struct {
+ values []*blkiodev.WeightDevice
+ validator ValidatorWeightFctType
+}
+
+// NewWeightdeviceOpt creates a new WeightdeviceOpt
+func NewWeightdeviceOpt(validator ValidatorWeightFctType) WeightdeviceOpt {
+ values := []*blkiodev.WeightDevice{}
+ return WeightdeviceOpt{
+ values: values,
+ validator: validator,
+ }
+}
+
+// Set validates a WeightDevice and sets its name as a key in WeightdeviceOpt
+func (opt *WeightdeviceOpt) Set(val string) error {
+ var value *blkiodev.WeightDevice
+ if opt.validator != nil {
+ v, err := opt.validator(val)
+ if err != nil {
+ return err
+ }
+ value = v
+ }
+ (opt.values) = append((opt.values), value)
+ return nil
+}
+
+// String returns WeightdeviceOpt values as a string.
+func (opt *WeightdeviceOpt) String() string {
+ var out []string
+ for _, v := range opt.values {
+ out = append(out, v.String())
+ }
+
+ return fmt.Sprintf("%v", out)
+}
+
+// GetList returns a slice of pointers to WeightDevices.
+func (opt *WeightdeviceOpt) GetList() []*blkiodev.WeightDevice {
+ return opt.values
+}
+
+// Type returns the option type
+func (opt *WeightdeviceOpt) Type() string {
+ return "list"
+}
diff --git a/vendor/github.com/docker/cli/vendor.conf b/vendor/github.com/docker/cli/vendor.conf
new file mode 100755
index 0000000..5fff08c
--- /dev/null
+++ b/vendor/github.com/docker/cli/vendor.conf
@@ -0,0 +1,51 @@
+github.com/Azure/go-ansiterm 388960b655244e76e24c75f48631564eaefade62
+github.com/Microsoft/go-winio v0.4.1
+github.com/Nvveen/Gotty a8b993ba6abdb0e0c12b0125c603323a71c7790c https://github.com/ijc25/Gotty
+github.com/Sirupsen/logrus v0.11.0
+github.com/agl/ed25519 d2b94fd789ea21d12fac1a4443dd3a3f79cda72c
+github.com/coreos/etcd 824277cb3a577a0e8c829ca9ec557b973fe06d20
+github.com/cpuguy83/go-md2man a65d4d2de4d5f7c74868dfa9b202a3c8be315aaa
+github.com/davecgh/go-spew 346938d642f2ec3594ed81d874461961cd0faa76
+github.com/docker/distribution b38e5838b7b2f2ad48e06ec4b500011976080621
+github.com/docker/docker 050c1bb17bd033e909cb653f5449b683608293d6
+github.com/docker/docker-credential-helpers v0.5.1
+github.com/docker/go d30aec9fd63c35133f8f79c3412ad91a3b08be06 #?
+github.com/docker/go-connections e15c02316c12de00874640cd76311849de2aeed5
+github.com/docker/go-events 18b43f1bc85d9cdd42c05a6cd2d444c7a200a894
+github.com/docker/go-units 9e638d38cf6977a37a8ea0078f3ee75a7cdb2dd1
+github.com/docker/libtrust 9cbd2a1374f46905c68a4eb3694a130610adc62a
+github.com/docker/notary v0.4.2
+github.com/docker/swarmkit 1a3e510517be82d18ac04380b5f71eddf06c2fc0
+github.com/flynn-archive/go-shlex 3f9db97f856818214da2e1057f8ad84803971cff
+github.com/gogo/protobuf 7efa791bd276fd4db00867cbd982b552627c24cb
+github.com/golang/protobuf 8ee79997227bf9b34611aee7946ae64735e6fd93
+github.com/gorilla/context v1.1
+github.com/gorilla/mux v1.1
+github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75
+github.com/mattn/go-shellwords v1.0.3
+github.com/miekg/pkcs11 df8ae6ca730422dba20c768ff38ef7d79077a59f
+github.com/mitchellh/mapstructure f3009df150dadf309fdee4a54ed65c124afad715
+github.com/opencontainers/go-digest a6d0ee40d4207ea02364bd3b9e8e77b9159ba1eb
+github.com/opencontainers/image-spec f03dbe35d449c54915d235f1a3cf8f585a24babe
+github.com/opencontainers/runc 9c2d8d184e5da67c95d601382adf14862e4f2228 https://github.com/docker/runc.git
+github.com/opencontainers/selinux v1.0.0-rc1
+github.com/pkg/errors 839d9e913e063e28dfd0e6c7b7512793e0a48be9
+github.com/pmezard/go-difflib 792786c7400a136282c1664665ae0a8db921c6c2
+github.com/russross/blackfriday 1d6b8e9301e720b08a8938b8c25c018285885438
+github.com/shurcooL/sanitized_anchor_name 10ef21a441db47d8b13ebcc5fd2310f636973c77
+github.com/spf13/cobra v1.5.1 https://github.com/dnephin/cobra.git
+github.com/spf13/pflag 9ff6c6923cfffbcd502984b8e0c80539a94968b7
+github.com/stretchr/testify 4d4bfba8f1d1027c4fdbe371823030df51419987
+github.com/xeipuuv/gojsonpointer e0fe6f68307607d540ed8eac07a342c33fa1b54a
+github.com/xeipuuv/gojsonreference e02fc20de94c78484cd5ffb007f8af96be030a45
+github.com/xeipuuv/gojsonschema 93e72a773fade158921402d6a24c819b48aba29d
+golang.org/x/crypto 3fbbcd23f1cb824e69491a5930cfeff09b12f4d2
+golang.org/x/net c427ad74c6d7a814201695e9ffde0c5d400a7674
+golang.org/x/sys 8f0908ab3b2457e2e15403d3697c9ef5cb4b57a9
+golang.org/x/text f72d8390a633d5dfb0cc84043294db9f6c935756
+golang.org/x/time a4bde12657593d5e90d0533a3e4fd95e635124cb
+google.golang.org/grpc v1.0.4
+gopkg.in/yaml.v2 4c78c975fe7c825c6d1466c42be594d1d6f3aba6
+github.com/tonistiigi/fsutil 0ac4c11b053b9c5c7c47558f81f96c7100ce50fb
+github.com/stevvooe/continuity cd7a8e21e2b6f84799f5dd4b65faf49c8d3ee02d
+golang.org/x/sync de49d9dcd27d4f764488181bea099dfe6179bcf0
diff --git a/vendor/github.com/docker/distribution/LICENSE b/vendor/github.com/docker/distribution/LICENSE
new file mode 100644
index 0000000..e06d208
--- /dev/null
+++ b/vendor/github.com/docker/distribution/LICENSE
@@ -0,0 +1,202 @@
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/vendor/github.com/docker/distribution/README.md b/vendor/github.com/docker/distribution/README.md
new file mode 100644
index 0000000..a6e8db0
--- /dev/null
+++ b/vendor/github.com/docker/distribution/README.md
@@ -0,0 +1,131 @@
+# Distribution
+
+The Docker toolset to pack, ship, store, and deliver content.
+
+This repository's main product is the Docker Registry 2.0 implementation
+for storing and distributing Docker images. It supersedes the
+[docker/docker-registry](https://github.com/docker/docker-registry)
+project with a new API design, focused around security and performance.
+
+<img src="https://www.docker.com/sites/default/files/oyster-registry-3.png" width=200px/>
+
+[![Circle CI](https://circleci.com/gh/docker/distribution/tree/master.svg?style=svg)](https://circleci.com/gh/docker/distribution/tree/master)
+[![GoDoc](https://godoc.org/github.com/docker/distribution?status.svg)](https://godoc.org/github.com/docker/distribution)
+
+This repository contains the following components:
+
+|**Component** |Description |
+|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| **registry** | An implementation of the [Docker Registry HTTP API V2](docs/spec/api.md) for use with docker 1.6+. |
+| **libraries** | A rich set of libraries for interacting with distribution components. Please see [godoc](https://godoc.org/github.com/docker/distribution) for details. **Note**: These libraries are **unstable**. |
+| **specifications** | _Distribution_ related specifications are available in [docs/spec](docs/spec) |
+| **documentation** | Docker's full documentation set is available at [docs.docker.com](https://docs.docker.com). This repository [contains the subset](docs/) related just to the registry. |
+
+### How does this integrate with Docker engine?
+
+This project should provide an implementation to a V2 API for use in the [Docker
+core project](https://github.com/docker/docker). The API should be embeddable
+and simplify the process of securely pulling and pushing content from `docker`
+daemons.
+
+### What are the long term goals of the Distribution project?
+
+The _Distribution_ project has the further long term goal of providing a
+secure tool chain for distributing content. The specifications, APIs and tools
+should be as useful with Docker as they are without.
+
+Our goal is to design a professional grade and extensible content distribution
+system that allow users to:
+
+* Enjoy an efficient, secured and reliable way to store, manage, package and
+ exchange content
+* Hack/roll their own on top of healthy open-source components
+* Implement their own home made solution through good specs, and solid
+ extensions mechanism.
+
+## More about Registry 2.0
+
+The new registry implementation provides the following benefits:
+
+- faster push and pull
+- new, more efficient implementation
+- simplified deployment
+- pluggable storage backend
+- webhook notifications
+
+For information on upcoming functionality, please see [ROADMAP.md](ROADMAP.md).
+
+### Who needs to deploy a registry?
+
+By default, Docker users pull images from Docker's public registry instance.
+[Installing Docker](https://docs.docker.com/engine/installation/) gives users this
+ability. Users can also push images to a repository on Docker's public registry,
+if they have a [Docker Hub](https://hub.docker.com/) account.
+
+For some users and even companies, this default behavior is sufficient. For
+others, it is not.
+
+For example, users with their own software products may want to maintain a
+registry for private, company images. Also, you may wish to deploy your own
+image repository for images used to test or in continuous integration. For these
+use cases and others, [deploying your own registry instance](https://github.com/docker/docker.github.io/blob/master/registry/deploying.md)
+may be the better choice.
+
+### Migration to Registry 2.0
+
+For those who have previously deployed their own registry based on the Registry
+1.0 implementation and wish to deploy a Registry 2.0 while retaining images,
+data migration is required. A tool to assist with migration efforts has been
+created. For more information see [docker/migrator]
+(https://github.com/docker/migrator).
+
+## Contribute
+
+Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute
+issues, fixes, and patches to this project. If you are contributing code, see
+the instructions for [building a development environment](BUILDING.md).
+
+## Support
+
+If any issues are encountered while using the _Distribution_ project, several
+avenues are available for support:
+
+<table>
+<tr>
+ <th align="left">
+ IRC
+ </th>
+ <td>
+ #docker-distribution on FreeNode
+ </td>
+</tr>
+<tr>
+ <th align="left">
+ Issue Tracker
+ </th>
+ <td>
+ github.com/docker/distribution/issues
+ </td>
+</tr>
+<tr>
+ <th align="left">
+ Google Groups
+ </th>
+ <td>
+ https://groups.google.com/a/dockerproject.org/forum/#!forum/distribution
+ </td>
+</tr>
+<tr>
+ <th align="left">
+ Mailing List
+ </th>
+ <td>
+ docker@dockerproject.org
+ </td>
+</tr>
+</table>
+
+
+## License
+
+This project is distributed under [Apache License, Version 2.0](LICENSE).
diff --git a/vendor/github.com/docker/distribution/blobs.go b/vendor/github.com/docker/distribution/blobs.go
new file mode 100644
index 0000000..79c5fb3
--- /dev/null
+++ b/vendor/github.com/docker/distribution/blobs.go
@@ -0,0 +1,257 @@
+package distribution
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/docker/distribution/context"
+ "github.com/docker/distribution/reference"
+ "github.com/opencontainers/go-digest"
+)
+
+var (
+ // ErrBlobExists returned when blob already exists
+ ErrBlobExists = errors.New("blob exists")
+
+ // ErrBlobDigestUnsupported when blob digest is an unsupported version.
+ ErrBlobDigestUnsupported = errors.New("unsupported blob digest")
+
+ // ErrBlobUnknown when blob is not found.
+ ErrBlobUnknown = errors.New("unknown blob")
+
+ // ErrBlobUploadUnknown returned when upload is not found.
+ ErrBlobUploadUnknown = errors.New("blob upload unknown")
+
+ // ErrBlobInvalidLength returned when the blob has an expected length on
+ // commit, meaning mismatched with the descriptor or an invalid value.
+ ErrBlobInvalidLength = errors.New("blob invalid length")
+)
+
+// ErrBlobInvalidDigest returned when digest check fails.
+type ErrBlobInvalidDigest struct {
+ Digest digest.Digest
+ Reason error
+}
+
+func (err ErrBlobInvalidDigest) Error() string {
+ return fmt.Sprintf("invalid digest for referenced layer: %v, %v",
+ err.Digest, err.Reason)
+}
+
+// ErrBlobMounted returned when a blob is mounted from another repository
+// instead of initiating an upload session.
+type ErrBlobMounted struct {
+ From reference.Canonical
+ Descriptor Descriptor
+}
+
+func (err ErrBlobMounted) Error() string {
+ return fmt.Sprintf("blob mounted from: %v to: %v",
+ err.From, err.Descriptor)
+}
+
+// Descriptor describes targeted content. Used in conjunction with a blob
+// store, a descriptor can be used to fetch, store and target any kind of
+// blob. The struct also describes the wire protocol format. Fields should
+// only be added but never changed.
+type Descriptor struct {
+ // MediaType describe the type of the content. All text based formats are
+ // encoded as utf-8.
+ MediaType string `json:"mediaType,omitempty"`
+
+ // Size in bytes of content.
+ Size int64 `json:"size,omitempty"`
+
+ // Digest uniquely identifies the content. A byte stream can be verified
+ // against against this digest.
+ Digest digest.Digest `json:"digest,omitempty"`
+
+ // URLs contains the source URLs of this content.
+ URLs []string `json:"urls,omitempty"`
+
+ // NOTE: Before adding a field here, please ensure that all
+ // other options have been exhausted. Much of the type relationships
+ // depend on the simplicity of this type.
+}
+
+// Descriptor returns the descriptor, to make it satisfy the Describable
+// interface. Note that implementations of Describable are generally objects
+// which can be described, not simply descriptors; this exception is in place
+// to make it more convenient to pass actual descriptors to functions that
+// expect Describable objects.
+func (d Descriptor) Descriptor() Descriptor {
+ return d
+}
+
+// BlobStatter makes blob descriptors available by digest. The service may
+// provide a descriptor of a different digest if the provided digest is not
+// canonical.
+type BlobStatter interface {
+ // Stat provides metadata about a blob identified by the digest. If the
+ // blob is unknown to the describer, ErrBlobUnknown will be returned.
+ Stat(ctx context.Context, dgst digest.Digest) (Descriptor, error)
+}
+
+// BlobDeleter enables deleting blobs from storage.
+type BlobDeleter interface {
+ Delete(ctx context.Context, dgst digest.Digest) error
+}
+
+// BlobEnumerator enables iterating over blobs from storage
+type BlobEnumerator interface {
+ Enumerate(ctx context.Context, ingester func(dgst digest.Digest) error) error
+}
+
+// BlobDescriptorService manages metadata about a blob by digest. Most
+// implementations will not expose such an interface explicitly. Such mappings
+// should be maintained by interacting with the BlobIngester. Hence, this is
+// left off of BlobService and BlobStore.
+type BlobDescriptorService interface {
+ BlobStatter
+
+ // SetDescriptor assigns the descriptor to the digest. The provided digest and
+ // the digest in the descriptor must map to identical content but they may
+ // differ on their algorithm. The descriptor must have the canonical
+ // digest of the content and the digest algorithm must match the
+ // annotators canonical algorithm.
+ //
+ // Such a facility can be used to map blobs between digest domains, with
+ // the restriction that the algorithm of the descriptor must match the
+ // canonical algorithm (ie sha256) of the annotator.
+ SetDescriptor(ctx context.Context, dgst digest.Digest, desc Descriptor) error
+
+ // Clear enables descriptors to be unlinked
+ Clear(ctx context.Context, dgst digest.Digest) error
+}
+
+// BlobDescriptorServiceFactory creates middleware for BlobDescriptorService.
+type BlobDescriptorServiceFactory interface {
+ BlobAccessController(svc BlobDescriptorService) BlobDescriptorService
+}
+
+// ReadSeekCloser is the primary reader type for blob data, combining
+// io.ReadSeeker with io.Closer.
+type ReadSeekCloser interface {
+ io.ReadSeeker
+ io.Closer
+}
+
+// BlobProvider describes operations for getting blob data.
+type BlobProvider interface {
+ // Get returns the entire blob identified by digest along with the descriptor.
+ Get(ctx context.Context, dgst digest.Digest) ([]byte, error)
+
+ // Open provides a ReadSeekCloser to the blob identified by the provided
+ // descriptor. If the blob is not known to the service, an error will be
+ // returned.
+ Open(ctx context.Context, dgst digest.Digest) (ReadSeekCloser, error)
+}
+
+// BlobServer can serve blobs via http.
+type BlobServer interface {
+ // ServeBlob attempts to serve the blob, identifed by dgst, via http. The
+ // service may decide to redirect the client elsewhere or serve the data
+ // directly.
+ //
+ // This handler only issues successful responses, such as 2xx or 3xx,
+ // meaning it serves data or issues a redirect. If the blob is not
+ // available, an error will be returned and the caller may still issue a
+ // response.
+ //
+ // The implementation may serve the same blob from a different digest
+ // domain. The appropriate headers will be set for the blob, unless they
+ // have already been set by the caller.
+ ServeBlob(ctx context.Context, w http.ResponseWriter, r *http.Request, dgst digest.Digest) error
+}
+
+// BlobIngester ingests blob data.
+type BlobIngester interface {
+ // Put inserts the content p into the blob service, returning a descriptor
+ // or an error.
+ Put(ctx context.Context, mediaType string, p []byte) (Descriptor, error)
+
+ // Create allocates a new blob writer to add a blob to this service. The
+ // returned handle can be written to and later resumed using an opaque
+ // identifier. With this approach, one can Close and Resume a BlobWriter
+ // multiple times until the BlobWriter is committed or cancelled.
+ Create(ctx context.Context, options ...BlobCreateOption) (BlobWriter, error)
+
+ // Resume attempts to resume a write to a blob, identified by an id.
+ Resume(ctx context.Context, id string) (BlobWriter, error)
+}
+
+// BlobCreateOption is a general extensible function argument for blob creation
+// methods. A BlobIngester may choose to honor any or none of the given
+// BlobCreateOptions, which can be specific to the implementation of the
+// BlobIngester receiving them.
+// TODO (brianbland): unify this with ManifestServiceOption in the future
+type BlobCreateOption interface {
+ Apply(interface{}) error
+}
+
+// CreateOptions is a collection of blob creation modifiers relevant to general
+// blob storage intended to be configured by the BlobCreateOption.Apply method.
+type CreateOptions struct {
+ Mount struct {
+ ShouldMount bool
+ From reference.Canonical
+ // Stat allows to pass precalculated descriptor to link and return.
+ // Blob access check will be skipped if set.
+ Stat *Descriptor
+ }
+}
+
+// BlobWriter provides a handle for inserting data into a blob store.
+// Instances should be obtained from BlobWriteService.Writer and
+// BlobWriteService.Resume. If supported by the store, a writer can be
+// recovered with the id.
+type BlobWriter interface {
+ io.WriteCloser
+ io.ReaderFrom
+
+ // Size returns the number of bytes written to this blob.
+ Size() int64
+
+ // ID returns the identifier for this writer. The ID can be used with the
+ // Blob service to later resume the write.
+ ID() string
+
+ // StartedAt returns the time this blob write was started.
+ StartedAt() time.Time
+
+ // Commit completes the blob writer process. The content is verified
+ // against the provided provisional descriptor, which may result in an
+ // error. Depending on the implementation, written data may be validated
+ // against the provisional descriptor fields. If MediaType is not present,
+ // the implementation may reject the commit or assign "application/octet-
+ // stream" to the blob. The returned descriptor may have a different
+ // digest depending on the blob store, referred to as the canonical
+ // descriptor.
+ Commit(ctx context.Context, provisional Descriptor) (canonical Descriptor, err error)
+
+ // Cancel ends the blob write without storing any data and frees any
+ // associated resources. Any data written thus far will be lost. Cancel
+ // implementations should allow multiple calls even after a commit that
+ // result in a no-op. This allows use of Cancel in a defer statement,
+ // increasing the assurance that it is correctly called.
+ Cancel(ctx context.Context) error
+}
+
+// BlobService combines the operations to access, read and write blobs. This
+// can be used to describe remote blob services.
+type BlobService interface {
+ BlobStatter
+ BlobProvider
+ BlobIngester
+}
+
+// BlobStore represent the entire suite of blob related operations. Such an
+// implementation can access, read, write, delete and serve blobs.
+type BlobStore interface {
+ BlobService
+ BlobServer
+ BlobDeleter
+}
diff --git a/vendor/github.com/docker/distribution/context/context.go b/vendor/github.com/docker/distribution/context/context.go
new file mode 100644
index 0000000..23cbf5b
--- /dev/null
+++ b/vendor/github.com/docker/distribution/context/context.go
@@ -0,0 +1,85 @@
+package context
+
+import (
+ "sync"
+
+ "github.com/docker/distribution/uuid"
+ "golang.org/x/net/context"
+)
+
+// Context is a copy of Context from the golang.org/x/net/context package.
+type Context interface {
+ context.Context
+}
+
+// instanceContext is a context that provides only an instance id. It is
+// provided as the main background context.
+type instanceContext struct {
+ Context
+ id string // id of context, logged as "instance.id"
+ once sync.Once // once protect generation of the id
+}
+
+func (ic *instanceContext) Value(key interface{}) interface{} {
+ if key == "instance.id" {
+ ic.once.Do(func() {
+ // We want to lazy initialize the UUID such that we don't
+ // call a random generator from the package initialization
+ // code. For various reasons random could not be available
+ // https://github.com/docker/distribution/issues/782
+ ic.id = uuid.Generate().String()
+ })
+ return ic.id
+ }
+
+ return ic.Context.Value(key)
+}
+
+var background = &instanceContext{
+ Context: context.Background(),
+}
+
+// Background returns a non-nil, empty Context. The background context
+// provides a single key, "instance.id" that is globally unique to the
+// process.
+func Background() Context {
+ return background
+}
+
+// WithValue returns a copy of parent in which the value associated with key is
+// val. Use context Values only for request-scoped data that transits processes
+// and APIs, not for passing optional parameters to functions.
+func WithValue(parent Context, key, val interface{}) Context {
+ return context.WithValue(parent, key, val)
+}
+
+// stringMapContext is a simple context implementation that checks a map for a
+// key, falling back to a parent if not present.
+type stringMapContext struct {
+ context.Context
+ m map[string]interface{}
+}
+
+// WithValues returns a context that proxies lookups through a map. Only
+// supports string keys.
+func WithValues(ctx context.Context, m map[string]interface{}) context.Context {
+ mo := make(map[string]interface{}, len(m)) // make our own copy.
+ for k, v := range m {
+ mo[k] = v
+ }
+
+ return stringMapContext{
+ Context: ctx,
+ m: mo,
+ }
+}
+
+func (smc stringMapContext) Value(key interface{}) interface{} {
+ if ks, ok := key.(string); ok {
+ if v, ok := smc.m[ks]; ok {
+ return v
+ }
+ }
+
+ return smc.Context.Value(key)
+}
diff --git a/vendor/github.com/docker/distribution/context/doc.go b/vendor/github.com/docker/distribution/context/doc.go
new file mode 100644
index 0000000..3b4ab88
--- /dev/null
+++ b/vendor/github.com/docker/distribution/context/doc.go
@@ -0,0 +1,89 @@
+// Package context provides several utilities for working with
+// golang.org/x/net/context in http requests. Primarily, the focus is on
+// logging relevant request information but this package is not limited to
+// that purpose.
+//
+// The easiest way to get started is to get the background context:
+//
+// ctx := context.Background()
+//
+// The returned context should be passed around your application and be the
+// root of all other context instances. If the application has a version, this
+// line should be called before anything else:
+//
+// ctx := context.WithVersion(context.Background(), version)
+//
+// The above will store the version in the context and will be available to
+// the logger.
+//
+// Logging
+//
+// The most useful aspect of this package is GetLogger. This function takes
+// any context.Context interface and returns the current logger from the
+// context. Canonical usage looks like this:
+//
+// GetLogger(ctx).Infof("something interesting happened")
+//
+// GetLogger also takes optional key arguments. The keys will be looked up in
+// the context and reported with the logger. The following example would
+// return a logger that prints the version with each log message:
+//
+// ctx := context.Context(context.Background(), "version", version)
+// GetLogger(ctx, "version").Infof("this log message has a version field")
+//
+// The above would print out a log message like this:
+//
+// INFO[0000] this log message has a version field version=v2.0.0-alpha.2.m
+//
+// When used with WithLogger, we gain the ability to decorate the context with
+// loggers that have information from disparate parts of the call stack.
+// Following from the version example, we can build a new context with the
+// configured logger such that we always print the version field:
+//
+// ctx = WithLogger(ctx, GetLogger(ctx, "version"))
+//
+// Since the logger has been pushed to the context, we can now get the version
+// field for free with our log messages. Future calls to GetLogger on the new
+// context will have the version field:
+//
+// GetLogger(ctx).Infof("this log message has a version field")
+//
+// This becomes more powerful when we start stacking loggers. Let's say we
+// have the version logger from above but also want a request id. Using the
+// context above, in our request scoped function, we place another logger in
+// the context:
+//
+// ctx = context.WithValue(ctx, "http.request.id", "unique id") // called when building request context
+// ctx = WithLogger(ctx, GetLogger(ctx, "http.request.id"))
+//
+// When GetLogger is called on the new context, "http.request.id" will be
+// included as a logger field, along with the original "version" field:
+//
+// INFO[0000] this log message has a version field http.request.id=unique id version=v2.0.0-alpha.2.m
+//
+// Note that this only affects the new context, the previous context, with the
+// version field, can be used independently. Put another way, the new logger,
+// added to the request context, is unique to that context and can have
+// request scoped varaibles.
+//
+// HTTP Requests
+//
+// This package also contains several methods for working with http requests.
+// The concepts are very similar to those described above. We simply place the
+// request in the context using WithRequest. This makes the request variables
+// available. GetRequestLogger can then be called to get request specific
+// variables in a log line:
+//
+// ctx = WithRequest(ctx, req)
+// GetRequestLogger(ctx).Infof("request variables")
+//
+// Like above, if we want to include the request data in all log messages in
+// the context, we push the logger to a new context and use that one:
+//
+// ctx = WithLogger(ctx, GetRequestLogger(ctx))
+//
+// The concept is fairly powerful and ensures that calls throughout the stack
+// can be traced in log messages. Using the fields like "http.request.id", one
+// can analyze call flow for a particular request with a simple grep of the
+// logs.
+package context
diff --git a/vendor/github.com/docker/distribution/context/http.go b/vendor/github.com/docker/distribution/context/http.go
new file mode 100644
index 0000000..7fe9b8a
--- /dev/null
+++ b/vendor/github.com/docker/distribution/context/http.go
@@ -0,0 +1,366 @@
+package context
+
+import (
+ "errors"
+ "net"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ log "github.com/Sirupsen/logrus"
+ "github.com/docker/distribution/uuid"
+ "github.com/gorilla/mux"
+)
+
+// Common errors used with this package.
+var (
+ ErrNoRequestContext = errors.New("no http request in context")
+ ErrNoResponseWriterContext = errors.New("no http response in context")
+)
+
+func parseIP(ipStr string) net.IP {
+ ip := net.ParseIP(ipStr)
+ if ip == nil {
+ log.Warnf("invalid remote IP address: %q", ipStr)
+ }
+ return ip
+}
+
+// RemoteAddr extracts the remote address of the request, taking into
+// account proxy headers.
+func RemoteAddr(r *http.Request) string {
+ if prior := r.Header.Get("X-Forwarded-For"); prior != "" {
+ proxies := strings.Split(prior, ",")
+ if len(proxies) > 0 {
+ remoteAddr := strings.Trim(proxies[0], " ")
+ if parseIP(remoteAddr) != nil {
+ return remoteAddr
+ }
+ }
+ }
+ // X-Real-Ip is less supported, but worth checking in the
+ // absence of X-Forwarded-For
+ if realIP := r.Header.Get("X-Real-Ip"); realIP != "" {
+ if parseIP(realIP) != nil {
+ return realIP
+ }
+ }
+
+ return r.RemoteAddr
+}
+
+// RemoteIP extracts the remote IP of the request, taking into
+// account proxy headers.
+func RemoteIP(r *http.Request) string {
+ addr := RemoteAddr(r)
+
+ // Try parsing it as "IP:port"
+ if ip, _, err := net.SplitHostPort(addr); err == nil {
+ return ip
+ }
+
+ return addr
+}
+
+// WithRequest places the request on the context. The context of the request
+// is assigned a unique id, available at "http.request.id". The request itself
+// is available at "http.request". Other common attributes are available under
+// the prefix "http.request.". If a request is already present on the context,
+// this method will panic.
+func WithRequest(ctx Context, r *http.Request) Context {
+ if ctx.Value("http.request") != nil {
+ // NOTE(stevvooe): This needs to be considered a programming error. It
+ // is unlikely that we'd want to have more than one request in
+ // context.
+ panic("only one request per context")
+ }
+
+ return &httpRequestContext{
+ Context: ctx,
+ startedAt: time.Now(),
+ id: uuid.Generate().String(),
+ r: r,
+ }
+}
+
+// GetRequest returns the http request in the given context. Returns
+// ErrNoRequestContext if the context does not have an http request associated
+// with it.
+func GetRequest(ctx Context) (*http.Request, error) {
+ if r, ok := ctx.Value("http.request").(*http.Request); r != nil && ok {
+ return r, nil
+ }
+ return nil, ErrNoRequestContext
+}
+
+// GetRequestID attempts to resolve the current request id, if possible. An
+// error is return if it is not available on the context.
+func GetRequestID(ctx Context) string {
+ return GetStringValue(ctx, "http.request.id")
+}
+
+// WithResponseWriter returns a new context and response writer that makes
+// interesting response statistics available within the context.
+func WithResponseWriter(ctx Context, w http.ResponseWriter) (Context, http.ResponseWriter) {
+ if closeNotifier, ok := w.(http.CloseNotifier); ok {
+ irwCN := &instrumentedResponseWriterCN{
+ instrumentedResponseWriter: instrumentedResponseWriter{
+ ResponseWriter: w,
+ Context: ctx,
+ },
+ CloseNotifier: closeNotifier,
+ }
+
+ return irwCN, irwCN
+ }
+
+ irw := instrumentedResponseWriter{
+ ResponseWriter: w,
+ Context: ctx,
+ }
+ return &irw, &irw
+}
+
+// GetResponseWriter returns the http.ResponseWriter from the provided
+// context. If not present, ErrNoResponseWriterContext is returned. The
+// returned instance provides instrumentation in the context.
+func GetResponseWriter(ctx Context) (http.ResponseWriter, error) {
+ v := ctx.Value("http.response")
+
+ rw, ok := v.(http.ResponseWriter)
+ if !ok || rw == nil {
+ return nil, ErrNoResponseWriterContext
+ }
+
+ return rw, nil
+}
+
+// getVarsFromRequest let's us change request vars implementation for testing
+// and maybe future changes.
+var getVarsFromRequest = mux.Vars
+
+// WithVars extracts gorilla/mux vars and makes them available on the returned
+// context. Variables are available at keys with the prefix "vars.". For
+// example, if looking for the variable "name", it can be accessed as
+// "vars.name". Implementations that are accessing values need not know that
+// the underlying context is implemented with gorilla/mux vars.
+func WithVars(ctx Context, r *http.Request) Context {
+ return &muxVarsContext{
+ Context: ctx,
+ vars: getVarsFromRequest(r),
+ }
+}
+
+// GetRequestLogger returns a logger that contains fields from the request in
+// the current context. If the request is not available in the context, no
+// fields will display. Request loggers can safely be pushed onto the context.
+func GetRequestLogger(ctx Context) Logger {
+ return GetLogger(ctx,
+ "http.request.id",
+ "http.request.method",
+ "http.request.host",
+ "http.request.uri",
+ "http.request.referer",
+ "http.request.useragent",
+ "http.request.remoteaddr",
+ "http.request.contenttype")
+}
+
+// GetResponseLogger reads the current response stats and builds a logger.
+// Because the values are read at call time, pushing a logger returned from
+// this function on the context will lead to missing or invalid data. Only
+// call this at the end of a request, after the response has been written.
+func GetResponseLogger(ctx Context) Logger {
+ l := getLogrusLogger(ctx,
+ "http.response.written",
+ "http.response.status",
+ "http.response.contenttype")
+
+ duration := Since(ctx, "http.request.startedat")
+
+ if duration > 0 {
+ l = l.WithField("http.response.duration", duration.String())
+ }
+
+ return l
+}
+
+// httpRequestContext makes information about a request available to context.
+type httpRequestContext struct {
+ Context
+
+ startedAt time.Time
+ id string
+ r *http.Request
+}
+
+// Value returns a keyed element of the request for use in the context. To get
+// the request itself, query "request". For other components, access them as
+// "request.<component>". For example, r.RequestURI
+func (ctx *httpRequestContext) Value(key interface{}) interface{} {
+ if keyStr, ok := key.(string); ok {
+ if keyStr == "http.request" {
+ return ctx.r
+ }
+
+ if !strings.HasPrefix(keyStr, "http.request.") {
+ goto fallback
+ }
+
+ parts := strings.Split(keyStr, ".")
+
+ if len(parts) != 3 {
+ goto fallback
+ }
+
+ switch parts[2] {
+ case "uri":
+ return ctx.r.RequestURI
+ case "remoteaddr":
+ return RemoteAddr(ctx.r)
+ case "method":
+ return ctx.r.Method
+ case "host":
+ return ctx.r.Host
+ case "referer":
+ referer := ctx.r.Referer()
+ if referer != "" {
+ return referer
+ }
+ case "useragent":
+ return ctx.r.UserAgent()
+ case "id":
+ return ctx.id
+ case "startedat":
+ return ctx.startedAt
+ case "contenttype":
+ ct := ctx.r.Header.Get("Content-Type")
+ if ct != "" {
+ return ct
+ }
+ }
+ }
+
+fallback:
+ return ctx.Context.Value(key)
+}
+
+type muxVarsContext struct {
+ Context
+ vars map[string]string
+}
+
+func (ctx *muxVarsContext) Value(key interface{}) interface{} {
+ if keyStr, ok := key.(string); ok {
+ if keyStr == "vars" {
+ return ctx.vars
+ }
+
+ if strings.HasPrefix(keyStr, "vars.") {
+ keyStr = strings.TrimPrefix(keyStr, "vars.")
+ }
+
+ if v, ok := ctx.vars[keyStr]; ok {
+ return v
+ }
+ }
+
+ return ctx.Context.Value(key)
+}
+
+// instrumentedResponseWriterCN provides response writer information in a
+// context. It implements http.CloseNotifier so that users can detect
+// early disconnects.
+type instrumentedResponseWriterCN struct {
+ instrumentedResponseWriter
+ http.CloseNotifier
+}
+
+// instrumentedResponseWriter provides response writer information in a
+// context. This variant is only used in the case where CloseNotifier is not
+// implemented by the parent ResponseWriter.
+type instrumentedResponseWriter struct {
+ http.ResponseWriter
+ Context
+
+ mu sync.Mutex
+ status int
+ written int64
+}
+
+func (irw *instrumentedResponseWriter) Write(p []byte) (n int, err error) {
+ n, err = irw.ResponseWriter.Write(p)
+
+ irw.mu.Lock()
+ irw.written += int64(n)
+
+ // Guess the likely status if not set.
+ if irw.status == 0 {
+ irw.status = http.StatusOK
+ }
+
+ irw.mu.Unlock()
+
+ return
+}
+
+func (irw *instrumentedResponseWriter) WriteHeader(status int) {
+ irw.ResponseWriter.WriteHeader(status)
+
+ irw.mu.Lock()
+ irw.status = status
+ irw.mu.Unlock()
+}
+
+func (irw *instrumentedResponseWriter) Flush() {
+ if flusher, ok := irw.ResponseWriter.(http.Flusher); ok {
+ flusher.Flush()
+ }
+}
+
+func (irw *instrumentedResponseWriter) Value(key interface{}) interface{} {
+ if keyStr, ok := key.(string); ok {
+ if keyStr == "http.response" {
+ return irw
+ }
+
+ if !strings.HasPrefix(keyStr, "http.response.") {
+ goto fallback
+ }
+
+ parts := strings.Split(keyStr, ".")
+
+ if len(parts) != 3 {
+ goto fallback
+ }
+
+ irw.mu.Lock()
+ defer irw.mu.Unlock()
+
+ switch parts[2] {
+ case "written":
+ return irw.written
+ case "status":
+ return irw.status
+ case "contenttype":
+ contentType := irw.Header().Get("Content-Type")
+ if contentType != "" {
+ return contentType
+ }
+ }
+ }
+
+fallback:
+ return irw.Context.Value(key)
+}
+
+func (irw *instrumentedResponseWriterCN) Value(key interface{}) interface{} {
+ if keyStr, ok := key.(string); ok {
+ if keyStr == "http.response" {
+ return irw
+ }
+ }
+
+ return irw.instrumentedResponseWriter.Value(key)
+}
diff --git a/vendor/github.com/docker/distribution/context/logger.go b/vendor/github.com/docker/distribution/context/logger.go
new file mode 100644
index 0000000..fbb6a05
--- /dev/null
+++ b/vendor/github.com/docker/distribution/context/logger.go
@@ -0,0 +1,116 @@
+package context
+
+import (
+ "fmt"
+
+ "github.com/Sirupsen/logrus"
+ "runtime"
+)
+
+// Logger provides a leveled-logging interface.
+type Logger interface {
+ // standard logger methods
+ Print(args ...interface{})
+ Printf(format string, args ...interface{})
+ Println(args ...interface{})
+
+ Fatal(args ...interface{})
+ Fatalf(format string, args ...interface{})
+ Fatalln(args ...interface{})
+
+ Panic(args ...interface{})
+ Panicf(format string, args ...interface{})
+ Panicln(args ...interface{})
+
+ // Leveled methods, from logrus
+ Debug(args ...interface{})
+ Debugf(format string, args ...interface{})
+ Debugln(args ...interface{})
+
+ Error(args ...interface{})
+ Errorf(format string, args ...interface{})
+ Errorln(args ...interface{})
+
+ Info(args ...interface{})
+ Infof(format string, args ...interface{})
+ Infoln(args ...interface{})
+
+ Warn(args ...interface{})
+ Warnf(format string, args ...interface{})
+ Warnln(args ...interface{})
+}
+
+// WithLogger creates a new context with provided logger.
+func WithLogger(ctx Context, logger Logger) Context {
+ return WithValue(ctx, "logger", logger)
+}
+
+// GetLoggerWithField returns a logger instance with the specified field key
+// and value without affecting the context. Extra specified keys will be
+// resolved from the context.
+func GetLoggerWithField(ctx Context, key, value interface{}, keys ...interface{}) Logger {
+ return getLogrusLogger(ctx, keys...).WithField(fmt.Sprint(key), value)
+}
+
+// GetLoggerWithFields returns a logger instance with the specified fields
+// without affecting the context. Extra specified keys will be resolved from
+// the context.
+func GetLoggerWithFields(ctx Context, fields map[interface{}]interface{}, keys ...interface{}) Logger {
+ // must convert from interface{} -> interface{} to string -> interface{} for logrus.
+ lfields := make(logrus.Fields, len(fields))
+ for key, value := range fields {
+ lfields[fmt.Sprint(key)] = value
+ }
+
+ return getLogrusLogger(ctx, keys...).WithFields(lfields)
+}
+
+// GetLogger returns the logger from the current context, if present. If one
+// or more keys are provided, they will be resolved on the context and
+// included in the logger. While context.Value takes an interface, any key
+// argument passed to GetLogger will be passed to fmt.Sprint when expanded as
+// a logging key field. If context keys are integer constants, for example,
+// its recommended that a String method is implemented.
+func GetLogger(ctx Context, keys ...interface{}) Logger {
+ return getLogrusLogger(ctx, keys...)
+}
+
+// GetLogrusLogger returns the logrus logger for the context. If one more keys
+// are provided, they will be resolved on the context and included in the
+// logger. Only use this function if specific logrus functionality is
+// required.
+func getLogrusLogger(ctx Context, keys ...interface{}) *logrus.Entry {
+ var logger *logrus.Entry
+
+ // Get a logger, if it is present.
+ loggerInterface := ctx.Value("logger")
+ if loggerInterface != nil {
+ if lgr, ok := loggerInterface.(*logrus.Entry); ok {
+ logger = lgr
+ }
+ }
+
+ if logger == nil {
+ fields := logrus.Fields{}
+
+ // Fill in the instance id, if we have it.
+ instanceID := ctx.Value("instance.id")
+ if instanceID != nil {
+ fields["instance.id"] = instanceID
+ }
+
+ fields["go.version"] = runtime.Version()
+ // If no logger is found, just return the standard logger.
+ logger = logrus.StandardLogger().WithFields(fields)
+ }
+
+ fields := logrus.Fields{}
+ for _, key := range keys {
+ v := ctx.Value(key)
+ if v != nil {
+ fields[fmt.Sprint(key)] = v
+ }
+ }
+
+ return logger.WithFields(fields)
+}
diff --git a/vendor/github.com/docker/distribution/context/trace.go b/vendor/github.com/docker/distribution/context/trace.go
new file mode 100644
index 0000000..721964a
--- /dev/null
+++ b/vendor/github.com/docker/distribution/context/trace.go
@@ -0,0 +1,104 @@
+package context
+
+import (
+ "runtime"
+ "time"
+
+ "github.com/docker/distribution/uuid"
+)
+
+// WithTrace allocates a traced timing span in a new context. This allows a
+// caller to track the time between calling WithTrace and the returned done
+// function. When the done function is called, a log message is emitted with a
+// "trace.duration" field, corresponding to the elapsed time and a
+// "trace.func" field, corresponding to the function that called WithTrace.
+//
+// The logging keys "trace.id" and "trace.parent.id" are provided to implement
+// dapper-like tracing. This function should be complemented with a WithSpan
+// method that could be used for tracing distributed RPC calls.
+//
+// The main benefit of this function is to post-process log messages or
+// intercept them in a hook to provide timing data. Trace ids and parent ids
+// can also be linked to provide call tracing, if so required.
+//
+// Here is an example of the usage:
+//
+// func timedOperation(ctx Context) {
+// ctx, done := WithTrace(ctx)
+// defer done("this will be the log message")
+// // ... function body ...
+// }
+//
+// If the function ran for roughly 1s, such a usage would emit a log message
+// as follows:
+//
+// INFO[0001] this will be the log message trace.duration=1.004575763s trace.func=github.com/docker/distribution/context.traceOperation trace.id=<id> ...
+//
+// Notice that the function name is automatically resolved, along with the
+// package and a trace id is emitted that can be linked with parent ids.
+func WithTrace(ctx Context) (Context, func(format string, a ...interface{})) {
+ if ctx == nil {
+ ctx = Background()
+ }
+
+ pc, file, line, _ := runtime.Caller(1)
+ f := runtime.FuncForPC(pc)
+ ctx = &traced{
+ Context: ctx,
+ id: uuid.Generate().String(),
+ start: time.Now(),
+ parent: GetStringValue(ctx, "trace.id"),
+ fnname: f.Name(),
+ file: file,
+ line: line,
+ }
+
+ return ctx, func(format string, a ...interface{}) {
+ GetLogger(ctx,
+ "trace.duration",
+ "trace.id",
+ "trace.parent.id",
+ "trace.func",
+ "trace.file",
+ "trace.line").
+ Debugf(format, a...)
+ }
+}
+
+// traced represents a context that is traced for function call timing. It
+// also provides fast lookup for the various attributes that are available on
+// the trace.
+type traced struct {
+ Context
+ id string
+ parent string
+ start time.Time
+ fnname string
+ file string
+ line int
+}
+
+func (ts *traced) Value(key interface{}) interface{} {
+ switch key {
+ case "trace.start":
+ return ts.start
+ case "trace.duration":
+ return time.Since(ts.start)
+ case "trace.id":
+ return ts.id
+ case "trace.parent.id":
+ if ts.parent == "" {
+ return nil // must return nil to signal no parent.
+ }
+
+ return ts.parent
+ case "trace.func":
+ return ts.fnname
+ case "trace.file":
+ return ts.file
+ case "trace.line":
+ return ts.line
+ }
+
+ return ts.Context.Value(key)
+}
diff --git a/vendor/github.com/docker/distribution/context/util.go b/vendor/github.com/docker/distribution/context/util.go
new file mode 100644
index 0000000..cb9ef52
--- /dev/null
+++ b/vendor/github.com/docker/distribution/context/util.go
@@ -0,0 +1,24 @@
+package context
+
+import (
+ "time"
+)
+
+// Since looks up key, which should be a time.Time, and returns the duration
+// since that time. If the key is not found, the value returned will be zero.
+// This is helpful when inferring metrics related to context execution times.
+func Since(ctx Context, key interface{}) time.Duration {
+ if startedAt, ok := ctx.Value(key).(time.Time); ok {
+ return time.Since(startedAt)
+ }
+ return 0
+}
+
+// GetStringValue returns a string value from the context. The empty string
+// will be returned if not found.
+func GetStringValue(ctx Context, key interface{}) (value string) {
+ if valuev, ok := ctx.Value(key).(string); ok {
+ value = valuev
+ }
+ return value
+}
diff --git a/vendor/github.com/docker/distribution/context/version.go b/vendor/github.com/docker/distribution/context/version.go
new file mode 100644
index 0000000..746cda0
--- /dev/null
+++ b/vendor/github.com/docker/distribution/context/version.go
@@ -0,0 +1,16 @@
+package context
+
+// WithVersion stores the application version in the context. The new context
+// gets a logger to ensure log messages are marked with the application
+// version.
+func WithVersion(ctx Context, version string) Context {
+ ctx = WithValue(ctx, "version", version)
+ // push a new logger onto the stack
+ return WithLogger(ctx, GetLogger(ctx, "version"))
+}
+
+// GetVersion returns the application version from the context. An empty
+// string may returned if the version was not set on the context.
+func GetVersion(ctx Context) string {
+ return GetStringValue(ctx, "version")
+}
diff --git a/vendor/github.com/docker/distribution/digestset/set.go b/vendor/github.com/docker/distribution/digestset/set.go
new file mode 100644
index 0000000..71327dc
--- /dev/null
+++ b/vendor/github.com/docker/distribution/digestset/set.go
@@ -0,0 +1,247 @@
+package digestset
+
+import (
+ "errors"
+ "sort"
+ "strings"
+ "sync"
+
+ digest "github.com/opencontainers/go-digest"
+)
+
+var (
+ // ErrDigestNotFound is used when a matching digest
+ // could not be found in a set.
+ ErrDigestNotFound = errors.New("digest not found")
+
+ // ErrDigestAmbiguous is used when multiple digests
+ // are found in a set. None of the matching digests
+ // should be considered valid matches.
+ ErrDigestAmbiguous = errors.New("ambiguous digest string")
+)
+
+// Set is used to hold a unique set of digests which
+// may be easily referenced by easily referenced by a string
+// representation of the digest as well as short representation.
+// The uniqueness of the short representation is based on other
+// digests in the set. If digests are omitted from this set,
+// collisions in a larger set may not be detected, therefore it
+// is important to always do short representation lookups on
+// the complete set of digests. To mitigate collisions, an
+// appropriately long short code should be used.
+type Set struct {
+ mutex sync.RWMutex
+ entries digestEntries
+}
+
+// NewSet creates an empty set of digests
+// which may have digests added.
+func NewSet() *Set {
+ return &Set{
+ entries: digestEntries{},
+ }
+}
+
+// checkShortMatch checks whether two digests match as either whole
+// values or short values. This function does not test equality,
+// rather whether the second value could match against the first
+// value.
+func checkShortMatch(alg digest.Algorithm, hex, shortAlg, shortHex string) bool {
+ if len(hex) == len(shortHex) {
+ if hex != shortHex {
+ return false
+ }
+ if len(shortAlg) > 0 && string(alg) != shortAlg {
+ return false
+ }
+ } else if !strings.HasPrefix(hex, shortHex) {
+ return false
+ } else if len(shortAlg) > 0 && string(alg) != shortAlg {
+ return false
+ }
+ return true
+}
+
+// Lookup looks for a digest matching the given string representation.
+// If no digests could be found ErrDigestNotFound will be returned
+// with an empty digest value. If multiple matches are found
+// ErrDigestAmbiguous will be returned with an empty digest value.
+func (dst *Set) Lookup(d string) (digest.Digest, error) {
+ dst.mutex.RLock()
+ defer dst.mutex.RUnlock()
+ if len(dst.entries) == 0 {
+ return "", ErrDigestNotFound
+ }
+ var (
+ searchFunc func(int) bool
+ alg digest.Algorithm
+ hex string
+ )
+ dgst, err := digest.Parse(d)
+ if err == digest.ErrDigestInvalidFormat {
+ hex = d
+ searchFunc = func(i int) bool {
+ return dst.entries[i].val >= d
+ }
+ } else {
+ hex = dgst.Hex()
+ alg = dgst.Algorithm()
+ searchFunc = func(i int) bool {
+ if dst.entries[i].val == hex {
+ return dst.entries[i].alg >= alg
+ }
+ return dst.entries[i].val >= hex
+ }
+ }
+ idx := sort.Search(len(dst.entries), searchFunc)
+ if idx == len(dst.entries) || !checkShortMatch(dst.entries[idx].alg, dst.entries[idx].val, string(alg), hex) {
+ return "", ErrDigestNotFound
+ }
+ if dst.entries[idx].alg == alg && dst.entries[idx].val == hex {
+ return dst.entries[idx].digest, nil
+ }
+ if idx+1 < len(dst.entries) && checkShortMatch(dst.entries[idx+1].alg, dst.entries[idx+1].val, string(alg), hex) {
+ return "", ErrDigestAmbiguous
+ }
+
+ return dst.entries[idx].digest, nil
+}
+
+// Add adds the given digest to the set. An error will be returned
+// if the given digest is invalid. If the digest already exists in the
+// set, this operation will be a no-op.
+func (dst *Set) Add(d digest.Digest) error {
+ if err := d.Validate(); err != nil {
+ return err
+ }
+ dst.mutex.Lock()
+ defer dst.mutex.Unlock()
+ entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d}
+ searchFunc := func(i int) bool {
+ if dst.entries[i].val == entry.val {
+ return dst.entries[i].alg >= entry.alg
+ }
+ return dst.entries[i].val >= entry.val
+ }
+ idx := sort.Search(len(dst.entries), searchFunc)
+ if idx == len(dst.entries) {
+ dst.entries = append(dst.entries, entry)
+ return nil
+ } else if dst.entries[idx].digest == d {
+ return nil
+ }
+
+ entries := append(dst.entries, nil)
+ copy(entries[idx+1:], entries[idx:len(entries)-1])
+ entries[idx] = entry
+ dst.entries = entries
+ return nil
+}
+
+// Remove removes the given digest from the set. An err will be
+// returned if the given digest is invalid. If the digest does
+// not exist in the set, this operation will be a no-op.
+func (dst *Set) Remove(d digest.Digest) error {
+ if err := d.Validate(); err != nil {
+ return err
+ }
+ dst.mutex.Lock()
+ defer dst.mutex.Unlock()
+ entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d}
+ searchFunc := func(i int) bool {
+ if dst.entries[i].val == entry.val {
+ return dst.entries[i].alg >= entry.alg
+ }
+ return dst.entries[i].val >= entry.val
+ }
+ idx := sort.Search(len(dst.entries), searchFunc)
+ // Not found if idx is after or value at idx is not digest
+ if idx == len(dst.entries) || dst.entries[idx].digest != d {
+ return nil
+ }
+
+ entries := dst.entries
+ copy(entries[idx:], entries[idx+1:])
+ entries = entries[:len(entries)-1]
+ dst.entries = entries
+
+ return nil
+}
+
+// All returns all the digests in the set
+func (dst *Set) All() []digest.Digest {
+ dst.mutex.RLock()
+ defer dst.mutex.RUnlock()
+ retValues := make([]digest.Digest, len(dst.entries))
+ for i := range dst.entries {
+ retValues[i] = dst.entries[i].digest
+ }
+
+ return retValues
+}
+
+// ShortCodeTable returns a map of Digest to unique short codes. The
+// length represents the minimum value, the maximum length may be the
+// entire value of digest if uniqueness cannot be achieved without the
+// full value. This function will attempt to make short codes as short
+// as possible to be unique.
+func ShortCodeTable(dst *Set, length int) map[digest.Digest]string {
+ dst.mutex.RLock()
+ defer dst.mutex.RUnlock()
+ m := make(map[digest.Digest]string, len(dst.entries))
+ l := length
+ resetIdx := 0
+ for i := 0; i < len(dst.entries); i++ {
+ var short string
+ extended := true
+ for extended {
+ extended = false
+ if len(dst.entries[i].val) <= l {
+ short = dst.entries[i].digest.String()
+ } else {
+ short = dst.entries[i].val[:l]
+ for j := i + 1; j < len(dst.entries); j++ {
+ if checkShortMatch(dst.entries[j].alg, dst.entries[j].val, "", short) {
+ if j > resetIdx {
+ resetIdx = j
+ }
+ extended = true
+ } else {
+ break
+ }
+ }
+ if extended {
+ l++
+ }
+ }
+ }
+ m[dst.entries[i].digest] = short
+ if i >= resetIdx {
+ l = length
+ }
+ }
+ return m
+}
+
+type digestEntry struct {
+ alg digest.Algorithm
+ val string
+ digest digest.Digest
+}
+
+type digestEntries []*digestEntry
+
+func (d digestEntries) Len() int {
+ return len(d)
+}
+
+func (d digestEntries) Less(i, j int) bool {
+ if d[i].val != d[j].val {
+ return d[i].val < d[j].val
+ }
+ return d[i].alg < d[j].alg
+}
+
+func (d digestEntries) Swap(i, j int) {
+ d[i], d[j] = d[j], d[i]
+}
diff --git a/vendor/github.com/docker/distribution/doc.go b/vendor/github.com/docker/distribution/doc.go
new file mode 100644
index 0000000..bdd8cb7
--- /dev/null
+++ b/vendor/github.com/docker/distribution/doc.go
@@ -0,0 +1,7 @@
+// Package distribution will define the interfaces for the components of
+// docker distribution. The goal is to allow users to reliably package, ship
+// and store content related to docker images.
+//
+// This is currently a work in progress. More details are available in the
+// README.md.
+package distribution
diff --git a/vendor/github.com/docker/distribution/errors.go b/vendor/github.com/docker/distribution/errors.go
new file mode 100644
index 0000000..2062a06
--- /dev/null
+++ b/vendor/github.com/docker/distribution/errors.go
@@ -0,0 +1,115 @@
+package distribution
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/opencontainers/go-digest"
+)
+
+// ErrAccessDenied is returned when an access to a requested resource is
+// denied.
+var ErrAccessDenied = errors.New("access denied")
+
+// ErrManifestNotModified is returned when a conditional manifest GetByTag
+// returns nil due to the client indicating it has the latest version
+var ErrManifestNotModified = errors.New("manifest not modified")
+
+// ErrUnsupported is returned when an unimplemented or unsupported action is
+// performed
+var ErrUnsupported = errors.New("operation unsupported")
+
+// ErrTagUnknown is returned if the given tag is not known by the tag service
+type ErrTagUnknown struct {
+ Tag string
+}
+
+func (err ErrTagUnknown) Error() string {
+ return fmt.Sprintf("unknown tag=%s", err.Tag)
+}
+
+// ErrRepositoryUnknown is returned if the named repository is not known by
+// the registry.
+type ErrRepositoryUnknown struct {
+ Name string
+}
+
+func (err ErrRepositoryUnknown) Error() string {
+ return fmt.Sprintf("unknown repository name=%s", err.Name)
+}
+
+// ErrRepositoryNameInvalid should be used to denote an invalid repository
+// name. Reason may set, indicating the cause of invalidity.
+type ErrRepositoryNameInvalid struct {
+ Name string
+ Reason error
+}
+
+func (err ErrRepositoryNameInvalid) Error() string {
+ return fmt.Sprintf("repository name %q invalid: %v", err.Name, err.Reason)
+}
+
+// ErrManifestUnknown is returned if the manifest is not known by the
+// registry.
+type ErrManifestUnknown struct {
+ Name string
+ Tag string
+}
+
+func (err ErrManifestUnknown) Error() string {
+ return fmt.Sprintf("unknown manifest name=%s tag=%s", err.Name, err.Tag)
+}
+
+// ErrManifestUnknownRevision is returned when a manifest cannot be found by
+// revision within a repository.
+type ErrManifestUnknownRevision struct {
+ Name string
+ Revision digest.Digest
+}
+
+func (err ErrManifestUnknownRevision) Error() string {
+ return fmt.Sprintf("unknown manifest name=%s revision=%s", err.Name, err.Revision)
+}
+
+// ErrManifestUnverified is returned when the registry is unable to verify
+// the manifest.
+type ErrManifestUnverified struct{}
+
+func (ErrManifestUnverified) Error() string {
+ return fmt.Sprintf("unverified manifest")
+}
+
+// ErrManifestVerification provides a type to collect errors encountered
+// during manifest verification. Currently, it accepts errors of all types,
+// but it may be narrowed to those involving manifest verification.
+type ErrManifestVerification []error
+
+func (errs ErrManifestVerification) Error() string {
+ var parts []string
+ for _, err := range errs {
+ parts = append(parts, err.Error())
+ }
+
+ return fmt.Sprintf("errors verifying manifest: %v", strings.Join(parts, ","))
+}
+
+// ErrManifestBlobUnknown returned when a referenced blob cannot be found.
+type ErrManifestBlobUnknown struct {
+ Digest digest.Digest
+}
+
+func (err ErrManifestBlobUnknown) Error() string {
+ return fmt.Sprintf("unknown blob %v on manifest", err.Digest)
+}
+
+// ErrManifestNameInvalid should be used to denote an invalid manifest
+// name. Reason may set, indicating the cause of invalidity.
+type ErrManifestNameInvalid struct {
+ Name string
+ Reason error
+}
+
+func (err ErrManifestNameInvalid) Error() string {
+ return fmt.Sprintf("manifest name %q invalid: %v", err.Name, err.Reason)
+}
diff --git a/vendor/github.com/docker/distribution/manifest/doc.go b/vendor/github.com/docker/distribution/manifest/doc.go
new file mode 100644
index 0000000..88367b0
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifest/doc.go
@@ -0,0 +1 @@
+package manifest
diff --git a/vendor/github.com/docker/distribution/manifest/manifestlist/manifestlist.go b/vendor/github.com/docker/distribution/manifest/manifestlist/manifestlist.go
new file mode 100644
index 0000000..7a8cabb
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifest/manifestlist/manifestlist.go
@@ -0,0 +1,155 @@
+package manifestlist
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "github.com/docker/distribution"
+ "github.com/docker/distribution/manifest"
+ "github.com/opencontainers/go-digest"
+)
+
+// MediaTypeManifestList specifies the mediaType for manifest lists.
+const MediaTypeManifestList = "application/vnd.docker.distribution.manifest.list.v2+json"
+
+// SchemaVersion provides a pre-initialized version structure for this
+// packages version of the manifest.
+var SchemaVersion = manifest.Versioned{
+ SchemaVersion: 2,
+ MediaType: MediaTypeManifestList,
+}
+
+func init() {
+ manifestListFunc := func(b []byte) (distribution.Manifest, distribution.Descriptor, error) {
+ m := new(DeserializedManifestList)
+ err := m.UnmarshalJSON(b)
+ if err != nil {
+ return nil, distribution.Descriptor{}, err
+ }
+
+ dgst := digest.FromBytes(b)
+ return m, distribution.Descriptor{Digest: dgst, Size: int64(len(b)), MediaType: MediaTypeManifestList}, err
+ }
+ err := distribution.RegisterManifestSchema(MediaTypeManifestList, manifestListFunc)
+ if err != nil {
+ panic(fmt.Sprintf("Unable to register manifest: %s", err))
+ }
+}
+
+// PlatformSpec specifies a platform where a particular image manifest is
+// applicable.
+type PlatformSpec struct {
+ // Architecture field specifies the CPU architecture, for example
+ // `amd64` or `ppc64`.
+ Architecture string `json:"architecture"`
+
+ // OS specifies the operating system, for example `linux` or `windows`.
+ OS string `json:"os"`
+
+ // OSVersion is an optional field specifying the operating system
+ // version, for example `10.0.10586`.
+ OSVersion string `json:"os.version,omitempty"`
+
+ // OSFeatures is an optional field specifying an array of strings,
+ // each listing a required OS feature (for example on Windows `win32k`).
+ OSFeatures []string `json:"os.features,omitempty"`
+
+ // Variant is an optional field specifying a variant of the CPU, for
+ // example `ppc64le` to specify a little-endian version of a PowerPC CPU.
+ Variant string `json:"variant,omitempty"`
+
+ // Features is an optional field specifying an array of strings, each
+ // listing a required CPU feature (for example `sse4` or `aes`).
+ Features []string `json:"features,omitempty"`
+}
+
+// A ManifestDescriptor references a platform-specific manifest.
+type ManifestDescriptor struct {
+ distribution.Descriptor
+
+ // Platform specifies which platform the manifest pointed to by the
+ // descriptor runs on.
+ Platform PlatformSpec `json:"platform"`
+}
+
+// ManifestList references manifests for various platforms.
+type ManifestList struct {
+ manifest.Versioned
+
+ // Config references the image configuration as a blob.
+ Manifests []ManifestDescriptor `json:"manifests"`
+}
+
+// References returnes the distribution descriptors for the referenced image
+// manifests.
+func (m ManifestList) References() []distribution.Descriptor {
+ dependencies := make([]distribution.Descriptor, len(m.Manifests))
+ for i := range m.Manifests {
+ dependencies[i] = m.Manifests[i].Descriptor
+ }
+
+ return dependencies
+}
+
+// DeserializedManifestList wraps ManifestList with a copy of the original
+// JSON.
+type DeserializedManifestList struct {
+ ManifestList
+
+ // canonical is the canonical byte representation of the Manifest.
+ canonical []byte
+}
+
+// FromDescriptors takes a slice of descriptors, and returns a
+// DeserializedManifestList which contains the resulting manifest list
+// and its JSON representation.
+func FromDescriptors(descriptors []ManifestDescriptor) (*DeserializedManifestList, error) {
+ m := ManifestList{
+ Versioned: SchemaVersion,
+ }
+
+ m.Manifests = make([]ManifestDescriptor, len(descriptors), len(descriptors))
+ copy(m.Manifests, descriptors)
+
+ deserialized := DeserializedManifestList{
+ ManifestList: m,
+ }
+
+ var err error
+ deserialized.canonical, err = json.MarshalIndent(&m, "", " ")
+ return &deserialized, err
+}
+
+// UnmarshalJSON populates a new ManifestList struct from JSON data.
+func (m *DeserializedManifestList) UnmarshalJSON(b []byte) error {
+ m.canonical = make([]byte, len(b), len(b))
+ // store manifest list in canonical
+ copy(m.canonical, b)
+
+ // Unmarshal canonical JSON into ManifestList object
+ var manifestList ManifestList
+ if err := json.Unmarshal(m.canonical, &manifestList); err != nil {
+ return err
+ }
+
+ m.ManifestList = manifestList
+
+ return nil
+}
+
+// MarshalJSON returns the contents of canonical. If canonical is empty,
+// marshals the inner contents.
+func (m *DeserializedManifestList) MarshalJSON() ([]byte, error) {
+ if len(m.canonical) > 0 {
+ return m.canonical, nil
+ }
+
+ return nil, errors.New("JSON representation not initialized in DeserializedManifestList")
+}
+
+// Payload returns the raw content of the manifest list. The contents can be
+// used to calculate the content identifier.
+func (m DeserializedManifestList) Payload() (string, []byte, error) {
+ return m.MediaType, m.canonical, nil
+}
diff --git a/vendor/github.com/docker/distribution/manifest/schema1/config_builder.go b/vendor/github.com/docker/distribution/manifest/schema1/config_builder.go
new file mode 100644
index 0000000..9d22256
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifest/schema1/config_builder.go
@@ -0,0 +1,287 @@
+package schema1
+
+import (
+ "crypto/sha512"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/docker/distribution"
+ "github.com/docker/distribution/context"
+ "github.com/docker/distribution/manifest"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/libtrust"
+ "github.com/opencontainers/go-digest"
+)
+
+type diffID digest.Digest
+
+// gzippedEmptyTar is a gzip-compressed version of an empty tar file
+// (1024 NULL bytes)
+var gzippedEmptyTar = []byte{
+ 31, 139, 8, 0, 0, 9, 110, 136, 0, 255, 98, 24, 5, 163, 96, 20, 140, 88,
+ 0, 8, 0, 0, 255, 255, 46, 175, 181, 239, 0, 4, 0, 0,
+}
+
+// digestSHA256GzippedEmptyTar is the canonical sha256 digest of
+// gzippedEmptyTar
+const digestSHA256GzippedEmptyTar = digest.Digest("sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4")
+
+// configManifestBuilder is a type for constructing manifests from an image
+// configuration and generic descriptors.
+type configManifestBuilder struct {
+ // bs is a BlobService used to create empty layer tars in the
+ // blob store if necessary.
+ bs distribution.BlobService
+ // pk is the libtrust private key used to sign the final manifest.
+ pk libtrust.PrivateKey
+ // configJSON is configuration supplied when the ManifestBuilder was
+ // created.
+ configJSON []byte
+ // ref contains the name and optional tag provided to NewConfigManifestBuilder.
+ ref reference.Named
+ // descriptors is the set of descriptors referencing the layers.
+ descriptors []distribution.Descriptor
+ // emptyTarDigest is set to a valid digest if an empty tar has been
+ // put in the blob store; otherwise it is empty.
+ emptyTarDigest digest.Digest
+}
+
+// NewConfigManifestBuilder is used to build new manifests for the current
+// schema version from an image configuration and a set of descriptors.
+// It takes a BlobService so that it can add an empty tar to the blob store
+// if the resulting manifest needs empty layers.
+func NewConfigManifestBuilder(bs distribution.BlobService, pk libtrust.PrivateKey, ref reference.Named, configJSON []byte) distribution.ManifestBuilder {
+ return &configManifestBuilder{
+ bs: bs,
+ pk: pk,
+ configJSON: configJSON,
+ ref: ref,
+ }
+}
+
+// Build produces a final manifest from the given references
+func (mb *configManifestBuilder) Build(ctx context.Context) (m distribution.Manifest, err error) {
+ type imageRootFS struct {
+ Type string `json:"type"`
+ DiffIDs []diffID `json:"diff_ids,omitempty"`
+ BaseLayer string `json:"base_layer,omitempty"`
+ }
+
+ type imageHistory struct {
+ Created time.Time `json:"created"`
+ Author string `json:"author,omitempty"`
+ CreatedBy string `json:"created_by,omitempty"`
+ Comment string `json:"comment,omitempty"`
+ EmptyLayer bool `json:"empty_layer,omitempty"`
+ }
+
+ type imageConfig struct {
+ RootFS *imageRootFS `json:"rootfs,omitempty"`
+ History []imageHistory `json:"history,omitempty"`
+ Architecture string `json:"architecture,omitempty"`
+ }
+
+ var img imageConfig
+
+ if err := json.Unmarshal(mb.configJSON, &img); err != nil {
+ return nil, err
+ }
+
+ if len(img.History) == 0 {
+ return nil, errors.New("empty history when trying to create schema1 manifest")
+ }
+
+ if len(img.RootFS.DiffIDs) != len(mb.descriptors) {
+ return nil, fmt.Errorf("number of descriptors and number of layers in rootfs must match: len(%v) != len(%v)", img.RootFS.DiffIDs, mb.descriptors)
+ }
+
+ // Generate IDs for each layer
+ // For non-top-level layers, create fake V1Compatibility strings that
+ // fit the format and don't collide with anything else, but don't
+ // result in runnable images on their own.
+ type v1Compatibility struct {
+ ID string `json:"id"`
+ Parent string `json:"parent,omitempty"`
+ Comment string `json:"comment,omitempty"`
+ Created time.Time `json:"created"`
+ ContainerConfig struct {
+ Cmd []string
+ } `json:"container_config,omitempty"`
+ Author string `json:"author,omitempty"`
+ ThrowAway bool `json:"throwaway,omitempty"`
+ }
+
+ fsLayerList := make([]FSLayer, len(img.History))
+ history := make([]History, len(img.History))
+
+ parent := ""
+ layerCounter := 0
+ for i, h := range img.History[:len(img.History)-1] {
+ var blobsum digest.Digest
+ if h.EmptyLayer {
+ if blobsum, err = mb.emptyTar(ctx); err != nil {
+ return nil, err
+ }
+ } else {
+ if len(img.RootFS.DiffIDs) <= layerCounter {
+ return nil, errors.New("too many non-empty layers in History section")
+ }
+ blobsum = mb.descriptors[layerCounter].Digest
+ layerCounter++
+ }
+
+ v1ID := digest.FromBytes([]byte(blobsum.Hex() + " " + parent)).Hex()
+
+ if i == 0 && img.RootFS.BaseLayer != "" {
+ // windows-only baselayer setup
+ baseID := sha512.Sum384([]byte(img.RootFS.BaseLayer))
+ parent = fmt.Sprintf("%x", baseID[:32])
+ }
+
+ v1Compatibility := v1Compatibility{
+ ID: v1ID,
+ Parent: parent,
+ Comment: h.Comment,
+ Created: h.Created,
+ Author: h.Author,
+ }
+ v1Compatibility.ContainerConfig.Cmd = []string{img.History[i].CreatedBy}
+ if h.EmptyLayer {
+ v1Compatibility.ThrowAway = true
+ }
+ jsonBytes, err := json.Marshal(&v1Compatibility)
+ if err != nil {
+ return nil, err
+ }
+
+ reversedIndex := len(img.History) - i - 1
+ history[reversedIndex].V1Compatibility = string(jsonBytes)
+ fsLayerList[reversedIndex] = FSLayer{BlobSum: blobsum}
+
+ parent = v1ID
+ }
+
+ latestHistory := img.History[len(img.History)-1]
+
+ var blobsum digest.Digest
+ if latestHistory.EmptyLayer {
+ if blobsum, err = mb.emptyTar(ctx); err != nil {
+ return nil, err
+ }
+ } else {
+ if len(img.RootFS.DiffIDs) <= layerCounter {
+ return nil, errors.New("too many non-empty layers in History section")
+ }
+ blobsum = mb.descriptors[layerCounter].Digest
+ }
+
+ fsLayerList[0] = FSLayer{BlobSum: blobsum}
+ dgst := digest.FromBytes([]byte(blobsum.Hex() + " " + parent + " " + string(mb.configJSON)))
+
+ // Top-level v1compatibility string should be a modified version of the
+ // image config.
+ transformedConfig, err := MakeV1ConfigFromConfig(mb.configJSON, dgst.Hex(), parent, latestHistory.EmptyLayer)
+ if err != nil {
+ return nil, err
+ }
+
+ history[0].V1Compatibility = string(transformedConfig)
+
+ tag := ""
+ if tagged, isTagged := mb.ref.(reference.Tagged); isTagged {
+ tag = tagged.Tag()
+ }
+
+ mfst := Manifest{
+ Versioned: manifest.Versioned{
+ SchemaVersion: 1,
+ },
+ Name: mb.ref.Name(),
+ Tag: tag,
+ Architecture: img.Architecture,
+ FSLayers: fsLayerList,
+ History: history,
+ }
+
+ return Sign(&mfst, mb.pk)
+}
+
+// emptyTar pushes a compressed empty tar to the blob store if one doesn't
+// already exist, and returns its blobsum.
+func (mb *configManifestBuilder) emptyTar(ctx context.Context) (digest.Digest, error) {
+ if mb.emptyTarDigest != "" {
+ // Already put an empty tar
+ return mb.emptyTarDigest, nil
+ }
+
+ descriptor, err := mb.bs.Stat(ctx, digestSHA256GzippedEmptyTar)
+ switch err {
+ case nil:
+ mb.emptyTarDigest = descriptor.Digest
+ return descriptor.Digest, nil
+ case distribution.ErrBlobUnknown:
+ // nop
+ default:
+ return "", err
+ }
+
+ // Add gzipped empty tar to the blob store
+ descriptor, err = mb.bs.Put(ctx, "", gzippedEmptyTar)
+ if err != nil {
+ return "", err
+ }
+
+ mb.emptyTarDigest = descriptor.Digest
+
+ return descriptor.Digest, nil
+}
+
+// AppendReference adds a reference to the current ManifestBuilder
+func (mb *configManifestBuilder) AppendReference(d distribution.Describable) error {
+ descriptor := d.Descriptor()
+
+ if err := descriptor.Digest.Validate(); err != nil {
+ return err
+ }
+
+ mb.descriptors = append(mb.descriptors, descriptor)
+ return nil
+}
+
+// References returns the current references added to this builder
+func (mb *configManifestBuilder) References() []distribution.Descriptor {
+ return mb.descriptors
+}
+
+// MakeV1ConfigFromConfig creates an legacy V1 image config from image config JSON
+func MakeV1ConfigFromConfig(configJSON []byte, v1ID, parentV1ID string, throwaway bool) ([]byte, error) {
+ // Top-level v1compatibility string should be a modified version of the
+ // image config.
+ var configAsMap map[string]*json.RawMessage
+ if err := json.Unmarshal(configJSON, &configAsMap); err != nil {
+ return nil, err
+ }
+
+ // Delete fields that didn't exist in old manifest
+ delete(configAsMap, "rootfs")
+ delete(configAsMap, "history")
+ configAsMap["id"] = rawJSON(v1ID)
+ if parentV1ID != "" {
+ configAsMap["parent"] = rawJSON(parentV1ID)
+ }
+ if throwaway {
+ configAsMap["throwaway"] = rawJSON(true)
+ }
+
+ return json.Marshal(configAsMap)
+}
+
+func rawJSON(value interface{}) *json.RawMessage {
+ jsonval, err := json.Marshal(value)
+ if err != nil {
+ return nil
+ }
+ return (*json.RawMessage)(&jsonval)
+}
diff --git a/vendor/github.com/docker/distribution/manifest/schema1/manifest.go b/vendor/github.com/docker/distribution/manifest/schema1/manifest.go
new file mode 100644
index 0000000..65042a7
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifest/schema1/manifest.go
@@ -0,0 +1,184 @@
+package schema1
+
+import (
+ "encoding/json"
+ "fmt"
+
+ "github.com/docker/distribution"
+ "github.com/docker/distribution/manifest"
+ "github.com/docker/libtrust"
+ "github.com/opencontainers/go-digest"
+)
+
+const (
+ // MediaTypeManifest specifies the mediaType for the current version. Note
+ // that for schema version 1, the the media is optionally "application/json".
+ MediaTypeManifest = "application/vnd.docker.distribution.manifest.v1+json"
+ // MediaTypeSignedManifest specifies the mediatype for current SignedManifest version
+ MediaTypeSignedManifest = "application/vnd.docker.distribution.manifest.v1+prettyjws"
+ // MediaTypeManifestLayer specifies the media type for manifest layers
+ MediaTypeManifestLayer = "application/vnd.docker.container.image.rootfs.diff+x-gtar"
+)
+
+var (
+ // SchemaVersion provides a pre-initialized version structure for this
+ // packages version of the manifest.
+ SchemaVersion = manifest.Versioned{
+ SchemaVersion: 1,
+ }
+)
+
+func init() {
+ schema1Func := func(b []byte) (distribution.Manifest, distribution.Descriptor, error) {
+ sm := new(SignedManifest)
+ err := sm.UnmarshalJSON(b)
+ if err != nil {
+ return nil, distribution.Descriptor{}, err
+ }
+
+ desc := distribution.Descriptor{
+ Digest: digest.FromBytes(sm.Canonical),
+ Size: int64(len(sm.Canonical)),
+ MediaType: MediaTypeSignedManifest,
+ }
+ return sm, desc, err
+ }
+ err := distribution.RegisterManifestSchema(MediaTypeSignedManifest, schema1Func)
+ if err != nil {
+ panic(fmt.Sprintf("Unable to register manifest: %s", err))
+ }
+ err = distribution.RegisterManifestSchema("", schema1Func)
+ if err != nil {
+ panic(fmt.Sprintf("Unable to register manifest: %s", err))
+ }
+ err = distribution.RegisterManifestSchema("application/json", schema1Func)
+ if err != nil {
+ panic(fmt.Sprintf("Unable to register manifest: %s", err))
+ }
+}
+
+// FSLayer is a container struct for BlobSums defined in an image manifest
+type FSLayer struct {
+ // BlobSum is the tarsum of the referenced filesystem image layer
+ BlobSum digest.Digest `json:"blobSum"`
+}
+
+// History stores unstructured v1 compatibility information
+type History struct {
+ // V1Compatibility is the raw v1 compatibility information
+ V1Compatibility string `json:"v1Compatibility"`
+}
+
+// Manifest provides the base accessible fields for working with V2 image
+// format in the registry.
+type Manifest struct {
+ manifest.Versioned
+
+ // Name is the name of the image's repository
+ Name string `json:"name"`
+
+ // Tag is the tag of the image specified by this manifest
+ Tag string `json:"tag"`
+
+ // Architecture is the host architecture on which this image is intended to
+ // run
+ Architecture string `json:"architecture"`
+
+ // FSLayers is a list of filesystem layer blobSums contained in this image
+ FSLayers []FSLayer `json:"fsLayers"`
+
+ // History is a list of unstructured historical data for v1 compatibility
+ History []History `json:"history"`
+}
+
+// SignedManifest provides an envelope for a signed image manifest, including
+// the format sensitive raw bytes.
+type SignedManifest struct {
+ Manifest
+
+ // Canonical is the canonical byte representation of the ImageManifest,
+ // without any attached signatures. The manifest byte
+ // representation cannot change or it will have to be re-signed.
+ Canonical []byte `json:"-"`
+
+ // all contains the byte representation of the Manifest including signatures
+ // and is returned by Payload()
+ all []byte
+}
+
+// UnmarshalJSON populates a new SignedManifest struct from JSON data.
+func (sm *SignedManifest) UnmarshalJSON(b []byte) error {
+ sm.all = make([]byte, len(b), len(b))
+ // store manifest and signatures in all
+ copy(sm.all, b)
+
+ jsig, err := libtrust.ParsePrettySignature(b, "signatures")
+ if err != nil {
+ return err
+ }
+
+ // Resolve the payload in the manifest.
+ bytes, err := jsig.Payload()
+ if err != nil {
+ return err
+ }
+
+ // sm.Canonical stores the canonical manifest JSON
+ sm.Canonical = make([]byte, len(bytes), len(bytes))
+ copy(sm.Canonical, bytes)
+
+ // Unmarshal canonical JSON into Manifest object
+ var manifest Manifest
+ if err := json.Unmarshal(sm.Canonical, &manifest); err != nil {
+ return err
+ }
+
+ sm.Manifest = manifest
+
+ return nil
+}
+
+// References returnes the descriptors of this manifests references
+func (sm SignedManifest) References() []distribution.Descriptor {
+ dependencies := make([]distribution.Descriptor, len(sm.FSLayers))
+ for i, fsLayer := range sm.FSLayers {
+ dependencies[i] = distribution.Descriptor{
+ MediaType: "application/vnd.docker.container.image.rootfs.diff+x-gtar",
+ Digest: fsLayer.BlobSum,
+ }
+ }
+
+ return dependencies
+
+}
+
+// MarshalJSON returns the contents of raw. If Raw is nil, marshals the inner
+// contents. Applications requiring a marshaled signed manifest should simply
+// use Raw directly, since the the content produced by json.Marshal will be
+// compacted and will fail signature checks.
+func (sm *SignedManifest) MarshalJSON() ([]byte, error) {
+ if len(sm.all) > 0 {
+ return sm.all, nil
+ }
+
+ // If the raw data is not available, just dump the inner content.
+ return json.Marshal(&sm.Manifest)
+}
+
+// Payload returns the signed content of the signed manifest.
+func (sm SignedManifest) Payload() (string, []byte, error) {
+ return MediaTypeSignedManifest, sm.all, nil
+}
+
+// Signatures returns the signatures as provided by
+// (*libtrust.JSONSignature).Signatures. The byte slices are opaque jws
+// signatures.
+func (sm *SignedManifest) Signatures() ([][]byte, error) {
+ jsig, err := libtrust.ParsePrettySignature(sm.all, "signatures")
+ if err != nil {
+ return nil, err
+ }
+
+ // Resolve the payload in the manifest.
+ return jsig.Signatures()
+}
diff --git a/vendor/github.com/docker/distribution/manifest/schema1/reference_builder.go b/vendor/github.com/docker/distribution/manifest/schema1/reference_builder.go
new file mode 100644
index 0000000..ae40147
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifest/schema1/reference_builder.go
@@ -0,0 +1,98 @@
+package schema1
+
+import (
+ "fmt"
+
+ "errors"
+ "github.com/docker/distribution"
+ "github.com/docker/distribution/context"
+ "github.com/docker/distribution/manifest"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/libtrust"
+ "github.com/opencontainers/go-digest"
+)
+
+// referenceManifestBuilder is a type for constructing manifests from schema1
+// dependencies.
+type referenceManifestBuilder struct {
+ Manifest
+ pk libtrust.PrivateKey
+}
+
+// NewReferenceManifestBuilder is used to build new manifests for the current
+// schema version using schema1 dependencies.
+func NewReferenceManifestBuilder(pk libtrust.PrivateKey, ref reference.Named, architecture string) distribution.ManifestBuilder {
+ tag := ""
+ if tagged, isTagged := ref.(reference.Tagged); isTagged {
+ tag = tagged.Tag()
+ }
+
+ return &referenceManifestBuilder{
+ Manifest: Manifest{
+ Versioned: manifest.Versioned{
+ SchemaVersion: 1,
+ },
+ Name: ref.Name(),
+ Tag: tag,
+ Architecture: architecture,
+ },
+ pk: pk,
+ }
+}
+
+func (mb *referenceManifestBuilder) Build(ctx context.Context) (distribution.Manifest, error) {
+ m := mb.Manifest
+ if len(m.FSLayers) == 0 {
+ return nil, errors.New("cannot build manifest with zero layers or history")
+ }
+
+ m.FSLayers = make([]FSLayer, len(mb.Manifest.FSLayers))
+ m.History = make([]History, len(mb.Manifest.History))
+ copy(m.FSLayers, mb.Manifest.FSLayers)
+ copy(m.History, mb.Manifest.History)
+
+ return Sign(&m, mb.pk)
+}
+
+// AppendReference adds a reference to the current ManifestBuilder
+func (mb *referenceManifestBuilder) AppendReference(d distribution.Describable) error {
+ r, ok := d.(Reference)
+ if !ok {
+ return fmt.Errorf("Unable to add non-reference type to v1 builder")
+ }
+
+ // Entries need to be prepended
+ mb.Manifest.FSLayers = append([]FSLayer{{BlobSum: r.Digest}}, mb.Manifest.FSLayers...)
+ mb.Manifest.History = append([]History{r.History}, mb.Manifest.History...)
+ return nil
+
+}
+
+// References returns the current references added to this builder
+func (mb *referenceManifestBuilder) References() []distribution.Descriptor {
+ refs := make([]distribution.Descriptor, len(mb.Manifest.FSLayers))
+ for i := range mb.Manifest.FSLayers {
+ layerDigest := mb.Manifest.FSLayers[i].BlobSum
+ history := mb.Manifest.History[i]
+ ref := Reference{layerDigest, 0, history}
+ refs[i] = ref.Descriptor()
+ }
+ return refs
+}
+
+// Reference describes a manifest v2, schema version 1 dependency.
+// An FSLayer associated with a history entry.
+type Reference struct {
+ Digest digest.Digest
+ Size int64 // if we know it, set it for the descriptor.
+ History History
+}
+
+// Descriptor describes a reference
+func (r Reference) Descriptor() distribution.Descriptor {
+ return distribution.Descriptor{
+ MediaType: MediaTypeManifestLayer,
+ Digest: r.Digest,
+ Size: r.Size,
+ }
+}
diff --git a/vendor/github.com/docker/distribution/manifest/schema1/sign.go b/vendor/github.com/docker/distribution/manifest/schema1/sign.go
new file mode 100644
index 0000000..c862dd8
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifest/schema1/sign.go
@@ -0,0 +1,68 @@
+package schema1
+
+import (
+ "crypto/x509"
+ "encoding/json"
+
+ "github.com/docker/libtrust"
+)
+
+// Sign signs the manifest with the provided private key, returning a
+// SignedManifest. This typically won't be used within the registry, except
+// for testing.
+func Sign(m *Manifest, pk libtrust.PrivateKey) (*SignedManifest, error) {
+ p, err := json.MarshalIndent(m, "", " ")
+ if err != nil {
+ return nil, err
+ }
+
+ js, err := libtrust.NewJSONSignature(p)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := js.Sign(pk); err != nil {
+ return nil, err
+ }
+
+ pretty, err := js.PrettySignature("signatures")
+ if err != nil {
+ return nil, err
+ }
+
+ return &SignedManifest{
+ Manifest: *m,
+ all: pretty,
+ Canonical: p,
+ }, nil
+}
+
+// SignWithChain signs the manifest with the given private key and x509 chain.
+// The public key of the first element in the chain must be the public key
+// corresponding with the sign key.
+func SignWithChain(m *Manifest, key libtrust.PrivateKey, chain []*x509.Certificate) (*SignedManifest, error) {
+ p, err := json.MarshalIndent(m, "", " ")
+ if err != nil {
+ return nil, err
+ }
+
+ js, err := libtrust.NewJSONSignature(p)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := js.SignWithChain(key, chain); err != nil {
+ return nil, err
+ }
+
+ pretty, err := js.PrettySignature("signatures")
+ if err != nil {
+ return nil, err
+ }
+
+ return &SignedManifest{
+ Manifest: *m,
+ all: pretty,
+ Canonical: p,
+ }, nil
+}
diff --git a/vendor/github.com/docker/distribution/manifest/schema1/verify.go b/vendor/github.com/docker/distribution/manifest/schema1/verify.go
new file mode 100644
index 0000000..fa8daa5
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifest/schema1/verify.go
@@ -0,0 +1,32 @@
+package schema1
+
+import (
+ "crypto/x509"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libtrust"
+)
+
+// Verify verifies the signature of the signed manifest returning the public
+// keys used during signing.
+func Verify(sm *SignedManifest) ([]libtrust.PublicKey, error) {
+ js, err := libtrust.ParsePrettySignature(sm.all, "signatures")
+ if err != nil {
+ logrus.WithField("err", err).Debugf("(*SignedManifest).Verify")
+ return nil, err
+ }
+
+ return js.Verify()
+}
+
+// VerifyChains verifies the signature of the signed manifest against the
+// certificate pool returning the list of verified chains. Signatures without
+// an x509 chain are not checked.
+func VerifyChains(sm *SignedManifest, ca *x509.CertPool) ([][]*x509.Certificate, error) {
+ js, err := libtrust.ParsePrettySignature(sm.all, "signatures")
+ if err != nil {
+ return nil, err
+ }
+
+ return js.VerifyChains(ca)
+}
diff --git a/vendor/github.com/docker/distribution/manifest/schema2/builder.go b/vendor/github.com/docker/distribution/manifest/schema2/builder.go
new file mode 100644
index 0000000..4b6ba56
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifest/schema2/builder.go
@@ -0,0 +1,84 @@
+package schema2
+
+import (
+ "github.com/docker/distribution"
+ "github.com/docker/distribution/context"
+ "github.com/opencontainers/go-digest"
+)
+
+// builder is a type for constructing manifests.
+type builder struct {
+ // bs is a BlobService used to publish the configuration blob.
+ bs distribution.BlobService
+
+ // configMediaType is media type used to describe configuration
+ configMediaType string
+
+ // configJSON references
+ configJSON []byte
+
+ // dependencies is a list of descriptors that gets built by successive
+ // calls to AppendReference. In case of image configuration these are layers.
+ dependencies []distribution.Descriptor
+}
+
+// NewManifestBuilder is used to build new manifests for the current schema
+// version. It takes a BlobService so it can publish the configuration blob
+// as part of the Build process.
+func NewManifestBuilder(bs distribution.BlobService, configMediaType string, configJSON []byte) distribution.ManifestBuilder {
+ mb := &builder{
+ bs: bs,
+ configMediaType: configMediaType,
+ configJSON: make([]byte, len(configJSON)),
+ }
+ copy(mb.configJSON, configJSON)
+
+ return mb
+}
+
+// Build produces a final manifest from the given references.
+func (mb *builder) Build(ctx context.Context) (distribution.Manifest, error) {
+ m := Manifest{
+ Versioned: SchemaVersion,
+ Layers: make([]distribution.Descriptor, len(mb.dependencies)),
+ }
+ copy(m.Layers, mb.dependencies)
+
+ configDigest := digest.FromBytes(mb.configJSON)
+
+ var err error
+ m.Config, err = mb.bs.Stat(ctx, configDigest)
+ switch err {
+ case nil:
+ // Override MediaType, since Put always replaces the specified media
+ // type with application/octet-stream in the descriptor it returns.
+ m.Config.MediaType = mb.configMediaType
+ return FromStruct(m)
+ case distribution.ErrBlobUnknown:
+ // nop
+ default:
+ return nil, err
+ }
+
+ // Add config to the blob store
+ m.Config, err = mb.bs.Put(ctx, mb.configMediaType, mb.configJSON)
+ // Override MediaType, since Put always replaces the specified media
+ // type with application/octet-stream in the descriptor it returns.
+ m.Config.MediaType = mb.configMediaType
+ if err != nil {
+ return nil, err
+ }
+
+ return FromStruct(m)
+}
+
+// AppendReference adds a reference to the current ManifestBuilder.
+func (mb *builder) AppendReference(d distribution.Describable) error {
+ mb.dependencies = append(mb.dependencies, d.Descriptor())
+ return nil
+}
+
+// References returns the current references added to this builder.
+func (mb *builder) References() []distribution.Descriptor {
+ return mb.dependencies
+}
diff --git a/vendor/github.com/docker/distribution/manifest/schema2/manifest.go b/vendor/github.com/docker/distribution/manifest/schema2/manifest.go
new file mode 100644
index 0000000..a2708c7
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifest/schema2/manifest.go
@@ -0,0 +1,138 @@
+package schema2
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "github.com/docker/distribution"
+ "github.com/docker/distribution/manifest"
+ "github.com/opencontainers/go-digest"
+)
+
+const (
+ // MediaTypeManifest specifies the mediaType for the current version.
+ MediaTypeManifest = "application/vnd.docker.distribution.manifest.v2+json"
+
+ // MediaTypeImageConfig specifies the mediaType for the image configuration.
+ MediaTypeImageConfig = "application/vnd.docker.container.image.v1+json"
+
+ // MediaTypePluginConfig specifies the mediaType for plugin configuration.
+ MediaTypePluginConfig = "application/vnd.docker.plugin.v1+json"
+
+ // MediaTypeLayer is the mediaType used for layers referenced by the
+ // manifest.
+ MediaTypeLayer = "application/vnd.docker.image.rootfs.diff.tar.gzip"
+
+ // MediaTypeForeignLayer is the mediaType used for layers that must be
+ // downloaded from foreign URLs.
+ MediaTypeForeignLayer = "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip"
+
+ // MediaTypeUncompressedLayer is the mediaType used for layers which
+ // are not compressed.
+ MediaTypeUncompressedLayer = "application/vnd.docker.image.rootfs.diff.tar"
+)
+
+var (
+ // SchemaVersion provides a pre-initialized version structure for this
+ // packages version of the manifest.
+ SchemaVersion = manifest.Versioned{
+ SchemaVersion: 2,
+ MediaType: MediaTypeManifest,
+ }
+)
+
+func init() {
+ schema2Func := func(b []byte) (distribution.Manifest, distribution.Descriptor, error) {
+ m := new(DeserializedManifest)
+ err := m.UnmarshalJSON(b)
+ if err != nil {
+ return nil, distribution.Descriptor{}, err
+ }
+
+ dgst := digest.FromBytes(b)
+ return m, distribution.Descriptor{Digest: dgst, Size: int64(len(b)), MediaType: MediaTypeManifest}, err
+ }
+ err := distribution.RegisterManifestSchema(MediaTypeManifest, schema2Func)
+ if err != nil {
+ panic(fmt.Sprintf("Unable to register manifest: %s", err))
+ }
+}
+
+// Manifest defines a schema2 manifest.
+type Manifest struct {
+ manifest.Versioned
+
+ // Config references the image configuration as a blob.
+ Config distribution.Descriptor `json:"config"`
+
+ // Layers lists descriptors for the layers referenced by the
+ // configuration.
+ Layers []distribution.Descriptor `json:"layers"`
+}
+
+// References returnes the descriptors of this manifests references.
+func (m Manifest) References() []distribution.Descriptor {
+ references := make([]distribution.Descriptor, 0, 1+len(m.Layers))
+ references = append(references, m.Config)
+ references = append(references, m.Layers...)
+ return references
+}
+
+// Target returns the target of this signed manifest.
+func (m Manifest) Target() distribution.Descriptor {
+ return m.Config
+}
+
+// DeserializedManifest wraps Manifest with a copy of the original JSON.
+// It satisfies the distribution.Manifest interface.
+type DeserializedManifest struct {
+ Manifest
+
+ // canonical is the canonical byte representation of the Manifest.
+ canonical []byte
+}
+
+// FromStruct takes a Manifest structure, marshals it to JSON, and returns a
+// DeserializedManifest which contains the manifest and its JSON representation.
+func FromStruct(m Manifest) (*DeserializedManifest, error) {
+ var deserialized DeserializedManifest
+ deserialized.Manifest = m
+
+ var err error
+ deserialized.canonical, err = json.MarshalIndent(&m, "", " ")
+ return &deserialized, err
+}
+
+// UnmarshalJSON populates a new Manifest struct from JSON data.
+func (m *DeserializedManifest) UnmarshalJSON(b []byte) error {
+ m.canonical = make([]byte, len(b), len(b))
+ // store manifest in canonical
+ copy(m.canonical, b)
+
+ // Unmarshal canonical JSON into Manifest object
+ var manifest Manifest
+ if err := json.Unmarshal(m.canonical, &manifest); err != nil {
+ return err
+ }
+
+ m.Manifest = manifest
+
+ return nil
+}
+
+// MarshalJSON returns the contents of canonical. If canonical is empty,
+// marshals the inner contents.
+func (m *DeserializedManifest) MarshalJSON() ([]byte, error) {
+ if len(m.canonical) > 0 {
+ return m.canonical, nil
+ }
+
+ return nil, errors.New("JSON representation not initialized in DeserializedManifest")
+}
+
+// Payload returns the raw content of the manifest. The contents can be used to
+// calculate the content identifier.
+func (m DeserializedManifest) Payload() (string, []byte, error) {
+ return m.MediaType, m.canonical, nil
+}
diff --git a/vendor/github.com/docker/distribution/manifest/versioned.go b/vendor/github.com/docker/distribution/manifest/versioned.go
new file mode 100644
index 0000000..caa6b14
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifest/versioned.go
@@ -0,0 +1,12 @@
+package manifest
+
+// Versioned provides a struct with the manifest schemaVersion and mediaType.
+// Incoming content with unknown schema version can be decoded against this
+// struct to check the version.
+type Versioned struct {
+ // SchemaVersion is the image manifest schema that this image follows
+ SchemaVersion int `json:"schemaVersion"`
+
+ // MediaType is the media type of this schema.
+ MediaType string `json:"mediaType,omitempty"`
+}
diff --git a/vendor/github.com/docker/distribution/manifests.go b/vendor/github.com/docker/distribution/manifests.go
new file mode 100644
index 0000000..2c99f25
--- /dev/null
+++ b/vendor/github.com/docker/distribution/manifests.go
@@ -0,0 +1,125 @@
+package distribution
+
+import (
+ "fmt"
+ "mime"
+
+ "github.com/docker/distribution/context"
+ "github.com/opencontainers/go-digest"
+)
+
+// Manifest represents a registry object specifying a set of
+// references and an optional target
+type Manifest interface {
+ // References returns a list of objects which make up this manifest.
+ // A reference is anything which can be represented by a
+ // distribution.Descriptor. These can consist of layers, resources or other
+ // manifests.
+ //
+ // While no particular order is required, implementations should return
+ // them from highest to lowest priority. For example, one might want to
+ // return the base layer before the top layer.
+ References() []Descriptor
+
+ // Payload provides the serialized format of the manifest, in addition to
+ // the media type.
+ Payload() (mediaType string, payload []byte, err error)
+}
+
+// ManifestBuilder creates a manifest allowing one to include dependencies.
+// Instances can be obtained from a version-specific manifest package. Manifest
+// specific data is passed into the function which creates the builder.
+type ManifestBuilder interface {
+ // Build creates the manifest from his builder.
+ Build(ctx context.Context) (Manifest, error)
+
+ // References returns a list of objects which have been added to this
+ // builder. The dependencies are returned in the order they were added,
+ // which should be from base to head.
+ References() []Descriptor
+
+ // AppendReference includes the given object in the manifest after any
+ // existing dependencies. If the add fails, such as when adding an
+ // unsupported dependency, an error may be returned.
+ //
+ // The destination of the reference is dependent on the manifest type and
+ // the dependency type.
+ AppendReference(dependency Describable) error
+}
+
+// ManifestService describes operations on image manifests.
+type ManifestService interface {
+ // Exists returns true if the manifest exists.
+ Exists(ctx context.Context, dgst digest.Digest) (bool, error)
+
+ // Get retrieves the manifest specified by the given digest
+ Get(ctx context.Context, dgst digest.Digest, options ...ManifestServiceOption) (Manifest, error)
+
+ // Put creates or updates the given manifest returning the manifest digest
+ Put(ctx context.Context, manifest Manifest, options ...ManifestServiceOption) (digest.Digest, error)
+
+ // Delete removes the manifest specified by the given digest. Deleting
+ // a manifest that doesn't exist will return ErrManifestNotFound
+ Delete(ctx context.Context, dgst digest.Digest) error
+}
+
+// ManifestEnumerator enables iterating over manifests
+type ManifestEnumerator interface {
+ // Enumerate calls ingester for each manifest.
+ Enumerate(ctx context.Context, ingester func(digest.Digest) error) error
+}
+
+// Describable is an interface for descriptors
+type Describable interface {
+ Descriptor() Descriptor
+}
+
+// ManifestMediaTypes returns the supported media types for manifests.
+func ManifestMediaTypes() (mediaTypes []string) {
+ for t := range mappings {
+ if t != "" {
+ mediaTypes = append(mediaTypes, t)
+ }
+ }
+ return
+}
+
+// UnmarshalFunc implements manifest unmarshalling a given MediaType
+type UnmarshalFunc func([]byte) (Manifest, Descriptor, error)
+
+var mappings = make(map[string]UnmarshalFunc, 0)
+
+// UnmarshalManifest looks up manifest unmarshal functions based on
+// MediaType
+func UnmarshalManifest(ctHeader string, p []byte) (Manifest, Descriptor, error) {
+ // Need to look up by the actual media type, not the raw contents of
+ // the header. Strip semicolons and anything following them.
+ var mediaType string
+ if ctHeader != "" {
+ var err error
+ mediaType, _, err = mime.ParseMediaType(ctHeader)
+ if err != nil {
+ return nil, Descriptor{}, err
+ }
+ }
+
+ unmarshalFunc, ok := mappings[mediaType]
+ if !ok {
+ unmarshalFunc, ok = mappings[""]
+ if !ok {
+ return nil, Descriptor{}, fmt.Errorf("unsupported manifest media type and no default available: %s", mediaType)
+ }
+ }
+
+ return unmarshalFunc(p)
+}
+
+// RegisterManifestSchema registers an UnmarshalFunc for a given schema type. This
+// should be called from specific
+func RegisterManifestSchema(mediaType string, u UnmarshalFunc) error {
+ if _, ok := mappings[mediaType]; ok {
+ return fmt.Errorf("manifest media type registration would overwrite existing: %s", mediaType)
+ }
+ mappings[mediaType] = u
+ return nil
+}
diff --git a/vendor/github.com/docker/distribution/reference/helpers.go b/vendor/github.com/docker/distribution/reference/helpers.go
new file mode 100644
index 0000000..978df7e
--- /dev/null
+++ b/vendor/github.com/docker/distribution/reference/helpers.go
@@ -0,0 +1,42 @@
+package reference
+
+import "path"
+
+// IsNameOnly returns true if reference only contains a repo name.
+func IsNameOnly(ref Named) bool {
+ if _, ok := ref.(NamedTagged); ok {
+ return false
+ }
+ if _, ok := ref.(Canonical); ok {
+ return false
+ }
+ return true
+}
+
+// FamiliarName returns the familiar name string
+// for the given named, familiarizing if needed.
+func FamiliarName(ref Named) string {
+ if nn, ok := ref.(normalizedNamed); ok {
+ return nn.Familiar().Name()
+ }
+ return ref.Name()
+}
+
+// FamiliarString returns the familiar string representation
+// for the given reference, familiarizing if needed.
+func FamiliarString(ref Reference) string {
+ if nn, ok := ref.(normalizedNamed); ok {
+ return nn.Familiar().String()
+ }
+ return ref.String()
+}
+
+// FamiliarMatch reports whether ref matches the specified pattern.
+// See https://godoc.org/path#Match for supported patterns.
+func FamiliarMatch(pattern string, ref Reference) (bool, error) {
+ matched, err := path.Match(pattern, FamiliarString(ref))
+ if namedRef, isNamed := ref.(Named); isNamed && !matched {
+ matched, _ = path.Match(pattern, FamiliarName(namedRef))
+ }
+ return matched, err
+}
diff --git a/vendor/github.com/docker/distribution/reference/normalize.go b/vendor/github.com/docker/distribution/reference/normalize.go
new file mode 100644
index 0000000..2d71fc5
--- /dev/null
+++ b/vendor/github.com/docker/distribution/reference/normalize.go
@@ -0,0 +1,170 @@
+package reference
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/docker/distribution/digestset"
+ "github.com/opencontainers/go-digest"
+)
+
+var (
+ legacyDefaultDomain = "index.docker.io"
+ defaultDomain = "docker.io"
+ officialRepoName = "library"
+ defaultTag = "latest"
+)
+
+// normalizedNamed represents a name which has been
+// normalized and has a familiar form. A familiar name
+// is what is used in Docker UI. An example normalized
+// name is "docker.io/library/ubuntu" and corresponding
+// familiar name of "ubuntu".
+type normalizedNamed interface {
+ Named
+ Familiar() Named
+}
+
+// ParseNormalizedNamed parses a string into a named reference
+// transforming a familiar name from Docker UI to a fully
+// qualified reference. If the value may be an identifier
+// use ParseAnyReference.
+func ParseNormalizedNamed(s string) (Named, error) {
+ if ok := anchoredIdentifierRegexp.MatchString(s); ok {
+ return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s)
+ }
+ domain, remainder := splitDockerDomain(s)
+ var remoteName string
+ if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 {
+ remoteName = remainder[:tagSep]
+ } else {
+ remoteName = remainder
+ }
+ if strings.ToLower(remoteName) != remoteName {
+ return nil, errors.New("invalid reference format: repository name must be lowercase")
+ }
+
+ ref, err := Parse(domain + "/" + remainder)
+ if err != nil {
+ return nil, err
+ }
+ named, isNamed := ref.(Named)
+ if !isNamed {
+ return nil, fmt.Errorf("reference %s has no name", ref.String())
+ }
+ return named, nil
+}
+
+// splitDockerDomain splits a repository name to domain and remotename string.
+// If no valid domain is found, the default domain is used. Repository name
+// needs to be already validated before.
+func splitDockerDomain(name string) (domain, remainder string) {
+ i := strings.IndexRune(name, '/')
+ if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost") {
+ domain, remainder = defaultDomain, name
+ } else {
+ domain, remainder = name[:i], name[i+1:]
+ }
+ if domain == legacyDefaultDomain {
+ domain = defaultDomain
+ }
+ if domain == defaultDomain && !strings.ContainsRune(remainder, '/') {
+ remainder = officialRepoName + "/" + remainder
+ }
+ return
+}
+
+// familiarizeName returns a shortened version of the name familiar
+// to to the Docker UI. Familiar names have the default domain
+// "docker.io" and "library/" repository prefix removed.
+// For example, "docker.io/library/redis" will have the familiar
+// name "redis" and "docker.io/dmcgowan/myapp" will be "dmcgowan/myapp".
+// Returns a familiarized named only reference.
+func familiarizeName(named namedRepository) repository {
+ repo := repository{
+ domain: named.Domain(),
+ path: named.Path(),
+ }
+
+ if repo.domain == defaultDomain {
+ repo.domain = ""
+ // Handle official repositories which have the pattern "library/<official repo name>"
+ if split := strings.Split(repo.path, "/"); len(split) == 2 && split[0] == officialRepoName {
+ repo.path = split[1]
+ }
+ }
+ return repo
+}
+
+func (r reference) Familiar() Named {
+ return reference{
+ namedRepository: familiarizeName(r.namedRepository),
+ tag: r.tag,
+ digest: r.digest,
+ }
+}
+
+func (r repository) Familiar() Named {
+ return familiarizeName(r)
+}
+
+func (t taggedReference) Familiar() Named {
+ return taggedReference{
+ namedRepository: familiarizeName(t.namedRepository),
+ tag: t.tag,
+ }
+}
+
+func (c canonicalReference) Familiar() Named {
+ return canonicalReference{
+ namedRepository: familiarizeName(c.namedRepository),
+ digest: c.digest,
+ }
+}
+
+// TagNameOnly adds the default tag "latest" to a reference if it only has
+// a repo name.
+func TagNameOnly(ref Named) Named {
+ if IsNameOnly(ref) {
+ namedTagged, err := WithTag(ref, defaultTag)
+ if err != nil {
+ // Default tag must be valid, to create a NamedTagged
+ // type with non-validated input the WithTag function
+ // should be used instead
+ panic(err)
+ }
+ return namedTagged
+ }
+ return ref
+}
+
+// ParseAnyReference parses a reference string as a possible identifier,
+// full digest, or familiar name.
+func ParseAnyReference(ref string) (Reference, error) {
+ if ok := anchoredIdentifierRegexp.MatchString(ref); ok {
+ return digestReference("sha256:" + ref), nil
+ }
+ if dgst, err := digest.Parse(ref); err == nil {
+ return digestReference(dgst), nil
+ }
+
+ return ParseNormalizedNamed(ref)
+}
+
+// ParseAnyReferenceWithSet parses a reference string as a possible short
+// identifier to be matched in a digest set, a full digest, or familiar name.
+func ParseAnyReferenceWithSet(ref string, ds *digestset.Set) (Reference, error) {
+ if ok := anchoredShortIdentifierRegexp.MatchString(ref); ok {
+ dgst, err := ds.Lookup(ref)
+ if err == nil {
+ return digestReference(dgst), nil
+ }
+ } else {
+ if dgst, err := digest.Parse(ref); err == nil {
+ return digestReference(dgst), nil
+ }
+ }
+
+ return ParseNormalizedNamed(ref)
+}
diff --git a/vendor/github.com/docker/distribution/reference/reference.go b/vendor/github.com/docker/distribution/reference/reference.go
new file mode 100644
index 0000000..fd3510e
--- /dev/null
+++ b/vendor/github.com/docker/distribution/reference/reference.go
@@ -0,0 +1,433 @@
+// Package reference provides a general type to represent any way of referencing images within the registry.
+// Its main purpose is to abstract tags and digests (content-addressable hash).
+//
+// Grammar
+//
+// reference := name [ ":" tag ] [ "@" digest ]
+// name := [domain '/'] path-component ['/' path-component]*
+// domain := domain-component ['.' domain-component]* [':' port-number]
+// domain-component := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/
+// port-number := /[0-9]+/
+// path-component := alpha-numeric [separator alpha-numeric]*
+// alpha-numeric := /[a-z0-9]+/
+// separator := /[_.]|__|[-]*/
+//
+// tag := /[\w][\w.-]{0,127}/
+//
+// digest := digest-algorithm ":" digest-hex
+// digest-algorithm := digest-algorithm-component [ digest-algorithm-separator digest-algorithm-component ]
+// digest-algorithm-separator := /[+.-_]/
+// digest-algorithm-component := /[A-Za-z][A-Za-z0-9]*/
+// digest-hex := /[0-9a-fA-F]{32,}/ ; At least 128 bit digest value
+//
+// identifier := /[a-f0-9]{64}/
+// short-identifier := /[a-f0-9]{6,64}/
+package reference
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/opencontainers/go-digest"
+)
+
+const (
+ // NameTotalLengthMax is the maximum total number of characters in a repository name.
+ NameTotalLengthMax = 255
+)
+
+var (
+ // ErrReferenceInvalidFormat represents an error while trying to parse a string as a reference.
+ ErrReferenceInvalidFormat = errors.New("invalid reference format")
+
+ // ErrTagInvalidFormat represents an error while trying to parse a string as a tag.
+ ErrTagInvalidFormat = errors.New("invalid tag format")
+
+ // ErrDigestInvalidFormat represents an error while trying to parse a string as a tag.
+ ErrDigestInvalidFormat = errors.New("invalid digest format")
+
+ // ErrNameContainsUppercase is returned for invalid repository names that contain uppercase characters.
+ ErrNameContainsUppercase = errors.New("repository name must be lowercase")
+
+ // ErrNameEmpty is returned for empty, invalid repository names.
+ ErrNameEmpty = errors.New("repository name must have at least one component")
+
+ // ErrNameTooLong is returned when a repository name is longer than NameTotalLengthMax.
+ ErrNameTooLong = fmt.Errorf("repository name must not be more than %v characters", NameTotalLengthMax)
+
+ // ErrNameNotCanonical is returned when a name is not canonical.
+ ErrNameNotCanonical = errors.New("repository name must be canonical")
+)
+
+// Reference is an opaque object reference identifier that may include
+// modifiers such as a hostname, name, tag, and digest.
+type Reference interface {
+ // String returns the full reference
+ String() string
+}
+
+// Field provides a wrapper type for resolving correct reference types when
+// working with encoding.
+type Field struct {
+ reference Reference
+}
+
+// AsField wraps a reference in a Field for encoding.
+func AsField(reference Reference) Field {
+ return Field{reference}
+}
+
+// Reference unwraps the reference type from the field to
+// return the Reference object. This object should be
+// of the appropriate type to further check for different
+// reference types.
+func (f Field) Reference() Reference {
+ return f.reference
+}
+
+// MarshalText serializes the field to byte text which
+// is the string of the reference.
+func (f Field) MarshalText() (p []byte, err error) {
+ return []byte(f.reference.String()), nil
+}
+
+// UnmarshalText parses text bytes by invoking the
+// reference parser to ensure the appropriately
+// typed reference object is wrapped by field.
+func (f *Field) UnmarshalText(p []byte) error {
+ r, err := Parse(string(p))
+ if err != nil {
+ return err
+ }
+
+ f.reference = r
+ return nil
+}
+
+// Named is an object with a full name
+type Named interface {
+ Reference
+ Name() string
+}
+
+// Tagged is an object which has a tag
+type Tagged interface {
+ Reference
+ Tag() string
+}
+
+// NamedTagged is an object including a name and tag.
+type NamedTagged interface {
+ Named
+ Tag() string
+}
+
+// Digested is an object which has a digest
+// in which it can be referenced by
+type Digested interface {
+ Reference
+ Digest() digest.Digest
+}
+
+// Canonical reference is an object with a fully unique
+// name including a name with domain and digest
+type Canonical interface {
+ Named
+ Digest() digest.Digest
+}
+
+// namedRepository is a reference to a repository with a name.
+// A namedRepository has both domain and path components.
+type namedRepository interface {
+ Named
+ Domain() string
+ Path() string
+}
+
+// Domain returns the domain part of the Named reference
+func Domain(named Named) string {
+ if r, ok := named.(namedRepository); ok {
+ return r.Domain()
+ }
+ domain, _ := splitDomain(named.Name())
+ return domain
+}
+
+// Path returns the name without the domain part of the Named reference
+func Path(named Named) (name string) {
+ if r, ok := named.(namedRepository); ok {
+ return r.Path()
+ }
+ _, path := splitDomain(named.Name())
+ return path
+}
+
+func splitDomain(name string) (string, string) {
+ match := anchoredNameRegexp.FindStringSubmatch(name)
+ if len(match) != 3 {
+ return "", name
+ }
+ return match[1], match[2]
+}
+
+// SplitHostname splits a named reference into a
+// hostname and name string. If no valid hostname is
+// found, the hostname is empty and the full value
+// is returned as name
+// DEPRECATED: Use Domain or Path
+func SplitHostname(named Named) (string, string) {
+ if r, ok := named.(namedRepository); ok {
+ return r.Domain(), r.Path()
+ }
+ return splitDomain(named.Name())
+}
+
+// Parse parses s and returns a syntactically valid Reference.
+// If an error was encountered it is returned, along with a nil Reference.
+// NOTE: Parse will not handle short digests.
+func Parse(s string) (Reference, error) {
+ matches := ReferenceRegexp.FindStringSubmatch(s)
+ if matches == nil {
+ if s == "" {
+ return nil, ErrNameEmpty
+ }
+ if ReferenceRegexp.FindStringSubmatch(strings.ToLower(s)) != nil {
+ return nil, ErrNameContainsUppercase
+ }
+ return nil, ErrReferenceInvalidFormat
+ }
+
+ if len(matches[1]) > NameTotalLengthMax {
+ return nil, ErrNameTooLong
+ }
+
+ var repo repository
+
+ nameMatch := anchoredNameRegexp.FindStringSubmatch(matches[1])
+ if nameMatch != nil && len(nameMatch) == 3 {
+ repo.domain = nameMatch[1]
+ repo.path = nameMatch[2]
+ } else {
+ repo.domain = ""
+ repo.path = matches[1]
+ }
+
+ ref := reference{
+ namedRepository: repo,
+ tag: matches[2],
+ }
+ if matches[3] != "" {
+ var err error
+ ref.digest, err = digest.Parse(matches[3])
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ r := getBestReferenceType(ref)
+ if r == nil {
+ return nil, ErrNameEmpty
+ }
+
+ return r, nil
+}
+
+// ParseNamed parses s and returns a syntactically valid reference implementing
+// the Named interface. The reference must have a name and be in the canonical
+// form, otherwise an error is returned.
+// If an error was encountered it is returned, along with a nil Reference.
+// NOTE: ParseNamed will not handle short digests.
+func ParseNamed(s string) (Named, error) {
+ named, err := ParseNormalizedNamed(s)
+ if err != nil {
+ return nil, err
+ }
+ if named.String() != s {
+ return nil, ErrNameNotCanonical
+ }
+ return named, nil
+}
+
+// WithName returns a named object representing the given string. If the input
+// is invalid ErrReferenceInvalidFormat will be returned.
+func WithName(name string) (Named, error) {
+ if len(name) > NameTotalLengthMax {
+ return nil, ErrNameTooLong
+ }
+
+ match := anchoredNameRegexp.FindStringSubmatch(name)
+ if match == nil || len(match) != 3 {
+ return nil, ErrReferenceInvalidFormat
+ }
+ return repository{
+ domain: match[1],
+ path: match[2],
+ }, nil
+}
+
+// WithTag combines the name from "name" and the tag from "tag" to form a
+// reference incorporating both the name and the tag.
+func WithTag(name Named, tag string) (NamedTagged, error) {
+ if !anchoredTagRegexp.MatchString(tag) {
+ return nil, ErrTagInvalidFormat
+ }
+ var repo repository
+ if r, ok := name.(namedRepository); ok {
+ repo.domain = r.Domain()
+ repo.path = r.Path()
+ } else {
+ repo.path = name.Name()
+ }
+ if canonical, ok := name.(Canonical); ok {
+ return reference{
+ namedRepository: repo,
+ tag: tag,
+ digest: canonical.Digest(),
+ }, nil
+ }
+ return taggedReference{
+ namedRepository: repo,
+ tag: tag,
+ }, nil
+}
+
+// WithDigest combines the name from "name" and the digest from "digest" to form
+// a reference incorporating both the name and the digest.
+func WithDigest(name Named, digest digest.Digest) (Canonical, error) {
+ if !anchoredDigestRegexp.MatchString(digest.String()) {
+ return nil, ErrDigestInvalidFormat
+ }
+ var repo repository
+ if r, ok := name.(namedRepository); ok {
+ repo.domain = r.Domain()
+ repo.path = r.Path()
+ } else {
+ repo.path = name.Name()
+ }
+ if tagged, ok := name.(Tagged); ok {
+ return reference{
+ namedRepository: repo,
+ tag: tagged.Tag(),
+ digest: digest,
+ }, nil
+ }
+ return canonicalReference{
+ namedRepository: repo,
+ digest: digest,
+ }, nil
+}
+
+// TrimNamed removes any tag or digest from the named reference.
+func TrimNamed(ref Named) Named {
+ domain, path := SplitHostname(ref)
+ return repository{
+ domain: domain,
+ path: path,
+ }
+}
+
+func getBestReferenceType(ref reference) Reference {
+ if ref.Name() == "" {
+ // Allow digest only references
+ if ref.digest != "" {
+ return digestReference(ref.digest)
+ }
+ return nil
+ }
+ if ref.tag == "" {
+ if ref.digest != "" {
+ return canonicalReference{
+ namedRepository: ref.namedRepository,
+ digest: ref.digest,
+ }
+ }
+ return ref.namedRepository
+ }
+ if ref.digest == "" {
+ return taggedReference{
+ namedRepository: ref.namedRepository,
+ tag: ref.tag,
+ }
+ }
+
+ return ref
+}
+
+type reference struct {
+ namedRepository
+ tag string
+ digest digest.Digest
+}
+
+func (r reference) String() string {
+ return r.Name() + ":" + r.tag + "@" + r.digest.String()
+}
+
+func (r reference) Tag() string {
+ return r.tag
+}
+
+func (r reference) Digest() digest.Digest {
+ return r.digest
+}
+
+type repository struct {
+ domain string
+ path string
+}
+
+func (r repository) String() string {
+ return r.Name()
+}
+
+func (r repository) Name() string {
+ if r.domain == "" {
+ return r.path
+ }
+ return r.domain + "/" + r.path
+}
+
+func (r repository) Domain() string {
+ return r.domain
+}
+
+func (r repository) Path() string {
+ return r.path
+}
+
+type digestReference digest.Digest
+
+func (d digestReference) String() string {
+ return digest.Digest(d).String()
+}
+
+func (d digestReference) Digest() digest.Digest {
+ return digest.Digest(d)
+}
+
+type taggedReference struct {
+ namedRepository
+ tag string
+}
+
+func (t taggedReference) String() string {
+ return t.Name() + ":" + t.tag
+}
+
+func (t taggedReference) Tag() string {
+ return t.tag
+}
+
+type canonicalReference struct {
+ namedRepository
+ digest digest.Digest
+}
+
+func (c canonicalReference) String() string {
+ return c.Name() + "@" + c.digest.String()
+}
+
+func (c canonicalReference) Digest() digest.Digest {
+ return c.digest
+}
diff --git a/vendor/github.com/docker/distribution/reference/regexp.go b/vendor/github.com/docker/distribution/reference/regexp.go
new file mode 100644
index 0000000..7860349
--- /dev/null
+++ b/vendor/github.com/docker/distribution/reference/regexp.go
@@ -0,0 +1,143 @@
+package reference
+
+import "regexp"
+
+var (
+ // alphaNumericRegexp defines the alpha numeric atom, typically a
+ // component of names. This only allows lower case characters and digits.
+ alphaNumericRegexp = match(`[a-z0-9]+`)
+
+ // separatorRegexp defines the separators allowed to be embedded in name
+ // components. This allow one period, one or two underscore and multiple
+ // dashes.
+ separatorRegexp = match(`(?:[._]|__|[-]*)`)
+
+ // nameComponentRegexp restricts registry path component names to start
+ // with at least one letter or number, with following parts able to be
+ // separated by one period, one or two underscore and multiple dashes.
+ nameComponentRegexp = expression(
+ alphaNumericRegexp,
+ optional(repeated(separatorRegexp, alphaNumericRegexp)))
+
+ // domainComponentRegexp restricts the registry domain component of a
+ // repository name to start with a component as defined by DomainRegexp
+ // and followed by an optional port.
+ domainComponentRegexp = match(`(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])`)
+
+ // DomainRegexp defines the structure of potential domain components
+ // that may be part of image names. This is purposely a subset of what is
+ // allowed by DNS to ensure backwards compatibility with Docker image
+ // names.
+ DomainRegexp = expression(
+ domainComponentRegexp,
+ optional(repeated(literal(`.`), domainComponentRegexp)),
+ optional(literal(`:`), match(`[0-9]+`)))
+
+ // TagRegexp matches valid tag names. From docker/docker:graph/tags.go.
+ TagRegexp = match(`[\w][\w.-]{0,127}`)
+
+ // anchoredTagRegexp matches valid tag names, anchored at the start and
+ // end of the matched string.
+ anchoredTagRegexp = anchored(TagRegexp)
+
+ // DigestRegexp matches valid digests.
+ DigestRegexp = match(`[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}`)
+
+ // anchoredDigestRegexp matches valid digests, anchored at the start and
+ // end of the matched string.
+ anchoredDigestRegexp = anchored(DigestRegexp)
+
+ // NameRegexp is the format for the name component of references. The
+ // regexp has capturing groups for the domain and name part omitting
+ // the separating forward slash from either.
+ NameRegexp = expression(
+ optional(DomainRegexp, literal(`/`)),
+ nameComponentRegexp,
+ optional(repeated(literal(`/`), nameComponentRegexp)))
+
+ // anchoredNameRegexp is used to parse a name value, capturing the
+ // domain and trailing components.
+ anchoredNameRegexp = anchored(
+ optional(capture(DomainRegexp), literal(`/`)),
+ capture(nameComponentRegexp,
+ optional(repeated(literal(`/`), nameComponentRegexp))))
+
+ // ReferenceRegexp is the full supported format of a reference. The regexp
+ // is anchored and has capturing groups for name, tag, and digest
+ // components.
+ ReferenceRegexp = anchored(capture(NameRegexp),
+ optional(literal(":"), capture(TagRegexp)),
+ optional(literal("@"), capture(DigestRegexp)))
+
+ // IdentifierRegexp is the format for string identifier used as a
+ // content addressable identifier using sha256. These identifiers
+ // are like digests without the algorithm, since sha256 is used.
+ IdentifierRegexp = match(`([a-f0-9]{64})`)
+
+ // ShortIdentifierRegexp is the format used to represent a prefix
+ // of an identifier. A prefix may be used to match a sha256 identifier
+ // within a list of trusted identifiers.
+ ShortIdentifierRegexp = match(`([a-f0-9]{6,64})`)
+
+ // anchoredIdentifierRegexp is used to check or match an
+ // identifier value, anchored at start and end of string.
+ anchoredIdentifierRegexp = anchored(IdentifierRegexp)
+
+ // anchoredShortIdentifierRegexp is used to check if a value
+ // is a possible identifier prefix, anchored at start and end
+ // of string.
+ anchoredShortIdentifierRegexp = anchored(ShortIdentifierRegexp)
+)
+
+// match compiles the string to a regular expression.
+var match = regexp.MustCompile
+
+// literal compiles s into a literal regular expression, escaping any regexp
+// reserved characters.
+func literal(s string) *regexp.Regexp {
+ re := match(regexp.QuoteMeta(s))
+
+ if _, complete := re.LiteralPrefix(); !complete {
+ panic("must be a literal")
+ }
+
+ return re
+}
+
+// expression defines a full expression, where each regular expression must
+// follow the previous.
+func expression(res ...*regexp.Regexp) *regexp.Regexp {
+ var s string
+ for _, re := range res {
+ s += re.String()
+ }
+
+ return match(s)
+}
+
+// optional wraps the expression in a non-capturing group and makes the
+// production optional.
+func optional(res ...*regexp.Regexp) *regexp.Regexp {
+ return match(group(expression(res...)).String() + `?`)
+}
+
+// repeated wraps the regexp in a non-capturing group to get one or more
+// matches.
+func repeated(res ...*regexp.Regexp) *regexp.Regexp {
+ return match(group(expression(res...)).String() + `+`)
+}
+
+// group wraps the regexp in a non-capturing group.
+func group(res ...*regexp.Regexp) *regexp.Regexp {
+ return match(`(?:` + expression(res...).String() + `)`)
+}
+
+// capture wraps the expression in a capturing group.
+func capture(res ...*regexp.Regexp) *regexp.Regexp {
+ return match(`(` + expression(res...).String() + `)`)
+}
+
+// anchored anchors the regular expression by adding start and end delimiters.
+func anchored(res ...*regexp.Regexp) *regexp.Regexp {
+ return match(`^` + expression(res...).String() + `$`)
+}
diff --git a/vendor/github.com/docker/distribution/registry.go b/vendor/github.com/docker/distribution/registry.go
new file mode 100644
index 0000000..1da1d53
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry.go
@@ -0,0 +1,97 @@
+package distribution
+
+import (
+ "github.com/docker/distribution/context"
+ "github.com/docker/distribution/reference"
+)
+
+// Scope defines the set of items that match a namespace.
+type Scope interface {
+ // Contains returns true if the name belongs to the namespace.
+ Contains(name string) bool
+}
+
+type fullScope struct{}
+
+func (f fullScope) Contains(string) bool {
+ return true
+}
+
+// GlobalScope represents the full namespace scope which contains
+// all other scopes.
+var GlobalScope = Scope(fullScope{})
+
+// Namespace represents a collection of repositories, addressable by name.
+// Generally, a namespace is backed by a set of one or more services,
+// providing facilities such as registry access, trust, and indexing.
+type Namespace interface {
+ // Scope describes the names that can be used with this Namespace. The
+ // global namespace will have a scope that matches all names. The scope
+ // effectively provides an identity for the namespace.
+ Scope() Scope
+
+ // Repository should return a reference to the named repository. The
+ // registry may or may not have the repository but should always return a
+ // reference.
+ Repository(ctx context.Context, name reference.Named) (Repository, error)
+
+ // Repositories fills 'repos' with a lexicographically sorted catalog of repositories
+ // up to the size of 'repos' and returns the value 'n' for the number of entries
+ // which were filled. 'last' contains an offset in the catalog, and 'err' will be
+ // set to io.EOF if there are no more entries to obtain.
+ Repositories(ctx context.Context, repos []string, last string) (n int, err error)
+
+ // Blobs returns a blob enumerator to access all blobs
+ Blobs() BlobEnumerator
+
+ // BlobStatter returns a BlobStatter to control
+ BlobStatter() BlobStatter
+}
+
+// RepositoryEnumerator describes an operation to enumerate repositories
+type RepositoryEnumerator interface {
+ Enumerate(ctx context.Context, ingester func(string) error) error
+}
+
+// ManifestServiceOption is a function argument for Manifest Service methods
+type ManifestServiceOption interface {
+ Apply(ManifestService) error
+}
+
+// WithTag allows a tag to be passed into Put
+func WithTag(tag string) ManifestServiceOption {
+ return WithTagOption{tag}
+}
+
+// WithTagOption holds a tag
+type WithTagOption struct{ Tag string }
+
+// Apply conforms to the ManifestServiceOption interface
+func (o WithTagOption) Apply(m ManifestService) error {
+ // no implementation
+ return nil
+}
+
+// Repository is a named collection of manifests and layers.
+type Repository interface {
+ // Named returns the name of the repository.
+ Named() reference.Named
+
+ // Manifests returns a reference to this repository's manifest service.
+ // with the supplied options applied.
+ Manifests(ctx context.Context, options ...ManifestServiceOption) (ManifestService, error)
+
+ // Blobs returns a reference to this repository's blob service.
+ Blobs(ctx context.Context) BlobStore
+
+ // TODO(stevvooe): The above BlobStore return can probably be relaxed to
+ // be a BlobService for use with clients. This will allow such
+ // implementations to avoid implementing ServeBlob.
+
+ // Tags returns a reference to this repositories tag service
+ Tags(ctx context.Context) TagService
+}
+
+// TODO(stevvooe): Must add close methods to all these. May want to change the
+// way instances are created to better reflect internal dependency
+// relationships.
diff --git a/vendor/github.com/docker/distribution/registry/api/errcode/errors.go b/vendor/github.com/docker/distribution/registry/api/errcode/errors.go
new file mode 100644
index 0000000..6d9bb4b
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/api/errcode/errors.go
@@ -0,0 +1,267 @@
+package errcode
+
+import (
+ "encoding/json"
+ "fmt"
+ "strings"
+)
+
+// ErrorCoder is the base interface for ErrorCode and Error allowing
+// users of each to just call ErrorCode to get the real ID of each
+type ErrorCoder interface {
+ ErrorCode() ErrorCode
+}
+
+// ErrorCode represents the error type. The errors are serialized via strings
+// and the integer format may change and should *never* be exported.
+type ErrorCode int
+
+var _ error = ErrorCode(0)
+
+// ErrorCode just returns itself
+func (ec ErrorCode) ErrorCode() ErrorCode {
+ return ec
+}
+
+// Error returns the ID/Value
+func (ec ErrorCode) Error() string {
+ // NOTE(stevvooe): Cannot use message here since it may have unpopulated args.
+ return strings.ToLower(strings.Replace(ec.String(), "_", " ", -1))
+}
+
+// Descriptor returns the descriptor for the error code.
+func (ec ErrorCode) Descriptor() ErrorDescriptor {
+ d, ok := errorCodeToDescriptors[ec]
+
+ if !ok {
+ return ErrorCodeUnknown.Descriptor()
+ }
+
+ return d
+}
+
+// String returns the canonical identifier for this error code.
+func (ec ErrorCode) String() string {
+ return ec.Descriptor().Value
+}
+
+// Message returned the human-readable error message for this error code.
+func (ec ErrorCode) Message() string {
+ return ec.Descriptor().Message
+}
+
+// MarshalText encodes the receiver into UTF-8-encoded text and returns the
+// result.
+func (ec ErrorCode) MarshalText() (text []byte, err error) {
+ return []byte(ec.String()), nil
+}
+
+// UnmarshalText decodes the form generated by MarshalText.
+func (ec *ErrorCode) UnmarshalText(text []byte) error {
+ desc, ok := idToDescriptors[string(text)]
+
+ if !ok {
+ desc = ErrorCodeUnknown.Descriptor()
+ }
+
+ *ec = desc.Code
+
+ return nil
+}
+
+// WithMessage creates a new Error struct based on the passed-in info and
+// overrides the Message property.
+func (ec ErrorCode) WithMessage(message string) Error {
+ return Error{
+ Code: ec,
+ Message: message,
+ }
+}
+
+// WithDetail creates a new Error struct based on the passed-in info and
+// set the Detail property appropriately
+func (ec ErrorCode) WithDetail(detail interface{}) Error {
+ return Error{
+ Code: ec,
+ Message: ec.Message(),
+ }.WithDetail(detail)
+}
+
+// WithArgs creates a new Error struct and sets the Args slice
+func (ec ErrorCode) WithArgs(args ...interface{}) Error {
+ return Error{
+ Code: ec,
+ Message: ec.Message(),
+ }.WithArgs(args...)
+}
+
+// Error provides a wrapper around ErrorCode with extra Details provided.
+type Error struct {
+ Code ErrorCode `json:"code"`
+ Message string `json:"message"`
+ Detail interface{} `json:"detail,omitempty"`
+
+ // TODO(duglin): See if we need an "args" property so we can do the
+ // variable substitution right before showing the message to the user
+}
+
+var _ error = Error{}
+
+// ErrorCode returns the ID/Value of this Error
+func (e Error) ErrorCode() ErrorCode {
+ return e.Code
+}
+
+// Error returns a human readable representation of the error.
+func (e Error) Error() string {
+ return fmt.Sprintf("%s: %s", e.Code.Error(), e.Message)
+}
+
+// WithDetail will return a new Error, based on the current one, but with
+// some Detail info added
+func (e Error) WithDetail(detail interface{}) Error {
+ return Error{
+ Code: e.Code,
+ Message: e.Message,
+ Detail: detail,
+ }
+}
+
+// WithArgs uses the passed-in list of interface{} as the substitution
+// variables in the Error's Message string, but returns a new Error
+func (e Error) WithArgs(args ...interface{}) Error {
+ return Error{
+ Code: e.Code,
+ Message: fmt.Sprintf(e.Code.Message(), args...),
+ Detail: e.Detail,
+ }
+}
+
+// ErrorDescriptor provides relevant information about a given error code.
+type ErrorDescriptor struct {
+ // Code is the error code that this descriptor describes.
+ Code ErrorCode
+
+ // Value provides a unique, string key, often captilized with
+ // underscores, to identify the error code. This value is used as the
+ // keyed value when serializing api errors.
+ Value string
+
+ // Message is a short, human readable decription of the error condition
+ // included in API responses.
+ Message string
+
+ // Description provides a complete account of the errors purpose, suitable
+ // for use in documentation.
+ Description string
+
+ // HTTPStatusCode provides the http status code that is associated with
+ // this error condition.
+ HTTPStatusCode int
+}
+
+// ParseErrorCode returns the value by the string error code.
+// `ErrorCodeUnknown` will be returned if the error is not known.
+func ParseErrorCode(value string) ErrorCode {
+ ed, ok := idToDescriptors[value]
+ if ok {
+ return ed.Code
+ }
+
+ return ErrorCodeUnknown
+}
+
+// Errors provides the envelope for multiple errors and a few sugar methods
+// for use within the application.
+type Errors []error
+
+var _ error = Errors{}
+
+func (errs Errors) Error() string {
+ switch len(errs) {
+ case 0:
+ return "<nil>"
+ case 1:
+ return errs[0].Error()
+ default:
+ msg := "errors:\n"
+ for _, err := range errs {
+ msg += err.Error() + "\n"
+ }
+ return msg
+ }
+}
+
+// Len returns the current number of errors.
+func (errs Errors) Len() int {
+ return len(errs)
+}
+
+// MarshalJSON converts slice of error, ErrorCode or Error into a
+// slice of Error - then serializes
+func (errs Errors) MarshalJSON() ([]byte, error) {
+ var tmpErrs struct {
+ Errors []Error `json:"errors,omitempty"`
+ }
+
+ for _, daErr := range errs {
+ var err Error
+
+ switch daErr.(type) {
+ case ErrorCode:
+ err = daErr.(ErrorCode).WithDetail(nil)
+ case Error:
+ err = daErr.(Error)
+ default:
+ err = ErrorCodeUnknown.WithDetail(daErr)
+
+ }
+
+ // If the Error struct was setup and they forgot to set the
+ // Message field (meaning its "") then grab it from the ErrCode
+ msg := err.Message
+ if msg == "" {
+ msg = err.Code.Message()
+ }
+
+ tmpErrs.Errors = append(tmpErrs.Errors, Error{
+ Code: err.Code,
+ Message: msg,
+ Detail: err.Detail,
+ })
+ }
+
+ return json.Marshal(tmpErrs)
+}
+
+// UnmarshalJSON deserializes []Error and then converts it into slice of
+// Error or ErrorCode
+func (errs *Errors) UnmarshalJSON(data []byte) error {
+ var tmpErrs struct {
+ Errors []Error
+ }
+
+ if err := json.Unmarshal(data, &tmpErrs); err != nil {
+ return err
+ }
+
+ var newErrs Errors
+ for _, daErr := range tmpErrs.Errors {
+ // If Message is empty or exactly matches the Code's message string
+ // then just use the Code, no need for a full Error struct
+ if daErr.Detail == nil && (daErr.Message == "" || daErr.Message == daErr.Code.Message()) {
+ // Error's w/o details get converted to ErrorCode
+ newErrs = append(newErrs, daErr.Code)
+ } else {
+ // Error's w/ details are untouched
+ newErrs = append(newErrs, Error{
+ Code: daErr.Code,
+ Message: daErr.Message,
+ Detail: daErr.Detail,
+ })
+ }
+ }
+
+ *errs = newErrs
+ return nil
+}
diff --git a/vendor/github.com/docker/distribution/registry/api/errcode/handler.go b/vendor/github.com/docker/distribution/registry/api/errcode/handler.go
new file mode 100644
index 0000000..49a64a8
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/api/errcode/handler.go
@@ -0,0 +1,44 @@
+package errcode
+
+import (
+ "encoding/json"
+ "net/http"
+)
+
+// ServeJSON attempts to serve the errcode in a JSON envelope. It marshals err
+// and sets the content-type header to 'application/json'. It will handle
+// ErrorCoder and Errors, and if necessary will create an envelope.
+func ServeJSON(w http.ResponseWriter, err error) error {
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ var sc int
+
+ switch errs := err.(type) {
+ case Errors:
+ if len(errs) < 1 {
+ break
+ }
+
+ if err, ok := errs[0].(ErrorCoder); ok {
+ sc = err.ErrorCode().Descriptor().HTTPStatusCode
+ }
+ case ErrorCoder:
+ sc = errs.ErrorCode().Descriptor().HTTPStatusCode
+ err = Errors{err} // create an envelope.
+ default:
+ // We just have an unhandled error type, so just place in an envelope
+ // and move along.
+ err = Errors{err}
+ }
+
+ if sc == 0 {
+ sc = http.StatusInternalServerError
+ }
+
+ w.WriteHeader(sc)
+
+ if err := json.NewEncoder(w).Encode(err); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/distribution/registry/api/errcode/register.go b/vendor/github.com/docker/distribution/registry/api/errcode/register.go
new file mode 100644
index 0000000..d1e8826
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/api/errcode/register.go
@@ -0,0 +1,138 @@
+package errcode
+
+import (
+ "fmt"
+ "net/http"
+ "sort"
+ "sync"
+)
+
+var (
+ errorCodeToDescriptors = map[ErrorCode]ErrorDescriptor{}
+ idToDescriptors = map[string]ErrorDescriptor{}
+ groupToDescriptors = map[string][]ErrorDescriptor{}
+)
+
+var (
+ // ErrorCodeUnknown is a generic error that can be used as a last
+ // resort if there is no situation-specific error message that can be used
+ ErrorCodeUnknown = Register("errcode", ErrorDescriptor{
+ Value: "UNKNOWN",
+ Message: "unknown error",
+ Description: `Generic error returned when the error does not have an
+ API classification.`,
+ HTTPStatusCode: http.StatusInternalServerError,
+ })
+
+ // ErrorCodeUnsupported is returned when an operation is not supported.
+ ErrorCodeUnsupported = Register("errcode", ErrorDescriptor{
+ Value: "UNSUPPORTED",
+ Message: "The operation is unsupported.",
+ Description: `The operation was unsupported due to a missing
+ implementation or invalid set of parameters.`,
+ HTTPStatusCode: http.StatusMethodNotAllowed,
+ })
+
+ // ErrorCodeUnauthorized is returned if a request requires
+ // authentication.
+ ErrorCodeUnauthorized = Register("errcode", ErrorDescriptor{
+ Value: "UNAUTHORIZED",
+ Message: "authentication required",
+ Description: `The access controller was unable to authenticate
+ the client. Often this will be accompanied by a
+ Www-Authenticate HTTP response header indicating how to
+ authenticate.`,
+ HTTPStatusCode: http.StatusUnauthorized,
+ })
+
+ // ErrorCodeDenied is returned if a client does not have sufficient
+ // permission to perform an action.
+ ErrorCodeDenied = Register("errcode", ErrorDescriptor{
+ Value: "DENIED",
+ Message: "requested access to the resource is denied",
+ Description: `The access controller denied access for the
+ operation on a resource.`,
+ HTTPStatusCode: http.StatusForbidden,
+ })
+
+ // ErrorCodeUnavailable provides a common error to report unavailability
+ // of a service or endpoint.
+ ErrorCodeUnavailable = Register("errcode", ErrorDescriptor{
+ Value: "UNAVAILABLE",
+ Message: "service unavailable",
+ Description: "Returned when a service is not available",
+ HTTPStatusCode: http.StatusServiceUnavailable,
+ })
+
+ // ErrorCodeTooManyRequests is returned if a client attempts too many
+ // times to contact a service endpoint.
+ ErrorCodeTooManyRequests = Register("errcode", ErrorDescriptor{
+ Value: "TOOMANYREQUESTS",
+ Message: "too many requests",
+ Description: `Returned when a client attempts to contact a
+ service too many times`,
+ HTTPStatusCode: http.StatusTooManyRequests,
+ })
+)
+
+var nextCode = 1000
+var registerLock sync.Mutex
+
+// Register will make the passed-in error known to the environment and
+// return a new ErrorCode
+func Register(group string, descriptor ErrorDescriptor) ErrorCode {
+ registerLock.Lock()
+ defer registerLock.Unlock()
+
+ descriptor.Code = ErrorCode(nextCode)
+
+ if _, ok := idToDescriptors[descriptor.Value]; ok {
+ panic(fmt.Sprintf("ErrorValue %q is already registered", descriptor.Value))
+ }
+ if _, ok := errorCodeToDescriptors[descriptor.Code]; ok {
+ panic(fmt.Sprintf("ErrorCode %v is already registered", descriptor.Code))
+ }
+
+ groupToDescriptors[group] = append(groupToDescriptors[group], descriptor)
+ errorCodeToDescriptors[descriptor.Code] = descriptor
+ idToDescriptors[descriptor.Value] = descriptor
+
+ nextCode++
+ return descriptor.Code
+}
+
+type byValue []ErrorDescriptor
+
+func (a byValue) Len() int { return len(a) }
+func (a byValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
+func (a byValue) Less(i, j int) bool { return a[i].Value < a[j].Value }
+
+// GetGroupNames returns the list of Error group names that are registered
+func GetGroupNames() []string {
+ keys := []string{}
+
+ for k := range groupToDescriptors {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ return keys
+}
+
+// GetErrorCodeGroup returns the named group of error descriptors
+func GetErrorCodeGroup(name string) []ErrorDescriptor {
+ desc := groupToDescriptors[name]
+ sort.Sort(byValue(desc))
+ return desc
+}
+
+// GetErrorAllDescriptors returns a slice of all ErrorDescriptors that are
+// registered, irrespective of what group they're in
+func GetErrorAllDescriptors() []ErrorDescriptor {
+ result := []ErrorDescriptor{}
+
+ for _, group := range GetGroupNames() {
+ result = append(result, GetErrorCodeGroup(group)...)
+ }
+ sort.Sort(byValue(result))
+ return result
+}
diff --git a/vendor/github.com/docker/distribution/registry/api/v2/descriptors.go b/vendor/github.com/docker/distribution/registry/api/v2/descriptors.go
new file mode 100644
index 0000000..a9616c5
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/api/v2/descriptors.go
@@ -0,0 +1,1596 @@
+package v2
+
+import (
+ "net/http"
+ "regexp"
+
+ "github.com/docker/distribution/reference"
+ "github.com/docker/distribution/registry/api/errcode"
+ "github.com/opencontainers/go-digest"
+)
+
+var (
+ nameParameterDescriptor = ParameterDescriptor{
+ Name: "name",
+ Type: "string",
+ Format: reference.NameRegexp.String(),
+ Required: true,
+ Description: `Name of the target repository.`,
+ }
+
+ referenceParameterDescriptor = ParameterDescriptor{
+ Name: "reference",
+ Type: "string",
+ Format: reference.TagRegexp.String(),
+ Required: true,
+ Description: `Tag or digest of the target manifest.`,
+ }
+
+ uuidParameterDescriptor = ParameterDescriptor{
+ Name: "uuid",
+ Type: "opaque",
+ Required: true,
+ Description: "A uuid identifying the upload. This field can accept characters that match `[a-zA-Z0-9-_.=]+`.",
+ }
+
+ digestPathParameter = ParameterDescriptor{
+ Name: "digest",
+ Type: "path",
+ Required: true,
+ Format: digest.DigestRegexp.String(),
+ Description: `Digest of desired blob.`,
+ }
+
+ hostHeader = ParameterDescriptor{
+ Name: "Host",
+ Type: "string",
+ Description: "Standard HTTP Host Header. Should be set to the registry host.",
+ Format: "<registry host>",
+ Examples: []string{"registry-1.docker.io"},
+ }
+
+ authHeader = ParameterDescriptor{
+ Name: "Authorization",
+ Type: "string",
+ Description: "An RFC7235 compliant authorization header.",
+ Format: "<scheme> <token>",
+ Examples: []string{"Bearer dGhpcyBpcyBhIGZha2UgYmVhcmVyIHRva2VuIQ=="},
+ }
+
+ authChallengeHeader = ParameterDescriptor{
+ Name: "WWW-Authenticate",
+ Type: "string",
+ Description: "An RFC7235 compliant authentication challenge header.",
+ Format: `<scheme> realm="<realm>", ..."`,
+ Examples: []string{
+ `Bearer realm="https://auth.docker.com/", service="registry.docker.com", scopes="repository:library/ubuntu:pull"`,
+ },
+ }
+
+ contentLengthZeroHeader = ParameterDescriptor{
+ Name: "Content-Length",
+ Description: "The `Content-Length` header must be zero and the body must be empty.",
+ Type: "integer",
+ Format: "0",
+ }
+
+ dockerUploadUUIDHeader = ParameterDescriptor{
+ Name: "Docker-Upload-UUID",
+ Description: "Identifies the docker upload uuid for the current request.",
+ Type: "uuid",
+ Format: "<uuid>",
+ }
+
+ digestHeader = ParameterDescriptor{
+ Name: "Docker-Content-Digest",
+ Description: "Digest of the targeted content for the request.",
+ Type: "digest",
+ Format: "<digest>",
+ }
+
+ linkHeader = ParameterDescriptor{
+ Name: "Link",
+ Type: "link",
+ Description: "RFC5988 compliant rel='next' with URL to next result set, if available",
+ Format: `<<url>?n=<last n value>&last=<last entry from response>>; rel="next"`,
+ }
+
+ paginationParameters = []ParameterDescriptor{
+ {
+ Name: "n",
+ Type: "integer",
+ Description: "Limit the number of entries in each response. It not present, all entries will be returned.",
+ Format: "<integer>",
+ Required: false,
+ },
+ {
+ Name: "last",
+ Type: "string",
+ Description: "Result set will include values lexically after last.",
+ Format: "<integer>",
+ Required: false,
+ },
+ }
+
+ unauthorizedResponseDescriptor = ResponseDescriptor{
+ Name: "Authentication Required",
+ StatusCode: http.StatusUnauthorized,
+ Description: "The client is not authenticated.",
+ Headers: []ParameterDescriptor{
+ authChallengeHeader,
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "Length of the JSON response body.",
+ Format: "<length>",
+ },
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ ErrorCodes: []errcode.ErrorCode{
+ errcode.ErrorCodeUnauthorized,
+ },
+ }
+
+ repositoryNotFoundResponseDescriptor = ResponseDescriptor{
+ Name: "No Such Repository Error",
+ StatusCode: http.StatusNotFound,
+ Description: "The repository is not known to the registry.",
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "Length of the JSON response body.",
+ Format: "<length>",
+ },
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameUnknown,
+ },
+ }
+
+ deniedResponseDescriptor = ResponseDescriptor{
+ Name: "Access Denied",
+ StatusCode: http.StatusForbidden,
+ Description: "The client does not have required access to the repository.",
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "Length of the JSON response body.",
+ Format: "<length>",
+ },
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ ErrorCodes: []errcode.ErrorCode{
+ errcode.ErrorCodeDenied,
+ },
+ }
+
+ tooManyRequestsDescriptor = ResponseDescriptor{
+ Name: "Too Many Requests",
+ StatusCode: http.StatusTooManyRequests,
+ Description: "The client made too many requests within a time interval.",
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "Length of the JSON response body.",
+ Format: "<length>",
+ },
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ ErrorCodes: []errcode.ErrorCode{
+ errcode.ErrorCodeTooManyRequests,
+ },
+ }
+)
+
+const (
+ manifestBody = `{
+ "name": <name>,
+ "tag": <tag>,
+ "fsLayers": [
+ {
+ "blobSum": "<digest>"
+ },
+ ...
+ ]
+ ],
+ "history": <v1 images>,
+ "signature": <JWS>
+}`
+
+ errorsBody = `{
+ "errors:" [
+ {
+ "code": <error code>,
+ "message": "<error message>",
+ "detail": ...
+ },
+ ...
+ ]
+}`
+)
+
+// APIDescriptor exports descriptions of the layout of the v2 registry API.
+var APIDescriptor = struct {
+ // RouteDescriptors provides a list of the routes available in the API.
+ RouteDescriptors []RouteDescriptor
+}{
+ RouteDescriptors: routeDescriptors,
+}
+
+// RouteDescriptor describes a route specified by name.
+type RouteDescriptor struct {
+ // Name is the name of the route, as specified in RouteNameXXX exports.
+ // These names a should be considered a unique reference for a route. If
+ // the route is registered with gorilla, this is the name that will be
+ // used.
+ Name string
+
+ // Path is a gorilla/mux-compatible regexp that can be used to match the
+ // route. For any incoming method and path, only one route descriptor
+ // should match.
+ Path string
+
+ // Entity should be a short, human-readalbe description of the object
+ // targeted by the endpoint.
+ Entity string
+
+ // Description should provide an accurate overview of the functionality
+ // provided by the route.
+ Description string
+
+ // Methods should describe the various HTTP methods that may be used on
+ // this route, including request and response formats.
+ Methods []MethodDescriptor
+}
+
+// MethodDescriptor provides a description of the requests that may be
+// conducted with the target method.
+type MethodDescriptor struct {
+
+ // Method is an HTTP method, such as GET, PUT or POST.
+ Method string
+
+ // Description should provide an overview of the functionality provided by
+ // the covered method, suitable for use in documentation. Use of markdown
+ // here is encouraged.
+ Description string
+
+ // Requests is a slice of request descriptors enumerating how this
+ // endpoint may be used.
+ Requests []RequestDescriptor
+}
+
+// RequestDescriptor covers a particular set of headers and parameters that
+// can be carried out with the parent method. Its most helpful to have one
+// RequestDescriptor per API use case.
+type RequestDescriptor struct {
+ // Name provides a short identifier for the request, usable as a title or
+ // to provide quick context for the particular request.
+ Name string
+
+ // Description should cover the requests purpose, covering any details for
+ // this particular use case.
+ Description string
+
+ // Headers describes headers that must be used with the HTTP request.
+ Headers []ParameterDescriptor
+
+ // PathParameters enumerate the parameterized path components for the
+ // given request, as defined in the route's regular expression.
+ PathParameters []ParameterDescriptor
+
+ // QueryParameters provides a list of query parameters for the given
+ // request.
+ QueryParameters []ParameterDescriptor
+
+ // Body describes the format of the request body.
+ Body BodyDescriptor
+
+ // Successes enumerates the possible responses that are considered to be
+ // the result of a successful request.
+ Successes []ResponseDescriptor
+
+ // Failures covers the possible failures from this particular request.
+ Failures []ResponseDescriptor
+}
+
+// ResponseDescriptor describes the components of an API response.
+type ResponseDescriptor struct {
+ // Name provides a short identifier for the response, usable as a title or
+ // to provide quick context for the particular response.
+ Name string
+
+ // Description should provide a brief overview of the role of the
+ // response.
+ Description string
+
+ // StatusCode specifies the status received by this particular response.
+ StatusCode int
+
+ // Headers covers any headers that may be returned from the response.
+ Headers []ParameterDescriptor
+
+ // Fields describes any fields that may be present in the response.
+ Fields []ParameterDescriptor
+
+ // ErrorCodes enumerates the error codes that may be returned along with
+ // the response.
+ ErrorCodes []errcode.ErrorCode
+
+ // Body describes the body of the response, if any.
+ Body BodyDescriptor
+}
+
+// BodyDescriptor describes a request body and its expected content type. For
+// the most part, it should be example json or some placeholder for body
+// data in documentation.
+type BodyDescriptor struct {
+ ContentType string
+ Format string
+}
+
+// ParameterDescriptor describes the format of a request parameter, which may
+// be a header, path parameter or query parameter.
+type ParameterDescriptor struct {
+ // Name is the name of the parameter, either of the path component or
+ // query parameter.
+ Name string
+
+ // Type specifies the type of the parameter, such as string, integer, etc.
+ Type string
+
+ // Description provides a human-readable description of the parameter.
+ Description string
+
+ // Required means the field is required when set.
+ Required bool
+
+ // Format is a specifying the string format accepted by this parameter.
+ Format string
+
+ // Regexp is a compiled regular expression that can be used to validate
+ // the contents of the parameter.
+ Regexp *regexp.Regexp
+
+ // Examples provides multiple examples for the values that might be valid
+ // for this parameter.
+ Examples []string
+}
+
+var routeDescriptors = []RouteDescriptor{
+ {
+ Name: RouteNameBase,
+ Path: "/v2/",
+ Entity: "Base",
+ Description: `Base V2 API route. Typically, this can be used for lightweight version checks and to validate registry authentication.`,
+ Methods: []MethodDescriptor{
+ {
+ Method: "GET",
+ Description: "Check that the endpoint implements Docker Registry API V2.",
+ Requests: []RequestDescriptor{
+ {
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Description: "The API implements V2 protocol and is accessible.",
+ StatusCode: http.StatusOK,
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Description: "The registry does not implement the V2 API.",
+ StatusCode: http.StatusNotFound,
+ },
+ unauthorizedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ },
+ },
+ },
+ },
+ {
+ Name: RouteNameTags,
+ Path: "/v2/{name:" + reference.NameRegexp.String() + "}/tags/list",
+ Entity: "Tags",
+ Description: "Retrieve information about tags.",
+ Methods: []MethodDescriptor{
+ {
+ Method: "GET",
+ Description: "Fetch the tags under the repository identified by `name`.",
+ Requests: []RequestDescriptor{
+ {
+ Name: "Tags",
+ Description: "Return all tags for the repository",
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ StatusCode: http.StatusOK,
+ Description: "A list of tags for the named repository.",
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "Length of the JSON response body.",
+ Format: "<length>",
+ },
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: `{
+ "name": <name>,
+ "tags": [
+ <tag>,
+ ...
+ ]
+}`,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ {
+ Name: "Tags Paginated",
+ Description: "Return a portion of the tags for the specified repository.",
+ PathParameters: []ParameterDescriptor{nameParameterDescriptor},
+ QueryParameters: paginationParameters,
+ Successes: []ResponseDescriptor{
+ {
+ StatusCode: http.StatusOK,
+ Description: "A list of tags for the named repository.",
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "Length of the JSON response body.",
+ Format: "<length>",
+ },
+ linkHeader,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: `{
+ "name": <name>,
+ "tags": [
+ <tag>,
+ ...
+ ],
+}`,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ },
+ },
+ },
+ },
+ {
+ Name: RouteNameManifest,
+ Path: "/v2/{name:" + reference.NameRegexp.String() + "}/manifests/{reference:" + reference.TagRegexp.String() + "|" + digest.DigestRegexp.String() + "}",
+ Entity: "Manifest",
+ Description: "Create, update, delete and retrieve manifests.",
+ Methods: []MethodDescriptor{
+ {
+ Method: "GET",
+ Description: "Fetch the manifest identified by `name` and `reference` where `reference` can be a tag or digest. A `HEAD` request can also be issued to this endpoint to obtain resource information without receiving all data.",
+ Requests: []RequestDescriptor{
+ {
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ referenceParameterDescriptor,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Description: "The manifest identified by `name` and `reference`. The contents can be used to identify and resolve resources required to run the specified image.",
+ StatusCode: http.StatusOK,
+ Headers: []ParameterDescriptor{
+ digestHeader,
+ },
+ Body: BodyDescriptor{
+ ContentType: "<media type of manifest>",
+ Format: manifestBody,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Description: "The name or reference was invalid.",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameInvalid,
+ ErrorCodeTagInvalid,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ },
+ },
+ {
+ Method: "PUT",
+ Description: "Put the manifest identified by `name` and `reference` where `reference` can be a tag or digest.",
+ Requests: []RequestDescriptor{
+ {
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ referenceParameterDescriptor,
+ },
+ Body: BodyDescriptor{
+ ContentType: "<media type of manifest>",
+ Format: manifestBody,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Description: "The manifest has been accepted by the registry and is stored under the specified `name` and `tag`.",
+ StatusCode: http.StatusCreated,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Location",
+ Type: "url",
+ Description: "The canonical location url of the uploaded manifest.",
+ Format: "<url>",
+ },
+ contentLengthZeroHeader,
+ digestHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Name: "Invalid Manifest",
+ Description: "The received manifest was invalid in some way, as described by the error codes. The client should resolve the issue and retry the request.",
+ StatusCode: http.StatusBadRequest,
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameInvalid,
+ ErrorCodeTagInvalid,
+ ErrorCodeManifestInvalid,
+ ErrorCodeManifestUnverified,
+ ErrorCodeBlobUnknown,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ {
+ Name: "Missing Layer(s)",
+ Description: "One or more layers may be missing during a manifest upload. If so, the missing layers will be enumerated in the error response.",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeBlobUnknown,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: `{
+ "errors:" [{
+ "code": "BLOB_UNKNOWN",
+ "message": "blob unknown to registry",
+ "detail": {
+ "digest": "<digest>"
+ }
+ },
+ ...
+ ]
+}`,
+ },
+ },
+ {
+ Name: "Not allowed",
+ Description: "Manifest put is not allowed because the registry is configured as a pull-through cache or for some other reason",
+ StatusCode: http.StatusMethodNotAllowed,
+ ErrorCodes: []errcode.ErrorCode{
+ errcode.ErrorCodeUnsupported,
+ },
+ },
+ },
+ },
+ },
+ },
+ {
+ Method: "DELETE",
+ Description: "Delete the manifest identified by `name` and `reference`. Note that a manifest can _only_ be deleted by `digest`.",
+ Requests: []RequestDescriptor{
+ {
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ referenceParameterDescriptor,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ StatusCode: http.StatusAccepted,
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Name: "Invalid Name or Reference",
+ Description: "The specified `name` or `reference` were invalid and the delete was unable to proceed.",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameInvalid,
+ ErrorCodeTagInvalid,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ {
+ Name: "Unknown Manifest",
+ Description: "The specified `name` or `reference` are unknown to the registry and the delete was unable to proceed. Clients can assume the manifest was already deleted if this response is returned.",
+ StatusCode: http.StatusNotFound,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameUnknown,
+ ErrorCodeManifestUnknown,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ {
+ Name: "Not allowed",
+ Description: "Manifest delete is not allowed because the registry is configured as a pull-through cache or `delete` has been disabled.",
+ StatusCode: http.StatusMethodNotAllowed,
+ ErrorCodes: []errcode.ErrorCode{
+ errcode.ErrorCodeUnsupported,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+
+ {
+ Name: RouteNameBlob,
+ Path: "/v2/{name:" + reference.NameRegexp.String() + "}/blobs/{digest:" + digest.DigestRegexp.String() + "}",
+ Entity: "Blob",
+ Description: "Operations on blobs identified by `name` and `digest`. Used to fetch or delete layers by digest.",
+ Methods: []MethodDescriptor{
+ {
+ Method: "GET",
+ Description: "Retrieve the blob from the registry identified by `digest`. A `HEAD` request can also be issued to this endpoint to obtain resource information without receiving all data.",
+ Requests: []RequestDescriptor{
+ {
+ Name: "Fetch Blob",
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ digestPathParameter,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Description: "The blob identified by `digest` is available. The blob content will be present in the body of the request.",
+ StatusCode: http.StatusOK,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "The length of the requested blob content.",
+ Format: "<length>",
+ },
+ digestHeader,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/octet-stream",
+ Format: "<blob binary data>",
+ },
+ },
+ {
+ Description: "The blob identified by `digest` is available at the provided location.",
+ StatusCode: http.StatusTemporaryRedirect,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Location",
+ Type: "url",
+ Description: "The location where the layer should be accessible.",
+ Format: "<blob location>",
+ },
+ digestHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Description: "There was a problem with the request that needs to be addressed by the client, such as an invalid `name` or `tag`.",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameInvalid,
+ ErrorCodeDigestInvalid,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ {
+ Description: "The blob, identified by `name` and `digest`, is unknown to the registry.",
+ StatusCode: http.StatusNotFound,
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameUnknown,
+ ErrorCodeBlobUnknown,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ {
+ Name: "Fetch Blob Part",
+ Description: "This endpoint may also support RFC7233 compliant range requests. Support can be detected by issuing a HEAD request. If the header `Accept-Range: bytes` is returned, range requests can be used to fetch partial content.",
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ {
+ Name: "Range",
+ Type: "string",
+ Description: "HTTP Range header specifying blob chunk.",
+ Format: "bytes=<start>-<end>",
+ },
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ digestPathParameter,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Description: "The blob identified by `digest` is available. The specified chunk of blob content will be present in the body of the request.",
+ StatusCode: http.StatusPartialContent,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "The length of the requested blob chunk.",
+ Format: "<length>",
+ },
+ {
+ Name: "Content-Range",
+ Type: "byte range",
+ Description: "Content range of blob chunk.",
+ Format: "bytes <start>-<end>/<size>",
+ },
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/octet-stream",
+ Format: "<blob binary data>",
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Description: "There was a problem with the request that needs to be addressed by the client, such as an invalid `name` or `tag`.",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameInvalid,
+ ErrorCodeDigestInvalid,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ {
+ StatusCode: http.StatusNotFound,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameUnknown,
+ ErrorCodeBlobUnknown,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ {
+ Description: "The range specification cannot be satisfied for the requested content. This can happen when the range is not formatted correctly or if the range is outside of the valid size of the content.",
+ StatusCode: http.StatusRequestedRangeNotSatisfiable,
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ },
+ },
+ {
+ Method: "DELETE",
+ Description: "Delete the blob identified by `name` and `digest`",
+ Requests: []RequestDescriptor{
+ {
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ digestPathParameter,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ StatusCode: http.StatusAccepted,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "0",
+ Format: "0",
+ },
+ digestHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Name: "Invalid Name or Digest",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeDigestInvalid,
+ ErrorCodeNameInvalid,
+ },
+ },
+ {
+ Description: "The blob, identified by `name` and `digest`, is unknown to the registry.",
+ StatusCode: http.StatusNotFound,
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameUnknown,
+ ErrorCodeBlobUnknown,
+ },
+ },
+ {
+ Description: "Blob delete is not allowed because the registry is configured as a pull-through cache or `delete` has been disabled",
+ StatusCode: http.StatusMethodNotAllowed,
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ ErrorCodes: []errcode.ErrorCode{
+ errcode.ErrorCodeUnsupported,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ },
+ },
+
+ // TODO(stevvooe): We may want to add a PUT request here to
+ // kickoff an upload of a blob, integrated with the blob upload
+ // API.
+ },
+ },
+
+ {
+ Name: RouteNameBlobUpload,
+ Path: "/v2/{name:" + reference.NameRegexp.String() + "}/blobs/uploads/",
+ Entity: "Initiate Blob Upload",
+ Description: "Initiate a blob upload. This endpoint can be used to create resumable uploads or monolithic uploads.",
+ Methods: []MethodDescriptor{
+ {
+ Method: "POST",
+ Description: "Initiate a resumable blob upload. If successful, an upload location will be provided to complete the upload. Optionally, if the `digest` parameter is present, the request body will be used to complete the upload in a single request.",
+ Requests: []RequestDescriptor{
+ {
+ Name: "Initiate Monolithic Blob Upload",
+ Description: "Upload a blob identified by the `digest` parameter in single request. This upload will not be resumable unless a recoverable error is returned.",
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Format: "<length of blob>",
+ },
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ },
+ QueryParameters: []ParameterDescriptor{
+ {
+ Name: "digest",
+ Type: "query",
+ Format: "<digest>",
+ Regexp: digest.DigestRegexp,
+ Description: `Digest of uploaded blob. If present, the upload will be completed, in a single request, with contents of the request body as the resulting blob.`,
+ },
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/octect-stream",
+ Format: "<binary data>",
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Description: "The blob has been created in the registry and is available at the provided location.",
+ StatusCode: http.StatusCreated,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Location",
+ Type: "url",
+ Format: "<blob location>",
+ },
+ contentLengthZeroHeader,
+ dockerUploadUUIDHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Name: "Invalid Name or Digest",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeDigestInvalid,
+ ErrorCodeNameInvalid,
+ },
+ },
+ {
+ Name: "Not allowed",
+ Description: "Blob upload is not allowed because the registry is configured as a pull-through cache or for some other reason",
+ StatusCode: http.StatusMethodNotAllowed,
+ ErrorCodes: []errcode.ErrorCode{
+ errcode.ErrorCodeUnsupported,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ {
+ Name: "Initiate Resumable Blob Upload",
+ Description: "Initiate a resumable blob upload with an empty request body.",
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ contentLengthZeroHeader,
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Description: "The upload has been created. The `Location` header must be used to complete the upload. The response should be identical to a `GET` request on the contents of the returned `Location` header.",
+ StatusCode: http.StatusAccepted,
+ Headers: []ParameterDescriptor{
+ contentLengthZeroHeader,
+ {
+ Name: "Location",
+ Type: "url",
+ Format: "/v2/<name>/blobs/uploads/<uuid>",
+ Description: "The location of the created upload. Clients should use the contents verbatim to complete the upload, adding parameters where required.",
+ },
+ {
+ Name: "Range",
+ Format: "0-0",
+ Description: "Range header indicating the progress of the upload. When starting an upload, it will return an empty range, since no content has been received.",
+ },
+ dockerUploadUUIDHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Name: "Invalid Name or Digest",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeDigestInvalid,
+ ErrorCodeNameInvalid,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ {
+ Name: "Mount Blob",
+ Description: "Mount a blob identified by the `mount` parameter from another repository.",
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ contentLengthZeroHeader,
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ },
+ QueryParameters: []ParameterDescriptor{
+ {
+ Name: "mount",
+ Type: "query",
+ Format: "<digest>",
+ Regexp: digest.DigestRegexp,
+ Description: `Digest of blob to mount from the source repository.`,
+ },
+ {
+ Name: "from",
+ Type: "query",
+ Format: "<repository name>",
+ Regexp: reference.NameRegexp,
+ Description: `Name of the source repository.`,
+ },
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Description: "The blob has been mounted in the repository and is available at the provided location.",
+ StatusCode: http.StatusCreated,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Location",
+ Type: "url",
+ Format: "<blob location>",
+ },
+ contentLengthZeroHeader,
+ dockerUploadUUIDHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Name: "Invalid Name or Digest",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeDigestInvalid,
+ ErrorCodeNameInvalid,
+ },
+ },
+ {
+ Name: "Not allowed",
+ Description: "Blob mount is not allowed because the registry is configured as a pull-through cache or for some other reason",
+ StatusCode: http.StatusMethodNotAllowed,
+ ErrorCodes: []errcode.ErrorCode{
+ errcode.ErrorCodeUnsupported,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ },
+ },
+ },
+ },
+
+ {
+ Name: RouteNameBlobUploadChunk,
+ Path: "/v2/{name:" + reference.NameRegexp.String() + "}/blobs/uploads/{uuid:[a-zA-Z0-9-_.=]+}",
+ Entity: "Blob Upload",
+ Description: "Interact with blob uploads. Clients should never assemble URLs for this endpoint and should only take it through the `Location` header on related API requests. The `Location` header and its parameters should be preserved by clients, using the latest value returned via upload related API calls.",
+ Methods: []MethodDescriptor{
+ {
+ Method: "GET",
+ Description: "Retrieve status of upload identified by `uuid`. The primary purpose of this endpoint is to resolve the current status of a resumable upload.",
+ Requests: []RequestDescriptor{
+ {
+ Description: "Retrieve the progress of the current upload, as reported by the `Range` header.",
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ uuidParameterDescriptor,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Name: "Upload Progress",
+ Description: "The upload is known and in progress. The last received offset is available in the `Range` header.",
+ StatusCode: http.StatusNoContent,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Range",
+ Type: "header",
+ Format: "0-<offset>",
+ Description: "Range indicating the current progress of the upload.",
+ },
+ contentLengthZeroHeader,
+ dockerUploadUUIDHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Description: "There was an error processing the upload and it must be restarted.",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeDigestInvalid,
+ ErrorCodeNameInvalid,
+ ErrorCodeBlobUploadInvalid,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ {
+ Description: "The upload is unknown to the registry. The upload must be restarted.",
+ StatusCode: http.StatusNotFound,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeBlobUploadUnknown,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ },
+ },
+ {
+ Method: "PATCH",
+ Description: "Upload a chunk of data for the specified upload.",
+ Requests: []RequestDescriptor{
+ {
+ Name: "Stream upload",
+ Description: "Upload a stream of data to upload without completing the upload.",
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ uuidParameterDescriptor,
+ },
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/octet-stream",
+ Format: "<binary data>",
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Name: "Data Accepted",
+ Description: "The stream of data has been accepted and the current progress is available in the range header. The updated upload location is available in the `Location` header.",
+ StatusCode: http.StatusNoContent,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Location",
+ Type: "url",
+ Format: "/v2/<name>/blobs/uploads/<uuid>",
+ Description: "The location of the upload. Clients should assume this changes after each request. Clients should use the contents verbatim to complete the upload, adding parameters where required.",
+ },
+ {
+ Name: "Range",
+ Type: "header",
+ Format: "0-<offset>",
+ Description: "Range indicating the current progress of the upload.",
+ },
+ contentLengthZeroHeader,
+ dockerUploadUUIDHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Description: "There was an error processing the upload and it must be restarted.",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeDigestInvalid,
+ ErrorCodeNameInvalid,
+ ErrorCodeBlobUploadInvalid,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ {
+ Description: "The upload is unknown to the registry. The upload must be restarted.",
+ StatusCode: http.StatusNotFound,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeBlobUploadUnknown,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ {
+ Name: "Chunked upload",
+ Description: "Upload a chunk of data to specified upload without completing the upload. The data will be uploaded to the specified Content Range.",
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ uuidParameterDescriptor,
+ },
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ {
+ Name: "Content-Range",
+ Type: "header",
+ Format: "<start of range>-<end of range, inclusive>",
+ Required: true,
+ Description: "Range of bytes identifying the desired block of content represented by the body. Start must the end offset retrieved via status check plus one. Note that this is a non-standard use of the `Content-Range` header.",
+ },
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Format: "<length of chunk>",
+ Description: "Length of the chunk being uploaded, corresponding the length of the request body.",
+ },
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/octet-stream",
+ Format: "<binary chunk>",
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Name: "Chunk Accepted",
+ Description: "The chunk of data has been accepted and the current progress is available in the range header. The updated upload location is available in the `Location` header.",
+ StatusCode: http.StatusNoContent,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Location",
+ Type: "url",
+ Format: "/v2/<name>/blobs/uploads/<uuid>",
+ Description: "The location of the upload. Clients should assume this changes after each request. Clients should use the contents verbatim to complete the upload, adding parameters where required.",
+ },
+ {
+ Name: "Range",
+ Type: "header",
+ Format: "0-<offset>",
+ Description: "Range indicating the current progress of the upload.",
+ },
+ contentLengthZeroHeader,
+ dockerUploadUUIDHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Description: "There was an error processing the upload and it must be restarted.",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeDigestInvalid,
+ ErrorCodeNameInvalid,
+ ErrorCodeBlobUploadInvalid,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ {
+ Description: "The upload is unknown to the registry. The upload must be restarted.",
+ StatusCode: http.StatusNotFound,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeBlobUploadUnknown,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ {
+ Description: "The `Content-Range` specification cannot be accepted, either because it does not overlap with the current progress or it is invalid.",
+ StatusCode: http.StatusRequestedRangeNotSatisfiable,
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ },
+ },
+ {
+ Method: "PUT",
+ Description: "Complete the upload specified by `uuid`, optionally appending the body as the final chunk.",
+ Requests: []RequestDescriptor{
+ {
+ Description: "Complete the upload, providing all the data in the body, if necessary. A request without a body will just complete the upload with previously uploaded content.",
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Format: "<length of data>",
+ Description: "Length of the data being uploaded, corresponding to the length of the request body. May be zero if no data is provided.",
+ },
+ },
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ uuidParameterDescriptor,
+ },
+ QueryParameters: []ParameterDescriptor{
+ {
+ Name: "digest",
+ Type: "string",
+ Format: "<digest>",
+ Regexp: digest.DigestRegexp,
+ Required: true,
+ Description: `Digest of uploaded blob.`,
+ },
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/octet-stream",
+ Format: "<binary data>",
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Name: "Upload Complete",
+ Description: "The upload has been completed and accepted by the registry. The canonical location will be available in the `Location` header.",
+ StatusCode: http.StatusNoContent,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Location",
+ Type: "url",
+ Format: "<blob location>",
+ Description: "The canonical location of the blob for retrieval",
+ },
+ {
+ Name: "Content-Range",
+ Type: "header",
+ Format: "<start of range>-<end of range, inclusive>",
+ Description: "Range of bytes identifying the desired block of content represented by the body. Start must match the end of offset retrieved via status check. Note that this is a non-standard use of the `Content-Range` header.",
+ },
+ contentLengthZeroHeader,
+ digestHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Description: "There was an error processing the upload and it must be restarted.",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeDigestInvalid,
+ ErrorCodeNameInvalid,
+ ErrorCodeBlobUploadInvalid,
+ errcode.ErrorCodeUnsupported,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ {
+ Description: "The upload is unknown to the registry. The upload must be restarted.",
+ StatusCode: http.StatusNotFound,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeBlobUploadUnknown,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ },
+ },
+ {
+ Method: "DELETE",
+ Description: "Cancel outstanding upload processes, releasing associated resources. If this is not called, the unfinished uploads will eventually timeout.",
+ Requests: []RequestDescriptor{
+ {
+ Description: "Cancel the upload specified by `uuid`.",
+ PathParameters: []ParameterDescriptor{
+ nameParameterDescriptor,
+ uuidParameterDescriptor,
+ },
+ Headers: []ParameterDescriptor{
+ hostHeader,
+ authHeader,
+ contentLengthZeroHeader,
+ },
+ Successes: []ResponseDescriptor{
+ {
+ Name: "Upload Deleted",
+ Description: "The upload has been successfully deleted.",
+ StatusCode: http.StatusNoContent,
+ Headers: []ParameterDescriptor{
+ contentLengthZeroHeader,
+ },
+ },
+ },
+ Failures: []ResponseDescriptor{
+ {
+ Description: "An error was encountered processing the delete. The client may ignore this error.",
+ StatusCode: http.StatusBadRequest,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeNameInvalid,
+ ErrorCodeBlobUploadInvalid,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ {
+ Description: "The upload is unknown to the registry. The client may ignore this error and assume the upload has been deleted.",
+ StatusCode: http.StatusNotFound,
+ ErrorCodes: []errcode.ErrorCode{
+ ErrorCodeBlobUploadUnknown,
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: errorsBody,
+ },
+ },
+ unauthorizedResponseDescriptor,
+ repositoryNotFoundResponseDescriptor,
+ deniedResponseDescriptor,
+ tooManyRequestsDescriptor,
+ },
+ },
+ },
+ },
+ },
+ },
+ {
+ Name: RouteNameCatalog,
+ Path: "/v2/_catalog",
+ Entity: "Catalog",
+ Description: "List a set of available repositories in the local registry cluster. Does not provide any indication of what may be available upstream. Applications can only determine if a repository is available but not if it is not available.",
+ Methods: []MethodDescriptor{
+ {
+ Method: "GET",
+ Description: "Retrieve a sorted, json list of repositories available in the registry.",
+ Requests: []RequestDescriptor{
+ {
+ Name: "Catalog Fetch",
+ Description: "Request an unabridged list of repositories available. The implementation may impose a maximum limit and return a partial set with pagination links.",
+ Successes: []ResponseDescriptor{
+ {
+ Description: "Returns the unabridged list of repositories as a json response.",
+ StatusCode: http.StatusOK,
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "Length of the JSON response body.",
+ Format: "<length>",
+ },
+ },
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: `{
+ "repositories": [
+ <name>,
+ ...
+ ]
+}`,
+ },
+ },
+ },
+ },
+ {
+ Name: "Catalog Fetch Paginated",
+ Description: "Return the specified portion of repositories.",
+ QueryParameters: paginationParameters,
+ Successes: []ResponseDescriptor{
+ {
+ StatusCode: http.StatusOK,
+ Body: BodyDescriptor{
+ ContentType: "application/json; charset=utf-8",
+ Format: `{
+ "repositories": [
+ <name>,
+ ...
+ ]
+ "next": "<url>?last=<name>&n=<last value of n>"
+}`,
+ },
+ Headers: []ParameterDescriptor{
+ {
+ Name: "Content-Length",
+ Type: "integer",
+ Description: "Length of the JSON response body.",
+ Format: "<length>",
+ },
+ linkHeader,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+}
+
+var routeDescriptorsMap map[string]RouteDescriptor
+
+func init() {
+ routeDescriptorsMap = make(map[string]RouteDescriptor, len(routeDescriptors))
+
+ for _, descriptor := range routeDescriptors {
+ routeDescriptorsMap[descriptor.Name] = descriptor
+ }
+}
diff --git a/vendor/github.com/docker/distribution/registry/api/v2/doc.go b/vendor/github.com/docker/distribution/registry/api/v2/doc.go
new file mode 100644
index 0000000..cde0119
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/api/v2/doc.go
@@ -0,0 +1,9 @@
+// Package v2 describes routes, urls and the error codes used in the Docker
+// Registry JSON HTTP API V2. In addition to declarations, descriptors are
+// provided for routes and error codes that can be used for implementation and
+// automatically generating documentation.
+//
+// Definitions here are considered to be locked down for the V2 registry api.
+// Any changes must be considered carefully and should not proceed without a
+// change proposal in docker core.
+package v2
diff --git a/vendor/github.com/docker/distribution/registry/api/v2/errors.go b/vendor/github.com/docker/distribution/registry/api/v2/errors.go
new file mode 100644
index 0000000..97d6923
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/api/v2/errors.go
@@ -0,0 +1,136 @@
+package v2
+
+import (
+ "net/http"
+
+ "github.com/docker/distribution/registry/api/errcode"
+)
+
+const errGroup = "registry.api.v2"
+
+var (
+ // ErrorCodeDigestInvalid is returned when uploading a blob if the
+ // provided digest does not match the blob contents.
+ ErrorCodeDigestInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "DIGEST_INVALID",
+ Message: "provided digest did not match uploaded content",
+ Description: `When a blob is uploaded, the registry will check that
+ the content matches the digest provided by the client. The error may
+ include a detail structure with the key "digest", including the
+ invalid digest string. This error may also be returned when a manifest
+ includes an invalid layer digest.`,
+ HTTPStatusCode: http.StatusBadRequest,
+ })
+
+ // ErrorCodeSizeInvalid is returned when uploading a blob if the provided
+ ErrorCodeSizeInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "SIZE_INVALID",
+ Message: "provided length did not match content length",
+ Description: `When a layer is uploaded, the provided size will be
+ checked against the uploaded content. If they do not match, this error
+ will be returned.`,
+ HTTPStatusCode: http.StatusBadRequest,
+ })
+
+ // ErrorCodeNameInvalid is returned when the name in the manifest does not
+ // match the provided name.
+ ErrorCodeNameInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "NAME_INVALID",
+ Message: "invalid repository name",
+ Description: `Invalid repository name encountered either during
+ manifest validation or any API operation.`,
+ HTTPStatusCode: http.StatusBadRequest,
+ })
+
+ // ErrorCodeTagInvalid is returned when the tag in the manifest does not
+ // match the provided tag.
+ ErrorCodeTagInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "TAG_INVALID",
+ Message: "manifest tag did not match URI",
+ Description: `During a manifest upload, if the tag in the manifest
+ does not match the uri tag, this error will be returned.`,
+ HTTPStatusCode: http.StatusBadRequest,
+ })
+
+ // ErrorCodeNameUnknown when the repository name is not known.
+ ErrorCodeNameUnknown = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "NAME_UNKNOWN",
+ Message: "repository name not known to registry",
+ Description: `This is returned if the name used during an operation is
+ unknown to the registry.`,
+ HTTPStatusCode: http.StatusNotFound,
+ })
+
+ // ErrorCodeManifestUnknown returned when image manifest is unknown.
+ ErrorCodeManifestUnknown = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "MANIFEST_UNKNOWN",
+ Message: "manifest unknown",
+ Description: `This error is returned when the manifest, identified by
+ name and tag is unknown to the repository.`,
+ HTTPStatusCode: http.StatusNotFound,
+ })
+
+ // ErrorCodeManifestInvalid returned when an image manifest is invalid,
+ // typically during a PUT operation. This error encompasses all errors
+ // encountered during manifest validation that aren't signature errors.
+ ErrorCodeManifestInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "MANIFEST_INVALID",
+ Message: "manifest invalid",
+ Description: `During upload, manifests undergo several checks ensuring
+ validity. If those checks fail, this error may be returned, unless a
+ more specific error is included. The detail will contain information
+ the failed validation.`,
+ HTTPStatusCode: http.StatusBadRequest,
+ })
+
+ // ErrorCodeManifestUnverified is returned when the manifest fails
+ // signature verification.
+ ErrorCodeManifestUnverified = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "MANIFEST_UNVERIFIED",
+ Message: "manifest failed signature verification",
+ Description: `During manifest upload, if the manifest fails signature
+ verification, this error will be returned.`,
+ HTTPStatusCode: http.StatusBadRequest,
+ })
+
+ // ErrorCodeManifestBlobUnknown is returned when a manifest blob is
+ // unknown to the registry.
+ ErrorCodeManifestBlobUnknown = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "MANIFEST_BLOB_UNKNOWN",
+ Message: "blob unknown to registry",
+ Description: `This error may be returned when a manifest blob is
+ unknown to the registry.`,
+ HTTPStatusCode: http.StatusBadRequest,
+ })
+
+ // ErrorCodeBlobUnknown is returned when a blob is unknown to the
+ // registry. This can happen when the manifest references a nonexistent
+ // layer or the result is not found by a blob fetch.
+ ErrorCodeBlobUnknown = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "BLOB_UNKNOWN",
+ Message: "blob unknown to registry",
+ Description: `This error may be returned when a blob is unknown to the
+ registry in a specified repository. This can be returned with a
+ standard get or if a manifest references an unknown layer during
+ upload.`,
+ HTTPStatusCode: http.StatusNotFound,
+ })
+
+ // ErrorCodeBlobUploadUnknown is returned when an upload is unknown.
+ ErrorCodeBlobUploadUnknown = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "BLOB_UPLOAD_UNKNOWN",
+ Message: "blob upload unknown to registry",
+ Description: `If a blob upload has been cancelled or was never
+ started, this error code may be returned.`,
+ HTTPStatusCode: http.StatusNotFound,
+ })
+
+ // ErrorCodeBlobUploadInvalid is returned when an upload is invalid.
+ ErrorCodeBlobUploadInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{
+ Value: "BLOB_UPLOAD_INVALID",
+ Message: "blob upload invalid",
+ Description: `The blob upload encountered an error and can no
+ longer proceed.`,
+ HTTPStatusCode: http.StatusNotFound,
+ })
+)
diff --git a/vendor/github.com/docker/distribution/registry/api/v2/headerparser.go b/vendor/github.com/docker/distribution/registry/api/v2/headerparser.go
new file mode 100644
index 0000000..9bc41a3
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/api/v2/headerparser.go
@@ -0,0 +1,161 @@
+package v2
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+ "unicode"
+)
+
+var (
+ // according to rfc7230
+ reToken = regexp.MustCompile(`^[^"(),/:;<=>?@[\]{}[:space:][:cntrl:]]+`)
+ reQuotedValue = regexp.MustCompile(`^[^\\"]+`)
+ reEscapedCharacter = regexp.MustCompile(`^[[:blank:][:graph:]]`)
+)
+
+// parseForwardedHeader is a benevolent parser of Forwarded header defined in rfc7239. The header contains
+// a comma-separated list of forwarding key-value pairs. Each list element is set by single proxy. The
+// function parses only the first element of the list, which is set by the very first proxy. It returns a map
+// of corresponding key-value pairs and an unparsed slice of the input string.
+//
+// Examples of Forwarded header values:
+//
+// 1. Forwarded: For=192.0.2.43; Proto=https,For="[2001:db8:cafe::17]",For=unknown
+// 2. Forwarded: for="192.0.2.43:443"; host="registry.example.org", for="10.10.05.40:80"
+//
+// The first will be parsed into {"for": "192.0.2.43", "proto": "https"} while the second into
+// {"for": "192.0.2.43:443", "host": "registry.example.org"}.
+func parseForwardedHeader(forwarded string) (map[string]string, string, error) {
+ // Following are states of forwarded header parser. Any state could transition to a failure.
+ const (
+ // terminating state; can transition to Parameter
+ stateElement = iota
+ // terminating state; can transition to KeyValueDelimiter
+ stateParameter
+ // can transition to Value
+ stateKeyValueDelimiter
+ // can transition to one of { QuotedValue, PairEnd }
+ stateValue
+ // can transition to one of { EscapedCharacter, PairEnd }
+ stateQuotedValue
+ // can transition to one of { QuotedValue }
+ stateEscapedCharacter
+ // terminating state; can transition to one of { Parameter, Element }
+ statePairEnd
+ )
+
+ var (
+ parameter string
+ value string
+ parse = forwarded[:]
+ res = map[string]string{}
+ state = stateElement
+ )
+
+Loop:
+ for {
+ // skip spaces unless in quoted value
+ if state != stateQuotedValue && state != stateEscapedCharacter {
+ parse = strings.TrimLeftFunc(parse, unicode.IsSpace)
+ }
+
+ if len(parse) == 0 {
+ if state != stateElement && state != statePairEnd && state != stateParameter {
+ return nil, parse, fmt.Errorf("unexpected end of input")
+ }
+ // terminating
+ break
+ }
+
+ switch state {
+ // terminate at list element delimiter
+ case stateElement:
+ if parse[0] == ',' {
+ parse = parse[1:]
+ break Loop
+ }
+ state = stateParameter
+
+ // parse parameter (the key of key-value pair)
+ case stateParameter:
+ match := reToken.FindString(parse)
+ if len(match) == 0 {
+ return nil, parse, fmt.Errorf("failed to parse token at position %d", len(forwarded)-len(parse))
+ }
+ parameter = strings.ToLower(match)
+ parse = parse[len(match):]
+ state = stateKeyValueDelimiter
+
+ // parse '='
+ case stateKeyValueDelimiter:
+ if parse[0] != '=' {
+ return nil, parse, fmt.Errorf("expected '=', not '%c' at position %d", parse[0], len(forwarded)-len(parse))
+ }
+ parse = parse[1:]
+ state = stateValue
+
+ // parse value or quoted value
+ case stateValue:
+ if parse[0] == '"' {
+ parse = parse[1:]
+ state = stateQuotedValue
+ } else {
+ value = reToken.FindString(parse)
+ if len(value) == 0 {
+ return nil, parse, fmt.Errorf("failed to parse value at position %d", len(forwarded)-len(parse))
+ }
+ if _, exists := res[parameter]; exists {
+ return nil, parse, fmt.Errorf("duplicate parameter %q at position %d", parameter, len(forwarded)-len(parse))
+ }
+ res[parameter] = value
+ parse = parse[len(value):]
+ value = ""
+ state = statePairEnd
+ }
+
+ // parse a part of quoted value until the first backslash
+ case stateQuotedValue:
+ match := reQuotedValue.FindString(parse)
+ value += match
+ parse = parse[len(match):]
+ switch {
+ case len(parse) == 0:
+ return nil, parse, fmt.Errorf("unterminated quoted string")
+ case parse[0] == '"':
+ res[parameter] = value
+ value = ""
+ parse = parse[1:]
+ state = statePairEnd
+ case parse[0] == '\\':
+ parse = parse[1:]
+ state = stateEscapedCharacter
+ }
+
+ // parse escaped character in a quoted string, ignore the backslash
+ // transition back to QuotedValue state
+ case stateEscapedCharacter:
+ c := reEscapedCharacter.FindString(parse)
+ if len(c) == 0 {
+ return nil, parse, fmt.Errorf("invalid escape sequence at position %d", len(forwarded)-len(parse)-1)
+ }
+ value += c
+ parse = parse[1:]
+ state = stateQuotedValue
+
+ // expect either a new key-value pair, new list or end of input
+ case statePairEnd:
+ switch parse[0] {
+ case ';':
+ parse = parse[1:]
+ state = stateParameter
+ case ',':
+ state = stateElement
+ default:
+ return nil, parse, fmt.Errorf("expected ',' or ';', not %c at position %d", parse[0], len(forwarded)-len(parse))
+ }
+ }
+ }
+
+ return res, parse, nil
+}
diff --git a/vendor/github.com/docker/distribution/registry/api/v2/routes.go b/vendor/github.com/docker/distribution/registry/api/v2/routes.go
new file mode 100644
index 0000000..5b80d5b
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/api/v2/routes.go
@@ -0,0 +1,49 @@
+package v2
+
+import "github.com/gorilla/mux"
+
+// The following are definitions of the name under which all V2 routes are
+// registered. These symbols can be used to look up a route based on the name.
+const (
+ RouteNameBase = "base"
+ RouteNameManifest = "manifest"
+ RouteNameTags = "tags"
+ RouteNameBlob = "blob"
+ RouteNameBlobUpload = "blob-upload"
+ RouteNameBlobUploadChunk = "blob-upload-chunk"
+ RouteNameCatalog = "catalog"
+)
+
+var allEndpoints = []string{
+ RouteNameManifest,
+ RouteNameCatalog,
+ RouteNameTags,
+ RouteNameBlob,
+ RouteNameBlobUpload,
+ RouteNameBlobUploadChunk,
+}
+
+// Router builds a gorilla router with named routes for the various API
+// methods. This can be used directly by both server implementations and
+// clients.
+func Router() *mux.Router {
+ return RouterWithPrefix("")
+}
+
+// RouterWithPrefix builds a gorilla router with a configured prefix
+// on all routes.
+func RouterWithPrefix(prefix string) *mux.Router {
+ rootRouter := mux.NewRouter()
+ router := rootRouter
+ if prefix != "" {
+ router = router.PathPrefix(prefix).Subrouter()
+ }
+
+ router.StrictSlash(true)
+
+ for _, descriptor := range routeDescriptors {
+ router.Path(descriptor.Path).Name(descriptor.Name)
+ }
+
+ return rootRouter
+}
diff --git a/vendor/github.com/docker/distribution/registry/api/v2/urls.go b/vendor/github.com/docker/distribution/registry/api/v2/urls.go
new file mode 100644
index 0000000..e2e242e
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/api/v2/urls.go
@@ -0,0 +1,314 @@
+package v2
+
+import (
+ "net"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+
+ "github.com/docker/distribution/reference"
+ "github.com/gorilla/mux"
+)
+
+// URLBuilder creates registry API urls from a single base endpoint. It can be
+// used to create urls for use in a registry client or server.
+//
+// All urls will be created from the given base, including the api version.
+// For example, if a root of "/foo/" is provided, urls generated will be fall
+// under "/foo/v2/...". Most application will only provide a schema, host and
+// port, such as "https://localhost:5000/".
+type URLBuilder struct {
+ root *url.URL // url root (ie http://localhost/)
+ router *mux.Router
+ relative bool
+}
+
+// NewURLBuilder creates a URLBuilder with provided root url object.
+func NewURLBuilder(root *url.URL, relative bool) *URLBuilder {
+ return &URLBuilder{
+ root: root,
+ router: Router(),
+ relative: relative,
+ }
+}
+
+// NewURLBuilderFromString workes identically to NewURLBuilder except it takes
+// a string argument for the root, returning an error if it is not a valid
+// url.
+func NewURLBuilderFromString(root string, relative bool) (*URLBuilder, error) {
+ u, err := url.Parse(root)
+ if err != nil {
+ return nil, err
+ }
+
+ return NewURLBuilder(u, relative), nil
+}
+
+// NewURLBuilderFromRequest uses information from an *http.Request to
+// construct the root url.
+func NewURLBuilderFromRequest(r *http.Request, relative bool) *URLBuilder {
+ var scheme string
+
+ forwardedProto := r.Header.Get("X-Forwarded-Proto")
+ // TODO: log the error
+ forwardedHeader, _, _ := parseForwardedHeader(r.Header.Get("Forwarded"))
+
+ switch {
+ case len(forwardedProto) > 0:
+ scheme = forwardedProto
+ case len(forwardedHeader["proto"]) > 0:
+ scheme = forwardedHeader["proto"]
+ case r.TLS != nil:
+ scheme = "https"
+ case len(r.URL.Scheme) > 0:
+ scheme = r.URL.Scheme
+ default:
+ scheme = "http"
+ }
+
+ host := r.Host
+
+ if forwardedHost := r.Header.Get("X-Forwarded-Host"); len(forwardedHost) > 0 {
+ // According to the Apache mod_proxy docs, X-Forwarded-Host can be a
+ // comma-separated list of hosts, to which each proxy appends the
+ // requested host. We want to grab the first from this comma-separated
+ // list.
+ hosts := strings.SplitN(forwardedHost, ",", 2)
+ host = strings.TrimSpace(hosts[0])
+ } else if addr, exists := forwardedHeader["for"]; exists {
+ host = addr
+ } else if h, exists := forwardedHeader["host"]; exists {
+ host = h
+ }
+
+ portLessHost, port := host, ""
+ if !isIPv6Address(portLessHost) {
+ // with go 1.6, this would treat the last part of IPv6 address as a port
+ portLessHost, port, _ = net.SplitHostPort(host)
+ }
+ if forwardedPort := r.Header.Get("X-Forwarded-Port"); len(port) == 0 && len(forwardedPort) > 0 {
+ ports := strings.SplitN(forwardedPort, ",", 2)
+ forwardedPort = strings.TrimSpace(ports[0])
+ if _, err := strconv.ParseInt(forwardedPort, 10, 32); err == nil {
+ port = forwardedPort
+ }
+ }
+
+ if len(portLessHost) > 0 {
+ host = portLessHost
+ }
+ if len(port) > 0 {
+ // remove enclosing brackets of ipv6 address otherwise they will be duplicated
+ if len(host) > 1 && host[0] == '[' && host[len(host)-1] == ']' {
+ host = host[1 : len(host)-1]
+ }
+ // JoinHostPort properly encloses ipv6 addresses in square brackets
+ host = net.JoinHostPort(host, port)
+ } else if isIPv6Address(host) && host[0] != '[' {
+ // ipv6 needs to be enclosed in square brackets in urls
+ host = "[" + host + "]"
+ }
+
+ basePath := routeDescriptorsMap[RouteNameBase].Path
+
+ requestPath := r.URL.Path
+ index := strings.Index(requestPath, basePath)
+
+ u := &url.URL{
+ Scheme: scheme,
+ Host: host,
+ }
+
+ if index > 0 {
+ // N.B. index+1 is important because we want to include the trailing /
+ u.Path = requestPath[0 : index+1]
+ }
+
+ return NewURLBuilder(u, relative)
+}
+
+// BuildBaseURL constructs a base url for the API, typically just "/v2/".
+func (ub *URLBuilder) BuildBaseURL() (string, error) {
+ route := ub.cloneRoute(RouteNameBase)
+
+ baseURL, err := route.URL()
+ if err != nil {
+ return "", err
+ }
+
+ return baseURL.String(), nil
+}
+
+// BuildCatalogURL constructs a url get a catalog of repositories
+func (ub *URLBuilder) BuildCatalogURL(values ...url.Values) (string, error) {
+ route := ub.cloneRoute(RouteNameCatalog)
+
+ catalogURL, err := route.URL()
+ if err != nil {
+ return "", err
+ }
+
+ return appendValuesURL(catalogURL, values...).String(), nil
+}
+
+// BuildTagsURL constructs a url to list the tags in the named repository.
+func (ub *URLBuilder) BuildTagsURL(name reference.Named) (string, error) {
+ route := ub.cloneRoute(RouteNameTags)
+
+ tagsURL, err := route.URL("name", name.Name())
+ if err != nil {
+ return "", err
+ }
+
+ return tagsURL.String(), nil
+}
+
+// BuildManifestURL constructs a url for the manifest identified by name and
+// reference. The argument reference may be either a tag or digest.
+func (ub *URLBuilder) BuildManifestURL(ref reference.Named) (string, error) {
+ route := ub.cloneRoute(RouteNameManifest)
+
+ tagOrDigest := ""
+ switch v := ref.(type) {
+ case reference.Tagged:
+ tagOrDigest = v.Tag()
+ case reference.Digested:
+ tagOrDigest = v.Digest().String()
+ }
+
+ manifestURL, err := route.URL("name", ref.Name(), "reference", tagOrDigest)
+ if err != nil {
+ return "", err
+ }
+
+ return manifestURL.String(), nil
+}
+
+// BuildBlobURL constructs the url for the blob identified by name and dgst.
+func (ub *URLBuilder) BuildBlobURL(ref reference.Canonical) (string, error) {
+ route := ub.cloneRoute(RouteNameBlob)
+
+ layerURL, err := route.URL("name", ref.Name(), "digest", ref.Digest().String())
+ if err != nil {
+ return "", err
+ }
+
+ return layerURL.String(), nil
+}
+
+// BuildBlobUploadURL constructs a url to begin a blob upload in the
+// repository identified by name.
+func (ub *URLBuilder) BuildBlobUploadURL(name reference.Named, values ...url.Values) (string, error) {
+ route := ub.cloneRoute(RouteNameBlobUpload)
+
+ uploadURL, err := route.URL("name", name.Name())
+ if err != nil {
+ return "", err
+ }
+
+ return appendValuesURL(uploadURL, values...).String(), nil
+}
+
+// BuildBlobUploadChunkURL constructs a url for the upload identified by uuid,
+// including any url values. This should generally not be used by clients, as
+// this url is provided by server implementations during the blob upload
+// process.
+func (ub *URLBuilder) BuildBlobUploadChunkURL(name reference.Named, uuid string, values ...url.Values) (string, error) {
+ route := ub.cloneRoute(RouteNameBlobUploadChunk)
+
+ uploadURL, err := route.URL("name", name.Name(), "uuid", uuid)
+ if err != nil {
+ return "", err
+ }
+
+ return appendValuesURL(uploadURL, values...).String(), nil
+}
+
+// clondedRoute returns a clone of the named route from the router. Routes
+// must be cloned to avoid modifying them during url generation.
+func (ub *URLBuilder) cloneRoute(name string) clonedRoute {
+ route := new(mux.Route)
+ root := new(url.URL)
+
+ *route = *ub.router.GetRoute(name) // clone the route
+ *root = *ub.root
+
+ return clonedRoute{Route: route, root: root, relative: ub.relative}
+}
+
+type clonedRoute struct {
+ *mux.Route
+ root *url.URL
+ relative bool
+}
+
+func (cr clonedRoute) URL(pairs ...string) (*url.URL, error) {
+ routeURL, err := cr.Route.URL(pairs...)
+ if err != nil {
+ return nil, err
+ }
+
+ if cr.relative {
+ return routeURL, nil
+ }
+
+ if routeURL.Scheme == "" && routeURL.User == nil && routeURL.Host == "" {
+ routeURL.Path = routeURL.Path[1:]
+ }
+
+ url := cr.root.ResolveReference(routeURL)
+ url.Scheme = cr.root.Scheme
+ return url, nil
+}
+
+// appendValuesURL appends the parameters to the url.
+func appendValuesURL(u *url.URL, values ...url.Values) *url.URL {
+ merged := u.Query()
+
+ for _, v := range values {
+ for k, vv := range v {
+ merged[k] = append(merged[k], vv...)
+ }
+ }
+
+ u.RawQuery = merged.Encode()
+ return u
+}
+
+// appendValues appends the parameters to the url. Panics if the string is not
+// a url.
+func appendValues(u string, values ...url.Values) string {
+ up, err := url.Parse(u)
+
+ if err != nil {
+ panic(err) // should never happen
+ }
+
+ return appendValuesURL(up, values...).String()
+}
+
+// isIPv6Address returns true if given string is a valid IPv6 address. No port is allowed. The address may be
+// enclosed in square brackets.
+func isIPv6Address(host string) bool {
+ if len(host) > 1 && host[0] == '[' && host[len(host)-1] == ']' {
+ host = host[1 : len(host)-1]
+ }
+ // The IPv6 scoped addressing zone identifier starts after the last percent sign.
+ if i := strings.LastIndexByte(host, '%'); i > 0 {
+ host = host[:i]
+ }
+ ip := net.ParseIP(host)
+ if ip == nil {
+ return false
+ }
+ if ip.To16() == nil {
+ return false
+ }
+ if ip.To4() == nil {
+ return true
+ }
+ // dot can be present in ipv4-mapped address, it needs to come after a colon though
+ i := strings.IndexAny(host, ":.")
+ return i >= 0 && host[i] == ':'
+}
diff --git a/vendor/github.com/docker/distribution/registry/client/auth/api_version.go b/vendor/github.com/docker/distribution/registry/client/auth/api_version.go
new file mode 100644
index 0000000..7d8f1d9
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/client/auth/api_version.go
@@ -0,0 +1,58 @@
+package auth
+
+import (
+ "net/http"
+ "strings"
+)
+
+// APIVersion represents a version of an API including its
+// type and version number.
+type APIVersion struct {
+ // Type refers to the name of a specific API specification
+ // such as "registry"
+ Type string
+
+ // Version is the version of the API specification implemented,
+ // This may omit the revision number and only include
+ // the major and minor version, such as "2.0"
+ Version string
+}
+
+// String returns the string formatted API Version
+func (v APIVersion) String() string {
+ return v.Type + "/" + v.Version
+}
+
+// APIVersions gets the API versions out of an HTTP response using the provided
+// version header as the key for the HTTP header.
+func APIVersions(resp *http.Response, versionHeader string) []APIVersion {
+ versions := []APIVersion{}
+ if versionHeader != "" {
+ for _, supportedVersions := range resp.Header[http.CanonicalHeaderKey(versionHeader)] {
+ for _, version := range strings.Fields(supportedVersions) {
+ versions = append(versions, ParseAPIVersion(version))
+ }
+ }
+ }
+ return versions
+}
+
+// ParseAPIVersion parses an API version string into an APIVersion
+// Format (Expected, not enforced):
+// API version string = <API type> '/' <API version>
+// API type = [a-z][a-z0-9]*
+// API version = [0-9]+(\.[0-9]+)?
+// TODO(dmcgowan): Enforce format, add error condition, remove unknown type
+func ParseAPIVersion(versionStr string) APIVersion {
+ idx := strings.IndexRune(versionStr, '/')
+ if idx == -1 {
+ return APIVersion{
+ Type: "unknown",
+ Version: versionStr,
+ }
+ }
+ return APIVersion{
+ Type: strings.ToLower(versionStr[:idx]),
+ Version: versionStr[idx+1:],
+ }
+}
diff --git a/vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go b/vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go
new file mode 100644
index 0000000..2c3ebe1
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go
@@ -0,0 +1,27 @@
+package challenge
+
+import (
+ "net/url"
+ "strings"
+)
+
+// FROM: https://golang.org/src/net/http/http.go
+// Given a string of the form "host", "host:port", or "[ipv6::address]:port",
+// return true if the string includes a port.
+func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") }
+
+// FROM: http://golang.org/src/net/http/transport.go
+var portMap = map[string]string{
+ "http": "80",
+ "https": "443",
+}
+
+// canonicalAddr returns url.Host but always with a ":port" suffix
+// FROM: http://golang.org/src/net/http/transport.go
+func canonicalAddr(url *url.URL) string {
+ addr := url.Host
+ if !hasPort(addr) {
+ return addr + ":" + portMap[url.Scheme]
+ }
+ return addr
+}
diff --git a/vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go b/vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go
new file mode 100644
index 0000000..c9bdfc3
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go
@@ -0,0 +1,237 @@
+package challenge
+
+import (
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+)
+
+// Challenge carries information from a WWW-Authenticate response header.
+// See RFC 2617.
+type Challenge struct {
+ // Scheme is the auth-scheme according to RFC 2617
+ Scheme string
+
+ // Parameters are the auth-params according to RFC 2617
+ Parameters map[string]string
+}
+
+// Manager manages the challenges for endpoints.
+// The challenges are pulled out of HTTP responses. Only
+// responses which expect challenges should be added to
+// the manager, since a non-unauthorized request will be
+// viewed as not requiring challenges.
+type Manager interface {
+ // GetChallenges returns the challenges for the given
+ // endpoint URL.
+ GetChallenges(endpoint url.URL) ([]Challenge, error)
+
+ // AddResponse adds the response to the challenge
+ // manager. The challenges will be parsed out of
+ // the WWW-Authenicate headers and added to the
+ // URL which was produced the response. If the
+ // response was authorized, any challenges for the
+ // endpoint will be cleared.
+ AddResponse(resp *http.Response) error
+}
+
+// NewSimpleManager returns an instance of
+// Manger which only maps endpoints to challenges
+// based on the responses which have been added the
+// manager. The simple manager will make no attempt to
+// perform requests on the endpoints or cache the responses
+// to a backend.
+func NewSimpleManager() Manager {
+ return &simpleManager{
+ Challanges: make(map[string][]Challenge),
+ }
+}
+
+type simpleManager struct {
+ sync.RWMutex
+ Challanges map[string][]Challenge
+}
+
+func normalizeURL(endpoint *url.URL) {
+ endpoint.Host = strings.ToLower(endpoint.Host)
+ endpoint.Host = canonicalAddr(endpoint)
+}
+
+func (m *simpleManager) GetChallenges(endpoint url.URL) ([]Challenge, error) {
+ normalizeURL(&endpoint)
+
+ m.RLock()
+ defer m.RUnlock()
+ challenges := m.Challanges[endpoint.String()]
+ return challenges, nil
+}
+
+func (m *simpleManager) AddResponse(resp *http.Response) error {
+ challenges := ResponseChallenges(resp)
+ if resp.Request == nil {
+ return fmt.Errorf("missing request reference")
+ }
+ urlCopy := url.URL{
+ Path: resp.Request.URL.Path,
+ Host: resp.Request.URL.Host,
+ Scheme: resp.Request.URL.Scheme,
+ }
+ normalizeURL(&urlCopy)
+
+ m.Lock()
+ defer m.Unlock()
+ m.Challanges[urlCopy.String()] = challenges
+ return nil
+}
+
+// Octet types from RFC 2616.
+type octetType byte
+
+var octetTypes [256]octetType
+
+const (
+ isToken octetType = 1 << iota
+ isSpace
+)
+
+func init() {
+ // OCTET = <any 8-bit sequence of data>
+ // CHAR = <any US-ASCII character (octets 0 - 127)>
+ // CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
+ // CR = <US-ASCII CR, carriage return (13)>
+ // LF = <US-ASCII LF, linefeed (10)>
+ // SP = <US-ASCII SP, space (32)>
+ // HT = <US-ASCII HT, horizontal-tab (9)>
+ // <"> = <US-ASCII double-quote mark (34)>
+ // CRLF = CR LF
+ // LWS = [CRLF] 1*( SP | HT )
+ // TEXT = <any OCTET except CTLs, but including LWS>
+ // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <">
+ // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT
+ // token = 1*<any CHAR except CTLs or separators>
+ // qdtext = <any TEXT except <">>
+
+ for c := 0; c < 256; c++ {
+ var t octetType
+ isCtl := c <= 31 || c == 127
+ isChar := 0 <= c && c <= 127
+ isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0
+ if strings.IndexRune(" \t\r\n", rune(c)) >= 0 {
+ t |= isSpace
+ }
+ if isChar && !isCtl && !isSeparator {
+ t |= isToken
+ }
+ octetTypes[c] = t
+ }
+}
+
+// ResponseChallenges returns a list of authorization challenges
+// for the given http Response. Challenges are only checked if
+// the response status code was a 401.
+func ResponseChallenges(resp *http.Response) []Challenge {
+ if resp.StatusCode == http.StatusUnauthorized {
+ // Parse the WWW-Authenticate Header and store the challenges
+ // on this endpoint object.
+ return parseAuthHeader(resp.Header)
+ }
+
+ return nil
+}
+
+func parseAuthHeader(header http.Header) []Challenge {
+ challenges := []Challenge{}
+ for _, h := range header[http.CanonicalHeaderKey("WWW-Authenticate")] {
+ v, p := parseValueAndParams(h)
+ if v != "" {
+ challenges = append(challenges, Challenge{Scheme: v, Parameters: p})
+ }
+ }
+ return challenges
+}
+
+func parseValueAndParams(header string) (value string, params map[string]string) {
+ params = make(map[string]string)
+ value, s := expectToken(header)
+ if value == "" {
+ return
+ }
+ value = strings.ToLower(value)
+ s = "," + skipSpace(s)
+ for strings.HasPrefix(s, ",") {
+ var pkey string
+ pkey, s = expectToken(skipSpace(s[1:]))
+ if pkey == "" {
+ return
+ }
+ if !strings.HasPrefix(s, "=") {
+ return
+ }
+ var pvalue string
+ pvalue, s = expectTokenOrQuoted(s[1:])
+ if pvalue == "" {
+ return
+ }
+ pkey = strings.ToLower(pkey)
+ params[pkey] = pvalue
+ s = skipSpace(s)
+ }
+ return
+}
+
+func skipSpace(s string) (rest string) {
+ i := 0
+ for ; i < len(s); i++ {
+ if octetTypes[s[i]]&isSpace == 0 {
+ break
+ }
+ }
+ return s[i:]
+}
+
+func expectToken(s string) (token, rest string) {
+ i := 0
+ for ; i < len(s); i++ {
+ if octetTypes[s[i]]&isToken == 0 {
+ break
+ }
+ }
+ return s[:i], s[i:]
+}
+
+func expectTokenOrQuoted(s string) (value string, rest string) {
+ if !strings.HasPrefix(s, "\"") {
+ return expectToken(s)
+ }
+ s = s[1:]
+ for i := 0; i < len(s); i++ {
+ switch s[i] {
+ case '"':
+ return s[:i], s[i+1:]
+ case '\\':
+ p := make([]byte, len(s)-1)
+ j := copy(p, s[:i])
+ escape := true
+ for i = i + 1; i < len(s); i++ {
+ b := s[i]
+ switch {
+ case escape:
+ escape = false
+ p[j] = b
+ j++
+ case b == '\\':
+ escape = true
+ case b == '"':
+ return string(p[:j]), s[i+1:]
+ default:
+ p[j] = b
+ j++
+ }
+ }
+ return "", ""
+ }
+ }
+ return "", ""
+}
diff --git a/vendor/github.com/docker/distribution/registry/client/auth/session.go b/vendor/github.com/docker/distribution/registry/client/auth/session.go
new file mode 100644
index 0000000..3ca5e8b
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/client/auth/session.go
@@ -0,0 +1,505 @@
+package auth
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/distribution/registry/client"
+ "github.com/docker/distribution/registry/client/auth/challenge"
+ "github.com/docker/distribution/registry/client/transport"
+)
+
+var (
+ // ErrNoBasicAuthCredentials is returned if a request can't be authorized with
+ // basic auth due to lack of credentials.
+ ErrNoBasicAuthCredentials = errors.New("no basic auth credentials")
+
+ // ErrNoToken is returned if a request is successful but the body does not
+ // contain an authorization token.
+ ErrNoToken = errors.New("authorization server did not include a token in the response")
+)
+
+const defaultClientID = "registry-client"
+
+// AuthenticationHandler is an interface for authorizing a request from
+// params from a "WWW-Authenicate" header for a single scheme.
+type AuthenticationHandler interface {
+ // Scheme returns the scheme as expected from the "WWW-Authenicate" header.
+ Scheme() string
+
+ // AuthorizeRequest adds the authorization header to a request (if needed)
+ // using the parameters from "WWW-Authenticate" method. The parameters
+ // values depend on the scheme.
+ AuthorizeRequest(req *http.Request, params map[string]string) error
+}
+
+// CredentialStore is an interface for getting credentials for
+// a given URL
+type CredentialStore interface {
+ // Basic returns basic auth for the given URL
+ Basic(*url.URL) (string, string)
+
+ // RefreshToken returns a refresh token for the
+ // given URL and service
+ RefreshToken(*url.URL, string) string
+
+ // SetRefreshToken sets the refresh token if none
+ // is provided for the given url and service
+ SetRefreshToken(realm *url.URL, service, token string)
+}
+
+// NewAuthorizer creates an authorizer which can handle multiple authentication
+// schemes. The handlers are tried in order, the higher priority authentication
+// methods should be first. The challengeMap holds a list of challenges for
+// a given root API endpoint (for example "https://registry-1.docker.io/v2/").
+func NewAuthorizer(manager challenge.Manager, handlers ...AuthenticationHandler) transport.RequestModifier {
+ return &endpointAuthorizer{
+ challenges: manager,
+ handlers: handlers,
+ }
+}
+
+type endpointAuthorizer struct {
+ challenges challenge.Manager
+ handlers []AuthenticationHandler
+ transport http.RoundTripper
+}
+
+func (ea *endpointAuthorizer) ModifyRequest(req *http.Request) error {
+ pingPath := req.URL.Path
+ if v2Root := strings.Index(req.URL.Path, "/v2/"); v2Root != -1 {
+ pingPath = pingPath[:v2Root+4]
+ } else if v1Root := strings.Index(req.URL.Path, "/v1/"); v1Root != -1 {
+ pingPath = pingPath[:v1Root] + "/v2/"
+ } else {
+ return nil
+ }
+
+ ping := url.URL{
+ Host: req.URL.Host,
+ Scheme: req.URL.Scheme,
+ Path: pingPath,
+ }
+
+ challenges, err := ea.challenges.GetChallenges(ping)
+ if err != nil {
+ return err
+ }
+
+ if len(challenges) > 0 {
+ for _, handler := range ea.handlers {
+ for _, c := range challenges {
+ if c.Scheme != handler.Scheme() {
+ continue
+ }
+ if err := handler.AuthorizeRequest(req, c.Parameters); err != nil {
+ return err
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
+// This is the minimum duration a token can last (in seconds).
+// A token must not live less than 60 seconds because older versions
+// of the Docker client didn't read their expiration from the token
+// response and assumed 60 seconds. So to remain compatible with
+// those implementations, a token must live at least this long.
+const minimumTokenLifetimeSeconds = 60
+
+// Private interface for time used by this package to enable tests to provide their own implementation.
+type clock interface {
+ Now() time.Time
+}
+
+type tokenHandler struct {
+ header http.Header
+ creds CredentialStore
+ transport http.RoundTripper
+ clock clock
+
+ offlineAccess bool
+ forceOAuth bool
+ clientID string
+ scopes []Scope
+
+ tokenLock sync.Mutex
+ tokenCache string
+ tokenExpiration time.Time
+}
+
+// Scope is a type which is serializable to a string
+// using the allow scope grammar.
+type Scope interface {
+ String() string
+}
+
+// RepositoryScope represents a token scope for access
+// to a repository.
+type RepositoryScope struct {
+ Repository string
+ Class string
+ Actions []string
+}
+
+// String returns the string representation of the repository
+// using the scope grammar
+func (rs RepositoryScope) String() string {
+ repoType := "repository"
+ // Keep existing format for image class to maintain backwards compatibility
+ // with authorization servers which do not support the expanded grammar.
+ if rs.Class != "" && rs.Class != "image" {
+ repoType = fmt.Sprintf("%s(%s)", repoType, rs.Class)
+ }
+ return fmt.Sprintf("%s:%s:%s", repoType, rs.Repository, strings.Join(rs.Actions, ","))
+}
+
+// RegistryScope represents a token scope for access
+// to resources in the registry.
+type RegistryScope struct {
+ Name string
+ Actions []string
+}
+
+// String returns the string representation of the user
+// using the scope grammar
+func (rs RegistryScope) String() string {
+ return fmt.Sprintf("registry:%s:%s", rs.Name, strings.Join(rs.Actions, ","))
+}
+
+// TokenHandlerOptions is used to configure a new token handler
+type TokenHandlerOptions struct {
+ Transport http.RoundTripper
+ Credentials CredentialStore
+
+ OfflineAccess bool
+ ForceOAuth bool
+ ClientID string
+ Scopes []Scope
+}
+
+// An implementation of clock for providing real time data.
+type realClock struct{}
+
+// Now implements clock
+func (realClock) Now() time.Time { return time.Now() }
+
+// NewTokenHandler creates a new AuthenicationHandler which supports
+// fetching tokens from a remote token server.
+func NewTokenHandler(transport http.RoundTripper, creds CredentialStore, scope string, actions ...string) AuthenticationHandler {
+ // Create options...
+ return NewTokenHandlerWithOptions(TokenHandlerOptions{
+ Transport: transport,
+ Credentials: creds,
+ Scopes: []Scope{
+ RepositoryScope{
+ Repository: scope,
+ Actions: actions,
+ },
+ },
+ })
+}
+
+// NewTokenHandlerWithOptions creates a new token handler using the provided
+// options structure.
+func NewTokenHandlerWithOptions(options TokenHandlerOptions) AuthenticationHandler {
+ handler := &tokenHandler{
+ transport: options.Transport,
+ creds: options.Credentials,
+ offlineAccess: options.OfflineAccess,
+ forceOAuth: options.ForceOAuth,
+ clientID: options.ClientID,
+ scopes: options.Scopes,
+ clock: realClock{},
+ }
+
+ return handler
+}
+
+func (th *tokenHandler) client() *http.Client {
+ return &http.Client{
+ Transport: th.transport,
+ Timeout: 15 * time.Second,
+ }
+}
+
+func (th *tokenHandler) Scheme() string {
+ return "bearer"
+}
+
+func (th *tokenHandler) AuthorizeRequest(req *http.Request, params map[string]string) error {
+ var additionalScopes []string
+ if fromParam := req.URL.Query().Get("from"); fromParam != "" {
+ additionalScopes = append(additionalScopes, RepositoryScope{
+ Repository: fromParam,
+ Actions: []string{"pull"},
+ }.String())
+ }
+
+ token, err := th.getToken(params, additionalScopes...)
+ if err != nil {
+ return err
+ }
+
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
+
+ return nil
+}
+
+func (th *tokenHandler) getToken(params map[string]string, additionalScopes ...string) (string, error) {
+ th.tokenLock.Lock()
+ defer th.tokenLock.Unlock()
+ scopes := make([]string, 0, len(th.scopes)+len(additionalScopes))
+ for _, scope := range th.scopes {
+ scopes = append(scopes, scope.String())
+ }
+ var addedScopes bool
+ for _, scope := range additionalScopes {
+ scopes = append(scopes, scope)
+ addedScopes = true
+ }
+
+ now := th.clock.Now()
+ if now.After(th.tokenExpiration) || addedScopes {
+ token, expiration, err := th.fetchToken(params, scopes)
+ if err != nil {
+ return "", err
+ }
+
+ // do not update cache for added scope tokens
+ if !addedScopes {
+ th.tokenCache = token
+ th.tokenExpiration = expiration
+ }
+
+ return token, nil
+ }
+
+ return th.tokenCache, nil
+}
+
+type postTokenResponse struct {
+ AccessToken string `json:"access_token"`
+ RefreshToken string `json:"refresh_token"`
+ ExpiresIn int `json:"expires_in"`
+ IssuedAt time.Time `json:"issued_at"`
+ Scope string `json:"scope"`
+}
+
+func (th *tokenHandler) fetchTokenWithOAuth(realm *url.URL, refreshToken, service string, scopes []string) (token string, expiration time.Time, err error) {
+ form := url.Values{}
+ form.Set("scope", strings.Join(scopes, " "))
+ form.Set("service", service)
+
+ clientID := th.clientID
+ if clientID == "" {
+ // Use default client, this is a required field
+ clientID = defaultClientID
+ }
+ form.Set("client_id", clientID)
+
+ if refreshToken != "" {
+ form.Set("grant_type", "refresh_token")
+ form.Set("refresh_token", refreshToken)
+ } else if th.creds != nil {
+ form.Set("grant_type", "password")
+ username, password := th.creds.Basic(realm)
+ form.Set("username", username)
+ form.Set("password", password)
+
+ // attempt to get a refresh token
+ form.Set("access_type", "offline")
+ } else {
+ // refuse to do oauth without a grant type
+ return "", time.Time{}, fmt.Errorf("no supported grant type")
+ }
+
+ resp, err := th.client().PostForm(realm.String(), form)
+ if err != nil {
+ return "", time.Time{}, err
+ }
+ defer resp.Body.Close()
+
+ if !client.SuccessStatus(resp.StatusCode) {
+ err := client.HandleErrorResponse(resp)
+ return "", time.Time{}, err
+ }
+
+ decoder := json.NewDecoder(resp.Body)
+
+ var tr postTokenResponse
+ if err = decoder.Decode(&tr); err != nil {
+ return "", time.Time{}, fmt.Errorf("unable to decode token response: %s", err)
+ }
+
+ if tr.RefreshToken != "" && tr.RefreshToken != refreshToken {
+ th.creds.SetRefreshToken(realm, service, tr.RefreshToken)
+ }
+
+ if tr.ExpiresIn < minimumTokenLifetimeSeconds {
+ // The default/minimum lifetime.
+ tr.ExpiresIn = minimumTokenLifetimeSeconds
+ logrus.Debugf("Increasing token expiration to: %d seconds", tr.ExpiresIn)
+ }
+
+ if tr.IssuedAt.IsZero() {
+ // issued_at is optional in the token response.
+ tr.IssuedAt = th.clock.Now().UTC()
+ }
+
+ return tr.AccessToken, tr.IssuedAt.Add(time.Duration(tr.ExpiresIn) * time.Second), nil
+}
+
+type getTokenResponse struct {
+ Token string `json:"token"`
+ AccessToken string `json:"access_token"`
+ ExpiresIn int `json:"expires_in"`
+ IssuedAt time.Time `json:"issued_at"`
+ RefreshToken string `json:"refresh_token"`
+}
+
+func (th *tokenHandler) fetchTokenWithBasicAuth(realm *url.URL, service string, scopes []string) (token string, expiration time.Time, err error) {
+
+ req, err := http.NewRequest("GET", realm.String(), nil)
+ if err != nil {
+ return "", time.Time{}, err
+ }
+
+ reqParams := req.URL.Query()
+
+ if service != "" {
+ reqParams.Add("service", service)
+ }
+
+ for _, scope := range scopes {
+ reqParams.Add("scope", scope)
+ }
+
+ if th.offlineAccess {
+ reqParams.Add("offline_token", "true")
+ clientID := th.clientID
+ if clientID == "" {
+ clientID = defaultClientID
+ }
+ reqParams.Add("client_id", clientID)
+ }
+
+ if th.creds != nil {
+ username, password := th.creds.Basic(realm)
+ if username != "" && password != "" {
+ reqParams.Add("account", username)
+ req.SetBasicAuth(username, password)
+ }
+ }
+
+ req.URL.RawQuery = reqParams.Encode()
+
+ resp, err := th.client().Do(req)
+ if err != nil {
+ return "", time.Time{}, err
+ }
+ defer resp.Body.Close()
+
+ if !client.SuccessStatus(resp.StatusCode) {
+ err := client.HandleErrorResponse(resp)
+ return "", time.Time{}, err
+ }
+
+ decoder := json.NewDecoder(resp.Body)
+
+ var tr getTokenResponse
+ if err = decoder.Decode(&tr); err != nil {
+ return "", time.Time{}, fmt.Errorf("unable to decode token response: %s", err)
+ }
+
+ if tr.RefreshToken != "" && th.creds != nil {
+ th.creds.SetRefreshToken(realm, service, tr.RefreshToken)
+ }
+
+ // `access_token` is equivalent to `token` and if both are specified
+ // the choice is undefined. Canonicalize `access_token` by sticking
+ // things in `token`.
+ if tr.AccessToken != "" {
+ tr.Token = tr.AccessToken
+ }
+
+ if tr.Token == "" {
+ return "", time.Time{}, ErrNoToken
+ }
+
+ if tr.ExpiresIn < minimumTokenLifetimeSeconds {
+ // The default/minimum lifetime.
+ tr.ExpiresIn = minimumTokenLifetimeSeconds
+ logrus.Debugf("Increasing token expiration to: %d seconds", tr.ExpiresIn)
+ }
+
+ if tr.IssuedAt.IsZero() {
+ // issued_at is optional in the token response.
+ tr.IssuedAt = th.clock.Now().UTC()
+ }
+
+ return tr.Token, tr.IssuedAt.Add(time.Duration(tr.ExpiresIn) * time.Second), nil
+}
+
+func (th *tokenHandler) fetchToken(params map[string]string, scopes []string) (token string, expiration time.Time, err error) {
+ realm, ok := params["realm"]
+ if !ok {
+ return "", time.Time{}, errors.New("no realm specified for token auth challenge")
+ }
+
+ // TODO(dmcgowan): Handle empty scheme and relative realm
+ realmURL, err := url.Parse(realm)
+ if err != nil {
+ return "", time.Time{}, fmt.Errorf("invalid token auth challenge realm: %s", err)
+ }
+
+ service := params["service"]
+
+ var refreshToken string
+
+ if th.creds != nil {
+ refreshToken = th.creds.RefreshToken(realmURL, service)
+ }
+
+ if refreshToken != "" || th.forceOAuth {
+ return th.fetchTokenWithOAuth(realmURL, refreshToken, service, scopes)
+ }
+
+ return th.fetchTokenWithBasicAuth(realmURL, service, scopes)
+}
+
+type basicHandler struct {
+ creds CredentialStore
+}
+
+// NewBasicHandler creaters a new authentiation handler which adds
+// basic authentication credentials to a request.
+func NewBasicHandler(creds CredentialStore) AuthenticationHandler {
+ return &basicHandler{
+ creds: creds,
+ }
+}
+
+func (*basicHandler) Scheme() string {
+ return "basic"
+}
+
+func (bh *basicHandler) AuthorizeRequest(req *http.Request, params map[string]string) error {
+ if bh.creds != nil {
+ username, password := bh.creds.Basic(req.URL)
+ if username != "" && password != "" {
+ req.SetBasicAuth(username, password)
+ return nil
+ }
+ }
+ return ErrNoBasicAuthCredentials
+}
diff --git a/vendor/github.com/docker/distribution/registry/client/blob_writer.go b/vendor/github.com/docker/distribution/registry/client/blob_writer.go
new file mode 100644
index 0000000..e3ffcb0
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/client/blob_writer.go
@@ -0,0 +1,162 @@
+package client
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net/http"
+ "time"
+
+ "github.com/docker/distribution"
+ "github.com/docker/distribution/context"
+)
+
+type httpBlobUpload struct {
+ statter distribution.BlobStatter
+ client *http.Client
+
+ uuid string
+ startedAt time.Time
+
+ location string // always the last value of the location header.
+ offset int64
+ closed bool
+}
+
+func (hbu *httpBlobUpload) Reader() (io.ReadCloser, error) {
+ panic("Not implemented")
+}
+
+func (hbu *httpBlobUpload) handleErrorResponse(resp *http.Response) error {
+ if resp.StatusCode == http.StatusNotFound {
+ return distribution.ErrBlobUploadUnknown
+ }
+ return HandleErrorResponse(resp)
+}
+
+func (hbu *httpBlobUpload) ReadFrom(r io.Reader) (n int64, err error) {
+ req, err := http.NewRequest("PATCH", hbu.location, ioutil.NopCloser(r))
+ if err != nil {
+ return 0, err
+ }
+ defer req.Body.Close()
+
+ resp, err := hbu.client.Do(req)
+ if err != nil {
+ return 0, err
+ }
+
+ if !SuccessStatus(resp.StatusCode) {
+ return 0, hbu.handleErrorResponse(resp)
+ }
+
+ hbu.uuid = resp.Header.Get("Docker-Upload-UUID")
+ hbu.location, err = sanitizeLocation(resp.Header.Get("Location"), hbu.location)
+ if err != nil {
+ return 0, err
+ }
+ rng := resp.Header.Get("Range")
+ var start, end int64
+ if n, err := fmt.Sscanf(rng, "%d-%d", &start, &end); err != nil {
+ return 0, err
+ } else if n != 2 || end < start {
+ return 0, fmt.Errorf("bad range format: %s", rng)
+ }
+
+ return (end - start + 1), nil
+
+}
+
+func (hbu *httpBlobUpload) Write(p []byte) (n int, err error) {
+ req, err := http.NewRequest("PATCH", hbu.location, bytes.NewReader(p))
+ if err != nil {
+ return 0, err
+ }
+ req.Header.Set("Content-Range", fmt.Sprintf("%d-%d", hbu.offset, hbu.offset+int64(len(p)-1)))
+ req.Header.Set("Content-Length", fmt.Sprintf("%d", len(p)))
+ req.Header.Set("Content-Type", "application/octet-stream")
+
+ resp, err := hbu.client.Do(req)
+ if err != nil {
+ return 0, err
+ }
+
+ if !SuccessStatus(resp.StatusCode) {
+ return 0, hbu.handleErrorResponse(resp)
+ }
+
+ hbu.uuid = resp.Header.Get("Docker-Upload-UUID")
+ hbu.location, err = sanitizeLocation(resp.Header.Get("Location"), hbu.location)
+ if err != nil {
+ return 0, err
+ }
+ rng := resp.Header.Get("Range")
+ var start, end int
+ if n, err := fmt.Sscanf(rng, "%d-%d", &start, &end); err != nil {
+ return 0, err
+ } else if n != 2 || end < start {
+ return 0, fmt.Errorf("bad range format: %s", rng)
+ }
+
+ return (end - start + 1), nil
+
+}
+
+func (hbu *httpBlobUpload) Size() int64 {
+ return hbu.offset
+}
+
+func (hbu *httpBlobUpload) ID() string {
+ return hbu.uuid
+}
+
+func (hbu *httpBlobUpload) StartedAt() time.Time {
+ return hbu.startedAt
+}
+
+func (hbu *httpBlobUpload) Commit(ctx context.Context, desc distribution.Descriptor) (distribution.Descriptor, error) {
+ // TODO(dmcgowan): Check if already finished, if so just fetch
+ req, err := http.NewRequest("PUT", hbu.location, nil)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+
+ values := req.URL.Query()
+ values.Set("digest", desc.Digest.String())
+ req.URL.RawQuery = values.Encode()
+
+ resp, err := hbu.client.Do(req)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ defer resp.Body.Close()
+
+ if !SuccessStatus(resp.StatusCode) {
+ return distribution.Descriptor{}, hbu.handleErrorResponse(resp)
+ }
+
+ return hbu.statter.Stat(ctx, desc.Digest)
+}
+
+func (hbu *httpBlobUpload) Cancel(ctx context.Context) error {
+ req, err := http.NewRequest("DELETE", hbu.location, nil)
+ if err != nil {
+ return err
+ }
+ resp, err := hbu.client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode == http.StatusNotFound || SuccessStatus(resp.StatusCode) {
+ return nil
+ }
+ return hbu.handleErrorResponse(resp)
+}
+
+func (hbu *httpBlobUpload) Close() error {
+ hbu.closed = true
+ return nil
+}
diff --git a/vendor/github.com/docker/distribution/registry/client/errors.go b/vendor/github.com/docker/distribution/registry/client/errors.go
new file mode 100644
index 0000000..52d49d5
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/client/errors.go
@@ -0,0 +1,139 @@
+package client
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net/http"
+
+ "github.com/docker/distribution/registry/api/errcode"
+ "github.com/docker/distribution/registry/client/auth/challenge"
+)
+
+// ErrNoErrorsInBody is returned when an HTTP response body parses to an empty
+// errcode.Errors slice.
+var ErrNoErrorsInBody = errors.New("no error details found in HTTP response body")
+
+// UnexpectedHTTPStatusError is returned when an unexpected HTTP status is
+// returned when making a registry api call.
+type UnexpectedHTTPStatusError struct {
+ Status string
+}
+
+func (e *UnexpectedHTTPStatusError) Error() string {
+ return fmt.Sprintf("received unexpected HTTP status: %s", e.Status)
+}
+
+// UnexpectedHTTPResponseError is returned when an expected HTTP status code
+// is returned, but the content was unexpected and failed to be parsed.
+type UnexpectedHTTPResponseError struct {
+ ParseErr error
+ StatusCode int
+ Response []byte
+}
+
+func (e *UnexpectedHTTPResponseError) Error() string {
+ return fmt.Sprintf("error parsing HTTP %d response body: %s: %q", e.StatusCode, e.ParseErr.Error(), string(e.Response))
+}
+
+func parseHTTPErrorResponse(statusCode int, r io.Reader) error {
+ var errors errcode.Errors
+ body, err := ioutil.ReadAll(r)
+ if err != nil {
+ return err
+ }
+
+ // For backward compatibility, handle irregularly formatted
+ // messages that contain a "details" field.
+ var detailsErr struct {
+ Details string `json:"details"`
+ }
+ err = json.Unmarshal(body, &detailsErr)
+ if err == nil && detailsErr.Details != "" {
+ switch statusCode {
+ case http.StatusUnauthorized:
+ return errcode.ErrorCodeUnauthorized.WithMessage(detailsErr.Details)
+ case http.StatusTooManyRequests:
+ return errcode.ErrorCodeTooManyRequests.WithMessage(detailsErr.Details)
+ default:
+ return errcode.ErrorCodeUnknown.WithMessage(detailsErr.Details)
+ }
+ }
+
+ if err := json.Unmarshal(body, &errors); err != nil {
+ return &UnexpectedHTTPResponseError{
+ ParseErr: err,
+ StatusCode: statusCode,
+ Response: body,
+ }
+ }
+
+ if len(errors) == 0 {
+ // If there was no error specified in the body, return
+ // UnexpectedHTTPResponseError.
+ return &UnexpectedHTTPResponseError{
+ ParseErr: ErrNoErrorsInBody,
+ StatusCode: statusCode,
+ Response: body,
+ }
+ }
+
+ return errors
+}
+
+func makeErrorList(err error) []error {
+ if errL, ok := err.(errcode.Errors); ok {
+ return []error(errL)
+ }
+ return []error{err}
+}
+
+func mergeErrors(err1, err2 error) error {
+ return errcode.Errors(append(makeErrorList(err1), makeErrorList(err2)...))
+}
+
+// HandleErrorResponse returns error parsed from HTTP response for an
+// unsuccessful HTTP response code (in the range 400 - 499 inclusive). An
+// UnexpectedHTTPStatusError returned for response code outside of expected
+// range.
+func HandleErrorResponse(resp *http.Response) error {
+ if resp.StatusCode >= 400 && resp.StatusCode < 500 {
+ // Check for OAuth errors within the `WWW-Authenticate` header first
+ // See https://tools.ietf.org/html/rfc6750#section-3
+ for _, c := range challenge.ResponseChallenges(resp) {
+ if c.Scheme == "bearer" {
+ var err errcode.Error
+ // codes defined at https://tools.ietf.org/html/rfc6750#section-3.1
+ switch c.Parameters["error"] {
+ case "invalid_token":
+ err.Code = errcode.ErrorCodeUnauthorized
+ case "insufficient_scope":
+ err.Code = errcode.ErrorCodeDenied
+ default:
+ continue
+ }
+ if description := c.Parameters["error_description"]; description != "" {
+ err.Message = description
+ } else {
+ err.Message = err.Code.Message()
+ }
+
+ return mergeErrors(err, parseHTTPErrorResponse(resp.StatusCode, resp.Body))
+ }
+ }
+ err := parseHTTPErrorResponse(resp.StatusCode, resp.Body)
+ if uErr, ok := err.(*UnexpectedHTTPResponseError); ok && resp.StatusCode == 401 {
+ return errcode.ErrorCodeUnauthorized.WithDetail(uErr.Response)
+ }
+ return err
+ }
+ return &UnexpectedHTTPStatusError{Status: resp.Status}
+}
+
+// SuccessStatus returns true if the argument is a successful HTTP response
+// code (in the range 200 - 399 inclusive).
+func SuccessStatus(status int) bool {
+ return status >= 200 && status <= 399
+}
diff --git a/vendor/github.com/docker/distribution/registry/client/repository.go b/vendor/github.com/docker/distribution/registry/client/repository.go
new file mode 100644
index 0000000..b82a968
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/client/repository.go
@@ -0,0 +1,853 @@
+package client
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/docker/distribution"
+ "github.com/docker/distribution/context"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/distribution/registry/api/v2"
+ "github.com/docker/distribution/registry/client/transport"
+ "github.com/docker/distribution/registry/storage/cache"
+ "github.com/docker/distribution/registry/storage/cache/memory"
+ "github.com/opencontainers/go-digest"
+)
+
+// Registry provides an interface for calling Repositories, which returns a catalog of repositories.
+type Registry interface {
+ Repositories(ctx context.Context, repos []string, last string) (n int, err error)
+}
+
+// checkHTTPRedirect is a callback that can manipulate redirected HTTP
+// requests. It is used to preserve Accept and Range headers.
+func checkHTTPRedirect(req *http.Request, via []*http.Request) error {
+ if len(via) >= 10 {
+ return errors.New("stopped after 10 redirects")
+ }
+
+ if len(via) > 0 {
+ for headerName, headerVals := range via[0].Header {
+ if headerName != "Accept" && headerName != "Range" {
+ continue
+ }
+ for _, val := range headerVals {
+ // Don't add to redirected request if redirected
+ // request already has a header with the same
+ // name and value.
+ hasValue := false
+ for _, existingVal := range req.Header[headerName] {
+ if existingVal == val {
+ hasValue = true
+ break
+ }
+ }
+ if !hasValue {
+ req.Header.Add(headerName, val)
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
+// NewRegistry creates a registry namespace which can be used to get a listing of repositories
+func NewRegistry(ctx context.Context, baseURL string, transport http.RoundTripper) (Registry, error) {
+ ub, err := v2.NewURLBuilderFromString(baseURL, false)
+ if err != nil {
+ return nil, err
+ }
+
+ client := &http.Client{
+ Transport: transport,
+ Timeout: 1 * time.Minute,
+ CheckRedirect: checkHTTPRedirect,
+ }
+
+ return &registry{
+ client: client,
+ ub: ub,
+ context: ctx,
+ }, nil
+}
+
+type registry struct {
+ client *http.Client
+ ub *v2.URLBuilder
+ context context.Context
+}
+
+// Repositories returns a lexigraphically sorted catalog given a base URL. The 'entries' slice will be filled up to the size
+// of the slice, starting at the value provided in 'last'. The number of entries will be returned along with io.EOF if there
+// are no more entries
+func (r *registry) Repositories(ctx context.Context, entries []string, last string) (int, error) {
+ var numFilled int
+ var returnErr error
+
+ values := buildCatalogValues(len(entries), last)
+ u, err := r.ub.BuildCatalogURL(values)
+ if err != nil {
+ return 0, err
+ }
+
+ resp, err := r.client.Get(u)
+ if err != nil {
+ return 0, err
+ }
+ defer resp.Body.Close()
+
+ if SuccessStatus(resp.StatusCode) {
+ var ctlg struct {
+ Repositories []string `json:"repositories"`
+ }
+ decoder := json.NewDecoder(resp.Body)
+
+ if err := decoder.Decode(&ctlg); err != nil {
+ return 0, err
+ }
+
+ for cnt := range ctlg.Repositories {
+ entries[cnt] = ctlg.Repositories[cnt]
+ }
+ numFilled = len(ctlg.Repositories)
+
+ link := resp.Header.Get("Link")
+ if link == "" {
+ returnErr = io.EOF
+ }
+ } else {
+ return 0, HandleErrorResponse(resp)
+ }
+
+ return numFilled, returnErr
+}
+
+// NewRepository creates a new Repository for the given repository name and base URL.
+func NewRepository(ctx context.Context, name reference.Named, baseURL string, transport http.RoundTripper) (distribution.Repository, error) {
+ ub, err := v2.NewURLBuilderFromString(baseURL, false)
+ if err != nil {
+ return nil, err
+ }
+
+ client := &http.Client{
+ Transport: transport,
+ CheckRedirect: checkHTTPRedirect,
+ // TODO(dmcgowan): create cookie jar
+ }
+
+ return &repository{
+ client: client,
+ ub: ub,
+ name: name,
+ context: ctx,
+ }, nil
+}
+
+type repository struct {
+ client *http.Client
+ ub *v2.URLBuilder
+ context context.Context
+ name reference.Named
+}
+
+func (r *repository) Named() reference.Named {
+ return r.name
+}
+
+func (r *repository) Blobs(ctx context.Context) distribution.BlobStore {
+ statter := &blobStatter{
+ name: r.name,
+ ub: r.ub,
+ client: r.client,
+ }
+ return &blobs{
+ name: r.name,
+ ub: r.ub,
+ client: r.client,
+ statter: cache.NewCachedBlobStatter(memory.NewInMemoryBlobDescriptorCacheProvider(), statter),
+ }
+}
+
+func (r *repository) Manifests(ctx context.Context, options ...distribution.ManifestServiceOption) (distribution.ManifestService, error) {
+ // todo(richardscothern): options should be sent over the wire
+ return &manifests{
+ name: r.name,
+ ub: r.ub,
+ client: r.client,
+ etags: make(map[string]string),
+ }, nil
+}
+
+func (r *repository) Tags(ctx context.Context) distribution.TagService {
+ return &tags{
+ client: r.client,
+ ub: r.ub,
+ context: r.context,
+ name: r.Named(),
+ }
+}
+
+// tags implements remote tagging operations.
+type tags struct {
+ client *http.Client
+ ub *v2.URLBuilder
+ context context.Context
+ name reference.Named
+}
+
+// All returns all tags
+func (t *tags) All(ctx context.Context) ([]string, error) {
+ var tags []string
+
+ u, err := t.ub.BuildTagsURL(t.name)
+ if err != nil {
+ return tags, err
+ }
+
+ for {
+ resp, err := t.client.Get(u)
+ if err != nil {
+ return tags, err
+ }
+ defer resp.Body.Close()
+
+ if SuccessStatus(resp.StatusCode) {
+ b, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return tags, err
+ }
+
+ tagsResponse := struct {
+ Tags []string `json:"tags"`
+ }{}
+ if err := json.Unmarshal(b, &tagsResponse); err != nil {
+ return tags, err
+ }
+ tags = append(tags, tagsResponse.Tags...)
+ if link := resp.Header.Get("Link"); link != "" {
+ u = strings.Trim(strings.Split(link, ";")[0], "<>")
+ } else {
+ return tags, nil
+ }
+ } else {
+ return tags, HandleErrorResponse(resp)
+ }
+ }
+}
+
+func descriptorFromResponse(response *http.Response) (distribution.Descriptor, error) {
+ desc := distribution.Descriptor{}
+ headers := response.Header
+
+ ctHeader := headers.Get("Content-Type")
+ if ctHeader == "" {
+ return distribution.Descriptor{}, errors.New("missing or empty Content-Type header")
+ }
+ desc.MediaType = ctHeader
+
+ digestHeader := headers.Get("Docker-Content-Digest")
+ if digestHeader == "" {
+ bytes, err := ioutil.ReadAll(response.Body)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ _, desc, err := distribution.UnmarshalManifest(ctHeader, bytes)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ return desc, nil
+ }
+
+ dgst, err := digest.Parse(digestHeader)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ desc.Digest = dgst
+
+ lengthHeader := headers.Get("Content-Length")
+ if lengthHeader == "" {
+ return distribution.Descriptor{}, errors.New("missing or empty Content-Length header")
+ }
+ length, err := strconv.ParseInt(lengthHeader, 10, 64)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ desc.Size = length
+
+ return desc, nil
+
+}
+
+// Get issues a HEAD request for a Manifest against its named endpoint in order
+// to construct a descriptor for the tag. If the registry doesn't support HEADing
+// a manifest, fallback to GET.
+func (t *tags) Get(ctx context.Context, tag string) (distribution.Descriptor, error) {
+ ref, err := reference.WithTag(t.name, tag)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ u, err := t.ub.BuildManifestURL(ref)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+
+ newRequest := func(method string) (*http.Response, error) {
+ req, err := http.NewRequest(method, u, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, t := range distribution.ManifestMediaTypes() {
+ req.Header.Add("Accept", t)
+ }
+ resp, err := t.client.Do(req)
+ return resp, err
+ }
+
+ resp, err := newRequest("HEAD")
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ defer resp.Body.Close()
+
+ switch {
+ case resp.StatusCode >= 200 && resp.StatusCode < 400:
+ return descriptorFromResponse(resp)
+ default:
+ // if the response is an error - there will be no body to decode.
+ // Issue a GET request:
+ // - for data from a server that does not handle HEAD
+ // - to get error details in case of a failure
+ resp, err = newRequest("GET")
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 200 && resp.StatusCode < 400 {
+ return descriptorFromResponse(resp)
+ }
+ return distribution.Descriptor{}, HandleErrorResponse(resp)
+ }
+}
+
+func (t *tags) Lookup(ctx context.Context, digest distribution.Descriptor) ([]string, error) {
+ panic("not implemented")
+}
+
+func (t *tags) Tag(ctx context.Context, tag string, desc distribution.Descriptor) error {
+ panic("not implemented")
+}
+
+func (t *tags) Untag(ctx context.Context, tag string) error {
+ panic("not implemented")
+}
+
+type manifests struct {
+ name reference.Named
+ ub *v2.URLBuilder
+ client *http.Client
+ etags map[string]string
+}
+
+func (ms *manifests) Exists(ctx context.Context, dgst digest.Digest) (bool, error) {
+ ref, err := reference.WithDigest(ms.name, dgst)
+ if err != nil {
+ return false, err
+ }
+ u, err := ms.ub.BuildManifestURL(ref)
+ if err != nil {
+ return false, err
+ }
+
+ resp, err := ms.client.Head(u)
+ if err != nil {
+ return false, err
+ }
+
+ if SuccessStatus(resp.StatusCode) {
+ return true, nil
+ } else if resp.StatusCode == http.StatusNotFound {
+ return false, nil
+ }
+ return false, HandleErrorResponse(resp)
+}
+
+// AddEtagToTag allows a client to supply an eTag to Get which will be
+// used for a conditional HTTP request. If the eTag matches, a nil manifest
+// and ErrManifestNotModified error will be returned. etag is automatically
+// quoted when added to this map.
+func AddEtagToTag(tag, etag string) distribution.ManifestServiceOption {
+ return etagOption{tag, etag}
+}
+
+type etagOption struct{ tag, etag string }
+
+func (o etagOption) Apply(ms distribution.ManifestService) error {
+ if ms, ok := ms.(*manifests); ok {
+ ms.etags[o.tag] = fmt.Sprintf(`"%s"`, o.etag)
+ return nil
+ }
+ return fmt.Errorf("etag options is a client-only option")
+}
+
+// ReturnContentDigest allows a client to set a the content digest on
+// a successful request from the 'Docker-Content-Digest' header. This
+// returned digest is represents the digest which the registry uses
+// to refer to the content and can be used to delete the content.
+func ReturnContentDigest(dgst *digest.Digest) distribution.ManifestServiceOption {
+ return contentDigestOption{dgst}
+}
+
+type contentDigestOption struct{ digest *digest.Digest }
+
+func (o contentDigestOption) Apply(ms distribution.ManifestService) error {
+ return nil
+}
+
+func (ms *manifests) Get(ctx context.Context, dgst digest.Digest, options ...distribution.ManifestServiceOption) (distribution.Manifest, error) {
+ var (
+ digestOrTag string
+ ref reference.Named
+ err error
+ contentDgst *digest.Digest
+ )
+
+ for _, option := range options {
+ if opt, ok := option.(distribution.WithTagOption); ok {
+ digestOrTag = opt.Tag
+ ref, err = reference.WithTag(ms.name, opt.Tag)
+ if err != nil {
+ return nil, err
+ }
+ } else if opt, ok := option.(contentDigestOption); ok {
+ contentDgst = opt.digest
+ } else {
+ err := option.Apply(ms)
+ if err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ if digestOrTag == "" {
+ digestOrTag = dgst.String()
+ ref, err = reference.WithDigest(ms.name, dgst)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ u, err := ms.ub.BuildManifestURL(ref)
+ if err != nil {
+ return nil, err
+ }
+
+ req, err := http.NewRequest("GET", u, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, t := range distribution.ManifestMediaTypes() {
+ req.Header.Add("Accept", t)
+ }
+
+ if _, ok := ms.etags[digestOrTag]; ok {
+ req.Header.Set("If-None-Match", ms.etags[digestOrTag])
+ }
+
+ resp, err := ms.client.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode == http.StatusNotModified {
+ return nil, distribution.ErrManifestNotModified
+ } else if SuccessStatus(resp.StatusCode) {
+ if contentDgst != nil {
+ dgst, err := digest.Parse(resp.Header.Get("Docker-Content-Digest"))
+ if err == nil {
+ *contentDgst = dgst
+ }
+ }
+ mt := resp.Header.Get("Content-Type")
+ body, err := ioutil.ReadAll(resp.Body)
+
+ if err != nil {
+ return nil, err
+ }
+ m, _, err := distribution.UnmarshalManifest(mt, body)
+ if err != nil {
+ return nil, err
+ }
+ return m, nil
+ }
+ return nil, HandleErrorResponse(resp)
+}
+
+// Put puts a manifest. A tag can be specified using an options parameter which uses some shared state to hold the
+// tag name in order to build the correct upload URL.
+func (ms *manifests) Put(ctx context.Context, m distribution.Manifest, options ...distribution.ManifestServiceOption) (digest.Digest, error) {
+ ref := ms.name
+ var tagged bool
+
+ for _, option := range options {
+ if opt, ok := option.(distribution.WithTagOption); ok {
+ var err error
+ ref, err = reference.WithTag(ref, opt.Tag)
+ if err != nil {
+ return "", err
+ }
+ tagged = true
+ } else {
+ err := option.Apply(ms)
+ if err != nil {
+ return "", err
+ }
+ }
+ }
+ mediaType, p, err := m.Payload()
+ if err != nil {
+ return "", err
+ }
+
+ if !tagged {
+ // generate a canonical digest and Put by digest
+ _, d, err := distribution.UnmarshalManifest(mediaType, p)
+ if err != nil {
+ return "", err
+ }
+ ref, err = reference.WithDigest(ref, d.Digest)
+ if err != nil {
+ return "", err
+ }
+ }
+
+ manifestURL, err := ms.ub.BuildManifestURL(ref)
+ if err != nil {
+ return "", err
+ }
+
+ putRequest, err := http.NewRequest("PUT", manifestURL, bytes.NewReader(p))
+ if err != nil {
+ return "", err
+ }
+
+ putRequest.Header.Set("Content-Type", mediaType)
+
+ resp, err := ms.client.Do(putRequest)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+
+ if SuccessStatus(resp.StatusCode) {
+ dgstHeader := resp.Header.Get("Docker-Content-Digest")
+ dgst, err := digest.Parse(dgstHeader)
+ if err != nil {
+ return "", err
+ }
+
+ return dgst, nil
+ }
+
+ return "", HandleErrorResponse(resp)
+}
+
+func (ms *manifests) Delete(ctx context.Context, dgst digest.Digest) error {
+ ref, err := reference.WithDigest(ms.name, dgst)
+ if err != nil {
+ return err
+ }
+ u, err := ms.ub.BuildManifestURL(ref)
+ if err != nil {
+ return err
+ }
+ req, err := http.NewRequest("DELETE", u, nil)
+ if err != nil {
+ return err
+ }
+
+ resp, err := ms.client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if SuccessStatus(resp.StatusCode) {
+ return nil
+ }
+ return HandleErrorResponse(resp)
+}
+
+// todo(richardscothern): Restore interface and implementation with merge of #1050
+/*func (ms *manifests) Enumerate(ctx context.Context, manifests []distribution.Manifest, last distribution.Manifest) (n int, err error) {
+ panic("not supported")
+}*/
+
+type blobs struct {
+ name reference.Named
+ ub *v2.URLBuilder
+ client *http.Client
+
+ statter distribution.BlobDescriptorService
+ distribution.BlobDeleter
+}
+
+func sanitizeLocation(location, base string) (string, error) {
+ baseURL, err := url.Parse(base)
+ if err != nil {
+ return "", err
+ }
+
+ locationURL, err := url.Parse(location)
+ if err != nil {
+ return "", err
+ }
+
+ return baseURL.ResolveReference(locationURL).String(), nil
+}
+
+func (bs *blobs) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
+ return bs.statter.Stat(ctx, dgst)
+
+}
+
+func (bs *blobs) Get(ctx context.Context, dgst digest.Digest) ([]byte, error) {
+ reader, err := bs.Open(ctx, dgst)
+ if err != nil {
+ return nil, err
+ }
+ defer reader.Close()
+
+ return ioutil.ReadAll(reader)
+}
+
+func (bs *blobs) Open(ctx context.Context, dgst digest.Digest) (distribution.ReadSeekCloser, error) {
+ ref, err := reference.WithDigest(bs.name, dgst)
+ if err != nil {
+ return nil, err
+ }
+ blobURL, err := bs.ub.BuildBlobURL(ref)
+ if err != nil {
+ return nil, err
+ }
+
+ return transport.NewHTTPReadSeeker(bs.client, blobURL,
+ func(resp *http.Response) error {
+ if resp.StatusCode == http.StatusNotFound {
+ return distribution.ErrBlobUnknown
+ }
+ return HandleErrorResponse(resp)
+ }), nil
+}
+
+func (bs *blobs) ServeBlob(ctx context.Context, w http.ResponseWriter, r *http.Request, dgst digest.Digest) error {
+ panic("not implemented")
+}
+
+func (bs *blobs) Put(ctx context.Context, mediaType string, p []byte) (distribution.Descriptor, error) {
+ writer, err := bs.Create(ctx)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ dgstr := digest.Canonical.Digester()
+ n, err := io.Copy(writer, io.TeeReader(bytes.NewReader(p), dgstr.Hash()))
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ if n < int64(len(p)) {
+ return distribution.Descriptor{}, fmt.Errorf("short copy: wrote %d of %d", n, len(p))
+ }
+
+ desc := distribution.Descriptor{
+ MediaType: mediaType,
+ Size: int64(len(p)),
+ Digest: dgstr.Digest(),
+ }
+
+ return writer.Commit(ctx, desc)
+}
+
+type optionFunc func(interface{}) error
+
+func (f optionFunc) Apply(v interface{}) error {
+ return f(v)
+}
+
+// WithMountFrom returns a BlobCreateOption which designates that the blob should be
+// mounted from the given canonical reference.
+func WithMountFrom(ref reference.Canonical) distribution.BlobCreateOption {
+ return optionFunc(func(v interface{}) error {
+ opts, ok := v.(*distribution.CreateOptions)
+ if !ok {
+ return fmt.Errorf("unexpected options type: %T", v)
+ }
+
+ opts.Mount.ShouldMount = true
+ opts.Mount.From = ref
+
+ return nil
+ })
+}
+
+func (bs *blobs) Create(ctx context.Context, options ...distribution.BlobCreateOption) (distribution.BlobWriter, error) {
+ var opts distribution.CreateOptions
+
+ for _, option := range options {
+ err := option.Apply(&opts)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ var values []url.Values
+
+ if opts.Mount.ShouldMount {
+ values = append(values, url.Values{"from": {opts.Mount.From.Name()}, "mount": {opts.Mount.From.Digest().String()}})
+ }
+
+ u, err := bs.ub.BuildBlobUploadURL(bs.name, values...)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := bs.client.Post(u, "", nil)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ switch resp.StatusCode {
+ case http.StatusCreated:
+ desc, err := bs.statter.Stat(ctx, opts.Mount.From.Digest())
+ if err != nil {
+ return nil, err
+ }
+ return nil, distribution.ErrBlobMounted{From: opts.Mount.From, Descriptor: desc}
+ case http.StatusAccepted:
+ // TODO(dmcgowan): Check for invalid UUID
+ uuid := resp.Header.Get("Docker-Upload-UUID")
+ location, err := sanitizeLocation(resp.Header.Get("Location"), u)
+ if err != nil {
+ return nil, err
+ }
+
+ return &httpBlobUpload{
+ statter: bs.statter,
+ client: bs.client,
+ uuid: uuid,
+ startedAt: time.Now(),
+ location: location,
+ }, nil
+ default:
+ return nil, HandleErrorResponse(resp)
+ }
+}
+
+func (bs *blobs) Resume(ctx context.Context, id string) (distribution.BlobWriter, error) {
+ panic("not implemented")
+}
+
+func (bs *blobs) Delete(ctx context.Context, dgst digest.Digest) error {
+ return bs.statter.Clear(ctx, dgst)
+}
+
+type blobStatter struct {
+ name reference.Named
+ ub *v2.URLBuilder
+ client *http.Client
+}
+
+func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
+ ref, err := reference.WithDigest(bs.name, dgst)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ u, err := bs.ub.BuildBlobURL(ref)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+
+ resp, err := bs.client.Head(u)
+ if err != nil {
+ return distribution.Descriptor{}, err
+ }
+ defer resp.Body.Close()
+
+ if SuccessStatus(resp.StatusCode) {
+ lengthHeader := resp.Header.Get("Content-Length")
+ if lengthHeader == "" {
+ return distribution.Descriptor{}, fmt.Errorf("missing content-length header for request: %s", u)
+ }
+
+ length, err := strconv.ParseInt(lengthHeader, 10, 64)
+ if err != nil {
+ return distribution.Descriptor{}, fmt.Errorf("error parsing content-length: %v", err)
+ }
+
+ return distribution.Descriptor{
+ MediaType: resp.Header.Get("Content-Type"),
+ Size: length,
+ Digest: dgst,
+ }, nil
+ } else if resp.StatusCode == http.StatusNotFound {
+ return distribution.Descriptor{}, distribution.ErrBlobUnknown
+ }
+ return distribution.Descriptor{}, HandleErrorResponse(resp)
+}
+
+func buildCatalogValues(maxEntries int, last string) url.Values {
+ values := url.Values{}
+
+ if maxEntries > 0 {
+ values.Add("n", strconv.Itoa(maxEntries))
+ }
+
+ if last != "" {
+ values.Add("last", last)
+ }
+
+ return values
+}
+
+func (bs *blobStatter) Clear(ctx context.Context, dgst digest.Digest) error {
+ ref, err := reference.WithDigest(bs.name, dgst)
+ if err != nil {
+ return err
+ }
+ blobURL, err := bs.ub.BuildBlobURL(ref)
+ if err != nil {
+ return err
+ }
+
+ req, err := http.NewRequest("DELETE", blobURL, nil)
+ if err != nil {
+ return err
+ }
+
+ resp, err := bs.client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if SuccessStatus(resp.StatusCode) {
+ return nil
+ }
+ return HandleErrorResponse(resp)
+}
+
+func (bs *blobStatter) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
+ return nil
+}
diff --git a/vendor/github.com/docker/distribution/registry/client/transport/http_reader.go b/vendor/github.com/docker/distribution/registry/client/transport/http_reader.go
new file mode 100644
index 0000000..e5ff09d
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/client/transport/http_reader.go
@@ -0,0 +1,251 @@
+package transport
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "regexp"
+ "strconv"
+)
+
+var (
+ contentRangeRegexp = regexp.MustCompile(`bytes ([0-9]+)-([0-9]+)/([0-9]+|\\*)`)
+
+ // ErrWrongCodeForByteRange is returned if the client sends a request
+ // with a Range header but the server returns a 2xx or 3xx code other
+ // than 206 Partial Content.
+ ErrWrongCodeForByteRange = errors.New("expected HTTP 206 from byte range request")
+)
+
+// ReadSeekCloser combines io.ReadSeeker with io.Closer.
+type ReadSeekCloser interface {
+ io.ReadSeeker
+ io.Closer
+}
+
+// NewHTTPReadSeeker handles reading from an HTTP endpoint using a GET
+// request. When seeking and starting a read from a non-zero offset
+// the a "Range" header will be added which sets the offset.
+// TODO(dmcgowan): Move this into a separate utility package
+func NewHTTPReadSeeker(client *http.Client, url string, errorHandler func(*http.Response) error) ReadSeekCloser {
+ return &httpReadSeeker{
+ client: client,
+ url: url,
+ errorHandler: errorHandler,
+ }
+}
+
+type httpReadSeeker struct {
+ client *http.Client
+ url string
+
+ // errorHandler creates an error from an unsuccessful HTTP response.
+ // This allows the error to be created with the HTTP response body
+ // without leaking the body through a returned error.
+ errorHandler func(*http.Response) error
+
+ size int64
+
+ // rc is the remote read closer.
+ rc io.ReadCloser
+ // readerOffset tracks the offset as of the last read.
+ readerOffset int64
+ // seekOffset allows Seek to override the offset. Seek changes
+ // seekOffset instead of changing readOffset directly so that
+ // connection resets can be delayed and possibly avoided if the
+ // seek is undone (i.e. seeking to the end and then back to the
+ // beginning).
+ seekOffset int64
+ err error
+}
+
+func (hrs *httpReadSeeker) Read(p []byte) (n int, err error) {
+ if hrs.err != nil {
+ return 0, hrs.err
+ }
+
+ // If we sought to a different position, we need to reset the
+ // connection. This logic is here instead of Seek so that if
+ // a seek is undone before the next read, the connection doesn't
+ // need to be closed and reopened. A common example of this is
+ // seeking to the end to determine the length, and then seeking
+ // back to the original position.
+ if hrs.readerOffset != hrs.seekOffset {
+ hrs.reset()
+ }
+
+ hrs.readerOffset = hrs.seekOffset
+
+ rd, err := hrs.reader()
+ if err != nil {
+ return 0, err
+ }
+
+ n, err = rd.Read(p)
+ hrs.seekOffset += int64(n)
+ hrs.readerOffset += int64(n)
+
+ return n, err
+}
+
+func (hrs *httpReadSeeker) Seek(offset int64, whence int) (int64, error) {
+ if hrs.err != nil {
+ return 0, hrs.err
+ }
+
+ lastReaderOffset := hrs.readerOffset
+
+ if whence == os.SEEK_SET && hrs.rc == nil {
+ // If no request has been made yet, and we are seeking to an
+ // absolute position, set the read offset as well to avoid an
+ // unnecessary request.
+ hrs.readerOffset = offset
+ }
+
+ _, err := hrs.reader()
+ if err != nil {
+ hrs.readerOffset = lastReaderOffset
+ return 0, err
+ }
+
+ newOffset := hrs.seekOffset
+
+ switch whence {
+ case os.SEEK_CUR:
+ newOffset += offset
+ case os.SEEK_END:
+ if hrs.size < 0 {
+ return 0, errors.New("content length not known")
+ }
+ newOffset = hrs.size + offset
+ case os.SEEK_SET:
+ newOffset = offset
+ }
+
+ if newOffset < 0 {
+ err = errors.New("cannot seek to negative position")
+ } else {
+ hrs.seekOffset = newOffset
+ }
+
+ return hrs.seekOffset, err
+}
+
+func (hrs *httpReadSeeker) Close() error {
+ if hrs.err != nil {
+ return hrs.err
+ }
+
+ // close and release reader chain
+ if hrs.rc != nil {
+ hrs.rc.Close()
+ }
+
+ hrs.rc = nil
+
+ hrs.err = errors.New("httpLayer: closed")
+
+ return nil
+}
+
+func (hrs *httpReadSeeker) reset() {
+ if hrs.err != nil {
+ return
+ }
+ if hrs.rc != nil {
+ hrs.rc.Close()
+ hrs.rc = nil
+ }
+}
+
+func (hrs *httpReadSeeker) reader() (io.Reader, error) {
+ if hrs.err != nil {
+ return nil, hrs.err
+ }
+
+ if hrs.rc != nil {
+ return hrs.rc, nil
+ }
+
+ req, err := http.NewRequest("GET", hrs.url, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ if hrs.readerOffset > 0 {
+ // If we are at different offset, issue a range request from there.
+ req.Header.Add("Range", fmt.Sprintf("bytes=%d-", hrs.readerOffset))
+ // TODO: get context in here
+ // context.GetLogger(hrs.context).Infof("Range: %s", req.Header.Get("Range"))
+ }
+
+ req.Header.Add("Accept-Encoding", "identity")
+ resp, err := hrs.client.Do(req)
+ if err != nil {
+ return nil, err
+ }
+
+ // Normally would use client.SuccessStatus, but that would be a cyclic
+ // import
+ if resp.StatusCode >= 200 && resp.StatusCode <= 399 {
+ if hrs.readerOffset > 0 {
+ if resp.StatusCode != http.StatusPartialContent {
+ return nil, ErrWrongCodeForByteRange
+ }
+
+ contentRange := resp.Header.Get("Content-Range")
+ if contentRange == "" {
+ return nil, errors.New("no Content-Range header found in HTTP 206 response")
+ }
+
+ submatches := contentRangeRegexp.FindStringSubmatch(contentRange)
+ if len(submatches) < 4 {
+ return nil, fmt.Errorf("could not parse Content-Range header: %s", contentRange)
+ }
+
+ startByte, err := strconv.ParseUint(submatches[1], 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("could not parse start of range in Content-Range header: %s", contentRange)
+ }
+
+ if startByte != uint64(hrs.readerOffset) {
+ return nil, fmt.Errorf("received Content-Range starting at offset %d instead of requested %d", startByte, hrs.readerOffset)
+ }
+
+ endByte, err := strconv.ParseUint(submatches[2], 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("could not parse end of range in Content-Range header: %s", contentRange)
+ }
+
+ if submatches[3] == "*" {
+ hrs.size = -1
+ } else {
+ size, err := strconv.ParseUint(submatches[3], 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("could not parse total size in Content-Range header: %s", contentRange)
+ }
+
+ if endByte+1 != size {
+ return nil, fmt.Errorf("range in Content-Range stops before the end of the content: %s", contentRange)
+ }
+
+ hrs.size = int64(size)
+ }
+ } else if resp.StatusCode == http.StatusOK {
+ hrs.size = resp.ContentLength
+ } else {
+ hrs.size = -1
+ }
+ hrs.rc = resp.Body
+ } else {
+ defer resp.Body.Close()
+ if hrs.errorHandler != nil {
+ return nil, hrs.errorHandler(resp)
+ }
+ return nil, fmt.Errorf("unexpected status resolving reader: %v", resp.Status)
+ }
+
+ return hrs.rc, nil
+}
diff --git a/vendor/github.com/docker/distribution/registry/client/transport/transport.go b/vendor/github.com/docker/distribution/registry/client/transport/transport.go
new file mode 100644
index 0000000..30e45fa
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/client/transport/transport.go
@@ -0,0 +1,147 @@
+package transport
+
+import (
+ "io"
+ "net/http"
+ "sync"
+)
+
+// RequestModifier represents an object which will do an inplace
+// modification of an HTTP request.
+type RequestModifier interface {
+ ModifyRequest(*http.Request) error
+}
+
+type headerModifier http.Header
+
+// NewHeaderRequestModifier returns a new RequestModifier which will
+// add the given headers to a request.
+func NewHeaderRequestModifier(header http.Header) RequestModifier {
+ return headerModifier(header)
+}
+
+func (h headerModifier) ModifyRequest(req *http.Request) error {
+ for k, s := range http.Header(h) {
+ req.Header[k] = append(req.Header[k], s...)
+ }
+
+ return nil
+}
+
+// NewTransport creates a new transport which will apply modifiers to
+// the request on a RoundTrip call.
+func NewTransport(base http.RoundTripper, modifiers ...RequestModifier) http.RoundTripper {
+ return &transport{
+ Modifiers: modifiers,
+ Base: base,
+ }
+}
+
+// transport is an http.RoundTripper that makes HTTP requests after
+// copying and modifying the request
+type transport struct {
+ Modifiers []RequestModifier
+ Base http.RoundTripper
+
+ mu sync.Mutex // guards modReq
+ modReq map[*http.Request]*http.Request // original -> modified
+}
+
+// RoundTrip authorizes and authenticates the request with an
+// access token. If no token exists or token is expired,
+// tries to refresh/fetch a new token.
+func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
+ req2 := cloneRequest(req)
+ for _, modifier := range t.Modifiers {
+ if err := modifier.ModifyRequest(req2); err != nil {
+ return nil, err
+ }
+ }
+
+ t.setModReq(req, req2)
+ res, err := t.base().RoundTrip(req2)
+ if err != nil {
+ t.setModReq(req, nil)
+ return nil, err
+ }
+ res.Body = &onEOFReader{
+ rc: res.Body,
+ fn: func() { t.setModReq(req, nil) },
+ }
+ return res, nil
+}
+
+// CancelRequest cancels an in-flight request by closing its connection.
+func (t *transport) CancelRequest(req *http.Request) {
+ type canceler interface {
+ CancelRequest(*http.Request)
+ }
+ if cr, ok := t.base().(canceler); ok {
+ t.mu.Lock()
+ modReq := t.modReq[req]
+ delete(t.modReq, req)
+ t.mu.Unlock()
+ cr.CancelRequest(modReq)
+ }
+}
+
+func (t *transport) base() http.RoundTripper {
+ if t.Base != nil {
+ return t.Base
+ }
+ return http.DefaultTransport
+}
+
+func (t *transport) setModReq(orig, mod *http.Request) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.modReq == nil {
+ t.modReq = make(map[*http.Request]*http.Request)
+ }
+ if mod == nil {
+ delete(t.modReq, orig)
+ } else {
+ t.modReq[orig] = mod
+ }
+}
+
+// cloneRequest returns a clone of the provided *http.Request.
+// The clone is a shallow copy of the struct and its Header map.
+func cloneRequest(r *http.Request) *http.Request {
+ // shallow copy of the struct
+ r2 := new(http.Request)
+ *r2 = *r
+ // deep copy of the Header
+ r2.Header = make(http.Header, len(r.Header))
+ for k, s := range r.Header {
+ r2.Header[k] = append([]string(nil), s...)
+ }
+
+ return r2
+}
+
+type onEOFReader struct {
+ rc io.ReadCloser
+ fn func()
+}
+
+func (r *onEOFReader) Read(p []byte) (n int, err error) {
+ n, err = r.rc.Read(p)
+ if err == io.EOF {
+ r.runFunc()
+ }
+ return
+}
+
+func (r *onEOFReader) Close() error {
+ err := r.rc.Close()
+ r.runFunc()
+ return err
+}
+
+func (r *onEOFReader) runFunc() {
+ if fn := r.fn; fn != nil {
+ fn()
+ r.fn = nil
+ }
+}
diff --git a/vendor/github.com/docker/distribution/registry/storage/cache/cache.go b/vendor/github.com/docker/distribution/registry/storage/cache/cache.go
new file mode 100644
index 0000000..10a3909
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/storage/cache/cache.go
@@ -0,0 +1,35 @@
+// Package cache provides facilities to speed up access to the storage
+// backend.
+package cache
+
+import (
+ "fmt"
+
+ "github.com/docker/distribution"
+)
+
+// BlobDescriptorCacheProvider provides repository scoped
+// BlobDescriptorService cache instances and a global descriptor cache.
+type BlobDescriptorCacheProvider interface {
+ distribution.BlobDescriptorService
+
+ RepositoryScoped(repo string) (distribution.BlobDescriptorService, error)
+}
+
+// ValidateDescriptor provides a helper function to ensure that caches have
+// common criteria for admitting descriptors.
+func ValidateDescriptor(desc distribution.Descriptor) error {
+ if err := desc.Digest.Validate(); err != nil {
+ return err
+ }
+
+ if desc.Size < 0 {
+ return fmt.Errorf("cache: invalid length in descriptor: %v < 0", desc.Size)
+ }
+
+ if desc.MediaType == "" {
+ return fmt.Errorf("cache: empty mediatype on descriptor: %v", desc)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/distribution/registry/storage/cache/cachedblobdescriptorstore.go b/vendor/github.com/docker/distribution/registry/storage/cache/cachedblobdescriptorstore.go
new file mode 100644
index 0000000..f647616
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/storage/cache/cachedblobdescriptorstore.go
@@ -0,0 +1,101 @@
+package cache
+
+import (
+ "github.com/docker/distribution/context"
+ "github.com/opencontainers/go-digest"
+
+ "github.com/docker/distribution"
+)
+
+// Metrics is used to hold metric counters
+// related to the number of times a cache was
+// hit or missed.
+type Metrics struct {
+ Requests uint64
+ Hits uint64
+ Misses uint64
+}
+
+// MetricsTracker represents a metric tracker
+// which simply counts the number of hits and misses.
+type MetricsTracker interface {
+ Hit()
+ Miss()
+ Metrics() Metrics
+}
+
+type cachedBlobStatter struct {
+ cache distribution.BlobDescriptorService
+ backend distribution.BlobDescriptorService
+ tracker MetricsTracker
+}
+
+// NewCachedBlobStatter creates a new statter which prefers a cache and
+// falls back to a backend.
+func NewCachedBlobStatter(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService) distribution.BlobDescriptorService {
+ return &cachedBlobStatter{
+ cache: cache,
+ backend: backend,
+ }
+}
+
+// NewCachedBlobStatterWithMetrics creates a new statter which prefers a cache and
+// falls back to a backend. Hits and misses will send to the tracker.
+func NewCachedBlobStatterWithMetrics(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService, tracker MetricsTracker) distribution.BlobStatter {
+ return &cachedBlobStatter{
+ cache: cache,
+ backend: backend,
+ tracker: tracker,
+ }
+}
+
+func (cbds *cachedBlobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
+ desc, err := cbds.cache.Stat(ctx, dgst)
+ if err != nil {
+ if err != distribution.ErrBlobUnknown {
+ context.GetLogger(ctx).Errorf("error retrieving descriptor from cache: %v", err)
+ }
+
+ goto fallback
+ }
+
+ if cbds.tracker != nil {
+ cbds.tracker.Hit()
+ }
+ return desc, nil
+fallback:
+ if cbds.tracker != nil {
+ cbds.tracker.Miss()
+ }
+ desc, err = cbds.backend.Stat(ctx, dgst)
+ if err != nil {
+ return desc, err
+ }
+
+ if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil {
+ context.GetLogger(ctx).Errorf("error adding descriptor %v to cache: %v", desc.Digest, err)
+ }
+
+ return desc, err
+
+}
+
+func (cbds *cachedBlobStatter) Clear(ctx context.Context, dgst digest.Digest) error {
+ err := cbds.cache.Clear(ctx, dgst)
+ if err != nil {
+ return err
+ }
+
+ err = cbds.backend.Clear(ctx, dgst)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+func (cbds *cachedBlobStatter) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
+ if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil {
+ context.GetLogger(ctx).Errorf("error adding descriptor %v to cache: %v", desc.Digest, err)
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/distribution/registry/storage/cache/memory/memory.go b/vendor/github.com/docker/distribution/registry/storage/cache/memory/memory.go
new file mode 100644
index 0000000..b2fcaf4
--- /dev/null
+++ b/vendor/github.com/docker/distribution/registry/storage/cache/memory/memory.go
@@ -0,0 +1,179 @@
+package memory
+
+import (
+ "sync"
+
+ "github.com/docker/distribution"
+ "github.com/docker/distribution/context"
+ "github.com/docker/distribution/reference"
+ "github.com/docker/distribution/registry/storage/cache"
+ "github.com/opencontainers/go-digest"
+)
+
+type inMemoryBlobDescriptorCacheProvider struct {
+ global *mapBlobDescriptorCache
+ repositories map[string]*mapBlobDescriptorCache
+ mu sync.RWMutex
+}
+
+// NewInMemoryBlobDescriptorCacheProvider returns a new mapped-based cache for
+// storing blob descriptor data.
+func NewInMemoryBlobDescriptorCacheProvider() cache.BlobDescriptorCacheProvider {
+ return &inMemoryBlobDescriptorCacheProvider{
+ global: newMapBlobDescriptorCache(),
+ repositories: make(map[string]*mapBlobDescriptorCache),
+ }
+}
+
+func (imbdcp *inMemoryBlobDescriptorCacheProvider) RepositoryScoped(repo string) (distribution.BlobDescriptorService, error) {
+ if _, err := reference.ParseNormalizedNamed(repo); err != nil {
+ return nil, err
+ }
+
+ imbdcp.mu.RLock()
+ defer imbdcp.mu.RUnlock()
+
+ return &repositoryScopedInMemoryBlobDescriptorCache{
+ repo: repo,
+ parent: imbdcp,
+ repository: imbdcp.repositories[repo],
+ }, nil
+}
+
+func (imbdcp *inMemoryBlobDescriptorCacheProvider) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
+ return imbdcp.global.Stat(ctx, dgst)
+}
+
+func (imbdcp *inMemoryBlobDescriptorCacheProvider) Clear(ctx context.Context, dgst digest.Digest) error {
+ return imbdcp.global.Clear(ctx, dgst)
+}
+
+func (imbdcp *inMemoryBlobDescriptorCacheProvider) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
+ _, err := imbdcp.Stat(ctx, dgst)
+ if err == distribution.ErrBlobUnknown {
+
+ if dgst.Algorithm() != desc.Digest.Algorithm() && dgst != desc.Digest {
+ // if the digests differ, set the other canonical mapping
+ if err := imbdcp.global.SetDescriptor(ctx, desc.Digest, desc); err != nil {
+ return err
+ }
+ }
+
+ // unknown, just set it
+ return imbdcp.global.SetDescriptor(ctx, dgst, desc)
+ }
+
+ // we already know it, do nothing
+ return err
+}
+
+// repositoryScopedInMemoryBlobDescriptorCache provides the request scoped
+// repository cache. Instances are not thread-safe but the delegated
+// operations are.
+type repositoryScopedInMemoryBlobDescriptorCache struct {
+ repo string
+ parent *inMemoryBlobDescriptorCacheProvider // allows lazy allocation of repo's map
+ repository *mapBlobDescriptorCache
+}
+
+func (rsimbdcp *repositoryScopedInMemoryBlobDescriptorCache) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
+ rsimbdcp.parent.mu.Lock()
+ repo := rsimbdcp.repository
+ rsimbdcp.parent.mu.Unlock()
+
+ if repo == nil {
+ return distribution.Descriptor{}, distribution.ErrBlobUnknown
+ }
+
+ return repo.Stat(ctx, dgst)
+}
+
+func (rsimbdcp *repositoryScopedInMemoryBlobDescriptorCache) Clear(ctx context.Context, dgst digest.Digest) error {
+ rsimbdcp.parent.mu.Lock()
+ repo := rsimbdcp.repository
+ rsimbdcp.parent.mu.Unlock()
+
+ if repo == nil {
+ return distribution.ErrBlobUnknown
+ }
+
+ return repo.Clear(ctx, dgst)
+}
+
+func (rsimbdcp *repositoryScopedInMemoryBlobDescriptorCache) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
+ rsimbdcp.parent.mu.Lock()
+ repo := rsimbdcp.repository
+ if repo == nil {
+ // allocate map since we are setting it now.
+ var ok bool
+ // have to read back value since we may have allocated elsewhere.
+ repo, ok = rsimbdcp.parent.repositories[rsimbdcp.repo]
+ if !ok {
+ repo = newMapBlobDescriptorCache()
+ rsimbdcp.parent.repositories[rsimbdcp.repo] = repo
+ }
+ rsimbdcp.repository = repo
+ }
+ rsimbdcp.parent.mu.Unlock()
+
+ if err := repo.SetDescriptor(ctx, dgst, desc); err != nil {
+ return err
+ }
+
+ return rsimbdcp.parent.SetDescriptor(ctx, dgst, desc)
+}
+
+// mapBlobDescriptorCache provides a simple map-based implementation of the
+// descriptor cache.
+type mapBlobDescriptorCache struct {
+ descriptors map[digest.Digest]distribution.Descriptor
+ mu sync.RWMutex
+}
+
+var _ distribution.BlobDescriptorService = &mapBlobDescriptorCache{}
+
+func newMapBlobDescriptorCache() *mapBlobDescriptorCache {
+ return &mapBlobDescriptorCache{
+ descriptors: make(map[digest.Digest]distribution.Descriptor),
+ }
+}
+
+func (mbdc *mapBlobDescriptorCache) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
+ if err := dgst.Validate(); err != nil {
+ return distribution.Descriptor{}, err
+ }
+
+ mbdc.mu.RLock()
+ defer mbdc.mu.RUnlock()
+
+ desc, ok := mbdc.descriptors[dgst]
+ if !ok {
+ return distribution.Descriptor{}, distribution.ErrBlobUnknown
+ }
+
+ return desc, nil
+}
+
+func (mbdc *mapBlobDescriptorCache) Clear(ctx context.Context, dgst digest.Digest) error {
+ mbdc.mu.Lock()
+ defer mbdc.mu.Unlock()
+
+ delete(mbdc.descriptors, dgst)
+ return nil
+}
+
+func (mbdc *mapBlobDescriptorCache) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error {
+ if err := dgst.Validate(); err != nil {
+ return err
+ }
+
+ if err := cache.ValidateDescriptor(desc); err != nil {
+ return err
+ }
+
+ mbdc.mu.Lock()
+ defer mbdc.mu.Unlock()
+
+ mbdc.descriptors[dgst] = desc
+ return nil
+}
diff --git a/vendor/github.com/docker/distribution/tags.go b/vendor/github.com/docker/distribution/tags.go
new file mode 100644
index 0000000..5030565
--- /dev/null
+++ b/vendor/github.com/docker/distribution/tags.go
@@ -0,0 +1,27 @@
+package distribution
+
+import (
+ "github.com/docker/distribution/context"
+)
+
+// TagService provides access to information about tagged objects.
+type TagService interface {
+ // Get retrieves the descriptor identified by the tag. Some
+ // implementations may differentiate between "trusted" tags and
+ // "untrusted" tags. If a tag is "untrusted", the mapping will be returned
+ // as an ErrTagUntrusted error, with the target descriptor.
+ Get(ctx context.Context, tag string) (Descriptor, error)
+
+ // Tag associates the tag with the provided descriptor, updating the
+ // current association, if needed.
+ Tag(ctx context.Context, tag string, desc Descriptor) error
+
+ // Untag removes the given tag association
+ Untag(ctx context.Context, tag string) error
+
+ // All returns the set of tags managed by this tag service
+ All(ctx context.Context) ([]string, error)
+
+ // Lookup returns the set of tags referencing the given digest.
+ Lookup(ctx context.Context, digest Descriptor) ([]string, error)
+}
diff --git a/vendor/github.com/docker/distribution/uuid/uuid.go b/vendor/github.com/docker/distribution/uuid/uuid.go
new file mode 100644
index 0000000..d433cca
--- /dev/null
+++ b/vendor/github.com/docker/distribution/uuid/uuid.go
@@ -0,0 +1,126 @@
+// Package uuid provides simple UUID generation. Only version 4 style UUIDs
+// can be generated.
+//
+// Please see http://tools.ietf.org/html/rfc4122 for details on UUIDs.
+package uuid
+
+import (
+ "crypto/rand"
+ "fmt"
+ "io"
+ "os"
+ "syscall"
+ "time"
+)
+
+const (
+ // Bits is the number of bits in a UUID
+ Bits = 128
+
+ // Size is the number of bytes in a UUID
+ Size = Bits / 8
+
+ format = "%08x-%04x-%04x-%04x-%012x"
+)
+
+var (
+ // ErrUUIDInvalid indicates a parsed string is not a valid uuid.
+ ErrUUIDInvalid = fmt.Errorf("invalid uuid")
+
+ // Loggerf can be used to override the default logging destination. Such
+ // log messages in this library should be logged at warning or higher.
+ Loggerf = func(format string, args ...interface{}) {}
+)
+
+// UUID represents a UUID value. UUIDs can be compared and set to other values
+// and accessed by byte.
+type UUID [Size]byte
+
+// Generate creates a new, version 4 uuid.
+func Generate() (u UUID) {
+ const (
+ // ensures we backoff for less than 450ms total. Use the following to
+ // select new value, in units of 10ms:
+ // n*(n+1)/2 = d -> n^2 + n - 2d -> n = (sqrt(8d + 1) - 1)/2
+ maxretries = 9
+ backoff = time.Millisecond * 10
+ )
+
+ var (
+ totalBackoff time.Duration
+ count int
+ retries int
+ )
+
+ for {
+ // This should never block but the read may fail. Because of this,
+ // we just try to read the random number generator until we get
+ // something. This is a very rare condition but may happen.
+ b := time.Duration(retries) * backoff
+ time.Sleep(b)
+ totalBackoff += b
+
+ n, err := io.ReadFull(rand.Reader, u[count:])
+ if err != nil {
+ if retryOnError(err) && retries < maxretries {
+ count += n
+ retries++
+ Loggerf("error generating version 4 uuid, retrying: %v", err)
+ continue
+ }
+
+ // Any other errors represent a system problem. What did someone
+ // do to /dev/urandom?
+ panic(fmt.Errorf("error reading random number generator, retried for %v: %v", totalBackoff.String(), err))
+ }
+
+ break
+ }
+
+ u[6] = (u[6] & 0x0f) | 0x40 // set version byte
+ u[8] = (u[8] & 0x3f) | 0x80 // set high order byte 0b10{8,9,a,b}
+
+ return u
+}
+
+// Parse attempts to extract a uuid from the string or returns an error.
+func Parse(s string) (u UUID, err error) {
+ if len(s) != 36 {
+ return UUID{}, ErrUUIDInvalid
+ }
+
+ // create stack addresses for each section of the uuid.
+ p := make([][]byte, 5)
+
+ if _, err := fmt.Sscanf(s, format, &p[0], &p[1], &p[2], &p[3], &p[4]); err != nil {
+ return u, err
+ }
+
+ copy(u[0:4], p[0])
+ copy(u[4:6], p[1])
+ copy(u[6:8], p[2])
+ copy(u[8:10], p[3])
+ copy(u[10:16], p[4])
+
+ return
+}
+
+func (u UUID) String() string {
+ return fmt.Sprintf(format, u[:4], u[4:6], u[6:8], u[8:10], u[10:])
+}
+
+// retryOnError tries to detect whether or not retrying would be fruitful.
+func retryOnError(err error) bool {
+ switch err := err.(type) {
+ case *os.PathError:
+ return retryOnError(err.Err) // unpack the target error
+ case syscall.Errno:
+ if err == syscall.EPERM {
+ // EPERM represents an entropy pool exhaustion, a condition under
+ // which we backoff and retry.
+ return true
+ }
+ }
+
+ return false
+}
diff --git a/vendor/github.com/docker/distribution/vendor.conf b/vendor/github.com/docker/distribution/vendor.conf
new file mode 100644
index 0000000..443b4bc
--- /dev/null
+++ b/vendor/github.com/docker/distribution/vendor.conf
@@ -0,0 +1,41 @@
+github.com/Azure/azure-sdk-for-go c6f0533defaaaa26ea4dff3c9774e36033088112
+github.com/Sirupsen/logrus d26492970760ca5d33129d2d799e34be5c4782eb
+github.com/aws/aws-sdk-go c6fc52983ea2375810aa38ddb5370e9cdf611716
+github.com/bshuster-repo/logrus-logstash-hook 5f729f2fb50a301153cae84ff5c58981d51c095a
+github.com/bugsnag/bugsnag-go b1d153021fcd90ca3f080db36bec96dc690fb274
+github.com/bugsnag/osext 0dd3f918b21bec95ace9dc86c7e70266cfc5c702
+github.com/bugsnag/panicwrap e2c28503fcd0675329da73bf48b33404db873782
+github.com/denverdino/aliyungo afedced274aa9a7fcdd47ac97018f0f8db4e5de2
+github.com/docker/goamz f0a21f5b2e12f83a505ecf79b633bb2035cf6f85
+github.com/docker/libtrust fa567046d9b14f6aa788882a950d69651d230b21
+github.com/garyburd/redigo 535138d7bcd717d6531c701ef5933d98b1866257
+github.com/go-ini/ini 2ba15ac2dc9cdf88c110ec2dc0ced7fa45f5678c
+github.com/golang/protobuf/proto 8d92cf5fc15a4382f8964b08e1f42a75c0591aa3
+github.com/gorilla/context 14f550f51af52180c2eefed15e5fd18d63c0a64a
+github.com/gorilla/handlers 60c7bfde3e33c201519a200a4507a158cc03a17b
+github.com/gorilla/mux e444e69cbd2e2e3e0749a2f3c717cec491552bbf
+github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75
+github.com/jmespath/go-jmespath bd40a432e4c76585ef6b72d3fd96fb9b6dc7b68d
+github.com/miekg/dns 271c58e0c14f552178ea321a545ff9af38930f39
+github.com/mitchellh/mapstructure 482a9fd5fa83e8c4e7817413b80f3eb8feec03ef
+github.com/ncw/swift b964f2ca856aac39885e258ad25aec08d5f64ee6
+github.com/spf13/cobra 312092086bed4968099259622145a0c9ae280064
+github.com/spf13/pflag 5644820622454e71517561946e3d94b9f9db6842
+github.com/stevvooe/resumable 51ad44105773cafcbe91927f70ac68e1bf78f8b4
+github.com/xenolf/lego/acme a9d8cec0e6563575e5868a005359ac97911b5985
+github.com/yvasiyarov/go-metrics 57bccd1ccd43f94bb17fdd8bf3007059b802f85e
+github.com/yvasiyarov/gorelic a9bba5b9ab508a086f9a12b8c51fab68478e2128
+github.com/yvasiyarov/newrelic_platform_go b21fdbd4370f3717f3bbd2bf41c223bc273068e6
+golang.org/x/crypto c10c31b5e94b6f7a0283272dc2bb27163dcea24b
+golang.org/x/net 4876518f9e71663000c348837735820161a42df7
+golang.org/x/oauth2 045497edb6234273d67dbc25da3f2ddbc4c4cacf
+golang.org/x/time/rate a4bde12657593d5e90d0533a3e4fd95e635124cb
+google.golang.org/api 9bf6e6e569ff057f75d9604a46c52928f17d2b54
+google.golang.org/appengine 12d5545dc1cfa6047a286d5e853841b6471f4c19
+google.golang.org/cloud 975617b05ea8a58727e6c1a06b6161ff4185a9f2
+google.golang.org/grpc d3ddb4469d5a1b949fc7a7da7c1d6a0d1b6de994
+gopkg.in/check.v1 64131543e7896d5bcc6bd5a76287eb75ea96c673
+gopkg.in/square/go-jose.v1 40d457b439244b546f023d056628e5184136899b
+gopkg.in/yaml.v2 bef53efd0c76e49e6de55ead051f886bea7e9420
+rsc.io/letsencrypt e770c10b0f1a64775ae91d240407ce00d1a5bdeb https://github.com/dmcgowan/letsencrypt.git
+github.com/opencontainers/go-digest a6d0ee40d4207ea02364bd3b9e8e77b9159ba1eb
diff --git a/vendor/github.com/docker/docker-credential-helpers/LICENSE b/vendor/github.com/docker/docker-credential-helpers/LICENSE
new file mode 100644
index 0000000..1ea555e
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2016 David Calavera
+
+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/docker/docker-credential-helpers/README.md b/vendor/github.com/docker/docker-credential-helpers/README.md
new file mode 100644
index 0000000..e795f7c
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/README.md
@@ -0,0 +1,76 @@
+## Introduction
+
+docker-credential-helpers is a suite of programs to use native stores to keep Docker credentials safe.
+
+## Installation
+
+Go to the [Releases](https://github.com/docker/docker-credential-helpers/releases) page and download the binary that works better for you. Put that binary in your `$PATH`, so Docker can find it.
+
+### Building from scratch
+
+The programs in this repository are written with the Go programming language. These instructions assume that you have previous knowledge about the language and you have it installed in your machine.
+
+1 - Download the source and put it in your `$GOPATH` with `go get`.
+
+```
+$ go get github.com/docker/docker-credential-helpers
+```
+
+2 - Use `make` to build the program you want. That will leave any executable in the `bin` directory inside the repository.
+
+```
+$ cd $GOPATH/docker/docker-credentials-helpers
+$ make osxkeychain
+```
+
+3 - Put that binary in your `$PATH`, so Docker can find it.
+
+## Usage
+
+### With the Docker Engine
+
+Set the `credsStore` option in your `.docker/config.json` file with the suffix of the program you want to use. For instance, set it to `osxkeychain` if you want to use `docker-credential-osxkeychain`.
+
+```json
+{
+ "credsStore": "osxkeychain"
+}
+```
+
+### With other command line applications
+
+The sub-package [client](https://godoc.org/github.com/docker/docker-credential-helpers/client) includes
+functions to call external programs from your own command line applications.
+
+There are three things you need to know if you need to interact with a helper:
+
+1. The name of the program to execute, for instance `docker-credential-osxkeychain`.
+2. The server address to identify the credentials, for instance `https://example.com`.
+3. The username and secret to store, when you want to store credentials.
+
+You can see examples of each function in the [client](https://godoc.org/github.com/docker/docker-credential-helpers/client) documentation.
+
+### Available programs
+
+1. osxkeychain: Provides a helper to use the OS X keychain as credentials store.
+2. secretservice: Provides a helper to use the D-Bus secret service as credentials store.
+3. wincred: Provides a helper to use Windows credentials manager as store.
+
+## Development
+
+A credential helper can be any program that can read values from the standard input. We use the first argument in the command line to differentiate the kind of command to execute. There are four valid values:
+
+- `store`: Adds credentials to the keychain. The payload in the standard input is a JSON document with `ServerURL`, `Username` and `Secret`.
+- `get`: Retrieves credentials from the keychain. The payload in the standard input is the raw value for the `ServerURL`.
+- `erase`: Removes credentials from the keychain. The payload in the standard input is the raw value for the `ServerURL`.
+- `list`: Lists stored credentials. There is no standard input payload.
+
+This repository also includes libraries to implement new credentials programs in Go. Adding a new helper program is pretty easy. You can see how the OS X keychain helper works in the [osxkeychain](osxkeychain) directory.
+
+1. Implement the interface `credentials.Helper` in `YOUR_PACKAGE/YOUR_PACKAGE_$GOOS.go`
+2. Create a main program in `YOUR_PACKAGE/cmd/main_$GOOS.go`.
+3. Add make tasks to build your program and run tests.
+
+## License
+
+MIT. See [LICENSE](LICENSE) for more information.
diff --git a/vendor/github.com/docker/docker-credential-helpers/client/client.go b/vendor/github.com/docker/docker-credential-helpers/client/client.go
new file mode 100644
index 0000000..d1d0434
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/client/client.go
@@ -0,0 +1,121 @@
+package client
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ "github.com/docker/docker-credential-helpers/credentials"
+)
+
+// isValidCredsMessage checks if 'msg' contains invalid credentials error message.
+// It returns whether the logs are free of invalid credentials errors and the error if it isn't.
+// error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername.
+func isValidCredsMessage(msg string) error {
+ if credentials.IsCredentialsMissingServerURLMessage(msg) {
+ return credentials.NewErrCredentialsMissingServerURL()
+ }
+
+ if credentials.IsCredentialsMissingUsernameMessage(msg) {
+ return credentials.NewErrCredentialsMissingUsername()
+ }
+
+ return nil
+}
+
+// Store uses an external program to save credentials.
+func Store(program ProgramFunc, creds *credentials.Credentials) error {
+ cmd := program("store")
+
+ buffer := new(bytes.Buffer)
+ if err := json.NewEncoder(buffer).Encode(creds); err != nil {
+ return err
+ }
+ cmd.Input(buffer)
+
+ out, err := cmd.Output()
+ if err != nil {
+ t := strings.TrimSpace(string(out))
+
+ if isValidErr := isValidCredsMessage(t); isValidErr != nil {
+ err = isValidErr
+ }
+
+ return fmt.Errorf("error storing credentials - err: %v, out: `%s`", err, t)
+ }
+
+ return nil
+}
+
+// Get executes an external program to get the credentials from a native store.
+func Get(program ProgramFunc, serverURL string) (*credentials.Credentials, error) {
+ cmd := program("get")
+ cmd.Input(strings.NewReader(serverURL))
+
+ out, err := cmd.Output()
+ if err != nil {
+ t := strings.TrimSpace(string(out))
+
+ if credentials.IsErrCredentialsNotFoundMessage(t) {
+ return nil, credentials.NewErrCredentialsNotFound()
+ }
+
+ if isValidErr := isValidCredsMessage(t); isValidErr != nil {
+ err = isValidErr
+ }
+
+ return nil, fmt.Errorf("error getting credentials - err: %v, out: `%s`", err, t)
+ }
+
+ resp := &credentials.Credentials{
+ ServerURL: serverURL,
+ }
+
+ if err := json.NewDecoder(bytes.NewReader(out)).Decode(resp); err != nil {
+ return nil, err
+ }
+
+ return resp, nil
+}
+
+// Erase executes a program to remove the server credentials from the native store.
+func Erase(program ProgramFunc, serverURL string) error {
+ cmd := program("erase")
+ cmd.Input(strings.NewReader(serverURL))
+ out, err := cmd.Output()
+ if err != nil {
+ t := strings.TrimSpace(string(out))
+
+ if isValidErr := isValidCredsMessage(t); isValidErr != nil {
+ err = isValidErr
+ }
+
+ return fmt.Errorf("error erasing credentials - err: %v, out: `%s`", err, t)
+ }
+
+ return nil
+}
+
+// List executes a program to list server credentials in the native store.
+func List(program ProgramFunc) (map[string]string, error) {
+ cmd := program("list")
+ cmd.Input(strings.NewReader("unused"))
+ out, err := cmd.Output()
+ if err != nil {
+ t := strings.TrimSpace(string(out))
+
+ if isValidErr := isValidCredsMessage(t); isValidErr != nil {
+ err = isValidErr
+ }
+
+ return nil, fmt.Errorf("error listing credentials - err: %v, out: `%s`", err, t)
+ }
+
+ var resp map[string]string
+ if err = json.NewDecoder(bytes.NewReader(out)).Decode(&resp); err != nil {
+ return nil, err
+ }
+
+ return resp, nil
+}
diff --git a/vendor/github.com/docker/docker-credential-helpers/client/command.go b/vendor/github.com/docker/docker-credential-helpers/client/command.go
new file mode 100644
index 0000000..a144d5a
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/client/command.go
@@ -0,0 +1,44 @@
+package client
+
+import (
+ "io"
+ "os"
+ "os/exec"
+)
+
+// Program is an interface to execute external programs.
+type Program interface {
+ Output() ([]byte, error)
+ Input(in io.Reader)
+}
+
+// ProgramFunc is a type of function that initializes programs based on arguments.
+type ProgramFunc func(args ...string) Program
+
+// NewShellProgramFunc creates programs that are executed in a Shell.
+func NewShellProgramFunc(name string) ProgramFunc {
+ return func(args ...string) Program {
+ return &Shell{cmd: newCmdRedirectErr(name, args)}
+ }
+}
+
+func newCmdRedirectErr(name string, args []string) *exec.Cmd {
+ newCmd := exec.Command(name, args...)
+ newCmd.Stderr = os.Stderr
+ return newCmd
+}
+
+// Shell invokes shell commands to talk with a remote credentials helper.
+type Shell struct {
+ cmd *exec.Cmd
+}
+
+// Output returns responses from the remote credentials helper.
+func (s *Shell) Output() ([]byte, error) {
+ return s.cmd.Output()
+}
+
+// Input sets the input to send to a remote credentials helper.
+func (s *Shell) Input(in io.Reader) {
+ s.cmd.Stdin = in
+}
diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go b/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go
new file mode 100644
index 0000000..544ab3c
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go
@@ -0,0 +1,177 @@
+package credentials
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+)
+
+// Credentials holds the information shared between docker and the credentials store.
+type Credentials struct {
+ ServerURL string
+ Username string
+ Secret string
+}
+
+// isValid checks the integrity of Credentials object such that no credentials lack
+// a server URL or a username.
+// It returns whether the credentials are valid and the error if it isn't.
+// error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername
+func (c *Credentials) isValid() (bool, error) {
+ if len(c.ServerURL) == 0 {
+ return false, NewErrCredentialsMissingServerURL()
+ }
+
+ if len(c.Username) == 0 {
+ return false, NewErrCredentialsMissingUsername()
+ }
+
+ return true, nil
+}
+
+// Docker credentials should be labeled as such in credentials stores that allow labelling.
+// That label allows to filter out non-Docker credentials too at lookup/search in macOS keychain,
+// Windows credentials manager and Linux libsecret. Default value is "Docker Credentials"
+var CredsLabel = "Docker Credentials"
+
+func SetCredsLabel(label string) {
+ CredsLabel = label
+}
+
+// Serve initializes the credentials helper and parses the action argument.
+// This function is designed to be called from a command line interface.
+// It uses os.Args[1] as the key for the action.
+// It uses os.Stdin as input and os.Stdout as output.
+// This function terminates the program with os.Exit(1) if there is an error.
+func Serve(helper Helper) {
+ var err error
+ if len(os.Args) != 2 {
+ err = fmt.Errorf("Usage: %s <store|get|erase|list>", os.Args[0])
+ }
+
+ if err == nil {
+ err = HandleCommand(helper, os.Args[1], os.Stdin, os.Stdout)
+ }
+
+ if err != nil {
+ fmt.Fprintf(os.Stdout, "%v\n", err)
+ os.Exit(1)
+ }
+}
+
+// HandleCommand uses a helper and a key to run a credential action.
+func HandleCommand(helper Helper, key string, in io.Reader, out io.Writer) error {
+ switch key {
+ case "store":
+ return Store(helper, in)
+ case "get":
+ return Get(helper, in, out)
+ case "erase":
+ return Erase(helper, in)
+ case "list":
+ return List(helper, out)
+ }
+ return fmt.Errorf("Unknown credential action `%s`", key)
+}
+
+// Store uses a helper and an input reader to save credentials.
+// The reader must contain the JSON serialization of a Credentials struct.
+func Store(helper Helper, reader io.Reader) error {
+ scanner := bufio.NewScanner(reader)
+
+ buffer := new(bytes.Buffer)
+ for scanner.Scan() {
+ buffer.Write(scanner.Bytes())
+ }
+
+ if err := scanner.Err(); err != nil && err != io.EOF {
+ return err
+ }
+
+ var creds Credentials
+ if err := json.NewDecoder(buffer).Decode(&creds); err != nil {
+ return err
+ }
+
+ if ok, err := creds.isValid(); !ok {
+ return err
+ }
+
+ return helper.Add(&creds)
+}
+
+// Get retrieves the credentials for a given server url.
+// The reader must contain the server URL to search.
+// The writer is used to write the JSON serialization of the credentials.
+func Get(helper Helper, reader io.Reader, writer io.Writer) error {
+ scanner := bufio.NewScanner(reader)
+
+ buffer := new(bytes.Buffer)
+ for scanner.Scan() {
+ buffer.Write(scanner.Bytes())
+ }
+
+ if err := scanner.Err(); err != nil && err != io.EOF {
+ return err
+ }
+
+ serverURL := strings.TrimSpace(buffer.String())
+ if len(serverURL) == 0 {
+ return NewErrCredentialsMissingServerURL()
+ }
+
+ username, secret, err := helper.Get(serverURL)
+ if err != nil {
+ return err
+ }
+
+ resp := Credentials{
+ ServerURL: serverURL,
+ Username: username,
+ Secret: secret,
+ }
+
+ buffer.Reset()
+ if err := json.NewEncoder(buffer).Encode(resp); err != nil {
+ return err
+ }
+
+ fmt.Fprint(writer, buffer.String())
+ return nil
+}
+
+// Erase removes credentials from the store.
+// The reader must contain the server URL to remove.
+func Erase(helper Helper, reader io.Reader) error {
+ scanner := bufio.NewScanner(reader)
+
+ buffer := new(bytes.Buffer)
+ for scanner.Scan() {
+ buffer.Write(scanner.Bytes())
+ }
+
+ if err := scanner.Err(); err != nil && err != io.EOF {
+ return err
+ }
+
+ serverURL := strings.TrimSpace(buffer.String())
+ if len(serverURL) == 0 {
+ return NewErrCredentialsMissingServerURL()
+ }
+
+ return helper.Delete(serverURL)
+}
+
+//List returns all the serverURLs of keys in
+//the OS store as a list of strings
+func List(helper Helper, writer io.Writer) error {
+ accts, err := helper.List()
+ if err != nil {
+ return err
+ }
+ return json.NewEncoder(writer).Encode(accts)
+}
diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/error.go b/vendor/github.com/docker/docker-credential-helpers/credentials/error.go
new file mode 100644
index 0000000..588d4a8
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/credentials/error.go
@@ -0,0 +1,105 @@
+package credentials
+
+const (
+ // ErrCredentialsNotFound standardizes the not found error, so every helper returns
+ // the same message and docker can handle it properly.
+ errCredentialsNotFoundMessage = "credentials not found in native keychain"
+
+ // ErrCredentialsMissingServerURL and ErrCredentialsMissingUsername standardize
+ // invalid credentials or credentials management operations
+ errCredentialsMissingServerURLMessage = "no credentials server URL"
+ errCredentialsMissingUsernameMessage = "no credentials username"
+)
+
+// errCredentialsNotFound represents an error
+// raised when credentials are not in the store.
+type errCredentialsNotFound struct{}
+
+// Error returns the standard error message
+// for when the credentials are not in the store.
+func (errCredentialsNotFound) Error() string {
+ return errCredentialsNotFoundMessage
+}
+
+// NewErrCredentialsNotFound creates a new error
+// for when the credentials are not in the store.
+func NewErrCredentialsNotFound() error {
+ return errCredentialsNotFound{}
+}
+
+// IsErrCredentialsNotFound returns true if the error
+// was caused by not having a set of credentials in a store.
+func IsErrCredentialsNotFound(err error) bool {
+ _, ok := err.(errCredentialsNotFound)
+ return ok
+}
+
+// IsErrCredentialsNotFoundMessage returns true if the error
+// was caused by not having a set of credentials in a store.
+//
+// This function helps to check messages returned by an
+// external program via its standard output.
+func IsErrCredentialsNotFoundMessage(err string) bool {
+ return err == errCredentialsNotFoundMessage
+}
+
+
+// errCredentialsMissingServerURL represents an error raised
+// when the credentials object has no server URL or when no
+// server URL is provided to a credentials operation requiring
+// one.
+type errCredentialsMissingServerURL struct{}
+
+func (errCredentialsMissingServerURL) Error() string {
+ return errCredentialsMissingServerURLMessage
+}
+
+// errCredentialsMissingUsername represents an error raised
+// when the credentials object has no username or when no
+// username is provided to a credentials operation requiring
+// one.
+type errCredentialsMissingUsername struct{}
+
+func (errCredentialsMissingUsername) Error() string {
+ return errCredentialsMissingUsernameMessage
+}
+
+
+// NewErrCredentialsMissingServerURL creates a new error for
+// errCredentialsMissingServerURL.
+func NewErrCredentialsMissingServerURL() error {
+ return errCredentialsMissingServerURL{}
+}
+
+// NewErrCredentialsMissingUsername creates a new error for
+// errCredentialsMissingUsername.
+func NewErrCredentialsMissingUsername() error {
+ return errCredentialsMissingUsername{}
+}
+
+
+// IsCredentialsMissingServerURL returns true if the error
+// was an errCredentialsMissingServerURL.
+func IsCredentialsMissingServerURL(err error) bool {
+ _, ok := err.(errCredentialsMissingServerURL)
+ return ok
+}
+
+// IsCredentialsMissingServerURLMessage checks for an
+// errCredentialsMissingServerURL in the error message.
+func IsCredentialsMissingServerURLMessage(err string) bool {
+ return err == errCredentialsMissingServerURLMessage
+}
+
+// IsCredentialsMissingUsername returns true if the error
+// was an errCredentialsMissingUsername.
+func IsCredentialsMissingUsername(err error) bool {
+ _, ok := err.(errCredentialsMissingUsername)
+ return ok
+}
+
+// IsCredentialsMissingUsernameMessage checks for an
+// errCredentialsMissingUsername in the error message.
+func IsCredentialsMissingUsernameMessage(err string) bool {
+ return err == errCredentialsMissingUsernameMessage
+}
diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go b/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go
new file mode 100644
index 0000000..135acd2
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go
@@ -0,0 +1,14 @@
+package credentials
+
+// Helper is the interface a credentials store helper must implement.
+type Helper interface {
+ // Add appends credentials to the store.
+ Add(*Credentials) error
+ // Delete removes credentials from the store.
+ Delete(serverURL string) error
+ // Get retrieves credentials from the store.
+ // It returns username and secret as strings.
+ Get(serverURL string) (string, string, error)
+ // List returns the stored serverURLs and their associated usernames.
+ List() (map[string]string, error)
+}
diff --git a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.c b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.c
new file mode 100644
index 0000000..f84d61e
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.c
@@ -0,0 +1,228 @@
+#include "osxkeychain_darwin.h"
+#include <CoreFoundation/CoreFoundation.h>
+#include <Foundation/NSValue.h>
+#include <stdio.h>
+#include <string.h>
+
+char *get_error(OSStatus status) {
+ char *buf = malloc(128);
+ CFStringRef str = SecCopyErrorMessageString(status, NULL);
+ int success = CFStringGetCString(str, buf, 128, kCFStringEncodingUTF8);
+ if (!success) {
+ strncpy(buf, "Unknown error", 128);
+ }
+ return buf;
+}
+
+char *keychain_add(struct Server *server, char *label, char *username, char *secret) {
+ SecKeychainItemRef item;
+
+ OSStatus status = SecKeychainAddInternetPassword(
+ NULL,
+ strlen(server->host), server->host,
+ 0, NULL,
+ strlen(username), username,
+ strlen(server->path), server->path,
+ server->port,
+ server->proto,
+ kSecAuthenticationTypeDefault,
+ strlen(secret), secret,
+ &item
+ );
+
+ if (status) {
+ return get_error(status);
+ }
+
+ SecKeychainAttribute attribute;
+ SecKeychainAttributeList attrs;
+ attribute.tag = kSecLabelItemAttr;
+ attribute.data = label;
+ attribute.length = strlen(label);
+ attrs.count = 1;
+ attrs.attr = &attribute;
+
+ status = SecKeychainItemModifyContent(item, &attrs, 0, NULL);
+
+ if (status) {
+ return get_error(status);
+ }
+
+ return NULL;
+}
+
+char *keychain_get(struct Server *server, unsigned int *username_l, char **username, unsigned int *secret_l, char **secret) {
+ char *tmp;
+ SecKeychainItemRef item;
+
+ OSStatus status = SecKeychainFindInternetPassword(
+ NULL,
+ strlen(server->host), server->host,
+ 0, NULL,
+ 0, NULL,
+ strlen(server->path), server->path,
+ server->port,
+ server->proto,
+ kSecAuthenticationTypeDefault,
+ secret_l, (void **)&tmp,
+ &item);
+
+ if (status) {
+ return get_error(status);
+ }
+
+ *secret = strdup(tmp);
+ SecKeychainItemFreeContent(NULL, tmp);
+
+ SecKeychainAttributeList list;
+ SecKeychainAttribute attr;
+
+ list.count = 1;
+ list.attr = &attr;
+ attr.tag = kSecAccountItemAttr;
+
+ status = SecKeychainItemCopyContent(item, NULL, &list, NULL, NULL);
+ if (status) {
+ return get_error(status);
+ }
+
+ *username = strdup(attr.data);
+ *username_l = attr.length;
+ SecKeychainItemFreeContent(&list, NULL);
+
+ return NULL;
+}
+
+char *keychain_delete(struct Server *server) {
+ SecKeychainItemRef item;
+
+ OSStatus status = SecKeychainFindInternetPassword(
+ NULL,
+ strlen(server->host), server->host,
+ 0, NULL,
+ 0, NULL,
+ strlen(server->path), server->path,
+ server->port,
+ server->proto,
+ kSecAuthenticationTypeDefault,
+ 0, NULL,
+ &item);
+
+ if (status) {
+ return get_error(status);
+ }
+
+ status = SecKeychainItemDelete(item);
+ if (status) {
+ return get_error(status);
+ }
+ return NULL;
+}
+
+char * CFStringToCharArr(CFStringRef aString) {
+ if (aString == NULL) {
+ return NULL;
+ }
+ CFIndex length = CFStringGetLength(aString);
+ CFIndex maxSize =
+ CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
+ char *buffer = (char *)malloc(maxSize);
+ if (CFStringGetCString(aString, buffer, maxSize,
+ kCFStringEncodingUTF8)) {
+ return buffer;
+ }
+ return NULL;
+}
+
+char *keychain_list(char *credsLabel, char *** paths, char *** accts, unsigned int *list_l) {
+ CFStringRef credsLabelCF = CFStringCreateWithCString(NULL, credsLabel, kCFStringEncodingUTF8);
+ CFMutableDictionaryRef query = CFDictionaryCreateMutable (NULL, 1, NULL, NULL);
+ CFDictionaryAddValue(query, kSecClass, kSecClassInternetPassword);
+ CFDictionaryAddValue(query, kSecReturnAttributes, kCFBooleanTrue);
+ CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitAll);
+ CFDictionaryAddValue(query, kSecAttrLabel, credsLabelCF);
+ //Use this query dictionary
+ CFTypeRef result= NULL;
+ OSStatus status = SecItemCopyMatching(
+ query,
+ &result);
+
+ CFRelease(credsLabelCF);
+
+ //Ran a search and store the results in result
+ if (status) {
+ return get_error(status);
+ }
+ CFIndex numKeys = CFArrayGetCount(result);
+ *paths = (char **) malloc((int)sizeof(char *)*numKeys);
+ *accts = (char **) malloc((int)sizeof(char *)*numKeys);
+ //result is of type CFArray
+ for(CFIndex i=0; i<numKeys; i++) {
+ CFDictionaryRef currKey = CFArrayGetValueAtIndex(result,i);
+
+ CFStringRef protocolTmp = CFDictionaryGetValue(currKey, CFSTR("ptcl"));
+ if (protocolTmp != NULL) {
+ CFStringRef protocolStr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), protocolTmp);
+ if (CFStringCompare(protocolStr, CFSTR("htps"), 0) == kCFCompareEqualTo) {
+ protocolTmp = CFSTR("https://");
+ }
+ else {
+ protocolTmp = CFSTR("http://");
+ }
+ CFRelease(protocolStr);
+ }
+ else {
+ char * path = "0";
+ char * acct = "0";
+ (*paths)[i] = (char *) malloc(sizeof(char)*(strlen(path)));
+ memcpy((*paths)[i], path, sizeof(char)*(strlen(path)));
+ (*accts)[i] = (char *) malloc(sizeof(char)*(strlen(acct)));
+ memcpy((*accts)[i], acct, sizeof(char)*(strlen(acct)));
+ continue;
+ }
+
+ CFMutableStringRef str = CFStringCreateMutableCopy(NULL, 0, protocolTmp);
+ CFStringRef serverTmp = CFDictionaryGetValue(currKey, CFSTR("srvr"));
+ if (serverTmp != NULL) {
+ CFStringAppend(str, serverTmp);
+ }
+
+ CFStringRef pathTmp = CFDictionaryGetValue(currKey, CFSTR("path"));
+ if (pathTmp != NULL) {
+ CFStringAppend(str, pathTmp);
+ }
+
+ const NSNumber * portTmp = CFDictionaryGetValue(currKey, CFSTR("port"));
+ if (portTmp != NULL && portTmp.integerValue != 0) {
+ CFStringRef portStr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), portTmp);
+ CFStringAppend(str, CFSTR(":"));
+ CFStringAppend(str, portStr);
+ CFRelease(portStr);
+ }
+
+ CFStringRef acctTmp = CFDictionaryGetValue(currKey, CFSTR("acct"));
+ if (acctTmp == NULL) {
+ acctTmp = CFSTR("account not defined");
+ }
+
+ char * path = CFStringToCharArr(str);
+ char * acct = CFStringToCharArr(acctTmp);
+
+ //We now have all we need, username and servername. Now export this to .go
+ (*paths)[i] = (char *) malloc(sizeof(char)*(strlen(path)+1));
+ memcpy((*paths)[i], path, sizeof(char)*(strlen(path)+1));
+ (*accts)[i] = (char *) malloc(sizeof(char)*(strlen(acct)+1));
+ memcpy((*accts)[i], acct, sizeof(char)*(strlen(acct)+1));
+
+ CFRelease(str);
+ }
+ *list_l = (int)numKeys;
+ return NULL;
+}
+
+void freeListData(char *** data, unsigned int length) {
+ for(int i=0; i<length; i++) {
+ free((*data)[i]);
+ }
+ free(*data);
+}
diff --git a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.go b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.go
new file mode 100644
index 0000000..a3f5da8
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.go
@@ -0,0 +1,170 @@
+package osxkeychain
+
+/*
+#cgo CFLAGS: -x objective-c -mmacosx-version-min=10.10
+#cgo LDFLAGS: -framework Security -framework Foundation -mmacosx-version-min=10.10
+
+#include "osxkeychain_darwin.h"
+#include <stdlib.h>
+*/
+import "C"
+import (
+ "errors"
+ "net/url"
+ "strconv"
+ "strings"
+ "unsafe"
+
+ "github.com/docker/docker-credential-helpers/credentials"
+)
+
+// errCredentialsNotFound is the specific error message returned by OS X
+// when the credentials are not in the keychain.
+const errCredentialsNotFound = "The specified item could not be found in the keychain."
+
+// Osxkeychain handles secrets using the OS X Keychain as store.
+type Osxkeychain struct{}
+
+// Add adds new credentials to the keychain.
+func (h Osxkeychain) Add(creds *credentials.Credentials) error {
+ h.Delete(creds.ServerURL)
+
+ s, err := splitServer(creds.ServerURL)
+ if err != nil {
+ return err
+ }
+ defer freeServer(s)
+
+ label := C.CString(credentials.CredsLabel)
+ defer C.free(unsafe.Pointer(label))
+ username := C.CString(creds.Username)
+ defer C.free(unsafe.Pointer(username))
+ secret := C.CString(creds.Secret)
+ defer C.free(unsafe.Pointer(secret))
+
+ errMsg := C.keychain_add(s, label, username, secret)
+ if errMsg != nil {
+ defer C.free(unsafe.Pointer(errMsg))
+ return errors.New(C.GoString(errMsg))
+ }
+
+ return nil
+}
+
+// Delete removes credentials from the keychain.
+func (h Osxkeychain) Delete(serverURL string) error {
+ s, err := splitServer(serverURL)
+ if err != nil {
+ return err
+ }
+ defer freeServer(s)
+
+ errMsg := C.keychain_delete(s)
+ if errMsg != nil {
+ defer C.free(unsafe.Pointer(errMsg))
+ return errors.New(C.GoString(errMsg))
+ }
+
+ return nil
+}
+
+// Get returns the username and secret to use for a given registry server URL.
+func (h Osxkeychain) Get(serverURL string) (string, string, error) {
+ s, err := splitServer(serverURL)
+ if err != nil {
+ return "", "", err
+ }
+ defer freeServer(s)
+
+ var usernameLen C.uint
+ var username *C.char
+ var secretLen C.uint
+ var secret *C.char
+ defer C.free(unsafe.Pointer(username))
+ defer C.free(unsafe.Pointer(secret))
+
+ errMsg := C.keychain_get(s, &usernameLen, &username, &secretLen, &secret)
+ if errMsg != nil {
+ defer C.free(unsafe.Pointer(errMsg))
+ goMsg := C.GoString(errMsg)
+ if goMsg == errCredentialsNotFound {
+ return "", "", credentials.NewErrCredentialsNotFound()
+ }
+
+ return "", "", errors.New(goMsg)
+ }
+
+ user := C.GoStringN(username, C.int(usernameLen))
+ pass := C.GoStringN(secret, C.int(secretLen))
+ return user, pass, nil
+}
+
+// List returns the stored URLs and corresponding usernames.
+func (h Osxkeychain) List() (map[string]string, error) {
+ credsLabelC := C.CString(credentials.CredsLabel)
+ defer C.free(unsafe.Pointer(credsLabelC))
+
+ var pathsC **C.char
+ defer C.free(unsafe.Pointer(pathsC))
+ var acctsC **C.char
+ defer C.free(unsafe.Pointer(acctsC))
+ var listLenC C.uint
+ errMsg := C.keychain_list(credsLabelC, &pathsC, &acctsC, &listLenC)
+ if errMsg != nil {
+ defer C.free(unsafe.Pointer(errMsg))
+ goMsg := C.GoString(errMsg)
+ return nil, errors.New(goMsg)
+ }
+
+ defer C.freeListData(&pathsC, listLenC)
+ defer C.freeListData(&acctsC, listLenC)
+
+ var listLen int
+ listLen = int(listLenC)
+ pathTmp := (*[1 << 30]*C.char)(unsafe.Pointer(pathsC))[:listLen:listLen]
+ acctTmp := (*[1 << 30]*C.char)(unsafe.Pointer(acctsC))[:listLen:listLen]
+ //taking the array of c strings into go while ignoring all the stuff irrelevant to credentials-helper
+ resp := make(map[string]string)
+ for i := 0; i < listLen; i++ {
+ if C.GoString(pathTmp[i]) == "0" {
+ continue
+ }
+ resp[C.GoString(pathTmp[i])] = C.GoString(acctTmp[i])
+ }
+ return resp, nil
+}
+
+func splitServer(serverURL string) (*C.struct_Server, error) {
+ u, err := url.Parse(serverURL)
+ if err != nil {
+ return nil, err
+ }
+
+ hostAndPort := strings.Split(u.Host, ":")
+ host := hostAndPort[0]
+ var port int
+ if len(hostAndPort) == 2 {
+ p, err := strconv.Atoi(hostAndPort[1])
+ if err != nil {
+ return nil, err
+ }
+ port = p
+ }
+
+ proto := C.kSecProtocolTypeHTTPS
+ if u.Scheme != "https" {
+ proto = C.kSecProtocolTypeHTTP
+ }
+
+ return &C.struct_Server{
+ proto: C.SecProtocolType(proto),
+ host: C.CString(host),
+ port: C.uint(port),
+ path: C.CString(u.Path),
+ }, nil
+}
+
+func freeServer(s *C.struct_Server) {
+ C.free(unsafe.Pointer(s.host))
+ C.free(unsafe.Pointer(s.path))
+}
diff --git a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.h b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.h
new file mode 100644
index 0000000..c54e7d7
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.h
@@ -0,0 +1,14 @@
+#include <Security/Security.h>
+
+struct Server {
+ SecProtocolType proto;
+ char *host;
+ char *path;
+ unsigned int port;
+};
+
+char *keychain_add(struct Server *server, char *label, char *username, char *secret);
+char *keychain_get(struct Server *server, unsigned int *username_l, char **username, unsigned int *secret_l, char **secret);
+char *keychain_delete(struct Server *server);
+char *keychain_list(char *credsLabel, char *** data, char *** accts, unsigned int *list_l);
+void freeListData(char *** data, unsigned int length); \ No newline at end of file
diff --git a/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.c b/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.c
new file mode 100644
index 0000000..35dea92
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.c
@@ -0,0 +1,162 @@
+#include <string.h>
+#include <stdlib.h>
+#include "secretservice_linux.h"
+
+const SecretSchema *docker_get_schema(void)
+{
+ static const SecretSchema docker_schema = {
+ "io.docker.Credentials", SECRET_SCHEMA_NONE,
+ {
+ { "label", SECRET_SCHEMA_ATTRIBUTE_STRING },
+ { "server", SECRET_SCHEMA_ATTRIBUTE_STRING },
+ { "username", SECRET_SCHEMA_ATTRIBUTE_STRING },
+ { "docker_cli", SECRET_SCHEMA_ATTRIBUTE_STRING },
+ { "NULL", 0 },
+ }
+ };
+ return &docker_schema;
+}
+
+GError *add(char *label, char *server, char *username, char *secret) {
+ GError *err = NULL;
+
+ secret_password_store_sync (DOCKER_SCHEMA, SECRET_COLLECTION_DEFAULT,
+ server, secret, NULL, &err,
+ "label", label,
+ "server", server,
+ "username", username,
+ "docker_cli", "1",
+ NULL);
+ return err;
+}
+
+GError *delete(char *server) {
+ GError *err = NULL;
+
+ secret_password_clear_sync(DOCKER_SCHEMA, NULL, &err,
+ "server", server,
+ "docker_cli", "1",
+ NULL);
+ if (err != NULL)
+ return err;
+ return NULL;
+}
+
+char *get_attribute(const char *attribute, SecretItem *item) {
+ GHashTable *attributes;
+ GHashTableIter iter;
+ gchar *value, *key;
+
+ attributes = secret_item_get_attributes(item);
+ g_hash_table_iter_init(&iter, attributes);
+ while (g_hash_table_iter_next(&iter, (void **)&key, (void **)&value)) {
+ if (strncmp(key, attribute, strlen(key)) == 0)
+ return (char *)value;
+ }
+ g_hash_table_unref(attributes);
+ return NULL;
+}
+
+GError *get(char *server, char **username, char **secret) {
+ GError *err = NULL;
+ GHashTable *attributes;
+ SecretService *service;
+ GList *items, *l;
+ SecretSearchFlags flags = SECRET_SEARCH_LOAD_SECRETS | SECRET_SEARCH_ALL | SECRET_SEARCH_UNLOCK;
+ SecretValue *secretValue;
+ gsize length;
+ gchar *value;
+
+ attributes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
+ g_hash_table_insert(attributes, g_strdup("server"), g_strdup(server));
+ g_hash_table_insert(attributes, g_strdup("docker_cli"), g_strdup("1"));
+
+ service = secret_service_get_sync(SECRET_SERVICE_NONE, NULL, &err);
+ if (err == NULL) {
+ items = secret_service_search_sync(service, DOCKER_SCHEMA, attributes, flags, NULL, &err);
+ if (err == NULL) {
+ for (l = items; l != NULL; l = g_list_next(l)) {
+ value = secret_item_get_schema_name(l->data);
+ if (strncmp(value, "io.docker.Credentials", strlen(value)) != 0) {
+ g_free(value);
+ continue;
+ }
+ g_free(value);
+ secretValue = secret_item_get_secret(l->data);
+ if (secret != NULL) {
+ *secret = strdup(secret_value_get(secretValue, &length));
+ secret_value_unref(secretValue);
+ }
+ *username = get_attribute("username", l->data);
+ }
+ g_list_free_full(items, g_object_unref);
+ }
+ g_object_unref(service);
+ }
+ g_hash_table_unref(attributes);
+ if (err != NULL) {
+ return err;
+ }
+ return NULL;
+}
+
+GError *list(char *ref_label, char *** paths, char *** accts, unsigned int *list_l) {
+ GList *items;
+ GError *err = NULL;
+ SecretService *service;
+ SecretSearchFlags flags = SECRET_SEARCH_LOAD_SECRETS | SECRET_SEARCH_ALL | SECRET_SEARCH_UNLOCK;
+ GHashTable *attributes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
+
+ // List credentials with the right label only
+ g_hash_table_insert(attributes, g_strdup("label"), g_strdup(ref_label));
+
+ service = secret_service_get_sync(SECRET_SERVICE_NONE, NULL, &err);
+ if (err != NULL) {
+ return err;
+ }
+
+ items = secret_service_search_sync(service, NULL, attributes, flags, NULL, &err);
+ int numKeys = g_list_length(items);
+ if (err != NULL) {
+ return err;
+ }
+
+ char **tmp_paths = (char **) calloc(1,(int)sizeof(char *)*numKeys);
+ char **tmp_accts = (char **) calloc(1,(int)sizeof(char *)*numKeys);
+
+ // items now contains our keys from the gnome keyring
+ // we will now put it in our two lists to return it to go
+ GList *current;
+ int listNumber = 0;
+ for(current = items; current!=NULL; current = current->next) {
+ char *pathTmp = secret_item_get_label(current->data);
+ // you cannot have a key without a label in the gnome keyring
+ char *acctTmp = get_attribute("username",current->data);
+ if (acctTmp==NULL) {
+ acctTmp = "account not defined";
+ }
+
+ tmp_paths[listNumber] = (char *) calloc(1, sizeof(char)*(strlen(pathTmp)+1));
+ tmp_accts[listNumber] = (char *) calloc(1, sizeof(char)*(strlen(acctTmp)+1));
+
+ memcpy(tmp_paths[listNumber], pathTmp, sizeof(char)*(strlen(pathTmp)+1));
+ memcpy(tmp_accts[listNumber], acctTmp, sizeof(char)*(strlen(acctTmp)+1));
+
+ listNumber = listNumber + 1;
+ }
+
+ *paths = (char **) realloc(tmp_paths, (int)sizeof(char *)*listNumber);
+ *accts = (char **) realloc(tmp_accts, (int)sizeof(char *)*listNumber);
+
+ *list_l = listNumber;
+
+ return NULL;
+}
+
+void freeListData(char *** data, unsigned int length) {
+ int i;
+ for(i=0; i<length; i++) {
+ free((*data)[i]);
+ }
+ free(*data);
+}
diff --git a/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.go b/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.go
new file mode 100644
index 0000000..ec1c5d3
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.go
@@ -0,0 +1,115 @@
+package secretservice
+
+/*
+#cgo pkg-config: libsecret-1
+
+#include "secretservice_linux.h"
+#include <stdlib.h>
+*/
+import "C"
+import (
+ "errors"
+ "unsafe"
+
+ "github.com/docker/docker-credential-helpers/credentials"
+)
+
+// Secretservice handles secrets using Linux secret-service as a store.
+type Secretservice struct{}
+
+// Add adds new credentials to the keychain.
+func (h Secretservice) Add(creds *credentials.Credentials) error {
+ if creds == nil {
+ return errors.New("missing credentials")
+ }
+ credsLabel := C.CString(credentials.CredsLabel)
+ defer C.free(unsafe.Pointer(credsLabel))
+ server := C.CString(creds.ServerURL)
+ defer C.free(unsafe.Pointer(server))
+ username := C.CString(creds.Username)
+ defer C.free(unsafe.Pointer(username))
+ secret := C.CString(creds.Secret)
+ defer C.free(unsafe.Pointer(secret))
+
+ if err := C.add(credsLabel, server, username, secret); err != nil {
+ defer C.g_error_free(err)
+ errMsg := (*C.char)(unsafe.Pointer(err.message))
+ return errors.New(C.GoString(errMsg))
+ }
+ return nil
+}
+
+// Delete removes credentials from the store.
+func (h Secretservice) Delete(serverURL string) error {
+ if serverURL == "" {
+ return errors.New("missing server url")
+ }
+ server := C.CString(serverURL)
+ defer C.free(unsafe.Pointer(server))
+
+ if err := C.delete(server); err != nil {
+ defer C.g_error_free(err)
+ errMsg := (*C.char)(unsafe.Pointer(err.message))
+ return errors.New(C.GoString(errMsg))
+ }
+ return nil
+}
+
+// Get returns the username and secret to use for a given registry server URL.
+func (h Secretservice) Get(serverURL string) (string, string, error) {
+ if serverURL == "" {
+ return "", "", errors.New("missing server url")
+ }
+ var username *C.char
+ defer C.free(unsafe.Pointer(username))
+ var secret *C.char
+ defer C.free(unsafe.Pointer(secret))
+ server := C.CString(serverURL)
+ defer C.free(unsafe.Pointer(server))
+
+ err := C.get(server, &username, &secret)
+ if err != nil {
+ defer C.g_error_free(err)
+ errMsg := (*C.char)(unsafe.Pointer(err.message))
+ return "", "", errors.New(C.GoString(errMsg))
+ }
+ user := C.GoString(username)
+ pass := C.GoString(secret)
+ if pass == "" {
+ return "", "", credentials.NewErrCredentialsNotFound()
+ }
+ return user, pass, nil
+}
+
+// List returns the stored URLs and corresponding usernames for a given credentials label
+func (h Secretservice) List() (map[string]string, error) {
+ credsLabelC := C.CString(credentials.CredsLabel)
+ defer C.free(unsafe.Pointer(credsLabelC))
+
+ var pathsC **C.char
+ defer C.free(unsafe.Pointer(pathsC))
+ var acctsC **C.char
+ defer C.free(unsafe.Pointer(acctsC))
+ var listLenC C.uint
+ err := C.list(credsLabelC, &pathsC, &acctsC, &listLenC)
+ if err != nil {
+ defer C.free(unsafe.Pointer(err))
+ return nil, errors.New("Error from list function in secretservice_linux.c likely due to error in secretservice library")
+ }
+ defer C.freeListData(&pathsC, listLenC)
+ defer C.freeListData(&acctsC, listLenC)
+
+ resp := make(map[string]string)
+
+ listLen := int(listLenC)
+ if listLen == 0 {
+ return resp, nil
+ }
+ pathTmp := (*[1 << 30]*C.char)(unsafe.Pointer(pathsC))[:listLen:listLen]
+ acctTmp := (*[1 << 30]*C.char)(unsafe.Pointer(acctsC))[:listLen:listLen]
+ for i := 0; i < listLen; i++ {
+ resp[C.GoString(pathTmp[i])] = C.GoString(acctTmp[i])
+ }
+
+ return resp, nil
+}
diff --git a/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.h b/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.h
new file mode 100644
index 0000000..a28179d
--- /dev/null
+++ b/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.h
@@ -0,0 +1,13 @@
+#define SECRET_WITH_UNSTABLE 1
+#define SECRET_API_SUBJECT_TO_CHANGE 1
+#include <libsecret/secret.h>
+
+const SecretSchema *docker_get_schema(void) G_GNUC_CONST;
+
+#define DOCKER_SCHEMA docker_get_schema()
+
+GError *add(char *label, char *server, char *username, char *secret);
+GError *delete(char *server);
+GError *get(char *server, char **username, char **secret);
+GError *list(char *label, char *** paths, char *** accts, unsigned int *list_l);
+void freeListData(char *** data, unsigned int length);
diff --git a/vendor/github.com/docker/go-connections/LICENSE b/vendor/github.com/docker/go-connections/LICENSE
new file mode 100644
index 0000000..b55b37b
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2015 Docker, Inc.
+
+ 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
+
+ https://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/docker/go-connections/README.md b/vendor/github.com/docker/go-connections/README.md
new file mode 100644
index 0000000..d257e44
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/README.md
@@ -0,0 +1,13 @@
+[![GoDoc](https://godoc.org/github.com/docker/go-connections?status.svg)](https://godoc.org/github.com/docker/go-connections)
+
+# Introduction
+
+go-connections provides common package to work with network connections.
+
+## Usage
+
+See the [docs in godoc](https://godoc.org/github.com/docker/go-connections) for examples and documentation.
+
+## License
+
+go-connections is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full license text.
diff --git a/vendor/github.com/docker/go-connections/nat/nat.go b/vendor/github.com/docker/go-connections/nat/nat.go
new file mode 100644
index 0000000..4d5f5ae
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/nat/nat.go
@@ -0,0 +1,242 @@
+// Package nat is a convenience package for manipulation of strings describing network ports.
+package nat
+
+import (
+ "fmt"
+ "net"
+ "strconv"
+ "strings"
+)
+
+const (
+ // portSpecTemplate is the expected format for port specifications
+ portSpecTemplate = "ip:hostPort:containerPort"
+)
+
+// PortBinding represents a binding between a Host IP address and a Host Port
+type PortBinding struct {
+ // HostIP is the host IP Address
+ HostIP string `json:"HostIp"`
+ // HostPort is the host port number
+ HostPort string
+}
+
+// PortMap is a collection of PortBinding indexed by Port
+type PortMap map[Port][]PortBinding
+
+// PortSet is a collection of structs indexed by Port
+type PortSet map[Port]struct{}
+
+// Port is a string containing port number and protocol in the format "80/tcp"
+type Port string
+
+// NewPort creates a new instance of a Port given a protocol and port number or port range
+func NewPort(proto, port string) (Port, error) {
+ // Check for parsing issues on "port" now so we can avoid having
+ // to check it later on.
+
+ portStartInt, portEndInt, err := ParsePortRangeToInt(port)
+ if err != nil {
+ return "", err
+ }
+
+ if portStartInt == portEndInt {
+ return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil
+ }
+ return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil
+}
+
+// ParsePort parses the port number string and returns an int
+func ParsePort(rawPort string) (int, error) {
+ if len(rawPort) == 0 {
+ return 0, nil
+ }
+ port, err := strconv.ParseUint(rawPort, 10, 16)
+ if err != nil {
+ return 0, err
+ }
+ return int(port), nil
+}
+
+// ParsePortRangeToInt parses the port range string and returns start/end ints
+func ParsePortRangeToInt(rawPort string) (int, int, error) {
+ if len(rawPort) == 0 {
+ return 0, 0, nil
+ }
+ start, end, err := ParsePortRange(rawPort)
+ if err != nil {
+ return 0, 0, err
+ }
+ return int(start), int(end), nil
+}
+
+// Proto returns the protocol of a Port
+func (p Port) Proto() string {
+ proto, _ := SplitProtoPort(string(p))
+ return proto
+}
+
+// Port returns the port number of a Port
+func (p Port) Port() string {
+ _, port := SplitProtoPort(string(p))
+ return port
+}
+
+// Int returns the port number of a Port as an int
+func (p Port) Int() int {
+ portStr := p.Port()
+ // We don't need to check for an error because we're going to
+ // assume that any error would have been found, and reported, in NewPort()
+ port, _ := ParsePort(portStr)
+ return port
+}
+
+// Range returns the start/end port numbers of a Port range as ints
+func (p Port) Range() (int, int, error) {
+ return ParsePortRangeToInt(p.Port())
+}
+
+// SplitProtoPort splits a port in the format of proto/port
+func SplitProtoPort(rawPort string) (string, string) {
+ parts := strings.Split(rawPort, "/")
+ l := len(parts)
+ if len(rawPort) == 0 || l == 0 || len(parts[0]) == 0 {
+ return "", ""
+ }
+ if l == 1 {
+ return "tcp", rawPort
+ }
+ if len(parts[1]) == 0 {
+ return "tcp", parts[0]
+ }
+ return parts[1], parts[0]
+}
+
+func validateProto(proto string) bool {
+ for _, availableProto := range []string{"tcp", "udp"} {
+ if availableProto == proto {
+ return true
+ }
+ }
+ return false
+}
+
+// ParsePortSpecs receives port specs in the format of ip:public:private/proto and parses
+// these in to the internal types
+func ParsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, error) {
+ var (
+ exposedPorts = make(map[Port]struct{}, len(ports))
+ bindings = make(map[Port][]PortBinding)
+ )
+ for _, rawPort := range ports {
+ portMappings, err := ParsePortSpec(rawPort)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ for _, portMapping := range portMappings {
+ port := portMapping.Port
+ if _, exists := exposedPorts[port]; !exists {
+ exposedPorts[port] = struct{}{}
+ }
+ bslice, exists := bindings[port]
+ if !exists {
+ bslice = []PortBinding{}
+ }
+ bindings[port] = append(bslice, portMapping.Binding)
+ }
+ }
+ return exposedPorts, bindings, nil
+}
+
+// PortMapping is a data object mapping a Port to a PortBinding
+type PortMapping struct {
+ Port Port
+ Binding PortBinding
+}
+
+func splitParts(rawport string) (string, string, string) {
+ parts := strings.Split(rawport, ":")
+ n := len(parts)
+ containerport := parts[n-1]
+
+ switch n {
+ case 1:
+ return "", "", containerport
+ case 2:
+ return "", parts[0], containerport
+ case 3:
+ return parts[0], parts[1], containerport
+ default:
+ return strings.Join(parts[:n-2], ":"), parts[n-2], containerport
+ }
+}
+
+// ParsePortSpec parses a port specification string into a slice of PortMappings
+func ParsePortSpec(rawPort string) ([]PortMapping, error) {
+ var proto string
+ rawIP, hostPort, containerPort := splitParts(rawPort)
+ proto, containerPort = SplitProtoPort(containerPort)
+
+ // Strip [] from IPV6 addresses
+ ip, _, err := net.SplitHostPort(rawIP + ":")
+ if err != nil {
+ return nil, fmt.Errorf("Invalid ip address %v: %s", rawIP, err)
+ }
+ if ip != "" && net.ParseIP(ip) == nil {
+ return nil, fmt.Errorf("Invalid ip address: %s", ip)
+ }
+ if containerPort == "" {
+ return nil, fmt.Errorf("No port specified: %s<empty>", rawPort)
+ }
+
+ startPort, endPort, err := ParsePortRange(containerPort)
+ if err != nil {
+ return nil, fmt.Errorf("Invalid containerPort: %s", containerPort)
+ }
+
+ var startHostPort, endHostPort uint64 = 0, 0
+ if len(hostPort) > 0 {
+ startHostPort, endHostPort, err = ParsePortRange(hostPort)
+ if err != nil {
+ return nil, fmt.Errorf("Invalid hostPort: %s", hostPort)
+ }
+ }
+
+ if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) {
+ // Allow host port range iff containerPort is not a range.
+ // In this case, use the host port range as the dynamic
+ // host port range to allocate into.
+ if endPort != startPort {
+ return nil, fmt.Errorf("Invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort)
+ }
+ }
+
+ if !validateProto(strings.ToLower(proto)) {
+ return nil, fmt.Errorf("Invalid proto: %s", proto)
+ }
+
+ ports := []PortMapping{}
+ for i := uint64(0); i <= (endPort - startPort); i++ {
+ containerPort = strconv.FormatUint(startPort+i, 10)
+ if len(hostPort) > 0 {
+ hostPort = strconv.FormatUint(startHostPort+i, 10)
+ }
+ // Set hostPort to a range only if there is a single container port
+ // and a dynamic host port.
+ if startPort == endPort && startHostPort != endHostPort {
+ hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10))
+ }
+ port, err := NewPort(strings.ToLower(proto), containerPort)
+ if err != nil {
+ return nil, err
+ }
+
+ binding := PortBinding{
+ HostIP: ip,
+ HostPort: hostPort,
+ }
+ ports = append(ports, PortMapping{Port: port, Binding: binding})
+ }
+ return ports, nil
+}
diff --git a/vendor/github.com/docker/go-connections/nat/parse.go b/vendor/github.com/docker/go-connections/nat/parse.go
new file mode 100644
index 0000000..892adf8
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/nat/parse.go
@@ -0,0 +1,57 @@
+package nat
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// PartParser parses and validates the specified string (data) using the specified template
+// e.g. ip:public:private -> 192.168.0.1:80:8000
+// DEPRECATED: do not use, this function may be removed in a future version
+func PartParser(template, data string) (map[string]string, error) {
+ // ip:public:private
+ var (
+ templateParts = strings.Split(template, ":")
+ parts = strings.Split(data, ":")
+ out = make(map[string]string, len(templateParts))
+ )
+ if len(parts) != len(templateParts) {
+ return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
+ }
+
+ for i, t := range templateParts {
+ value := ""
+ if len(parts) > i {
+ value = parts[i]
+ }
+ out[t] = value
+ }
+ return out, nil
+}
+
+// ParsePortRange parses and validates the specified string as a port-range (8000-9000)
+func ParsePortRange(ports string) (uint64, uint64, error) {
+ if ports == "" {
+ return 0, 0, fmt.Errorf("Empty string specified for ports.")
+ }
+ if !strings.Contains(ports, "-") {
+ start, err := strconv.ParseUint(ports, 10, 16)
+ end := start
+ return start, end, err
+ }
+
+ parts := strings.Split(ports, "-")
+ start, err := strconv.ParseUint(parts[0], 10, 16)
+ if err != nil {
+ return 0, 0, err
+ }
+ end, err := strconv.ParseUint(parts[1], 10, 16)
+ if err != nil {
+ return 0, 0, err
+ }
+ if end < start {
+ return 0, 0, fmt.Errorf("Invalid range specified for the Port: %s", ports)
+ }
+ return start, end, nil
+}
diff --git a/vendor/github.com/docker/go-connections/nat/sort.go b/vendor/github.com/docker/go-connections/nat/sort.go
new file mode 100644
index 0000000..ce95017
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/nat/sort.go
@@ -0,0 +1,96 @@
+package nat
+
+import (
+ "sort"
+ "strings"
+)
+
+type portSorter struct {
+ ports []Port
+ by func(i, j Port) bool
+}
+
+func (s *portSorter) Len() int {
+ return len(s.ports)
+}
+
+func (s *portSorter) Swap(i, j int) {
+ s.ports[i], s.ports[j] = s.ports[j], s.ports[i]
+}
+
+func (s *portSorter) Less(i, j int) bool {
+ ip := s.ports[i]
+ jp := s.ports[j]
+
+ return s.by(ip, jp)
+}
+
+// Sort sorts a list of ports using the provided predicate
+// This function should compare `i` and `j`, returning true if `i` is
+// considered to be less than `j`
+func Sort(ports []Port, predicate func(i, j Port) bool) {
+ s := &portSorter{ports, predicate}
+ sort.Sort(s)
+}
+
+type portMapEntry struct {
+ port Port
+ binding PortBinding
+}
+
+type portMapSorter []portMapEntry
+
+func (s portMapSorter) Len() int { return len(s) }
+func (s portMapSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+// sort the port so that the order is:
+// 1. port with larger specified bindings
+// 2. larger port
+// 3. port with tcp protocol
+func (s portMapSorter) Less(i, j int) bool {
+ pi, pj := s[i].port, s[j].port
+ hpi, hpj := toInt(s[i].binding.HostPort), toInt(s[j].binding.HostPort)
+ return hpi > hpj || pi.Int() > pj.Int() || (pi.Int() == pj.Int() && strings.ToLower(pi.Proto()) == "tcp")
+}
+
+// SortPortMap sorts the list of ports and their respected mapping. The ports
+// will explicit HostPort will be placed first.
+func SortPortMap(ports []Port, bindings PortMap) {
+ s := portMapSorter{}
+ for _, p := range ports {
+ if binding, ok := bindings[p]; ok {
+ for _, b := range binding {
+ s = append(s, portMapEntry{port: p, binding: b})
+ }
+ bindings[p] = []PortBinding{}
+ } else {
+ s = append(s, portMapEntry{port: p})
+ }
+ }
+
+ sort.Sort(s)
+ var (
+ i int
+ pm = make(map[Port]struct{})
+ )
+ // reorder ports
+ for _, entry := range s {
+ if _, ok := pm[entry.port]; !ok {
+ ports[i] = entry.port
+ pm[entry.port] = struct{}{}
+ i++
+ }
+ // reorder bindings for this port
+ if _, ok := bindings[entry.port]; ok {
+ bindings[entry.port] = append(bindings[entry.port], entry.binding)
+ }
+ }
+}
+
+func toInt(s string) uint64 {
+ i, _, err := ParsePortRange(s)
+ if err != nil {
+ i = 0
+ }
+ return i
+}
diff --git a/vendor/github.com/docker/go-connections/sockets/README.md b/vendor/github.com/docker/go-connections/sockets/README.md
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/sockets/README.md
diff --git a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go b/vendor/github.com/docker/go-connections/sockets/inmem_socket.go
new file mode 100644
index 0000000..99846ff
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/sockets/inmem_socket.go
@@ -0,0 +1,81 @@
+package sockets
+
+import (
+ "errors"
+ "net"
+ "sync"
+)
+
+var errClosed = errors.New("use of closed network connection")
+
+// InmemSocket implements net.Listener using in-memory only connections.
+type InmemSocket struct {
+ chConn chan net.Conn
+ chClose chan struct{}
+ addr string
+ mu sync.Mutex
+}
+
+// dummyAddr is used to satisfy net.Addr for the in-mem socket
+// it is just stored as a string and returns the string for all calls
+type dummyAddr string
+
+// NewInmemSocket creates an in-memory only net.Listener
+// The addr argument can be any string, but is used to satisfy the `Addr()` part
+// of the net.Listener interface
+func NewInmemSocket(addr string, bufSize int) *InmemSocket {
+ return &InmemSocket{
+ chConn: make(chan net.Conn, bufSize),
+ chClose: make(chan struct{}),
+ addr: addr,
+ }
+}
+
+// Addr returns the socket's addr string to satisfy net.Listener
+func (s *InmemSocket) Addr() net.Addr {
+ return dummyAddr(s.addr)
+}
+
+// Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn.
+func (s *InmemSocket) Accept() (net.Conn, error) {
+ select {
+ case conn := <-s.chConn:
+ return conn, nil
+ case <-s.chClose:
+ return nil, errClosed
+ }
+}
+
+// Close closes the listener. It will be unavailable for use once closed.
+func (s *InmemSocket) Close() error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ select {
+ case <-s.chClose:
+ default:
+ close(s.chClose)
+ }
+ return nil
+}
+
+// Dial is used to establish a connection with the in-mem server
+func (s *InmemSocket) Dial(network, addr string) (net.Conn, error) {
+ srvConn, clientConn := net.Pipe()
+ select {
+ case s.chConn <- srvConn:
+ case <-s.chClose:
+ return nil, errClosed
+ }
+
+ return clientConn, nil
+}
+
+// Network returns the addr string, satisfies net.Addr
+func (a dummyAddr) Network() string {
+ return string(a)
+}
+
+// String returns the string form
+func (a dummyAddr) String() string {
+ return string(a)
+}
diff --git a/vendor/github.com/docker/go-connections/sockets/proxy.go b/vendor/github.com/docker/go-connections/sockets/proxy.go
new file mode 100644
index 0000000..98e9a1d
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/sockets/proxy.go
@@ -0,0 +1,51 @@
+package sockets
+
+import (
+ "net"
+ "net/url"
+ "os"
+ "strings"
+
+ "golang.org/x/net/proxy"
+)
+
+// GetProxyEnv allows access to the uppercase and the lowercase forms of
+// proxy-related variables. See the Go specification for details on these
+// variables. https://golang.org/pkg/net/http/
+func GetProxyEnv(key string) string {
+ proxyValue := os.Getenv(strings.ToUpper(key))
+ if proxyValue == "" {
+ return os.Getenv(strings.ToLower(key))
+ }
+ return proxyValue
+}
+
+// DialerFromEnvironment takes in a "direct" *net.Dialer and returns a
+// proxy.Dialer which will route the connections through the proxy using the
+// given dialer.
+func DialerFromEnvironment(direct *net.Dialer) (proxy.Dialer, error) {
+ allProxy := GetProxyEnv("all_proxy")
+ if len(allProxy) == 0 {
+ return direct, nil
+ }
+
+ proxyURL, err := url.Parse(allProxy)
+ if err != nil {
+ return direct, err
+ }
+
+ proxyFromURL, err := proxy.FromURL(proxyURL, direct)
+ if err != nil {
+ return direct, err
+ }
+
+ noProxy := GetProxyEnv("no_proxy")
+ if len(noProxy) == 0 {
+ return proxyFromURL, nil
+ }
+
+ perHost := proxy.NewPerHost(proxyFromURL, direct)
+ perHost.AddFromString(noProxy)
+
+ return perHost, nil
+}
diff --git a/vendor/github.com/docker/go-connections/sockets/sockets.go b/vendor/github.com/docker/go-connections/sockets/sockets.go
new file mode 100644
index 0000000..a1d7beb
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/sockets/sockets.go
@@ -0,0 +1,38 @@
+// Package sockets provides helper functions to create and configure Unix or TCP sockets.
+package sockets
+
+import (
+ "errors"
+ "net"
+ "net/http"
+ "time"
+)
+
+// Why 32? See https://github.com/docker/docker/pull/8035.
+const defaultTimeout = 32 * time.Second
+
+// ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system.
+var ErrProtocolNotAvailable = errors.New("protocol not available")
+
+// ConfigureTransport configures the specified Transport according to the
+// specified proto and addr.
+// If the proto is unix (using a unix socket to communicate) or npipe the
+// compression is disabled.
+func ConfigureTransport(tr *http.Transport, proto, addr string) error {
+ switch proto {
+ case "unix":
+ return configureUnixTransport(tr, proto, addr)
+ case "npipe":
+ return configureNpipeTransport(tr, proto, addr)
+ default:
+ tr.Proxy = http.ProxyFromEnvironment
+ dialer, err := DialerFromEnvironment(&net.Dialer{
+ Timeout: defaultTimeout,
+ })
+ if err != nil {
+ return err
+ }
+ tr.Dial = dialer.Dial
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/go-connections/sockets/sockets_unix.go b/vendor/github.com/docker/go-connections/sockets/sockets_unix.go
new file mode 100644
index 0000000..386cf0d
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/sockets/sockets_unix.go
@@ -0,0 +1,35 @@
+// +build !windows
+
+package sockets
+
+import (
+ "fmt"
+ "net"
+ "net/http"
+ "syscall"
+ "time"
+)
+
+const maxUnixSocketPathSize = len(syscall.RawSockaddrUnix{}.Path)
+
+func configureUnixTransport(tr *http.Transport, proto, addr string) error {
+ if len(addr) > maxUnixSocketPathSize {
+ return fmt.Errorf("Unix socket path %q is too long", addr)
+ }
+ // No need for compression in local communications.
+ tr.DisableCompression = true
+ tr.Dial = func(_, _ string) (net.Conn, error) {
+ return net.DialTimeout(proto, addr, defaultTimeout)
+ }
+ return nil
+}
+
+func configureNpipeTransport(tr *http.Transport, proto, addr string) error {
+ return ErrProtocolNotAvailable
+}
+
+// DialPipe connects to a Windows named pipe.
+// This is not supported on other OSes.
+func DialPipe(_ string, _ time.Duration) (net.Conn, error) {
+ return nil, syscall.EAFNOSUPPORT
+}
diff --git a/vendor/github.com/docker/go-connections/sockets/sockets_windows.go b/vendor/github.com/docker/go-connections/sockets/sockets_windows.go
new file mode 100644
index 0000000..5c21644
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/sockets/sockets_windows.go
@@ -0,0 +1,27 @@
+package sockets
+
+import (
+ "net"
+ "net/http"
+ "time"
+
+ "github.com/Microsoft/go-winio"
+)
+
+func configureUnixTransport(tr *http.Transport, proto, addr string) error {
+ return ErrProtocolNotAvailable
+}
+
+func configureNpipeTransport(tr *http.Transport, proto, addr string) error {
+ // No need for compression in local communications.
+ tr.DisableCompression = true
+ tr.Dial = func(_, _ string) (net.Conn, error) {
+ return DialPipe(addr, defaultTimeout)
+ }
+ return nil
+}
+
+// DialPipe connects to a Windows named pipe.
+func DialPipe(addr string, timeout time.Duration) (net.Conn, error) {
+ return winio.DialPipe(addr, &timeout)
+}
diff --git a/vendor/github.com/docker/go-connections/sockets/tcp_socket.go b/vendor/github.com/docker/go-connections/sockets/tcp_socket.go
new file mode 100644
index 0000000..53cbb6c
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/sockets/tcp_socket.go
@@ -0,0 +1,22 @@
+// Package sockets provides helper functions to create and configure Unix or TCP sockets.
+package sockets
+
+import (
+ "crypto/tls"
+ "net"
+)
+
+// NewTCPSocket creates a TCP socket listener with the specified address and
+// the specified tls configuration. If TLSConfig is set, will encapsulate the
+// TCP listener inside a TLS one.
+func NewTCPSocket(addr string, tlsConfig *tls.Config) (net.Listener, error) {
+ l, err := net.Listen("tcp", addr)
+ if err != nil {
+ return nil, err
+ }
+ if tlsConfig != nil {
+ tlsConfig.NextProtos = []string{"http/1.1"}
+ l = tls.NewListener(l, tlsConfig)
+ }
+ return l, nil
+}
diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket.go b/vendor/github.com/docker/go-connections/sockets/unix_socket.go
new file mode 100644
index 0000000..a8b5dbb
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/sockets/unix_socket.go
@@ -0,0 +1,32 @@
+// +build !windows
+
+package sockets
+
+import (
+ "net"
+ "os"
+ "syscall"
+)
+
+// NewUnixSocket creates a unix socket with the specified path and group.
+func NewUnixSocket(path string, gid int) (net.Listener, error) {
+ if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) {
+ return nil, err
+ }
+ mask := syscall.Umask(0777)
+ defer syscall.Umask(mask)
+
+ l, err := net.Listen("unix", path)
+ if err != nil {
+ return nil, err
+ }
+ if err := os.Chown(path, 0, gid); err != nil {
+ l.Close()
+ return nil, err
+ }
+ if err := os.Chmod(path, 0660); err != nil {
+ l.Close()
+ return nil, err
+ }
+ return l, nil
+}
diff --git a/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go b/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go
new file mode 100644
index 0000000..1ca0965
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go
@@ -0,0 +1,18 @@
+// +build go1.7
+
+package tlsconfig
+
+import (
+ "crypto/x509"
+ "runtime"
+)
+
+// SystemCertPool returns a copy of the system cert pool,
+// returns an error if failed to load or empty pool on windows.
+func SystemCertPool() (*x509.CertPool, error) {
+ certpool, err := x509.SystemCertPool()
+ if err != nil && runtime.GOOS == "windows" {
+ return x509.NewCertPool(), nil
+ }
+ return certpool, err
+}
diff --git a/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go b/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go
new file mode 100644
index 0000000..9ca9745
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go
@@ -0,0 +1,14 @@
+// +build !go1.7
+
+package tlsconfig
+
+import (
+ "crypto/x509"
+
+)
+
+// SystemCertPool returns an new empty cert pool,
+// accessing system cert pool is supported in go 1.7
+func SystemCertPool() (*x509.CertPool, error) {
+ return x509.NewCertPool(), nil
+}
diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config.go b/vendor/github.com/docker/go-connections/tlsconfig/config.go
new file mode 100644
index 0000000..1b31bbb
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/tlsconfig/config.go
@@ -0,0 +1,244 @@
+// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers.
+//
+// As a reminder from https://golang.org/pkg/crypto/tls/#Config:
+// A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified.
+// A Config may be reused; the tls package will also not modify it.
+package tlsconfig
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/pem"
+ "fmt"
+ "io/ioutil"
+ "os"
+
+ "github.com/pkg/errors"
+)
+
+// Options represents the information needed to create client and server TLS configurations.
+type Options struct {
+ CAFile string
+
+ // If either CertFile or KeyFile is empty, Client() will not load them
+ // preventing the client from authenticating to the server.
+ // However, Server() requires them and will error out if they are empty.
+ CertFile string
+ KeyFile string
+
+ // client-only option
+ InsecureSkipVerify bool
+ // server-only option
+ ClientAuth tls.ClientAuthType
+ // If ExclusiveRootPools is set, then if a CA file is provided, the root pool used for TLS
+ // creds will include exclusively the roots in that CA file. If no CA file is provided,
+ // the system pool will be used.
+ ExclusiveRootPools bool
+ MinVersion uint16
+ // If Passphrase is set, it will be used to decrypt a TLS private key
+ // if the key is encrypted
+ Passphrase string
+}
+
+// Extra (server-side) accepted CBC cipher suites - will phase out in the future
+var acceptedCBCCiphers = []uint16{
+ tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
+ tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
+ tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
+ tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
+ tls.TLS_RSA_WITH_AES_256_CBC_SHA,
+ tls.TLS_RSA_WITH_AES_128_CBC_SHA,
+}
+
+// DefaultServerAcceptedCiphers should be uses by code which already has a crypto/tls
+// options struct but wants to use a commonly accepted set of TLS cipher suites, with
+// known weak algorithms removed.
+var DefaultServerAcceptedCiphers = append(clientCipherSuites, acceptedCBCCiphers...)
+
+// allTLSVersions lists all the TLS versions and is used by the code that validates
+// a uint16 value as a TLS version.
+var allTLSVersions = map[uint16]struct{}{
+ tls.VersionSSL30: {},
+ tls.VersionTLS10: {},
+ tls.VersionTLS11: {},
+ tls.VersionTLS12: {},
+}
+
+// ServerDefault returns a secure-enough TLS configuration for the server TLS configuration.
+func ServerDefault() *tls.Config {
+ return &tls.Config{
+ // Avoid fallback to SSL protocols < TLS1.0
+ MinVersion: tls.VersionTLS10,
+ PreferServerCipherSuites: true,
+ CipherSuites: DefaultServerAcceptedCiphers,
+ }
+}
+
+// ClientDefault returns a secure-enough TLS configuration for the client TLS configuration.
+func ClientDefault() *tls.Config {
+ return &tls.Config{
+ // Prefer TLS1.2 as the client minimum
+ MinVersion: tls.VersionTLS12,
+ CipherSuites: clientCipherSuites,
+ }
+}
+
+// certPool returns an X.509 certificate pool from `caFile`, the certificate file.
+func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) {
+ // If we should verify the server, we need to load a trusted ca
+ var (
+ certPool *x509.CertPool
+ err error
+ )
+ if exclusivePool {
+ certPool = x509.NewCertPool()
+ } else {
+ certPool, err = SystemCertPool()
+ if err != nil {
+ return nil, fmt.Errorf("failed to read system certificates: %v", err)
+ }
+ }
+ pem, err := ioutil.ReadFile(caFile)
+ if err != nil {
+ return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err)
+ }
+ if !certPool.AppendCertsFromPEM(pem) {
+ return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile)
+ }
+ return certPool, nil
+}
+
+// isValidMinVersion checks that the input value is a valid tls minimum version
+func isValidMinVersion(version uint16) bool {
+ _, ok := allTLSVersions[version]
+ return ok
+}
+
+// adjustMinVersion sets the MinVersion on `config`, the input configuration.
+// It assumes the current MinVersion on the `config` is the lowest allowed.
+func adjustMinVersion(options Options, config *tls.Config) error {
+ if options.MinVersion > 0 {
+ if !isValidMinVersion(options.MinVersion) {
+ return fmt.Errorf("Invalid minimum TLS version: %x", options.MinVersion)
+ }
+ if options.MinVersion < config.MinVersion {
+ return fmt.Errorf("Requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion)
+ }
+ config.MinVersion = options.MinVersion
+ }
+
+ return nil
+}
+
+// IsErrEncryptedKey returns true if the 'err' is an error of incorrect
+// password when tryin to decrypt a TLS private key
+func IsErrEncryptedKey(err error) bool {
+ return errors.Cause(err) == x509.IncorrectPasswordError
+}
+
+// getPrivateKey returns the private key in 'keyBytes', in PEM-encoded format.
+// If the private key is encrypted, 'passphrase' is used to decrypted the
+// private key.
+func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) {
+ // this section makes some small changes to code from notary/tuf/utils/x509.go
+ pemBlock, _ := pem.Decode(keyBytes)
+ if pemBlock == nil {
+ return nil, fmt.Errorf("no valid private key found")
+ }
+
+ var err error
+ if x509.IsEncryptedPEMBlock(pemBlock) {
+ keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase))
+ if err != nil {
+ return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it")
+ }
+ keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes})
+ }
+
+ return keyBytes, nil
+}
+
+// getCert returns a Certificate from the CertFile and KeyFile in 'options',
+// if the key is encrypted, the Passphrase in 'options' will be used to
+// decrypt it.
+func getCert(options Options) ([]tls.Certificate, error) {
+ if options.CertFile == "" && options.KeyFile == "" {
+ return nil, nil
+ }
+
+ errMessage := "Could not load X509 key pair"
+
+ cert, err := ioutil.ReadFile(options.CertFile)
+ if err != nil {
+ return nil, errors.Wrap(err, errMessage)
+ }
+
+ prKeyBytes, err := ioutil.ReadFile(options.KeyFile)
+ if err != nil {
+ return nil, errors.Wrap(err, errMessage)
+ }
+
+ prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase)
+ if err != nil {
+ return nil, errors.Wrap(err, errMessage)
+ }
+
+ tlsCert, err := tls.X509KeyPair(cert, prKeyBytes)
+ if err != nil {
+ return nil, errors.Wrap(err, errMessage)
+ }
+
+ return []tls.Certificate{tlsCert}, nil
+}
+
+// Client returns a TLS configuration meant to be used by a client.
+func Client(options Options) (*tls.Config, error) {
+ tlsConfig := ClientDefault()
+ tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify
+ if !options.InsecureSkipVerify && options.CAFile != "" {
+ CAs, err := certPool(options.CAFile, options.ExclusiveRootPools)
+ if err != nil {
+ return nil, err
+ }
+ tlsConfig.RootCAs = CAs
+ }
+
+ tlsCerts, err := getCert(options)
+ if err != nil {
+ return nil, err
+ }
+ tlsConfig.Certificates = tlsCerts
+
+ if err := adjustMinVersion(options, tlsConfig); err != nil {
+ return nil, err
+ }
+
+ return tlsConfig, nil
+}
+
+// Server returns a TLS configuration meant to be used by a server.
+func Server(options Options) (*tls.Config, error) {
+ tlsConfig := ServerDefault()
+ tlsConfig.ClientAuth = options.ClientAuth
+ tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, fmt.Errorf("Could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err)
+ }
+ return nil, fmt.Errorf("Error reading X509 key pair (cert: %q, key: %q): %v. Make sure the key is not encrypted.", options.CertFile, options.KeyFile, err)
+ }
+ tlsConfig.Certificates = []tls.Certificate{tlsCert}
+ if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" {
+ CAs, err := certPool(options.CAFile, options.ExclusiveRootPools)
+ if err != nil {
+ return nil, err
+ }
+ tlsConfig.ClientCAs = CAs
+ }
+
+ if err := adjustMinVersion(options, tlsConfig); err != nil {
+ return nil, err
+ }
+
+ return tlsConfig, nil
+}
diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go b/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go
new file mode 100644
index 0000000..6b4c6a7
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go
@@ -0,0 +1,17 @@
+// +build go1.5
+
+// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers.
+//
+package tlsconfig
+
+import (
+ "crypto/tls"
+)
+
+// Client TLS cipher suites (dropping CBC ciphers for client preferred suite set)
+var clientCipherSuites = []uint16{
+ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
+ tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
+ tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
+ tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
+}
diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go b/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go
new file mode 100644
index 0000000..ee22df4
--- /dev/null
+++ b/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go
@@ -0,0 +1,15 @@
+// +build !go1.5
+
+// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers.
+//
+package tlsconfig
+
+import (
+ "crypto/tls"
+)
+
+// Client TLS cipher suites (dropping CBC ciphers for client preferred suite set)
+var clientCipherSuites = []uint16{
+ tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
+ tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
+}
diff --git a/vendor/github.com/docker/go-events/LICENSE b/vendor/github.com/docker/go-events/LICENSE
new file mode 100644
index 0000000..6d630cf
--- /dev/null
+++ b/vendor/github.com/docker/go-events/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2016 Docker, Inc.
+
+ 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/docker/go-events/README.md b/vendor/github.com/docker/go-events/README.md
new file mode 100644
index 0000000..0acafc2
--- /dev/null
+++ b/vendor/github.com/docker/go-events/README.md
@@ -0,0 +1,117 @@
+# Docker Events Package
+
+[![GoDoc](https://godoc.org/github.com/docker/go-events?status.svg)](https://godoc.org/github.com/docker/go-events)
+[![Circle CI](https://circleci.com/gh/docker/go-events.svg?style=shield)](https://circleci.com/gh/docker/go-events)
+
+The Docker `events` package implements a composable event distribution package
+for Go.
+
+Originally created to implement the [notifications in Docker Registry
+2](https://github.com/docker/distribution/blob/master/docs/notifications.md),
+we've found the pattern to be useful in other applications. This package is
+most of the same code with slightly updated interfaces. Much of the internals
+have been made available.
+
+## Usage
+
+The `events` package centers around a `Sink` type. Events are written with
+calls to `Sink.Write(event Event)`. Sinks can be wired up in various
+configurations to achieve interesting behavior.
+
+The canonical example is that employed by the
+[docker/distribution/notifications](https://godoc.org/github.com/docker/distribution/notifications)
+package. Let's say we have a type `httpSink` where we'd like to queue
+notifications. As a rule, it should send a single http request and return an
+error if it fails:
+
+```go
+func (h *httpSink) Write(event Event) error {
+ p, err := json.Marshal(event)
+ if err != nil {
+ return err
+ }
+ body := bytes.NewReader(p)
+ resp, err := h.client.Post(h.url, "application/json", body)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.Status != 200 {
+ return errors.New("unexpected status")
+ }
+
+ return nil
+}
+
+// implement (*httpSink).Close()
+```
+
+With just that, we can start using components from this package. One can call
+`(*httpSink).Write` to send events as the body of a post request to a
+configured URL.
+
+### Retries
+
+HTTP can be unreliable. The first feature we'd like is to have some retry:
+
+```go
+hs := newHTTPSink(/*...*/)
+retry := NewRetryingSink(hs, NewBreaker(5, time.Second))
+```
+
+We now have a sink that will retry events against the `httpSink` until they
+succeed. The retry will backoff for one second after 5 consecutive failures
+using the breaker strategy.
+
+### Queues
+
+This isn't quite enough. We we want a sink that doesn't block while we are
+waiting for events to be sent. Let's add a `Queue`:
+
+```go
+queue := NewQueue(retry)
+```
+
+Now, we have an unbounded queue that will work through all events sent with
+`(*Queue).Write`. Events can be added asynchronously to the queue without
+blocking the current execution path. This is ideal for use in an http request.
+
+### Broadcast
+
+It usually turns out that you want to send to more than one listener. We can
+use `Broadcaster` to support this:
+
+```go
+var broadcast = NewBroadcaster() // make it available somewhere in your application.
+broadcast.Add(queue) // add your queue!
+broadcast.Add(queue2) // and another!
+```
+
+With the above, we can now call `broadcast.Write` in our http handlers and have
+all the events distributed to each queue. Because the events are queued, not
+listener blocks another.
+
+### Extending
+
+For the most part, the above is sufficient for a lot of applications. However,
+extending the above functionality can be done implementing your own `Sink`. The
+behavior and semantics of the sink can be completely dependent on the
+application requirements. The interface is provided below for reference:
+
+```go
+type Sink {
+ Write(Event) error
+ Close() error
+}
+```
+
+Application behavior can be controlled by how `Write` behaves. The examples
+above are designed to queue the message and return as quickly as possible.
+Other implementations may block until the event is committed to durable
+storage.
+
+## Copyright and license
+
+Copyright © 2016 Docker, Inc. go-events is licensed under the Apache License,
+Version 2.0. See [LICENSE](LICENSE) for the full license text.
diff --git a/vendor/github.com/docker/go-events/broadcast.go b/vendor/github.com/docker/go-events/broadcast.go
new file mode 100644
index 0000000..ee0a894
--- /dev/null
+++ b/vendor/github.com/docker/go-events/broadcast.go
@@ -0,0 +1,178 @@
+package events
+
+import (
+ "fmt"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// Broadcaster sends events to multiple, reliable Sinks. The goal of this
+// component is to dispatch events to configured endpoints. Reliability can be
+// provided by wrapping incoming sinks.
+type Broadcaster struct {
+ sinks []Sink
+ events chan Event
+ adds chan configureRequest
+ removes chan configureRequest
+
+ shutdown chan struct{}
+ closed chan struct{}
+ once sync.Once
+}
+
+// NewBroadcaster appends one or more sinks to the list of sinks. The
+// broadcaster behavior will be affected by the properties of the sink.
+// Generally, the sink should accept all messages and deal with reliability on
+// its own. Use of EventQueue and RetryingSink should be used here.
+func NewBroadcaster(sinks ...Sink) *Broadcaster {
+ b := Broadcaster{
+ sinks: sinks,
+ events: make(chan Event),
+ adds: make(chan configureRequest),
+ removes: make(chan configureRequest),
+ shutdown: make(chan struct{}),
+ closed: make(chan struct{}),
+ }
+
+ // Start the broadcaster
+ go b.run()
+
+ return &b
+}
+
+// Write accepts an event to be dispatched to all sinks. This method will never
+// fail and should never block (hopefully!). The caller cedes the memory to the
+// broadcaster and should not modify it after calling write.
+func (b *Broadcaster) Write(event Event) error {
+ select {
+ case b.events <- event:
+ case <-b.closed:
+ return ErrSinkClosed
+ }
+ return nil
+}
+
+// Add the sink to the broadcaster.
+//
+// The provided sink must be comparable with equality. Typically, this just
+// works with a regular pointer type.
+func (b *Broadcaster) Add(sink Sink) error {
+ return b.configure(b.adds, sink)
+}
+
+// Remove the provided sink.
+func (b *Broadcaster) Remove(sink Sink) error {
+ return b.configure(b.removes, sink)
+}
+
+type configureRequest struct {
+ sink Sink
+ response chan error
+}
+
+func (b *Broadcaster) configure(ch chan configureRequest, sink Sink) error {
+ response := make(chan error, 1)
+
+ for {
+ select {
+ case ch <- configureRequest{
+ sink: sink,
+ response: response}:
+ ch = nil
+ case err := <-response:
+ return err
+ case <-b.closed:
+ return ErrSinkClosed
+ }
+ }
+}
+
+// Close the broadcaster, ensuring that all messages are flushed to the
+// underlying sink before returning.
+func (b *Broadcaster) Close() error {
+ b.once.Do(func() {
+ close(b.shutdown)
+ })
+
+ <-b.closed
+ return nil
+}
+
+// run is the main broadcast loop, started when the broadcaster is created.
+// Under normal conditions, it waits for events on the event channel. After
+// Close is called, this goroutine will exit.
+func (b *Broadcaster) run() {
+ defer close(b.closed)
+ remove := func(target Sink) {
+ for i, sink := range b.sinks {
+ if sink == target {
+ b.sinks = append(b.sinks[:i], b.sinks[i+1:]...)
+ break
+ }
+ }
+ }
+
+ for {
+ select {
+ case event := <-b.events:
+ for _, sink := range b.sinks {
+ if err := sink.Write(event); err != nil {
+ if err == ErrSinkClosed {
+ // remove closed sinks
+ remove(sink)
+ continue
+ }
+ logrus.WithField("event", event).WithField("events.sink", sink).WithError(err).
+ Errorf("broadcaster: dropping event")
+ }
+ }
+ case request := <-b.adds:
+ // while we have to iterate for add/remove, common iteration for
+ // send is faster against slice.
+
+ var found bool
+ for _, sink := range b.sinks {
+ if request.sink == sink {
+ found = true
+ break
+ }
+ }
+
+ if !found {
+ b.sinks = append(b.sinks, request.sink)
+ }
+ // b.sinks[request.sink] = struct{}{}
+ request.response <- nil
+ case request := <-b.removes:
+ remove(request.sink)
+ request.response <- nil
+ case <-b.shutdown:
+ // close all the underlying sinks
+ for _, sink := range b.sinks {
+ if err := sink.Close(); err != nil && err != ErrSinkClosed {
+ logrus.WithField("events.sink", sink).WithError(err).
+ Errorf("broadcaster: closing sink failed")
+ }
+ }
+ return
+ }
+ }
+}
+
+func (b Broadcaster) String() string {
+ // Serialize copy of this broadcaster without the sync.Once, to avoid
+ // a data race.
+
+ b2 := map[string]interface{}{
+ "sinks": b.sinks,
+ "events": b.events,
+ "adds": b.adds,
+ "removes": b.removes,
+
+ "shutdown": b.shutdown,
+ "closed": b.closed,
+ }
+
+ return fmt.Sprint(b2)
+}
diff --git a/vendor/github.com/docker/go-events/channel.go b/vendor/github.com/docker/go-events/channel.go
new file mode 100644
index 0000000..de95fa4
--- /dev/null
+++ b/vendor/github.com/docker/go-events/channel.go
@@ -0,0 +1,61 @@
+package events
+
+import (
+ "fmt"
+ "sync"
+)
+
+// Channel provides a sink that can be listened on. The writer and channel
+// listener must operate in separate goroutines.
+//
+// Consumers should listen on Channel.C until Closed is closed.
+type Channel struct {
+ C chan Event
+
+ closed chan struct{}
+ once sync.Once
+}
+
+// NewChannel returns a channel. If buffer is zero, the channel is
+// unbuffered.
+func NewChannel(buffer int) *Channel {
+ return &Channel{
+ C: make(chan Event, buffer),
+ closed: make(chan struct{}),
+ }
+}
+
+// Done returns a channel that will always proceed once the sink is closed.
+func (ch *Channel) Done() chan struct{} {
+ return ch.closed
+}
+
+// Write the event to the channel. Must be called in a separate goroutine from
+// the listener.
+func (ch *Channel) Write(event Event) error {
+ select {
+ case ch.C <- event:
+ return nil
+ case <-ch.closed:
+ return ErrSinkClosed
+ }
+}
+
+// Close the channel sink.
+func (ch *Channel) Close() error {
+ ch.once.Do(func() {
+ close(ch.closed)
+ })
+
+ return nil
+}
+
+func (ch Channel) String() string {
+ // Serialize a copy of the Channel that doesn't contain the sync.Once,
+ // to avoid a data race.
+ ch2 := map[string]interface{}{
+ "C": ch.C,
+ "closed": ch.closed,
+ }
+ return fmt.Sprint(ch2)
+}
diff --git a/vendor/github.com/docker/go-events/errors.go b/vendor/github.com/docker/go-events/errors.go
new file mode 100644
index 0000000..56db7c2
--- /dev/null
+++ b/vendor/github.com/docker/go-events/errors.go
@@ -0,0 +1,10 @@
+package events
+
+import "fmt"
+
+var (
+ // ErrSinkClosed is returned if a write is issued to a sink that has been
+ // closed. If encountered, the error should be considered terminal and
+ // retries will not be successful.
+ ErrSinkClosed = fmt.Errorf("events: sink closed")
+)
diff --git a/vendor/github.com/docker/go-events/event.go b/vendor/github.com/docker/go-events/event.go
new file mode 100644
index 0000000..f0f1d9e
--- /dev/null
+++ b/vendor/github.com/docker/go-events/event.go
@@ -0,0 +1,15 @@
+package events
+
+// Event marks items that can be sent as events.
+type Event interface{}
+
+// Sink accepts and sends events.
+type Sink interface {
+ // Write an event to the Sink. If no error is returned, the caller will
+ // assume that all events have been committed to the sink. If an error is
+ // received, the caller may retry sending the event.
+ Write(event Event) error
+
+ // Close the sink, possibly waiting for pending events to flush.
+ Close() error
+}
diff --git a/vendor/github.com/docker/go-events/filter.go b/vendor/github.com/docker/go-events/filter.go
new file mode 100644
index 0000000..e6c0eb6
--- /dev/null
+++ b/vendor/github.com/docker/go-events/filter.go
@@ -0,0 +1,52 @@
+package events
+
+// Matcher matches events.
+type Matcher interface {
+ Match(event Event) bool
+}
+
+// MatcherFunc implements matcher with just a function.
+type MatcherFunc func(event Event) bool
+
+// Match calls the wrapped function.
+func (fn MatcherFunc) Match(event Event) bool {
+ return fn(event)
+}
+
+// Filter provides an event sink that sends only events that are accepted by a
+// Matcher. No methods on filter are goroutine safe.
+type Filter struct {
+ dst Sink
+ matcher Matcher
+ closed bool
+}
+
+// NewFilter returns a new filter that will send to events to dst that return
+// true for Matcher.
+func NewFilter(dst Sink, matcher Matcher) Sink {
+ return &Filter{dst: dst, matcher: matcher}
+}
+
+// Write an event to the filter.
+func (f *Filter) Write(event Event) error {
+ if f.closed {
+ return ErrSinkClosed
+ }
+
+ if f.matcher.Match(event) {
+ return f.dst.Write(event)
+ }
+
+ return nil
+}
+
+// Close the filter and allow no more events to pass through.
+func (f *Filter) Close() error {
+ // TODO(stevvooe): Not all sinks should have Close.
+ if f.closed {
+ return nil
+ }
+
+ f.closed = true
+ return f.dst.Close()
+}
diff --git a/vendor/github.com/docker/go-events/queue.go b/vendor/github.com/docker/go-events/queue.go
new file mode 100644
index 0000000..cbd657c
--- /dev/null
+++ b/vendor/github.com/docker/go-events/queue.go
@@ -0,0 +1,111 @@
+package events
+
+import (
+ "container/list"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// Queue accepts all messages into a queue for asynchronous consumption
+// by a sink. It is unbounded and thread safe but the sink must be reliable or
+// events will be dropped.
+type Queue struct {
+ dst Sink
+ events *list.List
+ cond *sync.Cond
+ mu sync.Mutex
+ closed bool
+}
+
+// NewQueue returns a queue to the provided Sink dst.
+func NewQueue(dst Sink) *Queue {
+ eq := Queue{
+ dst: dst,
+ events: list.New(),
+ }
+
+ eq.cond = sync.NewCond(&eq.mu)
+ go eq.run()
+ return &eq
+}
+
+// Write accepts the events into the queue, only failing if the queue has
+// beend closed.
+func (eq *Queue) Write(event Event) error {
+ eq.mu.Lock()
+ defer eq.mu.Unlock()
+
+ if eq.closed {
+ return ErrSinkClosed
+ }
+
+ eq.events.PushBack(event)
+ eq.cond.Signal() // signal waiters
+
+ return nil
+}
+
+// Close shutsdown the event queue, flushing
+func (eq *Queue) Close() error {
+ eq.mu.Lock()
+ defer eq.mu.Unlock()
+
+ if eq.closed {
+ return nil
+ }
+
+ // set closed flag
+ eq.closed = true
+ eq.cond.Signal() // signal flushes queue
+ eq.cond.Wait() // wait for signal from last flush
+ return eq.dst.Close()
+}
+
+// run is the main goroutine to flush events to the target sink.
+func (eq *Queue) run() {
+ for {
+ event := eq.next()
+
+ if event == nil {
+ return // nil block means event queue is closed.
+ }
+
+ if err := eq.dst.Write(event); err != nil {
+ // TODO(aaronl): Dropping events could be bad depending
+ // on the application. We should have a way of
+ // communicating this condition. However, logging
+ // at a log level above debug may not be appropriate.
+ // Eventually, go-events should not use logrus at all,
+ // and should bubble up conditions like this through
+ // error values.
+ logrus.WithFields(logrus.Fields{
+ "event": event,
+ "sink": eq.dst,
+ }).WithError(err).Debug("eventqueue: dropped event")
+ }
+ }
+}
+
+// next encompasses the critical section of the run loop. When the queue is
+// empty, it will block on the condition. If new data arrives, it will wake
+// and return a block. When closed, a nil slice will be returned.
+func (eq *Queue) next() Event {
+ eq.mu.Lock()
+ defer eq.mu.Unlock()
+
+ for eq.events.Len() < 1 {
+ if eq.closed {
+ eq.cond.Broadcast()
+ return nil
+ }
+
+ eq.cond.Wait()
+ }
+
+ front := eq.events.Front()
+ block := front.Value.(Event)
+ eq.events.Remove(front)
+
+ return block
+}
diff --git a/vendor/github.com/docker/go-events/retry.go b/vendor/github.com/docker/go-events/retry.go
new file mode 100644
index 0000000..55d40dc
--- /dev/null
+++ b/vendor/github.com/docker/go-events/retry.go
@@ -0,0 +1,260 @@
+package events
+
+import (
+ "fmt"
+ "math/rand"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// RetryingSink retries the write until success or an ErrSinkClosed is
+// returned. Underlying sink must have p > 0 of succeeding or the sink will
+// block. Retry is configured with a RetryStrategy. Concurrent calls to a
+// retrying sink are serialized through the sink, meaning that if one is
+// in-flight, another will not proceed.
+type RetryingSink struct {
+ sink Sink
+ strategy RetryStrategy
+ closed chan struct{}
+ once sync.Once
+}
+
+// NewRetryingSink returns a sink that will retry writes to a sink, backing
+// off on failure. Parameters threshold and backoff adjust the behavior of the
+// circuit breaker.
+func NewRetryingSink(sink Sink, strategy RetryStrategy) *RetryingSink {
+ rs := &RetryingSink{
+ sink: sink,
+ strategy: strategy,
+ closed: make(chan struct{}),
+ }
+
+ return rs
+}
+
+// Write attempts to flush the events to the downstream sink until it succeeds
+// or the sink is closed.
+func (rs *RetryingSink) Write(event Event) error {
+ logger := logrus.WithField("event", event)
+
+retry:
+ select {
+ case <-rs.closed:
+ return ErrSinkClosed
+ default:
+ }
+
+ if backoff := rs.strategy.Proceed(event); backoff > 0 {
+ select {
+ case <-time.After(backoff):
+ // TODO(stevvooe): This branch holds up the next try. Before, we
+ // would simply break to the "retry" label and then possibly wait
+ // again. However, this requires all retry strategies to have a
+ // large probability of probing the sync for success, rather than
+ // just backing off and sending the request.
+ case <-rs.closed:
+ return ErrSinkClosed
+ }
+ }
+
+ if err := rs.sink.Write(event); err != nil {
+ if err == ErrSinkClosed {
+ // terminal!
+ return err
+ }
+
+ logger := logger.WithError(err) // shadow!!
+
+ if rs.strategy.Failure(event, err) {
+ logger.Errorf("retryingsink: dropped event")
+ return nil
+ }
+
+ logger.Errorf("retryingsink: error writing event, retrying")
+ goto retry
+ }
+
+ rs.strategy.Success(event)
+ return nil
+}
+
+// Close closes the sink and the underlying sink.
+func (rs *RetryingSink) Close() error {
+ rs.once.Do(func() {
+ close(rs.closed)
+ })
+
+ return nil
+}
+
+func (rs RetryingSink) String() string {
+ // Serialize a copy of the RetryingSink without the sync.Once, to avoid
+ // a data race.
+ rs2 := map[string]interface{}{
+ "sink": rs.sink,
+ "strategy": rs.strategy,
+ "closed": rs.closed,
+ }
+ return fmt.Sprint(rs2)
+}
+
+// RetryStrategy defines a strategy for retrying event sink writes.
+//
+// All methods should be goroutine safe.
+type RetryStrategy interface {
+ // Proceed is called before every event send. If proceed returns a
+ // positive, non-zero integer, the retryer will back off by the provided
+ // duration.
+ //
+ // An event is provided, by may be ignored.
+ Proceed(event Event) time.Duration
+
+ // Failure reports a failure to the strategy. If this method returns true,
+ // the event should be dropped.
+ Failure(event Event, err error) bool
+
+ // Success should be called when an event is sent successfully.
+ Success(event Event)
+}
+
+// Breaker implements a circuit breaker retry strategy.
+//
+// The current implementation never drops events.
+type Breaker struct {
+ threshold int
+ recent int
+ last time.Time
+ backoff time.Duration // time after which we retry after failure.
+ mu sync.Mutex
+}
+
+var _ RetryStrategy = &Breaker{}
+
+// NewBreaker returns a breaker that will backoff after the threshold has been
+// tripped. A Breaker is thread safe and may be shared by many goroutines.
+func NewBreaker(threshold int, backoff time.Duration) *Breaker {
+ return &Breaker{
+ threshold: threshold,
+ backoff: backoff,
+ }
+}
+
+// Proceed checks the failures against the threshold.
+func (b *Breaker) Proceed(event Event) time.Duration {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+
+ if b.recent < b.threshold {
+ return 0
+ }
+
+ return b.last.Add(b.backoff).Sub(time.Now())
+}
+
+// Success resets the breaker.
+func (b *Breaker) Success(event Event) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+
+ b.recent = 0
+ b.last = time.Time{}
+}
+
+// Failure records the failure and latest failure time.
+func (b *Breaker) Failure(event Event, err error) bool {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+
+ b.recent++
+ b.last = time.Now().UTC()
+ return false // never drop events.
+}
+
+var (
+ // DefaultExponentialBackoffConfig provides a default configuration for
+ // exponential backoff.
+ DefaultExponentialBackoffConfig = ExponentialBackoffConfig{
+ Base: time.Second,
+ Factor: time.Second,
+ Max: 20 * time.Second,
+ }
+)
+
+// ExponentialBackoffConfig configures backoff parameters.
+//
+// Note that these parameters operate on the upper bound for choosing a random
+// value. For example, at Base=1s, a random value in [0,1s) will be chosen for
+// the backoff value.
+type ExponentialBackoffConfig struct {
+ // Base is the minimum bound for backing off after failure.
+ Base time.Duration
+
+ // Factor sets the amount of time by which the backoff grows with each
+ // failure.
+ Factor time.Duration
+
+ // Max is the absolute maxiumum bound for a single backoff.
+ Max time.Duration
+}
+
+// ExponentialBackoff implements random backoff with exponentially increasing
+// bounds as the number consecutive failures increase.
+type ExponentialBackoff struct {
+ config ExponentialBackoffConfig
+ failures uint64 // consecutive failure counter.
+}
+
+// NewExponentialBackoff returns an exponential backoff strategy with the
+// desired config. If config is nil, the default is returned.
+func NewExponentialBackoff(config ExponentialBackoffConfig) *ExponentialBackoff {
+ return &ExponentialBackoff{
+ config: config,
+ }
+}
+
+// Proceed returns the next randomly bound exponential backoff time.
+func (b *ExponentialBackoff) Proceed(event Event) time.Duration {
+ return b.backoff(atomic.LoadUint64(&b.failures))
+}
+
+// Success resets the failures counter.
+func (b *ExponentialBackoff) Success(event Event) {
+ atomic.StoreUint64(&b.failures, 0)
+}
+
+// Failure increments the failure counter.
+func (b *ExponentialBackoff) Failure(event Event, err error) bool {
+ atomic.AddUint64(&b.failures, 1)
+ return false
+}
+
+// backoff calculates the amount of time to wait based on the number of
+// consecutive failures.
+func (b *ExponentialBackoff) backoff(failures uint64) time.Duration {
+ if failures <= 0 {
+ // proceed normally when there are no failures.
+ return 0
+ }
+
+ factor := b.config.Factor
+ if factor <= 0 {
+ factor = DefaultExponentialBackoffConfig.Factor
+ }
+
+ backoff := b.config.Base + factor*time.Duration(1<<(failures-1))
+
+ max := b.config.Max
+ if max <= 0 {
+ max = DefaultExponentialBackoffConfig.Max
+ }
+
+ if backoff > max || backoff < 0 {
+ backoff = max
+ }
+
+ // Choose a uniformly distributed value from [0, backoff).
+ return time.Duration(rand.Int63n(int64(backoff)))
+}
diff --git a/vendor/github.com/docker/go-metrics/LICENSE.code b/vendor/github.com/docker/go-metrics/LICENSE.code
new file mode 100644
index 0000000..8f3fee6
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/LICENSE.code
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2013-2016 Docker, Inc.
+
+ 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
+
+ https://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/docker/go-metrics/LICENSE.docs b/vendor/github.com/docker/go-metrics/LICENSE.docs
new file mode 100644
index 0000000..e26cd4f
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/LICENSE.docs
@@ -0,0 +1,425 @@
+Attribution-ShareAlike 4.0 International
+
+=======================================================================
+
+Creative Commons Corporation ("Creative Commons") is not a law firm and
+does not provide legal services or legal advice. Distribution of
+Creative Commons public licenses does not create a lawyer-client or
+other relationship. Creative Commons makes its licenses and related
+information available on an "as-is" basis. Creative Commons gives no
+warranties regarding its licenses, any material licensed under their
+terms and conditions, or any related information. Creative Commons
+disclaims all liability for damages resulting from their use to the
+fullest extent possible.
+
+Using Creative Commons Public Licenses
+
+Creative Commons public licenses provide a standard set of terms and
+conditions that creators and other rights holders may use to share
+original works of authorship and other material subject to copyright
+and certain other rights specified in the public license below. The
+following considerations are for informational purposes only, are not
+exhaustive, and do not form part of our licenses.
+
+ Considerations for licensors: Our public licenses are
+ intended for use by those authorized to give the public
+ permission to use material in ways otherwise restricted by
+ copyright and certain other rights. Our licenses are
+ irrevocable. Licensors should read and understand the terms
+ and conditions of the license they choose before applying it.
+ Licensors should also secure all rights necessary before
+ applying our licenses so that the public can reuse the
+ material as expected. Licensors should clearly mark any
+ material not subject to the license. This includes other CC-
+ licensed material, or material used under an exception or
+ limitation to copyright. More considerations for licensors:
+ wiki.creativecommons.org/Considerations_for_licensors
+
+ Considerations for the public: By using one of our public
+ licenses, a licensor grants the public permission to use the
+ licensed material under specified terms and conditions. If
+ the licensor's permission is not necessary for any reason--for
+ example, because of any applicable exception or limitation to
+ copyright--then that use is not regulated by the license. Our
+ licenses grant only permissions under copyright and certain
+ other rights that a licensor has authority to grant. Use of
+ the licensed material may still be restricted for other
+ reasons, including because others have copyright or other
+ rights in the material. A licensor may make special requests,
+ such as asking that all changes be marked or described.
+ Although not required by our licenses, you are encouraged to
+ respect those requests where reasonable. More_considerations
+ for the public:
+ wiki.creativecommons.org/Considerations_for_licensees
+
+=======================================================================
+
+Creative Commons Attribution-ShareAlike 4.0 International Public
+License
+
+By exercising the Licensed Rights (defined below), You accept and agree
+to be bound by the terms and conditions of this Creative Commons
+Attribution-ShareAlike 4.0 International Public License ("Public
+License"). To the extent this Public License may be interpreted as a
+contract, You are granted the Licensed Rights in consideration of Your
+acceptance of these terms and conditions, and the Licensor grants You
+such rights in consideration of benefits the Licensor receives from
+making the Licensed Material available under these terms and
+conditions.
+
+
+Section 1 -- Definitions.
+
+ a. Adapted Material means material subject to Copyright and Similar
+ Rights that is derived from or based upon the Licensed Material
+ and in which the Licensed Material is translated, altered,
+ arranged, transformed, or otherwise modified in a manner requiring
+ permission under the Copyright and Similar Rights held by the
+ Licensor. For purposes of this Public License, where the Licensed
+ Material is a musical work, performance, or sound recording,
+ Adapted Material is always produced where the Licensed Material is
+ synched in timed relation with a moving image.
+
+ b. Adapter's License means the license You apply to Your Copyright
+ and Similar Rights in Your contributions to Adapted Material in
+ accordance with the terms and conditions of this Public License.
+
+ c. BY-SA Compatible License means a license listed at
+ creativecommons.org/compatiblelicenses, approved by Creative
+ Commons as essentially the equivalent of this Public License.
+
+ d. Copyright and Similar Rights means copyright and/or similar rights
+ closely related to copyright including, without limitation,
+ performance, broadcast, sound recording, and Sui Generis Database
+ Rights, without regard to how the rights are labeled or
+ categorized. For purposes of this Public License, the rights
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
+ Rights.
+
+ e. Effective Technological Measures means those measures that, in the
+ absence of proper authority, may not be circumvented under laws
+ fulfilling obligations under Article 11 of the WIPO Copyright
+ Treaty adopted on December 20, 1996, and/or similar international
+ agreements.
+
+ f. Exceptions and Limitations means fair use, fair dealing, and/or
+ any other exception or limitation to Copyright and Similar Rights
+ that applies to Your use of the Licensed Material.
+
+ g. License Elements means the license attributes listed in the name
+ of a Creative Commons Public License. The License Elements of this
+ Public License are Attribution and ShareAlike.
+
+ h. Licensed Material means the artistic or literary work, database,
+ or other material to which the Licensor applied this Public
+ License.
+
+ i. Licensed Rights means the rights granted to You subject to the
+ terms and conditions of this Public License, which are limited to
+ all Copyright and Similar Rights that apply to Your use of the
+ Licensed Material and that the Licensor has authority to license.
+
+ j. Licensor means the individual(s) or entity(ies) granting rights
+ under this Public License.
+
+ k. Share means to provide material to the public by any means or
+ process that requires permission under the Licensed Rights, such
+ as reproduction, public display, public performance, distribution,
+ dissemination, communication, or importation, and to make material
+ available to the public including in ways that members of the
+ public may access the material from a place and at a time
+ individually chosen by them.
+
+ l. Sui Generis Database Rights means rights other than copyright
+ resulting from Directive 96/9/EC of the European Parliament and of
+ the Council of 11 March 1996 on the legal protection of databases,
+ as amended and/or succeeded, as well as other essentially
+ equivalent rights anywhere in the world.
+
+ m. You means the individual or entity exercising the Licensed Rights
+ under this Public License. Your has a corresponding meaning.
+
+
+Section 2 -- Scope.
+
+ a. License grant.
+
+ 1. Subject to the terms and conditions of this Public License,
+ the Licensor hereby grants You a worldwide, royalty-free,
+ non-sublicensable, non-exclusive, irrevocable license to
+ exercise the Licensed Rights in the Licensed Material to:
+
+ a. reproduce and Share the Licensed Material, in whole or
+ in part; and
+
+ b. produce, reproduce, and Share Adapted Material.
+
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
+ Exceptions and Limitations apply to Your use, this Public
+ License does not apply, and You do not need to comply with
+ its terms and conditions.
+
+ 3. Term. The term of this Public License is specified in Section
+ 6(a).
+
+ 4. Media and formats; technical modifications allowed. The
+ Licensor authorizes You to exercise the Licensed Rights in
+ all media and formats whether now known or hereafter created,
+ and to make technical modifications necessary to do so. The
+ Licensor waives and/or agrees not to assert any right or
+ authority to forbid You from making technical modifications
+ necessary to exercise the Licensed Rights, including
+ technical modifications necessary to circumvent Effective
+ Technological Measures. For purposes of this Public License,
+ simply making modifications authorized by this Section 2(a)
+ (4) never produces Adapted Material.
+
+ 5. Downstream recipients.
+
+ a. Offer from the Licensor -- Licensed Material. Every
+ recipient of the Licensed Material automatically
+ receives an offer from the Licensor to exercise the
+ Licensed Rights under the terms and conditions of this
+ Public License.
+
+ b. Additional offer from the Licensor -- Adapted Material.
+ Every recipient of Adapted Material from You
+ automatically receives an offer from the Licensor to
+ exercise the Licensed Rights in the Adapted Material
+ under the conditions of the Adapter's License You apply.
+
+ c. No downstream restrictions. You may not offer or impose
+ any additional or different terms or conditions on, or
+ apply any Effective Technological Measures to, the
+ Licensed Material if doing so restricts exercise of the
+ Licensed Rights by any recipient of the Licensed
+ Material.
+
+ 6. No endorsement. Nothing in this Public License constitutes or
+ may be construed as permission to assert or imply that You
+ are, or that Your use of the Licensed Material is, connected
+ with, or sponsored, endorsed, or granted official status by,
+ the Licensor or others designated to receive attribution as
+ provided in Section 3(a)(1)(A)(i).
+
+ b. Other rights.
+
+ 1. Moral rights, such as the right of integrity, are not
+ licensed under this Public License, nor are publicity,
+ privacy, and/or other similar personality rights; however, to
+ the extent possible, the Licensor waives and/or agrees not to
+ assert any such rights held by the Licensor to the limited
+ extent necessary to allow You to exercise the Licensed
+ Rights, but not otherwise.
+
+ 2. Patent and trademark rights are not licensed under this
+ Public License.
+
+ 3. To the extent possible, the Licensor waives any right to
+ collect royalties from You for the exercise of the Licensed
+ Rights, whether directly or through a collecting society
+ under any voluntary or waivable statutory or compulsory
+ licensing scheme. In all other cases the Licensor expressly
+ reserves any right to collect such royalties.
+
+
+Section 3 -- License Conditions.
+
+Your exercise of the Licensed Rights is expressly made subject to the
+following conditions.
+
+ a. Attribution.
+
+ 1. If You Share the Licensed Material (including in modified
+ form), You must:
+
+ a. retain the following if it is supplied by the Licensor
+ with the Licensed Material:
+
+ i. identification of the creator(s) of the Licensed
+ Material and any others designated to receive
+ attribution, in any reasonable manner requested by
+ the Licensor (including by pseudonym if
+ designated);
+
+ ii. a copyright notice;
+
+ iii. a notice that refers to this Public License;
+
+ iv. a notice that refers to the disclaimer of
+ warranties;
+
+ v. a URI or hyperlink to the Licensed Material to the
+ extent reasonably practicable;
+
+ b. indicate if You modified the Licensed Material and
+ retain an indication of any previous modifications; and
+
+ c. indicate the Licensed Material is licensed under this
+ Public License, and include the text of, or the URI or
+ hyperlink to, this Public License.
+
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
+ reasonable manner based on the medium, means, and context in
+ which You Share the Licensed Material. For example, it may be
+ reasonable to satisfy the conditions by providing a URI or
+ hyperlink to a resource that includes the required
+ information.
+
+ 3. If requested by the Licensor, You must remove any of the
+ information required by Section 3(a)(1)(A) to the extent
+ reasonably practicable.
+
+ b. ShareAlike.
+
+ In addition to the conditions in Section 3(a), if You Share
+ Adapted Material You produce, the following conditions also apply.
+
+ 1. The Adapter's License You apply must be a Creative Commons
+ license with the same License Elements, this version or
+ later, or a BY-SA Compatible License.
+
+ 2. You must include the text of, or the URI or hyperlink to, the
+ Adapter's License You apply. You may satisfy this condition
+ in any reasonable manner based on the medium, means, and
+ context in which You Share Adapted Material.
+
+ 3. You may not offer or impose any additional or different terms
+ or conditions on, or apply any Effective Technological
+ Measures to, Adapted Material that restrict exercise of the
+ rights granted under the Adapter's License You apply.
+
+
+Section 4 -- Sui Generis Database Rights.
+
+Where the Licensed Rights include Sui Generis Database Rights that
+apply to Your use of the Licensed Material:
+
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
+ to extract, reuse, reproduce, and Share all or a substantial
+ portion of the contents of the database;
+
+ b. if You include all or a substantial portion of the database
+ contents in a database in which You have Sui Generis Database
+ Rights, then the database in which You have Sui Generis Database
+ Rights (but not its individual contents) is Adapted Material,
+
+ including for purposes of Section 3(b); and
+ c. You must comply with the conditions in Section 3(a) if You Share
+ all or a substantial portion of the contents of the database.
+
+For the avoidance of doubt, this Section 4 supplements and does not
+replace Your obligations under this Public License where the Licensed
+Rights include other Copyright and Similar Rights.
+
+
+Section 5 -- Disclaimer of Warranties and Limitation of Liability.
+
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
+
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
+
+ c. The disclaimer of warranties and limitation of liability provided
+ above shall be interpreted in a manner that, to the extent
+ possible, most closely approximates an absolute disclaimer and
+ waiver of all liability.
+
+
+Section 6 -- Term and Termination.
+
+ a. This Public License applies for the term of the Copyright and
+ Similar Rights licensed here. However, if You fail to comply with
+ this Public License, then Your rights under this Public License
+ terminate automatically.
+
+ b. Where Your right to use the Licensed Material has terminated under
+ Section 6(a), it reinstates:
+
+ 1. automatically as of the date the violation is cured, provided
+ it is cured within 30 days of Your discovery of the
+ violation; or
+
+ 2. upon express reinstatement by the Licensor.
+
+ For the avoidance of doubt, this Section 6(b) does not affect any
+ right the Licensor may have to seek remedies for Your violations
+ of this Public License.
+
+ c. For the avoidance of doubt, the Licensor may also offer the
+ Licensed Material under separate terms or conditions or stop
+ distributing the Licensed Material at any time; however, doing so
+ will not terminate this Public License.
+
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
+ License.
+
+
+Section 7 -- Other Terms and Conditions.
+
+ a. The Licensor shall not be bound by any additional or different
+ terms or conditions communicated by You unless expressly agreed.
+
+ b. Any arrangements, understandings, or agreements regarding the
+ Licensed Material not stated herein are separate from and
+ independent of the terms and conditions of this Public License.
+
+
+Section 8 -- Interpretation.
+
+ a. For the avoidance of doubt, this Public License does not, and
+ shall not be interpreted to, reduce, limit, restrict, or impose
+ conditions on any use of the Licensed Material that could lawfully
+ be made without permission under this Public License.
+
+ b. To the extent possible, if any provision of this Public License is
+ deemed unenforceable, it shall be automatically reformed to the
+ minimum extent necessary to make it enforceable. If the provision
+ cannot be reformed, it shall be severed from this Public License
+ without affecting the enforceability of the remaining terms and
+ conditions.
+
+ c. No term or condition of this Public License will be waived and no
+ failure to comply consented to unless expressly agreed to by the
+ Licensor.
+
+ d. Nothing in this Public License constitutes or may be interpreted
+ as a limitation upon, or waiver of, any privileges and immunities
+ that apply to the Licensor or You, including from the legal
+ processes of any jurisdiction or authority.
+
+
+=======================================================================
+
+Creative Commons is not a party to its public licenses.
+Notwithstanding, Creative Commons may elect to apply one of its public
+licenses to material it publishes and in those instances will be
+considered the "Licensor." Except for the limited purpose of indicating
+that material is shared under a Creative Commons public license or as
+otherwise permitted by the Creative Commons policies published at
+creativecommons.org/policies, Creative Commons does not authorize the
+use of the trademark "Creative Commons" or any other trademark or logo
+of Creative Commons without its prior written consent including,
+without limitation, in connection with any unauthorized modifications
+to any of its public licenses or any other arrangements,
+understandings, or agreements concerning use of licensed material. For
+the avoidance of doubt, this paragraph does not form part of the public
+licenses.
+
+Creative Commons may be contacted at creativecommons.org.
diff --git a/vendor/github.com/docker/go-metrics/NOTICE b/vendor/github.com/docker/go-metrics/NOTICE
new file mode 100644
index 0000000..8915f02
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/NOTICE
@@ -0,0 +1,16 @@
+Docker
+Copyright 2012-2015 Docker, Inc.
+
+This product includes software developed at Docker, Inc. (https://www.docker.com).
+
+The following is courtesy of our legal counsel:
+
+
+Use and transfer of Docker may be subject to certain restrictions by the
+United States and other governments.
+It is your responsibility to ensure that your use and/or transfer does not
+violate applicable laws.
+
+For more information, please see https://www.bis.doc.gov
+
+See also https://www.apache.org/dev/crypto.html and/or seek legal counsel.
diff --git a/vendor/github.com/docker/go-metrics/README.md b/vendor/github.com/docker/go-metrics/README.md
new file mode 100644
index 0000000..fdf7fb7
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/README.md
@@ -0,0 +1,79 @@
+# go-metrics [![GoDoc](https://godoc.org/github.com/docker/go-metrics?status.svg)](https://godoc.org/github.com/docker/go-metrics) ![Badge Badge](http://doyouevenbadge.com/github.com/docker/go-metrics)
+
+This package is small wrapper around the prometheus go client to help enforce convention and best practices for metrics collection in Docker projects.
+
+## Best Practices
+
+This packages is meant to be used for collecting metrics in Docker projects.
+It is not meant to be used as a replacement for the prometheus client but to help enforce consistent naming across metrics collected.
+If you have not already read the prometheus best practices around naming and labels you can read the page [here](https://prometheus.io/docs/practices/naming/).
+
+The following are a few Docker specific rules that will help you name and work with metrics in your project.
+
+1. Namespace and Subsystem
+
+This package provides you with a namespace type that allows you to specify the same namespace and subsystem for your metrics.
+
+```go
+ns := metrics.NewNamespace("engine", "daemon", metrics.Labels{
+ "version": dockerversion.Version,
+ "commit": dockerversion.GitCommit,
+})
+```
+
+In the example above we are creating metrics for the Docker engine's daemon package.
+`engine` would be the namespace in this example where `daemon` is the subsystem or package where we are collecting the metrics.
+
+A namespace also allows you to attach constant labels to the metrics such as the git commit and version that it is collecting.
+
+2. Declaring your Metrics
+
+Try to keep all your metric declarations in one file.
+This makes it easy for others to see what constant labels are defined on the namespace and what labels are defined on the metrics when they are created.
+
+3. Use labels instead of multiple metrics
+
+Labels allow you to define one metric such as the time it takes to perform a certain action on an object.
+If we wanted to collect timings on various container actions such as create, start, and delete then we can define one metric called `container_actions` and use labels to specify the type of action.
+
+
+```go
+containerActions = ns.NewLabeledTimer("container_actions", "The number of milliseconds it takes to process each container action", "action")
+```
+
+The last parameter is the label name or key.
+When adding a data point to the metric you will use the `WithValues` function to specify the `action` that you are collecting for.
+
+```go
+containerActions.WithValues("create").UpdateSince(start)
+```
+
+4. Always use a unit
+
+The metric name should describe what you are measuring but you also need to provide the unit that it is being measured with.
+For a timer, the standard unit is seconds and a counter's standard unit is a total.
+For gauges you must provide the unit.
+This package provides a standard set of units for use within the Docker projects.
+
+```go
+Nanoseconds Unit = "nanoseconds"
+Seconds Unit = "seconds"
+Bytes Unit = "bytes"
+Total Unit = "total"
+```
+
+If you need to use a unit but it is not defined in the package please open a PR to add it but first try to see if one of the already created units will work for your metric, i.e. seconds or nanoseconds vs adding milliseconds.
+
+## Docs
+
+Package documentation can be found [here](https://godoc.org/github.com/docker/go-metrics).
+
+## Additional Metrics
+
+Additional metrics are also defined here that are not avaliable in the prometheus client.
+If you need a custom metrics and it is generic enough to be used by multiple projects, define it here.
+
+
+## Copyright and license
+
+Copyright © 2016 Docker, Inc. All rights reserved, except as follows. Code is released under the Apache 2.0 license. The README.md file, and files in the "docs" folder are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file "LICENSE.docs". You may obtain a duplicate copy of the same license, titled CC-BY-SA-4.0, at http://creativecommons.org/licenses/by/4.0/.
diff --git a/vendor/github.com/docker/go-metrics/counter.go b/vendor/github.com/docker/go-metrics/counter.go
new file mode 100644
index 0000000..fe36316
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/counter.go
@@ -0,0 +1,52 @@
+package metrics
+
+import "github.com/prometheus/client_golang/prometheus"
+
+// Counter is a metrics that can only increment its current count
+type Counter interface {
+ // Inc adds Sum(vs) to the counter. Sum(vs) must be positive.
+ //
+ // If len(vs) == 0, increments the counter by 1.
+ Inc(vs ...float64)
+}
+
+// LabeledCounter is counter that must have labels populated before use.
+type LabeledCounter interface {
+ WithValues(vs ...string) Counter
+}
+
+type labeledCounter struct {
+ pc *prometheus.CounterVec
+}
+
+func (lc *labeledCounter) WithValues(vs ...string) Counter {
+ return &counter{pc: lc.pc.WithLabelValues(vs...)}
+}
+
+func (lc *labeledCounter) Describe(ch chan<- *prometheus.Desc) {
+ lc.pc.Describe(ch)
+}
+
+func (lc *labeledCounter) Collect(ch chan<- prometheus.Metric) {
+ lc.pc.Collect(ch)
+}
+
+type counter struct {
+ pc prometheus.Counter
+}
+
+func (c *counter) Inc(vs ...float64) {
+ if len(vs) == 0 {
+ c.pc.Inc()
+ }
+
+ c.pc.Add(sumFloat64(vs...))
+}
+
+func (c *counter) Describe(ch chan<- *prometheus.Desc) {
+ c.pc.Describe(ch)
+}
+
+func (c *counter) Collect(ch chan<- prometheus.Metric) {
+ c.pc.Collect(ch)
+}
diff --git a/vendor/github.com/docker/go-metrics/docs.go b/vendor/github.com/docker/go-metrics/docs.go
new file mode 100644
index 0000000..8fbdfc6
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/docs.go
@@ -0,0 +1,3 @@
+// This package is small wrapper around the prometheus go client to help enforce convention and best practices for metrics collection in Docker projects.
+
+package metrics
diff --git a/vendor/github.com/docker/go-metrics/gauge.go b/vendor/github.com/docker/go-metrics/gauge.go
new file mode 100644
index 0000000..74296e8
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/gauge.go
@@ -0,0 +1,72 @@
+package metrics
+
+import "github.com/prometheus/client_golang/prometheus"
+
+// Gauge is a metric that allows incrementing and decrementing a value
+type Gauge interface {
+ Inc(...float64)
+ Dec(...float64)
+
+ // Add adds the provided value to the gauge's current value
+ Add(float64)
+
+ // Set replaces the gauge's current value with the provided value
+ Set(float64)
+}
+
+// LabeledGauge describes a gauge the must have values populated before use.
+type LabeledGauge interface {
+ WithValues(labels ...string) Gauge
+}
+
+type labeledGauge struct {
+ pg *prometheus.GaugeVec
+}
+
+func (lg *labeledGauge) WithValues(labels ...string) Gauge {
+ return &gauge{pg: lg.pg.WithLabelValues(labels...)}
+}
+
+func (lg *labeledGauge) Describe(c chan<- *prometheus.Desc) {
+ lg.pg.Describe(c)
+}
+
+func (lg *labeledGauge) Collect(c chan<- prometheus.Metric) {
+ lg.pg.Collect(c)
+}
+
+type gauge struct {
+ pg prometheus.Gauge
+}
+
+func (g *gauge) Inc(vs ...float64) {
+ if len(vs) == 0 {
+ g.pg.Inc()
+ }
+
+ g.Add(sumFloat64(vs...))
+}
+
+func (g *gauge) Dec(vs ...float64) {
+ if len(vs) == 0 {
+ g.pg.Dec()
+ }
+
+ g.Add(-sumFloat64(vs...))
+}
+
+func (g *gauge) Add(v float64) {
+ g.pg.Add(v)
+}
+
+func (g *gauge) Set(v float64) {
+ g.pg.Set(v)
+}
+
+func (g *gauge) Describe(c chan<- *prometheus.Desc) {
+ g.pg.Describe(c)
+}
+
+func (g *gauge) Collect(c chan<- prometheus.Metric) {
+ g.pg.Collect(c)
+}
diff --git a/vendor/github.com/docker/go-metrics/handler.go b/vendor/github.com/docker/go-metrics/handler.go
new file mode 100644
index 0000000..bb3be41
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/handler.go
@@ -0,0 +1,13 @@
+package metrics
+
+import (
+ "net/http"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+// Handler returns the global http.Handler that provides the prometheus
+// metrics format on GET requests
+func Handler() http.Handler {
+ return prometheus.Handler()
+}
diff --git a/vendor/github.com/docker/go-metrics/helpers.go b/vendor/github.com/docker/go-metrics/helpers.go
new file mode 100644
index 0000000..68b7f51
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/helpers.go
@@ -0,0 +1,10 @@
+package metrics
+
+func sumFloat64(vs ...float64) float64 {
+ var sum float64
+ for _, v := range vs {
+ sum += v
+ }
+
+ return sum
+}
diff --git a/vendor/github.com/docker/go-metrics/namespace.go b/vendor/github.com/docker/go-metrics/namespace.go
new file mode 100644
index 0000000..7734c29
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/namespace.go
@@ -0,0 +1,181 @@
+package metrics
+
+import (
+ "fmt"
+ "sync"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+type Labels map[string]string
+
+// NewNamespace returns a namespaces that is responsible for managing a collection of
+// metrics for a particual namespace and subsystem
+//
+// labels allows const labels to be added to all metrics created in this namespace
+// and are commonly used for data like application version and git commit
+func NewNamespace(name, subsystem string, labels Labels) *Namespace {
+ if labels == nil {
+ labels = make(map[string]string)
+ }
+ return &Namespace{
+ name: name,
+ subsystem: subsystem,
+ labels: labels,
+ }
+}
+
+// Namespace describes a set of metrics that share a namespace and subsystem.
+type Namespace struct {
+ name string
+ subsystem string
+ labels Labels
+ mu sync.Mutex
+ metrics []prometheus.Collector
+}
+
+// WithConstLabels returns a namespace with the provided set of labels merged
+// with the existing constant labels on the namespace.
+//
+// Only metrics created with the returned namespace will get the new constant
+// labels. The returned namespace must be registered separately.
+func (n *Namespace) WithConstLabels(labels Labels) *Namespace {
+ n.mu.Lock()
+ ns := &Namespace{
+ name: n.name,
+ subsystem: n.subsystem,
+ labels: mergeLabels(n.labels, labels),
+ }
+ n.mu.Unlock()
+ return ns
+}
+
+func (n *Namespace) NewCounter(name, help string) Counter {
+ c := &counter{pc: prometheus.NewCounter(n.newCounterOpts(name, help))}
+ n.Add(c)
+ return c
+}
+
+func (n *Namespace) NewLabeledCounter(name, help string, labels ...string) LabeledCounter {
+ c := &labeledCounter{pc: prometheus.NewCounterVec(n.newCounterOpts(name, help), labels)}
+ n.Add(c)
+ return c
+}
+
+func (n *Namespace) newCounterOpts(name, help string) prometheus.CounterOpts {
+ return prometheus.CounterOpts{
+ Namespace: n.name,
+ Subsystem: n.subsystem,
+ Name: makeName(name, Total),
+ Help: help,
+ ConstLabels: prometheus.Labels(n.labels),
+ }
+}
+
+func (n *Namespace) NewTimer(name, help string) Timer {
+ t := &timer{
+ m: prometheus.NewHistogram(n.newTimerOpts(name, help)),
+ }
+ n.Add(t)
+ return t
+}
+
+func (n *Namespace) NewLabeledTimer(name, help string, labels ...string) LabeledTimer {
+ t := &labeledTimer{
+ m: prometheus.NewHistogramVec(n.newTimerOpts(name, help), labels),
+ }
+ n.Add(t)
+ return t
+}
+
+func (n *Namespace) newTimerOpts(name, help string) prometheus.HistogramOpts {
+ return prometheus.HistogramOpts{
+ Namespace: n.name,
+ Subsystem: n.subsystem,
+ Name: makeName(name, Seconds),
+ Help: help,
+ ConstLabels: prometheus.Labels(n.labels),
+ }
+}
+
+func (n *Namespace) NewGauge(name, help string, unit Unit) Gauge {
+ g := &gauge{
+ pg: prometheus.NewGauge(n.newGaugeOpts(name, help, unit)),
+ }
+ n.Add(g)
+ return g
+}
+
+func (n *Namespace) NewLabeledGauge(name, help string, unit Unit, labels ...string) LabeledGauge {
+ g := &labeledGauge{
+ pg: prometheus.NewGaugeVec(n.newGaugeOpts(name, help, unit), labels),
+ }
+ n.Add(g)
+ return g
+}
+
+func (n *Namespace) newGaugeOpts(name, help string, unit Unit) prometheus.GaugeOpts {
+ return prometheus.GaugeOpts{
+ Namespace: n.name,
+ Subsystem: n.subsystem,
+ Name: makeName(name, unit),
+ Help: help,
+ ConstLabels: prometheus.Labels(n.labels),
+ }
+}
+
+func (n *Namespace) Describe(ch chan<- *prometheus.Desc) {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+
+ for _, metric := range n.metrics {
+ metric.Describe(ch)
+ }
+}
+
+func (n *Namespace) Collect(ch chan<- prometheus.Metric) {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+
+ for _, metric := range n.metrics {
+ metric.Collect(ch)
+ }
+}
+
+func (n *Namespace) Add(collector prometheus.Collector) {
+ n.mu.Lock()
+ n.metrics = append(n.metrics, collector)
+ n.mu.Unlock()
+}
+
+func (n *Namespace) NewDesc(name, help string, unit Unit, labels ...string) *prometheus.Desc {
+ name = makeName(name, unit)
+ namespace := n.name
+ if n.subsystem != "" {
+ namespace = fmt.Sprintf("%s_%s", namespace, n.subsystem)
+ }
+ name = fmt.Sprintf("%s_%s", namespace, name)
+ return prometheus.NewDesc(name, help, labels, prometheus.Labels(n.labels))
+}
+
+// mergeLabels merges two or more labels objects into a single map, favoring
+// the later labels.
+func mergeLabels(lbs ...Labels) Labels {
+ merged := make(Labels)
+
+ for _, target := range lbs {
+ for k, v := range target {
+ merged[k] = v
+ }
+ }
+
+ return merged
+}
+
+func makeName(name string, unit Unit) string {
+ if unit == "" {
+ return name
+ }
+
+ return fmt.Sprintf("%s_%s", name, unit)
+}
diff --git a/vendor/github.com/docker/go-metrics/register.go b/vendor/github.com/docker/go-metrics/register.go
new file mode 100644
index 0000000..708358d
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/register.go
@@ -0,0 +1,15 @@
+package metrics
+
+import "github.com/prometheus/client_golang/prometheus"
+
+// Register adds all the metrics in the provided namespace to the global
+// metrics registry
+func Register(n *Namespace) {
+ prometheus.MustRegister(n)
+}
+
+// Deregister removes all the metrics in the provided namespace from the
+// global metrics registry
+func Deregister(n *Namespace) {
+ prometheus.Unregister(n)
+}
diff --git a/vendor/github.com/docker/go-metrics/timer.go b/vendor/github.com/docker/go-metrics/timer.go
new file mode 100644
index 0000000..e91eca7
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/timer.go
@@ -0,0 +1,68 @@
+package metrics
+
+import (
+ "time"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+// StartTimer begins a timer observation at the callsite. When the target
+// operation is completed, the caller should call the return done func().
+func StartTimer(timer Timer) (done func()) {
+ start := time.Now()
+ return func() {
+ timer.Update(time.Since(start))
+ }
+}
+
+// Timer is a metric that allows collecting the duration of an action in seconds
+type Timer interface {
+ // Update records an observation, duration, and converts to the target
+ // units.
+ Update(duration time.Duration)
+
+ // UpdateSince will add the duration from the provided starting time to the
+ // timer's summary with the precisions that was used in creation of the timer
+ UpdateSince(time.Time)
+}
+
+// LabeledTimer is a timer that must have label values populated before use.
+type LabeledTimer interface {
+ WithValues(labels ...string) Timer
+}
+
+type labeledTimer struct {
+ m *prometheus.HistogramVec
+}
+
+func (lt *labeledTimer) WithValues(labels ...string) Timer {
+ return &timer{m: lt.m.WithLabelValues(labels...)}
+}
+
+func (lt *labeledTimer) Describe(c chan<- *prometheus.Desc) {
+ lt.m.Describe(c)
+}
+
+func (lt *labeledTimer) Collect(c chan<- prometheus.Metric) {
+ lt.m.Collect(c)
+}
+
+type timer struct {
+ m prometheus.Histogram
+}
+
+func (t *timer) Update(duration time.Duration) {
+ t.m.Observe(duration.Seconds())
+}
+
+func (t *timer) UpdateSince(since time.Time) {
+ t.m.Observe(time.Since(since).Seconds())
+}
+
+func (t *timer) Describe(c chan<- *prometheus.Desc) {
+ t.m.Describe(c)
+}
+
+func (t *timer) Collect(c chan<- prometheus.Metric) {
+ t.m.Collect(c)
+}
diff --git a/vendor/github.com/docker/go-metrics/unit.go b/vendor/github.com/docker/go-metrics/unit.go
new file mode 100644
index 0000000..c96622f
--- /dev/null
+++ b/vendor/github.com/docker/go-metrics/unit.go
@@ -0,0 +1,12 @@
+package metrics
+
+// Unit represents the type or precision of a metric that is appended to
+// the metrics fully qualified name
+type Unit string
+
+const (
+ Nanoseconds Unit = "nanoseconds"
+ Seconds Unit = "seconds"
+ Bytes Unit = "bytes"
+ Total Unit = "total"
+)
diff --git a/vendor/github.com/docker/go-units/LICENSE b/vendor/github.com/docker/go-units/LICENSE
new file mode 100644
index 0000000..b55b37b
--- /dev/null
+++ b/vendor/github.com/docker/go-units/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2015 Docker, Inc.
+
+ 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
+
+ https://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/docker/go-units/README.md b/vendor/github.com/docker/go-units/README.md
new file mode 100644
index 0000000..4f70a4e
--- /dev/null
+++ b/vendor/github.com/docker/go-units/README.md
@@ -0,0 +1,16 @@
+[![GoDoc](https://godoc.org/github.com/docker/go-units?status.svg)](https://godoc.org/github.com/docker/go-units)
+
+# Introduction
+
+go-units is a library to transform human friendly measurements into machine friendly values.
+
+## Usage
+
+See the [docs in godoc](https://godoc.org/github.com/docker/go-units) for examples and documentation.
+
+## Copyright and license
+
+Copyright © 2015 Docker, Inc.
+
+go-units is licensed under the Apache License, Version 2.0.
+See [LICENSE](LICENSE) for the full text of the license.
diff --git a/vendor/github.com/docker/go-units/duration.go b/vendor/github.com/docker/go-units/duration.go
new file mode 100644
index 0000000..ba02af2
--- /dev/null
+++ b/vendor/github.com/docker/go-units/duration.go
@@ -0,0 +1,35 @@
+// Package units provides helper function to parse and print size and time units
+// in human-readable format.
+package units
+
+import (
+ "fmt"
+ "time"
+)
+
+// HumanDuration returns a human-readable approximation of a duration
+// (eg. "About a minute", "4 hours ago", etc.).
+func HumanDuration(d time.Duration) string {
+ if seconds := int(d.Seconds()); seconds < 1 {
+ return "Less than a second"
+ } else if seconds == 1 {
+ return "1 second"
+ } else if seconds < 60 {
+ return fmt.Sprintf("%d seconds", seconds)
+ } else if minutes := int(d.Minutes()); minutes == 1 {
+ return "About a minute"
+ } else if minutes < 46 {
+ return fmt.Sprintf("%d minutes", minutes)
+ } else if hours := int(d.Hours() + 0.5); hours == 1 {
+ return "About an hour"
+ } else if hours < 48 {
+ return fmt.Sprintf("%d hours", hours)
+ } else if hours < 24*7*2 {
+ return fmt.Sprintf("%d days", hours/24)
+ } else if hours < 24*30*2 {
+ return fmt.Sprintf("%d weeks", hours/24/7)
+ } else if hours < 24*365*2 {
+ return fmt.Sprintf("%d months", hours/24/30)
+ }
+ return fmt.Sprintf("%d years", int(d.Hours())/24/365)
+}
diff --git a/vendor/github.com/docker/go-units/size.go b/vendor/github.com/docker/go-units/size.go
new file mode 100644
index 0000000..44616c2
--- /dev/null
+++ b/vendor/github.com/docker/go-units/size.go
@@ -0,0 +1,108 @@
+package units
+
+import (
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+// See: http://en.wikipedia.org/wiki/Binary_prefix
+const (
+ // Decimal
+
+ KB = 1000
+ MB = 1000 * KB
+ GB = 1000 * MB
+ TB = 1000 * GB
+ PB = 1000 * TB
+
+ // Binary
+
+ KiB = 1024
+ MiB = 1024 * KiB
+ GiB = 1024 * MiB
+ TiB = 1024 * GiB
+ PiB = 1024 * TiB
+)
+
+type unitMap map[string]int64
+
+var (
+ decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB}
+ binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB}
+ sizeRegex = regexp.MustCompile(`^(\d+(\.\d+)*) ?([kKmMgGtTpP])?[bB]?$`)
+)
+
+var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
+var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
+
+func getSizeAndUnit(size float64, base float64, _map []string) (float64, string) {
+ i := 0
+ unitsLimit := len(_map) - 1
+ for size >= base && i < unitsLimit {
+ size = size / base
+ i++
+ }
+ return size, _map[i]
+}
+
+// CustomSize returns a human-readable approximation of a size
+// using custom format.
+func CustomSize(format string, size float64, base float64, _map []string) string {
+ size, unit := getSizeAndUnit(size, base, _map)
+ return fmt.Sprintf(format, size, unit)
+}
+
+// HumanSizeWithPrecision allows the size to be in any precision,
+// instead of 4 digit precision used in units.HumanSize.
+func HumanSizeWithPrecision(size float64, precision int) string {
+ size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs)
+ return fmt.Sprintf("%.*g%s", precision, size, unit)
+}
+
+// HumanSize returns a human-readable approximation of a size
+// capped at 4 valid numbers (eg. "2.746 MB", "796 KB").
+func HumanSize(size float64) string {
+ return HumanSizeWithPrecision(size, 4)
+}
+
+// BytesSize returns a human-readable size in bytes, kibibytes,
+// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB").
+func BytesSize(size float64) string {
+ return CustomSize("%.4g%s", size, 1024.0, binaryAbbrs)
+}
+
+// FromHumanSize returns an integer from a human-readable specification of a
+// size using SI standard (eg. "44kB", "17MB").
+func FromHumanSize(size string) (int64, error) {
+ return parseSize(size, decimalMap)
+}
+
+// RAMInBytes parses a human-readable string representing an amount of RAM
+// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and
+// returns the number of bytes, or -1 if the string is unparseable.
+// Units are case-insensitive, and the 'b' suffix is optional.
+func RAMInBytes(size string) (int64, error) {
+ return parseSize(size, binaryMap)
+}
+
+// Parses the human-readable size string into the amount it represents.
+func parseSize(sizeStr string, uMap unitMap) (int64, error) {
+ matches := sizeRegex.FindStringSubmatch(sizeStr)
+ if len(matches) != 4 {
+ return -1, fmt.Errorf("invalid size: '%s'", sizeStr)
+ }
+
+ size, err := strconv.ParseFloat(matches[1], 64)
+ if err != nil {
+ return -1, err
+ }
+
+ unitPrefix := strings.ToLower(matches[3])
+ if mul, ok := uMap[unitPrefix]; ok {
+ size *= float64(mul)
+ }
+
+ return int64(size), nil
+}
diff --git a/vendor/github.com/docker/go-units/ulimit.go b/vendor/github.com/docker/go-units/ulimit.go
new file mode 100644
index 0000000..5ac7fd8
--- /dev/null
+++ b/vendor/github.com/docker/go-units/ulimit.go
@@ -0,0 +1,118 @@
+package units
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// Ulimit is a human friendly version of Rlimit.
+type Ulimit struct {
+ Name string
+ Hard int64
+ Soft int64
+}
+
+// Rlimit specifies the resource limits, such as max open files.
+type Rlimit struct {
+ Type int `json:"type,omitempty"`
+ Hard uint64 `json:"hard,omitempty"`
+ Soft uint64 `json:"soft,omitempty"`
+}
+
+const (
+ // magic numbers for making the syscall
+ // some of these are defined in the syscall package, but not all.
+ // Also since Windows client doesn't get access to the syscall package, need to
+ // define these here
+ rlimitAs = 9
+ rlimitCore = 4
+ rlimitCPU = 0
+ rlimitData = 2
+ rlimitFsize = 1
+ rlimitLocks = 10
+ rlimitMemlock = 8
+ rlimitMsgqueue = 12
+ rlimitNice = 13
+ rlimitNofile = 7
+ rlimitNproc = 6
+ rlimitRss = 5
+ rlimitRtprio = 14
+ rlimitRttime = 15
+ rlimitSigpending = 11
+ rlimitStack = 3
+)
+
+var ulimitNameMapping = map[string]int{
+ //"as": rlimitAs, // Disabled since this doesn't seem usable with the way Docker inits a container.
+ "core": rlimitCore,
+ "cpu": rlimitCPU,
+ "data": rlimitData,
+ "fsize": rlimitFsize,
+ "locks": rlimitLocks,
+ "memlock": rlimitMemlock,
+ "msgqueue": rlimitMsgqueue,
+ "nice": rlimitNice,
+ "nofile": rlimitNofile,
+ "nproc": rlimitNproc,
+ "rss": rlimitRss,
+ "rtprio": rlimitRtprio,
+ "rttime": rlimitRttime,
+ "sigpending": rlimitSigpending,
+ "stack": rlimitStack,
+}
+
+// ParseUlimit parses and returns a Ulimit from the specified string.
+func ParseUlimit(val string) (*Ulimit, error) {
+ parts := strings.SplitN(val, "=", 2)
+ if len(parts) != 2 {
+ return nil, fmt.Errorf("invalid ulimit argument: %s", val)
+ }
+
+ if _, exists := ulimitNameMapping[parts[0]]; !exists {
+ return nil, fmt.Errorf("invalid ulimit type: %s", parts[0])
+ }
+
+ var (
+ soft int64
+ hard = &soft // default to soft in case no hard was set
+ temp int64
+ err error
+ )
+ switch limitVals := strings.Split(parts[1], ":"); len(limitVals) {
+ case 2:
+ temp, err = strconv.ParseInt(limitVals[1], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ hard = &temp
+ fallthrough
+ case 1:
+ soft, err = strconv.ParseInt(limitVals[0], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ default:
+ return nil, fmt.Errorf("too many limit value arguments - %s, can only have up to two, `soft[:hard]`", parts[1])
+ }
+
+ if soft > *hard {
+ return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: %d > %d", soft, *hard)
+ }
+
+ return &Ulimit{Name: parts[0], Soft: soft, Hard: *hard}, nil
+}
+
+// GetRlimit returns the RLimit corresponding to Ulimit.
+func (u *Ulimit) GetRlimit() (*Rlimit, error) {
+ t, exists := ulimitNameMapping[u.Name]
+ if !exists {
+ return nil, fmt.Errorf("invalid ulimit name %s", u.Name)
+ }
+
+ return &Rlimit{Type: t, Soft: uint64(u.Soft), Hard: uint64(u.Hard)}, nil
+}
+
+func (u *Ulimit) String() string {
+ return fmt.Sprintf("%s=%d:%d", u.Name, u.Soft, u.Hard)
+}
diff --git a/vendor/github.com/docker/go/LICENSE b/vendor/github.com/docker/go/LICENSE
new file mode 100644
index 0000000..7448756
--- /dev/null
+++ b/vendor/github.com/docker/go/LICENSE
@@ -0,0 +1,27 @@
+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/docker/go/README.md b/vendor/github.com/docker/go/README.md
new file mode 100644
index 0000000..730b880
--- /dev/null
+++ b/vendor/github.com/docker/go/README.md
@@ -0,0 +1,16 @@
+[![Circle CI](https://circleci.com/gh/docker/go.svg?style=svg)](https://circleci.com/gh/docker/go)
+
+This is a repository used for building go packages based off upstream with
+small patches.
+
+It is only used so far for a canonical json pkg.
+
+I hope we do not need to use it for anything else in the future.
+
+**To update:**
+
+```console
+$ make update
+```
+
+This will nuke the current package, clone upstream and apply the patch.
diff --git a/vendor/github.com/docker/go/canonical/json/decode.go b/vendor/github.com/docker/go/canonical/json/decode.go
new file mode 100644
index 0000000..72b981c
--- /dev/null
+++ b/vendor/github.com/docker/go/canonical/json/decode.go
@@ -0,0 +1,1168 @@
+// 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 string-keyed 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.
+//
+// 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 objects
+// 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
+ canonical bool
+}
+
+// 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 {
+ 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)
+ }
+}
+
+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 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, reflect.Value{}
+ }
+ if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
+ return nil, u, reflect.Value{}
+ }
+ }
+ 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")
+
+// 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 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
+ switch v.Kind() {
+ case reflect.Map:
+ // map must have string kind
+ t := v.Type()
+ if t.Key().Kind() != reflect.String {
+ 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
+
+ for {
+ // Read opening " of string key or closing }.
+ op := d.scanWhile(scanSkipSpace)
+ if op == scanEndObject {
+ // closing } - can only happen on first iteration.
+ break
+ }
+ if op != scanBeginLiteral {
+ d.error(errPhase)
+ }
+
+ // Read key.
+ start := d.off - 1
+ op = d.scanWhile(scanContinue)
+ item := d.data[start : d.off-1]
+ 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(), false)
+ 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 {
+ kv := reflect.ValueOf(key).Convert(v.Type().Key())
+ v.SetMapIndex(kv, subv)
+ }
+
+ // Next token must be , or }.
+ op = d.scanWhile(scanSkipSpace)
+ if op == scanEndObject {
+ break
+ }
+ if op != scanObjectValue {
+ d.error(errPhase)
+ }
+ }
+}
+
+// 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()
+ }
+}
+
+// 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 {
+ 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() map[string]interface{} {
+ m := make(map[string]interface{})
+ for {
+ // Read opening " of string key or closing }.
+ op := d.scanWhile(scanSkipSpace)
+ if op == scanEndObject {
+ // closing } - can only happen on first iteration.
+ break
+ }
+ if op != scanBeginLiteral {
+ d.error(errPhase)
+ }
+
+ // Read string key.
+ start := d.off - 1
+ op = d.scanWhile(scanContinue)
+ item := d.data[start : d.off-1]
+ 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
+ }
+}
+
+// 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/github.com/docker/go/canonical/json/encode.go b/vendor/github.com/docker/go/canonical/json/encode.go
new file mode 100644
index 0000000..f3491b1
--- /dev/null
+++ b/vendor/github.com/docker/go/canonical/json/encode.go
@@ -0,0 +1,1250 @@
+// 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 objects as defined in
+// RFC 4627. The mapping between JSON objects 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.
+//
+// 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 object.
+//
+// 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 be string; 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 object.
+//
+// Interface values encode as the value contained in the interface.
+// A nil interface value encodes as the null JSON object.
+//
+// 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) {
+ return marshal(v, false)
+}
+
+// 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
+}
+
+// MarshalCanonical is like Marshal but encodes into Canonical JSON.
+// Read more at: http://wiki.laptop.org/go/Canonical_JSON
+func MarshalCanonical(v interface{}) ([]byte, error) {
+ return marshal(v, true)
+}
+
+func marshal(v interface{}, canonical bool) ([]byte, error) {
+ e := &encodeState{canonical: canonical}
+ err := e.marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ return e.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 <script> tags.
+// For historical reasons, web browsers don't honor standard HTML
+// escaping within <script> tags, so an alternative JSON encoding must
+// be used.
+func HTMLEscape(dst *bytes.Buffer, src []byte) {
+ // The characters can only appear in string literals,
+ // so just scan the string one byte at a time.
+ start := 0
+ for i, c := range src {
+ if c == '<' || c == '>' || c == '&' {
+ if start < i {
+ dst.Write(src[start:i])
+ }
+ dst.WriteString(`\u00`)
+ dst.WriteByte(hex[c>>4])
+ dst.WriteByte(hex[c&0xF])
+ start = i + 1
+ }
+ // Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9).
+ if c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 {
+ if start < i {
+ dst.Write(src[start:i])
+ }
+ dst.WriteString(`\u202`)
+ dst.WriteByte(hex[src[i+2]&0xF])
+ start = i + 3
+ }
+ }
+ if start < len(src) {
+ dst.Write(src[start:])
+ }
+}
+
+// Marshaler is the interface implemented by objects that
+// can marshal themselves into valid JSON.
+type Marshaler interface {
+ MarshalJSON() ([]byte, error)
+}
+
+// An UnsupportedTypeError is returned by Marshal when attempting
+// to encode an unsupported value type.
+type UnsupportedTypeError struct {
+ Type reflect.Type
+}
+
+func (e *UnsupportedTypeError) Error() string {
+ return "json: unsupported type: " + e.Type.String()
+}
+
+type UnsupportedValueError struct {
+ Value reflect.Value
+ Str string
+}
+
+func (e *UnsupportedValueError) Error() string {
+ return "json: unsupported value: " + e.Str
+}
+
+// Before Go 1.2, an InvalidUTF8Error was returned by Marshal when
+// attempting to encode a string value with invalid UTF-8 sequences.
+// As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by
+// replacing invalid bytes with the Unicode replacement rune U+FFFD.
+// This error is no longer generated but is kept for backwards compatibility
+// with programs that might mention it.
+type InvalidUTF8Error struct {
+ S string // the whole string value that caused the error
+}
+
+func (e *InvalidUTF8Error) Error() string {
+ return "json: invalid UTF-8 in string: " + strconv.Quote(e.S)
+}
+
+type MarshalerError struct {
+ Type reflect.Type
+ Err error
+}
+
+func (e *MarshalerError) Error() string {
+ return "json: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Err.Error()
+}
+
+var hex = "0123456789abcdef"
+
+// An encodeState encodes JSON into a bytes.Buffer.
+type encodeState struct {
+ bytes.Buffer // accumulated output
+ scratch [64]byte
+ canonical bool
+}
+
+var encodeStatePool sync.Pool
+
+func newEncodeState(canonical bool) *encodeState {
+ if v := encodeStatePool.Get(); v != nil {
+ e := v.(*encodeState)
+ e.Reset()
+ e.canonical = canonical
+ return e
+ }
+ return &encodeState{canonical: canonical}
+}
+
+func (e *encodeState) marshal(v interface{}) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ if _, ok := r.(runtime.Error); ok {
+ panic(r)
+ }
+ if s, ok := r.(string); ok {
+ panic(s)
+ }
+ err = r.(error)
+ }
+ }()
+ e.reflectValue(reflect.ValueOf(v))
+ return nil
+}
+
+func (e *encodeState) error(err error) {
+ panic(err)
+}
+
+func isEmptyValue(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
+ return v.Len() == 0
+ case reflect.Bool:
+ return !v.Bool()
+ 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.Interface, reflect.Ptr:
+ return v.IsNil()
+ }
+ return false
+}
+
+func (e *encodeState) reflectValue(v reflect.Value) {
+ e.valueEncoder(v)(e, v, false)
+}
+
+type encoderFunc func(e *encodeState, v reflect.Value, quoted bool)
+
+var encoderCache struct {
+ sync.RWMutex
+ m map[reflect.Type]encoderFunc
+}
+
+func (e *encodeState) valueEncoder(v reflect.Value) encoderFunc {
+ if !v.IsValid() {
+ return invalidValueEncoder
+ }
+ return e.typeEncoder(v.Type())
+}
+
+func (e *encodeState) typeEncoder(t reflect.Type) encoderFunc {
+ encoderCache.RLock()
+ f := encoderCache.m[t]
+ encoderCache.RUnlock()
+ if f != nil {
+ return f
+ }
+
+ // To deal with recursive types, populate the map with an
+ // indirect func before we build it. This type waits on the
+ // real func (f) to be ready and then calls it. This indirect
+ // func is only used for recursive types.
+ encoderCache.Lock()
+ if encoderCache.m == nil {
+ encoderCache.m = make(map[reflect.Type]encoderFunc)
+ }
+ var wg sync.WaitGroup
+ wg.Add(1)
+ encoderCache.m[t] = func(e *encodeState, v reflect.Value, quoted bool) {
+ wg.Wait()
+ f(e, v, quoted)
+ }
+ encoderCache.Unlock()
+
+ // Compute fields without lock.
+ // Might duplicate effort but won't hold other computations back.
+ f = e.newTypeEncoder(t, true)
+ wg.Done()
+ encoderCache.Lock()
+ encoderCache.m[t] = f
+ encoderCache.Unlock()
+ return f
+}
+
+var (
+ marshalerType = reflect.TypeOf(new(Marshaler)).Elem()
+ textMarshalerType = reflect.TypeOf(new(encoding.TextMarshaler)).Elem()
+)
+
+// newTypeEncoder constructs an encoderFunc for a type.
+// The returned encoder only checks CanAddr when allowAddr is true.
+func (e *encodeState) newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc {
+ if t.Implements(marshalerType) {
+ return marshalerEncoder
+ }
+ if t.Kind() != reflect.Ptr && allowAddr {
+ if reflect.PtrTo(t).Implements(marshalerType) {
+ return newCondAddrEncoder(addrMarshalerEncoder, e.newTypeEncoder(t, false))
+ }
+ }
+
+ if t.Implements(textMarshalerType) {
+ return textMarshalerEncoder
+ }
+ if t.Kind() != reflect.Ptr && allowAddr {
+ if reflect.PtrTo(t).Implements(textMarshalerType) {
+ return newCondAddrEncoder(addrTextMarshalerEncoder, e.newTypeEncoder(t, false))
+ }
+ }
+
+ switch t.Kind() {
+ case reflect.Bool:
+ return boolEncoder
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ return intEncoder
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ return uintEncoder
+ case reflect.Float32:
+ return float32Encoder
+ case reflect.Float64:
+ return float64Encoder
+ case reflect.String:
+ return stringEncoder
+ case reflect.Interface:
+ return interfaceEncoder
+ case reflect.Struct:
+ return e.newStructEncoder(t)
+ case reflect.Map:
+ return e.newMapEncoder(t)
+ case reflect.Slice:
+ return e.newSliceEncoder(t)
+ case reflect.Array:
+ return e.newArrayEncoder(t)
+ case reflect.Ptr:
+ return e.newPtrEncoder(t)
+ default:
+ return unsupportedTypeEncoder
+ }
+}
+
+func invalidValueEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ e.WriteString("null")
+}
+
+func marshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ if v.Kind() == reflect.Ptr && v.IsNil() {
+ e.WriteString("null")
+ return
+ }
+ m := v.Interface().(Marshaler)
+ b, err := m.MarshalJSON()
+ if err == nil {
+ // copy JSON into buffer, checking validity.
+ err = compact(&e.Buffer, b, true)
+ }
+ if err != nil {
+ e.error(&MarshalerError{v.Type(), err})
+ }
+}
+
+func addrMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ va := v.Addr()
+ if va.IsNil() {
+ e.WriteString("null")
+ return
+ }
+ m := va.Interface().(Marshaler)
+ b, err := m.MarshalJSON()
+ if err == nil {
+ // copy JSON into buffer, checking validity.
+ err = compact(&e.Buffer, b, true)
+ }
+ if err != nil {
+ e.error(&MarshalerError{v.Type(), err})
+ }
+}
+
+func textMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ if v.Kind() == reflect.Ptr && v.IsNil() {
+ e.WriteString("null")
+ return
+ }
+ m := v.Interface().(encoding.TextMarshaler)
+ b, err := m.MarshalText()
+ if err != nil {
+ e.error(&MarshalerError{v.Type(), err})
+ }
+ e.stringBytes(b)
+}
+
+func addrTextMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ va := v.Addr()
+ if va.IsNil() {
+ e.WriteString("null")
+ return
+ }
+ m := va.Interface().(encoding.TextMarshaler)
+ b, err := m.MarshalText()
+ if err != nil {
+ e.error(&MarshalerError{v.Type(), err})
+ }
+ e.stringBytes(b)
+}
+
+func boolEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ if quoted {
+ e.WriteByte('"')
+ }
+ if v.Bool() {
+ e.WriteString("true")
+ } else {
+ e.WriteString("false")
+ }
+ if quoted {
+ e.WriteByte('"')
+ }
+}
+
+func intEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
+ if quoted {
+ e.WriteByte('"')
+ }
+ e.Write(b)
+ if quoted {
+ e.WriteByte('"')
+ }
+}
+
+func uintEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
+ if quoted {
+ e.WriteByte('"')
+ }
+ e.Write(b)
+ if quoted {
+ e.WriteByte('"')
+ }
+}
+
+type floatEncoder int // number of bits
+
+func (bits floatEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
+ f := v.Float()
+ if math.IsInf(f, 0) || math.IsNaN(f) || (e.canonical && math.Floor(f) != f) {
+ e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))})
+ }
+
+ var b []byte
+ if e.canonical {
+ b = strconv.AppendInt(e.scratch[:0], int64(f), 10)
+ } else {
+ b = strconv.AppendFloat(e.scratch[:0], f, 'g', -1, int(bits))
+ }
+ if quoted {
+ e.WriteByte('"')
+ }
+ e.Write(b)
+ if quoted {
+ e.WriteByte('"')
+ }
+}
+
+var (
+ float32Encoder = (floatEncoder(32)).encode
+ float64Encoder = (floatEncoder(64)).encode
+)
+
+func stringEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ if v.Type() == numberType {
+ numStr := v.String()
+ // In Go1.5 the empty string encodes to "0", while this is not a valid number literal
+ // we keep compatibility so check validity after this.
+ if numStr == "" {
+ numStr = "0" // Number's zero-val
+ }
+ if !isValidNumber(numStr) {
+ e.error(fmt.Errorf("json: invalid number literal %q", numStr))
+ }
+ e.WriteString(numStr)
+ return
+ }
+ if quoted {
+ sb, err := Marshal(v.String())
+ if err != nil {
+ e.error(err)
+ }
+ e.string(string(sb))
+ } else {
+ e.string(v.String())
+ }
+}
+
+func interfaceEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ if v.IsNil() {
+ e.WriteString("null")
+ return
+ }
+ e.reflectValue(v.Elem())
+}
+
+func unsupportedTypeEncoder(e *encodeState, v reflect.Value, quoted bool) {
+ e.error(&UnsupportedTypeError{v.Type()})
+}
+
+type structEncoder struct {
+ fields []field
+ fieldEncs []encoderFunc
+}
+
+func (se *structEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
+ e.WriteByte('{')
+ first := true
+ for i, f := range se.fields {
+ fv := fieldByIndex(v, f.index)
+ if !fv.IsValid() || f.omitEmpty && isEmptyValue(fv) {
+ continue
+ }
+ if first {
+ first = false
+ } else {
+ e.WriteByte(',')
+ }
+ e.string(f.name)
+ e.WriteByte(':')
+ se.fieldEncs[i](e, fv, f.quoted)
+ }
+ e.WriteByte('}')
+}
+
+func (e *encodeState) newStructEncoder(t reflect.Type) encoderFunc {
+ fields := cachedTypeFields(t, e.canonical)
+ se := &structEncoder{
+ fields: fields,
+ fieldEncs: make([]encoderFunc, len(fields)),
+ }
+ for i, f := range fields {
+ se.fieldEncs[i] = e.typeEncoder(typeByIndex(t, f.index))
+ }
+ return se.encode
+}
+
+type mapEncoder struct {
+ elemEnc encoderFunc
+}
+
+func (me *mapEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
+ if v.IsNil() {
+ e.WriteString("null")
+ return
+ }
+ e.WriteByte('{')
+ var sv stringValues = v.MapKeys()
+ sort.Sort(sv)
+ for i, k := range sv {
+ if i > 0 {
+ e.WriteByte(',')
+ }
+ e.string(k.String())
+ e.WriteByte(':')
+ me.elemEnc(e, v.MapIndex(k), false)
+ }
+ e.WriteByte('}')
+}
+
+func (e *encodeState) newMapEncoder(t reflect.Type) encoderFunc {
+ if t.Key().Kind() != reflect.String {
+ return unsupportedTypeEncoder
+ }
+ me := &mapEncoder{e.typeEncoder(t.Elem())}
+ return me.encode
+}
+
+func encodeByteSlice(e *encodeState, v reflect.Value, _ bool) {
+ if v.IsNil() {
+ e.WriteString("null")
+ return
+ }
+ s := v.Bytes()
+ e.WriteByte('"')
+ if len(s) < 1024 {
+ // for small buffers, using Encode directly is much faster.
+ dst := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
+ base64.StdEncoding.Encode(dst, s)
+ e.Write(dst)
+ } else {
+ // for large buffers, avoid unnecessary extra temporary
+ // buffer space.
+ enc := base64.NewEncoder(base64.StdEncoding, e)
+ enc.Write(s)
+ enc.Close()
+ }
+ e.WriteByte('"')
+}
+
+// sliceEncoder just wraps an arrayEncoder, checking to make sure the value isn't nil.
+type sliceEncoder struct {
+ arrayEnc encoderFunc
+}
+
+func (se *sliceEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
+ if v.IsNil() {
+ e.WriteString("null")
+ return
+ }
+ se.arrayEnc(e, v, false)
+}
+
+func (e *encodeState) newSliceEncoder(t reflect.Type) encoderFunc {
+ // Byte slices get special treatment; arrays don't.
+ if t.Elem().Kind() == reflect.Uint8 {
+ return encodeByteSlice
+ }
+ enc := &sliceEncoder{e.newArrayEncoder(t)}
+ return enc.encode
+}
+
+type arrayEncoder struct {
+ elemEnc encoderFunc
+}
+
+func (ae *arrayEncoder) encode(e *encodeState, v reflect.Value, _ bool) {
+ e.WriteByte('[')
+ n := v.Len()
+ for i := 0; i < n; i++ {
+ if i > 0 {
+ e.WriteByte(',')
+ }
+ ae.elemEnc(e, v.Index(i), false)
+ }
+ e.WriteByte(']')
+}
+
+func (e *encodeState) newArrayEncoder(t reflect.Type) encoderFunc {
+ enc := &arrayEncoder{e.typeEncoder(t.Elem())}
+ return enc.encode
+}
+
+type ptrEncoder struct {
+ elemEnc encoderFunc
+}
+
+func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
+ if v.IsNil() {
+ e.WriteString("null")
+ return
+ }
+ pe.elemEnc(e, v.Elem(), quoted)
+}
+
+func (e *encodeState) newPtrEncoder(t reflect.Type) encoderFunc {
+ enc := &ptrEncoder{e.typeEncoder(t.Elem())}
+ return enc.encode
+}
+
+type condAddrEncoder struct {
+ canAddrEnc, elseEnc encoderFunc
+}
+
+func (ce *condAddrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
+ if v.CanAddr() {
+ ce.canAddrEnc(e, v, quoted)
+ } else {
+ ce.elseEnc(e, v, quoted)
+ }
+}
+
+// newCondAddrEncoder returns an encoder that checks whether its value
+// CanAddr and delegates to canAddrEnc if so, else to elseEnc.
+func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc {
+ enc := &condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
+ return enc.encode
+}
+
+func isValidTag(s string) bool {
+ if s == "" {
+ return false
+ }
+ for _, c := range s {
+ switch {
+ case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
+ // Backslash and quote chars are reserved, but
+ // otherwise any punctuation chars are allowed
+ // in a tag name.
+ default:
+ if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+func fieldByIndex(v reflect.Value, index []int) reflect.Value {
+ for _, i := range index {
+ if v.Kind() == reflect.Ptr {
+ if v.IsNil() {
+ return reflect.Value{}
+ }
+ v = v.Elem()
+ }
+ v = v.Field(i)
+ }
+ return v
+}
+
+func typeByIndex(t reflect.Type, index []int) reflect.Type {
+ for _, i := range index {
+ if t.Kind() == reflect.Ptr {
+ t = t.Elem()
+ }
+ t = t.Field(i).Type
+ }
+ return t
+}
+
+// stringValues is a slice of reflect.Value holding *reflect.StringValue.
+// It implements the methods to sort by string.
+type stringValues []reflect.Value
+
+func (sv stringValues) Len() int { return len(sv) }
+func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
+func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
+func (sv stringValues) get(i int) string { return sv[i].String() }
+
+// NOTE: keep in sync with stringBytes below.
+func (e *encodeState) string(s string) int {
+ len0 := e.Len()
+ e.WriteByte('"')
+ start := 0
+ for i := 0; i < len(s); {
+ if b := s[i]; b < utf8.RuneSelf {
+ if b != '\\' && b != '"' {
+ if e.canonical || (0x20 <= b && b != '<' && b != '>' && b != '&') {
+ i++
+ continue
+ }
+ }
+ if start < i {
+ e.WriteString(s[start:i])
+ }
+ switch b {
+ case '\\', '"':
+ e.WriteByte('\\')
+ e.WriteByte(b)
+ case '\n':
+ e.WriteByte('\\')
+ e.WriteByte('n')
+ case '\r':
+ e.WriteByte('\\')
+ e.WriteByte('r')
+ case '\t':
+ e.WriteByte('\\')
+ e.WriteByte('t')
+ default:
+ // This encodes bytes < 0x20 except for \n and \r,
+ // as well as <, > and &. The latter are escaped because they
+ // can lead to security holes when user-controlled strings
+ // are rendered into JSON and served to some browsers.
+ e.WriteString(`\u00`)
+ e.WriteByte(hex[b>>4])
+ e.WriteByte(hex[b&0xF])
+ }
+ i++
+ start = i
+ continue
+ }
+ if e.canonical {
+ i++
+ continue
+ }
+ c, size := utf8.DecodeRuneInString(s[i:])
+ if c == utf8.RuneError && size == 1 {
+ if start < i {
+ e.WriteString(s[start:i])
+ }
+ e.WriteString(`\ufffd`)
+ i += size
+ start = i
+ continue
+ }
+ // U+2028 is LINE SEPARATOR.
+ // U+2029 is PARAGRAPH SEPARATOR.
+ // They are both technically valid characters in JSON strings,
+ // but don't work in JSONP, which has to be evaluated as JavaScript,
+ // and can lead to security holes there. It is valid JSON to
+ // escape them, so we do so unconditionally.
+ // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
+ if c == '\u2028' || c == '\u2029' {
+ if start < i {
+ e.WriteString(s[start:i])
+ }
+ e.WriteString(`\u202`)
+ e.WriteByte(hex[c&0xF])
+ i += size
+ start = i
+ continue
+ }
+ i += size
+ }
+ if start < len(s) {
+ e.WriteString(s[start:])
+ }
+ e.WriteByte('"')
+ return e.Len() - len0
+}
+
+// NOTE: keep in sync with string above.
+func (e *encodeState) stringBytes(s []byte) int {
+ len0 := e.Len()
+ e.WriteByte('"')
+ start := 0
+ for i := 0; i < len(s); {
+ if b := s[i]; b < utf8.RuneSelf {
+ if b != '\\' && b != '"' {
+ if e.canonical || (0x20 <= b && b != '<' && b != '>' && b != '&') {
+ i++
+ continue
+ }
+ }
+ if start < i {
+ e.Write(s[start:i])
+ }
+ switch b {
+ case '\\', '"':
+ e.WriteByte('\\')
+ e.WriteByte(b)
+ case '\n':
+ e.WriteByte('\\')
+ e.WriteByte('n')
+ case '\r':
+ e.WriteByte('\\')
+ e.WriteByte('r')
+ case '\t':
+ e.WriteByte('\\')
+ e.WriteByte('t')
+ default:
+ // This encodes bytes < 0x20 except for \n and \r,
+ // as well as <, >, and &. The latter are escaped because they
+ // can lead to security holes when user-controlled strings
+ // are rendered into JSON and served to some browsers.
+ e.WriteString(`\u00`)
+ e.WriteByte(hex[b>>4])
+ e.WriteByte(hex[b&0xF])
+ }
+ i++
+ start = i
+ continue
+ }
+ if e.canonical {
+ i++
+ continue
+ }
+ c, size := utf8.DecodeRune(s[i:])
+ if c == utf8.RuneError && size == 1 {
+ if start < i {
+ e.Write(s[start:i])
+ }
+ e.WriteString(`\ufffd`)
+ i += size
+ start = i
+ continue
+ }
+ // U+2028 is LINE SEPARATOR.
+ // U+2029 is PARAGRAPH SEPARATOR.
+ // They are both technically valid characters in JSON strings,
+ // but don't work in JSONP, which has to be evaluated as JavaScript,
+ // and can lead to security holes there. It is valid JSON to
+ // escape them, so we do so unconditionally.
+ // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
+ if c == '\u2028' || c == '\u2029' {
+ if start < i {
+ e.Write(s[start:i])
+ }
+ e.WriteString(`\u202`)
+ e.WriteByte(hex[c&0xF])
+ i += size
+ start = i
+ continue
+ }
+ i += size
+ }
+ if start < len(s) {
+ e.Write(s[start:])
+ }
+ e.WriteByte('"')
+ return e.Len() - len0
+}
+
+// A field represents a single field found in a struct.
+type field struct {
+ name string
+ nameBytes []byte // []byte(name)
+ equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent
+
+ tag bool
+ index []int
+ typ reflect.Type
+ omitEmpty bool
+ quoted bool
+}
+
+func fillField(f field) field {
+ f.nameBytes = []byte(f.name)
+ f.equalFold = foldFunc(f.nameBytes)
+ return f
+}
+
+// byName sorts field by name, breaking ties with depth,
+// then breaking ties with "name came from json tag", then
+// breaking ties with index sequence.
+type byName []field
+
+func (x byName) Len() int { return len(x) }
+
+func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
+
+func (x byName) Less(i, j int) bool {
+ if x[i].name != x[j].name {
+ return x[i].name < x[j].name
+ }
+ if len(x[i].index) != len(x[j].index) {
+ return len(x[i].index) < len(x[j].index)
+ }
+ if x[i].tag != x[j].tag {
+ return x[i].tag
+ }
+ return byIndex(x).Less(i, j)
+}
+
+// byIndex sorts field by index sequence.
+type byIndex []field
+
+func (x byIndex) Len() int { return len(x) }
+
+func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
+
+func (x byIndex) Less(i, j int) bool {
+ for k, xik := range x[i].index {
+ if k >= len(x[j].index) {
+ return false
+ }
+ if xik != x[j].index[k] {
+ return xik < x[j].index[k]
+ }
+ }
+ return len(x[i].index) < len(x[j].index)
+}
+
+// typeFields returns a list of fields that JSON should recognize for the given type.
+// The algorithm is breadth-first search over the set of structs to include - the top struct
+// and then any reachable anonymous structs.
+func typeFields(t reflect.Type) []field {
+ // Anonymous fields to explore at the current level and the next.
+ current := []field{}
+ next := []field{{typ: t}}
+
+ // Count of queued names for current level and the next.
+ count := map[reflect.Type]int{}
+ nextCount := map[reflect.Type]int{}
+
+ // Types already visited at an earlier level.
+ visited := map[reflect.Type]bool{}
+
+ // Fields found.
+ var fields []field
+
+ for len(next) > 0 {
+ current, next = next, current[:0]
+ count, nextCount = nextCount, map[reflect.Type]int{}
+
+ for _, f := range current {
+ if visited[f.typ] {
+ continue
+ }
+ visited[f.typ] = true
+
+ // Scan f.typ for fields to include.
+ for i := 0; i < f.typ.NumField(); i++ {
+ sf := f.typ.Field(i)
+ if sf.PkgPath != "" && !sf.Anonymous { // unexported
+ continue
+ }
+ tag := sf.Tag.Get("json")
+ if tag == "-" {
+ continue
+ }
+ name, opts := parseTag(tag)
+ if !isValidTag(name) {
+ name = ""
+ }
+ index := make([]int, len(f.index)+1)
+ copy(index, f.index)
+ index[len(f.index)] = i
+
+ ft := sf.Type
+ if ft.Name() == "" && ft.Kind() == reflect.Ptr {
+ // Follow pointer.
+ ft = ft.Elem()
+ }
+
+ // Only strings, floats, integers, and booleans can be quoted.
+ quoted := false
+ if opts.Contains("string") {
+ switch ft.Kind() {
+ case reflect.Bool,
+ reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
+ reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
+ reflect.Float32, reflect.Float64,
+ reflect.String:
+ quoted = true
+ }
+ }
+
+ // Record found field and index sequence.
+ if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
+ tagged := name != ""
+ if name == "" {
+ name = sf.Name
+ }
+ fields = append(fields, fillField(field{
+ name: name,
+ tag: tagged,
+ index: index,
+ typ: ft,
+ omitEmpty: opts.Contains("omitempty"),
+ quoted: quoted,
+ }))
+ if count[f.typ] > 1 {
+ // If there were multiple instances, add a second,
+ // so that the annihilation code will see a duplicate.
+ // It only cares about the distinction between 1 or 2,
+ // so don't bother generating any more copies.
+ fields = append(fields, fields[len(fields)-1])
+ }
+ continue
+ }
+
+ // Record new anonymous struct to explore in next round.
+ nextCount[ft]++
+ if nextCount[ft] == 1 {
+ next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft}))
+ }
+ }
+ }
+ }
+
+ sort.Sort(byName(fields))
+
+ // Delete all fields that are hidden by the Go rules for embedded fields,
+ // except that fields with JSON tags are promoted.
+
+ // The fields are sorted in primary order of name, secondary order
+ // of field index length. Loop over names; for each name, delete
+ // hidden fields by choosing the one dominant field that survives.
+ out := fields[:0]
+ for advance, i := 0, 0; i < len(fields); i += advance {
+ // One iteration per name.
+ // Find the sequence of fields with the name of this first field.
+ fi := fields[i]
+ name := fi.name
+ for advance = 1; i+advance < len(fields); advance++ {
+ fj := fields[i+advance]
+ if fj.name != name {
+ break
+ }
+ }
+ if advance == 1 { // Only one field with this name
+ out = append(out, fi)
+ continue
+ }
+ dominant, ok := dominantField(fields[i : i+advance])
+ if ok {
+ out = append(out, dominant)
+ }
+ }
+
+ return out
+}
+
+// dominantField looks through the fields, all of which are known to
+// have the same name, to find the single field that dominates the
+// others using Go's embedding rules, modified by the presence of
+// JSON tags. If there are multiple top-level fields, the boolean
+// will be false: This condition is an error in Go and we skip all
+// the fields.
+func dominantField(fields []field) (field, bool) {
+ // The fields are sorted in increasing index-length order. The winner
+ // must therefore be one with the shortest index length. Drop all
+ // longer entries, which is easy: just truncate the slice.
+ length := len(fields[0].index)
+ tagged := -1 // Index of first tagged field.
+ for i, f := range fields {
+ if len(f.index) > length {
+ fields = fields[:i]
+ break
+ }
+ if f.tag {
+ if tagged >= 0 {
+ // Multiple tagged fields at the same level: conflict.
+ // Return no field.
+ return field{}, false
+ }
+ tagged = i
+ }
+ }
+ if tagged >= 0 {
+ return fields[tagged], true
+ }
+ // All remaining fields have the same length. If there's more than one,
+ // we have a conflict (two fields named "X" at the same level) and we
+ // return no field.
+ if len(fields) > 1 {
+ return field{}, false
+ }
+ return fields[0], true
+}
+
+type fields struct {
+ byName []field
+ byIndex []field
+}
+
+var fieldCache struct {
+ sync.RWMutex
+ m map[reflect.Type]*fields
+}
+
+// cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
+func cachedTypeFields(t reflect.Type, canonical bool) []field {
+ fieldCache.RLock()
+ x := fieldCache.m[t]
+ fieldCache.RUnlock()
+
+ var f []field
+ if x != nil {
+ if canonical {
+ f = x.byName
+ }
+ f = x.byIndex
+ }
+ if f != nil {
+ return f
+ }
+
+ // Compute fields without lock.
+ // Might duplicate effort but won't hold other computations back.
+ f = typeFields(t)
+ if f == nil {
+ f = []field{}
+ }
+ if !canonical {
+ sort.Sort(byIndex(f))
+ }
+
+ fieldCache.Lock()
+ if fieldCache.m == nil {
+ fieldCache.m = map[reflect.Type]*fields{}
+ }
+ x = fieldCache.m[t]
+ fieldCache.Unlock()
+ if x == nil {
+ x = new(fields)
+ }
+ if canonical {
+ x.byName = f
+ } else {
+ x.byIndex = f
+ }
+ return f
+}
diff --git a/vendor/github.com/docker/go/canonical/json/fold.go b/vendor/github.com/docker/go/canonical/json/fold.go
new file mode 100644
index 0000000..9e17012
--- /dev/null
+++ b/vendor/github.com/docker/go/canonical/json/fold.go
@@ -0,0 +1,143 @@
+// 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 json
+
+import (
+ "bytes"
+ "unicode/utf8"
+)
+
+const (
+ caseMask = ^byte(0x20) // Mask to ignore case in ASCII.
+ kelvin = '\u212a'
+ smallLongEss = '\u017f'
+)
+
+// foldFunc returns one of four different case folding equivalence
+// functions, from most general (and slow) to fastest:
+//
+// 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8
+// 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S')
+// 3) asciiEqualFold, no special, but includes non-letters (including _)
+// 4) simpleLetterEqualFold, no specials, no non-letters.
+//
+// The letters S and K are special because they map to 3 runes, not just 2:
+// * S maps to s and to U+017F 'ſ' Latin small letter long s
+// * k maps to K and to U+212A 'K' Kelvin sign
+// See https://play.golang.org/p/tTxjOc0OGo
+//
+// The returned function is specialized for matching against s and
+// should only be given s. It's not curried for performance reasons.
+func foldFunc(s []byte) func(s, t []byte) bool {
+ nonLetter := false
+ special := false // special letter
+ for _, b := range s {
+ if b >= utf8.RuneSelf {
+ return bytes.EqualFold
+ }
+ upper := b & caseMask
+ if upper < 'A' || upper > 'Z' {
+ nonLetter = true
+ } else if upper == 'K' || upper == 'S' {
+ // See above for why these letters are special.
+ special = true
+ }
+ }
+ if special {
+ return equalFoldRight
+ }
+ if nonLetter {
+ return asciiEqualFold
+ }
+ return simpleLetterEqualFold
+}
+
+// equalFoldRight is a specialization of bytes.EqualFold when s is
+// known to be all ASCII (including punctuation), but contains an 's',
+// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t.
+// See comments on foldFunc.
+func equalFoldRight(s, t []byte) bool {
+ for _, sb := range s {
+ if len(t) == 0 {
+ return false
+ }
+ tb := t[0]
+ if tb < utf8.RuneSelf {
+ if sb != tb {
+ sbUpper := sb & caseMask
+ if 'A' <= sbUpper && sbUpper <= 'Z' {
+ if sbUpper != tb&caseMask {
+ return false
+ }
+ } else {
+ return false
+ }
+ }
+ t = t[1:]
+ continue
+ }
+ // sb is ASCII and t is not. t must be either kelvin
+ // sign or long s; sb must be s, S, k, or K.
+ tr, size := utf8.DecodeRune(t)
+ switch sb {
+ case 's', 'S':
+ if tr != smallLongEss {
+ return false
+ }
+ case 'k', 'K':
+ if tr != kelvin {
+ return false
+ }
+ default:
+ return false
+ }
+ t = t[size:]
+
+ }
+ if len(t) > 0 {
+ return false
+ }
+ return true
+}
+
+// asciiEqualFold is a specialization of bytes.EqualFold for use when
+// s is all ASCII (but may contain non-letters) and contains no
+// special-folding letters.
+// See comments on foldFunc.
+func asciiEqualFold(s, t []byte) bool {
+ if len(s) != len(t) {
+ return false
+ }
+ for i, sb := range s {
+ tb := t[i]
+ if sb == tb {
+ continue
+ }
+ if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') {
+ if sb&caseMask != tb&caseMask {
+ return false
+ }
+ } else {
+ return false
+ }
+ }
+ return true
+}
+
+// simpleLetterEqualFold is a specialization of bytes.EqualFold for
+// use when s is all ASCII letters (no underscores, etc) and also
+// doesn't contain 'k', 'K', 's', or 'S'.
+// See comments on foldFunc.
+func simpleLetterEqualFold(s, t []byte) bool {
+ if len(s) != len(t) {
+ return false
+ }
+ for i, b := range s {
+ if b&caseMask != t[i]&caseMask {
+ return false
+ }
+ }
+ return true
+}
diff --git a/vendor/github.com/docker/go/canonical/json/indent.go b/vendor/github.com/docker/go/canonical/json/indent.go
new file mode 100644
index 0000000..7cd9f4d
--- /dev/null
+++ b/vendor/github.com/docker/go/canonical/json/indent.go
@@ -0,0 +1,141 @@
+// 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
+
+import "bytes"
+
+// Compact appends to dst the JSON-encoded src with
+// insignificant space characters elided.
+func Compact(dst *bytes.Buffer, src []byte) error {
+ return compact(dst, src, false)
+}
+
+func compact(dst *bytes.Buffer, src []byte, escape bool) error {
+ origLen := dst.Len()
+ var scan scanner
+ scan.reset()
+ start := 0
+ for i, c := range src {
+ if escape && (c == '<' || c == '>' || c == '&') {
+ if start < i {
+ dst.Write(src[start:i])
+ }
+ dst.WriteString(`\u00`)
+ dst.WriteByte(hex[c>>4])
+ dst.WriteByte(hex[c&0xF])
+ start = i + 1
+ }
+ // Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9).
+ if c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 {
+ if start < i {
+ dst.Write(src[start:i])
+ }
+ dst.WriteString(`\u202`)
+ dst.WriteByte(hex[src[i+2]&0xF])
+ start = i + 3
+ }
+ v := scan.step(&scan, c)
+ if v >= scanSkipSpace {
+ if v == scanError {
+ break
+ }
+ if start < i {
+ dst.Write(src[start:i])
+ }
+ start = i + 1
+ }
+ }
+ if scan.eof() == scanError {
+ dst.Truncate(origLen)
+ return scan.err
+ }
+ if start < len(src) {
+ dst.Write(src[start:])
+ }
+ return nil
+}
+
+func newline(dst *bytes.Buffer, prefix, indent string, depth int) {
+ dst.WriteByte('\n')
+ dst.WriteString(prefix)
+ for i := 0; i < depth; i++ {
+ dst.WriteString(indent)
+ }
+}
+
+// Indent appends to dst an indented form of the JSON-encoded src.
+// Each element in a JSON object or array begins on a new,
+// indented line beginning with prefix followed by one or more
+// copies of indent according to the indentation nesting.
+// The data appended to dst does not begin with the prefix nor
+// any indentation, to make it easier to embed inside other formatted JSON data.
+// Although leading space characters (space, tab, carriage return, newline)
+// at the beginning of src are dropped, trailing space characters
+// at the end of src are preserved and copied to dst.
+// For example, if src has no trailing spaces, neither will dst;
+// if src ends in a trailing newline, so will dst.
+func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
+ origLen := dst.Len()
+ var scan scanner
+ scan.reset()
+ needIndent := false
+ depth := 0
+ for _, c := range src {
+ scan.bytes++
+ v := scan.step(&scan, c)
+ if v == scanSkipSpace {
+ continue
+ }
+ if v == scanError {
+ break
+ }
+ if needIndent && v != scanEndObject && v != scanEndArray {
+ needIndent = false
+ depth++
+ newline(dst, prefix, indent, depth)
+ }
+
+ // Emit semantically uninteresting bytes
+ // (in particular, punctuation in strings) unmodified.
+ if v == scanContinue {
+ dst.WriteByte(c)
+ continue
+ }
+
+ // Add spacing around real punctuation.
+ switch c {
+ case '{', '[':
+ // delay indent so that empty object and array are formatted as {} and [].
+ needIndent = true
+ dst.WriteByte(c)
+
+ case ',':
+ dst.WriteByte(c)
+ newline(dst, prefix, indent, depth)
+
+ case ':':
+ dst.WriteByte(c)
+ dst.WriteByte(' ')
+
+ case '}', ']':
+ if needIndent {
+ // suppress indent in empty object/array
+ needIndent = false
+ } else {
+ depth--
+ newline(dst, prefix, indent, depth)
+ }
+ dst.WriteByte(c)
+
+ default:
+ dst.WriteByte(c)
+ }
+ }
+ if scan.eof() == scanError {
+ dst.Truncate(origLen)
+ return scan.err
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/go/canonical/json/scanner.go b/vendor/github.com/docker/go/canonical/json/scanner.go
new file mode 100644
index 0000000..ee6622e
--- /dev/null
+++ b/vendor/github.com/docker/go/canonical/json/scanner.go
@@ -0,0 +1,623 @@
+// 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
+
+// JSON value parser state machine.
+// Just about at the limit of what is reasonable to write by hand.
+// Some parts are a bit tedious, but overall it nicely factors out the
+// otherwise common code from the multiple scanning functions
+// in this package (Compact, Indent, checkValid, nextValue, etc).
+//
+// This file starts with two simple examples using the scanner
+// before diving into the scanner itself.
+
+import "strconv"
+
+// checkValid verifies that data is valid JSON-encoded data.
+// scan is passed in for use by checkValid to avoid an allocation.
+func checkValid(data []byte, scan *scanner) error {
+ scan.reset()
+ for _, c := range data {
+ scan.bytes++
+ if scan.step(scan, c) == scanError {
+ return scan.err
+ }
+ }
+ if scan.eof() == scanError {
+ return scan.err
+ }
+ return nil
+}
+
+// nextValue splits data after the next whole JSON value,
+// returning that value and the bytes that follow it as separate slices.
+// scan is passed in for use by nextValue to avoid an allocation.
+func nextValue(data []byte, scan *scanner) (value, rest []byte, err error) {
+ scan.reset()
+ for i, c := range data {
+ v := scan.step(scan, c)
+ if v >= scanEndObject {
+ switch v {
+ // probe the scanner with a space to determine whether we will
+ // get scanEnd on the next character. Otherwise, if the next character
+ // is not a space, scanEndTop allocates a needless error.
+ case scanEndObject, scanEndArray:
+ if scan.step(scan, ' ') == scanEnd {
+ return data[:i+1], data[i+1:], nil
+ }
+ case scanError:
+ return nil, nil, scan.err
+ case scanEnd:
+ return data[:i], data[i:], nil
+ }
+ }
+ }
+ if scan.eof() == scanError {
+ return nil, nil, scan.err
+ }
+ return data, nil, nil
+}
+
+// A SyntaxError is a description of a JSON syntax error.
+type SyntaxError struct {
+ msg string // description of error
+ Offset int64 // error occurred after reading Offset bytes
+}
+
+func (e *SyntaxError) Error() string { return e.msg }
+
+// A scanner is a JSON scanning state machine.
+// Callers call scan.reset() and then pass bytes in one at a time
+// by calling scan.step(&scan, c) for each byte.
+// The return value, referred to as an opcode, tells the
+// caller about significant parsing events like beginning
+// and ending literals, objects, and arrays, so that the
+// caller can follow along if it wishes.
+// The return value scanEnd indicates that a single top-level
+// JSON value has been completed, *before* the byte that
+// just got passed in. (The indication must be delayed in order
+// to recognize the end of numbers: is 123 a whole value or
+// the beginning of 12345e+6?).
+type scanner struct {
+ // The step is a func to be called to execute the next transition.
+ // Also tried using an integer constant and a single func
+ // with a switch, but using the func directly was 10% faster
+ // on a 64-bit Mac Mini, and it's nicer to read.
+ step func(*scanner, byte) int
+
+ // Reached end of top-level value.
+ endTop bool
+
+ // Stack of what we're in the middle of - array values, object keys, object values.
+ parseState []int
+
+ // Error that happened, if any.
+ err error
+
+ // 1-byte redo (see undo method)
+ redo bool
+ redoCode int
+ redoState func(*scanner, byte) int
+
+ // total bytes consumed, updated by decoder.Decode
+ bytes int64
+}
+
+// These values are returned by the state transition functions
+// assigned to scanner.state and the method scanner.eof.
+// They give details about the current state of the scan that
+// callers might be interested to know about.
+// It is okay to ignore the return value of any particular
+// call to scanner.state: if one call returns scanError,
+// every subsequent call will return scanError too.
+const (
+ // Continue.
+ scanContinue = iota // uninteresting byte
+ scanBeginLiteral // end implied by next result != scanContinue
+ scanBeginObject // begin object
+ scanObjectKey // just finished object key (string)
+ scanObjectValue // just finished non-last object value
+ scanEndObject // end object (implies scanObjectValue if possible)
+ scanBeginArray // begin array
+ scanArrayValue // just finished array value
+ scanEndArray // end array (implies scanArrayValue if possible)
+ scanSkipSpace // space byte; can skip; known to be last "continue" result
+
+ // Stop.
+ scanEnd // top-level value ended *before* this byte; known to be first "stop" result
+ scanError // hit an error, scanner.err.
+)
+
+// These values are stored in the parseState stack.
+// They give the current state of a composite value
+// being scanned. If the parser is inside a nested value
+// the parseState describes the nested state, outermost at entry 0.
+const (
+ parseObjectKey = iota // parsing object key (before colon)
+ parseObjectValue // parsing object value (after colon)
+ parseArrayValue // parsing array value
+)
+
+// reset prepares the scanner for use.
+// It must be called before calling s.step.
+func (s *scanner) reset() {
+ s.step = stateBeginValue
+ s.parseState = s.parseState[0:0]
+ s.err = nil
+ s.redo = false
+ s.endTop = false
+}
+
+// eof tells the scanner that the end of input has been reached.
+// It returns a scan status just as s.step does.
+func (s *scanner) eof() int {
+ if s.err != nil {
+ return scanError
+ }
+ if s.endTop {
+ return scanEnd
+ }
+ s.step(s, ' ')
+ if s.endTop {
+ return scanEnd
+ }
+ if s.err == nil {
+ s.err = &SyntaxError{"unexpected end of JSON input", s.bytes}
+ }
+ return scanError
+}
+
+// pushParseState pushes a new parse state p onto the parse stack.
+func (s *scanner) pushParseState(p int) {
+ s.parseState = append(s.parseState, p)
+}
+
+// popParseState pops a parse state (already obtained) off the stack
+// and updates s.step accordingly.
+func (s *scanner) popParseState() {
+ n := len(s.parseState) - 1
+ s.parseState = s.parseState[0:n]
+ s.redo = false
+ if n == 0 {
+ s.step = stateEndTop
+ s.endTop = true
+ } else {
+ s.step = stateEndValue
+ }
+}
+
+func isSpace(c byte) bool {
+ return c == ' ' || c == '\t' || c == '\r' || c == '\n'
+}
+
+// stateBeginValueOrEmpty is the state after reading `[`.
+func stateBeginValueOrEmpty(s *scanner, c byte) int {
+ if c <= ' ' && isSpace(c) {
+ return scanSkipSpace
+ }
+ if c == ']' {
+ return stateEndValue(s, c)
+ }
+ return stateBeginValue(s, c)
+}
+
+// stateBeginValue is the state at the beginning of the input.
+func stateBeginValue(s *scanner, c byte) int {
+ if c <= ' ' && isSpace(c) {
+ return scanSkipSpace
+ }
+ switch c {
+ case '{':
+ s.step = stateBeginStringOrEmpty
+ s.pushParseState(parseObjectKey)
+ return scanBeginObject
+ case '[':
+ s.step = stateBeginValueOrEmpty
+ s.pushParseState(parseArrayValue)
+ return scanBeginArray
+ case '"':
+ s.step = stateInString
+ return scanBeginLiteral
+ case '-':
+ s.step = stateNeg
+ return scanBeginLiteral
+ case '0': // beginning of 0.123
+ s.step = state0
+ return scanBeginLiteral
+ case 't': // beginning of true
+ s.step = stateT
+ return scanBeginLiteral
+ case 'f': // beginning of false
+ s.step = stateF
+ return scanBeginLiteral
+ case 'n': // beginning of null
+ s.step = stateN
+ return scanBeginLiteral
+ }
+ if '1' <= c && c <= '9' { // beginning of 1234.5
+ s.step = state1
+ return scanBeginLiteral
+ }
+ return s.error(c, "looking for beginning of value")
+}
+
+// stateBeginStringOrEmpty is the state after reading `{`.
+func stateBeginStringOrEmpty(s *scanner, c byte) int {
+ if c <= ' ' && isSpace(c) {
+ return scanSkipSpace
+ }
+ if c == '}' {
+ n := len(s.parseState)
+ s.parseState[n-1] = parseObjectValue
+ return stateEndValue(s, c)
+ }
+ return stateBeginString(s, c)
+}
+
+// stateBeginString is the state after reading `{"key": value,`.
+func stateBeginString(s *scanner, c byte) int {
+ if c <= ' ' && isSpace(c) {
+ return scanSkipSpace
+ }
+ if c == '"' {
+ s.step = stateInString
+ return scanBeginLiteral
+ }
+ return s.error(c, "looking for beginning of object key string")
+}
+
+// stateEndValue is the state after completing a value,
+// such as after reading `{}` or `true` or `["x"`.
+func stateEndValue(s *scanner, c byte) int {
+ n := len(s.parseState)
+ if n == 0 {
+ // Completed top-level before the current byte.
+ s.step = stateEndTop
+ s.endTop = true
+ return stateEndTop(s, c)
+ }
+ if c <= ' ' && isSpace(c) {
+ s.step = stateEndValue
+ return scanSkipSpace
+ }
+ ps := s.parseState[n-1]
+ switch ps {
+ case parseObjectKey:
+ if c == ':' {
+ s.parseState[n-1] = parseObjectValue
+ s.step = stateBeginValue
+ return scanObjectKey
+ }
+ return s.error(c, "after object key")
+ case parseObjectValue:
+ if c == ',' {
+ s.parseState[n-1] = parseObjectKey
+ s.step = stateBeginString
+ return scanObjectValue
+ }
+ if c == '}' {
+ s.popParseState()
+ return scanEndObject
+ }
+ return s.error(c, "after object key:value pair")
+ case parseArrayValue:
+ if c == ',' {
+ s.step = stateBeginValue
+ return scanArrayValue
+ }
+ if c == ']' {
+ s.popParseState()
+ return scanEndArray
+ }
+ return s.error(c, "after array element")
+ }
+ return s.error(c, "")
+}
+
+// stateEndTop is the state after finishing the top-level value,
+// such as after reading `{}` or `[1,2,3]`.
+// Only space characters should be seen now.
+func stateEndTop(s *scanner, c byte) int {
+ if c != ' ' && c != '\t' && c != '\r' && c != '\n' {
+ // Complain about non-space byte on next call.
+ s.error(c, "after top-level value")
+ }
+ return scanEnd
+}
+
+// stateInString is the state after reading `"`.
+func stateInString(s *scanner, c byte) int {
+ if c == '"' {
+ s.step = stateEndValue
+ return scanContinue
+ }
+ if c == '\\' {
+ s.step = stateInStringEsc
+ return scanContinue
+ }
+ if c < 0x20 {
+ return s.error(c, "in string literal")
+ }
+ return scanContinue
+}
+
+// stateInStringEsc is the state after reading `"\` during a quoted string.
+func stateInStringEsc(s *scanner, c byte) int {
+ switch c {
+ case 'b', 'f', 'n', 'r', 't', '\\', '/', '"':
+ s.step = stateInString
+ return scanContinue
+ case 'u':
+ s.step = stateInStringEscU
+ return scanContinue
+ }
+ return s.error(c, "in string escape code")
+}
+
+// stateInStringEscU is the state after reading `"\u` during a quoted string.
+func stateInStringEscU(s *scanner, c byte) int {
+ if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
+ s.step = stateInStringEscU1
+ return scanContinue
+ }
+ // numbers
+ return s.error(c, "in \\u hexadecimal character escape")
+}
+
+// stateInStringEscU1 is the state after reading `"\u1` during a quoted string.
+func stateInStringEscU1(s *scanner, c byte) int {
+ if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
+ s.step = stateInStringEscU12
+ return scanContinue
+ }
+ // numbers
+ return s.error(c, "in \\u hexadecimal character escape")
+}
+
+// stateInStringEscU12 is the state after reading `"\u12` during a quoted string.
+func stateInStringEscU12(s *scanner, c byte) int {
+ if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
+ s.step = stateInStringEscU123
+ return scanContinue
+ }
+ // numbers
+ return s.error(c, "in \\u hexadecimal character escape")
+}
+
+// stateInStringEscU123 is the state after reading `"\u123` during a quoted string.
+func stateInStringEscU123(s *scanner, c byte) int {
+ if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
+ s.step = stateInString
+ return scanContinue
+ }
+ // numbers
+ return s.error(c, "in \\u hexadecimal character escape")
+}
+
+// stateNeg is the state after reading `-` during a number.
+func stateNeg(s *scanner, c byte) int {
+ if c == '0' {
+ s.step = state0
+ return scanContinue
+ }
+ if '1' <= c && c <= '9' {
+ s.step = state1
+ return scanContinue
+ }
+ return s.error(c, "in numeric literal")
+}
+
+// state1 is the state after reading a non-zero integer during a number,
+// such as after reading `1` or `100` but not `0`.
+func state1(s *scanner, c byte) int {
+ if '0' <= c && c <= '9' {
+ s.step = state1
+ return scanContinue
+ }
+ return state0(s, c)
+}
+
+// state0 is the state after reading `0` during a number.
+func state0(s *scanner, c byte) int {
+ if c == '.' {
+ s.step = stateDot
+ return scanContinue
+ }
+ if c == 'e' || c == 'E' {
+ s.step = stateE
+ return scanContinue
+ }
+ return stateEndValue(s, c)
+}
+
+// stateDot is the state after reading the integer and decimal point in a number,
+// such as after reading `1.`.
+func stateDot(s *scanner, c byte) int {
+ if '0' <= c && c <= '9' {
+ s.step = stateDot0
+ return scanContinue
+ }
+ return s.error(c, "after decimal point in numeric literal")
+}
+
+// stateDot0 is the state after reading the integer, decimal point, and subsequent
+// digits of a number, such as after reading `3.14`.
+func stateDot0(s *scanner, c byte) int {
+ if '0' <= c && c <= '9' {
+ return scanContinue
+ }
+ if c == 'e' || c == 'E' {
+ s.step = stateE
+ return scanContinue
+ }
+ return stateEndValue(s, c)
+}
+
+// stateE is the state after reading the mantissa and e in a number,
+// such as after reading `314e` or `0.314e`.
+func stateE(s *scanner, c byte) int {
+ if c == '+' || c == '-' {
+ s.step = stateESign
+ return scanContinue
+ }
+ return stateESign(s, c)
+}
+
+// stateESign is the state after reading the mantissa, e, and sign in a number,
+// such as after reading `314e-` or `0.314e+`.
+func stateESign(s *scanner, c byte) int {
+ if '0' <= c && c <= '9' {
+ s.step = stateE0
+ return scanContinue
+ }
+ return s.error(c, "in exponent of numeric literal")
+}
+
+// stateE0 is the state after reading the mantissa, e, optional sign,
+// and at least one digit of the exponent in a number,
+// such as after reading `314e-2` or `0.314e+1` or `3.14e0`.
+func stateE0(s *scanner, c byte) int {
+ if '0' <= c && c <= '9' {
+ return scanContinue
+ }
+ return stateEndValue(s, c)
+}
+
+// stateT is the state after reading `t`.
+func stateT(s *scanner, c byte) int {
+ if c == 'r' {
+ s.step = stateTr
+ return scanContinue
+ }
+ return s.error(c, "in literal true (expecting 'r')")
+}
+
+// stateTr is the state after reading `tr`.
+func stateTr(s *scanner, c byte) int {
+ if c == 'u' {
+ s.step = stateTru
+ return scanContinue
+ }
+ return s.error(c, "in literal true (expecting 'u')")
+}
+
+// stateTru is the state after reading `tru`.
+func stateTru(s *scanner, c byte) int {
+ if c == 'e' {
+ s.step = stateEndValue
+ return scanContinue
+ }
+ return s.error(c, "in literal true (expecting 'e')")
+}
+
+// stateF is the state after reading `f`.
+func stateF(s *scanner, c byte) int {
+ if c == 'a' {
+ s.step = stateFa
+ return scanContinue
+ }
+ return s.error(c, "in literal false (expecting 'a')")
+}
+
+// stateFa is the state after reading `fa`.
+func stateFa(s *scanner, c byte) int {
+ if c == 'l' {
+ s.step = stateFal
+ return scanContinue
+ }
+ return s.error(c, "in literal false (expecting 'l')")
+}
+
+// stateFal is the state after reading `fal`.
+func stateFal(s *scanner, c byte) int {
+ if c == 's' {
+ s.step = stateFals
+ return scanContinue
+ }
+ return s.error(c, "in literal false (expecting 's')")
+}
+
+// stateFals is the state after reading `fals`.
+func stateFals(s *scanner, c byte) int {
+ if c == 'e' {
+ s.step = stateEndValue
+ return scanContinue
+ }
+ return s.error(c, "in literal false (expecting 'e')")
+}
+
+// stateN is the state after reading `n`.
+func stateN(s *scanner, c byte) int {
+ if c == 'u' {
+ s.step = stateNu
+ return scanContinue
+ }
+ return s.error(c, "in literal null (expecting 'u')")
+}
+
+// stateNu is the state after reading `nu`.
+func stateNu(s *scanner, c byte) int {
+ if c == 'l' {
+ s.step = stateNul
+ return scanContinue
+ }
+ return s.error(c, "in literal null (expecting 'l')")
+}
+
+// stateNul is the state after reading `nul`.
+func stateNul(s *scanner, c byte) int {
+ if c == 'l' {
+ s.step = stateEndValue
+ return scanContinue
+ }
+ return s.error(c, "in literal null (expecting 'l')")
+}
+
+// stateError is the state after reaching a syntax error,
+// such as after reading `[1}` or `5.1.2`.
+func stateError(s *scanner, c byte) int {
+ return scanError
+}
+
+// error records an error and switches to the error state.
+func (s *scanner) error(c byte, context string) int {
+ s.step = stateError
+ s.err = &SyntaxError{"invalid character " + quoteChar(c) + " " + context, s.bytes}
+ return scanError
+}
+
+// quoteChar formats c as a quoted character literal
+func quoteChar(c byte) string {
+ // special cases - different from quoted strings
+ if c == '\'' {
+ return `'\''`
+ }
+ if c == '"' {
+ return `'"'`
+ }
+
+ // use quoted string with different quotation marks
+ s := strconv.Quote(string(c))
+ return "'" + s[1:len(s)-1] + "'"
+}
+
+// undo causes the scanner to return scanCode from the next state transition.
+// This gives callers a simple 1-byte undo mechanism.
+func (s *scanner) undo(scanCode int) {
+ if s.redo {
+ panic("json: invalid use of scanner")
+ }
+ s.redoCode = scanCode
+ s.redoState = s.step
+ s.step = stateRedo
+ s.redo = true
+}
+
+// stateRedo helps implement the scanner's 1-byte undo.
+func stateRedo(s *scanner, c byte) int {
+ s.redo = false
+ s.step = s.redoState
+ return s.redoCode
+}
diff --git a/vendor/github.com/docker/go/canonical/json/stream.go b/vendor/github.com/docker/go/canonical/json/stream.go
new file mode 100644
index 0000000..dc0f28e
--- /dev/null
+++ b/vendor/github.com/docker/go/canonical/json/stream.go
@@ -0,0 +1,487 @@
+// 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
+
+import (
+ "bytes"
+ "errors"
+ "io"
+)
+
+// A Decoder reads and decodes JSON objects from an input stream.
+type Decoder struct {
+ r io.Reader
+ buf []byte
+ d decodeState
+ scanp int // start of unread data in buf
+ scan scanner
+ err error
+
+ tokenState int
+ tokenStack []int
+}
+
+// NewDecoder returns a new decoder that reads from r.
+//
+// The decoder introduces its own buffering and may
+// read data from r beyond the JSON values requested.
+func NewDecoder(r io.Reader) *Decoder {
+ return &Decoder{r: r}
+}
+
+// UseNumber causes the Decoder to unmarshal a number into an interface{} as a
+// Number instead of as a float64.
+func (dec *Decoder) UseNumber() { dec.d.useNumber = true }
+
+// Decode reads the next JSON-encoded value from its
+// input and stores it in the value pointed to by v.
+//
+// See the documentation for Unmarshal for details about
+// the conversion of JSON into a Go value.
+func (dec *Decoder) Decode(v interface{}) error {
+ if dec.err != nil {
+ return dec.err
+ }
+
+ if err := dec.tokenPrepareForDecode(); err != nil {
+ return err
+ }
+
+ if !dec.tokenValueAllowed() {
+ return &SyntaxError{msg: "not at beginning of value"}
+ }
+
+ // Read whole value into buffer.
+ n, err := dec.readValue()
+ if err != nil {
+ return err
+ }
+ dec.d.init(dec.buf[dec.scanp : dec.scanp+n])
+ dec.scanp += n
+
+ // Don't save err from unmarshal into dec.err:
+ // the connection is still usable since we read a complete JSON
+ // object from it before the error happened.
+ err = dec.d.unmarshal(v)
+
+ // fixup token streaming state
+ dec.tokenValueEnd()
+
+ return err
+}
+
+// Buffered returns a reader of the data remaining in the Decoder's
+// buffer. The reader is valid until the next call to Decode.
+func (dec *Decoder) Buffered() io.Reader {
+ return bytes.NewReader(dec.buf[dec.scanp:])
+}
+
+// readValue reads a JSON value into dec.buf.
+// It returns the length of the encoding.
+func (dec *Decoder) readValue() (int, error) {
+ dec.scan.reset()
+
+ scanp := dec.scanp
+ var err error
+Input:
+ for {
+ // Look in the buffer for a new value.
+ for i, c := range dec.buf[scanp:] {
+ dec.scan.bytes++
+ v := dec.scan.step(&dec.scan, c)
+ if v == scanEnd {
+ scanp += i
+ break Input
+ }
+ // scanEnd is delayed one byte.
+ // We might block trying to get that byte from src,
+ // so instead invent a space byte.
+ if (v == scanEndObject || v == scanEndArray) && dec.scan.step(&dec.scan, ' ') == scanEnd {
+ scanp += i + 1
+ break Input
+ }
+ if v == scanError {
+ dec.err = dec.scan.err
+ return 0, dec.scan.err
+ }
+ }
+ scanp = len(dec.buf)
+
+ // Did the last read have an error?
+ // Delayed until now to allow buffer scan.
+ if err != nil {
+ if err == io.EOF {
+ if dec.scan.step(&dec.scan, ' ') == scanEnd {
+ break Input
+ }
+ if nonSpace(dec.buf) {
+ err = io.ErrUnexpectedEOF
+ }
+ }
+ dec.err = err
+ return 0, err
+ }
+
+ n := scanp - dec.scanp
+ err = dec.refill()
+ scanp = dec.scanp + n
+ }
+ return scanp - dec.scanp, nil
+}
+
+func (dec *Decoder) refill() error {
+ // Make room to read more into the buffer.
+ // First slide down data already consumed.
+ if dec.scanp > 0 {
+ n := copy(dec.buf, dec.buf[dec.scanp:])
+ dec.buf = dec.buf[:n]
+ dec.scanp = 0
+ }
+
+ // Grow buffer if not large enough.
+ const minRead = 512
+ if cap(dec.buf)-len(dec.buf) < minRead {
+ newBuf := make([]byte, len(dec.buf), 2*cap(dec.buf)+minRead)
+ copy(newBuf, dec.buf)
+ dec.buf = newBuf
+ }
+
+ // Read. Delay error for next iteration (after scan).
+ n, err := dec.r.Read(dec.buf[len(dec.buf):cap(dec.buf)])
+ dec.buf = dec.buf[0 : len(dec.buf)+n]
+
+ return err
+}
+
+func nonSpace(b []byte) bool {
+ for _, c := range b {
+ if !isSpace(c) {
+ return true
+ }
+ }
+ return false
+}
+
+// An Encoder writes JSON objects to an output stream.
+type Encoder struct {
+ w io.Writer
+ err error
+ canonical bool
+}
+
+// NewEncoder returns a new encoder that writes to w.
+func NewEncoder(w io.Writer) *Encoder {
+ return &Encoder{w: w}
+}
+
+// Canonical causes the encoder to switch to Canonical JSON mode.
+// Read more at: http://wiki.laptop.org/go/Canonical_JSON
+func (enc *Encoder) Canonical() { enc.canonical = true }
+
+// Encode writes the JSON encoding of v to the stream,
+// followed by a newline character.
+//
+// See the documentation for Marshal for details about the
+// conversion of Go values to JSON.
+func (enc *Encoder) Encode(v interface{}) error {
+ if enc.err != nil {
+ return enc.err
+ }
+ e := newEncodeState(enc.canonical)
+ err := e.marshal(v)
+ if err != nil {
+ return err
+ }
+
+ if !enc.canonical {
+ // Terminate each value with a newline.
+ // This makes the output look a little nicer
+ // when debugging, and some kind of space
+ // is required if the encoded value was a number,
+ // so that the reader knows there aren't more
+ // digits coming.
+ e.WriteByte('\n')
+ }
+
+ if _, err = enc.w.Write(e.Bytes()); err != nil {
+ enc.err = err
+ }
+ encodeStatePool.Put(e)
+ return err
+}
+
+// RawMessage is a raw encoded JSON object.
+// It implements Marshaler and Unmarshaler and can
+// be used to delay JSON decoding or precompute a JSON encoding.
+type RawMessage []byte
+
+// MarshalJSON returns *m as the JSON encoding of m.
+func (m *RawMessage) MarshalJSON() ([]byte, error) {
+ return *m, nil
+}
+
+// UnmarshalJSON sets *m to a copy of data.
+func (m *RawMessage) UnmarshalJSON(data []byte) error {
+ if m == nil {
+ return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
+ }
+ *m = append((*m)[0:0], data...)
+ return nil
+}
+
+var _ Marshaler = (*RawMessage)(nil)
+var _ Unmarshaler = (*RawMessage)(nil)
+
+// A Token holds a value of one of these types:
+//
+// Delim, for the four JSON delimiters [ ] { }
+// bool, for JSON booleans
+// float64, for JSON numbers
+// Number, for JSON numbers
+// string, for JSON string literals
+// nil, for JSON null
+//
+type Token interface{}
+
+const (
+ tokenTopValue = iota
+ tokenArrayStart
+ tokenArrayValue
+ tokenArrayComma
+ tokenObjectStart
+ tokenObjectKey
+ tokenObjectColon
+ tokenObjectValue
+ tokenObjectComma
+)
+
+// advance tokenstate from a separator state to a value state
+func (dec *Decoder) tokenPrepareForDecode() error {
+ // Note: Not calling peek before switch, to avoid
+ // putting peek into the standard Decode path.
+ // peek is only called when using the Token API.
+ switch dec.tokenState {
+ case tokenArrayComma:
+ c, err := dec.peek()
+ if err != nil {
+ return err
+ }
+ if c != ',' {
+ return &SyntaxError{"expected comma after array element", 0}
+ }
+ dec.scanp++
+ dec.tokenState = tokenArrayValue
+ case tokenObjectColon:
+ c, err := dec.peek()
+ if err != nil {
+ return err
+ }
+ if c != ':' {
+ return &SyntaxError{"expected colon after object key", 0}
+ }
+ dec.scanp++
+ dec.tokenState = tokenObjectValue
+ }
+ return nil
+}
+
+func (dec *Decoder) tokenValueAllowed() bool {
+ switch dec.tokenState {
+ case tokenTopValue, tokenArrayStart, tokenArrayValue, tokenObjectValue:
+ return true
+ }
+ return false
+}
+
+func (dec *Decoder) tokenValueEnd() {
+ switch dec.tokenState {
+ case tokenArrayStart, tokenArrayValue:
+ dec.tokenState = tokenArrayComma
+ case tokenObjectValue:
+ dec.tokenState = tokenObjectComma
+ }
+}
+
+// A Delim is a JSON array or object delimiter, one of [ ] { or }.
+type Delim rune
+
+func (d Delim) String() string {
+ return string(d)
+}
+
+// Token returns the next JSON token in the input stream.
+// At the end of the input stream, Token returns nil, io.EOF.
+//
+// Token guarantees that the delimiters [ ] { } it returns are
+// properly nested and matched: if Token encounters an unexpected
+// delimiter in the input, it will return an error.
+//
+// The input stream consists of basic JSON values—bool, string,
+// number, and null—along with delimiters [ ] { } of type Delim
+// to mark the start and end of arrays and objects.
+// Commas and colons are elided.
+func (dec *Decoder) Token() (Token, error) {
+ for {
+ c, err := dec.peek()
+ if err != nil {
+ return nil, err
+ }
+ switch c {
+ case '[':
+ if !dec.tokenValueAllowed() {
+ return dec.tokenError(c)
+ }
+ dec.scanp++
+ dec.tokenStack = append(dec.tokenStack, dec.tokenState)
+ dec.tokenState = tokenArrayStart
+ return Delim('['), nil
+
+ case ']':
+ if dec.tokenState != tokenArrayStart && dec.tokenState != tokenArrayComma {
+ return dec.tokenError(c)
+ }
+ dec.scanp++
+ dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1]
+ dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1]
+ dec.tokenValueEnd()
+ return Delim(']'), nil
+
+ case '{':
+ if !dec.tokenValueAllowed() {
+ return dec.tokenError(c)
+ }
+ dec.scanp++
+ dec.tokenStack = append(dec.tokenStack, dec.tokenState)
+ dec.tokenState = tokenObjectStart
+ return Delim('{'), nil
+
+ case '}':
+ if dec.tokenState != tokenObjectStart && dec.tokenState != tokenObjectComma {
+ return dec.tokenError(c)
+ }
+ dec.scanp++
+ dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1]
+ dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1]
+ dec.tokenValueEnd()
+ return Delim('}'), nil
+
+ case ':':
+ if dec.tokenState != tokenObjectColon {
+ return dec.tokenError(c)
+ }
+ dec.scanp++
+ dec.tokenState = tokenObjectValue
+ continue
+
+ case ',':
+ if dec.tokenState == tokenArrayComma {
+ dec.scanp++
+ dec.tokenState = tokenArrayValue
+ continue
+ }
+ if dec.tokenState == tokenObjectComma {
+ dec.scanp++
+ dec.tokenState = tokenObjectKey
+ continue
+ }
+ return dec.tokenError(c)
+
+ case '"':
+ if dec.tokenState == tokenObjectStart || dec.tokenState == tokenObjectKey {
+ var x string
+ old := dec.tokenState
+ dec.tokenState = tokenTopValue
+ err := dec.Decode(&x)
+ dec.tokenState = old
+ if err != nil {
+ clearOffset(err)
+ return nil, err
+ }
+ dec.tokenState = tokenObjectColon
+ return x, nil
+ }
+ fallthrough
+
+ default:
+ if !dec.tokenValueAllowed() {
+ return dec.tokenError(c)
+ }
+ var x interface{}
+ if err := dec.Decode(&x); err != nil {
+ clearOffset(err)
+ return nil, err
+ }
+ return x, nil
+ }
+ }
+}
+
+func clearOffset(err error) {
+ if s, ok := err.(*SyntaxError); ok {
+ s.Offset = 0
+ }
+}
+
+func (dec *Decoder) tokenError(c byte) (Token, error) {
+ var context string
+ switch dec.tokenState {
+ case tokenTopValue:
+ context = " looking for beginning of value"
+ case tokenArrayStart, tokenArrayValue, tokenObjectValue:
+ context = " looking for beginning of value"
+ case tokenArrayComma:
+ context = " after array element"
+ case tokenObjectKey:
+ context = " looking for beginning of object key string"
+ case tokenObjectColon:
+ context = " after object key"
+ case tokenObjectComma:
+ context = " after object key:value pair"
+ }
+ return nil, &SyntaxError{"invalid character " + quoteChar(c) + " " + context, 0}
+}
+
+// More reports whether there is another element in the
+// current array or object being parsed.
+func (dec *Decoder) More() bool {
+ c, err := dec.peek()
+ return err == nil && c != ']' && c != '}'
+}
+
+func (dec *Decoder) peek() (byte, error) {
+ var err error
+ for {
+ for i := dec.scanp; i < len(dec.buf); i++ {
+ c := dec.buf[i]
+ if isSpace(c) {
+ continue
+ }
+ dec.scanp = i
+ return c, nil
+ }
+ // buffer has been scanned, now report any error
+ if err != nil {
+ return 0, err
+ }
+ err = dec.refill()
+ }
+}
+
+/*
+TODO
+
+// EncodeToken writes the given JSON token to the stream.
+// It returns an error if the delimiters [ ] { } are not properly used.
+//
+// EncodeToken does not call Flush, because usually it is part of
+// a larger operation such as Encode, and those will call Flush when finished.
+// Callers that create an Encoder and then invoke EncodeToken directly,
+// without using Encode, need to call Flush when finished to ensure that
+// the JSON is written to the underlying writer.
+func (e *Encoder) EncodeToken(t Token) error {
+ ...
+}
+
+*/
diff --git a/vendor/github.com/docker/go/canonical/json/tags.go b/vendor/github.com/docker/go/canonical/json/tags.go
new file mode 100644
index 0000000..c38fd51
--- /dev/null
+++ b/vendor/github.com/docker/go/canonical/json/tags.go
@@ -0,0 +1,44 @@
+// 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 json
+
+import (
+ "strings"
+)
+
+// tagOptions is the string following a comma in a struct field's "json"
+// tag, or the empty string. It does not include the leading comma.
+type tagOptions string
+
+// parseTag splits a struct field's json tag into its name and
+// comma-separated options.
+func parseTag(tag string) (string, tagOptions) {
+ if idx := strings.Index(tag, ","); idx != -1 {
+ return tag[:idx], tagOptions(tag[idx+1:])
+ }
+ return tag, tagOptions("")
+}
+
+// Contains reports whether a comma-separated list of options
+// contains a particular substr flag. substr must be surrounded by a
+// string boundary or commas.
+func (o tagOptions) Contains(optionName string) bool {
+ if len(o) == 0 {
+ return false
+ }
+ s := string(o)
+ for s != "" {
+ var next string
+ i := strings.Index(s, ",")
+ if i >= 0 {
+ s, next = s[:i], s[i+1:]
+ }
+ if s == optionName {
+ return true
+ }
+ s = next
+ }
+ return false
+}
diff --git a/vendor/github.com/docker/libkv/LICENSE.code b/vendor/github.com/docker/libkv/LICENSE.code
new file mode 100644
index 0000000..34c4ea7
--- /dev/null
+++ b/vendor/github.com/docker/libkv/LICENSE.code
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2014-2016 Docker, Inc.
+
+ 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/docker/libkv/LICENSE.docs b/vendor/github.com/docker/libkv/LICENSE.docs
new file mode 100644
index 0000000..e26cd4f
--- /dev/null
+++ b/vendor/github.com/docker/libkv/LICENSE.docs
@@ -0,0 +1,425 @@
+Attribution-ShareAlike 4.0 International
+
+=======================================================================
+
+Creative Commons Corporation ("Creative Commons") is not a law firm and
+does not provide legal services or legal advice. Distribution of
+Creative Commons public licenses does not create a lawyer-client or
+other relationship. Creative Commons makes its licenses and related
+information available on an "as-is" basis. Creative Commons gives no
+warranties regarding its licenses, any material licensed under their
+terms and conditions, or any related information. Creative Commons
+disclaims all liability for damages resulting from their use to the
+fullest extent possible.
+
+Using Creative Commons Public Licenses
+
+Creative Commons public licenses provide a standard set of terms and
+conditions that creators and other rights holders may use to share
+original works of authorship and other material subject to copyright
+and certain other rights specified in the public license below. The
+following considerations are for informational purposes only, are not
+exhaustive, and do not form part of our licenses.
+
+ Considerations for licensors: Our public licenses are
+ intended for use by those authorized to give the public
+ permission to use material in ways otherwise restricted by
+ copyright and certain other rights. Our licenses are
+ irrevocable. Licensors should read and understand the terms
+ and conditions of the license they choose before applying it.
+ Licensors should also secure all rights necessary before
+ applying our licenses so that the public can reuse the
+ material as expected. Licensors should clearly mark any
+ material not subject to the license. This includes other CC-
+ licensed material, or material used under an exception or
+ limitation to copyright. More considerations for licensors:
+ wiki.creativecommons.org/Considerations_for_licensors
+
+ Considerations for the public: By using one of our public
+ licenses, a licensor grants the public permission to use the
+ licensed material under specified terms and conditions. If
+ the licensor's permission is not necessary for any reason--for
+ example, because of any applicable exception or limitation to
+ copyright--then that use is not regulated by the license. Our
+ licenses grant only permissions under copyright and certain
+ other rights that a licensor has authority to grant. Use of
+ the licensed material may still be restricted for other
+ reasons, including because others have copyright or other
+ rights in the material. A licensor may make special requests,
+ such as asking that all changes be marked or described.
+ Although not required by our licenses, you are encouraged to
+ respect those requests where reasonable. More_considerations
+ for the public:
+ wiki.creativecommons.org/Considerations_for_licensees
+
+=======================================================================
+
+Creative Commons Attribution-ShareAlike 4.0 International Public
+License
+
+By exercising the Licensed Rights (defined below), You accept and agree
+to be bound by the terms and conditions of this Creative Commons
+Attribution-ShareAlike 4.0 International Public License ("Public
+License"). To the extent this Public License may be interpreted as a
+contract, You are granted the Licensed Rights in consideration of Your
+acceptance of these terms and conditions, and the Licensor grants You
+such rights in consideration of benefits the Licensor receives from
+making the Licensed Material available under these terms and
+conditions.
+
+
+Section 1 -- Definitions.
+
+ a. Adapted Material means material subject to Copyright and Similar
+ Rights that is derived from or based upon the Licensed Material
+ and in which the Licensed Material is translated, altered,
+ arranged, transformed, or otherwise modified in a manner requiring
+ permission under the Copyright and Similar Rights held by the
+ Licensor. For purposes of this Public License, where the Licensed
+ Material is a musical work, performance, or sound recording,
+ Adapted Material is always produced where the Licensed Material is
+ synched in timed relation with a moving image.
+
+ b. Adapter's License means the license You apply to Your Copyright
+ and Similar Rights in Your contributions to Adapted Material in
+ accordance with the terms and conditions of this Public License.
+
+ c. BY-SA Compatible License means a license listed at
+ creativecommons.org/compatiblelicenses, approved by Creative
+ Commons as essentially the equivalent of this Public License.
+
+ d. Copyright and Similar Rights means copyright and/or similar rights
+ closely related to copyright including, without limitation,
+ performance, broadcast, sound recording, and Sui Generis Database
+ Rights, without regard to how the rights are labeled or
+ categorized. For purposes of this Public License, the rights
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
+ Rights.
+
+ e. Effective Technological Measures means those measures that, in the
+ absence of proper authority, may not be circumvented under laws
+ fulfilling obligations under Article 11 of the WIPO Copyright
+ Treaty adopted on December 20, 1996, and/or similar international
+ agreements.
+
+ f. Exceptions and Limitations means fair use, fair dealing, and/or
+ any other exception or limitation to Copyright and Similar Rights
+ that applies to Your use of the Licensed Material.
+
+ g. License Elements means the license attributes listed in the name
+ of a Creative Commons Public License. The License Elements of this
+ Public License are Attribution and ShareAlike.
+
+ h. Licensed Material means the artistic or literary work, database,
+ or other material to which the Licensor applied this Public
+ License.
+
+ i. Licensed Rights means the rights granted to You subject to the
+ terms and conditions of this Public License, which are limited to
+ all Copyright and Similar Rights that apply to Your use of the
+ Licensed Material and that the Licensor has authority to license.
+
+ j. Licensor means the individual(s) or entity(ies) granting rights
+ under this Public License.
+
+ k. Share means to provide material to the public by any means or
+ process that requires permission under the Licensed Rights, such
+ as reproduction, public display, public performance, distribution,
+ dissemination, communication, or importation, and to make material
+ available to the public including in ways that members of the
+ public may access the material from a place and at a time
+ individually chosen by them.
+
+ l. Sui Generis Database Rights means rights other than copyright
+ resulting from Directive 96/9/EC of the European Parliament and of
+ the Council of 11 March 1996 on the legal protection of databases,
+ as amended and/or succeeded, as well as other essentially
+ equivalent rights anywhere in the world.
+
+ m. You means the individual or entity exercising the Licensed Rights
+ under this Public License. Your has a corresponding meaning.
+
+
+Section 2 -- Scope.
+
+ a. License grant.
+
+ 1. Subject to the terms and conditions of this Public License,
+ the Licensor hereby grants You a worldwide, royalty-free,
+ non-sublicensable, non-exclusive, irrevocable license to
+ exercise the Licensed Rights in the Licensed Material to:
+
+ a. reproduce and Share the Licensed Material, in whole or
+ in part; and
+
+ b. produce, reproduce, and Share Adapted Material.
+
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
+ Exceptions and Limitations apply to Your use, this Public
+ License does not apply, and You do not need to comply with
+ its terms and conditions.
+
+ 3. Term. The term of this Public License is specified in Section
+ 6(a).
+
+ 4. Media and formats; technical modifications allowed. The
+ Licensor authorizes You to exercise the Licensed Rights in
+ all media and formats whether now known or hereafter created,
+ and to make technical modifications necessary to do so. The
+ Licensor waives and/or agrees not to assert any right or
+ authority to forbid You from making technical modifications
+ necessary to exercise the Licensed Rights, including
+ technical modifications necessary to circumvent Effective
+ Technological Measures. For purposes of this Public License,
+ simply making modifications authorized by this Section 2(a)
+ (4) never produces Adapted Material.
+
+ 5. Downstream recipients.
+
+ a. Offer from the Licensor -- Licensed Material. Every
+ recipient of the Licensed Material automatically
+ receives an offer from the Licensor to exercise the
+ Licensed Rights under the terms and conditions of this
+ Public License.
+
+ b. Additional offer from the Licensor -- Adapted Material.
+ Every recipient of Adapted Material from You
+ automatically receives an offer from the Licensor to
+ exercise the Licensed Rights in the Adapted Material
+ under the conditions of the Adapter's License You apply.
+
+ c. No downstream restrictions. You may not offer or impose
+ any additional or different terms or conditions on, or
+ apply any Effective Technological Measures to, the
+ Licensed Material if doing so restricts exercise of the
+ Licensed Rights by any recipient of the Licensed
+ Material.
+
+ 6. No endorsement. Nothing in this Public License constitutes or
+ may be construed as permission to assert or imply that You
+ are, or that Your use of the Licensed Material is, connected
+ with, or sponsored, endorsed, or granted official status by,
+ the Licensor or others designated to receive attribution as
+ provided in Section 3(a)(1)(A)(i).
+
+ b. Other rights.
+
+ 1. Moral rights, such as the right of integrity, are not
+ licensed under this Public License, nor are publicity,
+ privacy, and/or other similar personality rights; however, to
+ the extent possible, the Licensor waives and/or agrees not to
+ assert any such rights held by the Licensor to the limited
+ extent necessary to allow You to exercise the Licensed
+ Rights, but not otherwise.
+
+ 2. Patent and trademark rights are not licensed under this
+ Public License.
+
+ 3. To the extent possible, the Licensor waives any right to
+ collect royalties from You for the exercise of the Licensed
+ Rights, whether directly or through a collecting society
+ under any voluntary or waivable statutory or compulsory
+ licensing scheme. In all other cases the Licensor expressly
+ reserves any right to collect such royalties.
+
+
+Section 3 -- License Conditions.
+
+Your exercise of the Licensed Rights is expressly made subject to the
+following conditions.
+
+ a. Attribution.
+
+ 1. If You Share the Licensed Material (including in modified
+ form), You must:
+
+ a. retain the following if it is supplied by the Licensor
+ with the Licensed Material:
+
+ i. identification of the creator(s) of the Licensed
+ Material and any others designated to receive
+ attribution, in any reasonable manner requested by
+ the Licensor (including by pseudonym if
+ designated);
+
+ ii. a copyright notice;
+
+ iii. a notice that refers to this Public License;
+
+ iv. a notice that refers to the disclaimer of
+ warranties;
+
+ v. a URI or hyperlink to the Licensed Material to the
+ extent reasonably practicable;
+
+ b. indicate if You modified the Licensed Material and
+ retain an indication of any previous modifications; and
+
+ c. indicate the Licensed Material is licensed under this
+ Public License, and include the text of, or the URI or
+ hyperlink to, this Public License.
+
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
+ reasonable manner based on the medium, means, and context in
+ which You Share the Licensed Material. For example, it may be
+ reasonable to satisfy the conditions by providing a URI or
+ hyperlink to a resource that includes the required
+ information.
+
+ 3. If requested by the Licensor, You must remove any of the
+ information required by Section 3(a)(1)(A) to the extent
+ reasonably practicable.
+
+ b. ShareAlike.
+
+ In addition to the conditions in Section 3(a), if You Share
+ Adapted Material You produce, the following conditions also apply.
+
+ 1. The Adapter's License You apply must be a Creative Commons
+ license with the same License Elements, this version or
+ later, or a BY-SA Compatible License.
+
+ 2. You must include the text of, or the URI or hyperlink to, the
+ Adapter's License You apply. You may satisfy this condition
+ in any reasonable manner based on the medium, means, and
+ context in which You Share Adapted Material.
+
+ 3. You may not offer or impose any additional or different terms
+ or conditions on, or apply any Effective Technological
+ Measures to, Adapted Material that restrict exercise of the
+ rights granted under the Adapter's License You apply.
+
+
+Section 4 -- Sui Generis Database Rights.
+
+Where the Licensed Rights include Sui Generis Database Rights that
+apply to Your use of the Licensed Material:
+
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
+ to extract, reuse, reproduce, and Share all or a substantial
+ portion of the contents of the database;
+
+ b. if You include all or a substantial portion of the database
+ contents in a database in which You have Sui Generis Database
+ Rights, then the database in which You have Sui Generis Database
+ Rights (but not its individual contents) is Adapted Material,
+
+ including for purposes of Section 3(b); and
+ c. You must comply with the conditions in Section 3(a) if You Share
+ all or a substantial portion of the contents of the database.
+
+For the avoidance of doubt, this Section 4 supplements and does not
+replace Your obligations under this Public License where the Licensed
+Rights include other Copyright and Similar Rights.
+
+
+Section 5 -- Disclaimer of Warranties and Limitation of Liability.
+
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
+
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
+
+ c. The disclaimer of warranties and limitation of liability provided
+ above shall be interpreted in a manner that, to the extent
+ possible, most closely approximates an absolute disclaimer and
+ waiver of all liability.
+
+
+Section 6 -- Term and Termination.
+
+ a. This Public License applies for the term of the Copyright and
+ Similar Rights licensed here. However, if You fail to comply with
+ this Public License, then Your rights under this Public License
+ terminate automatically.
+
+ b. Where Your right to use the Licensed Material has terminated under
+ Section 6(a), it reinstates:
+
+ 1. automatically as of the date the violation is cured, provided
+ it is cured within 30 days of Your discovery of the
+ violation; or
+
+ 2. upon express reinstatement by the Licensor.
+
+ For the avoidance of doubt, this Section 6(b) does not affect any
+ right the Licensor may have to seek remedies for Your violations
+ of this Public License.
+
+ c. For the avoidance of doubt, the Licensor may also offer the
+ Licensed Material under separate terms or conditions or stop
+ distributing the Licensed Material at any time; however, doing so
+ will not terminate this Public License.
+
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
+ License.
+
+
+Section 7 -- Other Terms and Conditions.
+
+ a. The Licensor shall not be bound by any additional or different
+ terms or conditions communicated by You unless expressly agreed.
+
+ b. Any arrangements, understandings, or agreements regarding the
+ Licensed Material not stated herein are separate from and
+ independent of the terms and conditions of this Public License.
+
+
+Section 8 -- Interpretation.
+
+ a. For the avoidance of doubt, this Public License does not, and
+ shall not be interpreted to, reduce, limit, restrict, or impose
+ conditions on any use of the Licensed Material that could lawfully
+ be made without permission under this Public License.
+
+ b. To the extent possible, if any provision of this Public License is
+ deemed unenforceable, it shall be automatically reformed to the
+ minimum extent necessary to make it enforceable. If the provision
+ cannot be reformed, it shall be severed from this Public License
+ without affecting the enforceability of the remaining terms and
+ conditions.
+
+ c. No term or condition of this Public License will be waived and no
+ failure to comply consented to unless expressly agreed to by the
+ Licensor.
+
+ d. Nothing in this Public License constitutes or may be interpreted
+ as a limitation upon, or waiver of, any privileges and immunities
+ that apply to the Licensor or You, including from the legal
+ processes of any jurisdiction or authority.
+
+
+=======================================================================
+
+Creative Commons is not a party to its public licenses.
+Notwithstanding, Creative Commons may elect to apply one of its public
+licenses to material it publishes and in those instances will be
+considered the "Licensor." Except for the limited purpose of indicating
+that material is shared under a Creative Commons public license or as
+otherwise permitted by the Creative Commons policies published at
+creativecommons.org/policies, Creative Commons does not authorize the
+use of the trademark "Creative Commons" or any other trademark or logo
+of Creative Commons without its prior written consent including,
+without limitation, in connection with any unauthorized modifications
+to any of its public licenses or any other arrangements,
+understandings, or agreements concerning use of licensed material. For
+the avoidance of doubt, this paragraph does not form part of the public
+licenses.
+
+Creative Commons may be contacted at creativecommons.org.
diff --git a/vendor/github.com/docker/libkv/README.md b/vendor/github.com/docker/libkv/README.md
new file mode 100644
index 0000000..baad81b
--- /dev/null
+++ b/vendor/github.com/docker/libkv/README.md
@@ -0,0 +1,107 @@
+# libkv
+
+[![GoDoc](https://godoc.org/github.com/docker/libkv?status.png)](https://godoc.org/github.com/docker/libkv)
+[![Build Status](https://travis-ci.org/docker/libkv.svg?branch=master)](https://travis-ci.org/docker/libkv)
+[![Coverage Status](https://coveralls.io/repos/docker/libkv/badge.svg)](https://coveralls.io/r/docker/libkv)
+[![Go Report Card](https://goreportcard.com/badge/github.com/docker/libkv)](https://goreportcard.com/report/github.com/docker/libkv)
+
+`libkv` provides a `Go` native library to store metadata.
+
+The goal of `libkv` is to abstract common store operations for multiple distributed and/or local Key/Value store backends.
+
+For example, you can use it to store your metadata or for service discovery to register machines and endpoints inside your cluster.
+
+You can also easily implement a generic *Leader Election* on top of it (see the [docker/leadership](https://github.com/docker/leadership) repository).
+
+As of now, `libkv` offers support for `Consul`, `Etcd`, `Zookeeper` (**Distributed** store) and `BoltDB` (**Local** store).
+
+## Usage
+
+`libkv` is meant to be used as an abstraction layer over existing distributed Key/Value stores. It is especially useful if you plan to support `consul`, `etcd` and `zookeeper` using the same codebase.
+
+It is ideal if you plan for something written in Go that should support:
+
+- A simple metadata storage, distributed or local
+- A lightweight discovery service for your nodes
+- A distributed lock mechanism
+
+You can find examples of usage for `libkv` under in `docs/examples.go`. Optionally you can also take a look at the `docker/swarm` or `docker/libnetwork` repositories which are using `docker/libkv` for all the use cases listed above.
+
+## Supported versions
+
+`libkv` supports:
+- Consul versions >= `0.5.1` because it uses Sessions with `Delete` behavior for the use of `TTLs` (mimics zookeeper's Ephemeral node support), If you don't plan to use `TTLs`: you can use Consul version `0.4.0+`.
+- Etcd versions >= `2.0` because it uses the new `coreos/etcd/client`, this might change in the future as the support for `APIv3` comes along and adds more capabilities.
+- Zookeeper versions >= `3.4.5`. Although this might work with previous version but this remains untested as of now.
+- Boltdb, which shouldn't be subject to any version dependencies.
+
+## Interface
+
+A **storage backend** in `libkv` should implement (fully or partially) this interface:
+
+```go
+type Store interface {
+ Put(key string, value []byte, options *WriteOptions) error
+ Get(key string) (*KVPair, error)
+ Delete(key string) error
+ Exists(key string) (bool, error)
+ Watch(key string, stopCh <-chan struct{}) (<-chan *KVPair, error)
+ WatchTree(directory string, stopCh <-chan struct{}) (<-chan []*KVPair, error)
+ NewLock(key string, options *LockOptions) (Locker, error)
+ List(directory string) ([]*KVPair, error)
+ DeleteTree(directory string) error
+ AtomicPut(key string, value []byte, previous *KVPair, options *WriteOptions) (bool, *KVPair, error)
+ AtomicDelete(key string, previous *KVPair) (bool, error)
+ Close()
+}
+```
+
+## Compatibility matrix
+
+Backend drivers in `libkv` are generally divided between **local drivers** and **distributed drivers**. Distributed backends offer enhanced capabilities like `Watches` and/or distributed `Locks`.
+
+Local drivers are usually used in complement to the distributed drivers to store informations that only needs to be available locally.
+
+| Calls | Consul | Etcd | Zookeeper | BoltDB |
+|-----------------------|:----------:|:------:|:-----------:|:--------:|
+| Put | X | X | X | X |
+| Get | X | X | X | X |
+| Delete | X | X | X | X |
+| Exists | X | X | X | X |
+| Watch | X | X | X | |
+| WatchTree | X | X | X | |
+| NewLock (Lock/Unlock) | X | X | X | |
+| List | X | X | X | X |
+| DeleteTree | X | X | X | X |
+| AtomicPut | X | X | X | X |
+| Close | X | X | X | X |
+
+## Limitations
+
+Distributed Key/Value stores often have different concepts for managing and formatting keys and their associated values. Even though `libkv` tries to abstract those stores aiming for some consistency, in some cases it can't be applied easily.
+
+Please refer to the `docs/compatibility.md` to see what are the special cases for cross-backend compatibility.
+
+Other than those special cases, you should expect the same experience for basic operations like `Get`/`Put`, etc.
+
+Calls like `WatchTree` may return different events (or number of events) depending on the backend (for now, `Etcd` and `Consul` will likely return more events than `Zookeeper` that you should triage properly). Although you should be able to use it successfully to watch on events in an interchangeable way (see the **docker/leadership** repository or the **pkg/discovery/kv** package in **docker/docker**).
+
+## TLS
+
+Only `Consul` and `etcd` have support for TLS and you should build and provide your own `config.TLS` object to feed the client. Support is planned for `zookeeper`.
+
+##Roadmap
+
+- Make the API nicer to use (using `options`)
+- Provide more options (`consistency` for example)
+- Improve performance (remove extras `Get`/`List` operations)
+- Better key formatting
+- New backends?
+
+##Contributing
+
+Want to hack on libkv? [Docker's contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md) apply.
+
+##Copyright and license
+
+Copyright © 2014-2016 Docker, Inc. All rights reserved, except as follows. Code is released under the Apache 2.0 license. The README.md file, and files in the "docs" folder are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file "LICENSE.docs". You may obtain a duplicate copy of the same license, titled CC-BY-SA-4.0, at http://creativecommons.org/licenses/by/4.0/.
diff --git a/vendor/github.com/docker/libkv/libkv.go b/vendor/github.com/docker/libkv/libkv.go
new file mode 100644
index 0000000..bdb8c75
--- /dev/null
+++ b/vendor/github.com/docker/libkv/libkv.go
@@ -0,0 +1,40 @@
+package libkv
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+
+ "github.com/docker/libkv/store"
+)
+
+// Initialize creates a new Store object, initializing the client
+type Initialize func(addrs []string, options *store.Config) (store.Store, error)
+
+var (
+ // Backend initializers
+ initializers = make(map[store.Backend]Initialize)
+
+ supportedBackend = func() string {
+ keys := make([]string, 0, len(initializers))
+ for k := range initializers {
+ keys = append(keys, string(k))
+ }
+ sort.Strings(keys)
+ return strings.Join(keys, ", ")
+ }()
+)
+
+// NewStore creates an instance of store
+func NewStore(backend store.Backend, addrs []string, options *store.Config) (store.Store, error) {
+ if init, exists := initializers[backend]; exists {
+ return init(addrs, options)
+ }
+
+ return nil, fmt.Errorf("%s %s", store.ErrBackendNotSupported.Error(), supportedBackend)
+}
+
+// AddStore adds a new store backend to libkv
+func AddStore(store store.Backend, init Initialize) {
+ initializers[store] = init
+}
diff --git a/vendor/github.com/docker/libkv/store/boltdb/boltdb.go b/vendor/github.com/docker/libkv/store/boltdb/boltdb.go
new file mode 100644
index 0000000..cdfd74f
--- /dev/null
+++ b/vendor/github.com/docker/libkv/store/boltdb/boltdb.go
@@ -0,0 +1,474 @@
+package boltdb
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "os"
+ "path/filepath"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/boltdb/bolt"
+ "github.com/docker/libkv"
+ "github.com/docker/libkv/store"
+)
+
+var (
+ // ErrMultipleEndpointsUnsupported is thrown when multiple endpoints specified for
+ // BoltDB. Endpoint has to be a local file path
+ ErrMultipleEndpointsUnsupported = errors.New("boltdb supports one endpoint and should be a file path")
+ // ErrBoltBucketOptionMissing is thrown when boltBcuket config option is missing
+ ErrBoltBucketOptionMissing = errors.New("boltBucket config option missing")
+)
+
+const (
+ filePerm os.FileMode = 0644
+)
+
+//BoltDB type implements the Store interface
+type BoltDB struct {
+ client *bolt.DB
+ boltBucket []byte
+ dbIndex uint64
+ path string
+ timeout time.Duration
+ // By default libkv opens and closes the bolt DB connection for every
+ // get/put operation. This allows multiple apps to use a Bolt DB at the
+ // same time.
+ // PersistConnection flag provides an option to override ths behavior.
+ // ie: open the connection in New and use it till Close is called.
+ PersistConnection bool
+ sync.Mutex
+}
+
+const (
+ libkvmetadatalen = 8
+ transientTimeout = time.Duration(10) * time.Second
+)
+
+// Register registers boltdb to libkv
+func Register() {
+ libkv.AddStore(store.BOLTDB, New)
+}
+
+// New opens a new BoltDB connection to the specified path and bucket
+func New(endpoints []string, options *store.Config) (store.Store, error) {
+ var (
+ db *bolt.DB
+ err error
+ boltOptions *bolt.Options
+ timeout = transientTimeout
+ )
+
+ if len(endpoints) > 1 {
+ return nil, ErrMultipleEndpointsUnsupported
+ }
+
+ if (options == nil) || (len(options.Bucket) == 0) {
+ return nil, ErrBoltBucketOptionMissing
+ }
+
+ dir, _ := filepath.Split(endpoints[0])
+ if err = os.MkdirAll(dir, 0750); err != nil {
+ return nil, err
+ }
+
+ if options.PersistConnection {
+ boltOptions = &bolt.Options{Timeout: options.ConnectionTimeout}
+ db, err = bolt.Open(endpoints[0], filePerm, boltOptions)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ if options.ConnectionTimeout != 0 {
+ timeout = options.ConnectionTimeout
+ }
+
+ b := &BoltDB{
+ client: db,
+ path: endpoints[0],
+ boltBucket: []byte(options.Bucket),
+ timeout: timeout,
+ PersistConnection: options.PersistConnection,
+ }
+
+ return b, nil
+}
+
+func (b *BoltDB) reset() {
+ b.path = ""
+ b.boltBucket = []byte{}
+}
+
+func (b *BoltDB) getDBhandle() (*bolt.DB, error) {
+ var (
+ db *bolt.DB
+ err error
+ )
+ if !b.PersistConnection {
+ boltOptions := &bolt.Options{Timeout: b.timeout}
+ if db, err = bolt.Open(b.path, filePerm, boltOptions); err != nil {
+ return nil, err
+ }
+ b.client = db
+ }
+
+ return b.client, nil
+}
+
+func (b *BoltDB) releaseDBhandle() {
+ if !b.PersistConnection {
+ b.client.Close()
+ }
+}
+
+// Get the value at "key". BoltDB doesn't provide an inbuilt last modified index with every kv pair. Its implemented by
+// by a atomic counter maintained by the libkv and appened to the value passed by the client.
+func (b *BoltDB) Get(key string) (*store.KVPair, error) {
+ var (
+ val []byte
+ db *bolt.DB
+ err error
+ )
+ b.Lock()
+ defer b.Unlock()
+
+ if db, err = b.getDBhandle(); err != nil {
+ return nil, err
+ }
+ defer b.releaseDBhandle()
+
+ err = db.View(func(tx *bolt.Tx) error {
+ bucket := tx.Bucket(b.boltBucket)
+ if bucket == nil {
+ return store.ErrKeyNotFound
+ }
+
+ v := bucket.Get([]byte(key))
+ val = make([]byte, len(v))
+ copy(val, v)
+
+ return nil
+ })
+
+ if len(val) == 0 {
+ return nil, store.ErrKeyNotFound
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ dbIndex := binary.LittleEndian.Uint64(val[:libkvmetadatalen])
+ val = val[libkvmetadatalen:]
+
+ return &store.KVPair{Key: key, Value: val, LastIndex: (dbIndex)}, nil
+}
+
+//Put the key, value pair. index number metadata is prepended to the value
+func (b *BoltDB) Put(key string, value []byte, opts *store.WriteOptions) error {
+ var (
+ dbIndex uint64
+ db *bolt.DB
+ err error
+ )
+ b.Lock()
+ defer b.Unlock()
+
+ dbval := make([]byte, libkvmetadatalen)
+
+ if db, err = b.getDBhandle(); err != nil {
+ return err
+ }
+ defer b.releaseDBhandle()
+
+ err = db.Update(func(tx *bolt.Tx) error {
+ bucket, err := tx.CreateBucketIfNotExists(b.boltBucket)
+ if err != nil {
+ return err
+ }
+
+ dbIndex = atomic.AddUint64(&b.dbIndex, 1)
+ binary.LittleEndian.PutUint64(dbval, dbIndex)
+ dbval = append(dbval, value...)
+
+ err = bucket.Put([]byte(key), dbval)
+ if err != nil {
+ return err
+ }
+ return nil
+ })
+ return err
+}
+
+//Delete the value for the given key.
+func (b *BoltDB) Delete(key string) error {
+ var (
+ db *bolt.DB
+ err error
+ )
+ b.Lock()
+ defer b.Unlock()
+
+ if db, err = b.getDBhandle(); err != nil {
+ return err
+ }
+ defer b.releaseDBhandle()
+
+ err = db.Update(func(tx *bolt.Tx) error {
+ bucket := tx.Bucket(b.boltBucket)
+ if bucket == nil {
+ return store.ErrKeyNotFound
+ }
+ err := bucket.Delete([]byte(key))
+ return err
+ })
+ return err
+}
+
+// Exists checks if the key exists inside the store
+func (b *BoltDB) Exists(key string) (bool, error) {
+ var (
+ val []byte
+ db *bolt.DB
+ err error
+ )
+ b.Lock()
+ defer b.Unlock()
+
+ if db, err = b.getDBhandle(); err != nil {
+ return false, err
+ }
+ defer b.releaseDBhandle()
+
+ err = db.View(func(tx *bolt.Tx) error {
+ bucket := tx.Bucket(b.boltBucket)
+ if bucket == nil {
+ return store.ErrKeyNotFound
+ }
+
+ val = bucket.Get([]byte(key))
+
+ return nil
+ })
+
+ if len(val) == 0 {
+ return false, err
+ }
+ return true, err
+}
+
+// List returns the range of keys starting with the passed in prefix
+func (b *BoltDB) List(keyPrefix string) ([]*store.KVPair, error) {
+ var (
+ db *bolt.DB
+ err error
+ )
+ b.Lock()
+ defer b.Unlock()
+
+ kv := []*store.KVPair{}
+
+ if db, err = b.getDBhandle(); err != nil {
+ return nil, err
+ }
+ defer b.releaseDBhandle()
+
+ err = db.View(func(tx *bolt.Tx) error {
+ bucket := tx.Bucket(b.boltBucket)
+ if bucket == nil {
+ return store.ErrKeyNotFound
+ }
+
+ cursor := bucket.Cursor()
+ prefix := []byte(keyPrefix)
+
+ for key, v := cursor.Seek(prefix); bytes.HasPrefix(key, prefix); key, v = cursor.Next() {
+
+ dbIndex := binary.LittleEndian.Uint64(v[:libkvmetadatalen])
+ v = v[libkvmetadatalen:]
+ val := make([]byte, len(v))
+ copy(val, v)
+
+ kv = append(kv, &store.KVPair{
+ Key: string(key),
+ Value: val,
+ LastIndex: dbIndex,
+ })
+ }
+ return nil
+ })
+ if len(kv) == 0 {
+ return nil, store.ErrKeyNotFound
+ }
+ return kv, err
+}
+
+// AtomicDelete deletes a value at "key" if the key
+// has not been modified in the meantime, throws an
+// error if this is the case
+func (b *BoltDB) AtomicDelete(key string, previous *store.KVPair) (bool, error) {
+ var (
+ val []byte
+ db *bolt.DB
+ err error
+ )
+ b.Lock()
+ defer b.Unlock()
+
+ if previous == nil {
+ return false, store.ErrPreviousNotSpecified
+ }
+ if db, err = b.getDBhandle(); err != nil {
+ return false, err
+ }
+ defer b.releaseDBhandle()
+
+ err = db.Update(func(tx *bolt.Tx) error {
+ bucket := tx.Bucket(b.boltBucket)
+ if bucket == nil {
+ return store.ErrKeyNotFound
+ }
+
+ val = bucket.Get([]byte(key))
+ if val == nil {
+ return store.ErrKeyNotFound
+ }
+ dbIndex := binary.LittleEndian.Uint64(val[:libkvmetadatalen])
+ if dbIndex != previous.LastIndex {
+ return store.ErrKeyModified
+ }
+ err := bucket.Delete([]byte(key))
+ return err
+ })
+ if err != nil {
+ return false, err
+ }
+ return true, err
+}
+
+// AtomicPut puts a value at "key" if the key has not been
+// modified since the last Put, throws an error if this is the case
+func (b *BoltDB) AtomicPut(key string, value []byte, previous *store.KVPair, options *store.WriteOptions) (bool, *store.KVPair, error) {
+ var (
+ val []byte
+ dbIndex uint64
+ db *bolt.DB
+ err error
+ )
+ b.Lock()
+ defer b.Unlock()
+
+ dbval := make([]byte, libkvmetadatalen)
+
+ if db, err = b.getDBhandle(); err != nil {
+ return false, nil, err
+ }
+ defer b.releaseDBhandle()
+
+ err = db.Update(func(tx *bolt.Tx) error {
+ var err error
+ bucket := tx.Bucket(b.boltBucket)
+ if bucket == nil {
+ if previous != nil {
+ return store.ErrKeyNotFound
+ }
+ bucket, err = tx.CreateBucket(b.boltBucket)
+ if err != nil {
+ return err
+ }
+ }
+ // AtomicPut is equivalent to Put if previous is nil and the Ky
+ // doesn't exist in the DB.
+ val = bucket.Get([]byte(key))
+ if previous == nil && len(val) != 0 {
+ return store.ErrKeyExists
+ }
+ if previous != nil {
+ if len(val) == 0 {
+ return store.ErrKeyNotFound
+ }
+ dbIndex = binary.LittleEndian.Uint64(val[:libkvmetadatalen])
+ if dbIndex != previous.LastIndex {
+ return store.ErrKeyModified
+ }
+ }
+ dbIndex = atomic.AddUint64(&b.dbIndex, 1)
+ binary.LittleEndian.PutUint64(dbval, b.dbIndex)
+ dbval = append(dbval, value...)
+ return (bucket.Put([]byte(key), dbval))
+ })
+ if err != nil {
+ return false, nil, err
+ }
+
+ updated := &store.KVPair{
+ Key: key,
+ Value: value,
+ LastIndex: dbIndex,
+ }
+
+ return true, updated, nil
+}
+
+// Close the db connection to the BoltDB
+func (b *BoltDB) Close() {
+ b.Lock()
+ defer b.Unlock()
+
+ if !b.PersistConnection {
+ b.reset()
+ } else {
+ b.client.Close()
+ }
+ return
+}
+
+// DeleteTree deletes a range of keys with a given prefix
+func (b *BoltDB) DeleteTree(keyPrefix string) error {
+ var (
+ db *bolt.DB
+ err error
+ )
+ b.Lock()
+ defer b.Unlock()
+
+ if db, err = b.getDBhandle(); err != nil {
+ return err
+ }
+ defer b.releaseDBhandle()
+
+ err = db.Update(func(tx *bolt.Tx) error {
+ bucket := tx.Bucket(b.boltBucket)
+ if bucket == nil {
+ return store.ErrKeyNotFound
+ }
+
+ cursor := bucket.Cursor()
+ prefix := []byte(keyPrefix)
+
+ for key, _ := cursor.Seek(prefix); bytes.HasPrefix(key, prefix); key, _ = cursor.Next() {
+ _ = bucket.Delete([]byte(key))
+ }
+ return nil
+ })
+
+ return err
+}
+
+// NewLock has to implemented at the library level since its not supported by BoltDB
+func (b *BoltDB) NewLock(key string, options *store.LockOptions) (store.Locker, error) {
+ return nil, store.ErrCallNotSupported
+}
+
+// Watch has to implemented at the library level since its not supported by BoltDB
+func (b *BoltDB) Watch(key string, stopCh <-chan struct{}) (<-chan *store.KVPair, error) {
+ return nil, store.ErrCallNotSupported
+}
+
+// WatchTree has to implemented at the library level since its not supported by BoltDB
+func (b *BoltDB) WatchTree(directory string, stopCh <-chan struct{}) (<-chan []*store.KVPair, error) {
+ return nil, store.ErrCallNotSupported
+}
diff --git a/vendor/github.com/docker/libkv/store/helpers.go b/vendor/github.com/docker/libkv/store/helpers.go
new file mode 100644
index 0000000..0fb74c9
--- /dev/null
+++ b/vendor/github.com/docker/libkv/store/helpers.go
@@ -0,0 +1,47 @@
+package store
+
+import (
+ "strings"
+)
+
+// CreateEndpoints creates a list of endpoints given the right scheme
+func CreateEndpoints(addrs []string, scheme string) (entries []string) {
+ for _, addr := range addrs {
+ entries = append(entries, scheme+"://"+addr)
+ }
+ return entries
+}
+
+// Normalize the key for each store to the form:
+//
+// /path/to/key
+//
+func Normalize(key string) string {
+ return "/" + join(SplitKey(key))
+}
+
+// GetDirectory gets the full directory part of
+// the key to the form:
+//
+// /path/to/
+//
+func GetDirectory(key string) string {
+ parts := SplitKey(key)
+ parts = parts[:len(parts)-1]
+ return "/" + join(parts)
+}
+
+// SplitKey splits the key to extract path informations
+func SplitKey(key string) (path []string) {
+ if strings.Contains(key, "/") {
+ path = strings.Split(key, "/")
+ } else {
+ path = []string{key}
+ }
+ return path
+}
+
+// join the path parts with '/'
+func join(parts []string) string {
+ return strings.Join(parts, "/")
+}
diff --git a/vendor/github.com/docker/libkv/store/store.go b/vendor/github.com/docker/libkv/store/store.go
new file mode 100644
index 0000000..7a4850c
--- /dev/null
+++ b/vendor/github.com/docker/libkv/store/store.go
@@ -0,0 +1,132 @@
+package store
+
+import (
+ "crypto/tls"
+ "errors"
+ "time"
+)
+
+// Backend represents a KV Store Backend
+type Backend string
+
+const (
+ // CONSUL backend
+ CONSUL Backend = "consul"
+ // ETCD backend
+ ETCD Backend = "etcd"
+ // ZK backend
+ ZK Backend = "zk"
+ // BOLTDB backend
+ BOLTDB Backend = "boltdb"
+)
+
+var (
+ // ErrBackendNotSupported is thrown when the backend k/v store is not supported by libkv
+ ErrBackendNotSupported = errors.New("Backend storage not supported yet, please choose one of")
+ // ErrCallNotSupported is thrown when a method is not implemented/supported by the current backend
+ ErrCallNotSupported = errors.New("The current call is not supported with this backend")
+ // ErrNotReachable is thrown when the API cannot be reached for issuing common store operations
+ ErrNotReachable = errors.New("Api not reachable")
+ // ErrCannotLock is thrown when there is an error acquiring a lock on a key
+ ErrCannotLock = errors.New("Error acquiring the lock")
+ // ErrKeyModified is thrown during an atomic operation if the index does not match the one in the store
+ ErrKeyModified = errors.New("Unable to complete atomic operation, key modified")
+ // ErrKeyNotFound is thrown when the key is not found in the store during a Get operation
+ ErrKeyNotFound = errors.New("Key not found in store")
+ // ErrPreviousNotSpecified is thrown when the previous value is not specified for an atomic operation
+ ErrPreviousNotSpecified = errors.New("Previous K/V pair should be provided for the Atomic operation")
+ // ErrKeyExists is thrown when the previous value exists in the case of an AtomicPut
+ ErrKeyExists = errors.New("Previous K/V pair exists, cannot complete Atomic operation")
+)
+
+// Config contains the options for a storage client
+type Config struct {
+ ClientTLS *ClientTLSConfig
+ TLS *tls.Config
+ ConnectionTimeout time.Duration
+ Bucket string
+ PersistConnection bool
+ Username string
+ Password string
+}
+
+// ClientTLSConfig contains data for a Client TLS configuration in the form
+// the etcd client wants it. Eventually we'll adapt it for ZK and Consul.
+type ClientTLSConfig struct {
+ CertFile string
+ KeyFile string
+ CACertFile string
+}
+
+// Store represents the backend K/V storage
+// Each store should support every call listed
+// here. Or it couldn't be implemented as a K/V
+// backend for libkv
+type Store interface {
+ // Put a value at the specified key
+ Put(key string, value []byte, options *WriteOptions) error
+
+ // Get a value given its key
+ Get(key string) (*KVPair, error)
+
+ // Delete the value at the specified key
+ Delete(key string) error
+
+ // Verify if a Key exists in the store
+ Exists(key string) (bool, error)
+
+ // Watch for changes on a key
+ Watch(key string, stopCh <-chan struct{}) (<-chan *KVPair, error)
+
+ // WatchTree watches for changes on child nodes under
+ // a given directory
+ WatchTree(directory string, stopCh <-chan struct{}) (<-chan []*KVPair, error)
+
+ // NewLock creates a lock for a given key.
+ // The returned Locker is not held and must be acquired
+ // with `.Lock`. The Value is optional.
+ NewLock(key string, options *LockOptions) (Locker, error)
+
+ // List the content of a given prefix
+ List(directory string) ([]*KVPair, error)
+
+ // DeleteTree deletes a range of keys under a given directory
+ DeleteTree(directory string) error
+
+ // Atomic CAS operation on a single value.
+ // Pass previous = nil to create a new key.
+ AtomicPut(key string, value []byte, previous *KVPair, options *WriteOptions) (bool, *KVPair, error)
+
+ // Atomic delete of a single value
+ AtomicDelete(key string, previous *KVPair) (bool, error)
+
+ // Close the store connection
+ Close()
+}
+
+// KVPair represents {Key, Value, Lastindex} tuple
+type KVPair struct {
+ Key string
+ Value []byte
+ LastIndex uint64
+}
+
+// WriteOptions contains optional request parameters
+type WriteOptions struct {
+ IsDir bool
+ TTL time.Duration
+}
+
+// LockOptions contains optional request parameters
+type LockOptions struct {
+ Value []byte // Optional, value to associate with the lock
+ TTL time.Duration // Optional, expiration ttl associated with the lock
+ RenewLock chan struct{} // Optional, chan used to control and stop the session ttl renewal for the lock
+}
+
+// Locker provides locking mechanism on top of the store.
+// Similar to `sync.Lock` except it may return errors.
+type Locker interface {
+ Lock(stopChan chan struct{}) (<-chan struct{}, error)
+ Unlock() error
+}
diff --git a/vendor/github.com/docker/libnetwork/LICENSE b/vendor/github.com/docker/libnetwork/LICENSE
new file mode 100644
index 0000000..e06d208
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/LICENSE
@@ -0,0 +1,202 @@
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/vendor/github.com/docker/libnetwork/README.md b/vendor/github.com/docker/libnetwork/README.md
new file mode 100644
index 0000000..536f8aa
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/README.md
@@ -0,0 +1,89 @@
+# libnetwork - networking for containers
+
+[![Circle CI](https://circleci.com/gh/docker/libnetwork/tree/master.svg?style=svg)](https://circleci.com/gh/docker/libnetwork/tree/master) [![Coverage Status](https://coveralls.io/repos/docker/libnetwork/badge.svg)](https://coveralls.io/r/docker/libnetwork) [![GoDoc](https://godoc.org/github.com/docker/libnetwork?status.svg)](https://godoc.org/github.com/docker/libnetwork)
+
+Libnetwork provides a native Go implementation for connecting containers
+
+The goal of libnetwork is to deliver a robust Container Network Model that provides a consistent programming interface and the required network abstractions for applications.
+
+#### Design
+Please refer to the [design](docs/design.md) for more information.
+
+#### Using libnetwork
+
+There are many networking solutions available to suit a broad range of use-cases. libnetwork uses a driver / plugin model to support all of these solutions while abstracting the complexity of the driver implementations by exposing a simple and consistent Network Model to users.
+
+
+```go
+func main() {
+ if reexec.Init() {
+ return
+ }
+
+ // Select and configure the network driver
+ networkType := "bridge"
+
+ // Create a new controller instance
+ driverOptions := options.Generic{}
+ genericOption := make(map[string]interface{})
+ genericOption[netlabel.GenericData] = driverOptions
+ controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
+ if err != nil {
+ log.Fatalf("libnetwork.New: %s", err)
+ }
+
+ // Create a network for containers to join.
+ // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can use.
+ network, err := controller.NewNetwork(networkType, "network1", "")
+ if err != nil {
+ log.Fatalf("controller.NewNetwork: %s", err)
+ }
+
+ // For each new container: allocate IP and interfaces. The returned network
+ // settings will be used for container infos (inspect and such), as well as
+ // iptables rules for port publishing. This info is contained or accessible
+ // from the returned endpoint.
+ ep, err := network.CreateEndpoint("Endpoint1")
+ if err != nil {
+ log.Fatalf("network.CreateEndpoint: %s", err)
+ }
+
+ // Create the sandbox for the container.
+ // NewSandbox accepts Variadic optional arguments which libnetwork can use.
+ sbx, err := controller.NewSandbox("container1",
+ libnetwork.OptionHostname("test"),
+ libnetwork.OptionDomainname("docker.io"))
+ if err != nil {
+ log.Fatalf("controller.NewSandbox: %s", err)
+ }
+
+ // A sandbox can join the endpoint via the join api.
+ err = ep.Join(sbx)
+ if err != nil {
+ log.Fatalf("ep.Join: %s", err)
+ }
+
+ // libnetwork client can check the endpoint's operational data via the Info() API
+ epInfo, err := ep.DriverInfo()
+ if err != nil {
+ log.Fatalf("ep.DriverInfo: %s", err)
+ }
+
+ macAddress, ok := epInfo[netlabel.MacAddress]
+ if !ok {
+ log.Fatalf("failed to get mac address from endpoint info")
+ }
+
+ fmt.Printf("Joined endpoint %s (%s) to sandbox %s (%s)\n", ep.Name(), macAddress, sbx.ContainerID(), sbx.Key())
+}
+```
+
+## Future
+Please refer to [roadmap](ROADMAP.md) for more information.
+
+## Contributing
+
+Want to hack on libnetwork? [Docker's contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md) apply.
+
+## Copyright and license
+Code and documentation copyright 2015 Docker, inc. Code released under the Apache 2.0 license. Docs released under Creative commons.
diff --git a/vendor/github.com/docker/libnetwork/agent.go b/vendor/github.com/docker/libnetwork/agent.go
new file mode 100644
index 0000000..a45a569
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/agent.go
@@ -0,0 +1,915 @@
+package libnetwork
+
+//go:generate protoc -I.:Godeps/_workspace/src/github.com/gogo/protobuf --gogo_out=import_path=github.com/docker/libnetwork,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto:. agent.proto
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+ "os"
+ "sort"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/stringid"
+ "github.com/docker/go-events"
+ "github.com/docker/libnetwork/cluster"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/networkdb"
+ "github.com/docker/libnetwork/types"
+ "github.com/gogo/protobuf/proto"
+)
+
+const (
+ subsysGossip = "networking:gossip"
+ subsysIPSec = "networking:ipsec"
+ keyringSize = 3
+)
+
+// ByTime implements sort.Interface for []*types.EncryptionKey based on
+// the LamportTime field.
+type ByTime []*types.EncryptionKey
+
+func (b ByTime) Len() int { return len(b) }
+func (b ByTime) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
+func (b ByTime) Less(i, j int) bool { return b[i].LamportTime < b[j].LamportTime }
+
+type agent struct {
+ networkDB *networkdb.NetworkDB
+ bindAddr string
+ advertiseAddr string
+ dataPathAddr string
+ coreCancelFuncs []func()
+ driverCancelFuncs map[string][]func()
+ sync.Mutex
+}
+
+func (a *agent) dataPathAddress() string {
+ a.Lock()
+ defer a.Unlock()
+ if a.dataPathAddr != "" {
+ return a.dataPathAddr
+ }
+ return a.advertiseAddr
+}
+
+const libnetworkEPTable = "endpoint_table"
+
+func getBindAddr(ifaceName string) (string, error) {
+ iface, err := net.InterfaceByName(ifaceName)
+ if err != nil {
+ return "", fmt.Errorf("failed to find interface %s: %v", ifaceName, err)
+ }
+
+ addrs, err := iface.Addrs()
+ if err != nil {
+ return "", fmt.Errorf("failed to get interface addresses: %v", err)
+ }
+
+ for _, a := range addrs {
+ addr, ok := a.(*net.IPNet)
+ if !ok {
+ continue
+ }
+ addrIP := addr.IP
+
+ if addrIP.IsLinkLocalUnicast() {
+ continue
+ }
+
+ return addrIP.String(), nil
+ }
+
+ return "", fmt.Errorf("failed to get bind address")
+}
+
+func resolveAddr(addrOrInterface string) (string, error) {
+ // Try and see if this is a valid IP address
+ if net.ParseIP(addrOrInterface) != nil {
+ return addrOrInterface, nil
+ }
+
+ addr, err := net.ResolveIPAddr("ip", addrOrInterface)
+ if err != nil {
+ // If not a valid IP address, it should be a valid interface
+ return getBindAddr(addrOrInterface)
+ }
+ return addr.String(), nil
+}
+
+func (c *controller) handleKeyChange(keys []*types.EncryptionKey) error {
+ drvEnc := discoverapi.DriverEncryptionUpdate{}
+
+ a := c.getAgent()
+ if a == nil {
+ logrus.Debug("Skipping key change as agent is nil")
+ return nil
+ }
+
+ // Find the deleted key. If the deleted key was the primary key,
+ // a new primary key should be set before removing if from keyring.
+ c.Lock()
+ added := []byte{}
+ deleted := []byte{}
+ j := len(c.keys)
+ for i := 0; i < j; {
+ same := false
+ for _, key := range keys {
+ if same = key.LamportTime == c.keys[i].LamportTime; same {
+ break
+ }
+ }
+ if !same {
+ cKey := c.keys[i]
+ if cKey.Subsystem == subsysGossip {
+ deleted = cKey.Key
+ }
+
+ if cKey.Subsystem == subsysIPSec {
+ drvEnc.Prune = cKey.Key
+ drvEnc.PruneTag = cKey.LamportTime
+ }
+ c.keys[i], c.keys[j-1] = c.keys[j-1], c.keys[i]
+ c.keys[j-1] = nil
+ j--
+ }
+ i++
+ }
+ c.keys = c.keys[:j]
+
+ // Find the new key and add it to the key ring
+ for _, key := range keys {
+ same := false
+ for _, cKey := range c.keys {
+ if same = cKey.LamportTime == key.LamportTime; same {
+ break
+ }
+ }
+ if !same {
+ c.keys = append(c.keys, key)
+ if key.Subsystem == subsysGossip {
+ added = key.Key
+ }
+
+ if key.Subsystem == subsysIPSec {
+ drvEnc.Key = key.Key
+ drvEnc.Tag = key.LamportTime
+ }
+ }
+ }
+ c.Unlock()
+
+ if len(added) > 0 {
+ a.networkDB.SetKey(added)
+ }
+
+ key, _, err := c.getPrimaryKeyTag(subsysGossip)
+ if err != nil {
+ return err
+ }
+ a.networkDB.SetPrimaryKey(key)
+
+ key, tag, err := c.getPrimaryKeyTag(subsysIPSec)
+ if err != nil {
+ return err
+ }
+ drvEnc.Primary = key
+ drvEnc.PrimaryTag = tag
+
+ if len(deleted) > 0 {
+ a.networkDB.RemoveKey(deleted)
+ }
+
+ c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
+ err := driver.DiscoverNew(discoverapi.EncryptionKeysUpdate, drvEnc)
+ if err != nil {
+ logrus.Warnf("Failed to update datapath keys in driver %s: %v", name, err)
+ }
+ return false
+ })
+
+ return nil
+}
+
+func (c *controller) agentSetup(clusterProvider cluster.Provider) error {
+ agent := c.getAgent()
+
+ // If the agent is already present there is no need to try to initilize it again
+ if agent != nil {
+ return nil
+ }
+
+ bindAddr := clusterProvider.GetLocalAddress()
+ advAddr := clusterProvider.GetAdvertiseAddress()
+ dataAddr := clusterProvider.GetDataPathAddress()
+ remoteList := clusterProvider.GetRemoteAddressList()
+ remoteAddrList := make([]string, 0, len(remoteList))
+ for _, remote := range remoteList {
+ addr, _, _ := net.SplitHostPort(remote)
+ remoteAddrList = append(remoteAddrList, addr)
+ }
+
+ listen := clusterProvider.GetListenAddress()
+ listenAddr, _, _ := net.SplitHostPort(listen)
+
+ logrus.Infof("Initializing Libnetwork Agent Listen-Addr=%s Local-addr=%s Adv-addr=%s Data-addr=%s Remote-addr-list=%v",
+ listenAddr, bindAddr, advAddr, dataAddr, remoteAddrList)
+ if advAddr != "" && agent == nil {
+ if err := c.agentInit(listenAddr, bindAddr, advAddr, dataAddr); err != nil {
+ logrus.Errorf("error in agentInit: %v", err)
+ return err
+ }
+ c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
+ if capability.ConnectivityScope == datastore.GlobalScope {
+ c.agentDriverNotify(driver)
+ }
+ return false
+ })
+ }
+
+ if len(remoteAddrList) > 0 {
+ if err := c.agentJoin(remoteAddrList); err != nil {
+ logrus.Errorf("Error in joining gossip cluster : %v(join will be retried in background)", err)
+ }
+ }
+
+ return nil
+}
+
+// For a given subsystem getKeys sorts the keys by lamport time and returns
+// slice of keys and lamport time which can used as a unique tag for the keys
+func (c *controller) getKeys(subsys string) ([][]byte, []uint64) {
+ c.Lock()
+ defer c.Unlock()
+
+ sort.Sort(ByTime(c.keys))
+
+ keys := [][]byte{}
+ tags := []uint64{}
+ for _, key := range c.keys {
+ if key.Subsystem == subsys {
+ keys = append(keys, key.Key)
+ tags = append(tags, key.LamportTime)
+ }
+ }
+
+ keys[0], keys[1] = keys[1], keys[0]
+ tags[0], tags[1] = tags[1], tags[0]
+ return keys, tags
+}
+
+// getPrimaryKeyTag returns the primary key for a given subsystem from the
+// list of sorted key and the associated tag
+func (c *controller) getPrimaryKeyTag(subsys string) ([]byte, uint64, error) {
+ c.Lock()
+ defer c.Unlock()
+ sort.Sort(ByTime(c.keys))
+ keys := []*types.EncryptionKey{}
+ for _, key := range c.keys {
+ if key.Subsystem == subsys {
+ keys = append(keys, key)
+ }
+ }
+ return keys[1].Key, keys[1].LamportTime, nil
+}
+
+func (c *controller) agentInit(listenAddr, bindAddrOrInterface, advertiseAddr, dataPathAddr string) error {
+ bindAddr, err := resolveAddr(bindAddrOrInterface)
+ if err != nil {
+ return err
+ }
+
+ keys, _ := c.getKeys(subsysGossip)
+ hostname, _ := os.Hostname()
+ nodeName := hostname + "-" + stringid.TruncateID(stringid.GenerateRandomID())
+ logrus.Info("Gossip cluster hostname ", nodeName)
+
+ nDB, err := networkdb.New(&networkdb.Config{
+ BindAddr: listenAddr,
+ AdvertiseAddr: advertiseAddr,
+ NodeName: nodeName,
+ Keys: keys,
+ })
+
+ if err != nil {
+ return err
+ }
+
+ var cancelList []func()
+ ch, cancel := nDB.Watch(libnetworkEPTable, "", "")
+ cancelList = append(cancelList, cancel)
+ nodeCh, cancel := nDB.Watch(networkdb.NodeTable, "", "")
+ cancelList = append(cancelList, cancel)
+
+ c.Lock()
+ c.agent = &agent{
+ networkDB: nDB,
+ bindAddr: bindAddr,
+ advertiseAddr: advertiseAddr,
+ dataPathAddr: dataPathAddr,
+ coreCancelFuncs: cancelList,
+ driverCancelFuncs: make(map[string][]func()),
+ }
+ c.Unlock()
+
+ go c.handleTableEvents(ch, c.handleEpTableEvent)
+ go c.handleTableEvents(nodeCh, c.handleNodeTableEvent)
+
+ drvEnc := discoverapi.DriverEncryptionConfig{}
+ keys, tags := c.getKeys(subsysIPSec)
+ drvEnc.Keys = keys
+ drvEnc.Tags = tags
+
+ c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
+ err := driver.DiscoverNew(discoverapi.EncryptionKeysConfig, drvEnc)
+ if err != nil {
+ logrus.Warnf("Failed to set datapath keys in driver %s: %v", name, err)
+ }
+ return false
+ })
+
+ c.WalkNetworks(joinCluster)
+
+ return nil
+}
+
+func (c *controller) agentJoin(remoteAddrList []string) error {
+ agent := c.getAgent()
+ if agent == nil {
+ return nil
+ }
+ return agent.networkDB.Join(remoteAddrList)
+}
+
+func (c *controller) agentDriverNotify(d driverapi.Driver) {
+ agent := c.getAgent()
+ if agent == nil {
+ return
+ }
+
+ if err := d.DiscoverNew(discoverapi.NodeDiscovery, discoverapi.NodeDiscoveryData{
+ Address: agent.dataPathAddress(),
+ BindAddress: agent.bindAddr,
+ Self: true,
+ }); err != nil {
+ logrus.Warnf("Failed the node discovery in driver: %v", err)
+ }
+
+ drvEnc := discoverapi.DriverEncryptionConfig{}
+ keys, tags := c.getKeys(subsysIPSec)
+ drvEnc.Keys = keys
+ drvEnc.Tags = tags
+
+ if err := d.DiscoverNew(discoverapi.EncryptionKeysConfig, drvEnc); err != nil {
+ logrus.Warnf("Failed to set datapath keys in driver: %v", err)
+ }
+}
+
+func (c *controller) agentClose() {
+ // Acquire current agent instance and reset its pointer
+ // then run closing functions
+ c.Lock()
+ agent := c.agent
+ c.agent = nil
+ c.Unlock()
+
+ if agent == nil {
+ return
+ }
+
+ var cancelList []func()
+
+ agent.Lock()
+ for _, cancelFuncs := range agent.driverCancelFuncs {
+ for _, cancel := range cancelFuncs {
+ cancelList = append(cancelList, cancel)
+ }
+ }
+
+ // Add also the cancel functions for the network db
+ for _, cancel := range agent.coreCancelFuncs {
+ cancelList = append(cancelList, cancel)
+ }
+ agent.Unlock()
+
+ for _, cancel := range cancelList {
+ cancel()
+ }
+
+ agent.networkDB.Close()
+}
+
+// Task has the backend container details
+type Task struct {
+ Name string
+ EndpointID string
+ EndpointIP string
+ Info map[string]string
+}
+
+// ServiceInfo has service specific details along with the list of backend tasks
+type ServiceInfo struct {
+ VIP string
+ LocalLBIndex int
+ Tasks []Task
+ Ports []string
+}
+
+type epRecord struct {
+ ep EndpointRecord
+ info map[string]string
+ lbIndex int
+}
+
+func (n *network) Services() map[string]ServiceInfo {
+ eps := make(map[string]epRecord)
+
+ if !n.isClusterEligible() {
+ return nil
+ }
+ agent := n.getController().getAgent()
+ if agent == nil {
+ return nil
+ }
+
+ // Walk through libnetworkEPTable and fetch the driver agnostic endpoint info
+ entries := agent.networkDB.GetTableByNetwork(libnetworkEPTable, n.id)
+ for eid, value := range entries {
+ var epRec EndpointRecord
+ nid := n.ID()
+ if err := proto.Unmarshal(value.([]byte), &epRec); err != nil {
+ logrus.Errorf("Unmarshal of libnetworkEPTable failed for endpoint %s in network %s, %v", eid, nid, err)
+ continue
+ }
+ i := n.getController().getLBIndex(epRec.ServiceID, nid, epRec.IngressPorts)
+ eps[eid] = epRecord{
+ ep: epRec,
+ lbIndex: i,
+ }
+ }
+
+ // Walk through the driver's tables, have the driver decode the entries
+ // and return the tuple {ep ID, value}. value is a string that coveys
+ // relevant info about the endpoint.
+ d, err := n.driver(true)
+ if err != nil {
+ logrus.Errorf("Could not resolve driver for network %s/%s while fetching services: %v", n.networkType, n.ID(), err)
+ return nil
+ }
+ for _, table := range n.driverTables {
+ if table.objType != driverapi.EndpointObject {
+ continue
+ }
+ entries := agent.networkDB.GetTableByNetwork(table.name, n.id)
+ for key, value := range entries {
+ epID, info := d.DecodeTableEntry(table.name, key, value.([]byte))
+ if ep, ok := eps[epID]; !ok {
+ logrus.Errorf("Inconsistent driver and libnetwork state for endpoint %s", epID)
+ } else {
+ ep.info = info
+ eps[epID] = ep
+ }
+ }
+ }
+
+ // group the endpoints into a map keyed by the service name
+ sinfo := make(map[string]ServiceInfo)
+ for ep, epr := range eps {
+ var (
+ s ServiceInfo
+ ok bool
+ )
+ if s, ok = sinfo[epr.ep.ServiceName]; !ok {
+ s = ServiceInfo{
+ VIP: epr.ep.VirtualIP,
+ LocalLBIndex: epr.lbIndex,
+ }
+ }
+ ports := []string{}
+ if s.Ports == nil {
+ for _, port := range epr.ep.IngressPorts {
+ p := fmt.Sprintf("Target: %d, Publish: %d", port.TargetPort, port.PublishedPort)
+ ports = append(ports, p)
+ }
+ s.Ports = ports
+ }
+ s.Tasks = append(s.Tasks, Task{
+ Name: epr.ep.Name,
+ EndpointID: ep,
+ EndpointIP: epr.ep.EndpointIP,
+ Info: epr.info,
+ })
+ sinfo[epr.ep.ServiceName] = s
+ }
+ return sinfo
+}
+
+func (n *network) isClusterEligible() bool {
+ if n.scope != datastore.SwarmScope || !n.driverIsMultihost() {
+ return false
+ }
+ return n.getController().getAgent() != nil
+}
+
+func (n *network) joinCluster() error {
+ if !n.isClusterEligible() {
+ return nil
+ }
+
+ agent := n.getController().getAgent()
+ if agent == nil {
+ return nil
+ }
+
+ return agent.networkDB.JoinNetwork(n.ID())
+}
+
+func (n *network) leaveCluster() error {
+ if !n.isClusterEligible() {
+ return nil
+ }
+
+ agent := n.getController().getAgent()
+ if agent == nil {
+ return nil
+ }
+
+ return agent.networkDB.LeaveNetwork(n.ID())
+}
+
+func (ep *endpoint) addDriverInfoToCluster() error {
+ n := ep.getNetwork()
+ if !n.isClusterEligible() {
+ return nil
+ }
+ if ep.joinInfo == nil {
+ return nil
+ }
+
+ agent := n.getController().getAgent()
+ if agent == nil {
+ return nil
+ }
+
+ for _, te := range ep.joinInfo.driverTableEntries {
+ if err := agent.networkDB.CreateEntry(te.tableName, n.ID(), te.key, te.value); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (ep *endpoint) deleteDriverInfoFromCluster() error {
+ n := ep.getNetwork()
+ if !n.isClusterEligible() {
+ return nil
+ }
+ if ep.joinInfo == nil {
+ return nil
+ }
+
+ agent := n.getController().getAgent()
+ if agent == nil {
+ return nil
+ }
+
+ for _, te := range ep.joinInfo.driverTableEntries {
+ if err := agent.networkDB.DeleteEntry(te.tableName, n.ID(), te.key); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (ep *endpoint) addServiceInfoToCluster(sb *sandbox) error {
+ if ep.isAnonymous() && len(ep.myAliases) == 0 || ep.Iface().Address() == nil {
+ return nil
+ }
+
+ n := ep.getNetwork()
+ if !n.isClusterEligible() {
+ return nil
+ }
+
+ sb.Service.Lock()
+ defer sb.Service.Unlock()
+ logrus.Debugf("addServiceInfoToCluster START for %s %s", ep.svcName, ep.ID())
+
+ // Check that the endpoint is still present on the sandbox before adding it to the service discovery.
+ // This is to handle a race between the EnableService and the sbLeave
+ // It is possible that the EnableService starts, fetches the list of the endpoints and
+ // by the time the addServiceInfoToCluster is called the endpoint got removed from the sandbox
+ // The risk is that the deleteServiceInfoToCluster happens before the addServiceInfoToCluster.
+ // This check under the Service lock of the sandbox ensure the correct behavior.
+ // If the addServiceInfoToCluster arrives first may find or not the endpoint and will proceed or exit
+ // but in any case the deleteServiceInfoToCluster will follow doing the cleanup if needed.
+ // In case the deleteServiceInfoToCluster arrives first, this one is happening after the endpoint is
+ // removed from the list, in this situation the delete will bail out not finding any data to cleanup
+ // and the add will bail out not finding the endpoint on the sandbox.
+ if e := sb.getEndpoint(ep.ID()); e == nil {
+ logrus.Warnf("addServiceInfoToCluster suppressing service resolution ep is not anymore in the sandbox %s", ep.ID())
+ return nil
+ }
+
+ c := n.getController()
+ agent := c.getAgent()
+
+ name := ep.Name()
+ if ep.isAnonymous() {
+ name = ep.MyAliases()[0]
+ }
+
+ var ingressPorts []*PortConfig
+ if ep.svcID != "" {
+ // This is a task part of a service
+ // Gossip ingress ports only in ingress network.
+ if n.ingress {
+ ingressPorts = ep.ingressPorts
+ }
+ if err := c.addServiceBinding(ep.svcName, ep.svcID, n.ID(), ep.ID(), name, ep.virtualIP, ingressPorts, ep.svcAliases, ep.myAliases, ep.Iface().Address().IP, "addServiceInfoToCluster"); err != nil {
+ return err
+ }
+ } else {
+ // This is a container simply attached to an attachable network
+ if err := c.addContainerNameResolution(n.ID(), ep.ID(), name, ep.myAliases, ep.Iface().Address().IP, "addServiceInfoToCluster"); err != nil {
+ return err
+ }
+ }
+
+ buf, err := proto.Marshal(&EndpointRecord{
+ Name: name,
+ ServiceName: ep.svcName,
+ ServiceID: ep.svcID,
+ VirtualIP: ep.virtualIP.String(),
+ IngressPorts: ingressPorts,
+ Aliases: ep.svcAliases,
+ TaskAliases: ep.myAliases,
+ EndpointIP: ep.Iface().Address().IP.String(),
+ })
+ if err != nil {
+ return err
+ }
+
+ if agent != nil {
+ if err := agent.networkDB.CreateEntry(libnetworkEPTable, n.ID(), ep.ID(), buf); err != nil {
+ logrus.Warnf("addServiceInfoToCluster NetworkDB CreateEntry failed for %s %s err:%s", ep.id, n.id, err)
+ return err
+ }
+ }
+
+ logrus.Debugf("addServiceInfoToCluster END for %s %s", ep.svcName, ep.ID())
+
+ return nil
+}
+
+func (ep *endpoint) deleteServiceInfoFromCluster(sb *sandbox, method string) error {
+ if ep.isAnonymous() && len(ep.myAliases) == 0 {
+ return nil
+ }
+
+ n := ep.getNetwork()
+ if !n.isClusterEligible() {
+ return nil
+ }
+
+ sb.Service.Lock()
+ defer sb.Service.Unlock()
+ logrus.Debugf("deleteServiceInfoFromCluster from %s START for %s %s", method, ep.svcName, ep.ID())
+
+ c := n.getController()
+ agent := c.getAgent()
+
+ name := ep.Name()
+ if ep.isAnonymous() {
+ name = ep.MyAliases()[0]
+ }
+
+ if agent != nil {
+ // First delete from networkDB then locally
+ if err := agent.networkDB.DeleteEntry(libnetworkEPTable, n.ID(), ep.ID()); err != nil {
+ logrus.Warnf("deleteServiceInfoFromCluster NetworkDB DeleteEntry failed for %s %s err:%s", ep.id, n.id, err)
+ }
+ }
+
+ if ep.Iface().Address() != nil {
+ if ep.svcID != "" {
+ // This is a task part of a service
+ var ingressPorts []*PortConfig
+ if n.ingress {
+ ingressPorts = ep.ingressPorts
+ }
+ if err := c.rmServiceBinding(ep.svcName, ep.svcID, n.ID(), ep.ID(), name, ep.virtualIP, ingressPorts, ep.svcAliases, ep.myAliases, ep.Iface().Address().IP, "deleteServiceInfoFromCluster", true); err != nil {
+ return err
+ }
+ } else {
+ // This is a container simply attached to an attachable network
+ if err := c.delContainerNameResolution(n.ID(), ep.ID(), name, ep.myAliases, ep.Iface().Address().IP, "deleteServiceInfoFromCluster"); err != nil {
+ return err
+ }
+ }
+ }
+
+ logrus.Debugf("deleteServiceInfoFromCluster from %s END for %s %s", method, ep.svcName, ep.ID())
+
+ return nil
+}
+
+func (n *network) addDriverWatches() {
+ if !n.isClusterEligible() {
+ return
+ }
+
+ c := n.getController()
+ agent := c.getAgent()
+ if agent == nil {
+ return
+ }
+ for _, table := range n.driverTables {
+ ch, cancel := agent.networkDB.Watch(table.name, n.ID(), "")
+ agent.Lock()
+ agent.driverCancelFuncs[n.ID()] = append(agent.driverCancelFuncs[n.ID()], cancel)
+ agent.Unlock()
+ go c.handleTableEvents(ch, n.handleDriverTableEvent)
+ d, err := n.driver(false)
+ if err != nil {
+ logrus.Errorf("Could not resolve driver %s while walking driver tabl: %v", n.networkType, err)
+ return
+ }
+
+ agent.networkDB.WalkTable(table.name, func(nid, key string, value []byte) bool {
+ if nid == n.ID() {
+ d.EventNotify(driverapi.Create, nid, table.name, key, value)
+ }
+
+ return false
+ })
+ }
+}
+
+func (n *network) cancelDriverWatches() {
+ if !n.isClusterEligible() {
+ return
+ }
+
+ agent := n.getController().getAgent()
+ if agent == nil {
+ return
+ }
+
+ agent.Lock()
+ cancelFuncs := agent.driverCancelFuncs[n.ID()]
+ delete(agent.driverCancelFuncs, n.ID())
+ agent.Unlock()
+
+ for _, cancel := range cancelFuncs {
+ cancel()
+ }
+}
+
+func (c *controller) handleTableEvents(ch *events.Channel, fn func(events.Event)) {
+ for {
+ select {
+ case ev := <-ch.C:
+ fn(ev)
+ case <-ch.Done():
+ return
+ }
+ }
+}
+
+func (n *network) handleDriverTableEvent(ev events.Event) {
+ d, err := n.driver(false)
+ if err != nil {
+ logrus.Errorf("Could not resolve driver %s while handling driver table event: %v", n.networkType, err)
+ return
+ }
+
+ var (
+ etype driverapi.EventType
+ tname string
+ key string
+ value []byte
+ )
+
+ switch event := ev.(type) {
+ case networkdb.CreateEvent:
+ tname = event.Table
+ key = event.Key
+ value = event.Value
+ etype = driverapi.Create
+ case networkdb.DeleteEvent:
+ tname = event.Table
+ key = event.Key
+ value = event.Value
+ etype = driverapi.Delete
+ case networkdb.UpdateEvent:
+ tname = event.Table
+ key = event.Key
+ value = event.Value
+ etype = driverapi.Delete
+ }
+
+ d.EventNotify(etype, n.ID(), tname, key, value)
+}
+
+func (c *controller) handleNodeTableEvent(ev events.Event) {
+ var (
+ value []byte
+ isAdd bool
+ nodeAddr networkdb.NodeAddr
+ )
+ switch event := ev.(type) {
+ case networkdb.CreateEvent:
+ value = event.Value
+ isAdd = true
+ case networkdb.DeleteEvent:
+ value = event.Value
+ case networkdb.UpdateEvent:
+ logrus.Errorf("Unexpected update node table event = %#v", event)
+ }
+
+ err := json.Unmarshal(value, &nodeAddr)
+ if err != nil {
+ logrus.Errorf("Error unmarshalling node table event %v", err)
+ return
+ }
+ c.processNodeDiscovery([]net.IP{nodeAddr.Addr}, isAdd)
+
+}
+
+func (c *controller) handleEpTableEvent(ev events.Event) {
+ var (
+ nid string
+ eid string
+ value []byte
+ isAdd bool
+ epRec EndpointRecord
+ )
+
+ switch event := ev.(type) {
+ case networkdb.CreateEvent:
+ nid = event.NetworkID
+ eid = event.Key
+ value = event.Value
+ isAdd = true
+ case networkdb.DeleteEvent:
+ nid = event.NetworkID
+ eid = event.Key
+ value = event.Value
+ case networkdb.UpdateEvent:
+ logrus.Errorf("Unexpected update service table event = %#v", event)
+ return
+ }
+
+ err := proto.Unmarshal(value, &epRec)
+ if err != nil {
+ logrus.Errorf("Failed to unmarshal service table value: %v", err)
+ return
+ }
+
+ containerName := epRec.Name
+ svcName := epRec.ServiceName
+ svcID := epRec.ServiceID
+ vip := net.ParseIP(epRec.VirtualIP)
+ ip := net.ParseIP(epRec.EndpointIP)
+ ingressPorts := epRec.IngressPorts
+ serviceAliases := epRec.Aliases
+ taskAliases := epRec.TaskAliases
+
+ if containerName == "" || ip == nil {
+ logrus.Errorf("Invalid endpoint name/ip received while handling service table event %s", value)
+ return
+ }
+
+ if isAdd {
+ logrus.Debugf("handleEpTableEvent ADD %s R:%v", eid, epRec)
+ if svcID != "" {
+ // This is a remote task part of a service
+ if err := c.addServiceBinding(svcName, svcID, nid, eid, containerName, vip, ingressPorts, serviceAliases, taskAliases, ip, "handleEpTableEvent"); err != nil {
+ logrus.Errorf("failed adding service binding for %s epRec:%v err:%s", eid, epRec, err)
+ return
+ }
+ } else {
+ // This is a remote container simply attached to an attachable network
+ if err := c.addContainerNameResolution(nid, eid, containerName, taskAliases, ip, "handleEpTableEvent"); err != nil {
+ logrus.Errorf("failed adding service binding for %s epRec:%v err:%s", eid, epRec, err)
+ }
+ }
+ } else {
+ logrus.Debugf("handleEpTableEvent DEL %s R:%v", eid, epRec)
+ if svcID != "" {
+ // This is a remote task part of a service
+ if err := c.rmServiceBinding(svcName, svcID, nid, eid, containerName, vip, ingressPorts, serviceAliases, taskAliases, ip, "handleEpTableEvent", true); err != nil {
+ logrus.Errorf("failed removing service binding for %s epRec:%v err:%s", eid, epRec, err)
+ return
+ }
+ } else {
+ // This is a remote container simply attached to an attachable network
+ if err := c.delContainerNameResolution(nid, eid, containerName, taskAliases, ip, "handleEpTableEvent"); err != nil {
+ logrus.Errorf("failed adding service binding for %s epRec:%v err:%s", eid, epRec, err)
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/agent.pb.go b/vendor/github.com/docker/libnetwork/agent.pb.go
new file mode 100644
index 0000000..5b96923
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/agent.pb.go
@@ -0,0 +1,1003 @@
+// Code generated by protoc-gen-gogo.
+// source: agent.proto
+// DO NOT EDIT!
+
+/*
+ Package libnetwork is a generated protocol buffer package.
+
+ It is generated from these files:
+ agent.proto
+
+ It has these top-level messages:
+ EndpointRecord
+ PortConfig
+*/
+package libnetwork
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+
+import strings "strings"
+import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
+import sort "sort"
+import strconv "strconv"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+const _ = proto.GoGoProtoPackageIsVersion1
+
+type PortConfig_Protocol int32
+
+const (
+ ProtocolTCP PortConfig_Protocol = 0
+ ProtocolUDP PortConfig_Protocol = 1
+)
+
+var PortConfig_Protocol_name = map[int32]string{
+ 0: "TCP",
+ 1: "UDP",
+}
+var PortConfig_Protocol_value = map[string]int32{
+ "TCP": 0,
+ "UDP": 1,
+}
+
+func (x PortConfig_Protocol) String() string {
+ return proto.EnumName(PortConfig_Protocol_name, int32(x))
+}
+func (PortConfig_Protocol) EnumDescriptor() ([]byte, []int) { return fileDescriptorAgent, []int{1, 0} }
+
+// EndpointRecord specifies all the endpoint specific information that
+// needs to gossiped to nodes participating in the network.
+type EndpointRecord struct {
+ // Name of the endpoint
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ // Service name of the service to which this endpoint belongs.
+ ServiceName string `protobuf:"bytes,2,opt,name=service_name,json=serviceName,proto3" json:"service_name,omitempty"`
+ // Service ID of the service to which this endpoint belongs.
+ ServiceID string `protobuf:"bytes,3,opt,name=service_id,json=serviceId,proto3" json:"service_id,omitempty"`
+ // Virtual IP of the service to which this endpoint belongs.
+ VirtualIP string `protobuf:"bytes,4,opt,name=virtual_ip,json=virtualIp,proto3" json:"virtual_ip,omitempty"`
+ // IP assigned to this endpoint.
+ EndpointIP string `protobuf:"bytes,5,opt,name=endpoint_ip,json=endpointIp,proto3" json:"endpoint_ip,omitempty"`
+ // IngressPorts exposed by the service to which this endpoint belongs.
+ IngressPorts []*PortConfig `protobuf:"bytes,6,rep,name=ingress_ports,json=ingressPorts" json:"ingress_ports,omitempty"`
+ // A list of aliases which are alternate names for the service
+ Aliases []string `protobuf:"bytes,7,rep,name=aliases" json:"aliases,omitempty"`
+ // List of aliases task specific aliases
+ TaskAliases []string `protobuf:"bytes,8,rep,name=task_aliases,json=taskAliases" json:"task_aliases,omitempty"`
+}
+
+func (m *EndpointRecord) Reset() { *m = EndpointRecord{} }
+func (*EndpointRecord) ProtoMessage() {}
+func (*EndpointRecord) Descriptor() ([]byte, []int) { return fileDescriptorAgent, []int{0} }
+
+func (m *EndpointRecord) GetIngressPorts() []*PortConfig {
+ if m != nil {
+ return m.IngressPorts
+ }
+ return nil
+}
+
+// PortConfig specifies an exposed port which can be
+// addressed using the given name. This can be later queried
+// using a service discovery api or a DNS SRV query. The node
+// port specifies a port that can be used to address this
+// service external to the cluster by sending a connection
+// request to this port to any node on the cluster.
+type PortConfig struct {
+ // Name for the port. If provided the port information can
+ // be queried using the name as in a DNS SRV query.
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ // Protocol for the port which is exposed.
+ Protocol PortConfig_Protocol `protobuf:"varint,2,opt,name=protocol,proto3,enum=libnetwork.PortConfig_Protocol" json:"protocol,omitempty"`
+ // The port which the application is exposing and is bound to.
+ TargetPort uint32 `protobuf:"varint,3,opt,name=target_port,json=targetPort,proto3" json:"target_port,omitempty"`
+ // PublishedPort specifies the port on which the service is
+ // exposed on all nodes on the cluster. If not specified an
+ // arbitrary port in the node port range is allocated by the
+ // system. If specified it should be within the node port
+ // range and it should be available.
+ PublishedPort uint32 `protobuf:"varint,4,opt,name=published_port,json=publishedPort,proto3" json:"published_port,omitempty"`
+}
+
+func (m *PortConfig) Reset() { *m = PortConfig{} }
+func (*PortConfig) ProtoMessage() {}
+func (*PortConfig) Descriptor() ([]byte, []int) { return fileDescriptorAgent, []int{1} }
+
+func init() {
+ proto.RegisterType((*EndpointRecord)(nil), "libnetwork.EndpointRecord")
+ proto.RegisterType((*PortConfig)(nil), "libnetwork.PortConfig")
+ proto.RegisterEnum("libnetwork.PortConfig_Protocol", PortConfig_Protocol_name, PortConfig_Protocol_value)
+}
+func (this *EndpointRecord) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 12)
+ s = append(s, "&libnetwork.EndpointRecord{")
+ s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n")
+ s = append(s, "ServiceName: "+fmt.Sprintf("%#v", this.ServiceName)+",\n")
+ s = append(s, "ServiceID: "+fmt.Sprintf("%#v", this.ServiceID)+",\n")
+ s = append(s, "VirtualIP: "+fmt.Sprintf("%#v", this.VirtualIP)+",\n")
+ s = append(s, "EndpointIP: "+fmt.Sprintf("%#v", this.EndpointIP)+",\n")
+ if this.IngressPorts != nil {
+ s = append(s, "IngressPorts: "+fmt.Sprintf("%#v", this.IngressPorts)+",\n")
+ }
+ s = append(s, "Aliases: "+fmt.Sprintf("%#v", this.Aliases)+",\n")
+ s = append(s, "TaskAliases: "+fmt.Sprintf("%#v", this.TaskAliases)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *PortConfig) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 8)
+ s = append(s, "&libnetwork.PortConfig{")
+ s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n")
+ s = append(s, "Protocol: "+fmt.Sprintf("%#v", this.Protocol)+",\n")
+ s = append(s, "TargetPort: "+fmt.Sprintf("%#v", this.TargetPort)+",\n")
+ s = append(s, "PublishedPort: "+fmt.Sprintf("%#v", this.PublishedPort)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringAgent(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func extensionToGoStringAgent(e map[int32]github_com_gogo_protobuf_proto.Extension) string {
+ if e == nil {
+ return "nil"
+ }
+ s := "map[int32]proto.Extension{"
+ keys := make([]int, 0, len(e))
+ for k := range e {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+ ss := []string{}
+ for _, k := range keys {
+ ss = append(ss, strconv.Itoa(k)+": "+e[int32(k)].GoString())
+ }
+ s += strings.Join(ss, ",") + "}"
+ return s
+}
+func (m *EndpointRecord) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *EndpointRecord) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Name) > 0 {
+ data[i] = 0xa
+ i++
+ i = encodeVarintAgent(data, i, uint64(len(m.Name)))
+ i += copy(data[i:], m.Name)
+ }
+ if len(m.ServiceName) > 0 {
+ data[i] = 0x12
+ i++
+ i = encodeVarintAgent(data, i, uint64(len(m.ServiceName)))
+ i += copy(data[i:], m.ServiceName)
+ }
+ if len(m.ServiceID) > 0 {
+ data[i] = 0x1a
+ i++
+ i = encodeVarintAgent(data, i, uint64(len(m.ServiceID)))
+ i += copy(data[i:], m.ServiceID)
+ }
+ if len(m.VirtualIP) > 0 {
+ data[i] = 0x22
+ i++
+ i = encodeVarintAgent(data, i, uint64(len(m.VirtualIP)))
+ i += copy(data[i:], m.VirtualIP)
+ }
+ if len(m.EndpointIP) > 0 {
+ data[i] = 0x2a
+ i++
+ i = encodeVarintAgent(data, i, uint64(len(m.EndpointIP)))
+ i += copy(data[i:], m.EndpointIP)
+ }
+ if len(m.IngressPorts) > 0 {
+ for _, msg := range m.IngressPorts {
+ data[i] = 0x32
+ i++
+ i = encodeVarintAgent(data, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(data[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Aliases) > 0 {
+ for _, s := range m.Aliases {
+ data[i] = 0x3a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ data[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ data[i] = uint8(l)
+ i++
+ i += copy(data[i:], s)
+ }
+ }
+ if len(m.TaskAliases) > 0 {
+ for _, s := range m.TaskAliases {
+ data[i] = 0x42
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ data[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ data[i] = uint8(l)
+ i++
+ i += copy(data[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func (m *PortConfig) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *PortConfig) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Name) > 0 {
+ data[i] = 0xa
+ i++
+ i = encodeVarintAgent(data, i, uint64(len(m.Name)))
+ i += copy(data[i:], m.Name)
+ }
+ if m.Protocol != 0 {
+ data[i] = 0x10
+ i++
+ i = encodeVarintAgent(data, i, uint64(m.Protocol))
+ }
+ if m.TargetPort != 0 {
+ data[i] = 0x18
+ i++
+ i = encodeVarintAgent(data, i, uint64(m.TargetPort))
+ }
+ if m.PublishedPort != 0 {
+ data[i] = 0x20
+ i++
+ i = encodeVarintAgent(data, i, uint64(m.PublishedPort))
+ }
+ return i, nil
+}
+
+func encodeFixed64Agent(data []byte, offset int, v uint64) int {
+ data[offset] = uint8(v)
+ data[offset+1] = uint8(v >> 8)
+ data[offset+2] = uint8(v >> 16)
+ data[offset+3] = uint8(v >> 24)
+ data[offset+4] = uint8(v >> 32)
+ data[offset+5] = uint8(v >> 40)
+ data[offset+6] = uint8(v >> 48)
+ data[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Agent(data []byte, offset int, v uint32) int {
+ data[offset] = uint8(v)
+ data[offset+1] = uint8(v >> 8)
+ data[offset+2] = uint8(v >> 16)
+ data[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintAgent(data []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ data[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ data[offset] = uint8(v)
+ return offset + 1
+}
+func (m *EndpointRecord) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Name)
+ if l > 0 {
+ n += 1 + l + sovAgent(uint64(l))
+ }
+ l = len(m.ServiceName)
+ if l > 0 {
+ n += 1 + l + sovAgent(uint64(l))
+ }
+ l = len(m.ServiceID)
+ if l > 0 {
+ n += 1 + l + sovAgent(uint64(l))
+ }
+ l = len(m.VirtualIP)
+ if l > 0 {
+ n += 1 + l + sovAgent(uint64(l))
+ }
+ l = len(m.EndpointIP)
+ if l > 0 {
+ n += 1 + l + sovAgent(uint64(l))
+ }
+ if len(m.IngressPorts) > 0 {
+ for _, e := range m.IngressPorts {
+ l = e.Size()
+ n += 1 + l + sovAgent(uint64(l))
+ }
+ }
+ if len(m.Aliases) > 0 {
+ for _, s := range m.Aliases {
+ l = len(s)
+ n += 1 + l + sovAgent(uint64(l))
+ }
+ }
+ if len(m.TaskAliases) > 0 {
+ for _, s := range m.TaskAliases {
+ l = len(s)
+ n += 1 + l + sovAgent(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *PortConfig) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Name)
+ if l > 0 {
+ n += 1 + l + sovAgent(uint64(l))
+ }
+ if m.Protocol != 0 {
+ n += 1 + sovAgent(uint64(m.Protocol))
+ }
+ if m.TargetPort != 0 {
+ n += 1 + sovAgent(uint64(m.TargetPort))
+ }
+ if m.PublishedPort != 0 {
+ n += 1 + sovAgent(uint64(m.PublishedPort))
+ }
+ return n
+}
+
+func sovAgent(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozAgent(x uint64) (n int) {
+ return sovAgent(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *EndpointRecord) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&EndpointRecord{`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `ServiceName:` + fmt.Sprintf("%v", this.ServiceName) + `,`,
+ `ServiceID:` + fmt.Sprintf("%v", this.ServiceID) + `,`,
+ `VirtualIP:` + fmt.Sprintf("%v", this.VirtualIP) + `,`,
+ `EndpointIP:` + fmt.Sprintf("%v", this.EndpointIP) + `,`,
+ `IngressPorts:` + strings.Replace(fmt.Sprintf("%v", this.IngressPorts), "PortConfig", "PortConfig", 1) + `,`,
+ `Aliases:` + fmt.Sprintf("%v", this.Aliases) + `,`,
+ `TaskAliases:` + fmt.Sprintf("%v", this.TaskAliases) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *PortConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PortConfig{`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `Protocol:` + fmt.Sprintf("%v", this.Protocol) + `,`,
+ `TargetPort:` + fmt.Sprintf("%v", this.TargetPort) + `,`,
+ `PublishedPort:` + fmt.Sprintf("%v", this.PublishedPort) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringAgent(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *EndpointRecord) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: EndpointRecord: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: EndpointRecord: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthAgent
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Name = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceName", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthAgent
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ServiceName = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthAgent
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ServiceID = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field VirtualIP", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthAgent
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.VirtualIP = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field EndpointIP", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthAgent
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.EndpointIP = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IngressPorts", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthAgent
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IngressPorts = append(m.IngressPorts, &PortConfig{})
+ if err := m.IngressPorts[len(m.IngressPorts)-1].Unmarshal(data[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Aliases", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthAgent
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Aliases = append(m.Aliases, string(data[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TaskAliases", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthAgent
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TaskAliases = append(m.TaskAliases, string(data[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipAgent(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthAgent
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *PortConfig) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PortConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PortConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthAgent
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Name = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Protocol", wireType)
+ }
+ m.Protocol = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.Protocol |= (PortConfig_Protocol(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TargetPort", wireType)
+ }
+ m.TargetPort = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.TargetPort |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PublishedPort", wireType)
+ }
+ m.PublishedPort = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.PublishedPort |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipAgent(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthAgent
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipAgent(data []byte) (n int, err error) {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if data[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthAgent
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowAgent
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipAgent(data[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthAgent = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowAgent = fmt.Errorf("proto: integer overflow")
+)
+
+var fileDescriptorAgent = []byte{
+ // 413 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x6c, 0x90, 0xbf, 0xae, 0xd3, 0x30,
+ 0x14, 0x87, 0x9b, 0xdb, 0x70, 0x6f, 0x73, 0x72, 0x13, 0xae, 0x2c, 0x84, 0xa2, 0x0e, 0x69, 0xa9,
+ 0x84, 0x74, 0x07, 0x94, 0x2b, 0x95, 0xb1, 0x13, 0x6d, 0x19, 0xb2, 0xa0, 0xc8, 0xfc, 0x59, 0xa3,
+ 0xb4, 0x31, 0xc1, 0x6a, 0x88, 0x23, 0xdb, 0x2d, 0x2b, 0x23, 0xe2, 0x1d, 0x98, 0x78, 0x19, 0x26,
+ 0xc4, 0xc8, 0x84, 0x68, 0x57, 0x16, 0x1e, 0x01, 0xdb, 0x49, 0x5a, 0x21, 0x75, 0x38, 0x92, 0xf3,
+ 0xfd, 0xbe, 0xe3, 0x1c, 0x1f, 0x70, 0xb3, 0x82, 0x54, 0x32, 0xaa, 0x39, 0x93, 0x0c, 0x41, 0x49,
+ 0x57, 0x15, 0x91, 0x1f, 0x18, 0xdf, 0x0c, 0x1f, 0x14, 0xac, 0x60, 0x06, 0xdf, 0xe9, 0x53, 0x63,
+ 0x4c, 0xbe, 0x5f, 0x80, 0xff, 0xbc, 0xca, 0x6b, 0x46, 0x2b, 0x89, 0xc9, 0x9a, 0xf1, 0x1c, 0x21,
+ 0xb0, 0xab, 0xec, 0x3d, 0x09, 0xac, 0xb1, 0x75, 0xeb, 0x60, 0x73, 0x46, 0x8f, 0xe0, 0x5a, 0x10,
+ 0xbe, 0xa3, 0x6b, 0x92, 0x9a, 0xec, 0xc2, 0x64, 0x6e, 0xcb, 0x5e, 0x68, 0xe5, 0x09, 0x40, 0xa7,
+ 0xd0, 0x3c, 0xe8, 0x6b, 0x61, 0xee, 0x1d, 0x7e, 0x8d, 0x9c, 0x97, 0x0d, 0x8d, 0x97, 0xd8, 0x69,
+ 0x85, 0x38, 0xd7, 0xf6, 0x8e, 0x72, 0xb9, 0xcd, 0xca, 0x94, 0xd6, 0x81, 0x7d, 0xb2, 0xdf, 0x34,
+ 0x34, 0x4e, 0xb0, 0xd3, 0x0a, 0x71, 0x8d, 0xee, 0xc0, 0x25, 0xed, 0x90, 0x5a, 0xbf, 0x67, 0x74,
+ 0x5f, 0xe9, 0xd0, 0xcd, 0xae, 0x7c, 0xe8, 0x14, 0xd5, 0x30, 0x03, 0x8f, 0x56, 0x05, 0x27, 0x42,
+ 0xa4, 0x35, 0xe3, 0x52, 0x04, 0x97, 0xe3, 0xfe, 0xad, 0x3b, 0x7d, 0x18, 0x9d, 0x16, 0x12, 0x25,
+ 0x2a, 0x58, 0xb0, 0xea, 0x2d, 0x2d, 0xf0, 0x75, 0x2b, 0x6b, 0x24, 0x50, 0x00, 0x57, 0x59, 0x49,
+ 0x33, 0x41, 0x44, 0x70, 0xa5, 0xda, 0x1c, 0xdc, 0x7d, 0xea, 0x35, 0xc8, 0x4c, 0x6c, 0xd2, 0x2e,
+ 0x1e, 0x98, 0xd8, 0xd5, 0xec, 0x59, 0x83, 0x26, 0x7f, 0x2c, 0x80, 0xd3, 0xcd, 0x67, 0x97, 0x39,
+ 0x83, 0x81, 0x59, 0xfe, 0x9a, 0x95, 0x66, 0x91, 0xfe, 0x74, 0x74, 0x7e, 0xae, 0x28, 0x69, 0x35,
+ 0x7c, 0x6c, 0x40, 0x23, 0x50, 0xbf, 0xe3, 0x05, 0x91, 0xe6, 0x61, 0x66, 0xcf, 0x1e, 0x86, 0x06,
+ 0xe9, 0x4e, 0xf4, 0x18, 0xfc, 0x7a, 0xbb, 0x2a, 0xa9, 0x78, 0x47, 0xf2, 0xc6, 0xb1, 0x8d, 0xe3,
+ 0x1d, 0xa9, 0xd6, 0x26, 0x4b, 0x18, 0x74, 0xb7, 0xab, 0x07, 0xf7, 0x5f, 0x2d, 0x92, 0x9b, 0xde,
+ 0xf0, 0xfe, 0xe7, 0x2f, 0x63, 0xb7, 0xc3, 0x0a, 0xe9, 0xe4, 0xf5, 0x32, 0xb9, 0xb1, 0xfe, 0x4f,
+ 0x14, 0x1a, 0xda, 0x9f, 0xbe, 0x86, 0xbd, 0x79, 0xf0, 0x73, 0x1f, 0xf6, 0xfe, 0xee, 0x43, 0xeb,
+ 0xe3, 0x21, 0xb4, 0xbe, 0xa9, 0xfa, 0xa1, 0xea, 0xb7, 0xaa, 0xd5, 0xa5, 0x99, 0xf8, 0xe9, 0xbf,
+ 0x00, 0x00, 0x00, 0xff, 0xff, 0xc9, 0x63, 0x1a, 0x0f, 0x90, 0x02, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/libnetwork/agent.proto b/vendor/github.com/docker/libnetwork/agent.proto
new file mode 100644
index 0000000..54c71c0
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/agent.proto
@@ -0,0 +1,72 @@
+syntax = "proto3";
+
+import "gogoproto/gogo.proto";
+
+package libnetwork;
+
+option (gogoproto.marshaler_all) = true;
+option (gogoproto.unmarshaler_all) = true;
+option (gogoproto.stringer_all) = true;
+option (gogoproto.gostring_all) = true;
+option (gogoproto.sizer_all) = true;
+option (gogoproto.goproto_stringer_all) = false;
+
+// EndpointRecord specifies all the endpoint specific information that
+// needs to gossiped to nodes participating in the network.
+message EndpointRecord {
+ // Name of the container
+ string name = 1;
+
+ // Service name of the service to which this endpoint belongs.
+ string service_name = 2;
+
+ // Service ID of the service to which this endpoint belongs.
+ string service_id = 3 [(gogoproto.customname) = "ServiceID"];
+
+ // Virtual IP of the service to which this endpoint belongs.
+ string virtual_ip = 4 [(gogoproto.customname) = "VirtualIP"];
+
+ // IP assigned to this endpoint.
+ string endpoint_ip = 5 [(gogoproto.customname) = "EndpointIP"];
+
+ // IngressPorts exposed by the service to which this endpoint belongs.
+ repeated PortConfig ingress_ports = 6;
+
+ // A list of aliases which are alternate names for the service
+ repeated string aliases = 7;
+
+ // List of aliases task specific aliases
+ repeated string task_aliases = 8;
+}
+
+// PortConfig specifies an exposed port which can be
+// addressed using the given name. This can be later queried
+// using a service discovery api or a DNS SRV query. The node
+// port specifies a port that can be used to address this
+// service external to the cluster by sending a connection
+// request to this port to any node on the cluster.
+message PortConfig {
+ enum Protocol {
+ option (gogoproto.goproto_enum_prefix) = false;
+
+ TCP = 0 [(gogoproto.enumvalue_customname) = "ProtocolTCP"];
+ UDP = 1 [(gogoproto.enumvalue_customname) = "ProtocolUDP"];
+ }
+
+ // Name for the port. If provided the port information can
+ // be queried using the name as in a DNS SRV query.
+ string name = 1;
+
+ // Protocol for the port which is exposed.
+ Protocol protocol = 2;
+
+ // The port which the application is exposing and is bound to.
+ uint32 target_port = 3;
+
+ // PublishedPort specifies the port on which the service is
+ // exposed on all nodes on the cluster. If not specified an
+ // arbitrary port in the node port range is allocated by the
+ // system. If specified it should be within the node port
+ // range and it should be available.
+ uint32 published_port = 4;
+}
diff --git a/vendor/github.com/docker/libnetwork/bitseq/sequence.go b/vendor/github.com/docker/libnetwork/bitseq/sequence.go
new file mode 100644
index 0000000..86cf69b
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/bitseq/sequence.go
@@ -0,0 +1,679 @@
+// Package bitseq provides a structure and utilities for representing long bitmask
+// as sequence of run-length encoded blocks. It operates directly on the encoded
+// representation, it does not decode/encode.
+package bitseq
+
+import (
+ "encoding/binary"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/types"
+)
+
+// block sequence constants
+// If needed we can think of making these configurable
+const (
+ blockLen = uint32(32)
+ blockBytes = uint64(blockLen / 8)
+ blockMAX = uint32(1<<blockLen - 1)
+ blockFirstBit = uint32(1) << (blockLen - 1)
+ invalidPos = uint64(0xFFFFFFFFFFFFFFFF)
+)
+
+var (
+ // ErrNoBitAvailable is returned when no more bits are available to set
+ ErrNoBitAvailable = errors.New("no bit available")
+ // ErrBitAllocated is returned when the specific bit requested is already set
+ ErrBitAllocated = errors.New("requested bit is already allocated")
+)
+
+// Handle contains the sequece representing the bitmask and its identifier
+type Handle struct {
+ bits uint64
+ unselected uint64
+ head *sequence
+ app string
+ id string
+ dbIndex uint64
+ dbExists bool
+ store datastore.DataStore
+ sync.Mutex
+}
+
+// NewHandle returns a thread-safe instance of the bitmask handler
+func NewHandle(app string, ds datastore.DataStore, id string, numElements uint64) (*Handle, error) {
+ h := &Handle{
+ app: app,
+ id: id,
+ store: ds,
+ bits: numElements,
+ unselected: numElements,
+ head: &sequence{
+ block: 0x0,
+ count: getNumBlocks(numElements),
+ },
+ }
+
+ if h.store == nil {
+ return h, nil
+ }
+
+ // Get the initial status from the ds if present.
+ if err := h.store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound {
+ return nil, err
+ }
+
+ // If the handle is not in store, write it.
+ if !h.Exists() {
+ if err := h.writeToStore(); err != nil {
+ return nil, fmt.Errorf("failed to write bitsequence to store: %v", err)
+ }
+ }
+
+ return h, nil
+}
+
+// sequence represents a recurring sequence of 32 bits long bitmasks
+type sequence struct {
+ block uint32 // block is a symbol representing 4 byte long allocation bitmask
+ count uint64 // number of consecutive blocks (symbols)
+ next *sequence // next sequence
+}
+
+// String returns a string representation of the block sequence starting from this block
+func (s *sequence) toString() string {
+ var nextBlock string
+ if s.next == nil {
+ nextBlock = "end"
+ } else {
+ nextBlock = s.next.toString()
+ }
+ return fmt.Sprintf("(0x%x, %d)->%s", s.block, s.count, nextBlock)
+}
+
+// GetAvailableBit returns the position of the first unset bit in the bitmask represented by this sequence
+func (s *sequence) getAvailableBit(from uint64) (uint64, uint64, error) {
+ if s.block == blockMAX || s.count == 0 {
+ return invalidPos, invalidPos, ErrNoBitAvailable
+ }
+ bits := from
+ bitSel := blockFirstBit >> from
+ for bitSel > 0 && s.block&bitSel != 0 {
+ bitSel >>= 1
+ bits++
+ }
+ return bits / 8, bits % 8, nil
+}
+
+// GetCopy returns a copy of the linked list rooted at this node
+func (s *sequence) getCopy() *sequence {
+ n := &sequence{block: s.block, count: s.count}
+ pn := n
+ ps := s.next
+ for ps != nil {
+ pn.next = &sequence{block: ps.block, count: ps.count}
+ pn = pn.next
+ ps = ps.next
+ }
+ return n
+}
+
+// Equal checks if this sequence is equal to the passed one
+func (s *sequence) equal(o *sequence) bool {
+ this := s
+ other := o
+ for this != nil {
+ if other == nil {
+ return false
+ }
+ if this.block != other.block || this.count != other.count {
+ return false
+ }
+ this = this.next
+ other = other.next
+ }
+ // Check if other is longer than this
+ if other != nil {
+ return false
+ }
+ return true
+}
+
+// ToByteArray converts the sequence into a byte array
+func (s *sequence) toByteArray() ([]byte, error) {
+ var bb []byte
+
+ p := s
+ for p != nil {
+ b := make([]byte, 12)
+ binary.BigEndian.PutUint32(b[0:], p.block)
+ binary.BigEndian.PutUint64(b[4:], p.count)
+ bb = append(bb, b...)
+ p = p.next
+ }
+
+ return bb, nil
+}
+
+// fromByteArray construct the sequence from the byte array
+func (s *sequence) fromByteArray(data []byte) error {
+ l := len(data)
+ if l%12 != 0 {
+ return fmt.Errorf("cannot deserialize byte sequence of length %d (%v)", l, data)
+ }
+
+ p := s
+ i := 0
+ for {
+ p.block = binary.BigEndian.Uint32(data[i : i+4])
+ p.count = binary.BigEndian.Uint64(data[i+4 : i+12])
+ i += 12
+ if i == l {
+ break
+ }
+ p.next = &sequence{}
+ p = p.next
+ }
+
+ return nil
+}
+
+func (h *Handle) getCopy() *Handle {
+ return &Handle{
+ bits: h.bits,
+ unselected: h.unselected,
+ head: h.head.getCopy(),
+ app: h.app,
+ id: h.id,
+ dbIndex: h.dbIndex,
+ dbExists: h.dbExists,
+ store: h.store,
+ }
+}
+
+// SetAnyInRange atomically sets the first unset bit in the specified range in the sequence and returns the corresponding ordinal
+func (h *Handle) SetAnyInRange(start, end uint64) (uint64, error) {
+ if end < start || end >= h.bits {
+ return invalidPos, fmt.Errorf("invalid bit range [%d, %d]", start, end)
+ }
+ if h.Unselected() == 0 {
+ return invalidPos, ErrNoBitAvailable
+ }
+ return h.set(0, start, end, true, false)
+}
+
+// SetAny atomically sets the first unset bit in the sequence and returns the corresponding ordinal
+func (h *Handle) SetAny() (uint64, error) {
+ if h.Unselected() == 0 {
+ return invalidPos, ErrNoBitAvailable
+ }
+ return h.set(0, 0, h.bits-1, true, false)
+}
+
+// Set atomically sets the corresponding bit in the sequence
+func (h *Handle) Set(ordinal uint64) error {
+ if err := h.validateOrdinal(ordinal); err != nil {
+ return err
+ }
+ _, err := h.set(ordinal, 0, 0, false, false)
+ return err
+}
+
+// Unset atomically unsets the corresponding bit in the sequence
+func (h *Handle) Unset(ordinal uint64) error {
+ if err := h.validateOrdinal(ordinal); err != nil {
+ return err
+ }
+ _, err := h.set(ordinal, 0, 0, false, true)
+ return err
+}
+
+// IsSet atomically checks if the ordinal bit is set. In case ordinal
+// is outside of the bit sequence limits, false is returned.
+func (h *Handle) IsSet(ordinal uint64) bool {
+ if err := h.validateOrdinal(ordinal); err != nil {
+ return false
+ }
+ h.Lock()
+ _, _, err := checkIfAvailable(h.head, ordinal)
+ h.Unlock()
+ return err != nil
+}
+
+func (h *Handle) runConsistencyCheck() bool {
+ corrupted := false
+ for p, c := h.head, h.head.next; c != nil; c = c.next {
+ if c.count == 0 {
+ corrupted = true
+ p.next = c.next
+ continue // keep same p
+ }
+ p = c
+ }
+ return corrupted
+}
+
+// CheckConsistency checks if the bit sequence is in an inconsistent state and attempts to fix it.
+// It looks for a corruption signature that may happen in docker 1.9.0 and 1.9.1.
+func (h *Handle) CheckConsistency() error {
+ for {
+ h.Lock()
+ store := h.store
+ h.Unlock()
+
+ if store != nil {
+ if err := store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound {
+ return err
+ }
+ }
+
+ h.Lock()
+ nh := h.getCopy()
+ h.Unlock()
+
+ if !nh.runConsistencyCheck() {
+ return nil
+ }
+
+ if err := nh.writeToStore(); err != nil {
+ if _, ok := err.(types.RetryError); !ok {
+ return fmt.Errorf("internal failure while fixing inconsistent bitsequence: %v", err)
+ }
+ continue
+ }
+
+ logrus.Infof("Fixed inconsistent bit sequence in datastore:\n%s\n%s", h, nh)
+
+ h.Lock()
+ h.head = nh.head
+ h.Unlock()
+
+ return nil
+ }
+}
+
+// set/reset the bit
+func (h *Handle) set(ordinal, start, end uint64, any bool, release bool) (uint64, error) {
+ var (
+ bitPos uint64
+ bytePos uint64
+ ret uint64
+ err error
+ )
+
+ for {
+ var store datastore.DataStore
+ h.Lock()
+ store = h.store
+ h.Unlock()
+ if store != nil {
+ if err := store.GetObject(datastore.Key(h.Key()...), h); err != nil && err != datastore.ErrKeyNotFound {
+ return ret, err
+ }
+ }
+
+ h.Lock()
+ // Get position if available
+ if release {
+ bytePos, bitPos = ordinalToPos(ordinal)
+ } else {
+ if any {
+ bytePos, bitPos, err = getFirstAvailable(h.head, start)
+ ret = posToOrdinal(bytePos, bitPos)
+ if end < ret {
+ err = ErrNoBitAvailable
+ }
+ } else {
+ bytePos, bitPos, err = checkIfAvailable(h.head, ordinal)
+ ret = ordinal
+ }
+ }
+ if err != nil {
+ h.Unlock()
+ return ret, err
+ }
+
+ // Create a private copy of h and work on it
+ nh := h.getCopy()
+ h.Unlock()
+
+ nh.head = pushReservation(bytePos, bitPos, nh.head, release)
+ if release {
+ nh.unselected++
+ } else {
+ nh.unselected--
+ }
+
+ // Attempt to write private copy to store
+ if err := nh.writeToStore(); err != nil {
+ if _, ok := err.(types.RetryError); !ok {
+ return ret, fmt.Errorf("internal failure while setting the bit: %v", err)
+ }
+ // Retry
+ continue
+ }
+
+ // Previous atomic push was succesfull. Save private copy to local copy
+ h.Lock()
+ defer h.Unlock()
+ h.unselected = nh.unselected
+ h.head = nh.head
+ h.dbExists = nh.dbExists
+ h.dbIndex = nh.dbIndex
+ return ret, nil
+ }
+}
+
+// checks is needed because to cover the case where the number of bits is not a multiple of blockLen
+func (h *Handle) validateOrdinal(ordinal uint64) error {
+ h.Lock()
+ defer h.Unlock()
+ if ordinal >= h.bits {
+ return errors.New("bit does not belong to the sequence")
+ }
+ return nil
+}
+
+// Destroy removes from the datastore the data belonging to this handle
+func (h *Handle) Destroy() error {
+ for {
+ if err := h.deleteFromStore(); err != nil {
+ if _, ok := err.(types.RetryError); !ok {
+ return fmt.Errorf("internal failure while destroying the sequence: %v", err)
+ }
+ // Fetch latest
+ if err := h.store.GetObject(datastore.Key(h.Key()...), h); err != nil {
+ if err == datastore.ErrKeyNotFound { // already removed
+ return nil
+ }
+ return fmt.Errorf("failed to fetch from store when destroying the sequence: %v", err)
+ }
+ continue
+ }
+ return nil
+ }
+}
+
+// ToByteArray converts this handle's data into a byte array
+func (h *Handle) ToByteArray() ([]byte, error) {
+
+ h.Lock()
+ defer h.Unlock()
+ ba := make([]byte, 16)
+ binary.BigEndian.PutUint64(ba[0:], h.bits)
+ binary.BigEndian.PutUint64(ba[8:], h.unselected)
+ bm, err := h.head.toByteArray()
+ if err != nil {
+ return nil, fmt.Errorf("failed to serialize head: %s", err.Error())
+ }
+ ba = append(ba, bm...)
+
+ return ba, nil
+}
+
+// FromByteArray reads his handle's data from a byte array
+func (h *Handle) FromByteArray(ba []byte) error {
+ if ba == nil {
+ return errors.New("nil byte array")
+ }
+
+ nh := &sequence{}
+ err := nh.fromByteArray(ba[16:])
+ if err != nil {
+ return fmt.Errorf("failed to deserialize head: %s", err.Error())
+ }
+
+ h.Lock()
+ h.head = nh
+ h.bits = binary.BigEndian.Uint64(ba[0:8])
+ h.unselected = binary.BigEndian.Uint64(ba[8:16])
+ h.Unlock()
+
+ return nil
+}
+
+// Bits returns the length of the bit sequence
+func (h *Handle) Bits() uint64 {
+ return h.bits
+}
+
+// Unselected returns the number of bits which are not selected
+func (h *Handle) Unselected() uint64 {
+ h.Lock()
+ defer h.Unlock()
+ return h.unselected
+}
+
+func (h *Handle) String() string {
+ h.Lock()
+ defer h.Unlock()
+ return fmt.Sprintf("App: %s, ID: %s, DBIndex: 0x%x, bits: %d, unselected: %d, sequence: %s",
+ h.app, h.id, h.dbIndex, h.bits, h.unselected, h.head.toString())
+}
+
+// MarshalJSON encodes Handle into json message
+func (h *Handle) MarshalJSON() ([]byte, error) {
+ m := map[string]interface{}{
+ "id": h.id,
+ }
+
+ b, err := h.ToByteArray()
+ if err != nil {
+ return nil, err
+ }
+ m["sequence"] = b
+ return json.Marshal(m)
+}
+
+// UnmarshalJSON decodes json message into Handle
+func (h *Handle) UnmarshalJSON(data []byte) error {
+ var (
+ m map[string]interface{}
+ b []byte
+ err error
+ )
+ if err = json.Unmarshal(data, &m); err != nil {
+ return err
+ }
+ h.id = m["id"].(string)
+ bi, _ := json.Marshal(m["sequence"])
+ if err := json.Unmarshal(bi, &b); err != nil {
+ return err
+ }
+ return h.FromByteArray(b)
+}
+
+// getFirstAvailable looks for the first unset bit in passed mask starting from start
+func getFirstAvailable(head *sequence, start uint64) (uint64, uint64, error) {
+ // Find sequence which contains the start bit
+ byteStart, bitStart := ordinalToPos(start)
+ current, _, _, inBlockBytePos := findSequence(head, byteStart)
+
+ // Derive the this sequence offsets
+ byteOffset := byteStart - inBlockBytePos
+ bitOffset := inBlockBytePos*8 + bitStart
+
+ for current != nil {
+ if current.block != blockMAX {
+ bytePos, bitPos, err := current.getAvailableBit(bitOffset)
+ return byteOffset + bytePos, bitPos, err
+ }
+ // Moving to next block: Reset bit offset.
+ bitOffset = 0
+ byteOffset += current.count * blockBytes
+ current = current.next
+ }
+ return invalidPos, invalidPos, ErrNoBitAvailable
+}
+
+// checkIfAvailable checks if the bit correspondent to the specified ordinal is unset
+// If the ordinal is beyond the sequence limits, a negative response is returned
+func checkIfAvailable(head *sequence, ordinal uint64) (uint64, uint64, error) {
+ bytePos, bitPos := ordinalToPos(ordinal)
+
+ // Find the sequence containing this byte
+ current, _, _, inBlockBytePos := findSequence(head, bytePos)
+ if current != nil {
+ // Check whether the bit corresponding to the ordinal address is unset
+ bitSel := blockFirstBit >> (inBlockBytePos*8 + bitPos)
+ if current.block&bitSel == 0 {
+ return bytePos, bitPos, nil
+ }
+ }
+
+ return invalidPos, invalidPos, ErrBitAllocated
+}
+
+// Given the byte position and the sequences list head, return the pointer to the
+// sequence containing the byte (current), the pointer to the previous sequence,
+// the number of blocks preceding the block containing the byte inside the current sequence.
+// If bytePos is outside of the list, function will return (nil, nil, 0, invalidPos)
+func findSequence(head *sequence, bytePos uint64) (*sequence, *sequence, uint64, uint64) {
+ // Find the sequence containing this byte
+ previous := head
+ current := head
+ n := bytePos
+ for current.next != nil && n >= (current.count*blockBytes) { // Nil check for less than 32 addresses masks
+ n -= (current.count * blockBytes)
+ previous = current
+ current = current.next
+ }
+
+ // If byte is outside of the list, let caller know
+ if n >= (current.count * blockBytes) {
+ return nil, nil, 0, invalidPos
+ }
+
+ // Find the byte position inside the block and the number of blocks
+ // preceding the block containing the byte inside this sequence
+ precBlocks := n / blockBytes
+ inBlockBytePos := bytePos % blockBytes
+
+ return current, previous, precBlocks, inBlockBytePos
+}
+
+// PushReservation pushes the bit reservation inside the bitmask.
+// Given byte and bit positions, identify the sequence (current) which holds the block containing the affected bit.
+// Create a new block with the modified bit according to the operation (allocate/release).
+// Create a new sequence containing the new block and insert it in the proper position.
+// Remove current sequence if empty.
+// Check if new sequence can be merged with neighbour (previous/next) sequences.
+//
+//
+// Identify "current" sequence containing block:
+// [prev seq] [current seq] [next seq]
+//
+// Based on block position, resulting list of sequences can be any of three forms:
+//
+// block position Resulting list of sequences
+// A) block is first in current: [prev seq] [new] [modified current seq] [next seq]
+// B) block is last in current: [prev seq] [modified current seq] [new] [next seq]
+// C) block is in the middle of current: [prev seq] [curr pre] [new] [curr post] [next seq]
+func pushReservation(bytePos, bitPos uint64, head *sequence, release bool) *sequence {
+ // Store list's head
+ newHead := head
+
+ // Find the sequence containing this byte
+ current, previous, precBlocks, inBlockBytePos := findSequence(head, bytePos)
+ if current == nil {
+ return newHead
+ }
+
+ // Construct updated block
+ bitSel := blockFirstBit >> (inBlockBytePos*8 + bitPos)
+ newBlock := current.block
+ if release {
+ newBlock &^= bitSel
+ } else {
+ newBlock |= bitSel
+ }
+
+ // Quit if it was a redundant request
+ if current.block == newBlock {
+ return newHead
+ }
+
+ // Current sequence inevitably looses one block, upadate count
+ current.count--
+
+ // Create new sequence
+ newSequence := &sequence{block: newBlock, count: 1}
+
+ // Insert the new sequence in the list based on block position
+ if precBlocks == 0 { // First in sequence (A)
+ newSequence.next = current
+ if current == head {
+ newHead = newSequence
+ previous = newHead
+ } else {
+ previous.next = newSequence
+ }
+ removeCurrentIfEmpty(&newHead, newSequence, current)
+ mergeSequences(previous)
+ } else if precBlocks == current.count { // Last in sequence (B)
+ newSequence.next = current.next
+ current.next = newSequence
+ mergeSequences(current)
+ } else { // In between the sequence (C)
+ currPre := &sequence{block: current.block, count: precBlocks, next: newSequence}
+ currPost := current
+ currPost.count -= precBlocks
+ newSequence.next = currPost
+ if currPost == head {
+ newHead = currPre
+ } else {
+ previous.next = currPre
+ }
+ // No merging or empty current possible here
+ }
+
+ return newHead
+}
+
+// Removes the current sequence from the list if empty, adjusting the head pointer if needed
+func removeCurrentIfEmpty(head **sequence, previous, current *sequence) {
+ if current.count == 0 {
+ if current == *head {
+ *head = current.next
+ } else {
+ previous.next = current.next
+ current = current.next
+ }
+ }
+}
+
+// Given a pointer to a sequence, it checks if it can be merged with any following sequences
+// It stops when no more merging is possible.
+// TODO: Optimization: only attempt merge from start to end sequence, no need to scan till the end of the list
+func mergeSequences(seq *sequence) {
+ if seq != nil {
+ // Merge all what possible from seq
+ for seq.next != nil && seq.block == seq.next.block {
+ seq.count += seq.next.count
+ seq.next = seq.next.next
+ }
+ // Move to next
+ mergeSequences(seq.next)
+ }
+}
+
+func getNumBlocks(numBits uint64) uint64 {
+ numBlocks := numBits / uint64(blockLen)
+ if numBits%uint64(blockLen) != 0 {
+ numBlocks++
+ }
+ return numBlocks
+}
+
+func ordinalToPos(ordinal uint64) (uint64, uint64) {
+ return ordinal / 8, ordinal % 8
+}
+
+func posToOrdinal(bytePos, bitPos uint64) uint64 {
+ return bytePos*8 + bitPos
+}
diff --git a/vendor/github.com/docker/libnetwork/bitseq/store.go b/vendor/github.com/docker/libnetwork/bitseq/store.go
new file mode 100644
index 0000000..5448927
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/bitseq/store.go
@@ -0,0 +1,141 @@
+package bitseq
+
+import (
+ "encoding/json"
+ "fmt"
+
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/types"
+)
+
+// Key provides the Key to be used in KV Store
+func (h *Handle) Key() []string {
+ h.Lock()
+ defer h.Unlock()
+ return []string{h.app, h.id}
+}
+
+// KeyPrefix returns the immediate parent key that can be used for tree walk
+func (h *Handle) KeyPrefix() []string {
+ h.Lock()
+ defer h.Unlock()
+ return []string{h.app}
+}
+
+// Value marshals the data to be stored in the KV store
+func (h *Handle) Value() []byte {
+ b, err := json.Marshal(h)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+// SetValue unmarshals the data from the KV store
+func (h *Handle) SetValue(value []byte) error {
+ return json.Unmarshal(value, h)
+}
+
+// Index returns the latest DB Index as seen by this object
+func (h *Handle) Index() uint64 {
+ h.Lock()
+ defer h.Unlock()
+ return h.dbIndex
+}
+
+// SetIndex method allows the datastore to store the latest DB Index into this object
+func (h *Handle) SetIndex(index uint64) {
+ h.Lock()
+ h.dbIndex = index
+ h.dbExists = true
+ h.Unlock()
+}
+
+// Exists method is true if this object has been stored in the DB.
+func (h *Handle) Exists() bool {
+ h.Lock()
+ defer h.Unlock()
+ return h.dbExists
+}
+
+// New method returns a handle based on the receiver handle
+func (h *Handle) New() datastore.KVObject {
+ h.Lock()
+ defer h.Unlock()
+
+ return &Handle{
+ app: h.app,
+ store: h.store,
+ }
+}
+
+// CopyTo deep copies the handle into the passed destination object
+func (h *Handle) CopyTo(o datastore.KVObject) error {
+ h.Lock()
+ defer h.Unlock()
+
+ dstH := o.(*Handle)
+ if h == dstH {
+ return nil
+ }
+ dstH.Lock()
+ dstH.bits = h.bits
+ dstH.unselected = h.unselected
+ dstH.head = h.head.getCopy()
+ dstH.app = h.app
+ dstH.id = h.id
+ dstH.dbIndex = h.dbIndex
+ dstH.dbExists = h.dbExists
+ dstH.store = h.store
+ dstH.Unlock()
+
+ return nil
+}
+
+// Skip provides a way for a KV Object to avoid persisting it in the KV Store
+func (h *Handle) Skip() bool {
+ return false
+}
+
+// DataScope method returns the storage scope of the datastore
+func (h *Handle) DataScope() string {
+ h.Lock()
+ defer h.Unlock()
+
+ return h.store.Scope()
+}
+
+func (h *Handle) fromDsValue(value []byte) error {
+ var ba []byte
+ if err := json.Unmarshal(value, &ba); err != nil {
+ return fmt.Errorf("failed to decode json: %s", err.Error())
+ }
+ if err := h.FromByteArray(ba); err != nil {
+ return fmt.Errorf("failed to decode handle: %s", err.Error())
+ }
+ return nil
+}
+
+func (h *Handle) writeToStore() error {
+ h.Lock()
+ store := h.store
+ h.Unlock()
+ if store == nil {
+ return nil
+ }
+ err := store.PutObjectAtomic(h)
+ if err == datastore.ErrKeyModified {
+ return types.RetryErrorf("failed to perform atomic write (%v). Retry might fix the error", err)
+ }
+ return err
+}
+
+func (h *Handle) deleteFromStore() error {
+ h.Lock()
+ store := h.store
+ h.Unlock()
+ if store == nil {
+ return nil
+ }
+ return store.DeleteObjectAtomic(h)
+}
diff --git a/vendor/github.com/docker/libnetwork/cluster/provider.go b/vendor/github.com/docker/libnetwork/cluster/provider.go
new file mode 100644
index 0000000..491ccfd
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/cluster/provider.go
@@ -0,0 +1,36 @@
+package cluster
+
+import (
+ "github.com/docker/docker/api/types/network"
+ "golang.org/x/net/context"
+)
+
+const (
+ // EventSocketChange control socket changed
+ EventSocketChange = iota
+ // EventNodeReady cluster node in ready state
+ EventNodeReady
+ // EventNodeLeave node is leaving the cluster
+ EventNodeLeave
+ // EventNetworkKeysAvailable network keys correctly configured in the networking layer
+ EventNetworkKeysAvailable
+)
+
+// ConfigEventType type of the event produced by the cluster
+type ConfigEventType uint8
+
+// Provider provides clustering config details
+type Provider interface {
+ IsManager() bool
+ IsAgent() bool
+ GetLocalAddress() string
+ GetListenAddress() string
+ GetAdvertiseAddress() string
+ GetDataPathAddress() string
+ GetRemoteAddressList() []string
+ ListenClusterEvents() <-chan ConfigEventType
+ AttachNetwork(string, string, []string) (*network.NetworkingConfig, error)
+ DetachNetwork(string, string) error
+ UpdateAttachment(string, string, *network.NetworkingConfig) error
+ WaitForDetachment(context.Context, string, string, string, string) error
+}
diff --git a/vendor/github.com/docker/libnetwork/cmd/proxy/main.go b/vendor/github.com/docker/libnetwork/cmd/proxy/main.go
new file mode 100644
index 0000000..c5d1ed6
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/cmd/proxy/main.go
@@ -0,0 +1,67 @@
+package proxy
+
+import (
+ "flag"
+ "fmt"
+ "log"
+ "net"
+ "os"
+ "os/signal"
+ "syscall"
+)
+
+func Main() {
+ f := os.NewFile(3, "signal-parent")
+ host, container := parseHostContainerAddrs()
+
+ p, err := NewProxy(host, container)
+ if err != nil {
+ fmt.Fprintf(f, "1\n%s", err)
+ f.Close()
+ os.Exit(1)
+ }
+ go handleStopSignals(p)
+ fmt.Fprint(f, "0\n")
+ f.Close()
+
+ // Run will block until the proxy stops
+ p.Run()
+}
+
+// parseHostContainerAddrs parses the flags passed on reexec to create the TCP or UDP
+// net.Addrs to map the host and container ports
+func parseHostContainerAddrs() (host net.Addr, container net.Addr) {
+ var (
+ proto = flag.String("proto", "tcp", "proxy protocol")
+ hostIP = flag.String("host-ip", "", "host ip")
+ hostPort = flag.Int("host-port", -1, "host port")
+ containerIP = flag.String("container-ip", "", "container ip")
+ containerPort = flag.Int("container-port", -1, "container port")
+ )
+
+ flag.Parse()
+
+ switch *proto {
+ case "tcp":
+ host = &net.TCPAddr{IP: net.ParseIP(*hostIP), Port: *hostPort}
+ container = &net.TCPAddr{IP: net.ParseIP(*containerIP), Port: *containerPort}
+ case "udp":
+ host = &net.UDPAddr{IP: net.ParseIP(*hostIP), Port: *hostPort}
+ container = &net.UDPAddr{IP: net.ParseIP(*containerIP), Port: *containerPort}
+ default:
+ log.Fatalf("unsupported protocol %s", *proto)
+ }
+
+ return host, container
+}
+
+func handleStopSignals(p Proxy) {
+ s := make(chan os.Signal, 10)
+ signal.Notify(s, os.Interrupt, syscall.SIGTERM)
+
+ for range s {
+ p.Close()
+
+ os.Exit(0)
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/cmd/proxy/proxy.go b/vendor/github.com/docker/libnetwork/cmd/proxy/proxy.go
new file mode 100644
index 0000000..7303703
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/cmd/proxy/proxy.go
@@ -0,0 +1,36 @@
+// docker-proxy provides a network Proxy interface and implementations for TCP
+// and UDP.
+package proxy
+
+import (
+ "net"
+)
+
+// Proxy defines the behavior of a proxy. It forwards traffic back and forth
+// between two endpoints : the frontend and the backend.
+// It can be used to do software port-mapping between two addresses.
+// e.g. forward all traffic between the frontend (host) 127.0.0.1:3000
+// to the backend (container) at 172.17.42.108:4000.
+type Proxy interface {
+ // Run starts forwarding traffic back and forth between the front
+ // and back-end addresses.
+ Run()
+ // Close stops forwarding traffic and close both ends of the Proxy.
+ Close()
+ // FrontendAddr returns the address on which the proxy is listening.
+ FrontendAddr() net.Addr
+ // BackendAddr returns the proxied address.
+ BackendAddr() net.Addr
+}
+
+// NewProxy creates a Proxy according to the specified frontendAddr and backendAddr.
+func NewProxy(frontendAddr, backendAddr net.Addr) (Proxy, error) {
+ switch frontendAddr.(type) {
+ case *net.UDPAddr:
+ return NewUDPProxy(frontendAddr.(*net.UDPAddr), backendAddr.(*net.UDPAddr))
+ case *net.TCPAddr:
+ return NewTCPProxy(frontendAddr.(*net.TCPAddr), backendAddr.(*net.TCPAddr))
+ default:
+ panic("Unsupported protocol")
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/cmd/proxy/stub_proxy.go b/vendor/github.com/docker/libnetwork/cmd/proxy/stub_proxy.go
new file mode 100644
index 0000000..571749e
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/cmd/proxy/stub_proxy.go
@@ -0,0 +1,31 @@
+package proxy
+
+import (
+ "net"
+)
+
+// StubProxy is a proxy that is a stub (does nothing).
+type StubProxy struct {
+ frontendAddr net.Addr
+ backendAddr net.Addr
+}
+
+// Run does nothing.
+func (p *StubProxy) Run() {}
+
+// Close does nothing.
+func (p *StubProxy) Close() {}
+
+// FrontendAddr returns the frontend address.
+func (p *StubProxy) FrontendAddr() net.Addr { return p.frontendAddr }
+
+// BackendAddr returns the backend address.
+func (p *StubProxy) BackendAddr() net.Addr { return p.backendAddr }
+
+// NewStubProxy creates a new StubProxy
+func NewStubProxy(frontendAddr, backendAddr net.Addr) (Proxy, error) {
+ return &StubProxy{
+ frontendAddr: frontendAddr,
+ backendAddr: backendAddr,
+ }, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/cmd/proxy/tcp_proxy.go b/vendor/github.com/docker/libnetwork/cmd/proxy/tcp_proxy.go
new file mode 100644
index 0000000..fd214dd
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/cmd/proxy/tcp_proxy.go
@@ -0,0 +1,89 @@
+package proxy
+
+import (
+ "io"
+ "log"
+ "net"
+ "sync"
+)
+
+// TCPProxy is a proxy for TCP connections. It implements the Proxy interface to
+// handle TCP traffic forwarding between the frontend and backend addresses.
+type TCPProxy struct {
+ listener *net.TCPListener
+ frontendAddr *net.TCPAddr
+ backendAddr *net.TCPAddr
+}
+
+// NewTCPProxy creates a new TCPProxy.
+func NewTCPProxy(frontendAddr, backendAddr *net.TCPAddr) (*TCPProxy, error) {
+ listener, err := net.ListenTCP("tcp", frontendAddr)
+ if err != nil {
+ return nil, err
+ }
+ // If the port in frontendAddr was 0 then ListenTCP will have a picked
+ // a port to listen on, hence the call to Addr to get that actual port:
+ return &TCPProxy{
+ listener: listener,
+ frontendAddr: listener.Addr().(*net.TCPAddr),
+ backendAddr: backendAddr,
+ }, nil
+}
+
+func (proxy *TCPProxy) clientLoop(client *net.TCPConn, quit chan bool) {
+ backend, err := net.DialTCP("tcp", nil, proxy.backendAddr)
+ if err != nil {
+ log.Printf("Can't forward traffic to backend tcp/%v: %s\n", proxy.backendAddr, err)
+ client.Close()
+ return
+ }
+
+ var wg sync.WaitGroup
+ var broker = func(to, from *net.TCPConn) {
+ io.Copy(to, from)
+ from.CloseRead()
+ to.CloseWrite()
+ wg.Done()
+ }
+
+ wg.Add(2)
+ go broker(client, backend)
+ go broker(backend, client)
+
+ finish := make(chan struct{})
+ go func() {
+ wg.Wait()
+ close(finish)
+ }()
+
+ select {
+ case <-quit:
+ case <-finish:
+ }
+ client.Close()
+ backend.Close()
+ <-finish
+}
+
+// Run starts forwarding the traffic using TCP.
+func (proxy *TCPProxy) Run() {
+ quit := make(chan bool)
+ defer close(quit)
+ for {
+ client, err := proxy.listener.Accept()
+ if err != nil {
+ log.Printf("Stopping proxy on tcp/%v for tcp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err)
+ return
+ }
+ go proxy.clientLoop(client.(*net.TCPConn), quit)
+ }
+}
+
+// Close stops forwarding the traffic.
+func (proxy *TCPProxy) Close() { proxy.listener.Close() }
+
+// FrontendAddr returns the TCP address on which the proxy is listening.
+func (proxy *TCPProxy) FrontendAddr() net.Addr { return proxy.frontendAddr }
+
+// BackendAddr returns the TCP proxied address.
+func (proxy *TCPProxy) BackendAddr() net.Addr { return proxy.backendAddr }
diff --git a/vendor/github.com/docker/libnetwork/cmd/proxy/udp_proxy.go b/vendor/github.com/docker/libnetwork/cmd/proxy/udp_proxy.go
new file mode 100644
index 0000000..b95ee62
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/cmd/proxy/udp_proxy.go
@@ -0,0 +1,168 @@
+package proxy
+
+import (
+ "encoding/binary"
+ "log"
+ "net"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+)
+
+const (
+ // UDPConnTrackTimeout is the timeout used for UDP connection tracking
+ UDPConnTrackTimeout = 90 * time.Second
+ // UDPBufSize is the buffer size for the UDP proxy
+ UDPBufSize = 65507
+)
+
+// A net.Addr where the IP is split into two fields so you can use it as a key
+// in a map:
+type connTrackKey struct {
+ IPHigh uint64
+ IPLow uint64
+ Port int
+}
+
+func newConnTrackKey(addr *net.UDPAddr) *connTrackKey {
+ if len(addr.IP) == net.IPv4len {
+ return &connTrackKey{
+ IPHigh: 0,
+ IPLow: uint64(binary.BigEndian.Uint32(addr.IP)),
+ Port: addr.Port,
+ }
+ }
+ return &connTrackKey{
+ IPHigh: binary.BigEndian.Uint64(addr.IP[:8]),
+ IPLow: binary.BigEndian.Uint64(addr.IP[8:]),
+ Port: addr.Port,
+ }
+}
+
+type connTrackMap map[connTrackKey]*net.UDPConn
+
+// UDPProxy is proxy for which handles UDP datagrams. It implements the Proxy
+// interface to handle UDP traffic forwarding between the frontend and backend
+// addresses.
+type UDPProxy struct {
+ listener *net.UDPConn
+ frontendAddr *net.UDPAddr
+ backendAddr *net.UDPAddr
+ connTrackTable connTrackMap
+ connTrackLock sync.Mutex
+}
+
+// NewUDPProxy creates a new UDPProxy.
+func NewUDPProxy(frontendAddr, backendAddr *net.UDPAddr) (*UDPProxy, error) {
+ listener, err := net.ListenUDP("udp", frontendAddr)
+ if err != nil {
+ return nil, err
+ }
+ return &UDPProxy{
+ listener: listener,
+ frontendAddr: listener.LocalAddr().(*net.UDPAddr),
+ backendAddr: backendAddr,
+ connTrackTable: make(connTrackMap),
+ }, nil
+}
+
+func (proxy *UDPProxy) replyLoop(proxyConn *net.UDPConn, clientAddr *net.UDPAddr, clientKey *connTrackKey) {
+ defer func() {
+ proxy.connTrackLock.Lock()
+ delete(proxy.connTrackTable, *clientKey)
+ proxy.connTrackLock.Unlock()
+ proxyConn.Close()
+ }()
+
+ readBuf := make([]byte, UDPBufSize)
+ for {
+ proxyConn.SetReadDeadline(time.Now().Add(UDPConnTrackTimeout))
+ again:
+ read, err := proxyConn.Read(readBuf)
+ if err != nil {
+ if err, ok := err.(*net.OpError); ok && err.Err == syscall.ECONNREFUSED {
+ // This will happen if the last write failed
+ // (e.g: nothing is actually listening on the
+ // proxied port on the container), ignore it
+ // and continue until UDPConnTrackTimeout
+ // expires:
+ goto again
+ }
+ return
+ }
+ for i := 0; i != read; {
+ written, err := proxy.listener.WriteToUDP(readBuf[i:read], clientAddr)
+ if err != nil {
+ return
+ }
+ i += written
+ }
+ }
+}
+
+// Run starts forwarding the traffic using UDP.
+func (proxy *UDPProxy) Run() {
+ readBuf := make([]byte, UDPBufSize)
+ for {
+ read, from, err := proxy.listener.ReadFromUDP(readBuf)
+ if err != nil {
+ // NOTE: Apparently ReadFrom doesn't return
+ // ECONNREFUSED like Read do (see comment in
+ // UDPProxy.replyLoop)
+ if !isClosedError(err) {
+ log.Printf("Stopping proxy on udp/%v for udp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err)
+ }
+ break
+ }
+
+ fromKey := newConnTrackKey(from)
+ proxy.connTrackLock.Lock()
+ proxyConn, hit := proxy.connTrackTable[*fromKey]
+ if !hit {
+ proxyConn, err = net.DialUDP("udp", nil, proxy.backendAddr)
+ if err != nil {
+ log.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err)
+ proxy.connTrackLock.Unlock()
+ continue
+ }
+ proxy.connTrackTable[*fromKey] = proxyConn
+ go proxy.replyLoop(proxyConn, from, fromKey)
+ }
+ proxy.connTrackLock.Unlock()
+ for i := 0; i != read; {
+ written, err := proxyConn.Write(readBuf[i:read])
+ if err != nil {
+ log.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err)
+ break
+ }
+ i += written
+ }
+ }
+}
+
+// Close stops forwarding the traffic.
+func (proxy *UDPProxy) Close() {
+ proxy.listener.Close()
+ proxy.connTrackLock.Lock()
+ defer proxy.connTrackLock.Unlock()
+ for _, conn := range proxy.connTrackTable {
+ conn.Close()
+ }
+}
+
+// FrontendAddr returns the UDP address on which the proxy is listening.
+func (proxy *UDPProxy) FrontendAddr() net.Addr { return proxy.frontendAddr }
+
+// BackendAddr returns the proxied UDP address.
+func (proxy *UDPProxy) BackendAddr() net.Addr { return proxy.backendAddr }
+
+func isClosedError(err error) bool {
+ /* This comparison is ugly, but unfortunately, net.go doesn't export errClosing.
+ * See:
+ * http://golang.org/src/pkg/net/net.go
+ * https://code.google.com/p/go/issues/detail?id=4337
+ * https://groups.google.com/forum/#!msg/golang-nuts/0_aaCvBmOcM/SptmDyX1XJMJ
+ */
+ return strings.HasSuffix(err.Error(), "use of closed network connection")
+}
diff --git a/vendor/github.com/docker/libnetwork/common/setmatrix.go b/vendor/github.com/docker/libnetwork/common/setmatrix.go
new file mode 100644
index 0000000..72be5bb
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/common/setmatrix.go
@@ -0,0 +1,135 @@
+package common
+
+import (
+ "sync"
+
+ mapset "github.com/deckarep/golang-set"
+)
+
+// SetMatrix is a map of Sets
+type SetMatrix interface {
+ // Get returns the members of the set for a specific key as a slice.
+ Get(key string) ([]interface{}, bool)
+ // Contains is used to verify if an element is in a set for a specific key
+ // returns true if the element is in the set
+ // returns true if there is a set for the key
+ Contains(key string, value interface{}) (bool, bool)
+ // Insert inserts the value in the set of a key
+ // returns true if the value is inserted (was not already in the set), false otherwise
+ // returns also the length of the set for the key
+ Insert(key string, value interface{}) (bool, int)
+ // Remove removes the value in the set for a specific key
+ // returns true if the value is deleted, false otherwise
+ // returns also the length of the set for the key
+ Remove(key string, value interface{}) (bool, int)
+ // Cardinality returns the number of elements in the set for a key
+ // returns false if the set is not present
+ Cardinality(key string) (int, bool)
+ // String returns the string version of the set, empty otherwise
+ // returns false if the set is not present
+ String(key string) (string, bool)
+ // Returns all the keys in the map
+ Keys() []string
+}
+
+type setMatrix struct {
+ matrix map[string]mapset.Set
+
+ sync.Mutex
+}
+
+// NewSetMatrix creates a new set matrix object
+func NewSetMatrix() SetMatrix {
+ s := &setMatrix{}
+ s.init()
+ return s
+}
+
+func (s *setMatrix) init() {
+ s.matrix = make(map[string]mapset.Set)
+}
+
+func (s *setMatrix) Get(key string) ([]interface{}, bool) {
+ s.Lock()
+ defer s.Unlock()
+ set, ok := s.matrix[key]
+ if !ok {
+ return nil, ok
+ }
+ return set.ToSlice(), ok
+}
+
+func (s *setMatrix) Contains(key string, value interface{}) (bool, bool) {
+ s.Lock()
+ defer s.Unlock()
+ set, ok := s.matrix[key]
+ if !ok {
+ return false, ok
+ }
+ return set.Contains(value), ok
+}
+
+func (s *setMatrix) Insert(key string, value interface{}) (bool, int) {
+ s.Lock()
+ defer s.Unlock()
+ set, ok := s.matrix[key]
+ if !ok {
+ s.matrix[key] = mapset.NewSet()
+ s.matrix[key].Add(value)
+ return true, 1
+ }
+
+ return set.Add(value), set.Cardinality()
+}
+
+func (s *setMatrix) Remove(key string, value interface{}) (bool, int) {
+ s.Lock()
+ defer s.Unlock()
+ set, ok := s.matrix[key]
+ if !ok {
+ return false, 0
+ }
+
+ var removed bool
+ if set.Contains(value) {
+ set.Remove(value)
+ removed = true
+ // If the set is empty remove it from the matrix
+ if set.Cardinality() == 0 {
+ delete(s.matrix, key)
+ }
+ }
+
+ return removed, set.Cardinality()
+}
+
+func (s *setMatrix) Cardinality(key string) (int, bool) {
+ s.Lock()
+ defer s.Unlock()
+ set, ok := s.matrix[key]
+ if !ok {
+ return 0, ok
+ }
+
+ return set.Cardinality(), ok
+}
+
+func (s *setMatrix) String(key string) (string, bool) {
+ s.Lock()
+ defer s.Unlock()
+ set, ok := s.matrix[key]
+ if !ok {
+ return "", ok
+ }
+ return set.String(), ok
+}
+
+func (s *setMatrix) Keys() []string {
+ s.Lock()
+ defer s.Unlock()
+ keys := make([]string, 0, len(s.matrix))
+ for k := range s.matrix {
+ keys = append(keys, k)
+ }
+ return keys
+}
diff --git a/vendor/github.com/docker/libnetwork/config/config.go b/vendor/github.com/docker/libnetwork/config/config.go
new file mode 100644
index 0000000..3acb432
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/config/config.go
@@ -0,0 +1,280 @@
+package config
+
+import (
+ "strings"
+
+ "github.com/BurntSushi/toml"
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/discovery"
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/go-connections/tlsconfig"
+ "github.com/docker/libkv/store"
+ "github.com/docker/libnetwork/cluster"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/osl"
+)
+
+// Config encapsulates configurations of various Libnetwork components
+type Config struct {
+ Daemon DaemonCfg
+ Cluster ClusterCfg
+ Scopes map[string]*datastore.ScopeCfg
+ ActiveSandboxes map[string]interface{}
+ PluginGetter plugingetter.PluginGetter
+}
+
+// DaemonCfg represents libnetwork core configuration
+type DaemonCfg struct {
+ Debug bool
+ Experimental bool
+ DataDir string
+ DefaultNetwork string
+ DefaultDriver string
+ Labels []string
+ DriverCfg map[string]interface{}
+ ClusterProvider cluster.Provider
+}
+
+// ClusterCfg represents cluster configuration
+type ClusterCfg struct {
+ Watcher discovery.Watcher
+ Address string
+ Discovery string
+ Heartbeat uint64
+}
+
+// LoadDefaultScopes loads default scope configs for scopes which
+// doesn't have explicit user specified configs.
+func (c *Config) LoadDefaultScopes(dataDir string) {
+ for k, v := range datastore.DefaultScopes(dataDir) {
+ if _, ok := c.Scopes[k]; !ok {
+ c.Scopes[k] = v
+ }
+ }
+}
+
+// ParseConfig parses the libnetwork configuration file
+func ParseConfig(tomlCfgFile string) (*Config, error) {
+ cfg := &Config{
+ Scopes: map[string]*datastore.ScopeCfg{},
+ }
+
+ if _, err := toml.DecodeFile(tomlCfgFile, cfg); err != nil {
+ return nil, err
+ }
+
+ cfg.LoadDefaultScopes(cfg.Daemon.DataDir)
+ return cfg, nil
+}
+
+// ParseConfigOptions parses the configuration options and returns
+// a reference to the corresponding Config structure
+func ParseConfigOptions(cfgOptions ...Option) *Config {
+ cfg := &Config{
+ Daemon: DaemonCfg{
+ DriverCfg: make(map[string]interface{}),
+ },
+ Scopes: make(map[string]*datastore.ScopeCfg),
+ }
+
+ cfg.ProcessOptions(cfgOptions...)
+ cfg.LoadDefaultScopes(cfg.Daemon.DataDir)
+
+ return cfg
+}
+
+// Option is an option setter function type used to pass various configurations
+// to the controller
+type Option func(c *Config)
+
+// OptionDefaultNetwork function returns an option setter for a default network
+func OptionDefaultNetwork(dn string) Option {
+ return func(c *Config) {
+ logrus.Debugf("Option DefaultNetwork: %s", dn)
+ c.Daemon.DefaultNetwork = strings.TrimSpace(dn)
+ }
+}
+
+// OptionDefaultDriver function returns an option setter for default driver
+func OptionDefaultDriver(dd string) Option {
+ return func(c *Config) {
+ logrus.Debugf("Option DefaultDriver: %s", dd)
+ c.Daemon.DefaultDriver = strings.TrimSpace(dd)
+ }
+}
+
+// OptionDriverConfig returns an option setter for driver configuration.
+func OptionDriverConfig(networkType string, config map[string]interface{}) Option {
+ return func(c *Config) {
+ c.Daemon.DriverCfg[networkType] = config
+ }
+}
+
+// OptionLabels function returns an option setter for labels
+func OptionLabels(labels []string) Option {
+ return func(c *Config) {
+ for _, label := range labels {
+ if strings.HasPrefix(label, netlabel.Prefix) {
+ c.Daemon.Labels = append(c.Daemon.Labels, label)
+ }
+ }
+ }
+}
+
+// OptionKVProvider function returns an option setter for kvstore provider
+func OptionKVProvider(provider string) Option {
+ return func(c *Config) {
+ logrus.Debugf("Option OptionKVProvider: %s", provider)
+ if _, ok := c.Scopes[datastore.GlobalScope]; !ok {
+ c.Scopes[datastore.GlobalScope] = &datastore.ScopeCfg{}
+ }
+ c.Scopes[datastore.GlobalScope].Client.Provider = strings.TrimSpace(provider)
+ }
+}
+
+// OptionKVProviderURL function returns an option setter for kvstore url
+func OptionKVProviderURL(url string) Option {
+ return func(c *Config) {
+ logrus.Debugf("Option OptionKVProviderURL: %s", url)
+ if _, ok := c.Scopes[datastore.GlobalScope]; !ok {
+ c.Scopes[datastore.GlobalScope] = &datastore.ScopeCfg{}
+ }
+ c.Scopes[datastore.GlobalScope].Client.Address = strings.TrimSpace(url)
+ }
+}
+
+// OptionKVOpts function returns an option setter for kvstore options
+func OptionKVOpts(opts map[string]string) Option {
+ return func(c *Config) {
+ if opts["kv.cacertfile"] != "" && opts["kv.certfile"] != "" && opts["kv.keyfile"] != "" {
+ logrus.Info("Option Initializing KV with TLS")
+ tlsConfig, err := tlsconfig.Client(tlsconfig.Options{
+ CAFile: opts["kv.cacertfile"],
+ CertFile: opts["kv.certfile"],
+ KeyFile: opts["kv.keyfile"],
+ })
+ if err != nil {
+ logrus.Errorf("Unable to set up TLS: %s", err)
+ return
+ }
+ if _, ok := c.Scopes[datastore.GlobalScope]; !ok {
+ c.Scopes[datastore.GlobalScope] = &datastore.ScopeCfg{}
+ }
+ if c.Scopes[datastore.GlobalScope].Client.Config == nil {
+ c.Scopes[datastore.GlobalScope].Client.Config = &store.Config{TLS: tlsConfig}
+ } else {
+ c.Scopes[datastore.GlobalScope].Client.Config.TLS = tlsConfig
+ }
+ // Workaround libkv/etcd bug for https
+ c.Scopes[datastore.GlobalScope].Client.Config.ClientTLS = &store.ClientTLSConfig{
+ CACertFile: opts["kv.cacertfile"],
+ CertFile: opts["kv.certfile"],
+ KeyFile: opts["kv.keyfile"],
+ }
+ } else {
+ logrus.Info("Option Initializing KV without TLS")
+ }
+ }
+}
+
+// OptionDiscoveryWatcher function returns an option setter for discovery watcher
+func OptionDiscoveryWatcher(watcher discovery.Watcher) Option {
+ return func(c *Config) {
+ c.Cluster.Watcher = watcher
+ }
+}
+
+// OptionDiscoveryAddress function returns an option setter for self discovery address
+func OptionDiscoveryAddress(address string) Option {
+ return func(c *Config) {
+ c.Cluster.Address = address
+ }
+}
+
+// OptionDataDir function returns an option setter for data folder
+func OptionDataDir(dataDir string) Option {
+ return func(c *Config) {
+ c.Daemon.DataDir = dataDir
+ }
+}
+
+// OptionExecRoot function returns an option setter for exec root folder
+func OptionExecRoot(execRoot string) Option {
+ return func(c *Config) {
+ osl.SetBasePath(execRoot)
+ }
+}
+
+// OptionPluginGetter returns a plugingetter for remote drivers.
+func OptionPluginGetter(pg plugingetter.PluginGetter) Option {
+ return func(c *Config) {
+ c.PluginGetter = pg
+ }
+}
+
+// OptionExperimental function returns an option setter for experimental daemon
+func OptionExperimental(exp bool) Option {
+ return func(c *Config) {
+ logrus.Debugf("Option Experimental: %v", exp)
+ c.Daemon.Experimental = exp
+ }
+}
+
+// ProcessOptions processes options and stores it in config
+func (c *Config) ProcessOptions(options ...Option) {
+ for _, opt := range options {
+ if opt != nil {
+ opt(c)
+ }
+ }
+}
+
+// IsValidName validates configuration objects supported by libnetwork
+func IsValidName(name string) bool {
+ if strings.TrimSpace(name) == "" {
+ return false
+ }
+ return true
+}
+
+// OptionLocalKVProvider function returns an option setter for kvstore provider
+func OptionLocalKVProvider(provider string) Option {
+ return func(c *Config) {
+ logrus.Debugf("Option OptionLocalKVProvider: %s", provider)
+ if _, ok := c.Scopes[datastore.LocalScope]; !ok {
+ c.Scopes[datastore.LocalScope] = &datastore.ScopeCfg{}
+ }
+ c.Scopes[datastore.LocalScope].Client.Provider = strings.TrimSpace(provider)
+ }
+}
+
+// OptionLocalKVProviderURL function returns an option setter for kvstore url
+func OptionLocalKVProviderURL(url string) Option {
+ return func(c *Config) {
+ logrus.Debugf("Option OptionLocalKVProviderURL: %s", url)
+ if _, ok := c.Scopes[datastore.LocalScope]; !ok {
+ c.Scopes[datastore.LocalScope] = &datastore.ScopeCfg{}
+ }
+ c.Scopes[datastore.LocalScope].Client.Address = strings.TrimSpace(url)
+ }
+}
+
+// OptionLocalKVProviderConfig function returns an option setter for kvstore config
+func OptionLocalKVProviderConfig(config *store.Config) Option {
+ return func(c *Config) {
+ logrus.Debugf("Option OptionLocalKVProviderConfig: %v", config)
+ if _, ok := c.Scopes[datastore.LocalScope]; !ok {
+ c.Scopes[datastore.LocalScope] = &datastore.ScopeCfg{}
+ }
+ c.Scopes[datastore.LocalScope].Client.Config = config
+ }
+}
+
+// OptionActiveSandboxes function returns an option setter for passing the sandboxes
+// which were active during previous daemon life
+func OptionActiveSandboxes(sandboxes map[string]interface{}) Option {
+ return func(c *Config) {
+ c.ActiveSandboxes = sandboxes
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/controller.go b/vendor/github.com/docker/libnetwork/controller.go
new file mode 100644
index 0000000..1696e07
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/controller.go
@@ -0,0 +1,1269 @@
+/*
+Package libnetwork provides the basic functionality and extension points to
+create network namespaces and allocate interfaces for containers to use.
+
+ networkType := "bridge"
+
+ // Create a new controller instance
+ driverOptions := options.Generic{}
+ genericOption := make(map[string]interface{})
+ genericOption[netlabel.GenericData] = driverOptions
+ controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
+ if err != nil {
+ return
+ }
+
+ // Create a network for containers to join.
+ // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make use of
+ network, err := controller.NewNetwork(networkType, "network1", "")
+ if err != nil {
+ return
+ }
+
+ // For each new container: allocate IP and interfaces. The returned network
+ // settings will be used for container infos (inspect and such), as well as
+ // iptables rules for port publishing. This info is contained or accessible
+ // from the returned endpoint.
+ ep, err := network.CreateEndpoint("Endpoint1")
+ if err != nil {
+ return
+ }
+
+ // Create the sandbox for the container.
+ // NewSandbox accepts Variadic optional arguments which libnetwork can use.
+ sbx, err := controller.NewSandbox("container1",
+ libnetwork.OptionHostname("test"),
+ libnetwork.OptionDomainname("docker.io"))
+
+ // A sandbox can join the endpoint via the join api.
+ err = ep.Join(sbx)
+ if err != nil {
+ return
+ }
+*/
+package libnetwork
+
+import (
+ "container/heap"
+ "fmt"
+ "net"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/discovery"
+ "github.com/docker/docker/pkg/locker"
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/docker/pkg/plugins"
+ "github.com/docker/docker/pkg/stringid"
+ "github.com/docker/libnetwork/cluster"
+ "github.com/docker/libnetwork/config"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/drvregistry"
+ "github.com/docker/libnetwork/hostdiscovery"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/types"
+)
+
+// NetworkController provides the interface for controller instance which manages
+// networks.
+type NetworkController interface {
+ // ID provides a unique identity for the controller
+ ID() string
+
+ // BuiltinDrivers returns list of builtin drivers
+ BuiltinDrivers() []string
+
+ // BuiltinIPAMDrivers returns list of builtin ipam drivers
+ BuiltinIPAMDrivers() []string
+
+ // Config method returns the bootup configuration for the controller
+ Config() config.Config
+
+ // Create a new network. The options parameter carries network specific options.
+ NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error)
+
+ // Networks returns the list of Network(s) managed by this controller.
+ Networks() []Network
+
+ // WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
+ WalkNetworks(walker NetworkWalker)
+
+ // NetworkByName returns the Network which has the passed name. If not found, the error ErrNoSuchNetwork is returned.
+ NetworkByName(name string) (Network, error)
+
+ // NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned.
+ NetworkByID(id string) (Network, error)
+
+ // NewSandbox creates a new network sandbox for the passed container id
+ NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
+
+ // Sandboxes returns the list of Sandbox(s) managed by this controller.
+ Sandboxes() []Sandbox
+
+ // WalkSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
+ WalkSandboxes(walker SandboxWalker)
+
+ // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned.
+ SandboxByID(id string) (Sandbox, error)
+
+ // SandboxDestroy destroys a sandbox given a container ID
+ SandboxDestroy(id string) error
+
+ // Stop network controller
+ Stop()
+
+ // ReloadCondfiguration updates the controller configuration
+ ReloadConfiguration(cfgOptions ...config.Option) error
+
+ // SetClusterProvider sets cluster provider
+ SetClusterProvider(provider cluster.Provider)
+
+ // Wait for agent initialization complete in libnetwork controller
+ AgentInitWait()
+
+ // Wait for agent to stop if running
+ AgentStopWait()
+
+ // SetKeys configures the encryption key for gossip and overlay data path
+ SetKeys(keys []*types.EncryptionKey) error
+}
+
+// NetworkWalker is a client provided function which will be used to walk the Networks.
+// When the function returns true, the walk will stop.
+type NetworkWalker func(nw Network) bool
+
+// SandboxWalker is a client provided function which will be used to walk the Sandboxes.
+// When the function returns true, the walk will stop.
+type SandboxWalker func(sb Sandbox) bool
+
+type sandboxTable map[string]*sandbox
+
+type controller struct {
+ id string
+ drvRegistry *drvregistry.DrvRegistry
+ sandboxes sandboxTable
+ cfg *config.Config
+ stores []datastore.DataStore
+ discovery hostdiscovery.HostDiscovery
+ extKeyListener net.Listener
+ watchCh chan *endpoint
+ unWatchCh chan *endpoint
+ svcRecords map[string]svcInfo
+ nmap map[string]*netWatch
+ serviceBindings map[serviceKey]*service
+ defOsSbox osl.Sandbox
+ ingressSandbox *sandbox
+ sboxOnce sync.Once
+ agent *agent
+ networkLocker *locker.Locker
+ agentInitDone chan struct{}
+ agentStopDone chan struct{}
+ keys []*types.EncryptionKey
+ clusterConfigAvailable bool
+ sync.Mutex
+}
+
+type initializer struct {
+ fn drvregistry.InitFunc
+ ntype string
+}
+
+// New creates a new instance of network controller.
+func New(cfgOptions ...config.Option) (NetworkController, error) {
+ c := &controller{
+ id: stringid.GenerateRandomID(),
+ cfg: config.ParseConfigOptions(cfgOptions...),
+ sandboxes: sandboxTable{},
+ svcRecords: make(map[string]svcInfo),
+ serviceBindings: make(map[serviceKey]*service),
+ agentInitDone: make(chan struct{}),
+ networkLocker: locker.New(),
+ }
+
+ if err := c.initStores(); err != nil {
+ return nil, err
+ }
+
+ drvRegistry, err := drvregistry.New(c.getStore(datastore.LocalScope), c.getStore(datastore.GlobalScope), c.RegisterDriver, nil, c.cfg.PluginGetter)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, i := range getInitializers(c.cfg.Daemon.Experimental) {
+ var dcfg map[string]interface{}
+
+ // External plugins don't need config passed through daemon. They can
+ // bootstrap themselves
+ if i.ntype != "remote" {
+ dcfg = c.makeDriverConfig(i.ntype)
+ }
+
+ if err := drvRegistry.AddDriver(i.ntype, i.fn, dcfg); err != nil {
+ return nil, err
+ }
+ }
+
+ if err = initIPAMDrivers(drvRegistry, nil, c.getStore(datastore.GlobalScope)); err != nil {
+ return nil, err
+ }
+
+ c.drvRegistry = drvRegistry
+
+ if c.cfg != nil && c.cfg.Cluster.Watcher != nil {
+ if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
+ // Failing to initialize discovery is a bad situation to be in.
+ // But it cannot fail creating the Controller
+ logrus.Errorf("Failed to Initialize Discovery : %v", err)
+ }
+ }
+
+ c.WalkNetworks(populateSpecial)
+
+ // Reserve pools first before doing cleanup. Otherwise the
+ // cleanups of endpoint/network and sandbox below will
+ // generate many unnecessary warnings
+ c.reservePools()
+
+ // Cleanup resources
+ c.sandboxCleanup(c.cfg.ActiveSandboxes)
+ c.cleanupLocalEndpoints()
+ c.networkCleanup()
+
+ if err := c.startExternalKeyListener(); err != nil {
+ return nil, err
+ }
+
+ return c, nil
+}
+
+func (c *controller) SetClusterProvider(provider cluster.Provider) {
+ var sameProvider bool
+ c.Lock()
+ // Avoids to spawn multiple goroutine for the same cluster provider
+ if c.cfg.Daemon.ClusterProvider == provider {
+ // If the cluster provider is already set, there is already a go routine spawned
+ // that is listening for events, so nothing to do here
+ sameProvider = true
+ } else {
+ c.cfg.Daemon.ClusterProvider = provider
+ }
+ c.Unlock()
+
+ if provider == nil || sameProvider {
+ return
+ }
+ // We don't want to spawn a new go routine if the previous one did not exit yet
+ c.AgentStopWait()
+ go c.clusterAgentInit()
+}
+
+func isValidClusteringIP(addr string) bool {
+ return addr != "" && !net.ParseIP(addr).IsLoopback() && !net.ParseIP(addr).IsUnspecified()
+}
+
+// libnetwork side of agent depends on the keys. On the first receipt of
+// keys setup the agent. For subsequent key set handle the key change
+func (c *controller) SetKeys(keys []*types.EncryptionKey) error {
+ subsysKeys := make(map[string]int)
+ for _, key := range keys {
+ if key.Subsystem != subsysGossip &&
+ key.Subsystem != subsysIPSec {
+ return fmt.Errorf("key received for unrecognized subsystem")
+ }
+ subsysKeys[key.Subsystem]++
+ }
+ for s, count := range subsysKeys {
+ if count != keyringSize {
+ return fmt.Errorf("incorrect number of keys for subsystem %v", s)
+ }
+ }
+
+ agent := c.getAgent()
+
+ if agent == nil {
+ c.Lock()
+ c.keys = keys
+ c.Unlock()
+ return nil
+ }
+ return c.handleKeyChange(keys)
+}
+
+func (c *controller) getAgent() *agent {
+ c.Lock()
+ defer c.Unlock()
+ return c.agent
+}
+
+func (c *controller) clusterAgentInit() {
+ clusterProvider := c.cfg.Daemon.ClusterProvider
+ var keysAvailable bool
+ for {
+ eventType := <-clusterProvider.ListenClusterEvents()
+ // The events: EventSocketChange, EventNodeReady and EventNetworkKeysAvailable are not ordered
+ // when all the condition for the agent initialization are met then proceed with it
+ switch eventType {
+ case cluster.EventNetworkKeysAvailable:
+ // Validates that the keys are actually available before starting the initialization
+ // This will handle old spurious messages left on the channel
+ c.Lock()
+ keysAvailable = c.keys != nil
+ c.Unlock()
+ fallthrough
+ case cluster.EventSocketChange, cluster.EventNodeReady:
+ if keysAvailable && !c.isDistributedControl() {
+ c.agentOperationStart()
+ if err := c.agentSetup(clusterProvider); err != nil {
+ c.agentStopComplete()
+ } else {
+ c.agentInitComplete()
+ }
+ }
+ case cluster.EventNodeLeave:
+ keysAvailable = false
+ c.agentOperationStart()
+ c.Lock()
+ c.keys = nil
+ c.Unlock()
+
+ // We are leaving the cluster. Make sure we
+ // close the gossip so that we stop all
+ // incoming gossip updates before cleaning up
+ // any remaining service bindings. But before
+ // deleting the networks since the networks
+ // should still be present when cleaning up
+ // service bindings
+ c.agentClose()
+ c.cleanupServiceBindings("")
+
+ c.agentStopComplete()
+
+ return
+ }
+ }
+}
+
+// AgentInitWait waits for agent initialization to be completed in the controller.
+func (c *controller) AgentInitWait() {
+ c.Lock()
+ agentInitDone := c.agentInitDone
+ c.Unlock()
+
+ if agentInitDone != nil {
+ <-agentInitDone
+ }
+}
+
+// AgentStopWait waits for the Agent stop to be completed in the controller
+func (c *controller) AgentStopWait() {
+ c.Lock()
+ agentStopDone := c.agentStopDone
+ c.Unlock()
+ if agentStopDone != nil {
+ <-agentStopDone
+ }
+}
+
+// agentOperationStart marks the start of an Agent Init or Agent Stop
+func (c *controller) agentOperationStart() {
+ c.Lock()
+ if c.agentInitDone == nil {
+ c.agentInitDone = make(chan struct{})
+ }
+ if c.agentStopDone == nil {
+ c.agentStopDone = make(chan struct{})
+ }
+ c.Unlock()
+}
+
+// agentInitComplete notifies the successful completion of the Agent initialization
+func (c *controller) agentInitComplete() {
+ c.Lock()
+ if c.agentInitDone != nil {
+ close(c.agentInitDone)
+ c.agentInitDone = nil
+ }
+ c.Unlock()
+}
+
+// agentStopComplete notifies the successful completion of the Agent stop
+func (c *controller) agentStopComplete() {
+ c.Lock()
+ if c.agentStopDone != nil {
+ close(c.agentStopDone)
+ c.agentStopDone = nil
+ }
+ c.Unlock()
+}
+
+func (c *controller) makeDriverConfig(ntype string) map[string]interface{} {
+ if c.cfg == nil {
+ return nil
+ }
+
+ config := make(map[string]interface{})
+
+ for _, label := range c.cfg.Daemon.Labels {
+ if !strings.HasPrefix(netlabel.Key(label), netlabel.DriverPrefix+"."+ntype) {
+ continue
+ }
+
+ config[netlabel.Key(label)] = netlabel.Value(label)
+ }
+
+ drvCfg, ok := c.cfg.Daemon.DriverCfg[ntype]
+ if ok {
+ for k, v := range drvCfg.(map[string]interface{}) {
+ config[k] = v
+ }
+ }
+
+ for k, v := range c.cfg.Scopes {
+ if !v.IsValid() {
+ continue
+ }
+ config[netlabel.MakeKVClient(k)] = discoverapi.DatastoreConfigData{
+ Scope: k,
+ Provider: v.Client.Provider,
+ Address: v.Client.Address,
+ Config: v.Client.Config,
+ }
+ }
+
+ return config
+}
+
+var procReloadConfig = make(chan (bool), 1)
+
+func (c *controller) ReloadConfiguration(cfgOptions ...config.Option) error {
+ procReloadConfig <- true
+ defer func() { <-procReloadConfig }()
+
+ // For now we accept the configuration reload only as a mean to provide a global store config after boot.
+ // Refuse the configuration if it alters an existing datastore client configuration.
+ update := false
+ cfg := config.ParseConfigOptions(cfgOptions...)
+
+ for s := range c.cfg.Scopes {
+ if _, ok := cfg.Scopes[s]; !ok {
+ return types.ForbiddenErrorf("cannot accept new configuration because it removes an existing datastore client")
+ }
+ }
+ for s, nSCfg := range cfg.Scopes {
+ if eSCfg, ok := c.cfg.Scopes[s]; ok {
+ if eSCfg.Client.Provider != nSCfg.Client.Provider ||
+ eSCfg.Client.Address != nSCfg.Client.Address {
+ return types.ForbiddenErrorf("cannot accept new configuration because it modifies an existing datastore client")
+ }
+ } else {
+ if err := c.initScopedStore(s, nSCfg); err != nil {
+ return err
+ }
+ update = true
+ }
+ }
+ if !update {
+ return nil
+ }
+
+ c.Lock()
+ c.cfg = cfg
+ c.Unlock()
+
+ var dsConfig *discoverapi.DatastoreConfigData
+ for scope, sCfg := range cfg.Scopes {
+ if scope == datastore.LocalScope || !sCfg.IsValid() {
+ continue
+ }
+ dsConfig = &discoverapi.DatastoreConfigData{
+ Scope: scope,
+ Provider: sCfg.Client.Provider,
+ Address: sCfg.Client.Address,
+ Config: sCfg.Client.Config,
+ }
+ break
+ }
+ if dsConfig == nil {
+ return nil
+ }
+
+ c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
+ err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
+ if err != nil {
+ logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
+ }
+ return false
+ })
+
+ c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
+ err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
+ if err != nil {
+ logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
+ }
+ return false
+ })
+
+ if c.discovery == nil && c.cfg.Cluster.Watcher != nil {
+ if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
+ logrus.Errorf("Failed to Initialize Discovery after configuration update: %v", err)
+ }
+ }
+
+ return nil
+}
+
+func (c *controller) ID() string {
+ return c.id
+}
+
+func (c *controller) BuiltinDrivers() []string {
+ drivers := []string{}
+ c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
+ if driver.IsBuiltIn() {
+ drivers = append(drivers, name)
+ }
+ return false
+ })
+ return drivers
+}
+
+func (c *controller) BuiltinIPAMDrivers() []string {
+ drivers := []string{}
+ c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
+ if driver.IsBuiltIn() {
+ drivers = append(drivers, name)
+ }
+ return false
+ })
+ return drivers
+}
+
+func (c *controller) validateHostDiscoveryConfig() bool {
+ if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
+ return false
+ }
+ return true
+}
+
+func (c *controller) clusterHostID() string {
+ c.Lock()
+ defer c.Unlock()
+ if c.cfg == nil || c.cfg.Cluster.Address == "" {
+ return ""
+ }
+ addr := strings.Split(c.cfg.Cluster.Address, ":")
+ return addr[0]
+}
+
+func (c *controller) isNodeAlive(node string) bool {
+ if c.discovery == nil {
+ return false
+ }
+
+ nodes := c.discovery.Fetch()
+ for _, n := range nodes {
+ if n.String() == node {
+ return true
+ }
+ }
+
+ return false
+}
+
+func (c *controller) initDiscovery(watcher discovery.Watcher) error {
+ if c.cfg == nil {
+ return fmt.Errorf("discovery initialization requires a valid configuration")
+ }
+
+ c.discovery = hostdiscovery.NewHostDiscovery(watcher)
+ return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
+}
+
+func (c *controller) activeCallback() {
+ ds := c.getStore(datastore.GlobalScope)
+ if ds != nil && !ds.Active() {
+ ds.RestartWatch()
+ }
+}
+
+func (c *controller) hostJoinCallback(nodes []net.IP) {
+ c.processNodeDiscovery(nodes, true)
+}
+
+func (c *controller) hostLeaveCallback(nodes []net.IP) {
+ c.processNodeDiscovery(nodes, false)
+}
+
+func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
+ c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
+ c.pushNodeDiscovery(driver, capability, nodes, add)
+ return false
+ })
+}
+
+func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
+ var self net.IP
+ if c.cfg != nil {
+ addr := strings.Split(c.cfg.Cluster.Address, ":")
+ self = net.ParseIP(addr[0])
+ // if external kvstore is not configured, try swarm-mode config
+ if self == nil {
+ if agent := c.getAgent(); agent != nil {
+ self = net.ParseIP(agent.advertiseAddr)
+ }
+ }
+ }
+
+ if d == nil || cap.ConnectivityScope != datastore.GlobalScope || nodes == nil {
+ return
+ }
+
+ for _, node := range nodes {
+ nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
+ var err error
+ if add {
+ err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
+ } else {
+ err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
+ }
+ if err != nil {
+ logrus.Debugf("discovery notification error: %v", err)
+ }
+ }
+}
+
+func (c *controller) Config() config.Config {
+ c.Lock()
+ defer c.Unlock()
+ if c.cfg == nil {
+ return config.Config{}
+ }
+ return *c.cfg
+}
+
+func (c *controller) isManager() bool {
+ c.Lock()
+ defer c.Unlock()
+ if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
+ return false
+ }
+ return c.cfg.Daemon.ClusterProvider.IsManager()
+}
+
+func (c *controller) isAgent() bool {
+ c.Lock()
+ defer c.Unlock()
+ if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
+ return false
+ }
+ return c.cfg.Daemon.ClusterProvider.IsAgent()
+}
+
+func (c *controller) isDistributedControl() bool {
+ return !c.isManager() && !c.isAgent()
+}
+
+func (c *controller) GetPluginGetter() plugingetter.PluginGetter {
+ return c.drvRegistry.GetPluginGetter()
+}
+
+func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
+ c.Lock()
+ hd := c.discovery
+ c.Unlock()
+
+ if hd != nil {
+ c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
+ }
+
+ c.agentDriverNotify(driver)
+ return nil
+}
+
+// NewNetwork creates a new network of the specified network type. The options
+// are network specific and modeled in a generic way.
+func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
+ if id != "" {
+ c.networkLocker.Lock(id)
+ defer c.networkLocker.Unlock(id)
+
+ if _, err := c.NetworkByID(id); err == nil {
+ return nil, NetworkNameError(id)
+ }
+ }
+
+ if !config.IsValidName(name) {
+ return nil, ErrInvalidName(name)
+ }
+
+ if id == "" {
+ id = stringid.GenerateRandomID()
+ }
+
+ defaultIpam := defaultIpamForNetworkType(networkType)
+ // Construct the network object
+ network := &network{
+ name: name,
+ networkType: networkType,
+ generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
+ ipamType: defaultIpam,
+ id: id,
+ created: time.Now(),
+ ctrlr: c,
+ persist: true,
+ drvOnce: &sync.Once{},
+ }
+
+ network.processOptions(options...)
+ if err := network.validateConfiguration(); err != nil {
+ return nil, err
+ }
+
+ var (
+ cap *driverapi.Capability
+ err error
+ )
+
+ // Reset network types, force local scope and skip allocation and
+ // plumbing for configuration networks. Reset of the config-only
+ // network drivers is needed so that this special network is not
+ // usable by old engine versions.
+ if network.configOnly {
+ network.scope = datastore.LocalScope
+ network.networkType = "null"
+ goto addToStore
+ }
+
+ _, cap, err = network.resolveDriver(network.networkType, true)
+ if err != nil {
+ return nil, err
+ }
+
+ if network.scope == datastore.LocalScope && cap.DataScope == datastore.GlobalScope {
+ return nil, types.ForbiddenErrorf("cannot downgrade network scope for %s networks", networkType)
+
+ }
+ if network.ingress && cap.DataScope != datastore.GlobalScope {
+ return nil, types.ForbiddenErrorf("Ingress network can only be global scope network")
+ }
+
+ // At this point the network scope is still unknown if not set by user
+ if (cap.DataScope == datastore.GlobalScope || network.scope == datastore.SwarmScope) &&
+ !c.isDistributedControl() && !network.dynamic {
+ if c.isManager() {
+ // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
+ return nil, ManagerRedirectError(name)
+ }
+ return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
+ }
+
+ if network.scope == datastore.SwarmScope && c.isDistributedControl() {
+ return nil, types.ForbiddenErrorf("cannot create a swarm scoped network when swarm is not active")
+ }
+
+ // Make sure we have a driver available for this network type
+ // before we allocate anything.
+ if _, err := network.driver(true); err != nil {
+ return nil, err
+ }
+
+ // From this point on, we need the network specific configuration,
+ // which may come from a configuration-only network
+ if network.configFrom != "" {
+ t, err := c.getConfigNetwork(network.configFrom)
+ if err != nil {
+ return nil, types.NotFoundErrorf("configuration network %q does not exist", network.configFrom)
+ }
+ if err := t.applyConfigurationTo(network); err != nil {
+ return nil, types.InternalErrorf("Failed to apply configuration: %v", err)
+ }
+ defer func() {
+ if err == nil {
+ if err := t.getEpCnt().IncEndpointCnt(); err != nil {
+ logrus.Warnf("Failed to update reference count for configuration network %q on creation of network %q: %v",
+ t.Name(), network.Name(), err)
+ }
+ }
+ }()
+ }
+
+ err = network.ipamAllocate()
+ if err != nil {
+ return nil, err
+ }
+ defer func() {
+ if err != nil {
+ network.ipamRelease()
+ }
+ }()
+
+ err = c.addNetwork(network)
+ if err != nil {
+ return nil, err
+ }
+ defer func() {
+ if err != nil {
+ if e := network.deleteNetwork(); e != nil {
+ logrus.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
+ }
+ }
+ }()
+
+addToStore:
+ // First store the endpoint count, then the network. To avoid to
+ // end up with a datastore containing a network and not an epCnt,
+ // in case of an ungraceful shutdown during this function call.
+ epCnt := &endpointCnt{n: network}
+ if err = c.updateToStore(epCnt); err != nil {
+ return nil, err
+ }
+ defer func() {
+ if err != nil {
+ if e := c.deleteFromStore(epCnt); e != nil {
+ logrus.Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
+ }
+ }
+ }()
+
+ network.epCnt = epCnt
+ if err = c.updateToStore(network); err != nil {
+ return nil, err
+ }
+ if network.configOnly {
+ return network, nil
+ }
+
+ joinCluster(network)
+ if !c.isDistributedControl() {
+ c.Lock()
+ arrangeIngressFilterRule()
+ c.Unlock()
+ }
+
+ c.Lock()
+ arrangeUserFilterRule()
+ c.Unlock()
+
+ return network, nil
+}
+
+var joinCluster NetworkWalker = func(nw Network) bool {
+ n := nw.(*network)
+ if n.configOnly {
+ return false
+ }
+ if err := n.joinCluster(); err != nil {
+ logrus.Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err)
+ }
+ n.addDriverWatches()
+ return false
+}
+
+func (c *controller) reservePools() {
+ networks, err := c.getNetworksForScope(datastore.LocalScope)
+ if err != nil {
+ logrus.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
+ return
+ }
+
+ for _, n := range networks {
+ if n.configOnly {
+ continue
+ }
+ if !doReplayPoolReserve(n) {
+ continue
+ }
+ // Construct pseudo configs for the auto IP case
+ autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
+ autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
+ if autoIPv4 {
+ n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
+ }
+ if n.enableIPv6 && autoIPv6 {
+ n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
+ }
+ // Account current network gateways
+ for i, c := range n.ipamV4Config {
+ if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
+ c.Gateway = n.ipamV4Info[i].Gateway.IP.String()
+ }
+ }
+ if n.enableIPv6 {
+ for i, c := range n.ipamV6Config {
+ if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
+ c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
+ }
+ }
+ }
+ // Reserve pools
+ if err := n.ipamAllocate(); err != nil {
+ logrus.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
+ }
+ // Reserve existing endpoints' addresses
+ ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
+ if err != nil {
+ logrus.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
+ continue
+ }
+ epl, err := n.getEndpointsFromStore()
+ if err != nil {
+ logrus.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
+ continue
+ }
+ for _, ep := range epl {
+ if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
+ logrus.Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)",
+ ep.Name(), ep.ID(), n.Name(), n.ID())
+ }
+ }
+ }
+}
+
+func doReplayPoolReserve(n *network) bool {
+ _, caps, err := n.getController().getIPAMDriver(n.ipamType)
+ if err != nil {
+ logrus.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
+ return false
+ }
+ return caps.RequiresRequestReplay
+}
+
+func (c *controller) addNetwork(n *network) error {
+ d, err := n.driver(true)
+ if err != nil {
+ return err
+ }
+
+ // Create the network
+ if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
+ return err
+ }
+
+ n.startResolver()
+
+ return nil
+}
+
+func (c *controller) Networks() []Network {
+ var list []Network
+
+ networks, err := c.getNetworksFromStore()
+ if err != nil {
+ logrus.Error(err)
+ }
+
+ for _, n := range networks {
+ if n.inDelete {
+ continue
+ }
+ list = append(list, n)
+ }
+
+ return list
+}
+
+func (c *controller) WalkNetworks(walker NetworkWalker) {
+ for _, n := range c.Networks() {
+ if walker(n) {
+ return
+ }
+ }
+}
+
+func (c *controller) NetworkByName(name string) (Network, error) {
+ if name == "" {
+ return nil, ErrInvalidName(name)
+ }
+ var n Network
+
+ s := func(current Network) bool {
+ if current.Name() == name {
+ n = current
+ return true
+ }
+ return false
+ }
+
+ c.WalkNetworks(s)
+
+ if n == nil {
+ return nil, ErrNoSuchNetwork(name)
+ }
+
+ return n, nil
+}
+
+func (c *controller) NetworkByID(id string) (Network, error) {
+ if id == "" {
+ return nil, ErrInvalidID(id)
+ }
+
+ n, err := c.getNetworkFromStore(id)
+ if err != nil {
+ return nil, ErrNoSuchNetwork(id)
+ }
+
+ return n, nil
+}
+
+// NewSandbox creates a new sandbox for the passed container id
+func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
+ if containerID == "" {
+ return nil, types.BadRequestErrorf("invalid container ID")
+ }
+
+ var sb *sandbox
+ c.Lock()
+ for _, s := range c.sandboxes {
+ if s.containerID == containerID {
+ // If not a stub, then we already have a complete sandbox.
+ if !s.isStub {
+ sbID := s.ID()
+ c.Unlock()
+ return nil, types.ForbiddenErrorf("container %s is already present in sandbox %s", containerID, sbID)
+ }
+
+ // We already have a stub sandbox from the
+ // store. Make use of it so that we don't lose
+ // the endpoints from store but reset the
+ // isStub flag.
+ sb = s
+ sb.isStub = false
+ break
+ }
+ }
+ c.Unlock()
+
+ // Create sandbox and process options first. Key generation depends on an option
+ if sb == nil {
+ sb = &sandbox{
+ id: stringid.GenerateRandomID(),
+ containerID: containerID,
+ endpoints: epHeap{},
+ epPriority: map[string]int{},
+ populatedEndpoints: map[string]struct{}{},
+ config: containerConfig{},
+ controller: c,
+ extDNS: []extDNSEntry{},
+ }
+ }
+
+ heap.Init(&sb.endpoints)
+
+ sb.processOptions(options...)
+
+ c.Lock()
+ if sb.ingress && c.ingressSandbox != nil {
+ c.Unlock()
+ return nil, types.ForbiddenErrorf("ingress sandbox already present")
+ }
+
+ if sb.ingress {
+ c.ingressSandbox = sb
+ sb.config.hostsPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/hosts")
+ sb.config.resolvConfPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/resolv.conf")
+ sb.id = "ingress_sbox"
+ }
+ c.Unlock()
+
+ var err error
+ defer func() {
+ if err != nil {
+ c.Lock()
+ if sb.ingress {
+ c.ingressSandbox = nil
+ }
+ c.Unlock()
+ }
+ }()
+
+ if err = sb.setupResolutionFiles(); err != nil {
+ return nil, err
+ }
+
+ if sb.config.useDefaultSandBox {
+ c.sboxOnce.Do(func() {
+ c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
+ })
+
+ if err != nil {
+ c.sboxOnce = sync.Once{}
+ return nil, fmt.Errorf("failed to create default sandbox: %v", err)
+ }
+
+ sb.osSbox = c.defOsSbox
+ }
+
+ if sb.osSbox == nil && !sb.config.useExternalKey {
+ if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
+ return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
+ }
+ }
+
+ c.Lock()
+ c.sandboxes[sb.id] = sb
+ c.Unlock()
+ defer func() {
+ if err != nil {
+ c.Lock()
+ delete(c.sandboxes, sb.id)
+ c.Unlock()
+ }
+ }()
+
+ err = sb.storeUpdate()
+ if err != nil {
+ return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err)
+ }
+
+ return sb, nil
+}
+
+func (c *controller) Sandboxes() []Sandbox {
+ c.Lock()
+ defer c.Unlock()
+
+ list := make([]Sandbox, 0, len(c.sandboxes))
+ for _, s := range c.sandboxes {
+ // Hide stub sandboxes from libnetwork users
+ if s.isStub {
+ continue
+ }
+
+ list = append(list, s)
+ }
+
+ return list
+}
+
+func (c *controller) WalkSandboxes(walker SandboxWalker) {
+ for _, sb := range c.Sandboxes() {
+ if walker(sb) {
+ return
+ }
+ }
+}
+
+func (c *controller) SandboxByID(id string) (Sandbox, error) {
+ if id == "" {
+ return nil, ErrInvalidID(id)
+ }
+ c.Lock()
+ s, ok := c.sandboxes[id]
+ c.Unlock()
+ if !ok {
+ return nil, types.NotFoundErrorf("sandbox %s not found", id)
+ }
+ return s, nil
+}
+
+// SandboxDestroy destroys a sandbox given a container ID
+func (c *controller) SandboxDestroy(id string) error {
+ var sb *sandbox
+ c.Lock()
+ for _, s := range c.sandboxes {
+ if s.containerID == id {
+ sb = s
+ break
+ }
+ }
+ c.Unlock()
+
+ // It is not an error if sandbox is not available
+ if sb == nil {
+ return nil
+ }
+
+ return sb.Delete()
+}
+
+// SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
+func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
+ return func(sb Sandbox) bool {
+ if sb.ContainerID() == containerID {
+ *out = sb
+ return true
+ }
+ return false
+ }
+}
+
+// SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
+func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
+ return func(sb Sandbox) bool {
+ if sb.Key() == key {
+ *out = sb
+ return true
+ }
+ return false
+ }
+}
+
+func (c *controller) loadDriver(networkType string) error {
+ var err error
+
+ if pg := c.GetPluginGetter(); pg != nil {
+ _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.Lookup)
+ } else {
+ _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
+ }
+
+ if err != nil {
+ if err == plugins.ErrNotFound {
+ return types.NotFoundErrorf(err.Error())
+ }
+ return err
+ }
+
+ return nil
+}
+
+func (c *controller) loadIPAMDriver(name string) error {
+ var err error
+
+ if pg := c.GetPluginGetter(); pg != nil {
+ _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.Lookup)
+ } else {
+ _, err = plugins.Get(name, ipamapi.PluginEndpointType)
+ }
+
+ if err != nil {
+ if err == plugins.ErrNotFound {
+ return types.NotFoundErrorf(err.Error())
+ }
+ return err
+ }
+
+ return nil
+}
+
+func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
+ id, cap := c.drvRegistry.IPAM(name)
+ if id == nil {
+ // Might be a plugin name. Try loading it
+ if err := c.loadIPAMDriver(name); err != nil {
+ return nil, nil, err
+ }
+
+ // Now that we resolved the plugin, try again looking up the registry
+ id, cap = c.drvRegistry.IPAM(name)
+ if id == nil {
+ return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
+ }
+ }
+
+ return id, cap, nil
+}
+
+func (c *controller) Stop() {
+ c.closeStores()
+ c.stopExternalKeyListener()
+ osl.GC()
+}
diff --git a/vendor/github.com/docker/libnetwork/datastore/cache.go b/vendor/github.com/docker/libnetwork/datastore/cache.go
new file mode 100644
index 0000000..49839ae
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/datastore/cache.go
@@ -0,0 +1,178 @@
+package datastore
+
+import (
+ "errors"
+ "fmt"
+ "sync"
+
+ "github.com/docker/libkv/store"
+)
+
+type kvMap map[string]KVObject
+
+type cache struct {
+ sync.Mutex
+ kmm map[string]kvMap
+ ds *datastore
+}
+
+func newCache(ds *datastore) *cache {
+ return &cache{kmm: make(map[string]kvMap), ds: ds}
+}
+
+func (c *cache) kmap(kvObject KVObject) (kvMap, error) {
+ var err error
+
+ c.Lock()
+ keyPrefix := Key(kvObject.KeyPrefix()...)
+ kmap, ok := c.kmm[keyPrefix]
+ c.Unlock()
+
+ if ok {
+ return kmap, nil
+ }
+
+ kmap = kvMap{}
+
+ // Bail out right away if the kvObject does not implement KVConstructor
+ ctor, ok := kvObject.(KVConstructor)
+ if !ok {
+ return nil, errors.New("error while populating kmap, object does not implement KVConstructor interface")
+ }
+
+ kvList, err := c.ds.store.List(keyPrefix)
+ if err != nil {
+ if err == store.ErrKeyNotFound {
+ // If the store doesn't have anything then there is nothing to
+ // populate in the cache. Just bail out.
+ goto out
+ }
+
+ return nil, fmt.Errorf("error while populating kmap: %v", err)
+ }
+
+ for _, kvPair := range kvList {
+ // Ignore empty kvPair values
+ if len(kvPair.Value) == 0 {
+ continue
+ }
+
+ dstO := ctor.New()
+ err = dstO.SetValue(kvPair.Value)
+ if err != nil {
+ return nil, err
+ }
+
+ // Make sure the object has a correct view of the DB index in
+ // case we need to modify it and update the DB.
+ dstO.SetIndex(kvPair.LastIndex)
+
+ kmap[Key(dstO.Key()...)] = dstO
+ }
+
+out:
+ // There may multiple go routines racing to fill the
+ // cache. The one which places the kmap in c.kmm first
+ // wins. The others should just use what the first populated.
+ c.Lock()
+ kmapNew, ok := c.kmm[keyPrefix]
+ if ok {
+ c.Unlock()
+ return kmapNew, nil
+ }
+
+ c.kmm[keyPrefix] = kmap
+ c.Unlock()
+
+ return kmap, nil
+}
+
+func (c *cache) add(kvObject KVObject, atomic bool) error {
+ kmap, err := c.kmap(kvObject)
+ if err != nil {
+ return err
+ }
+
+ c.Lock()
+ // If atomic is true, cache needs to maintain its own index
+ // for atomicity and the add needs to be atomic.
+ if atomic {
+ if prev, ok := kmap[Key(kvObject.Key()...)]; ok {
+ if prev.Index() != kvObject.Index() {
+ c.Unlock()
+ return ErrKeyModified
+ }
+ }
+
+ // Increment index
+ index := kvObject.Index()
+ index++
+ kvObject.SetIndex(index)
+ }
+
+ kmap[Key(kvObject.Key()...)] = kvObject
+ c.Unlock()
+ return nil
+}
+
+func (c *cache) del(kvObject KVObject, atomic bool) error {
+ kmap, err := c.kmap(kvObject)
+ if err != nil {
+ return err
+ }
+
+ c.Lock()
+ // If atomic is true, cache needs to maintain its own index
+ // for atomicity and del needs to be atomic.
+ if atomic {
+ if prev, ok := kmap[Key(kvObject.Key()...)]; ok {
+ if prev.Index() != kvObject.Index() {
+ c.Unlock()
+ return ErrKeyModified
+ }
+ }
+ }
+
+ delete(kmap, Key(kvObject.Key()...))
+ c.Unlock()
+ return nil
+}
+
+func (c *cache) get(key string, kvObject KVObject) error {
+ kmap, err := c.kmap(kvObject)
+ if err != nil {
+ return err
+ }
+
+ c.Lock()
+ defer c.Unlock()
+
+ o, ok := kmap[Key(kvObject.Key()...)]
+ if !ok {
+ return ErrKeyNotFound
+ }
+
+ ctor, ok := o.(KVConstructor)
+ if !ok {
+ return errors.New("kvobject does not implement KVConstructor interface. could not get object")
+ }
+
+ return ctor.CopyTo(kvObject)
+}
+
+func (c *cache) list(kvObject KVObject) ([]KVObject, error) {
+ kmap, err := c.kmap(kvObject)
+ if err != nil {
+ return nil, err
+ }
+
+ c.Lock()
+ defer c.Unlock()
+
+ var kvol []KVObject
+ for _, v := range kmap {
+ kvol = append(kvol, v)
+ }
+
+ return kvol, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/datastore/datastore.go b/vendor/github.com/docker/libnetwork/datastore/datastore.go
new file mode 100644
index 0000000..82feef1
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/datastore/datastore.go
@@ -0,0 +1,660 @@
+package datastore
+
+import (
+ "fmt"
+ "log"
+ "reflect"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/docker/libkv"
+ "github.com/docker/libkv/store"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/types"
+)
+
+//DataStore exported
+type DataStore interface {
+ // GetObject gets data from datastore and unmarshals to the specified object
+ GetObject(key string, o KVObject) error
+ // PutObject adds a new Record based on an object into the datastore
+ PutObject(kvObject KVObject) error
+ // PutObjectAtomic provides an atomic add and update operation for a Record
+ PutObjectAtomic(kvObject KVObject) error
+ // DeleteObject deletes a record
+ DeleteObject(kvObject KVObject) error
+ // DeleteObjectAtomic performs an atomic delete operation
+ DeleteObjectAtomic(kvObject KVObject) error
+ // DeleteTree deletes a record
+ DeleteTree(kvObject KVObject) error
+ // Watchable returns whether the store is watchable or not
+ Watchable() bool
+ // Watch for changes on a KVObject
+ Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error)
+ // RestartWatch retriggers stopped Watches
+ RestartWatch()
+ // Active returns if the store is active
+ Active() bool
+ // List returns of a list of KVObjects belonging to the parent
+ // key. The caller must pass a KVObject of the same type as
+ // the objects that need to be listed
+ List(string, KVObject) ([]KVObject, error)
+ // Map returns a Map of KVObjects
+ Map(key string, kvObject KVObject) (map[string]KVObject, error)
+ // Scope returns the scope of the store
+ Scope() string
+ // KVStore returns access to the KV Store
+ KVStore() store.Store
+ // Close closes the data store
+ Close()
+}
+
+// ErrKeyModified is raised for an atomic update when the update is working on a stale state
+var (
+ ErrKeyModified = store.ErrKeyModified
+ ErrKeyNotFound = store.ErrKeyNotFound
+)
+
+type datastore struct {
+ scope string
+ store store.Store
+ cache *cache
+ watchCh chan struct{}
+ active bool
+ sequential bool
+ sync.Mutex
+}
+
+// KVObject is Key/Value interface used by objects to be part of the DataStore
+type KVObject interface {
+ // Key method lets an object provide the Key to be used in KV Store
+ Key() []string
+ // KeyPrefix method lets an object return immediate parent key that can be used for tree walk
+ KeyPrefix() []string
+ // Value method lets an object marshal its content to be stored in the KV store
+ Value() []byte
+ // SetValue is used by the datastore to set the object's value when loaded from the data store.
+ SetValue([]byte) error
+ // Index method returns the latest DB Index as seen by the object
+ Index() uint64
+ // SetIndex method allows the datastore to store the latest DB Index into the object
+ SetIndex(uint64)
+ // True if the object exists in the datastore, false if it hasn't been stored yet.
+ // When SetIndex() is called, the object has been stored.
+ Exists() bool
+ // DataScope indicates the storage scope of the KV object
+ DataScope() string
+ // Skip provides a way for a KV Object to avoid persisting it in the KV Store
+ Skip() bool
+}
+
+// KVConstructor interface defines methods which can construct a KVObject from another.
+type KVConstructor interface {
+ // New returns a new object which is created based on the
+ // source object
+ New() KVObject
+ // CopyTo deep copies the contents of the implementing object
+ // to the passed destination object
+ CopyTo(KVObject) error
+}
+
+// ScopeCfg represents Datastore configuration.
+type ScopeCfg struct {
+ Client ScopeClientCfg
+}
+
+// ScopeClientCfg represents Datastore Client-only mode configuration
+type ScopeClientCfg struct {
+ Provider string
+ Address string
+ Config *store.Config
+}
+
+const (
+ // LocalScope indicates to store the KV object in local datastore such as boltdb
+ LocalScope = "local"
+ // GlobalScope indicates to store the KV object in global datastore such as consul/etcd/zookeeper
+ GlobalScope = "global"
+ // SwarmScope is not indicating a datastore location. It is defined here
+ // along with the other two scopes just for consistency.
+ SwarmScope = "swarm"
+ defaultPrefix = "/var/lib/docker/network/files"
+)
+
+const (
+ // NetworkKeyPrefix is the prefix for network key in the kv store
+ NetworkKeyPrefix = "network"
+ // EndpointKeyPrefix is the prefix for endpoint key in the kv store
+ EndpointKeyPrefix = "endpoint"
+)
+
+var (
+ defaultScopes = makeDefaultScopes()
+)
+
+func makeDefaultScopes() map[string]*ScopeCfg {
+ def := make(map[string]*ScopeCfg)
+ def[LocalScope] = &ScopeCfg{
+ Client: ScopeClientCfg{
+ Provider: string(store.BOLTDB),
+ Address: defaultPrefix + "/local-kv.db",
+ Config: &store.Config{
+ Bucket: "libnetwork",
+ ConnectionTimeout: time.Minute,
+ },
+ },
+ }
+
+ return def
+}
+
+var defaultRootChain = []string{"docker", "network", "v1.0"}
+var rootChain = defaultRootChain
+
+// DefaultScopes returns a map of default scopes and its config for clients to use.
+func DefaultScopes(dataDir string) map[string]*ScopeCfg {
+ if dataDir != "" {
+ defaultScopes[LocalScope].Client.Address = dataDir + "/network/files/local-kv.db"
+ return defaultScopes
+ }
+
+ defaultScopes[LocalScope].Client.Address = defaultPrefix + "/local-kv.db"
+ return defaultScopes
+}
+
+// IsValid checks if the scope config has valid configuration.
+func (cfg *ScopeCfg) IsValid() bool {
+ if cfg == nil ||
+ strings.TrimSpace(cfg.Client.Provider) == "" ||
+ strings.TrimSpace(cfg.Client.Address) == "" {
+ return false
+ }
+
+ return true
+}
+
+//Key provides convenient method to create a Key
+func Key(key ...string) string {
+ keychain := append(rootChain, key...)
+ str := strings.Join(keychain, "/")
+ return str + "/"
+}
+
+//ParseKey provides convenient method to unpack the key to complement the Key function
+func ParseKey(key string) ([]string, error) {
+ chain := strings.Split(strings.Trim(key, "/"), "/")
+
+ // The key must atleast be equal to the rootChain in order to be considered as valid
+ if len(chain) <= len(rootChain) || !reflect.DeepEqual(chain[0:len(rootChain)], rootChain) {
+ return nil, types.BadRequestErrorf("invalid Key : %s", key)
+ }
+ return chain[len(rootChain):], nil
+}
+
+// newClient used to connect to KV Store
+func newClient(scope string, kv string, addr string, config *store.Config, cached bool) (DataStore, error) {
+
+ if cached && scope != LocalScope {
+ return nil, fmt.Errorf("caching supported only for scope %s", LocalScope)
+ }
+ sequential := false
+ if scope == LocalScope {
+ sequential = true
+ }
+
+ if config == nil {
+ config = &store.Config{}
+ }
+
+ var addrs []string
+
+ if kv == string(store.BOLTDB) {
+ // Parse file path
+ addrs = strings.Split(addr, ",")
+ } else {
+ // Parse URI
+ parts := strings.SplitN(addr, "/", 2)
+ addrs = strings.Split(parts[0], ",")
+
+ // Add the custom prefix to the root chain
+ if len(parts) == 2 {
+ rootChain = append([]string{parts[1]}, defaultRootChain...)
+ }
+ }
+
+ store, err := libkv.NewStore(store.Backend(kv), addrs, config)
+ if err != nil {
+ return nil, err
+ }
+
+ ds := &datastore{scope: scope, store: store, active: true, watchCh: make(chan struct{}), sequential: sequential}
+ if cached {
+ ds.cache = newCache(ds)
+ }
+
+ return ds, nil
+}
+
+// NewDataStore creates a new instance of LibKV data store
+func NewDataStore(scope string, cfg *ScopeCfg) (DataStore, error) {
+ if cfg == nil || cfg.Client.Provider == "" || cfg.Client.Address == "" {
+ c, ok := defaultScopes[scope]
+ if !ok || c.Client.Provider == "" || c.Client.Address == "" {
+ return nil, fmt.Errorf("unexpected scope %s without configuration passed", scope)
+ }
+
+ cfg = c
+ }
+
+ var cached bool
+ if scope == LocalScope {
+ cached = true
+ }
+
+ return newClient(scope, cfg.Client.Provider, cfg.Client.Address, cfg.Client.Config, cached)
+}
+
+// NewDataStoreFromConfig creates a new instance of LibKV data store starting from the datastore config data
+func NewDataStoreFromConfig(dsc discoverapi.DatastoreConfigData) (DataStore, error) {
+ var (
+ ok bool
+ sCfgP *store.Config
+ )
+
+ sCfgP, ok = dsc.Config.(*store.Config)
+ if !ok && dsc.Config != nil {
+ return nil, fmt.Errorf("cannot parse store configuration: %v", dsc.Config)
+ }
+
+ scopeCfg := &ScopeCfg{
+ Client: ScopeClientCfg{
+ Address: dsc.Address,
+ Provider: dsc.Provider,
+ Config: sCfgP,
+ },
+ }
+
+ ds, err := NewDataStore(dsc.Scope, scopeCfg)
+ if err != nil {
+ return nil, fmt.Errorf("failed to construct datastore client from datastore configuration %v: %v", dsc, err)
+ }
+
+ return ds, err
+}
+
+func (ds *datastore) Close() {
+ ds.store.Close()
+}
+
+func (ds *datastore) Scope() string {
+ return ds.scope
+}
+
+func (ds *datastore) Active() bool {
+ return ds.active
+}
+
+func (ds *datastore) Watchable() bool {
+ return ds.scope != LocalScope
+}
+
+func (ds *datastore) Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error) {
+ sCh := make(chan struct{})
+
+ ctor, ok := kvObject.(KVConstructor)
+ if !ok {
+ return nil, fmt.Errorf("error watching object type %T, object does not implement KVConstructor interface", kvObject)
+ }
+
+ kvpCh, err := ds.store.Watch(Key(kvObject.Key()...), sCh)
+ if err != nil {
+ return nil, err
+ }
+
+ kvoCh := make(chan KVObject)
+
+ go func() {
+ retry_watch:
+ var err error
+
+ // Make sure to get a new instance of watch channel
+ ds.Lock()
+ watchCh := ds.watchCh
+ ds.Unlock()
+
+ loop:
+ for {
+ select {
+ case <-stopCh:
+ close(sCh)
+ return
+ case kvPair := <-kvpCh:
+ // If the backend KV store gets reset libkv's go routine
+ // for the watch can exit resulting in a nil value in
+ // channel.
+ if kvPair == nil {
+ ds.Lock()
+ ds.active = false
+ ds.Unlock()
+ break loop
+ }
+
+ dstO := ctor.New()
+
+ if err = dstO.SetValue(kvPair.Value); err != nil {
+ log.Printf("Could not unmarshal kvpair value = %s", string(kvPair.Value))
+ break
+ }
+
+ dstO.SetIndex(kvPair.LastIndex)
+ kvoCh <- dstO
+ }
+ }
+
+ // Wait on watch channel for a re-trigger when datastore becomes active
+ <-watchCh
+
+ kvpCh, err = ds.store.Watch(Key(kvObject.Key()...), sCh)
+ if err != nil {
+ log.Printf("Could not watch the key %s in store: %v", Key(kvObject.Key()...), err)
+ }
+
+ goto retry_watch
+ }()
+
+ return kvoCh, nil
+}
+
+func (ds *datastore) RestartWatch() {
+ ds.Lock()
+ defer ds.Unlock()
+
+ ds.active = true
+ watchCh := ds.watchCh
+ ds.watchCh = make(chan struct{})
+ close(watchCh)
+}
+
+func (ds *datastore) KVStore() store.Store {
+ return ds.store
+}
+
+// PutObjectAtomic adds a new Record based on an object into the datastore
+func (ds *datastore) PutObjectAtomic(kvObject KVObject) error {
+ var (
+ previous *store.KVPair
+ pair *store.KVPair
+ err error
+ )
+ if ds.sequential {
+ ds.Lock()
+ defer ds.Unlock()
+ }
+
+ if kvObject == nil {
+ return types.BadRequestErrorf("invalid KV Object : nil")
+ }
+
+ kvObjValue := kvObject.Value()
+
+ if kvObjValue == nil {
+ return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
+ }
+
+ if kvObject.Skip() {
+ goto add_cache
+ }
+
+ if kvObject.Exists() {
+ previous = &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
+ } else {
+ previous = nil
+ }
+
+ _, pair, err = ds.store.AtomicPut(Key(kvObject.Key()...), kvObjValue, previous, nil)
+ if err != nil {
+ if err == store.ErrKeyExists {
+ return ErrKeyModified
+ }
+ return err
+ }
+
+ kvObject.SetIndex(pair.LastIndex)
+
+add_cache:
+ if ds.cache != nil {
+ // If persistent store is skipped, sequencing needs to
+ // happen in cache.
+ return ds.cache.add(kvObject, kvObject.Skip())
+ }
+
+ return nil
+}
+
+// PutObject adds a new Record based on an object into the datastore
+func (ds *datastore) PutObject(kvObject KVObject) error {
+ if ds.sequential {
+ ds.Lock()
+ defer ds.Unlock()
+ }
+
+ if kvObject == nil {
+ return types.BadRequestErrorf("invalid KV Object : nil")
+ }
+
+ if kvObject.Skip() {
+ goto add_cache
+ }
+
+ if err := ds.putObjectWithKey(kvObject, kvObject.Key()...); err != nil {
+ return err
+ }
+
+add_cache:
+ if ds.cache != nil {
+ // If persistent store is skipped, sequencing needs to
+ // happen in cache.
+ return ds.cache.add(kvObject, kvObject.Skip())
+ }
+
+ return nil
+}
+
+func (ds *datastore) putObjectWithKey(kvObject KVObject, key ...string) error {
+ kvObjValue := kvObject.Value()
+
+ if kvObjValue == nil {
+ return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
+ }
+ return ds.store.Put(Key(key...), kvObjValue, nil)
+}
+
+// GetObject returns a record matching the key
+func (ds *datastore) GetObject(key string, o KVObject) error {
+ if ds.sequential {
+ ds.Lock()
+ defer ds.Unlock()
+ }
+
+ if ds.cache != nil {
+ return ds.cache.get(key, o)
+ }
+
+ kvPair, err := ds.store.Get(key)
+ if err != nil {
+ return err
+ }
+
+ if err := o.SetValue(kvPair.Value); err != nil {
+ return err
+ }
+
+ // Make sure the object has a correct view of the DB index in
+ // case we need to modify it and update the DB.
+ o.SetIndex(kvPair.LastIndex)
+ return nil
+}
+
+func (ds *datastore) ensureParent(parent string) error {
+ exists, err := ds.store.Exists(parent)
+ if err != nil {
+ return err
+ }
+ if exists {
+ return nil
+ }
+ return ds.store.Put(parent, []byte{}, &store.WriteOptions{IsDir: true})
+}
+
+func (ds *datastore) List(key string, kvObject KVObject) ([]KVObject, error) {
+ if ds.sequential {
+ ds.Lock()
+ defer ds.Unlock()
+ }
+
+ if ds.cache != nil {
+ return ds.cache.list(kvObject)
+ }
+
+ var kvol []KVObject
+ cb := func(key string, val KVObject) {
+ kvol = append(kvol, val)
+ }
+ err := ds.iterateKVPairsFromStore(key, kvObject, cb)
+ if err != nil {
+ return nil, err
+ }
+ return kvol, nil
+}
+
+func (ds *datastore) iterateKVPairsFromStore(key string, kvObject KVObject, callback func(string, KVObject)) error {
+ // Bail out right away if the kvObject does not implement KVConstructor
+ ctor, ok := kvObject.(KVConstructor)
+ if !ok {
+ return fmt.Errorf("error listing objects, object does not implement KVConstructor interface")
+ }
+
+ // Make sure the parent key exists
+ if err := ds.ensureParent(key); err != nil {
+ return err
+ }
+
+ kvList, err := ds.store.List(key)
+ if err != nil {
+ return err
+ }
+
+ for _, kvPair := range kvList {
+ if len(kvPair.Value) == 0 {
+ continue
+ }
+
+ dstO := ctor.New()
+ if err := dstO.SetValue(kvPair.Value); err != nil {
+ return err
+ }
+
+ // Make sure the object has a correct view of the DB index in
+ // case we need to modify it and update the DB.
+ dstO.SetIndex(kvPair.LastIndex)
+ callback(kvPair.Key, dstO)
+ }
+
+ return nil
+}
+
+func (ds *datastore) Map(key string, kvObject KVObject) (map[string]KVObject, error) {
+ if ds.sequential {
+ ds.Lock()
+ defer ds.Unlock()
+ }
+
+ kvol := make(map[string]KVObject)
+ cb := func(key string, val KVObject) {
+ // Trim the leading & trailing "/" to make it consistent across all stores
+ kvol[strings.Trim(key, "/")] = val
+ }
+ err := ds.iterateKVPairsFromStore(key, kvObject, cb)
+ if err != nil {
+ return nil, err
+ }
+ return kvol, nil
+}
+
+// DeleteObject unconditionally deletes a record from the store
+func (ds *datastore) DeleteObject(kvObject KVObject) error {
+ if ds.sequential {
+ ds.Lock()
+ defer ds.Unlock()
+ }
+
+ // cleaup the cache first
+ if ds.cache != nil {
+ // If persistent store is skipped, sequencing needs to
+ // happen in cache.
+ ds.cache.del(kvObject, kvObject.Skip())
+ }
+
+ if kvObject.Skip() {
+ return nil
+ }
+
+ return ds.store.Delete(Key(kvObject.Key()...))
+}
+
+// DeleteObjectAtomic performs atomic delete on a record
+func (ds *datastore) DeleteObjectAtomic(kvObject KVObject) error {
+ if ds.sequential {
+ ds.Lock()
+ defer ds.Unlock()
+ }
+
+ if kvObject == nil {
+ return types.BadRequestErrorf("invalid KV Object : nil")
+ }
+
+ previous := &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
+
+ if kvObject.Skip() {
+ goto del_cache
+ }
+
+ if _, err := ds.store.AtomicDelete(Key(kvObject.Key()...), previous); err != nil {
+ if err == store.ErrKeyExists {
+ return ErrKeyModified
+ }
+ return err
+ }
+
+del_cache:
+ // cleanup the cache only if AtomicDelete went through successfully
+ if ds.cache != nil {
+ // If persistent store is skipped, sequencing needs to
+ // happen in cache.
+ return ds.cache.del(kvObject, kvObject.Skip())
+ }
+
+ return nil
+}
+
+// DeleteTree unconditionally deletes a record from the store
+func (ds *datastore) DeleteTree(kvObject KVObject) error {
+ if ds.sequential {
+ ds.Lock()
+ defer ds.Unlock()
+ }
+
+ // cleaup the cache first
+ if ds.cache != nil {
+ // If persistent store is skipped, sequencing needs to
+ // happen in cache.
+ ds.cache.del(kvObject, kvObject.Skip())
+ }
+
+ if kvObject.Skip() {
+ return nil
+ }
+
+ return ds.store.DeleteTree(Key(kvObject.KeyPrefix()...))
+}
diff --git a/vendor/github.com/docker/libnetwork/datastore/mock_store.go b/vendor/github.com/docker/libnetwork/datastore/mock_store.go
new file mode 100644
index 0000000..0817339
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/datastore/mock_store.go
@@ -0,0 +1,129 @@
+package datastore
+
+import (
+ "errors"
+
+ "github.com/docker/libkv/store"
+ "github.com/docker/libnetwork/types"
+)
+
+var (
+ // ErrNotImplmented exported
+ ErrNotImplmented = errors.New("Functionality not implemented")
+)
+
+// MockData exported
+type MockData struct {
+ Data []byte
+ Index uint64
+}
+
+// MockStore exported
+type MockStore struct {
+ db map[string]*MockData
+}
+
+// NewMockStore creates a Map backed Datastore that is useful for mocking
+func NewMockStore() *MockStore {
+ db := make(map[string]*MockData)
+ return &MockStore{db}
+}
+
+// Get the value at "key", returns the last modified index
+// to use in conjunction to CAS calls
+func (s *MockStore) Get(key string) (*store.KVPair, error) {
+ mData := s.db[key]
+ if mData == nil {
+ return nil, nil
+ }
+ return &store.KVPair{Value: mData.Data, LastIndex: mData.Index}, nil
+
+}
+
+// Put a value at "key"
+func (s *MockStore) Put(key string, value []byte, options *store.WriteOptions) error {
+ mData := s.db[key]
+ if mData == nil {
+ mData = &MockData{value, 0}
+ }
+ mData.Index = mData.Index + 1
+ s.db[key] = mData
+ return nil
+}
+
+// Delete a value at "key"
+func (s *MockStore) Delete(key string) error {
+ delete(s.db, key)
+ return nil
+}
+
+// Exists checks that the key exists inside the store
+func (s *MockStore) Exists(key string) (bool, error) {
+ _, ok := s.db[key]
+ return ok, nil
+}
+
+// List gets a range of values at "directory"
+func (s *MockStore) List(prefix string) ([]*store.KVPair, error) {
+ return nil, ErrNotImplmented
+}
+
+// DeleteTree deletes a range of values at "directory"
+func (s *MockStore) DeleteTree(prefix string) error {
+ delete(s.db, prefix)
+ return nil
+}
+
+// Watch a single key for modifications
+func (s *MockStore) Watch(key string, stopCh <-chan struct{}) (<-chan *store.KVPair, error) {
+ return nil, ErrNotImplmented
+}
+
+// WatchTree triggers a watch on a range of values at "directory"
+func (s *MockStore) WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*store.KVPair, error) {
+ return nil, ErrNotImplmented
+}
+
+// NewLock exposed
+func (s *MockStore) NewLock(key string, options *store.LockOptions) (store.Locker, error) {
+ return nil, ErrNotImplmented
+}
+
+// AtomicPut put a value at "key" if the key has not been
+// modified in the meantime, throws an error if this is the case
+func (s *MockStore) AtomicPut(key string, newValue []byte, previous *store.KVPair, options *store.WriteOptions) (bool, *store.KVPair, error) {
+ mData := s.db[key]
+
+ if previous == nil {
+ if mData != nil {
+ return false, nil, types.BadRequestErrorf("atomic put failed because key exists")
+ } // Else OK.
+ } else {
+ if mData == nil {
+ return false, nil, types.BadRequestErrorf("atomic put failed because key exists")
+ }
+ if mData != nil && mData.Index != previous.LastIndex {
+ return false, nil, types.BadRequestErrorf("atomic put failed due to mismatched Index")
+ } // Else OK.
+ }
+ err := s.Put(key, newValue, nil)
+ if err != nil {
+ return false, nil, err
+ }
+ return true, &store.KVPair{Key: key, Value: newValue, LastIndex: s.db[key].Index}, nil
+}
+
+// AtomicDelete deletes a value at "key" if the key has not
+// been modified in the meantime, throws an error if this is the case
+func (s *MockStore) AtomicDelete(key string, previous *store.KVPair) (bool, error) {
+ mData := s.db[key]
+ if mData != nil && mData.Index != previous.LastIndex {
+ return false, types.BadRequestErrorf("atomic delete failed due to mismatched Index")
+ }
+ return true, s.Delete(key)
+}
+
+// Close closes the client connection
+func (s *MockStore) Close() {
+ return
+}
diff --git a/vendor/github.com/docker/libnetwork/default_gateway.go b/vendor/github.com/docker/libnetwork/default_gateway.go
new file mode 100644
index 0000000..bf15924
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/default_gateway.go
@@ -0,0 +1,201 @@
+package libnetwork
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ gwEPlen = 12
+)
+
+var procGwNetwork = make(chan (bool), 1)
+
+/*
+ libnetwork creates a bridge network "docker_gw_bridge" for providing
+ default gateway for the containers if none of the container's endpoints
+ have GW set by the driver. ICC is set to false for the GW_bridge network.
+
+ If a driver can't provide external connectivity it can choose to not set
+ the GW IP for the endpoint.
+
+ endpoint on the GW_bridge network is managed dynamically by libnetwork.
+ ie:
+ - its created when an endpoint without GW joins the container
+ - its deleted when an endpoint with GW joins the container
+*/
+
+func (sb *sandbox) setupDefaultGW() error {
+
+ // check if the container already has a GW endpoint
+ if ep := sb.getEndpointInGWNetwork(); ep != nil {
+ return nil
+ }
+
+ c := sb.controller
+
+ // Look for default gw network. In case of error (includes not found),
+ // retry and create it if needed in a serialized execution.
+ n, err := c.NetworkByName(libnGWNetwork)
+ if err != nil {
+ if n, err = c.defaultGwNetwork(); err != nil {
+ return err
+ }
+ }
+
+ createOptions := []EndpointOption{CreateOptionAnonymous()}
+
+ eplen := gwEPlen
+ if len(sb.containerID) < gwEPlen {
+ eplen = len(sb.containerID)
+ }
+
+ sbLabels := sb.Labels()
+
+ if sbLabels[netlabel.PortMap] != nil {
+ createOptions = append(createOptions, CreateOptionPortMapping(sbLabels[netlabel.PortMap].([]types.PortBinding)))
+ }
+
+ if sbLabels[netlabel.ExposedPorts] != nil {
+ createOptions = append(createOptions, CreateOptionExposedPorts(sbLabels[netlabel.ExposedPorts].([]types.TransportPort)))
+ }
+
+ epOption := getPlatformOption()
+ if epOption != nil {
+ createOptions = append(createOptions, epOption)
+ }
+
+ newEp, err := n.CreateEndpoint("gateway_"+sb.containerID[0:eplen], createOptions...)
+ if err != nil {
+ return fmt.Errorf("container %s: endpoint create on GW Network failed: %v", sb.containerID, err)
+ }
+
+ defer func() {
+ if err != nil {
+ if err2 := newEp.Delete(true); err2 != nil {
+ logrus.Warnf("Failed to remove gw endpoint for container %s after failing to join the gateway network: %v",
+ sb.containerID, err2)
+ }
+ }
+ }()
+
+ epLocal := newEp.(*endpoint)
+
+ if err = epLocal.sbJoin(sb); err != nil {
+ return fmt.Errorf("container %s: endpoint join on GW Network failed: %v", sb.containerID, err)
+ }
+
+ return nil
+}
+
+// If present, detach and remove the endpoint connecting the sandbox to the default gw network.
+func (sb *sandbox) clearDefaultGW() error {
+ var ep *endpoint
+
+ if ep = sb.getEndpointInGWNetwork(); ep == nil {
+ return nil
+ }
+ if err := ep.sbLeave(sb, false); err != nil {
+ return fmt.Errorf("container %s: endpoint leaving GW Network failed: %v", sb.containerID, err)
+ }
+ if err := ep.Delete(false); err != nil {
+ return fmt.Errorf("container %s: deleting endpoint on GW Network failed: %v", sb.containerID, err)
+ }
+ return nil
+}
+
+// Evaluate whether the sandbox requires a default gateway based
+// on the endpoints to which it is connected. It does not account
+// for the default gateway network endpoint.
+
+func (sb *sandbox) needDefaultGW() bool {
+ var needGW bool
+
+ for _, ep := range sb.getConnectedEndpoints() {
+ if ep.endpointInGWNetwork() {
+ continue
+ }
+ if ep.getNetwork().Type() == "null" || ep.getNetwork().Type() == "host" {
+ continue
+ }
+ if ep.getNetwork().Internal() {
+ continue
+ }
+ // During stale sandbox cleanup, joinInfo may be nil
+ if ep.joinInfo != nil && ep.joinInfo.disableGatewayService {
+ continue
+ }
+ // TODO v6 needs to be handled.
+ if len(ep.Gateway()) > 0 {
+ return false
+ }
+ for _, r := range ep.StaticRoutes() {
+ if r.Destination != nil && r.Destination.String() == "0.0.0.0/0" {
+ return false
+ }
+ }
+ needGW = true
+ }
+
+ return needGW
+}
+
+func (sb *sandbox) getEndpointInGWNetwork() *endpoint {
+ for _, ep := range sb.getConnectedEndpoints() {
+ if ep.getNetwork().name == libnGWNetwork && strings.HasPrefix(ep.Name(), "gateway_") {
+ return ep
+ }
+ }
+ return nil
+}
+
+func (ep *endpoint) endpointInGWNetwork() bool {
+ if ep.getNetwork().name == libnGWNetwork && strings.HasPrefix(ep.Name(), "gateway_") {
+ return true
+ }
+ return false
+}
+
+func (sb *sandbox) getEPwithoutGateway() *endpoint {
+ for _, ep := range sb.getConnectedEndpoints() {
+ if ep.getNetwork().Type() == "null" || ep.getNetwork().Type() == "host" {
+ continue
+ }
+ if len(ep.Gateway()) == 0 {
+ return ep
+ }
+ }
+ return nil
+}
+
+// Looks for the default gw network and creates it if not there.
+// Parallel executions are serialized.
+func (c *controller) defaultGwNetwork() (Network, error) {
+ procGwNetwork <- true
+ defer func() { <-procGwNetwork }()
+
+ n, err := c.NetworkByName(libnGWNetwork)
+ if err != nil {
+ if _, ok := err.(types.NotFoundError); ok {
+ n, err = c.createGWNetwork()
+ }
+ }
+ return n, err
+}
+
+// Returns the endpoint which is providing external connectivity to the sandbox
+func (sb *sandbox) getGatewayEndpoint() *endpoint {
+ for _, ep := range sb.getConnectedEndpoints() {
+ if ep.getNetwork().Type() == "null" || ep.getNetwork().Type() == "host" {
+ continue
+ }
+ if len(ep.Gateway()) != 0 {
+ return ep
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/default_gateway_freebsd.go b/vendor/github.com/docker/libnetwork/default_gateway_freebsd.go
new file mode 100644
index 0000000..dc4b1bd
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/default_gateway_freebsd.go
@@ -0,0 +1,13 @@
+package libnetwork
+
+import "github.com/docker/libnetwork/types"
+
+const libnGWNetwork = "docker_gwbridge"
+
+func getPlatformOption() EndpointOption {
+ return nil
+}
+
+func (c *controller) createGWNetwork() (Network, error) {
+ return nil, types.NotImplementedErrorf("default gateway functionality is not implemented in freebsd")
+}
diff --git a/vendor/github.com/docker/libnetwork/default_gateway_linux.go b/vendor/github.com/docker/libnetwork/default_gateway_linux.go
new file mode 100644
index 0000000..60df856
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/default_gateway_linux.go
@@ -0,0 +1,32 @@
+package libnetwork
+
+import (
+ "fmt"
+ "strconv"
+
+ "github.com/docker/libnetwork/drivers/bridge"
+)
+
+const libnGWNetwork = "docker_gwbridge"
+
+func getPlatformOption() EndpointOption {
+ return nil
+}
+
+func (c *controller) createGWNetwork() (Network, error) {
+ netOption := map[string]string{
+ bridge.BridgeName: libnGWNetwork,
+ bridge.EnableICC: strconv.FormatBool(false),
+ bridge.EnableIPMasquerade: strconv.FormatBool(true),
+ }
+
+ n, err := c.NewNetwork("bridge", libnGWNetwork, "",
+ NetworkOptionDriverOpts(netOption),
+ NetworkOptionEnableIPv6(false),
+ )
+
+ if err != nil {
+ return nil, fmt.Errorf("error creating external connectivity network: %v", err)
+ }
+ return n, err
+}
diff --git a/vendor/github.com/docker/libnetwork/default_gateway_solaris.go b/vendor/github.com/docker/libnetwork/default_gateway_solaris.go
new file mode 100644
index 0000000..8d86a66
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/default_gateway_solaris.go
@@ -0,0 +1,32 @@
+package libnetwork
+
+import (
+ "fmt"
+ "strconv"
+
+ "github.com/docker/libnetwork/drivers/solaris/bridge"
+)
+
+const libnGWNetwork = "docker_gwbridge"
+
+func getPlatformOption() EndpointOption {
+ return nil
+}
+
+func (c *controller) createGWNetwork() (Network, error) {
+ netOption := map[string]string{
+ bridge.BridgeName: libnGWNetwork,
+ bridge.EnableICC: strconv.FormatBool(false),
+ bridge.EnableIPMasquerade: strconv.FormatBool(true),
+ }
+
+ n, err := c.NewNetwork("bridge", libnGWNetwork, "",
+ NetworkOptionDriverOpts(netOption),
+ NetworkOptionEnableIPv6(false),
+ )
+
+ if err != nil {
+ return nil, fmt.Errorf("error creating external connectivity network: %v", err)
+ }
+ return n, err
+}
diff --git a/vendor/github.com/docker/libnetwork/default_gateway_windows.go b/vendor/github.com/docker/libnetwork/default_gateway_windows.go
new file mode 100644
index 0000000..f4ba198
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/default_gateway_windows.go
@@ -0,0 +1,22 @@
+package libnetwork
+
+import (
+ windriver "github.com/docker/libnetwork/drivers/windows"
+ "github.com/docker/libnetwork/options"
+ "github.com/docker/libnetwork/types"
+)
+
+const libnGWNetwork = "nat"
+
+func getPlatformOption() EndpointOption {
+
+ epOption := options.Generic{
+ windriver.DisableICC: true,
+ windriver.DisableDNS: true,
+ }
+ return EndpointOptionGeneric(epOption)
+}
+
+func (c *controller) createGWNetwork() (Network, error) {
+ return nil, types.NotImplementedErrorf("default gateway functionality is not implemented in windows")
+}
diff --git a/vendor/github.com/docker/libnetwork/discoverapi/discoverapi.go b/vendor/github.com/docker/libnetwork/discoverapi/discoverapi.go
new file mode 100644
index 0000000..7ac3615
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/discoverapi/discoverapi.go
@@ -0,0 +1,60 @@
+package discoverapi
+
+// Discover is an interface to be implemented by the component interested in receiving discover events
+// like new node joining the cluster or datastore updates
+type Discover interface {
+ // DiscoverNew is a notification for a new discovery event, Example:a new node joining a cluster
+ DiscoverNew(dType DiscoveryType, data interface{}) error
+
+ // DiscoverDelete is a notification for a discovery delete event, Example:a node leaving a cluster
+ DiscoverDelete(dType DiscoveryType, data interface{}) error
+}
+
+// DiscoveryType represents the type of discovery element the DiscoverNew function is invoked on
+type DiscoveryType int
+
+const (
+ // NodeDiscovery represents Node join/leave events provided by discovery
+ NodeDiscovery = iota + 1
+ // DatastoreConfig represents an add/remove datastore event
+ DatastoreConfig
+ // EncryptionKeysConfig represents the initial key(s) for performing datapath encryption
+ EncryptionKeysConfig
+ // EncryptionKeysUpdate represents an update to the datapath encryption key(s)
+ EncryptionKeysUpdate
+)
+
+// NodeDiscoveryData represents the structure backing the node discovery data json string
+type NodeDiscoveryData struct {
+ Address string
+ BindAddress string
+ Self bool
+}
+
+// DatastoreConfigData is the data for the datastore update event message
+type DatastoreConfigData struct {
+ Scope string
+ Provider string
+ Address string
+ Config interface{}
+}
+
+// DriverEncryptionConfig contains the initial datapath encryption key(s)
+// Key in first position is the primary key, the one to be used in tx.
+// Original key and tag types are []byte and uint64
+type DriverEncryptionConfig struct {
+ Keys [][]byte
+ Tags []uint64
+}
+
+// DriverEncryptionUpdate carries an update to the encryption key(s) as:
+// a new key and/or set a primary key and/or a removal of an existing key.
+// Original key and tag types are []byte and uint64
+type DriverEncryptionUpdate struct {
+ Key []byte
+ Tag uint64
+ Primary []byte
+ PrimaryTag uint64
+ Prune []byte
+ PruneTag uint64
+}
diff --git a/vendor/github.com/docker/libnetwork/driverapi/driverapi.go b/vendor/github.com/docker/libnetwork/driverapi/driverapi.go
new file mode 100644
index 0000000..48a14ae
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/driverapi/driverapi.go
@@ -0,0 +1,213 @@
+package driverapi
+
+import (
+ "net"
+
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/libnetwork/discoverapi"
+)
+
+// NetworkPluginEndpointType represents the Endpoint Type used by Plugin system
+const NetworkPluginEndpointType = "NetworkDriver"
+
+// Driver is an interface that every plugin driver needs to implement.
+type Driver interface {
+ discoverapi.Discover
+
+ // NetworkAllocate invokes the driver method to allocate network
+ // specific resources passing network id and network specific config.
+ // It returns a key,value pair of network specific driver allocations
+ // to the caller.
+ NetworkAllocate(nid string, options map[string]string, ipV4Data, ipV6Data []IPAMData) (map[string]string, error)
+
+ // NetworkFree invokes the driver method to free network specific resources
+ // associated with a given network id.
+ NetworkFree(nid string) error
+
+ // CreateNetwork invokes the driver method to create a network
+ // passing the network id and network specific config. The
+ // config mechanism will eventually be replaced with labels
+ // which are yet to be introduced. The driver can return a
+ // list of table names for which it is interested in receiving
+ // notification when a CRUD operation is performed on any
+ // entry in that table. This will be ignored for local scope
+ // drivers.
+ CreateNetwork(nid string, options map[string]interface{}, nInfo NetworkInfo, ipV4Data, ipV6Data []IPAMData) error
+
+ // DeleteNetwork invokes the driver method to delete network passing
+ // the network id.
+ DeleteNetwork(nid string) error
+
+ // CreateEndpoint invokes the driver method to create an endpoint
+ // passing the network id, endpoint id endpoint information and driver
+ // specific config. The endpoint information can be either consumed by
+ // the driver or populated by the driver. The config mechanism will
+ // eventually be replaced with labels which are yet to be introduced.
+ CreateEndpoint(nid, eid string, ifInfo InterfaceInfo, options map[string]interface{}) error
+
+ // DeleteEndpoint invokes the driver method to delete an endpoint
+ // passing the network id and endpoint id.
+ DeleteEndpoint(nid, eid string) error
+
+ // EndpointOperInfo retrieves from the driver the operational data related to the specified endpoint
+ EndpointOperInfo(nid, eid string) (map[string]interface{}, error)
+
+ // Join method is invoked when a Sandbox is attached to an endpoint.
+ Join(nid, eid string, sboxKey string, jinfo JoinInfo, options map[string]interface{}) error
+
+ // Leave method is invoked when a Sandbox detaches from an endpoint.
+ Leave(nid, eid string) error
+
+ // ProgramExternalConnectivity invokes the driver method which does the necessary
+ // programming to allow the external connectivity dictated by the passed options
+ ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error
+
+ // RevokeExternalConnectivity asks the driver to remove any external connectivity
+ // programming that was done so far
+ RevokeExternalConnectivity(nid, eid string) error
+
+ // EventNotify notifies the driver when a CRUD operation has
+ // happened on a table of its interest as soon as this node
+ // receives such an event in the gossip layer. This method is
+ // only invoked for the global scope driver.
+ EventNotify(event EventType, nid string, tableName string, key string, value []byte)
+
+ // DecodeTableEntry passes the driver a key, value pair from table it registered
+ // with libnetwork. Driver should return {object ID, map[string]string} tuple.
+ // If DecodeTableEntry is called for a table associated with NetworkObject or
+ // EndpointObject the return object ID should be the network id or endppoint id
+ // associated with that entry. map should have information about the object that
+ // can be presented to the user.
+ // For exampe: overlay driver returns the VTEP IP of the host that has the endpoint
+ // which is shown in 'network inspect --verbose'
+ DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string)
+
+ // Type returns the type of this driver, the network type this driver manages
+ Type() string
+
+ // IsBuiltIn returns true if it is a built-in driver
+ IsBuiltIn() bool
+}
+
+// NetworkInfo provides a go interface for drivers to provide network
+// specific information to libnetwork.
+type NetworkInfo interface {
+ // TableEventRegister registers driver interest in a given
+ // table name.
+ TableEventRegister(tableName string, objType ObjectType) error
+}
+
+// InterfaceInfo provides a go interface for drivers to retrive
+// network information to interface resources.
+type InterfaceInfo interface {
+ // SetMacAddress allows the driver to set the mac address to the endpoint interface
+ // during the call to CreateEndpoint, if the mac address is not already set.
+ SetMacAddress(mac net.HardwareAddr) error
+
+ // SetIPAddress allows the driver to set the ip address to the endpoint interface
+ // during the call to CreateEndpoint, if the address is not already set.
+ // The API is to be used to assign both the IPv4 and IPv6 address types.
+ SetIPAddress(ip *net.IPNet) error
+
+ // MacAddress returns the MAC address.
+ MacAddress() net.HardwareAddr
+
+ // Address returns the IPv4 address.
+ Address() *net.IPNet
+
+ // AddressIPv6 returns the IPv6 address.
+ AddressIPv6() *net.IPNet
+}
+
+// InterfaceNameInfo provides a go interface for the drivers to assign names
+// to interfaces.
+type InterfaceNameInfo interface {
+ // SetNames method assigns the srcName and dstPrefix for the interface.
+ SetNames(srcName, dstPrefix string) error
+}
+
+// JoinInfo represents a set of resources that the driver has the ability to provide during
+// join time.
+type JoinInfo interface {
+ // InterfaceName returns an InterfaceNameInfo go interface to facilitate
+ // setting the names for the interface.
+ InterfaceName() InterfaceNameInfo
+
+ // SetGateway sets the default IPv4 gateway when a container joins the endpoint.
+ SetGateway(net.IP) error
+
+ // SetGatewayIPv6 sets the default IPv6 gateway when a container joins the endpoint.
+ SetGatewayIPv6(net.IP) error
+
+ // AddStaticRoute adds a route to the sandbox.
+ // It may be used in addition to or instead of a default gateway (as above).
+ AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP) error
+
+ // DisableGatewayService tells libnetwork not to provide Default GW for the container
+ DisableGatewayService()
+
+ // AddTableEntry adds a table entry to the gossip layer
+ // passing the table name, key and an opaque value.
+ AddTableEntry(tableName string, key string, value []byte) error
+}
+
+// DriverCallback provides a Callback interface for Drivers into LibNetwork
+type DriverCallback interface {
+ // GetPluginGetter returns the pluginv2 getter.
+ GetPluginGetter() plugingetter.PluginGetter
+ // RegisterDriver provides a way for Remote drivers to dynamically register new NetworkType and associate with a driver instance
+ RegisterDriver(name string, driver Driver, capability Capability) error
+}
+
+// Capability represents the high level capabilities of the drivers which libnetwork can make use of
+type Capability struct {
+ DataScope string
+ ConnectivityScope string
+}
+
+// IPAMData represents the per-network ip related
+// operational information libnetwork will send
+// to the network driver during CreateNetwork()
+type IPAMData struct {
+ AddressSpace string
+ Pool *net.IPNet
+ Gateway *net.IPNet
+ AuxAddresses map[string]*net.IPNet
+}
+
+// EventType defines a type for the CRUD event
+type EventType uint8
+
+const (
+ // Create event is generated when a table entry is created,
+ Create EventType = 1 + iota
+ // Update event is generated when a table entry is updated.
+ Update
+ // Delete event is generated when a table entry is deleted.
+ Delete
+)
+
+// ObjectType represents the type of object driver wants to store in libnetwork's networkDB
+type ObjectType int
+
+const (
+ // EndpointObject should be set for libnetwork endpoint object related data
+ EndpointObject ObjectType = 1 + iota
+ // NetworkObject should be set for libnetwork network object related data
+ NetworkObject
+ // OpaqueObject is for driver specific data with no corresponding libnetwork object
+ OpaqueObject
+)
+
+// IsValidType validates the passed in type against the valid object types
+func IsValidType(objType ObjectType) bool {
+ switch objType {
+ case EndpointObject:
+ fallthrough
+ case NetworkObject:
+ fallthrough
+ case OpaqueObject:
+ return true
+ }
+ return false
+}
diff --git a/vendor/github.com/docker/libnetwork/driverapi/errors.go b/vendor/github.com/docker/libnetwork/driverapi/errors.go
new file mode 100644
index 0000000..041ef41
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/driverapi/errors.go
@@ -0,0 +1,56 @@
+package driverapi
+
+import (
+ "fmt"
+)
+
+// ErrNoNetwork is returned if no network with the specified id exists
+type ErrNoNetwork string
+
+func (enn ErrNoNetwork) Error() string {
+ return fmt.Sprintf("No network (%s) exists", string(enn))
+}
+
+// NotFound denotes the type of this error
+func (enn ErrNoNetwork) NotFound() {}
+
+// ErrEndpointExists is returned if more than one endpoint is added to the network
+type ErrEndpointExists string
+
+func (ee ErrEndpointExists) Error() string {
+ return fmt.Sprintf("Endpoint (%s) already exists (Only one endpoint allowed)", string(ee))
+}
+
+// Forbidden denotes the type of this error
+func (ee ErrEndpointExists) Forbidden() {}
+
+// ErrNotImplemented is returned when a Driver has not implemented an API yet
+type ErrNotImplemented struct{}
+
+func (eni *ErrNotImplemented) Error() string {
+ return "The API is not implemented yet"
+}
+
+// NotImplemented denotes the type of this error
+func (eni *ErrNotImplemented) NotImplemented() {}
+
+// ErrNoEndpoint is returned if no endpoint with the specified id exists
+type ErrNoEndpoint string
+
+func (ene ErrNoEndpoint) Error() string {
+ return fmt.Sprintf("No endpoint (%s) exists", string(ene))
+}
+
+// NotFound denotes the type of this error
+func (ene ErrNoEndpoint) NotFound() {}
+
+// ErrActiveRegistration represents an error when a driver is registered to a networkType that is previously registered
+type ErrActiveRegistration string
+
+// Error interface for ErrActiveRegistration
+func (ar ErrActiveRegistration) Error() string {
+ return fmt.Sprintf("Driver already registered for type %q", string(ar))
+}
+
+// Forbidden denotes the type of this error
+func (ar ErrActiveRegistration) Forbidden() {}
diff --git a/vendor/github.com/docker/libnetwork/driverapi/ipamdata.go b/vendor/github.com/docker/libnetwork/driverapi/ipamdata.go
new file mode 100644
index 0000000..fc1c2af
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/driverapi/ipamdata.go
@@ -0,0 +1,103 @@
+package driverapi
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+
+ "github.com/docker/libnetwork/types"
+)
+
+// MarshalJSON encodes IPAMData into json message
+func (i *IPAMData) MarshalJSON() ([]byte, error) {
+ m := map[string]interface{}{}
+ m["AddressSpace"] = i.AddressSpace
+ if i.Pool != nil {
+ m["Pool"] = i.Pool.String()
+ }
+ if i.Gateway != nil {
+ m["Gateway"] = i.Gateway.String()
+ }
+ if i.AuxAddresses != nil {
+ am := make(map[string]string, len(i.AuxAddresses))
+ for k, v := range i.AuxAddresses {
+ am[k] = v.String()
+ }
+ m["AuxAddresses"] = am
+ }
+ return json.Marshal(m)
+}
+
+// UnmarshalJSON decodes a json message into IPAMData
+func (i *IPAMData) UnmarshalJSON(data []byte) error {
+ var (
+ m map[string]interface{}
+ err error
+ )
+ if err := json.Unmarshal(data, &m); err != nil {
+ return err
+ }
+ i.AddressSpace = m["AddressSpace"].(string)
+ if v, ok := m["Pool"]; ok {
+ if i.Pool, err = types.ParseCIDR(v.(string)); err != nil {
+ return err
+ }
+ }
+ if v, ok := m["Gateway"]; ok {
+ if i.Gateway, err = types.ParseCIDR(v.(string)); err != nil {
+ return err
+ }
+ }
+ if v, ok := m["AuxAddresses"]; ok {
+ b, _ := json.Marshal(v)
+ var am map[string]string
+ if err = json.Unmarshal(b, &am); err != nil {
+ return err
+ }
+ i.AuxAddresses = make(map[string]*net.IPNet, len(am))
+ for k, v := range am {
+ if i.AuxAddresses[k], err = types.ParseCIDR(v); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// Validate checks whether the IPAMData structure contains congruent data
+func (i *IPAMData) Validate() error {
+ var isV6 bool
+ if i.Pool == nil {
+ return types.BadRequestErrorf("invalid pool")
+ }
+ if i.Gateway == nil {
+ return types.BadRequestErrorf("invalid gateway address")
+ }
+ isV6 = i.IsV6()
+ if isV6 && i.Gateway.IP.To4() != nil || !isV6 && i.Gateway.IP.To4() == nil {
+ return types.BadRequestErrorf("incongruent ip versions for pool and gateway")
+ }
+ for k, sip := range i.AuxAddresses {
+ if isV6 && sip.IP.To4() != nil || !isV6 && sip.IP.To4() == nil {
+ return types.BadRequestErrorf("incongruent ip versions for pool and secondary ip address %s", k)
+ }
+ }
+ if !i.Pool.Contains(i.Gateway.IP) {
+ return types.BadRequestErrorf("invalid gateway address (%s) does not belong to the pool (%s)", i.Gateway, i.Pool)
+ }
+ for k, sip := range i.AuxAddresses {
+ if !i.Pool.Contains(sip.IP) {
+ return types.BadRequestErrorf("invalid secondary address %s (%s) does not belong to the pool (%s)", k, i.Gateway, i.Pool)
+ }
+ }
+ return nil
+}
+
+// IsV6 returns whether this is an IPv6 IPAMData structure
+func (i *IPAMData) IsV6() bool {
+ return nil == i.Pool.IP.To4()
+}
+
+func (i *IPAMData) String() string {
+ return fmt.Sprintf("AddressSpace: %s\nPool: %v\nGateway: %v\nAddresses: %v", i.AddressSpace, i.Pool, i.Gateway, i.AuxAddresses)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/bridge.go b/vendor/github.com/docker/libnetwork/drivers/bridge/bridge.go
new file mode 100644
index 0000000..dd79f04
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/bridge.go
@@ -0,0 +1,1531 @@
+package bridge
+
+import (
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "sync"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/iptables"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/netutils"
+ "github.com/docker/libnetwork/ns"
+ "github.com/docker/libnetwork/options"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/portmapper"
+ "github.com/docker/libnetwork/types"
+ "github.com/vishvananda/netlink"
+)
+
+const (
+ networkType = "bridge"
+ vethPrefix = "veth"
+ vethLen = 7
+ defaultContainerVethPrefix = "eth"
+ maxAllocatePortAttempts = 10
+)
+
+const (
+ // DefaultGatewayV4AuxKey represents the default-gateway configured by the user
+ DefaultGatewayV4AuxKey = "DefaultGatewayIPv4"
+ // DefaultGatewayV6AuxKey represents the ipv6 default-gateway configured by the user
+ DefaultGatewayV6AuxKey = "DefaultGatewayIPv6"
+)
+
+type iptableCleanFunc func() error
+type iptablesCleanFuncs []iptableCleanFunc
+
+// configuration info for the "bridge" driver.
+type configuration struct {
+ EnableIPForwarding bool
+ EnableIPTables bool
+ EnableUserlandProxy bool
+ UserlandProxyPath string
+}
+
+// networkConfiguration for network specific configuration
+type networkConfiguration struct {
+ ID string
+ BridgeName string
+ EnableIPv6 bool
+ EnableIPMasquerade bool
+ EnableICC bool
+ Mtu int
+ DefaultBindingIP net.IP
+ DefaultBridge bool
+ ContainerIfacePrefix string
+ // Internal fields set after ipam data parsing
+ AddressIPv4 *net.IPNet
+ AddressIPv6 *net.IPNet
+ DefaultGatewayIPv4 net.IP
+ DefaultGatewayIPv6 net.IP
+ dbIndex uint64
+ dbExists bool
+ Internal bool
+
+ BridgeIfaceCreator ifaceCreator
+}
+
+// ifaceCreator represents how the bridge interface was created
+type ifaceCreator int8
+
+const (
+ ifaceCreatorUnknown ifaceCreator = iota
+ ifaceCreatedByLibnetwork
+ ifaceCreatedByUser
+)
+
+// endpointConfiguration represents the user specified configuration for the sandbox endpoint
+type endpointConfiguration struct {
+ MacAddress net.HardwareAddr
+}
+
+// containerConfiguration represents the user specified configuration for a container
+type containerConfiguration struct {
+ ParentEndpoints []string
+ ChildEndpoints []string
+}
+
+// cnnectivityConfiguration represents the user specified configuration regarding the external connectivity
+type connectivityConfiguration struct {
+ PortBindings []types.PortBinding
+ ExposedPorts []types.TransportPort
+}
+
+type bridgeEndpoint struct {
+ id string
+ nid string
+ srcName string
+ addr *net.IPNet
+ addrv6 *net.IPNet
+ macAddress net.HardwareAddr
+ config *endpointConfiguration // User specified parameters
+ containerConfig *containerConfiguration
+ extConnConfig *connectivityConfiguration
+ portMapping []types.PortBinding // Operation port bindings
+ dbIndex uint64
+ dbExists bool
+}
+
+type bridgeNetwork struct {
+ id string
+ bridge *bridgeInterface // The bridge's L3 interface
+ config *networkConfiguration
+ endpoints map[string]*bridgeEndpoint // key: endpoint id
+ portMapper *portmapper.PortMapper
+ driver *driver // The network's driver
+ iptCleanFuncs iptablesCleanFuncs
+ sync.Mutex
+}
+
+type driver struct {
+ config *configuration
+ network *bridgeNetwork
+ natChain *iptables.ChainInfo
+ filterChain *iptables.ChainInfo
+ isolationChain *iptables.ChainInfo
+ networks map[string]*bridgeNetwork
+ store datastore.DataStore
+ nlh *netlink.Handle
+ sync.Mutex
+}
+
+// New constructs a new bridge driver
+func newDriver() *driver {
+ return &driver{networks: map[string]*bridgeNetwork{}, config: &configuration{}}
+}
+
+// Init registers a new instance of bridge driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ d := newDriver()
+ if err := d.configure(config); err != nil {
+ return err
+ }
+
+ c := driverapi.Capability{
+ DataScope: datastore.LocalScope,
+ ConnectivityScope: datastore.LocalScope,
+ }
+ return dc.RegisterDriver(networkType, d, c)
+}
+
+// Validate performs a static validation on the network configuration parameters.
+// Whatever can be assessed a priori before attempting any programming.
+func (c *networkConfiguration) Validate() error {
+ if c.Mtu < 0 {
+ return ErrInvalidMtu(c.Mtu)
+ }
+
+ // If bridge v4 subnet is specified
+ if c.AddressIPv4 != nil {
+ // If default gw is specified, it must be part of bridge subnet
+ if c.DefaultGatewayIPv4 != nil {
+ if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) {
+ return &ErrInvalidGateway{}
+ }
+ }
+ }
+
+ // If default v6 gw is specified, AddressIPv6 must be specified and gw must belong to AddressIPv6 subnet
+ if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil {
+ if c.AddressIPv6 == nil || !c.AddressIPv6.Contains(c.DefaultGatewayIPv6) {
+ return &ErrInvalidGateway{}
+ }
+ }
+ return nil
+}
+
+// Conflicts check if two NetworkConfiguration objects overlap
+func (c *networkConfiguration) Conflicts(o *networkConfiguration) error {
+ if o == nil {
+ return errors.New("same configuration")
+ }
+
+ // Also empty, because only one network with empty name is allowed
+ if c.BridgeName == o.BridgeName {
+ return errors.New("networks have same bridge name")
+ }
+
+ // They must be in different subnets
+ if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) &&
+ (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) {
+ return errors.New("networks have overlapping IPv4")
+ }
+
+ // They must be in different v6 subnets
+ if (c.AddressIPv6 != nil && o.AddressIPv6 != nil) &&
+ (c.AddressIPv6.Contains(o.AddressIPv6.IP) || o.AddressIPv6.Contains(c.AddressIPv6.IP)) {
+ return errors.New("networks have overlapping IPv6")
+ }
+
+ return nil
+}
+
+func (c *networkConfiguration) fromLabels(labels map[string]string) error {
+ var err error
+ for label, value := range labels {
+ switch label {
+ case BridgeName:
+ c.BridgeName = value
+ case netlabel.DriverMTU:
+ if c.Mtu, err = strconv.Atoi(value); err != nil {
+ return parseErr(label, value, err.Error())
+ }
+ case netlabel.EnableIPv6:
+ if c.EnableIPv6, err = strconv.ParseBool(value); err != nil {
+ return parseErr(label, value, err.Error())
+ }
+ case EnableIPMasquerade:
+ if c.EnableIPMasquerade, err = strconv.ParseBool(value); err != nil {
+ return parseErr(label, value, err.Error())
+ }
+ case EnableICC:
+ if c.EnableICC, err = strconv.ParseBool(value); err != nil {
+ return parseErr(label, value, err.Error())
+ }
+ case DefaultBridge:
+ if c.DefaultBridge, err = strconv.ParseBool(value); err != nil {
+ return parseErr(label, value, err.Error())
+ }
+ case DefaultBindingIP:
+ if c.DefaultBindingIP = net.ParseIP(value); c.DefaultBindingIP == nil {
+ return parseErr(label, value, "nil ip")
+ }
+ case netlabel.ContainerIfacePrefix:
+ c.ContainerIfacePrefix = value
+ }
+ }
+
+ return nil
+}
+
+func parseErr(label, value, errString string) error {
+ return types.BadRequestErrorf("failed to parse %s value: %v (%s)", label, value, errString)
+}
+
+func (n *bridgeNetwork) registerIptCleanFunc(clean iptableCleanFunc) {
+ n.iptCleanFuncs = append(n.iptCleanFuncs, clean)
+}
+
+func (n *bridgeNetwork) getDriverChains() (*iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, error) {
+ n.Lock()
+ defer n.Unlock()
+
+ if n.driver == nil {
+ return nil, nil, nil, types.BadRequestErrorf("no driver found")
+ }
+
+ return n.driver.natChain, n.driver.filterChain, n.driver.isolationChain, nil
+}
+
+func (n *bridgeNetwork) getNetworkBridgeName() string {
+ n.Lock()
+ config := n.config
+ n.Unlock()
+
+ return config.BridgeName
+}
+
+func (n *bridgeNetwork) getEndpoint(eid string) (*bridgeEndpoint, error) {
+ n.Lock()
+ defer n.Unlock()
+
+ if eid == "" {
+ return nil, InvalidEndpointIDError(eid)
+ }
+
+ if ep, ok := n.endpoints[eid]; ok {
+ return ep, nil
+ }
+
+ return nil, nil
+}
+
+// Install/Removes the iptables rules needed to isolate this network
+// from each of the other networks
+func (n *bridgeNetwork) isolateNetwork(others []*bridgeNetwork, enable bool) error {
+ n.Lock()
+ thisConfig := n.config
+ n.Unlock()
+
+ if thisConfig.Internal {
+ return nil
+ }
+
+ // Install the rules to isolate this networks against each of the other networks
+ for _, o := range others {
+ o.Lock()
+ otherConfig := o.config
+ o.Unlock()
+
+ if otherConfig.Internal {
+ continue
+ }
+
+ if thisConfig.BridgeName != otherConfig.BridgeName {
+ if err := setINC(thisConfig.BridgeName, otherConfig.BridgeName, enable); err != nil {
+ return err
+ }
+ }
+ }
+
+ return nil
+}
+
+// Checks whether this network's configuration for the network with this id conflicts with any of the passed networks
+func (c *networkConfiguration) conflictsWithNetworks(id string, others []*bridgeNetwork) error {
+ for _, nw := range others {
+
+ nw.Lock()
+ nwID := nw.id
+ nwConfig := nw.config
+ nwBridge := nw.bridge
+ nw.Unlock()
+
+ if nwID == id {
+ continue
+ }
+ // Verify the name (which may have been set by newInterface()) does not conflict with
+ // existing bridge interfaces. Ironically the system chosen name gets stored in the config...
+ // Basically we are checking if the two original configs were both empty.
+ if nwConfig.BridgeName == c.BridgeName {
+ return types.ForbiddenErrorf("conflicts with network %s (%s) by bridge name", nwID, nwConfig.BridgeName)
+ }
+ // If this network config specifies the AddressIPv4, we need
+ // to make sure it does not conflict with any previously allocated
+ // bridges. This could not be completely caught by the config conflict
+ // check, because networks which config does not specify the AddressIPv4
+ // get their address and subnet selected by the driver (see electBridgeIPv4())
+ if c.AddressIPv4 != nil && nwBridge.bridgeIPv4 != nil {
+ if nwBridge.bridgeIPv4.Contains(c.AddressIPv4.IP) ||
+ c.AddressIPv4.Contains(nwBridge.bridgeIPv4.IP) {
+ return types.ForbiddenErrorf("conflicts with network %s (%s) by ip network", nwID, nwConfig.BridgeName)
+ }
+ }
+ }
+
+ return nil
+}
+
+func (d *driver) configure(option map[string]interface{}) error {
+ var (
+ config *configuration
+ err error
+ natChain *iptables.ChainInfo
+ filterChain *iptables.ChainInfo
+ isolationChain *iptables.ChainInfo
+ )
+
+ genericData, ok := option[netlabel.GenericData]
+ if !ok || genericData == nil {
+ return nil
+ }
+
+ switch opt := genericData.(type) {
+ case options.Generic:
+ opaqueConfig, err := options.GenerateFromModel(opt, &configuration{})
+ if err != nil {
+ return err
+ }
+ config = opaqueConfig.(*configuration)
+ case *configuration:
+ config = opt
+ default:
+ return &ErrInvalidDriverConfig{}
+ }
+
+ if config.EnableIPTables {
+ if _, err := os.Stat("/proc/sys/net/bridge"); err != nil {
+ if out, err := exec.Command("modprobe", "-va", "bridge", "br_netfilter").CombinedOutput(); err != nil {
+ logrus.Warnf("Running modprobe bridge br_netfilter failed with message: %s, error: %v", out, err)
+ }
+ }
+ removeIPChains()
+ natChain, filterChain, isolationChain, err = setupIPChains(config)
+ if err != nil {
+ return err
+ }
+ // Make sure on firewall reload, first thing being re-played is chains creation
+ iptables.OnReloaded(func() { logrus.Debugf("Recreating iptables chains on firewall reload"); setupIPChains(config) })
+ }
+
+ if config.EnableIPForwarding {
+ err = setupIPForwarding(config.EnableIPTables)
+ if err != nil {
+ logrus.Warn(err)
+ return err
+ }
+ }
+
+ d.Lock()
+ d.natChain = natChain
+ d.filterChain = filterChain
+ d.isolationChain = isolationChain
+ d.config = config
+ d.Unlock()
+
+ err = d.initStore(option)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (d *driver) getNetwork(id string) (*bridgeNetwork, error) {
+ d.Lock()
+ defer d.Unlock()
+
+ if id == "" {
+ return nil, types.BadRequestErrorf("invalid network id: %s", id)
+ }
+
+ if nw, ok := d.networks[id]; ok {
+ return nw, nil
+ }
+
+ return nil, types.NotFoundErrorf("network not found: %s", id)
+}
+
+func parseNetworkGenericOptions(data interface{}) (*networkConfiguration, error) {
+ var (
+ err error
+ config *networkConfiguration
+ )
+
+ switch opt := data.(type) {
+ case *networkConfiguration:
+ config = opt
+ case map[string]string:
+ config = &networkConfiguration{
+ EnableICC: true,
+ EnableIPMasquerade: true,
+ }
+ err = config.fromLabels(opt)
+ case options.Generic:
+ var opaqueConfig interface{}
+ if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil {
+ config = opaqueConfig.(*networkConfiguration)
+ }
+ default:
+ err = types.BadRequestErrorf("do not recognize network configuration format: %T", opt)
+ }
+
+ return config, err
+}
+
+func (c *networkConfiguration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
+ if len(ipamV4Data) > 1 || len(ipamV6Data) > 1 {
+ return types.ForbiddenErrorf("bridge driver doesn't support multiple subnets")
+ }
+
+ if len(ipamV4Data) == 0 {
+ return types.BadRequestErrorf("bridge network %s requires ipv4 configuration", id)
+ }
+
+ if ipamV4Data[0].Gateway != nil {
+ c.AddressIPv4 = types.GetIPNetCopy(ipamV4Data[0].Gateway)
+ }
+
+ if gw, ok := ipamV4Data[0].AuxAddresses[DefaultGatewayV4AuxKey]; ok {
+ c.DefaultGatewayIPv4 = gw.IP
+ }
+
+ if len(ipamV6Data) > 0 {
+ c.AddressIPv6 = ipamV6Data[0].Pool
+
+ if ipamV6Data[0].Gateway != nil {
+ c.AddressIPv6 = types.GetIPNetCopy(ipamV6Data[0].Gateway)
+ }
+
+ if gw, ok := ipamV6Data[0].AuxAddresses[DefaultGatewayV6AuxKey]; ok {
+ c.DefaultGatewayIPv6 = gw.IP
+ }
+ }
+
+ return nil
+}
+
+func parseNetworkOptions(id string, option options.Generic) (*networkConfiguration, error) {
+ var (
+ err error
+ config = &networkConfiguration{}
+ )
+
+ // Parse generic label first, config will be re-assigned
+ if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
+ if config, err = parseNetworkGenericOptions(genData); err != nil {
+ return nil, err
+ }
+ }
+
+ // Process well-known labels next
+ if val, ok := option[netlabel.EnableIPv6]; ok {
+ config.EnableIPv6 = val.(bool)
+ }
+
+ if val, ok := option[netlabel.Internal]; ok {
+ if internal, ok := val.(bool); ok && internal {
+ config.Internal = true
+ }
+ }
+
+ // Finally validate the configuration
+ if err = config.Validate(); err != nil {
+ return nil, err
+ }
+
+ if config.BridgeName == "" && config.DefaultBridge == false {
+ config.BridgeName = "br-" + id[:12]
+ }
+
+ exists, err := bridgeInterfaceExists(config.BridgeName)
+ if err != nil {
+ return nil, err
+ }
+
+ if !exists {
+ config.BridgeIfaceCreator = ifaceCreatedByLibnetwork
+ } else {
+ config.BridgeIfaceCreator = ifaceCreatedByUser
+ }
+
+ config.ID = id
+ return config, nil
+}
+
+// Returns the non link-local IPv6 subnet for the containers attached to this bridge if found, nil otherwise
+func getV6Network(config *networkConfiguration, i *bridgeInterface) *net.IPNet {
+ if config.AddressIPv6 != nil {
+ return config.AddressIPv6
+ }
+ if i.bridgeIPv6 != nil && i.bridgeIPv6.IP != nil && !i.bridgeIPv6.IP.IsLinkLocalUnicast() {
+ return i.bridgeIPv6
+ }
+
+ return nil
+}
+
+// Return a slice of networks over which caller can iterate safely
+func (d *driver) getNetworks() []*bridgeNetwork {
+ d.Lock()
+ defer d.Unlock()
+
+ ls := make([]*bridgeNetwork, 0, len(d.networks))
+ for _, nw := range d.networks {
+ ls = append(ls, nw)
+ }
+ return ls
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+// Create a new network using bridge plugin
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
+ return types.BadRequestErrorf("ipv4 pool is empty")
+ }
+ // Sanity checks
+ d.Lock()
+ if _, ok := d.networks[id]; ok {
+ d.Unlock()
+ return types.ForbiddenErrorf("network %s exists", id)
+ }
+ d.Unlock()
+
+ // Parse and validate the config. It should not be conflict with existing networks' config
+ config, err := parseNetworkOptions(id, option)
+ if err != nil {
+ return err
+ }
+
+ err = config.processIPAM(id, ipV4Data, ipV6Data)
+ if err != nil {
+ return err
+ }
+
+ if err = d.createNetwork(config); err != nil {
+ return err
+ }
+
+ return d.storeUpdate(config)
+}
+
+func (d *driver) createNetwork(config *networkConfiguration) error {
+ var err error
+
+ defer osl.InitOSContext()()
+
+ networkList := d.getNetworks()
+ for i, nw := range networkList {
+ nw.Lock()
+ nwConfig := nw.config
+ nw.Unlock()
+ if err := nwConfig.Conflicts(config); err != nil {
+ if config.DefaultBridge {
+ // We encountered and identified a stale default network
+ // We must delete it as libnetwork is the source of thruth
+ // The default network being created must be the only one
+ // This can happen only from docker 1.12 on ward
+ logrus.Infof("Removing stale default bridge network %s (%s)", nwConfig.ID, nwConfig.BridgeName)
+ if err := d.DeleteNetwork(nwConfig.ID); err != nil {
+ logrus.Warnf("Failed to remove stale default network: %s (%s): %v. Will remove from store.", nwConfig.ID, nwConfig.BridgeName, err)
+ d.storeDelete(nwConfig)
+ }
+ networkList = append(networkList[:i], networkList[i+1:]...)
+ } else {
+ return types.ForbiddenErrorf("cannot create network %s (%s): conflicts with network %s (%s): %s",
+ config.ID, config.BridgeName, nwConfig.ID, nwConfig.BridgeName, err.Error())
+ }
+ }
+ }
+
+ // Create and set network handler in driver
+ network := &bridgeNetwork{
+ id: config.ID,
+ endpoints: make(map[string]*bridgeEndpoint),
+ config: config,
+ portMapper: portmapper.New(d.config.UserlandProxyPath),
+ driver: d,
+ }
+
+ d.Lock()
+ d.networks[config.ID] = network
+ d.Unlock()
+
+ // On failure make sure to reset driver network handler to nil
+ defer func() {
+ if err != nil {
+ d.Lock()
+ delete(d.networks, config.ID)
+ d.Unlock()
+ }
+ }()
+
+ // Initialize handle when needed
+ d.Lock()
+ if d.nlh == nil {
+ d.nlh = ns.NlHandle()
+ }
+ d.Unlock()
+
+ // Create or retrieve the bridge L3 interface
+ bridgeIface, err := newInterface(d.nlh, config)
+ if err != nil {
+ return err
+ }
+ network.bridge = bridgeIface
+
+ // Verify the network configuration does not conflict with previously installed
+ // networks. This step is needed now because driver might have now set the bridge
+ // name on this config struct. And because we need to check for possible address
+ // conflicts, so we need to check against operationa lnetworks.
+ if err = config.conflictsWithNetworks(config.ID, networkList); err != nil {
+ return err
+ }
+
+ setupNetworkIsolationRules := func(config *networkConfiguration, i *bridgeInterface) error {
+ if err := network.isolateNetwork(networkList, true); err != nil {
+ if err := network.isolateNetwork(networkList, false); err != nil {
+ logrus.Warnf("Failed on removing the inter-network iptables rules on cleanup: %v", err)
+ }
+ return err
+ }
+ network.registerIptCleanFunc(func() error {
+ nwList := d.getNetworks()
+ return network.isolateNetwork(nwList, false)
+ })
+ return nil
+ }
+
+ // Prepare the bridge setup configuration
+ bridgeSetup := newBridgeSetup(config, bridgeIface)
+
+ // If the bridge interface doesn't exist, we need to start the setup steps
+ // by creating a new device and assigning it an IPv4 address.
+ bridgeAlreadyExists := bridgeIface.exists()
+ if !bridgeAlreadyExists {
+ bridgeSetup.queueStep(setupDevice)
+ }
+
+ // Even if a bridge exists try to setup IPv4.
+ bridgeSetup.queueStep(setupBridgeIPv4)
+
+ enableIPv6Forwarding := d.config.EnableIPForwarding && config.AddressIPv6 != nil
+
+ // Conditionally queue setup steps depending on configuration values.
+ for _, step := range []struct {
+ Condition bool
+ Fn setupStep
+ }{
+ // Enable IPv6 on the bridge if required. We do this even for a
+ // previously existing bridge, as it may be here from a previous
+ // installation where IPv6 wasn't supported yet and needs to be
+ // assigned an IPv6 link-local address.
+ {config.EnableIPv6, setupBridgeIPv6},
+
+ // We ensure that the bridge has the expectedIPv4 and IPv6 addresses in
+ // the case of a previously existing device.
+ {bridgeAlreadyExists, setupVerifyAndReconcile},
+
+ // Enable IPv6 Forwarding
+ {enableIPv6Forwarding, setupIPv6Forwarding},
+
+ // Setup Loopback Adresses Routing
+ {!d.config.EnableUserlandProxy, setupLoopbackAdressesRouting},
+
+ // Setup IPTables.
+ {d.config.EnableIPTables, network.setupIPTables},
+
+ //We want to track firewalld configuration so that
+ //if it is started/reloaded, the rules can be applied correctly
+ {d.config.EnableIPTables, network.setupFirewalld},
+
+ // Setup DefaultGatewayIPv4
+ {config.DefaultGatewayIPv4 != nil, setupGatewayIPv4},
+
+ // Setup DefaultGatewayIPv6
+ {config.DefaultGatewayIPv6 != nil, setupGatewayIPv6},
+
+ // Add inter-network communication rules.
+ {d.config.EnableIPTables, setupNetworkIsolationRules},
+
+ //Configure bridge networking filtering if ICC is off and IP tables are enabled
+ {!config.EnableICC && d.config.EnableIPTables, setupBridgeNetFiltering},
+ } {
+ if step.Condition {
+ bridgeSetup.queueStep(step.Fn)
+ }
+ }
+
+ // Apply the prepared list of steps, and abort at the first error.
+ bridgeSetup.queueStep(setupDeviceUp)
+ if err = bridgeSetup.apply(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ var err error
+
+ defer osl.InitOSContext()()
+
+ // Get network handler and remove it from driver
+ d.Lock()
+ n, ok := d.networks[nid]
+ d.Unlock()
+
+ if !ok {
+ return types.InternalMaskableErrorf("network %s does not exist", nid)
+ }
+
+ n.Lock()
+ config := n.config
+ n.Unlock()
+
+ // delele endpoints belong to this network
+ for _, ep := range n.endpoints {
+ if err := n.releasePorts(ep); err != nil {
+ logrus.Warn(err)
+ }
+ if link, err := d.nlh.LinkByName(ep.srcName); err == nil {
+ d.nlh.LinkDel(link)
+ }
+
+ if err := d.storeDelete(ep); err != nil {
+ logrus.Warnf("Failed to remove bridge endpoint %s from store: %v", ep.id[0:7], err)
+ }
+ }
+
+ d.Lock()
+ delete(d.networks, nid)
+ d.Unlock()
+
+ // On failure set network handler back in driver, but
+ // only if is not already taken over by some other thread
+ defer func() {
+ if err != nil {
+ d.Lock()
+ if _, ok := d.networks[nid]; !ok {
+ d.networks[nid] = n
+ }
+ d.Unlock()
+ }
+ }()
+
+ // Sanity check
+ if n == nil {
+ err = driverapi.ErrNoNetwork(nid)
+ return err
+ }
+
+ switch config.BridgeIfaceCreator {
+ case ifaceCreatedByLibnetwork, ifaceCreatorUnknown:
+ // We only delete the bridge if it was created by the bridge driver and
+ // it is not the default one (to keep the backward compatible behavior.)
+ if !config.DefaultBridge {
+ if err := d.nlh.LinkDel(n.bridge.Link); err != nil {
+ logrus.Warnf("Failed to remove bridge interface %s on network %s delete: %v", config.BridgeName, nid, err)
+ }
+ }
+ case ifaceCreatedByUser:
+ // Don't delete the bridge interface if it was not created by libnetwork.
+ }
+
+ // clean all relevant iptables rules
+ for _, cleanFunc := range n.iptCleanFuncs {
+ if errClean := cleanFunc(); errClean != nil {
+ logrus.Warnf("Failed to clean iptables rules for bridge network: %v", errClean)
+ }
+ }
+ return d.storeDelete(config)
+}
+
+func addToBridge(nlh *netlink.Handle, ifaceName, bridgeName string) error {
+ link, err := nlh.LinkByName(ifaceName)
+ if err != nil {
+ return fmt.Errorf("could not find interface %s: %v", ifaceName, err)
+ }
+ if err = nlh.LinkSetMaster(link,
+ &netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: bridgeName}}); err != nil {
+ logrus.Debugf("Failed to add %s to bridge via netlink.Trying ioctl: %v", ifaceName, err)
+ iface, err := net.InterfaceByName(ifaceName)
+ if err != nil {
+ return fmt.Errorf("could not find network interface %s: %v", ifaceName, err)
+ }
+
+ master, err := net.InterfaceByName(bridgeName)
+ if err != nil {
+ return fmt.Errorf("could not find bridge %s: %v", bridgeName, err)
+ }
+
+ return ioctlAddToBridge(iface, master)
+ }
+ return nil
+}
+
+func setHairpinMode(nlh *netlink.Handle, link netlink.Link, enable bool) error {
+ err := nlh.LinkSetHairpin(link, enable)
+ if err != nil && err != syscall.EINVAL {
+ // If error is not EINVAL something else went wrong, bail out right away
+ return fmt.Errorf("unable to set hairpin mode on %s via netlink: %v",
+ link.Attrs().Name, err)
+ }
+
+ // Hairpin mode successfully set up
+ if err == nil {
+ return nil
+ }
+
+ // The netlink method failed with EINVAL which is probably because of an older
+ // kernel. Try one more time via the sysfs method.
+ path := filepath.Join("/sys/class/net", link.Attrs().Name, "brport/hairpin_mode")
+
+ var val []byte
+ if enable {
+ val = []byte{'1', '\n'}
+ } else {
+ val = []byte{'0', '\n'}
+ }
+
+ if err := ioutil.WriteFile(path, val, 0644); err != nil {
+ return fmt.Errorf("unable to set hairpin mode on %s via sysfs: %v", link.Attrs().Name, err)
+ }
+
+ return nil
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
+ defer osl.InitOSContext()()
+
+ if ifInfo == nil {
+ return errors.New("invalid interface info passed")
+ }
+
+ // Get the network handler and make sure it exists
+ d.Lock()
+ n, ok := d.networks[nid]
+ dconfig := d.config
+ d.Unlock()
+
+ if !ok {
+ return types.NotFoundErrorf("network %s does not exist", nid)
+ }
+ if n == nil {
+ return driverapi.ErrNoNetwork(nid)
+ }
+
+ // Sanity check
+ n.Lock()
+ if n.id != nid {
+ n.Unlock()
+ return InvalidNetworkIDError(nid)
+ }
+ n.Unlock()
+
+ // Check if endpoint id is good and retrieve correspondent endpoint
+ ep, err := n.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ // Endpoint with that id exists either on desired or other sandbox
+ if ep != nil {
+ return driverapi.ErrEndpointExists(eid)
+ }
+
+ // Try to convert the options to endpoint configuration
+ epConfig, err := parseEndpointOptions(epOptions)
+ if err != nil {
+ return err
+ }
+
+ // Create and add the endpoint
+ n.Lock()
+ endpoint := &bridgeEndpoint{id: eid, nid: nid, config: epConfig}
+ n.endpoints[eid] = endpoint
+ n.Unlock()
+
+ // On failure make sure to remove the endpoint
+ defer func() {
+ if err != nil {
+ n.Lock()
+ delete(n.endpoints, eid)
+ n.Unlock()
+ }
+ }()
+
+ // Generate a name for what will be the host side pipe interface
+ hostIfName, err := netutils.GenerateIfaceName(d.nlh, vethPrefix, vethLen)
+ if err != nil {
+ return err
+ }
+
+ // Generate a name for what will be the sandbox side pipe interface
+ containerIfName, err := netutils.GenerateIfaceName(d.nlh, vethPrefix, vethLen)
+ if err != nil {
+ return err
+ }
+
+ // Generate and add the interface pipe host <-> sandbox
+ veth := &netlink.Veth{
+ LinkAttrs: netlink.LinkAttrs{Name: hostIfName, TxQLen: 0},
+ PeerName: containerIfName}
+ if err = d.nlh.LinkAdd(veth); err != nil {
+ return types.InternalErrorf("failed to add the host (%s) <=> sandbox (%s) pair interfaces: %v", hostIfName, containerIfName, err)
+ }
+
+ // Get the host side pipe interface handler
+ host, err := d.nlh.LinkByName(hostIfName)
+ if err != nil {
+ return types.InternalErrorf("failed to find host side interface %s: %v", hostIfName, err)
+ }
+ defer func() {
+ if err != nil {
+ d.nlh.LinkDel(host)
+ }
+ }()
+
+ // Get the sandbox side pipe interface handler
+ sbox, err := d.nlh.LinkByName(containerIfName)
+ if err != nil {
+ return types.InternalErrorf("failed to find sandbox side interface %s: %v", containerIfName, err)
+ }
+ defer func() {
+ if err != nil {
+ d.nlh.LinkDel(sbox)
+ }
+ }()
+
+ n.Lock()
+ config := n.config
+ n.Unlock()
+
+ // Add bridge inherited attributes to pipe interfaces
+ if config.Mtu != 0 {
+ err = d.nlh.LinkSetMTU(host, config.Mtu)
+ if err != nil {
+ return types.InternalErrorf("failed to set MTU on host interface %s: %v", hostIfName, err)
+ }
+ err = d.nlh.LinkSetMTU(sbox, config.Mtu)
+ if err != nil {
+ return types.InternalErrorf("failed to set MTU on sandbox interface %s: %v", containerIfName, err)
+ }
+ }
+
+ // Attach host side pipe interface into the bridge
+ if err = addToBridge(d.nlh, hostIfName, config.BridgeName); err != nil {
+ return fmt.Errorf("adding interface %s to bridge %s failed: %v", hostIfName, config.BridgeName, err)
+ }
+
+ if !dconfig.EnableUserlandProxy {
+ err = setHairpinMode(d.nlh, host, true)
+ if err != nil {
+ return err
+ }
+ }
+
+ // Store the sandbox side pipe interface parameters
+ endpoint.srcName = containerIfName
+ endpoint.macAddress = ifInfo.MacAddress()
+ endpoint.addr = ifInfo.Address()
+ endpoint.addrv6 = ifInfo.AddressIPv6()
+
+ // Set the sbox's MAC if not provided. If specified, use the one configured by user, otherwise generate one based on IP.
+ if endpoint.macAddress == nil {
+ endpoint.macAddress = electMacAddress(epConfig, endpoint.addr.IP)
+ if err = ifInfo.SetMacAddress(endpoint.macAddress); err != nil {
+ return err
+ }
+ }
+
+ // Up the host interface after finishing all netlink configuration
+ if err = d.nlh.LinkSetUp(host); err != nil {
+ return fmt.Errorf("could not set link up for host interface %s: %v", hostIfName, err)
+ }
+
+ if endpoint.addrv6 == nil && config.EnableIPv6 {
+ var ip6 net.IP
+ network := n.bridge.bridgeIPv6
+ if config.AddressIPv6 != nil {
+ network = config.AddressIPv6
+ }
+
+ ones, _ := network.Mask.Size()
+ if ones > 80 {
+ err = types.ForbiddenErrorf("Cannot self generate an IPv6 address on network %v: At least 48 host bits are needed.", network)
+ return err
+ }
+
+ ip6 = make(net.IP, len(network.IP))
+ copy(ip6, network.IP)
+ for i, h := range endpoint.macAddress {
+ ip6[i+10] = h
+ }
+
+ endpoint.addrv6 = &net.IPNet{IP: ip6, Mask: network.Mask}
+ if err = ifInfo.SetIPAddress(endpoint.addrv6); err != nil {
+ return err
+ }
+ }
+
+ if err = d.storeUpdate(endpoint); err != nil {
+ return fmt.Errorf("failed to save bridge endpoint %s to store: %v", endpoint.id[0:7], err)
+ }
+
+ return nil
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ var err error
+
+ defer osl.InitOSContext()()
+
+ // Get the network handler and make sure it exists
+ d.Lock()
+ n, ok := d.networks[nid]
+ d.Unlock()
+
+ if !ok {
+ return types.InternalMaskableErrorf("network %s does not exist", nid)
+ }
+ if n == nil {
+ return driverapi.ErrNoNetwork(nid)
+ }
+
+ // Sanity Check
+ n.Lock()
+ if n.id != nid {
+ n.Unlock()
+ return InvalidNetworkIDError(nid)
+ }
+ n.Unlock()
+
+ // Check endpoint id and if an endpoint is actually there
+ ep, err := n.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+ if ep == nil {
+ return EndpointNotFoundError(eid)
+ }
+
+ // Remove it
+ n.Lock()
+ delete(n.endpoints, eid)
+ n.Unlock()
+
+ // On failure make sure to set back ep in n.endpoints, but only
+ // if it hasn't been taken over already by some other thread.
+ defer func() {
+ if err != nil {
+ n.Lock()
+ if _, ok := n.endpoints[eid]; !ok {
+ n.endpoints[eid] = ep
+ }
+ n.Unlock()
+ }
+ }()
+
+ // Try removal of link. Discard error: it is a best effort.
+ // Also make sure defer does not see this error either.
+ if link, err := d.nlh.LinkByName(ep.srcName); err == nil {
+ d.nlh.LinkDel(link)
+ }
+
+ if err := d.storeDelete(ep); err != nil {
+ logrus.Warnf("Failed to remove bridge endpoint %s from store: %v", ep.id[0:7], err)
+ }
+
+ return nil
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ // Get the network handler and make sure it exists
+ d.Lock()
+ n, ok := d.networks[nid]
+ d.Unlock()
+ if !ok {
+ return nil, types.NotFoundErrorf("network %s does not exist", nid)
+ }
+ if n == nil {
+ return nil, driverapi.ErrNoNetwork(nid)
+ }
+
+ // Sanity check
+ n.Lock()
+ if n.id != nid {
+ n.Unlock()
+ return nil, InvalidNetworkIDError(nid)
+ }
+ n.Unlock()
+
+ // Check if endpoint id is good and retrieve correspondent endpoint
+ ep, err := n.getEndpoint(eid)
+ if err != nil {
+ return nil, err
+ }
+ if ep == nil {
+ return nil, driverapi.ErrNoEndpoint(eid)
+ }
+
+ m := make(map[string]interface{})
+
+ if ep.extConnConfig != nil && ep.extConnConfig.ExposedPorts != nil {
+ // Return a copy of the config data
+ epc := make([]types.TransportPort, 0, len(ep.extConnConfig.ExposedPorts))
+ for _, tp := range ep.extConnConfig.ExposedPorts {
+ epc = append(epc, tp.GetCopy())
+ }
+ m[netlabel.ExposedPorts] = epc
+ }
+
+ if ep.portMapping != nil {
+ // Return a copy of the operational data
+ pmc := make([]types.PortBinding, 0, len(ep.portMapping))
+ for _, pm := range ep.portMapping {
+ pmc = append(pmc, pm.GetCopy())
+ }
+ m[netlabel.PortMap] = pmc
+ }
+
+ if len(ep.macAddress) != 0 {
+ m[netlabel.MacAddress] = ep.macAddress
+ }
+
+ return m, nil
+}
+
+// Join method is invoked when a Sandbox is attached to an endpoint.
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ defer osl.InitOSContext()()
+
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return err
+ }
+
+ endpoint, err := network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ if endpoint == nil {
+ return EndpointNotFoundError(eid)
+ }
+
+ endpoint.containerConfig, err = parseContainerOptions(options)
+ if err != nil {
+ return err
+ }
+
+ iNames := jinfo.InterfaceName()
+ containerVethPrefix := defaultContainerVethPrefix
+ if network.config.ContainerIfacePrefix != "" {
+ containerVethPrefix = network.config.ContainerIfacePrefix
+ }
+ err = iNames.SetNames(endpoint.srcName, containerVethPrefix)
+ if err != nil {
+ return err
+ }
+
+ err = jinfo.SetGateway(network.bridge.gatewayIPv4)
+ if err != nil {
+ return err
+ }
+
+ err = jinfo.SetGatewayIPv6(network.bridge.gatewayIPv6)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Leave method is invoked when a Sandbox detaches from an endpoint.
+func (d *driver) Leave(nid, eid string) error {
+ defer osl.InitOSContext()()
+
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return types.InternalMaskableErrorf("%s", err)
+ }
+
+ endpoint, err := network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ if endpoint == nil {
+ return EndpointNotFoundError(eid)
+ }
+
+ if !network.config.EnableICC {
+ if err = d.link(network, endpoint, false); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ defer osl.InitOSContext()()
+
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return err
+ }
+
+ endpoint, err := network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ if endpoint == nil {
+ return EndpointNotFoundError(eid)
+ }
+
+ endpoint.extConnConfig, err = parseConnectivityOptions(options)
+ if err != nil {
+ return err
+ }
+
+ // Program any required port mapping and store them in the endpoint
+ endpoint.portMapping, err = network.allocatePorts(endpoint, network.config.DefaultBindingIP, d.config.EnableUserlandProxy)
+ if err != nil {
+ return err
+ }
+
+ defer func() {
+ if err != nil {
+ if e := network.releasePorts(endpoint); e != nil {
+ logrus.Errorf("Failed to release ports allocated for the bridge endpoint %s on failure %v because of %v",
+ eid, err, e)
+ }
+ endpoint.portMapping = nil
+ }
+ }()
+
+ if err = d.storeUpdate(endpoint); err != nil {
+ return fmt.Errorf("failed to update bridge endpoint %s to store: %v", endpoint.id[0:7], err)
+ }
+
+ if !network.config.EnableICC {
+ return d.link(network, endpoint, true)
+ }
+
+ return nil
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ defer osl.InitOSContext()()
+
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return err
+ }
+
+ endpoint, err := network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ if endpoint == nil {
+ return EndpointNotFoundError(eid)
+ }
+
+ err = network.releasePorts(endpoint)
+ if err != nil {
+ logrus.Warn(err)
+ }
+
+ endpoint.portMapping = nil
+
+ // Clean the connection tracker state of the host for the specific endpoint
+ // The host kernel keeps track of the connections (TCP and UDP), so if a new endpoint gets the same IP of
+ // this one (that is going down), is possible that some of the packets would not be routed correctly inside
+ // the new endpoint
+ // Deeper details: https://github.com/docker/docker/issues/8795
+ clearEndpointConnections(d.nlh, endpoint)
+
+ if err = d.storeUpdate(endpoint); err != nil {
+ return fmt.Errorf("failed to update bridge endpoint %s to store: %v", endpoint.id[0:7], err)
+ }
+
+ return nil
+}
+
+func (d *driver) link(network *bridgeNetwork, endpoint *bridgeEndpoint, enable bool) error {
+ var err error
+
+ cc := endpoint.containerConfig
+ if cc == nil {
+ return nil
+ }
+ ec := endpoint.extConnConfig
+ if ec == nil {
+ return nil
+ }
+
+ if ec.ExposedPorts != nil {
+ for _, p := range cc.ParentEndpoints {
+ var parentEndpoint *bridgeEndpoint
+ parentEndpoint, err = network.getEndpoint(p)
+ if err != nil {
+ return err
+ }
+ if parentEndpoint == nil {
+ err = InvalidEndpointIDError(p)
+ return err
+ }
+
+ l := newLink(parentEndpoint.addr.IP.String(),
+ endpoint.addr.IP.String(),
+ ec.ExposedPorts, network.config.BridgeName)
+ if enable {
+ err = l.Enable()
+ if err != nil {
+ return err
+ }
+ defer func() {
+ if err != nil {
+ l.Disable()
+ }
+ }()
+ } else {
+ l.Disable()
+ }
+ }
+ }
+
+ for _, c := range cc.ChildEndpoints {
+ var childEndpoint *bridgeEndpoint
+ childEndpoint, err = network.getEndpoint(c)
+ if err != nil {
+ return err
+ }
+ if childEndpoint == nil {
+ err = InvalidEndpointIDError(c)
+ return err
+ }
+ if childEndpoint.extConnConfig == nil || childEndpoint.extConnConfig.ExposedPorts == nil {
+ continue
+ }
+
+ l := newLink(endpoint.addr.IP.String(),
+ childEndpoint.addr.IP.String(),
+ childEndpoint.extConnConfig.ExposedPorts, network.config.BridgeName)
+ if enable {
+ err = l.Enable()
+ if err != nil {
+ return err
+ }
+ defer func() {
+ if err != nil {
+ l.Disable()
+ }
+ }()
+ } else {
+ l.Disable()
+ }
+ }
+
+ return nil
+}
+
+func (d *driver) Type() string {
+ return networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+func parseEndpointOptions(epOptions map[string]interface{}) (*endpointConfiguration, error) {
+ if epOptions == nil {
+ return nil, nil
+ }
+
+ ec := &endpointConfiguration{}
+
+ if opt, ok := epOptions[netlabel.MacAddress]; ok {
+ if mac, ok := opt.(net.HardwareAddr); ok {
+ ec.MacAddress = mac
+ } else {
+ return nil, &ErrInvalidEndpointConfig{}
+ }
+ }
+
+ return ec, nil
+}
+
+func parseContainerOptions(cOptions map[string]interface{}) (*containerConfiguration, error) {
+ if cOptions == nil {
+ return nil, nil
+ }
+ genericData := cOptions[netlabel.GenericData]
+ if genericData == nil {
+ return nil, nil
+ }
+ switch opt := genericData.(type) {
+ case options.Generic:
+ opaqueConfig, err := options.GenerateFromModel(opt, &containerConfiguration{})
+ if err != nil {
+ return nil, err
+ }
+ return opaqueConfig.(*containerConfiguration), nil
+ case *containerConfiguration:
+ return opt, nil
+ default:
+ return nil, nil
+ }
+}
+
+func parseConnectivityOptions(cOptions map[string]interface{}) (*connectivityConfiguration, error) {
+ if cOptions == nil {
+ return nil, nil
+ }
+
+ cc := &connectivityConfiguration{}
+
+ if opt, ok := cOptions[netlabel.PortMap]; ok {
+ if pb, ok := opt.([]types.PortBinding); ok {
+ cc.PortBindings = pb
+ } else {
+ return nil, types.BadRequestErrorf("Invalid port mapping data in connectivity configuration: %v", opt)
+ }
+ }
+
+ if opt, ok := cOptions[netlabel.ExposedPorts]; ok {
+ if ports, ok := opt.([]types.TransportPort); ok {
+ cc.ExposedPorts = ports
+ } else {
+ return nil, types.BadRequestErrorf("Invalid exposed ports data in connectivity configuration: %v", opt)
+ }
+ }
+
+ return cc, nil
+}
+
+func electMacAddress(epConfig *endpointConfiguration, ip net.IP) net.HardwareAddr {
+ if epConfig != nil && epConfig.MacAddress != nil {
+ return epConfig.MacAddress
+ }
+ return netutils.GenerateMACFromIP(ip)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/bridge_store.go b/vendor/github.com/docker/libnetwork/drivers/bridge/bridge_store.go
new file mode 100644
index 0000000..c7c83d8
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/bridge_store.go
@@ -0,0 +1,388 @@
+package bridge
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ // network config prefix was not specific enough.
+ // To be backward compatible, need custom endpoint
+ // prefix with different root
+ bridgePrefix = "bridge"
+ bridgeEndpointPrefix = "bridge-endpoint"
+)
+
+func (d *driver) initStore(option map[string]interface{}) error {
+ if data, ok := option[netlabel.LocalKVClient]; ok {
+ var err error
+ dsc, ok := data.(discoverapi.DatastoreConfigData)
+ if !ok {
+ return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
+ }
+ d.store, err = datastore.NewDataStoreFromConfig(dsc)
+ if err != nil {
+ return types.InternalErrorf("bridge driver failed to initialize data store: %v", err)
+ }
+
+ err = d.populateNetworks()
+ if err != nil {
+ return err
+ }
+
+ err = d.populateEndpoints()
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (d *driver) populateNetworks() error {
+ kvol, err := d.store.List(datastore.Key(bridgePrefix), &networkConfiguration{})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ return fmt.Errorf("failed to get bridge network configurations from store: %v", err)
+ }
+
+ // It's normal for network configuration state to be empty. Just return.
+ if err == datastore.ErrKeyNotFound {
+ return nil
+ }
+
+ for _, kvo := range kvol {
+ ncfg := kvo.(*networkConfiguration)
+ if err = d.createNetwork(ncfg); err != nil {
+ logrus.Warnf("could not create bridge network for id %s bridge name %s while booting up from persistent state: %v", ncfg.ID, ncfg.BridgeName, err)
+ }
+ logrus.Debugf("Network (%s) restored", ncfg.ID[0:7])
+ }
+
+ return nil
+}
+
+func (d *driver) populateEndpoints() error {
+ kvol, err := d.store.List(datastore.Key(bridgeEndpointPrefix), &bridgeEndpoint{})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ return fmt.Errorf("failed to get bridge endpoints from store: %v", err)
+ }
+
+ if err == datastore.ErrKeyNotFound {
+ return nil
+ }
+
+ for _, kvo := range kvol {
+ ep := kvo.(*bridgeEndpoint)
+ n, ok := d.networks[ep.nid]
+ if !ok {
+ logrus.Debugf("Network (%s) not found for restored bridge endpoint (%s)", ep.nid[0:7], ep.id[0:7])
+ logrus.Debugf("Deleting stale bridge endpoint (%s) from store", ep.id[0:7])
+ if err := d.storeDelete(ep); err != nil {
+ logrus.Debugf("Failed to delete stale bridge endpoint (%s) from store", ep.id[0:7])
+ }
+ continue
+ }
+ n.endpoints[ep.id] = ep
+ n.restorePortAllocations(ep)
+ logrus.Debugf("Endpoint (%s) restored to network (%s)", ep.id[0:7], ep.nid[0:7])
+ }
+
+ return nil
+}
+
+func (d *driver) storeUpdate(kvObject datastore.KVObject) error {
+ if d.store == nil {
+ logrus.Warnf("bridge store not initialized. kv object %s is not added to the store", datastore.Key(kvObject.Key()...))
+ return nil
+ }
+
+ if err := d.store.PutObjectAtomic(kvObject); err != nil {
+ return fmt.Errorf("failed to update bridge store for object type %T: %v", kvObject, err)
+ }
+
+ return nil
+}
+
+func (d *driver) storeDelete(kvObject datastore.KVObject) error {
+ if d.store == nil {
+ logrus.Debugf("bridge store not initialized. kv object %s is not deleted from store", datastore.Key(kvObject.Key()...))
+ return nil
+ }
+
+retry:
+ if err := d.store.DeleteObjectAtomic(kvObject); err != nil {
+ if err == datastore.ErrKeyModified {
+ if err := d.store.GetObject(datastore.Key(kvObject.Key()...), kvObject); err != nil {
+ return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err)
+ }
+ goto retry
+ }
+ return err
+ }
+
+ return nil
+}
+
+func (ncfg *networkConfiguration) MarshalJSON() ([]byte, error) {
+ nMap := make(map[string]interface{})
+ nMap["ID"] = ncfg.ID
+ nMap["BridgeName"] = ncfg.BridgeName
+ nMap["EnableIPv6"] = ncfg.EnableIPv6
+ nMap["EnableIPMasquerade"] = ncfg.EnableIPMasquerade
+ nMap["EnableICC"] = ncfg.EnableICC
+ nMap["Mtu"] = ncfg.Mtu
+ nMap["Internal"] = ncfg.Internal
+ nMap["DefaultBridge"] = ncfg.DefaultBridge
+ nMap["DefaultBindingIP"] = ncfg.DefaultBindingIP.String()
+ nMap["DefaultGatewayIPv4"] = ncfg.DefaultGatewayIPv4.String()
+ nMap["DefaultGatewayIPv6"] = ncfg.DefaultGatewayIPv6.String()
+ nMap["ContainerIfacePrefix"] = ncfg.ContainerIfacePrefix
+ nMap["BridgeIfaceCreator"] = ncfg.BridgeIfaceCreator
+
+ if ncfg.AddressIPv4 != nil {
+ nMap["AddressIPv4"] = ncfg.AddressIPv4.String()
+ }
+
+ if ncfg.AddressIPv6 != nil {
+ nMap["AddressIPv6"] = ncfg.AddressIPv6.String()
+ }
+
+ return json.Marshal(nMap)
+}
+
+func (ncfg *networkConfiguration) UnmarshalJSON(b []byte) error {
+ var (
+ err error
+ nMap map[string]interface{}
+ )
+
+ if err = json.Unmarshal(b, &nMap); err != nil {
+ return err
+ }
+
+ if v, ok := nMap["AddressIPv4"]; ok {
+ if ncfg.AddressIPv4, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode bridge network address IPv4 after json unmarshal: %s", v.(string))
+ }
+ }
+
+ if v, ok := nMap["AddressIPv6"]; ok {
+ if ncfg.AddressIPv6, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode bridge network address IPv6 after json unmarshal: %s", v.(string))
+ }
+ }
+
+ if v, ok := nMap["ContainerIfacePrefix"]; ok {
+ ncfg.ContainerIfacePrefix = v.(string)
+ }
+
+ ncfg.DefaultBridge = nMap["DefaultBridge"].(bool)
+ ncfg.DefaultBindingIP = net.ParseIP(nMap["DefaultBindingIP"].(string))
+ ncfg.DefaultGatewayIPv4 = net.ParseIP(nMap["DefaultGatewayIPv4"].(string))
+ ncfg.DefaultGatewayIPv6 = net.ParseIP(nMap["DefaultGatewayIPv6"].(string))
+ ncfg.ID = nMap["ID"].(string)
+ ncfg.BridgeName = nMap["BridgeName"].(string)
+ ncfg.EnableIPv6 = nMap["EnableIPv6"].(bool)
+ ncfg.EnableIPMasquerade = nMap["EnableIPMasquerade"].(bool)
+ ncfg.EnableICC = nMap["EnableICC"].(bool)
+ ncfg.Mtu = int(nMap["Mtu"].(float64))
+ if v, ok := nMap["Internal"]; ok {
+ ncfg.Internal = v.(bool)
+ }
+
+ if v, ok := nMap["BridgeIfaceCreator"]; ok {
+ ncfg.BridgeIfaceCreator = ifaceCreator(v.(float64))
+ }
+
+ return nil
+}
+
+func (ncfg *networkConfiguration) Key() []string {
+ return []string{bridgePrefix, ncfg.ID}
+}
+
+func (ncfg *networkConfiguration) KeyPrefix() []string {
+ return []string{bridgePrefix}
+}
+
+func (ncfg *networkConfiguration) Value() []byte {
+ b, err := json.Marshal(ncfg)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (ncfg *networkConfiguration) SetValue(value []byte) error {
+ return json.Unmarshal(value, ncfg)
+}
+
+func (ncfg *networkConfiguration) Index() uint64 {
+ return ncfg.dbIndex
+}
+
+func (ncfg *networkConfiguration) SetIndex(index uint64) {
+ ncfg.dbIndex = index
+ ncfg.dbExists = true
+}
+
+func (ncfg *networkConfiguration) Exists() bool {
+ return ncfg.dbExists
+}
+
+func (ncfg *networkConfiguration) Skip() bool {
+ return false
+}
+
+func (ncfg *networkConfiguration) New() datastore.KVObject {
+ return &networkConfiguration{}
+}
+
+func (ncfg *networkConfiguration) CopyTo(o datastore.KVObject) error {
+ dstNcfg := o.(*networkConfiguration)
+ *dstNcfg = *ncfg
+ return nil
+}
+
+func (ncfg *networkConfiguration) DataScope() string {
+ return datastore.LocalScope
+}
+
+func (ep *bridgeEndpoint) MarshalJSON() ([]byte, error) {
+ epMap := make(map[string]interface{})
+ epMap["id"] = ep.id
+ epMap["nid"] = ep.nid
+ epMap["SrcName"] = ep.srcName
+ epMap["MacAddress"] = ep.macAddress.String()
+ epMap["Addr"] = ep.addr.String()
+ if ep.addrv6 != nil {
+ epMap["Addrv6"] = ep.addrv6.String()
+ }
+ epMap["Config"] = ep.config
+ epMap["ContainerConfig"] = ep.containerConfig
+ epMap["ExternalConnConfig"] = ep.extConnConfig
+ epMap["PortMapping"] = ep.portMapping
+
+ return json.Marshal(epMap)
+}
+
+func (ep *bridgeEndpoint) UnmarshalJSON(b []byte) error {
+ var (
+ err error
+ epMap map[string]interface{}
+ )
+
+ if err = json.Unmarshal(b, &epMap); err != nil {
+ return fmt.Errorf("Failed to unmarshal to bridge endpoint: %v", err)
+ }
+
+ if v, ok := epMap["MacAddress"]; ok {
+ if ep.macAddress, err = net.ParseMAC(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode bridge endpoint MAC address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ if v, ok := epMap["Addr"]; ok {
+ if ep.addr, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode bridge endpoint IPv4 address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ if v, ok := epMap["Addrv6"]; ok {
+ if ep.addrv6, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode bridge endpoint IPv6 address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ ep.id = epMap["id"].(string)
+ ep.nid = epMap["nid"].(string)
+ ep.srcName = epMap["SrcName"].(string)
+ d, _ := json.Marshal(epMap["Config"])
+ if err := json.Unmarshal(d, &ep.config); err != nil {
+ logrus.Warnf("Failed to decode endpoint config %v", err)
+ }
+ d, _ = json.Marshal(epMap["ContainerConfig"])
+ if err := json.Unmarshal(d, &ep.containerConfig); err != nil {
+ logrus.Warnf("Failed to decode endpoint container config %v", err)
+ }
+ d, _ = json.Marshal(epMap["ExternalConnConfig"])
+ if err := json.Unmarshal(d, &ep.extConnConfig); err != nil {
+ logrus.Warnf("Failed to decode endpoint external connectivity configuration %v", err)
+ }
+ d, _ = json.Marshal(epMap["PortMapping"])
+ if err := json.Unmarshal(d, &ep.portMapping); err != nil {
+ logrus.Warnf("Failed to decode endpoint port mapping %v", err)
+ }
+
+ return nil
+}
+
+func (ep *bridgeEndpoint) Key() []string {
+ return []string{bridgeEndpointPrefix, ep.id}
+}
+
+func (ep *bridgeEndpoint) KeyPrefix() []string {
+ return []string{bridgeEndpointPrefix}
+}
+
+func (ep *bridgeEndpoint) Value() []byte {
+ b, err := json.Marshal(ep)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (ep *bridgeEndpoint) SetValue(value []byte) error {
+ return json.Unmarshal(value, ep)
+}
+
+func (ep *bridgeEndpoint) Index() uint64 {
+ return ep.dbIndex
+}
+
+func (ep *bridgeEndpoint) SetIndex(index uint64) {
+ ep.dbIndex = index
+ ep.dbExists = true
+}
+
+func (ep *bridgeEndpoint) Exists() bool {
+ return ep.dbExists
+}
+
+func (ep *bridgeEndpoint) Skip() bool {
+ return false
+}
+
+func (ep *bridgeEndpoint) New() datastore.KVObject {
+ return &bridgeEndpoint{}
+}
+
+func (ep *bridgeEndpoint) CopyTo(o datastore.KVObject) error {
+ dstEp := o.(*bridgeEndpoint)
+ *dstEp = *ep
+ return nil
+}
+
+func (ep *bridgeEndpoint) DataScope() string {
+ return datastore.LocalScope
+}
+
+func (n *bridgeNetwork) restorePortAllocations(ep *bridgeEndpoint) {
+ if ep.extConnConfig == nil ||
+ ep.extConnConfig.ExposedPorts == nil ||
+ ep.extConnConfig.PortBindings == nil {
+ return
+ }
+ tmp := ep.extConnConfig.PortBindings
+ ep.extConnConfig.PortBindings = ep.portMapping
+ _, err := n.allocatePorts(ep, n.config.DefaultBindingIP, n.driver.config.EnableUserlandProxy)
+ if err != nil {
+ logrus.Warnf("Failed to reserve existing port mapping for endpoint %s:%v", ep.id[0:7], err)
+ }
+ ep.extConnConfig.PortBindings = tmp
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/brmanager/brmanager.go b/vendor/github.com/docker/libnetwork/drivers/bridge/brmanager/brmanager.go
new file mode 100644
index 0000000..74bb95c
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/brmanager/brmanager.go
@@ -0,0 +1,88 @@
+package brmanager
+
+import (
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/types"
+)
+
+const networkType = "bridge"
+
+type driver struct{}
+
+// Init registers a new instance of bridge manager driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ c := driverapi.Capability{
+ DataScope: datastore.LocalScope,
+ ConnectivityScope: datastore.LocalScope,
+ }
+ return dc.RegisterDriver(networkType, &driver{}, c)
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Leave(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Type() string {
+ return networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/errors.go b/vendor/github.com/docker/libnetwork/drivers/bridge/errors.go
new file mode 100644
index 0000000..9396079
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/errors.go
@@ -0,0 +1,341 @@
+package bridge
+
+import (
+ "fmt"
+ "net"
+)
+
+// ErrConfigExists error is returned when driver already has a config applied.
+type ErrConfigExists struct{}
+
+func (ece *ErrConfigExists) Error() string {
+ return "configuration already exists, bridge configuration can be applied only once"
+}
+
+// Forbidden denotes the type of this error
+func (ece *ErrConfigExists) Forbidden() {}
+
+// ErrInvalidDriverConfig error is returned when Bridge Driver is passed an invalid config
+type ErrInvalidDriverConfig struct{}
+
+func (eidc *ErrInvalidDriverConfig) Error() string {
+ return "Invalid configuration passed to Bridge Driver"
+}
+
+// BadRequest denotes the type of this error
+func (eidc *ErrInvalidDriverConfig) BadRequest() {}
+
+// ErrInvalidNetworkConfig error is returned when a network is created on a driver without valid config.
+type ErrInvalidNetworkConfig struct{}
+
+func (einc *ErrInvalidNetworkConfig) Error() string {
+ return "trying to create a network on a driver without valid config"
+}
+
+// Forbidden denotes the type of this error
+func (einc *ErrInvalidNetworkConfig) Forbidden() {}
+
+// ErrInvalidContainerConfig error is returned when an endpoint create is attempted with an invalid configuration.
+type ErrInvalidContainerConfig struct{}
+
+func (eicc *ErrInvalidContainerConfig) Error() string {
+ return "Error in joining a container due to invalid configuration"
+}
+
+// BadRequest denotes the type of this error
+func (eicc *ErrInvalidContainerConfig) BadRequest() {}
+
+// ErrInvalidEndpointConfig error is returned when an endpoint create is attempted with an invalid endpoint configuration.
+type ErrInvalidEndpointConfig struct{}
+
+func (eiec *ErrInvalidEndpointConfig) Error() string {
+ return "trying to create an endpoint with an invalid endpoint configuration"
+}
+
+// BadRequest denotes the type of this error
+func (eiec *ErrInvalidEndpointConfig) BadRequest() {}
+
+// ErrNetworkExists error is returned when a network already exists and another network is created.
+type ErrNetworkExists struct{}
+
+func (ene *ErrNetworkExists) Error() string {
+ return "network already exists, bridge can only have one network"
+}
+
+// Forbidden denotes the type of this error
+func (ene *ErrNetworkExists) Forbidden() {}
+
+// ErrIfaceName error is returned when a new name could not be generated.
+type ErrIfaceName struct{}
+
+func (ein *ErrIfaceName) Error() string {
+ return "failed to find name for new interface"
+}
+
+// InternalError denotes the type of this error
+func (ein *ErrIfaceName) InternalError() {}
+
+// ErrNoIPAddr error is returned when bridge has no IPv4 address configured.
+type ErrNoIPAddr struct{}
+
+func (enip *ErrNoIPAddr) Error() string {
+ return "bridge has no IPv4 address configured"
+}
+
+// InternalError denotes the type of this error
+func (enip *ErrNoIPAddr) InternalError() {}
+
+// ErrInvalidGateway is returned when the user provided default gateway (v4/v6) is not not valid.
+type ErrInvalidGateway struct{}
+
+func (eig *ErrInvalidGateway) Error() string {
+ return "default gateway ip must be part of the network"
+}
+
+// BadRequest denotes the type of this error
+func (eig *ErrInvalidGateway) BadRequest() {}
+
+// ErrInvalidContainerSubnet is returned when the container subnet (FixedCIDR) is not valid.
+type ErrInvalidContainerSubnet struct{}
+
+func (eis *ErrInvalidContainerSubnet) Error() string {
+ return "container subnet must be a subset of bridge network"
+}
+
+// BadRequest denotes the type of this error
+func (eis *ErrInvalidContainerSubnet) BadRequest() {}
+
+// ErrInvalidMtu is returned when the user provided MTU is not valid.
+type ErrInvalidMtu int
+
+func (eim ErrInvalidMtu) Error() string {
+ return fmt.Sprintf("invalid MTU number: %d", int(eim))
+}
+
+// BadRequest denotes the type of this error
+func (eim ErrInvalidMtu) BadRequest() {}
+
+// ErrInvalidPort is returned when the container or host port specified in the port binding is not valid.
+type ErrInvalidPort string
+
+func (ip ErrInvalidPort) Error() string {
+ return fmt.Sprintf("invalid transport port: %s", string(ip))
+}
+
+// BadRequest denotes the type of this error
+func (ip ErrInvalidPort) BadRequest() {}
+
+// ErrUnsupportedAddressType is returned when the specified address type is not supported.
+type ErrUnsupportedAddressType string
+
+func (uat ErrUnsupportedAddressType) Error() string {
+ return fmt.Sprintf("unsupported address type: %s", string(uat))
+}
+
+// BadRequest denotes the type of this error
+func (uat ErrUnsupportedAddressType) BadRequest() {}
+
+// ErrInvalidAddressBinding is returned when the host address specified in the port binding is not valid.
+type ErrInvalidAddressBinding string
+
+func (iab ErrInvalidAddressBinding) Error() string {
+ return fmt.Sprintf("invalid host address in port binding: %s", string(iab))
+}
+
+// BadRequest denotes the type of this error
+func (iab ErrInvalidAddressBinding) BadRequest() {}
+
+// ActiveEndpointsError is returned when there are
+// still active endpoints in the network being deleted.
+type ActiveEndpointsError string
+
+func (aee ActiveEndpointsError) Error() string {
+ return fmt.Sprintf("network %s has active endpoint", string(aee))
+}
+
+// Forbidden denotes the type of this error
+func (aee ActiveEndpointsError) Forbidden() {}
+
+// InvalidNetworkIDError is returned when the passed
+// network id for an existing network is not a known id.
+type InvalidNetworkIDError string
+
+func (inie InvalidNetworkIDError) Error() string {
+ return fmt.Sprintf("invalid network id %s", string(inie))
+}
+
+// NotFound denotes the type of this error
+func (inie InvalidNetworkIDError) NotFound() {}
+
+// InvalidEndpointIDError is returned when the passed
+// endpoint id is not valid.
+type InvalidEndpointIDError string
+
+func (ieie InvalidEndpointIDError) Error() string {
+ return fmt.Sprintf("invalid endpoint id: %s", string(ieie))
+}
+
+// BadRequest denotes the type of this error
+func (ieie InvalidEndpointIDError) BadRequest() {}
+
+// InvalidSandboxIDError is returned when the passed
+// sandbox id is not valid.
+type InvalidSandboxIDError string
+
+func (isie InvalidSandboxIDError) Error() string {
+ return fmt.Sprintf("invalid sandbox id: %s", string(isie))
+}
+
+// BadRequest denotes the type of this error
+func (isie InvalidSandboxIDError) BadRequest() {}
+
+// EndpointNotFoundError is returned when the no endpoint
+// with the passed endpoint id is found.
+type EndpointNotFoundError string
+
+func (enfe EndpointNotFoundError) Error() string {
+ return fmt.Sprintf("endpoint not found: %s", string(enfe))
+}
+
+// NotFound denotes the type of this error
+func (enfe EndpointNotFoundError) NotFound() {}
+
+// NonDefaultBridgeExistError is returned when a non-default
+// bridge config is passed but it does not already exist.
+type NonDefaultBridgeExistError string
+
+func (ndbee NonDefaultBridgeExistError) Error() string {
+ return fmt.Sprintf("bridge device with non default name %s must be created manually", string(ndbee))
+}
+
+// Forbidden denotes the type of this error
+func (ndbee NonDefaultBridgeExistError) Forbidden() {}
+
+// NonDefaultBridgeNeedsIPError is returned when a non-default
+// bridge config is passed but it has no ip configured
+type NonDefaultBridgeNeedsIPError string
+
+func (ndbee NonDefaultBridgeNeedsIPError) Error() string {
+ return fmt.Sprintf("bridge device with non default name %s must have a valid IP address", string(ndbee))
+}
+
+// Forbidden denotes the type of this error
+func (ndbee NonDefaultBridgeNeedsIPError) Forbidden() {}
+
+// FixedCIDRv4Error is returned when fixed-cidrv4 configuration
+// failed.
+type FixedCIDRv4Error struct {
+ Net *net.IPNet
+ Subnet *net.IPNet
+ Err error
+}
+
+func (fcv4 *FixedCIDRv4Error) Error() string {
+ return fmt.Sprintf("setup FixedCIDRv4 failed for subnet %s in %s: %v", fcv4.Subnet, fcv4.Net, fcv4.Err)
+}
+
+// InternalError denotes the type of this error
+func (fcv4 *FixedCIDRv4Error) InternalError() {}
+
+// FixedCIDRv6Error is returned when fixed-cidrv6 configuration
+// failed.
+type FixedCIDRv6Error struct {
+ Net *net.IPNet
+ Err error
+}
+
+func (fcv6 *FixedCIDRv6Error) Error() string {
+ return fmt.Sprintf("setup FixedCIDRv6 failed for subnet %s in %s: %v", fcv6.Net, fcv6.Net, fcv6.Err)
+}
+
+// InternalError denotes the type of this error
+func (fcv6 *FixedCIDRv6Error) InternalError() {}
+
+// IPTableCfgError is returned when an unexpected ip tables configuration is entered
+type IPTableCfgError string
+
+func (name IPTableCfgError) Error() string {
+ return fmt.Sprintf("unexpected request to set IP tables for interface: %s", string(name))
+}
+
+// BadRequest denotes the type of this error
+func (name IPTableCfgError) BadRequest() {}
+
+// InvalidIPTablesCfgError is returned when an invalid ip tables configuration is entered
+type InvalidIPTablesCfgError string
+
+func (action InvalidIPTablesCfgError) Error() string {
+ return fmt.Sprintf("Invalid IPTables action '%s'", string(action))
+}
+
+// BadRequest denotes the type of this error
+func (action InvalidIPTablesCfgError) BadRequest() {}
+
+// IPv4AddrRangeError is returned when a valid IP address range couldn't be found.
+type IPv4AddrRangeError string
+
+func (name IPv4AddrRangeError) Error() string {
+ return fmt.Sprintf("can't find an address range for interface %q", string(name))
+}
+
+// BadRequest denotes the type of this error
+func (name IPv4AddrRangeError) BadRequest() {}
+
+// IPv4AddrAddError is returned when IPv4 address could not be added to the bridge.
+type IPv4AddrAddError struct {
+ IP *net.IPNet
+ Err error
+}
+
+func (ipv4 *IPv4AddrAddError) Error() string {
+ return fmt.Sprintf("failed to add IPv4 address %s to bridge: %v", ipv4.IP, ipv4.Err)
+}
+
+// InternalError denotes the type of this error
+func (ipv4 *IPv4AddrAddError) InternalError() {}
+
+// IPv6AddrAddError is returned when IPv6 address could not be added to the bridge.
+type IPv6AddrAddError struct {
+ IP *net.IPNet
+ Err error
+}
+
+func (ipv6 *IPv6AddrAddError) Error() string {
+ return fmt.Sprintf("failed to add IPv6 address %s to bridge: %v", ipv6.IP, ipv6.Err)
+}
+
+// InternalError denotes the type of this error
+func (ipv6 *IPv6AddrAddError) InternalError() {}
+
+// IPv4AddrNoMatchError is returned when the bridge's IPv4 address does not match configured.
+type IPv4AddrNoMatchError struct {
+ IP net.IP
+ CfgIP net.IP
+}
+
+func (ipv4 *IPv4AddrNoMatchError) Error() string {
+ return fmt.Sprintf("bridge IPv4 (%s) does not match requested configuration %s", ipv4.IP, ipv4.CfgIP)
+}
+
+// BadRequest denotes the type of this error
+func (ipv4 *IPv4AddrNoMatchError) BadRequest() {}
+
+// IPv6AddrNoMatchError is returned when the bridge's IPv6 address does not match configured.
+type IPv6AddrNoMatchError net.IPNet
+
+func (ipv6 *IPv6AddrNoMatchError) Error() string {
+ return fmt.Sprintf("bridge IPv6 addresses do not match the expected bridge configuration %s", (*net.IPNet)(ipv6).String())
+}
+
+// BadRequest denotes the type of this error
+func (ipv6 *IPv6AddrNoMatchError) BadRequest() {}
+
+// InvalidLinkIPAddrError is returned when a link is configured to a container with an invalid ip address
+type InvalidLinkIPAddrError string
+
+func (address InvalidLinkIPAddrError) Error() string {
+ return fmt.Sprintf("Cannot link to a container with Invalid IP Address '%s'", string(address))
+}
+
+// BadRequest denotes the type of this error
+func (address InvalidLinkIPAddrError) BadRequest() {}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/interface.go b/vendor/github.com/docker/libnetwork/drivers/bridge/interface.go
new file mode 100644
index 0000000..9b20900
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/interface.go
@@ -0,0 +1,86 @@
+package bridge
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/vishvananda/netlink"
+)
+
+const (
+ // DefaultBridgeName is the default name for the bridge interface managed
+ // by the driver when unspecified by the caller.
+ DefaultBridgeName = "docker0"
+)
+
+// Interface models the bridge network device.
+type bridgeInterface struct {
+ Link netlink.Link
+ bridgeIPv4 *net.IPNet
+ bridgeIPv6 *net.IPNet
+ gatewayIPv4 net.IP
+ gatewayIPv6 net.IP
+ nlh *netlink.Handle
+}
+
+// newInterface creates a new bridge interface structure. It attempts to find
+// an already existing device identified by the configuration BridgeName field,
+// or the default bridge name when unspecified, but doesn't attempt to create
+// one when missing
+func newInterface(nlh *netlink.Handle, config *networkConfiguration) (*bridgeInterface, error) {
+ var err error
+ i := &bridgeInterface{nlh: nlh}
+
+ // Initialize the bridge name to the default if unspecified.
+ if config.BridgeName == "" {
+ config.BridgeName = DefaultBridgeName
+ }
+
+ // Attempt to find an existing bridge named with the specified name.
+ i.Link, err = nlh.LinkByName(config.BridgeName)
+ if err != nil {
+ logrus.Debugf("Did not find any interface with name %s: %v", config.BridgeName, err)
+ } else if _, ok := i.Link.(*netlink.Bridge); !ok {
+ return nil, fmt.Errorf("existing interface %s is not a bridge", i.Link.Attrs().Name)
+ }
+ return i, nil
+}
+
+// exists indicates if the existing bridge interface exists on the system.
+func (i *bridgeInterface) exists() bool {
+ return i.Link != nil
+}
+
+// addresses returns all IPv4 addresses and all IPv6 addresses for the bridge interface.
+func (i *bridgeInterface) addresses() ([]netlink.Addr, []netlink.Addr, error) {
+ v4addr, err := i.nlh.AddrList(i.Link, netlink.FAMILY_V4)
+ if err != nil {
+ return nil, nil, fmt.Errorf("Failed to retrieve V4 addresses: %v", err)
+ }
+
+ v6addr, err := i.nlh.AddrList(i.Link, netlink.FAMILY_V6)
+ if err != nil {
+ return nil, nil, fmt.Errorf("Failed to retrieve V6 addresses: %v", err)
+ }
+
+ if len(v4addr) == 0 {
+ return nil, v6addr, nil
+ }
+ return v4addr, v6addr, nil
+}
+
+func (i *bridgeInterface) programIPv6Address() error {
+ _, nlAddressList, err := i.addresses()
+ if err != nil {
+ return &IPv6AddrAddError{IP: i.bridgeIPv6, Err: fmt.Errorf("failed to retrieve address list: %v", err)}
+ }
+ nlAddr := netlink.Addr{IPNet: i.bridgeIPv6}
+ if findIPv6Address(nlAddr, nlAddressList) {
+ return nil
+ }
+ if err := i.nlh.AddrAdd(i.Link, &nlAddr); err != nil {
+ return &IPv6AddrAddError{IP: i.bridgeIPv6, Err: err}
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/labels.go b/vendor/github.com/docker/libnetwork/drivers/bridge/labels.go
new file mode 100644
index 0000000..7447bd3
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/labels.go
@@ -0,0 +1,18 @@
+package bridge
+
+const (
+ // BridgeName label for bridge driver
+ BridgeName = "com.docker.network.bridge.name"
+
+ // EnableIPMasquerade label for bridge driver
+ EnableIPMasquerade = "com.docker.network.bridge.enable_ip_masquerade"
+
+ // EnableICC label
+ EnableICC = "com.docker.network.bridge.enable_icc"
+
+ // DefaultBindingIP label
+ DefaultBindingIP = "com.docker.network.bridge.host_binding_ipv4"
+
+ // DefaultBridge label
+ DefaultBridge = "com.docker.network.bridge.default_bridge"
+)
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/link.go b/vendor/github.com/docker/libnetwork/drivers/bridge/link.go
new file mode 100644
index 0000000..53e9eee
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/link.go
@@ -0,0 +1,85 @@
+package bridge
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/iptables"
+ "github.com/docker/libnetwork/types"
+)
+
+type link struct {
+ parentIP string
+ childIP string
+ ports []types.TransportPort
+ bridge string
+}
+
+func (l *link) String() string {
+ return fmt.Sprintf("%s <-> %s [%v] on %s", l.parentIP, l.childIP, l.ports, l.bridge)
+}
+
+func newLink(parentIP, childIP string, ports []types.TransportPort, bridge string) *link {
+ return &link{
+ childIP: childIP,
+ parentIP: parentIP,
+ ports: ports,
+ bridge: bridge,
+ }
+
+}
+
+func (l *link) Enable() error {
+ // -A == iptables append flag
+ linkFunction := func() error {
+ return linkContainers("-A", l.parentIP, l.childIP, l.ports, l.bridge, false)
+ }
+
+ iptables.OnReloaded(func() { linkFunction() })
+ return linkFunction()
+}
+
+func (l *link) Disable() {
+ // -D == iptables delete flag
+ err := linkContainers("-D", l.parentIP, l.childIP, l.ports, l.bridge, true)
+ if err != nil {
+ logrus.Errorf("Error removing IPTables rules for a link %s due to %s", l.String(), err.Error())
+ }
+ // Return proper error once we move to use a proper iptables package
+ // that returns typed errors
+}
+
+func linkContainers(action, parentIP, childIP string, ports []types.TransportPort, bridge string,
+ ignoreErrors bool) error {
+ var nfAction iptables.Action
+
+ switch action {
+ case "-A":
+ nfAction = iptables.Append
+ case "-I":
+ nfAction = iptables.Insert
+ case "-D":
+ nfAction = iptables.Delete
+ default:
+ return InvalidIPTablesCfgError(action)
+ }
+
+ ip1 := net.ParseIP(parentIP)
+ if ip1 == nil {
+ return InvalidLinkIPAddrError(parentIP)
+ }
+ ip2 := net.ParseIP(childIP)
+ if ip2 == nil {
+ return InvalidLinkIPAddrError(childIP)
+ }
+
+ chain := iptables.ChainInfo{Name: DockerChain}
+ for _, port := range ports {
+ err := chain.Link(nfAction, ip1, ip2, int(port.Port), port.Proto.String(), bridge)
+ if !ignoreErrors && err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux.go b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux.go
new file mode 100644
index 0000000..6b49efa
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux.go
@@ -0,0 +1,131 @@
+package bridge
+
+import (
+ "fmt"
+ "math/rand"
+ "net"
+ "syscall"
+ "time"
+ "unsafe"
+
+ "github.com/docker/libnetwork/netutils"
+)
+
+const (
+ ifNameSize = 16
+ ioctlBrAdd = 0x89a0
+ ioctlBrAddIf = 0x89a2
+)
+
+type ifreqIndex struct {
+ IfrnName [ifNameSize]byte
+ IfruIndex int32
+}
+
+type ifreqHwaddr struct {
+ IfrnName [ifNameSize]byte
+ IfruHwaddr syscall.RawSockaddr
+}
+
+var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
+
+// THIS CODE DOES NOT COMMUNICATE WITH KERNEL VIA RTNETLINK INTERFACE
+// IT IS HERE FOR BACKWARDS COMPATIBILITY WITH OLDER LINUX KERNELS
+// WHICH SHIP WITH OLDER NOT ENTIRELY FUNCTIONAL VERSION OF NETLINK
+func getIfSocket() (fd int, err error) {
+ for _, socket := range []int{
+ syscall.AF_INET,
+ syscall.AF_PACKET,
+ syscall.AF_INET6,
+ } {
+ if fd, err = syscall.Socket(socket, syscall.SOCK_DGRAM, 0); err == nil {
+ break
+ }
+ }
+ if err == nil {
+ return fd, nil
+ }
+ return -1, err
+}
+
+func ifIoctBridge(iface, master *net.Interface, op uintptr) error {
+ if len(master.Name) >= ifNameSize {
+ return fmt.Errorf("Interface name %s too long", master.Name)
+ }
+
+ s, err := getIfSocket()
+ if err != nil {
+ return err
+ }
+ defer syscall.Close(s)
+
+ ifr := ifreqIndex{}
+ copy(ifr.IfrnName[:len(ifr.IfrnName)-1], master.Name)
+ ifr.IfruIndex = int32(iface.Index)
+
+ if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), op, uintptr(unsafe.Pointer(&ifr))); err != 0 {
+ return err
+ }
+
+ return nil
+}
+
+// Add a slave to a bridge device. This is more backward-compatible than
+// netlink.NetworkSetMaster and works on RHEL 6.
+func ioctlAddToBridge(iface, master *net.Interface) error {
+ return ifIoctBridge(iface, master, ioctlBrAddIf)
+}
+
+func ioctlSetMacAddress(name, addr string) error {
+ if len(name) >= ifNameSize {
+ return fmt.Errorf("Interface name %s too long", name)
+ }
+
+ hw, err := net.ParseMAC(addr)
+ if err != nil {
+ return err
+ }
+
+ s, err := getIfSocket()
+ if err != nil {
+ return err
+ }
+ defer syscall.Close(s)
+
+ ifr := ifreqHwaddr{}
+ ifr.IfruHwaddr.Family = syscall.ARPHRD_ETHER
+ copy(ifr.IfrnName[:len(ifr.IfrnName)-1], name)
+
+ for i := 0; i < 6; i++ {
+ ifr.IfruHwaddr.Data[i] = ifrDataByte(hw[i])
+ }
+
+ if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), syscall.SIOCSIFHWADDR, uintptr(unsafe.Pointer(&ifr))); err != 0 {
+ return err
+ }
+ return nil
+}
+
+func ioctlCreateBridge(name string, setMacAddr bool) error {
+ if len(name) >= ifNameSize {
+ return fmt.Errorf("Interface name %s too long", name)
+ }
+
+ s, err := getIfSocket()
+ if err != nil {
+ return err
+ }
+ defer syscall.Close(s)
+
+ nameBytePtr, err := syscall.BytePtrFromString(name)
+ if err != nil {
+ return err
+ }
+ if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), ioctlBrAdd, uintptr(unsafe.Pointer(nameBytePtr))); err != 0 {
+ return err
+ }
+ if setMacAddr {
+ return ioctlSetMacAddress(name, netutils.GenerateRandomMAC().String())
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_armppc64.go b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_armppc64.go
new file mode 100644
index 0000000..739d9c6
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_armppc64.go
@@ -0,0 +1,7 @@
+// +build arm ppc64 ppc64le
+
+package bridge
+
+func ifrDataByte(b byte) uint8 {
+ return uint8(b)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_notarm.go b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_notarm.go
new file mode 100644
index 0000000..df52695
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_linux_notarm.go
@@ -0,0 +1,7 @@
+// +build !arm,!ppc64,!ppc64le
+
+package bridge
+
+func ifrDataByte(b byte) int8 {
+ return int8(b)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_unsupported.go b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_unsupported.go
new file mode 100644
index 0000000..7e2d57b
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/netlink_deprecated_unsupported.go
@@ -0,0 +1,18 @@
+// +build !linux
+
+package bridge
+
+import (
+ "errors"
+ "net"
+)
+
+// Add a slave to a bridge device. This is more backward-compatible than
+// netlink.NetworkSetMaster and works on RHEL 6.
+func ioctlAddToBridge(iface, master *net.Interface) error {
+ return errors.New("not implemented")
+}
+
+func ioctlCreateBridge(name string, setMacAddr bool) error {
+ return errors.New("not implemented")
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/port_mapping.go b/vendor/github.com/docker/libnetwork/drivers/bridge/port_mapping.go
new file mode 100644
index 0000000..965cc9a
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/port_mapping.go
@@ -0,0 +1,128 @@
+package bridge
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/types"
+)
+
+var (
+ defaultBindingIP = net.IPv4(0, 0, 0, 0)
+)
+
+func (n *bridgeNetwork) allocatePorts(ep *bridgeEndpoint, reqDefBindIP net.IP, ulPxyEnabled bool) ([]types.PortBinding, error) {
+ if ep.extConnConfig == nil || ep.extConnConfig.PortBindings == nil {
+ return nil, nil
+ }
+
+ defHostIP := defaultBindingIP
+ if reqDefBindIP != nil {
+ defHostIP = reqDefBindIP
+ }
+
+ return n.allocatePortsInternal(ep.extConnConfig.PortBindings, ep.addr.IP, defHostIP, ulPxyEnabled)
+}
+
+func (n *bridgeNetwork) allocatePortsInternal(bindings []types.PortBinding, containerIP, defHostIP net.IP, ulPxyEnabled bool) ([]types.PortBinding, error) {
+ bs := make([]types.PortBinding, 0, len(bindings))
+ for _, c := range bindings {
+ b := c.GetCopy()
+ if err := n.allocatePort(&b, containerIP, defHostIP, ulPxyEnabled); err != nil {
+ // On allocation failure, release previously allocated ports. On cleanup error, just log a warning message
+ if cuErr := n.releasePortsInternal(bs); cuErr != nil {
+ logrus.Warnf("Upon allocation failure for %v, failed to clear previously allocated port bindings: %v", b, cuErr)
+ }
+ return nil, err
+ }
+ bs = append(bs, b)
+ }
+ return bs, nil
+}
+
+func (n *bridgeNetwork) allocatePort(bnd *types.PortBinding, containerIP, defHostIP net.IP, ulPxyEnabled bool) error {
+ var (
+ host net.Addr
+ err error
+ )
+
+ // Store the container interface address in the operational binding
+ bnd.IP = containerIP
+
+ // Adjust the host address in the operational binding
+ if len(bnd.HostIP) == 0 {
+ bnd.HostIP = defHostIP
+ }
+
+ // Adjust HostPortEnd if this is not a range.
+ if bnd.HostPortEnd == 0 {
+ bnd.HostPortEnd = bnd.HostPort
+ }
+
+ // Construct the container side transport address
+ container, err := bnd.ContainerAddr()
+ if err != nil {
+ return err
+ }
+
+ // Try up to maxAllocatePortAttempts times to get a port that's not already allocated.
+ for i := 0; i < maxAllocatePortAttempts; i++ {
+ if host, err = n.portMapper.MapRange(container, bnd.HostIP, int(bnd.HostPort), int(bnd.HostPortEnd), ulPxyEnabled); err == nil {
+ break
+ }
+ // There is no point in immediately retrying to map an explicitly chosen port.
+ if bnd.HostPort != 0 {
+ logrus.Warnf("Failed to allocate and map port %d-%d: %s", bnd.HostPort, bnd.HostPortEnd, err)
+ break
+ }
+ logrus.Warnf("Failed to allocate and map port: %s, retry: %d", err, i+1)
+ }
+ if err != nil {
+ return err
+ }
+
+ // Save the host port (regardless it was or not specified in the binding)
+ switch netAddr := host.(type) {
+ case *net.TCPAddr:
+ bnd.HostPort = uint16(host.(*net.TCPAddr).Port)
+ return nil
+ case *net.UDPAddr:
+ bnd.HostPort = uint16(host.(*net.UDPAddr).Port)
+ return nil
+ default:
+ // For completeness
+ return ErrUnsupportedAddressType(fmt.Sprintf("%T", netAddr))
+ }
+}
+
+func (n *bridgeNetwork) releasePorts(ep *bridgeEndpoint) error {
+ return n.releasePortsInternal(ep.portMapping)
+}
+
+func (n *bridgeNetwork) releasePortsInternal(bindings []types.PortBinding) error {
+ var errorBuf bytes.Buffer
+
+ // Attempt to release all port bindings, do not stop on failure
+ for _, m := range bindings {
+ if err := n.releasePort(m); err != nil {
+ errorBuf.WriteString(fmt.Sprintf("\ncould not release %v because of %v", m, err))
+ }
+ }
+
+ if errorBuf.Len() != 0 {
+ return errors.New(errorBuf.String())
+ }
+ return nil
+}
+
+func (n *bridgeNetwork) releasePort(bnd types.PortBinding) error {
+ // Construct the host side transport address
+ host, err := bnd.HostAddr()
+ if err != nil {
+ return err
+ }
+ return n.portMapper.Unmap(host)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup.go
new file mode 100644
index 0000000..eeb3611
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/setup.go
@@ -0,0 +1,26 @@
+package bridge
+
+type setupStep func(*networkConfiguration, *bridgeInterface) error
+
+type bridgeSetup struct {
+ config *networkConfiguration
+ bridge *bridgeInterface
+ steps []setupStep
+}
+
+func newBridgeSetup(c *networkConfiguration, i *bridgeInterface) *bridgeSetup {
+ return &bridgeSetup{config: c, bridge: i}
+}
+
+func (b *bridgeSetup) apply() error {
+ for _, fn := range b.steps {
+ if err := fn(b.config, b.bridge); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (b *bridgeSetup) queueStep(step setupStep) {
+ b.steps = append(b.steps, step)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_bridgenetfiltering.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_bridgenetfiltering.go
new file mode 100644
index 0000000..884c711
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_bridgenetfiltering.go
@@ -0,0 +1,163 @@
+package bridge
+
+import (
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// Enumeration type saying which versions of IP protocol to process.
+type ipVersion int
+
+const (
+ ipvnone ipVersion = iota
+ ipv4
+ ipv6
+ ipvboth
+)
+
+//Gets the IP version in use ( [ipv4], [ipv6] or [ipv4 and ipv6] )
+func getIPVersion(config *networkConfiguration) ipVersion {
+ ipVersion := ipv4
+ if config.AddressIPv6 != nil || config.EnableIPv6 {
+ ipVersion |= ipv6
+ }
+ return ipVersion
+}
+
+func setupBridgeNetFiltering(config *networkConfiguration, i *bridgeInterface) error {
+ err := checkBridgeNetFiltering(config, i)
+ if err != nil {
+ if ptherr, ok := err.(*os.PathError); ok {
+ if errno, ok := ptherr.Err.(syscall.Errno); ok && errno == syscall.ENOENT {
+ if isRunningInContainer() {
+ logrus.Warnf("running inside docker container, ignoring missing kernel params: %v", err)
+ err = nil
+ } else {
+ err = errors.New("please ensure that br_netfilter kernel module is loaded")
+ }
+ }
+ }
+ if err != nil {
+ return fmt.Errorf("cannot restrict inter-container communication: %v", err)
+ }
+ }
+ return nil
+}
+
+//Enable bridge net filtering if ip forwarding is enabled. See github issue #11404
+func checkBridgeNetFiltering(config *networkConfiguration, i *bridgeInterface) error {
+ ipVer := getIPVersion(config)
+ iface := config.BridgeName
+ doEnable := func(ipVer ipVersion) error {
+ var ipVerName string
+ if ipVer == ipv4 {
+ ipVerName = "IPv4"
+ } else {
+ ipVerName = "IPv6"
+ }
+ enabled, err := isPacketForwardingEnabled(ipVer, iface)
+ if err != nil {
+ logrus.Warnf("failed to check %s forwarding: %v", ipVerName, err)
+ } else if enabled {
+ enabled, err := getKernelBoolParam(getBridgeNFKernelParam(ipVer))
+ if err != nil || enabled {
+ return err
+ }
+ return setKernelBoolParam(getBridgeNFKernelParam(ipVer), true)
+ }
+ return nil
+ }
+
+ switch ipVer {
+ case ipv4, ipv6:
+ return doEnable(ipVer)
+ case ipvboth:
+ v4err := doEnable(ipv4)
+ v6err := doEnable(ipv6)
+ if v4err == nil {
+ return v6err
+ }
+ return v4err
+ default:
+ return nil
+ }
+}
+
+// Get kernel param path saying whether IPv${ipVer} traffic is being forwarded
+// on particular interface. Interface may be specified for IPv6 only. If
+// `iface` is empty, `default` will be assumed, which represents default value
+// for new interfaces.
+func getForwardingKernelParam(ipVer ipVersion, iface string) string {
+ switch ipVer {
+ case ipv4:
+ return "/proc/sys/net/ipv4/ip_forward"
+ case ipv6:
+ if iface == "" {
+ iface = "default"
+ }
+ return fmt.Sprintf("/proc/sys/net/ipv6/conf/%s/forwarding", iface)
+ default:
+ return ""
+ }
+}
+
+// Get kernel param path saying whether bridged IPv${ipVer} traffic shall be
+// passed to ip${ipVer}tables' chains.
+func getBridgeNFKernelParam(ipVer ipVersion) string {
+ switch ipVer {
+ case ipv4:
+ return "/proc/sys/net/bridge/bridge-nf-call-iptables"
+ case ipv6:
+ return "/proc/sys/net/bridge/bridge-nf-call-ip6tables"
+ default:
+ return ""
+ }
+}
+
+//Gets the value of the kernel parameters located at the given path
+func getKernelBoolParam(path string) (bool, error) {
+ enabled := false
+ line, err := ioutil.ReadFile(path)
+ if err != nil {
+ return false, err
+ }
+ if len(line) > 0 {
+ enabled = line[0] == '1'
+ }
+ return enabled, err
+}
+
+//Sets the value of the kernel parameter located at the given path
+func setKernelBoolParam(path string, on bool) error {
+ value := byte('0')
+ if on {
+ value = byte('1')
+ }
+ return ioutil.WriteFile(path, []byte{value, '\n'}, 0644)
+}
+
+//Checks to see if packet forwarding is enabled
+func isPacketForwardingEnabled(ipVer ipVersion, iface string) (bool, error) {
+ switch ipVer {
+ case ipv4, ipv6:
+ return getKernelBoolParam(getForwardingKernelParam(ipVer, iface))
+ case ipvboth:
+ enabled, err := getKernelBoolParam(getForwardingKernelParam(ipv4, ""))
+ if err != nil || !enabled {
+ return enabled, err
+ }
+ return getKernelBoolParam(getForwardingKernelParam(ipv6, iface))
+ default:
+ return true, nil
+ }
+}
+
+func isRunningInContainer() bool {
+ _, err := os.Stat("/.dockerenv")
+ return !os.IsNotExist(err)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_device.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_device.go
new file mode 100644
index 0000000..0961bea
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_device.go
@@ -0,0 +1,68 @@
+package bridge
+
+import (
+ "fmt"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/parsers/kernel"
+ "github.com/docker/libnetwork/netutils"
+ "github.com/vishvananda/netlink"
+)
+
+// SetupDevice create a new bridge interface/
+func setupDevice(config *networkConfiguration, i *bridgeInterface) error {
+ var setMac bool
+
+ // We only attempt to create the bridge when the requested device name is
+ // the default one.
+ if config.BridgeName != DefaultBridgeName && config.DefaultBridge {
+ return NonDefaultBridgeExistError(config.BridgeName)
+ }
+
+ // Set the bridgeInterface netlink.Bridge.
+ i.Link = &netlink.Bridge{
+ LinkAttrs: netlink.LinkAttrs{
+ Name: config.BridgeName,
+ },
+ }
+
+ // Only set the bridge's MAC address if the kernel version is > 3.3, as it
+ // was not supported before that.
+ kv, err := kernel.GetKernelVersion()
+ if err != nil {
+ logrus.Errorf("Failed to check kernel versions: %v. Will not assign a MAC address to the bridge interface", err)
+ } else {
+ setMac = kv.Kernel > 3 || (kv.Kernel == 3 && kv.Major >= 3)
+ }
+
+ if err = i.nlh.LinkAdd(i.Link); err != nil {
+ logrus.Debugf("Failed to create bridge %s via netlink. Trying ioctl", config.BridgeName)
+ return ioctlCreateBridge(config.BridgeName, setMac)
+ }
+
+ if setMac {
+ hwAddr := netutils.GenerateRandomMAC()
+ if err = i.nlh.LinkSetHardwareAddr(i.Link, hwAddr); err != nil {
+ return fmt.Errorf("failed to set bridge mac-address %s : %s", hwAddr, err.Error())
+ }
+ logrus.Debugf("Setting bridge mac address to %s", hwAddr)
+ }
+ return err
+}
+
+// SetupDeviceUp ups the given bridge interface.
+func setupDeviceUp(config *networkConfiguration, i *bridgeInterface) error {
+ err := i.nlh.LinkSetUp(i.Link)
+ if err != nil {
+ return fmt.Errorf("Failed to set link up for %s: %v", config.BridgeName, err)
+ }
+
+ // Attempt to update the bridge interface to refresh the flags status,
+ // ignoring any failure to do so.
+ if lnk, err := i.nlh.LinkByName(config.BridgeName); err == nil {
+ i.Link = lnk
+ } else {
+ logrus.Warnf("Failed to retrieve link for interface (%s): %v", config.BridgeName, err)
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_firewalld.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_firewalld.go
new file mode 100644
index 0000000..fc45a7e
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_firewalld.go
@@ -0,0 +1,20 @@
+package bridge
+
+import "github.com/docker/libnetwork/iptables"
+
+func (n *bridgeNetwork) setupFirewalld(config *networkConfiguration, i *bridgeInterface) error {
+ d := n.driver
+ d.Lock()
+ driverConfig := d.config
+ d.Unlock()
+
+ // Sanity check.
+ if driverConfig.EnableIPTables == false {
+ return IPTableCfgError(config.BridgeName)
+ }
+
+ iptables.OnReloaded(func() { n.setupIPTables(config, i) })
+ iptables.OnReloaded(n.portMapper.ReMapAll)
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_forwarding.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_forwarding.go
new file mode 100644
index 0000000..d46f8dd
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_forwarding.go
@@ -0,0 +1,56 @@
+package bridge
+
+import (
+ "fmt"
+ "io/ioutil"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/iptables"
+)
+
+const (
+ ipv4ForwardConf = "/proc/sys/net/ipv4/ip_forward"
+ ipv4ForwardConfPerm = 0644
+)
+
+func configureIPForwarding(enable bool) error {
+ var val byte
+ if enable {
+ val = '1'
+ }
+ return ioutil.WriteFile(ipv4ForwardConf, []byte{val, '\n'}, ipv4ForwardConfPerm)
+}
+
+func setupIPForwarding(enableIPTables bool) error {
+ // Get current IPv4 forward setup
+ ipv4ForwardData, err := ioutil.ReadFile(ipv4ForwardConf)
+ if err != nil {
+ return fmt.Errorf("Cannot read IP forwarding setup: %v", err)
+ }
+
+ // Enable IPv4 forwarding only if it is not already enabled
+ if ipv4ForwardData[0] != '1' {
+ // Enable IPv4 forwarding
+ if err := configureIPForwarding(true); err != nil {
+ return fmt.Errorf("Enabling IP forwarding failed: %v", err)
+ }
+ // When enabling ip_forward set the default policy on forward chain to
+ // drop only if the daemon option iptables is not set to false.
+ if !enableIPTables {
+ return nil
+ }
+ if err := iptables.SetDefaultPolicy(iptables.Filter, "FORWARD", iptables.Drop); err != nil {
+ if err := configureIPForwarding(false); err != nil {
+ logrus.Errorf("Disabling IP forwarding failed, %v", err)
+ }
+ return err
+ }
+ iptables.OnReloaded(func() {
+ logrus.Debug("Setting the default DROP policy on firewall reload")
+ if err := iptables.SetDefaultPolicy(iptables.Filter, "FORWARD", iptables.Drop); err != nil {
+ logrus.Warnf("Settig the default DROP policy on firewall reload failed, %v", err)
+ }
+ })
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_tables.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_tables.go
new file mode 100644
index 0000000..769debc
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ip_tables.go
@@ -0,0 +1,323 @@
+package bridge
+
+import (
+ "errors"
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/iptables"
+ "github.com/vishvananda/netlink"
+)
+
+// DockerChain: DOCKER iptable chain name
+const (
+ DockerChain = "DOCKER"
+ IsolationChain = "DOCKER-ISOLATION"
+)
+
+func setupIPChains(config *configuration) (*iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, error) {
+ // Sanity check.
+ if config.EnableIPTables == false {
+ return nil, nil, nil, errors.New("cannot create new chains, EnableIPTable is disabled")
+ }
+
+ hairpinMode := !config.EnableUserlandProxy
+
+ natChain, err := iptables.NewChain(DockerChain, iptables.Nat, hairpinMode)
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("failed to create NAT chain: %v", err)
+ }
+ defer func() {
+ if err != nil {
+ if err := iptables.RemoveExistingChain(DockerChain, iptables.Nat); err != nil {
+ logrus.Warnf("failed on removing iptables NAT chain on cleanup: %v", err)
+ }
+ }
+ }()
+
+ filterChain, err := iptables.NewChain(DockerChain, iptables.Filter, false)
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("failed to create FILTER chain: %v", err)
+ }
+ defer func() {
+ if err != nil {
+ if err := iptables.RemoveExistingChain(DockerChain, iptables.Filter); err != nil {
+ logrus.Warnf("failed on removing iptables FILTER chain on cleanup: %v", err)
+ }
+ }
+ }()
+
+ isolationChain, err := iptables.NewChain(IsolationChain, iptables.Filter, false)
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("failed to create FILTER isolation chain: %v", err)
+ }
+
+ if err := iptables.AddReturnRule(IsolationChain); err != nil {
+ return nil, nil, nil, err
+ }
+
+ return natChain, filterChain, isolationChain, nil
+}
+
+func (n *bridgeNetwork) setupIPTables(config *networkConfiguration, i *bridgeInterface) error {
+ var err error
+
+ d := n.driver
+ d.Lock()
+ driverConfig := d.config
+ d.Unlock()
+
+ // Sanity check.
+ if driverConfig.EnableIPTables == false {
+ return errors.New("Cannot program chains, EnableIPTable is disabled")
+ }
+
+ // Pickup this configuration option from driver
+ hairpinMode := !driverConfig.EnableUserlandProxy
+
+ maskedAddrv4 := &net.IPNet{
+ IP: i.bridgeIPv4.IP.Mask(i.bridgeIPv4.Mask),
+ Mask: i.bridgeIPv4.Mask,
+ }
+ if config.Internal {
+ if err = setupInternalNetworkRules(config.BridgeName, maskedAddrv4, config.EnableICC, true); err != nil {
+ return fmt.Errorf("Failed to Setup IP tables: %s", err.Error())
+ }
+ n.registerIptCleanFunc(func() error {
+ return setupInternalNetworkRules(config.BridgeName, maskedAddrv4, config.EnableICC, false)
+ })
+ } else {
+ if err = setupIPTablesInternal(config.BridgeName, maskedAddrv4, config.EnableICC, config.EnableIPMasquerade, hairpinMode, true); err != nil {
+ return fmt.Errorf("Failed to Setup IP tables: %s", err.Error())
+ }
+ n.registerIptCleanFunc(func() error {
+ return setupIPTablesInternal(config.BridgeName, maskedAddrv4, config.EnableICC, config.EnableIPMasquerade, hairpinMode, false)
+ })
+ natChain, filterChain, _, err := n.getDriverChains()
+ if err != nil {
+ return fmt.Errorf("Failed to setup IP tables, cannot acquire chain info %s", err.Error())
+ }
+
+ err = iptables.ProgramChain(natChain, config.BridgeName, hairpinMode, true)
+ if err != nil {
+ return fmt.Errorf("Failed to program NAT chain: %s", err.Error())
+ }
+
+ err = iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode, true)
+ if err != nil {
+ return fmt.Errorf("Failed to program FILTER chain: %s", err.Error())
+ }
+
+ n.registerIptCleanFunc(func() error {
+ return iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode, false)
+ })
+
+ n.portMapper.SetIptablesChain(natChain, n.getNetworkBridgeName())
+ }
+
+ d.Lock()
+ err = iptables.EnsureJumpRule("FORWARD", IsolationChain)
+ d.Unlock()
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+type iptRule struct {
+ table iptables.Table
+ chain string
+ preArgs []string
+ args []string
+}
+
+func setupIPTablesInternal(bridgeIface string, addr net.Addr, icc, ipmasq, hairpin, enable bool) error {
+
+ var (
+ address = addr.String()
+ natRule = iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-s", address, "!", "-o", bridgeIface, "-j", "MASQUERADE"}}
+ hpNatRule = iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-m", "addrtype", "--src-type", "LOCAL", "-o", bridgeIface, "-j", "MASQUERADE"}}
+ skipDNAT = iptRule{table: iptables.Nat, chain: DockerChain, preArgs: []string{"-t", "nat"}, args: []string{"-i", bridgeIface, "-j", "RETURN"}}
+ outRule = iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}}
+ )
+
+ // Set NAT.
+ if ipmasq {
+ if err := programChainRule(natRule, "NAT", enable); err != nil {
+ return err
+ }
+ }
+
+ if ipmasq && !hairpin {
+ if err := programChainRule(skipDNAT, "SKIP DNAT", enable); err != nil {
+ return err
+ }
+ }
+
+ // In hairpin mode, masquerade traffic from localhost
+ if hairpin {
+ if err := programChainRule(hpNatRule, "MASQ LOCAL HOST", enable); err != nil {
+ return err
+ }
+ }
+
+ // Set Inter Container Communication.
+ if err := setIcc(bridgeIface, icc, enable); err != nil {
+ return err
+ }
+
+ // Set Accept on all non-intercontainer outgoing packets.
+ if err := programChainRule(outRule, "ACCEPT NON_ICC OUTGOING", enable); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func programChainRule(rule iptRule, ruleDescr string, insert bool) error {
+ var (
+ prefix []string
+ operation string
+ condition bool
+ doesExist = iptables.Exists(rule.table, rule.chain, rule.args...)
+ )
+
+ if insert {
+ condition = !doesExist
+ prefix = []string{"-I", rule.chain}
+ operation = "enable"
+ } else {
+ condition = doesExist
+ prefix = []string{"-D", rule.chain}
+ operation = "disable"
+ }
+ if rule.preArgs != nil {
+ prefix = append(rule.preArgs, prefix...)
+ }
+
+ if condition {
+ if err := iptables.RawCombinedOutput(append(prefix, rule.args...)...); err != nil {
+ return fmt.Errorf("Unable to %s %s rule: %s", operation, ruleDescr, err.Error())
+ }
+ }
+
+ return nil
+}
+
+func setIcc(bridgeIface string, iccEnable, insert bool) error {
+ var (
+ table = iptables.Filter
+ chain = "FORWARD"
+ args = []string{"-i", bridgeIface, "-o", bridgeIface, "-j"}
+ acceptArgs = append(args, "ACCEPT")
+ dropArgs = append(args, "DROP")
+ )
+
+ if insert {
+ if !iccEnable {
+ iptables.Raw(append([]string{"-D", chain}, acceptArgs...)...)
+
+ if !iptables.Exists(table, chain, dropArgs...) {
+ if err := iptables.RawCombinedOutput(append([]string{"-A", chain}, dropArgs...)...); err != nil {
+ return fmt.Errorf("Unable to prevent intercontainer communication: %s", err.Error())
+ }
+ }
+ } else {
+ iptables.Raw(append([]string{"-D", chain}, dropArgs...)...)
+
+ if !iptables.Exists(table, chain, acceptArgs...) {
+ if err := iptables.RawCombinedOutput(append([]string{"-I", chain}, acceptArgs...)...); err != nil {
+ return fmt.Errorf("Unable to allow intercontainer communication: %s", err.Error())
+ }
+ }
+ }
+ } else {
+ // Remove any ICC rule.
+ if !iccEnable {
+ if iptables.Exists(table, chain, dropArgs...) {
+ iptables.Raw(append([]string{"-D", chain}, dropArgs...)...)
+ }
+ } else {
+ if iptables.Exists(table, chain, acceptArgs...) {
+ iptables.Raw(append([]string{"-D", chain}, acceptArgs...)...)
+ }
+ }
+ }
+
+ return nil
+}
+
+// Control Inter Network Communication. Install/remove only if it is not/is present.
+func setINC(iface1, iface2 string, enable bool) error {
+ var (
+ table = iptables.Filter
+ chain = IsolationChain
+ args = [2][]string{{"-i", iface1, "-o", iface2, "-j", "DROP"}, {"-i", iface2, "-o", iface1, "-j", "DROP"}}
+ )
+
+ if enable {
+ for i := 0; i < 2; i++ {
+ if iptables.Exists(table, chain, args[i]...) {
+ continue
+ }
+ if err := iptables.RawCombinedOutput(append([]string{"-I", chain}, args[i]...)...); err != nil {
+ return fmt.Errorf("unable to add inter-network communication rule: %v", err)
+ }
+ }
+ } else {
+ for i := 0; i < 2; i++ {
+ if !iptables.Exists(table, chain, args[i]...) {
+ continue
+ }
+ if err := iptables.RawCombinedOutput(append([]string{"-D", chain}, args[i]...)...); err != nil {
+ return fmt.Errorf("unable to remove inter-network communication rule: %v", err)
+ }
+ }
+ }
+
+ return nil
+}
+
+func removeIPChains() {
+ for _, chainInfo := range []iptables.ChainInfo{
+ {Name: DockerChain, Table: iptables.Nat},
+ {Name: DockerChain, Table: iptables.Filter},
+ {Name: IsolationChain, Table: iptables.Filter},
+ } {
+ if err := chainInfo.Remove(); err != nil {
+ logrus.Warnf("Failed to remove existing iptables entries in table %s chain %s : %v", chainInfo.Table, chainInfo.Name, err)
+ }
+ }
+}
+
+func setupInternalNetworkRules(bridgeIface string, addr net.Addr, icc, insert bool) error {
+ var (
+ inDropRule = iptRule{table: iptables.Filter, chain: IsolationChain, args: []string{"-i", bridgeIface, "!", "-d", addr.String(), "-j", "DROP"}}
+ outDropRule = iptRule{table: iptables.Filter, chain: IsolationChain, args: []string{"-o", bridgeIface, "!", "-s", addr.String(), "-j", "DROP"}}
+ )
+ if err := programChainRule(inDropRule, "DROP INCOMING", insert); err != nil {
+ return err
+ }
+ if err := programChainRule(outDropRule, "DROP OUTGOING", insert); err != nil {
+ return err
+ }
+ // Set Inter Container Communication.
+ if err := setIcc(bridgeIface, icc, insert); err != nil {
+ return err
+ }
+ return nil
+}
+
+func clearEndpointConnections(nlh *netlink.Handle, ep *bridgeEndpoint) {
+ var ipv4List []net.IP
+ var ipv6List []net.IP
+ if ep.addr != nil {
+ ipv4List = append(ipv4List, ep.addr.IP)
+ }
+ if ep.addrv6 != nil {
+ ipv6List = append(ipv6List, ep.addrv6.IP)
+ }
+ iptables.DeleteConntrackEntries(nlh, ipv4List, ipv6List)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv4.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv4.go
new file mode 100644
index 0000000..7f87072
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv4.go
@@ -0,0 +1,80 @@
+package bridge
+
+import (
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "net"
+ "path/filepath"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/types"
+ "github.com/vishvananda/netlink"
+)
+
+func selectIPv4Address(addresses []netlink.Addr, selector *net.IPNet) (netlink.Addr, error) {
+ if len(addresses) == 0 {
+ return netlink.Addr{}, errors.New("unable to select an address as the address pool is empty")
+ }
+ if selector != nil {
+ for _, addr := range addresses {
+ if selector.Contains(addr.IP) {
+ return addr, nil
+ }
+ }
+ }
+ return addresses[0], nil
+}
+
+func setupBridgeIPv4(config *networkConfiguration, i *bridgeInterface) error {
+ addrv4List, _, err := i.addresses()
+ if err != nil {
+ return fmt.Errorf("failed to retrieve bridge interface addresses: %v", err)
+ }
+
+ addrv4, _ := selectIPv4Address(addrv4List, config.AddressIPv4)
+
+ if !types.CompareIPNet(addrv4.IPNet, config.AddressIPv4) {
+ if addrv4.IPNet != nil {
+ if err := i.nlh.AddrDel(i.Link, &addrv4); err != nil {
+ return fmt.Errorf("failed to remove current ip address from bridge: %v", err)
+ }
+ }
+ logrus.Debugf("Assigning address to bridge interface %s: %s", config.BridgeName, config.AddressIPv4)
+ if err := i.nlh.AddrAdd(i.Link, &netlink.Addr{IPNet: config.AddressIPv4}); err != nil {
+ return &IPv4AddrAddError{IP: config.AddressIPv4, Err: err}
+ }
+ }
+
+ // Store bridge network and default gateway
+ i.bridgeIPv4 = config.AddressIPv4
+ i.gatewayIPv4 = config.AddressIPv4.IP
+
+ return nil
+}
+
+func setupGatewayIPv4(config *networkConfiguration, i *bridgeInterface) error {
+ if !i.bridgeIPv4.Contains(config.DefaultGatewayIPv4) {
+ return &ErrInvalidGateway{}
+ }
+
+ // Store requested default gateway
+ i.gatewayIPv4 = config.DefaultGatewayIPv4
+
+ return nil
+}
+
+func setupLoopbackAdressesRouting(config *networkConfiguration, i *bridgeInterface) error {
+ sysPath := filepath.Join("/proc/sys/net/ipv4/conf", config.BridgeName, "route_localnet")
+ ipv4LoRoutingData, err := ioutil.ReadFile(sysPath)
+ if err != nil {
+ return fmt.Errorf("Cannot read IPv4 local routing setup: %v", err)
+ }
+ // Enable loopback adresses routing only if it isn't already enabled
+ if ipv4LoRoutingData[0] != '1' {
+ if err := ioutil.WriteFile(sysPath, []byte{'1', '\n'}, 0644); err != nil {
+ return fmt.Errorf("Unable to enable local routing for hairpin mode: %v", err)
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv6.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv6.go
new file mode 100644
index 0000000..ee3d753
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_ipv6.go
@@ -0,0 +1,119 @@
+package bridge
+
+import (
+ "fmt"
+ "io/ioutil"
+ "net"
+ "os"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/types"
+ "github.com/vishvananda/netlink"
+)
+
+var bridgeIPv6 *net.IPNet
+
+const (
+ bridgeIPv6Str = "fe80::1/64"
+ ipv6ForwardConfPerm = 0644
+ ipv6ForwardConfDefault = "/proc/sys/net/ipv6/conf/default/forwarding"
+ ipv6ForwardConfAll = "/proc/sys/net/ipv6/conf/all/forwarding"
+)
+
+func init() {
+ // We allow ourselves to panic in this special case because we indicate a
+ // failure to parse a compile-time define constant.
+ var err error
+ if bridgeIPv6, err = types.ParseCIDR(bridgeIPv6Str); err != nil {
+ panic(fmt.Sprintf("Cannot parse default bridge IPv6 address %q: %v", bridgeIPv6Str, err))
+ }
+}
+
+func setupBridgeIPv6(config *networkConfiguration, i *bridgeInterface) error {
+ procFile := "/proc/sys/net/ipv6/conf/" + config.BridgeName + "/disable_ipv6"
+ ipv6BridgeData, err := ioutil.ReadFile(procFile)
+ if err != nil {
+ return fmt.Errorf("Cannot read IPv6 setup for bridge %v: %v", config.BridgeName, err)
+ }
+ // Enable IPv6 on the bridge only if it isn't already enabled
+ if ipv6BridgeData[0] != '0' {
+ if err := ioutil.WriteFile(procFile, []byte{'0', '\n'}, ipv6ForwardConfPerm); err != nil {
+ return fmt.Errorf("Unable to enable IPv6 addresses on bridge: %v", err)
+ }
+ }
+
+ // Store bridge network and default gateway
+ i.bridgeIPv6 = bridgeIPv6
+ i.gatewayIPv6 = i.bridgeIPv6.IP
+
+ if err := i.programIPv6Address(); err != nil {
+ return err
+ }
+
+ if config.AddressIPv6 == nil {
+ return nil
+ }
+
+ // Store the user specified bridge network and network gateway and program it
+ i.bridgeIPv6 = config.AddressIPv6
+ i.gatewayIPv6 = config.AddressIPv6.IP
+
+ if err := i.programIPv6Address(); err != nil {
+ return err
+ }
+
+ // Setting route to global IPv6 subnet
+ logrus.Debugf("Adding route to IPv6 network %s via device %s", config.AddressIPv6.String(), config.BridgeName)
+ err = i.nlh.RouteAdd(&netlink.Route{
+ Scope: netlink.SCOPE_UNIVERSE,
+ LinkIndex: i.Link.Attrs().Index,
+ Dst: config.AddressIPv6,
+ })
+ if err != nil && !os.IsExist(err) {
+ logrus.Errorf("Could not add route to IPv6 network %s via device %s", config.AddressIPv6.String(), config.BridgeName)
+ }
+
+ return nil
+}
+
+func setupGatewayIPv6(config *networkConfiguration, i *bridgeInterface) error {
+ if config.AddressIPv6 == nil {
+ return &ErrInvalidContainerSubnet{}
+ }
+ if !config.AddressIPv6.Contains(config.DefaultGatewayIPv6) {
+ return &ErrInvalidGateway{}
+ }
+
+ // Store requested default gateway
+ i.gatewayIPv6 = config.DefaultGatewayIPv6
+
+ return nil
+}
+
+func setupIPv6Forwarding(config *networkConfiguration, i *bridgeInterface) error {
+ // Get current IPv6 default forwarding setup
+ ipv6ForwardDataDefault, err := ioutil.ReadFile(ipv6ForwardConfDefault)
+ if err != nil {
+ return fmt.Errorf("Cannot read IPv6 default forwarding setup: %v", err)
+ }
+ // Enable IPv6 default forwarding only if it is not already enabled
+ if ipv6ForwardDataDefault[0] != '1' {
+ if err := ioutil.WriteFile(ipv6ForwardConfDefault, []byte{'1', '\n'}, ipv6ForwardConfPerm); err != nil {
+ logrus.Warnf("Unable to enable IPv6 default forwarding: %v", err)
+ }
+ }
+
+ // Get current IPv6 all forwarding setup
+ ipv6ForwardDataAll, err := ioutil.ReadFile(ipv6ForwardConfAll)
+ if err != nil {
+ return fmt.Errorf("Cannot read IPv6 all forwarding setup: %v", err)
+ }
+ // Enable IPv6 all forwarding only if it is not already enabled
+ if ipv6ForwardDataAll[0] != '1' {
+ if err := ioutil.WriteFile(ipv6ForwardConfAll, []byte{'1', '\n'}, ipv6ForwardConfPerm); err != nil {
+ logrus.Warnf("Unable to enable IPv6 all forwarding: %v", err)
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/bridge/setup_verify.go b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_verify.go
new file mode 100644
index 0000000..330a5b4
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/bridge/setup_verify.go
@@ -0,0 +1,73 @@
+package bridge
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/ns"
+ "github.com/docker/libnetwork/types"
+ "github.com/vishvananda/netlink"
+)
+
+func setupVerifyAndReconcile(config *networkConfiguration, i *bridgeInterface) error {
+ // Fetch a slice of IPv4 addresses and a slice of IPv6 addresses from the bridge.
+ addrsv4, addrsv6, err := i.addresses()
+ if err != nil {
+ return fmt.Errorf("Failed to verify ip addresses: %v", err)
+ }
+
+ addrv4, _ := selectIPv4Address(addrsv4, config.AddressIPv4)
+
+ // Verify that the bridge does have an IPv4 address.
+ if addrv4.IPNet == nil {
+ return &ErrNoIPAddr{}
+ }
+
+ // Verify that the bridge IPv4 address matches the requested configuration.
+ if config.AddressIPv4 != nil && !addrv4.IP.Equal(config.AddressIPv4.IP) {
+ return &IPv4AddrNoMatchError{IP: addrv4.IP, CfgIP: config.AddressIPv4.IP}
+ }
+
+ // Verify that one of the bridge IPv6 addresses matches the requested
+ // configuration.
+ if config.EnableIPv6 && !findIPv6Address(netlink.Addr{IPNet: bridgeIPv6}, addrsv6) {
+ return (*IPv6AddrNoMatchError)(bridgeIPv6)
+ }
+
+ // Release any residual IPv6 address that might be there because of older daemon instances
+ for _, addrv6 := range addrsv6 {
+ if addrv6.IP.IsGlobalUnicast() && !types.CompareIPNet(addrv6.IPNet, i.bridgeIPv6) {
+ if err := i.nlh.AddrDel(i.Link, &addrv6); err != nil {
+ logrus.Warnf("Failed to remove residual IPv6 address %s from bridge: %v", addrv6.IPNet, err)
+ }
+ }
+ }
+
+ return nil
+}
+
+func findIPv6Address(addr netlink.Addr, addresses []netlink.Addr) bool {
+ for _, addrv6 := range addresses {
+ if addrv6.String() == addr.String() {
+ return true
+ }
+ }
+ return false
+}
+
+func bridgeInterfaceExists(name string) (bool, error) {
+ nlh := ns.NlHandle()
+ link, err := nlh.LinkByName(name)
+ if err != nil {
+ if strings.Contains(err.Error(), "Link not found") {
+ return false, nil
+ }
+ return false, fmt.Errorf("failed to check bridge interface existence: %v", err)
+ }
+
+ if link.Type() == "bridge" {
+ return true, nil
+ }
+ return false, fmt.Errorf("existing interface %s is not a bridge", name)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/host/host.go b/vendor/github.com/docker/libnetwork/drivers/host/host.go
new file mode 100644
index 0000000..a71d461
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/host/host.go
@@ -0,0 +1,106 @@
+package host
+
+import (
+ "sync"
+
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/types"
+)
+
+const networkType = "host"
+
+type driver struct {
+ network string
+ sync.Mutex
+}
+
+// Init registers a new instance of host driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ c := driverapi.Capability{
+ DataScope: datastore.LocalScope,
+ ConnectivityScope: datastore.LocalScope,
+ }
+ return dc.RegisterDriver(networkType, &driver{}, c)
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ d.Lock()
+ defer d.Unlock()
+
+ if d.network != "" {
+ return types.ForbiddenErrorf("only one instance of \"%s\" network is allowed", networkType)
+ }
+
+ d.network = id
+
+ return nil
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ return types.ForbiddenErrorf("network of type \"%s\" cannot be deleted", networkType)
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
+ return nil
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ return nil
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ return make(map[string]interface{}, 0), nil
+}
+
+// Join method is invoked when a Sandbox is attached to an endpoint.
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ return nil
+}
+
+// Leave method is invoked when a Sandbox detaches from an endpoint.
+func (d *driver) Leave(nid, eid string) error {
+ return nil
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ return nil
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ return nil
+}
+
+func (d *driver) Type() string {
+ return networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan.go
new file mode 100644
index 0000000..c64ad55
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan.go
@@ -0,0 +1,115 @@
+package ipvlan
+
+import (
+ "net"
+ "sync"
+
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ vethLen = 7
+ containerVethPrefix = "eth"
+ vethPrefix = "veth"
+ ipvlanType = "ipvlan" // driver type name
+ modeL2 = "l2" // ipvlan mode l2 is the default
+ modeL3 = "l3" // ipvlan L3 mode
+ parentOpt = "parent" // parent interface -o parent
+ modeOpt = "_mode" // ipvlan mode ux opt suffix
+)
+
+var driverModeOpt = ipvlanType + modeOpt // mode -o ipvlan_mode
+
+type endpointTable map[string]*endpoint
+
+type networkTable map[string]*network
+
+type driver struct {
+ networks networkTable
+ sync.Once
+ sync.Mutex
+ store datastore.DataStore
+}
+
+type endpoint struct {
+ id string
+ nid string
+ mac net.HardwareAddr
+ addr *net.IPNet
+ addrv6 *net.IPNet
+ srcName string
+ dbIndex uint64
+ dbExists bool
+}
+
+type network struct {
+ id string
+ sbox osl.Sandbox
+ endpoints endpointTable
+ driver *driver
+ config *configuration
+ sync.Mutex
+}
+
+// Init initializes and registers the libnetwork ipvlan driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ c := driverapi.Capability{
+ DataScope: datastore.LocalScope,
+ ConnectivityScope: datastore.GlobalScope,
+ }
+ d := &driver{
+ networks: networkTable{},
+ }
+ d.initStore(config)
+
+ return dc.RegisterDriver(ipvlanType, d, c)
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ return make(map[string]interface{}, 0), nil
+}
+
+func (d *driver) Type() string {
+ return ipvlanType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ return nil
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ return nil
+}
+
+// DiscoverNew is a notification for a new discovery event.
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+// DiscoverDelete is a notification for a discovery delete event.
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_endpoint.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_endpoint.go
new file mode 100644
index 0000000..d30aeac
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_endpoint.go
@@ -0,0 +1,87 @@
+package ipvlan
+
+import (
+ "fmt"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/ns"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/types"
+)
+
+// CreateEndpoint assigns the mac, ip and endpoint id for the new container
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo,
+ epOptions map[string]interface{}) error {
+ defer osl.InitOSContext()()
+
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+ n, err := d.getNetwork(nid)
+ if err != nil {
+ return fmt.Errorf("network id %q not found", nid)
+ }
+ if ifInfo.MacAddress() != nil {
+ return fmt.Errorf("%s interfaces do not support custom mac address assigment", ipvlanType)
+ }
+ ep := &endpoint{
+ id: eid,
+ nid: nid,
+ addr: ifInfo.Address(),
+ addrv6: ifInfo.AddressIPv6(),
+ }
+ if ep.addr == nil {
+ return fmt.Errorf("create endpoint was not passed an IP address")
+ }
+ // disallow port mapping -p
+ if opt, ok := epOptions[netlabel.PortMap]; ok {
+ if _, ok := opt.([]types.PortBinding); ok {
+ if len(opt.([]types.PortBinding)) > 0 {
+ logrus.Warnf("%s driver does not support port mappings", ipvlanType)
+ }
+ }
+ }
+ // disallow port exposure --expose
+ if opt, ok := epOptions[netlabel.ExposedPorts]; ok {
+ if _, ok := opt.([]types.TransportPort); ok {
+ if len(opt.([]types.TransportPort)) > 0 {
+ logrus.Warnf("%s driver does not support port exposures", ipvlanType)
+ }
+ }
+ }
+
+ if err := d.storeUpdate(ep); err != nil {
+ return fmt.Errorf("failed to save ipvlan endpoint %s to store: %v", ep.id[0:7], err)
+ }
+
+ n.addEndpoint(ep)
+
+ return nil
+}
+
+// DeleteEndpoint remove the endpoint and associated netlink interface
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ defer osl.InitOSContext()()
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+ n := d.network(nid)
+ if n == nil {
+ return fmt.Errorf("network id %q not found", nid)
+ }
+ ep := n.endpoint(eid)
+ if ep == nil {
+ return fmt.Errorf("endpoint id %q not found", eid)
+ }
+ if link, err := ns.NlHandle().LinkByName(ep.srcName); err == nil {
+ ns.NlHandle().LinkDel(link)
+ }
+
+ if err := d.storeDelete(ep); err != nil {
+ logrus.Warnf("Failed to remove ipvlan endpoint %s from store: %v", ep.id[0:7], err)
+ }
+ n.deleteEndpoint(ep.id)
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_joinleave.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_joinleave.go
new file mode 100644
index 0000000..0c08dfc
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_joinleave.go
@@ -0,0 +1,199 @@
+package ipvlan
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/netutils"
+ "github.com/docker/libnetwork/ns"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/types"
+)
+
+type staticRoute struct {
+ Destination *net.IPNet
+ RouteType int
+ NextHop net.IP
+}
+
+const (
+ defaultV4RouteCidr = "0.0.0.0/0"
+ defaultV6RouteCidr = "::/0"
+)
+
+// Join method is invoked when a Sandbox is attached to an endpoint.
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ defer osl.InitOSContext()()
+ n, err := d.getNetwork(nid)
+ if err != nil {
+ return err
+ }
+ endpoint := n.endpoint(eid)
+ if endpoint == nil {
+ return fmt.Errorf("could not find endpoint with id %s", eid)
+ }
+ // generate a name for the iface that will be renamed to eth0 in the sbox
+ containerIfName, err := netutils.GenerateIfaceName(ns.NlHandle(), vethPrefix, vethLen)
+ if err != nil {
+ return fmt.Errorf("error generating an interface name: %v", err)
+ }
+ // create the netlink ipvlan interface
+ vethName, err := createIPVlan(containerIfName, n.config.Parent, n.config.IpvlanMode)
+ if err != nil {
+ return err
+ }
+ // bind the generated iface name to the endpoint
+ endpoint.srcName = vethName
+ ep := n.endpoint(eid)
+ if ep == nil {
+ return fmt.Errorf("could not find endpoint with id %s", eid)
+ }
+ if n.config.IpvlanMode == modeL3 {
+ // disable gateway services to add a default gw using dev eth0 only
+ jinfo.DisableGatewayService()
+ defaultRoute, err := ifaceGateway(defaultV4RouteCidr)
+ if err != nil {
+ return err
+ }
+ if err := jinfo.AddStaticRoute(defaultRoute.Destination, defaultRoute.RouteType, defaultRoute.NextHop); err != nil {
+ return fmt.Errorf("failed to set an ipvlan l3 mode ipv4 default gateway: %v", err)
+ }
+ logrus.Debugf("Ipvlan Endpoint Joined with IPv4_Addr: %s, Ipvlan_Mode: %s, Parent: %s",
+ ep.addr.IP.String(), n.config.IpvlanMode, n.config.Parent)
+ // If the endpoint has a v6 address, set a v6 default route
+ if ep.addrv6 != nil {
+ default6Route, err := ifaceGateway(defaultV6RouteCidr)
+ if err != nil {
+ return err
+ }
+ if err = jinfo.AddStaticRoute(default6Route.Destination, default6Route.RouteType, default6Route.NextHop); err != nil {
+ return fmt.Errorf("failed to set an ipvlan l3 mode ipv6 default gateway: %v", err)
+ }
+ logrus.Debugf("Ipvlan Endpoint Joined with IPv6_Addr: %s, Ipvlan_Mode: %s, Parent: %s",
+ ep.addrv6.IP.String(), n.config.IpvlanMode, n.config.Parent)
+ }
+ }
+ if n.config.IpvlanMode == modeL2 {
+ // parse and correlate the endpoint v4 address with the available v4 subnets
+ if len(n.config.Ipv4Subnets) > 0 {
+ s := n.getSubnetforIPv4(ep.addr)
+ if s == nil {
+ return fmt.Errorf("could not find a valid ipv4 subnet for endpoint %s", eid)
+ }
+ v4gw, _, err := net.ParseCIDR(s.GwIP)
+ if err != nil {
+ return fmt.Errorf("gatway %s is not a valid ipv4 address: %v", s.GwIP, err)
+ }
+ err = jinfo.SetGateway(v4gw)
+ if err != nil {
+ return err
+ }
+ logrus.Debugf("Ipvlan Endpoint Joined with IPv4_Addr: %s, Gateway: %s, Ipvlan_Mode: %s, Parent: %s",
+ ep.addr.IP.String(), v4gw.String(), n.config.IpvlanMode, n.config.Parent)
+ }
+ // parse and correlate the endpoint v6 address with the available v6 subnets
+ if len(n.config.Ipv6Subnets) > 0 {
+ s := n.getSubnetforIPv6(ep.addrv6)
+ if s == nil {
+ return fmt.Errorf("could not find a valid ipv6 subnet for endpoint %s", eid)
+ }
+ v6gw, _, err := net.ParseCIDR(s.GwIP)
+ if err != nil {
+ return fmt.Errorf("gatway %s is not a valid ipv6 address: %v", s.GwIP, err)
+ }
+ err = jinfo.SetGatewayIPv6(v6gw)
+ if err != nil {
+ return err
+ }
+ logrus.Debugf("Ipvlan Endpoint Joined with IPv6_Addr: %s, Gateway: %s, Ipvlan_Mode: %s, Parent: %s",
+ ep.addrv6.IP.String(), v6gw.String(), n.config.IpvlanMode, n.config.Parent)
+ }
+ }
+ iNames := jinfo.InterfaceName()
+ err = iNames.SetNames(vethName, containerVethPrefix)
+ if err != nil {
+ return err
+ }
+ if err = d.storeUpdate(ep); err != nil {
+ return fmt.Errorf("failed to save ipvlan endpoint %s to store: %v", ep.id[0:7], err)
+ }
+
+ return nil
+}
+
+// Leave method is invoked when a Sandbox detaches from an endpoint.
+func (d *driver) Leave(nid, eid string) error {
+ defer osl.InitOSContext()()
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return err
+ }
+ endpoint, err := network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+ if endpoint == nil {
+ return fmt.Errorf("could not find endpoint with id %s", eid)
+ }
+
+ return nil
+}
+
+// ifaceGateway returns a static route for either v4/v6 to be set to the container eth0
+func ifaceGateway(dfNet string) (*staticRoute, error) {
+ nh, dst, err := net.ParseCIDR(dfNet)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse default route %v", err)
+ }
+ defaultRoute := &staticRoute{
+ Destination: dst,
+ RouteType: types.CONNECTED,
+ NextHop: nh,
+ }
+
+ return defaultRoute, nil
+}
+
+// getSubnetforIPv4 returns the ipv4 subnet to which the given IP belongs
+func (n *network) getSubnetforIPv4(ip *net.IPNet) *ipv4Subnet {
+ for _, s := range n.config.Ipv4Subnets {
+ _, snet, err := net.ParseCIDR(s.SubnetIP)
+ if err != nil {
+ return nil
+ }
+ // first check if the mask lengths are the same
+ i, _ := snet.Mask.Size()
+ j, _ := ip.Mask.Size()
+ if i != j {
+ continue
+ }
+ if snet.Contains(ip.IP) {
+ return s
+ }
+ }
+
+ return nil
+}
+
+// getSubnetforIPv6 returns the ipv6 subnet to which the given IP belongs
+func (n *network) getSubnetforIPv6(ip *net.IPNet) *ipv6Subnet {
+ for _, s := range n.config.Ipv6Subnets {
+ _, snet, err := net.ParseCIDR(s.SubnetIP)
+ if err != nil {
+ return nil
+ }
+ // first check if the mask lengths are the same
+ i, _ := snet.Mask.Size()
+ j, _ := ip.Mask.Size()
+ if i != j {
+ continue
+ }
+ if snet.Contains(ip.IP) {
+ return s
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_network.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_network.go
new file mode 100644
index 0000000..801fc20
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_network.go
@@ -0,0 +1,250 @@
+package ipvlan
+
+import (
+ "fmt"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/parsers/kernel"
+ "github.com/docker/docker/pkg/stringid"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/ns"
+ "github.com/docker/libnetwork/options"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/types"
+)
+
+// CreateNetwork the network for the specified driver type
+func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ defer osl.InitOSContext()()
+ kv, err := kernel.GetKernelVersion()
+ if err != nil {
+ return fmt.Errorf("Failed to check kernel version for %s driver support: %v", ipvlanType, err)
+ }
+ // ensure Kernel version is >= v4.2 for ipvlan support
+ if kv.Kernel < ipvlanKernelVer || (kv.Kernel == ipvlanKernelVer && kv.Major < ipvlanMajorVer) {
+ return fmt.Errorf("kernel version failed to meet the minimum ipvlan kernel requirement of %d.%d, found %d.%d.%d",
+ ipvlanKernelVer, ipvlanMajorVer, kv.Kernel, kv.Major, kv.Minor)
+ }
+ // reject a null v4 network
+ if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
+ return fmt.Errorf("ipv4 pool is empty")
+ }
+ // parse and validate the config and bind to networkConfiguration
+ config, err := parseNetworkOptions(nid, option)
+ if err != nil {
+ return err
+ }
+ config.ID = nid
+ err = config.processIPAM(nid, ipV4Data, ipV6Data)
+ if err != nil {
+ return err
+ }
+ // verify the ipvlan mode from -o ipvlan_mode option
+ switch config.IpvlanMode {
+ case "", modeL2:
+ // default to ipvlan L2 mode if -o ipvlan_mode is empty
+ config.IpvlanMode = modeL2
+ case modeL3:
+ config.IpvlanMode = modeL3
+ default:
+ return fmt.Errorf("requested ipvlan mode '%s' is not valid, 'l2' mode is the ipvlan driver default", config.IpvlanMode)
+ }
+ // loopback is not a valid parent link
+ if config.Parent == "lo" {
+ return fmt.Errorf("loopback interface is not a valid %s parent link", ipvlanType)
+ }
+ // if parent interface not specified, create a dummy type link to use named dummy+net_id
+ if config.Parent == "" {
+ config.Parent = getDummyName(stringid.TruncateID(config.ID))
+ // empty parent and --internal are handled the same. Set here to update k/v
+ config.Internal = true
+ }
+ err = d.createNetwork(config)
+ if err != nil {
+ return err
+ }
+ // update persistent db, rollback on fail
+ err = d.storeUpdate(config)
+ if err != nil {
+ d.deleteNetwork(config.ID)
+ logrus.Debugf("encoutered an error rolling back a network create for %s : %v", config.ID, err)
+ return err
+ }
+
+ return nil
+}
+
+// createNetwork is used by new network callbacks and persistent network cache
+func (d *driver) createNetwork(config *configuration) error {
+ networkList := d.getNetworks()
+ for _, nw := range networkList {
+ if config.Parent == nw.config.Parent {
+ return fmt.Errorf("network %s is already using parent interface %s",
+ getDummyName(stringid.TruncateID(nw.config.ID)), config.Parent)
+ }
+ }
+ if !parentExists(config.Parent) {
+ // if the --internal flag is set, create a dummy link
+ if config.Internal {
+ err := createDummyLink(config.Parent, getDummyName(stringid.TruncateID(config.ID)))
+ if err != nil {
+ return err
+ }
+ config.CreatedSlaveLink = true
+ // notify the user in logs they have limited comunicatins
+ if config.Parent == getDummyName(stringid.TruncateID(config.ID)) {
+ logrus.Debugf("Empty -o parent= and --internal flags limit communications to other containers inside of network: %s",
+ config.Parent)
+ }
+ } else {
+ // if the subinterface parent_iface.vlan_id checks do not pass, return err.
+ // a valid example is 'eth0.10' for a parent iface 'eth0' with a vlan id '10'
+ err := createVlanLink(config.Parent)
+ if err != nil {
+ return err
+ }
+ // if driver created the networks slave link, record it for future deletion
+ config.CreatedSlaveLink = true
+ }
+ }
+ n := &network{
+ id: config.ID,
+ driver: d,
+ endpoints: endpointTable{},
+ config: config,
+ }
+ // add the *network
+ d.addNetwork(n)
+
+ return nil
+}
+
+// DeleteNetwork the network for the specified driver type
+func (d *driver) DeleteNetwork(nid string) error {
+ defer osl.InitOSContext()()
+ n := d.network(nid)
+ if n == nil {
+ return fmt.Errorf("network id %s not found", nid)
+ }
+ // if the driver created the slave interface, delete it, otherwise leave it
+ if ok := n.config.CreatedSlaveLink; ok {
+ // if the interface exists, only delete if it matches iface.vlan or dummy.net_id naming
+ if ok := parentExists(n.config.Parent); ok {
+ // only delete the link if it is named the net_id
+ if n.config.Parent == getDummyName(stringid.TruncateID(nid)) {
+ err := delDummyLink(n.config.Parent)
+ if err != nil {
+ logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v",
+ n.config.Parent, err)
+ }
+ } else {
+ // only delete the link if it matches iface.vlan naming
+ err := delVlanLink(n.config.Parent)
+ if err != nil {
+ logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v",
+ n.config.Parent, err)
+ }
+ }
+ }
+ }
+ for _, ep := range n.endpoints {
+ if link, err := ns.NlHandle().LinkByName(ep.srcName); err == nil {
+ ns.NlHandle().LinkDel(link)
+ }
+
+ if err := d.storeDelete(ep); err != nil {
+ logrus.Warnf("Failed to remove ipvlan endpoint %s from store: %v", ep.id[0:7], err)
+ }
+ }
+ // delete the *network
+ d.deleteNetwork(nid)
+ // delete the network record from persistent cache
+ err := d.storeDelete(n.config)
+ if err != nil {
+ return fmt.Errorf("error deleting deleting id %s from datastore: %v", nid, err)
+ }
+ return nil
+}
+
+// parseNetworkOptions parse docker network options
+func parseNetworkOptions(id string, option options.Generic) (*configuration, error) {
+ var (
+ err error
+ config = &configuration{}
+ )
+ // parse generic labels first
+ if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
+ if config, err = parseNetworkGenericOptions(genData); err != nil {
+ return nil, err
+ }
+ }
+ // setting the parent to "" will trigger an isolated network dummy parent link
+ if _, ok := option[netlabel.Internal]; ok {
+ config.Internal = true
+ // empty --parent= and --internal are handled the same.
+ config.Parent = ""
+ }
+ return config, nil
+}
+
+// parseNetworkGenericOptions parse generic driver docker network options
+func parseNetworkGenericOptions(data interface{}) (*configuration, error) {
+ var (
+ err error
+ config *configuration
+ )
+ switch opt := data.(type) {
+ case *configuration:
+ config = opt
+ case map[string]string:
+ config = &configuration{}
+ err = config.fromOptions(opt)
+ case options.Generic:
+ var opaqueConfig interface{}
+ if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil {
+ config = opaqueConfig.(*configuration)
+ }
+ default:
+ err = types.BadRequestErrorf("unrecognized network configuration format: %v", opt)
+ }
+ return config, err
+}
+
+// fromOptions binds the generic options to networkConfiguration to cache
+func (config *configuration) fromOptions(labels map[string]string) error {
+ for label, value := range labels {
+ switch label {
+ case parentOpt:
+ // parse driver option '-o parent'
+ config.Parent = value
+ case driverModeOpt:
+ // parse driver option '-o ipvlan_mode'
+ config.IpvlanMode = value
+ }
+ }
+ return nil
+}
+
+// processIPAM parses v4 and v6 IP information and binds it to the network configuration
+func (config *configuration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
+ if len(ipamV4Data) > 0 {
+ for _, ipd := range ipamV4Data {
+ s := &ipv4Subnet{
+ SubnetIP: ipd.Pool.String(),
+ GwIP: ipd.Gateway.String(),
+ }
+ config.Ipv4Subnets = append(config.Ipv4Subnets, s)
+ }
+ }
+ if len(ipamV6Data) > 0 {
+ for _, ipd := range ipamV6Data {
+ s := &ipv6Subnet{
+ SubnetIP: ipd.Pool.String(),
+ GwIP: ipd.Gateway.String(),
+ }
+ config.Ipv6Subnets = append(config.Ipv6Subnets, s)
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_setup.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_setup.go
new file mode 100644
index 0000000..75f0821
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_setup.go
@@ -0,0 +1,205 @@
+package ipvlan
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/ns"
+ "github.com/vishvananda/netlink"
+)
+
+const (
+ dummyPrefix = "di-" // ipvlan prefix for dummy parent interface
+ ipvlanKernelVer = 4 // minimum ipvlan kernel support
+ ipvlanMajorVer = 2 // minimum ipvlan major kernel support
+)
+
+// createIPVlan Create the ipvlan slave specifying the source name
+func createIPVlan(containerIfName, parent, ipvlanMode string) (string, error) {
+ // Set the ipvlan mode. Default is bridge mode
+ mode, err := setIPVlanMode(ipvlanMode)
+ if err != nil {
+ return "", fmt.Errorf("Unsupported %s ipvlan mode: %v", ipvlanMode, err)
+ }
+ // verify the Docker host interface acting as the macvlan parent iface exists
+ if !parentExists(parent) {
+ return "", fmt.Errorf("the requested parent interface %s was not found on the Docker host", parent)
+ }
+ // Get the link for the master index (Example: the docker host eth iface)
+ parentLink, err := ns.NlHandle().LinkByName(parent)
+ if err != nil {
+ return "", fmt.Errorf("error occoured looking up the %s parent iface %s error: %s", ipvlanType, parent, err)
+ }
+ // Create an ipvlan link
+ ipvlan := &netlink.IPVlan{
+ LinkAttrs: netlink.LinkAttrs{
+ Name: containerIfName,
+ ParentIndex: parentLink.Attrs().Index,
+ },
+ Mode: mode,
+ }
+ if err := ns.NlHandle().LinkAdd(ipvlan); err != nil {
+ // If a user creates a macvlan and ipvlan on same parent, only one slave iface can be active at a time.
+ return "", fmt.Errorf("failed to create the %s port: %v", ipvlanType, err)
+ }
+
+ return ipvlan.Attrs().Name, nil
+}
+
+// setIPVlanMode setter for one of the two ipvlan port types
+func setIPVlanMode(mode string) (netlink.IPVlanMode, error) {
+ switch mode {
+ case modeL2:
+ return netlink.IPVLAN_MODE_L2, nil
+ case modeL3:
+ return netlink.IPVLAN_MODE_L3, nil
+ default:
+ return 0, fmt.Errorf("Unknown ipvlan mode: %s", mode)
+ }
+}
+
+// parentExists check if the specified interface exists in the default namespace
+func parentExists(ifaceStr string) bool {
+ _, err := ns.NlHandle().LinkByName(ifaceStr)
+ if err != nil {
+ return false
+ }
+
+ return true
+}
+
+// createVlanLink parses sub-interfaces and vlan id for creation
+func createVlanLink(parentName string) error {
+ if strings.Contains(parentName, ".") {
+ parent, vidInt, err := parseVlan(parentName)
+ if err != nil {
+ return err
+ }
+ // VLAN identifier or VID is a 12-bit field specifying the VLAN to which the frame belongs
+ if vidInt > 4094 || vidInt < 1 {
+ return fmt.Errorf("vlan id must be between 1-4094, received: %d", vidInt)
+ }
+ // get the parent link to attach a vlan subinterface
+ parentLink, err := ns.NlHandle().LinkByName(parent)
+ if err != nil {
+ return fmt.Errorf("failed to find master interface %s on the Docker host: %v", parent, err)
+ }
+ vlanLink := &netlink.Vlan{
+ LinkAttrs: netlink.LinkAttrs{
+ Name: parentName,
+ ParentIndex: parentLink.Attrs().Index,
+ },
+ VlanId: vidInt,
+ }
+ // create the subinterface
+ if err := ns.NlHandle().LinkAdd(vlanLink); err != nil {
+ return fmt.Errorf("failed to create %s vlan link: %v", vlanLink.Name, err)
+ }
+ // Bring the new netlink iface up
+ if err := ns.NlHandle().LinkSetUp(vlanLink); err != nil {
+ return fmt.Errorf("failed to enable %s the ipvlan parent link %v", vlanLink.Name, err)
+ }
+ logrus.Debugf("Added a vlan tagged netlink subinterface: %s with a vlan id: %d", parentName, vidInt)
+ return nil
+ }
+
+ return fmt.Errorf("invalid subinterface vlan name %s, example formatting is eth0.10", parentName)
+}
+
+// delVlanLink verifies only sub-interfaces with a vlan id get deleted
+func delVlanLink(linkName string) error {
+ if strings.Contains(linkName, ".") {
+ _, _, err := parseVlan(linkName)
+ if err != nil {
+ return err
+ }
+ // delete the vlan subinterface
+ vlanLink, err := ns.NlHandle().LinkByName(linkName)
+ if err != nil {
+ return fmt.Errorf("failed to find interface %s on the Docker host : %v", linkName, err)
+ }
+ // verify a parent interface isn't being deleted
+ if vlanLink.Attrs().ParentIndex == 0 {
+ return fmt.Errorf("interface %s does not appear to be a slave device: %v", linkName, err)
+ }
+ // delete the ipvlan slave device
+ if err := ns.NlHandle().LinkDel(vlanLink); err != nil {
+ return fmt.Errorf("failed to delete %s link: %v", linkName, err)
+ }
+ logrus.Debugf("Deleted a vlan tagged netlink subinterface: %s", linkName)
+ }
+ // if the subinterface doesn't parse to iface.vlan_id leave the interface in
+ // place since it could be a user specified name not created by the driver.
+ return nil
+}
+
+// parseVlan parses and verifies a slave interface name: -o parent=eth0.10
+func parseVlan(linkName string) (string, int, error) {
+ // parse -o parent=eth0.10
+ splitName := strings.Split(linkName, ".")
+ if len(splitName) != 2 {
+ return "", 0, fmt.Errorf("required interface name format is: name.vlan_id, ex. eth0.10 for vlan 10, instead received %s", linkName)
+ }
+ parent, vidStr := splitName[0], splitName[1]
+ // validate type and convert vlan id to int
+ vidInt, err := strconv.Atoi(vidStr)
+ if err != nil {
+ return "", 0, fmt.Errorf("unable to parse a valid vlan id from: %s (ex. eth0.10 for vlan 10)", vidStr)
+ }
+ // Check if the interface exists
+ if !parentExists(parent) {
+ return "", 0, fmt.Errorf("-o parent interface does was not found on the host: %s", parent)
+ }
+
+ return parent, vidInt, nil
+}
+
+// createDummyLink creates a dummy0 parent link
+func createDummyLink(dummyName, truncNetID string) error {
+ // create a parent interface since one was not specified
+ parent := &netlink.Dummy{
+ LinkAttrs: netlink.LinkAttrs{
+ Name: dummyName,
+ },
+ }
+ if err := ns.NlHandle().LinkAdd(parent); err != nil {
+ return err
+ }
+ parentDummyLink, err := ns.NlHandle().LinkByName(dummyName)
+ if err != nil {
+ return fmt.Errorf("error occoured looking up the %s parent iface %s error: %s", ipvlanType, dummyName, err)
+ }
+ // bring the new netlink iface up
+ if err := ns.NlHandle().LinkSetUp(parentDummyLink); err != nil {
+ return fmt.Errorf("failed to enable %s the ipvlan parent link: %v", dummyName, err)
+ }
+
+ return nil
+}
+
+// delDummyLink deletes the link type dummy used when -o parent is not passed
+func delDummyLink(linkName string) error {
+ // delete the vlan subinterface
+ dummyLink, err := ns.NlHandle().LinkByName(linkName)
+ if err != nil {
+ return fmt.Errorf("failed to find link %s on the Docker host : %v", linkName, err)
+ }
+ // verify a parent interface is being deleted
+ if dummyLink.Attrs().ParentIndex != 0 {
+ return fmt.Errorf("link %s is not a parent dummy interface", linkName)
+ }
+ // delete the ipvlan dummy device
+ if err := ns.NlHandle().LinkDel(dummyLink); err != nil {
+ return fmt.Errorf("failed to delete the dummy %s link: %v", linkName, err)
+ }
+ logrus.Debugf("Deleted a dummy parent link: %s", linkName)
+
+ return nil
+}
+
+// getDummyName returns the name of a dummy parent with truncated net ID and driver prefix
+func getDummyName(netID string) string {
+ return fmt.Sprintf("%s%s", dummyPrefix, netID)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_state.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_state.go
new file mode 100644
index 0000000..2d8cb2d
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_state.go
@@ -0,0 +1,115 @@
+package ipvlan
+
+import (
+ "fmt"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/types"
+)
+
+func (d *driver) network(nid string) *network {
+ d.Lock()
+ n, ok := d.networks[nid]
+ d.Unlock()
+ if !ok {
+ logrus.Errorf("network id %s not found", nid)
+ }
+
+ return n
+}
+
+func (d *driver) addNetwork(n *network) {
+ d.Lock()
+ d.networks[n.id] = n
+ d.Unlock()
+}
+
+func (d *driver) deleteNetwork(nid string) {
+ d.Lock()
+ delete(d.networks, nid)
+ d.Unlock()
+}
+
+// getNetworks Safely returns a slice of existng networks
+func (d *driver) getNetworks() []*network {
+ d.Lock()
+ defer d.Unlock()
+
+ ls := make([]*network, 0, len(d.networks))
+ for _, nw := range d.networks {
+ ls = append(ls, nw)
+ }
+
+ return ls
+}
+
+func (n *network) endpoint(eid string) *endpoint {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.endpoints[eid]
+}
+
+func (n *network) addEndpoint(ep *endpoint) {
+ n.Lock()
+ n.endpoints[ep.id] = ep
+ n.Unlock()
+}
+
+func (n *network) deleteEndpoint(eid string) {
+ n.Lock()
+ delete(n.endpoints, eid)
+ n.Unlock()
+}
+
+func (n *network) getEndpoint(eid string) (*endpoint, error) {
+ n.Lock()
+ defer n.Unlock()
+ if eid == "" {
+ return nil, fmt.Errorf("endpoint id %s not found", eid)
+ }
+ if ep, ok := n.endpoints[eid]; ok {
+ return ep, nil
+ }
+
+ return nil, nil
+}
+
+func validateID(nid, eid string) error {
+ if nid == "" {
+ return fmt.Errorf("invalid network id")
+ }
+ if eid == "" {
+ return fmt.Errorf("invalid endpoint id")
+ }
+
+ return nil
+}
+
+func (n *network) sandbox() osl.Sandbox {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.sbox
+}
+
+func (n *network) setSandbox(sbox osl.Sandbox) {
+ n.Lock()
+ n.sbox = sbox
+ n.Unlock()
+}
+
+func (d *driver) getNetwork(id string) (*network, error) {
+ d.Lock()
+ defer d.Unlock()
+ if id == "" {
+ return nil, types.BadRequestErrorf("invalid network id: %s", id)
+ }
+
+ if nw, ok := d.networks[id]; ok {
+ return nw, nil
+ }
+
+ return nil, types.NotFoundErrorf("network not found: %s", id)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_store.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_store.go
new file mode 100644
index 0000000..de994fa
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ipvlan_store.go
@@ -0,0 +1,349 @@
+package ipvlan
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ ipvlanPrefix = "ipvlan"
+ ipvlanNetworkPrefix = ipvlanPrefix + "/network"
+ ipvlanEndpointPrefix = ipvlanPrefix + "/endpoint"
+)
+
+// networkConfiguration for this driver's network specific configuration
+type configuration struct {
+ ID string
+ Mtu int
+ dbIndex uint64
+ dbExists bool
+ Internal bool
+ Parent string
+ IpvlanMode string
+ CreatedSlaveLink bool
+ Ipv4Subnets []*ipv4Subnet
+ Ipv6Subnets []*ipv6Subnet
+}
+
+type ipv4Subnet struct {
+ SubnetIP string
+ GwIP string
+}
+
+type ipv6Subnet struct {
+ SubnetIP string
+ GwIP string
+}
+
+// initStore drivers are responsible for caching their own persistent state
+func (d *driver) initStore(option map[string]interface{}) error {
+ if data, ok := option[netlabel.LocalKVClient]; ok {
+ var err error
+ dsc, ok := data.(discoverapi.DatastoreConfigData)
+ if !ok {
+ return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
+ }
+ d.store, err = datastore.NewDataStoreFromConfig(dsc)
+ if err != nil {
+ return types.InternalErrorf("ipvlan driver failed to initialize data store: %v", err)
+ }
+
+ return d.populateNetworks()
+ }
+
+ return nil
+}
+
+// populateNetworks is invoked at driver init to recreate persistently stored networks
+func (d *driver) populateNetworks() error {
+ kvol, err := d.store.List(datastore.Key(ipvlanNetworkPrefix), &configuration{})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ return fmt.Errorf("failed to get ipvlan network configurations from store: %v", err)
+ }
+ // If empty it simply means no ipvlan networks have been created yet
+ if err == datastore.ErrKeyNotFound {
+ return nil
+ }
+ for _, kvo := range kvol {
+ config := kvo.(*configuration)
+ if err = d.createNetwork(config); err != nil {
+ logrus.Warnf("could not create ipvlan network for id %s from persistent state", config.ID)
+ }
+ }
+
+ return nil
+}
+
+func (d *driver) populateEndpoints() error {
+ kvol, err := d.store.List(datastore.Key(ipvlanEndpointPrefix), &endpoint{})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ return fmt.Errorf("failed to get ipvlan endpoints from store: %v", err)
+ }
+
+ if err == datastore.ErrKeyNotFound {
+ return nil
+ }
+
+ for _, kvo := range kvol {
+ ep := kvo.(*endpoint)
+ n, ok := d.networks[ep.nid]
+ if !ok {
+ logrus.Debugf("Network (%s) not found for restored ipvlan endpoint (%s)", ep.nid[0:7], ep.id[0:7])
+ logrus.Debugf("Deleting stale ipvlan endpoint (%s) from store", ep.id[0:7])
+ if err := d.storeDelete(ep); err != nil {
+ logrus.Debugf("Failed to delete stale ipvlan endpoint (%s) from store", ep.id[0:7])
+ }
+ continue
+ }
+ n.endpoints[ep.id] = ep
+ logrus.Debugf("Endpoint (%s) restored to network (%s)", ep.id[0:7], ep.nid[0:7])
+ }
+
+ return nil
+}
+
+// storeUpdate used to update persistent ipvlan network records as they are created
+func (d *driver) storeUpdate(kvObject datastore.KVObject) error {
+ if d.store == nil {
+ logrus.Warnf("ipvlan store not initialized. kv object %s is not added to the store", datastore.Key(kvObject.Key()...))
+ return nil
+ }
+ if err := d.store.PutObjectAtomic(kvObject); err != nil {
+ return fmt.Errorf("failed to update ipvlan store for object type %T: %v", kvObject, err)
+ }
+
+ return nil
+}
+
+// storeDelete used to delete ipvlan network records from persistent cache as they are deleted
+func (d *driver) storeDelete(kvObject datastore.KVObject) error {
+ if d.store == nil {
+ logrus.Debugf("ipvlan store not initialized. kv object %s is not deleted from store", datastore.Key(kvObject.Key()...))
+ return nil
+ }
+retry:
+ if err := d.store.DeleteObjectAtomic(kvObject); err != nil {
+ if err == datastore.ErrKeyModified {
+ if err := d.store.GetObject(datastore.Key(kvObject.Key()...), kvObject); err != nil {
+ return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err)
+ }
+ goto retry
+ }
+ return err
+ }
+
+ return nil
+}
+
+func (config *configuration) MarshalJSON() ([]byte, error) {
+ nMap := make(map[string]interface{})
+ nMap["ID"] = config.ID
+ nMap["Mtu"] = config.Mtu
+ nMap["Parent"] = config.Parent
+ nMap["IpvlanMode"] = config.IpvlanMode
+ nMap["Internal"] = config.Internal
+ nMap["CreatedSubIface"] = config.CreatedSlaveLink
+ if len(config.Ipv4Subnets) > 0 {
+ iis, err := json.Marshal(config.Ipv4Subnets)
+ if err != nil {
+ return nil, err
+ }
+ nMap["Ipv4Subnets"] = string(iis)
+ }
+ if len(config.Ipv6Subnets) > 0 {
+ iis, err := json.Marshal(config.Ipv6Subnets)
+ if err != nil {
+ return nil, err
+ }
+ nMap["Ipv6Subnets"] = string(iis)
+ }
+
+ return json.Marshal(nMap)
+}
+
+func (config *configuration) UnmarshalJSON(b []byte) error {
+ var (
+ err error
+ nMap map[string]interface{}
+ )
+
+ if err = json.Unmarshal(b, &nMap); err != nil {
+ return err
+ }
+ config.ID = nMap["ID"].(string)
+ config.Mtu = int(nMap["Mtu"].(float64))
+ config.Parent = nMap["Parent"].(string)
+ config.IpvlanMode = nMap["IpvlanMode"].(string)
+ config.Internal = nMap["Internal"].(bool)
+ config.CreatedSlaveLink = nMap["CreatedSubIface"].(bool)
+ if v, ok := nMap["Ipv4Subnets"]; ok {
+ if err := json.Unmarshal([]byte(v.(string)), &config.Ipv4Subnets); err != nil {
+ return err
+ }
+ }
+ if v, ok := nMap["Ipv6Subnets"]; ok {
+ if err := json.Unmarshal([]byte(v.(string)), &config.Ipv6Subnets); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (config *configuration) Key() []string {
+ return []string{ipvlanNetworkPrefix, config.ID}
+}
+
+func (config *configuration) KeyPrefix() []string {
+ return []string{ipvlanNetworkPrefix}
+}
+
+func (config *configuration) Value() []byte {
+ b, err := json.Marshal(config)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (config *configuration) SetValue(value []byte) error {
+ return json.Unmarshal(value, config)
+}
+
+func (config *configuration) Index() uint64 {
+ return config.dbIndex
+}
+
+func (config *configuration) SetIndex(index uint64) {
+ config.dbIndex = index
+ config.dbExists = true
+}
+
+func (config *configuration) Exists() bool {
+ return config.dbExists
+}
+
+func (config *configuration) Skip() bool {
+ return false
+}
+
+func (config *configuration) New() datastore.KVObject {
+ return &configuration{}
+}
+
+func (config *configuration) CopyTo(o datastore.KVObject) error {
+ dstNcfg := o.(*configuration)
+ *dstNcfg = *config
+ return nil
+}
+
+func (config *configuration) DataScope() string {
+ return datastore.LocalScope
+}
+
+func (ep *endpoint) MarshalJSON() ([]byte, error) {
+ epMap := make(map[string]interface{})
+ epMap["id"] = ep.id
+ epMap["nid"] = ep.nid
+ epMap["SrcName"] = ep.srcName
+ if len(ep.mac) != 0 {
+ epMap["MacAddress"] = ep.mac.String()
+ }
+ if ep.addr != nil {
+ epMap["Addr"] = ep.addr.String()
+ }
+ if ep.addrv6 != nil {
+ epMap["Addrv6"] = ep.addrv6.String()
+ }
+ return json.Marshal(epMap)
+}
+
+func (ep *endpoint) UnmarshalJSON(b []byte) error {
+ var (
+ err error
+ epMap map[string]interface{}
+ )
+
+ if err = json.Unmarshal(b, &epMap); err != nil {
+ return fmt.Errorf("Failed to unmarshal to ipvlan endpoint: %v", err)
+ }
+
+ if v, ok := epMap["MacAddress"]; ok {
+ if ep.mac, err = net.ParseMAC(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode ipvlan endpoint MAC address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ if v, ok := epMap["Addr"]; ok {
+ if ep.addr, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode ipvlan endpoint IPv4 address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ if v, ok := epMap["Addrv6"]; ok {
+ if ep.addrv6, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode ipvlan endpoint IPv6 address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ ep.id = epMap["id"].(string)
+ ep.nid = epMap["nid"].(string)
+ ep.srcName = epMap["SrcName"].(string)
+
+ return nil
+}
+
+func (ep *endpoint) Key() []string {
+ return []string{ipvlanEndpointPrefix, ep.id}
+}
+
+func (ep *endpoint) KeyPrefix() []string {
+ return []string{ipvlanEndpointPrefix}
+}
+
+func (ep *endpoint) Value() []byte {
+ b, err := json.Marshal(ep)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (ep *endpoint) SetValue(value []byte) error {
+ return json.Unmarshal(value, ep)
+}
+
+func (ep *endpoint) Index() uint64 {
+ return ep.dbIndex
+}
+
+func (ep *endpoint) SetIndex(index uint64) {
+ ep.dbIndex = index
+ ep.dbExists = true
+}
+
+func (ep *endpoint) Exists() bool {
+ return ep.dbExists
+}
+
+func (ep *endpoint) Skip() bool {
+ return false
+}
+
+func (ep *endpoint) New() datastore.KVObject {
+ return &endpoint{}
+}
+
+func (ep *endpoint) CopyTo(o datastore.KVObject) error {
+ dstEp := o.(*endpoint)
+ *dstEp = *ep
+ return nil
+}
+
+func (ep *endpoint) DataScope() string {
+ return datastore.LocalScope
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/ipvlan/ivmanager/ivmanager.go b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ivmanager/ivmanager.go
new file mode 100644
index 0000000..519f1e8
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/ipvlan/ivmanager/ivmanager.go
@@ -0,0 +1,88 @@
+package ivmanager
+
+import (
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/types"
+)
+
+const networkType = "ipvlan"
+
+type driver struct{}
+
+// Init registers a new instance of ipvlan manager driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ c := driverapi.Capability{
+ DataScope: datastore.LocalScope,
+ ConnectivityScope: datastore.GlobalScope,
+ }
+ return dc.RegisterDriver(networkType, &driver{}, c)
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Leave(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Type() string {
+ return networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/macvlan/mvmanager/mvmanager.go b/vendor/github.com/docker/libnetwork/drivers/macvlan/mvmanager/mvmanager.go
new file mode 100644
index 0000000..0f811ac
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/macvlan/mvmanager/mvmanager.go
@@ -0,0 +1,88 @@
+package mvmanager
+
+import (
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/types"
+)
+
+const networkType = "macvlan"
+
+type driver struct{}
+
+// Init registers a new instance of macvlan manager driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ c := driverapi.Capability{
+ DataScope: datastore.LocalScope,
+ ConnectivityScope: datastore.GlobalScope,
+ }
+ return dc.RegisterDriver(networkType, &driver{}, c)
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Leave(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Type() string {
+ return networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/null/null.go b/vendor/github.com/docker/libnetwork/drivers/null/null.go
new file mode 100644
index 0000000..7f2a5e3
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/null/null.go
@@ -0,0 +1,105 @@
+package null
+
+import (
+ "sync"
+
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/types"
+)
+
+const networkType = "null"
+
+type driver struct {
+ network string
+ sync.Mutex
+}
+
+// Init registers a new instance of null driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ c := driverapi.Capability{
+ DataScope: datastore.LocalScope,
+ }
+ return dc.RegisterDriver(networkType, &driver{}, c)
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ d.Lock()
+ defer d.Unlock()
+
+ if d.network != "" {
+ return types.ForbiddenErrorf("only one instance of \"%s\" network is allowed", networkType)
+ }
+
+ d.network = id
+
+ return nil
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ return types.ForbiddenErrorf("network of type \"%s\" cannot be deleted", networkType)
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
+ return nil
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ return nil
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ return make(map[string]interface{}, 0), nil
+}
+
+// Join method is invoked when a Sandbox is attached to an endpoint.
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ return nil
+}
+
+// Leave method is invoked when a Sandbox detaches from an endpoint.
+func (d *driver) Leave(nid, eid string) error {
+ return nil
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ return nil
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ return nil
+}
+
+func (d *driver) Type() string {
+ return networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/overlay/ovmanager/ovmanager.go b/vendor/github.com/docker/libnetwork/drivers/overlay/ovmanager/ovmanager.go
new file mode 100644
index 0000000..3c3c0bb
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/overlay/ovmanager/ovmanager.go
@@ -0,0 +1,257 @@
+package ovmanager
+
+import (
+ "fmt"
+ "net"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/idm"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ networkType = "overlay"
+ vxlanIDStart = 4096
+ vxlanIDEnd = (1 << 24) - 1
+)
+
+type networkTable map[string]*network
+
+type driver struct {
+ config map[string]interface{}
+ networks networkTable
+ store datastore.DataStore
+ vxlanIdm *idm.Idm
+ sync.Mutex
+}
+
+type subnet struct {
+ subnetIP *net.IPNet
+ gwIP *net.IPNet
+ vni uint32
+}
+
+type network struct {
+ id string
+ driver *driver
+ subnets []*subnet
+ sync.Mutex
+}
+
+// Init registers a new instance of overlay driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ var err error
+ c := driverapi.Capability{
+ DataScope: datastore.GlobalScope,
+ ConnectivityScope: datastore.GlobalScope,
+ }
+
+ d := &driver{
+ networks: networkTable{},
+ config: config,
+ }
+
+ d.vxlanIdm, err = idm.New(nil, "vxlan-id", 0, vxlanIDEnd)
+ if err != nil {
+ return fmt.Errorf("failed to initialize vxlan id manager: %v", err)
+ }
+
+ return dc.RegisterDriver(networkType, d, c)
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ if id == "" {
+ return nil, fmt.Errorf("invalid network id for overlay network")
+ }
+
+ if ipV4Data == nil {
+ return nil, fmt.Errorf("empty ipv4 data passed during overlay network creation")
+ }
+
+ n := &network{
+ id: id,
+ driver: d,
+ subnets: []*subnet{},
+ }
+
+ opts := make(map[string]string)
+ vxlanIDList := make([]uint32, 0, len(ipV4Data))
+ for key, val := range option {
+ if key == netlabel.OverlayVxlanIDList {
+ logrus.Debugf("overlay network option: %s", val)
+ valStrList := strings.Split(val, ",")
+ for _, idStr := range valStrList {
+ vni, err := strconv.Atoi(idStr)
+ if err != nil {
+ return nil, fmt.Errorf("invalid vxlan id value %q passed", idStr)
+ }
+
+ vxlanIDList = append(vxlanIDList, uint32(vni))
+ }
+ } else {
+ opts[key] = val
+ }
+ }
+
+ for i, ipd := range ipV4Data {
+ s := &subnet{
+ subnetIP: ipd.Pool,
+ gwIP: ipd.Gateway,
+ }
+
+ if len(vxlanIDList) > i {
+ s.vni = vxlanIDList[i]
+ }
+
+ if err := n.obtainVxlanID(s); err != nil {
+ n.releaseVxlanID()
+ return nil, fmt.Errorf("could not obtain vxlan id for pool %s: %v", s.subnetIP, err)
+ }
+
+ n.subnets = append(n.subnets, s)
+ }
+
+ val := fmt.Sprintf("%d", n.subnets[0].vni)
+ for _, s := range n.subnets[1:] {
+ val = val + fmt.Sprintf(",%d", s.vni)
+ }
+ opts[netlabel.OverlayVxlanIDList] = val
+
+ d.Lock()
+ d.networks[id] = n
+ d.Unlock()
+
+ return opts, nil
+}
+
+func (d *driver) NetworkFree(id string) error {
+ if id == "" {
+ return fmt.Errorf("invalid network id passed while freeing overlay network")
+ }
+
+ d.Lock()
+ n, ok := d.networks[id]
+ d.Unlock()
+
+ if !ok {
+ return fmt.Errorf("overlay network with id %s not found", id)
+ }
+
+ // Release all vxlan IDs in one shot.
+ n.releaseVxlanID()
+
+ d.Lock()
+ delete(d.networks, id)
+ d.Unlock()
+
+ return nil
+}
+
+func (n *network) obtainVxlanID(s *subnet) error {
+ var (
+ err error
+ vni uint64
+ )
+
+ n.Lock()
+ vni = uint64(s.vni)
+ n.Unlock()
+
+ if vni == 0 {
+ vni, err = n.driver.vxlanIdm.GetIDInRange(vxlanIDStart, vxlanIDEnd)
+ if err != nil {
+ return err
+ }
+
+ n.Lock()
+ s.vni = uint32(vni)
+ n.Unlock()
+ return nil
+ }
+
+ return n.driver.vxlanIdm.GetSpecificID(vni)
+}
+
+func (n *network) releaseVxlanID() {
+ n.Lock()
+ vnis := make([]uint32, 0, len(n.subnets))
+ for _, s := range n.subnets {
+ vnis = append(vnis, s.vni)
+ s.vni = 0
+ }
+ n.Unlock()
+
+ for _, vni := range vnis {
+ n.driver.vxlanIdm.Release(uint64(vni))
+ }
+}
+
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+// Join method is invoked when a Sandbox is attached to an endpoint.
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+// Leave method is invoked when a Sandbox detaches from an endpoint.
+func (d *driver) Leave(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Type() string {
+ return networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/remote/api/api.go b/vendor/github.com/docker/libnetwork/drivers/remote/api/api.go
new file mode 100644
index 0000000..d24f190
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/remote/api/api.go
@@ -0,0 +1,221 @@
+/*
+Package api represents all requests and responses suitable for conversation
+with a remote driver.
+*/
+package api
+
+import (
+ "net"
+
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+)
+
+// Response is the basic response structure used in all responses.
+type Response struct {
+ Err string
+}
+
+// GetError returns the error from the response, if any.
+func (r *Response) GetError() string {
+ return r.Err
+}
+
+// GetCapabilityResponse is the response of GetCapability request
+type GetCapabilityResponse struct {
+ Response
+ Scope string
+ ConnectivityScope string
+}
+
+// AllocateNetworkRequest requests allocation of new network by manager
+type AllocateNetworkRequest struct {
+ // A network ID that remote plugins are expected to store for future
+ // reference.
+ NetworkID string
+
+ // A free form map->object interface for communication of options.
+ Options map[string]string
+
+ // IPAMData contains the address pool information for this network
+ IPv4Data, IPv6Data []driverapi.IPAMData
+}
+
+// AllocateNetworkResponse is the response to the AllocateNetworkRequest.
+type AllocateNetworkResponse struct {
+ Response
+ // A free form plugin specific string->string object to be sent in
+ // CreateNetworkRequest call in the libnetwork agents
+ Options map[string]string
+}
+
+// FreeNetworkRequest is the request to free allocated network in the manager
+type FreeNetworkRequest struct {
+ // The ID of the network to be freed.
+ NetworkID string
+}
+
+// FreeNetworkResponse is the response to a request for freeing a network.
+type FreeNetworkResponse struct {
+ Response
+}
+
+// CreateNetworkRequest requests a new network.
+type CreateNetworkRequest struct {
+ // A network ID that remote plugins are expected to store for future
+ // reference.
+ NetworkID string
+
+ // A free form map->object interface for communication of options.
+ Options map[string]interface{}
+
+ // IPAMData contains the address pool information for this network
+ IPv4Data, IPv6Data []driverapi.IPAMData
+}
+
+// CreateNetworkResponse is the response to the CreateNetworkRequest.
+type CreateNetworkResponse struct {
+ Response
+}
+
+// DeleteNetworkRequest is the request to delete an existing network.
+type DeleteNetworkRequest struct {
+ // The ID of the network to delete.
+ NetworkID string
+}
+
+// DeleteNetworkResponse is the response to a request for deleting a network.
+type DeleteNetworkResponse struct {
+ Response
+}
+
+// CreateEndpointRequest is the request to create an endpoint within a network.
+type CreateEndpointRequest struct {
+ // Provided at create time, this will be the network id referenced.
+ NetworkID string
+ // The ID of the endpoint for later reference.
+ EndpointID string
+ Interface *EndpointInterface
+ Options map[string]interface{}
+}
+
+// EndpointInterface represents an interface endpoint.
+type EndpointInterface struct {
+ Address string
+ AddressIPv6 string
+ MacAddress string
+}
+
+// CreateEndpointResponse is the response to the CreateEndpoint action.
+type CreateEndpointResponse struct {
+ Response
+ Interface *EndpointInterface
+}
+
+// Interface is the representation of a linux interface.
+type Interface struct {
+ Address *net.IPNet
+ AddressIPv6 *net.IPNet
+ MacAddress net.HardwareAddr
+}
+
+// DeleteEndpointRequest describes the API for deleting an endpoint.
+type DeleteEndpointRequest struct {
+ NetworkID string
+ EndpointID string
+}
+
+// DeleteEndpointResponse is the response to the DeleteEndpoint action.
+type DeleteEndpointResponse struct {
+ Response
+}
+
+// EndpointInfoRequest retrieves information about the endpoint from the network driver.
+type EndpointInfoRequest struct {
+ NetworkID string
+ EndpointID string
+}
+
+// EndpointInfoResponse is the response to an EndpointInfoRequest.
+type EndpointInfoResponse struct {
+ Response
+ Value map[string]interface{}
+}
+
+// JoinRequest describes the API for joining an endpoint to a sandbox.
+type JoinRequest struct {
+ NetworkID string
+ EndpointID string
+ SandboxKey string
+ Options map[string]interface{}
+}
+
+// InterfaceName is the struct represetation of a pair of devices with source
+// and destination, for the purposes of putting an endpoint into a container.
+type InterfaceName struct {
+ SrcName string
+ DstName string
+ DstPrefix string
+}
+
+// StaticRoute is the plain JSON representation of a static route.
+type StaticRoute struct {
+ Destination string
+ RouteType int
+ NextHop string
+}
+
+// JoinResponse is the response to a JoinRequest.
+type JoinResponse struct {
+ Response
+ InterfaceName *InterfaceName
+ Gateway string
+ GatewayIPv6 string
+ StaticRoutes []StaticRoute
+ DisableGatewayService bool
+}
+
+// LeaveRequest describes the API for detaching an endpoint from a sandbox.
+type LeaveRequest struct {
+ NetworkID string
+ EndpointID string
+}
+
+// LeaveResponse is the answer to LeaveRequest.
+type LeaveResponse struct {
+ Response
+}
+
+// ProgramExternalConnectivityRequest describes the API for programming the external connectivity for the given endpoint.
+type ProgramExternalConnectivityRequest struct {
+ NetworkID string
+ EndpointID string
+ Options map[string]interface{}
+}
+
+// ProgramExternalConnectivityResponse is the answer to ProgramExternalConnectivityRequest.
+type ProgramExternalConnectivityResponse struct {
+ Response
+}
+
+// RevokeExternalConnectivityRequest describes the API for revoking the external connectivity for the given endpoint.
+type RevokeExternalConnectivityRequest struct {
+ NetworkID string
+ EndpointID string
+}
+
+// RevokeExternalConnectivityResponse is the answer to RevokeExternalConnectivityRequest.
+type RevokeExternalConnectivityResponse struct {
+ Response
+}
+
+// DiscoveryNotification represents a discovery notification
+type DiscoveryNotification struct {
+ DiscoveryType discoverapi.DiscoveryType
+ DiscoveryData interface{}
+}
+
+// DiscoveryResponse is used by libnetwork to log any plugin error processing the discovery notifications
+type DiscoveryResponse struct {
+ Response
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/remote/driver.go b/vendor/github.com/docker/libnetwork/drivers/remote/driver.go
new file mode 100644
index 0000000..ffe0730
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/remote/driver.go
@@ -0,0 +1,409 @@
+package remote
+
+import (
+ "errors"
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/plugins"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/drivers/remote/api"
+ "github.com/docker/libnetwork/types"
+)
+
+type driver struct {
+ endpoint *plugins.Client
+ networkType string
+}
+
+type maybeError interface {
+ GetError() string
+}
+
+func newDriver(name string, client *plugins.Client) driverapi.Driver {
+ return &driver{networkType: name, endpoint: client}
+}
+
+// Init makes sure a remote driver is registered when a network driver
+// plugin is activated.
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ newPluginHandler := func(name string, client *plugins.Client) {
+ // negotiate driver capability with client
+ d := newDriver(name, client)
+ c, err := d.(*driver).getCapabilities()
+ if err != nil {
+ logrus.Errorf("error getting capability for %s due to %v", name, err)
+ return
+ }
+ if err = dc.RegisterDriver(name, d, *c); err != nil {
+ logrus.Errorf("error registering driver for %s due to %v", name, err)
+ }
+ }
+
+ // Unit test code is unaware of a true PluginStore. So we fall back to v1 plugins.
+ handleFunc := plugins.Handle
+ if pg := dc.GetPluginGetter(); pg != nil {
+ handleFunc = pg.Handle
+ activePlugins := pg.GetAllManagedPluginsByCap(driverapi.NetworkPluginEndpointType)
+ for _, ap := range activePlugins {
+ newPluginHandler(ap.Name(), ap.Client())
+ }
+ }
+ handleFunc(driverapi.NetworkPluginEndpointType, newPluginHandler)
+
+ return nil
+}
+
+// Get capability from client
+func (d *driver) getCapabilities() (*driverapi.Capability, error) {
+ var capResp api.GetCapabilityResponse
+ if err := d.call("GetCapabilities", nil, &capResp); err != nil {
+ return nil, err
+ }
+
+ c := &driverapi.Capability{}
+ switch capResp.Scope {
+ case "global":
+ c.DataScope = datastore.GlobalScope
+ case "local":
+ c.DataScope = datastore.LocalScope
+ default:
+ return nil, fmt.Errorf("invalid capability: expecting 'local' or 'global', got %s", capResp.Scope)
+ }
+
+ switch capResp.ConnectivityScope {
+ case "global":
+ c.ConnectivityScope = datastore.GlobalScope
+ case "local":
+ c.ConnectivityScope = datastore.LocalScope
+ case "":
+ c.ConnectivityScope = c.DataScope
+ default:
+ return nil, fmt.Errorf("invalid capability: expecting 'local' or 'global', got %s", capResp.Scope)
+ }
+
+ return c, nil
+}
+
+// Config is not implemented for remote drivers, since it is assumed
+// to be supplied to the remote process out-of-band (e.g., as command
+// line arguments).
+func (d *driver) Config(option map[string]interface{}) error {
+ return &driverapi.ErrNotImplemented{}
+}
+
+func (d *driver) call(methodName string, arg interface{}, retVal maybeError) error {
+ method := driverapi.NetworkPluginEndpointType + "." + methodName
+ err := d.endpoint.Call(method, arg, retVal)
+ if err != nil {
+ return err
+ }
+ if e := retVal.GetError(); e != "" {
+ return fmt.Errorf("remote: %s", e)
+ }
+ return nil
+}
+
+func (d *driver) NetworkAllocate(id string, options map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ create := &api.AllocateNetworkRequest{
+ NetworkID: id,
+ Options: options,
+ IPv4Data: ipV4Data,
+ IPv6Data: ipV6Data,
+ }
+ retVal := api.AllocateNetworkResponse{}
+ err := d.call("AllocateNetwork", create, &retVal)
+ return retVal.Options, err
+}
+
+func (d *driver) NetworkFree(id string) error {
+ fr := &api.FreeNetworkRequest{NetworkID: id}
+ return d.call("FreeNetwork", fr, &api.FreeNetworkResponse{})
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+func (d *driver) CreateNetwork(id string, options map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ create := &api.CreateNetworkRequest{
+ NetworkID: id,
+ Options: options,
+ IPv4Data: ipV4Data,
+ IPv6Data: ipV6Data,
+ }
+ return d.call("CreateNetwork", create, &api.CreateNetworkResponse{})
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ delete := &api.DeleteNetworkRequest{NetworkID: nid}
+ return d.call("DeleteNetwork", delete, &api.DeleteNetworkResponse{})
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
+ if ifInfo == nil {
+ return errors.New("must not be called with nil InterfaceInfo")
+ }
+
+ reqIface := &api.EndpointInterface{}
+ if ifInfo.Address() != nil {
+ reqIface.Address = ifInfo.Address().String()
+ }
+ if ifInfo.AddressIPv6() != nil {
+ reqIface.AddressIPv6 = ifInfo.AddressIPv6().String()
+ }
+ if ifInfo.MacAddress() != nil {
+ reqIface.MacAddress = ifInfo.MacAddress().String()
+ }
+
+ create := &api.CreateEndpointRequest{
+ NetworkID: nid,
+ EndpointID: eid,
+ Interface: reqIface,
+ Options: epOptions,
+ }
+ var res api.CreateEndpointResponse
+ if err := d.call("CreateEndpoint", create, &res); err != nil {
+ return err
+ }
+
+ inIface, err := parseInterface(res)
+ if err != nil {
+ return err
+ }
+ if inIface == nil {
+ // Remote driver did not set any field
+ return nil
+ }
+
+ if inIface.MacAddress != nil {
+ if err := ifInfo.SetMacAddress(inIface.MacAddress); err != nil {
+ return errorWithRollback(fmt.Sprintf("driver modified interface MAC address: %v", err), d.DeleteEndpoint(nid, eid))
+ }
+ }
+ if inIface.Address != nil {
+ if err := ifInfo.SetIPAddress(inIface.Address); err != nil {
+ return errorWithRollback(fmt.Sprintf("driver modified interface address: %v", err), d.DeleteEndpoint(nid, eid))
+ }
+ }
+ if inIface.AddressIPv6 != nil {
+ if err := ifInfo.SetIPAddress(inIface.AddressIPv6); err != nil {
+ return errorWithRollback(fmt.Sprintf("driver modified interface address: %v", err), d.DeleteEndpoint(nid, eid))
+ }
+ }
+
+ return nil
+}
+
+func errorWithRollback(msg string, err error) error {
+ rollback := "rolled back"
+ if err != nil {
+ rollback = "failed to roll back: " + err.Error()
+ }
+ return fmt.Errorf("%s; %s", msg, rollback)
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ delete := &api.DeleteEndpointRequest{
+ NetworkID: nid,
+ EndpointID: eid,
+ }
+ return d.call("DeleteEndpoint", delete, &api.DeleteEndpointResponse{})
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ info := &api.EndpointInfoRequest{
+ NetworkID: nid,
+ EndpointID: eid,
+ }
+ var res api.EndpointInfoResponse
+ if err := d.call("EndpointOperInfo", info, &res); err != nil {
+ return nil, err
+ }
+ return res.Value, nil
+}
+
+// Join method is invoked when a Sandbox is attached to an endpoint.
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ join := &api.JoinRequest{
+ NetworkID: nid,
+ EndpointID: eid,
+ SandboxKey: sboxKey,
+ Options: options,
+ }
+ var (
+ res api.JoinResponse
+ err error
+ )
+ if err = d.call("Join", join, &res); err != nil {
+ return err
+ }
+
+ ifaceName := res.InterfaceName
+ if iface := jinfo.InterfaceName(); iface != nil && ifaceName != nil {
+ if err := iface.SetNames(ifaceName.SrcName, ifaceName.DstPrefix); err != nil {
+ return errorWithRollback(fmt.Sprintf("failed to set interface name: %s", err), d.Leave(nid, eid))
+ }
+ }
+
+ var addr net.IP
+ if res.Gateway != "" {
+ if addr = net.ParseIP(res.Gateway); addr == nil {
+ return fmt.Errorf(`unable to parse Gateway "%s"`, res.Gateway)
+ }
+ if jinfo.SetGateway(addr) != nil {
+ return errorWithRollback(fmt.Sprintf("failed to set gateway: %v", addr), d.Leave(nid, eid))
+ }
+ }
+ if res.GatewayIPv6 != "" {
+ if addr = net.ParseIP(res.GatewayIPv6); addr == nil {
+ return fmt.Errorf(`unable to parse GatewayIPv6 "%s"`, res.GatewayIPv6)
+ }
+ if jinfo.SetGatewayIPv6(addr) != nil {
+ return errorWithRollback(fmt.Sprintf("failed to set gateway IPv6: %v", addr), d.Leave(nid, eid))
+ }
+ }
+ if len(res.StaticRoutes) > 0 {
+ routes, err := parseStaticRoutes(res)
+ if err != nil {
+ return err
+ }
+ for _, route := range routes {
+ if jinfo.AddStaticRoute(route.Destination, route.RouteType, route.NextHop) != nil {
+ return errorWithRollback(fmt.Sprintf("failed to set static route: %v", route), d.Leave(nid, eid))
+ }
+ }
+ }
+ if res.DisableGatewayService {
+ jinfo.DisableGatewayService()
+ }
+ return nil
+}
+
+// Leave method is invoked when a Sandbox detaches from an endpoint.
+func (d *driver) Leave(nid, eid string) error {
+ leave := &api.LeaveRequest{
+ NetworkID: nid,
+ EndpointID: eid,
+ }
+ return d.call("Leave", leave, &api.LeaveResponse{})
+}
+
+// ProgramExternalConnectivity is invoked to program the rules to allow external connectivity for the endpoint.
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ data := &api.ProgramExternalConnectivityRequest{
+ NetworkID: nid,
+ EndpointID: eid,
+ Options: options,
+ }
+ err := d.call("ProgramExternalConnectivity", data, &api.ProgramExternalConnectivityResponse{})
+ if err != nil && plugins.IsNotFound(err) {
+ // It is not mandatory yet to support this method
+ return nil
+ }
+ return err
+}
+
+// RevokeExternalConnectivity method is invoked to remove any external connectivity programming related to the endpoint.
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ data := &api.RevokeExternalConnectivityRequest{
+ NetworkID: nid,
+ EndpointID: eid,
+ }
+ err := d.call("RevokeExternalConnectivity", data, &api.RevokeExternalConnectivityResponse{})
+ if err != nil && plugins.IsNotFound(err) {
+ // It is not mandatory yet to support this method
+ return nil
+ }
+ return err
+}
+
+func (d *driver) Type() string {
+ return d.networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return false
+}
+
+// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ if dType != discoverapi.NodeDiscovery {
+ return nil
+ }
+ notif := &api.DiscoveryNotification{
+ DiscoveryType: dType,
+ DiscoveryData: data,
+ }
+ return d.call("DiscoverNew", notif, &api.DiscoveryResponse{})
+}
+
+// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ if dType != discoverapi.NodeDiscovery {
+ return nil
+ }
+ notif := &api.DiscoveryNotification{
+ DiscoveryType: dType,
+ DiscoveryData: data,
+ }
+ return d.call("DiscoverDelete", notif, &api.DiscoveryResponse{})
+}
+
+func parseStaticRoutes(r api.JoinResponse) ([]*types.StaticRoute, error) {
+ var routes = make([]*types.StaticRoute, len(r.StaticRoutes))
+ for i, inRoute := range r.StaticRoutes {
+ var err error
+ outRoute := &types.StaticRoute{RouteType: inRoute.RouteType}
+
+ if inRoute.Destination != "" {
+ if outRoute.Destination, err = types.ParseCIDR(inRoute.Destination); err != nil {
+ return nil, err
+ }
+ }
+
+ if inRoute.NextHop != "" {
+ outRoute.NextHop = net.ParseIP(inRoute.NextHop)
+ if outRoute.NextHop == nil {
+ return nil, fmt.Errorf("failed to parse nexthop IP %s", inRoute.NextHop)
+ }
+ }
+
+ routes[i] = outRoute
+ }
+ return routes, nil
+}
+
+// parseInterfaces validates all the parameters of an Interface and returns them.
+func parseInterface(r api.CreateEndpointResponse) (*api.Interface, error) {
+ var outIf *api.Interface
+
+ inIf := r.Interface
+ if inIf != nil {
+ var err error
+ outIf = &api.Interface{}
+ if inIf.Address != "" {
+ if outIf.Address, err = types.ParseCIDR(inIf.Address); err != nil {
+ return nil, err
+ }
+ }
+ if inIf.AddressIPv6 != "" {
+ if outIf.AddressIPv6, err = types.ParseCIDR(inIf.AddressIPv6); err != nil {
+ return nil, err
+ }
+ }
+ if inIf.MacAddress != "" {
+ if outIf.MacAddress, err = net.ParseMAC(inIf.MacAddress); err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ return outIf, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/bridge.go b/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/bridge.go
new file mode 100644
index 0000000..2547016
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/bridge.go
@@ -0,0 +1,1263 @@
+// +build solaris
+
+package bridge
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "net"
+ "os"
+ "os/exec"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/iptables"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/netutils"
+ "github.com/docker/libnetwork/options"
+ "github.com/docker/libnetwork/portmapper"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ networkType = "bridge"
+
+ // DefaultBridgeName is the default name for the bridge interface managed
+ // by the driver when unspecified by the caller.
+ DefaultBridgeName = "docker0"
+
+ // BridgeName label for bridge driver
+ BridgeName = "com.docker.network.bridge.name"
+
+ // EnableIPMasquerade label for bridge driver
+ EnableIPMasquerade = "com.docker.network.bridge.enable_ip_masquerade"
+
+ // EnableICC label
+ EnableICC = "com.docker.network.bridge.enable_icc"
+
+ // DefaultBindingIP label
+ DefaultBindingIP = "com.docker.network.bridge.host_binding_ipv4"
+
+ // DefaultBridge label
+ DefaultBridge = "com.docker.network.bridge.default_bridge"
+
+ // DefaultGatewayV4AuxKey represents the default-gateway configured by the user
+ DefaultGatewayV4AuxKey = "DefaultGatewayIPv4"
+
+ // DefaultGatewayV6AuxKey represents the ipv6 default-gateway configured by the user
+ DefaultGatewayV6AuxKey = "DefaultGatewayIPv6"
+)
+
+// configuration info for the "bridge" driver.
+type configuration struct {
+ EnableIPForwarding bool
+ EnableIPTables bool
+ EnableUserlandProxy bool
+}
+
+// networkConfiguration for network specific configuration
+type networkConfiguration struct {
+ ID string
+ BridgeName string
+ BridgeNameInternal string
+ EnableIPv6 bool
+ EnableIPMasquerade bool
+ EnableICC bool
+ Mtu int
+ DefaultBindingIntf string
+ DefaultBindingIP net.IP
+ DefaultBridge bool
+ // Internal fields set after ipam data parsing
+ AddressIPv4 *net.IPNet
+ AddressIPv6 *net.IPNet
+ DefaultGatewayIPv4 net.IP
+ DefaultGatewayIPv6 net.IP
+ dbIndex uint64
+ dbExists bool
+ Internal bool
+}
+
+// endpointConfiguration represents the user specified configuration for the sandbox endpoint
+type endpointConfiguration struct {
+ MacAddress net.HardwareAddr
+ PortBindings []types.PortBinding
+ ExposedPorts []types.TransportPort
+}
+
+// containerConfiguration represents the user specified configuration for a container
+type containerConfiguration struct {
+ ParentEndpoints []string
+ ChildEndpoints []string
+}
+
+// cnnectivityConfiguration represents the user specified configuration regarding the external connectivity
+type connectivityConfiguration struct {
+ PortBindings []types.PortBinding
+ ExposedPorts []types.TransportPort
+}
+
+type bridgeEndpoint struct {
+ id string
+ nid string
+ srcName string
+ addr *net.IPNet
+ addrv6 *net.IPNet
+ macAddress net.HardwareAddr
+ config *endpointConfiguration // User specified parameters
+ containerConfig *containerConfiguration
+ extConnConfig *connectivityConfiguration
+ portMapping []types.PortBinding // Operation port bindings
+ dbIndex uint64
+ dbExists bool
+}
+
+type bridgeInterface struct {
+ bridgeIPv4 *net.IPNet
+ bridgeIPv6 *net.IPNet
+ gatewayIPv4 net.IP
+ gatewayIPv6 net.IP
+}
+
+type bridgeNetwork struct {
+ id string
+ bridge *bridgeInterface
+ config *networkConfiguration
+ endpoints map[string]*bridgeEndpoint // key: endpoint id
+ portMapper *portmapper.PortMapper
+ driver *driver // The network's driver
+ sync.Mutex
+}
+
+type driver struct {
+ config *configuration
+ network *bridgeNetwork
+ natChain *iptables.ChainInfo
+ filterChain *iptables.ChainInfo
+ isolationChain *iptables.ChainInfo
+ networks map[string]*bridgeNetwork
+ store datastore.DataStore
+ sync.Mutex
+ defrouteIP net.IP
+}
+
+// New constructs a new bridge driver
+func newDriver() *driver {
+ return &driver{networks: map[string]*bridgeNetwork{}}
+}
+
+// Init registers a new instance of bridge driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ d := newDriver()
+ if err := d.configure(config); err != nil {
+ return err
+ }
+
+ c := driverapi.Capability{
+ DataScope: datastore.LocalScope,
+ ConnectivityScope: datastore.LocalScope,
+ }
+ return dc.RegisterDriver(networkType, d, c)
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
+ return types.BadRequestErrorf("ipv4 pool is empty")
+ }
+ // Sanity checks
+ d.Lock()
+ if _, ok := d.networks[id]; ok {
+ d.Unlock()
+ return types.ForbiddenErrorf("network %s exists", id)
+ }
+ d.Unlock()
+
+ // Parse and validate the config. It should not conflict with existing networks' config
+ config, err := parseNetworkOptions(d, id, option)
+ if err != nil {
+ return err
+ }
+
+ err = config.processIPAM(id, ipV4Data, ipV6Data)
+ if err != nil {
+ return err
+ }
+
+ if err = d.createNetwork(config); err != nil {
+ return err
+ }
+
+ return d.storeUpdate(config)
+}
+
+func newInterface(config *networkConfiguration) *bridgeInterface {
+ i := &bridgeInterface{}
+
+ i.bridgeIPv4 = config.AddressIPv4
+ i.gatewayIPv4 = config.AddressIPv4.IP
+ if config.BridgeName == "" {
+ config.BridgeName = DefaultBridgeName
+ }
+ return i
+}
+
+// This function prunes the pf.conf for the firewall
+// that enable the service successfully.
+func fixPFConf() error {
+ conf := "/etc/firewall/pf.conf"
+ f, err := os.Open("/etc/firewall/pf.conf")
+ if err != nil {
+ return fmt.Errorf("cannot open %s: %v", conf, err)
+ }
+ defer f.Close()
+
+ // Look for line beginning with "REMOVE THIS LINE"
+ modify := false
+ lines := []string{}
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ l := scanner.Text()
+ if strings.Contains(l, "REMOVE THIS LINE") {
+ modify = true
+ continue
+ }
+ lines = append(lines, fmt.Sprintf("%s\n", l))
+ }
+ if err = scanner.Err(); err != nil {
+ return fmt.Errorf("cannot open %s: %v", conf, err)
+ }
+
+ // No changes needed to fix pf.conf
+ if !modify {
+ return nil
+ }
+
+ // Write back the file removing the line found above
+ tmpname := "/etc/firewall/pf.conf.tmp." + strconv.Itoa(os.Getpid())
+ tmp, err := os.OpenFile(tmpname,
+ os.O_CREATE|os.O_TRUNC|os.O_WRONLY|os.O_APPEND, 0644)
+ if err != nil {
+ return fmt.Errorf("cannot open %s: %v", tmpname, err)
+ }
+ defer tmp.Close()
+ for _, l := range lines {
+ _, err = tmp.WriteString(l)
+ if err != nil {
+ return fmt.Errorf("cannot write to %s: %v",
+ tmpname, err)
+ }
+ }
+ if err = tmp.Sync(); err != nil {
+ return fmt.Errorf("cannot sync %s: %v", tmpname, err)
+ }
+ if err = os.Rename(tmpname, conf); err != nil {
+ return fmt.Errorf("cannot rename %s to %s: %v",
+ tmpname, conf, err)
+ }
+ return nil
+}
+
+func (d *driver) initFirewall() error {
+ out, err := exec.Command("/usr/bin/svcs", "-Ho", "state",
+ "firewall").Output()
+ if err != nil {
+ return fmt.Errorf("cannot check firewall state: %v", err)
+ }
+ state := strings.TrimSpace(string(out))
+ if state != "online" {
+ if state != "disabled" {
+ return fmt.Errorf("firewall service is in %s state. "+
+ "please enable service manually.", state)
+ }
+ if err = fixPFConf(); err != nil {
+ return fmt.Errorf("cannot verify pf.conf: %v", err)
+ }
+ err = exec.Command("/usr/sbin/svcadm", "enable", "-ts",
+ "firewall").Run()
+ if err != nil {
+ return fmt.Errorf("cannot enable firewall service: %v", err)
+ }
+ }
+ out, err = exec.Command("/usr/sbin/pfctl", "-sr").Output()
+ if err != nil {
+ return fmt.Errorf("failed to list firewall rules: %v", err)
+ }
+ if strings.Contains(string(out), "anchor \"_auto/docker/*\" all") {
+ return nil
+ }
+ pfctlCmd := "(/usr/sbin/pfctl -sr; " +
+ "/usr/bin/echo \"anchor \\\"_auto/docker/*\\\"\") |" +
+ "/usr/sbin/pfctl -f -"
+ err = exec.Command("/usr/bin/bash", "-c", pfctlCmd).Run()
+ if err != nil {
+ return fmt.Errorf("failed to add docker firewall rules: %v", err)
+ }
+ return nil
+}
+
+func (d *driver) initRouting() error {
+ err := exec.Command("/usr/sbin/ipadm", "set-prop", "-t",
+ "-p", "forwarding=on", "ipv4").Run()
+ if err != nil {
+ return fmt.Errorf("cannot switch-on IP forwarding: %v", err)
+ }
+ routeCmd := "/usr/sbin/ipadm show-addr -p -o addr " +
+ "`/usr/sbin/route get default | /usr/bin/grep interface | " +
+ "/usr/bin/awk '{print $2}'`"
+ out, err := exec.Command("/usr/bin/bash", "-c", routeCmd).Output()
+ if err != nil {
+ return fmt.Errorf("cannot get default route: %v", err)
+ }
+ defroute := strings.SplitN(string(out), "/", 2)
+ d.defrouteIP = net.ParseIP(defroute[0])
+ if d.defrouteIP == nil {
+ return &ErrNoIPAddr{}
+ }
+ return nil
+}
+
+func (d *driver) configure(option map[string]interface{}) error {
+ var err error
+
+ if err = d.initFirewall(); err != nil {
+ return fmt.Errorf("failed to configure firewall: %v", err)
+ }
+ if err = d.initRouting(); err != nil {
+ return fmt.Errorf("failed to configure routing: %v", err)
+ }
+ if err = d.initStore(option); err != nil {
+ return fmt.Errorf("failed to initialize datastore: %v", err)
+ }
+
+ return nil
+}
+
+func (d *driver) getNetwork(id string) (*bridgeNetwork, error) {
+ d.Lock()
+ defer d.Unlock()
+
+ if id == "" {
+ return nil, types.BadRequestErrorf("invalid network id: %s", id)
+ }
+
+ if nw, ok := d.networks[id]; ok {
+ return nw, nil
+ }
+
+ return nil, types.NotFoundErrorf("network not found: %s", id)
+}
+
+// Return a slice of networks over which caller can iterate safely
+func (d *driver) getNetworks() []*bridgeNetwork {
+ d.Lock()
+ defer d.Unlock()
+
+ ls := make([]*bridgeNetwork, 0, len(d.networks))
+ for _, nw := range d.networks {
+ ls = append(ls, nw)
+ }
+ return ls
+}
+
+func bridgeSetup(config *networkConfiguration) error {
+ var err error
+ var bindingIntf string
+
+ bridgeName := config.BridgeName
+ gwName := fmt.Sprintf("%s_gw0", bridgeName)
+ gwIP := config.AddressIPv4.String()
+
+ if config.DefaultBindingIP == nil {
+ // Default to net0 if bindingIP is not provided.
+ bindingIntf = "net0"
+ } else {
+ ipadmCmd := "/usr/sbin/ipadm show-addr -p -o addrobj,addr |" +
+ "/usr/bin/grep " + config.DefaultBindingIP.String()
+ out, err := exec.Command("/usr/bin/bash", "-c", ipadmCmd).Output()
+ if err != nil {
+ logrus.Warn("cannot find binding interface")
+ return err
+ }
+ bindingIntf = strings.SplitN(string(out), "/", 2)[0]
+ if bindingIntf == "" {
+ logrus.Warnf("cannot parse binding interface %s", string(out))
+ return &ErrNoIPAddr{}
+ }
+ }
+ config.DefaultBindingIntf = bindingIntf
+
+ err = exec.Command("/usr/sbin/dladm", "create-etherstub",
+ "-t", config.BridgeNameInternal).Run()
+ if err != nil {
+ logrus.Warnf("cannot create etherstub %s: %+v", config.BridgeNameInternal, err)
+ return err
+ }
+ err = exec.Command("/usr/sbin/dladm", "create-vnic",
+ "-t", "-l", config.BridgeNameInternal, gwName).Run()
+ if err != nil {
+ logrus.Warnf("cannot create vnic %s", gwName)
+ return err
+ }
+ err = exec.Command("/usr/sbin/ifconfig", gwName,
+ "plumb", gwIP, "up").Run()
+ if err != nil {
+ logrus.Warnf("cannot create gateway interface %s on %s",
+ gwIP, gwName)
+ return err
+ }
+
+ tableName := "bridge_nw_subnets"
+ pfAnchor := fmt.Sprintf("_auto/docker/%s", tableName)
+ err = exec.Command("/usr/sbin/pfctl", "-a", pfAnchor, "-t", tableName, "-T", "add", gwIP).Run()
+ if err != nil {
+ logrus.Warnf("cannot add bridge network '%s' to PF table", bridgeName)
+ }
+
+ pfCmd := fmt.Sprintf(
+ "/usr/bin/echo \"pass out on %s from %s:network to any nat-to (%s)\n"+
+ "block in quick from { <%s>, ! %s } to %s\" |"+
+ "/usr/sbin/pfctl -a _auto/docker/%s -f -",
+ bindingIntf, gwName, bindingIntf,
+ tableName, gwIP, gwIP,
+ bridgeName)
+ err = exec.Command("/usr/bin/bash", "-c", pfCmd).Run()
+ if err != nil {
+ logrus.Warnf("cannot add pf rule using: %s", pfCmd)
+ return err
+ }
+
+ return nil
+}
+
+func bridgeCleanup(config *networkConfiguration, logErr bool) {
+ var err error
+
+ bridgeName := config.BridgeName
+ tableName := "bridge_nw_subnets"
+ gwName := fmt.Sprintf("%s_gw0", bridgeName)
+ gwIP := config.AddressIPv4.String()
+ pfAnchor := fmt.Sprintf("_auto/docker/%s", bridgeName)
+ tableAnchor := fmt.Sprintf("_auto/docker/%s", tableName)
+
+ err = exec.Command("/usr/sbin/pfctl", "-a", pfAnchor, "-F", "all").Run()
+ if err != nil && logErr {
+ logrus.Warn("cannot flush firewall rules")
+ }
+ err = exec.Command("/usr/sbin/ifconfig", gwName, "unplumb").Run()
+ if err != nil && logErr {
+ logrus.Warn("cannot remove gateway interface")
+ }
+ err = exec.Command("/usr/sbin/dladm", "delete-vnic",
+ "-t", gwName).Run()
+ if err != nil && logErr {
+ logrus.Warn("cannot delete vnic")
+ }
+ err = exec.Command("/usr/sbin/dladm", "delete-etherstub",
+ "-t", config.BridgeNameInternal).Run()
+ if err != nil && logErr {
+ logrus.Warn("cannot delete etherstub")
+ }
+ err = exec.Command("/usr/sbin/pfctl", "-a", tableAnchor, "-t", tableName, "-T", "delete", gwIP).Run()
+ if err != nil && logErr {
+ logrus.Warnf("cannot remove bridge network '%s' from PF table", bridgeName)
+ }
+}
+
+func (d *driver) createNetwork(config *networkConfiguration) error {
+ var err error
+
+ logrus.Infof("Creating bridge network: %s %s %s", config.ID,
+ config.BridgeName, config.AddressIPv4)
+
+ networkList := d.getNetworks()
+ for i, nw := range networkList {
+ nw.Lock()
+ nwConfig := nw.config
+ nw.Unlock()
+ if err := nwConfig.Conflicts(config); err != nil {
+ if config.DefaultBridge {
+ // We encountered and identified a stale default network
+ // We must delete it as libnetwork is the source of thruth
+ // The default network being created must be the only one
+ // This can happen only from docker 1.12 on ward
+ logrus.Infof("Removing stale default bridge network %s (%s)", nwConfig.ID, nwConfig.BridgeName)
+ if err := d.DeleteNetwork(nwConfig.ID); err != nil {
+ logrus.Warnf("Failed to remove stale default network: %s (%s): %v. Will remove from store.", nwConfig.ID, nwConfig.BridgeName, err)
+ d.storeDelete(nwConfig)
+ }
+ networkList = append(networkList[:i], networkList[i+1:]...)
+ } else {
+ return types.ForbiddenErrorf(
+ "cannot create network %s (%s): "+
+ "conflicts with network %s (%s): %s",
+ nwConfig.BridgeName, config.ID, nw.id,
+ nw.config.BridgeName, err.Error())
+ }
+ }
+ }
+ if config.DefaultBindingIP == nil ||
+ config.DefaultBindingIP.IsUnspecified() {
+ config.DefaultBindingIP = d.defrouteIP
+ }
+
+ // Create and set network handler in driver
+ network := &bridgeNetwork{
+ id: config.ID,
+ endpoints: make(map[string]*bridgeEndpoint),
+ config: config,
+ portMapper: portmapper.New(""),
+ driver: d,
+ }
+
+ d.Lock()
+ d.networks[config.ID] = network
+ d.Unlock()
+
+ // On failure make sure to reset driver network handler to nil
+ defer func() {
+ if err != nil {
+ d.Lock()
+ delete(d.networks, config.ID)
+ d.Unlock()
+ }
+ }()
+
+ // Create or retrieve the bridge L3 interface
+ bridgeIface := newInterface(config)
+ network.bridge = bridgeIface
+
+ // Verify the network configuration does not conflict with previously installed
+ // networks. This step is needed now because driver might have now set the bridge
+ // name on this config struct. And because we need to check for possible address
+ // conflicts, so we need to check against operational networks.
+ if err = config.conflictsWithNetworks(config.ID, networkList); err != nil {
+ return err
+ }
+
+ // We only attempt to create the bridge when the requested device name is
+ // the default one.
+ if config.BridgeName != DefaultBridgeName && config.DefaultBridge {
+ return NonDefaultBridgeExistError(config.BridgeName)
+ }
+
+ bridgeCleanup(config, false)
+ err = bridgeSetup(config)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ var err error
+ // Get network handler and remove it from driver
+ d.Lock()
+ n, ok := d.networks[nid]
+ d.Unlock()
+
+ if !ok {
+ return types.InternalMaskableErrorf("network %s does not exist", nid)
+ }
+ d.Lock()
+ delete(d.networks, nid)
+ d.Unlock()
+
+ // On failure set network handler back in driver, but
+ // only if is not already taken over by some other thread
+ defer func() {
+ if err != nil {
+ d.Lock()
+ if _, ok := d.networks[nid]; !ok {
+ d.networks[nid] = n
+ }
+ d.Unlock()
+ }
+ }()
+
+ // Sanity check
+ if n == nil {
+ err = driverapi.ErrNoNetwork(nid)
+ return err
+ }
+
+ // Cannot remove network if endpoints are still present
+ if len(n.endpoints) != 0 {
+ err = ActiveEndpointsError(n.id)
+ return err
+ }
+ bridgeCleanup(n.config, true)
+ logrus.Infof("Deleting bridge network: %s", nid[:12])
+ return d.storeDelete(n.config)
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
+ if ifInfo == nil {
+ return errors.New("invalid interface passed")
+ }
+
+ // Get the network handler and make sure it exists
+ d.Lock()
+ n, ok := d.networks[nid]
+ d.Unlock()
+
+ if !ok {
+ return types.NotFoundErrorf("network %s does not exist", nid)
+ }
+ if n == nil {
+ return driverapi.ErrNoNetwork(nid)
+ }
+
+ // Sanity check
+ n.Lock()
+ if n.id != nid {
+ n.Unlock()
+ return InvalidNetworkIDError(nid)
+ }
+ n.Unlock()
+
+ // Check if endpoint id is good and retrieve correspondent endpoint
+ ep, err := n.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ // Endpoint with that id exists either on desired or other sandbox
+ if ep != nil {
+ return driverapi.ErrEndpointExists(eid)
+ }
+
+ // Try to convert the options to endpoint configuration
+ epConfig, err := parseEndpointOptions(epOptions)
+ if err != nil {
+ return err
+ }
+
+ // Create and add the endpoint
+ n.Lock()
+ endpoint := &bridgeEndpoint{id: eid, config: epConfig}
+ n.endpoints[eid] = endpoint
+ n.Unlock()
+
+ // On failure make sure to remove the endpoint
+ defer func() {
+ if err != nil {
+ n.Lock()
+ delete(n.endpoints, eid)
+ n.Unlock()
+ }
+ }()
+
+ // Create the sandbox side pipe interface
+ if ifInfo.MacAddress() == nil {
+ // No MAC address assigned to interface. Generate a random MAC to assign
+ endpoint.macAddress = netutils.GenerateRandomMAC()
+ if err := ifInfo.SetMacAddress(endpoint.macAddress); err != nil {
+ logrus.Warnf("Unable to set mac address: %s to endpoint: %s",
+ endpoint.macAddress.String(), endpoint.id)
+ return err
+ }
+ } else {
+ endpoint.macAddress = ifInfo.MacAddress()
+ }
+ endpoint.addr = ifInfo.Address()
+ endpoint.addrv6 = ifInfo.AddressIPv6()
+ c := n.config
+
+ // Program any required port mapping and store them in the endpoint
+ endpoint.portMapping, err = n.allocatePorts(endpoint, c.DefaultBindingIntf, c.DefaultBindingIP, true)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ var err error
+
+ // Get the network handler and make sure it exists
+ d.Lock()
+ n, ok := d.networks[nid]
+ d.Unlock()
+
+ if !ok {
+ return types.InternalMaskableErrorf("network %s does not exist", nid)
+ }
+ if n == nil {
+ return driverapi.ErrNoNetwork(nid)
+ }
+
+ // Sanity Check
+ n.Lock()
+ if n.id != nid {
+ n.Unlock()
+ return InvalidNetworkIDError(nid)
+ }
+ n.Unlock()
+
+ // Check endpoint id and if an endpoint is actually there
+ ep, err := n.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+ if ep == nil {
+ return EndpointNotFoundError(eid)
+ }
+
+ // Remove it
+ n.Lock()
+ delete(n.endpoints, eid)
+ n.Unlock()
+
+ // On failure make sure to set back ep in n.endpoints, but only
+ // if it hasn't been taken over already by some other thread.
+ defer func() {
+ if err != nil {
+ n.Lock()
+ if _, ok := n.endpoints[eid]; !ok {
+ n.endpoints[eid] = ep
+ }
+ n.Unlock()
+ }
+ }()
+
+ err = n.releasePorts(ep)
+ if err != nil {
+ logrus.Warn(err)
+ }
+
+ return nil
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ // Get the network handler and make sure it exists
+ d.Lock()
+ n, ok := d.networks[nid]
+ d.Unlock()
+ if !ok {
+ return nil, types.NotFoundErrorf("network %s does not exist", nid)
+ }
+ if n == nil {
+ return nil, driverapi.ErrNoNetwork(nid)
+ }
+
+ // Sanity check
+ n.Lock()
+ if n.id != nid {
+ n.Unlock()
+ return nil, InvalidNetworkIDError(nid)
+ }
+ n.Unlock()
+
+ // Check if endpoint id is good and retrieve correspondent endpoint
+ ep, err := n.getEndpoint(eid)
+ if err != nil {
+ return nil, err
+ }
+ if ep == nil {
+ return nil, driverapi.ErrNoEndpoint(eid)
+ }
+
+ m := make(map[string]interface{})
+
+ if ep.extConnConfig != nil && ep.extConnConfig.ExposedPorts != nil {
+ // Return a copy of the config data
+ epc := make([]types.TransportPort, 0, len(ep.extConnConfig.ExposedPorts))
+ for _, tp := range ep.extConnConfig.ExposedPorts {
+ epc = append(epc, tp.GetCopy())
+ }
+ m[netlabel.ExposedPorts] = epc
+ }
+
+ if ep.portMapping != nil {
+ // Return a copy of the operational data
+ pmc := make([]types.PortBinding, 0, len(ep.portMapping))
+ for _, pm := range ep.portMapping {
+ pmc = append(pmc, pm.GetCopy())
+ }
+ m[netlabel.PortMap] = pmc
+ }
+
+ if len(ep.macAddress) != 0 {
+ m[netlabel.MacAddress] = ep.macAddress
+ }
+ return m, nil
+}
+
+// Join method is invoked when a Sandbox is attached to an endpoint.
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return err
+ }
+
+ endpoint, err := network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ if endpoint == nil {
+ return EndpointNotFoundError(eid)
+ }
+
+ endpoint.containerConfig, err = parseContainerOptions(options)
+ if err != nil {
+ return err
+ }
+
+ err = jinfo.SetGateway(network.bridge.gatewayIPv4)
+ if err != nil {
+ return err
+ }
+
+ err = jinfo.SetGatewayIPv6(network.bridge.gatewayIPv6)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (d *driver) link(network *bridgeNetwork, endpoint *bridgeEndpoint, enable bool) error {
+ return nil
+}
+
+// Leave method is invoked when a Sandbox detaches from an endpoint.
+func (d *driver) Leave(nid, eid string) error {
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return types.InternalMaskableErrorf("%s", err)
+ }
+
+ endpoint, err := network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ if endpoint == nil {
+ return EndpointNotFoundError(eid)
+ }
+
+ return nil
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return err
+ }
+
+ endpoint, err := network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ if endpoint == nil {
+ return EndpointNotFoundError(eid)
+ }
+
+ endpoint.extConnConfig, err = parseConnectivityOptions(options)
+ if err != nil {
+ return err
+ }
+
+ // Program any required port mapping and store them in the endpoint
+ endpoint.portMapping, err = network.allocatePorts(endpoint, network.config.DefaultBindingIntf, network.config.DefaultBindingIP, true)
+ if err != nil {
+ return err
+ }
+
+ if !network.config.EnableICC {
+ return d.link(network, endpoint, true)
+ }
+
+ return nil
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return err
+ }
+
+ endpoint, err := network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ if endpoint == nil {
+ return EndpointNotFoundError(eid)
+ }
+
+ err = network.releasePorts(endpoint)
+ if err != nil {
+ logrus.Warn(err)
+ }
+
+ return nil
+}
+
+func (d *driver) Type() string {
+ return networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+// Validate performs a static validation on the network configuration parameters.
+// Whatever can be assessed a priori before attempting any programming.
+func (c *networkConfiguration) Validate() error {
+ if c.Mtu < 0 {
+ return ErrInvalidMtu(c.Mtu)
+ }
+
+ // If bridge v4 subnet is specified
+ if c.AddressIPv4 != nil {
+ // If default gw is specified, it must be part of bridge subnet
+ if c.DefaultGatewayIPv4 != nil {
+ if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) {
+ return &ErrInvalidGateway{}
+ }
+ }
+ }
+
+ // If default v6 gw is specified, AddressIPv6 must be specified and gw must belong to AddressIPv6 subnet
+ if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil {
+ if c.AddressIPv6 == nil || !c.AddressIPv6.Contains(c.DefaultGatewayIPv6) {
+ return &ErrInvalidGateway{}
+ }
+ }
+ return nil
+}
+
+// Checks whether this network's configuration for the network with this id conflicts with any of the passed networks
+func (c *networkConfiguration) conflictsWithNetworks(id string, others []*bridgeNetwork) error {
+ for _, nw := range others {
+
+ nw.Lock()
+ nwID := nw.id
+ nwConfig := nw.config
+ nwBridge := nw.bridge
+ nw.Unlock()
+
+ if nwID == id {
+ continue
+ }
+ // Verify the name (which may have been set by newInterface()) does not conflict with
+ // existing bridge interfaces. Ironically the system chosen name gets stored in the config...
+ // Basically we are checking if the two original configs were both empty.
+ if nwConfig.BridgeName == c.BridgeName {
+ return types.ForbiddenErrorf("conflicts with network %s (%s) by bridge name", nwID, nwConfig.BridgeName)
+ }
+ // If this network config specifies the AddressIPv4, we need
+ // to make sure it does not conflict with any previously allocated
+ // bridges. This could not be completely caught by the config conflict
+ // check, because networks which config does not specify the AddressIPv4
+ // get their address and subnet selected by the driver (see electBridgeIPv4())
+ if c.AddressIPv4 != nil {
+ if nwBridge.bridgeIPv4.Contains(c.AddressIPv4.IP) ||
+ c.AddressIPv4.Contains(nwBridge.bridgeIPv4.IP) {
+ return types.ForbiddenErrorf("conflicts with network %s (%s) by ip network", nwID, nwConfig.BridgeName)
+ }
+ }
+ }
+
+ return nil
+}
+
+// Conflicts check if two NetworkConfiguration objects overlap
+func (c *networkConfiguration) Conflicts(o *networkConfiguration) error {
+ if o == nil {
+ return fmt.Errorf("same configuration")
+ }
+
+ // Also empty, because only one network with empty name is allowed
+ if c.BridgeName == o.BridgeName {
+ return fmt.Errorf("networks have same bridge name")
+ }
+
+ // They must be in different subnets
+ if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) &&
+ (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) {
+ return fmt.Errorf("networks have overlapping IPv4")
+ }
+
+ // They must be in different v6 subnets
+ if (c.AddressIPv6 != nil && o.AddressIPv6 != nil) &&
+ (c.AddressIPv6.Contains(o.AddressIPv6.IP) || o.AddressIPv6.Contains(c.AddressIPv6.IP)) {
+ return fmt.Errorf("networks have overlapping IPv6")
+ }
+
+ return nil
+}
+
+func (c *networkConfiguration) fromLabels(labels map[string]string) error {
+ var err error
+ for label, value := range labels {
+ switch label {
+ case BridgeName:
+ c.BridgeName = value
+ case netlabel.DriverMTU:
+ if c.Mtu, err = strconv.Atoi(value); err != nil {
+ return parseErr(label, value, err.Error())
+ }
+ case netlabel.EnableIPv6:
+ if c.EnableIPv6, err = strconv.ParseBool(value); err != nil {
+ return parseErr(label, value, err.Error())
+ }
+ case EnableIPMasquerade:
+ if c.EnableIPMasquerade, err = strconv.ParseBool(value); err != nil {
+ return parseErr(label, value, err.Error())
+ }
+ case EnableICC:
+ if c.EnableICC, err = strconv.ParseBool(value); err != nil {
+ return parseErr(label, value, err.Error())
+ }
+ case DefaultBridge:
+ if c.DefaultBridge, err = strconv.ParseBool(value); err != nil {
+ return parseErr(label, value, err.Error())
+ }
+ case DefaultBindingIP:
+ if c.DefaultBindingIP = net.ParseIP(value); c.DefaultBindingIP == nil {
+ return parseErr(label, value, "nil ip")
+ }
+ }
+ }
+
+ return nil
+}
+
+func parseErr(label, value, errString string) error {
+ return types.BadRequestErrorf("failed to parse %s value: %v (%s)", label, value, errString)
+}
+
+func parseNetworkGenericOptions(data interface{}) (*networkConfiguration, error) {
+ var (
+ err error
+ config *networkConfiguration
+ )
+
+ switch opt := data.(type) {
+ case *networkConfiguration:
+ config = opt
+ case map[string]string:
+ config = &networkConfiguration{
+ EnableICC: true,
+ EnableIPMasquerade: true,
+ }
+ err = config.fromLabels(opt)
+ case options.Generic:
+ var opaqueConfig interface{}
+ if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil {
+ config = opaqueConfig.(*networkConfiguration)
+ }
+ default:
+ err = types.BadRequestErrorf("do not recognize network configuration format: %T", opt)
+ }
+
+ return config, err
+}
+
+func parseNetworkOptions(d *driver, id string, option options.Generic) (*networkConfiguration, error) {
+ var (
+ err error
+ config = &networkConfiguration{}
+ )
+
+ // Parse generic label first, config will be re-assigned
+ if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
+ if config, err = parseNetworkGenericOptions(genData); err != nil {
+ return nil, err
+ }
+ }
+
+ // Process well-known labels next
+ if val, ok := option[netlabel.EnableIPv6]; ok {
+ config.EnableIPv6 = val.(bool)
+ }
+
+ if val, ok := option[netlabel.Internal]; ok {
+ if internal, ok := val.(bool); ok && internal {
+ config.Internal = true
+ }
+ }
+
+ // Finally validate the configuration
+ if err = config.Validate(); err != nil {
+ return nil, err
+ }
+
+ if config.BridgeName == "" && config.DefaultBridge == false {
+ config.BridgeName = "br_" + id[:12] + "_0"
+ }
+
+ lastChar := config.BridgeName[len(config.BridgeName)-1:]
+ if _, err = strconv.Atoi(lastChar); err != nil {
+ config.BridgeNameInternal = config.BridgeName + "_0"
+ } else {
+ config.BridgeNameInternal = config.BridgeName
+ }
+
+ config.ID = id
+ return config, nil
+}
+
+func (c *networkConfiguration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
+ if len(ipamV4Data) > 1 || len(ipamV6Data) > 1 {
+ return types.ForbiddenErrorf("bridge driver doesnt support multiple subnets")
+ }
+
+ if len(ipamV4Data) == 0 {
+ return types.BadRequestErrorf("bridge network %s requires ipv4 configuration", id)
+ }
+
+ if ipamV4Data[0].Gateway != nil {
+ c.AddressIPv4 = types.GetIPNetCopy(ipamV4Data[0].Gateway)
+ }
+
+ if gw, ok := ipamV4Data[0].AuxAddresses[DefaultGatewayV4AuxKey]; ok {
+ c.DefaultGatewayIPv4 = gw.IP
+ }
+
+ if len(ipamV6Data) > 0 {
+ c.AddressIPv6 = ipamV6Data[0].Pool
+
+ if ipamV6Data[0].Gateway != nil {
+ c.AddressIPv6 = types.GetIPNetCopy(ipamV6Data[0].Gateway)
+ }
+
+ if gw, ok := ipamV6Data[0].AuxAddresses[DefaultGatewayV6AuxKey]; ok {
+ c.DefaultGatewayIPv6 = gw.IP
+ }
+ }
+
+ return nil
+}
+
+func (n *bridgeNetwork) getEndpoint(eid string) (*bridgeEndpoint, error) {
+ n.Lock()
+ defer n.Unlock()
+
+ if eid == "" {
+ return nil, InvalidEndpointIDError(eid)
+ }
+
+ if ep, ok := n.endpoints[eid]; ok {
+ return ep, nil
+ }
+
+ return nil, nil
+}
+
+func parseEndpointOptions(epOptions map[string]interface{}) (*endpointConfiguration, error) {
+ if epOptions == nil {
+ return nil, nil
+ }
+
+ ec := &endpointConfiguration{}
+
+ if opt, ok := epOptions[netlabel.MacAddress]; ok {
+ if mac, ok := opt.(net.HardwareAddr); ok {
+ ec.MacAddress = mac
+ } else {
+ return nil, &ErrInvalidEndpointConfig{}
+ }
+ }
+
+ if opt, ok := epOptions[netlabel.PortMap]; ok {
+ if bs, ok := opt.([]types.PortBinding); ok {
+ ec.PortBindings = bs
+ } else {
+ return nil, &ErrInvalidEndpointConfig{}
+ }
+ }
+
+ if opt, ok := epOptions[netlabel.ExposedPorts]; ok {
+ if ports, ok := opt.([]types.TransportPort); ok {
+ ec.ExposedPorts = ports
+ } else {
+ return nil, &ErrInvalidEndpointConfig{}
+ }
+ }
+
+ return ec, nil
+}
+
+func parseContainerOptions(cOptions map[string]interface{}) (*containerConfiguration, error) {
+ if cOptions == nil {
+ return nil, nil
+ }
+ genericData := cOptions[netlabel.GenericData]
+ if genericData == nil {
+ return nil, nil
+ }
+ switch opt := genericData.(type) {
+ case options.Generic:
+ opaqueConfig, err := options.GenerateFromModel(opt, &containerConfiguration{})
+ if err != nil {
+ return nil, err
+ }
+ return opaqueConfig.(*containerConfiguration), nil
+ case *containerConfiguration:
+ return opt, nil
+ default:
+ return nil, nil
+ }
+}
+
+func parseConnectivityOptions(cOptions map[string]interface{}) (*connectivityConfiguration, error) {
+ if cOptions == nil {
+ return nil, nil
+ }
+
+ cc := &connectivityConfiguration{}
+
+ if opt, ok := cOptions[netlabel.PortMap]; ok {
+ if pb, ok := opt.([]types.PortBinding); ok {
+ cc.PortBindings = pb
+ } else {
+ return nil, types.BadRequestErrorf("Invalid port mapping data in connectivity configuration: %v", opt)
+ }
+ }
+
+ if opt, ok := cOptions[netlabel.ExposedPorts]; ok {
+ if ports, ok := opt.([]types.TransportPort); ok {
+ cc.ExposedPorts = ports
+ } else {
+ return nil, types.BadRequestErrorf("Invalid exposed ports data in connectivity configuration: %v", opt)
+ }
+ }
+
+ return cc, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/bridge_store.go b/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/bridge_store.go
new file mode 100644
index 0000000..956e829
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/bridge_store.go
@@ -0,0 +1,384 @@
+// +build solaris
+
+package bridge
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ // network config prefix was not specific enough.
+ // To be backward compatible, need custom endpoint
+ // prefix with different root
+ bridgePrefix = "bridge"
+ bridgeEndpointPrefix = "bridge-endpoint"
+)
+
+func (d *driver) initStore(option map[string]interface{}) error {
+ if data, ok := option[netlabel.LocalKVClient]; ok {
+ var err error
+ dsc, ok := data.(discoverapi.DatastoreConfigData)
+ if !ok {
+ return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
+ }
+ d.store, err = datastore.NewDataStoreFromConfig(dsc)
+ if err != nil {
+ return types.InternalErrorf("bridge driver failed to initialize data store: %v", err)
+ }
+
+ err = d.populateNetworks()
+ if err != nil {
+ return err
+ }
+
+ err = d.populateEndpoints()
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (d *driver) populateNetworks() error {
+ kvol, err := d.store.List(datastore.Key(bridgePrefix), &networkConfiguration{})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ return fmt.Errorf("failed to get bridge network configurations from store: %v", err)
+ }
+
+ // It's normal for network configuration state to be empty. Just return.
+ if err == datastore.ErrKeyNotFound {
+ return nil
+ }
+
+ for _, kvo := range kvol {
+ ncfg := kvo.(*networkConfiguration)
+ if err = d.createNetwork(ncfg); err != nil {
+ logrus.Warnf("could not create bridge network for id %s bridge name %s while booting up from persistent state: %v", ncfg.ID, ncfg.BridgeName, err)
+ }
+ logrus.Debugf("Network (%s) restored", ncfg.ID[0:7])
+ }
+
+ return nil
+}
+
+func (d *driver) populateEndpoints() error {
+ kvol, err := d.store.List(datastore.Key(bridgeEndpointPrefix), &bridgeEndpoint{})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ return fmt.Errorf("failed to get bridge endpoints from store: %v", err)
+ }
+
+ if err == datastore.ErrKeyNotFound {
+ return nil
+ }
+
+ for _, kvo := range kvol {
+ ep := kvo.(*bridgeEndpoint)
+ n, ok := d.networks[ep.nid]
+ if !ok {
+ logrus.Debugf("Network (%s) not found for restored bridge endpoint (%s)", ep.nid[0:7], ep.id[0:7])
+ logrus.Debugf("Deleting stale bridge endpoint (%s) from store", ep.nid[0:7])
+ if err := d.storeDelete(ep); err != nil {
+ logrus.Debugf("Failed to delete stale bridge endpoint (%s) from store", ep.nid[0:7])
+ }
+ continue
+ }
+ n.endpoints[ep.id] = ep
+ n.restorePortAllocations(ep)
+ logrus.Debugf("Endpoint (%s) restored to network (%s)", ep.id[0:7], ep.nid[0:7])
+ }
+
+ return nil
+}
+
+func (d *driver) storeUpdate(kvObject datastore.KVObject) error {
+ if d.store == nil {
+ logrus.Warnf("bridge store not initialized. kv object %s is not added to the store", datastore.Key(kvObject.Key()...))
+ return nil
+ }
+
+ if err := d.store.PutObjectAtomic(kvObject); err != nil {
+ return fmt.Errorf("failed to update bridge store for object type %T: %v", kvObject, err)
+ }
+
+ return nil
+}
+
+func (d *driver) storeDelete(kvObject datastore.KVObject) error {
+ if d.store == nil {
+ logrus.Debugf("bridge store not initialized. kv object %s is not deleted from store", datastore.Key(kvObject.Key()...))
+ return nil
+ }
+
+retry:
+ if err := d.store.DeleteObjectAtomic(kvObject); err != nil {
+ if err == datastore.ErrKeyModified {
+ if err := d.store.GetObject(datastore.Key(kvObject.Key()...), kvObject); err != nil {
+ return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err)
+ }
+ goto retry
+ }
+ return err
+ }
+
+ return nil
+}
+
+func (ncfg *networkConfiguration) MarshalJSON() ([]byte, error) {
+ nMap := make(map[string]interface{})
+ nMap["ID"] = ncfg.ID
+ nMap["BridgeName"] = ncfg.BridgeName
+ nMap["BridgeNameInternal"] = ncfg.BridgeNameInternal
+ nMap["EnableIPv6"] = ncfg.EnableIPv6
+ nMap["EnableIPMasquerade"] = ncfg.EnableIPMasquerade
+ nMap["EnableICC"] = ncfg.EnableICC
+ nMap["Mtu"] = ncfg.Mtu
+ nMap["Internal"] = ncfg.Internal
+ nMap["DefaultBridge"] = ncfg.DefaultBridge
+ nMap["DefaultBindingIP"] = ncfg.DefaultBindingIP.String()
+ nMap["DefaultBindingIntf"] = ncfg.DefaultBindingIntf
+ nMap["DefaultGatewayIPv4"] = ncfg.DefaultGatewayIPv4.String()
+ nMap["DefaultGatewayIPv6"] = ncfg.DefaultGatewayIPv6.String()
+
+ if ncfg.AddressIPv4 != nil {
+ nMap["AddressIPv4"] = ncfg.AddressIPv4.String()
+ }
+
+ if ncfg.AddressIPv6 != nil {
+ nMap["AddressIPv6"] = ncfg.AddressIPv6.String()
+ }
+
+ return json.Marshal(nMap)
+}
+
+func (ncfg *networkConfiguration) UnmarshalJSON(b []byte) error {
+ var (
+ err error
+ nMap map[string]interface{}
+ )
+
+ if err = json.Unmarshal(b, &nMap); err != nil {
+ return err
+ }
+
+ if v, ok := nMap["AddressIPv4"]; ok {
+ if ncfg.AddressIPv4, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode bridge network address IPv4 after json unmarshal: %s", v.(string))
+ }
+ }
+
+ if v, ok := nMap["AddressIPv6"]; ok {
+ if ncfg.AddressIPv6, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode bridge network address IPv6 after json unmarshal: %s", v.(string))
+ }
+ }
+
+ ncfg.DefaultBridge = nMap["DefaultBridge"].(bool)
+ ncfg.DefaultBindingIP = net.ParseIP(nMap["DefaultBindingIP"].(string))
+ ncfg.DefaultBindingIntf = nMap["DefaultBindingIntf"].(string)
+ ncfg.DefaultGatewayIPv4 = net.ParseIP(nMap["DefaultGatewayIPv4"].(string))
+ ncfg.DefaultGatewayIPv6 = net.ParseIP(nMap["DefaultGatewayIPv6"].(string))
+ ncfg.ID = nMap["ID"].(string)
+ ncfg.BridgeName = nMap["BridgeName"].(string)
+ ncfg.BridgeNameInternal = nMap["BridgeNameInternal"].(string)
+ ncfg.EnableIPv6 = nMap["EnableIPv6"].(bool)
+ ncfg.EnableIPMasquerade = nMap["EnableIPMasquerade"].(bool)
+ ncfg.EnableICC = nMap["EnableICC"].(bool)
+ ncfg.Mtu = int(nMap["Mtu"].(float64))
+ if v, ok := nMap["Internal"]; ok {
+ ncfg.Internal = v.(bool)
+ }
+
+ return nil
+}
+
+func (ncfg *networkConfiguration) Key() []string {
+ return []string{bridgePrefix, ncfg.ID}
+}
+
+func (ncfg *networkConfiguration) KeyPrefix() []string {
+ return []string{bridgePrefix}
+}
+
+func (ncfg *networkConfiguration) Value() []byte {
+ b, err := json.Marshal(ncfg)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (ncfg *networkConfiguration) SetValue(value []byte) error {
+ return json.Unmarshal(value, ncfg)
+}
+
+func (ncfg *networkConfiguration) Index() uint64 {
+ return ncfg.dbIndex
+}
+
+func (ncfg *networkConfiguration) SetIndex(index uint64) {
+ ncfg.dbIndex = index
+ ncfg.dbExists = true
+}
+
+func (ncfg *networkConfiguration) Exists() bool {
+ return ncfg.dbExists
+}
+
+func (ncfg *networkConfiguration) Skip() bool {
+ return false
+}
+
+func (ncfg *networkConfiguration) New() datastore.KVObject {
+ return &networkConfiguration{}
+}
+
+func (ncfg *networkConfiguration) CopyTo(o datastore.KVObject) error {
+ dstNcfg := o.(*networkConfiguration)
+ *dstNcfg = *ncfg
+ return nil
+}
+
+func (ncfg *networkConfiguration) DataScope() string {
+ return datastore.LocalScope
+}
+
+func (ep *bridgeEndpoint) MarshalJSON() ([]byte, error) {
+ epMap := make(map[string]interface{})
+ epMap["id"] = ep.id
+ epMap["nid"] = ep.nid
+ epMap["SrcName"] = ep.srcName
+ epMap["MacAddress"] = ep.macAddress.String()
+ epMap["Addr"] = ep.addr.String()
+ if ep.addrv6 != nil {
+ epMap["Addrv6"] = ep.addrv6.String()
+ }
+ epMap["Config"] = ep.config
+ epMap["ContainerConfig"] = ep.containerConfig
+ epMap["ExternalConnConfig"] = ep.extConnConfig
+ epMap["PortMapping"] = ep.portMapping
+
+ return json.Marshal(epMap)
+}
+
+func (ep *bridgeEndpoint) UnmarshalJSON(b []byte) error {
+ var (
+ err error
+ epMap map[string]interface{}
+ )
+
+ if err = json.Unmarshal(b, &epMap); err != nil {
+ return fmt.Errorf("Failed to unmarshal to bridge endpoint: %v", err)
+ }
+
+ if v, ok := epMap["MacAddress"]; ok {
+ if ep.macAddress, err = net.ParseMAC(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode bridge endpoint MAC address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ if v, ok := epMap["Addr"]; ok {
+ if ep.addr, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode bridge endpoint IPv4 address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ if v, ok := epMap["Addrv6"]; ok {
+ if ep.addrv6, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode bridge endpoint IPv6 address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ ep.id = epMap["id"].(string)
+ ep.nid = epMap["nid"].(string)
+ ep.srcName = epMap["SrcName"].(string)
+ d, _ := json.Marshal(epMap["Config"])
+ if err := json.Unmarshal(d, &ep.config); err != nil {
+ logrus.Warnf("Failed to decode endpoint config %v", err)
+ }
+ d, _ = json.Marshal(epMap["ContainerConfig"])
+ if err := json.Unmarshal(d, &ep.containerConfig); err != nil {
+ logrus.Warnf("Failed to decode endpoint container config %v", err)
+ }
+ d, _ = json.Marshal(epMap["ExternalConnConfig"])
+ if err := json.Unmarshal(d, &ep.extConnConfig); err != nil {
+ logrus.Warnf("Failed to decode endpoint external connectivity configuration %v", err)
+ }
+ d, _ = json.Marshal(epMap["PortMapping"])
+ if err := json.Unmarshal(d, &ep.portMapping); err != nil {
+ logrus.Warnf("Failed to decode endpoint port mapping %v", err)
+ }
+
+ return nil
+}
+
+func (ep *bridgeEndpoint) Key() []string {
+ return []string{bridgeEndpointPrefix, ep.id}
+}
+
+func (ep *bridgeEndpoint) KeyPrefix() []string {
+ return []string{bridgeEndpointPrefix}
+}
+
+func (ep *bridgeEndpoint) Value() []byte {
+ b, err := json.Marshal(ep)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (ep *bridgeEndpoint) SetValue(value []byte) error {
+ return json.Unmarshal(value, ep)
+}
+
+func (ep *bridgeEndpoint) Index() uint64 {
+ return ep.dbIndex
+}
+
+func (ep *bridgeEndpoint) SetIndex(index uint64) {
+ ep.dbIndex = index
+ ep.dbExists = true
+}
+
+func (ep *bridgeEndpoint) Exists() bool {
+ return ep.dbExists
+}
+
+func (ep *bridgeEndpoint) Skip() bool {
+ return false
+}
+
+func (ep *bridgeEndpoint) New() datastore.KVObject {
+ return &bridgeEndpoint{}
+}
+
+func (ep *bridgeEndpoint) CopyTo(o datastore.KVObject) error {
+ dstEp := o.(*bridgeEndpoint)
+ *dstEp = *ep
+ return nil
+}
+
+func (ep *bridgeEndpoint) DataScope() string {
+ return datastore.LocalScope
+}
+
+func (n *bridgeNetwork) restorePortAllocations(ep *bridgeEndpoint) {
+ if ep.extConnConfig == nil ||
+ ep.extConnConfig.ExposedPorts == nil ||
+ ep.extConnConfig.PortBindings == nil {
+ return
+ }
+ tmp := ep.extConnConfig.PortBindings
+ ep.extConnConfig.PortBindings = ep.portMapping
+ _, err := n.allocatePorts(ep, n.config.DefaultBindingIntf, n.config.DefaultBindingIP, n.driver.config.EnableUserlandProxy)
+ if err != nil {
+ logrus.Warnf("Failed to reserve existing port mapping for endpoint %s:%v", ep.id[0:7], err)
+ }
+ ep.extConnConfig.PortBindings = tmp
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/errors.go b/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/errors.go
new file mode 100644
index 0000000..ceb2388
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/errors.go
@@ -0,0 +1,119 @@
+package bridge
+
+import "fmt"
+
+// ErrInvalidEndpointConfig error is returned when an endpoint create is attempted with an invalid endpoint configuration.
+type ErrInvalidEndpointConfig struct{}
+
+func (eiec *ErrInvalidEndpointConfig) Error() string {
+ return "trying to create an endpoint with an invalid endpoint configuration"
+}
+
+// BadRequest denotes the type of this error
+func (eiec *ErrInvalidEndpointConfig) BadRequest() {}
+
+// ErrNoIPAddr error is returned when bridge has no IPv4 address configured.
+type ErrNoIPAddr struct{}
+
+func (enip *ErrNoIPAddr) Error() string {
+ return "bridge has no IPv4 address configured"
+}
+
+// InternalError denotes the type of this error
+func (enip *ErrNoIPAddr) InternalError() {}
+
+// ErrInvalidGateway is returned when the user provided default gateway (v4/v6) is not not valid.
+type ErrInvalidGateway struct{}
+
+func (eig *ErrInvalidGateway) Error() string {
+ return "default gateway ip must be part of the network"
+}
+
+// BadRequest denotes the type of this error
+func (eig *ErrInvalidGateway) BadRequest() {}
+
+// ErrInvalidMtu is returned when the user provided MTU is not valid.
+type ErrInvalidMtu int
+
+func (eim ErrInvalidMtu) Error() string {
+ return fmt.Sprintf("invalid MTU number: %d", int(eim))
+}
+
+// BadRequest denotes the type of this error
+func (eim ErrInvalidMtu) BadRequest() {}
+
+// ErrUnsupportedAddressType is returned when the specified address type is not supported.
+type ErrUnsupportedAddressType string
+
+func (uat ErrUnsupportedAddressType) Error() string {
+ return fmt.Sprintf("unsupported address type: %s", string(uat))
+}
+
+// BadRequest denotes the type of this error
+func (uat ErrUnsupportedAddressType) BadRequest() {}
+
+// ActiveEndpointsError is returned when there are
+// still active endpoints in the network being deleted.
+type ActiveEndpointsError string
+
+func (aee ActiveEndpointsError) Error() string {
+ return fmt.Sprintf("network %s has active endpoint", string(aee))
+}
+
+// Forbidden denotes the type of this error
+func (aee ActiveEndpointsError) Forbidden() {}
+
+// InvalidNetworkIDError is returned when the passed
+// network id for an existing network is not a known id.
+type InvalidNetworkIDError string
+
+func (inie InvalidNetworkIDError) Error() string {
+ return fmt.Sprintf("invalid network id %s", string(inie))
+}
+
+// NotFound denotes the type of this error
+func (inie InvalidNetworkIDError) NotFound() {}
+
+// InvalidEndpointIDError is returned when the passed
+// endpoint id is not valid.
+type InvalidEndpointIDError string
+
+func (ieie InvalidEndpointIDError) Error() string {
+ return fmt.Sprintf("invalid endpoint id: %s", string(ieie))
+}
+
+// BadRequest denotes the type of this error
+func (ieie InvalidEndpointIDError) BadRequest() {}
+
+// EndpointNotFoundError is returned when the no endpoint
+// with the passed endpoint id is found.
+type EndpointNotFoundError string
+
+func (enfe EndpointNotFoundError) Error() string {
+ return fmt.Sprintf("endpoint not found: %s", string(enfe))
+}
+
+// NotFound denotes the type of this error
+func (enfe EndpointNotFoundError) NotFound() {}
+
+// NonDefaultBridgeExistError is returned when a non-default
+// bridge config is passed but it does not already exist.
+type NonDefaultBridgeExistError string
+
+func (ndbee NonDefaultBridgeExistError) Error() string {
+ return fmt.Sprintf("bridge device with non default name %s must be created manually", string(ndbee))
+}
+
+// Forbidden denotes the type of this error
+func (ndbee NonDefaultBridgeExistError) Forbidden() {}
+
+// NonDefaultBridgeNeedsIPError is returned when a non-default
+// bridge config is passed but it has no ip configured
+type NonDefaultBridgeNeedsIPError string
+
+func (ndbee NonDefaultBridgeNeedsIPError) Error() string {
+ return fmt.Sprintf("bridge device with non default name %s must have a valid IP address", string(ndbee))
+}
+
+// Forbidden denotes the type of this error
+func (ndbee NonDefaultBridgeNeedsIPError) Forbidden() {}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/port_mapping.go b/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/port_mapping.go
new file mode 100644
index 0000000..1cf22c1
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/bridge/port_mapping.go
@@ -0,0 +1,225 @@
+// +build solaris
+
+package bridge
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "net"
+ "os"
+ "os/exec"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/types"
+)
+
+var (
+ defaultBindingIP = net.IPv4(0, 0, 0, 0)
+)
+
+const (
+ maxAllocatePortAttempts = 10
+)
+
+func addPFRules(epid, bindIntf string, bs []types.PortBinding) {
+ var id string
+
+ if len(epid) > 12 {
+ id = epid[:12]
+ } else {
+ id = epid
+ }
+
+ fname := "/var/lib/docker/network/files/pf." + id
+
+ f, err := os.OpenFile(fname,
+ os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
+ if err != nil {
+ logrus.Warn("cannot open temp pf file")
+ return
+ }
+ for _, b := range bs {
+ r := fmt.Sprintf(
+ "pass in on %s proto %s from any to (%s) "+
+ "port %d rdr-to %s port %d\n", bindIntf,
+ b.Proto.String(), bindIntf, b.HostPort,
+ b.IP.String(), b.Port)
+ _, err = f.WriteString(r)
+ if err != nil {
+ logrus.Warnf("cannot write firewall rules to %s: %v", fname, err)
+ }
+ }
+ f.Close()
+
+ anchor := fmt.Sprintf("_auto/docker/ep%s", id)
+ err = exec.Command("/usr/sbin/pfctl", "-a", anchor, "-f", fname).Run()
+ if err != nil {
+ logrus.Warnf("failed to add firewall rules: %v", err)
+ }
+ os.Remove(fname)
+}
+
+func removePFRules(epid string) {
+ var id string
+
+ if len(epid) > 12 {
+ id = epid[:12]
+ } else {
+ id = epid
+ }
+
+ anchor := fmt.Sprintf("_auto/docker/ep%s", id)
+ err := exec.Command("/usr/sbin/pfctl", "-a", anchor, "-F", "all").Run()
+ if err != nil {
+ logrus.Warnf("failed to remove firewall rules: %v", err)
+ }
+}
+
+func (n *bridgeNetwork) allocatePorts(ep *bridgeEndpoint, bindIntf string, reqDefBindIP net.IP, ulPxyEnabled bool) ([]types.PortBinding, error) {
+ if ep.extConnConfig == nil || ep.extConnConfig.PortBindings == nil {
+ return nil, nil
+ }
+
+ defHostIP := defaultBindingIP
+ if reqDefBindIP != nil {
+ defHostIP = reqDefBindIP
+ }
+
+ bs, err := n.allocatePortsInternal(ep.extConnConfig.PortBindings, bindIntf, ep.addr.IP, defHostIP, ulPxyEnabled)
+ if err != nil {
+ return nil, err
+ }
+
+ // Add PF rules for port bindings, if any
+ if len(bs) > 0 {
+ addPFRules(ep.id, bindIntf, bs)
+ }
+
+ return bs, err
+}
+
+func (n *bridgeNetwork) allocatePortsInternal(bindings []types.PortBinding, bindIntf string, containerIP, defHostIP net.IP, ulPxyEnabled bool) ([]types.PortBinding, error) {
+ bs := make([]types.PortBinding, 0, len(bindings))
+ for _, c := range bindings {
+ b := c.GetCopy()
+ if err := n.allocatePort(&b, containerIP, defHostIP); err != nil {
+ // On allocation failure,release previously
+ // allocated ports. On cleanup error, just log
+ // a warning message
+ if cuErr := n.releasePortsInternal(bs); cuErr != nil {
+ logrus.Warnf("Upon allocation failure "+
+ "for %v, failed to clear previously "+
+ "allocated port bindings: %v", b, cuErr)
+ }
+ return nil, err
+ }
+ bs = append(bs, b)
+ }
+ return bs, nil
+}
+
+func (n *bridgeNetwork) allocatePort(bnd *types.PortBinding, containerIP, defHostIP net.IP) error {
+ var (
+ host net.Addr
+ err error
+ )
+
+ // Store the container interface address in the operational binding
+ bnd.IP = containerIP
+
+ // Adjust the host address in the operational binding
+ if len(bnd.HostIP) == 0 {
+ bnd.HostIP = defHostIP
+ }
+
+ // Adjust HostPortEnd if this is not a range.
+ if bnd.HostPortEnd == 0 {
+ bnd.HostPortEnd = bnd.HostPort
+ }
+
+ // Construct the container side transport address
+ container, err := bnd.ContainerAddr()
+ if err != nil {
+ return err
+ }
+
+ // Try up to maxAllocatePortAttempts times to get a port that's
+ // not already allocated.
+ for i := 0; i < maxAllocatePortAttempts; i++ {
+ if host, err = n.portMapper.MapRange(container, bnd.HostIP,
+ int(bnd.HostPort), int(bnd.HostPortEnd), false); err == nil {
+ break
+ }
+ // There is no point in immediately retrying to map an
+ // explicitly chosen port.
+ if bnd.HostPort != 0 {
+ logrus.Warnf(
+ "Failed to allocate and map port %d-%d: %s",
+ bnd.HostPort, bnd.HostPortEnd, err)
+ break
+ }
+ logrus.Warnf("Failed to allocate and map port: %s, retry: %d",
+ err, i+1)
+ }
+ if err != nil {
+ return err
+ }
+
+ // Save the host port (regardless it was or not specified in the
+ // binding)
+ switch netAddr := host.(type) {
+ case *net.TCPAddr:
+ bnd.HostPort = uint16(host.(*net.TCPAddr).Port)
+ return nil
+ case *net.UDPAddr:
+ bnd.HostPort = uint16(host.(*net.UDPAddr).Port)
+ return nil
+ default:
+ // For completeness
+ return ErrUnsupportedAddressType(fmt.Sprintf("%T", netAddr))
+ }
+}
+
+func (n *bridgeNetwork) releasePorts(ep *bridgeEndpoint) error {
+ err := n.releasePortsInternal(ep.portMapping)
+ if err != nil {
+ return nil
+ }
+
+ // remove rules if there are any port mappings
+ if len(ep.portMapping) > 0 {
+ removePFRules(ep.id)
+ }
+
+ return nil
+
+}
+
+func (n *bridgeNetwork) releasePortsInternal(bindings []types.PortBinding) error {
+ var errorBuf bytes.Buffer
+
+ // Attempt to release all port bindings, do not stop on failure
+ for _, m := range bindings {
+ if err := n.releasePort(m); err != nil {
+ errorBuf.WriteString(
+ fmt.Sprintf(
+ "\ncould not release %v because of %v",
+ m, err))
+ }
+ }
+
+ if errorBuf.Len() != 0 {
+ return errors.New(errorBuf.String())
+ }
+ return nil
+}
+
+func (n *bridgeNetwork) releasePort(bnd types.PortBinding) error {
+ // Construct the host side transport address
+ host, err := bnd.HostAddr()
+ if err != nil {
+ return err
+ }
+ return n.portMapper.Unmap(host)
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/encryption.go b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/encryption.go
new file mode 100644
index 0000000..ca7b60b
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/encryption.go
@@ -0,0 +1,274 @@
+package overlay
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/hex"
+ "fmt"
+ "hash/fnv"
+ "net"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ mark = uint32(0xD0C4E3)
+ timeout = 30
+ pktExpansion = 26 // SPI(4) + SeqN(4) + IV(8) + PadLength(1) + NextHeader(1) + ICV(8)
+)
+
+const (
+ forward = iota + 1
+ reverse
+ bidir
+)
+
+type key struct {
+ value []byte
+ tag uint32
+}
+
+func (k *key) String() string {
+ if k != nil {
+ return fmt.Sprintf("(key: %s, tag: 0x%x)", hex.EncodeToString(k.value)[0:5], k.tag)
+ }
+ return ""
+}
+
+type spi struct {
+ forward int
+ reverse int
+}
+
+func (s *spi) String() string {
+ return fmt.Sprintf("SPI(FWD: 0x%x, REV: 0x%x)", uint32(s.forward), uint32(s.reverse))
+}
+
+type encrMap struct {
+ nodes map[string][]*spi
+ sync.Mutex
+}
+
+func (e *encrMap) String() string {
+ e.Lock()
+ defer e.Unlock()
+ b := new(bytes.Buffer)
+ for k, v := range e.nodes {
+ b.WriteString("\n")
+ b.WriteString(k)
+ b.WriteString(":")
+ b.WriteString("[")
+ for _, s := range v {
+ b.WriteString(s.String())
+ b.WriteString(",")
+ }
+ b.WriteString("]")
+
+ }
+ return b.String()
+}
+
+func (d *driver) checkEncryption(nid string, rIP net.IP, vxlanID uint32, isLocal, add bool) error {
+ logrus.Debugf("checkEncryption(%s, %v, %d, %t)", nid[0:7], rIP, vxlanID, isLocal)
+
+ n := d.network(nid)
+ if n == nil || !n.secure {
+ return nil
+ }
+
+ if len(d.keys) == 0 {
+ return types.ForbiddenErrorf("encryption key is not present")
+ }
+
+ lIP := net.ParseIP(d.bindAddress)
+ aIP := net.ParseIP(d.advertiseAddress)
+ nodes := map[string]net.IP{}
+
+ switch {
+ case isLocal:
+ if err := d.peerDbNetworkWalk(nid, func(pKey *peerKey, pEntry *peerEntry) bool {
+ if !aIP.Equal(pEntry.vtep) {
+ nodes[pEntry.vtep.String()] = pEntry.vtep
+ }
+ return false
+ }); err != nil {
+ logrus.Warnf("Failed to retrieve list of participating nodes in overlay network %s: %v", nid[0:5], err)
+ }
+ default:
+ if len(d.network(nid).endpoints) > 0 {
+ nodes[rIP.String()] = rIP
+ }
+ }
+
+ logrus.Debugf("List of nodes: %s", nodes)
+
+ if add {
+ for _, rIP := range nodes {
+ if err := setupEncryption(lIP, aIP, rIP, vxlanID, d.secMap, d.keys); err != nil {
+ logrus.Warnf("Failed to program network encryption between %s and %s: %v", lIP, rIP, err)
+ }
+ }
+ } else {
+ if len(nodes) == 0 {
+ if err := removeEncryption(lIP, rIP, d.secMap); err != nil {
+ logrus.Warnf("Failed to remove network encryption between %s and %s: %v", lIP, rIP, err)
+ }
+ }
+ }
+
+ return nil
+}
+
+func setupEncryption(localIP, advIP, remoteIP net.IP, vni uint32, em *encrMap, keys []*key) error {
+ logrus.Debugf("Programming encryption for vxlan %d between %s and %s", vni, localIP, remoteIP)
+ rIPs := remoteIP.String()
+
+ indices := make([]*spi, 0, len(keys))
+
+ err := programMangle(vni, true)
+ if err != nil {
+ logrus.Warn(err)
+ }
+
+ em.Lock()
+ em.nodes[rIPs] = indices
+ em.Unlock()
+
+ return nil
+}
+
+func removeEncryption(localIP, remoteIP net.IP, em *encrMap) error {
+ return nil
+}
+
+func programMangle(vni uint32, add bool) (err error) {
+ return
+}
+
+func buildSPI(src, dst net.IP, st uint32) int {
+ b := make([]byte, 4)
+ binary.BigEndian.PutUint32(b, st)
+ h := fnv.New32a()
+ h.Write(src)
+ h.Write(b)
+ h.Write(dst)
+ return int(binary.BigEndian.Uint32(h.Sum(nil)))
+}
+
+func (d *driver) secMapWalk(f func(string, []*spi) ([]*spi, bool)) error {
+ d.secMap.Lock()
+ for node, indices := range d.secMap.nodes {
+ idxs, stop := f(node, indices)
+ if idxs != nil {
+ d.secMap.nodes[node] = idxs
+ }
+ if stop {
+ break
+ }
+ }
+ d.secMap.Unlock()
+ return nil
+}
+
+func (d *driver) setKeys(keys []*key) error {
+ if d.keys != nil {
+ return types.ForbiddenErrorf("initial keys are already present")
+ }
+ d.keys = keys
+ logrus.Debugf("Initial encryption keys: %v", d.keys)
+ return nil
+}
+
+// updateKeys allows to add a new key and/or change the primary key and/or prune an existing key
+// The primary key is the key used in transmission and will go in first position in the list.
+func (d *driver) updateKeys(newKey, primary, pruneKey *key) error {
+ logrus.Debugf("Updating Keys. New: %v, Primary: %v, Pruned: %v", newKey, primary, pruneKey)
+
+ logrus.Debugf("Current: %v", d.keys)
+
+ var (
+ newIdx = -1
+ priIdx = -1
+ delIdx = -1
+ lIP = net.ParseIP(d.bindAddress)
+ )
+
+ d.Lock()
+ // add new
+ if newKey != nil {
+ d.keys = append(d.keys, newKey)
+ newIdx += len(d.keys)
+ }
+ for i, k := range d.keys {
+ if primary != nil && k.tag == primary.tag {
+ priIdx = i
+ }
+ if pruneKey != nil && k.tag == pruneKey.tag {
+ delIdx = i
+ }
+ }
+ d.Unlock()
+
+ if (newKey != nil && newIdx == -1) ||
+ (primary != nil && priIdx == -1) ||
+ (pruneKey != nil && delIdx == -1) {
+ err := types.BadRequestErrorf("cannot find proper key indices while processing key update:"+
+ "(newIdx,priIdx,delIdx):(%d, %d, %d)", newIdx, priIdx, delIdx)
+ logrus.Warn(err)
+ return err
+ }
+
+ d.secMapWalk(func(rIPs string, spis []*spi) ([]*spi, bool) {
+ rIP := net.ParseIP(rIPs)
+ return updateNodeKey(lIP, rIP, spis, d.keys, newIdx, priIdx, delIdx), false
+ })
+
+ d.Lock()
+ // swap primary
+ if priIdx != -1 {
+ swp := d.keys[0]
+ d.keys[0] = d.keys[priIdx]
+ d.keys[priIdx] = swp
+ }
+ // prune
+ if delIdx != -1 {
+ if delIdx == 0 {
+ delIdx = priIdx
+ }
+ d.keys = append(d.keys[:delIdx], d.keys[delIdx+1:]...)
+ }
+ d.Unlock()
+
+ logrus.Debugf("Updated: %v", d.keys)
+
+ return nil
+}
+
+/********************************************************
+ * Steady state: rSA0, rSA1, rSA2, fSA1, fSP1
+ * Rotation --> -rSA0, +rSA3, +fSA2, +fSP2/-fSP1, -fSA1
+ * Steady state: rSA1, rSA2, rSA3, fSA2, fSP2
+ *********************************************************/
+
+// Spis and keys are sorted in such away the one in position 0 is the primary
+func updateNodeKey(lIP, rIP net.IP, idxs []*spi, curKeys []*key, newIdx, priIdx, delIdx int) []*spi {
+ logrus.Debugf("Updating keys for node: %s (%d,%d,%d)", rIP, newIdx, priIdx, delIdx)
+ return nil
+}
+
+func (n *network) maxMTU() int {
+ mtu := 1500
+ if n.mtu != 0 {
+ mtu = n.mtu
+ }
+ mtu -= vxlanEncap
+ if n.secure {
+ // In case of encryption account for the
+ // esp packet espansion and padding
+ mtu -= pktExpansion
+ mtu -= (mtu % 4)
+ }
+ return mtu
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/joinleave.go b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/joinleave.go
new file mode 100644
index 0000000..fd41198
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/joinleave.go
@@ -0,0 +1,188 @@
+package overlay
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/types"
+ "github.com/gogo/protobuf/proto"
+)
+
+// Join method is invoked when a Sandbox is attached to an endpoint.
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return fmt.Errorf("could not find network with id %s", nid)
+ }
+
+ ep := n.endpoint(eid)
+ if ep == nil {
+ return fmt.Errorf("could not find endpoint with id %s", eid)
+ }
+
+ if n.secure && len(d.keys) == 0 {
+ return fmt.Errorf("cannot join secure network: encryption keys not present")
+ }
+
+ s := n.getSubnetforIP(ep.addr)
+ if s == nil {
+ return fmt.Errorf("could not find subnet for endpoint %s", eid)
+ }
+
+ if err := n.obtainVxlanID(s); err != nil {
+ return fmt.Errorf("couldn't get vxlan id for %q: %v", s.subnetIP.String(), err)
+ }
+
+ if err := n.joinSandbox(false); err != nil {
+ return fmt.Errorf("network sandbox join failed: %v", err)
+ }
+
+ if err := n.joinSubnetSandbox(s, false); err != nil {
+ return fmt.Errorf("subnet sandbox join failed for %q: %v", s.subnetIP.String(), err)
+ }
+
+ // joinSubnetSandbox gets called when an endpoint comes up on a new subnet in the
+ // overlay network. Hence the Endpoint count should be updated outside joinSubnetSandbox
+ n.incEndpointCount()
+
+ // Add creating a veth Pair for Solaris
+
+ containerIfName := "solaris-if"
+ ep.ifName = containerIfName
+
+ if err := d.writeEndpointToStore(ep); err != nil {
+ return fmt.Errorf("failed to update overlay endpoint %s to local data store: %v", ep.id[0:7], err)
+ }
+
+ // Add solaris plumbing to add veth (with ep mac addr) to sandbox
+
+ for _, sub := range n.subnets {
+ if sub == s {
+ continue
+ }
+ if err := jinfo.AddStaticRoute(sub.subnetIP, types.NEXTHOP, s.gwIP.IP); err != nil {
+ logrus.Errorf("Adding subnet %s static route in network %q failed\n", s.subnetIP, n.id)
+ }
+ }
+
+ if iNames := jinfo.InterfaceName(); iNames != nil {
+ err := iNames.SetNames(containerIfName, "eth")
+ if err != nil {
+ return err
+ }
+ }
+
+ d.peerDbAdd(nid, eid, ep.addr.IP, ep.addr.Mask, ep.mac,
+ net.ParseIP(d.advertiseAddress), true)
+
+ if err := d.checkEncryption(nid, nil, n.vxlanID(s), true, true); err != nil {
+ logrus.Warn(err)
+ }
+
+ buf, err := proto.Marshal(&PeerRecord{
+ EndpointIP: ep.addr.String(),
+ EndpointMAC: ep.mac.String(),
+ TunnelEndpointIP: d.advertiseAddress,
+ })
+ if err != nil {
+ return err
+ }
+
+ if err := jinfo.AddTableEntry(ovPeerTable, eid, buf); err != nil {
+ logrus.Errorf("overlay: Failed adding table entry to joininfo: %v", err)
+ }
+
+ d.pushLocalEndpointEvent("join", nid, eid)
+
+ return nil
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+ if tableName != ovPeerTable {
+ logrus.Errorf("Unexpected table notification for table %s received", tableName)
+ return
+ }
+
+ eid := key
+
+ var peer PeerRecord
+ if err := proto.Unmarshal(value, &peer); err != nil {
+ logrus.Errorf("Failed to unmarshal peer record: %v", err)
+ return
+ }
+
+ // Ignore local peers. We already know about them and they
+ // should not be added to vxlan fdb.
+ if peer.TunnelEndpointIP == d.advertiseAddress {
+ return
+ }
+
+ addr, err := types.ParseCIDR(peer.EndpointIP)
+ if err != nil {
+ logrus.Errorf("Invalid peer IP %s received in event notify", peer.EndpointIP)
+ return
+ }
+
+ mac, err := net.ParseMAC(peer.EndpointMAC)
+ if err != nil {
+ logrus.Errorf("Invalid mac %s received in event notify", peer.EndpointMAC)
+ return
+ }
+
+ vtep := net.ParseIP(peer.TunnelEndpointIP)
+ if vtep == nil {
+ logrus.Errorf("Invalid VTEP %s received in event notify", peer.TunnelEndpointIP)
+ return
+ }
+
+ if etype == driverapi.Delete {
+ d.peerDelete(nid, eid, addr.IP, addr.Mask, mac, vtep, true)
+ return
+ }
+
+ d.peerAdd(nid, eid, addr.IP, addr.Mask, mac, vtep, true)
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+// Leave method is invoked when a Sandbox detaches from an endpoint.
+func (d *driver) Leave(nid, eid string) error {
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return fmt.Errorf("could not find network with id %s", nid)
+ }
+
+ ep := n.endpoint(eid)
+
+ if ep == nil {
+ return types.InternalMaskableErrorf("could not find endpoint with id %s", eid)
+ }
+
+ if d.notifyCh != nil {
+ d.notifyCh <- ovNotify{
+ action: "leave",
+ nw: n,
+ ep: ep,
+ }
+ }
+
+ n.leaveSandbox()
+
+ if err := d.checkEncryption(nid, nil, 0, true, false); err != nil {
+ logrus.Warn(err)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_endpoint.go b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_endpoint.go
new file mode 100644
index 0000000..ca0c477
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_endpoint.go
@@ -0,0 +1,249 @@
+package overlay
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/netutils"
+ "github.com/docker/libnetwork/types"
+)
+
+type endpointTable map[string]*endpoint
+
+const overlayEndpointPrefix = "overlay/endpoint"
+
+type endpoint struct {
+ id string
+ nid string
+ ifName string
+ mac net.HardwareAddr
+ addr *net.IPNet
+ dbExists bool
+ dbIndex uint64
+}
+
+func (n *network) endpoint(eid string) *endpoint {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.endpoints[eid]
+}
+
+func (n *network) addEndpoint(ep *endpoint) {
+ n.Lock()
+ n.endpoints[ep.id] = ep
+ n.Unlock()
+}
+
+func (n *network) deleteEndpoint(eid string) {
+ n.Lock()
+ delete(n.endpoints, eid)
+ n.Unlock()
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo,
+ epOptions map[string]interface{}) error {
+ var err error
+
+ if err = validateID(nid, eid); err != nil {
+ return err
+ }
+
+ // Since we perform lazy configuration make sure we try
+ // configuring the driver when we enter CreateEndpoint since
+ // CreateNetwork may not be called in every node.
+ if err := d.configure(); err != nil {
+ return err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return fmt.Errorf("network id %q not found", nid)
+ }
+
+ ep := &endpoint{
+ id: eid,
+ nid: n.id,
+ addr: ifInfo.Address(),
+ mac: ifInfo.MacAddress(),
+ }
+ if ep.addr == nil {
+ return fmt.Errorf("create endpoint was not passed interface IP address")
+ }
+
+ if s := n.getSubnetforIP(ep.addr); s == nil {
+ return fmt.Errorf("no matching subnet for IP %q in network %q", ep.addr, nid)
+ }
+
+ if ep.mac == nil {
+ ep.mac = netutils.GenerateMACFromIP(ep.addr.IP)
+ if err := ifInfo.SetMacAddress(ep.mac); err != nil {
+ return err
+ }
+ }
+
+ n.addEndpoint(ep)
+
+ if err := d.writeEndpointToStore(ep); err != nil {
+ return fmt.Errorf("failed to update overlay endpoint %s to local store: %v", ep.id[0:7], err)
+ }
+
+ return nil
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return fmt.Errorf("network id %q not found", nid)
+ }
+
+ ep := n.endpoint(eid)
+ if ep == nil {
+ return fmt.Errorf("endpoint id %q not found", eid)
+ }
+
+ n.deleteEndpoint(eid)
+
+ if err := d.deleteEndpointFromStore(ep); err != nil {
+ logrus.Warnf("Failed to delete overlay endpoint %s from local store: %v", ep.id[0:7], err)
+ }
+
+ if ep.ifName == "" {
+ return nil
+ }
+
+ // OVERLAY_SOLARIS: Add Solaris unplumbing for removing the interface endpoint
+
+ return nil
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ return make(map[string]interface{}, 0), nil
+}
+
+func (d *driver) deleteEndpointFromStore(e *endpoint) error {
+ if d.localStore == nil {
+ return fmt.Errorf("overlay local store not initialized, ep not deleted")
+ }
+
+ if err := d.localStore.DeleteObjectAtomic(e); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (d *driver) writeEndpointToStore(e *endpoint) error {
+ if d.localStore == nil {
+ return fmt.Errorf("overlay local store not initialized, ep not added")
+ }
+
+ if err := d.localStore.PutObjectAtomic(e); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (ep *endpoint) DataScope() string {
+ return datastore.LocalScope
+}
+
+func (ep *endpoint) New() datastore.KVObject {
+ return &endpoint{}
+}
+
+func (ep *endpoint) CopyTo(o datastore.KVObject) error {
+ dstep := o.(*endpoint)
+ *dstep = *ep
+ return nil
+}
+
+func (ep *endpoint) Key() []string {
+ return []string{overlayEndpointPrefix, ep.id}
+}
+
+func (ep *endpoint) KeyPrefix() []string {
+ return []string{overlayEndpointPrefix}
+}
+
+func (ep *endpoint) Index() uint64 {
+ return ep.dbIndex
+}
+
+func (ep *endpoint) SetIndex(index uint64) {
+ ep.dbIndex = index
+ ep.dbExists = true
+}
+
+func (ep *endpoint) Exists() bool {
+ return ep.dbExists
+}
+
+func (ep *endpoint) Skip() bool {
+ return false
+}
+
+func (ep *endpoint) Value() []byte {
+ b, err := json.Marshal(ep)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (ep *endpoint) SetValue(value []byte) error {
+ return json.Unmarshal(value, ep)
+}
+
+func (ep *endpoint) MarshalJSON() ([]byte, error) {
+ epMap := make(map[string]interface{})
+
+ epMap["id"] = ep.id
+ epMap["nid"] = ep.nid
+ if ep.ifName != "" {
+ epMap["ifName"] = ep.ifName
+ }
+ if ep.addr != nil {
+ epMap["addr"] = ep.addr.String()
+ }
+ if len(ep.mac) != 0 {
+ epMap["mac"] = ep.mac.String()
+ }
+
+ return json.Marshal(epMap)
+}
+
+func (ep *endpoint) UnmarshalJSON(value []byte) error {
+ var (
+ err error
+ epMap map[string]interface{}
+ )
+
+ json.Unmarshal(value, &epMap)
+
+ ep.id = epMap["id"].(string)
+ ep.nid = epMap["nid"].(string)
+ if v, ok := epMap["mac"]; ok {
+ if ep.mac, err = net.ParseMAC(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode endpoint interface mac address after json unmarshal: %s", v.(string))
+ }
+ }
+ if v, ok := epMap["addr"]; ok {
+ if ep.addr, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode endpoint interface ipv4 address after json unmarshal: %v", err)
+ }
+ }
+ if v, ok := epMap["ifName"]; ok {
+ ep.ifName = v.(string)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_network.go b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_network.go
new file mode 100644
index 0000000..b056726
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_network.go
@@ -0,0 +1,786 @@
+package overlay
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/netutils"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/resolvconf"
+ "github.com/docker/libnetwork/types"
+)
+
+var (
+ hostMode bool
+ networkOnce sync.Once
+ networkMu sync.Mutex
+ vniTbl = make(map[uint32]string)
+)
+
+type networkTable map[string]*network
+
+type subnet struct {
+ once *sync.Once
+ vxlanName string
+ brName string
+ vni uint32
+ initErr error
+ subnetIP *net.IPNet
+ gwIP *net.IPNet
+}
+
+type subnetJSON struct {
+ SubnetIP string
+ GwIP string
+ Vni uint32
+}
+
+type network struct {
+ id string
+ dbIndex uint64
+ dbExists bool
+ sbox osl.Sandbox
+ endpoints endpointTable
+ driver *driver
+ joinCnt int
+ once *sync.Once
+ initEpoch int
+ initErr error
+ subnets []*subnet
+ secure bool
+ mtu int
+ sync.Mutex
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ if id == "" {
+ return fmt.Errorf("invalid network id")
+ }
+ if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
+ return types.BadRequestErrorf("ipv4 pool is empty")
+ }
+
+ // Since we perform lazy configuration make sure we try
+ // configuring the driver when we enter CreateNetwork
+ if err := d.configure(); err != nil {
+ return err
+ }
+
+ n := &network{
+ id: id,
+ driver: d,
+ endpoints: endpointTable{},
+ once: &sync.Once{},
+ subnets: []*subnet{},
+ }
+
+ vnis := make([]uint32, 0, len(ipV4Data))
+ if gval, ok := option[netlabel.GenericData]; ok {
+ optMap := gval.(map[string]string)
+ if val, ok := optMap[netlabel.OverlayVxlanIDList]; ok {
+ logrus.Debugf("overlay: Received vxlan IDs: %s", val)
+ vniStrings := strings.Split(val, ",")
+ for _, vniStr := range vniStrings {
+ vni, err := strconv.Atoi(vniStr)
+ if err != nil {
+ return fmt.Errorf("invalid vxlan id value %q passed", vniStr)
+ }
+
+ vnis = append(vnis, uint32(vni))
+ }
+ }
+ if _, ok := optMap[secureOption]; ok {
+ n.secure = true
+ }
+ if val, ok := optMap[netlabel.DriverMTU]; ok {
+ var err error
+ if n.mtu, err = strconv.Atoi(val); err != nil {
+ return fmt.Errorf("failed to parse %v: %v", val, err)
+ }
+ if n.mtu < 0 {
+ return fmt.Errorf("invalid MTU value: %v", n.mtu)
+ }
+ }
+ }
+
+ // If we are getting vnis from libnetwork, either we get for
+ // all subnets or none.
+ if len(vnis) != 0 && len(vnis) < len(ipV4Data) {
+ return fmt.Errorf("insufficient vnis(%d) passed to overlay", len(vnis))
+ }
+
+ for i, ipd := range ipV4Data {
+ s := &subnet{
+ subnetIP: ipd.Pool,
+ gwIP: ipd.Gateway,
+ once: &sync.Once{},
+ }
+
+ if len(vnis) != 0 {
+ s.vni = vnis[i]
+ }
+
+ n.subnets = append(n.subnets, s)
+ }
+
+ if err := n.writeToStore(); err != nil {
+ return fmt.Errorf("failed to update data store for network %v: %v", n.id, err)
+ }
+
+ // Make sure no rule is on the way from any stale secure network
+ if !n.secure {
+ for _, vni := range vnis {
+ programMangle(vni, false)
+ }
+ }
+
+ if nInfo != nil {
+ if err := nInfo.TableEventRegister(ovPeerTable, driverapi.EndpointObject); err != nil {
+ return err
+ }
+ }
+
+ d.addNetwork(n)
+ return nil
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ if nid == "" {
+ return fmt.Errorf("invalid network id")
+ }
+
+ // Make sure driver resources are initialized before proceeding
+ if err := d.configure(); err != nil {
+ return err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return fmt.Errorf("could not find network with id %s", nid)
+ }
+
+ d.deleteNetwork(nid)
+
+ vnis, err := n.releaseVxlanID()
+ if err != nil {
+ return err
+ }
+
+ if n.secure {
+ for _, vni := range vnis {
+ programMangle(vni, false)
+ }
+ }
+
+ return nil
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ return nil
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ return nil
+}
+
+func (n *network) incEndpointCount() {
+ n.Lock()
+ defer n.Unlock()
+ n.joinCnt++
+}
+
+func (n *network) joinSandbox(restore bool) error {
+ // If there is a race between two go routines here only one will win
+ // the other will wait.
+ n.once.Do(func() {
+ // save the error status of initSandbox in n.initErr so that
+ // all the racing go routines are able to know the status.
+ n.initErr = n.initSandbox(restore)
+ })
+
+ return n.initErr
+}
+
+func (n *network) joinSubnetSandbox(s *subnet, restore bool) error {
+ s.once.Do(func() {
+ s.initErr = n.initSubnetSandbox(s, restore)
+ })
+ return s.initErr
+}
+
+func (n *network) leaveSandbox() {
+ n.Lock()
+ defer n.Unlock()
+ n.joinCnt--
+ if n.joinCnt != 0 {
+ return
+ }
+
+ // We are about to destroy sandbox since the container is leaving the network
+ // Reinitialize the once variable so that we will be able to trigger one time
+ // sandbox initialization(again) when another container joins subsequently.
+ n.once = &sync.Once{}
+ for _, s := range n.subnets {
+ s.once = &sync.Once{}
+ }
+
+ n.destroySandbox()
+}
+
+// to be called while holding network lock
+func (n *network) destroySandbox() {
+ if n.sbox != nil {
+ for _, iface := range n.sbox.Info().Interfaces() {
+ if err := iface.Remove(); err != nil {
+ logrus.Debugf("Remove interface %s failed: %v", iface.SrcName(), err)
+ }
+ }
+
+ for _, s := range n.subnets {
+ if s.vxlanName != "" {
+ err := deleteInterface(s.vxlanName)
+ if err != nil {
+ logrus.Warnf("could not cleanup sandbox properly: %v", err)
+ }
+ }
+ }
+
+ n.sbox.Destroy()
+ n.sbox = nil
+ }
+}
+
+func networkOnceInit() {
+ if os.Getenv("_OVERLAY_HOST_MODE") != "" {
+ hostMode = true
+ return
+ }
+
+ err := createVxlan("testvxlan1", 1, 0)
+ if err != nil {
+ logrus.Errorf("Failed to create testvxlan1 interface: %v", err)
+ return
+ }
+
+ defer deleteInterface("testvxlan1")
+}
+
+func (n *network) generateVxlanName(s *subnet) string {
+ id := n.id
+ if len(n.id) > 12 {
+ id = n.id[:12]
+ }
+
+ return "vx_" + id + "_0"
+}
+
+func (n *network) generateBridgeName(s *subnet) string {
+ id := n.id
+ if len(n.id) > 5 {
+ id = n.id[:5]
+ }
+
+ return n.getBridgeNamePrefix(s) + "_" + id + "_0"
+}
+
+func (n *network) getBridgeNamePrefix(s *subnet) string {
+ return "ov_" + fmt.Sprintf("%06x", n.vxlanID(s))
+}
+
+func isOverlap(nw *net.IPNet) bool {
+ var nameservers []string
+
+ if rc, err := resolvconf.Get(); err == nil {
+ nameservers = resolvconf.GetNameserversAsCIDR(rc.Content)
+ }
+
+ if err := netutils.CheckNameserverOverlaps(nameservers, nw); err != nil {
+ return true
+ }
+
+ if err := netutils.CheckRouteOverlaps(nw); err != nil {
+ return true
+ }
+
+ return false
+}
+
+func (n *network) restoreSubnetSandbox(s *subnet, brName, vxlanName string) error {
+ sbox := n.sandbox()
+
+ // restore overlay osl sandbox
+ Ifaces := make(map[string][]osl.IfaceOption)
+ brIfaceOption := make([]osl.IfaceOption, 2)
+ brIfaceOption = append(brIfaceOption, sbox.InterfaceOptions().Address(s.gwIP))
+ brIfaceOption = append(brIfaceOption, sbox.InterfaceOptions().Bridge(true))
+ Ifaces[fmt.Sprintf("%s+%s", brName, "br")] = brIfaceOption
+
+ err := sbox.Restore(Ifaces, nil, nil, nil)
+ if err != nil {
+ return err
+ }
+
+ Ifaces = make(map[string][]osl.IfaceOption)
+ vxlanIfaceOption := make([]osl.IfaceOption, 1)
+ vxlanIfaceOption = append(vxlanIfaceOption, sbox.InterfaceOptions().Master(brName))
+ Ifaces[fmt.Sprintf("%s+%s", vxlanName, "vxlan")] = vxlanIfaceOption
+ err = sbox.Restore(Ifaces, nil, nil, nil)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+func (n *network) addInterface(srcName, dstPrefix, name string, isBridge bool) error {
+ return nil
+}
+
+func (n *network) setupSubnetSandbox(s *subnet, brName, vxlanName string) error {
+
+ if hostMode {
+ // Try to delete stale bridge interface if it exists
+ if err := deleteInterface(brName); err != nil {
+ deleteInterfaceBySubnet(n.getBridgeNamePrefix(s), s)
+ }
+
+ if isOverlap(s.subnetIP) {
+ return fmt.Errorf("overlay subnet %s has conflicts in the host while running in host mode", s.subnetIP.String())
+ }
+ }
+
+ if !hostMode {
+ // Try to find this subnet's vni is being used in some
+ // other namespace by looking at vniTbl that we just
+ // populated in the once init. If a hit is found then
+ // it must a stale namespace from previous
+ // life. Destroy it completely and reclaim resourced.
+ networkMu.Lock()
+ path, ok := vniTbl[n.vxlanID(s)]
+ networkMu.Unlock()
+
+ if ok {
+ os.Remove(path)
+
+ networkMu.Lock()
+ delete(vniTbl, n.vxlanID(s))
+ networkMu.Unlock()
+ }
+ }
+
+ err := createVxlan(vxlanName, n.vxlanID(s), n.maxMTU())
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (n *network) initSubnetSandbox(s *subnet, restore bool) error {
+ brName := n.generateBridgeName(s)
+ vxlanName := n.generateVxlanName(s)
+
+ if restore {
+ n.restoreSubnetSandbox(s, brName, vxlanName)
+ } else {
+ n.setupSubnetSandbox(s, brName, vxlanName)
+ }
+
+ n.Lock()
+ s.vxlanName = vxlanName
+ s.brName = brName
+ n.Unlock()
+
+ return nil
+}
+
+func (n *network) cleanupStaleSandboxes() {
+ filepath.Walk(filepath.Dir(osl.GenerateKey("walk")),
+ func(path string, info os.FileInfo, err error) error {
+ _, fname := filepath.Split(path)
+
+ pList := strings.Split(fname, "-")
+ if len(pList) <= 1 {
+ return nil
+ }
+
+ pattern := pList[1]
+ if strings.Contains(n.id, pattern) {
+ // Now that we have destroyed this
+ // sandbox, remove all references to
+ // it in vniTbl so that we don't
+ // inadvertently destroy the sandbox
+ // created in this life.
+ networkMu.Lock()
+ for vni, tblPath := range vniTbl {
+ if tblPath == path {
+ delete(vniTbl, vni)
+ }
+ }
+ networkMu.Unlock()
+ }
+
+ return nil
+ })
+}
+
+func (n *network) initSandbox(restore bool) error {
+ n.Lock()
+ n.initEpoch++
+ n.Unlock()
+
+ networkOnce.Do(networkOnceInit)
+
+ if !restore {
+ // If there are any stale sandboxes related to this network
+ // from previous daemon life clean it up here
+ n.cleanupStaleSandboxes()
+ }
+
+ // In the restore case network sandbox already exist; but we don't know
+ // what epoch number it was created with. It has to be retrieved by
+ // searching the net namespaces.
+ var key string
+ if restore {
+ key = osl.GenerateKey("-" + n.id)
+ } else {
+ key = osl.GenerateKey(fmt.Sprintf("%d-", n.initEpoch) + n.id)
+ }
+
+ sbox, err := osl.NewSandbox(key, !hostMode, restore)
+ if err != nil {
+ return fmt.Errorf("could not get network sandbox (oper %t): %v", restore, err)
+ }
+
+ n.setSandbox(sbox)
+
+ if !restore {
+ n.driver.peerDbUpdateSandbox(n.id)
+ }
+
+ return nil
+}
+
+func (d *driver) addNetwork(n *network) {
+ d.Lock()
+ d.networks[n.id] = n
+ d.Unlock()
+}
+
+func (d *driver) deleteNetwork(nid string) {
+ d.Lock()
+ delete(d.networks, nid)
+ d.Unlock()
+}
+
+func (d *driver) network(nid string) *network {
+ d.Lock()
+ networks := d.networks
+ d.Unlock()
+
+ n, ok := networks[nid]
+ if !ok {
+ n = d.getNetworkFromStore(nid)
+ if n != nil {
+ n.driver = d
+ n.endpoints = endpointTable{}
+ n.once = &sync.Once{}
+ networks[nid] = n
+ }
+ }
+
+ return n
+}
+
+func (d *driver) getNetworkFromStore(nid string) *network {
+ if d.store == nil {
+ return nil
+ }
+
+ n := &network{id: nid}
+ if err := d.store.GetObject(datastore.Key(n.Key()...), n); err != nil {
+ return nil
+ }
+
+ return n
+}
+
+func (n *network) sandbox() osl.Sandbox {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.sbox
+}
+
+func (n *network) setSandbox(sbox osl.Sandbox) {
+ n.Lock()
+ n.sbox = sbox
+ n.Unlock()
+}
+
+func (n *network) vxlanID(s *subnet) uint32 {
+ n.Lock()
+ defer n.Unlock()
+
+ return s.vni
+}
+
+func (n *network) setVxlanID(s *subnet, vni uint32) {
+ n.Lock()
+ s.vni = vni
+ n.Unlock()
+}
+
+func (n *network) Key() []string {
+ return []string{"overlay", "network", n.id}
+}
+
+func (n *network) KeyPrefix() []string {
+ return []string{"overlay", "network"}
+}
+
+func (n *network) Value() []byte {
+ m := map[string]interface{}{}
+
+ netJSON := []*subnetJSON{}
+
+ for _, s := range n.subnets {
+ sj := &subnetJSON{
+ SubnetIP: s.subnetIP.String(),
+ GwIP: s.gwIP.String(),
+ Vni: s.vni,
+ }
+ netJSON = append(netJSON, sj)
+ }
+
+ m["secure"] = n.secure
+ m["subnets"] = netJSON
+ m["mtu"] = n.mtu
+ b, err := json.Marshal(m)
+ if err != nil {
+ return []byte{}
+ }
+
+ return b
+}
+
+func (n *network) Index() uint64 {
+ return n.dbIndex
+}
+
+func (n *network) SetIndex(index uint64) {
+ n.dbIndex = index
+ n.dbExists = true
+}
+
+func (n *network) Exists() bool {
+ return n.dbExists
+}
+
+func (n *network) Skip() bool {
+ return false
+}
+
+func (n *network) SetValue(value []byte) error {
+ var (
+ m map[string]interface{}
+ newNet bool
+ isMap = true
+ netJSON = []*subnetJSON{}
+ )
+
+ if err := json.Unmarshal(value, &m); err != nil {
+ err := json.Unmarshal(value, &netJSON)
+ if err != nil {
+ return err
+ }
+ isMap = false
+ }
+
+ if len(n.subnets) == 0 {
+ newNet = true
+ }
+
+ if isMap {
+ if val, ok := m["secure"]; ok {
+ n.secure = val.(bool)
+ }
+ if val, ok := m["mtu"]; ok {
+ n.mtu = int(val.(float64))
+ }
+ bytes, err := json.Marshal(m["subnets"])
+ if err != nil {
+ return err
+ }
+ if err := json.Unmarshal(bytes, &netJSON); err != nil {
+ return err
+ }
+ }
+
+ for _, sj := range netJSON {
+ subnetIPstr := sj.SubnetIP
+ gwIPstr := sj.GwIP
+ vni := sj.Vni
+
+ subnetIP, _ := types.ParseCIDR(subnetIPstr)
+ gwIP, _ := types.ParseCIDR(gwIPstr)
+
+ if newNet {
+ s := &subnet{
+ subnetIP: subnetIP,
+ gwIP: gwIP,
+ vni: vni,
+ once: &sync.Once{},
+ }
+ n.subnets = append(n.subnets, s)
+ } else {
+ sNet := n.getMatchingSubnet(subnetIP)
+ if sNet != nil {
+ sNet.vni = vni
+ }
+ }
+ }
+ return nil
+}
+
+func (n *network) DataScope() string {
+ return datastore.GlobalScope
+}
+
+func (n *network) writeToStore() error {
+ if n.driver.store == nil {
+ return nil
+ }
+
+ return n.driver.store.PutObjectAtomic(n)
+}
+
+func (n *network) releaseVxlanID() ([]uint32, error) {
+ if len(n.subnets) == 0 {
+ return nil, nil
+ }
+
+ if n.driver.store != nil {
+ if err := n.driver.store.DeleteObjectAtomic(n); err != nil {
+ if err == datastore.ErrKeyModified || err == datastore.ErrKeyNotFound {
+ // In both the above cases we can safely assume that the key has been removed by some other
+ // instance and so simply get out of here
+ return nil, nil
+ }
+
+ return nil, fmt.Errorf("failed to delete network to vxlan id map: %v", err)
+ }
+ }
+ var vnis []uint32
+ for _, s := range n.subnets {
+ if n.driver.vxlanIdm != nil {
+ vni := n.vxlanID(s)
+ vnis = append(vnis, vni)
+ n.driver.vxlanIdm.Release(uint64(vni))
+ }
+
+ n.setVxlanID(s, 0)
+ }
+
+ return vnis, nil
+}
+
+func (n *network) obtainVxlanID(s *subnet) error {
+ //return if the subnet already has a vxlan id assigned
+ if s.vni != 0 {
+ return nil
+ }
+
+ if n.driver.store == nil {
+ return fmt.Errorf("no valid vxlan id and no datastore configured, cannot obtain vxlan id")
+ }
+
+ for {
+ if err := n.driver.store.GetObject(datastore.Key(n.Key()...), n); err != nil {
+ return fmt.Errorf("getting network %q from datastore failed %v", n.id, err)
+ }
+
+ if s.vni == 0 {
+ vxlanID, err := n.driver.vxlanIdm.GetID()
+ if err != nil {
+ return fmt.Errorf("failed to allocate vxlan id: %v", err)
+ }
+
+ n.setVxlanID(s, uint32(vxlanID))
+ if err := n.writeToStore(); err != nil {
+ n.driver.vxlanIdm.Release(uint64(n.vxlanID(s)))
+ n.setVxlanID(s, 0)
+ if err == datastore.ErrKeyModified {
+ continue
+ }
+ return fmt.Errorf("network %q failed to update data store: %v", n.id, err)
+ }
+ return nil
+ }
+ return nil
+ }
+}
+
+// contains return true if the passed ip belongs to one the network's
+// subnets
+func (n *network) contains(ip net.IP) bool {
+ for _, s := range n.subnets {
+ if s.subnetIP.Contains(ip) {
+ return true
+ }
+ }
+
+ return false
+}
+
+// getSubnetforIP returns the subnet to which the given IP belongs
+func (n *network) getSubnetforIP(ip *net.IPNet) *subnet {
+ for _, s := range n.subnets {
+ // first check if the mask lengths are the same
+ i, _ := s.subnetIP.Mask.Size()
+ j, _ := ip.Mask.Size()
+ if i != j {
+ continue
+ }
+ if s.subnetIP.Contains(ip.IP) {
+ return s
+ }
+ }
+ return nil
+}
+
+// getMatchingSubnet return the network's subnet that matches the input
+func (n *network) getMatchingSubnet(ip *net.IPNet) *subnet {
+ if ip == nil {
+ return nil
+ }
+ for _, s := range n.subnets {
+ // first check if the mask lengths are the same
+ i, _ := s.subnetIP.Mask.Size()
+ j, _ := ip.Mask.Size()
+ if i != j {
+ continue
+ }
+ if s.subnetIP.IP.Equal(ip.IP) {
+ return s
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_serf.go b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_serf.go
new file mode 100644
index 0000000..53c59b4
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_serf.go
@@ -0,0 +1,233 @@
+package overlay
+
+import (
+ "fmt"
+ "net"
+ "strings"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/hashicorp/serf/serf"
+)
+
+type ovNotify struct {
+ action string
+ ep *endpoint
+ nw *network
+}
+
+type logWriter struct{}
+
+func (l *logWriter) Write(p []byte) (int, error) {
+ str := string(p)
+
+ switch {
+ case strings.Contains(str, "[WARN]"):
+ logrus.Warn(str)
+ case strings.Contains(str, "[DEBUG]"):
+ logrus.Debug(str)
+ case strings.Contains(str, "[INFO]"):
+ logrus.Info(str)
+ case strings.Contains(str, "[ERR]"):
+ logrus.Error(str)
+ }
+
+ return len(p), nil
+}
+
+func (d *driver) serfInit() error {
+ var err error
+
+ config := serf.DefaultConfig()
+ config.Init()
+ config.MemberlistConfig.BindAddr = d.advertiseAddress
+
+ d.eventCh = make(chan serf.Event, 4)
+ config.EventCh = d.eventCh
+ config.UserCoalescePeriod = 1 * time.Second
+ config.UserQuiescentPeriod = 50 * time.Millisecond
+
+ config.LogOutput = &logWriter{}
+ config.MemberlistConfig.LogOutput = config.LogOutput
+
+ s, err := serf.Create(config)
+ if err != nil {
+ return fmt.Errorf("failed to create cluster node: %v", err)
+ }
+ defer func() {
+ if err != nil {
+ s.Shutdown()
+ }
+ }()
+
+ d.serfInstance = s
+
+ d.notifyCh = make(chan ovNotify)
+ d.exitCh = make(chan chan struct{})
+
+ go d.startSerfLoop(d.eventCh, d.notifyCh, d.exitCh)
+ return nil
+}
+
+func (d *driver) serfJoin(neighIP string) error {
+ if neighIP == "" {
+ return fmt.Errorf("no neighbor to join")
+ }
+ if _, err := d.serfInstance.Join([]string{neighIP}, false); err != nil {
+ return fmt.Errorf("Failed to join the cluster at neigh IP %s: %v",
+ neighIP, err)
+ }
+ return nil
+}
+
+func (d *driver) notifyEvent(event ovNotify) {
+ ep := event.ep
+
+ ePayload := fmt.Sprintf("%s %s %s %s", event.action, ep.addr.IP.String(),
+ net.IP(ep.addr.Mask).String(), ep.mac.String())
+ eName := fmt.Sprintf("jl %s %s %s", d.serfInstance.LocalMember().Addr.String(),
+ event.nw.id, ep.id)
+
+ if err := d.serfInstance.UserEvent(eName, []byte(ePayload), true); err != nil {
+ logrus.Errorf("Sending user event failed: %v\n", err)
+ }
+}
+
+func (d *driver) processEvent(u serf.UserEvent) {
+ logrus.Debugf("Received user event name:%s, payload:%s\n", u.Name,
+ string(u.Payload))
+
+ var dummy, action, vtepStr, nid, eid, ipStr, maskStr, macStr string
+ if _, err := fmt.Sscan(u.Name, &dummy, &vtepStr, &nid, &eid); err != nil {
+ fmt.Printf("Failed to scan name string: %v\n", err)
+ }
+
+ if _, err := fmt.Sscan(string(u.Payload), &action,
+ &ipStr, &maskStr, &macStr); err != nil {
+ fmt.Printf("Failed to scan value string: %v\n", err)
+ }
+
+ logrus.Debugf("Parsed data = %s/%s/%s/%s/%s/%s\n", nid, eid, vtepStr, ipStr, maskStr, macStr)
+
+ mac, err := net.ParseMAC(macStr)
+ if err != nil {
+ logrus.Errorf("Failed to parse mac: %v\n", err)
+ }
+
+ if d.serfInstance.LocalMember().Addr.String() == vtepStr {
+ return
+ }
+
+ switch action {
+ case "join":
+ if err := d.peerAdd(nid, eid, net.ParseIP(ipStr), net.IPMask(net.ParseIP(maskStr).To4()), mac,
+ net.ParseIP(vtepStr), true); err != nil {
+ logrus.Errorf("Peer add failed in the driver: %v\n", err)
+ }
+ case "leave":
+ if err := d.peerDelete(nid, eid, net.ParseIP(ipStr), net.IPMask(net.ParseIP(maskStr).To4()), mac,
+ net.ParseIP(vtepStr), true); err != nil {
+ logrus.Errorf("Peer delete failed in the driver: %v\n", err)
+ }
+ }
+}
+
+func (d *driver) processQuery(q *serf.Query) {
+ logrus.Debugf("Received query name:%s, payload:%s\n", q.Name,
+ string(q.Payload))
+
+ var nid, ipStr string
+ if _, err := fmt.Sscan(string(q.Payload), &nid, &ipStr); err != nil {
+ fmt.Printf("Failed to scan query payload string: %v\n", err)
+ }
+
+ peerMac, peerIPMask, vtep, err := d.peerDbSearch(nid, net.ParseIP(ipStr))
+ if err != nil {
+ return
+ }
+
+ q.Respond([]byte(fmt.Sprintf("%s %s %s", peerMac.String(), net.IP(peerIPMask).String(), vtep.String())))
+}
+
+func (d *driver) resolvePeer(nid string, peerIP net.IP) (net.HardwareAddr, net.IPMask, net.IP, error) {
+ if d.serfInstance == nil {
+ return nil, nil, nil, fmt.Errorf("could not resolve peer: serf instance not initialized")
+ }
+
+ qPayload := fmt.Sprintf("%s %s", string(nid), peerIP.String())
+ resp, err := d.serfInstance.Query("peerlookup", []byte(qPayload), nil)
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("resolving peer by querying the cluster failed: %v", err)
+ }
+
+ respCh := resp.ResponseCh()
+ select {
+ case r := <-respCh:
+ var macStr, maskStr, vtepStr string
+ if _, err := fmt.Sscan(string(r.Payload), &macStr, &maskStr, &vtepStr); err != nil {
+ return nil, nil, nil, fmt.Errorf("bad response %q for the resolve query: %v", string(r.Payload), err)
+ }
+
+ mac, err := net.ParseMAC(macStr)
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("failed to parse mac: %v", err)
+ }
+
+ return mac, net.IPMask(net.ParseIP(maskStr).To4()), net.ParseIP(vtepStr), nil
+
+ case <-time.After(time.Second):
+ return nil, nil, nil, fmt.Errorf("timed out resolving peer by querying the cluster")
+ }
+}
+
+func (d *driver) startSerfLoop(eventCh chan serf.Event, notifyCh chan ovNotify,
+ exitCh chan chan struct{}) {
+
+ for {
+ select {
+ case notify, ok := <-notifyCh:
+ if !ok {
+ break
+ }
+
+ d.notifyEvent(notify)
+ case ch, ok := <-exitCh:
+ if !ok {
+ break
+ }
+
+ if err := d.serfInstance.Leave(); err != nil {
+ logrus.Errorf("failed leaving the cluster: %v\n", err)
+ }
+
+ d.serfInstance.Shutdown()
+ close(ch)
+ return
+ case e, ok := <-eventCh:
+ if !ok {
+ break
+ }
+
+ if e.EventType() == serf.EventQuery {
+ d.processQuery(e.(*serf.Query))
+ break
+ }
+
+ u, ok := e.(serf.UserEvent)
+ if !ok {
+ break
+ }
+ d.processEvent(u)
+ }
+ }
+}
+
+func (d *driver) isSerfAlive() bool {
+ d.Lock()
+ serfInstance := d.serfInstance
+ d.Unlock()
+ if serfInstance == nil || serfInstance.State() != serf.SerfAlive {
+ return false
+ }
+ return true
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_utils.go b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_utils.go
new file mode 100644
index 0000000..5e315e7
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/ov_utils.go
@@ -0,0 +1,61 @@
+package overlay
+
+import (
+ "fmt"
+ "os/exec"
+ "strings"
+
+ "github.com/docker/libnetwork/osl"
+)
+
+func validateID(nid, eid string) error {
+ if nid == "" {
+ return fmt.Errorf("invalid network id")
+ }
+
+ if eid == "" {
+ return fmt.Errorf("invalid endpoint id")
+ }
+
+ return nil
+}
+
+func createVxlan(name string, vni uint32, mtu int) error {
+ defer osl.InitOSContext()()
+
+ // Get default interface to plumb the vxlan on
+ routeCmd := "/usr/sbin/ipadm show-addr -p -o addrobj " +
+ "`/usr/sbin/route get default | /usr/bin/grep interface | " +
+ "/usr/bin/awk '{print $2}'`"
+ out, err := exec.Command("/usr/bin/bash", "-c", routeCmd).Output()
+ if err != nil {
+ return fmt.Errorf("cannot get default route: %v", err)
+ }
+
+ defaultInterface := strings.SplitN(string(out), "/", 2)
+ propList := fmt.Sprintf("interface=%s,vni=%d", defaultInterface[0], vni)
+
+ out, err = exec.Command("/usr/sbin/dladm", "create-vxlan", "-t", "-p", propList,
+ name).Output()
+ if err != nil {
+ return fmt.Errorf("error creating vxlan interface: %v %s", err, out)
+ }
+
+ return nil
+}
+
+func deleteInterfaceBySubnet(brPrefix string, s *subnet) error {
+ return nil
+
+}
+
+func deleteInterface(name string) error {
+ defer osl.InitOSContext()()
+
+ out, err := exec.Command("/usr/sbin/dladm", "delete-vxlan", name).Output()
+ if err != nil {
+ return fmt.Errorf("error creating vxlan interface: %v %s", err, out)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.go b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.go
new file mode 100644
index 0000000..0a5a1bf
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.go
@@ -0,0 +1,367 @@
+package overlay
+
+//go:generate protoc -I.:../../Godeps/_workspace/src/github.com/gogo/protobuf --gogo_out=import_path=github.com/docker/libnetwork/drivers/overlay,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto:. overlay.proto
+
+import (
+ "fmt"
+ "net"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/idm"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/types"
+ "github.com/hashicorp/serf/serf"
+)
+
+// XXX OVERLAY_SOLARIS
+// Might need changes for names/constant values in solaris
+const (
+ networkType = "overlay"
+ vethPrefix = "veth"
+ vethLen = 7
+ vxlanIDStart = 256
+ vxlanIDEnd = (1 << 24) - 1
+ vxlanPort = 4789
+ vxlanEncap = 50
+ secureOption = "encrypted"
+)
+
+var initVxlanIdm = make(chan (bool), 1)
+
+type driver struct {
+ eventCh chan serf.Event
+ notifyCh chan ovNotify
+ exitCh chan chan struct{}
+ bindAddress string
+ advertiseAddress string
+ neighIP string
+ config map[string]interface{}
+ peerDb peerNetworkMap
+ secMap *encrMap
+ serfInstance *serf.Serf
+ networks networkTable
+ store datastore.DataStore
+ localStore datastore.DataStore
+ vxlanIdm *idm.Idm
+ once sync.Once
+ joinOnce sync.Once
+ keys []*key
+ sync.Mutex
+}
+
+// Init registers a new instance of overlay driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ c := driverapi.Capability{
+ DataScope: datastore.GlobalScope,
+ ConnectivityScope: datastore.GlobalScope,
+ }
+ d := &driver{
+ networks: networkTable{},
+ peerDb: peerNetworkMap{
+ mp: map[string]*peerMap{},
+ },
+ secMap: &encrMap{nodes: map[string][]*spi{}},
+ config: config,
+ }
+
+ if data, ok := config[netlabel.GlobalKVClient]; ok {
+ var err error
+ dsc, ok := data.(discoverapi.DatastoreConfigData)
+ if !ok {
+ return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
+ }
+ d.store, err = datastore.NewDataStoreFromConfig(dsc)
+ if err != nil {
+ return types.InternalErrorf("failed to initialize data store: %v", err)
+ }
+ }
+
+ if data, ok := config[netlabel.LocalKVClient]; ok {
+ var err error
+ dsc, ok := data.(discoverapi.DatastoreConfigData)
+ if !ok {
+ return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
+ }
+ d.localStore, err = datastore.NewDataStoreFromConfig(dsc)
+ if err != nil {
+ return types.InternalErrorf("failed to initialize local data store: %v", err)
+ }
+ }
+
+ d.restoreEndpoints()
+
+ return dc.RegisterDriver(networkType, d, c)
+}
+
+// Endpoints are stored in the local store. Restore them and reconstruct the overlay sandbox
+func (d *driver) restoreEndpoints() error {
+ if d.localStore == nil {
+ logrus.Warnf("Cannot restore overlay endpoints because local datastore is missing")
+ return nil
+ }
+ kvol, err := d.localStore.List(datastore.Key(overlayEndpointPrefix), &endpoint{})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ return fmt.Errorf("failed to read overlay endpoint from store: %v", err)
+ }
+
+ if err == datastore.ErrKeyNotFound {
+ return nil
+ }
+ for _, kvo := range kvol {
+ ep := kvo.(*endpoint)
+ n := d.network(ep.nid)
+ if n == nil {
+ logrus.Debugf("Network (%s) not found for restored endpoint (%s)", ep.nid[0:7], ep.id[0:7])
+ logrus.Debugf("Deleting stale overlay endpoint (%s) from store", ep.id[0:7])
+ if err := d.deleteEndpointFromStore(ep); err != nil {
+ logrus.Debugf("Failed to delete stale overlay endpoint (%s) from store", ep.id[0:7])
+ }
+ continue
+ }
+ n.addEndpoint(ep)
+
+ s := n.getSubnetforIP(ep.addr)
+ if s == nil {
+ return fmt.Errorf("could not find subnet for endpoint %s", ep.id)
+ }
+
+ if err := n.joinSandbox(true); err != nil {
+ return fmt.Errorf("restore network sandbox failed: %v", err)
+ }
+
+ if err := n.joinSubnetSandbox(s, true); err != nil {
+ return fmt.Errorf("restore subnet sandbox failed for %q: %v", s.subnetIP.String(), err)
+ }
+
+ Ifaces := make(map[string][]osl.IfaceOption)
+ vethIfaceOption := make([]osl.IfaceOption, 1)
+ vethIfaceOption = append(vethIfaceOption, n.sbox.InterfaceOptions().Master(s.brName))
+ Ifaces[fmt.Sprintf("%s+%s", "veth", "veth")] = vethIfaceOption
+
+ err := n.sbox.Restore(Ifaces, nil, nil, nil)
+ if err != nil {
+ return fmt.Errorf("failed to restore overlay sandbox: %v", err)
+ }
+
+ n.incEndpointCount()
+ d.peerDbAdd(ep.nid, ep.id, ep.addr.IP, ep.addr.Mask, ep.mac, net.ParseIP(d.advertiseAddress), true)
+ }
+ return nil
+}
+
+// Fini cleans up the driver resources
+func Fini(drv driverapi.Driver) {
+ d := drv.(*driver)
+
+ if d.exitCh != nil {
+ waitCh := make(chan struct{})
+
+ d.exitCh <- waitCh
+
+ <-waitCh
+ }
+}
+
+func (d *driver) configure() error {
+ if d.store == nil {
+ return nil
+ }
+
+ if d.vxlanIdm == nil {
+ return d.initializeVxlanIdm()
+ }
+
+ return nil
+}
+
+func (d *driver) initializeVxlanIdm() error {
+ var err error
+
+ initVxlanIdm <- true
+ defer func() { <-initVxlanIdm }()
+
+ if d.vxlanIdm != nil {
+ return nil
+ }
+
+ d.vxlanIdm, err = idm.New(d.store, "vxlan-id", vxlanIDStart, vxlanIDEnd)
+ if err != nil {
+ return fmt.Errorf("failed to initialize vxlan id manager: %v", err)
+ }
+
+ return nil
+}
+
+func (d *driver) Type() string {
+ return networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+func validateSelf(node string) error {
+ advIP := net.ParseIP(node)
+ if advIP == nil {
+ return fmt.Errorf("invalid self address (%s)", node)
+ }
+
+ addrs, err := net.InterfaceAddrs()
+ if err != nil {
+ return fmt.Errorf("Unable to get interface addresses %v", err)
+ }
+ for _, addr := range addrs {
+ ip, _, err := net.ParseCIDR(addr.String())
+ if err == nil && ip.Equal(advIP) {
+ return nil
+ }
+ }
+ return fmt.Errorf("Multi-Host overlay networking requires cluster-advertise(%s) to be configured with a local ip-address that is reachable within the cluster", advIP.String())
+}
+
+func (d *driver) nodeJoin(advertiseAddress, bindAddress string, self bool) {
+ if self && !d.isSerfAlive() {
+ d.Lock()
+ d.advertiseAddress = advertiseAddress
+ d.bindAddress = bindAddress
+ d.Unlock()
+
+ // If there is no cluster store there is no need to start serf.
+ if d.store != nil {
+ if err := validateSelf(advertiseAddress); err != nil {
+ logrus.Warnf("%s", err.Error())
+ }
+ err := d.serfInit()
+ if err != nil {
+ logrus.Errorf("initializing serf instance failed: %v", err)
+ d.Lock()
+ d.advertiseAddress = ""
+ d.bindAddress = ""
+ d.Unlock()
+ return
+ }
+ }
+ }
+
+ d.Lock()
+ if !self {
+ d.neighIP = advertiseAddress
+ }
+ neighIP := d.neighIP
+ d.Unlock()
+
+ if d.serfInstance != nil && neighIP != "" {
+ var err error
+ d.joinOnce.Do(func() {
+ err = d.serfJoin(neighIP)
+ if err == nil {
+ d.pushLocalDb()
+ }
+ })
+ if err != nil {
+ logrus.Errorf("joining serf neighbor %s failed: %v", advertiseAddress, err)
+ d.Lock()
+ d.joinOnce = sync.Once{}
+ d.Unlock()
+ return
+ }
+ }
+}
+
+func (d *driver) pushLocalEndpointEvent(action, nid, eid string) {
+ n := d.network(nid)
+ if n == nil {
+ logrus.Debugf("Error pushing local endpoint event for network %s", nid)
+ return
+ }
+ ep := n.endpoint(eid)
+ if ep == nil {
+ logrus.Debugf("Error pushing local endpoint event for ep %s / %s", nid, eid)
+ return
+ }
+
+ if !d.isSerfAlive() {
+ return
+ }
+ d.notifyCh <- ovNotify{
+ action: "join",
+ nw: n,
+ ep: ep,
+ }
+}
+
+// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ var err error
+ switch dType {
+ case discoverapi.NodeDiscovery:
+ nodeData, ok := data.(discoverapi.NodeDiscoveryData)
+ if !ok || nodeData.Address == "" {
+ return fmt.Errorf("invalid discovery data")
+ }
+ d.nodeJoin(nodeData.Address, nodeData.BindAddress, nodeData.Self)
+ case discoverapi.DatastoreConfig:
+ if d.store != nil {
+ return types.ForbiddenErrorf("cannot accept datastore configuration: Overlay driver has a datastore configured already")
+ }
+ dsc, ok := data.(discoverapi.DatastoreConfigData)
+ if !ok {
+ return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
+ }
+ d.store, err = datastore.NewDataStoreFromConfig(dsc)
+ if err != nil {
+ return types.InternalErrorf("failed to initialize data store: %v", err)
+ }
+ case discoverapi.EncryptionKeysConfig:
+ encrData, ok := data.(discoverapi.DriverEncryptionConfig)
+ if !ok {
+ return fmt.Errorf("invalid encryption key notification data")
+ }
+ keys := make([]*key, 0, len(encrData.Keys))
+ for i := 0; i < len(encrData.Keys); i++ {
+ k := &key{
+ value: encrData.Keys[i],
+ tag: uint32(encrData.Tags[i]),
+ }
+ keys = append(keys, k)
+ }
+ d.setKeys(keys)
+ case discoverapi.EncryptionKeysUpdate:
+ var newKey, delKey, priKey *key
+ encrData, ok := data.(discoverapi.DriverEncryptionUpdate)
+ if !ok {
+ return fmt.Errorf("invalid encryption key notification data")
+ }
+ if encrData.Key != nil {
+ newKey = &key{
+ value: encrData.Key,
+ tag: uint32(encrData.Tag),
+ }
+ }
+ if encrData.Primary != nil {
+ priKey = &key{
+ value: encrData.Primary,
+ tag: uint32(encrData.PrimaryTag),
+ }
+ }
+ if encrData.Prune != nil {
+ delKey = &key{
+ value: encrData.Prune,
+ tag: uint32(encrData.PruneTag),
+ }
+ }
+ d.updateKeys(newKey, priKey, delKey)
+ default:
+ }
+ return nil
+}
+
+// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.pb.go b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.pb.go
new file mode 100644
index 0000000..cfa0eee
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.pb.go
@@ -0,0 +1,468 @@
+// Code generated by protoc-gen-gogo.
+// source: overlay.proto
+// DO NOT EDIT!
+
+/*
+ Package overlay is a generated protocol buffer package.
+
+ It is generated from these files:
+ overlay.proto
+
+ It has these top-level messages:
+ PeerRecord
+*/
+package overlay
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+
+import strings "strings"
+import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
+import sort "sort"
+import strconv "strconv"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+const _ = proto.GoGoProtoPackageIsVersion1
+
+// PeerRecord defines the information corresponding to a peer
+// container in the overlay network.
+type PeerRecord struct {
+ // Endpoint IP is the IP of the container attachment on the
+ // given overlay network.
+ EndpointIP string `protobuf:"bytes,1,opt,name=endpoint_ip,json=endpointIp,proto3" json:"endpoint_ip,omitempty"`
+ // Endpoint MAC is the mac address of the container attachment
+ // on the given overlay network.
+ EndpointMAC string `protobuf:"bytes,2,opt,name=endpoint_mac,json=endpointMac,proto3" json:"endpoint_mac,omitempty"`
+ // Tunnel Endpoint IP defines the host IP for the host in
+ // which this container is running and can be reached by
+ // building a tunnel to that host IP.
+ TunnelEndpointIP string `protobuf:"bytes,3,opt,name=tunnel_endpoint_ip,json=tunnelEndpointIp,proto3" json:"tunnel_endpoint_ip,omitempty"`
+}
+
+func (m *PeerRecord) Reset() { *m = PeerRecord{} }
+func (*PeerRecord) ProtoMessage() {}
+func (*PeerRecord) Descriptor() ([]byte, []int) { return fileDescriptorOverlay, []int{0} }
+
+func init() {
+ proto.RegisterType((*PeerRecord)(nil), "overlay.PeerRecord")
+}
+func (this *PeerRecord) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&overlay.PeerRecord{")
+ s = append(s, "EndpointIP: "+fmt.Sprintf("%#v", this.EndpointIP)+",\n")
+ s = append(s, "EndpointMAC: "+fmt.Sprintf("%#v", this.EndpointMAC)+",\n")
+ s = append(s, "TunnelEndpointIP: "+fmt.Sprintf("%#v", this.TunnelEndpointIP)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringOverlay(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func extensionToGoStringOverlay(e map[int32]github_com_gogo_protobuf_proto.Extension) string {
+ if e == nil {
+ return "nil"
+ }
+ s := "map[int32]proto.Extension{"
+ keys := make([]int, 0, len(e))
+ for k := range e {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+ ss := []string{}
+ for _, k := range keys {
+ ss = append(ss, strconv.Itoa(k)+": "+e[int32(k)].GoString())
+ }
+ s += strings.Join(ss, ",") + "}"
+ return s
+}
+func (m *PeerRecord) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *PeerRecord) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.EndpointIP) > 0 {
+ data[i] = 0xa
+ i++
+ i = encodeVarintOverlay(data, i, uint64(len(m.EndpointIP)))
+ i += copy(data[i:], m.EndpointIP)
+ }
+ if len(m.EndpointMAC) > 0 {
+ data[i] = 0x12
+ i++
+ i = encodeVarintOverlay(data, i, uint64(len(m.EndpointMAC)))
+ i += copy(data[i:], m.EndpointMAC)
+ }
+ if len(m.TunnelEndpointIP) > 0 {
+ data[i] = 0x1a
+ i++
+ i = encodeVarintOverlay(data, i, uint64(len(m.TunnelEndpointIP)))
+ i += copy(data[i:], m.TunnelEndpointIP)
+ }
+ return i, nil
+}
+
+func encodeFixed64Overlay(data []byte, offset int, v uint64) int {
+ data[offset] = uint8(v)
+ data[offset+1] = uint8(v >> 8)
+ data[offset+2] = uint8(v >> 16)
+ data[offset+3] = uint8(v >> 24)
+ data[offset+4] = uint8(v >> 32)
+ data[offset+5] = uint8(v >> 40)
+ data[offset+6] = uint8(v >> 48)
+ data[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Overlay(data []byte, offset int, v uint32) int {
+ data[offset] = uint8(v)
+ data[offset+1] = uint8(v >> 8)
+ data[offset+2] = uint8(v >> 16)
+ data[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintOverlay(data []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ data[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ data[offset] = uint8(v)
+ return offset + 1
+}
+func (m *PeerRecord) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.EndpointIP)
+ if l > 0 {
+ n += 1 + l + sovOverlay(uint64(l))
+ }
+ l = len(m.EndpointMAC)
+ if l > 0 {
+ n += 1 + l + sovOverlay(uint64(l))
+ }
+ l = len(m.TunnelEndpointIP)
+ if l > 0 {
+ n += 1 + l + sovOverlay(uint64(l))
+ }
+ return n
+}
+
+func sovOverlay(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozOverlay(x uint64) (n int) {
+ return sovOverlay(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *PeerRecord) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PeerRecord{`,
+ `EndpointIP:` + fmt.Sprintf("%v", this.EndpointIP) + `,`,
+ `EndpointMAC:` + fmt.Sprintf("%v", this.EndpointMAC) + `,`,
+ `TunnelEndpointIP:` + fmt.Sprintf("%v", this.TunnelEndpointIP) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringOverlay(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *PeerRecord) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PeerRecord: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PeerRecord: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field EndpointIP", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthOverlay
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.EndpointIP = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field EndpointMAC", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthOverlay
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.EndpointMAC = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TunnelEndpointIP", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthOverlay
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TunnelEndpointIP = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipOverlay(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthOverlay
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipOverlay(data []byte) (n int, err error) {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if data[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthOverlay
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipOverlay(data[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthOverlay = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowOverlay = fmt.Errorf("proto: integer overflow")
+)
+
+var fileDescriptorOverlay = []byte{
+ // 195 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0xcd, 0x2f, 0x4b, 0x2d,
+ 0xca, 0x49, 0xac, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x87, 0x72, 0xa5, 0x44, 0xd2,
+ 0xf3, 0xd3, 0xf3, 0xc1, 0x62, 0xfa, 0x20, 0x16, 0x44, 0x5a, 0x69, 0x2b, 0x23, 0x17, 0x57, 0x40,
+ 0x6a, 0x6a, 0x51, 0x50, 0x6a, 0x72, 0x7e, 0x51, 0x8a, 0x90, 0x3e, 0x17, 0x77, 0x6a, 0x5e, 0x4a,
+ 0x41, 0x7e, 0x66, 0x5e, 0x49, 0x7c, 0x66, 0x81, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xa7, 0x13, 0xdf,
+ 0xa3, 0x7b, 0xf2, 0x5c, 0xae, 0x50, 0x61, 0xcf, 0x80, 0x20, 0x2e, 0x98, 0x12, 0xcf, 0x02, 0x21,
+ 0x23, 0x2e, 0x1e, 0xb8, 0x86, 0xdc, 0xc4, 0x64, 0x09, 0x26, 0xb0, 0x0e, 0x7e, 0xa0, 0x0e, 0x6e,
+ 0x98, 0x0e, 0x5f, 0x47, 0xe7, 0x20, 0xb8, 0xa9, 0xbe, 0x89, 0xc9, 0x42, 0x4e, 0x5c, 0x42, 0x25,
+ 0xa5, 0x79, 0x79, 0xa9, 0x39, 0xf1, 0xc8, 0x76, 0x31, 0x83, 0x75, 0x8a, 0x00, 0x75, 0x0a, 0x84,
+ 0x80, 0x65, 0x91, 0x6c, 0x14, 0x28, 0x41, 0x15, 0x29, 0x70, 0x92, 0xb8, 0xf1, 0x50, 0x8e, 0xe1,
+ 0xc3, 0x43, 0x39, 0xc6, 0x86, 0x47, 0x72, 0x8c, 0x27, 0x80, 0xf8, 0x02, 0x10, 0x3f, 0x00, 0xe2,
+ 0x24, 0x36, 0xb0, 0xc7, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbf, 0xd7, 0x7d, 0x7d, 0x08,
+ 0x01, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.proto b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.proto
new file mode 100644
index 0000000..45b8c9d
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/overlay.proto
@@ -0,0 +1,27 @@
+syntax = "proto3";
+
+import "gogoproto/gogo.proto";
+
+package overlay;
+
+option (gogoproto.marshaler_all) = true;
+option (gogoproto.unmarshaler_all) = true;
+option (gogoproto.stringer_all) = true;
+option (gogoproto.gostring_all) = true;
+option (gogoproto.sizer_all) = true;
+option (gogoproto.goproto_stringer_all) = false;
+
+// PeerRecord defines the information corresponding to a peer
+// container in the overlay network.
+message PeerRecord {
+ // Endpoint IP is the IP of the container attachment on the
+ // given overlay network.
+ string endpoint_ip = 1 [(gogoproto.customname) = "EndpointIP"];
+ // Endpoint MAC is the mac address of the container attachment
+ // on the given overlay network.
+ string endpoint_mac = 2 [(gogoproto.customname) = "EndpointMAC"];
+ // Tunnel Endpoint IP defines the host IP for the host in
+ // which this container is running and can be reached by
+ // building a tunnel to that host IP.
+ string tunnel_endpoint_ip = 3 [(gogoproto.customname) = "TunnelEndpointIP"];
+} \ No newline at end of file
diff --git a/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/peerdb.go b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/peerdb.go
new file mode 100644
index 0000000..d1499e2
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/solaris/overlay/peerdb.go
@@ -0,0 +1,336 @@
+package overlay
+
+import (
+ "fmt"
+ "net"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+)
+
+const ovPeerTable = "overlay_peer_table"
+
+type peerKey struct {
+ peerIP net.IP
+ peerMac net.HardwareAddr
+}
+
+type peerEntry struct {
+ eid string
+ vtep net.IP
+ peerIPMask net.IPMask
+ inSandbox bool
+ isLocal bool
+}
+
+type peerMap struct {
+ mp map[string]peerEntry
+ sync.Mutex
+}
+
+type peerNetworkMap struct {
+ mp map[string]*peerMap
+ sync.Mutex
+}
+
+func (pKey peerKey) String() string {
+ return fmt.Sprintf("%s %s", pKey.peerIP, pKey.peerMac)
+}
+
+func (pKey *peerKey) Scan(state fmt.ScanState, verb rune) error {
+ ipB, err := state.Token(true, nil)
+ if err != nil {
+ return err
+ }
+
+ pKey.peerIP = net.ParseIP(string(ipB))
+
+ macB, err := state.Token(true, nil)
+ if err != nil {
+ return err
+ }
+
+ pKey.peerMac, err = net.ParseMAC(string(macB))
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+var peerDbWg sync.WaitGroup
+
+func (d *driver) peerDbWalk(f func(string, *peerKey, *peerEntry) bool) error {
+ d.peerDb.Lock()
+ nids := []string{}
+ for nid := range d.peerDb.mp {
+ nids = append(nids, nid)
+ }
+ d.peerDb.Unlock()
+
+ for _, nid := range nids {
+ d.peerDbNetworkWalk(nid, func(pKey *peerKey, pEntry *peerEntry) bool {
+ return f(nid, pKey, pEntry)
+ })
+ }
+ return nil
+}
+
+func (d *driver) peerDbNetworkWalk(nid string, f func(*peerKey, *peerEntry) bool) error {
+ d.peerDb.Lock()
+ pMap, ok := d.peerDb.mp[nid]
+ if !ok {
+ d.peerDb.Unlock()
+ return nil
+ }
+ d.peerDb.Unlock()
+
+ pMap.Lock()
+ for pKeyStr, pEntry := range pMap.mp {
+ var pKey peerKey
+ if _, err := fmt.Sscan(pKeyStr, &pKey); err != nil {
+ logrus.Warnf("Peer key scan on network %s failed: %v", nid, err)
+ }
+
+ if f(&pKey, &pEntry) {
+ pMap.Unlock()
+ return nil
+ }
+ }
+ pMap.Unlock()
+
+ return nil
+}
+
+func (d *driver) peerDbSearch(nid string, peerIP net.IP) (net.HardwareAddr, net.IPMask, net.IP, error) {
+ var (
+ peerMac net.HardwareAddr
+ vtep net.IP
+ peerIPMask net.IPMask
+ found bool
+ )
+
+ err := d.peerDbNetworkWalk(nid, func(pKey *peerKey, pEntry *peerEntry) bool {
+ if pKey.peerIP.Equal(peerIP) {
+ peerMac = pKey.peerMac
+ peerIPMask = pEntry.peerIPMask
+ vtep = pEntry.vtep
+ found = true
+ return found
+ }
+
+ return found
+ })
+
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("peerdb search for peer ip %q failed: %v", peerIP, err)
+ }
+
+ if !found {
+ return nil, nil, nil, fmt.Errorf("peer ip %q not found in peerdb", peerIP)
+ }
+
+ return peerMac, peerIPMask, vtep, nil
+}
+
+func (d *driver) peerDbAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
+ peerMac net.HardwareAddr, vtep net.IP, isLocal bool) {
+
+ peerDbWg.Wait()
+
+ d.peerDb.Lock()
+ pMap, ok := d.peerDb.mp[nid]
+ if !ok {
+ d.peerDb.mp[nid] = &peerMap{
+ mp: make(map[string]peerEntry),
+ }
+
+ pMap = d.peerDb.mp[nid]
+ }
+ d.peerDb.Unlock()
+
+ pKey := peerKey{
+ peerIP: peerIP,
+ peerMac: peerMac,
+ }
+
+ pEntry := peerEntry{
+ eid: eid,
+ vtep: vtep,
+ peerIPMask: peerIPMask,
+ isLocal: isLocal,
+ }
+
+ pMap.Lock()
+ pMap.mp[pKey.String()] = pEntry
+ pMap.Unlock()
+}
+
+func (d *driver) peerDbDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
+ peerMac net.HardwareAddr, vtep net.IP) {
+ peerDbWg.Wait()
+
+ d.peerDb.Lock()
+ pMap, ok := d.peerDb.mp[nid]
+ if !ok {
+ d.peerDb.Unlock()
+ return
+ }
+ d.peerDb.Unlock()
+
+ pKey := peerKey{
+ peerIP: peerIP,
+ peerMac: peerMac,
+ }
+
+ pMap.Lock()
+ delete(pMap.mp, pKey.String())
+ pMap.Unlock()
+}
+
+func (d *driver) peerDbUpdateSandbox(nid string) {
+ d.peerDb.Lock()
+ pMap, ok := d.peerDb.mp[nid]
+ if !ok {
+ d.peerDb.Unlock()
+ return
+ }
+ d.peerDb.Unlock()
+
+ peerDbWg.Add(1)
+
+ var peerOps []func()
+ pMap.Lock()
+ for pKeyStr, pEntry := range pMap.mp {
+ var pKey peerKey
+ if _, err := fmt.Sscan(pKeyStr, &pKey); err != nil {
+ fmt.Printf("peer key scan failed: %v", err)
+ }
+
+ if pEntry.isLocal {
+ continue
+ }
+
+ // Go captures variables by reference. The pEntry could be
+ // pointing to the same memory location for every iteration. Make
+ // a copy of pEntry before capturing it in the following closure.
+ entry := pEntry
+ op := func() {
+ if err := d.peerAdd(nid, entry.eid, pKey.peerIP, entry.peerIPMask,
+ pKey.peerMac, entry.vtep,
+ false); err != nil {
+ fmt.Printf("peerdbupdate in sandbox failed for ip %s and mac %s: %v",
+ pKey.peerIP, pKey.peerMac, err)
+ }
+ }
+
+ peerOps = append(peerOps, op)
+ }
+ pMap.Unlock()
+
+ for _, op := range peerOps {
+ op()
+ }
+
+ peerDbWg.Done()
+}
+
+func (d *driver) peerAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
+ peerMac net.HardwareAddr, vtep net.IP, updateDb bool) error {
+
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+
+ if updateDb {
+ d.peerDbAdd(nid, eid, peerIP, peerIPMask, peerMac, vtep, false)
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return nil
+ }
+
+ sbox := n.sandbox()
+ if sbox == nil {
+ return nil
+ }
+
+ IP := &net.IPNet{
+ IP: peerIP,
+ Mask: peerIPMask,
+ }
+
+ s := n.getSubnetforIP(IP)
+ if s == nil {
+ return fmt.Errorf("couldn't find the subnet %q in network %q", IP.String(), n.id)
+ }
+
+ if err := n.obtainVxlanID(s); err != nil {
+ return fmt.Errorf("couldn't get vxlan id for %q: %v", s.subnetIP.String(), err)
+ }
+
+ if err := n.joinSubnetSandbox(s, false); err != nil {
+ return fmt.Errorf("subnet sandbox join failed for %q: %v", s.subnetIP.String(), err)
+ }
+
+ if err := d.checkEncryption(nid, vtep, n.vxlanID(s), false, true); err != nil {
+ logrus.Warn(err)
+ }
+
+ // Add neighbor entry for the peer IP
+ if err := sbox.AddNeighbor(peerIP, peerMac, false, sbox.NeighborOptions().LinkName(s.vxlanName)); err != nil {
+ return fmt.Errorf("could not add neigbor entry into the sandbox: %v", err)
+ }
+
+ // XXX Add fdb entry to the bridge for the peer mac
+
+ return nil
+}
+
+func (d *driver) peerDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
+ peerMac net.HardwareAddr, vtep net.IP, updateDb bool) error {
+
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+
+ if updateDb {
+ d.peerDbDelete(nid, eid, peerIP, peerIPMask, peerMac, vtep)
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return nil
+ }
+
+ sbox := n.sandbox()
+ if sbox == nil {
+ return nil
+ }
+
+ // Delete fdb entry to the bridge for the peer mac
+ if err := sbox.DeleteNeighbor(vtep, peerMac, true); err != nil {
+ return fmt.Errorf("could not delete fdb entry into the sandbox: %v", err)
+ }
+
+ // Delete neighbor entry for the peer IP
+ if err := sbox.DeleteNeighbor(peerIP, peerMac, true); err != nil {
+ return fmt.Errorf("could not delete neigbor entry into the sandbox: %v", err)
+ }
+
+ if err := d.checkEncryption(nid, vtep, 0, false, false); err != nil {
+ logrus.Warn(err)
+ }
+
+ return nil
+}
+
+func (d *driver) pushLocalDb() {
+ d.peerDbWalk(func(nid string, pKey *peerKey, pEntry *peerEntry) bool {
+ if pEntry.isLocal {
+ d.pushLocalEndpointEvent("join", nid, pEntry.eid)
+ }
+ return false
+ })
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/labels.go b/vendor/github.com/docker/libnetwork/drivers/windows/labels.go
new file mode 100644
index 0000000..b32c6ff
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/windows/labels.go
@@ -0,0 +1,39 @@
+package windows
+
+const (
+ // NetworkName label for bridge driver
+ NetworkName = "com.docker.network.windowsshim.networkname"
+
+ // HNSID of the discovered network
+ HNSID = "com.docker.network.windowsshim.hnsid"
+
+ // RoutingDomain of the network
+ RoutingDomain = "com.docker.network.windowsshim.routingdomain"
+
+ // Interface of the network
+ Interface = "com.docker.network.windowsshim.interface"
+
+ // QosPolicies of the endpoint
+ QosPolicies = "com.docker.endpoint.windowsshim.qospolicies"
+
+ // VLAN of the network
+ VLAN = "com.docker.network.windowsshim.vlanid"
+
+ // VSID of the network
+ VSID = "com.docker.network.windowsshim.vsid"
+
+ // DNSSuffix of the network
+ DNSSuffix = "com.docker.network.windowsshim.dnssuffix"
+
+ // DNSServers of the network
+ DNSServers = "com.docker.network.windowsshim.dnsservers"
+
+ // SourceMac of the network
+ SourceMac = "com.docker.network.windowsshim.sourcemac"
+
+ // DisableICC label
+ DisableICC = "com.docker.network.windowsshim.disableicc"
+
+ // DisableDNS label
+ DisableDNS = "com.docker.network.windowsshim.disable_dns"
+)
diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go
new file mode 100644
index 0000000..91dcf28
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go
@@ -0,0 +1,107 @@
+package overlay
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/types"
+ "github.com/gogo/protobuf/proto"
+)
+
+// Join method is invoked when a Sandbox is attached to an endpoint.
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return fmt.Errorf("could not find network with id %s", nid)
+ }
+
+ ep := n.endpoint(eid)
+ if ep == nil {
+ return fmt.Errorf("could not find endpoint with id %s", eid)
+ }
+
+ buf, err := proto.Marshal(&PeerRecord{
+ EndpointIP: ep.addr.String(),
+ EndpointMAC: ep.mac.String(),
+ TunnelEndpointIP: n.providerAddress,
+ })
+
+ if err != nil {
+ return err
+ }
+
+ if err := jinfo.AddTableEntry(ovPeerTable, eid, buf); err != nil {
+ logrus.Errorf("overlay: Failed adding table entry to joininfo: %v", err)
+ }
+ return nil
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+ if tableName != ovPeerTable {
+ logrus.Errorf("Unexpected table notification for table %s received", tableName)
+ return
+ }
+
+ eid := key
+
+ var peer PeerRecord
+ if err := proto.Unmarshal(value, &peer); err != nil {
+ logrus.Errorf("Failed to unmarshal peer record: %v", err)
+ return
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return
+ }
+
+ // Ignore local peers. We already know about them and they
+ // should not be added to vxlan fdb.
+ if peer.TunnelEndpointIP == n.providerAddress {
+ return
+ }
+
+ addr, err := types.ParseCIDR(peer.EndpointIP)
+ if err != nil {
+ logrus.Errorf("Invalid peer IP %s received in event notify", peer.EndpointIP)
+ return
+ }
+
+ mac, err := net.ParseMAC(peer.EndpointMAC)
+ if err != nil {
+ logrus.Errorf("Invalid mac %s received in event notify", peer.EndpointMAC)
+ return
+ }
+
+ vtep := net.ParseIP(peer.TunnelEndpointIP)
+ if vtep == nil {
+ logrus.Errorf("Invalid VTEP %s received in event notify", peer.TunnelEndpointIP)
+ return
+ }
+
+ if etype == driverapi.Delete {
+ d.peerDelete(nid, eid, addr.IP, addr.Mask, mac, vtep, true)
+ return
+ }
+
+ d.peerAdd(nid, eid, addr.IP, addr.Mask, mac, vtep, true)
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+// Leave method is invoked when a Sandbox detaches from an endpoint.
+func (d *driver) Leave(nid, eid string) error {
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go
new file mode 100644
index 0000000..3e45115
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go
@@ -0,0 +1,216 @@
+package overlay
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+
+ "github.com/Microsoft/hcsshim"
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/driverapi"
+)
+
+type endpointTable map[string]*endpoint
+
+const overlayEndpointPrefix = "overlay/endpoint"
+
+type endpoint struct {
+ id string
+ nid string
+ profileId string
+ remote bool
+ mac net.HardwareAddr
+ addr *net.IPNet
+}
+
+func validateID(nid, eid string) error {
+ if nid == "" {
+ return fmt.Errorf("invalid network id")
+ }
+
+ if eid == "" {
+ return fmt.Errorf("invalid endpoint id")
+ }
+
+ return nil
+}
+
+func (n *network) endpoint(eid string) *endpoint {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.endpoints[eid]
+}
+
+func (n *network) addEndpoint(ep *endpoint) {
+ n.Lock()
+ n.endpoints[ep.id] = ep
+ n.Unlock()
+}
+
+func (n *network) deleteEndpoint(eid string) {
+ n.Lock()
+ delete(n.endpoints, eid)
+ n.Unlock()
+}
+
+func (n *network) removeEndpointWithAddress(addr *net.IPNet) {
+ var networkEndpoint *endpoint
+ n.Lock()
+ for _, ep := range n.endpoints {
+ if ep.addr.IP.Equal(addr.IP) {
+ networkEndpoint = ep
+ break
+ }
+ }
+
+ if networkEndpoint != nil {
+ delete(n.endpoints, networkEndpoint.id)
+ }
+ n.Unlock()
+
+ if networkEndpoint != nil {
+ logrus.Debugf("Removing stale endpoint from HNS")
+ _, err := hcsshim.HNSEndpointRequest("DELETE", networkEndpoint.profileId, "")
+
+ if err != nil {
+ logrus.Debugf("Failed to delete stale overlay endpoint (%s) from hns", networkEndpoint.id[0:7])
+ }
+ }
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo,
+ epOptions map[string]interface{}) error {
+ var err error
+ if err = validateID(nid, eid); err != nil {
+ return err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return fmt.Errorf("network id %q not found", nid)
+ }
+
+ ep := n.endpoint(eid)
+ if ep != nil {
+ logrus.Debugf("Deleting stale endpoint %s", eid)
+ n.deleteEndpoint(eid)
+
+ _, err := hcsshim.HNSEndpointRequest("DELETE", ep.profileId, "")
+ if err != nil {
+ return err
+ }
+ }
+
+ ep = &endpoint{
+ id: eid,
+ nid: n.id,
+ addr: ifInfo.Address(),
+ mac: ifInfo.MacAddress(),
+ }
+
+ if ep.addr == nil {
+ return fmt.Errorf("create endpoint was not passed interface IP address")
+ }
+
+ if s := n.getSubnetforIP(ep.addr); s == nil {
+ return fmt.Errorf("no matching subnet for IP %q in network %q\n", ep.addr, nid)
+ }
+
+ // Todo: Add port bindings and qos policies here
+
+ hnsEndpoint := &hcsshim.HNSEndpoint{
+ Name: eid,
+ VirtualNetwork: n.hnsId,
+ IPAddress: ep.addr.IP,
+ EnableInternalDNS: true,
+ }
+
+ if ep.mac != nil {
+ hnsEndpoint.MacAddress = ep.mac.String()
+ }
+
+ paPolicy, err := json.Marshal(hcsshim.PaPolicy{
+ Type: "PA",
+ PA: n.providerAddress,
+ })
+
+ if err != nil {
+ return err
+ }
+
+ hnsEndpoint.Policies = append(hnsEndpoint.Policies, paPolicy)
+
+ configurationb, err := json.Marshal(hnsEndpoint)
+ if err != nil {
+ return err
+ }
+
+ hnsresponse, err := hcsshim.HNSEndpointRequest("POST", "", string(configurationb))
+ if err != nil {
+ return err
+ }
+
+ ep.profileId = hnsresponse.Id
+
+ if ep.mac == nil {
+ ep.mac, err = net.ParseMAC(hnsresponse.MacAddress)
+ if err != nil {
+ return err
+ }
+
+ if err := ifInfo.SetMacAddress(ep.mac); err != nil {
+ return err
+ }
+ }
+
+ n.addEndpoint(ep)
+
+ return nil
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return fmt.Errorf("network id %q not found", nid)
+ }
+
+ ep := n.endpoint(eid)
+ if ep == nil {
+ return fmt.Errorf("endpoint id %q not found", eid)
+ }
+
+ n.deleteEndpoint(eid)
+
+ _, err := hcsshim.HNSEndpointRequest("DELETE", ep.profileId, "")
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ if err := validateID(nid, eid); err != nil {
+ return nil, err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return nil, fmt.Errorf("network id %q not found", nid)
+ }
+
+ ep := n.endpoint(eid)
+ if ep == nil {
+ return nil, fmt.Errorf("endpoint id %q not found", eid)
+ }
+
+ data := make(map[string]interface{}, 1)
+ data["hnsid"] = ep.profileId
+ data["AllowUnqualifiedDNSQuery"] = true
+ return data, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go
new file mode 100644
index 0000000..65b7e38
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go
@@ -0,0 +1,380 @@
+package overlay
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/Microsoft/hcsshim"
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/types"
+)
+
+var (
+ hostMode bool
+ networkMu sync.Mutex
+)
+
+type networkTable map[string]*network
+
+type subnet struct {
+ vni uint32
+ subnetIP *net.IPNet
+ gwIP *net.IP
+}
+
+type subnetJSON struct {
+ SubnetIP string
+ GwIP string
+ Vni uint32
+}
+
+type network struct {
+ id string
+ name string
+ hnsId string
+ providerAddress string
+ interfaceName string
+ endpoints endpointTable
+ driver *driver
+ initEpoch int
+ initErr error
+ subnets []*subnet
+ secure bool
+ sync.Mutex
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ var (
+ networkName string
+ interfaceName string
+ staleNetworks []string
+ )
+
+ if id == "" {
+ return fmt.Errorf("invalid network id")
+ }
+
+ if nInfo == nil {
+ return fmt.Errorf("invalid network info structure")
+ }
+
+ if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
+ return types.BadRequestErrorf("ipv4 pool is empty")
+ }
+
+ staleNetworks = make([]string, 0)
+ vnis := make([]uint32, 0, len(ipV4Data))
+
+ existingNetwork := d.network(id)
+ if existingNetwork != nil {
+ logrus.Debugf("Network preexists. Deleting %s", id)
+ err := d.DeleteNetwork(id)
+ if err != nil {
+ logrus.Errorf("Error deleting stale network %s", err.Error())
+ }
+ }
+
+ n := &network{
+ id: id,
+ driver: d,
+ endpoints: endpointTable{},
+ subnets: []*subnet{},
+ }
+
+ genData, ok := option[netlabel.GenericData].(map[string]string)
+
+ if !ok {
+ return fmt.Errorf("Unknown generic data option")
+ }
+
+ for label, value := range genData {
+ switch label {
+ case "com.docker.network.windowsshim.networkname":
+ networkName = value
+ case "com.docker.network.windowsshim.interface":
+ interfaceName = value
+ case "com.docker.network.windowsshim.hnsid":
+ n.hnsId = value
+ case netlabel.OverlayVxlanIDList:
+ vniStrings := strings.Split(value, ",")
+ for _, vniStr := range vniStrings {
+ vni, err := strconv.Atoi(vniStr)
+ if err != nil {
+ return fmt.Errorf("invalid vxlan id value %q passed", vniStr)
+ }
+
+ vnis = append(vnis, uint32(vni))
+ }
+ }
+ }
+
+ // If we are getting vnis from libnetwork, either we get for
+ // all subnets or none.
+ if len(vnis) < len(ipV4Data) {
+ return fmt.Errorf("insufficient vnis(%d) passed to overlay. Windows driver requires VNIs to be prepopulated", len(vnis))
+ }
+
+ for i, ipd := range ipV4Data {
+ s := &subnet{
+ subnetIP: ipd.Pool,
+ gwIP: &ipd.Gateway.IP,
+ }
+
+ if len(vnis) != 0 {
+ s.vni = vnis[i]
+ }
+
+ d.Lock()
+ for _, network := range d.networks {
+ found := false
+ for _, sub := range network.subnets {
+ if sub.vni == s.vni {
+ staleNetworks = append(staleNetworks, network.id)
+ found = true
+ break
+ }
+ }
+ if found {
+ break
+ }
+ }
+ d.Unlock()
+
+ n.subnets = append(n.subnets, s)
+ }
+
+ for _, staleNetwork := range staleNetworks {
+ d.DeleteNetwork(staleNetwork)
+ }
+
+ n.name = networkName
+ if n.name == "" {
+ n.name = id
+ }
+
+ n.interfaceName = interfaceName
+
+ if nInfo != nil {
+ if err := nInfo.TableEventRegister(ovPeerTable, driverapi.EndpointObject); err != nil {
+ return err
+ }
+ }
+
+ d.addNetwork(n)
+
+ err := d.createHnsNetwork(n)
+
+ if err != nil {
+ d.deleteNetwork(id)
+ } else {
+ genData["com.docker.network.windowsshim.hnsid"] = n.hnsId
+ }
+
+ return err
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ if nid == "" {
+ return fmt.Errorf("invalid network id")
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return types.ForbiddenErrorf("could not find network with id %s", nid)
+ }
+
+ _, err := hcsshim.HNSNetworkRequest("DELETE", n.hnsId, "")
+ if err != nil {
+ return types.ForbiddenErrorf(err.Error())
+ }
+
+ d.deleteNetwork(nid)
+
+ return nil
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ return nil
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ return nil
+}
+
+func (d *driver) addNetwork(n *network) {
+ d.Lock()
+ d.networks[n.id] = n
+ d.Unlock()
+}
+
+func (d *driver) deleteNetwork(nid string) {
+ d.Lock()
+ delete(d.networks, nid)
+ d.Unlock()
+}
+
+func (d *driver) network(nid string) *network {
+ d.Lock()
+ defer d.Unlock()
+ return d.networks[nid]
+}
+
+// func (n *network) restoreNetworkEndpoints() error {
+// logrus.Infof("Restoring endpoints for overlay network: %s", n.id)
+
+// hnsresponse, err := hcsshim.HNSListEndpointRequest("GET", "", "")
+// if err != nil {
+// return err
+// }
+
+// for _, endpoint := range hnsresponse {
+// if endpoint.VirtualNetwork != n.hnsId {
+// continue
+// }
+
+// ep := n.convertToOverlayEndpoint(&endpoint)
+
+// if ep != nil {
+// logrus.Debugf("Restored endpoint:%s Remote:%t", ep.id, ep.remote)
+// n.addEndpoint(ep)
+// }
+// }
+
+// return nil
+// }
+
+func (n *network) convertToOverlayEndpoint(v *hcsshim.HNSEndpoint) *endpoint {
+ ep := &endpoint{
+ id: v.Name,
+ profileId: v.Id,
+ nid: n.id,
+ remote: v.IsRemoteEndpoint,
+ }
+
+ mac, err := net.ParseMAC(v.MacAddress)
+
+ if err != nil {
+ return nil
+ }
+
+ ep.mac = mac
+ ep.addr = &net.IPNet{
+ IP: v.IPAddress,
+ Mask: net.CIDRMask(32, 32),
+ }
+
+ return ep
+}
+
+func (d *driver) createHnsNetwork(n *network) error {
+
+ subnets := []hcsshim.Subnet{}
+
+ for _, s := range n.subnets {
+ subnet := hcsshim.Subnet{
+ AddressPrefix: s.subnetIP.String(),
+ }
+
+ if s.gwIP != nil {
+ subnet.GatewayAddress = s.gwIP.String()
+ }
+
+ vsidPolicy, err := json.Marshal(hcsshim.VsidPolicy{
+ Type: "VSID",
+ VSID: uint(s.vni),
+ })
+
+ if err != nil {
+ return err
+ }
+
+ subnet.Policies = append(subnet.Policies, vsidPolicy)
+ subnets = append(subnets, subnet)
+ }
+
+ network := &hcsshim.HNSNetwork{
+ Name: n.name,
+ Type: d.Type(),
+ Subnets: subnets,
+ NetworkAdapterName: n.interfaceName,
+ }
+
+ configurationb, err := json.Marshal(network)
+ if err != nil {
+ return err
+ }
+
+ configuration := string(configurationb)
+ logrus.Infof("HNSNetwork Request =%v", configuration)
+
+ hnsresponse, err := hcsshim.HNSNetworkRequest("POST", "", configuration)
+ if err != nil {
+ return err
+ }
+
+ n.hnsId = hnsresponse.Id
+ n.providerAddress = hnsresponse.ManagementIP
+
+ return nil
+}
+
+// contains return true if the passed ip belongs to one the network's
+// subnets
+func (n *network) contains(ip net.IP) bool {
+ for _, s := range n.subnets {
+ if s.subnetIP.Contains(ip) {
+ return true
+ }
+ }
+
+ return false
+}
+
+// getSubnetforIP returns the subnet to which the given IP belongs
+func (n *network) getSubnetforIP(ip *net.IPNet) *subnet {
+ for _, s := range n.subnets {
+ // first check if the mask lengths are the same
+ i, _ := s.subnetIP.Mask.Size()
+ j, _ := ip.Mask.Size()
+ if i != j {
+ continue
+ }
+ if s.subnetIP.Contains(ip.IP) {
+ return s
+ }
+ }
+ return nil
+}
+
+// getMatchingSubnet return the network's subnet that matches the input
+func (n *network) getMatchingSubnet(ip *net.IPNet) *subnet {
+ if ip == nil {
+ return nil
+ }
+ for _, s := range n.subnets {
+ // first check if the mask lengths are the same
+ i, _ := s.subnetIP.Mask.Size()
+ j, _ := ip.Mask.Size()
+ if i != j {
+ continue
+ }
+ if s.subnetIP.IP.Equal(ip.IP) {
+ return s
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.pb.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.pb.go
new file mode 100644
index 0000000..cfa0eee
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.pb.go
@@ -0,0 +1,468 @@
+// Code generated by protoc-gen-gogo.
+// source: overlay.proto
+// DO NOT EDIT!
+
+/*
+ Package overlay is a generated protocol buffer package.
+
+ It is generated from these files:
+ overlay.proto
+
+ It has these top-level messages:
+ PeerRecord
+*/
+package overlay
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+
+import strings "strings"
+import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
+import sort "sort"
+import strconv "strconv"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+const _ = proto.GoGoProtoPackageIsVersion1
+
+// PeerRecord defines the information corresponding to a peer
+// container in the overlay network.
+type PeerRecord struct {
+ // Endpoint IP is the IP of the container attachment on the
+ // given overlay network.
+ EndpointIP string `protobuf:"bytes,1,opt,name=endpoint_ip,json=endpointIp,proto3" json:"endpoint_ip,omitempty"`
+ // Endpoint MAC is the mac address of the container attachment
+ // on the given overlay network.
+ EndpointMAC string `protobuf:"bytes,2,opt,name=endpoint_mac,json=endpointMac,proto3" json:"endpoint_mac,omitempty"`
+ // Tunnel Endpoint IP defines the host IP for the host in
+ // which this container is running and can be reached by
+ // building a tunnel to that host IP.
+ TunnelEndpointIP string `protobuf:"bytes,3,opt,name=tunnel_endpoint_ip,json=tunnelEndpointIp,proto3" json:"tunnel_endpoint_ip,omitempty"`
+}
+
+func (m *PeerRecord) Reset() { *m = PeerRecord{} }
+func (*PeerRecord) ProtoMessage() {}
+func (*PeerRecord) Descriptor() ([]byte, []int) { return fileDescriptorOverlay, []int{0} }
+
+func init() {
+ proto.RegisterType((*PeerRecord)(nil), "overlay.PeerRecord")
+}
+func (this *PeerRecord) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&overlay.PeerRecord{")
+ s = append(s, "EndpointIP: "+fmt.Sprintf("%#v", this.EndpointIP)+",\n")
+ s = append(s, "EndpointMAC: "+fmt.Sprintf("%#v", this.EndpointMAC)+",\n")
+ s = append(s, "TunnelEndpointIP: "+fmt.Sprintf("%#v", this.TunnelEndpointIP)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringOverlay(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func extensionToGoStringOverlay(e map[int32]github_com_gogo_protobuf_proto.Extension) string {
+ if e == nil {
+ return "nil"
+ }
+ s := "map[int32]proto.Extension{"
+ keys := make([]int, 0, len(e))
+ for k := range e {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+ ss := []string{}
+ for _, k := range keys {
+ ss = append(ss, strconv.Itoa(k)+": "+e[int32(k)].GoString())
+ }
+ s += strings.Join(ss, ",") + "}"
+ return s
+}
+func (m *PeerRecord) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *PeerRecord) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.EndpointIP) > 0 {
+ data[i] = 0xa
+ i++
+ i = encodeVarintOverlay(data, i, uint64(len(m.EndpointIP)))
+ i += copy(data[i:], m.EndpointIP)
+ }
+ if len(m.EndpointMAC) > 0 {
+ data[i] = 0x12
+ i++
+ i = encodeVarintOverlay(data, i, uint64(len(m.EndpointMAC)))
+ i += copy(data[i:], m.EndpointMAC)
+ }
+ if len(m.TunnelEndpointIP) > 0 {
+ data[i] = 0x1a
+ i++
+ i = encodeVarintOverlay(data, i, uint64(len(m.TunnelEndpointIP)))
+ i += copy(data[i:], m.TunnelEndpointIP)
+ }
+ return i, nil
+}
+
+func encodeFixed64Overlay(data []byte, offset int, v uint64) int {
+ data[offset] = uint8(v)
+ data[offset+1] = uint8(v >> 8)
+ data[offset+2] = uint8(v >> 16)
+ data[offset+3] = uint8(v >> 24)
+ data[offset+4] = uint8(v >> 32)
+ data[offset+5] = uint8(v >> 40)
+ data[offset+6] = uint8(v >> 48)
+ data[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Overlay(data []byte, offset int, v uint32) int {
+ data[offset] = uint8(v)
+ data[offset+1] = uint8(v >> 8)
+ data[offset+2] = uint8(v >> 16)
+ data[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintOverlay(data []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ data[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ data[offset] = uint8(v)
+ return offset + 1
+}
+func (m *PeerRecord) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.EndpointIP)
+ if l > 0 {
+ n += 1 + l + sovOverlay(uint64(l))
+ }
+ l = len(m.EndpointMAC)
+ if l > 0 {
+ n += 1 + l + sovOverlay(uint64(l))
+ }
+ l = len(m.TunnelEndpointIP)
+ if l > 0 {
+ n += 1 + l + sovOverlay(uint64(l))
+ }
+ return n
+}
+
+func sovOverlay(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozOverlay(x uint64) (n int) {
+ return sovOverlay(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *PeerRecord) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PeerRecord{`,
+ `EndpointIP:` + fmt.Sprintf("%v", this.EndpointIP) + `,`,
+ `EndpointMAC:` + fmt.Sprintf("%v", this.EndpointMAC) + `,`,
+ `TunnelEndpointIP:` + fmt.Sprintf("%v", this.TunnelEndpointIP) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringOverlay(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *PeerRecord) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PeerRecord: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PeerRecord: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field EndpointIP", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthOverlay
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.EndpointIP = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field EndpointMAC", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthOverlay
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.EndpointMAC = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TunnelEndpointIP", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthOverlay
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TunnelEndpointIP = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipOverlay(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthOverlay
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipOverlay(data []byte) (n int, err error) {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if data[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthOverlay
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowOverlay
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipOverlay(data[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthOverlay = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowOverlay = fmt.Errorf("proto: integer overflow")
+)
+
+var fileDescriptorOverlay = []byte{
+ // 195 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0xcd, 0x2f, 0x4b, 0x2d,
+ 0xca, 0x49, 0xac, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x87, 0x72, 0xa5, 0x44, 0xd2,
+ 0xf3, 0xd3, 0xf3, 0xc1, 0x62, 0xfa, 0x20, 0x16, 0x44, 0x5a, 0x69, 0x2b, 0x23, 0x17, 0x57, 0x40,
+ 0x6a, 0x6a, 0x51, 0x50, 0x6a, 0x72, 0x7e, 0x51, 0x8a, 0x90, 0x3e, 0x17, 0x77, 0x6a, 0x5e, 0x4a,
+ 0x41, 0x7e, 0x66, 0x5e, 0x49, 0x7c, 0x66, 0x81, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xa7, 0x13, 0xdf,
+ 0xa3, 0x7b, 0xf2, 0x5c, 0xae, 0x50, 0x61, 0xcf, 0x80, 0x20, 0x2e, 0x98, 0x12, 0xcf, 0x02, 0x21,
+ 0x23, 0x2e, 0x1e, 0xb8, 0x86, 0xdc, 0xc4, 0x64, 0x09, 0x26, 0xb0, 0x0e, 0x7e, 0xa0, 0x0e, 0x6e,
+ 0x98, 0x0e, 0x5f, 0x47, 0xe7, 0x20, 0xb8, 0xa9, 0xbe, 0x89, 0xc9, 0x42, 0x4e, 0x5c, 0x42, 0x25,
+ 0xa5, 0x79, 0x79, 0xa9, 0x39, 0xf1, 0xc8, 0x76, 0x31, 0x83, 0x75, 0x8a, 0x00, 0x75, 0x0a, 0x84,
+ 0x80, 0x65, 0x91, 0x6c, 0x14, 0x28, 0x41, 0x15, 0x29, 0x70, 0x92, 0xb8, 0xf1, 0x50, 0x8e, 0xe1,
+ 0xc3, 0x43, 0x39, 0xc6, 0x86, 0x47, 0x72, 0x8c, 0x27, 0x80, 0xf8, 0x02, 0x10, 0x3f, 0x00, 0xe2,
+ 0x24, 0x36, 0xb0, 0xc7, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbf, 0xd7, 0x7d, 0x7d, 0x08,
+ 0x01, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.proto b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.proto
new file mode 100644
index 0000000..45b8c9d
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay.proto
@@ -0,0 +1,27 @@
+syntax = "proto3";
+
+import "gogoproto/gogo.proto";
+
+package overlay;
+
+option (gogoproto.marshaler_all) = true;
+option (gogoproto.unmarshaler_all) = true;
+option (gogoproto.stringer_all) = true;
+option (gogoproto.gostring_all) = true;
+option (gogoproto.sizer_all) = true;
+option (gogoproto.goproto_stringer_all) = false;
+
+// PeerRecord defines the information corresponding to a peer
+// container in the overlay network.
+message PeerRecord {
+ // Endpoint IP is the IP of the container attachment on the
+ // given overlay network.
+ string endpoint_ip = 1 [(gogoproto.customname) = "EndpointIP"];
+ // Endpoint MAC is the mac address of the container attachment
+ // on the given overlay network.
+ string endpoint_mac = 2 [(gogoproto.customname) = "EndpointMAC"];
+ // Tunnel Endpoint IP defines the host IP for the host in
+ // which this container is running and can be reached by
+ // building a tunnel to that host IP.
+ string tunnel_endpoint_ip = 3 [(gogoproto.customname) = "TunnelEndpointIP"];
+} \ No newline at end of file
diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go
new file mode 100644
index 0000000..111e517
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go
@@ -0,0 +1,159 @@
+package overlay
+
+//go:generate protoc -I.:../../Godeps/_workspace/src/github.com/gogo/protobuf --gogo_out=import_path=github.com/docker/libnetwork/drivers/overlay,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto:. overlay.proto
+
+import (
+ "encoding/json"
+ "net"
+ "sync"
+
+ "github.com/Microsoft/hcsshim"
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ networkType = "overlay"
+ vethPrefix = "veth"
+ vethLen = 7
+ secureOption = "encrypted"
+)
+
+type driver struct {
+ config map[string]interface{}
+ networks networkTable
+ store datastore.DataStore
+ localStore datastore.DataStore
+ once sync.Once
+ joinOnce sync.Once
+ sync.Mutex
+}
+
+// Init registers a new instance of overlay driver
+func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ c := driverapi.Capability{
+ DataScope: datastore.GlobalScope,
+ ConnectivityScope: datastore.GlobalScope,
+ }
+
+ d := &driver{
+ networks: networkTable{},
+ config: config,
+ }
+
+ if data, ok := config[netlabel.GlobalKVClient]; ok {
+ var err error
+ dsc, ok := data.(discoverapi.DatastoreConfigData)
+ if !ok {
+ return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
+ }
+ d.store, err = datastore.NewDataStoreFromConfig(dsc)
+ if err != nil {
+ return types.InternalErrorf("failed to initialize data store: %v", err)
+ }
+ }
+
+ if data, ok := config[netlabel.LocalKVClient]; ok {
+ var err error
+ dsc, ok := data.(discoverapi.DatastoreConfigData)
+ if !ok {
+ return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
+ }
+ d.localStore, err = datastore.NewDataStoreFromConfig(dsc)
+ if err != nil {
+ return types.InternalErrorf("failed to initialize local data store: %v", err)
+ }
+ }
+
+ d.restoreHNSNetworks()
+
+ return dc.RegisterDriver(networkType, d, c)
+}
+
+func (d *driver) restoreHNSNetworks() error {
+ logrus.Infof("Restoring existing overlay networks from HNS into docker")
+
+ hnsresponse, err := hcsshim.HNSListNetworkRequest("GET", "", "")
+ if err != nil {
+ return err
+ }
+
+ for _, v := range hnsresponse {
+ if v.Type != networkType {
+ continue
+ }
+
+ logrus.Infof("Restoring overlay network: %s", v.Name)
+ n := d.convertToOverlayNetwork(&v)
+ d.addNetwork(n)
+
+ //
+ // We assume that any network will be recreated on daemon restart
+ // and therefore don't restore hns endpoints for now
+ //
+ //n.restoreNetworkEndpoints()
+ }
+
+ return nil
+}
+
+func (d *driver) convertToOverlayNetwork(v *hcsshim.HNSNetwork) *network {
+ n := &network{
+ id: v.Name,
+ hnsId: v.Id,
+ driver: d,
+ endpoints: endpointTable{},
+ subnets: []*subnet{},
+ providerAddress: v.ManagementIP,
+ }
+
+ for _, hnsSubnet := range v.Subnets {
+ vsidPolicy := &hcsshim.VsidPolicy{}
+ for _, policy := range hnsSubnet.Policies {
+ if err := json.Unmarshal([]byte(policy), &vsidPolicy); err == nil && vsidPolicy.Type == "VSID" {
+ break
+ }
+ }
+
+ gwIP := net.ParseIP(hnsSubnet.GatewayAddress)
+ localsubnet := &subnet{
+ vni: uint32(vsidPolicy.VSID),
+ gwIP: &gwIP,
+ }
+
+ _, subnetIP, err := net.ParseCIDR(hnsSubnet.AddressPrefix)
+
+ if err != nil {
+ logrus.Errorf("Error parsing subnet address %s ", hnsSubnet.AddressPrefix)
+ continue
+ }
+
+ localsubnet.subnetIP = subnetIP
+
+ n.subnets = append(n.subnets, localsubnet)
+ }
+
+ return n
+}
+
+func (d *driver) Type() string {
+ return networkType
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return types.NotImplementedErrorf("not implemented")
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go
new file mode 100644
index 0000000..04581f7
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go
@@ -0,0 +1,120 @@
+package overlay
+
+import (
+ "fmt"
+ "net"
+
+ "encoding/json"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/types"
+
+ "github.com/Microsoft/hcsshim"
+)
+
+const ovPeerTable = "overlay_peer_table"
+
+func (d *driver) peerAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
+ peerMac net.HardwareAddr, vtep net.IP, updateDb bool) error {
+
+ logrus.Debugf("WINOVERLAY: Enter peerAdd for ca ip %s with ca mac %s", peerIP.String(), peerMac.String())
+
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return nil
+ }
+
+ if updateDb {
+ logrus.Info("WINOVERLAY: peerAdd: notifying HNS of the REMOTE endpoint")
+
+ hnsEndpoint := &hcsshim.HNSEndpoint{
+ Name: eid,
+ VirtualNetwork: n.hnsId,
+ MacAddress: peerMac.String(),
+ IPAddress: peerIP,
+ IsRemoteEndpoint: true,
+ }
+
+ paPolicy, err := json.Marshal(hcsshim.PaPolicy{
+ Type: "PA",
+ PA: vtep.String(),
+ })
+
+ if err != nil {
+ return err
+ }
+
+ hnsEndpoint.Policies = append(hnsEndpoint.Policies, paPolicy)
+
+ configurationb, err := json.Marshal(hnsEndpoint)
+ if err != nil {
+ return err
+ }
+
+ // Temp: We have to create an endpoint object to keep track of the HNS ID for
+ // this endpoint so that we can retrieve it later when the endpoint is deleted.
+ // This seems unnecessary when we already have dockers EID. See if we can pass
+ // the global EID to HNS to use as it's ID, rather than having each HNS assign
+ // it's own local ID for the endpoint
+
+ addr, err := types.ParseCIDR(peerIP.String() + "/32")
+ if err != nil {
+ return err
+ }
+
+ n.removeEndpointWithAddress(addr)
+
+ hnsresponse, err := hcsshim.HNSEndpointRequest("POST", "", string(configurationb))
+ if err != nil {
+ return err
+ }
+
+ ep := &endpoint{
+ id: eid,
+ nid: nid,
+ addr: addr,
+ mac: peerMac,
+ profileId: hnsresponse.Id,
+ remote: true,
+ }
+
+ n.addEndpoint(ep)
+ }
+
+ return nil
+}
+
+func (d *driver) peerDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
+ peerMac net.HardwareAddr, vtep net.IP, updateDb bool) error {
+
+ logrus.Infof("WINOVERLAY: Enter peerDelete for endpoint %s and peer ip %s", eid, peerIP.String())
+
+ if err := validateID(nid, eid); err != nil {
+ return err
+ }
+
+ n := d.network(nid)
+ if n == nil {
+ return nil
+ }
+
+ ep := n.endpoint(eid)
+ if ep == nil {
+ return fmt.Errorf("could not find endpoint with id %s", eid)
+ }
+
+ if updateDb {
+ _, err := hcsshim.HNSEndpointRequest("DELETE", ep.profileId, "")
+ if err != nil {
+ return err
+ }
+
+ n.deleteEndpoint(eid)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/windows.go
new file mode 100644
index 0000000..eb1522a
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/windows/windows.go
@@ -0,0 +1,771 @@
+// +build windows
+
+// Shim for the Host Network Service (HNS) to manage networking for
+// Windows Server containers and Hyper-V containers. This module
+// is a basic libnetwork driver that passes all the calls to HNS
+// It implements the 4 networking modes supported by HNS L2Bridge,
+// L2Tunnel, NAT and Transparent(DHCP)
+//
+// The network are stored in memory and docker daemon ensures discovering
+// and loading these networks on startup
+
+package windows
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/Microsoft/hcsshim"
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/types"
+)
+
+// networkConfiguration for network specific configuration
+type networkConfiguration struct {
+ ID string
+ Type string
+ Name string
+ HnsID string
+ RDID string
+ VLAN uint
+ VSID uint
+ DNSServers string
+ DNSSuffix string
+ SourceMac string
+ NetworkAdapterName string
+ dbIndex uint64
+ dbExists bool
+}
+
+// endpointConfiguration represents the user specified configuration for the sandbox endpoint
+type endpointOption struct {
+ MacAddress net.HardwareAddr
+ QosPolicies []types.QosPolicy
+ DNSServers []string
+ DisableDNS bool
+ DisableICC bool
+}
+
+type endpointConnectivity struct {
+ PortBindings []types.PortBinding
+ ExposedPorts []types.TransportPort
+}
+
+type hnsEndpoint struct {
+ id string
+ nid string
+ profileID string
+ Type string
+ macAddress net.HardwareAddr
+ epOption *endpointOption // User specified parameters
+ epConnectivity *endpointConnectivity // User specified parameters
+ portMapping []types.PortBinding // Operation port bindings
+ addr *net.IPNet
+ gateway net.IP
+ dbIndex uint64
+ dbExists bool
+}
+
+type hnsNetwork struct {
+ id string
+ created bool
+ config *networkConfiguration
+ endpoints map[string]*hnsEndpoint // key: endpoint id
+ driver *driver // The network's driver
+ sync.Mutex
+}
+
+type driver struct {
+ name string
+ networks map[string]*hnsNetwork
+ store datastore.DataStore
+ sync.Mutex
+}
+
+const (
+ errNotFound = "HNS failed with error : The object identifier does not represent a valid object. "
+)
+
+// IsBuiltinWindowsDriver vaidates if network-type is a builtin local-scoped driver
+func IsBuiltinLocalDriver(networkType string) bool {
+ if "l2bridge" == networkType || "l2tunnel" == networkType || "nat" == networkType || "ics" == networkType || "transparent" == networkType {
+ return true
+ }
+
+ return false
+}
+
+// New constructs a new bridge driver
+func newDriver(networkType string) *driver {
+ return &driver{name: networkType, networks: map[string]*hnsNetwork{}}
+}
+
+// GetInit returns an initializer for the given network type
+func GetInit(networkType string) func(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ return func(dc driverapi.DriverCallback, config map[string]interface{}) error {
+ if !IsBuiltinLocalDriver(networkType) {
+ return types.BadRequestErrorf("Network type not supported: %s", networkType)
+ }
+
+ d := newDriver(networkType)
+
+ err := d.initStore(config)
+ if err != nil {
+ return err
+ }
+
+ return dc.RegisterDriver(networkType, d, driverapi.Capability{
+ DataScope: datastore.LocalScope,
+ ConnectivityScope: datastore.LocalScope,
+ })
+ }
+}
+
+func (d *driver) getNetwork(id string) (*hnsNetwork, error) {
+ d.Lock()
+ defer d.Unlock()
+
+ if nw, ok := d.networks[id]; ok {
+ return nw, nil
+ }
+
+ return nil, types.NotFoundErrorf("network not found: %s", id)
+}
+
+func (n *hnsNetwork) getEndpoint(eid string) (*hnsEndpoint, error) {
+ n.Lock()
+ defer n.Unlock()
+
+ if ep, ok := n.endpoints[eid]; ok {
+ return ep, nil
+ }
+
+ return nil, types.NotFoundErrorf("Endpoint not found: %s", eid)
+}
+
+func (d *driver) parseNetworkOptions(id string, genericOptions map[string]string) (*networkConfiguration, error) {
+ config := &networkConfiguration{Type: d.name}
+
+ for label, value := range genericOptions {
+ switch label {
+ case NetworkName:
+ config.Name = value
+ case HNSID:
+ config.HnsID = value
+ case RoutingDomain:
+ config.RDID = value
+ case Interface:
+ config.NetworkAdapterName = value
+ case DNSSuffix:
+ config.DNSSuffix = value
+ case DNSServers:
+ config.DNSServers = value
+ case VLAN:
+ vlan, err := strconv.ParseUint(value, 10, 32)
+ if err != nil {
+ return nil, err
+ }
+ config.VLAN = uint(vlan)
+ case VSID:
+ vsid, err := strconv.ParseUint(value, 10, 32)
+ if err != nil {
+ return nil, err
+ }
+ config.VSID = uint(vsid)
+ }
+ }
+
+ config.ID = id
+ config.Type = d.name
+ return config, nil
+}
+
+func (c *networkConfiguration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
+ if len(ipamV6Data) > 0 {
+ return types.ForbiddenErrorf("windowsshim driver doesn't support v6 subnets")
+ }
+
+ if len(ipamV4Data) == 0 {
+ return types.BadRequestErrorf("network %s requires ipv4 configuration", id)
+ }
+
+ return nil
+}
+
+func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
+}
+
+func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
+ return "", nil
+}
+
+func (d *driver) createNetwork(config *networkConfiguration) error {
+ network := &hnsNetwork{
+ id: config.ID,
+ endpoints: make(map[string]*hnsEndpoint),
+ config: config,
+ driver: d,
+ }
+
+ d.Lock()
+ d.networks[config.ID] = network
+ d.Unlock()
+
+ return nil
+}
+
+// Create a new network
+func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
+ if _, err := d.getNetwork(id); err == nil {
+ return types.ForbiddenErrorf("network %s exists", id)
+ }
+
+ genData, ok := option[netlabel.GenericData].(map[string]string)
+ if !ok {
+ return fmt.Errorf("Unknown generic data option")
+ }
+
+ // Parse and validate the config. It should not conflict with existing networks' config
+ config, err := d.parseNetworkOptions(id, genData)
+ if err != nil {
+ return err
+ }
+
+ err = config.processIPAM(id, ipV4Data, ipV6Data)
+ if err != nil {
+ return err
+ }
+
+ err = d.createNetwork(config)
+
+ if err != nil {
+ return err
+ }
+
+ // A non blank hnsid indicates that the network was discovered
+ // from HNS. No need to call HNS if this network was discovered
+ // from HNS
+ if config.HnsID == "" {
+ subnets := []hcsshim.Subnet{}
+
+ for _, ipData := range ipV4Data {
+ subnet := hcsshim.Subnet{
+ AddressPrefix: ipData.Pool.String(),
+ }
+
+ if ipData.Gateway != nil {
+ subnet.GatewayAddress = ipData.Gateway.IP.String()
+ }
+
+ subnets = append(subnets, subnet)
+ }
+
+ network := &hcsshim.HNSNetwork{
+ Name: config.Name,
+ Type: d.name,
+ Subnets: subnets,
+ DNSServerList: config.DNSServers,
+ DNSSuffix: config.DNSSuffix,
+ SourceMac: config.SourceMac,
+ NetworkAdapterName: config.NetworkAdapterName,
+ }
+
+ if config.VLAN != 0 {
+ vlanPolicy, err := json.Marshal(hcsshim.VlanPolicy{
+ Type: "VLAN",
+ VLAN: config.VLAN,
+ })
+
+ if err != nil {
+ return err
+ }
+ network.Policies = append(network.Policies, vlanPolicy)
+ }
+
+ if config.VSID != 0 {
+ vsidPolicy, err := json.Marshal(hcsshim.VsidPolicy{
+ Type: "VSID",
+ VSID: config.VSID,
+ })
+
+ if err != nil {
+ return err
+ }
+ network.Policies = append(network.Policies, vsidPolicy)
+ }
+
+ if network.Name == "" {
+ network.Name = id
+ }
+
+ configurationb, err := json.Marshal(network)
+ if err != nil {
+ return err
+ }
+
+ configuration := string(configurationb)
+ logrus.Debugf("HNSNetwork Request =%v Address Space=%v", configuration, subnets)
+
+ hnsresponse, err := hcsshim.HNSNetworkRequest("POST", "", configuration)
+ if err != nil {
+ return err
+ }
+
+ config.HnsID = hnsresponse.Id
+ genData[HNSID] = config.HnsID
+ }
+
+ n, err := d.getNetwork(id)
+ if err != nil {
+ return err
+ }
+ n.created = true
+ return d.storeUpdate(config)
+}
+
+func (d *driver) DeleteNetwork(nid string) error {
+ n, err := d.getNetwork(nid)
+ if err != nil {
+ return types.InternalMaskableErrorf("%s", err)
+ }
+
+ n.Lock()
+ config := n.config
+ n.Unlock()
+
+ if n.created {
+ _, err = hcsshim.HNSNetworkRequest("DELETE", config.HnsID, "")
+ if err != nil && err.Error() != errNotFound {
+ return types.ForbiddenErrorf(err.Error())
+ }
+ }
+
+ d.Lock()
+ delete(d.networks, nid)
+ d.Unlock()
+
+ // delele endpoints belong to this network
+ for _, ep := range n.endpoints {
+ if err := d.storeDelete(ep); err != nil {
+ logrus.Warnf("Failed to remove bridge endpoint %s from store: %v", ep.id[0:7], err)
+ }
+ }
+
+ return d.storeDelete(config)
+}
+
+func convertQosPolicies(qosPolicies []types.QosPolicy) ([]json.RawMessage, error) {
+ var qps []json.RawMessage
+
+ // Enumerate through the qos policies specified by the user and convert
+ // them into the internal structure matching the JSON blob that can be
+ // understood by the HCS.
+ for _, elem := range qosPolicies {
+ encodedPolicy, err := json.Marshal(hcsshim.QosPolicy{
+ Type: "QOS",
+ MaximumOutgoingBandwidthInBytes: elem.MaxEgressBandwidth,
+ })
+
+ if err != nil {
+ return nil, err
+ }
+ qps = append(qps, encodedPolicy)
+ }
+ return qps, nil
+}
+
+func convertPortBindings(portBindings []types.PortBinding) ([]json.RawMessage, error) {
+ var pbs []json.RawMessage
+
+ // Enumerate through the port bindings specified by the user and convert
+ // them into the internal structure matching the JSON blob that can be
+ // understood by the HCS.
+ for _, elem := range portBindings {
+ proto := strings.ToUpper(elem.Proto.String())
+ if proto != "TCP" && proto != "UDP" {
+ return nil, fmt.Errorf("invalid protocol %s", elem.Proto.String())
+ }
+
+ if elem.HostPort != elem.HostPortEnd {
+ return nil, fmt.Errorf("Windows does not support more than one host port in NAT settings")
+ }
+
+ if len(elem.HostIP) != 0 {
+ return nil, fmt.Errorf("Windows does not support host IP addresses in NAT settings")
+ }
+
+ encodedPolicy, err := json.Marshal(hcsshim.NatPolicy{
+ Type: "NAT",
+ ExternalPort: elem.HostPort,
+ InternalPort: elem.Port,
+ Protocol: elem.Proto.String(),
+ })
+
+ if err != nil {
+ return nil, err
+ }
+ pbs = append(pbs, encodedPolicy)
+ }
+ return pbs, nil
+}
+
+func parsePortBindingPolicies(policies []json.RawMessage) ([]types.PortBinding, error) {
+ var bindings []types.PortBinding
+ hcsPolicy := &hcsshim.NatPolicy{}
+
+ for _, elem := range policies {
+
+ if err := json.Unmarshal([]byte(elem), &hcsPolicy); err != nil || hcsPolicy.Type != "NAT" {
+ continue
+ }
+
+ binding := types.PortBinding{
+ HostPort: hcsPolicy.ExternalPort,
+ HostPortEnd: hcsPolicy.ExternalPort,
+ Port: hcsPolicy.InternalPort,
+ Proto: types.ParseProtocol(hcsPolicy.Protocol),
+ HostIP: net.IPv4(0, 0, 0, 0),
+ }
+
+ bindings = append(bindings, binding)
+ }
+
+ return bindings, nil
+}
+
+func parseEndpointOptions(epOptions map[string]interface{}) (*endpointOption, error) {
+ if epOptions == nil {
+ return nil, nil
+ }
+
+ ec := &endpointOption{}
+
+ if opt, ok := epOptions[netlabel.MacAddress]; ok {
+ if mac, ok := opt.(net.HardwareAddr); ok {
+ ec.MacAddress = mac
+ } else {
+ return nil, fmt.Errorf("Invalid endpoint configuration")
+ }
+ }
+
+ if opt, ok := epOptions[QosPolicies]; ok {
+ if policies, ok := opt.([]types.QosPolicy); ok {
+ ec.QosPolicies = policies
+ } else {
+ return nil, fmt.Errorf("Invalid endpoint configuration")
+ }
+ }
+
+ if opt, ok := epOptions[netlabel.DNSServers]; ok {
+ if dns, ok := opt.([]string); ok {
+ ec.DNSServers = dns
+ } else {
+ return nil, fmt.Errorf("Invalid endpoint configuration")
+ }
+ }
+
+ if opt, ok := epOptions[DisableICC]; ok {
+ if disableICC, ok := opt.(bool); ok {
+ ec.DisableICC = disableICC
+ } else {
+ return nil, fmt.Errorf("Invalid endpoint configuration")
+ }
+ }
+
+ if opt, ok := epOptions[DisableDNS]; ok {
+ if disableDNS, ok := opt.(bool); ok {
+ ec.DisableDNS = disableDNS
+ } else {
+ return nil, fmt.Errorf("Invalid endpoint configuration")
+ }
+ }
+
+ return ec, nil
+}
+
+func parseEndpointConnectivity(epOptions map[string]interface{}) (*endpointConnectivity, error) {
+ if epOptions == nil {
+ return nil, nil
+ }
+
+ ec := &endpointConnectivity{}
+
+ if opt, ok := epOptions[netlabel.PortMap]; ok {
+ if bs, ok := opt.([]types.PortBinding); ok {
+ ec.PortBindings = bs
+ } else {
+ return nil, fmt.Errorf("Invalid endpoint configuration")
+ }
+ }
+
+ if opt, ok := epOptions[netlabel.ExposedPorts]; ok {
+ if ports, ok := opt.([]types.TransportPort); ok {
+ ec.ExposedPorts = ports
+ } else {
+ return nil, fmt.Errorf("Invalid endpoint configuration")
+ }
+ }
+ return ec, nil
+}
+
+func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
+ n, err := d.getNetwork(nid)
+ if err != nil {
+ return err
+ }
+
+ // Check if endpoint id is good and retrieve corresponding endpoint
+ ep, err := n.getEndpoint(eid)
+ if err == nil && ep != nil {
+ return driverapi.ErrEndpointExists(eid)
+ }
+
+ endpointStruct := &hcsshim.HNSEndpoint{
+ VirtualNetwork: n.config.HnsID,
+ }
+
+ epOption, err := parseEndpointOptions(epOptions)
+ if err != nil {
+ return err
+ }
+ epConnectivity, err := parseEndpointConnectivity(epOptions)
+ if err != nil {
+ return err
+ }
+
+ macAddress := ifInfo.MacAddress()
+ // Use the macaddress if it was provided
+ if macAddress != nil {
+ endpointStruct.MacAddress = strings.Replace(macAddress.String(), ":", "-", -1)
+ }
+
+ endpointStruct.Policies, err = convertPortBindings(epConnectivity.PortBindings)
+ if err != nil {
+ return err
+ }
+
+ qosPolicies, err := convertQosPolicies(epOption.QosPolicies)
+ if err != nil {
+ return err
+ }
+ endpointStruct.Policies = append(endpointStruct.Policies, qosPolicies...)
+
+ if ifInfo.Address() != nil {
+ endpointStruct.IPAddress = ifInfo.Address().IP
+ }
+
+ endpointStruct.DNSServerList = strings.Join(epOption.DNSServers, ",")
+
+ if n.driver.name == "nat" && !epOption.DisableDNS {
+ endpointStruct.EnableInternalDNS = true
+ }
+
+ endpointStruct.DisableICC = epOption.DisableICC
+
+ configurationb, err := json.Marshal(endpointStruct)
+ if err != nil {
+ return err
+ }
+
+ hnsresponse, err := hcsshim.HNSEndpointRequest("POST", "", string(configurationb))
+ if err != nil {
+ return err
+ }
+
+ mac, err := net.ParseMAC(hnsresponse.MacAddress)
+ if err != nil {
+ return err
+ }
+
+ // TODO For now the ip mask is not in the info generated by HNS
+ endpoint := &hnsEndpoint{
+ id: eid,
+ nid: n.id,
+ Type: d.name,
+ addr: &net.IPNet{IP: hnsresponse.IPAddress, Mask: hnsresponse.IPAddress.DefaultMask()},
+ macAddress: mac,
+ }
+
+ if hnsresponse.GatewayAddress != "" {
+ endpoint.gateway = net.ParseIP(hnsresponse.GatewayAddress)
+ }
+
+ endpoint.profileID = hnsresponse.Id
+ endpoint.epConnectivity = epConnectivity
+ endpoint.epOption = epOption
+ endpoint.portMapping, err = parsePortBindingPolicies(hnsresponse.Policies)
+
+ if err != nil {
+ hcsshim.HNSEndpointRequest("DELETE", hnsresponse.Id, "")
+ return err
+ }
+
+ n.Lock()
+ n.endpoints[eid] = endpoint
+ n.Unlock()
+
+ if ifInfo.Address() == nil {
+ ifInfo.SetIPAddress(endpoint.addr)
+ }
+
+ if macAddress == nil {
+ ifInfo.SetMacAddress(endpoint.macAddress)
+ }
+
+ if err = d.storeUpdate(endpoint); err != nil {
+ return fmt.Errorf("failed to save endpoint %s to store: %v", endpoint.id[0:7], err)
+ }
+
+ return nil
+}
+
+func (d *driver) DeleteEndpoint(nid, eid string) error {
+ n, err := d.getNetwork(nid)
+ if err != nil {
+ return types.InternalMaskableErrorf("%s", err)
+ }
+
+ ep, err := n.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ n.Lock()
+ delete(n.endpoints, eid)
+ n.Unlock()
+
+ _, err = hcsshim.HNSEndpointRequest("DELETE", ep.profileID, "")
+ if err != nil && err.Error() != errNotFound {
+ return err
+ }
+
+ if err := d.storeDelete(ep); err != nil {
+ logrus.Warnf("Failed to remove bridge endpoint %s from store: %v", ep.id[0:7], err)
+ }
+ return nil
+}
+
+func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return nil, err
+ }
+
+ ep, err := network.getEndpoint(eid)
+ if err != nil {
+ return nil, err
+ }
+
+ data := make(map[string]interface{}, 1)
+ if network.driver.name == "nat" {
+ data["AllowUnqualifiedDNSQuery"] = true
+ }
+
+ data["hnsid"] = ep.profileID
+ if ep.epConnectivity.ExposedPorts != nil {
+ // Return a copy of the config data
+ epc := make([]types.TransportPort, 0, len(ep.epConnectivity.ExposedPorts))
+ for _, tp := range ep.epConnectivity.ExposedPorts {
+ epc = append(epc, tp.GetCopy())
+ }
+ data[netlabel.ExposedPorts] = epc
+ }
+
+ if ep.portMapping != nil {
+ // Return a copy of the operational data
+ pmc := make([]types.PortBinding, 0, len(ep.portMapping))
+ for _, pm := range ep.portMapping {
+ pmc = append(pmc, pm.GetCopy())
+ }
+ data[netlabel.PortMap] = pmc
+ }
+
+ if len(ep.macAddress) != 0 {
+ data[netlabel.MacAddress] = ep.macAddress
+ }
+ return data, nil
+}
+
+// Join method is invoked when a Sandbox is attached to an endpoint.
+func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return err
+ }
+
+ // Ensure that the endpoint exists
+ endpoint, err := network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ err = jinfo.SetGateway(endpoint.gateway)
+ if err != nil {
+ return err
+ }
+
+ // This is just a stub for now
+
+ jinfo.DisableGatewayService()
+ return nil
+}
+
+// Leave method is invoked when a Sandbox detaches from an endpoint.
+func (d *driver) Leave(nid, eid string) error {
+ network, err := d.getNetwork(nid)
+ if err != nil {
+ return types.InternalMaskableErrorf("%s", err)
+ }
+
+ // Ensure that the endpoint exists
+ _, err = network.getEndpoint(eid)
+ if err != nil {
+ return err
+ }
+
+ // This is just a stub for now
+
+ return nil
+}
+
+func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
+ return nil
+}
+
+func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
+ return nil
+}
+
+func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
+ return nil, types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) NetworkFree(id string) error {
+ return types.NotImplementedErrorf("not implemented")
+}
+
+func (d *driver) Type() string {
+ return d.name
+}
+
+func (d *driver) IsBuiltIn() bool {
+ return true
+}
+
+// DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
+func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
+func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/windows_store.go b/vendor/github.com/docker/libnetwork/drivers/windows/windows_store.go
new file mode 100644
index 0000000..bbed5ae
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers/windows/windows_store.go
@@ -0,0 +1,339 @@
+// +build windows
+
+package windows
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ windowsPrefix = "windows"
+ windowsEndpointPrefix = "windows-endpoint"
+)
+
+func (d *driver) initStore(option map[string]interface{}) error {
+ if data, ok := option[netlabel.LocalKVClient]; ok {
+ var err error
+ dsc, ok := data.(discoverapi.DatastoreConfigData)
+ if !ok {
+ return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
+ }
+ d.store, err = datastore.NewDataStoreFromConfig(dsc)
+ if err != nil {
+ return types.InternalErrorf("windows driver failed to initialize data store: %v", err)
+ }
+
+ err = d.populateNetworks()
+ if err != nil {
+ return err
+ }
+
+ err = d.populateEndpoints()
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (d *driver) populateNetworks() error {
+ kvol, err := d.store.List(datastore.Key(windowsPrefix), &networkConfiguration{Type: d.name})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ return fmt.Errorf("failed to get windows network configurations from store: %v", err)
+ }
+
+ // It's normal for network configuration state to be empty. Just return.
+ if err == datastore.ErrKeyNotFound {
+ return nil
+ }
+
+ for _, kvo := range kvol {
+ ncfg := kvo.(*networkConfiguration)
+ if ncfg.Type != d.name {
+ continue
+ }
+ if err = d.createNetwork(ncfg); err != nil {
+ logrus.Warnf("could not create windows network for id %s hnsid %s while booting up from persistent state: %v", ncfg.ID, ncfg.HnsID, err)
+ }
+ logrus.Debugf("Network (%s) restored", ncfg.ID[0:7])
+ }
+
+ return nil
+}
+
+func (d *driver) populateEndpoints() error {
+ kvol, err := d.store.List(datastore.Key(windowsEndpointPrefix), &hnsEndpoint{Type: d.name})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ return fmt.Errorf("failed to get endpoints from store: %v", err)
+ }
+
+ if err == datastore.ErrKeyNotFound {
+ return nil
+ }
+
+ for _, kvo := range kvol {
+ ep := kvo.(*hnsEndpoint)
+ if ep.Type != d.name {
+ continue
+ }
+ n, ok := d.networks[ep.nid]
+ if !ok {
+ logrus.Debugf("Network (%s) not found for restored endpoint (%s)", ep.nid[0:7], ep.id[0:7])
+ logrus.Debugf("Deleting stale endpoint (%s) from store", ep.id[0:7])
+ if err := d.storeDelete(ep); err != nil {
+ logrus.Debugf("Failed to delete stale endpoint (%s) from store", ep.id[0:7])
+ }
+ continue
+ }
+ n.endpoints[ep.id] = ep
+ logrus.Debugf("Endpoint (%s) restored to network (%s)", ep.id[0:7], ep.nid[0:7])
+ }
+
+ return nil
+}
+
+func (d *driver) storeUpdate(kvObject datastore.KVObject) error {
+ if d.store == nil {
+ logrus.Warnf("store not initialized. kv object %s is not added to the store", datastore.Key(kvObject.Key()...))
+ return nil
+ }
+
+ if err := d.store.PutObjectAtomic(kvObject); err != nil {
+ return fmt.Errorf("failed to update store for object type %T: %v", kvObject, err)
+ }
+
+ return nil
+}
+
+func (d *driver) storeDelete(kvObject datastore.KVObject) error {
+ if d.store == nil {
+ logrus.Debugf("store not initialized. kv object %s is not deleted from store", datastore.Key(kvObject.Key()...))
+ return nil
+ }
+
+retry:
+ if err := d.store.DeleteObjectAtomic(kvObject); err != nil {
+ if err == datastore.ErrKeyModified {
+ if err := d.store.GetObject(datastore.Key(kvObject.Key()...), kvObject); err != nil {
+ return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err)
+ }
+ goto retry
+ }
+ return err
+ }
+
+ return nil
+}
+
+func (ncfg *networkConfiguration) MarshalJSON() ([]byte, error) {
+ nMap := make(map[string]interface{})
+
+ nMap["ID"] = ncfg.ID
+ nMap["Type"] = ncfg.Type
+ nMap["Name"] = ncfg.Name
+ nMap["HnsID"] = ncfg.HnsID
+ nMap["VLAN"] = ncfg.VLAN
+ nMap["VSID"] = ncfg.VSID
+ nMap["DNSServers"] = ncfg.DNSServers
+ nMap["DNSSuffix"] = ncfg.DNSSuffix
+ nMap["SourceMac"] = ncfg.SourceMac
+ nMap["NetworkAdapterName"] = ncfg.NetworkAdapterName
+
+ return json.Marshal(nMap)
+}
+
+func (ncfg *networkConfiguration) UnmarshalJSON(b []byte) error {
+ var (
+ err error
+ nMap map[string]interface{}
+ )
+
+ if err = json.Unmarshal(b, &nMap); err != nil {
+ return err
+ }
+
+ ncfg.ID = nMap["ID"].(string)
+ ncfg.Type = nMap["Type"].(string)
+ ncfg.Name = nMap["Name"].(string)
+ ncfg.HnsID = nMap["HnsID"].(string)
+ ncfg.VLAN = uint(nMap["VLAN"].(float64))
+ ncfg.VSID = uint(nMap["VSID"].(float64))
+ ncfg.DNSServers = nMap["DNSServers"].(string)
+ ncfg.DNSSuffix = nMap["DNSSuffix"].(string)
+ ncfg.SourceMac = nMap["SourceMac"].(string)
+ ncfg.NetworkAdapterName = nMap["NetworkAdapterName"].(string)
+ return nil
+}
+
+func (ncfg *networkConfiguration) Key() []string {
+ return []string{windowsPrefix + ncfg.Type, ncfg.ID}
+}
+
+func (ncfg *networkConfiguration) KeyPrefix() []string {
+ return []string{windowsPrefix + ncfg.Type}
+}
+
+func (ncfg *networkConfiguration) Value() []byte {
+ b, err := json.Marshal(ncfg)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (ncfg *networkConfiguration) SetValue(value []byte) error {
+ return json.Unmarshal(value, ncfg)
+}
+
+func (ncfg *networkConfiguration) Index() uint64 {
+ return ncfg.dbIndex
+}
+
+func (ncfg *networkConfiguration) SetIndex(index uint64) {
+ ncfg.dbIndex = index
+ ncfg.dbExists = true
+}
+
+func (ncfg *networkConfiguration) Exists() bool {
+ return ncfg.dbExists
+}
+
+func (ncfg *networkConfiguration) Skip() bool {
+ return false
+}
+
+func (ncfg *networkConfiguration) New() datastore.KVObject {
+ return &networkConfiguration{Type: ncfg.Type}
+}
+
+func (ncfg *networkConfiguration) CopyTo(o datastore.KVObject) error {
+ dstNcfg := o.(*networkConfiguration)
+ *dstNcfg = *ncfg
+ return nil
+}
+
+func (ncfg *networkConfiguration) DataScope() string {
+ return datastore.LocalScope
+}
+
+func (ep *hnsEndpoint) MarshalJSON() ([]byte, error) {
+ epMap := make(map[string]interface{})
+ epMap["id"] = ep.id
+ epMap["nid"] = ep.nid
+ epMap["Type"] = ep.Type
+ epMap["profileID"] = ep.profileID
+ epMap["MacAddress"] = ep.macAddress.String()
+ if ep.addr.IP != nil {
+ epMap["Addr"] = ep.addr.String()
+ }
+ if ep.gateway != nil {
+ epMap["gateway"] = ep.gateway.String()
+ }
+ epMap["epOption"] = ep.epOption
+ epMap["epConnectivity"] = ep.epConnectivity
+ epMap["PortMapping"] = ep.portMapping
+
+ return json.Marshal(epMap)
+}
+
+func (ep *hnsEndpoint) UnmarshalJSON(b []byte) error {
+ var (
+ err error
+ epMap map[string]interface{}
+ )
+
+ if err = json.Unmarshal(b, &epMap); err != nil {
+ return fmt.Errorf("Failed to unmarshal to endpoint: %v", err)
+ }
+ if v, ok := epMap["MacAddress"]; ok {
+ if ep.macAddress, err = net.ParseMAC(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode endpoint MAC address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ if v, ok := epMap["Addr"]; ok {
+ if ep.addr, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode endpoint IPv4 address (%s) after json unmarshal: %v", v.(string), err)
+ }
+ }
+ if v, ok := epMap["gateway"]; ok {
+ ep.gateway = net.ParseIP(v.(string))
+ }
+ ep.id = epMap["id"].(string)
+ ep.Type = epMap["Type"].(string)
+ ep.nid = epMap["nid"].(string)
+ ep.profileID = epMap["profileID"].(string)
+ d, _ := json.Marshal(epMap["epOption"])
+ if err := json.Unmarshal(d, &ep.epOption); err != nil {
+ logrus.Warnf("Failed to decode endpoint container config %v", err)
+ }
+ d, _ = json.Marshal(epMap["epConnectivity"])
+ if err := json.Unmarshal(d, &ep.epConnectivity); err != nil {
+ logrus.Warnf("Failed to decode endpoint external connectivity configuration %v", err)
+ }
+ d, _ = json.Marshal(epMap["PortMapping"])
+ if err := json.Unmarshal(d, &ep.portMapping); err != nil {
+ logrus.Warnf("Failed to decode endpoint port mapping %v", err)
+ }
+
+ return nil
+}
+
+func (ep *hnsEndpoint) Key() []string {
+ return []string{windowsEndpointPrefix + ep.Type, ep.id}
+}
+
+func (ep *hnsEndpoint) KeyPrefix() []string {
+ return []string{windowsEndpointPrefix + ep.Type}
+}
+
+func (ep *hnsEndpoint) Value() []byte {
+ b, err := json.Marshal(ep)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (ep *hnsEndpoint) SetValue(value []byte) error {
+ return json.Unmarshal(value, ep)
+}
+
+func (ep *hnsEndpoint) Index() uint64 {
+ return ep.dbIndex
+}
+
+func (ep *hnsEndpoint) SetIndex(index uint64) {
+ ep.dbIndex = index
+ ep.dbExists = true
+}
+
+func (ep *hnsEndpoint) Exists() bool {
+ return ep.dbExists
+}
+
+func (ep *hnsEndpoint) Skip() bool {
+ return false
+}
+
+func (ep *hnsEndpoint) New() datastore.KVObject {
+ return &hnsEndpoint{Type: ep.Type}
+}
+
+func (ep *hnsEndpoint) CopyTo(o datastore.KVObject) error {
+ dstEp := o.(*hnsEndpoint)
+ *dstEp = *ep
+ return nil
+}
+
+func (ep *hnsEndpoint) DataScope() string {
+ return datastore.LocalScope
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers_experimental_linux.go b/vendor/github.com/docker/libnetwork/drivers_experimental_linux.go
new file mode 100644
index 0000000..4f540d4
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers_experimental_linux.go
@@ -0,0 +1,9 @@
+package libnetwork
+
+import "github.com/docker/libnetwork/drivers/ipvlan"
+
+func additionalDrivers() []initializer {
+ return []initializer{
+ {ipvlan.Init, "ipvlan"},
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers_freebsd.go b/vendor/github.com/docker/libnetwork/drivers_freebsd.go
new file mode 100644
index 0000000..d117c25
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers_freebsd.go
@@ -0,0 +1,13 @@
+package libnetwork
+
+import (
+ "github.com/docker/libnetwork/drivers/null"
+ "github.com/docker/libnetwork/drivers/remote"
+)
+
+func getInitializers(experimental bool) []initializer {
+ return []initializer{
+ {null.Init, "null"},
+ {remote.Init, "remote"},
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers_ipam.go b/vendor/github.com/docker/libnetwork/drivers_ipam.go
new file mode 100644
index 0000000..be0204a
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers_ipam.go
@@ -0,0 +1,23 @@
+package libnetwork
+
+import (
+ "github.com/docker/libnetwork/drvregistry"
+ "github.com/docker/libnetwork/ipamapi"
+ builtinIpam "github.com/docker/libnetwork/ipams/builtin"
+ nullIpam "github.com/docker/libnetwork/ipams/null"
+ remoteIpam "github.com/docker/libnetwork/ipams/remote"
+)
+
+func initIPAMDrivers(r *drvregistry.DrvRegistry, lDs, gDs interface{}) error {
+ for _, fn := range [](func(ipamapi.Callback, interface{}, interface{}) error){
+ builtinIpam.Init,
+ remoteIpam.Init,
+ nullIpam.Init,
+ } {
+ if err := fn(r, lDs, gDs); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers_linux.go b/vendor/github.com/docker/libnetwork/drivers_linux.go
new file mode 100644
index 0000000..08db380
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers_linux.go
@@ -0,0 +1,22 @@
+package libnetwork
+
+import (
+ "github.com/docker/libnetwork/drivers/bridge"
+ "github.com/docker/libnetwork/drivers/host"
+ "github.com/docker/libnetwork/drivers/null"
+ "github.com/docker/libnetwork/drivers/remote"
+)
+
+func getInitializers(experimental bool) []initializer {
+ in := []initializer{
+ {bridge.Init, "bridge"},
+ {host.Init, "host"},
+ {null.Init, "null"},
+ {remote.Init, "remote"},
+ }
+
+ if experimental {
+ in = append(in, additionalDrivers()...)
+ }
+ return in
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers_solaris.go b/vendor/github.com/docker/libnetwork/drivers_solaris.go
new file mode 100644
index 0000000..c4fcd96
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers_solaris.go
@@ -0,0 +1,15 @@
+package libnetwork
+
+import (
+ "github.com/docker/libnetwork/drivers/null"
+ "github.com/docker/libnetwork/drivers/solaris/bridge"
+ "github.com/docker/libnetwork/drivers/solaris/overlay"
+)
+
+func getInitializers(experimental bool) []initializer {
+ return []initializer{
+ {overlay.Init, "overlay"},
+ {bridge.Init, "bridge"},
+ {null.Init, "null"},
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/drivers_windows.go b/vendor/github.com/docker/libnetwork/drivers_windows.go
new file mode 100644
index 0000000..384d855
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drivers_windows.go
@@ -0,0 +1,20 @@
+package libnetwork
+
+import (
+ "github.com/docker/libnetwork/drivers/null"
+ "github.com/docker/libnetwork/drivers/remote"
+ "github.com/docker/libnetwork/drivers/windows"
+ "github.com/docker/libnetwork/drivers/windows/overlay"
+)
+
+func getInitializers(experimental bool) []initializer {
+ return []initializer{
+ {null.Init, "null"},
+ {overlay.Init, "overlay"},
+ {remote.Init, "remote"},
+ {windows.GetInit("transparent"), "transparent"},
+ {windows.GetInit("l2bridge"), "l2bridge"},
+ {windows.GetInit("l2tunnel"), "l2tunnel"},
+ {windows.GetInit("nat"), "nat"},
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/drvregistry/drvregistry.go b/vendor/github.com/docker/libnetwork/drvregistry/drvregistry.go
new file mode 100644
index 0000000..b3fe9ba
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/drvregistry/drvregistry.go
@@ -0,0 +1,228 @@
+package drvregistry
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/types"
+)
+
+type driverData struct {
+ driver driverapi.Driver
+ capability driverapi.Capability
+}
+
+type ipamData struct {
+ driver ipamapi.Ipam
+ capability *ipamapi.Capability
+ // default address spaces are provided by ipam driver at registration time
+ defaultLocalAddressSpace, defaultGlobalAddressSpace string
+}
+
+type driverTable map[string]*driverData
+type ipamTable map[string]*ipamData
+
+// DrvRegistry holds the registry of all network drivers and IPAM drivers that it knows about.
+type DrvRegistry struct {
+ sync.Mutex
+ drivers driverTable
+ ipamDrivers ipamTable
+ dfn DriverNotifyFunc
+ ifn IPAMNotifyFunc
+ pluginGetter plugingetter.PluginGetter
+}
+
+// Functors definition
+
+// InitFunc defines the driver initialization function signature.
+type InitFunc func(driverapi.DriverCallback, map[string]interface{}) error
+
+// IPAMWalkFunc defines the IPAM driver table walker function signature.
+type IPAMWalkFunc func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool
+
+// DriverWalkFunc defines the network driver table walker function signature.
+type DriverWalkFunc func(name string, driver driverapi.Driver, capability driverapi.Capability) bool
+
+// IPAMNotifyFunc defines the notify function signature when a new IPAM driver gets registered.
+type IPAMNotifyFunc func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) error
+
+// DriverNotifyFunc defines the notify function signature when a new network driver gets registered.
+type DriverNotifyFunc func(name string, driver driverapi.Driver, capability driverapi.Capability) error
+
+// New retruns a new driver registry handle.
+func New(lDs, gDs interface{}, dfn DriverNotifyFunc, ifn IPAMNotifyFunc, pg plugingetter.PluginGetter) (*DrvRegistry, error) {
+ r := &DrvRegistry{
+ drivers: make(driverTable),
+ ipamDrivers: make(ipamTable),
+ dfn: dfn,
+ ifn: ifn,
+ pluginGetter: pg,
+ }
+
+ return r, nil
+}
+
+// AddDriver adds a network driver to the registry.
+func (r *DrvRegistry) AddDriver(ntype string, fn InitFunc, config map[string]interface{}) error {
+ return fn(r, config)
+}
+
+// WalkIPAMs walks the IPAM drivers registered in the registry and invokes the passed walk function and each one of them.
+func (r *DrvRegistry) WalkIPAMs(ifn IPAMWalkFunc) {
+ type ipamVal struct {
+ name string
+ data *ipamData
+ }
+
+ r.Lock()
+ ivl := make([]ipamVal, 0, len(r.ipamDrivers))
+ for k, v := range r.ipamDrivers {
+ ivl = append(ivl, ipamVal{name: k, data: v})
+ }
+ r.Unlock()
+
+ for _, iv := range ivl {
+ if ifn(iv.name, iv.data.driver, iv.data.capability) {
+ break
+ }
+ }
+}
+
+// WalkDrivers walks the network drivers registered in the registry and invokes the passed walk function and each one of them.
+func (r *DrvRegistry) WalkDrivers(dfn DriverWalkFunc) {
+ type driverVal struct {
+ name string
+ data *driverData
+ }
+
+ r.Lock()
+ dvl := make([]driverVal, 0, len(r.drivers))
+ for k, v := range r.drivers {
+ dvl = append(dvl, driverVal{name: k, data: v})
+ }
+ r.Unlock()
+
+ for _, dv := range dvl {
+ if dfn(dv.name, dv.data.driver, dv.data.capability) {
+ break
+ }
+ }
+}
+
+// Driver returns the actual network driver instance and its capability which registered with the passed name.
+func (r *DrvRegistry) Driver(name string) (driverapi.Driver, *driverapi.Capability) {
+ r.Lock()
+ defer r.Unlock()
+
+ d, ok := r.drivers[name]
+ if !ok {
+ return nil, nil
+ }
+
+ return d.driver, &d.capability
+}
+
+// IPAM returns the actual IPAM driver instance and its capability which registered with the passed name.
+func (r *DrvRegistry) IPAM(name string) (ipamapi.Ipam, *ipamapi.Capability) {
+ r.Lock()
+ defer r.Unlock()
+
+ i, ok := r.ipamDrivers[name]
+ if !ok {
+ return nil, nil
+ }
+
+ return i.driver, i.capability
+}
+
+// IPAMDefaultAddressSpaces returns the default address space strings for the passed IPAM driver name.
+func (r *DrvRegistry) IPAMDefaultAddressSpaces(name string) (string, string, error) {
+ r.Lock()
+ defer r.Unlock()
+
+ i, ok := r.ipamDrivers[name]
+ if !ok {
+ return "", "", fmt.Errorf("ipam %s not found", name)
+ }
+
+ return i.defaultLocalAddressSpace, i.defaultGlobalAddressSpace, nil
+}
+
+// GetPluginGetter returns the plugingetter
+func (r *DrvRegistry) GetPluginGetter() plugingetter.PluginGetter {
+ return r.pluginGetter
+}
+
+// RegisterDriver registers the network driver when it gets discovered.
+func (r *DrvRegistry) RegisterDriver(ntype string, driver driverapi.Driver, capability driverapi.Capability) error {
+ if strings.TrimSpace(ntype) == "" {
+ return errors.New("network type string cannot be empty")
+ }
+
+ r.Lock()
+ dd, ok := r.drivers[ntype]
+ r.Unlock()
+
+ if ok && dd.driver.IsBuiltIn() {
+ return driverapi.ErrActiveRegistration(ntype)
+ }
+
+ if r.dfn != nil {
+ if err := r.dfn(ntype, driver, capability); err != nil {
+ return err
+ }
+ }
+
+ dData := &driverData{driver, capability}
+
+ r.Lock()
+ r.drivers[ntype] = dData
+ r.Unlock()
+
+ return nil
+}
+
+func (r *DrvRegistry) registerIpamDriver(name string, driver ipamapi.Ipam, caps *ipamapi.Capability) error {
+ if strings.TrimSpace(name) == "" {
+ return errors.New("ipam driver name string cannot be empty")
+ }
+
+ r.Lock()
+ dd, ok := r.ipamDrivers[name]
+ r.Unlock()
+ if ok && dd.driver.IsBuiltIn() {
+ return types.ForbiddenErrorf("ipam driver %q already registered", name)
+ }
+
+ locAS, glbAS, err := driver.GetDefaultAddressSpaces()
+ if err != nil {
+ return types.InternalErrorf("ipam driver %q failed to return default address spaces: %v", name, err)
+ }
+
+ if r.ifn != nil {
+ if err := r.ifn(name, driver, caps); err != nil {
+ return err
+ }
+ }
+
+ r.Lock()
+ r.ipamDrivers[name] = &ipamData{driver: driver, defaultLocalAddressSpace: locAS, defaultGlobalAddressSpace: glbAS, capability: caps}
+ r.Unlock()
+
+ return nil
+}
+
+// RegisterIpamDriver registers the IPAM driver discovered with default capabilities.
+func (r *DrvRegistry) RegisterIpamDriver(name string, driver ipamapi.Ipam) error {
+ return r.registerIpamDriver(name, driver, &ipamapi.Capability{})
+}
+
+// RegisterIpamDriverWithCapabilities registers the IPAM driver discovered with specified capabilities.
+func (r *DrvRegistry) RegisterIpamDriverWithCapabilities(name string, driver ipamapi.Ipam, caps *ipamapi.Capability) error {
+ return r.registerIpamDriver(name, driver, caps)
+}
diff --git a/vendor/github.com/docker/libnetwork/endpoint.go b/vendor/github.com/docker/libnetwork/endpoint.go
new file mode 100644
index 0000000..111b747
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/endpoint.go
@@ -0,0 +1,1192 @@
+package libnetwork
+
+import (
+ "container/heap"
+ "encoding/json"
+ "fmt"
+ "net"
+ "strings"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/options"
+ "github.com/docker/libnetwork/types"
+)
+
+// Endpoint represents a logical connection between a network and a sandbox.
+type Endpoint interface {
+ // A system generated id for this endpoint.
+ ID() string
+
+ // Name returns the name of this endpoint.
+ Name() string
+
+ // Network returns the name of the network to which this endpoint is attached.
+ Network() string
+
+ // Join joins the sandbox to the endpoint and populates into the sandbox
+ // the network resources allocated for the endpoint.
+ Join(sandbox Sandbox, options ...EndpointOption) error
+
+ // Leave detaches the network resources populated in the sandbox.
+ Leave(sandbox Sandbox, options ...EndpointOption) error
+
+ // Return certain operational data belonging to this endpoint
+ Info() EndpointInfo
+
+ // DriverInfo returns a collection of driver operational data related to this endpoint retrieved from the driver
+ DriverInfo() (map[string]interface{}, error)
+
+ // Delete and detaches this endpoint from the network.
+ Delete(force bool) error
+}
+
+// EndpointOption is an option setter function type used to pass various options to Network
+// and Endpoint interfaces methods. The various setter functions of type EndpointOption are
+// provided by libnetwork, they look like <Create|Join|Leave>Option[...](...)
+type EndpointOption func(ep *endpoint)
+
+type endpoint struct {
+ name string
+ id string
+ network *network
+ iface *endpointInterface
+ joinInfo *endpointJoinInfo
+ sandboxID string
+ locator string
+ exposedPorts []types.TransportPort
+ anonymous bool
+ disableResolution bool
+ generic map[string]interface{}
+ joinLeaveDone chan struct{}
+ prefAddress net.IP
+ prefAddressV6 net.IP
+ ipamOptions map[string]string
+ aliases map[string]string
+ myAliases []string
+ svcID string
+ svcName string
+ virtualIP net.IP
+ svcAliases []string
+ ingressPorts []*PortConfig
+ dbIndex uint64
+ dbExists bool
+ serviceEnabled bool
+ sync.Mutex
+}
+
+func (ep *endpoint) MarshalJSON() ([]byte, error) {
+ ep.Lock()
+ defer ep.Unlock()
+
+ epMap := make(map[string]interface{})
+ epMap["name"] = ep.name
+ epMap["id"] = ep.id
+ epMap["ep_iface"] = ep.iface
+ epMap["joinInfo"] = ep.joinInfo
+ epMap["exposed_ports"] = ep.exposedPorts
+ if ep.generic != nil {
+ epMap["generic"] = ep.generic
+ }
+ epMap["sandbox"] = ep.sandboxID
+ epMap["locator"] = ep.locator
+ epMap["anonymous"] = ep.anonymous
+ epMap["disableResolution"] = ep.disableResolution
+ epMap["myAliases"] = ep.myAliases
+ epMap["svcName"] = ep.svcName
+ epMap["svcID"] = ep.svcID
+ epMap["virtualIP"] = ep.virtualIP.String()
+ epMap["ingressPorts"] = ep.ingressPorts
+ epMap["svcAliases"] = ep.svcAliases
+
+ return json.Marshal(epMap)
+}
+
+func (ep *endpoint) UnmarshalJSON(b []byte) (err error) {
+ ep.Lock()
+ defer ep.Unlock()
+
+ var epMap map[string]interface{}
+ if err := json.Unmarshal(b, &epMap); err != nil {
+ return err
+ }
+ ep.name = epMap["name"].(string)
+ ep.id = epMap["id"].(string)
+
+ ib, _ := json.Marshal(epMap["ep_iface"])
+ json.Unmarshal(ib, &ep.iface)
+
+ jb, _ := json.Marshal(epMap["joinInfo"])
+ json.Unmarshal(jb, &ep.joinInfo)
+
+ tb, _ := json.Marshal(epMap["exposed_ports"])
+ var tPorts []types.TransportPort
+ json.Unmarshal(tb, &tPorts)
+ ep.exposedPorts = tPorts
+
+ cb, _ := json.Marshal(epMap["sandbox"])
+ json.Unmarshal(cb, &ep.sandboxID)
+
+ if v, ok := epMap["generic"]; ok {
+ ep.generic = v.(map[string]interface{})
+
+ if opt, ok := ep.generic[netlabel.PortMap]; ok {
+ pblist := []types.PortBinding{}
+
+ for i := 0; i < len(opt.([]interface{})); i++ {
+ pb := types.PortBinding{}
+ tmp := opt.([]interface{})[i].(map[string]interface{})
+
+ bytes, err := json.Marshal(tmp)
+ if err != nil {
+ logrus.Error(err)
+ break
+ }
+ err = json.Unmarshal(bytes, &pb)
+ if err != nil {
+ logrus.Error(err)
+ break
+ }
+ pblist = append(pblist, pb)
+ }
+ ep.generic[netlabel.PortMap] = pblist
+ }
+
+ if opt, ok := ep.generic[netlabel.ExposedPorts]; ok {
+ tplist := []types.TransportPort{}
+
+ for i := 0; i < len(opt.([]interface{})); i++ {
+ tp := types.TransportPort{}
+ tmp := opt.([]interface{})[i].(map[string]interface{})
+
+ bytes, err := json.Marshal(tmp)
+ if err != nil {
+ logrus.Error(err)
+ break
+ }
+ err = json.Unmarshal(bytes, &tp)
+ if err != nil {
+ logrus.Error(err)
+ break
+ }
+ tplist = append(tplist, tp)
+ }
+ ep.generic[netlabel.ExposedPorts] = tplist
+
+ }
+ }
+
+ if v, ok := epMap["anonymous"]; ok {
+ ep.anonymous = v.(bool)
+ }
+ if v, ok := epMap["disableResolution"]; ok {
+ ep.disableResolution = v.(bool)
+ }
+ if l, ok := epMap["locator"]; ok {
+ ep.locator = l.(string)
+ }
+
+ if sn, ok := epMap["svcName"]; ok {
+ ep.svcName = sn.(string)
+ }
+
+ if si, ok := epMap["svcID"]; ok {
+ ep.svcID = si.(string)
+ }
+
+ if vip, ok := epMap["virtualIP"]; ok {
+ ep.virtualIP = net.ParseIP(vip.(string))
+ }
+
+ sal, _ := json.Marshal(epMap["svcAliases"])
+ var svcAliases []string
+ json.Unmarshal(sal, &svcAliases)
+ ep.svcAliases = svcAliases
+
+ pc, _ := json.Marshal(epMap["ingressPorts"])
+ var ingressPorts []*PortConfig
+ json.Unmarshal(pc, &ingressPorts)
+ ep.ingressPorts = ingressPorts
+
+ ma, _ := json.Marshal(epMap["myAliases"])
+ var myAliases []string
+ json.Unmarshal(ma, &myAliases)
+ ep.myAliases = myAliases
+ return nil
+}
+
+func (ep *endpoint) New() datastore.KVObject {
+ return &endpoint{network: ep.getNetwork()}
+}
+
+func (ep *endpoint) CopyTo(o datastore.KVObject) error {
+ ep.Lock()
+ defer ep.Unlock()
+
+ dstEp := o.(*endpoint)
+ dstEp.name = ep.name
+ dstEp.id = ep.id
+ dstEp.sandboxID = ep.sandboxID
+ dstEp.locator = ep.locator
+ dstEp.dbIndex = ep.dbIndex
+ dstEp.dbExists = ep.dbExists
+ dstEp.anonymous = ep.anonymous
+ dstEp.disableResolution = ep.disableResolution
+ dstEp.svcName = ep.svcName
+ dstEp.svcID = ep.svcID
+ dstEp.virtualIP = ep.virtualIP
+
+ dstEp.svcAliases = make([]string, len(ep.svcAliases))
+ copy(dstEp.svcAliases, ep.svcAliases)
+
+ dstEp.ingressPorts = make([]*PortConfig, len(ep.ingressPorts))
+ copy(dstEp.ingressPorts, ep.ingressPorts)
+
+ if ep.iface != nil {
+ dstEp.iface = &endpointInterface{}
+ ep.iface.CopyTo(dstEp.iface)
+ }
+
+ if ep.joinInfo != nil {
+ dstEp.joinInfo = &endpointJoinInfo{}
+ ep.joinInfo.CopyTo(dstEp.joinInfo)
+ }
+
+ dstEp.exposedPorts = make([]types.TransportPort, len(ep.exposedPorts))
+ copy(dstEp.exposedPorts, ep.exposedPorts)
+
+ dstEp.myAliases = make([]string, len(ep.myAliases))
+ copy(dstEp.myAliases, ep.myAliases)
+
+ dstEp.generic = options.Generic{}
+ for k, v := range ep.generic {
+ dstEp.generic[k] = v
+ }
+
+ return nil
+}
+
+func (ep *endpoint) ID() string {
+ ep.Lock()
+ defer ep.Unlock()
+
+ return ep.id
+}
+
+func (ep *endpoint) Name() string {
+ ep.Lock()
+ defer ep.Unlock()
+
+ return ep.name
+}
+
+func (ep *endpoint) MyAliases() []string {
+ ep.Lock()
+ defer ep.Unlock()
+
+ return ep.myAliases
+}
+
+func (ep *endpoint) Network() string {
+ if ep.network == nil {
+ return ""
+ }
+
+ return ep.network.name
+}
+
+func (ep *endpoint) isAnonymous() bool {
+ ep.Lock()
+ defer ep.Unlock()
+ return ep.anonymous
+}
+
+// enableService sets ep's serviceEnabled to the passed value if it's not in the
+// current state and returns true; false otherwise.
+func (ep *endpoint) enableService(state bool) bool {
+ ep.Lock()
+ defer ep.Unlock()
+ if ep.serviceEnabled != state {
+ ep.serviceEnabled = state
+ return true
+ }
+ return false
+}
+
+func (ep *endpoint) needResolver() bool {
+ ep.Lock()
+ defer ep.Unlock()
+ return !ep.disableResolution
+}
+
+// endpoint Key structure : endpoint/network-id/endpoint-id
+func (ep *endpoint) Key() []string {
+ if ep.network == nil {
+ return nil
+ }
+
+ return []string{datastore.EndpointKeyPrefix, ep.network.id, ep.id}
+}
+
+func (ep *endpoint) KeyPrefix() []string {
+ if ep.network == nil {
+ return nil
+ }
+
+ return []string{datastore.EndpointKeyPrefix, ep.network.id}
+}
+
+func (ep *endpoint) networkIDFromKey(key string) (string, error) {
+ // endpoint Key structure : docker/libnetwork/endpoint/${network-id}/${endpoint-id}
+ // it's an invalid key if the key doesn't have all the 5 key elements above
+ keyElements := strings.Split(key, "/")
+ if !strings.HasPrefix(key, datastore.Key(datastore.EndpointKeyPrefix)) || len(keyElements) < 5 {
+ return "", fmt.Errorf("invalid endpoint key : %v", key)
+ }
+ // network-id is placed at index=3. pls refer to endpoint.Key() method
+ return strings.Split(key, "/")[3], nil
+}
+
+func (ep *endpoint) Value() []byte {
+ b, err := json.Marshal(ep)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (ep *endpoint) SetValue(value []byte) error {
+ return json.Unmarshal(value, ep)
+}
+
+func (ep *endpoint) Index() uint64 {
+ ep.Lock()
+ defer ep.Unlock()
+ return ep.dbIndex
+}
+
+func (ep *endpoint) SetIndex(index uint64) {
+ ep.Lock()
+ defer ep.Unlock()
+ ep.dbIndex = index
+ ep.dbExists = true
+}
+
+func (ep *endpoint) Exists() bool {
+ ep.Lock()
+ defer ep.Unlock()
+ return ep.dbExists
+}
+
+func (ep *endpoint) Skip() bool {
+ return ep.getNetwork().Skip()
+}
+
+func (ep *endpoint) processOptions(options ...EndpointOption) {
+ ep.Lock()
+ defer ep.Unlock()
+
+ for _, opt := range options {
+ if opt != nil {
+ opt(ep)
+ }
+ }
+}
+
+func (ep *endpoint) getNetwork() *network {
+ ep.Lock()
+ defer ep.Unlock()
+
+ return ep.network
+}
+
+func (ep *endpoint) getNetworkFromStore() (*network, error) {
+ if ep.network == nil {
+ return nil, fmt.Errorf("invalid network object in endpoint %s", ep.Name())
+ }
+
+ return ep.network.getController().getNetworkFromStore(ep.network.id)
+}
+
+func (ep *endpoint) Join(sbox Sandbox, options ...EndpointOption) error {
+ if sbox == nil {
+ return types.BadRequestErrorf("endpoint cannot be joined by nil container")
+ }
+
+ sb, ok := sbox.(*sandbox)
+ if !ok {
+ return types.BadRequestErrorf("not a valid Sandbox interface")
+ }
+
+ sb.joinLeaveStart()
+ defer sb.joinLeaveEnd()
+
+ return ep.sbJoin(sb, options...)
+}
+
+func (ep *endpoint) sbJoin(sb *sandbox, options ...EndpointOption) (err error) {
+ n, err := ep.getNetworkFromStore()
+ if err != nil {
+ return fmt.Errorf("failed to get network from store during join: %v", err)
+ }
+
+ ep, err = n.getEndpointFromStore(ep.ID())
+ if err != nil {
+ return fmt.Errorf("failed to get endpoint from store during join: %v", err)
+ }
+
+ ep.Lock()
+ if ep.sandboxID != "" {
+ ep.Unlock()
+ return types.ForbiddenErrorf("another container is attached to the same network endpoint")
+ }
+ ep.network = n
+ ep.sandboxID = sb.ID()
+ ep.joinInfo = &endpointJoinInfo{}
+ epid := ep.id
+ ep.Unlock()
+ defer func() {
+ if err != nil {
+ ep.Lock()
+ ep.sandboxID = ""
+ ep.Unlock()
+ }
+ }()
+
+ nid := n.ID()
+
+ ep.processOptions(options...)
+
+ d, err := n.driver(true)
+ if err != nil {
+ return fmt.Errorf("failed to get driver during join: %v", err)
+ }
+
+ err = d.Join(nid, epid, sb.Key(), ep, sb.Labels())
+ if err != nil {
+ return err
+ }
+ defer func() {
+ if err != nil {
+ if e := d.Leave(nid, epid); e != nil {
+ logrus.Warnf("driver leave failed while rolling back join: %v", e)
+ }
+ }
+ }()
+
+ // Watch for service records
+ if !n.getController().isAgent() {
+ n.getController().watchSvcRecord(ep)
+ }
+
+ if doUpdateHostsFile(n, sb) {
+ address := ""
+ if ip := ep.getFirstInterfaceAddress(); ip != nil {
+ address = ip.String()
+ }
+ if err = sb.updateHostsFile(address); err != nil {
+ return err
+ }
+ }
+ if err = sb.updateDNS(n.enableIPv6); err != nil {
+ return err
+ }
+
+ // Current endpoint providing external connectivity for the sandbox
+ extEp := sb.getGatewayEndpoint()
+
+ sb.Lock()
+ heap.Push(&sb.endpoints, ep)
+ sb.Unlock()
+ defer func() {
+ if err != nil {
+ sb.removeEndpoint(ep)
+ }
+ }()
+
+ if err = sb.populateNetworkResources(ep); err != nil {
+ return err
+ }
+
+ if err = n.getController().updateToStore(ep); err != nil {
+ return err
+ }
+
+ if err = ep.addDriverInfoToCluster(); err != nil {
+ return err
+ }
+
+ defer func() {
+ if err != nil {
+ if e := ep.deleteDriverInfoFromCluster(); e != nil {
+ logrus.Errorf("Could not delete endpoint state for endpoint %s from cluster on join failure: %v", ep.Name(), e)
+ }
+ }
+ }()
+
+ if sb.needDefaultGW() && sb.getEndpointInGWNetwork() == nil {
+ return sb.setupDefaultGW()
+ }
+
+ moveExtConn := sb.getGatewayEndpoint() != extEp
+
+ if moveExtConn {
+ if extEp != nil {
+ logrus.Debugf("Revoking external connectivity on endpoint %s (%s)", extEp.Name(), extEp.ID())
+ extN, err := extEp.getNetworkFromStore()
+ if err != nil {
+ return fmt.Errorf("failed to get network from store for revoking external connectivity during join: %v", err)
+ }
+ extD, err := extN.driver(true)
+ if err != nil {
+ return fmt.Errorf("failed to get driver for revoking external connectivity during join: %v", err)
+ }
+ if err = extD.RevokeExternalConnectivity(extEp.network.ID(), extEp.ID()); err != nil {
+ return types.InternalErrorf(
+ "driver failed revoking external connectivity on endpoint %s (%s): %v",
+ extEp.Name(), extEp.ID(), err)
+ }
+ defer func() {
+ if err != nil {
+ if e := extD.ProgramExternalConnectivity(extEp.network.ID(), extEp.ID(), sb.Labels()); e != nil {
+ logrus.Warnf("Failed to roll-back external connectivity on endpoint %s (%s): %v",
+ extEp.Name(), extEp.ID(), e)
+ }
+ }
+ }()
+ }
+ if !n.internal {
+ logrus.Debugf("Programming external connectivity on endpoint %s (%s)", ep.Name(), ep.ID())
+ if err = d.ProgramExternalConnectivity(n.ID(), ep.ID(), sb.Labels()); err != nil {
+ return types.InternalErrorf(
+ "driver failed programming external connectivity on endpoint %s (%s): %v",
+ ep.Name(), ep.ID(), err)
+ }
+ }
+
+ }
+
+ if !sb.needDefaultGW() {
+ if e := sb.clearDefaultGW(); e != nil {
+ logrus.Warnf("Failure while disconnecting sandbox %s (%s) from gateway network: %v",
+ sb.ID(), sb.ContainerID(), e)
+ }
+ }
+
+ return nil
+}
+
+func doUpdateHostsFile(n *network, sb *sandbox) bool {
+ return !n.ingress && n.Name() != libnGWNetwork
+}
+
+func (ep *endpoint) rename(name string) error {
+ var (
+ err error
+ netWatch *netWatch
+ ok bool
+ )
+
+ n := ep.getNetwork()
+ if n == nil {
+ return fmt.Errorf("network not connected for ep %q", ep.name)
+ }
+
+ c := n.getController()
+
+ sb, ok := ep.getSandbox()
+ if !ok {
+ logrus.Warnf("rename for %s aborted, sandbox %s is not anymore present", ep.ID(), ep.sandboxID)
+ return nil
+ }
+
+ if c.isAgent() {
+ if err = ep.deleteServiceInfoFromCluster(sb, "rename"); err != nil {
+ return types.InternalErrorf("Could not delete service state for endpoint %s from cluster on rename: %v", ep.Name(), err)
+ }
+ } else {
+ c.Lock()
+ netWatch, ok = c.nmap[n.ID()]
+ c.Unlock()
+ if !ok {
+ return fmt.Errorf("watch null for network %q", n.Name())
+ }
+ n.updateSvcRecord(ep, c.getLocalEps(netWatch), false)
+ }
+
+ oldName := ep.name
+ oldAnonymous := ep.anonymous
+ ep.name = name
+ ep.anonymous = false
+
+ if c.isAgent() {
+ if err = ep.addServiceInfoToCluster(sb); err != nil {
+ return types.InternalErrorf("Could not add service state for endpoint %s to cluster on rename: %v", ep.Name(), err)
+ }
+ defer func() {
+ if err != nil {
+ ep.deleteServiceInfoFromCluster(sb, "rename")
+ ep.name = oldName
+ ep.anonymous = oldAnonymous
+ ep.addServiceInfoToCluster(sb)
+ }
+ }()
+ } else {
+ n.updateSvcRecord(ep, c.getLocalEps(netWatch), true)
+ defer func() {
+ if err != nil {
+ n.updateSvcRecord(ep, c.getLocalEps(netWatch), false)
+ ep.name = oldName
+ ep.anonymous = oldAnonymous
+ n.updateSvcRecord(ep, c.getLocalEps(netWatch), true)
+ }
+ }()
+ }
+
+ // Update the store with the updated name
+ if err = c.updateToStore(ep); err != nil {
+ return err
+ }
+ // After the name change do a dummy endpoint count update to
+ // trigger the service record update in the peer nodes
+
+ // Ignore the error because updateStore fail for EpCnt is a
+ // benign error. Besides there is no meaningful recovery that
+ // we can do. When the cluster recovers subsequent EpCnt update
+ // will force the peers to get the correct EP name.
+ n.getEpCnt().updateStore()
+
+ return err
+}
+
+func (ep *endpoint) hasInterface(iName string) bool {
+ ep.Lock()
+ defer ep.Unlock()
+
+ return ep.iface != nil && ep.iface.srcName == iName
+}
+
+func (ep *endpoint) Leave(sbox Sandbox, options ...EndpointOption) error {
+ if sbox == nil || sbox.ID() == "" || sbox.Key() == "" {
+ return types.BadRequestErrorf("invalid Sandbox passed to endpoint leave: %v", sbox)
+ }
+
+ sb, ok := sbox.(*sandbox)
+ if !ok {
+ return types.BadRequestErrorf("not a valid Sandbox interface")
+ }
+
+ sb.joinLeaveStart()
+ defer sb.joinLeaveEnd()
+
+ return ep.sbLeave(sb, false, options...)
+}
+
+func (ep *endpoint) sbLeave(sb *sandbox, force bool, options ...EndpointOption) error {
+ n, err := ep.getNetworkFromStore()
+ if err != nil {
+ return fmt.Errorf("failed to get network from store during leave: %v", err)
+ }
+
+ ep, err = n.getEndpointFromStore(ep.ID())
+ if err != nil {
+ return fmt.Errorf("failed to get endpoint from store during leave: %v", err)
+ }
+
+ ep.Lock()
+ sid := ep.sandboxID
+ ep.Unlock()
+
+ if sid == "" {
+ return types.ForbiddenErrorf("cannot leave endpoint with no attached sandbox")
+ }
+ if sid != sb.ID() {
+ return types.ForbiddenErrorf("unexpected sandbox ID in leave request. Expected %s. Got %s", ep.sandboxID, sb.ID())
+ }
+
+ ep.processOptions(options...)
+
+ d, err := n.driver(!force)
+ if err != nil {
+ return fmt.Errorf("failed to get driver during endpoint leave: %v", err)
+ }
+
+ ep.Lock()
+ ep.sandboxID = ""
+ ep.network = n
+ ep.Unlock()
+
+ // Current endpoint providing external connectivity to the sandbox
+ extEp := sb.getGatewayEndpoint()
+ moveExtConn := extEp != nil && (extEp.ID() == ep.ID())
+
+ if d != nil {
+ if moveExtConn {
+ logrus.Debugf("Revoking external connectivity on endpoint %s (%s)", ep.Name(), ep.ID())
+ if err := d.RevokeExternalConnectivity(n.id, ep.id); err != nil {
+ logrus.Warnf("driver failed revoking external connectivity on endpoint %s (%s): %v",
+ ep.Name(), ep.ID(), err)
+ }
+ }
+
+ if err := d.Leave(n.id, ep.id); err != nil {
+ if _, ok := err.(types.MaskableError); !ok {
+ logrus.Warnf("driver error disconnecting container %s : %v", ep.name, err)
+ }
+ }
+ }
+
+ if err := sb.clearNetworkResources(ep); err != nil {
+ logrus.Warnf("Could not cleanup network resources on container %s disconnect: %v", ep.name, err)
+ }
+
+ // Update the store about the sandbox detach only after we
+ // have completed sb.clearNetworkresources above to avoid
+ // spurious logs when cleaning up the sandbox when the daemon
+ // ungracefully exits and restarts before completing sandbox
+ // detach but after store has been updated.
+ if err := n.getController().updateToStore(ep); err != nil {
+ return err
+ }
+
+ if e := ep.deleteServiceInfoFromCluster(sb, "sbLeave"); e != nil {
+ logrus.Errorf("Could not delete service state for endpoint %s from cluster: %v", ep.Name(), e)
+ }
+
+ if e := ep.deleteDriverInfoFromCluster(); e != nil {
+ logrus.Errorf("Could not delete endpoint state for endpoint %s from cluster: %v", ep.Name(), e)
+ }
+
+ sb.deleteHostsEntries(n.getSvcRecords(ep))
+ if !sb.inDelete && sb.needDefaultGW() && sb.getEndpointInGWNetwork() == nil {
+ return sb.setupDefaultGW()
+ }
+
+ // New endpoint providing external connectivity for the sandbox
+ extEp = sb.getGatewayEndpoint()
+ if moveExtConn && extEp != nil {
+ logrus.Debugf("Programming external connectivity on endpoint %s (%s)", extEp.Name(), extEp.ID())
+ extN, err := extEp.getNetworkFromStore()
+ if err != nil {
+ return fmt.Errorf("failed to get network from store for programming external connectivity during leave: %v", err)
+ }
+ extD, err := extN.driver(true)
+ if err != nil {
+ return fmt.Errorf("failed to get driver for programming external connectivity during leave: %v", err)
+ }
+ if err := extD.ProgramExternalConnectivity(extEp.network.ID(), extEp.ID(), sb.Labels()); err != nil {
+ logrus.Warnf("driver failed programming external connectivity on endpoint %s: (%s) %v",
+ extEp.Name(), extEp.ID(), err)
+ }
+ }
+
+ if !sb.needDefaultGW() {
+ if err := sb.clearDefaultGW(); err != nil {
+ logrus.Warnf("Failure while disconnecting sandbox %s (%s) from gateway network: %v",
+ sb.ID(), sb.ContainerID(), err)
+ }
+ }
+
+ return nil
+}
+
+func (ep *endpoint) Delete(force bool) error {
+ var err error
+ n, err := ep.getNetworkFromStore()
+ if err != nil {
+ return fmt.Errorf("failed to get network during Delete: %v", err)
+ }
+
+ ep, err = n.getEndpointFromStore(ep.ID())
+ if err != nil {
+ return fmt.Errorf("failed to get endpoint from store during Delete: %v", err)
+ }
+
+ ep.Lock()
+ epid := ep.id
+ name := ep.name
+ sbid := ep.sandboxID
+ ep.Unlock()
+
+ sb, _ := n.getController().SandboxByID(sbid)
+ if sb != nil && !force {
+ return &ActiveContainerError{name: name, id: epid}
+ }
+
+ if sb != nil {
+ if e := ep.sbLeave(sb.(*sandbox), force); e != nil {
+ logrus.Warnf("failed to leave sandbox for endpoint %s : %v", name, e)
+ }
+ }
+
+ if err = n.getController().deleteFromStore(ep); err != nil {
+ return err
+ }
+
+ defer func() {
+ if err != nil && !force {
+ ep.dbExists = false
+ if e := n.getController().updateToStore(ep); e != nil {
+ logrus.Warnf("failed to recreate endpoint in store %s : %v", name, e)
+ }
+ }
+ }()
+
+ // unwatch for service records
+ n.getController().unWatchSvcRecord(ep)
+
+ if err = ep.deleteEndpoint(force); err != nil && !force {
+ return err
+ }
+
+ ep.releaseAddress()
+
+ if err := n.getEpCnt().DecEndpointCnt(); err != nil {
+ logrus.Warnf("failed to decrement endpoint count for ep %s: %v", ep.ID(), err)
+ }
+
+ return nil
+}
+
+func (ep *endpoint) deleteEndpoint(force bool) error {
+ ep.Lock()
+ n := ep.network
+ name := ep.name
+ epid := ep.id
+ ep.Unlock()
+
+ driver, err := n.driver(!force)
+ if err != nil {
+ return fmt.Errorf("failed to delete endpoint: %v", err)
+ }
+
+ if driver == nil {
+ return nil
+ }
+
+ if err := driver.DeleteEndpoint(n.id, epid); err != nil {
+ if _, ok := err.(types.ForbiddenError); ok {
+ return err
+ }
+
+ if _, ok := err.(types.MaskableError); !ok {
+ logrus.Warnf("driver error deleting endpoint %s : %v", name, err)
+ }
+ }
+
+ return nil
+}
+
+func (ep *endpoint) getSandbox() (*sandbox, bool) {
+ c := ep.network.getController()
+ ep.Lock()
+ sid := ep.sandboxID
+ ep.Unlock()
+
+ c.Lock()
+ ps, ok := c.sandboxes[sid]
+ c.Unlock()
+
+ return ps, ok
+}
+
+func (ep *endpoint) getFirstInterfaceAddress() net.IP {
+ ep.Lock()
+ defer ep.Unlock()
+
+ if ep.iface.addr != nil {
+ return ep.iface.addr.IP
+ }
+
+ return nil
+}
+
+// EndpointOptionGeneric function returns an option setter for a Generic option defined
+// in a Dictionary of Key-Value pair
+func EndpointOptionGeneric(generic map[string]interface{}) EndpointOption {
+ return func(ep *endpoint) {
+ for k, v := range generic {
+ ep.generic[k] = v
+ }
+ }
+}
+
+var (
+ linkLocalMask = net.CIDRMask(16, 32)
+ linkLocalMaskIPv6 = net.CIDRMask(64, 128)
+)
+
+// CreateOptionIpam function returns an option setter for the ipam configuration for this endpoint
+func CreateOptionIpam(ipV4, ipV6 net.IP, llIPs []net.IP, ipamOptions map[string]string) EndpointOption {
+ return func(ep *endpoint) {
+ ep.prefAddress = ipV4
+ ep.prefAddressV6 = ipV6
+ if len(llIPs) != 0 {
+ for _, ip := range llIPs {
+ nw := &net.IPNet{IP: ip, Mask: linkLocalMask}
+ if ip.To4() == nil {
+ nw.Mask = linkLocalMaskIPv6
+ }
+ ep.iface.llAddrs = append(ep.iface.llAddrs, nw)
+ }
+ }
+ ep.ipamOptions = ipamOptions
+ }
+}
+
+// CreateOptionExposedPorts function returns an option setter for the container exposed
+// ports option to be passed to network.CreateEndpoint() method.
+func CreateOptionExposedPorts(exposedPorts []types.TransportPort) EndpointOption {
+ return func(ep *endpoint) {
+ // Defensive copy
+ eps := make([]types.TransportPort, len(exposedPorts))
+ copy(eps, exposedPorts)
+ // Store endpoint label and in generic because driver needs it
+ ep.exposedPorts = eps
+ ep.generic[netlabel.ExposedPorts] = eps
+ }
+}
+
+// CreateOptionPortMapping function returns an option setter for the mapping
+// ports option to be passed to network.CreateEndpoint() method.
+func CreateOptionPortMapping(portBindings []types.PortBinding) EndpointOption {
+ return func(ep *endpoint) {
+ // Store a copy of the bindings as generic data to pass to the driver
+ pbs := make([]types.PortBinding, len(portBindings))
+ copy(pbs, portBindings)
+ ep.generic[netlabel.PortMap] = pbs
+ }
+}
+
+// CreateOptionDNS function returns an option setter for dns entry option to
+// be passed to container Create method.
+func CreateOptionDNS(dns []string) EndpointOption {
+ return func(ep *endpoint) {
+ ep.generic[netlabel.DNSServers] = dns
+ }
+}
+
+// CreateOptionAnonymous function returns an option setter for setting
+// this endpoint as anonymous
+func CreateOptionAnonymous() EndpointOption {
+ return func(ep *endpoint) {
+ ep.anonymous = true
+ }
+}
+
+// CreateOptionDisableResolution function returns an option setter to indicate
+// this endpoint doesn't want embedded DNS server functionality
+func CreateOptionDisableResolution() EndpointOption {
+ return func(ep *endpoint) {
+ ep.disableResolution = true
+ }
+}
+
+//CreateOptionAlias function returns an option setter for setting endpoint alias
+func CreateOptionAlias(name string, alias string) EndpointOption {
+ return func(ep *endpoint) {
+ if ep.aliases == nil {
+ ep.aliases = make(map[string]string)
+ }
+ ep.aliases[alias] = name
+ }
+}
+
+// CreateOptionService function returns an option setter for setting service binding configuration
+func CreateOptionService(name, id string, vip net.IP, ingressPorts []*PortConfig, aliases []string) EndpointOption {
+ return func(ep *endpoint) {
+ ep.svcName = name
+ ep.svcID = id
+ ep.virtualIP = vip
+ ep.ingressPorts = ingressPorts
+ ep.svcAliases = aliases
+ }
+}
+
+//CreateOptionMyAlias function returns an option setter for setting endpoint's self alias
+func CreateOptionMyAlias(alias string) EndpointOption {
+ return func(ep *endpoint) {
+ ep.myAliases = append(ep.myAliases, alias)
+ }
+}
+
+// JoinOptionPriority function returns an option setter for priority option to
+// be passed to the endpoint.Join() method.
+func JoinOptionPriority(ep Endpoint, prio int) EndpointOption {
+ return func(ep *endpoint) {
+ // ep lock already acquired
+ c := ep.network.getController()
+ c.Lock()
+ sb, ok := c.sandboxes[ep.sandboxID]
+ c.Unlock()
+ if !ok {
+ logrus.Errorf("Could not set endpoint priority value during Join to endpoint %s: No sandbox id present in endpoint", ep.id)
+ return
+ }
+ sb.epPriority[ep.id] = prio
+ }
+}
+
+func (ep *endpoint) DataScope() string {
+ return ep.getNetwork().DataScope()
+}
+
+func (ep *endpoint) assignAddress(ipam ipamapi.Ipam, assignIPv4, assignIPv6 bool) error {
+ var err error
+
+ n := ep.getNetwork()
+ if n.hasSpecialDriver() {
+ return nil
+ }
+
+ logrus.Debugf("Assigning addresses for endpoint %s's interface on network %s", ep.Name(), n.Name())
+
+ if assignIPv4 {
+ if err = ep.assignAddressVersion(4, ipam); err != nil {
+ return err
+ }
+ }
+
+ if assignIPv6 {
+ err = ep.assignAddressVersion(6, ipam)
+ }
+
+ return err
+}
+
+func (ep *endpoint) assignAddressVersion(ipVer int, ipam ipamapi.Ipam) error {
+ var (
+ poolID *string
+ address **net.IPNet
+ prefAdd net.IP
+ progAdd net.IP
+ )
+
+ n := ep.getNetwork()
+ switch ipVer {
+ case 4:
+ poolID = &ep.iface.v4PoolID
+ address = &ep.iface.addr
+ prefAdd = ep.prefAddress
+ case 6:
+ poolID = &ep.iface.v6PoolID
+ address = &ep.iface.addrv6
+ prefAdd = ep.prefAddressV6
+ default:
+ return types.InternalErrorf("incorrect ip version number passed: %d", ipVer)
+ }
+
+ ipInfo := n.getIPInfo(ipVer)
+
+ // ipv6 address is not mandatory
+ if len(ipInfo) == 0 && ipVer == 6 {
+ return nil
+ }
+
+ // The address to program may be chosen by the user or by the network driver in one specific
+ // case to support backward compatibility with `docker daemon --fixed-cidrv6` use case
+ if prefAdd != nil {
+ progAdd = prefAdd
+ } else if *address != nil {
+ progAdd = (*address).IP
+ }
+
+ for _, d := range ipInfo {
+ if progAdd != nil && !d.Pool.Contains(progAdd) {
+ continue
+ }
+ addr, _, err := ipam.RequestAddress(d.PoolID, progAdd, ep.ipamOptions)
+ if err == nil {
+ ep.Lock()
+ *address = addr
+ *poolID = d.PoolID
+ ep.Unlock()
+ return nil
+ }
+ if err != ipamapi.ErrNoAvailableIPs || progAdd != nil {
+ return err
+ }
+ }
+ if progAdd != nil {
+ return types.BadRequestErrorf("Invalid address %s: It does not belong to any of this network's subnets", prefAdd)
+ }
+ return fmt.Errorf("no available IPv%d addresses on this network's address pools: %s (%s)", ipVer, n.Name(), n.ID())
+}
+
+func (ep *endpoint) releaseAddress() {
+ n := ep.getNetwork()
+ if n.hasSpecialDriver() {
+ return
+ }
+
+ logrus.Debugf("Releasing addresses for endpoint %s's interface on network %s", ep.Name(), n.Name())
+
+ ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
+ if err != nil {
+ logrus.Warnf("Failed to retrieve ipam driver to release interface address on delete of endpoint %s (%s): %v", ep.Name(), ep.ID(), err)
+ return
+ }
+
+ if ep.iface.addr != nil {
+ if err := ipam.ReleaseAddress(ep.iface.v4PoolID, ep.iface.addr.IP); err != nil {
+ logrus.Warnf("Failed to release ip address %s on delete of endpoint %s (%s): %v", ep.iface.addr.IP, ep.Name(), ep.ID(), err)
+ }
+ }
+
+ if ep.iface.addrv6 != nil && ep.iface.addrv6.IP.IsGlobalUnicast() {
+ if err := ipam.ReleaseAddress(ep.iface.v6PoolID, ep.iface.addrv6.IP); err != nil {
+ logrus.Warnf("Failed to release ip address %s on delete of endpoint %s (%s): %v", ep.iface.addrv6.IP, ep.Name(), ep.ID(), err)
+ }
+ }
+}
+
+func (c *controller) cleanupLocalEndpoints() {
+ // Get used endpoints
+ eps := make(map[string]interface{})
+ for _, sb := range c.sandboxes {
+ for _, ep := range sb.endpoints {
+ eps[ep.id] = true
+ }
+ }
+ nl, err := c.getNetworksForScope(datastore.LocalScope)
+ if err != nil {
+ logrus.Warnf("Could not get list of networks during endpoint cleanup: %v", err)
+ return
+ }
+
+ for _, n := range nl {
+ if n.ConfigOnly() {
+ continue
+ }
+ epl, err := n.getEndpointsFromStore()
+ if err != nil {
+ logrus.Warnf("Could not get list of endpoints in network %s during endpoint cleanup: %v", n.name, err)
+ continue
+ }
+
+ for _, ep := range epl {
+ if _, ok := eps[ep.id]; ok {
+ continue
+ }
+ logrus.Infof("Removing stale endpoint %s (%s)", ep.name, ep.id)
+ if err := ep.Delete(true); err != nil {
+ logrus.Warnf("Could not delete local endpoint %s during endpoint cleanup: %v", ep.name, err)
+ }
+ }
+
+ epl, err = n.getEndpointsFromStore()
+ if err != nil {
+ logrus.Warnf("Could not get list of endpoints in network %s for count update: %v", n.name, err)
+ continue
+ }
+
+ epCnt := n.getEpCnt().EndpointCnt()
+ if epCnt != uint64(len(epl)) {
+ logrus.Infof("Fixing inconsistent endpoint_cnt for network %s. Expected=%d, Actual=%d", n.name, len(epl), epCnt)
+ n.getEpCnt().setCnt(uint64(len(epl)))
+ }
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/endpoint_cnt.go b/vendor/github.com/docker/libnetwork/endpoint_cnt.go
new file mode 100644
index 0000000..c63d06a
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/endpoint_cnt.go
@@ -0,0 +1,178 @@
+package libnetwork
+
+import (
+ "encoding/json"
+ "fmt"
+ "sync"
+
+ "github.com/docker/libnetwork/datastore"
+)
+
+type endpointCnt struct {
+ n *network
+ Count uint64
+ dbIndex uint64
+ dbExists bool
+ sync.Mutex
+}
+
+const epCntKeyPrefix = "endpoint_count"
+
+func (ec *endpointCnt) Key() []string {
+ ec.Lock()
+ defer ec.Unlock()
+
+ return []string{epCntKeyPrefix, ec.n.id}
+}
+
+func (ec *endpointCnt) KeyPrefix() []string {
+ ec.Lock()
+ defer ec.Unlock()
+
+ return []string{epCntKeyPrefix, ec.n.id}
+}
+
+func (ec *endpointCnt) Value() []byte {
+ ec.Lock()
+ defer ec.Unlock()
+
+ b, err := json.Marshal(ec)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (ec *endpointCnt) SetValue(value []byte) error {
+ ec.Lock()
+ defer ec.Unlock()
+
+ return json.Unmarshal(value, &ec)
+}
+
+func (ec *endpointCnt) Index() uint64 {
+ ec.Lock()
+ defer ec.Unlock()
+ return ec.dbIndex
+}
+
+func (ec *endpointCnt) SetIndex(index uint64) {
+ ec.Lock()
+ ec.dbIndex = index
+ ec.dbExists = true
+ ec.Unlock()
+}
+
+func (ec *endpointCnt) Exists() bool {
+ ec.Lock()
+ defer ec.Unlock()
+ return ec.dbExists
+}
+
+func (ec *endpointCnt) Skip() bool {
+ ec.Lock()
+ defer ec.Unlock()
+ return !ec.n.persist
+}
+
+func (ec *endpointCnt) New() datastore.KVObject {
+ ec.Lock()
+ defer ec.Unlock()
+
+ return &endpointCnt{
+ n: ec.n,
+ }
+}
+
+func (ec *endpointCnt) CopyTo(o datastore.KVObject) error {
+ ec.Lock()
+ defer ec.Unlock()
+
+ dstEc := o.(*endpointCnt)
+ dstEc.n = ec.n
+ dstEc.Count = ec.Count
+ dstEc.dbExists = ec.dbExists
+ dstEc.dbIndex = ec.dbIndex
+
+ return nil
+}
+
+func (ec *endpointCnt) DataScope() string {
+ return ec.n.DataScope()
+}
+
+func (ec *endpointCnt) EndpointCnt() uint64 {
+ ec.Lock()
+ defer ec.Unlock()
+
+ return ec.Count
+}
+
+func (ec *endpointCnt) updateStore() error {
+ store := ec.n.getController().getStore(ec.DataScope())
+ if store == nil {
+ return fmt.Errorf("store not found for scope %s on endpoint count update", ec.DataScope())
+ }
+ // make a copy of count and n to avoid being overwritten by store.GetObject
+ count := ec.EndpointCnt()
+ n := ec.n
+ for {
+ if err := ec.n.getController().updateToStore(ec); err == nil || err != datastore.ErrKeyModified {
+ return err
+ }
+ if err := store.GetObject(datastore.Key(ec.Key()...), ec); err != nil {
+ return fmt.Errorf("could not update the kvobject to latest on endpoint count update: %v", err)
+ }
+ ec.Lock()
+ ec.Count = count
+ ec.n = n
+ ec.Unlock()
+ }
+}
+
+func (ec *endpointCnt) setCnt(cnt uint64) error {
+ ec.Lock()
+ ec.Count = cnt
+ ec.Unlock()
+ return ec.updateStore()
+}
+
+func (ec *endpointCnt) atomicIncDecEpCnt(inc bool) error {
+retry:
+ ec.Lock()
+ if inc {
+ ec.Count++
+ } else {
+ if ec.Count > 0 {
+ ec.Count--
+ }
+ }
+ ec.Unlock()
+
+ store := ec.n.getController().getStore(ec.DataScope())
+ if store == nil {
+ return fmt.Errorf("store not found for scope %s", ec.DataScope())
+ }
+
+ if err := ec.n.getController().updateToStore(ec); err != nil {
+ if err == datastore.ErrKeyModified {
+ if err := store.GetObject(datastore.Key(ec.Key()...), ec); err != nil {
+ return fmt.Errorf("could not update the kvobject to latest when trying to atomic add endpoint count: %v", err)
+ }
+
+ goto retry
+ }
+
+ return err
+ }
+
+ return nil
+}
+
+func (ec *endpointCnt) IncEndpointCnt() error {
+ return ec.atomicIncDecEpCnt(true)
+}
+
+func (ec *endpointCnt) DecEndpointCnt() error {
+ return ec.atomicIncDecEpCnt(false)
+}
diff --git a/vendor/github.com/docker/libnetwork/endpoint_info.go b/vendor/github.com/docker/libnetwork/endpoint_info.go
new file mode 100644
index 0000000..202c27b
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/endpoint_info.go
@@ -0,0 +1,449 @@
+package libnetwork
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/types"
+)
+
+// EndpointInfo provides an interface to retrieve network resources bound to the endpoint.
+type EndpointInfo interface {
+ // Iface returns InterfaceInfo, go interface that can be used
+ // to get more information on the interface which was assigned to
+ // the endpoint by the driver. This can be used after the
+ // endpoint has been created.
+ Iface() InterfaceInfo
+
+ // Gateway returns the IPv4 gateway assigned by the driver.
+ // This will only return a valid value if a container has joined the endpoint.
+ Gateway() net.IP
+
+ // GatewayIPv6 returns the IPv6 gateway assigned by the driver.
+ // This will only return a valid value if a container has joined the endpoint.
+ GatewayIPv6() net.IP
+
+ // StaticRoutes returns the list of static routes configured by the network
+ // driver when the container joins a network
+ StaticRoutes() []*types.StaticRoute
+
+ // Sandbox returns the attached sandbox if there, nil otherwise.
+ Sandbox() Sandbox
+}
+
+// InterfaceInfo provides an interface to retrieve interface addresses bound to the endpoint.
+type InterfaceInfo interface {
+ // MacAddress returns the MAC address assigned to the endpoint.
+ MacAddress() net.HardwareAddr
+
+ // Address returns the IPv4 address assigned to the endpoint.
+ Address() *net.IPNet
+
+ // AddressIPv6 returns the IPv6 address assigned to the endpoint.
+ AddressIPv6() *net.IPNet
+
+ // LinkLocalAddresses returns the list of link-local (IPv4/IPv6) addresses assigned to the endpoint.
+ LinkLocalAddresses() []*net.IPNet
+}
+
+type endpointInterface struct {
+ mac net.HardwareAddr
+ addr *net.IPNet
+ addrv6 *net.IPNet
+ llAddrs []*net.IPNet
+ srcName string
+ dstPrefix string
+ routes []*net.IPNet
+ v4PoolID string
+ v6PoolID string
+}
+
+func (epi *endpointInterface) MarshalJSON() ([]byte, error) {
+ epMap := make(map[string]interface{})
+ if epi.mac != nil {
+ epMap["mac"] = epi.mac.String()
+ }
+ if epi.addr != nil {
+ epMap["addr"] = epi.addr.String()
+ }
+ if epi.addrv6 != nil {
+ epMap["addrv6"] = epi.addrv6.String()
+ }
+ if len(epi.llAddrs) != 0 {
+ list := make([]string, 0, len(epi.llAddrs))
+ for _, ll := range epi.llAddrs {
+ list = append(list, ll.String())
+ }
+ epMap["llAddrs"] = list
+ }
+ epMap["srcName"] = epi.srcName
+ epMap["dstPrefix"] = epi.dstPrefix
+ var routes []string
+ for _, route := range epi.routes {
+ routes = append(routes, route.String())
+ }
+ epMap["routes"] = routes
+ epMap["v4PoolID"] = epi.v4PoolID
+ epMap["v6PoolID"] = epi.v6PoolID
+ return json.Marshal(epMap)
+}
+
+func (epi *endpointInterface) UnmarshalJSON(b []byte) error {
+ var (
+ err error
+ epMap map[string]interface{}
+ )
+ if err = json.Unmarshal(b, &epMap); err != nil {
+ return err
+ }
+ if v, ok := epMap["mac"]; ok {
+ if epi.mac, err = net.ParseMAC(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode endpoint interface mac address after json unmarshal: %s", v.(string))
+ }
+ }
+ if v, ok := epMap["addr"]; ok {
+ if epi.addr, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode endpoint interface ipv4 address after json unmarshal: %v", err)
+ }
+ }
+ if v, ok := epMap["addrv6"]; ok {
+ if epi.addrv6, err = types.ParseCIDR(v.(string)); err != nil {
+ return types.InternalErrorf("failed to decode endpoint interface ipv6 address after json unmarshal: %v", err)
+ }
+ }
+ if v, ok := epMap["llAddrs"]; ok {
+ list := v.([]interface{})
+ epi.llAddrs = make([]*net.IPNet, 0, len(list))
+ for _, llS := range list {
+ ll, err := types.ParseCIDR(llS.(string))
+ if err != nil {
+ return types.InternalErrorf("failed to decode endpoint interface link-local address (%v) after json unmarshal: %v", llS, err)
+ }
+ epi.llAddrs = append(epi.llAddrs, ll)
+ }
+ }
+ epi.srcName = epMap["srcName"].(string)
+ epi.dstPrefix = epMap["dstPrefix"].(string)
+
+ rb, _ := json.Marshal(epMap["routes"])
+ var routes []string
+ json.Unmarshal(rb, &routes)
+ epi.routes = make([]*net.IPNet, 0)
+ for _, route := range routes {
+ ip, ipr, err := net.ParseCIDR(route)
+ if err == nil {
+ ipr.IP = ip
+ epi.routes = append(epi.routes, ipr)
+ }
+ }
+ epi.v4PoolID = epMap["v4PoolID"].(string)
+ epi.v6PoolID = epMap["v6PoolID"].(string)
+
+ return nil
+}
+
+func (epi *endpointInterface) CopyTo(dstEpi *endpointInterface) error {
+ dstEpi.mac = types.GetMacCopy(epi.mac)
+ dstEpi.addr = types.GetIPNetCopy(epi.addr)
+ dstEpi.addrv6 = types.GetIPNetCopy(epi.addrv6)
+ dstEpi.srcName = epi.srcName
+ dstEpi.dstPrefix = epi.dstPrefix
+ dstEpi.v4PoolID = epi.v4PoolID
+ dstEpi.v6PoolID = epi.v6PoolID
+ if len(epi.llAddrs) != 0 {
+ dstEpi.llAddrs = make([]*net.IPNet, 0, len(epi.llAddrs))
+ for _, ll := range epi.llAddrs {
+ dstEpi.llAddrs = append(dstEpi.llAddrs, ll)
+ }
+ }
+
+ for _, route := range epi.routes {
+ dstEpi.routes = append(dstEpi.routes, types.GetIPNetCopy(route))
+ }
+
+ return nil
+}
+
+type endpointJoinInfo struct {
+ gw net.IP
+ gw6 net.IP
+ StaticRoutes []*types.StaticRoute
+ driverTableEntries []*tableEntry
+ disableGatewayService bool
+}
+
+type tableEntry struct {
+ tableName string
+ key string
+ value []byte
+}
+
+func (ep *endpoint) Info() EndpointInfo {
+ if ep.sandboxID != "" {
+ return ep
+ }
+ n, err := ep.getNetworkFromStore()
+ if err != nil {
+ return nil
+ }
+
+ ep, err = n.getEndpointFromStore(ep.ID())
+ if err != nil {
+ return nil
+ }
+
+ sb, ok := ep.getSandbox()
+ if !ok {
+ // endpoint hasn't joined any sandbox.
+ // Just return the endpoint
+ return ep
+ }
+
+ if epi := sb.getEndpoint(ep.ID()); epi != nil {
+ return epi
+ }
+
+ return nil
+}
+
+func (ep *endpoint) Iface() InterfaceInfo {
+ ep.Lock()
+ defer ep.Unlock()
+
+ if ep.iface != nil {
+ return ep.iface
+ }
+
+ return nil
+}
+
+func (ep *endpoint) Interface() driverapi.InterfaceInfo {
+ ep.Lock()
+ defer ep.Unlock()
+
+ if ep.iface != nil {
+ return ep.iface
+ }
+
+ return nil
+}
+
+func (epi *endpointInterface) SetMacAddress(mac net.HardwareAddr) error {
+ if epi.mac != nil {
+ return types.ForbiddenErrorf("endpoint interface MAC address present (%s). Cannot be modified with %s.", epi.mac, mac)
+ }
+ if mac == nil {
+ return types.BadRequestErrorf("tried to set nil MAC address to endpoint interface")
+ }
+ epi.mac = types.GetMacCopy(mac)
+ return nil
+}
+
+func (epi *endpointInterface) SetIPAddress(address *net.IPNet) error {
+ if address.IP == nil {
+ return types.BadRequestErrorf("tried to set nil IP address to endpoint interface")
+ }
+ if address.IP.To4() == nil {
+ return setAddress(&epi.addrv6, address)
+ }
+ return setAddress(&epi.addr, address)
+}
+
+func setAddress(ifaceAddr **net.IPNet, address *net.IPNet) error {
+ if *ifaceAddr != nil {
+ return types.ForbiddenErrorf("endpoint interface IP present (%s). Cannot be modified with (%s).", *ifaceAddr, address)
+ }
+ *ifaceAddr = types.GetIPNetCopy(address)
+ return nil
+}
+
+func (epi *endpointInterface) MacAddress() net.HardwareAddr {
+ return types.GetMacCopy(epi.mac)
+}
+
+func (epi *endpointInterface) Address() *net.IPNet {
+ return types.GetIPNetCopy(epi.addr)
+}
+
+func (epi *endpointInterface) AddressIPv6() *net.IPNet {
+ return types.GetIPNetCopy(epi.addrv6)
+}
+
+func (epi *endpointInterface) LinkLocalAddresses() []*net.IPNet {
+ return epi.llAddrs
+}
+
+func (epi *endpointInterface) SetNames(srcName string, dstPrefix string) error {
+ epi.srcName = srcName
+ epi.dstPrefix = dstPrefix
+ return nil
+}
+
+func (ep *endpoint) InterfaceName() driverapi.InterfaceNameInfo {
+ ep.Lock()
+ defer ep.Unlock()
+
+ if ep.iface != nil {
+ return ep.iface
+ }
+
+ return nil
+}
+
+func (ep *endpoint) AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP) error {
+ ep.Lock()
+ defer ep.Unlock()
+
+ r := types.StaticRoute{Destination: destination, RouteType: routeType, NextHop: nextHop}
+
+ if routeType == types.NEXTHOP {
+ // If the route specifies a next-hop, then it's loosely routed (i.e. not bound to a particular interface).
+ ep.joinInfo.StaticRoutes = append(ep.joinInfo.StaticRoutes, &r)
+ } else {
+ // If the route doesn't specify a next-hop, it must be a connected route, bound to an interface.
+ ep.iface.routes = append(ep.iface.routes, r.Destination)
+ }
+ return nil
+}
+
+func (ep *endpoint) AddTableEntry(tableName, key string, value []byte) error {
+ ep.Lock()
+ defer ep.Unlock()
+
+ ep.joinInfo.driverTableEntries = append(ep.joinInfo.driverTableEntries, &tableEntry{
+ tableName: tableName,
+ key: key,
+ value: value,
+ })
+
+ return nil
+}
+
+func (ep *endpoint) Sandbox() Sandbox {
+ cnt, ok := ep.getSandbox()
+ if !ok {
+ return nil
+ }
+ return cnt
+}
+
+func (ep *endpoint) StaticRoutes() []*types.StaticRoute {
+ ep.Lock()
+ defer ep.Unlock()
+
+ if ep.joinInfo == nil {
+ return nil
+ }
+
+ return ep.joinInfo.StaticRoutes
+}
+
+func (ep *endpoint) Gateway() net.IP {
+ ep.Lock()
+ defer ep.Unlock()
+
+ if ep.joinInfo == nil {
+ return net.IP{}
+ }
+
+ return types.GetIPCopy(ep.joinInfo.gw)
+}
+
+func (ep *endpoint) GatewayIPv6() net.IP {
+ ep.Lock()
+ defer ep.Unlock()
+
+ if ep.joinInfo == nil {
+ return net.IP{}
+ }
+
+ return types.GetIPCopy(ep.joinInfo.gw6)
+}
+
+func (ep *endpoint) SetGateway(gw net.IP) error {
+ ep.Lock()
+ defer ep.Unlock()
+
+ ep.joinInfo.gw = types.GetIPCopy(gw)
+ return nil
+}
+
+func (ep *endpoint) SetGatewayIPv6(gw6 net.IP) error {
+ ep.Lock()
+ defer ep.Unlock()
+
+ ep.joinInfo.gw6 = types.GetIPCopy(gw6)
+ return nil
+}
+
+func (ep *endpoint) retrieveFromStore() (*endpoint, error) {
+ n, err := ep.getNetworkFromStore()
+ if err != nil {
+ return nil, fmt.Errorf("could not find network in store to get latest endpoint %s: %v", ep.Name(), err)
+ }
+ return n.getEndpointFromStore(ep.ID())
+}
+
+func (ep *endpoint) DisableGatewayService() {
+ ep.Lock()
+ defer ep.Unlock()
+
+ ep.joinInfo.disableGatewayService = true
+}
+
+func (epj *endpointJoinInfo) MarshalJSON() ([]byte, error) {
+ epMap := make(map[string]interface{})
+ if epj.gw != nil {
+ epMap["gw"] = epj.gw.String()
+ }
+ if epj.gw6 != nil {
+ epMap["gw6"] = epj.gw6.String()
+ }
+ epMap["disableGatewayService"] = epj.disableGatewayService
+ epMap["StaticRoutes"] = epj.StaticRoutes
+ return json.Marshal(epMap)
+}
+
+func (epj *endpointJoinInfo) UnmarshalJSON(b []byte) error {
+ var (
+ err error
+ epMap map[string]interface{}
+ )
+ if err = json.Unmarshal(b, &epMap); err != nil {
+ return err
+ }
+ if v, ok := epMap["gw"]; ok {
+ epj.gw6 = net.ParseIP(v.(string))
+ }
+ if v, ok := epMap["gw6"]; ok {
+ epj.gw6 = net.ParseIP(v.(string))
+ }
+ epj.disableGatewayService = epMap["disableGatewayService"].(bool)
+
+ var tStaticRoute []types.StaticRoute
+ if v, ok := epMap["StaticRoutes"]; ok {
+ tb, _ := json.Marshal(v)
+ var tStaticRoute []types.StaticRoute
+ json.Unmarshal(tb, &tStaticRoute)
+ }
+ var StaticRoutes []*types.StaticRoute
+ for _, r := range tStaticRoute {
+ StaticRoutes = append(StaticRoutes, &r)
+ }
+ epj.StaticRoutes = StaticRoutes
+
+ return nil
+}
+
+func (epj *endpointJoinInfo) CopyTo(dstEpj *endpointJoinInfo) error {
+ dstEpj.disableGatewayService = epj.disableGatewayService
+ dstEpj.StaticRoutes = make([]*types.StaticRoute, len(epj.StaticRoutes))
+ copy(dstEpj.StaticRoutes, epj.StaticRoutes)
+ dstEpj.driverTableEntries = make([]*tableEntry, len(epj.driverTableEntries))
+ copy(dstEpj.driverTableEntries, epj.driverTableEntries)
+ dstEpj.gw = types.GetIPCopy(epj.gw)
+ dstEpj.gw = types.GetIPCopy(epj.gw6)
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/endpoint_info_unix.go b/vendor/github.com/docker/libnetwork/endpoint_info_unix.go
new file mode 100644
index 0000000..f2534f4
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/endpoint_info_unix.go
@@ -0,0 +1,30 @@
+// +build !windows
+
+package libnetwork
+
+import "fmt"
+
+func (ep *endpoint) DriverInfo() (map[string]interface{}, error) {
+ ep, err := ep.retrieveFromStore()
+ if err != nil {
+ return nil, err
+ }
+
+ if sb, ok := ep.getSandbox(); ok {
+ if gwep := sb.getEndpointInGWNetwork(); gwep != nil && gwep.ID() != ep.ID() {
+ return gwep.DriverInfo()
+ }
+ }
+
+ n, err := ep.getNetworkFromStore()
+ if err != nil {
+ return nil, fmt.Errorf("could not find network in store for driver info: %v", err)
+ }
+
+ driver, err := n.driver(true)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get driver info: %v", err)
+ }
+
+ return driver.EndpointOperInfo(n.ID(), ep.ID())
+}
diff --git a/vendor/github.com/docker/libnetwork/endpoint_info_windows.go b/vendor/github.com/docker/libnetwork/endpoint_info_windows.go
new file mode 100644
index 0000000..93ad833
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/endpoint_info_windows.go
@@ -0,0 +1,45 @@
+// +build windows
+
+package libnetwork
+
+import "fmt"
+
+func (ep *endpoint) DriverInfo() (map[string]interface{}, error) {
+ ep, err := ep.retrieveFromStore()
+ if err != nil {
+ return nil, err
+ }
+
+ var gwDriverInfo map[string]interface{}
+ if sb, ok := ep.getSandbox(); ok {
+ if gwep := sb.getEndpointInGWNetwork(); gwep != nil && gwep.ID() != ep.ID() {
+
+ gwDriverInfo, err = gwep.DriverInfo()
+ if err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ n, err := ep.getNetworkFromStore()
+ if err != nil {
+ return nil, fmt.Errorf("could not find network in store for driver info: %v", err)
+ }
+
+ driver, err := n.driver(true)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get driver info: %v", err)
+ }
+
+ epInfo, err := driver.EndpointOperInfo(n.ID(), ep.ID())
+ if err != nil {
+ return nil, err
+ }
+
+ if epInfo != nil {
+ epInfo["GW_INFO"] = gwDriverInfo
+ return epInfo, nil
+ }
+
+ return gwDriverInfo, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/error.go b/vendor/github.com/docker/libnetwork/error.go
new file mode 100644
index 0000000..5f00709
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/error.go
@@ -0,0 +1,193 @@
+package libnetwork
+
+import (
+ "fmt"
+)
+
+// ErrNoSuchNetwork is returned when a network query finds no result
+type ErrNoSuchNetwork string
+
+func (nsn ErrNoSuchNetwork) Error() string {
+ return fmt.Sprintf("network %s not found", string(nsn))
+}
+
+// NotFound denotes the type of this error
+func (nsn ErrNoSuchNetwork) NotFound() {}
+
+// ErrNoSuchEndpoint is returned when an endpoint query finds no result
+type ErrNoSuchEndpoint string
+
+func (nse ErrNoSuchEndpoint) Error() string {
+ return fmt.Sprintf("endpoint %s not found", string(nse))
+}
+
+// NotFound denotes the type of this error
+func (nse ErrNoSuchEndpoint) NotFound() {}
+
+// ErrInvalidNetworkDriver is returned if an invalid driver
+// name is passed.
+type ErrInvalidNetworkDriver string
+
+func (ind ErrInvalidNetworkDriver) Error() string {
+ return fmt.Sprintf("invalid driver bound to network: %s", string(ind))
+}
+
+// BadRequest denotes the type of this error
+func (ind ErrInvalidNetworkDriver) BadRequest() {}
+
+// ErrInvalidJoin is returned if a join is attempted on an endpoint
+// which already has a container joined.
+type ErrInvalidJoin struct{}
+
+func (ij ErrInvalidJoin) Error() string {
+ return "a container has already joined the endpoint"
+}
+
+// BadRequest denotes the type of this error
+func (ij ErrInvalidJoin) BadRequest() {}
+
+// ErrNoContainer is returned when the endpoint has no container
+// attached to it.
+type ErrNoContainer struct{}
+
+func (nc ErrNoContainer) Error() string {
+ return "no container is attached to the endpoint"
+}
+
+// Maskable denotes the type of this error
+func (nc ErrNoContainer) Maskable() {}
+
+// ErrInvalidID is returned when a query-by-id method is being invoked
+// with an empty id parameter
+type ErrInvalidID string
+
+func (ii ErrInvalidID) Error() string {
+ return fmt.Sprintf("invalid id: %s", string(ii))
+}
+
+// BadRequest denotes the type of this error
+func (ii ErrInvalidID) BadRequest() {}
+
+// ErrInvalidName is returned when a query-by-name or resource create method is
+// invoked with an empty name parameter
+type ErrInvalidName string
+
+func (in ErrInvalidName) Error() string {
+ return fmt.Sprintf("invalid name: %s", string(in))
+}
+
+// BadRequest denotes the type of this error
+func (in ErrInvalidName) BadRequest() {}
+
+// ErrInvalidConfigFile type is returned when an invalid LibNetwork config file is detected
+type ErrInvalidConfigFile string
+
+func (cf ErrInvalidConfigFile) Error() string {
+ return fmt.Sprintf("Invalid Config file %q", string(cf))
+}
+
+// NetworkTypeError type is returned when the network type string is not
+// known to libnetwork.
+type NetworkTypeError string
+
+func (nt NetworkTypeError) Error() string {
+ return fmt.Sprintf("unknown driver %q", string(nt))
+}
+
+// NotFound denotes the type of this error
+func (nt NetworkTypeError) NotFound() {}
+
+// NetworkNameError is returned when a network with the same name already exists.
+type NetworkNameError string
+
+func (nnr NetworkNameError) Error() string {
+ return fmt.Sprintf("network with name %s already exists", string(nnr))
+}
+
+// Forbidden denotes the type of this error
+func (nnr NetworkNameError) Forbidden() {}
+
+// UnknownNetworkError is returned when libnetwork could not find in its database
+// a network with the same name and id.
+type UnknownNetworkError struct {
+ name string
+ id string
+}
+
+func (une *UnknownNetworkError) Error() string {
+ return fmt.Sprintf("unknown network %s id %s", une.name, une.id)
+}
+
+// NotFound denotes the type of this error
+func (une *UnknownNetworkError) NotFound() {}
+
+// ActiveEndpointsError is returned when a network is deleted which has active
+// endpoints in it.
+type ActiveEndpointsError struct {
+ name string
+ id string
+}
+
+func (aee *ActiveEndpointsError) Error() string {
+ return fmt.Sprintf("network %s id %s has active endpoints", aee.name, aee.id)
+}
+
+// Forbidden denotes the type of this error
+func (aee *ActiveEndpointsError) Forbidden() {}
+
+// UnknownEndpointError is returned when libnetwork could not find in its database
+// an endpoint with the same name and id.
+type UnknownEndpointError struct {
+ name string
+ id string
+}
+
+func (uee *UnknownEndpointError) Error() string {
+ return fmt.Sprintf("unknown endpoint %s id %s", uee.name, uee.id)
+}
+
+// NotFound denotes the type of this error
+func (uee *UnknownEndpointError) NotFound() {}
+
+// ActiveContainerError is returned when an endpoint is deleted which has active
+// containers attached to it.
+type ActiveContainerError struct {
+ name string
+ id string
+}
+
+func (ace *ActiveContainerError) Error() string {
+ return fmt.Sprintf("endpoint with name %s id %s has active containers", ace.name, ace.id)
+}
+
+// Forbidden denotes the type of this error
+func (ace *ActiveContainerError) Forbidden() {}
+
+// InvalidContainerIDError is returned when an invalid container id is passed
+// in Join/Leave
+type InvalidContainerIDError string
+
+func (id InvalidContainerIDError) Error() string {
+ return fmt.Sprintf("invalid container id %s", string(id))
+}
+
+// BadRequest denotes the type of this error
+func (id InvalidContainerIDError) BadRequest() {}
+
+// ManagerRedirectError is returned when the request should be redirected to Manager
+type ManagerRedirectError string
+
+func (mr ManagerRedirectError) Error() string {
+ return "Redirect the request to the manager"
+}
+
+// Maskable denotes the type of this error
+func (mr ManagerRedirectError) Maskable() {}
+
+// ErrDataStoreNotInitialized is returned if an invalid data scope is passed
+// for getting data store
+type ErrDataStoreNotInitialized string
+
+func (dsni ErrDataStoreNotInitialized) Error() string {
+ return fmt.Sprintf("datastore for scope %q is not initialized", string(dsni))
+}
diff --git a/vendor/github.com/docker/libnetwork/etchosts/etchosts.go b/vendor/github.com/docker/libnetwork/etchosts/etchosts.go
new file mode 100644
index 0000000..d55298a
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/etchosts/etchosts.go
@@ -0,0 +1,208 @@
+package etchosts
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "regexp"
+ "strings"
+ "sync"
+)
+
+// Record Structure for a single host record
+type Record struct {
+ Hosts string
+ IP string
+}
+
+// WriteTo writes record to file and returns bytes written or error
+func (r Record) WriteTo(w io.Writer) (int64, error) {
+ n, err := fmt.Fprintf(w, "%s\t%s\n", r.IP, r.Hosts)
+ return int64(n), err
+}
+
+var (
+ // Default hosts config records slice
+ defaultContent = []Record{
+ {Hosts: "localhost", IP: "127.0.0.1"},
+ {Hosts: "localhost ip6-localhost ip6-loopback", IP: "::1"},
+ {Hosts: "ip6-localnet", IP: "fe00::0"},
+ {Hosts: "ip6-mcastprefix", IP: "ff00::0"},
+ {Hosts: "ip6-allnodes", IP: "ff02::1"},
+ {Hosts: "ip6-allrouters", IP: "ff02::2"},
+ }
+
+ // A cache of path level locks for synchronizing /etc/hosts
+ // updates on a file level
+ pathMap = make(map[string]*sync.Mutex)
+
+ // A package level mutex to synchronize the cache itself
+ pathMutex sync.Mutex
+)
+
+func pathLock(path string) func() {
+ pathMutex.Lock()
+ defer pathMutex.Unlock()
+
+ pl, ok := pathMap[path]
+ if !ok {
+ pl = &sync.Mutex{}
+ pathMap[path] = pl
+ }
+
+ pl.Lock()
+ return func() {
+ pl.Unlock()
+ }
+}
+
+// Drop drops the path string from the path cache
+func Drop(path string) {
+ pathMutex.Lock()
+ defer pathMutex.Unlock()
+
+ delete(pathMap, path)
+}
+
+// Build function
+// path is path to host file string required
+// IP, hostname, and domainname set main record leave empty for no master record
+// extraContent is an array of extra host records.
+func Build(path, IP, hostname, domainname string, extraContent []Record) error {
+ defer pathLock(path)()
+
+ content := bytes.NewBuffer(nil)
+ if IP != "" {
+ //set main record
+ var mainRec Record
+ mainRec.IP = IP
+ // User might have provided a FQDN in hostname or split it across hostname
+ // and domainname. We want the FQDN and the bare hostname.
+ fqdn := hostname
+ if domainname != "" {
+ fqdn = fmt.Sprintf("%s.%s", fqdn, domainname)
+ }
+ parts := strings.SplitN(fqdn, ".", 2)
+ if len(parts) == 2 {
+ mainRec.Hosts = fmt.Sprintf("%s %s", fqdn, parts[0])
+ } else {
+ mainRec.Hosts = fqdn
+ }
+ if _, err := mainRec.WriteTo(content); err != nil {
+ return err
+ }
+ }
+ // Write defaultContent slice to buffer
+ for _, r := range defaultContent {
+ if _, err := r.WriteTo(content); err != nil {
+ return err
+ }
+ }
+ // Write extra content from function arguments
+ for _, r := range extraContent {
+ if _, err := r.WriteTo(content); err != nil {
+ return err
+ }
+ }
+
+ return ioutil.WriteFile(path, content.Bytes(), 0644)
+}
+
+// Add adds an arbitrary number of Records to an already existing /etc/hosts file
+func Add(path string, recs []Record) error {
+ defer pathLock(path)()
+
+ if len(recs) == 0 {
+ return nil
+ }
+
+ b, err := mergeRecords(path, recs)
+ if err != nil {
+ return err
+ }
+
+ return ioutil.WriteFile(path, b, 0644)
+}
+
+func mergeRecords(path string, recs []Record) ([]byte, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ content := bytes.NewBuffer(nil)
+
+ if _, err := content.ReadFrom(f); err != nil {
+ return nil, err
+ }
+
+ for _, r := range recs {
+ if _, err := r.WriteTo(content); err != nil {
+ return nil, err
+ }
+ }
+
+ return content.Bytes(), nil
+}
+
+// Delete deletes an arbitrary number of Records already existing in /etc/hosts file
+func Delete(path string, recs []Record) error {
+ defer pathLock(path)()
+
+ if len(recs) == 0 {
+ return nil
+ }
+ old, err := os.Open(path)
+ if err != nil {
+ return err
+ }
+
+ var buf bytes.Buffer
+
+ s := bufio.NewScanner(old)
+ eol := []byte{'\n'}
+loop:
+ for s.Scan() {
+ b := s.Bytes()
+ if len(b) == 0 {
+ continue
+ }
+
+ if b[0] == '#' {
+ buf.Write(b)
+ buf.Write(eol)
+ continue
+ }
+ for _, r := range recs {
+ if bytes.HasSuffix(b, []byte("\t"+r.Hosts)) {
+ continue loop
+ }
+ }
+ buf.Write(b)
+ buf.Write(eol)
+ }
+ old.Close()
+ if err := s.Err(); err != nil {
+ return err
+ }
+ return ioutil.WriteFile(path, buf.Bytes(), 0644)
+}
+
+// Update all IP addresses where hostname matches.
+// path is path to host file
+// IP is new IP address
+// hostname is hostname to search for to replace IP
+func Update(path, IP, hostname string) error {
+ defer pathLock(path)()
+
+ old, err := ioutil.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ var re = regexp.MustCompile(fmt.Sprintf("(\\S*)(\\t%s)(\\s|\\.)", regexp.QuoteMeta(hostname)))
+ return ioutil.WriteFile(path, re.ReplaceAll(old, []byte(IP+"$2"+"$3")), 0644)
+}
diff --git a/vendor/github.com/docker/libnetwork/firewall_linux.go b/vendor/github.com/docker/libnetwork/firewall_linux.go
new file mode 100644
index 0000000..8c27c1d
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/firewall_linux.go
@@ -0,0 +1,29 @@
+package libnetwork
+
+import (
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/iptables"
+)
+
+const userChain = "DOCKER-USER"
+
+// This chain allow users to configure firewall policies in a way that persists
+// docker operations/restarts. Docker will not delete or modify any pre-existing
+// rules from the DOCKER-USER filter chain.
+func arrangeUserFilterRule() {
+ _, err := iptables.NewChain(userChain, iptables.Filter, false)
+ if err != nil {
+ logrus.Warnf("Failed to create %s chain: %v", userChain, err)
+ return
+ }
+
+ if err = iptables.AddReturnRule(userChain); err != nil {
+ logrus.Warnf("Failed to add the RETURN rule for %s: %v", userChain, err)
+ return
+ }
+
+ err = iptables.EnsureJumpRule("FORWARD", userChain)
+ if err != nil {
+ logrus.Warnf("Failed to ensure the jump rule for %s: %v", userChain, err)
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/firewall_others.go b/vendor/github.com/docker/libnetwork/firewall_others.go
new file mode 100644
index 0000000..c41b3e0
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/firewall_others.go
@@ -0,0 +1,6 @@
+// +build !linux
+
+package libnetwork
+
+func arrangeUserFilterRule() {
+}
diff --git a/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery.go b/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery.go
new file mode 100644
index 0000000..32b09ee
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery.go
@@ -0,0 +1,112 @@
+package hostdiscovery
+
+import (
+ "net"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+
+ mapset "github.com/deckarep/golang-set"
+ "github.com/docker/docker/pkg/discovery"
+ // Including KV
+ _ "github.com/docker/docker/pkg/discovery/kv"
+ "github.com/docker/libnetwork/types"
+)
+
+type hostDiscovery struct {
+ watcher discovery.Watcher
+ nodes mapset.Set
+ stopChan chan struct{}
+ sync.Mutex
+}
+
+// NewHostDiscovery function creates a host discovery object
+func NewHostDiscovery(watcher discovery.Watcher) HostDiscovery {
+ return &hostDiscovery{watcher: watcher, nodes: mapset.NewSet(), stopChan: make(chan struct{})}
+}
+
+func (h *hostDiscovery) Watch(activeCallback ActiveCallback, joinCallback JoinCallback, leaveCallback LeaveCallback) error {
+ h.Lock()
+ d := h.watcher
+ h.Unlock()
+ if d == nil {
+ return types.BadRequestErrorf("invalid discovery watcher")
+ }
+ discoveryCh, errCh := d.Watch(h.stopChan)
+ go h.monitorDiscovery(discoveryCh, errCh, activeCallback, joinCallback, leaveCallback)
+ return nil
+}
+
+func (h *hostDiscovery) monitorDiscovery(ch <-chan discovery.Entries, errCh <-chan error,
+ activeCallback ActiveCallback, joinCallback JoinCallback, leaveCallback LeaveCallback) {
+ for {
+ select {
+ case entries := <-ch:
+ h.processCallback(entries, activeCallback, joinCallback, leaveCallback)
+ case err := <-errCh:
+ if err != nil {
+ logrus.Errorf("discovery error: %v", err)
+ }
+ case <-h.stopChan:
+ return
+ }
+ }
+}
+
+func (h *hostDiscovery) StopDiscovery() error {
+ h.Lock()
+ stopChan := h.stopChan
+ h.watcher = nil
+ h.Unlock()
+
+ close(stopChan)
+ return nil
+}
+
+func (h *hostDiscovery) processCallback(entries discovery.Entries,
+ activeCallback ActiveCallback, joinCallback JoinCallback, leaveCallback LeaveCallback) {
+ updated := hosts(entries)
+ h.Lock()
+ existing := h.nodes
+ added, removed := diff(existing, updated)
+ h.nodes = updated
+ h.Unlock()
+
+ activeCallback()
+ if len(added) > 0 {
+ joinCallback(added)
+ }
+ if len(removed) > 0 {
+ leaveCallback(removed)
+ }
+}
+
+func diff(existing mapset.Set, updated mapset.Set) (added []net.IP, removed []net.IP) {
+ addSlice := updated.Difference(existing).ToSlice()
+ removeSlice := existing.Difference(updated).ToSlice()
+ for _, ip := range addSlice {
+ added = append(added, net.ParseIP(ip.(string)))
+ }
+ for _, ip := range removeSlice {
+ removed = append(removed, net.ParseIP(ip.(string)))
+ }
+ return
+}
+
+func (h *hostDiscovery) Fetch() []net.IP {
+ h.Lock()
+ defer h.Unlock()
+ ips := []net.IP{}
+ for _, ipstr := range h.nodes.ToSlice() {
+ ips = append(ips, net.ParseIP(ipstr.(string)))
+ }
+ return ips
+}
+
+func hosts(entries discovery.Entries) mapset.Set {
+ hosts := mapset.NewSet()
+ for _, entry := range entries {
+ hosts.Add(entry.Host)
+ }
+ return hosts
+}
diff --git a/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery_api.go b/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery_api.go
new file mode 100644
index 0000000..f0ca40e
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/hostdiscovery/hostdiscovery_api.go
@@ -0,0 +1,22 @@
+package hostdiscovery
+
+import "net"
+
+// JoinCallback provides a callback event for new node joining the cluster
+type JoinCallback func(entries []net.IP)
+
+// ActiveCallback provides a callback event for active discovery event
+type ActiveCallback func()
+
+// LeaveCallback provides a callback event for node leaving the cluster
+type LeaveCallback func(entries []net.IP)
+
+// HostDiscovery primary interface
+type HostDiscovery interface {
+ //Watch Node join and leave cluster events
+ Watch(activeCallback ActiveCallback, joinCallback JoinCallback, leaveCallback LeaveCallback) error
+ // StopDiscovery stops the discovery process
+ StopDiscovery() error
+ // Fetch returns a list of host IPs that are currently discovered
+ Fetch() []net.IP
+}
diff --git a/vendor/github.com/docker/libnetwork/idm/idm.go b/vendor/github.com/docker/libnetwork/idm/idm.go
new file mode 100644
index 0000000..7e449a0
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/idm/idm.go
@@ -0,0 +1,76 @@
+// Package idm manages reservation/release of numerical ids from a configured set of contiguous ids
+package idm
+
+import (
+ "errors"
+ "fmt"
+
+ "github.com/docker/libnetwork/bitseq"
+ "github.com/docker/libnetwork/datastore"
+)
+
+// Idm manages the reservation/release of numerical ids from a contiguous set
+type Idm struct {
+ start uint64
+ end uint64
+ handle *bitseq.Handle
+}
+
+// New returns an instance of id manager for a [start,end] set of numerical ids
+func New(ds datastore.DataStore, id string, start, end uint64) (*Idm, error) {
+ if id == "" {
+ return nil, errors.New("Invalid id")
+ }
+ if end <= start {
+ return nil, fmt.Errorf("Invalid set range: [%d, %d]", start, end)
+ }
+
+ h, err := bitseq.NewHandle("idm", ds, id, 1+end-start)
+ if err != nil {
+ return nil, fmt.Errorf("failed to initialize bit sequence handler: %s", err.Error())
+ }
+
+ return &Idm{start: start, end: end, handle: h}, nil
+}
+
+// GetID returns the first available id in the set
+func (i *Idm) GetID() (uint64, error) {
+ if i.handle == nil {
+ return 0, errors.New("ID set is not initialized")
+ }
+ ordinal, err := i.handle.SetAny()
+ return i.start + ordinal, err
+}
+
+// GetSpecificID tries to reserve the specified id
+func (i *Idm) GetSpecificID(id uint64) error {
+ if i.handle == nil {
+ return errors.New("ID set is not initialized")
+ }
+
+ if id < i.start || id > i.end {
+ return errors.New("Requested id does not belong to the set")
+ }
+
+ return i.handle.Set(id - i.start)
+}
+
+// GetIDInRange returns the first available id in the set within a [start,end] range
+func (i *Idm) GetIDInRange(start, end uint64) (uint64, error) {
+ if i.handle == nil {
+ return 0, errors.New("ID set is not initialized")
+ }
+
+ if start < i.start || end > i.end {
+ return 0, errors.New("Requested range does not belong to the set")
+ }
+
+ ordinal, err := i.handle.SetAnyInRange(start-i.start, end-i.start)
+
+ return i.start + ordinal, err
+}
+
+// Release releases the specified id
+func (i *Idm) Release(id uint64) {
+ i.handle.Unset(id - i.start)
+}
diff --git a/vendor/github.com/docker/libnetwork/ipam/allocator.go b/vendor/github.com/docker/libnetwork/ipam/allocator.go
new file mode 100644
index 0000000..b3876ff
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipam/allocator.go
@@ -0,0 +1,601 @@
+package ipam
+
+import (
+ "fmt"
+ "net"
+ "sort"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/bitseq"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/ipamutils"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ localAddressSpace = "LocalDefault"
+ globalAddressSpace = "GlobalDefault"
+ // The biggest configurable host subnets
+ minNetSize = 8
+ minNetSizeV6 = 64
+ // datastore keyes for ipam objects
+ dsConfigKey = "ipam/" + ipamapi.DefaultIPAM + "/config"
+ dsDataKey = "ipam/" + ipamapi.DefaultIPAM + "/data"
+)
+
+// Allocator provides per address space ipv4/ipv6 book keeping
+type Allocator struct {
+ // Predefined pools for default address spaces
+ predefined map[string][]*net.IPNet
+ addrSpaces map[string]*addrSpace
+ // stores []datastore.Datastore
+ // Allocated addresses in each address space's subnet
+ addresses map[SubnetKey]*bitseq.Handle
+ sync.Mutex
+}
+
+// NewAllocator returns an instance of libnetwork ipam
+func NewAllocator(lcDs, glDs datastore.DataStore) (*Allocator, error) {
+ a := &Allocator{}
+
+ // Load predefined subnet pools
+ a.predefined = map[string][]*net.IPNet{
+ localAddressSpace: ipamutils.PredefinedBroadNetworks,
+ globalAddressSpace: ipamutils.PredefinedGranularNetworks,
+ }
+
+ // Initialize bitseq map
+ a.addresses = make(map[SubnetKey]*bitseq.Handle)
+
+ // Initialize address spaces
+ a.addrSpaces = make(map[string]*addrSpace)
+ for _, aspc := range []struct {
+ as string
+ ds datastore.DataStore
+ }{
+ {localAddressSpace, lcDs},
+ {globalAddressSpace, glDs},
+ } {
+ a.initializeAddressSpace(aspc.as, aspc.ds)
+ }
+
+ return a, nil
+}
+
+func (a *Allocator) refresh(as string) error {
+ aSpace, err := a.getAddressSpaceFromStore(as)
+ if err != nil {
+ return types.InternalErrorf("error getting pools config from store: %v", err)
+ }
+
+ if aSpace == nil {
+ return nil
+ }
+
+ a.Lock()
+ a.addrSpaces[as] = aSpace
+ a.Unlock()
+
+ return nil
+}
+
+func (a *Allocator) updateBitMasks(aSpace *addrSpace) error {
+ var inserterList []func() error
+
+ aSpace.Lock()
+ for k, v := range aSpace.subnets {
+ if v.Range == nil {
+ kk := k
+ vv := v
+ inserterList = append(inserterList, func() error { return a.insertBitMask(kk, vv.Pool) })
+ }
+ }
+ aSpace.Unlock()
+
+ // Add the bitmasks (data could come from datastore)
+ if inserterList != nil {
+ for _, f := range inserterList {
+ if err := f(); err != nil {
+ return err
+ }
+ }
+ }
+
+ return nil
+}
+
+// Checks for and fixes damaged bitmask.
+func (a *Allocator) checkConsistency(as string) {
+ var sKeyList []SubnetKey
+
+ // Retrieve this address space's configuration and bitmasks from the datastore
+ a.refresh(as)
+ a.Lock()
+ aSpace, ok := a.addrSpaces[as]
+ a.Unlock()
+ if !ok {
+ return
+ }
+ a.updateBitMasks(aSpace)
+
+ aSpace.Lock()
+ for sk, pd := range aSpace.subnets {
+ if pd.Range != nil {
+ continue
+ }
+ sKeyList = append(sKeyList, sk)
+ }
+ aSpace.Unlock()
+
+ for _, sk := range sKeyList {
+ a.Lock()
+ bm := a.addresses[sk]
+ a.Unlock()
+ if err := bm.CheckConsistency(); err != nil {
+ logrus.Warnf("Error while running consistency check for %s: %v", sk, err)
+ }
+ }
+}
+
+func (a *Allocator) initializeAddressSpace(as string, ds datastore.DataStore) error {
+ scope := ""
+ if ds != nil {
+ scope = ds.Scope()
+ }
+
+ a.Lock()
+ if currAS, ok := a.addrSpaces[as]; ok {
+ if currAS.ds != nil {
+ a.Unlock()
+ return types.ForbiddenErrorf("a datastore is already configured for the address space %s", as)
+ }
+ }
+ a.addrSpaces[as] = &addrSpace{
+ subnets: map[SubnetKey]*PoolData{},
+ id: dsConfigKey + "/" + as,
+ scope: scope,
+ ds: ds,
+ alloc: a,
+ }
+ a.Unlock()
+
+ a.checkConsistency(as)
+
+ return nil
+}
+
+// DiscoverNew informs the allocator about a new global scope datastore
+func (a *Allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ if dType != discoverapi.DatastoreConfig {
+ return nil
+ }
+
+ dsc, ok := data.(discoverapi.DatastoreConfigData)
+ if !ok {
+ return types.InternalErrorf("incorrect data in datastore update notification: %v", data)
+ }
+
+ ds, err := datastore.NewDataStoreFromConfig(dsc)
+ if err != nil {
+ return err
+ }
+
+ return a.initializeAddressSpace(globalAddressSpace, ds)
+}
+
+// DiscoverDelete is a notification of no interest for the allocator
+func (a *Allocator) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+// GetDefaultAddressSpaces returns the local and global default address spaces
+func (a *Allocator) GetDefaultAddressSpaces() (string, string, error) {
+ return localAddressSpace, globalAddressSpace, nil
+}
+
+// RequestPool returns an address pool along with its unique id.
+func (a *Allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) {
+ logrus.Debugf("RequestPool(%s, %s, %s, %v, %t)", addressSpace, pool, subPool, options, v6)
+
+ k, nw, ipr, err := a.parsePoolRequest(addressSpace, pool, subPool, v6)
+ if err != nil {
+ return "", nil, nil, types.InternalErrorf("failed to parse pool request for address space %q pool %q subpool %q: %v", addressSpace, pool, subPool, err)
+ }
+
+ pdf := k == nil
+
+retry:
+ if pdf {
+ if nw, err = a.getPredefinedPool(addressSpace, v6); err != nil {
+ return "", nil, nil, err
+ }
+ k = &SubnetKey{AddressSpace: addressSpace, Subnet: nw.String()}
+ }
+
+ if err := a.refresh(addressSpace); err != nil {
+ return "", nil, nil, err
+ }
+
+ aSpace, err := a.getAddrSpace(addressSpace)
+ if err != nil {
+ return "", nil, nil, err
+ }
+
+ insert, err := aSpace.updatePoolDBOnAdd(*k, nw, ipr, pdf)
+ if err != nil {
+ if _, ok := err.(types.MaskableError); ok {
+ logrus.Debugf("Retrying predefined pool search: %v", err)
+ goto retry
+ }
+ return "", nil, nil, err
+ }
+
+ if err := a.writeToStore(aSpace); err != nil {
+ if _, ok := err.(types.RetryError); !ok {
+ return "", nil, nil, types.InternalErrorf("pool configuration failed because of %s", err.Error())
+ }
+
+ goto retry
+ }
+
+ return k.String(), nw, nil, insert()
+}
+
+// ReleasePool releases the address pool identified by the passed id
+func (a *Allocator) ReleasePool(poolID string) error {
+ logrus.Debugf("ReleasePool(%s)", poolID)
+ k := SubnetKey{}
+ if err := k.FromString(poolID); err != nil {
+ return types.BadRequestErrorf("invalid pool id: %s", poolID)
+ }
+
+retry:
+ if err := a.refresh(k.AddressSpace); err != nil {
+ return err
+ }
+
+ aSpace, err := a.getAddrSpace(k.AddressSpace)
+ if err != nil {
+ return err
+ }
+
+ remove, err := aSpace.updatePoolDBOnRemoval(k)
+ if err != nil {
+ return err
+ }
+
+ if err = a.writeToStore(aSpace); err != nil {
+ if _, ok := err.(types.RetryError); !ok {
+ return types.InternalErrorf("pool (%s) removal failed because of %v", poolID, err)
+ }
+ goto retry
+ }
+
+ return remove()
+}
+
+// Given the address space, returns the local or global PoolConfig based on the
+// address space is local or global. AddressSpace locality is being registered with IPAM out of band.
+func (a *Allocator) getAddrSpace(as string) (*addrSpace, error) {
+ a.Lock()
+ defer a.Unlock()
+ aSpace, ok := a.addrSpaces[as]
+ if !ok {
+ return nil, types.BadRequestErrorf("cannot find address space %s (most likely the backing datastore is not configured)", as)
+ }
+ return aSpace, nil
+}
+
+func (a *Allocator) parsePoolRequest(addressSpace, pool, subPool string, v6 bool) (*SubnetKey, *net.IPNet, *AddressRange, error) {
+ var (
+ nw *net.IPNet
+ ipr *AddressRange
+ err error
+ )
+
+ if addressSpace == "" {
+ return nil, nil, nil, ipamapi.ErrInvalidAddressSpace
+ }
+
+ if pool == "" && subPool != "" {
+ return nil, nil, nil, ipamapi.ErrInvalidSubPool
+ }
+
+ if pool == "" {
+ return nil, nil, nil, nil
+ }
+
+ if _, nw, err = net.ParseCIDR(pool); err != nil {
+ return nil, nil, nil, ipamapi.ErrInvalidPool
+ }
+
+ if subPool != "" {
+ if ipr, err = getAddressRange(subPool, nw); err != nil {
+ return nil, nil, nil, err
+ }
+ }
+
+ return &SubnetKey{AddressSpace: addressSpace, Subnet: nw.String(), ChildSubnet: subPool}, nw, ipr, nil
+}
+
+func (a *Allocator) insertBitMask(key SubnetKey, pool *net.IPNet) error {
+ //logrus.Debugf("Inserting bitmask (%s, %s)", key.String(), pool.String())
+
+ store := a.getStore(key.AddressSpace)
+ ipVer := getAddressVersion(pool.IP)
+ ones, bits := pool.Mask.Size()
+ numAddresses := uint64(1 << uint(bits-ones))
+
+ // Allow /64 subnet
+ if ipVer == v6 && numAddresses == 0 {
+ numAddresses--
+ }
+
+ // Generate the new address masks. AddressMask content may come from datastore
+ h, err := bitseq.NewHandle(dsDataKey, store, key.String(), numAddresses)
+ if err != nil {
+ return err
+ }
+
+ // Do not let network identifier address be reserved
+ // Do the same for IPv6 so that bridge ip starts with XXXX...::1
+ h.Set(0)
+
+ // Do not let broadcast address be reserved
+ if ipVer == v4 {
+ h.Set(numAddresses - 1)
+ }
+
+ a.Lock()
+ a.addresses[key] = h
+ a.Unlock()
+ return nil
+}
+
+func (a *Allocator) retrieveBitmask(k SubnetKey, n *net.IPNet) (*bitseq.Handle, error) {
+ a.Lock()
+ bm, ok := a.addresses[k]
+ a.Unlock()
+ if !ok {
+ logrus.Debugf("Retrieving bitmask (%s, %s)", k.String(), n.String())
+ if err := a.insertBitMask(k, n); err != nil {
+ return nil, types.InternalErrorf("could not find bitmask in datastore for %s", k.String())
+ }
+ a.Lock()
+ bm = a.addresses[k]
+ a.Unlock()
+ }
+ return bm, nil
+}
+
+func (a *Allocator) getPredefineds(as string) []*net.IPNet {
+ a.Lock()
+ defer a.Unlock()
+ l := make([]*net.IPNet, 0, len(a.predefined[as]))
+ for _, pool := range a.predefined[as] {
+ l = append(l, pool)
+ }
+ return l
+}
+
+func (a *Allocator) getPredefinedPool(as string, ipV6 bool) (*net.IPNet, error) {
+ var v ipVersion
+ v = v4
+ if ipV6 {
+ v = v6
+ }
+
+ if as != localAddressSpace && as != globalAddressSpace {
+ return nil, types.NotImplementedErrorf("no default pool availbale for non-default addresss spaces")
+ }
+
+ aSpace, err := a.getAddrSpace(as)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, nw := range a.getPredefineds(as) {
+ if v != getAddressVersion(nw.IP) {
+ continue
+ }
+ aSpace.Lock()
+ _, ok := aSpace.subnets[SubnetKey{AddressSpace: as, Subnet: nw.String()}]
+ aSpace.Unlock()
+ if ok {
+ continue
+ }
+
+ if !aSpace.contains(as, nw) {
+ return nw, nil
+ }
+ }
+
+ return nil, types.NotFoundErrorf("could not find an available, non-overlapping IPv%d address pool among the defaults to assign to the network", v)
+}
+
+// RequestAddress returns an address from the specified pool ID
+func (a *Allocator) RequestAddress(poolID string, prefAddress net.IP, opts map[string]string) (*net.IPNet, map[string]string, error) {
+ logrus.Debugf("RequestAddress(%s, %v, %v)", poolID, prefAddress, opts)
+ k := SubnetKey{}
+ if err := k.FromString(poolID); err != nil {
+ return nil, nil, types.BadRequestErrorf("invalid pool id: %s", poolID)
+ }
+
+ if err := a.refresh(k.AddressSpace); err != nil {
+ return nil, nil, err
+ }
+
+ aSpace, err := a.getAddrSpace(k.AddressSpace)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ aSpace.Lock()
+ p, ok := aSpace.subnets[k]
+ if !ok {
+ aSpace.Unlock()
+ return nil, nil, types.NotFoundErrorf("cannot find address pool for poolID:%s", poolID)
+ }
+
+ if prefAddress != nil && !p.Pool.Contains(prefAddress) {
+ aSpace.Unlock()
+ return nil, nil, ipamapi.ErrIPOutOfRange
+ }
+
+ c := p
+ for c.Range != nil {
+ k = c.ParentKey
+ c = aSpace.subnets[k]
+ }
+ aSpace.Unlock()
+
+ bm, err := a.retrieveBitmask(k, c.Pool)
+ if err != nil {
+ return nil, nil, types.InternalErrorf("could not find bitmask in datastore for %s on address %v request from pool %s: %v",
+ k.String(), prefAddress, poolID, err)
+ }
+ ip, err := a.getAddress(p.Pool, bm, prefAddress, p.Range)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ return &net.IPNet{IP: ip, Mask: p.Pool.Mask}, nil, nil
+}
+
+// ReleaseAddress releases the address from the specified pool ID
+func (a *Allocator) ReleaseAddress(poolID string, address net.IP) error {
+ logrus.Debugf("ReleaseAddress(%s, %v)", poolID, address)
+ k := SubnetKey{}
+ if err := k.FromString(poolID); err != nil {
+ return types.BadRequestErrorf("invalid pool id: %s", poolID)
+ }
+
+ if err := a.refresh(k.AddressSpace); err != nil {
+ return err
+ }
+
+ aSpace, err := a.getAddrSpace(k.AddressSpace)
+ if err != nil {
+ return err
+ }
+
+ aSpace.Lock()
+ p, ok := aSpace.subnets[k]
+ if !ok {
+ aSpace.Unlock()
+ return types.NotFoundErrorf("cannot find address pool for poolID:%s", poolID)
+ }
+
+ if address == nil {
+ aSpace.Unlock()
+ return types.BadRequestErrorf("invalid address: nil")
+ }
+
+ if !p.Pool.Contains(address) {
+ aSpace.Unlock()
+ return ipamapi.ErrIPOutOfRange
+ }
+
+ c := p
+ for c.Range != nil {
+ k = c.ParentKey
+ c = aSpace.subnets[k]
+ }
+ aSpace.Unlock()
+
+ mask := p.Pool.Mask
+
+ h, err := types.GetHostPartIP(address, mask)
+ if err != nil {
+ return types.InternalErrorf("failed to release address %s: %v", address.String(), err)
+ }
+
+ bm, err := a.retrieveBitmask(k, c.Pool)
+ if err != nil {
+ return types.InternalErrorf("could not find bitmask in datastore for %s on address %v release from pool %s: %v",
+ k.String(), address, poolID, err)
+ }
+
+ return bm.Unset(ipToUint64(h))
+}
+
+func (a *Allocator) getAddress(nw *net.IPNet, bitmask *bitseq.Handle, prefAddress net.IP, ipr *AddressRange) (net.IP, error) {
+ var (
+ ordinal uint64
+ err error
+ base *net.IPNet
+ )
+
+ base = types.GetIPNetCopy(nw)
+
+ if bitmask.Unselected() <= 0 {
+ return nil, ipamapi.ErrNoAvailableIPs
+ }
+ if ipr == nil && prefAddress == nil {
+ ordinal, err = bitmask.SetAny()
+ } else if prefAddress != nil {
+ hostPart, e := types.GetHostPartIP(prefAddress, base.Mask)
+ if e != nil {
+ return nil, types.InternalErrorf("failed to allocate requested address %s: %v", prefAddress.String(), e)
+ }
+ ordinal = ipToUint64(types.GetMinimalIP(hostPart))
+ err = bitmask.Set(ordinal)
+ } else {
+ ordinal, err = bitmask.SetAnyInRange(ipr.Start, ipr.End)
+ }
+
+ switch err {
+ case nil:
+ // Convert IP ordinal for this subnet into IP address
+ return generateAddress(ordinal, base), nil
+ case bitseq.ErrBitAllocated:
+ return nil, ipamapi.ErrIPAlreadyAllocated
+ case bitseq.ErrNoBitAvailable:
+ return nil, ipamapi.ErrNoAvailableIPs
+ default:
+ return nil, err
+ }
+}
+
+// DumpDatabase dumps the internal info
+func (a *Allocator) DumpDatabase() string {
+ a.Lock()
+ aspaces := make(map[string]*addrSpace, len(a.addrSpaces))
+ orderedAS := make([]string, 0, len(a.addrSpaces))
+ for as, aSpace := range a.addrSpaces {
+ orderedAS = append(orderedAS, as)
+ aspaces[as] = aSpace
+ }
+ a.Unlock()
+
+ sort.Strings(orderedAS)
+
+ var s string
+ for _, as := range orderedAS {
+ aSpace := aspaces[as]
+ s = fmt.Sprintf("\n\n%s Config", as)
+ aSpace.Lock()
+ for k, config := range aSpace.subnets {
+ s = fmt.Sprintf("%s%s", s, fmt.Sprintf("\n%v: %v", k, config))
+ if config.Range == nil {
+ a.retrieveBitmask(k, config.Pool)
+ }
+ }
+ aSpace.Unlock()
+ }
+
+ s = fmt.Sprintf("%s\n\nBitmasks", s)
+ for k, bm := range a.addresses {
+ s = fmt.Sprintf("%s%s", s, fmt.Sprintf("\n%s: %s", k, bm))
+ }
+
+ return s
+}
+
+// IsBuiltIn returns true for builtin drivers
+func (a *Allocator) IsBuiltIn() bool {
+ return true
+}
diff --git a/vendor/github.com/docker/libnetwork/ipam/store.go b/vendor/github.com/docker/libnetwork/ipam/store.go
new file mode 100644
index 0000000..d05e1b7
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipam/store.go
@@ -0,0 +1,136 @@
+package ipam
+
+import (
+ "encoding/json"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/types"
+)
+
+// Key provides the Key to be used in KV Store
+func (aSpace *addrSpace) Key() []string {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+ return []string{aSpace.id}
+}
+
+// KeyPrefix returns the immediate parent key that can be used for tree walk
+func (aSpace *addrSpace) KeyPrefix() []string {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+ return []string{dsConfigKey}
+}
+
+// Value marshals the data to be stored in the KV store
+func (aSpace *addrSpace) Value() []byte {
+ b, err := json.Marshal(aSpace)
+ if err != nil {
+ logrus.Warnf("Failed to marshal ipam configured pools: %v", err)
+ return nil
+ }
+ return b
+}
+
+// SetValue unmarshalls the data from the KV store.
+func (aSpace *addrSpace) SetValue(value []byte) error {
+ rc := &addrSpace{subnets: make(map[SubnetKey]*PoolData)}
+ if err := json.Unmarshal(value, rc); err != nil {
+ return err
+ }
+ aSpace.subnets = rc.subnets
+ return nil
+}
+
+// Index returns the latest DB Index as seen by this object
+func (aSpace *addrSpace) Index() uint64 {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+ return aSpace.dbIndex
+}
+
+// SetIndex method allows the datastore to store the latest DB Index into this object
+func (aSpace *addrSpace) SetIndex(index uint64) {
+ aSpace.Lock()
+ aSpace.dbIndex = index
+ aSpace.dbExists = true
+ aSpace.Unlock()
+}
+
+// Exists method is true if this object has been stored in the DB.
+func (aSpace *addrSpace) Exists() bool {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+ return aSpace.dbExists
+}
+
+// Skip provides a way for a KV Object to avoid persisting it in the KV Store
+func (aSpace *addrSpace) Skip() bool {
+ return false
+}
+
+func (a *Allocator) getStore(as string) datastore.DataStore {
+ a.Lock()
+ defer a.Unlock()
+
+ if aSpace, ok := a.addrSpaces[as]; ok {
+ return aSpace.ds
+ }
+
+ return nil
+}
+
+func (a *Allocator) getAddressSpaceFromStore(as string) (*addrSpace, error) {
+ store := a.getStore(as)
+
+ // IPAM may not have a valid store. In such cases it is just in-memory state.
+ if store == nil {
+ return nil, nil
+ }
+
+ pc := &addrSpace{id: dsConfigKey + "/" + as, ds: store, alloc: a}
+ if err := store.GetObject(datastore.Key(pc.Key()...), pc); err != nil {
+ if err == datastore.ErrKeyNotFound {
+ return nil, nil
+ }
+
+ return nil, types.InternalErrorf("could not get pools config from store: %v", err)
+ }
+
+ return pc, nil
+}
+
+func (a *Allocator) writeToStore(aSpace *addrSpace) error {
+ store := aSpace.store()
+
+ // IPAM may not have a valid store. In such cases it is just in-memory state.
+ if store == nil {
+ return nil
+ }
+
+ err := store.PutObjectAtomic(aSpace)
+ if err == datastore.ErrKeyModified {
+ return types.RetryErrorf("failed to perform atomic write (%v). retry might fix the error", err)
+ }
+
+ return err
+}
+
+func (a *Allocator) deleteFromStore(aSpace *addrSpace) error {
+ store := aSpace.store()
+
+ // IPAM may not have a valid store. In such cases it is just in-memory state.
+ if store == nil {
+ return nil
+ }
+
+ return store.DeleteObjectAtomic(aSpace)
+}
+
+// DataScope method returns the storage scope of the datastore
+func (aSpace *addrSpace) DataScope() string {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+
+ return aSpace.scope
+}
diff --git a/vendor/github.com/docker/libnetwork/ipam/structures.go b/vendor/github.com/docker/libnetwork/ipam/structures.go
new file mode 100644
index 0000000..09a7769
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipam/structures.go
@@ -0,0 +1,362 @@
+package ipam
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+ "strings"
+ "sync"
+
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/types"
+)
+
+// SubnetKey is the pointer to the configured pools in each address space
+type SubnetKey struct {
+ AddressSpace string
+ Subnet string
+ ChildSubnet string
+}
+
+// PoolData contains the configured pool data
+type PoolData struct {
+ ParentKey SubnetKey
+ Pool *net.IPNet
+ Range *AddressRange `json:",omitempty"`
+ RefCount int
+}
+
+// addrSpace contains the pool configurations for the address space
+type addrSpace struct {
+ subnets map[SubnetKey]*PoolData
+ dbIndex uint64
+ dbExists bool
+ id string
+ scope string
+ ds datastore.DataStore
+ alloc *Allocator
+ sync.Mutex
+}
+
+// AddressRange specifies first and last ip ordinal which
+// identifies a range in a pool of addresses
+type AddressRange struct {
+ Sub *net.IPNet
+ Start, End uint64
+}
+
+// String returns the string form of the AddressRange object
+func (r *AddressRange) String() string {
+ return fmt.Sprintf("Sub: %s, range [%d, %d]", r.Sub, r.Start, r.End)
+}
+
+// MarshalJSON returns the JSON encoding of the Range object
+func (r *AddressRange) MarshalJSON() ([]byte, error) {
+ m := map[string]interface{}{
+ "Sub": r.Sub.String(),
+ "Start": r.Start,
+ "End": r.End,
+ }
+ return json.Marshal(m)
+}
+
+// UnmarshalJSON decodes data into the Range object
+func (r *AddressRange) UnmarshalJSON(data []byte) error {
+ m := map[string]interface{}{}
+ err := json.Unmarshal(data, &m)
+ if err != nil {
+ return err
+ }
+ if r.Sub, err = types.ParseCIDR(m["Sub"].(string)); err != nil {
+ return err
+ }
+ r.Start = uint64(m["Start"].(float64))
+ r.End = uint64(m["End"].(float64))
+ return nil
+}
+
+// String returns the string form of the SubnetKey object
+func (s *SubnetKey) String() string {
+ k := fmt.Sprintf("%s/%s", s.AddressSpace, s.Subnet)
+ if s.ChildSubnet != "" {
+ k = fmt.Sprintf("%s/%s", k, s.ChildSubnet)
+ }
+ return k
+}
+
+// FromString populates the SubnetKey object reading it from string
+func (s *SubnetKey) FromString(str string) error {
+ if str == "" || !strings.Contains(str, "/") {
+ return types.BadRequestErrorf("invalid string form for subnetkey: %s", str)
+ }
+
+ p := strings.Split(str, "/")
+ if len(p) != 3 && len(p) != 5 {
+ return types.BadRequestErrorf("invalid string form for subnetkey: %s", str)
+ }
+ s.AddressSpace = p[0]
+ s.Subnet = fmt.Sprintf("%s/%s", p[1], p[2])
+ if len(p) == 5 {
+ s.ChildSubnet = fmt.Sprintf("%s/%s", p[3], p[4])
+ }
+
+ return nil
+}
+
+// String returns the string form of the PoolData object
+func (p *PoolData) String() string {
+ return fmt.Sprintf("ParentKey: %s, Pool: %s, Range: %s, RefCount: %d",
+ p.ParentKey.String(), p.Pool.String(), p.Range, p.RefCount)
+}
+
+// MarshalJSON returns the JSON encoding of the PoolData object
+func (p *PoolData) MarshalJSON() ([]byte, error) {
+ m := map[string]interface{}{
+ "ParentKey": p.ParentKey,
+ "RefCount": p.RefCount,
+ }
+ if p.Pool != nil {
+ m["Pool"] = p.Pool.String()
+ }
+ if p.Range != nil {
+ m["Range"] = p.Range
+ }
+ return json.Marshal(m)
+}
+
+// UnmarshalJSON decodes data into the PoolData object
+func (p *PoolData) UnmarshalJSON(data []byte) error {
+ var (
+ err error
+ t struct {
+ ParentKey SubnetKey
+ Pool string
+ Range *AddressRange `json:",omitempty"`
+ RefCount int
+ }
+ )
+
+ if err = json.Unmarshal(data, &t); err != nil {
+ return err
+ }
+
+ p.ParentKey = t.ParentKey
+ p.Range = t.Range
+ p.RefCount = t.RefCount
+ if t.Pool != "" {
+ if p.Pool, err = types.ParseCIDR(t.Pool); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+// MarshalJSON returns the JSON encoding of the addrSpace object
+func (aSpace *addrSpace) MarshalJSON() ([]byte, error) {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+
+ m := map[string]interface{}{
+ "Scope": string(aSpace.scope),
+ }
+
+ if aSpace.subnets != nil {
+ s := map[string]*PoolData{}
+ for k, v := range aSpace.subnets {
+ s[k.String()] = v
+ }
+ m["Subnets"] = s
+ }
+
+ return json.Marshal(m)
+}
+
+// UnmarshalJSON decodes data into the addrSpace object
+func (aSpace *addrSpace) UnmarshalJSON(data []byte) error {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+
+ m := map[string]interface{}{}
+ err := json.Unmarshal(data, &m)
+ if err != nil {
+ return err
+ }
+
+ aSpace.scope = datastore.LocalScope
+ s := m["Scope"].(string)
+ if s == string(datastore.GlobalScope) {
+ aSpace.scope = datastore.GlobalScope
+ }
+
+ if v, ok := m["Subnets"]; ok {
+ sb, _ := json.Marshal(v)
+ var s map[string]*PoolData
+ err := json.Unmarshal(sb, &s)
+ if err != nil {
+ return err
+ }
+ for ks, v := range s {
+ k := SubnetKey{}
+ k.FromString(ks)
+ aSpace.subnets[k] = v
+ }
+ }
+
+ return nil
+}
+
+// CopyTo deep copies the pool data to the destination pooldata
+func (p *PoolData) CopyTo(dstP *PoolData) error {
+ dstP.ParentKey = p.ParentKey
+ dstP.Pool = types.GetIPNetCopy(p.Pool)
+
+ if p.Range != nil {
+ dstP.Range = &AddressRange{}
+ dstP.Range.Sub = types.GetIPNetCopy(p.Range.Sub)
+ dstP.Range.Start = p.Range.Start
+ dstP.Range.End = p.Range.End
+ }
+
+ dstP.RefCount = p.RefCount
+ return nil
+}
+
+func (aSpace *addrSpace) CopyTo(o datastore.KVObject) error {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+
+ dstAspace := o.(*addrSpace)
+
+ dstAspace.id = aSpace.id
+ dstAspace.ds = aSpace.ds
+ dstAspace.alloc = aSpace.alloc
+ dstAspace.scope = aSpace.scope
+ dstAspace.dbIndex = aSpace.dbIndex
+ dstAspace.dbExists = aSpace.dbExists
+
+ dstAspace.subnets = make(map[SubnetKey]*PoolData)
+ for k, v := range aSpace.subnets {
+ dstAspace.subnets[k] = &PoolData{}
+ v.CopyTo(dstAspace.subnets[k])
+ }
+
+ return nil
+}
+
+func (aSpace *addrSpace) New() datastore.KVObject {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+
+ return &addrSpace{
+ id: aSpace.id,
+ ds: aSpace.ds,
+ alloc: aSpace.alloc,
+ scope: aSpace.scope,
+ }
+}
+
+func (aSpace *addrSpace) updatePoolDBOnAdd(k SubnetKey, nw *net.IPNet, ipr *AddressRange, pdf bool) (func() error, error) {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+
+ // Check if already allocated
+ if p, ok := aSpace.subnets[k]; ok {
+ if pdf {
+ return nil, types.InternalMaskableErrorf("predefined pool %s is already reserved", nw)
+ }
+ aSpace.incRefCount(p, 1)
+ return func() error { return nil }, nil
+ }
+
+ // If master pool, check for overlap
+ if ipr == nil {
+ if aSpace.contains(k.AddressSpace, nw) {
+ return nil, ipamapi.ErrPoolOverlap
+ }
+ // This is a new master pool, add it along with corresponding bitmask
+ aSpace.subnets[k] = &PoolData{Pool: nw, RefCount: 1}
+ return func() error { return aSpace.alloc.insertBitMask(k, nw) }, nil
+ }
+
+ // This is a new non-master pool
+ p := &PoolData{
+ ParentKey: SubnetKey{AddressSpace: k.AddressSpace, Subnet: k.Subnet},
+ Pool: nw,
+ Range: ipr,
+ RefCount: 1,
+ }
+ aSpace.subnets[k] = p
+
+ // Look for parent pool
+ pp, ok := aSpace.subnets[p.ParentKey]
+ if ok {
+ aSpace.incRefCount(pp, 1)
+ return func() error { return nil }, nil
+ }
+
+ // Parent pool does not exist, add it along with corresponding bitmask
+ aSpace.subnets[p.ParentKey] = &PoolData{Pool: nw, RefCount: 1}
+ return func() error { return aSpace.alloc.insertBitMask(p.ParentKey, nw) }, nil
+}
+
+func (aSpace *addrSpace) updatePoolDBOnRemoval(k SubnetKey) (func() error, error) {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+
+ p, ok := aSpace.subnets[k]
+ if !ok {
+ return nil, ipamapi.ErrBadPool
+ }
+
+ aSpace.incRefCount(p, -1)
+
+ c := p
+ for ok {
+ if c.RefCount == 0 {
+ delete(aSpace.subnets, k)
+ if c.Range == nil {
+ return func() error {
+ bm, err := aSpace.alloc.retrieveBitmask(k, c.Pool)
+ if err != nil {
+ return types.InternalErrorf("could not find bitmask in datastore for pool %s removal: %v", k.String(), err)
+ }
+ return bm.Destroy()
+ }, nil
+ }
+ }
+ k = c.ParentKey
+ c, ok = aSpace.subnets[k]
+ }
+
+ return func() error { return nil }, nil
+}
+
+func (aSpace *addrSpace) incRefCount(p *PoolData, delta int) {
+ c := p
+ ok := true
+ for ok {
+ c.RefCount += delta
+ c, ok = aSpace.subnets[c.ParentKey]
+ }
+}
+
+// Checks whether the passed subnet is a superset or subset of any of the subset in this config db
+func (aSpace *addrSpace) contains(space string, nw *net.IPNet) bool {
+ for k, v := range aSpace.subnets {
+ if space == k.AddressSpace && k.ChildSubnet == "" {
+ if nw.Contains(v.Pool.IP) || v.Pool.Contains(nw.IP) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func (aSpace *addrSpace) store() datastore.DataStore {
+ aSpace.Lock()
+ defer aSpace.Unlock()
+
+ return aSpace.ds
+}
diff --git a/vendor/github.com/docker/libnetwork/ipam/utils.go b/vendor/github.com/docker/libnetwork/ipam/utils.go
new file mode 100644
index 0000000..5117c55
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipam/utils.go
@@ -0,0 +1,81 @@
+package ipam
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/types"
+)
+
+type ipVersion int
+
+const (
+ v4 = 4
+ v6 = 6
+)
+
+func getAddressRange(pool string, masterNw *net.IPNet) (*AddressRange, error) {
+ ip, nw, err := net.ParseCIDR(pool)
+ if err != nil {
+ return nil, ipamapi.ErrInvalidSubPool
+ }
+ lIP, e := types.GetHostPartIP(nw.IP, masterNw.Mask)
+ if e != nil {
+ return nil, fmt.Errorf("failed to compute range's lowest ip address: %v", e)
+ }
+ bIP, e := types.GetBroadcastIP(nw.IP, nw.Mask)
+ if e != nil {
+ return nil, fmt.Errorf("failed to compute range's broadcast ip address: %v", e)
+ }
+ hIP, e := types.GetHostPartIP(bIP, masterNw.Mask)
+ if e != nil {
+ return nil, fmt.Errorf("failed to compute range's highest ip address: %v", e)
+ }
+ nw.IP = ip
+ return &AddressRange{nw, ipToUint64(types.GetMinimalIP(lIP)), ipToUint64(types.GetMinimalIP(hIP))}, nil
+}
+
+// It generates the ip address in the passed subnet specified by
+// the passed host address ordinal
+func generateAddress(ordinal uint64, network *net.IPNet) net.IP {
+ var address [16]byte
+
+ // Get network portion of IP
+ if getAddressVersion(network.IP) == v4 {
+ copy(address[:], network.IP.To4())
+ } else {
+ copy(address[:], network.IP)
+ }
+
+ end := len(network.Mask)
+ addIntToIP(address[:end], ordinal)
+
+ return net.IP(address[:end])
+}
+
+func getAddressVersion(ip net.IP) ipVersion {
+ if ip.To4() == nil {
+ return v6
+ }
+ return v4
+}
+
+// Adds the ordinal IP to the current array
+// 192.168.0.0 + 53 => 192.168.0.53
+func addIntToIP(array []byte, ordinal uint64) {
+ for i := len(array) - 1; i >= 0; i-- {
+ array[i] |= (byte)(ordinal & 0xff)
+ ordinal >>= 8
+ }
+}
+
+// Convert an ordinal to the respective IP address
+func ipToUint64(ip []byte) (value uint64) {
+ cip := types.GetMinimalIP(ip)
+ for i := 0; i < len(cip); i++ {
+ j := len(cip) - 1 - i
+ value += uint64(cip[i]) << uint(j*8)
+ }
+ return value
+}
diff --git a/vendor/github.com/docker/libnetwork/ipamapi/contract.go b/vendor/github.com/docker/libnetwork/ipamapi/contract.go
new file mode 100644
index 0000000..7f96786
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipamapi/contract.go
@@ -0,0 +1,96 @@
+// Package ipamapi specifies the contract the IPAM service (built-in or remote) needs to satisfy.
+package ipamapi
+
+import (
+ "net"
+
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/types"
+)
+
+/********************
+ * IPAM plugin types
+ ********************/
+
+const (
+ // DefaultIPAM is the name of the built-in default ipam driver
+ DefaultIPAM = "default"
+ // NullIPAM is the name of the built-in null ipam driver
+ NullIPAM = "null"
+ // PluginEndpointType represents the Endpoint Type used by Plugin system
+ PluginEndpointType = "IpamDriver"
+ // RequestAddressType represents the Address Type used when requesting an address
+ RequestAddressType = "RequestAddressType"
+)
+
+// Callback provides a Callback interface for registering an IPAM instance into LibNetwork
+type Callback interface {
+ // GetPluginGetter returns the pluginv2 getter.
+ GetPluginGetter() plugingetter.PluginGetter
+ // RegisterIpamDriver provides a way for Remote drivers to dynamically register with libnetwork
+ RegisterIpamDriver(name string, driver Ipam) error
+ // RegisterIpamDriverWithCapabilities provides a way for Remote drivers to dynamically register with libnetwork and specify capabilities
+ RegisterIpamDriverWithCapabilities(name string, driver Ipam, capability *Capability) error
+}
+
+/**************
+ * IPAM Errors
+ **************/
+
+// Well-known errors returned by IPAM
+var (
+ ErrIpamInternalError = types.InternalErrorf("IPAM Internal Error")
+ ErrInvalidAddressSpace = types.BadRequestErrorf("Invalid Address Space")
+ ErrInvalidPool = types.BadRequestErrorf("Invalid Address Pool")
+ ErrInvalidSubPool = types.BadRequestErrorf("Invalid Address SubPool")
+ ErrInvalidRequest = types.BadRequestErrorf("Invalid Request")
+ ErrPoolNotFound = types.BadRequestErrorf("Address Pool not found")
+ ErrOverlapPool = types.ForbiddenErrorf("Address pool overlaps with existing pool on this address space")
+ ErrNoAvailablePool = types.NoServiceErrorf("No available pool")
+ ErrNoAvailableIPs = types.NoServiceErrorf("No available addresses on this pool")
+ ErrNoIPReturned = types.NoServiceErrorf("No address returned")
+ ErrIPAlreadyAllocated = types.ForbiddenErrorf("Address already in use")
+ ErrIPOutOfRange = types.BadRequestErrorf("Requested address is out of range")
+ ErrPoolOverlap = types.ForbiddenErrorf("Pool overlaps with other one on this address space")
+ ErrBadPool = types.BadRequestErrorf("Address space does not contain specified address pool")
+)
+
+/*******************************
+ * IPAM Service Interface
+ *******************************/
+
+// Ipam represents the interface the IPAM service plugins must implement
+// in order to allow injection/modification of IPAM database.
+type Ipam interface {
+ discoverapi.Discover
+
+ // GetDefaultAddressSpaces returns the default local and global address spaces for this ipam
+ GetDefaultAddressSpaces() (string, string, error)
+ // RequestPool returns an address pool along with its unique id. Address space is a mandatory field
+ // which denotes a set of non-overlapping pools. pool describes the pool of addresses in CIDR notation.
+ // subpool indicates a smaller range of addresses from the pool, for now it is specified in CIDR notation.
+ // Both pool and subpool are non mandatory fields. When they are not specified, Ipam driver may choose to
+ // return a self chosen pool for this request. In such case the v6 flag needs to be set appropriately so
+ // that the driver would return the expected ip version pool.
+ RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error)
+ // ReleasePool releases the address pool identified by the passed id
+ ReleasePool(poolID string) error
+ // Request address from the specified pool ID. Input options or required IP can be passed.
+ RequestAddress(string, net.IP, map[string]string) (*net.IPNet, map[string]string, error)
+ // Release the address from the specified pool ID
+ ReleaseAddress(string, net.IP) error
+
+ //IsBuiltIn returns true if it is a built-in driver.
+ IsBuiltIn() bool
+}
+
+// Capability represents the requirements and capabilities of the IPAM driver
+type Capability struct {
+ // Whether on address request, libnetwork must
+ // specify the endpoint MAC address
+ RequiresMACAddress bool
+ // Whether of daemon start, libnetwork must replay the pool
+ // request and the address request for current local networks
+ RequiresRequestReplay bool
+}
diff --git a/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_unix.go b/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_unix.go
new file mode 100644
index 0000000..321448a
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_unix.go
@@ -0,0 +1,43 @@
+// +build linux freebsd solaris darwin
+
+package builtin
+
+import (
+ "errors"
+
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/ipam"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/ipamutils"
+)
+
+// Init registers the built-in ipam service with libnetwork
+func Init(ic ipamapi.Callback, l, g interface{}) error {
+ var (
+ ok bool
+ localDs, globalDs datastore.DataStore
+ )
+
+ if l != nil {
+ if localDs, ok = l.(datastore.DataStore); !ok {
+ return errors.New("incorrect local datastore passed to built-in ipam init")
+ }
+ }
+
+ if g != nil {
+ if globalDs, ok = g.(datastore.DataStore); !ok {
+ return errors.New("incorrect global datastore passed to built-in ipam init")
+ }
+ }
+
+ ipamutils.InitNetworks()
+
+ a, err := ipam.NewAllocator(localDs, globalDs)
+ if err != nil {
+ return err
+ }
+
+ cps := &ipamapi.Capability{RequiresRequestReplay: true}
+
+ return ic.RegisterIpamDriverWithCapabilities(ipamapi.DefaultIPAM, a, cps)
+}
diff --git a/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_windows.go b/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_windows.go
new file mode 100644
index 0000000..7805e6a
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipams/builtin/builtin_windows.go
@@ -0,0 +1,57 @@
+// +build windows
+
+package builtin
+
+import (
+ "errors"
+
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/ipam"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/ipamutils"
+
+ windowsipam "github.com/docker/libnetwork/ipams/windowsipam"
+)
+
+// InitDockerDefault registers the built-in ipam service with libnetwork
+func InitDockerDefault(ic ipamapi.Callback, l, g interface{}) error {
+ var (
+ ok bool
+ localDs, globalDs datastore.DataStore
+ )
+
+ if l != nil {
+ if localDs, ok = l.(datastore.DataStore); !ok {
+ return errors.New("incorrect local datastore passed to built-in ipam init")
+ }
+ }
+
+ if g != nil {
+ if globalDs, ok = g.(datastore.DataStore); !ok {
+ return errors.New("incorrect global datastore passed to built-in ipam init")
+ }
+ }
+
+ ipamutils.InitNetworks()
+
+ a, err := ipam.NewAllocator(localDs, globalDs)
+ if err != nil {
+ return err
+ }
+
+ cps := &ipamapi.Capability{RequiresRequestReplay: true}
+
+ return ic.RegisterIpamDriverWithCapabilities(ipamapi.DefaultIPAM, a, cps)
+}
+
+// Init registers the built-in ipam service with libnetwork
+func Init(ic ipamapi.Callback, l, g interface{}) error {
+ initFunc := windowsipam.GetInit(windowsipam.DefaultIPAM)
+
+ err := InitDockerDefault(ic, l, g)
+ if err != nil {
+ return err
+ }
+
+ return initFunc(ic, l, g)
+}
diff --git a/vendor/github.com/docker/libnetwork/ipams/null/null.go b/vendor/github.com/docker/libnetwork/ipams/null/null.go
new file mode 100644
index 0000000..339b530
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipams/null/null.go
@@ -0,0 +1,75 @@
+// Package null implements the null ipam driver. Null ipam driver satisfies ipamapi contract,
+// but does not effectively reserve/allocate any address pool or address
+package null
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/types"
+)
+
+var (
+ defaultAS = "null"
+ defaultPool, _ = types.ParseCIDR("0.0.0.0/0")
+ defaultPoolID = fmt.Sprintf("%s/%s", defaultAS, defaultPool.String())
+)
+
+type allocator struct{}
+
+func (a *allocator) GetDefaultAddressSpaces() (string, string, error) {
+ return defaultAS, defaultAS, nil
+}
+
+func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) {
+ if addressSpace != defaultAS {
+ return "", nil, nil, types.BadRequestErrorf("unknown address space: %s", addressSpace)
+ }
+ if pool != "" {
+ return "", nil, nil, types.BadRequestErrorf("null ipam driver does not handle specific address pool requests")
+ }
+ if subPool != "" {
+ return "", nil, nil, types.BadRequestErrorf("null ipam driver does not handle specific address subpool requests")
+ }
+ if v6 {
+ return "", nil, nil, types.BadRequestErrorf("null ipam driver does not handle IPv6 address pool pool requests")
+ }
+ return defaultPoolID, defaultPool, nil, nil
+}
+
+func (a *allocator) ReleasePool(poolID string) error {
+ return nil
+}
+
+func (a *allocator) RequestAddress(poolID string, ip net.IP, opts map[string]string) (*net.IPNet, map[string]string, error) {
+ if poolID != defaultPoolID {
+ return nil, nil, types.BadRequestErrorf("unknown pool id: %s", poolID)
+ }
+ return nil, nil, nil
+}
+
+func (a *allocator) ReleaseAddress(poolID string, ip net.IP) error {
+ if poolID != defaultPoolID {
+ return types.BadRequestErrorf("unknown pool id: %s", poolID)
+ }
+ return nil
+}
+
+func (a *allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+func (a *allocator) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+func (a *allocator) IsBuiltIn() bool {
+ return true
+}
+
+// Init registers a remote ipam when its plugin is activated
+func Init(ic ipamapi.Callback, l, g interface{}) error {
+ return ic.RegisterIpamDriver(ipamapi.NullIPAM, &allocator{})
+}
diff --git a/vendor/github.com/docker/libnetwork/ipams/remote/api/api.go b/vendor/github.com/docker/libnetwork/ipams/remote/api/api.go
new file mode 100644
index 0000000..543c99b
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipams/remote/api/api.go
@@ -0,0 +1,94 @@
+// Package api defines the data structure to be used in the request/response
+// messages between libnetwork and the remote ipam plugin
+package api
+
+import "github.com/docker/libnetwork/ipamapi"
+
+// Response is the basic response structure used in all responses
+type Response struct {
+ Error string
+}
+
+// IsSuccess returns whether the plugin response is successful
+func (r *Response) IsSuccess() bool {
+ return r.Error == ""
+}
+
+// GetError returns the error from the response, if any.
+func (r *Response) GetError() string {
+ return r.Error
+}
+
+// GetCapabilityResponse is the response of GetCapability request
+type GetCapabilityResponse struct {
+ Response
+ RequiresMACAddress bool
+ RequiresRequestReplay bool
+}
+
+// ToCapability converts the capability response into the internal ipam driver capability structure
+func (capRes GetCapabilityResponse) ToCapability() *ipamapi.Capability {
+ return &ipamapi.Capability{
+ RequiresMACAddress: capRes.RequiresMACAddress,
+ RequiresRequestReplay: capRes.RequiresRequestReplay,
+ }
+}
+
+// GetAddressSpacesResponse is the response to the ``get default address spaces`` request message
+type GetAddressSpacesResponse struct {
+ Response
+ LocalDefaultAddressSpace string
+ GlobalDefaultAddressSpace string
+}
+
+// RequestPoolRequest represents the expected data in a ``request address pool`` request message
+type RequestPoolRequest struct {
+ AddressSpace string
+ Pool string
+ SubPool string
+ Options map[string]string
+ V6 bool
+}
+
+// RequestPoolResponse represents the response message to a ``request address pool`` request
+type RequestPoolResponse struct {
+ Response
+ PoolID string
+ Pool string // CIDR format
+ Data map[string]string
+}
+
+// ReleasePoolRequest represents the expected data in a ``release address pool`` request message
+type ReleasePoolRequest struct {
+ PoolID string
+}
+
+// ReleasePoolResponse represents the response message to a ``release address pool`` request
+type ReleasePoolResponse struct {
+ Response
+}
+
+// RequestAddressRequest represents the expected data in a ``request address`` request message
+type RequestAddressRequest struct {
+ PoolID string
+ Address string
+ Options map[string]string
+}
+
+// RequestAddressResponse represents the expected data in the response message to a ``request address`` request
+type RequestAddressResponse struct {
+ Response
+ Address string // in CIDR format
+ Data map[string]string
+}
+
+// ReleaseAddressRequest represents the expected data in a ``release address`` request message
+type ReleaseAddressRequest struct {
+ PoolID string
+ Address string
+}
+
+// ReleaseAddressResponse represents the response message to a ``release address`` request
+type ReleaseAddressResponse struct {
+ Response
+}
diff --git a/vendor/github.com/docker/libnetwork/ipams/remote/remote.go b/vendor/github.com/docker/libnetwork/ipams/remote/remote.go
new file mode 100644
index 0000000..d2e2b4f
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipams/remote/remote.go
@@ -0,0 +1,155 @@
+package remote
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/plugins"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/ipams/remote/api"
+ "github.com/docker/libnetwork/types"
+)
+
+type allocator struct {
+ endpoint *plugins.Client
+ name string
+}
+
+// PluginResponse is the interface for the plugin request responses
+type PluginResponse interface {
+ IsSuccess() bool
+ GetError() string
+}
+
+func newAllocator(name string, client *plugins.Client) ipamapi.Ipam {
+ a := &allocator{name: name, endpoint: client}
+ return a
+}
+
+// Init registers a remote ipam when its plugin is activated
+func Init(cb ipamapi.Callback, l, g interface{}) error {
+
+ newPluginHandler := func(name string, client *plugins.Client) {
+ a := newAllocator(name, client)
+ if cps, err := a.(*allocator).getCapabilities(); err == nil {
+ if err := cb.RegisterIpamDriverWithCapabilities(name, a, cps); err != nil {
+ logrus.Errorf("error registering remote ipam driver %s due to %v", name, err)
+ }
+ } else {
+ logrus.Infof("remote ipam driver %s does not support capabilities", name)
+ logrus.Debug(err)
+ if err := cb.RegisterIpamDriver(name, a); err != nil {
+ logrus.Errorf("error registering remote ipam driver %s due to %v", name, err)
+ }
+ }
+ }
+
+ // Unit test code is unaware of a true PluginStore. So we fall back to v1 plugins.
+ handleFunc := plugins.Handle
+ if pg := cb.GetPluginGetter(); pg != nil {
+ handleFunc = pg.Handle
+ activePlugins := pg.GetAllManagedPluginsByCap(ipamapi.PluginEndpointType)
+ for _, ap := range activePlugins {
+ newPluginHandler(ap.Name(), ap.Client())
+ }
+ }
+ handleFunc(ipamapi.PluginEndpointType, newPluginHandler)
+ return nil
+}
+
+func (a *allocator) call(methodName string, arg interface{}, retVal PluginResponse) error {
+ method := ipamapi.PluginEndpointType + "." + methodName
+ err := a.endpoint.Call(method, arg, retVal)
+ if err != nil {
+ return err
+ }
+ if !retVal.IsSuccess() {
+ return fmt.Errorf("remote: %s", retVal.GetError())
+ }
+ return nil
+}
+
+func (a *allocator) getCapabilities() (*ipamapi.Capability, error) {
+ var res api.GetCapabilityResponse
+ if err := a.call("GetCapabilities", nil, &res); err != nil {
+ return nil, err
+ }
+ return res.ToCapability(), nil
+}
+
+// GetDefaultAddressSpaces returns the local and global default address spaces
+func (a *allocator) GetDefaultAddressSpaces() (string, string, error) {
+ res := &api.GetAddressSpacesResponse{}
+ if err := a.call("GetDefaultAddressSpaces", nil, res); err != nil {
+ return "", "", err
+ }
+ return res.LocalDefaultAddressSpace, res.GlobalDefaultAddressSpace, nil
+}
+
+// RequestPool requests an address pool in the specified address space
+func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) {
+ req := &api.RequestPoolRequest{AddressSpace: addressSpace, Pool: pool, SubPool: subPool, Options: options, V6: v6}
+ res := &api.RequestPoolResponse{}
+ if err := a.call("RequestPool", req, res); err != nil {
+ return "", nil, nil, err
+ }
+ retPool, err := types.ParseCIDR(res.Pool)
+ return res.PoolID, retPool, res.Data, err
+}
+
+// ReleasePool removes an address pool from the specified address space
+func (a *allocator) ReleasePool(poolID string) error {
+ req := &api.ReleasePoolRequest{PoolID: poolID}
+ res := &api.ReleasePoolResponse{}
+ return a.call("ReleasePool", req, res)
+}
+
+// RequestAddress requests an address from the address pool
+func (a *allocator) RequestAddress(poolID string, address net.IP, options map[string]string) (*net.IPNet, map[string]string, error) {
+ var (
+ prefAddress string
+ retAddress *net.IPNet
+ err error
+ )
+ if address != nil {
+ prefAddress = address.String()
+ }
+ req := &api.RequestAddressRequest{PoolID: poolID, Address: prefAddress, Options: options}
+ res := &api.RequestAddressResponse{}
+ if err := a.call("RequestAddress", req, res); err != nil {
+ return nil, nil, err
+ }
+ if res.Address != "" {
+ retAddress, err = types.ParseCIDR(res.Address)
+ } else {
+ return nil, nil, ipamapi.ErrNoIPReturned
+ }
+ return retAddress, res.Data, err
+}
+
+// ReleaseAddress releases the address from the specified address pool
+func (a *allocator) ReleaseAddress(poolID string, address net.IP) error {
+ var relAddress string
+ if address != nil {
+ relAddress = address.String()
+ }
+ req := &api.ReleaseAddressRequest{PoolID: poolID, Address: relAddress}
+ res := &api.ReleaseAddressResponse{}
+ return a.call("ReleaseAddress", req, res)
+}
+
+// DiscoverNew is a notification for a new discovery event, such as a new global datastore
+func (a *allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+// DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
+func (a *allocator) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+func (a *allocator) IsBuiltIn() bool {
+ return false
+}
diff --git a/vendor/github.com/docker/libnetwork/ipams/windowsipam/windowsipam.go b/vendor/github.com/docker/libnetwork/ipams/windowsipam/windowsipam.go
new file mode 100644
index 0000000..6b124d4
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipams/windowsipam/windowsipam.go
@@ -0,0 +1,107 @@
+package windowsipam
+
+import (
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/discoverapi"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ localAddressSpace = "LocalDefault"
+ globalAddressSpace = "GlobalDefault"
+)
+
+// DefaultIPAM defines the default ipam-driver for local-scoped windows networks
+const DefaultIPAM = "windows"
+
+var (
+ defaultPool, _ = types.ParseCIDR("0.0.0.0/0")
+)
+
+type allocator struct {
+}
+
+// GetInit registers the built-in ipam service with libnetwork
+func GetInit(ipamName string) func(ic ipamapi.Callback, l, g interface{}) error {
+ return func(ic ipamapi.Callback, l, g interface{}) error {
+ return ic.RegisterIpamDriver(ipamName, &allocator{})
+ }
+}
+
+func (a *allocator) GetDefaultAddressSpaces() (string, string, error) {
+ return localAddressSpace, globalAddressSpace, nil
+}
+
+// RequestPool returns an address pool along with its unique id. This is a null ipam driver. It allocates the
+// subnet user asked and does not validate anything. Doesn't support subpool allocation
+func (a *allocator) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) {
+ logrus.Debugf("RequestPool(%s, %s, %s, %v, %t)", addressSpace, pool, subPool, options, v6)
+ if subPool != "" || v6 {
+ return "", nil, nil, types.InternalErrorf("This request is not supported by null ipam driver")
+ }
+
+ var ipNet *net.IPNet
+ var err error
+
+ if pool != "" {
+ _, ipNet, err = net.ParseCIDR(pool)
+ if err != nil {
+ return "", nil, nil, err
+ }
+ } else {
+ ipNet = defaultPool
+ }
+
+ return ipNet.String(), ipNet, nil, nil
+}
+
+// ReleasePool releases the address pool - always succeeds
+func (a *allocator) ReleasePool(poolID string) error {
+ logrus.Debugf("ReleasePool(%s)", poolID)
+ return nil
+}
+
+// RequestAddress returns an address from the specified pool ID.
+// Always allocate the 0.0.0.0/32 ip if no preferred address was specified
+func (a *allocator) RequestAddress(poolID string, prefAddress net.IP, opts map[string]string) (*net.IPNet, map[string]string, error) {
+ logrus.Debugf("RequestAddress(%s, %v, %v)", poolID, prefAddress, opts)
+ _, ipNet, err := net.ParseCIDR(poolID)
+
+ if err != nil {
+ return nil, nil, err
+ }
+
+ // TODO Windows: Remove this once the bug in docker daemon is fixed
+ // that causes it to throw an exception on nil gateway
+ if prefAddress != nil {
+ return &net.IPNet{IP: prefAddress, Mask: ipNet.Mask}, nil, nil
+ } else if opts[ipamapi.RequestAddressType] == netlabel.Gateway {
+ return ipNet, nil, nil
+ } else {
+ return nil, nil, nil
+ }
+}
+
+// ReleaseAddress releases the address - always succeeds
+func (a *allocator) ReleaseAddress(poolID string, address net.IP) error {
+ logrus.Debugf("ReleaseAddress(%s, %v)", poolID, address)
+ return nil
+}
+
+// DiscoverNew informs the allocator about a new global scope datastore
+func (a *allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+// DiscoverDelete is a notification of no interest for the allocator
+func (a *allocator) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
+ return nil
+}
+
+func (a *allocator) IsBuiltIn() bool {
+ return true
+}
diff --git a/vendor/github.com/docker/libnetwork/ipamutils/utils.go b/vendor/github.com/docker/libnetwork/ipamutils/utils.go
new file mode 100644
index 0000000..bca4e9e
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipamutils/utils.go
@@ -0,0 +1,50 @@
+// Package ipamutils provides utility functions for ipam management
+package ipamutils
+
+import (
+ "net"
+ "sync"
+)
+
+var (
+ // PredefinedBroadNetworks contains a list of 31 IPv4 private networks with host size 16 and 12
+ // (172.17-31.x.x/16, 192.168.x.x/20) which do not overlap with the networks in `PredefinedGranularNetworks`
+ PredefinedBroadNetworks []*net.IPNet
+ // PredefinedGranularNetworks contains a list of 64K IPv4 private networks with host size 8
+ // (10.x.x.x/24) which do not overlap with the networks in `PredefinedBroadNetworks`
+ PredefinedGranularNetworks []*net.IPNet
+
+ initNetworksOnce sync.Once
+)
+
+// InitNetworks initializes the pre-defined networks used by the built-in IP allocator
+func InitNetworks() {
+ initNetworksOnce.Do(func() {
+ PredefinedBroadNetworks = initBroadPredefinedNetworks()
+ PredefinedGranularNetworks = initGranularPredefinedNetworks()
+ })
+}
+
+func initBroadPredefinedNetworks() []*net.IPNet {
+ pl := make([]*net.IPNet, 0, 31)
+ mask := []byte{255, 255, 0, 0}
+ for i := 17; i < 32; i++ {
+ pl = append(pl, &net.IPNet{IP: []byte{172, byte(i), 0, 0}, Mask: mask})
+ }
+ mask20 := []byte{255, 255, 240, 0}
+ for i := 0; i < 16; i++ {
+ pl = append(pl, &net.IPNet{IP: []byte{192, 168, byte(i << 4), 0}, Mask: mask20})
+ }
+ return pl
+}
+
+func initGranularPredefinedNetworks() []*net.IPNet {
+ pl := make([]*net.IPNet, 0, 256*256)
+ mask := []byte{255, 255, 255, 0}
+ for i := 0; i < 256; i++ {
+ for j := 0; j < 256; j++ {
+ pl = append(pl, &net.IPNet{IP: []byte{10, byte(i), byte(j), 0}, Mask: mask})
+ }
+ }
+ return pl
+}
diff --git a/vendor/github.com/docker/libnetwork/iptables/conntrack.go b/vendor/github.com/docker/libnetwork/iptables/conntrack.go
new file mode 100644
index 0000000..5731c53
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/iptables/conntrack.go
@@ -0,0 +1,59 @@
+package iptables
+
+import (
+ "errors"
+ "net"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/vishvananda/netlink"
+)
+
+var (
+ // ErrConntrackNotConfigurable means that conntrack module is not loaded or does not have the netlink module loaded
+ ErrConntrackNotConfigurable = errors.New("conntrack is not available")
+)
+
+// IsConntrackProgrammable returns true if the handle supports the NETLINK_NETFILTER and the base modules are loaded
+func IsConntrackProgrammable(nlh *netlink.Handle) bool {
+ return nlh.SupportsNetlinkFamily(syscall.NETLINK_NETFILTER)
+}
+
+// DeleteConntrackEntries deletes all the conntrack connections on the host for the specified IP
+// Returns the number of flows deleted for IPv4, IPv6 else error
+func DeleteConntrackEntries(nlh *netlink.Handle, ipv4List []net.IP, ipv6List []net.IP) (uint, uint, error) {
+ if !IsConntrackProgrammable(nlh) {
+ return 0, 0, ErrConntrackNotConfigurable
+ }
+
+ var totalIPv4FlowPurged uint
+ for _, ipAddress := range ipv4List {
+ flowPurged, err := purgeConntrackState(nlh, syscall.AF_INET, ipAddress)
+ if err != nil {
+ logrus.Warnf("Failed to delete conntrack state for %s: %v", ipAddress, err)
+ continue
+ }
+ totalIPv4FlowPurged += flowPurged
+ }
+
+ var totalIPv6FlowPurged uint
+ for _, ipAddress := range ipv6List {
+ flowPurged, err := purgeConntrackState(nlh, syscall.AF_INET6, ipAddress)
+ if err != nil {
+ logrus.Warnf("Failed to delete conntrack state for %s: %v", ipAddress, err)
+ continue
+ }
+ totalIPv6FlowPurged += flowPurged
+ }
+
+ logrus.Debugf("DeleteConntrackEntries purged ipv4:%d, ipv6:%d", totalIPv4FlowPurged, totalIPv6FlowPurged)
+ return totalIPv4FlowPurged, totalIPv6FlowPurged, nil
+}
+
+func purgeConntrackState(nlh *netlink.Handle, family netlink.InetFamily, ipAddress net.IP) (uint, error) {
+ filter := &netlink.ConntrackFilter{}
+ // NOTE: doing the flush using the ipAddress is safe because today there cannot be multiple networks with the same subnet
+ // so it will not be possible to flush flows that are of other containers
+ filter.AddIP(netlink.ConntrackNatAnyIP, ipAddress)
+ return nlh.ConntrackDeleteFilter(netlink.ConntrackTable, family, filter)
+}
diff --git a/vendor/github.com/docker/libnetwork/iptables/firewalld.go b/vendor/github.com/docker/libnetwork/iptables/firewalld.go
new file mode 100644
index 0000000..7dc5127
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/iptables/firewalld.go
@@ -0,0 +1,167 @@
+package iptables
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/godbus/dbus"
+)
+
+// IPV defines the table string
+type IPV string
+
+const (
+ // Iptables point ipv4 table
+ Iptables IPV = "ipv4"
+ // IP6Tables point to ipv6 table
+ IP6Tables IPV = "ipv6"
+ // Ebtables point to bridge table
+ Ebtables IPV = "eb"
+)
+const (
+ dbusInterface = "org.fedoraproject.FirewallD1"
+ dbusPath = "/org/fedoraproject/FirewallD1"
+)
+
+// Conn is a connection to firewalld dbus endpoint.
+type Conn struct {
+ sysconn *dbus.Conn
+ sysobj dbus.BusObject
+ signal chan *dbus.Signal
+}
+
+var (
+ connection *Conn
+ firewalldRunning bool // is Firewalld service running
+ onReloaded []*func() // callbacks when Firewalld has been reloaded
+)
+
+// FirewalldInit initializes firewalld management code.
+func FirewalldInit() error {
+ var err error
+
+ if connection, err = newConnection(); err != nil {
+ return fmt.Errorf("Failed to connect to D-Bus system bus: %v", err)
+ }
+ firewalldRunning = checkRunning()
+ if !firewalldRunning {
+ connection.sysconn.Close()
+ connection = nil
+ }
+ if connection != nil {
+ go signalHandler()
+ }
+
+ return nil
+}
+
+// New() establishes a connection to the system bus.
+func newConnection() (*Conn, error) {
+ c := new(Conn)
+ if err := c.initConnection(); err != nil {
+ return nil, err
+ }
+
+ return c, nil
+}
+
+// Innitialize D-Bus connection.
+func (c *Conn) initConnection() error {
+ var err error
+
+ c.sysconn, err = dbus.SystemBus()
+ if err != nil {
+ return err
+ }
+
+ // This never fails, even if the service is not running atm.
+ c.sysobj = c.sysconn.Object(dbusInterface, dbus.ObjectPath(dbusPath))
+
+ rule := fmt.Sprintf("type='signal',path='%s',interface='%s',sender='%s',member='Reloaded'",
+ dbusPath, dbusInterface, dbusInterface)
+ c.sysconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule)
+
+ rule = fmt.Sprintf("type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus',sender='org.freedesktop.DBus',arg0='%s'",
+ dbusInterface)
+ c.sysconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule)
+
+ c.signal = make(chan *dbus.Signal, 10)
+ c.sysconn.Signal(c.signal)
+
+ return nil
+}
+
+func signalHandler() {
+ for signal := range connection.signal {
+ if strings.Contains(signal.Name, "NameOwnerChanged") {
+ firewalldRunning = checkRunning()
+ dbusConnectionChanged(signal.Body)
+ } else if strings.Contains(signal.Name, "Reloaded") {
+ reloaded()
+ }
+ }
+}
+
+func dbusConnectionChanged(args []interface{}) {
+ name := args[0].(string)
+ oldOwner := args[1].(string)
+ newOwner := args[2].(string)
+
+ if name != dbusInterface {
+ return
+ }
+
+ if len(newOwner) > 0 {
+ connectionEstablished()
+ } else if len(oldOwner) > 0 {
+ connectionLost()
+ }
+}
+
+func connectionEstablished() {
+ reloaded()
+}
+
+func connectionLost() {
+ // Doesn't do anything for now. Libvirt also doesn't react to this.
+}
+
+// call all callbacks
+func reloaded() {
+ for _, pf := range onReloaded {
+ (*pf)()
+ }
+}
+
+// OnReloaded add callback
+func OnReloaded(callback func()) {
+ for _, pf := range onReloaded {
+ if pf == &callback {
+ return
+ }
+ }
+ onReloaded = append(onReloaded, &callback)
+}
+
+// Call some remote method to see whether the service is actually running.
+func checkRunning() bool {
+ var zone string
+ var err error
+
+ if connection != nil {
+ err = connection.sysobj.Call(dbusInterface+".getDefaultZone", 0).Store(&zone)
+ return err == nil
+ }
+ return false
+}
+
+// Passthrough method simply passes args through to iptables/ip6tables
+func Passthrough(ipv IPV, args ...string) ([]byte, error) {
+ var output string
+ logrus.Debugf("Firewalld passthrough: %s, %s", ipv, args)
+ if err := connection.sysobj.Call(dbusInterface+".direct.passthrough", 0, ipv, args).Store(&output); err != nil {
+ return nil, err
+ }
+ return []byte(output), nil
+}
diff --git a/vendor/github.com/docker/libnetwork/iptables/iptables.go b/vendor/github.com/docker/libnetwork/iptables/iptables.go
new file mode 100644
index 0000000..20edb9b
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/iptables/iptables.go
@@ -0,0 +1,541 @@
+package iptables
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "os/exec"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// Action signifies the iptable action.
+type Action string
+
+// Policy is the default iptable policies
+type Policy string
+
+// Table refers to Nat, Filter or Mangle.
+type Table string
+
+const (
+ // Append appends the rule at the end of the chain.
+ Append Action = "-A"
+ // Delete deletes the rule from the chain.
+ Delete Action = "-D"
+ // Insert inserts the rule at the top of the chain.
+ Insert Action = "-I"
+ // Nat table is used for nat translation rules.
+ Nat Table = "nat"
+ // Filter table is used for filter rules.
+ Filter Table = "filter"
+ // Mangle table is used for mangling the packet.
+ Mangle Table = "mangle"
+ // Drop is the default iptables DROP policy
+ Drop Policy = "DROP"
+ // Accept is the default iptables ACCEPT policy
+ Accept Policy = "ACCEPT"
+)
+
+var (
+ iptablesPath string
+ supportsXlock = false
+ supportsCOpt = false
+ xLockWaitMsg = "Another app is currently holding the xtables lock; waiting"
+ // used to lock iptables commands if xtables lock is not supported
+ bestEffortLock sync.Mutex
+ // ErrIptablesNotFound is returned when the rule is not found.
+ ErrIptablesNotFound = errors.New("Iptables not found")
+ initOnce sync.Once
+)
+
+// ChainInfo defines the iptables chain.
+type ChainInfo struct {
+ Name string
+ Table Table
+ HairpinMode bool
+}
+
+// ChainError is returned to represent errors during ip table operation.
+type ChainError struct {
+ Chain string
+ Output []byte
+}
+
+func (e ChainError) Error() string {
+ return fmt.Sprintf("Error iptables %s: %s", e.Chain, string(e.Output))
+}
+
+func probe() {
+ if out, err := exec.Command("modprobe", "-va", "nf_nat").CombinedOutput(); err != nil {
+ logrus.Warnf("Running modprobe nf_nat failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
+ }
+ if out, err := exec.Command("modprobe", "-va", "xt_conntrack").CombinedOutput(); err != nil {
+ logrus.Warnf("Running modprobe xt_conntrack failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
+ }
+}
+
+func initFirewalld() {
+ if err := FirewalldInit(); err != nil {
+ logrus.Debugf("Fail to initialize firewalld: %v, using raw iptables instead", err)
+ }
+}
+
+func detectIptables() {
+ path, err := exec.LookPath("iptables")
+ if err != nil {
+ return
+ }
+ iptablesPath = path
+ supportsXlock = exec.Command(iptablesPath, "--wait", "-L", "-n").Run() == nil
+ mj, mn, mc, err := GetVersion()
+ if err != nil {
+ logrus.Warnf("Failed to read iptables version: %v", err)
+ return
+ }
+ supportsCOpt = supportsCOption(mj, mn, mc)
+}
+
+func initDependencies() {
+ probe()
+ initFirewalld()
+ detectIptables()
+}
+
+func initCheck() error {
+ initOnce.Do(initDependencies)
+
+ if iptablesPath == "" {
+ return ErrIptablesNotFound
+ }
+ return nil
+}
+
+// NewChain adds a new chain to ip table.
+func NewChain(name string, table Table, hairpinMode bool) (*ChainInfo, error) {
+ c := &ChainInfo{
+ Name: name,
+ Table: table,
+ HairpinMode: hairpinMode,
+ }
+ if string(c.Table) == "" {
+ c.Table = Filter
+ }
+
+ // Add chain if it doesn't exist
+ if _, err := Raw("-t", string(c.Table), "-n", "-L", c.Name); err != nil {
+ if output, err := Raw("-t", string(c.Table), "-N", c.Name); err != nil {
+ return nil, err
+ } else if len(output) != 0 {
+ return nil, fmt.Errorf("Could not create %s/%s chain: %s", c.Table, c.Name, output)
+ }
+ }
+ return c, nil
+}
+
+// ProgramChain is used to add rules to a chain
+func ProgramChain(c *ChainInfo, bridgeName string, hairpinMode, enable bool) error {
+ if c.Name == "" {
+ return errors.New("Could not program chain, missing chain name")
+ }
+
+ switch c.Table {
+ case Nat:
+ preroute := []string{
+ "-m", "addrtype",
+ "--dst-type", "LOCAL",
+ "-j", c.Name}
+ if !Exists(Nat, "PREROUTING", preroute...) && enable {
+ if err := c.Prerouting(Append, preroute...); err != nil {
+ return fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err)
+ }
+ } else if Exists(Nat, "PREROUTING", preroute...) && !enable {
+ if err := c.Prerouting(Delete, preroute...); err != nil {
+ return fmt.Errorf("Failed to remove docker in PREROUTING chain: %s", err)
+ }
+ }
+ output := []string{
+ "-m", "addrtype",
+ "--dst-type", "LOCAL",
+ "-j", c.Name}
+ if !hairpinMode {
+ output = append(output, "!", "--dst", "127.0.0.0/8")
+ }
+ if !Exists(Nat, "OUTPUT", output...) && enable {
+ if err := c.Output(Append, output...); err != nil {
+ return fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err)
+ }
+ } else if Exists(Nat, "OUTPUT", output...) && !enable {
+ if err := c.Output(Delete, output...); err != nil {
+ return fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err)
+ }
+ }
+ case Filter:
+ if bridgeName == "" {
+ return fmt.Errorf("Could not program chain %s/%s, missing bridge name",
+ c.Table, c.Name)
+ }
+ link := []string{
+ "-o", bridgeName,
+ "-j", c.Name}
+ if !Exists(Filter, "FORWARD", link...) && enable {
+ insert := append([]string{string(Insert), "FORWARD"}, link...)
+ if output, err := Raw(insert...); err != nil {
+ return err
+ } else if len(output) != 0 {
+ return fmt.Errorf("Could not create linking rule to %s/%s: %s", c.Table, c.Name, output)
+ }
+ } else if Exists(Filter, "FORWARD", link...) && !enable {
+ del := append([]string{string(Delete), "FORWARD"}, link...)
+ if output, err := Raw(del...); err != nil {
+ return err
+ } else if len(output) != 0 {
+ return fmt.Errorf("Could not delete linking rule from %s/%s: %s", c.Table, c.Name, output)
+ }
+
+ }
+ establish := []string{
+ "-o", bridgeName,
+ "-m", "conntrack",
+ "--ctstate", "RELATED,ESTABLISHED",
+ "-j", "ACCEPT"}
+ if !Exists(Filter, "FORWARD", establish...) && enable {
+ insert := append([]string{string(Insert), "FORWARD"}, establish...)
+ if output, err := Raw(insert...); err != nil {
+ return err
+ } else if len(output) != 0 {
+ return fmt.Errorf("Could not create establish rule to %s: %s", c.Table, output)
+ }
+ } else if Exists(Filter, "FORWARD", establish...) && !enable {
+ del := append([]string{string(Delete), "FORWARD"}, establish...)
+ if output, err := Raw(del...); err != nil {
+ return err
+ } else if len(output) != 0 {
+ return fmt.Errorf("Could not delete establish rule from %s: %s", c.Table, output)
+ }
+ }
+ }
+ return nil
+}
+
+// RemoveExistingChain removes existing chain from the table.
+func RemoveExistingChain(name string, table Table) error {
+ c := &ChainInfo{
+ Name: name,
+ Table: table,
+ }
+ if string(c.Table) == "" {
+ c.Table = Filter
+ }
+ return c.Remove()
+}
+
+// Forward adds forwarding rule to 'filter' table and corresponding nat rule to 'nat' table.
+func (c *ChainInfo) Forward(action Action, ip net.IP, port int, proto, destAddr string, destPort int, bridgeName string) error {
+ daddr := ip.String()
+ if ip.IsUnspecified() {
+ // iptables interprets "0.0.0.0" as "0.0.0.0/32", whereas we
+ // want "0.0.0.0/0". "0/0" is correctly interpreted as "any
+ // value" by both iptables and ip6tables.
+ daddr = "0/0"
+ }
+
+ args := []string{
+ "-p", proto,
+ "-d", daddr,
+ "--dport", strconv.Itoa(port),
+ "-j", "DNAT",
+ "--to-destination", net.JoinHostPort(destAddr, strconv.Itoa(destPort))}
+ if !c.HairpinMode {
+ args = append(args, "!", "-i", bridgeName)
+ }
+ if err := ProgramRule(Nat, c.Name, action, args); err != nil {
+ return err
+ }
+
+ args = []string{
+ "!", "-i", bridgeName,
+ "-o", bridgeName,
+ "-p", proto,
+ "-d", destAddr,
+ "--dport", strconv.Itoa(destPort),
+ "-j", "ACCEPT",
+ }
+ if err := ProgramRule(Filter, c.Name, action, args); err != nil {
+ return err
+ }
+
+ args = []string{
+ "-p", proto,
+ "-s", destAddr,
+ "-d", destAddr,
+ "--dport", strconv.Itoa(destPort),
+ "-j", "MASQUERADE",
+ }
+ if err := ProgramRule(Nat, "POSTROUTING", action, args); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Link adds reciprocal ACCEPT rule for two supplied IP addresses.
+// Traffic is allowed from ip1 to ip2 and vice-versa
+func (c *ChainInfo) Link(action Action, ip1, ip2 net.IP, port int, proto string, bridgeName string) error {
+ // forward
+ args := []string{
+ "-i", bridgeName, "-o", bridgeName,
+ "-p", proto,
+ "-s", ip1.String(),
+ "-d", ip2.String(),
+ "--dport", strconv.Itoa(port),
+ "-j", "ACCEPT",
+ }
+ if err := ProgramRule(Filter, c.Name, action, args); err != nil {
+ return err
+ }
+ // reverse
+ args[7], args[9] = args[9], args[7]
+ args[10] = "--sport"
+ if err := ProgramRule(Filter, c.Name, action, args); err != nil {
+ return err
+ }
+ return nil
+}
+
+// ProgramRule adds the rule specified by args only if the
+// rule is not already present in the chain. Reciprocally,
+// it removes the rule only if present.
+func ProgramRule(table Table, chain string, action Action, args []string) error {
+ if Exists(table, chain, args...) != (action == Delete) {
+ return nil
+ }
+ return RawCombinedOutput(append([]string{"-t", string(table), string(action), chain}, args...)...)
+}
+
+// Prerouting adds linking rule to nat/PREROUTING chain.
+func (c *ChainInfo) Prerouting(action Action, args ...string) error {
+ a := []string{"-t", string(Nat), string(action), "PREROUTING"}
+ if len(args) > 0 {
+ a = append(a, args...)
+ }
+ if output, err := Raw(a...); err != nil {
+ return err
+ } else if len(output) != 0 {
+ return ChainError{Chain: "PREROUTING", Output: output}
+ }
+ return nil
+}
+
+// Output adds linking rule to an OUTPUT chain.
+func (c *ChainInfo) Output(action Action, args ...string) error {
+ a := []string{"-t", string(c.Table), string(action), "OUTPUT"}
+ if len(args) > 0 {
+ a = append(a, args...)
+ }
+ if output, err := Raw(a...); err != nil {
+ return err
+ } else if len(output) != 0 {
+ return ChainError{Chain: "OUTPUT", Output: output}
+ }
+ return nil
+}
+
+// Remove removes the chain.
+func (c *ChainInfo) Remove() error {
+ // Ignore errors - This could mean the chains were never set up
+ if c.Table == Nat {
+ c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name)
+ c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8", "-j", c.Name)
+ c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6
+
+ c.Prerouting(Delete)
+ c.Output(Delete)
+ }
+ Raw("-t", string(c.Table), "-F", c.Name)
+ Raw("-t", string(c.Table), "-X", c.Name)
+ return nil
+}
+
+// Exists checks if a rule exists
+func Exists(table Table, chain string, rule ...string) bool {
+ return exists(false, table, chain, rule...)
+}
+
+// ExistsNative behaves as Exists with the difference it
+// will always invoke `iptables` binary.
+func ExistsNative(table Table, chain string, rule ...string) bool {
+ return exists(true, table, chain, rule...)
+}
+
+func exists(native bool, table Table, chain string, rule ...string) bool {
+ f := Raw
+ if native {
+ f = raw
+ }
+
+ if string(table) == "" {
+ table = Filter
+ }
+
+ if err := initCheck(); err != nil {
+ // The exists() signature does not allow us to return an error, but at least
+ // we can skip the (likely invalid) exec invocation.
+ return false
+ }
+
+ if supportsCOpt {
+ // if exit status is 0 then return true, the rule exists
+ _, err := f(append([]string{"-t", string(table), "-C", chain}, rule...)...)
+ return err == nil
+ }
+
+ // parse "iptables -S" for the rule (it checks rules in a specific chain
+ // in a specific table and it is very unreliable)
+ return existsRaw(table, chain, rule...)
+}
+
+func existsRaw(table Table, chain string, rule ...string) bool {
+ ruleString := fmt.Sprintf("%s %s\n", chain, strings.Join(rule, " "))
+ existingRules, _ := exec.Command(iptablesPath, "-t", string(table), "-S", chain).Output()
+
+ return strings.Contains(string(existingRules), ruleString)
+}
+
+// Raw calls 'iptables' system command, passing supplied arguments.
+func Raw(args ...string) ([]byte, error) {
+ if firewalldRunning {
+ output, err := Passthrough(Iptables, args...)
+ if err == nil || !strings.Contains(err.Error(), "was not provided by any .service files") {
+ return output, err
+ }
+ }
+ return raw(args...)
+}
+
+func raw(args ...string) ([]byte, error) {
+ if err := initCheck(); err != nil {
+ return nil, err
+ }
+ if supportsXlock {
+ args = append([]string{"--wait"}, args...)
+ } else {
+ bestEffortLock.Lock()
+ defer bestEffortLock.Unlock()
+ }
+
+ logrus.Debugf("%s, %v", iptablesPath, args)
+
+ output, err := exec.Command(iptablesPath, args...).CombinedOutput()
+ if err != nil {
+ return nil, fmt.Errorf("iptables failed: iptables %v: %s (%s)", strings.Join(args, " "), output, err)
+ }
+
+ // ignore iptables' message about xtables lock
+ if strings.Contains(string(output), xLockWaitMsg) {
+ output = []byte("")
+ }
+
+ return output, err
+}
+
+// RawCombinedOutput inernally calls the Raw function and returns a non nil
+// error if Raw returned a non nil error or a non empty output
+func RawCombinedOutput(args ...string) error {
+ if output, err := Raw(args...); err != nil || len(output) != 0 {
+ return fmt.Errorf("%s (%v)", string(output), err)
+ }
+ return nil
+}
+
+// RawCombinedOutputNative behave as RawCombinedOutput with the difference it
+// will always invoke `iptables` binary
+func RawCombinedOutputNative(args ...string) error {
+ if output, err := raw(args...); err != nil || len(output) != 0 {
+ return fmt.Errorf("%s (%v)", string(output), err)
+ }
+ return nil
+}
+
+// ExistChain checks if a chain exists
+func ExistChain(chain string, table Table) bool {
+ if _, err := Raw("-t", string(table), "-L", chain); err == nil {
+ return true
+ }
+ return false
+}
+
+// GetVersion reads the iptables version numbers during initialization
+func GetVersion() (major, minor, micro int, err error) {
+ out, err := exec.Command(iptablesPath, "--version").CombinedOutput()
+ if err == nil {
+ major, minor, micro = parseVersionNumbers(string(out))
+ }
+ return
+}
+
+// SetDefaultPolicy sets the passed default policy for the table/chain
+func SetDefaultPolicy(table Table, chain string, policy Policy) error {
+ if err := RawCombinedOutput("-t", string(table), "-P", chain, string(policy)); err != nil {
+ return fmt.Errorf("setting default policy to %v in %v chain failed: %v", policy, chain, err)
+ }
+ return nil
+}
+
+func parseVersionNumbers(input string) (major, minor, micro int) {
+ re := regexp.MustCompile(`v\d*.\d*.\d*`)
+ line := re.FindString(input)
+ fmt.Sscanf(line, "v%d.%d.%d", &major, &minor, &micro)
+ return
+}
+
+// iptables -C, --check option was added in v.1.4.11
+// http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt
+func supportsCOption(mj, mn, mc int) bool {
+ return mj > 1 || (mj == 1 && (mn > 4 || (mn == 4 && mc >= 11)))
+}
+
+// AddReturnRule adds a return rule for the chain in the filter table
+func AddReturnRule(chain string) error {
+ var (
+ table = Filter
+ args = []string{"-j", "RETURN"}
+ )
+
+ if Exists(table, chain, args...) {
+ return nil
+ }
+
+ err := RawCombinedOutput(append([]string{"-A", chain}, args...)...)
+ if err != nil {
+ return fmt.Errorf("unable to add return rule in %s chain: %s", chain, err.Error())
+ }
+
+ return nil
+}
+
+// EnsureJumpRule ensures the jump rule is on top
+func EnsureJumpRule(fromChain, toChain string) error {
+ var (
+ table = Filter
+ args = []string{"-j", toChain}
+ )
+
+ if Exists(table, fromChain, args...) {
+ err := RawCombinedOutput(append([]string{"-D", fromChain}, args...)...)
+ if err != nil {
+ return fmt.Errorf("unable to remove jump to %s rule in %s chain: %s", toChain, fromChain, err.Error())
+ }
+ }
+
+ err := RawCombinedOutput(append([]string{"-I", fromChain}, args...)...)
+ if err != nil {
+ return fmt.Errorf("unable to insert jump to %s rule in %s chain: %s", toChain, fromChain, err.Error())
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/ipvs/constants.go b/vendor/github.com/docker/libnetwork/ipvs/constants.go
new file mode 100644
index 0000000..d36bec0
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipvs/constants.go
@@ -0,0 +1,147 @@
+// +build linux
+
+package ipvs
+
+const (
+ genlCtrlID = 0x10
+)
+
+// GENL control commands
+const (
+ genlCtrlCmdUnspec uint8 = iota
+ genlCtrlCmdNewFamily
+ genlCtrlCmdDelFamily
+ genlCtrlCmdGetFamily
+)
+
+// GENL family attributes
+const (
+ genlCtrlAttrUnspec int = iota
+ genlCtrlAttrFamilyID
+ genlCtrlAttrFamilyName
+)
+
+// IPVS genl commands
+const (
+ ipvsCmdUnspec uint8 = iota
+ ipvsCmdNewService
+ ipvsCmdSetService
+ ipvsCmdDelService
+ ipvsCmdGetService
+ ipvsCmdNewDest
+ ipvsCmdSetDest
+ ipvsCmdDelDest
+ ipvsCmdGetDest
+ ipvsCmdNewDaemon
+ ipvsCmdDelDaemon
+ ipvsCmdGetDaemon
+ ipvsCmdSetConfig
+ ipvsCmdGetConfig
+ ipvsCmdSetInfo
+ ipvsCmdGetInfo
+ ipvsCmdZero
+ ipvsCmdFlush
+)
+
+// Attributes used in the first level of commands
+const (
+ ipvsCmdAttrUnspec int = iota
+ ipvsCmdAttrService
+ ipvsCmdAttrDest
+ ipvsCmdAttrDaemon
+ ipvsCmdAttrTimeoutTCP
+ ipvsCmdAttrTimeoutTCPFin
+ ipvsCmdAttrTimeoutUDP
+)
+
+// Attributes used to describe a service. Used inside nested attribute
+// ipvsCmdAttrService
+const (
+ ipvsSvcAttrUnspec int = iota
+ ipvsSvcAttrAddressFamily
+ ipvsSvcAttrProtocol
+ ipvsSvcAttrAddress
+ ipvsSvcAttrPort
+ ipvsSvcAttrFWMark
+ ipvsSvcAttrSchedName
+ ipvsSvcAttrFlags
+ ipvsSvcAttrTimeout
+ ipvsSvcAttrNetmask
+ ipvsSvcAttrStats
+ ipvsSvcAttrPEName
+)
+
+// Attributes used to describe a destination (real server). Used
+// inside nested attribute ipvsCmdAttrDest.
+const (
+ ipvsDestAttrUnspec int = iota
+ ipvsDestAttrAddress
+ ipvsDestAttrPort
+ ipvsDestAttrForwardingMethod
+ ipvsDestAttrWeight
+ ipvsDestAttrUpperThreshold
+ ipvsDestAttrLowerThreshold
+ ipvsDestAttrActiveConnections
+ ipvsDestAttrInactiveConnections
+ ipvsDestAttrPersistentConnections
+ ipvsDestAttrStats
+ ipvsDestAttrAddressFamily
+)
+
+// IPVS Svc Statistics constancs
+
+const (
+ ipvsSvcStatsUnspec int = iota
+ ipvsSvcStatsConns
+ ipvsSvcStatsPktsIn
+ ipvsSvcStatsPktsOut
+ ipvsSvcStatsBytesIn
+ ipvsSvcStatsBytesOut
+ ipvsSvcStatsCPS
+ ipvsSvcStatsPPSIn
+ ipvsSvcStatsPPSOut
+ ipvsSvcStatsBPSIn
+ ipvsSvcStatsBPSOut
+)
+
+// Destination forwarding methods
+const (
+ // ConnectionFlagFwdmask indicates the mask in the connection
+ // flags which is used by forwarding method bits.
+ ConnectionFlagFwdMask = 0x0007
+
+ // ConnectionFlagMasq is used for masquerade forwarding method.
+ ConnectionFlagMasq = 0x0000
+
+ // ConnectionFlagLocalNode is used for local node forwarding
+ // method.
+ ConnectionFlagLocalNode = 0x0001
+
+ // ConnectionFlagTunnel is used for tunnel mode forwarding
+ // method.
+ ConnectionFlagTunnel = 0x0002
+
+ // ConnectionFlagDirectRoute is used for direct routing
+ // forwarding method.
+ ConnectionFlagDirectRoute = 0x0003
+)
+
+const (
+ // RoundRobin distributes jobs equally amongst the available
+ // real servers.
+ RoundRobin = "rr"
+
+ // LeastConnection assigns more jobs to real servers with
+ // fewer active jobs.
+ LeastConnection = "lc"
+
+ // DestinationHashing assigns jobs to servers through looking
+ // up a statically assigned hash table by their destination IP
+ // addresses.
+ DestinationHashing = "dh"
+
+ // SourceHashing assigns jobs to servers through looking up
+ // a statically assigned hash table by their source IP
+ // addresses.
+ SourceHashing = "sh"
+)
diff --git a/vendor/github.com/docker/libnetwork/ipvs/ipvs.go b/vendor/github.com/docker/libnetwork/ipvs/ipvs.go
new file mode 100644
index 0000000..a285e10
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipvs/ipvs.go
@@ -0,0 +1,161 @@
+// +build linux
+
+package ipvs
+
+import (
+ "net"
+ "syscall"
+
+ "fmt"
+ "github.com/vishvananda/netlink/nl"
+ "github.com/vishvananda/netns"
+)
+
+// Service defines an IPVS service in its entirety.
+type Service struct {
+ // Virtual service address.
+ Address net.IP
+ Protocol uint16
+ Port uint16
+ FWMark uint32 // Firewall mark of the service.
+
+ // Virtual service options.
+ SchedName string
+ Flags uint32
+ Timeout uint32
+ Netmask uint32
+ AddressFamily uint16
+ PEName string
+ Stats SvcStats
+}
+
+// SvcStats defines an IPVS service statistics
+type SvcStats struct {
+ Connections uint32
+ PacketsIn uint32
+ PacketsOut uint32
+ BytesIn uint64
+ BytesOut uint64
+ CPS uint32
+ BPSOut uint32
+ PPSIn uint32
+ PPSOut uint32
+ BPSIn uint32
+}
+
+// Destination defines an IPVS destination (real server) in its
+// entirety.
+type Destination struct {
+ Address net.IP
+ Port uint16
+ Weight int
+ ConnectionFlags uint32
+ AddressFamily uint16
+ UpperThreshold uint32
+ LowerThreshold uint32
+}
+
+// Handle provides a namespace specific ipvs handle to program ipvs
+// rules.
+type Handle struct {
+ seq uint32
+ sock *nl.NetlinkSocket
+}
+
+// New provides a new ipvs handle in the namespace pointed to by the
+// passed path. It will return a valid handle or an error in case an
+// error occurred while creating the handle.
+func New(path string) (*Handle, error) {
+ setup()
+
+ n := netns.None()
+ if path != "" {
+ var err error
+ n, err = netns.GetFromPath(path)
+ if err != nil {
+ return nil, err
+ }
+ }
+ defer n.Close()
+
+ sock, err := nl.GetNetlinkSocketAt(n, netns.None(), syscall.NETLINK_GENERIC)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Handle{sock: sock}, nil
+}
+
+// Close closes the ipvs handle. The handle is invalid after Close
+// returns.
+func (i *Handle) Close() {
+ if i.sock != nil {
+ i.sock.Close()
+ }
+}
+
+// NewService creates a new ipvs service in the passed handle.
+func (i *Handle) NewService(s *Service) error {
+ return i.doCmd(s, nil, ipvsCmdNewService)
+}
+
+// IsServicePresent queries for the ipvs service in the passed handle.
+func (i *Handle) IsServicePresent(s *Service) bool {
+ return nil == i.doCmd(s, nil, ipvsCmdGetService)
+}
+
+// UpdateService updates an already existing service in the passed
+// handle.
+func (i *Handle) UpdateService(s *Service) error {
+ return i.doCmd(s, nil, ipvsCmdSetService)
+}
+
+// DelService deletes an already existing service in the passed
+// handle.
+func (i *Handle) DelService(s *Service) error {
+ return i.doCmd(s, nil, ipvsCmdDelService)
+}
+
+// NewDestination creates a new real server in the passed ipvs
+// service which should already be existing in the passed handle.
+func (i *Handle) NewDestination(s *Service, d *Destination) error {
+ return i.doCmd(s, d, ipvsCmdNewDest)
+}
+
+// UpdateDestination updates an already existing real server in the
+// passed ipvs service in the passed handle.
+func (i *Handle) UpdateDestination(s *Service, d *Destination) error {
+ return i.doCmd(s, d, ipvsCmdSetDest)
+}
+
+// DelDestination deletes an already existing real server in the
+// passed ipvs service in the passed handle.
+func (i *Handle) DelDestination(s *Service, d *Destination) error {
+ return i.doCmd(s, d, ipvsCmdDelDest)
+}
+
+// GetServices returns an array of services configured on the Node
+func (i *Handle) GetServices() ([]*Service, error) {
+ return i.doGetServicesCmd(nil)
+}
+
+// GetDestinations returns an array of Destinations configured for this Service
+func (i *Handle) GetDestinations(s *Service) ([]*Destination, error) {
+ return i.doGetDestinationsCmd(s, nil)
+}
+
+// GetService gets details of a specific IPVS services, useful in updating statisics etc.,
+func (i *Handle) GetService(s *Service) (*Service, error) {
+
+ res, err := i.doGetServicesCmd(s)
+ if err != nil {
+ return nil, err
+ }
+
+ // We are looking for exactly one service otherwise error out
+ if len(res) != 1 {
+ return nil, fmt.Errorf("Expected only one service obtained=%d", len(res))
+ }
+
+ return res[0], nil
+}
diff --git a/vendor/github.com/docker/libnetwork/ipvs/netlink.go b/vendor/github.com/docker/libnetwork/ipvs/netlink.go
new file mode 100644
index 0000000..5450679
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ipvs/netlink.go
@@ -0,0 +1,546 @@
+// +build linux
+
+package ipvs
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "net"
+ "os/exec"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "unsafe"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/vishvananda/netlink/nl"
+ "github.com/vishvananda/netns"
+)
+
+// For Quick Reference IPVS related netlink message is described at the end of this file.
+var (
+ native = nl.NativeEndian()
+ ipvsFamily int
+ ipvsOnce sync.Once
+)
+
+type genlMsgHdr struct {
+ cmd uint8
+ version uint8
+ reserved uint16
+}
+
+type ipvsFlags struct {
+ flags uint32
+ mask uint32
+}
+
+func deserializeGenlMsg(b []byte) (hdr *genlMsgHdr) {
+ return (*genlMsgHdr)(unsafe.Pointer(&b[0:unsafe.Sizeof(*hdr)][0]))
+}
+
+func (hdr *genlMsgHdr) Serialize() []byte {
+ return (*(*[unsafe.Sizeof(*hdr)]byte)(unsafe.Pointer(hdr)))[:]
+}
+
+func (hdr *genlMsgHdr) Len() int {
+ return int(unsafe.Sizeof(*hdr))
+}
+
+func (f *ipvsFlags) Serialize() []byte {
+ return (*(*[unsafe.Sizeof(*f)]byte)(unsafe.Pointer(f)))[:]
+}
+
+func (f *ipvsFlags) Len() int {
+ return int(unsafe.Sizeof(*f))
+}
+
+func setup() {
+ ipvsOnce.Do(func() {
+ var err error
+ if out, err := exec.Command("modprobe", "-va", "ip_vs").CombinedOutput(); err != nil {
+ logrus.Warnf("Running modprobe ip_vs failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
+ }
+
+ ipvsFamily, err = getIPVSFamily()
+ if err != nil {
+ logrus.Error("Could not get ipvs family information from the kernel. It is possible that ipvs is not enabled in your kernel. Native loadbalancing will not work until this is fixed.")
+ }
+ })
+}
+
+func fillService(s *Service) nl.NetlinkRequestData {
+ cmdAttr := nl.NewRtAttr(ipvsCmdAttrService, nil)
+ nl.NewRtAttrChild(cmdAttr, ipvsSvcAttrAddressFamily, nl.Uint16Attr(s.AddressFamily))
+ if s.FWMark != 0 {
+ nl.NewRtAttrChild(cmdAttr, ipvsSvcAttrFWMark, nl.Uint32Attr(s.FWMark))
+ } else {
+ nl.NewRtAttrChild(cmdAttr, ipvsSvcAttrProtocol, nl.Uint16Attr(s.Protocol))
+ nl.NewRtAttrChild(cmdAttr, ipvsSvcAttrAddress, rawIPData(s.Address))
+
+ // Port needs to be in network byte order.
+ portBuf := new(bytes.Buffer)
+ binary.Write(portBuf, binary.BigEndian, s.Port)
+ nl.NewRtAttrChild(cmdAttr, ipvsSvcAttrPort, portBuf.Bytes())
+ }
+
+ nl.NewRtAttrChild(cmdAttr, ipvsSvcAttrSchedName, nl.ZeroTerminated(s.SchedName))
+ if s.PEName != "" {
+ nl.NewRtAttrChild(cmdAttr, ipvsSvcAttrPEName, nl.ZeroTerminated(s.PEName))
+ }
+ f := &ipvsFlags{
+ flags: s.Flags,
+ mask: 0xFFFFFFFF,
+ }
+ nl.NewRtAttrChild(cmdAttr, ipvsSvcAttrFlags, f.Serialize())
+ nl.NewRtAttrChild(cmdAttr, ipvsSvcAttrTimeout, nl.Uint32Attr(s.Timeout))
+ nl.NewRtAttrChild(cmdAttr, ipvsSvcAttrNetmask, nl.Uint32Attr(s.Netmask))
+ return cmdAttr
+}
+
+func fillDestinaton(d *Destination) nl.NetlinkRequestData {
+ cmdAttr := nl.NewRtAttr(ipvsCmdAttrDest, nil)
+
+ nl.NewRtAttrChild(cmdAttr, ipvsDestAttrAddress, rawIPData(d.Address))
+ // Port needs to be in network byte order.
+ portBuf := new(bytes.Buffer)
+ binary.Write(portBuf, binary.BigEndian, d.Port)
+ nl.NewRtAttrChild(cmdAttr, ipvsDestAttrPort, portBuf.Bytes())
+
+ nl.NewRtAttrChild(cmdAttr, ipvsDestAttrForwardingMethod, nl.Uint32Attr(d.ConnectionFlags&ConnectionFlagFwdMask))
+ nl.NewRtAttrChild(cmdAttr, ipvsDestAttrWeight, nl.Uint32Attr(uint32(d.Weight)))
+ nl.NewRtAttrChild(cmdAttr, ipvsDestAttrUpperThreshold, nl.Uint32Attr(d.UpperThreshold))
+ nl.NewRtAttrChild(cmdAttr, ipvsDestAttrLowerThreshold, nl.Uint32Attr(d.LowerThreshold))
+
+ return cmdAttr
+}
+
+func (i *Handle) doCmdwithResponse(s *Service, d *Destination, cmd uint8) ([][]byte, error) {
+ req := newIPVSRequest(cmd)
+ req.Seq = atomic.AddUint32(&i.seq, 1)
+
+ if s == nil {
+ req.Flags |= syscall.NLM_F_DUMP //Flag to dump all messages
+ req.AddData(nl.NewRtAttr(ipvsCmdAttrService, nil)) //Add a dummy attribute
+ } else {
+ req.AddData(fillService(s))
+ }
+
+ if d == nil {
+ if cmd == ipvsCmdGetDest {
+ req.Flags |= syscall.NLM_F_DUMP
+ }
+
+ } else {
+ req.AddData(fillDestinaton(d))
+ }
+
+ res, err := execute(i.sock, req, 0)
+ if err != nil {
+ return [][]byte{}, err
+ }
+
+ return res, nil
+}
+
+func (i *Handle) doCmd(s *Service, d *Destination, cmd uint8) error {
+ _, err := i.doCmdwithResponse(s, d, cmd)
+
+ return err
+}
+
+func getIPVSFamily() (int, error) {
+ sock, err := nl.GetNetlinkSocketAt(netns.None(), netns.None(), syscall.NETLINK_GENERIC)
+ if err != nil {
+ return 0, err
+ }
+ defer sock.Close()
+
+ req := newGenlRequest(genlCtrlID, genlCtrlCmdGetFamily)
+ req.AddData(nl.NewRtAttr(genlCtrlAttrFamilyName, nl.ZeroTerminated("IPVS")))
+
+ msgs, err := execute(sock, req, 0)
+ if err != nil {
+ return 0, err
+ }
+
+ for _, m := range msgs {
+ hdr := deserializeGenlMsg(m)
+ attrs, err := nl.ParseRouteAttr(m[hdr.Len():])
+ if err != nil {
+ return 0, err
+ }
+
+ for _, attr := range attrs {
+ switch int(attr.Attr.Type) {
+ case genlCtrlAttrFamilyID:
+ return int(native.Uint16(attr.Value[0:2])), nil
+ }
+ }
+ }
+
+ return 0, fmt.Errorf("no family id in the netlink response")
+}
+
+func rawIPData(ip net.IP) []byte {
+ family := nl.GetIPFamily(ip)
+ if family == nl.FAMILY_V4 {
+ return ip.To4()
+ }
+ return ip
+}
+
+func newIPVSRequest(cmd uint8) *nl.NetlinkRequest {
+ return newGenlRequest(ipvsFamily, cmd)
+}
+
+func newGenlRequest(familyID int, cmd uint8) *nl.NetlinkRequest {
+ req := nl.NewNetlinkRequest(familyID, syscall.NLM_F_ACK)
+ req.AddData(&genlMsgHdr{cmd: cmd, version: 1})
+ return req
+}
+
+func execute(s *nl.NetlinkSocket, req *nl.NetlinkRequest, resType uint16) ([][]byte, error) {
+ var (
+ err error
+ )
+
+ if err := s.Send(req); err != nil {
+ return nil, err
+ }
+
+ pid, err := s.GetPid()
+ if err != nil {
+ return nil, err
+ }
+
+ var res [][]byte
+
+done:
+ for {
+ msgs, err := s.Receive()
+ if err != nil {
+ return nil, err
+ }
+ for _, m := range msgs {
+ if m.Header.Seq != req.Seq {
+ continue
+ }
+ if m.Header.Pid != pid {
+ return nil, fmt.Errorf("Wrong pid %d, expected %d", m.Header.Pid, pid)
+ }
+ if m.Header.Type == syscall.NLMSG_DONE {
+ break done
+ }
+ if m.Header.Type == syscall.NLMSG_ERROR {
+ error := int32(native.Uint32(m.Data[0:4]))
+ if error == 0 {
+ break done
+ }
+ return nil, syscall.Errno(-error)
+ }
+ if resType != 0 && m.Header.Type != resType {
+ continue
+ }
+ res = append(res, m.Data)
+ if m.Header.Flags&syscall.NLM_F_MULTI == 0 {
+ break done
+ }
+ }
+ }
+ return res, nil
+}
+
+func parseIP(ip []byte, family uint16) (net.IP, error) {
+
+ var resIP net.IP
+
+ switch family {
+ case syscall.AF_INET:
+ resIP = (net.IP)(ip[:4])
+ case syscall.AF_INET6:
+ resIP = (net.IP)(ip[:16])
+ default:
+ return nil, fmt.Errorf("parseIP Error ip=%v", ip)
+
+ }
+ return resIP, nil
+}
+
+// parseStats
+func assembleStats(msg []byte) (SvcStats, error) {
+
+ var s SvcStats
+
+ attrs, err := nl.ParseRouteAttr(msg)
+ if err != nil {
+ return s, err
+ }
+
+ for _, attr := range attrs {
+ attrType := int(attr.Attr.Type)
+ switch attrType {
+ case ipvsSvcStatsConns:
+ s.Connections = native.Uint32(attr.Value)
+ case ipvsSvcStatsPktsIn:
+ s.PacketsIn = native.Uint32(attr.Value)
+ case ipvsSvcStatsPktsOut:
+ s.PacketsOut = native.Uint32(attr.Value)
+ case ipvsSvcStatsBytesIn:
+ s.BytesIn = native.Uint64(attr.Value)
+ case ipvsSvcStatsBytesOut:
+ s.BytesOut = native.Uint64(attr.Value)
+ case ipvsSvcStatsCPS:
+ s.CPS = native.Uint32(attr.Value)
+ case ipvsSvcStatsPPSIn:
+ s.PPSIn = native.Uint32(attr.Value)
+ case ipvsSvcStatsPPSOut:
+ s.PPSOut = native.Uint32(attr.Value)
+ case ipvsSvcStatsBPSIn:
+ s.BPSIn = native.Uint32(attr.Value)
+ case ipvsSvcStatsBPSOut:
+ s.BPSOut = native.Uint32(attr.Value)
+ }
+ }
+ return s, nil
+}
+
+// assembleService assembles a services back from a hain of netlink attributes
+func assembleService(attrs []syscall.NetlinkRouteAttr) (*Service, error) {
+
+ var s Service
+
+ for _, attr := range attrs {
+
+ attrType := int(attr.Attr.Type)
+
+ switch attrType {
+
+ case ipvsSvcAttrAddressFamily:
+ s.AddressFamily = native.Uint16(attr.Value)
+ case ipvsSvcAttrProtocol:
+ s.Protocol = native.Uint16(attr.Value)
+ case ipvsSvcAttrAddress:
+ ip, err := parseIP(attr.Value, s.AddressFamily)
+ if err != nil {
+ return nil, err
+ }
+ s.Address = ip
+ case ipvsSvcAttrPort:
+ s.Port = binary.BigEndian.Uint16(attr.Value)
+ case ipvsSvcAttrFWMark:
+ s.FWMark = native.Uint32(attr.Value)
+ case ipvsSvcAttrSchedName:
+ s.SchedName = nl.BytesToString(attr.Value)
+ case ipvsSvcAttrFlags:
+ s.Flags = native.Uint32(attr.Value)
+ case ipvsSvcAttrTimeout:
+ s.Timeout = native.Uint32(attr.Value)
+ case ipvsSvcAttrNetmask:
+ s.Netmask = native.Uint32(attr.Value)
+ case ipvsSvcAttrStats:
+ stats, err := assembleStats(attr.Value)
+ if err != nil {
+ return nil, err
+ }
+ s.Stats = stats
+ }
+
+ }
+ return &s, nil
+}
+
+// parseService given a ipvs netlink response this function will respond with a valid service entry, an error otherwise
+func (i *Handle) parseService(msg []byte) (*Service, error) {
+
+ var s *Service
+
+ //Remove General header for this message and parse the NetLink message
+ hdr := deserializeGenlMsg(msg)
+ NetLinkAttrs, err := nl.ParseRouteAttr(msg[hdr.Len():])
+ if err != nil {
+ return nil, err
+ }
+ if len(NetLinkAttrs) == 0 {
+ return nil, fmt.Errorf("error no valid netlink message found while parsing service record")
+ }
+
+ //Now Parse and get IPVS related attributes messages packed in this message.
+ ipvsAttrs, err := nl.ParseRouteAttr(NetLinkAttrs[0].Value)
+ if err != nil {
+ return nil, err
+ }
+
+ //Assemble all the IPVS related attribute messages and create a service record
+ s, err = assembleService(ipvsAttrs)
+ if err != nil {
+ return nil, err
+ }
+
+ return s, nil
+}
+
+// doGetServicesCmd a wrapper which could be used commonly for both GetServices() and GetService(*Service)
+func (i *Handle) doGetServicesCmd(svc *Service) ([]*Service, error) {
+ var res []*Service
+
+ msgs, err := i.doCmdwithResponse(svc, nil, ipvsCmdGetService)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, msg := range msgs {
+ srv, err := i.parseService(msg)
+ if err != nil {
+ return nil, err
+ }
+ res = append(res, srv)
+ }
+
+ return res, nil
+}
+
+func assembleDestination(attrs []syscall.NetlinkRouteAttr) (*Destination, error) {
+
+ var d Destination
+
+ for _, attr := range attrs {
+
+ attrType := int(attr.Attr.Type)
+
+ switch attrType {
+ case ipvsDestAttrAddress:
+ ip, err := parseIP(attr.Value, syscall.AF_INET)
+ if err != nil {
+ return nil, err
+ }
+ d.Address = ip
+ case ipvsDestAttrPort:
+ d.Port = binary.BigEndian.Uint16(attr.Value)
+ case ipvsDestAttrForwardingMethod:
+ d.ConnectionFlags = native.Uint32(attr.Value)
+ case ipvsDestAttrWeight:
+ d.Weight = int(native.Uint16(attr.Value))
+ case ipvsDestAttrUpperThreshold:
+ d.UpperThreshold = native.Uint32(attr.Value)
+ case ipvsDestAttrLowerThreshold:
+ d.LowerThreshold = native.Uint32(attr.Value)
+ case ipvsDestAttrAddressFamily:
+ d.AddressFamily = native.Uint16(attr.Value)
+ }
+ }
+ return &d, nil
+}
+
+// parseDestination given a ipvs netlink response this function will respond with a valid destination entry, an error otherwise
+func (i *Handle) parseDestination(msg []byte) (*Destination, error) {
+ var dst *Destination
+
+ //Remove General header for this message
+ hdr := deserializeGenlMsg(msg)
+ NetLinkAttrs, err := nl.ParseRouteAttr(msg[hdr.Len():])
+ if err != nil {
+ return nil, err
+ }
+ if len(NetLinkAttrs) == 0 {
+ return nil, fmt.Errorf("error no valid netlink message found while parsing destination record")
+ }
+
+ //Now Parse and get IPVS related attributes messages packed in this message.
+ ipvsAttrs, err := nl.ParseRouteAttr(NetLinkAttrs[0].Value)
+ if err != nil {
+ return nil, err
+ }
+
+ //Assemble netlink attributes and create a Destination record
+ dst, err = assembleDestination(ipvsAttrs)
+ if err != nil {
+ return nil, err
+ }
+
+ return dst, nil
+}
+
+// doGetDestinationsCmd a wrapper function to be used by GetDestinations and GetDestination(d) apis
+func (i *Handle) doGetDestinationsCmd(s *Service, d *Destination) ([]*Destination, error) {
+
+ var res []*Destination
+
+ msgs, err := i.doCmdwithResponse(s, d, ipvsCmdGetDest)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, msg := range msgs {
+ dest, err := i.parseDestination(msg)
+ if err != nil {
+ return res, err
+ }
+ res = append(res, dest)
+ }
+ return res, nil
+}
+
+// IPVS related netlink message format explained
+
+/* EACH NETLINK MSG is of the below format, this is what we will receive from execute() api.
+ If we have multiple netlink objects to process like GetServices() etc., execute() will
+ supply an array of this below object
+
+ NETLINK MSG
+|-----------------------------------|
+ 0 1 2 3
+|--------|--------|--------|--------| -
+| CMD ID | VER | RESERVED | |==> General Message Header represented by genlMsgHdr
+|-----------------------------------| -
+| ATTR LEN | ATTR TYPE | |
+|-----------------------------------| |
+| | |
+| VALUE | |
+| []byte Array of IPVS MSG | |==> Attribute Message represented by syscall.NetlinkRouteAttr
+| PADDED BY 4 BYTES | |
+| | |
+|-----------------------------------| -
+
+
+ Once We strip genlMsgHdr from above NETLINK MSG, we should parse the VALUE.
+ VALUE will have an array of netlink attributes (syscall.NetlinkRouteAttr) such that each attribute will
+ represent a "Service" or "Destination" object's field. If we assemble these attributes we can construct
+ Service or Destination.
+
+ IPVS MSG
+|-----------------------------------|
+ 0 1 2 3
+|--------|--------|--------|--------|
+| ATTR LEN | ATTR TYPE |
+|-----------------------------------|
+| |
+| |
+| []byte IPVS ATTRIBUTE BY 4 BYTES |
+| |
+| |
+|-----------------------------------|
+ NEXT ATTRIBUTE
+|-----------------------------------|
+| ATTR LEN | ATTR TYPE |
+|-----------------------------------|
+| |
+| |
+| []byte IPVS ATTRIBUTE BY 4 BYTES |
+| |
+| |
+|-----------------------------------|
+ NEXT ATTRIBUTE
+|-----------------------------------|
+| ATTR LEN | ATTR TYPE |
+|-----------------------------------|
+| |
+| |
+| []byte IPVS ATTRIBUTE BY 4 BYTES |
+| |
+| |
+|-----------------------------------|
+
+*/
diff --git a/vendor/github.com/docker/libnetwork/netlabel/labels.go b/vendor/github.com/docker/libnetwork/netlabel/labels.go
new file mode 100644
index 0000000..1594556
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/netlabel/labels.go
@@ -0,0 +1,129 @@
+package netlabel
+
+import (
+ "strings"
+)
+
+const (
+ // Prefix constant marks the reserved label space for libnetwork
+ Prefix = "com.docker.network"
+
+ // DriverPrefix constant marks the reserved label space for libnetwork drivers
+ DriverPrefix = Prefix + ".driver"
+
+ // DriverPrivatePrefix constant marks the reserved label space
+ // for internal libnetwork drivers
+ DriverPrivatePrefix = DriverPrefix + ".private"
+
+ // GenericData constant that helps to identify an option as a Generic constant
+ GenericData = Prefix + ".generic"
+
+ // PortMap constant represents Port Mapping
+ PortMap = Prefix + ".portmap"
+
+ // MacAddress constant represents Mac Address config of a Container
+ MacAddress = Prefix + ".endpoint.macaddress"
+
+ // ExposedPorts constant represents the container's Exposed Ports
+ ExposedPorts = Prefix + ".endpoint.exposedports"
+
+ // DNSServers A list of DNS servers associated with the endpoint
+ DNSServers = Prefix + ".endpoint.dnsservers"
+
+ //EnableIPv6 constant represents enabling IPV6 at network level
+ EnableIPv6 = Prefix + ".enable_ipv6"
+
+ // DriverMTU constant represents the MTU size for the network driver
+ DriverMTU = DriverPrefix + ".mtu"
+
+ // OverlayBindInterface constant represents overlay driver bind interface
+ OverlayBindInterface = DriverPrefix + ".overlay.bind_interface"
+
+ // OverlayNeighborIP constant represents overlay driver neighbor IP
+ OverlayNeighborIP = DriverPrefix + ".overlay.neighbor_ip"
+
+ // OverlayVxlanIDList constant represents a list of VXLAN Ids as csv
+ OverlayVxlanIDList = DriverPrefix + ".overlay.vxlanid_list"
+
+ // Gateway represents the gateway for the network
+ Gateway = Prefix + ".gateway"
+
+ // Internal constant represents that the network is internal which disables default gateway service
+ Internal = Prefix + ".internal"
+
+ // ContainerIfacePrefix can be used to override the interface prefix used inside the container
+ ContainerIfacePrefix = Prefix + ".container_iface_prefix"
+)
+
+var (
+ // GlobalKVProvider constant represents the KV provider backend
+ GlobalKVProvider = MakeKVProvider("global")
+
+ // GlobalKVProviderURL constant represents the KV provider URL
+ GlobalKVProviderURL = MakeKVProviderURL("global")
+
+ // GlobalKVProviderConfig constant represents the KV provider Config
+ GlobalKVProviderConfig = MakeKVProviderConfig("global")
+
+ // GlobalKVClient constants represents the global kv store client
+ GlobalKVClient = MakeKVClient("global")
+
+ // LocalKVProvider constant represents the KV provider backend
+ LocalKVProvider = MakeKVProvider("local")
+
+ // LocalKVProviderURL constant represents the KV provider URL
+ LocalKVProviderURL = MakeKVProviderURL("local")
+
+ // LocalKVProviderConfig constant represents the KV provider Config
+ LocalKVProviderConfig = MakeKVProviderConfig("local")
+
+ // LocalKVClient constants represents the local kv store client
+ LocalKVClient = MakeKVClient("local")
+)
+
+// MakeKVProvider returns the kvprovider label for the scope
+func MakeKVProvider(scope string) string {
+ return DriverPrivatePrefix + scope + "kv_provider"
+}
+
+// MakeKVProviderURL returns the kvprovider url label for the scope
+func MakeKVProviderURL(scope string) string {
+ return DriverPrivatePrefix + scope + "kv_provider_url"
+}
+
+// MakeKVProviderConfig returns the kvprovider config label for the scope
+func MakeKVProviderConfig(scope string) string {
+ return DriverPrivatePrefix + scope + "kv_provider_config"
+}
+
+// MakeKVClient returns the kv client label for the scope
+func MakeKVClient(scope string) string {
+ return DriverPrivatePrefix + scope + "kv_client"
+}
+
+// Key extracts the key portion of the label
+func Key(label string) (key string) {
+ if kv := strings.SplitN(label, "=", 2); len(kv) > 0 {
+ key = kv[0]
+ }
+ return
+}
+
+// Value extracts the value portion of the label
+func Value(label string) (value string) {
+ if kv := strings.SplitN(label, "=", 2); len(kv) > 1 {
+ value = kv[1]
+ }
+ return
+}
+
+// KeyValue decomposes the label in the (key,value) pair
+func KeyValue(label string) (key string, value string) {
+ if kv := strings.SplitN(label, "=", 2); len(kv) > 0 {
+ key = kv[0]
+ if len(kv) > 1 {
+ value = kv[1]
+ }
+ }
+ return
+}
diff --git a/vendor/github.com/docker/libnetwork/netutils/utils.go b/vendor/github.com/docker/libnetwork/netutils/utils.go
new file mode 100644
index 0000000..7de98f6
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/netutils/utils.go
@@ -0,0 +1,194 @@
+// Network utility functions.
+
+package netutils
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "strings"
+
+ "github.com/docker/libnetwork/types"
+)
+
+var (
+ // ErrNetworkOverlapsWithNameservers preformatted error
+ ErrNetworkOverlapsWithNameservers = errors.New("requested network overlaps with nameserver")
+ // ErrNetworkOverlaps preformatted error
+ ErrNetworkOverlaps = errors.New("requested network overlaps with existing network")
+ // ErrNoDefaultRoute preformatted error
+ ErrNoDefaultRoute = errors.New("no default route")
+)
+
+// CheckNameserverOverlaps checks whether the passed network overlaps with any of the nameservers
+func CheckNameserverOverlaps(nameservers []string, toCheck *net.IPNet) error {
+ if len(nameservers) > 0 {
+ for _, ns := range nameservers {
+ _, nsNetwork, err := net.ParseCIDR(ns)
+ if err != nil {
+ return err
+ }
+ if NetworkOverlaps(toCheck, nsNetwork) {
+ return ErrNetworkOverlapsWithNameservers
+ }
+ }
+ }
+ return nil
+}
+
+// NetworkOverlaps detects overlap between one IPNet and another
+func NetworkOverlaps(netX *net.IPNet, netY *net.IPNet) bool {
+ return netX.Contains(netY.IP) || netY.Contains(netX.IP)
+}
+
+// NetworkRange calculates the first and last IP addresses in an IPNet
+func NetworkRange(network *net.IPNet) (net.IP, net.IP) {
+ if network == nil {
+ return nil, nil
+ }
+
+ firstIP := network.IP.Mask(network.Mask)
+ lastIP := types.GetIPCopy(firstIP)
+ for i := 0; i < len(firstIP); i++ {
+ lastIP[i] = firstIP[i] | ^network.Mask[i]
+ }
+
+ if network.IP.To4() != nil {
+ firstIP = firstIP.To4()
+ lastIP = lastIP.To4()
+ }
+
+ return firstIP, lastIP
+}
+
+// GetIfaceAddr returns the first IPv4 address and slice of IPv6 addresses for the specified network interface
+func GetIfaceAddr(name string) (net.Addr, []net.Addr, error) {
+ iface, err := net.InterfaceByName(name)
+ if err != nil {
+ return nil, nil, err
+ }
+ addrs, err := iface.Addrs()
+ if err != nil {
+ return nil, nil, err
+ }
+ var addrs4 []net.Addr
+ var addrs6 []net.Addr
+ for _, addr := range addrs {
+ ip := (addr.(*net.IPNet)).IP
+ if ip4 := ip.To4(); ip4 != nil {
+ addrs4 = append(addrs4, addr)
+ } else if ip6 := ip.To16(); len(ip6) == net.IPv6len {
+ addrs6 = append(addrs6, addr)
+ }
+ }
+ switch {
+ case len(addrs4) == 0:
+ return nil, nil, fmt.Errorf("Interface %v has no IPv4 addresses", name)
+ case len(addrs4) > 1:
+ fmt.Printf("Interface %v has more than 1 IPv4 address. Defaulting to using %v\n",
+ name, (addrs4[0].(*net.IPNet)).IP)
+ }
+ return addrs4[0], addrs6, nil
+}
+
+func genMAC(ip net.IP) net.HardwareAddr {
+ hw := make(net.HardwareAddr, 6)
+ // The first byte of the MAC address has to comply with these rules:
+ // 1. Unicast: Set the least-significant bit to 0.
+ // 2. Address is locally administered: Set the second-least-significant bit (U/L) to 1.
+ hw[0] = 0x02
+ // The first 24 bits of the MAC represent the Organizationally Unique Identifier (OUI).
+ // Since this address is locally administered, we can do whatever we want as long as
+ // it doesn't conflict with other addresses.
+ hw[1] = 0x42
+ // Fill the remaining 4 bytes based on the input
+ if ip == nil {
+ rand.Read(hw[2:])
+ } else {
+ copy(hw[2:], ip.To4())
+ }
+ return hw
+}
+
+// GenerateRandomMAC returns a new 6-byte(48-bit) hardware address (MAC)
+func GenerateRandomMAC() net.HardwareAddr {
+ return genMAC(nil)
+}
+
+// GenerateMACFromIP returns a locally administered MAC address where the 4 least
+// significant bytes are derived from the IPv4 address.
+func GenerateMACFromIP(ip net.IP) net.HardwareAddr {
+ return genMAC(ip)
+}
+
+// GenerateRandomName returns a new name joined with a prefix. This size
+// specified is used to truncate the randomly generated value
+func GenerateRandomName(prefix string, size int) (string, error) {
+ id := make([]byte, 32)
+ if _, err := io.ReadFull(rand.Reader, id); err != nil {
+ return "", err
+ }
+ return prefix + hex.EncodeToString(id)[:size], nil
+}
+
+// ReverseIP accepts a V4 or V6 IP string in the canonical form and returns a reversed IP in
+// the dotted decimal form . This is used to setup the IP to service name mapping in the optimal
+// way for the DNS PTR queries.
+func ReverseIP(IP string) string {
+ var reverseIP []string
+
+ if net.ParseIP(IP).To4() != nil {
+ reverseIP = strings.Split(IP, ".")
+ l := len(reverseIP)
+ for i, j := 0, l-1; i < l/2; i, j = i+1, j-1 {
+ reverseIP[i], reverseIP[j] = reverseIP[j], reverseIP[i]
+ }
+ } else {
+ reverseIP = strings.Split(IP, ":")
+
+ // Reversed IPv6 is represented in dotted decimal instead of the typical
+ // colon hex notation
+ for key := range reverseIP {
+ if len(reverseIP[key]) == 0 { // expand the compressed 0s
+ reverseIP[key] = strings.Repeat("0000", 8-strings.Count(IP, ":"))
+ } else if len(reverseIP[key]) < 4 { // 0-padding needed
+ reverseIP[key] = strings.Repeat("0", 4-len(reverseIP[key])) + reverseIP[key]
+ }
+ }
+
+ reverseIP = strings.Split(strings.Join(reverseIP, ""), "")
+
+ l := len(reverseIP)
+ for i, j := 0, l-1; i < l/2; i, j = i+1, j-1 {
+ reverseIP[i], reverseIP[j] = reverseIP[j], reverseIP[i]
+ }
+ }
+
+ return strings.Join(reverseIP, ".")
+}
+
+// ParseAlias parses and validates the specified string as an alias format (name:alias)
+func ParseAlias(val string) (string, string, error) {
+ if val == "" {
+ return "", "", errors.New("empty string specified for alias")
+ }
+ arr := strings.Split(val, ":")
+ if len(arr) > 2 {
+ return "", "", fmt.Errorf("bad format for alias: %s", val)
+ }
+ if len(arr) == 1 {
+ return val, val, nil
+ }
+ return arr[0], arr[1], nil
+}
+
+// ValidateAlias validates that the specified string has a valid alias format (containerName:alias).
+func ValidateAlias(val string) (string, error) {
+ if _, _, err := ParseAlias(val); err != nil {
+ return val, err
+ }
+ return val, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/netutils/utils_freebsd.go b/vendor/github.com/docker/libnetwork/netutils/utils_freebsd.go
new file mode 100644
index 0000000..02bcd32
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/netutils/utils_freebsd.go
@@ -0,0 +1,23 @@
+package netutils
+
+import (
+ "net"
+
+ "github.com/docker/libnetwork/types"
+)
+
+// ElectInterfaceAddresses looks for an interface on the OS with the specified name
+// and returns returns all its IPv4 and IPv6 addresses in CIDR notation.
+// If a failure in retrieving the addresses or no IPv4 address is found, an error is returned.
+// If the interface does not exist, it chooses from a predefined
+// list the first IPv4 address which does not conflict with other
+// interfaces on the system.
+func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error) {
+ return nil, nil, types.NotImplementedErrorf("not supported on freebsd")
+}
+
+// FindAvailableNetwork returns a network from the passed list which does not
+// overlap with existing interfaces in the system
+func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) {
+ return nil, types.NotImplementedErrorf("not supported on freebsd")
+}
diff --git a/vendor/github.com/docker/libnetwork/netutils/utils_linux.go b/vendor/github.com/docker/libnetwork/netutils/utils_linux.go
new file mode 100644
index 0000000..870cc12
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/netutils/utils_linux.go
@@ -0,0 +1,126 @@
+// +build linux
+// Network utility functions.
+
+package netutils
+
+import (
+ "fmt"
+ "net"
+ "strings"
+
+ "github.com/docker/libnetwork/ipamutils"
+ "github.com/docker/libnetwork/ns"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/resolvconf"
+ "github.com/docker/libnetwork/types"
+ "github.com/vishvananda/netlink"
+)
+
+var (
+ networkGetRoutesFct func(netlink.Link, int) ([]netlink.Route, error)
+)
+
+// CheckRouteOverlaps checks whether the passed network overlaps with any existing routes
+func CheckRouteOverlaps(toCheck *net.IPNet) error {
+ if networkGetRoutesFct == nil {
+ networkGetRoutesFct = ns.NlHandle().RouteList
+ }
+ networks, err := networkGetRoutesFct(nil, netlink.FAMILY_V4)
+ if err != nil {
+ return err
+ }
+ for _, network := range networks {
+ if network.Dst != nil && NetworkOverlaps(toCheck, network.Dst) {
+ return ErrNetworkOverlaps
+ }
+ }
+ return nil
+}
+
+// GenerateIfaceName returns an interface name using the passed in
+// prefix and the length of random bytes. The api ensures that the
+// there are is no interface which exists with that name.
+func GenerateIfaceName(nlh *netlink.Handle, prefix string, len int) (string, error) {
+ linkByName := netlink.LinkByName
+ if nlh != nil {
+ linkByName = nlh.LinkByName
+ }
+ for i := 0; i < 3; i++ {
+ name, err := GenerateRandomName(prefix, len)
+ if err != nil {
+ continue
+ }
+ _, err = linkByName(name)
+ if err != nil {
+ if strings.Contains(err.Error(), "not found") {
+ return name, nil
+ }
+ return "", err
+ }
+ }
+ return "", types.InternalErrorf("could not generate interface name")
+}
+
+// ElectInterfaceAddresses looks for an interface on the OS with the
+// specified name and returns returns all its IPv4 and IPv6 addresses in CIDR notation.
+// If a failure in retrieving the addresses or no IPv4 address is found, an error is returned.
+// If the interface does not exist, it chooses from a predefined
+// list the first IPv4 address which does not conflict with other
+// interfaces on the system.
+func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error) {
+ var (
+ v4Nets []*net.IPNet
+ v6Nets []*net.IPNet
+ )
+
+ defer osl.InitOSContext()()
+
+ link, _ := ns.NlHandle().LinkByName(name)
+ if link != nil {
+ v4addr, err := ns.NlHandle().AddrList(link, netlink.FAMILY_V4)
+ if err != nil {
+ return nil, nil, err
+ }
+ v6addr, err := ns.NlHandle().AddrList(link, netlink.FAMILY_V6)
+ if err != nil {
+ return nil, nil, err
+ }
+ for _, nlAddr := range v4addr {
+ v4Nets = append(v4Nets, nlAddr.IPNet)
+ }
+ for _, nlAddr := range v6addr {
+ v6Nets = append(v6Nets, nlAddr.IPNet)
+ }
+ }
+
+ if link == nil || len(v4Nets) == 0 {
+ // Choose from predefined broad networks
+ v4Net, err := FindAvailableNetwork(ipamutils.PredefinedBroadNetworks)
+ if err != nil {
+ return nil, nil, err
+ }
+ v4Nets = append(v4Nets, v4Net)
+ }
+
+ return v4Nets, v6Nets, nil
+}
+
+// FindAvailableNetwork returns a network from the passed list which does not
+// overlap with existing interfaces in the system
+func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) {
+ // We don't check for an error here, because we don't really care if we
+ // can't read /etc/resolv.conf. So instead we skip the append if resolvConf
+ // is nil. It either doesn't exist, or we can't read it for some reason.
+ var nameservers []string
+ if rc, err := resolvconf.Get(); err == nil {
+ nameservers = resolvconf.GetNameserversAsCIDR(rc.Content)
+ }
+ for _, nw := range list {
+ if err := CheckNameserverOverlaps(nameservers, nw); err == nil {
+ if err := CheckRouteOverlaps(nw); err == nil {
+ return nw, nil
+ }
+ }
+ }
+ return nil, fmt.Errorf("no available network")
+}
diff --git a/vendor/github.com/docker/libnetwork/netutils/utils_solaris.go b/vendor/github.com/docker/libnetwork/netutils/utils_solaris.go
new file mode 100644
index 0000000..dc67101
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/netutils/utils_solaris.go
@@ -0,0 +1,104 @@
+// +build solaris
+
+package netutils
+
+import (
+ "fmt"
+ "net"
+ "os/exec"
+ "strings"
+
+ "github.com/docker/libnetwork/ipamutils"
+ "github.com/vishvananda/netlink"
+)
+
+var (
+ networkGetRoutesFct func(netlink.Link, int) ([]netlink.Route, error)
+)
+
+// CheckRouteOverlaps checks whether the passed network overlaps with any existing routes
+func CheckRouteOverlaps(toCheck *net.IPNet) error {
+ return nil
+}
+
+// ElectInterfaceAddresses looks for an interface on the OS with the specified name
+// and returns returns all its IPv4 and IPv6 addresses in CIDR notation.
+// If a failure in retrieving the addresses or no IPv4 address is found, an error is returned.
+// If the interface does not exist, it chooses from a predefined
+// list the first IPv4 address which does not conflict with other
+// interfaces on the system.
+func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error) {
+ var (
+ v4Net *net.IPNet
+ )
+
+ out, err := exec.Command("/usr/sbin/ipadm", "show-addr",
+ "-p", "-o", "addrobj,addr").Output()
+ if err != nil {
+ fmt.Println("failed to list interfaces on system")
+ return nil, nil, err
+ }
+ alist := strings.Fields(string(out))
+ for _, a := range alist {
+ linkandaddr := strings.SplitN(a, ":", 2)
+ if len(linkandaddr) != 2 {
+ fmt.Println("failed to check interfaces on system: ", a)
+ continue
+ }
+ gw := fmt.Sprintf("%s_gw0", name)
+ link := strings.Split(linkandaddr[0], "/")[0]
+ addr := linkandaddr[1]
+ if gw != link {
+ continue
+ }
+ _, ipnet, err := net.ParseCIDR(addr)
+ if err != nil {
+ fmt.Println("failed to parse address: ", addr)
+ continue
+ }
+ v4Net = ipnet
+ break
+ }
+ if v4Net == nil {
+ v4Net, err = FindAvailableNetwork(ipamutils.PredefinedBroadNetworks)
+ if err != nil {
+ return nil, nil, err
+ }
+ }
+ return []*net.IPNet{v4Net}, nil, nil
+}
+
+// FindAvailableNetwork returns a network from the passed list which does not
+// overlap with existing interfaces in the system
+func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) {
+ out, err := exec.Command("/usr/sbin/ipadm", "show-addr",
+ "-p", "-o", "addr").Output()
+
+ if err != nil {
+ fmt.Println("failed to list interfaces on system")
+ return nil, err
+ }
+ ipaddrs := strings.Fields(string(out))
+ inuse := []*net.IPNet{}
+ for _, ip := range ipaddrs {
+ _, ipnet, err := net.ParseCIDR(ip)
+ if err != nil {
+ fmt.Println("failed to check interfaces on system: ", ip)
+ continue
+ }
+ inuse = append(inuse, ipnet)
+ }
+ for _, avail := range list {
+ is_avail := true
+ for _, ipnet := range inuse {
+ if NetworkOverlaps(avail, ipnet) {
+ is_avail = false
+ break
+ }
+ }
+ if is_avail {
+ return avail, nil
+ }
+ }
+ return nil, fmt.Errorf("no available network")
+}
diff --git a/vendor/github.com/docker/libnetwork/netutils/utils_windows.go b/vendor/github.com/docker/libnetwork/netutils/utils_windows.go
new file mode 100644
index 0000000..73af44e
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/netutils/utils_windows.go
@@ -0,0 +1,25 @@
+package netutils
+
+import (
+ "net"
+
+ "github.com/docker/libnetwork/types"
+)
+
+// ElectInterfaceAddresses looks for an interface on the OS with the specified name
+// and returns returns all its IPv4 and IPv6 addresses in CIDR notation.
+// If a failure in retrieving the addresses or no IPv4 address is found, an error is returned.
+// If the interface does not exist, it chooses from a predefined
+// list the first IPv4 address which does not conflict with other
+// interfaces on the system.
+func ElectInterfaceAddresses(name string) ([]*net.IPNet, []*net.IPNet, error) {
+ return nil, nil, types.NotImplementedErrorf("not supported on windows")
+}
+
+// FindAvailableNetwork returns a network from the passed list which does not
+// overlap with existing interfaces in the system
+
+// TODO : Use appropriate windows APIs to identify non-overlapping subnets
+func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) {
+ return nil, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/network.go b/vendor/github.com/docker/libnetwork/network.go
new file mode 100644
index 0000000..9f99064
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/network.go
@@ -0,0 +1,2030 @@
+package libnetwork
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/stringid"
+ "github.com/docker/libnetwork/common"
+ "github.com/docker/libnetwork/config"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/etchosts"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/netutils"
+ "github.com/docker/libnetwork/networkdb"
+ "github.com/docker/libnetwork/options"
+ "github.com/docker/libnetwork/types"
+)
+
+// A Network represents a logical connectivity zone that containers may
+// join using the Link method. A Network is managed by a specific driver.
+type Network interface {
+ // A user chosen name for this network.
+ Name() string
+
+ // A system generated id for this network.
+ ID() string
+
+ // The type of network, which corresponds to its managing driver.
+ Type() string
+
+ // Create a new endpoint to this network symbolically identified by the
+ // specified unique name. The options parameter carries driver specific options.
+ CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error)
+
+ // Delete the network.
+ Delete() error
+
+ // Endpoints returns the list of Endpoint(s) in this network.
+ Endpoints() []Endpoint
+
+ // WalkEndpoints uses the provided function to walk the Endpoints
+ WalkEndpoints(walker EndpointWalker)
+
+ // EndpointByName returns the Endpoint which has the passed name. If not found, the error ErrNoSuchEndpoint is returned.
+ EndpointByName(name string) (Endpoint, error)
+
+ // EndpointByID returns the Endpoint which has the passed id. If not found, the error ErrNoSuchEndpoint is returned.
+ EndpointByID(id string) (Endpoint, error)
+
+ // Return certain operational data belonging to this network
+ Info() NetworkInfo
+}
+
+// NetworkInfo returns some configuration and operational information about the network
+type NetworkInfo interface {
+ IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf)
+ IpamInfo() ([]*IpamInfo, []*IpamInfo)
+ DriverOptions() map[string]string
+ Scope() string
+ IPv6Enabled() bool
+ Internal() bool
+ Attachable() bool
+ Ingress() bool
+ ConfigFrom() string
+ ConfigOnly() bool
+ Labels() map[string]string
+ Dynamic() bool
+ Created() time.Time
+ // Peers returns a slice of PeerInfo structures which has the information about the peer
+ // nodes participating in the same overlay network. This is currently the per-network
+ // gossip cluster. For non-dynamic overlay networks and bridge networks it returns an
+ // empty slice
+ Peers() []networkdb.PeerInfo
+ //Services returns a map of services keyed by the service name with the details
+ //of all the tasks that belong to the service. Applicable only in swarm mode.
+ Services() map[string]ServiceInfo
+}
+
+// EndpointWalker is a client provided function which will be used to walk the Endpoints.
+// When the function returns true, the walk will stop.
+type EndpointWalker func(ep Endpoint) bool
+
+// ipInfo is the reverse mapping from IP to service name to serve the PTR query.
+// extResolver is set if an externl server resolves a service name to this IP.
+// Its an indication to defer PTR queries also to that external server.
+type ipInfo struct {
+ name string
+ serviceID string
+ extResolver bool
+}
+
+// svcMapEntry is the body of the element into the svcMap
+// The ip is a string because the SetMatrix does not accept non hashable values
+type svcMapEntry struct {
+ ip string
+ serviceID string
+}
+
+type svcInfo struct {
+ svcMap common.SetMatrix
+ svcIPv6Map common.SetMatrix
+ ipMap common.SetMatrix
+ service map[string][]servicePorts
+}
+
+// backing container or host's info
+type serviceTarget struct {
+ name string
+ ip net.IP
+ port uint16
+}
+
+type servicePorts struct {
+ portName string
+ proto string
+ target []serviceTarget
+}
+
+type networkDBTable struct {
+ name string
+ objType driverapi.ObjectType
+}
+
+// IpamConf contains all the ipam related configurations for a network
+type IpamConf struct {
+ // The master address pool for containers and network interfaces
+ PreferredPool string
+ // A subset of the master pool. If specified,
+ // this becomes the container pool
+ SubPool string
+ // Preferred Network Gateway address (optional)
+ Gateway string
+ // Auxiliary addresses for network driver. Must be within the master pool.
+ // libnetwork will reserve them if they fall into the container pool
+ AuxAddresses map[string]string
+}
+
+// Validate checks whether the configuration is valid
+func (c *IpamConf) Validate() error {
+ if c.Gateway != "" && nil == net.ParseIP(c.Gateway) {
+ return types.BadRequestErrorf("invalid gateway address %s in Ipam configuration", c.Gateway)
+ }
+ return nil
+}
+
+// IpamInfo contains all the ipam related operational info for a network
+type IpamInfo struct {
+ PoolID string
+ Meta map[string]string
+ driverapi.IPAMData
+}
+
+// MarshalJSON encodes IpamInfo into json message
+func (i *IpamInfo) MarshalJSON() ([]byte, error) {
+ m := map[string]interface{}{
+ "PoolID": i.PoolID,
+ }
+ v, err := json.Marshal(&i.IPAMData)
+ if err != nil {
+ return nil, err
+ }
+ m["IPAMData"] = string(v)
+
+ if i.Meta != nil {
+ m["Meta"] = i.Meta
+ }
+ return json.Marshal(m)
+}
+
+// UnmarshalJSON decodes json message into PoolData
+func (i *IpamInfo) UnmarshalJSON(data []byte) error {
+ var (
+ m map[string]interface{}
+ err error
+ )
+ if err = json.Unmarshal(data, &m); err != nil {
+ return err
+ }
+ i.PoolID = m["PoolID"].(string)
+ if v, ok := m["Meta"]; ok {
+ b, _ := json.Marshal(v)
+ if err = json.Unmarshal(b, &i.Meta); err != nil {
+ return err
+ }
+ }
+ if v, ok := m["IPAMData"]; ok {
+ if err = json.Unmarshal([]byte(v.(string)), &i.IPAMData); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+type network struct {
+ ctrlr *controller
+ name string
+ networkType string
+ id string
+ created time.Time
+ scope string // network data scope
+ labels map[string]string
+ ipamType string
+ ipamOptions map[string]string
+ addrSpace string
+ ipamV4Config []*IpamConf
+ ipamV6Config []*IpamConf
+ ipamV4Info []*IpamInfo
+ ipamV6Info []*IpamInfo
+ enableIPv6 bool
+ postIPv6 bool
+ epCnt *endpointCnt
+ generic options.Generic
+ dbIndex uint64
+ dbExists bool
+ persist bool
+ stopWatchCh chan struct{}
+ drvOnce *sync.Once
+ resolverOnce sync.Once
+ resolver []Resolver
+ internal bool
+ attachable bool
+ inDelete bool
+ ingress bool
+ driverTables []networkDBTable
+ dynamic bool
+ configOnly bool
+ configFrom string
+ sync.Mutex
+}
+
+func (n *network) Name() string {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.name
+}
+
+func (n *network) ID() string {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.id
+}
+
+func (n *network) Created() time.Time {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.created
+}
+
+func (n *network) Type() string {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.networkType
+}
+
+func (n *network) Key() []string {
+ n.Lock()
+ defer n.Unlock()
+ return []string{datastore.NetworkKeyPrefix, n.id}
+}
+
+func (n *network) KeyPrefix() []string {
+ return []string{datastore.NetworkKeyPrefix}
+}
+
+func (n *network) Value() []byte {
+ n.Lock()
+ defer n.Unlock()
+ b, err := json.Marshal(n)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (n *network) SetValue(value []byte) error {
+ return json.Unmarshal(value, n)
+}
+
+func (n *network) Index() uint64 {
+ n.Lock()
+ defer n.Unlock()
+ return n.dbIndex
+}
+
+func (n *network) SetIndex(index uint64) {
+ n.Lock()
+ n.dbIndex = index
+ n.dbExists = true
+ n.Unlock()
+}
+
+func (n *network) Exists() bool {
+ n.Lock()
+ defer n.Unlock()
+ return n.dbExists
+}
+
+func (n *network) Skip() bool {
+ n.Lock()
+ defer n.Unlock()
+ return !n.persist
+}
+
+func (n *network) New() datastore.KVObject {
+ n.Lock()
+ defer n.Unlock()
+
+ return &network{
+ ctrlr: n.ctrlr,
+ drvOnce: &sync.Once{},
+ scope: n.scope,
+ }
+}
+
+// CopyTo deep copies to the destination IpamConfig
+func (c *IpamConf) CopyTo(dstC *IpamConf) error {
+ dstC.PreferredPool = c.PreferredPool
+ dstC.SubPool = c.SubPool
+ dstC.Gateway = c.Gateway
+ if c.AuxAddresses != nil {
+ dstC.AuxAddresses = make(map[string]string, len(c.AuxAddresses))
+ for k, v := range c.AuxAddresses {
+ dstC.AuxAddresses[k] = v
+ }
+ }
+ return nil
+}
+
+// CopyTo deep copies to the destination IpamInfo
+func (i *IpamInfo) CopyTo(dstI *IpamInfo) error {
+ dstI.PoolID = i.PoolID
+ if i.Meta != nil {
+ dstI.Meta = make(map[string]string)
+ for k, v := range i.Meta {
+ dstI.Meta[k] = v
+ }
+ }
+
+ dstI.AddressSpace = i.AddressSpace
+ dstI.Pool = types.GetIPNetCopy(i.Pool)
+ dstI.Gateway = types.GetIPNetCopy(i.Gateway)
+
+ if i.AuxAddresses != nil {
+ dstI.AuxAddresses = make(map[string]*net.IPNet)
+ for k, v := range i.AuxAddresses {
+ dstI.AuxAddresses[k] = types.GetIPNetCopy(v)
+ }
+ }
+
+ return nil
+}
+
+func (n *network) validateConfiguration() error {
+ if n.configOnly {
+ // Only supports network specific configurations.
+ // Network operator configurations are not supported.
+ if n.ingress || n.internal || n.attachable || n.scope != "" {
+ return types.ForbiddenErrorf("configuration network can only contain network " +
+ "specific fields. Network operator fields like " +
+ "[ ingress | internal | attachable | scope ] are not supported.")
+ }
+ }
+ if n.configFrom != "" {
+ if n.configOnly {
+ return types.ForbiddenErrorf("a configuration network cannot depend on another configuration network")
+ }
+ if n.ipamType != "" &&
+ n.ipamType != defaultIpamForNetworkType(n.networkType) ||
+ n.enableIPv6 ||
+ len(n.labels) > 0 || len(n.ipamOptions) > 0 ||
+ len(n.ipamV4Config) > 0 || len(n.ipamV6Config) > 0 {
+ return types.ForbiddenErrorf("user specified configurations are not supported if the network depends on a configuration network")
+ }
+ if len(n.generic) > 0 {
+ if data, ok := n.generic[netlabel.GenericData]; ok {
+ var (
+ driverOptions map[string]string
+ opts interface{}
+ )
+ switch data.(type) {
+ case map[string]interface{}:
+ opts = data.(map[string]interface{})
+ case map[string]string:
+ opts = data.(map[string]string)
+ }
+ ba, err := json.Marshal(opts)
+ if err != nil {
+ return fmt.Errorf("failed to validate network configuration: %v", err)
+ }
+ if err := json.Unmarshal(ba, &driverOptions); err != nil {
+ return fmt.Errorf("failed to validate network configuration: %v", err)
+ }
+ if len(driverOptions) > 0 {
+ return types.ForbiddenErrorf("network driver options are not supported if the network depends on a configuration network")
+ }
+ }
+ }
+ }
+ return nil
+}
+
+// Applies network specific configurations
+func (n *network) applyConfigurationTo(to *network) error {
+ to.enableIPv6 = n.enableIPv6
+ if len(n.labels) > 0 {
+ to.labels = make(map[string]string, len(n.labels))
+ for k, v := range n.labels {
+ if _, ok := to.labels[k]; !ok {
+ to.labels[k] = v
+ }
+ }
+ }
+ if len(n.ipamType) != 0 {
+ to.ipamType = n.ipamType
+ }
+ if len(n.ipamOptions) > 0 {
+ to.ipamOptions = make(map[string]string, len(n.ipamOptions))
+ for k, v := range n.ipamOptions {
+ if _, ok := to.ipamOptions[k]; !ok {
+ to.ipamOptions[k] = v
+ }
+ }
+ }
+ if len(n.ipamV4Config) > 0 {
+ to.ipamV4Config = make([]*IpamConf, 0, len(n.ipamV4Config))
+ for _, v4conf := range n.ipamV4Config {
+ to.ipamV4Config = append(to.ipamV4Config, v4conf)
+ }
+ }
+ if len(n.ipamV6Config) > 0 {
+ to.ipamV6Config = make([]*IpamConf, 0, len(n.ipamV6Config))
+ for _, v6conf := range n.ipamV6Config {
+ to.ipamV6Config = append(to.ipamV6Config, v6conf)
+ }
+ }
+ if len(n.generic) > 0 {
+ to.generic = options.Generic{}
+ for k, v := range n.generic {
+ to.generic[k] = v
+ }
+ }
+ return nil
+}
+
+func (n *network) CopyTo(o datastore.KVObject) error {
+ n.Lock()
+ defer n.Unlock()
+
+ dstN := o.(*network)
+ dstN.name = n.name
+ dstN.id = n.id
+ dstN.created = n.created
+ dstN.networkType = n.networkType
+ dstN.scope = n.scope
+ dstN.dynamic = n.dynamic
+ dstN.ipamType = n.ipamType
+ dstN.enableIPv6 = n.enableIPv6
+ dstN.persist = n.persist
+ dstN.postIPv6 = n.postIPv6
+ dstN.dbIndex = n.dbIndex
+ dstN.dbExists = n.dbExists
+ dstN.drvOnce = n.drvOnce
+ dstN.internal = n.internal
+ dstN.attachable = n.attachable
+ dstN.inDelete = n.inDelete
+ dstN.ingress = n.ingress
+ dstN.configOnly = n.configOnly
+ dstN.configFrom = n.configFrom
+
+ // copy labels
+ if dstN.labels == nil {
+ dstN.labels = make(map[string]string, len(n.labels))
+ }
+ for k, v := range n.labels {
+ dstN.labels[k] = v
+ }
+
+ if n.ipamOptions != nil {
+ dstN.ipamOptions = make(map[string]string, len(n.ipamOptions))
+ for k, v := range n.ipamOptions {
+ dstN.ipamOptions[k] = v
+ }
+ }
+
+ for _, v4conf := range n.ipamV4Config {
+ dstV4Conf := &IpamConf{}
+ v4conf.CopyTo(dstV4Conf)
+ dstN.ipamV4Config = append(dstN.ipamV4Config, dstV4Conf)
+ }
+
+ for _, v4info := range n.ipamV4Info {
+ dstV4Info := &IpamInfo{}
+ v4info.CopyTo(dstV4Info)
+ dstN.ipamV4Info = append(dstN.ipamV4Info, dstV4Info)
+ }
+
+ for _, v6conf := range n.ipamV6Config {
+ dstV6Conf := &IpamConf{}
+ v6conf.CopyTo(dstV6Conf)
+ dstN.ipamV6Config = append(dstN.ipamV6Config, dstV6Conf)
+ }
+
+ for _, v6info := range n.ipamV6Info {
+ dstV6Info := &IpamInfo{}
+ v6info.CopyTo(dstV6Info)
+ dstN.ipamV6Info = append(dstN.ipamV6Info, dstV6Info)
+ }
+
+ dstN.generic = options.Generic{}
+ for k, v := range n.generic {
+ dstN.generic[k] = v
+ }
+
+ return nil
+}
+
+func (n *network) DataScope() string {
+ s := n.Scope()
+ // All swarm scope networks have local datascope
+ if s == datastore.SwarmScope {
+ s = datastore.LocalScope
+ }
+ return s
+}
+
+func (n *network) getEpCnt() *endpointCnt {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.epCnt
+}
+
+// TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
+func (n *network) MarshalJSON() ([]byte, error) {
+ netMap := make(map[string]interface{})
+ netMap["name"] = n.name
+ netMap["id"] = n.id
+ netMap["created"] = n.created
+ netMap["networkType"] = n.networkType
+ netMap["scope"] = n.scope
+ netMap["labels"] = n.labels
+ netMap["ipamType"] = n.ipamType
+ netMap["ipamOptions"] = n.ipamOptions
+ netMap["addrSpace"] = n.addrSpace
+ netMap["enableIPv6"] = n.enableIPv6
+ if n.generic != nil {
+ netMap["generic"] = n.generic
+ }
+ netMap["persist"] = n.persist
+ netMap["postIPv6"] = n.postIPv6
+ if len(n.ipamV4Config) > 0 {
+ ics, err := json.Marshal(n.ipamV4Config)
+ if err != nil {
+ return nil, err
+ }
+ netMap["ipamV4Config"] = string(ics)
+ }
+ if len(n.ipamV4Info) > 0 {
+ iis, err := json.Marshal(n.ipamV4Info)
+ if err != nil {
+ return nil, err
+ }
+ netMap["ipamV4Info"] = string(iis)
+ }
+ if len(n.ipamV6Config) > 0 {
+ ics, err := json.Marshal(n.ipamV6Config)
+ if err != nil {
+ return nil, err
+ }
+ netMap["ipamV6Config"] = string(ics)
+ }
+ if len(n.ipamV6Info) > 0 {
+ iis, err := json.Marshal(n.ipamV6Info)
+ if err != nil {
+ return nil, err
+ }
+ netMap["ipamV6Info"] = string(iis)
+ }
+ netMap["internal"] = n.internal
+ netMap["attachable"] = n.attachable
+ netMap["inDelete"] = n.inDelete
+ netMap["ingress"] = n.ingress
+ netMap["configOnly"] = n.configOnly
+ netMap["configFrom"] = n.configFrom
+ return json.Marshal(netMap)
+}
+
+// TODO : Can be made much more generic with the help of reflection (but has some golang limitations)
+func (n *network) UnmarshalJSON(b []byte) (err error) {
+ var netMap map[string]interface{}
+ if err := json.Unmarshal(b, &netMap); err != nil {
+ return err
+ }
+ n.name = netMap["name"].(string)
+ n.id = netMap["id"].(string)
+ // "created" is not available in older versions
+ if v, ok := netMap["created"]; ok {
+ // n.created is time.Time but marshalled as string
+ if err = n.created.UnmarshalText([]byte(v.(string))); err != nil {
+ logrus.Warnf("failed to unmarshal creation time %v: %v", v, err)
+ n.created = time.Time{}
+ }
+ }
+ n.networkType = netMap["networkType"].(string)
+ n.enableIPv6 = netMap["enableIPv6"].(bool)
+
+ // if we weren't unmarshaling to netMap we could simply set n.labels
+ // unfortunately, we can't because map[string]interface{} != map[string]string
+ if labels, ok := netMap["labels"].(map[string]interface{}); ok {
+ n.labels = make(map[string]string, len(labels))
+ for label, value := range labels {
+ n.labels[label] = value.(string)
+ }
+ }
+
+ if v, ok := netMap["ipamOptions"]; ok {
+ if iOpts, ok := v.(map[string]interface{}); ok {
+ n.ipamOptions = make(map[string]string, len(iOpts))
+ for k, v := range iOpts {
+ n.ipamOptions[k] = v.(string)
+ }
+ }
+ }
+
+ if v, ok := netMap["generic"]; ok {
+ n.generic = v.(map[string]interface{})
+ // Restore opts in their map[string]string form
+ if v, ok := n.generic[netlabel.GenericData]; ok {
+ var lmap map[string]string
+ ba, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+ if err := json.Unmarshal(ba, &lmap); err != nil {
+ return err
+ }
+ n.generic[netlabel.GenericData] = lmap
+ }
+ }
+ if v, ok := netMap["persist"]; ok {
+ n.persist = v.(bool)
+ }
+ if v, ok := netMap["postIPv6"]; ok {
+ n.postIPv6 = v.(bool)
+ }
+ if v, ok := netMap["ipamType"]; ok {
+ n.ipamType = v.(string)
+ } else {
+ n.ipamType = ipamapi.DefaultIPAM
+ }
+ if v, ok := netMap["addrSpace"]; ok {
+ n.addrSpace = v.(string)
+ }
+ if v, ok := netMap["ipamV4Config"]; ok {
+ if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Config); err != nil {
+ return err
+ }
+ }
+ if v, ok := netMap["ipamV4Info"]; ok {
+ if err := json.Unmarshal([]byte(v.(string)), &n.ipamV4Info); err != nil {
+ return err
+ }
+ }
+ if v, ok := netMap["ipamV6Config"]; ok {
+ if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Config); err != nil {
+ return err
+ }
+ }
+ if v, ok := netMap["ipamV6Info"]; ok {
+ if err := json.Unmarshal([]byte(v.(string)), &n.ipamV6Info); err != nil {
+ return err
+ }
+ }
+ if v, ok := netMap["internal"]; ok {
+ n.internal = v.(bool)
+ }
+ if v, ok := netMap["attachable"]; ok {
+ n.attachable = v.(bool)
+ }
+ if s, ok := netMap["scope"]; ok {
+ n.scope = s.(string)
+ }
+ if v, ok := netMap["inDelete"]; ok {
+ n.inDelete = v.(bool)
+ }
+ if v, ok := netMap["ingress"]; ok {
+ n.ingress = v.(bool)
+ }
+ if v, ok := netMap["configOnly"]; ok {
+ n.configOnly = v.(bool)
+ }
+ if v, ok := netMap["configFrom"]; ok {
+ n.configFrom = v.(string)
+ }
+ // Reconcile old networks with the recently added `--ipv6` flag
+ if !n.enableIPv6 {
+ n.enableIPv6 = len(n.ipamV6Info) > 0
+ }
+ return nil
+}
+
+// NetworkOption is an option setter function type used to pass various options to
+// NewNetwork method. The various setter functions of type NetworkOption are
+// provided by libnetwork, they look like NetworkOptionXXXX(...)
+type NetworkOption func(n *network)
+
+// NetworkOptionGeneric function returns an option setter for a Generic option defined
+// in a Dictionary of Key-Value pair
+func NetworkOptionGeneric(generic map[string]interface{}) NetworkOption {
+ return func(n *network) {
+ if n.generic == nil {
+ n.generic = make(map[string]interface{})
+ }
+ if val, ok := generic[netlabel.EnableIPv6]; ok {
+ n.enableIPv6 = val.(bool)
+ }
+ if val, ok := generic[netlabel.Internal]; ok {
+ n.internal = val.(bool)
+ }
+ for k, v := range generic {
+ n.generic[k] = v
+ }
+ }
+}
+
+// NetworkOptionIngress returns an option setter to indicate if a network is
+// an ingress network.
+func NetworkOptionIngress(ingress bool) NetworkOption {
+ return func(n *network) {
+ n.ingress = ingress
+ }
+}
+
+// NetworkOptionPersist returns an option setter to set persistence policy for a network
+func NetworkOptionPersist(persist bool) NetworkOption {
+ return func(n *network) {
+ n.persist = persist
+ }
+}
+
+// NetworkOptionEnableIPv6 returns an option setter to explicitly configure IPv6
+func NetworkOptionEnableIPv6(enableIPv6 bool) NetworkOption {
+ return func(n *network) {
+ if n.generic == nil {
+ n.generic = make(map[string]interface{})
+ }
+ n.enableIPv6 = enableIPv6
+ n.generic[netlabel.EnableIPv6] = enableIPv6
+ }
+}
+
+// NetworkOptionInternalNetwork returns an option setter to config the network
+// to be internal which disables default gateway service
+func NetworkOptionInternalNetwork() NetworkOption {
+ return func(n *network) {
+ if n.generic == nil {
+ n.generic = make(map[string]interface{})
+ }
+ n.internal = true
+ n.generic[netlabel.Internal] = true
+ }
+}
+
+// NetworkOptionAttachable returns an option setter to set attachable for a network
+func NetworkOptionAttachable(attachable bool) NetworkOption {
+ return func(n *network) {
+ n.attachable = attachable
+ }
+}
+
+// NetworkOptionScope returns an option setter to overwrite the network's scope.
+// By default the network's scope is set to the network driver's datascope.
+func NetworkOptionScope(scope string) NetworkOption {
+ return func(n *network) {
+ n.scope = scope
+ }
+}
+
+// NetworkOptionIpam function returns an option setter for the ipam configuration for this network
+func NetworkOptionIpam(ipamDriver string, addrSpace string, ipV4 []*IpamConf, ipV6 []*IpamConf, opts map[string]string) NetworkOption {
+ return func(n *network) {
+ if ipamDriver != "" {
+ n.ipamType = ipamDriver
+ if ipamDriver == ipamapi.DefaultIPAM {
+ n.ipamType = defaultIpamForNetworkType(n.Type())
+ }
+ }
+ n.ipamOptions = opts
+ n.addrSpace = addrSpace
+ n.ipamV4Config = ipV4
+ n.ipamV6Config = ipV6
+ }
+}
+
+// NetworkOptionDriverOpts function returns an option setter for any driver parameter described by a map
+func NetworkOptionDriverOpts(opts map[string]string) NetworkOption {
+ return func(n *network) {
+ if n.generic == nil {
+ n.generic = make(map[string]interface{})
+ }
+ if opts == nil {
+ opts = make(map[string]string)
+ }
+ // Store the options
+ n.generic[netlabel.GenericData] = opts
+ }
+}
+
+// NetworkOptionLabels function returns an option setter for labels specific to a network
+func NetworkOptionLabels(labels map[string]string) NetworkOption {
+ return func(n *network) {
+ n.labels = labels
+ }
+}
+
+// NetworkOptionDynamic function returns an option setter for dynamic option for a network
+func NetworkOptionDynamic() NetworkOption {
+ return func(n *network) {
+ n.dynamic = true
+ }
+}
+
+// NetworkOptionDeferIPv6Alloc instructs the network to defer the IPV6 address allocation until after the endpoint has been created
+// It is being provided to support the specific docker daemon flags where user can deterministically assign an IPv6 address
+// to a container as combination of fixed-cidr-v6 + mac-address
+// TODO: Remove this option setter once we support endpoint ipam options
+func NetworkOptionDeferIPv6Alloc(enable bool) NetworkOption {
+ return func(n *network) {
+ n.postIPv6 = enable
+ }
+}
+
+// NetworkOptionConfigOnly tells controller this network is
+// a configuration only network. It serves as a configuration
+// for other networks.
+func NetworkOptionConfigOnly() NetworkOption {
+ return func(n *network) {
+ n.configOnly = true
+ }
+}
+
+// NetworkOptionConfigFrom tells controller to pick the
+// network configuration from a configuration only network
+func NetworkOptionConfigFrom(name string) NetworkOption {
+ return func(n *network) {
+ n.configFrom = name
+ }
+}
+
+func (n *network) processOptions(options ...NetworkOption) {
+ for _, opt := range options {
+ if opt != nil {
+ opt(n)
+ }
+ }
+}
+
+func (n *network) resolveDriver(name string, load bool) (driverapi.Driver, *driverapi.Capability, error) {
+ c := n.getController()
+
+ // Check if a driver for the specified network type is available
+ d, cap := c.drvRegistry.Driver(name)
+ if d == nil {
+ if load {
+ var err error
+ err = c.loadDriver(name)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ d, cap = c.drvRegistry.Driver(name)
+ if d == nil {
+ return nil, nil, fmt.Errorf("could not resolve driver %s in registry", name)
+ }
+ } else {
+ // don't fail if driver loading is not required
+ return nil, nil, nil
+ }
+ }
+
+ return d, cap, nil
+}
+
+func (n *network) driverScope() string {
+ _, cap, err := n.resolveDriver(n.networkType, true)
+ if err != nil {
+ // If driver could not be resolved simply return an empty string
+ return ""
+ }
+
+ return cap.DataScope
+}
+
+func (n *network) driverIsMultihost() bool {
+ _, cap, err := n.resolveDriver(n.networkType, true)
+ if err != nil {
+ return false
+ }
+ return cap.ConnectivityScope == datastore.GlobalScope
+}
+
+func (n *network) driver(load bool) (driverapi.Driver, error) {
+ d, cap, err := n.resolveDriver(n.networkType, load)
+ if err != nil {
+ return nil, err
+ }
+
+ n.Lock()
+ // If load is not required, driver, cap and err may all be nil
+ if n.scope == "" && cap != nil {
+ n.scope = cap.DataScope
+ }
+ if n.dynamic {
+ // If the network is dynamic, then it is swarm
+ // scoped regardless of the backing driver.
+ n.scope = datastore.SwarmScope
+ }
+ n.Unlock()
+ return d, nil
+}
+
+func (n *network) Delete() error {
+ return n.delete(false)
+}
+
+func (n *network) delete(force bool) error {
+ n.Lock()
+ c := n.ctrlr
+ name := n.name
+ id := n.id
+ n.Unlock()
+
+ c.networkLocker.Lock(id)
+ defer c.networkLocker.Unlock(id)
+
+ n, err := c.getNetworkFromStore(id)
+ if err != nil {
+ return &UnknownNetworkError{name: name, id: id}
+ }
+
+ if !force && n.getEpCnt().EndpointCnt() != 0 {
+ if n.configOnly {
+ return types.ForbiddenErrorf("configuration network %q is in use", n.Name())
+ }
+ return &ActiveEndpointsError{name: n.name, id: n.id}
+ }
+
+ // Mark the network for deletion
+ n.inDelete = true
+ if err = c.updateToStore(n); err != nil {
+ return fmt.Errorf("error marking network %s (%s) for deletion: %v", n.Name(), n.ID(), err)
+ }
+
+ if n.ConfigFrom() != "" {
+ if t, err := c.getConfigNetwork(n.ConfigFrom()); err == nil {
+ if err := t.getEpCnt().DecEndpointCnt(); err != nil {
+ logrus.Warnf("Failed to update reference count for configuration network %q on removal of network %q: %v",
+ t.Name(), n.Name(), err)
+ }
+ } else {
+ logrus.Warnf("Could not find configuration network %q during removal of network %q", n.configOnly, n.Name())
+ }
+ }
+
+ if n.configOnly {
+ goto removeFromStore
+ }
+
+ if err = n.deleteNetwork(); err != nil {
+ if !force {
+ return err
+ }
+ logrus.Debugf("driver failed to delete stale network %s (%s): %v", n.Name(), n.ID(), err)
+ }
+
+ n.ipamRelease()
+ if err = c.updateToStore(n); err != nil {
+ logrus.Warnf("Failed to update store after ipam release for network %s (%s): %v", n.Name(), n.ID(), err)
+ }
+
+ // We are about to delete the network. Leave the gossip
+ // cluster for the network to stop all incoming network
+ // specific gossip updates before cleaning up all the service
+ // bindings for the network. But cleanup service binding
+ // before deleting the network from the store since service
+ // bindings cleanup requires the network in the store.
+ n.cancelDriverWatches()
+ if err = n.leaveCluster(); err != nil {
+ logrus.Errorf("Failed leaving network %s from the agent cluster: %v", n.Name(), err)
+ }
+
+ c.cleanupServiceBindings(n.ID())
+
+removeFromStore:
+ // deleteFromStore performs an atomic delete operation and the
+ // network.epCnt will help prevent any possible
+ // race between endpoint join and network delete
+ if err = c.deleteFromStore(n.getEpCnt()); err != nil {
+ if !force {
+ return fmt.Errorf("error deleting network endpoint count from store: %v", err)
+ }
+ logrus.Debugf("Error deleting endpoint count from store for stale network %s (%s) for deletion: %v", n.Name(), n.ID(), err)
+ }
+
+ if err = c.deleteFromStore(n); err != nil {
+ return fmt.Errorf("error deleting network from store: %v", err)
+ }
+
+ return nil
+}
+
+func (n *network) deleteNetwork() error {
+ d, err := n.driver(true)
+ if err != nil {
+ return fmt.Errorf("failed deleting network: %v", err)
+ }
+
+ if err := d.DeleteNetwork(n.ID()); err != nil {
+ // Forbidden Errors should be honored
+ if _, ok := err.(types.ForbiddenError); ok {
+ return err
+ }
+
+ if _, ok := err.(types.MaskableError); !ok {
+ logrus.Warnf("driver error deleting network %s : %v", n.name, err)
+ }
+ }
+
+ for _, resolver := range n.resolver {
+ resolver.Stop()
+ }
+ return nil
+}
+
+func (n *network) addEndpoint(ep *endpoint) error {
+ d, err := n.driver(true)
+ if err != nil {
+ return fmt.Errorf("failed to add endpoint: %v", err)
+ }
+
+ err = d.CreateEndpoint(n.id, ep.id, ep.Interface(), ep.generic)
+ if err != nil {
+ return types.InternalErrorf("failed to create endpoint %s on network %s: %v",
+ ep.Name(), n.Name(), err)
+ }
+
+ return nil
+}
+
+func (n *network) CreateEndpoint(name string, options ...EndpointOption) (Endpoint, error) {
+ var err error
+ if !config.IsValidName(name) {
+ return nil, ErrInvalidName(name)
+ }
+
+ if n.ConfigOnly() {
+ return nil, types.ForbiddenErrorf("cannot create endpoint on configuration-only network")
+ }
+
+ if _, err = n.EndpointByName(name); err == nil {
+ return nil, types.ForbiddenErrorf("endpoint with name %s already exists in network %s", name, n.Name())
+ }
+
+ ep := &endpoint{name: name, generic: make(map[string]interface{}), iface: &endpointInterface{}}
+ ep.id = stringid.GenerateRandomID()
+
+ n.ctrlr.networkLocker.Lock(n.id)
+ defer n.ctrlr.networkLocker.Unlock(n.id)
+
+ // Initialize ep.network with a possibly stale copy of n. We need this to get network from
+ // store. But once we get it from store we will have the most uptodate copy possibly.
+ ep.network = n
+ ep.locator = n.getController().clusterHostID()
+ ep.network, err = ep.getNetworkFromStore()
+ if err != nil {
+ return nil, fmt.Errorf("failed to get network during CreateEndpoint: %v", err)
+ }
+ n = ep.network
+
+ ep.processOptions(options...)
+
+ for _, llIPNet := range ep.Iface().LinkLocalAddresses() {
+ if !llIPNet.IP.IsLinkLocalUnicast() {
+ return nil, types.BadRequestErrorf("invalid link local IP address: %v", llIPNet.IP)
+ }
+ }
+
+ if opt, ok := ep.generic[netlabel.MacAddress]; ok {
+ if mac, ok := opt.(net.HardwareAddr); ok {
+ ep.iface.mac = mac
+ }
+ }
+
+ ipam, cap, err := n.getController().getIPAMDriver(n.ipamType)
+ if err != nil {
+ return nil, err
+ }
+
+ if cap.RequiresMACAddress {
+ if ep.iface.mac == nil {
+ ep.iface.mac = netutils.GenerateRandomMAC()
+ }
+ if ep.ipamOptions == nil {
+ ep.ipamOptions = make(map[string]string)
+ }
+ ep.ipamOptions[netlabel.MacAddress] = ep.iface.mac.String()
+ }
+
+ if err = ep.assignAddress(ipam, true, n.enableIPv6 && !n.postIPv6); err != nil {
+ return nil, err
+ }
+ defer func() {
+ if err != nil {
+ ep.releaseAddress()
+ }
+ }()
+
+ if err = n.addEndpoint(ep); err != nil {
+ return nil, err
+ }
+ defer func() {
+ if err != nil {
+ if e := ep.deleteEndpoint(false); e != nil {
+ logrus.Warnf("cleaning up endpoint failed %s : %v", name, e)
+ }
+ }
+ }()
+
+ if err = ep.assignAddress(ipam, false, n.enableIPv6 && n.postIPv6); err != nil {
+ return nil, err
+ }
+
+ if err = n.getController().updateToStore(ep); err != nil {
+ return nil, err
+ }
+ defer func() {
+ if err != nil {
+ if e := n.getController().deleteFromStore(ep); e != nil {
+ logrus.Warnf("error rolling back endpoint %s from store: %v", name, e)
+ }
+ }
+ }()
+
+ // Watch for service records
+ n.getController().watchSvcRecord(ep)
+ defer func() {
+ if err != nil {
+ n.getController().unWatchSvcRecord(ep)
+ }
+ }()
+
+ // Increment endpoint count to indicate completion of endpoint addition
+ if err = n.getEpCnt().IncEndpointCnt(); err != nil {
+ return nil, err
+ }
+
+ return ep, nil
+}
+
+func (n *network) Endpoints() []Endpoint {
+ var list []Endpoint
+
+ endpoints, err := n.getEndpointsFromStore()
+ if err != nil {
+ logrus.Error(err)
+ }
+
+ for _, ep := range endpoints {
+ list = append(list, ep)
+ }
+
+ return list
+}
+
+func (n *network) WalkEndpoints(walker EndpointWalker) {
+ for _, e := range n.Endpoints() {
+ if walker(e) {
+ return
+ }
+ }
+}
+
+func (n *network) EndpointByName(name string) (Endpoint, error) {
+ if name == "" {
+ return nil, ErrInvalidName(name)
+ }
+ var e Endpoint
+
+ s := func(current Endpoint) bool {
+ if current.Name() == name {
+ e = current
+ return true
+ }
+ return false
+ }
+
+ n.WalkEndpoints(s)
+
+ if e == nil {
+ return nil, ErrNoSuchEndpoint(name)
+ }
+
+ return e, nil
+}
+
+func (n *network) EndpointByID(id string) (Endpoint, error) {
+ if id == "" {
+ return nil, ErrInvalidID(id)
+ }
+
+ ep, err := n.getEndpointFromStore(id)
+ if err != nil {
+ return nil, ErrNoSuchEndpoint(id)
+ }
+
+ return ep, nil
+}
+
+func (n *network) updateSvcRecord(ep *endpoint, localEps []*endpoint, isAdd bool) {
+ var ipv6 net.IP
+ epName := ep.Name()
+ if iface := ep.Iface(); iface.Address() != nil {
+ myAliases := ep.MyAliases()
+ if iface.AddressIPv6() != nil {
+ ipv6 = iface.AddressIPv6().IP
+ }
+
+ serviceID := ep.svcID
+ if serviceID == "" {
+ serviceID = ep.ID()
+ }
+ if isAdd {
+ // If anonymous endpoint has an alias use the first alias
+ // for ip->name mapping. Not having the reverse mapping
+ // breaks some apps
+ if ep.isAnonymous() {
+ if len(myAliases) > 0 {
+ n.addSvcRecords(ep.ID(), myAliases[0], serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
+ }
+ } else {
+ n.addSvcRecords(ep.ID(), epName, serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
+ }
+ for _, alias := range myAliases {
+ n.addSvcRecords(ep.ID(), alias, serviceID, iface.Address().IP, ipv6, false, "updateSvcRecord")
+ }
+ } else {
+ if ep.isAnonymous() {
+ if len(myAliases) > 0 {
+ n.deleteSvcRecords(ep.ID(), myAliases[0], serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
+ }
+ } else {
+ n.deleteSvcRecords(ep.ID(), epName, serviceID, iface.Address().IP, ipv6, true, "updateSvcRecord")
+ }
+ for _, alias := range myAliases {
+ n.deleteSvcRecords(ep.ID(), alias, serviceID, iface.Address().IP, ipv6, false, "updateSvcRecord")
+ }
+ }
+ }
+}
+
+func addIPToName(ipMap common.SetMatrix, name, serviceID string, ip net.IP) {
+ reverseIP := netutils.ReverseIP(ip.String())
+ ipMap.Insert(reverseIP, ipInfo{
+ name: name,
+ serviceID: serviceID,
+ })
+}
+
+func delIPToName(ipMap common.SetMatrix, name, serviceID string, ip net.IP) {
+ reverseIP := netutils.ReverseIP(ip.String())
+ ipMap.Remove(reverseIP, ipInfo{
+ name: name,
+ serviceID: serviceID,
+ })
+}
+
+func addNameToIP(svcMap common.SetMatrix, name, serviceID string, epIP net.IP) {
+ svcMap.Insert(name, svcMapEntry{
+ ip: epIP.String(),
+ serviceID: serviceID,
+ })
+}
+
+func delNameToIP(svcMap common.SetMatrix, name, serviceID string, epIP net.IP) {
+ svcMap.Remove(name, svcMapEntry{
+ ip: epIP.String(),
+ serviceID: serviceID,
+ })
+}
+
+func (n *network) addSvcRecords(eID, name, serviceID string, epIP, epIPv6 net.IP, ipMapUpdate bool, method string) {
+ // Do not add service names for ingress network as this is a
+ // routing only network
+ if n.ingress {
+ return
+ }
+
+ logrus.Debugf("%s (%s).addSvcRecords(%s, %s, %s, %t) %s sid:%s", eID, n.ID()[0:7], name, epIP, epIPv6, ipMapUpdate, method, serviceID)
+
+ c := n.getController()
+ c.Lock()
+ defer c.Unlock()
+
+ sr, ok := c.svcRecords[n.ID()]
+ if !ok {
+ sr = svcInfo{
+ svcMap: common.NewSetMatrix(),
+ svcIPv6Map: common.NewSetMatrix(),
+ ipMap: common.NewSetMatrix(),
+ }
+ c.svcRecords[n.ID()] = sr
+ }
+
+ if ipMapUpdate {
+ addIPToName(sr.ipMap, name, serviceID, epIP)
+ if epIPv6 != nil {
+ addIPToName(sr.ipMap, name, serviceID, epIPv6)
+ }
+ }
+
+ addNameToIP(sr.svcMap, name, serviceID, epIP)
+ if epIPv6 != nil {
+ addNameToIP(sr.svcIPv6Map, name, serviceID, epIPv6)
+ }
+}
+
+func (n *network) deleteSvcRecords(eID, name, serviceID string, epIP net.IP, epIPv6 net.IP, ipMapUpdate bool, method string) {
+ // Do not delete service names from ingress network as this is a
+ // routing only network
+ if n.ingress {
+ return
+ }
+
+ logrus.Debugf("%s (%s).deleteSvcRecords(%s, %s, %s, %t) %s sid:%s ", eID, n.ID()[0:7], name, epIP, epIPv6, ipMapUpdate, method, serviceID)
+
+ c := n.getController()
+ c.Lock()
+ defer c.Unlock()
+
+ sr, ok := c.svcRecords[n.ID()]
+ if !ok {
+ return
+ }
+
+ if ipMapUpdate {
+ delIPToName(sr.ipMap, name, serviceID, epIP)
+
+ if epIPv6 != nil {
+ delIPToName(sr.ipMap, name, serviceID, epIPv6)
+ }
+ }
+
+ delNameToIP(sr.svcMap, name, serviceID, epIP)
+
+ if epIPv6 != nil {
+ delNameToIP(sr.svcIPv6Map, name, serviceID, epIPv6)
+ }
+}
+
+func (n *network) getSvcRecords(ep *endpoint) []etchosts.Record {
+ n.Lock()
+ defer n.Unlock()
+
+ if ep == nil {
+ return nil
+ }
+
+ var recs []etchosts.Record
+
+ epName := ep.Name()
+
+ n.ctrlr.Lock()
+ defer n.ctrlr.Unlock()
+ sr, ok := n.ctrlr.svcRecords[n.id]
+ if !ok || sr.svcMap == nil {
+ return nil
+ }
+
+ svcMapKeys := sr.svcMap.Keys()
+ // Loop on service names on this network
+ for _, k := range svcMapKeys {
+ if strings.Split(k, ".")[0] == epName {
+ continue
+ }
+ // Get all the IPs associated to this service
+ mapEntryList, ok := sr.svcMap.Get(k)
+ if !ok {
+ // The key got deleted
+ continue
+ }
+ if len(mapEntryList) == 0 {
+ logrus.Warnf("Found empty list of IP addresses for service %s on network %s (%s)", k, n.name, n.id)
+ continue
+ }
+
+ recs = append(recs, etchosts.Record{
+ Hosts: k,
+ IP: mapEntryList[0].(svcMapEntry).ip,
+ })
+ }
+
+ return recs
+}
+
+func (n *network) getController() *controller {
+ n.Lock()
+ defer n.Unlock()
+ return n.ctrlr
+}
+
+func (n *network) ipamAllocate() error {
+ if n.hasSpecialDriver() {
+ return nil
+ }
+
+ ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
+ if err != nil {
+ return err
+ }
+
+ if n.addrSpace == "" {
+ if n.addrSpace, err = n.deriveAddressSpace(); err != nil {
+ return err
+ }
+ }
+
+ err = n.ipamAllocateVersion(4, ipam)
+ if err != nil {
+ return err
+ }
+
+ defer func() {
+ if err != nil {
+ n.ipamReleaseVersion(4, ipam)
+ }
+ }()
+
+ if !n.enableIPv6 {
+ return nil
+ }
+
+ err = n.ipamAllocateVersion(6, ipam)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (n *network) requestPoolHelper(ipam ipamapi.Ipam, addressSpace, preferredPool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) {
+ for {
+ poolID, pool, meta, err := ipam.RequestPool(addressSpace, preferredPool, subPool, options, v6)
+ if err != nil {
+ return "", nil, nil, err
+ }
+
+ // If the network belongs to global scope or the pool was
+ // explicitly chosen or it is invalid, do not perform the overlap check.
+ if n.Scope() == datastore.GlobalScope || preferredPool != "" || !types.IsIPNetValid(pool) {
+ return poolID, pool, meta, nil
+ }
+
+ // Check for overlap and if none found, we have found the right pool.
+ if _, err := netutils.FindAvailableNetwork([]*net.IPNet{pool}); err == nil {
+ return poolID, pool, meta, nil
+ }
+
+ // Pool obtained in this iteration is
+ // overlapping. Hold onto the pool and don't release
+ // it yet, because we don't want ipam to give us back
+ // the same pool over again. But make sure we still do
+ // a deferred release when we have either obtained a
+ // non-overlapping pool or ran out of pre-defined
+ // pools.
+ defer func() {
+ if err := ipam.ReleasePool(poolID); err != nil {
+ logrus.Warnf("Failed to release overlapping pool %s while returning from pool request helper for network %s", pool, n.Name())
+ }
+ }()
+
+ // If this is a preferred pool request and the network
+ // is local scope and there is an overlap, we fail the
+ // network creation right here. The pool will be
+ // released in the defer.
+ if preferredPool != "" {
+ return "", nil, nil, fmt.Errorf("requested subnet %s overlaps in the host", preferredPool)
+ }
+ }
+}
+
+func (n *network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error {
+ var (
+ cfgList *[]*IpamConf
+ infoList *[]*IpamInfo
+ err error
+ )
+
+ switch ipVer {
+ case 4:
+ cfgList = &n.ipamV4Config
+ infoList = &n.ipamV4Info
+ case 6:
+ cfgList = &n.ipamV6Config
+ infoList = &n.ipamV6Info
+ default:
+ return types.InternalErrorf("incorrect ip version passed to ipam allocate: %d", ipVer)
+ }
+
+ if len(*cfgList) == 0 {
+ *cfgList = []*IpamConf{{}}
+ }
+
+ *infoList = make([]*IpamInfo, len(*cfgList))
+
+ logrus.Debugf("Allocating IPv%d pools for network %s (%s)", ipVer, n.Name(), n.ID())
+
+ for i, cfg := range *cfgList {
+ if err = cfg.Validate(); err != nil {
+ return err
+ }
+ d := &IpamInfo{}
+ (*infoList)[i] = d
+
+ d.AddressSpace = n.addrSpace
+ d.PoolID, d.Pool, d.Meta, err = n.requestPoolHelper(ipam, n.addrSpace, cfg.PreferredPool, cfg.SubPool, n.ipamOptions, ipVer == 6)
+ if err != nil {
+ return err
+ }
+
+ defer func() {
+ if err != nil {
+ if err := ipam.ReleasePool(d.PoolID); err != nil {
+ logrus.Warnf("Failed to release address pool %s after failure to create network %s (%s)", d.PoolID, n.Name(), n.ID())
+ }
+ }
+ }()
+
+ if gws, ok := d.Meta[netlabel.Gateway]; ok {
+ if d.Gateway, err = types.ParseCIDR(gws); err != nil {
+ return types.BadRequestErrorf("failed to parse gateway address (%v) returned by ipam driver: %v", gws, err)
+ }
+ }
+
+ // If user requested a specific gateway, libnetwork will allocate it
+ // irrespective of whether ipam driver returned a gateway already.
+ // If none of the above is true, libnetwork will allocate one.
+ if cfg.Gateway != "" || d.Gateway == nil {
+ var gatewayOpts = map[string]string{
+ ipamapi.RequestAddressType: netlabel.Gateway,
+ }
+ if d.Gateway, _, err = ipam.RequestAddress(d.PoolID, net.ParseIP(cfg.Gateway), gatewayOpts); err != nil {
+ return types.InternalErrorf("failed to allocate gateway (%v): %v", cfg.Gateway, err)
+ }
+ }
+
+ // Auxiliary addresses must be part of the master address pool
+ // If they fall into the container addressable pool, libnetwork will reserve them
+ if cfg.AuxAddresses != nil {
+ var ip net.IP
+ d.IPAMData.AuxAddresses = make(map[string]*net.IPNet, len(cfg.AuxAddresses))
+ for k, v := range cfg.AuxAddresses {
+ if ip = net.ParseIP(v); ip == nil {
+ return types.BadRequestErrorf("non parsable secondary ip address (%s:%s) passed for network %s", k, v, n.Name())
+ }
+ if !d.Pool.Contains(ip) {
+ return types.ForbiddenErrorf("auxilairy address: (%s:%s) must belong to the master pool: %s", k, v, d.Pool)
+ }
+ // Attempt reservation in the container addressable pool, silent the error if address does not belong to that pool
+ if d.IPAMData.AuxAddresses[k], _, err = ipam.RequestAddress(d.PoolID, ip, nil); err != nil && err != ipamapi.ErrIPOutOfRange {
+ return types.InternalErrorf("failed to allocate secondary ip address (%s:%s): %v", k, v, err)
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
+func (n *network) ipamRelease() {
+ if n.hasSpecialDriver() {
+ return
+ }
+ ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
+ if err != nil {
+ logrus.Warnf("Failed to retrieve ipam driver to release address pool(s) on delete of network %s (%s): %v", n.Name(), n.ID(), err)
+ return
+ }
+ n.ipamReleaseVersion(4, ipam)
+ n.ipamReleaseVersion(6, ipam)
+}
+
+func (n *network) ipamReleaseVersion(ipVer int, ipam ipamapi.Ipam) {
+ var infoList *[]*IpamInfo
+
+ switch ipVer {
+ case 4:
+ infoList = &n.ipamV4Info
+ case 6:
+ infoList = &n.ipamV6Info
+ default:
+ logrus.Warnf("incorrect ip version passed to ipam release: %d", ipVer)
+ return
+ }
+
+ if len(*infoList) == 0 {
+ return
+ }
+
+ logrus.Debugf("releasing IPv%d pools from network %s (%s)", ipVer, n.Name(), n.ID())
+
+ for _, d := range *infoList {
+ if d.Gateway != nil {
+ if err := ipam.ReleaseAddress(d.PoolID, d.Gateway.IP); err != nil {
+ logrus.Warnf("Failed to release gateway ip address %s on delete of network %s (%s): %v", d.Gateway.IP, n.Name(), n.ID(), err)
+ }
+ }
+ if d.IPAMData.AuxAddresses != nil {
+ for k, nw := range d.IPAMData.AuxAddresses {
+ if d.Pool.Contains(nw.IP) {
+ if err := ipam.ReleaseAddress(d.PoolID, nw.IP); err != nil && err != ipamapi.ErrIPOutOfRange {
+ logrus.Warnf("Failed to release secondary ip address %s (%v) on delete of network %s (%s): %v", k, nw.IP, n.Name(), n.ID(), err)
+ }
+ }
+ }
+ }
+ if err := ipam.ReleasePool(d.PoolID); err != nil {
+ logrus.Warnf("Failed to release address pool %s on delete of network %s (%s): %v", d.PoolID, n.Name(), n.ID(), err)
+ }
+ }
+
+ *infoList = nil
+}
+
+func (n *network) getIPInfo(ipVer int) []*IpamInfo {
+ var info []*IpamInfo
+ switch ipVer {
+ case 4:
+ info = n.ipamV4Info
+ case 6:
+ info = n.ipamV6Info
+ default:
+ return nil
+ }
+ l := make([]*IpamInfo, 0, len(info))
+ n.Lock()
+ for _, d := range info {
+ l = append(l, d)
+ }
+ n.Unlock()
+ return l
+}
+
+func (n *network) getIPData(ipVer int) []driverapi.IPAMData {
+ var info []*IpamInfo
+ switch ipVer {
+ case 4:
+ info = n.ipamV4Info
+ case 6:
+ info = n.ipamV6Info
+ default:
+ return nil
+ }
+ l := make([]driverapi.IPAMData, 0, len(info))
+ n.Lock()
+ for _, d := range info {
+ l = append(l, d.IPAMData)
+ }
+ n.Unlock()
+ return l
+}
+
+func (n *network) deriveAddressSpace() (string, error) {
+ local, global, err := n.getController().drvRegistry.IPAMDefaultAddressSpaces(n.ipamType)
+ if err != nil {
+ return "", types.NotFoundErrorf("failed to get default address space: %v", err)
+ }
+ if n.DataScope() == datastore.GlobalScope {
+ return global, nil
+ }
+ return local, nil
+}
+
+func (n *network) Info() NetworkInfo {
+ return n
+}
+
+func (n *network) Peers() []networkdb.PeerInfo {
+ if !n.Dynamic() {
+ return []networkdb.PeerInfo{}
+ }
+
+ agent := n.getController().getAgent()
+ if agent == nil {
+ return []networkdb.PeerInfo{}
+ }
+
+ return agent.networkDB.Peers(n.ID())
+}
+
+func (n *network) DriverOptions() map[string]string {
+ n.Lock()
+ defer n.Unlock()
+ if n.generic != nil {
+ if m, ok := n.generic[netlabel.GenericData]; ok {
+ return m.(map[string]string)
+ }
+ }
+ return map[string]string{}
+}
+
+func (n *network) Scope() string {
+ n.Lock()
+ defer n.Unlock()
+ return n.scope
+}
+
+func (n *network) IpamConfig() (string, map[string]string, []*IpamConf, []*IpamConf) {
+ n.Lock()
+ defer n.Unlock()
+
+ v4L := make([]*IpamConf, len(n.ipamV4Config))
+ v6L := make([]*IpamConf, len(n.ipamV6Config))
+
+ for i, c := range n.ipamV4Config {
+ cc := &IpamConf{}
+ c.CopyTo(cc)
+ v4L[i] = cc
+ }
+
+ for i, c := range n.ipamV6Config {
+ cc := &IpamConf{}
+ c.CopyTo(cc)
+ v6L[i] = cc
+ }
+
+ return n.ipamType, n.ipamOptions, v4L, v6L
+}
+
+func (n *network) IpamInfo() ([]*IpamInfo, []*IpamInfo) {
+ n.Lock()
+ defer n.Unlock()
+
+ v4Info := make([]*IpamInfo, len(n.ipamV4Info))
+ v6Info := make([]*IpamInfo, len(n.ipamV6Info))
+
+ for i, info := range n.ipamV4Info {
+ ic := &IpamInfo{}
+ info.CopyTo(ic)
+ v4Info[i] = ic
+ }
+
+ for i, info := range n.ipamV6Info {
+ ic := &IpamInfo{}
+ info.CopyTo(ic)
+ v6Info[i] = ic
+ }
+
+ return v4Info, v6Info
+}
+
+func (n *network) Internal() bool {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.internal
+}
+
+func (n *network) Attachable() bool {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.attachable
+}
+
+func (n *network) Ingress() bool {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.ingress
+}
+
+func (n *network) Dynamic() bool {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.dynamic
+}
+
+func (n *network) IPv6Enabled() bool {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.enableIPv6
+}
+
+func (n *network) ConfigFrom() string {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.configFrom
+}
+
+func (n *network) ConfigOnly() bool {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.configOnly
+}
+
+func (n *network) Labels() map[string]string {
+ n.Lock()
+ defer n.Unlock()
+
+ var lbls = make(map[string]string, len(n.labels))
+ for k, v := range n.labels {
+ lbls[k] = v
+ }
+
+ return lbls
+}
+
+func (n *network) TableEventRegister(tableName string, objType driverapi.ObjectType) error {
+ if !driverapi.IsValidType(objType) {
+ return fmt.Errorf("invalid object type %v in registering table, %s", objType, tableName)
+ }
+
+ t := networkDBTable{
+ name: tableName,
+ objType: objType,
+ }
+ n.Lock()
+ defer n.Unlock()
+ n.driverTables = append(n.driverTables, t)
+ return nil
+}
+
+// Special drivers are ones which do not need to perform any network plumbing
+func (n *network) hasSpecialDriver() bool {
+ return n.Type() == "host" || n.Type() == "null"
+}
+
+func (n *network) ResolveName(req string, ipType int) ([]net.IP, bool) {
+ var ipv6Miss bool
+
+ c := n.getController()
+ c.Lock()
+ defer c.Unlock()
+ sr, ok := c.svcRecords[n.ID()]
+
+ if !ok {
+ return nil, false
+ }
+
+ req = strings.TrimSuffix(req, ".")
+ ipSet, ok := sr.svcMap.Get(req)
+
+ if ipType == types.IPv6 {
+ // If the name resolved to v4 address then its a valid name in
+ // the docker network domain. If the network is not v6 enabled
+ // set ipv6Miss to filter the DNS query from going to external
+ // resolvers.
+ if ok && n.enableIPv6 == false {
+ ipv6Miss = true
+ }
+ ipSet, ok = sr.svcIPv6Map.Get(req)
+ }
+
+ if ok && len(ipSet) > 0 {
+ // this map is to avoid IP duplicates, this can happen during a transition period where 2 services are using the same IP
+ noDup := make(map[string]bool)
+ var ipLocal []net.IP
+ for _, ip := range ipSet {
+ if _, dup := noDup[ip.(svcMapEntry).ip]; !dup {
+ noDup[ip.(svcMapEntry).ip] = true
+ ipLocal = append(ipLocal, net.ParseIP(ip.(svcMapEntry).ip))
+ }
+ }
+ return ipLocal, ok
+ }
+
+ return nil, ipv6Miss
+}
+
+func (n *network) HandleQueryResp(name string, ip net.IP) {
+ c := n.getController()
+ c.Lock()
+ defer c.Unlock()
+ sr, ok := c.svcRecords[n.ID()]
+
+ if !ok {
+ return
+ }
+
+ ipStr := netutils.ReverseIP(ip.String())
+ // If an object with extResolver == true is already in the set this call will fail
+ // but anyway it means that has already been inserted before
+ if ok, _ := sr.ipMap.Contains(ipStr, ipInfo{name: name}); ok {
+ sr.ipMap.Remove(ipStr, ipInfo{name: name})
+ sr.ipMap.Insert(ipStr, ipInfo{name: name, extResolver: true})
+ }
+}
+
+func (n *network) ResolveIP(ip string) string {
+ c := n.getController()
+ c.Lock()
+ defer c.Unlock()
+ sr, ok := c.svcRecords[n.ID()]
+
+ if !ok {
+ return ""
+ }
+
+ nwName := n.Name()
+
+ elemSet, ok := sr.ipMap.Get(ip)
+ if !ok || len(elemSet) == 0 {
+ return ""
+ }
+ // NOTE it is possible to have more than one element in the Set, this will happen
+ // because of interleave of different events from different sources (local container create vs
+ // network db notifications)
+ // In such cases the resolution will be based on the first element of the set, and can vary
+ // during the system stabilitation
+ elem, ok := elemSet[0].(ipInfo)
+ if !ok {
+ setStr, b := sr.ipMap.String(ip)
+ logrus.Errorf("expected set of ipInfo type for key %s set:%t %s", ip, b, setStr)
+ return ""
+ }
+
+ if elem.extResolver {
+ return ""
+ }
+
+ return elem.name + "." + nwName
+}
+
+func (n *network) ResolveService(name string) ([]*net.SRV, []net.IP) {
+ c := n.getController()
+
+ srv := []*net.SRV{}
+ ip := []net.IP{}
+
+ logrus.Debugf("Service name To resolve: %v", name)
+
+ // There are DNS implementaions that allow SRV queries for names not in
+ // the format defined by RFC 2782. Hence specific validations checks are
+ // not done
+ parts := strings.Split(name, ".")
+ if len(parts) < 3 {
+ return nil, nil
+ }
+
+ portName := parts[0]
+ proto := parts[1]
+ svcName := strings.Join(parts[2:], ".")
+
+ c.Lock()
+ defer c.Unlock()
+ sr, ok := c.svcRecords[n.ID()]
+
+ if !ok {
+ return nil, nil
+ }
+
+ svcs, ok := sr.service[svcName]
+ if !ok {
+ return nil, nil
+ }
+
+ for _, svc := range svcs {
+ if svc.portName != portName {
+ continue
+ }
+ if svc.proto != proto {
+ continue
+ }
+ for _, t := range svc.target {
+ srv = append(srv,
+ &net.SRV{
+ Target: t.name,
+ Port: t.port,
+ })
+
+ ip = append(ip, t.ip)
+ }
+ }
+
+ return srv, ip
+}
+
+func (n *network) ExecFunc(f func()) error {
+ return types.NotImplementedErrorf("ExecFunc not supported by network")
+}
+
+func (n *network) NdotsSet() bool {
+ return false
+}
+
+// config-only network is looked up by name
+func (c *controller) getConfigNetwork(name string) (*network, error) {
+ var n Network
+
+ s := func(current Network) bool {
+ if current.Info().ConfigOnly() && current.Name() == name {
+ n = current
+ return true
+ }
+ return false
+ }
+
+ c.WalkNetworks(s)
+
+ if n == nil {
+ return nil, types.NotFoundErrorf("configuration network %q not found", name)
+ }
+
+ return n.(*network), nil
+}
diff --git a/vendor/github.com/docker/libnetwork/network_unix.go b/vendor/github.com/docker/libnetwork/network_unix.go
new file mode 100644
index 0000000..585261e
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/network_unix.go
@@ -0,0 +1,14 @@
+// +build !windows
+
+package libnetwork
+
+import "github.com/docker/libnetwork/ipamapi"
+
+// Stub implementations for DNS related functions
+
+func (n *network) startResolver() {
+}
+
+func defaultIpamForNetworkType(networkType string) string {
+ return ipamapi.DefaultIPAM
+}
diff --git a/vendor/github.com/docker/libnetwork/network_windows.go b/vendor/github.com/docker/libnetwork/network_windows.go
new file mode 100644
index 0000000..07a1c1d
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/network_windows.go
@@ -0,0 +1,72 @@
+// +build windows
+
+package libnetwork
+
+import (
+ "runtime"
+ "time"
+
+ "github.com/Microsoft/hcsshim"
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/drivers/windows"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/ipams/windowsipam"
+)
+
+func executeInCompartment(compartmentID uint32, x func()) {
+ runtime.LockOSThread()
+
+ if err := hcsshim.SetCurrentThreadCompartmentId(compartmentID); err != nil {
+ logrus.Error(err)
+ }
+ defer func() {
+ hcsshim.SetCurrentThreadCompartmentId(0)
+ runtime.UnlockOSThread()
+ }()
+
+ x()
+}
+
+func (n *network) startResolver() {
+ n.resolverOnce.Do(func() {
+ logrus.Debugf("Launching DNS server for network", n.Name())
+ options := n.Info().DriverOptions()
+ hnsid := options[windows.HNSID]
+
+ if hnsid == "" {
+ return
+ }
+
+ hnsresponse, err := hcsshim.HNSNetworkRequest("GET", hnsid, "")
+ if err != nil {
+ logrus.Errorf("Resolver Setup/Start failed for container %s, %q", n.Name(), err)
+ return
+ }
+
+ for _, subnet := range hnsresponse.Subnets {
+ if subnet.GatewayAddress != "" {
+ for i := 0; i < 3; i++ {
+ resolver := NewResolver(subnet.GatewayAddress, false, "", n)
+ logrus.Debugf("Binding a resolver on network %s gateway %s", n.Name(), subnet.GatewayAddress)
+ executeInCompartment(hnsresponse.DNSServerCompartment, resolver.SetupFunc(53))
+
+ if err = resolver.Start(); err != nil {
+ logrus.Errorf("Resolver Setup/Start failed for container %s, %q", n.Name(), err)
+ time.Sleep(1 * time.Second)
+ } else {
+ logrus.Debugf("Resolver bound successfully for network %s", n.Name())
+ n.resolver = append(n.resolver, resolver)
+ break
+ }
+ }
+ }
+ }
+ })
+}
+
+func defaultIpamForNetworkType(networkType string) string {
+ if windows.IsBuiltinLocalDriver(networkType) {
+ return windowsipam.DefaultIPAM
+ }
+ return ipamapi.DefaultIPAM
+}
diff --git a/vendor/github.com/docker/libnetwork/networkdb/broadcast.go b/vendor/github.com/docker/libnetwork/networkdb/broadcast.go
new file mode 100644
index 0000000..3fe9f62
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/networkdb/broadcast.go
@@ -0,0 +1,171 @@
+package networkdb
+
+import (
+ "errors"
+ "time"
+
+ "github.com/hashicorp/memberlist"
+ "github.com/hashicorp/serf/serf"
+)
+
+const broadcastTimeout = 5 * time.Second
+
+type networkEventMessage struct {
+ id string
+ node string
+ msg []byte
+}
+
+func (m *networkEventMessage) Invalidates(other memberlist.Broadcast) bool {
+ otherm := other.(*networkEventMessage)
+ return m.id == otherm.id && m.node == otherm.node
+}
+
+func (m *networkEventMessage) Message() []byte {
+ return m.msg
+}
+
+func (m *networkEventMessage) Finished() {
+}
+
+func (nDB *NetworkDB) sendNetworkEvent(nid string, event NetworkEvent_Type, ltime serf.LamportTime) error {
+ nEvent := NetworkEvent{
+ Type: event,
+ LTime: ltime,
+ NodeName: nDB.config.NodeName,
+ NetworkID: nid,
+ }
+
+ raw, err := encodeMessage(MessageTypeNetworkEvent, &nEvent)
+ if err != nil {
+ return err
+ }
+
+ nDB.networkBroadcasts.QueueBroadcast(&networkEventMessage{
+ msg: raw,
+ id: nid,
+ node: nDB.config.NodeName,
+ })
+ return nil
+}
+
+type nodeEventMessage struct {
+ msg []byte
+ notify chan<- struct{}
+}
+
+func (m *nodeEventMessage) Invalidates(other memberlist.Broadcast) bool {
+ return false
+}
+
+func (m *nodeEventMessage) Message() []byte {
+ return m.msg
+}
+
+func (m *nodeEventMessage) Finished() {
+ if m.notify != nil {
+ close(m.notify)
+ }
+}
+
+func (nDB *NetworkDB) sendNodeEvent(event NodeEvent_Type) error {
+ nEvent := NodeEvent{
+ Type: event,
+ LTime: nDB.networkClock.Increment(),
+ NodeName: nDB.config.NodeName,
+ }
+
+ raw, err := encodeMessage(MessageTypeNodeEvent, &nEvent)
+ if err != nil {
+ return err
+ }
+
+ notifyCh := make(chan struct{})
+ nDB.nodeBroadcasts.QueueBroadcast(&nodeEventMessage{
+ msg: raw,
+ notify: notifyCh,
+ })
+
+ nDB.RLock()
+ noPeers := len(nDB.nodes) <= 1
+ nDB.RUnlock()
+
+ // Message enqueued, do not wait for a send if no peer is present
+ if noPeers {
+ return nil
+ }
+
+ // Wait for the broadcast
+ select {
+ case <-notifyCh:
+ case <-time.After(broadcastTimeout):
+ return errors.New("timed out broadcasting node event")
+ }
+
+ return nil
+}
+
+type tableEventMessage struct {
+ id string
+ tname string
+ key string
+ msg []byte
+ node string
+}
+
+func (m *tableEventMessage) Invalidates(other memberlist.Broadcast) bool {
+ return false
+}
+
+func (m *tableEventMessage) Message() []byte {
+ return m.msg
+}
+
+func (m *tableEventMessage) Finished() {
+}
+
+func (nDB *NetworkDB) sendTableEvent(event TableEvent_Type, nid string, tname string, key string, entry *entry) error {
+ tEvent := TableEvent{
+ Type: event,
+ LTime: entry.ltime,
+ NodeName: nDB.config.NodeName,
+ NetworkID: nid,
+ TableName: tname,
+ Key: key,
+ Value: entry.value,
+ }
+
+ raw, err := encodeMessage(MessageTypeTableEvent, &tEvent)
+ if err != nil {
+ return err
+ }
+
+ var broadcastQ *memberlist.TransmitLimitedQueue
+ nDB.RLock()
+ thisNodeNetworks, ok := nDB.networks[nDB.config.NodeName]
+ if ok {
+ // The network may have been removed
+ network, networkOk := thisNodeNetworks[nid]
+ if !networkOk {
+ nDB.RUnlock()
+ return nil
+ }
+
+ broadcastQ = network.tableBroadcasts
+ }
+ nDB.RUnlock()
+
+ // The network may have been removed
+ if broadcastQ == nil {
+ return nil
+ }
+
+ broadcastQ.QueueBroadcast(&tableEventMessage{
+ msg: raw,
+ id: nid,
+ tname: tname,
+ key: key,
+ node: nDB.config.NodeName,
+ })
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/networkdb/cluster.go b/vendor/github.com/docker/libnetwork/networkdb/cluster.go
new file mode 100644
index 0000000..9156d0d
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/networkdb/cluster.go
@@ -0,0 +1,663 @@
+package networkdb
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/hex"
+ "fmt"
+ "log"
+ "math/big"
+ rnd "math/rand"
+ "net"
+ "strings"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/hashicorp/memberlist"
+)
+
+const (
+ reapInterval = 30 * time.Minute
+ reapPeriod = 5 * time.Second
+ retryInterval = 1 * time.Second
+ nodeReapInterval = 24 * time.Hour
+ nodeReapPeriod = 2 * time.Hour
+)
+
+type logWriter struct{}
+
+func (l *logWriter) Write(p []byte) (int, error) {
+ str := string(p)
+ str = strings.TrimSuffix(str, "\n")
+
+ switch {
+ case strings.HasPrefix(str, "[WARN] "):
+ str = strings.TrimPrefix(str, "[WARN] ")
+ logrus.Warn(str)
+ case strings.HasPrefix(str, "[DEBUG] "):
+ str = strings.TrimPrefix(str, "[DEBUG] ")
+ logrus.Debug(str)
+ case strings.HasPrefix(str, "[INFO] "):
+ str = strings.TrimPrefix(str, "[INFO] ")
+ logrus.Info(str)
+ case strings.HasPrefix(str, "[ERR] "):
+ str = strings.TrimPrefix(str, "[ERR] ")
+ logrus.Warn(str)
+ }
+
+ return len(p), nil
+}
+
+// SetKey adds a new key to the key ring
+func (nDB *NetworkDB) SetKey(key []byte) {
+ logrus.Debugf("Adding key %s", hex.EncodeToString(key)[0:5])
+ nDB.Lock()
+ defer nDB.Unlock()
+ for _, dbKey := range nDB.config.Keys {
+ if bytes.Equal(key, dbKey) {
+ return
+ }
+ }
+ nDB.config.Keys = append(nDB.config.Keys, key)
+ if nDB.keyring != nil {
+ nDB.keyring.AddKey(key)
+ }
+}
+
+// SetPrimaryKey sets the given key as the primary key. This should have
+// been added apriori through SetKey
+func (nDB *NetworkDB) SetPrimaryKey(key []byte) {
+ logrus.Debugf("Primary Key %s", hex.EncodeToString(key)[0:5])
+ nDB.RLock()
+ defer nDB.RUnlock()
+ for _, dbKey := range nDB.config.Keys {
+ if bytes.Equal(key, dbKey) {
+ if nDB.keyring != nil {
+ nDB.keyring.UseKey(dbKey)
+ }
+ break
+ }
+ }
+}
+
+// RemoveKey removes a key from the key ring. The key being removed
+// can't be the primary key
+func (nDB *NetworkDB) RemoveKey(key []byte) {
+ logrus.Debugf("Remove Key %s", hex.EncodeToString(key)[0:5])
+ nDB.Lock()
+ defer nDB.Unlock()
+ for i, dbKey := range nDB.config.Keys {
+ if bytes.Equal(key, dbKey) {
+ nDB.config.Keys = append(nDB.config.Keys[:i], nDB.config.Keys[i+1:]...)
+ if nDB.keyring != nil {
+ nDB.keyring.RemoveKey(dbKey)
+ }
+ break
+ }
+ }
+}
+
+func (nDB *NetworkDB) clusterInit() error {
+ config := memberlist.DefaultLANConfig()
+ config.Name = nDB.config.NodeName
+ config.BindAddr = nDB.config.BindAddr
+ config.AdvertiseAddr = nDB.config.AdvertiseAddr
+
+ if nDB.config.BindPort != 0 {
+ config.BindPort = nDB.config.BindPort
+ }
+
+ config.ProtocolVersion = memberlist.ProtocolVersion2Compatible
+ config.Delegate = &delegate{nDB: nDB}
+ config.Events = &eventDelegate{nDB: nDB}
+ // custom logger that does not add time or date, so they are not
+ // duplicated by logrus
+ config.Logger = log.New(&logWriter{}, "", 0)
+
+ var err error
+ if len(nDB.config.Keys) > 0 {
+ for i, key := range nDB.config.Keys {
+ logrus.Debugf("Encryption key %d: %s", i+1, hex.EncodeToString(key)[0:5])
+ }
+ nDB.keyring, err = memberlist.NewKeyring(nDB.config.Keys, nDB.config.Keys[0])
+ if err != nil {
+ return err
+ }
+ config.Keyring = nDB.keyring
+ }
+
+ nDB.networkBroadcasts = &memberlist.TransmitLimitedQueue{
+ NumNodes: func() int {
+ nDB.RLock()
+ num := len(nDB.nodes)
+ nDB.RUnlock()
+ return num
+ },
+ RetransmitMult: config.RetransmitMult,
+ }
+
+ nDB.nodeBroadcasts = &memberlist.TransmitLimitedQueue{
+ NumNodes: func() int {
+ nDB.RLock()
+ num := len(nDB.nodes)
+ nDB.RUnlock()
+ return num
+ },
+ RetransmitMult: config.RetransmitMult,
+ }
+
+ mlist, err := memberlist.Create(config)
+ if err != nil {
+ return fmt.Errorf("failed to create memberlist: %v", err)
+ }
+
+ nDB.stopCh = make(chan struct{})
+ nDB.memberlist = mlist
+
+ for _, trigger := range []struct {
+ interval time.Duration
+ fn func()
+ }{
+ {reapPeriod, nDB.reapState},
+ {config.GossipInterval, nDB.gossip},
+ {config.PushPullInterval, nDB.bulkSyncTables},
+ {retryInterval, nDB.reconnectNode},
+ {nodeReapPeriod, nDB.reapDeadNode},
+ } {
+ t := time.NewTicker(trigger.interval)
+ go nDB.triggerFunc(trigger.interval, t.C, nDB.stopCh, trigger.fn)
+ nDB.tickers = append(nDB.tickers, t)
+ }
+
+ return nil
+}
+
+func (nDB *NetworkDB) retryJoin(members []string, stop <-chan struct{}) {
+ t := time.NewTicker(retryInterval)
+ defer t.Stop()
+
+ for {
+ select {
+ case <-t.C:
+ if _, err := nDB.memberlist.Join(members); err != nil {
+ logrus.Errorf("Failed to join memberlist %s on retry: %v", members, err)
+ continue
+ }
+ if err := nDB.sendNodeEvent(NodeEventTypeJoin); err != nil {
+ logrus.Errorf("failed to send node join on retry: %v", err)
+ continue
+ }
+ return
+ case <-stop:
+ return
+ }
+ }
+
+}
+
+func (nDB *NetworkDB) clusterJoin(members []string) error {
+ mlist := nDB.memberlist
+
+ if _, err := mlist.Join(members); err != nil {
+ // Incase of failure, keep retrying join until it succeeds or the cluster is shutdown.
+ go nDB.retryJoin(members, nDB.stopCh)
+
+ return fmt.Errorf("could not join node to memberlist: %v", err)
+ }
+
+ if err := nDB.sendNodeEvent(NodeEventTypeJoin); err != nil {
+ return fmt.Errorf("failed to send node join: %v", err)
+ }
+
+ return nil
+}
+
+func (nDB *NetworkDB) clusterLeave() error {
+ mlist := nDB.memberlist
+
+ if err := nDB.sendNodeEvent(NodeEventTypeLeave); err != nil {
+ logrus.Errorf("failed to send node leave: %v", err)
+ }
+
+ if err := mlist.Leave(time.Second); err != nil {
+ return err
+ }
+
+ close(nDB.stopCh)
+
+ for _, t := range nDB.tickers {
+ t.Stop()
+ }
+
+ return mlist.Shutdown()
+}
+
+func (nDB *NetworkDB) triggerFunc(stagger time.Duration, C <-chan time.Time, stop <-chan struct{}, f func()) {
+ // Use a random stagger to avoid syncronizing
+ randStagger := time.Duration(uint64(rnd.Int63()) % uint64(stagger))
+ select {
+ case <-time.After(randStagger):
+ case <-stop:
+ return
+ }
+ for {
+ select {
+ case <-C:
+ f()
+ case <-stop:
+ return
+ }
+ }
+}
+
+func (nDB *NetworkDB) reapDeadNode() {
+ nDB.Lock()
+ defer nDB.Unlock()
+ for id, n := range nDB.failedNodes {
+ if n.reapTime > 0 {
+ n.reapTime -= nodeReapPeriod
+ continue
+ }
+ logrus.Debugf("Removing failed node %v from gossip cluster", n.Name)
+ delete(nDB.failedNodes, id)
+ }
+}
+
+func (nDB *NetworkDB) reconnectNode() {
+ nDB.RLock()
+ if len(nDB.failedNodes) == 0 {
+ nDB.RUnlock()
+ return
+ }
+
+ nodes := make([]*node, 0, len(nDB.failedNodes))
+ for _, n := range nDB.failedNodes {
+ nodes = append(nodes, n)
+ }
+ nDB.RUnlock()
+
+ node := nodes[randomOffset(len(nodes))]
+ addr := net.UDPAddr{IP: node.Addr, Port: int(node.Port)}
+
+ if _, err := nDB.memberlist.Join([]string{addr.String()}); err != nil {
+ return
+ }
+
+ if err := nDB.sendNodeEvent(NodeEventTypeJoin); err != nil {
+ return
+ }
+
+ // Update all the local table state to a new time to
+ // force update on the node we are trying to rejoin, just in
+ // case that node has these in deleting state still. This is
+ // facilitate fast convergence after recovering from a gossip
+ // failure.
+ nDB.updateLocalTableTime()
+
+ logrus.Debugf("Initiating bulk sync with node %s after reconnect", node.Name)
+ nDB.bulkSync([]string{node.Name}, true)
+}
+
+// For timing the entry deletion in the repaer APIs that doesn't use monotonic clock
+// source (time.Now, Sub etc.) should be avoided. Hence we use reapTime in every
+// entry which is set initially to reapInterval and decremented by reapPeriod every time
+// the reaper runs. NOTE nDB.reapTableEntries updates the reapTime with a readlock. This
+// is safe as long as no other concurrent path touches the reapTime field.
+func (nDB *NetworkDB) reapState() {
+ nDB.reapNetworks()
+ nDB.reapTableEntries()
+}
+
+func (nDB *NetworkDB) reapNetworks() {
+ nDB.Lock()
+ for name, nn := range nDB.networks {
+ for id, n := range nn {
+ if n.leaving {
+ if n.reapTime <= 0 {
+ delete(nn, id)
+ nDB.deleteNetworkNode(id, name)
+ continue
+ }
+ n.reapTime -= reapPeriod
+ }
+ }
+ }
+ nDB.Unlock()
+}
+
+func (nDB *NetworkDB) reapTableEntries() {
+ var paths []string
+
+ nDB.RLock()
+ nDB.indexes[byTable].Walk(func(path string, v interface{}) bool {
+ entry, ok := v.(*entry)
+ if !ok {
+ return false
+ }
+
+ if !entry.deleting {
+ return false
+ }
+ if entry.reapTime > 0 {
+ entry.reapTime -= reapPeriod
+ return false
+ }
+ paths = append(paths, path)
+ return false
+ })
+ nDB.RUnlock()
+
+ nDB.Lock()
+ for _, path := range paths {
+ params := strings.Split(path[1:], "/")
+ tname := params[0]
+ nid := params[1]
+ key := params[2]
+
+ if _, ok := nDB.indexes[byTable].Delete(fmt.Sprintf("/%s/%s/%s", tname, nid, key)); !ok {
+ logrus.Errorf("Could not delete entry in table %s with network id %s and key %s as it does not exist", tname, nid, key)
+ }
+
+ if _, ok := nDB.indexes[byNetwork].Delete(fmt.Sprintf("/%s/%s/%s", nid, tname, key)); !ok {
+ logrus.Errorf("Could not delete entry in network %s with table name %s and key %s as it does not exist", nid, tname, key)
+ }
+ }
+ nDB.Unlock()
+}
+
+func (nDB *NetworkDB) gossip() {
+ networkNodes := make(map[string][]string)
+ nDB.RLock()
+ thisNodeNetworks := nDB.networks[nDB.config.NodeName]
+ for nid := range thisNodeNetworks {
+ networkNodes[nid] = nDB.networkNodes[nid]
+
+ }
+ nDB.RUnlock()
+
+ for nid, nodes := range networkNodes {
+ mNodes := nDB.mRandomNodes(3, nodes)
+ bytesAvail := udpSendBuf - compoundHeaderOverhead
+
+ nDB.RLock()
+ network, ok := thisNodeNetworks[nid]
+ nDB.RUnlock()
+ if !ok || network == nil {
+ // It is normal for the network to be removed
+ // between the time we collect the network
+ // attachments of this node and processing
+ // them here.
+ continue
+ }
+
+ broadcastQ := network.tableBroadcasts
+
+ if broadcastQ == nil {
+ logrus.Errorf("Invalid broadcastQ encountered while gossiping for network %s", nid)
+ continue
+ }
+
+ msgs := broadcastQ.GetBroadcasts(compoundOverhead, bytesAvail)
+ if len(msgs) == 0 {
+ continue
+ }
+
+ // Create a compound message
+ compound := makeCompoundMessage(msgs)
+
+ for _, node := range mNodes {
+ nDB.RLock()
+ mnode := nDB.nodes[node]
+ nDB.RUnlock()
+
+ if mnode == nil {
+ break
+ }
+
+ // Send the compound message
+ if err := nDB.memberlist.SendToUDP(&mnode.Node, compound); err != nil {
+ logrus.Errorf("Failed to send gossip to %s: %s", mnode.Addr, err)
+ }
+ }
+ }
+}
+
+func (nDB *NetworkDB) bulkSyncTables() {
+ var networks []string
+ nDB.RLock()
+ for nid, network := range nDB.networks[nDB.config.NodeName] {
+ if network.leaving {
+ continue
+ }
+ networks = append(networks, nid)
+ }
+ nDB.RUnlock()
+
+ for {
+ if len(networks) == 0 {
+ break
+ }
+
+ nid := networks[0]
+ networks = networks[1:]
+
+ nDB.RLock()
+ nodes := nDB.networkNodes[nid]
+ nDB.RUnlock()
+
+ // No peer nodes on this network. Move on.
+ if len(nodes) == 0 {
+ continue
+ }
+
+ completed, err := nDB.bulkSync(nodes, false)
+ if err != nil {
+ logrus.Errorf("periodic bulk sync failure for network %s: %v", nid, err)
+ continue
+ }
+
+ // Remove all the networks for which we have
+ // successfully completed bulk sync in this iteration.
+ updatedNetworks := make([]string, 0, len(networks))
+ for _, nid := range networks {
+ var found bool
+ for _, completedNid := range completed {
+ if nid == completedNid {
+ found = true
+ break
+ }
+ }
+
+ if !found {
+ updatedNetworks = append(updatedNetworks, nid)
+ }
+ }
+
+ networks = updatedNetworks
+ }
+}
+
+func (nDB *NetworkDB) bulkSync(nodes []string, all bool) ([]string, error) {
+ if !all {
+ // Get 2 random nodes. 2nd node will be tried if the bulk sync to
+ // 1st node fails.
+ nodes = nDB.mRandomNodes(2, nodes)
+ }
+
+ if len(nodes) == 0 {
+ return nil, nil
+ }
+
+ var err error
+ var networks []string
+ for _, node := range nodes {
+ if node == nDB.config.NodeName {
+ continue
+ }
+ logrus.Debugf("%s: Initiating bulk sync with node %v", nDB.config.NodeName, node)
+ networks = nDB.findCommonNetworks(node)
+ err = nDB.bulkSyncNode(networks, node, true)
+ // if its periodic bulksync stop after the first successful sync
+ if !all && err == nil {
+ break
+ }
+ if err != nil {
+ err = fmt.Errorf("bulk sync to node %s failed: %v", node, err)
+ logrus.Warn(err.Error())
+ }
+ }
+
+ if err != nil {
+ return nil, err
+ }
+
+ return networks, nil
+}
+
+// Bulk sync all the table entries belonging to a set of networks to a
+// single peer node. It can be unsolicited or can be in response to an
+// unsolicited bulk sync
+func (nDB *NetworkDB) bulkSyncNode(networks []string, node string, unsolicited bool) error {
+ var msgs [][]byte
+
+ var unsolMsg string
+ if unsolicited {
+ unsolMsg = "unsolicited"
+ }
+
+ logrus.Debugf("%s: Initiating %s bulk sync for networks %v with node %s", nDB.config.NodeName, unsolMsg, networks, node)
+
+ nDB.RLock()
+ mnode := nDB.nodes[node]
+ if mnode == nil {
+ nDB.RUnlock()
+ return nil
+ }
+
+ for _, nid := range networks {
+ nDB.indexes[byNetwork].WalkPrefix(fmt.Sprintf("/%s", nid), func(path string, v interface{}) bool {
+ entry, ok := v.(*entry)
+ if !ok {
+ return false
+ }
+
+ eType := TableEventTypeCreate
+ if entry.deleting {
+ eType = TableEventTypeDelete
+ }
+
+ params := strings.Split(path[1:], "/")
+ tEvent := TableEvent{
+ Type: eType,
+ LTime: entry.ltime,
+ NodeName: entry.node,
+ NetworkID: nid,
+ TableName: params[1],
+ Key: params[2],
+ Value: entry.value,
+ }
+
+ msg, err := encodeMessage(MessageTypeTableEvent, &tEvent)
+ if err != nil {
+ logrus.Errorf("Encode failure during bulk sync: %#v", tEvent)
+ return false
+ }
+
+ msgs = append(msgs, msg)
+ return false
+ })
+ }
+ nDB.RUnlock()
+
+ // Create a compound message
+ compound := makeCompoundMessage(msgs)
+
+ bsm := BulkSyncMessage{
+ LTime: nDB.tableClock.Time(),
+ Unsolicited: unsolicited,
+ NodeName: nDB.config.NodeName,
+ Networks: networks,
+ Payload: compound,
+ }
+
+ buf, err := encodeMessage(MessageTypeBulkSync, &bsm)
+ if err != nil {
+ return fmt.Errorf("failed to encode bulk sync message: %v", err)
+ }
+
+ nDB.Lock()
+ ch := make(chan struct{})
+ nDB.bulkSyncAckTbl[node] = ch
+ nDB.Unlock()
+
+ err = nDB.memberlist.SendToTCP(&mnode.Node, buf)
+ if err != nil {
+ nDB.Lock()
+ delete(nDB.bulkSyncAckTbl, node)
+ nDB.Unlock()
+
+ return fmt.Errorf("failed to send a TCP message during bulk sync: %v", err)
+ }
+
+ // Wait on a response only if it is unsolicited.
+ if unsolicited {
+ startTime := time.Now()
+ t := time.NewTimer(30 * time.Second)
+ select {
+ case <-t.C:
+ logrus.Errorf("Bulk sync to node %s timed out", node)
+ case <-ch:
+ logrus.Debugf("%s: Bulk sync to node %s took %s", nDB.config.NodeName, node, time.Now().Sub(startTime))
+ }
+ t.Stop()
+ }
+
+ return nil
+}
+
+// Returns a random offset between 0 and n
+func randomOffset(n int) int {
+ if n == 0 {
+ return 0
+ }
+
+ val, err := rand.Int(rand.Reader, big.NewInt(int64(n)))
+ if err != nil {
+ logrus.Errorf("Failed to get a random offset: %v", err)
+ return 0
+ }
+
+ return int(val.Int64())
+}
+
+// mRandomNodes is used to select up to m random nodes. It is possible
+// that less than m nodes are returned.
+func (nDB *NetworkDB) mRandomNodes(m int, nodes []string) []string {
+ n := len(nodes)
+ mNodes := make([]string, 0, m)
+OUTER:
+ // Probe up to 3*n times, with large n this is not necessary
+ // since k << n, but with small n we want search to be
+ // exhaustive
+ for i := 0; i < 3*n && len(mNodes) < m; i++ {
+ // Get random node
+ idx := randomOffset(n)
+ node := nodes[idx]
+
+ if node == nDB.config.NodeName {
+ continue
+ }
+
+ // Check if we have this node already
+ for j := 0; j < len(mNodes); j++ {
+ if node == mNodes[j] {
+ continue OUTER
+ }
+ }
+
+ // Append the node
+ mNodes = append(mNodes, node)
+ }
+
+ return mNodes
+}
diff --git a/vendor/github.com/docker/libnetwork/networkdb/delegate.go b/vendor/github.com/docker/libnetwork/networkdb/delegate.go
new file mode 100644
index 0000000..6df3583
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/networkdb/delegate.go
@@ -0,0 +1,516 @@
+package networkdb
+
+import (
+ "fmt"
+ "net"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/gogo/protobuf/proto"
+)
+
+type delegate struct {
+ nDB *NetworkDB
+}
+
+func (d *delegate) NodeMeta(limit int) []byte {
+ return []byte{}
+}
+
+func (nDB *NetworkDB) getNode(nEvent *NodeEvent) *node {
+ nDB.Lock()
+ defer nDB.Unlock()
+
+ for _, nodes := range []map[string]*node{
+ nDB.failedNodes,
+ nDB.leftNodes,
+ nDB.nodes,
+ } {
+ if n, ok := nodes[nEvent.NodeName]; ok {
+ if n.ltime >= nEvent.LTime {
+ return nil
+ }
+ return n
+ }
+ }
+ return nil
+}
+
+func (nDB *NetworkDB) checkAndGetNode(nEvent *NodeEvent) *node {
+ nDB.Lock()
+ defer nDB.Unlock()
+
+ for _, nodes := range []map[string]*node{
+ nDB.failedNodes,
+ nDB.leftNodes,
+ nDB.nodes,
+ } {
+ if n, ok := nodes[nEvent.NodeName]; ok {
+ if n.ltime >= nEvent.LTime {
+ return nil
+ }
+
+ delete(nodes, n.Name)
+ return n
+ }
+ }
+
+ return nil
+}
+
+func (nDB *NetworkDB) purgeSameNode(n *node) {
+ nDB.Lock()
+ defer nDB.Unlock()
+
+ prefix := strings.Split(n.Name, "-")[0]
+ for _, nodes := range []map[string]*node{
+ nDB.failedNodes,
+ nDB.leftNodes,
+ nDB.nodes,
+ } {
+ var nodeNames []string
+ for name, node := range nodes {
+ if strings.HasPrefix(name, prefix) && n.Addr.Equal(node.Addr) {
+ nodeNames = append(nodeNames, name)
+ }
+ }
+
+ for _, name := range nodeNames {
+ delete(nodes, name)
+ }
+ }
+}
+
+func (nDB *NetworkDB) handleNodeEvent(nEvent *NodeEvent) bool {
+ // Update our local clock if the received messages has newer
+ // time.
+ nDB.networkClock.Witness(nEvent.LTime)
+
+ n := nDB.getNode(nEvent)
+ if n == nil {
+ return false
+ }
+ // If its a node leave event for a manager and this is the only manager we
+ // know of we want the reconnect logic to kick in. In a single manager
+ // cluster manager's gossip can't be bootstrapped unless some other node
+ // connects to it.
+ if len(nDB.bootStrapIP) == 1 && nEvent.Type == NodeEventTypeLeave {
+ for _, ip := range nDB.bootStrapIP {
+ if ip.Equal(n.Addr) {
+ n.ltime = nEvent.LTime
+ return true
+ }
+ }
+ }
+
+ n = nDB.checkAndGetNode(nEvent)
+
+ nDB.purgeSameNode(n)
+ n.ltime = nEvent.LTime
+
+ switch nEvent.Type {
+ case NodeEventTypeJoin:
+ nDB.Lock()
+ nDB.nodes[n.Name] = n
+ nDB.Unlock()
+ logrus.Infof("Node join event for %s/%s", n.Name, n.Addr)
+ return true
+ case NodeEventTypeLeave:
+ nDB.Lock()
+ nDB.leftNodes[n.Name] = n
+ nDB.Unlock()
+ logrus.Infof("Node leave event for %s/%s", n.Name, n.Addr)
+ return true
+ }
+
+ return false
+}
+
+func (nDB *NetworkDB) handleNetworkEvent(nEvent *NetworkEvent) bool {
+ var flushEntries bool
+ // Update our local clock if the received messages has newer
+ // time.
+ nDB.networkClock.Witness(nEvent.LTime)
+
+ nDB.Lock()
+ defer func() {
+ nDB.Unlock()
+ // When a node leaves a network on the last task removal cleanup the
+ // local entries for this network & node combination. When the tasks
+ // on a network are removed we could have missed the gossip updates.
+ // Not doing this cleanup can leave stale entries because bulksyncs
+ // from the node will no longer include this network state.
+ //
+ // deleteNodeNetworkEntries takes nDB lock.
+ if flushEntries {
+ nDB.deleteNodeNetworkEntries(nEvent.NetworkID, nEvent.NodeName)
+ }
+ }()
+
+ if nEvent.NodeName == nDB.config.NodeName {
+ return false
+ }
+
+ nodeNetworks, ok := nDB.networks[nEvent.NodeName]
+ if !ok {
+ // We haven't heard about this node at all. Ignore the leave
+ if nEvent.Type == NetworkEventTypeLeave {
+ return false
+ }
+
+ nodeNetworks = make(map[string]*network)
+ nDB.networks[nEvent.NodeName] = nodeNetworks
+ }
+
+ if n, ok := nodeNetworks[nEvent.NetworkID]; ok {
+ // We have the latest state. Ignore the event
+ // since it is stale.
+ if n.ltime >= nEvent.LTime {
+ return false
+ }
+
+ n.ltime = nEvent.LTime
+ n.leaving = nEvent.Type == NetworkEventTypeLeave
+ if n.leaving {
+ n.reapTime = reapInterval
+ flushEntries = true
+ }
+
+ nDB.addNetworkNode(nEvent.NetworkID, nEvent.NodeName)
+ return true
+ }
+
+ if nEvent.Type == NetworkEventTypeLeave {
+ return false
+ }
+
+ // This remote network join is being seen the first time.
+ nodeNetworks[nEvent.NetworkID] = &network{
+ id: nEvent.NetworkID,
+ ltime: nEvent.LTime,
+ }
+
+ nDB.addNetworkNode(nEvent.NetworkID, nEvent.NodeName)
+ return true
+}
+
+func (nDB *NetworkDB) handleTableEvent(tEvent *TableEvent) bool {
+ // Update our local clock if the received messages has newer
+ // time.
+ nDB.tableClock.Witness(tEvent.LTime)
+
+ // Ignore the table events for networks that are in the process of going away
+ nDB.RLock()
+ networks := nDB.networks[nDB.config.NodeName]
+ network, ok := networks[tEvent.NetworkID]
+ nDB.RUnlock()
+ if !ok || network.leaving {
+ return true
+ }
+
+ e, err := nDB.getEntry(tEvent.TableName, tEvent.NetworkID, tEvent.Key)
+ if err != nil && tEvent.Type == TableEventTypeDelete {
+ // If it is a delete event and we don't have the entry here nothing to do.
+ return false
+ }
+
+ if err == nil {
+ // We have the latest state. Ignore the event
+ // since it is stale.
+ if e.ltime >= tEvent.LTime {
+ return false
+ }
+ }
+
+ e = &entry{
+ ltime: tEvent.LTime,
+ node: tEvent.NodeName,
+ value: tEvent.Value,
+ deleting: tEvent.Type == TableEventTypeDelete,
+ }
+
+ if e.deleting {
+ e.reapTime = reapInterval
+ }
+
+ nDB.Lock()
+ nDB.indexes[byTable].Insert(fmt.Sprintf("/%s/%s/%s", tEvent.TableName, tEvent.NetworkID, tEvent.Key), e)
+ nDB.indexes[byNetwork].Insert(fmt.Sprintf("/%s/%s/%s", tEvent.NetworkID, tEvent.TableName, tEvent.Key), e)
+ nDB.Unlock()
+
+ var op opType
+ switch tEvent.Type {
+ case TableEventTypeCreate:
+ op = opCreate
+ case TableEventTypeUpdate:
+ op = opUpdate
+ case TableEventTypeDelete:
+ op = opDelete
+ }
+
+ nDB.broadcaster.Write(makeEvent(op, tEvent.TableName, tEvent.NetworkID, tEvent.Key, tEvent.Value))
+ return true
+}
+
+func (nDB *NetworkDB) handleCompound(buf []byte, isBulkSync bool) {
+ // Decode the parts
+ parts, err := decodeCompoundMessage(buf)
+ if err != nil {
+ logrus.Errorf("Failed to decode compound request: %v", err)
+ return
+ }
+
+ // Handle each message
+ for _, part := range parts {
+ nDB.handleMessage(part, isBulkSync)
+ }
+}
+
+func (nDB *NetworkDB) handleTableMessage(buf []byte, isBulkSync bool) {
+ var tEvent TableEvent
+ if err := proto.Unmarshal(buf, &tEvent); err != nil {
+ logrus.Errorf("Error decoding table event message: %v", err)
+ return
+ }
+
+ // Ignore messages that this node generated.
+ if tEvent.NodeName == nDB.config.NodeName {
+ return
+ }
+
+ // Do not rebroadcast a bulk sync
+ if rebroadcast := nDB.handleTableEvent(&tEvent); rebroadcast && !isBulkSync {
+ var err error
+ buf, err = encodeRawMessage(MessageTypeTableEvent, buf)
+ if err != nil {
+ logrus.Errorf("Error marshalling gossip message for network event rebroadcast: %v", err)
+ return
+ }
+
+ nDB.RLock()
+ n, ok := nDB.networks[nDB.config.NodeName][tEvent.NetworkID]
+ nDB.RUnlock()
+
+ if !ok {
+ return
+ }
+
+ broadcastQ := n.tableBroadcasts
+
+ if broadcastQ == nil {
+ return
+ }
+
+ broadcastQ.QueueBroadcast(&tableEventMessage{
+ msg: buf,
+ id: tEvent.NetworkID,
+ tname: tEvent.TableName,
+ key: tEvent.Key,
+ node: nDB.config.NodeName,
+ })
+ }
+}
+
+func (nDB *NetworkDB) handleNodeMessage(buf []byte) {
+ var nEvent NodeEvent
+ if err := proto.Unmarshal(buf, &nEvent); err != nil {
+ logrus.Errorf("Error decoding node event message: %v", err)
+ return
+ }
+
+ if rebroadcast := nDB.handleNodeEvent(&nEvent); rebroadcast {
+ var err error
+ buf, err = encodeRawMessage(MessageTypeNodeEvent, buf)
+ if err != nil {
+ logrus.Errorf("Error marshalling gossip message for node event rebroadcast: %v", err)
+ return
+ }
+
+ nDB.nodeBroadcasts.QueueBroadcast(&nodeEventMessage{
+ msg: buf,
+ })
+ }
+}
+
+func (nDB *NetworkDB) handleNetworkMessage(buf []byte) {
+ var nEvent NetworkEvent
+ if err := proto.Unmarshal(buf, &nEvent); err != nil {
+ logrus.Errorf("Error decoding network event message: %v", err)
+ return
+ }
+
+ if rebroadcast := nDB.handleNetworkEvent(&nEvent); rebroadcast {
+ var err error
+ buf, err = encodeRawMessage(MessageTypeNetworkEvent, buf)
+ if err != nil {
+ logrus.Errorf("Error marshalling gossip message for network event rebroadcast: %v", err)
+ return
+ }
+
+ nDB.networkBroadcasts.QueueBroadcast(&networkEventMessage{
+ msg: buf,
+ id: nEvent.NetworkID,
+ node: nEvent.NodeName,
+ })
+ }
+}
+
+func (nDB *NetworkDB) handleBulkSync(buf []byte) {
+ var bsm BulkSyncMessage
+ if err := proto.Unmarshal(buf, &bsm); err != nil {
+ logrus.Errorf("Error decoding bulk sync message: %v", err)
+ return
+ }
+
+ if bsm.LTime > 0 {
+ nDB.tableClock.Witness(bsm.LTime)
+ }
+
+ nDB.handleMessage(bsm.Payload, true)
+
+ // Don't respond to a bulk sync which was not unsolicited
+ if !bsm.Unsolicited {
+ nDB.Lock()
+ ch, ok := nDB.bulkSyncAckTbl[bsm.NodeName]
+ if ok {
+ close(ch)
+ delete(nDB.bulkSyncAckTbl, bsm.NodeName)
+ }
+ nDB.Unlock()
+
+ return
+ }
+
+ var nodeAddr net.IP
+ nDB.RLock()
+ if node, ok := nDB.nodes[bsm.NodeName]; ok {
+ nodeAddr = node.Addr
+ }
+ nDB.RUnlock()
+
+ if err := nDB.bulkSyncNode(bsm.Networks, bsm.NodeName, false); err != nil {
+ logrus.Errorf("Error in responding to bulk sync from node %s: %v", nodeAddr, err)
+ }
+}
+
+func (nDB *NetworkDB) handleMessage(buf []byte, isBulkSync bool) {
+ mType, data, err := decodeMessage(buf)
+ if err != nil {
+ logrus.Errorf("Error decoding gossip message to get message type: %v", err)
+ return
+ }
+
+ switch mType {
+ case MessageTypeNodeEvent:
+ nDB.handleNodeMessage(data)
+ case MessageTypeNetworkEvent:
+ nDB.handleNetworkMessage(data)
+ case MessageTypeTableEvent:
+ nDB.handleTableMessage(data, isBulkSync)
+ case MessageTypeBulkSync:
+ nDB.handleBulkSync(data)
+ case MessageTypeCompound:
+ nDB.handleCompound(data, isBulkSync)
+ default:
+ logrus.Errorf("%s: unknown message type %d", nDB.config.NodeName, mType)
+ }
+}
+
+func (d *delegate) NotifyMsg(buf []byte) {
+ if len(buf) == 0 {
+ return
+ }
+
+ d.nDB.handleMessage(buf, false)
+}
+
+func (d *delegate) GetBroadcasts(overhead, limit int) [][]byte {
+ msgs := d.nDB.networkBroadcasts.GetBroadcasts(overhead, limit)
+ msgs = append(msgs, d.nDB.nodeBroadcasts.GetBroadcasts(overhead, limit)...)
+ return msgs
+}
+
+func (d *delegate) LocalState(join bool) []byte {
+ if join {
+ // Update all the local node/network state to a new time to
+ // force update on the node we are trying to rejoin, just in
+ // case that node has these in leaving state still. This is
+ // facilitate fast convergence after recovering from a gossip
+ // failure.
+ d.nDB.updateLocalNetworkTime()
+ }
+
+ d.nDB.RLock()
+ defer d.nDB.RUnlock()
+
+ pp := NetworkPushPull{
+ LTime: d.nDB.networkClock.Time(),
+ NodeName: d.nDB.config.NodeName,
+ }
+
+ for name, nn := range d.nDB.networks {
+ for _, n := range nn {
+ pp.Networks = append(pp.Networks, &NetworkEntry{
+ LTime: n.ltime,
+ NetworkID: n.id,
+ NodeName: name,
+ Leaving: n.leaving,
+ })
+ }
+ }
+
+ buf, err := encodeMessage(MessageTypePushPull, &pp)
+ if err != nil {
+ logrus.Errorf("Failed to encode local network state: %v", err)
+ return nil
+ }
+
+ return buf
+}
+
+func (d *delegate) MergeRemoteState(buf []byte, isJoin bool) {
+ if len(buf) == 0 {
+ logrus.Error("zero byte remote network state received")
+ return
+ }
+
+ var gMsg GossipMessage
+ err := proto.Unmarshal(buf, &gMsg)
+ if err != nil {
+ logrus.Errorf("Error unmarshalling push pull messsage: %v", err)
+ return
+ }
+
+ if gMsg.Type != MessageTypePushPull {
+ logrus.Errorf("Invalid message type %v received from remote", buf[0])
+ }
+
+ pp := NetworkPushPull{}
+ if err := proto.Unmarshal(gMsg.Data, &pp); err != nil {
+ logrus.Errorf("Failed to decode remote network state: %v", err)
+ return
+ }
+
+ nodeEvent := &NodeEvent{
+ LTime: pp.LTime,
+ NodeName: pp.NodeName,
+ Type: NodeEventTypeJoin,
+ }
+ d.nDB.handleNodeEvent(nodeEvent)
+
+ for _, n := range pp.Networks {
+ nEvent := &NetworkEvent{
+ LTime: n.LTime,
+ NodeName: n.NodeName,
+ NetworkID: n.NetworkID,
+ Type: NetworkEventTypeJoin,
+ }
+
+ if n.Leaving {
+ nEvent.Type = NetworkEventTypeLeave
+ }
+
+ d.nDB.handleNetworkEvent(nEvent)
+ }
+
+}
diff --git a/vendor/github.com/docker/libnetwork/networkdb/event_delegate.go b/vendor/github.com/docker/libnetwork/networkdb/event_delegate.go
new file mode 100644
index 0000000..23e1683
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/networkdb/event_delegate.go
@@ -0,0 +1,68 @@
+package networkdb
+
+import (
+ "encoding/json"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/hashicorp/memberlist"
+)
+
+type eventDelegate struct {
+ nDB *NetworkDB
+}
+
+func (e *eventDelegate) broadcastNodeEvent(addr net.IP, op opType) {
+ value, err := json.Marshal(&NodeAddr{addr})
+ if err == nil {
+ e.nDB.broadcaster.Write(makeEvent(op, NodeTable, "", "", value))
+ } else {
+ logrus.Errorf("Error marshalling node broadcast event %s", addr.String())
+ }
+}
+
+func (e *eventDelegate) NotifyJoin(mn *memberlist.Node) {
+ logrus.Infof("Node %s/%s, joined gossip cluster", mn.Name, mn.Addr)
+ e.broadcastNodeEvent(mn.Addr, opCreate)
+ e.nDB.Lock()
+ // In case the node is rejoining after a failure or leave,
+ // wait until an explicit join message arrives before adding
+ // it to the nodes just to make sure this is not a stale
+ // join. If you don't know about this node add it immediately.
+ _, fOk := e.nDB.failedNodes[mn.Name]
+ _, lOk := e.nDB.leftNodes[mn.Name]
+ if fOk || lOk {
+ e.nDB.Unlock()
+ return
+ }
+
+ e.nDB.nodes[mn.Name] = &node{Node: *mn}
+ e.nDB.Unlock()
+ logrus.Infof("Node %s/%s, added to nodes list", mn.Name, mn.Addr)
+}
+
+func (e *eventDelegate) NotifyLeave(mn *memberlist.Node) {
+ var failed bool
+ logrus.Infof("Node %s/%s, left gossip cluster", mn.Name, mn.Addr)
+ e.broadcastNodeEvent(mn.Addr, opDelete)
+ e.nDB.deleteNodeTableEntries(mn.Name)
+ e.nDB.deleteNetworkEntriesForNode(mn.Name)
+ e.nDB.Lock()
+ if n, ok := e.nDB.nodes[mn.Name]; ok {
+ delete(e.nDB.nodes, mn.Name)
+
+ // In case of node failure, keep retrying to reconnect every retryInterval (1sec) for nodeReapInterval (24h)
+ // Explicit leave will have already removed the node from the list of nodes (nDB.nodes) and put it into the leftNodes map
+ n.reapTime = nodeReapInterval
+ e.nDB.failedNodes[mn.Name] = n
+ failed = true
+ }
+ e.nDB.Unlock()
+ if failed {
+ logrus.Infof("Node %s/%s, added to failed nodes list", mn.Name, mn.Addr)
+ }
+
+}
+
+func (e *eventDelegate) NotifyUpdate(n *memberlist.Node) {
+}
diff --git a/vendor/github.com/docker/libnetwork/networkdb/message.go b/vendor/github.com/docker/libnetwork/networkdb/message.go
new file mode 100644
index 0000000..a861752
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/networkdb/message.go
@@ -0,0 +1,102 @@
+package networkdb
+
+import "github.com/gogo/protobuf/proto"
+
+const (
+ // Max udp message size chosen to avoid network packet
+ // fragmentation.
+ udpSendBuf = 1400
+
+ // Compound message header overhead 1 byte(message type) + 4
+ // bytes (num messages)
+ compoundHeaderOverhead = 5
+
+ // Overhead for each embedded message in a compound message 4
+ // bytes (len of embedded message)
+ compoundOverhead = 4
+)
+
+func encodeRawMessage(t MessageType, raw []byte) ([]byte, error) {
+ gMsg := GossipMessage{
+ Type: t,
+ Data: raw,
+ }
+
+ buf, err := proto.Marshal(&gMsg)
+ if err != nil {
+ return nil, err
+ }
+
+ return buf, nil
+}
+
+func encodeMessage(t MessageType, msg interface{}) ([]byte, error) {
+ buf, err := proto.Marshal(msg.(proto.Message))
+ if err != nil {
+ return nil, err
+ }
+
+ buf, err = encodeRawMessage(t, buf)
+ if err != nil {
+ return nil, err
+ }
+
+ return buf, nil
+}
+
+func decodeMessage(buf []byte) (MessageType, []byte, error) {
+ var gMsg GossipMessage
+
+ err := proto.Unmarshal(buf, &gMsg)
+ if err != nil {
+ return MessageTypeInvalid, nil, err
+ }
+
+ return gMsg.Type, gMsg.Data, nil
+}
+
+// makeCompoundMessage takes a list of messages and generates
+// a single compound message containing all of them
+func makeCompoundMessage(msgs [][]byte) []byte {
+ cMsg := CompoundMessage{}
+
+ cMsg.Messages = make([]*CompoundMessage_SimpleMessage, 0, len(msgs))
+ for _, m := range msgs {
+ cMsg.Messages = append(cMsg.Messages, &CompoundMessage_SimpleMessage{
+ Payload: m,
+ })
+ }
+
+ buf, err := proto.Marshal(&cMsg)
+ if err != nil {
+ return nil
+ }
+
+ gMsg := GossipMessage{
+ Type: MessageTypeCompound,
+ Data: buf,
+ }
+
+ buf, err = proto.Marshal(&gMsg)
+ if err != nil {
+ return nil
+ }
+
+ return buf
+}
+
+// decodeCompoundMessage splits a compound message and returns
+// the slices of individual messages. Returns any potential error.
+func decodeCompoundMessage(buf []byte) ([][]byte, error) {
+ var cMsg CompoundMessage
+ if err := proto.Unmarshal(buf, &cMsg); err != nil {
+ return nil, err
+ }
+
+ parts := make([][]byte, 0, len(cMsg.Messages))
+ for _, m := range cMsg.Messages {
+ parts = append(parts, m.Payload)
+ }
+
+ return parts, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/networkdb/networkdb.go b/vendor/github.com/docker/libnetwork/networkdb/networkdb.go
new file mode 100644
index 0000000..b93a90d
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/networkdb/networkdb.go
@@ -0,0 +1,644 @@
+package networkdb
+
+//go:generate protoc -I.:../Godeps/_workspace/src/github.com/gogo/protobuf --gogo_out=import_path=github.com/docker/libnetwork/networkdb,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto:. networkdb.proto
+
+import (
+ "fmt"
+ "net"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/armon/go-radix"
+ "github.com/docker/go-events"
+ "github.com/docker/libnetwork/types"
+ "github.com/hashicorp/memberlist"
+ "github.com/hashicorp/serf/serf"
+)
+
+const (
+ byTable int = 1 + iota
+ byNetwork
+)
+
+// NetworkDB instance drives the networkdb cluster and acts the broker
+// for cluster-scoped and network-scoped gossip and watches.
+type NetworkDB struct {
+ // The clocks MUST be the first things
+ // in this struct due to Golang issue #599.
+
+ // Global lamport clock for node network attach events.
+ networkClock serf.LamportClock
+
+ // Global lamport clock for table events.
+ tableClock serf.LamportClock
+
+ sync.RWMutex
+
+ // NetworkDB configuration.
+ config *Config
+
+ // All the tree index (byTable, byNetwork) that we maintain
+ // the db.
+ indexes map[int]*radix.Tree
+
+ // Memberlist we use to drive the cluster.
+ memberlist *memberlist.Memberlist
+
+ // List of all peer nodes in the cluster not-limited to any
+ // network.
+ nodes map[string]*node
+
+ // List of all peer nodes which have failed
+ failedNodes map[string]*node
+
+ // List of all peer nodes which have left
+ leftNodes map[string]*node
+
+ // A multi-dimensional map of network/node attachmemts. The
+ // first key is a node name and the second key is a network ID
+ // for the network that node is participating in.
+ networks map[string]map[string]*network
+
+ // A map of nodes which are participating in a given
+ // network. The key is a network ID.
+ networkNodes map[string][]string
+
+ // A table of ack channels for every node from which we are
+ // waiting for an ack.
+ bulkSyncAckTbl map[string]chan struct{}
+
+ // Broadcast queue for network event gossip.
+ networkBroadcasts *memberlist.TransmitLimitedQueue
+
+ // Broadcast queue for node event gossip.
+ nodeBroadcasts *memberlist.TransmitLimitedQueue
+
+ // A central stop channel to stop all go routines running on
+ // behalf of the NetworkDB instance.
+ stopCh chan struct{}
+
+ // A central broadcaster for all local watchers watching table
+ // events.
+ broadcaster *events.Broadcaster
+
+ // List of all tickers which needed to be stopped when
+ // cleaning up.
+ tickers []*time.Ticker
+
+ // Reference to the memberlist's keyring to add & remove keys
+ keyring *memberlist.Keyring
+
+ // bootStrapIP is the list of IPs that can be used to bootstrap
+ // the gossip.
+ bootStrapIP []net.IP
+}
+
+// PeerInfo represents the peer (gossip cluster) nodes of a network
+type PeerInfo struct {
+ Name string
+ IP string
+}
+
+type node struct {
+ memberlist.Node
+ ltime serf.LamportTime
+ // Number of hours left before the reaper removes the node
+ reapTime time.Duration
+}
+
+// network describes the node/network attachment.
+type network struct {
+ // Network ID
+ id string
+
+ // Lamport time for the latest state of the entry.
+ ltime serf.LamportTime
+
+ // Node leave is in progress.
+ leaving bool
+
+ // Number of seconds still left before a deleted network entry gets
+ // removed from networkDB
+ reapTime time.Duration
+
+ // The broadcast queue for table event gossip. This is only
+ // initialized for this node's network attachment entries.
+ tableBroadcasts *memberlist.TransmitLimitedQueue
+}
+
+// Config represents the configuration of the networdb instance and
+// can be passed by the caller.
+type Config struct {
+ // NodeName is the cluster wide unique name for this node.
+ NodeName string
+
+ // BindAddr is the IP on which networkdb listens. It can be
+ // 0.0.0.0 to listen on all addresses on the host.
+ BindAddr string
+
+ // AdvertiseAddr is the node's IP address that we advertise for
+ // cluster communication.
+ AdvertiseAddr string
+
+ // BindPort is the local node's port to which we bind to for
+ // cluster communication.
+ BindPort int
+
+ // Keys to be added to the Keyring of the memberlist. Key at index
+ // 0 is the primary key
+ Keys [][]byte
+}
+
+// entry defines a table entry
+type entry struct {
+ // node from which this entry was learned.
+ node string
+
+ // Lamport time for the most recent update to the entry
+ ltime serf.LamportTime
+
+ // Opaque value store in the entry
+ value []byte
+
+ // Deleting the entry is in progress. All entries linger in
+ // the cluster for certain amount of time after deletion.
+ deleting bool
+
+ // Number of seconds still left before a deleted table entry gets
+ // removed from networkDB
+ reapTime time.Duration
+}
+
+// New creates a new instance of NetworkDB using the Config passed by
+// the caller.
+func New(c *Config) (*NetworkDB, error) {
+ nDB := &NetworkDB{
+ config: c,
+ indexes: make(map[int]*radix.Tree),
+ networks: make(map[string]map[string]*network),
+ nodes: make(map[string]*node),
+ failedNodes: make(map[string]*node),
+ leftNodes: make(map[string]*node),
+ networkNodes: make(map[string][]string),
+ bulkSyncAckTbl: make(map[string]chan struct{}),
+ broadcaster: events.NewBroadcaster(),
+ }
+
+ nDB.indexes[byTable] = radix.New()
+ nDB.indexes[byNetwork] = radix.New()
+
+ if err := nDB.clusterInit(); err != nil {
+ return nil, err
+ }
+
+ return nDB, nil
+}
+
+// Join joins this NetworkDB instance with a list of peer NetworkDB
+// instances passed by the caller in the form of addr:port
+func (nDB *NetworkDB) Join(members []string) error {
+ nDB.Lock()
+ for _, m := range members {
+ nDB.bootStrapIP = append(nDB.bootStrapIP, net.ParseIP(m))
+ }
+ nDB.Unlock()
+ return nDB.clusterJoin(members)
+}
+
+// Close destroys this NetworkDB instance by leave the cluster,
+// stopping timers, canceling goroutines etc.
+func (nDB *NetworkDB) Close() {
+ if err := nDB.clusterLeave(); err != nil {
+ logrus.Errorf("Could not close DB %s: %v", nDB.config.NodeName, err)
+ }
+}
+
+// Peers returns the gossip peers for a given network.
+func (nDB *NetworkDB) Peers(nid string) []PeerInfo {
+ nDB.RLock()
+ defer nDB.RUnlock()
+ peers := make([]PeerInfo, 0, len(nDB.networkNodes[nid]))
+ for _, nodeName := range nDB.networkNodes[nid] {
+ if node, ok := nDB.nodes[nodeName]; ok {
+ peers = append(peers, PeerInfo{
+ Name: node.Name,
+ IP: node.Addr.String(),
+ })
+ }
+ }
+ return peers
+}
+
+// GetEntry retrieves the value of a table entry in a given (network,
+// table, key) tuple
+func (nDB *NetworkDB) GetEntry(tname, nid, key string) ([]byte, error) {
+ entry, err := nDB.getEntry(tname, nid, key)
+ if err != nil {
+ return nil, err
+ }
+
+ return entry.value, nil
+}
+
+func (nDB *NetworkDB) getEntry(tname, nid, key string) (*entry, error) {
+ nDB.RLock()
+ defer nDB.RUnlock()
+
+ e, ok := nDB.indexes[byTable].Get(fmt.Sprintf("/%s/%s/%s", tname, nid, key))
+ if !ok {
+ return nil, types.NotFoundErrorf("could not get entry in table %s with network id %s and key %s", tname, nid, key)
+ }
+
+ return e.(*entry), nil
+}
+
+// CreateEntry creates a table entry in NetworkDB for given (network,
+// table, key) tuple and if the NetworkDB is part of the cluster
+// propagates this event to the cluster. It is an error to create an
+// entry for the same tuple for which there is already an existing
+// entry unless the current entry is deleting state.
+func (nDB *NetworkDB) CreateEntry(tname, nid, key string, value []byte) error {
+ oldEntry, err := nDB.getEntry(tname, nid, key)
+ if err != nil {
+ if _, ok := err.(types.NotFoundError); !ok {
+ return fmt.Errorf("cannot create entry in table %s with network id %s and key %s: %v", tname, nid, key, err)
+ }
+ }
+ if oldEntry != nil && !oldEntry.deleting {
+ return fmt.Errorf("cannot create entry in table %s with network id %s and key %s, already exists", tname, nid, key)
+ }
+
+ entry := &entry{
+ ltime: nDB.tableClock.Increment(),
+ node: nDB.config.NodeName,
+ value: value,
+ }
+
+ if err := nDB.sendTableEvent(TableEventTypeCreate, nid, tname, key, entry); err != nil {
+ return fmt.Errorf("cannot send create event for table %s, %v", tname, err)
+ }
+
+ nDB.Lock()
+ nDB.indexes[byTable].Insert(fmt.Sprintf("/%s/%s/%s", tname, nid, key), entry)
+ nDB.indexes[byNetwork].Insert(fmt.Sprintf("/%s/%s/%s", nid, tname, key), entry)
+ nDB.Unlock()
+
+ return nil
+}
+
+// UpdateEntry updates a table entry in NetworkDB for given (network,
+// table, key) tuple and if the NetworkDB is part of the cluster
+// propagates this event to the cluster. It is an error to update a
+// non-existent entry.
+func (nDB *NetworkDB) UpdateEntry(tname, nid, key string, value []byte) error {
+ if _, err := nDB.GetEntry(tname, nid, key); err != nil {
+ return fmt.Errorf("cannot update entry as the entry in table %s with network id %s and key %s does not exist", tname, nid, key)
+ }
+
+ entry := &entry{
+ ltime: nDB.tableClock.Increment(),
+ node: nDB.config.NodeName,
+ value: value,
+ }
+
+ if err := nDB.sendTableEvent(TableEventTypeUpdate, nid, tname, key, entry); err != nil {
+ return fmt.Errorf("cannot send table update event: %v", err)
+ }
+
+ nDB.Lock()
+ nDB.indexes[byTable].Insert(fmt.Sprintf("/%s/%s/%s", tname, nid, key), entry)
+ nDB.indexes[byNetwork].Insert(fmt.Sprintf("/%s/%s/%s", nid, tname, key), entry)
+ nDB.Unlock()
+
+ return nil
+}
+
+// GetTableByNetwork walks the networkdb by the give table and network id and
+// returns a map of keys and values
+func (nDB *NetworkDB) GetTableByNetwork(tname, nid string) map[string]interface{} {
+ entries := make(map[string]interface{})
+ nDB.indexes[byTable].WalkPrefix(fmt.Sprintf("/%s/%s", tname, nid), func(k string, v interface{}) bool {
+ entry := v.(*entry)
+ if entry.deleting {
+ return false
+ }
+ key := k[strings.LastIndex(k, "/")+1:]
+ entries[key] = entry.value
+ return false
+ })
+ return entries
+}
+
+// DeleteEntry deletes a table entry in NetworkDB for given (network,
+// table, key) tuple and if the NetworkDB is part of the cluster
+// propagates this event to the cluster.
+func (nDB *NetworkDB) DeleteEntry(tname, nid, key string) error {
+ value, err := nDB.GetEntry(tname, nid, key)
+ if err != nil {
+ return fmt.Errorf("cannot delete entry as the entry in table %s with network id %s and key %s does not exist", tname, nid, key)
+ }
+
+ entry := &entry{
+ ltime: nDB.tableClock.Increment(),
+ node: nDB.config.NodeName,
+ value: value,
+ deleting: true,
+ reapTime: reapInterval,
+ }
+
+ if err := nDB.sendTableEvent(TableEventTypeDelete, nid, tname, key, entry); err != nil {
+ return fmt.Errorf("cannot send table delete event: %v", err)
+ }
+
+ nDB.Lock()
+ nDB.indexes[byTable].Insert(fmt.Sprintf("/%s/%s/%s", tname, nid, key), entry)
+ nDB.indexes[byNetwork].Insert(fmt.Sprintf("/%s/%s/%s", nid, tname, key), entry)
+ nDB.Unlock()
+
+ return nil
+}
+
+func (nDB *NetworkDB) deleteNetworkEntriesForNode(deletedNode string) {
+ nDB.Lock()
+ for nid, nodes := range nDB.networkNodes {
+ updatedNodes := make([]string, 0, len(nodes))
+ for _, node := range nodes {
+ if node == deletedNode {
+ continue
+ }
+
+ updatedNodes = append(updatedNodes, node)
+ }
+
+ nDB.networkNodes[nid] = updatedNodes
+ }
+
+ delete(nDB.networks, deletedNode)
+ nDB.Unlock()
+}
+
+func (nDB *NetworkDB) deleteNodeNetworkEntries(nid, node string) {
+ nDB.Lock()
+ nDB.indexes[byNetwork].WalkPrefix(fmt.Sprintf("/%s", nid),
+ func(path string, v interface{}) bool {
+ oldEntry := v.(*entry)
+ params := strings.Split(path[1:], "/")
+ nid := params[0]
+ tname := params[1]
+ key := params[2]
+
+ if oldEntry.node != node {
+ return false
+ }
+
+ entry := &entry{
+ ltime: oldEntry.ltime,
+ node: node,
+ value: oldEntry.value,
+ deleting: true,
+ reapTime: reapInterval,
+ }
+
+ nDB.indexes[byTable].Insert(fmt.Sprintf("/%s/%s/%s", tname, nid, key), entry)
+ nDB.indexes[byNetwork].Insert(fmt.Sprintf("/%s/%s/%s", nid, tname, key), entry)
+
+ nDB.broadcaster.Write(makeEvent(opDelete, tname, nid, key, entry.value))
+ return false
+ })
+ nDB.Unlock()
+}
+
+func (nDB *NetworkDB) deleteNodeTableEntries(node string) {
+ nDB.Lock()
+ nDB.indexes[byTable].Walk(func(path string, v interface{}) bool {
+ oldEntry := v.(*entry)
+ if oldEntry.node != node {
+ return false
+ }
+
+ params := strings.Split(path[1:], "/")
+ tname := params[0]
+ nid := params[1]
+ key := params[2]
+
+ entry := &entry{
+ ltime: oldEntry.ltime,
+ node: node,
+ value: oldEntry.value,
+ deleting: true,
+ reapTime: reapInterval,
+ }
+
+ nDB.indexes[byTable].Insert(fmt.Sprintf("/%s/%s/%s", tname, nid, key), entry)
+ nDB.indexes[byNetwork].Insert(fmt.Sprintf("/%s/%s/%s", nid, tname, key), entry)
+
+ nDB.broadcaster.Write(makeEvent(opDelete, tname, nid, key, entry.value))
+ return false
+ })
+ nDB.Unlock()
+}
+
+// WalkTable walks a single table in NetworkDB and invokes the passed
+// function for each entry in the table passing the network, key,
+// value. The walk stops if the passed function returns a true.
+func (nDB *NetworkDB) WalkTable(tname string, fn func(string, string, []byte) bool) error {
+ nDB.RLock()
+ values := make(map[string]interface{})
+ nDB.indexes[byTable].WalkPrefix(fmt.Sprintf("/%s", tname), func(path string, v interface{}) bool {
+ values[path] = v
+ return false
+ })
+ nDB.RUnlock()
+
+ for k, v := range values {
+ params := strings.Split(k[1:], "/")
+ nid := params[1]
+ key := params[2]
+ if fn(nid, key, v.(*entry).value) {
+ return nil
+ }
+ }
+
+ return nil
+}
+
+// JoinNetwork joins this node to a given network and propagates this
+// event across the cluster. This triggers this node joining the
+// sub-cluster of this network and participates in the network-scoped
+// gossip and bulk sync for this network.
+func (nDB *NetworkDB) JoinNetwork(nid string) error {
+ ltime := nDB.networkClock.Increment()
+
+ nDB.Lock()
+ nodeNetworks, ok := nDB.networks[nDB.config.NodeName]
+ if !ok {
+ nodeNetworks = make(map[string]*network)
+ nDB.networks[nDB.config.NodeName] = nodeNetworks
+ }
+ nodeNetworks[nid] = &network{id: nid, ltime: ltime}
+ nodeNetworks[nid].tableBroadcasts = &memberlist.TransmitLimitedQueue{
+ NumNodes: func() int {
+ nDB.RLock()
+ num := len(nDB.networkNodes[nid])
+ nDB.RUnlock()
+ return num
+ },
+ RetransmitMult: 4,
+ }
+ nDB.networkNodes[nid] = append(nDB.networkNodes[nid], nDB.config.NodeName)
+ networkNodes := nDB.networkNodes[nid]
+ nDB.Unlock()
+
+ if err := nDB.sendNetworkEvent(nid, NetworkEventTypeJoin, ltime); err != nil {
+ return fmt.Errorf("failed to send leave network event for %s: %v", nid, err)
+ }
+
+ logrus.Debugf("%s: joined network %s", nDB.config.NodeName, nid)
+ if _, err := nDB.bulkSync(networkNodes, true); err != nil {
+ logrus.Errorf("Error bulk syncing while joining network %s: %v", nid, err)
+ }
+
+ return nil
+}
+
+// LeaveNetwork leaves this node from a given network and propagates
+// this event across the cluster. This triggers this node leaving the
+// sub-cluster of this network and as a result will no longer
+// participate in the network-scoped gossip and bulk sync for this
+// network. Also remove all the table entries for this network from
+// networkdb
+func (nDB *NetworkDB) LeaveNetwork(nid string) error {
+ ltime := nDB.networkClock.Increment()
+ if err := nDB.sendNetworkEvent(nid, NetworkEventTypeLeave, ltime); err != nil {
+ return fmt.Errorf("failed to send leave network event for %s: %v", nid, err)
+ }
+
+ nDB.Lock()
+ defer nDB.Unlock()
+ var (
+ paths []string
+ entries []*entry
+ )
+
+ nwWalker := func(path string, v interface{}) bool {
+ entry, ok := v.(*entry)
+ if !ok {
+ return false
+ }
+ paths = append(paths, path)
+ entries = append(entries, entry)
+ return false
+ }
+
+ nDB.indexes[byNetwork].WalkPrefix(fmt.Sprintf("/%s", nid), nwWalker)
+ for _, path := range paths {
+ params := strings.Split(path[1:], "/")
+ tname := params[1]
+ key := params[2]
+
+ if _, ok := nDB.indexes[byTable].Delete(fmt.Sprintf("/%s/%s/%s", tname, nid, key)); !ok {
+ logrus.Errorf("Could not delete entry in table %s with network id %s and key %s as it does not exist", tname, nid, key)
+ }
+
+ if _, ok := nDB.indexes[byNetwork].Delete(fmt.Sprintf("/%s/%s/%s", nid, tname, key)); !ok {
+ logrus.Errorf("Could not delete entry in network %s with table name %s and key %s as it does not exist", nid, tname, key)
+ }
+ }
+
+ nodeNetworks, ok := nDB.networks[nDB.config.NodeName]
+ if !ok {
+ return fmt.Errorf("could not find self node for network %s while trying to leave", nid)
+ }
+
+ n, ok := nodeNetworks[nid]
+ if !ok {
+ return fmt.Errorf("could not find network %s while trying to leave", nid)
+ }
+
+ n.ltime = ltime
+ n.leaving = true
+ return nil
+}
+
+// addNetworkNode adds the node to the list of nodes which participate
+// in the passed network only if it is not already present. Caller
+// should hold the NetworkDB lock while calling this
+func (nDB *NetworkDB) addNetworkNode(nid string, nodeName string) {
+ nodes := nDB.networkNodes[nid]
+ for _, node := range nodes {
+ if node == nodeName {
+ return
+ }
+ }
+
+ nDB.networkNodes[nid] = append(nDB.networkNodes[nid], nodeName)
+}
+
+// Deletes the node from the list of nodes which participate in the
+// passed network. Caller should hold the NetworkDB lock while calling
+// this
+func (nDB *NetworkDB) deleteNetworkNode(nid string, nodeName string) {
+ nodes := nDB.networkNodes[nid]
+ newNodes := make([]string, 0, len(nodes)-1)
+ for _, name := range nodes {
+ if name == nodeName {
+ continue
+ }
+ newNodes = append(newNodes, name)
+ }
+ nDB.networkNodes[nid] = newNodes
+}
+
+// findCommonnetworks find the networks that both this node and the
+// passed node have joined.
+func (nDB *NetworkDB) findCommonNetworks(nodeName string) []string {
+ nDB.RLock()
+ defer nDB.RUnlock()
+
+ var networks []string
+ for nid := range nDB.networks[nDB.config.NodeName] {
+ if n, ok := nDB.networks[nodeName][nid]; ok {
+ if !n.leaving {
+ networks = append(networks, nid)
+ }
+ }
+ }
+
+ return networks
+}
+
+func (nDB *NetworkDB) updateLocalNetworkTime() {
+ nDB.Lock()
+ defer nDB.Unlock()
+
+ ltime := nDB.networkClock.Increment()
+ for _, n := range nDB.networks[nDB.config.NodeName] {
+ n.ltime = ltime
+ }
+}
+
+func (nDB *NetworkDB) updateLocalTableTime() {
+ nDB.Lock()
+ defer nDB.Unlock()
+
+ ltime := nDB.tableClock.Increment()
+ nDB.indexes[byTable].Walk(func(path string, v interface{}) bool {
+ entry := v.(*entry)
+ if entry.node != nDB.config.NodeName {
+ return false
+ }
+
+ params := strings.Split(path[1:], "/")
+ tname := params[0]
+ nid := params[1]
+ key := params[2]
+ entry.ltime = ltime
+
+ nDB.indexes[byTable].Insert(fmt.Sprintf("/%s/%s/%s", tname, nid, key), entry)
+ nDB.indexes[byNetwork].Insert(fmt.Sprintf("/%s/%s/%s", nid, tname, key), entry)
+
+ return false
+ })
+}
diff --git a/vendor/github.com/docker/libnetwork/networkdb/networkdb.pb.go b/vendor/github.com/docker/libnetwork/networkdb/networkdb.pb.go
new file mode 100644
index 0000000..dfbc713
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/networkdb/networkdb.pb.go
@@ -0,0 +1,2554 @@
+// Code generated by protoc-gen-gogo.
+// source: networkdb.proto
+// DO NOT EDIT!
+
+/*
+ Package networkdb is a generated protocol buffer package.
+
+ It is generated from these files:
+ networkdb.proto
+
+ It has these top-level messages:
+ GossipMessage
+ NodeEvent
+ NetworkEvent
+ NetworkEntry
+ NetworkPushPull
+ TableEvent
+ BulkSyncMessage
+ CompoundMessage
+*/
+package networkdb
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+
+import github_com_hashicorp_serf_serf "github.com/hashicorp/serf/serf"
+
+import strings "strings"
+import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
+import sort "sort"
+import strconv "strconv"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+const _ = proto.GoGoProtoPackageIsVersion1
+
+// MessageType enum defines all the core message types that networkdb
+// uses to communicate to peers.
+type MessageType int32
+
+const (
+ MessageTypeInvalid MessageType = 0
+ // NetworEvent message type is used to communicate network
+ // attachments on the node.
+ MessageTypeNetworkEvent MessageType = 1
+ // TableEvent message type is used to communicate any table
+ // CRUD event that happened on the node.
+ MessageTypeTableEvent MessageType = 2
+ // PushPull message type is used to syncup all network
+ // attachments on a peer node either during startup of this
+ // node or with a random peer node periodically thereafter.
+ MessageTypePushPull MessageType = 3
+ // BulkSync message is used to bulksync the whole networkdb
+ // state with a peer node during startup of this node or with
+ // a random peer node periodically thereafter.
+ MessageTypeBulkSync MessageType = 4
+ // Compound message type is used to form a compound message
+ // which is a pack of many message of above types, packed into
+ // a single compound message.
+ MessageTypeCompound MessageType = 5
+ // NodeEvent message type is used to communicare node
+ // join/leave events in the cluster
+ MessageTypeNodeEvent MessageType = 6
+)
+
+var MessageType_name = map[int32]string{
+ 0: "INVALID",
+ 1: "NETWORK_EVENT",
+ 2: "TABLE_EVENT",
+ 3: "PUSH_PULL",
+ 4: "BULK_SYNC",
+ 5: "COMPOUND",
+ 6: "NODE_EVENT",
+}
+var MessageType_value = map[string]int32{
+ "INVALID": 0,
+ "NETWORK_EVENT": 1,
+ "TABLE_EVENT": 2,
+ "PUSH_PULL": 3,
+ "BULK_SYNC": 4,
+ "COMPOUND": 5,
+ "NODE_EVENT": 6,
+}
+
+func (x MessageType) String() string {
+ return proto.EnumName(MessageType_name, int32(x))
+}
+func (MessageType) EnumDescriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{0} }
+
+type NodeEvent_Type int32
+
+const (
+ NodeEventTypeInvalid NodeEvent_Type = 0
+ // Join event is generated when this node joins the cluster.
+ NodeEventTypeJoin NodeEvent_Type = 1
+ // Leave event is generated when this node leaves the cluster.
+ NodeEventTypeLeave NodeEvent_Type = 2
+)
+
+var NodeEvent_Type_name = map[int32]string{
+ 0: "INVALID",
+ 1: "JOIN",
+ 2: "LEAVE",
+}
+var NodeEvent_Type_value = map[string]int32{
+ "INVALID": 0,
+ "JOIN": 1,
+ "LEAVE": 2,
+}
+
+func (x NodeEvent_Type) String() string {
+ return proto.EnumName(NodeEvent_Type_name, int32(x))
+}
+func (NodeEvent_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{1, 0} }
+
+type NetworkEvent_Type int32
+
+const (
+ NetworkEventTypeInvalid NetworkEvent_Type = 0
+ // Join event is generated when this node joins a network.
+ NetworkEventTypeJoin NetworkEvent_Type = 1
+ // Leave event is generated when this node leaves a network.
+ NetworkEventTypeLeave NetworkEvent_Type = 2
+)
+
+var NetworkEvent_Type_name = map[int32]string{
+ 0: "INVALID",
+ 1: "JOIN",
+ 2: "LEAVE",
+}
+var NetworkEvent_Type_value = map[string]int32{
+ "INVALID": 0,
+ "JOIN": 1,
+ "LEAVE": 2,
+}
+
+func (x NetworkEvent_Type) String() string {
+ return proto.EnumName(NetworkEvent_Type_name, int32(x))
+}
+func (NetworkEvent_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{2, 0} }
+
+type TableEvent_Type int32
+
+const (
+ TableEventTypeInvalid TableEvent_Type = 0
+ // Create signifies that this table entry was just
+ // created.
+ TableEventTypeCreate TableEvent_Type = 1
+ // Update signifies that this table entry was just
+ // updated.
+ TableEventTypeUpdate TableEvent_Type = 2
+ // Delete signifies that this table entry was just
+ // updated.
+ TableEventTypeDelete TableEvent_Type = 3
+)
+
+var TableEvent_Type_name = map[int32]string{
+ 0: "INVALID",
+ 1: "CREATE",
+ 2: "UPDATE",
+ 3: "DELETE",
+}
+var TableEvent_Type_value = map[string]int32{
+ "INVALID": 0,
+ "CREATE": 1,
+ "UPDATE": 2,
+ "DELETE": 3,
+}
+
+func (x TableEvent_Type) String() string {
+ return proto.EnumName(TableEvent_Type_name, int32(x))
+}
+func (TableEvent_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{5, 0} }
+
+// GossipMessage is a basic message header used by all messages types.
+type GossipMessage struct {
+ Type MessageType `protobuf:"varint,1,opt,name=type,proto3,enum=networkdb.MessageType" json:"type,omitempty"`
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+}
+
+func (m *GossipMessage) Reset() { *m = GossipMessage{} }
+func (*GossipMessage) ProtoMessage() {}
+func (*GossipMessage) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{0} }
+
+// NodeEvent message payload definition.
+type NodeEvent struct {
+ Type NodeEvent_Type `protobuf:"varint,1,opt,name=type,proto3,enum=networkdb.NodeEvent_Type" json:"type,omitempty"`
+ // Lamport time using a network lamport clock indicating the
+ // time this event was generated on the node where it was
+ // generated.
+ LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,2,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"`
+ // Source node name.
+ NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"`
+}
+
+func (m *NodeEvent) Reset() { *m = NodeEvent{} }
+func (*NodeEvent) ProtoMessage() {}
+func (*NodeEvent) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{1} }
+
+// NetworkEvent message payload definition.
+type NetworkEvent struct {
+ Type NetworkEvent_Type `protobuf:"varint,1,opt,name=type,proto3,enum=networkdb.NetworkEvent_Type" json:"type,omitempty"`
+ // Lamport time using a network lamport clock indicating the
+ // time this event was generated on the node where it was
+ // generated.
+ LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,2,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"`
+ // Source node name.
+ NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"`
+ // ID of the network for which the event is generated.
+ NetworkID string `protobuf:"bytes,4,opt,name=network_id,json=networkId,proto3" json:"network_id,omitempty"`
+}
+
+func (m *NetworkEvent) Reset() { *m = NetworkEvent{} }
+func (*NetworkEvent) ProtoMessage() {}
+func (*NetworkEvent) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{2} }
+
+// NetworkEntry for push pull of networks.
+type NetworkEntry struct {
+ // ID of the network
+ NetworkID string `protobuf:"bytes,1,opt,name=network_id,json=networkId,proto3" json:"network_id,omitempty"`
+ // Latest lamport time of the network attachment when this
+ // network event was recorded.
+ LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,2,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"`
+ // Source node name where this network attachment happened.
+ NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"`
+ // Indicates if a leave from this network is in progress.
+ Leaving bool `protobuf:"varint,4,opt,name=leaving,proto3" json:"leaving,omitempty"`
+}
+
+func (m *NetworkEntry) Reset() { *m = NetworkEntry{} }
+func (*NetworkEntry) ProtoMessage() {}
+func (*NetworkEntry) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{3} }
+
+// NetworkPushpull message payload definition.
+type NetworkPushPull struct {
+ // Lamport time when this push pull was initiated.
+ LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,1,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"`
+ Networks []*NetworkEntry `protobuf:"bytes,2,rep,name=networks" json:"networks,omitempty"`
+ // Name of the node sending this push pull payload.
+ NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"`
+}
+
+func (m *NetworkPushPull) Reset() { *m = NetworkPushPull{} }
+func (*NetworkPushPull) ProtoMessage() {}
+func (*NetworkPushPull) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{4} }
+
+func (m *NetworkPushPull) GetNetworks() []*NetworkEntry {
+ if m != nil {
+ return m.Networks
+ }
+ return nil
+}
+
+// TableEvent message payload definition.
+type TableEvent struct {
+ Type TableEvent_Type `protobuf:"varint,1,opt,name=type,proto3,enum=networkdb.TableEvent_Type" json:"type,omitempty"`
+ // Lamport time when this event was generated.
+ LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,2,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"`
+ // Node name where this event originated.
+ NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"`
+ // ID of the network to which this table entry belongs.
+ NetworkID string `protobuf:"bytes,4,opt,name=network_id,json=networkId,proto3" json:"network_id,omitempty"`
+ // Name of the table to which this table entry belongs.
+ TableName string `protobuf:"bytes,5,opt,name=table_name,json=tableName,proto3" json:"table_name,omitempty"`
+ // Entry key.
+ Key string `protobuf:"bytes,6,opt,name=key,proto3" json:"key,omitempty"`
+ // Entry value.
+ Value []byte `protobuf:"bytes,7,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *TableEvent) Reset() { *m = TableEvent{} }
+func (*TableEvent) ProtoMessage() {}
+func (*TableEvent) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{5} }
+
+// BulkSync message payload definition.
+type BulkSyncMessage struct {
+ // Lamport time when this bulk sync was initiated.
+ LTime github_com_hashicorp_serf_serf.LamportTime `protobuf:"varint,1,opt,name=l_time,json=lTime,proto3,customtype=github.com/hashicorp/serf/serf.LamportTime" json:"l_time"`
+ // Indicates if this bulksync is a response to a bulk sync
+ // request from a peer node.
+ Unsolicited bool `protobuf:"varint,2,opt,name=unsolicited,proto3" json:"unsolicited,omitempty"`
+ // Name of the node which is producing this bulk sync message.
+ NodeName string `protobuf:"bytes,3,opt,name=node_name,json=nodeName,proto3" json:"node_name,omitempty"`
+ // List of network names whose table entries are getting
+ // bulksynced as part of the bulksync.
+ Networks []string `protobuf:"bytes,4,rep,name=networks" json:"networks,omitempty"`
+ // Bulksync payload
+ Payload []byte `protobuf:"bytes,5,opt,name=payload,proto3" json:"payload,omitempty"`
+}
+
+func (m *BulkSyncMessage) Reset() { *m = BulkSyncMessage{} }
+func (*BulkSyncMessage) ProtoMessage() {}
+func (*BulkSyncMessage) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{6} }
+
+// Compound message payload definition.
+type CompoundMessage struct {
+ // A list of simple messages.
+ Messages []*CompoundMessage_SimpleMessage `protobuf:"bytes,1,rep,name=messages" json:"messages,omitempty"`
+}
+
+func (m *CompoundMessage) Reset() { *m = CompoundMessage{} }
+func (*CompoundMessage) ProtoMessage() {}
+func (*CompoundMessage) Descriptor() ([]byte, []int) { return fileDescriptorNetworkdb, []int{7} }
+
+func (m *CompoundMessage) GetMessages() []*CompoundMessage_SimpleMessage {
+ if m != nil {
+ return m.Messages
+ }
+ return nil
+}
+
+type CompoundMessage_SimpleMessage struct {
+ // Bytestring payload of a message constructed using
+ // other message type definitions.
+ Payload []byte `protobuf:"bytes,1,opt,name=Payload,json=payload,proto3" json:"Payload,omitempty"`
+}
+
+func (m *CompoundMessage_SimpleMessage) Reset() { *m = CompoundMessage_SimpleMessage{} }
+func (*CompoundMessage_SimpleMessage) ProtoMessage() {}
+func (*CompoundMessage_SimpleMessage) Descriptor() ([]byte, []int) {
+ return fileDescriptorNetworkdb, []int{7, 0}
+}
+
+func init() {
+ proto.RegisterType((*GossipMessage)(nil), "networkdb.GossipMessage")
+ proto.RegisterType((*NodeEvent)(nil), "networkdb.NodeEvent")
+ proto.RegisterType((*NetworkEvent)(nil), "networkdb.NetworkEvent")
+ proto.RegisterType((*NetworkEntry)(nil), "networkdb.NetworkEntry")
+ proto.RegisterType((*NetworkPushPull)(nil), "networkdb.NetworkPushPull")
+ proto.RegisterType((*TableEvent)(nil), "networkdb.TableEvent")
+ proto.RegisterType((*BulkSyncMessage)(nil), "networkdb.BulkSyncMessage")
+ proto.RegisterType((*CompoundMessage)(nil), "networkdb.CompoundMessage")
+ proto.RegisterType((*CompoundMessage_SimpleMessage)(nil), "networkdb.CompoundMessage.SimpleMessage")
+ proto.RegisterEnum("networkdb.MessageType", MessageType_name, MessageType_value)
+ proto.RegisterEnum("networkdb.NodeEvent_Type", NodeEvent_Type_name, NodeEvent_Type_value)
+ proto.RegisterEnum("networkdb.NetworkEvent_Type", NetworkEvent_Type_name, NetworkEvent_Type_value)
+ proto.RegisterEnum("networkdb.TableEvent_Type", TableEvent_Type_name, TableEvent_Type_value)
+}
+func (this *GossipMessage) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&networkdb.GossipMessage{")
+ s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n")
+ s = append(s, "Data: "+fmt.Sprintf("%#v", this.Data)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *NodeEvent) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&networkdb.NodeEvent{")
+ s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n")
+ s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n")
+ s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *NetworkEvent) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 8)
+ s = append(s, "&networkdb.NetworkEvent{")
+ s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n")
+ s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n")
+ s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n")
+ s = append(s, "NetworkID: "+fmt.Sprintf("%#v", this.NetworkID)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *NetworkEntry) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 8)
+ s = append(s, "&networkdb.NetworkEntry{")
+ s = append(s, "NetworkID: "+fmt.Sprintf("%#v", this.NetworkID)+",\n")
+ s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n")
+ s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n")
+ s = append(s, "Leaving: "+fmt.Sprintf("%#v", this.Leaving)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *NetworkPushPull) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&networkdb.NetworkPushPull{")
+ s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n")
+ if this.Networks != nil {
+ s = append(s, "Networks: "+fmt.Sprintf("%#v", this.Networks)+",\n")
+ }
+ s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *TableEvent) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 11)
+ s = append(s, "&networkdb.TableEvent{")
+ s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n")
+ s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n")
+ s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n")
+ s = append(s, "NetworkID: "+fmt.Sprintf("%#v", this.NetworkID)+",\n")
+ s = append(s, "TableName: "+fmt.Sprintf("%#v", this.TableName)+",\n")
+ s = append(s, "Key: "+fmt.Sprintf("%#v", this.Key)+",\n")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *BulkSyncMessage) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 9)
+ s = append(s, "&networkdb.BulkSyncMessage{")
+ s = append(s, "LTime: "+fmt.Sprintf("%#v", this.LTime)+",\n")
+ s = append(s, "Unsolicited: "+fmt.Sprintf("%#v", this.Unsolicited)+",\n")
+ s = append(s, "NodeName: "+fmt.Sprintf("%#v", this.NodeName)+",\n")
+ s = append(s, "Networks: "+fmt.Sprintf("%#v", this.Networks)+",\n")
+ s = append(s, "Payload: "+fmt.Sprintf("%#v", this.Payload)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *CompoundMessage) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&networkdb.CompoundMessage{")
+ if this.Messages != nil {
+ s = append(s, "Messages: "+fmt.Sprintf("%#v", this.Messages)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *CompoundMessage_SimpleMessage) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&networkdb.CompoundMessage_SimpleMessage{")
+ s = append(s, "Payload: "+fmt.Sprintf("%#v", this.Payload)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringNetworkdb(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func extensionToGoStringNetworkdb(e map[int32]github_com_gogo_protobuf_proto.Extension) string {
+ if e == nil {
+ return "nil"
+ }
+ s := "map[int32]proto.Extension{"
+ keys := make([]int, 0, len(e))
+ for k := range e {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+ ss := []string{}
+ for _, k := range keys {
+ ss = append(ss, strconv.Itoa(k)+": "+e[int32(k)].GoString())
+ }
+ s += strings.Join(ss, ",") + "}"
+ return s
+}
+func (m *GossipMessage) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *GossipMessage) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Type != 0 {
+ data[i] = 0x8
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(m.Type))
+ }
+ if len(m.Data) > 0 {
+ data[i] = 0x12
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.Data)))
+ i += copy(data[i:], m.Data)
+ }
+ return i, nil
+}
+
+func (m *NodeEvent) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *NodeEvent) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Type != 0 {
+ data[i] = 0x8
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(m.Type))
+ }
+ if m.LTime != 0 {
+ data[i] = 0x10
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(m.LTime))
+ }
+ if len(m.NodeName) > 0 {
+ data[i] = 0x1a
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.NodeName)))
+ i += copy(data[i:], m.NodeName)
+ }
+ return i, nil
+}
+
+func (m *NetworkEvent) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *NetworkEvent) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Type != 0 {
+ data[i] = 0x8
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(m.Type))
+ }
+ if m.LTime != 0 {
+ data[i] = 0x10
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(m.LTime))
+ }
+ if len(m.NodeName) > 0 {
+ data[i] = 0x1a
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.NodeName)))
+ i += copy(data[i:], m.NodeName)
+ }
+ if len(m.NetworkID) > 0 {
+ data[i] = 0x22
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.NetworkID)))
+ i += copy(data[i:], m.NetworkID)
+ }
+ return i, nil
+}
+
+func (m *NetworkEntry) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *NetworkEntry) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.NetworkID) > 0 {
+ data[i] = 0xa
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.NetworkID)))
+ i += copy(data[i:], m.NetworkID)
+ }
+ if m.LTime != 0 {
+ data[i] = 0x10
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(m.LTime))
+ }
+ if len(m.NodeName) > 0 {
+ data[i] = 0x1a
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.NodeName)))
+ i += copy(data[i:], m.NodeName)
+ }
+ if m.Leaving {
+ data[i] = 0x20
+ i++
+ if m.Leaving {
+ data[i] = 1
+ } else {
+ data[i] = 0
+ }
+ i++
+ }
+ return i, nil
+}
+
+func (m *NetworkPushPull) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *NetworkPushPull) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.LTime != 0 {
+ data[i] = 0x8
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(m.LTime))
+ }
+ if len(m.Networks) > 0 {
+ for _, msg := range m.Networks {
+ data[i] = 0x12
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(data[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.NodeName) > 0 {
+ data[i] = 0x1a
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.NodeName)))
+ i += copy(data[i:], m.NodeName)
+ }
+ return i, nil
+}
+
+func (m *TableEvent) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *TableEvent) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Type != 0 {
+ data[i] = 0x8
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(m.Type))
+ }
+ if m.LTime != 0 {
+ data[i] = 0x10
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(m.LTime))
+ }
+ if len(m.NodeName) > 0 {
+ data[i] = 0x1a
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.NodeName)))
+ i += copy(data[i:], m.NodeName)
+ }
+ if len(m.NetworkID) > 0 {
+ data[i] = 0x22
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.NetworkID)))
+ i += copy(data[i:], m.NetworkID)
+ }
+ if len(m.TableName) > 0 {
+ data[i] = 0x2a
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.TableName)))
+ i += copy(data[i:], m.TableName)
+ }
+ if len(m.Key) > 0 {
+ data[i] = 0x32
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.Key)))
+ i += copy(data[i:], m.Key)
+ }
+ if len(m.Value) > 0 {
+ data[i] = 0x3a
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.Value)))
+ i += copy(data[i:], m.Value)
+ }
+ return i, nil
+}
+
+func (m *BulkSyncMessage) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *BulkSyncMessage) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.LTime != 0 {
+ data[i] = 0x8
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(m.LTime))
+ }
+ if m.Unsolicited {
+ data[i] = 0x10
+ i++
+ if m.Unsolicited {
+ data[i] = 1
+ } else {
+ data[i] = 0
+ }
+ i++
+ }
+ if len(m.NodeName) > 0 {
+ data[i] = 0x1a
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.NodeName)))
+ i += copy(data[i:], m.NodeName)
+ }
+ if len(m.Networks) > 0 {
+ for _, s := range m.Networks {
+ data[i] = 0x22
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ data[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ data[i] = uint8(l)
+ i++
+ i += copy(data[i:], s)
+ }
+ }
+ if len(m.Payload) > 0 {
+ data[i] = 0x2a
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.Payload)))
+ i += copy(data[i:], m.Payload)
+ }
+ return i, nil
+}
+
+func (m *CompoundMessage) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *CompoundMessage) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Messages) > 0 {
+ for _, msg := range m.Messages {
+ data[i] = 0xa
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(data[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *CompoundMessage_SimpleMessage) Marshal() (data []byte, err error) {
+ size := m.Size()
+ data = make([]byte, size)
+ n, err := m.MarshalTo(data)
+ if err != nil {
+ return nil, err
+ }
+ return data[:n], nil
+}
+
+func (m *CompoundMessage_SimpleMessage) MarshalTo(data []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Payload) > 0 {
+ data[i] = 0xa
+ i++
+ i = encodeVarintNetworkdb(data, i, uint64(len(m.Payload)))
+ i += copy(data[i:], m.Payload)
+ }
+ return i, nil
+}
+
+func encodeFixed64Networkdb(data []byte, offset int, v uint64) int {
+ data[offset] = uint8(v)
+ data[offset+1] = uint8(v >> 8)
+ data[offset+2] = uint8(v >> 16)
+ data[offset+3] = uint8(v >> 24)
+ data[offset+4] = uint8(v >> 32)
+ data[offset+5] = uint8(v >> 40)
+ data[offset+6] = uint8(v >> 48)
+ data[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Networkdb(data []byte, offset int, v uint32) int {
+ data[offset] = uint8(v)
+ data[offset+1] = uint8(v >> 8)
+ data[offset+2] = uint8(v >> 16)
+ data[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintNetworkdb(data []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ data[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ data[offset] = uint8(v)
+ return offset + 1
+}
+func (m *GossipMessage) Size() (n int) {
+ var l int
+ _ = l
+ if m.Type != 0 {
+ n += 1 + sovNetworkdb(uint64(m.Type))
+ }
+ l = len(m.Data)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ return n
+}
+
+func (m *NodeEvent) Size() (n int) {
+ var l int
+ _ = l
+ if m.Type != 0 {
+ n += 1 + sovNetworkdb(uint64(m.Type))
+ }
+ if m.LTime != 0 {
+ n += 1 + sovNetworkdb(uint64(m.LTime))
+ }
+ l = len(m.NodeName)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ return n
+}
+
+func (m *NetworkEvent) Size() (n int) {
+ var l int
+ _ = l
+ if m.Type != 0 {
+ n += 1 + sovNetworkdb(uint64(m.Type))
+ }
+ if m.LTime != 0 {
+ n += 1 + sovNetworkdb(uint64(m.LTime))
+ }
+ l = len(m.NodeName)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ l = len(m.NetworkID)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ return n
+}
+
+func (m *NetworkEntry) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.NetworkID)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ if m.LTime != 0 {
+ n += 1 + sovNetworkdb(uint64(m.LTime))
+ }
+ l = len(m.NodeName)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ if m.Leaving {
+ n += 2
+ }
+ return n
+}
+
+func (m *NetworkPushPull) Size() (n int) {
+ var l int
+ _ = l
+ if m.LTime != 0 {
+ n += 1 + sovNetworkdb(uint64(m.LTime))
+ }
+ if len(m.Networks) > 0 {
+ for _, e := range m.Networks {
+ l = e.Size()
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ }
+ l = len(m.NodeName)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ return n
+}
+
+func (m *TableEvent) Size() (n int) {
+ var l int
+ _ = l
+ if m.Type != 0 {
+ n += 1 + sovNetworkdb(uint64(m.Type))
+ }
+ if m.LTime != 0 {
+ n += 1 + sovNetworkdb(uint64(m.LTime))
+ }
+ l = len(m.NodeName)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ l = len(m.NetworkID)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ l = len(m.TableName)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ l = len(m.Key)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ l = len(m.Value)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ return n
+}
+
+func (m *BulkSyncMessage) Size() (n int) {
+ var l int
+ _ = l
+ if m.LTime != 0 {
+ n += 1 + sovNetworkdb(uint64(m.LTime))
+ }
+ if m.Unsolicited {
+ n += 2
+ }
+ l = len(m.NodeName)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ if len(m.Networks) > 0 {
+ for _, s := range m.Networks {
+ l = len(s)
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ }
+ l = len(m.Payload)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ return n
+}
+
+func (m *CompoundMessage) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Messages) > 0 {
+ for _, e := range m.Messages {
+ l = e.Size()
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *CompoundMessage_SimpleMessage) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Payload)
+ if l > 0 {
+ n += 1 + l + sovNetworkdb(uint64(l))
+ }
+ return n
+}
+
+func sovNetworkdb(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozNetworkdb(x uint64) (n int) {
+ return sovNetworkdb(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *GossipMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GossipMessage{`,
+ `Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+ `Data:` + fmt.Sprintf("%v", this.Data) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NodeEvent) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NodeEvent{`,
+ `Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+ `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`,
+ `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NetworkEvent) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NetworkEvent{`,
+ `Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+ `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`,
+ `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`,
+ `NetworkID:` + fmt.Sprintf("%v", this.NetworkID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NetworkEntry) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NetworkEntry{`,
+ `NetworkID:` + fmt.Sprintf("%v", this.NetworkID) + `,`,
+ `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`,
+ `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`,
+ `Leaving:` + fmt.Sprintf("%v", this.Leaving) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NetworkPushPull) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NetworkPushPull{`,
+ `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`,
+ `Networks:` + strings.Replace(fmt.Sprintf("%v", this.Networks), "NetworkEntry", "NetworkEntry", 1) + `,`,
+ `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TableEvent) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TableEvent{`,
+ `Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+ `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`,
+ `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`,
+ `NetworkID:` + fmt.Sprintf("%v", this.NetworkID) + `,`,
+ `TableName:` + fmt.Sprintf("%v", this.TableName) + `,`,
+ `Key:` + fmt.Sprintf("%v", this.Key) + `,`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *BulkSyncMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&BulkSyncMessage{`,
+ `LTime:` + fmt.Sprintf("%v", this.LTime) + `,`,
+ `Unsolicited:` + fmt.Sprintf("%v", this.Unsolicited) + `,`,
+ `NodeName:` + fmt.Sprintf("%v", this.NodeName) + `,`,
+ `Networks:` + fmt.Sprintf("%v", this.Networks) + `,`,
+ `Payload:` + fmt.Sprintf("%v", this.Payload) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CompoundMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CompoundMessage{`,
+ `Messages:` + strings.Replace(fmt.Sprintf("%v", this.Messages), "CompoundMessage_SimpleMessage", "CompoundMessage_SimpleMessage", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CompoundMessage_SimpleMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CompoundMessage_SimpleMessage{`,
+ `Payload:` + fmt.Sprintf("%v", this.Payload) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringNetworkdb(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *GossipMessage) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GossipMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GossipMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.Type |= (MessageType(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], data[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipNetworkdb(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NodeEvent) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NodeEvent: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NodeEvent: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.Type |= (NodeEvent_Type(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType)
+ }
+ m.LTime = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeName = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipNetworkdb(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NetworkEvent) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NetworkEvent: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NetworkEvent: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.Type |= (NetworkEvent_Type(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType)
+ }
+ m.LTime = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeName = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NetworkID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NetworkID = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipNetworkdb(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NetworkEntry) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NetworkEntry: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NetworkEntry: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NetworkID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NetworkID = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType)
+ }
+ m.LTime = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeName = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Leaving", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Leaving = bool(v != 0)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipNetworkdb(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NetworkPushPull) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NetworkPushPull: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NetworkPushPull: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType)
+ }
+ m.LTime = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Networks", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Networks = append(m.Networks, &NetworkEntry{})
+ if err := m.Networks[len(m.Networks)-1].Unmarshal(data[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeName = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipNetworkdb(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *TableEvent) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: TableEvent: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: TableEvent: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.Type |= (TableEvent_Type(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType)
+ }
+ m.LTime = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeName = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NetworkID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NetworkID = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TableName", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TableName = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Key = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Value = append(m.Value[:0], data[iNdEx:postIndex]...)
+ if m.Value == nil {
+ m.Value = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipNetworkdb(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *BulkSyncMessage) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: BulkSyncMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: BulkSyncMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LTime", wireType)
+ }
+ m.LTime = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ m.LTime |= (github_com_hashicorp_serf_serf.LamportTime(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Unsolicited", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Unsolicited = bool(v != 0)
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeName", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeName = string(data[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Networks", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Networks = append(m.Networks, string(data[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Payload = append(m.Payload[:0], data[iNdEx:postIndex]...)
+ if m.Payload == nil {
+ m.Payload = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipNetworkdb(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CompoundMessage) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CompoundMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CompoundMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Messages", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Messages = append(m.Messages, &CompoundMessage_SimpleMessage{})
+ if err := m.Messages[len(m.Messages)-1].Unmarshal(data[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipNetworkdb(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CompoundMessage_SimpleMessage) Unmarshal(data []byte) error {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SimpleMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SimpleMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Payload = append(m.Payload[:0], data[iNdEx:postIndex]...)
+ if m.Payload == nil {
+ m.Payload = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipNetworkdb(data[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthNetworkdb
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipNetworkdb(data []byte) (n int, err error) {
+ l := len(data)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if data[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthNetworkdb
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowNetworkdb
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipNetworkdb(data[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthNetworkdb = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowNetworkdb = fmt.Errorf("proto: integer overflow")
+)
+
+var fileDescriptorNetworkdb = []byte{
+ // 887 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xcc, 0x96, 0xc1, 0x6e, 0xe3, 0x44,
+ 0x18, 0xc7, 0xeb, 0xc4, 0x49, 0xe3, 0xaf, 0x0d, 0x1b, 0xbc, 0xdd, 0xad, 0xd7, 0x0b, 0x49, 0x31,
+ 0xcb, 0x2a, 0x44, 0xe0, 0xa2, 0xee, 0x13, 0x24, 0xb1, 0x05, 0xd9, 0xf5, 0x3a, 0x91, 0x93, 0x14,
+ 0x71, 0x8a, 0x9c, 0x78, 0x48, 0xac, 0x3a, 0xb6, 0x15, 0x3b, 0x45, 0x39, 0x81, 0x38, 0xad, 0x78,
+ 0x07, 0x4e, 0xcb, 0x99, 0x07, 0xe0, 0xc0, 0x89, 0xc3, 0x8a, 0x13, 0xdc, 0x10, 0x87, 0x8a, 0xee,
+ 0x13, 0xf0, 0x08, 0x8c, 0xc7, 0x76, 0x32, 0x4e, 0xa3, 0x5e, 0x40, 0xc0, 0xc1, 0xad, 0x67, 0xe6,
+ 0xe7, 0xcf, 0xdf, 0xf7, 0x9f, 0xff, 0xe7, 0x09, 0xdc, 0x71, 0x51, 0xf8, 0x85, 0xb7, 0xb8, 0xb0,
+ 0xc6, 0xb2, 0xbf, 0xf0, 0x42, 0x8f, 0xe7, 0xd6, 0x13, 0xe2, 0xd1, 0xd4, 0x9b, 0x7a, 0x64, 0xf6,
+ 0x34, 0xba, 0x8b, 0x01, 0xa9, 0x0b, 0xe5, 0x8f, 0xbd, 0x20, 0xb0, 0xfd, 0xe7, 0x28, 0x08, 0xcc,
+ 0x29, 0xe2, 0x1b, 0xc0, 0x86, 0x2b, 0x1f, 0x09, 0xcc, 0x09, 0x53, 0x7f, 0xe3, 0xec, 0xbe, 0xbc,
+ 0x89, 0x98, 0x10, 0x03, 0xbc, 0x6a, 0x10, 0x86, 0xe7, 0x81, 0xb5, 0xcc, 0xd0, 0x14, 0x72, 0x98,
+ 0x3d, 0x34, 0xc8, 0xbd, 0xf4, 0x32, 0x07, 0x9c, 0xee, 0x59, 0x48, 0xbd, 0x44, 0x6e, 0xc8, 0x7f,
+ 0x98, 0x89, 0xf6, 0x80, 0x8a, 0xb6, 0x66, 0x64, 0x2a, 0x60, 0x07, 0x8a, 0xce, 0x28, 0xb4, 0xe7,
+ 0x88, 0x84, 0x64, 0x5b, 0x67, 0xaf, 0xae, 0x6a, 0x7b, 0xbf, 0x5f, 0xd5, 0x1a, 0x53, 0x3b, 0x9c,
+ 0x2d, 0xc7, 0xf2, 0xc4, 0x9b, 0x9f, 0xce, 0xcc, 0x60, 0x66, 0x4f, 0xbc, 0x85, 0x7f, 0x1a, 0xa0,
+ 0xc5, 0xe7, 0xe4, 0x8f, 0xac, 0x99, 0x73, 0xdf, 0x5b, 0x84, 0x03, 0xfc, 0xa4, 0x51, 0x70, 0xa2,
+ 0x7f, 0xfc, 0x43, 0xe0, 0x5c, 0xfc, 0x8a, 0x91, 0x6b, 0xe2, 0x68, 0x79, 0x1c, 0x8d, 0x33, 0x4a,
+ 0xd1, 0x84, 0x8e, 0xc7, 0xd2, 0x97, 0xc0, 0x46, 0x6f, 0xe5, 0xdf, 0x83, 0xfd, 0x8e, 0x7e, 0xde,
+ 0xd4, 0x3a, 0x4a, 0x65, 0x4f, 0x14, 0xbe, 0xf9, 0xf6, 0xe4, 0x68, 0x9d, 0x56, 0xb4, 0xde, 0x71,
+ 0x2f, 0x4d, 0xc7, 0xb6, 0xf8, 0x1a, 0xb0, 0x4f, 0xbb, 0x1d, 0xbd, 0xc2, 0x88, 0xf7, 0x30, 0xf3,
+ 0x66, 0x86, 0x79, 0xea, 0xd9, 0x2e, 0xff, 0x0e, 0x14, 0x34, 0xb5, 0x79, 0xae, 0x56, 0x72, 0xe2,
+ 0x7d, 0x4c, 0xf0, 0x19, 0x42, 0x43, 0xe6, 0x25, 0x12, 0x0f, 0x5f, 0xbc, 0xac, 0xee, 0xfd, 0xf0,
+ 0x5d, 0x95, 0xbc, 0x58, 0xba, 0xce, 0xc1, 0xa1, 0x1e, 0x6b, 0x11, 0x0b, 0xf5, 0x51, 0x46, 0xa8,
+ 0xb7, 0x68, 0xa1, 0x28, 0xec, 0x3f, 0xd0, 0x8a, 0xff, 0x00, 0x20, 0x49, 0x66, 0x64, 0x5b, 0x02,
+ 0x1b, 0xad, 0xb6, 0xca, 0xaf, 0xaf, 0x6a, 0x5c, 0x92, 0x58, 0x47, 0x31, 0x52, 0x97, 0x75, 0x2c,
+ 0xe9, 0x05, 0x93, 0x48, 0x5b, 0xa7, 0xa5, 0x7d, 0x88, 0x45, 0x39, 0xa6, 0x0b, 0xa1, 0xd5, 0x95,
+ 0xd6, 0xea, 0xc6, 0x3b, 0xb0, 0x85, 0x11, 0x81, 0x1f, 0x6d, 0x04, 0x7e, 0x80, 0xa1, 0x7b, 0xdb,
+ 0xd0, 0x2e, 0x8d, 0x7f, 0x64, 0x36, 0x1a, 0xbb, 0xe1, 0x62, 0xb5, 0x55, 0x09, 0x73, 0x7b, 0x25,
+ 0xff, 0x9a, 0xbe, 0x02, 0xec, 0x3b, 0x38, 0x7b, 0xdb, 0x9d, 0x12, 0x71, 0x4b, 0x46, 0x3a, 0x94,
+ 0xbe, 0x67, 0xe0, 0x4e, 0x92, 0x5a, 0x6f, 0x19, 0xcc, 0x7a, 0x4b, 0xc7, 0xa1, 0xb2, 0x62, 0xfe,
+ 0x6e, 0x56, 0x4f, 0xa0, 0x94, 0x54, 0x1b, 0xe0, 0x12, 0xf3, 0xf5, 0x83, 0xb3, 0xe3, 0x1d, 0xb6,
+ 0x8b, 0x94, 0x33, 0xd6, 0xe0, 0xed, 0x6d, 0xf5, 0x73, 0x1e, 0x60, 0x60, 0x8e, 0x9d, 0xa4, 0xf9,
+ 0xe5, 0x8c, 0xa7, 0x45, 0x2a, 0xf8, 0x06, 0xfa, 0xdf, 0x3b, 0x9a, 0x7f, 0x1b, 0x20, 0x8c, 0xd2,
+ 0x8d, 0x63, 0x15, 0x48, 0x2c, 0x8e, 0xcc, 0x90, 0x60, 0x15, 0xc8, 0x5f, 0xa0, 0x95, 0x50, 0x24,
+ 0xf3, 0xd1, 0x2d, 0x7f, 0x04, 0x05, 0x6c, 0xec, 0x25, 0x12, 0xf6, 0xc9, 0x67, 0x31, 0x1e, 0x44,
+ 0x9b, 0x19, 0x37, 0xc6, 0x63, 0xba, 0x31, 0x88, 0x99, 0x37, 0x6a, 0xd0, 0x6d, 0xf1, 0x08, 0x8a,
+ 0x6d, 0x43, 0x6d, 0x0e, 0xd4, 0xb4, 0x31, 0xb2, 0x58, 0x7b, 0x81, 0xcc, 0x10, 0x45, 0xd4, 0xb0,
+ 0xa7, 0x44, 0x54, 0x6e, 0x17, 0x35, 0xf4, 0xad, 0x84, 0x52, 0x54, 0x4d, 0xc5, 0x54, 0x7e, 0x17,
+ 0xa5, 0x20, 0x07, 0x85, 0xdb, 0xed, 0xf3, 0x2b, 0x76, 0x5f, 0x6b, 0xe9, 0x5c, 0xf4, 0x57, 0xee,
+ 0x24, 0x3d, 0x1c, 0xfe, 0x41, 0xf7, 0x9d, 0xc0, 0xc1, 0xd2, 0x0d, 0x3c, 0xc7, 0x9e, 0xd8, 0x21,
+ 0xb2, 0xc8, 0x8e, 0x97, 0x0c, 0x7a, 0xea, 0xf6, 0x3d, 0x14, 0x29, 0xf3, 0xb2, 0xd8, 0xbc, 0x1c,
+ 0xe5, 0x51, 0xdc, 0x51, 0xbe, 0xb9, 0x72, 0x3c, 0xd3, 0x22, 0xdb, 0x75, 0x68, 0xa4, 0x43, 0xe9,
+ 0x6b, 0x5c, 0x53, 0xdb, 0xc3, 0xb9, 0x2c, 0x5d, 0x2b, 0xad, 0x49, 0x81, 0xd2, 0x3c, 0xbe, 0x0d,
+ 0x70, 0x55, 0x51, 0x1b, 0xd4, 0x29, 0xa7, 0x6e, 0xd1, 0x72, 0xdf, 0x9e, 0xfb, 0x0e, 0x4a, 0x46,
+ 0xc6, 0xfa, 0x49, 0xf1, 0x7d, 0x28, 0x67, 0x96, 0xa2, 0x24, 0x7a, 0x49, 0x12, 0x4c, 0x26, 0x89,
+ 0xc6, 0x4f, 0x39, 0x38, 0xa0, 0xce, 0x52, 0xfe, 0x5d, 0xda, 0x10, 0xe4, 0xf8, 0xa0, 0x56, 0x53,
+ 0x37, 0xc8, 0x50, 0xd6, 0xd5, 0xc1, 0xa7, 0x5d, 0xe3, 0xd9, 0x48, 0x3d, 0x57, 0xf5, 0x01, 0x36,
+ 0x05, 0xf9, 0xa8, 0x52, 0x68, 0xe6, 0x3c, 0x69, 0xc0, 0xc1, 0xa0, 0xd9, 0xd2, 0xd4, 0x84, 0x4e,
+ 0x3e, 0x9b, 0x14, 0x4d, 0xf5, 0xe9, 0x63, 0xe0, 0x7a, 0xc3, 0xfe, 0x27, 0xa3, 0xde, 0x50, 0xd3,
+ 0xb0, 0x41, 0x8e, 0x31, 0x79, 0x97, 0x22, 0xd7, 0xdf, 0x1e, 0xcc, 0xb5, 0x86, 0xda, 0xb3, 0x51,
+ 0xff, 0x33, 0xbd, 0x5d, 0x61, 0x6f, 0x70, 0xa9, 0x59, 0xf0, 0xa9, 0x5a, 0x6a, 0x77, 0x9f, 0xf7,
+ 0xba, 0x43, 0x5d, 0xa9, 0x14, 0x6e, 0x60, 0xa9, 0xa2, 0xf8, 0x84, 0x00, 0xbd, 0xab, 0xa4, 0x19,
+ 0x16, 0x63, 0x63, 0xd2, 0xf5, 0xa4, 0x87, 0xa8, 0x78, 0x37, 0x31, 0x26, 0x2d, 0x5b, 0x4b, 0xf8,
+ 0xed, 0xba, 0xba, 0xf7, 0xe7, 0x75, 0x95, 0xf9, 0xea, 0x75, 0x95, 0x79, 0x85, 0xaf, 0x5f, 0xf0,
+ 0xf5, 0x07, 0xbe, 0xc6, 0x45, 0xf2, 0xd3, 0xe6, 0xc9, 0x5f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x21,
+ 0x78, 0x72, 0xc3, 0x0e, 0x09, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/libnetwork/networkdb/networkdb.proto b/vendor/github.com/docker/libnetwork/networkdb/networkdb.proto
new file mode 100644
index 0000000..7df1b42
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/networkdb/networkdb.proto
@@ -0,0 +1,183 @@
+syntax = "proto3";
+
+import "gogoproto/gogo.proto";
+
+package networkdb;
+
+option (gogoproto.marshaler_all) = true;
+option (gogoproto.unmarshaler_all) = true;
+option (gogoproto.stringer_all) = true;
+option (gogoproto.gostring_all) = true;
+option (gogoproto.sizer_all) = true;
+option (gogoproto.goproto_stringer_all) = false;
+
+// MessageType enum defines all the core message types that networkdb
+// uses to communicate to peers.
+enum MessageType {
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "MessageType";
+
+ INVALID = 0 [(gogoproto.enumvalue_customname) = "MessageTypeInvalid"];
+
+ // NetworEvent message type is used to communicate network
+ // attachments on the node.
+ NETWORK_EVENT = 1 [(gogoproto.enumvalue_customname) = "MessageTypeNetworkEvent"];
+
+ // TableEvent message type is used to communicate any table
+ // CRUD event that happened on the node.
+ TABLE_EVENT = 2 [(gogoproto.enumvalue_customname) = "MessageTypeTableEvent"];
+
+ // PushPull message type is used to syncup all network
+ // attachments on a peer node either during startup of this
+ // node or with a random peer node periodically thereafter.
+ PUSH_PULL = 3 [(gogoproto.enumvalue_customname) = "MessageTypePushPull"];
+
+ // BulkSync message is used to bulksync the whole networkdb
+ // state with a peer node during startup of this node or with
+ // a random peer node periodically thereafter.
+ BULK_SYNC = 4 [(gogoproto.enumvalue_customname) = "MessageTypeBulkSync"];
+
+ // Compound message type is used to form a compound message
+ // which is a pack of many message of above types, packed into
+ // a single compound message.
+ COMPOUND = 5 [(gogoproto.enumvalue_customname) = "MessageTypeCompound"];
+
+ // NodeEvent message type is used to communicare node
+ // join/leave events in the cluster
+ NODE_EVENT = 6 [(gogoproto.enumvalue_customname) = "MessageTypeNodeEvent"];
+}
+
+// GossipMessage is a basic message header used by all messages types.
+message GossipMessage {
+ MessageType type = 1; // type defines one of the message types defined above.
+ bytes data = 2; // Payload of the message of any type defined here.
+}
+
+// NodeEvent message payload definition.
+message NodeEvent {
+ enum Type {
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "Type";
+
+ INVALID = 0 [(gogoproto.enumvalue_customname) = "NodeEventTypeInvalid"];
+ // Join event is generated when this node joins the cluster.
+ JOIN = 1 [(gogoproto.enumvalue_customname) = "NodeEventTypeJoin"];;
+ // Leave event is generated when this node leaves the cluster.
+ LEAVE = 2 [(gogoproto.enumvalue_customname) = "NodeEventTypeLeave"];;
+ }
+
+ Type type = 1;
+
+ // Lamport time using a network lamport clock indicating the
+ // time this event was generated on the node where it was
+ // generated.
+ uint64 l_time = 2 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false];
+ // Source node name.
+ string node_name = 3;
+}
+
+// NetworkEvent message payload definition.
+message NetworkEvent {
+ enum Type {
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "Type";
+
+ INVALID = 0 [(gogoproto.enumvalue_customname) = "NetworkEventTypeInvalid"];
+ // Join event is generated when this node joins a network.
+ JOIN = 1 [(gogoproto.enumvalue_customname) = "NetworkEventTypeJoin"];;
+ // Leave event is generated when this node leaves a network.
+ LEAVE = 2 [(gogoproto.enumvalue_customname) = "NetworkEventTypeLeave"];;
+ }
+
+ Type type = 1;
+
+ // Lamport time using a network lamport clock indicating the
+ // time this event was generated on the node where it was
+ // generated.
+ uint64 l_time = 2 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false];
+ // Source node name.
+ string node_name = 3;
+ // ID of the network for which the event is generated.
+ string network_id = 4 [(gogoproto.customname) = "NetworkID"];
+}
+
+// NetworkEntry for push pull of networks.
+message NetworkEntry {
+ // ID of the network
+ string network_id = 1 [(gogoproto.customname) = "NetworkID"];
+ // Latest lamport time of the network attachment when this
+ // network event was recorded.
+ uint64 l_time = 2 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false];
+ // Source node name where this network attachment happened.
+ string node_name = 3;
+ // Indicates if a leave from this network is in progress.
+ bool leaving = 4;
+}
+
+// NetworkPushpull message payload definition.
+message NetworkPushPull {
+ // Lamport time when this push pull was initiated.
+ uint64 l_time = 1 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false];
+ repeated NetworkEntry networks = 2;
+}
+
+// TableEvent message payload definition.
+message TableEvent {
+ enum Type {
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "Type";
+
+ INVALID = 0 [(gogoproto.enumvalue_customname) = "TableEventTypeInvalid"];
+ // Create signifies that this table entry was just
+ // created.
+ CREATE = 1 [(gogoproto.enumvalue_customname) = "TableEventTypeCreate"];
+ // Update signifies that this table entry was just
+ // updated.
+ UPDATE = 2 [(gogoproto.enumvalue_customname) = "TableEventTypeUpdate"];
+ // Delete signifies that this table entry was just
+ // updated.
+ DELETE = 3 [(gogoproto.enumvalue_customname) = "TableEventTypeDelete"];
+ }
+
+ Type type = 1;
+ // Lamport time when this event was generated.
+ uint64 l_time = 2 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false];
+ // Node name where this event originated.
+ string node_name = 3;
+ // ID of the network to which this table entry belongs.
+ string network_id = 4 [(gogoproto.customname) = "NetworkID"];
+ // Name of the table to which this table entry belongs.
+ string table_name = 5;
+ // Entry key.
+ string key = 6;
+ // Entry value.
+ bytes value = 7;
+}
+
+// BulkSync message payload definition.
+message BulkSyncMessage {
+ // Lamport time when this bulk sync was initiated.
+ uint64 l_time = 1 [(gogoproto.customtype) = "github.com/hashicorp/serf/serf.LamportTime", (gogoproto.nullable) = false];
+ // Indicates if this bulksync is a response to a bulk sync
+ // request from a peer node.
+ bool unsolicited = 2;
+ // Name of the node which is producing this bulk sync message.
+ string node_name = 3;
+ // List of network names whose table entries are getting
+ // bulksynced as part of the bulksync.
+ repeated string networks = 4;
+ // Bulksync payload
+ bytes payload = 5;
+}
+
+// Compound message payload definition.
+message CompoundMessage {
+ message SimpleMessage {
+ // Bytestring payload of a message constructed using
+ // other message type definitions.
+ bytes Payload = 1;
+ }
+
+ // A list of simple messages.
+ repeated SimpleMessage messages = 1;
+} \ No newline at end of file
diff --git a/vendor/github.com/docker/libnetwork/networkdb/watch.go b/vendor/github.com/docker/libnetwork/networkdb/watch.go
new file mode 100644
index 0000000..2ef3042
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/networkdb/watch.go
@@ -0,0 +1,110 @@
+package networkdb
+
+import (
+ "net"
+
+ "github.com/docker/go-events"
+)
+
+type opType uint8
+
+const (
+ opCreate opType = 1 + iota
+ opUpdate
+ opDelete
+)
+
+type event struct {
+ Table string
+ NetworkID string
+ Key string
+ Value []byte
+}
+
+// NodeTable represents table event for node join and leave
+const NodeTable = "NodeTable"
+
+// NodeAddr represents the value carried for node event in NodeTable
+type NodeAddr struct {
+ Addr net.IP
+}
+
+// CreateEvent generates a table entry create event to the watchers
+type CreateEvent event
+
+// UpdateEvent generates a table entry update event to the watchers
+type UpdateEvent event
+
+// DeleteEvent generates a table entry delete event to the watchers
+type DeleteEvent event
+
+// Watch creates a watcher with filters for a particular table or
+// network or key or any combination of the tuple. If any of the
+// filter is an empty string it acts as a wildcard for that
+// field. Watch returns a channel of events, where the events will be
+// sent.
+func (nDB *NetworkDB) Watch(tname, nid, key string) (*events.Channel, func()) {
+ var matcher events.Matcher
+
+ if tname != "" || nid != "" || key != "" {
+ matcher = events.MatcherFunc(func(ev events.Event) bool {
+ var evt event
+ switch ev := ev.(type) {
+ case CreateEvent:
+ evt = event(ev)
+ case UpdateEvent:
+ evt = event(ev)
+ case DeleteEvent:
+ evt = event(ev)
+ }
+
+ if tname != "" && evt.Table != tname {
+ return false
+ }
+
+ if nid != "" && evt.NetworkID != nid {
+ return false
+ }
+
+ if key != "" && evt.Key != key {
+ return false
+ }
+
+ return true
+ })
+ }
+
+ ch := events.NewChannel(0)
+ sink := events.Sink(events.NewQueue(ch))
+
+ if matcher != nil {
+ sink = events.NewFilter(sink, matcher)
+ }
+
+ nDB.broadcaster.Add(sink)
+ return ch, func() {
+ nDB.broadcaster.Remove(sink)
+ ch.Close()
+ sink.Close()
+ }
+}
+
+func makeEvent(op opType, tname, nid, key string, value []byte) events.Event {
+ ev := event{
+ Table: tname,
+ NetworkID: nid,
+ Key: key,
+ Value: value,
+ }
+
+ switch op {
+ case opCreate:
+ return CreateEvent(ev)
+ case opUpdate:
+ return UpdateEvent(ev)
+ case opDelete:
+ return DeleteEvent(ev)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/ns/init_linux.go b/vendor/github.com/docker/libnetwork/ns/init_linux.go
new file mode 100644
index 0000000..84d4950
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/ns/init_linux.go
@@ -0,0 +1,140 @@
+package ns
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/vishvananda/netlink"
+ "github.com/vishvananda/netns"
+)
+
+var (
+ initNs netns.NsHandle
+ initNl *netlink.Handle
+ initOnce sync.Once
+ // NetlinkSocketsTimeout represents the default timeout duration for the sockets
+ NetlinkSocketsTimeout = 3 * time.Second
+)
+
+// Init initializes a new network namespace
+func Init() {
+ var err error
+ initNs, err = netns.Get()
+ if err != nil {
+ logrus.Errorf("could not get initial namespace: %v", err)
+ }
+ initNl, err = netlink.NewHandle(getSupportedNlFamilies()...)
+ if err != nil {
+ logrus.Errorf("could not create netlink handle on initial namespace: %v", err)
+ }
+ err = initNl.SetSocketTimeout(NetlinkSocketsTimeout)
+ if err != nil {
+ logrus.Warnf("Failed to set the timeout on the default netlink handle sockets: %v", err)
+ }
+}
+
+// SetNamespace sets the initial namespace handler
+func SetNamespace() error {
+ initOnce.Do(Init)
+ if err := netns.Set(initNs); err != nil {
+ linkInfo, linkErr := getLink()
+ if linkErr != nil {
+ linkInfo = linkErr.Error()
+ }
+ return fmt.Errorf("failed to set to initial namespace, %v, initns fd %d: %v", linkInfo, initNs, err)
+ }
+ return nil
+}
+
+// ParseHandlerInt transforms the namespace handler into an integer
+func ParseHandlerInt() int {
+ return int(getHandler())
+}
+
+// GetHandler returns the namespace handler
+func getHandler() netns.NsHandle {
+ initOnce.Do(Init)
+ return initNs
+}
+
+func getLink() (string, error) {
+ return os.Readlink(fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), syscall.Gettid()))
+}
+
+// NlHandle returns the netlink handler
+func NlHandle() *netlink.Handle {
+ initOnce.Do(Init)
+ return initNl
+}
+
+func getSupportedNlFamilies() []int {
+ fams := []int{syscall.NETLINK_ROUTE}
+ // NETLINK_XFRM test
+ if err := loadXfrmModules(); err != nil {
+ if checkXfrmSocket() != nil {
+ logrus.Warnf("Could not load necessary modules for IPSEC rules: %v", err)
+ } else {
+ fams = append(fams, syscall.NETLINK_XFRM)
+ }
+ } else {
+ fams = append(fams, syscall.NETLINK_XFRM)
+ }
+ // NETLINK_NETFILTER test
+ if err := loadNfConntrackModules(); err != nil {
+ if checkNfSocket() != nil {
+ logrus.Warnf("Could not load necessary modules for Conntrack: %v", err)
+ } else {
+ fams = append(fams, syscall.NETLINK_NETFILTER)
+ }
+ } else {
+ fams = append(fams, syscall.NETLINK_NETFILTER)
+ }
+
+ return fams
+}
+
+func loadXfrmModules() error {
+ if out, err := exec.Command("modprobe", "-va", "xfrm_user").CombinedOutput(); err != nil {
+ return fmt.Errorf("Running modprobe xfrm_user failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
+ }
+ if out, err := exec.Command("modprobe", "-va", "xfrm_algo").CombinedOutput(); err != nil {
+ return fmt.Errorf("Running modprobe xfrm_algo failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
+ }
+ return nil
+}
+
+// API check on required xfrm modules (xfrm_user, xfrm_algo)
+func checkXfrmSocket() error {
+ fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, syscall.NETLINK_XFRM)
+ if err != nil {
+ return err
+ }
+ syscall.Close(fd)
+ return nil
+}
+
+func loadNfConntrackModules() error {
+ if out, err := exec.Command("modprobe", "-va", "nf_conntrack").CombinedOutput(); err != nil {
+ return fmt.Errorf("Running modprobe nf_conntrack failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
+ }
+ if out, err := exec.Command("modprobe", "-va", "nf_conntrack_netlink").CombinedOutput(); err != nil {
+ return fmt.Errorf("Running modprobe nf_conntrack_netlink failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
+ }
+ return nil
+}
+
+// API check on required nf_conntrack* modules (nf_conntrack, nf_conntrack_netlink)
+func checkNfSocket() error {
+ fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, syscall.NETLINK_NETFILTER)
+ if err != nil {
+ return err
+ }
+ syscall.Close(fd)
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/options/options.go b/vendor/github.com/docker/libnetwork/options/options.go
new file mode 100644
index 0000000..06d8ae5
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/options/options.go
@@ -0,0 +1,88 @@
+// Package options provides a way to pass unstructured sets of options to a
+// component expecting a strongly-typed configuration structure.
+package options
+
+import (
+ "fmt"
+ "reflect"
+)
+
+// NoSuchFieldError is the error returned when the generic parameters hold a
+// value for a field absent from the destination structure.
+type NoSuchFieldError struct {
+ Field string
+ Type string
+}
+
+func (e NoSuchFieldError) Error() string {
+ return fmt.Sprintf("no field %q in type %q", e.Field, e.Type)
+}
+
+// CannotSetFieldError is the error returned when the generic parameters hold a
+// value for a field that cannot be set in the destination structure.
+type CannotSetFieldError struct {
+ Field string
+ Type string
+}
+
+func (e CannotSetFieldError) Error() string {
+ return fmt.Sprintf("cannot set field %q of type %q", e.Field, e.Type)
+}
+
+// TypeMismatchError is the error returned when the type of the generic value
+// for a field mismatches the type of the destination structure.
+type TypeMismatchError struct {
+ Field string
+ ExpectType string
+ ActualType string
+}
+
+func (e TypeMismatchError) Error() string {
+ return fmt.Sprintf("type mismatch, field %s require type %v, actual type %v", e.Field, e.ExpectType, e.ActualType)
+}
+
+// Generic is a basic type to store arbitrary settings.
+type Generic map[string]interface{}
+
+// NewGeneric returns a new Generic instance.
+func NewGeneric() Generic {
+ return make(Generic)
+}
+
+// GenerateFromModel takes the generic options, and tries to build a new
+// instance of the model's type by matching keys from the generic options to
+// fields in the model.
+//
+// The return value is of the same type than the model (including a potential
+// pointer qualifier).
+func GenerateFromModel(options Generic, model interface{}) (interface{}, error) {
+ modType := reflect.TypeOf(model)
+
+ // If the model is of pointer type, we need to dereference for New.
+ resType := reflect.TypeOf(model)
+ if modType.Kind() == reflect.Ptr {
+ resType = resType.Elem()
+ }
+
+ // Populate the result structure with the generic layout content.
+ res := reflect.New(resType)
+ for name, value := range options {
+ field := res.Elem().FieldByName(name)
+ if !field.IsValid() {
+ return nil, NoSuchFieldError{name, resType.String()}
+ }
+ if !field.CanSet() {
+ return nil, CannotSetFieldError{name, resType.String()}
+ }
+ if reflect.TypeOf(value) != field.Type() {
+ return nil, TypeMismatchError{name, field.Type().String(), reflect.TypeOf(value).String()}
+ }
+ field.Set(reflect.ValueOf(value))
+ }
+
+ // If the model is not of pointer type, return content of the result.
+ if modType.Kind() == reflect.Ptr {
+ return res.Interface(), nil
+ }
+ return res.Elem().Interface(), nil
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/interface_freebsd.go b/vendor/github.com/docker/libnetwork/osl/interface_freebsd.go
new file mode 100644
index 0000000..9c0141f
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/interface_freebsd.go
@@ -0,0 +1,4 @@
+package osl
+
+// IfaceOption is a function option type to set interface options
+type IfaceOption func()
diff --git a/vendor/github.com/docker/libnetwork/osl/interface_linux.go b/vendor/github.com/docker/libnetwork/osl/interface_linux.go
new file mode 100644
index 0000000..ac174e6
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/interface_linux.go
@@ -0,0 +1,469 @@
+package osl
+
+import (
+ "fmt"
+ "net"
+ "regexp"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/ns"
+ "github.com/docker/libnetwork/types"
+ "github.com/vishvananda/netlink"
+ "github.com/vishvananda/netns"
+)
+
+// IfaceOption is a function option type to set interface options
+type IfaceOption func(i *nwIface)
+
+type nwIface struct {
+ srcName string
+ dstName string
+ master string
+ dstMaster string
+ mac net.HardwareAddr
+ address *net.IPNet
+ addressIPv6 *net.IPNet
+ ipAliases []*net.IPNet
+ llAddrs []*net.IPNet
+ routes []*net.IPNet
+ bridge bool
+ ns *networkNamespace
+ sync.Mutex
+}
+
+func (i *nwIface) SrcName() string {
+ i.Lock()
+ defer i.Unlock()
+
+ return i.srcName
+}
+
+func (i *nwIface) DstName() string {
+ i.Lock()
+ defer i.Unlock()
+
+ return i.dstName
+}
+
+func (i *nwIface) DstMaster() string {
+ i.Lock()
+ defer i.Unlock()
+
+ return i.dstMaster
+}
+
+func (i *nwIface) Bridge() bool {
+ i.Lock()
+ defer i.Unlock()
+
+ return i.bridge
+}
+
+func (i *nwIface) Master() string {
+ i.Lock()
+ defer i.Unlock()
+
+ return i.master
+}
+
+func (i *nwIface) MacAddress() net.HardwareAddr {
+ i.Lock()
+ defer i.Unlock()
+
+ return types.GetMacCopy(i.mac)
+}
+
+func (i *nwIface) Address() *net.IPNet {
+ i.Lock()
+ defer i.Unlock()
+
+ return types.GetIPNetCopy(i.address)
+}
+
+func (i *nwIface) AddressIPv6() *net.IPNet {
+ i.Lock()
+ defer i.Unlock()
+
+ return types.GetIPNetCopy(i.addressIPv6)
+}
+
+func (i *nwIface) LinkLocalAddresses() []*net.IPNet {
+ i.Lock()
+ defer i.Unlock()
+
+ return i.llAddrs
+}
+
+func (i *nwIface) IPAliases() []*net.IPNet {
+ i.Lock()
+ defer i.Unlock()
+
+ return i.ipAliases
+}
+
+func (i *nwIface) Routes() []*net.IPNet {
+ i.Lock()
+ defer i.Unlock()
+
+ routes := make([]*net.IPNet, len(i.routes))
+ for index, route := range i.routes {
+ r := types.GetIPNetCopy(route)
+ routes[index] = r
+ }
+
+ return routes
+}
+
+func (n *networkNamespace) Interfaces() []Interface {
+ n.Lock()
+ defer n.Unlock()
+
+ ifaces := make([]Interface, len(n.iFaces))
+
+ for i, iface := range n.iFaces {
+ ifaces[i] = iface
+ }
+
+ return ifaces
+}
+
+func (i *nwIface) Remove() error {
+ i.Lock()
+ n := i.ns
+ i.Unlock()
+
+ n.Lock()
+ isDefault := n.isDefault
+ nlh := n.nlHandle
+ n.Unlock()
+
+ // Find the network interface identified by the DstName attribute.
+ iface, err := nlh.LinkByName(i.DstName())
+ if err != nil {
+ return err
+ }
+
+ // Down the interface before configuring
+ if err := nlh.LinkSetDown(iface); err != nil {
+ return err
+ }
+
+ err = nlh.LinkSetName(iface, i.SrcName())
+ if err != nil {
+ logrus.Debugf("LinkSetName failed for interface %s: %v", i.SrcName(), err)
+ return err
+ }
+
+ // if it is a bridge just delete it.
+ if i.Bridge() {
+ if err := nlh.LinkDel(iface); err != nil {
+ return fmt.Errorf("failed deleting bridge %q: %v", i.SrcName(), err)
+ }
+ } else if !isDefault {
+ // Move the network interface to caller namespace.
+ if err := nlh.LinkSetNsFd(iface, ns.ParseHandlerInt()); err != nil {
+ logrus.Debugf("LinkSetNsPid failed for interface %s: %v", i.SrcName(), err)
+ return err
+ }
+ }
+
+ n.Lock()
+ for index, intf := range n.iFaces {
+ if intf == i {
+ n.iFaces = append(n.iFaces[:index], n.iFaces[index+1:]...)
+ break
+ }
+ }
+ n.Unlock()
+
+ n.checkLoV6()
+
+ return nil
+}
+
+// Returns the sandbox's side veth interface statistics
+func (i *nwIface) Statistics() (*types.InterfaceStatistics, error) {
+ i.Lock()
+ n := i.ns
+ i.Unlock()
+
+ l, err := n.nlHandle.LinkByName(i.DstName())
+ if err != nil {
+ return nil, fmt.Errorf("failed to retrieve the statistics for %s in netns %s: %v", i.DstName(), n.path, err)
+ }
+
+ stats := l.Attrs().Statistics
+ if stats == nil {
+ return nil, fmt.Errorf("no statistics were returned")
+ }
+
+ return &types.InterfaceStatistics{
+ RxBytes: uint64(stats.RxBytes),
+ TxBytes: uint64(stats.TxBytes),
+ RxPackets: uint64(stats.RxPackets),
+ TxPackets: uint64(stats.TxPackets),
+ RxDropped: uint64(stats.RxDropped),
+ TxDropped: uint64(stats.TxDropped),
+ }, nil
+}
+
+func (n *networkNamespace) findDst(srcName string, isBridge bool) string {
+ n.Lock()
+ defer n.Unlock()
+
+ for _, i := range n.iFaces {
+ // The master should match the srcname of the interface and the
+ // master interface should be of type bridge, if searching for a bridge type
+ if i.SrcName() == srcName && (!isBridge || i.Bridge()) {
+ return i.DstName()
+ }
+ }
+
+ return ""
+}
+
+func (n *networkNamespace) AddInterface(srcName, dstPrefix string, options ...IfaceOption) error {
+ i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
+ i.processInterfaceOptions(options...)
+
+ if i.master != "" {
+ i.dstMaster = n.findDst(i.master, true)
+ if i.dstMaster == "" {
+ return fmt.Errorf("could not find an appropriate master %q for %q",
+ i.master, i.srcName)
+ }
+ }
+
+ n.Lock()
+ if n.isDefault {
+ i.dstName = i.srcName
+ } else {
+ i.dstName = fmt.Sprintf("%s%d", dstPrefix, n.nextIfIndex[dstPrefix])
+ n.nextIfIndex[dstPrefix]++
+ }
+
+ path := n.path
+ isDefault := n.isDefault
+ nlh := n.nlHandle
+ nlhHost := ns.NlHandle()
+ n.Unlock()
+
+ // If it is a bridge interface we have to create the bridge inside
+ // the namespace so don't try to lookup the interface using srcName
+ if i.bridge {
+ link := &netlink.Bridge{
+ LinkAttrs: netlink.LinkAttrs{
+ Name: i.srcName,
+ },
+ }
+ if err := nlh.LinkAdd(link); err != nil {
+ return fmt.Errorf("failed to create bridge %q: %v", i.srcName, err)
+ }
+ } else {
+ // Find the network interface identified by the SrcName attribute.
+ iface, err := nlhHost.LinkByName(i.srcName)
+ if err != nil {
+ return fmt.Errorf("failed to get link by name %q: %v", i.srcName, err)
+ }
+
+ // Move the network interface to the destination
+ // namespace only if the namespace is not a default
+ // type
+ if !isDefault {
+ newNs, err := netns.GetFromPath(path)
+ if err != nil {
+ return fmt.Errorf("failed get network namespace %q: %v", path, err)
+ }
+ defer newNs.Close()
+ if err := nlhHost.LinkSetNsFd(iface, int(newNs)); err != nil {
+ return fmt.Errorf("failed to set namespace on link %q: %v", i.srcName, err)
+ }
+ }
+ }
+
+ // Find the network interface identified by the SrcName attribute.
+ iface, err := nlh.LinkByName(i.srcName)
+ if err != nil {
+ return fmt.Errorf("failed to get link by name %q: %v", i.srcName, err)
+ }
+
+ // Down the interface before configuring
+ if err := nlh.LinkSetDown(iface); err != nil {
+ return fmt.Errorf("failed to set link down: %v", err)
+ }
+
+ // Configure the interface now this is moved in the proper namespace.
+ if err := configureInterface(nlh, iface, i); err != nil {
+ return err
+ }
+
+ // Up the interface.
+ cnt := 0
+ for err = nlh.LinkSetUp(iface); err != nil && cnt < 3; cnt++ {
+ logrus.Debugf("retrying link setup because of: %v", err)
+ time.Sleep(10 * time.Millisecond)
+ err = nlh.LinkSetUp(iface)
+ }
+ if err != nil {
+ return fmt.Errorf("failed to set link up: %v", err)
+ }
+
+ // Set the routes on the interface. This can only be done when the interface is up.
+ if err := setInterfaceRoutes(nlh, iface, i); err != nil {
+ return fmt.Errorf("error setting interface %q routes to %q: %v", iface.Attrs().Name, i.Routes(), err)
+ }
+
+ n.Lock()
+ n.iFaces = append(n.iFaces, i)
+ n.Unlock()
+
+ n.checkLoV6()
+
+ return nil
+}
+
+func configureInterface(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
+ ifaceName := iface.Attrs().Name
+ ifaceConfigurators := []struct {
+ Fn func(*netlink.Handle, netlink.Link, *nwIface) error
+ ErrMessage string
+ }{
+ {setInterfaceName, fmt.Sprintf("error renaming interface %q to %q", ifaceName, i.DstName())},
+ {setInterfaceMAC, fmt.Sprintf("error setting interface %q MAC to %q", ifaceName, i.MacAddress())},
+ {setInterfaceIP, fmt.Sprintf("error setting interface %q IP to %#v", ifaceName, i.Address())},
+ {setInterfaceIPv6, fmt.Sprintf("error setting interface %q IPv6 to %#v", ifaceName, i.AddressIPv6())},
+ {setInterfaceMaster, fmt.Sprintf("error setting interface %q master to %q", ifaceName, i.DstMaster())},
+ {setInterfaceLinkLocalIPs, fmt.Sprintf("error setting interface %q link local IPs to %v", ifaceName, i.LinkLocalAddresses())},
+ {setInterfaceIPAliases, fmt.Sprintf("error setting interface %q IP Aliases to %v", ifaceName, i.IPAliases())},
+ }
+
+ for _, config := range ifaceConfigurators {
+ if err := config.Fn(nlh, iface, i); err != nil {
+ return fmt.Errorf("%s: %v", config.ErrMessage, err)
+ }
+ }
+ return nil
+}
+
+func setInterfaceMaster(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
+ if i.DstMaster() == "" {
+ return nil
+ }
+
+ return nlh.LinkSetMaster(iface, &netlink.Bridge{
+ LinkAttrs: netlink.LinkAttrs{Name: i.DstMaster()}})
+}
+
+func setInterfaceMAC(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
+ if i.MacAddress() == nil {
+ return nil
+ }
+ return nlh.LinkSetHardwareAddr(iface, i.MacAddress())
+}
+
+func setInterfaceIP(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
+ if i.Address() == nil {
+ return nil
+ }
+ if err := checkRouteConflict(nlh, i.Address(), netlink.FAMILY_V4); err != nil {
+ return err
+ }
+ ipAddr := &netlink.Addr{IPNet: i.Address(), Label: ""}
+ return nlh.AddrAdd(iface, ipAddr)
+}
+
+func setInterfaceIPv6(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
+ if i.AddressIPv6() == nil {
+ return nil
+ }
+ if err := checkRouteConflict(nlh, i.AddressIPv6(), netlink.FAMILY_V6); err != nil {
+ return err
+ }
+ if err := setIPv6(i.ns.path, i.DstName(), true); err != nil {
+ return fmt.Errorf("failed to enable ipv6: %v", err)
+ }
+ ipAddr := &netlink.Addr{IPNet: i.AddressIPv6(), Label: "", Flags: syscall.IFA_F_NODAD}
+ return nlh.AddrAdd(iface, ipAddr)
+}
+
+func setInterfaceLinkLocalIPs(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
+ for _, llIP := range i.LinkLocalAddresses() {
+ ipAddr := &netlink.Addr{IPNet: llIP}
+ if err := nlh.AddrAdd(iface, ipAddr); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func setInterfaceIPAliases(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
+ for _, si := range i.IPAliases() {
+ ipAddr := &netlink.Addr{IPNet: si}
+ if err := nlh.AddrAdd(iface, ipAddr); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func setInterfaceName(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
+ return nlh.LinkSetName(iface, i.DstName())
+}
+
+func setInterfaceRoutes(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
+ for _, route := range i.Routes() {
+ err := nlh.RouteAdd(&netlink.Route{
+ Scope: netlink.SCOPE_LINK,
+ LinkIndex: iface.Attrs().Index,
+ Dst: route,
+ })
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// In older kernels (like the one in Centos 6.6 distro) sysctl does not have netns support. Therefore
+// we cannot gather the statistics from /sys/class/net/<dev>/statistics/<counter> files. Per-netns stats
+// are naturally found in /proc/net/dev in kernels which support netns (ifconfig relies on that).
+const (
+ netStatsFile = "/proc/net/dev"
+ base = "[ ]*%s:([ ]+[0-9]+){16}"
+)
+
+func scanInterfaceStats(data, ifName string, i *types.InterfaceStatistics) error {
+ var (
+ bktStr string
+ bkt uint64
+ )
+
+ regex := fmt.Sprintf(base, ifName)
+ re := regexp.MustCompile(regex)
+ line := re.FindString(data)
+
+ _, err := fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d",
+ &bktStr, &i.RxBytes, &i.RxPackets, &i.RxErrors, &i.RxDropped, &bkt, &bkt, &bkt,
+ &bkt, &i.TxBytes, &i.TxPackets, &i.TxErrors, &i.TxDropped, &bkt, &bkt, &bkt, &bkt)
+
+ return err
+}
+
+func checkRouteConflict(nlh *netlink.Handle, address *net.IPNet, family int) error {
+ routes, err := nlh.RouteList(nil, family)
+ if err != nil {
+ return err
+ }
+ for _, route := range routes {
+ if route.Dst != nil {
+ if route.Dst.Contains(address.IP) || address.Contains(route.Dst.IP) {
+ return fmt.Errorf("cannot program address %v in sandbox interface because it conflicts with existing route %s",
+ address, route)
+ }
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/interface_solaris.go b/vendor/github.com/docker/libnetwork/osl/interface_solaris.go
new file mode 100644
index 0000000..9c0141f
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/interface_solaris.go
@@ -0,0 +1,4 @@
+package osl
+
+// IfaceOption is a function option type to set interface options
+type IfaceOption func()
diff --git a/vendor/github.com/docker/libnetwork/osl/interface_windows.go b/vendor/github.com/docker/libnetwork/osl/interface_windows.go
new file mode 100644
index 0000000..9c0141f
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/interface_windows.go
@@ -0,0 +1,4 @@
+package osl
+
+// IfaceOption is a function option type to set interface options
+type IfaceOption func()
diff --git a/vendor/github.com/docker/libnetwork/osl/namespace_linux.go b/vendor/github.com/docker/libnetwork/osl/namespace_linux.go
new file mode 100644
index 0000000..d6b9d78
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/namespace_linux.go
@@ -0,0 +1,610 @@
+package osl
+
+import (
+ "fmt"
+ "io/ioutil"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/reexec"
+ "github.com/docker/libnetwork/ns"
+ "github.com/docker/libnetwork/types"
+ "github.com/vishvananda/netlink"
+ "github.com/vishvananda/netns"
+)
+
+const defaultPrefix = "/var/run/docker"
+
+func init() {
+ reexec.Register("set-ipv6", reexecSetIPv6)
+}
+
+var (
+ once sync.Once
+ garbagePathMap = make(map[string]bool)
+ gpmLock sync.Mutex
+ gpmWg sync.WaitGroup
+ gpmCleanupPeriod = 60 * time.Second
+ gpmChan = make(chan chan struct{})
+ prefix = defaultPrefix
+)
+
+// The networkNamespace type is the linux implementation of the Sandbox
+// interface. It represents a linux network namespace, and moves an interface
+// into it when called on method AddInterface or sets the gateway etc.
+type networkNamespace struct {
+ path string
+ iFaces []*nwIface
+ gw net.IP
+ gwv6 net.IP
+ staticRoutes []*types.StaticRoute
+ neighbors []*neigh
+ nextIfIndex map[string]int
+ isDefault bool
+ nlHandle *netlink.Handle
+ loV6Enabled bool
+ sync.Mutex
+}
+
+// SetBasePath sets the base url prefix for the ns path
+func SetBasePath(path string) {
+ prefix = path
+}
+
+func init() {
+ reexec.Register("netns-create", reexecCreateNamespace)
+}
+
+func basePath() string {
+ return filepath.Join(prefix, "netns")
+}
+
+func createBasePath() {
+ err := os.MkdirAll(basePath(), 0755)
+ if err != nil {
+ panic("Could not create net namespace path directory")
+ }
+
+ // Start the garbage collection go routine
+ go removeUnusedPaths()
+}
+
+func removeUnusedPaths() {
+ gpmLock.Lock()
+ period := gpmCleanupPeriod
+ gpmLock.Unlock()
+
+ ticker := time.NewTicker(period)
+ for {
+ var (
+ gc chan struct{}
+ gcOk bool
+ )
+
+ select {
+ case <-ticker.C:
+ case gc, gcOk = <-gpmChan:
+ }
+
+ gpmLock.Lock()
+ pathList := make([]string, 0, len(garbagePathMap))
+ for path := range garbagePathMap {
+ pathList = append(pathList, path)
+ }
+ garbagePathMap = make(map[string]bool)
+ gpmWg.Add(1)
+ gpmLock.Unlock()
+
+ for _, path := range pathList {
+ os.Remove(path)
+ }
+
+ gpmWg.Done()
+ if gcOk {
+ close(gc)
+ }
+ }
+}
+
+func addToGarbagePaths(path string) {
+ gpmLock.Lock()
+ garbagePathMap[path] = true
+ gpmLock.Unlock()
+}
+
+func removeFromGarbagePaths(path string) {
+ gpmLock.Lock()
+ delete(garbagePathMap, path)
+ gpmLock.Unlock()
+}
+
+// GC triggers garbage collection of namespace path right away
+// and waits for it.
+func GC() {
+ gpmLock.Lock()
+ if len(garbagePathMap) == 0 {
+ // No need for GC if map is empty
+ gpmLock.Unlock()
+ return
+ }
+ gpmLock.Unlock()
+
+ // if content exists in the garbage paths
+ // we can trigger GC to run, providing a
+ // channel to be notified on completion
+ waitGC := make(chan struct{})
+ gpmChan <- waitGC
+ // wait for GC completion
+ <-waitGC
+}
+
+// GenerateKey generates a sandbox key based on the passed
+// container id.
+func GenerateKey(containerID string) string {
+ maxLen := 12
+ // Read sandbox key from host for overlay
+ if strings.HasPrefix(containerID, "-") {
+ var (
+ index int
+ indexStr string
+ tmpkey string
+ )
+ dir, err := ioutil.ReadDir(basePath())
+ if err != nil {
+ return ""
+ }
+
+ for _, v := range dir {
+ id := v.Name()
+ if strings.HasSuffix(id, containerID[:maxLen-1]) {
+ indexStr = strings.TrimSuffix(id, containerID[:maxLen-1])
+ tmpindex, err := strconv.Atoi(indexStr)
+ if err != nil {
+ return ""
+ }
+ if tmpindex > index {
+ index = tmpindex
+ tmpkey = id
+ }
+
+ }
+ }
+ containerID = tmpkey
+ if containerID == "" {
+ return ""
+ }
+ }
+
+ if len(containerID) < maxLen {
+ maxLen = len(containerID)
+ }
+
+ return basePath() + "/" + containerID[:maxLen]
+}
+
+// NewSandbox provides a new sandbox instance created in an os specific way
+// provided a key which uniquely identifies the sandbox
+func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) {
+ if !isRestore {
+ err := createNetworkNamespace(key, osCreate)
+ if err != nil {
+ return nil, err
+ }
+ } else {
+ once.Do(createBasePath)
+ }
+
+ n := &networkNamespace{path: key, isDefault: !osCreate, nextIfIndex: make(map[string]int)}
+
+ sboxNs, err := netns.GetFromPath(n.path)
+ if err != nil {
+ return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err)
+ }
+ defer sboxNs.Close()
+
+ n.nlHandle, err = netlink.NewHandleAt(sboxNs, syscall.NETLINK_ROUTE)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create a netlink handle: %v", err)
+ }
+
+ err = n.nlHandle.SetSocketTimeout(ns.NetlinkSocketsTimeout)
+ if err != nil {
+ logrus.Warnf("Failed to set the timeout on the sandbox netlink handle sockets: %v", err)
+ }
+
+ // As starting point, disable IPv6 on all interfaces
+ if !n.isDefault {
+ err = setIPv6(n.path, "all", false)
+ if err != nil {
+ logrus.Warnf("Failed to disable IPv6 on all interfaces on network namespace %q: %v", n.path, err)
+ }
+ }
+
+ if err = n.loopbackUp(); err != nil {
+ n.nlHandle.Delete()
+ return nil, err
+ }
+
+ return n, nil
+}
+
+func (n *networkNamespace) InterfaceOptions() IfaceOptionSetter {
+ return n
+}
+
+func (n *networkNamespace) NeighborOptions() NeighborOptionSetter {
+ return n
+}
+
+func mountNetworkNamespace(basePath string, lnPath string) error {
+ return syscall.Mount(basePath, lnPath, "bind", syscall.MS_BIND, "")
+}
+
+// GetSandboxForExternalKey returns sandbox object for the supplied path
+func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) {
+ if err := createNamespaceFile(key); err != nil {
+ return nil, err
+ }
+
+ if err := mountNetworkNamespace(basePath, key); err != nil {
+ return nil, err
+ }
+ n := &networkNamespace{path: key, nextIfIndex: make(map[string]int)}
+
+ sboxNs, err := netns.GetFromPath(n.path)
+ if err != nil {
+ return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err)
+ }
+ defer sboxNs.Close()
+
+ n.nlHandle, err = netlink.NewHandleAt(sboxNs, syscall.NETLINK_ROUTE)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create a netlink handle: %v", err)
+ }
+
+ err = n.nlHandle.SetSocketTimeout(ns.NetlinkSocketsTimeout)
+ if err != nil {
+ logrus.Warnf("Failed to set the timeout on the sandbox netlink handle sockets: %v", err)
+ }
+
+ // As starting point, disable IPv6 on all interfaces
+ err = setIPv6(n.path, "all", false)
+ if err != nil {
+ logrus.Warnf("Failed to disable IPv6 on all interfaces on network namespace %q: %v", n.path, err)
+ }
+
+ if err = n.loopbackUp(); err != nil {
+ n.nlHandle.Delete()
+ return nil, err
+ }
+
+ return n, nil
+}
+
+func reexecCreateNamespace() {
+ if len(os.Args) < 2 {
+ logrus.Fatal("no namespace path provided")
+ }
+ if err := mountNetworkNamespace("/proc/self/ns/net", os.Args[1]); err != nil {
+ logrus.Fatal(err)
+ }
+}
+
+func createNetworkNamespace(path string, osCreate bool) error {
+ if err := createNamespaceFile(path); err != nil {
+ return err
+ }
+
+ cmd := &exec.Cmd{
+ Path: reexec.Self(),
+ Args: append([]string{"netns-create"}, path),
+ Stdout: os.Stdout,
+ Stderr: os.Stderr,
+ }
+ if osCreate {
+ cmd.SysProcAttr = &syscall.SysProcAttr{}
+ cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
+ }
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("namespace creation reexec command failed: %v", err)
+ }
+
+ return nil
+}
+
+func unmountNamespaceFile(path string) {
+ if _, err := os.Stat(path); err == nil {
+ syscall.Unmount(path, syscall.MNT_DETACH)
+ }
+}
+
+func createNamespaceFile(path string) (err error) {
+ var f *os.File
+
+ once.Do(createBasePath)
+ // Remove it from garbage collection list if present
+ removeFromGarbagePaths(path)
+
+ // If the path is there unmount it first
+ unmountNamespaceFile(path)
+
+ // wait for garbage collection to complete if it is in progress
+ // before trying to create the file.
+ gpmWg.Wait()
+
+ if f, err = os.Create(path); err == nil {
+ f.Close()
+ }
+
+ return err
+}
+
+func (n *networkNamespace) loopbackUp() error {
+ iface, err := n.nlHandle.LinkByName("lo")
+ if err != nil {
+ return err
+ }
+ return n.nlHandle.LinkSetUp(iface)
+}
+
+func (n *networkNamespace) InvokeFunc(f func()) error {
+ return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error {
+ f()
+ return nil
+ })
+}
+
+// InitOSContext initializes OS context while configuring network resources
+func InitOSContext() func() {
+ runtime.LockOSThread()
+ if err := ns.SetNamespace(); err != nil {
+ logrus.Error(err)
+ }
+ return runtime.UnlockOSThread
+}
+
+func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
+ defer InitOSContext()()
+
+ newNs, err := netns.GetFromPath(path)
+ if err != nil {
+ return fmt.Errorf("failed get network namespace %q: %v", path, err)
+ }
+ defer newNs.Close()
+
+ // Invoked before the namespace switch happens but after the namespace file
+ // handle is obtained.
+ if err := prefunc(int(newNs)); err != nil {
+ return fmt.Errorf("failed in prefunc: %v", err)
+ }
+
+ if err = netns.Set(newNs); err != nil {
+ return err
+ }
+ defer ns.SetNamespace()
+
+ // Invoked after the namespace switch.
+ return postfunc(ns.ParseHandlerInt())
+}
+
+func (n *networkNamespace) nsPath() string {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.path
+}
+
+func (n *networkNamespace) Info() Info {
+ return n
+}
+
+func (n *networkNamespace) Key() string {
+ return n.path
+}
+
+func (n *networkNamespace) Destroy() error {
+ if n.nlHandle != nil {
+ n.nlHandle.Delete()
+ }
+ // Assuming no running process is executing in this network namespace,
+ // unmounting is sufficient to destroy it.
+ if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
+ return err
+ }
+
+ // Stash it into the garbage collection list
+ addToGarbagePaths(n.path)
+ return nil
+}
+
+// Restore restore the network namespace
+func (n *networkNamespace) Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error {
+ // restore interfaces
+ for name, opts := range ifsopt {
+ if !strings.Contains(name, "+") {
+ return fmt.Errorf("wrong iface name in restore osl sandbox interface: %s", name)
+ }
+ seps := strings.Split(name, "+")
+ srcName := seps[0]
+ dstPrefix := seps[1]
+ i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
+ i.processInterfaceOptions(opts...)
+ if i.master != "" {
+ i.dstMaster = n.findDst(i.master, true)
+ if i.dstMaster == "" {
+ return fmt.Errorf("could not find an appropriate master %q for %q",
+ i.master, i.srcName)
+ }
+ }
+ if n.isDefault {
+ i.dstName = i.srcName
+ } else {
+ links, err := n.nlHandle.LinkList()
+ if err != nil {
+ return fmt.Errorf("failed to retrieve list of links in network namespace %q during restore", n.path)
+ }
+ // due to the docker network connect/disconnect, so the dstName should
+ // restore from the namespace
+ for _, link := range links {
+ addrs, err := n.nlHandle.AddrList(link, netlink.FAMILY_V4)
+ if err != nil {
+ return err
+ }
+ ifaceName := link.Attrs().Name
+ if strings.HasPrefix(ifaceName, "vxlan") {
+ if i.dstName == "vxlan" {
+ i.dstName = ifaceName
+ break
+ }
+ }
+ // find the interface name by ip
+ if i.address != nil {
+ for _, addr := range addrs {
+ if addr.IPNet.String() == i.address.String() {
+ i.dstName = ifaceName
+ break
+ }
+ continue
+ }
+ if i.dstName == ifaceName {
+ break
+ }
+ }
+ // This is to find the interface name of the pair in overlay sandbox
+ if strings.HasPrefix(ifaceName, "veth") {
+ if i.master != "" && i.dstName == "veth" {
+ i.dstName = ifaceName
+ }
+ }
+ }
+
+ var index int
+ indexStr := strings.TrimPrefix(i.dstName, dstPrefix)
+ if indexStr != "" {
+ index, err = strconv.Atoi(indexStr)
+ if err != nil {
+ return err
+ }
+ }
+ index++
+ n.Lock()
+ if index > n.nextIfIndex[dstPrefix] {
+ n.nextIfIndex[dstPrefix] = index
+ }
+ n.iFaces = append(n.iFaces, i)
+ n.Unlock()
+ }
+ }
+
+ // restore routes
+ for _, r := range routes {
+ n.Lock()
+ n.staticRoutes = append(n.staticRoutes, r)
+ n.Unlock()
+ }
+
+ // restore gateway
+ if len(gw) > 0 {
+ n.Lock()
+ n.gw = gw
+ n.Unlock()
+ }
+
+ if len(gw6) > 0 {
+ n.Lock()
+ n.gwv6 = gw6
+ n.Unlock()
+ }
+
+ return nil
+}
+
+// Checks whether IPv6 needs to be enabled/disabled on the loopback interface
+func (n *networkNamespace) checkLoV6() {
+ var (
+ enable = false
+ action = "disable"
+ )
+
+ n.Lock()
+ for _, iface := range n.iFaces {
+ if iface.AddressIPv6() != nil {
+ enable = true
+ action = "enable"
+ break
+ }
+ }
+ n.Unlock()
+
+ if n.loV6Enabled == enable {
+ return
+ }
+
+ if err := setIPv6(n.path, "lo", enable); err != nil {
+ logrus.Warnf("Failed to %s IPv6 on loopback interface on network namespace %q: %v", action, n.path, err)
+ }
+
+ n.loV6Enabled = enable
+}
+
+func reexecSetIPv6() {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+
+ if len(os.Args) < 3 {
+ logrus.Errorf("invalid number of arguments for %s", os.Args[0])
+ os.Exit(1)
+ }
+
+ ns, err := netns.GetFromPath(os.Args[1])
+ if err != nil {
+ logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
+ os.Exit(2)
+ }
+ defer ns.Close()
+
+ if err = netns.Set(ns); err != nil {
+ logrus.Errorf("setting into container netns %q failed: %v", os.Args[1], err)
+ os.Exit(3)
+ }
+
+ var (
+ action = "disable"
+ value = byte('1')
+ path = fmt.Sprintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", os.Args[2])
+ )
+
+ if os.Args[3] == "true" {
+ action = "enable"
+ value = byte('0')
+ }
+
+ if err = ioutil.WriteFile(path, []byte{value, '\n'}, 0644); err != nil {
+ logrus.Errorf("failed to %s IPv6 forwarding for container's interface %s: %v", action, os.Args[2], err)
+ os.Exit(4)
+ }
+
+ os.Exit(0)
+}
+
+func setIPv6(path, iface string, enable bool) error {
+ cmd := &exec.Cmd{
+ Path: reexec.Self(),
+ Args: append([]string{"set-ipv6"}, path, iface, strconv.FormatBool(enable)),
+ Stdout: os.Stdout,
+ Stderr: os.Stderr,
+ }
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("reexec to set IPv6 failed: %v", err)
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/namespace_unsupported.go b/vendor/github.com/docker/libnetwork/osl/namespace_unsupported.go
new file mode 100644
index 0000000..74372e2
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/namespace_unsupported.go
@@ -0,0 +1,17 @@
+// +build !linux,!windows,!freebsd
+
+package osl
+
+// GC triggers garbage collection of namespace path right away
+// and waits for it.
+func GC() {
+}
+
+// GetSandboxForExternalKey returns sandbox object for the supplied path
+func GetSandboxForExternalKey(path string, key string) (Sandbox, error) {
+ return nil, nil
+}
+
+// SetBasePath sets the base url prefix for the ns path
+func SetBasePath(path string) {
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/namespace_windows.go b/vendor/github.com/docker/libnetwork/osl/namespace_windows.go
new file mode 100644
index 0000000..bfdca30
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/namespace_windows.go
@@ -0,0 +1,43 @@
+package osl
+
+import "testing"
+
+// GenerateKey generates a sandbox key based on the passed
+// container id.
+func GenerateKey(containerID string) string {
+ maxLen := 12
+ if len(containerID) < maxLen {
+ maxLen = len(containerID)
+ }
+
+ return containerID[:maxLen]
+}
+
+// NewSandbox provides a new sandbox instance created in an os specific way
+// provided a key which uniquely identifies the sandbox
+func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) {
+ return nil, nil
+}
+
+func GetSandboxForExternalKey(path string, key string) (Sandbox, error) {
+ return nil, nil
+}
+
+// GC triggers garbage collection of namespace path right away
+// and waits for it.
+func GC() {
+}
+
+// InitOSContext initializes OS context while configuring network resources
+func InitOSContext() func() {
+ return func() {}
+}
+
+// SetupTestOSContext sets up a separate test OS context in which tests will be executed.
+func SetupTestOSContext(t *testing.T) func() {
+ return func() {}
+}
+
+// SetBasePath sets the base url prefix for the ns path
+func SetBasePath(path string) {
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/neigh_freebsd.go b/vendor/github.com/docker/libnetwork/osl/neigh_freebsd.go
new file mode 100644
index 0000000..280f006
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/neigh_freebsd.go
@@ -0,0 +1,4 @@
+package osl
+
+// NeighOption is a function option type to set neighbor options
+type NeighOption func()
diff --git a/vendor/github.com/docker/libnetwork/osl/neigh_linux.go b/vendor/github.com/docker/libnetwork/osl/neigh_linux.go
new file mode 100644
index 0000000..161ffa7
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/neigh_linux.go
@@ -0,0 +1,181 @@
+package osl
+
+import (
+ "bytes"
+ "fmt"
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/vishvananda/netlink"
+)
+
+// NeighOption is a function option type to set interface options
+type NeighOption func(nh *neigh)
+
+type neigh struct {
+ dstIP net.IP
+ dstMac net.HardwareAddr
+ linkName string
+ linkDst string
+ family int
+}
+
+func (n *networkNamespace) findNeighbor(dstIP net.IP, dstMac net.HardwareAddr) *neigh {
+ n.Lock()
+ defer n.Unlock()
+
+ for _, nh := range n.neighbors {
+ if nh.dstIP.Equal(dstIP) && bytes.Equal(nh.dstMac, dstMac) {
+ return nh
+ }
+ }
+
+ return nil
+}
+
+func (n *networkNamespace) DeleteNeighbor(dstIP net.IP, dstMac net.HardwareAddr, osDelete bool) error {
+ var (
+ iface netlink.Link
+ err error
+ )
+
+ nh := n.findNeighbor(dstIP, dstMac)
+ if nh == nil {
+ return fmt.Errorf("could not find the neighbor entry to delete")
+ }
+
+ if osDelete {
+ n.Lock()
+ nlh := n.nlHandle
+ n.Unlock()
+
+ if nh.linkDst != "" {
+ iface, err = nlh.LinkByName(nh.linkDst)
+ if err != nil {
+ return fmt.Errorf("could not find interface with destination name %s: %v",
+ nh.linkDst, err)
+ }
+ }
+
+ nlnh := &netlink.Neigh{
+ IP: dstIP,
+ State: netlink.NUD_PERMANENT,
+ Family: nh.family,
+ }
+
+ if nlnh.Family > 0 {
+ nlnh.HardwareAddr = dstMac
+ nlnh.Flags = netlink.NTF_SELF
+ }
+
+ if nh.linkDst != "" {
+ nlnh.LinkIndex = iface.Attrs().Index
+ }
+
+ // If the kernel deletion fails for the neighbor entry still remote it
+ // from the namespace cache. Otherwise if the neighbor moves back to the
+ // same host again, kernel update can fail.
+ if err := nlh.NeighDel(nlnh); err != nil {
+ logrus.Warnf("Deleting neighbor IP %s, mac %s failed, %v", dstIP, dstMac, err)
+ }
+
+ // Delete the dynamic entry in the bridge
+ if nlnh.Family > 0 {
+ nlnh := &netlink.Neigh{
+ IP: dstIP,
+ Family: nh.family,
+ }
+
+ nlnh.HardwareAddr = dstMac
+ nlnh.Flags = netlink.NTF_MASTER
+ if nh.linkDst != "" {
+ nlnh.LinkIndex = iface.Attrs().Index
+ }
+ if err := nlh.NeighDel(nlnh); err != nil {
+ logrus.Warnf("Deleting bridge mac mac %s failed, %v", dstMac, err)
+ }
+ }
+ }
+
+ n.Lock()
+ for i, nh := range n.neighbors {
+ if nh.dstIP.Equal(dstIP) && bytes.Equal(nh.dstMac, dstMac) {
+ n.neighbors = append(n.neighbors[:i], n.neighbors[i+1:]...)
+ break
+ }
+ }
+ n.Unlock()
+ logrus.Debugf("Neighbor entry deleted for IP %v, mac %v", dstIP, dstMac)
+
+ return nil
+}
+
+func (n *networkNamespace) AddNeighbor(dstIP net.IP, dstMac net.HardwareAddr, force bool, options ...NeighOption) error {
+ var (
+ iface netlink.Link
+ err error
+ )
+
+ // If the namespace already has the neighbor entry but the AddNeighbor is called
+ // because of a miss notification (force flag) program the kernel anyway.
+ nh := n.findNeighbor(dstIP, dstMac)
+ if nh != nil {
+ if !force {
+ logrus.Warnf("Neighbor entry already present for IP %v, mac %v", dstIP, dstMac)
+ return nil
+ }
+ logrus.Warnf("Force kernel update, Neighbor entry already present for IP %v, mac %v", dstIP, dstMac)
+ }
+
+ nh = &neigh{
+ dstIP: dstIP,
+ dstMac: dstMac,
+ }
+
+ nh.processNeighOptions(options...)
+
+ if nh.linkName != "" {
+ nh.linkDst = n.findDst(nh.linkName, false)
+ if nh.linkDst == "" {
+ return fmt.Errorf("could not find the interface with name %s", nh.linkName)
+ }
+ }
+
+ n.Lock()
+ nlh := n.nlHandle
+ n.Unlock()
+
+ if nh.linkDst != "" {
+ iface, err = nlh.LinkByName(nh.linkDst)
+ if err != nil {
+ return fmt.Errorf("could not find interface with destination name %s: %v",
+ nh.linkDst, err)
+ }
+ }
+
+ nlnh := &netlink.Neigh{
+ IP: dstIP,
+ HardwareAddr: dstMac,
+ State: netlink.NUD_PERMANENT,
+ Family: nh.family,
+ }
+
+ if nlnh.Family > 0 {
+ nlnh.Flags = netlink.NTF_SELF
+ }
+
+ if nh.linkDst != "" {
+ nlnh.LinkIndex = iface.Attrs().Index
+ }
+
+ if err := nlh.NeighSet(nlnh); err != nil {
+ return fmt.Errorf("could not add neighbor entry: %v", err)
+ }
+
+ n.Lock()
+ n.neighbors = append(n.neighbors, nh)
+ n.Unlock()
+ logrus.Debugf("Neighbor entry added for IP %v, mac %v", dstIP, dstMac)
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/neigh_solaris.go b/vendor/github.com/docker/libnetwork/osl/neigh_solaris.go
new file mode 100644
index 0000000..ffa8d75
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/neigh_solaris.go
@@ -0,0 +1,4 @@
+package osl
+
+// NeighOption is a function option type to set interface options
+type NeighOption func()
diff --git a/vendor/github.com/docker/libnetwork/osl/neigh_windows.go b/vendor/github.com/docker/libnetwork/osl/neigh_windows.go
new file mode 100644
index 0000000..280f006
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/neigh_windows.go
@@ -0,0 +1,4 @@
+package osl
+
+// NeighOption is a function option type to set neighbor options
+type NeighOption func()
diff --git a/vendor/github.com/docker/libnetwork/osl/options_linux.go b/vendor/github.com/docker/libnetwork/osl/options_linux.go
new file mode 100644
index 0000000..64309d0
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/options_linux.go
@@ -0,0 +1,79 @@
+package osl
+
+import "net"
+
+func (nh *neigh) processNeighOptions(options ...NeighOption) {
+ for _, opt := range options {
+ if opt != nil {
+ opt(nh)
+ }
+ }
+}
+
+func (n *networkNamespace) LinkName(name string) NeighOption {
+ return func(nh *neigh) {
+ nh.linkName = name
+ }
+}
+
+func (n *networkNamespace) Family(family int) NeighOption {
+ return func(nh *neigh) {
+ nh.family = family
+ }
+}
+
+func (i *nwIface) processInterfaceOptions(options ...IfaceOption) {
+ for _, opt := range options {
+ if opt != nil {
+ opt(i)
+ }
+ }
+}
+
+func (n *networkNamespace) Bridge(isBridge bool) IfaceOption {
+ return func(i *nwIface) {
+ i.bridge = isBridge
+ }
+}
+
+func (n *networkNamespace) Master(name string) IfaceOption {
+ return func(i *nwIface) {
+ i.master = name
+ }
+}
+
+func (n *networkNamespace) MacAddress(mac net.HardwareAddr) IfaceOption {
+ return func(i *nwIface) {
+ i.mac = mac
+ }
+}
+
+func (n *networkNamespace) Address(addr *net.IPNet) IfaceOption {
+ return func(i *nwIface) {
+ i.address = addr
+ }
+}
+
+func (n *networkNamespace) AddressIPv6(addr *net.IPNet) IfaceOption {
+ return func(i *nwIface) {
+ i.addressIPv6 = addr
+ }
+}
+
+func (n *networkNamespace) LinkLocalAddresses(list []*net.IPNet) IfaceOption {
+ return func(i *nwIface) {
+ i.llAddrs = list
+ }
+}
+
+func (n *networkNamespace) IPAliases(list []*net.IPNet) IfaceOption {
+ return func(i *nwIface) {
+ i.ipAliases = list
+ }
+}
+
+func (n *networkNamespace) Routes(routes []*net.IPNet) IfaceOption {
+ return func(i *nwIface) {
+ i.routes = routes
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/route_linux.go b/vendor/github.com/docker/libnetwork/osl/route_linux.go
new file mode 100644
index 0000000..a9ff191
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/route_linux.go
@@ -0,0 +1,203 @@
+package osl
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/docker/libnetwork/types"
+ "github.com/vishvananda/netlink"
+)
+
+func (n *networkNamespace) Gateway() net.IP {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.gw
+}
+
+func (n *networkNamespace) GatewayIPv6() net.IP {
+ n.Lock()
+ defer n.Unlock()
+
+ return n.gwv6
+}
+
+func (n *networkNamespace) StaticRoutes() []*types.StaticRoute {
+ n.Lock()
+ defer n.Unlock()
+
+ routes := make([]*types.StaticRoute, len(n.staticRoutes))
+ for i, route := range n.staticRoutes {
+ r := route.GetCopy()
+ routes[i] = r
+ }
+
+ return routes
+}
+
+func (n *networkNamespace) setGateway(gw net.IP) {
+ n.Lock()
+ n.gw = gw
+ n.Unlock()
+}
+
+func (n *networkNamespace) setGatewayIPv6(gwv6 net.IP) {
+ n.Lock()
+ n.gwv6 = gwv6
+ n.Unlock()
+}
+
+func (n *networkNamespace) SetGateway(gw net.IP) error {
+ // Silently return if the gateway is empty
+ if len(gw) == 0 {
+ return nil
+ }
+
+ err := n.programGateway(gw, true)
+ if err == nil {
+ n.setGateway(gw)
+ }
+
+ return err
+}
+
+func (n *networkNamespace) UnsetGateway() error {
+ gw := n.Gateway()
+
+ // Silently return if the gateway is empty
+ if len(gw) == 0 {
+ return nil
+ }
+
+ err := n.programGateway(gw, false)
+ if err == nil {
+ n.setGateway(net.IP{})
+ }
+
+ return err
+}
+
+func (n *networkNamespace) programGateway(gw net.IP, isAdd bool) error {
+ gwRoutes, err := n.nlHandle.RouteGet(gw)
+ if err != nil {
+ return fmt.Errorf("route for the gateway %s could not be found: %v", gw, err)
+ }
+
+ var linkIndex int
+ for _, gwRoute := range gwRoutes {
+ if gwRoute.Gw == nil {
+ linkIndex = gwRoute.LinkIndex
+ break
+ }
+ }
+
+ if linkIndex == 0 {
+ return fmt.Errorf("Direct route for the gateway %s could not be found", gw)
+ }
+
+ if isAdd {
+ return n.nlHandle.RouteAdd(&netlink.Route{
+ Scope: netlink.SCOPE_UNIVERSE,
+ LinkIndex: linkIndex,
+ Gw: gw,
+ })
+ }
+
+ return n.nlHandle.RouteDel(&netlink.Route{
+ Scope: netlink.SCOPE_UNIVERSE,
+ LinkIndex: linkIndex,
+ Gw: gw,
+ })
+}
+
+// Program a route in to the namespace routing table.
+func (n *networkNamespace) programRoute(path string, dest *net.IPNet, nh net.IP) error {
+ gwRoutes, err := n.nlHandle.RouteGet(nh)
+ if err != nil {
+ return fmt.Errorf("route for the next hop %s could not be found: %v", nh, err)
+ }
+
+ return n.nlHandle.RouteAdd(&netlink.Route{
+ Scope: netlink.SCOPE_UNIVERSE,
+ LinkIndex: gwRoutes[0].LinkIndex,
+ Gw: nh,
+ Dst: dest,
+ })
+}
+
+// Delete a route from the namespace routing table.
+func (n *networkNamespace) removeRoute(path string, dest *net.IPNet, nh net.IP) error {
+ gwRoutes, err := n.nlHandle.RouteGet(nh)
+ if err != nil {
+ return fmt.Errorf("route for the next hop could not be found: %v", err)
+ }
+
+ return n.nlHandle.RouteDel(&netlink.Route{
+ Scope: netlink.SCOPE_UNIVERSE,
+ LinkIndex: gwRoutes[0].LinkIndex,
+ Gw: nh,
+ Dst: dest,
+ })
+}
+
+func (n *networkNamespace) SetGatewayIPv6(gwv6 net.IP) error {
+ // Silently return if the gateway is empty
+ if len(gwv6) == 0 {
+ return nil
+ }
+
+ err := n.programGateway(gwv6, true)
+ if err == nil {
+ n.setGatewayIPv6(gwv6)
+ }
+
+ return err
+}
+
+func (n *networkNamespace) UnsetGatewayIPv6() error {
+ gwv6 := n.GatewayIPv6()
+
+ // Silently return if the gateway is empty
+ if len(gwv6) == 0 {
+ return nil
+ }
+
+ err := n.programGateway(gwv6, false)
+ if err == nil {
+ n.Lock()
+ n.gwv6 = net.IP{}
+ n.Unlock()
+ }
+
+ return err
+}
+
+func (n *networkNamespace) AddStaticRoute(r *types.StaticRoute) error {
+ err := n.programRoute(n.nsPath(), r.Destination, r.NextHop)
+ if err == nil {
+ n.Lock()
+ n.staticRoutes = append(n.staticRoutes, r)
+ n.Unlock()
+ }
+ return err
+}
+
+func (n *networkNamespace) RemoveStaticRoute(r *types.StaticRoute) error {
+
+ err := n.removeRoute(n.nsPath(), r.Destination, r.NextHop)
+ if err == nil {
+ n.Lock()
+ lastIndex := len(n.staticRoutes) - 1
+ for i, v := range n.staticRoutes {
+ if v == r {
+ // Overwrite the route we're removing with the last element
+ n.staticRoutes[i] = n.staticRoutes[lastIndex]
+ // Shorten the slice to trim the extra element
+ n.staticRoutes = n.staticRoutes[:lastIndex]
+ break
+ }
+ }
+ n.Unlock()
+ }
+ return err
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/sandbox.go b/vendor/github.com/docker/libnetwork/osl/sandbox.go
new file mode 100644
index 0000000..64288f9
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/sandbox.go
@@ -0,0 +1,171 @@
+// Package osl describes structures and interfaces which abstract os entities
+package osl
+
+import (
+ "net"
+
+ "github.com/docker/libnetwork/types"
+)
+
+// Sandbox represents a network sandbox, identified by a specific key. It
+// holds a list of Interfaces, routes etc, and more can be added dynamically.
+type Sandbox interface {
+ // The path where the network namespace is mounted.
+ Key() string
+
+ // Add an existing Interface to this sandbox. The operation will rename
+ // from the Interface SrcName to DstName as it moves, and reconfigure the
+ // interface according to the specified settings. The caller is expected
+ // to only provide a prefix for DstName. The AddInterface api will auto-generate
+ // an appropriate suffix for the DstName to disambiguate.
+ AddInterface(SrcName string, DstPrefix string, options ...IfaceOption) error
+
+ // Set default IPv4 gateway for the sandbox
+ SetGateway(gw net.IP) error
+
+ // Set default IPv6 gateway for the sandbox
+ SetGatewayIPv6(gw net.IP) error
+
+ // Unset the previously set default IPv4 gateway in the sandbox
+ UnsetGateway() error
+
+ // Unset the previously set default IPv6 gateway in the sandbox
+ UnsetGatewayIPv6() error
+
+ // Add a static route to the sandbox.
+ AddStaticRoute(*types.StaticRoute) error
+
+ // Remove a static route from the sandbox.
+ RemoveStaticRoute(*types.StaticRoute) error
+
+ // AddNeighbor adds a neighbor entry into the sandbox.
+ AddNeighbor(dstIP net.IP, dstMac net.HardwareAddr, force bool, option ...NeighOption) error
+
+ // DeleteNeighbor deletes neighbor entry from the sandbox.
+ DeleteNeighbor(dstIP net.IP, dstMac net.HardwareAddr, osDelete bool) error
+
+ // Returns an interface with methods to set neighbor options.
+ NeighborOptions() NeighborOptionSetter
+
+ // Returns an interface with methods to set interface options.
+ InterfaceOptions() IfaceOptionSetter
+
+ //Invoke
+ InvokeFunc(func()) error
+
+ // Returns an interface with methods to get sandbox state.
+ Info() Info
+
+ // Destroy the sandbox
+ Destroy() error
+
+ // restore sandbox
+ Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error
+}
+
+// NeighborOptionSetter interface defines the option setter methods for interface options
+type NeighborOptionSetter interface {
+ // LinkName returns an option setter to set the srcName of the link that should
+ // be used in the neighbor entry
+ LinkName(string) NeighOption
+
+ // Family returns an option setter to set the address family for the neighbor
+ // entry. eg. AF_BRIDGE
+ Family(int) NeighOption
+}
+
+// IfaceOptionSetter interface defines the option setter methods for interface options.
+type IfaceOptionSetter interface {
+ // Bridge returns an option setter to set if the interface is a bridge.
+ Bridge(bool) IfaceOption
+
+ // MacAddress returns an option setter to set the MAC address.
+ MacAddress(net.HardwareAddr) IfaceOption
+
+ // Address returns an option setter to set IPv4 address.
+ Address(*net.IPNet) IfaceOption
+
+ // Address returns an option setter to set IPv6 address.
+ AddressIPv6(*net.IPNet) IfaceOption
+
+ // LinkLocalAddresses returns an option setter to set the link-local IP addresses.
+ LinkLocalAddresses([]*net.IPNet) IfaceOption
+
+ // IPAliases returns an option setter to set IP address Aliases
+ IPAliases([]*net.IPNet) IfaceOption
+
+ // Master returns an option setter to set the master interface if any for this
+ // interface. The master interface name should refer to the srcname of a
+ // previously added interface of type bridge.
+ Master(string) IfaceOption
+
+ // Address returns an option setter to set interface routes.
+ Routes([]*net.IPNet) IfaceOption
+}
+
+// Info represents all possible information that
+// the driver wants to place in the sandbox which includes
+// interfaces, routes and gateway
+type Info interface {
+ // The collection of Interface previously added with the AddInterface
+ // method. Note that this doesn't include network interfaces added in any
+ // other way (such as the default loopback interface which is automatically
+ // created on creation of a sandbox).
+ Interfaces() []Interface
+
+ // IPv4 gateway for the sandbox.
+ Gateway() net.IP
+
+ // IPv6 gateway for the sandbox.
+ GatewayIPv6() net.IP
+
+ // Additional static routes for the sandbox. (Note that directly
+ // connected routes are stored on the particular interface they refer to.)
+ StaticRoutes() []*types.StaticRoute
+
+ // TODO: Add ip tables etc.
+}
+
+// Interface represents the settings and identity of a network device. It is
+// used as a return type for Network.Link, and it is common practice for the
+// caller to use this information when moving interface SrcName from host
+// namespace to DstName in a different net namespace with the appropriate
+// network settings.
+type Interface interface {
+ // The name of the interface in the origin network namespace.
+ SrcName() string
+
+ // The name that will be assigned to the interface once moves inside a
+ // network namespace. When the caller passes in a DstName, it is only
+ // expected to pass a prefix. The name will modified with an appropriately
+ // auto-generated suffix.
+ DstName() string
+
+ // IPv4 address for the interface.
+ Address() *net.IPNet
+
+ // IPv6 address for the interface.
+ AddressIPv6() *net.IPNet
+
+ // LinkLocalAddresses returns the link-local IP addresses assigned to the interface.
+ LinkLocalAddresses() []*net.IPNet
+
+ // IPAliases returns the IP address aliases assigned to the interface.
+ IPAliases() []*net.IPNet
+
+ // IP routes for the interface.
+ Routes() []*net.IPNet
+
+ // Bridge returns true if the interface is a bridge
+ Bridge() bool
+
+ // Master returns the srcname of the master interface for this interface.
+ Master() string
+
+ // Remove an interface from the sandbox by renaming to original name
+ // and moving it out of the sandbox.
+ Remove() error
+
+ // Statistics returns the statistics for this interface
+ Statistics() (*types.InterfaceStatistics, error)
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/sandbox_freebsd.go b/vendor/github.com/docker/libnetwork/osl/sandbox_freebsd.go
new file mode 100644
index 0000000..e5bc627
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/sandbox_freebsd.go
@@ -0,0 +1,44 @@
+package osl
+
+import "testing"
+
+// GenerateKey generates a sandbox key based on the passed
+// container id.
+func GenerateKey(containerID string) string {
+ maxLen := 12
+ if len(containerID) < maxLen {
+ maxLen = len(containerID)
+ }
+
+ return containerID[:maxLen]
+}
+
+// NewSandbox provides a new sandbox instance created in an os specific way
+// provided a key which uniquely identifies the sandbox
+func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) {
+ return nil, nil
+}
+
+// GetSandboxForExternalKey returns sandbox object for the supplied path
+func GetSandboxForExternalKey(path string, key string) (Sandbox, error) {
+ return nil, nil
+}
+
+// GC triggers garbage collection of namespace path right away
+// and waits for it.
+func GC() {
+}
+
+// InitOSContext initializes OS context while configuring network resources
+func InitOSContext() func() {
+ return func() {}
+}
+
+// SetupTestOSContext sets up a separate test OS context in which tests will be executed.
+func SetupTestOSContext(t *testing.T) func() {
+ return func() {}
+}
+
+// SetBasePath sets the base url prefix for the ns path
+func SetBasePath(path string) {
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/sandbox_solaris.go b/vendor/github.com/docker/libnetwork/osl/sandbox_solaris.go
new file mode 100644
index 0000000..9de44e5
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/sandbox_solaris.go
@@ -0,0 +1,24 @@
+package osl
+
+// NewSandbox provides a new sandbox instance created in an os specific way
+// provided a key which uniquely identifies the sandbox
+func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) {
+ return nil, nil
+}
+
+// GenerateKey generates a sandbox key based on the passed
+// container id.
+func GenerateKey(containerID string) string {
+ maxLen := 12
+
+ if len(containerID) < maxLen {
+ maxLen = len(containerID)
+ }
+
+ return containerID[:maxLen]
+}
+
+// InitOSContext initializes OS context while configuring network resources
+func InitOSContext() func() {
+ return func() {}
+}
diff --git a/vendor/github.com/docker/libnetwork/osl/sandbox_unsupported.go b/vendor/github.com/docker/libnetwork/osl/sandbox_unsupported.go
new file mode 100644
index 0000000..49184d6
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/osl/sandbox_unsupported.go
@@ -0,0 +1,22 @@
+// +build !linux,!windows,!freebsd,!solaris
+
+package osl
+
+import "errors"
+
+var (
+ // ErrNotImplemented is for platforms which don't implement sandbox
+ ErrNotImplemented = errors.New("not implemented")
+)
+
+// NewSandbox provides a new sandbox instance created in an os specific way
+// provided a key which uniquely identifies the sandbox
+func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) {
+ return nil, ErrNotImplemented
+}
+
+// GenerateKey generates a sandbox key based on the passed
+// container id.
+func GenerateKey(containerID string) string {
+ return ""
+}
diff --git a/vendor/github.com/docker/libnetwork/portallocator/portallocator.go b/vendor/github.com/docker/libnetwork/portallocator/portallocator.go
new file mode 100644
index 0000000..b7f790b
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/portallocator/portallocator.go
@@ -0,0 +1,248 @@
+package portallocator
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "sync"
+)
+
+const (
+ // DefaultPortRangeStart indicates the first port in port range
+ DefaultPortRangeStart = 49153
+ // DefaultPortRangeEnd indicates the last port in port range
+ DefaultPortRangeEnd = 65535
+)
+
+type ipMapping map[string]protoMap
+
+var (
+ // ErrAllPortsAllocated is returned when no more ports are available
+ ErrAllPortsAllocated = errors.New("all ports are allocated")
+ // ErrUnknownProtocol is returned when an unknown protocol was specified
+ ErrUnknownProtocol = errors.New("unknown protocol")
+ defaultIP = net.ParseIP("0.0.0.0")
+ once sync.Once
+ instance *PortAllocator
+ createInstance = func() { instance = newInstance() }
+)
+
+// ErrPortAlreadyAllocated is the returned error information when a requested port is already being used
+type ErrPortAlreadyAllocated struct {
+ ip string
+ port int
+}
+
+func newErrPortAlreadyAllocated(ip string, port int) ErrPortAlreadyAllocated {
+ return ErrPortAlreadyAllocated{
+ ip: ip,
+ port: port,
+ }
+}
+
+// IP returns the address to which the used port is associated
+func (e ErrPortAlreadyAllocated) IP() string {
+ return e.ip
+}
+
+// Port returns the value of the already used port
+func (e ErrPortAlreadyAllocated) Port() int {
+ return e.port
+}
+
+// IPPort returns the address and the port in the form ip:port
+func (e ErrPortAlreadyAllocated) IPPort() string {
+ return fmt.Sprintf("%s:%d", e.ip, e.port)
+}
+
+// Error is the implementation of error.Error interface
+func (e ErrPortAlreadyAllocated) Error() string {
+ return fmt.Sprintf("Bind for %s:%d failed: port is already allocated", e.ip, e.port)
+}
+
+type (
+ // PortAllocator manages the transport ports database
+ PortAllocator struct {
+ mutex sync.Mutex
+ ipMap ipMapping
+ Begin int
+ End int
+ }
+ portRange struct {
+ begin int
+ end int
+ last int
+ }
+ portMap struct {
+ p map[int]struct{}
+ defaultRange string
+ portRanges map[string]*portRange
+ }
+ protoMap map[string]*portMap
+)
+
+// Get returns the default instance of PortAllocator
+func Get() *PortAllocator {
+ // Port Allocator is a singleton
+ // Note: Long term solution will be each PortAllocator will have access to
+ // the OS so that it can have up to date view of the OS port allocation.
+ // When this happens singleton behavior will be removed. Clients do not
+ // need to worry about this, they will not see a change in behavior.
+ once.Do(createInstance)
+ return instance
+}
+
+func newInstance() *PortAllocator {
+ start, end, err := getDynamicPortRange()
+ if err != nil {
+ start, end = DefaultPortRangeStart, DefaultPortRangeEnd
+ }
+ return &PortAllocator{
+ ipMap: ipMapping{},
+ Begin: start,
+ End: end,
+ }
+}
+
+// RequestPort requests new port from global ports pool for specified ip and proto.
+// If port is 0 it returns first free port. Otherwise it checks port availability
+// in proto's pool and returns that port or error if port is already busy.
+func (p *PortAllocator) RequestPort(ip net.IP, proto string, port int) (int, error) {
+ return p.RequestPortInRange(ip, proto, port, port)
+}
+
+// RequestPortInRange requests new port from global ports pool for specified ip and proto.
+// If portStart and portEnd are 0 it returns the first free port in the default ephemeral range.
+// If portStart != portEnd it returns the first free port in the requested range.
+// Otherwise (portStart == portEnd) it checks port availability in the requested proto's port-pool
+// and returns that port or error if port is already busy.
+func (p *PortAllocator) RequestPortInRange(ip net.IP, proto string, portStart, portEnd int) (int, error) {
+ p.mutex.Lock()
+ defer p.mutex.Unlock()
+
+ if proto != "tcp" && proto != "udp" {
+ return 0, ErrUnknownProtocol
+ }
+
+ if ip == nil {
+ ip = defaultIP
+ }
+ ipstr := ip.String()
+ protomap, ok := p.ipMap[ipstr]
+ if !ok {
+ protomap = protoMap{
+ "tcp": p.newPortMap(),
+ "udp": p.newPortMap(),
+ }
+
+ p.ipMap[ipstr] = protomap
+ }
+ mapping := protomap[proto]
+ if portStart > 0 && portStart == portEnd {
+ if _, ok := mapping.p[portStart]; !ok {
+ mapping.p[portStart] = struct{}{}
+ return portStart, nil
+ }
+ return 0, newErrPortAlreadyAllocated(ipstr, portStart)
+ }
+
+ port, err := mapping.findPort(portStart, portEnd)
+ if err != nil {
+ return 0, err
+ }
+ return port, nil
+}
+
+// ReleasePort releases port from global ports pool for specified ip and proto.
+func (p *PortAllocator) ReleasePort(ip net.IP, proto string, port int) error {
+ p.mutex.Lock()
+ defer p.mutex.Unlock()
+
+ if ip == nil {
+ ip = defaultIP
+ }
+ protomap, ok := p.ipMap[ip.String()]
+ if !ok {
+ return nil
+ }
+ delete(protomap[proto].p, port)
+ return nil
+}
+
+func (p *PortAllocator) newPortMap() *portMap {
+ defaultKey := getRangeKey(p.Begin, p.End)
+ pm := &portMap{
+ p: map[int]struct{}{},
+ defaultRange: defaultKey,
+ portRanges: map[string]*portRange{
+ defaultKey: newPortRange(p.Begin, p.End),
+ },
+ }
+ return pm
+}
+
+// ReleaseAll releases all ports for all ips.
+func (p *PortAllocator) ReleaseAll() error {
+ p.mutex.Lock()
+ p.ipMap = ipMapping{}
+ p.mutex.Unlock()
+ return nil
+}
+
+func getRangeKey(portStart, portEnd int) string {
+ return fmt.Sprintf("%d-%d", portStart, portEnd)
+}
+
+func newPortRange(portStart, portEnd int) *portRange {
+ return &portRange{
+ begin: portStart,
+ end: portEnd,
+ last: portEnd,
+ }
+}
+
+func (pm *portMap) getPortRange(portStart, portEnd int) (*portRange, error) {
+ var key string
+ if portStart == 0 && portEnd == 0 {
+ key = pm.defaultRange
+ } else {
+ key = getRangeKey(portStart, portEnd)
+ if portStart == portEnd ||
+ portStart == 0 || portEnd == 0 ||
+ portEnd < portStart {
+ return nil, fmt.Errorf("invalid port range: %s", key)
+ }
+ }
+
+ // Return existing port range, if already known.
+ if pr, exists := pm.portRanges[key]; exists {
+ return pr, nil
+ }
+
+ // Otherwise create a new port range.
+ pr := newPortRange(portStart, portEnd)
+ pm.portRanges[key] = pr
+ return pr, nil
+}
+
+func (pm *portMap) findPort(portStart, portEnd int) (int, error) {
+ pr, err := pm.getPortRange(portStart, portEnd)
+ if err != nil {
+ return 0, err
+ }
+ port := pr.last
+
+ for i := 0; i <= pr.end-pr.begin; i++ {
+ port++
+ if port > pr.end {
+ port = pr.begin
+ }
+
+ if _, ok := pm.p[port]; !ok {
+ pm.p[port] = struct{}{}
+ pr.last = port
+ return port, nil
+ }
+ }
+ return 0, ErrAllPortsAllocated
+}
diff --git a/vendor/github.com/docker/libnetwork/portallocator/portallocator_linux.go b/vendor/github.com/docker/libnetwork/portallocator/portallocator_linux.go
new file mode 100644
index 0000000..687f6da
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/portallocator/portallocator_linux.go
@@ -0,0 +1,27 @@
+package portallocator
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+)
+
+func getDynamicPortRange() (start int, end int, err error) {
+ const portRangeKernelParam = "/proc/sys/net/ipv4/ip_local_port_range"
+ portRangeFallback := fmt.Sprintf("using fallback port range %d-%d", DefaultPortRangeStart, DefaultPortRangeEnd)
+ file, err := os.Open(portRangeKernelParam)
+ if err != nil {
+ return 0, 0, fmt.Errorf("port allocator - %s due to error: %v", portRangeFallback, err)
+ }
+
+ defer file.Close()
+
+ n, err := fmt.Fscanf(bufio.NewReader(file), "%d\t%d", &start, &end)
+ if n != 2 || err != nil {
+ if err == nil {
+ err = fmt.Errorf("unexpected count of parsed numbers (%d)", n)
+ }
+ return 0, 0, fmt.Errorf("port allocator - failed to parse system ephemeral port range from %s - %s: %v", portRangeKernelParam, portRangeFallback, err)
+ }
+ return start, end, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/portallocator/portallocator_solaris.go b/vendor/github.com/docker/libnetwork/portallocator/portallocator_solaris.go
new file mode 100644
index 0000000..ccc20b1
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/portallocator/portallocator_solaris.go
@@ -0,0 +1,5 @@
+package portallocator
+
+func getDynamicPortRange() (start int, end int, err error) {
+ return 32768, 65535, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/portmapper/mapper.go b/vendor/github.com/docker/libnetwork/portmapper/mapper.go
new file mode 100644
index 0000000..7f2a67c
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/portmapper/mapper.go
@@ -0,0 +1,241 @@
+package portmapper
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/iptables"
+ "github.com/docker/libnetwork/portallocator"
+)
+
+type mapping struct {
+ proto string
+ userlandProxy userlandProxy
+ host net.Addr
+ container net.Addr
+}
+
+var newProxy = newProxyCommand
+
+var (
+ // ErrUnknownBackendAddressType refers to an unknown container or unsupported address type
+ ErrUnknownBackendAddressType = errors.New("unknown container address type not supported")
+ // ErrPortMappedForIP refers to a port already mapped to an ip address
+ ErrPortMappedForIP = errors.New("port is already mapped to ip")
+ // ErrPortNotMapped refers to an unmapped port
+ ErrPortNotMapped = errors.New("port is not mapped")
+)
+
+// PortMapper manages the network address translation
+type PortMapper struct {
+ chain *iptables.ChainInfo
+ bridgeName string
+
+ // udp:ip:port
+ currentMappings map[string]*mapping
+ lock sync.Mutex
+
+ proxyPath string
+
+ Allocator *portallocator.PortAllocator
+}
+
+// New returns a new instance of PortMapper
+func New(proxyPath string) *PortMapper {
+ return NewWithPortAllocator(portallocator.Get(), proxyPath)
+}
+
+// NewWithPortAllocator returns a new instance of PortMapper which will use the specified PortAllocator
+func NewWithPortAllocator(allocator *portallocator.PortAllocator, proxyPath string) *PortMapper {
+ return &PortMapper{
+ currentMappings: make(map[string]*mapping),
+ Allocator: allocator,
+ proxyPath: proxyPath,
+ }
+}
+
+// SetIptablesChain sets the specified chain into portmapper
+func (pm *PortMapper) SetIptablesChain(c *iptables.ChainInfo, bridgeName string) {
+ pm.chain = c
+ pm.bridgeName = bridgeName
+}
+
+// Map maps the specified container transport address to the host's network address and transport port
+func (pm *PortMapper) Map(container net.Addr, hostIP net.IP, hostPort int, useProxy bool) (host net.Addr, err error) {
+ return pm.MapRange(container, hostIP, hostPort, hostPort, useProxy)
+}
+
+// MapRange maps the specified container transport address to the host's network address and transport port range
+func (pm *PortMapper) MapRange(container net.Addr, hostIP net.IP, hostPortStart, hostPortEnd int, useProxy bool) (host net.Addr, err error) {
+ pm.lock.Lock()
+ defer pm.lock.Unlock()
+
+ var (
+ m *mapping
+ proto string
+ allocatedHostPort int
+ )
+
+ switch container.(type) {
+ case *net.TCPAddr:
+ proto = "tcp"
+ if allocatedHostPort, err = pm.Allocator.RequestPortInRange(hostIP, proto, hostPortStart, hostPortEnd); err != nil {
+ return nil, err
+ }
+
+ m = &mapping{
+ proto: proto,
+ host: &net.TCPAddr{IP: hostIP, Port: allocatedHostPort},
+ container: container,
+ }
+
+ if useProxy {
+ m.userlandProxy, err = newProxy(proto, hostIP, allocatedHostPort, container.(*net.TCPAddr).IP, container.(*net.TCPAddr).Port, pm.proxyPath)
+ if err != nil {
+ return nil, err
+ }
+ } else {
+ m.userlandProxy = newDummyProxy(proto, hostIP, allocatedHostPort)
+ }
+ case *net.UDPAddr:
+ proto = "udp"
+ if allocatedHostPort, err = pm.Allocator.RequestPortInRange(hostIP, proto, hostPortStart, hostPortEnd); err != nil {
+ return nil, err
+ }
+
+ m = &mapping{
+ proto: proto,
+ host: &net.UDPAddr{IP: hostIP, Port: allocatedHostPort},
+ container: container,
+ }
+
+ if useProxy {
+ m.userlandProxy, err = newProxy(proto, hostIP, allocatedHostPort, container.(*net.UDPAddr).IP, container.(*net.UDPAddr).Port, pm.proxyPath)
+ if err != nil {
+ return nil, err
+ }
+ } else {
+ m.userlandProxy = newDummyProxy(proto, hostIP, allocatedHostPort)
+ }
+ default:
+ return nil, ErrUnknownBackendAddressType
+ }
+
+ // release the allocated port on any further error during return.
+ defer func() {
+ if err != nil {
+ pm.Allocator.ReleasePort(hostIP, proto, allocatedHostPort)
+ }
+ }()
+
+ key := getKey(m.host)
+ if _, exists := pm.currentMappings[key]; exists {
+ return nil, ErrPortMappedForIP
+ }
+
+ containerIP, containerPort := getIPAndPort(m.container)
+ if hostIP.To4() != nil {
+ if err := pm.forward(iptables.Append, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort); err != nil {
+ return nil, err
+ }
+ }
+
+ cleanup := func() error {
+ // need to undo the iptables rules before we return
+ m.userlandProxy.Stop()
+ if hostIP.To4() != nil {
+ pm.forward(iptables.Delete, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort)
+ if err := pm.Allocator.ReleasePort(hostIP, m.proto, allocatedHostPort); err != nil {
+ return err
+ }
+ }
+
+ return nil
+ }
+
+ if err := m.userlandProxy.Start(); err != nil {
+ if err := cleanup(); err != nil {
+ return nil, fmt.Errorf("Error during port allocation cleanup: %v", err)
+ }
+ return nil, err
+ }
+
+ pm.currentMappings[key] = m
+ return m.host, nil
+}
+
+// Unmap removes stored mapping for the specified host transport address
+func (pm *PortMapper) Unmap(host net.Addr) error {
+ pm.lock.Lock()
+ defer pm.lock.Unlock()
+
+ key := getKey(host)
+ data, exists := pm.currentMappings[key]
+ if !exists {
+ return ErrPortNotMapped
+ }
+
+ if data.userlandProxy != nil {
+ data.userlandProxy.Stop()
+ }
+
+ delete(pm.currentMappings, key)
+
+ containerIP, containerPort := getIPAndPort(data.container)
+ hostIP, hostPort := getIPAndPort(data.host)
+ if err := pm.forward(iptables.Delete, data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil {
+ logrus.Errorf("Error on iptables delete: %s", err)
+ }
+
+ switch a := host.(type) {
+ case *net.TCPAddr:
+ return pm.Allocator.ReleasePort(a.IP, "tcp", a.Port)
+ case *net.UDPAddr:
+ return pm.Allocator.ReleasePort(a.IP, "udp", a.Port)
+ }
+ return nil
+}
+
+//ReMapAll will re-apply all port mappings
+func (pm *PortMapper) ReMapAll() {
+ pm.lock.Lock()
+ defer pm.lock.Unlock()
+ logrus.Debugln("Re-applying all port mappings.")
+ for _, data := range pm.currentMappings {
+ containerIP, containerPort := getIPAndPort(data.container)
+ hostIP, hostPort := getIPAndPort(data.host)
+ if err := pm.forward(iptables.Append, data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil {
+ logrus.Errorf("Error on iptables add: %s", err)
+ }
+ }
+}
+
+func getKey(a net.Addr) string {
+ switch t := a.(type) {
+ case *net.TCPAddr:
+ return fmt.Sprintf("%s:%d/%s", t.IP.String(), t.Port, "tcp")
+ case *net.UDPAddr:
+ return fmt.Sprintf("%s:%d/%s", t.IP.String(), t.Port, "udp")
+ }
+ return ""
+}
+
+func getIPAndPort(a net.Addr) (net.IP, int) {
+ switch t := a.(type) {
+ case *net.TCPAddr:
+ return t.IP, t.Port
+ case *net.UDPAddr:
+ return t.IP, t.Port
+ }
+ return nil, 0
+}
+
+func (pm *PortMapper) forward(action iptables.Action, proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error {
+ if pm.chain == nil {
+ return nil
+ }
+ return pm.chain.Forward(action, sourceIP, sourcePort, proto, containerIP, containerPort, pm.bridgeName)
+}
diff --git a/vendor/github.com/docker/libnetwork/portmapper/mock_proxy.go b/vendor/github.com/docker/libnetwork/portmapper/mock_proxy.go
new file mode 100644
index 0000000..ceb7b02
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/portmapper/mock_proxy.go
@@ -0,0 +1,18 @@
+package portmapper
+
+import "net"
+
+func newMockProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int, userlandProxyPath string) (userlandProxy, error) {
+ return &mockProxyCommand{}, nil
+}
+
+type mockProxyCommand struct {
+}
+
+func (p *mockProxyCommand) Start() error {
+ return nil
+}
+
+func (p *mockProxyCommand) Stop() error {
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/portmapper/proxy.go b/vendor/github.com/docker/libnetwork/portmapper/proxy.go
new file mode 100644
index 0000000..a5bdc55
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/portmapper/proxy.go
@@ -0,0 +1,119 @@
+package portmapper
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net"
+ "os"
+ "os/exec"
+ "time"
+)
+
+const userlandProxyCommandName = "docker-proxy"
+
+type userlandProxy interface {
+ Start() error
+ Stop() error
+}
+
+// proxyCommand wraps an exec.Cmd to run the userland TCP and UDP
+// proxies as separate processes.
+type proxyCommand struct {
+ cmd *exec.Cmd
+}
+
+func (p *proxyCommand) Start() error {
+ r, w, err := os.Pipe()
+ if err != nil {
+ return fmt.Errorf("proxy unable to open os.Pipe %s", err)
+ }
+ defer r.Close()
+ p.cmd.ExtraFiles = []*os.File{w}
+ if err := p.cmd.Start(); err != nil {
+ return err
+ }
+ w.Close()
+
+ errchan := make(chan error, 1)
+ go func() {
+ buf := make([]byte, 2)
+ r.Read(buf)
+
+ if string(buf) != "0\n" {
+ errStr, err := ioutil.ReadAll(r)
+ if err != nil {
+ errchan <- fmt.Errorf("Error reading exit status from userland proxy: %v", err)
+ return
+ }
+
+ errchan <- fmt.Errorf("Error starting userland proxy: %s", errStr)
+ return
+ }
+ errchan <- nil
+ }()
+
+ select {
+ case err := <-errchan:
+ return err
+ case <-time.After(16 * time.Second):
+ return fmt.Errorf("Timed out proxy starting the userland proxy")
+ }
+}
+
+func (p *proxyCommand) Stop() error {
+ if p.cmd.Process != nil {
+ if err := p.cmd.Process.Signal(os.Interrupt); err != nil {
+ return err
+ }
+ return p.cmd.Wait()
+ }
+ return nil
+}
+
+// dummyProxy just listen on some port, it is needed to prevent accidental
+// port allocations on bound port, because without userland proxy we using
+// iptables rules and not net.Listen
+type dummyProxy struct {
+ listener io.Closer
+ addr net.Addr
+}
+
+func newDummyProxy(proto string, hostIP net.IP, hostPort int) userlandProxy {
+ switch proto {
+ case "tcp":
+ addr := &net.TCPAddr{IP: hostIP, Port: hostPort}
+ return &dummyProxy{addr: addr}
+ case "udp":
+ addr := &net.UDPAddr{IP: hostIP, Port: hostPort}
+ return &dummyProxy{addr: addr}
+ }
+ return nil
+}
+
+func (p *dummyProxy) Start() error {
+ switch addr := p.addr.(type) {
+ case *net.TCPAddr:
+ l, err := net.ListenTCP("tcp", addr)
+ if err != nil {
+ return err
+ }
+ p.listener = l
+ case *net.UDPAddr:
+ l, err := net.ListenUDP("udp", addr)
+ if err != nil {
+ return err
+ }
+ p.listener = l
+ default:
+ return fmt.Errorf("Unknown addr type: %T", p.addr)
+ }
+ return nil
+}
+
+func (p *dummyProxy) Stop() error {
+ if p.listener != nil {
+ return p.listener.Close()
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/portmapper/proxy_linux.go b/vendor/github.com/docker/libnetwork/portmapper/proxy_linux.go
new file mode 100644
index 0000000..947cd0b
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/portmapper/proxy_linux.go
@@ -0,0 +1,38 @@
+package portmapper
+
+import (
+ "net"
+ "os/exec"
+ "strconv"
+ "syscall"
+)
+
+func newProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int, proxyPath string) (userlandProxy, error) {
+ path := proxyPath
+ if proxyPath == "" {
+ cmd, err := exec.LookPath(userlandProxyCommandName)
+ if err != nil {
+ return nil, err
+ }
+ path = cmd
+ }
+
+ args := []string{
+ path,
+ "-proto", proto,
+ "-host-ip", hostIP.String(),
+ "-host-port", strconv.Itoa(hostPort),
+ "-container-ip", containerIP.String(),
+ "-container-port", strconv.Itoa(containerPort),
+ }
+
+ return &proxyCommand{
+ cmd: &exec.Cmd{
+ Path: path,
+ Args: args,
+ SysProcAttr: &syscall.SysProcAttr{
+ Pdeathsig: syscall.SIGTERM, // send a sigterm to the proxy if the daemon process dies
+ },
+ },
+ }, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/portmapper/proxy_solaris.go b/vendor/github.com/docker/libnetwork/portmapper/proxy_solaris.go
new file mode 100644
index 0000000..dc70b5e
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/portmapper/proxy_solaris.go
@@ -0,0 +1,34 @@
+package portmapper
+
+import (
+ "net"
+ "os/exec"
+ "strconv"
+)
+
+func newProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int, proxyPath string) (userlandProxy, error) {
+ path := proxyPath
+ if proxyPath == "" {
+ cmd, err := exec.LookPath(userlandProxyCommandName)
+ if err != nil {
+ return nil, err
+ }
+ path = cmd
+ }
+
+ args := []string{
+ path,
+ "-proto", proto,
+ "-host-ip", hostIP.String(),
+ "-host-port", strconv.Itoa(hostPort),
+ "-container-ip", containerIP.String(),
+ "-container-port", strconv.Itoa(containerPort),
+ }
+
+ return &proxyCommand{
+ cmd: &exec.Cmd{
+ Path: path,
+ Args: args,
+ },
+ }, nil
+}
diff --git a/vendor/github.com/docker/libnetwork/resolvconf/README.md b/vendor/github.com/docker/libnetwork/resolvconf/README.md
new file mode 100644
index 0000000..cdda554
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/resolvconf/README.md
@@ -0,0 +1 @@
+Package resolvconf provides utility code to query and update DNS configuration in /etc/resolv.conf
diff --git a/vendor/github.com/docker/libnetwork/resolvconf/dns/resolvconf.go b/vendor/github.com/docker/libnetwork/resolvconf/dns/resolvconf.go
new file mode 100644
index 0000000..e348bc5
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/resolvconf/dns/resolvconf.go
@@ -0,0 +1,26 @@
+package dns
+
+import (
+ "regexp"
+)
+
+// IPLocalhost is a regex pattern for IPv4 or IPv6 loopback range.
+const IPLocalhost = `((127\.([0-9]{1,3}\.){2}[0-9]{1,3})|(::1)$)`
+
+// IPv4Localhost is a regex pattern for IPv4 localhost address range.
+const IPv4Localhost = `(127\.([0-9]{1,3}\.){2}[0-9]{1,3})`
+
+var localhostIPRegexp = regexp.MustCompile(IPLocalhost)
+var localhostIPv4Regexp = regexp.MustCompile(IPv4Localhost)
+
+// IsLocalhost returns true if ip matches the localhost IP regular expression.
+// Used for determining if nameserver settings are being passed which are
+// localhost addresses
+func IsLocalhost(ip string) bool {
+ return localhostIPRegexp.MatchString(ip)
+}
+
+// IsIPv4Localhost returns true if ip matches the IPv4 localhost regular expression.
+func IsIPv4Localhost(ip string) bool {
+ return localhostIPv4Regexp.MatchString(ip)
+}
diff --git a/vendor/github.com/docker/libnetwork/resolvconf/resolvconf.go b/vendor/github.com/docker/libnetwork/resolvconf/resolvconf.go
new file mode 100644
index 0000000..9da6922
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/resolvconf/resolvconf.go
@@ -0,0 +1,254 @@
+// Package resolvconf provides utility code to query and update DNS configuration in /etc/resolv.conf
+package resolvconf
+
+import (
+ "bytes"
+ "io/ioutil"
+ "regexp"
+ "strings"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/ioutils"
+ "github.com/docker/libnetwork/resolvconf/dns"
+ "github.com/docker/libnetwork/types"
+)
+
+var (
+ // Note: the default IPv4 & IPv6 resolvers are set to Google's Public DNS
+ defaultIPv4Dns = []string{"nameserver 8.8.8.8", "nameserver 8.8.4.4"}
+ defaultIPv6Dns = []string{"nameserver 2001:4860:4860::8888", "nameserver 2001:4860:4860::8844"}
+ ipv4NumBlock = `(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)`
+ ipv4Address = `(` + ipv4NumBlock + `\.){3}` + ipv4NumBlock
+ // This is not an IPv6 address verifier as it will accept a super-set of IPv6, and also
+ // will *not match* IPv4-Embedded IPv6 Addresses (RFC6052), but that and other variants
+ // -- e.g. other link-local types -- either won't work in containers or are unnecessary.
+ // For readability and sufficiency for Docker purposes this seemed more reasonable than a
+ // 1000+ character regexp with exact and complete IPv6 validation
+ ipv6Address = `([0-9A-Fa-f]{0,4}:){2,7}([0-9A-Fa-f]{0,4})(%\w+)?`
+
+ localhostNSRegexp = regexp.MustCompile(`(?m)^nameserver\s+` + dns.IPLocalhost + `\s*\n*`)
+ nsIPv6Regexp = regexp.MustCompile(`(?m)^nameserver\s+` + ipv6Address + `\s*\n*`)
+ nsRegexp = regexp.MustCompile(`^\s*nameserver\s*((` + ipv4Address + `)|(` + ipv6Address + `))\s*$`)
+ nsIPv6Regexpmatch = regexp.MustCompile(`^\s*nameserver\s*((` + ipv6Address + `))\s*$`)
+ nsIPv4Regexpmatch = regexp.MustCompile(`^\s*nameserver\s*((` + ipv4Address + `))\s*$`)
+ searchRegexp = regexp.MustCompile(`^\s*search\s*(([^\s]+\s*)*)$`)
+ optionsRegexp = regexp.MustCompile(`^\s*options\s*(([^\s]+\s*)*)$`)
+)
+
+var lastModified struct {
+ sync.Mutex
+ sha256 string
+ contents []byte
+}
+
+// File contains the resolv.conf content and its hash
+type File struct {
+ Content []byte
+ Hash string
+}
+
+// Get returns the contents of /etc/resolv.conf and its hash
+func Get() (*File, error) {
+ resolv, err := ioutil.ReadFile("/etc/resolv.conf")
+ if err != nil {
+ return nil, err
+ }
+ hash, err := ioutils.HashData(bytes.NewReader(resolv))
+ if err != nil {
+ return nil, err
+ }
+ return &File{Content: resolv, Hash: hash}, nil
+}
+
+// GetSpecific returns the contents of the user specified resolv.conf file and its hash
+func GetSpecific(path string) (*File, error) {
+ resolv, err := ioutil.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ hash, err := ioutils.HashData(bytes.NewReader(resolv))
+ if err != nil {
+ return nil, err
+ }
+ return &File{Content: resolv, Hash: hash}, nil
+}
+
+// GetIfChanged retrieves the host /etc/resolv.conf file, checks against the last hash
+// and, if modified since last check, returns the bytes and new hash.
+// This feature is used by the resolv.conf updater for containers
+func GetIfChanged() (*File, error) {
+ lastModified.Lock()
+ defer lastModified.Unlock()
+
+ resolv, err := ioutil.ReadFile("/etc/resolv.conf")
+ if err != nil {
+ return nil, err
+ }
+ newHash, err := ioutils.HashData(bytes.NewReader(resolv))
+ if err != nil {
+ return nil, err
+ }
+ if lastModified.sha256 != newHash {
+ lastModified.sha256 = newHash
+ lastModified.contents = resolv
+ return &File{Content: resolv, Hash: newHash}, nil
+ }
+ // nothing changed, so return no data
+ return nil, nil
+}
+
+// GetLastModified retrieves the last used contents and hash of the host resolv.conf.
+// Used by containers updating on restart
+func GetLastModified() *File {
+ lastModified.Lock()
+ defer lastModified.Unlock()
+
+ return &File{Content: lastModified.contents, Hash: lastModified.sha256}
+}
+
+// FilterResolvDNS cleans up the config in resolvConf. It has two main jobs:
+// 1. It looks for localhost (127.*|::1) entries in the provided
+// resolv.conf, removing local nameserver entries, and, if the resulting
+// cleaned config has no defined nameservers left, adds default DNS entries
+// 2. Given the caller provides the enable/disable state of IPv6, the filter
+// code will remove all IPv6 nameservers if it is not enabled for containers
+//
+func FilterResolvDNS(resolvConf []byte, ipv6Enabled bool) (*File, error) {
+ cleanedResolvConf := localhostNSRegexp.ReplaceAll(resolvConf, []byte{})
+ // if IPv6 is not enabled, also clean out any IPv6 address nameserver
+ if !ipv6Enabled {
+ cleanedResolvConf = nsIPv6Regexp.ReplaceAll(cleanedResolvConf, []byte{})
+ }
+ // if the resulting resolvConf has no more nameservers defined, add appropriate
+ // default DNS servers for IPv4 and (optionally) IPv6
+ if len(GetNameservers(cleanedResolvConf, types.IP)) == 0 {
+ logrus.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers: %v", defaultIPv4Dns)
+ dns := defaultIPv4Dns
+ if ipv6Enabled {
+ logrus.Infof("IPv6 enabled; Adding default IPv6 external servers: %v", defaultIPv6Dns)
+ dns = append(dns, defaultIPv6Dns...)
+ }
+ cleanedResolvConf = append(cleanedResolvConf, []byte("\n"+strings.Join(dns, "\n"))...)
+ }
+ hash, err := ioutils.HashData(bytes.NewReader(cleanedResolvConf))
+ if err != nil {
+ return nil, err
+ }
+ return &File{Content: cleanedResolvConf, Hash: hash}, nil
+}
+
+// getLines parses input into lines and strips away comments.
+func getLines(input []byte, commentMarker []byte) [][]byte {
+ lines := bytes.Split(input, []byte("\n"))
+ var output [][]byte
+ for _, currentLine := range lines {
+ var commentIndex = bytes.Index(currentLine, commentMarker)
+ if commentIndex == -1 {
+ output = append(output, currentLine)
+ } else {
+ output = append(output, currentLine[:commentIndex])
+ }
+ }
+ return output
+}
+
+// GetNameservers returns nameservers (if any) listed in /etc/resolv.conf
+func GetNameservers(resolvConf []byte, kind int) []string {
+ nameservers := []string{}
+ for _, line := range getLines(resolvConf, []byte("#")) {
+ var ns [][]byte
+ if kind == types.IP {
+ ns = nsRegexp.FindSubmatch(line)
+ } else if kind == types.IPv4 {
+ ns = nsIPv4Regexpmatch.FindSubmatch(line)
+ } else if kind == types.IPv6 {
+ ns = nsIPv6Regexpmatch.FindSubmatch(line)
+ }
+ if len(ns) > 0 {
+ nameservers = append(nameservers, string(ns[1]))
+ }
+ }
+ return nameservers
+}
+
+// GetNameserversAsCIDR returns nameservers (if any) listed in
+// /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
+// This function's output is intended for net.ParseCIDR
+func GetNameserversAsCIDR(resolvConf []byte) []string {
+ nameservers := []string{}
+ for _, nameserver := range GetNameservers(resolvConf, types.IP) {
+ var address string
+ // If IPv6, strip zone if present
+ if strings.Contains(nameserver, ":") {
+ address = strings.Split(nameserver, "%")[0] + "/128"
+ } else {
+ address = nameserver + "/32"
+ }
+ nameservers = append(nameservers, address)
+ }
+ return nameservers
+}
+
+// GetSearchDomains returns search domains (if any) listed in /etc/resolv.conf
+// If more than one search line is encountered, only the contents of the last
+// one is returned.
+func GetSearchDomains(resolvConf []byte) []string {
+ domains := []string{}
+ for _, line := range getLines(resolvConf, []byte("#")) {
+ match := searchRegexp.FindSubmatch(line)
+ if match == nil {
+ continue
+ }
+ domains = strings.Fields(string(match[1]))
+ }
+ return domains
+}
+
+// GetOptions returns options (if any) listed in /etc/resolv.conf
+// If more than one options line is encountered, only the contents of the last
+// one is returned.
+func GetOptions(resolvConf []byte) []string {
+ options := []string{}
+ for _, line := range getLines(resolvConf, []byte("#")) {
+ match := optionsRegexp.FindSubmatch(line)
+ if match == nil {
+ continue
+ }
+ options = strings.Fields(string(match[1]))
+ }
+ return options
+}
+
+// Build writes a configuration file to path containing a "nameserver" entry
+// for every element in dns, a "search" entry for every element in
+// dnsSearch, and an "options" entry for every element in dnsOptions.
+func Build(path string, dns, dnsSearch, dnsOptions []string) (*File, error) {
+ content := bytes.NewBuffer(nil)
+ if len(dnsSearch) > 0 {
+ if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." {
+ if _, err := content.WriteString("search " + searchString + "\n"); err != nil {
+ return nil, err
+ }
+ }
+ }
+ for _, dns := range dns {
+ if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
+ return nil, err
+ }
+ }
+ if len(dnsOptions) > 0 {
+ if optsString := strings.Join(dnsOptions, " "); strings.Trim(optsString, " ") != "" {
+ if _, err := content.WriteString("options " + optsString + "\n"); err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ hash, err := ioutils.HashData(bytes.NewReader(content.Bytes()))
+ if err != nil {
+ return nil, err
+ }
+
+ return &File{Content: content.Bytes(), Hash: hash}, ioutil.WriteFile(path, content.Bytes(), 0644)
+}
diff --git a/vendor/github.com/docker/libnetwork/resolver.go b/vendor/github.com/docker/libnetwork/resolver.go
new file mode 100644
index 0000000..cc76926
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/resolver.go
@@ -0,0 +1,521 @@
+package libnetwork
+
+import (
+ "fmt"
+ "math/rand"
+ "net"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/types"
+ "github.com/miekg/dns"
+)
+
+// Resolver represents the embedded DNS server in Docker. It operates
+// by listening on container's loopback interface for DNS queries.
+type Resolver interface {
+ // Start starts the name server for the container
+ Start() error
+ // Stop stops the name server for the container. Stopped resolver
+ // can be reused after running the SetupFunc again.
+ Stop()
+ // SetupFunc() provides the setup function that should be run
+ // in the container's network namespace.
+ SetupFunc(int) func()
+ // NameServer() returns the IP of the DNS resolver for the
+ // containers.
+ NameServer() string
+ // SetExtServers configures the external nameservers the resolver
+ // should use to forward queries
+ SetExtServers([]extDNSEntry)
+ // ResolverOptions returns resolv.conf options that should be set
+ ResolverOptions() []string
+}
+
+// DNSBackend represents a backend DNS resolver used for DNS name
+// resolution. All the queries to the resolver are forwared to the
+// backend resolver.
+type DNSBackend interface {
+ // ResolveName resolves a service name to an IPv4 or IPv6 address by searching
+ // the networks the sandbox is connected to. For IPv6 queries, second return
+ // value will be true if the name exists in docker domain but doesn't have an
+ // IPv6 address. Such queries shouldn't be forwarded to external nameservers.
+ ResolveName(name string, iplen int) ([]net.IP, bool)
+ // ResolveIP returns the service name for the passed in IP. IP is in reverse dotted
+ // notation; the format used for DNS PTR records
+ ResolveIP(name string) string
+ // ResolveService returns all the backend details about the containers or hosts
+ // backing a service. Its purpose is to satisfy an SRV query
+ ResolveService(name string) ([]*net.SRV, []net.IP)
+ // ExecFunc allows a function to be executed in the context of the backend
+ // on behalf of the resolver.
+ ExecFunc(f func()) error
+ //NdotsSet queries the backends ndots dns option settings
+ NdotsSet() bool
+ // HandleQueryResp passes the name & IP from a response to the backend. backend
+ // can use it to maintain any required state about the resolution
+ HandleQueryResp(name string, ip net.IP)
+}
+
+const (
+ dnsPort = "53"
+ ptrIPv4domain = ".in-addr.arpa."
+ ptrIPv6domain = ".ip6.arpa."
+ respTTL = 600
+ maxExtDNS = 3 //max number of external servers to try
+ extIOTimeout = 4 * time.Second
+ defaultRespSize = 512
+ maxConcurrent = 100
+ logInterval = 2 * time.Second
+)
+
+type extDNSEntry struct {
+ IPStr string
+ HostLoopback bool
+}
+
+// resolver implements the Resolver interface
+type resolver struct {
+ backend DNSBackend
+ extDNSList [maxExtDNS]extDNSEntry
+ server *dns.Server
+ conn *net.UDPConn
+ tcpServer *dns.Server
+ tcpListen *net.TCPListener
+ err error
+ count int32
+ tStamp time.Time
+ queryLock sync.Mutex
+ listenAddress string
+ proxyDNS bool
+ resolverKey string
+ startCh chan struct{}
+}
+
+func init() {
+ rand.Seed(time.Now().Unix())
+}
+
+// NewResolver creates a new instance of the Resolver
+func NewResolver(address string, proxyDNS bool, resolverKey string, backend DNSBackend) Resolver {
+ return &resolver{
+ backend: backend,
+ proxyDNS: proxyDNS,
+ listenAddress: address,
+ resolverKey: resolverKey,
+ err: fmt.Errorf("setup not done yet"),
+ startCh: make(chan struct{}, 1),
+ }
+}
+
+func (r *resolver) SetupFunc(port int) func() {
+ return (func() {
+ var err error
+
+ // DNS operates primarily on UDP
+ addr := &net.UDPAddr{
+ IP: net.ParseIP(r.listenAddress),
+ Port: port,
+ }
+
+ r.conn, err = net.ListenUDP("udp", addr)
+ if err != nil {
+ r.err = fmt.Errorf("error in opening name server socket %v", err)
+ return
+ }
+
+ // Listen on a TCP as well
+ tcpaddr := &net.TCPAddr{
+ IP: net.ParseIP(r.listenAddress),
+ Port: port,
+ }
+
+ r.tcpListen, err = net.ListenTCP("tcp", tcpaddr)
+ if err != nil {
+ r.err = fmt.Errorf("error in opening name TCP server socket %v", err)
+ return
+ }
+ r.err = nil
+ })
+}
+
+func (r *resolver) Start() error {
+ r.startCh <- struct{}{}
+ defer func() { <-r.startCh }()
+
+ // make sure the resolver has been setup before starting
+ if r.err != nil {
+ return r.err
+ }
+
+ if err := r.setupIPTable(); err != nil {
+ return fmt.Errorf("setting up IP table rules failed: %v", err)
+ }
+
+ s := &dns.Server{Handler: r, PacketConn: r.conn}
+ r.server = s
+ go func() {
+ s.ActivateAndServe()
+ }()
+
+ tcpServer := &dns.Server{Handler: r, Listener: r.tcpListen}
+ r.tcpServer = tcpServer
+ go func() {
+ tcpServer.ActivateAndServe()
+ }()
+ return nil
+}
+
+func (r *resolver) Stop() {
+ r.startCh <- struct{}{}
+ defer func() { <-r.startCh }()
+
+ if r.server != nil {
+ r.server.Shutdown()
+ }
+ if r.tcpServer != nil {
+ r.tcpServer.Shutdown()
+ }
+ r.conn = nil
+ r.tcpServer = nil
+ r.err = fmt.Errorf("setup not done yet")
+ r.tStamp = time.Time{}
+ r.count = 0
+ r.queryLock = sync.Mutex{}
+}
+
+func (r *resolver) SetExtServers(extDNS []extDNSEntry) {
+ l := len(extDNS)
+ if l > maxExtDNS {
+ l = maxExtDNS
+ }
+ for i := 0; i < l; i++ {
+ r.extDNSList[i] = extDNS[i]
+ }
+}
+
+func (r *resolver) NameServer() string {
+ return r.listenAddress
+}
+
+func (r *resolver) ResolverOptions() []string {
+ return []string{"ndots:0"}
+}
+
+func setCommonFlags(msg *dns.Msg) {
+ msg.RecursionAvailable = true
+}
+
+func shuffleAddr(addr []net.IP) []net.IP {
+ for i := len(addr) - 1; i > 0; i-- {
+ r := rand.Intn(i + 1)
+ addr[i], addr[r] = addr[r], addr[i]
+ }
+ return addr
+}
+
+func createRespMsg(query *dns.Msg) *dns.Msg {
+ resp := new(dns.Msg)
+ resp.SetReply(query)
+ setCommonFlags(resp)
+
+ return resp
+}
+
+func (r *resolver) handleIPQuery(name string, query *dns.Msg, ipType int) (*dns.Msg, error) {
+ var addr []net.IP
+ var ipv6Miss bool
+ addr, ipv6Miss = r.backend.ResolveName(name, ipType)
+
+ if addr == nil && ipv6Miss {
+ // Send a reply without any Answer sections
+ logrus.Debugf("Lookup name %s present without IPv6 address", name)
+ resp := createRespMsg(query)
+ return resp, nil
+ }
+ if addr == nil {
+ return nil, nil
+ }
+
+ logrus.Debugf("Lookup for %s: IP %v", name, addr)
+
+ resp := createRespMsg(query)
+ if len(addr) > 1 {
+ addr = shuffleAddr(addr)
+ }
+ if ipType == types.IPv4 {
+ for _, ip := range addr {
+ rr := new(dns.A)
+ rr.Hdr = dns.RR_Header{Name: name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: respTTL}
+ rr.A = ip
+ resp.Answer = append(resp.Answer, rr)
+ }
+ } else {
+ for _, ip := range addr {
+ rr := new(dns.AAAA)
+ rr.Hdr = dns.RR_Header{Name: name, Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: respTTL}
+ rr.AAAA = ip
+ resp.Answer = append(resp.Answer, rr)
+ }
+ }
+ return resp, nil
+}
+
+func (r *resolver) handlePTRQuery(ptr string, query *dns.Msg) (*dns.Msg, error) {
+ parts := []string{}
+
+ if strings.HasSuffix(ptr, ptrIPv4domain) {
+ parts = strings.Split(ptr, ptrIPv4domain)
+ } else if strings.HasSuffix(ptr, ptrIPv6domain) {
+ parts = strings.Split(ptr, ptrIPv6domain)
+ } else {
+ return nil, fmt.Errorf("invalid PTR query, %v", ptr)
+ }
+
+ host := r.backend.ResolveIP(parts[0])
+
+ if len(host) == 0 {
+ return nil, nil
+ }
+
+ logrus.Debugf("Lookup for IP %s: name %s", parts[0], host)
+ fqdn := dns.Fqdn(host)
+
+ resp := new(dns.Msg)
+ resp.SetReply(query)
+ setCommonFlags(resp)
+
+ rr := new(dns.PTR)
+ rr.Hdr = dns.RR_Header{Name: ptr, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: respTTL}
+ rr.Ptr = fqdn
+ resp.Answer = append(resp.Answer, rr)
+ return resp, nil
+}
+
+func (r *resolver) handleSRVQuery(svc string, query *dns.Msg) (*dns.Msg, error) {
+
+ srv, ip := r.backend.ResolveService(svc)
+
+ if len(srv) == 0 {
+ return nil, nil
+ }
+ if len(srv) != len(ip) {
+ return nil, fmt.Errorf("invalid reply for SRV query %s", svc)
+ }
+
+ resp := createRespMsg(query)
+
+ for i, r := range srv {
+ rr := new(dns.SRV)
+ rr.Hdr = dns.RR_Header{Name: svc, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: respTTL}
+ rr.Port = r.Port
+ rr.Target = r.Target
+ resp.Answer = append(resp.Answer, rr)
+
+ rr1 := new(dns.A)
+ rr1.Hdr = dns.RR_Header{Name: r.Target, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: respTTL}
+ rr1.A = ip[i]
+ resp.Extra = append(resp.Extra, rr1)
+ }
+ return resp, nil
+
+}
+
+func truncateResp(resp *dns.Msg, maxSize int, isTCP bool) {
+ if !isTCP {
+ resp.Truncated = true
+ }
+
+ srv := resp.Question[0].Qtype == dns.TypeSRV
+ // trim the Answer RRs one by one till the whole message fits
+ // within the reply size
+ for resp.Len() > maxSize {
+ resp.Answer = resp.Answer[:len(resp.Answer)-1]
+
+ if srv && len(resp.Extra) > 0 {
+ resp.Extra = resp.Extra[:len(resp.Extra)-1]
+ }
+ }
+}
+
+func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
+ var (
+ extConn net.Conn
+ resp *dns.Msg
+ err error
+ )
+
+ if query == nil || len(query.Question) == 0 {
+ return
+ }
+ name := query.Question[0].Name
+
+ switch query.Question[0].Qtype {
+ case dns.TypeA:
+ resp, err = r.handleIPQuery(name, query, types.IPv4)
+ case dns.TypeAAAA:
+ resp, err = r.handleIPQuery(name, query, types.IPv6)
+ case dns.TypePTR:
+ resp, err = r.handlePTRQuery(name, query)
+ case dns.TypeSRV:
+ resp, err = r.handleSRVQuery(name, query)
+ }
+
+ if err != nil {
+ logrus.Error(err)
+ return
+ }
+
+ if resp == nil {
+ // If the backend doesn't support proxying dns request
+ // fail the response
+ if !r.proxyDNS {
+ resp = new(dns.Msg)
+ resp.SetRcode(query, dns.RcodeServerFailure)
+ w.WriteMsg(resp)
+ return
+ }
+
+ // If the user sets ndots > 0 explicitly and the query is
+ // in the root domain don't forward it out. We will return
+ // failure and let the client retry with the search domain
+ // attached
+ switch query.Question[0].Qtype {
+ case dns.TypeA:
+ fallthrough
+ case dns.TypeAAAA:
+ if r.backend.NdotsSet() && !strings.Contains(strings.TrimSuffix(name, "."), ".") {
+ resp = createRespMsg(query)
+ }
+ }
+ }
+
+ proto := w.LocalAddr().Network()
+ maxSize := 0
+ if proto == "tcp" {
+ maxSize = dns.MaxMsgSize - 1
+ } else if proto == "udp" {
+ optRR := query.IsEdns0()
+ if optRR != nil {
+ maxSize = int(optRR.UDPSize())
+ }
+ if maxSize < defaultRespSize {
+ maxSize = defaultRespSize
+ }
+ }
+
+ if resp != nil {
+ if resp.Len() > maxSize {
+ truncateResp(resp, maxSize, proto == "tcp")
+ }
+ } else {
+ for i := 0; i < maxExtDNS; i++ {
+ extDNS := &r.extDNSList[i]
+ if extDNS.IPStr == "" {
+ break
+ }
+ extConnect := func() {
+ addr := fmt.Sprintf("%s:%d", extDNS.IPStr, 53)
+ extConn, err = net.DialTimeout(proto, addr, extIOTimeout)
+ }
+
+ if extDNS.HostLoopback {
+ extConnect()
+ } else {
+ execErr := r.backend.ExecFunc(extConnect)
+ if execErr != nil {
+ logrus.Warn(execErr)
+ continue
+ }
+ }
+ if err != nil {
+ logrus.Warnf("Connect failed: %s", err)
+ continue
+ }
+ logrus.Debugf("Query %s[%d] from %s, forwarding to %s:%s", name, query.Question[0].Qtype,
+ extConn.LocalAddr().String(), proto, extDNS.IPStr)
+
+ // Timeout has to be set for every IO operation.
+ extConn.SetDeadline(time.Now().Add(extIOTimeout))
+ co := &dns.Conn{
+ Conn: extConn,
+ UDPSize: uint16(maxSize),
+ }
+ defer co.Close()
+
+ // limits the number of outstanding concurrent queries.
+ if r.forwardQueryStart() == false {
+ old := r.tStamp
+ r.tStamp = time.Now()
+ if r.tStamp.Sub(old) > logInterval {
+ logrus.Errorf("More than %v concurrent queries from %s", maxConcurrent, extConn.LocalAddr().String())
+ }
+ continue
+ }
+
+ err = co.WriteMsg(query)
+ if err != nil {
+ r.forwardQueryEnd()
+ logrus.Debugf("Send to DNS server failed, %s", err)
+ continue
+ }
+
+ resp, err = co.ReadMsg()
+ // Truncated DNS replies should be sent to the client so that the
+ // client can retry over TCP
+ if err != nil && err != dns.ErrTruncated {
+ r.forwardQueryEnd()
+ logrus.Debugf("Read from DNS server failed, %s", err)
+ continue
+ }
+ r.forwardQueryEnd()
+ if resp != nil {
+ for _, rr := range resp.Answer {
+ h := rr.Header()
+ switch h.Rrtype {
+ case dns.TypeA:
+ ip := rr.(*dns.A).A
+ r.backend.HandleQueryResp(h.Name, ip)
+ case dns.TypeAAAA:
+ ip := rr.(*dns.AAAA).AAAA
+ r.backend.HandleQueryResp(h.Name, ip)
+ }
+ }
+ }
+ resp.Compress = true
+ break
+ }
+ if resp == nil {
+ return
+ }
+ }
+
+ if err = w.WriteMsg(resp); err != nil {
+ logrus.Errorf("error writing resolver resp, %s", err)
+ }
+}
+
+func (r *resolver) forwardQueryStart() bool {
+ r.queryLock.Lock()
+ defer r.queryLock.Unlock()
+
+ if r.count == maxConcurrent {
+ return false
+ }
+ r.count++
+
+ return true
+}
+
+func (r *resolver) forwardQueryEnd() {
+ r.queryLock.Lock()
+ defer r.queryLock.Unlock()
+
+ if r.count == 0 {
+ logrus.Error("Invalid concurrent query count")
+ } else {
+ r.count--
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/resolver_unix.go b/vendor/github.com/docker/libnetwork/resolver_unix.go
new file mode 100644
index 0000000..5fcc6b9
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/resolver_unix.go
@@ -0,0 +1,101 @@
+// +build !windows
+
+package libnetwork
+
+import (
+ "fmt"
+ "net"
+ "os"
+ "os/exec"
+ "runtime"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/reexec"
+ "github.com/docker/libnetwork/iptables"
+ "github.com/vishvananda/netns"
+)
+
+func init() {
+ reexec.Register("setup-resolver", reexecSetupResolver)
+}
+
+const (
+ // outputChain used for docker embed dns
+ outputChain = "DOCKER_OUTPUT"
+ //postroutingchain used for docker embed dns
+ postroutingchain = "DOCKER_POSTROUTING"
+)
+
+func reexecSetupResolver() {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+
+ if len(os.Args) < 4 {
+ logrus.Error("invalid number of arguments..")
+ os.Exit(1)
+ }
+
+ resolverIP, ipPort, _ := net.SplitHostPort(os.Args[2])
+ _, tcpPort, _ := net.SplitHostPort(os.Args[3])
+ rules := [][]string{
+ {"-t", "nat", "-I", outputChain, "-d", resolverIP, "-p", "udp", "--dport", dnsPort, "-j", "DNAT", "--to-destination", os.Args[2]},
+ {"-t", "nat", "-I", postroutingchain, "-s", resolverIP, "-p", "udp", "--sport", ipPort, "-j", "SNAT", "--to-source", ":" + dnsPort},
+ {"-t", "nat", "-I", outputChain, "-d", resolverIP, "-p", "tcp", "--dport", dnsPort, "-j", "DNAT", "--to-destination", os.Args[3]},
+ {"-t", "nat", "-I", postroutingchain, "-s", resolverIP, "-p", "tcp", "--sport", tcpPort, "-j", "SNAT", "--to-source", ":" + dnsPort},
+ }
+
+ f, err := os.OpenFile(os.Args[1], os.O_RDONLY, 0)
+ if err != nil {
+ logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
+ os.Exit(2)
+ }
+ defer f.Close()
+
+ nsFD := f.Fd()
+ if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
+ logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err)
+ os.Exit(3)
+ }
+
+ // insert outputChain and postroutingchain
+ err = iptables.RawCombinedOutputNative("-t", "nat", "-C", "OUTPUT", "-d", resolverIP, "-j", outputChain)
+ if err == nil {
+ iptables.RawCombinedOutputNative("-t", "nat", "-F", outputChain)
+ } else {
+ iptables.RawCombinedOutputNative("-t", "nat", "-N", outputChain)
+ iptables.RawCombinedOutputNative("-t", "nat", "-I", "OUTPUT", "-d", resolverIP, "-j", outputChain)
+ }
+
+ err = iptables.RawCombinedOutputNative("-t", "nat", "-C", "POSTROUTING", "-d", resolverIP, "-j", postroutingchain)
+ if err == nil {
+ iptables.RawCombinedOutputNative("-t", "nat", "-F", postroutingchain)
+ } else {
+ iptables.RawCombinedOutputNative("-t", "nat", "-N", postroutingchain)
+ iptables.RawCombinedOutputNative("-t", "nat", "-I", "POSTROUTING", "-d", resolverIP, "-j", postroutingchain)
+ }
+
+ for _, rule := range rules {
+ if iptables.RawCombinedOutputNative(rule...) != nil {
+ logrus.Errorf("setting up rule failed, %v", rule)
+ }
+ }
+}
+
+func (r *resolver) setupIPTable() error {
+ if r.err != nil {
+ return r.err
+ }
+ laddr := r.conn.LocalAddr().String()
+ ltcpaddr := r.tcpListen.Addr().String()
+
+ cmd := &exec.Cmd{
+ Path: reexec.Self(),
+ Args: append([]string{"setup-resolver"}, r.resolverKey, laddr, ltcpaddr),
+ Stdout: os.Stdout,
+ Stderr: os.Stderr,
+ }
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("reexec failed: %v", err)
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/resolver_windows.go b/vendor/github.com/docker/libnetwork/resolver_windows.go
new file mode 100644
index 0000000..aa33b1a
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/resolver_windows.go
@@ -0,0 +1,7 @@
+// +build windows
+
+package libnetwork
+
+func (r *resolver) setupIPTable() error {
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/sandbox.go b/vendor/github.com/docker/libnetwork/sandbox.go
new file mode 100644
index 0000000..9454c5c
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/sandbox.go
@@ -0,0 +1,1224 @@
+package libnetwork
+
+import (
+ "container/heap"
+ "encoding/json"
+ "fmt"
+ "net"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/etchosts"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/libnetwork/osl"
+ "github.com/docker/libnetwork/types"
+)
+
+// Sandbox provides the control over the network container entity. It is a one to one mapping with the container.
+type Sandbox interface {
+ // ID returns the ID of the sandbox
+ ID() string
+ // Key returns the sandbox's key
+ Key() string
+ // ContainerID returns the container id associated to this sandbox
+ ContainerID() string
+ // Labels returns the sandbox's labels
+ Labels() map[string]interface{}
+ // Statistics retrieves the interfaces' statistics for the sandbox
+ Statistics() (map[string]*types.InterfaceStatistics, error)
+ // Refresh leaves all the endpoints, resets and re-applies the options,
+ // re-joins all the endpoints without destroying the osl sandbox
+ Refresh(options ...SandboxOption) error
+ // SetKey updates the Sandbox Key
+ SetKey(key string) error
+ // Rename changes the name of all attached Endpoints
+ Rename(name string) error
+ // Delete destroys this container after detaching it from all connected endpoints.
+ Delete() error
+ // Endpoints returns all the endpoints connected to the sandbox
+ Endpoints() []Endpoint
+ // ResolveService returns all the backend details about the containers or hosts
+ // backing a service. Its purpose is to satisfy an SRV query
+ ResolveService(name string) ([]*net.SRV, []net.IP)
+ // EnableService makes a managed container's service available by adding the
+ // endpoint to the service load balancer and service discovery
+ EnableService() error
+ // DisableService removes a managed container's endpoints from the load balancer
+ // and service discovery
+ DisableService() error
+}
+
+// SandboxOption is an option setter function type used to pass various options to
+// NewNetContainer method. The various setter functions of type SandboxOption are
+// provided by libnetwork, they look like ContainerOptionXXXX(...)
+type SandboxOption func(sb *sandbox)
+
+func (sb *sandbox) processOptions(options ...SandboxOption) {
+ for _, opt := range options {
+ if opt != nil {
+ opt(sb)
+ }
+ }
+}
+
+type epHeap []*endpoint
+
+type sandbox struct {
+ id string
+ containerID string
+ config containerConfig
+ extDNS []extDNSEntry
+ osSbox osl.Sandbox
+ controller *controller
+ resolver Resolver
+ resolverOnce sync.Once
+ refCnt int
+ endpoints epHeap
+ epPriority map[string]int
+ populatedEndpoints map[string]struct{}
+ joinLeaveDone chan struct{}
+ dbIndex uint64
+ dbExists bool
+ isStub bool
+ inDelete bool
+ ingress bool
+ ndotsSet bool
+ sync.Mutex
+ // This mutex is used to serialize service related operation for an endpoint
+ // The lock is here because the endpoint is saved into the store so is not unique
+ Service sync.Mutex
+}
+
+// These are the container configs used to customize container /etc/hosts file.
+type hostsPathConfig struct {
+ hostName string
+ domainName string
+ hostsPath string
+ originHostsPath string
+ extraHosts []extraHost
+ parentUpdates []parentUpdate
+}
+
+type parentUpdate struct {
+ cid string
+ name string
+ ip string
+}
+
+type extraHost struct {
+ name string
+ IP string
+}
+
+// These are the container configs used to customize container /etc/resolv.conf file.
+type resolvConfPathConfig struct {
+ resolvConfPath string
+ originResolvConfPath string
+ resolvConfHashFile string
+ dnsList []string
+ dnsSearchList []string
+ dnsOptionsList []string
+}
+
+type containerConfig struct {
+ hostsPathConfig
+ resolvConfPathConfig
+ generic map[string]interface{}
+ useDefaultSandBox bool
+ useExternalKey bool
+ prio int // higher the value, more the priority
+ exposedPorts []types.TransportPort
+}
+
+const (
+ resolverIPSandbox = "127.0.0.11"
+)
+
+func (sb *sandbox) ID() string {
+ return sb.id
+}
+
+func (sb *sandbox) ContainerID() string {
+ return sb.containerID
+}
+
+func (sb *sandbox) Key() string {
+ if sb.config.useDefaultSandBox {
+ return osl.GenerateKey("default")
+ }
+ return osl.GenerateKey(sb.id)
+}
+
+func (sb *sandbox) Labels() map[string]interface{} {
+ sb.Lock()
+ defer sb.Unlock()
+ opts := make(map[string]interface{}, len(sb.config.generic))
+ for k, v := range sb.config.generic {
+ opts[k] = v
+ }
+ return opts
+}
+
+func (sb *sandbox) Statistics() (map[string]*types.InterfaceStatistics, error) {
+ m := make(map[string]*types.InterfaceStatistics)
+
+ sb.Lock()
+ osb := sb.osSbox
+ sb.Unlock()
+ if osb == nil {
+ return m, nil
+ }
+
+ var err error
+ for _, i := range osb.Info().Interfaces() {
+ if m[i.DstName()], err = i.Statistics(); err != nil {
+ return m, err
+ }
+ }
+
+ return m, nil
+}
+
+func (sb *sandbox) Delete() error {
+ return sb.delete(false)
+}
+
+func (sb *sandbox) delete(force bool) error {
+ sb.Lock()
+ if sb.inDelete {
+ sb.Unlock()
+ return types.ForbiddenErrorf("another sandbox delete in progress")
+ }
+ // Set the inDelete flag. This will ensure that we don't
+ // update the store until we have completed all the endpoint
+ // leaves and deletes. And when endpoint leaves and deletes
+ // are completed then we can finally delete the sandbox object
+ // altogether from the data store. If the daemon exits
+ // ungracefully in the middle of a sandbox delete this way we
+ // will have all the references to the endpoints in the
+ // sandbox so that we can clean them up when we restart
+ sb.inDelete = true
+ sb.Unlock()
+
+ c := sb.controller
+
+ // Detach from all endpoints
+ retain := false
+ for _, ep := range sb.getConnectedEndpoints() {
+ // gw network endpoint detach and removal are automatic
+ if ep.endpointInGWNetwork() && !force {
+ continue
+ }
+ // Retain the sanbdox if we can't obtain the network from store.
+ if _, err := c.getNetworkFromStore(ep.getNetwork().ID()); err != nil {
+ if c.isDistributedControl() {
+ retain = true
+ }
+ logrus.Warnf("Failed getting network for ep %s during sandbox %s delete: %v", ep.ID(), sb.ID(), err)
+ continue
+ }
+
+ if !force {
+ if err := ep.Leave(sb); err != nil {
+ logrus.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
+ }
+ }
+
+ if err := ep.Delete(force); err != nil {
+ logrus.Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err)
+ }
+ }
+
+ if retain {
+ sb.Lock()
+ sb.inDelete = false
+ sb.Unlock()
+ return fmt.Errorf("could not cleanup all the endpoints in container %s / sandbox %s", sb.containerID, sb.id)
+ }
+ // Container is going away. Path cache in etchosts is most
+ // likely not required any more. Drop it.
+ etchosts.Drop(sb.config.hostsPath)
+
+ if sb.resolver != nil {
+ sb.resolver.Stop()
+ }
+
+ if sb.osSbox != nil && !sb.config.useDefaultSandBox {
+ sb.osSbox.Destroy()
+ }
+
+ if err := sb.storeDelete(); err != nil {
+ logrus.Warnf("Failed to delete sandbox %s from store: %v", sb.ID(), err)
+ }
+
+ c.Lock()
+ if sb.ingress {
+ c.ingressSandbox = nil
+ }
+ delete(c.sandboxes, sb.ID())
+ c.Unlock()
+
+ return nil
+}
+
+func (sb *sandbox) Rename(name string) error {
+ var err error
+
+ for _, ep := range sb.getConnectedEndpoints() {
+ if ep.endpointInGWNetwork() {
+ continue
+ }
+
+ oldName := ep.Name()
+ lEp := ep
+ if err = ep.rename(name); err != nil {
+ break
+ }
+
+ defer func() {
+ if err != nil {
+ lEp.rename(oldName)
+ }
+ }()
+ }
+
+ return err
+}
+
+func (sb *sandbox) Refresh(options ...SandboxOption) error {
+ // Store connected endpoints
+ epList := sb.getConnectedEndpoints()
+
+ // Detach from all endpoints
+ for _, ep := range epList {
+ if err := ep.Leave(sb); err != nil {
+ logrus.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
+ }
+ }
+
+ // Re-apply options
+ sb.config = containerConfig{}
+ sb.processOptions(options...)
+
+ // Setup discovery files
+ if err := sb.setupResolutionFiles(); err != nil {
+ return err
+ }
+
+ // Re-connect to all endpoints
+ for _, ep := range epList {
+ if err := ep.Join(sb); err != nil {
+ logrus.Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err)
+ }
+ }
+
+ return nil
+}
+
+func (sb *sandbox) MarshalJSON() ([]byte, error) {
+ sb.Lock()
+ defer sb.Unlock()
+
+ // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
+ return json.Marshal(sb.id)
+}
+
+func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
+ sb.Lock()
+ defer sb.Unlock()
+
+ var id string
+ if err := json.Unmarshal(b, &id); err != nil {
+ return err
+ }
+ sb.id = id
+ return nil
+}
+
+func (sb *sandbox) Endpoints() []Endpoint {
+ sb.Lock()
+ defer sb.Unlock()
+
+ endpoints := make([]Endpoint, len(sb.endpoints))
+ for i, ep := range sb.endpoints {
+ endpoints[i] = ep
+ }
+ return endpoints
+}
+
+func (sb *sandbox) getConnectedEndpoints() []*endpoint {
+ sb.Lock()
+ defer sb.Unlock()
+
+ eps := make([]*endpoint, len(sb.endpoints))
+ for i, ep := range sb.endpoints {
+ eps[i] = ep
+ }
+
+ return eps
+}
+
+func (sb *sandbox) removeEndpoint(ep *endpoint) {
+ sb.Lock()
+ defer sb.Unlock()
+
+ for i, e := range sb.endpoints {
+ if e == ep {
+ heap.Remove(&sb.endpoints, i)
+ return
+ }
+ }
+}
+
+func (sb *sandbox) getEndpoint(id string) *endpoint {
+ sb.Lock()
+ defer sb.Unlock()
+
+ for _, ep := range sb.endpoints {
+ if ep.id == id {
+ return ep
+ }
+ }
+
+ return nil
+}
+
+func (sb *sandbox) updateGateway(ep *endpoint) error {
+ sb.Lock()
+ osSbox := sb.osSbox
+ sb.Unlock()
+ if osSbox == nil {
+ return nil
+ }
+ osSbox.UnsetGateway()
+ osSbox.UnsetGatewayIPv6()
+
+ if ep == nil {
+ return nil
+ }
+
+ ep.Lock()
+ joinInfo := ep.joinInfo
+ ep.Unlock()
+
+ if err := osSbox.SetGateway(joinInfo.gw); err != nil {
+ return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
+ }
+
+ if err := osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
+ return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
+ }
+
+ return nil
+}
+
+func (sb *sandbox) HandleQueryResp(name string, ip net.IP) {
+ for _, ep := range sb.getConnectedEndpoints() {
+ n := ep.getNetwork()
+ n.HandleQueryResp(name, ip)
+ }
+}
+
+func (sb *sandbox) ResolveIP(ip string) string {
+ var svc string
+ logrus.Debugf("IP To resolve %v", ip)
+
+ for _, ep := range sb.getConnectedEndpoints() {
+ n := ep.getNetwork()
+ svc = n.ResolveIP(ip)
+ if len(svc) != 0 {
+ return svc
+ }
+ }
+
+ return svc
+}
+
+func (sb *sandbox) ExecFunc(f func()) error {
+ sb.Lock()
+ osSbox := sb.osSbox
+ sb.Unlock()
+ if osSbox != nil {
+ return osSbox.InvokeFunc(f)
+ }
+ return fmt.Errorf("osl sandbox unavailable in ExecFunc for %v", sb.ContainerID())
+}
+
+func (sb *sandbox) ResolveService(name string) ([]*net.SRV, []net.IP) {
+ srv := []*net.SRV{}
+ ip := []net.IP{}
+
+ logrus.Debugf("Service name To resolve: %v", name)
+
+ // There are DNS implementaions that allow SRV queries for names not in
+ // the format defined by RFC 2782. Hence specific validations checks are
+ // not done
+ parts := strings.Split(name, ".")
+ if len(parts) < 3 {
+ return nil, nil
+ }
+
+ for _, ep := range sb.getConnectedEndpoints() {
+ n := ep.getNetwork()
+
+ srv, ip = n.ResolveService(name)
+ if len(srv) > 0 {
+ break
+ }
+ }
+ return srv, ip
+}
+
+func getDynamicNwEndpoints(epList []*endpoint) []*endpoint {
+ eps := []*endpoint{}
+ for _, ep := range epList {
+ n := ep.getNetwork()
+ if n.dynamic && !n.ingress {
+ eps = append(eps, ep)
+ }
+ }
+ return eps
+}
+
+func getIngressNwEndpoint(epList []*endpoint) *endpoint {
+ for _, ep := range epList {
+ n := ep.getNetwork()
+ if n.ingress {
+ return ep
+ }
+ }
+ return nil
+}
+
+func getLocalNwEndpoints(epList []*endpoint) []*endpoint {
+ eps := []*endpoint{}
+ for _, ep := range epList {
+ n := ep.getNetwork()
+ if !n.dynamic && !n.ingress {
+ eps = append(eps, ep)
+ }
+ }
+ return eps
+}
+
+func (sb *sandbox) ResolveName(name string, ipType int) ([]net.IP, bool) {
+ // Embedded server owns the docker network domain. Resolution should work
+ // for both container_name and container_name.network_name
+ // We allow '.' in service name and network name. For a name a.b.c.d the
+ // following have to tried;
+ // {a.b.c.d in the networks container is connected to}
+ // {a.b.c in network d},
+ // {a.b in network c.d},
+ // {a in network b.c.d},
+
+ logrus.Debugf("Name To resolve: %v", name)
+ name = strings.TrimSuffix(name, ".")
+ reqName := []string{name}
+ networkName := []string{""}
+
+ if strings.Contains(name, ".") {
+ var i int
+ dup := name
+ for {
+ if i = strings.LastIndex(dup, "."); i == -1 {
+ break
+ }
+ networkName = append(networkName, name[i+1:])
+ reqName = append(reqName, name[:i])
+
+ dup = dup[:i]
+ }
+ }
+
+ epList := sb.getConnectedEndpoints()
+
+ // In swarm mode services with exposed ports are connected to user overlay
+ // network, ingress network and docker_gwbridge network. Name resolution
+ // should prioritize returning the VIP/IPs on user overlay network.
+ newList := []*endpoint{}
+ if !sb.controller.isDistributedControl() {
+ newList = append(newList, getDynamicNwEndpoints(epList)...)
+ ingressEP := getIngressNwEndpoint(epList)
+ if ingressEP != nil {
+ newList = append(newList, ingressEP)
+ }
+ newList = append(newList, getLocalNwEndpoints(epList)...)
+ epList = newList
+ }
+
+ for i := 0; i < len(reqName); i++ {
+
+ // First check for local container alias
+ ip, ipv6Miss := sb.resolveName(reqName[i], networkName[i], epList, true, ipType)
+ if ip != nil {
+ return ip, false
+ }
+ if ipv6Miss {
+ return ip, ipv6Miss
+ }
+
+ // Resolve the actual container name
+ ip, ipv6Miss = sb.resolveName(reqName[i], networkName[i], epList, false, ipType)
+ if ip != nil {
+ return ip, false
+ }
+ if ipv6Miss {
+ return ip, ipv6Miss
+ }
+ }
+ return nil, false
+}
+
+func (sb *sandbox) resolveName(req string, networkName string, epList []*endpoint, alias bool, ipType int) ([]net.IP, bool) {
+ var ipv6Miss bool
+
+ for _, ep := range epList {
+ name := req
+ n := ep.getNetwork()
+
+ if networkName != "" && networkName != n.Name() {
+ continue
+ }
+
+ if alias {
+ if ep.aliases == nil {
+ continue
+ }
+
+ var ok bool
+ ep.Lock()
+ name, ok = ep.aliases[req]
+ ep.Unlock()
+ if !ok {
+ continue
+ }
+ } else {
+ // If it is a regular lookup and if the requested name is an alias
+ // don't perform a svc lookup for this endpoint.
+ ep.Lock()
+ if _, ok := ep.aliases[req]; ok {
+ ep.Unlock()
+ continue
+ }
+ ep.Unlock()
+ }
+
+ ip, miss := n.ResolveName(name, ipType)
+
+ if ip != nil {
+ return ip, false
+ }
+
+ if miss {
+ ipv6Miss = miss
+ }
+ }
+ return nil, ipv6Miss
+}
+
+func (sb *sandbox) SetKey(basePath string) error {
+ start := time.Now()
+ defer func() {
+ logrus.Debugf("sandbox set key processing took %s for container %s", time.Now().Sub(start), sb.ContainerID())
+ }()
+
+ if basePath == "" {
+ return types.BadRequestErrorf("invalid sandbox key")
+ }
+
+ sb.Lock()
+ if sb.inDelete {
+ sb.Unlock()
+ return types.ForbiddenErrorf("failed to SetKey: sandbox %q delete in progress", sb.id)
+ }
+ oldosSbox := sb.osSbox
+ sb.Unlock()
+
+ if oldosSbox != nil {
+ // If we already have an OS sandbox, release the network resources from that
+ // and destroy the OS snab. We are moving into a new home further down. Note that none
+ // of the network resources gets destroyed during the move.
+ sb.releaseOSSbox()
+ }
+
+ osSbox, err := osl.GetSandboxForExternalKey(basePath, sb.Key())
+ if err != nil {
+ return err
+ }
+
+ sb.Lock()
+ sb.osSbox = osSbox
+ sb.Unlock()
+
+ // If the resolver was setup before stop it and set it up in the
+ // new osl sandbox.
+ if oldosSbox != nil && sb.resolver != nil {
+ sb.resolver.Stop()
+
+ if err := sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err == nil {
+ if err := sb.resolver.Start(); err != nil {
+ logrus.Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err)
+ }
+ } else {
+ logrus.Errorf("Resolver Setup Function failed for container %s, %q", sb.ContainerID(), err)
+ }
+ }
+
+ for _, ep := range sb.getConnectedEndpoints() {
+ if err = sb.populateNetworkResources(ep); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (sb *sandbox) EnableService() error {
+ logrus.Debugf("EnableService %s START", sb.containerID)
+ for _, ep := range sb.getConnectedEndpoints() {
+ if ep.enableService(true) {
+ if err := ep.addServiceInfoToCluster(sb); err != nil {
+ ep.enableService(false)
+ return fmt.Errorf("could not update state for endpoint %s into cluster: %v", ep.Name(), err)
+ }
+ }
+ }
+ logrus.Debugf("EnableService %s DONE", sb.containerID)
+ return nil
+}
+
+func (sb *sandbox) DisableService() error {
+ logrus.Debugf("DisableService %s START", sb.containerID)
+ for _, ep := range sb.getConnectedEndpoints() {
+ ep.enableService(false)
+ }
+ logrus.Debugf("DisableService %s DONE", sb.containerID)
+ return nil
+}
+
+func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) {
+ for _, i := range osSbox.Info().Interfaces() {
+ // Only remove the interfaces owned by this endpoint from the sandbox.
+ if ep.hasInterface(i.SrcName()) {
+ if err := i.Remove(); err != nil {
+ logrus.Debugf("Remove interface %s failed: %v", i.SrcName(), err)
+ }
+ }
+ }
+
+ ep.Lock()
+ joinInfo := ep.joinInfo
+ ep.Unlock()
+
+ if joinInfo == nil {
+ return
+ }
+
+ // Remove non-interface routes.
+ for _, r := range joinInfo.StaticRoutes {
+ if err := osSbox.RemoveStaticRoute(r); err != nil {
+ logrus.Debugf("Remove route failed: %v", err)
+ }
+ }
+}
+
+func (sb *sandbox) releaseOSSbox() {
+ sb.Lock()
+ osSbox := sb.osSbox
+ sb.osSbox = nil
+ sb.Unlock()
+
+ if osSbox == nil {
+ return
+ }
+
+ for _, ep := range sb.getConnectedEndpoints() {
+ releaseOSSboxResources(osSbox, ep)
+ }
+
+ osSbox.Destroy()
+}
+
+func (sb *sandbox) restoreOslSandbox() error {
+ var routes []*types.StaticRoute
+
+ // restore osl sandbox
+ Ifaces := make(map[string][]osl.IfaceOption)
+ for _, ep := range sb.endpoints {
+ var ifaceOptions []osl.IfaceOption
+ ep.Lock()
+ joinInfo := ep.joinInfo
+ i := ep.iface
+ ep.Unlock()
+
+ if i == nil {
+ logrus.Errorf("error restoring endpoint %s for container %s", ep.Name(), sb.ContainerID())
+ continue
+ }
+
+ ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
+ if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
+ ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
+ }
+ if i.mac != nil {
+ ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
+ }
+ if len(i.llAddrs) != 0 {
+ ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs))
+ }
+ if len(ep.virtualIP) != 0 {
+ vipAlias := &net.IPNet{IP: ep.virtualIP, Mask: net.CIDRMask(32, 32)}
+ ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().IPAliases([]*net.IPNet{vipAlias}))
+ }
+ Ifaces[fmt.Sprintf("%s+%s", i.srcName, i.dstPrefix)] = ifaceOptions
+ if joinInfo != nil {
+ for _, r := range joinInfo.StaticRoutes {
+ routes = append(routes, r)
+ }
+ }
+ if ep.needResolver() {
+ sb.startResolver(true)
+ }
+ }
+
+ gwep := sb.getGatewayEndpoint()
+ if gwep == nil {
+ return nil
+ }
+
+ // restore osl sandbox
+ err := sb.osSbox.Restore(Ifaces, routes, gwep.joinInfo.gw, gwep.joinInfo.gw6)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
+ sb.Lock()
+ if sb.osSbox == nil {
+ sb.Unlock()
+ return nil
+ }
+ inDelete := sb.inDelete
+ sb.Unlock()
+
+ ep.Lock()
+ joinInfo := ep.joinInfo
+ i := ep.iface
+ ep.Unlock()
+
+ if ep.needResolver() {
+ sb.startResolver(false)
+ }
+
+ if i != nil && i.srcName != "" {
+ var ifaceOptions []osl.IfaceOption
+
+ ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
+ if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
+ ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
+ }
+ if len(i.llAddrs) != 0 {
+ ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs))
+ }
+ if len(ep.virtualIP) != 0 {
+ vipAlias := &net.IPNet{IP: ep.virtualIP, Mask: net.CIDRMask(32, 32)}
+ ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().IPAliases([]*net.IPNet{vipAlias}))
+ }
+ if i.mac != nil {
+ ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
+ }
+
+ if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
+ return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
+ }
+ }
+
+ if joinInfo != nil {
+ // Set up non-interface routes.
+ for _, r := range joinInfo.StaticRoutes {
+ if err := sb.osSbox.AddStaticRoute(r); err != nil {
+ return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
+ }
+ }
+ }
+
+ if ep == sb.getGatewayEndpoint() {
+ if err := sb.updateGateway(ep); err != nil {
+ return err
+ }
+ }
+
+ // Make sure to add the endpoint to the populated endpoint set
+ // before populating loadbalancers.
+ sb.Lock()
+ sb.populatedEndpoints[ep.ID()] = struct{}{}
+ sb.Unlock()
+
+ // Populate load balancer only after updating all the other
+ // information including gateway and other routes so that
+ // loadbalancers are populated all the network state is in
+ // place in the sandbox.
+ sb.populateLoadbalancers(ep)
+
+ // Only update the store if we did not come here as part of
+ // sandbox delete. If we came here as part of delete then do
+ // not bother updating the store. The sandbox object will be
+ // deleted anyway
+ if !inDelete {
+ return sb.storeUpdate()
+ }
+
+ return nil
+}
+
+func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
+ ep := sb.getEndpoint(origEp.id)
+ if ep == nil {
+ return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
+ origEp.id)
+ }
+
+ sb.Lock()
+ osSbox := sb.osSbox
+ inDelete := sb.inDelete
+ sb.Unlock()
+ if osSbox != nil {
+ releaseOSSboxResources(osSbox, ep)
+ }
+
+ sb.Lock()
+ delete(sb.populatedEndpoints, ep.ID())
+
+ if len(sb.endpoints) == 0 {
+ // sb.endpoints should never be empty and this is unexpected error condition
+ // We log an error message to note this down for debugging purposes.
+ logrus.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
+ sb.Unlock()
+ return nil
+ }
+
+ var (
+ gwepBefore, gwepAfter *endpoint
+ index = -1
+ )
+ for i, e := range sb.endpoints {
+ if e == ep {
+ index = i
+ }
+ if len(e.Gateway()) > 0 && gwepBefore == nil {
+ gwepBefore = e
+ }
+ if index != -1 && gwepBefore != nil {
+ break
+ }
+ }
+ heap.Remove(&sb.endpoints, index)
+ for _, e := range sb.endpoints {
+ if len(e.Gateway()) > 0 {
+ gwepAfter = e
+ break
+ }
+ }
+ delete(sb.epPriority, ep.ID())
+ sb.Unlock()
+
+ if gwepAfter != nil && gwepBefore != gwepAfter {
+ sb.updateGateway(gwepAfter)
+ }
+
+ // Only update the store if we did not come here as part of
+ // sandbox delete. If we came here as part of delete then do
+ // not bother updating the store. The sandbox object will be
+ // deleted anyway
+ if !inDelete {
+ return sb.storeUpdate()
+ }
+
+ return nil
+}
+
+func (sb *sandbox) isEndpointPopulated(ep *endpoint) bool {
+ sb.Lock()
+ _, ok := sb.populatedEndpoints[ep.ID()]
+ sb.Unlock()
+ return ok
+}
+
+// joinLeaveStart waits to ensure there are no joins or leaves in progress and
+// marks this join/leave in progress without race
+func (sb *sandbox) joinLeaveStart() {
+ sb.Lock()
+ defer sb.Unlock()
+
+ for sb.joinLeaveDone != nil {
+ joinLeaveDone := sb.joinLeaveDone
+ sb.Unlock()
+
+ select {
+ case <-joinLeaveDone:
+ }
+
+ sb.Lock()
+ }
+
+ sb.joinLeaveDone = make(chan struct{})
+}
+
+// joinLeaveEnd marks the end of this join/leave operation and
+// signals the same without race to other join and leave waiters
+func (sb *sandbox) joinLeaveEnd() {
+ sb.Lock()
+ defer sb.Unlock()
+
+ if sb.joinLeaveDone != nil {
+ close(sb.joinLeaveDone)
+ sb.joinLeaveDone = nil
+ }
+}
+
+func (sb *sandbox) hasPortConfigs() bool {
+ opts := sb.Labels()
+ _, hasExpPorts := opts[netlabel.ExposedPorts]
+ _, hasPortMaps := opts[netlabel.PortMap]
+ return hasExpPorts || hasPortMaps
+}
+
+// OptionHostname function returns an option setter for hostname option to
+// be passed to NewSandbox method.
+func OptionHostname(name string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.hostName = name
+ }
+}
+
+// OptionDomainname function returns an option setter for domainname option to
+// be passed to NewSandbox method.
+func OptionDomainname(name string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.domainName = name
+ }
+}
+
+// OptionHostsPath function returns an option setter for hostspath option to
+// be passed to NewSandbox method.
+func OptionHostsPath(path string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.hostsPath = path
+ }
+}
+
+// OptionOriginHostsPath function returns an option setter for origin hosts file path
+// to be passed to NewSandbox method.
+func OptionOriginHostsPath(path string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.originHostsPath = path
+ }
+}
+
+// OptionExtraHost function returns an option setter for extra /etc/hosts options
+// which is a name and IP as strings.
+func OptionExtraHost(name string, IP string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
+ }
+}
+
+// OptionParentUpdate function returns an option setter for parent container
+// which needs to update the IP address for the linked container.
+func OptionParentUpdate(cid string, name, ip string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
+ }
+}
+
+// OptionResolvConfPath function returns an option setter for resolvconfpath option to
+// be passed to net container methods.
+func OptionResolvConfPath(path string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.resolvConfPath = path
+ }
+}
+
+// OptionOriginResolvConfPath function returns an option setter to set the path to the
+// origin resolv.conf file to be passed to net container methods.
+func OptionOriginResolvConfPath(path string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.originResolvConfPath = path
+ }
+}
+
+// OptionDNS function returns an option setter for dns entry option to
+// be passed to container Create method.
+func OptionDNS(dns string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.dnsList = append(sb.config.dnsList, dns)
+ }
+}
+
+// OptionDNSSearch function returns an option setter for dns search entry option to
+// be passed to container Create method.
+func OptionDNSSearch(search string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
+ }
+}
+
+// OptionDNSOptions function returns an option setter for dns options entry option to
+// be passed to container Create method.
+func OptionDNSOptions(options string) SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
+ }
+}
+
+// OptionUseDefaultSandbox function returns an option setter for using default sandbox to
+// be passed to container Create method.
+func OptionUseDefaultSandbox() SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.useDefaultSandBox = true
+ }
+}
+
+// OptionUseExternalKey function returns an option setter for using provided namespace
+// instead of creating one.
+func OptionUseExternalKey() SandboxOption {
+ return func(sb *sandbox) {
+ sb.config.useExternalKey = true
+ }
+}
+
+// OptionGeneric function returns an option setter for Generic configuration
+// that is not managed by libNetwork but can be used by the Drivers during the call to
+// net container creation method. Container Labels are a good example.
+func OptionGeneric(generic map[string]interface{}) SandboxOption {
+ return func(sb *sandbox) {
+ if sb.config.generic == nil {
+ sb.config.generic = make(map[string]interface{}, len(generic))
+ }
+ for k, v := range generic {
+ sb.config.generic[k] = v
+ }
+ }
+}
+
+// OptionExposedPorts function returns an option setter for the container exposed
+// ports option to be passed to container Create method.
+func OptionExposedPorts(exposedPorts []types.TransportPort) SandboxOption {
+ return func(sb *sandbox) {
+ if sb.config.generic == nil {
+ sb.config.generic = make(map[string]interface{})
+ }
+ // Defensive copy
+ eps := make([]types.TransportPort, len(exposedPorts))
+ copy(eps, exposedPorts)
+ // Store endpoint label and in generic because driver needs it
+ sb.config.exposedPorts = eps
+ sb.config.generic[netlabel.ExposedPorts] = eps
+ }
+}
+
+// OptionPortMapping function returns an option setter for the mapping
+// ports option to be passed to container Create method.
+func OptionPortMapping(portBindings []types.PortBinding) SandboxOption {
+ return func(sb *sandbox) {
+ if sb.config.generic == nil {
+ sb.config.generic = make(map[string]interface{})
+ }
+ // Store a copy of the bindings as generic data to pass to the driver
+ pbs := make([]types.PortBinding, len(portBindings))
+ copy(pbs, portBindings)
+ sb.config.generic[netlabel.PortMap] = pbs
+ }
+}
+
+// OptionIngress function returns an option setter for marking a
+// sandbox as the controller's ingress sandbox.
+func OptionIngress() SandboxOption {
+ return func(sb *sandbox) {
+ sb.ingress = true
+ }
+}
+
+func (eh epHeap) Len() int { return len(eh) }
+
+func (eh epHeap) Less(i, j int) bool {
+ var (
+ cip, cjp int
+ ok bool
+ )
+
+ ci, _ := eh[i].getSandbox()
+ cj, _ := eh[j].getSandbox()
+
+ epi := eh[i]
+ epj := eh[j]
+
+ if epi.endpointInGWNetwork() {
+ return false
+ }
+
+ if epj.endpointInGWNetwork() {
+ return true
+ }
+
+ if epi.getNetwork().Internal() {
+ return false
+ }
+
+ if epj.getNetwork().Internal() {
+ return true
+ }
+
+ if epi.joinInfo != nil && epj.joinInfo != nil {
+ if (epi.joinInfo.gw != nil && epi.joinInfo.gw6 != nil) &&
+ (epj.joinInfo.gw == nil || epj.joinInfo.gw6 == nil) {
+ return true
+ }
+ if (epj.joinInfo.gw != nil && epj.joinInfo.gw6 != nil) &&
+ (epi.joinInfo.gw == nil || epi.joinInfo.gw6 == nil) {
+ return false
+ }
+ }
+
+ if ci != nil {
+ cip, ok = ci.epPriority[eh[i].ID()]
+ if !ok {
+ cip = 0
+ }
+ }
+
+ if cj != nil {
+ cjp, ok = cj.epPriority[eh[j].ID()]
+ if !ok {
+ cjp = 0
+ }
+ }
+
+ if cip == cjp {
+ return eh[i].network.Name() < eh[j].network.Name()
+ }
+
+ return cip > cjp
+}
+
+func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
+
+func (eh *epHeap) Push(x interface{}) {
+ *eh = append(*eh, x.(*endpoint))
+}
+
+func (eh *epHeap) Pop() interface{} {
+ old := *eh
+ n := len(old)
+ x := old[n-1]
+ *eh = old[0 : n-1]
+ return x
+}
+
+func (sb *sandbox) NdotsSet() bool {
+ return sb.ndotsSet
+}
diff --git a/vendor/github.com/docker/libnetwork/sandbox_dns_unix.go b/vendor/github.com/docker/libnetwork/sandbox_dns_unix.go
new file mode 100644
index 0000000..867cc8a
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/sandbox_dns_unix.go
@@ -0,0 +1,407 @@
+// +build !windows
+
+package libnetwork
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/etchosts"
+ "github.com/docker/libnetwork/resolvconf"
+ "github.com/docker/libnetwork/resolvconf/dns"
+ "github.com/docker/libnetwork/types"
+)
+
+const (
+ defaultPrefix = "/var/lib/docker/network/files"
+ dirPerm = 0755
+ filePerm = 0644
+)
+
+func (sb *sandbox) startResolver(restore bool) {
+ sb.resolverOnce.Do(func() {
+ var err error
+ sb.resolver = NewResolver(resolverIPSandbox, true, sb.Key(), sb)
+ defer func() {
+ if err != nil {
+ sb.resolver = nil
+ }
+ }()
+
+ // In the case of live restore container is already running with
+ // right resolv.conf contents created before. Just update the
+ // external DNS servers from the restored sandbox for embedded
+ // server to use.
+ if !restore {
+ err = sb.rebuildDNS()
+ if err != nil {
+ logrus.Errorf("Updating resolv.conf failed for container %s, %q", sb.ContainerID(), err)
+ return
+ }
+ }
+ sb.resolver.SetExtServers(sb.extDNS)
+
+ if err = sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err != nil {
+ logrus.Errorf("Resolver Setup function failed for container %s, %q", sb.ContainerID(), err)
+ return
+ }
+
+ if err = sb.resolver.Start(); err != nil {
+ logrus.Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err)
+ }
+ })
+}
+
+func (sb *sandbox) setupResolutionFiles() error {
+ if err := sb.buildHostsFile(); err != nil {
+ return err
+ }
+
+ if err := sb.updateParentHosts(); err != nil {
+ return err
+ }
+
+ if err := sb.setupDNS(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (sb *sandbox) buildHostsFile() error {
+ if sb.config.hostsPath == "" {
+ sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
+ }
+
+ dir, _ := filepath.Split(sb.config.hostsPath)
+ if err := createBasePath(dir); err != nil {
+ return err
+ }
+
+ // This is for the host mode networking
+ if sb.config.originHostsPath != "" {
+ if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
+ return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
+ }
+ return nil
+ }
+
+ extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
+ for _, extraHost := range sb.config.extraHosts {
+ extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
+ }
+
+ return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
+}
+
+func (sb *sandbox) updateHostsFile(ifaceIP string) error {
+ if ifaceIP == "" {
+ return nil
+ }
+
+ if sb.config.originHostsPath != "" {
+ return nil
+ }
+
+ // User might have provided a FQDN in hostname or split it across hostname
+ // and domainname. We want the FQDN and the bare hostname.
+ fqdn := sb.config.hostName
+ mhost := sb.config.hostName
+ if sb.config.domainName != "" {
+ fqdn = fmt.Sprintf("%s.%s", fqdn, sb.config.domainName)
+ }
+
+ parts := strings.SplitN(fqdn, ".", 2)
+ if len(parts) == 2 {
+ mhost = fmt.Sprintf("%s %s", fqdn, parts[0])
+ }
+
+ extraContent := []etchosts.Record{{Hosts: mhost, IP: ifaceIP}}
+
+ sb.addHostsEntries(extraContent)
+ return nil
+}
+
+func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
+ if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
+ logrus.Warnf("Failed adding service host entries to the running container: %v", err)
+ }
+}
+
+func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
+ if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
+ logrus.Warnf("Failed deleting service host entries to the running container: %v", err)
+ }
+}
+
+func (sb *sandbox) updateParentHosts() error {
+ var pSb Sandbox
+
+ for _, update := range sb.config.parentUpdates {
+ sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
+ if pSb == nil {
+ continue
+ }
+ if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (sb *sandbox) restorePath() {
+ if sb.config.resolvConfPath == "" {
+ sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
+ }
+ sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
+ if sb.config.hostsPath == "" {
+ sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
+ }
+}
+
+func (sb *sandbox) setExternalResolvers(content []byte, addrType int, checkLoopback bool) {
+ servers := resolvconf.GetNameservers(content, addrType)
+ for _, ip := range servers {
+ hostLoopback := false
+ if checkLoopback {
+ hostLoopback = dns.IsIPv4Localhost(ip)
+ }
+ sb.extDNS = append(sb.extDNS, extDNSEntry{
+ IPStr: ip,
+ HostLoopback: hostLoopback,
+ })
+ }
+}
+
+func (sb *sandbox) setupDNS() error {
+ var newRC *resolvconf.File
+
+ if sb.config.resolvConfPath == "" {
+ sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
+ }
+
+ sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
+
+ dir, _ := filepath.Split(sb.config.resolvConfPath)
+ if err := createBasePath(dir); err != nil {
+ return err
+ }
+
+ // This is for the host mode networking
+ if sb.config.originResolvConfPath != "" {
+ if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
+ return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
+ }
+ return nil
+ }
+
+ currRC, err := resolvconf.Get()
+ if err != nil {
+ return err
+ }
+
+ if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
+ var (
+ err error
+ dnsList = resolvconf.GetNameservers(currRC.Content, types.IP)
+ dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
+ dnsOptionsList = resolvconf.GetOptions(currRC.Content)
+ )
+ if len(sb.config.dnsList) > 0 {
+ dnsList = sb.config.dnsList
+ }
+ if len(sb.config.dnsSearchList) > 0 {
+ dnsSearchList = sb.config.dnsSearchList
+ }
+ if len(sb.config.dnsOptionsList) > 0 {
+ dnsOptionsList = sb.config.dnsOptionsList
+ }
+ newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
+ if err != nil {
+ return err
+ }
+ // After building the resolv.conf from the user config save the
+ // external resolvers in the sandbox. Note that --dns 127.0.0.x
+ // config refers to the loopback in the container namespace
+ sb.setExternalResolvers(newRC.Content, types.IPv4, false)
+ } else {
+ // If the host resolv.conf file has 127.0.0.x container should
+ // use the host restolver for queries. This is supported by the
+ // docker embedded DNS server. Hence save the external resolvers
+ // before filtering it out.
+ sb.setExternalResolvers(currRC.Content, types.IPv4, true)
+
+ // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
+ if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
+ return err
+ }
+ // No contention on container resolv.conf file at sandbox creation
+ if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
+ return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
+ }
+ }
+
+ // Write hash
+ if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
+ return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
+ }
+
+ return nil
+}
+
+func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
+ var (
+ currHash string
+ hashFile = sb.config.resolvConfHashFile
+ )
+
+ // This is for the host mode networking
+ if sb.config.originResolvConfPath != "" {
+ return nil
+ }
+
+ if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
+ return nil
+ }
+
+ currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ return err
+ }
+ } else {
+ h, err := ioutil.ReadFile(hashFile)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ return err
+ }
+ } else {
+ currHash = string(h)
+ }
+ }
+
+ if currHash != "" && currHash != currRC.Hash {
+ // Seems the user has changed the container resolv.conf since the last time
+ // we checked so return without doing anything.
+ //logrus.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
+ return nil
+ }
+
+ // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
+ newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
+ if err != nil {
+ return err
+ }
+ err = ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, 0644)
+ if err != nil {
+ return err
+ }
+
+ // write the new hash in a temp file and rename it to make the update atomic
+ dir := path.Dir(sb.config.resolvConfPath)
+ tmpHashFile, err := ioutil.TempFile(dir, "hash")
+ if err != nil {
+ return err
+ }
+ if err = tmpHashFile.Chmod(filePerm); err != nil {
+ tmpHashFile.Close()
+ return err
+ }
+ _, err = tmpHashFile.Write([]byte(newRC.Hash))
+ if err1 := tmpHashFile.Close(); err == nil {
+ err = err1
+ }
+ if err != nil {
+ return err
+ }
+ return os.Rename(tmpHashFile.Name(), hashFile)
+}
+
+// Embedded DNS server has to be enabled for this sandbox. Rebuild the container's
+// resolv.conf by doing the following
+// - Add only the embedded server's IP to container's resolv.conf
+// - If the embedded server needs any resolv.conf options add it to the current list
+func (sb *sandbox) rebuildDNS() error {
+ currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
+ if err != nil {
+ return err
+ }
+
+ if len(sb.extDNS) == 0 {
+ sb.setExternalResolvers(currRC.Content, types.IPv4, false)
+ }
+ var (
+ dnsList = []string{sb.resolver.NameServer()}
+ dnsOptionsList = resolvconf.GetOptions(currRC.Content)
+ dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
+ )
+
+ // external v6 DNS servers has to be listed in resolv.conf
+ dnsList = append(dnsList, resolvconf.GetNameservers(currRC.Content, types.IPv6)...)
+
+ // If the user config and embedded DNS server both have ndots option set,
+ // remember the user's config so that unqualified names not in the docker
+ // domain can be dropped.
+ resOptions := sb.resolver.ResolverOptions()
+
+dnsOpt:
+ for _, resOpt := range resOptions {
+ if strings.Contains(resOpt, "ndots") {
+ for _, option := range dnsOptionsList {
+ if strings.Contains(option, "ndots") {
+ parts := strings.Split(option, ":")
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid ndots option %v", option)
+ }
+ if num, err := strconv.Atoi(parts[1]); err != nil {
+ return fmt.Errorf("invalid number for ndots option %v", option)
+ } else if num > 0 {
+ sb.ndotsSet = true
+ break dnsOpt
+ }
+ }
+ }
+ }
+ }
+
+ dnsOptionsList = append(dnsOptionsList, resOptions...)
+
+ _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
+ return err
+}
+
+func createBasePath(dir string) error {
+ return os.MkdirAll(dir, dirPerm)
+}
+
+func createFile(path string) error {
+ var f *os.File
+
+ dir, _ := filepath.Split(path)
+ err := createBasePath(dir)
+ if err != nil {
+ return err
+ }
+
+ f, err = os.Create(path)
+ if err == nil {
+ f.Close()
+ }
+
+ return err
+}
+
+func copyFile(src, dst string) error {
+ sBytes, err := ioutil.ReadFile(src)
+ if err != nil {
+ return err
+ }
+ return ioutil.WriteFile(dst, sBytes, filePerm)
+}
diff --git a/vendor/github.com/docker/libnetwork/sandbox_dns_windows.go b/vendor/github.com/docker/libnetwork/sandbox_dns_windows.go
new file mode 100644
index 0000000..e1ca73e
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/sandbox_dns_windows.go
@@ -0,0 +1,35 @@
+// +build windows
+
+package libnetwork
+
+import (
+ "github.com/docker/libnetwork/etchosts"
+)
+
+// Stub implementations for DNS related functions
+
+func (sb *sandbox) startResolver(bool) {
+}
+
+func (sb *sandbox) setupResolutionFiles() error {
+ return nil
+}
+
+func (sb *sandbox) restorePath() {
+}
+
+func (sb *sandbox) updateHostsFile(ifaceIP string) error {
+ return nil
+}
+
+func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
+
+}
+
+func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
+
+}
+
+func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/sandbox_externalkey.go b/vendor/github.com/docker/libnetwork/sandbox_externalkey.go
new file mode 100644
index 0000000..3c362f3
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/sandbox_externalkey.go
@@ -0,0 +1,12 @@
+package libnetwork
+
+import "github.com/docker/docker/pkg/reexec"
+
+type setKeyData struct {
+ ContainerID string
+ Key string
+}
+
+func init() {
+ reexec.Register("libnetwork-setkey", processSetKeyReexec)
+}
diff --git a/vendor/github.com/docker/libnetwork/sandbox_externalkey_solaris.go b/vendor/github.com/docker/libnetwork/sandbox_externalkey_solaris.go
new file mode 100644
index 0000000..7569e46
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/sandbox_externalkey_solaris.go
@@ -0,0 +1,45 @@
+// +build solaris
+
+package libnetwork
+
+import (
+ "io"
+ "net"
+
+ "github.com/docker/libnetwork/types"
+)
+
+// processSetKeyReexec is a private function that must be called only on an reexec path
+// It expects 3 args { [0] = "libnetwork-setkey", [1] = <container-id>, [2] = <controller-id> }
+// It also expects libcontainer.State as a json string in <stdin>
+// Refer to https://github.com/opencontainers/runc/pull/160/ for more information
+func processSetKeyReexec() {
+}
+
+// SetExternalKey provides a convenient way to set an External key to a sandbox
+func SetExternalKey(controllerID string, containerID string, key string) error {
+ return types.NotImplementedErrorf("SetExternalKey isn't supported on non linux systems")
+}
+
+func sendKey(c net.Conn, data setKeyData) error {
+ return types.NotImplementedErrorf("sendKey isn't supported on non linux systems")
+}
+
+func processReturn(r io.Reader) error {
+ return types.NotImplementedErrorf("processReturn isn't supported on non linux systems")
+}
+
+// no-op on non linux systems
+func (c *controller) startExternalKeyListener() error {
+ return nil
+}
+
+func (c *controller) acceptClientConnections(sock string, l net.Listener) {
+}
+
+func (c *controller) processExternalKey(conn net.Conn) error {
+ return types.NotImplementedErrorf("processExternalKey isn't supported on non linux systems")
+}
+
+func (c *controller) stopExternalKeyListener() {
+}
diff --git a/vendor/github.com/docker/libnetwork/sandbox_externalkey_unix.go b/vendor/github.com/docker/libnetwork/sandbox_externalkey_unix.go
new file mode 100644
index 0000000..4a7ac06
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/sandbox_externalkey_unix.go
@@ -0,0 +1,177 @@
+// +build linux freebsd
+
+package libnetwork
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net"
+ "os"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/types"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+const udsBase = "/run/docker/libnetwork/"
+const success = "success"
+
+// processSetKeyReexec is a private function that must be called only on an reexec path
+// It expects 3 args { [0] = "libnetwork-setkey", [1] = <container-id>, [2] = <controller-id> }
+// It also expects configs.HookState as a json string in <stdin>
+// Refer to https://github.com/opencontainers/runc/pull/160/ for more information
+func processSetKeyReexec() {
+ var err error
+
+ // Return a failure to the calling process via ExitCode
+ defer func() {
+ if err != nil {
+ logrus.Fatalf("%v", err)
+ }
+ }()
+
+ // expecting 3 args {[0]="libnetwork-setkey", [1]=<container-id>, [2]=<controller-id> }
+ if len(os.Args) < 3 {
+ err = fmt.Errorf("Re-exec expects 3 args, received : %d", len(os.Args))
+ return
+ }
+ containerID := os.Args[1]
+
+ // We expect configs.HookState as a json string in <stdin>
+ stateBuf, err := ioutil.ReadAll(os.Stdin)
+ if err != nil {
+ return
+ }
+ var state configs.HookState
+ if err = json.Unmarshal(stateBuf, &state); err != nil {
+ return
+ }
+
+ controllerID := os.Args[2]
+
+ err = SetExternalKey(controllerID, containerID, fmt.Sprintf("/proc/%d/ns/net", state.Pid))
+ return
+}
+
+// SetExternalKey provides a convenient way to set an External key to a sandbox
+func SetExternalKey(controllerID string, containerID string, key string) error {
+ keyData := setKeyData{
+ ContainerID: containerID,
+ Key: key}
+
+ c, err := net.Dial("unix", udsBase+controllerID+".sock")
+ if err != nil {
+ return err
+ }
+ defer c.Close()
+
+ if err = sendKey(c, keyData); err != nil {
+ return fmt.Errorf("sendKey failed with : %v", err)
+ }
+ return processReturn(c)
+}
+
+func sendKey(c net.Conn, data setKeyData) error {
+ var err error
+ defer func() {
+ if err != nil {
+ c.Close()
+ }
+ }()
+
+ var b []byte
+ if b, err = json.Marshal(data); err != nil {
+ return err
+ }
+
+ _, err = c.Write(b)
+ return err
+}
+
+func processReturn(r io.Reader) error {
+ buf := make([]byte, 1024)
+ n, err := r.Read(buf[:])
+ if err != nil {
+ return fmt.Errorf("failed to read buf in processReturn : %v", err)
+ }
+ if string(buf[0:n]) != success {
+ return fmt.Errorf(string(buf[0:n]))
+ }
+ return nil
+}
+
+func (c *controller) startExternalKeyListener() error {
+ if err := os.MkdirAll(udsBase, 0600); err != nil {
+ return err
+ }
+ uds := udsBase + c.id + ".sock"
+ l, err := net.Listen("unix", uds)
+ if err != nil {
+ return err
+ }
+ if err := os.Chmod(uds, 0600); err != nil {
+ l.Close()
+ return err
+ }
+ c.Lock()
+ c.extKeyListener = l
+ c.Unlock()
+
+ go c.acceptClientConnections(uds, l)
+ return nil
+}
+
+func (c *controller) acceptClientConnections(sock string, l net.Listener) {
+ for {
+ conn, err := l.Accept()
+ if err != nil {
+ if _, err1 := os.Stat(sock); os.IsNotExist(err1) {
+ logrus.Debugf("Unix socket %s doesn't exist. cannot accept client connections", sock)
+ return
+ }
+ logrus.Errorf("Error accepting connection %v", err)
+ continue
+ }
+ go func() {
+ defer conn.Close()
+
+ err := c.processExternalKey(conn)
+ ret := success
+ if err != nil {
+ ret = err.Error()
+ }
+
+ _, err = conn.Write([]byte(ret))
+ if err != nil {
+ logrus.Errorf("Error returning to the client %v", err)
+ }
+ }()
+ }
+}
+
+func (c *controller) processExternalKey(conn net.Conn) error {
+ buf := make([]byte, 1280)
+ nr, err := conn.Read(buf)
+ if err != nil {
+ return err
+ }
+ var s setKeyData
+ if err = json.Unmarshal(buf[0:nr], &s); err != nil {
+ return err
+ }
+
+ var sandbox Sandbox
+ search := SandboxContainerWalker(&sandbox, s.ContainerID)
+ c.WalkSandboxes(search)
+ if sandbox == nil {
+ return types.BadRequestErrorf("no sandbox present for %s", s.ContainerID)
+ }
+
+ return sandbox.SetKey(s.Key)
+}
+
+func (c *controller) stopExternalKeyListener() {
+ c.extKeyListener.Close()
+}
diff --git a/vendor/github.com/docker/libnetwork/sandbox_externalkey_windows.go b/vendor/github.com/docker/libnetwork/sandbox_externalkey_windows.go
new file mode 100644
index 0000000..340cd17
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/sandbox_externalkey_windows.go
@@ -0,0 +1,45 @@
+// +build windows
+
+package libnetwork
+
+import (
+ "io"
+ "net"
+
+ "github.com/docker/libnetwork/types"
+)
+
+// processSetKeyReexec is a private function that must be called only on an reexec path
+// It expects 3 args { [0] = "libnetwork-setkey", [1] = <container-id>, [2] = <controller-id> }
+// It also expects configs.HookState as a json string in <stdin>
+// Refer to https://github.com/opencontainers/runc/pull/160/ for more information
+func processSetKeyReexec() {
+}
+
+// SetExternalKey provides a convenient way to set an External key to a sandbox
+func SetExternalKey(controllerID string, containerID string, key string) error {
+ return types.NotImplementedErrorf("SetExternalKey isn't supported on non linux systems")
+}
+
+func sendKey(c net.Conn, data setKeyData) error {
+ return types.NotImplementedErrorf("sendKey isn't supported on non linux systems")
+}
+
+func processReturn(r io.Reader) error {
+ return types.NotImplementedErrorf("processReturn isn't supported on non linux systems")
+}
+
+// no-op on non linux systems
+func (c *controller) startExternalKeyListener() error {
+ return nil
+}
+
+func (c *controller) acceptClientConnections(sock string, l net.Listener) {
+}
+
+func (c *controller) processExternalKey(conn net.Conn) error {
+ return types.NotImplementedErrorf("processExternalKey isn't supported on non linux systems")
+}
+
+func (c *controller) stopExternalKeyListener() {
+}
diff --git a/vendor/github.com/docker/libnetwork/sandbox_store.go b/vendor/github.com/docker/libnetwork/sandbox_store.go
new file mode 100644
index 0000000..38b2bd7
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/sandbox_store.go
@@ -0,0 +1,307 @@
+package libnetwork
+
+import (
+ "container/heap"
+ "encoding/json"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/osl"
+)
+
+const (
+ sandboxPrefix = "sandbox"
+)
+
+type epState struct {
+ Eid string
+ Nid string
+}
+
+type sbState struct {
+ ID string
+ Cid string
+ c *controller
+ dbIndex uint64
+ dbExists bool
+ Eps []epState
+ EpPriority map[string]int
+ // external servers have to be persisted so that on restart of a live-restore
+ // enabled daemon we get the external servers for the running containers.
+ // We have two versions of ExtDNS to support upgrade & downgrade of the daemon
+ // between >=1.14 and <1.14 versions.
+ ExtDNS []string
+ ExtDNS2 []extDNSEntry
+}
+
+func (sbs *sbState) Key() []string {
+ return []string{sandboxPrefix, sbs.ID}
+}
+
+func (sbs *sbState) KeyPrefix() []string {
+ return []string{sandboxPrefix}
+}
+
+func (sbs *sbState) Value() []byte {
+ b, err := json.Marshal(sbs)
+ if err != nil {
+ return nil
+ }
+ return b
+}
+
+func (sbs *sbState) SetValue(value []byte) error {
+ return json.Unmarshal(value, sbs)
+}
+
+func (sbs *sbState) Index() uint64 {
+ sbi, err := sbs.c.SandboxByID(sbs.ID)
+ if err != nil {
+ return sbs.dbIndex
+ }
+
+ sb := sbi.(*sandbox)
+ maxIndex := sb.dbIndex
+ if sbs.dbIndex > maxIndex {
+ maxIndex = sbs.dbIndex
+ }
+
+ return maxIndex
+}
+
+func (sbs *sbState) SetIndex(index uint64) {
+ sbs.dbIndex = index
+ sbs.dbExists = true
+
+ sbi, err := sbs.c.SandboxByID(sbs.ID)
+ if err != nil {
+ return
+ }
+
+ sb := sbi.(*sandbox)
+ sb.dbIndex = index
+ sb.dbExists = true
+}
+
+func (sbs *sbState) Exists() bool {
+ if sbs.dbExists {
+ return sbs.dbExists
+ }
+
+ sbi, err := sbs.c.SandboxByID(sbs.ID)
+ if err != nil {
+ return false
+ }
+
+ sb := sbi.(*sandbox)
+ return sb.dbExists
+}
+
+func (sbs *sbState) Skip() bool {
+ return false
+}
+
+func (sbs *sbState) New() datastore.KVObject {
+ return &sbState{c: sbs.c}
+}
+
+func (sbs *sbState) CopyTo(o datastore.KVObject) error {
+ dstSbs := o.(*sbState)
+ dstSbs.c = sbs.c
+ dstSbs.ID = sbs.ID
+ dstSbs.Cid = sbs.Cid
+ dstSbs.dbIndex = sbs.dbIndex
+ dstSbs.dbExists = sbs.dbExists
+ dstSbs.EpPriority = sbs.EpPriority
+
+ for _, eps := range sbs.Eps {
+ dstSbs.Eps = append(dstSbs.Eps, eps)
+ }
+
+ if len(sbs.ExtDNS2) > 0 {
+ for _, dns := range sbs.ExtDNS2 {
+ dstSbs.ExtDNS2 = append(dstSbs.ExtDNS2, dns)
+ dstSbs.ExtDNS = append(dstSbs.ExtDNS, dns.IPStr)
+ }
+ return nil
+ }
+ for _, dns := range sbs.ExtDNS {
+ dstSbs.ExtDNS = append(dstSbs.ExtDNS, dns)
+ dstSbs.ExtDNS2 = append(dstSbs.ExtDNS2, extDNSEntry{IPStr: dns})
+ }
+
+ return nil
+}
+
+func (sbs *sbState) DataScope() string {
+ return datastore.LocalScope
+}
+
+func (sb *sandbox) storeUpdate() error {
+ sbs := &sbState{
+ c: sb.controller,
+ ID: sb.id,
+ Cid: sb.containerID,
+ EpPriority: sb.epPriority,
+ ExtDNS2: sb.extDNS,
+ }
+
+ for _, ext := range sb.extDNS {
+ sbs.ExtDNS = append(sbs.ExtDNS, ext.IPStr)
+ }
+
+retry:
+ sbs.Eps = nil
+ for _, ep := range sb.getConnectedEndpoints() {
+ // If the endpoint is not persisted then do not add it to
+ // the sandbox checkpoint
+ if ep.Skip() {
+ continue
+ }
+
+ eps := epState{
+ Nid: ep.getNetwork().ID(),
+ Eid: ep.ID(),
+ }
+
+ sbs.Eps = append(sbs.Eps, eps)
+ }
+
+ err := sb.controller.updateToStore(sbs)
+ if err == datastore.ErrKeyModified {
+ // When we get ErrKeyModified it is sufficient to just
+ // go back and retry. No need to get the object from
+ // the store because we always regenerate the store
+ // state from in memory sandbox state
+ goto retry
+ }
+
+ return err
+}
+
+func (sb *sandbox) storeDelete() error {
+ sbs := &sbState{
+ c: sb.controller,
+ ID: sb.id,
+ Cid: sb.containerID,
+ dbIndex: sb.dbIndex,
+ dbExists: sb.dbExists,
+ }
+
+ return sb.controller.deleteFromStore(sbs)
+}
+
+func (c *controller) sandboxCleanup(activeSandboxes map[string]interface{}) {
+ store := c.getStore(datastore.LocalScope)
+ if store == nil {
+ logrus.Error("Could not find local scope store while trying to cleanup sandboxes")
+ return
+ }
+
+ kvol, err := store.List(datastore.Key(sandboxPrefix), &sbState{c: c})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ logrus.Errorf("failed to get sandboxes for scope %s: %v", store.Scope(), err)
+ return
+ }
+
+ // It's normal for no sandboxes to be found. Just bail out.
+ if err == datastore.ErrKeyNotFound {
+ return
+ }
+
+ for _, kvo := range kvol {
+ sbs := kvo.(*sbState)
+
+ sb := &sandbox{
+ id: sbs.ID,
+ controller: sbs.c,
+ containerID: sbs.Cid,
+ endpoints: epHeap{},
+ populatedEndpoints: map[string]struct{}{},
+ dbIndex: sbs.dbIndex,
+ isStub: true,
+ dbExists: true,
+ }
+ // If we are restoring from a older version extDNSEntry won't have the
+ // HostLoopback field
+ if len(sbs.ExtDNS2) > 0 {
+ sb.extDNS = sbs.ExtDNS2
+ } else {
+ for _, dns := range sbs.ExtDNS {
+ sb.extDNS = append(sb.extDNS, extDNSEntry{IPStr: dns})
+ }
+ }
+
+ msg := " for cleanup"
+ create := true
+ isRestore := false
+ if val, ok := activeSandboxes[sb.ID()]; ok {
+ msg = ""
+ sb.isStub = false
+ isRestore = true
+ opts := val.([]SandboxOption)
+ sb.processOptions(opts...)
+ sb.restorePath()
+ create = !sb.config.useDefaultSandBox
+ heap.Init(&sb.endpoints)
+ }
+ sb.osSbox, err = osl.NewSandbox(sb.Key(), create, isRestore)
+ if err != nil {
+ logrus.Errorf("failed to create osl sandbox while trying to restore sandbox %s%s: %v", sb.ID()[0:7], msg, err)
+ continue
+ }
+
+ c.Lock()
+ c.sandboxes[sb.id] = sb
+ c.Unlock()
+
+ for _, eps := range sbs.Eps {
+ n, err := c.getNetworkFromStore(eps.Nid)
+ var ep *endpoint
+ if err != nil {
+ logrus.Errorf("getNetworkFromStore for nid %s failed while trying to build sandbox for cleanup: %v", eps.Nid, err)
+ n = &network{id: eps.Nid, ctrlr: c, drvOnce: &sync.Once{}, persist: true}
+ ep = &endpoint{id: eps.Eid, network: n, sandboxID: sbs.ID}
+ } else {
+ ep, err = n.getEndpointFromStore(eps.Eid)
+ if err != nil {
+ logrus.Errorf("getEndpointFromStore for eid %s failed while trying to build sandbox for cleanup: %v", eps.Eid, err)
+ ep = &endpoint{id: eps.Eid, network: n, sandboxID: sbs.ID}
+ }
+ }
+ if _, ok := activeSandboxes[sb.ID()]; ok && err != nil {
+ logrus.Errorf("failed to restore endpoint %s in %s for container %s due to %v", eps.Eid, eps.Nid, sb.ContainerID(), err)
+ continue
+ }
+ heap.Push(&sb.endpoints, ep)
+ }
+
+ if _, ok := activeSandboxes[sb.ID()]; !ok {
+ logrus.Infof("Removing stale sandbox %s (%s)", sb.id, sb.containerID)
+ if err := sb.delete(true); err != nil {
+ logrus.Errorf("Failed to delete sandbox %s while trying to cleanup: %v", sb.id, err)
+ }
+ continue
+ }
+
+ // reconstruct osl sandbox field
+ if !sb.config.useDefaultSandBox {
+ if err := sb.restoreOslSandbox(); err != nil {
+ logrus.Errorf("failed to populate fields for osl sandbox %s", sb.ID())
+ continue
+ }
+ } else {
+ c.sboxOnce.Do(func() {
+ c.defOsSbox = sb.osSbox
+ })
+ }
+
+ for _, ep := range sb.endpoints {
+ // Watch for service records
+ if !c.isAgent() {
+ c.watchSvcRecord(ep)
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/service.go b/vendor/github.com/docker/libnetwork/service.go
new file mode 100644
index 0000000..5a0d7e0
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/service.go
@@ -0,0 +1,92 @@
+package libnetwork
+
+import (
+ "fmt"
+ "net"
+ "sync"
+
+ "github.com/docker/libnetwork/common"
+)
+
+var (
+ // A global monotonic counter to assign firewall marks to
+ // services.
+ fwMarkCtr uint32 = 256
+ fwMarkCtrMu sync.Mutex
+)
+
+type portConfigs []*PortConfig
+
+func (p portConfigs) String() string {
+ if len(p) == 0 {
+ return ""
+ }
+
+ pc := p[0]
+ str := fmt.Sprintf("%d:%d/%s", pc.PublishedPort, pc.TargetPort, PortConfig_Protocol_name[int32(pc.Protocol)])
+ for _, pc := range p[1:] {
+ str = str + fmt.Sprintf(",%d:%d/%s", pc.PublishedPort, pc.TargetPort, PortConfig_Protocol_name[int32(pc.Protocol)])
+ }
+
+ return str
+}
+
+type serviceKey struct {
+ id string
+ ports string
+}
+
+type service struct {
+ name string // Service Name
+ id string // Service ID
+
+ // Map of loadbalancers for the service one-per attached
+ // network. It is keyed with network ID.
+ loadBalancers map[string]*loadBalancer
+
+ // List of ingress ports exposed by the service
+ ingressPorts portConfigs
+
+ // Service aliases
+ aliases []string
+
+ // This maps tracks for each IP address the list of endpoints ID
+ // associated with it. At stable state the endpoint ID expected is 1
+ // but during transition and service change it is possible to have
+ // temporary more than 1
+ ipToEndpoint common.SetMatrix
+
+ deleted bool
+
+ sync.Mutex
+}
+
+// assignIPToEndpoint inserts the mapping between the IP and the endpoint identifier
+// returns true if the mapping was not present, false otherwise
+// returns also the number of endpoints associated to the IP
+func (s *service) assignIPToEndpoint(ip, eID string) (bool, int) {
+ return s.ipToEndpoint.Insert(ip, eID)
+}
+
+// removeIPToEndpoint removes the mapping between the IP and the endpoint identifier
+// returns true if the mapping was deleted, false otherwise
+// returns also the number of endpoints associated to the IP
+func (s *service) removeIPToEndpoint(ip, eID string) (bool, int) {
+ return s.ipToEndpoint.Remove(ip, eID)
+}
+
+func (s *service) printIPToEndpoint(ip string) (string, bool) {
+ return s.ipToEndpoint.String(ip)
+}
+
+type loadBalancer struct {
+ vip net.IP
+ fwMark uint32
+
+ // Map of backend IPs backing this loadbalancer on this
+ // network. It is keyed with endpoint ID.
+ backEnds map[string]net.IP
+
+ // Back pointer to service to which the loadbalancer belongs.
+ service *service
+}
diff --git a/vendor/github.com/docker/libnetwork/service_common.go b/vendor/github.com/docker/libnetwork/service_common.go
new file mode 100644
index 0000000..7e3367c
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/service_common.go
@@ -0,0 +1,381 @@
+// +build linux windows
+
+package libnetwork
+
+import (
+ "net"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libnetwork/common"
+)
+
+func (c *controller) addEndpointNameResolution(svcName, svcID, nID, eID, containerName string, vip net.IP, serviceAliases, taskAliases []string, ip net.IP, addService bool, method string) error {
+ n, err := c.NetworkByID(nID)
+ if err != nil {
+ return err
+ }
+
+ logrus.Debugf("addEndpointNameResolution %s %s add_service:%t sAliases:%v tAliases:%v", eID, svcName, addService, serviceAliases, taskAliases)
+
+ // Add container resolution mappings
+ c.addContainerNameResolution(nID, eID, containerName, taskAliases, ip, method)
+
+ serviceID := svcID
+ if serviceID == "" {
+ // This is the case of a normal container not part of a service
+ serviceID = eID
+ }
+
+ // Add endpoint IP to special "tasks.svc_name" so that the applications have access to DNS RR.
+ n.(*network).addSvcRecords(eID, "tasks."+svcName, serviceID, ip, nil, false, method)
+ for _, alias := range serviceAliases {
+ n.(*network).addSvcRecords(eID, "tasks."+alias, serviceID, ip, nil, false, method)
+ }
+
+ // Add service name to vip in DNS, if vip is valid. Otherwise resort to DNS RR
+ if len(vip) == 0 {
+ n.(*network).addSvcRecords(eID, svcName, serviceID, ip, nil, false, method)
+ for _, alias := range serviceAliases {
+ n.(*network).addSvcRecords(eID, alias, serviceID, ip, nil, false, method)
+ }
+ }
+
+ if addService && len(vip) != 0 {
+ n.(*network).addSvcRecords(eID, svcName, serviceID, vip, nil, false, method)
+ for _, alias := range serviceAliases {
+ n.(*network).addSvcRecords(eID, alias, serviceID, vip, nil, false, method)
+ }
+ }
+
+ return nil
+}
+
+func (c *controller) addContainerNameResolution(nID, eID, containerName string, taskAliases []string, ip net.IP, method string) error {
+ n, err := c.NetworkByID(nID)
+ if err != nil {
+ return err
+ }
+ logrus.Debugf("addContainerNameResolution %s %s", eID, containerName)
+
+ // Add resolution for container name
+ n.(*network).addSvcRecords(eID, containerName, eID, ip, nil, true, method)
+
+ // Add resolution for taskaliases
+ for _, alias := range taskAliases {
+ n.(*network).addSvcRecords(eID, alias, eID, ip, nil, true, method)
+ }
+
+ return nil
+}
+
+func (c *controller) deleteEndpointNameResolution(svcName, svcID, nID, eID, containerName string, vip net.IP, serviceAliases, taskAliases []string, ip net.IP, rmService, multipleEntries bool, method string) error {
+ n, err := c.NetworkByID(nID)
+ if err != nil {
+ return err
+ }
+
+ logrus.Debugf("deleteEndpointNameResolution %s %s rm_service:%t suppress:%t sAliases:%v tAliases:%v", eID, svcName, rmService, multipleEntries, serviceAliases, taskAliases)
+
+ // Delete container resolution mappings
+ c.delContainerNameResolution(nID, eID, containerName, taskAliases, ip, method)
+
+ serviceID := svcID
+ if serviceID == "" {
+ // This is the case of a normal container not part of a service
+ serviceID = eID
+ }
+
+ // Delete the special "tasks.svc_name" backend record.
+ if !multipleEntries {
+ n.(*network).deleteSvcRecords(eID, "tasks."+svcName, serviceID, ip, nil, false, method)
+ for _, alias := range serviceAliases {
+ n.(*network).deleteSvcRecords(eID, "tasks."+alias, serviceID, ip, nil, false, method)
+ }
+ }
+
+ // If we are doing DNS RR delete the endpoint IP from DNS record right away.
+ if !multipleEntries && len(vip) == 0 {
+ n.(*network).deleteSvcRecords(eID, svcName, serviceID, ip, nil, false, method)
+ for _, alias := range serviceAliases {
+ n.(*network).deleteSvcRecords(eID, alias, serviceID, ip, nil, false, method)
+ }
+ }
+
+ // Remove the DNS record for VIP only if we are removing the service
+ if rmService && len(vip) != 0 && !multipleEntries {
+ n.(*network).deleteSvcRecords(eID, svcName, serviceID, vip, nil, false, method)
+ for _, alias := range serviceAliases {
+ n.(*network).deleteSvcRecords(eID, alias, serviceID, vip, nil, false, method)
+ }
+ }
+
+ return nil
+}
+
+func (c *controller) delContainerNameResolution(nID, eID, containerName string, taskAliases []string, ip net.IP, method string) error {
+ n, err := c.NetworkByID(nID)
+ if err != nil {
+ return err
+ }
+ logrus.Debugf("delContainerNameResolution %s %s", eID, containerName)
+
+ // Delete resolution for container name
+ n.(*network).deleteSvcRecords(eID, containerName, eID, ip, nil, true, method)
+
+ // Delete resolution for taskaliases
+ for _, alias := range taskAliases {
+ n.(*network).deleteSvcRecords(eID, alias, eID, ip, nil, true, method)
+ }
+
+ return nil
+}
+
+func newService(name string, id string, ingressPorts []*PortConfig, serviceAliases []string) *service {
+ return &service{
+ name: name,
+ id: id,
+ ingressPorts: ingressPorts,
+ loadBalancers: make(map[string]*loadBalancer),
+ aliases: serviceAliases,
+ ipToEndpoint: common.NewSetMatrix(),
+ }
+}
+
+func (c *controller) getLBIndex(sid, nid string, ingressPorts []*PortConfig) int {
+ skey := serviceKey{
+ id: sid,
+ ports: portConfigs(ingressPorts).String(),
+ }
+ c.Lock()
+ s, ok := c.serviceBindings[skey]
+ c.Unlock()
+
+ if !ok {
+ return 0
+ }
+
+ s.Lock()
+ lb := s.loadBalancers[nid]
+ s.Unlock()
+
+ return int(lb.fwMark)
+}
+
+func (c *controller) cleanupServiceBindings(cleanupNID string) {
+ var cleanupFuncs []func()
+
+ logrus.Debugf("cleanupServiceBindings for %s", cleanupNID)
+ c.Lock()
+ services := make([]*service, 0, len(c.serviceBindings))
+ for _, s := range c.serviceBindings {
+ services = append(services, s)
+ }
+ c.Unlock()
+
+ for _, s := range services {
+ s.Lock()
+ // Skip the serviceBindings that got deleted
+ if s.deleted {
+ s.Unlock()
+ continue
+ }
+ for nid, lb := range s.loadBalancers {
+ if cleanupNID != "" && nid != cleanupNID {
+ continue
+ }
+
+ // The network is being deleted, erase all the associated service discovery records
+ // TODO(fcrisciani) separate the Load Balancer from the Service discovery, this operation
+ // can be done safely here, but the rmServiceBinding is still keeping consistency in the
+ // data structures that are tracking the endpoint to IP mapping.
+ c.Lock()
+ logrus.Debugf("cleanupServiceBindings erasing the svcRecords for %s", nid)
+ delete(c.svcRecords, nid)
+ c.Unlock()
+
+ for eid, ip := range lb.backEnds {
+ epID := eid
+ epIP := ip
+ service := s
+ loadBalancer := lb
+ networkID := nid
+ cleanupFuncs = append(cleanupFuncs, func() {
+ // ContainerName and taskAliases are not available here, this is still fine because the Service discovery
+ // cleanup already happened before. The only thing that rmServiceBinding is still doing here a part from the Load
+ // Balancer bookeeping, is to keep consistent the mapping of endpoint to IP.
+ if err := c.rmServiceBinding(service.name, service.id, networkID, epID, "", loadBalancer.vip,
+ service.ingressPorts, service.aliases, []string{}, epIP, "cleanupServiceBindings", false); err != nil {
+ logrus.Errorf("Failed to remove service bindings for service %s network %s endpoint %s while cleanup: %v",
+ service.id, networkID, epID, err)
+ }
+ })
+ }
+ }
+ s.Unlock()
+ }
+
+ for _, f := range cleanupFuncs {
+ f()
+ }
+
+}
+
+func (c *controller) addServiceBinding(svcName, svcID, nID, eID, containerName string, vip net.IP, ingressPorts []*PortConfig, serviceAliases, taskAliases []string, ip net.IP, method string) error {
+ var addService bool
+
+ n, err := c.NetworkByID(nID)
+ if err != nil {
+ return err
+ }
+
+ skey := serviceKey{
+ id: svcID,
+ ports: portConfigs(ingressPorts).String(),
+ }
+
+ var s *service
+ for {
+ c.Lock()
+ var ok bool
+ s, ok = c.serviceBindings[skey]
+ if !ok {
+ // Create a new service if we are seeing this service
+ // for the first time.
+ s = newService(svcName, svcID, ingressPorts, serviceAliases)
+ c.serviceBindings[skey] = s
+ }
+ c.Unlock()
+ s.Lock()
+ if !s.deleted {
+ // ok the object is good to be used
+ break
+ }
+ s.Unlock()
+ }
+ logrus.Debugf("addServiceBinding from %s START for %s %s p:%p nid:%s skey:%v", method, svcName, eID, s, nID, skey)
+ defer s.Unlock()
+
+ lb, ok := s.loadBalancers[nID]
+ if !ok {
+ // Create a new load balancer if we are seeing this
+ // network attachment on the service for the first
+ // time.
+ fwMarkCtrMu.Lock()
+
+ lb = &loadBalancer{
+ vip: vip,
+ fwMark: fwMarkCtr,
+ backEnds: make(map[string]net.IP),
+ service: s,
+ }
+
+ fwMarkCtr++
+ fwMarkCtrMu.Unlock()
+
+ s.loadBalancers[nID] = lb
+ addService = true
+ }
+
+ lb.backEnds[eID] = ip
+
+ ok, entries := s.assignIPToEndpoint(ip.String(), eID)
+ if !ok || entries > 1 {
+ setStr, b := s.printIPToEndpoint(ip.String())
+ logrus.Warnf("addServiceBinding %s possible trainsient state ok:%t entries:%d set:%t %s", eID, ok, entries, b, setStr)
+ }
+
+ // Add loadbalancer service and backend in all sandboxes in
+ // the network only if vip is valid.
+ if len(vip) != 0 {
+ n.(*network).addLBBackend(ip, vip, lb.fwMark, ingressPorts)
+ }
+
+ // Add the appropriate name resolutions
+ c.addEndpointNameResolution(svcName, svcID, nID, eID, containerName, vip, serviceAliases, taskAliases, ip, addService, "addServiceBinding")
+
+ logrus.Debugf("addServiceBinding from %s END for %s %s", method, svcName, eID)
+
+ return nil
+}
+
+func (c *controller) rmServiceBinding(svcName, svcID, nID, eID, containerName string, vip net.IP, ingressPorts []*PortConfig, serviceAliases []string, taskAliases []string, ip net.IP, method string, deleteSvcRecords bool) error {
+
+ var rmService bool
+
+ n, err := c.NetworkByID(nID)
+ if err != nil {
+ return err
+ }
+
+ skey := serviceKey{
+ id: svcID,
+ ports: portConfigs(ingressPorts).String(),
+ }
+
+ c.Lock()
+ s, ok := c.serviceBindings[skey]
+ c.Unlock()
+ if !ok {
+ logrus.Warnf("rmServiceBinding %s %s %s aborted c.serviceBindings[skey] !ok", method, svcName, eID)
+ return nil
+ }
+
+ s.Lock()
+ defer s.Unlock()
+ logrus.Debugf("rmServiceBinding from %s START for %s %s p:%p nid:%s sKey:%v deleteSvc:%t", method, svcName, eID, s, nID, skey, deleteSvcRecords)
+ lb, ok := s.loadBalancers[nID]
+ if !ok {
+ logrus.Warnf("rmServiceBinding %s %s %s aborted s.loadBalancers[nid] !ok", method, svcName, eID)
+ return nil
+ }
+
+ _, ok = lb.backEnds[eID]
+ if !ok {
+ logrus.Warnf("rmServiceBinding %s %s %s aborted lb.backEnds[eid] !ok", method, svcName, eID)
+ return nil
+ }
+
+ delete(lb.backEnds, eID)
+ if len(lb.backEnds) == 0 {
+ // All the backends for this service have been
+ // removed. Time to remove the load balancer and also
+ // remove the service entry in IPVS.
+ rmService = true
+
+ delete(s.loadBalancers, nID)
+ logrus.Debugf("rmServiceBinding %s delete %s, p:%p in loadbalancers len:%d", eID, nID, lb, len(s.loadBalancers))
+ }
+
+ ok, entries := s.removeIPToEndpoint(ip.String(), eID)
+ if !ok || entries > 0 {
+ setStr, b := s.printIPToEndpoint(ip.String())
+ logrus.Warnf("rmServiceBinding %s possible trainsient state ok:%t entries:%d set:%t %s", eID, ok, entries, b, setStr)
+ }
+
+ // Remove loadbalancer service(if needed) and backend in all
+ // sandboxes in the network only if the vip is valid.
+ if len(vip) != 0 && entries == 0 {
+ n.(*network).rmLBBackend(ip, vip, lb.fwMark, ingressPorts, rmService)
+ }
+
+ // Delete the name resolutions
+ if deleteSvcRecords {
+ c.deleteEndpointNameResolution(svcName, svcID, nID, eID, containerName, vip, serviceAliases, taskAliases, ip, rmService, entries > 0, "rmServiceBinding")
+ }
+
+ if len(s.loadBalancers) == 0 {
+ // All loadbalancers for the service removed. Time to
+ // remove the service itself.
+ c.Lock()
+
+ // Mark the object as deleted so that the add won't use it wrongly
+ s.deleted = true
+ // NOTE The delete from the serviceBindings map has to be the last operation else we are allowing a race between this service
+ // that is getting deleted and a new service that will be created if the entry is not anymore there
+ delete(c.serviceBindings, skey)
+ c.Unlock()
+ }
+
+ logrus.Debugf("rmServiceBinding from %s END for %s %s", method, svcName, eID)
+ return nil
+}
diff --git a/vendor/github.com/docker/libnetwork/service_linux.go b/vendor/github.com/docker/libnetwork/service_linux.go
new file mode 100644
index 0000000..1cf7ee9
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/service_linux.go
@@ -0,0 +1,778 @@
+package libnetwork
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/docker/pkg/reexec"
+ "github.com/docker/libnetwork/iptables"
+ "github.com/docker/libnetwork/ipvs"
+ "github.com/docker/libnetwork/ns"
+ "github.com/gogo/protobuf/proto"
+ "github.com/vishvananda/netlink/nl"
+ "github.com/vishvananda/netns"
+)
+
+func init() {
+ reexec.Register("fwmarker", fwMarker)
+ reexec.Register("redirecter", redirecter)
+}
+
+// Get all loadbalancers on this network that is currently discovered
+// on this node.
+func (n *network) connectedLoadbalancers() []*loadBalancer {
+ c := n.getController()
+
+ c.Lock()
+ serviceBindings := make([]*service, 0, len(c.serviceBindings))
+ for _, s := range c.serviceBindings {
+ serviceBindings = append(serviceBindings, s)
+ }
+ c.Unlock()
+
+ var lbs []*loadBalancer
+ for _, s := range serviceBindings {
+ s.Lock()
+ // Skip the serviceBindings that got deleted
+ if s.deleted {
+ s.Unlock()
+ continue
+ }
+ if lb, ok := s.loadBalancers[n.ID()]; ok {
+ lbs = append(lbs, lb)
+ }
+ s.Unlock()
+ }
+
+ return lbs
+}
+
+// Populate all loadbalancers on the network that the passed endpoint
+// belongs to, into this sandbox.
+func (sb *sandbox) populateLoadbalancers(ep *endpoint) {
+ var gwIP net.IP
+
+ // This is an interface less endpoint. Nothing to do.
+ if ep.Iface() == nil {
+ return
+ }
+
+ n := ep.getNetwork()
+ eIP := ep.Iface().Address()
+
+ if n.ingress {
+ if err := addRedirectRules(sb.Key(), eIP, ep.ingressPorts); err != nil {
+ logrus.Errorf("Failed to add redirect rules for ep %s (%s): %v", ep.Name(), ep.ID()[0:7], err)
+ }
+ }
+
+ if sb.ingress {
+ // For the ingress sandbox if this is not gateway
+ // endpoint do nothing.
+ if ep != sb.getGatewayEndpoint() {
+ return
+ }
+
+ // This is the gateway endpoint. Now get the ingress
+ // network and plumb the loadbalancers.
+ gwIP = ep.Iface().Address().IP
+ for _, ep := range sb.getConnectedEndpoints() {
+ if !ep.endpointInGWNetwork() {
+ n = ep.getNetwork()
+ eIP = ep.Iface().Address()
+ }
+ }
+ }
+
+ for _, lb := range n.connectedLoadbalancers() {
+ // Skip if vip is not valid.
+ if len(lb.vip) == 0 {
+ continue
+ }
+
+ lb.service.Lock()
+ for _, ip := range lb.backEnds {
+ sb.addLBBackend(ip, lb.vip, lb.fwMark, lb.service.ingressPorts, eIP, gwIP, n.ingress)
+ }
+ lb.service.Unlock()
+ }
+}
+
+// Add loadbalancer backend to all sandboxes which has a connection to
+// this network. If needed add the service as well.
+func (n *network) addLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*PortConfig) {
+ n.WalkEndpoints(func(e Endpoint) bool {
+ ep := e.(*endpoint)
+ if sb, ok := ep.getSandbox(); ok {
+ if !sb.isEndpointPopulated(ep) {
+ return false
+ }
+
+ var gwIP net.IP
+ if ep := sb.getGatewayEndpoint(); ep != nil {
+ gwIP = ep.Iface().Address().IP
+ }
+
+ sb.addLBBackend(ip, vip, fwMark, ingressPorts, ep.Iface().Address(), gwIP, n.ingress)
+ }
+
+ return false
+ })
+}
+
+// Remove loadbalancer backend from all sandboxes which has a
+// connection to this network. If needed remove the service entry as
+// well, as specified by the rmService bool.
+func (n *network) rmLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, rmService bool) {
+ n.WalkEndpoints(func(e Endpoint) bool {
+ ep := e.(*endpoint)
+ if sb, ok := ep.getSandbox(); ok {
+ if !sb.isEndpointPopulated(ep) {
+ return false
+ }
+
+ var gwIP net.IP
+ if ep := sb.getGatewayEndpoint(); ep != nil {
+ gwIP = ep.Iface().Address().IP
+ }
+
+ sb.rmLBBackend(ip, vip, fwMark, ingressPorts, ep.Iface().Address(), gwIP, rmService, n.ingress)
+ }
+
+ return false
+ })
+}
+
+// Add loadbalancer backend into one connected sandbox.
+func (sb *sandbox) addLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, eIP *net.IPNet, gwIP net.IP, isIngressNetwork bool) {
+ if sb.osSbox == nil {
+ return
+ }
+
+ if isIngressNetwork && !sb.ingress {
+ return
+ }
+
+ i, err := ipvs.New(sb.Key())
+ if err != nil {
+ logrus.Errorf("Failed to create an ipvs handle for sbox %s (%s,%s) for lb addition: %v", sb.ID()[0:7], sb.ContainerID()[0:7], sb.Key(), err)
+ return
+ }
+ defer i.Close()
+
+ s := &ipvs.Service{
+ AddressFamily: nl.FAMILY_V4,
+ FWMark: fwMark,
+ SchedName: ipvs.RoundRobin,
+ }
+
+ if !i.IsServicePresent(s) {
+ var filteredPorts []*PortConfig
+ if sb.ingress {
+ filteredPorts = filterPortConfigs(ingressPorts, false)
+ if err := programIngress(gwIP, filteredPorts, false); err != nil {
+ logrus.Errorf("Failed to add ingress: %v", err)
+ return
+ }
+ }
+
+ logrus.Debugf("Creating service for vip %s fwMark %d ingressPorts %#v in sbox %s (%s)", vip, fwMark, ingressPorts, sb.ID()[0:7], sb.ContainerID()[0:7])
+ if err := invokeFWMarker(sb.Key(), vip, fwMark, ingressPorts, eIP, false); err != nil {
+ logrus.Errorf("Failed to add firewall mark rule in sbox %s (%s): %v", sb.ID()[0:7], sb.ContainerID()[0:7], err)
+ return
+ }
+
+ if err := i.NewService(s); err != nil && err != syscall.EEXIST {
+ logrus.Errorf("Failed to create a new service for vip %s fwmark %d in sbox %s (%s): %v", vip, fwMark, sb.ID()[0:7], sb.ContainerID()[0:7], err)
+ return
+ }
+ }
+
+ d := &ipvs.Destination{
+ AddressFamily: nl.FAMILY_V4,
+ Address: ip,
+ Weight: 1,
+ }
+
+ // Remove the sched name before using the service to add
+ // destination.
+ s.SchedName = ""
+ if err := i.NewDestination(s, d); err != nil && err != syscall.EEXIST {
+ logrus.Errorf("Failed to create real server %s for vip %s fwmark %d in sbox %s (%s): %v", ip, vip, fwMark, sb.ID()[0:7], sb.ContainerID()[0:7], err)
+ }
+}
+
+// Remove loadbalancer backend from one connected sandbox.
+func (sb *sandbox) rmLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, eIP *net.IPNet, gwIP net.IP, rmService bool, isIngressNetwork bool) {
+ if sb.osSbox == nil {
+ return
+ }
+
+ if isIngressNetwork && !sb.ingress {
+ return
+ }
+
+ i, err := ipvs.New(sb.Key())
+ if err != nil {
+ logrus.Errorf("Failed to create an ipvs handle for sbox %s (%s,%s) for lb removal: %v", sb.ID()[0:7], sb.ContainerID()[0:7], sb.Key(), err)
+ return
+ }
+ defer i.Close()
+
+ s := &ipvs.Service{
+ AddressFamily: nl.FAMILY_V4,
+ FWMark: fwMark,
+ }
+
+ d := &ipvs.Destination{
+ AddressFamily: nl.FAMILY_V4,
+ Address: ip,
+ Weight: 1,
+ }
+
+ if err := i.DelDestination(s, d); err != nil && err != syscall.ENOENT {
+ logrus.Errorf("Failed to delete real server %s for vip %s fwmark %d in sbox %s (%s): %v", ip, vip, fwMark, sb.ID()[0:7], sb.ContainerID()[0:7], err)
+ }
+
+ if rmService {
+ s.SchedName = ipvs.RoundRobin
+ if err := i.DelService(s); err != nil && err != syscall.ENOENT {
+ logrus.Errorf("Failed to delete service for vip %s fwmark %d in sbox %s (%s): %v", vip, fwMark, sb.ID()[0:7], sb.ContainerID()[0:7], err)
+ }
+
+ var filteredPorts []*PortConfig
+ if sb.ingress {
+ filteredPorts = filterPortConfigs(ingressPorts, true)
+ if err := programIngress(gwIP, filteredPorts, true); err != nil {
+ logrus.Errorf("Failed to delete ingress: %v", err)
+ }
+ }
+
+ if err := invokeFWMarker(sb.Key(), vip, fwMark, ingressPorts, eIP, true); err != nil {
+ logrus.Errorf("Failed to delete firewall mark rule in sbox %s (%s): %v", sb.ID()[0:7], sb.ContainerID()[0:7], err)
+ }
+ }
+}
+
+const ingressChain = "DOCKER-INGRESS"
+
+var (
+ ingressOnce sync.Once
+ ingressProxyMu sync.Mutex
+ ingressProxyTbl = make(map[string]io.Closer)
+ portConfigMu sync.Mutex
+ portConfigTbl = make(map[PortConfig]int)
+)
+
+func filterPortConfigs(ingressPorts []*PortConfig, isDelete bool) []*PortConfig {
+ portConfigMu.Lock()
+ iPorts := make([]*PortConfig, 0, len(ingressPorts))
+ for _, pc := range ingressPorts {
+ if isDelete {
+ if cnt, ok := portConfigTbl[*pc]; ok {
+ // This is the last reference to this
+ // port config. Delete the port config
+ // and add it to filtered list to be
+ // plumbed.
+ if cnt == 1 {
+ delete(portConfigTbl, *pc)
+ iPorts = append(iPorts, pc)
+ continue
+ }
+
+ portConfigTbl[*pc] = cnt - 1
+ }
+
+ continue
+ }
+
+ if cnt, ok := portConfigTbl[*pc]; ok {
+ portConfigTbl[*pc] = cnt + 1
+ continue
+ }
+
+ // We are adding it for the first time. Add it to the
+ // filter list to be plumbed.
+ portConfigTbl[*pc] = 1
+ iPorts = append(iPorts, pc)
+ }
+ portConfigMu.Unlock()
+
+ return iPorts
+}
+
+func programIngress(gwIP net.IP, ingressPorts []*PortConfig, isDelete bool) error {
+ addDelOpt := "-I"
+ if isDelete {
+ addDelOpt = "-D"
+ }
+
+ chainExists := iptables.ExistChain(ingressChain, iptables.Nat)
+ filterChainExists := iptables.ExistChain(ingressChain, iptables.Filter)
+
+ ingressOnce.Do(func() {
+ // Flush nat table and filter table ingress chain rules during init if it
+ // exists. It might contain stale rules from previous life.
+ if chainExists {
+ if err := iptables.RawCombinedOutput("-t", "nat", "-F", ingressChain); err != nil {
+ logrus.Errorf("Could not flush nat table ingress chain rules during init: %v", err)
+ }
+ }
+ if filterChainExists {
+ if err := iptables.RawCombinedOutput("-F", ingressChain); err != nil {
+ logrus.Errorf("Could not flush filter table ingress chain rules during init: %v", err)
+ }
+ }
+ })
+
+ if !isDelete {
+ if !chainExists {
+ if err := iptables.RawCombinedOutput("-t", "nat", "-N", ingressChain); err != nil {
+ return fmt.Errorf("failed to create ingress chain: %v", err)
+ }
+ }
+ if !filterChainExists {
+ if err := iptables.RawCombinedOutput("-N", ingressChain); err != nil {
+ return fmt.Errorf("failed to create filter table ingress chain: %v", err)
+ }
+ }
+
+ if !iptables.Exists(iptables.Nat, ingressChain, "-j", "RETURN") {
+ if err := iptables.RawCombinedOutput("-t", "nat", "-A", ingressChain, "-j", "RETURN"); err != nil {
+ return fmt.Errorf("failed to add return rule in nat table ingress chain: %v", err)
+ }
+ }
+
+ if !iptables.Exists(iptables.Filter, ingressChain, "-j", "RETURN") {
+ if err := iptables.RawCombinedOutput("-A", ingressChain, "-j", "RETURN"); err != nil {
+ return fmt.Errorf("failed to add return rule to filter table ingress chain: %v", err)
+ }
+ }
+
+ for _, chain := range []string{"OUTPUT", "PREROUTING"} {
+ if !iptables.Exists(iptables.Nat, chain, "-m", "addrtype", "--dst-type", "LOCAL", "-j", ingressChain) {
+ if err := iptables.RawCombinedOutput("-t", "nat", "-I", chain, "-m", "addrtype", "--dst-type", "LOCAL", "-j", ingressChain); err != nil {
+ return fmt.Errorf("failed to add jump rule in %s to ingress chain: %v", chain, err)
+ }
+ }
+ }
+
+ if !iptables.Exists(iptables.Filter, "FORWARD", "-j", ingressChain) {
+ if err := iptables.RawCombinedOutput("-I", "FORWARD", "-j", ingressChain); err != nil {
+ return fmt.Errorf("failed to add jump rule to %s in filter table forward chain: %v", ingressChain, err)
+ }
+ }
+
+ oifName, err := findOIFName(gwIP)
+ if err != nil {
+ return fmt.Errorf("failed to find gateway bridge interface name for %s: %v", gwIP, err)
+ }
+
+ path := filepath.Join("/proc/sys/net/ipv4/conf", oifName, "route_localnet")
+ if err := ioutil.WriteFile(path, []byte{'1', '\n'}, 0644); err != nil {
+ return fmt.Errorf("could not write to %s: %v", path, err)
+ }
+
+ ruleArgs := strings.Fields(fmt.Sprintf("-m addrtype --src-type LOCAL -o %s -j MASQUERADE", oifName))
+ if !iptables.Exists(iptables.Nat, "POSTROUTING", ruleArgs...) {
+ if err := iptables.RawCombinedOutput(append([]string{"-t", "nat", "-I", "POSTROUTING"}, ruleArgs...)...); err != nil {
+ return fmt.Errorf("failed to add ingress localhost POSTROUTING rule for %s: %v", oifName, err)
+ }
+ }
+ }
+
+ for _, iPort := range ingressPorts {
+ if iptables.ExistChain(ingressChain, iptables.Nat) {
+ rule := strings.Fields(fmt.Sprintf("-t nat %s %s -p %s --dport %d -j DNAT --to-destination %s:%d",
+ addDelOpt, ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, gwIP, iPort.PublishedPort))
+ if err := iptables.RawCombinedOutput(rule...); err != nil {
+ errStr := fmt.Sprintf("setting up rule failed, %v: %v", rule, err)
+ if !isDelete {
+ return fmt.Errorf("%s", errStr)
+ }
+
+ logrus.Infof("%s", errStr)
+ }
+ }
+
+ // Filter table rules to allow a published service to be accessible in the local node from..
+ // 1) service tasks attached to other networks
+ // 2) unmanaged containers on bridge networks
+ rule := strings.Fields(fmt.Sprintf("%s %s -m state -p %s --sport %d --state ESTABLISHED,RELATED -j ACCEPT",
+ addDelOpt, ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort))
+ if err := iptables.RawCombinedOutput(rule...); err != nil {
+ errStr := fmt.Sprintf("setting up rule failed, %v: %v", rule, err)
+ if !isDelete {
+ return fmt.Errorf("%s", errStr)
+ }
+ logrus.Warnf("%s", errStr)
+ }
+
+ rule = strings.Fields(fmt.Sprintf("%s %s -p %s --dport %d -j ACCEPT",
+ addDelOpt, ingressChain, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort))
+ if err := iptables.RawCombinedOutput(rule...); err != nil {
+ errStr := fmt.Sprintf("setting up rule failed, %v: %v", rule, err)
+ if !isDelete {
+ return fmt.Errorf("%s", errStr)
+ }
+
+ logrus.Warnf("%s", errStr)
+ }
+
+ if err := plumbProxy(iPort, isDelete); err != nil {
+ logrus.Warnf("failed to create proxy for port %d: %v", iPort.PublishedPort, err)
+ }
+ }
+
+ return nil
+}
+
+// In the filter table FORWARD chain first rule should be to jump to INGRESS-CHAIN
+// This chain has the rules to allow access to the published ports for swarm tasks
+// from local bridge networks and docker_gwbridge (ie:taks on other swarm netwroks)
+func arrangeIngressFilterRule() {
+ if iptables.ExistChain(ingressChain, iptables.Filter) {
+ if iptables.Exists(iptables.Filter, "FORWARD", "-j", ingressChain) {
+ if err := iptables.RawCombinedOutput("-D", "FORWARD", "-j", ingressChain); err != nil {
+ logrus.Warnf("failed to delete jump rule to ingressChain in filter table: %v", err)
+ }
+ }
+ if err := iptables.RawCombinedOutput("-I", "FORWARD", "-j", ingressChain); err != nil {
+ logrus.Warnf("failed to add jump rule to ingressChain in filter table: %v", err)
+ }
+ }
+}
+
+func findOIFName(ip net.IP) (string, error) {
+ nlh := ns.NlHandle()
+
+ routes, err := nlh.RouteGet(ip)
+ if err != nil {
+ return "", err
+ }
+
+ if len(routes) == 0 {
+ return "", fmt.Errorf("no route to %s", ip)
+ }
+
+ // Pick the first route(typically there is only one route). We
+ // don't support multipath.
+ link, err := nlh.LinkByIndex(routes[0].LinkIndex)
+ if err != nil {
+ return "", err
+ }
+
+ return link.Attrs().Name, nil
+}
+
+func plumbProxy(iPort *PortConfig, isDelete bool) error {
+ var (
+ err error
+ l io.Closer
+ )
+
+ portSpec := fmt.Sprintf("%d/%s", iPort.PublishedPort, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]))
+ if isDelete {
+ ingressProxyMu.Lock()
+ if listener, ok := ingressProxyTbl[portSpec]; ok {
+ if listener != nil {
+ listener.Close()
+ }
+ }
+ ingressProxyMu.Unlock()
+
+ return nil
+ }
+
+ switch iPort.Protocol {
+ case ProtocolTCP:
+ l, err = net.ListenTCP("tcp", &net.TCPAddr{Port: int(iPort.PublishedPort)})
+ case ProtocolUDP:
+ l, err = net.ListenUDP("udp", &net.UDPAddr{Port: int(iPort.PublishedPort)})
+ }
+
+ if err != nil {
+ return err
+ }
+
+ ingressProxyMu.Lock()
+ ingressProxyTbl[portSpec] = l
+ ingressProxyMu.Unlock()
+
+ return nil
+}
+
+func writePortsToFile(ports []*PortConfig) (string, error) {
+ f, err := ioutil.TempFile("", "port_configs")
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+
+ buf, _ := proto.Marshal(&EndpointRecord{
+ IngressPorts: ports,
+ })
+
+ n, err := f.Write(buf)
+ if err != nil {
+ return "", err
+ }
+
+ if n < len(buf) {
+ return "", io.ErrShortWrite
+ }
+
+ return f.Name(), nil
+}
+
+func readPortsFromFile(fileName string) ([]*PortConfig, error) {
+ buf, err := ioutil.ReadFile(fileName)
+ if err != nil {
+ return nil, err
+ }
+
+ var epRec EndpointRecord
+ err = proto.Unmarshal(buf, &epRec)
+ if err != nil {
+ return nil, err
+ }
+
+ return epRec.IngressPorts, nil
+}
+
+// Invoke fwmarker reexec routine to mark vip destined packets with
+// the passed firewall mark.
+func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, eIP *net.IPNet, isDelete bool) error {
+ var ingressPortsFile string
+
+ if len(ingressPorts) != 0 {
+ var err error
+ ingressPortsFile, err = writePortsToFile(ingressPorts)
+ if err != nil {
+ return err
+ }
+
+ defer os.Remove(ingressPortsFile)
+ }
+
+ addDelOpt := "-A"
+ if isDelete {
+ addDelOpt = "-D"
+ }
+
+ cmd := &exec.Cmd{
+ Path: reexec.Self(),
+ Args: append([]string{"fwmarker"}, path, vip.String(), fmt.Sprintf("%d", fwMark), addDelOpt, ingressPortsFile, eIP.String()),
+ Stdout: os.Stdout,
+ Stderr: os.Stderr,
+ }
+
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("reexec failed: %v", err)
+ }
+
+ return nil
+}
+
+// Firewall marker reexec function.
+func fwMarker() {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+
+ if len(os.Args) < 7 {
+ logrus.Error("invalid number of arguments..")
+ os.Exit(1)
+ }
+
+ var ingressPorts []*PortConfig
+ if os.Args[5] != "" {
+ var err error
+ ingressPorts, err = readPortsFromFile(os.Args[5])
+ if err != nil {
+ logrus.Errorf("Failed reading ingress ports file: %v", err)
+ os.Exit(6)
+ }
+ }
+
+ vip := os.Args[2]
+ fwMark, err := strconv.ParseUint(os.Args[3], 10, 32)
+ if err != nil {
+ logrus.Errorf("bad fwmark value(%s) passed: %v", os.Args[3], err)
+ os.Exit(2)
+ }
+ addDelOpt := os.Args[4]
+
+ rules := [][]string{}
+ for _, iPort := range ingressPorts {
+ rule := strings.Fields(fmt.Sprintf("-t mangle %s PREROUTING -p %s --dport %d -j MARK --set-mark %d",
+ addDelOpt, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, fwMark))
+ rules = append(rules, rule)
+ }
+
+ ns, err := netns.GetFromPath(os.Args[1])
+ if err != nil {
+ logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
+ os.Exit(3)
+ }
+ defer ns.Close()
+
+ if err := netns.Set(ns); err != nil {
+ logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err)
+ os.Exit(4)
+ }
+
+ if addDelOpt == "-A" {
+ eIP, subnet, err := net.ParseCIDR(os.Args[6])
+ if err != nil {
+ logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[6], err)
+ os.Exit(9)
+ }
+
+ ruleParams := strings.Fields(fmt.Sprintf("-m ipvs --ipvs -d %s -j SNAT --to-source %s", subnet, eIP))
+ if !iptables.Exists("nat", "POSTROUTING", ruleParams...) {
+ rule := append(strings.Fields("-t nat -A POSTROUTING"), ruleParams...)
+ rules = append(rules, rule)
+
+ err := ioutil.WriteFile("/proc/sys/net/ipv4/vs/conntrack", []byte{'1', '\n'}, 0644)
+ if err != nil {
+ logrus.Errorf("Failed to write to /proc/sys/net/ipv4/vs/conntrack: %v", err)
+ os.Exit(8)
+ }
+ }
+ }
+
+ rule := strings.Fields(fmt.Sprintf("-t mangle %s OUTPUT -d %s/32 -j MARK --set-mark %d", addDelOpt, vip, fwMark))
+ rules = append(rules, rule)
+
+ rule = strings.Fields(fmt.Sprintf("-t nat %s OUTPUT -p icmp --icmp echo-request -d %s -j DNAT --to 127.0.0.1", addDelOpt, vip))
+ rules = append(rules, rule)
+
+ for _, rule := range rules {
+ if err := iptables.RawCombinedOutputNative(rule...); err != nil {
+ logrus.Errorf("setting up rule failed, %v: %v", rule, err)
+ os.Exit(5)
+ }
+ }
+}
+
+func addRedirectRules(path string, eIP *net.IPNet, ingressPorts []*PortConfig) error {
+ var ingressPortsFile string
+
+ if len(ingressPorts) != 0 {
+ var err error
+ ingressPortsFile, err = writePortsToFile(ingressPorts)
+ if err != nil {
+ return err
+ }
+ defer os.Remove(ingressPortsFile)
+ }
+
+ cmd := &exec.Cmd{
+ Path: reexec.Self(),
+ Args: append([]string{"redirecter"}, path, eIP.String(), ingressPortsFile),
+ Stdout: os.Stdout,
+ Stderr: os.Stderr,
+ }
+
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("reexec failed: %v", err)
+ }
+
+ return nil
+}
+
+// Redirecter reexec function.
+func redirecter() {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+
+ if len(os.Args) < 4 {
+ logrus.Error("invalid number of arguments..")
+ os.Exit(1)
+ }
+
+ var ingressPorts []*PortConfig
+ if os.Args[3] != "" {
+ var err error
+ ingressPorts, err = readPortsFromFile(os.Args[3])
+ if err != nil {
+ logrus.Errorf("Failed reading ingress ports file: %v", err)
+ os.Exit(2)
+ }
+ }
+
+ eIP, _, err := net.ParseCIDR(os.Args[2])
+ if err != nil {
+ logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[2], err)
+ os.Exit(3)
+ }
+
+ rules := [][]string{}
+ for _, iPort := range ingressPorts {
+ rule := strings.Fields(fmt.Sprintf("-t nat -A PREROUTING -d %s -p %s --dport %d -j REDIRECT --to-port %d",
+ eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, iPort.TargetPort))
+ rules = append(rules, rule)
+ // Allow only incoming connections to exposed ports
+ iRule := strings.Fields(fmt.Sprintf("-I INPUT -d %s -p %s --dport %d -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT",
+ eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.TargetPort))
+ rules = append(rules, iRule)
+ // Allow only outgoing connections from exposed ports
+ oRule := strings.Fields(fmt.Sprintf("-I OUTPUT -s %s -p %s --sport %d -m conntrack --ctstate ESTABLISHED -j ACCEPT",
+ eIP.String(), strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.TargetPort))
+ rules = append(rules, oRule)
+ }
+
+ ns, err := netns.GetFromPath(os.Args[1])
+ if err != nil {
+ logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
+ os.Exit(4)
+ }
+ defer ns.Close()
+
+ if err := netns.Set(ns); err != nil {
+ logrus.Errorf("setting into container net ns %v failed, %v", os.Args[1], err)
+ os.Exit(5)
+ }
+
+ for _, rule := range rules {
+ if err := iptables.RawCombinedOutputNative(rule...); err != nil {
+ logrus.Errorf("setting up rule failed, %v: %v", rule, err)
+ os.Exit(6)
+ }
+ }
+
+ if len(ingressPorts) == 0 {
+ return
+ }
+
+ // Ensure blocking rules for anything else in/to ingress network
+ for _, rule := range [][]string{
+ {"-d", eIP.String(), "-p", "udp", "-j", "DROP"},
+ {"-d", eIP.String(), "-p", "tcp", "-j", "DROP"},
+ } {
+ if !iptables.ExistsNative(iptables.Filter, "INPUT", rule...) {
+ if err := iptables.RawCombinedOutputNative(append([]string{"-A", "INPUT"}, rule...)...); err != nil {
+ logrus.Errorf("setting up rule failed, %v: %v", rule, err)
+ os.Exit(7)
+ }
+ }
+ rule[0] = "-s"
+ if !iptables.ExistsNative(iptables.Filter, "OUTPUT", rule...) {
+ if err := iptables.RawCombinedOutputNative(append([]string{"-A", "OUTPUT"}, rule...)...); err != nil {
+ logrus.Errorf("setting up rule failed, %v: %v", rule, err)
+ os.Exit(8)
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/docker/libnetwork/service_unsupported.go b/vendor/github.com/docker/libnetwork/service_unsupported.go
new file mode 100644
index 0000000..37b9828
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/service_unsupported.go
@@ -0,0 +1,25 @@
+// +build !linux,!windows
+
+package libnetwork
+
+import (
+ "fmt"
+ "net"
+)
+
+func (c *controller) cleanupServiceBindings(nid string) {
+}
+
+func (c *controller) addServiceBinding(name, sid, nid, eid string, vip net.IP, ingressPorts []*PortConfig, aliases []string, ip net.IP) error {
+ return fmt.Errorf("not supported")
+}
+
+func (c *controller) rmServiceBinding(name, sid, nid, eid string, vip net.IP, ingressPorts []*PortConfig, aliases []string, ip net.IP) error {
+ return fmt.Errorf("not supported")
+}
+
+func (sb *sandbox) populateLoadbalancers(ep *endpoint) {
+}
+
+func arrangeIngressFilterRule() {
+}
diff --git a/vendor/github.com/docker/libnetwork/service_windows.go b/vendor/github.com/docker/libnetwork/service_windows.go
new file mode 100644
index 0000000..6fe521e
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/service_windows.go
@@ -0,0 +1,15 @@
+package libnetwork
+
+import "net"
+
+func (n *network) addLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*PortConfig) {
+}
+
+func (n *network) rmLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, rmService bool) {
+}
+
+func (sb *sandbox) populateLoadbalancers(ep *endpoint) {
+}
+
+func arrangeIngressFilterRule() {
+}
diff --git a/vendor/github.com/docker/libnetwork/store.go b/vendor/github.com/docker/libnetwork/store.go
new file mode 100644
index 0000000..4e6ced2
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/store.go
@@ -0,0 +1,489 @@
+package libnetwork
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/libkv/store/boltdb"
+ "github.com/docker/libnetwork/datastore"
+)
+
+func registerKVStores() {
+ boltdb.Register()
+}
+
+func (c *controller) initScopedStore(scope string, scfg *datastore.ScopeCfg) error {
+ store, err := datastore.NewDataStore(scope, scfg)
+ if err != nil {
+ return err
+ }
+ c.Lock()
+ c.stores = append(c.stores, store)
+ c.Unlock()
+
+ return nil
+}
+
+func (c *controller) initStores() error {
+ registerKVStores()
+
+ c.Lock()
+ if c.cfg == nil {
+ c.Unlock()
+ return nil
+ }
+ scopeConfigs := c.cfg.Scopes
+ c.stores = nil
+ c.Unlock()
+
+ for scope, scfg := range scopeConfigs {
+ if err := c.initScopedStore(scope, scfg); err != nil {
+ return err
+ }
+ }
+
+ c.startWatch()
+ return nil
+}
+
+func (c *controller) closeStores() {
+ for _, store := range c.getStores() {
+ store.Close()
+ }
+}
+
+func (c *controller) getStore(scope string) datastore.DataStore {
+ c.Lock()
+ defer c.Unlock()
+
+ for _, store := range c.stores {
+ if store.Scope() == scope {
+ return store
+ }
+ }
+
+ return nil
+}
+
+func (c *controller) getStores() []datastore.DataStore {
+ c.Lock()
+ defer c.Unlock()
+
+ return c.stores
+}
+
+func (c *controller) getNetworkFromStore(nid string) (*network, error) {
+ for _, store := range c.getStores() {
+ n := &network{id: nid, ctrlr: c}
+ err := store.GetObject(datastore.Key(n.Key()...), n)
+ // Continue searching in the next store if the key is not found in this store
+ if err != nil {
+ if err != datastore.ErrKeyNotFound {
+ logrus.Debugf("could not find network %s: %v", nid, err)
+ }
+ continue
+ }
+
+ ec := &endpointCnt{n: n}
+ err = store.GetObject(datastore.Key(ec.Key()...), ec)
+ if err != nil && !n.inDelete {
+ return nil, fmt.Errorf("could not find endpoint count for network %s: %v", n.Name(), err)
+ }
+
+ n.epCnt = ec
+ if n.scope == "" {
+ n.scope = store.Scope()
+ }
+ return n, nil
+ }
+
+ return nil, fmt.Errorf("network %s not found", nid)
+}
+
+func (c *controller) getNetworksForScope(scope string) ([]*network, error) {
+ var nl []*network
+
+ store := c.getStore(scope)
+ if store == nil {
+ return nil, nil
+ }
+
+ kvol, err := store.List(datastore.Key(datastore.NetworkKeyPrefix),
+ &network{ctrlr: c})
+ if err != nil && err != datastore.ErrKeyNotFound {
+ return nil, fmt.Errorf("failed to get networks for scope %s: %v",
+ scope, err)
+ }
+
+ for _, kvo := range kvol {
+ n := kvo.(*network)
+ n.ctrlr = c
+
+ ec := &endpointCnt{n: n}
+ err = store.GetObject(datastore.Key(ec.Key()...), ec)
+ if err != nil && !n.inDelete {
+ logrus.Warnf("Could not find endpoint count key %s for network %s while listing: %v", datastore.Key(ec.Key()...), n.Name(), err)
+ continue
+ }
+
+ n.epCnt = ec
+ if n.scope == "" {
+ n.scope = scope
+ }
+ nl = append(nl, n)
+ }
+
+ return nl, nil
+}
+
+func (c *controller) getNetworksFromStore() ([]*network, error) {
+ var nl []*network
+
+ for _, store := range c.getStores() {
+ kvol, err := store.List(datastore.Key(datastore.NetworkKeyPrefix),
+ &network{ctrlr: c})
+ // Continue searching in the next store if no keys found in this store
+ if err != nil {
+ if err != datastore.ErrKeyNotFound {
+ logrus.Debugf("failed to get networks for scope %s: %v", store.Scope(), err)
+ }
+ continue
+ }
+
+ kvep, err := store.Map(datastore.Key(epCntKeyPrefix), &endpointCnt{})
+ if err != nil {
+ if err != datastore.ErrKeyNotFound {
+ logrus.Warnf("failed to get endpoint_count map for scope %s: %v", store.Scope(), err)
+ }
+ }
+
+ for _, kvo := range kvol {
+ n := kvo.(*network)
+ n.Lock()
+ n.ctrlr = c
+ ec := &endpointCnt{n: n}
+ // Trim the leading & trailing "/" to make it consistent across all stores
+ if val, ok := kvep[strings.Trim(datastore.Key(ec.Key()...), "/")]; ok {
+ ec = val.(*endpointCnt)
+ ec.n = n
+ n.epCnt = ec
+ }
+ if n.scope == "" {
+ n.scope = store.Scope()
+ }
+ n.Unlock()
+ nl = append(nl, n)
+ }
+ }
+
+ return nl, nil
+}
+
+func (n *network) getEndpointFromStore(eid string) (*endpoint, error) {
+ var errors []string
+ for _, store := range n.ctrlr.getStores() {
+ ep := &endpoint{id: eid, network: n}
+ err := store.GetObject(datastore.Key(ep.Key()...), ep)
+ // Continue searching in the next store if the key is not found in this store
+ if err != nil {
+ if err != datastore.ErrKeyNotFound {
+ errors = append(errors, fmt.Sprintf("{%s:%v}, ", store.Scope(), err))
+ logrus.Debugf("could not find endpoint %s in %s: %v", eid, store.Scope(), err)
+ }
+ continue
+ }
+ return ep, nil
+ }
+ return nil, fmt.Errorf("could not find endpoint %s: %v", eid, errors)
+}
+
+func (n *network) getEndpointsFromStore() ([]*endpoint, error) {
+ var epl []*endpoint
+
+ tmp := endpoint{network: n}
+ for _, store := range n.getController().getStores() {
+ kvol, err := store.List(datastore.Key(tmp.KeyPrefix()...), &endpoint{network: n})
+ // Continue searching in the next store if no keys found in this store
+ if err != nil {
+ if err != datastore.ErrKeyNotFound {
+ logrus.Debugf("failed to get endpoints for network %s scope %s: %v",
+ n.Name(), store.Scope(), err)
+ }
+ continue
+ }
+
+ for _, kvo := range kvol {
+ ep := kvo.(*endpoint)
+ epl = append(epl, ep)
+ }
+ }
+
+ return epl, nil
+}
+
+func (c *controller) updateToStore(kvObject datastore.KVObject) error {
+ cs := c.getStore(kvObject.DataScope())
+ if cs == nil {
+ return ErrDataStoreNotInitialized(kvObject.DataScope())
+ }
+
+ if err := cs.PutObjectAtomic(kvObject); err != nil {
+ if err == datastore.ErrKeyModified {
+ return err
+ }
+ return fmt.Errorf("failed to update store for object type %T: %v", kvObject, err)
+ }
+
+ return nil
+}
+
+func (c *controller) deleteFromStore(kvObject datastore.KVObject) error {
+ cs := c.getStore(kvObject.DataScope())
+ if cs == nil {
+ return ErrDataStoreNotInitialized(kvObject.DataScope())
+ }
+
+retry:
+ if err := cs.DeleteObjectAtomic(kvObject); err != nil {
+ if err == datastore.ErrKeyModified {
+ if err := cs.GetObject(datastore.Key(kvObject.Key()...), kvObject); err != nil {
+ return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err)
+ }
+ goto retry
+ }
+ return err
+ }
+
+ return nil
+}
+
+type netWatch struct {
+ localEps map[string]*endpoint
+ remoteEps map[string]*endpoint
+ stopCh chan struct{}
+}
+
+func (c *controller) getLocalEps(nw *netWatch) []*endpoint {
+ c.Lock()
+ defer c.Unlock()
+
+ var epl []*endpoint
+ for _, ep := range nw.localEps {
+ epl = append(epl, ep)
+ }
+
+ return epl
+}
+
+func (c *controller) watchSvcRecord(ep *endpoint) {
+ c.watchCh <- ep
+}
+
+func (c *controller) unWatchSvcRecord(ep *endpoint) {
+ c.unWatchCh <- ep
+}
+
+func (c *controller) networkWatchLoop(nw *netWatch, ep *endpoint, ecCh <-chan datastore.KVObject) {
+ for {
+ select {
+ case <-nw.stopCh:
+ return
+ case o := <-ecCh:
+ ec := o.(*endpointCnt)
+
+ epl, err := ec.n.getEndpointsFromStore()
+ if err != nil {
+ break
+ }
+
+ c.Lock()
+ var addEp []*endpoint
+
+ delEpMap := make(map[string]*endpoint)
+ renameEpMap := make(map[string]bool)
+ for k, v := range nw.remoteEps {
+ delEpMap[k] = v
+ }
+
+ for _, lEp := range epl {
+ if _, ok := nw.localEps[lEp.ID()]; ok {
+ continue
+ }
+
+ if ep, ok := nw.remoteEps[lEp.ID()]; ok {
+ // On a container rename EP ID will remain
+ // the same but the name will change. service
+ // records should reflect the change.
+ // Keep old EP entry in the delEpMap and add
+ // EP from the store (which has the new name)
+ // into the new list
+ if lEp.name == ep.name {
+ delete(delEpMap, lEp.ID())
+ continue
+ }
+ renameEpMap[lEp.ID()] = true
+ }
+ nw.remoteEps[lEp.ID()] = lEp
+ addEp = append(addEp, lEp)
+ }
+
+ // EPs whose name are to be deleted from the svc records
+ // should also be removed from nw's remote EP list, except
+ // the ones that are getting renamed.
+ for _, lEp := range delEpMap {
+ if !renameEpMap[lEp.ID()] {
+ delete(nw.remoteEps, lEp.ID())
+ }
+ }
+ c.Unlock()
+
+ for _, lEp := range delEpMap {
+ ep.getNetwork().updateSvcRecord(lEp, c.getLocalEps(nw), false)
+
+ }
+ for _, lEp := range addEp {
+ ep.getNetwork().updateSvcRecord(lEp, c.getLocalEps(nw), true)
+ }
+ }
+ }
+}
+
+func (c *controller) processEndpointCreate(nmap map[string]*netWatch, ep *endpoint) {
+ n := ep.getNetwork()
+ if !c.isDistributedControl() && n.Scope() == datastore.SwarmScope && n.driverIsMultihost() {
+ return
+ }
+
+ c.Lock()
+ nw, ok := nmap[n.ID()]
+ c.Unlock()
+
+ if ok {
+ // Update the svc db for the local endpoint join right away
+ n.updateSvcRecord(ep, c.getLocalEps(nw), true)
+
+ c.Lock()
+ nw.localEps[ep.ID()] = ep
+
+ // If we had learned that from the kv store remove it
+ // from remote ep list now that we know that this is
+ // indeed a local endpoint
+ delete(nw.remoteEps, ep.ID())
+ c.Unlock()
+ return
+ }
+
+ nw = &netWatch{
+ localEps: make(map[string]*endpoint),
+ remoteEps: make(map[string]*endpoint),
+ }
+
+ // Update the svc db for the local endpoint join right away
+ // Do this before adding this ep to localEps so that we don't
+ // try to update this ep's container's svc records
+ n.updateSvcRecord(ep, c.getLocalEps(nw), true)
+
+ c.Lock()
+ nw.localEps[ep.ID()] = ep
+ nmap[n.ID()] = nw
+ nw.stopCh = make(chan struct{})
+ c.Unlock()
+
+ store := c.getStore(n.DataScope())
+ if store == nil {
+ return
+ }
+
+ if !store.Watchable() {
+ return
+ }
+
+ ch, err := store.Watch(n.getEpCnt(), nw.stopCh)
+ if err != nil {
+ logrus.Warnf("Error creating watch for network: %v", err)
+ return
+ }
+
+ go c.networkWatchLoop(nw, ep, ch)
+}
+
+func (c *controller) processEndpointDelete(nmap map[string]*netWatch, ep *endpoint) {
+ n := ep.getNetwork()
+ if !c.isDistributedControl() && n.Scope() == datastore.SwarmScope && n.driverIsMultihost() {
+ return
+ }
+
+ c.Lock()
+ nw, ok := nmap[n.ID()]
+
+ if ok {
+ delete(nw.localEps, ep.ID())
+ c.Unlock()
+
+ // Update the svc db about local endpoint leave right away
+ // Do this after we remove this ep from localEps so that we
+ // don't try to remove this svc record from this ep's container.
+ n.updateSvcRecord(ep, c.getLocalEps(nw), false)
+
+ c.Lock()
+ if len(nw.localEps) == 0 {
+ close(nw.stopCh)
+
+ // This is the last container going away for the network. Destroy
+ // this network's svc db entry
+ delete(c.svcRecords, n.ID())
+
+ delete(nmap, n.ID())
+ }
+ }
+ c.Unlock()
+}
+
+func (c *controller) watchLoop() {
+ for {
+ select {
+ case ep := <-c.watchCh:
+ c.processEndpointCreate(c.nmap, ep)
+ case ep := <-c.unWatchCh:
+ c.processEndpointDelete(c.nmap, ep)
+ }
+ }
+}
+
+func (c *controller) startWatch() {
+ if c.watchCh != nil {
+ return
+ }
+ c.watchCh = make(chan *endpoint)
+ c.unWatchCh = make(chan *endpoint)
+ c.nmap = make(map[string]*netWatch)
+
+ go c.watchLoop()
+}
+
+func (c *controller) networkCleanup() {
+ networks, err := c.getNetworksFromStore()
+ if err != nil {
+ logrus.Warnf("Could not retrieve networks from store(s) during network cleanup: %v", err)
+ return
+ }
+
+ for _, n := range networks {
+ if n.inDelete {
+ logrus.Infof("Removing stale network %s (%s)", n.Name(), n.ID())
+ if err := n.delete(true); err != nil {
+ logrus.Debugf("Error while removing stale network: %v", err)
+ }
+ }
+ }
+}
+
+var populateSpecial NetworkWalker = func(nw Network) bool {
+ if n := nw.(*network); n.hasSpecialDriver() && !n.ConfigOnly() {
+ if err := n.getController().addNetwork(n); err != nil {
+ logrus.Warnf("Failed to populate network %q with driver %q", nw.Name(), nw.Type())
+ }
+ }
+ return false
+}
diff --git a/vendor/github.com/docker/libnetwork/types/types.go b/vendor/github.com/docker/libnetwork/types/types.go
new file mode 100644
index 0000000..da113e2
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/types/types.go
@@ -0,0 +1,636 @@
+// Package types contains types that are common across libnetwork project
+package types
+
+import (
+ "bytes"
+ "fmt"
+ "net"
+ "strconv"
+ "strings"
+)
+
+// constants for the IP address type
+const (
+ IP = iota // IPv4 and IPv6
+ IPv4
+ IPv6
+)
+
+// EncryptionKey is the libnetwork representation of the key distributed by the lead
+// manager.
+type EncryptionKey struct {
+ Subsystem string
+ Algorithm int32
+ Key []byte
+ LamportTime uint64
+}
+
+// UUID represents a globally unique ID of various resources like network and endpoint
+type UUID string
+
+// QosPolicy represents a quality of service policy on an endpoint
+type QosPolicy struct {
+ MaxEgressBandwidth uint64
+}
+
+// TransportPort represents a local Layer 4 endpoint
+type TransportPort struct {
+ Proto Protocol
+ Port uint16
+}
+
+// Equal checks if this instance of Transportport is equal to the passed one
+func (t *TransportPort) Equal(o *TransportPort) bool {
+ if t == o {
+ return true
+ }
+
+ if o == nil {
+ return false
+ }
+
+ if t.Proto != o.Proto || t.Port != o.Port {
+ return false
+ }
+
+ return true
+}
+
+// GetCopy returns a copy of this TransportPort structure instance
+func (t *TransportPort) GetCopy() TransportPort {
+ return TransportPort{Proto: t.Proto, Port: t.Port}
+}
+
+// String returns the TransportPort structure in string form
+func (t *TransportPort) String() string {
+ return fmt.Sprintf("%s/%d", t.Proto.String(), t.Port)
+}
+
+// FromString reads the TransportPort structure from string
+func (t *TransportPort) FromString(s string) error {
+ ps := strings.Split(s, "/")
+ if len(ps) == 2 {
+ t.Proto = ParseProtocol(ps[0])
+ if p, err := strconv.ParseUint(ps[1], 10, 16); err == nil {
+ t.Port = uint16(p)
+ return nil
+ }
+ }
+ return BadRequestErrorf("invalid format for transport port: %s", s)
+}
+
+// PortBinding represents a port binding between the container and the host
+type PortBinding struct {
+ Proto Protocol
+ IP net.IP
+ Port uint16
+ HostIP net.IP
+ HostPort uint16
+ HostPortEnd uint16
+}
+
+// HostAddr returns the host side transport address
+func (p PortBinding) HostAddr() (net.Addr, error) {
+ switch p.Proto {
+ case UDP:
+ return &net.UDPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
+ case TCP:
+ return &net.TCPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
+ default:
+ return nil, ErrInvalidProtocolBinding(p.Proto.String())
+ }
+}
+
+// ContainerAddr returns the container side transport address
+func (p PortBinding) ContainerAddr() (net.Addr, error) {
+ switch p.Proto {
+ case UDP:
+ return &net.UDPAddr{IP: p.IP, Port: int(p.Port)}, nil
+ case TCP:
+ return &net.TCPAddr{IP: p.IP, Port: int(p.Port)}, nil
+ default:
+ return nil, ErrInvalidProtocolBinding(p.Proto.String())
+ }
+}
+
+// GetCopy returns a copy of this PortBinding structure instance
+func (p *PortBinding) GetCopy() PortBinding {
+ return PortBinding{
+ Proto: p.Proto,
+ IP: GetIPCopy(p.IP),
+ Port: p.Port,
+ HostIP: GetIPCopy(p.HostIP),
+ HostPort: p.HostPort,
+ HostPortEnd: p.HostPortEnd,
+ }
+}
+
+// String returns the PortBinding structure in string form
+func (p *PortBinding) String() string {
+ ret := fmt.Sprintf("%s/", p.Proto)
+ if p.IP != nil {
+ ret = fmt.Sprintf("%s%s", ret, p.IP.String())
+ }
+ ret = fmt.Sprintf("%s:%d/", ret, p.Port)
+ if p.HostIP != nil {
+ ret = fmt.Sprintf("%s%s", ret, p.HostIP.String())
+ }
+ ret = fmt.Sprintf("%s:%d", ret, p.HostPort)
+ return ret
+}
+
+// FromString reads the TransportPort structure from string
+func (p *PortBinding) FromString(s string) error {
+ ps := strings.Split(s, "/")
+ if len(ps) != 3 {
+ return BadRequestErrorf("invalid format for port binding: %s", s)
+ }
+
+ p.Proto = ParseProtocol(ps[0])
+
+ var err error
+ if p.IP, p.Port, err = parseIPPort(ps[1]); err != nil {
+ return BadRequestErrorf("failed to parse Container IP/Port in port binding: %s", err.Error())
+ }
+
+ if p.HostIP, p.HostPort, err = parseIPPort(ps[2]); err != nil {
+ return BadRequestErrorf("failed to parse Host IP/Port in port binding: %s", err.Error())
+ }
+
+ return nil
+}
+
+func parseIPPort(s string) (net.IP, uint16, error) {
+ pp := strings.Split(s, ":")
+ if len(pp) != 2 {
+ return nil, 0, BadRequestErrorf("invalid format: %s", s)
+ }
+
+ var ip net.IP
+ if pp[0] != "" {
+ if ip = net.ParseIP(pp[0]); ip == nil {
+ return nil, 0, BadRequestErrorf("invalid ip: %s", pp[0])
+ }
+ }
+
+ port, err := strconv.ParseUint(pp[1], 10, 16)
+ if err != nil {
+ return nil, 0, BadRequestErrorf("invalid port: %s", pp[1])
+ }
+
+ return ip, uint16(port), nil
+}
+
+// Equal checks if this instance of PortBinding is equal to the passed one
+func (p *PortBinding) Equal(o *PortBinding) bool {
+ if p == o {
+ return true
+ }
+
+ if o == nil {
+ return false
+ }
+
+ if p.Proto != o.Proto || p.Port != o.Port ||
+ p.HostPort != o.HostPort || p.HostPortEnd != o.HostPortEnd {
+ return false
+ }
+
+ if p.IP != nil {
+ if !p.IP.Equal(o.IP) {
+ return false
+ }
+ } else {
+ if o.IP != nil {
+ return false
+ }
+ }
+
+ if p.HostIP != nil {
+ if !p.HostIP.Equal(o.HostIP) {
+ return false
+ }
+ } else {
+ if o.HostIP != nil {
+ return false
+ }
+ }
+
+ return true
+}
+
+// ErrInvalidProtocolBinding is returned when the port binding protocol is not valid.
+type ErrInvalidProtocolBinding string
+
+func (ipb ErrInvalidProtocolBinding) Error() string {
+ return fmt.Sprintf("invalid transport protocol: %s", string(ipb))
+}
+
+const (
+ // ICMP is for the ICMP ip protocol
+ ICMP = 1
+ // TCP is for the TCP ip protocol
+ TCP = 6
+ // UDP is for the UDP ip protocol
+ UDP = 17
+)
+
+// Protocol represents an IP protocol number
+type Protocol uint8
+
+func (p Protocol) String() string {
+ switch p {
+ case ICMP:
+ return "icmp"
+ case TCP:
+ return "tcp"
+ case UDP:
+ return "udp"
+ default:
+ return fmt.Sprintf("%d", p)
+ }
+}
+
+// ParseProtocol returns the respective Protocol type for the passed string
+func ParseProtocol(s string) Protocol {
+ switch strings.ToLower(s) {
+ case "icmp":
+ return ICMP
+ case "udp":
+ return UDP
+ case "tcp":
+ return TCP
+ default:
+ return 0
+ }
+}
+
+// GetMacCopy returns a copy of the passed MAC address
+func GetMacCopy(from net.HardwareAddr) net.HardwareAddr {
+ if from == nil {
+ return nil
+ }
+ to := make(net.HardwareAddr, len(from))
+ copy(to, from)
+ return to
+}
+
+// GetIPCopy returns a copy of the passed IP address
+func GetIPCopy(from net.IP) net.IP {
+ if from == nil {
+ return nil
+ }
+ to := make(net.IP, len(from))
+ copy(to, from)
+ return to
+}
+
+// GetIPNetCopy returns a copy of the passed IP Network
+func GetIPNetCopy(from *net.IPNet) *net.IPNet {
+ if from == nil {
+ return nil
+ }
+ bm := make(net.IPMask, len(from.Mask))
+ copy(bm, from.Mask)
+ return &net.IPNet{IP: GetIPCopy(from.IP), Mask: bm}
+}
+
+// GetIPNetCanonical returns the canonical form for the passed network
+func GetIPNetCanonical(nw *net.IPNet) *net.IPNet {
+ if nw == nil {
+ return nil
+ }
+ c := GetIPNetCopy(nw)
+ c.IP = c.IP.Mask(nw.Mask)
+ return c
+}
+
+// CompareIPNet returns equal if the two IP Networks are equal
+func CompareIPNet(a, b *net.IPNet) bool {
+ if a == b {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask)
+}
+
+// GetMinimalIP returns the address in its shortest form
+func GetMinimalIP(ip net.IP) net.IP {
+ if ip != nil && ip.To4() != nil {
+ return ip.To4()
+ }
+ return ip
+}
+
+// GetMinimalIPNet returns a copy of the passed IP Network with congruent ip and mask notation
+func GetMinimalIPNet(nw *net.IPNet) *net.IPNet {
+ if nw == nil {
+ return nil
+ }
+ if len(nw.IP) == 16 && nw.IP.To4() != nil {
+ m := nw.Mask
+ if len(m) == 16 {
+ m = m[12:16]
+ }
+ return &net.IPNet{IP: nw.IP.To4(), Mask: m}
+ }
+ return nw
+}
+
+// IsIPNetValid returns true if the ipnet is a valid network/mask
+// combination. Otherwise returns false.
+func IsIPNetValid(nw *net.IPNet) bool {
+ return nw.String() != "0.0.0.0/0"
+}
+
+var v4inV6MaskPrefix = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
+
+// compareIPMask checks if the passed ip and mask are semantically compatible.
+// It returns the byte indexes for the address and mask so that caller can
+// do bitwise operations without modifying address representation.
+func compareIPMask(ip net.IP, mask net.IPMask) (is int, ms int, err error) {
+ // Find the effective starting of address and mask
+ if len(ip) == net.IPv6len && ip.To4() != nil {
+ is = 12
+ }
+ if len(ip[is:]) == net.IPv4len && len(mask) == net.IPv6len && bytes.Equal(mask[:12], v4inV6MaskPrefix) {
+ ms = 12
+ }
+ // Check if address and mask are semantically compatible
+ if len(ip[is:]) != len(mask[ms:]) {
+ err = fmt.Errorf("ip and mask are not compatible: (%#v, %#v)", ip, mask)
+ }
+ return
+}
+
+// GetHostPartIP returns the host portion of the ip address identified by the mask.
+// IP address representation is not modified. If address and mask are not compatible
+// an error is returned.
+func GetHostPartIP(ip net.IP, mask net.IPMask) (net.IP, error) {
+ // Find the effective starting of address and mask
+ is, ms, err := compareIPMask(ip, mask)
+ if err != nil {
+ return nil, fmt.Errorf("cannot compute host portion ip address because %s", err)
+ }
+
+ // Compute host portion
+ out := GetIPCopy(ip)
+ for i := 0; i < len(mask[ms:]); i++ {
+ out[is+i] &= ^mask[ms+i]
+ }
+
+ return out, nil
+}
+
+// GetBroadcastIP returns the broadcast ip address for the passed network (ip and mask).
+// IP address representation is not modified. If address and mask are not compatible
+// an error is returned.
+func GetBroadcastIP(ip net.IP, mask net.IPMask) (net.IP, error) {
+ // Find the effective starting of address and mask
+ is, ms, err := compareIPMask(ip, mask)
+ if err != nil {
+ return nil, fmt.Errorf("cannot compute broadcast ip address because %s", err)
+ }
+
+ // Compute broadcast address
+ out := GetIPCopy(ip)
+ for i := 0; i < len(mask[ms:]); i++ {
+ out[is+i] |= ^mask[ms+i]
+ }
+
+ return out, nil
+}
+
+// ParseCIDR returns the *net.IPNet represented by the passed CIDR notation
+func ParseCIDR(cidr string) (n *net.IPNet, e error) {
+ var i net.IP
+ if i, n, e = net.ParseCIDR(cidr); e == nil {
+ n.IP = i
+ }
+ return
+}
+
+const (
+ // NEXTHOP indicates a StaticRoute with an IP next hop.
+ NEXTHOP = iota
+
+ // CONNECTED indicates a StaticRoute with an interface for directly connected peers.
+ CONNECTED
+)
+
+// StaticRoute is a statically-provisioned IP route.
+type StaticRoute struct {
+ Destination *net.IPNet
+
+ RouteType int // NEXT_HOP or CONNECTED
+
+ // NextHop will be resolved by the kernel (i.e. as a loose hop).
+ NextHop net.IP
+}
+
+// GetCopy returns a copy of this StaticRoute structure
+func (r *StaticRoute) GetCopy() *StaticRoute {
+ d := GetIPNetCopy(r.Destination)
+ nh := GetIPCopy(r.NextHop)
+ return &StaticRoute{Destination: d,
+ RouteType: r.RouteType,
+ NextHop: nh,
+ }
+}
+
+// InterfaceStatistics represents the interface's statistics
+type InterfaceStatistics struct {
+ RxBytes uint64
+ RxPackets uint64
+ RxErrors uint64
+ RxDropped uint64
+ TxBytes uint64
+ TxPackets uint64
+ TxErrors uint64
+ TxDropped uint64
+}
+
+func (is *InterfaceStatistics) String() string {
+ return fmt.Sprintf("\nRxBytes: %d, RxPackets: %d, RxErrors: %d, RxDropped: %d, TxBytes: %d, TxPackets: %d, TxErrors: %d, TxDropped: %d",
+ is.RxBytes, is.RxPackets, is.RxErrors, is.RxDropped, is.TxBytes, is.TxPackets, is.TxErrors, is.TxDropped)
+}
+
+/******************************
+ * Well-known Error Interfaces
+ ******************************/
+
+// MaskableError is an interface for errors which can be ignored by caller
+type MaskableError interface {
+ // Maskable makes implementer into MaskableError type
+ Maskable()
+}
+
+// RetryError is an interface for errors which might get resolved through retry
+type RetryError interface {
+ // Retry makes implementer into RetryError type
+ Retry()
+}
+
+// BadRequestError is an interface for errors originated by a bad request
+type BadRequestError interface {
+ // BadRequest makes implementer into BadRequestError type
+ BadRequest()
+}
+
+// NotFoundError is an interface for errors raised because a needed resource is not available
+type NotFoundError interface {
+ // NotFound makes implementer into NotFoundError type
+ NotFound()
+}
+
+// ForbiddenError is an interface for errors which denote a valid request that cannot be honored
+type ForbiddenError interface {
+ // Forbidden makes implementer into ForbiddenError type
+ Forbidden()
+}
+
+// NoServiceError is an interface for errors returned when the required service is not available
+type NoServiceError interface {
+ // NoService makes implementer into NoServiceError type
+ NoService()
+}
+
+// TimeoutError is an interface for errors raised because of timeout
+type TimeoutError interface {
+ // Timeout makes implementer into TimeoutError type
+ Timeout()
+}
+
+// NotImplementedError is an interface for errors raised because of requested functionality is not yet implemented
+type NotImplementedError interface {
+ // NotImplemented makes implementer into NotImplementedError type
+ NotImplemented()
+}
+
+// InternalError is an interface for errors raised because of an internal error
+type InternalError interface {
+ // Internal makes implementer into InternalError type
+ Internal()
+}
+
+/******************************
+ * Well-known Error Formatters
+ ******************************/
+
+// BadRequestErrorf creates an instance of BadRequestError
+func BadRequestErrorf(format string, params ...interface{}) error {
+ return badRequest(fmt.Sprintf(format, params...))
+}
+
+// NotFoundErrorf creates an instance of NotFoundError
+func NotFoundErrorf(format string, params ...interface{}) error {
+ return notFound(fmt.Sprintf(format, params...))
+}
+
+// ForbiddenErrorf creates an instance of ForbiddenError
+func ForbiddenErrorf(format string, params ...interface{}) error {
+ return forbidden(fmt.Sprintf(format, params...))
+}
+
+// NoServiceErrorf creates an instance of NoServiceError
+func NoServiceErrorf(format string, params ...interface{}) error {
+ return noService(fmt.Sprintf(format, params...))
+}
+
+// NotImplementedErrorf creates an instance of NotImplementedError
+func NotImplementedErrorf(format string, params ...interface{}) error {
+ return notImpl(fmt.Sprintf(format, params...))
+}
+
+// TimeoutErrorf creates an instance of TimeoutError
+func TimeoutErrorf(format string, params ...interface{}) error {
+ return timeout(fmt.Sprintf(format, params...))
+}
+
+// InternalErrorf creates an instance of InternalError
+func InternalErrorf(format string, params ...interface{}) error {
+ return internal(fmt.Sprintf(format, params...))
+}
+
+// InternalMaskableErrorf creates an instance of InternalError and MaskableError
+func InternalMaskableErrorf(format string, params ...interface{}) error {
+ return maskInternal(fmt.Sprintf(format, params...))
+}
+
+// RetryErrorf creates an instance of RetryError
+func RetryErrorf(format string, params ...interface{}) error {
+ return retry(fmt.Sprintf(format, params...))
+}
+
+/***********************
+ * Internal Error Types
+ ***********************/
+type badRequest string
+
+func (br badRequest) Error() string {
+ return string(br)
+}
+func (br badRequest) BadRequest() {}
+
+type maskBadRequest string
+
+type notFound string
+
+func (nf notFound) Error() string {
+ return string(nf)
+}
+func (nf notFound) NotFound() {}
+
+type forbidden string
+
+func (frb forbidden) Error() string {
+ return string(frb)
+}
+func (frb forbidden) Forbidden() {}
+
+type noService string
+
+func (ns noService) Error() string {
+ return string(ns)
+}
+func (ns noService) NoService() {}
+
+type maskNoService string
+
+type timeout string
+
+func (to timeout) Error() string {
+ return string(to)
+}
+func (to timeout) Timeout() {}
+
+type notImpl string
+
+func (ni notImpl) Error() string {
+ return string(ni)
+}
+func (ni notImpl) NotImplemented() {}
+
+type internal string
+
+func (nt internal) Error() string {
+ return string(nt)
+}
+func (nt internal) Internal() {}
+
+type maskInternal string
+
+func (mnt maskInternal) Error() string {
+ return string(mnt)
+}
+func (mnt maskInternal) Internal() {}
+func (mnt maskInternal) Maskable() {}
+
+type retry string
+
+func (r retry) Error() string {
+ return string(r)
+}
+func (r retry) Retry() {}
diff --git a/vendor/github.com/docker/libnetwork/vendor.conf b/vendor/github.com/docker/libnetwork/vendor.conf
new file mode 100644
index 0000000..203e1ce
--- /dev/null
+++ b/vendor/github.com/docker/libnetwork/vendor.conf
@@ -0,0 +1,44 @@
+github.com/Azure/go-ansiterm 04b7f292a41fcb5da32dda536c0807fc13e8351c
+github.com/BurntSushi/toml f706d00e3de6abe700c994cdd545a1a4915af060
+github.com/Microsoft/go-winio ce2922f643c8fd76b46cadc7f404a06282678b34
+github.com/Microsoft/hcsshim e439b7d2b63f036d3a50c93a9e0b154a0d50e788
+github.com/Sirupsen/logrus 4b6ea7319e214d98c938f12692336f7ca9348d6b
+github.com/armon/go-metrics eb0af217e5e9747e41dd5303755356b62d28e3ec
+github.com/armon/go-radix e39d623f12e8e41c7b5529e9a9dd67a1e2261f80
+github.com/boltdb/bolt c6ba97b89e0454fec9aa92e1d33a4e2c5fc1f631
+github.com/codegangsta/cli a65b733b303f0055f8d324d805f393cd3e7a7904
+github.com/coreos/etcd 925d1d74cec8c3b169c52fd4b2dc234a35934fce
+github.com/coreos/go-systemd b4a58d95188dd092ae20072bac14cece0e67c388
+github.com/deckarep/golang-set ef32fa3046d9f249d399f98ebaf9be944430fd1d
+
+github.com/docker/docker 9c96768eae4b3a65147b47a55c850c103ab8972d
+github.com/docker/go-connections 34b5052da6b11e27f5f2e357b38b571ddddd3928
+github.com/docker/go-events 2e7d352816128aa84f4d29b2a21d400133701a0d
+github.com/docker/go-units 8e2d4523730c73120e10d4652f36ad6010998f4e
+github.com/docker/libkv 1d8431073ae03cdaedb198a89722f3aab6d418ef
+
+github.com/godbus/dbus 5f6efc7ef2759c81b7ba876593971bfce311eab3
+github.com/gogo/protobuf 8d70fb3182befc465c4a1eac8ad4d38ff49778e2
+github.com/golang/protobuf f7137ae6b19afbfd61a94b746fda3b3fe0491874
+github.com/gorilla/context 215affda49addc4c8ef7e2534915df2c8c35c6cd
+github.com/gorilla/mux 8096f47503459bcc74d1f4c487b7e6e42e5746b5
+github.com/hashicorp/consul 954aec66231b79c161a4122b023fbcad13047f79
+github.com/hashicorp/go-msgpack 71c2886f5a673a35f909803f38ece5810165097b
+github.com/hashicorp/go-multierror 2167c8ec40776024589f483a6b836489e47e1049
+github.com/hashicorp/memberlist v0.1.0
+github.com/sean-/seed e2103e2c35297fb7e17febb81e49b312087a2372
+github.com/hashicorp/go-sockaddr acd314c5781ea706c710d9ea70069fd2e110d61d
+github.com/hashicorp/serf 598c54895cc5a7b1a24a398d635e8c0ea0959870
+github.com/mattn/go-shellwords 525bedee691b5a8df547cb5cf9f86b7fb1883e24
+github.com/miekg/dns d27455715200c7d3e321a1e5cadb27c9ee0b0f02
+github.com/opencontainers/runc ba1568de399395774ad84c2ace65937814c542ed
+github.com/samuel/go-zookeeper d0e0d8e11f318e000a8cc434616d69e329edc374
+github.com/seccomp/libseccomp-golang 1b506fc7c24eec5a3693cdcbed40d9c226cfc6a1
+github.com/stretchr/testify dab07ac62d4905d3e48d17dc549c684ac3b7c15a
+github.com/syndtr/gocapability 2c00daeb6c3b45114c80ac44119e7b8801fdd852
+github.com/ugorji/go f1f1a805ed361a0e078bb537e4ea78cd37dcf065
+github.com/vishvananda/netlink bd6d5de5ccef2d66b0a26177928d0d8895d7f969
+github.com/vishvananda/netns 604eaf189ee867d8c147fafc28def2394e878d25
+golang.org/x/net c427ad74c6d7a814201695e9ffde0c5d400a7674
+golang.org/x/sys 8f0908ab3b2457e2e15403d3697c9ef5cb4b57a9
+github.com/pkg/errors 839d9e913e063e28dfd0e6c7b7512793e0a48be9
diff --git a/vendor/github.com/docker/libtrust/LICENSE b/vendor/github.com/docker/libtrust/LICENSE
new file mode 100644
index 0000000..2744858
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2014 Docker, Inc.
+
+ 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/docker/libtrust/README.md b/vendor/github.com/docker/libtrust/README.md
new file mode 100644
index 0000000..8e7db38
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/README.md
@@ -0,0 +1,18 @@
+# libtrust
+
+Libtrust is library for managing authentication and authorization using public key cryptography.
+
+Authentication is handled using the identity attached to the public key.
+Libtrust provides multiple methods to prove possession of the private key associated with an identity.
+ - TLS x509 certificates
+ - Signature verification
+ - Key Challenge
+
+Authorization and access control is managed through a distributed trust graph.
+Trust servers are used as the authorities of the trust graph and allow caching portions of the graph for faster access.
+
+## Copyright and license
+
+Code and documentation copyright 2014 Docker, inc. Code released under the Apache 2.0 license.
+Docs released under Creative commons.
+
diff --git a/vendor/github.com/docker/libtrust/certificates.go b/vendor/github.com/docker/libtrust/certificates.go
new file mode 100644
index 0000000..3dcca33
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/certificates.go
@@ -0,0 +1,175 @@
+package libtrust
+
+import (
+ "crypto/rand"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/pem"
+ "fmt"
+ "io/ioutil"
+ "math/big"
+ "net"
+ "time"
+)
+
+type certTemplateInfo struct {
+ commonName string
+ domains []string
+ ipAddresses []net.IP
+ isCA bool
+ clientAuth bool
+ serverAuth bool
+}
+
+func generateCertTemplate(info *certTemplateInfo) *x509.Certificate {
+ // Generate a certificate template which is valid from the past week to
+ // 10 years from now. The usage of the certificate depends on the
+ // specified fields in the given certTempInfo object.
+ var (
+ keyUsage x509.KeyUsage
+ extKeyUsage []x509.ExtKeyUsage
+ )
+
+ if info.isCA {
+ keyUsage = x509.KeyUsageCertSign
+ }
+
+ if info.clientAuth {
+ extKeyUsage = append(extKeyUsage, x509.ExtKeyUsageClientAuth)
+ }
+
+ if info.serverAuth {
+ extKeyUsage = append(extKeyUsage, x509.ExtKeyUsageServerAuth)
+ }
+
+ return &x509.Certificate{
+ SerialNumber: big.NewInt(0),
+ Subject: pkix.Name{
+ CommonName: info.commonName,
+ },
+ NotBefore: time.Now().Add(-time.Hour * 24 * 7),
+ NotAfter: time.Now().Add(time.Hour * 24 * 365 * 10),
+ DNSNames: info.domains,
+ IPAddresses: info.ipAddresses,
+ IsCA: info.isCA,
+ KeyUsage: keyUsage,
+ ExtKeyUsage: extKeyUsage,
+ BasicConstraintsValid: info.isCA,
+ }
+}
+
+func generateCert(pub PublicKey, priv PrivateKey, subInfo, issInfo *certTemplateInfo) (cert *x509.Certificate, err error) {
+ pubCertTemplate := generateCertTemplate(subInfo)
+ privCertTemplate := generateCertTemplate(issInfo)
+
+ certDER, err := x509.CreateCertificate(
+ rand.Reader, pubCertTemplate, privCertTemplate,
+ pub.CryptoPublicKey(), priv.CryptoPrivateKey(),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("failed to create certificate: %s", err)
+ }
+
+ cert, err = x509.ParseCertificate(certDER)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse certificate: %s", err)
+ }
+
+ return
+}
+
+// GenerateSelfSignedServerCert creates a self-signed certificate for the
+// given key which is to be used for TLS servers with the given domains and
+// IP addresses.
+func GenerateSelfSignedServerCert(key PrivateKey, domains []string, ipAddresses []net.IP) (*x509.Certificate, error) {
+ info := &certTemplateInfo{
+ commonName: key.KeyID(),
+ domains: domains,
+ ipAddresses: ipAddresses,
+ serverAuth: true,
+ }
+
+ return generateCert(key.PublicKey(), key, info, info)
+}
+
+// GenerateSelfSignedClientCert creates a self-signed certificate for the
+// given key which is to be used for TLS clients.
+func GenerateSelfSignedClientCert(key PrivateKey) (*x509.Certificate, error) {
+ info := &certTemplateInfo{
+ commonName: key.KeyID(),
+ clientAuth: true,
+ }
+
+ return generateCert(key.PublicKey(), key, info, info)
+}
+
+// GenerateCACert creates a certificate which can be used as a trusted
+// certificate authority.
+func GenerateCACert(signer PrivateKey, trustedKey PublicKey) (*x509.Certificate, error) {
+ subjectInfo := &certTemplateInfo{
+ commonName: trustedKey.KeyID(),
+ isCA: true,
+ }
+ issuerInfo := &certTemplateInfo{
+ commonName: signer.KeyID(),
+ }
+
+ return generateCert(trustedKey, signer, subjectInfo, issuerInfo)
+}
+
+// GenerateCACertPool creates a certificate authority pool to be used for a
+// TLS configuration. Any self-signed certificates issued by the specified
+// trusted keys will be verified during a TLS handshake
+func GenerateCACertPool(signer PrivateKey, trustedKeys []PublicKey) (*x509.CertPool, error) {
+ certPool := x509.NewCertPool()
+
+ for _, trustedKey := range trustedKeys {
+ cert, err := GenerateCACert(signer, trustedKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate CA certificate: %s", err)
+ }
+
+ certPool.AddCert(cert)
+ }
+
+ return certPool, nil
+}
+
+// LoadCertificateBundle loads certificates from the given file. The file should be pem encoded
+// containing one or more certificates. The expected pem type is "CERTIFICATE".
+func LoadCertificateBundle(filename string) ([]*x509.Certificate, error) {
+ b, err := ioutil.ReadFile(filename)
+ if err != nil {
+ return nil, err
+ }
+ certificates := []*x509.Certificate{}
+ var block *pem.Block
+ block, b = pem.Decode(b)
+ for ; block != nil; block, b = pem.Decode(b) {
+ if block.Type == "CERTIFICATE" {
+ cert, err := x509.ParseCertificate(block.Bytes)
+ if err != nil {
+ return nil, err
+ }
+ certificates = append(certificates, cert)
+ } else {
+ return nil, fmt.Errorf("invalid pem block type: %s", block.Type)
+ }
+ }
+
+ return certificates, nil
+}
+
+// LoadCertificatePool loads a CA pool from the given file. The file should be pem encoded
+// containing one or more certificates. The expected pem type is "CERTIFICATE".
+func LoadCertificatePool(filename string) (*x509.CertPool, error) {
+ certs, err := LoadCertificateBundle(filename)
+ if err != nil {
+ return nil, err
+ }
+ pool := x509.NewCertPool()
+ for _, cert := range certs {
+ pool.AddCert(cert)
+ }
+ return pool, nil
+}
diff --git a/vendor/github.com/docker/libtrust/doc.go b/vendor/github.com/docker/libtrust/doc.go
new file mode 100644
index 0000000..ec5d215
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/doc.go
@@ -0,0 +1,9 @@
+/*
+Package libtrust provides an interface for managing authentication and
+authorization using public key cryptography. Authentication is handled
+using the identity attached to the public key and verified through TLS
+x509 certificates, a key challenge, or signature. Authorization and
+access control is managed through a trust graph distributed between
+both remote trust servers and locally cached and managed data.
+*/
+package libtrust
diff --git a/vendor/github.com/docker/libtrust/ec_key.go b/vendor/github.com/docker/libtrust/ec_key.go
new file mode 100644
index 0000000..00bbe4b
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/ec_key.go
@@ -0,0 +1,428 @@
+package libtrust
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/x509"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "math/big"
+)
+
+/*
+ * EC DSA PUBLIC KEY
+ */
+
+// ecPublicKey implements a libtrust.PublicKey using elliptic curve digital
+// signature algorithms.
+type ecPublicKey struct {
+ *ecdsa.PublicKey
+ curveName string
+ signatureAlgorithm *signatureAlgorithm
+ extended map[string]interface{}
+}
+
+func fromECPublicKey(cryptoPublicKey *ecdsa.PublicKey) (*ecPublicKey, error) {
+ curve := cryptoPublicKey.Curve
+
+ switch {
+ case curve == elliptic.P256():
+ return &ecPublicKey{cryptoPublicKey, "P-256", es256, map[string]interface{}{}}, nil
+ case curve == elliptic.P384():
+ return &ecPublicKey{cryptoPublicKey, "P-384", es384, map[string]interface{}{}}, nil
+ case curve == elliptic.P521():
+ return &ecPublicKey{cryptoPublicKey, "P-521", es512, map[string]interface{}{}}, nil
+ default:
+ return nil, errors.New("unsupported elliptic curve")
+ }
+}
+
+// KeyType returns the key type for elliptic curve keys, i.e., "EC".
+func (k *ecPublicKey) KeyType() string {
+ return "EC"
+}
+
+// CurveName returns the elliptic curve identifier.
+// Possible values are "P-256", "P-384", and "P-521".
+func (k *ecPublicKey) CurveName() string {
+ return k.curveName
+}
+
+// KeyID returns a distinct identifier which is unique to this Public Key.
+func (k *ecPublicKey) KeyID() string {
+ return keyIDFromCryptoKey(k)
+}
+
+func (k *ecPublicKey) String() string {
+ return fmt.Sprintf("EC Public Key <%s>", k.KeyID())
+}
+
+// Verify verifyies the signature of the data in the io.Reader using this
+// PublicKey. The alg parameter should identify the digital signature
+// algorithm which was used to produce the signature and should be supported
+// by this public key. Returns a nil error if the signature is valid.
+func (k *ecPublicKey) Verify(data io.Reader, alg string, signature []byte) error {
+ // For EC keys there is only one supported signature algorithm depending
+ // on the curve parameters.
+ if k.signatureAlgorithm.HeaderParam() != alg {
+ return fmt.Errorf("unable to verify signature: EC Public Key with curve %q does not support signature algorithm %q", k.curveName, alg)
+ }
+
+ // signature is the concatenation of (r, s), base64Url encoded.
+ sigLength := len(signature)
+ expectedOctetLength := 2 * ((k.Params().BitSize + 7) >> 3)
+ if sigLength != expectedOctetLength {
+ return fmt.Errorf("signature length is %d octets long, should be %d", sigLength, expectedOctetLength)
+ }
+
+ rBytes, sBytes := signature[:sigLength/2], signature[sigLength/2:]
+ r := new(big.Int).SetBytes(rBytes)
+ s := new(big.Int).SetBytes(sBytes)
+
+ hasher := k.signatureAlgorithm.HashID().New()
+ _, err := io.Copy(hasher, data)
+ if err != nil {
+ return fmt.Errorf("error reading data to sign: %s", err)
+ }
+ hash := hasher.Sum(nil)
+
+ if !ecdsa.Verify(k.PublicKey, hash, r, s) {
+ return errors.New("invalid signature")
+ }
+
+ return nil
+}
+
+// CryptoPublicKey returns the internal object which can be used as a
+// crypto.PublicKey for use with other standard library operations. The type
+// is either *rsa.PublicKey or *ecdsa.PublicKey
+func (k *ecPublicKey) CryptoPublicKey() crypto.PublicKey {
+ return k.PublicKey
+}
+
+func (k *ecPublicKey) toMap() map[string]interface{} {
+ jwk := make(map[string]interface{})
+ for k, v := range k.extended {
+ jwk[k] = v
+ }
+ jwk["kty"] = k.KeyType()
+ jwk["kid"] = k.KeyID()
+ jwk["crv"] = k.CurveName()
+
+ xBytes := k.X.Bytes()
+ yBytes := k.Y.Bytes()
+ octetLength := (k.Params().BitSize + 7) >> 3
+ // MUST include leading zeros in the output so that x, y are each
+ // *octetLength* bytes long.
+ xBuf := make([]byte, octetLength-len(xBytes), octetLength)
+ yBuf := make([]byte, octetLength-len(yBytes), octetLength)
+ xBuf = append(xBuf, xBytes...)
+ yBuf = append(yBuf, yBytes...)
+
+ jwk["x"] = joseBase64UrlEncode(xBuf)
+ jwk["y"] = joseBase64UrlEncode(yBuf)
+
+ return jwk
+}
+
+// MarshalJSON serializes this Public Key using the JWK JSON serialization format for
+// elliptic curve keys.
+func (k *ecPublicKey) MarshalJSON() (data []byte, err error) {
+ return json.Marshal(k.toMap())
+}
+
+// PEMBlock serializes this Public Key to DER-encoded PKIX format.
+func (k *ecPublicKey) PEMBlock() (*pem.Block, error) {
+ derBytes, err := x509.MarshalPKIXPublicKey(k.PublicKey)
+ if err != nil {
+ return nil, fmt.Errorf("unable to serialize EC PublicKey to DER-encoded PKIX format: %s", err)
+ }
+ k.extended["kid"] = k.KeyID() // For display purposes.
+ return createPemBlock("PUBLIC KEY", derBytes, k.extended)
+}
+
+func (k *ecPublicKey) AddExtendedField(field string, value interface{}) {
+ k.extended[field] = value
+}
+
+func (k *ecPublicKey) GetExtendedField(field string) interface{} {
+ v, ok := k.extended[field]
+ if !ok {
+ return nil
+ }
+ return v
+}
+
+func ecPublicKeyFromMap(jwk map[string]interface{}) (*ecPublicKey, error) {
+ // JWK key type (kty) has already been determined to be "EC".
+ // Need to extract 'crv', 'x', 'y', and 'kid' and check for
+ // consistency.
+
+ // Get the curve identifier value.
+ crv, err := stringFromMap(jwk, "crv")
+ if err != nil {
+ return nil, fmt.Errorf("JWK EC Public Key curve identifier: %s", err)
+ }
+
+ var (
+ curve elliptic.Curve
+ sigAlg *signatureAlgorithm
+ )
+
+ switch {
+ case crv == "P-256":
+ curve = elliptic.P256()
+ sigAlg = es256
+ case crv == "P-384":
+ curve = elliptic.P384()
+ sigAlg = es384
+ case crv == "P-521":
+ curve = elliptic.P521()
+ sigAlg = es512
+ default:
+ return nil, fmt.Errorf("JWK EC Public Key curve identifier not supported: %q\n", crv)
+ }
+
+ // Get the X and Y coordinates for the public key point.
+ xB64Url, err := stringFromMap(jwk, "x")
+ if err != nil {
+ return nil, fmt.Errorf("JWK EC Public Key x-coordinate: %s", err)
+ }
+ x, err := parseECCoordinate(xB64Url, curve)
+ if err != nil {
+ return nil, fmt.Errorf("JWK EC Public Key x-coordinate: %s", err)
+ }
+
+ yB64Url, err := stringFromMap(jwk, "y")
+ if err != nil {
+ return nil, fmt.Errorf("JWK EC Public Key y-coordinate: %s", err)
+ }
+ y, err := parseECCoordinate(yB64Url, curve)
+ if err != nil {
+ return nil, fmt.Errorf("JWK EC Public Key y-coordinate: %s", err)
+ }
+
+ key := &ecPublicKey{
+ PublicKey: &ecdsa.PublicKey{Curve: curve, X: x, Y: y},
+ curveName: crv, signatureAlgorithm: sigAlg,
+ }
+
+ // Key ID is optional too, but if it exists, it should match the key.
+ _, ok := jwk["kid"]
+ if ok {
+ kid, err := stringFromMap(jwk, "kid")
+ if err != nil {
+ return nil, fmt.Errorf("JWK EC Public Key ID: %s", err)
+ }
+ if kid != key.KeyID() {
+ return nil, fmt.Errorf("JWK EC Public Key ID does not match: %s", kid)
+ }
+ }
+
+ key.extended = jwk
+
+ return key, nil
+}
+
+/*
+ * EC DSA PRIVATE KEY
+ */
+
+// ecPrivateKey implements a JWK Private Key using elliptic curve digital signature
+// algorithms.
+type ecPrivateKey struct {
+ ecPublicKey
+ *ecdsa.PrivateKey
+}
+
+func fromECPrivateKey(cryptoPrivateKey *ecdsa.PrivateKey) (*ecPrivateKey, error) {
+ publicKey, err := fromECPublicKey(&cryptoPrivateKey.PublicKey)
+ if err != nil {
+ return nil, err
+ }
+
+ return &ecPrivateKey{*publicKey, cryptoPrivateKey}, nil
+}
+
+// PublicKey returns the Public Key data associated with this Private Key.
+func (k *ecPrivateKey) PublicKey() PublicKey {
+ return &k.ecPublicKey
+}
+
+func (k *ecPrivateKey) String() string {
+ return fmt.Sprintf("EC Private Key <%s>", k.KeyID())
+}
+
+// Sign signs the data read from the io.Reader using a signature algorithm supported
+// by the elliptic curve private key. If the specified hashing algorithm is
+// supported by this key, that hash function is used to generate the signature
+// otherwise the the default hashing algorithm for this key is used. Returns
+// the signature and the name of the JWK signature algorithm used, e.g.,
+// "ES256", "ES384", "ES512".
+func (k *ecPrivateKey) Sign(data io.Reader, hashID crypto.Hash) (signature []byte, alg string, err error) {
+ // Generate a signature of the data using the internal alg.
+ // The given hashId is only a suggestion, and since EC keys only support
+ // on signature/hash algorithm given the curve name, we disregard it for
+ // the elliptic curve JWK signature implementation.
+ hasher := k.signatureAlgorithm.HashID().New()
+ _, err = io.Copy(hasher, data)
+ if err != nil {
+ return nil, "", fmt.Errorf("error reading data to sign: %s", err)
+ }
+ hash := hasher.Sum(nil)
+
+ r, s, err := ecdsa.Sign(rand.Reader, k.PrivateKey, hash)
+ if err != nil {
+ return nil, "", fmt.Errorf("error producing signature: %s", err)
+ }
+ rBytes, sBytes := r.Bytes(), s.Bytes()
+ octetLength := (k.ecPublicKey.Params().BitSize + 7) >> 3
+ // MUST include leading zeros in the output
+ rBuf := make([]byte, octetLength-len(rBytes), octetLength)
+ sBuf := make([]byte, octetLength-len(sBytes), octetLength)
+
+ rBuf = append(rBuf, rBytes...)
+ sBuf = append(sBuf, sBytes...)
+
+ signature = append(rBuf, sBuf...)
+ alg = k.signatureAlgorithm.HeaderParam()
+
+ return
+}
+
+// CryptoPrivateKey returns the internal object which can be used as a
+// crypto.PublicKey for use with other standard library operations. The type
+// is either *rsa.PublicKey or *ecdsa.PublicKey
+func (k *ecPrivateKey) CryptoPrivateKey() crypto.PrivateKey {
+ return k.PrivateKey
+}
+
+func (k *ecPrivateKey) toMap() map[string]interface{} {
+ jwk := k.ecPublicKey.toMap()
+
+ dBytes := k.D.Bytes()
+ // The length of this octet string MUST be ceiling(log-base-2(n)/8)
+ // octets (where n is the order of the curve). This is because the private
+ // key d must be in the interval [1, n-1] so the bitlength of d should be
+ // no larger than the bitlength of n-1. The easiest way to find the octet
+ // length is to take bitlength(n-1), add 7 to force a carry, and shift this
+ // bit sequence right by 3, which is essentially dividing by 8 and adding
+ // 1 if there is any remainder. Thus, the private key value d should be
+ // output to (bitlength(n-1)+7)>>3 octets.
+ n := k.ecPublicKey.Params().N
+ octetLength := (new(big.Int).Sub(n, big.NewInt(1)).BitLen() + 7) >> 3
+ // Create a buffer with the necessary zero-padding.
+ dBuf := make([]byte, octetLength-len(dBytes), octetLength)
+ dBuf = append(dBuf, dBytes...)
+
+ jwk["d"] = joseBase64UrlEncode(dBuf)
+
+ return jwk
+}
+
+// MarshalJSON serializes this Private Key using the JWK JSON serialization format for
+// elliptic curve keys.
+func (k *ecPrivateKey) MarshalJSON() (data []byte, err error) {
+ return json.Marshal(k.toMap())
+}
+
+// PEMBlock serializes this Private Key to DER-encoded PKIX format.
+func (k *ecPrivateKey) PEMBlock() (*pem.Block, error) {
+ derBytes, err := x509.MarshalECPrivateKey(k.PrivateKey)
+ if err != nil {
+ return nil, fmt.Errorf("unable to serialize EC PrivateKey to DER-encoded PKIX format: %s", err)
+ }
+ k.extended["keyID"] = k.KeyID() // For display purposes.
+ return createPemBlock("EC PRIVATE KEY", derBytes, k.extended)
+}
+
+func ecPrivateKeyFromMap(jwk map[string]interface{}) (*ecPrivateKey, error) {
+ dB64Url, err := stringFromMap(jwk, "d")
+ if err != nil {
+ return nil, fmt.Errorf("JWK EC Private Key: %s", err)
+ }
+
+ // JWK key type (kty) has already been determined to be "EC".
+ // Need to extract the public key information, then extract the private
+ // key value 'd'.
+ publicKey, err := ecPublicKeyFromMap(jwk)
+ if err != nil {
+ return nil, err
+ }
+
+ d, err := parseECPrivateParam(dB64Url, publicKey.Curve)
+ if err != nil {
+ return nil, fmt.Errorf("JWK EC Private Key d-param: %s", err)
+ }
+
+ key := &ecPrivateKey{
+ ecPublicKey: *publicKey,
+ PrivateKey: &ecdsa.PrivateKey{
+ PublicKey: *publicKey.PublicKey,
+ D: d,
+ },
+ }
+
+ return key, nil
+}
+
+/*
+ * Key Generation Functions.
+ */
+
+func generateECPrivateKey(curve elliptic.Curve) (k *ecPrivateKey, err error) {
+ k = new(ecPrivateKey)
+ k.PrivateKey, err = ecdsa.GenerateKey(curve, rand.Reader)
+ if err != nil {
+ return nil, err
+ }
+
+ k.ecPublicKey.PublicKey = &k.PrivateKey.PublicKey
+ k.extended = make(map[string]interface{})
+
+ return
+}
+
+// GenerateECP256PrivateKey generates a key pair using elliptic curve P-256.
+func GenerateECP256PrivateKey() (PrivateKey, error) {
+ k, err := generateECPrivateKey(elliptic.P256())
+ if err != nil {
+ return nil, fmt.Errorf("error generating EC P-256 key: %s", err)
+ }
+
+ k.curveName = "P-256"
+ k.signatureAlgorithm = es256
+
+ return k, nil
+}
+
+// GenerateECP384PrivateKey generates a key pair using elliptic curve P-384.
+func GenerateECP384PrivateKey() (PrivateKey, error) {
+ k, err := generateECPrivateKey(elliptic.P384())
+ if err != nil {
+ return nil, fmt.Errorf("error generating EC P-384 key: %s", err)
+ }
+
+ k.curveName = "P-384"
+ k.signatureAlgorithm = es384
+
+ return k, nil
+}
+
+// GenerateECP521PrivateKey generates aß key pair using elliptic curve P-521.
+func GenerateECP521PrivateKey() (PrivateKey, error) {
+ k, err := generateECPrivateKey(elliptic.P521())
+ if err != nil {
+ return nil, fmt.Errorf("error generating EC P-521 key: %s", err)
+ }
+
+ k.curveName = "P-521"
+ k.signatureAlgorithm = es512
+
+ return k, nil
+}
diff --git a/vendor/github.com/docker/libtrust/filter.go b/vendor/github.com/docker/libtrust/filter.go
new file mode 100644
index 0000000..5b2b4fc
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/filter.go
@@ -0,0 +1,50 @@
+package libtrust
+
+import (
+ "path/filepath"
+)
+
+// FilterByHosts filters the list of PublicKeys to only those which contain a
+// 'hosts' pattern which matches the given host. If *includeEmpty* is true,
+// then keys which do not specify any hosts are also returned.
+func FilterByHosts(keys []PublicKey, host string, includeEmpty bool) ([]PublicKey, error) {
+ filtered := make([]PublicKey, 0, len(keys))
+
+ for _, pubKey := range keys {
+ var hosts []string
+ switch v := pubKey.GetExtendedField("hosts").(type) {
+ case []string:
+ hosts = v
+ case []interface{}:
+ for _, value := range v {
+ h, ok := value.(string)
+ if !ok {
+ continue
+ }
+ hosts = append(hosts, h)
+ }
+ }
+
+ if len(hosts) == 0 {
+ if includeEmpty {
+ filtered = append(filtered, pubKey)
+ }
+ continue
+ }
+
+ // Check if any hosts match pattern
+ for _, hostPattern := range hosts {
+ match, err := filepath.Match(hostPattern, host)
+ if err != nil {
+ return nil, err
+ }
+
+ if match {
+ filtered = append(filtered, pubKey)
+ continue
+ }
+ }
+ }
+
+ return filtered, nil
+}
diff --git a/vendor/github.com/docker/libtrust/hash.go b/vendor/github.com/docker/libtrust/hash.go
new file mode 100644
index 0000000..a2df787
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/hash.go
@@ -0,0 +1,56 @@
+package libtrust
+
+import (
+ "crypto"
+ _ "crypto/sha256" // Registrer SHA224 and SHA256
+ _ "crypto/sha512" // Registrer SHA384 and SHA512
+ "fmt"
+)
+
+type signatureAlgorithm struct {
+ algHeaderParam string
+ hashID crypto.Hash
+}
+
+func (h *signatureAlgorithm) HeaderParam() string {
+ return h.algHeaderParam
+}
+
+func (h *signatureAlgorithm) HashID() crypto.Hash {
+ return h.hashID
+}
+
+var (
+ rs256 = &signatureAlgorithm{"RS256", crypto.SHA256}
+ rs384 = &signatureAlgorithm{"RS384", crypto.SHA384}
+ rs512 = &signatureAlgorithm{"RS512", crypto.SHA512}
+ es256 = &signatureAlgorithm{"ES256", crypto.SHA256}
+ es384 = &signatureAlgorithm{"ES384", crypto.SHA384}
+ es512 = &signatureAlgorithm{"ES512", crypto.SHA512}
+)
+
+func rsaSignatureAlgorithmByName(alg string) (*signatureAlgorithm, error) {
+ switch {
+ case alg == "RS256":
+ return rs256, nil
+ case alg == "RS384":
+ return rs384, nil
+ case alg == "RS512":
+ return rs512, nil
+ default:
+ return nil, fmt.Errorf("RSA Digital Signature Algorithm %q not supported", alg)
+ }
+}
+
+func rsaPKCS1v15SignatureAlgorithmForHashID(hashID crypto.Hash) *signatureAlgorithm {
+ switch {
+ case hashID == crypto.SHA512:
+ return rs512
+ case hashID == crypto.SHA384:
+ return rs384
+ case hashID == crypto.SHA256:
+ fallthrough
+ default:
+ return rs256
+ }
+}
diff --git a/vendor/github.com/docker/libtrust/jsonsign.go b/vendor/github.com/docker/libtrust/jsonsign.go
new file mode 100644
index 0000000..cb2ca9a
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/jsonsign.go
@@ -0,0 +1,657 @@
+package libtrust
+
+import (
+ "bytes"
+ "crypto"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "sort"
+ "time"
+ "unicode"
+)
+
+var (
+ // ErrInvalidSignContent is used when the content to be signed is invalid.
+ ErrInvalidSignContent = errors.New("invalid sign content")
+
+ // ErrInvalidJSONContent is used when invalid json is encountered.
+ ErrInvalidJSONContent = errors.New("invalid json content")
+
+ // ErrMissingSignatureKey is used when the specified signature key
+ // does not exist in the JSON content.
+ ErrMissingSignatureKey = errors.New("missing signature key")
+)
+
+type jsHeader struct {
+ JWK PublicKey `json:"jwk,omitempty"`
+ Algorithm string `json:"alg"`
+ Chain []string `json:"x5c,omitempty"`
+}
+
+type jsSignature struct {
+ Header jsHeader `json:"header"`
+ Signature string `json:"signature"`
+ Protected string `json:"protected,omitempty"`
+}
+
+type jsSignaturesSorted []jsSignature
+
+func (jsbkid jsSignaturesSorted) Swap(i, j int) { jsbkid[i], jsbkid[j] = jsbkid[j], jsbkid[i] }
+func (jsbkid jsSignaturesSorted) Len() int { return len(jsbkid) }
+
+func (jsbkid jsSignaturesSorted) Less(i, j int) bool {
+ ki, kj := jsbkid[i].Header.JWK.KeyID(), jsbkid[j].Header.JWK.KeyID()
+ si, sj := jsbkid[i].Signature, jsbkid[j].Signature
+
+ if ki == kj {
+ return si < sj
+ }
+
+ return ki < kj
+}
+
+type signKey struct {
+ PrivateKey
+ Chain []*x509.Certificate
+}
+
+// JSONSignature represents a signature of a json object.
+type JSONSignature struct {
+ payload string
+ signatures []jsSignature
+ indent string
+ formatLength int
+ formatTail []byte
+}
+
+func newJSONSignature() *JSONSignature {
+ return &JSONSignature{
+ signatures: make([]jsSignature, 0, 1),
+ }
+}
+
+// Payload returns the encoded payload of the signature. This
+// payload should not be signed directly
+func (js *JSONSignature) Payload() ([]byte, error) {
+ return joseBase64UrlDecode(js.payload)
+}
+
+func (js *JSONSignature) protectedHeader() (string, error) {
+ protected := map[string]interface{}{
+ "formatLength": js.formatLength,
+ "formatTail": joseBase64UrlEncode(js.formatTail),
+ "time": time.Now().UTC().Format(time.RFC3339),
+ }
+ protectedBytes, err := json.Marshal(protected)
+ if err != nil {
+ return "", err
+ }
+
+ return joseBase64UrlEncode(protectedBytes), nil
+}
+
+func (js *JSONSignature) signBytes(protectedHeader string) ([]byte, error) {
+ buf := make([]byte, len(js.payload)+len(protectedHeader)+1)
+ copy(buf, protectedHeader)
+ buf[len(protectedHeader)] = '.'
+ copy(buf[len(protectedHeader)+1:], js.payload)
+ return buf, nil
+}
+
+// Sign adds a signature using the given private key.
+func (js *JSONSignature) Sign(key PrivateKey) error {
+ protected, err := js.protectedHeader()
+ if err != nil {
+ return err
+ }
+ signBytes, err := js.signBytes(protected)
+ if err != nil {
+ return err
+ }
+ sigBytes, algorithm, err := key.Sign(bytes.NewReader(signBytes), crypto.SHA256)
+ if err != nil {
+ return err
+ }
+
+ js.signatures = append(js.signatures, jsSignature{
+ Header: jsHeader{
+ JWK: key.PublicKey(),
+ Algorithm: algorithm,
+ },
+ Signature: joseBase64UrlEncode(sigBytes),
+ Protected: protected,
+ })
+
+ return nil
+}
+
+// SignWithChain adds a signature using the given private key
+// and setting the x509 chain. The public key of the first element
+// in the chain must be the public key corresponding with the sign key.
+func (js *JSONSignature) SignWithChain(key PrivateKey, chain []*x509.Certificate) error {
+ // Ensure key.Chain[0] is public key for key
+ //key.Chain.PublicKey
+ //key.PublicKey().CryptoPublicKey()
+
+ // Verify chain
+ protected, err := js.protectedHeader()
+ if err != nil {
+ return err
+ }
+ signBytes, err := js.signBytes(protected)
+ if err != nil {
+ return err
+ }
+ sigBytes, algorithm, err := key.Sign(bytes.NewReader(signBytes), crypto.SHA256)
+ if err != nil {
+ return err
+ }
+
+ header := jsHeader{
+ Chain: make([]string, len(chain)),
+ Algorithm: algorithm,
+ }
+
+ for i, cert := range chain {
+ header.Chain[i] = base64.StdEncoding.EncodeToString(cert.Raw)
+ }
+
+ js.signatures = append(js.signatures, jsSignature{
+ Header: header,
+ Signature: joseBase64UrlEncode(sigBytes),
+ Protected: protected,
+ })
+
+ return nil
+}
+
+// Verify verifies all the signatures and returns the list of
+// public keys used to sign. Any x509 chains are not checked.
+func (js *JSONSignature) Verify() ([]PublicKey, error) {
+ keys := make([]PublicKey, len(js.signatures))
+ for i, signature := range js.signatures {
+ signBytes, err := js.signBytes(signature.Protected)
+ if err != nil {
+ return nil, err
+ }
+ var publicKey PublicKey
+ if len(signature.Header.Chain) > 0 {
+ certBytes, err := base64.StdEncoding.DecodeString(signature.Header.Chain[0])
+ if err != nil {
+ return nil, err
+ }
+ cert, err := x509.ParseCertificate(certBytes)
+ if err != nil {
+ return nil, err
+ }
+ publicKey, err = FromCryptoPublicKey(cert.PublicKey)
+ if err != nil {
+ return nil, err
+ }
+ } else if signature.Header.JWK != nil {
+ publicKey = signature.Header.JWK
+ } else {
+ return nil, errors.New("missing public key")
+ }
+
+ sigBytes, err := joseBase64UrlDecode(signature.Signature)
+ if err != nil {
+ return nil, err
+ }
+
+ err = publicKey.Verify(bytes.NewReader(signBytes), signature.Header.Algorithm, sigBytes)
+ if err != nil {
+ return nil, err
+ }
+
+ keys[i] = publicKey
+ }
+ return keys, nil
+}
+
+// VerifyChains verifies all the signatures and the chains associated
+// with each signature and returns the list of verified chains.
+// Signatures without an x509 chain are not checked.
+func (js *JSONSignature) VerifyChains(ca *x509.CertPool) ([][]*x509.Certificate, error) {
+ chains := make([][]*x509.Certificate, 0, len(js.signatures))
+ for _, signature := range js.signatures {
+ signBytes, err := js.signBytes(signature.Protected)
+ if err != nil {
+ return nil, err
+ }
+ var publicKey PublicKey
+ if len(signature.Header.Chain) > 0 {
+ certBytes, err := base64.StdEncoding.DecodeString(signature.Header.Chain[0])
+ if err != nil {
+ return nil, err
+ }
+ cert, err := x509.ParseCertificate(certBytes)
+ if err != nil {
+ return nil, err
+ }
+ publicKey, err = FromCryptoPublicKey(cert.PublicKey)
+ if err != nil {
+ return nil, err
+ }
+ intermediates := x509.NewCertPool()
+ if len(signature.Header.Chain) > 1 {
+ intermediateChain := signature.Header.Chain[1:]
+ for i := range intermediateChain {
+ certBytes, err := base64.StdEncoding.DecodeString(intermediateChain[i])
+ if err != nil {
+ return nil, err
+ }
+ intermediate, err := x509.ParseCertificate(certBytes)
+ if err != nil {
+ return nil, err
+ }
+ intermediates.AddCert(intermediate)
+ }
+ }
+
+ verifyOptions := x509.VerifyOptions{
+ Intermediates: intermediates,
+ Roots: ca,
+ }
+
+ verifiedChains, err := cert.Verify(verifyOptions)
+ if err != nil {
+ return nil, err
+ }
+ chains = append(chains, verifiedChains...)
+
+ sigBytes, err := joseBase64UrlDecode(signature.Signature)
+ if err != nil {
+ return nil, err
+ }
+
+ err = publicKey.Verify(bytes.NewReader(signBytes), signature.Header.Algorithm, sigBytes)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ }
+ return chains, nil
+}
+
+// JWS returns JSON serialized JWS according to
+// http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-31#section-7.2
+func (js *JSONSignature) JWS() ([]byte, error) {
+ if len(js.signatures) == 0 {
+ return nil, errors.New("missing signature")
+ }
+
+ sort.Sort(jsSignaturesSorted(js.signatures))
+
+ jsonMap := map[string]interface{}{
+ "payload": js.payload,
+ "signatures": js.signatures,
+ }
+
+ return json.MarshalIndent(jsonMap, "", " ")
+}
+
+func notSpace(r rune) bool {
+ return !unicode.IsSpace(r)
+}
+
+func detectJSONIndent(jsonContent []byte) (indent string) {
+ if len(jsonContent) > 2 && jsonContent[0] == '{' && jsonContent[1] == '\n' {
+ quoteIndex := bytes.IndexRune(jsonContent[1:], '"')
+ if quoteIndex > 0 {
+ indent = string(jsonContent[2 : quoteIndex+1])
+ }
+ }
+ return
+}
+
+type jsParsedHeader struct {
+ JWK json.RawMessage `json:"jwk"`
+ Algorithm string `json:"alg"`
+ Chain []string `json:"x5c"`
+}
+
+type jsParsedSignature struct {
+ Header jsParsedHeader `json:"header"`
+ Signature string `json:"signature"`
+ Protected string `json:"protected"`
+}
+
+// ParseJWS parses a JWS serialized JSON object into a Json Signature.
+func ParseJWS(content []byte) (*JSONSignature, error) {
+ type jsParsed struct {
+ Payload string `json:"payload"`
+ Signatures []jsParsedSignature `json:"signatures"`
+ }
+ parsed := &jsParsed{}
+ err := json.Unmarshal(content, parsed)
+ if err != nil {
+ return nil, err
+ }
+ if len(parsed.Signatures) == 0 {
+ return nil, errors.New("missing signatures")
+ }
+ payload, err := joseBase64UrlDecode(parsed.Payload)
+ if err != nil {
+ return nil, err
+ }
+
+ js, err := NewJSONSignature(payload)
+ if err != nil {
+ return nil, err
+ }
+ js.signatures = make([]jsSignature, len(parsed.Signatures))
+ for i, signature := range parsed.Signatures {
+ header := jsHeader{
+ Algorithm: signature.Header.Algorithm,
+ }
+ if signature.Header.Chain != nil {
+ header.Chain = signature.Header.Chain
+ }
+ if signature.Header.JWK != nil {
+ publicKey, err := UnmarshalPublicKeyJWK([]byte(signature.Header.JWK))
+ if err != nil {
+ return nil, err
+ }
+ header.JWK = publicKey
+ }
+ js.signatures[i] = jsSignature{
+ Header: header,
+ Signature: signature.Signature,
+ Protected: signature.Protected,
+ }
+ }
+
+ return js, nil
+}
+
+// NewJSONSignature returns a new unsigned JWS from a json byte array.
+// JSONSignature will need to be signed before serializing or storing.
+// Optionally, one or more signatures can be provided as byte buffers,
+// containing serialized JWS signatures, to assemble a fully signed JWS
+// package. It is the callers responsibility to ensure uniqueness of the
+// provided signatures.
+func NewJSONSignature(content []byte, signatures ...[]byte) (*JSONSignature, error) {
+ var dataMap map[string]interface{}
+ err := json.Unmarshal(content, &dataMap)
+ if err != nil {
+ return nil, err
+ }
+
+ js := newJSONSignature()
+ js.indent = detectJSONIndent(content)
+
+ js.payload = joseBase64UrlEncode(content)
+
+ // Find trailing } and whitespace, put in protected header
+ closeIndex := bytes.LastIndexFunc(content, notSpace)
+ if content[closeIndex] != '}' {
+ return nil, ErrInvalidJSONContent
+ }
+ lastRuneIndex := bytes.LastIndexFunc(content[:closeIndex], notSpace)
+ if content[lastRuneIndex] == ',' {
+ return nil, ErrInvalidJSONContent
+ }
+ js.formatLength = lastRuneIndex + 1
+ js.formatTail = content[js.formatLength:]
+
+ if len(signatures) > 0 {
+ for _, signature := range signatures {
+ var parsedJSig jsParsedSignature
+
+ if err := json.Unmarshal(signature, &parsedJSig); err != nil {
+ return nil, err
+ }
+
+ // TODO(stevvooe): A lot of the code below is repeated in
+ // ParseJWS. It will require more refactoring to fix that.
+ jsig := jsSignature{
+ Header: jsHeader{
+ Algorithm: parsedJSig.Header.Algorithm,
+ },
+ Signature: parsedJSig.Signature,
+ Protected: parsedJSig.Protected,
+ }
+
+ if parsedJSig.Header.Chain != nil {
+ jsig.Header.Chain = parsedJSig.Header.Chain
+ }
+
+ if parsedJSig.Header.JWK != nil {
+ publicKey, err := UnmarshalPublicKeyJWK([]byte(parsedJSig.Header.JWK))
+ if err != nil {
+ return nil, err
+ }
+ jsig.Header.JWK = publicKey
+ }
+
+ js.signatures = append(js.signatures, jsig)
+ }
+ }
+
+ return js, nil
+}
+
+// NewJSONSignatureFromMap returns a new unsigned JSONSignature from a map or
+// struct. JWS will need to be signed before serializing or storing.
+func NewJSONSignatureFromMap(content interface{}) (*JSONSignature, error) {
+ switch content.(type) {
+ case map[string]interface{}:
+ case struct{}:
+ default:
+ return nil, errors.New("invalid data type")
+ }
+
+ js := newJSONSignature()
+ js.indent = " "
+
+ payload, err := json.MarshalIndent(content, "", js.indent)
+ if err != nil {
+ return nil, err
+ }
+ js.payload = joseBase64UrlEncode(payload)
+
+ // Remove '\n}' from formatted section, put in protected header
+ js.formatLength = len(payload) - 2
+ js.formatTail = payload[js.formatLength:]
+
+ return js, nil
+}
+
+func readIntFromMap(key string, m map[string]interface{}) (int, bool) {
+ value, ok := m[key]
+ if !ok {
+ return 0, false
+ }
+ switch v := value.(type) {
+ case int:
+ return v, true
+ case float64:
+ return int(v), true
+ default:
+ return 0, false
+ }
+}
+
+func readStringFromMap(key string, m map[string]interface{}) (v string, ok bool) {
+ value, ok := m[key]
+ if !ok {
+ return "", false
+ }
+ v, ok = value.(string)
+ return
+}
+
+// ParsePrettySignature parses a formatted signature into a
+// JSON signature. If the signatures are missing the format information
+// an error is thrown. The formatted signature must be created by
+// the same method as format signature.
+func ParsePrettySignature(content []byte, signatureKey string) (*JSONSignature, error) {
+ var contentMap map[string]json.RawMessage
+ err := json.Unmarshal(content, &contentMap)
+ if err != nil {
+ return nil, fmt.Errorf("error unmarshalling content: %s", err)
+ }
+ sigMessage, ok := contentMap[signatureKey]
+ if !ok {
+ return nil, ErrMissingSignatureKey
+ }
+
+ var signatureBlocks []jsParsedSignature
+ err = json.Unmarshal([]byte(sigMessage), &signatureBlocks)
+ if err != nil {
+ return nil, fmt.Errorf("error unmarshalling signatures: %s", err)
+ }
+
+ js := newJSONSignature()
+ js.signatures = make([]jsSignature, len(signatureBlocks))
+
+ for i, signatureBlock := range signatureBlocks {
+ protectedBytes, err := joseBase64UrlDecode(signatureBlock.Protected)
+ if err != nil {
+ return nil, fmt.Errorf("base64 decode error: %s", err)
+ }
+ var protectedHeader map[string]interface{}
+ err = json.Unmarshal(protectedBytes, &protectedHeader)
+ if err != nil {
+ return nil, fmt.Errorf("error unmarshalling protected header: %s", err)
+ }
+
+ formatLength, ok := readIntFromMap("formatLength", protectedHeader)
+ if !ok {
+ return nil, errors.New("missing formatted length")
+ }
+ encodedTail, ok := readStringFromMap("formatTail", protectedHeader)
+ if !ok {
+ return nil, errors.New("missing formatted tail")
+ }
+ formatTail, err := joseBase64UrlDecode(encodedTail)
+ if err != nil {
+ return nil, fmt.Errorf("base64 decode error on tail: %s", err)
+ }
+ if js.formatLength == 0 {
+ js.formatLength = formatLength
+ } else if js.formatLength != formatLength {
+ return nil, errors.New("conflicting format length")
+ }
+ if len(js.formatTail) == 0 {
+ js.formatTail = formatTail
+ } else if bytes.Compare(js.formatTail, formatTail) != 0 {
+ return nil, errors.New("conflicting format tail")
+ }
+
+ header := jsHeader{
+ Algorithm: signatureBlock.Header.Algorithm,
+ Chain: signatureBlock.Header.Chain,
+ }
+ if signatureBlock.Header.JWK != nil {
+ publicKey, err := UnmarshalPublicKeyJWK([]byte(signatureBlock.Header.JWK))
+ if err != nil {
+ return nil, fmt.Errorf("error unmarshalling public key: %s", err)
+ }
+ header.JWK = publicKey
+ }
+ js.signatures[i] = jsSignature{
+ Header: header,
+ Signature: signatureBlock.Signature,
+ Protected: signatureBlock.Protected,
+ }
+ }
+ if js.formatLength > len(content) {
+ return nil, errors.New("invalid format length")
+ }
+ formatted := make([]byte, js.formatLength+len(js.formatTail))
+ copy(formatted, content[:js.formatLength])
+ copy(formatted[js.formatLength:], js.formatTail)
+ js.indent = detectJSONIndent(formatted)
+ js.payload = joseBase64UrlEncode(formatted)
+
+ return js, nil
+}
+
+// PrettySignature formats a json signature into an easy to read
+// single json serialized object.
+func (js *JSONSignature) PrettySignature(signatureKey string) ([]byte, error) {
+ if len(js.signatures) == 0 {
+ return nil, errors.New("no signatures")
+ }
+ payload, err := joseBase64UrlDecode(js.payload)
+ if err != nil {
+ return nil, err
+ }
+ payload = payload[:js.formatLength]
+
+ sort.Sort(jsSignaturesSorted(js.signatures))
+
+ var marshalled []byte
+ var marshallErr error
+ if js.indent != "" {
+ marshalled, marshallErr = json.MarshalIndent(js.signatures, js.indent, js.indent)
+ } else {
+ marshalled, marshallErr = json.Marshal(js.signatures)
+ }
+ if marshallErr != nil {
+ return nil, marshallErr
+ }
+
+ buf := bytes.NewBuffer(make([]byte, 0, len(payload)+len(marshalled)+34))
+ buf.Write(payload)
+ buf.WriteByte(',')
+ if js.indent != "" {
+ buf.WriteByte('\n')
+ buf.WriteString(js.indent)
+ buf.WriteByte('"')
+ buf.WriteString(signatureKey)
+ buf.WriteString("\": ")
+ buf.Write(marshalled)
+ buf.WriteByte('\n')
+ } else {
+ buf.WriteByte('"')
+ buf.WriteString(signatureKey)
+ buf.WriteString("\":")
+ buf.Write(marshalled)
+ }
+ buf.WriteByte('}')
+
+ return buf.Bytes(), nil
+}
+
+// Signatures provides the signatures on this JWS as opaque blobs, sorted by
+// keyID. These blobs can be stored and reassembled with payloads. Internally,
+// they are simply marshaled json web signatures but implementations should
+// not rely on this.
+func (js *JSONSignature) Signatures() ([][]byte, error) {
+ sort.Sort(jsSignaturesSorted(js.signatures))
+
+ var sb [][]byte
+ for _, jsig := range js.signatures {
+ p, err := json.Marshal(jsig)
+ if err != nil {
+ return nil, err
+ }
+
+ sb = append(sb, p)
+ }
+
+ return sb, nil
+}
+
+// Merge combines the signatures from one or more other signatures into the
+// method receiver. If the payloads differ for any argument, an error will be
+// returned and the receiver will not be modified.
+func (js *JSONSignature) Merge(others ...*JSONSignature) error {
+ merged := js.signatures
+ for _, other := range others {
+ if js.payload != other.payload {
+ return fmt.Errorf("payloads differ from merge target")
+ }
+ merged = append(merged, other.signatures...)
+ }
+
+ js.signatures = merged
+ return nil
+}
diff --git a/vendor/github.com/docker/libtrust/key.go b/vendor/github.com/docker/libtrust/key.go
new file mode 100644
index 0000000..73642db
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/key.go
@@ -0,0 +1,253 @@
+package libtrust
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/rsa"
+ "crypto/x509"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+)
+
+// PublicKey is a generic interface for a Public Key.
+type PublicKey interface {
+ // KeyType returns the key type for this key. For elliptic curve keys,
+ // this value should be "EC". For RSA keys, this value should be "RSA".
+ KeyType() string
+ // KeyID returns a distinct identifier which is unique to this Public Key.
+ // The format generated by this library is a base32 encoding of a 240 bit
+ // hash of the public key data divided into 12 groups like so:
+ // ABCD:EFGH:IJKL:MNOP:QRST:UVWX:YZ23:4567:ABCD:EFGH:IJKL:MNOP
+ KeyID() string
+ // Verify verifyies the signature of the data in the io.Reader using this
+ // Public Key. The alg parameter should identify the digital signature
+ // algorithm which was used to produce the signature and should be
+ // supported by this public key. Returns a nil error if the signature
+ // is valid.
+ Verify(data io.Reader, alg string, signature []byte) error
+ // CryptoPublicKey returns the internal object which can be used as a
+ // crypto.PublicKey for use with other standard library operations. The type
+ // is either *rsa.PublicKey or *ecdsa.PublicKey
+ CryptoPublicKey() crypto.PublicKey
+ // These public keys can be serialized to the standard JSON encoding for
+ // JSON Web Keys. See section 6 of the IETF draft RFC for JOSE JSON Web
+ // Algorithms.
+ MarshalJSON() ([]byte, error)
+ // These keys can also be serialized to the standard PEM encoding.
+ PEMBlock() (*pem.Block, error)
+ // The string representation of a key is its key type and ID.
+ String() string
+ AddExtendedField(string, interface{})
+ GetExtendedField(string) interface{}
+}
+
+// PrivateKey is a generic interface for a Private Key.
+type PrivateKey interface {
+ // A PrivateKey contains all fields and methods of a PublicKey of the
+ // same type. The MarshalJSON method also outputs the private key as a
+ // JSON Web Key, and the PEMBlock method outputs the private key as a
+ // PEM block.
+ PublicKey
+ // PublicKey returns the PublicKey associated with this PrivateKey.
+ PublicKey() PublicKey
+ // Sign signs the data read from the io.Reader using a signature algorithm
+ // supported by the private key. If the specified hashing algorithm is
+ // supported by this key, that hash function is used to generate the
+ // signature otherwise the the default hashing algorithm for this key is
+ // used. Returns the signature and identifier of the algorithm used.
+ Sign(data io.Reader, hashID crypto.Hash) (signature []byte, alg string, err error)
+ // CryptoPrivateKey returns the internal object which can be used as a
+ // crypto.PublicKey for use with other standard library operations. The
+ // type is either *rsa.PublicKey or *ecdsa.PublicKey
+ CryptoPrivateKey() crypto.PrivateKey
+}
+
+// FromCryptoPublicKey returns a libtrust PublicKey representation of the given
+// *ecdsa.PublicKey or *rsa.PublicKey. Returns a non-nil error when the given
+// key is of an unsupported type.
+func FromCryptoPublicKey(cryptoPublicKey crypto.PublicKey) (PublicKey, error) {
+ switch cryptoPublicKey := cryptoPublicKey.(type) {
+ case *ecdsa.PublicKey:
+ return fromECPublicKey(cryptoPublicKey)
+ case *rsa.PublicKey:
+ return fromRSAPublicKey(cryptoPublicKey), nil
+ default:
+ return nil, fmt.Errorf("public key type %T is not supported", cryptoPublicKey)
+ }
+}
+
+// FromCryptoPrivateKey returns a libtrust PrivateKey representation of the given
+// *ecdsa.PrivateKey or *rsa.PrivateKey. Returns a non-nil error when the given
+// key is of an unsupported type.
+func FromCryptoPrivateKey(cryptoPrivateKey crypto.PrivateKey) (PrivateKey, error) {
+ switch cryptoPrivateKey := cryptoPrivateKey.(type) {
+ case *ecdsa.PrivateKey:
+ return fromECPrivateKey(cryptoPrivateKey)
+ case *rsa.PrivateKey:
+ return fromRSAPrivateKey(cryptoPrivateKey), nil
+ default:
+ return nil, fmt.Errorf("private key type %T is not supported", cryptoPrivateKey)
+ }
+}
+
+// UnmarshalPublicKeyPEM parses the PEM encoded data and returns a libtrust
+// PublicKey or an error if there is a problem with the encoding.
+func UnmarshalPublicKeyPEM(data []byte) (PublicKey, error) {
+ pemBlock, _ := pem.Decode(data)
+ if pemBlock == nil {
+ return nil, errors.New("unable to find PEM encoded data")
+ } else if pemBlock.Type != "PUBLIC KEY" {
+ return nil, fmt.Errorf("unable to get PublicKey from PEM type: %s", pemBlock.Type)
+ }
+
+ return pubKeyFromPEMBlock(pemBlock)
+}
+
+// UnmarshalPublicKeyPEMBundle parses the PEM encoded data as a bundle of
+// PEM blocks appended one after the other and returns a slice of PublicKey
+// objects that it finds.
+func UnmarshalPublicKeyPEMBundle(data []byte) ([]PublicKey, error) {
+ pubKeys := []PublicKey{}
+
+ for {
+ var pemBlock *pem.Block
+ pemBlock, data = pem.Decode(data)
+ if pemBlock == nil {
+ break
+ } else if pemBlock.Type != "PUBLIC KEY" {
+ return nil, fmt.Errorf("unable to get PublicKey from PEM type: %s", pemBlock.Type)
+ }
+
+ pubKey, err := pubKeyFromPEMBlock(pemBlock)
+ if err != nil {
+ return nil, err
+ }
+
+ pubKeys = append(pubKeys, pubKey)
+ }
+
+ return pubKeys, nil
+}
+
+// UnmarshalPrivateKeyPEM parses the PEM encoded data and returns a libtrust
+// PrivateKey or an error if there is a problem with the encoding.
+func UnmarshalPrivateKeyPEM(data []byte) (PrivateKey, error) {
+ pemBlock, _ := pem.Decode(data)
+ if pemBlock == nil {
+ return nil, errors.New("unable to find PEM encoded data")
+ }
+
+ var key PrivateKey
+
+ switch {
+ case pemBlock.Type == "RSA PRIVATE KEY":
+ rsaPrivateKey, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("unable to decode RSA Private Key PEM data: %s", err)
+ }
+ key = fromRSAPrivateKey(rsaPrivateKey)
+ case pemBlock.Type == "EC PRIVATE KEY":
+ ecPrivateKey, err := x509.ParseECPrivateKey(pemBlock.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("unable to decode EC Private Key PEM data: %s", err)
+ }
+ key, err = fromECPrivateKey(ecPrivateKey)
+ if err != nil {
+ return nil, err
+ }
+ default:
+ return nil, fmt.Errorf("unable to get PrivateKey from PEM type: %s", pemBlock.Type)
+ }
+
+ addPEMHeadersToKey(pemBlock, key.PublicKey())
+
+ return key, nil
+}
+
+// UnmarshalPublicKeyJWK unmarshals the given JSON Web Key into a generic
+// Public Key to be used with libtrust.
+func UnmarshalPublicKeyJWK(data []byte) (PublicKey, error) {
+ jwk := make(map[string]interface{})
+
+ err := json.Unmarshal(data, &jwk)
+ if err != nil {
+ return nil, fmt.Errorf(
+ "decoding JWK Public Key JSON data: %s\n", err,
+ )
+ }
+
+ // Get the Key Type value.
+ kty, err := stringFromMap(jwk, "kty")
+ if err != nil {
+ return nil, fmt.Errorf("JWK Public Key type: %s", err)
+ }
+
+ switch {
+ case kty == "EC":
+ // Call out to unmarshal EC public key.
+ return ecPublicKeyFromMap(jwk)
+ case kty == "RSA":
+ // Call out to unmarshal RSA public key.
+ return rsaPublicKeyFromMap(jwk)
+ default:
+ return nil, fmt.Errorf(
+ "JWK Public Key type not supported: %q\n", kty,
+ )
+ }
+}
+
+// UnmarshalPublicKeyJWKSet parses the JSON encoded data as a JSON Web Key Set
+// and returns a slice of Public Key objects.
+func UnmarshalPublicKeyJWKSet(data []byte) ([]PublicKey, error) {
+ rawKeys, err := loadJSONKeySetRaw(data)
+ if err != nil {
+ return nil, err
+ }
+
+ pubKeys := make([]PublicKey, 0, len(rawKeys))
+
+ for _, rawKey := range rawKeys {
+ pubKey, err := UnmarshalPublicKeyJWK(rawKey)
+ if err != nil {
+ return nil, err
+ }
+ pubKeys = append(pubKeys, pubKey)
+ }
+
+ return pubKeys, nil
+}
+
+// UnmarshalPrivateKeyJWK unmarshals the given JSON Web Key into a generic
+// Private Key to be used with libtrust.
+func UnmarshalPrivateKeyJWK(data []byte) (PrivateKey, error) {
+ jwk := make(map[string]interface{})
+
+ err := json.Unmarshal(data, &jwk)
+ if err != nil {
+ return nil, fmt.Errorf(
+ "decoding JWK Private Key JSON data: %s\n", err,
+ )
+ }
+
+ // Get the Key Type value.
+ kty, err := stringFromMap(jwk, "kty")
+ if err != nil {
+ return nil, fmt.Errorf("JWK Private Key type: %s", err)
+ }
+
+ switch {
+ case kty == "EC":
+ // Call out to unmarshal EC private key.
+ return ecPrivateKeyFromMap(jwk)
+ case kty == "RSA":
+ // Call out to unmarshal RSA private key.
+ return rsaPrivateKeyFromMap(jwk)
+ default:
+ return nil, fmt.Errorf(
+ "JWK Private Key type not supported: %q\n", kty,
+ )
+ }
+}
diff --git a/vendor/github.com/docker/libtrust/key_files.go b/vendor/github.com/docker/libtrust/key_files.go
new file mode 100644
index 0000000..c526de5
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/key_files.go
@@ -0,0 +1,255 @@
+package libtrust
+
+import (
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "strings"
+)
+
+var (
+ // ErrKeyFileDoesNotExist indicates that the private key file does not exist.
+ ErrKeyFileDoesNotExist = errors.New("key file does not exist")
+)
+
+func readKeyFileBytes(filename string) ([]byte, error) {
+ data, err := ioutil.ReadFile(filename)
+ if err != nil {
+ if os.IsNotExist(err) {
+ err = ErrKeyFileDoesNotExist
+ } else {
+ err = fmt.Errorf("unable to read key file %s: %s", filename, err)
+ }
+
+ return nil, err
+ }
+
+ return data, nil
+}
+
+/*
+ Loading and Saving of Public and Private Keys in either PEM or JWK format.
+*/
+
+// LoadKeyFile opens the given filename and attempts to read a Private Key
+// encoded in either PEM or JWK format (if .json or .jwk file extension).
+func LoadKeyFile(filename string) (PrivateKey, error) {
+ contents, err := readKeyFileBytes(filename)
+ if err != nil {
+ return nil, err
+ }
+
+ var key PrivateKey
+
+ if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") {
+ key, err = UnmarshalPrivateKeyJWK(contents)
+ if err != nil {
+ return nil, fmt.Errorf("unable to decode private key JWK: %s", err)
+ }
+ } else {
+ key, err = UnmarshalPrivateKeyPEM(contents)
+ if err != nil {
+ return nil, fmt.Errorf("unable to decode private key PEM: %s", err)
+ }
+ }
+
+ return key, nil
+}
+
+// LoadPublicKeyFile opens the given filename and attempts to read a Public Key
+// encoded in either PEM or JWK format (if .json or .jwk file extension).
+func LoadPublicKeyFile(filename string) (PublicKey, error) {
+ contents, err := readKeyFileBytes(filename)
+ if err != nil {
+ return nil, err
+ }
+
+ var key PublicKey
+
+ if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") {
+ key, err = UnmarshalPublicKeyJWK(contents)
+ if err != nil {
+ return nil, fmt.Errorf("unable to decode public key JWK: %s", err)
+ }
+ } else {
+ key, err = UnmarshalPublicKeyPEM(contents)
+ if err != nil {
+ return nil, fmt.Errorf("unable to decode public key PEM: %s", err)
+ }
+ }
+
+ return key, nil
+}
+
+// SaveKey saves the given key to a file using the provided filename.
+// This process will overwrite any existing file at the provided location.
+func SaveKey(filename string, key PrivateKey) error {
+ var encodedKey []byte
+ var err error
+
+ if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") {
+ // Encode in JSON Web Key format.
+ encodedKey, err = json.MarshalIndent(key, "", " ")
+ if err != nil {
+ return fmt.Errorf("unable to encode private key JWK: %s", err)
+ }
+ } else {
+ // Encode in PEM format.
+ pemBlock, err := key.PEMBlock()
+ if err != nil {
+ return fmt.Errorf("unable to encode private key PEM: %s", err)
+ }
+ encodedKey = pem.EncodeToMemory(pemBlock)
+ }
+
+ err = ioutil.WriteFile(filename, encodedKey, os.FileMode(0600))
+ if err != nil {
+ return fmt.Errorf("unable to write private key file %s: %s", filename, err)
+ }
+
+ return nil
+}
+
+// SavePublicKey saves the given public key to the file.
+func SavePublicKey(filename string, key PublicKey) error {
+ var encodedKey []byte
+ var err error
+
+ if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") {
+ // Encode in JSON Web Key format.
+ encodedKey, err = json.MarshalIndent(key, "", " ")
+ if err != nil {
+ return fmt.Errorf("unable to encode public key JWK: %s", err)
+ }
+ } else {
+ // Encode in PEM format.
+ pemBlock, err := key.PEMBlock()
+ if err != nil {
+ return fmt.Errorf("unable to encode public key PEM: %s", err)
+ }
+ encodedKey = pem.EncodeToMemory(pemBlock)
+ }
+
+ err = ioutil.WriteFile(filename, encodedKey, os.FileMode(0644))
+ if err != nil {
+ return fmt.Errorf("unable to write public key file %s: %s", filename, err)
+ }
+
+ return nil
+}
+
+// Public Key Set files
+
+type jwkSet struct {
+ Keys []json.RawMessage `json:"keys"`
+}
+
+// LoadKeySetFile loads a key set
+func LoadKeySetFile(filename string) ([]PublicKey, error) {
+ if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") {
+ return loadJSONKeySetFile(filename)
+ }
+
+ // Must be a PEM format file
+ return loadPEMKeySetFile(filename)
+}
+
+func loadJSONKeySetRaw(data []byte) ([]json.RawMessage, error) {
+ if len(data) == 0 {
+ // This is okay, just return an empty slice.
+ return []json.RawMessage{}, nil
+ }
+
+ keySet := jwkSet{}
+
+ err := json.Unmarshal(data, &keySet)
+ if err != nil {
+ return nil, fmt.Errorf("unable to decode JSON Web Key Set: %s", err)
+ }
+
+ return keySet.Keys, nil
+}
+
+func loadJSONKeySetFile(filename string) ([]PublicKey, error) {
+ contents, err := readKeyFileBytes(filename)
+ if err != nil && err != ErrKeyFileDoesNotExist {
+ return nil, err
+ }
+
+ return UnmarshalPublicKeyJWKSet(contents)
+}
+
+func loadPEMKeySetFile(filename string) ([]PublicKey, error) {
+ data, err := readKeyFileBytes(filename)
+ if err != nil && err != ErrKeyFileDoesNotExist {
+ return nil, err
+ }
+
+ return UnmarshalPublicKeyPEMBundle(data)
+}
+
+// AddKeySetFile adds a key to a key set
+func AddKeySetFile(filename string, key PublicKey) error {
+ if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") {
+ return addKeySetJSONFile(filename, key)
+ }
+
+ // Must be a PEM format file
+ return addKeySetPEMFile(filename, key)
+}
+
+func addKeySetJSONFile(filename string, key PublicKey) error {
+ encodedKey, err := json.Marshal(key)
+ if err != nil {
+ return fmt.Errorf("unable to encode trusted client key: %s", err)
+ }
+
+ contents, err := readKeyFileBytes(filename)
+ if err != nil && err != ErrKeyFileDoesNotExist {
+ return err
+ }
+
+ rawEntries, err := loadJSONKeySetRaw(contents)
+ if err != nil {
+ return err
+ }
+
+ rawEntries = append(rawEntries, json.RawMessage(encodedKey))
+ entriesWrapper := jwkSet{Keys: rawEntries}
+
+ encodedEntries, err := json.MarshalIndent(entriesWrapper, "", " ")
+ if err != nil {
+ return fmt.Errorf("unable to encode trusted client keys: %s", err)
+ }
+
+ err = ioutil.WriteFile(filename, encodedEntries, os.FileMode(0644))
+ if err != nil {
+ return fmt.Errorf("unable to write trusted client keys file %s: %s", filename, err)
+ }
+
+ return nil
+}
+
+func addKeySetPEMFile(filename string, key PublicKey) error {
+ // Encode to PEM, open file for appending, write PEM.
+ file, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_RDWR, os.FileMode(0644))
+ if err != nil {
+ return fmt.Errorf("unable to open trusted client keys file %s: %s", filename, err)
+ }
+ defer file.Close()
+
+ pemBlock, err := key.PEMBlock()
+ if err != nil {
+ return fmt.Errorf("unable to encoded trusted key: %s", err)
+ }
+
+ _, err = file.Write(pem.EncodeToMemory(pemBlock))
+ if err != nil {
+ return fmt.Errorf("unable to write trusted keys file: %s", err)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/libtrust/key_manager.go b/vendor/github.com/docker/libtrust/key_manager.go
new file mode 100644
index 0000000..9a98ae3
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/key_manager.go
@@ -0,0 +1,175 @@
+package libtrust
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "fmt"
+ "io/ioutil"
+ "net"
+ "os"
+ "path"
+ "sync"
+)
+
+// ClientKeyManager manages client keys on the filesystem
+type ClientKeyManager struct {
+ key PrivateKey
+ clientFile string
+ clientDir string
+
+ clientLock sync.RWMutex
+ clients []PublicKey
+
+ configLock sync.Mutex
+ configs []*tls.Config
+}
+
+// NewClientKeyManager loads a new manager from a set of key files
+// and managed by the given private key.
+func NewClientKeyManager(trustKey PrivateKey, clientFile, clientDir string) (*ClientKeyManager, error) {
+ m := &ClientKeyManager{
+ key: trustKey,
+ clientFile: clientFile,
+ clientDir: clientDir,
+ }
+ if err := m.loadKeys(); err != nil {
+ return nil, err
+ }
+ // TODO Start watching file and directory
+
+ return m, nil
+}
+
+func (c *ClientKeyManager) loadKeys() (err error) {
+ // Load authorized keys file
+ var clients []PublicKey
+ if c.clientFile != "" {
+ clients, err = LoadKeySetFile(c.clientFile)
+ if err != nil {
+ return fmt.Errorf("unable to load authorized keys: %s", err)
+ }
+ }
+
+ // Add clients from authorized keys directory
+ files, err := ioutil.ReadDir(c.clientDir)
+ if err != nil && !os.IsNotExist(err) {
+ return fmt.Errorf("unable to open authorized keys directory: %s", err)
+ }
+ for _, f := range files {
+ if !f.IsDir() {
+ publicKey, err := LoadPublicKeyFile(path.Join(c.clientDir, f.Name()))
+ if err != nil {
+ return fmt.Errorf("unable to load authorized key file: %s", err)
+ }
+ clients = append(clients, publicKey)
+ }
+ }
+
+ c.clientLock.Lock()
+ c.clients = clients
+ c.clientLock.Unlock()
+
+ return nil
+}
+
+// RegisterTLSConfig registers a tls configuration to manager
+// such that any changes to the keys may be reflected in
+// the tls client CA pool
+func (c *ClientKeyManager) RegisterTLSConfig(tlsConfig *tls.Config) error {
+ c.clientLock.RLock()
+ certPool, err := GenerateCACertPool(c.key, c.clients)
+ if err != nil {
+ return fmt.Errorf("CA pool generation error: %s", err)
+ }
+ c.clientLock.RUnlock()
+
+ tlsConfig.ClientCAs = certPool
+
+ c.configLock.Lock()
+ c.configs = append(c.configs, tlsConfig)
+ c.configLock.Unlock()
+
+ return nil
+}
+
+// NewIdentityAuthTLSConfig creates a tls.Config for the server to use for
+// libtrust identity authentication for the domain specified
+func NewIdentityAuthTLSConfig(trustKey PrivateKey, clients *ClientKeyManager, addr string, domain string) (*tls.Config, error) {
+ tlsConfig := newTLSConfig()
+
+ tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
+ if err := clients.RegisterTLSConfig(tlsConfig); err != nil {
+ return nil, err
+ }
+
+ // Generate cert
+ ips, domains, err := parseAddr(addr)
+ if err != nil {
+ return nil, err
+ }
+ // add domain that it expects clients to use
+ domains = append(domains, domain)
+ x509Cert, err := GenerateSelfSignedServerCert(trustKey, domains, ips)
+ if err != nil {
+ return nil, fmt.Errorf("certificate generation error: %s", err)
+ }
+ tlsConfig.Certificates = []tls.Certificate{{
+ Certificate: [][]byte{x509Cert.Raw},
+ PrivateKey: trustKey.CryptoPrivateKey(),
+ Leaf: x509Cert,
+ }}
+
+ return tlsConfig, nil
+}
+
+// NewCertAuthTLSConfig creates a tls.Config for the server to use for
+// certificate authentication
+func NewCertAuthTLSConfig(caPath, certPath, keyPath string) (*tls.Config, error) {
+ tlsConfig := newTLSConfig()
+
+ cert, err := tls.LoadX509KeyPair(certPath, keyPath)
+ if err != nil {
+ return nil, fmt.Errorf("Couldn't load X509 key pair (%s, %s): %s. Key encrypted?", certPath, keyPath, err)
+ }
+ tlsConfig.Certificates = []tls.Certificate{cert}
+
+ // Verify client certificates against a CA?
+ if caPath != "" {
+ certPool := x509.NewCertPool()
+ file, err := ioutil.ReadFile(caPath)
+ if err != nil {
+ return nil, fmt.Errorf("Couldn't read CA certificate: %s", err)
+ }
+ certPool.AppendCertsFromPEM(file)
+
+ tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
+ tlsConfig.ClientCAs = certPool
+ }
+
+ return tlsConfig, nil
+}
+
+func newTLSConfig() *tls.Config {
+ return &tls.Config{
+ NextProtos: []string{"http/1.1"},
+ // Avoid fallback on insecure SSL protocols
+ MinVersion: tls.VersionTLS10,
+ }
+}
+
+// parseAddr parses an address into an array of IPs and domains
+func parseAddr(addr string) ([]net.IP, []string, error) {
+ host, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ return nil, nil, err
+ }
+ var domains []string
+ var ips []net.IP
+ ip := net.ParseIP(host)
+ if ip != nil {
+ ips = []net.IP{ip}
+ } else {
+ domains = []string{host}
+ }
+ return ips, domains, nil
+}
diff --git a/vendor/github.com/docker/libtrust/rsa_key.go b/vendor/github.com/docker/libtrust/rsa_key.go
new file mode 100644
index 0000000..dac4cac
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/rsa_key.go
@@ -0,0 +1,427 @@
+package libtrust
+
+import (
+ "crypto"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/x509"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "math/big"
+)
+
+/*
+ * RSA DSA PUBLIC KEY
+ */
+
+// rsaPublicKey implements a JWK Public Key using RSA digital signature algorithms.
+type rsaPublicKey struct {
+ *rsa.PublicKey
+ extended map[string]interface{}
+}
+
+func fromRSAPublicKey(cryptoPublicKey *rsa.PublicKey) *rsaPublicKey {
+ return &rsaPublicKey{cryptoPublicKey, map[string]interface{}{}}
+}
+
+// KeyType returns the JWK key type for RSA keys, i.e., "RSA".
+func (k *rsaPublicKey) KeyType() string {
+ return "RSA"
+}
+
+// KeyID returns a distinct identifier which is unique to this Public Key.
+func (k *rsaPublicKey) KeyID() string {
+ return keyIDFromCryptoKey(k)
+}
+
+func (k *rsaPublicKey) String() string {
+ return fmt.Sprintf("RSA Public Key <%s>", k.KeyID())
+}
+
+// Verify verifyies the signature of the data in the io.Reader using this Public Key.
+// The alg parameter should be the name of the JWA digital signature algorithm
+// which was used to produce the signature and should be supported by this
+// public key. Returns a nil error if the signature is valid.
+func (k *rsaPublicKey) Verify(data io.Reader, alg string, signature []byte) error {
+ // Verify the signature of the given date, return non-nil error if valid.
+ sigAlg, err := rsaSignatureAlgorithmByName(alg)
+ if err != nil {
+ return fmt.Errorf("unable to verify Signature: %s", err)
+ }
+
+ hasher := sigAlg.HashID().New()
+ _, err = io.Copy(hasher, data)
+ if err != nil {
+ return fmt.Errorf("error reading data to sign: %s", err)
+ }
+ hash := hasher.Sum(nil)
+
+ err = rsa.VerifyPKCS1v15(k.PublicKey, sigAlg.HashID(), hash, signature)
+ if err != nil {
+ return fmt.Errorf("invalid %s signature: %s", sigAlg.HeaderParam(), err)
+ }
+
+ return nil
+}
+
+// CryptoPublicKey returns the internal object which can be used as a
+// crypto.PublicKey for use with other standard library operations. The type
+// is either *rsa.PublicKey or *ecdsa.PublicKey
+func (k *rsaPublicKey) CryptoPublicKey() crypto.PublicKey {
+ return k.PublicKey
+}
+
+func (k *rsaPublicKey) toMap() map[string]interface{} {
+ jwk := make(map[string]interface{})
+ for k, v := range k.extended {
+ jwk[k] = v
+ }
+ jwk["kty"] = k.KeyType()
+ jwk["kid"] = k.KeyID()
+ jwk["n"] = joseBase64UrlEncode(k.N.Bytes())
+ jwk["e"] = joseBase64UrlEncode(serializeRSAPublicExponentParam(k.E))
+
+ return jwk
+}
+
+// MarshalJSON serializes this Public Key using the JWK JSON serialization format for
+// RSA keys.
+func (k *rsaPublicKey) MarshalJSON() (data []byte, err error) {
+ return json.Marshal(k.toMap())
+}
+
+// PEMBlock serializes this Public Key to DER-encoded PKIX format.
+func (k *rsaPublicKey) PEMBlock() (*pem.Block, error) {
+ derBytes, err := x509.MarshalPKIXPublicKey(k.PublicKey)
+ if err != nil {
+ return nil, fmt.Errorf("unable to serialize RSA PublicKey to DER-encoded PKIX format: %s", err)
+ }
+ k.extended["kid"] = k.KeyID() // For display purposes.
+ return createPemBlock("PUBLIC KEY", derBytes, k.extended)
+}
+
+func (k *rsaPublicKey) AddExtendedField(field string, value interface{}) {
+ k.extended[field] = value
+}
+
+func (k *rsaPublicKey) GetExtendedField(field string) interface{} {
+ v, ok := k.extended[field]
+ if !ok {
+ return nil
+ }
+ return v
+}
+
+func rsaPublicKeyFromMap(jwk map[string]interface{}) (*rsaPublicKey, error) {
+ // JWK key type (kty) has already been determined to be "RSA".
+ // Need to extract 'n', 'e', and 'kid' and check for
+ // consistency.
+
+ // Get the modulus parameter N.
+ nB64Url, err := stringFromMap(jwk, "n")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Public Key modulus: %s", err)
+ }
+
+ n, err := parseRSAModulusParam(nB64Url)
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Public Key modulus: %s", err)
+ }
+
+ // Get the public exponent E.
+ eB64Url, err := stringFromMap(jwk, "e")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Public Key exponent: %s", err)
+ }
+
+ e, err := parseRSAPublicExponentParam(eB64Url)
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Public Key exponent: %s", err)
+ }
+
+ key := &rsaPublicKey{
+ PublicKey: &rsa.PublicKey{N: n, E: e},
+ }
+
+ // Key ID is optional, but if it exists, it should match the key.
+ _, ok := jwk["kid"]
+ if ok {
+ kid, err := stringFromMap(jwk, "kid")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Public Key ID: %s", err)
+ }
+ if kid != key.KeyID() {
+ return nil, fmt.Errorf("JWK RSA Public Key ID does not match: %s", kid)
+ }
+ }
+
+ if _, ok := jwk["d"]; ok {
+ return nil, fmt.Errorf("JWK RSA Public Key cannot contain private exponent")
+ }
+
+ key.extended = jwk
+
+ return key, nil
+}
+
+/*
+ * RSA DSA PRIVATE KEY
+ */
+
+// rsaPrivateKey implements a JWK Private Key using RSA digital signature algorithms.
+type rsaPrivateKey struct {
+ rsaPublicKey
+ *rsa.PrivateKey
+}
+
+func fromRSAPrivateKey(cryptoPrivateKey *rsa.PrivateKey) *rsaPrivateKey {
+ return &rsaPrivateKey{
+ *fromRSAPublicKey(&cryptoPrivateKey.PublicKey),
+ cryptoPrivateKey,
+ }
+}
+
+// PublicKey returns the Public Key data associated with this Private Key.
+func (k *rsaPrivateKey) PublicKey() PublicKey {
+ return &k.rsaPublicKey
+}
+
+func (k *rsaPrivateKey) String() string {
+ return fmt.Sprintf("RSA Private Key <%s>", k.KeyID())
+}
+
+// Sign signs the data read from the io.Reader using a signature algorithm supported
+// by the RSA private key. If the specified hashing algorithm is supported by
+// this key, that hash function is used to generate the signature otherwise the
+// the default hashing algorithm for this key is used. Returns the signature
+// and the name of the JWK signature algorithm used, e.g., "RS256", "RS384",
+// "RS512".
+func (k *rsaPrivateKey) Sign(data io.Reader, hashID crypto.Hash) (signature []byte, alg string, err error) {
+ // Generate a signature of the data using the internal alg.
+ sigAlg := rsaPKCS1v15SignatureAlgorithmForHashID(hashID)
+ hasher := sigAlg.HashID().New()
+
+ _, err = io.Copy(hasher, data)
+ if err != nil {
+ return nil, "", fmt.Errorf("error reading data to sign: %s", err)
+ }
+ hash := hasher.Sum(nil)
+
+ signature, err = rsa.SignPKCS1v15(rand.Reader, k.PrivateKey, sigAlg.HashID(), hash)
+ if err != nil {
+ return nil, "", fmt.Errorf("error producing signature: %s", err)
+ }
+
+ alg = sigAlg.HeaderParam()
+
+ return
+}
+
+// CryptoPrivateKey returns the internal object which can be used as a
+// crypto.PublicKey for use with other standard library operations. The type
+// is either *rsa.PublicKey or *ecdsa.PublicKey
+func (k *rsaPrivateKey) CryptoPrivateKey() crypto.PrivateKey {
+ return k.PrivateKey
+}
+
+func (k *rsaPrivateKey) toMap() map[string]interface{} {
+ k.Precompute() // Make sure the precomputed values are stored.
+ jwk := k.rsaPublicKey.toMap()
+
+ jwk["d"] = joseBase64UrlEncode(k.D.Bytes())
+ jwk["p"] = joseBase64UrlEncode(k.Primes[0].Bytes())
+ jwk["q"] = joseBase64UrlEncode(k.Primes[1].Bytes())
+ jwk["dp"] = joseBase64UrlEncode(k.Precomputed.Dp.Bytes())
+ jwk["dq"] = joseBase64UrlEncode(k.Precomputed.Dq.Bytes())
+ jwk["qi"] = joseBase64UrlEncode(k.Precomputed.Qinv.Bytes())
+
+ otherPrimes := k.Primes[2:]
+
+ if len(otherPrimes) > 0 {
+ otherPrimesInfo := make([]interface{}, len(otherPrimes))
+ for i, r := range otherPrimes {
+ otherPrimeInfo := make(map[string]string, 3)
+ otherPrimeInfo["r"] = joseBase64UrlEncode(r.Bytes())
+ crtVal := k.Precomputed.CRTValues[i]
+ otherPrimeInfo["d"] = joseBase64UrlEncode(crtVal.Exp.Bytes())
+ otherPrimeInfo["t"] = joseBase64UrlEncode(crtVal.Coeff.Bytes())
+ otherPrimesInfo[i] = otherPrimeInfo
+ }
+ jwk["oth"] = otherPrimesInfo
+ }
+
+ return jwk
+}
+
+// MarshalJSON serializes this Private Key using the JWK JSON serialization format for
+// RSA keys.
+func (k *rsaPrivateKey) MarshalJSON() (data []byte, err error) {
+ return json.Marshal(k.toMap())
+}
+
+// PEMBlock serializes this Private Key to DER-encoded PKIX format.
+func (k *rsaPrivateKey) PEMBlock() (*pem.Block, error) {
+ derBytes := x509.MarshalPKCS1PrivateKey(k.PrivateKey)
+ k.extended["keyID"] = k.KeyID() // For display purposes.
+ return createPemBlock("RSA PRIVATE KEY", derBytes, k.extended)
+}
+
+func rsaPrivateKeyFromMap(jwk map[string]interface{}) (*rsaPrivateKey, error) {
+ // The JWA spec for RSA Private Keys (draft rfc section 5.3.2) states that
+ // only the private key exponent 'd' is REQUIRED, the others are just for
+ // signature/decryption optimizations and SHOULD be included when the JWK
+ // is produced. We MAY choose to accept a JWK which only includes 'd', but
+ // we're going to go ahead and not choose to accept it without the extra
+ // fields. Only the 'oth' field will be optional (for multi-prime keys).
+ privateExponent, err := parseRSAPrivateKeyParamFromMap(jwk, "d")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Private Key exponent: %s", err)
+ }
+ firstPrimeFactor, err := parseRSAPrivateKeyParamFromMap(jwk, "p")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err)
+ }
+ secondPrimeFactor, err := parseRSAPrivateKeyParamFromMap(jwk, "q")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err)
+ }
+ firstFactorCRT, err := parseRSAPrivateKeyParamFromMap(jwk, "dp")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err)
+ }
+ secondFactorCRT, err := parseRSAPrivateKeyParamFromMap(jwk, "dq")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err)
+ }
+ crtCoeff, err := parseRSAPrivateKeyParamFromMap(jwk, "qi")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Private Key CRT coefficient: %s", err)
+ }
+
+ var oth interface{}
+ if _, ok := jwk["oth"]; ok {
+ oth = jwk["oth"]
+ delete(jwk, "oth")
+ }
+
+ // JWK key type (kty) has already been determined to be "RSA".
+ // Need to extract the public key information, then extract the private
+ // key values.
+ publicKey, err := rsaPublicKeyFromMap(jwk)
+ if err != nil {
+ return nil, err
+ }
+
+ privateKey := &rsa.PrivateKey{
+ PublicKey: *publicKey.PublicKey,
+ D: privateExponent,
+ Primes: []*big.Int{firstPrimeFactor, secondPrimeFactor},
+ Precomputed: rsa.PrecomputedValues{
+ Dp: firstFactorCRT,
+ Dq: secondFactorCRT,
+ Qinv: crtCoeff,
+ },
+ }
+
+ if oth != nil {
+ // Should be an array of more JSON objects.
+ otherPrimesInfo, ok := oth.([]interface{})
+ if !ok {
+ return nil, errors.New("JWK RSA Private Key: Invalid other primes info: must be an array")
+ }
+ numOtherPrimeFactors := len(otherPrimesInfo)
+ if numOtherPrimeFactors == 0 {
+ return nil, errors.New("JWK RSA Privake Key: Invalid other primes info: must be absent or non-empty")
+ }
+ otherPrimeFactors := make([]*big.Int, numOtherPrimeFactors)
+ productOfPrimes := new(big.Int).Mul(firstPrimeFactor, secondPrimeFactor)
+ crtValues := make([]rsa.CRTValue, numOtherPrimeFactors)
+
+ for i, val := range otherPrimesInfo {
+ otherPrimeinfo, ok := val.(map[string]interface{})
+ if !ok {
+ return nil, errors.New("JWK RSA Private Key: Invalid other prime info: must be a JSON object")
+ }
+
+ otherPrimeFactor, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "r")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err)
+ }
+ otherFactorCRT, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "d")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err)
+ }
+ otherCrtCoeff, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "t")
+ if err != nil {
+ return nil, fmt.Errorf("JWK RSA Private Key CRT coefficient: %s", err)
+ }
+
+ crtValue := crtValues[i]
+ crtValue.Exp = otherFactorCRT
+ crtValue.Coeff = otherCrtCoeff
+ crtValue.R = productOfPrimes
+ otherPrimeFactors[i] = otherPrimeFactor
+ productOfPrimes = new(big.Int).Mul(productOfPrimes, otherPrimeFactor)
+ }
+
+ privateKey.Primes = append(privateKey.Primes, otherPrimeFactors...)
+ privateKey.Precomputed.CRTValues = crtValues
+ }
+
+ key := &rsaPrivateKey{
+ rsaPublicKey: *publicKey,
+ PrivateKey: privateKey,
+ }
+
+ return key, nil
+}
+
+/*
+ * Key Generation Functions.
+ */
+
+func generateRSAPrivateKey(bits int) (k *rsaPrivateKey, err error) {
+ k = new(rsaPrivateKey)
+ k.PrivateKey, err = rsa.GenerateKey(rand.Reader, bits)
+ if err != nil {
+ return nil, err
+ }
+
+ k.rsaPublicKey.PublicKey = &k.PrivateKey.PublicKey
+ k.extended = make(map[string]interface{})
+
+ return
+}
+
+// GenerateRSA2048PrivateKey generates a key pair using 2048-bit RSA.
+func GenerateRSA2048PrivateKey() (PrivateKey, error) {
+ k, err := generateRSAPrivateKey(2048)
+ if err != nil {
+ return nil, fmt.Errorf("error generating RSA 2048-bit key: %s", err)
+ }
+
+ return k, nil
+}
+
+// GenerateRSA3072PrivateKey generates a key pair using 3072-bit RSA.
+func GenerateRSA3072PrivateKey() (PrivateKey, error) {
+ k, err := generateRSAPrivateKey(3072)
+ if err != nil {
+ return nil, fmt.Errorf("error generating RSA 3072-bit key: %s", err)
+ }
+
+ return k, nil
+}
+
+// GenerateRSA4096PrivateKey generates a key pair using 4096-bit RSA.
+func GenerateRSA4096PrivateKey() (PrivateKey, error) {
+ k, err := generateRSAPrivateKey(4096)
+ if err != nil {
+ return nil, fmt.Errorf("error generating RSA 4096-bit key: %s", err)
+ }
+
+ return k, nil
+}
diff --git a/vendor/github.com/docker/libtrust/util.go b/vendor/github.com/docker/libtrust/util.go
new file mode 100644
index 0000000..d88176c
--- /dev/null
+++ b/vendor/github.com/docker/libtrust/util.go
@@ -0,0 +1,363 @@
+package libtrust
+
+import (
+ "bytes"
+ "crypto"
+ "crypto/elliptic"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/base32"
+ "encoding/base64"
+ "encoding/binary"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "math/big"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+// LoadOrCreateTrustKey will load a PrivateKey from the specified path
+func LoadOrCreateTrustKey(trustKeyPath string) (PrivateKey, error) {
+ if err := os.MkdirAll(filepath.Dir(trustKeyPath), 0700); err != nil {
+ return nil, err
+ }
+
+ trustKey, err := LoadKeyFile(trustKeyPath)
+ if err == ErrKeyFileDoesNotExist {
+ trustKey, err = GenerateECP256PrivateKey()
+ if err != nil {
+ return nil, fmt.Errorf("error generating key: %s", err)
+ }
+
+ if err := SaveKey(trustKeyPath, trustKey); err != nil {
+ return nil, fmt.Errorf("error saving key file: %s", err)
+ }
+
+ dir, file := filepath.Split(trustKeyPath)
+ if err := SavePublicKey(filepath.Join(dir, "public-"+file), trustKey.PublicKey()); err != nil {
+ return nil, fmt.Errorf("error saving public key file: %s", err)
+ }
+ } else if err != nil {
+ return nil, fmt.Errorf("error loading key file: %s", err)
+ }
+ return trustKey, nil
+}
+
+// NewIdentityAuthTLSClientConfig returns a tls.Config configured to use identity
+// based authentication from the specified dockerUrl, the rootConfigPath and
+// the server name to which it is connecting.
+// If trustUnknownHosts is true it will automatically add the host to the
+// known-hosts.json in rootConfigPath.
+func NewIdentityAuthTLSClientConfig(dockerUrl string, trustUnknownHosts bool, rootConfigPath string, serverName string) (*tls.Config, error) {
+ tlsConfig := newTLSConfig()
+
+ trustKeyPath := filepath.Join(rootConfigPath, "key.json")
+ knownHostsPath := filepath.Join(rootConfigPath, "known-hosts.json")
+
+ u, err := url.Parse(dockerUrl)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse machine url")
+ }
+
+ if u.Scheme == "unix" {
+ return nil, nil
+ }
+
+ addr := u.Host
+ proto := "tcp"
+
+ trustKey, err := LoadOrCreateTrustKey(trustKeyPath)
+ if err != nil {
+ return nil, fmt.Errorf("unable to load trust key: %s", err)
+ }
+
+ knownHosts, err := LoadKeySetFile(knownHostsPath)
+ if err != nil {
+ return nil, fmt.Errorf("could not load trusted hosts file: %s", err)
+ }
+
+ allowedHosts, err := FilterByHosts(knownHosts, addr, false)
+ if err != nil {
+ return nil, fmt.Errorf("error filtering hosts: %s", err)
+ }
+
+ certPool, err := GenerateCACertPool(trustKey, allowedHosts)
+ if err != nil {
+ return nil, fmt.Errorf("Could not create CA pool: %s", err)
+ }
+
+ tlsConfig.ServerName = serverName
+ tlsConfig.RootCAs = certPool
+
+ x509Cert, err := GenerateSelfSignedClientCert(trustKey)
+ if err != nil {
+ return nil, fmt.Errorf("certificate generation error: %s", err)
+ }
+
+ tlsConfig.Certificates = []tls.Certificate{{
+ Certificate: [][]byte{x509Cert.Raw},
+ PrivateKey: trustKey.CryptoPrivateKey(),
+ Leaf: x509Cert,
+ }}
+
+ tlsConfig.InsecureSkipVerify = true
+
+ testConn, err := tls.Dial(proto, addr, tlsConfig)
+ if err != nil {
+ return nil, fmt.Errorf("tls Handshake error: %s", err)
+ }
+
+ opts := x509.VerifyOptions{
+ Roots: tlsConfig.RootCAs,
+ CurrentTime: time.Now(),
+ DNSName: tlsConfig.ServerName,
+ Intermediates: x509.NewCertPool(),
+ }
+
+ certs := testConn.ConnectionState().PeerCertificates
+ for i, cert := range certs {
+ if i == 0 {
+ continue
+ }
+ opts.Intermediates.AddCert(cert)
+ }
+
+ if _, err := certs[0].Verify(opts); err != nil {
+ if _, ok := err.(x509.UnknownAuthorityError); ok {
+ if trustUnknownHosts {
+ pubKey, err := FromCryptoPublicKey(certs[0].PublicKey)
+ if err != nil {
+ return nil, fmt.Errorf("error extracting public key from cert: %s", err)
+ }
+
+ pubKey.AddExtendedField("hosts", []string{addr})
+
+ if err := AddKeySetFile(knownHostsPath, pubKey); err != nil {
+ return nil, fmt.Errorf("error adding machine to known hosts: %s", err)
+ }
+ } else {
+ return nil, fmt.Errorf("unable to connect. unknown host: %s", addr)
+ }
+ }
+ }
+
+ testConn.Close()
+ tlsConfig.InsecureSkipVerify = false
+
+ return tlsConfig, nil
+}
+
+// joseBase64UrlEncode encodes the given data using the standard base64 url
+// encoding format but with all trailing '=' characters ommitted in accordance
+// with the jose specification.
+// http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-31#section-2
+func joseBase64UrlEncode(b []byte) string {
+ return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=")
+}
+
+// joseBase64UrlDecode decodes the given string using the standard base64 url
+// decoder but first adds the appropriate number of trailing '=' characters in
+// accordance with the jose specification.
+// http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-31#section-2
+func joseBase64UrlDecode(s string) ([]byte, error) {
+ s = strings.Replace(s, "\n", "", -1)
+ s = strings.Replace(s, " ", "", -1)
+ switch len(s) % 4 {
+ case 0:
+ case 2:
+ s += "=="
+ case 3:
+ s += "="
+ default:
+ return nil, errors.New("illegal base64url string")
+ }
+ return base64.URLEncoding.DecodeString(s)
+}
+
+func keyIDEncode(b []byte) string {
+ s := strings.TrimRight(base32.StdEncoding.EncodeToString(b), "=")
+ var buf bytes.Buffer
+ var i int
+ for i = 0; i < len(s)/4-1; i++ {
+ start := i * 4
+ end := start + 4
+ buf.WriteString(s[start:end] + ":")
+ }
+ buf.WriteString(s[i*4:])
+ return buf.String()
+}
+
+func keyIDFromCryptoKey(pubKey PublicKey) string {
+ // Generate and return a 'libtrust' fingerprint of the public key.
+ // For an RSA key this should be:
+ // SHA256(DER encoded ASN1)
+ // Then truncated to 240 bits and encoded into 12 base32 groups like so:
+ // ABCD:EFGH:IJKL:MNOP:QRST:UVWX:YZ23:4567:ABCD:EFGH:IJKL:MNOP
+ derBytes, err := x509.MarshalPKIXPublicKey(pubKey.CryptoPublicKey())
+ if err != nil {
+ return ""
+ }
+ hasher := crypto.SHA256.New()
+ hasher.Write(derBytes)
+ return keyIDEncode(hasher.Sum(nil)[:30])
+}
+
+func stringFromMap(m map[string]interface{}, key string) (string, error) {
+ val, ok := m[key]
+ if !ok {
+ return "", fmt.Errorf("%q value not specified", key)
+ }
+
+ str, ok := val.(string)
+ if !ok {
+ return "", fmt.Errorf("%q value must be a string", key)
+ }
+ delete(m, key)
+
+ return str, nil
+}
+
+func parseECCoordinate(cB64Url string, curve elliptic.Curve) (*big.Int, error) {
+ curveByteLen := (curve.Params().BitSize + 7) >> 3
+
+ cBytes, err := joseBase64UrlDecode(cB64Url)
+ if err != nil {
+ return nil, fmt.Errorf("invalid base64 URL encoding: %s", err)
+ }
+ cByteLength := len(cBytes)
+ if cByteLength != curveByteLen {
+ return nil, fmt.Errorf("invalid number of octets: got %d, should be %d", cByteLength, curveByteLen)
+ }
+ return new(big.Int).SetBytes(cBytes), nil
+}
+
+func parseECPrivateParam(dB64Url string, curve elliptic.Curve) (*big.Int, error) {
+ dBytes, err := joseBase64UrlDecode(dB64Url)
+ if err != nil {
+ return nil, fmt.Errorf("invalid base64 URL encoding: %s", err)
+ }
+
+ // The length of this octet string MUST be ceiling(log-base-2(n)/8)
+ // octets (where n is the order of the curve). This is because the private
+ // key d must be in the interval [1, n-1] so the bitlength of d should be
+ // no larger than the bitlength of n-1. The easiest way to find the octet
+ // length is to take bitlength(n-1), add 7 to force a carry, and shift this
+ // bit sequence right by 3, which is essentially dividing by 8 and adding
+ // 1 if there is any remainder. Thus, the private key value d should be
+ // output to (bitlength(n-1)+7)>>3 octets.
+ n := curve.Params().N
+ octetLength := (new(big.Int).Sub(n, big.NewInt(1)).BitLen() + 7) >> 3
+ dByteLength := len(dBytes)
+
+ if dByteLength != octetLength {
+ return nil, fmt.Errorf("invalid number of octets: got %d, should be %d", dByteLength, octetLength)
+ }
+
+ return new(big.Int).SetBytes(dBytes), nil
+}
+
+func parseRSAModulusParam(nB64Url string) (*big.Int, error) {
+ nBytes, err := joseBase64UrlDecode(nB64Url)
+ if err != nil {
+ return nil, fmt.Errorf("invalid base64 URL encoding: %s", err)
+ }
+
+ return new(big.Int).SetBytes(nBytes), nil
+}
+
+func serializeRSAPublicExponentParam(e int) []byte {
+ // We MUST use the minimum number of octets to represent E.
+ // E is supposed to be 65537 for performance and security reasons
+ // and is what golang's rsa package generates, but it might be
+ // different if imported from some other generator.
+ buf := make([]byte, 4)
+ binary.BigEndian.PutUint32(buf, uint32(e))
+ var i int
+ for i = 0; i < 8; i++ {
+ if buf[i] != 0 {
+ break
+ }
+ }
+ return buf[i:]
+}
+
+func parseRSAPublicExponentParam(eB64Url string) (int, error) {
+ eBytes, err := joseBase64UrlDecode(eB64Url)
+ if err != nil {
+ return 0, fmt.Errorf("invalid base64 URL encoding: %s", err)
+ }
+ // Only the minimum number of bytes were used to represent E, but
+ // binary.BigEndian.Uint32 expects at least 4 bytes, so we need
+ // to add zero padding if necassary.
+ byteLen := len(eBytes)
+ buf := make([]byte, 4-byteLen, 4)
+ eBytes = append(buf, eBytes...)
+
+ return int(binary.BigEndian.Uint32(eBytes)), nil
+}
+
+func parseRSAPrivateKeyParamFromMap(m map[string]interface{}, key string) (*big.Int, error) {
+ b64Url, err := stringFromMap(m, key)
+ if err != nil {
+ return nil, err
+ }
+
+ paramBytes, err := joseBase64UrlDecode(b64Url)
+ if err != nil {
+ return nil, fmt.Errorf("invaled base64 URL encoding: %s", err)
+ }
+
+ return new(big.Int).SetBytes(paramBytes), nil
+}
+
+func createPemBlock(name string, derBytes []byte, headers map[string]interface{}) (*pem.Block, error) {
+ pemBlock := &pem.Block{Type: name, Bytes: derBytes, Headers: map[string]string{}}
+ for k, v := range headers {
+ switch val := v.(type) {
+ case string:
+ pemBlock.Headers[k] = val
+ case []string:
+ if k == "hosts" {
+ pemBlock.Headers[k] = strings.Join(val, ",")
+ } else {
+ // Return error, non-encodable type
+ }
+ default:
+ // Return error, non-encodable type
+ }
+ }
+
+ return pemBlock, nil
+}
+
+func pubKeyFromPEMBlock(pemBlock *pem.Block) (PublicKey, error) {
+ cryptoPublicKey, err := x509.ParsePKIXPublicKey(pemBlock.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("unable to decode Public Key PEM data: %s", err)
+ }
+
+ pubKey, err := FromCryptoPublicKey(cryptoPublicKey)
+ if err != nil {
+ return nil, err
+ }
+
+ addPEMHeadersToKey(pemBlock, pubKey)
+
+ return pubKey, nil
+}
+
+func addPEMHeadersToKey(pemBlock *pem.Block, pubKey PublicKey) {
+ for key, value := range pemBlock.Headers {
+ var safeVal interface{}
+ if key == "hosts" {
+ safeVal = strings.Split(value, ",")
+ } else {
+ safeVal = value
+ }
+ pubKey.AddExtendedField(key, safeVal)
+ }
+}
diff --git a/vendor/github.com/docker/notary/LICENSE b/vendor/github.com/docker/notary/LICENSE
new file mode 100644
index 0000000..6daf85e
--- /dev/null
+++ b/vendor/github.com/docker/notary/LICENSE
@@ -0,0 +1,201 @@
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2015 Docker, Inc.
+
+ 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/docker/notary/README.md b/vendor/github.com/docker/notary/README.md
new file mode 100644
index 0000000..e81a91c
--- /dev/null
+++ b/vendor/github.com/docker/notary/README.md
@@ -0,0 +1,100 @@
+# Notary
+[![Circle CI](https://circleci.com/gh/docker/notary/tree/master.svg?style=shield)](https://circleci.com/gh/docker/notary/tree/master) [![CodeCov](https://codecov.io/github/docker/notary/coverage.svg?branch=master)](https://codecov.io/github/docker/notary) [![GoReportCard](https://goreportcard.com/badge/docker/notary)](https://goreportcard.com/report/github.com/docker/notary)
+
+The Notary project comprises a [server](cmd/notary-server) and a [client](cmd/notary) for running and interacting
+with trusted collections. Please see the [service architecture](docs/service_architecture.md) documentation
+for more information.
+
+
+Notary aims to make the internet more secure by making it easy for people to
+publish and verify content. We often rely on TLS to secure our communications
+with a web server which is inherently flawed, as any compromise of the server
+enables malicious content to be substituted for the legitimate content.
+
+With Notary, publishers can sign their content offline using keys kept highly
+secure. Once the publisher is ready to make the content available, they can
+push their signed trusted collection to a Notary Server.
+
+Consumers, having acquired the publisher's public key through a secure channel,
+can then communicate with any notary server or (insecure) mirror, relying
+only on the publisher's key to determine the validity and integrity of the
+received content.
+
+## Goals
+
+Notary is based on [The Update Framework](https://www.theupdateframework.com/), a secure general design for the problem of software distribution and updates. By using TUF, notary achieves a number of key advantages:
+
+* **Survivable Key Compromise**: Content publishers must manage keys in order to sign their content. Signing keys may be compromised or lost so systems must be designed in order to be flexible and recoverable in the case of key compromise. TUF's notion of key roles is utilized to separate responsibilities across a hierarchy of keys such that loss of any particular key (except the root role) by itself is not fatal to the security of the system.
+* **Freshness Guarantees**: Replay attacks are a common problem in designing secure systems, where previously valid payloads are replayed to trick another system. The same problem exists in the software update systems, where old signed can be presented as the most recent. notary makes use of timestamping on publishing so that consumers can know that they are receiving the most up to date content. This is particularly important when dealing with software update where old vulnerable versions could be used to attack users.
+* **Configurable Trust Thresholds**: Oftentimes there are a large number of publishers that are allowed to publish a particular piece of content. For example, open source projects where there are a number of core maintainers. Trust thresholds can be used so that content consumers require a configurable number of signatures on a piece of content in order to trust it. Using thresholds increases security so that loss of individual signing keys doesn't allow publishing of malicious content.
+* **Signing Delegation**: To allow for flexible publishing of trusted collections, a content publisher can delegate part of their collection to another signer. This delegation is represented as signed metadata so that a consumer of the content can verify both the content and the delegation.
+* **Use of Existing Distribution**: Notary's trust guarantees are not tied at all to particular distribution channels from which content is delivered. Therefore, trust can be added to any existing content delivery mechanism.
+* **Untrusted Mirrors and Transport**: All of the notary metadata can be mirrored and distributed via arbitrary channels.
+
+## Security
+
+Please see our [service architecture docs](docs/service_architecture.md#threat-model) for more information about our threat model, which details the varying survivability and severities for key compromise as well as mitigations.
+
+Our last security audit was on July 31, 2015 by NCC ([results](docs/resources/ncc_docker_notary_audit_2015_07_31.pdf)).
+
+Any security vulnerabilities can be reported to security@docker.com.
+
+# Getting started with the Notary CLI
+
+Please get the Notary Client CLI binary from [the official releases page](https://github.com/docker/notary/releases) or you can [build one yourself](#building-notary).
+The version of Notary server and signer should be greater than or equal to Notary CLI's version to ensure feature compatibility (ex: CLI version 0.2, server/signer version >= 0.2), and all official releases are associated with GitHub tags.
+
+To use the Notary CLI with Docker hub images, please have a look at our
+[getting started docs](docs/getting_started.md).
+
+For more advanced usage, please see the
+[advanced usage docs](docs/advanced_usage.md).
+
+To use the CLI against a local Notary server rather than against Docker Hub:
+
+1. Please ensure that you have [docker and docker-compose](http://docs.docker.com/compose/install/) installed.
+1. `git clone https://github.com/docker/notary.git` and from the cloned repository path,
+ start up a local Notary server and signer and copy the config file and testing certs to your
+ local notary config directory:
+
+ ```sh
+ $ docker-compose build
+ $ docker-compose up -d
+ $ mkdir -p ~/.notary && cp cmd/notary/config.json cmd/notary/root-ca.crt ~/.notary
+ ```
+
+1. Add `127.0.0.1 notary-server` to your `/etc/hosts`, or if using docker-machine,
+ add `$(docker-machine ip) notary-server`).
+
+You can run through the examples in the
+[getting started docs](docs/getting_started.md) and
+[advanced usage docs](docs/advanced_usage.md), but
+without the `-s` (server URL) argument to the `notary` command since the server
+URL is specified already in the configuration, file you copied.
+
+You can also leave off the `-d ~/.docker/trust` argument if you do not care
+to use `notary` with Docker images.
+
+
+## Building Notary
+
+Prerequisites:
+
+- Go >= 1.7
+
+- [godep](https://github.com/tools/godep) installed
+- libtool development headers installed
+ - Ubuntu: `apt-get install libltdl-dev`
+ - CentOS/RedHat: `yum install libtool-ltdl-devel`
+ - Mac OS ([Homebrew](http://brew.sh/)): `brew install libtool`
+
+Run `make binaries`, which creates the Notary Client CLI binary at `bin/notary`.
+Note that `make binaries` assumes a standard Go directory structure, in which
+Notary is checked out to the `src` directory in your `GOPATH`. For example:
+```
+$GOPATH/
+ src/
+ github.com/
+ docker/
+ notary/
+```
diff --git a/vendor/github.com/docker/notary/client/changelist/change.go b/vendor/github.com/docker/notary/client/changelist/change.go
new file mode 100644
index 0000000..3e872e6
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/changelist/change.go
@@ -0,0 +1,102 @@
+package changelist
+
+import (
+ "github.com/docker/notary/tuf/data"
+)
+
+// Scopes for TUFChanges are simply the TUF roles.
+// Unfortunately because of targets delegations, we can only
+// cover the base roles.
+const (
+ ScopeRoot = "root"
+ ScopeTargets = "targets"
+ ScopeSnapshot = "snapshot"
+ ScopeTimestamp = "timestamp"
+)
+
+// Types for TUFChanges are namespaced by the Role they
+// are relevant for. The Root and Targets roles are the
+// only ones for which user action can cause a change, as
+// all changes in Snapshot and Timestamp are programmatically
+// generated base on Root and Targets changes.
+const (
+ TypeRootRole = "role"
+ TypeTargetsTarget = "target"
+ TypeTargetsDelegation = "delegation"
+ TypeWitness = "witness"
+)
+
+// TUFChange represents a change to a TUF repo
+type TUFChange struct {
+ // Abbreviated because Go doesn't permit a field and method of the same name
+ Actn string `json:"action"`
+ Role string `json:"role"`
+ ChangeType string `json:"type"`
+ ChangePath string `json:"path"`
+ Data []byte `json:"data"`
+}
+
+// TUFRootData represents a modification of the keys associated
+// with a role that appears in the root.json
+type TUFRootData struct {
+ Keys data.KeyList `json:"keys"`
+ RoleName string `json:"role"`
+}
+
+// NewTUFChange initializes a TUFChange object
+func NewTUFChange(action string, role, changeType, changePath string, content []byte) *TUFChange {
+ return &TUFChange{
+ Actn: action,
+ Role: role,
+ ChangeType: changeType,
+ ChangePath: changePath,
+ Data: content,
+ }
+}
+
+// Action return c.Actn
+func (c TUFChange) Action() string {
+ return c.Actn
+}
+
+// Scope returns c.Role
+func (c TUFChange) Scope() string {
+ return c.Role
+}
+
+// Type returns c.ChangeType
+func (c TUFChange) Type() string {
+ return c.ChangeType
+}
+
+// Path return c.ChangePath
+func (c TUFChange) Path() string {
+ return c.ChangePath
+}
+
+// Content returns c.Data
+func (c TUFChange) Content() []byte {
+ return c.Data
+}
+
+// TUFDelegation represents a modification to a target delegation
+// this includes creating a delegations. This format is used to avoid
+// unexpected race conditions between humans modifying the same delegation
+type TUFDelegation struct {
+ NewName string `json:"new_name,omitempty"`
+ NewThreshold int `json:"threshold, omitempty"`
+ AddKeys data.KeyList `json:"add_keys, omitempty"`
+ RemoveKeys []string `json:"remove_keys,omitempty"`
+ AddPaths []string `json:"add_paths,omitempty"`
+ RemovePaths []string `json:"remove_paths,omitempty"`
+ ClearAllPaths bool `json:"clear_paths,omitempty"`
+}
+
+// ToNewRole creates a fresh role object from the TUFDelegation data
+func (td TUFDelegation) ToNewRole(scope string) (*data.Role, error) {
+ name := scope
+ if td.NewName != "" {
+ name = td.NewName
+ }
+ return data.NewRole(name, td.NewThreshold, td.AddKeys.IDs(), td.AddPaths)
+}
diff --git a/vendor/github.com/docker/notary/client/changelist/changelist.go b/vendor/github.com/docker/notary/client/changelist/changelist.go
new file mode 100644
index 0000000..9b52981
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/changelist/changelist.go
@@ -0,0 +1,77 @@
+package changelist
+
+// memChangeList implements a simple in memory change list.
+type memChangelist struct {
+ changes []Change
+}
+
+// NewMemChangelist instantiates a new in-memory changelist
+func NewMemChangelist() Changelist {
+ return &memChangelist{}
+}
+
+// List returns a list of Changes
+func (cl memChangelist) List() []Change {
+ return cl.changes
+}
+
+// Add adds a change to the in-memory change list
+func (cl *memChangelist) Add(c Change) error {
+ cl.changes = append(cl.changes, c)
+ return nil
+}
+
+// Remove deletes the changes found at the given indices
+func (cl *memChangelist) Remove(idxs []int) error {
+ remove := make(map[int]struct{})
+ for _, i := range idxs {
+ remove[i] = struct{}{}
+ }
+ var keep []Change
+
+ for i, c := range cl.changes {
+ if _, ok := remove[i]; ok {
+ continue
+ }
+ keep = append(keep, c)
+ }
+ cl.changes = keep
+ return nil
+}
+
+// Clear empties the changelist file.
+func (cl *memChangelist) Clear(archive string) error {
+ // appending to a nil list initializes it.
+ cl.changes = nil
+ return nil
+}
+
+// Close is a no-op in this in-memory change-list
+func (cl *memChangelist) Close() error {
+ return nil
+}
+
+func (cl *memChangelist) NewIterator() (ChangeIterator, error) {
+ return &MemChangeListIterator{index: 0, collection: cl.changes}, nil
+}
+
+// MemChangeListIterator is a concrete instance of ChangeIterator
+type MemChangeListIterator struct {
+ index int
+ collection []Change // Same type as memChangeList.changes
+}
+
+// Next returns the next Change
+func (m *MemChangeListIterator) Next() (item Change, err error) {
+ if m.index >= len(m.collection) {
+ return nil, IteratorBoundsError(m.index)
+ }
+ item = m.collection[m.index]
+ m.index++
+ return item, err
+}
+
+// HasNext indicates whether the iterator is exhausted
+func (m *MemChangeListIterator) HasNext() bool {
+ return m.index < len(m.collection)
+}
diff --git a/vendor/github.com/docker/notary/client/changelist/file_changelist.go b/vendor/github.com/docker/notary/client/changelist/file_changelist.go
new file mode 100644
index 0000000..a252154
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/changelist/file_changelist.go
@@ -0,0 +1,197 @@
+package changelist
+
+import (
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "sort"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/distribution/uuid"
+ "path/filepath"
+)
+
+// FileChangelist stores all the changes as files
+type FileChangelist struct {
+ dir string
+}
+
+// NewFileChangelist is a convenience method for returning FileChangeLists
+func NewFileChangelist(dir string) (*FileChangelist, error) {
+ logrus.Debug("Making dir path: ", dir)
+ err := os.MkdirAll(dir, 0700)
+ if err != nil {
+ return nil, err
+ }
+ return &FileChangelist{dir: dir}, nil
+}
+
+// getFileNames reads directory, filtering out child directories
+func getFileNames(dirName string) ([]os.FileInfo, error) {
+ var dirListing, fileInfos []os.FileInfo
+ dir, err := os.Open(dirName)
+ if err != nil {
+ return fileInfos, err
+ }
+ defer dir.Close()
+ dirListing, err = dir.Readdir(0)
+ if err != nil {
+ return fileInfos, err
+ }
+ for _, f := range dirListing {
+ if f.IsDir() {
+ continue
+ }
+ fileInfos = append(fileInfos, f)
+ }
+ sort.Sort(fileChanges(fileInfos))
+ return fileInfos, nil
+}
+
+// Read a JSON formatted file from disk; convert to TUFChange struct
+func unmarshalFile(dirname string, f os.FileInfo) (*TUFChange, error) {
+ c := &TUFChange{}
+ raw, err := ioutil.ReadFile(filepath.Join(dirname, f.Name()))
+ if err != nil {
+ return c, err
+ }
+ err = json.Unmarshal(raw, c)
+ if err != nil {
+ return c, err
+ }
+ return c, nil
+}
+
+// List returns a list of sorted changes
+func (cl FileChangelist) List() []Change {
+ var changes []Change
+ fileInfos, err := getFileNames(cl.dir)
+ if err != nil {
+ return changes
+ }
+ for _, f := range fileInfos {
+ c, err := unmarshalFile(cl.dir, f)
+ if err != nil {
+ logrus.Warn(err.Error())
+ continue
+ }
+ changes = append(changes, c)
+ }
+ return changes
+}
+
+// Add adds a change to the file change list
+func (cl FileChangelist) Add(c Change) error {
+ cJSON, err := json.Marshal(c)
+ if err != nil {
+ return err
+ }
+ filename := fmt.Sprintf("%020d_%s.change", time.Now().UnixNano(), uuid.Generate())
+ return ioutil.WriteFile(filepath.Join(cl.dir, filename), cJSON, 0644)
+}
+
+// Remove deletes the changes found at the given indices
+func (cl FileChangelist) Remove(idxs []int) error {
+ fileInfos, err := getFileNames(cl.dir)
+ if err != nil {
+ return err
+ }
+ remove := make(map[int]struct{})
+ for _, i := range idxs {
+ remove[i] = struct{}{}
+ }
+ for i, c := range fileInfos {
+ if _, ok := remove[i]; ok {
+ file := filepath.Join(cl.dir, c.Name())
+ if err := os.Remove(file); err != nil {
+ logrus.Errorf("could not remove change %d: %s", i, err.Error())
+ }
+ }
+ }
+ return nil
+}
+
+// Clear clears the change list
+// N.B. archiving not currently implemented
+func (cl FileChangelist) Clear(archive string) error {
+ dir, err := os.Open(cl.dir)
+ if err != nil {
+ return err
+ }
+ defer dir.Close()
+ files, err := dir.Readdir(0)
+ if err != nil {
+ return err
+ }
+ for _, f := range files {
+ os.Remove(filepath.Join(cl.dir, f.Name()))
+ }
+ return nil
+}
+
+// Close is a no-op
+func (cl FileChangelist) Close() error {
+ // Nothing to do here
+ return nil
+}
+
+// NewIterator creates an iterator from FileChangelist
+func (cl FileChangelist) NewIterator() (ChangeIterator, error) {
+ fileInfos, err := getFileNames(cl.dir)
+ if err != nil {
+ return &FileChangeListIterator{}, err
+ }
+ return &FileChangeListIterator{dirname: cl.dir, collection: fileInfos}, nil
+}
+
+// IteratorBoundsError is an Error type used by Next()
+type IteratorBoundsError int
+
+// Error implements the Error interface
+func (e IteratorBoundsError) Error() string {
+ return fmt.Sprintf("Iterator index (%d) out of bounds", e)
+}
+
+// FileChangeListIterator is a concrete instance of ChangeIterator
+type FileChangeListIterator struct {
+ index int
+ dirname string
+ collection []os.FileInfo
+}
+
+// Next returns the next Change in the FileChangeList
+func (m *FileChangeListIterator) Next() (item Change, err error) {
+ if m.index >= len(m.collection) {
+ return nil, IteratorBoundsError(m.index)
+ }
+ f := m.collection[m.index]
+ m.index++
+ item, err = unmarshalFile(m.dirname, f)
+ return
+}
+
+// HasNext indicates whether iterator is exhausted
+func (m *FileChangeListIterator) HasNext() bool {
+ return m.index < len(m.collection)
+}
+
+type fileChanges []os.FileInfo
+
+// Len returns the length of a file change list
+func (cs fileChanges) Len() int {
+ return len(cs)
+}
+
+// Less compares the names of two different file changes
+func (cs fileChanges) Less(i, j int) bool {
+ return cs[i].Name() < cs[j].Name()
+}
+
+// Swap swaps the position of two file changes
+func (cs fileChanges) Swap(i, j int) {
+ tmp := cs[i]
+ cs[i] = cs[j]
+ cs[j] = tmp
+}
diff --git a/vendor/github.com/docker/notary/client/changelist/interface.go b/vendor/github.com/docker/notary/client/changelist/interface.go
new file mode 100644
index 0000000..a319b7b
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/changelist/interface.go
@@ -0,0 +1,73 @@
+package changelist
+
+// Changelist is the interface for all TUF change lists
+type Changelist interface {
+ // List returns the ordered list of changes
+ // currently stored
+ List() []Change
+
+ // Add change appends the provided change to
+ // the list of changes
+ Add(Change) error
+
+ // Clear empties the current change list.
+ // Archive may be provided as a directory path
+ // to save a copy of the changelist in that location
+ Clear(archive string) error
+
+ // Remove deletes the changes corresponding with the indices given
+ Remove(idxs []int) error
+
+ // Close syncronizes any pending writes to the underlying
+ // storage and closes the file/connection
+ Close() error
+
+ // NewIterator returns an iterator for walking through the list
+ // of changes currently stored
+ NewIterator() (ChangeIterator, error)
+}
+
+const (
+ // ActionCreate represents a Create action
+ ActionCreate = "create"
+ // ActionUpdate represents an Update action
+ ActionUpdate = "update"
+ // ActionDelete represents a Delete action
+ ActionDelete = "delete"
+)
+
+// Change is the interface for a TUF Change
+type Change interface {
+ // "create","update", or "delete"
+ Action() string
+
+ // Where the change should be made.
+ // For TUF this will be the role
+ Scope() string
+
+ // The content type being affected.
+ // For TUF this will be "target", or "delegation".
+ // If the type is "delegation", the Scope will be
+ // used to determine if a root role is being updated
+ // or a target delegation.
+ Type() string
+
+ // Path indicates the entry within a role to be affected by the
+ // change. For targets, this is simply the target's path,
+ // for delegations it's the delegated role name.
+ Path() string
+
+ // Serialized content that the interpreter of a changelist
+ // can use to apply the change.
+ // For TUF this will be the serialized JSON that needs
+ // to be inserted or merged. In the case of a "delete"
+ // action, it will be nil.
+ Content() []byte
+}
+
+// ChangeIterator is the interface for iterating across collections of
+// TUF Change items
+type ChangeIterator interface {
+ Next() (Change, error)
+ HasNext() bool
+}
diff --git a/vendor/github.com/docker/notary/client/client.go b/vendor/github.com/docker/notary/client/client.go
new file mode 100644
index 0000000..15070fb
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/client.go
@@ -0,0 +1,1014 @@
+package client
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary"
+ "github.com/docker/notary/client/changelist"
+ "github.com/docker/notary/cryptoservice"
+ store "github.com/docker/notary/storage"
+ "github.com/docker/notary/trustmanager"
+ "github.com/docker/notary/trustpinning"
+ "github.com/docker/notary/tuf"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/signed"
+ "github.com/docker/notary/tuf/utils"
+)
+
+func init() {
+ data.SetDefaultExpiryTimes(notary.NotaryDefaultExpiries)
+}
+
+// ErrRepoNotInitialized is returned when trying to publish an uninitialized
+// notary repository
+type ErrRepoNotInitialized struct{}
+
+func (err ErrRepoNotInitialized) Error() string {
+ return "repository has not been initialized"
+}
+
+// ErrInvalidRemoteRole is returned when the server is requested to manage
+// a key type that is not permitted
+type ErrInvalidRemoteRole struct {
+ Role string
+}
+
+func (err ErrInvalidRemoteRole) Error() string {
+ return fmt.Sprintf(
+ "notary does not permit the server managing the %s key", err.Role)
+}
+
+// ErrInvalidLocalRole is returned when the client wants to manage
+// a key type that is not permitted
+type ErrInvalidLocalRole struct {
+ Role string
+}
+
+func (err ErrInvalidLocalRole) Error() string {
+ return fmt.Sprintf(
+ "notary does not permit the client managing the %s key", err.Role)
+}
+
+// ErrRepositoryNotExist is returned when an action is taken on a remote
+// repository that doesn't exist
+type ErrRepositoryNotExist struct {
+ remote string
+ gun string
+}
+
+func (err ErrRepositoryNotExist) Error() string {
+ return fmt.Sprintf("%s does not have trust data for %s", err.remote, err.gun)
+}
+
+const (
+ tufDir = "tuf"
+)
+
+// NotaryRepository stores all the information needed to operate on a notary
+// repository.
+type NotaryRepository struct {
+ baseDir string
+ gun string
+ baseURL string
+ tufRepoPath string
+ fileStore store.MetadataStore
+ CryptoService signed.CryptoService
+ tufRepo *tuf.Repo
+ invalid *tuf.Repo // known data that was parsable but deemed invalid
+ roundTrip http.RoundTripper
+ trustPinning trustpinning.TrustPinConfig
+}
+
+// repositoryFromKeystores is a helper function for NewNotaryRepository that
+// takes some basic NotaryRepository parameters as well as keystores (in order
+// of usage preference), and returns a NotaryRepository.
+func repositoryFromKeystores(baseDir, gun, baseURL string, rt http.RoundTripper,
+ keyStores []trustmanager.KeyStore, trustPin trustpinning.TrustPinConfig) (*NotaryRepository, error) {
+
+ cryptoService := cryptoservice.NewCryptoService(keyStores...)
+
+ nRepo := &NotaryRepository{
+ gun: gun,
+ baseDir: baseDir,
+ baseURL: baseURL,
+ tufRepoPath: filepath.Join(baseDir, tufDir, filepath.FromSlash(gun)),
+ CryptoService: cryptoService,
+ roundTrip: rt,
+ trustPinning: trustPin,
+ }
+
+ fileStore, err := store.NewFilesystemStore(
+ nRepo.tufRepoPath,
+ "metadata",
+ "json",
+ )
+ if err != nil {
+ return nil, err
+ }
+ nRepo.fileStore = fileStore
+
+ return nRepo, nil
+}
+
+// Target represents a simplified version of the data TUF operates on, so external
+// applications don't have to depend on TUF data types.
+type Target struct {
+ Name string // the name of the target
+ Hashes data.Hashes // the hash of the target
+ Length int64 // the size in bytes of the target
+}
+
+// TargetWithRole represents a Target that exists in a particular role - this is
+// produced by ListTargets and GetTargetByName
+type TargetWithRole struct {
+ Target
+ Role string
+}
+
+// NewTarget is a helper method that returns a Target
+func NewTarget(targetName string, targetPath string) (*Target, error) {
+ b, err := ioutil.ReadFile(targetPath)
+ if err != nil {
+ return nil, err
+ }
+
+ meta, err := data.NewFileMeta(bytes.NewBuffer(b), data.NotaryDefaultHashes...)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Target{Name: targetName, Hashes: meta.Hashes, Length: meta.Length}, nil
+}
+
+func rootCertKey(gun string, privKey data.PrivateKey) (data.PublicKey, error) {
+ // Hard-coded policy: the generated certificate expires in 10 years.
+ startTime := time.Now()
+ cert, err := cryptoservice.GenerateCertificate(
+ privKey, gun, startTime, startTime.Add(notary.Year*10))
+ if err != nil {
+ return nil, err
+ }
+
+ x509PublicKey := utils.CertToKey(cert)
+ if x509PublicKey == nil {
+ return nil, fmt.Errorf(
+ "cannot use regenerated certificate: format %s", cert.PublicKeyAlgorithm)
+ }
+
+ return x509PublicKey, nil
+}
+
+// Initialize creates a new repository by using rootKey as the root Key for the
+// TUF repository. The server must be reachable (and is asked to generate a
+// timestamp key and possibly other serverManagedRoles), but the created repository
+// result is only stored on local disk, not published to the server. To do that,
+// use r.Publish() eventually.
+func (r *NotaryRepository) Initialize(rootKeyIDs []string, serverManagedRoles ...string) error {
+ privKeys := make([]data.PrivateKey, 0, len(rootKeyIDs))
+ for _, keyID := range rootKeyIDs {
+ privKey, _, err := r.CryptoService.GetPrivateKey(keyID)
+ if err != nil {
+ return err
+ }
+ privKeys = append(privKeys, privKey)
+ }
+
+ // currently we only support server managing timestamps and snapshots, and
+ // nothing else - timestamps are always managed by the server, and implicit
+ // (do not have to be passed in as part of `serverManagedRoles`, so that
+ // the API of Initialize doesn't change).
+ var serverManagesSnapshot bool
+ locallyManagedKeys := []string{
+ data.CanonicalTargetsRole,
+ data.CanonicalSnapshotRole,
+ // root is also locally managed, but that should have been created
+ // already
+ }
+ remotelyManagedKeys := []string{data.CanonicalTimestampRole}
+ for _, role := range serverManagedRoles {
+ switch role {
+ case data.CanonicalTimestampRole:
+ continue // timestamp is already in the right place
+ case data.CanonicalSnapshotRole:
+ // because we put Snapshot last
+ locallyManagedKeys = []string{data.CanonicalTargetsRole}
+ remotelyManagedKeys = append(
+ remotelyManagedKeys, data.CanonicalSnapshotRole)
+ serverManagesSnapshot = true
+ default:
+ return ErrInvalidRemoteRole{Role: role}
+ }
+ }
+
+ rootKeys := make([]data.PublicKey, 0, len(privKeys))
+ for _, privKey := range privKeys {
+ rootKey, err := rootCertKey(r.gun, privKey)
+ if err != nil {
+ return err
+ }
+ rootKeys = append(rootKeys, rootKey)
+ }
+
+ var (
+ rootRole = data.NewBaseRole(
+ data.CanonicalRootRole,
+ notary.MinThreshold,
+ rootKeys...,
+ )
+ timestampRole data.BaseRole
+ snapshotRole data.BaseRole
+ targetsRole data.BaseRole
+ )
+
+ // we want to create all the local keys first so we don't have to
+ // make unnecessary network calls
+ for _, role := range locallyManagedKeys {
+ // This is currently hardcoding the keys to ECDSA.
+ key, err := r.CryptoService.Create(role, r.gun, data.ECDSAKey)
+ if err != nil {
+ return err
+ }
+ switch role {
+ case data.CanonicalSnapshotRole:
+ snapshotRole = data.NewBaseRole(
+ role,
+ notary.MinThreshold,
+ key,
+ )
+ case data.CanonicalTargetsRole:
+ targetsRole = data.NewBaseRole(
+ role,
+ notary.MinThreshold,
+ key,
+ )
+ }
+ }
+ for _, role := range remotelyManagedKeys {
+ // This key is generated by the remote server.
+ key, err := getRemoteKey(r.baseURL, r.gun, role, r.roundTrip)
+ if err != nil {
+ return err
+ }
+ logrus.Debugf("got remote %s %s key with keyID: %s",
+ role, key.Algorithm(), key.ID())
+ switch role {
+ case data.CanonicalSnapshotRole:
+ snapshotRole = data.NewBaseRole(
+ role,
+ notary.MinThreshold,
+ key,
+ )
+ case data.CanonicalTimestampRole:
+ timestampRole = data.NewBaseRole(
+ role,
+ notary.MinThreshold,
+ key,
+ )
+ }
+ }
+
+ r.tufRepo = tuf.NewRepo(r.CryptoService)
+
+ err := r.tufRepo.InitRoot(
+ rootRole,
+ timestampRole,
+ snapshotRole,
+ targetsRole,
+ false,
+ )
+ if err != nil {
+ logrus.Debug("Error on InitRoot: ", err.Error())
+ return err
+ }
+ _, err = r.tufRepo.InitTargets(data.CanonicalTargetsRole)
+ if err != nil {
+ logrus.Debug("Error on InitTargets: ", err.Error())
+ return err
+ }
+ err = r.tufRepo.InitSnapshot()
+ if err != nil {
+ logrus.Debug("Error on InitSnapshot: ", err.Error())
+ return err
+ }
+
+ return r.saveMetadata(serverManagesSnapshot)
+}
+
+// adds a TUF Change template to the given roles
+func addChange(cl *changelist.FileChangelist, c changelist.Change, roles ...string) error {
+
+ if len(roles) == 0 {
+ roles = []string{data.CanonicalTargetsRole}
+ }
+
+ var changes []changelist.Change
+ for _, role := range roles {
+ // Ensure we can only add targets to the CanonicalTargetsRole,
+ // or a Delegation role (which is <CanonicalTargetsRole>/something else)
+ if role != data.CanonicalTargetsRole && !data.IsDelegation(role) && !data.IsWildDelegation(role) {
+ return data.ErrInvalidRole{
+ Role: role,
+ Reason: "cannot add targets to this role",
+ }
+ }
+
+ changes = append(changes, changelist.NewTUFChange(
+ c.Action(),
+ role,
+ c.Type(),
+ c.Path(),
+ c.Content(),
+ ))
+ }
+
+ for _, c := range changes {
+ if err := cl.Add(c); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// AddTarget creates new changelist entries to add a target to the given roles
+// in the repository when the changelist gets applied at publish time.
+// If roles are unspecified, the default role is "targets"
+func (r *NotaryRepository) AddTarget(target *Target, roles ...string) error {
+
+ if len(target.Hashes) == 0 {
+ return fmt.Errorf("no hashes specified for target \"%s\"", target.Name)
+ }
+ cl, err := changelist.NewFileChangelist(filepath.Join(r.tufRepoPath, "changelist"))
+ if err != nil {
+ return err
+ }
+ defer cl.Close()
+ logrus.Debugf("Adding target \"%s\" with sha256 \"%x\" and size %d bytes.\n", target.Name, target.Hashes["sha256"], target.Length)
+
+ meta := data.FileMeta{Length: target.Length, Hashes: target.Hashes}
+ metaJSON, err := json.Marshal(meta)
+ if err != nil {
+ return err
+ }
+
+ template := changelist.NewTUFChange(
+ changelist.ActionCreate, "", changelist.TypeTargetsTarget,
+ target.Name, metaJSON)
+ return addChange(cl, template, roles...)
+}
+
+// RemoveTarget creates new changelist entries to remove a target from the given
+// roles in the repository when the changelist gets applied at publish time.
+// If roles are unspecified, the default role is "target".
+func (r *NotaryRepository) RemoveTarget(targetName string, roles ...string) error {
+
+ cl, err := changelist.NewFileChangelist(filepath.Join(r.tufRepoPath, "changelist"))
+ if err != nil {
+ return err
+ }
+ logrus.Debugf("Removing target \"%s\"", targetName)
+ template := changelist.NewTUFChange(changelist.ActionDelete, "",
+ changelist.TypeTargetsTarget, targetName, nil)
+ return addChange(cl, template, roles...)
+}
+
+// ListTargets lists all targets for the current repository. The list of
+// roles should be passed in order from highest to lowest priority.
+//
+// IMPORTANT: if you pass a set of roles such as [ "targets/a", "targets/x"
+// "targets/a/b" ], even though "targets/a/b" is part of the "targets/a" subtree
+// its entries will be strictly shadowed by those in other parts of the "targets/a"
+// subtree and also the "targets/x" subtree, as we will defer parsing it until
+// we explicitly reach it in our iteration of the provided list of roles.
+func (r *NotaryRepository) ListTargets(roles ...string) ([]*TargetWithRole, error) {
+ if err := r.Update(false); err != nil {
+ return nil, err
+ }
+
+ if len(roles) == 0 {
+ roles = []string{data.CanonicalTargetsRole}
+ }
+ targets := make(map[string]*TargetWithRole)
+ for _, role := range roles {
+ // Define an array of roles to skip for this walk (see IMPORTANT comment above)
+ skipRoles := utils.StrSliceRemove(roles, role)
+
+ // Define a visitor function to populate the targets map in priority order
+ listVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
+ // We found targets so we should try to add them to our targets map
+ for targetName, targetMeta := range tgt.Signed.Targets {
+ // Follow the priority by not overriding previously set targets
+ // and check that this path is valid with this role
+ if _, ok := targets[targetName]; ok || !validRole.CheckPaths(targetName) {
+ continue
+ }
+ targets[targetName] = &TargetWithRole{
+ Target: Target{
+ Name: targetName,
+ Hashes: targetMeta.Hashes,
+ Length: targetMeta.Length,
+ },
+ Role: validRole.Name,
+ }
+ }
+ return nil
+ }
+
+ r.tufRepo.WalkTargets("", role, listVisitorFunc, skipRoles...)
+ }
+
+ var targetList []*TargetWithRole
+ for _, v := range targets {
+ targetList = append(targetList, v)
+ }
+
+ return targetList, nil
+}
+
+// GetTargetByName returns a target by the given name. If no roles are passed
+// it uses the targets role and does a search of the entire delegation
+// graph, finding the first entry in a breadth first search of the delegations.
+// If roles are passed, they should be passed in descending priority and
+// the target entry found in the subtree of the highest priority role
+// will be returned.
+// See the IMPORTANT section on ListTargets above. Those roles also apply here.
+func (r *NotaryRepository) GetTargetByName(name string, roles ...string) (*TargetWithRole, error) {
+ if err := r.Update(false); err != nil {
+ return nil, err
+ }
+
+ if len(roles) == 0 {
+ roles = append(roles, data.CanonicalTargetsRole)
+ }
+ var resultMeta data.FileMeta
+ var resultRoleName string
+ var foundTarget bool
+ for _, role := range roles {
+ // Define an array of roles to skip for this walk (see IMPORTANT comment above)
+ skipRoles := utils.StrSliceRemove(roles, role)
+
+ // Define a visitor function to find the specified target
+ getTargetVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
+ if tgt == nil {
+ return nil
+ }
+ // We found the target and validated path compatibility in our walk,
+ // so we should stop our walk and set the resultMeta and resultRoleName variables
+ if resultMeta, foundTarget = tgt.Signed.Targets[name]; foundTarget {
+ resultRoleName = validRole.Name
+ return tuf.StopWalk{}
+ }
+ return nil
+ }
+ // Check that we didn't error, and that we assigned to our target
+ if err := r.tufRepo.WalkTargets(name, role, getTargetVisitorFunc, skipRoles...); err == nil && foundTarget {
+ return &TargetWithRole{Target: Target{Name: name, Hashes: resultMeta.Hashes, Length: resultMeta.Length}, Role: resultRoleName}, nil
+ }
+ }
+ return nil, fmt.Errorf("No trust data for %s", name)
+
+}
+
+// TargetSignedStruct is a struct that contains a Target, the role it was found in, and the list of signatures for that role
+type TargetSignedStruct struct {
+ Role data.DelegationRole
+ Target Target
+ Signatures []data.Signature
+}
+
+// GetAllTargetMetadataByName searches the entire delegation role tree to find the specified target by name for all
+// roles, and returns a list of TargetSignedStructs for each time it finds the specified target.
+// If given an empty string for a target name, it will return back all targets signed into the repository in every role
+func (r *NotaryRepository) GetAllTargetMetadataByName(name string) ([]TargetSignedStruct, error) {
+ if err := r.Update(false); err != nil {
+ return nil, err
+ }
+
+ var targetInfoList []TargetSignedStruct
+
+ // Define a visitor function to find the specified target
+ getAllTargetInfoByNameVisitorFunc := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
+ if tgt == nil {
+ return nil
+ }
+ // We found a target and validated path compatibility in our walk,
+ // so add it to our list if we have a match
+ // if we have an empty name, add all targets, else check if we have it
+ var targetMetaToAdd data.Files
+ if name == "" {
+ targetMetaToAdd = tgt.Signed.Targets
+ } else {
+ if meta, ok := tgt.Signed.Targets[name]; ok {
+ targetMetaToAdd = data.Files{name: meta}
+ }
+ }
+
+ for targetName, resultMeta := range targetMetaToAdd {
+ targetInfo := TargetSignedStruct{
+ Role: validRole,
+ Target: Target{Name: targetName, Hashes: resultMeta.Hashes, Length: resultMeta.Length},
+ Signatures: tgt.Signatures,
+ }
+ targetInfoList = append(targetInfoList, targetInfo)
+ }
+ // continue walking to all child roles
+ return nil
+ }
+
+ // Check that we didn't error, and that we found the target at least once
+ if err := r.tufRepo.WalkTargets(name, "", getAllTargetInfoByNameVisitorFunc); err != nil {
+ return nil, err
+ }
+ if len(targetInfoList) == 0 {
+ return nil, fmt.Errorf("No valid trust data for %s", name)
+ }
+ return targetInfoList, nil
+}
+
+// GetChangelist returns the list of the repository's unpublished changes
+func (r *NotaryRepository) GetChangelist() (changelist.Changelist, error) {
+ changelistDir := filepath.Join(r.tufRepoPath, "changelist")
+ cl, err := changelist.NewFileChangelist(changelistDir)
+ if err != nil {
+ logrus.Debug("Error initializing changelist")
+ return nil, err
+ }
+ return cl, nil
+}
+
+// RoleWithSignatures is a Role with its associated signatures
+type RoleWithSignatures struct {
+ Signatures []data.Signature
+ data.Role
+}
+
+// ListRoles returns a list of RoleWithSignatures objects for this repo
+// This represents the latest metadata for each role in this repo
+func (r *NotaryRepository) ListRoles() ([]RoleWithSignatures, error) {
+ // Update to latest repo state
+ if err := r.Update(false); err != nil {
+ return nil, err
+ }
+
+ // Get all role info from our updated keysDB, can be empty
+ roles := r.tufRepo.GetAllLoadedRoles()
+
+ var roleWithSigs []RoleWithSignatures
+
+ // Populate RoleWithSignatures with Role from keysDB and signatures from TUF metadata
+ for _, role := range roles {
+ roleWithSig := RoleWithSignatures{Role: *role, Signatures: nil}
+ switch role.Name {
+ case data.CanonicalRootRole:
+ roleWithSig.Signatures = r.tufRepo.Root.Signatures
+ case data.CanonicalTargetsRole:
+ roleWithSig.Signatures = r.tufRepo.Targets[data.CanonicalTargetsRole].Signatures
+ case data.CanonicalSnapshotRole:
+ roleWithSig.Signatures = r.tufRepo.Snapshot.Signatures
+ case data.CanonicalTimestampRole:
+ roleWithSig.Signatures = r.tufRepo.Timestamp.Signatures
+ default:
+ if !data.IsDelegation(role.Name) {
+ continue
+ }
+ if _, ok := r.tufRepo.Targets[role.Name]; ok {
+ // We'll only find a signature if we've published any targets with this delegation
+ roleWithSig.Signatures = r.tufRepo.Targets[role.Name].Signatures
+ }
+ }
+ roleWithSigs = append(roleWithSigs, roleWithSig)
+ }
+ return roleWithSigs, nil
+}
+
+// Publish pushes the local changes in signed material to the remote notary-server
+// Conceptually it performs an operation similar to a `git rebase`
+func (r *NotaryRepository) Publish() error {
+ cl, err := r.GetChangelist()
+ if err != nil {
+ return err
+ }
+ if err = r.publish(cl); err != nil {
+ return err
+ }
+ if err = cl.Clear(""); err != nil {
+ // This is not a critical problem when only a single host is pushing
+ // but will cause weird behaviour if changelist cleanup is failing
+ // and there are multiple hosts writing to the repo.
+ logrus.Warn("Unable to clear changelist. You may want to manually delete the folder ", filepath.Join(r.tufRepoPath, "changelist"))
+ }
+ return nil
+}
+
+// publish pushes the changes in the given changelist to the remote notary-server
+// Conceptually it performs an operation similar to a `git rebase`
+func (r *NotaryRepository) publish(cl changelist.Changelist) error {
+ var initialPublish bool
+ // update first before publishing
+ if err := r.Update(true); err != nil {
+ // If the remote is not aware of the repo, then this is being published
+ // for the first time. Try to load from disk instead for publishing.
+ if _, ok := err.(ErrRepositoryNotExist); ok {
+ err := r.bootstrapRepo()
+ if err != nil {
+ logrus.Debugf("Unable to load repository from local files: %s",
+ err.Error())
+ if _, ok := err.(store.ErrMetaNotFound); ok {
+ return ErrRepoNotInitialized{}
+ }
+ return err
+ }
+ // Ensure we will push the initial root and targets file. Either or
+ // both of the root and targets may not be marked as Dirty, since
+ // there may not be any changes that update them, so use a
+ // different boolean.
+ initialPublish = true
+ } else {
+ // We could not update, so we cannot publish.
+ logrus.Error("Could not publish Repository since we could not update: ", err.Error())
+ return err
+ }
+ }
+ // apply the changelist to the repo
+ if err := applyChangelist(r.tufRepo, r.invalid, cl); err != nil {
+ logrus.Debug("Error applying changelist")
+ return err
+ }
+
+ // these are the TUF files we will need to update, serialized as JSON before
+ // we send anything to remote
+ updatedFiles := make(map[string][]byte)
+
+ // check if our root file is nearing expiry or dirty. Resign if it is. If
+ // root is not dirty but we are publishing for the first time, then just
+ // publish the existing root we have.
+ if nearExpiry(r.tufRepo.Root.Signed.SignedCommon) || r.tufRepo.Root.Dirty {
+ rootJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalRootRole)
+ if err != nil {
+ return err
+ }
+ updatedFiles[data.CanonicalRootRole] = rootJSON
+ } else if initialPublish {
+ rootJSON, err := r.tufRepo.Root.MarshalJSON()
+ if err != nil {
+ return err
+ }
+ updatedFiles[data.CanonicalRootRole] = rootJSON
+ }
+
+ // iterate through all the targets files - if they are dirty, sign and update
+ for roleName, roleObj := range r.tufRepo.Targets {
+ if roleObj.Dirty || (roleName == data.CanonicalTargetsRole && initialPublish) {
+ targetsJSON, err := serializeCanonicalRole(r.tufRepo, roleName)
+ if err != nil {
+ return err
+ }
+ updatedFiles[roleName] = targetsJSON
+ }
+ }
+
+ // if we initialized the repo while designating the server as the snapshot
+ // signer, then there won't be a snapshots file. However, we might now
+ // have a local key (if there was a rotation), so initialize one.
+ if r.tufRepo.Snapshot == nil {
+ if err := r.tufRepo.InitSnapshot(); err != nil {
+ return err
+ }
+ }
+
+ snapshotJSON, err := serializeCanonicalRole(
+ r.tufRepo, data.CanonicalSnapshotRole)
+
+ if err == nil {
+ // Only update the snapshot if we've successfully signed it.
+ updatedFiles[data.CanonicalSnapshotRole] = snapshotJSON
+ } else if signErr, ok := err.(signed.ErrInsufficientSignatures); ok && signErr.FoundKeys == 0 {
+ // If signing fails due to us not having the snapshot key, then
+ // assume the server is going to sign, and do not include any snapshot
+ // data.
+ logrus.Debugf("Client does not have the key to sign snapshot. " +
+ "Assuming that server should sign the snapshot.")
+ } else {
+ logrus.Debugf("Client was unable to sign the snapshot: %s", err.Error())
+ return err
+ }
+
+ remote, err := getRemoteStore(r.baseURL, r.gun, r.roundTrip)
+ if err != nil {
+ return err
+ }
+
+ return remote.SetMulti(updatedFiles)
+}
+
+// bootstrapRepo loads the repository from the local file system (i.e.
+// a not yet published repo or a possibly obsolete local copy) into
+// r.tufRepo. This attempts to load metadata for all roles. Since server
+// snapshots are supported, if the snapshot metadata fails to load, that's ok.
+// This assumes that bootstrapRepo is only used by Publish() or RotateKey()
+func (r *NotaryRepository) bootstrapRepo() error {
+ b := tuf.NewRepoBuilder(r.gun, r.CryptoService, r.trustPinning)
+
+ logrus.Debugf("Loading trusted collection.")
+
+ for _, role := range data.BaseRoles {
+ jsonBytes, err := r.fileStore.GetSized(role, store.NoSizeLimit)
+ if err != nil {
+ if _, ok := err.(store.ErrMetaNotFound); ok &&
+ // server snapshots are supported, and server timestamp management
+ // is required, so if either of these fail to load that's ok - especially
+ // if the repo is new
+ role == data.CanonicalSnapshotRole || role == data.CanonicalTimestampRole {
+ continue
+ }
+ return err
+ }
+ if err := b.Load(role, jsonBytes, 1, true); err != nil {
+ return err
+ }
+ }
+
+ tufRepo, _, err := b.Finish()
+ if err == nil {
+ r.tufRepo = tufRepo
+ }
+ return nil
+}
+
+// saveMetadata saves contents of r.tufRepo onto the local disk, creating
+// signatures as necessary, possibly prompting for passphrases.
+func (r *NotaryRepository) saveMetadata(ignoreSnapshot bool) error {
+ logrus.Debugf("Saving changes to Trusted Collection.")
+
+ rootJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalRootRole)
+ if err != nil {
+ return err
+ }
+ err = r.fileStore.Set(data.CanonicalRootRole, rootJSON)
+ if err != nil {
+ return err
+ }
+
+ targetsToSave := make(map[string][]byte)
+ for t := range r.tufRepo.Targets {
+ signedTargets, err := r.tufRepo.SignTargets(t, data.DefaultExpires(data.CanonicalTargetsRole))
+ if err != nil {
+ return err
+ }
+ targetsJSON, err := json.Marshal(signedTargets)
+ if err != nil {
+ return err
+ }
+ targetsToSave[t] = targetsJSON
+ }
+
+ for role, blob := range targetsToSave {
+ parentDir := filepath.Dir(role)
+ os.MkdirAll(parentDir, 0755)
+ r.fileStore.Set(role, blob)
+ }
+
+ if ignoreSnapshot {
+ return nil
+ }
+
+ snapshotJSON, err := serializeCanonicalRole(r.tufRepo, data.CanonicalSnapshotRole)
+ if err != nil {
+ return err
+ }
+
+ return r.fileStore.Set(data.CanonicalSnapshotRole, snapshotJSON)
+}
+
+// returns a properly constructed ErrRepositoryNotExist error based on this
+// repo's information
+func (r *NotaryRepository) errRepositoryNotExist() error {
+ host := r.baseURL
+ parsed, err := url.Parse(r.baseURL)
+ if err == nil {
+ host = parsed.Host // try to exclude the scheme and any paths
+ }
+ return ErrRepositoryNotExist{remote: host, gun: r.gun}
+}
+
+// Update bootstraps a trust anchor (root.json) before updating all the
+// metadata from the repo.
+func (r *NotaryRepository) Update(forWrite bool) error {
+ c, err := r.bootstrapClient(forWrite)
+ if err != nil {
+ if _, ok := err.(store.ErrMetaNotFound); ok {
+ return r.errRepositoryNotExist()
+ }
+ return err
+ }
+ repo, invalid, err := c.Update()
+ if err != nil {
+ // notFound.Resource may include a checksum so when the role is root,
+ // it will be root or root.<checksum>. Therefore best we can
+ // do it match a "root." prefix
+ if notFound, ok := err.(store.ErrMetaNotFound); ok && strings.HasPrefix(notFound.Resource, data.CanonicalRootRole+".") {
+ return r.errRepositoryNotExist()
+ }
+ return err
+ }
+ // we can be assured if we are at this stage that the repo we built is good
+ // no need to test the following function call for an error as it will always be fine should the repo be good- it is!
+ r.tufRepo = repo
+ r.invalid = invalid
+ warnRolesNearExpiry(repo)
+ return nil
+}
+
+// bootstrapClient attempts to bootstrap a root.json to be used as the trust
+// anchor for a repository. The checkInitialized argument indicates whether
+// we should always attempt to contact the server to determine if the repository
+// is initialized or not. If set to true, we will always attempt to download
+// and return an error if the remote repository errors.
+//
+// Populates a tuf.RepoBuilder with this root metadata (only use
+// TUFClient.Update to load the rest).
+//
+// Fails if the remote server is reachable and does not know the repo
+// (i.e. before the first r.Publish()), in which case the error is
+// store.ErrMetaNotFound, or if the root metadata (from whichever source is used)
+// is not trusted.
+//
+// Returns a TUFClient for the remote server, which may not be actually
+// operational (if the URL is invalid but a root.json is cached).
+func (r *NotaryRepository) bootstrapClient(checkInitialized bool) (*TUFClient, error) {
+ minVersion := 1
+ // the old root on disk should not be validated against any trust pinning configuration
+ // because if we have an old root, it itself is the thing that pins trust
+ oldBuilder := tuf.NewRepoBuilder(r.gun, r.CryptoService, trustpinning.TrustPinConfig{})
+
+ // by default, we want to use the trust pinning configuration on any new root that we download
+ newBuilder := tuf.NewRepoBuilder(r.gun, r.CryptoService, r.trustPinning)
+
+ // Try to read root from cache first. We will trust this root until we detect a problem
+ // during update which will cause us to download a new root and perform a rotation.
+ // If we have an old root, and it's valid, then we overwrite the newBuilder to be one
+ // preloaded with the old root or one which uses the old root for trust bootstrapping.
+ if rootJSON, err := r.fileStore.GetSized(data.CanonicalRootRole, store.NoSizeLimit); err == nil {
+ // if we can't load the cached root, fail hard because that is how we pin trust
+ if err := oldBuilder.Load(data.CanonicalRootRole, rootJSON, minVersion, true); err != nil {
+ return nil, err
+ }
+
+ // again, the root on disk is the source of trust pinning, so use an empty trust
+ // pinning configuration
+ newBuilder = tuf.NewRepoBuilder(r.gun, r.CryptoService, trustpinning.TrustPinConfig{})
+
+ if err := newBuilder.Load(data.CanonicalRootRole, rootJSON, minVersion, false); err != nil {
+ // Ok, the old root is expired - we want to download a new one. But we want to use the
+ // old root to verify the new root, so bootstrap a new builder with the old builder
+ // but use the trustpinning to validate the new root
+ minVersion = oldBuilder.GetLoadedVersion(data.CanonicalRootRole)
+ newBuilder = oldBuilder.BootstrapNewBuilderWithNewTrustpin(r.trustPinning)
+ }
+ }
+
+ remote, remoteErr := getRemoteStore(r.baseURL, r.gun, r.roundTrip)
+ if remoteErr != nil {
+ logrus.Error(remoteErr)
+ } else if !newBuilder.IsLoaded(data.CanonicalRootRole) || checkInitialized {
+ // remoteErr was nil and we were not able to load a root from cache or
+ // are specifically checking for initialization of the repo.
+
+ // if remote store successfully set up, try and get root from remote
+ // We don't have any local data to determine the size of root, so try the maximum (though it is restricted at 100MB)
+ tmpJSON, err := remote.GetSized(data.CanonicalRootRole, store.NoSizeLimit)
+ if err != nil {
+ // we didn't have a root in cache and were unable to load one from
+ // the server. Nothing we can do but error.
+ return nil, err
+ }
+
+ if !newBuilder.IsLoaded(data.CanonicalRootRole) {
+ // we always want to use the downloaded root if we couldn't load from cache
+ if err := newBuilder.Load(data.CanonicalRootRole, tmpJSON, minVersion, false); err != nil {
+ return nil, err
+ }
+
+ err = r.fileStore.Set(data.CanonicalRootRole, tmpJSON)
+ if err != nil {
+ // if we can't write cache we should still continue, just log error
+ logrus.Errorf("could not save root to cache: %s", err.Error())
+ }
+ }
+ }
+
+ // We can only get here if remoteErr != nil (hence we don't download any new root),
+ // and there was no root on disk
+ if !newBuilder.IsLoaded(data.CanonicalRootRole) {
+ return nil, ErrRepoNotInitialized{}
+ }
+
+ return NewTUFClient(oldBuilder, newBuilder, remote, r.fileStore), nil
+}
+
+// RotateKey removes all existing keys associated with the role, and either
+// creates and adds one new key or delegates managing the key to the server.
+// These changes are staged in a changelist until publish is called.
+func (r *NotaryRepository) RotateKey(role string, serverManagesKey bool) error {
+ // We currently support remotely managing timestamp and snapshot keys
+ canBeRemoteKey := role == data.CanonicalTimestampRole || role == data.CanonicalSnapshotRole
+ // And locally managing root, targets, and snapshot keys
+ canBeLocalKey := (role == data.CanonicalSnapshotRole || role == data.CanonicalTargetsRole ||
+ role == data.CanonicalRootRole)
+
+ switch {
+ case !data.ValidRole(role) || data.IsDelegation(role):
+ return fmt.Errorf("notary does not currently permit rotating the %s key", role)
+ case serverManagesKey && !canBeRemoteKey:
+ return ErrInvalidRemoteRole{Role: role}
+ case !serverManagesKey && !canBeLocalKey:
+ return ErrInvalidLocalRole{Role: role}
+ }
+
+ var (
+ pubKey data.PublicKey
+ err error
+ errFmtMsg string
+ )
+ switch serverManagesKey {
+ case true:
+ pubKey, err = rotateRemoteKey(r.baseURL, r.gun, role, r.roundTrip)
+ errFmtMsg = "unable to rotate remote key: %s"
+ default:
+ pubKey, err = r.CryptoService.Create(role, r.gun, data.ECDSAKey)
+ errFmtMsg = "unable to generate key: %s"
+ }
+
+ if err != nil {
+ return fmt.Errorf(errFmtMsg, err)
+ }
+
+ // if this is a root role, generate a root cert for the public key
+ if role == data.CanonicalRootRole {
+ privKey, _, err := r.CryptoService.GetPrivateKey(pubKey.ID())
+ if err != nil {
+ return err
+ }
+ pubKey, err = rootCertKey(r.gun, privKey)
+ if err != nil {
+ return err
+ }
+ }
+
+ cl := changelist.NewMemChangelist()
+ if err := r.rootFileKeyChange(cl, role, changelist.ActionCreate, pubKey); err != nil {
+ return err
+ }
+ return r.publish(cl)
+}
+
+func (r *NotaryRepository) rootFileKeyChange(cl changelist.Changelist, role, action string, key data.PublicKey) error {
+ kl := make(data.KeyList, 0, 1)
+ kl = append(kl, key)
+ meta := changelist.TUFRootData{
+ RoleName: role,
+ Keys: kl,
+ }
+ metaJSON, err := json.Marshal(meta)
+ if err != nil {
+ return err
+ }
+
+ c := changelist.NewTUFChange(
+ action,
+ changelist.ScopeRoot,
+ changelist.TypeRootRole,
+ role,
+ metaJSON,
+ )
+ return cl.Add(c)
+}
+
+// DeleteTrustData removes the trust data stored for this repo in the TUF cache on the client side
+// Note that we will not delete any private key material from local storage
+func (r *NotaryRepository) DeleteTrustData(deleteRemote bool) error {
+ // Remove the tufRepoPath directory, which includes local TUF metadata files and changelist information
+ if err := os.RemoveAll(r.tufRepoPath); err != nil {
+ return fmt.Errorf("error clearing TUF repo data: %v", err)
+ }
+ // Note that this will require admin permission in this NotaryRepository's roundtripper
+ if deleteRemote {
+ remote, err := getRemoteStore(r.baseURL, r.gun, r.roundTrip)
+ if err != nil {
+ return err
+ }
+ if err := remote.RemoveAll(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/notary/client/delegations.go b/vendor/github.com/docker/notary/client/delegations.go
new file mode 100644
index 0000000..9b5a40f
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/delegations.go
@@ -0,0 +1,299 @@
+package client
+
+import (
+ "encoding/json"
+ "fmt"
+ "path/filepath"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary"
+ "github.com/docker/notary/client/changelist"
+ store "github.com/docker/notary/storage"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/utils"
+)
+
+// AddDelegation creates changelist entries to add provided delegation public keys and paths.
+// This method composes AddDelegationRoleAndKeys and AddDelegationPaths (each creates one changelist if called).
+func (r *NotaryRepository) AddDelegation(name string, delegationKeys []data.PublicKey, paths []string) error {
+ if len(delegationKeys) > 0 {
+ err := r.AddDelegationRoleAndKeys(name, delegationKeys)
+ if err != nil {
+ return err
+ }
+ }
+ if len(paths) > 0 {
+ err := r.AddDelegationPaths(name, paths)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// AddDelegationRoleAndKeys creates a changelist entry to add provided delegation public keys.
+// This method is the simplest way to create a new delegation, because the delegation must have at least
+// one key upon creation to be valid since we will reject the changelist while validating the threshold.
+func (r *NotaryRepository) AddDelegationRoleAndKeys(name string, delegationKeys []data.PublicKey) error {
+
+ if !data.IsDelegation(name) {
+ return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
+ }
+
+ cl, err := changelist.NewFileChangelist(filepath.Join(r.tufRepoPath, "changelist"))
+ if err != nil {
+ return err
+ }
+ defer cl.Close()
+
+ logrus.Debugf(`Adding delegation "%s" with threshold %d, and %d keys\n`,
+ name, notary.MinThreshold, len(delegationKeys))
+
+ // Defaulting to threshold of 1, since we don't allow for larger thresholds at the moment.
+ tdJSON, err := json.Marshal(&changelist.TUFDelegation{
+ NewThreshold: notary.MinThreshold,
+ AddKeys: data.KeyList(delegationKeys),
+ })
+ if err != nil {
+ return err
+ }
+
+ template := newCreateDelegationChange(name, tdJSON)
+ return addChange(cl, template, name)
+}
+
+// AddDelegationPaths creates a changelist entry to add provided paths to an existing delegation.
+// This method cannot create a new delegation itself because the role must meet the key threshold upon creation.
+func (r *NotaryRepository) AddDelegationPaths(name string, paths []string) error {
+
+ if !data.IsDelegation(name) {
+ return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
+ }
+
+ cl, err := changelist.NewFileChangelist(filepath.Join(r.tufRepoPath, "changelist"))
+ if err != nil {
+ return err
+ }
+ defer cl.Close()
+
+ logrus.Debugf(`Adding %s paths to delegation %s\n`, paths, name)
+
+ tdJSON, err := json.Marshal(&changelist.TUFDelegation{
+ AddPaths: paths,
+ })
+ if err != nil {
+ return err
+ }
+
+ template := newCreateDelegationChange(name, tdJSON)
+ return addChange(cl, template, name)
+}
+
+// RemoveDelegationKeysAndPaths creates changelist entries to remove provided delegation key IDs and paths.
+// This method composes RemoveDelegationPaths and RemoveDelegationKeys (each creates one changelist if called).
+func (r *NotaryRepository) RemoveDelegationKeysAndPaths(name string, keyIDs, paths []string) error {
+ if len(paths) > 0 {
+ err := r.RemoveDelegationPaths(name, paths)
+ if err != nil {
+ return err
+ }
+ }
+ if len(keyIDs) > 0 {
+ err := r.RemoveDelegationKeys(name, keyIDs)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// RemoveDelegationRole creates a changelist to remove all paths and keys from a role, and delete the role in its entirety.
+func (r *NotaryRepository) RemoveDelegationRole(name string) error {
+
+ if !data.IsDelegation(name) {
+ return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
+ }
+
+ cl, err := changelist.NewFileChangelist(filepath.Join(r.tufRepoPath, "changelist"))
+ if err != nil {
+ return err
+ }
+ defer cl.Close()
+
+ logrus.Debugf(`Removing delegation "%s"\n`, name)
+
+ template := newDeleteDelegationChange(name, nil)
+ return addChange(cl, template, name)
+}
+
+// RemoveDelegationPaths creates a changelist entry to remove provided paths from an existing delegation.
+func (r *NotaryRepository) RemoveDelegationPaths(name string, paths []string) error {
+
+ if !data.IsDelegation(name) {
+ return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
+ }
+
+ cl, err := changelist.NewFileChangelist(filepath.Join(r.tufRepoPath, "changelist"))
+ if err != nil {
+ return err
+ }
+ defer cl.Close()
+
+ logrus.Debugf(`Removing %s paths from delegation "%s"\n`, paths, name)
+
+ tdJSON, err := json.Marshal(&changelist.TUFDelegation{
+ RemovePaths: paths,
+ })
+ if err != nil {
+ return err
+ }
+
+ template := newUpdateDelegationChange(name, tdJSON)
+ return addChange(cl, template, name)
+}
+
+// RemoveDelegationKeys creates a changelist entry to remove provided keys from an existing delegation.
+// When this changelist is applied, if the specified keys are the only keys left in the role,
+// the role itself will be deleted in its entirety.
+// It can also delete a key from all delegations under a parent using a name
+// with a wildcard at the end.
+func (r *NotaryRepository) RemoveDelegationKeys(name string, keyIDs []string) error {
+
+ if !data.IsDelegation(name) && !data.IsWildDelegation(name) {
+ return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
+ }
+
+ cl, err := changelist.NewFileChangelist(filepath.Join(r.tufRepoPath, "changelist"))
+ if err != nil {
+ return err
+ }
+ defer cl.Close()
+
+ logrus.Debugf(`Removing %s keys from delegation "%s"\n`, keyIDs, name)
+
+ tdJSON, err := json.Marshal(&changelist.TUFDelegation{
+ RemoveKeys: keyIDs,
+ })
+ if err != nil {
+ return err
+ }
+
+ template := newUpdateDelegationChange(name, tdJSON)
+ return addChange(cl, template, name)
+}
+
+// ClearDelegationPaths creates a changelist entry to remove all paths from an existing delegation.
+func (r *NotaryRepository) ClearDelegationPaths(name string) error {
+
+ if !data.IsDelegation(name) {
+ return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
+ }
+
+ cl, err := changelist.NewFileChangelist(filepath.Join(r.tufRepoPath, "changelist"))
+ if err != nil {
+ return err
+ }
+ defer cl.Close()
+
+ logrus.Debugf(`Removing all paths from delegation "%s"\n`, name)
+
+ tdJSON, err := json.Marshal(&changelist.TUFDelegation{
+ ClearAllPaths: true,
+ })
+ if err != nil {
+ return err
+ }
+
+ template := newUpdateDelegationChange(name, tdJSON)
+ return addChange(cl, template, name)
+}
+
+func newUpdateDelegationChange(name string, content []byte) *changelist.TUFChange {
+ return changelist.NewTUFChange(
+ changelist.ActionUpdate,
+ name,
+ changelist.TypeTargetsDelegation,
+ "", // no path for delegations
+ content,
+ )
+}
+
+func newCreateDelegationChange(name string, content []byte) *changelist.TUFChange {
+ return changelist.NewTUFChange(
+ changelist.ActionCreate,
+ name,
+ changelist.TypeTargetsDelegation,
+ "", // no path for delegations
+ content,
+ )
+}
+
+func newDeleteDelegationChange(name string, content []byte) *changelist.TUFChange {
+ return changelist.NewTUFChange(
+ changelist.ActionDelete,
+ name,
+ changelist.TypeTargetsDelegation,
+ "", // no path for delegations
+ content,
+ )
+}
+
+// GetDelegationRoles returns the keys and roles of the repository's delegations
+// Also converts key IDs to canonical key IDs to keep consistent with signing prompts
+func (r *NotaryRepository) GetDelegationRoles() ([]data.Role, error) {
+ // Update state of the repo to latest
+ if err := r.Update(false); err != nil {
+ return nil, err
+ }
+
+ // All top level delegations (ex: targets/level1) are stored exclusively in targets.json
+ _, ok := r.tufRepo.Targets[data.CanonicalTargetsRole]
+ if !ok {
+ return nil, store.ErrMetaNotFound{Resource: data.CanonicalTargetsRole}
+ }
+
+ // make a copy for traversing nested delegations
+ allDelegations := []data.Role{}
+
+ // Define a visitor function to populate the delegations list and translate their key IDs to canonical IDs
+ delegationCanonicalListVisitor := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
+ // For the return list, update with a copy that includes canonicalKeyIDs
+ // These aren't validated by the validRole
+ canonicalDelegations, err := translateDelegationsToCanonicalIDs(tgt.Signed.Delegations)
+ if err != nil {
+ return err
+ }
+ allDelegations = append(allDelegations, canonicalDelegations...)
+ return nil
+ }
+ err := r.tufRepo.WalkTargets("", "", delegationCanonicalListVisitor)
+ if err != nil {
+ return nil, err
+ }
+ return allDelegations, nil
+}
+
+func translateDelegationsToCanonicalIDs(delegationInfo data.Delegations) ([]data.Role, error) {
+ canonicalDelegations := make([]data.Role, len(delegationInfo.Roles))
+ // Do a copy by value to ensure local delegation metadata is untouched
+ for idx, origRole := range delegationInfo.Roles {
+ canonicalDelegations[idx] = *origRole
+ }
+ delegationKeys := delegationInfo.Keys
+ for i, delegation := range canonicalDelegations {
+ canonicalKeyIDs := []string{}
+ for _, keyID := range delegation.KeyIDs {
+ pubKey, ok := delegationKeys[keyID]
+ if !ok {
+ return []data.Role{}, fmt.Errorf("Could not translate canonical key IDs for %s", delegation.Name)
+ }
+ canonicalKeyID, err := utils.CanonicalKeyID(pubKey)
+ if err != nil {
+ return []data.Role{}, fmt.Errorf("Could not translate canonical key IDs for %s: %v", delegation.Name, err)
+ }
+ canonicalKeyIDs = append(canonicalKeyIDs, canonicalKeyID)
+ }
+ canonicalDelegations[i].KeyIDs = canonicalKeyIDs
+ }
+ return canonicalDelegations, nil
+}
diff --git a/vendor/github.com/docker/notary/client/helpers.go b/vendor/github.com/docker/notary/client/helpers.go
new file mode 100644
index 0000000..11691f6
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/helpers.go
@@ -0,0 +1,278 @@
+package client
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary/client/changelist"
+ store "github.com/docker/notary/storage"
+ "github.com/docker/notary/tuf"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/utils"
+)
+
+// Use this to initialize remote HTTPStores from the config settings
+func getRemoteStore(baseURL, gun string, rt http.RoundTripper) (store.RemoteStore, error) {
+ s, err := store.NewHTTPStore(
+ baseURL+"/v2/"+gun+"/_trust/tuf/",
+ "",
+ "json",
+ "key",
+ rt,
+ )
+ if err != nil {
+ return store.OfflineStore{}, err
+ }
+ return s, err
+}
+
+func applyChangelist(repo *tuf.Repo, invalid *tuf.Repo, cl changelist.Changelist) error {
+ it, err := cl.NewIterator()
+ if err != nil {
+ return err
+ }
+ index := 0
+ for it.HasNext() {
+ c, err := it.Next()
+ if err != nil {
+ return err
+ }
+ isDel := data.IsDelegation(c.Scope()) || data.IsWildDelegation(c.Scope())
+ switch {
+ case c.Scope() == changelist.ScopeTargets || isDel:
+ err = applyTargetsChange(repo, invalid, c)
+ case c.Scope() == changelist.ScopeRoot:
+ err = applyRootChange(repo, c)
+ default:
+ return fmt.Errorf("scope not supported: %s", c.Scope())
+ }
+ if err != nil {
+ logrus.Debugf("error attempting to apply change #%d: %s, on scope: %s path: %s type: %s", index, c.Action(), c.Scope(), c.Path(), c.Type())
+ return err
+ }
+ index++
+ }
+ logrus.Debugf("applied %d change(s)", index)
+ return nil
+}
+
+func applyTargetsChange(repo *tuf.Repo, invalid *tuf.Repo, c changelist.Change) error {
+ switch c.Type() {
+ case changelist.TypeTargetsTarget:
+ return changeTargetMeta(repo, c)
+ case changelist.TypeTargetsDelegation:
+ return changeTargetsDelegation(repo, c)
+ case changelist.TypeWitness:
+ return witnessTargets(repo, invalid, c.Scope())
+ default:
+ return fmt.Errorf("only target meta and delegations changes supported")
+ }
+}
+
+func changeTargetsDelegation(repo *tuf.Repo, c changelist.Change) error {
+ switch c.Action() {
+ case changelist.ActionCreate:
+ td := changelist.TUFDelegation{}
+ err := json.Unmarshal(c.Content(), &td)
+ if err != nil {
+ return err
+ }
+
+ // Try to create brand new role or update one
+ // First add the keys, then the paths. We can only add keys and paths in this scenario
+ err = repo.UpdateDelegationKeys(c.Scope(), td.AddKeys, []string{}, td.NewThreshold)
+ if err != nil {
+ return err
+ }
+ return repo.UpdateDelegationPaths(c.Scope(), td.AddPaths, []string{}, false)
+ case changelist.ActionUpdate:
+ td := changelist.TUFDelegation{}
+ err := json.Unmarshal(c.Content(), &td)
+ if err != nil {
+ return err
+ }
+ if data.IsWildDelegation(c.Scope()) {
+ return repo.PurgeDelegationKeys(c.Scope(), td.RemoveKeys)
+ }
+
+ delgRole, err := repo.GetDelegationRole(c.Scope())
+ if err != nil {
+ return err
+ }
+
+ // We need to translate the keys from canonical ID to TUF ID for compatibility
+ canonicalToTUFID := make(map[string]string)
+ for tufID, pubKey := range delgRole.Keys {
+ canonicalID, err := utils.CanonicalKeyID(pubKey)
+ if err != nil {
+ return err
+ }
+ canonicalToTUFID[canonicalID] = tufID
+ }
+
+ removeTUFKeyIDs := []string{}
+ for _, canonID := range td.RemoveKeys {
+ removeTUFKeyIDs = append(removeTUFKeyIDs, canonicalToTUFID[canonID])
+ }
+
+ err = repo.UpdateDelegationKeys(c.Scope(), td.AddKeys, removeTUFKeyIDs, td.NewThreshold)
+ if err != nil {
+ return err
+ }
+ return repo.UpdateDelegationPaths(c.Scope(), td.AddPaths, td.RemovePaths, td.ClearAllPaths)
+ case changelist.ActionDelete:
+ return repo.DeleteDelegation(c.Scope())
+ default:
+ return fmt.Errorf("unsupported action against delegations: %s", c.Action())
+ }
+
+}
+
+func changeTargetMeta(repo *tuf.Repo, c changelist.Change) error {
+ var err error
+ switch c.Action() {
+ case changelist.ActionCreate:
+ logrus.Debug("changelist add: ", c.Path())
+ meta := &data.FileMeta{}
+ err = json.Unmarshal(c.Content(), meta)
+ if err != nil {
+ return err
+ }
+ files := data.Files{c.Path(): *meta}
+
+ // Attempt to add the target to this role
+ if _, err = repo.AddTargets(c.Scope(), files); err != nil {
+ logrus.Errorf("couldn't add target to %s: %s", c.Scope(), err.Error())
+ }
+
+ case changelist.ActionDelete:
+ logrus.Debug("changelist remove: ", c.Path())
+
+ // Attempt to remove the target from this role
+ if err = repo.RemoveTargets(c.Scope(), c.Path()); err != nil {
+ logrus.Errorf("couldn't remove target from %s: %s", c.Scope(), err.Error())
+ }
+
+ default:
+ err = fmt.Errorf("action not yet supported: %s", c.Action())
+ }
+ return err
+}
+
+func applyRootChange(repo *tuf.Repo, c changelist.Change) error {
+ var err error
+ switch c.Type() {
+ case changelist.TypeRootRole:
+ err = applyRootRoleChange(repo, c)
+ default:
+ err = fmt.Errorf("type of root change not yet supported: %s", c.Type())
+ }
+ return err // might be nil
+}
+
+func applyRootRoleChange(repo *tuf.Repo, c changelist.Change) error {
+ switch c.Action() {
+ case changelist.ActionCreate:
+ // replaces all keys for a role
+ d := &changelist.TUFRootData{}
+ err := json.Unmarshal(c.Content(), d)
+ if err != nil {
+ return err
+ }
+ err = repo.ReplaceBaseKeys(d.RoleName, d.Keys...)
+ if err != nil {
+ return err
+ }
+ default:
+ return fmt.Errorf("action not yet supported for root: %s", c.Action())
+ }
+ return nil
+}
+
+func nearExpiry(r data.SignedCommon) bool {
+ plus6mo := time.Now().AddDate(0, 6, 0)
+ return r.Expires.Before(plus6mo)
+}
+
+func warnRolesNearExpiry(r *tuf.Repo) {
+ //get every role and its respective signed common and call nearExpiry on it
+ //Root check
+ if nearExpiry(r.Root.Signed.SignedCommon) {
+ logrus.Warn("root is nearing expiry, you should re-sign the role metadata")
+ }
+ //Targets and delegations check
+ for role, signedTOrD := range r.Targets {
+ //signedTOrD is of type *data.SignedTargets
+ if nearExpiry(signedTOrD.Signed.SignedCommon) {
+ logrus.Warn(role, " metadata is nearing expiry, you should re-sign the role metadata")
+ }
+ }
+ //Snapshot check
+ if nearExpiry(r.Snapshot.Signed.SignedCommon) {
+ logrus.Warn("snapshot is nearing expiry, you should re-sign the role metadata")
+ }
+ //do not need to worry about Timestamp, notary signer will re-sign with the timestamp key
+}
+
+// Fetches a public key from a remote store, given a gun and role
+func getRemoteKey(url, gun, role string, rt http.RoundTripper) (data.PublicKey, error) {
+ remote, err := getRemoteStore(url, gun, rt)
+ if err != nil {
+ return nil, err
+ }
+ rawPubKey, err := remote.GetKey(role)
+ if err != nil {
+ return nil, err
+ }
+
+ pubKey, err := data.UnmarshalPublicKey(rawPubKey)
+ if err != nil {
+ return nil, err
+ }
+
+ return pubKey, nil
+}
+
+// Rotates a private key in a remote store and returns the public key component
+func rotateRemoteKey(url, gun, role string, rt http.RoundTripper) (data.PublicKey, error) {
+ remote, err := getRemoteStore(url, gun, rt)
+ if err != nil {
+ return nil, err
+ }
+ rawPubKey, err := remote.RotateKey(role)
+ if err != nil {
+ return nil, err
+ }
+
+ pubKey, err := data.UnmarshalPublicKey(rawPubKey)
+ if err != nil {
+ return nil, err
+ }
+
+ return pubKey, nil
+}
+
+// signs and serializes the metadata for a canonical role in a TUF repo to JSON
+func serializeCanonicalRole(tufRepo *tuf.Repo, role string) (out []byte, err error) {
+ var s *data.Signed
+ switch {
+ case role == data.CanonicalRootRole:
+ s, err = tufRepo.SignRoot(data.DefaultExpires(role))
+ case role == data.CanonicalSnapshotRole:
+ s, err = tufRepo.SignSnapshot(data.DefaultExpires(role))
+ case tufRepo.Targets[role] != nil:
+ s, err = tufRepo.SignTargets(
+ role, data.DefaultExpires(data.CanonicalTargetsRole))
+ default:
+ err = fmt.Errorf("%s not supported role to sign on the client", role)
+ }
+
+ if err != nil {
+ return
+ }
+
+ return json.Marshal(s)
+}
diff --git a/vendor/github.com/docker/notary/client/repo.go b/vendor/github.com/docker/notary/client/repo.go
new file mode 100644
index 0000000..27f8576
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/repo.go
@@ -0,0 +1,29 @@
+// +build !pkcs11
+
+package client
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/docker/notary"
+ "github.com/docker/notary/trustmanager"
+ "github.com/docker/notary/trustpinning"
+)
+
+// NewNotaryRepository is a helper method that returns a new notary repository.
+// It takes the base directory under where all the trust files will be stored
+// (This is normally defaults to "~/.notary" or "~/.docker/trust" when enabling
+// docker content trust).
+func NewNotaryRepository(baseDir, gun, baseURL string, rt http.RoundTripper,
+ retriever notary.PassRetriever, trustPinning trustpinning.TrustPinConfig) (
+ *NotaryRepository, error) {
+
+ fileKeyStore, err := trustmanager.NewKeyFileStore(baseDir, retriever)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create private key store in directory: %s", baseDir)
+ }
+
+ return repositoryFromKeystores(baseDir, gun, baseURL, rt,
+ []trustmanager.KeyStore{fileKeyStore}, trustPinning)
+}
diff --git a/vendor/github.com/docker/notary/client/repo_pkcs11.go b/vendor/github.com/docker/notary/client/repo_pkcs11.go
new file mode 100644
index 0000000..bbbe476
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/repo_pkcs11.go
@@ -0,0 +1,34 @@
+// +build pkcs11
+
+package client
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/docker/notary"
+ "github.com/docker/notary/trustmanager"
+ "github.com/docker/notary/trustmanager/yubikey"
+ "github.com/docker/notary/trustpinning"
+)
+
+// NewNotaryRepository is a helper method that returns a new notary repository.
+// It takes the base directory under where all the trust files will be stored
+// (usually ~/.docker/trust/).
+func NewNotaryRepository(baseDir, gun, baseURL string, rt http.RoundTripper,
+ retriever notary.PassRetriever, trustPinning trustpinning.TrustPinConfig) (
+ *NotaryRepository, error) {
+
+ fileKeyStore, err := trustmanager.NewKeyFileStore(baseDir, retriever)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create private key store in directory: %s", baseDir)
+ }
+
+ keyStores := []trustmanager.KeyStore{fileKeyStore}
+ yubiKeyStore, _ := yubikey.NewYubiStore(fileKeyStore, retriever)
+ if yubiKeyStore != nil {
+ keyStores = []trustmanager.KeyStore{yubiKeyStore, fileKeyStore}
+ }
+
+ return repositoryFromKeystores(baseDir, gun, baseURL, rt, keyStores, trustPinning)
+}
diff --git a/vendor/github.com/docker/notary/client/tufclient.go b/vendor/github.com/docker/notary/client/tufclient.go
new file mode 100644
index 0000000..a6abdac
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/tufclient.go
@@ -0,0 +1,239 @@
+package client
+
+import (
+ "encoding/json"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary"
+ store "github.com/docker/notary/storage"
+ "github.com/docker/notary/tuf"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/signed"
+)
+
+// TUFClient is a usability wrapper around a raw TUF repo
+type TUFClient struct {
+ remote store.RemoteStore
+ cache store.MetadataStore
+ oldBuilder tuf.RepoBuilder
+ newBuilder tuf.RepoBuilder
+}
+
+// NewTUFClient initialized a TUFClient with the given repo, remote source of content, and cache
+func NewTUFClient(oldBuilder, newBuilder tuf.RepoBuilder, remote store.RemoteStore, cache store.MetadataStore) *TUFClient {
+ return &TUFClient{
+ oldBuilder: oldBuilder,
+ newBuilder: newBuilder,
+ remote: remote,
+ cache: cache,
+ }
+}
+
+// Update performs an update to the TUF repo as defined by the TUF spec
+func (c *TUFClient) Update() (*tuf.Repo, *tuf.Repo, error) {
+ // 1. Get timestamp
+ // a. If timestamp error (verification, expired, etc...) download new root and return to 1.
+ // 2. Check if local snapshot is up to date
+ // a. If out of date, get updated snapshot
+ // i. If snapshot error, download new root and return to 1.
+ // 3. Check if root correct against snapshot
+ // a. If incorrect, download new root and return to 1.
+ // 4. Iteratively download and search targets and delegations to find target meta
+ logrus.Debug("updating TUF client")
+ err := c.update()
+ if err != nil {
+ logrus.Debug("Error occurred. Root will be downloaded and another update attempted")
+ logrus.Debug("Resetting the TUF builder...")
+
+ c.newBuilder = c.newBuilder.BootstrapNewBuilder()
+
+ if err := c.downloadRoot(); err != nil {
+ logrus.Debug("Client Update (Root):", err)
+ return nil, nil, err
+ }
+ // If we error again, we now have the latest root and just want to fail
+ // out as there's no expectation the problem can be resolved automatically
+ logrus.Debug("retrying TUF client update")
+ if err := c.update(); err != nil {
+ return nil, nil, err
+ }
+ }
+ return c.newBuilder.Finish()
+}
+
+func (c *TUFClient) update() error {
+ if err := c.downloadTimestamp(); err != nil {
+ logrus.Debugf("Client Update (Timestamp): %s", err.Error())
+ return err
+ }
+ if err := c.downloadSnapshot(); err != nil {
+ logrus.Debugf("Client Update (Snapshot): %s", err.Error())
+ return err
+ }
+ // will always need top level targets at a minimum
+ if err := c.downloadTargets(); err != nil {
+ logrus.Debugf("Client Update (Targets): %s", err.Error())
+ return err
+ }
+ return nil
+}
+
+// downloadRoot is responsible for downloading the root.json
+func (c *TUFClient) downloadRoot() error {
+ role := data.CanonicalRootRole
+ consistentInfo := c.newBuilder.GetConsistentInfo(role)
+
+ // We can't read an exact size for the root metadata without risking getting stuck in the TUF update cycle
+ // since it's possible that downloading timestamp/snapshot metadata may fail due to a signature mismatch
+ if !consistentInfo.ChecksumKnown() {
+ logrus.Debugf("Loading root with no expected checksum")
+
+ // get the cached root, if it exists, just for version checking
+ cachedRoot, _ := c.cache.GetSized(role, -1)
+ // prefer to download a new root
+ _, remoteErr := c.tryLoadRemote(consistentInfo, cachedRoot)
+ return remoteErr
+ }
+
+ _, err := c.tryLoadCacheThenRemote(consistentInfo)
+ return err
+}
+
+// downloadTimestamp is responsible for downloading the timestamp.json
+// Timestamps are special in that we ALWAYS attempt to download and only
+// use cache if the download fails (and the cache is still valid).
+func (c *TUFClient) downloadTimestamp() error {
+ logrus.Debug("Loading timestamp...")
+ role := data.CanonicalTimestampRole
+ consistentInfo := c.newBuilder.GetConsistentInfo(role)
+
+ // always get the remote timestamp, since it supersedes the local one
+ cachedTS, cachedErr := c.cache.GetSized(role, notary.MaxTimestampSize)
+ _, remoteErr := c.tryLoadRemote(consistentInfo, cachedTS)
+
+ // check that there was no remote error, or if there was a network problem
+ // If there was a validation error, we should error out so we can download a new root or fail the update
+ switch remoteErr.(type) {
+ case nil:
+ return nil
+ case store.ErrMetaNotFound, store.ErrServerUnavailable, store.ErrOffline, store.NetworkError:
+ break
+ default:
+ return remoteErr
+ }
+
+ // since it was a network error: get the cached timestamp, if it exists
+ if cachedErr != nil {
+ logrus.Debug("no cached or remote timestamp available")
+ return remoteErr
+ }
+
+ logrus.Warn("Error while downloading remote metadata, using cached timestamp - this might not be the latest version available remotely")
+ err := c.newBuilder.Load(role, cachedTS, 1, false)
+ if err == nil {
+ logrus.Debug("successfully verified cached timestamp")
+ }
+ return err
+
+}
+
+// downloadSnapshot is responsible for downloading the snapshot.json
+func (c *TUFClient) downloadSnapshot() error {
+ logrus.Debug("Loading snapshot...")
+ role := data.CanonicalSnapshotRole
+ consistentInfo := c.newBuilder.GetConsistentInfo(role)
+
+ _, err := c.tryLoadCacheThenRemote(consistentInfo)
+ return err
+}
+
+// downloadTargets downloads all targets and delegated targets for the repository.
+// It uses a pre-order tree traversal as it's necessary to download parents first
+// to obtain the keys to validate children.
+func (c *TUFClient) downloadTargets() error {
+ toDownload := []data.DelegationRole{{
+ BaseRole: data.BaseRole{Name: data.CanonicalTargetsRole},
+ Paths: []string{""},
+ }}
+
+ for len(toDownload) > 0 {
+ role := toDownload[0]
+ toDownload = toDownload[1:]
+
+ consistentInfo := c.newBuilder.GetConsistentInfo(role.Name)
+ if !consistentInfo.ChecksumKnown() {
+ logrus.Debugf("skipping %s because there is no checksum for it", role.Name)
+ continue
+ }
+
+ children, err := c.getTargetsFile(role, consistentInfo)
+ switch err.(type) {
+ case signed.ErrExpired, signed.ErrRoleThreshold:
+ if role.Name == data.CanonicalTargetsRole {
+ return err
+ }
+ logrus.Warnf("Error getting %s: %s", role.Name, err)
+ break
+ case nil:
+ toDownload = append(children, toDownload...)
+ default:
+ return err
+ }
+ }
+ return nil
+}
+
+func (c TUFClient) getTargetsFile(role data.DelegationRole, ci tuf.ConsistentInfo) ([]data.DelegationRole, error) {
+ logrus.Debugf("Loading %s...", role.Name)
+ tgs := &data.SignedTargets{}
+
+ raw, err := c.tryLoadCacheThenRemote(ci)
+ if err != nil {
+ return nil, err
+ }
+
+ // we know it unmarshals because if `tryLoadCacheThenRemote` didn't fail, then
+ // the raw has already been loaded into the builder
+ json.Unmarshal(raw, tgs)
+ return tgs.GetValidDelegations(role), nil
+}
+
+func (c *TUFClient) tryLoadCacheThenRemote(consistentInfo tuf.ConsistentInfo) ([]byte, error) {
+ cachedTS, err := c.cache.GetSized(consistentInfo.RoleName, consistentInfo.Length())
+ if err != nil {
+ logrus.Debugf("no %s in cache, must download", consistentInfo.RoleName)
+ return c.tryLoadRemote(consistentInfo, nil)
+ }
+
+ if err = c.newBuilder.Load(consistentInfo.RoleName, cachedTS, 1, false); err == nil {
+ logrus.Debugf("successfully verified cached %s", consistentInfo.RoleName)
+ return cachedTS, nil
+ }
+
+ logrus.Debugf("cached %s is invalid (must download): %s", consistentInfo.RoleName, err)
+ return c.tryLoadRemote(consistentInfo, cachedTS)
+}
+
+func (c *TUFClient) tryLoadRemote(consistentInfo tuf.ConsistentInfo, old []byte) ([]byte, error) {
+ consistentName := consistentInfo.ConsistentName()
+ raw, err := c.remote.GetSized(consistentName, consistentInfo.Length())
+ if err != nil {
+ logrus.Debugf("error downloading %s: %s", consistentName, err)
+ return old, err
+ }
+
+ // try to load the old data into the old builder - only use it to validate
+ // versions if it loads successfully. If it errors, then the loaded version
+ // will be 1
+ c.oldBuilder.Load(consistentInfo.RoleName, old, 1, true)
+ minVersion := c.oldBuilder.GetLoadedVersion(consistentInfo.RoleName)
+ if err := c.newBuilder.Load(consistentInfo.RoleName, raw, minVersion, false); err != nil {
+ logrus.Debugf("downloaded %s is invalid: %s", consistentName, err)
+ return raw, err
+ }
+ logrus.Debugf("successfully verified downloaded %s", consistentName)
+ if err := c.cache.Set(consistentInfo.RoleName, raw); err != nil {
+ logrus.Debugf("Unable to write %s to cache: %s", consistentInfo.RoleName, err)
+ }
+ return raw, nil
+}
diff --git a/vendor/github.com/docker/notary/client/witness.go b/vendor/github.com/docker/notary/client/witness.go
new file mode 100644
index 0000000..21a42aa
--- /dev/null
+++ b/vendor/github.com/docker/notary/client/witness.go
@@ -0,0 +1,69 @@
+package client
+
+import (
+ "path/filepath"
+
+ "github.com/docker/notary/client/changelist"
+ "github.com/docker/notary/tuf"
+ "github.com/docker/notary/tuf/data"
+)
+
+// Witness creates change objects to witness (i.e. re-sign) the given
+// roles on the next publish. One change is created per role
+func (r *NotaryRepository) Witness(roles ...string) ([]string, error) {
+ cl, err := changelist.NewFileChangelist(filepath.Join(r.tufRepoPath, "changelist"))
+ if err != nil {
+ return nil, err
+ }
+ defer cl.Close()
+
+ successful := make([]string, 0, len(roles))
+ for _, role := range roles {
+ // scope is role
+ c := changelist.NewTUFChange(
+ changelist.ActionUpdate,
+ role,
+ changelist.TypeWitness,
+ "",
+ nil,
+ )
+ err = cl.Add(c)
+ if err != nil {
+ break
+ }
+ successful = append(successful, role)
+ }
+ return successful, err
+}
+
+func witnessTargets(repo *tuf.Repo, invalid *tuf.Repo, role string) error {
+ if r, ok := repo.Targets[role]; ok {
+ // role is already valid, mark for re-signing/updating
+ r.Dirty = true
+ return nil
+ }
+
+ if roleObj, err := repo.GetDelegationRole(role); err == nil && invalid != nil {
+ // A role with a threshold > len(keys) is technically invalid, but we let it build in the builder because
+ // we want to be able to download the role (which may still have targets on it), add more keys, and then
+ // witness the role, thus bringing it back to valid. However, if no keys have been added before witnessing,
+ // then it is still an invalid role, and can't be witnessed because nothing can bring it back to valid.
+ if roleObj.Threshold > len(roleObj.Keys) {
+ return data.ErrInvalidRole{
+ Role: role,
+ Reason: "role does not specify enough valid signing keys to meet its required threshold",
+ }
+ }
+ if r, ok := invalid.Targets[role]; ok {
+ // role is recognized but invalid, move to valid data and mark for re-signing
+ repo.Targets[role] = r
+ r.Dirty = true
+ return nil
+ }
+ }
+ // role isn't recognized, even as invalid
+ return data.ErrInvalidRole{
+ Role: role,
+ Reason: "this role is not known",
+ }
+}
diff --git a/vendor/github.com/docker/notary/const.go b/vendor/github.com/docker/notary/const.go
new file mode 100644
index 0000000..0c4d403
--- /dev/null
+++ b/vendor/github.com/docker/notary/const.go
@@ -0,0 +1,70 @@
+package notary
+
+import "time"
+
+// application wide constants
+const (
+ // MaxDownloadSize is the maximum size we'll download for metadata if no limit is given
+ MaxDownloadSize int64 = 100 << 20
+ // MaxTimestampSize is the maximum size of timestamp metadata - 1MiB.
+ MaxTimestampSize int64 = 1 << 20
+ // MinRSABitSize is the minimum bit size for RSA keys allowed in notary
+ MinRSABitSize = 2048
+ // MinThreshold requires a minimum of one threshold for roles; currently we do not support a higher threshold
+ MinThreshold = 1
+ // PrivKeyPerms are the file permissions to use when writing private keys to disk
+ PrivKeyPerms = 0700
+ // PubCertPerms are the file permissions to use when writing public certificates to disk
+ PubCertPerms = 0755
+ // Sha256HexSize is how big a Sha256 hex is in number of characters
+ Sha256HexSize = 64
+ // Sha512HexSize is how big a Sha512 hex is in number of characters
+ Sha512HexSize = 128
+ // SHA256 is the name of SHA256 hash algorithm
+ SHA256 = "sha256"
+ // SHA512 is the name of SHA512 hash algorithm
+ SHA512 = "sha512"
+ // TrustedCertsDir is the directory, under the notary repo base directory, where trusted certs are stored
+ TrustedCertsDir = "trusted_certificates"
+ // PrivDir is the directory, under the notary repo base directory, where private keys are stored
+ PrivDir = "private"
+ // RootKeysSubdir is the subdirectory under PrivDir where root private keys are stored
+ RootKeysSubdir = "root_keys"
+ // NonRootKeysSubdir is the subdirectory under PrivDir where non-root private keys are stored
+ NonRootKeysSubdir = "tuf_keys"
+ // KeyExtension is the file extension to use for private key files
+ KeyExtension = "key"
+
+ // Day is a duration of one day
+ Day = 24 * time.Hour
+ Year = 365 * Day
+
+ // NotaryRootExpiry is the duration representing the expiry time of the Root role
+ NotaryRootExpiry = 10 * Year
+ NotaryTargetsExpiry = 3 * Year
+ NotarySnapshotExpiry = 3 * Year
+ NotaryTimestampExpiry = 14 * Day
+
+ ConsistentMetadataCacheMaxAge = 30 * Day
+ CurrentMetadataCacheMaxAge = 5 * time.Minute
+ // CacheMaxAgeLimit is the generally recommended maximum age for Cache-Control headers
+ // (one year, in seconds, since one year is forever in terms of internet
+ // content)
+ CacheMaxAgeLimit = 1 * Year
+
+ MySQLBackend = "mysql"
+ MemoryBackend = "memory"
+ SQLiteBackend = "sqlite3"
+ RethinkDBBackend = "rethinkdb"
+
+ DefaultImportRole = "delegation"
+)
+
+// NotaryDefaultExpiries is the construct used to configure the default expiry times of
+// the various role files.
+var NotaryDefaultExpiries = map[string]time.Duration{
+ "root": NotaryRootExpiry,
+ "targets": NotaryTargetsExpiry,
+ "snapshot": NotarySnapshotExpiry,
+ "timestamp": NotaryTimestampExpiry,
+}
diff --git a/vendor/github.com/docker/notary/const_nowindows.go b/vendor/github.com/docker/notary/const_nowindows.go
new file mode 100644
index 0000000..6755171
--- /dev/null
+++ b/vendor/github.com/docker/notary/const_nowindows.go
@@ -0,0 +1,16 @@
+// +build !windows
+
+package notary
+
+import (
+ "os"
+ "syscall"
+)
+
+// NotarySupportedSignals contains the signals we would like to capture:
+// - SIGUSR1, indicates a increment of the log level.
+// - SIGUSR2, indicates a decrement of the log level.
+var NotarySupportedSignals = []os.Signal{
+ syscall.SIGUSR1,
+ syscall.SIGUSR2,
+}
diff --git a/vendor/github.com/docker/notary/const_windows.go b/vendor/github.com/docker/notary/const_windows.go
new file mode 100644
index 0000000..e2dff0e
--- /dev/null
+++ b/vendor/github.com/docker/notary/const_windows.go
@@ -0,0 +1,8 @@
+// +build windows
+
+package notary
+
+import "os"
+
+// NotarySupportedSignals does not contain any signals, because SIGUSR1/2 are not supported on windows
+var NotarySupportedSignals = []os.Signal{}
diff --git a/vendor/github.com/docker/notary/cryptoservice/certificate.go b/vendor/github.com/docker/notary/cryptoservice/certificate.go
new file mode 100644
index 0000000..805a169
--- /dev/null
+++ b/vendor/github.com/docker/notary/cryptoservice/certificate.go
@@ -0,0 +1,41 @@
+package cryptoservice
+
+import (
+ "crypto"
+ "crypto/rand"
+ "crypto/x509"
+ "fmt"
+ "time"
+
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/utils"
+)
+
+// GenerateCertificate generates an X509 Certificate from a template, given a GUN and validity interval
+func GenerateCertificate(rootKey data.PrivateKey, gun string, startTime, endTime time.Time) (*x509.Certificate, error) {
+ signer := rootKey.CryptoSigner()
+ if signer == nil {
+ return nil, fmt.Errorf("key type not supported for Certificate generation: %s\n", rootKey.Algorithm())
+ }
+
+ return generateCertificate(signer, gun, startTime, endTime)
+}
+
+func generateCertificate(signer crypto.Signer, gun string, startTime, endTime time.Time) (*x509.Certificate, error) {
+ template, err := utils.NewCertificate(gun, startTime, endTime)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create the certificate template for: %s (%v)", gun, err)
+ }
+
+ derBytes, err := x509.CreateCertificate(rand.Reader, template, template, signer.Public(), signer)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create the certificate for: %s (%v)", gun, err)
+ }
+
+ cert, err := x509.ParseCertificate(derBytes)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse the certificate for key: %s (%v)", gun, err)
+ }
+
+ return cert, nil
+}
diff --git a/vendor/github.com/docker/notary/cryptoservice/crypto_service.go b/vendor/github.com/docker/notary/cryptoservice/crypto_service.go
new file mode 100644
index 0000000..3f50029
--- /dev/null
+++ b/vendor/github.com/docker/notary/cryptoservice/crypto_service.go
@@ -0,0 +1,181 @@
+package cryptoservice
+
+import (
+ "crypto/rand"
+ "fmt"
+
+ "crypto/x509"
+ "encoding/pem"
+ "errors"
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary"
+ "github.com/docker/notary/trustmanager"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/utils"
+)
+
+var (
+ // ErrNoValidPrivateKey is returned if a key being imported doesn't
+ // look like a private key
+ ErrNoValidPrivateKey = errors.New("no valid private key found")
+
+ // ErrRootKeyNotEncrypted is returned if a root key being imported is
+ // unencrypted
+ ErrRootKeyNotEncrypted = errors.New("only encrypted root keys may be imported")
+)
+
+// CryptoService implements Sign and Create, holding a specific GUN and keystore to
+// operate on
+type CryptoService struct {
+ keyStores []trustmanager.KeyStore
+}
+
+// NewCryptoService returns an instance of CryptoService
+func NewCryptoService(keyStores ...trustmanager.KeyStore) *CryptoService {
+ return &CryptoService{keyStores: keyStores}
+}
+
+// Create is used to generate keys for targets, snapshots and timestamps
+func (cs *CryptoService) Create(role, gun, algorithm string) (data.PublicKey, error) {
+ var privKey data.PrivateKey
+ var err error
+
+ switch algorithm {
+ case data.RSAKey:
+ privKey, err = utils.GenerateRSAKey(rand.Reader, notary.MinRSABitSize)
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate RSA key: %v", err)
+ }
+ case data.ECDSAKey:
+ privKey, err = utils.GenerateECDSAKey(rand.Reader)
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate EC key: %v", err)
+ }
+ case data.ED25519Key:
+ privKey, err = utils.GenerateED25519Key(rand.Reader)
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate ED25519 key: %v", err)
+ }
+ default:
+ return nil, fmt.Errorf("private key type not supported for key generation: %s", algorithm)
+ }
+ logrus.Debugf("generated new %s key for role: %s and keyID: %s", algorithm, role, privKey.ID())
+
+ // Store the private key into our keystore
+ for _, ks := range cs.keyStores {
+ err = ks.AddKey(trustmanager.KeyInfo{Role: role, Gun: gun}, privKey)
+ if err == nil {
+ return data.PublicKeyFromPrivate(privKey), nil
+ }
+ }
+ if err != nil {
+ return nil, fmt.Errorf("failed to add key to filestore: %v", err)
+ }
+
+ return nil, fmt.Errorf("keystores would not accept new private keys for unknown reasons")
+}
+
+// GetPrivateKey returns a private key and role if present by ID.
+func (cs *CryptoService) GetPrivateKey(keyID string) (k data.PrivateKey, role string, err error) {
+ for _, ks := range cs.keyStores {
+ if k, role, err = ks.GetKey(keyID); err == nil {
+ return
+ }
+ switch err.(type) {
+ case trustmanager.ErrPasswordInvalid, trustmanager.ErrAttemptsExceeded:
+ return
+ default:
+ continue
+ }
+ }
+ return // returns whatever the final values were
+}
+
+// GetKey returns a key by ID
+func (cs *CryptoService) GetKey(keyID string) data.PublicKey {
+ privKey, _, err := cs.GetPrivateKey(keyID)
+ if err != nil {
+ return nil
+ }
+ return data.PublicKeyFromPrivate(privKey)
+}
+
+// GetKeyInfo returns role and GUN info of a key by ID
+func (cs *CryptoService) GetKeyInfo(keyID string) (trustmanager.KeyInfo, error) {
+ for _, store := range cs.keyStores {
+ if info, err := store.GetKeyInfo(keyID); err == nil {
+ return info, nil
+ }
+ }
+ return trustmanager.KeyInfo{}, fmt.Errorf("Could not find info for keyID %s", keyID)
+}
+
+// RemoveKey deletes a key by ID
+func (cs *CryptoService) RemoveKey(keyID string) (err error) {
+ for _, ks := range cs.keyStores {
+ ks.RemoveKey(keyID)
+ }
+ return // returns whatever the final values were
+}
+
+// AddKey adds a private key to a specified role.
+// The GUN is inferred from the cryptoservice itself for non-root roles
+func (cs *CryptoService) AddKey(role, gun string, key data.PrivateKey) (err error) {
+ // First check if this key already exists in any of our keystores
+ for _, ks := range cs.keyStores {
+ if keyInfo, err := ks.GetKeyInfo(key.ID()); err == nil {
+ if keyInfo.Role != role {
+ return fmt.Errorf("key with same ID already exists for role: %s", keyInfo.Role)
+ }
+ logrus.Debugf("key with same ID %s and role %s already exists", key.ID(), keyInfo.Role)
+ return nil
+ }
+ }
+ // If the key didn't exist in any of our keystores, add and return on the first successful keystore
+ for _, ks := range cs.keyStores {
+ // Try to add to this keystore, return if successful
+ if err = ks.AddKey(trustmanager.KeyInfo{Role: role, Gun: gun}, key); err == nil {
+ return nil
+ }
+ }
+ return // returns whatever the final values were
+}
+
+// ListKeys returns a list of key IDs valid for the given role
+func (cs *CryptoService) ListKeys(role string) []string {
+ var res []string
+ for _, ks := range cs.keyStores {
+ for k, r := range ks.ListKeys() {
+ if r.Role == role {
+ res = append(res, k)
+ }
+ }
+ }
+ return res
+}
+
+// ListAllKeys returns a map of key IDs to role
+func (cs *CryptoService) ListAllKeys() map[string]string {
+ res := make(map[string]string)
+ for _, ks := range cs.keyStores {
+ for k, r := range ks.ListKeys() {
+ res[k] = r.Role // keys are content addressed so don't care about overwrites
+ }
+ }
+ return res
+}
+
+// CheckRootKeyIsEncrypted makes sure the root key is encrypted. We have
+// internal assumptions that depend on this.
+func CheckRootKeyIsEncrypted(pemBytes []byte) error {
+ block, _ := pem.Decode(pemBytes)
+ if block == nil {
+ return ErrNoValidPrivateKey
+ }
+
+ if !x509.IsEncryptedPEMBlock(block) {
+ return ErrRootKeyNotEncrypted
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/notary/notary.go b/vendor/github.com/docker/notary/notary.go
new file mode 100644
index 0000000..d6f070a
--- /dev/null
+++ b/vendor/github.com/docker/notary/notary.go
@@ -0,0 +1,7 @@
+package notary
+
+// PassRetriever is a callback function that should retrieve a passphrase
+// for a given named key. If it should be treated as new passphrase (e.g. with
+// confirmation), createNew will be true. Attempts is passed in so that implementers
+// decide how many chances to give to a human, for example.
+type PassRetriever func(keyName, alias string, createNew bool, attempts int) (passphrase string, giveup bool, err error)
diff --git a/vendor/github.com/docker/notary/passphrase/passphrase.go b/vendor/github.com/docker/notary/passphrase/passphrase.go
new file mode 100644
index 0000000..23c7e6a
--- /dev/null
+++ b/vendor/github.com/docker/notary/passphrase/passphrase.go
@@ -0,0 +1,205 @@
+// Package passphrase is a utility function for managing passphrase
+// for TUF and Notary keys.
+package passphrase
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/docker/docker/pkg/term"
+ "github.com/docker/notary"
+)
+
+const (
+ idBytesToDisplay = 7
+ tufRootAlias = "root"
+ tufTargetsAlias = "targets"
+ tufSnapshotAlias = "snapshot"
+ tufRootKeyGenerationWarning = `You are about to create a new root signing key passphrase. This passphrase
+will be used to protect the most sensitive key in your signing system. Please
+choose a long, complex passphrase and be careful to keep the password and the
+key file itself secure and backed up. It is highly recommended that you use a
+password manager to generate the passphrase and keep it safe. There will be no
+way to recover this key. You can find the key in your config directory.`
+)
+
+var (
+ // ErrTooShort is returned if the passphrase entered for a new key is
+ // below the minimum length
+ ErrTooShort = errors.New("Passphrase too short")
+
+ // ErrDontMatch is returned if the two entered passphrases don't match.
+ // new key is below the minimum length
+ ErrDontMatch = errors.New("The entered passphrases do not match")
+
+ // ErrTooManyAttempts is returned if the maximum number of passphrase
+ // entry attempts is reached.
+ ErrTooManyAttempts = errors.New("Too many attempts")
+
+ // ErrNoInput is returned if we do not have a valid input method for passphrases
+ ErrNoInput = errors.New("Please either use environment variables or STDIN with a terminal to provide key passphrases")
+)
+
+// PromptRetriever returns a new Retriever which will provide a prompt on stdin
+// and stdout to retrieve a passphrase. stdin will be checked if it is a terminal,
+// else the PromptRetriever will error when attempting to retrieve a passphrase.
+// Upon successful passphrase retrievals, the passphrase will be cached such that
+// subsequent prompts will produce the same passphrase.
+func PromptRetriever() notary.PassRetriever {
+ if !term.IsTerminal(os.Stdin.Fd()) {
+ return func(string, string, bool, int) (string, bool, error) {
+ return "", false, ErrNoInput
+ }
+ }
+ return PromptRetrieverWithInOut(os.Stdin, os.Stdout, nil)
+}
+
+type boundRetriever struct {
+ in io.Reader
+ out io.Writer
+ aliasMap map[string]string
+ passphraseCache map[string]string
+}
+
+func (br *boundRetriever) getPassphrase(keyName, alias string, createNew bool, numAttempts int) (string, bool, error) {
+ if numAttempts == 0 {
+ if alias == tufRootAlias && createNew {
+ fmt.Fprintln(br.out, tufRootKeyGenerationWarning)
+ }
+
+ if pass, ok := br.passphraseCache[alias]; ok {
+ return pass, false, nil
+ }
+ } else if !createNew { // per `if`, numAttempts > 0 if we're at this `else`
+ if numAttempts > 3 {
+ return "", true, ErrTooManyAttempts
+ }
+ fmt.Fprintln(br.out, "Passphrase incorrect. Please retry.")
+ }
+
+ // passphrase not cached and we're not aborting, get passphrase from user!
+ return br.requestPassphrase(keyName, alias, createNew, numAttempts)
+}
+
+func (br *boundRetriever) requestPassphrase(keyName, alias string, createNew bool, numAttempts int) (string, bool, error) {
+ // Figure out if we should display a different string for this alias
+ displayAlias := alias
+ if val, ok := br.aliasMap[alias]; ok {
+ displayAlias = val
+ }
+
+ // If typing on the terminal, we do not want the terminal to echo the
+ // password that is typed (so it doesn't display)
+ if term.IsTerminal(os.Stdin.Fd()) {
+ state, err := term.SaveState(os.Stdin.Fd())
+ if err != nil {
+ return "", false, err
+ }
+ term.DisableEcho(os.Stdin.Fd(), state)
+ defer term.RestoreTerminal(os.Stdin.Fd(), state)
+ }
+
+ indexOfLastSeparator := strings.LastIndex(keyName, string(filepath.Separator))
+ if indexOfLastSeparator == -1 {
+ indexOfLastSeparator = 0
+ }
+
+ var shortName string
+ if len(keyName) > indexOfLastSeparator+idBytesToDisplay {
+ if indexOfLastSeparator > 0 {
+ keyNamePrefix := keyName[:indexOfLastSeparator]
+ keyNameID := keyName[indexOfLastSeparator+1 : indexOfLastSeparator+idBytesToDisplay+1]
+ shortName = keyNameID + " (" + keyNamePrefix + ")"
+ } else {
+ shortName = keyName[indexOfLastSeparator : indexOfLastSeparator+idBytesToDisplay]
+ }
+ }
+
+ withID := fmt.Sprintf(" with ID %s", shortName)
+ if shortName == "" {
+ withID = ""
+ }
+
+ switch {
+ case createNew:
+ fmt.Fprintf(br.out, "Enter passphrase for new %s key%s: ", displayAlias, withID)
+ case displayAlias == "yubikey":
+ fmt.Fprintf(br.out, "Enter the %s for the attached Yubikey: ", keyName)
+ default:
+ fmt.Fprintf(br.out, "Enter passphrase for %s key%s: ", displayAlias, withID)
+ }
+
+ stdin := bufio.NewReader(br.in)
+ passphrase, err := stdin.ReadBytes('\n')
+ fmt.Fprintln(br.out)
+ if err != nil {
+ return "", false, err
+ }
+
+ retPass := strings.TrimSpace(string(passphrase))
+
+ if createNew {
+ err = br.verifyAndConfirmPassword(stdin, retPass, displayAlias, withID)
+ if err != nil {
+ return "", false, err
+ }
+ }
+
+ br.cachePassword(alias, retPass)
+
+ return retPass, false, nil
+}
+
+func (br *boundRetriever) verifyAndConfirmPassword(stdin *bufio.Reader, retPass, displayAlias, withID string) error {
+ if len(retPass) < 8 {
+ fmt.Fprintln(br.out, "Passphrase is too short. Please use a password manager to generate and store a good random passphrase.")
+ return ErrTooShort
+ }
+
+ fmt.Fprintf(br.out, "Repeat passphrase for new %s key%s: ", displayAlias, withID)
+ confirmation, err := stdin.ReadBytes('\n')
+ fmt.Fprintln(br.out)
+ if err != nil {
+ return err
+ }
+ confirmationStr := strings.TrimSpace(string(confirmation))
+
+ if retPass != confirmationStr {
+ fmt.Fprintln(br.out, "Passphrases do not match. Please retry.")
+ return ErrDontMatch
+ }
+ return nil
+}
+
+func (br *boundRetriever) cachePassword(alias, retPass string) {
+ br.passphraseCache[alias] = retPass
+}
+
+// PromptRetrieverWithInOut returns a new Retriever which will provide a
+// prompt using the given in and out readers. The passphrase will be cached
+// such that subsequent prompts will produce the same passphrase.
+// aliasMap can be used to specify display names for TUF key aliases. If aliasMap
+// is nil, a sensible default will be used.
+func PromptRetrieverWithInOut(in io.Reader, out io.Writer, aliasMap map[string]string) notary.PassRetriever {
+ bound := &boundRetriever{
+ in: in,
+ out: out,
+ aliasMap: aliasMap,
+ passphraseCache: make(map[string]string),
+ }
+
+ return bound.getPassphrase
+}
+
+// ConstantRetriever returns a new Retriever which will return a constant string
+// as a passphrase.
+func ConstantRetriever(constantPassphrase string) notary.PassRetriever {
+ return func(k, a string, c bool, n int) (string, bool, error) {
+ return constantPassphrase, false, nil
+ }
+}
diff --git a/vendor/github.com/docker/notary/storage/errors.go b/vendor/github.com/docker/notary/storage/errors.go
new file mode 100644
index 0000000..2c7b876
--- /dev/null
+++ b/vendor/github.com/docker/notary/storage/errors.go
@@ -0,0 +1,22 @@
+package storage
+
+import (
+ "errors"
+ "fmt"
+)
+
+var (
+ // ErrPathOutsideStore indicates that the returned path would be
+ // outside the store
+ ErrPathOutsideStore = errors.New("path outside file store")
+)
+
+// ErrMetaNotFound indicates we did not find a particular piece
+// of metadata in the store
+type ErrMetaNotFound struct {
+ Resource string
+}
+
+func (err ErrMetaNotFound) Error() string {
+ return fmt.Sprintf("%s trust data unavailable. Has a notary repository been initialized?", err.Resource)
+}
diff --git a/vendor/github.com/docker/notary/storage/filestore.go b/vendor/github.com/docker/notary/storage/filestore.go
new file mode 100644
index 0000000..1d50a58
--- /dev/null
+++ b/vendor/github.com/docker/notary/storage/filestore.go
@@ -0,0 +1,222 @@
+package storage
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/docker/notary"
+)
+
+// NewFilesystemStore creates a new store in a directory tree
+func NewFilesystemStore(baseDir, subDir, extension string) (*FilesystemStore, error) {
+ baseDir = filepath.Join(baseDir, subDir)
+
+ return NewFileStore(baseDir, extension, notary.PrivKeyPerms)
+}
+
+// NewFileStore creates a fully configurable file store
+func NewFileStore(baseDir, fileExt string, perms os.FileMode) (*FilesystemStore, error) {
+ baseDir = filepath.Clean(baseDir)
+ if err := createDirectory(baseDir, perms); err != nil {
+ return nil, err
+ }
+ if !strings.HasPrefix(fileExt, ".") {
+ fileExt = "." + fileExt
+ }
+
+ return &FilesystemStore{
+ baseDir: baseDir,
+ ext: fileExt,
+ perms: perms,
+ }, nil
+}
+
+// NewSimpleFileStore is a convenience wrapper to create a world readable,
+// owner writeable filestore
+func NewSimpleFileStore(baseDir, fileExt string) (*FilesystemStore, error) {
+ return NewFileStore(baseDir, fileExt, notary.PubCertPerms)
+}
+
+// NewPrivateKeyFileStorage initializes a new filestore for private keys, appending
+// the notary.PrivDir to the baseDir.
+func NewPrivateKeyFileStorage(baseDir, fileExt string) (*FilesystemStore, error) {
+ baseDir = filepath.Join(baseDir, notary.PrivDir)
+ return NewFileStore(baseDir, fileExt, notary.PrivKeyPerms)
+}
+
+// NewPrivateSimpleFileStore is a wrapper to create an owner readable/writeable
+// _only_ filestore
+func NewPrivateSimpleFileStore(baseDir, fileExt string) (*FilesystemStore, error) {
+ return NewFileStore(baseDir, fileExt, notary.PrivKeyPerms)
+}
+
+// FilesystemStore is a store in a locally accessible directory
+type FilesystemStore struct {
+ baseDir string
+ ext string
+ perms os.FileMode
+}
+
+func (f *FilesystemStore) getPath(name string) (string, error) {
+ fileName := fmt.Sprintf("%s%s", name, f.ext)
+ fullPath := filepath.Join(f.baseDir, fileName)
+
+ if !strings.HasPrefix(fullPath, f.baseDir) {
+ return "", ErrPathOutsideStore
+ }
+ return fullPath, nil
+}
+
+// GetSized returns the meta for the given name (a role) up to size bytes
+// If size is "NoSizeLimit", this corresponds to "infinite," but we cut off at a
+// predefined threshold "notary.MaxDownloadSize". If the file is larger than size
+// we return ErrMaliciousServer for consistency with the HTTPStore
+func (f *FilesystemStore) GetSized(name string, size int64) ([]byte, error) {
+ p, err := f.getPath(name)
+ if err != nil {
+ return nil, err
+ }
+ file, err := os.OpenFile(p, os.O_RDONLY, f.perms)
+ if err != nil {
+ if os.IsNotExist(err) {
+ err = ErrMetaNotFound{Resource: name}
+ }
+ return nil, err
+ }
+ defer file.Close()
+
+ if size == NoSizeLimit {
+ size = notary.MaxDownloadSize
+ }
+
+ stat, err := file.Stat()
+ if err != nil {
+ return nil, err
+ }
+ if stat.Size() > size {
+ return nil, ErrMaliciousServer{}
+ }
+
+ l := io.LimitReader(file, size)
+ return ioutil.ReadAll(l)
+}
+
+// Get returns the meta for the given name.
+func (f *FilesystemStore) Get(name string) ([]byte, error) {
+ p, err := f.getPath(name)
+ if err != nil {
+ return nil, err
+ }
+ meta, err := ioutil.ReadFile(p)
+ if err != nil {
+ if os.IsNotExist(err) {
+ err = ErrMetaNotFound{Resource: name}
+ }
+ return nil, err
+ }
+ return meta, nil
+}
+
+// SetMulti sets the metadata for multiple roles in one operation
+func (f *FilesystemStore) SetMulti(metas map[string][]byte) error {
+ for role, blob := range metas {
+ err := f.Set(role, blob)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Set sets the meta for a single role
+func (f *FilesystemStore) Set(name string, meta []byte) error {
+ fp, err := f.getPath(name)
+ if err != nil {
+ return err
+ }
+
+ // Ensures the parent directories of the file we are about to write exist
+ err = os.MkdirAll(filepath.Dir(fp), f.perms)
+ if err != nil {
+ return err
+ }
+
+ // if something already exists, just delete it and re-write it
+ os.RemoveAll(fp)
+
+ // Write the file to disk
+ if err = ioutil.WriteFile(fp, meta, f.perms); err != nil {
+ return err
+ }
+ return nil
+}
+
+// RemoveAll clears the existing filestore by removing its base directory
+func (f *FilesystemStore) RemoveAll() error {
+ return os.RemoveAll(f.baseDir)
+}
+
+// Remove removes the metadata for a single role - if the metadata doesn't
+// exist, no error is returned
+func (f *FilesystemStore) Remove(name string) error {
+ p, err := f.getPath(name)
+ if err != nil {
+ return err
+ }
+ return os.RemoveAll(p) // RemoveAll succeeds if path doesn't exist
+}
+
+// Location returns a human readable name for the storage location
+func (f FilesystemStore) Location() string {
+ return f.baseDir
+}
+
+// ListFiles returns a list of all the filenames that can be used with Get*
+// to retrieve content from this filestore
+func (f FilesystemStore) ListFiles() []string {
+ files := make([]string, 0, 0)
+ filepath.Walk(f.baseDir, func(fp string, fi os.FileInfo, err error) error {
+ // If there are errors, ignore this particular file
+ if err != nil {
+ return nil
+ }
+ // Ignore if it is a directory
+ if fi.IsDir() {
+ return nil
+ }
+
+ // If this is a symlink, ignore it
+ if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
+ return nil
+ }
+
+ // Only allow matches that end with our certificate extension (e.g. *.crt)
+ matched, _ := filepath.Match("*"+f.ext, fi.Name())
+
+ if matched {
+ // Find the relative path for this file relative to the base path.
+ fp, err = filepath.Rel(f.baseDir, fp)
+ if err != nil {
+ return err
+ }
+ trimmed := strings.TrimSuffix(fp, f.ext)
+ files = append(files, trimmed)
+ }
+ return nil
+ })
+ return files
+}
+
+// createDirectory receives a string of the path to a directory.
+// It does not support passing files, so the caller has to remove
+// the filename by doing filepath.Dir(full_path_to_file)
+func createDirectory(dir string, perms os.FileMode) error {
+ // This prevents someone passing /path/to/dir and 'dir' not being created
+ // If two '//' exist, MkdirAll deals it with correctly
+ dir = dir + "/"
+ return os.MkdirAll(dir, perms)
+}
diff --git a/vendor/github.com/docker/notary/storage/httpstore.go b/vendor/github.com/docker/notary/storage/httpstore.go
new file mode 100644
index 0000000..994f949
--- /dev/null
+++ b/vendor/github.com/docker/notary/storage/httpstore.go
@@ -0,0 +1,339 @@
+// A Store that can fetch and set metadata on a remote server.
+// Some API constraints:
+// - Response bodies for error codes should be unmarshallable as:
+// {"errors": [{..., "detail": <serialized validation error>}]}
+// else validation error details, etc. will be unparsable. The errors
+// should have a github.com/docker/notary/tuf/validation/SerializableError
+// in the Details field.
+// If writing your own server, please have a look at
+// github.com/docker/distribution/registry/api/errcode
+
+package storage
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "mime/multipart"
+ "net/http"
+ "net/url"
+ "path"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary"
+ "github.com/docker/notary/tuf/validation"
+)
+
+// ErrServerUnavailable indicates an error from the server. code allows us to
+// populate the http error we received
+type ErrServerUnavailable struct {
+ code int
+}
+
+// NetworkError represents any kind of network error when attempting to make a request
+type NetworkError struct {
+ Wrapped error
+}
+
+func (n NetworkError) Error() string {
+ return n.Wrapped.Error()
+}
+
+func (err ErrServerUnavailable) Error() string {
+ if err.code == 401 {
+ return fmt.Sprintf("you are not authorized to perform this operation: server returned 401.")
+ }
+ return fmt.Sprintf("unable to reach trust server at this time: %d.", err.code)
+}
+
+// ErrMaliciousServer indicates the server returned a response that is highly suspected
+// of being malicious. i.e. it attempted to send us more data than the known size of a
+// particular role metadata.
+type ErrMaliciousServer struct{}
+
+func (err ErrMaliciousServer) Error() string {
+ return "trust server returned a bad response."
+}
+
+// ErrInvalidOperation indicates that the server returned a 400 response and
+// propagate any body we received.
+type ErrInvalidOperation struct {
+ msg string
+}
+
+func (err ErrInvalidOperation) Error() string {
+ if err.msg != "" {
+ return fmt.Sprintf("trust server rejected operation: %s", err.msg)
+ }
+ return "trust server rejected operation."
+}
+
+// HTTPStore manages pulling and pushing metadata from and to a remote
+// service over HTTP. It assumes the URL structure of the remote service
+// maps identically to the structure of the TUF repo:
+// <baseURL>/<metaPrefix>/(root|targets|snapshot|timestamp).json
+// <baseURL>/<targetsPrefix>/foo.sh
+//
+// If consistent snapshots are disabled, it is advised that caching is not
+// enabled. Simple set a cachePath (and ensure it's writeable) to enable
+// caching.
+type HTTPStore struct {
+ baseURL url.URL
+ metaPrefix string
+ metaExtension string
+ keyExtension string
+ roundTrip http.RoundTripper
+}
+
+// NewHTTPStore initializes a new store against a URL and a number of configuration options
+func NewHTTPStore(baseURL, metaPrefix, metaExtension, keyExtension string, roundTrip http.RoundTripper) (RemoteStore, error) {
+ base, err := url.Parse(baseURL)
+ if err != nil {
+ return nil, err
+ }
+ if !base.IsAbs() {
+ return nil, errors.New("HTTPStore requires an absolute baseURL")
+ }
+ if roundTrip == nil {
+ return &OfflineStore{}, nil
+ }
+ return &HTTPStore{
+ baseURL: *base,
+ metaPrefix: metaPrefix,
+ metaExtension: metaExtension,
+ keyExtension: keyExtension,
+ roundTrip: roundTrip,
+ }, nil
+}
+
+func tryUnmarshalError(resp *http.Response, defaultError error) error {
+ bodyBytes, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return defaultError
+ }
+ var parsedErrors struct {
+ Errors []struct {
+ Detail validation.SerializableError `json:"detail"`
+ } `json:"errors"`
+ }
+ if err := json.Unmarshal(bodyBytes, &parsedErrors); err != nil {
+ return defaultError
+ }
+ if len(parsedErrors.Errors) != 1 {
+ return defaultError
+ }
+ err = parsedErrors.Errors[0].Detail.Error
+ if err == nil {
+ return defaultError
+ }
+ return err
+}
+
+func translateStatusToError(resp *http.Response, resource string) error {
+ switch resp.StatusCode {
+ case http.StatusOK:
+ return nil
+ case http.StatusNotFound:
+ return ErrMetaNotFound{Resource: resource}
+ case http.StatusBadRequest:
+ return tryUnmarshalError(resp, ErrInvalidOperation{})
+ default:
+ return ErrServerUnavailable{code: resp.StatusCode}
+ }
+}
+
+// GetSized downloads the named meta file with the given size. A short body
+// is acceptable because in the case of timestamp.json, the size is a cap,
+// not an exact length.
+// If size is "NoSizeLimit", this corresponds to "infinite," but we cut off at a
+// predefined threshold "notary.MaxDownloadSize".
+func (s HTTPStore) GetSized(name string, size int64) ([]byte, error) {
+ url, err := s.buildMetaURL(name)
+ if err != nil {
+ return nil, err
+ }
+ req, err := http.NewRequest("GET", url.String(), nil)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := s.roundTrip.RoundTrip(req)
+ if err != nil {
+ return nil, NetworkError{Wrapped: err}
+ }
+ defer resp.Body.Close()
+ if err := translateStatusToError(resp, name); err != nil {
+ logrus.Debugf("received HTTP status %d when requesting %s.", resp.StatusCode, name)
+ return nil, err
+ }
+ if size == NoSizeLimit {
+ size = notary.MaxDownloadSize
+ }
+ if resp.ContentLength > size {
+ return nil, ErrMaliciousServer{}
+ }
+ logrus.Debugf("%d when retrieving metadata for %s", resp.StatusCode, name)
+ b := io.LimitReader(resp.Body, size)
+ body, err := ioutil.ReadAll(b)
+ if err != nil {
+ return nil, err
+ }
+ return body, nil
+}
+
+// Set sends a single piece of metadata to the TUF server
+func (s HTTPStore) Set(name string, blob []byte) error {
+ return s.SetMulti(map[string][]byte{name: blob})
+}
+
+// Remove always fails, because we should never be able to delete metadata
+// remotely
+func (s HTTPStore) Remove(name string) error {
+ return ErrInvalidOperation{msg: "cannot delete individual metadata files"}
+}
+
+// NewMultiPartMetaRequest builds a request with the provided metadata updates
+// in multipart form
+func NewMultiPartMetaRequest(url string, metas map[string][]byte) (*http.Request, error) {
+ body := &bytes.Buffer{}
+ writer := multipart.NewWriter(body)
+ for role, blob := range metas {
+ part, err := writer.CreateFormFile("files", role)
+ if err != nil {
+ return nil, err
+ }
+ _, err = io.Copy(part, bytes.NewBuffer(blob))
+ if err != nil {
+ return nil, err
+ }
+ }
+ err := writer.Close()
+ if err != nil {
+ return nil, err
+ }
+ req, err := http.NewRequest("POST", url, body)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ return req, nil
+}
+
+// SetMulti does a single batch upload of multiple pieces of TUF metadata.
+// This should be preferred for updating a remote server as it enable the server
+// to remain consistent, either accepting or rejecting the complete update.
+func (s HTTPStore) SetMulti(metas map[string][]byte) error {
+ url, err := s.buildMetaURL("")
+ if err != nil {
+ return err
+ }
+ req, err := NewMultiPartMetaRequest(url.String(), metas)
+ if err != nil {
+ return err
+ }
+ resp, err := s.roundTrip.RoundTrip(req)
+ if err != nil {
+ return NetworkError{Wrapped: err}
+ }
+ defer resp.Body.Close()
+ // if this 404's something is pretty wrong
+ return translateStatusToError(resp, "POST metadata endpoint")
+}
+
+// RemoveAll will attempt to delete all TUF metadata for a GUN
+func (s HTTPStore) RemoveAll() error {
+ url, err := s.buildMetaURL("")
+ if err != nil {
+ return err
+ }
+ req, err := http.NewRequest("DELETE", url.String(), nil)
+ if err != nil {
+ return err
+ }
+ resp, err := s.roundTrip.RoundTrip(req)
+ if err != nil {
+ return NetworkError{Wrapped: err}
+ }
+ defer resp.Body.Close()
+ return translateStatusToError(resp, "DELETE metadata for GUN endpoint")
+}
+
+func (s HTTPStore) buildMetaURL(name string) (*url.URL, error) {
+ var filename string
+ if name != "" {
+ filename = fmt.Sprintf("%s.%s", name, s.metaExtension)
+ }
+ uri := path.Join(s.metaPrefix, filename)
+ return s.buildURL(uri)
+}
+
+func (s HTTPStore) buildKeyURL(name string) (*url.URL, error) {
+ filename := fmt.Sprintf("%s.%s", name, s.keyExtension)
+ uri := path.Join(s.metaPrefix, filename)
+ return s.buildURL(uri)
+}
+
+func (s HTTPStore) buildURL(uri string) (*url.URL, error) {
+ sub, err := url.Parse(uri)
+ if err != nil {
+ return nil, err
+ }
+ return s.baseURL.ResolveReference(sub), nil
+}
+
+// GetKey retrieves a public key from the remote server
+func (s HTTPStore) GetKey(role string) ([]byte, error) {
+ url, err := s.buildKeyURL(role)
+ if err != nil {
+ return nil, err
+ }
+ req, err := http.NewRequest("GET", url.String(), nil)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := s.roundTrip.RoundTrip(req)
+ if err != nil {
+ return nil, NetworkError{Wrapped: err}
+ }
+ defer resp.Body.Close()
+ if err := translateStatusToError(resp, role+" key"); err != nil {
+ return nil, err
+ }
+ body, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+ return body, nil
+}
+
+// RotateKey rotates a private key and returns the public component from the remote server
+func (s HTTPStore) RotateKey(role string) ([]byte, error) {
+ url, err := s.buildKeyURL(role)
+ if err != nil {
+ return nil, err
+ }
+ req, err := http.NewRequest("POST", url.String(), nil)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := s.roundTrip.RoundTrip(req)
+ if err != nil {
+ return nil, NetworkError{Wrapped: err}
+ }
+ defer resp.Body.Close()
+ if err := translateStatusToError(resp, role+" key"); err != nil {
+ return nil, err
+ }
+ body, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+ return body, nil
+}
+
+// Location returns a human readable name for the storage location
+func (s HTTPStore) Location() string {
+ return s.baseURL.String()
+}
diff --git a/vendor/github.com/docker/notary/storage/interfaces.go b/vendor/github.com/docker/notary/storage/interfaces.go
new file mode 100644
index 0000000..867c9f1
--- /dev/null
+++ b/vendor/github.com/docker/notary/storage/interfaces.go
@@ -0,0 +1,34 @@
+package storage
+
+// NoSizeLimit is represented as -1 for arguments to GetMeta
+const NoSizeLimit int64 = -1
+
+// MetadataStore must be implemented by anything that intends to interact
+// with a store of TUF files
+type MetadataStore interface {
+ GetSized(name string, size int64) ([]byte, error)
+ Set(name string, blob []byte) error
+ SetMulti(map[string][]byte) error
+ RemoveAll() error
+ Remove(name string) error
+}
+
+// PublicKeyStore must be implemented by a key service
+type PublicKeyStore interface {
+ GetKey(role string) ([]byte, error)
+ RotateKey(role string) ([]byte, error)
+}
+
+// RemoteStore is similar to LocalStore with the added expectation that it should
+// provide a way to download targets once located
+type RemoteStore interface {
+ MetadataStore
+ PublicKeyStore
+}
+
+// Bootstrapper is a thing that can set itself up
+type Bootstrapper interface {
+ // Bootstrap instructs a configured Bootstrapper to perform
+ // its setup operations.
+ Bootstrap() error
+}
diff --git a/vendor/github.com/docker/notary/storage/memorystore.go b/vendor/github.com/docker/notary/storage/memorystore.go
new file mode 100644
index 0000000..8a2ade5
--- /dev/null
+++ b/vendor/github.com/docker/notary/storage/memorystore.go
@@ -0,0 +1,124 @@
+package storage
+
+import (
+ "crypto/sha256"
+
+ "github.com/docker/notary"
+ "github.com/docker/notary/tuf/utils"
+)
+
+// NewMemoryStore returns a MetadataStore that operates entirely in memory.
+// Very useful for testing
+func NewMemoryStore(initial map[string][]byte) *MemoryStore {
+ var consistent = make(map[string][]byte)
+ if initial == nil {
+ initial = make(map[string][]byte)
+ } else {
+ // add all seed meta to consistent
+ for name, data := range initial {
+ checksum := sha256.Sum256(data)
+ path := utils.ConsistentName(name, checksum[:])
+ consistent[path] = data
+ }
+ }
+ return &MemoryStore{
+ data: initial,
+ consistent: consistent,
+ }
+}
+
+// MemoryStore implements a mock RemoteStore entirely in memory.
+// For testing purposes only.
+type MemoryStore struct {
+ data map[string][]byte
+ consistent map[string][]byte
+}
+
+// GetSized returns up to size bytes of data references by name.
+// If size is "NoSizeLimit", this corresponds to "infinite," but we cut off at a
+// predefined threshold "notary.MaxDownloadSize", as we will always know the
+// size for everything but a timestamp and sometimes a root,
+// neither of which should be exceptionally large
+func (m MemoryStore) GetSized(name string, size int64) ([]byte, error) {
+ d, ok := m.data[name]
+ if ok {
+ if size == NoSizeLimit {
+ size = notary.MaxDownloadSize
+ }
+ if int64(len(d)) < size {
+ return d, nil
+ }
+ return d[:size], nil
+ }
+ d, ok = m.consistent[name]
+ if ok {
+ if int64(len(d)) < size {
+ return d, nil
+ }
+ return d[:size], nil
+ }
+ return nil, ErrMetaNotFound{Resource: name}
+}
+
+// Get returns the data associated with name
+func (m MemoryStore) Get(name string) ([]byte, error) {
+ if d, ok := m.data[name]; ok {
+ return d, nil
+ }
+ if d, ok := m.consistent[name]; ok {
+ return d, nil
+ }
+ return nil, ErrMetaNotFound{Resource: name}
+}
+
+// Set sets the metadata value for the given name
+func (m *MemoryStore) Set(name string, meta []byte) error {
+ m.data[name] = meta
+
+ checksum := sha256.Sum256(meta)
+ path := utils.ConsistentName(name, checksum[:])
+ m.consistent[path] = meta
+ return nil
+}
+
+// SetMulti sets multiple pieces of metadata for multiple names
+// in a single operation.
+func (m *MemoryStore) SetMulti(metas map[string][]byte) error {
+ for role, blob := range metas {
+ m.Set(role, blob)
+ }
+ return nil
+}
+
+// Remove removes the metadata for a single role - if the metadata doesn't
+// exist, no error is returned
+func (m *MemoryStore) Remove(name string) error {
+ if meta, ok := m.data[name]; ok {
+ checksum := sha256.Sum256(meta)
+ path := utils.ConsistentName(name, checksum[:])
+ delete(m.data, name)
+ delete(m.consistent, path)
+ }
+ return nil
+}
+
+// RemoveAll clears the existing memory store by setting this store as new empty one
+func (m *MemoryStore) RemoveAll() error {
+ *m = *NewMemoryStore(nil)
+ return nil
+}
+
+// Location provides a human readable name for the storage location
+func (m MemoryStore) Location() string {
+ return "memory"
+}
+
+// ListFiles returns a list of all files. The names returned should be
+// usable with Get directly, with no modification.
+func (m *MemoryStore) ListFiles() []string {
+ names := make([]string, 0, len(m.data))
+ for n := range m.data {
+ names = append(names, n)
+ }
+ return names
+}
diff --git a/vendor/github.com/docker/notary/storage/offlinestore.go b/vendor/github.com/docker/notary/storage/offlinestore.go
new file mode 100644
index 0000000..fd29760
--- /dev/null
+++ b/vendor/github.com/docker/notary/storage/offlinestore.go
@@ -0,0 +1,54 @@
+package storage
+
+// ErrOffline is used to indicate we are operating offline
+type ErrOffline struct{}
+
+func (e ErrOffline) Error() string {
+ return "client is offline"
+}
+
+var err = ErrOffline{}
+
+// OfflineStore is to be used as a placeholder for a nil store. It simply
+// returns ErrOffline for every operation
+type OfflineStore struct{}
+
+// GetSized returns ErrOffline
+func (es OfflineStore) GetSized(name string, size int64) ([]byte, error) {
+ return nil, err
+}
+
+// Set returns ErrOffline
+func (es OfflineStore) Set(name string, blob []byte) error {
+ return err
+}
+
+// SetMulti returns ErrOffline
+func (es OfflineStore) SetMulti(map[string][]byte) error {
+ return err
+}
+
+// Remove returns ErrOffline
+func (es OfflineStore) Remove(name string) error {
+ return err
+}
+
+// GetKey returns ErrOffline
+func (es OfflineStore) GetKey(role string) ([]byte, error) {
+ return nil, err
+}
+
+// RotateKey returns ErrOffline
+func (es OfflineStore) RotateKey(role string) ([]byte, error) {
+ return nil, err
+}
+
+// RemoveAll return ErrOffline
+func (es OfflineStore) RemoveAll() error {
+ return err
+}
+
+// Location returns a human readable name for the storage location
+func (es OfflineStore) Location() string {
+ return "offline"
+}
diff --git a/vendor/github.com/docker/notary/trustmanager/interfaces.go b/vendor/github.com/docker/notary/trustmanager/interfaces.go
new file mode 100644
index 0000000..34bc128
--- /dev/null
+++ b/vendor/github.com/docker/notary/trustmanager/interfaces.go
@@ -0,0 +1,82 @@
+package trustmanager
+
+import (
+ "fmt"
+
+ "github.com/docker/notary/tuf/data"
+)
+
+// Storage implements the bare bones primitives (no hierarchy)
+type Storage interface {
+ // Add writes a file to the specified location, returning an error if this
+ // is not possible (reasons may include permissions errors). The path is cleaned
+ // before being made absolute against the store's base dir.
+ Set(fileName string, data []byte) error
+
+ // Remove deletes a file from the store relative to the store's base directory.
+ // The path is cleaned before being made absolute to ensure no path traversal
+ // outside the base directory is possible.
+ Remove(fileName string) error
+
+ // Get returns the file content found at fileName relative to the base directory
+ // of the file store. The path is cleaned before being made absolute to ensure
+ // path traversal outside the store is not possible. If the file is not found
+ // an error to that effect is returned.
+ Get(fileName string) ([]byte, error)
+
+ // ListFiles returns a list of paths relative to the base directory of the
+ // filestore. Any of these paths must be retrievable via the
+ // Storage.Get method.
+ ListFiles() []string
+
+ // Location returns a human readable name indicating where the implementer
+ // is storing keys
+ Location() string
+}
+
+// ErrAttemptsExceeded is returned when too many attempts have been made to decrypt a key
+type ErrAttemptsExceeded struct{}
+
+// ErrAttemptsExceeded is returned when too many attempts have been made to decrypt a key
+func (err ErrAttemptsExceeded) Error() string {
+ return "maximum number of passphrase attempts exceeded"
+}
+
+// ErrPasswordInvalid is returned when signing fails. It could also mean the signing
+// key file was corrupted, but we have no way to distinguish.
+type ErrPasswordInvalid struct{}
+
+// ErrPasswordInvalid is returned when signing fails. It could also mean the signing
+// key file was corrupted, but we have no way to distinguish.
+func (err ErrPasswordInvalid) Error() string {
+ return "password invalid, operation has failed."
+}
+
+// ErrKeyNotFound is returned when the keystore fails to retrieve a specific key.
+type ErrKeyNotFound struct {
+ KeyID string
+}
+
+// ErrKeyNotFound is returned when the keystore fails to retrieve a specific key.
+func (err ErrKeyNotFound) Error() string {
+ return fmt.Sprintf("signing key not found: %s", err.KeyID)
+}
+
+// KeyStore is a generic interface for private key storage
+type KeyStore interface {
+ // AddKey adds a key to the KeyStore, and if the key already exists,
+ // succeeds. Otherwise, returns an error if it cannot add.
+ AddKey(keyInfo KeyInfo, privKey data.PrivateKey) error
+ // Should fail with ErrKeyNotFound if the keystore is operating normally
+ // and knows that it does not store the requested key.
+ GetKey(keyID string) (data.PrivateKey, string, error)
+ GetKeyInfo(keyID string) (KeyInfo, error)
+ ListKeys() map[string]KeyInfo
+ RemoveKey(keyID string) error
+ Name() string
+}
+
+type cachedKey struct {
+ alias string
+ key data.PrivateKey
+}
diff --git a/vendor/github.com/docker/notary/trustmanager/keystore.go b/vendor/github.com/docker/notary/trustmanager/keystore.go
new file mode 100644
index 0000000..03d9d96
--- /dev/null
+++ b/vendor/github.com/docker/notary/trustmanager/keystore.go
@@ -0,0 +1,325 @@
+package trustmanager
+
+import (
+ "encoding/pem"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary"
+ store "github.com/docker/notary/storage"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/utils"
+)
+
+type keyInfoMap map[string]KeyInfo
+
+// KeyInfo stores the role, path, and gun for a corresponding private key ID
+// It is assumed that each private key ID is unique
+type KeyInfo struct {
+ Gun string
+ Role string
+}
+
+// GenericKeyStore is a wrapper for Storage instances that provides
+// translation between the []byte form and Public/PrivateKey objects
+type GenericKeyStore struct {
+ store Storage
+ sync.Mutex
+ notary.PassRetriever
+ cachedKeys map[string]*cachedKey
+ keyInfoMap
+}
+
+// NewKeyFileStore returns a new KeyFileStore creating a private directory to
+// hold the keys.
+func NewKeyFileStore(baseDir string, p notary.PassRetriever) (*GenericKeyStore, error) {
+ fileStore, err := store.NewPrivateKeyFileStorage(baseDir, notary.KeyExtension)
+ if err != nil {
+ return nil, err
+ }
+ return NewGenericKeyStore(fileStore, p), nil
+}
+
+// NewKeyMemoryStore returns a new KeyMemoryStore which holds keys in memory
+func NewKeyMemoryStore(p notary.PassRetriever) *GenericKeyStore {
+ memStore := store.NewMemoryStore(nil)
+ return NewGenericKeyStore(memStore, p)
+}
+
+// NewGenericKeyStore creates a GenericKeyStore wrapping the provided
+// Storage instance, using the PassRetriever to enc/decrypt keys
+func NewGenericKeyStore(s Storage, p notary.PassRetriever) *GenericKeyStore {
+ ks := GenericKeyStore{
+ store: s,
+ PassRetriever: p,
+ cachedKeys: make(map[string]*cachedKey),
+ keyInfoMap: make(keyInfoMap),
+ }
+ ks.loadKeyInfo()
+ return &ks
+}
+
+func generateKeyInfoMap(s Storage) map[string]KeyInfo {
+ keyInfoMap := make(map[string]KeyInfo)
+ for _, keyPath := range s.ListFiles() {
+ d, err := s.Get(keyPath)
+ if err != nil {
+ logrus.Error(err)
+ continue
+ }
+ keyID, keyInfo, err := KeyInfoFromPEM(d, keyPath)
+ if err != nil {
+ logrus.Error(err)
+ continue
+ }
+ keyInfoMap[keyID] = keyInfo
+ }
+ return keyInfoMap
+}
+
+// Attempts to infer the keyID, role, and GUN from the specified key path.
+// Note that non-root roles can only be inferred if this is a legacy style filename: KEYID_ROLE.key
+func inferKeyInfoFromKeyPath(keyPath string) (string, string, string) {
+ var keyID, role, gun string
+ keyID = filepath.Base(keyPath)
+ underscoreIndex := strings.LastIndex(keyID, "_")
+
+ // This is the legacy KEYID_ROLE filename
+ // The keyID is the first part of the keyname
+ // The keyRole is the second part of the keyname
+ // in a key named abcde_root, abcde is the keyID and root is the KeyAlias
+ if underscoreIndex != -1 {
+ role = keyID[underscoreIndex+1:]
+ keyID = keyID[:underscoreIndex]
+ }
+
+ if filepath.HasPrefix(keyPath, notary.RootKeysSubdir+"/") {
+ return keyID, data.CanonicalRootRole, ""
+ }
+
+ keyPath = strings.TrimPrefix(keyPath, notary.NonRootKeysSubdir+"/")
+ gun = getGunFromFullID(keyPath)
+ return keyID, role, gun
+}
+
+func getGunFromFullID(fullKeyID string) string {
+ keyGun := filepath.Dir(fullKeyID)
+ // If the gun is empty, Dir will return .
+ if keyGun == "." {
+ keyGun = ""
+ }
+ return keyGun
+}
+
+func (s *GenericKeyStore) loadKeyInfo() {
+ s.keyInfoMap = generateKeyInfoMap(s.store)
+}
+
+// GetKeyInfo returns the corresponding gun and role key info for a keyID
+func (s *GenericKeyStore) GetKeyInfo(keyID string) (KeyInfo, error) {
+ if info, ok := s.keyInfoMap[keyID]; ok {
+ return info, nil
+ }
+ return KeyInfo{}, fmt.Errorf("Could not find info for keyID %s", keyID)
+}
+
+// AddKey stores the contents of a PEM-encoded private key as a PEM block
+func (s *GenericKeyStore) AddKey(keyInfo KeyInfo, privKey data.PrivateKey) error {
+ var (
+ chosenPassphrase string
+ giveup bool
+ err error
+ pemPrivKey []byte
+ )
+ s.Lock()
+ defer s.Unlock()
+ if keyInfo.Role == data.CanonicalRootRole || data.IsDelegation(keyInfo.Role) || !data.ValidRole(keyInfo.Role) {
+ keyInfo.Gun = ""
+ }
+ name := filepath.Join(keyInfo.Gun, privKey.ID())
+ for attempts := 0; ; attempts++ {
+ chosenPassphrase, giveup, err = s.PassRetriever(name, keyInfo.Role, true, attempts)
+ if err == nil {
+ break
+ }
+ if giveup || attempts > 10 {
+ return ErrAttemptsExceeded{}
+ }
+ }
+
+ if chosenPassphrase != "" {
+ pemPrivKey, err = utils.EncryptPrivateKey(privKey, keyInfo.Role, keyInfo.Gun, chosenPassphrase)
+ } else {
+ pemPrivKey, err = utils.KeyToPEM(privKey, keyInfo.Role)
+ }
+
+ if err != nil {
+ return err
+ }
+
+ s.cachedKeys[name] = &cachedKey{alias: keyInfo.Role, key: privKey}
+ err = s.store.Set(filepath.Join(getSubdir(keyInfo.Role), name), pemPrivKey)
+ if err != nil {
+ return err
+ }
+ s.keyInfoMap[privKey.ID()] = keyInfo
+ return nil
+}
+
+// GetKey returns the PrivateKey given a KeyID
+func (s *GenericKeyStore) GetKey(name string) (data.PrivateKey, string, error) {
+ s.Lock()
+ defer s.Unlock()
+ cachedKeyEntry, ok := s.cachedKeys[name]
+ if ok {
+ return cachedKeyEntry.key, cachedKeyEntry.alias, nil
+ }
+
+ keyBytes, _, keyAlias, err := getKey(s.store, name)
+ if err != nil {
+ return nil, "", err
+ }
+
+ // See if the key is encrypted. If its encrypted we'll fail to parse the private key
+ privKey, err := utils.ParsePEMPrivateKey(keyBytes, "")
+ if err != nil {
+ privKey, _, err = GetPasswdDecryptBytes(s.PassRetriever, keyBytes, name, string(keyAlias))
+ if err != nil {
+ return nil, "", err
+ }
+ }
+ s.cachedKeys[name] = &cachedKey{alias: keyAlias, key: privKey}
+ return privKey, keyAlias, nil
+}
+
+// ListKeys returns a list of unique PublicKeys present on the KeyFileStore, by returning a copy of the keyInfoMap
+func (s *GenericKeyStore) ListKeys() map[string]KeyInfo {
+ return copyKeyInfoMap(s.keyInfoMap)
+}
+
+// RemoveKey removes the key from the keyfilestore
+func (s *GenericKeyStore) RemoveKey(keyID string) error {
+ s.Lock()
+ defer s.Unlock()
+
+ _, filename, _, err := getKey(s.store, keyID)
+ switch err.(type) {
+ case ErrKeyNotFound, nil:
+ break
+ default:
+ return err
+ }
+
+ delete(s.cachedKeys, keyID)
+
+ err = s.store.Remove(filename) // removing a file that doesn't exist doesn't fail
+ if err != nil {
+ return err
+ }
+
+ // Remove this key from our keyInfo map if we removed from our filesystem
+ delete(s.keyInfoMap, filepath.Base(keyID))
+ return nil
+}
+
+// Name returns a user friendly name for the location this store
+// keeps its data
+func (s *GenericKeyStore) Name() string {
+ return s.store.Location()
+}
+
+// copyKeyInfoMap returns a deep copy of the passed-in keyInfoMap
+func copyKeyInfoMap(keyInfoMap map[string]KeyInfo) map[string]KeyInfo {
+ copyMap := make(map[string]KeyInfo)
+ for keyID, keyInfo := range keyInfoMap {
+ copyMap[keyID] = KeyInfo{Role: keyInfo.Role, Gun: keyInfo.Gun}
+ }
+ return copyMap
+}
+
+// KeyInfoFromPEM attempts to get a keyID and KeyInfo from the filename and PEM bytes of a key
+func KeyInfoFromPEM(pemBytes []byte, filename string) (string, KeyInfo, error) {
+ keyID, role, gun := inferKeyInfoFromKeyPath(filename)
+ if role == "" {
+ block, _ := pem.Decode(pemBytes)
+ if block == nil {
+ return "", KeyInfo{}, fmt.Errorf("could not decode PEM block for key %s", filename)
+ }
+ if keyRole, ok := block.Headers["role"]; ok {
+ role = keyRole
+ }
+ }
+ return keyID, KeyInfo{Gun: gun, Role: role}, nil
+}
+
+// getKey finds the key and role for the given keyID. It attempts to
+// look both in the newer format PEM headers, and also in the legacy filename
+// format. It returns: the key bytes, the filename it was found under, the role,
+// and an error
+func getKey(s Storage, keyID string) ([]byte, string, string, error) {
+ name := strings.TrimSpace(strings.TrimSuffix(filepath.Base(keyID), filepath.Ext(keyID)))
+
+ for _, file := range s.ListFiles() {
+ filename := filepath.Base(file)
+
+ if strings.HasPrefix(filename, name) {
+ d, err := s.Get(file)
+ if err != nil {
+ return nil, "", "", err
+ }
+ block, _ := pem.Decode(d)
+ if block != nil {
+ if role, ok := block.Headers["role"]; ok {
+ return d, file, role, nil
+ }
+ }
+
+ role := strings.TrimPrefix(filename, name+"_")
+ return d, file, role, nil
+ }
+ }
+
+ return nil, "", "", ErrKeyNotFound{KeyID: keyID}
+}
+
+// Assumes 2 subdirectories, 1 containing root keys and 1 containing TUF keys
+func getSubdir(alias string) string {
+ if alias == data.CanonicalRootRole {
+ return notary.RootKeysSubdir
+ }
+ return notary.NonRootKeysSubdir
+}
+
+// GetPasswdDecryptBytes gets the password to decrypt the given pem bytes.
+// Returns the password and private key
+func GetPasswdDecryptBytes(passphraseRetriever notary.PassRetriever, pemBytes []byte, name, alias string) (data.PrivateKey, string, error) {
+ var (
+ passwd string
+ privKey data.PrivateKey
+ )
+ for attempts := 0; ; attempts++ {
+ var (
+ giveup bool
+ err error
+ )
+ if attempts > 10 {
+ return nil, "", ErrAttemptsExceeded{}
+ }
+ passwd, giveup, err = passphraseRetriever(name, alias, false, attempts)
+ // Check if the passphrase retriever got an error or if it is telling us to give up
+ if giveup || err != nil {
+ return nil, "", ErrPasswordInvalid{}
+ }
+
+ // Try to convert PEM encoded bytes back to a PrivateKey using the passphrase
+ privKey, err = utils.ParsePEMPrivateKey(pemBytes, passwd)
+ if err == nil {
+ // We managed to parse the PrivateKey. We've succeeded!
+ break
+ }
+ }
+ return privKey, passwd, nil
+}
diff --git a/vendor/github.com/docker/notary/trustmanager/yubikey/import.go b/vendor/github.com/docker/notary/trustmanager/yubikey/import.go
new file mode 100644
index 0000000..08048ef
--- /dev/null
+++ b/vendor/github.com/docker/notary/trustmanager/yubikey/import.go
@@ -0,0 +1,57 @@
+// +build pkcs11
+
+package yubikey
+
+import (
+ "encoding/pem"
+ "errors"
+ "github.com/docker/notary"
+ "github.com/docker/notary/trustmanager"
+ "github.com/docker/notary/tuf/utils"
+)
+
+// YubiImport is a wrapper around the YubiStore that allows us to import private
+// keys to the yubikey
+type YubiImport struct {
+ dest *YubiStore
+ passRetriever notary.PassRetriever
+}
+
+// NewImporter returns a wrapper for the YubiStore provided that enables importing
+// keys via the simple Set(string, []byte) interface
+func NewImporter(ys *YubiStore, ret notary.PassRetriever) *YubiImport {
+ return &YubiImport{
+ dest: ys,
+ passRetriever: ret,
+ }
+}
+
+// Set determines if we are allowed to set the given key on the Yubikey and
+// calls through to YubiStore.AddKey if it's valid
+func (s *YubiImport) Set(name string, bytes []byte) error {
+ block, _ := pem.Decode(bytes)
+ if block == nil {
+ return errors.New("invalid PEM data, could not parse")
+ }
+ role, ok := block.Headers["role"]
+ if !ok {
+ return errors.New("no role found for key")
+ }
+ ki := trustmanager.KeyInfo{
+ // GUN is ignored by YubiStore
+ Role: role,
+ }
+ privKey, err := utils.ParsePEMPrivateKey(bytes, "")
+ if err != nil {
+ privKey, _, err = trustmanager.GetPasswdDecryptBytes(
+ s.passRetriever,
+ bytes,
+ name,
+ ki.Role,
+ )
+ if err != nil {
+ return err
+ }
+ }
+ return s.dest.AddKey(ki, privKey)
+}
diff --git a/vendor/github.com/docker/notary/trustmanager/yubikey/non_pkcs11.go b/vendor/github.com/docker/notary/trustmanager/yubikey/non_pkcs11.go
new file mode 100644
index 0000000..77c07e6
--- /dev/null
+++ b/vendor/github.com/docker/notary/trustmanager/yubikey/non_pkcs11.go
@@ -0,0 +1,9 @@
+// go list ./... and go test ./... will not pick up this package without this
+// file, because go ? ./... does not honor build tags.
+
+// e.g. "go list -tags pkcs11 ./..." will not list this package if all the
+// files in it have a build tag.
+
+// See https://github.com/golang/go/issues/11246
+
+package yubikey
diff --git a/vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_darwin.go b/vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_darwin.go
new file mode 100644
index 0000000..f399dff
--- /dev/null
+++ b/vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_darwin.go
@@ -0,0 +1,9 @@
+// +build pkcs11,darwin
+
+package yubikey
+
+var possiblePkcs11Libs = []string{
+ "/usr/local/lib/libykcs11.dylib",
+ "/usr/local/docker/lib/libykcs11.dylib",
+ "/usr/local/docker-experimental/lib/libykcs11.dylib",
+}
diff --git a/vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_interface.go b/vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_interface.go
new file mode 100644
index 0000000..4a46e05
--- /dev/null
+++ b/vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_interface.go
@@ -0,0 +1,40 @@
+// +build pkcs11
+
+// an interface around the pkcs11 library, so that things can be mocked out
+// for testing
+
+package yubikey
+
+import "github.com/miekg/pkcs11"
+
+// IPKCS11 is an interface for wrapping github.com/miekg/pkcs11
+type pkcs11LibLoader func(module string) IPKCS11Ctx
+
+func defaultLoader(module string) IPKCS11Ctx {
+ return pkcs11.New(module)
+}
+
+// IPKCS11Ctx is an interface for wrapping the parts of
+// github.com/miekg/pkcs11.Ctx that yubikeystore requires
+type IPKCS11Ctx interface {
+ Destroy()
+ Initialize() error
+ Finalize() error
+ GetSlotList(tokenPresent bool) ([]uint, error)
+ OpenSession(slotID uint, flags uint) (pkcs11.SessionHandle, error)
+ CloseSession(sh pkcs11.SessionHandle) error
+ Login(sh pkcs11.SessionHandle, userType uint, pin string) error
+ Logout(sh pkcs11.SessionHandle) error
+ CreateObject(sh pkcs11.SessionHandle, temp []*pkcs11.Attribute) (
+ pkcs11.ObjectHandle, error)
+ DestroyObject(sh pkcs11.SessionHandle, oh pkcs11.ObjectHandle) error
+ GetAttributeValue(sh pkcs11.SessionHandle, o pkcs11.ObjectHandle,
+ a []*pkcs11.Attribute) ([]*pkcs11.Attribute, error)
+ FindObjectsInit(sh pkcs11.SessionHandle, temp []*pkcs11.Attribute) error
+ FindObjects(sh pkcs11.SessionHandle, max int) (
+ []pkcs11.ObjectHandle, bool, error)
+ FindObjectsFinal(sh pkcs11.SessionHandle) error
+ SignInit(sh pkcs11.SessionHandle, m []*pkcs11.Mechanism,
+ o pkcs11.ObjectHandle) error
+ Sign(sh pkcs11.SessionHandle, message []byte) ([]byte, error)
+}
diff --git a/vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_linux.go b/vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_linux.go
new file mode 100644
index 0000000..9967e89
--- /dev/null
+++ b/vendor/github.com/docker/notary/trustmanager/yubikey/pkcs11_linux.go
@@ -0,0 +1,10 @@
+// +build pkcs11,linux
+
+package yubikey
+
+var possiblePkcs11Libs = []string{
+ "/usr/lib/libykcs11.so",
+ "/usr/lib64/libykcs11.so",
+ "/usr/lib/x86_64-linux-gnu/libykcs11.so",
+ "/usr/local/lib/libykcs11.so",
+}
diff --git a/vendor/github.com/docker/notary/trustmanager/yubikey/yubikeystore.go b/vendor/github.com/docker/notary/trustmanager/yubikey/yubikeystore.go
new file mode 100644
index 0000000..94f9bd1
--- /dev/null
+++ b/vendor/github.com/docker/notary/trustmanager/yubikey/yubikeystore.go
@@ -0,0 +1,914 @@
+// +build pkcs11
+
+package yubikey
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/x509"
+ "errors"
+ "fmt"
+ "io"
+ "math/big"
+ "os"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary"
+ "github.com/docker/notary/trustmanager"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/signed"
+ "github.com/docker/notary/tuf/utils"
+ "github.com/miekg/pkcs11"
+)
+
+const (
+ // UserPin is the user pin of a yubikey (in PIV parlance, is the PIN)
+ UserPin = "123456"
+ // SOUserPin is the "Security Officer" user pin - this is the PIV management
+ // (MGM) key, which is different than the admin pin of the Yubikey PGP interface
+ // (which in PIV parlance is the PUK, and defaults to 12345678)
+ SOUserPin = "010203040506070801020304050607080102030405060708"
+ numSlots = 4 // number of slots in the yubikey
+
+ // KeymodeNone means that no touch or PIN is required to sign with the yubikey
+ KeymodeNone = 0
+ // KeymodeTouch means that only touch is required to sign with the yubikey
+ KeymodeTouch = 1
+ // KeymodePinOnce means that the pin entry is required once the first time to sign with the yubikey
+ KeymodePinOnce = 2
+ // KeymodePinAlways means that pin entry is required every time to sign with the yubikey
+ KeymodePinAlways = 4
+
+ // the key size, when importing a key into yubikey, MUST be 32 bytes
+ ecdsaPrivateKeySize = 32
+
+ sigAttempts = 5
+)
+
+// what key mode to use when generating keys
+var (
+ yubikeyKeymode = KeymodeTouch | KeymodePinOnce
+ // order in which to prefer token locations on the yubikey.
+ // corresponds to: 9c, 9e, 9d, 9a
+ slotIDs = []int{2, 1, 3, 0}
+)
+
+// SetYubikeyKeyMode - sets the mode when generating yubikey keys.
+// This is to be used for testing. It does nothing if not building with tag
+// pkcs11.
+func SetYubikeyKeyMode(keyMode int) error {
+ // technically 7 (1 | 2 | 4) is valid, but KeymodePinOnce +
+ // KeymdoePinAlways don't really make sense together
+ if keyMode < 0 || keyMode > 5 {
+ return errors.New("Invalid key mode")
+ }
+ yubikeyKeymode = keyMode
+ return nil
+}
+
+// SetTouchToSignUI - allows configurable UX for notifying a user that they
+// need to touch the yubikey to sign. The callback may be used to provide a
+// mechanism for updating a GUI (such as removing a modal) after the touch
+// has been made
+func SetTouchToSignUI(notifier func(), callback func()) {
+ touchToSignUI = notifier
+ if callback != nil {
+ touchDoneCallback = callback
+ }
+}
+
+var touchToSignUI = func() {
+ fmt.Println("Please touch the attached Yubikey to perform signing.")
+}
+
+var touchDoneCallback = func() {
+ // noop
+}
+
+var pkcs11Lib string
+
+func init() {
+ for _, loc := range possiblePkcs11Libs {
+ _, err := os.Stat(loc)
+ if err == nil {
+ p := pkcs11.New(loc)
+ if p != nil {
+ pkcs11Lib = loc
+ return
+ }
+ }
+ }
+}
+
+// ErrBackupFailed is returned when a YubiStore fails to back up a key that
+// is added
+type ErrBackupFailed struct {
+ err string
+}
+
+func (err ErrBackupFailed) Error() string {
+ return fmt.Sprintf("Failed to backup private key to: %s", err.err)
+}
+
+// An error indicating that the HSM is not present (as opposed to failing),
+// i.e. that we can confidently claim that the key is not stored in the HSM
+// without notifying the user about a missing or failing HSM.
+type errHSMNotPresent struct {
+ err string
+}
+
+func (err errHSMNotPresent) Error() string {
+ return err.err
+}
+
+type yubiSlot struct {
+ role string
+ slotID []byte
+}
+
+// YubiPrivateKey represents a private key inside of a yubikey
+type YubiPrivateKey struct {
+ data.ECDSAPublicKey
+ passRetriever notary.PassRetriever
+ slot []byte
+ libLoader pkcs11LibLoader
+}
+
+// yubikeySigner wraps a YubiPrivateKey and implements the crypto.Signer interface
+type yubikeySigner struct {
+ YubiPrivateKey
+}
+
+// NewYubiPrivateKey returns a YubiPrivateKey, which implements the data.PrivateKey
+// interface except that the private material is inaccessible
+func NewYubiPrivateKey(slot []byte, pubKey data.ECDSAPublicKey,
+ passRetriever notary.PassRetriever) *YubiPrivateKey {
+
+ return &YubiPrivateKey{
+ ECDSAPublicKey: pubKey,
+ passRetriever: passRetriever,
+ slot: slot,
+ libLoader: defaultLoader,
+ }
+}
+
+// Public is a required method of the crypto.Signer interface
+func (ys *yubikeySigner) Public() crypto.PublicKey {
+ publicKey, err := x509.ParsePKIXPublicKey(ys.YubiPrivateKey.Public())
+ if err != nil {
+ return nil
+ }
+
+ return publicKey
+}
+
+func (y *YubiPrivateKey) setLibLoader(loader pkcs11LibLoader) {
+ y.libLoader = loader
+}
+
+// CryptoSigner returns a crypto.Signer tha wraps the YubiPrivateKey. Needed for
+// Certificate generation only
+func (y *YubiPrivateKey) CryptoSigner() crypto.Signer {
+ return &yubikeySigner{YubiPrivateKey: *y}
+}
+
+// Private is not implemented in hardware keys
+func (y *YubiPrivateKey) Private() []byte {
+ // We cannot return the private material from a Yubikey
+ // TODO(david): We probably want to return an error here
+ return nil
+}
+
+// SignatureAlgorithm returns which algorithm this key uses to sign - currently
+// hardcoded to ECDSA
+func (y YubiPrivateKey) SignatureAlgorithm() data.SigAlgorithm {
+ return data.ECDSASignature
+}
+
+// Sign is a required method of the crypto.Signer interface and the data.PrivateKey
+// interface
+func (y *YubiPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) {
+ ctx, session, err := SetupHSMEnv(pkcs11Lib, y.libLoader)
+ if err != nil {
+ return nil, err
+ }
+ defer cleanup(ctx, session)
+
+ v := signed.Verifiers[data.ECDSASignature]
+ for i := 0; i < sigAttempts; i++ {
+ sig, err := sign(ctx, session, y.slot, y.passRetriever, msg)
+ if err != nil {
+ return nil, fmt.Errorf("failed to sign using Yubikey: %v", err)
+ }
+ if err := v.Verify(&y.ECDSAPublicKey, sig, msg); err == nil {
+ return sig, nil
+ }
+ }
+ return nil, errors.New("Failed to generate signature on Yubikey.")
+}
+
+// If a byte array is less than the number of bytes specified by
+// ecdsaPrivateKeySize, left-zero-pad the byte array until
+// it is the required size.
+func ensurePrivateKeySize(payload []byte) []byte {
+ final := payload
+ if len(payload) < ecdsaPrivateKeySize {
+ final = make([]byte, ecdsaPrivateKeySize)
+ copy(final[ecdsaPrivateKeySize-len(payload):], payload)
+ }
+ return final
+}
+
+// addECDSAKey adds a key to the yubikey
+func addECDSAKey(
+ ctx IPKCS11Ctx,
+ session pkcs11.SessionHandle,
+ privKey data.PrivateKey,
+ pkcs11KeyID []byte,
+ passRetriever notary.PassRetriever,
+ role string,
+) error {
+ logrus.Debugf("Attempting to add key to yubikey with ID: %s", privKey.ID())
+
+ err := login(ctx, session, passRetriever, pkcs11.CKU_SO, SOUserPin)
+ if err != nil {
+ return err
+ }
+ defer ctx.Logout(session)
+
+ // Create an ecdsa.PrivateKey out of the private key bytes
+ ecdsaPrivKey, err := x509.ParseECPrivateKey(privKey.Private())
+ if err != nil {
+ return err
+ }
+
+ ecdsaPrivKeyD := ensurePrivateKeySize(ecdsaPrivKey.D.Bytes())
+
+ // Hard-coded policy: the generated certificate expires in 10 years.
+ startTime := time.Now()
+ template, err := utils.NewCertificate(role, startTime, startTime.AddDate(10, 0, 0))
+ if err != nil {
+ return fmt.Errorf("failed to create the certificate template: %v", err)
+ }
+
+ certBytes, err := x509.CreateCertificate(rand.Reader, template, template, ecdsaPrivKey.Public(), ecdsaPrivKey)
+ if err != nil {
+ return fmt.Errorf("failed to create the certificate: %v", err)
+ }
+
+ certTemplate := []*pkcs11.Attribute{
+ pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_CERTIFICATE),
+ pkcs11.NewAttribute(pkcs11.CKA_VALUE, certBytes),
+ pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID),
+ }
+
+ privateKeyTemplate := []*pkcs11.Attribute{
+ pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),
+ pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_ECDSA),
+ pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID),
+ pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07}),
+ pkcs11.NewAttribute(pkcs11.CKA_VALUE, ecdsaPrivKeyD),
+ pkcs11.NewAttribute(pkcs11.CKA_VENDOR_DEFINED, yubikeyKeymode),
+ }
+
+ _, err = ctx.CreateObject(session, certTemplate)
+ if err != nil {
+ return fmt.Errorf("error importing: %v", err)
+ }
+
+ _, err = ctx.CreateObject(session, privateKeyTemplate)
+ if err != nil {
+ return fmt.Errorf("error importing: %v", err)
+ }
+
+ return nil
+}
+
+func getECDSAKey(ctx IPKCS11Ctx, session pkcs11.SessionHandle, pkcs11KeyID []byte) (*data.ECDSAPublicKey, string, error) {
+ findTemplate := []*pkcs11.Attribute{
+ pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
+ pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID),
+ pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),
+ }
+
+ attrTemplate := []*pkcs11.Attribute{
+ pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, []byte{0}),
+ pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, []byte{0}),
+ pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{0}),
+ }
+
+ if err := ctx.FindObjectsInit(session, findTemplate); err != nil {
+ logrus.Debugf("Failed to init: %s", err.Error())
+ return nil, "", err
+ }
+ obj, _, err := ctx.FindObjects(session, 1)
+ if err != nil {
+ logrus.Debugf("Failed to find objects: %v", err)
+ return nil, "", err
+ }
+ if err := ctx.FindObjectsFinal(session); err != nil {
+ logrus.Debugf("Failed to finalize: %s", err.Error())
+ return nil, "", err
+ }
+ if len(obj) != 1 {
+ logrus.Debugf("should have found one object")
+ return nil, "", errors.New("no matching keys found inside of yubikey")
+ }
+
+ // Retrieve the public-key material to be able to create a new ECSAKey
+ attr, err := ctx.GetAttributeValue(session, obj[0], attrTemplate)
+ if err != nil {
+ logrus.Debugf("Failed to get Attribute for: %v", obj[0])
+ return nil, "", err
+ }
+
+ // Iterate through all the attributes of this key and saves CKA_PUBLIC_EXPONENT and CKA_MODULUS. Removes ordering specific issues.
+ var rawPubKey []byte
+ for _, a := range attr {
+ if a.Type == pkcs11.CKA_EC_POINT {
+ rawPubKey = a.Value
+ }
+
+ }
+
+ ecdsaPubKey := ecdsa.PublicKey{Curve: elliptic.P256(), X: new(big.Int).SetBytes(rawPubKey[3:35]), Y: new(big.Int).SetBytes(rawPubKey[35:])}
+ pubBytes, err := x509.MarshalPKIXPublicKey(&ecdsaPubKey)
+ if err != nil {
+ logrus.Debugf("Failed to Marshal public key")
+ return nil, "", err
+ }
+
+ return data.NewECDSAPublicKey(pubBytes), data.CanonicalRootRole, nil
+}
+
+// sign returns a signature for a given signature request
+func sign(ctx IPKCS11Ctx, session pkcs11.SessionHandle, pkcs11KeyID []byte, passRetriever notary.PassRetriever, payload []byte) ([]byte, error) {
+ err := login(ctx, session, passRetriever, pkcs11.CKU_USER, UserPin)
+ if err != nil {
+ return nil, fmt.Errorf("error logging in: %v", err)
+ }
+ defer ctx.Logout(session)
+
+ // Define the ECDSA Private key template
+ class := pkcs11.CKO_PRIVATE_KEY
+ privateKeyTemplate := []*pkcs11.Attribute{
+ pkcs11.NewAttribute(pkcs11.CKA_CLASS, class),
+ pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_ECDSA),
+ pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID),
+ }
+
+ if err := ctx.FindObjectsInit(session, privateKeyTemplate); err != nil {
+ logrus.Debugf("Failed to init find objects: %s", err.Error())
+ return nil, err
+ }
+ obj, _, err := ctx.FindObjects(session, 1)
+ if err != nil {
+ logrus.Debugf("Failed to find objects: %v", err)
+ return nil, err
+ }
+ if err = ctx.FindObjectsFinal(session); err != nil {
+ logrus.Debugf("Failed to finalize find objects: %s", err.Error())
+ return nil, err
+ }
+ if len(obj) != 1 {
+ return nil, errors.New("length of objects found not 1")
+ }
+
+ var sig []byte
+ err = ctx.SignInit(
+ session, []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_ECDSA, nil)}, obj[0])
+ if err != nil {
+ return nil, err
+ }
+
+ // Get the SHA256 of the payload
+ digest := sha256.Sum256(payload)
+
+ if (yubikeyKeymode & KeymodeTouch) > 0 {
+ touchToSignUI()
+ defer touchDoneCallback()
+ }
+ // a call to Sign, whether or not Sign fails, will clear the SignInit
+ sig, err = ctx.Sign(session, digest[:])
+ if err != nil {
+ logrus.Debugf("Error while signing: %s", err)
+ return nil, err
+ }
+
+ if sig == nil {
+ return nil, errors.New("Failed to create signature")
+ }
+ return sig[:], nil
+}
+
+func yubiRemoveKey(ctx IPKCS11Ctx, session pkcs11.SessionHandle, pkcs11KeyID []byte, passRetriever notary.PassRetriever, keyID string) error {
+ err := login(ctx, session, passRetriever, pkcs11.CKU_SO, SOUserPin)
+ if err != nil {
+ return err
+ }
+ defer ctx.Logout(session)
+
+ template := []*pkcs11.Attribute{
+ pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
+ pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID),
+ //pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),
+ pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_CERTIFICATE),
+ }
+
+ if err := ctx.FindObjectsInit(session, template); err != nil {
+ logrus.Debugf("Failed to init find objects: %s", err.Error())
+ return err
+ }
+ obj, b, err := ctx.FindObjects(session, 1)
+ if err != nil {
+ logrus.Debugf("Failed to find objects: %s %v", err.Error(), b)
+ return err
+ }
+ if err := ctx.FindObjectsFinal(session); err != nil {
+ logrus.Debugf("Failed to finalize find objects: %s", err.Error())
+ return err
+ }
+ if len(obj) != 1 {
+ logrus.Debugf("should have found exactly one object")
+ return err
+ }
+
+ // Delete the certificate
+ err = ctx.DestroyObject(session, obj[0])
+ if err != nil {
+ logrus.Debugf("Failed to delete cert")
+ return err
+ }
+ return nil
+}
+
+func yubiListKeys(ctx IPKCS11Ctx, session pkcs11.SessionHandle) (keys map[string]yubiSlot, err error) {
+ keys = make(map[string]yubiSlot)
+ findTemplate := []*pkcs11.Attribute{
+ pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
+ //pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID),
+ pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_CERTIFICATE),
+ }
+
+ attrTemplate := []*pkcs11.Attribute{
+ pkcs11.NewAttribute(pkcs11.CKA_ID, []byte{0}),
+ pkcs11.NewAttribute(pkcs11.CKA_VALUE, []byte{0}),
+ }
+
+ if err = ctx.FindObjectsInit(session, findTemplate); err != nil {
+ logrus.Debugf("Failed to init: %s", err.Error())
+ return
+ }
+ objs, b, err := ctx.FindObjects(session, numSlots)
+ for err == nil {
+ var o []pkcs11.ObjectHandle
+ o, b, err = ctx.FindObjects(session, numSlots)
+ if err != nil {
+ continue
+ }
+ if len(o) == 0 {
+ break
+ }
+ objs = append(objs, o...)
+ }
+ if err != nil {
+ logrus.Debugf("Failed to find: %s %v", err.Error(), b)
+ if len(objs) == 0 {
+ return nil, err
+ }
+ }
+ if err = ctx.FindObjectsFinal(session); err != nil {
+ logrus.Debugf("Failed to finalize: %s", err.Error())
+ return
+ }
+ if len(objs) == 0 {
+ return nil, errors.New("No keys found in yubikey.")
+ }
+ logrus.Debugf("Found %d objects matching list filters", len(objs))
+ for _, obj := range objs {
+ var (
+ cert *x509.Certificate
+ slot []byte
+ )
+ // Retrieve the public-key material to be able to create a new ECDSA
+ attr, err := ctx.GetAttributeValue(session, obj, attrTemplate)
+ if err != nil {
+ logrus.Debugf("Failed to get Attribute for: %v", obj)
+ continue
+ }
+
+ // Iterate through all the attributes of this key and saves CKA_PUBLIC_EXPONENT and CKA_MODULUS. Removes ordering specific issues.
+ for _, a := range attr {
+ if a.Type == pkcs11.CKA_ID {
+ slot = a.Value
+ }
+ if a.Type == pkcs11.CKA_VALUE {
+ cert, err = x509.ParseCertificate(a.Value)
+ if err != nil {
+ continue
+ }
+ if !data.ValidRole(cert.Subject.CommonName) {
+ continue
+ }
+ }
+ }
+
+ // we found nothing
+ if cert == nil {
+ continue
+ }
+
+ var ecdsaPubKey *ecdsa.PublicKey
+ switch cert.PublicKeyAlgorithm {
+ case x509.ECDSA:
+ ecdsaPubKey = cert.PublicKey.(*ecdsa.PublicKey)
+ default:
+ logrus.Infof("Unsupported x509 PublicKeyAlgorithm: %d", cert.PublicKeyAlgorithm)
+ continue
+ }
+
+ pubBytes, err := x509.MarshalPKIXPublicKey(ecdsaPubKey)
+ if err != nil {
+ logrus.Debugf("Failed to Marshal public key")
+ continue
+ }
+
+ keys[data.NewECDSAPublicKey(pubBytes).ID()] = yubiSlot{
+ role: cert.Subject.CommonName,
+ slotID: slot,
+ }
+ }
+ return
+}
+
+func getNextEmptySlot(ctx IPKCS11Ctx, session pkcs11.SessionHandle) ([]byte, error) {
+ findTemplate := []*pkcs11.Attribute{
+ pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
+ }
+ attrTemplate := []*pkcs11.Attribute{
+ pkcs11.NewAttribute(pkcs11.CKA_ID, []byte{0}),
+ }
+
+ if err := ctx.FindObjectsInit(session, findTemplate); err != nil {
+ logrus.Debugf("Failed to init: %s", err.Error())
+ return nil, err
+ }
+ objs, b, err := ctx.FindObjects(session, numSlots)
+ // if there are more objects than `numSlots`, get all of them until
+ // there are no more to get
+ for err == nil {
+ var o []pkcs11.ObjectHandle
+ o, b, err = ctx.FindObjects(session, numSlots)
+ if err != nil {
+ continue
+ }
+ if len(o) == 0 {
+ break
+ }
+ objs = append(objs, o...)
+ }
+ taken := make(map[int]bool)
+ if err != nil {
+ logrus.Debugf("Failed to find: %s %v", err.Error(), b)
+ return nil, err
+ }
+ if err = ctx.FindObjectsFinal(session); err != nil {
+ logrus.Debugf("Failed to finalize: %s\n", err.Error())
+ return nil, err
+ }
+ for _, obj := range objs {
+ // Retrieve the slot ID
+ attr, err := ctx.GetAttributeValue(session, obj, attrTemplate)
+ if err != nil {
+ continue
+ }
+
+ // Iterate through attributes. If an ID attr was found, mark it as taken
+ for _, a := range attr {
+ if a.Type == pkcs11.CKA_ID {
+ if len(a.Value) < 1 {
+ continue
+ }
+ // a byte will always be capable of representing all slot IDs
+ // for the Yubikeys
+ slotNum := int(a.Value[0])
+ if slotNum >= numSlots {
+ // defensive
+ continue
+ }
+ taken[slotNum] = true
+ }
+ }
+ }
+ // iterate the token locations in our preferred order and use the first
+ // available one. Otherwise exit the loop and return an error.
+ for _, loc := range slotIDs {
+ if !taken[loc] {
+ return []byte{byte(loc)}, nil
+ }
+ }
+ return nil, errors.New("Yubikey has no available slots.")
+}
+
+// YubiStore is a KeyStore for private keys inside a Yubikey
+type YubiStore struct {
+ passRetriever notary.PassRetriever
+ keys map[string]yubiSlot
+ backupStore trustmanager.KeyStore
+ libLoader pkcs11LibLoader
+}
+
+// NewYubiStore returns a YubiStore, given a backup key store to write any
+// generated keys to (usually a KeyFileStore)
+func NewYubiStore(backupStore trustmanager.KeyStore, passphraseRetriever notary.PassRetriever) (
+ *YubiStore, error) {
+
+ s := &YubiStore{
+ passRetriever: passphraseRetriever,
+ keys: make(map[string]yubiSlot),
+ backupStore: backupStore,
+ libLoader: defaultLoader,
+ }
+ s.ListKeys() // populate keys field
+ return s, nil
+}
+
+// Name returns a user friendly name for the location this store
+// keeps its data
+func (s YubiStore) Name() string {
+ return "yubikey"
+}
+
+func (s *YubiStore) setLibLoader(loader pkcs11LibLoader) {
+ s.libLoader = loader
+}
+
+// ListKeys returns a list of keys in the yubikey store
+func (s *YubiStore) ListKeys() map[string]trustmanager.KeyInfo {
+ if len(s.keys) > 0 {
+ return buildKeyMap(s.keys)
+ }
+ ctx, session, err := SetupHSMEnv(pkcs11Lib, s.libLoader)
+ if err != nil {
+ logrus.Debugf("No yubikey found, using alternative key storage: %s", err.Error())
+ return nil
+ }
+ defer cleanup(ctx, session)
+
+ keys, err := yubiListKeys(ctx, session)
+ if err != nil {
+ logrus.Debugf("Failed to list key from the yubikey: %s", err.Error())
+ return nil
+ }
+ s.keys = keys
+
+ return buildKeyMap(keys)
+}
+
+// AddKey puts a key inside the Yubikey, as well as writing it to the backup store
+func (s *YubiStore) AddKey(keyInfo trustmanager.KeyInfo, privKey data.PrivateKey) error {
+ added, err := s.addKey(privKey.ID(), keyInfo.Role, privKey)
+ if err != nil {
+ return err
+ }
+ if added && s.backupStore != nil {
+ err = s.backupStore.AddKey(keyInfo, privKey)
+ if err != nil {
+ defer s.RemoveKey(privKey.ID())
+ return ErrBackupFailed{err: err.Error()}
+ }
+ }
+ return nil
+}
+
+// Only add if we haven't seen the key already. Return whether the key was
+// added.
+func (s *YubiStore) addKey(keyID, role string, privKey data.PrivateKey) (
+ bool, error) {
+
+ // We only allow adding root keys for now
+ if role != data.CanonicalRootRole {
+ return false, fmt.Errorf(
+ "yubikey only supports storing root keys, got %s for key: %s", role, keyID)
+ }
+
+ ctx, session, err := SetupHSMEnv(pkcs11Lib, s.libLoader)
+ if err != nil {
+ logrus.Debugf("No yubikey found, using alternative key storage: %s", err.Error())
+ return false, err
+ }
+ defer cleanup(ctx, session)
+
+ if k, ok := s.keys[keyID]; ok {
+ if k.role == role {
+ // already have the key and it's associated with the correct role
+ return false, nil
+ }
+ }
+
+ slot, err := getNextEmptySlot(ctx, session)
+ if err != nil {
+ logrus.Debugf("Failed to get an empty yubikey slot: %s", err.Error())
+ return false, err
+ }
+ logrus.Debugf("Attempting to store key using yubikey slot %v", slot)
+
+ err = addECDSAKey(
+ ctx, session, privKey, slot, s.passRetriever, role)
+ if err == nil {
+ s.keys[privKey.ID()] = yubiSlot{
+ role: role,
+ slotID: slot,
+ }
+ return true, nil
+ }
+ logrus.Debugf("Failed to add key to yubikey: %v", err)
+
+ return false, err
+}
+
+// GetKey retrieves a key from the Yubikey only (it does not look inside the
+// backup store)
+func (s *YubiStore) GetKey(keyID string) (data.PrivateKey, string, error) {
+ ctx, session, err := SetupHSMEnv(pkcs11Lib, s.libLoader)
+ if err != nil {
+ logrus.Debugf("No yubikey found, using alternative key storage: %s", err.Error())
+ if _, ok := err.(errHSMNotPresent); ok {
+ err = trustmanager.ErrKeyNotFound{KeyID: keyID}
+ }
+ return nil, "", err
+ }
+ defer cleanup(ctx, session)
+
+ key, ok := s.keys[keyID]
+ if !ok {
+ return nil, "", trustmanager.ErrKeyNotFound{KeyID: keyID}
+ }
+
+ pubKey, alias, err := getECDSAKey(ctx, session, key.slotID)
+ if err != nil {
+ logrus.Debugf("Failed to get key from slot %s: %s", key.slotID, err.Error())
+ return nil, "", err
+ }
+ // Check to see if we're returning the intended keyID
+ if pubKey.ID() != keyID {
+ return nil, "", fmt.Errorf("expected root key: %s, but found: %s", keyID, pubKey.ID())
+ }
+ privKey := NewYubiPrivateKey(key.slotID, *pubKey, s.passRetriever)
+ if privKey == nil {
+ return nil, "", errors.New("could not initialize new YubiPrivateKey")
+ }
+
+ return privKey, alias, err
+}
+
+// RemoveKey deletes a key from the Yubikey only (it does not remove it from the
+// backup store)
+func (s *YubiStore) RemoveKey(keyID string) error {
+ ctx, session, err := SetupHSMEnv(pkcs11Lib, s.libLoader)
+ if err != nil {
+ logrus.Debugf("No yubikey found, using alternative key storage: %s", err.Error())
+ return nil
+ }
+ defer cleanup(ctx, session)
+
+ key, ok := s.keys[keyID]
+ if !ok {
+ return errors.New("Key not present in yubikey")
+ }
+ err = yubiRemoveKey(ctx, session, key.slotID, s.passRetriever, keyID)
+ if err == nil {
+ delete(s.keys, keyID)
+ } else {
+ logrus.Debugf("Failed to remove from the yubikey KeyID %s: %v", keyID, err)
+ }
+
+ return err
+}
+
+// GetKeyInfo is not yet implemented
+func (s *YubiStore) GetKeyInfo(keyID string) (trustmanager.KeyInfo, error) {
+ return trustmanager.KeyInfo{}, fmt.Errorf("Not yet implemented")
+}
+
+func cleanup(ctx IPKCS11Ctx, session pkcs11.SessionHandle) {
+ err := ctx.CloseSession(session)
+ if err != nil {
+ logrus.Debugf("Error closing session: %s", err.Error())
+ }
+ finalizeAndDestroy(ctx)
+}
+
+func finalizeAndDestroy(ctx IPKCS11Ctx) {
+ err := ctx.Finalize()
+ if err != nil {
+ logrus.Debugf("Error finalizing: %s", err.Error())
+ }
+ ctx.Destroy()
+}
+
+// SetupHSMEnv is a method that depends on the existences
+func SetupHSMEnv(libraryPath string, libLoader pkcs11LibLoader) (
+ IPKCS11Ctx, pkcs11.SessionHandle, error) {
+
+ if libraryPath == "" {
+ return nil, 0, errHSMNotPresent{err: "no library found"}
+ }
+ p := libLoader(libraryPath)
+
+ if p == nil {
+ return nil, 0, fmt.Errorf("failed to load library %s", libraryPath)
+ }
+
+ if err := p.Initialize(); err != nil {
+ defer finalizeAndDestroy(p)
+ return nil, 0, fmt.Errorf("found library %s, but initialize error %s", libraryPath, err.Error())
+ }
+
+ slots, err := p.GetSlotList(true)
+ if err != nil {
+ defer finalizeAndDestroy(p)
+ return nil, 0, fmt.Errorf(
+ "loaded library %s, but failed to list HSM slots %s", libraryPath, err)
+ }
+ // Check to see if we got any slots from the HSM.
+ if len(slots) < 1 {
+ defer finalizeAndDestroy(p)
+ return nil, 0, fmt.Errorf(
+ "loaded library %s, but no HSM slots found", libraryPath)
+ }
+
+ // CKF_SERIAL_SESSION: TRUE if cryptographic functions are performed in serial with the application; FALSE if the functions may be performed in parallel with the application.
+ // CKF_RW_SESSION: TRUE if the session is read/write; FALSE if the session is read-only
+ session, err := p.OpenSession(slots[0], pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION)
+ if err != nil {
+ defer cleanup(p, session)
+ return nil, 0, fmt.Errorf(
+ "loaded library %s, but failed to start session with HSM %s",
+ libraryPath, err)
+ }
+
+ logrus.Debugf("Initialized PKCS11 library %s and started HSM session", libraryPath)
+ return p, session, nil
+}
+
+// IsAccessible returns true if a Yubikey can be accessed
+func IsAccessible() bool {
+ if pkcs11Lib == "" {
+ return false
+ }
+ ctx, session, err := SetupHSMEnv(pkcs11Lib, defaultLoader)
+ if err != nil {
+ return false
+ }
+ defer cleanup(ctx, session)
+ return true
+}
+
+func login(ctx IPKCS11Ctx, session pkcs11.SessionHandle, passRetriever notary.PassRetriever, userFlag uint, defaultPassw string) error {
+ // try default password
+ err := ctx.Login(session, userFlag, defaultPassw)
+ if err == nil {
+ return nil
+ }
+
+ // default failed, ask user for password
+ for attempts := 0; ; attempts++ {
+ var (
+ giveup bool
+ err error
+ user string
+ )
+ if userFlag == pkcs11.CKU_SO {
+ user = "SO Pin"
+ } else {
+ user = "User Pin"
+ }
+ passwd, giveup, err := passRetriever(user, "yubikey", false, attempts)
+ // Check if the passphrase retriever got an error or if it is telling us to give up
+ if giveup || err != nil {
+ return trustmanager.ErrPasswordInvalid{}
+ }
+ if attempts > 2 {
+ return trustmanager.ErrAttemptsExceeded{}
+ }
+
+ // attempt to login. Loop if failed
+ err = ctx.Login(session, userFlag, passwd)
+ if err == nil {
+ return nil
+ }
+ }
+}
+
+func buildKeyMap(keys map[string]yubiSlot) map[string]trustmanager.KeyInfo {
+ res := make(map[string]trustmanager.KeyInfo)
+ for k, v := range keys {
+ res[k] = trustmanager.KeyInfo{Role: v.role, Gun: ""}
+ }
+ return res
+}
diff --git a/vendor/github.com/docker/notary/trustpinning/certs.go b/vendor/github.com/docker/notary/trustpinning/certs.go
new file mode 100644
index 0000000..709df67
--- /dev/null
+++ b/vendor/github.com/docker/notary/trustpinning/certs.go
@@ -0,0 +1,291 @@
+package trustpinning
+
+import (
+ "crypto/x509"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/signed"
+ "github.com/docker/notary/tuf/utils"
+)
+
+// ErrValidationFail is returned when there is no valid trusted certificates
+// being served inside of the roots.json
+type ErrValidationFail struct {
+ Reason string
+}
+
+// ErrValidationFail is returned when there is no valid trusted certificates
+// being served inside of the roots.json
+func (err ErrValidationFail) Error() string {
+ return fmt.Sprintf("could not validate the path to a trusted root: %s", err.Reason)
+}
+
+// ErrRootRotationFail is returned when we fail to do a full root key rotation
+// by either failing to add the new root certificate, or delete the old ones
+type ErrRootRotationFail struct {
+ Reason string
+}
+
+// ErrRootRotationFail is returned when we fail to do a full root key rotation
+// by either failing to add the new root certificate, or delete the old ones
+func (err ErrRootRotationFail) Error() string {
+ return fmt.Sprintf("could not rotate trust to a new trusted root: %s", err.Reason)
+}
+
+func prettyFormatCertIDs(certs map[string]*x509.Certificate) string {
+ ids := make([]string, 0, len(certs))
+ for id := range certs {
+ ids = append(ids, id)
+ }
+ return strings.Join(ids, ", ")
+}
+
+/*
+ValidateRoot receives a new root, validates its correctness and attempts to
+do root key rotation if needed.
+
+First we check if we have any trusted certificates for a particular GUN in
+a previous root, if we have one. If the previous root is not nil and we find
+certificates for this GUN, we've already seen this repository before, and
+have a list of trusted certificates for it. In this case, we use this list of
+certificates to attempt to validate this root file.
+
+If the previous validation succeeds, we check the integrity of the root by
+making sure that it is validated by itself. This means that we will attempt to
+validate the root data with the certificates that are included in the root keys
+themselves.
+
+However, if we do not have any current trusted certificates for this GUN, we
+check if there are any pinned certificates specified in the trust_pinning section
+of the notary client config. If this section specifies a Certs section with this
+GUN, we attempt to validate that the certificates present in the downloaded root
+file match the pinned ID.
+
+If the Certs section is empty for this GUN, we check if the trust_pinning
+section specifies a CA section specified in the config for this GUN. If so, we check
+that the specified CA is valid and has signed a certificate included in the downloaded
+root file. The specified CA can be a prefix for this GUN.
+
+If both the Certs and CA configs do not match this GUN, we fall back to the TOFU
+section in the config: if true, we trust certificates specified in the root for
+this GUN. If later we see a different certificate for that certificate, we return
+an ErrValidationFailed error.
+
+Note that since we only allow trust data to be downloaded over an HTTPS channel
+we are using the current public PKI to validate the first download of the certificate
+adding an extra layer of security over the normal (SSH style) trust model.
+We shall call this: TOFUS.
+
+Validation failure at any step will result in an ErrValidationFailed error.
+*/
+func ValidateRoot(prevRoot *data.SignedRoot, root *data.Signed, gun string, trustPinning TrustPinConfig) (*data.SignedRoot, error) {
+ logrus.Debugf("entered ValidateRoot with dns: %s", gun)
+ signedRoot, err := data.RootFromSigned(root)
+ if err != nil {
+ return nil, err
+ }
+
+ rootRole, err := signedRoot.BuildBaseRole(data.CanonicalRootRole)
+ if err != nil {
+ return nil, err
+ }
+
+ // Retrieve all the leaf and intermediate certificates in root for which the CN matches the GUN
+ allLeafCerts, allIntCerts := parseAllCerts(signedRoot)
+ certsFromRoot, err := validRootLeafCerts(allLeafCerts, gun, true)
+ validIntCerts := validRootIntCerts(allIntCerts)
+
+ if err != nil {
+ logrus.Debugf("error retrieving valid leaf certificates for: %s, %v", gun, err)
+ return nil, &ErrValidationFail{Reason: "unable to retrieve valid leaf certificates"}
+ }
+
+ logrus.Debugf("found %d leaf certs, of which %d are valid leaf certs for %s", len(allLeafCerts), len(certsFromRoot), gun)
+
+ // If we have a previous root, let's try to use it to validate that this new root is valid.
+ havePrevRoot := prevRoot != nil
+ if havePrevRoot {
+ // Retrieve all the trusted certificates from our previous root
+ // Note that we do not validate expiries here since our originally trusted root might have expired certs
+ allTrustedLeafCerts, allTrustedIntCerts := parseAllCerts(prevRoot)
+ trustedLeafCerts, err := validRootLeafCerts(allTrustedLeafCerts, gun, false)
+ if err != nil {
+ return nil, &ErrValidationFail{Reason: "could not retrieve trusted certs from previous root role data"}
+ }
+
+ // Use the certificates we found in the previous root for the GUN to verify its signatures
+ // This could potentially be an empty set, in which case we will fail to verify
+ logrus.Debugf("found %d valid root leaf certificates for %s: %s", len(trustedLeafCerts), gun,
+ prettyFormatCertIDs(trustedLeafCerts))
+
+ // Extract the previous root's threshold for signature verification
+ prevRootRoleData, ok := prevRoot.Signed.Roles[data.CanonicalRootRole]
+ if !ok {
+ return nil, &ErrValidationFail{Reason: "could not retrieve previous root role data"}
+ }
+ err = signed.VerifySignatures(
+ root, data.BaseRole{Keys: utils.CertsToKeys(trustedLeafCerts, allTrustedIntCerts), Threshold: prevRootRoleData.Threshold})
+ if err != nil {
+ logrus.Debugf("failed to verify TUF data for: %s, %v", gun, err)
+ return nil, &ErrRootRotationFail{Reason: "failed to validate data with current trusted certificates"}
+ }
+ // Clear the IsValid marks we could have received from VerifySignatures
+ for i := range root.Signatures {
+ root.Signatures[i].IsValid = false
+ }
+ }
+
+ // Regardless of having a previous root or not, confirm that the new root validates against the trust pinning
+ logrus.Debugf("checking root against trust_pinning config", gun)
+ trustPinCheckFunc, err := NewTrustPinChecker(trustPinning, gun, !havePrevRoot)
+ if err != nil {
+ return nil, &ErrValidationFail{Reason: err.Error()}
+ }
+
+ validPinnedCerts := map[string]*x509.Certificate{}
+ for id, cert := range certsFromRoot {
+ logrus.Debugf("checking trust-pinning for cert: %s", id)
+ if ok := trustPinCheckFunc(cert, validIntCerts[id]); !ok {
+ logrus.Debugf("trust-pinning check failed for cert: %s", id)
+ continue
+ }
+ validPinnedCerts[id] = cert
+ }
+ if len(validPinnedCerts) == 0 {
+ return nil, &ErrValidationFail{Reason: "unable to match any certificates to trust_pinning config"}
+ }
+ certsFromRoot = validPinnedCerts
+
+ // Validate the integrity of the new root (does it have valid signatures)
+ // Note that certsFromRoot is guaranteed to be unchanged only if we had prior cert data for this GUN or enabled TOFUS
+ // If we attempted to pin a certain certificate or CA, certsFromRoot could have been pruned accordingly
+ err = signed.VerifySignatures(root, data.BaseRole{
+ Keys: utils.CertsToKeys(certsFromRoot, validIntCerts), Threshold: rootRole.Threshold})
+ if err != nil {
+ logrus.Debugf("failed to verify TUF data for: %s, %v", gun, err)
+ return nil, &ErrValidationFail{Reason: "failed to validate integrity of roots"}
+ }
+
+ logrus.Debugf("root validation succeeded for %s", gun)
+ // Call RootFromSigned to make sure we pick up on the IsValid markings from VerifySignatures
+ return data.RootFromSigned(root)
+}
+
+// validRootLeafCerts returns a list of possibly (if checkExpiry is true) non-expired, non-sha1 certificates
+// found in root whose Common-Names match the provided GUN. Note that this
+// "validity" alone does not imply any measure of trust.
+func validRootLeafCerts(allLeafCerts map[string]*x509.Certificate, gun string, checkExpiry bool) (map[string]*x509.Certificate, error) {
+ validLeafCerts := make(map[string]*x509.Certificate)
+
+ // Go through every leaf certificate and check that the CN matches the gun
+ for id, cert := range allLeafCerts {
+ // Validate that this leaf certificate has a CN that matches the exact gun
+ if cert.Subject.CommonName != gun {
+ logrus.Debugf("error leaf certificate CN: %s doesn't match the given GUN: %s",
+ cert.Subject.CommonName, gun)
+ continue
+ }
+ // Make sure the certificate is not expired if checkExpiry is true
+ // and warn if it hasn't expired yet but is within 6 months of expiry
+ if err := utils.ValidateCertificate(cert, checkExpiry); err != nil {
+ logrus.Debugf("%s is invalid: %s", id, err.Error())
+ continue
+ }
+
+ validLeafCerts[id] = cert
+ }
+
+ if len(validLeafCerts) < 1 {
+ logrus.Debugf("didn't find any valid leaf certificates for %s", gun)
+ return nil, errors.New("no valid leaf certificates found in any of the root keys")
+ }
+
+ logrus.Debugf("found %d valid leaf certificates for %s: %s", len(validLeafCerts), gun,
+ prettyFormatCertIDs(validLeafCerts))
+ return validLeafCerts, nil
+}
+
+// validRootIntCerts filters the passed in structure of intermediate certificates to only include non-expired, non-sha1 certificates
+// Note that this "validity" alone does not imply any measure of trust.
+func validRootIntCerts(allIntCerts map[string][]*x509.Certificate) map[string][]*x509.Certificate {
+ validIntCerts := make(map[string][]*x509.Certificate)
+
+ // Go through every leaf cert ID, and build its valid intermediate certificate list
+ for leafID, intCertList := range allIntCerts {
+ for _, intCert := range intCertList {
+ if err := utils.ValidateCertificate(intCert, true); err != nil {
+ continue
+ }
+ validIntCerts[leafID] = append(validIntCerts[leafID], intCert)
+ }
+
+ }
+ return validIntCerts
+}
+
+// parseAllCerts returns two maps, one with all of the leafCertificates and one
+// with all the intermediate certificates found in signedRoot
+func parseAllCerts(signedRoot *data.SignedRoot) (map[string]*x509.Certificate, map[string][]*x509.Certificate) {
+ if signedRoot == nil {
+ return nil, nil
+ }
+
+ leafCerts := make(map[string]*x509.Certificate)
+ intCerts := make(map[string][]*x509.Certificate)
+
+ // Before we loop through all root keys available, make sure any exist
+ rootRoles, ok := signedRoot.Signed.Roles[data.CanonicalRootRole]
+ if !ok {
+ logrus.Debugf("tried to parse certificates from invalid root signed data")
+ return nil, nil
+ }
+
+ logrus.Debugf("found the following root keys: %v", rootRoles.KeyIDs)
+ // Iterate over every keyID for the root role inside of roots.json
+ for _, keyID := range rootRoles.KeyIDs {
+ // check that the key exists in the signed root keys map
+ key, ok := signedRoot.Signed.Keys[keyID]
+ if !ok {
+ logrus.Debugf("error while getting data for keyID: %s", keyID)
+ continue
+ }
+
+ // Decode all the x509 certificates that were bundled with this
+ // Specific root key
+ decodedCerts, err := utils.LoadCertBundleFromPEM(key.Public())
+ if err != nil {
+ logrus.Debugf("error while parsing root certificate with keyID: %s, %v", keyID, err)
+ continue
+ }
+
+ // Get all non-CA certificates in the decoded certificates
+ leafCertList := utils.GetLeafCerts(decodedCerts)
+
+ // If we got no leaf certificates or we got more than one, fail
+ if len(leafCertList) != 1 {
+ logrus.Debugf("invalid chain due to leaf certificate missing or too many leaf certificates for keyID: %s", keyID)
+ continue
+ }
+ // If we found a leaf certificate, assert that the cert bundle started with a leaf
+ if decodedCerts[0].IsCA {
+ logrus.Debugf("invalid chain due to leaf certificate not being first certificate for keyID: %s", keyID)
+ continue
+ }
+
+ // Get the ID of the leaf certificate
+ leafCert := leafCertList[0]
+
+ // Store the leaf cert in the map
+ leafCerts[key.ID()] = leafCert
+
+ // Get all the remainder certificates marked as a CA to be used as intermediates
+ intermediateCerts := utils.GetIntermediateCerts(decodedCerts)
+ intCerts[key.ID()] = intermediateCerts
+ }
+
+ return leafCerts, intCerts
+}
diff --git a/vendor/github.com/docker/notary/trustpinning/trustpin.go b/vendor/github.com/docker/notary/trustpinning/trustpin.go
new file mode 100644
index 0000000..2528856
--- /dev/null
+++ b/vendor/github.com/docker/notary/trustpinning/trustpin.go
@@ -0,0 +1,121 @@
+package trustpinning
+
+import (
+ "crypto/x509"
+ "fmt"
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary/tuf/utils"
+ "strings"
+)
+
+// TrustPinConfig represents the configuration under the trust_pinning section of the config file
+// This struct represents the preferred way to bootstrap trust for this repository
+type TrustPinConfig struct {
+ CA map[string]string
+ Certs map[string][]string
+ DisableTOFU bool
+}
+
+type trustPinChecker struct {
+ gun string
+ config TrustPinConfig
+ pinnedCAPool *x509.CertPool
+ pinnedCertIDs []string
+}
+
+// CertChecker is a function type that will be used to check leaf certs against pinned trust
+type CertChecker func(leafCert *x509.Certificate, intCerts []*x509.Certificate) bool
+
+// NewTrustPinChecker returns a new certChecker function from a TrustPinConfig for a GUN
+func NewTrustPinChecker(trustPinConfig TrustPinConfig, gun string, firstBootstrap bool) (CertChecker, error) {
+ t := trustPinChecker{gun: gun, config: trustPinConfig}
+ // Determine the mode, and if it's even valid
+ if pinnedCerts, ok := trustPinConfig.Certs[gun]; ok {
+ logrus.Debugf("trust-pinning using Cert IDs")
+ t.pinnedCertIDs = pinnedCerts
+ return t.certsCheck, nil
+ }
+
+ if caFilepath, err := getPinnedCAFilepathByPrefix(gun, trustPinConfig); err == nil {
+ logrus.Debugf("trust-pinning using root CA bundle at: %s", caFilepath)
+
+ // Try to add the CA certs from its bundle file to our certificate store,
+ // and use it to validate certs in the root.json later
+ caCerts, err := utils.LoadCertBundleFromFile(caFilepath)
+ if err != nil {
+ return nil, fmt.Errorf("could not load root cert from CA path")
+ }
+ // Now only consider certificates that are direct children from this CA cert chain
+ caRootPool := x509.NewCertPool()
+ for _, caCert := range caCerts {
+ if err = utils.ValidateCertificate(caCert, true); err != nil {
+ logrus.Debugf("ignoring root CA certificate with CN %s in bundle: %s", caCert.Subject.CommonName, err)
+ continue
+ }
+ caRootPool.AddCert(caCert)
+ }
+ // If we didn't have any valid CA certs, error out
+ if len(caRootPool.Subjects()) == 0 {
+ return nil, fmt.Errorf("invalid CA certs provided")
+ }
+ t.pinnedCAPool = caRootPool
+ return t.caCheck, nil
+ }
+
+ // If TOFUs is disabled and we don't have any previous trusted root data for this GUN, we error out
+ if trustPinConfig.DisableTOFU && firstBootstrap {
+ return nil, fmt.Errorf("invalid trust pinning specified")
+
+ }
+ return t.tofusCheck, nil
+}
+
+func (t trustPinChecker) certsCheck(leafCert *x509.Certificate, intCerts []*x509.Certificate) bool {
+ // reconstruct the leaf + intermediate cert chain, which is bundled as {leaf, intermediates...},
+ // in order to get the matching id in the root file
+ key, err := utils.CertBundleToKey(leafCert, intCerts)
+ if err != nil {
+ logrus.Debug("error creating cert bundle: ", err.Error())
+ return false
+ }
+ return utils.StrSliceContains(t.pinnedCertIDs, key.ID())
+}
+
+func (t trustPinChecker) caCheck(leafCert *x509.Certificate, intCerts []*x509.Certificate) bool {
+ // Use intermediate certificates included in the root TUF metadata for our validation
+ caIntPool := x509.NewCertPool()
+ for _, intCert := range intCerts {
+ caIntPool.AddCert(intCert)
+ }
+ // Attempt to find a valid certificate chain from the leaf cert to CA root
+ // Use this certificate if such a valid chain exists (possibly using intermediates)
+ var err error
+ if _, err = leafCert.Verify(x509.VerifyOptions{Roots: t.pinnedCAPool, Intermediates: caIntPool}); err == nil {
+ return true
+ }
+ logrus.Debugf("unable to find a valid certificate chain from leaf cert to CA root: %s", err)
+ return false
+}
+
+func (t trustPinChecker) tofusCheck(leafCert *x509.Certificate, intCerts []*x509.Certificate) bool {
+ return true
+}
+
+// Will return the CA filepath corresponding to the most specific (longest) entry in the map that is still a prefix
+// of the provided gun. Returns an error if no entry matches this GUN as a prefix.
+func getPinnedCAFilepathByPrefix(gun string, t TrustPinConfig) (string, error) {
+ specificGUN := ""
+ specificCAFilepath := ""
+ foundCA := false
+ for gunPrefix, caFilepath := range t.CA {
+ if strings.HasPrefix(gun, gunPrefix) && len(gunPrefix) >= len(specificGUN) {
+ specificGUN = gunPrefix
+ specificCAFilepath = caFilepath
+ foundCA = true
+ }
+ }
+ if !foundCA {
+ return "", fmt.Errorf("could not find pinned CA for GUN: %s\n", gun)
+ }
+ return specificCAFilepath, nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/LICENSE b/vendor/github.com/docker/notary/tuf/LICENSE
new file mode 100644
index 0000000..d92ae9e
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/LICENSE
@@ -0,0 +1,30 @@
+Copyright (c) 2015, Docker Inc.
+Copyright (c) 2014-2015 Prime Directive, Inc.
+
+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 Prime Directive, 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/docker/notary/tuf/README.md b/vendor/github.com/docker/notary/tuf/README.md
new file mode 100644
index 0000000..22dd9cd
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/README.md
@@ -0,0 +1,6 @@
+## Credits
+
+This implementation was originally forked from [flynn/go-tuf](https://github.com/flynn/go-tuf)
+
+This implementation retains the same 3 Clause BSD license present on
+the original flynn implementation.
diff --git a/vendor/github.com/docker/notary/tuf/builder.go b/vendor/github.com/docker/notary/tuf/builder.go
new file mode 100644
index 0000000..1eaf049
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/builder.go
@@ -0,0 +1,710 @@
+package tuf
+
+import (
+ "fmt"
+
+ "github.com/docker/go/canonical/json"
+ "github.com/docker/notary"
+
+ "github.com/docker/notary/trustpinning"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/signed"
+ "github.com/docker/notary/tuf/utils"
+)
+
+// ErrBuildDone is returned when any functions are called on RepoBuilder, and it
+// is already finished building
+var ErrBuildDone = fmt.Errorf(
+ "the builder has finished building and cannot accept any more input or produce any more output")
+
+// ErrInvalidBuilderInput is returned when RepoBuilder.Load is called
+// with the wrong type of metadata for the state that it's in
+type ErrInvalidBuilderInput struct{ msg string }
+
+func (e ErrInvalidBuilderInput) Error() string {
+ return e.msg
+}
+
+// ConsistentInfo is the consistent name and size of a role, or just the name
+// of the role and a -1 if no file metadata for the role is known
+type ConsistentInfo struct {
+ RoleName string
+ fileMeta data.FileMeta
+}
+
+// ChecksumKnown determines whether or not we know enough to provide a size and
+// consistent name
+func (c ConsistentInfo) ChecksumKnown() bool {
+ // empty hash, no size : this is the zero value
+ return len(c.fileMeta.Hashes) > 0 || c.fileMeta.Length != 0
+}
+
+// ConsistentName returns the consistent name (rolename.sha256) for the role
+// given this consistent information
+func (c ConsistentInfo) ConsistentName() string {
+ return utils.ConsistentName(c.RoleName, c.fileMeta.Hashes[notary.SHA256])
+}
+
+// Length returns the expected length of the role as per this consistent
+// information - if no checksum information is known, the size is -1.
+func (c ConsistentInfo) Length() int64 {
+ if c.ChecksumKnown() {
+ return c.fileMeta.Length
+ }
+ return -1
+}
+
+// RepoBuilder is an interface for an object which builds a tuf.Repo
+type RepoBuilder interface {
+ Load(roleName string, content []byte, minVersion int, allowExpired bool) error
+ GenerateSnapshot(prev *data.SignedSnapshot) ([]byte, int, error)
+ GenerateTimestamp(prev *data.SignedTimestamp) ([]byte, int, error)
+ Finish() (*Repo, *Repo, error)
+ BootstrapNewBuilder() RepoBuilder
+ BootstrapNewBuilderWithNewTrustpin(trustpin trustpinning.TrustPinConfig) RepoBuilder
+
+ // informative functions
+ IsLoaded(roleName string) bool
+ GetLoadedVersion(roleName string) int
+ GetConsistentInfo(roleName string) ConsistentInfo
+}
+
+// finishedBuilder refuses any more input or output
+type finishedBuilder struct{}
+
+func (f finishedBuilder) Load(roleName string, content []byte, minVersion int, allowExpired bool) error {
+ return ErrBuildDone
+}
+func (f finishedBuilder) GenerateSnapshot(prev *data.SignedSnapshot) ([]byte, int, error) {
+ return nil, 0, ErrBuildDone
+}
+func (f finishedBuilder) GenerateTimestamp(prev *data.SignedTimestamp) ([]byte, int, error) {
+ return nil, 0, ErrBuildDone
+}
+func (f finishedBuilder) Finish() (*Repo, *Repo, error) { return nil, nil, ErrBuildDone }
+func (f finishedBuilder) BootstrapNewBuilder() RepoBuilder { return f }
+func (f finishedBuilder) BootstrapNewBuilderWithNewTrustpin(trustpin trustpinning.TrustPinConfig) RepoBuilder {
+ return f
+}
+func (f finishedBuilder) IsLoaded(roleName string) bool { return false }
+func (f finishedBuilder) GetLoadedVersion(roleName string) int { return 0 }
+func (f finishedBuilder) GetConsistentInfo(roleName string) ConsistentInfo {
+ return ConsistentInfo{RoleName: roleName}
+}
+
+// NewRepoBuilder is the only way to get a pre-built RepoBuilder
+func NewRepoBuilder(gun string, cs signed.CryptoService, trustpin trustpinning.TrustPinConfig) RepoBuilder {
+ return NewBuilderFromRepo(gun, NewRepo(cs), trustpin)
+}
+
+// NewBuilderFromRepo allows us to bootstrap a builder given existing repo data.
+// YOU PROBABLY SHOULDN'T BE USING THIS OUTSIDE OF TESTING CODE!!!
+func NewBuilderFromRepo(gun string, repo *Repo, trustpin trustpinning.TrustPinConfig) RepoBuilder {
+ return &repoBuilderWrapper{
+ RepoBuilder: &repoBuilder{
+ repo: repo,
+ invalidRoles: NewRepo(nil),
+ gun: gun,
+ trustpin: trustpin,
+ loadedNotChecksummed: make(map[string][]byte),
+ },
+ }
+}
+
+// repoBuilderWrapper embeds a repoBuilder, but once Finish is called, swaps
+// the embed out with a finishedBuilder
+type repoBuilderWrapper struct {
+ RepoBuilder
+}
+
+func (rbw *repoBuilderWrapper) Finish() (*Repo, *Repo, error) {
+ switch rbw.RepoBuilder.(type) {
+ case finishedBuilder:
+ return rbw.RepoBuilder.Finish()
+ default:
+ old := rbw.RepoBuilder
+ rbw.RepoBuilder = finishedBuilder{}
+ return old.Finish()
+ }
+}
+
+// repoBuilder actually builds a tuf.Repo
+type repoBuilder struct {
+ repo *Repo
+ invalidRoles *Repo
+
+ // needed for root trust pininng verification
+ gun string
+ trustpin trustpinning.TrustPinConfig
+
+ // in case we load root and/or targets before snapshot and timestamp (
+ // or snapshot and not timestamp), so we know what to verify when the
+ // data with checksums come in
+ loadedNotChecksummed map[string][]byte
+
+ // bootstrapped values to validate a new root
+ prevRoot *data.SignedRoot
+ bootstrappedRootChecksum *data.FileMeta
+
+ // for bootstrapping the next builder
+ nextRootChecksum *data.FileMeta
+}
+
+func (rb *repoBuilder) Finish() (*Repo, *Repo, error) {
+ return rb.repo, rb.invalidRoles, nil
+}
+
+func (rb *repoBuilder) BootstrapNewBuilder() RepoBuilder {
+ return &repoBuilderWrapper{RepoBuilder: &repoBuilder{
+ repo: NewRepo(rb.repo.cryptoService),
+ invalidRoles: NewRepo(nil),
+ gun: rb.gun,
+ loadedNotChecksummed: make(map[string][]byte),
+ trustpin: rb.trustpin,
+
+ prevRoot: rb.repo.Root,
+ bootstrappedRootChecksum: rb.nextRootChecksum,
+ }}
+}
+
+func (rb *repoBuilder) BootstrapNewBuilderWithNewTrustpin(trustpin trustpinning.TrustPinConfig) RepoBuilder {
+ return &repoBuilderWrapper{RepoBuilder: &repoBuilder{
+ repo: NewRepo(rb.repo.cryptoService),
+ gun: rb.gun,
+ loadedNotChecksummed: make(map[string][]byte),
+ trustpin: trustpin,
+
+ prevRoot: rb.repo.Root,
+ bootstrappedRootChecksum: rb.nextRootChecksum,
+ }}
+}
+
+// IsLoaded returns whether a particular role has already been loaded
+func (rb *repoBuilder) IsLoaded(roleName string) bool {
+ switch roleName {
+ case data.CanonicalRootRole:
+ return rb.repo.Root != nil
+ case data.CanonicalSnapshotRole:
+ return rb.repo.Snapshot != nil
+ case data.CanonicalTimestampRole:
+ return rb.repo.Timestamp != nil
+ default:
+ return rb.repo.Targets[roleName] != nil
+ }
+}
+
+// GetLoadedVersion returns the metadata version, if it is loaded, or 1 (the
+// minimum valid version number) otherwise
+func (rb *repoBuilder) GetLoadedVersion(roleName string) int {
+ switch {
+ case roleName == data.CanonicalRootRole && rb.repo.Root != nil:
+ return rb.repo.Root.Signed.Version
+ case roleName == data.CanonicalSnapshotRole && rb.repo.Snapshot != nil:
+ return rb.repo.Snapshot.Signed.Version
+ case roleName == data.CanonicalTimestampRole && rb.repo.Timestamp != nil:
+ return rb.repo.Timestamp.Signed.Version
+ default:
+ if tgts, ok := rb.repo.Targets[roleName]; ok {
+ return tgts.Signed.Version
+ }
+ }
+
+ return 1
+}
+
+// GetConsistentInfo returns the consistent name and size of a role, if it is known,
+// otherwise just the rolename and a -1 for size (both of which are inside a
+// ConsistentInfo object)
+func (rb *repoBuilder) GetConsistentInfo(roleName string) ConsistentInfo {
+ info := ConsistentInfo{RoleName: roleName} // starts out with unknown filemeta
+ switch roleName {
+ case data.CanonicalTimestampRole:
+ // we do not want to get a consistent timestamp, but we do want to
+ // limit its size
+ info.fileMeta.Length = notary.MaxTimestampSize
+ case data.CanonicalSnapshotRole:
+ if rb.repo.Timestamp != nil {
+ info.fileMeta = rb.repo.Timestamp.Signed.Meta[roleName]
+ }
+ case data.CanonicalRootRole:
+ switch {
+ case rb.bootstrappedRootChecksum != nil:
+ info.fileMeta = *rb.bootstrappedRootChecksum
+ case rb.repo.Snapshot != nil:
+ info.fileMeta = rb.repo.Snapshot.Signed.Meta[roleName]
+ }
+ default:
+ if rb.repo.Snapshot != nil {
+ info.fileMeta = rb.repo.Snapshot.Signed.Meta[roleName]
+ }
+ }
+ return info
+}
+
+func (rb *repoBuilder) Load(roleName string, content []byte, minVersion int, allowExpired bool) error {
+ if !data.ValidRole(roleName) {
+ return ErrInvalidBuilderInput{msg: fmt.Sprintf("%s is an invalid role", roleName)}
+ }
+
+ if rb.IsLoaded(roleName) {
+ return ErrInvalidBuilderInput{msg: fmt.Sprintf("%s has already been loaded", roleName)}
+ }
+
+ var err error
+ switch roleName {
+ case data.CanonicalRootRole:
+ break
+ case data.CanonicalTimestampRole, data.CanonicalSnapshotRole, data.CanonicalTargetsRole:
+ err = rb.checkPrereqsLoaded([]string{data.CanonicalRootRole})
+ default: // delegations
+ err = rb.checkPrereqsLoaded([]string{data.CanonicalRootRole, data.CanonicalTargetsRole})
+ }
+ if err != nil {
+ return err
+ }
+
+ switch roleName {
+ case data.CanonicalRootRole:
+ return rb.loadRoot(content, minVersion, allowExpired)
+ case data.CanonicalSnapshotRole:
+ return rb.loadSnapshot(content, minVersion, allowExpired)
+ case data.CanonicalTimestampRole:
+ return rb.loadTimestamp(content, minVersion, allowExpired)
+ case data.CanonicalTargetsRole:
+ return rb.loadTargets(content, minVersion, allowExpired)
+ default:
+ return rb.loadDelegation(roleName, content, minVersion, allowExpired)
+ }
+}
+
+func (rb *repoBuilder) checkPrereqsLoaded(prereqRoles []string) error {
+ for _, req := range prereqRoles {
+ if !rb.IsLoaded(req) {
+ return ErrInvalidBuilderInput{msg: fmt.Sprintf("%s must be loaded first", req)}
+ }
+ }
+ return nil
+}
+
+// GenerateSnapshot generates a new snapshot given a previous (optional) snapshot
+// We can't just load the previous snapshot, because it may have been signed by a different
+// snapshot key (maybe from a previous root version). Note that we need the root role and
+// targets role to be loaded, because we need to generate metadata for both (and we need
+// the root to be loaded so we can get the snapshot role to sign with)
+func (rb *repoBuilder) GenerateSnapshot(prev *data.SignedSnapshot) ([]byte, int, error) {
+ switch {
+ case rb.repo.cryptoService == nil:
+ return nil, 0, ErrInvalidBuilderInput{msg: "cannot generate snapshot without a cryptoservice"}
+ case rb.IsLoaded(data.CanonicalSnapshotRole):
+ return nil, 0, ErrInvalidBuilderInput{msg: "snapshot has already been loaded"}
+ case rb.IsLoaded(data.CanonicalTimestampRole):
+ return nil, 0, ErrInvalidBuilderInput{msg: "cannot generate snapshot if timestamp has already been loaded"}
+ }
+
+ if err := rb.checkPrereqsLoaded([]string{data.CanonicalRootRole}); err != nil {
+ return nil, 0, err
+ }
+
+ // If there is no previous snapshot, we need to generate one, and so the targets must
+ // have already been loaded. Otherwise, so long as the previous snapshot structure is
+ // valid (it has a targets meta), we're good.
+ switch prev {
+ case nil:
+ if err := rb.checkPrereqsLoaded([]string{data.CanonicalTargetsRole}); err != nil {
+ return nil, 0, err
+ }
+
+ if err := rb.repo.InitSnapshot(); err != nil {
+ rb.repo.Snapshot = nil
+ return nil, 0, err
+ }
+ default:
+ if err := data.IsValidSnapshotStructure(prev.Signed); err != nil {
+ return nil, 0, err
+ }
+ rb.repo.Snapshot = prev
+ }
+
+ sgnd, err := rb.repo.SignSnapshot(data.DefaultExpires(data.CanonicalSnapshotRole))
+ if err != nil {
+ rb.repo.Snapshot = nil
+ return nil, 0, err
+ }
+
+ sgndJSON, err := json.Marshal(sgnd)
+ if err != nil {
+ rb.repo.Snapshot = nil
+ return nil, 0, err
+ }
+
+ // loadedNotChecksummed should currently contain the root awaiting checksumming,
+ // since it has to have been loaded. Since the snapshot was generated using
+ // the root and targets data (there may not be any) that that have been loaded,
+ // remove all of them from rb.loadedNotChecksummed
+ for tgtName := range rb.repo.Targets {
+ delete(rb.loadedNotChecksummed, tgtName)
+ }
+ delete(rb.loadedNotChecksummed, data.CanonicalRootRole)
+
+ // The timestamp can't have been loaded yet, so we want to cache the snapshot
+ // bytes so we can validate the checksum when a timestamp gets generated or
+ // loaded later.
+ rb.loadedNotChecksummed[data.CanonicalSnapshotRole] = sgndJSON
+
+ return sgndJSON, rb.repo.Snapshot.Signed.Version, nil
+}
+
+// GenerateTimestamp generates a new timestamp given a previous (optional) timestamp
+// We can't just load the previous timestamp, because it may have been signed by a different
+// timestamp key (maybe from a previous root version)
+func (rb *repoBuilder) GenerateTimestamp(prev *data.SignedTimestamp) ([]byte, int, error) {
+ switch {
+ case rb.repo.cryptoService == nil:
+ return nil, 0, ErrInvalidBuilderInput{msg: "cannot generate timestamp without a cryptoservice"}
+ case rb.IsLoaded(data.CanonicalTimestampRole):
+ return nil, 0, ErrInvalidBuilderInput{msg: "timestamp has already been loaded"}
+ }
+
+ // SignTimestamp always serializes the loaded snapshot and signs in the data, so we must always
+ // have the snapshot loaded first
+ if err := rb.checkPrereqsLoaded([]string{data.CanonicalRootRole, data.CanonicalSnapshotRole}); err != nil {
+ return nil, 0, err
+ }
+
+ switch prev {
+ case nil:
+ if err := rb.repo.InitTimestamp(); err != nil {
+ rb.repo.Timestamp = nil
+ return nil, 0, err
+ }
+ default:
+ if err := data.IsValidTimestampStructure(prev.Signed); err != nil {
+ return nil, 0, err
+ }
+ rb.repo.Timestamp = prev
+ }
+
+ sgnd, err := rb.repo.SignTimestamp(data.DefaultExpires(data.CanonicalTimestampRole))
+ if err != nil {
+ rb.repo.Timestamp = nil
+ return nil, 0, err
+ }
+
+ sgndJSON, err := json.Marshal(sgnd)
+ if err != nil {
+ rb.repo.Timestamp = nil
+ return nil, 0, err
+ }
+
+ // The snapshot should have been loaded (and not checksummed, since a timestamp
+ // cannot have been loaded), so it is awaiting checksumming. Since this
+ // timestamp was generated using the snapshot awaiting checksumming, we can
+ // remove it from rb.loadedNotChecksummed. There should be no other items
+ // awaiting checksumming now since loading/generating a snapshot should have
+ // cleared out everything else in `loadNotChecksummed`.
+ delete(rb.loadedNotChecksummed, data.CanonicalSnapshotRole)
+
+ return sgndJSON, rb.repo.Timestamp.Signed.Version, nil
+}
+
+// loadRoot loads a root if one has not been loaded
+func (rb *repoBuilder) loadRoot(content []byte, minVersion int, allowExpired bool) error {
+ roleName := data.CanonicalRootRole
+
+ signedObj, err := rb.bytesToSigned(content, data.CanonicalRootRole)
+ if err != nil {
+ return err
+ }
+ // ValidateRoot validates against the previous root's role, as well as validates that the root
+ // itself is self-consistent with its own signatures and thresholds.
+ // This assumes that ValidateRoot calls data.RootFromSigned, which validates
+ // the metadata, rather than just unmarshalling signedObject into a SignedRoot object itself.
+ signedRoot, err := trustpinning.ValidateRoot(rb.prevRoot, signedObj, rb.gun, rb.trustpin)
+ if err != nil {
+ return err
+ }
+
+ if err := signed.VerifyVersion(&(signedRoot.Signed.SignedCommon), minVersion); err != nil {
+ return err
+ }
+
+ if !allowExpired { // check must go at the end because all other validation should pass
+ if err := signed.VerifyExpiry(&(signedRoot.Signed.SignedCommon), roleName); err != nil {
+ return err
+ }
+ }
+
+ rootRole, err := signedRoot.BuildBaseRole(data.CanonicalRootRole)
+ if err != nil { // this should never happen since the root has been validated
+ return err
+ }
+ rb.repo.Root = signedRoot
+ rb.repo.originalRootRole = rootRole
+ return nil
+}
+
+func (rb *repoBuilder) loadTimestamp(content []byte, minVersion int, allowExpired bool) error {
+ roleName := data.CanonicalTimestampRole
+
+ timestampRole, err := rb.repo.Root.BuildBaseRole(roleName)
+ if err != nil { // this should never happen, since it's already been validated
+ return err
+ }
+
+ signedObj, err := rb.bytesToSignedAndValidateSigs(timestampRole, content)
+ if err != nil {
+ return err
+ }
+
+ signedTimestamp, err := data.TimestampFromSigned(signedObj)
+ if err != nil {
+ return err
+ }
+
+ if err := signed.VerifyVersion(&(signedTimestamp.Signed.SignedCommon), minVersion); err != nil {
+ return err
+ }
+
+ if !allowExpired { // check must go at the end because all other validation should pass
+ if err := signed.VerifyExpiry(&(signedTimestamp.Signed.SignedCommon), roleName); err != nil {
+ return err
+ }
+ }
+
+ if err := rb.validateChecksumsFromTimestamp(signedTimestamp); err != nil {
+ return err
+ }
+
+ rb.repo.Timestamp = signedTimestamp
+ return nil
+}
+
+func (rb *repoBuilder) loadSnapshot(content []byte, minVersion int, allowExpired bool) error {
+ roleName := data.CanonicalSnapshotRole
+
+ snapshotRole, err := rb.repo.Root.BuildBaseRole(roleName)
+ if err != nil { // this should never happen, since it's already been validated
+ return err
+ }
+
+ signedObj, err := rb.bytesToSignedAndValidateSigs(snapshotRole, content)
+ if err != nil {
+ return err
+ }
+
+ signedSnapshot, err := data.SnapshotFromSigned(signedObj)
+ if err != nil {
+ return err
+ }
+
+ if err := signed.VerifyVersion(&(signedSnapshot.Signed.SignedCommon), minVersion); err != nil {
+ return err
+ }
+
+ if !allowExpired { // check must go at the end because all other validation should pass
+ if err := signed.VerifyExpiry(&(signedSnapshot.Signed.SignedCommon), roleName); err != nil {
+ return err
+ }
+ }
+
+ // at this point, the only thing left to validate is existing checksums - we can use
+ // this snapshot to bootstrap the next builder if needed - and we don't need to do
+ // the 2-value assignment since we've already validated the signedSnapshot, which MUST
+ // have root metadata
+ rootMeta := signedSnapshot.Signed.Meta[data.CanonicalRootRole]
+ rb.nextRootChecksum = &rootMeta
+
+ if err := rb.validateChecksumsFromSnapshot(signedSnapshot); err != nil {
+ return err
+ }
+
+ rb.repo.Snapshot = signedSnapshot
+ return nil
+}
+
+func (rb *repoBuilder) loadTargets(content []byte, minVersion int, allowExpired bool) error {
+ roleName := data.CanonicalTargetsRole
+
+ targetsRole, err := rb.repo.Root.BuildBaseRole(roleName)
+ if err != nil { // this should never happen, since it's already been validated
+ return err
+ }
+
+ signedObj, err := rb.bytesToSignedAndValidateSigs(targetsRole, content)
+ if err != nil {
+ return err
+ }
+
+ signedTargets, err := data.TargetsFromSigned(signedObj, roleName)
+ if err != nil {
+ return err
+ }
+
+ if err := signed.VerifyVersion(&(signedTargets.Signed.SignedCommon), minVersion); err != nil {
+ return err
+ }
+
+ if !allowExpired { // check must go at the end because all other validation should pass
+ if err := signed.VerifyExpiry(&(signedTargets.Signed.SignedCommon), roleName); err != nil {
+ return err
+ }
+ }
+
+ signedTargets.Signatures = signedObj.Signatures
+ rb.repo.Targets[roleName] = signedTargets
+ return nil
+}
+
+func (rb *repoBuilder) loadDelegation(roleName string, content []byte, minVersion int, allowExpired bool) error {
+ delegationRole, err := rb.repo.GetDelegationRole(roleName)
+ if err != nil {
+ return err
+ }
+
+ // bytesToSigned checks checksum
+ signedObj, err := rb.bytesToSigned(content, roleName)
+ if err != nil {
+ return err
+ }
+
+ signedTargets, err := data.TargetsFromSigned(signedObj, roleName)
+ if err != nil {
+ return err
+ }
+
+ if err := signed.VerifyVersion(&(signedTargets.Signed.SignedCommon), minVersion); err != nil {
+ // don't capture in invalidRoles because the role we received is a rollback
+ return err
+ }
+
+ // verify signature
+ if err := signed.VerifySignatures(signedObj, delegationRole.BaseRole); err != nil {
+ rb.invalidRoles.Targets[roleName] = signedTargets
+ return err
+ }
+
+ if !allowExpired { // check must go at the end because all other validation should pass
+ if err := signed.VerifyExpiry(&(signedTargets.Signed.SignedCommon), roleName); err != nil {
+ rb.invalidRoles.Targets[roleName] = signedTargets
+ return err
+ }
+ }
+
+ signedTargets.Signatures = signedObj.Signatures
+ rb.repo.Targets[roleName] = signedTargets
+ return nil
+}
+
+func (rb *repoBuilder) validateChecksumsFromTimestamp(ts *data.SignedTimestamp) error {
+ sn, ok := rb.loadedNotChecksummed[data.CanonicalSnapshotRole]
+ if ok {
+ // by this point, the SignedTimestamp has been validated so it must have a snapshot hash
+ snMeta := ts.Signed.Meta[data.CanonicalSnapshotRole].Hashes
+ if err := data.CheckHashes(sn, data.CanonicalSnapshotRole, snMeta); err != nil {
+ return err
+ }
+ delete(rb.loadedNotChecksummed, data.CanonicalSnapshotRole)
+ }
+ return nil
+}
+
+func (rb *repoBuilder) validateChecksumsFromSnapshot(sn *data.SignedSnapshot) error {
+ var goodRoles []string
+ for roleName, loadedBytes := range rb.loadedNotChecksummed {
+ switch roleName {
+ case data.CanonicalSnapshotRole, data.CanonicalTimestampRole:
+ break
+ default:
+ if err := data.CheckHashes(loadedBytes, roleName, sn.Signed.Meta[roleName].Hashes); err != nil {
+ return err
+ }
+ goodRoles = append(goodRoles, roleName)
+ }
+ }
+ for _, roleName := range goodRoles {
+ delete(rb.loadedNotChecksummed, roleName)
+ }
+ return nil
+}
+
+func (rb *repoBuilder) validateChecksumFor(content []byte, roleName string) error {
+ // validate the bootstrap checksum for root, if provided
+ if roleName == data.CanonicalRootRole && rb.bootstrappedRootChecksum != nil {
+ if err := data.CheckHashes(content, roleName, rb.bootstrappedRootChecksum.Hashes); err != nil {
+ return err
+ }
+ }
+
+ // but we also want to cache the root content, so that when the snapshot is
+ // loaded it is validated (to make sure everything in the repo is self-consistent)
+ checksums := rb.getChecksumsFor(roleName)
+ if checksums != nil { // as opposed to empty, in which case hash check should fail
+ if err := data.CheckHashes(content, roleName, *checksums); err != nil {
+ return err
+ }
+ } else if roleName != data.CanonicalTimestampRole {
+ // timestamp is the only role which does not need to be checksummed, but
+ // for everything else, cache the contents in the list of roles that have
+ // not been checksummed by the snapshot/timestamp yet
+ rb.loadedNotChecksummed[roleName] = content
+ }
+
+ return nil
+}
+
+// Checksums the given bytes, and if they validate, convert to a data.Signed object.
+// If a checksums are nil (as opposed to empty), adds the bytes to the list of roles that
+// haven't been checksummed (unless it's a timestamp, which has no checksum reference).
+func (rb *repoBuilder) bytesToSigned(content []byte, roleName string) (*data.Signed, error) {
+ if err := rb.validateChecksumFor(content, roleName); err != nil {
+ return nil, err
+ }
+
+ // unmarshal to signed
+ signedObj := &data.Signed{}
+ if err := json.Unmarshal(content, signedObj); err != nil {
+ return nil, err
+ }
+
+ return signedObj, nil
+}
+
+func (rb *repoBuilder) bytesToSignedAndValidateSigs(role data.BaseRole, content []byte) (*data.Signed, error) {
+
+ signedObj, err := rb.bytesToSigned(content, role.Name)
+ if err != nil {
+ return nil, err
+ }
+
+ // verify signature
+ if err := signed.VerifySignatures(signedObj, role); err != nil {
+ return nil, err
+ }
+
+ return signedObj, nil
+}
+
+// If the checksum reference (the loaded timestamp for the snapshot role, and
+// the loaded snapshot for every other role except timestamp and snapshot) is nil,
+// then return nil for the checksums, meaning that the checksum is not yet
+// available. If the checksum reference *is* loaded, then always returns the
+// Hashes object for the given role - if it doesn't exist, returns an empty Hash
+// object (against which any checksum validation would fail).
+func (rb *repoBuilder) getChecksumsFor(role string) *data.Hashes {
+ var hashes data.Hashes
+ switch role {
+ case data.CanonicalTimestampRole:
+ return nil
+ case data.CanonicalSnapshotRole:
+ if rb.repo.Timestamp == nil {
+ return nil
+ }
+ hashes = rb.repo.Timestamp.Signed.Meta[data.CanonicalSnapshotRole].Hashes
+ default:
+ if rb.repo.Snapshot == nil {
+ return nil
+ }
+ hashes = rb.repo.Snapshot.Signed.Meta[role].Hashes
+ }
+ return &hashes
+}
diff --git a/vendor/github.com/docker/notary/tuf/data/errors.go b/vendor/github.com/docker/notary/tuf/data/errors.go
new file mode 100644
index 0000000..5c1397d
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/data/errors.go
@@ -0,0 +1,53 @@
+package data
+
+import "fmt"
+
+// ErrInvalidMetadata is the error to be returned when metadata is invalid
+type ErrInvalidMetadata struct {
+ role string
+ msg string
+}
+
+func (e ErrInvalidMetadata) Error() string {
+ return fmt.Sprintf("%s type metadata invalid: %s", e.role, e.msg)
+}
+
+// ErrMissingMeta - couldn't find the FileMeta object for the given Role, or
+// the FileMeta object contained no supported checksums
+type ErrMissingMeta struct {
+ Role string
+}
+
+func (e ErrMissingMeta) Error() string {
+ return fmt.Sprintf("no checksums for supported algorithms were provided for %s", e.Role)
+}
+
+// ErrInvalidChecksum is the error to be returned when checksum is invalid
+type ErrInvalidChecksum struct {
+ alg string
+}
+
+func (e ErrInvalidChecksum) Error() string {
+ return fmt.Sprintf("%s checksum invalid", e.alg)
+}
+
+// ErrMismatchedChecksum is the error to be returned when checksum is mismatched
+type ErrMismatchedChecksum struct {
+ alg string
+ name string
+ expected string
+}
+
+func (e ErrMismatchedChecksum) Error() string {
+ return fmt.Sprintf("%s checksum for %s did not match: expected %s", e.alg, e.name,
+ e.expected)
+}
+
+// ErrCertExpired is the error to be returned when a certificate has expired
+type ErrCertExpired struct {
+ CN string
+}
+
+func (e ErrCertExpired) Error() string {
+ return fmt.Sprintf("certificate with CN %s is expired", e.CN)
+}
diff --git a/vendor/github.com/docker/notary/tuf/data/keys.go b/vendor/github.com/docker/notary/tuf/data/keys.go
new file mode 100644
index 0000000..25df598
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/data/keys.go
@@ -0,0 +1,528 @@
+package data
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/rsa"
+ "crypto/sha256"
+ "crypto/x509"
+ "encoding/asn1"
+ "encoding/hex"
+ "errors"
+ "io"
+ "math/big"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/agl/ed25519"
+ "github.com/docker/go/canonical/json"
+)
+
+// PublicKey is the necessary interface for public keys
+type PublicKey interface {
+ ID() string
+ Algorithm() string
+ Public() []byte
+}
+
+// PrivateKey adds the ability to access the private key
+type PrivateKey interface {
+ PublicKey
+ Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error)
+ Private() []byte
+ CryptoSigner() crypto.Signer
+ SignatureAlgorithm() SigAlgorithm
+}
+
+// KeyPair holds the public and private key bytes
+type KeyPair struct {
+ Public []byte `json:"public"`
+ Private []byte `json:"private"`
+}
+
+// Keys represents a map of key ID to PublicKey object. It's necessary
+// to allow us to unmarshal into an interface via the json.Unmarshaller
+// interface
+type Keys map[string]PublicKey
+
+// UnmarshalJSON implements the json.Unmarshaller interface
+func (ks *Keys) UnmarshalJSON(data []byte) error {
+ parsed := make(map[string]TUFKey)
+ err := json.Unmarshal(data, &parsed)
+ if err != nil {
+ return err
+ }
+ final := make(map[string]PublicKey)
+ for k, tk := range parsed {
+ final[k] = typedPublicKey(tk)
+ }
+ *ks = final
+ return nil
+}
+
+// KeyList represents a list of keys
+type KeyList []PublicKey
+
+// UnmarshalJSON implements the json.Unmarshaller interface
+func (ks *KeyList) UnmarshalJSON(data []byte) error {
+ parsed := make([]TUFKey, 0, 1)
+ err := json.Unmarshal(data, &parsed)
+ if err != nil {
+ return err
+ }
+ final := make([]PublicKey, 0, len(parsed))
+ for _, tk := range parsed {
+ final = append(final, typedPublicKey(tk))
+ }
+ *ks = final
+ return nil
+}
+
+// IDs generates a list of the hex encoded key IDs in the KeyList
+func (ks KeyList) IDs() []string {
+ keyIDs := make([]string, 0, len(ks))
+ for _, k := range ks {
+ keyIDs = append(keyIDs, k.ID())
+ }
+ return keyIDs
+}
+
+func typedPublicKey(tk TUFKey) PublicKey {
+ switch tk.Algorithm() {
+ case ECDSAKey:
+ return &ECDSAPublicKey{TUFKey: tk}
+ case ECDSAx509Key:
+ return &ECDSAx509PublicKey{TUFKey: tk}
+ case RSAKey:
+ return &RSAPublicKey{TUFKey: tk}
+ case RSAx509Key:
+ return &RSAx509PublicKey{TUFKey: tk}
+ case ED25519Key:
+ return &ED25519PublicKey{TUFKey: tk}
+ }
+ return &UnknownPublicKey{TUFKey: tk}
+}
+
+func typedPrivateKey(tk TUFKey) (PrivateKey, error) {
+ private := tk.Value.Private
+ tk.Value.Private = nil
+ switch tk.Algorithm() {
+ case ECDSAKey:
+ return NewECDSAPrivateKey(
+ &ECDSAPublicKey{
+ TUFKey: tk,
+ },
+ private,
+ )
+ case ECDSAx509Key:
+ return NewECDSAPrivateKey(
+ &ECDSAx509PublicKey{
+ TUFKey: tk,
+ },
+ private,
+ )
+ case RSAKey:
+ return NewRSAPrivateKey(
+ &RSAPublicKey{
+ TUFKey: tk,
+ },
+ private,
+ )
+ case RSAx509Key:
+ return NewRSAPrivateKey(
+ &RSAx509PublicKey{
+ TUFKey: tk,
+ },
+ private,
+ )
+ case ED25519Key:
+ return NewED25519PrivateKey(
+ ED25519PublicKey{
+ TUFKey: tk,
+ },
+ private,
+ )
+ }
+ return &UnknownPrivateKey{
+ TUFKey: tk,
+ privateKey: privateKey{private: private},
+ }, nil
+}
+
+// NewPublicKey creates a new, correctly typed PublicKey, using the
+// UnknownPublicKey catchall for unsupported ciphers
+func NewPublicKey(alg string, public []byte) PublicKey {
+ tk := TUFKey{
+ Type: alg,
+ Value: KeyPair{
+ Public: public,
+ },
+ }
+ return typedPublicKey(tk)
+}
+
+// NewPrivateKey creates a new, correctly typed PrivateKey, using the
+// UnknownPrivateKey catchall for unsupported ciphers
+func NewPrivateKey(pubKey PublicKey, private []byte) (PrivateKey, error) {
+ tk := TUFKey{
+ Type: pubKey.Algorithm(),
+ Value: KeyPair{
+ Public: pubKey.Public(),
+ Private: private, // typedPrivateKey moves this value
+ },
+ }
+ return typedPrivateKey(tk)
+}
+
+// UnmarshalPublicKey is used to parse individual public keys in JSON
+func UnmarshalPublicKey(data []byte) (PublicKey, error) {
+ var parsed TUFKey
+ err := json.Unmarshal(data, &parsed)
+ if err != nil {
+ return nil, err
+ }
+ return typedPublicKey(parsed), nil
+}
+
+// UnmarshalPrivateKey is used to parse individual private keys in JSON
+func UnmarshalPrivateKey(data []byte) (PrivateKey, error) {
+ var parsed TUFKey
+ err := json.Unmarshal(data, &parsed)
+ if err != nil {
+ return nil, err
+ }
+ return typedPrivateKey(parsed)
+}
+
+// TUFKey is the structure used for both public and private keys in TUF.
+// Normally it would make sense to use a different structures for public and
+// private keys, but that would change the key ID algorithm (since the canonical
+// JSON would be different). This structure should normally be accessed through
+// the PublicKey or PrivateKey interfaces.
+type TUFKey struct {
+ id string
+ Type string `json:"keytype"`
+ Value KeyPair `json:"keyval"`
+}
+
+// Algorithm returns the algorithm of the key
+func (k TUFKey) Algorithm() string {
+ return k.Type
+}
+
+// ID efficiently generates if necessary, and caches the ID of the key
+func (k *TUFKey) ID() string {
+ if k.id == "" {
+ pubK := TUFKey{
+ Type: k.Algorithm(),
+ Value: KeyPair{
+ Public: k.Public(),
+ Private: nil,
+ },
+ }
+ data, err := json.MarshalCanonical(&pubK)
+ if err != nil {
+ logrus.Error("Error generating key ID:", err)
+ }
+ digest := sha256.Sum256(data)
+ k.id = hex.EncodeToString(digest[:])
+ }
+ return k.id
+}
+
+// Public returns the public bytes
+func (k TUFKey) Public() []byte {
+ return k.Value.Public
+}
+
+// Public key types
+
+// ECDSAPublicKey represents an ECDSA key using a raw serialization
+// of the public key
+type ECDSAPublicKey struct {
+ TUFKey
+}
+
+// ECDSAx509PublicKey represents an ECDSA key using an x509 cert
+// as the serialized format of the public key
+type ECDSAx509PublicKey struct {
+ TUFKey
+}
+
+// RSAPublicKey represents an RSA key using a raw serialization
+// of the public key
+type RSAPublicKey struct {
+ TUFKey
+}
+
+// RSAx509PublicKey represents an RSA key using an x509 cert
+// as the serialized format of the public key
+type RSAx509PublicKey struct {
+ TUFKey
+}
+
+// ED25519PublicKey represents an ED25519 key using a raw serialization
+// of the public key
+type ED25519PublicKey struct {
+ TUFKey
+}
+
+// UnknownPublicKey is a catchall for key types that are not supported
+type UnknownPublicKey struct {
+ TUFKey
+}
+
+// NewECDSAPublicKey initializes a new public key with the ECDSAKey type
+func NewECDSAPublicKey(public []byte) *ECDSAPublicKey {
+ return &ECDSAPublicKey{
+ TUFKey: TUFKey{
+ Type: ECDSAKey,
+ Value: KeyPair{
+ Public: public,
+ Private: nil,
+ },
+ },
+ }
+}
+
+// NewECDSAx509PublicKey initializes a new public key with the ECDSAx509Key type
+func NewECDSAx509PublicKey(public []byte) *ECDSAx509PublicKey {
+ return &ECDSAx509PublicKey{
+ TUFKey: TUFKey{
+ Type: ECDSAx509Key,
+ Value: KeyPair{
+ Public: public,
+ Private: nil,
+ },
+ },
+ }
+}
+
+// NewRSAPublicKey initializes a new public key with the RSA type
+func NewRSAPublicKey(public []byte) *RSAPublicKey {
+ return &RSAPublicKey{
+ TUFKey: TUFKey{
+ Type: RSAKey,
+ Value: KeyPair{
+ Public: public,
+ Private: nil,
+ },
+ },
+ }
+}
+
+// NewRSAx509PublicKey initializes a new public key with the RSAx509Key type
+func NewRSAx509PublicKey(public []byte) *RSAx509PublicKey {
+ return &RSAx509PublicKey{
+ TUFKey: TUFKey{
+ Type: RSAx509Key,
+ Value: KeyPair{
+ Public: public,
+ Private: nil,
+ },
+ },
+ }
+}
+
+// NewED25519PublicKey initializes a new public key with the ED25519Key type
+func NewED25519PublicKey(public []byte) *ED25519PublicKey {
+ return &ED25519PublicKey{
+ TUFKey: TUFKey{
+ Type: ED25519Key,
+ Value: KeyPair{
+ Public: public,
+ Private: nil,
+ },
+ },
+ }
+}
+
+// Private key types
+type privateKey struct {
+ private []byte
+}
+
+type signer struct {
+ signer crypto.Signer
+}
+
+// ECDSAPrivateKey represents a private ECDSA key
+type ECDSAPrivateKey struct {
+ PublicKey
+ privateKey
+ signer
+}
+
+// RSAPrivateKey represents a private RSA key
+type RSAPrivateKey struct {
+ PublicKey
+ privateKey
+ signer
+}
+
+// ED25519PrivateKey represents a private ED25519 key
+type ED25519PrivateKey struct {
+ ED25519PublicKey
+ privateKey
+}
+
+// UnknownPrivateKey is a catchall for unsupported key types
+type UnknownPrivateKey struct {
+ TUFKey
+ privateKey
+}
+
+// NewECDSAPrivateKey initializes a new ECDSA private key
+func NewECDSAPrivateKey(public PublicKey, private []byte) (*ECDSAPrivateKey, error) {
+ switch public.(type) {
+ case *ECDSAPublicKey, *ECDSAx509PublicKey:
+ default:
+ return nil, errors.New("Invalid public key type provided to NewECDSAPrivateKey")
+ }
+ ecdsaPrivKey, err := x509.ParseECPrivateKey(private)
+ if err != nil {
+ return nil, err
+ }
+ return &ECDSAPrivateKey{
+ PublicKey: public,
+ privateKey: privateKey{private: private},
+ signer: signer{signer: ecdsaPrivKey},
+ }, nil
+}
+
+// NewRSAPrivateKey initialized a new RSA private key
+func NewRSAPrivateKey(public PublicKey, private []byte) (*RSAPrivateKey, error) {
+ switch public.(type) {
+ case *RSAPublicKey, *RSAx509PublicKey:
+ default:
+ return nil, errors.New("Invalid public key type provided to NewRSAPrivateKey")
+ }
+ rsaPrivKey, err := x509.ParsePKCS1PrivateKey(private)
+ if err != nil {
+ return nil, err
+ }
+ return &RSAPrivateKey{
+ PublicKey: public,
+ privateKey: privateKey{private: private},
+ signer: signer{signer: rsaPrivKey},
+ }, nil
+}
+
+// NewED25519PrivateKey initialized a new ED25519 private key
+func NewED25519PrivateKey(public ED25519PublicKey, private []byte) (*ED25519PrivateKey, error) {
+ return &ED25519PrivateKey{
+ ED25519PublicKey: public,
+ privateKey: privateKey{private: private},
+ }, nil
+}
+
+// Private return the serialized private bytes of the key
+func (k privateKey) Private() []byte {
+ return k.private
+}
+
+// CryptoSigner returns the underlying crypto.Signer for use cases where we need the default
+// signature or public key functionality (like when we generate certificates)
+func (s signer) CryptoSigner() crypto.Signer {
+ return s.signer
+}
+
+// CryptoSigner returns the ED25519PrivateKey which already implements crypto.Signer
+func (k ED25519PrivateKey) CryptoSigner() crypto.Signer {
+ return nil
+}
+
+// CryptoSigner returns the UnknownPrivateKey which already implements crypto.Signer
+func (k UnknownPrivateKey) CryptoSigner() crypto.Signer {
+ return nil
+}
+
+type ecdsaSig struct {
+ R *big.Int
+ S *big.Int
+}
+
+// Sign creates an ecdsa signature
+func (k ECDSAPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
+ ecdsaPrivKey, ok := k.CryptoSigner().(*ecdsa.PrivateKey)
+ if !ok {
+ return nil, errors.New("Signer was based on the wrong key type")
+ }
+ hashed := sha256.Sum256(msg)
+ sigASN1, err := ecdsaPrivKey.Sign(rand, hashed[:], opts)
+ if err != nil {
+ return nil, err
+ }
+
+ sig := ecdsaSig{}
+ _, err = asn1.Unmarshal(sigASN1, &sig)
+ if err != nil {
+ return nil, err
+ }
+ rBytes, sBytes := sig.R.Bytes(), sig.S.Bytes()
+ octetLength := (ecdsaPrivKey.Params().BitSize + 7) >> 3
+
+ // MUST include leading zeros in the output
+ rBuf := make([]byte, octetLength-len(rBytes), octetLength)
+ sBuf := make([]byte, octetLength-len(sBytes), octetLength)
+
+ rBuf = append(rBuf, rBytes...)
+ sBuf = append(sBuf, sBytes...)
+ return append(rBuf, sBuf...), nil
+}
+
+// Sign creates an rsa signature
+func (k RSAPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
+ hashed := sha256.Sum256(msg)
+ if opts == nil {
+ opts = &rsa.PSSOptions{
+ SaltLength: rsa.PSSSaltLengthEqualsHash,
+ Hash: crypto.SHA256,
+ }
+ }
+ return k.CryptoSigner().Sign(rand, hashed[:], opts)
+}
+
+// Sign creates an ed25519 signature
+func (k ED25519PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
+ priv := [ed25519.PrivateKeySize]byte{}
+ copy(priv[:], k.private[ed25519.PublicKeySize:])
+ return ed25519.Sign(&priv, msg)[:], nil
+}
+
+// Sign on an UnknownPrivateKey raises an error because the client does not
+// know how to sign with this key type.
+func (k UnknownPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
+ return nil, errors.New("Unknown key type, cannot sign.")
+}
+
+// SignatureAlgorithm returns the SigAlgorithm for a ECDSAPrivateKey
+func (k ECDSAPrivateKey) SignatureAlgorithm() SigAlgorithm {
+ return ECDSASignature
+}
+
+// SignatureAlgorithm returns the SigAlgorithm for a RSAPrivateKey
+func (k RSAPrivateKey) SignatureAlgorithm() SigAlgorithm {
+ return RSAPSSSignature
+}
+
+// SignatureAlgorithm returns the SigAlgorithm for a ED25519PrivateKey
+func (k ED25519PrivateKey) SignatureAlgorithm() SigAlgorithm {
+ return EDDSASignature
+}
+
+// SignatureAlgorithm returns the SigAlgorithm for an UnknownPrivateKey
+func (k UnknownPrivateKey) SignatureAlgorithm() SigAlgorithm {
+ return ""
+}
+
+// PublicKeyFromPrivate returns a new TUFKey based on a private key, with
+// the private key bytes guaranteed to be nil.
+func PublicKeyFromPrivate(pk PrivateKey) PublicKey {
+ return typedPublicKey(TUFKey{
+ Type: pk.Algorithm(),
+ Value: KeyPair{
+ Public: pk.Public(),
+ Private: nil,
+ },
+ })
+}
diff --git a/vendor/github.com/docker/notary/tuf/data/roles.go b/vendor/github.com/docker/notary/tuf/data/roles.go
new file mode 100644
index 0000000..2823778
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/data/roles.go
@@ -0,0 +1,338 @@
+package data
+
+import (
+ "fmt"
+ "path"
+ "regexp"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+)
+
+// Canonical base role names
+const (
+ CanonicalRootRole = "root"
+ CanonicalTargetsRole = "targets"
+ CanonicalSnapshotRole = "snapshot"
+ CanonicalTimestampRole = "timestamp"
+)
+
+// BaseRoles is an easy to iterate list of the top level
+// roles.
+var BaseRoles = []string{
+ CanonicalRootRole,
+ CanonicalTargetsRole,
+ CanonicalSnapshotRole,
+ CanonicalTimestampRole,
+}
+
+// Regex for validating delegation names
+var delegationRegexp = regexp.MustCompile("^[-a-z0-9_/]+$")
+
+// ErrNoSuchRole indicates the roles doesn't exist
+type ErrNoSuchRole struct {
+ Role string
+}
+
+func (e ErrNoSuchRole) Error() string {
+ return fmt.Sprintf("role does not exist: %s", e.Role)
+}
+
+// ErrInvalidRole represents an error regarding a role. Typically
+// something like a role for which sone of the public keys were
+// not found in the TUF repo.
+type ErrInvalidRole struct {
+ Role string
+ Reason string
+}
+
+func (e ErrInvalidRole) Error() string {
+ if e.Reason != "" {
+ return fmt.Sprintf("tuf: invalid role %s. %s", e.Role, e.Reason)
+ }
+ return fmt.Sprintf("tuf: invalid role %s.", e.Role)
+}
+
+// ValidRole only determines the name is semantically
+// correct. For target delegated roles, it does NOT check
+// the the appropriate parent roles exist.
+func ValidRole(name string) bool {
+ if IsDelegation(name) {
+ return true
+ }
+
+ for _, v := range BaseRoles {
+ if name == v {
+ return true
+ }
+ }
+ return false
+}
+
+// IsDelegation checks if the role is a delegation or a root role
+func IsDelegation(role string) bool {
+ targetsBase := CanonicalTargetsRole + "/"
+
+ whitelistedChars := delegationRegexp.MatchString(role)
+
+ // Limit size of full role string to 255 chars for db column size limit
+ correctLength := len(role) < 256
+
+ // Removes ., .., extra slashes, and trailing slash
+ isClean := path.Clean(role) == role
+ return strings.HasPrefix(role, targetsBase) &&
+ whitelistedChars &&
+ correctLength &&
+ isClean
+}
+
+// IsBaseRole checks if the role is a base role
+func IsBaseRole(role string) bool {
+ for _, baseRole := range BaseRoles {
+ if role == baseRole {
+ return true
+ }
+ }
+ return false
+}
+
+// IsWildDelegation determines if a role represents a valid wildcard delegation
+// path, i.e. targets/*, targets/foo/*.
+// The wildcard may only appear as the final part of the delegation and must
+// be a whole segment, i.e. targets/foo* is not a valid wildcard delegation.
+func IsWildDelegation(role string) bool {
+ if path.Clean(role) != role {
+ return false
+ }
+ base := path.Dir(role)
+ if !(IsDelegation(base) || base == CanonicalTargetsRole) {
+ return false
+ }
+ return role[len(role)-2:] == "/*"
+}
+
+// BaseRole is an internal representation of a root/targets/snapshot/timestamp role, with its public keys included
+type BaseRole struct {
+ Keys map[string]PublicKey
+ Name string
+ Threshold int
+}
+
+// NewBaseRole creates a new BaseRole object with the provided parameters
+func NewBaseRole(name string, threshold int, keys ...PublicKey) BaseRole {
+ r := BaseRole{
+ Name: name,
+ Threshold: threshold,
+ Keys: make(map[string]PublicKey),
+ }
+ for _, k := range keys {
+ r.Keys[k.ID()] = k
+ }
+ return r
+}
+
+// ListKeys retrieves the public keys valid for this role
+func (b BaseRole) ListKeys() KeyList {
+ return listKeys(b.Keys)
+}
+
+// ListKeyIDs retrieves the list of key IDs valid for this role
+func (b BaseRole) ListKeyIDs() []string {
+ return listKeyIDs(b.Keys)
+}
+
+// Equals returns whether this BaseRole equals another BaseRole
+func (b BaseRole) Equals(o BaseRole) bool {
+ if b.Threshold != o.Threshold || b.Name != o.Name || len(b.Keys) != len(o.Keys) {
+ return false
+ }
+
+ for keyID, key := range b.Keys {
+ oKey, ok := o.Keys[keyID]
+ if !ok || key.ID() != oKey.ID() {
+ return false
+ }
+ }
+
+ return true
+}
+
+// DelegationRole is an internal representation of a delegation role, with its public keys included
+type DelegationRole struct {
+ BaseRole
+ Paths []string
+}
+
+func listKeys(keyMap map[string]PublicKey) KeyList {
+ keys := KeyList{}
+ for _, key := range keyMap {
+ keys = append(keys, key)
+ }
+ return keys
+}
+
+func listKeyIDs(keyMap map[string]PublicKey) []string {
+ keyIDs := []string{}
+ for id := range keyMap {
+ keyIDs = append(keyIDs, id)
+ }
+ return keyIDs
+}
+
+// Restrict restricts the paths and path hash prefixes for the passed in delegation role,
+// returning a copy of the role with validated paths as if it was a direct child
+func (d DelegationRole) Restrict(child DelegationRole) (DelegationRole, error) {
+ if !d.IsParentOf(child) {
+ return DelegationRole{}, fmt.Errorf("%s is not a parent of %s", d.Name, child.Name)
+ }
+ return DelegationRole{
+ BaseRole: BaseRole{
+ Keys: child.Keys,
+ Name: child.Name,
+ Threshold: child.Threshold,
+ },
+ Paths: RestrictDelegationPathPrefixes(d.Paths, child.Paths),
+ }, nil
+}
+
+// IsParentOf returns whether the passed in delegation role is the direct child of this role,
+// determined by delegation name.
+// Ex: targets/a is a direct parent of targets/a/b, but targets/a is not a direct parent of targets/a/b/c
+func (d DelegationRole) IsParentOf(child DelegationRole) bool {
+ return path.Dir(child.Name) == d.Name
+}
+
+// CheckPaths checks if a given path is valid for the role
+func (d DelegationRole) CheckPaths(path string) bool {
+ return checkPaths(path, d.Paths)
+}
+
+func checkPaths(path string, permitted []string) bool {
+ for _, p := range permitted {
+ if strings.HasPrefix(path, p) {
+ return true
+ }
+ }
+ return false
+}
+
+// RestrictDelegationPathPrefixes returns the list of valid delegationPaths that are prefixed by parentPaths
+func RestrictDelegationPathPrefixes(parentPaths, delegationPaths []string) []string {
+ validPaths := []string{}
+ if len(delegationPaths) == 0 {
+ return validPaths
+ }
+
+ // Validate each individual delegation path
+ for _, delgPath := range delegationPaths {
+ isPrefixed := false
+ for _, parentPath := range parentPaths {
+ if strings.HasPrefix(delgPath, parentPath) {
+ isPrefixed = true
+ break
+ }
+ }
+ // If the delegation path did not match prefix against any parent path, it is not valid
+ if isPrefixed {
+ validPaths = append(validPaths, delgPath)
+ }
+ }
+ return validPaths
+}
+
+// RootRole is a cut down role as it appears in the root.json
+// Eventually should only be used for immediately before and after serialization/deserialization
+type RootRole struct {
+ KeyIDs []string `json:"keyids"`
+ Threshold int `json:"threshold"`
+}
+
+// Role is a more verbose role as they appear in targets delegations
+// Eventually should only be used for immediately before and after serialization/deserialization
+type Role struct {
+ RootRole
+ Name string `json:"name"`
+ Paths []string `json:"paths,omitempty"`
+}
+
+// NewRole creates a new Role object from the given parameters
+func NewRole(name string, threshold int, keyIDs, paths []string) (*Role, error) {
+ if IsDelegation(name) {
+ if len(paths) == 0 {
+ logrus.Debugf("role %s with no Paths will never be able to publish content until one or more are added", name)
+ }
+ }
+ if threshold < 1 {
+ return nil, ErrInvalidRole{Role: name}
+ }
+ if !ValidRole(name) {
+ return nil, ErrInvalidRole{Role: name}
+ }
+ return &Role{
+ RootRole: RootRole{
+ KeyIDs: keyIDs,
+ Threshold: threshold,
+ },
+ Name: name,
+ Paths: paths,
+ }, nil
+
+}
+
+// CheckPaths checks if a given path is valid for the role
+func (r Role) CheckPaths(path string) bool {
+ return checkPaths(path, r.Paths)
+}
+
+// AddKeys merges the ids into the current list of role key ids
+func (r *Role) AddKeys(ids []string) {
+ r.KeyIDs = mergeStrSlices(r.KeyIDs, ids)
+}
+
+// AddPaths merges the paths into the current list of role paths
+func (r *Role) AddPaths(paths []string) error {
+ if len(paths) == 0 {
+ return nil
+ }
+ r.Paths = mergeStrSlices(r.Paths, paths)
+ return nil
+}
+
+// RemoveKeys removes the ids from the current list of key ids
+func (r *Role) RemoveKeys(ids []string) {
+ r.KeyIDs = subtractStrSlices(r.KeyIDs, ids)
+}
+
+// RemovePaths removes the paths from the current list of role paths
+func (r *Role) RemovePaths(paths []string) {
+ r.Paths = subtractStrSlices(r.Paths, paths)
+}
+
+func mergeStrSlices(orig, new []string) []string {
+ have := make(map[string]bool)
+ for _, e := range orig {
+ have[e] = true
+ }
+ merged := make([]string, len(orig), len(orig)+len(new))
+ copy(merged, orig)
+ for _, e := range new {
+ if !have[e] {
+ merged = append(merged, e)
+ }
+ }
+ return merged
+}
+
+func subtractStrSlices(orig, remove []string) []string {
+ kill := make(map[string]bool)
+ for _, e := range remove {
+ kill[e] = true
+ }
+ var keep []string
+ for _, e := range orig {
+ if !kill[e] {
+ keep = append(keep, e)
+ }
+ }
+ return keep
+}
diff --git a/vendor/github.com/docker/notary/tuf/data/root.go b/vendor/github.com/docker/notary/tuf/data/root.go
new file mode 100644
index 0000000..cfadbdb
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/data/root.go
@@ -0,0 +1,171 @@
+package data
+
+import (
+ "fmt"
+
+ "github.com/docker/go/canonical/json"
+)
+
+// SignedRoot is a fully unpacked root.json
+type SignedRoot struct {
+ Signatures []Signature
+ Signed Root
+ Dirty bool
+}
+
+// Root is the Signed component of a root.json
+type Root struct {
+ SignedCommon
+ Keys Keys `json:"keys"`
+ Roles map[string]*RootRole `json:"roles"`
+ ConsistentSnapshot bool `json:"consistent_snapshot"`
+}
+
+// isValidRootStructure returns an error, or nil, depending on whether the content of the struct
+// is valid for root metadata. This does not check signatures or expiry, just that
+// the metadata content is valid.
+func isValidRootStructure(r Root) error {
+ expectedType := TUFTypes[CanonicalRootRole]
+ if r.Type != expectedType {
+ return ErrInvalidMetadata{
+ role: CanonicalRootRole, msg: fmt.Sprintf("expected type %s, not %s", expectedType, r.Type)}
+ }
+
+ if r.Version < 1 {
+ return ErrInvalidMetadata{
+ role: CanonicalRootRole, msg: "version cannot be less than 1"}
+ }
+
+ // all the base roles MUST appear in the root.json - other roles are allowed,
+ // but other than the mirror role (not currently supported) are out of spec
+ for _, roleName := range BaseRoles {
+ roleObj, ok := r.Roles[roleName]
+ if !ok || roleObj == nil {
+ return ErrInvalidMetadata{
+ role: CanonicalRootRole, msg: fmt.Sprintf("missing %s role specification", roleName)}
+ }
+ if err := isValidRootRoleStructure(CanonicalRootRole, roleName, *roleObj, r.Keys); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func isValidRootRoleStructure(metaContainingRole, rootRoleName string, r RootRole, validKeys Keys) error {
+ if r.Threshold < 1 {
+ return ErrInvalidMetadata{
+ role: metaContainingRole,
+ msg: fmt.Sprintf("invalid threshold specified for %s: %v ", rootRoleName, r.Threshold),
+ }
+ }
+ for _, keyID := range r.KeyIDs {
+ if _, ok := validKeys[keyID]; !ok {
+ return ErrInvalidMetadata{
+ role: metaContainingRole,
+ msg: fmt.Sprintf("key ID %s specified in %s without corresponding key", keyID, rootRoleName),
+ }
+ }
+ }
+ return nil
+}
+
+// NewRoot initializes a new SignedRoot with a set of keys, roles, and the consistent flag
+func NewRoot(keys map[string]PublicKey, roles map[string]*RootRole, consistent bool) (*SignedRoot, error) {
+ signedRoot := &SignedRoot{
+ Signatures: make([]Signature, 0),
+ Signed: Root{
+ SignedCommon: SignedCommon{
+ Type: TUFTypes[CanonicalRootRole],
+ Version: 0,
+ Expires: DefaultExpires(CanonicalRootRole),
+ },
+ Keys: keys,
+ Roles: roles,
+ ConsistentSnapshot: consistent,
+ },
+ Dirty: true,
+ }
+
+ return signedRoot, nil
+}
+
+// BuildBaseRole returns a copy of a BaseRole using the information in this SignedRoot for the specified role name.
+// Will error for invalid role name or key metadata within this SignedRoot
+func (r SignedRoot) BuildBaseRole(roleName string) (BaseRole, error) {
+ roleData, ok := r.Signed.Roles[roleName]
+ if !ok {
+ return BaseRole{}, ErrInvalidRole{Role: roleName, Reason: "role not found in root file"}
+ }
+ // Get all public keys for the base role from TUF metadata
+ keyIDs := roleData.KeyIDs
+ pubKeys := make(map[string]PublicKey)
+ for _, keyID := range keyIDs {
+ pubKey, ok := r.Signed.Keys[keyID]
+ if !ok {
+ return BaseRole{}, ErrInvalidRole{
+ Role: roleName,
+ Reason: fmt.Sprintf("key with ID %s was not found in root metadata", keyID),
+ }
+ }
+ pubKeys[keyID] = pubKey
+ }
+
+ return BaseRole{
+ Name: roleName,
+ Keys: pubKeys,
+ Threshold: roleData.Threshold,
+ }, nil
+}
+
+// ToSigned partially serializes a SignedRoot for further signing
+func (r SignedRoot) ToSigned() (*Signed, error) {
+ s, err := defaultSerializer.MarshalCanonical(r.Signed)
+ if err != nil {
+ return nil, err
+ }
+ // cast into a json.RawMessage
+ signed := json.RawMessage{}
+ err = signed.UnmarshalJSON(s)
+ if err != nil {
+ return nil, err
+ }
+ sigs := make([]Signature, len(r.Signatures))
+ copy(sigs, r.Signatures)
+ return &Signed{
+ Signatures: sigs,
+ Signed: &signed,
+ }, nil
+}
+
+// MarshalJSON returns the serialized form of SignedRoot as bytes
+func (r SignedRoot) MarshalJSON() ([]byte, error) {
+ signed, err := r.ToSigned()
+ if err != nil {
+ return nil, err
+ }
+ return defaultSerializer.Marshal(signed)
+}
+
+// RootFromSigned fully unpacks a Signed object into a SignedRoot and ensures
+// that it is a valid SignedRoot
+func RootFromSigned(s *Signed) (*SignedRoot, error) {
+ r := Root{}
+ if s.Signed == nil {
+ return nil, ErrInvalidMetadata{
+ role: CanonicalRootRole,
+ msg: "root file contained an empty payload",
+ }
+ }
+ if err := defaultSerializer.Unmarshal(*s.Signed, &r); err != nil {
+ return nil, err
+ }
+ if err := isValidRootStructure(r); err != nil {
+ return nil, err
+ }
+ sigs := make([]Signature, len(s.Signatures))
+ copy(sigs, s.Signatures)
+ return &SignedRoot{
+ Signatures: sigs,
+ Signed: r,
+ }, nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/data/serializer.go b/vendor/github.com/docker/notary/tuf/data/serializer.go
new file mode 100644
index 0000000..5c33d12
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/data/serializer.go
@@ -0,0 +1,36 @@
+package data
+
+import "github.com/docker/go/canonical/json"
+
+// Serializer is an interface that can marshal and unmarshal TUF data. This
+// is expected to be a canonical JSON marshaller
+type serializer interface {
+ MarshalCanonical(from interface{}) ([]byte, error)
+ Marshal(from interface{}) ([]byte, error)
+ Unmarshal(from []byte, to interface{}) error
+}
+
+// CanonicalJSON marshals to and from canonical JSON
+type canonicalJSON struct{}
+
+// MarshalCanonical returns the canonical JSON form of a thing
+func (c canonicalJSON) MarshalCanonical(from interface{}) ([]byte, error) {
+ return json.MarshalCanonical(from)
+}
+
+// Marshal returns the regular non-canonical JSON form of a thing
+func (c canonicalJSON) Marshal(from interface{}) ([]byte, error) {
+ return json.Marshal(from)
+}
+
+// Unmarshal unmarshals some JSON bytes
+func (c canonicalJSON) Unmarshal(from []byte, to interface{}) error {
+ return json.Unmarshal(from, to)
+}
+
+// defaultSerializer is a canonical JSON serializer
+var defaultSerializer serializer = canonicalJSON{}
+
+func setDefaultSerializer(s serializer) {
+ defaultSerializer = s
+}
diff --git a/vendor/github.com/docker/notary/tuf/data/snapshot.go b/vendor/github.com/docker/notary/tuf/data/snapshot.go
new file mode 100644
index 0000000..1d1178e
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/data/snapshot.go
@@ -0,0 +1,169 @@
+package data
+
+import (
+ "bytes"
+ "fmt"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/go/canonical/json"
+ "github.com/docker/notary"
+)
+
+// SignedSnapshot is a fully unpacked snapshot.json
+type SignedSnapshot struct {
+ Signatures []Signature
+ Signed Snapshot
+ Dirty bool
+}
+
+// Snapshot is the Signed component of a snapshot.json
+type Snapshot struct {
+ SignedCommon
+ Meta Files `json:"meta"`
+}
+
+// IsValidSnapshotStructure returns an error, or nil, depending on whether the content of the
+// struct is valid for snapshot metadata. This does not check signatures or expiry, just that
+// the metadata content is valid.
+func IsValidSnapshotStructure(s Snapshot) error {
+ expectedType := TUFTypes[CanonicalSnapshotRole]
+ if s.Type != expectedType {
+ return ErrInvalidMetadata{
+ role: CanonicalSnapshotRole, msg: fmt.Sprintf("expected type %s, not %s", expectedType, s.Type)}
+ }
+
+ if s.Version < 1 {
+ return ErrInvalidMetadata{
+ role: CanonicalSnapshotRole, msg: "version cannot be less than one"}
+ }
+
+ for _, role := range []string{CanonicalRootRole, CanonicalTargetsRole} {
+ // Meta is a map of FileMeta, so if the role isn't in the map it returns
+ // an empty FileMeta, which has an empty map, and you can check on keys
+ // from an empty map.
+ //
+ // For now sha256 is required and sha512 is not.
+ if _, ok := s.Meta[role].Hashes[notary.SHA256]; !ok {
+ return ErrInvalidMetadata{
+ role: CanonicalSnapshotRole,
+ msg: fmt.Sprintf("missing %s sha256 checksum information", role),
+ }
+ }
+ if err := CheckValidHashStructures(s.Meta[role].Hashes); err != nil {
+ return ErrInvalidMetadata{
+ role: CanonicalSnapshotRole,
+ msg: fmt.Sprintf("invalid %s checksum information, %v", role, err),
+ }
+ }
+ }
+ return nil
+}
+
+// NewSnapshot initilizes a SignedSnapshot with a given top level root
+// and targets objects
+func NewSnapshot(root *Signed, targets *Signed) (*SignedSnapshot, error) {
+ logrus.Debug("generating new snapshot...")
+ targetsJSON, err := json.Marshal(targets)
+ if err != nil {
+ logrus.Debug("Error Marshalling Targets")
+ return nil, err
+ }
+ rootJSON, err := json.Marshal(root)
+ if err != nil {
+ logrus.Debug("Error Marshalling Root")
+ return nil, err
+ }
+ rootMeta, err := NewFileMeta(bytes.NewReader(rootJSON), NotaryDefaultHashes...)
+ if err != nil {
+ return nil, err
+ }
+ targetsMeta, err := NewFileMeta(bytes.NewReader(targetsJSON), NotaryDefaultHashes...)
+ if err != nil {
+ return nil, err
+ }
+ return &SignedSnapshot{
+ Signatures: make([]Signature, 0),
+ Signed: Snapshot{
+ SignedCommon: SignedCommon{
+ Type: TUFTypes[CanonicalSnapshotRole],
+ Version: 0,
+ Expires: DefaultExpires(CanonicalSnapshotRole),
+ },
+ Meta: Files{
+ CanonicalRootRole: rootMeta,
+ CanonicalTargetsRole: targetsMeta,
+ },
+ },
+ }, nil
+}
+
+// ToSigned partially serializes a SignedSnapshot for further signing
+func (sp *SignedSnapshot) ToSigned() (*Signed, error) {
+ s, err := defaultSerializer.MarshalCanonical(sp.Signed)
+ if err != nil {
+ return nil, err
+ }
+ signed := json.RawMessage{}
+ err = signed.UnmarshalJSON(s)
+ if err != nil {
+ return nil, err
+ }
+ sigs := make([]Signature, len(sp.Signatures))
+ copy(sigs, sp.Signatures)
+ return &Signed{
+ Signatures: sigs,
+ Signed: &signed,
+ }, nil
+}
+
+// AddMeta updates a role in the snapshot with new meta
+func (sp *SignedSnapshot) AddMeta(role string, meta FileMeta) {
+ sp.Signed.Meta[role] = meta
+ sp.Dirty = true
+}
+
+// GetMeta gets the metadata for a particular role, returning an error if it's
+// not found
+func (sp *SignedSnapshot) GetMeta(role string) (*FileMeta, error) {
+ if meta, ok := sp.Signed.Meta[role]; ok {
+ if _, ok := meta.Hashes["sha256"]; ok {
+ return &meta, nil
+ }
+ }
+ return nil, ErrMissingMeta{Role: role}
+}
+
+// DeleteMeta removes a role from the snapshot. If the role doesn't
+// exist in the snapshot, it's a noop.
+func (sp *SignedSnapshot) DeleteMeta(role string) {
+ if _, ok := sp.Signed.Meta[role]; ok {
+ delete(sp.Signed.Meta, role)
+ sp.Dirty = true
+ }
+}
+
+// MarshalJSON returns the serialized form of SignedSnapshot as bytes
+func (sp *SignedSnapshot) MarshalJSON() ([]byte, error) {
+ signed, err := sp.ToSigned()
+ if err != nil {
+ return nil, err
+ }
+ return defaultSerializer.Marshal(signed)
+}
+
+// SnapshotFromSigned fully unpacks a Signed object into a SignedSnapshot
+func SnapshotFromSigned(s *Signed) (*SignedSnapshot, error) {
+ sp := Snapshot{}
+ if err := defaultSerializer.Unmarshal(*s.Signed, &sp); err != nil {
+ return nil, err
+ }
+ if err := IsValidSnapshotStructure(sp); err != nil {
+ return nil, err
+ }
+ sigs := make([]Signature, len(s.Signatures))
+ copy(sigs, s.Signatures)
+ return &SignedSnapshot{
+ Signatures: sigs,
+ Signed: sp,
+ }, nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/data/targets.go b/vendor/github.com/docker/notary/tuf/data/targets.go
new file mode 100644
index 0000000..04cca12
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/data/targets.go
@@ -0,0 +1,201 @@
+package data
+
+import (
+ "errors"
+ "fmt"
+ "path"
+
+ "github.com/docker/go/canonical/json"
+)
+
+// SignedTargets is a fully unpacked targets.json, or target delegation
+// json file
+type SignedTargets struct {
+ Signatures []Signature
+ Signed Targets
+ Dirty bool
+}
+
+// Targets is the Signed components of a targets.json or delegation json file
+type Targets struct {
+ SignedCommon
+ Targets Files `json:"targets"`
+ Delegations Delegations `json:"delegations,omitempty"`
+}
+
+// isValidTargetsStructure returns an error, or nil, depending on whether the content of the struct
+// is valid for targets metadata. This does not check signatures or expiry, just that
+// the metadata content is valid.
+func isValidTargetsStructure(t Targets, roleName string) error {
+ if roleName != CanonicalTargetsRole && !IsDelegation(roleName) {
+ return ErrInvalidRole{Role: roleName}
+ }
+
+ // even if it's a delegated role, the metadata type is "Targets"
+ expectedType := TUFTypes[CanonicalTargetsRole]
+ if t.Type != expectedType {
+ return ErrInvalidMetadata{
+ role: roleName, msg: fmt.Sprintf("expected type %s, not %s", expectedType, t.Type)}
+ }
+
+ if t.Version < 1 {
+ return ErrInvalidMetadata{role: roleName, msg: "version cannot be less than one"}
+ }
+
+ for _, roleObj := range t.Delegations.Roles {
+ if !IsDelegation(roleObj.Name) || path.Dir(roleObj.Name) != roleName {
+ return ErrInvalidMetadata{
+ role: roleName, msg: fmt.Sprintf("delegation role %s invalid", roleObj.Name)}
+ }
+ if err := isValidRootRoleStructure(roleName, roleObj.Name, roleObj.RootRole, t.Delegations.Keys); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// NewTargets intiializes a new empty SignedTargets object
+func NewTargets() *SignedTargets {
+ return &SignedTargets{
+ Signatures: make([]Signature, 0),
+ Signed: Targets{
+ SignedCommon: SignedCommon{
+ Type: TUFTypes["targets"],
+ Version: 0,
+ Expires: DefaultExpires("targets"),
+ },
+ Targets: make(Files),
+ Delegations: *NewDelegations(),
+ },
+ Dirty: true,
+ }
+}
+
+// GetMeta attempts to find the targets entry for the path. It
+// will return nil in the case of the target not being found.
+func (t SignedTargets) GetMeta(path string) *FileMeta {
+ for p, meta := range t.Signed.Targets {
+ if p == path {
+ return &meta
+ }
+ }
+ return nil
+}
+
+// GetValidDelegations filters the delegation roles specified in the signed targets, and
+// only returns roles that are direct children and restricts their paths
+func (t SignedTargets) GetValidDelegations(parent DelegationRole) []DelegationRole {
+ roles := t.buildDelegationRoles()
+ result := []DelegationRole{}
+ for _, r := range roles {
+ validRole, err := parent.Restrict(r)
+ if err != nil {
+ continue
+ }
+ result = append(result, validRole)
+ }
+ return result
+}
+
+// BuildDelegationRole returns a copy of a DelegationRole using the information in this SignedTargets for the specified role name.
+// Will error for invalid role name or key metadata within this SignedTargets. Path data is not validated.
+func (t *SignedTargets) BuildDelegationRole(roleName string) (DelegationRole, error) {
+ for _, role := range t.Signed.Delegations.Roles {
+ if role.Name == roleName {
+ pubKeys := make(map[string]PublicKey)
+ for _, keyID := range role.KeyIDs {
+ pubKey, ok := t.Signed.Delegations.Keys[keyID]
+ if !ok {
+ // Couldn't retrieve all keys, so stop walking and return invalid role
+ return DelegationRole{}, ErrInvalidRole{
+ Role: roleName,
+ Reason: "role lists unknown key " + keyID + " as a signing key",
+ }
+ }
+ pubKeys[keyID] = pubKey
+ }
+ return DelegationRole{
+ BaseRole: BaseRole{
+ Name: role.Name,
+ Keys: pubKeys,
+ Threshold: role.Threshold,
+ },
+ Paths: role.Paths,
+ }, nil
+ }
+ }
+ return DelegationRole{}, ErrNoSuchRole{Role: roleName}
+}
+
+// helper function to create DelegationRole structures from all delegations in a SignedTargets,
+// these delegations are read directly from the SignedTargets and not modified or validated
+func (t SignedTargets) buildDelegationRoles() []DelegationRole {
+ var roles []DelegationRole
+ for _, roleData := range t.Signed.Delegations.Roles {
+ delgRole, err := t.BuildDelegationRole(roleData.Name)
+ if err != nil {
+ continue
+ }
+ roles = append(roles, delgRole)
+ }
+ return roles
+}
+
+// AddTarget adds or updates the meta for the given path
+func (t *SignedTargets) AddTarget(path string, meta FileMeta) {
+ t.Signed.Targets[path] = meta
+ t.Dirty = true
+}
+
+// AddDelegation will add a new delegated role with the given keys,
+// ensuring the keys either already exist, or are added to the map
+// of delegation keys
+func (t *SignedTargets) AddDelegation(role *Role, keys []*PublicKey) error {
+ return errors.New("Not Implemented")
+}
+
+// ToSigned partially serializes a SignedTargets for further signing
+func (t *SignedTargets) ToSigned() (*Signed, error) {
+ s, err := defaultSerializer.MarshalCanonical(t.Signed)
+ if err != nil {
+ return nil, err
+ }
+ signed := json.RawMessage{}
+ err = signed.UnmarshalJSON(s)
+ if err != nil {
+ return nil, err
+ }
+ sigs := make([]Signature, len(t.Signatures))
+ copy(sigs, t.Signatures)
+ return &Signed{
+ Signatures: sigs,
+ Signed: &signed,
+ }, nil
+}
+
+// MarshalJSON returns the serialized form of SignedTargets as bytes
+func (t *SignedTargets) MarshalJSON() ([]byte, error) {
+ signed, err := t.ToSigned()
+ if err != nil {
+ return nil, err
+ }
+ return defaultSerializer.Marshal(signed)
+}
+
+// TargetsFromSigned fully unpacks a Signed object into a SignedTargets, given
+// a role name (so it can validate the SignedTargets object)
+func TargetsFromSigned(s *Signed, roleName string) (*SignedTargets, error) {
+ t := Targets{}
+ if err := defaultSerializer.Unmarshal(*s.Signed, &t); err != nil {
+ return nil, err
+ }
+ if err := isValidTargetsStructure(t, roleName); err != nil {
+ return nil, err
+ }
+ sigs := make([]Signature, len(s.Signatures))
+ copy(sigs, s.Signatures)
+ return &SignedTargets{
+ Signatures: sigs,
+ Signed: t,
+ }, nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/data/timestamp.go b/vendor/github.com/docker/notary/tuf/data/timestamp.go
new file mode 100644
index 0000000..1a64241
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/data/timestamp.go
@@ -0,0 +1,136 @@
+package data
+
+import (
+ "bytes"
+ "fmt"
+
+ "github.com/docker/go/canonical/json"
+ "github.com/docker/notary"
+)
+
+// SignedTimestamp is a fully unpacked timestamp.json
+type SignedTimestamp struct {
+ Signatures []Signature
+ Signed Timestamp
+ Dirty bool
+}
+
+// Timestamp is the Signed component of a timestamp.json
+type Timestamp struct {
+ SignedCommon
+ Meta Files `json:"meta"`
+}
+
+// IsValidTimestampStructure returns an error, or nil, depending on whether the content of the struct
+// is valid for timestamp metadata. This does not check signatures or expiry, just that
+// the metadata content is valid.
+func IsValidTimestampStructure(t Timestamp) error {
+ expectedType := TUFTypes[CanonicalTimestampRole]
+ if t.Type != expectedType {
+ return ErrInvalidMetadata{
+ role: CanonicalTimestampRole, msg: fmt.Sprintf("expected type %s, not %s", expectedType, t.Type)}
+ }
+
+ if t.Version < 1 {
+ return ErrInvalidMetadata{
+ role: CanonicalTimestampRole, msg: "version cannot be less than one"}
+ }
+
+ // Meta is a map of FileMeta, so if the role isn't in the map it returns
+ // an empty FileMeta, which has an empty map, and you can check on keys
+ // from an empty map.
+ //
+ // For now sha256 is required and sha512 is not.
+ if _, ok := t.Meta[CanonicalSnapshotRole].Hashes[notary.SHA256]; !ok {
+ return ErrInvalidMetadata{
+ role: CanonicalTimestampRole, msg: "missing snapshot sha256 checksum information"}
+ }
+ if err := CheckValidHashStructures(t.Meta[CanonicalSnapshotRole].Hashes); err != nil {
+ return ErrInvalidMetadata{
+ role: CanonicalTimestampRole, msg: fmt.Sprintf("invalid snapshot checksum information, %v", err)}
+ }
+
+ return nil
+}
+
+// NewTimestamp initializes a timestamp with an existing snapshot
+func NewTimestamp(snapshot *Signed) (*SignedTimestamp, error) {
+ snapshotJSON, err := json.Marshal(snapshot)
+ if err != nil {
+ return nil, err
+ }
+ snapshotMeta, err := NewFileMeta(bytes.NewReader(snapshotJSON), NotaryDefaultHashes...)
+ if err != nil {
+ return nil, err
+ }
+ return &SignedTimestamp{
+ Signatures: make([]Signature, 0),
+ Signed: Timestamp{
+ SignedCommon: SignedCommon{
+ Type: TUFTypes[CanonicalTimestampRole],
+ Version: 0,
+ Expires: DefaultExpires(CanonicalTimestampRole),
+ },
+ Meta: Files{
+ CanonicalSnapshotRole: snapshotMeta,
+ },
+ },
+ }, nil
+}
+
+// ToSigned partially serializes a SignedTimestamp such that it can
+// be signed
+func (ts *SignedTimestamp) ToSigned() (*Signed, error) {
+ s, err := defaultSerializer.MarshalCanonical(ts.Signed)
+ if err != nil {
+ return nil, err
+ }
+ signed := json.RawMessage{}
+ err = signed.UnmarshalJSON(s)
+ if err != nil {
+ return nil, err
+ }
+ sigs := make([]Signature, len(ts.Signatures))
+ copy(sigs, ts.Signatures)
+ return &Signed{
+ Signatures: sigs,
+ Signed: &signed,
+ }, nil
+}
+
+// GetSnapshot gets the expected snapshot metadata hashes in the timestamp metadata,
+// or nil if it doesn't exist
+func (ts *SignedTimestamp) GetSnapshot() (*FileMeta, error) {
+ snapshotExpected, ok := ts.Signed.Meta[CanonicalSnapshotRole]
+ if !ok {
+ return nil, ErrMissingMeta{Role: CanonicalSnapshotRole}
+ }
+ return &snapshotExpected, nil
+}
+
+// MarshalJSON returns the serialized form of SignedTimestamp as bytes
+func (ts *SignedTimestamp) MarshalJSON() ([]byte, error) {
+ signed, err := ts.ToSigned()
+ if err != nil {
+ return nil, err
+ }
+ return defaultSerializer.Marshal(signed)
+}
+
+// TimestampFromSigned parsed a Signed object into a fully unpacked
+// SignedTimestamp
+func TimestampFromSigned(s *Signed) (*SignedTimestamp, error) {
+ ts := Timestamp{}
+ if err := defaultSerializer.Unmarshal(*s.Signed, &ts); err != nil {
+ return nil, err
+ }
+ if err := IsValidTimestampStructure(ts); err != nil {
+ return nil, err
+ }
+ sigs := make([]Signature, len(s.Signatures))
+ copy(sigs, s.Signatures)
+ return &SignedTimestamp{
+ Signatures: sigs,
+ Signed: ts,
+ }, nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/data/types.go b/vendor/github.com/docker/notary/tuf/data/types.go
new file mode 100644
index 0000000..1f46a10
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/data/types.go
@@ -0,0 +1,311 @@
+package data
+
+import (
+ "crypto/sha256"
+ "crypto/sha512"
+ "crypto/subtle"
+ "encoding/hex"
+ "fmt"
+ "hash"
+ "io"
+ "io/ioutil"
+ "strings"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/go/canonical/json"
+ "github.com/docker/notary"
+)
+
+// SigAlgorithm for types of signatures
+type SigAlgorithm string
+
+func (k SigAlgorithm) String() string {
+ return string(k)
+}
+
+const defaultHashAlgorithm = "sha256"
+
+// Signature types
+const (
+ EDDSASignature SigAlgorithm = "eddsa"
+ RSAPSSSignature SigAlgorithm = "rsapss"
+ RSAPKCS1v15Signature SigAlgorithm = "rsapkcs1v15"
+ ECDSASignature SigAlgorithm = "ecdsa"
+ PyCryptoSignature SigAlgorithm = "pycrypto-pkcs#1 pss"
+)
+
+// Key types
+const (
+ ED25519Key = "ed25519"
+ RSAKey = "rsa"
+ RSAx509Key = "rsa-x509"
+ ECDSAKey = "ecdsa"
+ ECDSAx509Key = "ecdsa-x509"
+)
+
+// TUFTypes is the set of metadata types
+var TUFTypes = map[string]string{
+ CanonicalRootRole: "Root",
+ CanonicalTargetsRole: "Targets",
+ CanonicalSnapshotRole: "Snapshot",
+ CanonicalTimestampRole: "Timestamp",
+}
+
+// SetTUFTypes allows one to override some or all of the default
+// type names in TUF.
+func SetTUFTypes(ts map[string]string) {
+ for k, v := range ts {
+ TUFTypes[k] = v
+ }
+}
+
+// ValidTUFType checks if the given type is valid for the role
+func ValidTUFType(typ, role string) bool {
+ if ValidRole(role) {
+ // All targets delegation roles must have
+ // the valid type is for targets.
+ if role == "" {
+ // role is unknown and does not map to
+ // a type
+ return false
+ }
+ if strings.HasPrefix(role, CanonicalTargetsRole+"/") {
+ role = CanonicalTargetsRole
+ }
+ }
+ // most people will just use the defaults so have this optimal check
+ // first. Do comparison just in case there is some unknown vulnerability
+ // if a key and value in the map differ.
+ if v, ok := TUFTypes[role]; ok {
+ return typ == v
+ }
+ return false
+}
+
+// Signed is the high level, partially deserialized metadata object
+// used to verify signatures before fully unpacking, or to add signatures
+// before fully packing
+type Signed struct {
+ Signed *json.RawMessage `json:"signed"`
+ Signatures []Signature `json:"signatures"`
+}
+
+// SignedCommon contains the fields common to the Signed component of all
+// TUF metadata files
+type SignedCommon struct {
+ Type string `json:"_type"`
+ Expires time.Time `json:"expires"`
+ Version int `json:"version"`
+}
+
+// SignedMeta is used in server validation where we only need signatures
+// and common fields
+type SignedMeta struct {
+ Signed SignedCommon `json:"signed"`
+ Signatures []Signature `json:"signatures"`
+}
+
+// Signature is a signature on a piece of metadata
+type Signature struct {
+ KeyID string `json:"keyid"`
+ Method SigAlgorithm `json:"method"`
+ Signature []byte `json:"sig"`
+ IsValid bool `json:"-"`
+}
+
+// Files is the map of paths to file meta container in targets and delegations
+// metadata files
+type Files map[string]FileMeta
+
+// Hashes is the map of hash type to digest created for each metadata
+// and target file
+type Hashes map[string][]byte
+
+// NotaryDefaultHashes contains the default supported hash algorithms.
+var NotaryDefaultHashes = []string{notary.SHA256, notary.SHA512}
+
+// FileMeta contains the size and hashes for a metadata or target file. Custom
+// data can be optionally added.
+type FileMeta struct {
+ Length int64 `json:"length"`
+ Hashes Hashes `json:"hashes"`
+ Custom *json.RawMessage `json:"custom,omitempty"`
+}
+
+// CheckHashes verifies all the checksums specified by the "hashes" of the payload.
+func CheckHashes(payload []byte, name string, hashes Hashes) error {
+ cnt := 0
+
+ // k, v indicate the hash algorithm and the corresponding value
+ for k, v := range hashes {
+ switch k {
+ case notary.SHA256:
+ checksum := sha256.Sum256(payload)
+ if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
+ return ErrMismatchedChecksum{alg: notary.SHA256, name: name, expected: hex.EncodeToString(v)}
+ }
+ cnt++
+ case notary.SHA512:
+ checksum := sha512.Sum512(payload)
+ if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
+ return ErrMismatchedChecksum{alg: notary.SHA512, name: name, expected: hex.EncodeToString(v)}
+ }
+ cnt++
+ }
+ }
+
+ if cnt == 0 {
+ return ErrMissingMeta{Role: name}
+ }
+
+ return nil
+}
+
+// CompareMultiHashes verifies that the two Hashes passed in can represent the same data.
+// This means that both maps must have at least one key defined for which they map, and no conflicts.
+// Note that we check the intersection of map keys, which adds support for non-default hash algorithms in notary
+func CompareMultiHashes(hashes1, hashes2 Hashes) error {
+ // First check if the two hash structures are valid
+ if err := CheckValidHashStructures(hashes1); err != nil {
+ return err
+ }
+ if err := CheckValidHashStructures(hashes2); err != nil {
+ return err
+ }
+ // Check if they have at least one matching hash, and no conflicts
+ cnt := 0
+ for hashAlg, hash1 := range hashes1 {
+
+ hash2, ok := hashes2[hashAlg]
+ if !ok {
+ continue
+ }
+
+ if subtle.ConstantTimeCompare(hash1[:], hash2[:]) == 0 {
+ return fmt.Errorf("mismatched %s checksum", hashAlg)
+ }
+ // If we reached here, we had a match
+ cnt++
+ }
+
+ if cnt == 0 {
+ return fmt.Errorf("at least one matching hash needed")
+ }
+
+ return nil
+}
+
+// CheckValidHashStructures returns an error, or nil, depending on whether
+// the content of the hashes is valid or not.
+func CheckValidHashStructures(hashes Hashes) error {
+ cnt := 0
+
+ for k, v := range hashes {
+ switch k {
+ case notary.SHA256:
+ if len(v) != sha256.Size {
+ return ErrInvalidChecksum{alg: notary.SHA256}
+ }
+ cnt++
+ case notary.SHA512:
+ if len(v) != sha512.Size {
+ return ErrInvalidChecksum{alg: notary.SHA512}
+ }
+ cnt++
+ }
+ }
+
+ if cnt == 0 {
+ return fmt.Errorf("at least one supported hash needed")
+ }
+
+ return nil
+}
+
+// NewFileMeta generates a FileMeta object from the reader, using the
+// hash algorithms provided
+func NewFileMeta(r io.Reader, hashAlgorithms ...string) (FileMeta, error) {
+ if len(hashAlgorithms) == 0 {
+ hashAlgorithms = []string{defaultHashAlgorithm}
+ }
+ hashes := make(map[string]hash.Hash, len(hashAlgorithms))
+ for _, hashAlgorithm := range hashAlgorithms {
+ var h hash.Hash
+ switch hashAlgorithm {
+ case notary.SHA256:
+ h = sha256.New()
+ case notary.SHA512:
+ h = sha512.New()
+ default:
+ return FileMeta{}, fmt.Errorf("Unknown hash algorithm: %s", hashAlgorithm)
+ }
+ hashes[hashAlgorithm] = h
+ r = io.TeeReader(r, h)
+ }
+ n, err := io.Copy(ioutil.Discard, r)
+ if err != nil {
+ return FileMeta{}, err
+ }
+ m := FileMeta{Length: n, Hashes: make(Hashes, len(hashes))}
+ for hashAlgorithm, h := range hashes {
+ m.Hashes[hashAlgorithm] = h.Sum(nil)
+ }
+ return m, nil
+}
+
+// Delegations holds a tier of targets delegations
+type Delegations struct {
+ Keys Keys `json:"keys"`
+ Roles []*Role `json:"roles"`
+}
+
+// NewDelegations initializes an empty Delegations object
+func NewDelegations() *Delegations {
+ return &Delegations{
+ Keys: make(map[string]PublicKey),
+ Roles: make([]*Role, 0),
+ }
+}
+
+// These values are recommended TUF expiry times.
+var defaultExpiryTimes = map[string]time.Duration{
+ CanonicalRootRole: notary.Year,
+ CanonicalTargetsRole: 90 * notary.Day,
+ CanonicalSnapshotRole: 7 * notary.Day,
+ CanonicalTimestampRole: notary.Day,
+}
+
+// SetDefaultExpiryTimes allows one to change the default expiries.
+func SetDefaultExpiryTimes(times map[string]time.Duration) {
+ for key, value := range times {
+ if _, ok := defaultExpiryTimes[key]; !ok {
+ logrus.Errorf("Attempted to set default expiry for an unknown role: %s", key)
+ continue
+ }
+ defaultExpiryTimes[key] = value
+ }
+}
+
+// DefaultExpires gets the default expiry time for the given role
+func DefaultExpires(role string) time.Time {
+ if d, ok := defaultExpiryTimes[role]; ok {
+ return time.Now().Add(d)
+ }
+ var t time.Time
+ return t.UTC().Round(time.Second)
+}
+
+type unmarshalledSignature Signature
+
+// UnmarshalJSON does a custom unmarshalling of the signature JSON
+func (s *Signature) UnmarshalJSON(data []byte) error {
+ uSignature := unmarshalledSignature{}
+ err := json.Unmarshal(data, &uSignature)
+ if err != nil {
+ return err
+ }
+ uSignature.Method = SigAlgorithm(strings.ToLower(string(uSignature.Method)))
+ *s = Signature(uSignature)
+ return nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/signed/ed25519.go b/vendor/github.com/docker/notary/tuf/signed/ed25519.go
new file mode 100644
index 0000000..7a70739
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/signed/ed25519.go
@@ -0,0 +1,111 @@
+package signed
+
+import (
+ "crypto/rand"
+ "errors"
+
+ "github.com/docker/notary/trustmanager"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/utils"
+)
+
+type edCryptoKey struct {
+ role string
+ privKey data.PrivateKey
+}
+
+// Ed25519 implements a simple in memory cryptosystem for ED25519 keys
+type Ed25519 struct {
+ keys map[string]edCryptoKey
+}
+
+// NewEd25519 initializes a new empty Ed25519 CryptoService that operates
+// entirely in memory
+func NewEd25519() *Ed25519 {
+ return &Ed25519{
+ make(map[string]edCryptoKey),
+ }
+}
+
+// AddKey allows you to add a private key
+func (e *Ed25519) AddKey(role, gun string, k data.PrivateKey) error {
+ e.addKey(role, k)
+ return nil
+}
+
+// addKey allows you to add a private key
+func (e *Ed25519) addKey(role string, k data.PrivateKey) {
+ e.keys[k.ID()] = edCryptoKey{
+ role: role,
+ privKey: k,
+ }
+}
+
+// RemoveKey deletes a key from the signer
+func (e *Ed25519) RemoveKey(keyID string) error {
+ delete(e.keys, keyID)
+ return nil
+}
+
+// ListKeys returns the list of keys IDs for the role
+func (e *Ed25519) ListKeys(role string) []string {
+ keyIDs := make([]string, 0, len(e.keys))
+ for id, edCryptoKey := range e.keys {
+ if edCryptoKey.role == role {
+ keyIDs = append(keyIDs, id)
+ }
+ }
+ return keyIDs
+}
+
+// ListAllKeys returns the map of keys IDs to role
+func (e *Ed25519) ListAllKeys() map[string]string {
+ keys := make(map[string]string)
+ for id, edKey := range e.keys {
+ keys[id] = edKey.role
+ }
+ return keys
+}
+
+// Create generates a new key and returns the public part
+func (e *Ed25519) Create(role, gun, algorithm string) (data.PublicKey, error) {
+ if algorithm != data.ED25519Key {
+ return nil, errors.New("only ED25519 supported by this cryptoservice")
+ }
+
+ private, err := utils.GenerateED25519Key(rand.Reader)
+ if err != nil {
+ return nil, err
+ }
+
+ e.addKey(role, private)
+ return data.PublicKeyFromPrivate(private), nil
+}
+
+// PublicKeys returns a map of public keys for the ids provided, when those IDs are found
+// in the store.
+func (e *Ed25519) PublicKeys(keyIDs ...string) (map[string]data.PublicKey, error) {
+ k := make(map[string]data.PublicKey)
+ for _, keyID := range keyIDs {
+ if edKey, ok := e.keys[keyID]; ok {
+ k[keyID] = data.PublicKeyFromPrivate(edKey.privKey)
+ }
+ }
+ return k, nil
+}
+
+// GetKey returns a single public key based on the ID
+func (e *Ed25519) GetKey(keyID string) data.PublicKey {
+ if privKey, _, err := e.GetPrivateKey(keyID); err == nil {
+ return data.PublicKeyFromPrivate(privKey)
+ }
+ return nil
+}
+
+// GetPrivateKey returns a single private key and role if present, based on the ID
+func (e *Ed25519) GetPrivateKey(keyID string) (data.PrivateKey, string, error) {
+ if k, ok := e.keys[keyID]; ok {
+ return k.privKey, k.role, nil
+ }
+ return nil, "", trustmanager.ErrKeyNotFound{KeyID: keyID}
+}
diff --git a/vendor/github.com/docker/notary/tuf/signed/errors.go b/vendor/github.com/docker/notary/tuf/signed/errors.go
new file mode 100644
index 0000000..2a633c8
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/signed/errors.go
@@ -0,0 +1,96 @@
+package signed
+
+import (
+ "fmt"
+ "strings"
+)
+
+// ErrInsufficientSignatures - can not create enough signatures on a piece of
+// metadata
+type ErrInsufficientSignatures struct {
+ FoundKeys int
+ NeededKeys int
+ MissingKeyIDs []string
+}
+
+func (e ErrInsufficientSignatures) Error() string {
+ candidates := ""
+ if len(e.MissingKeyIDs) > 0 {
+ candidates = fmt.Sprintf(" (%s)", strings.Join(e.MissingKeyIDs, ", "))
+ }
+
+ if e.FoundKeys == 0 {
+ return fmt.Sprintf("signing keys not available: need %d keys from %d possible keys%s",
+ e.NeededKeys, len(e.MissingKeyIDs), candidates)
+ }
+ return fmt.Sprintf("not enough signing keys: found %d of %d needed keys - %d other possible keys%s",
+ e.FoundKeys, e.NeededKeys, len(e.MissingKeyIDs), candidates)
+}
+
+// ErrExpired indicates a piece of metadata has expired
+type ErrExpired struct {
+ Role string
+ Expired string
+}
+
+func (e ErrExpired) Error() string {
+ return fmt.Sprintf("%s expired at %v", e.Role, e.Expired)
+}
+
+// ErrLowVersion indicates the piece of metadata has a version number lower than
+// a version number we're already seen for this role
+type ErrLowVersion struct {
+ Actual int
+ Current int
+}
+
+func (e ErrLowVersion) Error() string {
+ return fmt.Sprintf("version %d is lower than current version %d", e.Actual, e.Current)
+}
+
+// ErrRoleThreshold indicates we did not validate enough signatures to meet the threshold
+type ErrRoleThreshold struct {
+ Msg string
+}
+
+func (e ErrRoleThreshold) Error() string {
+ if e.Msg == "" {
+ return "valid signatures did not meet threshold"
+ }
+ return e.Msg
+}
+
+// ErrInvalidKeyType indicates the types for the key and signature it's associated with are
+// mismatched. Probably a sign of malicious behaviour
+type ErrInvalidKeyType struct{}
+
+func (e ErrInvalidKeyType) Error() string {
+ return "key type is not valid for signature"
+}
+
+// ErrInvalidKeyID indicates the specified key ID was incorrect for its associated data
+type ErrInvalidKeyID struct{}
+
+func (e ErrInvalidKeyID) Error() string {
+ return "key ID is not valid for key content"
+}
+
+// ErrInvalidKeyLength indicates that while we may support the cipher, the provided
+// key length is not specifically supported, i.e. we support RSA, but not 1024 bit keys
+type ErrInvalidKeyLength struct {
+ msg string
+}
+
+func (e ErrInvalidKeyLength) Error() string {
+ return fmt.Sprintf("key length is not supported: %s", e.msg)
+}
+
+// ErrNoKeys indicates no signing keys were found when trying to sign
+type ErrNoKeys struct {
+ KeyIDs []string
+}
+
+func (e ErrNoKeys) Error() string {
+ return fmt.Sprintf("could not find necessary signing keys, at least one of these keys must be available: %s",
+ strings.Join(e.KeyIDs, ", "))
+}
diff --git a/vendor/github.com/docker/notary/tuf/signed/interface.go b/vendor/github.com/docker/notary/tuf/signed/interface.go
new file mode 100644
index 0000000..862b23b
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/signed/interface.go
@@ -0,0 +1,49 @@
+package signed
+
+import (
+ "github.com/docker/notary/tuf/data"
+)
+
+// KeyService provides management of keys locally. It will never
+// accept or provide private keys. Communication between the KeyService
+// and a SigningService happen behind the Create function.
+type KeyService interface {
+ // Create issues a new key pair and is responsible for loading
+ // the private key into the appropriate signing service.
+ Create(role, gun, algorithm string) (data.PublicKey, error)
+
+ // AddKey adds a private key to the specified role and gun
+ AddKey(role, gun string, key data.PrivateKey) error
+
+ // GetKey retrieves the public key if present, otherwise it returns nil
+ GetKey(keyID string) data.PublicKey
+
+ // GetPrivateKey retrieves the private key and role if present and retrievable,
+ // otherwise it returns nil and an error
+ GetPrivateKey(keyID string) (data.PrivateKey, string, error)
+
+ // RemoveKey deletes the specified key, and returns an error only if the key
+ // removal fails. If the key doesn't exist, no error should be returned.
+ RemoveKey(keyID string) error
+
+ // ListKeys returns a list of key IDs for the role, or an empty list or
+ // nil if there are no keys.
+ ListKeys(role string) []string
+
+ // ListAllKeys returns a map of all available signing key IDs to role, or
+ // an empty map or nil if there are no keys.
+ ListAllKeys() map[string]string
+}
+
+// CryptoService is deprecated and all instances of its use should be
+// replaced with KeyService
+type CryptoService interface {
+ KeyService
+}
+
+// Verifier defines an interface for verfying signatures. An implementer
+// of this interface should verify signatures for one and only one
+// signing scheme.
+type Verifier interface {
+ Verify(key data.PublicKey, sig []byte, msg []byte) error
+}
diff --git a/vendor/github.com/docker/notary/tuf/signed/sign.go b/vendor/github.com/docker/notary/tuf/signed/sign.go
new file mode 100644
index 0000000..31abb12
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/signed/sign.go
@@ -0,0 +1,113 @@
+package signed
+
+// The Sign function is a choke point for all code paths that do signing.
+// We use this fact to do key ID translation. There are 2 types of key ID:
+// - Scoped: the key ID based purely on the data that appears in the TUF
+// files. This may be wrapped by a certificate that scopes the
+// key to be used in a specific context.
+// - Canonical: the key ID based purely on the public key bytes. This is
+// used by keystores to easily identify keys that may be reused
+// in many scoped locations.
+// Currently these types only differ in the context of Root Keys in Notary
+// for which the root key is wrapped using an x509 certificate.
+
+import (
+ "crypto/rand"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary/trustmanager"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/utils"
+)
+
+// Sign takes a data.Signed and a cryptoservice containing private keys,
+// calculates and adds at least minSignature signatures using signingKeys the
+// data.Signed. It will also clean up any signatures that are not in produced
+// by either a signingKey or an otherWhitelistedKey.
+// Note that in most cases, otherWhitelistedKeys should probably be null. They
+// are for keys you don't want to sign with, but you also don't want to remove
+// existing signatures by those keys. For instance, if you want to call Sign
+// multiple times with different sets of signing keys without undoing removing
+// signatures produced by the previous call to Sign.
+func Sign(service CryptoService, s *data.Signed, signingKeys []data.PublicKey,
+ minSignatures int, otherWhitelistedKeys []data.PublicKey) error {
+
+ logrus.Debugf("sign called with %d/%d required keys", minSignatures, len(signingKeys))
+ signatures := make([]data.Signature, 0, len(s.Signatures)+1)
+ signingKeyIDs := make(map[string]struct{})
+ tufIDs := make(map[string]data.PublicKey)
+
+ privKeys := make(map[string]data.PrivateKey)
+
+ // Get all the private key objects related to the public keys
+ missingKeyIDs := []string{}
+ for _, key := range signingKeys {
+ canonicalID, err := utils.CanonicalKeyID(key)
+ tufIDs[key.ID()] = key
+ if err != nil {
+ return err
+ }
+ k, _, err := service.GetPrivateKey(canonicalID)
+ if err != nil {
+ if _, ok := err.(trustmanager.ErrKeyNotFound); ok {
+ missingKeyIDs = append(missingKeyIDs, canonicalID)
+ continue
+ }
+ return err
+ }
+ privKeys[key.ID()] = k
+ }
+
+ // include the list of otherWhitelistedKeys
+ for _, key := range otherWhitelistedKeys {
+ if _, ok := tufIDs[key.ID()]; !ok {
+ tufIDs[key.ID()] = key
+ }
+ }
+
+ // Check to ensure we have enough signing keys
+ if len(privKeys) < minSignatures {
+ return ErrInsufficientSignatures{FoundKeys: len(privKeys),
+ NeededKeys: minSignatures, MissingKeyIDs: missingKeyIDs}
+ }
+
+ emptyStruct := struct{}{}
+ // Do signing and generate list of signatures
+ for keyID, pk := range privKeys {
+ sig, err := pk.Sign(rand.Reader, *s.Signed, nil)
+ if err != nil {
+ logrus.Debugf("Failed to sign with key: %s. Reason: %v", keyID, err)
+ return err
+ }
+ signingKeyIDs[keyID] = emptyStruct
+ signatures = append(signatures, data.Signature{
+ KeyID: keyID,
+ Method: pk.SignatureAlgorithm(),
+ Signature: sig[:],
+ })
+ }
+
+ for _, sig := range s.Signatures {
+ if _, ok := signingKeyIDs[sig.KeyID]; ok {
+ // key is in the set of key IDs for which a signature has been created
+ continue
+ }
+ var (
+ k data.PublicKey
+ ok bool
+ )
+ if k, ok = tufIDs[sig.KeyID]; !ok {
+ // key is no longer a valid signing key
+ continue
+ }
+ if err := VerifySignature(*s.Signed, &sig, k); err != nil {
+ // signature is no longer valid
+ continue
+ }
+ // keep any signatures that still represent valid keys and are
+ // themselves valid
+ signatures = append(signatures, sig)
+ }
+ s.Signatures = signatures
+ return nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/signed/verifiers.go b/vendor/github.com/docker/notary/tuf/signed/verifiers.go
new file mode 100644
index 0000000..7921863
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/signed/verifiers.go
@@ -0,0 +1,283 @@
+package signed
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/rsa"
+ "crypto/sha256"
+ "crypto/x509"
+ "encoding/pem"
+ "fmt"
+ "math/big"
+ "reflect"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/agl/ed25519"
+ "github.com/docker/notary/tuf/data"
+)
+
+const (
+ minRSAKeySizeBit = 2048 // 2048 bits = 256 bytes
+ minRSAKeySizeByte = minRSAKeySizeBit / 8
+)
+
+// Verifiers serves as a map of all verifiers available on the system and
+// can be injected into a verificationService. For testing and configuration
+// purposes, it will not be used by default.
+var Verifiers = map[data.SigAlgorithm]Verifier{
+ data.RSAPSSSignature: RSAPSSVerifier{},
+ data.RSAPKCS1v15Signature: RSAPKCS1v15Verifier{},
+ data.PyCryptoSignature: RSAPyCryptoVerifier{},
+ data.ECDSASignature: ECDSAVerifier{},
+ data.EDDSASignature: Ed25519Verifier{},
+}
+
+// RegisterVerifier provides a convenience function for init() functions
+// to register additional verifiers or replace existing ones.
+func RegisterVerifier(algorithm data.SigAlgorithm, v Verifier) {
+ curr, ok := Verifiers[algorithm]
+ if ok {
+ typOld := reflect.TypeOf(curr)
+ typNew := reflect.TypeOf(v)
+ logrus.Debugf(
+ "replacing already loaded verifier %s:%s with %s:%s",
+ typOld.PkgPath(), typOld.Name(),
+ typNew.PkgPath(), typNew.Name(),
+ )
+ } else {
+ logrus.Debug("adding verifier for: ", algorithm)
+ }
+ Verifiers[algorithm] = v
+}
+
+// Ed25519Verifier used to verify Ed25519 signatures
+type Ed25519Verifier struct{}
+
+// Verify checks that an ed25519 signature is valid
+func (v Ed25519Verifier) Verify(key data.PublicKey, sig []byte, msg []byte) error {
+ if key.Algorithm() != data.ED25519Key {
+ return ErrInvalidKeyType{}
+ }
+ var sigBytes [ed25519.SignatureSize]byte
+ if len(sig) != ed25519.SignatureSize {
+ logrus.Debugf("signature length is incorrect, must be %d, was %d.", ed25519.SignatureSize, len(sig))
+ return ErrInvalid
+ }
+ copy(sigBytes[:], sig)
+
+ var keyBytes [ed25519.PublicKeySize]byte
+ pub := key.Public()
+ if len(pub) != ed25519.PublicKeySize {
+ logrus.Errorf("public key is incorrect size, must be %d, was %d.", ed25519.PublicKeySize, len(pub))
+ return ErrInvalidKeyLength{msg: fmt.Sprintf("ed25519 public key must be %d bytes.", ed25519.PublicKeySize)}
+ }
+ n := copy(keyBytes[:], key.Public())
+ if n < ed25519.PublicKeySize {
+ logrus.Errorf("failed to copy the key, must have %d bytes, copied %d bytes.", ed25519.PublicKeySize, n)
+ return ErrInvalid
+ }
+
+ if !ed25519.Verify(&keyBytes, msg, &sigBytes) {
+ logrus.Debugf("failed ed25519 verification")
+ return ErrInvalid
+ }
+ return nil
+}
+
+func verifyPSS(key interface{}, digest, sig []byte) error {
+ rsaPub, ok := key.(*rsa.PublicKey)
+ if !ok {
+ logrus.Debugf("value was not an RSA public key")
+ return ErrInvalid
+ }
+
+ if rsaPub.N.BitLen() < minRSAKeySizeBit {
+ logrus.Debugf("RSA keys less than 2048 bits are not acceptable, provided key has length %d.", rsaPub.N.BitLen())
+ return ErrInvalidKeyLength{msg: fmt.Sprintf("RSA key must be at least %d bits.", minRSAKeySizeBit)}
+ }
+
+ if len(sig) < minRSAKeySizeByte {
+ logrus.Debugf("RSA keys less than 2048 bits are not acceptable, provided signature has length %d.", len(sig))
+ return ErrInvalid
+ }
+
+ opts := rsa.PSSOptions{SaltLength: sha256.Size, Hash: crypto.SHA256}
+ if err := rsa.VerifyPSS(rsaPub, crypto.SHA256, digest[:], sig, &opts); err != nil {
+ logrus.Debugf("failed RSAPSS verification: %s", err)
+ return ErrInvalid
+ }
+ return nil
+}
+
+func getRSAPubKey(key data.PublicKey) (crypto.PublicKey, error) {
+ algorithm := key.Algorithm()
+ var pubKey crypto.PublicKey
+
+ switch algorithm {
+ case data.RSAx509Key:
+ pemCert, _ := pem.Decode([]byte(key.Public()))
+ if pemCert == nil {
+ logrus.Debugf("failed to decode PEM-encoded x509 certificate")
+ return nil, ErrInvalid
+ }
+ cert, err := x509.ParseCertificate(pemCert.Bytes)
+ if err != nil {
+ logrus.Debugf("failed to parse x509 certificate: %s\n", err)
+ return nil, ErrInvalid
+ }
+ pubKey = cert.PublicKey
+ case data.RSAKey:
+ var err error
+ pubKey, err = x509.ParsePKIXPublicKey(key.Public())
+ if err != nil {
+ logrus.Debugf("failed to parse public key: %s\n", err)
+ return nil, ErrInvalid
+ }
+ default:
+ // only accept RSA keys
+ logrus.Debugf("invalid key type for RSAPSS verifier: %s", algorithm)
+ return nil, ErrInvalidKeyType{}
+ }
+
+ return pubKey, nil
+}
+
+// RSAPSSVerifier checks RSASSA-PSS signatures
+type RSAPSSVerifier struct{}
+
+// Verify does the actual check.
+func (v RSAPSSVerifier) Verify(key data.PublicKey, sig []byte, msg []byte) error {
+ // will return err if keytype is not a recognized RSA type
+ pubKey, err := getRSAPubKey(key)
+ if err != nil {
+ return err
+ }
+
+ digest := sha256.Sum256(msg)
+
+ return verifyPSS(pubKey, digest[:], sig)
+}
+
+// RSAPKCS1v15Verifier checks RSA PKCS1v15 signatures
+type RSAPKCS1v15Verifier struct{}
+
+// Verify does the actual verification
+func (v RSAPKCS1v15Verifier) Verify(key data.PublicKey, sig []byte, msg []byte) error {
+ // will return err if keytype is not a recognized RSA type
+ pubKey, err := getRSAPubKey(key)
+ if err != nil {
+ return err
+ }
+ digest := sha256.Sum256(msg)
+
+ rsaPub, ok := pubKey.(*rsa.PublicKey)
+ if !ok {
+ logrus.Debugf("value was not an RSA public key")
+ return ErrInvalid
+ }
+
+ if rsaPub.N.BitLen() < minRSAKeySizeBit {
+ logrus.Debugf("RSA keys less than 2048 bits are not acceptable, provided key has length %d.", rsaPub.N.BitLen())
+ return ErrInvalidKeyLength{msg: fmt.Sprintf("RSA key must be at least %d bits.", minRSAKeySizeBit)}
+ }
+
+ if len(sig) < minRSAKeySizeByte {
+ logrus.Debugf("RSA keys less than 2048 bits are not acceptable, provided signature has length %d.", len(sig))
+ return ErrInvalid
+ }
+
+ if err = rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, digest[:], sig); err != nil {
+ logrus.Errorf("Failed verification: %s", err.Error())
+ return ErrInvalid
+ }
+ return nil
+}
+
+// RSAPyCryptoVerifier checks RSASSA-PSS signatures
+type RSAPyCryptoVerifier struct{}
+
+// Verify does the actual check.
+// N.B. We have not been able to make this work in a way that is compatible
+// with PyCrypto.
+func (v RSAPyCryptoVerifier) Verify(key data.PublicKey, sig []byte, msg []byte) error {
+ digest := sha256.Sum256(msg)
+ if key.Algorithm() != data.RSAKey {
+ return ErrInvalidKeyType{}
+ }
+
+ k, _ := pem.Decode([]byte(key.Public()))
+ if k == nil {
+ logrus.Debugf("failed to decode PEM-encoded x509 certificate")
+ return ErrInvalid
+ }
+
+ pub, err := x509.ParsePKIXPublicKey(k.Bytes)
+ if err != nil {
+ logrus.Debugf("failed to parse public key: %s\n", err)
+ return ErrInvalid
+ }
+
+ return verifyPSS(pub, digest[:], sig)
+}
+
+// ECDSAVerifier checks ECDSA signatures, decoding the keyType appropriately
+type ECDSAVerifier struct{}
+
+// Verify does the actual check.
+func (v ECDSAVerifier) Verify(key data.PublicKey, sig []byte, msg []byte) error {
+ algorithm := key.Algorithm()
+ var pubKey crypto.PublicKey
+
+ switch algorithm {
+ case data.ECDSAx509Key:
+ pemCert, _ := pem.Decode([]byte(key.Public()))
+ if pemCert == nil {
+ logrus.Debugf("failed to decode PEM-encoded x509 certificate for keyID: %s", key.ID())
+ logrus.Debugf("certificate bytes: %s", string(key.Public()))
+ return ErrInvalid
+ }
+ cert, err := x509.ParseCertificate(pemCert.Bytes)
+ if err != nil {
+ logrus.Debugf("failed to parse x509 certificate: %s\n", err)
+ return ErrInvalid
+ }
+ pubKey = cert.PublicKey
+ case data.ECDSAKey:
+ var err error
+ pubKey, err = x509.ParsePKIXPublicKey(key.Public())
+ if err != nil {
+ logrus.Debugf("Failed to parse private key for keyID: %s, %s\n", key.ID(), err)
+ return ErrInvalid
+ }
+ default:
+ // only accept ECDSA keys.
+ logrus.Debugf("invalid key type for ECDSA verifier: %s", algorithm)
+ return ErrInvalidKeyType{}
+ }
+
+ ecdsaPubKey, ok := pubKey.(*ecdsa.PublicKey)
+ if !ok {
+ logrus.Debugf("value isn't an ECDSA public key")
+ return ErrInvalid
+ }
+
+ sigLength := len(sig)
+ expectedOctetLength := 2 * ((ecdsaPubKey.Params().BitSize + 7) >> 3)
+ if sigLength != expectedOctetLength {
+ logrus.Debugf("signature had an unexpected length")
+ return ErrInvalid
+ }
+
+ rBytes, sBytes := sig[:sigLength/2], sig[sigLength/2:]
+ r := new(big.Int).SetBytes(rBytes)
+ s := new(big.Int).SetBytes(sBytes)
+
+ digest := sha256.Sum256(msg)
+
+ if !ecdsa.Verify(ecdsaPubKey, digest[:], r, s) {
+ logrus.Debugf("failed ECDSA signature validation")
+ return ErrInvalid
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/signed/verify.go b/vendor/github.com/docker/notary/tuf/signed/verify.go
new file mode 100644
index 0000000..5858766
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/signed/verify.go
@@ -0,0 +1,112 @@
+package signed
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/go/canonical/json"
+ "github.com/docker/notary/tuf/data"
+)
+
+// Various basic signing errors
+var (
+ ErrMissingKey = errors.New("tuf: missing key")
+ ErrNoSignatures = errors.New("tuf: data has no signatures")
+ ErrInvalid = errors.New("tuf: signature verification failed")
+ ErrWrongMethod = errors.New("tuf: invalid signature type")
+ ErrUnknownRole = errors.New("tuf: unknown role")
+ ErrWrongType = errors.New("tuf: meta file has wrong type")
+)
+
+// IsExpired checks if the given time passed before the present time
+func IsExpired(t time.Time) bool {
+ return t.Before(time.Now())
+}
+
+// VerifyExpiry returns ErrExpired if the metadata is expired
+func VerifyExpiry(s *data.SignedCommon, role string) error {
+ if IsExpired(s.Expires) {
+ logrus.Errorf("Metadata for %s expired", role)
+ return ErrExpired{Role: role, Expired: s.Expires.Format("Mon Jan 2 15:04:05 MST 2006")}
+ }
+ return nil
+}
+
+// VerifyVersion returns ErrLowVersion if the metadata version is lower than the min version
+func VerifyVersion(s *data.SignedCommon, minVersion int) error {
+ if s.Version < minVersion {
+ return ErrLowVersion{Actual: s.Version, Current: minVersion}
+ }
+ return nil
+}
+
+// VerifySignatures checks the we have sufficient valid signatures for the given role
+func VerifySignatures(s *data.Signed, roleData data.BaseRole) error {
+ if len(s.Signatures) == 0 {
+ return ErrNoSignatures
+ }
+
+ if roleData.Threshold < 1 {
+ return ErrRoleThreshold{}
+ }
+ logrus.Debugf("%s role has key IDs: %s", roleData.Name, strings.Join(roleData.ListKeyIDs(), ","))
+
+ // remarshal the signed part so we can verify the signature, since the signature has
+ // to be of a canonically marshalled signed object
+ var decoded map[string]interface{}
+ if err := json.Unmarshal(*s.Signed, &decoded); err != nil {
+ return err
+ }
+ msg, err := json.MarshalCanonical(decoded)
+ if err != nil {
+ return err
+ }
+
+ valid := make(map[string]struct{})
+ for i := range s.Signatures {
+ sig := &(s.Signatures[i])
+ logrus.Debug("verifying signature for key ID: ", sig.KeyID)
+ key, ok := roleData.Keys[sig.KeyID]
+ if !ok {
+ logrus.Debugf("continuing b/c keyid lookup was nil: %s\n", sig.KeyID)
+ continue
+ }
+ // Check that the signature key ID actually matches the content ID of the key
+ if key.ID() != sig.KeyID {
+ return ErrInvalidKeyID{}
+ }
+ if err := VerifySignature(msg, sig, key); err != nil {
+ logrus.Debugf("continuing b/c %s", err.Error())
+ continue
+ }
+ valid[sig.KeyID] = struct{}{}
+ }
+ if len(valid) < roleData.Threshold {
+ return ErrRoleThreshold{
+ Msg: fmt.Sprintf("valid signatures did not meet threshold for %s", roleData.Name),
+ }
+ }
+
+ return nil
+}
+
+// VerifySignature checks a single signature and public key against a payload
+// If the signature is verified, the signature's is valid field will actually
+// be mutated to be equal to the boolean true
+func VerifySignature(msg []byte, sig *data.Signature, pk data.PublicKey) error {
+ // method lookup is consistent due to Unmarshal JSON doing lower case for us.
+ method := sig.Method
+ verifier, ok := Verifiers[method]
+ if !ok {
+ return fmt.Errorf("signing method is not supported: %s\n", sig.Method)
+ }
+
+ if err := verifier.Verify(pk, sig.Signature, msg); err != nil {
+ return fmt.Errorf("signature was invalid\n")
+ }
+ sig.IsValid = true
+ return nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/tuf.go b/vendor/github.com/docker/notary/tuf/tuf.go
new file mode 100644
index 0000000..91f3fa5
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/tuf.go
@@ -0,0 +1,1148 @@
+// Package tuf defines the core TUF logic around manipulating a repo.
+package tuf
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "path"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/notary"
+ "github.com/docker/notary/tuf/data"
+ "github.com/docker/notary/tuf/signed"
+ "github.com/docker/notary/tuf/utils"
+)
+
+// ErrSigVerifyFail - signature verification failed
+type ErrSigVerifyFail struct{}
+
+func (e ErrSigVerifyFail) Error() string {
+ return "Error: Signature verification failed"
+}
+
+// ErrMetaExpired - metadata file has expired
+type ErrMetaExpired struct{}
+
+func (e ErrMetaExpired) Error() string {
+ return "Error: Metadata has expired"
+}
+
+// ErrLocalRootExpired - the local root file is out of date
+type ErrLocalRootExpired struct{}
+
+func (e ErrLocalRootExpired) Error() string {
+ return "Error: Local Root Has Expired"
+}
+
+// ErrNotLoaded - attempted to access data that has not been loaded into
+// the repo. This means specifically that the relevant JSON file has not
+// been loaded.
+type ErrNotLoaded struct {
+ Role string
+}
+
+func (err ErrNotLoaded) Error() string {
+ return fmt.Sprintf("%s role has not been loaded", err.Role)
+}
+
+// StopWalk - used by visitor functions to signal WalkTargets to stop walking
+type StopWalk struct{}
+
+// Repo is an in memory representation of the TUF Repo.
+// It operates at the data.Signed level, accepting and producing
+// data.Signed objects. Users of a Repo are responsible for
+// fetching raw JSON and using the Set* functions to populate
+// the Repo instance.
+type Repo struct {
+ Root *data.SignedRoot
+ Targets map[string]*data.SignedTargets
+ Snapshot *data.SignedSnapshot
+ Timestamp *data.SignedTimestamp
+ cryptoService signed.CryptoService
+
+ // Because Repo is a mutable structure, these keep track of what the root
+ // role was when a root is set on the repo (as opposed to what it might be
+ // after things like AddBaseKeys and RemoveBaseKeys have been called on it).
+ // If we know what the original was, we'll if and how to handle root
+ // rotations.
+ originalRootRole data.BaseRole
+}
+
+// NewRepo initializes a Repo instance with a CryptoService.
+// If the Repo will only be used for reading, the CryptoService
+// can be nil.
+func NewRepo(cryptoService signed.CryptoService) *Repo {
+ return &Repo{
+ Targets: make(map[string]*data.SignedTargets),
+ cryptoService: cryptoService,
+ }
+}
+
+// AddBaseKeys is used to add keys to the role in root.json
+func (tr *Repo) AddBaseKeys(role string, keys ...data.PublicKey) error {
+ if tr.Root == nil {
+ return ErrNotLoaded{Role: data.CanonicalRootRole}
+ }
+ ids := []string{}
+ for _, k := range keys {
+ // Store only the public portion
+ tr.Root.Signed.Keys[k.ID()] = k
+ tr.Root.Signed.Roles[role].KeyIDs = append(tr.Root.Signed.Roles[role].KeyIDs, k.ID())
+ ids = append(ids, k.ID())
+ }
+ tr.Root.Dirty = true
+
+ // also, whichever role was switched out needs to be re-signed
+ // root has already been marked dirty.
+ switch role {
+ case data.CanonicalSnapshotRole:
+ if tr.Snapshot != nil {
+ tr.Snapshot.Dirty = true
+ }
+ case data.CanonicalTargetsRole:
+ if target, ok := tr.Targets[data.CanonicalTargetsRole]; ok {
+ target.Dirty = true
+ }
+ case data.CanonicalTimestampRole:
+ if tr.Timestamp != nil {
+ tr.Timestamp.Dirty = true
+ }
+ }
+ return nil
+}
+
+// ReplaceBaseKeys is used to replace all keys for the given role with the new keys
+func (tr *Repo) ReplaceBaseKeys(role string, keys ...data.PublicKey) error {
+ r, err := tr.GetBaseRole(role)
+ if err != nil {
+ return err
+ }
+ err = tr.RemoveBaseKeys(role, r.ListKeyIDs()...)
+ if err != nil {
+ return err
+ }
+ return tr.AddBaseKeys(role, keys...)
+}
+
+// RemoveBaseKeys is used to remove keys from the roles in root.json
+func (tr *Repo) RemoveBaseKeys(role string, keyIDs ...string) error {
+ if tr.Root == nil {
+ return ErrNotLoaded{Role: data.CanonicalRootRole}
+ }
+ var keep []string
+ toDelete := make(map[string]struct{})
+ emptyStruct := struct{}{}
+ // remove keys from specified role
+ for _, k := range keyIDs {
+ toDelete[k] = emptyStruct
+ }
+
+ oldKeyIDs := tr.Root.Signed.Roles[role].KeyIDs
+ for _, rk := range oldKeyIDs {
+ if _, ok := toDelete[rk]; !ok {
+ keep = append(keep, rk)
+ }
+ }
+
+ tr.Root.Signed.Roles[role].KeyIDs = keep
+
+ // also, whichever role had keys removed needs to be re-signed
+ // root has already been marked dirty.
+ switch role {
+ case data.CanonicalSnapshotRole:
+ if tr.Snapshot != nil {
+ tr.Snapshot.Dirty = true
+ }
+ case data.CanonicalTargetsRole:
+ if target, ok := tr.Targets[data.CanonicalTargetsRole]; ok {
+ target.Dirty = true
+ }
+ case data.CanonicalTimestampRole:
+ if tr.Timestamp != nil {
+ tr.Timestamp.Dirty = true
+ }
+ }
+
+ // determine which keys are no longer in use by any roles
+ for roleName, r := range tr.Root.Signed.Roles {
+ if roleName == role {
+ continue
+ }
+ for _, rk := range r.KeyIDs {
+ if _, ok := toDelete[rk]; ok {
+ delete(toDelete, rk)
+ }
+ }
+ }
+
+ // Remove keys no longer in use by any roles, except for root keys.
+ // Root private keys must be kept in tr.cryptoService to be able to sign
+ // for rotation, and root certificates must be kept in tr.Root.SignedKeys
+ // because we are not necessarily storing them elsewhere (tuf.Repo does not
+ // depend on certs.Manager, that is an upper layer), and without storing
+ // the certificates in their x509 form we are not able to do the
+ // util.CanonicalKeyID conversion.
+ if role != data.CanonicalRootRole {
+ for k := range toDelete {
+ delete(tr.Root.Signed.Keys, k)
+ tr.cryptoService.RemoveKey(k)
+ }
+ }
+ tr.Root.Dirty = true
+ return nil
+}
+
+// GetBaseRole gets a base role from this repo's metadata
+func (tr *Repo) GetBaseRole(name string) (data.BaseRole, error) {
+ if !data.ValidRole(name) {
+ return data.BaseRole{}, data.ErrInvalidRole{Role: name, Reason: "invalid base role name"}
+ }
+ if tr.Root == nil {
+ return data.BaseRole{}, ErrNotLoaded{data.CanonicalRootRole}
+ }
+ // Find the role data public keys for the base role from TUF metadata
+ baseRole, err := tr.Root.BuildBaseRole(name)
+ if err != nil {
+ return data.BaseRole{}, err
+ }
+
+ return baseRole, nil
+}
+
+// GetDelegationRole gets a delegation role from this repo's metadata, walking from the targets role down to the delegation itself
+func (tr *Repo) GetDelegationRole(name string) (data.DelegationRole, error) {
+ if !data.IsDelegation(name) {
+ return data.DelegationRole{}, data.ErrInvalidRole{Role: name, Reason: "invalid delegation name"}
+ }
+ if tr.Root == nil {
+ return data.DelegationRole{}, ErrNotLoaded{data.CanonicalRootRole}
+ }
+ _, ok := tr.Root.Signed.Roles[data.CanonicalTargetsRole]
+ if !ok {
+ return data.DelegationRole{}, ErrNotLoaded{data.CanonicalTargetsRole}
+ }
+ // Traverse target metadata, down to delegation itself
+ // Get all public keys for the base role from TUF metadata
+ _, ok = tr.Targets[data.CanonicalTargetsRole]
+ if !ok {
+ return data.DelegationRole{}, ErrNotLoaded{data.CanonicalTargetsRole}
+ }
+
+ // Start with top level roles in targets. Walk the chain of ancestors
+ // until finding the desired role, or we run out of targets files to search.
+ var foundRole *data.DelegationRole
+ buildDelegationRoleVisitor := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
+ // Try to find the delegation and build a DelegationRole structure
+ for _, role := range tgt.Signed.Delegations.Roles {
+ if role.Name == name {
+ delgRole, err := tgt.BuildDelegationRole(name)
+ if err != nil {
+ return err
+ }
+ // Check all public key certificates in the role for expiry
+ // Currently we do not reject expired delegation keys but warn if they might expire soon or have already
+ for keyID, pubKey := range delgRole.Keys {
+ certFromKey, err := utils.LoadCertFromPEM(pubKey.Public())
+ if err != nil {
+ continue
+ }
+ if err := utils.ValidateCertificate(certFromKey, true); err != nil {
+ if _, ok := err.(data.ErrCertExpired); !ok {
+ // do not allow other invalid cert errors
+ return err
+ }
+ logrus.Warnf("error with delegation %s key ID %d: %s", delgRole.Name, keyID, err)
+ }
+ }
+ foundRole = &delgRole
+ return StopWalk{}
+ }
+ }
+ return nil
+ }
+
+ // Walk to the parent of this delegation, since that is where its role metadata exists
+ err := tr.WalkTargets("", path.Dir(name), buildDelegationRoleVisitor)
+ if err != nil {
+ return data.DelegationRole{}, err
+ }
+
+ // We never found the delegation. In the context of this repo it is considered
+ // invalid. N.B. it may be that it existed at one point but an ancestor has since
+ // been modified/removed.
+ if foundRole == nil {
+ return data.DelegationRole{}, data.ErrInvalidRole{Role: name, Reason: "delegation does not exist"}
+ }
+
+ return *foundRole, nil
+}
+
+// GetAllLoadedRoles returns a list of all role entries loaded in this TUF repo, could be empty
+func (tr *Repo) GetAllLoadedRoles() []*data.Role {
+ var res []*data.Role
+ if tr.Root == nil {
+ // if root isn't loaded, we should consider we have no loaded roles because we can't
+ // trust any other state that might be present
+ return res
+ }
+ for name, rr := range tr.Root.Signed.Roles {
+ res = append(res, &data.Role{
+ RootRole: *rr,
+ Name: name,
+ })
+ }
+ for _, delegate := range tr.Targets {
+ for _, r := range delegate.Signed.Delegations.Roles {
+ res = append(res, r)
+ }
+ }
+ return res
+}
+
+// Walk to parent, and either create or update this delegation. We can only create a new delegation if we're given keys
+// Ensure all updates are valid, by checking against parent ancestor paths and ensuring the keys meet the role threshold.
+func delegationUpdateVisitor(roleName string, addKeys data.KeyList, removeKeys, addPaths, removePaths []string, clearAllPaths bool, newThreshold int) walkVisitorFunc {
+ return func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
+ var err error
+ // Validate the changes underneath this restricted validRole for adding paths, reject invalid path additions
+ if len(addPaths) != len(data.RestrictDelegationPathPrefixes(validRole.Paths, addPaths)) {
+ return data.ErrInvalidRole{Role: roleName, Reason: "invalid paths to add to role"}
+ }
+ // Try to find the delegation and amend it using our changelist
+ var delgRole *data.Role
+ for _, role := range tgt.Signed.Delegations.Roles {
+ if role.Name == roleName {
+ // Make a copy and operate on this role until we validate the changes
+ keyIDCopy := make([]string, len(role.KeyIDs))
+ copy(keyIDCopy, role.KeyIDs)
+ pathsCopy := make([]string, len(role.Paths))
+ copy(pathsCopy, role.Paths)
+ delgRole = &data.Role{
+ RootRole: data.RootRole{
+ KeyIDs: keyIDCopy,
+ Threshold: role.Threshold,
+ },
+ Name: role.Name,
+ Paths: pathsCopy,
+ }
+ delgRole.RemovePaths(removePaths)
+ if clearAllPaths {
+ delgRole.Paths = []string{}
+ }
+ delgRole.AddPaths(addPaths)
+ delgRole.RemoveKeys(removeKeys)
+ break
+ }
+ }
+ // We didn't find the role earlier, so create it.
+ if addKeys == nil {
+ addKeys = data.KeyList{} // initialize to empty list if necessary so calling .IDs() below won't panic
+ }
+ if delgRole == nil {
+ delgRole, err = data.NewRole(roleName, newThreshold, addKeys.IDs(), addPaths)
+ if err != nil {
+ return err
+ }
+
+ }
+ // Add the key IDs to the role and the keys themselves to the parent
+ for _, k := range addKeys {
+ if !utils.StrSliceContains(delgRole.KeyIDs, k.ID()) {
+ delgRole.KeyIDs = append(delgRole.KeyIDs, k.ID())
+ }
+ }
+ // Make sure we have a valid role still
+ if len(delgRole.KeyIDs) < delgRole.Threshold {
+ logrus.Warnf("role %s has fewer keys than its threshold of %d; it will not be usable until keys are added to it", delgRole.Name, delgRole.Threshold)
+ }
+ // NOTE: this closure CANNOT error after this point, as we've committed to editing the SignedTargets metadata in the repo object.
+ // Any errors related to updating this delegation must occur before this point.
+ // If all of our changes were valid, we should edit the actual SignedTargets to match our copy
+ for _, k := range addKeys {
+ tgt.Signed.Delegations.Keys[k.ID()] = k
+ }
+ foundAt := utils.FindRoleIndex(tgt.Signed.Delegations.Roles, delgRole.Name)
+ if foundAt < 0 {
+ tgt.Signed.Delegations.Roles = append(tgt.Signed.Delegations.Roles, delgRole)
+ } else {
+ tgt.Signed.Delegations.Roles[foundAt] = delgRole
+ }
+ tgt.Dirty = true
+ utils.RemoveUnusedKeys(tgt)
+ return StopWalk{}
+ }
+}
+
+// UpdateDelegationKeys updates the appropriate delegations, either adding
+// a new delegation or updating an existing one. If keys are
+// provided, the IDs will be added to the role (if they do not exist
+// there already), and the keys will be added to the targets file.
+func (tr *Repo) UpdateDelegationKeys(roleName string, addKeys data.KeyList, removeKeys []string, newThreshold int) error {
+ if !data.IsDelegation(roleName) {
+ return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"}
+ }
+ parent := path.Dir(roleName)
+
+ if err := tr.VerifyCanSign(parent); err != nil {
+ return err
+ }
+
+ // check the parent role's metadata
+ _, ok := tr.Targets[parent]
+ if !ok { // the parent targetfile may not exist yet - if not, then create it
+ var err error
+ _, err = tr.InitTargets(parent)
+ if err != nil {
+ return err
+ }
+ }
+
+ // Walk to the parent of this delegation, since that is where its role metadata exists
+ // We do not have to verify that the walker reached its desired role in this scenario
+ // since we've already done another walk to the parent role in VerifyCanSign, and potentially made a targets file
+ return tr.WalkTargets("", parent, delegationUpdateVisitor(roleName, addKeys, removeKeys, []string{}, []string{}, false, newThreshold))
+}
+
+// PurgeDelegationKeys removes the provided canonical key IDs from all delegations
+// present in the subtree rooted at role. The role argument must be provided in a wildcard
+// format, i.e. targets/* would remove the key from all delegations in the repo
+func (tr *Repo) PurgeDelegationKeys(role string, removeKeys []string) error {
+ if !data.IsWildDelegation(role) {
+ return data.ErrInvalidRole{
+ Role: role,
+ Reason: "only wildcard roles can be used in a purge",
+ }
+ }
+
+ removeIDs := make(map[string]struct{})
+ for _, id := range removeKeys {
+ removeIDs[id] = struct{}{}
+ }
+
+ start := path.Dir(role)
+ tufIDToCanon := make(map[string]string)
+
+ purgeKeys := func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
+ var (
+ deleteCandidates []string
+ err error
+ )
+ for id, key := range tgt.Signed.Delegations.Keys {
+ var (
+ canonID string
+ ok bool
+ )
+ if canonID, ok = tufIDToCanon[id]; !ok {
+ canonID, err = utils.CanonicalKeyID(key)
+ if err != nil {
+ return err
+ }
+ tufIDToCanon[id] = canonID
+ }
+ if _, ok := removeIDs[canonID]; ok {
+ deleteCandidates = append(deleteCandidates, id)
+ }
+ }
+ if len(deleteCandidates) == 0 {
+ // none of the interesting keys were present. We're done with this role
+ return nil
+ }
+ // now we know there are changes, check if we'll be able to sign them in
+ if err := tr.VerifyCanSign(validRole.Name); err != nil {
+ logrus.Warnf(
+ "role %s contains keys being purged but you do not have the necessary keys present to sign it; keys will not be purged from %s or its immediate children",
+ validRole.Name,
+ validRole.Name,
+ )
+ return nil
+ }
+ // we know we can sign in the changes, delete the keys
+ for _, id := range deleteCandidates {
+ delete(tgt.Signed.Delegations.Keys, id)
+ }
+ // delete candidate keys from all roles.
+ for _, role := range tgt.Signed.Delegations.Roles {
+ role.RemoveKeys(deleteCandidates)
+ if len(role.KeyIDs) < role.Threshold {
+ logrus.Warnf("role %s has fewer keys than its threshold of %d; it will not be usable until keys are added to it", role.Name, role.Threshold)
+ }
+ }
+ tgt.Dirty = true
+ return nil
+ }
+ return tr.WalkTargets("", start, purgeKeys)
+}
+
+// UpdateDelegationPaths updates the appropriate delegation's paths.
+// It is not allowed to create a new delegation.
+func (tr *Repo) UpdateDelegationPaths(roleName string, addPaths, removePaths []string, clearPaths bool) error {
+ if !data.IsDelegation(roleName) {
+ return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"}
+ }
+ parent := path.Dir(roleName)
+
+ if err := tr.VerifyCanSign(parent); err != nil {
+ return err
+ }
+
+ // check the parent role's metadata
+ _, ok := tr.Targets[parent]
+ if !ok { // the parent targetfile may not exist yet
+ // if not, this is an error because a delegation must exist to edit only paths
+ return data.ErrInvalidRole{Role: roleName, Reason: "no valid delegated role exists"}
+ }
+
+ // Walk to the parent of this delegation, since that is where its role metadata exists
+ // We do not have to verify that the walker reached its desired role in this scenario
+ // since we've already done another walk to the parent role in VerifyCanSign
+ err := tr.WalkTargets("", parent, delegationUpdateVisitor(roleName, data.KeyList{}, []string{}, addPaths, removePaths, clearPaths, notary.MinThreshold))
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+// DeleteDelegation removes a delegated targets role from its parent
+// targets object. It also deletes the delegation from the snapshot.
+// DeleteDelegation will only make use of the role Name field.
+func (tr *Repo) DeleteDelegation(roleName string) error {
+ if !data.IsDelegation(roleName) {
+ return data.ErrInvalidRole{Role: roleName, Reason: "not a valid delegated role"}
+ }
+
+ parent := path.Dir(roleName)
+ if err := tr.VerifyCanSign(parent); err != nil {
+ return err
+ }
+
+ // delete delegated data from Targets map and Snapshot - if they don't
+ // exist, these are no-op
+ delete(tr.Targets, roleName)
+ tr.Snapshot.DeleteMeta(roleName)
+
+ p, ok := tr.Targets[parent]
+ if !ok {
+ // if there is no parent metadata (the role exists though), then this
+ // is as good as done.
+ return nil
+ }
+
+ foundAt := utils.FindRoleIndex(p.Signed.Delegations.Roles, roleName)
+
+ if foundAt >= 0 {
+ var roles []*data.Role
+ // slice out deleted role
+ roles = append(roles, p.Signed.Delegations.Roles[:foundAt]...)
+ if foundAt+1 < len(p.Signed.Delegations.Roles) {
+ roles = append(roles, p.Signed.Delegations.Roles[foundAt+1:]...)
+ }
+ p.Signed.Delegations.Roles = roles
+
+ utils.RemoveUnusedKeys(p)
+
+ p.Dirty = true
+ } // if the role wasn't found, it's a good as deleted
+
+ return nil
+}
+
+// InitRoot initializes an empty root file with the 4 core roles passed to the
+// method, and the consistent flag.
+func (tr *Repo) InitRoot(root, timestamp, snapshot, targets data.BaseRole, consistent bool) error {
+ rootRoles := make(map[string]*data.RootRole)
+ rootKeys := make(map[string]data.PublicKey)
+
+ for _, r := range []data.BaseRole{root, timestamp, snapshot, targets} {
+ rootRoles[r.Name] = &data.RootRole{
+ Threshold: r.Threshold,
+ KeyIDs: r.ListKeyIDs(),
+ }
+ for kid, k := range r.Keys {
+ rootKeys[kid] = k
+ }
+ }
+ r, err := data.NewRoot(rootKeys, rootRoles, consistent)
+ if err != nil {
+ return err
+ }
+ tr.Root = r
+ tr.originalRootRole = root
+ return nil
+}
+
+// InitTargets initializes an empty targets, and returns the new empty target
+func (tr *Repo) InitTargets(role string) (*data.SignedTargets, error) {
+ if !data.IsDelegation(role) && role != data.CanonicalTargetsRole {
+ return nil, data.ErrInvalidRole{
+ Role: role,
+ Reason: fmt.Sprintf("role is not a valid targets role name: %s", role),
+ }
+ }
+ targets := data.NewTargets()
+ tr.Targets[role] = targets
+ return targets, nil
+}
+
+// InitSnapshot initializes a snapshot based on the current root and targets
+func (tr *Repo) InitSnapshot() error {
+ if tr.Root == nil {
+ return ErrNotLoaded{Role: data.CanonicalRootRole}
+ }
+ root, err := tr.Root.ToSigned()
+ if err != nil {
+ return err
+ }
+
+ if _, ok := tr.Targets[data.CanonicalTargetsRole]; !ok {
+ return ErrNotLoaded{Role: data.CanonicalTargetsRole}
+ }
+ targets, err := tr.Targets[data.CanonicalTargetsRole].ToSigned()
+ if err != nil {
+ return err
+ }
+ snapshot, err := data.NewSnapshot(root, targets)
+ if err != nil {
+ return err
+ }
+ tr.Snapshot = snapshot
+ return nil
+}
+
+// InitTimestamp initializes a timestamp based on the current snapshot
+func (tr *Repo) InitTimestamp() error {
+ snap, err := tr.Snapshot.ToSigned()
+ if err != nil {
+ return err
+ }
+ timestamp, err := data.NewTimestamp(snap)
+ if err != nil {
+ return err
+ }
+
+ tr.Timestamp = timestamp
+ return nil
+}
+
+// TargetMeta returns the FileMeta entry for the given path in the
+// targets file associated with the given role. This may be nil if
+// the target isn't found in the targets file.
+func (tr Repo) TargetMeta(role, path string) *data.FileMeta {
+ if t, ok := tr.Targets[role]; ok {
+ if m, ok := t.Signed.Targets[path]; ok {
+ return &m
+ }
+ }
+ return nil
+}
+
+// TargetDelegations returns a slice of Roles that are valid publishers
+// for the target path provided.
+func (tr Repo) TargetDelegations(role, path string) []*data.Role {
+ var roles []*data.Role
+ if t, ok := tr.Targets[role]; ok {
+ for _, r := range t.Signed.Delegations.Roles {
+ if r.CheckPaths(path) {
+ roles = append(roles, r)
+ }
+ }
+ }
+ return roles
+}
+
+// VerifyCanSign returns nil if the role exists and we have at least one
+// signing key for the role, false otherwise. This does not check that we have
+// enough signing keys to meet the threshold, since we want to support the use
+// case of multiple signers for a role. It returns an error if the role doesn't
+// exist or if there are no signing keys.
+func (tr *Repo) VerifyCanSign(roleName string) error {
+ var (
+ role data.BaseRole
+ err error
+ canonicalKeyIDs []string
+ )
+ // we only need the BaseRole part of a delegation because we're just
+ // checking KeyIDs
+ if data.IsDelegation(roleName) {
+ r, err := tr.GetDelegationRole(roleName)
+ if err != nil {
+ return err
+ }
+ role = r.BaseRole
+ } else {
+ role, err = tr.GetBaseRole(roleName)
+ }
+ if err != nil {
+ return data.ErrInvalidRole{Role: roleName, Reason: "does not exist"}
+ }
+
+ for keyID, k := range role.Keys {
+ check := []string{keyID}
+ if canonicalID, err := utils.CanonicalKeyID(k); err == nil {
+ check = append(check, canonicalID)
+ canonicalKeyIDs = append(canonicalKeyIDs, canonicalID)
+ }
+ for _, id := range check {
+ p, _, err := tr.cryptoService.GetPrivateKey(id)
+ if err == nil && p != nil {
+ return nil
+ }
+ }
+ }
+ return signed.ErrNoKeys{KeyIDs: canonicalKeyIDs}
+}
+
+// used for walking the targets/delegations tree, potentially modifying the underlying SignedTargets for the repo
+type walkVisitorFunc func(*data.SignedTargets, data.DelegationRole) interface{}
+
+// WalkTargets will apply the specified visitor function to iteratively walk the targets/delegation metadata tree,
+// until receiving a StopWalk. The walk starts from the base "targets" role, and searches for the correct targetPath and/or rolePath
+// to call the visitor function on. Any roles passed into skipRoles will be excluded from the walk, as well as roles in those subtrees
+func (tr *Repo) WalkTargets(targetPath, rolePath string, visitTargets walkVisitorFunc, skipRoles ...string) error {
+ // Start with the base targets role, which implicitly has the "" targets path
+ targetsRole, err := tr.GetBaseRole(data.CanonicalTargetsRole)
+ if err != nil {
+ return err
+ }
+ // Make the targets role have the empty path, when we treat it as a delegation role
+ roles := []data.DelegationRole{
+ {
+ BaseRole: targetsRole,
+ Paths: []string{""},
+ },
+ }
+
+ for len(roles) > 0 {
+ role := roles[0]
+ roles = roles[1:]
+
+ // Check the role metadata
+ signedTgt, ok := tr.Targets[role.Name]
+ if !ok {
+ // The role meta doesn't exist in the repo so continue onward
+ continue
+ }
+
+ // We're at a prefix of the desired role subtree, so add its delegation role children and continue walking
+ if strings.HasPrefix(rolePath, role.Name+"/") {
+ roles = append(roles, signedTgt.GetValidDelegations(role)...)
+ continue
+ }
+
+ // Determine whether to visit this role or not:
+ // If the paths validate against the specified targetPath and the rolePath is empty or is in the subtree.
+ // Also check if we are choosing to skip visiting this role on this walk (see ListTargets and GetTargetByName priority)
+ if isValidPath(targetPath, role) && isAncestorRole(role.Name, rolePath) && !utils.StrSliceContains(skipRoles, role.Name) {
+ // If we had matching path or role name, visit this target and determine whether or not to keep walking
+ res := visitTargets(signedTgt, role)
+ switch typedRes := res.(type) {
+ case StopWalk:
+ // If the visitor function signalled a stop, return nil to finish the walk
+ return nil
+ case nil:
+ // If the visitor function signalled to continue, add this role's delegation to the walk
+ roles = append(roles, signedTgt.GetValidDelegations(role)...)
+ case error:
+ // Propagate any errors from the visitor
+ return typedRes
+ default:
+ // Return out with an error if we got a different result
+ return fmt.Errorf("unexpected return while walking: %v", res)
+ }
+
+ }
+ }
+ return nil
+}
+
+// helper function that returns whether the candidateChild role name is an ancestor or equal to the candidateAncestor role name
+// Will return true if given an empty candidateAncestor role name
+// The HasPrefix check is for determining whether the role name for candidateChild is a child (direct or further down the chain)
+// of candidateAncestor, for ex: candidateAncestor targets/a and candidateChild targets/a/b/c
+func isAncestorRole(candidateChild, candidateAncestor string) bool {
+ return candidateAncestor == "" || candidateAncestor == candidateChild || strings.HasPrefix(candidateChild, candidateAncestor+"/")
+}
+
+// helper function that returns whether the delegation Role is valid against the given path
+// Will return true if given an empty candidatePath
+func isValidPath(candidatePath string, delgRole data.DelegationRole) bool {
+ return candidatePath == "" || delgRole.CheckPaths(candidatePath)
+}
+
+// AddTargets will attempt to add the given targets specifically to
+// the directed role. If the metadata for the role doesn't exist yet,
+// AddTargets will create one.
+func (tr *Repo) AddTargets(role string, targets data.Files) (data.Files, error) {
+ err := tr.VerifyCanSign(role)
+ if err != nil {
+ return nil, err
+ }
+
+ // check existence of the role's metadata
+ _, ok := tr.Targets[role]
+ if !ok { // the targetfile may not exist yet - if not, then create it
+ var err error
+ _, err = tr.InitTargets(role)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ addedTargets := make(data.Files)
+ addTargetVisitor := func(targetPath string, targetMeta data.FileMeta) func(*data.SignedTargets, data.DelegationRole) interface{} {
+ return func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
+ // We've already validated the role's target path in our walk, so just modify the metadata
+ tgt.Signed.Targets[targetPath] = targetMeta
+ tgt.Dirty = true
+ // Also add to our new addedTargets map to keep track of every target we've added successfully
+ addedTargets[targetPath] = targetMeta
+ return StopWalk{}
+ }
+ }
+
+ // Walk the role tree while validating the target paths, and add all of our targets
+ for path, target := range targets {
+ tr.WalkTargets(path, role, addTargetVisitor(path, target))
+ }
+ if len(addedTargets) != len(targets) {
+ return nil, fmt.Errorf("Could not add all targets")
+ }
+ return nil, nil
+}
+
+// RemoveTargets removes the given target (paths) from the given target role (delegation)
+func (tr *Repo) RemoveTargets(role string, targets ...string) error {
+ if err := tr.VerifyCanSign(role); err != nil {
+ return err
+ }
+
+ removeTargetVisitor := func(targetPath string) func(*data.SignedTargets, data.DelegationRole) interface{} {
+ return func(tgt *data.SignedTargets, validRole data.DelegationRole) interface{} {
+ // We've already validated the role path in our walk, so just modify the metadata
+ // We don't check against the target path against the valid role paths because it's
+ // possible we got into an invalid state and are trying to fix it
+ delete(tgt.Signed.Targets, targetPath)
+ tgt.Dirty = true
+ return StopWalk{}
+ }
+ }
+
+ // if the role exists but metadata does not yet, then our work is done
+ _, ok := tr.Targets[role]
+ if ok {
+ for _, path := range targets {
+ tr.WalkTargets("", role, removeTargetVisitor(path))
+ }
+ }
+
+ return nil
+}
+
+// UpdateSnapshot updates the FileMeta for the given role based on the Signed object
+func (tr *Repo) UpdateSnapshot(role string, s *data.Signed) error {
+ jsonData, err := json.Marshal(s)
+ if err != nil {
+ return err
+ }
+ meta, err := data.NewFileMeta(bytes.NewReader(jsonData), data.NotaryDefaultHashes...)
+ if err != nil {
+ return err
+ }
+ tr.Snapshot.Signed.Meta[role] = meta
+ tr.Snapshot.Dirty = true
+ return nil
+}
+
+// UpdateTimestamp updates the snapshot meta in the timestamp based on the Signed object
+func (tr *Repo) UpdateTimestamp(s *data.Signed) error {
+ jsonData, err := json.Marshal(s)
+ if err != nil {
+ return err
+ }
+ meta, err := data.NewFileMeta(bytes.NewReader(jsonData), data.NotaryDefaultHashes...)
+ if err != nil {
+ return err
+ }
+ tr.Timestamp.Signed.Meta[data.CanonicalSnapshotRole] = meta
+ tr.Timestamp.Dirty = true
+ return nil
+}
+
+type versionedRootRole struct {
+ data.BaseRole
+ version int
+}
+
+type versionedRootRoles []versionedRootRole
+
+func (v versionedRootRoles) Len() int { return len(v) }
+func (v versionedRootRoles) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
+func (v versionedRootRoles) Less(i, j int) bool { return v[i].version < v[j].version }
+
+// SignRoot signs the root, using all keys from the "root" role (i.e. currently trusted)
+// as well as available keys used to sign the previous version, if the public part is
+// carried in tr.Root.Keys and the private key is available (i.e. probably previously
+// trusted keys, to allow rollover). If there are any errors, attempt to put root
+// back to the way it was (so version won't be incremented, for instance).
+func (tr *Repo) SignRoot(expires time.Time) (*data.Signed, error) {
+ logrus.Debug("signing root...")
+
+ // duplicate root and attempt to modify it rather than the existing root
+ rootBytes, err := tr.Root.MarshalJSON()
+ if err != nil {
+ return nil, err
+ }
+ tempRoot := data.SignedRoot{}
+ if err := json.Unmarshal(rootBytes, &tempRoot); err != nil {
+ return nil, err
+ }
+
+ currRoot, err := tr.GetBaseRole(data.CanonicalRootRole)
+ if err != nil {
+ return nil, err
+ }
+
+ oldRootRoles := tr.getOldRootRoles()
+
+ var latestSavedRole data.BaseRole
+ rolesToSignWith := make([]data.BaseRole, 0, len(oldRootRoles))
+
+ if len(oldRootRoles) > 0 {
+ sort.Sort(oldRootRoles)
+ for _, vRole := range oldRootRoles {
+ rolesToSignWith = append(rolesToSignWith, vRole.BaseRole)
+ }
+ latest := rolesToSignWith[len(rolesToSignWith)-1]
+ latestSavedRole = data.BaseRole{
+ Name: data.CanonicalRootRole,
+ Threshold: latest.Threshold,
+ Keys: latest.Keys,
+ }
+ }
+
+ // If the root role (root keys or root threshold) has changed, save the
+ // previous role under the role name "root.<n>", such that the "n" is the
+ // latest root.json version for which previous root role was valid.
+ // Also, guard against re-saving the previous role if the latest
+ // saved role is the same (which should not happen).
+ // n = root.json version of the originalRootRole (previous role)
+ // n+1 = root.json version of the currRoot (current role)
+ // n-m = root.json version of latestSavedRole (not necessarily n-1, because the
+ // last root rotation could have happened several root.json versions ago
+ if !tr.originalRootRole.Equals(currRoot) && !tr.originalRootRole.Equals(latestSavedRole) {
+ rolesToSignWith = append(rolesToSignWith, tr.originalRootRole)
+ latestSavedRole = tr.originalRootRole
+
+ versionName := oldRootVersionName(tempRoot.Signed.Version)
+ tempRoot.Signed.Roles[versionName] = &data.RootRole{
+ KeyIDs: latestSavedRole.ListKeyIDs(), Threshold: latestSavedRole.Threshold}
+ }
+
+ tempRoot.Signed.Expires = expires
+ tempRoot.Signed.Version++
+ rolesToSignWith = append(rolesToSignWith, currRoot)
+
+ signed, err := tempRoot.ToSigned()
+ if err != nil {
+ return nil, err
+ }
+ signed, err = tr.sign(signed, rolesToSignWith, tr.getOptionalRootKeys(rolesToSignWith))
+ if err != nil {
+ return nil, err
+ }
+
+ tr.Root = &tempRoot
+ tr.Root.Signatures = signed.Signatures
+ tr.originalRootRole = currRoot
+ return signed, nil
+}
+
+// get all the saved previous roles < the current root version
+func (tr *Repo) getOldRootRoles() versionedRootRoles {
+ oldRootRoles := make(versionedRootRoles, 0, len(tr.Root.Signed.Roles))
+
+ // now go through the old roles
+ for roleName := range tr.Root.Signed.Roles {
+ // ensure that the rolename matches our format and that the version is
+ // not too high
+ if data.ValidRole(roleName) {
+ continue
+ }
+ nameTokens := strings.Split(roleName, ".")
+ if len(nameTokens) != 2 || nameTokens[0] != data.CanonicalRootRole {
+ continue
+ }
+ version, err := strconv.Atoi(nameTokens[1])
+ if err != nil || version >= tr.Root.Signed.Version {
+ continue
+ }
+
+ // ignore invalid roles, which shouldn't happen
+ oldRole, err := tr.Root.BuildBaseRole(roleName)
+ if err != nil {
+ continue
+ }
+
+ oldRootRoles = append(oldRootRoles, versionedRootRole{BaseRole: oldRole, version: version})
+ }
+
+ return oldRootRoles
+}
+
+// gets any extra optional root keys from the existing root.json signatures
+// (because older repositories that have already done root rotation may not
+// necessarily have older root roles)
+func (tr *Repo) getOptionalRootKeys(signingRoles []data.BaseRole) []data.PublicKey {
+ oldKeysMap := make(map[string]data.PublicKey)
+ for _, oldSig := range tr.Root.Signatures {
+ if k, ok := tr.Root.Signed.Keys[oldSig.KeyID]; ok {
+ oldKeysMap[k.ID()] = k
+ }
+ }
+ for _, role := range signingRoles {
+ for keyID := range role.Keys {
+ delete(oldKeysMap, keyID)
+ }
+ }
+
+ oldKeys := make([]data.PublicKey, 0, len(oldKeysMap))
+ for _, key := range oldKeysMap {
+ oldKeys = append(oldKeys, key)
+ }
+
+ return oldKeys
+}
+
+func oldRootVersionName(version int) string {
+ return fmt.Sprintf("%s.%v", data.CanonicalRootRole, version)
+}
+
+// SignTargets signs the targets file for the given top level or delegated targets role
+func (tr *Repo) SignTargets(role string, expires time.Time) (*data.Signed, error) {
+ logrus.Debugf("sign targets called for role %s", role)
+ if _, ok := tr.Targets[role]; !ok {
+ return nil, data.ErrInvalidRole{
+ Role: role,
+ Reason: "SignTargets called with non-existent targets role",
+ }
+ }
+ tr.Targets[role].Signed.Expires = expires
+ tr.Targets[role].Signed.Version++
+ signed, err := tr.Targets[role].ToSigned()
+ if err != nil {
+ logrus.Debug("errored getting targets data.Signed object")
+ return nil, err
+ }
+
+ var targets data.BaseRole
+ if role == data.CanonicalTargetsRole {
+ targets, err = tr.GetBaseRole(role)
+ } else {
+ tr, err := tr.GetDelegationRole(role)
+ if err != nil {
+ return nil, err
+ }
+ targets = tr.BaseRole
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ signed, err = tr.sign(signed, []data.BaseRole{targets}, nil)
+ if err != nil {
+ logrus.Debug("errored signing ", role)
+ return nil, err
+ }
+ tr.Targets[role].Signatures = signed.Signatures
+ return signed, nil
+}
+
+// SignSnapshot updates the snapshot based on the current targets and root then signs it
+func (tr *Repo) SignSnapshot(expires time.Time) (*data.Signed, error) {
+ logrus.Debug("signing snapshot...")
+ signedRoot, err := tr.Root.ToSigned()
+ if err != nil {
+ return nil, err
+ }
+ err = tr.UpdateSnapshot(data.CanonicalRootRole, signedRoot)
+ if err != nil {
+ return nil, err
+ }
+ tr.Root.Dirty = false // root dirty until changes captures in snapshot
+ for role, targets := range tr.Targets {
+ signedTargets, err := targets.ToSigned()
+ if err != nil {
+ return nil, err
+ }
+ err = tr.UpdateSnapshot(role, signedTargets)
+ if err != nil {
+ return nil, err
+ }
+ targets.Dirty = false
+ }
+ tr.Snapshot.Signed.Expires = expires
+ tr.Snapshot.Signed.Version++
+ signed, err := tr.Snapshot.ToSigned()
+ if err != nil {
+ return nil, err
+ }
+ snapshot, err := tr.GetBaseRole(data.CanonicalSnapshotRole)
+ if err != nil {
+ return nil, err
+ }
+ signed, err = tr.sign(signed, []data.BaseRole{snapshot}, nil)
+ if err != nil {
+ return nil, err
+ }
+ tr.Snapshot.Signatures = signed.Signatures
+ return signed, nil
+}
+
+// SignTimestamp updates the timestamp based on the current snapshot then signs it
+func (tr *Repo) SignTimestamp(expires time.Time) (*data.Signed, error) {
+ logrus.Debug("SignTimestamp")
+ signedSnapshot, err := tr.Snapshot.ToSigned()
+ if err != nil {
+ return nil, err
+ }
+ err = tr.UpdateTimestamp(signedSnapshot)
+ if err != nil {
+ return nil, err
+ }
+ tr.Timestamp.Signed.Expires = expires
+ tr.Timestamp.Signed.Version++
+ signed, err := tr.Timestamp.ToSigned()
+ if err != nil {
+ return nil, err
+ }
+ timestamp, err := tr.GetBaseRole(data.CanonicalTimestampRole)
+ if err != nil {
+ return nil, err
+ }
+ signed, err = tr.sign(signed, []data.BaseRole{timestamp}, nil)
+ if err != nil {
+ return nil, err
+ }
+ tr.Timestamp.Signatures = signed.Signatures
+ tr.Snapshot.Dirty = false // snapshot is dirty until changes have been captured in timestamp
+ return signed, nil
+}
+
+func (tr Repo) sign(signedData *data.Signed, roles []data.BaseRole, optionalKeys []data.PublicKey) (*data.Signed, error) {
+ validKeys := optionalKeys
+ for _, r := range roles {
+ roleKeys := r.ListKeys()
+ validKeys = append(roleKeys, validKeys...)
+ if err := signed.Sign(tr.cryptoService, signedData, roleKeys, r.Threshold, validKeys); err != nil {
+ return nil, err
+ }
+ }
+ // Attempt to sign with the optional keys, but ignore any errors, because these keys are optional
+ signed.Sign(tr.cryptoService, signedData, optionalKeys, 0, validKeys)
+
+ return signedData, nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/utils/role_sort.go b/vendor/github.com/docker/notary/tuf/utils/role_sort.go
new file mode 100644
index 0000000..368925c
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/utils/role_sort.go
@@ -0,0 +1,31 @@
+package utils
+
+import (
+ "strings"
+)
+
+// RoleList is a list of roles
+type RoleList []string
+
+// Len returns the length of the list
+func (r RoleList) Len() int {
+ return len(r)
+}
+
+// Less returns true if the item at i should be sorted
+// before the item at j. It's an unstable partial ordering
+// based on the number of segments, separated by "/", in
+// the role name
+func (r RoleList) Less(i, j int) bool {
+ segsI := strings.Split(r[i], "/")
+ segsJ := strings.Split(r[j], "/")
+ if len(segsI) == len(segsJ) {
+ return r[i] < r[j]
+ }
+ return len(segsI) < len(segsJ)
+}
+
+// Swap the items at 2 locations in the list
+func (r RoleList) Swap(i, j int) {
+ r[i], r[j] = r[j], r[i]
+}
diff --git a/vendor/github.com/docker/notary/tuf/utils/stack.go b/vendor/github.com/docker/notary/tuf/utils/stack.go
new file mode 100644
index 0000000..e79b5c8
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/utils/stack.go
@@ -0,0 +1,85 @@
+package utils
+
+import (
+ "fmt"
+ "sync"
+)
+
+// ErrEmptyStack is used when an action that requires some
+// content is invoked and the stack is empty
+type ErrEmptyStack struct {
+ action string
+}
+
+func (err ErrEmptyStack) Error() string {
+ return fmt.Sprintf("attempted to %s with empty stack", err.action)
+}
+
+// ErrBadTypeCast is used by PopX functions when the item
+// cannot be typed to X
+type ErrBadTypeCast struct{}
+
+func (err ErrBadTypeCast) Error() string {
+ return "attempted to do a typed pop and item was not of type"
+}
+
+// Stack is a simple type agnostic stack implementation
+type Stack struct {
+ s []interface{}
+ l sync.Mutex
+}
+
+// NewStack create a new stack
+func NewStack() *Stack {
+ s := &Stack{
+ s: make([]interface{}, 0),
+ }
+ return s
+}
+
+// Push adds an item to the top of the stack.
+func (s *Stack) Push(item interface{}) {
+ s.l.Lock()
+ defer s.l.Unlock()
+ s.s = append(s.s, item)
+}
+
+// Pop removes and returns the top item on the stack, or returns
+// ErrEmptyStack if the stack has no content
+func (s *Stack) Pop() (interface{}, error) {
+ s.l.Lock()
+ defer s.l.Unlock()
+ l := len(s.s)
+ if l > 0 {
+ item := s.s[l-1]
+ s.s = s.s[:l-1]
+ return item, nil
+ }
+ return nil, ErrEmptyStack{action: "Pop"}
+}
+
+// PopString attempts to cast the top item on the stack to the string type.
+// If this succeeds, it removes and returns the top item. If the item
+// is not of the string type, ErrBadTypeCast is returned. If the stack
+// is empty, ErrEmptyStack is returned
+func (s *Stack) PopString() (string, error) {
+ s.l.Lock()
+ defer s.l.Unlock()
+ l := len(s.s)
+ if l > 0 {
+ item := s.s[l-1]
+ if item, ok := item.(string); ok {
+ s.s = s.s[:l-1]
+ return item, nil
+ }
+ return "", ErrBadTypeCast{}
+ }
+ return "", ErrEmptyStack{action: "PopString"}
+}
+
+// Empty returns true if the stack is empty
+func (s *Stack) Empty() bool {
+ s.l.Lock()
+ defer s.l.Unlock()
+ return len(s.s) == 0
+}
diff --git a/vendor/github.com/docker/notary/tuf/utils/utils.go b/vendor/github.com/docker/notary/tuf/utils/utils.go
new file mode 100644
index 0000000..8de72b6
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/utils/utils.go
@@ -0,0 +1,152 @@
+package utils
+
+import (
+ "crypto/sha256"
+ "crypto/sha512"
+ "crypto/tls"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+
+ "github.com/docker/notary/tuf/data"
+)
+
+// Download does a simple download from a URL
+func Download(url url.URL) (*http.Response, error) {
+ tr := &http.Transport{
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ }
+ client := &http.Client{Transport: tr}
+ return client.Get(url.String())
+}
+
+// Upload does a simple JSON upload to a URL
+func Upload(url string, body io.Reader) (*http.Response, error) {
+ tr := &http.Transport{
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ }
+ client := &http.Client{Transport: tr}
+ return client.Post(url, "application/json", body)
+}
+
+// StrSliceContains checks if the given string appears in the slice
+func StrSliceContains(ss []string, s string) bool {
+ for _, v := range ss {
+ if v == s {
+ return true
+ }
+ }
+ return false
+}
+
+// StrSliceRemove removes the the given string from the slice, returning a new slice
+func StrSliceRemove(ss []string, s string) []string {
+ res := []string{}
+ for _, v := range ss {
+ if v != s {
+ res = append(res, v)
+ }
+ }
+ return res
+}
+
+// StrSliceContainsI checks if the given string appears in the slice
+// in a case insensitive manner
+func StrSliceContainsI(ss []string, s string) bool {
+ s = strings.ToLower(s)
+ for _, v := range ss {
+ v = strings.ToLower(v)
+ if v == s {
+ return true
+ }
+ }
+ return false
+}
+
+// FileExists returns true if a file (or dir) exists at the given path,
+// false otherwise
+func FileExists(path string) bool {
+ _, err := os.Stat(path)
+ return os.IsNotExist(err)
+}
+
+// NoopCloser is a simple Reader wrapper that does nothing when Close is
+// called
+type NoopCloser struct {
+ io.Reader
+}
+
+// Close does nothing for a NoopCloser
+func (nc *NoopCloser) Close() error {
+ return nil
+}
+
+// DoHash returns the digest of d using the hashing algorithm named
+// in alg
+func DoHash(alg string, d []byte) []byte {
+ switch alg {
+ case "sha256":
+ digest := sha256.Sum256(d)
+ return digest[:]
+ case "sha512":
+ digest := sha512.Sum512(d)
+ return digest[:]
+ }
+ return nil
+}
+
+// UnusedDelegationKeys prunes a list of keys, returning those that are no
+// longer in use for a given targets file
+func UnusedDelegationKeys(t data.SignedTargets) []string {
+ // compare ids to all still active key ids in all active roles
+ // with the targets file
+ found := make(map[string]bool)
+ for _, r := range t.Signed.Delegations.Roles {
+ for _, id := range r.KeyIDs {
+ found[id] = true
+ }
+ }
+ var discard []string
+ for id := range t.Signed.Delegations.Keys {
+ if !found[id] {
+ discard = append(discard, id)
+ }
+ }
+ return discard
+}
+
+// RemoveUnusedKeys determines which keys in the slice of IDs are no longer
+// used in the given targets file and removes them from the delegated keys
+// map
+func RemoveUnusedKeys(t *data.SignedTargets) {
+ unusedIDs := UnusedDelegationKeys(*t)
+ for _, id := range unusedIDs {
+ delete(t.Signed.Delegations.Keys, id)
+ }
+}
+
+// FindRoleIndex returns the index of the role named <name> or -1 if no
+// matching role is found.
+func FindRoleIndex(rs []*data.Role, name string) int {
+ for i, r := range rs {
+ if r.Name == name {
+ return i
+ }
+ }
+ return -1
+}
+
+// ConsistentName generates the appropriate HTTP URL path for the role,
+// based on whether the repo is marked as consistent. The RemoteStore
+// is responsible for adding file extensions.
+func ConsistentName(role string, hashSha256 []byte) string {
+ if len(hashSha256) > 0 {
+ hash := hex.EncodeToString(hashSha256)
+ return fmt.Sprintf("%s.%s", role, hash)
+ }
+ return role
+}
diff --git a/vendor/github.com/docker/notary/tuf/utils/x509.go b/vendor/github.com/docker/notary/tuf/utils/x509.go
new file mode 100644
index 0000000..57624f6
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/utils/x509.go
@@ -0,0 +1,551 @@
+package utils
+
+import (
+ "bytes"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "math/big"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/agl/ed25519"
+ "github.com/docker/notary"
+ "github.com/docker/notary/tuf/data"
+)
+
+// CanonicalKeyID returns the ID of the public bytes version of a TUF key.
+// On regular RSA/ECDSA TUF keys, this is just the key ID. On X509 RSA/ECDSA
+// TUF keys, this is the key ID of the public key part of the key in the leaf cert
+func CanonicalKeyID(k data.PublicKey) (string, error) {
+ switch k.Algorithm() {
+ case data.ECDSAx509Key, data.RSAx509Key:
+ return X509PublicKeyID(k)
+ default:
+ return k.ID(), nil
+ }
+}
+
+// LoadCertFromPEM returns the first certificate found in a bunch of bytes or error
+// if nothing is found. Taken from https://golang.org/src/crypto/x509/cert_pool.go#L85.
+func LoadCertFromPEM(pemBytes []byte) (*x509.Certificate, error) {
+ for len(pemBytes) > 0 {
+ var block *pem.Block
+ block, pemBytes = pem.Decode(pemBytes)
+ if block == nil {
+ return nil, errors.New("no certificates found in PEM data")
+ }
+ if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
+ continue
+ }
+
+ cert, err := x509.ParseCertificate(block.Bytes)
+ if err != nil {
+ continue
+ }
+
+ return cert, nil
+ }
+
+ return nil, errors.New("no certificates found in PEM data")
+}
+
+// X509PublicKeyID returns a public key ID as a string, given a
+// data.PublicKey that contains an X509 Certificate
+func X509PublicKeyID(certPubKey data.PublicKey) (string, error) {
+ // Note that this only loads the first certificate from the public key
+ cert, err := LoadCertFromPEM(certPubKey.Public())
+ if err != nil {
+ return "", err
+ }
+ pubKeyBytes, err := x509.MarshalPKIXPublicKey(cert.PublicKey)
+ if err != nil {
+ return "", err
+ }
+
+ var key data.PublicKey
+ switch certPubKey.Algorithm() {
+ case data.ECDSAx509Key:
+ key = data.NewECDSAPublicKey(pubKeyBytes)
+ case data.RSAx509Key:
+ key = data.NewRSAPublicKey(pubKeyBytes)
+ }
+
+ return key.ID(), nil
+}
+
+// ParsePEMPrivateKey returns a data.PrivateKey from a PEM encoded private key. It
+// only supports RSA (PKCS#1) and attempts to decrypt using the passphrase, if encrypted.
+func ParsePEMPrivateKey(pemBytes []byte, passphrase string) (data.PrivateKey, error) {
+ block, _ := pem.Decode(pemBytes)
+ if block == nil {
+ return nil, errors.New("no valid private key found")
+ }
+
+ var privKeyBytes []byte
+ var err error
+ if x509.IsEncryptedPEMBlock(block) {
+ privKeyBytes, err = x509.DecryptPEMBlock(block, []byte(passphrase))
+ if err != nil {
+ return nil, errors.New("could not decrypt private key")
+ }
+ } else {
+ privKeyBytes = block.Bytes
+ }
+
+ switch block.Type {
+ case "RSA PRIVATE KEY":
+ rsaPrivKey, err := x509.ParsePKCS1PrivateKey(privKeyBytes)
+ if err != nil {
+ return nil, fmt.Errorf("could not parse DER encoded key: %v", err)
+ }
+
+ tufRSAPrivateKey, err := RSAToPrivateKey(rsaPrivKey)
+ if err != nil {
+ return nil, fmt.Errorf("could not convert rsa.PrivateKey to data.PrivateKey: %v", err)
+ }
+
+ return tufRSAPrivateKey, nil
+ case "EC PRIVATE KEY":
+ ecdsaPrivKey, err := x509.ParseECPrivateKey(privKeyBytes)
+ if err != nil {
+ return nil, fmt.Errorf("could not parse DER encoded private key: %v", err)
+ }
+
+ tufECDSAPrivateKey, err := ECDSAToPrivateKey(ecdsaPrivKey)
+ if err != nil {
+ return nil, fmt.Errorf("could not convert ecdsa.PrivateKey to data.PrivateKey: %v", err)
+ }
+
+ return tufECDSAPrivateKey, nil
+ case "ED25519 PRIVATE KEY":
+ // We serialize ED25519 keys by concatenating the private key
+ // to the public key and encoding with PEM. See the
+ // ED25519ToPrivateKey function.
+ tufECDSAPrivateKey, err := ED25519ToPrivateKey(privKeyBytes)
+ if err != nil {
+ return nil, fmt.Errorf("could not convert ecdsa.PrivateKey to data.PrivateKey: %v", err)
+ }
+
+ return tufECDSAPrivateKey, nil
+
+ default:
+ return nil, fmt.Errorf("unsupported key type %q", block.Type)
+ }
+}
+
+// CertToPEM is a utility function returns a PEM encoded x509 Certificate
+func CertToPEM(cert *x509.Certificate) []byte {
+ pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
+
+ return pemCert
+}
+
+// CertChainToPEM is a utility function returns a PEM encoded chain of x509 Certificates, in the order they are passed
+func CertChainToPEM(certChain []*x509.Certificate) ([]byte, error) {
+ var pemBytes bytes.Buffer
+ for _, cert := range certChain {
+ if err := pem.Encode(&pemBytes, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}); err != nil {
+ return nil, err
+ }
+ }
+ return pemBytes.Bytes(), nil
+}
+
+// LoadCertFromFile loads the first certificate from the file provided. The
+// data is expected to be PEM Encoded and contain one of more certificates
+// with PEM type "CERTIFICATE"
+func LoadCertFromFile(filename string) (*x509.Certificate, error) {
+ certs, err := LoadCertBundleFromFile(filename)
+ if err != nil {
+ return nil, err
+ }
+ return certs[0], nil
+}
+
+// LoadCertBundleFromFile loads certificates from the []byte provided. The
+// data is expected to be PEM Encoded and contain one of more certificates
+// with PEM type "CERTIFICATE"
+func LoadCertBundleFromFile(filename string) ([]*x509.Certificate, error) {
+ b, err := ioutil.ReadFile(filename)
+ if err != nil {
+ return nil, err
+ }
+
+ return LoadCertBundleFromPEM(b)
+}
+
+// LoadCertBundleFromPEM loads certificates from the []byte provided. The
+// data is expected to be PEM Encoded and contain one of more certificates
+// with PEM type "CERTIFICATE"
+func LoadCertBundleFromPEM(pemBytes []byte) ([]*x509.Certificate, error) {
+ certificates := []*x509.Certificate{}
+ var block *pem.Block
+ block, pemBytes = pem.Decode(pemBytes)
+ for ; block != nil; block, pemBytes = pem.Decode(pemBytes) {
+ if block.Type == "CERTIFICATE" {
+ cert, err := x509.ParseCertificate(block.Bytes)
+ if err != nil {
+ return nil, err
+ }
+ certificates = append(certificates, cert)
+ } else {
+ return nil, fmt.Errorf("invalid pem block type: %s", block.Type)
+ }
+ }
+
+ if len(certificates) == 0 {
+ return nil, fmt.Errorf("no valid certificates found")
+ }
+
+ return certificates, nil
+}
+
+// GetLeafCerts parses a list of x509 Certificates and returns all of them
+// that aren't CA
+func GetLeafCerts(certs []*x509.Certificate) []*x509.Certificate {
+ var leafCerts []*x509.Certificate
+ for _, cert := range certs {
+ if cert.IsCA {
+ continue
+ }
+ leafCerts = append(leafCerts, cert)
+ }
+ return leafCerts
+}
+
+// GetIntermediateCerts parses a list of x509 Certificates and returns all of the
+// ones marked as a CA, to be used as intermediates
+func GetIntermediateCerts(certs []*x509.Certificate) []*x509.Certificate {
+ var intCerts []*x509.Certificate
+ for _, cert := range certs {
+ if cert.IsCA {
+ intCerts = append(intCerts, cert)
+ }
+ }
+ return intCerts
+}
+
+// ParsePEMPublicKey returns a data.PublicKey from a PEM encoded public key or certificate.
+func ParsePEMPublicKey(pubKeyBytes []byte) (data.PublicKey, error) {
+ pemBlock, _ := pem.Decode(pubKeyBytes)
+ if pemBlock == nil {
+ return nil, errors.New("no valid public key found")
+ }
+
+ switch pemBlock.Type {
+ case "CERTIFICATE":
+ cert, err := x509.ParseCertificate(pemBlock.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("could not parse provided certificate: %v", err)
+ }
+ err = ValidateCertificate(cert, true)
+ if err != nil {
+ return nil, fmt.Errorf("invalid certificate: %v", err)
+ }
+ return CertToKey(cert), nil
+ default:
+ return nil, fmt.Errorf("unsupported PEM block type %q, expected certificate", pemBlock.Type)
+ }
+}
+
+// ValidateCertificate returns an error if the certificate is not valid for notary
+// Currently this is only ensuring the public key has a large enough modulus if RSA,
+// using a non SHA1 signature algorithm, and an optional time expiry check
+func ValidateCertificate(c *x509.Certificate, checkExpiry bool) error {
+ if (c.NotBefore).After(c.NotAfter) {
+ return fmt.Errorf("certificate validity window is invalid")
+ }
+ // Can't have SHA1 sig algorithm
+ if c.SignatureAlgorithm == x509.SHA1WithRSA || c.SignatureAlgorithm == x509.DSAWithSHA1 || c.SignatureAlgorithm == x509.ECDSAWithSHA1 {
+ return fmt.Errorf("certificate with CN %s uses invalid SHA1 signature algorithm", c.Subject.CommonName)
+ }
+ // If we have an RSA key, make sure it's long enough
+ if c.PublicKeyAlgorithm == x509.RSA {
+ rsaKey, ok := c.PublicKey.(*rsa.PublicKey)
+ if !ok {
+ return fmt.Errorf("unable to parse RSA public key")
+ }
+ if rsaKey.N.BitLen() < notary.MinRSABitSize {
+ return fmt.Errorf("RSA bit length is too short")
+ }
+ }
+ if checkExpiry {
+ now := time.Now()
+ tomorrow := now.AddDate(0, 0, 1)
+ // Give one day leeway on creation "before" time, check "after" against today
+ if (tomorrow).Before(c.NotBefore) || now.After(c.NotAfter) {
+ return data.ErrCertExpired{CN: c.Subject.CommonName}
+ }
+ // If this certificate is expiring within 6 months, put out a warning
+ if (c.NotAfter).Before(time.Now().AddDate(0, 6, 0)) {
+ logrus.Warnf("certificate with CN %s is near expiry", c.Subject.CommonName)
+ }
+ }
+ return nil
+}
+
+// GenerateRSAKey generates an RSA private key and returns a TUF PrivateKey
+func GenerateRSAKey(random io.Reader, bits int) (data.PrivateKey, error) {
+ rsaPrivKey, err := rsa.GenerateKey(random, bits)
+ if err != nil {
+ return nil, fmt.Errorf("could not generate private key: %v", err)
+ }
+
+ tufPrivKey, err := RSAToPrivateKey(rsaPrivKey)
+ if err != nil {
+ return nil, err
+ }
+
+ logrus.Debugf("generated RSA key with keyID: %s", tufPrivKey.ID())
+
+ return tufPrivKey, nil
+}
+
+// RSAToPrivateKey converts an rsa.Private key to a TUF data.PrivateKey type
+func RSAToPrivateKey(rsaPrivKey *rsa.PrivateKey) (data.PrivateKey, error) {
+ // Get a DER-encoded representation of the PublicKey
+ rsaPubBytes, err := x509.MarshalPKIXPublicKey(&rsaPrivKey.PublicKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal public key: %v", err)
+ }
+
+ // Get a DER-encoded representation of the PrivateKey
+ rsaPrivBytes := x509.MarshalPKCS1PrivateKey(rsaPrivKey)
+
+ pubKey := data.NewRSAPublicKey(rsaPubBytes)
+ return data.NewRSAPrivateKey(pubKey, rsaPrivBytes)
+}
+
+// GenerateECDSAKey generates an ECDSA Private key and returns a TUF PrivateKey
+func GenerateECDSAKey(random io.Reader) (data.PrivateKey, error) {
+ ecdsaPrivKey, err := ecdsa.GenerateKey(elliptic.P256(), random)
+ if err != nil {
+ return nil, err
+ }
+
+ tufPrivKey, err := ECDSAToPrivateKey(ecdsaPrivKey)
+ if err != nil {
+ return nil, err
+ }
+
+ logrus.Debugf("generated ECDSA key with keyID: %s", tufPrivKey.ID())
+
+ return tufPrivKey, nil
+}
+
+// GenerateED25519Key generates an ED25519 private key and returns a TUF
+// PrivateKey. The serialization format we use is just the public key bytes
+// followed by the private key bytes
+func GenerateED25519Key(random io.Reader) (data.PrivateKey, error) {
+ pub, priv, err := ed25519.GenerateKey(random)
+ if err != nil {
+ return nil, err
+ }
+
+ var serialized [ed25519.PublicKeySize + ed25519.PrivateKeySize]byte
+ copy(serialized[:], pub[:])
+ copy(serialized[ed25519.PublicKeySize:], priv[:])
+
+ tufPrivKey, err := ED25519ToPrivateKey(serialized[:])
+ if err != nil {
+ return nil, err
+ }
+
+ logrus.Debugf("generated ED25519 key with keyID: %s", tufPrivKey.ID())
+
+ return tufPrivKey, nil
+}
+
+// ECDSAToPrivateKey converts an ecdsa.Private key to a TUF data.PrivateKey type
+func ECDSAToPrivateKey(ecdsaPrivKey *ecdsa.PrivateKey) (data.PrivateKey, error) {
+ // Get a DER-encoded representation of the PublicKey
+ ecdsaPubBytes, err := x509.MarshalPKIXPublicKey(&ecdsaPrivKey.PublicKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal public key: %v", err)
+ }
+
+ // Get a DER-encoded representation of the PrivateKey
+ ecdsaPrivKeyBytes, err := x509.MarshalECPrivateKey(ecdsaPrivKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal private key: %v", err)
+ }
+
+ pubKey := data.NewECDSAPublicKey(ecdsaPubBytes)
+ return data.NewECDSAPrivateKey(pubKey, ecdsaPrivKeyBytes)
+}
+
+// ED25519ToPrivateKey converts a serialized ED25519 key to a TUF
+// data.PrivateKey type
+func ED25519ToPrivateKey(privKeyBytes []byte) (data.PrivateKey, error) {
+ if len(privKeyBytes) != ed25519.PublicKeySize+ed25519.PrivateKeySize {
+ return nil, errors.New("malformed ed25519 private key")
+ }
+
+ pubKey := data.NewED25519PublicKey(privKeyBytes[:ed25519.PublicKeySize])
+ return data.NewED25519PrivateKey(*pubKey, privKeyBytes)
+}
+
+func blockType(k data.PrivateKey) (string, error) {
+ switch k.Algorithm() {
+ case data.RSAKey, data.RSAx509Key:
+ return "RSA PRIVATE KEY", nil
+ case data.ECDSAKey, data.ECDSAx509Key:
+ return "EC PRIVATE KEY", nil
+ case data.ED25519Key:
+ return "ED25519 PRIVATE KEY", nil
+ default:
+ return "", fmt.Errorf("algorithm %s not supported", k.Algorithm())
+ }
+}
+
+// KeyToPEM returns a PEM encoded key from a Private Key
+func KeyToPEM(privKey data.PrivateKey, role string) ([]byte, error) {
+ bt, err := blockType(privKey)
+ if err != nil {
+ return nil, err
+ }
+
+ headers := map[string]string{}
+ if role != "" {
+ headers = map[string]string{
+ "role": role,
+ }
+ }
+
+ block := &pem.Block{
+ Type: bt,
+ Headers: headers,
+ Bytes: privKey.Private(),
+ }
+
+ return pem.EncodeToMemory(block), nil
+}
+
+// EncryptPrivateKey returns an encrypted PEM key given a Privatekey
+// and a passphrase
+func EncryptPrivateKey(key data.PrivateKey, role, gun, passphrase string) ([]byte, error) {
+ bt, err := blockType(key)
+ if err != nil {
+ return nil, err
+ }
+
+ password := []byte(passphrase)
+ cipherType := x509.PEMCipherAES256
+
+ encryptedPEMBlock, err := x509.EncryptPEMBlock(rand.Reader,
+ bt,
+ key.Private(),
+ password,
+ cipherType)
+ if err != nil {
+ return nil, err
+ }
+
+ if encryptedPEMBlock.Headers == nil {
+ return nil, fmt.Errorf("unable to encrypt key - invalid PEM file produced")
+ }
+ encryptedPEMBlock.Headers["role"] = role
+
+ if gun != "" {
+ encryptedPEMBlock.Headers["gun"] = gun
+ }
+
+ return pem.EncodeToMemory(encryptedPEMBlock), nil
+}
+
+// ReadRoleFromPEM returns the value from the role PEM header, if it exists
+func ReadRoleFromPEM(pemBytes []byte) string {
+ pemBlock, _ := pem.Decode(pemBytes)
+ if pemBlock == nil || pemBlock.Headers == nil {
+ return ""
+ }
+ role, ok := pemBlock.Headers["role"]
+ if !ok {
+ return ""
+ }
+ return role
+}
+
+// CertToKey transforms a single input certificate into its corresponding
+// PublicKey
+func CertToKey(cert *x509.Certificate) data.PublicKey {
+ block := pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}
+ pemdata := pem.EncodeToMemory(&block)
+
+ switch cert.PublicKeyAlgorithm {
+ case x509.RSA:
+ return data.NewRSAx509PublicKey(pemdata)
+ case x509.ECDSA:
+ return data.NewECDSAx509PublicKey(pemdata)
+ default:
+ logrus.Debugf("Unknown key type parsed from certificate: %v", cert.PublicKeyAlgorithm)
+ return nil
+ }
+}
+
+// CertsToKeys transforms each of the input certificate chains into its corresponding
+// PublicKey
+func CertsToKeys(leafCerts map[string]*x509.Certificate, intCerts map[string][]*x509.Certificate) map[string]data.PublicKey {
+ keys := make(map[string]data.PublicKey)
+ for id, leafCert := range leafCerts {
+ if key, err := CertBundleToKey(leafCert, intCerts[id]); err == nil {
+ keys[key.ID()] = key
+ }
+ }
+ return keys
+}
+
+// CertBundleToKey creates a TUF key from a leaf certs and a list of
+// intermediates
+func CertBundleToKey(leafCert *x509.Certificate, intCerts []*x509.Certificate) (data.PublicKey, error) {
+ certBundle := []*x509.Certificate{leafCert}
+ certBundle = append(certBundle, intCerts...)
+ certChainPEM, err := CertChainToPEM(certBundle)
+ if err != nil {
+ return nil, err
+ }
+ var newKey data.PublicKey
+ // Use the leaf cert's public key algorithm for typing
+ switch leafCert.PublicKeyAlgorithm {
+ case x509.RSA:
+ newKey = data.NewRSAx509PublicKey(certChainPEM)
+ case x509.ECDSA:
+ newKey = data.NewECDSAx509PublicKey(certChainPEM)
+ default:
+ logrus.Debugf("Unknown key type parsed from certificate: %v", leafCert.PublicKeyAlgorithm)
+ return nil, x509.ErrUnsupportedAlgorithm
+ }
+ return newKey, nil
+}
+
+// NewCertificate returns an X509 Certificate following a template, given a GUN and validity interval.
+func NewCertificate(gun string, startTime, endTime time.Time) (*x509.Certificate, error) {
+ serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
+
+ serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate new certificate: %v", err)
+ }
+
+ return &x509.Certificate{
+ SerialNumber: serialNumber,
+ Subject: pkix.Name{
+ CommonName: gun,
+ },
+ NotBefore: startTime,
+ NotAfter: endTime,
+
+ KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning},
+ BasicConstraintsValid: true,
+ }, nil
+}
diff --git a/vendor/github.com/docker/notary/tuf/validation/errors.go b/vendor/github.com/docker/notary/tuf/validation/errors.go
new file mode 100644
index 0000000..6cca0df
--- /dev/null
+++ b/vendor/github.com/docker/notary/tuf/validation/errors.go
@@ -0,0 +1,126 @@
+package validation
+
+import (
+ "encoding/json"
+ "fmt"
+)
+
+// VALIDATION ERRORS
+
+// ErrValidation represents a general validation error
+type ErrValidation struct {
+ Msg string
+}
+
+func (err ErrValidation) Error() string {
+ return fmt.Sprintf("An error occurred during validation: %s", err.Msg)
+}
+
+// ErrBadHierarchy represents missing metadata. Currently: a missing snapshot
+// at this current time. When delegations are implemented it will also
+// represent a missing delegation parent
+type ErrBadHierarchy struct {
+ Missing string
+ Msg string
+}
+
+func (err ErrBadHierarchy) Error() string {
+ return fmt.Sprintf("Metadata hierarchy is incomplete: %s", err.Msg)
+}
+
+// ErrBadRoot represents a failure validating the root
+type ErrBadRoot struct {
+ Msg string
+}
+
+func (err ErrBadRoot) Error() string {
+ return fmt.Sprintf("The root metadata is invalid: %s", err.Msg)
+}
+
+// ErrBadTargets represents a failure to validate a targets (incl delegations)
+type ErrBadTargets struct {
+ Msg string
+}
+
+func (err ErrBadTargets) Error() string {
+ return fmt.Sprintf("The targets metadata is invalid: %s", err.Msg)
+}
+
+// ErrBadSnapshot represents a failure to validate the snapshot
+type ErrBadSnapshot struct {
+ Msg string
+}
+
+func (err ErrBadSnapshot) Error() string {
+ return fmt.Sprintf("The snapshot metadata is invalid: %s", err.Msg)
+}
+
+// END VALIDATION ERRORS
+
+// SerializableError is a struct that can be used to serialize an error as JSON
+type SerializableError struct {
+ Name string
+ Error error
+}
+
+// UnmarshalJSON attempts to unmarshal the error into the right type
+func (s *SerializableError) UnmarshalJSON(text []byte) (err error) {
+ var x struct{ Name string }
+ err = json.Unmarshal(text, &x)
+ if err != nil {
+ return
+ }
+ var theError error
+ switch x.Name {
+ case "ErrValidation":
+ var e struct{ Error ErrValidation }
+ err = json.Unmarshal(text, &e)
+ theError = e.Error
+ case "ErrBadHierarchy":
+ var e struct{ Error ErrBadHierarchy }
+ err = json.Unmarshal(text, &e)
+ theError = e.Error
+ case "ErrBadRoot":
+ var e struct{ Error ErrBadRoot }
+ err = json.Unmarshal(text, &e)
+ theError = e.Error
+ case "ErrBadTargets":
+ var e struct{ Error ErrBadTargets }
+ err = json.Unmarshal(text, &e)
+ theError = e.Error
+ case "ErrBadSnapshot":
+ var e struct{ Error ErrBadSnapshot }
+ err = json.Unmarshal(text, &e)
+ theError = e.Error
+ default:
+ err = fmt.Errorf("do not know how to unmarshal %s", x.Name)
+ return
+ }
+ if err != nil {
+ return
+ }
+ s.Name = x.Name
+ s.Error = theError
+ return nil
+}
+
+// NewSerializableError serializes one of the above errors into JSON
+func NewSerializableError(err error) (*SerializableError, error) {
+ // make sure it's one of our errors
+ var name string
+ switch err.(type) {
+ case ErrValidation:
+ name = "ErrValidation"
+ case ErrBadHierarchy:
+ name = "ErrBadHierarchy"
+ case ErrBadRoot:
+ name = "ErrBadRoot"
+ case ErrBadTargets:
+ name = "ErrBadTargets"
+ case ErrBadSnapshot:
+ name = "ErrBadSnapshot"
+ default:
+ return nil, fmt.Errorf("does not support serializing non-validation errors")
+ }
+ return &SerializableError{Name: name, Error: err}, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/LICENSE b/vendor/github.com/docker/swarmkit/LICENSE
new file mode 100644
index 0000000..8dada3e
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/docker/swarmkit/README.md b/vendor/github.com/docker/swarmkit/README.md
new file mode 100644
index 0000000..4900fe3
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/README.md
@@ -0,0 +1,327 @@
+# [SwarmKit](https://github.com/docker/swarmkit)
+
+[![GoDoc](https://godoc.org/github.com/docker/swarmkit?status.svg)](https://godoc.org/github.com/docker/swarmkit)
+[![Circle CI](https://circleci.com/gh/docker/swarmkit.svg?style=shield&circle-token=a7bf494e28963703a59de71cf19b73ad546058a7)](https://circleci.com/gh/docker/swarmkit)
+[![codecov.io](https://codecov.io/github/docker/swarmkit/coverage.svg?branch=master&token=LqD1dzTjsN)](https://codecov.io/github/docker/swarmkit?branch=master)
+[![Badge Badge](http://doyouevenbadge.com/github.com/docker/swarmkit)](http://doyouevenbadge.com/report/github.com/docker/swarmkit)
+
+*SwarmKit* is a toolkit for orchestrating distributed systems at any scale. It includes primitives for node discovery, raft-based consensus, task scheduling and more.
+
+Its main benefits are:
+
+- **Distributed**: *SwarmKit* uses the [Raft Consensus Algorithm](https://raft.github.io/) in order to coordinate and does not rely on a single point of failure to perform decisions.
+- **Secure**: Node communication and membership within a *Swarm* are secure out of the box. *SwarmKit* uses mutual TLS for node *authentication*, *role authorization* and *transport encryption*, automating both certificate issuance and rotation.
+- **Simple**: *SwarmKit* is operationally simple and minimizes infrastructure dependencies. It does not need an external database to operate.
+
+## Overview
+
+Machines running *SwarmKit* can be grouped together in order to form a *Swarm*, coordinating tasks with each other.
+Once a machine joins, it becomes a *Swarm Node*. Nodes can either be *worker* nodes or *manager* nodes.
+
+- **Worker Nodes** are responsible for running Tasks using an *Executor*. *SwarmKit* comes with a default *Docker Container Executor* that can be easily swapped out.
+- **Manager Nodes** on the other hand accept specifications from the user and are responsible for reconciling the desired state with the actual cluster state.
+
+An operator can dynamically update a Node's role by promoting a Worker to Manager or demoting a Manager to Worker.
+
+*Tasks* are organized in *Services*. A service is a higher level abstraction that allows the user to declare the desired state of a group of tasks.
+Services define what type of task should be created as well as how to execute them (e.g. run this many replicas at all times) and how to update them (e.g. rolling updates).
+
+## Features
+
+Some of *SwarmKit*'s main features are:
+
+- **Orchestration**
+
+ - **Desired State Reconciliation**: *SwarmKit* constantly compares the desired state against the current cluster state and reconciles the two if necessary. For instance, if a node fails, *SwarmKit* reschedules its tasks onto a different node.
+
+ - **Service Types**: There are different types of services. The project currently ships with two of them out of the box
+
+ - **Replicated Services** are scaled to the desired number of replicas.
+ - **Global Services** run one task on every available node in the cluster.
+
+ - **Configurable Updates**: At any time, you can change the value of one or more fields for a service. After you make the update, *SwarmKit* reconciles the desired state by ensuring all tasks are using the desired settings. By default, it performs a lockstep update - that is, update all tasks at the same time. This can be configured through different knobs:
+
+ - **Parallelism** defines how many updates can be performed at the same time.
+ - **Delay** sets the minimum delay between updates. *SwarmKit* will start by shutting down the previous task, bring up a new one, wait for it to transition to the *RUNNING* state *then* wait for the additional configured delay. Finally, it will move onto other tasks.
+
+ - **Restart Policies**: The orchestration layer monitors tasks and reacts to failures based on the specified policy. The operator can define restart conditions, delays and limits (maximum number of attempts in a given time window). *SwarmKit* can decide to restart a task on a different machine. This means that faulty nodes will gradually be drained of their tasks.
+
+- **Scheduling**
+
+ - **Resource Awareness**: *SwarmKit* is aware of resources available on nodes and will place tasks accordingly.
+ - **Constraints**: Operators can limit the set of nodes where a task can be scheduled by defining constraint expressions. Multiple constraints find nodes that satisfy every expression, i.e., an `AND` match. Constraints can match node attributes in the following table. Note that `engine.labels` are collected from Docker Engine with information like operating system, drivers, etc. `node.labels` are added by cluster administrators for operational purpose. For example, some nodes have security compliant labels to run tasks with compliant requirements.
+
+ | node attribute | matches | example |
+ |:------------- |:-------------| :-------------|
+ | node.id | node's ID | `node.id == 2ivku8v2gvtg4`|
+ | node.hostname | node's hostname | `node.hostname != node-2`|
+ | node.ip | node's IP address | `node.ip != 172.19.17.0/24`|
+ | node.role | node's manager or worker role | `node.role == manager`|
+ | node.platform.os | node's operating system | `node.platform.os == linux`|
+ | node.platform.arch | node's architecture | `node.platform.arch == x86_64`|
+ | node.labels | node's labels added by cluster admins | `node.labels.security == high`|
+ | engine.labels | Docker Engine's labels | `engine.labels.operatingsystem == ubuntu 14.04`|
+
+ - **Strategies**: The project currently ships with a *spread strategy* which will attempt to schedule tasks on the least loaded
+ nodes, provided they meet the constraints and resource requirements.
+
+- **Cluster Management**
+
+ - **State Store**: Manager nodes maintain a strongly consistent, replicated (Raft based) and extremely fast (in-memory reads) view of the cluster which allows them to make quick scheduling decisions while tolerating failures.
+ - **Topology Management**: Node roles (*Worker* / *Manager*) can be dynamically changed through API/CLI calls.
+ - **Node Management**: An operator can alter the desired availability of a node: Setting it to *Paused* will prevent any further tasks from being scheduled to it while *Drained* will have the same effect while also re-scheduling its tasks somewhere else (mostly for maintenance scenarios).
+
+- **Security**
+
+ - **Mutual TLS**: All nodes communicate with each other using mutual *TLS*. Swarm managers act as a *Root Certificate Authority*, issuing certificates to new nodes.
+ - **Token-based Join**: All nodes require a cryptographic token to join the swarm, which defines that node's role. Tokens can be rotated as often as desired without affecting already-joined nodes.
+ - **Certificate Rotation**: TLS Certificates are rotated and reloaded transparently on every node, allowing a user to set how frequently rotation should happen (the current default is 3 months, the minimum is 30 minutes).
+
+## Build
+
+Requirements:
+
+- Go 1.6 or higher
+- A [working golang](https://golang.org/doc/code.html) environment
+- [Protobuf 3.x or higher](https://developers.google.com/protocol-buffers/docs/downloads) to regenerate protocol buffer files (e.g. using `make generate`)
+
+*SwarmKit* is built in Go and leverages a standard project structure to work well with Go tooling.
+If you are new to Go, please see [BUILDING.md](BUILDING.md) for a more detailed guide.
+
+Once you have *SwarmKit* checked out in your `$GOPATH`, the `Makefile` can be used for common tasks.
+
+From the project root directory, run the following to build `swarmd` and `swarmctl`:
+
+```sh
+$ make binaries
+```
+
+## Test
+
+Before running tests for the first time, setup the tooling:
+
+```sh
+$ make setup
+```
+
+Then run:
+
+```sh
+$ make all
+```
+
+## Usage Examples
+
+### Setting up a Swarm
+
+These instructions assume that `swarmd` and `swarmctl` are in your PATH.
+
+(Before starting, make sure `/tmp/node-N` don't exist)
+
+Initialize the first node:
+
+```sh
+$ swarmd -d /tmp/node-1 --listen-control-api /tmp/node-1/swarm.sock --hostname node-1
+```
+
+Before joining cluster, the token should be fetched:
+
+```
+$ export SWARM_SOCKET=/tmp/node-1/swarm.sock
+$ swarmctl cluster inspect default
+ID : 87d2ecpg12dfonxp3g562fru1
+Name : default
+Orchestration settings:
+ Task history entries: 5
+Dispatcher settings:
+ Dispatcher heartbeat period: 5s
+Certificate Authority settings:
+ Certificate Validity Duration: 2160h0m0s
+ Join Tokens:
+ Worker: SWMTKN-1-3vi7ajem0jed8guusgvyl98nfg18ibg4pclify6wzac6ucrhg3-0117z3s2ytr6egmmnlr6gd37n
+ Manager: SWMTKN-1-3vi7ajem0jed8guusgvyl98nfg18ibg4pclify6wzac6ucrhg3-d1ohk84br3ph0njyexw0wdagx
+```
+
+In two additional terminals, join two nodes. From the example below, replace `127.0.0.1:4242`
+with the address of the first node, and use the `<Worker Token>` acquired above.
+In this example, the `<Worker Token>` is `SWMTKN-1-3vi7ajem0jed8guusgvyl98nfg18ibg4pclify6wzac6ucrhg3-0117z3s2ytr6egmmnlr6gd37n`.
+If the joining nodes run on the same host as `node-1`, select a different remote
+listening port, e.g., `--listen-remote-api 127.0.0.1:4343`.
+
+```sh
+$ swarmd -d /tmp/node-2 --hostname node-2 --join-addr 127.0.0.1:4242 --join-token <Worker Token>
+$ swarmd -d /tmp/node-3 --hostname node-3 --join-addr 127.0.0.1:4242 --join-token <Worker Token>
+```
+
+In a fourth terminal, use `swarmctl` to explore and control the cluster. Before
+running `swarmctl`, set the `SWARM_SOCKET` environment variable to the path of the
+manager socket that was specified in `--listen-control-api` when starting the
+manager.
+
+To list nodes:
+
+```
+$ export SWARM_SOCKET=/tmp/node-1/swarm.sock
+$ swarmctl node ls
+ID Name Membership Status Availability Manager Status
+-- ---- ---------- ------ ------------ --------------
+3x12fpoi36eujbdkgdnbvbi6r node-2 ACCEPTED READY ACTIVE
+4spl3tyipofoa2iwqgabsdcve node-1 ACCEPTED READY ACTIVE REACHABLE *
+dknwk1uqxhnyyujq66ho0h54t node-3 ACCEPTED READY ACTIVE
+
+
+```
+
+### Creating Services
+
+Start a *redis* service:
+
+```
+$ swarmctl service create --name redis --image redis:3.0.5
+08ecg7vc7cbf9k57qs722n2le
+```
+
+List the running services:
+
+```
+$ swarmctl service ls
+ID Name Image Replicas
+-- ---- ----- --------
+08ecg7vc7cbf9k57qs722n2le redis redis:3.0.5 1/1
+```
+
+Inspect the service:
+
+```
+$ swarmctl service inspect redis
+ID : 08ecg7vc7cbf9k57qs722n2le
+Name : redis
+Replicas : 1/1
+Template
+ Container
+ Image : redis:3.0.5
+
+Task ID Service Slot Image Desired State Last State Node
+------- ------- ---- ----- ------------- ---------- ----
+0xk1ir8wr85lbs8sqg0ug03vr redis 1 redis:3.0.5 RUNNING RUNNING 1 minutes ago node-1
+```
+
+### Updating Services
+
+You can update any attribute of a service.
+
+For example, you can scale the service by changing the instance count:
+
+```
+$ swarmctl service update redis --replicas 6
+08ecg7vc7cbf9k57qs722n2le
+
+$ swarmctl service inspect redis
+ID : 08ecg7vc7cbf9k57qs722n2le
+Name : redis
+Replicas : 6/6
+Template
+ Container
+ Image : redis:3.0.5
+
+Task ID Service Slot Image Desired State Last State Node
+------- ------- ---- ----- ------------- ---------- ----
+0xk1ir8wr85lbs8sqg0ug03vr redis 1 redis:3.0.5 RUNNING RUNNING 3 minutes ago node-1
+25m48y9fevrnh77til1d09vqq redis 2 redis:3.0.5 RUNNING RUNNING 28 seconds ago node-3
+42vwc8z93c884anjgpkiatnx6 redis 3 redis:3.0.5 RUNNING RUNNING 28 seconds ago node-2
+d41f3wnf9dex3mk6jfqp4tdjw redis 4 redis:3.0.5 RUNNING RUNNING 28 seconds ago node-2
+66lefnooz63met6yfrsk6myvg redis 5 redis:3.0.5 RUNNING RUNNING 28 seconds ago node-1
+3a2sawtoyk19wqhmtuiq7z9pt redis 6 redis:3.0.5 RUNNING RUNNING 28 seconds ago node-3
+```
+
+Changing *replicas* from *1* to *6* forced *SwarmKit* to create *5* additional Tasks in order to
+comply with the desired state.
+
+Every other field can be changed as well, such as image, args, env, ...
+
+Let's change the image from *redis:3.0.5* to *redis:3.0.6* (e.g. upgrade):
+
+```
+$ swarmctl service update redis --image redis:3.0.6
+08ecg7vc7cbf9k57qs722n2le
+
+$ swarmctl service inspect redis
+ID : 08ecg7vc7cbf9k57qs722n2le
+Name : redis
+Replicas : 6/6
+Update Status
+ State : COMPLETED
+ Started : 3 minutes ago
+ Completed : 1 minute ago
+ Message : update completed
+Template
+ Container
+ Image : redis:3.0.6
+
+Task ID Service Slot Image Desired State Last State Node
+------- ------- ---- ----- ------------- ---------- ----
+0udsjss61lmwz52pke5hd107g redis 1 redis:3.0.6 RUNNING RUNNING 1 minute ago node-3
+b8o394v840thk10tamfqlwztb redis 2 redis:3.0.6 RUNNING RUNNING 1 minute ago node-1
+efw7j66xqpoj3cn3zjkdrwff7 redis 3 redis:3.0.6 RUNNING RUNNING 1 minute ago node-3
+8ajeipzvxucs3776e4z8gemey redis 4 redis:3.0.6 RUNNING RUNNING 1 minute ago node-2
+f05f2lbqzk9fh4kstwpulygvu redis 5 redis:3.0.6 RUNNING RUNNING 1 minute ago node-2
+7sbpoy82deq7hu3q9cnucfin6 redis 6 redis:3.0.6 RUNNING RUNNING 1 minute ago node-1
+```
+
+By default, all tasks are updated at the same time.
+
+This behavior can be changed by defining update options.
+
+For instance, in order to update tasks 2 at a time and wait at least 10 seconds between updates:
+
+```
+$ swarmctl service update redis --image redis:3.0.7 --update-parallelism 2 --update-delay 10s
+$ watch -n1 "swarmctl service inspect redis" # watch the update
+```
+
+This will update 2 tasks, wait for them to become *RUNNING*, then wait an additional 10 seconds before moving to other tasks.
+
+Update options can be set at service creation and updated later on. If an update command doesn't specify update options, the last set of options will be used.
+
+### Node Management
+
+*SwarmKit* monitors node health. In the case of node failures, it re-schedules tasks to other nodes.
+
+An operator can manually define the *Availability* of a node and can *Pause* and *Drain* nodes.
+
+Let's put `node-1` into maintenance mode:
+
+```
+$ swarmctl node drain node-1
+
+$ swarmctl node ls
+ID Name Membership Status Availability Manager Status
+-- ---- ---------- ------ ------------ --------------
+3x12fpoi36eujbdkgdnbvbi6r node-2 ACCEPTED READY ACTIVE
+4spl3tyipofoa2iwqgabsdcve node-1 ACCEPTED READY DRAIN REACHABLE *
+dknwk1uqxhnyyujq66ho0h54t node-3 ACCEPTED READY ACTIVE
+
+$ swarmctl service inspect redis
+ID : 08ecg7vc7cbf9k57qs722n2le
+Name : redis
+Replicas : 6/6
+Update Status
+ State : COMPLETED
+ Started : 2 minutes ago
+ Completed : 1 minute ago
+ Message : update completed
+Template
+ Container
+ Image : redis:3.0.7
+
+Task ID Service Slot Image Desired State Last State Node
+------- ------- ---- ----- ------------- ---------- ----
+8uy2fy8dqbwmlvw5iya802tj0 redis 1 redis:3.0.7 RUNNING RUNNING 23 seconds ago node-2
+7h9lgvidypcr7q1k3lfgohb42 redis 2 redis:3.0.7 RUNNING RUNNING 2 minutes ago node-3
+ae4dl0chk3gtwm1100t5yeged redis 3 redis:3.0.7 RUNNING RUNNING 23 seconds ago node-3
+9fz7fxbg0igypstwliyameobs redis 4 redis:3.0.7 RUNNING RUNNING 2 minutes ago node-3
+drzndxnjz3c8iujdewzaplgr6 redis 5 redis:3.0.7 RUNNING RUNNING 23 seconds ago node-2
+7rcgciqhs4239quraw7evttyf redis 6 redis:3.0.7 RUNNING RUNNING 2 minutes ago node-2
+```
+
+As you can see, every Task running on `node-1` was rebalanced to either `node-2` or `node-3` by the reconciliation loop.
diff --git a/vendor/github.com/docker/swarmkit/agent/agent.go b/vendor/github.com/docker/swarmkit/agent/agent.go
new file mode 100644
index 0000000..dc72fa0
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/agent.go
@@ -0,0 +1,595 @@
+package agent
+
+import (
+ "bytes"
+ "fmt"
+ "math/rand"
+ "reflect"
+ "sync"
+ "time"
+
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "golang.org/x/net/context"
+)
+
+const (
+ initialSessionFailureBackoff = 100 * time.Millisecond
+ maxSessionFailureBackoff = 8 * time.Second
+ nodeUpdatePeriod = 20 * time.Second
+)
+
+// Agent implements the primary node functionality for a member of a swarm
+// cluster. The primary functionality is to run and report on the status of
+// tasks assigned to the node.
+type Agent struct {
+ config *Config
+
+ // The latest node object state from manager
+ // for this node known to the agent.
+ node *api.Node
+
+ keys []*api.EncryptionKey
+
+ sessionq chan sessionOperation
+ worker Worker
+
+ started chan struct{}
+ startOnce sync.Once // start only once
+ ready chan struct{}
+ leaving chan struct{}
+ leaveOnce sync.Once
+ left chan struct{} // closed after "run" processes "leaving" and will no longer accept new assignments
+ stopped chan struct{} // requests shutdown
+ stopOnce sync.Once // only allow stop to be called once
+ closed chan struct{} // only closed in run
+ err error // read only after closed is closed
+
+ nodeUpdatePeriod time.Duration
+}
+
+// New returns a new agent, ready for task dispatch.
+func New(config *Config) (*Agent, error) {
+ if err := config.validate(); err != nil {
+ return nil, err
+ }
+
+ a := &Agent{
+ config: config,
+ sessionq: make(chan sessionOperation),
+ started: make(chan struct{}),
+ leaving: make(chan struct{}),
+ left: make(chan struct{}),
+ stopped: make(chan struct{}),
+ closed: make(chan struct{}),
+ ready: make(chan struct{}),
+ nodeUpdatePeriod: nodeUpdatePeriod,
+ }
+
+ a.worker = newWorker(config.DB, config.Executor, a)
+ return a, nil
+}
+
+// Start begins execution of the agent in the provided context, if not already
+// started.
+//
+// Start returns an error if the agent has already started.
+func (a *Agent) Start(ctx context.Context) error {
+ err := errAgentStarted
+
+ a.startOnce.Do(func() {
+ close(a.started)
+ go a.run(ctx)
+ err = nil // clear error above, only once.
+ })
+
+ return err
+}
+
+// Leave instructs the agent to leave the cluster. This method will shutdown
+// assignment processing and remove all assignments from the node.
+// Leave blocks until worker has finished closing all task managers or agent
+// is closed.
+func (a *Agent) Leave(ctx context.Context) error {
+ select {
+ case <-a.started:
+ default:
+ return errAgentNotStarted
+ }
+
+ a.leaveOnce.Do(func() {
+ close(a.leaving)
+ })
+
+ // Do not call Wait until we have confirmed that the agent is no longer
+ // accepting assignments. Starting a worker might race with Wait.
+ select {
+ case <-a.left:
+ case <-a.closed:
+ return ErrClosed
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+
+ // agent could be closed while Leave is in progress
+ var err error
+ ch := make(chan struct{})
+ go func() {
+ err = a.worker.Wait(ctx)
+ close(ch)
+ }()
+
+ select {
+ case <-ch:
+ return err
+ case <-a.closed:
+ return ErrClosed
+ }
+}
+
+// Stop shuts down the agent, blocking until full shutdown. If the agent is not
+// started, Stop will block until the agent has fully shutdown.
+func (a *Agent) Stop(ctx context.Context) error {
+ select {
+ case <-a.started:
+ default:
+ return errAgentNotStarted
+ }
+
+ a.stop()
+
+ // wait till closed or context cancelled
+ select {
+ case <-a.closed:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+// stop signals the agent shutdown process, returning true if this call was the
+// first to actually shutdown the agent.
+func (a *Agent) stop() bool {
+ var stopped bool
+ a.stopOnce.Do(func() {
+ close(a.stopped)
+ stopped = true
+ })
+
+ return stopped
+}
+
+// Err returns the error that caused the agent to shutdown or nil. Err blocks
+// until the agent is fully shutdown.
+func (a *Agent) Err(ctx context.Context) error {
+ select {
+ case <-a.closed:
+ return a.err
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+// Ready returns a channel that will be closed when agent first becomes ready.
+func (a *Agent) Ready() <-chan struct{} {
+ return a.ready
+}
+
+func (a *Agent) run(ctx context.Context) {
+ ctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ defer close(a.closed) // full shutdown.
+
+ ctx = log.WithModule(ctx, "agent")
+
+ log.G(ctx).Debug("(*Agent).run")
+ defer log.G(ctx).Debug("(*Agent).run exited")
+
+ nodeTLSInfo := a.config.NodeTLSInfo
+
+ // get the node description
+ nodeDescription, err := a.nodeDescriptionWithHostname(ctx, nodeTLSInfo)
+ if err != nil {
+ log.G(ctx).WithError(err).WithField("agent", a.config.Executor).Error("agent: node description unavailable")
+ }
+ // nodeUpdateTicker is used to periodically check for updates to node description
+ nodeUpdateTicker := time.NewTicker(a.nodeUpdatePeriod)
+ defer nodeUpdateTicker.Stop()
+
+ var (
+ backoff time.Duration
+ session = newSession(ctx, a, backoff, "", nodeDescription) // start the initial session
+ registered = session.registered
+ ready = a.ready // first session ready
+ sessionq chan sessionOperation
+ leaving = a.leaving
+ subscriptions = map[string]context.CancelFunc{}
+ )
+ defer func() {
+ session.close()
+ }()
+
+ if err := a.worker.Init(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("worker initialization failed")
+ a.err = err
+ return // fatal?
+ }
+ defer a.worker.Close()
+
+ // setup a reliable reporter to call back to us.
+ reporter := newStatusReporter(ctx, a)
+ defer reporter.Close()
+
+ a.worker.Listen(ctx, reporter)
+
+ updateNode := func() {
+ // skip updating if the registration isn't finished
+ if registered != nil {
+ return
+ }
+ // get the current node description
+ newNodeDescription, err := a.nodeDescriptionWithHostname(ctx, nodeTLSInfo)
+ if err != nil {
+ log.G(ctx).WithError(err).WithField("agent", a.config.Executor).Error("agent: updated node description unavailable")
+ }
+
+ // if newNodeDescription is nil, it will cause a panic when
+ // trying to create a session. Typically this can happen
+ // if the engine goes down
+ if newNodeDescription == nil {
+ return
+ }
+
+ // if the node description has changed, update it to the new one
+ // and close the session. The old session will be stopped and a
+ // new one will be created with the updated description
+ if !reflect.DeepEqual(nodeDescription, newNodeDescription) {
+ nodeDescription = newNodeDescription
+ // close the session
+ log.G(ctx).Info("agent: found node update")
+
+ if err := session.close(); err != nil {
+ log.G(ctx).WithError(err).Error("agent: closing session failed")
+ }
+ sessionq = nil
+ registered = nil
+ }
+ }
+
+ for {
+ select {
+ case operation := <-sessionq:
+ operation.response <- operation.fn(session)
+ case <-leaving:
+ leaving = nil
+
+ // TODO(stevvooe): Signal to the manager that the node is leaving.
+
+ // when leaving we remove all assignments.
+ if err := a.worker.Assign(ctx, nil); err != nil {
+ log.G(ctx).WithError(err).Error("failed removing all assignments")
+ }
+
+ close(a.left)
+ case msg := <-session.assignments:
+ // if we have left, accept no more assignments
+ if leaving == nil {
+ continue
+ }
+
+ switch msg.Type {
+ case api.AssignmentsMessage_COMPLETE:
+ // Need to assign secrets and configs before tasks,
+ // because tasks might depend on new secrets or configs
+ if err := a.worker.Assign(ctx, msg.Changes); err != nil {
+ log.G(ctx).WithError(err).Error("failed to synchronize worker assignments")
+ }
+ case api.AssignmentsMessage_INCREMENTAL:
+ if err := a.worker.Update(ctx, msg.Changes); err != nil {
+ log.G(ctx).WithError(err).Error("failed to update worker assignments")
+ }
+ }
+ case msg := <-session.messages:
+ if err := a.handleSessionMessage(ctx, msg, nodeTLSInfo); err != nil {
+ log.G(ctx).WithError(err).Error("session message handler failed")
+ }
+ case sub := <-session.subscriptions:
+ if sub.Close {
+ if cancel, ok := subscriptions[sub.ID]; ok {
+ cancel()
+ }
+ delete(subscriptions, sub.ID)
+ continue
+ }
+
+ if _, ok := subscriptions[sub.ID]; ok {
+ // Duplicate subscription
+ continue
+ }
+
+ subCtx, subCancel := context.WithCancel(ctx)
+ subscriptions[sub.ID] = subCancel
+ // TODO(dperny) we're tossing the error here, that seems wrong
+ go a.worker.Subscribe(subCtx, sub)
+ case <-registered:
+ log.G(ctx).Debugln("agent: registered")
+ if ready != nil {
+ close(ready)
+ }
+ if a.config.SessionTracker != nil {
+ a.config.SessionTracker.SessionEstablished()
+ }
+ ready = nil
+ registered = nil // we only care about this once per session
+ backoff = 0 // reset backoff
+ sessionq = a.sessionq
+ case err := <-session.errs:
+ // TODO(stevvooe): This may actually block if a session is closed
+ // but no error was sent. This must be the only place
+ // session.close is called in response to errors, for this to work.
+ if err != nil {
+ if a.config.SessionTracker != nil {
+ a.config.SessionTracker.SessionError(err)
+ }
+
+ log.G(ctx).WithError(err).Error("agent: session failed")
+ backoff = initialSessionFailureBackoff + 2*backoff
+ if backoff > maxSessionFailureBackoff {
+ backoff = maxSessionFailureBackoff
+ }
+ }
+
+ if err := session.close(); err != nil {
+ log.G(ctx).WithError(err).Error("agent: closing session failed")
+ }
+ sessionq = nil
+ // if we're here before <-registered, do nothing for that event
+ registered = nil
+ case <-session.closed:
+ if a.config.SessionTracker != nil {
+ if err := a.config.SessionTracker.SessionClosed(); err != nil {
+ log.G(ctx).WithError(err).Error("agent: exiting")
+ a.err = err
+ return
+ }
+ }
+
+ log.G(ctx).Debugf("agent: rebuild session")
+
+ // select a session registration delay from backoff range.
+ delay := time.Duration(0)
+ if backoff > 0 {
+ delay = time.Duration(rand.Int63n(int64(backoff)))
+ }
+ session = newSession(ctx, a, delay, session.sessionID, nodeDescription)
+ registered = session.registered
+ case ev := <-a.config.NotifyTLSChange:
+ // the TLS info has changed, so force a check to see if we need to restart the session
+ if tlsInfo, ok := ev.(*api.NodeTLSInfo); ok {
+ nodeTLSInfo = tlsInfo
+ updateNode()
+ nodeUpdateTicker.Stop()
+ nodeUpdateTicker = time.NewTicker(a.nodeUpdatePeriod)
+ }
+ case <-nodeUpdateTicker.C:
+ // periodically check to see whether the node information has changed, and if so, restart the session
+ updateNode()
+ case <-a.stopped:
+ // TODO(stevvooe): Wait on shutdown and cleanup. May need to pump
+ // this loop a few times.
+ return
+ case <-ctx.Done():
+ if a.err == nil {
+ a.err = ctx.Err()
+ }
+ return
+ }
+ }
+}
+
+func (a *Agent) handleSessionMessage(ctx context.Context, message *api.SessionMessage, nti *api.NodeTLSInfo) error {
+ seen := map[api.Peer]struct{}{}
+ for _, manager := range message.Managers {
+ if manager.Peer.Addr == "" {
+ continue
+ }
+
+ a.config.ConnBroker.Remotes().Observe(*manager.Peer, int(manager.Weight))
+ seen[*manager.Peer] = struct{}{}
+ }
+
+ var changes *NodeChanges
+ if message.Node != nil && (a.node == nil || !nodesEqual(a.node, message.Node)) {
+ if a.config.NotifyNodeChange != nil {
+ changes = &NodeChanges{Node: message.Node.Copy()}
+ }
+ a.node = message.Node.Copy()
+ if err := a.config.Executor.Configure(ctx, a.node); err != nil {
+ log.G(ctx).WithError(err).Error("node configure failed")
+ }
+ }
+ if len(message.RootCA) > 0 && !bytes.Equal(message.RootCA, nti.TrustRoot) {
+ if changes == nil {
+ changes = &NodeChanges{RootCert: message.RootCA}
+ } else {
+ changes.RootCert = message.RootCA
+ }
+ }
+
+ if changes != nil {
+ a.config.NotifyNodeChange <- changes
+ }
+
+ // prune managers not in list.
+ for peer := range a.config.ConnBroker.Remotes().Weights() {
+ if _, ok := seen[peer]; !ok {
+ a.config.ConnBroker.Remotes().Remove(peer)
+ }
+ }
+
+ if message.NetworkBootstrapKeys == nil {
+ return nil
+ }
+
+ for _, key := range message.NetworkBootstrapKeys {
+ same := false
+ for _, agentKey := range a.keys {
+ if agentKey.LamportTime == key.LamportTime {
+ same = true
+ }
+ }
+ if !same {
+ a.keys = message.NetworkBootstrapKeys
+ if err := a.config.Executor.SetNetworkBootstrapKeys(a.keys); err != nil {
+ panic(fmt.Errorf("configuring network key failed"))
+ }
+ }
+ }
+
+ return nil
+}
+
+type sessionOperation struct {
+ fn func(session *session) error
+ response chan error
+}
+
+// withSession runs fn with the current session.
+func (a *Agent) withSession(ctx context.Context, fn func(session *session) error) error {
+ response := make(chan error, 1)
+ select {
+ case a.sessionq <- sessionOperation{
+ fn: fn,
+ response: response,
+ }:
+ select {
+ case err := <-response:
+ return err
+ case <-a.closed:
+ return ErrClosed
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ case <-a.closed:
+ return ErrClosed
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+// UpdateTaskStatus attempts to send a task status update over the current session,
+// blocking until the operation is completed.
+//
+// If an error is returned, the operation should be retried.
+func (a *Agent) UpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error {
+ log.G(ctx).WithField("task.id", taskID).Debug("(*Agent).UpdateTaskStatus")
+ ctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+
+ errs := make(chan error, 1)
+ if err := a.withSession(ctx, func(session *session) error {
+ go func() {
+ err := session.sendTaskStatus(ctx, taskID, status)
+ if err != nil {
+ if err == errTaskUnknown {
+ err = nil // dispatcher no longer cares about this task.
+ } else {
+ log.G(ctx).WithError(err).Error("closing session after fatal error")
+ session.sendError(err)
+ }
+ } else {
+ log.G(ctx).Debug("task status reported")
+ }
+
+ errs <- err
+ }()
+
+ return nil
+ }); err != nil {
+ return err
+ }
+
+ select {
+ case err := <-errs:
+ return err
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+// Publisher returns a LogPublisher for the given subscription
+// as well as a cancel function that should be called when the log stream
+// is completed.
+func (a *Agent) Publisher(ctx context.Context, subscriptionID string) (exec.LogPublisher, func(), error) {
+ // TODO(stevvooe): The level of coordination here is WAY too much for logs.
+ // These should only be best effort and really just buffer until a session is
+ // ready. Ideally, they would use a separate connection completely.
+
+ var (
+ err error
+ publisher api.LogBroker_PublishLogsClient
+ )
+
+ err = a.withSession(ctx, func(session *session) error {
+ publisher, err = api.NewLogBrokerClient(session.conn.ClientConn).PublishLogs(ctx)
+ return err
+ })
+ if err != nil {
+ return nil, nil, err
+ }
+
+ // make little closure for ending the log stream
+ sendCloseMsg := func() {
+ // send a close message, to tell the manager our logs are done
+ publisher.Send(&api.PublishLogsMessage{
+ SubscriptionID: subscriptionID,
+ Close: true,
+ })
+ // close the stream forreal
+ publisher.CloseSend()
+ }
+
+ return exec.LogPublisherFunc(func(ctx context.Context, message api.LogMessage) error {
+ select {
+ case <-ctx.Done():
+ sendCloseMsg()
+ return ctx.Err()
+ default:
+ }
+
+ return publisher.Send(&api.PublishLogsMessage{
+ SubscriptionID: subscriptionID,
+ Messages: []api.LogMessage{message},
+ })
+ }), func() {
+ sendCloseMsg()
+ }, nil
+}
+
+// nodeDescriptionWithHostname retrieves node description, and overrides hostname if available
+func (a *Agent) nodeDescriptionWithHostname(ctx context.Context, tlsInfo *api.NodeTLSInfo) (*api.NodeDescription, error) {
+ desc, err := a.config.Executor.Describe(ctx)
+
+ // Override hostname and TLS info
+ if desc != nil {
+ if a.config.Hostname != "" && desc != nil {
+ desc.Hostname = a.config.Hostname
+ }
+ desc.TLSInfo = tlsInfo
+ }
+ return desc, err
+}
+
+// nodesEqual returns true if the node states are functionally equal, ignoring status,
+// version and other superfluous fields.
+//
+// This used to decide whether or not to propagate a node update to executor.
+func nodesEqual(a, b *api.Node) bool {
+ a, b = a.Copy(), b.Copy()
+
+ a.Status, b.Status = api.NodeStatus{}, api.NodeStatus{}
+ a.Meta, b.Meta = api.Meta{}, api.Meta{}
+
+ return reflect.DeepEqual(a, b)
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/config.go b/vendor/github.com/docker/swarmkit/agent/config.go
new file mode 100644
index 0000000..98d5bf5
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/config.go
@@ -0,0 +1,83 @@
+package agent
+
+import (
+ "github.com/boltdb/bolt"
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/connectionbroker"
+ "github.com/pkg/errors"
+ "google.golang.org/grpc/credentials"
+)
+
+// NodeChanges encapsulates changes that should be made to the node as per session messages
+// from the dispatcher
+type NodeChanges struct {
+ Node *api.Node
+ RootCert []byte
+}
+
+// Config provides values for an Agent.
+type Config struct {
+ // Hostname the name of host for agent instance.
+ Hostname string
+
+ // ConnBroker provides a connection broker for retrieving gRPC
+ // connections to managers.
+ ConnBroker *connectionbroker.Broker
+
+ // Executor specifies the executor to use for the agent.
+ Executor exec.Executor
+
+ // DB used for task storage. Must be open for the lifetime of the agent.
+ DB *bolt.DB
+
+ // NotifyNodeChange channel receives new node changes from session messages.
+ NotifyNodeChange chan<- *NodeChanges
+
+ // NotifyTLSChange channel sends new TLS information changes, which can cause a session to restart
+ NotifyTLSChange <-chan events.Event
+
+ // Credentials is credentials for grpc connection to manager.
+ Credentials credentials.TransportCredentials
+
+ // NodeTLSInfo contains the starting node TLS info to bootstrap into the agent
+ NodeTLSInfo *api.NodeTLSInfo
+
+ // SessionTracker, if provided, will have its SessionClosed and SessionError methods called
+ // when sessions close and error.
+ SessionTracker SessionTracker
+}
+
+func (c *Config) validate() error {
+ if c.Credentials == nil {
+ return errors.New("agent: Credentials is required")
+ }
+
+ if c.Executor == nil {
+ return errors.New("agent: executor required")
+ }
+
+ if c.DB == nil {
+ return errors.New("agent: database required")
+ }
+
+ if c.NodeTLSInfo == nil {
+ return errors.New("agent: Node TLS info is required")
+ }
+
+ return nil
+}
+
+// A SessionTracker gets notified when sessions close and error
+type SessionTracker interface {
+ // SessionClosed is called whenever a session is closed - if the function errors, the agent
+ // will exit with the returned error. Otherwise the agent can continue and rebuild a new session.
+ SessionClosed() error
+
+ // SessionError is called whenever a session errors
+ SessionError(err error)
+
+ // SessionEstablished is called whenever a session is established
+ SessionEstablished()
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/configs/configs.go b/vendor/github.com/docker/swarmkit/agent/configs/configs.go
new file mode 100644
index 0000000..ae5fc8c
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/configs/configs.go
@@ -0,0 +1,88 @@
+package configs
+
+import (
+ "fmt"
+ "sync"
+
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/api"
+)
+
+// configs is a map that keeps all the currently available configs to the agent
+// mapped by config ID.
+type configs struct {
+ mu sync.RWMutex
+ m map[string]*api.Config
+}
+
+// NewManager returns a place to store configs.
+func NewManager() exec.ConfigsManager {
+ return &configs{
+ m: make(map[string]*api.Config),
+ }
+}
+
+// Get returns a config by ID. If the config doesn't exist, returns nil.
+func (r *configs) Get(configID string) (*api.Config, error) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ if r, ok := r.m[configID]; ok {
+ return r, nil
+ }
+ return nil, fmt.Errorf("config %s not found", configID)
+}
+
+// Add adds one or more configs to the config map.
+func (r *configs) Add(configs ...api.Config) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ for _, config := range configs {
+ r.m[config.ID] = config.Copy()
+ }
+}
+
+// Remove removes one or more configs by ID from the config map. Succeeds
+// whether or not the given IDs are in the map.
+func (r *configs) Remove(configs []string) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ for _, config := range configs {
+ delete(r.m, config)
+ }
+}
+
+// Reset removes all the configs.
+func (r *configs) Reset() {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.m = make(map[string]*api.Config)
+}
+
+// taskRestrictedConfigsProvider restricts the ids to the task.
+type taskRestrictedConfigsProvider struct {
+ configs exec.ConfigGetter
+ configIDs map[string]struct{} // allow list of config ids
+}
+
+func (sp *taskRestrictedConfigsProvider) Get(configID string) (*api.Config, error) {
+ if _, ok := sp.configIDs[configID]; !ok {
+ return nil, fmt.Errorf("task not authorized to access config %s", configID)
+ }
+
+ return sp.configs.Get(configID)
+}
+
+// Restrict provides a getter that only allows access to the configs
+// referenced by the task.
+func Restrict(configs exec.ConfigGetter, t *api.Task) exec.ConfigGetter {
+ cids := map[string]struct{}{}
+
+ container := t.Spec.GetContainer()
+ if container != nil {
+ for _, configRef := range container.Configs {
+ cids[configRef.ConfigID] = struct{}{}
+ }
+ }
+
+ return &taskRestrictedConfigsProvider{configs: configs, configIDs: cids}
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/dependency.go b/vendor/github.com/docker/swarmkit/agent/dependency.go
new file mode 100644
index 0000000..4872500
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/dependency.go
@@ -0,0 +1,52 @@
+package agent
+
+import (
+ "github.com/docker/swarmkit/agent/configs"
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/agent/secrets"
+ "github.com/docker/swarmkit/api"
+)
+
+type dependencyManager struct {
+ secrets exec.SecretsManager
+ configs exec.ConfigsManager
+}
+
+// NewDependencyManager creates a dependency manager object that wraps
+// objects which provide access to various dependency types.
+func NewDependencyManager() exec.DependencyManager {
+ return &dependencyManager{
+ secrets: secrets.NewManager(),
+ configs: configs.NewManager(),
+ }
+}
+
+func (d *dependencyManager) Secrets() exec.SecretsManager {
+ return d.secrets
+}
+
+func (d *dependencyManager) Configs() exec.ConfigsManager {
+ return d.configs
+}
+
+type dependencyGetter struct {
+ secrets exec.SecretGetter
+ configs exec.ConfigGetter
+}
+
+func (d *dependencyGetter) Secrets() exec.SecretGetter {
+ return d.secrets
+}
+
+func (d *dependencyGetter) Configs() exec.ConfigGetter {
+ return d.configs
+}
+
+// Restrict provides getters that only allows access to the dependencies
+// referenced by the task.
+func Restrict(dependencies exec.DependencyManager, t *api.Task) exec.DependencyGetter {
+ return &dependencyGetter{
+ secrets: secrets.Restrict(dependencies.Secrets(), t),
+ configs: configs.Restrict(dependencies.Configs(), t),
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/errors.go b/vendor/github.com/docker/swarmkit/agent/errors.go
new file mode 100644
index 0000000..c45f99b
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/errors.go
@@ -0,0 +1,22 @@
+package agent
+
+import (
+ "errors"
+)
+
+var (
+ // ErrClosed is returned when an operation fails because the resource is closed.
+ ErrClosed = errors.New("agent: closed")
+
+ errNodeNotRegistered = errors.New("node not registered")
+
+ errAgentStarted = errors.New("agent: already started")
+ errAgentNotStarted = errors.New("agent: not started")
+
+ errTaskNoContoller = errors.New("agent: no task controller")
+ errTaskNotAssigned = errors.New("agent: task not assigned")
+ errTaskStatusUpdateNoChange = errors.New("agent: no change in task status")
+ errTaskUnknown = errors.New("agent: task unknown")
+
+ errTaskInvalid = errors.New("task: invalid")
+)
diff --git a/vendor/github.com/docker/swarmkit/agent/exec/controller.go b/vendor/github.com/docker/swarmkit/agent/exec/controller.go
new file mode 100644
index 0000000..1cafb47
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/exec/controller.go
@@ -0,0 +1,358 @@
+package exec
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/equality"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/protobuf/ptypes"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+// Controller controls execution of a task.
+type Controller interface {
+ // Update the task definition seen by the controller. Will return
+ // ErrTaskUpdateFailed if the provided task definition changes fields that
+ // cannot be changed.
+ //
+ // Will be ignored if the task has exited.
+ Update(ctx context.Context, t *api.Task) error
+
+ // Prepare the task for execution. This should ensure that all resources
+ // are created such that a call to start should execute immediately.
+ Prepare(ctx context.Context) error
+
+ // Start the target and return when it has started successfully.
+ Start(ctx context.Context) error
+
+ // Wait blocks until the target has exited.
+ Wait(ctx context.Context) error
+
+ // Shutdown requests to exit the target gracefully.
+ Shutdown(ctx context.Context) error
+
+ // Terminate the target.
+ Terminate(ctx context.Context) error
+
+ // Remove all resources allocated by the controller.
+ Remove(ctx context.Context) error
+
+ // Close closes any ephemeral resources associated with controller instance.
+ Close() error
+}
+
+// ControllerLogs defines a component that makes logs accessible.
+//
+// Can usually be accessed on a controller instance via type assertion.
+type ControllerLogs interface {
+ // Logs will write publisher until the context is cancelled or an error
+ // occurs.
+ Logs(ctx context.Context, publisher LogPublisher, options api.LogSubscriptionOptions) error
+}
+
+// LogPublisher defines the protocol for receiving a log message.
+type LogPublisher interface {
+ Publish(ctx context.Context, message api.LogMessage) error
+}
+
+// LogPublisherFunc implements publisher with just a function.
+type LogPublisherFunc func(ctx context.Context, message api.LogMessage) error
+
+// Publish calls the wrapped function.
+func (fn LogPublisherFunc) Publish(ctx context.Context, message api.LogMessage) error {
+ return fn(ctx, message)
+}
+
+// LogPublisherProvider defines the protocol for receiving a log publisher
+type LogPublisherProvider interface {
+ Publisher(ctx context.Context, subscriptionID string) (LogPublisher, func(), error)
+}
+
+// ContainerStatuser reports status of a container.
+//
+// This can be implemented by controllers or error types.
+type ContainerStatuser interface {
+ // ContainerStatus returns the status of the target container, if
+ // available. When the container is not available, the status will be nil.
+ ContainerStatus(ctx context.Context) (*api.ContainerStatus, error)
+}
+
+// PortStatuser reports status of ports which are allocated by the executor
+type PortStatuser interface {
+ // PortStatus returns the status on a list of PortConfigs
+ // which are managed at the host level by the controller.
+ PortStatus(ctx context.Context) (*api.PortStatus, error)
+}
+
+// Resolve attempts to get a controller from the executor and reports the
+// correct status depending on the tasks current state according to the result.
+//
+// Unlike Do, if an error is returned, the status should still be reported. The
+// error merely reports the failure at getting the controller.
+func Resolve(ctx context.Context, task *api.Task, executor Executor) (Controller, *api.TaskStatus, error) {
+ status := task.Status.Copy()
+
+ defer func() {
+ logStateChange(ctx, task.DesiredState, task.Status.State, status.State)
+ }()
+
+ ctlr, err := executor.Controller(task)
+
+ // depending on the tasks state, a failed controller resolution has varying
+ // impact. The following expresses that impact.
+ if err != nil {
+ status.Message = "resolving controller failed"
+ status.Err = err.Error()
+ // before the task has been started, we consider it a rejection.
+ // if task is running, consider the task has failed
+ // otherwise keep the existing state
+ if task.Status.State < api.TaskStateStarting {
+ status.State = api.TaskStateRejected
+ } else if task.Status.State <= api.TaskStateRunning {
+ status.State = api.TaskStateFailed
+ }
+ } else if task.Status.State < api.TaskStateAccepted {
+ // we always want to proceed to accepted when we resolve the controller
+ status.Message = "accepted"
+ status.State = api.TaskStateAccepted
+ }
+
+ return ctlr, status, err
+}
+
+// Do progresses the task state using the controller performing a single
+// operation on the controller. The return TaskStatus should be marked as the
+// new state of the task.
+//
+// The returned status should be reported and placed back on to task
+// before the next call. The operation can be cancelled by creating a
+// cancelling context.
+//
+// Errors from the task controller will reported on the returned status. Any
+// errors coming from this function should not be reported as related to the
+// individual task.
+//
+// If ErrTaskNoop is returned, it means a second call to Do will result in no
+// change. If ErrTaskDead is returned, calls to Do will no longer result in any
+// action.
+func Do(ctx context.Context, task *api.Task, ctlr Controller) (*api.TaskStatus, error) {
+ status := task.Status.Copy()
+
+ // stay in the current state.
+ noop := func(errs ...error) (*api.TaskStatus, error) {
+ return status, ErrTaskNoop
+ }
+
+ retry := func() (*api.TaskStatus, error) {
+ // while we retry on all errors, this allows us to explicitly declare
+ // retry cases.
+ return status, ErrTaskRetry
+ }
+
+ // transition moves the task to the next state.
+ transition := func(state api.TaskState, msg string) (*api.TaskStatus, error) {
+ current := status.State
+ status.State = state
+ status.Message = msg
+
+ if current > state {
+ panic("invalid state transition")
+ }
+ return status, nil
+ }
+
+ // containerStatus exitCode keeps track of whether or not we've set it in
+ // this particular method. Eventually, we assemble this as part of a defer.
+ var (
+ containerStatus *api.ContainerStatus
+ portStatus *api.PortStatus
+ exitCode int
+ )
+
+ // returned when a fatal execution of the task is fatal. In this case, we
+ // proceed to a terminal error state and set the appropriate fields.
+ //
+ // Common checks for the nature of an error should be included here. If the
+ // error is determined not to be fatal for the task,
+ fatal := func(err error) (*api.TaskStatus, error) {
+ if err == nil {
+ panic("err must not be nil when fatal")
+ }
+
+ if cs, ok := err.(ContainerStatuser); ok {
+ var err error
+ containerStatus, err = cs.ContainerStatus(ctx)
+ if err != nil && !contextDoneError(err) {
+ log.G(ctx).WithError(err).Error("error resolving container status on fatal")
+ }
+ }
+
+ // make sure we've set the *correct* exit code
+ if ec, ok := err.(ExitCoder); ok {
+ exitCode = ec.ExitCode()
+ }
+
+ if cause := errors.Cause(err); cause == context.DeadlineExceeded || cause == context.Canceled {
+ return retry()
+ }
+
+ status.Err = err.Error() // still reported on temporary
+ if IsTemporary(err) {
+ return retry()
+ }
+
+ // only at this point do we consider the error fatal to the task.
+ log.G(ctx).WithError(err).Error("fatal task error")
+
+ // NOTE(stevvooe): The following switch dictates the terminal failure
+ // state based on the state in which the failure was encountered.
+ switch {
+ case status.State < api.TaskStateStarting:
+ status.State = api.TaskStateRejected
+ case status.State >= api.TaskStateStarting:
+ status.State = api.TaskStateFailed
+ }
+
+ return status, nil
+ }
+
+ // below, we have several callbacks that are run after the state transition
+ // is completed.
+ defer func() {
+ logStateChange(ctx, task.DesiredState, task.Status.State, status.State)
+
+ if !equality.TaskStatusesEqualStable(status, &task.Status) {
+ status.Timestamp = ptypes.MustTimestampProto(time.Now())
+ }
+ }()
+
+ // extract the container status from the container, if supported.
+ defer func() {
+ // only do this if in an active state
+ if status.State < api.TaskStateStarting {
+ return
+ }
+
+ if containerStatus == nil {
+ // collect this, if we haven't
+ cctlr, ok := ctlr.(ContainerStatuser)
+ if !ok {
+ return
+ }
+
+ var err error
+ containerStatus, err = cctlr.ContainerStatus(ctx)
+ if err != nil && !contextDoneError(err) {
+ log.G(ctx).WithError(err).Error("container status unavailable")
+ }
+
+ // at this point, things have gone fairly wrong. Remain positive
+ // and let's get something out the door.
+ if containerStatus == nil {
+ containerStatus = new(api.ContainerStatus)
+ containerStatusTask := task.Status.GetContainer()
+ if containerStatusTask != nil {
+ *containerStatus = *containerStatusTask // copy it over.
+ }
+ }
+ }
+
+ // at this point, we *must* have a containerStatus.
+ if exitCode != 0 {
+ containerStatus.ExitCode = int32(exitCode)
+ }
+
+ status.RuntimeStatus = &api.TaskStatus_Container{
+ Container: containerStatus,
+ }
+
+ if portStatus == nil {
+ pctlr, ok := ctlr.(PortStatuser)
+ if !ok {
+ return
+ }
+
+ var err error
+ portStatus, err = pctlr.PortStatus(ctx)
+ if err != nil && !contextDoneError(err) {
+ log.G(ctx).WithError(err).Error("container port status unavailable")
+ }
+ }
+
+ status.PortStatus = portStatus
+ }()
+
+ if task.DesiredState == api.TaskStateShutdown {
+ if status.State >= api.TaskStateCompleted {
+ return noop()
+ }
+
+ if err := ctlr.Shutdown(ctx); err != nil {
+ return fatal(err)
+ }
+
+ return transition(api.TaskStateShutdown, "shutdown")
+ }
+
+ if status.State > task.DesiredState {
+ return noop() // way beyond desired state, pause
+ }
+
+ // the following states may proceed past desired state.
+ switch status.State {
+ case api.TaskStatePreparing:
+ if err := ctlr.Prepare(ctx); err != nil && err != ErrTaskPrepared {
+ return fatal(err)
+ }
+
+ return transition(api.TaskStateReady, "prepared")
+ case api.TaskStateStarting:
+ if err := ctlr.Start(ctx); err != nil && err != ErrTaskStarted {
+ return fatal(err)
+ }
+
+ return transition(api.TaskStateRunning, "started")
+ case api.TaskStateRunning:
+ if err := ctlr.Wait(ctx); err != nil {
+ return fatal(err)
+ }
+
+ return transition(api.TaskStateCompleted, "finished")
+ }
+
+ // The following represent "pause" states. We can only proceed when the
+ // desired state is beyond our current state.
+ if status.State >= task.DesiredState {
+ return noop()
+ }
+
+ switch status.State {
+ case api.TaskStateNew, api.TaskStatePending, api.TaskStateAssigned:
+ return transition(api.TaskStateAccepted, "accepted")
+ case api.TaskStateAccepted:
+ return transition(api.TaskStatePreparing, "preparing")
+ case api.TaskStateReady:
+ return transition(api.TaskStateStarting, "starting")
+ default: // terminal states
+ return noop()
+ }
+}
+
+func logStateChange(ctx context.Context, desired, previous, next api.TaskState) {
+ if previous != next {
+ fields := logrus.Fields{
+ "state.transition": fmt.Sprintf("%v->%v", previous, next),
+ "state.desired": desired,
+ }
+ log.G(ctx).WithFields(fields).Debug("state changed")
+ }
+}
+
+func contextDoneError(err error) bool {
+ cause := errors.Cause(err)
+ return cause == context.Canceled || cause == context.DeadlineExceeded
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/exec/controller_stub.go b/vendor/github.com/docker/swarmkit/agent/exec/controller_stub.go
new file mode 100644
index 0000000..076955f
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/exec/controller_stub.go
@@ -0,0 +1,75 @@
+package exec
+
+import (
+ "github.com/docker/swarmkit/api"
+ "golang.org/x/net/context"
+ "runtime"
+ "strings"
+)
+
+// StubController implements the Controller interface,
+// but allows you to specify behaviors for each of its methods.
+type StubController struct {
+ Controller
+ UpdateFn func(ctx context.Context, t *api.Task) error
+ PrepareFn func(ctx context.Context) error
+ StartFn func(ctx context.Context) error
+ WaitFn func(ctx context.Context) error
+ ShutdownFn func(ctx context.Context) error
+ TerminateFn func(ctx context.Context) error
+ RemoveFn func(ctx context.Context) error
+ CloseFn func() error
+ calls map[string]int
+ cstatus *api.ContainerStatus
+}
+
+// NewStubController returns an initialized StubController
+func NewStubController() *StubController {
+ return &StubController{
+ calls: make(map[string]int),
+ }
+}
+
+// If function A calls updateCountsForSelf,
+// The callCount[A] value will be incremented
+func (sc *StubController) called() {
+ pc, _, _, ok := runtime.Caller(1)
+ if !ok {
+ panic("Failed to find caller of function")
+ }
+ // longName looks like 'github.com/docker/swarmkit/agent/exec.(*StubController).Prepare:1'
+ longName := runtime.FuncForPC(pc).Name()
+ parts := strings.Split(longName, ".")
+ tail := strings.Split(parts[len(parts)-1], ":")
+ sc.calls[tail[0]]++
+}
+
+// Update is part of the Controller interface
+func (sc *StubController) Update(ctx context.Context, t *api.Task) error {
+ sc.called()
+ return sc.UpdateFn(ctx, t)
+}
+
+// Prepare is part of the Controller interface
+func (sc *StubController) Prepare(ctx context.Context) error { sc.called(); return sc.PrepareFn(ctx) }
+
+// Start is part of the Controller interface
+func (sc *StubController) Start(ctx context.Context) error { sc.called(); return sc.StartFn(ctx) }
+
+// Wait is part of the Controller interface
+func (sc *StubController) Wait(ctx context.Context) error { sc.called(); return sc.WaitFn(ctx) }
+
+// Shutdown is part of the Controller interface
+func (sc *StubController) Shutdown(ctx context.Context) error { sc.called(); return sc.ShutdownFn(ctx) }
+
+// Terminate is part of the Controller interface
+func (sc *StubController) Terminate(ctx context.Context) error {
+ sc.called()
+ return sc.TerminateFn(ctx)
+}
+
+// Remove is part of the Controller interface
+func (sc *StubController) Remove(ctx context.Context) error { sc.called(); return sc.RemoveFn(ctx) }
+
+// Close is part of the Controller interface
+func (sc *StubController) Close() error { sc.called(); return sc.CloseFn() }
diff --git a/vendor/github.com/docker/swarmkit/agent/exec/errors.go b/vendor/github.com/docker/swarmkit/agent/exec/errors.go
new file mode 100644
index 0000000..af57e6b
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/exec/errors.go
@@ -0,0 +1,82 @@
+package exec
+
+import "github.com/pkg/errors"
+
+var (
+ // ErrRuntimeUnsupported encountered when a task requires a runtime
+ // unsupported by the executor.
+ ErrRuntimeUnsupported = errors.New("exec: unsupported runtime")
+
+ // ErrTaskPrepared is called if the task is already prepared.
+ ErrTaskPrepared = errors.New("exec: task already prepared")
+
+ // ErrTaskStarted can be returned from any operation that cannot be
+ // performed because the task has already been started. This does not imply
+ // that the task is running but rather that it is no longer valid to call
+ // Start.
+ ErrTaskStarted = errors.New("exec: task already started")
+
+ // ErrTaskUpdateRejected is returned if a task update is rejected by a controller.
+ ErrTaskUpdateRejected = errors.New("exec: task update rejected")
+
+ // ErrControllerClosed returned when a task controller has been closed.
+ ErrControllerClosed = errors.New("exec: controller closed")
+
+ // ErrTaskRetry is returned by Do when an operation failed by should be
+ // retried. The status should still be reported in this case.
+ ErrTaskRetry = errors.New("exec: task retry")
+
+ // ErrTaskNoop returns when the a subsequent call to Do will not result in
+ // advancing the task. Callers should avoid calling Do until the task has been updated.
+ ErrTaskNoop = errors.New("exec: task noop")
+)
+
+// ExitCoder is implemented by errors that have an exit code.
+type ExitCoder interface {
+ // ExitCode returns the exit code.
+ ExitCode() int
+}
+
+// Temporary indicates whether or not the error condition is temporary.
+//
+// If this is encountered in the controller, the failing operation will be
+// retried when this returns true. Otherwise, the operation is considered
+// fatal.
+type Temporary interface {
+ Temporary() bool
+}
+
+// MakeTemporary makes the error temporary.
+func MakeTemporary(err error) error {
+ if IsTemporary(err) {
+ return err
+ }
+
+ return temporary{err}
+}
+
+type temporary struct {
+ error
+}
+
+func (t temporary) Cause() error { return t.error }
+func (t temporary) Temporary() bool { return true }
+
+// IsTemporary returns true if the error or a recursive cause returns true for
+// temporary.
+func IsTemporary(err error) bool {
+ for err != nil {
+ if tmp, ok := err.(Temporary); ok && tmp.Temporary() {
+ return true
+ }
+
+ cause := errors.Cause(err)
+ if cause == err {
+ break
+ }
+
+ err = cause
+ }
+
+ return false
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/exec/executor.go b/vendor/github.com/docker/swarmkit/agent/exec/executor.go
new file mode 100644
index 0000000..8c3fd03
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/exec/executor.go
@@ -0,0 +1,81 @@
+package exec
+
+import (
+ "github.com/docker/swarmkit/api"
+ "golang.org/x/net/context"
+)
+
+// Executor provides controllers for tasks.
+type Executor interface {
+ // Describe returns the underlying node description.
+ Describe(ctx context.Context) (*api.NodeDescription, error)
+
+ // Configure uses the node object state to propagate node
+ // state to the underlying executor.
+ Configure(ctx context.Context, node *api.Node) error
+
+ // Controller provides a controller for the given task.
+ Controller(t *api.Task) (Controller, error)
+
+ // SetNetworkBootstrapKeys passes the symmetric keys from the
+ // manager to the executor.
+ SetNetworkBootstrapKeys([]*api.EncryptionKey) error
+}
+
+// SecretsProvider is implemented by objects that can store secrets, typically
+// an executor.
+type SecretsProvider interface {
+ Secrets() SecretsManager
+}
+
+// ConfigsProvider is implemented by objects that can store configs,
+// typically an executor.
+type ConfigsProvider interface {
+ Configs() ConfigsManager
+}
+
+// DependencyManager is a meta-object that can keep track of typed objects
+// such as secrets and configs.
+type DependencyManager interface {
+ SecretsProvider
+ ConfigsProvider
+}
+
+// DependencyGetter is a meta-object that can provide access to typed objects
+// such as secrets and configs.
+type DependencyGetter interface {
+ Secrets() SecretGetter
+ Configs() ConfigGetter
+}
+
+// SecretGetter contains secret data necessary for the Controller.
+type SecretGetter interface {
+ // Get returns the the secret with a specific secret ID, if available.
+ // When the secret is not available, the return will be nil.
+ Get(secretID string) (*api.Secret, error)
+}
+
+// SecretsManager is the interface for secret storage and updates.
+type SecretsManager interface {
+ SecretGetter
+
+ Add(secrets ...api.Secret) // add one or more secrets
+ Remove(secrets []string) // remove the secrets by ID
+ Reset() // remove all secrets
+}
+
+// ConfigGetter contains config data necessary for the Controller.
+type ConfigGetter interface {
+ // Get returns the the config with a specific config ID, if available.
+ // When the config is not available, the return will be nil.
+ Get(configID string) (*api.Config, error)
+}
+
+// ConfigsManager is the interface for config storage and updates.
+type ConfigsManager interface {
+ ConfigGetter
+
+ Add(configs ...api.Config) // add one or more configs
+ Remove(configs []string) // remove the configs by ID
+ Reset() // remove all configs
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/helpers.go b/vendor/github.com/docker/swarmkit/agent/helpers.go
new file mode 100644
index 0000000..5fdf166
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/helpers.go
@@ -0,0 +1,13 @@
+package agent
+
+import "golang.org/x/net/context"
+
+// runctx blocks until the function exits, closed is closed, or the context is
+// cancelled. Call as part of go statement.
+func runctx(ctx context.Context, closed chan struct{}, errs chan error, fn func(ctx context.Context) error) {
+ select {
+ case errs <- fn(ctx):
+ case <-closed:
+ case <-ctx.Done():
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/reporter.go b/vendor/github.com/docker/swarmkit/agent/reporter.go
new file mode 100644
index 0000000..73e6ab3
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/reporter.go
@@ -0,0 +1,129 @@
+package agent
+
+import (
+ "reflect"
+ "sync"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "golang.org/x/net/context"
+)
+
+// StatusReporter receives updates to task status. Method may be called
+// concurrently, so implementations should be goroutine-safe.
+type StatusReporter interface {
+ UpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error
+}
+
+type statusReporterFunc func(ctx context.Context, taskID string, status *api.TaskStatus) error
+
+func (fn statusReporterFunc) UpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error {
+ return fn(ctx, taskID, status)
+}
+
+// statusReporter creates a reliable StatusReporter that will always succeed.
+// It handles several tasks at once, ensuring all statuses are reported.
+//
+// The reporter will continue reporting the current status until it succeeds.
+type statusReporter struct {
+ reporter StatusReporter
+ statuses map[string]*api.TaskStatus
+ mu sync.Mutex
+ cond sync.Cond
+ closed bool
+}
+
+func newStatusReporter(ctx context.Context, upstream StatusReporter) *statusReporter {
+ r := &statusReporter{
+ reporter: upstream,
+ statuses: make(map[string]*api.TaskStatus),
+ }
+
+ r.cond.L = &r.mu
+
+ go r.run(ctx)
+ return r
+}
+
+func (sr *statusReporter) UpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error {
+ sr.mu.Lock()
+ defer sr.mu.Unlock()
+
+ current, ok := sr.statuses[taskID]
+ if ok {
+ if reflect.DeepEqual(current, status) {
+ return nil
+ }
+
+ if current.State > status.State {
+ return nil // ignore old updates
+ }
+ }
+ sr.statuses[taskID] = status
+ sr.cond.Signal()
+
+ return nil
+}
+
+func (sr *statusReporter) Close() error {
+ sr.mu.Lock()
+ defer sr.mu.Unlock()
+
+ sr.closed = true
+ sr.cond.Signal()
+
+ return nil
+}
+
+func (sr *statusReporter) run(ctx context.Context) {
+ done := make(chan struct{})
+ defer close(done)
+
+ sr.mu.Lock() // released during wait, below.
+ defer sr.mu.Unlock()
+
+ go func() {
+ select {
+ case <-ctx.Done():
+ sr.Close()
+ case <-done:
+ return
+ }
+ }()
+
+ for {
+ if len(sr.statuses) == 0 {
+ sr.cond.Wait()
+ }
+
+ if sr.closed {
+ // TODO(stevvooe): Add support here for waiting until all
+ // statuses are flushed before shutting down.
+ return
+ }
+
+ for taskID, status := range sr.statuses {
+ delete(sr.statuses, taskID) // delete the entry, while trying to send.
+
+ sr.mu.Unlock()
+ err := sr.reporter.UpdateTaskStatus(ctx, taskID, status)
+ sr.mu.Lock()
+
+ // reporter might be closed during UpdateTaskStatus call
+ if sr.closed {
+ return
+ }
+
+ if err != nil {
+ log.G(ctx).WithError(err).Error("status reporter failed to report status to agent")
+
+ // place it back in the map, if not there, allowing us to pick
+ // the value if a new one came in when we were sending the last
+ // update.
+ if _, ok := sr.statuses[taskID]; !ok {
+ sr.statuses[taskID] = status
+ }
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/resource.go b/vendor/github.com/docker/swarmkit/agent/resource.go
new file mode 100644
index 0000000..8e88d2c
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/resource.go
@@ -0,0 +1,69 @@
+package agent
+
+import (
+ "github.com/docker/swarmkit/api"
+ "golang.org/x/net/context"
+)
+
+type resourceAllocator struct {
+ agent *Agent
+}
+
+// ResourceAllocator is an interface to allocate resource such as
+// network attachments from a worker node.
+type ResourceAllocator interface {
+ // AttachNetwork creates a network attachment in the manager
+ // given a target network and a unique ID representing the
+ // connecting entity and optionally a list of ipv4/ipv6
+ // addresses to be assigned to the attachment. AttachNetwork
+ // returns a unique ID for the attachment if successful or an
+ // error in case of failure.
+ AttachNetwork(ctx context.Context, id, target string, addresses []string) (string, error)
+
+ // DetachNetworks deletes a network attachment for the passed
+ // attachment ID. The attachment ID is obtained from a
+ // previous AttachNetwork call.
+ DetachNetwork(ctx context.Context, aID string) error
+}
+
+// AttachNetwork creates a network attachment.
+func (r *resourceAllocator) AttachNetwork(ctx context.Context, id, target string, addresses []string) (string, error) {
+ var taskID string
+ if err := r.agent.withSession(ctx, func(session *session) error {
+ client := api.NewResourceAllocatorClient(session.conn.ClientConn)
+ r, err := client.AttachNetwork(ctx, &api.AttachNetworkRequest{
+ Config: &api.NetworkAttachmentConfig{
+ Target: target,
+ Addresses: addresses,
+ },
+ ContainerID: id,
+ })
+ if err != nil {
+ return err
+ }
+ taskID = r.AttachmentID
+ return nil
+ }); err != nil {
+ return "", err
+ }
+
+ return taskID, nil
+}
+
+// DetachNetwork deletes a network attachment.
+func (r *resourceAllocator) DetachNetwork(ctx context.Context, aID string) error {
+ return r.agent.withSession(ctx, func(session *session) error {
+ client := api.NewResourceAllocatorClient(session.conn.ClientConn)
+ _, err := client.DetachNetwork(ctx, &api.DetachNetworkRequest{
+ AttachmentID: aID,
+ })
+
+ return err
+ })
+}
+
+// ResourceAllocator provides an interface to access resource
+// allocation methods such as AttachNetwork and DetachNetwork.
+func (a *Agent) ResourceAllocator() ResourceAllocator {
+ return &resourceAllocator{agent: a}
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/secrets/secrets.go b/vendor/github.com/docker/swarmkit/agent/secrets/secrets.go
new file mode 100644
index 0000000..233101d
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/secrets/secrets.go
@@ -0,0 +1,88 @@
+package secrets
+
+import (
+ "fmt"
+ "sync"
+
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/api"
+)
+
+// secrets is a map that keeps all the currently available secrets to the agent
+// mapped by secret ID.
+type secrets struct {
+ mu sync.RWMutex
+ m map[string]*api.Secret
+}
+
+// NewManager returns a place to store secrets.
+func NewManager() exec.SecretsManager {
+ return &secrets{
+ m: make(map[string]*api.Secret),
+ }
+}
+
+// Get returns a secret by ID. If the secret doesn't exist, returns nil.
+func (s *secrets) Get(secretID string) (*api.Secret, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s, ok := s.m[secretID]; ok {
+ return s, nil
+ }
+ return nil, fmt.Errorf("secret %s not found", secretID)
+}
+
+// Add adds one or more secrets to the secret map.
+func (s *secrets) Add(secrets ...api.Secret) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for _, secret := range secrets {
+ s.m[secret.ID] = secret.Copy()
+ }
+}
+
+// Remove removes one or more secrets by ID from the secret map. Succeeds
+// whether or not the given IDs are in the map.
+func (s *secrets) Remove(secrets []string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for _, secret := range secrets {
+ delete(s.m, secret)
+ }
+}
+
+// Reset removes all the secrets.
+func (s *secrets) Reset() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.m = make(map[string]*api.Secret)
+}
+
+// taskRestrictedSecretsProvider restricts the ids to the task.
+type taskRestrictedSecretsProvider struct {
+ secrets exec.SecretGetter
+ secretIDs map[string]struct{} // allow list of secret ids
+}
+
+func (sp *taskRestrictedSecretsProvider) Get(secretID string) (*api.Secret, error) {
+ if _, ok := sp.secretIDs[secretID]; !ok {
+ return nil, fmt.Errorf("task not authorized to access secret %s", secretID)
+ }
+
+ return sp.secrets.Get(secretID)
+}
+
+// Restrict provides a getter that only allows access to the secrets
+// referenced by the task.
+func Restrict(secrets exec.SecretGetter, t *api.Task) exec.SecretGetter {
+ sids := map[string]struct{}{}
+
+ container := t.Spec.GetContainer()
+ if container != nil {
+ for _, ref := range container.Secrets {
+ sids[ref.SecretID] = struct{}{}
+ }
+ }
+
+ return &taskRestrictedSecretsProvider{secrets: secrets, secretIDs: sids}
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/session.go b/vendor/github.com/docker/swarmkit/agent/session.go
new file mode 100644
index 0000000..faa1fa8
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/session.go
@@ -0,0 +1,423 @@
+package agent
+
+import (
+ "errors"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/connectionbroker"
+ "github.com/docker/swarmkit/log"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+var (
+ dispatcherRPCTimeout = 5 * time.Second
+ errSessionDisconnect = errors.New("agent: session disconnect") // instructed to disconnect
+ errSessionClosed = errors.New("agent: session closed")
+)
+
+// session encapsulates one round of registration with the manager. session
+// starts the registration and heartbeat control cycle. Any failure will result
+// in a complete shutdown of the session and it must be reestablished.
+//
+// All communication with the master is done through session. Changes that
+// flow into the agent, such as task assignment, are called back into the
+// agent through errs, messages and tasks.
+type session struct {
+ conn *connectionbroker.Conn
+
+ agent *Agent
+ sessionID string
+ session api.Dispatcher_SessionClient
+ errs chan error
+ messages chan *api.SessionMessage
+ assignments chan *api.AssignmentsMessage
+ subscriptions chan *api.SubscriptionMessage
+
+ cancel func() // this is assumed to be never nil, and set whenever a session is created
+ registered chan struct{} // closed registration
+ closed chan struct{}
+ closeOnce sync.Once
+}
+
+func newSession(ctx context.Context, agent *Agent, delay time.Duration, sessionID string, description *api.NodeDescription) *session {
+ sessionCtx, sessionCancel := context.WithCancel(ctx)
+ s := &session{
+ agent: agent,
+ sessionID: sessionID,
+ errs: make(chan error, 1),
+ messages: make(chan *api.SessionMessage),
+ assignments: make(chan *api.AssignmentsMessage),
+ subscriptions: make(chan *api.SubscriptionMessage),
+ registered: make(chan struct{}),
+ closed: make(chan struct{}),
+ cancel: sessionCancel,
+ }
+
+ // TODO(stevvooe): Need to move connection management up a level or create
+ // independent connection for log broker client.
+
+ cc, err := agent.config.ConnBroker.Select(
+ grpc.WithTransportCredentials(agent.config.Credentials),
+ grpc.WithTimeout(dispatcherRPCTimeout),
+ )
+ if err != nil {
+ s.errs <- err
+ return s
+ }
+ s.conn = cc
+
+ go s.run(sessionCtx, delay, description)
+ return s
+}
+
+func (s *session) run(ctx context.Context, delay time.Duration, description *api.NodeDescription) {
+ timer := time.NewTimer(delay) // delay before registering.
+ defer timer.Stop()
+ select {
+ case <-timer.C:
+ case <-ctx.Done():
+ return
+ }
+
+ if err := s.start(ctx, description); err != nil {
+ select {
+ case s.errs <- err:
+ case <-s.closed:
+ case <-ctx.Done():
+ }
+ return
+ }
+
+ ctx = log.WithLogger(ctx, log.G(ctx).WithField("session.id", s.sessionID))
+
+ go runctx(ctx, s.closed, s.errs, s.heartbeat)
+ go runctx(ctx, s.closed, s.errs, s.watch)
+ go runctx(ctx, s.closed, s.errs, s.listen)
+ go runctx(ctx, s.closed, s.errs, s.logSubscriptions)
+
+ close(s.registered)
+}
+
+// start begins the session and returns the first SessionMessage.
+func (s *session) start(ctx context.Context, description *api.NodeDescription) error {
+ log.G(ctx).Debugf("(*session).start")
+
+ errChan := make(chan error, 1)
+ var (
+ msg *api.SessionMessage
+ stream api.Dispatcher_SessionClient
+ err error
+ )
+ // Note: we don't defer cancellation of this context, because the
+ // streaming RPC is used after this function returned. We only cancel
+ // it in the timeout case to make sure the goroutine completes.
+
+ // We also fork this context again from the `run` context, because on
+ // `dispatcherRPCTimeout`, we want to cancel establishing a session and
+ // return an error. If we cancel the `run` context instead of forking,
+ // then in `run` it's possible that we just terminate the function because
+ // `ctx` is done and hence fail to propagate the timeout error to the agent.
+ // If the error is not propogated to the agent, the agent will not close
+ // the session or rebuild a new sesssion.
+ sessionCtx, cancelSession := context.WithCancel(ctx)
+
+ // Need to run Session in a goroutine since there's no way to set a
+ // timeout for an individual Recv call in a stream.
+ go func() {
+ client := api.NewDispatcherClient(s.conn.ClientConn)
+
+ stream, err = client.Session(sessionCtx, &api.SessionRequest{
+ Description: description,
+ SessionID: s.sessionID,
+ })
+ if err != nil {
+ errChan <- err
+ return
+ }
+
+ msg, err = stream.Recv()
+ errChan <- err
+ }()
+
+ select {
+ case err := <-errChan:
+ if err != nil {
+ return err
+ }
+ case <-time.After(dispatcherRPCTimeout):
+ cancelSession()
+ return errors.New("session initiation timed out")
+ }
+
+ s.sessionID = msg.SessionID
+ s.session = stream
+
+ return s.handleSessionMessage(ctx, msg)
+}
+
+func (s *session) heartbeat(ctx context.Context) error {
+ log.G(ctx).Debugf("(*session).heartbeat")
+ client := api.NewDispatcherClient(s.conn.ClientConn)
+ heartbeat := time.NewTimer(1) // send out a heartbeat right away
+ defer heartbeat.Stop()
+
+ for {
+ select {
+ case <-heartbeat.C:
+ heartbeatCtx, cancel := context.WithTimeout(ctx, dispatcherRPCTimeout)
+ resp, err := client.Heartbeat(heartbeatCtx, &api.HeartbeatRequest{
+ SessionID: s.sessionID,
+ })
+ cancel()
+ if err != nil {
+ if grpc.Code(err) == codes.NotFound {
+ err = errNodeNotRegistered
+ }
+
+ return err
+ }
+
+ heartbeat.Reset(resp.Period)
+ case <-s.closed:
+ return errSessionClosed
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+}
+
+func (s *session) listen(ctx context.Context) error {
+ defer s.session.CloseSend()
+ log.G(ctx).Debugf("(*session).listen")
+ for {
+ msg, err := s.session.Recv()
+ if err != nil {
+ return err
+ }
+
+ if err := s.handleSessionMessage(ctx, msg); err != nil {
+ return err
+ }
+ }
+}
+
+func (s *session) handleSessionMessage(ctx context.Context, msg *api.SessionMessage) error {
+ select {
+ case s.messages <- msg:
+ return nil
+ case <-s.closed:
+ return errSessionClosed
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+func (s *session) logSubscriptions(ctx context.Context) error {
+ log := log.G(ctx).WithFields(logrus.Fields{"method": "(*session).logSubscriptions"})
+ log.Debugf("")
+
+ client := api.NewLogBrokerClient(s.conn.ClientConn)
+ subscriptions, err := client.ListenSubscriptions(ctx, &api.ListenSubscriptionsRequest{})
+ if err != nil {
+ return err
+ }
+ defer subscriptions.CloseSend()
+
+ for {
+ resp, err := subscriptions.Recv()
+ if grpc.Code(err) == codes.Unimplemented {
+ log.Warning("manager does not support log subscriptions")
+ // Don't return, because returning would bounce the session
+ select {
+ case <-s.closed:
+ return errSessionClosed
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+ if err != nil {
+ return err
+ }
+
+ select {
+ case s.subscriptions <- resp:
+ case <-s.closed:
+ return errSessionClosed
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+}
+
+func (s *session) watch(ctx context.Context) error {
+ log := log.G(ctx).WithFields(logrus.Fields{"method": "(*session).watch"})
+ log.Debugf("")
+ var (
+ resp *api.AssignmentsMessage
+ assignmentWatch api.Dispatcher_AssignmentsClient
+ tasksWatch api.Dispatcher_TasksClient
+ streamReference string
+ tasksFallback bool
+ err error
+ )
+
+ client := api.NewDispatcherClient(s.conn.ClientConn)
+ for {
+ // If this is the first time we're running the loop, or there was a reference mismatch
+ // attempt to get the assignmentWatch
+ if assignmentWatch == nil && !tasksFallback {
+ assignmentWatch, err = client.Assignments(ctx, &api.AssignmentsRequest{SessionID: s.sessionID})
+ if err != nil {
+ return err
+ }
+ }
+ // We have an assignmentWatch, let's try to receive an AssignmentMessage
+ if assignmentWatch != nil {
+ // If we get a code = 12 desc = unknown method Assignments, try to use tasks
+ resp, err = assignmentWatch.Recv()
+ if err != nil {
+ if grpc.Code(err) != codes.Unimplemented {
+ return err
+ }
+ tasksFallback = true
+ assignmentWatch = nil
+ log.WithError(err).Infof("falling back to Tasks")
+ }
+ }
+
+ // This code is here for backwards compatibility (so that newer clients can use the
+ // older method Tasks)
+ if tasksWatch == nil && tasksFallback {
+ tasksWatch, err = client.Tasks(ctx, &api.TasksRequest{SessionID: s.sessionID})
+ if err != nil {
+ return err
+ }
+ }
+ if tasksWatch != nil {
+ // When falling back to Tasks because of an old managers, we wrap the tasks in assignments.
+ var taskResp *api.TasksMessage
+ var assignmentChanges []*api.AssignmentChange
+ taskResp, err = tasksWatch.Recv()
+ if err != nil {
+ return err
+ }
+ for _, t := range taskResp.Tasks {
+ taskChange := &api.AssignmentChange{
+ Assignment: &api.Assignment{
+ Item: &api.Assignment_Task{
+ Task: t,
+ },
+ },
+ Action: api.AssignmentChange_AssignmentActionUpdate,
+ }
+
+ assignmentChanges = append(assignmentChanges, taskChange)
+ }
+ resp = &api.AssignmentsMessage{Type: api.AssignmentsMessage_COMPLETE, Changes: assignmentChanges}
+ }
+
+ // If there seems to be a gap in the stream, let's break out of the inner for and
+ // re-sync (by calling Assignments again).
+ if streamReference != "" && streamReference != resp.AppliesTo {
+ assignmentWatch = nil
+ } else {
+ streamReference = resp.ResultsIn
+ }
+
+ select {
+ case s.assignments <- resp:
+ case <-s.closed:
+ return errSessionClosed
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+}
+
+// sendTaskStatus uses the current session to send the status of a single task.
+func (s *session) sendTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error {
+ client := api.NewDispatcherClient(s.conn.ClientConn)
+ if _, err := client.UpdateTaskStatus(ctx, &api.UpdateTaskStatusRequest{
+ SessionID: s.sessionID,
+ Updates: []*api.UpdateTaskStatusRequest_TaskStatusUpdate{
+ {
+ TaskID: taskID,
+ Status: status,
+ },
+ },
+ }); err != nil {
+ // TODO(stevvooe): Dispatcher should not return this error. Status
+ // reports for unknown tasks should be ignored.
+ if grpc.Code(err) == codes.NotFound {
+ return errTaskUnknown
+ }
+
+ return err
+ }
+
+ return nil
+}
+
+func (s *session) sendTaskStatuses(ctx context.Context, updates ...*api.UpdateTaskStatusRequest_TaskStatusUpdate) ([]*api.UpdateTaskStatusRequest_TaskStatusUpdate, error) {
+ if len(updates) < 1 {
+ return nil, nil
+ }
+
+ const batchSize = 1024
+ select {
+ case <-s.registered:
+ select {
+ case <-s.closed:
+ return updates, ErrClosed
+ default:
+ }
+ case <-s.closed:
+ return updates, ErrClosed
+ case <-ctx.Done():
+ return updates, ctx.Err()
+ }
+
+ client := api.NewDispatcherClient(s.conn.ClientConn)
+ n := batchSize
+
+ if len(updates) < n {
+ n = len(updates)
+ }
+
+ if _, err := client.UpdateTaskStatus(ctx, &api.UpdateTaskStatusRequest{
+ SessionID: s.sessionID,
+ Updates: updates[:n],
+ }); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed sending task status batch size of %d", len(updates[:n]))
+ return updates, err
+ }
+
+ return updates[n:], nil
+}
+
+// sendError is used to send errors to errs channel and trigger session recreation
+func (s *session) sendError(err error) {
+ select {
+ case s.errs <- err:
+ case <-s.closed:
+ }
+}
+
+// close closing session. It should be called only in <-session.errs branch
+// of event loop, or when cleaning up the agent.
+func (s *session) close() error {
+ s.closeOnce.Do(func() {
+ s.cancel()
+ if s.conn != nil {
+ s.conn.Close(false)
+ }
+ close(s.closed)
+ })
+
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/storage.go b/vendor/github.com/docker/swarmkit/agent/storage.go
new file mode 100644
index 0000000..f488de7
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/storage.go
@@ -0,0 +1,216 @@
+package agent
+
+import (
+ "github.com/boltdb/bolt"
+ "github.com/docker/swarmkit/api"
+ "github.com/gogo/protobuf/proto"
+)
+
+// Layout:
+//
+// bucket(v1.tasks.<id>) ->
+// data (task protobuf)
+// status (task status protobuf)
+// assigned (key present)
+var (
+ bucketKeyStorageVersion = []byte("v1")
+ bucketKeyTasks = []byte("tasks")
+ bucketKeyAssigned = []byte("assigned")
+ bucketKeyData = []byte("data")
+ bucketKeyStatus = []byte("status")
+)
+
+// InitDB prepares a database for writing task data.
+//
+// Proper buckets will be created if they don't already exist.
+func InitDB(db *bolt.DB) error {
+ return db.Update(func(tx *bolt.Tx) error {
+ _, err := createBucketIfNotExists(tx, bucketKeyStorageVersion, bucketKeyTasks)
+ return err
+ })
+}
+
+// GetTask retrieves the task with id from the datastore.
+func GetTask(tx *bolt.Tx, id string) (*api.Task, error) {
+ var t api.Task
+
+ if err := withTaskBucket(tx, id, func(bkt *bolt.Bucket) error {
+ p := bkt.Get([]byte("data"))
+ if p == nil {
+ return errTaskUnknown
+ }
+
+ return proto.Unmarshal(p, &t)
+ }); err != nil {
+ return nil, err
+ }
+
+ return &t, nil
+}
+
+// WalkTasks walks all tasks in the datastore.
+func WalkTasks(tx *bolt.Tx, fn func(task *api.Task) error) error {
+ bkt := getTasksBucket(tx)
+ if bkt == nil {
+ return nil
+ }
+
+ return bkt.ForEach(func(k, v []byte) error {
+ tbkt := bkt.Bucket(k)
+
+ p := tbkt.Get(bucketKeyData)
+ var t api.Task
+ if err := proto.Unmarshal(p, &t); err != nil {
+ return err
+ }
+
+ return fn(&t)
+ })
+}
+
+// TaskAssigned returns true if the task is assigned to the node.
+func TaskAssigned(tx *bolt.Tx, id string) bool {
+ bkt := getTaskBucket(tx, id)
+ if bkt == nil {
+ return false
+ }
+
+ return len(bkt.Get(bucketKeyAssigned)) > 0
+}
+
+// GetTaskStatus returns the current status for the task.
+func GetTaskStatus(tx *bolt.Tx, id string) (*api.TaskStatus, error) {
+ var ts api.TaskStatus
+ if err := withTaskBucket(tx, id, func(bkt *bolt.Bucket) error {
+ p := bkt.Get(bucketKeyStatus)
+ if p == nil {
+ return errTaskUnknown
+ }
+
+ return proto.Unmarshal(p, &ts)
+ }); err != nil {
+ return nil, err
+ }
+
+ return &ts, nil
+}
+
+// WalkTaskStatus calls fn for the status of each task.
+func WalkTaskStatus(tx *bolt.Tx, fn func(id string, status *api.TaskStatus) error) error {
+ bkt := getTasksBucket(tx)
+ if bkt == nil {
+ return nil
+ }
+
+ return bkt.ForEach(func(k, v []byte) error {
+ tbkt := bkt.Bucket(k)
+
+ p := tbkt.Get(bucketKeyStatus)
+ var ts api.TaskStatus
+ if err := proto.Unmarshal(p, &ts); err != nil {
+ return err
+ }
+
+ return fn(string(k), &ts)
+ })
+}
+
+// PutTask places the task into the database.
+func PutTask(tx *bolt.Tx, task *api.Task) error {
+ return withCreateTaskBucketIfNotExists(tx, task.ID, func(bkt *bolt.Bucket) error {
+ taskCopy := *task
+ taskCopy.Status = api.TaskStatus{} // blank out the status.
+
+ p, err := proto.Marshal(&taskCopy)
+ if err != nil {
+ return err
+ }
+ return bkt.Put(bucketKeyData, p)
+ })
+}
+
+// PutTaskStatus updates the status for the task with id.
+func PutTaskStatus(tx *bolt.Tx, id string, status *api.TaskStatus) error {
+ return withCreateTaskBucketIfNotExists(tx, id, func(bkt *bolt.Bucket) error {
+ p, err := proto.Marshal(status)
+ if err != nil {
+ return err
+ }
+ return bkt.Put([]byte("status"), p)
+ })
+}
+
+// DeleteTask completely removes the task from the database.
+func DeleteTask(tx *bolt.Tx, id string) error {
+ bkt := getTasksBucket(tx)
+ if bkt == nil {
+ return nil
+ }
+
+ return bkt.DeleteBucket([]byte(id))
+}
+
+// SetTaskAssignment sets the current assignment state.
+func SetTaskAssignment(tx *bolt.Tx, id string, assigned bool) error {
+ return withTaskBucket(tx, id, func(bkt *bolt.Bucket) error {
+ if assigned {
+ return bkt.Put([]byte("assigned"), []byte{0xFF})
+ }
+ return bkt.Delete([]byte("assigned"))
+ })
+}
+
+func createBucketIfNotExists(tx *bolt.Tx, keys ...[]byte) (*bolt.Bucket, error) {
+ bkt, err := tx.CreateBucketIfNotExists(keys[0])
+ if err != nil {
+ return nil, err
+ }
+
+ for _, key := range keys[1:] {
+ bkt, err = bkt.CreateBucketIfNotExists(key)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ return bkt, nil
+}
+
+func withCreateTaskBucketIfNotExists(tx *bolt.Tx, id string, fn func(bkt *bolt.Bucket) error) error {
+ bkt, err := createBucketIfNotExists(tx, bucketKeyStorageVersion, bucketKeyTasks, []byte(id))
+ if err != nil {
+ return err
+ }
+
+ return fn(bkt)
+}
+
+func withTaskBucket(tx *bolt.Tx, id string, fn func(bkt *bolt.Bucket) error) error {
+ bkt := getTaskBucket(tx, id)
+ if bkt == nil {
+ return errTaskUnknown
+ }
+
+ return fn(bkt)
+}
+
+func getTaskBucket(tx *bolt.Tx, id string) *bolt.Bucket {
+ return getBucket(tx, bucketKeyStorageVersion, bucketKeyTasks, []byte(id))
+}
+
+func getTasksBucket(tx *bolt.Tx) *bolt.Bucket {
+ return getBucket(tx, bucketKeyStorageVersion, bucketKeyTasks)
+}
+
+func getBucket(tx *bolt.Tx, keys ...[]byte) *bolt.Bucket {
+ bkt := tx.Bucket(keys[0])
+
+ for _, key := range keys[1:] {
+ if bkt == nil {
+ break
+ }
+ bkt = bkt.Bucket(key)
+ }
+
+ return bkt
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/task.go b/vendor/github.com/docker/swarmkit/agent/task.go
new file mode 100644
index 0000000..95fe931
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/task.go
@@ -0,0 +1,248 @@
+package agent
+
+import (
+ "sync"
+ "time"
+
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/equality"
+ "github.com/docker/swarmkit/log"
+ "golang.org/x/net/context"
+)
+
+// taskManager manages all aspects of task execution and reporting for an agent
+// through state management.
+type taskManager struct {
+ task *api.Task
+ ctlr exec.Controller
+ reporter StatusReporter
+
+ updateq chan *api.Task
+
+ shutdown chan struct{}
+ shutdownOnce sync.Once
+ closed chan struct{}
+ closeOnce sync.Once
+}
+
+func newTaskManager(ctx context.Context, task *api.Task, ctlr exec.Controller, reporter StatusReporter) *taskManager {
+ t := &taskManager{
+ task: task.Copy(),
+ ctlr: ctlr,
+ reporter: reporter,
+ updateq: make(chan *api.Task),
+ shutdown: make(chan struct{}),
+ closed: make(chan struct{}),
+ }
+ go t.run(ctx)
+ return t
+}
+
+// Update the task data.
+func (tm *taskManager) Update(ctx context.Context, task *api.Task) error {
+ select {
+ case tm.updateq <- task:
+ return nil
+ case <-tm.closed:
+ return ErrClosed
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+// Close shuts down the task manager, blocking until it is closed.
+func (tm *taskManager) Close() error {
+ tm.shutdownOnce.Do(func() {
+ close(tm.shutdown)
+ })
+
+ <-tm.closed
+
+ return nil
+}
+
+func (tm *taskManager) Logs(ctx context.Context, options api.LogSubscriptionOptions, publisher exec.LogPublisher) {
+ ctx = log.WithModule(ctx, "taskmanager")
+
+ logCtlr, ok := tm.ctlr.(exec.ControllerLogs)
+ if !ok {
+ return // no logs available
+ }
+ if err := logCtlr.Logs(ctx, publisher, options); err != nil {
+ log.G(ctx).WithError(err).Errorf("logs call failed")
+ }
+}
+
+func (tm *taskManager) run(ctx context.Context) {
+ ctx, cancelAll := context.WithCancel(ctx)
+ defer cancelAll() // cancel all child operations on exit.
+
+ ctx = log.WithModule(ctx, "taskmanager")
+
+ var (
+ opctx context.Context
+ cancel context.CancelFunc
+ run = make(chan struct{}, 1)
+ statusq = make(chan *api.TaskStatus)
+ errs = make(chan error)
+ shutdown = tm.shutdown
+ updated bool // true if the task was updated.
+ )
+
+ defer func() {
+ // closure picks up current value of cancel.
+ if cancel != nil {
+ cancel()
+ }
+ }()
+
+ run <- struct{}{} // prime the pump
+ for {
+ select {
+ case <-run:
+ // always check for shutdown before running.
+ select {
+ case <-tm.shutdown:
+ shutdown = tm.shutdown // a little questionable
+ continue // ignore run request and handle shutdown
+ case <-tm.closed:
+ continue
+ default:
+ }
+
+ opctx, cancel = context.WithCancel(ctx)
+
+ // Several variables need to be snapshotted for the closure below.
+ opcancel := cancel // fork for the closure
+ running := tm.task.Copy() // clone the task before dispatch
+ statusqLocal := statusq
+ updatedLocal := updated // capture state of update for goroutine
+ updated = false
+ go runctx(ctx, tm.closed, errs, func(ctx context.Context) error {
+ defer opcancel()
+
+ if updatedLocal {
+ // before we do anything, update the task for the controller.
+ // always update the controller before running.
+ if err := tm.ctlr.Update(opctx, running); err != nil {
+ log.G(ctx).WithError(err).Error("updating task controller failed")
+ return err
+ }
+ }
+
+ status, err := exec.Do(opctx, running, tm.ctlr)
+ if status != nil {
+ // always report the status if we get one back. This
+ // returns to the manager loop, then reports the status
+ // upstream.
+ select {
+ case statusqLocal <- status:
+ case <-ctx.Done(): // not opctx, since that may have been cancelled.
+ }
+
+ if err := tm.reporter.UpdateTaskStatus(ctx, running.ID, status); err != nil {
+ log.G(ctx).WithError(err).Error("task manager failed to report status to agent")
+ }
+ }
+
+ return err
+ })
+ case err := <-errs:
+ // This branch is always executed when an operations completes. The
+ // goal is to decide whether or not we re-dispatch the operation.
+ cancel = nil
+
+ select {
+ case <-tm.shutdown:
+ shutdown = tm.shutdown // re-enable the shutdown branch
+ continue // no dispatch if we are in shutdown.
+ default:
+ }
+
+ switch err {
+ case exec.ErrTaskNoop:
+ if !updated {
+ continue // wait till getting pumped via update.
+ }
+ case exec.ErrTaskRetry:
+ // TODO(stevvooe): Add exponential backoff with random jitter
+ // here. For now, this backoff is enough to keep the task
+ // manager from running away with the CPU.
+ time.AfterFunc(time.Second, func() {
+ errs <- nil // repump this branch, with no err
+ })
+ continue
+ case nil, context.Canceled, context.DeadlineExceeded:
+ // no log in this case
+ default:
+ log.G(ctx).WithError(err).Error("task operation failed")
+ }
+
+ select {
+ case run <- struct{}{}:
+ default:
+ }
+ case status := <-statusq:
+ tm.task.Status = *status
+ case task := <-tm.updateq:
+ if equality.TasksEqualStable(task, tm.task) {
+ continue // ignore the update
+ }
+
+ if task.ID != tm.task.ID {
+ log.G(ctx).WithField("task.update.id", task.ID).Error("received update for incorrect task")
+ continue
+ }
+
+ if task.DesiredState < tm.task.DesiredState {
+ log.G(ctx).WithField("task.update.desiredstate", task.DesiredState).
+ Error("ignoring task update with invalid desired state")
+ continue
+ }
+
+ task = task.Copy()
+ task.Status = tm.task.Status // overwrite our status, as it is canonical.
+ tm.task = task
+ updated = true
+
+ // we have accepted the task update
+ if cancel != nil {
+ cancel() // cancel outstanding if necessary.
+ } else {
+ // If this channel op fails, it means there is already a
+ // message on the run queue.
+ select {
+ case run <- struct{}{}:
+ default:
+ }
+ }
+ case <-shutdown:
+ if cancel != nil {
+ // cancel outstanding operation.
+ cancel()
+
+ // subtle: after a cancellation, we want to avoid busy wait
+ // here. this gets renabled in the errs branch and we'll come
+ // back around and try shutdown again.
+ shutdown = nil // turn off this branch until op proceeds
+ continue // wait until operation actually exits.
+ }
+
+ // disable everything, and prepare for closing.
+ statusq = nil
+ errs = nil
+ shutdown = nil
+ tm.closeOnce.Do(func() {
+ close(tm.closed)
+ })
+ case <-tm.closed:
+ return
+ case <-ctx.Done():
+ tm.closeOnce.Do(func() {
+ close(tm.closed)
+ })
+ return
+ }
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/agent/worker.go b/vendor/github.com/docker/swarmkit/agent/worker.go
new file mode 100644
index 0000000..ff138c2
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/agent/worker.go
@@ -0,0 +1,604 @@
+package agent
+
+import (
+ "sync"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/boltdb/bolt"
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/watch"
+ "golang.org/x/net/context"
+)
+
+// Worker implements the core task management logic and persistence. It
+// coordinates the set of assignments with the executor.
+type Worker interface {
+ // Init prepares the worker for task assignment.
+ Init(ctx context.Context) error
+
+ // Close performs worker cleanup when no longer needed.
+ //
+ // It is not safe to call any worker function after that.
+ Close()
+
+ // Assign assigns a complete set of tasks and configs/secrets to a
+ // worker. Any items not included in this set will be removed.
+ Assign(ctx context.Context, assignments []*api.AssignmentChange) error
+
+ // Updates updates an incremental set of tasks or configs/secrets of
+ // the worker. Any items not included either in added or removed will
+ // remain untouched.
+ Update(ctx context.Context, assignments []*api.AssignmentChange) error
+
+ // Listen to updates about tasks controlled by the worker. When first
+ // called, the reporter will receive all updates for all tasks controlled
+ // by the worker.
+ //
+ // The listener will be removed if the context is cancelled.
+ Listen(ctx context.Context, reporter StatusReporter)
+
+ // Subscribe to log messages matching the subscription.
+ Subscribe(ctx context.Context, subscription *api.SubscriptionMessage) error
+
+ // Wait blocks until all task managers have closed
+ Wait(ctx context.Context) error
+}
+
+// statusReporterKey protects removal map from panic.
+type statusReporterKey struct {
+ StatusReporter
+}
+
+type worker struct {
+ db *bolt.DB
+ executor exec.Executor
+ publisher exec.LogPublisher
+ listeners map[*statusReporterKey]struct{}
+ taskevents *watch.Queue
+ publisherProvider exec.LogPublisherProvider
+
+ taskManagers map[string]*taskManager
+ mu sync.RWMutex
+
+ closed bool
+ closers sync.WaitGroup // keeps track of active closers
+}
+
+func newWorker(db *bolt.DB, executor exec.Executor, publisherProvider exec.LogPublisherProvider) *worker {
+ return &worker{
+ db: db,
+ executor: executor,
+ publisherProvider: publisherProvider,
+ taskevents: watch.NewQueue(),
+ listeners: make(map[*statusReporterKey]struct{}),
+ taskManagers: make(map[string]*taskManager),
+ }
+}
+
+// Init prepares the worker for assignments.
+func (w *worker) Init(ctx context.Context) error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ ctx = log.WithModule(ctx, "worker")
+
+ // TODO(stevvooe): Start task cleanup process.
+
+ // read the tasks from the database and start any task managers that may be needed.
+ return w.db.Update(func(tx *bolt.Tx) error {
+ return WalkTasks(tx, func(task *api.Task) error {
+ if !TaskAssigned(tx, task.ID) {
+ // NOTE(stevvooe): If tasks can survive worker restart, we need
+ // to startup the controller and ensure they are removed. For
+ // now, we can simply remove them from the database.
+ if err := DeleteTask(tx, task.ID); err != nil {
+ log.G(ctx).WithError(err).Errorf("error removing task %v", task.ID)
+ }
+ return nil
+ }
+
+ status, err := GetTaskStatus(tx, task.ID)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("unable to read tasks status")
+ return nil
+ }
+
+ task.Status = *status // merges the status into the task, ensuring we start at the right point.
+ return w.startTask(ctx, tx, task)
+ })
+ })
+}
+
+// Close performs worker cleanup when no longer needed.
+func (w *worker) Close() {
+ w.mu.Lock()
+ w.closed = true
+ w.mu.Unlock()
+
+ w.taskevents.Close()
+}
+
+// Assign assigns a full set of tasks, configs, and secrets to the worker.
+// Any tasks not previously known will be started. Any tasks that are in the task set
+// and already running will be updated, if possible. Any tasks currently running on
+// the worker outside the task set will be terminated.
+// Anything not in the set of assignments will be removed.
+func (w *worker) Assign(ctx context.Context, assignments []*api.AssignmentChange) error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ if w.closed {
+ return ErrClosed
+ }
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "len(assignments)": len(assignments),
+ }).Debug("(*worker).Assign")
+
+ // Need to update dependencies before tasks
+
+ err := reconcileSecrets(ctx, w, assignments, true)
+ if err != nil {
+ return err
+ }
+
+ err = reconcileConfigs(ctx, w, assignments, true)
+ if err != nil {
+ return err
+ }
+
+ return reconcileTaskState(ctx, w, assignments, true)
+}
+
+// Update updates the set of tasks, configs, and secrets for the worker.
+// Tasks in the added set will be added to the worker, and tasks in the removed set
+// will be removed from the worker
+// Secrets in the added set will be added to the worker, and secrets in the removed set
+// will be removed from the worker.
+// Configs in the added set will be added to the worker, and configs in the removed set
+// will be removed from the worker.
+func (w *worker) Update(ctx context.Context, assignments []*api.AssignmentChange) error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ if w.closed {
+ return ErrClosed
+ }
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "len(assignments)": len(assignments),
+ }).Debug("(*worker).Update")
+
+ err := reconcileSecrets(ctx, w, assignments, false)
+ if err != nil {
+ return err
+ }
+
+ err = reconcileConfigs(ctx, w, assignments, false)
+ if err != nil {
+ return err
+ }
+
+ return reconcileTaskState(ctx, w, assignments, false)
+}
+
+func reconcileTaskState(ctx context.Context, w *worker, assignments []*api.AssignmentChange, fullSnapshot bool) error {
+ var (
+ updatedTasks []*api.Task
+ removedTasks []*api.Task
+ )
+ for _, a := range assignments {
+ if t := a.Assignment.GetTask(); t != nil {
+ switch a.Action {
+ case api.AssignmentChange_AssignmentActionUpdate:
+ updatedTasks = append(updatedTasks, t)
+ case api.AssignmentChange_AssignmentActionRemove:
+ removedTasks = append(removedTasks, t)
+ }
+ }
+ }
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "len(updatedTasks)": len(updatedTasks),
+ "len(removedTasks)": len(removedTasks),
+ }).Debug("(*worker).reconcileTaskState")
+
+ tx, err := w.db.Begin(true)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed starting transaction against task database")
+ return err
+ }
+ defer tx.Rollback()
+
+ assigned := map[string]struct{}{}
+
+ for _, task := range updatedTasks {
+ log.G(ctx).WithFields(
+ logrus.Fields{
+ "task.id": task.ID,
+ "task.desiredstate": task.DesiredState}).Debug("assigned")
+ if err := PutTask(tx, task); err != nil {
+ return err
+ }
+
+ if err := SetTaskAssignment(tx, task.ID, true); err != nil {
+ return err
+ }
+
+ if mgr, ok := w.taskManagers[task.ID]; ok {
+ if err := mgr.Update(ctx, task); err != nil && err != ErrClosed {
+ log.G(ctx).WithError(err).Error("failed updating assigned task")
+ }
+ } else {
+ // we may have still seen the task, let's grab the status from
+ // storage and replace it with our status, if we have it.
+ status, err := GetTaskStatus(tx, task.ID)
+ if err != nil {
+ if err != errTaskUnknown {
+ return err
+ }
+
+ // never seen before, register the provided status
+ if err := PutTaskStatus(tx, task.ID, &task.Status); err != nil {
+ return err
+ }
+ } else {
+ task.Status = *status
+ }
+ w.startTask(ctx, tx, task)
+ }
+
+ assigned[task.ID] = struct{}{}
+ }
+
+ closeManager := func(tm *taskManager) {
+ go func(tm *taskManager) {
+ defer w.closers.Done()
+ // when a task is no longer assigned, we shutdown the task manager
+ if err := tm.Close(); err != nil {
+ log.G(ctx).WithError(err).Error("error closing task manager")
+ }
+ }(tm)
+
+ // make an attempt at removing. this is best effort. any errors will be
+ // retried by the reaper later.
+ if err := tm.ctlr.Remove(ctx); err != nil {
+ log.G(ctx).WithError(err).WithField("task.id", tm.task.ID).Error("remove task failed")
+ }
+
+ if err := tm.ctlr.Close(); err != nil {
+ log.G(ctx).WithError(err).Error("error closing controller")
+ }
+ }
+
+ removeTaskAssignment := func(taskID string) error {
+ ctx := log.WithLogger(ctx, log.G(ctx).WithField("task.id", taskID))
+ if err := SetTaskAssignment(tx, taskID, false); err != nil {
+ log.G(ctx).WithError(err).Error("error setting task assignment in database")
+ }
+ return err
+ }
+
+ // If this was a complete set of assignments, we're going to remove all the remaining
+ // tasks.
+ if fullSnapshot {
+ for id, tm := range w.taskManagers {
+ if _, ok := assigned[id]; ok {
+ continue
+ }
+
+ err := removeTaskAssignment(id)
+ if err == nil {
+ delete(w.taskManagers, id)
+ go closeManager(tm)
+ }
+ }
+ } else {
+ // If this was an incremental set of assignments, we're going to remove only the tasks
+ // in the removed set
+ for _, task := range removedTasks {
+ err := removeTaskAssignment(task.ID)
+ if err != nil {
+ continue
+ }
+
+ tm, ok := w.taskManagers[task.ID]
+ if ok {
+ delete(w.taskManagers, task.ID)
+ go closeManager(tm)
+ }
+ }
+ }
+
+ return tx.Commit()
+}
+
+func reconcileSecrets(ctx context.Context, w *worker, assignments []*api.AssignmentChange, fullSnapshot bool) error {
+ var (
+ updatedSecrets []api.Secret
+ removedSecrets []string
+ )
+ for _, a := range assignments {
+ if s := a.Assignment.GetSecret(); s != nil {
+ switch a.Action {
+ case api.AssignmentChange_AssignmentActionUpdate:
+ updatedSecrets = append(updatedSecrets, *s)
+ case api.AssignmentChange_AssignmentActionRemove:
+ removedSecrets = append(removedSecrets, s.ID)
+ }
+
+ }
+ }
+
+ secretsProvider, ok := w.executor.(exec.SecretsProvider)
+ if !ok {
+ if len(updatedSecrets) != 0 || len(removedSecrets) != 0 {
+ log.G(ctx).Warn("secrets update ignored; executor does not support secrets")
+ }
+ return nil
+ }
+
+ secrets := secretsProvider.Secrets()
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "len(updatedSecrets)": len(updatedSecrets),
+ "len(removedSecrets)": len(removedSecrets),
+ }).Debug("(*worker).reconcileSecrets")
+
+ // If this was a complete set of secrets, we're going to clear the secrets map and add all of them
+ if fullSnapshot {
+ secrets.Reset()
+ } else {
+ secrets.Remove(removedSecrets)
+ }
+ secrets.Add(updatedSecrets...)
+
+ return nil
+}
+
+func reconcileConfigs(ctx context.Context, w *worker, assignments []*api.AssignmentChange, fullSnapshot bool) error {
+ var (
+ updatedConfigs []api.Config
+ removedConfigs []string
+ )
+ for _, a := range assignments {
+ if r := a.Assignment.GetConfig(); r != nil {
+ switch a.Action {
+ case api.AssignmentChange_AssignmentActionUpdate:
+ updatedConfigs = append(updatedConfigs, *r)
+ case api.AssignmentChange_AssignmentActionRemove:
+ removedConfigs = append(removedConfigs, r.ID)
+ }
+
+ }
+ }
+
+ configsProvider, ok := w.executor.(exec.ConfigsProvider)
+ if !ok {
+ if len(updatedConfigs) != 0 || len(removedConfigs) != 0 {
+ log.G(ctx).Warn("configs update ignored; executor does not support configs")
+ }
+ return nil
+ }
+
+ configs := configsProvider.Configs()
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "len(updatedConfigs)": len(updatedConfigs),
+ "len(removedConfigs)": len(removedConfigs),
+ }).Debug("(*worker).reconcileConfigs")
+
+ // If this was a complete set of configs, we're going to clear the configs map and add all of them
+ if fullSnapshot {
+ configs.Reset()
+ } else {
+ configs.Remove(removedConfigs)
+ }
+ configs.Add(updatedConfigs...)
+
+ return nil
+}
+
+func (w *worker) Listen(ctx context.Context, reporter StatusReporter) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+
+ key := &statusReporterKey{reporter}
+ w.listeners[key] = struct{}{}
+
+ go func() {
+ <-ctx.Done()
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ delete(w.listeners, key) // remove the listener if the context is closed.
+ }()
+
+ // report the current statuses to the new listener
+ if err := w.db.View(func(tx *bolt.Tx) error {
+ return WalkTaskStatus(tx, func(id string, status *api.TaskStatus) error {
+ return reporter.UpdateTaskStatus(ctx, id, status)
+ })
+ }); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed reporting initial statuses to registered listener %v", reporter)
+ }
+}
+
+func (w *worker) startTask(ctx context.Context, tx *bolt.Tx, task *api.Task) error {
+ _, err := w.taskManager(ctx, tx, task) // side-effect taskManager creation.
+
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed to start taskManager")
+ // we ignore this error: it gets reported in the taskStatus within
+ // `newTaskManager`. We log it here and move on. If their is an
+ // attempted restart, the lack of taskManager will have this retry
+ // again.
+ return nil
+ }
+
+ // only publish if controller resolution was successful.
+ w.taskevents.Publish(task.Copy())
+ return nil
+}
+
+func (w *worker) taskManager(ctx context.Context, tx *bolt.Tx, task *api.Task) (*taskManager, error) {
+ if tm, ok := w.taskManagers[task.ID]; ok {
+ return tm, nil
+ }
+
+ tm, err := w.newTaskManager(ctx, tx, task)
+ if err != nil {
+ return nil, err
+ }
+ w.taskManagers[task.ID] = tm
+ // keep track of active tasks
+ w.closers.Add(1)
+ return tm, nil
+}
+
+func (w *worker) newTaskManager(ctx context.Context, tx *bolt.Tx, task *api.Task) (*taskManager, error) {
+ ctx = log.WithLogger(ctx, log.G(ctx).WithFields(logrus.Fields{
+ "task.id": task.ID,
+ "service.id": task.ServiceID,
+ }))
+
+ ctlr, status, err := exec.Resolve(ctx, task, w.executor)
+ if err := w.updateTaskStatus(ctx, tx, task.ID, status); err != nil {
+ log.G(ctx).WithError(err).Error("error updating task status after controller resolution")
+ }
+
+ if err != nil {
+ log.G(ctx).WithError(err).Error("controller resolution failed")
+ return nil, err
+ }
+
+ return newTaskManager(ctx, task, ctlr, statusReporterFunc(func(ctx context.Context, taskID string, status *api.TaskStatus) error {
+ w.mu.RLock()
+ defer w.mu.RUnlock()
+
+ return w.db.Update(func(tx *bolt.Tx) error {
+ return w.updateTaskStatus(ctx, tx, taskID, status)
+ })
+ })), nil
+}
+
+// updateTaskStatus reports statuses to listeners, read lock must be held.
+func (w *worker) updateTaskStatus(ctx context.Context, tx *bolt.Tx, taskID string, status *api.TaskStatus) error {
+ if err := PutTaskStatus(tx, taskID, status); err != nil {
+ log.G(ctx).WithError(err).Error("failed writing status to disk")
+ return err
+ }
+
+ // broadcast the task status out.
+ for key := range w.listeners {
+ if err := key.StatusReporter.UpdateTaskStatus(ctx, taskID, status); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed updating status for reporter %v", key.StatusReporter)
+ }
+ }
+
+ return nil
+}
+
+// Subscribe to log messages matching the subscription.
+func (w *worker) Subscribe(ctx context.Context, subscription *api.SubscriptionMessage) error {
+ log.G(ctx).Debugf("Received subscription %s (selector: %v)", subscription.ID, subscription.Selector)
+
+ publisher, cancel, err := w.publisherProvider.Publisher(ctx, subscription.ID)
+ if err != nil {
+ return err
+ }
+ // Send a close once we're done
+ defer cancel()
+
+ match := func(t *api.Task) bool {
+ // TODO(aluzzardi): Consider using maps to limit the iterations.
+ for _, tid := range subscription.Selector.TaskIDs {
+ if t.ID == tid {
+ return true
+ }
+ }
+
+ for _, sid := range subscription.Selector.ServiceIDs {
+ if t.ServiceID == sid {
+ return true
+ }
+ }
+
+ for _, nid := range subscription.Selector.NodeIDs {
+ if t.NodeID == nid {
+ return true
+ }
+ }
+
+ return false
+ }
+
+ wg := sync.WaitGroup{}
+ w.mu.Lock()
+ for _, tm := range w.taskManagers {
+ if match(tm.task) {
+ wg.Add(1)
+ go func(tm *taskManager) {
+ defer wg.Done()
+ tm.Logs(ctx, *subscription.Options, publisher)
+ }(tm)
+ }
+ }
+ w.mu.Unlock()
+
+ // If follow mode is disabled, wait for the current set of matched tasks
+ // to finish publishing logs, then close the subscription by returning.
+ if subscription.Options == nil || !subscription.Options.Follow {
+ waitCh := make(chan struct{})
+ go func() {
+ defer close(waitCh)
+ wg.Wait()
+ }()
+
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-waitCh:
+ return nil
+ }
+ }
+
+ // In follow mode, watch for new tasks. Don't close the subscription
+ // until it's cancelled.
+ ch, cancel := w.taskevents.Watch()
+ defer cancel()
+ for {
+ select {
+ case v := <-ch:
+ task := v.(*api.Task)
+ if match(task) {
+ w.mu.RLock()
+ tm, ok := w.taskManagers[task.ID]
+ w.mu.RUnlock()
+ if !ok {
+ continue
+ }
+
+ go tm.Logs(ctx, *subscription.Options, publisher)
+ }
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+}
+
+func (w *worker) Wait(ctx context.Context) error {
+ ch := make(chan struct{})
+ go func() {
+ w.closers.Wait()
+ close(ch)
+ }()
+
+ select {
+ case <-ch:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/api/README.md b/vendor/github.com/docker/swarmkit/api/README.md
new file mode 100644
index 0000000..78eee22
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/README.md
@@ -0,0 +1,8 @@
+### Notice
+
+Do not change .pb.go files directly. You need to change the corresponding .proto files and run the following command to regenerate the .pb.go files.
+```
+$ make generate
+```
+
+Click [here](https://github.com/google/protobuf) for more information about protobuf.
diff --git a/vendor/github.com/docker/swarmkit/api/ca.pb.go b/vendor/github.com/docker/swarmkit/api/ca.pb.go
new file mode 100644
index 0000000..679e4a8
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/ca.pb.go
@@ -0,0 +1,2116 @@
+// Code generated by protoc-gen-gogo.
+// source: ca.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+import _ "github.com/docker/swarmkit/protobuf/plugin"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+import raftselector "github.com/docker/swarmkit/manager/raftselector"
+import codes "google.golang.org/grpc/codes"
+import metadata "google.golang.org/grpc/metadata"
+import transport "google.golang.org/grpc/transport"
+import rafttime "time"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+type NodeCertificateStatusRequest struct {
+ NodeID string `protobuf:"bytes,1,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"`
+}
+
+func (m *NodeCertificateStatusRequest) Reset() { *m = NodeCertificateStatusRequest{} }
+func (*NodeCertificateStatusRequest) ProtoMessage() {}
+func (*NodeCertificateStatusRequest) Descriptor() ([]byte, []int) { return fileDescriptorCa, []int{0} }
+
+type NodeCertificateStatusResponse struct {
+ Status *IssuanceStatus `protobuf:"bytes,1,opt,name=status" json:"status,omitempty"`
+ Certificate *Certificate `protobuf:"bytes,2,opt,name=certificate" json:"certificate,omitempty"`
+}
+
+func (m *NodeCertificateStatusResponse) Reset() { *m = NodeCertificateStatusResponse{} }
+func (*NodeCertificateStatusResponse) ProtoMessage() {}
+func (*NodeCertificateStatusResponse) Descriptor() ([]byte, []int) { return fileDescriptorCa, []int{1} }
+
+type IssueNodeCertificateRequest struct {
+ // DEPRECATED: Role is now selected based on which secret is matched.
+ Role NodeRole `protobuf:"varint,1,opt,name=role,proto3,enum=docker.swarmkit.v1.NodeRole" json:"role,omitempty"`
+ // CSR is the certificate signing request.
+ CSR []byte `protobuf:"bytes,2,opt,name=csr,proto3" json:"csr,omitempty"`
+ // Token represents a user-provided string that is necessary for new
+ // nodes to join the cluster
+ Token string `protobuf:"bytes,3,opt,name=token,proto3" json:"token,omitempty"`
+ // Availability allows a user to control the current scheduling status of a node
+ Availability NodeSpec_Availability `protobuf:"varint,4,opt,name=availability,proto3,enum=docker.swarmkit.v1.NodeSpec_Availability" json:"availability,omitempty"`
+}
+
+func (m *IssueNodeCertificateRequest) Reset() { *m = IssueNodeCertificateRequest{} }
+func (*IssueNodeCertificateRequest) ProtoMessage() {}
+func (*IssueNodeCertificateRequest) Descriptor() ([]byte, []int) { return fileDescriptorCa, []int{2} }
+
+type IssueNodeCertificateResponse struct {
+ NodeID string `protobuf:"bytes,1,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"`
+ NodeMembership NodeSpec_Membership `protobuf:"varint,2,opt,name=node_membership,json=nodeMembership,proto3,enum=docker.swarmkit.v1.NodeSpec_Membership" json:"node_membership,omitempty"`
+}
+
+func (m *IssueNodeCertificateResponse) Reset() { *m = IssueNodeCertificateResponse{} }
+func (*IssueNodeCertificateResponse) ProtoMessage() {}
+func (*IssueNodeCertificateResponse) Descriptor() ([]byte, []int) { return fileDescriptorCa, []int{3} }
+
+type GetRootCACertificateRequest struct {
+}
+
+func (m *GetRootCACertificateRequest) Reset() { *m = GetRootCACertificateRequest{} }
+func (*GetRootCACertificateRequest) ProtoMessage() {}
+func (*GetRootCACertificateRequest) Descriptor() ([]byte, []int) { return fileDescriptorCa, []int{4} }
+
+type GetRootCACertificateResponse struct {
+ Certificate []byte `protobuf:"bytes,1,opt,name=certificate,proto3" json:"certificate,omitempty"`
+}
+
+func (m *GetRootCACertificateResponse) Reset() { *m = GetRootCACertificateResponse{} }
+func (*GetRootCACertificateResponse) ProtoMessage() {}
+func (*GetRootCACertificateResponse) Descriptor() ([]byte, []int) { return fileDescriptorCa, []int{5} }
+
+type GetUnlockKeyRequest struct {
+}
+
+func (m *GetUnlockKeyRequest) Reset() { *m = GetUnlockKeyRequest{} }
+func (*GetUnlockKeyRequest) ProtoMessage() {}
+func (*GetUnlockKeyRequest) Descriptor() ([]byte, []int) { return fileDescriptorCa, []int{6} }
+
+type GetUnlockKeyResponse struct {
+ UnlockKey []byte `protobuf:"bytes,1,opt,name=unlock_key,json=unlockKey,proto3" json:"unlock_key,omitempty"`
+ Version Version `protobuf:"bytes,2,opt,name=version" json:"version"`
+}
+
+func (m *GetUnlockKeyResponse) Reset() { *m = GetUnlockKeyResponse{} }
+func (*GetUnlockKeyResponse) ProtoMessage() {}
+func (*GetUnlockKeyResponse) Descriptor() ([]byte, []int) { return fileDescriptorCa, []int{7} }
+
+func init() {
+ proto.RegisterType((*NodeCertificateStatusRequest)(nil), "docker.swarmkit.v1.NodeCertificateStatusRequest")
+ proto.RegisterType((*NodeCertificateStatusResponse)(nil), "docker.swarmkit.v1.NodeCertificateStatusResponse")
+ proto.RegisterType((*IssueNodeCertificateRequest)(nil), "docker.swarmkit.v1.IssueNodeCertificateRequest")
+ proto.RegisterType((*IssueNodeCertificateResponse)(nil), "docker.swarmkit.v1.IssueNodeCertificateResponse")
+ proto.RegisterType((*GetRootCACertificateRequest)(nil), "docker.swarmkit.v1.GetRootCACertificateRequest")
+ proto.RegisterType((*GetRootCACertificateResponse)(nil), "docker.swarmkit.v1.GetRootCACertificateResponse")
+ proto.RegisterType((*GetUnlockKeyRequest)(nil), "docker.swarmkit.v1.GetUnlockKeyRequest")
+ proto.RegisterType((*GetUnlockKeyResponse)(nil), "docker.swarmkit.v1.GetUnlockKeyResponse")
+}
+
+type authenticatedWrapperCAServer struct {
+ local CAServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperCAServer(local CAServer, authorize func(context.Context, []string) error) CAServer {
+ return &authenticatedWrapperCAServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperCAServer) GetRootCACertificate(ctx context.Context, r *GetRootCACertificateRequest) (*GetRootCACertificateResponse, error) {
+
+ return p.local.GetRootCACertificate(ctx, r)
+}
+
+func (p *authenticatedWrapperCAServer) GetUnlockKey(ctx context.Context, r *GetUnlockKeyRequest) (*GetUnlockKeyResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.GetUnlockKey(ctx, r)
+}
+
+type authenticatedWrapperNodeCAServer struct {
+ local NodeCAServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperNodeCAServer(local NodeCAServer, authorize func(context.Context, []string) error) NodeCAServer {
+ return &authenticatedWrapperNodeCAServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperNodeCAServer) IssueNodeCertificate(ctx context.Context, r *IssueNodeCertificateRequest) (*IssueNodeCertificateResponse, error) {
+
+ return p.local.IssueNodeCertificate(ctx, r)
+}
+
+func (p *authenticatedWrapperNodeCAServer) NodeCertificateStatus(ctx context.Context, r *NodeCertificateStatusRequest) (*NodeCertificateStatusResponse, error) {
+
+ return p.local.NodeCertificateStatus(ctx, r)
+}
+
+func (m *NodeCertificateStatusRequest) Copy() *NodeCertificateStatusRequest {
+ if m == nil {
+ return nil
+ }
+ o := &NodeCertificateStatusRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *NodeCertificateStatusRequest) CopyFrom(src interface{}) {
+
+ o := src.(*NodeCertificateStatusRequest)
+ *m = *o
+}
+
+func (m *NodeCertificateStatusResponse) Copy() *NodeCertificateStatusResponse {
+ if m == nil {
+ return nil
+ }
+ o := &NodeCertificateStatusResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *NodeCertificateStatusResponse) CopyFrom(src interface{}) {
+
+ o := src.(*NodeCertificateStatusResponse)
+ *m = *o
+ if o.Status != nil {
+ m.Status = &IssuanceStatus{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Status, o.Status)
+ }
+ if o.Certificate != nil {
+ m.Certificate = &Certificate{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Certificate, o.Certificate)
+ }
+}
+
+func (m *IssueNodeCertificateRequest) Copy() *IssueNodeCertificateRequest {
+ if m == nil {
+ return nil
+ }
+ o := &IssueNodeCertificateRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *IssueNodeCertificateRequest) CopyFrom(src interface{}) {
+
+ o := src.(*IssueNodeCertificateRequest)
+ *m = *o
+ if o.CSR != nil {
+ m.CSR = make([]byte, len(o.CSR))
+ copy(m.CSR, o.CSR)
+ }
+}
+
+func (m *IssueNodeCertificateResponse) Copy() *IssueNodeCertificateResponse {
+ if m == nil {
+ return nil
+ }
+ o := &IssueNodeCertificateResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *IssueNodeCertificateResponse) CopyFrom(src interface{}) {
+
+ o := src.(*IssueNodeCertificateResponse)
+ *m = *o
+}
+
+func (m *GetRootCACertificateRequest) Copy() *GetRootCACertificateRequest {
+ if m == nil {
+ return nil
+ }
+ o := &GetRootCACertificateRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetRootCACertificateRequest) CopyFrom(src interface{}) {}
+func (m *GetRootCACertificateResponse) Copy() *GetRootCACertificateResponse {
+ if m == nil {
+ return nil
+ }
+ o := &GetRootCACertificateResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetRootCACertificateResponse) CopyFrom(src interface{}) {
+
+ o := src.(*GetRootCACertificateResponse)
+ *m = *o
+ if o.Certificate != nil {
+ m.Certificate = make([]byte, len(o.Certificate))
+ copy(m.Certificate, o.Certificate)
+ }
+}
+
+func (m *GetUnlockKeyRequest) Copy() *GetUnlockKeyRequest {
+ if m == nil {
+ return nil
+ }
+ o := &GetUnlockKeyRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetUnlockKeyRequest) CopyFrom(src interface{}) {}
+func (m *GetUnlockKeyResponse) Copy() *GetUnlockKeyResponse {
+ if m == nil {
+ return nil
+ }
+ o := &GetUnlockKeyResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetUnlockKeyResponse) CopyFrom(src interface{}) {
+
+ o := src.(*GetUnlockKeyResponse)
+ *m = *o
+ if o.UnlockKey != nil {
+ m.UnlockKey = make([]byte, len(o.UnlockKey))
+ copy(m.UnlockKey, o.UnlockKey)
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Version, &o.Version)
+}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for CA service
+
+type CAClient interface {
+ GetRootCACertificate(ctx context.Context, in *GetRootCACertificateRequest, opts ...grpc.CallOption) (*GetRootCACertificateResponse, error)
+ // GetUnlockKey returns the current unlock key for the cluster for the role of the client
+ // asking.
+ GetUnlockKey(ctx context.Context, in *GetUnlockKeyRequest, opts ...grpc.CallOption) (*GetUnlockKeyResponse, error)
+}
+
+type cAClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewCAClient(cc *grpc.ClientConn) CAClient {
+ return &cAClient{cc}
+}
+
+func (c *cAClient) GetRootCACertificate(ctx context.Context, in *GetRootCACertificateRequest, opts ...grpc.CallOption) (*GetRootCACertificateResponse, error) {
+ out := new(GetRootCACertificateResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.CA/GetRootCACertificate", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *cAClient) GetUnlockKey(ctx context.Context, in *GetUnlockKeyRequest, opts ...grpc.CallOption) (*GetUnlockKeyResponse, error) {
+ out := new(GetUnlockKeyResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.CA/GetUnlockKey", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for CA service
+
+type CAServer interface {
+ GetRootCACertificate(context.Context, *GetRootCACertificateRequest) (*GetRootCACertificateResponse, error)
+ // GetUnlockKey returns the current unlock key for the cluster for the role of the client
+ // asking.
+ GetUnlockKey(context.Context, *GetUnlockKeyRequest) (*GetUnlockKeyResponse, error)
+}
+
+func RegisterCAServer(s *grpc.Server, srv CAServer) {
+ s.RegisterService(&_CA_serviceDesc, srv)
+}
+
+func _CA_GetRootCACertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetRootCACertificateRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(CAServer).GetRootCACertificate(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.CA/GetRootCACertificate",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(CAServer).GetRootCACertificate(ctx, req.(*GetRootCACertificateRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _CA_GetUnlockKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetUnlockKeyRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(CAServer).GetUnlockKey(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.CA/GetUnlockKey",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(CAServer).GetUnlockKey(ctx, req.(*GetUnlockKeyRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _CA_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.CA",
+ HandlerType: (*CAServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "GetRootCACertificate",
+ Handler: _CA_GetRootCACertificate_Handler,
+ },
+ {
+ MethodName: "GetUnlockKey",
+ Handler: _CA_GetUnlockKey_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "ca.proto",
+}
+
+// Client API for NodeCA service
+
+type NodeCAClient interface {
+ IssueNodeCertificate(ctx context.Context, in *IssueNodeCertificateRequest, opts ...grpc.CallOption) (*IssueNodeCertificateResponse, error)
+ NodeCertificateStatus(ctx context.Context, in *NodeCertificateStatusRequest, opts ...grpc.CallOption) (*NodeCertificateStatusResponse, error)
+}
+
+type nodeCAClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewNodeCAClient(cc *grpc.ClientConn) NodeCAClient {
+ return &nodeCAClient{cc}
+}
+
+func (c *nodeCAClient) IssueNodeCertificate(ctx context.Context, in *IssueNodeCertificateRequest, opts ...grpc.CallOption) (*IssueNodeCertificateResponse, error) {
+ out := new(IssueNodeCertificateResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.NodeCA/IssueNodeCertificate", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *nodeCAClient) NodeCertificateStatus(ctx context.Context, in *NodeCertificateStatusRequest, opts ...grpc.CallOption) (*NodeCertificateStatusResponse, error) {
+ out := new(NodeCertificateStatusResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.NodeCA/NodeCertificateStatus", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for NodeCA service
+
+type NodeCAServer interface {
+ IssueNodeCertificate(context.Context, *IssueNodeCertificateRequest) (*IssueNodeCertificateResponse, error)
+ NodeCertificateStatus(context.Context, *NodeCertificateStatusRequest) (*NodeCertificateStatusResponse, error)
+}
+
+func RegisterNodeCAServer(s *grpc.Server, srv NodeCAServer) {
+ s.RegisterService(&_NodeCA_serviceDesc, srv)
+}
+
+func _NodeCA_IssueNodeCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(IssueNodeCertificateRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(NodeCAServer).IssueNodeCertificate(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.NodeCA/IssueNodeCertificate",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(NodeCAServer).IssueNodeCertificate(ctx, req.(*IssueNodeCertificateRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _NodeCA_NodeCertificateStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(NodeCertificateStatusRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(NodeCAServer).NodeCertificateStatus(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.NodeCA/NodeCertificateStatus",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(NodeCAServer).NodeCertificateStatus(ctx, req.(*NodeCertificateStatusRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _NodeCA_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.NodeCA",
+ HandlerType: (*NodeCAServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "IssueNodeCertificate",
+ Handler: _NodeCA_IssueNodeCertificate_Handler,
+ },
+ {
+ MethodName: "NodeCertificateStatus",
+ Handler: _NodeCA_NodeCertificateStatus_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "ca.proto",
+}
+
+func (m *NodeCertificateStatusRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NodeCertificateStatusRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.NodeID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(len(m.NodeID)))
+ i += copy(dAtA[i:], m.NodeID)
+ }
+ return i, nil
+}
+
+func (m *NodeCertificateStatusResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NodeCertificateStatusResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Status != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(m.Status.Size()))
+ n1, err := m.Status.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ }
+ if m.Certificate != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(m.Certificate.Size()))
+ n2, err := m.Certificate.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ }
+ return i, nil
+}
+
+func (m *IssueNodeCertificateRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *IssueNodeCertificateRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Role != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(m.Role))
+ }
+ if len(m.CSR) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(len(m.CSR)))
+ i += copy(dAtA[i:], m.CSR)
+ }
+ if len(m.Token) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(len(m.Token)))
+ i += copy(dAtA[i:], m.Token)
+ }
+ if m.Availability != 0 {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(m.Availability))
+ }
+ return i, nil
+}
+
+func (m *IssueNodeCertificateResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *IssueNodeCertificateResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.NodeID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(len(m.NodeID)))
+ i += copy(dAtA[i:], m.NodeID)
+ }
+ if m.NodeMembership != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(m.NodeMembership))
+ }
+ return i, nil
+}
+
+func (m *GetRootCACertificateRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetRootCACertificateRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *GetRootCACertificateResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetRootCACertificateResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Certificate) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(len(m.Certificate)))
+ i += copy(dAtA[i:], m.Certificate)
+ }
+ return i, nil
+}
+
+func (m *GetUnlockKeyRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetUnlockKeyRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *GetUnlockKeyResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetUnlockKeyResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.UnlockKey) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(len(m.UnlockKey)))
+ i += copy(dAtA[i:], m.UnlockKey)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintCa(dAtA, i, uint64(m.Version.Size()))
+ n3, err := m.Version.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ return i, nil
+}
+
+func encodeFixed64Ca(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Ca(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintCa(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+type raftProxyCAServer struct {
+ local CAServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyCAServer(local CAServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) CAServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyCAServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyCAServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyCAServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+func (p *raftProxyCAServer) GetRootCACertificate(ctx context.Context, r *GetRootCACertificateRequest) (*GetRootCACertificateResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.GetRootCACertificate(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewCAClient(conn).GetRootCACertificate(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.GetRootCACertificate(ctx, r)
+ }
+ return nil, err
+ }
+ return NewCAClient(conn).GetRootCACertificate(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyCAServer) GetUnlockKey(ctx context.Context, r *GetUnlockKeyRequest) (*GetUnlockKeyResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.GetUnlockKey(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewCAClient(conn).GetUnlockKey(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.GetUnlockKey(ctx, r)
+ }
+ return nil, err
+ }
+ return NewCAClient(conn).GetUnlockKey(modCtx, r)
+ }
+ return resp, err
+}
+
+type raftProxyNodeCAServer struct {
+ local NodeCAServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyNodeCAServer(local NodeCAServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) NodeCAServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyNodeCAServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyNodeCAServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyNodeCAServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+func (p *raftProxyNodeCAServer) IssueNodeCertificate(ctx context.Context, r *IssueNodeCertificateRequest) (*IssueNodeCertificateResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.IssueNodeCertificate(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewNodeCAClient(conn).IssueNodeCertificate(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.IssueNodeCertificate(ctx, r)
+ }
+ return nil, err
+ }
+ return NewNodeCAClient(conn).IssueNodeCertificate(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyNodeCAServer) NodeCertificateStatus(ctx context.Context, r *NodeCertificateStatusRequest) (*NodeCertificateStatusResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.NodeCertificateStatus(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewNodeCAClient(conn).NodeCertificateStatus(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.NodeCertificateStatus(ctx, r)
+ }
+ return nil, err
+ }
+ return NewNodeCAClient(conn).NodeCertificateStatus(modCtx, r)
+ }
+ return resp, err
+}
+
+func (m *NodeCertificateStatusRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.NodeID)
+ if l > 0 {
+ n += 1 + l + sovCa(uint64(l))
+ }
+ return n
+}
+
+func (m *NodeCertificateStatusResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Status != nil {
+ l = m.Status.Size()
+ n += 1 + l + sovCa(uint64(l))
+ }
+ if m.Certificate != nil {
+ l = m.Certificate.Size()
+ n += 1 + l + sovCa(uint64(l))
+ }
+ return n
+}
+
+func (m *IssueNodeCertificateRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Role != 0 {
+ n += 1 + sovCa(uint64(m.Role))
+ }
+ l = len(m.CSR)
+ if l > 0 {
+ n += 1 + l + sovCa(uint64(l))
+ }
+ l = len(m.Token)
+ if l > 0 {
+ n += 1 + l + sovCa(uint64(l))
+ }
+ if m.Availability != 0 {
+ n += 1 + sovCa(uint64(m.Availability))
+ }
+ return n
+}
+
+func (m *IssueNodeCertificateResponse) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.NodeID)
+ if l > 0 {
+ n += 1 + l + sovCa(uint64(l))
+ }
+ if m.NodeMembership != 0 {
+ n += 1 + sovCa(uint64(m.NodeMembership))
+ }
+ return n
+}
+
+func (m *GetRootCACertificateRequest) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *GetRootCACertificateResponse) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Certificate)
+ if l > 0 {
+ n += 1 + l + sovCa(uint64(l))
+ }
+ return n
+}
+
+func (m *GetUnlockKeyRequest) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *GetUnlockKeyResponse) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.UnlockKey)
+ if l > 0 {
+ n += 1 + l + sovCa(uint64(l))
+ }
+ l = m.Version.Size()
+ n += 1 + l + sovCa(uint64(l))
+ return n
+}
+
+func sovCa(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozCa(x uint64) (n int) {
+ return sovCa(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *NodeCertificateStatusRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NodeCertificateStatusRequest{`,
+ `NodeID:` + fmt.Sprintf("%v", this.NodeID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NodeCertificateStatusResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NodeCertificateStatusResponse{`,
+ `Status:` + strings.Replace(fmt.Sprintf("%v", this.Status), "IssuanceStatus", "IssuanceStatus", 1) + `,`,
+ `Certificate:` + strings.Replace(fmt.Sprintf("%v", this.Certificate), "Certificate", "Certificate", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *IssueNodeCertificateRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&IssueNodeCertificateRequest{`,
+ `Role:` + fmt.Sprintf("%v", this.Role) + `,`,
+ `CSR:` + fmt.Sprintf("%v", this.CSR) + `,`,
+ `Token:` + fmt.Sprintf("%v", this.Token) + `,`,
+ `Availability:` + fmt.Sprintf("%v", this.Availability) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *IssueNodeCertificateResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&IssueNodeCertificateResponse{`,
+ `NodeID:` + fmt.Sprintf("%v", this.NodeID) + `,`,
+ `NodeMembership:` + fmt.Sprintf("%v", this.NodeMembership) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetRootCACertificateRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetRootCACertificateRequest{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetRootCACertificateResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetRootCACertificateResponse{`,
+ `Certificate:` + fmt.Sprintf("%v", this.Certificate) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetUnlockKeyRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetUnlockKeyRequest{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetUnlockKeyResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetUnlockKeyResponse{`,
+ `UnlockKey:` + fmt.Sprintf("%v", this.UnlockKey) + `,`,
+ `Version:` + strings.Replace(strings.Replace(this.Version.String(), "Version", "Version", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringCa(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *NodeCertificateStatusRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NodeCertificateStatusRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NodeCertificateStatusRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthCa
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipCa(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthCa
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NodeCertificateStatusResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NodeCertificateStatusResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NodeCertificateStatusResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthCa
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Status == nil {
+ m.Status = &IssuanceStatus{}
+ }
+ if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Certificate", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthCa
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Certificate == nil {
+ m.Certificate = &Certificate{}
+ }
+ if err := m.Certificate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipCa(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthCa
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *IssueNodeCertificateRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: IssueNodeCertificateRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: IssueNodeCertificateRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Role", wireType)
+ }
+ m.Role = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Role |= (NodeRole(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CSR", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthCa
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CSR = append(m.CSR[:0], dAtA[iNdEx:postIndex]...)
+ if m.CSR == nil {
+ m.CSR = []byte{}
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Token", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthCa
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Token = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Availability", wireType)
+ }
+ m.Availability = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Availability |= (NodeSpec_Availability(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipCa(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthCa
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *IssueNodeCertificateResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: IssueNodeCertificateResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: IssueNodeCertificateResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthCa
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeMembership", wireType)
+ }
+ m.NodeMembership = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.NodeMembership |= (NodeSpec_Membership(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipCa(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthCa
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetRootCACertificateRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetRootCACertificateRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetRootCACertificateRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipCa(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthCa
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetRootCACertificateResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetRootCACertificateResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetRootCACertificateResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Certificate", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthCa
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Certificate = append(m.Certificate[:0], dAtA[iNdEx:postIndex]...)
+ if m.Certificate == nil {
+ m.Certificate = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipCa(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthCa
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetUnlockKeyRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetUnlockKeyRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetUnlockKeyRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipCa(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthCa
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetUnlockKeyResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetUnlockKeyResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetUnlockKeyResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field UnlockKey", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthCa
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.UnlockKey = append(m.UnlockKey[:0], dAtA[iNdEx:postIndex]...)
+ if m.UnlockKey == nil {
+ m.UnlockKey = []byte{}
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthCa
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Version.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipCa(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthCa
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipCa(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthCa
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowCa
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipCa(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthCa = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowCa = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("ca.proto", fileDescriptorCa) }
+
+var fileDescriptorCa = []byte{
+ // 610 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0xcd, 0x6e, 0xd3, 0x40,
+ 0x10, 0xee, 0xba, 0x25, 0x6d, 0x27, 0xa1, 0x45, 0xdb, 0x56, 0x32, 0x69, 0xea, 0x54, 0xe6, 0xd0,
+ 0x72, 0xc0, 0x6d, 0x03, 0x27, 0xb8, 0x90, 0x04, 0xa9, 0x8a, 0x50, 0x11, 0xda, 0x08, 0xae, 0x95,
+ 0xe3, 0x2c, 0xc1, 0x8a, 0xe3, 0x35, 0xde, 0x75, 0x20, 0x37, 0x24, 0x10, 0x6f, 0x80, 0xe0, 0xc4,
+ 0x23, 0xf0, 0x1c, 0x11, 0x27, 0x24, 0x2e, 0x9c, 0x22, 0xea, 0x07, 0xe0, 0x19, 0x90, 0xd7, 0x36,
+ 0xcd, 0x8f, 0x13, 0xca, 0xc9, 0xbb, 0xb3, 0xdf, 0xf7, 0xcd, 0xcc, 0xb7, 0xe3, 0x85, 0x35, 0xcb,
+ 0x34, 0x3c, 0x9f, 0x09, 0x86, 0x71, 0x9b, 0x59, 0x5d, 0xea, 0x1b, 0xfc, 0xb5, 0xe9, 0xf7, 0xba,
+ 0xb6, 0x30, 0xfa, 0x27, 0xc5, 0xbc, 0x18, 0x78, 0x94, 0xc7, 0x80, 0x62, 0x9e, 0x7b, 0xd4, 0x4a,
+ 0x37, 0xdb, 0x1d, 0xd6, 0x61, 0x72, 0x79, 0x14, 0xad, 0x92, 0xe8, 0x96, 0xe7, 0x04, 0x1d, 0xdb,
+ 0x3d, 0x8a, 0x3f, 0x71, 0x50, 0xaf, 0x43, 0xe9, 0x09, 0x6b, 0xd3, 0x3a, 0xf5, 0x85, 0xfd, 0xc2,
+ 0xb6, 0x4c, 0x41, 0x9b, 0xc2, 0x14, 0x01, 0x27, 0xf4, 0x55, 0x40, 0xb9, 0xc0, 0xb7, 0x60, 0xd5,
+ 0x65, 0x6d, 0x7a, 0x6e, 0xb7, 0x55, 0xb4, 0x8f, 0x0e, 0xd7, 0x6b, 0x10, 0x8e, 0xca, 0xb9, 0x88,
+ 0xd2, 0x78, 0x44, 0x72, 0xd1, 0x51, 0xa3, 0xad, 0x7f, 0x41, 0xb0, 0x37, 0x47, 0x85, 0x7b, 0xcc,
+ 0xe5, 0x14, 0xdf, 0x87, 0x1c, 0x97, 0x11, 0xa9, 0x92, 0xaf, 0xe8, 0xc6, 0x6c, 0x43, 0x46, 0x83,
+ 0xf3, 0xc0, 0x74, 0xad, 0x94, 0x9b, 0x30, 0x70, 0x15, 0xf2, 0xd6, 0xa5, 0xb0, 0xaa, 0x48, 0x81,
+ 0x72, 0x96, 0xc0, 0x58, 0x7e, 0x32, 0xce, 0xd1, 0x7f, 0x20, 0xd8, 0x8d, 0xd4, 0xe9, 0x54, 0x95,
+ 0x69, 0x97, 0xf7, 0x60, 0xc5, 0x67, 0x0e, 0x95, 0xc5, 0x6d, 0x54, 0x4a, 0x59, 0xda, 0x11, 0x93,
+ 0x30, 0x87, 0xd6, 0x14, 0x15, 0x11, 0x89, 0xc6, 0x37, 0x61, 0xd9, 0xe2, 0xbe, 0x2c, 0xa8, 0x50,
+ 0x5b, 0x0d, 0x47, 0xe5, 0xe5, 0x7a, 0x93, 0x90, 0x28, 0x86, 0xb7, 0xe1, 0x9a, 0x60, 0x5d, 0xea,
+ 0xaa, 0xcb, 0x91, 0x69, 0x24, 0xde, 0xe0, 0x33, 0x28, 0x98, 0x7d, 0xd3, 0x76, 0xcc, 0x96, 0xed,
+ 0xd8, 0x62, 0xa0, 0xae, 0xc8, 0x74, 0xb7, 0xe7, 0xa5, 0x6b, 0x7a, 0xd4, 0x32, 0xaa, 0x63, 0x04,
+ 0x32, 0x41, 0xd7, 0x3f, 0x22, 0x28, 0x65, 0x77, 0x95, 0xb8, 0x7e, 0x95, 0xcb, 0xc3, 0x4f, 0x61,
+ 0x53, 0x82, 0x7a, 0xb4, 0xd7, 0xa2, 0x3e, 0x7f, 0x69, 0x7b, 0xb2, 0xa3, 0x8d, 0xca, 0xc1, 0xc2,
+ 0xba, 0xce, 0xfe, 0xc2, 0xc9, 0x46, 0xc4, 0xbf, 0xdc, 0xeb, 0x7b, 0xb0, 0x7b, 0x4a, 0x05, 0x61,
+ 0x4c, 0xd4, 0xab, 0xb3, 0x66, 0xeb, 0x0f, 0xa1, 0x94, 0x7d, 0x9c, 0x54, 0xbd, 0x3f, 0x79, 0xdf,
+ 0x51, 0xe5, 0x85, 0xc9, 0xeb, 0xdc, 0x81, 0xad, 0x53, 0x2a, 0x9e, 0xb9, 0x0e, 0xb3, 0xba, 0x8f,
+ 0xe9, 0x20, 0x15, 0xf6, 0x61, 0x7b, 0x32, 0x9c, 0x08, 0xee, 0x01, 0x04, 0x32, 0x78, 0xde, 0xa5,
+ 0x83, 0x44, 0x6f, 0x3d, 0x48, 0x61, 0xf8, 0x01, 0xac, 0xf6, 0xa9, 0xcf, 0x6d, 0xe6, 0x26, 0xb3,
+ 0xb5, 0x9b, 0xd5, 0xf8, 0xf3, 0x18, 0x52, 0x5b, 0x19, 0x8e, 0xca, 0x4b, 0x24, 0x65, 0x54, 0xde,
+ 0x2b, 0xa0, 0xd4, 0xab, 0xf8, 0x1d, 0x92, 0xb9, 0x67, 0x9a, 0xc2, 0x47, 0x59, 0x5a, 0x0b, 0xdc,
+ 0x29, 0x1e, 0x5f, 0x9d, 0x10, 0xb7, 0xa7, 0xaf, 0x7d, 0xfb, 0xfa, 0xfb, 0xb3, 0xa2, 0xdc, 0x40,
+ 0xf8, 0x0d, 0x14, 0xc6, 0x0d, 0xc0, 0x07, 0x73, 0xb4, 0xa6, 0x9d, 0x2b, 0x1e, 0xfe, 0x1b, 0x98,
+ 0x24, 0xdb, 0x91, 0xc9, 0x36, 0xe1, 0xba, 0x44, 0xde, 0xe9, 0x99, 0xae, 0xd9, 0xa1, 0x7e, 0xe5,
+ 0x93, 0x02, 0x72, 0xae, 0x12, 0x2b, 0xb2, 0xa6, 0x32, 0xdb, 0x8a, 0x05, 0x7f, 0x65, 0xb6, 0x15,
+ 0x8b, 0x06, 0x7e, 0xcc, 0x8a, 0x0f, 0x08, 0x76, 0x32, 0x9f, 0x24, 0x7c, 0x3c, 0x6f, 0xac, 0xe7,
+ 0xbd, 0x81, 0xc5, 0x93, 0xff, 0x60, 0x4c, 0x17, 0x52, 0x53, 0x87, 0x17, 0xda, 0xd2, 0xcf, 0x0b,
+ 0x6d, 0xe9, 0x6d, 0xa8, 0xa1, 0x61, 0xa8, 0xa1, 0xef, 0xa1, 0x86, 0x7e, 0x85, 0x1a, 0x6a, 0xe5,
+ 0xe4, 0x0b, 0x7c, 0xf7, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x69, 0xad, 0xed, 0x8f, 0xe6, 0x05,
+ 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/ca.proto b/vendor/github.com/docker/swarmkit/api/ca.proto
new file mode 100644
index 0000000..84ec7d3
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/ca.proto
@@ -0,0 +1,72 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "types.proto";
+import "specs.proto";
+import "gogoproto/gogo.proto";
+import "plugin/plugin.proto";
+
+// CA defines the RPC methods for requesting certificates from a CA.
+
+service CA {
+ rpc GetRootCACertificate(GetRootCACertificateRequest) returns (GetRootCACertificateResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { insecure: true };
+ };
+ // GetUnlockKey returns the current unlock key for the cluster for the role of the client
+ // asking.
+ rpc GetUnlockKey(GetUnlockKeyRequest) returns (GetUnlockKeyResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: ["swarm-manager"] };
+ };
+}
+
+service NodeCA {
+ rpc IssueNodeCertificate(IssueNodeCertificateRequest) returns (IssueNodeCertificateResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { insecure: true };
+ };
+ rpc NodeCertificateStatus(NodeCertificateStatusRequest) returns (NodeCertificateStatusResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { insecure: true };
+ };
+}
+
+message NodeCertificateStatusRequest {
+ string node_id = 1;
+}
+
+message NodeCertificateStatusResponse {
+ IssuanceStatus status = 1;
+ Certificate certificate = 2;
+}
+
+message IssueNodeCertificateRequest {
+ // DEPRECATED: Role is now selected based on which secret is matched.
+ NodeRole role = 1 [deprecated=true];
+
+ // CSR is the certificate signing request.
+ bytes csr = 2 [(gogoproto.customname) = "CSR"];
+
+ // Token represents a user-provided string that is necessary for new
+ // nodes to join the cluster
+ string token = 3;
+
+ // Availability allows a user to control the current scheduling status of a node
+ NodeSpec.Availability availability = 4;
+}
+
+message IssueNodeCertificateResponse {
+ string node_id = 1;
+ NodeSpec.Membership node_membership = 2;
+}
+
+message GetRootCACertificateRequest {}
+
+message GetRootCACertificateResponse {
+ bytes certificate = 1;
+}
+
+message GetUnlockKeyRequest {}
+
+message GetUnlockKeyResponse {
+ bytes unlock_key = 1;
+ Version version = 2 [(gogoproto.nullable) = false];
+}
diff --git a/vendor/github.com/docker/swarmkit/api/control.pb.go b/vendor/github.com/docker/swarmkit/api/control.pb.go
new file mode 100644
index 0000000..096228e
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/control.pb.go
@@ -0,0 +1,16092 @@
+// Code generated by protoc-gen-gogo.
+// source: control.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+import _ "github.com/docker/swarmkit/protobuf/plugin"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+import raftselector "github.com/docker/swarmkit/manager/raftselector"
+import codes "google.golang.org/grpc/codes"
+import metadata "google.golang.org/grpc/metadata"
+import transport "google.golang.org/grpc/transport"
+import rafttime "time"
+
+import strings "strings"
+import reflect "reflect"
+import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+type UpdateServiceRequest_Rollback int32
+
+const (
+ // This is not a rollback. The spec field of the request will
+ // be honored.
+ UpdateServiceRequest_NONE UpdateServiceRequest_Rollback = 0
+ // Roll back the service - get spec from the service's
+ // previous_spec.
+ UpdateServiceRequest_PREVIOUS UpdateServiceRequest_Rollback = 1
+)
+
+var UpdateServiceRequest_Rollback_name = map[int32]string{
+ 0: "NONE",
+ 1: "PREVIOUS",
+}
+var UpdateServiceRequest_Rollback_value = map[string]int32{
+ "NONE": 0,
+ "PREVIOUS": 1,
+}
+
+func (x UpdateServiceRequest_Rollback) String() string {
+ return proto.EnumName(UpdateServiceRequest_Rollback_name, int32(x))
+}
+func (UpdateServiceRequest_Rollback) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorControl, []int{18, 0}
+}
+
+type GetNodeRequest struct {
+ NodeID string `protobuf:"bytes,1,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"`
+}
+
+func (m *GetNodeRequest) Reset() { *m = GetNodeRequest{} }
+func (*GetNodeRequest) ProtoMessage() {}
+func (*GetNodeRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{0} }
+
+type GetNodeResponse struct {
+ Node *Node `protobuf:"bytes,1,opt,name=node" json:"node,omitempty"`
+}
+
+func (m *GetNodeResponse) Reset() { *m = GetNodeResponse{} }
+func (*GetNodeResponse) ProtoMessage() {}
+func (*GetNodeResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{1} }
+
+type ListNodesRequest struct {
+ Filters *ListNodesRequest_Filters `protobuf:"bytes,1,opt,name=filters" json:"filters,omitempty"`
+}
+
+func (m *ListNodesRequest) Reset() { *m = ListNodesRequest{} }
+func (*ListNodesRequest) ProtoMessage() {}
+func (*ListNodesRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{2} }
+
+type ListNodesRequest_Filters struct {
+ Names []string `protobuf:"bytes,1,rep,name=names" json:"names,omitempty"`
+ IDPrefixes []string `protobuf:"bytes,2,rep,name=id_prefixes,json=idPrefixes" json:"id_prefixes,omitempty"`
+ Labels map[string]string `protobuf:"bytes,3,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ Memberships []NodeSpec_Membership `protobuf:"varint,4,rep,name=memberships,enum=docker.swarmkit.v1.NodeSpec_Membership" json:"memberships,omitempty"`
+ Roles []NodeRole `protobuf:"varint,5,rep,name=roles,enum=docker.swarmkit.v1.NodeRole" json:"roles,omitempty"`
+ // NamePrefixes matches all objects with the given prefixes
+ NamePrefixes []string `protobuf:"bytes,6,rep,name=name_prefixes,json=namePrefixes" json:"name_prefixes,omitempty"`
+}
+
+func (m *ListNodesRequest_Filters) Reset() { *m = ListNodesRequest_Filters{} }
+func (*ListNodesRequest_Filters) ProtoMessage() {}
+func (*ListNodesRequest_Filters) Descriptor() ([]byte, []int) {
+ return fileDescriptorControl, []int{2, 0}
+}
+
+type ListNodesResponse struct {
+ Nodes []*Node `protobuf:"bytes,1,rep,name=nodes" json:"nodes,omitempty"`
+}
+
+func (m *ListNodesResponse) Reset() { *m = ListNodesResponse{} }
+func (*ListNodesResponse) ProtoMessage() {}
+func (*ListNodesResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{3} }
+
+// UpdateNodeRequest requests an update to the specified node. This may be used
+// to request a new availability for a node, such as PAUSE. Invalid updates
+// will be denied and cause an error.
+type UpdateNodeRequest struct {
+ NodeID string `protobuf:"bytes,1,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"`
+ NodeVersion *Version `protobuf:"bytes,2,opt,name=node_version,json=nodeVersion" json:"node_version,omitempty"`
+ Spec *NodeSpec `protobuf:"bytes,3,opt,name=spec" json:"spec,omitempty"`
+}
+
+func (m *UpdateNodeRequest) Reset() { *m = UpdateNodeRequest{} }
+func (*UpdateNodeRequest) ProtoMessage() {}
+func (*UpdateNodeRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{4} }
+
+type UpdateNodeResponse struct {
+ Node *Node `protobuf:"bytes,1,opt,name=node" json:"node,omitempty"`
+}
+
+func (m *UpdateNodeResponse) Reset() { *m = UpdateNodeResponse{} }
+func (*UpdateNodeResponse) ProtoMessage() {}
+func (*UpdateNodeResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{5} }
+
+// RemoveNodeRequest requests to delete the specified node from store.
+type RemoveNodeRequest struct {
+ NodeID string `protobuf:"bytes,1,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"`
+ Force bool `protobuf:"varint,2,opt,name=force,proto3" json:"force,omitempty"`
+}
+
+func (m *RemoveNodeRequest) Reset() { *m = RemoveNodeRequest{} }
+func (*RemoveNodeRequest) ProtoMessage() {}
+func (*RemoveNodeRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{6} }
+
+type RemoveNodeResponse struct {
+}
+
+func (m *RemoveNodeResponse) Reset() { *m = RemoveNodeResponse{} }
+func (*RemoveNodeResponse) ProtoMessage() {}
+func (*RemoveNodeResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{7} }
+
+type GetTaskRequest struct {
+ TaskID string `protobuf:"bytes,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
+}
+
+func (m *GetTaskRequest) Reset() { *m = GetTaskRequest{} }
+func (*GetTaskRequest) ProtoMessage() {}
+func (*GetTaskRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{8} }
+
+type GetTaskResponse struct {
+ Task *Task `protobuf:"bytes,1,opt,name=task" json:"task,omitempty"`
+}
+
+func (m *GetTaskResponse) Reset() { *m = GetTaskResponse{} }
+func (*GetTaskResponse) ProtoMessage() {}
+func (*GetTaskResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{9} }
+
+type RemoveTaskRequest struct {
+ TaskID string `protobuf:"bytes,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
+}
+
+func (m *RemoveTaskRequest) Reset() { *m = RemoveTaskRequest{} }
+func (*RemoveTaskRequest) ProtoMessage() {}
+func (*RemoveTaskRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{10} }
+
+type RemoveTaskResponse struct {
+}
+
+func (m *RemoveTaskResponse) Reset() { *m = RemoveTaskResponse{} }
+func (*RemoveTaskResponse) ProtoMessage() {}
+func (*RemoveTaskResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{11} }
+
+type ListTasksRequest struct {
+ Filters *ListTasksRequest_Filters `protobuf:"bytes,1,opt,name=filters" json:"filters,omitempty"`
+}
+
+func (m *ListTasksRequest) Reset() { *m = ListTasksRequest{} }
+func (*ListTasksRequest) ProtoMessage() {}
+func (*ListTasksRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{12} }
+
+type ListTasksRequest_Filters struct {
+ Names []string `protobuf:"bytes,1,rep,name=names" json:"names,omitempty"`
+ IDPrefixes []string `protobuf:"bytes,2,rep,name=id_prefixes,json=idPrefixes" json:"id_prefixes,omitempty"`
+ Labels map[string]string `protobuf:"bytes,3,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ ServiceIDs []string `protobuf:"bytes,4,rep,name=service_ids,json=serviceIds" json:"service_ids,omitempty"`
+ NodeIDs []string `protobuf:"bytes,5,rep,name=node_ids,json=nodeIds" json:"node_ids,omitempty"`
+ DesiredStates []TaskState `protobuf:"varint,6,rep,name=desired_states,json=desiredStates,enum=docker.swarmkit.v1.TaskState" json:"desired_states,omitempty"`
+ // NamePrefixes matches all objects with the given prefixes
+ NamePrefixes []string `protobuf:"bytes,7,rep,name=name_prefixes,json=namePrefixes" json:"name_prefixes,omitempty"`
+ Runtimes []string `protobuf:"bytes,9,rep,name=runtimes" json:"runtimes,omitempty"`
+ // UpToDate matches tasks that are consistent with the current
+ // service definition.
+ // Note: this is intended for internal status reporting rather
+ // than being exposed to users. It may be removed in the future.
+ UpToDate bool `protobuf:"varint,8,opt,name=up_to_date,json=upToDate,proto3" json:"up_to_date,omitempty"`
+}
+
+func (m *ListTasksRequest_Filters) Reset() { *m = ListTasksRequest_Filters{} }
+func (*ListTasksRequest_Filters) ProtoMessage() {}
+func (*ListTasksRequest_Filters) Descriptor() ([]byte, []int) {
+ return fileDescriptorControl, []int{12, 0}
+}
+
+type ListTasksResponse struct {
+ Tasks []*Task `protobuf:"bytes,1,rep,name=tasks" json:"tasks,omitempty"`
+}
+
+func (m *ListTasksResponse) Reset() { *m = ListTasksResponse{} }
+func (*ListTasksResponse) ProtoMessage() {}
+func (*ListTasksResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{13} }
+
+type CreateServiceRequest struct {
+ Spec *ServiceSpec `protobuf:"bytes,1,opt,name=spec" json:"spec,omitempty"`
+}
+
+func (m *CreateServiceRequest) Reset() { *m = CreateServiceRequest{} }
+func (*CreateServiceRequest) ProtoMessage() {}
+func (*CreateServiceRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{14} }
+
+type CreateServiceResponse struct {
+ Service *Service `protobuf:"bytes,1,opt,name=service" json:"service,omitempty"`
+}
+
+func (m *CreateServiceResponse) Reset() { *m = CreateServiceResponse{} }
+func (*CreateServiceResponse) ProtoMessage() {}
+func (*CreateServiceResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{15} }
+
+type GetServiceRequest struct {
+ ServiceID string `protobuf:"bytes,1,opt,name=service_id,json=serviceId,proto3" json:"service_id,omitempty"`
+ InsertDefaults bool `protobuf:"varint,2,opt,name=insert_defaults,json=insertDefaults,proto3" json:"insert_defaults,omitempty"`
+}
+
+func (m *GetServiceRequest) Reset() { *m = GetServiceRequest{} }
+func (*GetServiceRequest) ProtoMessage() {}
+func (*GetServiceRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{16} }
+
+type GetServiceResponse struct {
+ Service *Service `protobuf:"bytes,1,opt,name=service" json:"service,omitempty"`
+}
+
+func (m *GetServiceResponse) Reset() { *m = GetServiceResponse{} }
+func (*GetServiceResponse) ProtoMessage() {}
+func (*GetServiceResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{17} }
+
+type UpdateServiceRequest struct {
+ ServiceID string `protobuf:"bytes,1,opt,name=service_id,json=serviceId,proto3" json:"service_id,omitempty"`
+ ServiceVersion *Version `protobuf:"bytes,2,opt,name=service_version,json=serviceVersion" json:"service_version,omitempty"`
+ Spec *ServiceSpec `protobuf:"bytes,3,opt,name=spec" json:"spec,omitempty"`
+ // Rollback may be set to PREVIOUS to request a rollback (the service's
+ // spec will be set to the value of its previous_spec field). In this
+ // case, the spec field of this request is ignored.
+ Rollback UpdateServiceRequest_Rollback `protobuf:"varint,4,opt,name=rollback,proto3,enum=docker.swarmkit.v1.UpdateServiceRequest_Rollback" json:"rollback,omitempty"`
+}
+
+func (m *UpdateServiceRequest) Reset() { *m = UpdateServiceRequest{} }
+func (*UpdateServiceRequest) ProtoMessage() {}
+func (*UpdateServiceRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{18} }
+
+type UpdateServiceResponse struct {
+ Service *Service `protobuf:"bytes,1,opt,name=service" json:"service,omitempty"`
+}
+
+func (m *UpdateServiceResponse) Reset() { *m = UpdateServiceResponse{} }
+func (*UpdateServiceResponse) ProtoMessage() {}
+func (*UpdateServiceResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{19} }
+
+type RemoveServiceRequest struct {
+ ServiceID string `protobuf:"bytes,1,opt,name=service_id,json=serviceId,proto3" json:"service_id,omitempty"`
+}
+
+func (m *RemoveServiceRequest) Reset() { *m = RemoveServiceRequest{} }
+func (*RemoveServiceRequest) ProtoMessage() {}
+func (*RemoveServiceRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{20} }
+
+type RemoveServiceResponse struct {
+}
+
+func (m *RemoveServiceResponse) Reset() { *m = RemoveServiceResponse{} }
+func (*RemoveServiceResponse) ProtoMessage() {}
+func (*RemoveServiceResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{21} }
+
+type ListServicesRequest struct {
+ Filters *ListServicesRequest_Filters `protobuf:"bytes,1,opt,name=filters" json:"filters,omitempty"`
+}
+
+func (m *ListServicesRequest) Reset() { *m = ListServicesRequest{} }
+func (*ListServicesRequest) ProtoMessage() {}
+func (*ListServicesRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{22} }
+
+type ListServicesRequest_Filters struct {
+ Names []string `protobuf:"bytes,1,rep,name=names" json:"names,omitempty"`
+ IDPrefixes []string `protobuf:"bytes,2,rep,name=id_prefixes,json=idPrefixes" json:"id_prefixes,omitempty"`
+ Labels map[string]string `protobuf:"bytes,3,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ // NamePrefixes matches all objects with the given prefixes
+ NamePrefixes []string `protobuf:"bytes,4,rep,name=name_prefixes,json=namePrefixes" json:"name_prefixes,omitempty"`
+ Runtimes []string `protobuf:"bytes,5,rep,name=runtimes" json:"runtimes,omitempty"`
+}
+
+func (m *ListServicesRequest_Filters) Reset() { *m = ListServicesRequest_Filters{} }
+func (*ListServicesRequest_Filters) ProtoMessage() {}
+func (*ListServicesRequest_Filters) Descriptor() ([]byte, []int) {
+ return fileDescriptorControl, []int{22, 0}
+}
+
+type ListServicesResponse struct {
+ Services []*Service `protobuf:"bytes,1,rep,name=services" json:"services,omitempty"`
+}
+
+func (m *ListServicesResponse) Reset() { *m = ListServicesResponse{} }
+func (*ListServicesResponse) ProtoMessage() {}
+func (*ListServicesResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{23} }
+
+type CreateNetworkRequest struct {
+ Spec *NetworkSpec `protobuf:"bytes,1,opt,name=spec" json:"spec,omitempty"`
+}
+
+func (m *CreateNetworkRequest) Reset() { *m = CreateNetworkRequest{} }
+func (*CreateNetworkRequest) ProtoMessage() {}
+func (*CreateNetworkRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{24} }
+
+type CreateNetworkResponse struct {
+ Network *Network `protobuf:"bytes,1,opt,name=network" json:"network,omitempty"`
+}
+
+func (m *CreateNetworkResponse) Reset() { *m = CreateNetworkResponse{} }
+func (*CreateNetworkResponse) ProtoMessage() {}
+func (*CreateNetworkResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{25} }
+
+type GetNetworkRequest struct {
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ NetworkID string `protobuf:"bytes,2,opt,name=network_id,json=networkId,proto3" json:"network_id,omitempty"`
+}
+
+func (m *GetNetworkRequest) Reset() { *m = GetNetworkRequest{} }
+func (*GetNetworkRequest) ProtoMessage() {}
+func (*GetNetworkRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{26} }
+
+type GetNetworkResponse struct {
+ Network *Network `protobuf:"bytes,1,opt,name=network" json:"network,omitempty"`
+}
+
+func (m *GetNetworkResponse) Reset() { *m = GetNetworkResponse{} }
+func (*GetNetworkResponse) ProtoMessage() {}
+func (*GetNetworkResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{27} }
+
+type RemoveNetworkRequest struct {
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ NetworkID string `protobuf:"bytes,2,opt,name=network_id,json=networkId,proto3" json:"network_id,omitempty"`
+}
+
+func (m *RemoveNetworkRequest) Reset() { *m = RemoveNetworkRequest{} }
+func (*RemoveNetworkRequest) ProtoMessage() {}
+func (*RemoveNetworkRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{28} }
+
+type RemoveNetworkResponse struct {
+}
+
+func (m *RemoveNetworkResponse) Reset() { *m = RemoveNetworkResponse{} }
+func (*RemoveNetworkResponse) ProtoMessage() {}
+func (*RemoveNetworkResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{29} }
+
+type ListNetworksRequest struct {
+ Filters *ListNetworksRequest_Filters `protobuf:"bytes,1,opt,name=filters" json:"filters,omitempty"`
+}
+
+func (m *ListNetworksRequest) Reset() { *m = ListNetworksRequest{} }
+func (*ListNetworksRequest) ProtoMessage() {}
+func (*ListNetworksRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{30} }
+
+type ListNetworksRequest_Filters struct {
+ Names []string `protobuf:"bytes,1,rep,name=names" json:"names,omitempty"`
+ IDPrefixes []string `protobuf:"bytes,2,rep,name=id_prefixes,json=idPrefixes" json:"id_prefixes,omitempty"`
+ Labels map[string]string `protobuf:"bytes,3,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ // NamePrefixes matches all objects with the given prefixes
+ NamePrefixes []string `protobuf:"bytes,4,rep,name=name_prefixes,json=namePrefixes" json:"name_prefixes,omitempty"`
+}
+
+func (m *ListNetworksRequest_Filters) Reset() { *m = ListNetworksRequest_Filters{} }
+func (*ListNetworksRequest_Filters) ProtoMessage() {}
+func (*ListNetworksRequest_Filters) Descriptor() ([]byte, []int) {
+ return fileDescriptorControl, []int{30, 0}
+}
+
+type ListNetworksResponse struct {
+ Networks []*Network `protobuf:"bytes,1,rep,name=networks" json:"networks,omitempty"`
+}
+
+func (m *ListNetworksResponse) Reset() { *m = ListNetworksResponse{} }
+func (*ListNetworksResponse) ProtoMessage() {}
+func (*ListNetworksResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{31} }
+
+type GetClusterRequest struct {
+ ClusterID string `protobuf:"bytes,1,opt,name=cluster_id,json=clusterId,proto3" json:"cluster_id,omitempty"`
+}
+
+func (m *GetClusterRequest) Reset() { *m = GetClusterRequest{} }
+func (*GetClusterRequest) ProtoMessage() {}
+func (*GetClusterRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{32} }
+
+type GetClusterResponse struct {
+ Cluster *Cluster `protobuf:"bytes,1,opt,name=cluster" json:"cluster,omitempty"`
+}
+
+func (m *GetClusterResponse) Reset() { *m = GetClusterResponse{} }
+func (*GetClusterResponse) ProtoMessage() {}
+func (*GetClusterResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{33} }
+
+type ListClustersRequest struct {
+ Filters *ListClustersRequest_Filters `protobuf:"bytes,1,opt,name=filters" json:"filters,omitempty"`
+}
+
+func (m *ListClustersRequest) Reset() { *m = ListClustersRequest{} }
+func (*ListClustersRequest) ProtoMessage() {}
+func (*ListClustersRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{34} }
+
+type ListClustersRequest_Filters struct {
+ Names []string `protobuf:"bytes,1,rep,name=names" json:"names,omitempty"`
+ IDPrefixes []string `protobuf:"bytes,2,rep,name=id_prefixes,json=idPrefixes" json:"id_prefixes,omitempty"`
+ Labels map[string]string `protobuf:"bytes,3,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ // NamePrefixes matches all objects with the given prefixes
+ NamePrefixes []string `protobuf:"bytes,4,rep,name=name_prefixes,json=namePrefixes" json:"name_prefixes,omitempty"`
+}
+
+func (m *ListClustersRequest_Filters) Reset() { *m = ListClustersRequest_Filters{} }
+func (*ListClustersRequest_Filters) ProtoMessage() {}
+func (*ListClustersRequest_Filters) Descriptor() ([]byte, []int) {
+ return fileDescriptorControl, []int{34, 0}
+}
+
+type ListClustersResponse struct {
+ Clusters []*Cluster `protobuf:"bytes,1,rep,name=clusters" json:"clusters,omitempty"`
+}
+
+func (m *ListClustersResponse) Reset() { *m = ListClustersResponse{} }
+func (*ListClustersResponse) ProtoMessage() {}
+func (*ListClustersResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{35} }
+
+// KeyRotation tells UpdateCluster what items to rotate
+type KeyRotation struct {
+ // WorkerJoinToken tells UpdateCluster to rotate the worker secret token.
+ WorkerJoinToken bool `protobuf:"varint,1,opt,name=worker_join_token,json=workerJoinToken,proto3" json:"worker_join_token,omitempty"`
+ // ManagerJoinToken tells UpdateCluster to rotate the manager secret token.
+ ManagerJoinToken bool `protobuf:"varint,2,opt,name=manager_join_token,json=managerJoinToken,proto3" json:"manager_join_token,omitempty"`
+ // ManagerUnlockKey tells UpdateCluster to rotate the manager unlock key
+ ManagerUnlockKey bool `protobuf:"varint,3,opt,name=manager_unlock_key,json=managerUnlockKey,proto3" json:"manager_unlock_key,omitempty"`
+}
+
+func (m *KeyRotation) Reset() { *m = KeyRotation{} }
+func (*KeyRotation) ProtoMessage() {}
+func (*KeyRotation) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{36} }
+
+type UpdateClusterRequest struct {
+ // ClusterID is the cluster ID to update.
+ ClusterID string `protobuf:"bytes,1,opt,name=cluster_id,json=clusterId,proto3" json:"cluster_id,omitempty"`
+ // ClusterVersion is the version of the cluster being updated.
+ ClusterVersion *Version `protobuf:"bytes,2,opt,name=cluster_version,json=clusterVersion" json:"cluster_version,omitempty"`
+ // Spec is the new spec to apply to the cluster.
+ Spec *ClusterSpec `protobuf:"bytes,3,opt,name=spec" json:"spec,omitempty"`
+ // Rotation contains flags for join token and unlock key rotation
+ Rotation KeyRotation `protobuf:"bytes,4,opt,name=rotation" json:"rotation"`
+}
+
+func (m *UpdateClusterRequest) Reset() { *m = UpdateClusterRequest{} }
+func (*UpdateClusterRequest) ProtoMessage() {}
+func (*UpdateClusterRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{37} }
+
+type UpdateClusterResponse struct {
+ Cluster *Cluster `protobuf:"bytes,1,opt,name=cluster" json:"cluster,omitempty"`
+}
+
+func (m *UpdateClusterResponse) Reset() { *m = UpdateClusterResponse{} }
+func (*UpdateClusterResponse) ProtoMessage() {}
+func (*UpdateClusterResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{38} }
+
+// GetSecretRequest is the request to get a `Secret` object given a secret id.
+type GetSecretRequest struct {
+ SecretID string `protobuf:"bytes,1,opt,name=secret_id,json=secretId,proto3" json:"secret_id,omitempty"`
+}
+
+func (m *GetSecretRequest) Reset() { *m = GetSecretRequest{} }
+func (*GetSecretRequest) ProtoMessage() {}
+func (*GetSecretRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{39} }
+
+// GetSecretResponse contains the Secret corresponding to the id in
+// `GetSecretRequest`, but the `Secret.Spec.Data` field in each `Secret`
+// object should be nil instead of actually containing the secret bytes.
+type GetSecretResponse struct {
+ Secret *Secret `protobuf:"bytes,1,opt,name=secret" json:"secret,omitempty"`
+}
+
+func (m *GetSecretResponse) Reset() { *m = GetSecretResponse{} }
+func (*GetSecretResponse) ProtoMessage() {}
+func (*GetSecretResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{40} }
+
+type UpdateSecretRequest struct {
+ // SecretID is the secret ID to update.
+ SecretID string `protobuf:"bytes,1,opt,name=secret_id,json=secretId,proto3" json:"secret_id,omitempty"`
+ // SecretVersion is the version of the secret being updated.
+ SecretVersion *Version `protobuf:"bytes,2,opt,name=secret_version,json=secretVersion" json:"secret_version,omitempty"`
+ // Spec is the new spec to apply to the Secret
+ // Only some fields are allowed to be updated.
+ Spec *SecretSpec `protobuf:"bytes,3,opt,name=spec" json:"spec,omitempty"`
+}
+
+func (m *UpdateSecretRequest) Reset() { *m = UpdateSecretRequest{} }
+func (*UpdateSecretRequest) ProtoMessage() {}
+func (*UpdateSecretRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{41} }
+
+type UpdateSecretResponse struct {
+ Secret *Secret `protobuf:"bytes,1,opt,name=secret" json:"secret,omitempty"`
+}
+
+func (m *UpdateSecretResponse) Reset() { *m = UpdateSecretResponse{} }
+func (*UpdateSecretResponse) ProtoMessage() {}
+func (*UpdateSecretResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{42} }
+
+// ListSecretRequest is the request to list all non-internal secrets in the secret store,
+// or all secrets filtered by (name or name prefix or id prefix) and labels.
+type ListSecretsRequest struct {
+ Filters *ListSecretsRequest_Filters `protobuf:"bytes,1,opt,name=filters" json:"filters,omitempty"`
+}
+
+func (m *ListSecretsRequest) Reset() { *m = ListSecretsRequest{} }
+func (*ListSecretsRequest) ProtoMessage() {}
+func (*ListSecretsRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{43} }
+
+type ListSecretsRequest_Filters struct {
+ Names []string `protobuf:"bytes,1,rep,name=names" json:"names,omitempty"`
+ IDPrefixes []string `protobuf:"bytes,2,rep,name=id_prefixes,json=idPrefixes" json:"id_prefixes,omitempty"`
+ Labels map[string]string `protobuf:"bytes,3,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ NamePrefixes []string `protobuf:"bytes,4,rep,name=name_prefixes,json=namePrefixes" json:"name_prefixes,omitempty"`
+}
+
+func (m *ListSecretsRequest_Filters) Reset() { *m = ListSecretsRequest_Filters{} }
+func (*ListSecretsRequest_Filters) ProtoMessage() {}
+func (*ListSecretsRequest_Filters) Descriptor() ([]byte, []int) {
+ return fileDescriptorControl, []int{43, 0}
+}
+
+// ListSecretResponse contains a list of all the secrets that match the name or
+// name prefix filters provided in `ListSecretRequest`. The `Secret.Spec.Data`
+// field in each `Secret` object should be nil instead of actually containing
+// the secret bytes.
+type ListSecretsResponse struct {
+ Secrets []*Secret `protobuf:"bytes,1,rep,name=secrets" json:"secrets,omitempty"`
+}
+
+func (m *ListSecretsResponse) Reset() { *m = ListSecretsResponse{} }
+func (*ListSecretsResponse) ProtoMessage() {}
+func (*ListSecretsResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{44} }
+
+// CreateSecretRequest specifies a new secret (it will not update an existing
+// secret) to create.
+type CreateSecretRequest struct {
+ Spec *SecretSpec `protobuf:"bytes,1,opt,name=spec" json:"spec,omitempty"`
+}
+
+func (m *CreateSecretRequest) Reset() { *m = CreateSecretRequest{} }
+func (*CreateSecretRequest) ProtoMessage() {}
+func (*CreateSecretRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{45} }
+
+// CreateSecretResponse contains the newly created `Secret` corresponding to the
+// name in `CreateSecretRequest`. The `Secret.Spec.Data` field should be nil instead
+// of actually containing the secret bytes.
+type CreateSecretResponse struct {
+ Secret *Secret `protobuf:"bytes,1,opt,name=secret" json:"secret,omitempty"`
+}
+
+func (m *CreateSecretResponse) Reset() { *m = CreateSecretResponse{} }
+func (*CreateSecretResponse) ProtoMessage() {}
+func (*CreateSecretResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{46} }
+
+// RemoveSecretRequest contains the ID of the secret that should be removed. This
+// removes all versions of the secret.
+type RemoveSecretRequest struct {
+ SecretID string `protobuf:"bytes,1,opt,name=secret_id,json=secretId,proto3" json:"secret_id,omitempty"`
+}
+
+func (m *RemoveSecretRequest) Reset() { *m = RemoveSecretRequest{} }
+func (*RemoveSecretRequest) ProtoMessage() {}
+func (*RemoveSecretRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{47} }
+
+// RemoveSecretResponse is an empty object indicating the successful removal of
+// a secret.
+type RemoveSecretResponse struct {
+}
+
+func (m *RemoveSecretResponse) Reset() { *m = RemoveSecretResponse{} }
+func (*RemoveSecretResponse) ProtoMessage() {}
+func (*RemoveSecretResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{48} }
+
+// GetConfigRequest is the request to get a `Config` object given a config id.
+type GetConfigRequest struct {
+ ConfigID string `protobuf:"bytes,1,opt,name=config_id,json=configId,proto3" json:"config_id,omitempty"`
+}
+
+func (m *GetConfigRequest) Reset() { *m = GetConfigRequest{} }
+func (*GetConfigRequest) ProtoMessage() {}
+func (*GetConfigRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{49} }
+
+// GetConfigResponse contains the Config corresponding to the id in
+// `GetConfigRequest`.
+type GetConfigResponse struct {
+ Config *Config `protobuf:"bytes,1,opt,name=config" json:"config,omitempty"`
+}
+
+func (m *GetConfigResponse) Reset() { *m = GetConfigResponse{} }
+func (*GetConfigResponse) ProtoMessage() {}
+func (*GetConfigResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{50} }
+
+type UpdateConfigRequest struct {
+ // ConfigID is the config ID to update.
+ ConfigID string `protobuf:"bytes,1,opt,name=config_id,json=configId,proto3" json:"config_id,omitempty"`
+ // ConfigVersion is the version of the config being updated.
+ ConfigVersion *Version `protobuf:"bytes,2,opt,name=config_version,json=configVersion" json:"config_version,omitempty"`
+ // Spec is the new spec to apply to the Config
+ // Only some fields are allowed to be updated.
+ Spec *ConfigSpec `protobuf:"bytes,3,opt,name=spec" json:"spec,omitempty"`
+}
+
+func (m *UpdateConfigRequest) Reset() { *m = UpdateConfigRequest{} }
+func (*UpdateConfigRequest) ProtoMessage() {}
+func (*UpdateConfigRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{51} }
+
+type UpdateConfigResponse struct {
+ Config *Config `protobuf:"bytes,1,opt,name=config" json:"config,omitempty"`
+}
+
+func (m *UpdateConfigResponse) Reset() { *m = UpdateConfigResponse{} }
+func (*UpdateConfigResponse) ProtoMessage() {}
+func (*UpdateConfigResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{52} }
+
+// ListConfigRequest is the request to list all configs in the config store,
+// or all configs filtered by (name or name prefix or id prefix) and labels.
+type ListConfigsRequest struct {
+ Filters *ListConfigsRequest_Filters `protobuf:"bytes,1,opt,name=filters" json:"filters,omitempty"`
+}
+
+func (m *ListConfigsRequest) Reset() { *m = ListConfigsRequest{} }
+func (*ListConfigsRequest) ProtoMessage() {}
+func (*ListConfigsRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{53} }
+
+type ListConfigsRequest_Filters struct {
+ Names []string `protobuf:"bytes,1,rep,name=names" json:"names,omitempty"`
+ IDPrefixes []string `protobuf:"bytes,2,rep,name=id_prefixes,json=idPrefixes" json:"id_prefixes,omitempty"`
+ Labels map[string]string `protobuf:"bytes,3,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ NamePrefixes []string `protobuf:"bytes,4,rep,name=name_prefixes,json=namePrefixes" json:"name_prefixes,omitempty"`
+}
+
+func (m *ListConfigsRequest_Filters) Reset() { *m = ListConfigsRequest_Filters{} }
+func (*ListConfigsRequest_Filters) ProtoMessage() {}
+func (*ListConfigsRequest_Filters) Descriptor() ([]byte, []int) {
+ return fileDescriptorControl, []int{53, 0}
+}
+
+// ListConfigResponse contains a list of all the configs that match the name or
+// name prefix filters provided in `ListConfigRequest`.
+type ListConfigsResponse struct {
+ Configs []*Config `protobuf:"bytes,1,rep,name=configs" json:"configs,omitempty"`
+}
+
+func (m *ListConfigsResponse) Reset() { *m = ListConfigsResponse{} }
+func (*ListConfigsResponse) ProtoMessage() {}
+func (*ListConfigsResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{54} }
+
+// CreateConfigRequest specifies a new config (it will not update an existing
+// config) to create.
+type CreateConfigRequest struct {
+ Spec *ConfigSpec `protobuf:"bytes,1,opt,name=spec" json:"spec,omitempty"`
+}
+
+func (m *CreateConfigRequest) Reset() { *m = CreateConfigRequest{} }
+func (*CreateConfigRequest) ProtoMessage() {}
+func (*CreateConfigRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{55} }
+
+// CreateConfigResponse contains the newly created `Config` corresponding to the
+// name in `CreateConfigRequest`.
+type CreateConfigResponse struct {
+ Config *Config `protobuf:"bytes,1,opt,name=config" json:"config,omitempty"`
+}
+
+func (m *CreateConfigResponse) Reset() { *m = CreateConfigResponse{} }
+func (*CreateConfigResponse) ProtoMessage() {}
+func (*CreateConfigResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{56} }
+
+// RemoveConfigRequest contains the ID of the config that should be removed. This
+// removes all versions of the config.
+type RemoveConfigRequest struct {
+ ConfigID string `protobuf:"bytes,1,opt,name=config_id,json=configId,proto3" json:"config_id,omitempty"`
+}
+
+func (m *RemoveConfigRequest) Reset() { *m = RemoveConfigRequest{} }
+func (*RemoveConfigRequest) ProtoMessage() {}
+func (*RemoveConfigRequest) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{57} }
+
+// RemoveConfigResponse is an empty object indicating the successful removal of
+// a config.
+type RemoveConfigResponse struct {
+}
+
+func (m *RemoveConfigResponse) Reset() { *m = RemoveConfigResponse{} }
+func (*RemoveConfigResponse) ProtoMessage() {}
+func (*RemoveConfigResponse) Descriptor() ([]byte, []int) { return fileDescriptorControl, []int{58} }
+
+func init() {
+ proto.RegisterType((*GetNodeRequest)(nil), "docker.swarmkit.v1.GetNodeRequest")
+ proto.RegisterType((*GetNodeResponse)(nil), "docker.swarmkit.v1.GetNodeResponse")
+ proto.RegisterType((*ListNodesRequest)(nil), "docker.swarmkit.v1.ListNodesRequest")
+ proto.RegisterType((*ListNodesRequest_Filters)(nil), "docker.swarmkit.v1.ListNodesRequest.Filters")
+ proto.RegisterType((*ListNodesResponse)(nil), "docker.swarmkit.v1.ListNodesResponse")
+ proto.RegisterType((*UpdateNodeRequest)(nil), "docker.swarmkit.v1.UpdateNodeRequest")
+ proto.RegisterType((*UpdateNodeResponse)(nil), "docker.swarmkit.v1.UpdateNodeResponse")
+ proto.RegisterType((*RemoveNodeRequest)(nil), "docker.swarmkit.v1.RemoveNodeRequest")
+ proto.RegisterType((*RemoveNodeResponse)(nil), "docker.swarmkit.v1.RemoveNodeResponse")
+ proto.RegisterType((*GetTaskRequest)(nil), "docker.swarmkit.v1.GetTaskRequest")
+ proto.RegisterType((*GetTaskResponse)(nil), "docker.swarmkit.v1.GetTaskResponse")
+ proto.RegisterType((*RemoveTaskRequest)(nil), "docker.swarmkit.v1.RemoveTaskRequest")
+ proto.RegisterType((*RemoveTaskResponse)(nil), "docker.swarmkit.v1.RemoveTaskResponse")
+ proto.RegisterType((*ListTasksRequest)(nil), "docker.swarmkit.v1.ListTasksRequest")
+ proto.RegisterType((*ListTasksRequest_Filters)(nil), "docker.swarmkit.v1.ListTasksRequest.Filters")
+ proto.RegisterType((*ListTasksResponse)(nil), "docker.swarmkit.v1.ListTasksResponse")
+ proto.RegisterType((*CreateServiceRequest)(nil), "docker.swarmkit.v1.CreateServiceRequest")
+ proto.RegisterType((*CreateServiceResponse)(nil), "docker.swarmkit.v1.CreateServiceResponse")
+ proto.RegisterType((*GetServiceRequest)(nil), "docker.swarmkit.v1.GetServiceRequest")
+ proto.RegisterType((*GetServiceResponse)(nil), "docker.swarmkit.v1.GetServiceResponse")
+ proto.RegisterType((*UpdateServiceRequest)(nil), "docker.swarmkit.v1.UpdateServiceRequest")
+ proto.RegisterType((*UpdateServiceResponse)(nil), "docker.swarmkit.v1.UpdateServiceResponse")
+ proto.RegisterType((*RemoveServiceRequest)(nil), "docker.swarmkit.v1.RemoveServiceRequest")
+ proto.RegisterType((*RemoveServiceResponse)(nil), "docker.swarmkit.v1.RemoveServiceResponse")
+ proto.RegisterType((*ListServicesRequest)(nil), "docker.swarmkit.v1.ListServicesRequest")
+ proto.RegisterType((*ListServicesRequest_Filters)(nil), "docker.swarmkit.v1.ListServicesRequest.Filters")
+ proto.RegisterType((*ListServicesResponse)(nil), "docker.swarmkit.v1.ListServicesResponse")
+ proto.RegisterType((*CreateNetworkRequest)(nil), "docker.swarmkit.v1.CreateNetworkRequest")
+ proto.RegisterType((*CreateNetworkResponse)(nil), "docker.swarmkit.v1.CreateNetworkResponse")
+ proto.RegisterType((*GetNetworkRequest)(nil), "docker.swarmkit.v1.GetNetworkRequest")
+ proto.RegisterType((*GetNetworkResponse)(nil), "docker.swarmkit.v1.GetNetworkResponse")
+ proto.RegisterType((*RemoveNetworkRequest)(nil), "docker.swarmkit.v1.RemoveNetworkRequest")
+ proto.RegisterType((*RemoveNetworkResponse)(nil), "docker.swarmkit.v1.RemoveNetworkResponse")
+ proto.RegisterType((*ListNetworksRequest)(nil), "docker.swarmkit.v1.ListNetworksRequest")
+ proto.RegisterType((*ListNetworksRequest_Filters)(nil), "docker.swarmkit.v1.ListNetworksRequest.Filters")
+ proto.RegisterType((*ListNetworksResponse)(nil), "docker.swarmkit.v1.ListNetworksResponse")
+ proto.RegisterType((*GetClusterRequest)(nil), "docker.swarmkit.v1.GetClusterRequest")
+ proto.RegisterType((*GetClusterResponse)(nil), "docker.swarmkit.v1.GetClusterResponse")
+ proto.RegisterType((*ListClustersRequest)(nil), "docker.swarmkit.v1.ListClustersRequest")
+ proto.RegisterType((*ListClustersRequest_Filters)(nil), "docker.swarmkit.v1.ListClustersRequest.Filters")
+ proto.RegisterType((*ListClustersResponse)(nil), "docker.swarmkit.v1.ListClustersResponse")
+ proto.RegisterType((*KeyRotation)(nil), "docker.swarmkit.v1.KeyRotation")
+ proto.RegisterType((*UpdateClusterRequest)(nil), "docker.swarmkit.v1.UpdateClusterRequest")
+ proto.RegisterType((*UpdateClusterResponse)(nil), "docker.swarmkit.v1.UpdateClusterResponse")
+ proto.RegisterType((*GetSecretRequest)(nil), "docker.swarmkit.v1.GetSecretRequest")
+ proto.RegisterType((*GetSecretResponse)(nil), "docker.swarmkit.v1.GetSecretResponse")
+ proto.RegisterType((*UpdateSecretRequest)(nil), "docker.swarmkit.v1.UpdateSecretRequest")
+ proto.RegisterType((*UpdateSecretResponse)(nil), "docker.swarmkit.v1.UpdateSecretResponse")
+ proto.RegisterType((*ListSecretsRequest)(nil), "docker.swarmkit.v1.ListSecretsRequest")
+ proto.RegisterType((*ListSecretsRequest_Filters)(nil), "docker.swarmkit.v1.ListSecretsRequest.Filters")
+ proto.RegisterType((*ListSecretsResponse)(nil), "docker.swarmkit.v1.ListSecretsResponse")
+ proto.RegisterType((*CreateSecretRequest)(nil), "docker.swarmkit.v1.CreateSecretRequest")
+ proto.RegisterType((*CreateSecretResponse)(nil), "docker.swarmkit.v1.CreateSecretResponse")
+ proto.RegisterType((*RemoveSecretRequest)(nil), "docker.swarmkit.v1.RemoveSecretRequest")
+ proto.RegisterType((*RemoveSecretResponse)(nil), "docker.swarmkit.v1.RemoveSecretResponse")
+ proto.RegisterType((*GetConfigRequest)(nil), "docker.swarmkit.v1.GetConfigRequest")
+ proto.RegisterType((*GetConfigResponse)(nil), "docker.swarmkit.v1.GetConfigResponse")
+ proto.RegisterType((*UpdateConfigRequest)(nil), "docker.swarmkit.v1.UpdateConfigRequest")
+ proto.RegisterType((*UpdateConfigResponse)(nil), "docker.swarmkit.v1.UpdateConfigResponse")
+ proto.RegisterType((*ListConfigsRequest)(nil), "docker.swarmkit.v1.ListConfigsRequest")
+ proto.RegisterType((*ListConfigsRequest_Filters)(nil), "docker.swarmkit.v1.ListConfigsRequest.Filters")
+ proto.RegisterType((*ListConfigsResponse)(nil), "docker.swarmkit.v1.ListConfigsResponse")
+ proto.RegisterType((*CreateConfigRequest)(nil), "docker.swarmkit.v1.CreateConfigRequest")
+ proto.RegisterType((*CreateConfigResponse)(nil), "docker.swarmkit.v1.CreateConfigResponse")
+ proto.RegisterType((*RemoveConfigRequest)(nil), "docker.swarmkit.v1.RemoveConfigRequest")
+ proto.RegisterType((*RemoveConfigResponse)(nil), "docker.swarmkit.v1.RemoveConfigResponse")
+ proto.RegisterEnum("docker.swarmkit.v1.UpdateServiceRequest_Rollback", UpdateServiceRequest_Rollback_name, UpdateServiceRequest_Rollback_value)
+}
+
+type authenticatedWrapperControlServer struct {
+ local ControlServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperControlServer(local ControlServer, authorize func(context.Context, []string) error) ControlServer {
+ return &authenticatedWrapperControlServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperControlServer) GetNode(ctx context.Context, r *GetNodeRequest) (*GetNodeResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.GetNode(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) ListNodes(ctx context.Context, r *ListNodesRequest) (*ListNodesResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.ListNodes(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) UpdateNode(ctx context.Context, r *UpdateNodeRequest) (*UpdateNodeResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.UpdateNode(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) RemoveNode(ctx context.Context, r *RemoveNodeRequest) (*RemoveNodeResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.RemoveNode(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) GetTask(ctx context.Context, r *GetTaskRequest) (*GetTaskResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.GetTask(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) ListTasks(ctx context.Context, r *ListTasksRequest) (*ListTasksResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.ListTasks(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) RemoveTask(ctx context.Context, r *RemoveTaskRequest) (*RemoveTaskResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.RemoveTask(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) GetService(ctx context.Context, r *GetServiceRequest) (*GetServiceResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.GetService(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) ListServices(ctx context.Context, r *ListServicesRequest) (*ListServicesResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.ListServices(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) CreateService(ctx context.Context, r *CreateServiceRequest) (*CreateServiceResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.CreateService(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) UpdateService(ctx context.Context, r *UpdateServiceRequest) (*UpdateServiceResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.UpdateService(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) RemoveService(ctx context.Context, r *RemoveServiceRequest) (*RemoveServiceResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.RemoveService(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) GetNetwork(ctx context.Context, r *GetNetworkRequest) (*GetNetworkResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.GetNetwork(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) ListNetworks(ctx context.Context, r *ListNetworksRequest) (*ListNetworksResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.ListNetworks(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) CreateNetwork(ctx context.Context, r *CreateNetworkRequest) (*CreateNetworkResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.CreateNetwork(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) RemoveNetwork(ctx context.Context, r *RemoveNetworkRequest) (*RemoveNetworkResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.RemoveNetwork(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) GetCluster(ctx context.Context, r *GetClusterRequest) (*GetClusterResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.GetCluster(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) ListClusters(ctx context.Context, r *ListClustersRequest) (*ListClustersResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.ListClusters(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) UpdateCluster(ctx context.Context, r *UpdateClusterRequest) (*UpdateClusterResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.UpdateCluster(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) GetSecret(ctx context.Context, r *GetSecretRequest) (*GetSecretResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.GetSecret(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) UpdateSecret(ctx context.Context, r *UpdateSecretRequest) (*UpdateSecretResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.UpdateSecret(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) ListSecrets(ctx context.Context, r *ListSecretsRequest) (*ListSecretsResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.ListSecrets(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) CreateSecret(ctx context.Context, r *CreateSecretRequest) (*CreateSecretResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.CreateSecret(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) RemoveSecret(ctx context.Context, r *RemoveSecretRequest) (*RemoveSecretResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.RemoveSecret(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) GetConfig(ctx context.Context, r *GetConfigRequest) (*GetConfigResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.GetConfig(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) UpdateConfig(ctx context.Context, r *UpdateConfigRequest) (*UpdateConfigResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.UpdateConfig(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) ListConfigs(ctx context.Context, r *ListConfigsRequest) (*ListConfigsResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.ListConfigs(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) CreateConfig(ctx context.Context, r *CreateConfigRequest) (*CreateConfigResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.CreateConfig(ctx, r)
+}
+
+func (p *authenticatedWrapperControlServer) RemoveConfig(ctx context.Context, r *RemoveConfigRequest) (*RemoveConfigResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.RemoveConfig(ctx, r)
+}
+
+func (m *GetNodeRequest) Copy() *GetNodeRequest {
+ if m == nil {
+ return nil
+ }
+ o := &GetNodeRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetNodeRequest) CopyFrom(src interface{}) {
+
+ o := src.(*GetNodeRequest)
+ *m = *o
+}
+
+func (m *GetNodeResponse) Copy() *GetNodeResponse {
+ if m == nil {
+ return nil
+ }
+ o := &GetNodeResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetNodeResponse) CopyFrom(src interface{}) {
+
+ o := src.(*GetNodeResponse)
+ *m = *o
+ if o.Node != nil {
+ m.Node = &Node{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Node, o.Node)
+ }
+}
+
+func (m *ListNodesRequest) Copy() *ListNodesRequest {
+ if m == nil {
+ return nil
+ }
+ o := &ListNodesRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListNodesRequest) CopyFrom(src interface{}) {
+
+ o := src.(*ListNodesRequest)
+ *m = *o
+ if o.Filters != nil {
+ m.Filters = &ListNodesRequest_Filters{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Filters, o.Filters)
+ }
+}
+
+func (m *ListNodesRequest_Filters) Copy() *ListNodesRequest_Filters {
+ if m == nil {
+ return nil
+ }
+ o := &ListNodesRequest_Filters{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListNodesRequest_Filters) CopyFrom(src interface{}) {
+
+ o := src.(*ListNodesRequest_Filters)
+ *m = *o
+ if o.Names != nil {
+ m.Names = make([]string, len(o.Names))
+ copy(m.Names, o.Names)
+ }
+
+ if o.IDPrefixes != nil {
+ m.IDPrefixes = make([]string, len(o.IDPrefixes))
+ copy(m.IDPrefixes, o.IDPrefixes)
+ }
+
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.Memberships != nil {
+ m.Memberships = make([]NodeSpec_Membership, len(o.Memberships))
+ copy(m.Memberships, o.Memberships)
+ }
+
+ if o.Roles != nil {
+ m.Roles = make([]NodeRole, len(o.Roles))
+ copy(m.Roles, o.Roles)
+ }
+
+ if o.NamePrefixes != nil {
+ m.NamePrefixes = make([]string, len(o.NamePrefixes))
+ copy(m.NamePrefixes, o.NamePrefixes)
+ }
+
+}
+
+func (m *ListNodesResponse) Copy() *ListNodesResponse {
+ if m == nil {
+ return nil
+ }
+ o := &ListNodesResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListNodesResponse) CopyFrom(src interface{}) {
+
+ o := src.(*ListNodesResponse)
+ *m = *o
+ if o.Nodes != nil {
+ m.Nodes = make([]*Node, len(o.Nodes))
+ for i := range m.Nodes {
+ m.Nodes[i] = &Node{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Nodes[i], o.Nodes[i])
+ }
+ }
+
+}
+
+func (m *UpdateNodeRequest) Copy() *UpdateNodeRequest {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateNodeRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateNodeRequest) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateNodeRequest)
+ *m = *o
+ if o.NodeVersion != nil {
+ m.NodeVersion = &Version{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.NodeVersion, o.NodeVersion)
+ }
+ if o.Spec != nil {
+ m.Spec = &NodeSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Spec, o.Spec)
+ }
+}
+
+func (m *UpdateNodeResponse) Copy() *UpdateNodeResponse {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateNodeResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateNodeResponse) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateNodeResponse)
+ *m = *o
+ if o.Node != nil {
+ m.Node = &Node{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Node, o.Node)
+ }
+}
+
+func (m *RemoveNodeRequest) Copy() *RemoveNodeRequest {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveNodeRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveNodeRequest) CopyFrom(src interface{}) {
+
+ o := src.(*RemoveNodeRequest)
+ *m = *o
+}
+
+func (m *RemoveNodeResponse) Copy() *RemoveNodeResponse {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveNodeResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveNodeResponse) CopyFrom(src interface{}) {}
+func (m *GetTaskRequest) Copy() *GetTaskRequest {
+ if m == nil {
+ return nil
+ }
+ o := &GetTaskRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetTaskRequest) CopyFrom(src interface{}) {
+
+ o := src.(*GetTaskRequest)
+ *m = *o
+}
+
+func (m *GetTaskResponse) Copy() *GetTaskResponse {
+ if m == nil {
+ return nil
+ }
+ o := &GetTaskResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetTaskResponse) CopyFrom(src interface{}) {
+
+ o := src.(*GetTaskResponse)
+ *m = *o
+ if o.Task != nil {
+ m.Task = &Task{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Task, o.Task)
+ }
+}
+
+func (m *RemoveTaskRequest) Copy() *RemoveTaskRequest {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveTaskRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveTaskRequest) CopyFrom(src interface{}) {
+
+ o := src.(*RemoveTaskRequest)
+ *m = *o
+}
+
+func (m *RemoveTaskResponse) Copy() *RemoveTaskResponse {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveTaskResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveTaskResponse) CopyFrom(src interface{}) {}
+func (m *ListTasksRequest) Copy() *ListTasksRequest {
+ if m == nil {
+ return nil
+ }
+ o := &ListTasksRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListTasksRequest) CopyFrom(src interface{}) {
+
+ o := src.(*ListTasksRequest)
+ *m = *o
+ if o.Filters != nil {
+ m.Filters = &ListTasksRequest_Filters{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Filters, o.Filters)
+ }
+}
+
+func (m *ListTasksRequest_Filters) Copy() *ListTasksRequest_Filters {
+ if m == nil {
+ return nil
+ }
+ o := &ListTasksRequest_Filters{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListTasksRequest_Filters) CopyFrom(src interface{}) {
+
+ o := src.(*ListTasksRequest_Filters)
+ *m = *o
+ if o.Names != nil {
+ m.Names = make([]string, len(o.Names))
+ copy(m.Names, o.Names)
+ }
+
+ if o.IDPrefixes != nil {
+ m.IDPrefixes = make([]string, len(o.IDPrefixes))
+ copy(m.IDPrefixes, o.IDPrefixes)
+ }
+
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.ServiceIDs != nil {
+ m.ServiceIDs = make([]string, len(o.ServiceIDs))
+ copy(m.ServiceIDs, o.ServiceIDs)
+ }
+
+ if o.NodeIDs != nil {
+ m.NodeIDs = make([]string, len(o.NodeIDs))
+ copy(m.NodeIDs, o.NodeIDs)
+ }
+
+ if o.DesiredStates != nil {
+ m.DesiredStates = make([]TaskState, len(o.DesiredStates))
+ copy(m.DesiredStates, o.DesiredStates)
+ }
+
+ if o.NamePrefixes != nil {
+ m.NamePrefixes = make([]string, len(o.NamePrefixes))
+ copy(m.NamePrefixes, o.NamePrefixes)
+ }
+
+ if o.Runtimes != nil {
+ m.Runtimes = make([]string, len(o.Runtimes))
+ copy(m.Runtimes, o.Runtimes)
+ }
+
+}
+
+func (m *ListTasksResponse) Copy() *ListTasksResponse {
+ if m == nil {
+ return nil
+ }
+ o := &ListTasksResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListTasksResponse) CopyFrom(src interface{}) {
+
+ o := src.(*ListTasksResponse)
+ *m = *o
+ if o.Tasks != nil {
+ m.Tasks = make([]*Task, len(o.Tasks))
+ for i := range m.Tasks {
+ m.Tasks[i] = &Task{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Tasks[i], o.Tasks[i])
+ }
+ }
+
+}
+
+func (m *CreateServiceRequest) Copy() *CreateServiceRequest {
+ if m == nil {
+ return nil
+ }
+ o := &CreateServiceRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *CreateServiceRequest) CopyFrom(src interface{}) {
+
+ o := src.(*CreateServiceRequest)
+ *m = *o
+ if o.Spec != nil {
+ m.Spec = &ServiceSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Spec, o.Spec)
+ }
+}
+
+func (m *CreateServiceResponse) Copy() *CreateServiceResponse {
+ if m == nil {
+ return nil
+ }
+ o := &CreateServiceResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *CreateServiceResponse) CopyFrom(src interface{}) {
+
+ o := src.(*CreateServiceResponse)
+ *m = *o
+ if o.Service != nil {
+ m.Service = &Service{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Service, o.Service)
+ }
+}
+
+func (m *GetServiceRequest) Copy() *GetServiceRequest {
+ if m == nil {
+ return nil
+ }
+ o := &GetServiceRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetServiceRequest) CopyFrom(src interface{}) {
+
+ o := src.(*GetServiceRequest)
+ *m = *o
+}
+
+func (m *GetServiceResponse) Copy() *GetServiceResponse {
+ if m == nil {
+ return nil
+ }
+ o := &GetServiceResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetServiceResponse) CopyFrom(src interface{}) {
+
+ o := src.(*GetServiceResponse)
+ *m = *o
+ if o.Service != nil {
+ m.Service = &Service{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Service, o.Service)
+ }
+}
+
+func (m *UpdateServiceRequest) Copy() *UpdateServiceRequest {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateServiceRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateServiceRequest) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateServiceRequest)
+ *m = *o
+ if o.ServiceVersion != nil {
+ m.ServiceVersion = &Version{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.ServiceVersion, o.ServiceVersion)
+ }
+ if o.Spec != nil {
+ m.Spec = &ServiceSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Spec, o.Spec)
+ }
+}
+
+func (m *UpdateServiceResponse) Copy() *UpdateServiceResponse {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateServiceResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateServiceResponse) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateServiceResponse)
+ *m = *o
+ if o.Service != nil {
+ m.Service = &Service{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Service, o.Service)
+ }
+}
+
+func (m *RemoveServiceRequest) Copy() *RemoveServiceRequest {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveServiceRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveServiceRequest) CopyFrom(src interface{}) {
+
+ o := src.(*RemoveServiceRequest)
+ *m = *o
+}
+
+func (m *RemoveServiceResponse) Copy() *RemoveServiceResponse {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveServiceResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveServiceResponse) CopyFrom(src interface{}) {}
+func (m *ListServicesRequest) Copy() *ListServicesRequest {
+ if m == nil {
+ return nil
+ }
+ o := &ListServicesRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListServicesRequest) CopyFrom(src interface{}) {
+
+ o := src.(*ListServicesRequest)
+ *m = *o
+ if o.Filters != nil {
+ m.Filters = &ListServicesRequest_Filters{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Filters, o.Filters)
+ }
+}
+
+func (m *ListServicesRequest_Filters) Copy() *ListServicesRequest_Filters {
+ if m == nil {
+ return nil
+ }
+ o := &ListServicesRequest_Filters{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListServicesRequest_Filters) CopyFrom(src interface{}) {
+
+ o := src.(*ListServicesRequest_Filters)
+ *m = *o
+ if o.Names != nil {
+ m.Names = make([]string, len(o.Names))
+ copy(m.Names, o.Names)
+ }
+
+ if o.IDPrefixes != nil {
+ m.IDPrefixes = make([]string, len(o.IDPrefixes))
+ copy(m.IDPrefixes, o.IDPrefixes)
+ }
+
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.NamePrefixes != nil {
+ m.NamePrefixes = make([]string, len(o.NamePrefixes))
+ copy(m.NamePrefixes, o.NamePrefixes)
+ }
+
+ if o.Runtimes != nil {
+ m.Runtimes = make([]string, len(o.Runtimes))
+ copy(m.Runtimes, o.Runtimes)
+ }
+
+}
+
+func (m *ListServicesResponse) Copy() *ListServicesResponse {
+ if m == nil {
+ return nil
+ }
+ o := &ListServicesResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListServicesResponse) CopyFrom(src interface{}) {
+
+ o := src.(*ListServicesResponse)
+ *m = *o
+ if o.Services != nil {
+ m.Services = make([]*Service, len(o.Services))
+ for i := range m.Services {
+ m.Services[i] = &Service{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Services[i], o.Services[i])
+ }
+ }
+
+}
+
+func (m *CreateNetworkRequest) Copy() *CreateNetworkRequest {
+ if m == nil {
+ return nil
+ }
+ o := &CreateNetworkRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *CreateNetworkRequest) CopyFrom(src interface{}) {
+
+ o := src.(*CreateNetworkRequest)
+ *m = *o
+ if o.Spec != nil {
+ m.Spec = &NetworkSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Spec, o.Spec)
+ }
+}
+
+func (m *CreateNetworkResponse) Copy() *CreateNetworkResponse {
+ if m == nil {
+ return nil
+ }
+ o := &CreateNetworkResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *CreateNetworkResponse) CopyFrom(src interface{}) {
+
+ o := src.(*CreateNetworkResponse)
+ *m = *o
+ if o.Network != nil {
+ m.Network = &Network{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Network, o.Network)
+ }
+}
+
+func (m *GetNetworkRequest) Copy() *GetNetworkRequest {
+ if m == nil {
+ return nil
+ }
+ o := &GetNetworkRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetNetworkRequest) CopyFrom(src interface{}) {
+
+ o := src.(*GetNetworkRequest)
+ *m = *o
+}
+
+func (m *GetNetworkResponse) Copy() *GetNetworkResponse {
+ if m == nil {
+ return nil
+ }
+ o := &GetNetworkResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetNetworkResponse) CopyFrom(src interface{}) {
+
+ o := src.(*GetNetworkResponse)
+ *m = *o
+ if o.Network != nil {
+ m.Network = &Network{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Network, o.Network)
+ }
+}
+
+func (m *RemoveNetworkRequest) Copy() *RemoveNetworkRequest {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveNetworkRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveNetworkRequest) CopyFrom(src interface{}) {
+
+ o := src.(*RemoveNetworkRequest)
+ *m = *o
+}
+
+func (m *RemoveNetworkResponse) Copy() *RemoveNetworkResponse {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveNetworkResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveNetworkResponse) CopyFrom(src interface{}) {}
+func (m *ListNetworksRequest) Copy() *ListNetworksRequest {
+ if m == nil {
+ return nil
+ }
+ o := &ListNetworksRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListNetworksRequest) CopyFrom(src interface{}) {
+
+ o := src.(*ListNetworksRequest)
+ *m = *o
+ if o.Filters != nil {
+ m.Filters = &ListNetworksRequest_Filters{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Filters, o.Filters)
+ }
+}
+
+func (m *ListNetworksRequest_Filters) Copy() *ListNetworksRequest_Filters {
+ if m == nil {
+ return nil
+ }
+ o := &ListNetworksRequest_Filters{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListNetworksRequest_Filters) CopyFrom(src interface{}) {
+
+ o := src.(*ListNetworksRequest_Filters)
+ *m = *o
+ if o.Names != nil {
+ m.Names = make([]string, len(o.Names))
+ copy(m.Names, o.Names)
+ }
+
+ if o.IDPrefixes != nil {
+ m.IDPrefixes = make([]string, len(o.IDPrefixes))
+ copy(m.IDPrefixes, o.IDPrefixes)
+ }
+
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.NamePrefixes != nil {
+ m.NamePrefixes = make([]string, len(o.NamePrefixes))
+ copy(m.NamePrefixes, o.NamePrefixes)
+ }
+
+}
+
+func (m *ListNetworksResponse) Copy() *ListNetworksResponse {
+ if m == nil {
+ return nil
+ }
+ o := &ListNetworksResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListNetworksResponse) CopyFrom(src interface{}) {
+
+ o := src.(*ListNetworksResponse)
+ *m = *o
+ if o.Networks != nil {
+ m.Networks = make([]*Network, len(o.Networks))
+ for i := range m.Networks {
+ m.Networks[i] = &Network{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Networks[i], o.Networks[i])
+ }
+ }
+
+}
+
+func (m *GetClusterRequest) Copy() *GetClusterRequest {
+ if m == nil {
+ return nil
+ }
+ o := &GetClusterRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetClusterRequest) CopyFrom(src interface{}) {
+
+ o := src.(*GetClusterRequest)
+ *m = *o
+}
+
+func (m *GetClusterResponse) Copy() *GetClusterResponse {
+ if m == nil {
+ return nil
+ }
+ o := &GetClusterResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetClusterResponse) CopyFrom(src interface{}) {
+
+ o := src.(*GetClusterResponse)
+ *m = *o
+ if o.Cluster != nil {
+ m.Cluster = &Cluster{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Cluster, o.Cluster)
+ }
+}
+
+func (m *ListClustersRequest) Copy() *ListClustersRequest {
+ if m == nil {
+ return nil
+ }
+ o := &ListClustersRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListClustersRequest) CopyFrom(src interface{}) {
+
+ o := src.(*ListClustersRequest)
+ *m = *o
+ if o.Filters != nil {
+ m.Filters = &ListClustersRequest_Filters{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Filters, o.Filters)
+ }
+}
+
+func (m *ListClustersRequest_Filters) Copy() *ListClustersRequest_Filters {
+ if m == nil {
+ return nil
+ }
+ o := &ListClustersRequest_Filters{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListClustersRequest_Filters) CopyFrom(src interface{}) {
+
+ o := src.(*ListClustersRequest_Filters)
+ *m = *o
+ if o.Names != nil {
+ m.Names = make([]string, len(o.Names))
+ copy(m.Names, o.Names)
+ }
+
+ if o.IDPrefixes != nil {
+ m.IDPrefixes = make([]string, len(o.IDPrefixes))
+ copy(m.IDPrefixes, o.IDPrefixes)
+ }
+
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.NamePrefixes != nil {
+ m.NamePrefixes = make([]string, len(o.NamePrefixes))
+ copy(m.NamePrefixes, o.NamePrefixes)
+ }
+
+}
+
+func (m *ListClustersResponse) Copy() *ListClustersResponse {
+ if m == nil {
+ return nil
+ }
+ o := &ListClustersResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListClustersResponse) CopyFrom(src interface{}) {
+
+ o := src.(*ListClustersResponse)
+ *m = *o
+ if o.Clusters != nil {
+ m.Clusters = make([]*Cluster, len(o.Clusters))
+ for i := range m.Clusters {
+ m.Clusters[i] = &Cluster{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Clusters[i], o.Clusters[i])
+ }
+ }
+
+}
+
+func (m *KeyRotation) Copy() *KeyRotation {
+ if m == nil {
+ return nil
+ }
+ o := &KeyRotation{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *KeyRotation) CopyFrom(src interface{}) {
+
+ o := src.(*KeyRotation)
+ *m = *o
+}
+
+func (m *UpdateClusterRequest) Copy() *UpdateClusterRequest {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateClusterRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateClusterRequest) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateClusterRequest)
+ *m = *o
+ if o.ClusterVersion != nil {
+ m.ClusterVersion = &Version{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.ClusterVersion, o.ClusterVersion)
+ }
+ if o.Spec != nil {
+ m.Spec = &ClusterSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Spec, o.Spec)
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Rotation, &o.Rotation)
+}
+
+func (m *UpdateClusterResponse) Copy() *UpdateClusterResponse {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateClusterResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateClusterResponse) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateClusterResponse)
+ *m = *o
+ if o.Cluster != nil {
+ m.Cluster = &Cluster{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Cluster, o.Cluster)
+ }
+}
+
+func (m *GetSecretRequest) Copy() *GetSecretRequest {
+ if m == nil {
+ return nil
+ }
+ o := &GetSecretRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetSecretRequest) CopyFrom(src interface{}) {
+
+ o := src.(*GetSecretRequest)
+ *m = *o
+}
+
+func (m *GetSecretResponse) Copy() *GetSecretResponse {
+ if m == nil {
+ return nil
+ }
+ o := &GetSecretResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetSecretResponse) CopyFrom(src interface{}) {
+
+ o := src.(*GetSecretResponse)
+ *m = *o
+ if o.Secret != nil {
+ m.Secret = &Secret{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Secret, o.Secret)
+ }
+}
+
+func (m *UpdateSecretRequest) Copy() *UpdateSecretRequest {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateSecretRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateSecretRequest) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateSecretRequest)
+ *m = *o
+ if o.SecretVersion != nil {
+ m.SecretVersion = &Version{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.SecretVersion, o.SecretVersion)
+ }
+ if o.Spec != nil {
+ m.Spec = &SecretSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Spec, o.Spec)
+ }
+}
+
+func (m *UpdateSecretResponse) Copy() *UpdateSecretResponse {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateSecretResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateSecretResponse) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateSecretResponse)
+ *m = *o
+ if o.Secret != nil {
+ m.Secret = &Secret{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Secret, o.Secret)
+ }
+}
+
+func (m *ListSecretsRequest) Copy() *ListSecretsRequest {
+ if m == nil {
+ return nil
+ }
+ o := &ListSecretsRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListSecretsRequest) CopyFrom(src interface{}) {
+
+ o := src.(*ListSecretsRequest)
+ *m = *o
+ if o.Filters != nil {
+ m.Filters = &ListSecretsRequest_Filters{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Filters, o.Filters)
+ }
+}
+
+func (m *ListSecretsRequest_Filters) Copy() *ListSecretsRequest_Filters {
+ if m == nil {
+ return nil
+ }
+ o := &ListSecretsRequest_Filters{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListSecretsRequest_Filters) CopyFrom(src interface{}) {
+
+ o := src.(*ListSecretsRequest_Filters)
+ *m = *o
+ if o.Names != nil {
+ m.Names = make([]string, len(o.Names))
+ copy(m.Names, o.Names)
+ }
+
+ if o.IDPrefixes != nil {
+ m.IDPrefixes = make([]string, len(o.IDPrefixes))
+ copy(m.IDPrefixes, o.IDPrefixes)
+ }
+
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.NamePrefixes != nil {
+ m.NamePrefixes = make([]string, len(o.NamePrefixes))
+ copy(m.NamePrefixes, o.NamePrefixes)
+ }
+
+}
+
+func (m *ListSecretsResponse) Copy() *ListSecretsResponse {
+ if m == nil {
+ return nil
+ }
+ o := &ListSecretsResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListSecretsResponse) CopyFrom(src interface{}) {
+
+ o := src.(*ListSecretsResponse)
+ *m = *o
+ if o.Secrets != nil {
+ m.Secrets = make([]*Secret, len(o.Secrets))
+ for i := range m.Secrets {
+ m.Secrets[i] = &Secret{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Secrets[i], o.Secrets[i])
+ }
+ }
+
+}
+
+func (m *CreateSecretRequest) Copy() *CreateSecretRequest {
+ if m == nil {
+ return nil
+ }
+ o := &CreateSecretRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *CreateSecretRequest) CopyFrom(src interface{}) {
+
+ o := src.(*CreateSecretRequest)
+ *m = *o
+ if o.Spec != nil {
+ m.Spec = &SecretSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Spec, o.Spec)
+ }
+}
+
+func (m *CreateSecretResponse) Copy() *CreateSecretResponse {
+ if m == nil {
+ return nil
+ }
+ o := &CreateSecretResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *CreateSecretResponse) CopyFrom(src interface{}) {
+
+ o := src.(*CreateSecretResponse)
+ *m = *o
+ if o.Secret != nil {
+ m.Secret = &Secret{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Secret, o.Secret)
+ }
+}
+
+func (m *RemoveSecretRequest) Copy() *RemoveSecretRequest {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveSecretRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveSecretRequest) CopyFrom(src interface{}) {
+
+ o := src.(*RemoveSecretRequest)
+ *m = *o
+}
+
+func (m *RemoveSecretResponse) Copy() *RemoveSecretResponse {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveSecretResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveSecretResponse) CopyFrom(src interface{}) {}
+func (m *GetConfigRequest) Copy() *GetConfigRequest {
+ if m == nil {
+ return nil
+ }
+ o := &GetConfigRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetConfigRequest) CopyFrom(src interface{}) {
+
+ o := src.(*GetConfigRequest)
+ *m = *o
+}
+
+func (m *GetConfigResponse) Copy() *GetConfigResponse {
+ if m == nil {
+ return nil
+ }
+ o := &GetConfigResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GetConfigResponse) CopyFrom(src interface{}) {
+
+ o := src.(*GetConfigResponse)
+ *m = *o
+ if o.Config != nil {
+ m.Config = &Config{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Config, o.Config)
+ }
+}
+
+func (m *UpdateConfigRequest) Copy() *UpdateConfigRequest {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateConfigRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateConfigRequest) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateConfigRequest)
+ *m = *o
+ if o.ConfigVersion != nil {
+ m.ConfigVersion = &Version{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.ConfigVersion, o.ConfigVersion)
+ }
+ if o.Spec != nil {
+ m.Spec = &ConfigSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Spec, o.Spec)
+ }
+}
+
+func (m *UpdateConfigResponse) Copy() *UpdateConfigResponse {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateConfigResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateConfigResponse) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateConfigResponse)
+ *m = *o
+ if o.Config != nil {
+ m.Config = &Config{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Config, o.Config)
+ }
+}
+
+func (m *ListConfigsRequest) Copy() *ListConfigsRequest {
+ if m == nil {
+ return nil
+ }
+ o := &ListConfigsRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListConfigsRequest) CopyFrom(src interface{}) {
+
+ o := src.(*ListConfigsRequest)
+ *m = *o
+ if o.Filters != nil {
+ m.Filters = &ListConfigsRequest_Filters{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Filters, o.Filters)
+ }
+}
+
+func (m *ListConfigsRequest_Filters) Copy() *ListConfigsRequest_Filters {
+ if m == nil {
+ return nil
+ }
+ o := &ListConfigsRequest_Filters{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListConfigsRequest_Filters) CopyFrom(src interface{}) {
+
+ o := src.(*ListConfigsRequest_Filters)
+ *m = *o
+ if o.Names != nil {
+ m.Names = make([]string, len(o.Names))
+ copy(m.Names, o.Names)
+ }
+
+ if o.IDPrefixes != nil {
+ m.IDPrefixes = make([]string, len(o.IDPrefixes))
+ copy(m.IDPrefixes, o.IDPrefixes)
+ }
+
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.NamePrefixes != nil {
+ m.NamePrefixes = make([]string, len(o.NamePrefixes))
+ copy(m.NamePrefixes, o.NamePrefixes)
+ }
+
+}
+
+func (m *ListConfigsResponse) Copy() *ListConfigsResponse {
+ if m == nil {
+ return nil
+ }
+ o := &ListConfigsResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListConfigsResponse) CopyFrom(src interface{}) {
+
+ o := src.(*ListConfigsResponse)
+ *m = *o
+ if o.Configs != nil {
+ m.Configs = make([]*Config, len(o.Configs))
+ for i := range m.Configs {
+ m.Configs[i] = &Config{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Configs[i], o.Configs[i])
+ }
+ }
+
+}
+
+func (m *CreateConfigRequest) Copy() *CreateConfigRequest {
+ if m == nil {
+ return nil
+ }
+ o := &CreateConfigRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *CreateConfigRequest) CopyFrom(src interface{}) {
+
+ o := src.(*CreateConfigRequest)
+ *m = *o
+ if o.Spec != nil {
+ m.Spec = &ConfigSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Spec, o.Spec)
+ }
+}
+
+func (m *CreateConfigResponse) Copy() *CreateConfigResponse {
+ if m == nil {
+ return nil
+ }
+ o := &CreateConfigResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *CreateConfigResponse) CopyFrom(src interface{}) {
+
+ o := src.(*CreateConfigResponse)
+ *m = *o
+ if o.Config != nil {
+ m.Config = &Config{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Config, o.Config)
+ }
+}
+
+func (m *RemoveConfigRequest) Copy() *RemoveConfigRequest {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveConfigRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveConfigRequest) CopyFrom(src interface{}) {
+
+ o := src.(*RemoveConfigRequest)
+ *m = *o
+}
+
+func (m *RemoveConfigResponse) Copy() *RemoveConfigResponse {
+ if m == nil {
+ return nil
+ }
+ o := &RemoveConfigResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RemoveConfigResponse) CopyFrom(src interface{}) {}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for Control service
+
+type ControlClient interface {
+ GetNode(ctx context.Context, in *GetNodeRequest, opts ...grpc.CallOption) (*GetNodeResponse, error)
+ ListNodes(ctx context.Context, in *ListNodesRequest, opts ...grpc.CallOption) (*ListNodesResponse, error)
+ UpdateNode(ctx context.Context, in *UpdateNodeRequest, opts ...grpc.CallOption) (*UpdateNodeResponse, error)
+ RemoveNode(ctx context.Context, in *RemoveNodeRequest, opts ...grpc.CallOption) (*RemoveNodeResponse, error)
+ GetTask(ctx context.Context, in *GetTaskRequest, opts ...grpc.CallOption) (*GetTaskResponse, error)
+ ListTasks(ctx context.Context, in *ListTasksRequest, opts ...grpc.CallOption) (*ListTasksResponse, error)
+ RemoveTask(ctx context.Context, in *RemoveTaskRequest, opts ...grpc.CallOption) (*RemoveTaskResponse, error)
+ GetService(ctx context.Context, in *GetServiceRequest, opts ...grpc.CallOption) (*GetServiceResponse, error)
+ ListServices(ctx context.Context, in *ListServicesRequest, opts ...grpc.CallOption) (*ListServicesResponse, error)
+ CreateService(ctx context.Context, in *CreateServiceRequest, opts ...grpc.CallOption) (*CreateServiceResponse, error)
+ UpdateService(ctx context.Context, in *UpdateServiceRequest, opts ...grpc.CallOption) (*UpdateServiceResponse, error)
+ RemoveService(ctx context.Context, in *RemoveServiceRequest, opts ...grpc.CallOption) (*RemoveServiceResponse, error)
+ GetNetwork(ctx context.Context, in *GetNetworkRequest, opts ...grpc.CallOption) (*GetNetworkResponse, error)
+ ListNetworks(ctx context.Context, in *ListNetworksRequest, opts ...grpc.CallOption) (*ListNetworksResponse, error)
+ CreateNetwork(ctx context.Context, in *CreateNetworkRequest, opts ...grpc.CallOption) (*CreateNetworkResponse, error)
+ RemoveNetwork(ctx context.Context, in *RemoveNetworkRequest, opts ...grpc.CallOption) (*RemoveNetworkResponse, error)
+ GetCluster(ctx context.Context, in *GetClusterRequest, opts ...grpc.CallOption) (*GetClusterResponse, error)
+ ListClusters(ctx context.Context, in *ListClustersRequest, opts ...grpc.CallOption) (*ListClustersResponse, error)
+ UpdateCluster(ctx context.Context, in *UpdateClusterRequest, opts ...grpc.CallOption) (*UpdateClusterResponse, error)
+ // GetSecret returns a `GetSecretResponse` with a `Secret` with the same
+ // id as `GetSecretRequest.SecretID`
+ // - Returns `NotFound` if the Secret with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetSecretRequest.SecretID` is empty.
+ // - Returns an error if getting fails.
+ GetSecret(ctx context.Context, in *GetSecretRequest, opts ...grpc.CallOption) (*GetSecretResponse, error)
+ // UpdateSecret returns a `UpdateSecretResponse` with a `Secret` with the same
+ // id as `GetSecretRequest.SecretID`
+ // - Returns `NotFound` if the Secret with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetSecretRequest.SecretID` is empty.
+ // - Returns an error if updating fails.
+ UpdateSecret(ctx context.Context, in *UpdateSecretRequest, opts ...grpc.CallOption) (*UpdateSecretResponse, error)
+ // ListSecrets returns a `ListSecretResponse` with a list of all non-internal `Secret`s being
+ // managed, or all secrets matching any name in `ListSecretsRequest.Names`, any
+ // name prefix in `ListSecretsRequest.NamePrefixes`, any id in
+ // `ListSecretsRequest.SecretIDs`, or any id prefix in `ListSecretsRequest.IDPrefixes`.
+ // - Returns an error if listing fails.
+ ListSecrets(ctx context.Context, in *ListSecretsRequest, opts ...grpc.CallOption) (*ListSecretsResponse, error)
+ // CreateSecret creates and return a `CreateSecretResponse` with a `Secret` based
+ // on the provided `CreateSecretRequest.SecretSpec`.
+ // - Returns `InvalidArgument` if the `CreateSecretRequest.SecretSpec` is malformed,
+ // or if the secret data is too long or contains invalid characters.
+ // - Returns an error if the creation fails.
+ CreateSecret(ctx context.Context, in *CreateSecretRequest, opts ...grpc.CallOption) (*CreateSecretResponse, error)
+ // RemoveSecret removes the secret referenced by `RemoveSecretRequest.ID`.
+ // - Returns `InvalidArgument` if `RemoveSecretRequest.ID` is empty.
+ // - Returns `NotFound` if the a secret named `RemoveSecretRequest.ID` is not found.
+ // - Returns an error if the deletion fails.
+ RemoveSecret(ctx context.Context, in *RemoveSecretRequest, opts ...grpc.CallOption) (*RemoveSecretResponse, error)
+ // GetConfig returns a `GetConfigResponse` with a `Config` with the same
+ // id as `GetConfigRequest.ConfigID`
+ // - Returns `NotFound` if the Config with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetConfigRequest.ConfigID` is empty.
+ // - Returns an error if getting fails.
+ GetConfig(ctx context.Context, in *GetConfigRequest, opts ...grpc.CallOption) (*GetConfigResponse, error)
+ // UpdateConfig returns a `UpdateConfigResponse` with a `Config` with the same
+ // id as `GetConfigRequest.ConfigID`
+ // - Returns `NotFound` if the Config with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetConfigRequest.ConfigID` is empty.
+ // - Returns an error if updating fails.
+ UpdateConfig(ctx context.Context, in *UpdateConfigRequest, opts ...grpc.CallOption) (*UpdateConfigResponse, error)
+ // ListConfigs returns a `ListConfigResponse` with a list of `Config`s being
+ // managed, or all configs matching any name in `ListConfigsRequest.Names`, any
+ // name prefix in `ListConfigsRequest.NamePrefixes`, any id in
+ // `ListConfigsRequest.ConfigIDs`, or any id prefix in `ListConfigsRequest.IDPrefixes`.
+ // - Returns an error if listing fails.
+ ListConfigs(ctx context.Context, in *ListConfigsRequest, opts ...grpc.CallOption) (*ListConfigsResponse, error)
+ // CreateConfig creates and return a `CreateConfigResponse` with a `Config` based
+ // on the provided `CreateConfigRequest.ConfigSpec`.
+ // - Returns `InvalidArgument` if the `CreateConfigRequest.ConfigSpec` is malformed,
+ // or if the config data is too long or contains invalid characters.
+ // - Returns an error if the creation fails.
+ CreateConfig(ctx context.Context, in *CreateConfigRequest, opts ...grpc.CallOption) (*CreateConfigResponse, error)
+ // RemoveConfig removes the config referenced by `RemoveConfigRequest.ID`.
+ // - Returns `InvalidArgument` if `RemoveConfigRequest.ID` is empty.
+ // - Returns `NotFound` if the a config named `RemoveConfigRequest.ID` is not found.
+ // - Returns an error if the deletion fails.
+ RemoveConfig(ctx context.Context, in *RemoveConfigRequest, opts ...grpc.CallOption) (*RemoveConfigResponse, error)
+}
+
+type controlClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewControlClient(cc *grpc.ClientConn) ControlClient {
+ return &controlClient{cc}
+}
+
+func (c *controlClient) GetNode(ctx context.Context, in *GetNodeRequest, opts ...grpc.CallOption) (*GetNodeResponse, error) {
+ out := new(GetNodeResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/GetNode", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) ListNodes(ctx context.Context, in *ListNodesRequest, opts ...grpc.CallOption) (*ListNodesResponse, error) {
+ out := new(ListNodesResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/ListNodes", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) UpdateNode(ctx context.Context, in *UpdateNodeRequest, opts ...grpc.CallOption) (*UpdateNodeResponse, error) {
+ out := new(UpdateNodeResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/UpdateNode", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) RemoveNode(ctx context.Context, in *RemoveNodeRequest, opts ...grpc.CallOption) (*RemoveNodeResponse, error) {
+ out := new(RemoveNodeResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/RemoveNode", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) GetTask(ctx context.Context, in *GetTaskRequest, opts ...grpc.CallOption) (*GetTaskResponse, error) {
+ out := new(GetTaskResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/GetTask", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) ListTasks(ctx context.Context, in *ListTasksRequest, opts ...grpc.CallOption) (*ListTasksResponse, error) {
+ out := new(ListTasksResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/ListTasks", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) RemoveTask(ctx context.Context, in *RemoveTaskRequest, opts ...grpc.CallOption) (*RemoveTaskResponse, error) {
+ out := new(RemoveTaskResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/RemoveTask", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) GetService(ctx context.Context, in *GetServiceRequest, opts ...grpc.CallOption) (*GetServiceResponse, error) {
+ out := new(GetServiceResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/GetService", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) ListServices(ctx context.Context, in *ListServicesRequest, opts ...grpc.CallOption) (*ListServicesResponse, error) {
+ out := new(ListServicesResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/ListServices", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) CreateService(ctx context.Context, in *CreateServiceRequest, opts ...grpc.CallOption) (*CreateServiceResponse, error) {
+ out := new(CreateServiceResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/CreateService", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) UpdateService(ctx context.Context, in *UpdateServiceRequest, opts ...grpc.CallOption) (*UpdateServiceResponse, error) {
+ out := new(UpdateServiceResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/UpdateService", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) RemoveService(ctx context.Context, in *RemoveServiceRequest, opts ...grpc.CallOption) (*RemoveServiceResponse, error) {
+ out := new(RemoveServiceResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/RemoveService", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) GetNetwork(ctx context.Context, in *GetNetworkRequest, opts ...grpc.CallOption) (*GetNetworkResponse, error) {
+ out := new(GetNetworkResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/GetNetwork", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) ListNetworks(ctx context.Context, in *ListNetworksRequest, opts ...grpc.CallOption) (*ListNetworksResponse, error) {
+ out := new(ListNetworksResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/ListNetworks", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) CreateNetwork(ctx context.Context, in *CreateNetworkRequest, opts ...grpc.CallOption) (*CreateNetworkResponse, error) {
+ out := new(CreateNetworkResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/CreateNetwork", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) RemoveNetwork(ctx context.Context, in *RemoveNetworkRequest, opts ...grpc.CallOption) (*RemoveNetworkResponse, error) {
+ out := new(RemoveNetworkResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/RemoveNetwork", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) GetCluster(ctx context.Context, in *GetClusterRequest, opts ...grpc.CallOption) (*GetClusterResponse, error) {
+ out := new(GetClusterResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/GetCluster", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) ListClusters(ctx context.Context, in *ListClustersRequest, opts ...grpc.CallOption) (*ListClustersResponse, error) {
+ out := new(ListClustersResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/ListClusters", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) UpdateCluster(ctx context.Context, in *UpdateClusterRequest, opts ...grpc.CallOption) (*UpdateClusterResponse, error) {
+ out := new(UpdateClusterResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/UpdateCluster", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) GetSecret(ctx context.Context, in *GetSecretRequest, opts ...grpc.CallOption) (*GetSecretResponse, error) {
+ out := new(GetSecretResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/GetSecret", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) UpdateSecret(ctx context.Context, in *UpdateSecretRequest, opts ...grpc.CallOption) (*UpdateSecretResponse, error) {
+ out := new(UpdateSecretResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/UpdateSecret", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) ListSecrets(ctx context.Context, in *ListSecretsRequest, opts ...grpc.CallOption) (*ListSecretsResponse, error) {
+ out := new(ListSecretsResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/ListSecrets", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) CreateSecret(ctx context.Context, in *CreateSecretRequest, opts ...grpc.CallOption) (*CreateSecretResponse, error) {
+ out := new(CreateSecretResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/CreateSecret", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) RemoveSecret(ctx context.Context, in *RemoveSecretRequest, opts ...grpc.CallOption) (*RemoveSecretResponse, error) {
+ out := new(RemoveSecretResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/RemoveSecret", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) GetConfig(ctx context.Context, in *GetConfigRequest, opts ...grpc.CallOption) (*GetConfigResponse, error) {
+ out := new(GetConfigResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/GetConfig", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) UpdateConfig(ctx context.Context, in *UpdateConfigRequest, opts ...grpc.CallOption) (*UpdateConfigResponse, error) {
+ out := new(UpdateConfigResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/UpdateConfig", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) ListConfigs(ctx context.Context, in *ListConfigsRequest, opts ...grpc.CallOption) (*ListConfigsResponse, error) {
+ out := new(ListConfigsResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/ListConfigs", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) CreateConfig(ctx context.Context, in *CreateConfigRequest, opts ...grpc.CallOption) (*CreateConfigResponse, error) {
+ out := new(CreateConfigResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/CreateConfig", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *controlClient) RemoveConfig(ctx context.Context, in *RemoveConfigRequest, opts ...grpc.CallOption) (*RemoveConfigResponse, error) {
+ out := new(RemoveConfigResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Control/RemoveConfig", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for Control service
+
+type ControlServer interface {
+ GetNode(context.Context, *GetNodeRequest) (*GetNodeResponse, error)
+ ListNodes(context.Context, *ListNodesRequest) (*ListNodesResponse, error)
+ UpdateNode(context.Context, *UpdateNodeRequest) (*UpdateNodeResponse, error)
+ RemoveNode(context.Context, *RemoveNodeRequest) (*RemoveNodeResponse, error)
+ GetTask(context.Context, *GetTaskRequest) (*GetTaskResponse, error)
+ ListTasks(context.Context, *ListTasksRequest) (*ListTasksResponse, error)
+ RemoveTask(context.Context, *RemoveTaskRequest) (*RemoveTaskResponse, error)
+ GetService(context.Context, *GetServiceRequest) (*GetServiceResponse, error)
+ ListServices(context.Context, *ListServicesRequest) (*ListServicesResponse, error)
+ CreateService(context.Context, *CreateServiceRequest) (*CreateServiceResponse, error)
+ UpdateService(context.Context, *UpdateServiceRequest) (*UpdateServiceResponse, error)
+ RemoveService(context.Context, *RemoveServiceRequest) (*RemoveServiceResponse, error)
+ GetNetwork(context.Context, *GetNetworkRequest) (*GetNetworkResponse, error)
+ ListNetworks(context.Context, *ListNetworksRequest) (*ListNetworksResponse, error)
+ CreateNetwork(context.Context, *CreateNetworkRequest) (*CreateNetworkResponse, error)
+ RemoveNetwork(context.Context, *RemoveNetworkRequest) (*RemoveNetworkResponse, error)
+ GetCluster(context.Context, *GetClusterRequest) (*GetClusterResponse, error)
+ ListClusters(context.Context, *ListClustersRequest) (*ListClustersResponse, error)
+ UpdateCluster(context.Context, *UpdateClusterRequest) (*UpdateClusterResponse, error)
+ // GetSecret returns a `GetSecretResponse` with a `Secret` with the same
+ // id as `GetSecretRequest.SecretID`
+ // - Returns `NotFound` if the Secret with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetSecretRequest.SecretID` is empty.
+ // - Returns an error if getting fails.
+ GetSecret(context.Context, *GetSecretRequest) (*GetSecretResponse, error)
+ // UpdateSecret returns a `UpdateSecretResponse` with a `Secret` with the same
+ // id as `GetSecretRequest.SecretID`
+ // - Returns `NotFound` if the Secret with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetSecretRequest.SecretID` is empty.
+ // - Returns an error if updating fails.
+ UpdateSecret(context.Context, *UpdateSecretRequest) (*UpdateSecretResponse, error)
+ // ListSecrets returns a `ListSecretResponse` with a list of all non-internal `Secret`s being
+ // managed, or all secrets matching any name in `ListSecretsRequest.Names`, any
+ // name prefix in `ListSecretsRequest.NamePrefixes`, any id in
+ // `ListSecretsRequest.SecretIDs`, or any id prefix in `ListSecretsRequest.IDPrefixes`.
+ // - Returns an error if listing fails.
+ ListSecrets(context.Context, *ListSecretsRequest) (*ListSecretsResponse, error)
+ // CreateSecret creates and return a `CreateSecretResponse` with a `Secret` based
+ // on the provided `CreateSecretRequest.SecretSpec`.
+ // - Returns `InvalidArgument` if the `CreateSecretRequest.SecretSpec` is malformed,
+ // or if the secret data is too long or contains invalid characters.
+ // - Returns an error if the creation fails.
+ CreateSecret(context.Context, *CreateSecretRequest) (*CreateSecretResponse, error)
+ // RemoveSecret removes the secret referenced by `RemoveSecretRequest.ID`.
+ // - Returns `InvalidArgument` if `RemoveSecretRequest.ID` is empty.
+ // - Returns `NotFound` if the a secret named `RemoveSecretRequest.ID` is not found.
+ // - Returns an error if the deletion fails.
+ RemoveSecret(context.Context, *RemoveSecretRequest) (*RemoveSecretResponse, error)
+ // GetConfig returns a `GetConfigResponse` with a `Config` with the same
+ // id as `GetConfigRequest.ConfigID`
+ // - Returns `NotFound` if the Config with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetConfigRequest.ConfigID` is empty.
+ // - Returns an error if getting fails.
+ GetConfig(context.Context, *GetConfigRequest) (*GetConfigResponse, error)
+ // UpdateConfig returns a `UpdateConfigResponse` with a `Config` with the same
+ // id as `GetConfigRequest.ConfigID`
+ // - Returns `NotFound` if the Config with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetConfigRequest.ConfigID` is empty.
+ // - Returns an error if updating fails.
+ UpdateConfig(context.Context, *UpdateConfigRequest) (*UpdateConfigResponse, error)
+ // ListConfigs returns a `ListConfigResponse` with a list of `Config`s being
+ // managed, or all configs matching any name in `ListConfigsRequest.Names`, any
+ // name prefix in `ListConfigsRequest.NamePrefixes`, any id in
+ // `ListConfigsRequest.ConfigIDs`, or any id prefix in `ListConfigsRequest.IDPrefixes`.
+ // - Returns an error if listing fails.
+ ListConfigs(context.Context, *ListConfigsRequest) (*ListConfigsResponse, error)
+ // CreateConfig creates and return a `CreateConfigResponse` with a `Config` based
+ // on the provided `CreateConfigRequest.ConfigSpec`.
+ // - Returns `InvalidArgument` if the `CreateConfigRequest.ConfigSpec` is malformed,
+ // or if the config data is too long or contains invalid characters.
+ // - Returns an error if the creation fails.
+ CreateConfig(context.Context, *CreateConfigRequest) (*CreateConfigResponse, error)
+ // RemoveConfig removes the config referenced by `RemoveConfigRequest.ID`.
+ // - Returns `InvalidArgument` if `RemoveConfigRequest.ID` is empty.
+ // - Returns `NotFound` if the a config named `RemoveConfigRequest.ID` is not found.
+ // - Returns an error if the deletion fails.
+ RemoveConfig(context.Context, *RemoveConfigRequest) (*RemoveConfigResponse, error)
+}
+
+func RegisterControlServer(s *grpc.Server, srv ControlServer) {
+ s.RegisterService(&_Control_serviceDesc, srv)
+}
+
+func _Control_GetNode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetNodeRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).GetNode(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/GetNode",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).GetNode(ctx, req.(*GetNodeRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_ListNodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListNodesRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).ListNodes(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/ListNodes",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).ListNodes(ctx, req.(*ListNodesRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_UpdateNode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateNodeRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).UpdateNode(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/UpdateNode",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).UpdateNode(ctx, req.(*UpdateNodeRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_RemoveNode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RemoveNodeRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).RemoveNode(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/RemoveNode",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).RemoveNode(ctx, req.(*RemoveNodeRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_GetTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetTaskRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).GetTask(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/GetTask",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).GetTask(ctx, req.(*GetTaskRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_ListTasks_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListTasksRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).ListTasks(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/ListTasks",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).ListTasks(ctx, req.(*ListTasksRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_RemoveTask_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RemoveTaskRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).RemoveTask(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/RemoveTask",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).RemoveTask(ctx, req.(*RemoveTaskRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_GetService_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetServiceRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).GetService(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/GetService",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).GetService(ctx, req.(*GetServiceRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_ListServices_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListServicesRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).ListServices(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/ListServices",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).ListServices(ctx, req.(*ListServicesRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_CreateService_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreateServiceRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).CreateService(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/CreateService",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).CreateService(ctx, req.(*CreateServiceRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_UpdateService_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateServiceRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).UpdateService(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/UpdateService",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).UpdateService(ctx, req.(*UpdateServiceRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_RemoveService_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RemoveServiceRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).RemoveService(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/RemoveService",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).RemoveService(ctx, req.(*RemoveServiceRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_GetNetwork_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetNetworkRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).GetNetwork(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/GetNetwork",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).GetNetwork(ctx, req.(*GetNetworkRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_ListNetworks_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListNetworksRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).ListNetworks(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/ListNetworks",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).ListNetworks(ctx, req.(*ListNetworksRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_CreateNetwork_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreateNetworkRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).CreateNetwork(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/CreateNetwork",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).CreateNetwork(ctx, req.(*CreateNetworkRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_RemoveNetwork_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RemoveNetworkRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).RemoveNetwork(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/RemoveNetwork",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).RemoveNetwork(ctx, req.(*RemoveNetworkRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_GetCluster_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetClusterRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).GetCluster(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/GetCluster",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).GetCluster(ctx, req.(*GetClusterRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_ListClusters_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListClustersRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).ListClusters(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/ListClusters",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).ListClusters(ctx, req.(*ListClustersRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_UpdateCluster_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateClusterRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).UpdateCluster(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/UpdateCluster",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).UpdateCluster(ctx, req.(*UpdateClusterRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_GetSecret_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetSecretRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).GetSecret(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/GetSecret",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).GetSecret(ctx, req.(*GetSecretRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_UpdateSecret_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateSecretRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).UpdateSecret(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/UpdateSecret",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).UpdateSecret(ctx, req.(*UpdateSecretRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_ListSecrets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListSecretsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).ListSecrets(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/ListSecrets",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).ListSecrets(ctx, req.(*ListSecretsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_CreateSecret_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreateSecretRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).CreateSecret(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/CreateSecret",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).CreateSecret(ctx, req.(*CreateSecretRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_RemoveSecret_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RemoveSecretRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).RemoveSecret(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/RemoveSecret",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).RemoveSecret(ctx, req.(*RemoveSecretRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_GetConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetConfigRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).GetConfig(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/GetConfig",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).GetConfig(ctx, req.(*GetConfigRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_UpdateConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateConfigRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).UpdateConfig(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/UpdateConfig",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).UpdateConfig(ctx, req.(*UpdateConfigRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_ListConfigs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListConfigsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).ListConfigs(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/ListConfigs",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).ListConfigs(ctx, req.(*ListConfigsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_CreateConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreateConfigRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).CreateConfig(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/CreateConfig",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).CreateConfig(ctx, req.(*CreateConfigRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Control_RemoveConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RemoveConfigRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ControlServer).RemoveConfig(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Control/RemoveConfig",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ControlServer).RemoveConfig(ctx, req.(*RemoveConfigRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _Control_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.Control",
+ HandlerType: (*ControlServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "GetNode",
+ Handler: _Control_GetNode_Handler,
+ },
+ {
+ MethodName: "ListNodes",
+ Handler: _Control_ListNodes_Handler,
+ },
+ {
+ MethodName: "UpdateNode",
+ Handler: _Control_UpdateNode_Handler,
+ },
+ {
+ MethodName: "RemoveNode",
+ Handler: _Control_RemoveNode_Handler,
+ },
+ {
+ MethodName: "GetTask",
+ Handler: _Control_GetTask_Handler,
+ },
+ {
+ MethodName: "ListTasks",
+ Handler: _Control_ListTasks_Handler,
+ },
+ {
+ MethodName: "RemoveTask",
+ Handler: _Control_RemoveTask_Handler,
+ },
+ {
+ MethodName: "GetService",
+ Handler: _Control_GetService_Handler,
+ },
+ {
+ MethodName: "ListServices",
+ Handler: _Control_ListServices_Handler,
+ },
+ {
+ MethodName: "CreateService",
+ Handler: _Control_CreateService_Handler,
+ },
+ {
+ MethodName: "UpdateService",
+ Handler: _Control_UpdateService_Handler,
+ },
+ {
+ MethodName: "RemoveService",
+ Handler: _Control_RemoveService_Handler,
+ },
+ {
+ MethodName: "GetNetwork",
+ Handler: _Control_GetNetwork_Handler,
+ },
+ {
+ MethodName: "ListNetworks",
+ Handler: _Control_ListNetworks_Handler,
+ },
+ {
+ MethodName: "CreateNetwork",
+ Handler: _Control_CreateNetwork_Handler,
+ },
+ {
+ MethodName: "RemoveNetwork",
+ Handler: _Control_RemoveNetwork_Handler,
+ },
+ {
+ MethodName: "GetCluster",
+ Handler: _Control_GetCluster_Handler,
+ },
+ {
+ MethodName: "ListClusters",
+ Handler: _Control_ListClusters_Handler,
+ },
+ {
+ MethodName: "UpdateCluster",
+ Handler: _Control_UpdateCluster_Handler,
+ },
+ {
+ MethodName: "GetSecret",
+ Handler: _Control_GetSecret_Handler,
+ },
+ {
+ MethodName: "UpdateSecret",
+ Handler: _Control_UpdateSecret_Handler,
+ },
+ {
+ MethodName: "ListSecrets",
+ Handler: _Control_ListSecrets_Handler,
+ },
+ {
+ MethodName: "CreateSecret",
+ Handler: _Control_CreateSecret_Handler,
+ },
+ {
+ MethodName: "RemoveSecret",
+ Handler: _Control_RemoveSecret_Handler,
+ },
+ {
+ MethodName: "GetConfig",
+ Handler: _Control_GetConfig_Handler,
+ },
+ {
+ MethodName: "UpdateConfig",
+ Handler: _Control_UpdateConfig_Handler,
+ },
+ {
+ MethodName: "ListConfigs",
+ Handler: _Control_ListConfigs_Handler,
+ },
+ {
+ MethodName: "CreateConfig",
+ Handler: _Control_CreateConfig_Handler,
+ },
+ {
+ MethodName: "RemoveConfig",
+ Handler: _Control_RemoveConfig_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "control.proto",
+}
+
+func (m *GetNodeRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetNodeRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.NodeID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.NodeID)))
+ i += copy(dAtA[i:], m.NodeID)
+ }
+ return i, nil
+}
+
+func (m *GetNodeResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetNodeResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Node != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Node.Size()))
+ n1, err := m.Node.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ }
+ return i, nil
+}
+
+func (m *ListNodesRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListNodesRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Filters != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Filters.Size()))
+ n2, err := m.Filters.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ }
+ return i, nil
+}
+
+func (m *ListNodesRequest_Filters) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListNodesRequest_Filters) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x1a
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ i = encodeVarintControl(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.Memberships) > 0 {
+ for _, num := range m.Memberships {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(num))
+ }
+ }
+ if len(m.Roles) > 0 {
+ for _, num := range m.Roles {
+ dAtA[i] = 0x28
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(num))
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ dAtA[i] = 0x32
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func (m *ListNodesResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListNodesResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Nodes) > 0 {
+ for _, msg := range m.Nodes {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *UpdateNodeRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateNodeRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.NodeID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.NodeID)))
+ i += copy(dAtA[i:], m.NodeID)
+ }
+ if m.NodeVersion != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.NodeVersion.Size()))
+ n3, err := m.NodeVersion.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ }
+ if m.Spec != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Spec.Size()))
+ n4, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n4
+ }
+ return i, nil
+}
+
+func (m *UpdateNodeResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateNodeResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Node != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Node.Size()))
+ n5, err := m.Node.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n5
+ }
+ return i, nil
+}
+
+func (m *RemoveNodeRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveNodeRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.NodeID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.NodeID)))
+ i += copy(dAtA[i:], m.NodeID)
+ }
+ if m.Force {
+ dAtA[i] = 0x10
+ i++
+ if m.Force {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ return i, nil
+}
+
+func (m *RemoveNodeResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveNodeResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *GetTaskRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetTaskRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.TaskID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.TaskID)))
+ i += copy(dAtA[i:], m.TaskID)
+ }
+ return i, nil
+}
+
+func (m *GetTaskResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetTaskResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Task != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Task.Size()))
+ n6, err := m.Task.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n6
+ }
+ return i, nil
+}
+
+func (m *RemoveTaskRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveTaskRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.TaskID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.TaskID)))
+ i += copy(dAtA[i:], m.TaskID)
+ }
+ return i, nil
+}
+
+func (m *RemoveTaskResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveTaskResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *ListTasksRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListTasksRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Filters != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Filters.Size()))
+ n7, err := m.Filters.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n7
+ }
+ return i, nil
+}
+
+func (m *ListTasksRequest_Filters) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListTasksRequest_Filters) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x1a
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ i = encodeVarintControl(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.ServiceIDs) > 0 {
+ for _, s := range m.ServiceIDs {
+ dAtA[i] = 0x22
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.NodeIDs) > 0 {
+ for _, s := range m.NodeIDs {
+ dAtA[i] = 0x2a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.DesiredStates) > 0 {
+ for _, num := range m.DesiredStates {
+ dAtA[i] = 0x30
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(num))
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ dAtA[i] = 0x3a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if m.UpToDate {
+ dAtA[i] = 0x40
+ i++
+ if m.UpToDate {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if len(m.Runtimes) > 0 {
+ for _, s := range m.Runtimes {
+ dAtA[i] = 0x4a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func (m *ListTasksResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListTasksResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Tasks) > 0 {
+ for _, msg := range m.Tasks {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *CreateServiceRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CreateServiceRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Spec != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Spec.Size()))
+ n8, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n8
+ }
+ return i, nil
+}
+
+func (m *CreateServiceResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CreateServiceResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Service != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Service.Size()))
+ n9, err := m.Service.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n9
+ }
+ return i, nil
+}
+
+func (m *GetServiceRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetServiceRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ServiceID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.ServiceID)))
+ i += copy(dAtA[i:], m.ServiceID)
+ }
+ if m.InsertDefaults {
+ dAtA[i] = 0x10
+ i++
+ if m.InsertDefaults {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ return i, nil
+}
+
+func (m *GetServiceResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetServiceResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Service != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Service.Size()))
+ n10, err := m.Service.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n10
+ }
+ return i, nil
+}
+
+func (m *UpdateServiceRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateServiceRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ServiceID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.ServiceID)))
+ i += copy(dAtA[i:], m.ServiceID)
+ }
+ if m.ServiceVersion != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.ServiceVersion.Size()))
+ n11, err := m.ServiceVersion.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n11
+ }
+ if m.Spec != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Spec.Size()))
+ n12, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n12
+ }
+ if m.Rollback != 0 {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Rollback))
+ }
+ return i, nil
+}
+
+func (m *UpdateServiceResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateServiceResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Service != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Service.Size()))
+ n13, err := m.Service.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n13
+ }
+ return i, nil
+}
+
+func (m *RemoveServiceRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveServiceRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ServiceID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.ServiceID)))
+ i += copy(dAtA[i:], m.ServiceID)
+ }
+ return i, nil
+}
+
+func (m *RemoveServiceResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveServiceResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *ListServicesRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListServicesRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Filters != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Filters.Size()))
+ n14, err := m.Filters.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n14
+ }
+ return i, nil
+}
+
+func (m *ListServicesRequest_Filters) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListServicesRequest_Filters) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x1a
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ i = encodeVarintControl(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ dAtA[i] = 0x22
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Runtimes) > 0 {
+ for _, s := range m.Runtimes {
+ dAtA[i] = 0x2a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func (m *ListServicesResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListServicesResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Services) > 0 {
+ for _, msg := range m.Services {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *CreateNetworkRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CreateNetworkRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Spec != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Spec.Size()))
+ n15, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n15
+ }
+ return i, nil
+}
+
+func (m *CreateNetworkResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CreateNetworkResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Network != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Network.Size()))
+ n16, err := m.Network.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n16
+ }
+ return i, nil
+}
+
+func (m *GetNetworkRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetNetworkRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Name) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.Name)))
+ i += copy(dAtA[i:], m.Name)
+ }
+ if len(m.NetworkID) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.NetworkID)))
+ i += copy(dAtA[i:], m.NetworkID)
+ }
+ return i, nil
+}
+
+func (m *GetNetworkResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetNetworkResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Network != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Network.Size()))
+ n17, err := m.Network.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n17
+ }
+ return i, nil
+}
+
+func (m *RemoveNetworkRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveNetworkRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Name) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.Name)))
+ i += copy(dAtA[i:], m.Name)
+ }
+ if len(m.NetworkID) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.NetworkID)))
+ i += copy(dAtA[i:], m.NetworkID)
+ }
+ return i, nil
+}
+
+func (m *RemoveNetworkResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveNetworkResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *ListNetworksRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListNetworksRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Filters != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Filters.Size()))
+ n18, err := m.Filters.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n18
+ }
+ return i, nil
+}
+
+func (m *ListNetworksRequest_Filters) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListNetworksRequest_Filters) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x1a
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ i = encodeVarintControl(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ dAtA[i] = 0x22
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func (m *ListNetworksResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListNetworksResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Networks) > 0 {
+ for _, msg := range m.Networks {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *GetClusterRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetClusterRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ClusterID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.ClusterID)))
+ i += copy(dAtA[i:], m.ClusterID)
+ }
+ return i, nil
+}
+
+func (m *GetClusterResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetClusterResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Cluster != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Cluster.Size()))
+ n19, err := m.Cluster.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n19
+ }
+ return i, nil
+}
+
+func (m *ListClustersRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListClustersRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Filters != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Filters.Size()))
+ n20, err := m.Filters.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n20
+ }
+ return i, nil
+}
+
+func (m *ListClustersRequest_Filters) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListClustersRequest_Filters) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x1a
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ i = encodeVarintControl(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ dAtA[i] = 0x22
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func (m *ListClustersResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListClustersResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Clusters) > 0 {
+ for _, msg := range m.Clusters {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *KeyRotation) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *KeyRotation) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.WorkerJoinToken {
+ dAtA[i] = 0x8
+ i++
+ if m.WorkerJoinToken {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.ManagerJoinToken {
+ dAtA[i] = 0x10
+ i++
+ if m.ManagerJoinToken {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.ManagerUnlockKey {
+ dAtA[i] = 0x18
+ i++
+ if m.ManagerUnlockKey {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ return i, nil
+}
+
+func (m *UpdateClusterRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateClusterRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ClusterID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.ClusterID)))
+ i += copy(dAtA[i:], m.ClusterID)
+ }
+ if m.ClusterVersion != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.ClusterVersion.Size()))
+ n21, err := m.ClusterVersion.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n21
+ }
+ if m.Spec != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Spec.Size()))
+ n22, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n22
+ }
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Rotation.Size()))
+ n23, err := m.Rotation.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n23
+ return i, nil
+}
+
+func (m *UpdateClusterResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateClusterResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Cluster != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Cluster.Size()))
+ n24, err := m.Cluster.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n24
+ }
+ return i, nil
+}
+
+func (m *GetSecretRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetSecretRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SecretID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.SecretID)))
+ i += copy(dAtA[i:], m.SecretID)
+ }
+ return i, nil
+}
+
+func (m *GetSecretResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetSecretResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Secret != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Secret.Size()))
+ n25, err := m.Secret.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n25
+ }
+ return i, nil
+}
+
+func (m *UpdateSecretRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateSecretRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SecretID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.SecretID)))
+ i += copy(dAtA[i:], m.SecretID)
+ }
+ if m.SecretVersion != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.SecretVersion.Size()))
+ n26, err := m.SecretVersion.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n26
+ }
+ if m.Spec != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Spec.Size()))
+ n27, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n27
+ }
+ return i, nil
+}
+
+func (m *UpdateSecretResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateSecretResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Secret != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Secret.Size()))
+ n28, err := m.Secret.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n28
+ }
+ return i, nil
+}
+
+func (m *ListSecretsRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListSecretsRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Filters != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Filters.Size()))
+ n29, err := m.Filters.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n29
+ }
+ return i, nil
+}
+
+func (m *ListSecretsRequest_Filters) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListSecretsRequest_Filters) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x1a
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ i = encodeVarintControl(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ dAtA[i] = 0x22
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func (m *ListSecretsResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListSecretsResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Secrets) > 0 {
+ for _, msg := range m.Secrets {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *CreateSecretRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CreateSecretRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Spec != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Spec.Size()))
+ n30, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n30
+ }
+ return i, nil
+}
+
+func (m *CreateSecretResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CreateSecretResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Secret != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Secret.Size()))
+ n31, err := m.Secret.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n31
+ }
+ return i, nil
+}
+
+func (m *RemoveSecretRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveSecretRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SecretID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.SecretID)))
+ i += copy(dAtA[i:], m.SecretID)
+ }
+ return i, nil
+}
+
+func (m *RemoveSecretResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveSecretResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *GetConfigRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetConfigRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ConfigID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.ConfigID)))
+ i += copy(dAtA[i:], m.ConfigID)
+ }
+ return i, nil
+}
+
+func (m *GetConfigResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GetConfigResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Config != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Config.Size()))
+ n32, err := m.Config.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n32
+ }
+ return i, nil
+}
+
+func (m *UpdateConfigRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateConfigRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ConfigID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.ConfigID)))
+ i += copy(dAtA[i:], m.ConfigID)
+ }
+ if m.ConfigVersion != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.ConfigVersion.Size()))
+ n33, err := m.ConfigVersion.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n33
+ }
+ if m.Spec != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Spec.Size()))
+ n34, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n34
+ }
+ return i, nil
+}
+
+func (m *UpdateConfigResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateConfigResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Config != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Config.Size()))
+ n35, err := m.Config.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n35
+ }
+ return i, nil
+}
+
+func (m *ListConfigsRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListConfigsRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Filters != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Filters.Size()))
+ n36, err := m.Filters.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n36
+ }
+ return i, nil
+}
+
+func (m *ListConfigsRequest_Filters) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListConfigsRequest_Filters) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x1a
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ i = encodeVarintControl(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ dAtA[i] = 0x22
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func (m *ListConfigsResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListConfigsResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Configs) > 0 {
+ for _, msg := range m.Configs {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *CreateConfigRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CreateConfigRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Spec != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Spec.Size()))
+ n37, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n37
+ }
+ return i, nil
+}
+
+func (m *CreateConfigResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CreateConfigResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Config != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(m.Config.Size()))
+ n38, err := m.Config.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n38
+ }
+ return i, nil
+}
+
+func (m *RemoveConfigRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveConfigRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ConfigID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintControl(dAtA, i, uint64(len(m.ConfigID)))
+ i += copy(dAtA[i:], m.ConfigID)
+ }
+ return i, nil
+}
+
+func (m *RemoveConfigResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RemoveConfigResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func encodeFixed64Control(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Control(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintControl(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+type raftProxyControlServer struct {
+ local ControlServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyControlServer(local ControlServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) ControlServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyControlServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyControlServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyControlServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+func (p *raftProxyControlServer) GetNode(ctx context.Context, r *GetNodeRequest) (*GetNodeResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.GetNode(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).GetNode(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.GetNode(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).GetNode(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) ListNodes(ctx context.Context, r *ListNodesRequest) (*ListNodesResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.ListNodes(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).ListNodes(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.ListNodes(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).ListNodes(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) UpdateNode(ctx context.Context, r *UpdateNodeRequest) (*UpdateNodeResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.UpdateNode(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).UpdateNode(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.UpdateNode(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).UpdateNode(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) RemoveNode(ctx context.Context, r *RemoveNodeRequest) (*RemoveNodeResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.RemoveNode(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).RemoveNode(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.RemoveNode(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).RemoveNode(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) GetTask(ctx context.Context, r *GetTaskRequest) (*GetTaskResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.GetTask(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).GetTask(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.GetTask(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).GetTask(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) ListTasks(ctx context.Context, r *ListTasksRequest) (*ListTasksResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.ListTasks(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).ListTasks(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.ListTasks(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).ListTasks(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) RemoveTask(ctx context.Context, r *RemoveTaskRequest) (*RemoveTaskResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.RemoveTask(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).RemoveTask(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.RemoveTask(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).RemoveTask(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) GetService(ctx context.Context, r *GetServiceRequest) (*GetServiceResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.GetService(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).GetService(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.GetService(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).GetService(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) ListServices(ctx context.Context, r *ListServicesRequest) (*ListServicesResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.ListServices(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).ListServices(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.ListServices(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).ListServices(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) CreateService(ctx context.Context, r *CreateServiceRequest) (*CreateServiceResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.CreateService(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).CreateService(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.CreateService(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).CreateService(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) UpdateService(ctx context.Context, r *UpdateServiceRequest) (*UpdateServiceResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.UpdateService(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).UpdateService(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.UpdateService(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).UpdateService(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) RemoveService(ctx context.Context, r *RemoveServiceRequest) (*RemoveServiceResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.RemoveService(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).RemoveService(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.RemoveService(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).RemoveService(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) GetNetwork(ctx context.Context, r *GetNetworkRequest) (*GetNetworkResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.GetNetwork(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).GetNetwork(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.GetNetwork(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).GetNetwork(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) ListNetworks(ctx context.Context, r *ListNetworksRequest) (*ListNetworksResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.ListNetworks(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).ListNetworks(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.ListNetworks(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).ListNetworks(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) CreateNetwork(ctx context.Context, r *CreateNetworkRequest) (*CreateNetworkResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.CreateNetwork(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).CreateNetwork(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.CreateNetwork(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).CreateNetwork(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) RemoveNetwork(ctx context.Context, r *RemoveNetworkRequest) (*RemoveNetworkResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.RemoveNetwork(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).RemoveNetwork(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.RemoveNetwork(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).RemoveNetwork(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) GetCluster(ctx context.Context, r *GetClusterRequest) (*GetClusterResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.GetCluster(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).GetCluster(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.GetCluster(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).GetCluster(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) ListClusters(ctx context.Context, r *ListClustersRequest) (*ListClustersResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.ListClusters(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).ListClusters(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.ListClusters(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).ListClusters(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) UpdateCluster(ctx context.Context, r *UpdateClusterRequest) (*UpdateClusterResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.UpdateCluster(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).UpdateCluster(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.UpdateCluster(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).UpdateCluster(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) GetSecret(ctx context.Context, r *GetSecretRequest) (*GetSecretResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.GetSecret(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).GetSecret(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.GetSecret(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).GetSecret(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) UpdateSecret(ctx context.Context, r *UpdateSecretRequest) (*UpdateSecretResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.UpdateSecret(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).UpdateSecret(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.UpdateSecret(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).UpdateSecret(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) ListSecrets(ctx context.Context, r *ListSecretsRequest) (*ListSecretsResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.ListSecrets(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).ListSecrets(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.ListSecrets(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).ListSecrets(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) CreateSecret(ctx context.Context, r *CreateSecretRequest) (*CreateSecretResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.CreateSecret(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).CreateSecret(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.CreateSecret(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).CreateSecret(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) RemoveSecret(ctx context.Context, r *RemoveSecretRequest) (*RemoveSecretResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.RemoveSecret(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).RemoveSecret(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.RemoveSecret(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).RemoveSecret(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) GetConfig(ctx context.Context, r *GetConfigRequest) (*GetConfigResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.GetConfig(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).GetConfig(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.GetConfig(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).GetConfig(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) UpdateConfig(ctx context.Context, r *UpdateConfigRequest) (*UpdateConfigResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.UpdateConfig(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).UpdateConfig(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.UpdateConfig(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).UpdateConfig(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) ListConfigs(ctx context.Context, r *ListConfigsRequest) (*ListConfigsResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.ListConfigs(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).ListConfigs(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.ListConfigs(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).ListConfigs(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) CreateConfig(ctx context.Context, r *CreateConfigRequest) (*CreateConfigResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.CreateConfig(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).CreateConfig(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.CreateConfig(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).CreateConfig(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyControlServer) RemoveConfig(ctx context.Context, r *RemoveConfigRequest) (*RemoveConfigResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.RemoveConfig(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewControlClient(conn).RemoveConfig(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.RemoveConfig(ctx, r)
+ }
+ return nil, err
+ }
+ return NewControlClient(conn).RemoveConfig(modCtx, r)
+ }
+ return resp, err
+}
+
+func (m *GetNodeRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.NodeID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *GetNodeResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Node != nil {
+ l = m.Node.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListNodesRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Filters != nil {
+ l = m.Filters.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListNodesRequest_Filters) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ n += mapEntrySize + 1 + sovControl(uint64(mapEntrySize))
+ }
+ }
+ if len(m.Memberships) > 0 {
+ for _, e := range m.Memberships {
+ n += 1 + sovControl(uint64(e))
+ }
+ }
+ if len(m.Roles) > 0 {
+ for _, e := range m.Roles {
+ n += 1 + sovControl(uint64(e))
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *ListNodesResponse) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Nodes) > 0 {
+ for _, e := range m.Nodes {
+ l = e.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *UpdateNodeRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.NodeID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.NodeVersion != nil {
+ l = m.NodeVersion.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.Spec != nil {
+ l = m.Spec.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *UpdateNodeResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Node != nil {
+ l = m.Node.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveNodeRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.NodeID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.Force {
+ n += 2
+ }
+ return n
+}
+
+func (m *RemoveNodeResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *GetTaskRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.TaskID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *GetTaskResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Task != nil {
+ l = m.Task.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveTaskRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.TaskID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveTaskResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *ListTasksRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Filters != nil {
+ l = m.Filters.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListTasksRequest_Filters) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ n += mapEntrySize + 1 + sovControl(uint64(mapEntrySize))
+ }
+ }
+ if len(m.ServiceIDs) > 0 {
+ for _, s := range m.ServiceIDs {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.NodeIDs) > 0 {
+ for _, s := range m.NodeIDs {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.DesiredStates) > 0 {
+ for _, e := range m.DesiredStates {
+ n += 1 + sovControl(uint64(e))
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if m.UpToDate {
+ n += 2
+ }
+ if len(m.Runtimes) > 0 {
+ for _, s := range m.Runtimes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *ListTasksResponse) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Tasks) > 0 {
+ for _, e := range m.Tasks {
+ l = e.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *CreateServiceRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Spec != nil {
+ l = m.Spec.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *CreateServiceResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Service != nil {
+ l = m.Service.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *GetServiceRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ServiceID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.InsertDefaults {
+ n += 2
+ }
+ return n
+}
+
+func (m *GetServiceResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Service != nil {
+ l = m.Service.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *UpdateServiceRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ServiceID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.ServiceVersion != nil {
+ l = m.ServiceVersion.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.Spec != nil {
+ l = m.Spec.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.Rollback != 0 {
+ n += 1 + sovControl(uint64(m.Rollback))
+ }
+ return n
+}
+
+func (m *UpdateServiceResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Service != nil {
+ l = m.Service.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveServiceRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ServiceID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveServiceResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *ListServicesRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Filters != nil {
+ l = m.Filters.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListServicesRequest_Filters) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ n += mapEntrySize + 1 + sovControl(uint64(mapEntrySize))
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.Runtimes) > 0 {
+ for _, s := range m.Runtimes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *ListServicesResponse) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Services) > 0 {
+ for _, e := range m.Services {
+ l = e.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *CreateNetworkRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Spec != nil {
+ l = m.Spec.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *CreateNetworkResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Network != nil {
+ l = m.Network.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *GetNetworkRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Name)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ l = len(m.NetworkID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *GetNetworkResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Network != nil {
+ l = m.Network.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveNetworkRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Name)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ l = len(m.NetworkID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveNetworkResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *ListNetworksRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Filters != nil {
+ l = m.Filters.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListNetworksRequest_Filters) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ n += mapEntrySize + 1 + sovControl(uint64(mapEntrySize))
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *ListNetworksResponse) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Networks) > 0 {
+ for _, e := range m.Networks {
+ l = e.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *GetClusterRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ClusterID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *GetClusterResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Cluster != nil {
+ l = m.Cluster.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListClustersRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Filters != nil {
+ l = m.Filters.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListClustersRequest_Filters) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ n += mapEntrySize + 1 + sovControl(uint64(mapEntrySize))
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *ListClustersResponse) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Clusters) > 0 {
+ for _, e := range m.Clusters {
+ l = e.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *KeyRotation) Size() (n int) {
+ var l int
+ _ = l
+ if m.WorkerJoinToken {
+ n += 2
+ }
+ if m.ManagerJoinToken {
+ n += 2
+ }
+ if m.ManagerUnlockKey {
+ n += 2
+ }
+ return n
+}
+
+func (m *UpdateClusterRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ClusterID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.ClusterVersion != nil {
+ l = m.ClusterVersion.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.Spec != nil {
+ l = m.Spec.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ l = m.Rotation.Size()
+ n += 1 + l + sovControl(uint64(l))
+ return n
+}
+
+func (m *UpdateClusterResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Cluster != nil {
+ l = m.Cluster.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *GetSecretRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SecretID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *GetSecretResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Secret != nil {
+ l = m.Secret.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *UpdateSecretRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SecretID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.SecretVersion != nil {
+ l = m.SecretVersion.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.Spec != nil {
+ l = m.Spec.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *UpdateSecretResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Secret != nil {
+ l = m.Secret.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListSecretsRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Filters != nil {
+ l = m.Filters.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListSecretsRequest_Filters) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ n += mapEntrySize + 1 + sovControl(uint64(mapEntrySize))
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *ListSecretsResponse) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Secrets) > 0 {
+ for _, e := range m.Secrets {
+ l = e.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *CreateSecretRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Spec != nil {
+ l = m.Spec.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *CreateSecretResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Secret != nil {
+ l = m.Secret.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveSecretRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SecretID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveSecretResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *GetConfigRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ConfigID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *GetConfigResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Config != nil {
+ l = m.Config.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *UpdateConfigRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ConfigID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.ConfigVersion != nil {
+ l = m.ConfigVersion.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ if m.Spec != nil {
+ l = m.Spec.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *UpdateConfigResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Config != nil {
+ l = m.Config.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListConfigsRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Filters != nil {
+ l = m.Filters.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *ListConfigsRequest_Filters) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Names) > 0 {
+ for _, s := range m.Names {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.IDPrefixes) > 0 {
+ for _, s := range m.IDPrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovControl(uint64(len(k))) + 1 + len(v) + sovControl(uint64(len(v)))
+ n += mapEntrySize + 1 + sovControl(uint64(mapEntrySize))
+ }
+ }
+ if len(m.NamePrefixes) > 0 {
+ for _, s := range m.NamePrefixes {
+ l = len(s)
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *ListConfigsResponse) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Configs) > 0 {
+ for _, e := range m.Configs {
+ l = e.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *CreateConfigRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Spec != nil {
+ l = m.Spec.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *CreateConfigResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Config != nil {
+ l = m.Config.Size()
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveConfigRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ConfigID)
+ if l > 0 {
+ n += 1 + l + sovControl(uint64(l))
+ }
+ return n
+}
+
+func (m *RemoveConfigResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func sovControl(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozControl(x uint64) (n int) {
+ return sovControl(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *GetNodeRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetNodeRequest{`,
+ `NodeID:` + fmt.Sprintf("%v", this.NodeID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetNodeResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetNodeResponse{`,
+ `Node:` + strings.Replace(fmt.Sprintf("%v", this.Node), "Node", "Node", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListNodesRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListNodesRequest{`,
+ `Filters:` + strings.Replace(fmt.Sprintf("%v", this.Filters), "ListNodesRequest_Filters", "ListNodesRequest_Filters", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListNodesRequest_Filters) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&ListNodesRequest_Filters{`,
+ `Names:` + fmt.Sprintf("%v", this.Names) + `,`,
+ `IDPrefixes:` + fmt.Sprintf("%v", this.IDPrefixes) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `Memberships:` + fmt.Sprintf("%v", this.Memberships) + `,`,
+ `Roles:` + fmt.Sprintf("%v", this.Roles) + `,`,
+ `NamePrefixes:` + fmt.Sprintf("%v", this.NamePrefixes) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListNodesResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListNodesResponse{`,
+ `Nodes:` + strings.Replace(fmt.Sprintf("%v", this.Nodes), "Node", "Node", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateNodeRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateNodeRequest{`,
+ `NodeID:` + fmt.Sprintf("%v", this.NodeID) + `,`,
+ `NodeVersion:` + strings.Replace(fmt.Sprintf("%v", this.NodeVersion), "Version", "Version", 1) + `,`,
+ `Spec:` + strings.Replace(fmt.Sprintf("%v", this.Spec), "NodeSpec", "NodeSpec", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateNodeResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateNodeResponse{`,
+ `Node:` + strings.Replace(fmt.Sprintf("%v", this.Node), "Node", "Node", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveNodeRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveNodeRequest{`,
+ `NodeID:` + fmt.Sprintf("%v", this.NodeID) + `,`,
+ `Force:` + fmt.Sprintf("%v", this.Force) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveNodeResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveNodeResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetTaskRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetTaskRequest{`,
+ `TaskID:` + fmt.Sprintf("%v", this.TaskID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetTaskResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetTaskResponse{`,
+ `Task:` + strings.Replace(fmt.Sprintf("%v", this.Task), "Task", "Task", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveTaskRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveTaskRequest{`,
+ `TaskID:` + fmt.Sprintf("%v", this.TaskID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveTaskResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveTaskResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListTasksRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListTasksRequest{`,
+ `Filters:` + strings.Replace(fmt.Sprintf("%v", this.Filters), "ListTasksRequest_Filters", "ListTasksRequest_Filters", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListTasksRequest_Filters) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&ListTasksRequest_Filters{`,
+ `Names:` + fmt.Sprintf("%v", this.Names) + `,`,
+ `IDPrefixes:` + fmt.Sprintf("%v", this.IDPrefixes) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `ServiceIDs:` + fmt.Sprintf("%v", this.ServiceIDs) + `,`,
+ `NodeIDs:` + fmt.Sprintf("%v", this.NodeIDs) + `,`,
+ `DesiredStates:` + fmt.Sprintf("%v", this.DesiredStates) + `,`,
+ `NamePrefixes:` + fmt.Sprintf("%v", this.NamePrefixes) + `,`,
+ `UpToDate:` + fmt.Sprintf("%v", this.UpToDate) + `,`,
+ `Runtimes:` + fmt.Sprintf("%v", this.Runtimes) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListTasksResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListTasksResponse{`,
+ `Tasks:` + strings.Replace(fmt.Sprintf("%v", this.Tasks), "Task", "Task", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CreateServiceRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CreateServiceRequest{`,
+ `Spec:` + strings.Replace(fmt.Sprintf("%v", this.Spec), "ServiceSpec", "ServiceSpec", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CreateServiceResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CreateServiceResponse{`,
+ `Service:` + strings.Replace(fmt.Sprintf("%v", this.Service), "Service", "Service", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetServiceRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetServiceRequest{`,
+ `ServiceID:` + fmt.Sprintf("%v", this.ServiceID) + `,`,
+ `InsertDefaults:` + fmt.Sprintf("%v", this.InsertDefaults) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetServiceResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetServiceResponse{`,
+ `Service:` + strings.Replace(fmt.Sprintf("%v", this.Service), "Service", "Service", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateServiceRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateServiceRequest{`,
+ `ServiceID:` + fmt.Sprintf("%v", this.ServiceID) + `,`,
+ `ServiceVersion:` + strings.Replace(fmt.Sprintf("%v", this.ServiceVersion), "Version", "Version", 1) + `,`,
+ `Spec:` + strings.Replace(fmt.Sprintf("%v", this.Spec), "ServiceSpec", "ServiceSpec", 1) + `,`,
+ `Rollback:` + fmt.Sprintf("%v", this.Rollback) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateServiceResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateServiceResponse{`,
+ `Service:` + strings.Replace(fmt.Sprintf("%v", this.Service), "Service", "Service", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveServiceRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveServiceRequest{`,
+ `ServiceID:` + fmt.Sprintf("%v", this.ServiceID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveServiceResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveServiceResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListServicesRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListServicesRequest{`,
+ `Filters:` + strings.Replace(fmt.Sprintf("%v", this.Filters), "ListServicesRequest_Filters", "ListServicesRequest_Filters", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListServicesRequest_Filters) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&ListServicesRequest_Filters{`,
+ `Names:` + fmt.Sprintf("%v", this.Names) + `,`,
+ `IDPrefixes:` + fmt.Sprintf("%v", this.IDPrefixes) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `NamePrefixes:` + fmt.Sprintf("%v", this.NamePrefixes) + `,`,
+ `Runtimes:` + fmt.Sprintf("%v", this.Runtimes) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListServicesResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListServicesResponse{`,
+ `Services:` + strings.Replace(fmt.Sprintf("%v", this.Services), "Service", "Service", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CreateNetworkRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CreateNetworkRequest{`,
+ `Spec:` + strings.Replace(fmt.Sprintf("%v", this.Spec), "NetworkSpec", "NetworkSpec", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CreateNetworkResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CreateNetworkResponse{`,
+ `Network:` + strings.Replace(fmt.Sprintf("%v", this.Network), "Network", "Network", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetNetworkRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetNetworkRequest{`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `NetworkID:` + fmt.Sprintf("%v", this.NetworkID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetNetworkResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetNetworkResponse{`,
+ `Network:` + strings.Replace(fmt.Sprintf("%v", this.Network), "Network", "Network", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveNetworkRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveNetworkRequest{`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `NetworkID:` + fmt.Sprintf("%v", this.NetworkID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveNetworkResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveNetworkResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListNetworksRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListNetworksRequest{`,
+ `Filters:` + strings.Replace(fmt.Sprintf("%v", this.Filters), "ListNetworksRequest_Filters", "ListNetworksRequest_Filters", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListNetworksRequest_Filters) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&ListNetworksRequest_Filters{`,
+ `Names:` + fmt.Sprintf("%v", this.Names) + `,`,
+ `IDPrefixes:` + fmt.Sprintf("%v", this.IDPrefixes) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `NamePrefixes:` + fmt.Sprintf("%v", this.NamePrefixes) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListNetworksResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListNetworksResponse{`,
+ `Networks:` + strings.Replace(fmt.Sprintf("%v", this.Networks), "Network", "Network", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetClusterRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetClusterRequest{`,
+ `ClusterID:` + fmt.Sprintf("%v", this.ClusterID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetClusterResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetClusterResponse{`,
+ `Cluster:` + strings.Replace(fmt.Sprintf("%v", this.Cluster), "Cluster", "Cluster", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListClustersRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListClustersRequest{`,
+ `Filters:` + strings.Replace(fmt.Sprintf("%v", this.Filters), "ListClustersRequest_Filters", "ListClustersRequest_Filters", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListClustersRequest_Filters) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&ListClustersRequest_Filters{`,
+ `Names:` + fmt.Sprintf("%v", this.Names) + `,`,
+ `IDPrefixes:` + fmt.Sprintf("%v", this.IDPrefixes) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `NamePrefixes:` + fmt.Sprintf("%v", this.NamePrefixes) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListClustersResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListClustersResponse{`,
+ `Clusters:` + strings.Replace(fmt.Sprintf("%v", this.Clusters), "Cluster", "Cluster", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *KeyRotation) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&KeyRotation{`,
+ `WorkerJoinToken:` + fmt.Sprintf("%v", this.WorkerJoinToken) + `,`,
+ `ManagerJoinToken:` + fmt.Sprintf("%v", this.ManagerJoinToken) + `,`,
+ `ManagerUnlockKey:` + fmt.Sprintf("%v", this.ManagerUnlockKey) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateClusterRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateClusterRequest{`,
+ `ClusterID:` + fmt.Sprintf("%v", this.ClusterID) + `,`,
+ `ClusterVersion:` + strings.Replace(fmt.Sprintf("%v", this.ClusterVersion), "Version", "Version", 1) + `,`,
+ `Spec:` + strings.Replace(fmt.Sprintf("%v", this.Spec), "ClusterSpec", "ClusterSpec", 1) + `,`,
+ `Rotation:` + strings.Replace(strings.Replace(this.Rotation.String(), "KeyRotation", "KeyRotation", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateClusterResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateClusterResponse{`,
+ `Cluster:` + strings.Replace(fmt.Sprintf("%v", this.Cluster), "Cluster", "Cluster", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetSecretRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetSecretRequest{`,
+ `SecretID:` + fmt.Sprintf("%v", this.SecretID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetSecretResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetSecretResponse{`,
+ `Secret:` + strings.Replace(fmt.Sprintf("%v", this.Secret), "Secret", "Secret", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateSecretRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateSecretRequest{`,
+ `SecretID:` + fmt.Sprintf("%v", this.SecretID) + `,`,
+ `SecretVersion:` + strings.Replace(fmt.Sprintf("%v", this.SecretVersion), "Version", "Version", 1) + `,`,
+ `Spec:` + strings.Replace(fmt.Sprintf("%v", this.Spec), "SecretSpec", "SecretSpec", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateSecretResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateSecretResponse{`,
+ `Secret:` + strings.Replace(fmt.Sprintf("%v", this.Secret), "Secret", "Secret", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListSecretsRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListSecretsRequest{`,
+ `Filters:` + strings.Replace(fmt.Sprintf("%v", this.Filters), "ListSecretsRequest_Filters", "ListSecretsRequest_Filters", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListSecretsRequest_Filters) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&ListSecretsRequest_Filters{`,
+ `Names:` + fmt.Sprintf("%v", this.Names) + `,`,
+ `IDPrefixes:` + fmt.Sprintf("%v", this.IDPrefixes) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `NamePrefixes:` + fmt.Sprintf("%v", this.NamePrefixes) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListSecretsResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListSecretsResponse{`,
+ `Secrets:` + strings.Replace(fmt.Sprintf("%v", this.Secrets), "Secret", "Secret", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CreateSecretRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CreateSecretRequest{`,
+ `Spec:` + strings.Replace(fmt.Sprintf("%v", this.Spec), "SecretSpec", "SecretSpec", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CreateSecretResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CreateSecretResponse{`,
+ `Secret:` + strings.Replace(fmt.Sprintf("%v", this.Secret), "Secret", "Secret", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveSecretRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveSecretRequest{`,
+ `SecretID:` + fmt.Sprintf("%v", this.SecretID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveSecretResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveSecretResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetConfigRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetConfigRequest{`,
+ `ConfigID:` + fmt.Sprintf("%v", this.ConfigID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GetConfigResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GetConfigResponse{`,
+ `Config:` + strings.Replace(fmt.Sprintf("%v", this.Config), "Config", "Config", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateConfigRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateConfigRequest{`,
+ `ConfigID:` + fmt.Sprintf("%v", this.ConfigID) + `,`,
+ `ConfigVersion:` + strings.Replace(fmt.Sprintf("%v", this.ConfigVersion), "Version", "Version", 1) + `,`,
+ `Spec:` + strings.Replace(fmt.Sprintf("%v", this.Spec), "ConfigSpec", "ConfigSpec", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateConfigResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateConfigResponse{`,
+ `Config:` + strings.Replace(fmt.Sprintf("%v", this.Config), "Config", "Config", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListConfigsRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListConfigsRequest{`,
+ `Filters:` + strings.Replace(fmt.Sprintf("%v", this.Filters), "ListConfigsRequest_Filters", "ListConfigsRequest_Filters", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListConfigsRequest_Filters) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&ListConfigsRequest_Filters{`,
+ `Names:` + fmt.Sprintf("%v", this.Names) + `,`,
+ `IDPrefixes:` + fmt.Sprintf("%v", this.IDPrefixes) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `NamePrefixes:` + fmt.Sprintf("%v", this.NamePrefixes) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListConfigsResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListConfigsResponse{`,
+ `Configs:` + strings.Replace(fmt.Sprintf("%v", this.Configs), "Config", "Config", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CreateConfigRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CreateConfigRequest{`,
+ `Spec:` + strings.Replace(fmt.Sprintf("%v", this.Spec), "ConfigSpec", "ConfigSpec", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CreateConfigResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CreateConfigResponse{`,
+ `Config:` + strings.Replace(fmt.Sprintf("%v", this.Config), "Config", "Config", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveConfigRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveConfigRequest{`,
+ `ConfigID:` + fmt.Sprintf("%v", this.ConfigID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RemoveConfigResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RemoveConfigResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringControl(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *GetNodeRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetNodeRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetNodeRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetNodeResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetNodeResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetNodeResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Node", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Node == nil {
+ m.Node = &Node{}
+ }
+ if err := m.Node.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListNodesRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListNodesRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListNodesRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Filters", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Filters == nil {
+ m.Filters = &ListNodesRequest_Filters{}
+ }
+ if err := m.Filters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListNodesRequest_Filters) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Filters: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Filters: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Names", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Names = append(m.Names, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IDPrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IDPrefixes = append(m.IDPrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType == 0 {
+ var v NodeSpec_Membership
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (NodeSpec_Membership(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Memberships = append(m.Memberships, v)
+ } else if wireType == 2 {
+ var packedLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ packedLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if packedLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + packedLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ for iNdEx < postIndex {
+ var v NodeSpec_Membership
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (NodeSpec_Membership(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Memberships = append(m.Memberships, v)
+ }
+ } else {
+ return fmt.Errorf("proto: wrong wireType = %d for field Memberships", wireType)
+ }
+ case 5:
+ if wireType == 0 {
+ var v NodeRole
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (NodeRole(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Roles = append(m.Roles, v)
+ } else if wireType == 2 {
+ var packedLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ packedLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if packedLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + packedLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ for iNdEx < postIndex {
+ var v NodeRole
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (NodeRole(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Roles = append(m.Roles, v)
+ }
+ } else {
+ return fmt.Errorf("proto: wrong wireType = %d for field Roles", wireType)
+ }
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NamePrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NamePrefixes = append(m.NamePrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListNodesResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListNodesResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListNodesResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Nodes", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Nodes = append(m.Nodes, &Node{})
+ if err := m.Nodes[len(m.Nodes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateNodeRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateNodeRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateNodeRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeVersion", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.NodeVersion == nil {
+ m.NodeVersion = &Version{}
+ }
+ if err := m.NodeVersion.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Spec == nil {
+ m.Spec = &NodeSpec{}
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateNodeResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateNodeResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateNodeResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Node", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Node == nil {
+ m.Node = &Node{}
+ }
+ if err := m.Node.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveNodeRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveNodeRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveNodeRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Force", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Force = bool(v != 0)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveNodeResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveNodeResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveNodeResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetTaskRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetTaskRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetTaskRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TaskID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TaskID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetTaskResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetTaskResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetTaskResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Task", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Task == nil {
+ m.Task = &Task{}
+ }
+ if err := m.Task.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveTaskRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveTaskRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveTaskRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TaskID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TaskID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveTaskResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveTaskResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveTaskResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListTasksRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListTasksRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListTasksRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Filters", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Filters == nil {
+ m.Filters = &ListTasksRequest_Filters{}
+ }
+ if err := m.Filters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListTasksRequest_Filters) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Filters: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Filters: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Names", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Names = append(m.Names, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IDPrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IDPrefixes = append(m.IDPrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceIDs", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ServiceIDs = append(m.ServiceIDs, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeIDs", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeIDs = append(m.NodeIDs, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 6:
+ if wireType == 0 {
+ var v TaskState
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (TaskState(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.DesiredStates = append(m.DesiredStates, v)
+ } else if wireType == 2 {
+ var packedLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ packedLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if packedLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + packedLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ for iNdEx < postIndex {
+ var v TaskState
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (TaskState(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.DesiredStates = append(m.DesiredStates, v)
+ }
+ } else {
+ return fmt.Errorf("proto: wrong wireType = %d for field DesiredStates", wireType)
+ }
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NamePrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NamePrefixes = append(m.NamePrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 8:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field UpToDate", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.UpToDate = bool(v != 0)
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Runtimes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Runtimes = append(m.Runtimes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListTasksResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListTasksResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListTasksResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Tasks", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Tasks = append(m.Tasks, &Task{})
+ if err := m.Tasks[len(m.Tasks)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CreateServiceRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CreateServiceRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CreateServiceRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Spec == nil {
+ m.Spec = &ServiceSpec{}
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CreateServiceResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CreateServiceResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CreateServiceResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Service", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Service == nil {
+ m.Service = &Service{}
+ }
+ if err := m.Service.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetServiceRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetServiceRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetServiceRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ServiceID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field InsertDefaults", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.InsertDefaults = bool(v != 0)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetServiceResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetServiceResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetServiceResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Service", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Service == nil {
+ m.Service = &Service{}
+ }
+ if err := m.Service.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateServiceRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateServiceRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateServiceRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ServiceID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceVersion", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.ServiceVersion == nil {
+ m.ServiceVersion = &Version{}
+ }
+ if err := m.ServiceVersion.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Spec == nil {
+ m.Spec = &ServiceSpec{}
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Rollback", wireType)
+ }
+ m.Rollback = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Rollback |= (UpdateServiceRequest_Rollback(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateServiceResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateServiceResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateServiceResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Service", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Service == nil {
+ m.Service = &Service{}
+ }
+ if err := m.Service.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveServiceRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveServiceRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveServiceRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ServiceID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveServiceResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveServiceResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveServiceResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListServicesRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListServicesRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListServicesRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Filters", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Filters == nil {
+ m.Filters = &ListServicesRequest_Filters{}
+ }
+ if err := m.Filters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListServicesRequest_Filters) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Filters: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Filters: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Names", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Names = append(m.Names, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IDPrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IDPrefixes = append(m.IDPrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NamePrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NamePrefixes = append(m.NamePrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Runtimes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Runtimes = append(m.Runtimes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListServicesResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListServicesResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListServicesResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Services", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Services = append(m.Services, &Service{})
+ if err := m.Services[len(m.Services)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CreateNetworkRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CreateNetworkRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CreateNetworkRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Spec == nil {
+ m.Spec = &NetworkSpec{}
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CreateNetworkResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CreateNetworkResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CreateNetworkResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Network", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Network == nil {
+ m.Network = &Network{}
+ }
+ if err := m.Network.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetNetworkRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetNetworkRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetNetworkRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Name = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NetworkID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NetworkID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetNetworkResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetNetworkResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetNetworkResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Network", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Network == nil {
+ m.Network = &Network{}
+ }
+ if err := m.Network.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveNetworkRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveNetworkRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveNetworkRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Name = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NetworkID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NetworkID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveNetworkResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveNetworkResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveNetworkResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListNetworksRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListNetworksRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListNetworksRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Filters", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Filters == nil {
+ m.Filters = &ListNetworksRequest_Filters{}
+ }
+ if err := m.Filters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListNetworksRequest_Filters) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Filters: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Filters: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Names", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Names = append(m.Names, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IDPrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IDPrefixes = append(m.IDPrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NamePrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NamePrefixes = append(m.NamePrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListNetworksResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListNetworksResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListNetworksResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Networks", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Networks = append(m.Networks, &Network{})
+ if err := m.Networks[len(m.Networks)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetClusterRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetClusterRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetClusterRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ClusterID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ClusterID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetClusterResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetClusterResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetClusterResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Cluster", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Cluster == nil {
+ m.Cluster = &Cluster{}
+ }
+ if err := m.Cluster.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListClustersRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListClustersRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListClustersRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Filters", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Filters == nil {
+ m.Filters = &ListClustersRequest_Filters{}
+ }
+ if err := m.Filters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListClustersRequest_Filters) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Filters: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Filters: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Names", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Names = append(m.Names, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IDPrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IDPrefixes = append(m.IDPrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NamePrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NamePrefixes = append(m.NamePrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListClustersResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListClustersResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListClustersResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Clusters", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Clusters = append(m.Clusters, &Cluster{})
+ if err := m.Clusters[len(m.Clusters)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *KeyRotation) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: KeyRotation: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: KeyRotation: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field WorkerJoinToken", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.WorkerJoinToken = bool(v != 0)
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ManagerJoinToken", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.ManagerJoinToken = bool(v != 0)
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ManagerUnlockKey", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.ManagerUnlockKey = bool(v != 0)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateClusterRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateClusterRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateClusterRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ClusterID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ClusterID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ClusterVersion", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.ClusterVersion == nil {
+ m.ClusterVersion = &Version{}
+ }
+ if err := m.ClusterVersion.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Spec == nil {
+ m.Spec = &ClusterSpec{}
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Rotation", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Rotation.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateClusterResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateClusterResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateClusterResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Cluster", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Cluster == nil {
+ m.Cluster = &Cluster{}
+ }
+ if err := m.Cluster.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetSecretRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetSecretRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetSecretRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SecretID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SecretID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetSecretResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetSecretResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetSecretResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Secret", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Secret == nil {
+ m.Secret = &Secret{}
+ }
+ if err := m.Secret.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateSecretRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateSecretRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateSecretRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SecretID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SecretID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SecretVersion", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.SecretVersion == nil {
+ m.SecretVersion = &Version{}
+ }
+ if err := m.SecretVersion.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Spec == nil {
+ m.Spec = &SecretSpec{}
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateSecretResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateSecretResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateSecretResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Secret", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Secret == nil {
+ m.Secret = &Secret{}
+ }
+ if err := m.Secret.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListSecretsRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListSecretsRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListSecretsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Filters", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Filters == nil {
+ m.Filters = &ListSecretsRequest_Filters{}
+ }
+ if err := m.Filters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListSecretsRequest_Filters) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Filters: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Filters: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Names", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Names = append(m.Names, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IDPrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IDPrefixes = append(m.IDPrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NamePrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NamePrefixes = append(m.NamePrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListSecretsResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListSecretsResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListSecretsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Secrets", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Secrets = append(m.Secrets, &Secret{})
+ if err := m.Secrets[len(m.Secrets)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CreateSecretRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CreateSecretRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CreateSecretRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Spec == nil {
+ m.Spec = &SecretSpec{}
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CreateSecretResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CreateSecretResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CreateSecretResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Secret", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Secret == nil {
+ m.Secret = &Secret{}
+ }
+ if err := m.Secret.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveSecretRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveSecretRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveSecretRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SecretID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SecretID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveSecretResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveSecretResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveSecretResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetConfigRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetConfigRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetConfigRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ConfigID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ConfigID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GetConfigResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GetConfigResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GetConfigResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Config == nil {
+ m.Config = &Config{}
+ }
+ if err := m.Config.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateConfigRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateConfigRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateConfigRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ConfigID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ConfigID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ConfigVersion", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.ConfigVersion == nil {
+ m.ConfigVersion = &Version{}
+ }
+ if err := m.ConfigVersion.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Spec == nil {
+ m.Spec = &ConfigSpec{}
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateConfigResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateConfigResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateConfigResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Config == nil {
+ m.Config = &Config{}
+ }
+ if err := m.Config.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListConfigsRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListConfigsRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListConfigsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Filters", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Filters == nil {
+ m.Filters = &ListConfigsRequest_Filters{}
+ }
+ if err := m.Filters.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListConfigsRequest_Filters) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Filters: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Filters: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Names", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Names = append(m.Names, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IDPrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IDPrefixes = append(m.IDPrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthControl
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NamePrefixes", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NamePrefixes = append(m.NamePrefixes, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListConfigsResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListConfigsResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListConfigsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Configs", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Configs = append(m.Configs, &Config{})
+ if err := m.Configs[len(m.Configs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CreateConfigRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CreateConfigRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CreateConfigRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Spec == nil {
+ m.Spec = &ConfigSpec{}
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CreateConfigResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CreateConfigResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CreateConfigResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Config == nil {
+ m.Config = &Config{}
+ }
+ if err := m.Config.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveConfigRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveConfigRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveConfigRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ConfigID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthControl
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ConfigID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RemoveConfigResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RemoveConfigResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RemoveConfigResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipControl(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthControl
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipControl(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthControl
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowControl
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipControl(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthControl = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowControl = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("control.proto", fileDescriptorControl) }
+
+var fileDescriptorControl = []byte{
+ // 2106 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x5a, 0xcd, 0x73, 0x1b, 0x49,
+ 0x15, 0xb7, 0x3e, 0x6c, 0xc9, 0x4f, 0xb6, 0x6c, 0xb7, 0x1d, 0x50, 0x29, 0xc1, 0x4e, 0x4d, 0x48,
+ 0xa2, 0x50, 0x41, 0x66, 0x15, 0x16, 0xc2, 0x52, 0x7c, 0xac, 0xed, 0x6c, 0x56, 0xeb, 0x8d, 0x93,
+ 0x1a, 0xc7, 0x5b, 0xdc, 0x54, 0xb2, 0xd4, 0x36, 0x13, 0xc9, 0x1a, 0x31, 0x33, 0xf2, 0xae, 0x8b,
+ 0x0b, 0x50, 0xcb, 0x81, 0x3f, 0x80, 0x2a, 0xae, 0x5c, 0x39, 0x70, 0xe0, 0xc4, 0x81, 0x3f, 0x20,
+ 0xc5, 0x89, 0x23, 0x27, 0xc3, 0xaa, 0x0a, 0x8a, 0x13, 0x7f, 0xc3, 0x56, 0x77, 0xbf, 0x9e, 0x2f,
+ 0xf5, 0xcc, 0xe8, 0xab, 0xca, 0x7b, 0xb2, 0xa6, 0xe7, 0xf7, 0xfa, 0xbd, 0xee, 0xf7, 0xeb, 0xdf,
+ 0x74, 0xbf, 0x36, 0xac, 0xb6, 0xcc, 0x9e, 0x63, 0x99, 0xdd, 0x6a, 0xdf, 0x32, 0x1d, 0x93, 0x90,
+ 0xb6, 0xd9, 0xea, 0x50, 0xab, 0x6a, 0x7f, 0xda, 0xb4, 0x2e, 0x3a, 0x86, 0x53, 0xbd, 0x7c, 0xa7,
+ 0x5c, 0xb0, 0xfb, 0xb4, 0x65, 0x0b, 0x40, 0x79, 0xd5, 0x3c, 0x7d, 0x43, 0x5b, 0x8e, 0x7c, 0x2c,
+ 0x38, 0x57, 0x7d, 0x2a, 0x1f, 0xb6, 0xce, 0xcd, 0x73, 0x93, 0xff, 0xdc, 0x65, 0xbf, 0xb0, 0x75,
+ 0xb3, 0xdf, 0x1d, 0x9c, 0x1b, 0xbd, 0x5d, 0xf1, 0x47, 0x34, 0x6a, 0xef, 0x42, 0xf1, 0x39, 0x75,
+ 0x8e, 0xcc, 0x36, 0xd5, 0xe9, 0x2f, 0x06, 0xd4, 0x76, 0xc8, 0x3d, 0xc8, 0xf5, 0xcc, 0x36, 0x6d,
+ 0x18, 0xed, 0x52, 0xea, 0x6e, 0xaa, 0xb2, 0xbc, 0x07, 0xc3, 0xeb, 0x9d, 0x25, 0x86, 0xa8, 0x1f,
+ 0xe8, 0x4b, 0xec, 0x55, 0xbd, 0xad, 0xfd, 0x04, 0xd6, 0x5c, 0x33, 0xbb, 0x6f, 0xf6, 0x6c, 0x4a,
+ 0x1e, 0x43, 0x96, 0xbd, 0xe4, 0x46, 0x85, 0x5a, 0xa9, 0x3a, 0x3a, 0x80, 0x2a, 0xc7, 0x73, 0x94,
+ 0xf6, 0xdf, 0x0c, 0xac, 0x7f, 0x6c, 0xd8, 0xbc, 0x0b, 0x5b, 0xba, 0xfe, 0x00, 0x72, 0x67, 0x46,
+ 0xd7, 0xa1, 0x96, 0x8d, 0xbd, 0x3c, 0x56, 0xf5, 0x12, 0x36, 0xab, 0x7e, 0x20, 0x6c, 0x74, 0x69,
+ 0x5c, 0xfe, 0x5d, 0x06, 0x72, 0xd8, 0x48, 0xb6, 0x60, 0xb1, 0xd7, 0xbc, 0xa0, 0xac, 0xc7, 0x4c,
+ 0x65, 0x59, 0x17, 0x0f, 0x64, 0x17, 0x0a, 0x46, 0xbb, 0xd1, 0xb7, 0xe8, 0x99, 0xf1, 0x19, 0xb5,
+ 0x4b, 0x69, 0xf6, 0x6e, 0xaf, 0x38, 0xbc, 0xde, 0x81, 0xfa, 0xc1, 0x2b, 0x6c, 0xd5, 0xc1, 0x68,
+ 0xcb, 0xdf, 0xe4, 0x15, 0x2c, 0x75, 0x9b, 0xa7, 0xb4, 0x6b, 0x97, 0x32, 0x77, 0x33, 0x95, 0x42,
+ 0xed, 0xe9, 0x24, 0x91, 0x55, 0x3f, 0xe6, 0xa6, 0xcf, 0x7a, 0x8e, 0x75, 0xa5, 0x63, 0x3f, 0xe4,
+ 0x05, 0x14, 0x2e, 0xe8, 0xc5, 0x29, 0xb5, 0xec, 0x9f, 0x1b, 0x7d, 0xbb, 0x94, 0xbd, 0x9b, 0xa9,
+ 0x14, 0x6b, 0x0f, 0xa3, 0xa6, 0xed, 0xb8, 0x4f, 0x5b, 0xd5, 0x17, 0x2e, 0x7e, 0x2f, 0xbd, 0xbe,
+ 0xa0, 0xfb, 0xed, 0xc9, 0xf7, 0x60, 0xd1, 0x32, 0xbb, 0xd4, 0x2e, 0x2d, 0xf2, 0x8e, 0xee, 0x44,
+ 0xce, 0xbf, 0xd9, 0xa5, 0xdc, 0x5a, 0xc0, 0xc9, 0x3d, 0x58, 0x65, 0x53, 0xe2, 0xcd, 0xc5, 0x12,
+ 0x9f, 0xa7, 0x15, 0xd6, 0x28, 0x47, 0x5f, 0xfe, 0x01, 0x14, 0x7c, 0x43, 0x20, 0xeb, 0x90, 0xe9,
+ 0xd0, 0x2b, 0x41, 0x0f, 0x9d, 0xfd, 0x64, 0xb3, 0x7c, 0xd9, 0xec, 0x0e, 0x68, 0x29, 0xcd, 0xdb,
+ 0xc4, 0xc3, 0x7b, 0xe9, 0xa7, 0x29, 0x6d, 0x1f, 0x36, 0x7c, 0xd3, 0x82, 0x5c, 0xa9, 0xc2, 0x22,
+ 0x63, 0x81, 0x48, 0x4a, 0x1c, 0x59, 0x04, 0x4c, 0xfb, 0x53, 0x0a, 0x36, 0x4e, 0xfa, 0xed, 0xa6,
+ 0x43, 0x27, 0x65, 0x2a, 0xf9, 0x31, 0xac, 0x70, 0xd0, 0x25, 0xb5, 0x6c, 0xc3, 0xec, 0xf1, 0x00,
+ 0x0b, 0xb5, 0xdb, 0x2a, 0x8f, 0x9f, 0x08, 0x88, 0x5e, 0x60, 0x06, 0xf8, 0x40, 0xbe, 0x03, 0x59,
+ 0xb6, 0xec, 0x4a, 0x19, 0x6e, 0x77, 0x27, 0x2e, 0x3f, 0x3a, 0x47, 0x6a, 0x7b, 0x40, 0xfc, 0xb1,
+ 0x4e, 0xb5, 0x3c, 0x8e, 0x60, 0x43, 0xa7, 0x17, 0xe6, 0xe5, 0xe4, 0xe3, 0xdd, 0x82, 0xc5, 0x33,
+ 0xd3, 0x6a, 0x89, 0x4c, 0xe4, 0x75, 0xf1, 0xa0, 0x6d, 0x01, 0xf1, 0xf7, 0x27, 0x62, 0xc2, 0xc5,
+ 0xff, 0xba, 0x69, 0x77, 0x7c, 0x2e, 0x9c, 0xa6, 0xdd, 0x09, 0xb9, 0x60, 0x08, 0xe6, 0x82, 0xbd,
+ 0x72, 0x17, 0xbf, 0x30, 0xf3, 0x46, 0xc7, 0x5e, 0xc6, 0x8d, 0x8e, 0xe3, 0x39, 0x4a, 0x7b, 0x2a,
+ 0x47, 0x37, 0xb1, 0x6b, 0x77, 0x1c, 0x7e, 0xef, 0xda, 0xdf, 0xb2, 0x42, 0x4c, 0x58, 0xe3, 0x14,
+ 0x62, 0xe2, 0x37, 0x1b, 0x15, 0x93, 0x7f, 0xdd, 0xa0, 0x98, 0xa8, 0x22, 0x53, 0x8a, 0xc9, 0x2e,
+ 0x14, 0x6c, 0x6a, 0x5d, 0x1a, 0x2d, 0xc6, 0x0e, 0x21, 0x26, 0x18, 0xc2, 0xb1, 0x68, 0xae, 0x1f,
+ 0xd8, 0x3a, 0x20, 0xa4, 0xde, 0xb6, 0xc9, 0x03, 0xc8, 0x23, 0x97, 0x84, 0x62, 0x2c, 0xef, 0x15,
+ 0x86, 0xd7, 0x3b, 0x39, 0x41, 0x26, 0x5b, 0xcf, 0x09, 0x36, 0xd9, 0xe4, 0x43, 0x28, 0xb6, 0xa9,
+ 0x6d, 0x58, 0xb4, 0xdd, 0xb0, 0x9d, 0xa6, 0x83, 0xfa, 0x50, 0xac, 0x7d, 0x23, 0x2a, 0xc5, 0xc7,
+ 0x0c, 0xc5, 0x05, 0x66, 0x15, 0x0d, 0x79, 0x8b, 0x42, 0x68, 0x72, 0xa3, 0x42, 0x43, 0xee, 0x00,
+ 0x0c, 0xfa, 0x0d, 0xc7, 0x6c, 0xb0, 0xf5, 0x53, 0xca, 0x73, 0x0a, 0xe7, 0x07, 0xfd, 0xd7, 0xe6,
+ 0x41, 0xd3, 0xa1, 0xa4, 0x0c, 0x79, 0x6b, 0xd0, 0x73, 0x0c, 0x96, 0x81, 0x65, 0x6e, 0xed, 0x3e,
+ 0xcf, 0x41, 0xa2, 0x70, 0xb2, 0x3d, 0x89, 0x62, 0x9c, 0x8b, 0x95, 0x28, 0x4e, 0x42, 0x01, 0xd3,
+ 0x0e, 0x61, 0x6b, 0xdf, 0xa2, 0x4d, 0x87, 0xe2, 0x84, 0x4b, 0x1a, 0x3e, 0x41, 0xfd, 0x10, 0x1c,
+ 0xdc, 0x51, 0x75, 0x83, 0x16, 0x3e, 0x09, 0x39, 0x82, 0x5b, 0xa1, 0xce, 0x30, 0xaa, 0x77, 0x21,
+ 0x87, 0x49, 0xc4, 0x0e, 0x6f, 0xc7, 0x74, 0xa8, 0x4b, 0xac, 0xf6, 0x06, 0x36, 0x9e, 0x53, 0x27,
+ 0x14, 0xd9, 0x63, 0x00, 0x8f, 0x33, 0xb8, 0xe6, 0x56, 0x87, 0xd7, 0x3b, 0xcb, 0x2e, 0x65, 0xf4,
+ 0x65, 0x97, 0x31, 0xe4, 0x21, 0xac, 0x19, 0x3d, 0x9b, 0x5a, 0x4e, 0xa3, 0x4d, 0xcf, 0x9a, 0x83,
+ 0xae, 0x63, 0xa3, 0xc2, 0x14, 0x45, 0xf3, 0x01, 0xb6, 0x6a, 0x87, 0x40, 0xfc, 0xbe, 0x66, 0x0b,
+ 0xfc, 0x2f, 0x69, 0xd8, 0x12, 0x62, 0x3a, 0x53, 0xf0, 0x07, 0xb0, 0x26, 0xd1, 0x13, 0x7c, 0x07,
+ 0x8a, 0x68, 0x23, 0x3f, 0x05, 0x4f, 0x02, 0x9f, 0x82, 0xf1, 0x52, 0x49, 0x5e, 0x40, 0xde, 0x32,
+ 0xbb, 0xdd, 0xd3, 0x66, 0xab, 0x53, 0xca, 0xde, 0x4d, 0x55, 0x8a, 0xb5, 0x77, 0x54, 0x86, 0xaa,
+ 0x41, 0x56, 0x75, 0x34, 0xd4, 0xdd, 0x2e, 0x34, 0x0d, 0xf2, 0xb2, 0x95, 0xe4, 0x21, 0x7b, 0xf4,
+ 0xf2, 0xe8, 0xd9, 0xfa, 0x02, 0x59, 0x81, 0xfc, 0x2b, 0xfd, 0xd9, 0x27, 0xf5, 0x97, 0x27, 0xc7,
+ 0xeb, 0x29, 0xc6, 0x9e, 0x50, 0x77, 0xb3, 0x25, 0xe1, 0x00, 0xb6, 0x84, 0xe8, 0xce, 0x92, 0x03,
+ 0xed, 0xeb, 0x70, 0x2b, 0xd4, 0x0b, 0xaa, 0xf7, 0xe7, 0x19, 0xd8, 0x64, 0xeb, 0x0f, 0xdb, 0x5d,
+ 0x01, 0xaf, 0x87, 0x05, 0x7c, 0x37, 0x4a, 0x26, 0x43, 0x96, 0xa3, 0x1a, 0xfe, 0xc7, 0xf4, 0xdc,
+ 0x35, 0xfc, 0x38, 0xa4, 0xe1, 0x3f, 0x9c, 0x30, 0x38, 0xa5, 0x8c, 0x8f, 0x68, 0x64, 0x56, 0xa1,
+ 0x91, 0x7e, 0x15, 0x5c, 0x9c, 0x9f, 0x0a, 0xbe, 0x84, 0xad, 0x60, 0xb8, 0x48, 0x9a, 0xef, 0x43,
+ 0x1e, 0x93, 0x28, 0xb5, 0x30, 0x96, 0x35, 0x2e, 0xd8, 0x53, 0xc4, 0x23, 0xea, 0x7c, 0x6a, 0x5a,
+ 0x9d, 0x09, 0x14, 0x11, 0x2d, 0x54, 0x8a, 0xe8, 0x76, 0xe6, 0x71, 0xba, 0x27, 0x9a, 0xe2, 0x38,
+ 0x2d, 0xad, 0x24, 0x56, 0x3b, 0xe1, 0x8a, 0x18, 0x8a, 0x8c, 0x40, 0x96, 0xcd, 0x34, 0xce, 0x17,
+ 0xff, 0xcd, 0x48, 0x8e, 0x36, 0x8c, 0xe4, 0x69, 0x8f, 0xe4, 0x68, 0xcb, 0x48, 0x8e, 0x80, 0x7a,
+ 0x1b, 0xc5, 0x6f, 0x4e, 0x31, 0xfe, 0x4c, 0xae, 0xbb, 0xb9, 0x87, 0xe9, 0xae, 0xc5, 0x50, 0xa4,
+ 0xda, 0xff, 0xd2, 0x62, 0x2d, 0x62, 0xfb, 0x14, 0x6b, 0x31, 0x64, 0x39, 0xba, 0x16, 0x7f, 0x7b,
+ 0x83, 0x6b, 0x31, 0x22, 0xb8, 0xa9, 0xd7, 0xe2, 0x1c, 0xd6, 0x9b, 0x17, 0x92, 0xb7, 0xde, 0x30,
+ 0x51, 0xb1, 0xeb, 0x4d, 0x66, 0xce, 0x05, 0x6b, 0xef, 0x73, 0x4a, 0xef, 0x77, 0x07, 0xb6, 0x43,
+ 0x2d, 0x9f, 0x46, 0xb7, 0x44, 0x4b, 0x48, 0xa3, 0x11, 0xc7, 0x78, 0x81, 0x00, 0x97, 0xbe, 0x6e,
+ 0x17, 0x1e, 0x7d, 0x11, 0x12, 0x47, 0x5f, 0x69, 0x25, 0xb1, 0x2e, 0x97, 0xf0, 0xc5, 0x14, 0x5c,
+ 0x0a, 0x59, 0x7e, 0xb5, 0xb8, 0x14, 0x11, 0xdc, 0x4d, 0x72, 0xc9, 0x0b, 0xc9, 0xe3, 0x12, 0x66,
+ 0x23, 0x96, 0x4b, 0x32, 0x75, 0x2e, 0x58, 0xfb, 0x7d, 0x0a, 0x0a, 0x87, 0xf4, 0x4a, 0x37, 0x9d,
+ 0xa6, 0xc3, 0xb6, 0x3e, 0xdf, 0x82, 0x0d, 0x46, 0x32, 0x6a, 0x35, 0xde, 0x98, 0x46, 0xaf, 0xe1,
+ 0x98, 0x1d, 0xda, 0xe3, 0xa1, 0xe5, 0xf5, 0x35, 0xf1, 0xe2, 0x23, 0xd3, 0xe8, 0xbd, 0x66, 0xcd,
+ 0xe4, 0x31, 0x90, 0x8b, 0x66, 0xaf, 0x79, 0x1e, 0x04, 0x8b, 0xcd, 0xe2, 0x3a, 0xbe, 0x51, 0xa2,
+ 0x07, 0xbd, 0xae, 0xd9, 0xea, 0x34, 0xd8, 0xa8, 0x33, 0x01, 0xf4, 0x09, 0x7f, 0x71, 0x48, 0xaf,
+ 0xb4, 0xdf, 0xb8, 0xfb, 0xc1, 0x59, 0x78, 0xce, 0xf6, 0x83, 0x12, 0x3d, 0xc9, 0x7e, 0x10, 0x6d,
+ 0x26, 0xd8, 0x0f, 0xa2, 0x77, 0xdf, 0x7e, 0xf0, 0x7d, 0xb6, 0x1f, 0x14, 0xb3, 0xca, 0xf7, 0x83,
+ 0x11, 0x86, 0xbe, 0xc9, 0xdf, 0xcb, 0xbe, 0xbd, 0xde, 0x59, 0xd0, 0x5d, 0x33, 0x6f, 0x7f, 0x37,
+ 0xa7, 0x85, 0xfa, 0x23, 0x58, 0xe7, 0x3b, 0xf6, 0x96, 0x45, 0x1d, 0x39, 0x9f, 0x8f, 0x60, 0xd9,
+ 0xe6, 0x0d, 0xde, 0x74, 0xae, 0x0c, 0xaf, 0x77, 0xf2, 0x02, 0x55, 0x3f, 0x60, 0xdf, 0x79, 0xfe,
+ 0xab, 0xad, 0x3d, 0xc7, 0xc3, 0x85, 0x30, 0xc7, 0x50, 0x6a, 0xb0, 0x24, 0x00, 0x18, 0x49, 0x59,
+ 0xbd, 0x67, 0xe0, 0x36, 0x88, 0xd4, 0xfe, 0x9a, 0x82, 0x4d, 0xb9, 0x71, 0x9d, 0x2e, 0x16, 0xb2,
+ 0x07, 0x45, 0x84, 0x4e, 0x90, 0xd7, 0x55, 0x61, 0x22, 0xd3, 0x5a, 0x0b, 0xa4, 0x75, 0x3b, 0x3a,
+ 0x70, 0xdf, 0xf6, 0xe4, 0x23, 0xef, 0x98, 0x32, 0xf3, 0x34, 0xfc, 0x27, 0x0d, 0x44, 0xec, 0xc4,
+ 0xd8, 0xa3, 0x2b, 0x9b, 0x1f, 0x86, 0x65, 0xb3, 0x1a, 0xbd, 0xe3, 0xf4, 0x1b, 0x8e, 0xaa, 0xe6,
+ 0xe7, 0xf3, 0x57, 0x4d, 0x3d, 0xa4, 0x9a, 0xef, 0x4d, 0x16, 0xdb, 0x8d, 0x88, 0xe6, 0xa1, 0x3c,
+ 0x76, 0x60, 0x44, 0x98, 0xb2, 0xef, 0xb2, 0x43, 0x12, 0x6f, 0x42, 0xc9, 0x8c, 0xcb, 0x99, 0x84,
+ 0x6a, 0x75, 0xd8, 0x94, 0x27, 0x76, 0x3f, 0x75, 0x6b, 0x81, 0xbd, 0xee, 0xd8, 0x5c, 0x0a, 0x76,
+ 0x35, 0x03, 0x97, 0x7e, 0x0a, 0x9b, 0xf2, 0xd0, 0x35, 0xe5, 0xea, 0xfe, 0x9a, 0x77, 0xf8, 0xf3,
+ 0x47, 0x83, 0xa2, 0xb1, 0x6f, 0xf6, 0xce, 0x8c, 0x73, 0x5f, 0xb7, 0x2d, 0xde, 0x10, 0xea, 0x56,
+ 0xa0, 0x58, 0xb7, 0xe2, 0xb5, 0x2b, 0x1a, 0xd2, 0xdc, 0x1b, 0xa1, 0x00, 0xc4, 0x8d, 0x10, 0x6d,
+ 0x10, 0xe9, 0x13, 0x8d, 0x69, 0x63, 0x61, 0xa2, 0x81, 0xd0, 0x49, 0x44, 0x43, 0x98, 0x4c, 0x20,
+ 0x1a, 0xc2, 0xb3, 0x4a, 0x34, 0xe6, 0x30, 0x0d, 0x52, 0x34, 0x44, 0xf3, 0x14, 0xa2, 0x11, 0x34,
+ 0xfc, 0x6a, 0x89, 0x86, 0x3a, 0xb6, 0x9b, 0x14, 0x0d, 0x37, 0x22, 0x4f, 0x34, 0x44, 0x22, 0x62,
+ 0x45, 0x03, 0x73, 0x26, 0xa1, 0x9e, 0x68, 0x04, 0xa9, 0x3b, 0x86, 0x68, 0xa8, 0xb8, 0x14, 0xec,
+ 0x6a, 0x06, 0x2e, 0xb9, 0xa2, 0x31, 0xf5, 0xea, 0x76, 0x45, 0x23, 0x18, 0x4d, 0xed, 0xd7, 0xb7,
+ 0x21, 0xb7, 0x2f, 0xee, 0x39, 0x89, 0x01, 0x39, 0xbc, 0x42, 0x24, 0x9a, 0x2a, 0xa8, 0xe0, 0xb5,
+ 0x64, 0xf9, 0x5e, 0x2c, 0x06, 0x45, 0xe9, 0xd6, 0xdf, 0xff, 0xfc, 0xff, 0x3f, 0xa4, 0xd7, 0x60,
+ 0x95, 0x83, 0xbe, 0x8d, 0xdb, 0x47, 0x62, 0xc2, 0xb2, 0x7b, 0x07, 0x45, 0xbe, 0x39, 0xce, 0xcd,
+ 0x5d, 0xf9, 0x7e, 0x02, 0x2a, 0xde, 0xa1, 0x05, 0xe0, 0x5d, 0x01, 0x91, 0xfb, 0xd1, 0x05, 0x3f,
+ 0xff, 0x08, 0x1f, 0x24, 0xc1, 0x12, 0x7d, 0x7a, 0x57, 0x3c, 0x6a, 0x9f, 0x23, 0x57, 0x4a, 0x6a,
+ 0x9f, 0x8a, 0x9b, 0xa2, 0x08, 0x9f, 0x22, 0x87, 0xaf, 0x9b, 0x76, 0x27, 0x32, 0x87, 0xbe, 0x2b,
+ 0x9e, 0xc8, 0x1c, 0x06, 0x2e, 0x73, 0xe2, 0x73, 0xc8, 0x8b, 0xf4, 0xd1, 0x39, 0xf4, 0x5f, 0x98,
+ 0x44, 0xe7, 0x30, 0x50, 0xe9, 0x4f, 0x9c, 0x4f, 0x3e, 0xbc, 0x98, 0xf9, 0xf4, 0x8f, 0xf0, 0x41,
+ 0x12, 0x2c, 0xd1, 0xa7, 0x57, 0x3b, 0x57, 0xfb, 0x1c, 0xa9, 0xe3, 0xab, 0x7d, 0x8e, 0x96, 0xe0,
+ 0xa3, 0x7c, 0x7e, 0x06, 0x2b, 0xfe, 0xba, 0x1f, 0x79, 0x38, 0x66, 0x21, 0xb3, 0x5c, 0x49, 0x06,
+ 0xc6, 0x7b, 0xfe, 0x25, 0xac, 0x06, 0x6e, 0x39, 0x88, 0xb2, 0x47, 0xd5, 0xad, 0x4a, 0xf9, 0xd1,
+ 0x18, 0xc8, 0x44, 0xe7, 0x81, 0x22, 0xb9, 0xda, 0xb9, 0xaa, 0x2c, 0xaf, 0x76, 0xae, 0xac, 0xb8,
+ 0xc7, 0x38, 0x0f, 0xd4, 0xc2, 0xd5, 0xce, 0x55, 0x45, 0x77, 0xb5, 0x73, 0x75, 0x61, 0x3d, 0x96,
+ 0x64, 0x58, 0x3f, 0x8a, 0x24, 0x59, 0xb0, 0xe6, 0x18, 0x49, 0xb2, 0x70, 0x01, 0x31, 0x9e, 0x64,
+ 0xb2, 0xd8, 0x15, 0x4d, 0xb2, 0x50, 0x85, 0x2e, 0x9a, 0x64, 0xe1, 0xba, 0x59, 0x22, 0xc9, 0xe4,
+ 0x80, 0x63, 0x48, 0x16, 0x1a, 0xf3, 0xa3, 0x31, 0x90, 0x63, 0xe6, 0x39, 0xd6, 0xb9, 0xaa, 0xc8,
+ 0x1b, 0x97, 0xe7, 0x31, 0x9d, 0x8b, 0x3c, 0xe3, 0x69, 0x3f, 0x32, 0xcf, 0xc1, 0x3a, 0x4a, 0x64,
+ 0x9e, 0x43, 0xa5, 0x86, 0x84, 0x3c, 0xcb, 0x42, 0x54, 0x74, 0x9e, 0x43, 0xd5, 0xb3, 0xe8, 0x3c,
+ 0x87, 0x6b, 0x5a, 0x89, 0xeb, 0x59, 0x0e, 0x38, 0x66, 0x3d, 0x87, 0xc6, 0xfc, 0x68, 0x0c, 0x64,
+ 0xe2, 0xc7, 0xc9, 0x2d, 0x81, 0xa8, 0x3f, 0x4e, 0xe1, 0x02, 0x4b, 0xf9, 0x7e, 0x02, 0x2a, 0x71,
+ 0x9e, 0xfd, 0xf5, 0x06, 0xf5, 0x3c, 0x2b, 0x6a, 0x29, 0xe5, 0x4a, 0x32, 0x30, 0xde, 0xf3, 0x00,
+ 0x0a, 0xbe, 0x53, 0x33, 0x79, 0x30, 0xde, 0x41, 0xbf, 0xfc, 0x30, 0x11, 0x97, 0x38, 0x60, 0xff,
+ 0xa1, 0x58, 0x3d, 0x60, 0xc5, 0x09, 0xbc, 0x5c, 0x49, 0x06, 0x26, 0x7a, 0xf6, 0x1f, 0x80, 0xd5,
+ 0x9e, 0x15, 0x87, 0xec, 0x72, 0x25, 0x19, 0x38, 0x0e, 0xab, 0xc4, 0x16, 0x3a, 0x92, 0x55, 0x81,
+ 0x3d, 0x7a, 0x24, 0xab, 0x82, 0xfb, 0xf0, 0x44, 0x56, 0xa1, 0xcf, 0x18, 0x56, 0x05, 0xdd, 0x56,
+ 0x92, 0x81, 0x63, 0xb1, 0x0a, 0x8f, 0x55, 0xd1, 0xac, 0x0a, 0x9e, 0x04, 0xa3, 0x59, 0x15, 0x3a,
+ 0x9f, 0x25, 0xb2, 0x2a, 0x6e, 0xc0, 0x8a, 0x23, 0x5a, 0x1c, 0xab, 0xc6, 0x9e, 0x6a, 0xff, 0x09,
+ 0x29, 0x8e, 0x55, 0x63, 0x78, 0x56, 0x1d, 0xb6, 0x22, 0x3c, 0xef, 0x95, 0xde, 0x7e, 0xb1, 0xbd,
+ 0xf0, 0xcf, 0x2f, 0xb6, 0x17, 0x7e, 0x35, 0xdc, 0x4e, 0xbd, 0x1d, 0x6e, 0xa7, 0xfe, 0x31, 0xdc,
+ 0x4e, 0xfd, 0x7b, 0xb8, 0x9d, 0x3a, 0x5d, 0xe2, 0xff, 0x12, 0xfa, 0xe4, 0xcb, 0x00, 0x00, 0x00,
+ 0xff, 0xff, 0x69, 0xfa, 0x48, 0xde, 0x8b, 0x2a, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/control.proto b/vendor/github.com/docker/swarmkit/api/control.proto
new file mode 100644
index 0000000..c8254ca
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/control.proto
@@ -0,0 +1,554 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "specs.proto";
+import "objects.proto";
+import "types.proto";
+import "gogoproto/gogo.proto";
+import "plugin/plugin.proto";
+
+// Control defines the RPC methods for controlling a cluster.
+service Control {
+ rpc GetNode(GetNodeRequest) returns (GetNodeResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc ListNodes(ListNodesRequest) returns (ListNodesResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc UpdateNode(UpdateNodeRequest) returns (UpdateNodeResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc RemoveNode(RemoveNodeRequest) returns (RemoveNodeResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+
+ rpc GetTask(GetTaskRequest) returns (GetTaskResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc ListTasks(ListTasksRequest) returns (ListTasksResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc RemoveTask(RemoveTaskRequest) returns (RemoveTaskResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+
+ rpc GetService(GetServiceRequest) returns (GetServiceResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc ListServices(ListServicesRequest) returns (ListServicesResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc CreateService(CreateServiceRequest) returns (CreateServiceResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc UpdateService(UpdateServiceRequest) returns (UpdateServiceResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc RemoveService(RemoveServiceRequest) returns (RemoveServiceResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+
+ rpc GetNetwork(GetNetworkRequest) returns (GetNetworkResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc ListNetworks(ListNetworksRequest) returns (ListNetworksResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc CreateNetwork(CreateNetworkRequest) returns (CreateNetworkResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc RemoveNetwork(RemoveNetworkRequest) returns (RemoveNetworkResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+
+ rpc GetCluster(GetClusterRequest) returns (GetClusterResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc ListClusters(ListClustersRequest) returns (ListClustersResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+ rpc UpdateCluster(UpdateClusterRequest) returns (UpdateClusterResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+
+ // --- secret APIs ---
+
+ // GetSecret returns a `GetSecretResponse` with a `Secret` with the same
+ // id as `GetSecretRequest.SecretID`
+ // - Returns `NotFound` if the Secret with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetSecretRequest.SecretID` is empty.
+ // - Returns an error if getting fails.
+ rpc GetSecret(GetSecretRequest) returns (GetSecretResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ }
+
+ // UpdateSecret returns a `UpdateSecretResponse` with a `Secret` with the same
+ // id as `GetSecretRequest.SecretID`
+ // - Returns `NotFound` if the Secret with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetSecretRequest.SecretID` is empty.
+ // - Returns an error if updating fails.
+ rpc UpdateSecret(UpdateSecretRequest) returns (UpdateSecretResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+
+ // ListSecrets returns a `ListSecretResponse` with a list of all non-internal `Secret`s being
+ // managed, or all secrets matching any name in `ListSecretsRequest.Names`, any
+ // name prefix in `ListSecretsRequest.NamePrefixes`, any id in
+ // `ListSecretsRequest.SecretIDs`, or any id prefix in `ListSecretsRequest.IDPrefixes`.
+ // - Returns an error if listing fails.
+ rpc ListSecrets(ListSecretsRequest) returns (ListSecretsResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ }
+ // CreateSecret creates and return a `CreateSecretResponse` with a `Secret` based
+ // on the provided `CreateSecretRequest.SecretSpec`.
+ // - Returns `InvalidArgument` if the `CreateSecretRequest.SecretSpec` is malformed,
+ // or if the secret data is too long or contains invalid characters.
+ // - Returns an error if the creation fails.
+ rpc CreateSecret(CreateSecretRequest) returns (CreateSecretResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ }
+
+ // RemoveSecret removes the secret referenced by `RemoveSecretRequest.ID`.
+ // - Returns `InvalidArgument` if `RemoveSecretRequest.ID` is empty.
+ // - Returns `NotFound` if the a secret named `RemoveSecretRequest.ID` is not found.
+ // - Returns an error if the deletion fails.
+ rpc RemoveSecret(RemoveSecretRequest) returns (RemoveSecretResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ }
+
+ // --- config APIs ---
+
+ // GetConfig returns a `GetConfigResponse` with a `Config` with the same
+ // id as `GetConfigRequest.ConfigID`
+ // - Returns `NotFound` if the Config with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetConfigRequest.ConfigID` is empty.
+ // - Returns an error if getting fails.
+ rpc GetConfig(GetConfigRequest) returns (GetConfigResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ }
+
+ // UpdateConfig returns a `UpdateConfigResponse` with a `Config` with the same
+ // id as `GetConfigRequest.ConfigID`
+ // - Returns `NotFound` if the Config with the given id is not found.
+ // - Returns `InvalidArgument` if the `GetConfigRequest.ConfigID` is empty.
+ // - Returns an error if updating fails.
+ rpc UpdateConfig(UpdateConfigRequest) returns (UpdateConfigResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+
+ // ListConfigs returns a `ListConfigResponse` with a list of `Config`s being
+ // managed, or all configs matching any name in `ListConfigsRequest.Names`, any
+ // name prefix in `ListConfigsRequest.NamePrefixes`, any id in
+ // `ListConfigsRequest.ConfigIDs`, or any id prefix in `ListConfigsRequest.IDPrefixes`.
+ // - Returns an error if listing fails.
+ rpc ListConfigs(ListConfigsRequest) returns (ListConfigsResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ }
+ // CreateConfig creates and return a `CreateConfigResponse` with a `Config` based
+ // on the provided `CreateConfigRequest.ConfigSpec`.
+ // - Returns `InvalidArgument` if the `CreateConfigRequest.ConfigSpec` is malformed,
+ // or if the config data is too long or contains invalid characters.
+ // - Returns an error if the creation fails.
+ rpc CreateConfig(CreateConfigRequest) returns (CreateConfigResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ }
+
+ // RemoveConfig removes the config referenced by `RemoveConfigRequest.ID`.
+ // - Returns `InvalidArgument` if `RemoveConfigRequest.ID` is empty.
+ // - Returns `NotFound` if the a config named `RemoveConfigRequest.ID` is not found.
+ // - Returns an error if the deletion fails.
+ rpc RemoveConfig(RemoveConfigRequest) returns (RemoveConfigResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ }
+}
+
+message GetNodeRequest {
+ string node_id = 1;
+}
+
+message GetNodeResponse {
+ Node node = 1;
+}
+
+message ListNodesRequest {
+ message Filters {
+ repeated string names = 1;
+ repeated string id_prefixes = 2;
+ map<string, string> labels = 3;
+ repeated NodeSpec.Membership memberships = 4 [packed=false];
+ repeated NodeRole roles = 5 [packed=false];
+ // NamePrefixes matches all objects with the given prefixes
+ repeated string name_prefixes = 6;
+ }
+
+ Filters filters = 1;
+}
+
+message ListNodesResponse {
+ repeated Node nodes = 1;
+}
+
+// UpdateNodeRequest requests an update to the specified node. This may be used
+// to request a new availability for a node, such as PAUSE. Invalid updates
+// will be denied and cause an error.
+message UpdateNodeRequest {
+ string node_id = 1;
+ Version node_version = 2;
+ NodeSpec spec = 3;
+}
+
+message UpdateNodeResponse {
+ Node node = 1;
+}
+
+// RemoveNodeRequest requests to delete the specified node from store.
+message RemoveNodeRequest {
+ string node_id = 1;
+ bool force = 2;
+}
+
+message RemoveNodeResponse {
+}
+
+message GetTaskRequest {
+ string task_id = 1;
+}
+
+message GetTaskResponse {
+ Task task = 1;
+}
+
+message RemoveTaskRequest {
+ string task_id = 1;
+}
+
+message RemoveTaskResponse {
+}
+
+message ListTasksRequest {
+ message Filters {
+ repeated string names = 1;
+ repeated string id_prefixes = 2;
+ map<string, string> labels = 3;
+ repeated string service_ids = 4;
+ repeated string node_ids = 5;
+ repeated docker.swarmkit.v1.TaskState desired_states = 6 [packed=false];
+ // NamePrefixes matches all objects with the given prefixes
+ repeated string name_prefixes = 7;
+ repeated string runtimes = 9;
+
+ // UpToDate matches tasks that are consistent with the current
+ // service definition.
+ // Note: this is intended for internal status reporting rather
+ // than being exposed to users. It may be removed in the future.
+ bool up_to_date = 8;
+ }
+
+ Filters filters = 1;
+}
+
+message ListTasksResponse {
+ repeated Task tasks = 1;
+}
+
+message CreateServiceRequest {
+ ServiceSpec spec = 1;
+}
+
+message CreateServiceResponse {
+ Service service = 1;
+}
+
+message GetServiceRequest {
+ string service_id = 1;
+ bool insert_defaults = 2;
+}
+
+message GetServiceResponse {
+ Service service = 1;
+}
+
+message UpdateServiceRequest {
+ string service_id = 1;
+ Version service_version = 2;
+ ServiceSpec spec = 3;
+
+ enum Rollback {
+ // This is not a rollback. The spec field of the request will
+ // be honored.
+ NONE = 0;
+
+ // Roll back the service - get spec from the service's
+ // previous_spec.
+ PREVIOUS = 1;
+ }
+
+ // Rollback may be set to PREVIOUS to request a rollback (the service's
+ // spec will be set to the value of its previous_spec field). In this
+ // case, the spec field of this request is ignored.
+ Rollback rollback = 4;
+}
+
+message UpdateServiceResponse {
+ Service service = 1;
+}
+
+message RemoveServiceRequest {
+ string service_id = 1;
+}
+
+message RemoveServiceResponse {
+}
+
+message ListServicesRequest {
+ message Filters {
+ repeated string names = 1;
+ repeated string id_prefixes = 2;
+ map<string, string> labels = 3;
+ // NamePrefixes matches all objects with the given prefixes
+ repeated string name_prefixes = 4;
+ repeated string runtimes = 5;
+ }
+
+ Filters filters = 1;
+}
+
+message ListServicesResponse {
+ repeated Service services = 1;
+}
+
+message CreateNetworkRequest {
+ NetworkSpec spec = 1;
+}
+
+message CreateNetworkResponse {
+ Network network = 1;
+}
+
+message GetNetworkRequest {
+ string name = 1;
+ string network_id = 2;
+}
+
+message GetNetworkResponse {
+ Network network = 1;
+}
+
+message RemoveNetworkRequest {
+ string name = 1;
+ string network_id = 2;
+}
+
+message RemoveNetworkResponse {}
+
+message ListNetworksRequest {
+ message Filters {
+ repeated string names = 1;
+ repeated string id_prefixes = 2;
+ map<string, string> labels = 3;
+ // NamePrefixes matches all objects with the given prefixes
+ repeated string name_prefixes = 4;
+ }
+
+ Filters filters = 1;
+}
+
+message ListNetworksResponse {
+ repeated Network networks = 1;
+}
+
+message GetClusterRequest {
+ string cluster_id = 1;
+}
+
+message GetClusterResponse {
+ Cluster cluster = 1;
+}
+
+message ListClustersRequest {
+ message Filters {
+ repeated string names = 1;
+ repeated string id_prefixes = 2;
+ map<string, string> labels = 3;
+ // NamePrefixes matches all objects with the given prefixes
+ repeated string name_prefixes = 4;
+ }
+
+ Filters filters = 1;
+}
+
+message ListClustersResponse {
+ repeated Cluster clusters = 1;
+}
+
+// KeyRotation tells UpdateCluster what items to rotate
+message KeyRotation {
+ // WorkerJoinToken tells UpdateCluster to rotate the worker secret token.
+ bool worker_join_token = 1;
+
+ // ManagerJoinToken tells UpdateCluster to rotate the manager secret token.
+ bool manager_join_token = 2;
+
+ // ManagerUnlockKey tells UpdateCluster to rotate the manager unlock key
+ bool manager_unlock_key = 3;
+
+}
+
+message UpdateClusterRequest {
+ // ClusterID is the cluster ID to update.
+ string cluster_id = 1;
+
+ // ClusterVersion is the version of the cluster being updated.
+ Version cluster_version = 2;
+
+ // Spec is the new spec to apply to the cluster.
+ ClusterSpec spec = 3;
+
+ // Rotation contains flags for join token and unlock key rotation
+ KeyRotation rotation = 4 [(gogoproto.nullable) = false];
+}
+
+message UpdateClusterResponse {
+ Cluster cluster = 1;
+}
+
+// GetSecretRequest is the request to get a `Secret` object given a secret id.
+message GetSecretRequest {
+ string secret_id = 1;
+}
+
+// GetSecretResponse contains the Secret corresponding to the id in
+// `GetSecretRequest`, but the `Secret.Spec.Data` field in each `Secret`
+// object should be nil instead of actually containing the secret bytes.
+message GetSecretResponse {
+ Secret secret = 1;
+}
+
+message UpdateSecretRequest {
+ // SecretID is the secret ID to update.
+ string secret_id = 1;
+
+ // SecretVersion is the version of the secret being updated.
+ Version secret_version = 2;
+
+ // Spec is the new spec to apply to the Secret
+ // Only some fields are allowed to be updated.
+ SecretSpec spec = 3;
+}
+
+message UpdateSecretResponse {
+ Secret secret = 1;
+}
+
+// ListSecretRequest is the request to list all non-internal secrets in the secret store,
+// or all secrets filtered by (name or name prefix or id prefix) and labels.
+message ListSecretsRequest {
+ message Filters {
+ repeated string names = 1;
+ repeated string id_prefixes = 2;
+ map<string, string> labels = 3;
+ repeated string name_prefixes = 4;
+ }
+
+ Filters filters = 1;
+}
+
+// ListSecretResponse contains a list of all the secrets that match the name or
+// name prefix filters provided in `ListSecretRequest`. The `Secret.Spec.Data`
+// field in each `Secret` object should be nil instead of actually containing
+// the secret bytes.
+message ListSecretsResponse {
+ repeated Secret secrets = 1;
+}
+
+// CreateSecretRequest specifies a new secret (it will not update an existing
+// secret) to create.
+message CreateSecretRequest {
+ SecretSpec spec = 1;
+}
+
+// CreateSecretResponse contains the newly created `Secret` corresponding to the
+// name in `CreateSecretRequest`. The `Secret.Spec.Data` field should be nil instead
+// of actually containing the secret bytes.
+message CreateSecretResponse {
+ Secret secret = 1;
+}
+
+// RemoveSecretRequest contains the ID of the secret that should be removed. This
+// removes all versions of the secret.
+message RemoveSecretRequest {
+ string secret_id = 1;
+}
+
+// RemoveSecretResponse is an empty object indicating the successful removal of
+// a secret.
+message RemoveSecretResponse {}
+
+// GetConfigRequest is the request to get a `Config` object given a config id.
+message GetConfigRequest {
+ string config_id = 1;
+}
+
+// GetConfigResponse contains the Config corresponding to the id in
+// `GetConfigRequest`.
+message GetConfigResponse {
+ Config config = 1;
+}
+
+message UpdateConfigRequest {
+ // ConfigID is the config ID to update.
+ string config_id = 1;
+
+ // ConfigVersion is the version of the config being updated.
+ Version config_version = 2;
+
+ // Spec is the new spec to apply to the Config
+ // Only some fields are allowed to be updated.
+ ConfigSpec spec = 3;
+}
+
+message UpdateConfigResponse {
+ Config config = 1;
+}
+
+// ListConfigRequest is the request to list all configs in the config store,
+// or all configs filtered by (name or name prefix or id prefix) and labels.
+message ListConfigsRequest {
+ message Filters {
+ repeated string names = 1;
+ repeated string id_prefixes = 2;
+ map<string, string> labels = 3;
+ repeated string name_prefixes = 4;
+ }
+
+ Filters filters = 1;
+}
+
+// ListConfigResponse contains a list of all the configs that match the name or
+// name prefix filters provided in `ListConfigRequest`.
+message ListConfigsResponse {
+ repeated Config configs = 1;
+}
+
+// CreateConfigRequest specifies a new config (it will not update an existing
+// config) to create.
+message CreateConfigRequest {
+ ConfigSpec spec = 1;
+}
+
+// CreateConfigResponse contains the newly created `Config` corresponding to the
+// name in `CreateConfigRequest`.
+message CreateConfigResponse {
+ Config config = 1;
+}
+
+// RemoveConfigRequest contains the ID of the config that should be removed. This
+// removes all versions of the config.
+message RemoveConfigRequest {
+ string config_id = 1;
+}
+
+// RemoveConfigResponse is an empty object indicating the successful removal of
+// a config.
+message RemoveConfigResponse {}
diff --git a/vendor/github.com/docker/swarmkit/api/deepcopy/copy.go b/vendor/github.com/docker/swarmkit/api/deepcopy/copy.go
new file mode 100644
index 0000000..64e370c
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/deepcopy/copy.go
@@ -0,0 +1,53 @@
+package deepcopy
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/gogo/protobuf/types"
+)
+
+// CopierFrom can be implemented if an object knows how to copy another into itself.
+type CopierFrom interface {
+ // Copy takes the fields from src and copies them into the target object.
+ //
+ // Calling this method with a nil receiver or a nil src may panic.
+ CopyFrom(src interface{})
+}
+
+// Copy copies src into dst. dst and src must have the same type.
+//
+// If the type has a copy function defined, it will be used.
+//
+// Default implementations for builtin types and well known protobuf types may
+// be provided.
+//
+// If the copy cannot be performed, this function will panic. Make sure to test
+// types that use this function.
+func Copy(dst, src interface{}) {
+ switch dst := dst.(type) {
+ case *types.Any:
+ src := src.(*types.Any)
+ dst.TypeUrl = src.TypeUrl
+ if src.Value != nil {
+ dst.Value = make([]byte, len(src.Value))
+ copy(dst.Value, src.Value)
+ } else {
+ dst.Value = nil
+ }
+ case *types.Duration:
+ src := src.(*types.Duration)
+ *dst = *src
+ case *time.Duration:
+ src := src.(*time.Duration)
+ *dst = *src
+ case *types.Timestamp:
+ src := src.(*types.Timestamp)
+ *dst = *src
+ case CopierFrom:
+ dst.CopyFrom(src)
+ default:
+ panic(fmt.Sprintf("Copy for %T not implemented", dst))
+ }
+
+}
diff --git a/vendor/github.com/docker/swarmkit/api/defaults/service.go b/vendor/github.com/docker/swarmkit/api/defaults/service.go
new file mode 100644
index 0000000..ce1e864
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/defaults/service.go
@@ -0,0 +1,99 @@
+package defaults
+
+import (
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/deepcopy"
+ gogotypes "github.com/gogo/protobuf/types"
+)
+
+// Service is a ServiceSpec object with all fields filled in using default
+// values.
+var Service = api.ServiceSpec{
+ Task: api.TaskSpec{
+ Runtime: &api.TaskSpec_Container{
+ Container: &api.ContainerSpec{
+ StopGracePeriod: gogotypes.DurationProto(10 * time.Second),
+ PullOptions: &api.ContainerSpec_PullOptions{},
+ DNSConfig: &api.ContainerSpec_DNSConfig{},
+ },
+ },
+ Resources: &api.ResourceRequirements{},
+ Restart: &api.RestartPolicy{
+ Condition: api.RestartOnAny,
+ Delay: gogotypes.DurationProto(5 * time.Second),
+ },
+ Placement: &api.Placement{},
+ },
+ Update: &api.UpdateConfig{
+ FailureAction: api.UpdateConfig_PAUSE,
+ Monitor: gogotypes.DurationProto(5 * time.Second),
+ Parallelism: 1,
+ Order: api.UpdateConfig_STOP_FIRST,
+ },
+ Rollback: &api.UpdateConfig{
+ FailureAction: api.UpdateConfig_PAUSE,
+ Monitor: gogotypes.DurationProto(5 * time.Second),
+ Parallelism: 1,
+ Order: api.UpdateConfig_STOP_FIRST,
+ },
+}
+
+// InterpolateService returns a ServiceSpec based on the provided spec, which
+// has all unspecified values filled in with default values.
+func InterpolateService(origSpec *api.ServiceSpec) *api.ServiceSpec {
+ spec := origSpec.Copy()
+
+ container := spec.Task.GetContainer()
+ defaultContainer := Service.Task.GetContainer()
+ if container != nil {
+ if container.StopGracePeriod == nil {
+ container.StopGracePeriod = &gogotypes.Duration{}
+ deepcopy.Copy(container.StopGracePeriod, defaultContainer.StopGracePeriod)
+ }
+ if container.PullOptions == nil {
+ container.PullOptions = defaultContainer.PullOptions.Copy()
+ }
+ if container.DNSConfig == nil {
+ container.DNSConfig = defaultContainer.DNSConfig.Copy()
+ }
+ }
+
+ if spec.Task.Resources == nil {
+ spec.Task.Resources = Service.Task.Resources.Copy()
+ }
+
+ if spec.Task.Restart == nil {
+ spec.Task.Restart = Service.Task.Restart.Copy()
+ } else {
+ if spec.Task.Restart.Delay == nil {
+ spec.Task.Restart.Delay = &gogotypes.Duration{}
+ deepcopy.Copy(spec.Task.Restart.Delay, Service.Task.Restart.Delay)
+ }
+ }
+
+ if spec.Task.Placement == nil {
+ spec.Task.Placement = Service.Task.Placement.Copy()
+ }
+
+ if spec.Update == nil {
+ spec.Update = Service.Update.Copy()
+ } else {
+ if spec.Update.Monitor == nil {
+ spec.Update.Monitor = &gogotypes.Duration{}
+ deepcopy.Copy(spec.Update.Monitor, Service.Update.Monitor)
+ }
+ }
+
+ if spec.Rollback == nil {
+ spec.Rollback = Service.Rollback.Copy()
+ } else {
+ if spec.Rollback.Monitor == nil {
+ spec.Rollback.Monitor = &gogotypes.Duration{}
+ deepcopy.Copy(spec.Rollback.Monitor, Service.Rollback.Monitor)
+ }
+ }
+
+ return spec
+}
diff --git a/vendor/github.com/docker/swarmkit/api/dispatcher.pb.go b/vendor/github.com/docker/swarmkit/api/dispatcher.pb.go
new file mode 100644
index 0000000..825a607
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/dispatcher.pb.go
@@ -0,0 +1,3847 @@
+// Code generated by protoc-gen-gogo.
+// source: dispatcher.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+import _ "github.com/docker/swarmkit/protobuf/plugin"
+import _ "github.com/gogo/protobuf/types"
+
+import time "time"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+import github_com_gogo_protobuf_types "github.com/gogo/protobuf/types"
+
+import raftselector "github.com/docker/swarmkit/manager/raftselector"
+import codes "google.golang.org/grpc/codes"
+import metadata "google.golang.org/grpc/metadata"
+import transport "google.golang.org/grpc/transport"
+import rafttime "time"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+var _ = time.Kitchen
+
+type AssignmentChange_AssignmentAction int32
+
+const (
+ AssignmentChange_AssignmentActionUpdate AssignmentChange_AssignmentAction = 0
+ AssignmentChange_AssignmentActionRemove AssignmentChange_AssignmentAction = 1
+)
+
+var AssignmentChange_AssignmentAction_name = map[int32]string{
+ 0: "UPDATE",
+ 1: "REMOVE",
+}
+var AssignmentChange_AssignmentAction_value = map[string]int32{
+ "UPDATE": 0,
+ "REMOVE": 1,
+}
+
+func (x AssignmentChange_AssignmentAction) String() string {
+ return proto.EnumName(AssignmentChange_AssignmentAction_name, int32(x))
+}
+func (AssignmentChange_AssignmentAction) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorDispatcher, []int{10, 0}
+}
+
+// AssignmentType specifies whether this assignment message carries
+// the full state, or is an update to an existing state.
+type AssignmentsMessage_Type int32
+
+const (
+ AssignmentsMessage_COMPLETE AssignmentsMessage_Type = 0
+ AssignmentsMessage_INCREMENTAL AssignmentsMessage_Type = 1
+)
+
+var AssignmentsMessage_Type_name = map[int32]string{
+ 0: "COMPLETE",
+ 1: "INCREMENTAL",
+}
+var AssignmentsMessage_Type_value = map[string]int32{
+ "COMPLETE": 0,
+ "INCREMENTAL": 1,
+}
+
+func (x AssignmentsMessage_Type) String() string {
+ return proto.EnumName(AssignmentsMessage_Type_name, int32(x))
+}
+func (AssignmentsMessage_Type) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorDispatcher, []int{11, 0}
+}
+
+// SessionRequest starts a session.
+type SessionRequest struct {
+ Description *NodeDescription `protobuf:"bytes,1,opt,name=description" json:"description,omitempty"`
+ // SessionID can be provided to attempt resuming an existing session. If the
+ // SessionID is empty or invalid, a new SessionID will be assigned.
+ //
+ // See SessionMessage.SessionID for details.
+ SessionID string `protobuf:"bytes,2,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+}
+
+func (m *SessionRequest) Reset() { *m = SessionRequest{} }
+func (*SessionRequest) ProtoMessage() {}
+func (*SessionRequest) Descriptor() ([]byte, []int) { return fileDescriptorDispatcher, []int{0} }
+
+// SessionMessage instructs an agent on various actions as part of the current
+// session. An agent should act immediately on the contents.
+type SessionMessage struct {
+ // SessionID is allocated after a successful registration. It should be
+ // used on all RPC calls after registration. A dispatcher may choose to
+ // change the SessionID, at which time an agent must re-register and obtain
+ // a new one.
+ //
+ // All Dispatcher calls after register should include the SessionID. If the
+ // Dispatcher so chooses, it may reject the call with an InvalidArgument
+ // error code, at which time the agent should call Register to start a new
+ // session.
+ //
+ // As a rule, once an agent has a SessionID, it should never save it to
+ // disk or try to otherwise reuse. If the agent loses its SessionID, it
+ // must start a new session through a call to Register. A Dispatcher may
+ // choose to reuse the SessionID, if it sees fit, but it is not advised.
+ //
+ // The actual implementation of the SessionID is Dispatcher specific and
+ // should be treated as opaque by agents.
+ //
+ // From a Dispatcher perspective, there are many ways to use the SessionID
+ // to ensure uniqueness of a set of client RPC calls. One method is to keep
+ // the SessionID unique to every call to Register in a single Dispatcher
+ // instance. This ensures that the SessionID represents the unique
+ // session from a single Agent to Manager. If the Agent restarts, we
+ // allocate a new session, since the restarted Agent is not aware of the
+ // new SessionID.
+ //
+ // The most compelling use case is to support duplicate node detection. If
+ // one clones a virtual machine, including certificate material, two nodes
+ // may end up with the same identity. This can also happen if two identical
+ // agent processes are coming from the same node. If the SessionID is
+ // replicated through the cluster, we can immediately detect the condition
+ // and address it.
+ //
+ // Extending from the case above, we can actually detect a compromised
+ // identity. Coupled with provisions to rebuild node identity, we can ban
+ // the compromised node identity and have the nodes re-authenticate and
+ // build a new identity. At this time, an administrator can then
+ // re-authorize the compromised nodes, if it was a mistake or ensure that a
+ // misbehaved node can no longer connect to the cluster.
+ //
+ // We considered placing this field in a GRPC header. Because this is a
+ // critical feature of the protocol, we thought it should be represented
+ // directly in the RPC message set.
+ SessionID string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ // Node identifies the registering node.
+ Node *Node `protobuf:"bytes,2,opt,name=node" json:"node,omitempty"`
+ // Managers provides a weight list of alternative dispatchers
+ Managers []*WeightedPeer `protobuf:"bytes,3,rep,name=managers" json:"managers,omitempty"`
+ // Symmetric encryption key distributed by the lead manager. Used by agents
+ // for securing network bootstrapping and communication.
+ NetworkBootstrapKeys []*EncryptionKey `protobuf:"bytes,4,rep,name=network_bootstrap_keys,json=networkBootstrapKeys" json:"network_bootstrap_keys,omitempty"`
+ // Which root certificates to trust
+ RootCA []byte `protobuf:"bytes,5,opt,name=RootCA,proto3" json:"RootCA,omitempty"`
+}
+
+func (m *SessionMessage) Reset() { *m = SessionMessage{} }
+func (*SessionMessage) ProtoMessage() {}
+func (*SessionMessage) Descriptor() ([]byte, []int) { return fileDescriptorDispatcher, []int{1} }
+
+// HeartbeatRequest provides identifying properties for a single heartbeat.
+type HeartbeatRequest struct {
+ SessionID string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+}
+
+func (m *HeartbeatRequest) Reset() { *m = HeartbeatRequest{} }
+func (*HeartbeatRequest) ProtoMessage() {}
+func (*HeartbeatRequest) Descriptor() ([]byte, []int) { return fileDescriptorDispatcher, []int{2} }
+
+type HeartbeatResponse struct {
+ // Period is the duration to wait before sending the next heartbeat.
+ // Well-behaved agents should update this on every heartbeat round trip.
+ Period time.Duration `protobuf:"bytes,1,opt,name=period,stdduration" json:"period"`
+}
+
+func (m *HeartbeatResponse) Reset() { *m = HeartbeatResponse{} }
+func (*HeartbeatResponse) ProtoMessage() {}
+func (*HeartbeatResponse) Descriptor() ([]byte, []int) { return fileDescriptorDispatcher, []int{3} }
+
+type UpdateTaskStatusRequest struct {
+ // Tasks should contain all statuses for running tasks. Only the status
+ // field must be set. The spec is not required.
+ SessionID string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ Updates []*UpdateTaskStatusRequest_TaskStatusUpdate `protobuf:"bytes,3,rep,name=updates" json:"updates,omitempty"`
+}
+
+func (m *UpdateTaskStatusRequest) Reset() { *m = UpdateTaskStatusRequest{} }
+func (*UpdateTaskStatusRequest) ProtoMessage() {}
+func (*UpdateTaskStatusRequest) Descriptor() ([]byte, []int) {
+ return fileDescriptorDispatcher, []int{4}
+}
+
+type UpdateTaskStatusRequest_TaskStatusUpdate struct {
+ TaskID string `protobuf:"bytes,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
+ Status *TaskStatus `protobuf:"bytes,2,opt,name=status" json:"status,omitempty"`
+}
+
+func (m *UpdateTaskStatusRequest_TaskStatusUpdate) Reset() {
+ *m = UpdateTaskStatusRequest_TaskStatusUpdate{}
+}
+func (*UpdateTaskStatusRequest_TaskStatusUpdate) ProtoMessage() {}
+func (*UpdateTaskStatusRequest_TaskStatusUpdate) Descriptor() ([]byte, []int) {
+ return fileDescriptorDispatcher, []int{4, 0}
+}
+
+type UpdateTaskStatusResponse struct {
+}
+
+func (m *UpdateTaskStatusResponse) Reset() { *m = UpdateTaskStatusResponse{} }
+func (*UpdateTaskStatusResponse) ProtoMessage() {}
+func (*UpdateTaskStatusResponse) Descriptor() ([]byte, []int) {
+ return fileDescriptorDispatcher, []int{5}
+}
+
+type TasksRequest struct {
+ SessionID string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+}
+
+func (m *TasksRequest) Reset() { *m = TasksRequest{} }
+func (*TasksRequest) ProtoMessage() {}
+func (*TasksRequest) Descriptor() ([]byte, []int) { return fileDescriptorDispatcher, []int{6} }
+
+type TasksMessage struct {
+ // Tasks is the set of tasks that should be running on the node.
+ // Tasks outside of this set running on the node should be terminated.
+ Tasks []*Task `protobuf:"bytes,1,rep,name=tasks" json:"tasks,omitempty"`
+}
+
+func (m *TasksMessage) Reset() { *m = TasksMessage{} }
+func (*TasksMessage) ProtoMessage() {}
+func (*TasksMessage) Descriptor() ([]byte, []int) { return fileDescriptorDispatcher, []int{7} }
+
+type AssignmentsRequest struct {
+ SessionID string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+}
+
+func (m *AssignmentsRequest) Reset() { *m = AssignmentsRequest{} }
+func (*AssignmentsRequest) ProtoMessage() {}
+func (*AssignmentsRequest) Descriptor() ([]byte, []int) { return fileDescriptorDispatcher, []int{8} }
+
+type Assignment struct {
+ // Types that are valid to be assigned to Item:
+ // *Assignment_Task
+ // *Assignment_Secret
+ // *Assignment_Config
+ Item isAssignment_Item `protobuf_oneof:"item"`
+}
+
+func (m *Assignment) Reset() { *m = Assignment{} }
+func (*Assignment) ProtoMessage() {}
+func (*Assignment) Descriptor() ([]byte, []int) { return fileDescriptorDispatcher, []int{9} }
+
+type isAssignment_Item interface {
+ isAssignment_Item()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type Assignment_Task struct {
+ Task *Task `protobuf:"bytes,1,opt,name=task,oneof"`
+}
+type Assignment_Secret struct {
+ Secret *Secret `protobuf:"bytes,2,opt,name=secret,oneof"`
+}
+type Assignment_Config struct {
+ Config *Config `protobuf:"bytes,3,opt,name=config,oneof"`
+}
+
+func (*Assignment_Task) isAssignment_Item() {}
+func (*Assignment_Secret) isAssignment_Item() {}
+func (*Assignment_Config) isAssignment_Item() {}
+
+func (m *Assignment) GetItem() isAssignment_Item {
+ if m != nil {
+ return m.Item
+ }
+ return nil
+}
+
+func (m *Assignment) GetTask() *Task {
+ if x, ok := m.GetItem().(*Assignment_Task); ok {
+ return x.Task
+ }
+ return nil
+}
+
+func (m *Assignment) GetSecret() *Secret {
+ if x, ok := m.GetItem().(*Assignment_Secret); ok {
+ return x.Secret
+ }
+ return nil
+}
+
+func (m *Assignment) GetConfig() *Config {
+ if x, ok := m.GetItem().(*Assignment_Config); ok {
+ return x.Config
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Assignment) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Assignment_OneofMarshaler, _Assignment_OneofUnmarshaler, _Assignment_OneofSizer, []interface{}{
+ (*Assignment_Task)(nil),
+ (*Assignment_Secret)(nil),
+ (*Assignment_Config)(nil),
+ }
+}
+
+func _Assignment_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Assignment)
+ // item
+ switch x := m.Item.(type) {
+ case *Assignment_Task:
+ _ = b.EncodeVarint(1<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Task); err != nil {
+ return err
+ }
+ case *Assignment_Secret:
+ _ = b.EncodeVarint(2<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Secret); err != nil {
+ return err
+ }
+ case *Assignment_Config:
+ _ = b.EncodeVarint(3<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Config); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("Assignment.Item has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Assignment_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Assignment)
+ switch tag {
+ case 1: // item.task
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Task)
+ err := b.DecodeMessage(msg)
+ m.Item = &Assignment_Task{msg}
+ return true, err
+ case 2: // item.secret
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Secret)
+ err := b.DecodeMessage(msg)
+ m.Item = &Assignment_Secret{msg}
+ return true, err
+ case 3: // item.config
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Config)
+ err := b.DecodeMessage(msg)
+ m.Item = &Assignment_Config{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Assignment_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Assignment)
+ // item
+ switch x := m.Item.(type) {
+ case *Assignment_Task:
+ s := proto.Size(x.Task)
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Assignment_Secret:
+ s := proto.Size(x.Secret)
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Assignment_Config:
+ s := proto.Size(x.Config)
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type AssignmentChange struct {
+ Assignment *Assignment `protobuf:"bytes,1,opt,name=assignment" json:"assignment,omitempty"`
+ Action AssignmentChange_AssignmentAction `protobuf:"varint,2,opt,name=action,proto3,enum=docker.swarmkit.v1.AssignmentChange_AssignmentAction" json:"action,omitempty"`
+}
+
+func (m *AssignmentChange) Reset() { *m = AssignmentChange{} }
+func (*AssignmentChange) ProtoMessage() {}
+func (*AssignmentChange) Descriptor() ([]byte, []int) { return fileDescriptorDispatcher, []int{10} }
+
+type AssignmentsMessage struct {
+ Type AssignmentsMessage_Type `protobuf:"varint,1,opt,name=type,proto3,enum=docker.swarmkit.v1.AssignmentsMessage_Type" json:"type,omitempty"`
+ // AppliesTo references the previous ResultsIn value, to chain
+ // incremental updates together. For the first update in a stream,
+ // AppliesTo is empty. If AppliesTo does not match the previously
+ // received ResultsIn, the consumer of the stream should start a new
+ // Assignments stream to re-sync.
+ AppliesTo string `protobuf:"bytes,2,opt,name=applies_to,json=appliesTo,proto3" json:"applies_to,omitempty"`
+ // ResultsIn identifies the result of this assignments message, to
+ // match against the next message's AppliesTo value and protect
+ // against missed messages.
+ ResultsIn string `protobuf:"bytes,3,opt,name=results_in,json=resultsIn,proto3" json:"results_in,omitempty"`
+ // AssignmentChange is a set of changes to apply on this node.
+ Changes []*AssignmentChange `protobuf:"bytes,4,rep,name=changes" json:"changes,omitempty"`
+}
+
+func (m *AssignmentsMessage) Reset() { *m = AssignmentsMessage{} }
+func (*AssignmentsMessage) ProtoMessage() {}
+func (*AssignmentsMessage) Descriptor() ([]byte, []int) { return fileDescriptorDispatcher, []int{11} }
+
+func init() {
+ proto.RegisterType((*SessionRequest)(nil), "docker.swarmkit.v1.SessionRequest")
+ proto.RegisterType((*SessionMessage)(nil), "docker.swarmkit.v1.SessionMessage")
+ proto.RegisterType((*HeartbeatRequest)(nil), "docker.swarmkit.v1.HeartbeatRequest")
+ proto.RegisterType((*HeartbeatResponse)(nil), "docker.swarmkit.v1.HeartbeatResponse")
+ proto.RegisterType((*UpdateTaskStatusRequest)(nil), "docker.swarmkit.v1.UpdateTaskStatusRequest")
+ proto.RegisterType((*UpdateTaskStatusRequest_TaskStatusUpdate)(nil), "docker.swarmkit.v1.UpdateTaskStatusRequest.TaskStatusUpdate")
+ proto.RegisterType((*UpdateTaskStatusResponse)(nil), "docker.swarmkit.v1.UpdateTaskStatusResponse")
+ proto.RegisterType((*TasksRequest)(nil), "docker.swarmkit.v1.TasksRequest")
+ proto.RegisterType((*TasksMessage)(nil), "docker.swarmkit.v1.TasksMessage")
+ proto.RegisterType((*AssignmentsRequest)(nil), "docker.swarmkit.v1.AssignmentsRequest")
+ proto.RegisterType((*Assignment)(nil), "docker.swarmkit.v1.Assignment")
+ proto.RegisterType((*AssignmentChange)(nil), "docker.swarmkit.v1.AssignmentChange")
+ proto.RegisterType((*AssignmentsMessage)(nil), "docker.swarmkit.v1.AssignmentsMessage")
+ proto.RegisterEnum("docker.swarmkit.v1.AssignmentChange_AssignmentAction", AssignmentChange_AssignmentAction_name, AssignmentChange_AssignmentAction_value)
+ proto.RegisterEnum("docker.swarmkit.v1.AssignmentsMessage_Type", AssignmentsMessage_Type_name, AssignmentsMessage_Type_value)
+}
+
+type authenticatedWrapperDispatcherServer struct {
+ local DispatcherServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperDispatcherServer(local DispatcherServer, authorize func(context.Context, []string) error) DispatcherServer {
+ return &authenticatedWrapperDispatcherServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperDispatcherServer) Session(r *SessionRequest, stream Dispatcher_SessionServer) error {
+
+ if err := p.authorize(stream.Context(), []string{"swarm-worker", "swarm-manager"}); err != nil {
+ return err
+ }
+ return p.local.Session(r, stream)
+}
+
+func (p *authenticatedWrapperDispatcherServer) Heartbeat(ctx context.Context, r *HeartbeatRequest) (*HeartbeatResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-worker", "swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.Heartbeat(ctx, r)
+}
+
+func (p *authenticatedWrapperDispatcherServer) UpdateTaskStatus(ctx context.Context, r *UpdateTaskStatusRequest) (*UpdateTaskStatusResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-worker", "swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.UpdateTaskStatus(ctx, r)
+}
+
+func (p *authenticatedWrapperDispatcherServer) Tasks(r *TasksRequest, stream Dispatcher_TasksServer) error {
+
+ if err := p.authorize(stream.Context(), []string{"swarm-worker", "swarm-manager"}); err != nil {
+ return err
+ }
+ return p.local.Tasks(r, stream)
+}
+
+func (p *authenticatedWrapperDispatcherServer) Assignments(r *AssignmentsRequest, stream Dispatcher_AssignmentsServer) error {
+
+ if err := p.authorize(stream.Context(), []string{"swarm-worker", "swarm-manager"}); err != nil {
+ return err
+ }
+ return p.local.Assignments(r, stream)
+}
+
+func (m *SessionRequest) Copy() *SessionRequest {
+ if m == nil {
+ return nil
+ }
+ o := &SessionRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SessionRequest) CopyFrom(src interface{}) {
+
+ o := src.(*SessionRequest)
+ *m = *o
+ if o.Description != nil {
+ m.Description = &NodeDescription{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Description, o.Description)
+ }
+}
+
+func (m *SessionMessage) Copy() *SessionMessage {
+ if m == nil {
+ return nil
+ }
+ o := &SessionMessage{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SessionMessage) CopyFrom(src interface{}) {
+
+ o := src.(*SessionMessage)
+ *m = *o
+ if o.Node != nil {
+ m.Node = &Node{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Node, o.Node)
+ }
+ if o.Managers != nil {
+ m.Managers = make([]*WeightedPeer, len(o.Managers))
+ for i := range m.Managers {
+ m.Managers[i] = &WeightedPeer{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Managers[i], o.Managers[i])
+ }
+ }
+
+ if o.NetworkBootstrapKeys != nil {
+ m.NetworkBootstrapKeys = make([]*EncryptionKey, len(o.NetworkBootstrapKeys))
+ for i := range m.NetworkBootstrapKeys {
+ m.NetworkBootstrapKeys[i] = &EncryptionKey{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.NetworkBootstrapKeys[i], o.NetworkBootstrapKeys[i])
+ }
+ }
+
+ if o.RootCA != nil {
+ m.RootCA = make([]byte, len(o.RootCA))
+ copy(m.RootCA, o.RootCA)
+ }
+}
+
+func (m *HeartbeatRequest) Copy() *HeartbeatRequest {
+ if m == nil {
+ return nil
+ }
+ o := &HeartbeatRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *HeartbeatRequest) CopyFrom(src interface{}) {
+
+ o := src.(*HeartbeatRequest)
+ *m = *o
+}
+
+func (m *HeartbeatResponse) Copy() *HeartbeatResponse {
+ if m == nil {
+ return nil
+ }
+ o := &HeartbeatResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *HeartbeatResponse) CopyFrom(src interface{}) {
+
+ o := src.(*HeartbeatResponse)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Period, &o.Period)
+}
+
+func (m *UpdateTaskStatusRequest) Copy() *UpdateTaskStatusRequest {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateTaskStatusRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateTaskStatusRequest) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateTaskStatusRequest)
+ *m = *o
+ if o.Updates != nil {
+ m.Updates = make([]*UpdateTaskStatusRequest_TaskStatusUpdate, len(o.Updates))
+ for i := range m.Updates {
+ m.Updates[i] = &UpdateTaskStatusRequest_TaskStatusUpdate{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Updates[i], o.Updates[i])
+ }
+ }
+
+}
+
+func (m *UpdateTaskStatusRequest_TaskStatusUpdate) Copy() *UpdateTaskStatusRequest_TaskStatusUpdate {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateTaskStatusRequest_TaskStatusUpdate{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateTaskStatusRequest_TaskStatusUpdate) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateTaskStatusRequest_TaskStatusUpdate)
+ *m = *o
+ if o.Status != nil {
+ m.Status = &TaskStatus{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Status, o.Status)
+ }
+}
+
+func (m *UpdateTaskStatusResponse) Copy() *UpdateTaskStatusResponse {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateTaskStatusResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateTaskStatusResponse) CopyFrom(src interface{}) {}
+func (m *TasksRequest) Copy() *TasksRequest {
+ if m == nil {
+ return nil
+ }
+ o := &TasksRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *TasksRequest) CopyFrom(src interface{}) {
+
+ o := src.(*TasksRequest)
+ *m = *o
+}
+
+func (m *TasksMessage) Copy() *TasksMessage {
+ if m == nil {
+ return nil
+ }
+ o := &TasksMessage{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *TasksMessage) CopyFrom(src interface{}) {
+
+ o := src.(*TasksMessage)
+ *m = *o
+ if o.Tasks != nil {
+ m.Tasks = make([]*Task, len(o.Tasks))
+ for i := range m.Tasks {
+ m.Tasks[i] = &Task{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Tasks[i], o.Tasks[i])
+ }
+ }
+
+}
+
+func (m *AssignmentsRequest) Copy() *AssignmentsRequest {
+ if m == nil {
+ return nil
+ }
+ o := &AssignmentsRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *AssignmentsRequest) CopyFrom(src interface{}) {
+
+ o := src.(*AssignmentsRequest)
+ *m = *o
+}
+
+func (m *Assignment) Copy() *Assignment {
+ if m == nil {
+ return nil
+ }
+ o := &Assignment{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Assignment) CopyFrom(src interface{}) {
+
+ o := src.(*Assignment)
+ *m = *o
+ if o.Item != nil {
+ switch o.Item.(type) {
+ case *Assignment_Task:
+ v := Assignment_Task{
+ Task: &Task{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Task, o.GetTask())
+ m.Item = &v
+ case *Assignment_Secret:
+ v := Assignment_Secret{
+ Secret: &Secret{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Secret, o.GetSecret())
+ m.Item = &v
+ case *Assignment_Config:
+ v := Assignment_Config{
+ Config: &Config{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Config, o.GetConfig())
+ m.Item = &v
+ }
+ }
+
+}
+
+func (m *AssignmentChange) Copy() *AssignmentChange {
+ if m == nil {
+ return nil
+ }
+ o := &AssignmentChange{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *AssignmentChange) CopyFrom(src interface{}) {
+
+ o := src.(*AssignmentChange)
+ *m = *o
+ if o.Assignment != nil {
+ m.Assignment = &Assignment{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Assignment, o.Assignment)
+ }
+}
+
+func (m *AssignmentsMessage) Copy() *AssignmentsMessage {
+ if m == nil {
+ return nil
+ }
+ o := &AssignmentsMessage{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *AssignmentsMessage) CopyFrom(src interface{}) {
+
+ o := src.(*AssignmentsMessage)
+ *m = *o
+ if o.Changes != nil {
+ m.Changes = make([]*AssignmentChange, len(o.Changes))
+ for i := range m.Changes {
+ m.Changes[i] = &AssignmentChange{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Changes[i], o.Changes[i])
+ }
+ }
+
+}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for Dispatcher service
+
+type DispatcherClient interface {
+ // Session starts an agent session with the dispatcher. The session is
+ // started after the first SessionMessage is received.
+ //
+ // Once started, the agent is controlled with a stream of SessionMessage.
+ // Agents should list on the stream at all times for instructions.
+ Session(ctx context.Context, in *SessionRequest, opts ...grpc.CallOption) (Dispatcher_SessionClient, error)
+ // Heartbeat is heartbeat method for nodes. It returns new TTL in response.
+ // Node should send new heartbeat earlier than now + TTL, otherwise it will
+ // be deregistered from dispatcher and its status will be updated to NodeStatus_DOWN
+ Heartbeat(ctx context.Context, in *HeartbeatRequest, opts ...grpc.CallOption) (*HeartbeatResponse, error)
+ // UpdateTaskStatus updates status of task. Node should send such updates
+ // on every status change of its tasks.
+ //
+ // Whether receiving batch updates or single status updates, this method
+ // should be accepting. Errors should only be returned if the entire update
+ // should be retried, due to data loss or other problems.
+ //
+ // If a task is unknown the dispatcher, the status update should be
+ // accepted regardless.
+ UpdateTaskStatus(ctx context.Context, in *UpdateTaskStatusRequest, opts ...grpc.CallOption) (*UpdateTaskStatusResponse, error)
+ // Tasks is a stream of tasks state for node. Each message contains full list
+ // of tasks which should be run on node, if task is not present in that list,
+ // it should be terminated.
+ Tasks(ctx context.Context, in *TasksRequest, opts ...grpc.CallOption) (Dispatcher_TasksClient, error)
+ // Assignments is a stream of assignments such as tasks and secrets for node.
+ // The first message in the stream contains all of the tasks and secrets
+ // that are relevant to the node. Future messages in the stream are updates to
+ // the set of assignments.
+ Assignments(ctx context.Context, in *AssignmentsRequest, opts ...grpc.CallOption) (Dispatcher_AssignmentsClient, error)
+}
+
+type dispatcherClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewDispatcherClient(cc *grpc.ClientConn) DispatcherClient {
+ return &dispatcherClient{cc}
+}
+
+func (c *dispatcherClient) Session(ctx context.Context, in *SessionRequest, opts ...grpc.CallOption) (Dispatcher_SessionClient, error) {
+ stream, err := grpc.NewClientStream(ctx, &_Dispatcher_serviceDesc.Streams[0], c.cc, "/docker.swarmkit.v1.Dispatcher/Session", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &dispatcherSessionClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Dispatcher_SessionClient interface {
+ Recv() (*SessionMessage, error)
+ grpc.ClientStream
+}
+
+type dispatcherSessionClient struct {
+ grpc.ClientStream
+}
+
+func (x *dispatcherSessionClient) Recv() (*SessionMessage, error) {
+ m := new(SessionMessage)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+func (c *dispatcherClient) Heartbeat(ctx context.Context, in *HeartbeatRequest, opts ...grpc.CallOption) (*HeartbeatResponse, error) {
+ out := new(HeartbeatResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Dispatcher/Heartbeat", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *dispatcherClient) UpdateTaskStatus(ctx context.Context, in *UpdateTaskStatusRequest, opts ...grpc.CallOption) (*UpdateTaskStatusResponse, error) {
+ out := new(UpdateTaskStatusResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Dispatcher/UpdateTaskStatus", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *dispatcherClient) Tasks(ctx context.Context, in *TasksRequest, opts ...grpc.CallOption) (Dispatcher_TasksClient, error) {
+ stream, err := grpc.NewClientStream(ctx, &_Dispatcher_serviceDesc.Streams[1], c.cc, "/docker.swarmkit.v1.Dispatcher/Tasks", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &dispatcherTasksClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Dispatcher_TasksClient interface {
+ Recv() (*TasksMessage, error)
+ grpc.ClientStream
+}
+
+type dispatcherTasksClient struct {
+ grpc.ClientStream
+}
+
+func (x *dispatcherTasksClient) Recv() (*TasksMessage, error) {
+ m := new(TasksMessage)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+func (c *dispatcherClient) Assignments(ctx context.Context, in *AssignmentsRequest, opts ...grpc.CallOption) (Dispatcher_AssignmentsClient, error) {
+ stream, err := grpc.NewClientStream(ctx, &_Dispatcher_serviceDesc.Streams[2], c.cc, "/docker.swarmkit.v1.Dispatcher/Assignments", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &dispatcherAssignmentsClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Dispatcher_AssignmentsClient interface {
+ Recv() (*AssignmentsMessage, error)
+ grpc.ClientStream
+}
+
+type dispatcherAssignmentsClient struct {
+ grpc.ClientStream
+}
+
+func (x *dispatcherAssignmentsClient) Recv() (*AssignmentsMessage, error) {
+ m := new(AssignmentsMessage)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// Server API for Dispatcher service
+
+type DispatcherServer interface {
+ // Session starts an agent session with the dispatcher. The session is
+ // started after the first SessionMessage is received.
+ //
+ // Once started, the agent is controlled with a stream of SessionMessage.
+ // Agents should list on the stream at all times for instructions.
+ Session(*SessionRequest, Dispatcher_SessionServer) error
+ // Heartbeat is heartbeat method for nodes. It returns new TTL in response.
+ // Node should send new heartbeat earlier than now + TTL, otherwise it will
+ // be deregistered from dispatcher and its status will be updated to NodeStatus_DOWN
+ Heartbeat(context.Context, *HeartbeatRequest) (*HeartbeatResponse, error)
+ // UpdateTaskStatus updates status of task. Node should send such updates
+ // on every status change of its tasks.
+ //
+ // Whether receiving batch updates or single status updates, this method
+ // should be accepting. Errors should only be returned if the entire update
+ // should be retried, due to data loss or other problems.
+ //
+ // If a task is unknown the dispatcher, the status update should be
+ // accepted regardless.
+ UpdateTaskStatus(context.Context, *UpdateTaskStatusRequest) (*UpdateTaskStatusResponse, error)
+ // Tasks is a stream of tasks state for node. Each message contains full list
+ // of tasks which should be run on node, if task is not present in that list,
+ // it should be terminated.
+ Tasks(*TasksRequest, Dispatcher_TasksServer) error
+ // Assignments is a stream of assignments such as tasks and secrets for node.
+ // The first message in the stream contains all of the tasks and secrets
+ // that are relevant to the node. Future messages in the stream are updates to
+ // the set of assignments.
+ Assignments(*AssignmentsRequest, Dispatcher_AssignmentsServer) error
+}
+
+func RegisterDispatcherServer(s *grpc.Server, srv DispatcherServer) {
+ s.RegisterService(&_Dispatcher_serviceDesc, srv)
+}
+
+func _Dispatcher_Session_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(SessionRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(DispatcherServer).Session(m, &dispatcherSessionServer{stream})
+}
+
+type Dispatcher_SessionServer interface {
+ Send(*SessionMessage) error
+ grpc.ServerStream
+}
+
+type dispatcherSessionServer struct {
+ grpc.ServerStream
+}
+
+func (x *dispatcherSessionServer) Send(m *SessionMessage) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+func _Dispatcher_Heartbeat_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(HeartbeatRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(DispatcherServer).Heartbeat(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Dispatcher/Heartbeat",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(DispatcherServer).Heartbeat(ctx, req.(*HeartbeatRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Dispatcher_UpdateTaskStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateTaskStatusRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(DispatcherServer).UpdateTaskStatus(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Dispatcher/UpdateTaskStatus",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(DispatcherServer).UpdateTaskStatus(ctx, req.(*UpdateTaskStatusRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Dispatcher_Tasks_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(TasksRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(DispatcherServer).Tasks(m, &dispatcherTasksServer{stream})
+}
+
+type Dispatcher_TasksServer interface {
+ Send(*TasksMessage) error
+ grpc.ServerStream
+}
+
+type dispatcherTasksServer struct {
+ grpc.ServerStream
+}
+
+func (x *dispatcherTasksServer) Send(m *TasksMessage) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+func _Dispatcher_Assignments_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(AssignmentsRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(DispatcherServer).Assignments(m, &dispatcherAssignmentsServer{stream})
+}
+
+type Dispatcher_AssignmentsServer interface {
+ Send(*AssignmentsMessage) error
+ grpc.ServerStream
+}
+
+type dispatcherAssignmentsServer struct {
+ grpc.ServerStream
+}
+
+func (x *dispatcherAssignmentsServer) Send(m *AssignmentsMessage) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+var _Dispatcher_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.Dispatcher",
+ HandlerType: (*DispatcherServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "Heartbeat",
+ Handler: _Dispatcher_Heartbeat_Handler,
+ },
+ {
+ MethodName: "UpdateTaskStatus",
+ Handler: _Dispatcher_UpdateTaskStatus_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "Session",
+ Handler: _Dispatcher_Session_Handler,
+ ServerStreams: true,
+ },
+ {
+ StreamName: "Tasks",
+ Handler: _Dispatcher_Tasks_Handler,
+ ServerStreams: true,
+ },
+ {
+ StreamName: "Assignments",
+ Handler: _Dispatcher_Assignments_Handler,
+ ServerStreams: true,
+ },
+ },
+ Metadata: "dispatcher.proto",
+}
+
+func (m *SessionRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SessionRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Description != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(m.Description.Size()))
+ n1, err := m.Description.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ }
+ if len(m.SessionID) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(len(m.SessionID)))
+ i += copy(dAtA[i:], m.SessionID)
+ }
+ return i, nil
+}
+
+func (m *SessionMessage) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SessionMessage) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SessionID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(len(m.SessionID)))
+ i += copy(dAtA[i:], m.SessionID)
+ }
+ if m.Node != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(m.Node.Size()))
+ n2, err := m.Node.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ }
+ if len(m.Managers) > 0 {
+ for _, msg := range m.Managers {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.NetworkBootstrapKeys) > 0 {
+ for _, msg := range m.NetworkBootstrapKeys {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.RootCA) > 0 {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(len(m.RootCA)))
+ i += copy(dAtA[i:], m.RootCA)
+ }
+ return i, nil
+}
+
+func (m *HeartbeatRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *HeartbeatRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SessionID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(len(m.SessionID)))
+ i += copy(dAtA[i:], m.SessionID)
+ }
+ return i, nil
+}
+
+func (m *HeartbeatResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *HeartbeatResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(github_com_gogo_protobuf_types.SizeOfStdDuration(m.Period)))
+ n3, err := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.Period, dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ return i, nil
+}
+
+func (m *UpdateTaskStatusRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateTaskStatusRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SessionID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(len(m.SessionID)))
+ i += copy(dAtA[i:], m.SessionID)
+ }
+ if len(m.Updates) > 0 {
+ for _, msg := range m.Updates {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *UpdateTaskStatusRequest_TaskStatusUpdate) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateTaskStatusRequest_TaskStatusUpdate) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.TaskID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(len(m.TaskID)))
+ i += copy(dAtA[i:], m.TaskID)
+ }
+ if m.Status != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(m.Status.Size()))
+ n4, err := m.Status.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n4
+ }
+ return i, nil
+}
+
+func (m *UpdateTaskStatusResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateTaskStatusResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *TasksRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *TasksRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SessionID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(len(m.SessionID)))
+ i += copy(dAtA[i:], m.SessionID)
+ }
+ return i, nil
+}
+
+func (m *TasksMessage) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *TasksMessage) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Tasks) > 0 {
+ for _, msg := range m.Tasks {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *AssignmentsRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *AssignmentsRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SessionID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(len(m.SessionID)))
+ i += copy(dAtA[i:], m.SessionID)
+ }
+ return i, nil
+}
+
+func (m *Assignment) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Assignment) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Item != nil {
+ nn5, err := m.Item.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn5
+ }
+ return i, nil
+}
+
+func (m *Assignment_Task) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Task != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(m.Task.Size()))
+ n6, err := m.Task.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n6
+ }
+ return i, nil
+}
+func (m *Assignment_Secret) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Secret != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(m.Secret.Size()))
+ n7, err := m.Secret.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n7
+ }
+ return i, nil
+}
+func (m *Assignment_Config) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Config != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(m.Config.Size()))
+ n8, err := m.Config.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n8
+ }
+ return i, nil
+}
+func (m *AssignmentChange) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *AssignmentChange) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Assignment != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(m.Assignment.Size()))
+ n9, err := m.Assignment.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n9
+ }
+ if m.Action != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(m.Action))
+ }
+ return i, nil
+}
+
+func (m *AssignmentsMessage) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *AssignmentsMessage) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Type != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(m.Type))
+ }
+ if len(m.AppliesTo) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(len(m.AppliesTo)))
+ i += copy(dAtA[i:], m.AppliesTo)
+ }
+ if len(m.ResultsIn) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(len(m.ResultsIn)))
+ i += copy(dAtA[i:], m.ResultsIn)
+ }
+ if len(m.Changes) > 0 {
+ for _, msg := range m.Changes {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintDispatcher(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func encodeFixed64Dispatcher(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Dispatcher(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintDispatcher(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+type raftProxyDispatcherServer struct {
+ local DispatcherServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyDispatcherServer(local DispatcherServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) DispatcherServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyDispatcherServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyDispatcherServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyDispatcherServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+type Dispatcher_SessionServerWrapper struct {
+ Dispatcher_SessionServer
+ ctx context.Context
+}
+
+func (s Dispatcher_SessionServerWrapper) Context() context.Context {
+ return s.ctx
+}
+
+func (p *raftProxyDispatcherServer) Session(r *SessionRequest, stream Dispatcher_SessionServer) error {
+ ctx := stream.Context()
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return err
+ }
+ streamWrapper := Dispatcher_SessionServerWrapper{
+ Dispatcher_SessionServer: stream,
+ ctx: ctx,
+ }
+ return p.local.Session(r, streamWrapper)
+ }
+ return err
+ }
+ ctx, err = p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return err
+ }
+ clientStream, err := NewDispatcherClient(conn).Session(ctx, r)
+
+ if err != nil {
+ return err
+ }
+
+ for {
+ msg, err := clientStream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+ if err := stream.Send(msg); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (p *raftProxyDispatcherServer) Heartbeat(ctx context.Context, r *HeartbeatRequest) (*HeartbeatResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.Heartbeat(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewDispatcherClient(conn).Heartbeat(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.Heartbeat(ctx, r)
+ }
+ return nil, err
+ }
+ return NewDispatcherClient(conn).Heartbeat(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyDispatcherServer) UpdateTaskStatus(ctx context.Context, r *UpdateTaskStatusRequest) (*UpdateTaskStatusResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.UpdateTaskStatus(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewDispatcherClient(conn).UpdateTaskStatus(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.UpdateTaskStatus(ctx, r)
+ }
+ return nil, err
+ }
+ return NewDispatcherClient(conn).UpdateTaskStatus(modCtx, r)
+ }
+ return resp, err
+}
+
+type Dispatcher_TasksServerWrapper struct {
+ Dispatcher_TasksServer
+ ctx context.Context
+}
+
+func (s Dispatcher_TasksServerWrapper) Context() context.Context {
+ return s.ctx
+}
+
+func (p *raftProxyDispatcherServer) Tasks(r *TasksRequest, stream Dispatcher_TasksServer) error {
+ ctx := stream.Context()
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return err
+ }
+ streamWrapper := Dispatcher_TasksServerWrapper{
+ Dispatcher_TasksServer: stream,
+ ctx: ctx,
+ }
+ return p.local.Tasks(r, streamWrapper)
+ }
+ return err
+ }
+ ctx, err = p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return err
+ }
+ clientStream, err := NewDispatcherClient(conn).Tasks(ctx, r)
+
+ if err != nil {
+ return err
+ }
+
+ for {
+ msg, err := clientStream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+ if err := stream.Send(msg); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+type Dispatcher_AssignmentsServerWrapper struct {
+ Dispatcher_AssignmentsServer
+ ctx context.Context
+}
+
+func (s Dispatcher_AssignmentsServerWrapper) Context() context.Context {
+ return s.ctx
+}
+
+func (p *raftProxyDispatcherServer) Assignments(r *AssignmentsRequest, stream Dispatcher_AssignmentsServer) error {
+ ctx := stream.Context()
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return err
+ }
+ streamWrapper := Dispatcher_AssignmentsServerWrapper{
+ Dispatcher_AssignmentsServer: stream,
+ ctx: ctx,
+ }
+ return p.local.Assignments(r, streamWrapper)
+ }
+ return err
+ }
+ ctx, err = p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return err
+ }
+ clientStream, err := NewDispatcherClient(conn).Assignments(ctx, r)
+
+ if err != nil {
+ return err
+ }
+
+ for {
+ msg, err := clientStream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+ if err := stream.Send(msg); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (m *SessionRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Description != nil {
+ l = m.Description.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ l = len(m.SessionID)
+ if l > 0 {
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ return n
+}
+
+func (m *SessionMessage) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SessionID)
+ if l > 0 {
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ if m.Node != nil {
+ l = m.Node.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ if len(m.Managers) > 0 {
+ for _, e := range m.Managers {
+ l = e.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ }
+ if len(m.NetworkBootstrapKeys) > 0 {
+ for _, e := range m.NetworkBootstrapKeys {
+ l = e.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ }
+ l = len(m.RootCA)
+ if l > 0 {
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ return n
+}
+
+func (m *HeartbeatRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SessionID)
+ if l > 0 {
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ return n
+}
+
+func (m *HeartbeatResponse) Size() (n int) {
+ var l int
+ _ = l
+ l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.Period)
+ n += 1 + l + sovDispatcher(uint64(l))
+ return n
+}
+
+func (m *UpdateTaskStatusRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SessionID)
+ if l > 0 {
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ if len(m.Updates) > 0 {
+ for _, e := range m.Updates {
+ l = e.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *UpdateTaskStatusRequest_TaskStatusUpdate) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.TaskID)
+ if l > 0 {
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ if m.Status != nil {
+ l = m.Status.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ return n
+}
+
+func (m *UpdateTaskStatusResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *TasksRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SessionID)
+ if l > 0 {
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ return n
+}
+
+func (m *TasksMessage) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Tasks) > 0 {
+ for _, e := range m.Tasks {
+ l = e.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *AssignmentsRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SessionID)
+ if l > 0 {
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ return n
+}
+
+func (m *Assignment) Size() (n int) {
+ var l int
+ _ = l
+ if m.Item != nil {
+ n += m.Item.Size()
+ }
+ return n
+}
+
+func (m *Assignment_Task) Size() (n int) {
+ var l int
+ _ = l
+ if m.Task != nil {
+ l = m.Task.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ return n
+}
+func (m *Assignment_Secret) Size() (n int) {
+ var l int
+ _ = l
+ if m.Secret != nil {
+ l = m.Secret.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ return n
+}
+func (m *Assignment_Config) Size() (n int) {
+ var l int
+ _ = l
+ if m.Config != nil {
+ l = m.Config.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ return n
+}
+func (m *AssignmentChange) Size() (n int) {
+ var l int
+ _ = l
+ if m.Assignment != nil {
+ l = m.Assignment.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ if m.Action != 0 {
+ n += 1 + sovDispatcher(uint64(m.Action))
+ }
+ return n
+}
+
+func (m *AssignmentsMessage) Size() (n int) {
+ var l int
+ _ = l
+ if m.Type != 0 {
+ n += 1 + sovDispatcher(uint64(m.Type))
+ }
+ l = len(m.AppliesTo)
+ if l > 0 {
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ l = len(m.ResultsIn)
+ if l > 0 {
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ if len(m.Changes) > 0 {
+ for _, e := range m.Changes {
+ l = e.Size()
+ n += 1 + l + sovDispatcher(uint64(l))
+ }
+ }
+ return n
+}
+
+func sovDispatcher(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozDispatcher(x uint64) (n int) {
+ return sovDispatcher(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *SessionRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SessionRequest{`,
+ `Description:` + strings.Replace(fmt.Sprintf("%v", this.Description), "NodeDescription", "NodeDescription", 1) + `,`,
+ `SessionID:` + fmt.Sprintf("%v", this.SessionID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SessionMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SessionMessage{`,
+ `SessionID:` + fmt.Sprintf("%v", this.SessionID) + `,`,
+ `Node:` + strings.Replace(fmt.Sprintf("%v", this.Node), "Node", "Node", 1) + `,`,
+ `Managers:` + strings.Replace(fmt.Sprintf("%v", this.Managers), "WeightedPeer", "WeightedPeer", 1) + `,`,
+ `NetworkBootstrapKeys:` + strings.Replace(fmt.Sprintf("%v", this.NetworkBootstrapKeys), "EncryptionKey", "EncryptionKey", 1) + `,`,
+ `RootCA:` + fmt.Sprintf("%v", this.RootCA) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *HeartbeatRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&HeartbeatRequest{`,
+ `SessionID:` + fmt.Sprintf("%v", this.SessionID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *HeartbeatResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&HeartbeatResponse{`,
+ `Period:` + strings.Replace(strings.Replace(this.Period.String(), "Duration", "google_protobuf1.Duration", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateTaskStatusRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateTaskStatusRequest{`,
+ `SessionID:` + fmt.Sprintf("%v", this.SessionID) + `,`,
+ `Updates:` + strings.Replace(fmt.Sprintf("%v", this.Updates), "UpdateTaskStatusRequest_TaskStatusUpdate", "UpdateTaskStatusRequest_TaskStatusUpdate", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateTaskStatusRequest_TaskStatusUpdate) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateTaskStatusRequest_TaskStatusUpdate{`,
+ `TaskID:` + fmt.Sprintf("%v", this.TaskID) + `,`,
+ `Status:` + strings.Replace(fmt.Sprintf("%v", this.Status), "TaskStatus", "TaskStatus", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateTaskStatusResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateTaskStatusResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TasksRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TasksRequest{`,
+ `SessionID:` + fmt.Sprintf("%v", this.SessionID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TasksMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TasksMessage{`,
+ `Tasks:` + strings.Replace(fmt.Sprintf("%v", this.Tasks), "Task", "Task", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *AssignmentsRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&AssignmentsRequest{`,
+ `SessionID:` + fmt.Sprintf("%v", this.SessionID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Assignment) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Assignment{`,
+ `Item:` + fmt.Sprintf("%v", this.Item) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Assignment_Task) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Assignment_Task{`,
+ `Task:` + strings.Replace(fmt.Sprintf("%v", this.Task), "Task", "Task", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Assignment_Secret) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Assignment_Secret{`,
+ `Secret:` + strings.Replace(fmt.Sprintf("%v", this.Secret), "Secret", "Secret", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Assignment_Config) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Assignment_Config{`,
+ `Config:` + strings.Replace(fmt.Sprintf("%v", this.Config), "Config", "Config", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *AssignmentChange) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&AssignmentChange{`,
+ `Assignment:` + strings.Replace(fmt.Sprintf("%v", this.Assignment), "Assignment", "Assignment", 1) + `,`,
+ `Action:` + fmt.Sprintf("%v", this.Action) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *AssignmentsMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&AssignmentsMessage{`,
+ `Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+ `AppliesTo:` + fmt.Sprintf("%v", this.AppliesTo) + `,`,
+ `ResultsIn:` + fmt.Sprintf("%v", this.ResultsIn) + `,`,
+ `Changes:` + strings.Replace(fmt.Sprintf("%v", this.Changes), "AssignmentChange", "AssignmentChange", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringDispatcher(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *SessionRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SessionRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SessionRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Description == nil {
+ m.Description = &NodeDescription{}
+ }
+ if err := m.Description.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SessionID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SessionID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SessionMessage) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SessionMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SessionMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SessionID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SessionID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Node", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Node == nil {
+ m.Node = &Node{}
+ }
+ if err := m.Node.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Managers", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Managers = append(m.Managers, &WeightedPeer{})
+ if err := m.Managers[len(m.Managers)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NetworkBootstrapKeys", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NetworkBootstrapKeys = append(m.NetworkBootstrapKeys, &EncryptionKey{})
+ if err := m.NetworkBootstrapKeys[len(m.NetworkBootstrapKeys)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RootCA", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.RootCA = append(m.RootCA[:0], dAtA[iNdEx:postIndex]...)
+ if m.RootCA == nil {
+ m.RootCA = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *HeartbeatRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: HeartbeatRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: HeartbeatRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SessionID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SessionID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *HeartbeatResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: HeartbeatResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: HeartbeatResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Period", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := github_com_gogo_protobuf_types.StdDurationUnmarshal(&m.Period, dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateTaskStatusRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateTaskStatusRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateTaskStatusRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SessionID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SessionID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Updates", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Updates = append(m.Updates, &UpdateTaskStatusRequest_TaskStatusUpdate{})
+ if err := m.Updates[len(m.Updates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateTaskStatusRequest_TaskStatusUpdate) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: TaskStatusUpdate: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: TaskStatusUpdate: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TaskID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TaskID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Status == nil {
+ m.Status = &TaskStatus{}
+ }
+ if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateTaskStatusResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateTaskStatusResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateTaskStatusResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *TasksRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: TasksRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: TasksRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SessionID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SessionID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *TasksMessage) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: TasksMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: TasksMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Tasks", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Tasks = append(m.Tasks, &Task{})
+ if err := m.Tasks[len(m.Tasks)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *AssignmentsRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: AssignmentsRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: AssignmentsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SessionID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SessionID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Assignment) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Assignment: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Assignment: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Task", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Task{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Item = &Assignment_Task{v}
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Secret", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Secret{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Item = &Assignment_Secret{v}
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Config{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Item = &Assignment_Config{v}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *AssignmentChange) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: AssignmentChange: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: AssignmentChange: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Assignment", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Assignment == nil {
+ m.Assignment = &Assignment{}
+ }
+ if err := m.Assignment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Action", wireType)
+ }
+ m.Action = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Action |= (AssignmentChange_AssignmentAction(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *AssignmentsMessage) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: AssignmentsMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: AssignmentsMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Type |= (AssignmentsMessage_Type(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field AppliesTo", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.AppliesTo = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ResultsIn", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ResultsIn = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Changes", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Changes = append(m.Changes, &AssignmentChange{})
+ if err := m.Changes[len(m.Changes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDispatcher(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDispatcher
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipDispatcher(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthDispatcher
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowDispatcher
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipDispatcher(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthDispatcher = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowDispatcher = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("dispatcher.proto", fileDescriptorDispatcher) }
+
+var fileDescriptorDispatcher = []byte{
+ // 983 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0x4f, 0x6f, 0x1b, 0x45,
+ 0x14, 0xf7, 0x38, 0xce, 0x26, 0x7e, 0x4e, 0x82, 0x19, 0xaa, 0xb0, 0xac, 0x54, 0xc7, 0x6c, 0x68,
+ 0x14, 0xa9, 0x61, 0x53, 0xcc, 0x9f, 0x0b, 0x51, 0x20, 0x8e, 0x2d, 0xc5, 0x6a, 0x93, 0x46, 0x13,
+ 0xb7, 0x3d, 0x5a, 0x6b, 0xef, 0x74, 0xb3, 0x38, 0xde, 0x59, 0x76, 0xc6, 0x2d, 0x3e, 0x20, 0x71,
+ 0xa0, 0x12, 0xe2, 0x84, 0x38, 0x45, 0x42, 0x7c, 0x05, 0xc4, 0xc7, 0x88, 0x38, 0x71, 0xe4, 0x14,
+ 0xa8, 0x3f, 0x00, 0x1f, 0x80, 0x13, 0xda, 0xd9, 0x59, 0xdb, 0x75, 0xed, 0xd4, 0xc9, 0xc9, 0x9e,
+ 0x37, 0xbf, 0xdf, 0x9b, 0xdf, 0xbc, 0xf7, 0xdb, 0x37, 0x90, 0x77, 0x3c, 0x1e, 0xd8, 0xa2, 0x75,
+ 0x4a, 0x43, 0x2b, 0x08, 0x99, 0x60, 0x18, 0x3b, 0xac, 0xd5, 0xa6, 0xa1, 0xc5, 0x9f, 0xdb, 0x61,
+ 0xa7, 0xed, 0x09, 0xeb, 0xd9, 0x47, 0x46, 0x4e, 0xf4, 0x02, 0xca, 0x63, 0x80, 0xb1, 0xcc, 0x9a,
+ 0x5f, 0xd1, 0x96, 0x48, 0x96, 0xb7, 0x5c, 0xe6, 0x32, 0xf9, 0x77, 0x3b, 0xfa, 0xa7, 0xa2, 0xef,
+ 0x04, 0x67, 0x5d, 0xd7, 0xf3, 0xb7, 0xe3, 0x1f, 0x15, 0x2c, 0xb8, 0x8c, 0xb9, 0x67, 0x74, 0x5b,
+ 0xae, 0x9a, 0xdd, 0xa7, 0xdb, 0x4e, 0x37, 0xb4, 0x85, 0xc7, 0xd4, 0xbe, 0xf9, 0x02, 0xc1, 0xca,
+ 0x09, 0xe5, 0xdc, 0x63, 0x3e, 0xa1, 0x5f, 0x77, 0x29, 0x17, 0xb8, 0x0a, 0x39, 0x87, 0xf2, 0x56,
+ 0xe8, 0x05, 0x11, 0x4e, 0x47, 0x45, 0xb4, 0x99, 0x2b, 0xad, 0x5b, 0xaf, 0x6b, 0xb4, 0x8e, 0x98,
+ 0x43, 0x2b, 0x43, 0x28, 0x19, 0xe5, 0xe1, 0x2d, 0x00, 0x1e, 0x27, 0x6e, 0x78, 0x8e, 0x9e, 0x2e,
+ 0xa2, 0xcd, 0x6c, 0x79, 0xb9, 0x7f, 0xb9, 0x96, 0x55, 0xc7, 0xd5, 0x2a, 0x24, 0xab, 0x00, 0x35,
+ 0xc7, 0xfc, 0x25, 0x3d, 0xd0, 0x71, 0x48, 0x39, 0xb7, 0x5d, 0x3a, 0x96, 0x00, 0x5d, 0x9d, 0x00,
+ 0x6f, 0x41, 0xc6, 0x67, 0x0e, 0x95, 0x07, 0xe5, 0x4a, 0xfa, 0x34, 0xb9, 0x44, 0xa2, 0xf0, 0x0e,
+ 0x2c, 0x76, 0x6c, 0xdf, 0x76, 0x69, 0xc8, 0xf5, 0xb9, 0xe2, 0xdc, 0x66, 0xae, 0x54, 0x9c, 0xc4,
+ 0x78, 0x42, 0x3d, 0xf7, 0x54, 0x50, 0xe7, 0x98, 0xd2, 0x90, 0x0c, 0x18, 0xf8, 0x09, 0xac, 0xfa,
+ 0x54, 0x3c, 0x67, 0x61, 0xbb, 0xd1, 0x64, 0x4c, 0x70, 0x11, 0xda, 0x41, 0xa3, 0x4d, 0x7b, 0x5c,
+ 0xcf, 0xc8, 0x5c, 0xef, 0x4f, 0xca, 0x55, 0xf5, 0x5b, 0x61, 0x4f, 0x96, 0xe6, 0x3e, 0xed, 0x91,
+ 0x5b, 0x2a, 0x41, 0x39, 0xe1, 0xdf, 0xa7, 0x3d, 0x8e, 0x57, 0x41, 0x23, 0x8c, 0x89, 0xfd, 0x3d,
+ 0x7d, 0xbe, 0x88, 0x36, 0x97, 0x88, 0x5a, 0x99, 0x5f, 0x42, 0xfe, 0x80, 0xda, 0xa1, 0x68, 0x52,
+ 0x5b, 0x24, 0x6d, 0xba, 0x56, 0x79, 0xcc, 0x63, 0x78, 0x7b, 0x24, 0x03, 0x0f, 0x98, 0xcf, 0x29,
+ 0xfe, 0x1c, 0xb4, 0x80, 0x86, 0x1e, 0x73, 0x54, 0x93, 0xdf, 0xb3, 0x62, 0xb7, 0x58, 0x89, 0x5b,
+ 0xac, 0x8a, 0x72, 0x4b, 0x79, 0xf1, 0xe2, 0x72, 0x2d, 0x75, 0xfe, 0xf7, 0x1a, 0x22, 0x8a, 0x62,
+ 0xfe, 0x94, 0x86, 0x77, 0x1f, 0x05, 0x8e, 0x2d, 0x68, 0xdd, 0xe6, 0xed, 0x13, 0x61, 0x8b, 0x2e,
+ 0xbf, 0x91, 0x36, 0xfc, 0x18, 0x16, 0xba, 0x32, 0x51, 0xd2, 0x8b, 0x9d, 0x49, 0xf5, 0x9b, 0x72,
+ 0x96, 0x35, 0x8c, 0xc4, 0x08, 0x92, 0x24, 0x33, 0x18, 0xe4, 0xc7, 0x37, 0xf1, 0x3a, 0x2c, 0x08,
+ 0x9b, 0xb7, 0x87, 0xb2, 0xa0, 0x7f, 0xb9, 0xa6, 0x45, 0xb0, 0x5a, 0x85, 0x68, 0xd1, 0x56, 0xcd,
+ 0xc1, 0x9f, 0x81, 0xc6, 0x25, 0x49, 0xb9, 0xa9, 0x30, 0x49, 0xcf, 0x88, 0x12, 0x85, 0x36, 0x0d,
+ 0xd0, 0x5f, 0x57, 0x19, 0xd7, 0xda, 0xdc, 0x81, 0xa5, 0x28, 0x7a, 0xb3, 0x12, 0x99, 0xbb, 0x8a,
+ 0x9d, 0x7c, 0x1b, 0x16, 0xcc, 0x47, 0x5a, 0xb9, 0x8e, 0x64, 0xc1, 0xf4, 0x69, 0x02, 0x49, 0x0c,
+ 0x33, 0xcb, 0x80, 0xf7, 0x38, 0xf7, 0x5c, 0xbf, 0x43, 0x7d, 0x71, 0x43, 0x0d, 0xbf, 0x23, 0x80,
+ 0x61, 0x12, 0x6c, 0x41, 0x26, 0xca, 0xad, 0xac, 0x33, 0x55, 0xc1, 0x41, 0x8a, 0x48, 0x1c, 0xfe,
+ 0x04, 0x34, 0x4e, 0x5b, 0x21, 0x15, 0xaa, 0xa8, 0xc6, 0x24, 0xc6, 0x89, 0x44, 0x1c, 0xa4, 0x88,
+ 0xc2, 0x46, 0xac, 0x16, 0xf3, 0x9f, 0x7a, 0xae, 0x3e, 0x37, 0x9d, 0xb5, 0x2f, 0x11, 0x11, 0x2b,
+ 0xc6, 0x96, 0x35, 0xc8, 0x78, 0x82, 0x76, 0xcc, 0x17, 0x69, 0xc8, 0x0f, 0x25, 0xef, 0x9f, 0xda,
+ 0xbe, 0x4b, 0xf1, 0x2e, 0x80, 0x3d, 0x88, 0x29, 0xf9, 0x13, 0x3b, 0x3c, 0x64, 0x92, 0x11, 0x06,
+ 0x3e, 0x04, 0xcd, 0x6e, 0xc9, 0xd1, 0x18, 0x5d, 0x64, 0xa5, 0xf4, 0xe9, 0xd5, 0xdc, 0xf8, 0xd4,
+ 0x91, 0xc0, 0x9e, 0x24, 0x13, 0x95, 0xc4, 0x6c, 0x8e, 0x4a, 0x8c, 0xf7, 0xf0, 0x06, 0x68, 0x8f,
+ 0x8e, 0x2b, 0x7b, 0xf5, 0x6a, 0x3e, 0x65, 0x18, 0x3f, 0xfe, 0x5a, 0x5c, 0x1d, 0x47, 0x28, 0x37,
+ 0x6f, 0x80, 0x46, 0xaa, 0x87, 0x0f, 0x1f, 0x57, 0xf3, 0x68, 0x32, 0x8e, 0xd0, 0x0e, 0x7b, 0x46,
+ 0xcd, 0xff, 0xd0, 0x2b, 0xfd, 0x4f, 0x5c, 0xf4, 0x05, 0x64, 0xa2, 0x57, 0x46, 0xd6, 0x60, 0xa5,
+ 0x74, 0xf7, 0xea, 0x7b, 0x24, 0x2c, 0xab, 0xde, 0x0b, 0x28, 0x91, 0x44, 0x7c, 0x1b, 0xc0, 0x0e,
+ 0x82, 0x33, 0x8f, 0xf2, 0x86, 0x60, 0xf1, 0x8c, 0x27, 0x59, 0x15, 0xa9, 0xb3, 0x68, 0x3b, 0xa4,
+ 0xbc, 0x7b, 0x26, 0x78, 0xc3, 0xf3, 0x65, 0x03, 0xb3, 0x24, 0xab, 0x22, 0x35, 0x1f, 0xef, 0xc2,
+ 0x42, 0x4b, 0x16, 0x27, 0x99, 0x9b, 0x1f, 0xcc, 0x52, 0x49, 0x92, 0x90, 0xcc, 0x3b, 0x90, 0x89,
+ 0xb4, 0xe0, 0x25, 0x58, 0xdc, 0x7f, 0x78, 0x78, 0xfc, 0xa0, 0x1a, 0xd5, 0x0b, 0xbf, 0x05, 0xb9,
+ 0xda, 0xd1, 0x3e, 0xa9, 0x1e, 0x56, 0x8f, 0xea, 0x7b, 0x0f, 0xf2, 0xa8, 0x74, 0x3e, 0x0f, 0x50,
+ 0x19, 0x3c, 0xb9, 0xf8, 0x1b, 0x58, 0x50, 0xf6, 0xc6, 0xe6, 0x64, 0x0b, 0x8e, 0xbe, 0x86, 0xc6,
+ 0x55, 0x18, 0x55, 0x11, 0x73, 0xfd, 0x8f, 0xdf, 0xfe, 0x3d, 0x4f, 0xdf, 0x86, 0x25, 0x89, 0xf9,
+ 0x30, 0x9a, 0xeb, 0x34, 0x84, 0xe5, 0x78, 0xa5, 0x5e, 0x8d, 0x7b, 0x08, 0x7f, 0x0b, 0xd9, 0xc1,
+ 0x0c, 0xc6, 0x13, 0xef, 0x3a, 0x3e, 0xe4, 0x8d, 0x3b, 0x6f, 0x40, 0xa9, 0xe1, 0x32, 0x8b, 0x00,
+ 0xfc, 0x33, 0x82, 0xfc, 0xf8, 0x78, 0xc2, 0x77, 0xaf, 0x31, 0x6a, 0x8d, 0xad, 0xd9, 0xc0, 0xd7,
+ 0x11, 0xd5, 0x85, 0x79, 0x39, 0xd8, 0x70, 0x71, 0xda, 0x00, 0x19, 0x9c, 0x3e, 0x1d, 0x91, 0xf4,
+ 0x61, 0x63, 0x86, 0x13, 0x7f, 0x48, 0xa3, 0x7b, 0x08, 0x7f, 0x8f, 0x20, 0x37, 0x62, 0x6d, 0xbc,
+ 0xf1, 0x06, 0xef, 0x27, 0x1a, 0x36, 0x66, 0xfb, 0x46, 0x66, 0x74, 0x44, 0x59, 0xbf, 0x78, 0x59,
+ 0x48, 0xfd, 0xf5, 0xb2, 0x90, 0xfa, 0xae, 0x5f, 0x40, 0x17, 0xfd, 0x02, 0xfa, 0xb3, 0x5f, 0x40,
+ 0xff, 0xf4, 0x0b, 0xa8, 0xa9, 0xc9, 0x27, 0xf8, 0xe3, 0xff, 0x03, 0x00, 0x00, 0xff, 0xff, 0x6c,
+ 0xba, 0x38, 0xbd, 0x2d, 0x0a, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/dispatcher.proto b/vendor/github.com/docker/swarmkit/api/dispatcher.proto
new file mode 100644
index 0000000..505a80b
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/dispatcher.proto
@@ -0,0 +1,218 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "types.proto";
+import "objects.proto";
+import "gogoproto/gogo.proto";
+import "plugin/plugin.proto";
+import "google/protobuf/duration.proto";
+
+// Dispatcher is the API provided by a manager group for agents to connect to. Agents
+// connect to this service to receive task assignments and report status.
+//
+// API methods on this service are used only by agent nodes.
+service Dispatcher { // maybe dispatch, al likes this
+ // Session starts an agent session with the dispatcher. The session is
+ // started after the first SessionMessage is received.
+ //
+ // Once started, the agent is controlled with a stream of SessionMessage.
+ // Agents should list on the stream at all times for instructions.
+ rpc Session(SessionRequest) returns (stream SessionMessage) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-worker" roles: "swarm-manager" };
+ };
+
+ // Heartbeat is heartbeat method for nodes. It returns new TTL in response.
+ // Node should send new heartbeat earlier than now + TTL, otherwise it will
+ // be deregistered from dispatcher and its status will be updated to NodeStatus_DOWN
+ rpc Heartbeat(HeartbeatRequest) returns (HeartbeatResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-worker" roles: "swarm-manager" };
+ };
+
+ // UpdateTaskStatus updates status of task. Node should send such updates
+ // on every status change of its tasks.
+ //
+ // Whether receiving batch updates or single status updates, this method
+ // should be accepting. Errors should only be returned if the entire update
+ // should be retried, due to data loss or other problems.
+ //
+ // If a task is unknown the dispatcher, the status update should be
+ // accepted regardless.
+ rpc UpdateTaskStatus(UpdateTaskStatusRequest) returns (UpdateTaskStatusResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-worker" roles: "swarm-manager" };
+ };
+
+ // Tasks is a stream of tasks state for node. Each message contains full list
+ // of tasks which should be run on node, if task is not present in that list,
+ // it should be terminated.
+ rpc Tasks(TasksRequest) returns (stream TasksMessage) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-worker" roles: "swarm-manager" };
+ option deprecated = true;
+ };
+
+ // Assignments is a stream of assignments such as tasks and secrets for node.
+ // The first message in the stream contains all of the tasks and secrets
+ // that are relevant to the node. Future messages in the stream are updates to
+ // the set of assignments.
+ rpc Assignments(AssignmentsRequest) returns (stream AssignmentsMessage) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-worker" roles: "swarm-manager" };
+ };
+}
+
+// SessionRequest starts a session.
+message SessionRequest {
+ NodeDescription description = 1;
+ // SessionID can be provided to attempt resuming an existing session. If the
+ // SessionID is empty or invalid, a new SessionID will be assigned.
+ //
+ // See SessionMessage.SessionID for details.
+ string session_id = 2;
+}
+
+// SessionMessage instructs an agent on various actions as part of the current
+// session. An agent should act immediately on the contents.
+message SessionMessage {
+ // SessionID is allocated after a successful registration. It should be
+ // used on all RPC calls after registration. A dispatcher may choose to
+ // change the SessionID, at which time an agent must re-register and obtain
+ // a new one.
+ //
+ // All Dispatcher calls after register should include the SessionID. If the
+ // Dispatcher so chooses, it may reject the call with an InvalidArgument
+ // error code, at which time the agent should call Register to start a new
+ // session.
+ //
+ // As a rule, once an agent has a SessionID, it should never save it to
+ // disk or try to otherwise reuse. If the agent loses its SessionID, it
+ // must start a new session through a call to Register. A Dispatcher may
+ // choose to reuse the SessionID, if it sees fit, but it is not advised.
+ //
+ // The actual implementation of the SessionID is Dispatcher specific and
+ // should be treated as opaque by agents.
+ //
+ // From a Dispatcher perspective, there are many ways to use the SessionID
+ // to ensure uniqueness of a set of client RPC calls. One method is to keep
+ // the SessionID unique to every call to Register in a single Dispatcher
+ // instance. This ensures that the SessionID represents the unique
+ // session from a single Agent to Manager. If the Agent restarts, we
+ // allocate a new session, since the restarted Agent is not aware of the
+ // new SessionID.
+ //
+ // The most compelling use case is to support duplicate node detection. If
+ // one clones a virtual machine, including certificate material, two nodes
+ // may end up with the same identity. This can also happen if two identical
+ // agent processes are coming from the same node. If the SessionID is
+ // replicated through the cluster, we can immediately detect the condition
+ // and address it.
+ //
+ // Extending from the case above, we can actually detect a compromised
+ // identity. Coupled with provisions to rebuild node identity, we can ban
+ // the compromised node identity and have the nodes re-authenticate and
+ // build a new identity. At this time, an administrator can then
+ // re-authorize the compromised nodes, if it was a mistake or ensure that a
+ // misbehaved node can no longer connect to the cluster.
+ //
+ // We considered placing this field in a GRPC header. Because this is a
+ // critical feature of the protocol, we thought it should be represented
+ // directly in the RPC message set.
+ string session_id = 1;
+
+ // Node identifies the registering node.
+ Node node = 2;
+
+ // Managers provides a weight list of alternative dispatchers
+ repeated WeightedPeer managers = 3;
+
+ // Symmetric encryption key distributed by the lead manager. Used by agents
+ // for securing network bootstrapping and communication.
+ repeated EncryptionKey network_bootstrap_keys = 4;
+
+ // Which root certificates to trust
+ bytes RootCA = 5;
+}
+
+// HeartbeatRequest provides identifying properties for a single heartbeat.
+message HeartbeatRequest {
+ string session_id = 1;
+}
+
+message HeartbeatResponse {
+ // Period is the duration to wait before sending the next heartbeat.
+ // Well-behaved agents should update this on every heartbeat round trip.
+ google.protobuf.Duration period = 1 [(gogoproto.stdduration) = true, (gogoproto.nullable) = false];
+}
+
+message UpdateTaskStatusRequest {
+ // Tasks should contain all statuses for running tasks. Only the status
+ // field must be set. The spec is not required.
+ string session_id = 1;
+
+ message TaskStatusUpdate {
+ string task_id = 1;
+ TaskStatus status = 2;
+ }
+
+ repeated TaskStatusUpdate updates = 3;
+}
+
+message UpdateTaskStatusResponse{
+ // void
+}
+
+message TasksRequest {
+ string session_id = 1;
+}
+
+message TasksMessage {
+ // Tasks is the set of tasks that should be running on the node.
+ // Tasks outside of this set running on the node should be terminated.
+ repeated Task tasks = 1;
+}
+
+message AssignmentsRequest {
+ string session_id = 1;
+}
+
+message Assignment {
+ oneof item {
+ Task task = 1;
+ Secret secret = 2;
+ Config config = 3;
+ }
+}
+
+message AssignmentChange {
+ enum AssignmentAction {
+ UPDATE = 0 [(gogoproto.enumvalue_customname) = "AssignmentActionUpdate"];
+ REMOVE = 1 [(gogoproto.enumvalue_customname) = "AssignmentActionRemove"];
+ }
+
+ Assignment assignment = 1;
+ AssignmentAction action = 2;
+}
+
+message AssignmentsMessage {
+ // AssignmentType specifies whether this assignment message carries
+ // the full state, or is an update to an existing state.
+ enum Type {
+ COMPLETE = 0;
+ INCREMENTAL = 1;
+ }
+
+ Type type = 1;
+
+ // AppliesTo references the previous ResultsIn value, to chain
+ // incremental updates together. For the first update in a stream,
+ // AppliesTo is empty. If AppliesTo does not match the previously
+ // received ResultsIn, the consumer of the stream should start a new
+ // Assignments stream to re-sync.
+ string applies_to = 2;
+
+ // ResultsIn identifies the result of this assignments message, to
+ // match against the next message's AppliesTo value and protect
+ // against missed messages.
+ string results_in = 3;
+
+ // AssignmentChange is a set of changes to apply on this node.
+ repeated AssignmentChange changes = 4;
+}
diff --git a/vendor/github.com/docker/swarmkit/api/equality/equality.go b/vendor/github.com/docker/swarmkit/api/equality/equality.go
new file mode 100644
index 0000000..522c719
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/equality/equality.go
@@ -0,0 +1,67 @@
+package equality
+
+import (
+ "crypto/subtle"
+ "reflect"
+
+ "github.com/docker/swarmkit/api"
+)
+
+// TasksEqualStable returns true if the tasks are functionally equal, ignoring status,
+// version and other superfluous fields.
+//
+// This used to decide whether or not to propagate a task update to a controller.
+func TasksEqualStable(a, b *api.Task) bool {
+ // shallow copy
+ copyA, copyB := *a, *b
+
+ copyA.Status, copyB.Status = api.TaskStatus{}, api.TaskStatus{}
+ copyA.Meta, copyB.Meta = api.Meta{}, api.Meta{}
+
+ return reflect.DeepEqual(&copyA, &copyB)
+}
+
+// TaskStatusesEqualStable compares the task status excluding timestamp fields.
+func TaskStatusesEqualStable(a, b *api.TaskStatus) bool {
+ copyA, copyB := *a, *b
+
+ copyA.Timestamp, copyB.Timestamp = nil, nil
+ return reflect.DeepEqual(&copyA, &copyB)
+}
+
+// RootCAEqualStable compares RootCAs, excluding join tokens, which are randomly generated
+func RootCAEqualStable(a, b *api.RootCA) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+
+ var aRotationKey, bRotationKey []byte
+ if a.RootRotation != nil {
+ aRotationKey = a.RootRotation.CAKey
+ }
+ if b.RootRotation != nil {
+ bRotationKey = b.RootRotation.CAKey
+ }
+ if subtle.ConstantTimeCompare(a.CAKey, b.CAKey) != 1 || subtle.ConstantTimeCompare(aRotationKey, bRotationKey) != 1 {
+ return false
+ }
+
+ copyA, copyB := *a, *b
+ copyA.JoinTokens, copyB.JoinTokens = api.JoinTokens{}, api.JoinTokens{}
+ return reflect.DeepEqual(copyA, copyB)
+}
+
+// ExternalCAsEqualStable compares lists of external CAs and determines whether they are equal.
+func ExternalCAsEqualStable(a, b []*api.ExternalCA) bool {
+ // because DeepEqual will treat an empty list and a nil list differently, we want to manually check this first
+ if len(a) == 0 && len(b) == 0 {
+ return true
+ }
+ // The assumption is that each individual api.ExternalCA within both lists are created from deserializing from a
+ // protobuf, so no special affordances are made to treat a nil map and empty map in the Options field of an
+ // api.ExternalCA as equivalent.
+ return reflect.DeepEqual(a, b)
+}
diff --git a/vendor/github.com/docker/swarmkit/api/gen.go b/vendor/github.com/docker/swarmkit/api/gen.go
new file mode 100644
index 0000000..5a0bd33
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/gen.go
@@ -0,0 +1,3 @@
+package api
+
+//go:generate protoc -I.:../protobuf:../vendor:../vendor/github.com/gogo/protobuf --gogoswarm_out=plugins=grpc+deepcopy+storeobject+raftproxy+authenticatedwrapper,import_path=github.com/docker/swarmkit/api,Mgogoproto/gogo.proto=github.com/gogo/protobuf/gogoproto,Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor,Mplugin/plugin.proto=github.com/docker/swarmkit/protobuf/plugin,Mgoogle/protobuf/duration.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/any.proto=github.com/gogo/protobuf/types:. types.proto specs.proto objects.proto control.proto dispatcher.proto ca.proto snapshot.proto raft.proto health.proto resource.proto logbroker.proto watch.proto
diff --git a/vendor/github.com/docker/swarmkit/api/genericresource/helpers.go b/vendor/github.com/docker/swarmkit/api/genericresource/helpers.go
new file mode 100644
index 0000000..f9c22ac
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/genericresource/helpers.go
@@ -0,0 +1,111 @@
+package genericresource
+
+import (
+ "github.com/docker/swarmkit/api"
+)
+
+// NewSet creates a set object
+func NewSet(key string, vals ...string) []*api.GenericResource {
+ rs := make([]*api.GenericResource, 0, len(vals))
+
+ for _, v := range vals {
+ rs = append(rs, NewString(key, v))
+ }
+
+ return rs
+}
+
+// NewString creates a String resource
+func NewString(key, val string) *api.GenericResource {
+ return &api.GenericResource{
+ Resource: &api.GenericResource_Str{
+ Str: &api.GenericString{
+ Kind: key,
+ Value: val,
+ },
+ },
+ }
+}
+
+// NewDiscrete creates a Discrete resource
+func NewDiscrete(key string, val int64) *api.GenericResource {
+ return &api.GenericResource{
+ Resource: &api.GenericResource_Discrete{
+ Discrete: &api.GenericDiscrete{
+ Kind: key,
+ Value: val,
+ },
+ },
+ }
+}
+
+// GetResource returns resources from the "resources" parameter matching the kind key
+func GetResource(kind string, resources []*api.GenericResource) []*api.GenericResource {
+ var res []*api.GenericResource
+
+ for _, r := range resources {
+ if Kind(r) != kind {
+ continue
+ }
+
+ res = append(res, r)
+ }
+
+ return res
+}
+
+// ConsumeNodeResources removes "res" from nodeAvailableResources
+func ConsumeNodeResources(nodeAvailableResources *[]*api.GenericResource, res []*api.GenericResource) {
+ if nodeAvailableResources == nil {
+ return
+ }
+
+ w := 0
+
+loop:
+ for _, na := range *nodeAvailableResources {
+ for _, r := range res {
+ if Kind(na) != Kind(r) {
+ continue
+ }
+
+ if remove(na, r) {
+ continue loop
+ }
+ // If this wasn't the right element then
+ // we need to continue
+ }
+
+ (*nodeAvailableResources)[w] = na
+ w++
+ }
+
+ *nodeAvailableResources = (*nodeAvailableResources)[:w]
+}
+
+// Returns true if the element is to be removed from the list
+func remove(na, r *api.GenericResource) bool {
+ switch tr := r.Resource.(type) {
+ case *api.GenericResource_Discrete:
+ if na.GetDiscrete() == nil {
+ return false // Type change, ignore
+ }
+
+ na.GetDiscrete().Value -= tr.Discrete.Value
+ if na.GetDiscrete().Value <= 0 {
+ return true
+ }
+ case *api.GenericResource_Str:
+ if na.GetStr() == nil {
+ return false // Type change, ignore
+ }
+
+ if tr.Str.Value != na.GetStr().Value {
+ return false // not the right item, ignore
+ }
+
+ return true
+ }
+
+ return false
+}
diff --git a/vendor/github.com/docker/swarmkit/api/genericresource/parse.go b/vendor/github.com/docker/swarmkit/api/genericresource/parse.go
new file mode 100644
index 0000000..de30908
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/genericresource/parse.go
@@ -0,0 +1,47 @@
+package genericresource
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+)
+
+func newParseError(format string, args ...interface{}) error {
+ return fmt.Errorf("could not parse GenericResource: "+format, args...)
+}
+
+// Parse parses the GenericResource resources given by the arguments
+func Parse(cmd string) ([]*api.GenericResource, error) {
+ var rs []*api.GenericResource
+
+ for _, term := range strings.Split(cmd, ";") {
+ kva := strings.Split(term, "=")
+ if len(kva) != 2 {
+ return nil, newParseError("incorrect term %s, missing '=' or malformed expr", term)
+ }
+
+ key := strings.TrimSpace(kva[0])
+ val := strings.TrimSpace(kva[1])
+
+ u, err := strconv.ParseInt(val, 10, 64)
+ if err == nil {
+ if u < 0 {
+ return nil, newParseError("cannot ask for negative resource %s", key)
+ }
+ rs = append(rs, NewDiscrete(key, u))
+ continue
+ }
+
+ if len(val) > 2 && val[0] == '{' && val[len(val)-1] == '}' {
+ val = val[1 : len(val)-1]
+ rs = append(rs, NewSet(key, strings.Split(val, ",")...)...)
+ continue
+ }
+
+ return nil, newParseError("could not parse expression '%s'", term)
+ }
+
+ return rs, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/api/genericresource/resource_management.go b/vendor/github.com/docker/swarmkit/api/genericresource/resource_management.go
new file mode 100644
index 0000000..217c520
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/genericresource/resource_management.go
@@ -0,0 +1,202 @@
+package genericresource
+
+import (
+ "fmt"
+ "github.com/docker/swarmkit/api"
+)
+
+// Claim assigns GenericResources to a task by taking them from the
+// node's GenericResource list and storing them in the task's available list
+func Claim(nodeAvailableResources, taskAssigned *[]*api.GenericResource,
+ taskReservations []*api.GenericResource) error {
+ var resSelected []*api.GenericResource
+
+ for _, res := range taskReservations {
+ tr := res.GetDiscrete()
+ if tr == nil {
+ return fmt.Errorf("task should only hold Discrete type")
+ }
+
+ // Select the resources
+ nrs, err := selectNodeResources(*nodeAvailableResources, tr)
+ if err != nil {
+ return err
+ }
+
+ resSelected = append(resSelected, nrs...)
+ }
+
+ ClaimResources(nodeAvailableResources, taskAssigned, resSelected)
+ return nil
+}
+
+// ClaimResources adds the specified resources to the task's list
+// and removes them from the node's generic resource list
+func ClaimResources(nodeAvailableResources, taskAssigned *[]*api.GenericResource,
+ resSelected []*api.GenericResource) {
+ *taskAssigned = append(*taskAssigned, resSelected...)
+ ConsumeNodeResources(nodeAvailableResources, resSelected)
+}
+
+func selectNodeResources(nodeRes []*api.GenericResource,
+ tr *api.GenericDiscrete) ([]*api.GenericResource, error) {
+ var nrs []*api.GenericResource
+
+ for _, res := range nodeRes {
+ if Kind(res) != tr.Kind {
+ continue
+ }
+
+ switch nr := res.Resource.(type) {
+ case *api.GenericResource_Discrete:
+ if nr.Discrete.Value >= tr.Value && tr.Value != 0 {
+ nrs = append(nrs, NewDiscrete(tr.Kind, tr.Value))
+ }
+
+ return nrs, nil
+ case *api.GenericResource_Str:
+ nrs = append(nrs, res.Copy())
+
+ if int64(len(nrs)) == tr.Value {
+ return nrs, nil
+ }
+ }
+ }
+
+ if len(nrs) == 0 {
+ return nil, fmt.Errorf("not enough resources available for task reservations: %+v", tr)
+ }
+
+ return nrs, nil
+}
+
+// Reclaim adds the resources taken by the task to the node's store
+func Reclaim(nodeAvailableResources *[]*api.GenericResource, taskAssigned, nodeRes []*api.GenericResource) error {
+ err := reclaimResources(nodeAvailableResources, taskAssigned)
+ if err != nil {
+ return err
+ }
+
+ sanitize(nodeRes, nodeAvailableResources)
+
+ return nil
+}
+
+func reclaimResources(nodeAvailableResources *[]*api.GenericResource, taskAssigned []*api.GenericResource) error {
+ // The node could have been updated
+ if nodeAvailableResources == nil {
+ return fmt.Errorf("node no longer has any resources")
+ }
+
+ for _, res := range taskAssigned {
+ switch tr := res.Resource.(type) {
+ case *api.GenericResource_Discrete:
+ nrs := GetResource(tr.Discrete.Kind, *nodeAvailableResources)
+
+ // If the resource went down to 0 it's no longer in the
+ // available list
+ if len(nrs) == 0 {
+ *nodeAvailableResources = append(*nodeAvailableResources, res.Copy())
+ }
+
+ if len(nrs) != 1 {
+ continue // Type change
+ }
+
+ nr := nrs[0].GetDiscrete()
+ if nr == nil {
+ continue // Type change
+ }
+
+ nr.Value += tr.Discrete.Value
+ case *api.GenericResource_Str:
+ *nodeAvailableResources = append(*nodeAvailableResources, res.Copy())
+ }
+ }
+
+ return nil
+}
+
+// sanitize checks that nodeAvailableResources does not add resources unknown
+// to the nodeSpec (nodeRes) or goes over the integer bound specified
+// by the spec.
+// Note this is because the user is able to update a node's resources
+func sanitize(nodeRes []*api.GenericResource, nodeAvailableResources *[]*api.GenericResource) {
+ // - We add the sanitized resources at the end, after
+ // having removed the elements from the list
+
+ // - When a set changes to a Discrete we also need
+ // to make sure that we don't add the Discrete multiple
+ // time hence, the need of a map to remember that
+ var sanitized []*api.GenericResource
+ kindSanitized := make(map[string]struct{})
+ w := 0
+
+ for _, na := range *nodeAvailableResources {
+ ok, nrs := sanitizeResource(nodeRes, na)
+ if !ok {
+ if _, ok = kindSanitized[Kind(na)]; ok {
+ continue
+ }
+
+ kindSanitized[Kind(na)] = struct{}{}
+ sanitized = append(sanitized, nrs...)
+
+ continue
+ }
+
+ (*nodeAvailableResources)[w] = na
+ w++
+ }
+
+ *nodeAvailableResources = (*nodeAvailableResources)[:w]
+ *nodeAvailableResources = append(*nodeAvailableResources, sanitized...)
+}
+
+// Returns true if the element is in nodeRes and "sane"
+// Returns false if the element isn't in nodeRes and "sane" and the element(s) that should be replacing it
+func sanitizeResource(nodeRes []*api.GenericResource, res *api.GenericResource) (ok bool, nrs []*api.GenericResource) {
+ switch na := res.Resource.(type) {
+ case *api.GenericResource_Discrete:
+ nrs := GetResource(na.Discrete.Kind, nodeRes)
+
+ // Type change or removed: reset
+ if len(nrs) != 1 {
+ return false, nrs
+ }
+
+ // Type change: reset
+ nr := nrs[0].GetDiscrete()
+ if nr == nil {
+ return false, nrs
+ }
+
+ // Amount change: reset
+ if na.Discrete.Value > nr.Value {
+ return false, nrs
+ }
+ case *api.GenericResource_Str:
+ nrs := GetResource(na.Str.Kind, nodeRes)
+
+ // Type change
+ if len(nrs) == 0 {
+ return false, nrs
+ }
+
+ for _, nr := range nrs {
+ // Type change: reset
+ if nr.GetDiscrete() != nil {
+ return false, nrs
+ }
+
+ if na.Str.Value == nr.GetStr().Value {
+ return true, nil
+ }
+ }
+
+ // Removed
+ return false, nil
+ }
+
+ return true, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/api/genericresource/string.go b/vendor/github.com/docker/swarmkit/api/genericresource/string.go
new file mode 100644
index 0000000..a353853
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/genericresource/string.go
@@ -0,0 +1,54 @@
+package genericresource
+
+import (
+ "strconv"
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+)
+
+func discreteToString(d *api.GenericResource_Discrete) string {
+ return strconv.FormatInt(d.Discrete.Value, 10)
+}
+
+// Kind returns the kind key as a string
+func Kind(res *api.GenericResource) string {
+ switch r := res.Resource.(type) {
+ case *api.GenericResource_Discrete:
+ return r.Discrete.Kind
+ case *api.GenericResource_Str:
+ return r.Str.Kind
+ }
+
+ return ""
+}
+
+// Value returns the value key as a string
+func Value(res *api.GenericResource) string {
+ switch res := res.Resource.(type) {
+ case *api.GenericResource_Discrete:
+ return discreteToString(res)
+ case *api.GenericResource_Str:
+ return res.Str.Value
+ }
+
+ return ""
+}
+
+// EnvFormat returns the environment string version of the resource
+func EnvFormat(res []*api.GenericResource, prefix string) []string {
+ envs := make(map[string][]string)
+ for _, v := range res {
+ key := Kind(v)
+ val := Value(v)
+ envs[key] = append(envs[key], val)
+ }
+
+ env := make([]string, 0, len(res))
+ for k, v := range envs {
+ k = strings.ToUpper(prefix + "_" + k)
+ env = append(env, k+"="+strings.Join(v, ","))
+ }
+
+ return env
+}
diff --git a/vendor/github.com/docker/swarmkit/api/genericresource/validate.go b/vendor/github.com/docker/swarmkit/api/genericresource/validate.go
new file mode 100644
index 0000000..98953e1
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/genericresource/validate.go
@@ -0,0 +1,84 @@
+package genericresource
+
+import (
+ "fmt"
+ "github.com/docker/swarmkit/api"
+)
+
+// ValidateTask validates that the task only uses integers
+// for generic resources
+func ValidateTask(resources *api.Resources) error {
+ for _, v := range resources.Generic {
+ if v.GetDiscrete() != nil {
+ continue
+ }
+
+ return fmt.Errorf("invalid argument for resource %s", Kind(v))
+ }
+
+ return nil
+}
+
+// HasEnough returns true if node can satisfy the task's GenericResource request
+func HasEnough(nodeRes []*api.GenericResource, taskRes *api.GenericResource) (bool, error) {
+ t := taskRes.GetDiscrete()
+ if t == nil {
+ return false, fmt.Errorf("task should only hold Discrete type")
+ }
+
+ if nodeRes == nil {
+ return false, nil
+ }
+
+ nrs := GetResource(t.Kind, nodeRes)
+ if len(nrs) == 0 {
+ return false, nil
+ }
+
+ switch nr := nrs[0].Resource.(type) {
+ case *api.GenericResource_Discrete:
+ if t.Value > nr.Discrete.Value {
+ return false, nil
+ }
+ case *api.GenericResource_Str:
+ if t.Value > int64(len(nrs)) {
+ return false, nil
+ }
+ }
+
+ return true, nil
+}
+
+// HasResource checks if there is enough "res" in the "resources" argument
+func HasResource(res *api.GenericResource, resources []*api.GenericResource) bool {
+ for _, r := range resources {
+ if Kind(res) != Kind(r) {
+ continue
+ }
+
+ switch rtype := r.Resource.(type) {
+ case *api.GenericResource_Discrete:
+ if res.GetDiscrete() == nil {
+ return false
+ }
+
+ if res.GetDiscrete().Value < rtype.Discrete.Value {
+ return false
+ }
+
+ return true
+ case *api.GenericResource_Str:
+ if res.GetStr() == nil {
+ return false
+ }
+
+ if res.GetStr().Value != rtype.Str.Value {
+ continue
+ }
+
+ return true
+ }
+ }
+
+ return false
+}
diff --git a/vendor/github.com/docker/swarmkit/api/health.pb.go b/vendor/github.com/docker/swarmkit/api/health.pb.go
new file mode 100644
index 0000000..500e45b
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/health.pb.go
@@ -0,0 +1,721 @@
+// Code generated by protoc-gen-gogo.
+// source: health.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+import _ "github.com/docker/swarmkit/protobuf/plugin"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+import raftselector "github.com/docker/swarmkit/manager/raftselector"
+import codes "google.golang.org/grpc/codes"
+import metadata "google.golang.org/grpc/metadata"
+import transport "google.golang.org/grpc/transport"
+import rafttime "time"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+type HealthCheckResponse_ServingStatus int32
+
+const (
+ HealthCheckResponse_UNKNOWN HealthCheckResponse_ServingStatus = 0
+ HealthCheckResponse_SERVING HealthCheckResponse_ServingStatus = 1
+ HealthCheckResponse_NOT_SERVING HealthCheckResponse_ServingStatus = 2
+)
+
+var HealthCheckResponse_ServingStatus_name = map[int32]string{
+ 0: "UNKNOWN",
+ 1: "SERVING",
+ 2: "NOT_SERVING",
+}
+var HealthCheckResponse_ServingStatus_value = map[string]int32{
+ "UNKNOWN": 0,
+ "SERVING": 1,
+ "NOT_SERVING": 2,
+}
+
+func (x HealthCheckResponse_ServingStatus) String() string {
+ return proto.EnumName(HealthCheckResponse_ServingStatus_name, int32(x))
+}
+func (HealthCheckResponse_ServingStatus) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorHealth, []int{1, 0}
+}
+
+type HealthCheckRequest struct {
+ Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"`
+}
+
+func (m *HealthCheckRequest) Reset() { *m = HealthCheckRequest{} }
+func (*HealthCheckRequest) ProtoMessage() {}
+func (*HealthCheckRequest) Descriptor() ([]byte, []int) { return fileDescriptorHealth, []int{0} }
+
+type HealthCheckResponse struct {
+ Status HealthCheckResponse_ServingStatus `protobuf:"varint,1,opt,name=status,proto3,enum=docker.swarmkit.v1.HealthCheckResponse_ServingStatus" json:"status,omitempty"`
+}
+
+func (m *HealthCheckResponse) Reset() { *m = HealthCheckResponse{} }
+func (*HealthCheckResponse) ProtoMessage() {}
+func (*HealthCheckResponse) Descriptor() ([]byte, []int) { return fileDescriptorHealth, []int{1} }
+
+func init() {
+ proto.RegisterType((*HealthCheckRequest)(nil), "docker.swarmkit.v1.HealthCheckRequest")
+ proto.RegisterType((*HealthCheckResponse)(nil), "docker.swarmkit.v1.HealthCheckResponse")
+ proto.RegisterEnum("docker.swarmkit.v1.HealthCheckResponse_ServingStatus", HealthCheckResponse_ServingStatus_name, HealthCheckResponse_ServingStatus_value)
+}
+
+type authenticatedWrapperHealthServer struct {
+ local HealthServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperHealthServer(local HealthServer, authorize func(context.Context, []string) error) HealthServer {
+ return &authenticatedWrapperHealthServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperHealthServer) Check(ctx context.Context, r *HealthCheckRequest) (*HealthCheckResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.Check(ctx, r)
+}
+
+func (m *HealthCheckRequest) Copy() *HealthCheckRequest {
+ if m == nil {
+ return nil
+ }
+ o := &HealthCheckRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *HealthCheckRequest) CopyFrom(src interface{}) {
+
+ o := src.(*HealthCheckRequest)
+ *m = *o
+}
+
+func (m *HealthCheckResponse) Copy() *HealthCheckResponse {
+ if m == nil {
+ return nil
+ }
+ o := &HealthCheckResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *HealthCheckResponse) CopyFrom(src interface{}) {
+
+ o := src.(*HealthCheckResponse)
+ *m = *o
+}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for Health service
+
+type HealthClient interface {
+ Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error)
+}
+
+type healthClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewHealthClient(cc *grpc.ClientConn) HealthClient {
+ return &healthClient{cc}
+}
+
+func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) {
+ out := new(HealthCheckResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Health/Check", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for Health service
+
+type HealthServer interface {
+ Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error)
+}
+
+func RegisterHealthServer(s *grpc.Server, srv HealthServer) {
+ s.RegisterService(&_Health_serviceDesc, srv)
+}
+
+func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(HealthCheckRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(HealthServer).Check(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Health/Check",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(HealthServer).Check(ctx, req.(*HealthCheckRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _Health_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.Health",
+ HandlerType: (*HealthServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "Check",
+ Handler: _Health_Check_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "health.proto",
+}
+
+func (m *HealthCheckRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *HealthCheckRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Service) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintHealth(dAtA, i, uint64(len(m.Service)))
+ i += copy(dAtA[i:], m.Service)
+ }
+ return i, nil
+}
+
+func (m *HealthCheckResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *HealthCheckResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Status != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintHealth(dAtA, i, uint64(m.Status))
+ }
+ return i, nil
+}
+
+func encodeFixed64Health(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Health(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintHealth(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+type raftProxyHealthServer struct {
+ local HealthServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyHealthServer(local HealthServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) HealthServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyHealthServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyHealthServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyHealthServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+func (p *raftProxyHealthServer) Check(ctx context.Context, r *HealthCheckRequest) (*HealthCheckResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.Check(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewHealthClient(conn).Check(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.Check(ctx, r)
+ }
+ return nil, err
+ }
+ return NewHealthClient(conn).Check(modCtx, r)
+ }
+ return resp, err
+}
+
+func (m *HealthCheckRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Service)
+ if l > 0 {
+ n += 1 + l + sovHealth(uint64(l))
+ }
+ return n
+}
+
+func (m *HealthCheckResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.Status != 0 {
+ n += 1 + sovHealth(uint64(m.Status))
+ }
+ return n
+}
+
+func sovHealth(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozHealth(x uint64) (n int) {
+ return sovHealth(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *HealthCheckRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&HealthCheckRequest{`,
+ `Service:` + fmt.Sprintf("%v", this.Service) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *HealthCheckResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&HealthCheckResponse{`,
+ `Status:` + fmt.Sprintf("%v", this.Status) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringHealth(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *HealthCheckRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowHealth
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: HealthCheckRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: HealthCheckRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Service", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowHealth
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthHealth
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Service = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipHealth(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthHealth
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *HealthCheckResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowHealth
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: HealthCheckResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: HealthCheckResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
+ }
+ m.Status = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowHealth
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Status |= (HealthCheckResponse_ServingStatus(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipHealth(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthHealth
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipHealth(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowHealth
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowHealth
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowHealth
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthHealth
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowHealth
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipHealth(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthHealth = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowHealth = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("health.proto", fileDescriptorHealth) }
+
+var fileDescriptorHealth = []byte{
+ // 287 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0xc9, 0x48, 0x4d, 0xcc,
+ 0x29, 0xc9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x4a, 0xc9, 0x4f, 0xce, 0x4e, 0x2d,
+ 0xd2, 0x2b, 0x2e, 0x4f, 0x2c, 0xca, 0xcd, 0xce, 0x2c, 0xd1, 0x2b, 0x33, 0x94, 0x12, 0x49, 0xcf,
+ 0x4f, 0xcf, 0x07, 0x4b, 0xeb, 0x83, 0x58, 0x10, 0x95, 0x52, 0xc2, 0x05, 0x39, 0xa5, 0xe9, 0x99,
+ 0x79, 0xfa, 0x10, 0x0a, 0x22, 0xa8, 0xa4, 0xc7, 0x25, 0xe4, 0x01, 0x36, 0xce, 0x39, 0x23, 0x35,
+ 0x39, 0x3b, 0x28, 0xb5, 0xb0, 0x34, 0xb5, 0xb8, 0x44, 0x48, 0x82, 0x8b, 0xbd, 0x38, 0xb5, 0xa8,
+ 0x2c, 0x33, 0x39, 0x55, 0x82, 0x51, 0x81, 0x51, 0x83, 0x33, 0x08, 0xc6, 0x55, 0x5a, 0xc0, 0xc8,
+ 0x25, 0x8c, 0xa2, 0xa1, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, 0xc8, 0x97, 0x8b, 0xad, 0xb8, 0x24,
+ 0xb1, 0xa4, 0xb4, 0x18, 0xac, 0x81, 0xcf, 0xc8, 0x54, 0x0f, 0xd3, 0x5d, 0x7a, 0x58, 0x34, 0xea,
+ 0x05, 0x83, 0x0c, 0xce, 0x4b, 0x0f, 0x06, 0x6b, 0x0e, 0x82, 0x1a, 0xa2, 0x64, 0xc5, 0xc5, 0x8b,
+ 0x22, 0x21, 0xc4, 0xcd, 0xc5, 0x1e, 0xea, 0xe7, 0xed, 0xe7, 0x1f, 0xee, 0x27, 0xc0, 0x00, 0xe2,
+ 0x04, 0xbb, 0x06, 0x85, 0x79, 0xfa, 0xb9, 0x0b, 0x30, 0x0a, 0xf1, 0x73, 0x71, 0xfb, 0xf9, 0x87,
+ 0xc4, 0xc3, 0x04, 0x98, 0x8c, 0x2a, 0xb9, 0xd8, 0x20, 0x16, 0x09, 0xe5, 0x73, 0xb1, 0x82, 0x2d,
+ 0x13, 0x52, 0x23, 0xe8, 0x1a, 0xb0, 0xbf, 0xa5, 0xd4, 0x89, 0x74, 0xb5, 0x92, 0xe8, 0xa9, 0x75,
+ 0xef, 0x66, 0x30, 0xf1, 0x73, 0xf1, 0x82, 0x15, 0xea, 0xe6, 0x26, 0xe6, 0x25, 0xa6, 0xa7, 0x16,
+ 0x39, 0x49, 0x9c, 0x78, 0x28, 0xc7, 0x70, 0xe3, 0xa1, 0x1c, 0x43, 0xc3, 0x23, 0x39, 0xc6, 0x13,
+ 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x31, 0x89, 0x0d, 0x1c, 0xdc,
+ 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x59, 0xcd, 0x52, 0xee, 0xbd, 0x01, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/health.proto b/vendor/github.com/docker/swarmkit/api/health.proto
new file mode 100644
index 0000000..5edb38b
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/health.proto
@@ -0,0 +1,34 @@
+syntax = "proto3";
+
+// See: https://github.com/grpc/grpc-go/blob/master/health/grpc_health_v1/health.proto
+//
+// We use the same health check service proto description defined in the gRPC documentation,
+// including the authorization check. This requires our own implementation of the health
+// package located in `manager/health`.
+//
+// For more infos, refer to:
+// https://github.com/grpc/grpc/blob/master/doc/health-checking.md
+
+package docker.swarmkit.v1;
+
+import "gogoproto/gogo.proto";
+import "plugin/plugin.proto";
+
+service Health {
+ rpc Check(HealthCheckRequest) returns (HealthCheckResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+}
+
+message HealthCheckRequest {
+ string service = 1;
+}
+
+message HealthCheckResponse {
+ enum ServingStatus {
+ UNKNOWN = 0;
+ SERVING = 1;
+ NOT_SERVING = 2;
+ }
+ ServingStatus status = 1;
+}
diff --git a/vendor/github.com/docker/swarmkit/api/logbroker.pb.go b/vendor/github.com/docker/swarmkit/api/logbroker.pb.go
new file mode 100644
index 0000000..6a22eca
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/logbroker.pb.go
@@ -0,0 +1,3416 @@
+// Code generated by protoc-gen-gogo.
+// source: logbroker.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+import google_protobuf "github.com/gogo/protobuf/types"
+import _ "github.com/docker/swarmkit/protobuf/plugin"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+import raftselector "github.com/docker/swarmkit/manager/raftselector"
+import codes "google.golang.org/grpc/codes"
+import metadata "google.golang.org/grpc/metadata"
+import transport "google.golang.org/grpc/transport"
+import rafttime "time"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// LogStream defines the stream from which the log message came.
+type LogStream int32
+
+const (
+ LogStreamUnknown LogStream = 0
+ LogStreamStdout LogStream = 1
+ LogStreamStderr LogStream = 2
+)
+
+var LogStream_name = map[int32]string{
+ 0: "LOG_STREAM_UNKNOWN",
+ 1: "LOG_STREAM_STDOUT",
+ 2: "LOG_STREAM_STDERR",
+}
+var LogStream_value = map[string]int32{
+ "LOG_STREAM_UNKNOWN": 0,
+ "LOG_STREAM_STDOUT": 1,
+ "LOG_STREAM_STDERR": 2,
+}
+
+func (x LogStream) String() string {
+ return proto.EnumName(LogStream_name, int32(x))
+}
+func (LogStream) EnumDescriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{0} }
+
+type LogSubscriptionOptions struct {
+ // Streams defines which log streams should be sent from the task source.
+ // Empty means send all the messages.
+ Streams []LogStream `protobuf:"varint,1,rep,name=streams,enum=docker.swarmkit.v1.LogStream" json:"streams,omitempty"`
+ // Follow instructs the publisher to continue sending log messages as they
+ // are produced, after satisfying the initial query.
+ Follow bool `protobuf:"varint,2,opt,name=follow,proto3" json:"follow,omitempty"`
+ // Tail defines how many messages relative to the log stream to send when
+ // starting the stream.
+ //
+ // Positive values will skip that number of messages from the start of the
+ // stream before publishing.
+ //
+ // Negative values will specify messages relative to the end of the stream,
+ // offset by one. We can say that the last (-n-1) lines are returned when n
+ // < 0. As reference, -1 would mean send no log lines (typically used with
+ // follow), -2 would return the last log line, -11 would return the last 10
+ // and so on.
+ //
+ // The default value of zero will return all logs.
+ //
+ // Note that this is very different from the Docker API.
+ Tail int64 `protobuf:"varint,3,opt,name=tail,proto3" json:"tail,omitempty"`
+ // Since indicates that only log messages produced after this timestamp
+ // should be sent.
+ // Note: can't use stdtime because this field is nullable.
+ Since *google_protobuf.Timestamp `protobuf:"bytes,4,opt,name=since" json:"since,omitempty"`
+}
+
+func (m *LogSubscriptionOptions) Reset() { *m = LogSubscriptionOptions{} }
+func (*LogSubscriptionOptions) ProtoMessage() {}
+func (*LogSubscriptionOptions) Descriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{0} }
+
+// LogSelector will match logs from ANY of the defined parameters.
+//
+// For the best effect, the client should use the least specific parameter
+// possible. For example, if they want to listen to all the tasks of a service,
+// they should use the service id, rather than specifying the individual tasks.
+type LogSelector struct {
+ ServiceIDs []string `protobuf:"bytes,1,rep,name=service_ids,json=serviceIds" json:"service_ids,omitempty"`
+ NodeIDs []string `protobuf:"bytes,2,rep,name=node_ids,json=nodeIds" json:"node_ids,omitempty"`
+ TaskIDs []string `protobuf:"bytes,3,rep,name=task_ids,json=taskIds" json:"task_ids,omitempty"`
+}
+
+func (m *LogSelector) Reset() { *m = LogSelector{} }
+func (*LogSelector) ProtoMessage() {}
+func (*LogSelector) Descriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{1} }
+
+// LogContext marks the context from which a log message was generated.
+type LogContext struct {
+ ServiceID string `protobuf:"bytes,1,opt,name=service_id,json=serviceId,proto3" json:"service_id,omitempty"`
+ NodeID string `protobuf:"bytes,2,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"`
+ TaskID string `protobuf:"bytes,3,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"`
+}
+
+func (m *LogContext) Reset() { *m = LogContext{} }
+func (*LogContext) ProtoMessage() {}
+func (*LogContext) Descriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{2} }
+
+// LogAttr is an extra key/value pair that may be have been set by users
+type LogAttr struct {
+ Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
+ Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *LogAttr) Reset() { *m = LogAttr{} }
+func (*LogAttr) ProtoMessage() {}
+func (*LogAttr) Descriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{3} }
+
+// LogMessage
+type LogMessage struct {
+ // Context identifies the source of the log message.
+ Context LogContext `protobuf:"bytes,1,opt,name=context" json:"context"`
+ // Timestamp is the time at which the message was generated.
+ // Note: can't use stdtime because this field is nullable.
+ Timestamp *google_protobuf.Timestamp `protobuf:"bytes,2,opt,name=timestamp" json:"timestamp,omitempty"`
+ // Stream identifies the stream of the log message, stdout or stderr.
+ Stream LogStream `protobuf:"varint,3,opt,name=stream,proto3,enum=docker.swarmkit.v1.LogStream" json:"stream,omitempty"`
+ // Data is the raw log message, as generated by the application.
+ Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"`
+ // Attrs is a list of key value pairs representing additional log details
+ // that may have been returned from the logger
+ Attrs []LogAttr `protobuf:"bytes,5,rep,name=attrs" json:"attrs"`
+}
+
+func (m *LogMessage) Reset() { *m = LogMessage{} }
+func (*LogMessage) ProtoMessage() {}
+func (*LogMessage) Descriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{4} }
+
+type SubscribeLogsRequest struct {
+ // LogSelector describes the logs to which the subscriber is
+ Selector *LogSelector `protobuf:"bytes,1,opt,name=selector" json:"selector,omitempty"`
+ Options *LogSubscriptionOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"`
+}
+
+func (m *SubscribeLogsRequest) Reset() { *m = SubscribeLogsRequest{} }
+func (*SubscribeLogsRequest) ProtoMessage() {}
+func (*SubscribeLogsRequest) Descriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{5} }
+
+type SubscribeLogsMessage struct {
+ Messages []LogMessage `protobuf:"bytes,1,rep,name=messages" json:"messages"`
+}
+
+func (m *SubscribeLogsMessage) Reset() { *m = SubscribeLogsMessage{} }
+func (*SubscribeLogsMessage) ProtoMessage() {}
+func (*SubscribeLogsMessage) Descriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{6} }
+
+// ListenSubscriptionsRequest is a placeholder to begin listening for
+// subscriptions.
+type ListenSubscriptionsRequest struct {
+}
+
+func (m *ListenSubscriptionsRequest) Reset() { *m = ListenSubscriptionsRequest{} }
+func (*ListenSubscriptionsRequest) ProtoMessage() {}
+func (*ListenSubscriptionsRequest) Descriptor() ([]byte, []int) {
+ return fileDescriptorLogbroker, []int{7}
+}
+
+// SubscriptionMessage instructs the listener to start publishing messages for
+// the stream or end a subscription.
+//
+// If Options.Follow == false, the worker should end the subscription on its own.
+type SubscriptionMessage struct {
+ // ID identifies the subscription.
+ ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
+ // Selector defines which sources should be sent for the subscription.
+ Selector *LogSelector `protobuf:"bytes,2,opt,name=selector" json:"selector,omitempty"`
+ // Options specify how the subscription should be satisfied.
+ Options *LogSubscriptionOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ // Close will be true if the node should shutdown the subscription with the
+ // provided identifier.
+ Close bool `protobuf:"varint,4,opt,name=close,proto3" json:"close,omitempty"`
+}
+
+func (m *SubscriptionMessage) Reset() { *m = SubscriptionMessage{} }
+func (*SubscriptionMessage) ProtoMessage() {}
+func (*SubscriptionMessage) Descriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{8} }
+
+type PublishLogsMessage struct {
+ // SubscriptionID identifies which subscription the set of messages should
+ // be sent to. We can think of this as a "mail box" for the subscription.
+ SubscriptionID string `protobuf:"bytes,1,opt,name=subscription_id,json=subscriptionId,proto3" json:"subscription_id,omitempty"`
+ // Messages is the log message for publishing.
+ Messages []LogMessage `protobuf:"bytes,2,rep,name=messages" json:"messages"`
+ // Close is a boolean for whether or not the client has completed its log
+ // stream. When close is called, the manager can hang up the subscription.
+ // Any further logs from this subscription are an error condition. Any
+ // messages included when close is set can be discarded
+ Close bool `protobuf:"varint,3,opt,name=close,proto3" json:"close,omitempty"`
+}
+
+func (m *PublishLogsMessage) Reset() { *m = PublishLogsMessage{} }
+func (*PublishLogsMessage) ProtoMessage() {}
+func (*PublishLogsMessage) Descriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{9} }
+
+type PublishLogsResponse struct {
+}
+
+func (m *PublishLogsResponse) Reset() { *m = PublishLogsResponse{} }
+func (*PublishLogsResponse) ProtoMessage() {}
+func (*PublishLogsResponse) Descriptor() ([]byte, []int) { return fileDescriptorLogbroker, []int{10} }
+
+func init() {
+ proto.RegisterType((*LogSubscriptionOptions)(nil), "docker.swarmkit.v1.LogSubscriptionOptions")
+ proto.RegisterType((*LogSelector)(nil), "docker.swarmkit.v1.LogSelector")
+ proto.RegisterType((*LogContext)(nil), "docker.swarmkit.v1.LogContext")
+ proto.RegisterType((*LogAttr)(nil), "docker.swarmkit.v1.LogAttr")
+ proto.RegisterType((*LogMessage)(nil), "docker.swarmkit.v1.LogMessage")
+ proto.RegisterType((*SubscribeLogsRequest)(nil), "docker.swarmkit.v1.SubscribeLogsRequest")
+ proto.RegisterType((*SubscribeLogsMessage)(nil), "docker.swarmkit.v1.SubscribeLogsMessage")
+ proto.RegisterType((*ListenSubscriptionsRequest)(nil), "docker.swarmkit.v1.ListenSubscriptionsRequest")
+ proto.RegisterType((*SubscriptionMessage)(nil), "docker.swarmkit.v1.SubscriptionMessage")
+ proto.RegisterType((*PublishLogsMessage)(nil), "docker.swarmkit.v1.PublishLogsMessage")
+ proto.RegisterType((*PublishLogsResponse)(nil), "docker.swarmkit.v1.PublishLogsResponse")
+ proto.RegisterEnum("docker.swarmkit.v1.LogStream", LogStream_name, LogStream_value)
+}
+
+type authenticatedWrapperLogsServer struct {
+ local LogsServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperLogsServer(local LogsServer, authorize func(context.Context, []string) error) LogsServer {
+ return &authenticatedWrapperLogsServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperLogsServer) SubscribeLogs(r *SubscribeLogsRequest, stream Logs_SubscribeLogsServer) error {
+
+ if err := p.authorize(stream.Context(), []string{"swarm-manager"}); err != nil {
+ return err
+ }
+ return p.local.SubscribeLogs(r, stream)
+}
+
+type authenticatedWrapperLogBrokerServer struct {
+ local LogBrokerServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperLogBrokerServer(local LogBrokerServer, authorize func(context.Context, []string) error) LogBrokerServer {
+ return &authenticatedWrapperLogBrokerServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperLogBrokerServer) ListenSubscriptions(r *ListenSubscriptionsRequest, stream LogBroker_ListenSubscriptionsServer) error {
+
+ if err := p.authorize(stream.Context(), []string{"swarm-worker", "swarm-manager"}); err != nil {
+ return err
+ }
+ return p.local.ListenSubscriptions(r, stream)
+}
+
+func (p *authenticatedWrapperLogBrokerServer) PublishLogs(stream LogBroker_PublishLogsServer) error {
+
+ if err := p.authorize(stream.Context(), []string{"swarm-worker", "swarm-manager"}); err != nil {
+ return err
+ }
+ return p.local.PublishLogs(stream)
+}
+
+func (m *LogSubscriptionOptions) Copy() *LogSubscriptionOptions {
+ if m == nil {
+ return nil
+ }
+ o := &LogSubscriptionOptions{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *LogSubscriptionOptions) CopyFrom(src interface{}) {
+
+ o := src.(*LogSubscriptionOptions)
+ *m = *o
+ if o.Streams != nil {
+ m.Streams = make([]LogStream, len(o.Streams))
+ copy(m.Streams, o.Streams)
+ }
+
+ if o.Since != nil {
+ m.Since = &google_protobuf.Timestamp{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Since, o.Since)
+ }
+}
+
+func (m *LogSelector) Copy() *LogSelector {
+ if m == nil {
+ return nil
+ }
+ o := &LogSelector{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *LogSelector) CopyFrom(src interface{}) {
+
+ o := src.(*LogSelector)
+ *m = *o
+ if o.ServiceIDs != nil {
+ m.ServiceIDs = make([]string, len(o.ServiceIDs))
+ copy(m.ServiceIDs, o.ServiceIDs)
+ }
+
+ if o.NodeIDs != nil {
+ m.NodeIDs = make([]string, len(o.NodeIDs))
+ copy(m.NodeIDs, o.NodeIDs)
+ }
+
+ if o.TaskIDs != nil {
+ m.TaskIDs = make([]string, len(o.TaskIDs))
+ copy(m.TaskIDs, o.TaskIDs)
+ }
+
+}
+
+func (m *LogContext) Copy() *LogContext {
+ if m == nil {
+ return nil
+ }
+ o := &LogContext{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *LogContext) CopyFrom(src interface{}) {
+
+ o := src.(*LogContext)
+ *m = *o
+}
+
+func (m *LogAttr) Copy() *LogAttr {
+ if m == nil {
+ return nil
+ }
+ o := &LogAttr{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *LogAttr) CopyFrom(src interface{}) {
+
+ o := src.(*LogAttr)
+ *m = *o
+}
+
+func (m *LogMessage) Copy() *LogMessage {
+ if m == nil {
+ return nil
+ }
+ o := &LogMessage{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *LogMessage) CopyFrom(src interface{}) {
+
+ o := src.(*LogMessage)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Context, &o.Context)
+ if o.Timestamp != nil {
+ m.Timestamp = &google_protobuf.Timestamp{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Timestamp, o.Timestamp)
+ }
+ if o.Data != nil {
+ m.Data = make([]byte, len(o.Data))
+ copy(m.Data, o.Data)
+ }
+ if o.Attrs != nil {
+ m.Attrs = make([]LogAttr, len(o.Attrs))
+ for i := range m.Attrs {
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Attrs[i], &o.Attrs[i])
+ }
+ }
+
+}
+
+func (m *SubscribeLogsRequest) Copy() *SubscribeLogsRequest {
+ if m == nil {
+ return nil
+ }
+ o := &SubscribeLogsRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SubscribeLogsRequest) CopyFrom(src interface{}) {
+
+ o := src.(*SubscribeLogsRequest)
+ *m = *o
+ if o.Selector != nil {
+ m.Selector = &LogSelector{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Selector, o.Selector)
+ }
+ if o.Options != nil {
+ m.Options = &LogSubscriptionOptions{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Options, o.Options)
+ }
+}
+
+func (m *SubscribeLogsMessage) Copy() *SubscribeLogsMessage {
+ if m == nil {
+ return nil
+ }
+ o := &SubscribeLogsMessage{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SubscribeLogsMessage) CopyFrom(src interface{}) {
+
+ o := src.(*SubscribeLogsMessage)
+ *m = *o
+ if o.Messages != nil {
+ m.Messages = make([]LogMessage, len(o.Messages))
+ for i := range m.Messages {
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Messages[i], &o.Messages[i])
+ }
+ }
+
+}
+
+func (m *ListenSubscriptionsRequest) Copy() *ListenSubscriptionsRequest {
+ if m == nil {
+ return nil
+ }
+ o := &ListenSubscriptionsRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ListenSubscriptionsRequest) CopyFrom(src interface{}) {}
+func (m *SubscriptionMessage) Copy() *SubscriptionMessage {
+ if m == nil {
+ return nil
+ }
+ o := &SubscriptionMessage{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SubscriptionMessage) CopyFrom(src interface{}) {
+
+ o := src.(*SubscriptionMessage)
+ *m = *o
+ if o.Selector != nil {
+ m.Selector = &LogSelector{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Selector, o.Selector)
+ }
+ if o.Options != nil {
+ m.Options = &LogSubscriptionOptions{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Options, o.Options)
+ }
+}
+
+func (m *PublishLogsMessage) Copy() *PublishLogsMessage {
+ if m == nil {
+ return nil
+ }
+ o := &PublishLogsMessage{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *PublishLogsMessage) CopyFrom(src interface{}) {
+
+ o := src.(*PublishLogsMessage)
+ *m = *o
+ if o.Messages != nil {
+ m.Messages = make([]LogMessage, len(o.Messages))
+ for i := range m.Messages {
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Messages[i], &o.Messages[i])
+ }
+ }
+
+}
+
+func (m *PublishLogsResponse) Copy() *PublishLogsResponse {
+ if m == nil {
+ return nil
+ }
+ o := &PublishLogsResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *PublishLogsResponse) CopyFrom(src interface{}) {}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for Logs service
+
+type LogsClient interface {
+ // SubscribeLogs starts a subscription with the specified selector and options.
+ //
+ // The subscription will be distributed to relevant nodes and messages will
+ // be collected and sent via the returned stream.
+ //
+ // The subscription will end with an EOF.
+ SubscribeLogs(ctx context.Context, in *SubscribeLogsRequest, opts ...grpc.CallOption) (Logs_SubscribeLogsClient, error)
+}
+
+type logsClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewLogsClient(cc *grpc.ClientConn) LogsClient {
+ return &logsClient{cc}
+}
+
+func (c *logsClient) SubscribeLogs(ctx context.Context, in *SubscribeLogsRequest, opts ...grpc.CallOption) (Logs_SubscribeLogsClient, error) {
+ stream, err := grpc.NewClientStream(ctx, &_Logs_serviceDesc.Streams[0], c.cc, "/docker.swarmkit.v1.Logs/SubscribeLogs", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &logsSubscribeLogsClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Logs_SubscribeLogsClient interface {
+ Recv() (*SubscribeLogsMessage, error)
+ grpc.ClientStream
+}
+
+type logsSubscribeLogsClient struct {
+ grpc.ClientStream
+}
+
+func (x *logsSubscribeLogsClient) Recv() (*SubscribeLogsMessage, error) {
+ m := new(SubscribeLogsMessage)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// Server API for Logs service
+
+type LogsServer interface {
+ // SubscribeLogs starts a subscription with the specified selector and options.
+ //
+ // The subscription will be distributed to relevant nodes and messages will
+ // be collected and sent via the returned stream.
+ //
+ // The subscription will end with an EOF.
+ SubscribeLogs(*SubscribeLogsRequest, Logs_SubscribeLogsServer) error
+}
+
+func RegisterLogsServer(s *grpc.Server, srv LogsServer) {
+ s.RegisterService(&_Logs_serviceDesc, srv)
+}
+
+func _Logs_SubscribeLogs_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(SubscribeLogsRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(LogsServer).SubscribeLogs(m, &logsSubscribeLogsServer{stream})
+}
+
+type Logs_SubscribeLogsServer interface {
+ Send(*SubscribeLogsMessage) error
+ grpc.ServerStream
+}
+
+type logsSubscribeLogsServer struct {
+ grpc.ServerStream
+}
+
+func (x *logsSubscribeLogsServer) Send(m *SubscribeLogsMessage) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+var _Logs_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.Logs",
+ HandlerType: (*LogsServer)(nil),
+ Methods: []grpc.MethodDesc{},
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "SubscribeLogs",
+ Handler: _Logs_SubscribeLogs_Handler,
+ ServerStreams: true,
+ },
+ },
+ Metadata: "logbroker.proto",
+}
+
+// Client API for LogBroker service
+
+type LogBrokerClient interface {
+ // ListenSubscriptions starts a subscription stream for the node. For each
+ // message received, the node should attempt to satisfy the subscription.
+ //
+ // Log messages that match the provided subscription should be sent via
+ // PublishLogs.
+ ListenSubscriptions(ctx context.Context, in *ListenSubscriptionsRequest, opts ...grpc.CallOption) (LogBroker_ListenSubscriptionsClient, error)
+ // PublishLogs receives sets of log messages destined for a single
+ // subscription identifier.
+ PublishLogs(ctx context.Context, opts ...grpc.CallOption) (LogBroker_PublishLogsClient, error)
+}
+
+type logBrokerClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewLogBrokerClient(cc *grpc.ClientConn) LogBrokerClient {
+ return &logBrokerClient{cc}
+}
+
+func (c *logBrokerClient) ListenSubscriptions(ctx context.Context, in *ListenSubscriptionsRequest, opts ...grpc.CallOption) (LogBroker_ListenSubscriptionsClient, error) {
+ stream, err := grpc.NewClientStream(ctx, &_LogBroker_serviceDesc.Streams[0], c.cc, "/docker.swarmkit.v1.LogBroker/ListenSubscriptions", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &logBrokerListenSubscriptionsClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type LogBroker_ListenSubscriptionsClient interface {
+ Recv() (*SubscriptionMessage, error)
+ grpc.ClientStream
+}
+
+type logBrokerListenSubscriptionsClient struct {
+ grpc.ClientStream
+}
+
+func (x *logBrokerListenSubscriptionsClient) Recv() (*SubscriptionMessage, error) {
+ m := new(SubscriptionMessage)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+func (c *logBrokerClient) PublishLogs(ctx context.Context, opts ...grpc.CallOption) (LogBroker_PublishLogsClient, error) {
+ stream, err := grpc.NewClientStream(ctx, &_LogBroker_serviceDesc.Streams[1], c.cc, "/docker.swarmkit.v1.LogBroker/PublishLogs", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &logBrokerPublishLogsClient{stream}
+ return x, nil
+}
+
+type LogBroker_PublishLogsClient interface {
+ Send(*PublishLogsMessage) error
+ CloseAndRecv() (*PublishLogsResponse, error)
+ grpc.ClientStream
+}
+
+type logBrokerPublishLogsClient struct {
+ grpc.ClientStream
+}
+
+func (x *logBrokerPublishLogsClient) Send(m *PublishLogsMessage) error {
+ return x.ClientStream.SendMsg(m)
+}
+
+func (x *logBrokerPublishLogsClient) CloseAndRecv() (*PublishLogsResponse, error) {
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ m := new(PublishLogsResponse)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// Server API for LogBroker service
+
+type LogBrokerServer interface {
+ // ListenSubscriptions starts a subscription stream for the node. For each
+ // message received, the node should attempt to satisfy the subscription.
+ //
+ // Log messages that match the provided subscription should be sent via
+ // PublishLogs.
+ ListenSubscriptions(*ListenSubscriptionsRequest, LogBroker_ListenSubscriptionsServer) error
+ // PublishLogs receives sets of log messages destined for a single
+ // subscription identifier.
+ PublishLogs(LogBroker_PublishLogsServer) error
+}
+
+func RegisterLogBrokerServer(s *grpc.Server, srv LogBrokerServer) {
+ s.RegisterService(&_LogBroker_serviceDesc, srv)
+}
+
+func _LogBroker_ListenSubscriptions_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(ListenSubscriptionsRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(LogBrokerServer).ListenSubscriptions(m, &logBrokerListenSubscriptionsServer{stream})
+}
+
+type LogBroker_ListenSubscriptionsServer interface {
+ Send(*SubscriptionMessage) error
+ grpc.ServerStream
+}
+
+type logBrokerListenSubscriptionsServer struct {
+ grpc.ServerStream
+}
+
+func (x *logBrokerListenSubscriptionsServer) Send(m *SubscriptionMessage) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+func _LogBroker_PublishLogs_Handler(srv interface{}, stream grpc.ServerStream) error {
+ return srv.(LogBrokerServer).PublishLogs(&logBrokerPublishLogsServer{stream})
+}
+
+type LogBroker_PublishLogsServer interface {
+ SendAndClose(*PublishLogsResponse) error
+ Recv() (*PublishLogsMessage, error)
+ grpc.ServerStream
+}
+
+type logBrokerPublishLogsServer struct {
+ grpc.ServerStream
+}
+
+func (x *logBrokerPublishLogsServer) SendAndClose(m *PublishLogsResponse) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+func (x *logBrokerPublishLogsServer) Recv() (*PublishLogsMessage, error) {
+ m := new(PublishLogsMessage)
+ if err := x.ServerStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+var _LogBroker_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.LogBroker",
+ HandlerType: (*LogBrokerServer)(nil),
+ Methods: []grpc.MethodDesc{},
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "ListenSubscriptions",
+ Handler: _LogBroker_ListenSubscriptions_Handler,
+ ServerStreams: true,
+ },
+ {
+ StreamName: "PublishLogs",
+ Handler: _LogBroker_PublishLogs_Handler,
+ ClientStreams: true,
+ },
+ },
+ Metadata: "logbroker.proto",
+}
+
+func (m *LogSubscriptionOptions) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *LogSubscriptionOptions) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Streams) > 0 {
+ for _, num := range m.Streams {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(num))
+ }
+ }
+ if m.Follow {
+ dAtA[i] = 0x10
+ i++
+ if m.Follow {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Tail != 0 {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(m.Tail))
+ }
+ if m.Since != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(m.Since.Size()))
+ n1, err := m.Since.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ }
+ return i, nil
+}
+
+func (m *LogSelector) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *LogSelector) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ServiceIDs) > 0 {
+ for _, s := range m.ServiceIDs {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.NodeIDs) > 0 {
+ for _, s := range m.NodeIDs {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.TaskIDs) > 0 {
+ for _, s := range m.TaskIDs {
+ dAtA[i] = 0x1a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func (m *LogContext) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *LogContext) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ServiceID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(len(m.ServiceID)))
+ i += copy(dAtA[i:], m.ServiceID)
+ }
+ if len(m.NodeID) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(len(m.NodeID)))
+ i += copy(dAtA[i:], m.NodeID)
+ }
+ if len(m.TaskID) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(len(m.TaskID)))
+ i += copy(dAtA[i:], m.TaskID)
+ }
+ return i, nil
+}
+
+func (m *LogAttr) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *LogAttr) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Key) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(len(m.Key)))
+ i += copy(dAtA[i:], m.Key)
+ }
+ if len(m.Value) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(len(m.Value)))
+ i += copy(dAtA[i:], m.Value)
+ }
+ return i, nil
+}
+
+func (m *LogMessage) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *LogMessage) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(m.Context.Size()))
+ n2, err := m.Context.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ if m.Timestamp != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(m.Timestamp.Size()))
+ n3, err := m.Timestamp.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ }
+ if m.Stream != 0 {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(m.Stream))
+ }
+ if len(m.Data) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(len(m.Data)))
+ i += copy(dAtA[i:], m.Data)
+ }
+ if len(m.Attrs) > 0 {
+ for _, msg := range m.Attrs {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *SubscribeLogsRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SubscribeLogsRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Selector != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(m.Selector.Size()))
+ n4, err := m.Selector.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n4
+ }
+ if m.Options != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(m.Options.Size()))
+ n5, err := m.Options.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n5
+ }
+ return i, nil
+}
+
+func (m *SubscribeLogsMessage) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SubscribeLogsMessage) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Messages) > 0 {
+ for _, msg := range m.Messages {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *ListenSubscriptionsRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListenSubscriptionsRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *SubscriptionMessage) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SubscriptionMessage) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ }
+ if m.Selector != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(m.Selector.Size()))
+ n6, err := m.Selector.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n6
+ }
+ if m.Options != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(m.Options.Size()))
+ n7, err := m.Options.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n7
+ }
+ if m.Close {
+ dAtA[i] = 0x20
+ i++
+ if m.Close {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ return i, nil
+}
+
+func (m *PublishLogsMessage) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *PublishLogsMessage) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SubscriptionID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(len(m.SubscriptionID)))
+ i += copy(dAtA[i:], m.SubscriptionID)
+ }
+ if len(m.Messages) > 0 {
+ for _, msg := range m.Messages {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintLogbroker(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if m.Close {
+ dAtA[i] = 0x18
+ i++
+ if m.Close {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ return i, nil
+}
+
+func (m *PublishLogsResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *PublishLogsResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func encodeFixed64Logbroker(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Logbroker(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintLogbroker(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+type raftProxyLogsServer struct {
+ local LogsServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyLogsServer(local LogsServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) LogsServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyLogsServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyLogsServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyLogsServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+type Logs_SubscribeLogsServerWrapper struct {
+ Logs_SubscribeLogsServer
+ ctx context.Context
+}
+
+func (s Logs_SubscribeLogsServerWrapper) Context() context.Context {
+ return s.ctx
+}
+
+func (p *raftProxyLogsServer) SubscribeLogs(r *SubscribeLogsRequest, stream Logs_SubscribeLogsServer) error {
+ ctx := stream.Context()
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return err
+ }
+ streamWrapper := Logs_SubscribeLogsServerWrapper{
+ Logs_SubscribeLogsServer: stream,
+ ctx: ctx,
+ }
+ return p.local.SubscribeLogs(r, streamWrapper)
+ }
+ return err
+ }
+ ctx, err = p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return err
+ }
+ clientStream, err := NewLogsClient(conn).SubscribeLogs(ctx, r)
+
+ if err != nil {
+ return err
+ }
+
+ for {
+ msg, err := clientStream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+ if err := stream.Send(msg); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+type raftProxyLogBrokerServer struct {
+ local LogBrokerServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyLogBrokerServer(local LogBrokerServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) LogBrokerServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyLogBrokerServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyLogBrokerServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyLogBrokerServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+type LogBroker_ListenSubscriptionsServerWrapper struct {
+ LogBroker_ListenSubscriptionsServer
+ ctx context.Context
+}
+
+func (s LogBroker_ListenSubscriptionsServerWrapper) Context() context.Context {
+ return s.ctx
+}
+
+func (p *raftProxyLogBrokerServer) ListenSubscriptions(r *ListenSubscriptionsRequest, stream LogBroker_ListenSubscriptionsServer) error {
+ ctx := stream.Context()
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return err
+ }
+ streamWrapper := LogBroker_ListenSubscriptionsServerWrapper{
+ LogBroker_ListenSubscriptionsServer: stream,
+ ctx: ctx,
+ }
+ return p.local.ListenSubscriptions(r, streamWrapper)
+ }
+ return err
+ }
+ ctx, err = p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return err
+ }
+ clientStream, err := NewLogBrokerClient(conn).ListenSubscriptions(ctx, r)
+
+ if err != nil {
+ return err
+ }
+
+ for {
+ msg, err := clientStream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+ if err := stream.Send(msg); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+type LogBroker_PublishLogsServerWrapper struct {
+ LogBroker_PublishLogsServer
+ ctx context.Context
+}
+
+func (s LogBroker_PublishLogsServerWrapper) Context() context.Context {
+ return s.ctx
+}
+
+func (p *raftProxyLogBrokerServer) PublishLogs(stream LogBroker_PublishLogsServer) error {
+ ctx := stream.Context()
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return err
+ }
+ streamWrapper := LogBroker_PublishLogsServerWrapper{
+ LogBroker_PublishLogsServer: stream,
+ ctx: ctx,
+ }
+ return p.local.PublishLogs(streamWrapper)
+ }
+ return err
+ }
+ ctx, err = p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return err
+ }
+ clientStream, err := NewLogBrokerClient(conn).PublishLogs(ctx)
+
+ if err != nil {
+ return err
+ }
+
+ for {
+ msg, err := stream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+ if err := clientStream.Send(msg); err != nil {
+ return err
+ }
+ }
+
+ reply, err := clientStream.CloseAndRecv()
+ if err != nil {
+ return err
+ }
+
+ return stream.SendAndClose(reply)
+}
+
+func (m *LogSubscriptionOptions) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Streams) > 0 {
+ for _, e := range m.Streams {
+ n += 1 + sovLogbroker(uint64(e))
+ }
+ }
+ if m.Follow {
+ n += 2
+ }
+ if m.Tail != 0 {
+ n += 1 + sovLogbroker(uint64(m.Tail))
+ }
+ if m.Since != nil {
+ l = m.Since.Size()
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ return n
+}
+
+func (m *LogSelector) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.ServiceIDs) > 0 {
+ for _, s := range m.ServiceIDs {
+ l = len(s)
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ }
+ if len(m.NodeIDs) > 0 {
+ for _, s := range m.NodeIDs {
+ l = len(s)
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ }
+ if len(m.TaskIDs) > 0 {
+ for _, s := range m.TaskIDs {
+ l = len(s)
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *LogContext) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ServiceID)
+ if l > 0 {
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ l = len(m.NodeID)
+ if l > 0 {
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ l = len(m.TaskID)
+ if l > 0 {
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ return n
+}
+
+func (m *LogAttr) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Key)
+ if l > 0 {
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ l = len(m.Value)
+ if l > 0 {
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ return n
+}
+
+func (m *LogMessage) Size() (n int) {
+ var l int
+ _ = l
+ l = m.Context.Size()
+ n += 1 + l + sovLogbroker(uint64(l))
+ if m.Timestamp != nil {
+ l = m.Timestamp.Size()
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ if m.Stream != 0 {
+ n += 1 + sovLogbroker(uint64(m.Stream))
+ }
+ l = len(m.Data)
+ if l > 0 {
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ if len(m.Attrs) > 0 {
+ for _, e := range m.Attrs {
+ l = e.Size()
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *SubscribeLogsRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Selector != nil {
+ l = m.Selector.Size()
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ if m.Options != nil {
+ l = m.Options.Size()
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ return n
+}
+
+func (m *SubscribeLogsMessage) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Messages) > 0 {
+ for _, e := range m.Messages {
+ l = e.Size()
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *ListenSubscriptionsRequest) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *SubscriptionMessage) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ if l > 0 {
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ if m.Selector != nil {
+ l = m.Selector.Size()
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ if m.Options != nil {
+ l = m.Options.Size()
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ if m.Close {
+ n += 2
+ }
+ return n
+}
+
+func (m *PublishLogsMessage) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SubscriptionID)
+ if l > 0 {
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ if len(m.Messages) > 0 {
+ for _, e := range m.Messages {
+ l = e.Size()
+ n += 1 + l + sovLogbroker(uint64(l))
+ }
+ }
+ if m.Close {
+ n += 2
+ }
+ return n
+}
+
+func (m *PublishLogsResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func sovLogbroker(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozLogbroker(x uint64) (n int) {
+ return sovLogbroker(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *LogSubscriptionOptions) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&LogSubscriptionOptions{`,
+ `Streams:` + fmt.Sprintf("%v", this.Streams) + `,`,
+ `Follow:` + fmt.Sprintf("%v", this.Follow) + `,`,
+ `Tail:` + fmt.Sprintf("%v", this.Tail) + `,`,
+ `Since:` + strings.Replace(fmt.Sprintf("%v", this.Since), "Timestamp", "google_protobuf.Timestamp", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *LogSelector) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&LogSelector{`,
+ `ServiceIDs:` + fmt.Sprintf("%v", this.ServiceIDs) + `,`,
+ `NodeIDs:` + fmt.Sprintf("%v", this.NodeIDs) + `,`,
+ `TaskIDs:` + fmt.Sprintf("%v", this.TaskIDs) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *LogContext) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&LogContext{`,
+ `ServiceID:` + fmt.Sprintf("%v", this.ServiceID) + `,`,
+ `NodeID:` + fmt.Sprintf("%v", this.NodeID) + `,`,
+ `TaskID:` + fmt.Sprintf("%v", this.TaskID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *LogAttr) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&LogAttr{`,
+ `Key:` + fmt.Sprintf("%v", this.Key) + `,`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *LogMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&LogMessage{`,
+ `Context:` + strings.Replace(strings.Replace(this.Context.String(), "LogContext", "LogContext", 1), `&`, ``, 1) + `,`,
+ `Timestamp:` + strings.Replace(fmt.Sprintf("%v", this.Timestamp), "Timestamp", "google_protobuf.Timestamp", 1) + `,`,
+ `Stream:` + fmt.Sprintf("%v", this.Stream) + `,`,
+ `Data:` + fmt.Sprintf("%v", this.Data) + `,`,
+ `Attrs:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Attrs), "LogAttr", "LogAttr", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SubscribeLogsRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SubscribeLogsRequest{`,
+ `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LogSelector", "LogSelector", 1) + `,`,
+ `Options:` + strings.Replace(fmt.Sprintf("%v", this.Options), "LogSubscriptionOptions", "LogSubscriptionOptions", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SubscribeLogsMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SubscribeLogsMessage{`,
+ `Messages:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Messages), "LogMessage", "LogMessage", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListenSubscriptionsRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListenSubscriptionsRequest{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SubscriptionMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SubscriptionMessage{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Selector:` + strings.Replace(fmt.Sprintf("%v", this.Selector), "LogSelector", "LogSelector", 1) + `,`,
+ `Options:` + strings.Replace(fmt.Sprintf("%v", this.Options), "LogSubscriptionOptions", "LogSubscriptionOptions", 1) + `,`,
+ `Close:` + fmt.Sprintf("%v", this.Close) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *PublishLogsMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PublishLogsMessage{`,
+ `SubscriptionID:` + fmt.Sprintf("%v", this.SubscriptionID) + `,`,
+ `Messages:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Messages), "LogMessage", "LogMessage", 1), `&`, ``, 1) + `,`,
+ `Close:` + fmt.Sprintf("%v", this.Close) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *PublishLogsResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PublishLogsResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringLogbroker(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *LogSubscriptionOptions) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: LogSubscriptionOptions: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: LogSubscriptionOptions: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType == 0 {
+ var v LogStream
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (LogStream(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Streams = append(m.Streams, v)
+ } else if wireType == 2 {
+ var packedLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ packedLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if packedLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + packedLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ for iNdEx < postIndex {
+ var v LogStream
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (LogStream(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Streams = append(m.Streams, v)
+ }
+ } else {
+ return fmt.Errorf("proto: wrong wireType = %d for field Streams", wireType)
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Follow", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Follow = bool(v != 0)
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Tail", wireType)
+ }
+ m.Tail = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Tail |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Since", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Since == nil {
+ m.Since = &google_protobuf.Timestamp{}
+ }
+ if err := m.Since.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *LogSelector) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: LogSelector: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: LogSelector: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceIDs", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ServiceIDs = append(m.ServiceIDs, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeIDs", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeIDs = append(m.NodeIDs, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TaskIDs", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TaskIDs = append(m.TaskIDs, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *LogContext) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: LogContext: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: LogContext: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ServiceID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TaskID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TaskID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *LogAttr) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: LogAttr: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: LogAttr: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Key = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Value = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *LogMessage) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: LogMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: LogMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Context", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Context.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Timestamp == nil {
+ m.Timestamp = &google_protobuf.Timestamp{}
+ }
+ if err := m.Timestamp.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Stream", wireType)
+ }
+ m.Stream = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Stream |= (LogStream(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Attrs", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Attrs = append(m.Attrs, LogAttr{})
+ if err := m.Attrs[len(m.Attrs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SubscribeLogsRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SubscribeLogsRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SubscribeLogsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Selector", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Selector == nil {
+ m.Selector = &LogSelector{}
+ }
+ if err := m.Selector.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Options == nil {
+ m.Options = &LogSubscriptionOptions{}
+ }
+ if err := m.Options.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SubscribeLogsMessage) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SubscribeLogsMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SubscribeLogsMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Messages", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Messages = append(m.Messages, LogMessage{})
+ if err := m.Messages[len(m.Messages)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListenSubscriptionsRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListenSubscriptionsRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListenSubscriptionsRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SubscriptionMessage) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SubscriptionMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SubscriptionMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Selector", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Selector == nil {
+ m.Selector = &LogSelector{}
+ }
+ if err := m.Selector.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Options == nil {
+ m.Options = &LogSubscriptionOptions{}
+ }
+ if err := m.Options.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Close", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Close = bool(v != 0)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *PublishLogsMessage) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PublishLogsMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PublishLogsMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SubscriptionID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SubscriptionID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Messages", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Messages = append(m.Messages, LogMessage{})
+ if err := m.Messages[len(m.Messages)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Close", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Close = bool(v != 0)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *PublishLogsResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PublishLogsResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PublishLogsResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipLogbroker(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthLogbroker
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipLogbroker(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthLogbroker
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowLogbroker
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipLogbroker(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthLogbroker = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowLogbroker = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("logbroker.proto", fileDescriptorLogbroker) }
+
+var fileDescriptorLogbroker = []byte{
+ // 944 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x95, 0x41, 0x6f, 0x1b, 0x45,
+ 0x14, 0xc7, 0x3d, 0xeb, 0xc4, 0x8e, 0x9f, 0x9b, 0xc4, 0x1d, 0xa7, 0x91, 0x65, 0xa8, 0x6d, 0x6d,
+ 0xa5, 0x62, 0x45, 0xc5, 0x6e, 0x8d, 0x10, 0x48, 0x91, 0x10, 0x35, 0xae, 0x90, 0x85, 0x9b, 0xa0,
+ 0xb1, 0x23, 0xb8, 0x45, 0x6b, 0xef, 0x74, 0x59, 0x79, 0xbd, 0x63, 0x76, 0xc6, 0x09, 0x48, 0x1c,
+ 0x38, 0x14, 0x09, 0xe5, 0xc0, 0x0d, 0x09, 0x0e, 0x3d, 0xd1, 0x0b, 0x42, 0xe2, 0xc2, 0x8d, 0x0f,
+ 0x80, 0x22, 0x4e, 0x1c, 0x39, 0x59, 0x74, 0x3f, 0x00, 0x9f, 0x01, 0xed, 0xcc, 0xd8, 0xde, 0x60,
+ 0xbb, 0x45, 0xe5, 0x92, 0xcc, 0xec, 0xfc, 0xdf, 0xbe, 0xdf, 0xfb, 0xcf, 0x7b, 0x6b, 0xd8, 0xf5,
+ 0x98, 0xd3, 0x0f, 0xd8, 0x90, 0x06, 0xb5, 0x71, 0xc0, 0x04, 0xc3, 0xd8, 0x66, 0x83, 0x68, 0xc7,
+ 0xcf, 0xad, 0x60, 0x34, 0x74, 0x45, 0xed, 0xec, 0x5e, 0x71, 0xcf, 0x61, 0x0e, 0x93, 0xc7, 0xf5,
+ 0x68, 0xa5, 0x94, 0xc5, 0xb2, 0xc3, 0x98, 0xe3, 0xd1, 0xba, 0xdc, 0xf5, 0x27, 0x8f, 0xea, 0xc2,
+ 0x1d, 0x51, 0x2e, 0xac, 0xd1, 0x58, 0x0b, 0xf2, 0x63, 0x6f, 0xe2, 0xb8, 0x7e, 0x5d, 0xfd, 0x53,
+ 0x0f, 0xcd, 0x5f, 0x10, 0xec, 0x77, 0x98, 0xd3, 0x9d, 0xf4, 0xf9, 0x20, 0x70, 0xc7, 0xc2, 0x65,
+ 0xfe, 0xb1, 0xfc, 0xcb, 0xf1, 0x21, 0xa4, 0xb9, 0x08, 0xa8, 0x35, 0xe2, 0x05, 0x54, 0x49, 0x56,
+ 0x77, 0x1a, 0x37, 0x6b, 0xcb, 0x30, 0xb5, 0x28, 0x58, 0xaa, 0x9a, 0x46, 0x2e, 0x41, 0x66, 0x11,
+ 0x78, 0x1f, 0x52, 0x8f, 0x98, 0xe7, 0xb1, 0xf3, 0x82, 0x51, 0x41, 0xd5, 0x2d, 0xa2, 0x77, 0x18,
+ 0xc3, 0x86, 0xb0, 0x5c, 0xaf, 0x90, 0xac, 0xa0, 0x6a, 0x92, 0xc8, 0x35, 0xbe, 0x0b, 0x9b, 0xdc,
+ 0xf5, 0x07, 0xb4, 0xb0, 0x51, 0x41, 0xd5, 0x6c, 0xa3, 0x58, 0x53, 0x95, 0xd4, 0x66, 0x95, 0xd4,
+ 0x7a, 0xb3, 0x4a, 0x88, 0x12, 0x9a, 0xdf, 0x20, 0xc8, 0x46, 0x89, 0xa9, 0x47, 0x07, 0x82, 0x05,
+ 0xb8, 0x0e, 0x59, 0x4e, 0x83, 0x33, 0x77, 0x40, 0x4f, 0x5d, 0x5b, 0xe1, 0x66, 0x9a, 0x3b, 0xe1,
+ 0xb4, 0x0c, 0x5d, 0xf5, 0xb8, 0xdd, 0xe2, 0x04, 0xb4, 0xa4, 0x6d, 0x73, 0x7c, 0x1b, 0xb6, 0x7c,
+ 0x66, 0x2b, 0xb5, 0x21, 0xd5, 0xd9, 0x70, 0x5a, 0x4e, 0x1f, 0x31, 0x5b, 0x4a, 0xd3, 0xd1, 0xa1,
+ 0xd6, 0x09, 0x8b, 0x0f, 0xa5, 0x2e, 0xb9, 0xd0, 0xf5, 0x2c, 0x3e, 0x94, 0xba, 0xe8, 0xb0, 0x6d,
+ 0x73, 0xf3, 0x31, 0x02, 0xe8, 0x30, 0xe7, 0x3d, 0xe6, 0x0b, 0xfa, 0x99, 0xc0, 0x77, 0x00, 0x16,
+ 0x3c, 0x05, 0x54, 0x41, 0xd5, 0x4c, 0x73, 0x3b, 0x9c, 0x96, 0x33, 0x73, 0x1c, 0x92, 0x99, 0xd3,
+ 0xe0, 0x5b, 0x90, 0xd6, 0x30, 0xd2, 0xac, 0x4c, 0x13, 0xc2, 0x69, 0x39, 0xa5, 0x58, 0x48, 0x4a,
+ 0xa1, 0x44, 0x22, 0x4d, 0x22, 0xbd, 0xd3, 0x22, 0x05, 0x42, 0x52, 0x8a, 0xc3, 0xbc, 0x07, 0xe9,
+ 0x0e, 0x73, 0xee, 0x0b, 0x11, 0xe0, 0x1c, 0x24, 0x87, 0xf4, 0x73, 0x95, 0x9b, 0x44, 0x4b, 0xbc,
+ 0x07, 0x9b, 0x67, 0x96, 0x37, 0xa1, 0x2a, 0x09, 0x51, 0x1b, 0xf3, 0xc2, 0x90, 0xe4, 0x0f, 0x29,
+ 0xe7, 0x96, 0x43, 0xf1, 0x3b, 0x90, 0x1e, 0xa8, 0x22, 0x64, 0x68, 0xb6, 0x51, 0x5a, 0x73, 0xe9,
+ 0xba, 0xd4, 0xe6, 0xc6, 0xe5, 0xb4, 0x9c, 0x20, 0xb3, 0x20, 0xfc, 0x36, 0x64, 0xe6, 0x7d, 0x27,
+ 0x13, 0x3d, 0xff, 0x3e, 0x17, 0x62, 0xfc, 0x26, 0xa4, 0x54, 0xf3, 0xc8, 0xfa, 0x5e, 0xd4, 0x6d,
+ 0x44, 0x8b, 0xa3, 0x86, 0xb2, 0x2d, 0x61, 0xc9, 0xde, 0xb9, 0x46, 0xe4, 0x1a, 0xbf, 0x05, 0x9b,
+ 0x96, 0x10, 0x01, 0x2f, 0x6c, 0x56, 0x92, 0xd5, 0x6c, 0xe3, 0x95, 0x35, 0x6f, 0x8a, 0x7c, 0xd2,
+ 0xfc, 0x4a, 0x6f, 0x7e, 0x8f, 0x60, 0x4f, 0x8f, 0x42, 0x9f, 0x76, 0x98, 0xc3, 0x09, 0xfd, 0x74,
+ 0x42, 0xb9, 0xc0, 0x87, 0xb0, 0xc5, 0x75, 0xb3, 0x69, 0x5f, 0xca, 0xeb, 0xf0, 0xb4, 0x8c, 0xcc,
+ 0x03, 0x70, 0x0b, 0xd2, 0x4c, 0xcd, 0x94, 0x76, 0xe4, 0x60, 0x5d, 0xec, 0xf2, 0x14, 0x92, 0x59,
+ 0xa8, 0xf9, 0xf1, 0xbf, 0xd0, 0x66, 0x37, 0xf6, 0x2e, 0x6c, 0x8d, 0xd4, 0x52, 0x35, 0xfe, 0xfa,
+ 0x2b, 0xd3, 0x11, 0xba, 0xe4, 0x79, 0x94, 0xf9, 0x2a, 0x14, 0x3b, 0x2e, 0x17, 0xd4, 0x8f, 0xe7,
+ 0x9f, 0x95, 0x6e, 0xfe, 0x86, 0x20, 0x1f, 0x3f, 0x98, 0xe5, 0xdd, 0x07, 0x63, 0xde, 0xdb, 0xa9,
+ 0x70, 0x5a, 0x36, 0xda, 0x2d, 0x62, 0xb8, 0xf6, 0x15, 0xab, 0x8c, 0xff, 0x61, 0x55, 0xf2, 0xa5,
+ 0xad, 0x8a, 0x3a, 0x7d, 0xe0, 0x31, 0xae, 0x3e, 0x28, 0x5b, 0x44, 0x6d, 0xcc, 0x1f, 0x11, 0xe0,
+ 0x0f, 0x27, 0x7d, 0xcf, 0xe5, 0x9f, 0xc4, 0xfd, 0x3b, 0x84, 0x5d, 0x1e, 0x7b, 0xd9, 0x62, 0x60,
+ 0x71, 0x38, 0x2d, 0xef, 0xc4, 0xf3, 0xb4, 0x5b, 0x64, 0x27, 0x2e, 0x6d, 0xdb, 0x57, 0xcc, 0x37,
+ 0x5e, 0xc6, 0xfc, 0x05, 0x6b, 0x32, 0xce, 0x7a, 0x03, 0xf2, 0x31, 0x54, 0x42, 0xf9, 0x98, 0xf9,
+ 0x9c, 0x1e, 0x3c, 0x45, 0x90, 0x99, 0x8f, 0x00, 0xbe, 0x03, 0xb8, 0x73, 0xfc, 0xfe, 0x69, 0xb7,
+ 0x47, 0x1e, 0xdc, 0x7f, 0x78, 0x7a, 0x72, 0xf4, 0xc1, 0xd1, 0xf1, 0x47, 0x47, 0xb9, 0x44, 0x71,
+ 0xef, 0xe2, 0x49, 0x25, 0x37, 0x97, 0x9d, 0xf8, 0x43, 0x9f, 0x9d, 0xfb, 0xf8, 0x00, 0xae, 0xc7,
+ 0xd4, 0xdd, 0x5e, 0xeb, 0xf8, 0xa4, 0x97, 0x43, 0xc5, 0xfc, 0xc5, 0x93, 0xca, 0xee, 0x5c, 0xdc,
+ 0x15, 0x36, 0x9b, 0x88, 0x65, 0xed, 0x03, 0x42, 0x72, 0xc6, 0xb2, 0x96, 0x06, 0x41, 0xf1, 0xfa,
+ 0xd7, 0x3f, 0x94, 0x12, 0xbf, 0x3e, 0x2d, 0x2d, 0xc0, 0x1a, 0x8f, 0x11, 0x6c, 0x44, 0xdc, 0xf8,
+ 0x0b, 0xd8, 0xbe, 0xd2, 0xb3, 0xb8, 0xba, 0xca, 0x9d, 0x55, 0x13, 0x57, 0x7c, 0xb1, 0x52, 0x3b,
+ 0x6a, 0xde, 0xf8, 0xfd, 0xe7, 0xbf, 0xbf, 0x33, 0x76, 0x61, 0x5b, 0x2a, 0x5f, 0x1f, 0x59, 0xbe,
+ 0xe5, 0xd0, 0xe0, 0x2e, 0x6a, 0xfc, 0x64, 0x48, 0xb7, 0x9a, 0xf2, 0xf7, 0x14, 0x7f, 0x8b, 0x20,
+ 0xbf, 0xa2, 0xcd, 0x71, 0x6d, 0xe5, 0x85, 0xad, 0x9d, 0x87, 0xe2, 0x6b, 0xcf, 0x01, 0x8b, 0x0f,
+ 0x88, 0x79, 0x4b, 0x72, 0xdd, 0x84, 0x6b, 0x8a, 0xeb, 0x9c, 0x05, 0x43, 0x1a, 0x2c, 0x51, 0xe2,
+ 0xaf, 0x10, 0x64, 0x63, 0x77, 0x8d, 0x6f, 0xaf, 0x7a, 0xff, 0x72, 0xdf, 0xae, 0xe6, 0x58, 0xd1,
+ 0x34, 0xff, 0x89, 0xa3, 0x8a, 0x9a, 0x85, 0xcb, 0x67, 0xa5, 0xc4, 0x9f, 0xcf, 0x4a, 0x89, 0x2f,
+ 0xc3, 0x12, 0xba, 0x0c, 0x4b, 0xe8, 0x8f, 0xb0, 0x84, 0xfe, 0x0a, 0x4b, 0xa8, 0x9f, 0x92, 0x1f,
+ 0xee, 0x37, 0xfe, 0x09, 0x00, 0x00, 0xff, 0xff, 0x08, 0xa1, 0xea, 0xc7, 0x9d, 0x08, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/logbroker.proto b/vendor/github.com/docker/swarmkit/api/logbroker.proto
new file mode 100644
index 0000000..b86b8e8
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/logbroker.proto
@@ -0,0 +1,188 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "gogoproto/gogo.proto";
+import "google/protobuf/timestamp.proto";
+import "plugin/plugin.proto";
+
+// LogStream defines the stream from which the log message came.
+enum LogStream {
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "LogStream";
+
+ LOG_STREAM_UNKNOWN = 0 [(gogoproto.enumvalue_customname) = "LogStreamUnknown"];
+ LOG_STREAM_STDOUT = 1 [(gogoproto.enumvalue_customname) = "LogStreamStdout"];
+ LOG_STREAM_STDERR = 2 [(gogoproto.enumvalue_customname) = "LogStreamStderr"];
+}
+
+message LogSubscriptionOptions {
+ // Streams defines which log streams should be sent from the task source.
+ // Empty means send all the messages.
+ repeated LogStream streams = 1 [packed=false];
+
+ // Follow instructs the publisher to continue sending log messages as they
+ // are produced, after satisfying the initial query.
+ bool follow = 2;
+
+ // Tail defines how many messages relative to the log stream to send when
+ // starting the stream.
+ //
+ // Positive values will skip that number of messages from the start of the
+ // stream before publishing.
+ //
+ // Negative values will specify messages relative to the end of the stream,
+ // offset by one. We can say that the last (-n-1) lines are returned when n
+ // < 0. As reference, -1 would mean send no log lines (typically used with
+ // follow), -2 would return the last log line, -11 would return the last 10
+ // and so on.
+ //
+ // The default value of zero will return all logs.
+ //
+ // Note that this is very different from the Docker API.
+ int64 tail = 3;
+
+ // Since indicates that only log messages produced after this timestamp
+ // should be sent.
+ // Note: can't use stdtime because this field is nullable.
+ google.protobuf.Timestamp since = 4;
+}
+
+// LogSelector will match logs from ANY of the defined parameters.
+//
+// For the best effect, the client should use the least specific parameter
+// possible. For example, if they want to listen to all the tasks of a service,
+// they should use the service id, rather than specifying the individual tasks.
+message LogSelector {
+ repeated string service_ids = 1;
+ repeated string node_ids = 2;
+ repeated string task_ids = 3;
+}
+
+// LogContext marks the context from which a log message was generated.
+message LogContext {
+ string service_id = 1;
+ string node_id = 2;
+ string task_id = 3;
+}
+
+// LogAttr is an extra key/value pair that may be have been set by users
+message LogAttr {
+ string key = 1;
+ string value = 2;
+}
+
+// LogMessage
+message LogMessage {
+ // Context identifies the source of the log message.
+ LogContext context = 1 [(gogoproto.nullable) = false];
+
+ // Timestamp is the time at which the message was generated.
+ // Note: can't use stdtime because this field is nullable.
+ google.protobuf.Timestamp timestamp = 2;
+
+ // Stream identifies the stream of the log message, stdout or stderr.
+ LogStream stream = 3;
+
+ // Data is the raw log message, as generated by the application.
+ bytes data = 4;
+
+ // Attrs is a list of key value pairs representing additional log details
+ // that may have been returned from the logger
+ repeated LogAttr attrs = 5 [(gogoproto.nullable) = false];
+}
+
+// Logs defines the methods for retrieving task logs messages from a cluster.
+service Logs {
+ // SubscribeLogs starts a subscription with the specified selector and options.
+ //
+ // The subscription will be distributed to relevant nodes and messages will
+ // be collected and sent via the returned stream.
+ //
+ // The subscription will end with an EOF.
+ rpc SubscribeLogs(SubscribeLogsRequest) returns (stream SubscribeLogsMessage) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ }
+}
+
+message SubscribeLogsRequest {
+ // LogSelector describes the logs to which the subscriber is
+ LogSelector selector = 1;
+
+ LogSubscriptionOptions options = 2;
+}
+
+message SubscribeLogsMessage {
+ repeated LogMessage messages = 1 [(gogoproto.nullable) = false];
+}
+
+// LogBroker defines the API used by the worker to send task logs back to a
+// manager. A client listens for subscriptions then optimistically retrieves
+// logs satisfying said subscriptions, calling PublishLogs for results that are
+// relevant.
+//
+// The structure of ListenSubscriptions is similar to the Dispatcher API but
+// decoupled to allow log distribution to work outside of the regular task
+// flow.
+service LogBroker {
+ // ListenSubscriptions starts a subscription stream for the node. For each
+ // message received, the node should attempt to satisfy the subscription.
+ //
+ // Log messages that match the provided subscription should be sent via
+ // PublishLogs.
+ rpc ListenSubscriptions(ListenSubscriptionsRequest) returns (stream SubscriptionMessage) {
+ option (docker.protobuf.plugin.tls_authorization) = {
+ roles: "swarm-worker"
+ roles: "swarm-manager"
+ };
+ }
+
+ // PublishLogs receives sets of log messages destined for a single
+ // subscription identifier.
+ rpc PublishLogs(stream PublishLogsMessage) returns (PublishLogsResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = {
+ roles: "swarm-worker"
+ roles: "swarm-manager"
+ };
+ }
+}
+
+// ListenSubscriptionsRequest is a placeholder to begin listening for
+// subscriptions.
+message ListenSubscriptionsRequest { }
+
+// SubscriptionMessage instructs the listener to start publishing messages for
+// the stream or end a subscription.
+//
+// If Options.Follow == false, the worker should end the subscription on its own.
+message SubscriptionMessage {
+ // ID identifies the subscription.
+ string id = 1;
+
+ // Selector defines which sources should be sent for the subscription.
+ LogSelector selector = 2;
+
+ // Options specify how the subscription should be satisfied.
+ LogSubscriptionOptions options = 3;
+
+ // Close will be true if the node should shutdown the subscription with the
+ // provided identifier.
+ bool close = 4;
+}
+
+message PublishLogsMessage {
+ // SubscriptionID identifies which subscription the set of messages should
+ // be sent to. We can think of this as a "mail box" for the subscription.
+ string subscription_id = 1;
+
+ // Messages is the log message for publishing.
+ repeated LogMessage messages = 2 [(gogoproto.nullable) = false];
+
+ // Close is a boolean for whether or not the client has completed its log
+ // stream. When close is called, the manager can hang up the subscription.
+ // Any further logs from this subscription are an error condition. Any
+ // messages included when close is set can be discarded
+ bool close = 3;
+}
+
+message PublishLogsResponse { }
diff --git a/vendor/github.com/docker/swarmkit/api/naming/naming.go b/vendor/github.com/docker/swarmkit/api/naming/naming.go
new file mode 100644
index 0000000..7e7d458
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/naming/naming.go
@@ -0,0 +1,49 @@
+// Package naming centralizes the naming of SwarmKit objects.
+package naming
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+)
+
+var (
+ errUnknownRuntime = errors.New("unrecognized runtime")
+)
+
+// Task returns the task name from Annotations.Name,
+// and, in case Annotations.Name is missing, fallback
+// to construct the name from other information.
+func Task(t *api.Task) string {
+ if t.Annotations.Name != "" {
+ // if set, use the container Annotations.Name field, set in the orchestrator.
+ return t.Annotations.Name
+ }
+
+ slot := fmt.Sprint(t.Slot)
+ if slot == "" || t.Slot == 0 {
+ // when no slot id is assigned, we assume that this is node-bound task.
+ slot = t.NodeID
+ }
+
+ // fallback to service.instance.id.
+ return fmt.Sprintf("%s.%s.%s", t.ServiceAnnotations.Name, slot, t.ID)
+}
+
+// TODO(stevvooe): Consolidate "Hostname" style validation here.
+
+// Runtime returns the runtime name from a given spec.
+func Runtime(t api.TaskSpec) (string, error) {
+ switch r := t.GetRuntime().(type) {
+ case *api.TaskSpec_Attachment:
+ return "attachment", nil
+ case *api.TaskSpec_Container:
+ return "container", nil
+ case *api.TaskSpec_Generic:
+ return strings.ToLower(r.Generic.Kind), nil
+ default:
+ return "", errUnknownRuntime
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/api/objects.pb.go b/vendor/github.com/docker/swarmkit/api/objects.pb.go
new file mode 100644
index 0000000..b6a9389
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/objects.pb.go
@@ -0,0 +1,7787 @@
+// Code generated by protoc-gen-gogo.
+// source: objects.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_protobuf "github.com/gogo/protobuf/types"
+import _ "github.com/gogo/protobuf/gogoproto"
+import google_protobuf3 "github.com/gogo/protobuf/types"
+import _ "github.com/docker/swarmkit/protobuf/plugin"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import github_com_docker_go_events "github.com/docker/go-events"
+import strings "strings"
+
+import reflect "reflect"
+import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// Meta contains metadata about objects. Every object contains a meta field.
+type Meta struct {
+ // Version tracks the current version of the object.
+ Version Version `protobuf:"bytes,1,opt,name=version" json:"version"`
+ // Object timestamps.
+ // Note: can't use stdtime because these fields are nullable.
+ CreatedAt *google_protobuf.Timestamp `protobuf:"bytes,2,opt,name=created_at,json=createdAt" json:"created_at,omitempty"`
+ UpdatedAt *google_protobuf.Timestamp `protobuf:"bytes,3,opt,name=updated_at,json=updatedAt" json:"updated_at,omitempty"`
+}
+
+func (m *Meta) Reset() { *m = Meta{} }
+func (*Meta) ProtoMessage() {}
+func (*Meta) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{0} }
+
+// Node provides the internal node state as seen by the cluster.
+type Node struct {
+ // ID specifies the identity of the node.
+ ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
+ Meta Meta `protobuf:"bytes,2,opt,name=meta" json:"meta"`
+ // Spec defines the desired state of the node as specified by the user.
+ // The system will honor this and will *never* modify it.
+ Spec NodeSpec `protobuf:"bytes,3,opt,name=spec" json:"spec"`
+ // Description encapsulated the properties of the Node as reported by the
+ // agent.
+ Description *NodeDescription `protobuf:"bytes,4,opt,name=description" json:"description,omitempty"`
+ // Status provides the current status of the node, as seen by the manager.
+ Status NodeStatus `protobuf:"bytes,5,opt,name=status" json:"status"`
+ // ManagerStatus provides the current status of the node's manager
+ // component, if the node is a manager.
+ ManagerStatus *ManagerStatus `protobuf:"bytes,6,opt,name=manager_status,json=managerStatus" json:"manager_status,omitempty"`
+ // The node attachment to the ingress network.
+ Attachment *NetworkAttachment `protobuf:"bytes,7,opt,name=attachment" json:"attachment,omitempty"`
+ // Certificate is the TLS certificate issued for the node, if any.
+ Certificate Certificate `protobuf:"bytes,8,opt,name=certificate" json:"certificate"`
+ // Role is the *observed* role for this node. It differs from the
+ // desired role set in Node.Spec.Role because the role here is only
+ // updated after the Raft member list has been reconciled with the
+ // desired role from the spec.
+ //
+ // This field represents the current reconciled state. If an action is
+ // to be performed, first verify the role in the cert. This field only
+ // shows the privilege level that the CA would currently grant when
+ // issuing or renewing the node's certificate.
+ Role NodeRole `protobuf:"varint,9,opt,name=role,proto3,enum=docker.swarmkit.v1.NodeRole" json:"role,omitempty"`
+}
+
+func (m *Node) Reset() { *m = Node{} }
+func (*Node) ProtoMessage() {}
+func (*Node) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{1} }
+
+type Service struct {
+ ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
+ Meta Meta `protobuf:"bytes,2,opt,name=meta" json:"meta"`
+ Spec ServiceSpec `protobuf:"bytes,3,opt,name=spec" json:"spec"`
+ // SpecVersion versions Spec, to identify changes in the spec. Note that
+ // this is not directly comparable to the service's Version.
+ SpecVersion *Version `protobuf:"bytes,10,opt,name=spec_version,json=specVersion" json:"spec_version,omitempty"`
+ // PreviousSpec is the previous service spec that was in place before
+ // "Spec".
+ PreviousSpec *ServiceSpec `protobuf:"bytes,6,opt,name=previous_spec,json=previousSpec" json:"previous_spec,omitempty"`
+ // PreviousSpecVersion versions PreviousSpec. Note that this is not
+ // directly comparable to the service's Version.
+ PreviousSpecVersion *Version `protobuf:"bytes,11,opt,name=previous_spec_version,json=previousSpecVersion" json:"previous_spec_version,omitempty"`
+ // Runtime state of service endpoint. This may be different
+ // from the spec version because the user may not have entered
+ // the optional fields like node_port or virtual_ip and it
+ // could be auto allocated by the system.
+ Endpoint *Endpoint `protobuf:"bytes,4,opt,name=endpoint" json:"endpoint,omitempty"`
+ // UpdateStatus contains the status of an update, if one is in
+ // progress.
+ UpdateStatus *UpdateStatus `protobuf:"bytes,5,opt,name=update_status,json=updateStatus" json:"update_status,omitempty"`
+}
+
+func (m *Service) Reset() { *m = Service{} }
+func (*Service) ProtoMessage() {}
+func (*Service) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{2} }
+
+// Endpoint specified all the network parameters required to
+// correctly discover and load balance a service
+type Endpoint struct {
+ Spec *EndpointSpec `protobuf:"bytes,1,opt,name=spec" json:"spec,omitempty"`
+ // Runtime state of the exposed ports which may carry
+ // auto-allocated swarm ports in addition to the user
+ // configured information.
+ Ports []*PortConfig `protobuf:"bytes,2,rep,name=ports" json:"ports,omitempty"`
+ // VirtualIPs specifies the IP addresses under which this endpoint will be
+ // made available.
+ VirtualIPs []*Endpoint_VirtualIP `protobuf:"bytes,3,rep,name=virtual_ips,json=virtualIps" json:"virtual_ips,omitempty"`
+}
+
+func (m *Endpoint) Reset() { *m = Endpoint{} }
+func (*Endpoint) ProtoMessage() {}
+func (*Endpoint) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{3} }
+
+// VirtualIP specifies a set of networks this endpoint will be attached to
+// and the IP addresses the target service will be made available under.
+type Endpoint_VirtualIP struct {
+ // NetworkID for which this endpoint attachment was created.
+ NetworkID string `protobuf:"bytes,1,opt,name=network_id,json=networkId,proto3" json:"network_id,omitempty"`
+ // A virtual IP is used to address this service in IP
+ // layer that the client can use to send requests to
+ // this service. A DNS A/AAAA query on the service
+ // name might return this IP to the client. This is
+ // strictly a logical IP and there may not be any
+ // interfaces assigned this IP address or any route
+ // created for this address. More than one to
+ // accommodate for both IPv4 and IPv6
+ Addr string `protobuf:"bytes,2,opt,name=addr,proto3" json:"addr,omitempty"`
+}
+
+func (m *Endpoint_VirtualIP) Reset() { *m = Endpoint_VirtualIP{} }
+func (*Endpoint_VirtualIP) ProtoMessage() {}
+func (*Endpoint_VirtualIP) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{3, 0} }
+
+// Task specifies the parameters for implementing a Spec. A task is effectively
+// immutable and idempotent. Once it is dispatched to a node, it will not be
+// dispatched to another node.
+type Task struct {
+ ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
+ Meta Meta `protobuf:"bytes,2,opt,name=meta" json:"meta"`
+ // Spec defines the desired state of the task as specified by the user.
+ // The system will honor this and will *never* modify it.
+ Spec TaskSpec `protobuf:"bytes,3,opt,name=spec" json:"spec"`
+ // SpecVersion is copied from Service, to identify which version of the
+ // spec this task has. Note that this is not directly comparable to the
+ // service's Version.
+ SpecVersion *Version `protobuf:"bytes,14,opt,name=spec_version,json=specVersion" json:"spec_version,omitempty"`
+ // ServiceID indicates the service under which this task is orchestrated. This
+ // should almost always be set.
+ ServiceID string `protobuf:"bytes,4,opt,name=service_id,json=serviceId,proto3" json:"service_id,omitempty"`
+ // Slot is the service slot number for a task.
+ // For example, if a replicated service has replicas = 2, there will be a
+ // task with slot = 1, and another with slot = 2.
+ Slot uint64 `protobuf:"varint,5,opt,name=slot,proto3" json:"slot,omitempty"`
+ // NodeID indicates the node to which the task is assigned. If this field
+ // is empty or not set, the task is unassigned.
+ NodeID string `protobuf:"bytes,6,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"`
+ // Annotations defines the names and labels for the runtime, as set by
+ // the cluster manager.
+ //
+ // As backup, if this field has an empty name, the runtime will
+ // allocate a unique name for the actual container.
+ //
+ // NOTE(stevvooe): The preserves the ability for us to making naming
+ // decisions for tasks in orchestrator, albeit, this is left empty for now.
+ Annotations Annotations `protobuf:"bytes,7,opt,name=annotations" json:"annotations"`
+ // ServiceAnnotations is a direct copy of the service name and labels when
+ // this task is created.
+ //
+ // Labels set here will *not* be propagated to the runtime target, such as a
+ // container. Use labels on the runtime target for that purpose.
+ ServiceAnnotations Annotations `protobuf:"bytes,8,opt,name=service_annotations,json=serviceAnnotations" json:"service_annotations"`
+ Status TaskStatus `protobuf:"bytes,9,opt,name=status" json:"status"`
+ // DesiredState is the target state for the task. It is set to
+ // TaskStateRunning when a task is first created, and changed to
+ // TaskStateShutdown if the manager wants to terminate the task. This field
+ // is only written by the manager.
+ DesiredState TaskState `protobuf:"varint,10,opt,name=desired_state,json=desiredState,proto3,enum=docker.swarmkit.v1.TaskState" json:"desired_state,omitempty"`
+ // List of network attachments by the task.
+ Networks []*NetworkAttachment `protobuf:"bytes,11,rep,name=networks" json:"networks,omitempty"`
+ // A copy of runtime state of service endpoint from Service
+ // object to be distributed to agents as part of the task.
+ Endpoint *Endpoint `protobuf:"bytes,12,opt,name=endpoint" json:"endpoint,omitempty"`
+ // LogDriver specifies the selected log driver to use for the task. Agent
+ // processes should always favor the value in this field.
+ //
+ // If present in the TaskSpec, this will be a copy of that value. The
+ // orchestrator may choose to insert a value here, which should be honored,
+ // such a cluster default or policy-based value.
+ //
+ // If not present, the daemon's default will be used.
+ LogDriver *Driver `protobuf:"bytes,13,opt,name=log_driver,json=logDriver" json:"log_driver,omitempty"`
+ AssignedGenericResources []*GenericResource `protobuf:"bytes,15,rep,name=assigned_generic_resources,json=assignedGenericResources" json:"assigned_generic_resources,omitempty"`
+}
+
+func (m *Task) Reset() { *m = Task{} }
+func (*Task) ProtoMessage() {}
+func (*Task) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{4} }
+
+// NetworkAttachment specifies the network parameters of attachment to
+// a single network by an object such as task or node.
+type NetworkAttachment struct {
+ // Network state as a whole becomes part of the object so that
+ // it always is available for use in agents so that agents
+ // don't have any other dependency during execution.
+ Network *Network `protobuf:"bytes,1,opt,name=network" json:"network,omitempty"`
+ // List of IPv4/IPv6 addresses that are assigned to the object
+ // as part of getting attached to this network.
+ Addresses []string `protobuf:"bytes,2,rep,name=addresses" json:"addresses,omitempty"`
+ // List of aliases by which a task is resolved in a network
+ Aliases []string `protobuf:"bytes,3,rep,name=aliases" json:"aliases,omitempty"`
+ // Map of all the driver attachment options for this network
+ DriverAttachmentOpts map[string]string `protobuf:"bytes,4,rep,name=driver_attachment_opts,json=driverAttachmentOpts" json:"driver_attachment_opts,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+}
+
+func (m *NetworkAttachment) Reset() { *m = NetworkAttachment{} }
+func (*NetworkAttachment) ProtoMessage() {}
+func (*NetworkAttachment) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{5} }
+
+type Network struct {
+ ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
+ Meta Meta `protobuf:"bytes,2,opt,name=meta" json:"meta"`
+ Spec NetworkSpec `protobuf:"bytes,3,opt,name=spec" json:"spec"`
+ // Driver specific operational state provided by the network driver.
+ DriverState *Driver `protobuf:"bytes,4,opt,name=driver_state,json=driverState" json:"driver_state,omitempty"`
+ // Runtime state of IPAM options. This may not reflect the
+ // ipam options from NetworkSpec.
+ IPAM *IPAMOptions `protobuf:"bytes,5,opt,name=ipam" json:"ipam,omitempty"`
+}
+
+func (m *Network) Reset() { *m = Network{} }
+func (*Network) ProtoMessage() {}
+func (*Network) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{6} }
+
+// Cluster provides global cluster settings.
+type Cluster struct {
+ ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
+ Meta Meta `protobuf:"bytes,2,opt,name=meta" json:"meta"`
+ Spec ClusterSpec `protobuf:"bytes,3,opt,name=spec" json:"spec"`
+ // RootCA contains key material for the root CA.
+ RootCA RootCA `protobuf:"bytes,4,opt,name=root_ca,json=rootCa" json:"root_ca"`
+ // Symmetric encryption key distributed by the lead manager. Used by agents
+ // for securing network bootstrapping and communication.
+ NetworkBootstrapKeys []*EncryptionKey `protobuf:"bytes,5,rep,name=network_bootstrap_keys,json=networkBootstrapKeys" json:"network_bootstrap_keys,omitempty"`
+ // Logical clock used to timestamp every key. It allows other managers
+ // and agents to unambiguously identify the older key to be deleted when
+ // a new key is allocated on key rotation.
+ EncryptionKeyLamportClock uint64 `protobuf:"varint,6,opt,name=encryption_key_lamport_clock,json=encryptionKeyLamportClock,proto3" json:"encryption_key_lamport_clock,omitempty"`
+ // BlacklistedCertificates tracks certificates that should no longer
+ // be honored. It's a mapping from CN -> BlacklistedCertificate.
+ // swarm. Their certificates should effectively be blacklisted.
+ BlacklistedCertificates map[string]*BlacklistedCertificate `protobuf:"bytes,8,rep,name=blacklisted_certificates,json=blacklistedCertificates" json:"blacklisted_certificates,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"`
+ // UnlockKeys defines the keys that lock node data at rest. For example,
+ // this would contain the key encrypting key (KEK) that will encrypt the
+ // manager TLS keys at rest and the raft encryption keys at rest.
+ // If the key is empty, the node will be unlocked (will not require a key
+ // to start up from a shut down state).
+ UnlockKeys []*EncryptionKey `protobuf:"bytes,9,rep,name=unlock_keys,json=unlockKeys" json:"unlock_keys,omitempty"`
+}
+
+func (m *Cluster) Reset() { *m = Cluster{} }
+func (*Cluster) ProtoMessage() {}
+func (*Cluster) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{7} }
+
+// Secret represents a secret that should be passed to a container or a node,
+// and is immutable.
+type Secret struct {
+ ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
+ Meta Meta `protobuf:"bytes,2,opt,name=meta" json:"meta"`
+ // Spec contains the actual secret data, as well as any context around the
+ // secret data that the user provides.
+ Spec SecretSpec `protobuf:"bytes,3,opt,name=spec" json:"spec"`
+ // Whether the secret is an internal secret (not set by a user) or not.
+ Internal bool `protobuf:"varint,4,opt,name=internal,proto3" json:"internal,omitempty"`
+}
+
+func (m *Secret) Reset() { *m = Secret{} }
+func (*Secret) ProtoMessage() {}
+func (*Secret) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{8} }
+
+// Config represents a set of configuration files that should be passed to a
+// container.
+type Config struct {
+ ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
+ Meta Meta `protobuf:"bytes,2,opt,name=meta" json:"meta"`
+ // Spec contains the actual config data, as well as any context around the
+ // config data that the user provides.
+ Spec ConfigSpec `protobuf:"bytes,3,opt,name=spec" json:"spec"`
+}
+
+func (m *Config) Reset() { *m = Config{} }
+func (*Config) ProtoMessage() {}
+func (*Config) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{9} }
+
+// Resource is a top-level object with externally defined content and indexing.
+// SwarmKit can serve as a store for these objects without understanding their
+// meanings.
+type Resource struct {
+ ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
+ Meta Meta `protobuf:"bytes,2,opt,name=meta" json:"meta"`
+ Annotations Annotations `protobuf:"bytes,3,opt,name=annotations" json:"annotations"`
+ // Kind identifies this class of object. It is essentially a namespace
+ // to keep IDs or indices from colliding between unrelated Resource
+ // objects. This must correspond to the name of an Extension.
+ Kind string `protobuf:"bytes,4,opt,name=kind,proto3" json:"kind,omitempty"`
+ // Payload bytes. This data is not interpreted in any way by SwarmKit.
+ // By convention, it should be a marshalled protocol buffers message.
+ Payload *google_protobuf3.Any `protobuf:"bytes,5,opt,name=payload" json:"payload,omitempty"`
+}
+
+func (m *Resource) Reset() { *m = Resource{} }
+func (*Resource) ProtoMessage() {}
+func (*Resource) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{10} }
+
+// Extension declares a type of "resource" object. This message provides some
+// metadata about the objects.
+type Extension struct {
+ ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
+ Meta Meta `protobuf:"bytes,2,opt,name=meta" json:"meta"`
+ Annotations Annotations `protobuf:"bytes,3,opt,name=annotations" json:"annotations"`
+ Description string `protobuf:"bytes,4,opt,name=description,proto3" json:"description,omitempty"`
+}
+
+func (m *Extension) Reset() { *m = Extension{} }
+func (*Extension) ProtoMessage() {}
+func (*Extension) Descriptor() ([]byte, []int) { return fileDescriptorObjects, []int{11} }
+
+func init() {
+ proto.RegisterType((*Meta)(nil), "docker.swarmkit.v1.Meta")
+ proto.RegisterType((*Node)(nil), "docker.swarmkit.v1.Node")
+ proto.RegisterType((*Service)(nil), "docker.swarmkit.v1.Service")
+ proto.RegisterType((*Endpoint)(nil), "docker.swarmkit.v1.Endpoint")
+ proto.RegisterType((*Endpoint_VirtualIP)(nil), "docker.swarmkit.v1.Endpoint.VirtualIP")
+ proto.RegisterType((*Task)(nil), "docker.swarmkit.v1.Task")
+ proto.RegisterType((*NetworkAttachment)(nil), "docker.swarmkit.v1.NetworkAttachment")
+ proto.RegisterType((*Network)(nil), "docker.swarmkit.v1.Network")
+ proto.RegisterType((*Cluster)(nil), "docker.swarmkit.v1.Cluster")
+ proto.RegisterType((*Secret)(nil), "docker.swarmkit.v1.Secret")
+ proto.RegisterType((*Config)(nil), "docker.swarmkit.v1.Config")
+ proto.RegisterType((*Resource)(nil), "docker.swarmkit.v1.Resource")
+ proto.RegisterType((*Extension)(nil), "docker.swarmkit.v1.Extension")
+}
+
+func (m *Meta) Copy() *Meta {
+ if m == nil {
+ return nil
+ }
+ o := &Meta{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Meta) CopyFrom(src interface{}) {
+
+ o := src.(*Meta)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Version, &o.Version)
+ if o.CreatedAt != nil {
+ m.CreatedAt = &google_protobuf.Timestamp{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.CreatedAt, o.CreatedAt)
+ }
+ if o.UpdatedAt != nil {
+ m.UpdatedAt = &google_protobuf.Timestamp{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.UpdatedAt, o.UpdatedAt)
+ }
+}
+
+func (m *Node) Copy() *Node {
+ if m == nil {
+ return nil
+ }
+ o := &Node{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Node) CopyFrom(src interface{}) {
+
+ o := src.(*Node)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Meta, &o.Meta)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Spec, &o.Spec)
+ if o.Description != nil {
+ m.Description = &NodeDescription{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Description, o.Description)
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Status, &o.Status)
+ if o.ManagerStatus != nil {
+ m.ManagerStatus = &ManagerStatus{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.ManagerStatus, o.ManagerStatus)
+ }
+ if o.Attachment != nil {
+ m.Attachment = &NetworkAttachment{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Attachment, o.Attachment)
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Certificate, &o.Certificate)
+}
+
+func (m *Service) Copy() *Service {
+ if m == nil {
+ return nil
+ }
+ o := &Service{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Service) CopyFrom(src interface{}) {
+
+ o := src.(*Service)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Meta, &o.Meta)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Spec, &o.Spec)
+ if o.SpecVersion != nil {
+ m.SpecVersion = &Version{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.SpecVersion, o.SpecVersion)
+ }
+ if o.PreviousSpec != nil {
+ m.PreviousSpec = &ServiceSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.PreviousSpec, o.PreviousSpec)
+ }
+ if o.PreviousSpecVersion != nil {
+ m.PreviousSpecVersion = &Version{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.PreviousSpecVersion, o.PreviousSpecVersion)
+ }
+ if o.Endpoint != nil {
+ m.Endpoint = &Endpoint{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Endpoint, o.Endpoint)
+ }
+ if o.UpdateStatus != nil {
+ m.UpdateStatus = &UpdateStatus{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.UpdateStatus, o.UpdateStatus)
+ }
+}
+
+func (m *Endpoint) Copy() *Endpoint {
+ if m == nil {
+ return nil
+ }
+ o := &Endpoint{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Endpoint) CopyFrom(src interface{}) {
+
+ o := src.(*Endpoint)
+ *m = *o
+ if o.Spec != nil {
+ m.Spec = &EndpointSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Spec, o.Spec)
+ }
+ if o.Ports != nil {
+ m.Ports = make([]*PortConfig, len(o.Ports))
+ for i := range m.Ports {
+ m.Ports[i] = &PortConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Ports[i], o.Ports[i])
+ }
+ }
+
+ if o.VirtualIPs != nil {
+ m.VirtualIPs = make([]*Endpoint_VirtualIP, len(o.VirtualIPs))
+ for i := range m.VirtualIPs {
+ m.VirtualIPs[i] = &Endpoint_VirtualIP{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.VirtualIPs[i], o.VirtualIPs[i])
+ }
+ }
+
+}
+
+func (m *Endpoint_VirtualIP) Copy() *Endpoint_VirtualIP {
+ if m == nil {
+ return nil
+ }
+ o := &Endpoint_VirtualIP{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Endpoint_VirtualIP) CopyFrom(src interface{}) {
+
+ o := src.(*Endpoint_VirtualIP)
+ *m = *o
+}
+
+func (m *Task) Copy() *Task {
+ if m == nil {
+ return nil
+ }
+ o := &Task{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Task) CopyFrom(src interface{}) {
+
+ o := src.(*Task)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Meta, &o.Meta)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Spec, &o.Spec)
+ if o.SpecVersion != nil {
+ m.SpecVersion = &Version{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.SpecVersion, o.SpecVersion)
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Annotations, &o.Annotations)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.ServiceAnnotations, &o.ServiceAnnotations)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Status, &o.Status)
+ if o.Networks != nil {
+ m.Networks = make([]*NetworkAttachment, len(o.Networks))
+ for i := range m.Networks {
+ m.Networks[i] = &NetworkAttachment{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Networks[i], o.Networks[i])
+ }
+ }
+
+ if o.Endpoint != nil {
+ m.Endpoint = &Endpoint{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Endpoint, o.Endpoint)
+ }
+ if o.LogDriver != nil {
+ m.LogDriver = &Driver{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.LogDriver, o.LogDriver)
+ }
+ if o.AssignedGenericResources != nil {
+ m.AssignedGenericResources = make([]*GenericResource, len(o.AssignedGenericResources))
+ for i := range m.AssignedGenericResources {
+ m.AssignedGenericResources[i] = &GenericResource{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.AssignedGenericResources[i], o.AssignedGenericResources[i])
+ }
+ }
+
+}
+
+func (m *NetworkAttachment) Copy() *NetworkAttachment {
+ if m == nil {
+ return nil
+ }
+ o := &NetworkAttachment{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *NetworkAttachment) CopyFrom(src interface{}) {
+
+ o := src.(*NetworkAttachment)
+ *m = *o
+ if o.Network != nil {
+ m.Network = &Network{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Network, o.Network)
+ }
+ if o.Addresses != nil {
+ m.Addresses = make([]string, len(o.Addresses))
+ copy(m.Addresses, o.Addresses)
+ }
+
+ if o.Aliases != nil {
+ m.Aliases = make([]string, len(o.Aliases))
+ copy(m.Aliases, o.Aliases)
+ }
+
+ if o.DriverAttachmentOpts != nil {
+ m.DriverAttachmentOpts = make(map[string]string, len(o.DriverAttachmentOpts))
+ for k, v := range o.DriverAttachmentOpts {
+ m.DriverAttachmentOpts[k] = v
+ }
+ }
+
+}
+
+func (m *Network) Copy() *Network {
+ if m == nil {
+ return nil
+ }
+ o := &Network{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Network) CopyFrom(src interface{}) {
+
+ o := src.(*Network)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Meta, &o.Meta)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Spec, &o.Spec)
+ if o.DriverState != nil {
+ m.DriverState = &Driver{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.DriverState, o.DriverState)
+ }
+ if o.IPAM != nil {
+ m.IPAM = &IPAMOptions{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.IPAM, o.IPAM)
+ }
+}
+
+func (m *Cluster) Copy() *Cluster {
+ if m == nil {
+ return nil
+ }
+ o := &Cluster{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Cluster) CopyFrom(src interface{}) {
+
+ o := src.(*Cluster)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Meta, &o.Meta)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Spec, &o.Spec)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.RootCA, &o.RootCA)
+ if o.NetworkBootstrapKeys != nil {
+ m.NetworkBootstrapKeys = make([]*EncryptionKey, len(o.NetworkBootstrapKeys))
+ for i := range m.NetworkBootstrapKeys {
+ m.NetworkBootstrapKeys[i] = &EncryptionKey{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.NetworkBootstrapKeys[i], o.NetworkBootstrapKeys[i])
+ }
+ }
+
+ if o.BlacklistedCertificates != nil {
+ m.BlacklistedCertificates = make(map[string]*BlacklistedCertificate, len(o.BlacklistedCertificates))
+ for k, v := range o.BlacklistedCertificates {
+ m.BlacklistedCertificates[k] = &BlacklistedCertificate{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.BlacklistedCertificates[k], v)
+ }
+ }
+
+ if o.UnlockKeys != nil {
+ m.UnlockKeys = make([]*EncryptionKey, len(o.UnlockKeys))
+ for i := range m.UnlockKeys {
+ m.UnlockKeys[i] = &EncryptionKey{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.UnlockKeys[i], o.UnlockKeys[i])
+ }
+ }
+
+}
+
+func (m *Secret) Copy() *Secret {
+ if m == nil {
+ return nil
+ }
+ o := &Secret{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Secret) CopyFrom(src interface{}) {
+
+ o := src.(*Secret)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Meta, &o.Meta)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Spec, &o.Spec)
+}
+
+func (m *Config) Copy() *Config {
+ if m == nil {
+ return nil
+ }
+ o := &Config{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Config) CopyFrom(src interface{}) {
+
+ o := src.(*Config)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Meta, &o.Meta)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Spec, &o.Spec)
+}
+
+func (m *Resource) Copy() *Resource {
+ if m == nil {
+ return nil
+ }
+ o := &Resource{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Resource) CopyFrom(src interface{}) {
+
+ o := src.(*Resource)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Meta, &o.Meta)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Annotations, &o.Annotations)
+ if o.Payload != nil {
+ m.Payload = &google_protobuf3.Any{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Payload, o.Payload)
+ }
+}
+
+func (m *Extension) Copy() *Extension {
+ if m == nil {
+ return nil
+ }
+ o := &Extension{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Extension) CopyFrom(src interface{}) {
+
+ o := src.(*Extension)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Meta, &o.Meta)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Annotations, &o.Annotations)
+}
+
+func (m *Meta) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Meta) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Version.Size()))
+ n1, err := m.Version.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ if m.CreatedAt != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.CreatedAt.Size()))
+ n2, err := m.CreatedAt.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ }
+ if m.UpdatedAt != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.UpdatedAt.Size()))
+ n3, err := m.UpdatedAt.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ }
+ return i, nil
+}
+
+func (m *Node) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Node) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Meta.Size()))
+ n4, err := m.Meta.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n4
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Spec.Size()))
+ n5, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n5
+ if m.Description != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Description.Size()))
+ n6, err := m.Description.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n6
+ }
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Status.Size()))
+ n7, err := m.Status.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n7
+ if m.ManagerStatus != nil {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.ManagerStatus.Size()))
+ n8, err := m.ManagerStatus.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n8
+ }
+ if m.Attachment != nil {
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Attachment.Size()))
+ n9, err := m.Attachment.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n9
+ }
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Certificate.Size()))
+ n10, err := m.Certificate.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n10
+ if m.Role != 0 {
+ dAtA[i] = 0x48
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Role))
+ }
+ return i, nil
+}
+
+func (m *Service) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Service) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Meta.Size()))
+ n11, err := m.Meta.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n11
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Spec.Size()))
+ n12, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n12
+ if m.Endpoint != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Endpoint.Size()))
+ n13, err := m.Endpoint.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n13
+ }
+ if m.UpdateStatus != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.UpdateStatus.Size()))
+ n14, err := m.UpdateStatus.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n14
+ }
+ if m.PreviousSpec != nil {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.PreviousSpec.Size()))
+ n15, err := m.PreviousSpec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n15
+ }
+ if m.SpecVersion != nil {
+ dAtA[i] = 0x52
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.SpecVersion.Size()))
+ n16, err := m.SpecVersion.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n16
+ }
+ if m.PreviousSpecVersion != nil {
+ dAtA[i] = 0x5a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.PreviousSpecVersion.Size()))
+ n17, err := m.PreviousSpecVersion.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n17
+ }
+ return i, nil
+}
+
+func (m *Endpoint) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Endpoint) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Spec != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Spec.Size()))
+ n18, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n18
+ }
+ if len(m.Ports) > 0 {
+ for _, msg := range m.Ports {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.VirtualIPs) > 0 {
+ for _, msg := range m.VirtualIPs {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *Endpoint_VirtualIP) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Endpoint_VirtualIP) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.NetworkID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.NetworkID)))
+ i += copy(dAtA[i:], m.NetworkID)
+ }
+ if len(m.Addr) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.Addr)))
+ i += copy(dAtA[i:], m.Addr)
+ }
+ return i, nil
+}
+
+func (m *Task) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Task) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Meta.Size()))
+ n19, err := m.Meta.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n19
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Spec.Size()))
+ n20, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n20
+ if len(m.ServiceID) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.ServiceID)))
+ i += copy(dAtA[i:], m.ServiceID)
+ }
+ if m.Slot != 0 {
+ dAtA[i] = 0x28
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Slot))
+ }
+ if len(m.NodeID) > 0 {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.NodeID)))
+ i += copy(dAtA[i:], m.NodeID)
+ }
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Annotations.Size()))
+ n21, err := m.Annotations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n21
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.ServiceAnnotations.Size()))
+ n22, err := m.ServiceAnnotations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n22
+ dAtA[i] = 0x4a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Status.Size()))
+ n23, err := m.Status.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n23
+ if m.DesiredState != 0 {
+ dAtA[i] = 0x50
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.DesiredState))
+ }
+ if len(m.Networks) > 0 {
+ for _, msg := range m.Networks {
+ dAtA[i] = 0x5a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if m.Endpoint != nil {
+ dAtA[i] = 0x62
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Endpoint.Size()))
+ n24, err := m.Endpoint.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n24
+ }
+ if m.LogDriver != nil {
+ dAtA[i] = 0x6a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.LogDriver.Size()))
+ n25, err := m.LogDriver.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n25
+ }
+ if m.SpecVersion != nil {
+ dAtA[i] = 0x72
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.SpecVersion.Size()))
+ n26, err := m.SpecVersion.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n26
+ }
+ if len(m.AssignedGenericResources) > 0 {
+ for _, msg := range m.AssignedGenericResources {
+ dAtA[i] = 0x7a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *NetworkAttachment) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NetworkAttachment) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Network != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Network.Size()))
+ n27, err := m.Network.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n27
+ }
+ if len(m.Addresses) > 0 {
+ for _, s := range m.Addresses {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Aliases) > 0 {
+ for _, s := range m.Aliases {
+ dAtA[i] = 0x1a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.DriverAttachmentOpts) > 0 {
+ for k, _ := range m.DriverAttachmentOpts {
+ dAtA[i] = 0x22
+ i++
+ v := m.DriverAttachmentOpts[k]
+ mapSize := 1 + len(k) + sovObjects(uint64(len(k))) + 1 + len(v) + sovObjects(uint64(len(v)))
+ i = encodeVarintObjects(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ return i, nil
+}
+
+func (m *Network) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Network) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Meta.Size()))
+ n28, err := m.Meta.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n28
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Spec.Size()))
+ n29, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n29
+ if m.DriverState != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.DriverState.Size()))
+ n30, err := m.DriverState.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n30
+ }
+ if m.IPAM != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.IPAM.Size()))
+ n31, err := m.IPAM.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n31
+ }
+ return i, nil
+}
+
+func (m *Cluster) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Cluster) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Meta.Size()))
+ n32, err := m.Meta.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n32
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Spec.Size()))
+ n33, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n33
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.RootCA.Size()))
+ n34, err := m.RootCA.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n34
+ if len(m.NetworkBootstrapKeys) > 0 {
+ for _, msg := range m.NetworkBootstrapKeys {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if m.EncryptionKeyLamportClock != 0 {
+ dAtA[i] = 0x30
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.EncryptionKeyLamportClock))
+ }
+ if len(m.BlacklistedCertificates) > 0 {
+ for k, _ := range m.BlacklistedCertificates {
+ dAtA[i] = 0x42
+ i++
+ v := m.BlacklistedCertificates[k]
+ msgSize := 0
+ if v != nil {
+ msgSize = v.Size()
+ msgSize += 1 + sovObjects(uint64(msgSize))
+ }
+ mapSize := 1 + len(k) + sovObjects(uint64(len(k))) + msgSize
+ i = encodeVarintObjects(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ if v != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(v.Size()))
+ n35, err := v.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n35
+ }
+ }
+ }
+ if len(m.UnlockKeys) > 0 {
+ for _, msg := range m.UnlockKeys {
+ dAtA[i] = 0x4a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *Secret) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Secret) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Meta.Size()))
+ n36, err := m.Meta.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n36
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Spec.Size()))
+ n37, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n37
+ if m.Internal {
+ dAtA[i] = 0x20
+ i++
+ if m.Internal {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ return i, nil
+}
+
+func (m *Config) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Config) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Meta.Size()))
+ n38, err := m.Meta.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n38
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Spec.Size()))
+ n39, err := m.Spec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n39
+ return i, nil
+}
+
+func (m *Resource) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Resource) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Meta.Size()))
+ n40, err := m.Meta.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n40
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Annotations.Size()))
+ n41, err := m.Annotations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n41
+ if len(m.Kind) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.Kind)))
+ i += copy(dAtA[i:], m.Kind)
+ }
+ if m.Payload != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Payload.Size()))
+ n42, err := m.Payload.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n42
+ }
+ return i, nil
+}
+
+func (m *Extension) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Extension) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Meta.Size()))
+ n43, err := m.Meta.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n43
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(m.Annotations.Size()))
+ n44, err := m.Annotations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n44
+ if len(m.Description) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintObjects(dAtA, i, uint64(len(m.Description)))
+ i += copy(dAtA[i:], m.Description)
+ }
+ return i, nil
+}
+
+func encodeFixed64Objects(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Objects(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintObjects(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+func (m *Meta) Size() (n int) {
+ var l int
+ _ = l
+ l = m.Version.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ if m.CreatedAt != nil {
+ l = m.CreatedAt.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.UpdatedAt != nil {
+ l = m.UpdatedAt.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ return n
+}
+
+func (m *Node) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Meta.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.Spec.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ if m.Description != nil {
+ l = m.Description.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Status.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ if m.ManagerStatus != nil {
+ l = m.ManagerStatus.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.Attachment != nil {
+ l = m.Attachment.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Certificate.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ if m.Role != 0 {
+ n += 1 + sovObjects(uint64(m.Role))
+ }
+ return n
+}
+
+func (m *Service) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Meta.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.Spec.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ if m.Endpoint != nil {
+ l = m.Endpoint.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.UpdateStatus != nil {
+ l = m.UpdateStatus.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.PreviousSpec != nil {
+ l = m.PreviousSpec.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.SpecVersion != nil {
+ l = m.SpecVersion.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.PreviousSpecVersion != nil {
+ l = m.PreviousSpecVersion.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ return n
+}
+
+func (m *Endpoint) Size() (n int) {
+ var l int
+ _ = l
+ if m.Spec != nil {
+ l = m.Spec.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if len(m.Ports) > 0 {
+ for _, e := range m.Ports {
+ l = e.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ }
+ if len(m.VirtualIPs) > 0 {
+ for _, e := range m.VirtualIPs {
+ l = e.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *Endpoint_VirtualIP) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.NetworkID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = len(m.Addr)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ return n
+}
+
+func (m *Task) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Meta.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.Spec.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = len(m.ServiceID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.Slot != 0 {
+ n += 1 + sovObjects(uint64(m.Slot))
+ }
+ l = len(m.NodeID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Annotations.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.ServiceAnnotations.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.Status.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ if m.DesiredState != 0 {
+ n += 1 + sovObjects(uint64(m.DesiredState))
+ }
+ if len(m.Networks) > 0 {
+ for _, e := range m.Networks {
+ l = e.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ }
+ if m.Endpoint != nil {
+ l = m.Endpoint.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.LogDriver != nil {
+ l = m.LogDriver.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.SpecVersion != nil {
+ l = m.SpecVersion.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if len(m.AssignedGenericResources) > 0 {
+ for _, e := range m.AssignedGenericResources {
+ l = e.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *NetworkAttachment) Size() (n int) {
+ var l int
+ _ = l
+ if m.Network != nil {
+ l = m.Network.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if len(m.Addresses) > 0 {
+ for _, s := range m.Addresses {
+ l = len(s)
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ }
+ if len(m.Aliases) > 0 {
+ for _, s := range m.Aliases {
+ l = len(s)
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ }
+ if len(m.DriverAttachmentOpts) > 0 {
+ for k, v := range m.DriverAttachmentOpts {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovObjects(uint64(len(k))) + 1 + len(v) + sovObjects(uint64(len(v)))
+ n += mapEntrySize + 1 + sovObjects(uint64(mapEntrySize))
+ }
+ }
+ return n
+}
+
+func (m *Network) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Meta.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.Spec.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ if m.DriverState != nil {
+ l = m.DriverState.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.IPAM != nil {
+ l = m.IPAM.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ return n
+}
+
+func (m *Cluster) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Meta.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.Spec.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.RootCA.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ if len(m.NetworkBootstrapKeys) > 0 {
+ for _, e := range m.NetworkBootstrapKeys {
+ l = e.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ }
+ if m.EncryptionKeyLamportClock != 0 {
+ n += 1 + sovObjects(uint64(m.EncryptionKeyLamportClock))
+ }
+ if len(m.BlacklistedCertificates) > 0 {
+ for k, v := range m.BlacklistedCertificates {
+ _ = k
+ _ = v
+ l = 0
+ if v != nil {
+ l = v.Size()
+ l += 1 + sovObjects(uint64(l))
+ }
+ mapEntrySize := 1 + len(k) + sovObjects(uint64(len(k))) + l
+ n += mapEntrySize + 1 + sovObjects(uint64(mapEntrySize))
+ }
+ }
+ if len(m.UnlockKeys) > 0 {
+ for _, e := range m.UnlockKeys {
+ l = e.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *Secret) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Meta.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.Spec.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ if m.Internal {
+ n += 2
+ }
+ return n
+}
+
+func (m *Config) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Meta.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.Spec.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ return n
+}
+
+func (m *Resource) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Meta.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.Annotations.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = len(m.Kind)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ if m.Payload != nil {
+ l = m.Payload.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ return n
+}
+
+func (m *Extension) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ l = m.Meta.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = m.Annotations.Size()
+ n += 1 + l + sovObjects(uint64(l))
+ l = len(m.Description)
+ if l > 0 {
+ n += 1 + l + sovObjects(uint64(l))
+ }
+ return n
+}
+
+func sovObjects(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozObjects(x uint64) (n int) {
+ return sovObjects(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+
+type NodeCheckFunc func(t1, t2 *Node) bool
+
+type EventCreateNode struct {
+ Node *Node
+ Checks []NodeCheckFunc
+}
+
+func (e EventCreateNode) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventCreateNode)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Node, typedEvent.Node) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventUpdateNode struct {
+ Node *Node
+ OldNode *Node
+ Checks []NodeCheckFunc
+}
+
+func (e EventUpdateNode) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventUpdateNode)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Node, typedEvent.Node) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventDeleteNode struct {
+ Node *Node
+ Checks []NodeCheckFunc
+}
+
+func (e EventDeleteNode) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventDeleteNode)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Node, typedEvent.Node) {
+ return false
+ }
+ }
+ return true
+}
+func (m *Node) CopyStoreObject() StoreObject {
+ return m.Copy()
+}
+
+func (m *Node) GetMeta() Meta {
+ return m.Meta
+}
+
+func (m *Node) SetMeta(meta Meta) {
+ m.Meta = meta
+}
+
+func (m *Node) GetID() string {
+ return m.ID
+}
+
+func (m *Node) EventCreate() Event {
+ return EventCreateNode{Node: m}
+}
+
+func (m *Node) EventUpdate(oldObject StoreObject) Event {
+ if oldObject != nil {
+ return EventUpdateNode{Node: m, OldNode: oldObject.(*Node)}
+ } else {
+ return EventUpdateNode{Node: m}
+ }
+}
+
+func (m *Node) EventDelete() Event {
+ return EventDeleteNode{Node: m}
+}
+
+func NodeCheckID(v1, v2 *Node) bool {
+ return v1.ID == v2.ID
+}
+
+func NodeCheckIDPrefix(v1, v2 *Node) bool {
+ return strings.HasPrefix(v2.ID, v1.ID)
+}
+
+func NodeCheckName(v1, v2 *Node) bool {
+ if v1.Description == nil || v2.Description == nil {
+ return false
+ }
+ return v1.Description.Hostname == v2.Description.Hostname
+}
+
+func NodeCheckNamePrefix(v1, v2 *Node) bool {
+ if v1.Description == nil || v2.Description == nil {
+ return false
+ }
+ return strings.HasPrefix(v2.Description.Hostname, v1.Description.Hostname)
+}
+
+func NodeCheckCustom(v1, v2 *Node) bool {
+ return checkCustom(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func NodeCheckCustomPrefix(v1, v2 *Node) bool {
+ return checkCustomPrefix(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func NodeCheckRole(v1, v2 *Node) bool {
+ return v1.Role == v2.Role
+}
+
+func NodeCheckMembership(v1, v2 *Node) bool {
+ return v1.Spec.Membership == v2.Spec.Membership
+}
+
+func ConvertNodeWatch(action WatchActionKind, filters []*SelectBy) ([]Event, error) {
+ var (
+ m Node
+ checkFuncs []NodeCheckFunc
+ hasRole bool
+ hasMembership bool
+ )
+
+ for _, filter := range filters {
+ switch v := filter.By.(type) {
+ case *SelectBy_ID:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.ID
+ checkFuncs = append(checkFuncs, NodeCheckID)
+ case *SelectBy_IDPrefix:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.IDPrefix
+ checkFuncs = append(checkFuncs, NodeCheckIDPrefix)
+ case *SelectBy_Name:
+ if m.Description != nil {
+ return nil, errConflictingFilters
+ }
+ m.Description = &NodeDescription{Hostname: v.Name}
+ checkFuncs = append(checkFuncs, NodeCheckName)
+ case *SelectBy_NamePrefix:
+ if m.Description != nil {
+ return nil, errConflictingFilters
+ }
+ m.Description = &NodeDescription{Hostname: v.NamePrefix}
+ checkFuncs = append(checkFuncs, NodeCheckNamePrefix)
+ case *SelectBy_Custom:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.Custom.Index, Val: v.Custom.Value}}
+ checkFuncs = append(checkFuncs, NodeCheckCustom)
+ case *SelectBy_CustomPrefix:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.CustomPrefix.Index, Val: v.CustomPrefix.Value}}
+ checkFuncs = append(checkFuncs, NodeCheckCustomPrefix)
+ case *SelectBy_Role:
+ if hasRole {
+ return nil, errConflictingFilters
+ }
+ hasRole = true
+ m.Role = v.Role
+ checkFuncs = append(checkFuncs, NodeCheckRole)
+ case *SelectBy_Membership:
+ if hasMembership {
+ return nil, errConflictingFilters
+ }
+ hasMembership = true
+ m.Spec.Membership = v.Membership
+ checkFuncs = append(checkFuncs, NodeCheckMembership)
+ }
+ }
+ var events []Event
+ if (action & WatchActionKindCreate) != 0 {
+ events = append(events, EventCreateNode{Node: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindUpdate) != 0 {
+ events = append(events, EventUpdateNode{Node: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindRemove) != 0 {
+ events = append(events, EventDeleteNode{Node: &m, Checks: checkFuncs})
+ }
+ if len(events) == 0 {
+ return nil, errUnrecognizedAction
+ }
+ return events, nil
+}
+
+type NodeIndexerByID struct{}
+
+func (indexer NodeIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer NodeIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer NodeIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Node)
+ return true, []byte(m.ID + "\x00"), nil
+}
+
+type NodeIndexerByName struct{}
+
+func (indexer NodeIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer NodeIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer NodeIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Node)
+ val := m.Spec.Annotations.Name
+ return true, []byte(strings.ToLower(val) + "\x00"), nil
+}
+
+type NodeCustomIndexer struct{}
+
+func (indexer NodeCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer NodeCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer NodeCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ m := obj.(*Node)
+ return customIndexer("", &m.Spec.Annotations)
+}
+
+type ServiceCheckFunc func(t1, t2 *Service) bool
+
+type EventCreateService struct {
+ Service *Service
+ Checks []ServiceCheckFunc
+}
+
+func (e EventCreateService) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventCreateService)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Service, typedEvent.Service) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventUpdateService struct {
+ Service *Service
+ OldService *Service
+ Checks []ServiceCheckFunc
+}
+
+func (e EventUpdateService) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventUpdateService)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Service, typedEvent.Service) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventDeleteService struct {
+ Service *Service
+ Checks []ServiceCheckFunc
+}
+
+func (e EventDeleteService) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventDeleteService)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Service, typedEvent.Service) {
+ return false
+ }
+ }
+ return true
+}
+func (m *Service) CopyStoreObject() StoreObject {
+ return m.Copy()
+}
+
+func (m *Service) GetMeta() Meta {
+ return m.Meta
+}
+
+func (m *Service) SetMeta(meta Meta) {
+ m.Meta = meta
+}
+
+func (m *Service) GetID() string {
+ return m.ID
+}
+
+func (m *Service) EventCreate() Event {
+ return EventCreateService{Service: m}
+}
+
+func (m *Service) EventUpdate(oldObject StoreObject) Event {
+ if oldObject != nil {
+ return EventUpdateService{Service: m, OldService: oldObject.(*Service)}
+ } else {
+ return EventUpdateService{Service: m}
+ }
+}
+
+func (m *Service) EventDelete() Event {
+ return EventDeleteService{Service: m}
+}
+
+func ServiceCheckID(v1, v2 *Service) bool {
+ return v1.ID == v2.ID
+}
+
+func ServiceCheckIDPrefix(v1, v2 *Service) bool {
+ return strings.HasPrefix(v2.ID, v1.ID)
+}
+
+func ServiceCheckName(v1, v2 *Service) bool {
+ return v1.Spec.Annotations.Name == v2.Spec.Annotations.Name
+}
+
+func ServiceCheckNamePrefix(v1, v2 *Service) bool {
+ return strings.HasPrefix(v2.Spec.Annotations.Name, v1.Spec.Annotations.Name)
+}
+
+func ServiceCheckCustom(v1, v2 *Service) bool {
+ return checkCustom(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func ServiceCheckCustomPrefix(v1, v2 *Service) bool {
+ return checkCustomPrefix(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func ConvertServiceWatch(action WatchActionKind, filters []*SelectBy) ([]Event, error) {
+ var (
+ m Service
+ checkFuncs []ServiceCheckFunc
+ )
+
+ for _, filter := range filters {
+ switch v := filter.By.(type) {
+ case *SelectBy_ID:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.ID
+ checkFuncs = append(checkFuncs, ServiceCheckID)
+ case *SelectBy_IDPrefix:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.IDPrefix
+ checkFuncs = append(checkFuncs, ServiceCheckIDPrefix)
+ case *SelectBy_Name:
+ if m.Spec.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Name = v.Name
+ checkFuncs = append(checkFuncs, ServiceCheckName)
+ case *SelectBy_NamePrefix:
+ if m.Spec.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Name = v.NamePrefix
+ checkFuncs = append(checkFuncs, ServiceCheckNamePrefix)
+ case *SelectBy_Custom:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.Custom.Index, Val: v.Custom.Value}}
+ checkFuncs = append(checkFuncs, ServiceCheckCustom)
+ case *SelectBy_CustomPrefix:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.CustomPrefix.Index, Val: v.CustomPrefix.Value}}
+ checkFuncs = append(checkFuncs, ServiceCheckCustomPrefix)
+ }
+ }
+ var events []Event
+ if (action & WatchActionKindCreate) != 0 {
+ events = append(events, EventCreateService{Service: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindUpdate) != 0 {
+ events = append(events, EventUpdateService{Service: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindRemove) != 0 {
+ events = append(events, EventDeleteService{Service: &m, Checks: checkFuncs})
+ }
+ if len(events) == 0 {
+ return nil, errUnrecognizedAction
+ }
+ return events, nil
+}
+
+type ServiceIndexerByID struct{}
+
+func (indexer ServiceIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ServiceIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ServiceIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Service)
+ return true, []byte(m.ID + "\x00"), nil
+}
+
+type ServiceIndexerByName struct{}
+
+func (indexer ServiceIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ServiceIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ServiceIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Service)
+ val := m.Spec.Annotations.Name
+ return true, []byte(strings.ToLower(val) + "\x00"), nil
+}
+
+type ServiceCustomIndexer struct{}
+
+func (indexer ServiceCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ServiceCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ServiceCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ m := obj.(*Service)
+ return customIndexer("", &m.Spec.Annotations)
+}
+
+type TaskCheckFunc func(t1, t2 *Task) bool
+
+type EventCreateTask struct {
+ Task *Task
+ Checks []TaskCheckFunc
+}
+
+func (e EventCreateTask) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventCreateTask)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Task, typedEvent.Task) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventUpdateTask struct {
+ Task *Task
+ OldTask *Task
+ Checks []TaskCheckFunc
+}
+
+func (e EventUpdateTask) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventUpdateTask)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Task, typedEvent.Task) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventDeleteTask struct {
+ Task *Task
+ Checks []TaskCheckFunc
+}
+
+func (e EventDeleteTask) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventDeleteTask)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Task, typedEvent.Task) {
+ return false
+ }
+ }
+ return true
+}
+func (m *Task) CopyStoreObject() StoreObject {
+ return m.Copy()
+}
+
+func (m *Task) GetMeta() Meta {
+ return m.Meta
+}
+
+func (m *Task) SetMeta(meta Meta) {
+ m.Meta = meta
+}
+
+func (m *Task) GetID() string {
+ return m.ID
+}
+
+func (m *Task) EventCreate() Event {
+ return EventCreateTask{Task: m}
+}
+
+func (m *Task) EventUpdate(oldObject StoreObject) Event {
+ if oldObject != nil {
+ return EventUpdateTask{Task: m, OldTask: oldObject.(*Task)}
+ } else {
+ return EventUpdateTask{Task: m}
+ }
+}
+
+func (m *Task) EventDelete() Event {
+ return EventDeleteTask{Task: m}
+}
+
+func TaskCheckID(v1, v2 *Task) bool {
+ return v1.ID == v2.ID
+}
+
+func TaskCheckIDPrefix(v1, v2 *Task) bool {
+ return strings.HasPrefix(v2.ID, v1.ID)
+}
+
+func TaskCheckName(v1, v2 *Task) bool {
+ return v1.Annotations.Name == v2.Annotations.Name
+}
+
+func TaskCheckNamePrefix(v1, v2 *Task) bool {
+ return strings.HasPrefix(v2.Annotations.Name, v1.Annotations.Name)
+}
+
+func TaskCheckCustom(v1, v2 *Task) bool {
+ return checkCustom(v1.Annotations, v2.Annotations)
+}
+
+func TaskCheckCustomPrefix(v1, v2 *Task) bool {
+ return checkCustomPrefix(v1.Annotations, v2.Annotations)
+}
+
+func TaskCheckNodeID(v1, v2 *Task) bool {
+ return v1.NodeID == v2.NodeID
+}
+
+func TaskCheckServiceID(v1, v2 *Task) bool {
+ return v1.ServiceID == v2.ServiceID
+}
+
+func TaskCheckSlot(v1, v2 *Task) bool {
+ return v1.Slot == v2.Slot
+}
+
+func TaskCheckDesiredState(v1, v2 *Task) bool {
+ return v1.DesiredState == v2.DesiredState
+}
+
+func ConvertTaskWatch(action WatchActionKind, filters []*SelectBy) ([]Event, error) {
+ var (
+ m Task
+ checkFuncs []TaskCheckFunc
+ hasDesiredState bool
+ )
+
+ for _, filter := range filters {
+ switch v := filter.By.(type) {
+ case *SelectBy_ID:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.ID
+ checkFuncs = append(checkFuncs, TaskCheckID)
+ case *SelectBy_IDPrefix:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.IDPrefix
+ checkFuncs = append(checkFuncs, TaskCheckIDPrefix)
+ case *SelectBy_Name:
+ if m.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Name = v.Name
+ checkFuncs = append(checkFuncs, TaskCheckName)
+ case *SelectBy_NamePrefix:
+ if m.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Name = v.NamePrefix
+ checkFuncs = append(checkFuncs, TaskCheckNamePrefix)
+ case *SelectBy_Custom:
+ if len(m.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Indices = []IndexEntry{{Key: v.Custom.Index, Val: v.Custom.Value}}
+ checkFuncs = append(checkFuncs, TaskCheckCustom)
+ case *SelectBy_CustomPrefix:
+ if len(m.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Indices = []IndexEntry{{Key: v.CustomPrefix.Index, Val: v.CustomPrefix.Value}}
+ checkFuncs = append(checkFuncs, TaskCheckCustomPrefix)
+ case *SelectBy_ServiceID:
+ if m.ServiceID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ServiceID = v.ServiceID
+ checkFuncs = append(checkFuncs, TaskCheckServiceID)
+ case *SelectBy_NodeID:
+ if m.NodeID != "" {
+ return nil, errConflictingFilters
+ }
+ m.NodeID = v.NodeID
+ checkFuncs = append(checkFuncs, TaskCheckNodeID)
+ case *SelectBy_Slot:
+ if m.Slot != 0 || m.ServiceID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ServiceID = v.Slot.ServiceID
+ m.Slot = v.Slot.Slot
+ checkFuncs = append(checkFuncs, TaskCheckNodeID, TaskCheckSlot)
+ case *SelectBy_DesiredState:
+ if hasDesiredState {
+ return nil, errConflictingFilters
+ }
+ hasDesiredState = true
+ m.DesiredState = v.DesiredState
+ checkFuncs = append(checkFuncs, TaskCheckDesiredState)
+ }
+ }
+ var events []Event
+ if (action & WatchActionKindCreate) != 0 {
+ events = append(events, EventCreateTask{Task: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindUpdate) != 0 {
+ events = append(events, EventUpdateTask{Task: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindRemove) != 0 {
+ events = append(events, EventDeleteTask{Task: &m, Checks: checkFuncs})
+ }
+ if len(events) == 0 {
+ return nil, errUnrecognizedAction
+ }
+ return events, nil
+}
+
+type TaskIndexerByID struct{}
+
+func (indexer TaskIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer TaskIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer TaskIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Task)
+ return true, []byte(m.ID + "\x00"), nil
+}
+
+type TaskIndexerByName struct{}
+
+func (indexer TaskIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer TaskIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer TaskIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Task)
+ val := m.Annotations.Name
+ return true, []byte(strings.ToLower(val) + "\x00"), nil
+}
+
+type TaskCustomIndexer struct{}
+
+func (indexer TaskCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer TaskCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer TaskCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ m := obj.(*Task)
+ return customIndexer("", &m.Annotations)
+}
+
+type NetworkCheckFunc func(t1, t2 *Network) bool
+
+type EventCreateNetwork struct {
+ Network *Network
+ Checks []NetworkCheckFunc
+}
+
+func (e EventCreateNetwork) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventCreateNetwork)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Network, typedEvent.Network) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventUpdateNetwork struct {
+ Network *Network
+ OldNetwork *Network
+ Checks []NetworkCheckFunc
+}
+
+func (e EventUpdateNetwork) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventUpdateNetwork)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Network, typedEvent.Network) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventDeleteNetwork struct {
+ Network *Network
+ Checks []NetworkCheckFunc
+}
+
+func (e EventDeleteNetwork) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventDeleteNetwork)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Network, typedEvent.Network) {
+ return false
+ }
+ }
+ return true
+}
+func (m *Network) CopyStoreObject() StoreObject {
+ return m.Copy()
+}
+
+func (m *Network) GetMeta() Meta {
+ return m.Meta
+}
+
+func (m *Network) SetMeta(meta Meta) {
+ m.Meta = meta
+}
+
+func (m *Network) GetID() string {
+ return m.ID
+}
+
+func (m *Network) EventCreate() Event {
+ return EventCreateNetwork{Network: m}
+}
+
+func (m *Network) EventUpdate(oldObject StoreObject) Event {
+ if oldObject != nil {
+ return EventUpdateNetwork{Network: m, OldNetwork: oldObject.(*Network)}
+ } else {
+ return EventUpdateNetwork{Network: m}
+ }
+}
+
+func (m *Network) EventDelete() Event {
+ return EventDeleteNetwork{Network: m}
+}
+
+func NetworkCheckID(v1, v2 *Network) bool {
+ return v1.ID == v2.ID
+}
+
+func NetworkCheckIDPrefix(v1, v2 *Network) bool {
+ return strings.HasPrefix(v2.ID, v1.ID)
+}
+
+func NetworkCheckName(v1, v2 *Network) bool {
+ return v1.Spec.Annotations.Name == v2.Spec.Annotations.Name
+}
+
+func NetworkCheckNamePrefix(v1, v2 *Network) bool {
+ return strings.HasPrefix(v2.Spec.Annotations.Name, v1.Spec.Annotations.Name)
+}
+
+func NetworkCheckCustom(v1, v2 *Network) bool {
+ return checkCustom(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func NetworkCheckCustomPrefix(v1, v2 *Network) bool {
+ return checkCustomPrefix(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func ConvertNetworkWatch(action WatchActionKind, filters []*SelectBy) ([]Event, error) {
+ var (
+ m Network
+ checkFuncs []NetworkCheckFunc
+ )
+
+ for _, filter := range filters {
+ switch v := filter.By.(type) {
+ case *SelectBy_ID:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.ID
+ checkFuncs = append(checkFuncs, NetworkCheckID)
+ case *SelectBy_IDPrefix:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.IDPrefix
+ checkFuncs = append(checkFuncs, NetworkCheckIDPrefix)
+ case *SelectBy_Name:
+ if m.Spec.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Name = v.Name
+ checkFuncs = append(checkFuncs, NetworkCheckName)
+ case *SelectBy_NamePrefix:
+ if m.Spec.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Name = v.NamePrefix
+ checkFuncs = append(checkFuncs, NetworkCheckNamePrefix)
+ case *SelectBy_Custom:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.Custom.Index, Val: v.Custom.Value}}
+ checkFuncs = append(checkFuncs, NetworkCheckCustom)
+ case *SelectBy_CustomPrefix:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.CustomPrefix.Index, Val: v.CustomPrefix.Value}}
+ checkFuncs = append(checkFuncs, NetworkCheckCustomPrefix)
+ }
+ }
+ var events []Event
+ if (action & WatchActionKindCreate) != 0 {
+ events = append(events, EventCreateNetwork{Network: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindUpdate) != 0 {
+ events = append(events, EventUpdateNetwork{Network: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindRemove) != 0 {
+ events = append(events, EventDeleteNetwork{Network: &m, Checks: checkFuncs})
+ }
+ if len(events) == 0 {
+ return nil, errUnrecognizedAction
+ }
+ return events, nil
+}
+
+type NetworkIndexerByID struct{}
+
+func (indexer NetworkIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer NetworkIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer NetworkIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Network)
+ return true, []byte(m.ID + "\x00"), nil
+}
+
+type NetworkIndexerByName struct{}
+
+func (indexer NetworkIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer NetworkIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer NetworkIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Network)
+ val := m.Spec.Annotations.Name
+ return true, []byte(strings.ToLower(val) + "\x00"), nil
+}
+
+type NetworkCustomIndexer struct{}
+
+func (indexer NetworkCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer NetworkCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer NetworkCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ m := obj.(*Network)
+ return customIndexer("", &m.Spec.Annotations)
+}
+
+type ClusterCheckFunc func(t1, t2 *Cluster) bool
+
+type EventCreateCluster struct {
+ Cluster *Cluster
+ Checks []ClusterCheckFunc
+}
+
+func (e EventCreateCluster) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventCreateCluster)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Cluster, typedEvent.Cluster) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventUpdateCluster struct {
+ Cluster *Cluster
+ OldCluster *Cluster
+ Checks []ClusterCheckFunc
+}
+
+func (e EventUpdateCluster) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventUpdateCluster)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Cluster, typedEvent.Cluster) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventDeleteCluster struct {
+ Cluster *Cluster
+ Checks []ClusterCheckFunc
+}
+
+func (e EventDeleteCluster) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventDeleteCluster)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Cluster, typedEvent.Cluster) {
+ return false
+ }
+ }
+ return true
+}
+func (m *Cluster) CopyStoreObject() StoreObject {
+ return m.Copy()
+}
+
+func (m *Cluster) GetMeta() Meta {
+ return m.Meta
+}
+
+func (m *Cluster) SetMeta(meta Meta) {
+ m.Meta = meta
+}
+
+func (m *Cluster) GetID() string {
+ return m.ID
+}
+
+func (m *Cluster) EventCreate() Event {
+ return EventCreateCluster{Cluster: m}
+}
+
+func (m *Cluster) EventUpdate(oldObject StoreObject) Event {
+ if oldObject != nil {
+ return EventUpdateCluster{Cluster: m, OldCluster: oldObject.(*Cluster)}
+ } else {
+ return EventUpdateCluster{Cluster: m}
+ }
+}
+
+func (m *Cluster) EventDelete() Event {
+ return EventDeleteCluster{Cluster: m}
+}
+
+func ClusterCheckID(v1, v2 *Cluster) bool {
+ return v1.ID == v2.ID
+}
+
+func ClusterCheckIDPrefix(v1, v2 *Cluster) bool {
+ return strings.HasPrefix(v2.ID, v1.ID)
+}
+
+func ClusterCheckName(v1, v2 *Cluster) bool {
+ return v1.Spec.Annotations.Name == v2.Spec.Annotations.Name
+}
+
+func ClusterCheckNamePrefix(v1, v2 *Cluster) bool {
+ return strings.HasPrefix(v2.Spec.Annotations.Name, v1.Spec.Annotations.Name)
+}
+
+func ClusterCheckCustom(v1, v2 *Cluster) bool {
+ return checkCustom(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func ClusterCheckCustomPrefix(v1, v2 *Cluster) bool {
+ return checkCustomPrefix(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func ConvertClusterWatch(action WatchActionKind, filters []*SelectBy) ([]Event, error) {
+ var (
+ m Cluster
+ checkFuncs []ClusterCheckFunc
+ )
+
+ for _, filter := range filters {
+ switch v := filter.By.(type) {
+ case *SelectBy_ID:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.ID
+ checkFuncs = append(checkFuncs, ClusterCheckID)
+ case *SelectBy_IDPrefix:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.IDPrefix
+ checkFuncs = append(checkFuncs, ClusterCheckIDPrefix)
+ case *SelectBy_Name:
+ if m.Spec.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Name = v.Name
+ checkFuncs = append(checkFuncs, ClusterCheckName)
+ case *SelectBy_NamePrefix:
+ if m.Spec.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Name = v.NamePrefix
+ checkFuncs = append(checkFuncs, ClusterCheckNamePrefix)
+ case *SelectBy_Custom:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.Custom.Index, Val: v.Custom.Value}}
+ checkFuncs = append(checkFuncs, ClusterCheckCustom)
+ case *SelectBy_CustomPrefix:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.CustomPrefix.Index, Val: v.CustomPrefix.Value}}
+ checkFuncs = append(checkFuncs, ClusterCheckCustomPrefix)
+ }
+ }
+ var events []Event
+ if (action & WatchActionKindCreate) != 0 {
+ events = append(events, EventCreateCluster{Cluster: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindUpdate) != 0 {
+ events = append(events, EventUpdateCluster{Cluster: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindRemove) != 0 {
+ events = append(events, EventDeleteCluster{Cluster: &m, Checks: checkFuncs})
+ }
+ if len(events) == 0 {
+ return nil, errUnrecognizedAction
+ }
+ return events, nil
+}
+
+type ClusterIndexerByID struct{}
+
+func (indexer ClusterIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ClusterIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ClusterIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Cluster)
+ return true, []byte(m.ID + "\x00"), nil
+}
+
+type ClusterIndexerByName struct{}
+
+func (indexer ClusterIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ClusterIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ClusterIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Cluster)
+ val := m.Spec.Annotations.Name
+ return true, []byte(strings.ToLower(val) + "\x00"), nil
+}
+
+type ClusterCustomIndexer struct{}
+
+func (indexer ClusterCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ClusterCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ClusterCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ m := obj.(*Cluster)
+ return customIndexer("", &m.Spec.Annotations)
+}
+
+type SecretCheckFunc func(t1, t2 *Secret) bool
+
+type EventCreateSecret struct {
+ Secret *Secret
+ Checks []SecretCheckFunc
+}
+
+func (e EventCreateSecret) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventCreateSecret)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Secret, typedEvent.Secret) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventUpdateSecret struct {
+ Secret *Secret
+ OldSecret *Secret
+ Checks []SecretCheckFunc
+}
+
+func (e EventUpdateSecret) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventUpdateSecret)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Secret, typedEvent.Secret) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventDeleteSecret struct {
+ Secret *Secret
+ Checks []SecretCheckFunc
+}
+
+func (e EventDeleteSecret) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventDeleteSecret)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Secret, typedEvent.Secret) {
+ return false
+ }
+ }
+ return true
+}
+func (m *Secret) CopyStoreObject() StoreObject {
+ return m.Copy()
+}
+
+func (m *Secret) GetMeta() Meta {
+ return m.Meta
+}
+
+func (m *Secret) SetMeta(meta Meta) {
+ m.Meta = meta
+}
+
+func (m *Secret) GetID() string {
+ return m.ID
+}
+
+func (m *Secret) EventCreate() Event {
+ return EventCreateSecret{Secret: m}
+}
+
+func (m *Secret) EventUpdate(oldObject StoreObject) Event {
+ if oldObject != nil {
+ return EventUpdateSecret{Secret: m, OldSecret: oldObject.(*Secret)}
+ } else {
+ return EventUpdateSecret{Secret: m}
+ }
+}
+
+func (m *Secret) EventDelete() Event {
+ return EventDeleteSecret{Secret: m}
+}
+
+func SecretCheckID(v1, v2 *Secret) bool {
+ return v1.ID == v2.ID
+}
+
+func SecretCheckIDPrefix(v1, v2 *Secret) bool {
+ return strings.HasPrefix(v2.ID, v1.ID)
+}
+
+func SecretCheckName(v1, v2 *Secret) bool {
+ return v1.Spec.Annotations.Name == v2.Spec.Annotations.Name
+}
+
+func SecretCheckNamePrefix(v1, v2 *Secret) bool {
+ return strings.HasPrefix(v2.Spec.Annotations.Name, v1.Spec.Annotations.Name)
+}
+
+func SecretCheckCustom(v1, v2 *Secret) bool {
+ return checkCustom(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func SecretCheckCustomPrefix(v1, v2 *Secret) bool {
+ return checkCustomPrefix(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func ConvertSecretWatch(action WatchActionKind, filters []*SelectBy) ([]Event, error) {
+ var (
+ m Secret
+ checkFuncs []SecretCheckFunc
+ )
+
+ for _, filter := range filters {
+ switch v := filter.By.(type) {
+ case *SelectBy_ID:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.ID
+ checkFuncs = append(checkFuncs, SecretCheckID)
+ case *SelectBy_IDPrefix:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.IDPrefix
+ checkFuncs = append(checkFuncs, SecretCheckIDPrefix)
+ case *SelectBy_Name:
+ if m.Spec.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Name = v.Name
+ checkFuncs = append(checkFuncs, SecretCheckName)
+ case *SelectBy_NamePrefix:
+ if m.Spec.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Name = v.NamePrefix
+ checkFuncs = append(checkFuncs, SecretCheckNamePrefix)
+ case *SelectBy_Custom:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.Custom.Index, Val: v.Custom.Value}}
+ checkFuncs = append(checkFuncs, SecretCheckCustom)
+ case *SelectBy_CustomPrefix:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.CustomPrefix.Index, Val: v.CustomPrefix.Value}}
+ checkFuncs = append(checkFuncs, SecretCheckCustomPrefix)
+ }
+ }
+ var events []Event
+ if (action & WatchActionKindCreate) != 0 {
+ events = append(events, EventCreateSecret{Secret: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindUpdate) != 0 {
+ events = append(events, EventUpdateSecret{Secret: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindRemove) != 0 {
+ events = append(events, EventDeleteSecret{Secret: &m, Checks: checkFuncs})
+ }
+ if len(events) == 0 {
+ return nil, errUnrecognizedAction
+ }
+ return events, nil
+}
+
+type SecretIndexerByID struct{}
+
+func (indexer SecretIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer SecretIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer SecretIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Secret)
+ return true, []byte(m.ID + "\x00"), nil
+}
+
+type SecretIndexerByName struct{}
+
+func (indexer SecretIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer SecretIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer SecretIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Secret)
+ val := m.Spec.Annotations.Name
+ return true, []byte(strings.ToLower(val) + "\x00"), nil
+}
+
+type SecretCustomIndexer struct{}
+
+func (indexer SecretCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer SecretCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer SecretCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ m := obj.(*Secret)
+ return customIndexer("", &m.Spec.Annotations)
+}
+
+type ConfigCheckFunc func(t1, t2 *Config) bool
+
+type EventCreateConfig struct {
+ Config *Config
+ Checks []ConfigCheckFunc
+}
+
+func (e EventCreateConfig) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventCreateConfig)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Config, typedEvent.Config) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventUpdateConfig struct {
+ Config *Config
+ OldConfig *Config
+ Checks []ConfigCheckFunc
+}
+
+func (e EventUpdateConfig) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventUpdateConfig)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Config, typedEvent.Config) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventDeleteConfig struct {
+ Config *Config
+ Checks []ConfigCheckFunc
+}
+
+func (e EventDeleteConfig) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventDeleteConfig)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Config, typedEvent.Config) {
+ return false
+ }
+ }
+ return true
+}
+func (m *Config) CopyStoreObject() StoreObject {
+ return m.Copy()
+}
+
+func (m *Config) GetMeta() Meta {
+ return m.Meta
+}
+
+func (m *Config) SetMeta(meta Meta) {
+ m.Meta = meta
+}
+
+func (m *Config) GetID() string {
+ return m.ID
+}
+
+func (m *Config) EventCreate() Event {
+ return EventCreateConfig{Config: m}
+}
+
+func (m *Config) EventUpdate(oldObject StoreObject) Event {
+ if oldObject != nil {
+ return EventUpdateConfig{Config: m, OldConfig: oldObject.(*Config)}
+ } else {
+ return EventUpdateConfig{Config: m}
+ }
+}
+
+func (m *Config) EventDelete() Event {
+ return EventDeleteConfig{Config: m}
+}
+
+func ConfigCheckID(v1, v2 *Config) bool {
+ return v1.ID == v2.ID
+}
+
+func ConfigCheckIDPrefix(v1, v2 *Config) bool {
+ return strings.HasPrefix(v2.ID, v1.ID)
+}
+
+func ConfigCheckName(v1, v2 *Config) bool {
+ return v1.Spec.Annotations.Name == v2.Spec.Annotations.Name
+}
+
+func ConfigCheckNamePrefix(v1, v2 *Config) bool {
+ return strings.HasPrefix(v2.Spec.Annotations.Name, v1.Spec.Annotations.Name)
+}
+
+func ConfigCheckCustom(v1, v2 *Config) bool {
+ return checkCustom(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func ConfigCheckCustomPrefix(v1, v2 *Config) bool {
+ return checkCustomPrefix(v1.Spec.Annotations, v2.Spec.Annotations)
+}
+
+func ConvertConfigWatch(action WatchActionKind, filters []*SelectBy) ([]Event, error) {
+ var (
+ m Config
+ checkFuncs []ConfigCheckFunc
+ )
+
+ for _, filter := range filters {
+ switch v := filter.By.(type) {
+ case *SelectBy_ID:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.ID
+ checkFuncs = append(checkFuncs, ConfigCheckID)
+ case *SelectBy_IDPrefix:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.IDPrefix
+ checkFuncs = append(checkFuncs, ConfigCheckIDPrefix)
+ case *SelectBy_Name:
+ if m.Spec.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Name = v.Name
+ checkFuncs = append(checkFuncs, ConfigCheckName)
+ case *SelectBy_NamePrefix:
+ if m.Spec.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Name = v.NamePrefix
+ checkFuncs = append(checkFuncs, ConfigCheckNamePrefix)
+ case *SelectBy_Custom:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.Custom.Index, Val: v.Custom.Value}}
+ checkFuncs = append(checkFuncs, ConfigCheckCustom)
+ case *SelectBy_CustomPrefix:
+ if len(m.Spec.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Spec.Annotations.Indices = []IndexEntry{{Key: v.CustomPrefix.Index, Val: v.CustomPrefix.Value}}
+ checkFuncs = append(checkFuncs, ConfigCheckCustomPrefix)
+ }
+ }
+ var events []Event
+ if (action & WatchActionKindCreate) != 0 {
+ events = append(events, EventCreateConfig{Config: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindUpdate) != 0 {
+ events = append(events, EventUpdateConfig{Config: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindRemove) != 0 {
+ events = append(events, EventDeleteConfig{Config: &m, Checks: checkFuncs})
+ }
+ if len(events) == 0 {
+ return nil, errUnrecognizedAction
+ }
+ return events, nil
+}
+
+type ConfigIndexerByID struct{}
+
+func (indexer ConfigIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ConfigIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ConfigIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Config)
+ return true, []byte(m.ID + "\x00"), nil
+}
+
+type ConfigIndexerByName struct{}
+
+func (indexer ConfigIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ConfigIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ConfigIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Config)
+ val := m.Spec.Annotations.Name
+ return true, []byte(strings.ToLower(val) + "\x00"), nil
+}
+
+type ConfigCustomIndexer struct{}
+
+func (indexer ConfigCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ConfigCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ConfigCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ m := obj.(*Config)
+ return customIndexer("", &m.Spec.Annotations)
+}
+
+type ResourceCheckFunc func(t1, t2 *Resource) bool
+
+type EventCreateResource struct {
+ Resource *Resource
+ Checks []ResourceCheckFunc
+}
+
+func (e EventCreateResource) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventCreateResource)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Resource, typedEvent.Resource) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventUpdateResource struct {
+ Resource *Resource
+ OldResource *Resource
+ Checks []ResourceCheckFunc
+}
+
+func (e EventUpdateResource) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventUpdateResource)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Resource, typedEvent.Resource) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventDeleteResource struct {
+ Resource *Resource
+ Checks []ResourceCheckFunc
+}
+
+func (e EventDeleteResource) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventDeleteResource)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Resource, typedEvent.Resource) {
+ return false
+ }
+ }
+ return true
+}
+func (m *Resource) CopyStoreObject() StoreObject {
+ return m.Copy()
+}
+
+func (m *Resource) GetMeta() Meta {
+ return m.Meta
+}
+
+func (m *Resource) SetMeta(meta Meta) {
+ m.Meta = meta
+}
+
+func (m *Resource) GetID() string {
+ return m.ID
+}
+
+func (m *Resource) EventCreate() Event {
+ return EventCreateResource{Resource: m}
+}
+
+func (m *Resource) EventUpdate(oldObject StoreObject) Event {
+ if oldObject != nil {
+ return EventUpdateResource{Resource: m, OldResource: oldObject.(*Resource)}
+ } else {
+ return EventUpdateResource{Resource: m}
+ }
+}
+
+func (m *Resource) EventDelete() Event {
+ return EventDeleteResource{Resource: m}
+}
+
+func ResourceCheckID(v1, v2 *Resource) bool {
+ return v1.ID == v2.ID
+}
+
+func ResourceCheckIDPrefix(v1, v2 *Resource) bool {
+ return strings.HasPrefix(v2.ID, v1.ID)
+}
+
+func ResourceCheckName(v1, v2 *Resource) bool {
+ return v1.Annotations.Name == v2.Annotations.Name
+}
+
+func ResourceCheckNamePrefix(v1, v2 *Resource) bool {
+ return strings.HasPrefix(v2.Annotations.Name, v1.Annotations.Name)
+}
+
+func ResourceCheckCustom(v1, v2 *Resource) bool {
+ return checkCustom(v1.Annotations, v2.Annotations)
+}
+
+func ResourceCheckCustomPrefix(v1, v2 *Resource) bool {
+ return checkCustomPrefix(v1.Annotations, v2.Annotations)
+}
+
+func ResourceCheckKind(v1, v2 *Resource) bool {
+ return v1.Kind == v2.Kind
+}
+
+func ConvertResourceWatch(action WatchActionKind, filters []*SelectBy, kind string) ([]Event, error) {
+ var (
+ m Resource
+ checkFuncs []ResourceCheckFunc
+ )
+ m.Kind = kind
+ checkFuncs = append(checkFuncs, ResourceCheckKind)
+
+ for _, filter := range filters {
+ switch v := filter.By.(type) {
+ case *SelectBy_ID:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.ID
+ checkFuncs = append(checkFuncs, ResourceCheckID)
+ case *SelectBy_IDPrefix:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.IDPrefix
+ checkFuncs = append(checkFuncs, ResourceCheckIDPrefix)
+ case *SelectBy_Name:
+ if m.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Name = v.Name
+ checkFuncs = append(checkFuncs, ResourceCheckName)
+ case *SelectBy_NamePrefix:
+ if m.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Name = v.NamePrefix
+ checkFuncs = append(checkFuncs, ResourceCheckNamePrefix)
+ case *SelectBy_Custom:
+ if len(m.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Indices = []IndexEntry{{Key: v.Custom.Index, Val: v.Custom.Value}}
+ checkFuncs = append(checkFuncs, ResourceCheckCustom)
+ case *SelectBy_CustomPrefix:
+ if len(m.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Indices = []IndexEntry{{Key: v.CustomPrefix.Index, Val: v.CustomPrefix.Value}}
+ checkFuncs = append(checkFuncs, ResourceCheckCustomPrefix)
+ }
+ }
+ var events []Event
+ if (action & WatchActionKindCreate) != 0 {
+ events = append(events, EventCreateResource{Resource: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindUpdate) != 0 {
+ events = append(events, EventUpdateResource{Resource: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindRemove) != 0 {
+ events = append(events, EventDeleteResource{Resource: &m, Checks: checkFuncs})
+ }
+ if len(events) == 0 {
+ return nil, errUnrecognizedAction
+ }
+ return events, nil
+}
+
+type ResourceIndexerByID struct{}
+
+func (indexer ResourceIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ResourceIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ResourceIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Resource)
+ return true, []byte(m.ID + "\x00"), nil
+}
+
+type ResourceIndexerByName struct{}
+
+func (indexer ResourceIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ResourceIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ResourceIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Resource)
+ val := m.Annotations.Name
+ return true, []byte(strings.ToLower(val) + "\x00"), nil
+}
+
+type ResourceCustomIndexer struct{}
+
+func (indexer ResourceCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ResourceCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ResourceCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ m := obj.(*Resource)
+ return customIndexer("", &m.Annotations)
+}
+
+type ExtensionCheckFunc func(t1, t2 *Extension) bool
+
+type EventCreateExtension struct {
+ Extension *Extension
+ Checks []ExtensionCheckFunc
+}
+
+func (e EventCreateExtension) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventCreateExtension)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Extension, typedEvent.Extension) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventUpdateExtension struct {
+ Extension *Extension
+ OldExtension *Extension
+ Checks []ExtensionCheckFunc
+}
+
+func (e EventUpdateExtension) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventUpdateExtension)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Extension, typedEvent.Extension) {
+ return false
+ }
+ }
+ return true
+}
+
+type EventDeleteExtension struct {
+ Extension *Extension
+ Checks []ExtensionCheckFunc
+}
+
+func (e EventDeleteExtension) Matches(apiEvent github_com_docker_go_events.Event) bool {
+ typedEvent, ok := apiEvent.(EventDeleteExtension)
+ if !ok {
+ return false
+ }
+
+ for _, check := range e.Checks {
+ if !check(e.Extension, typedEvent.Extension) {
+ return false
+ }
+ }
+ return true
+}
+func (m *Extension) CopyStoreObject() StoreObject {
+ return m.Copy()
+}
+
+func (m *Extension) GetMeta() Meta {
+ return m.Meta
+}
+
+func (m *Extension) SetMeta(meta Meta) {
+ m.Meta = meta
+}
+
+func (m *Extension) GetID() string {
+ return m.ID
+}
+
+func (m *Extension) EventCreate() Event {
+ return EventCreateExtension{Extension: m}
+}
+
+func (m *Extension) EventUpdate(oldObject StoreObject) Event {
+ if oldObject != nil {
+ return EventUpdateExtension{Extension: m, OldExtension: oldObject.(*Extension)}
+ } else {
+ return EventUpdateExtension{Extension: m}
+ }
+}
+
+func (m *Extension) EventDelete() Event {
+ return EventDeleteExtension{Extension: m}
+}
+
+func ExtensionCheckID(v1, v2 *Extension) bool {
+ return v1.ID == v2.ID
+}
+
+func ExtensionCheckIDPrefix(v1, v2 *Extension) bool {
+ return strings.HasPrefix(v2.ID, v1.ID)
+}
+
+func ExtensionCheckName(v1, v2 *Extension) bool {
+ return v1.Annotations.Name == v2.Annotations.Name
+}
+
+func ExtensionCheckNamePrefix(v1, v2 *Extension) bool {
+ return strings.HasPrefix(v2.Annotations.Name, v1.Annotations.Name)
+}
+
+func ExtensionCheckCustom(v1, v2 *Extension) bool {
+ return checkCustom(v1.Annotations, v2.Annotations)
+}
+
+func ExtensionCheckCustomPrefix(v1, v2 *Extension) bool {
+ return checkCustomPrefix(v1.Annotations, v2.Annotations)
+}
+
+func ConvertExtensionWatch(action WatchActionKind, filters []*SelectBy) ([]Event, error) {
+ var (
+ m Extension
+ checkFuncs []ExtensionCheckFunc
+ )
+
+ for _, filter := range filters {
+ switch v := filter.By.(type) {
+ case *SelectBy_ID:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.ID
+ checkFuncs = append(checkFuncs, ExtensionCheckID)
+ case *SelectBy_IDPrefix:
+ if m.ID != "" {
+ return nil, errConflictingFilters
+ }
+ m.ID = v.IDPrefix
+ checkFuncs = append(checkFuncs, ExtensionCheckIDPrefix)
+ case *SelectBy_Name:
+ if m.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Name = v.Name
+ checkFuncs = append(checkFuncs, ExtensionCheckName)
+ case *SelectBy_NamePrefix:
+ if m.Annotations.Name != "" {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Name = v.NamePrefix
+ checkFuncs = append(checkFuncs, ExtensionCheckNamePrefix)
+ case *SelectBy_Custom:
+ if len(m.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Indices = []IndexEntry{{Key: v.Custom.Index, Val: v.Custom.Value}}
+ checkFuncs = append(checkFuncs, ExtensionCheckCustom)
+ case *SelectBy_CustomPrefix:
+ if len(m.Annotations.Indices) != 0 {
+ return nil, errConflictingFilters
+ }
+ m.Annotations.Indices = []IndexEntry{{Key: v.CustomPrefix.Index, Val: v.CustomPrefix.Value}}
+ checkFuncs = append(checkFuncs, ExtensionCheckCustomPrefix)
+ }
+ }
+ var events []Event
+ if (action & WatchActionKindCreate) != 0 {
+ events = append(events, EventCreateExtension{Extension: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindUpdate) != 0 {
+ events = append(events, EventUpdateExtension{Extension: &m, Checks: checkFuncs})
+ }
+ if (action & WatchActionKindRemove) != 0 {
+ events = append(events, EventDeleteExtension{Extension: &m, Checks: checkFuncs})
+ }
+ if len(events) == 0 {
+ return nil, errUnrecognizedAction
+ }
+ return events, nil
+}
+
+type ExtensionIndexerByID struct{}
+
+func (indexer ExtensionIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ExtensionIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ExtensionIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Extension)
+ return true, []byte(m.ID + "\x00"), nil
+}
+
+type ExtensionIndexerByName struct{}
+
+func (indexer ExtensionIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ExtensionIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ExtensionIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ m := obj.(*Extension)
+ val := m.Annotations.Name
+ return true, []byte(strings.ToLower(val) + "\x00"), nil
+}
+
+type ExtensionCustomIndexer struct{}
+
+func (indexer ExtensionCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+func (indexer ExtensionCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+func (indexer ExtensionCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ m := obj.(*Extension)
+ return customIndexer("", &m.Annotations)
+}
+func NewStoreAction(c Event) (StoreAction, error) {
+ var sa StoreAction
+ switch v := c.(type) {
+ case EventCreateNode:
+ sa.Action = StoreActionKindCreate
+ sa.Target = &StoreAction_Node{Node: v.Node}
+ case EventUpdateNode:
+ sa.Action = StoreActionKindUpdate
+ sa.Target = &StoreAction_Node{Node: v.Node}
+ case EventDeleteNode:
+ sa.Action = StoreActionKindRemove
+ sa.Target = &StoreAction_Node{Node: v.Node}
+ case EventCreateService:
+ sa.Action = StoreActionKindCreate
+ sa.Target = &StoreAction_Service{Service: v.Service}
+ case EventUpdateService:
+ sa.Action = StoreActionKindUpdate
+ sa.Target = &StoreAction_Service{Service: v.Service}
+ case EventDeleteService:
+ sa.Action = StoreActionKindRemove
+ sa.Target = &StoreAction_Service{Service: v.Service}
+ case EventCreateTask:
+ sa.Action = StoreActionKindCreate
+ sa.Target = &StoreAction_Task{Task: v.Task}
+ case EventUpdateTask:
+ sa.Action = StoreActionKindUpdate
+ sa.Target = &StoreAction_Task{Task: v.Task}
+ case EventDeleteTask:
+ sa.Action = StoreActionKindRemove
+ sa.Target = &StoreAction_Task{Task: v.Task}
+ case EventCreateNetwork:
+ sa.Action = StoreActionKindCreate
+ sa.Target = &StoreAction_Network{Network: v.Network}
+ case EventUpdateNetwork:
+ sa.Action = StoreActionKindUpdate
+ sa.Target = &StoreAction_Network{Network: v.Network}
+ case EventDeleteNetwork:
+ sa.Action = StoreActionKindRemove
+ sa.Target = &StoreAction_Network{Network: v.Network}
+ case EventCreateCluster:
+ sa.Action = StoreActionKindCreate
+ sa.Target = &StoreAction_Cluster{Cluster: v.Cluster}
+ case EventUpdateCluster:
+ sa.Action = StoreActionKindUpdate
+ sa.Target = &StoreAction_Cluster{Cluster: v.Cluster}
+ case EventDeleteCluster:
+ sa.Action = StoreActionKindRemove
+ sa.Target = &StoreAction_Cluster{Cluster: v.Cluster}
+ case EventCreateSecret:
+ sa.Action = StoreActionKindCreate
+ sa.Target = &StoreAction_Secret{Secret: v.Secret}
+ case EventUpdateSecret:
+ sa.Action = StoreActionKindUpdate
+ sa.Target = &StoreAction_Secret{Secret: v.Secret}
+ case EventDeleteSecret:
+ sa.Action = StoreActionKindRemove
+ sa.Target = &StoreAction_Secret{Secret: v.Secret}
+ case EventCreateConfig:
+ sa.Action = StoreActionKindCreate
+ sa.Target = &StoreAction_Config{Config: v.Config}
+ case EventUpdateConfig:
+ sa.Action = StoreActionKindUpdate
+ sa.Target = &StoreAction_Config{Config: v.Config}
+ case EventDeleteConfig:
+ sa.Action = StoreActionKindRemove
+ sa.Target = &StoreAction_Config{Config: v.Config}
+ case EventCreateResource:
+ sa.Action = StoreActionKindCreate
+ sa.Target = &StoreAction_Resource{Resource: v.Resource}
+ case EventUpdateResource:
+ sa.Action = StoreActionKindUpdate
+ sa.Target = &StoreAction_Resource{Resource: v.Resource}
+ case EventDeleteResource:
+ sa.Action = StoreActionKindRemove
+ sa.Target = &StoreAction_Resource{Resource: v.Resource}
+ case EventCreateExtension:
+ sa.Action = StoreActionKindCreate
+ sa.Target = &StoreAction_Extension{Extension: v.Extension}
+ case EventUpdateExtension:
+ sa.Action = StoreActionKindUpdate
+ sa.Target = &StoreAction_Extension{Extension: v.Extension}
+ case EventDeleteExtension:
+ sa.Action = StoreActionKindRemove
+ sa.Target = &StoreAction_Extension{Extension: v.Extension}
+ default:
+ return StoreAction{}, errUnknownStoreAction
+ }
+ return sa, nil
+}
+
+func EventFromStoreAction(sa StoreAction, oldObject StoreObject) (Event, error) {
+ switch v := sa.Target.(type) {
+ case *StoreAction_Node:
+ switch sa.Action {
+ case StoreActionKindCreate:
+ return EventCreateNode{Node: v.Node}, nil
+ case StoreActionKindUpdate:
+ if oldObject != nil {
+ return EventUpdateNode{Node: v.Node, OldNode: oldObject.(*Node)}, nil
+ } else {
+ return EventUpdateNode{Node: v.Node}, nil
+ }
+ case StoreActionKindRemove:
+ return EventDeleteNode{Node: v.Node}, nil
+ }
+ case *StoreAction_Service:
+ switch sa.Action {
+ case StoreActionKindCreate:
+ return EventCreateService{Service: v.Service}, nil
+ case StoreActionKindUpdate:
+ if oldObject != nil {
+ return EventUpdateService{Service: v.Service, OldService: oldObject.(*Service)}, nil
+ } else {
+ return EventUpdateService{Service: v.Service}, nil
+ }
+ case StoreActionKindRemove:
+ return EventDeleteService{Service: v.Service}, nil
+ }
+ case *StoreAction_Task:
+ switch sa.Action {
+ case StoreActionKindCreate:
+ return EventCreateTask{Task: v.Task}, nil
+ case StoreActionKindUpdate:
+ if oldObject != nil {
+ return EventUpdateTask{Task: v.Task, OldTask: oldObject.(*Task)}, nil
+ } else {
+ return EventUpdateTask{Task: v.Task}, nil
+ }
+ case StoreActionKindRemove:
+ return EventDeleteTask{Task: v.Task}, nil
+ }
+ case *StoreAction_Network:
+ switch sa.Action {
+ case StoreActionKindCreate:
+ return EventCreateNetwork{Network: v.Network}, nil
+ case StoreActionKindUpdate:
+ if oldObject != nil {
+ return EventUpdateNetwork{Network: v.Network, OldNetwork: oldObject.(*Network)}, nil
+ } else {
+ return EventUpdateNetwork{Network: v.Network}, nil
+ }
+ case StoreActionKindRemove:
+ return EventDeleteNetwork{Network: v.Network}, nil
+ }
+ case *StoreAction_Cluster:
+ switch sa.Action {
+ case StoreActionKindCreate:
+ return EventCreateCluster{Cluster: v.Cluster}, nil
+ case StoreActionKindUpdate:
+ if oldObject != nil {
+ return EventUpdateCluster{Cluster: v.Cluster, OldCluster: oldObject.(*Cluster)}, nil
+ } else {
+ return EventUpdateCluster{Cluster: v.Cluster}, nil
+ }
+ case StoreActionKindRemove:
+ return EventDeleteCluster{Cluster: v.Cluster}, nil
+ }
+ case *StoreAction_Secret:
+ switch sa.Action {
+ case StoreActionKindCreate:
+ return EventCreateSecret{Secret: v.Secret}, nil
+ case StoreActionKindUpdate:
+ if oldObject != nil {
+ return EventUpdateSecret{Secret: v.Secret, OldSecret: oldObject.(*Secret)}, nil
+ } else {
+ return EventUpdateSecret{Secret: v.Secret}, nil
+ }
+ case StoreActionKindRemove:
+ return EventDeleteSecret{Secret: v.Secret}, nil
+ }
+ case *StoreAction_Config:
+ switch sa.Action {
+ case StoreActionKindCreate:
+ return EventCreateConfig{Config: v.Config}, nil
+ case StoreActionKindUpdate:
+ if oldObject != nil {
+ return EventUpdateConfig{Config: v.Config, OldConfig: oldObject.(*Config)}, nil
+ } else {
+ return EventUpdateConfig{Config: v.Config}, nil
+ }
+ case StoreActionKindRemove:
+ return EventDeleteConfig{Config: v.Config}, nil
+ }
+ case *StoreAction_Resource:
+ switch sa.Action {
+ case StoreActionKindCreate:
+ return EventCreateResource{Resource: v.Resource}, nil
+ case StoreActionKindUpdate:
+ if oldObject != nil {
+ return EventUpdateResource{Resource: v.Resource, OldResource: oldObject.(*Resource)}, nil
+ } else {
+ return EventUpdateResource{Resource: v.Resource}, nil
+ }
+ case StoreActionKindRemove:
+ return EventDeleteResource{Resource: v.Resource}, nil
+ }
+ case *StoreAction_Extension:
+ switch sa.Action {
+ case StoreActionKindCreate:
+ return EventCreateExtension{Extension: v.Extension}, nil
+ case StoreActionKindUpdate:
+ if oldObject != nil {
+ return EventUpdateExtension{Extension: v.Extension, OldExtension: oldObject.(*Extension)}, nil
+ } else {
+ return EventUpdateExtension{Extension: v.Extension}, nil
+ }
+ case StoreActionKindRemove:
+ return EventDeleteExtension{Extension: v.Extension}, nil
+ }
+ }
+ return nil, errUnknownStoreAction
+}
+
+func WatchMessageEvent(c Event) *WatchMessage_Event {
+ switch v := c.(type) {
+ case EventCreateNode:
+ return &WatchMessage_Event{Action: WatchActionKindCreate, Object: &Object{Object: &Object_Node{Node: v.Node}}}
+ case EventUpdateNode:
+ if v.OldNode != nil {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Node{Node: v.Node}}, OldObject: &Object{Object: &Object_Node{Node: v.OldNode}}}
+ } else {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Node{Node: v.Node}}}
+ }
+ case EventDeleteNode:
+ return &WatchMessage_Event{Action: WatchActionKindRemove, Object: &Object{Object: &Object_Node{Node: v.Node}}}
+ case EventCreateService:
+ return &WatchMessage_Event{Action: WatchActionKindCreate, Object: &Object{Object: &Object_Service{Service: v.Service}}}
+ case EventUpdateService:
+ if v.OldService != nil {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Service{Service: v.Service}}, OldObject: &Object{Object: &Object_Service{Service: v.OldService}}}
+ } else {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Service{Service: v.Service}}}
+ }
+ case EventDeleteService:
+ return &WatchMessage_Event{Action: WatchActionKindRemove, Object: &Object{Object: &Object_Service{Service: v.Service}}}
+ case EventCreateTask:
+ return &WatchMessage_Event{Action: WatchActionKindCreate, Object: &Object{Object: &Object_Task{Task: v.Task}}}
+ case EventUpdateTask:
+ if v.OldTask != nil {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Task{Task: v.Task}}, OldObject: &Object{Object: &Object_Task{Task: v.OldTask}}}
+ } else {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Task{Task: v.Task}}}
+ }
+ case EventDeleteTask:
+ return &WatchMessage_Event{Action: WatchActionKindRemove, Object: &Object{Object: &Object_Task{Task: v.Task}}}
+ case EventCreateNetwork:
+ return &WatchMessage_Event{Action: WatchActionKindCreate, Object: &Object{Object: &Object_Network{Network: v.Network}}}
+ case EventUpdateNetwork:
+ if v.OldNetwork != nil {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Network{Network: v.Network}}, OldObject: &Object{Object: &Object_Network{Network: v.OldNetwork}}}
+ } else {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Network{Network: v.Network}}}
+ }
+ case EventDeleteNetwork:
+ return &WatchMessage_Event{Action: WatchActionKindRemove, Object: &Object{Object: &Object_Network{Network: v.Network}}}
+ case EventCreateCluster:
+ return &WatchMessage_Event{Action: WatchActionKindCreate, Object: &Object{Object: &Object_Cluster{Cluster: v.Cluster}}}
+ case EventUpdateCluster:
+ if v.OldCluster != nil {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Cluster{Cluster: v.Cluster}}, OldObject: &Object{Object: &Object_Cluster{Cluster: v.OldCluster}}}
+ } else {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Cluster{Cluster: v.Cluster}}}
+ }
+ case EventDeleteCluster:
+ return &WatchMessage_Event{Action: WatchActionKindRemove, Object: &Object{Object: &Object_Cluster{Cluster: v.Cluster}}}
+ case EventCreateSecret:
+ return &WatchMessage_Event{Action: WatchActionKindCreate, Object: &Object{Object: &Object_Secret{Secret: v.Secret}}}
+ case EventUpdateSecret:
+ if v.OldSecret != nil {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Secret{Secret: v.Secret}}, OldObject: &Object{Object: &Object_Secret{Secret: v.OldSecret}}}
+ } else {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Secret{Secret: v.Secret}}}
+ }
+ case EventDeleteSecret:
+ return &WatchMessage_Event{Action: WatchActionKindRemove, Object: &Object{Object: &Object_Secret{Secret: v.Secret}}}
+ case EventCreateConfig:
+ return &WatchMessage_Event{Action: WatchActionKindCreate, Object: &Object{Object: &Object_Config{Config: v.Config}}}
+ case EventUpdateConfig:
+ if v.OldConfig != nil {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Config{Config: v.Config}}, OldObject: &Object{Object: &Object_Config{Config: v.OldConfig}}}
+ } else {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Config{Config: v.Config}}}
+ }
+ case EventDeleteConfig:
+ return &WatchMessage_Event{Action: WatchActionKindRemove, Object: &Object{Object: &Object_Config{Config: v.Config}}}
+ case EventCreateResource:
+ return &WatchMessage_Event{Action: WatchActionKindCreate, Object: &Object{Object: &Object_Resource{Resource: v.Resource}}}
+ case EventUpdateResource:
+ if v.OldResource != nil {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Resource{Resource: v.Resource}}, OldObject: &Object{Object: &Object_Resource{Resource: v.OldResource}}}
+ } else {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Resource{Resource: v.Resource}}}
+ }
+ case EventDeleteResource:
+ return &WatchMessage_Event{Action: WatchActionKindRemove, Object: &Object{Object: &Object_Resource{Resource: v.Resource}}}
+ case EventCreateExtension:
+ return &WatchMessage_Event{Action: WatchActionKindCreate, Object: &Object{Object: &Object_Extension{Extension: v.Extension}}}
+ case EventUpdateExtension:
+ if v.OldExtension != nil {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Extension{Extension: v.Extension}}, OldObject: &Object{Object: &Object_Extension{Extension: v.OldExtension}}}
+ } else {
+ return &WatchMessage_Event{Action: WatchActionKindUpdate, Object: &Object{Object: &Object_Extension{Extension: v.Extension}}}
+ }
+ case EventDeleteExtension:
+ return &WatchMessage_Event{Action: WatchActionKindRemove, Object: &Object{Object: &Object_Extension{Extension: v.Extension}}}
+ }
+ return nil
+}
+
+func ConvertWatchArgs(entries []*WatchRequest_WatchEntry) ([]Event, error) {
+ var events []Event
+ for _, entry := range entries {
+ var newEvents []Event
+ var err error
+ switch entry.Kind {
+ case "":
+ return nil, errNoKindSpecified
+ case "node":
+ newEvents, err = ConvertNodeWatch(entry.Action, entry.Filters)
+ case "service":
+ newEvents, err = ConvertServiceWatch(entry.Action, entry.Filters)
+ case "task":
+ newEvents, err = ConvertTaskWatch(entry.Action, entry.Filters)
+ case "network":
+ newEvents, err = ConvertNetworkWatch(entry.Action, entry.Filters)
+ case "cluster":
+ newEvents, err = ConvertClusterWatch(entry.Action, entry.Filters)
+ case "secret":
+ newEvents, err = ConvertSecretWatch(entry.Action, entry.Filters)
+ case "config":
+ newEvents, err = ConvertConfigWatch(entry.Action, entry.Filters)
+ default:
+ newEvents, err = ConvertResourceWatch(entry.Action, entry.Filters, entry.Kind)
+ case "extension":
+ newEvents, err = ConvertExtensionWatch(entry.Action, entry.Filters)
+ }
+ if err != nil {
+ return nil, err
+ }
+ events = append(events, newEvents...)
+ }
+ return events, nil
+}
+
+func (this *Meta) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Meta{`,
+ `Version:` + strings.Replace(strings.Replace(this.Version.String(), "Version", "Version", 1), `&`, ``, 1) + `,`,
+ `CreatedAt:` + strings.Replace(fmt.Sprintf("%v", this.CreatedAt), "Timestamp", "google_protobuf.Timestamp", 1) + `,`,
+ `UpdatedAt:` + strings.Replace(fmt.Sprintf("%v", this.UpdatedAt), "Timestamp", "google_protobuf.Timestamp", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Node) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Node{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Meta:` + strings.Replace(strings.Replace(this.Meta.String(), "Meta", "Meta", 1), `&`, ``, 1) + `,`,
+ `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "NodeSpec", "NodeSpec", 1), `&`, ``, 1) + `,`,
+ `Description:` + strings.Replace(fmt.Sprintf("%v", this.Description), "NodeDescription", "NodeDescription", 1) + `,`,
+ `Status:` + strings.Replace(strings.Replace(this.Status.String(), "NodeStatus", "NodeStatus", 1), `&`, ``, 1) + `,`,
+ `ManagerStatus:` + strings.Replace(fmt.Sprintf("%v", this.ManagerStatus), "ManagerStatus", "ManagerStatus", 1) + `,`,
+ `Attachment:` + strings.Replace(fmt.Sprintf("%v", this.Attachment), "NetworkAttachment", "NetworkAttachment", 1) + `,`,
+ `Certificate:` + strings.Replace(strings.Replace(this.Certificate.String(), "Certificate", "Certificate", 1), `&`, ``, 1) + `,`,
+ `Role:` + fmt.Sprintf("%v", this.Role) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Service) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Service{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Meta:` + strings.Replace(strings.Replace(this.Meta.String(), "Meta", "Meta", 1), `&`, ``, 1) + `,`,
+ `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ServiceSpec", "ServiceSpec", 1), `&`, ``, 1) + `,`,
+ `Endpoint:` + strings.Replace(fmt.Sprintf("%v", this.Endpoint), "Endpoint", "Endpoint", 1) + `,`,
+ `UpdateStatus:` + strings.Replace(fmt.Sprintf("%v", this.UpdateStatus), "UpdateStatus", "UpdateStatus", 1) + `,`,
+ `PreviousSpec:` + strings.Replace(fmt.Sprintf("%v", this.PreviousSpec), "ServiceSpec", "ServiceSpec", 1) + `,`,
+ `SpecVersion:` + strings.Replace(fmt.Sprintf("%v", this.SpecVersion), "Version", "Version", 1) + `,`,
+ `PreviousSpecVersion:` + strings.Replace(fmt.Sprintf("%v", this.PreviousSpecVersion), "Version", "Version", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Endpoint) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Endpoint{`,
+ `Spec:` + strings.Replace(fmt.Sprintf("%v", this.Spec), "EndpointSpec", "EndpointSpec", 1) + `,`,
+ `Ports:` + strings.Replace(fmt.Sprintf("%v", this.Ports), "PortConfig", "PortConfig", 1) + `,`,
+ `VirtualIPs:` + strings.Replace(fmt.Sprintf("%v", this.VirtualIPs), "Endpoint_VirtualIP", "Endpoint_VirtualIP", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Endpoint_VirtualIP) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Endpoint_VirtualIP{`,
+ `NetworkID:` + fmt.Sprintf("%v", this.NetworkID) + `,`,
+ `Addr:` + fmt.Sprintf("%v", this.Addr) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Task) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Task{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Meta:` + strings.Replace(strings.Replace(this.Meta.String(), "Meta", "Meta", 1), `&`, ``, 1) + `,`,
+ `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "TaskSpec", "TaskSpec", 1), `&`, ``, 1) + `,`,
+ `ServiceID:` + fmt.Sprintf("%v", this.ServiceID) + `,`,
+ `Slot:` + fmt.Sprintf("%v", this.Slot) + `,`,
+ `NodeID:` + fmt.Sprintf("%v", this.NodeID) + `,`,
+ `Annotations:` + strings.Replace(strings.Replace(this.Annotations.String(), "Annotations", "Annotations", 1), `&`, ``, 1) + `,`,
+ `ServiceAnnotations:` + strings.Replace(strings.Replace(this.ServiceAnnotations.String(), "Annotations", "Annotations", 1), `&`, ``, 1) + `,`,
+ `Status:` + strings.Replace(strings.Replace(this.Status.String(), "TaskStatus", "TaskStatus", 1), `&`, ``, 1) + `,`,
+ `DesiredState:` + fmt.Sprintf("%v", this.DesiredState) + `,`,
+ `Networks:` + strings.Replace(fmt.Sprintf("%v", this.Networks), "NetworkAttachment", "NetworkAttachment", 1) + `,`,
+ `Endpoint:` + strings.Replace(fmt.Sprintf("%v", this.Endpoint), "Endpoint", "Endpoint", 1) + `,`,
+ `LogDriver:` + strings.Replace(fmt.Sprintf("%v", this.LogDriver), "Driver", "Driver", 1) + `,`,
+ `SpecVersion:` + strings.Replace(fmt.Sprintf("%v", this.SpecVersion), "Version", "Version", 1) + `,`,
+ `AssignedGenericResources:` + strings.Replace(fmt.Sprintf("%v", this.AssignedGenericResources), "GenericResource", "GenericResource", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NetworkAttachment) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForDriverAttachmentOpts := make([]string, 0, len(this.DriverAttachmentOpts))
+ for k, _ := range this.DriverAttachmentOpts {
+ keysForDriverAttachmentOpts = append(keysForDriverAttachmentOpts, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForDriverAttachmentOpts)
+ mapStringForDriverAttachmentOpts := "map[string]string{"
+ for _, k := range keysForDriverAttachmentOpts {
+ mapStringForDriverAttachmentOpts += fmt.Sprintf("%v: %v,", k, this.DriverAttachmentOpts[k])
+ }
+ mapStringForDriverAttachmentOpts += "}"
+ s := strings.Join([]string{`&NetworkAttachment{`,
+ `Network:` + strings.Replace(fmt.Sprintf("%v", this.Network), "Network", "Network", 1) + `,`,
+ `Addresses:` + fmt.Sprintf("%v", this.Addresses) + `,`,
+ `Aliases:` + fmt.Sprintf("%v", this.Aliases) + `,`,
+ `DriverAttachmentOpts:` + mapStringForDriverAttachmentOpts + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Network) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Network{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Meta:` + strings.Replace(strings.Replace(this.Meta.String(), "Meta", "Meta", 1), `&`, ``, 1) + `,`,
+ `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "NetworkSpec", "NetworkSpec", 1), `&`, ``, 1) + `,`,
+ `DriverState:` + strings.Replace(fmt.Sprintf("%v", this.DriverState), "Driver", "Driver", 1) + `,`,
+ `IPAM:` + strings.Replace(fmt.Sprintf("%v", this.IPAM), "IPAMOptions", "IPAMOptions", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Cluster) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForBlacklistedCertificates := make([]string, 0, len(this.BlacklistedCertificates))
+ for k, _ := range this.BlacklistedCertificates {
+ keysForBlacklistedCertificates = append(keysForBlacklistedCertificates, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForBlacklistedCertificates)
+ mapStringForBlacklistedCertificates := "map[string]*BlacklistedCertificate{"
+ for _, k := range keysForBlacklistedCertificates {
+ mapStringForBlacklistedCertificates += fmt.Sprintf("%v: %v,", k, this.BlacklistedCertificates[k])
+ }
+ mapStringForBlacklistedCertificates += "}"
+ s := strings.Join([]string{`&Cluster{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Meta:` + strings.Replace(strings.Replace(this.Meta.String(), "Meta", "Meta", 1), `&`, ``, 1) + `,`,
+ `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ClusterSpec", "ClusterSpec", 1), `&`, ``, 1) + `,`,
+ `RootCA:` + strings.Replace(strings.Replace(this.RootCA.String(), "RootCA", "RootCA", 1), `&`, ``, 1) + `,`,
+ `NetworkBootstrapKeys:` + strings.Replace(fmt.Sprintf("%v", this.NetworkBootstrapKeys), "EncryptionKey", "EncryptionKey", 1) + `,`,
+ `EncryptionKeyLamportClock:` + fmt.Sprintf("%v", this.EncryptionKeyLamportClock) + `,`,
+ `BlacklistedCertificates:` + mapStringForBlacklistedCertificates + `,`,
+ `UnlockKeys:` + strings.Replace(fmt.Sprintf("%v", this.UnlockKeys), "EncryptionKey", "EncryptionKey", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Secret) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Secret{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Meta:` + strings.Replace(strings.Replace(this.Meta.String(), "Meta", "Meta", 1), `&`, ``, 1) + `,`,
+ `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "SecretSpec", "SecretSpec", 1), `&`, ``, 1) + `,`,
+ `Internal:` + fmt.Sprintf("%v", this.Internal) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Config) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Config{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Meta:` + strings.Replace(strings.Replace(this.Meta.String(), "Meta", "Meta", 1), `&`, ``, 1) + `,`,
+ `Spec:` + strings.Replace(strings.Replace(this.Spec.String(), "ConfigSpec", "ConfigSpec", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Resource) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Resource{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Meta:` + strings.Replace(strings.Replace(this.Meta.String(), "Meta", "Meta", 1), `&`, ``, 1) + `,`,
+ `Annotations:` + strings.Replace(strings.Replace(this.Annotations.String(), "Annotations", "Annotations", 1), `&`, ``, 1) + `,`,
+ `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`,
+ `Payload:` + strings.Replace(fmt.Sprintf("%v", this.Payload), "Any", "google_protobuf3.Any", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Extension) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Extension{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Meta:` + strings.Replace(strings.Replace(this.Meta.String(), "Meta", "Meta", 1), `&`, ``, 1) + `,`,
+ `Annotations:` + strings.Replace(strings.Replace(this.Annotations.String(), "Annotations", "Annotations", 1), `&`, ``, 1) + `,`,
+ `Description:` + fmt.Sprintf("%v", this.Description) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringObjects(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *Meta) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Meta: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Meta: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Version.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CreatedAt", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.CreatedAt == nil {
+ m.CreatedAt = &google_protobuf.Timestamp{}
+ }
+ if err := m.CreatedAt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field UpdatedAt", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.UpdatedAt == nil {
+ m.UpdatedAt = &google_protobuf.Timestamp{}
+ }
+ if err := m.UpdatedAt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Node) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Node: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Node: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Meta", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Meta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Description == nil {
+ m.Description = &NodeDescription{}
+ }
+ if err := m.Description.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ManagerStatus", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.ManagerStatus == nil {
+ m.ManagerStatus = &ManagerStatus{}
+ }
+ if err := m.ManagerStatus.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Attachment", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Attachment == nil {
+ m.Attachment = &NetworkAttachment{}
+ }
+ if err := m.Attachment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Certificate", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Certificate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 9:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Role", wireType)
+ }
+ m.Role = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Role |= (NodeRole(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Service) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Service: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Service: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Meta", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Meta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Endpoint", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Endpoint == nil {
+ m.Endpoint = &Endpoint{}
+ }
+ if err := m.Endpoint.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field UpdateStatus", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.UpdateStatus == nil {
+ m.UpdateStatus = &UpdateStatus{}
+ }
+ if err := m.UpdateStatus.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PreviousSpec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.PreviousSpec == nil {
+ m.PreviousSpec = &ServiceSpec{}
+ }
+ if err := m.PreviousSpec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 10:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SpecVersion", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.SpecVersion == nil {
+ m.SpecVersion = &Version{}
+ }
+ if err := m.SpecVersion.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 11:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PreviousSpecVersion", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.PreviousSpecVersion == nil {
+ m.PreviousSpecVersion = &Version{}
+ }
+ if err := m.PreviousSpecVersion.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Endpoint) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Endpoint: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Endpoint: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Spec == nil {
+ m.Spec = &EndpointSpec{}
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Ports", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Ports = append(m.Ports, &PortConfig{})
+ if err := m.Ports[len(m.Ports)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field VirtualIPs", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.VirtualIPs = append(m.VirtualIPs, &Endpoint_VirtualIP{})
+ if err := m.VirtualIPs[len(m.VirtualIPs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Endpoint_VirtualIP) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: VirtualIP: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: VirtualIP: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NetworkID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NetworkID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Addr", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Addr = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Task) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Task: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Task: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Meta", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Meta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ServiceID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Slot", wireType)
+ }
+ m.Slot = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Slot |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Annotations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Annotations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceAnnotations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.ServiceAnnotations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 10:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field DesiredState", wireType)
+ }
+ m.DesiredState = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.DesiredState |= (TaskState(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 11:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Networks", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Networks = append(m.Networks, &NetworkAttachment{})
+ if err := m.Networks[len(m.Networks)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 12:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Endpoint", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Endpoint == nil {
+ m.Endpoint = &Endpoint{}
+ }
+ if err := m.Endpoint.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 13:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LogDriver", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.LogDriver == nil {
+ m.LogDriver = &Driver{}
+ }
+ if err := m.LogDriver.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 14:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SpecVersion", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.SpecVersion == nil {
+ m.SpecVersion = &Version{}
+ }
+ if err := m.SpecVersion.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 15:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field AssignedGenericResources", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.AssignedGenericResources = append(m.AssignedGenericResources, &GenericResource{})
+ if err := m.AssignedGenericResources[len(m.AssignedGenericResources)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NetworkAttachment) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NetworkAttachment: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NetworkAttachment: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Network", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Network == nil {
+ m.Network = &Network{}
+ }
+ if err := m.Network.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Addresses", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Addresses = append(m.Addresses, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Aliases", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Aliases = append(m.Aliases, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field DriverAttachmentOpts", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.DriverAttachmentOpts == nil {
+ m.DriverAttachmentOpts = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.DriverAttachmentOpts[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.DriverAttachmentOpts[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Network) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Network: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Network: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Meta", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Meta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field DriverState", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.DriverState == nil {
+ m.DriverState = &Driver{}
+ }
+ if err := m.DriverState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IPAM", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.IPAM == nil {
+ m.IPAM = &IPAMOptions{}
+ }
+ if err := m.IPAM.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Cluster) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Cluster: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Cluster: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Meta", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Meta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RootCA", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.RootCA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NetworkBootstrapKeys", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NetworkBootstrapKeys = append(m.NetworkBootstrapKeys, &EncryptionKey{})
+ if err := m.NetworkBootstrapKeys[len(m.NetworkBootstrapKeys)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field EncryptionKeyLamportClock", wireType)
+ }
+ m.EncryptionKeyLamportClock = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.EncryptionKeyLamportClock |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field BlacklistedCertificates", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.BlacklistedCertificates == nil {
+ m.BlacklistedCertificates = make(map[string]*BlacklistedCertificate)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var mapmsglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ mapmsglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if mapmsglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postmsgIndex := iNdEx + mapmsglen
+ if mapmsglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if postmsgIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := &BlacklistedCertificate{}
+ if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil {
+ return err
+ }
+ iNdEx = postmsgIndex
+ m.BlacklistedCertificates[mapkey] = mapvalue
+ } else {
+ var mapvalue *BlacklistedCertificate
+ m.BlacklistedCertificates[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field UnlockKeys", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.UnlockKeys = append(m.UnlockKeys, &EncryptionKey{})
+ if err := m.UnlockKeys[len(m.UnlockKeys)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Secret) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Secret: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Secret: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Meta", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Meta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Internal", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Internal = bool(v != 0)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Config) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Config: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Config: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Meta", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Meta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Spec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Resource) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Resource: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Resource: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Meta", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Meta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Annotations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Annotations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Kind = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Payload == nil {
+ m.Payload = &google_protobuf3.Any{}
+ }
+ if err := m.Payload.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Extension) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Extension: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Extension: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Meta", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Meta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Annotations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Annotations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthObjects
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Description = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipObjects(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthObjects
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipObjects(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthObjects
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowObjects
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipObjects(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthObjects = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowObjects = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("objects.proto", fileDescriptorObjects) }
+
+var fileDescriptorObjects = []byte{
+ // 1491 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x58, 0xcf, 0x6f, 0x1b, 0x4f,
+ 0x15, 0xef, 0xda, 0x1b, 0xff, 0x78, 0x4e, 0x4c, 0x98, 0x86, 0xb0, 0x35, 0xc1, 0x0e, 0xae, 0x40,
+ 0x15, 0xaa, 0x9c, 0x12, 0x0a, 0x4a, 0x03, 0xa5, 0xb5, 0x93, 0xa8, 0xb5, 0x4a, 0x69, 0x34, 0x2d,
+ 0x2d, 0xb7, 0x65, 0xb2, 0x3b, 0x75, 0x17, 0xaf, 0x77, 0x56, 0x3b, 0x63, 0x17, 0xdf, 0x38, 0x87,
+ 0x3f, 0x20, 0x37, 0x0e, 0xfd, 0x17, 0xe0, 0xc2, 0x85, 0x03, 0xa7, 0x1e, 0x39, 0x21, 0x4e, 0x11,
+ 0xf5, 0x7f, 0x81, 0xc4, 0xe1, 0xab, 0x99, 0x9d, 0xb5, 0x37, 0xf1, 0x3a, 0x49, 0xbf, 0xaa, 0xa2,
+ 0xef, 0x29, 0x33, 0x3b, 0x9f, 0xcf, 0x9b, 0xf7, 0xde, 0xbc, 0x5f, 0x31, 0xac, 0xb0, 0xa3, 0x3f,
+ 0x50, 0x47, 0xf0, 0x56, 0x18, 0x31, 0xc1, 0x10, 0x72, 0x99, 0xd3, 0xa7, 0x51, 0x8b, 0xbf, 0x27,
+ 0xd1, 0xa0, 0xef, 0x89, 0xd6, 0xe8, 0x27, 0xb5, 0x8a, 0x18, 0x87, 0x54, 0x03, 0x6a, 0x15, 0x1e,
+ 0x52, 0x27, 0xd9, 0x34, 0x7a, 0x8c, 0xf5, 0x7c, 0xba, 0xa5, 0x76, 0x47, 0xc3, 0xb7, 0x5b, 0xc2,
+ 0x1b, 0x50, 0x2e, 0xc8, 0x20, 0xd4, 0x80, 0xb5, 0x1e, 0xeb, 0x31, 0xb5, 0xdc, 0x92, 0x2b, 0xfd,
+ 0xf5, 0xd6, 0x79, 0x1a, 0x09, 0xc6, 0xfa, 0xe8, 0x66, 0xe8, 0x0f, 0x7b, 0x5e, 0xb0, 0x15, 0xff,
+ 0x89, 0x3f, 0x36, 0xff, 0x6e, 0x80, 0xf9, 0x9c, 0x0a, 0x82, 0x7e, 0x01, 0xc5, 0x11, 0x8d, 0xb8,
+ 0xc7, 0x02, 0xcb, 0xd8, 0x34, 0xee, 0x54, 0xb6, 0xbf, 0xd7, 0x9a, 0xd7, 0xb7, 0xf5, 0x3a, 0x86,
+ 0x74, 0xcc, 0x8f, 0xa7, 0x8d, 0x1b, 0x38, 0x61, 0xa0, 0x07, 0x00, 0x4e, 0x44, 0x89, 0xa0, 0xae,
+ 0x4d, 0x84, 0x95, 0x53, 0xfc, 0x5a, 0x2b, 0x56, 0xa5, 0x95, 0xa8, 0xd2, 0x7a, 0x95, 0x58, 0x80,
+ 0xcb, 0x1a, 0xdd, 0x16, 0x92, 0x3a, 0x0c, 0xdd, 0x84, 0x9a, 0xbf, 0x9c, 0xaa, 0xd1, 0x6d, 0xd1,
+ 0xfc, 0xab, 0x09, 0xe6, 0x6f, 0x98, 0x4b, 0xd1, 0x3a, 0xe4, 0x3c, 0x57, 0xa9, 0x5d, 0xee, 0x14,
+ 0x26, 0xa7, 0x8d, 0x5c, 0x77, 0x1f, 0xe7, 0x3c, 0x17, 0x6d, 0x83, 0x39, 0xa0, 0x82, 0x68, 0x85,
+ 0xac, 0x2c, 0x83, 0xa4, 0xed, 0xda, 0x1a, 0x85, 0x45, 0x3f, 0x07, 0x53, 0x3e, 0x83, 0xd6, 0x64,
+ 0x23, 0x8b, 0x23, 0xef, 0x7c, 0x19, 0x52, 0x27, 0xe1, 0x49, 0x3c, 0x3a, 0x80, 0x8a, 0x4b, 0xb9,
+ 0x13, 0x79, 0xa1, 0x90, 0x3e, 0x34, 0x15, 0xfd, 0xf6, 0x22, 0xfa, 0xfe, 0x0c, 0x8a, 0xd3, 0x3c,
+ 0xf4, 0x4b, 0x28, 0x70, 0x41, 0xc4, 0x90, 0x5b, 0x4b, 0x4a, 0x42, 0x7d, 0xa1, 0x02, 0x0a, 0xa5,
+ 0x55, 0xd0, 0x1c, 0xf4, 0x14, 0xaa, 0x03, 0x12, 0x90, 0x1e, 0x8d, 0x6c, 0x2d, 0xa5, 0xa0, 0xa4,
+ 0xfc, 0x20, 0xd3, 0xf4, 0x18, 0x19, 0x0b, 0xc2, 0x2b, 0x83, 0xf4, 0x16, 0x1d, 0x00, 0x10, 0x21,
+ 0x88, 0xf3, 0x6e, 0x40, 0x03, 0x61, 0x15, 0x95, 0x94, 0x1f, 0x66, 0xea, 0x42, 0xc5, 0x7b, 0x16,
+ 0xf5, 0xdb, 0x53, 0x30, 0x4e, 0x11, 0xd1, 0x13, 0xa8, 0x38, 0x34, 0x12, 0xde, 0x5b, 0xcf, 0x21,
+ 0x82, 0x5a, 0x25, 0x25, 0xa7, 0x91, 0x25, 0x67, 0x6f, 0x06, 0xd3, 0x46, 0xa5, 0x99, 0xe8, 0x1e,
+ 0x98, 0x11, 0xf3, 0xa9, 0x55, 0xde, 0x34, 0xee, 0x54, 0x17, 0x3f, 0x0b, 0x66, 0x3e, 0xc5, 0x0a,
+ 0xb9, 0xbb, 0x7e, 0x7c, 0xd2, 0x44, 0xb0, 0x5a, 0x32, 0x56, 0x0d, 0x15, 0x1a, 0xc6, 0x3d, 0xe3,
+ 0x77, 0xc6, 0xef, 0x8d, 0xe6, 0xff, 0xf3, 0x50, 0x7c, 0x49, 0xa3, 0x91, 0xe7, 0x7c, 0xd9, 0xc0,
+ 0x79, 0x70, 0x26, 0x70, 0x32, 0x6d, 0xd4, 0xd7, 0xce, 0xc5, 0xce, 0x0e, 0x94, 0x68, 0xe0, 0x86,
+ 0xcc, 0x0b, 0x84, 0x0e, 0x9c, 0x4c, 0x03, 0x0f, 0x34, 0x06, 0x4f, 0xd1, 0xe8, 0x00, 0x56, 0xe2,
+ 0x7c, 0xb0, 0xcf, 0x44, 0xcd, 0x66, 0x16, 0xfd, 0xb7, 0x0a, 0xa8, 0x9f, 0x7b, 0x79, 0x98, 0xda,
+ 0xa1, 0x7d, 0x58, 0x09, 0x23, 0x3a, 0xf2, 0xd8, 0x90, 0xdb, 0xca, 0x88, 0xc2, 0x95, 0x8c, 0xc0,
+ 0xcb, 0x09, 0x4b, 0xee, 0xd0, 0xaf, 0x60, 0x59, 0x92, 0xed, 0xa4, 0x8e, 0xc0, 0xa5, 0x75, 0x04,
+ 0xab, 0x92, 0xa7, 0x37, 0xe8, 0x05, 0x7c, 0xe7, 0x8c, 0x16, 0x53, 0x41, 0x95, 0xcb, 0x05, 0xdd,
+ 0x4c, 0x6b, 0xa2, 0x3f, 0xee, 0xa2, 0xe3, 0x93, 0x66, 0x15, 0x96, 0xd3, 0x21, 0xd0, 0xfc, 0x4b,
+ 0x0e, 0x4a, 0x89, 0x23, 0xd1, 0x7d, 0xfd, 0x66, 0xc6, 0x62, 0xaf, 0x25, 0x58, 0x65, 0x6f, 0xfc,
+ 0x5c, 0xf7, 0x61, 0x29, 0x64, 0x91, 0xe0, 0x56, 0x6e, 0x33, 0xbf, 0x28, 0x45, 0x0f, 0x59, 0x24,
+ 0xf6, 0x58, 0xf0, 0xd6, 0xeb, 0xe1, 0x18, 0x8c, 0xde, 0x40, 0x65, 0xe4, 0x45, 0x62, 0x48, 0x7c,
+ 0xdb, 0x0b, 0xb9, 0x95, 0x57, 0xdc, 0x1f, 0x5d, 0x74, 0x65, 0xeb, 0x75, 0x8c, 0xef, 0x1e, 0x76,
+ 0xaa, 0x93, 0xd3, 0x06, 0x4c, 0xb7, 0x1c, 0x83, 0x16, 0xd5, 0x0d, 0x79, 0xed, 0x39, 0x94, 0xa7,
+ 0x27, 0xe8, 0x2e, 0x40, 0x10, 0x67, 0xa4, 0x3d, 0x8d, 0xec, 0x95, 0xc9, 0x69, 0xa3, 0xac, 0xf3,
+ 0xb4, 0xbb, 0x8f, 0xcb, 0x1a, 0xd0, 0x75, 0x11, 0x02, 0x93, 0xb8, 0x6e, 0xa4, 0xe2, 0xbc, 0x8c,
+ 0xd5, 0xba, 0xf9, 0xe7, 0x22, 0x98, 0xaf, 0x08, 0xef, 0x5f, 0x77, 0x55, 0x95, 0x77, 0xce, 0x65,
+ 0xc6, 0x5d, 0x00, 0x1e, 0xc7, 0x9b, 0x34, 0xc7, 0x9c, 0x99, 0xa3, 0xa3, 0x50, 0x9a, 0xa3, 0x01,
+ 0xb1, 0x39, 0xdc, 0x67, 0x42, 0x25, 0x81, 0x89, 0xd5, 0x1a, 0xdd, 0x86, 0x62, 0xc0, 0x5c, 0x45,
+ 0x2f, 0x28, 0x3a, 0x4c, 0x4e, 0x1b, 0x05, 0x59, 0x2b, 0xba, 0xfb, 0xb8, 0x20, 0x8f, 0xba, 0xae,
+ 0x2c, 0x53, 0x24, 0x08, 0x98, 0x20, 0xb2, 0x06, 0x73, 0x5d, 0xee, 0x32, 0xa3, 0xbf, 0x3d, 0x83,
+ 0x25, 0x65, 0x2a, 0xc5, 0x44, 0xaf, 0xe1, 0x66, 0xa2, 0x6f, 0x5a, 0x60, 0xe9, 0x73, 0x04, 0x22,
+ 0x2d, 0x21, 0x75, 0x92, 0x6a, 0x0b, 0xe5, 0xc5, 0x6d, 0x41, 0x79, 0x30, 0xab, 0x2d, 0x74, 0x60,
+ 0xc5, 0xa5, 0xdc, 0x8b, 0xa8, 0xab, 0xca, 0x04, 0x55, 0x99, 0x59, 0xdd, 0xfe, 0xfe, 0x45, 0x42,
+ 0x28, 0x5e, 0xd6, 0x1c, 0xb5, 0x43, 0x6d, 0x28, 0xe9, 0xb8, 0xe1, 0x56, 0x45, 0xc5, 0xee, 0x15,
+ 0xdb, 0xc1, 0x94, 0x76, 0xa6, 0xcc, 0x2d, 0x7f, 0x56, 0x99, 0x7b, 0x00, 0xe0, 0xb3, 0x9e, 0xed,
+ 0x46, 0xde, 0x88, 0x46, 0xd6, 0x8a, 0x1e, 0x12, 0x32, 0xb8, 0xfb, 0x0a, 0x81, 0xcb, 0x3e, 0xeb,
+ 0xc5, 0xcb, 0xb9, 0xa2, 0x54, 0xfd, 0xcc, 0xa2, 0x44, 0xa0, 0x46, 0x38, 0xf7, 0x7a, 0x01, 0x75,
+ 0xed, 0x1e, 0x0d, 0x68, 0xe4, 0x39, 0x76, 0x44, 0x39, 0x1b, 0x46, 0x0e, 0xe5, 0xd6, 0xb7, 0x94,
+ 0x27, 0x32, 0xdb, 0xfc, 0x93, 0x18, 0x8c, 0x35, 0x16, 0x5b, 0x89, 0x98, 0x73, 0x07, 0x7c, 0xb7,
+ 0x76, 0x7c, 0xd2, 0x5c, 0x87, 0xb5, 0x74, 0x99, 0xda, 0x31, 0x1e, 0x1b, 0x4f, 0x8d, 0x43, 0xa3,
+ 0xf9, 0xcf, 0x1c, 0x7c, 0x7b, 0xce, 0xa7, 0xe8, 0x67, 0x50, 0xd4, 0x5e, 0xbd, 0x68, 0x58, 0xd3,
+ 0x3c, 0x9c, 0x60, 0xd1, 0x06, 0x94, 0x65, 0x8a, 0x53, 0xce, 0x69, 0x5c, 0xbc, 0xca, 0x78, 0xf6,
+ 0x01, 0x59, 0x50, 0x24, 0xbe, 0x47, 0xe4, 0x59, 0x5e, 0x9d, 0x25, 0x5b, 0x34, 0x84, 0xf5, 0xd8,
+ 0xf5, 0xf6, 0xac, 0xb5, 0xdb, 0x2c, 0x14, 0xdc, 0x32, 0x95, 0xfd, 0x8f, 0xae, 0x14, 0x09, 0xfa,
+ 0x71, 0x66, 0x1f, 0x5e, 0x84, 0x82, 0x1f, 0x04, 0x22, 0x1a, 0xe3, 0x35, 0x37, 0xe3, 0xa8, 0xf6,
+ 0x04, 0x6e, 0x2d, 0xa4, 0xa0, 0x55, 0xc8, 0xf7, 0xe9, 0x38, 0x2e, 0x4f, 0x58, 0x2e, 0xd1, 0x1a,
+ 0x2c, 0x8d, 0x88, 0x3f, 0xa4, 0xba, 0x9a, 0xc5, 0x9b, 0xdd, 0xdc, 0x8e, 0xd1, 0xfc, 0x90, 0x83,
+ 0xa2, 0x56, 0xe7, 0xba, 0x5b, 0xbe, 0xbe, 0x76, 0xae, 0xb0, 0x3d, 0x84, 0x65, 0xed, 0xd2, 0x38,
+ 0x23, 0xcd, 0x4b, 0x63, 0xba, 0x12, 0xe3, 0xe3, 0x6c, 0x7c, 0x08, 0xa6, 0x17, 0x92, 0x81, 0x6e,
+ 0xf7, 0x99, 0x37, 0x77, 0x0f, 0xdb, 0xcf, 0x5f, 0x84, 0x71, 0x61, 0x29, 0x4d, 0x4e, 0x1b, 0xa6,
+ 0xfc, 0x80, 0x15, 0x2d, 0xb3, 0x31, 0xfe, 0x6d, 0x09, 0x8a, 0x7b, 0xfe, 0x90, 0x0b, 0x1a, 0x5d,
+ 0xb7, 0x93, 0xf4, 0xb5, 0x73, 0x4e, 0xda, 0x83, 0x62, 0xc4, 0x98, 0xb0, 0x1d, 0x72, 0x91, 0x7f,
+ 0x30, 0x63, 0x62, 0xaf, 0xdd, 0xa9, 0x4a, 0xa2, 0xac, 0xed, 0xf1, 0x1e, 0x17, 0x24, 0x75, 0x8f,
+ 0xa0, 0x37, 0xb0, 0x9e, 0x74, 0xc4, 0x23, 0xc6, 0x04, 0x17, 0x11, 0x09, 0xed, 0x3e, 0x1d, 0xcb,
+ 0x59, 0x29, 0xbf, 0x68, 0x36, 0x3e, 0x08, 0x9c, 0x68, 0xac, 0x9c, 0xf7, 0x8c, 0x8e, 0xf1, 0x9a,
+ 0x16, 0xd0, 0x49, 0xf8, 0xcf, 0xe8, 0x98, 0xa3, 0x47, 0xb0, 0x41, 0xa7, 0x30, 0x29, 0xd1, 0xf6,
+ 0xc9, 0x40, 0xf6, 0x7a, 0xdb, 0xf1, 0x99, 0xd3, 0x57, 0xed, 0xc6, 0xc4, 0xb7, 0x68, 0x5a, 0xd4,
+ 0xaf, 0x63, 0xc4, 0x9e, 0x04, 0x20, 0x0e, 0xd6, 0x91, 0x4f, 0x9c, 0xbe, 0xef, 0x71, 0xf9, 0xef,
+ 0x4f, 0x6a, 0xdc, 0x95, 0x1d, 0x43, 0xea, 0xb6, 0x73, 0x81, 0xb7, 0x5a, 0x9d, 0x19, 0x37, 0x35,
+ 0x3c, 0xeb, 0x8c, 0xfa, 0xee, 0x51, 0xf6, 0x29, 0xea, 0x40, 0x65, 0x18, 0xc8, 0xeb, 0x63, 0x1f,
+ 0x94, 0xaf, 0xea, 0x03, 0x88, 0x59, 0xd2, 0xf2, 0xda, 0x08, 0x36, 0x2e, 0xba, 0x3c, 0x23, 0x37,
+ 0x1f, 0xa7, 0x73, 0xb3, 0xb2, 0xfd, 0xe3, 0xac, 0xfb, 0xb2, 0x45, 0xa6, 0xf2, 0x38, 0x33, 0x6c,
+ 0xff, 0x61, 0x40, 0xe1, 0x25, 0x75, 0x22, 0x2a, 0xbe, 0x68, 0xd4, 0xee, 0x9c, 0x89, 0xda, 0x7a,
+ 0xf6, 0x20, 0x2c, 0x6f, 0x9d, 0x0b, 0xda, 0x1a, 0x94, 0xbc, 0x40, 0xd0, 0x28, 0x20, 0xbe, 0x8a,
+ 0xda, 0x12, 0x9e, 0xee, 0x33, 0x0d, 0xf8, 0x60, 0x40, 0x21, 0x9e, 0x14, 0xaf, 0xdb, 0x80, 0xf8,
+ 0xd6, 0xf3, 0x06, 0x64, 0x2a, 0xf9, 0x3f, 0x03, 0x4a, 0x49, 0xc3, 0xfa, 0xa2, 0x6a, 0x9e, 0x9b,
+ 0xbc, 0xf2, 0x5f, 0x7b, 0xf2, 0x42, 0x60, 0xf6, 0xbd, 0x40, 0xcf, 0x88, 0x58, 0xad, 0x51, 0x0b,
+ 0x8a, 0x21, 0x19, 0xfb, 0x8c, 0xb8, 0xba, 0x50, 0xae, 0xcd, 0xfd, 0xb0, 0xd0, 0x0e, 0xc6, 0x38,
+ 0x01, 0xed, 0xae, 0x1d, 0x9f, 0x34, 0x57, 0xa1, 0x9a, 0xb6, 0xfc, 0x9d, 0xd1, 0xfc, 0xb7, 0x01,
+ 0xe5, 0x83, 0x3f, 0x0a, 0x1a, 0xa8, 0x79, 0xe0, 0x1b, 0x69, 0xfc, 0xe6, 0xfc, 0x8f, 0x0f, 0xe5,
+ 0x33, 0xbf, 0x2b, 0x64, 0x3d, 0x6a, 0xc7, 0xfa, 0xf8, 0xa9, 0x7e, 0xe3, 0x3f, 0x9f, 0xea, 0x37,
+ 0xfe, 0x34, 0xa9, 0x1b, 0x1f, 0x27, 0x75, 0xe3, 0x5f, 0x93, 0xba, 0xf1, 0xdf, 0x49, 0xdd, 0x38,
+ 0x2a, 0x28, 0xff, 0xfc, 0xf4, 0xab, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe4, 0x48, 0xcb, 0x39, 0xc2,
+ 0x12, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/objects.proto b/vendor/github.com/docker/swarmkit/api/objects.proto
new file mode 100644
index 0000000..311c1f2
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/objects.proto
@@ -0,0 +1,452 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "types.proto";
+import "specs.proto";
+import "google/protobuf/timestamp.proto";
+import "gogoproto/gogo.proto";
+import "google/protobuf/any.proto";
+import "plugin/plugin.proto";
+
+// This file contains definitions for all first-class objects in the cluster
+// API. Such types typically have a corresponding specification, with the
+// naming XXXSpec, but not all.
+
+// Meta contains metadata about objects. Every object contains a meta field.
+message Meta {
+ // Version tracks the current version of the object.
+ Version version = 1 [(gogoproto.nullable) = false];
+
+ // Object timestamps.
+ // Note: can't use stdtime because these fields are nullable.
+ google.protobuf.Timestamp created_at = 2;
+ google.protobuf.Timestamp updated_at = 3;
+}
+
+// Node provides the internal node state as seen by the cluster.
+message Node {
+ option (docker.protobuf.plugin.store_object) = {
+ watch_selectors: {
+ id: true
+ id_prefix: true
+ name: true
+ name_prefix: true
+ custom: true
+ custom_prefix: true
+ role: true
+ membership: true
+ }
+ };
+
+ // ID specifies the identity of the node.
+ string id = 1;
+
+ Meta meta = 2 [(gogoproto.nullable) = false];
+
+ // Spec defines the desired state of the node as specified by the user.
+ // The system will honor this and will *never* modify it.
+ NodeSpec spec = 3 [(gogoproto.nullable) = false];
+
+ // Description encapsulated the properties of the Node as reported by the
+ // agent.
+ NodeDescription description = 4;
+
+ // Status provides the current status of the node, as seen by the manager.
+ NodeStatus status = 5 [(gogoproto.nullable) = false];
+
+ // ManagerStatus provides the current status of the node's manager
+ // component, if the node is a manager.
+ ManagerStatus manager_status = 6;
+
+ // The node attachment to the ingress network.
+ NetworkAttachment attachment = 7;
+
+ // Certificate is the TLS certificate issued for the node, if any.
+ Certificate certificate = 8 [(gogoproto.nullable) = false];
+
+ // Role is the *observed* role for this node. It differs from the
+ // desired role set in Node.Spec.Role because the role here is only
+ // updated after the Raft member list has been reconciled with the
+ // desired role from the spec.
+ //
+ // This field represents the current reconciled state. If an action is
+ // to be performed, first verify the role in the cert. This field only
+ // shows the privilege level that the CA would currently grant when
+ // issuing or renewing the node's certificate.
+ NodeRole role = 9;
+}
+
+message Service {
+ option (docker.protobuf.plugin.store_object) = {
+ watch_selectors: {
+ id: true
+ id_prefix: true
+ name: true
+ name_prefix: true
+ custom: true
+ custom_prefix: true
+ }
+ };
+
+ string id = 1;
+
+ Meta meta = 2 [(gogoproto.nullable) = false];
+
+ ServiceSpec spec = 3 [(gogoproto.nullable) = false];
+
+ // SpecVersion versions Spec, to identify changes in the spec. Note that
+ // this is not directly comparable to the service's Version.
+ Version spec_version = 10;
+
+ // PreviousSpec is the previous service spec that was in place before
+ // "Spec".
+ ServiceSpec previous_spec = 6;
+
+ // PreviousSpecVersion versions PreviousSpec. Note that this is not
+ // directly comparable to the service's Version.
+ Version previous_spec_version = 11;
+
+ // Runtime state of service endpoint. This may be different
+ // from the spec version because the user may not have entered
+ // the optional fields like node_port or virtual_ip and it
+ // could be auto allocated by the system.
+ Endpoint endpoint = 4;
+
+ // UpdateStatus contains the status of an update, if one is in
+ // progress.
+ UpdateStatus update_status = 5;
+}
+
+// Endpoint specified all the network parameters required to
+// correctly discover and load balance a service
+message Endpoint {
+ EndpointSpec spec = 1;
+
+ // Runtime state of the exposed ports which may carry
+ // auto-allocated swarm ports in addition to the user
+ // configured information.
+ repeated PortConfig ports = 2;
+
+ // An endpoint attachment specifies the data that the process
+ // of attaching an endpoint to a network creates.
+
+ // VirtualIP specifies a set of networks this endpoint will be attached to
+ // and the IP addresses the target service will be made available under.
+ message VirtualIP {
+ // NetworkID for which this endpoint attachment was created.
+ string network_id = 1;
+
+ // A virtual IP is used to address this service in IP
+ // layer that the client can use to send requests to
+ // this service. A DNS A/AAAA query on the service
+ // name might return this IP to the client. This is
+ // strictly a logical IP and there may not be any
+ // interfaces assigned this IP address or any route
+ // created for this address. More than one to
+ // accommodate for both IPv4 and IPv6
+ string addr = 2;
+ }
+
+ // VirtualIPs specifies the IP addresses under which this endpoint will be
+ // made available.
+ repeated VirtualIP virtual_ips = 3 [(gogoproto.customname) = "VirtualIPs"];
+}
+
+// Task specifies the parameters for implementing a Spec. A task is effectively
+// immutable and idempotent. Once it is dispatched to a node, it will not be
+// dispatched to another node.
+message Task {
+ option (docker.protobuf.plugin.store_object) = {
+ watch_selectors: {
+ id: true
+ id_prefix: true
+ name: true
+ name_prefix: true
+ custom: true
+ custom_prefix: true
+ service_id: true
+ node_id: true
+ slot: true
+ desired_state: true
+ }
+ };
+
+ string id = 1;
+
+ Meta meta = 2 [(gogoproto.nullable) = false];
+
+ // Spec defines the desired state of the task as specified by the user.
+ // The system will honor this and will *never* modify it.
+ TaskSpec spec = 3 [(gogoproto.nullable) = false];
+
+ // SpecVersion is copied from Service, to identify which version of the
+ // spec this task has. Note that this is not directly comparable to the
+ // service's Version.
+ Version spec_version = 14;
+
+ // ServiceID indicates the service under which this task is orchestrated. This
+ // should almost always be set.
+ string service_id = 4;
+
+ // Slot is the service slot number for a task.
+ // For example, if a replicated service has replicas = 2, there will be a
+ // task with slot = 1, and another with slot = 2.
+ uint64 slot = 5;
+
+ // NodeID indicates the node to which the task is assigned. If this field
+ // is empty or not set, the task is unassigned.
+ string node_id = 6;
+
+ // Annotations defines the names and labels for the runtime, as set by
+ // the cluster manager.
+ //
+ // As backup, if this field has an empty name, the runtime will
+ // allocate a unique name for the actual container.
+ //
+ // NOTE(stevvooe): The preserves the ability for us to making naming
+ // decisions for tasks in orchestrator, albeit, this is left empty for now.
+ Annotations annotations = 7 [(gogoproto.nullable) = false];
+
+ // ServiceAnnotations is a direct copy of the service name and labels when
+ // this task is created.
+ //
+ // Labels set here will *not* be propagated to the runtime target, such as a
+ // container. Use labels on the runtime target for that purpose.
+ Annotations service_annotations = 8 [(gogoproto.nullable) = false];
+
+ TaskStatus status = 9 [(gogoproto.nullable) = false];
+
+ // DesiredState is the target state for the task. It is set to
+ // TaskStateRunning when a task is first created, and changed to
+ // TaskStateShutdown if the manager wants to terminate the task. This field
+ // is only written by the manager.
+ TaskState desired_state = 10;
+
+ // List of network attachments by the task.
+ repeated NetworkAttachment networks = 11;
+
+ // A copy of runtime state of service endpoint from Service
+ // object to be distributed to agents as part of the task.
+ Endpoint endpoint = 12;
+
+ // LogDriver specifies the selected log driver to use for the task. Agent
+ // processes should always favor the value in this field.
+ //
+ // If present in the TaskSpec, this will be a copy of that value. The
+ // orchestrator may choose to insert a value here, which should be honored,
+ // such a cluster default or policy-based value.
+ //
+ // If not present, the daemon's default will be used.
+ Driver log_driver = 13;
+
+ repeated GenericResource assigned_generic_resources = 15;
+}
+
+// NetworkAttachment specifies the network parameters of attachment to
+// a single network by an object such as task or node.
+message NetworkAttachment {
+ // Network state as a whole becomes part of the object so that
+ // it always is available for use in agents so that agents
+ // don't have any other dependency during execution.
+ Network network = 1;
+
+ // List of IPv4/IPv6 addresses that are assigned to the object
+ // as part of getting attached to this network.
+ repeated string addresses = 2;
+
+ // List of aliases by which a task is resolved in a network
+ repeated string aliases = 3;
+
+ // Map of all the driver attachment options for this network
+ map<string,string> driver_attachment_opts = 4;
+}
+
+message Network {
+ option (docker.protobuf.plugin.store_object) = {
+ watch_selectors: {
+ id: true
+ id_prefix: true
+ name: true
+ name_prefix: true
+ custom: true
+ custom_prefix: true
+ }
+ };
+
+ string id = 1;
+
+ Meta meta = 2 [(gogoproto.nullable) = false];
+
+ NetworkSpec spec = 3 [(gogoproto.nullable) = false];
+
+ // Driver specific operational state provided by the network driver.
+ Driver driver_state = 4;
+
+ // Runtime state of IPAM options. This may not reflect the
+ // ipam options from NetworkSpec.
+ IPAMOptions ipam = 5 [(gogoproto.customname) = "IPAM"];
+}
+
+// Cluster provides global cluster settings.
+message Cluster {
+ option (docker.protobuf.plugin.store_object) = {
+ watch_selectors: {
+ id: true
+ id_prefix: true
+ name: true
+ name_prefix: true
+ custom: true
+ custom_prefix: true
+ }
+ };
+
+ string id = 1;
+
+ Meta meta = 2 [(gogoproto.nullable) = false];
+
+ ClusterSpec spec = 3 [(gogoproto.nullable) = false];
+
+ // RootCA contains key material for the root CA.
+ RootCA root_ca = 4 [(gogoproto.nullable)=false, (gogoproto.customname) = "RootCA"];
+
+ // Symmetric encryption key distributed by the lead manager. Used by agents
+ // for securing network bootstrapping and communication.
+ repeated EncryptionKey network_bootstrap_keys = 5;
+
+ // Logical clock used to timestamp every key. It allows other managers
+ // and agents to unambiguously identify the older key to be deleted when
+ // a new key is allocated on key rotation.
+ uint64 encryption_key_lamport_clock = 6;
+
+ // BlacklistedCertificates tracks certificates that should no longer
+ // be honored. It's a mapping from CN -> BlacklistedCertificate.
+ // swarm. Their certificates should effectively be blacklisted.
+ map<string, BlacklistedCertificate> blacklisted_certificates = 8;
+
+ // UnlockKeys defines the keys that lock node data at rest. For example,
+ // this would contain the key encrypting key (KEK) that will encrypt the
+ // manager TLS keys at rest and the raft encryption keys at rest.
+ // If the key is empty, the node will be unlocked (will not require a key
+ // to start up from a shut down state).
+ repeated EncryptionKey unlock_keys = 9;
+}
+
+// Secret represents a secret that should be passed to a container or a node,
+// and is immutable.
+message Secret {
+ option (docker.protobuf.plugin.store_object) = {
+ watch_selectors: {
+ id: true
+ id_prefix: true
+ name: true
+ name_prefix: true
+ custom: true
+ custom_prefix: true
+ }
+ };
+
+ string id = 1;
+
+ Meta meta = 2 [(gogoproto.nullable) = false];
+
+ // Spec contains the actual secret data, as well as any context around the
+ // secret data that the user provides.
+ SecretSpec spec = 3 [(gogoproto.nullable) = false];
+
+ // Whether the secret is an internal secret (not set by a user) or not.
+ bool internal = 4;
+}
+
+// Config represents a set of configuration files that should be passed to a
+// container.
+message Config {
+ option (docker.protobuf.plugin.store_object) = {
+ watch_selectors: {
+ id: true
+ id_prefix: true
+ name: true
+ name_prefix: true
+ custom: true
+ custom_prefix: true
+ }
+ };
+
+ string id = 1;
+
+ Meta meta = 2 [(gogoproto.nullable) = false];
+
+ // Spec contains the actual config data, as well as any context around the
+ // config data that the user provides.
+ ConfigSpec spec = 3 [(gogoproto.nullable) = false];
+}
+
+// Resource is a top-level object with externally defined content and indexing.
+// SwarmKit can serve as a store for these objects without understanding their
+// meanings.
+message Resource {
+ option (docker.protobuf.plugin.store_object) = {
+ watch_selectors: {
+ id: true
+ id_prefix: true
+ name: true
+ name_prefix: true
+ custom: true
+ custom_prefix: true
+ kind: true
+ }
+ };
+
+ string id = 1 [(gogoproto.customname) = "ID"];
+
+ Meta meta = 2 [(gogoproto.nullable) = false];
+
+ Annotations annotations = 3 [(gogoproto.nullable) = false];
+
+ // Kind identifies this class of object. It is essentially a namespace
+ // to keep IDs or indices from colliding between unrelated Resource
+ // objects. This must correspond to the name of an Extension.
+ string kind = 4;
+
+ // Payload bytes. This data is not interpreted in any way by SwarmKit.
+ // By convention, it should be a marshalled protocol buffers message.
+ google.protobuf.Any payload = 5;
+}
+
+// Extension declares a type of "resource" object. This message provides some
+// metadata about the objects.
+message Extension {
+ option (docker.protobuf.plugin.store_object) = {
+ watch_selectors: {
+ id: true
+ id_prefix: true
+ name: true
+ name_prefix: true
+ custom: true
+ custom_prefix: true
+ }
+ };
+
+ string id = 1 [(gogoproto.customname) = "ID"];
+
+ Meta meta = 2 [(gogoproto.nullable) = false];
+
+ Annotations annotations = 3 [(gogoproto.nullable) = false];
+
+ string description = 4;
+
+ // TODO(aaronl): Add optional indexing capabilities. It would be
+ // extremely useful be able to automatically introspect protobuf, json,
+ // etc. objects and automatically index them based on a schema and field
+ // paths defined here.
+ //
+ //oneof Schema {
+ // google.protobuf.Descriptor protobuf = 1;
+ // bytes json = 2;
+ //}
+ //
+ //Schema schema = 5;
+ //
+ // // Indices, with values expressed as Go templates.
+ //repeated IndexEntry index_templates = 6;
+}
diff --git a/vendor/github.com/docker/swarmkit/api/raft.pb.go b/vendor/github.com/docker/swarmkit/api/raft.pb.go
new file mode 100644
index 0000000..6a1e8ef
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/raft.pb.go
@@ -0,0 +1,3638 @@
+// Code generated by protoc-gen-gogo.
+// source: raft.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import raftpb "github.com/coreos/etcd/raft/raftpb"
+
+// skipping weak import gogoproto "github.com/gogo/protobuf/gogoproto"
+// skipping weak import docker_protobuf_plugin "github.com/docker/swarmkit/protobuf/plugin"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+import raftselector "github.com/docker/swarmkit/manager/raftselector"
+import codes "google.golang.org/grpc/codes"
+import metadata "google.golang.org/grpc/metadata"
+import transport "google.golang.org/grpc/transport"
+import rafttime "time"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// StoreActionKind defines the operation to take on the store for the target of
+// a storage action.
+type StoreActionKind int32
+
+const (
+ StoreActionKindUnknown StoreActionKind = 0
+ StoreActionKindCreate StoreActionKind = 1
+ StoreActionKindUpdate StoreActionKind = 2
+ StoreActionKindRemove StoreActionKind = 3
+)
+
+var StoreActionKind_name = map[int32]string{
+ 0: "UNKNOWN",
+ 1: "STORE_ACTION_CREATE",
+ 2: "STORE_ACTION_UPDATE",
+ 3: "STORE_ACTION_REMOVE",
+}
+var StoreActionKind_value = map[string]int32{
+ "UNKNOWN": 0,
+ "STORE_ACTION_CREATE": 1,
+ "STORE_ACTION_UPDATE": 2,
+ "STORE_ACTION_REMOVE": 3,
+}
+
+func (x StoreActionKind) String() string {
+ return proto.EnumName(StoreActionKind_name, int32(x))
+}
+func (StoreActionKind) EnumDescriptor() ([]byte, []int) { return fileDescriptorRaft, []int{0} }
+
+type RaftMember struct {
+ // RaftID specifies the internal ID used by the manager in a raft context, it can never be modified
+ // and is used only for information purposes
+ RaftID uint64 `protobuf:"varint,1,opt,name=raft_id,json=raftId,proto3" json:"raft_id,omitempty"`
+ // NodeID is the node's ID.
+ NodeID string `protobuf:"bytes,2,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"`
+ // Addr specifies the address of the member
+ Addr string `protobuf:"bytes,3,opt,name=addr,proto3" json:"addr,omitempty"`
+ // Status provides the current status of the manager from the perspective of another manager.
+ Status RaftMemberStatus `protobuf:"bytes,4,opt,name=status" json:"status"`
+}
+
+func (m *RaftMember) Reset() { *m = RaftMember{} }
+func (*RaftMember) ProtoMessage() {}
+func (*RaftMember) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{0} }
+
+type JoinRequest struct {
+ // Addr specifies the address of the member
+ Addr string `protobuf:"bytes,1,opt,name=addr,proto3" json:"addr,omitempty"`
+}
+
+func (m *JoinRequest) Reset() { *m = JoinRequest{} }
+func (*JoinRequest) ProtoMessage() {}
+func (*JoinRequest) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{1} }
+
+type JoinResponse struct {
+ // RaftID is the ID assigned to the new member.
+ RaftID uint64 `protobuf:"varint,1,opt,name=raft_id,json=raftId,proto3" json:"raft_id,omitempty"`
+ // Members is the membership set of the cluster.
+ Members []*RaftMember `protobuf:"bytes,2,rep,name=members" json:"members,omitempty"`
+ // RemovedMembers is a list of members that have been removed from
+ // the cluster, so the new node can avoid communicating with them.
+ RemovedMembers []uint64 `protobuf:"varint,3,rep,name=removed_members,json=removedMembers" json:"removed_members,omitempty"`
+}
+
+func (m *JoinResponse) Reset() { *m = JoinResponse{} }
+func (*JoinResponse) ProtoMessage() {}
+func (*JoinResponse) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{2} }
+
+type LeaveRequest struct {
+ Node *RaftMember `protobuf:"bytes,1,opt,name=node" json:"node,omitempty"`
+}
+
+func (m *LeaveRequest) Reset() { *m = LeaveRequest{} }
+func (*LeaveRequest) ProtoMessage() {}
+func (*LeaveRequest) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{3} }
+
+type LeaveResponse struct {
+}
+
+func (m *LeaveResponse) Reset() { *m = LeaveResponse{} }
+func (*LeaveResponse) ProtoMessage() {}
+func (*LeaveResponse) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{4} }
+
+type ProcessRaftMessageRequest struct {
+ Message *raftpb.Message `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"`
+}
+
+func (m *ProcessRaftMessageRequest) Reset() { *m = ProcessRaftMessageRequest{} }
+func (*ProcessRaftMessageRequest) ProtoMessage() {}
+func (*ProcessRaftMessageRequest) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{5} }
+
+type ProcessRaftMessageResponse struct {
+}
+
+func (m *ProcessRaftMessageResponse) Reset() { *m = ProcessRaftMessageResponse{} }
+func (*ProcessRaftMessageResponse) ProtoMessage() {}
+func (*ProcessRaftMessageResponse) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{6} }
+
+type ResolveAddressRequest struct {
+ // raft_id is the ID to resolve to an address.
+ RaftID uint64 `protobuf:"varint,1,opt,name=raft_id,json=raftId,proto3" json:"raft_id,omitempty"`
+}
+
+func (m *ResolveAddressRequest) Reset() { *m = ResolveAddressRequest{} }
+func (*ResolveAddressRequest) ProtoMessage() {}
+func (*ResolveAddressRequest) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{7} }
+
+type ResolveAddressResponse struct {
+ // Addr specifies the address of the member
+ Addr string `protobuf:"bytes,1,opt,name=addr,proto3" json:"addr,omitempty"`
+}
+
+func (m *ResolveAddressResponse) Reset() { *m = ResolveAddressResponse{} }
+func (*ResolveAddressResponse) ProtoMessage() {}
+func (*ResolveAddressResponse) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{8} }
+
+// Contains one of many protobuf encoded objects to replicate
+// over the raft backend with a request ID to track when the
+// action is effectively applied
+type InternalRaftRequest struct {
+ ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
+ Action []StoreAction `protobuf:"bytes,2,rep,name=action" json:"action"`
+}
+
+func (m *InternalRaftRequest) Reset() { *m = InternalRaftRequest{} }
+func (*InternalRaftRequest) ProtoMessage() {}
+func (*InternalRaftRequest) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{9} }
+
+// StoreAction defines a target and operation to apply on the storage system.
+type StoreAction struct {
+ Action StoreActionKind `protobuf:"varint,1,opt,name=action,proto3,enum=docker.swarmkit.v1.StoreActionKind" json:"action,omitempty"`
+ // Types that are valid to be assigned to Target:
+ // *StoreAction_Node
+ // *StoreAction_Service
+ // *StoreAction_Task
+ // *StoreAction_Network
+ // *StoreAction_Cluster
+ // *StoreAction_Secret
+ // *StoreAction_Resource
+ // *StoreAction_Extension
+ // *StoreAction_Config
+ Target isStoreAction_Target `protobuf_oneof:"target"`
+}
+
+func (m *StoreAction) Reset() { *m = StoreAction{} }
+func (*StoreAction) ProtoMessage() {}
+func (*StoreAction) Descriptor() ([]byte, []int) { return fileDescriptorRaft, []int{10} }
+
+type isStoreAction_Target interface {
+ isStoreAction_Target()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type StoreAction_Node struct {
+ Node *Node `protobuf:"bytes,2,opt,name=node,oneof"`
+}
+type StoreAction_Service struct {
+ Service *Service `protobuf:"bytes,3,opt,name=service,oneof"`
+}
+type StoreAction_Task struct {
+ Task *Task `protobuf:"bytes,4,opt,name=task,oneof"`
+}
+type StoreAction_Network struct {
+ Network *Network `protobuf:"bytes,5,opt,name=network,oneof"`
+}
+type StoreAction_Cluster struct {
+ Cluster *Cluster `protobuf:"bytes,6,opt,name=cluster,oneof"`
+}
+type StoreAction_Secret struct {
+ Secret *Secret `protobuf:"bytes,7,opt,name=secret,oneof"`
+}
+type StoreAction_Resource struct {
+ Resource *Resource `protobuf:"bytes,8,opt,name=resource,oneof"`
+}
+type StoreAction_Extension struct {
+ Extension *Extension `protobuf:"bytes,9,opt,name=extension,oneof"`
+}
+type StoreAction_Config struct {
+ Config *Config `protobuf:"bytes,10,opt,name=config,oneof"`
+}
+
+func (*StoreAction_Node) isStoreAction_Target() {}
+func (*StoreAction_Service) isStoreAction_Target() {}
+func (*StoreAction_Task) isStoreAction_Target() {}
+func (*StoreAction_Network) isStoreAction_Target() {}
+func (*StoreAction_Cluster) isStoreAction_Target() {}
+func (*StoreAction_Secret) isStoreAction_Target() {}
+func (*StoreAction_Resource) isStoreAction_Target() {}
+func (*StoreAction_Extension) isStoreAction_Target() {}
+func (*StoreAction_Config) isStoreAction_Target() {}
+
+func (m *StoreAction) GetTarget() isStoreAction_Target {
+ if m != nil {
+ return m.Target
+ }
+ return nil
+}
+
+func (m *StoreAction) GetNode() *Node {
+ if x, ok := m.GetTarget().(*StoreAction_Node); ok {
+ return x.Node
+ }
+ return nil
+}
+
+func (m *StoreAction) GetService() *Service {
+ if x, ok := m.GetTarget().(*StoreAction_Service); ok {
+ return x.Service
+ }
+ return nil
+}
+
+func (m *StoreAction) GetTask() *Task {
+ if x, ok := m.GetTarget().(*StoreAction_Task); ok {
+ return x.Task
+ }
+ return nil
+}
+
+func (m *StoreAction) GetNetwork() *Network {
+ if x, ok := m.GetTarget().(*StoreAction_Network); ok {
+ return x.Network
+ }
+ return nil
+}
+
+func (m *StoreAction) GetCluster() *Cluster {
+ if x, ok := m.GetTarget().(*StoreAction_Cluster); ok {
+ return x.Cluster
+ }
+ return nil
+}
+
+func (m *StoreAction) GetSecret() *Secret {
+ if x, ok := m.GetTarget().(*StoreAction_Secret); ok {
+ return x.Secret
+ }
+ return nil
+}
+
+func (m *StoreAction) GetResource() *Resource {
+ if x, ok := m.GetTarget().(*StoreAction_Resource); ok {
+ return x.Resource
+ }
+ return nil
+}
+
+func (m *StoreAction) GetExtension() *Extension {
+ if x, ok := m.GetTarget().(*StoreAction_Extension); ok {
+ return x.Extension
+ }
+ return nil
+}
+
+func (m *StoreAction) GetConfig() *Config {
+ if x, ok := m.GetTarget().(*StoreAction_Config); ok {
+ return x.Config
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*StoreAction) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _StoreAction_OneofMarshaler, _StoreAction_OneofUnmarshaler, _StoreAction_OneofSizer, []interface{}{
+ (*StoreAction_Node)(nil),
+ (*StoreAction_Service)(nil),
+ (*StoreAction_Task)(nil),
+ (*StoreAction_Network)(nil),
+ (*StoreAction_Cluster)(nil),
+ (*StoreAction_Secret)(nil),
+ (*StoreAction_Resource)(nil),
+ (*StoreAction_Extension)(nil),
+ (*StoreAction_Config)(nil),
+ }
+}
+
+func _StoreAction_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*StoreAction)
+ // target
+ switch x := m.Target.(type) {
+ case *StoreAction_Node:
+ _ = b.EncodeVarint(2<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Node); err != nil {
+ return err
+ }
+ case *StoreAction_Service:
+ _ = b.EncodeVarint(3<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Service); err != nil {
+ return err
+ }
+ case *StoreAction_Task:
+ _ = b.EncodeVarint(4<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Task); err != nil {
+ return err
+ }
+ case *StoreAction_Network:
+ _ = b.EncodeVarint(5<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Network); err != nil {
+ return err
+ }
+ case *StoreAction_Cluster:
+ _ = b.EncodeVarint(6<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Cluster); err != nil {
+ return err
+ }
+ case *StoreAction_Secret:
+ _ = b.EncodeVarint(7<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Secret); err != nil {
+ return err
+ }
+ case *StoreAction_Resource:
+ _ = b.EncodeVarint(8<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Resource); err != nil {
+ return err
+ }
+ case *StoreAction_Extension:
+ _ = b.EncodeVarint(9<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Extension); err != nil {
+ return err
+ }
+ case *StoreAction_Config:
+ _ = b.EncodeVarint(10<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Config); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("StoreAction.Target has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _StoreAction_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*StoreAction)
+ switch tag {
+ case 2: // target.node
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Node)
+ err := b.DecodeMessage(msg)
+ m.Target = &StoreAction_Node{msg}
+ return true, err
+ case 3: // target.service
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Service)
+ err := b.DecodeMessage(msg)
+ m.Target = &StoreAction_Service{msg}
+ return true, err
+ case 4: // target.task
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Task)
+ err := b.DecodeMessage(msg)
+ m.Target = &StoreAction_Task{msg}
+ return true, err
+ case 5: // target.network
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Network)
+ err := b.DecodeMessage(msg)
+ m.Target = &StoreAction_Network{msg}
+ return true, err
+ case 6: // target.cluster
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Cluster)
+ err := b.DecodeMessage(msg)
+ m.Target = &StoreAction_Cluster{msg}
+ return true, err
+ case 7: // target.secret
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Secret)
+ err := b.DecodeMessage(msg)
+ m.Target = &StoreAction_Secret{msg}
+ return true, err
+ case 8: // target.resource
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Resource)
+ err := b.DecodeMessage(msg)
+ m.Target = &StoreAction_Resource{msg}
+ return true, err
+ case 9: // target.extension
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Extension)
+ err := b.DecodeMessage(msg)
+ m.Target = &StoreAction_Extension{msg}
+ return true, err
+ case 10: // target.config
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Config)
+ err := b.DecodeMessage(msg)
+ m.Target = &StoreAction_Config{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _StoreAction_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*StoreAction)
+ // target
+ switch x := m.Target.(type) {
+ case *StoreAction_Node:
+ s := proto.Size(x.Node)
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *StoreAction_Service:
+ s := proto.Size(x.Service)
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *StoreAction_Task:
+ s := proto.Size(x.Task)
+ n += proto.SizeVarint(4<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *StoreAction_Network:
+ s := proto.Size(x.Network)
+ n += proto.SizeVarint(5<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *StoreAction_Cluster:
+ s := proto.Size(x.Cluster)
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *StoreAction_Secret:
+ s := proto.Size(x.Secret)
+ n += proto.SizeVarint(7<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *StoreAction_Resource:
+ s := proto.Size(x.Resource)
+ n += proto.SizeVarint(8<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *StoreAction_Extension:
+ s := proto.Size(x.Extension)
+ n += proto.SizeVarint(9<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *StoreAction_Config:
+ s := proto.Size(x.Config)
+ n += proto.SizeVarint(10<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+func init() {
+ proto.RegisterType((*RaftMember)(nil), "docker.swarmkit.v1.RaftMember")
+ proto.RegisterType((*JoinRequest)(nil), "docker.swarmkit.v1.JoinRequest")
+ proto.RegisterType((*JoinResponse)(nil), "docker.swarmkit.v1.JoinResponse")
+ proto.RegisterType((*LeaveRequest)(nil), "docker.swarmkit.v1.LeaveRequest")
+ proto.RegisterType((*LeaveResponse)(nil), "docker.swarmkit.v1.LeaveResponse")
+ proto.RegisterType((*ProcessRaftMessageRequest)(nil), "docker.swarmkit.v1.ProcessRaftMessageRequest")
+ proto.RegisterType((*ProcessRaftMessageResponse)(nil), "docker.swarmkit.v1.ProcessRaftMessageResponse")
+ proto.RegisterType((*ResolveAddressRequest)(nil), "docker.swarmkit.v1.ResolveAddressRequest")
+ proto.RegisterType((*ResolveAddressResponse)(nil), "docker.swarmkit.v1.ResolveAddressResponse")
+ proto.RegisterType((*InternalRaftRequest)(nil), "docker.swarmkit.v1.InternalRaftRequest")
+ proto.RegisterType((*StoreAction)(nil), "docker.swarmkit.v1.StoreAction")
+ proto.RegisterEnum("docker.swarmkit.v1.StoreActionKind", StoreActionKind_name, StoreActionKind_value)
+}
+
+type authenticatedWrapperRaftServer struct {
+ local RaftServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperRaftServer(local RaftServer, authorize func(context.Context, []string) error) RaftServer {
+ return &authenticatedWrapperRaftServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperRaftServer) ProcessRaftMessage(ctx context.Context, r *ProcessRaftMessageRequest) (*ProcessRaftMessageResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.ProcessRaftMessage(ctx, r)
+}
+
+func (p *authenticatedWrapperRaftServer) ResolveAddress(ctx context.Context, r *ResolveAddressRequest) (*ResolveAddressResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.ResolveAddress(ctx, r)
+}
+
+type authenticatedWrapperRaftMembershipServer struct {
+ local RaftMembershipServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperRaftMembershipServer(local RaftMembershipServer, authorize func(context.Context, []string) error) RaftMembershipServer {
+ return &authenticatedWrapperRaftMembershipServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperRaftMembershipServer) Join(ctx context.Context, r *JoinRequest) (*JoinResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.Join(ctx, r)
+}
+
+func (p *authenticatedWrapperRaftMembershipServer) Leave(ctx context.Context, r *LeaveRequest) (*LeaveResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.Leave(ctx, r)
+}
+
+func (m *RaftMember) Copy() *RaftMember {
+ if m == nil {
+ return nil
+ }
+ o := &RaftMember{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RaftMember) CopyFrom(src interface{}) {
+
+ o := src.(*RaftMember)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Status, &o.Status)
+}
+
+func (m *JoinRequest) Copy() *JoinRequest {
+ if m == nil {
+ return nil
+ }
+ o := &JoinRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *JoinRequest) CopyFrom(src interface{}) {
+
+ o := src.(*JoinRequest)
+ *m = *o
+}
+
+func (m *JoinResponse) Copy() *JoinResponse {
+ if m == nil {
+ return nil
+ }
+ o := &JoinResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *JoinResponse) CopyFrom(src interface{}) {
+
+ o := src.(*JoinResponse)
+ *m = *o
+ if o.Members != nil {
+ m.Members = make([]*RaftMember, len(o.Members))
+ for i := range m.Members {
+ m.Members[i] = &RaftMember{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Members[i], o.Members[i])
+ }
+ }
+
+ if o.RemovedMembers != nil {
+ m.RemovedMembers = make([]uint64, len(o.RemovedMembers))
+ copy(m.RemovedMembers, o.RemovedMembers)
+ }
+
+}
+
+func (m *LeaveRequest) Copy() *LeaveRequest {
+ if m == nil {
+ return nil
+ }
+ o := &LeaveRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *LeaveRequest) CopyFrom(src interface{}) {
+
+ o := src.(*LeaveRequest)
+ *m = *o
+ if o.Node != nil {
+ m.Node = &RaftMember{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Node, o.Node)
+ }
+}
+
+func (m *LeaveResponse) Copy() *LeaveResponse {
+ if m == nil {
+ return nil
+ }
+ o := &LeaveResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *LeaveResponse) CopyFrom(src interface{}) {}
+func (m *ProcessRaftMessageResponse) Copy() *ProcessRaftMessageResponse {
+ if m == nil {
+ return nil
+ }
+ o := &ProcessRaftMessageResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ProcessRaftMessageResponse) CopyFrom(src interface{}) {}
+func (m *ResolveAddressRequest) Copy() *ResolveAddressRequest {
+ if m == nil {
+ return nil
+ }
+ o := &ResolveAddressRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ResolveAddressRequest) CopyFrom(src interface{}) {
+
+ o := src.(*ResolveAddressRequest)
+ *m = *o
+}
+
+func (m *ResolveAddressResponse) Copy() *ResolveAddressResponse {
+ if m == nil {
+ return nil
+ }
+ o := &ResolveAddressResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ResolveAddressResponse) CopyFrom(src interface{}) {
+
+ o := src.(*ResolveAddressResponse)
+ *m = *o
+}
+
+func (m *InternalRaftRequest) Copy() *InternalRaftRequest {
+ if m == nil {
+ return nil
+ }
+ o := &InternalRaftRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *InternalRaftRequest) CopyFrom(src interface{}) {
+
+ o := src.(*InternalRaftRequest)
+ *m = *o
+ if o.Action != nil {
+ m.Action = make([]StoreAction, len(o.Action))
+ for i := range m.Action {
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Action[i], &o.Action[i])
+ }
+ }
+
+}
+
+func (m *StoreAction) Copy() *StoreAction {
+ if m == nil {
+ return nil
+ }
+ o := &StoreAction{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *StoreAction) CopyFrom(src interface{}) {
+
+ o := src.(*StoreAction)
+ *m = *o
+ if o.Target != nil {
+ switch o.Target.(type) {
+ case *StoreAction_Node:
+ v := StoreAction_Node{
+ Node: &Node{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Node, o.GetNode())
+ m.Target = &v
+ case *StoreAction_Service:
+ v := StoreAction_Service{
+ Service: &Service{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Service, o.GetService())
+ m.Target = &v
+ case *StoreAction_Task:
+ v := StoreAction_Task{
+ Task: &Task{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Task, o.GetTask())
+ m.Target = &v
+ case *StoreAction_Network:
+ v := StoreAction_Network{
+ Network: &Network{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Network, o.GetNetwork())
+ m.Target = &v
+ case *StoreAction_Cluster:
+ v := StoreAction_Cluster{
+ Cluster: &Cluster{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Cluster, o.GetCluster())
+ m.Target = &v
+ case *StoreAction_Secret:
+ v := StoreAction_Secret{
+ Secret: &Secret{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Secret, o.GetSecret())
+ m.Target = &v
+ case *StoreAction_Resource:
+ v := StoreAction_Resource{
+ Resource: &Resource{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Resource, o.GetResource())
+ m.Target = &v
+ case *StoreAction_Extension:
+ v := StoreAction_Extension{
+ Extension: &Extension{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Extension, o.GetExtension())
+ m.Target = &v
+ case *StoreAction_Config:
+ v := StoreAction_Config{
+ Config: &Config{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Config, o.GetConfig())
+ m.Target = &v
+ }
+ }
+
+}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for Raft service
+
+type RaftClient interface {
+ // ProcessRaftMessage sends a raft message to be processed on a raft member, it is
+ // called from the RaftMember willing to send a message to its destination ('To' field)
+ ProcessRaftMessage(ctx context.Context, in *ProcessRaftMessageRequest, opts ...grpc.CallOption) (*ProcessRaftMessageResponse, error)
+ // ResolveAddress returns the address where the node with the given ID can be reached.
+ ResolveAddress(ctx context.Context, in *ResolveAddressRequest, opts ...grpc.CallOption) (*ResolveAddressResponse, error)
+}
+
+type raftClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewRaftClient(cc *grpc.ClientConn) RaftClient {
+ return &raftClient{cc}
+}
+
+func (c *raftClient) ProcessRaftMessage(ctx context.Context, in *ProcessRaftMessageRequest, opts ...grpc.CallOption) (*ProcessRaftMessageResponse, error) {
+ out := new(ProcessRaftMessageResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Raft/ProcessRaftMessage", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *raftClient) ResolveAddress(ctx context.Context, in *ResolveAddressRequest, opts ...grpc.CallOption) (*ResolveAddressResponse, error) {
+ out := new(ResolveAddressResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.Raft/ResolveAddress", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for Raft service
+
+type RaftServer interface {
+ // ProcessRaftMessage sends a raft message to be processed on a raft member, it is
+ // called from the RaftMember willing to send a message to its destination ('To' field)
+ ProcessRaftMessage(context.Context, *ProcessRaftMessageRequest) (*ProcessRaftMessageResponse, error)
+ // ResolveAddress returns the address where the node with the given ID can be reached.
+ ResolveAddress(context.Context, *ResolveAddressRequest) (*ResolveAddressResponse, error)
+}
+
+func RegisterRaftServer(s *grpc.Server, srv RaftServer) {
+ s.RegisterService(&_Raft_serviceDesc, srv)
+}
+
+func _Raft_ProcessRaftMessage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ProcessRaftMessageRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(RaftServer).ProcessRaftMessage(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Raft/ProcessRaftMessage",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(RaftServer).ProcessRaftMessage(ctx, req.(*ProcessRaftMessageRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Raft_ResolveAddress_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ResolveAddressRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(RaftServer).ResolveAddress(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.Raft/ResolveAddress",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(RaftServer).ResolveAddress(ctx, req.(*ResolveAddressRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _Raft_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.Raft",
+ HandlerType: (*RaftServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "ProcessRaftMessage",
+ Handler: _Raft_ProcessRaftMessage_Handler,
+ },
+ {
+ MethodName: "ResolveAddress",
+ Handler: _Raft_ResolveAddress_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "raft.proto",
+}
+
+// Client API for RaftMembership service
+
+type RaftMembershipClient interface {
+ // Join adds a RaftMember to the raft cluster.
+ Join(ctx context.Context, in *JoinRequest, opts ...grpc.CallOption) (*JoinResponse, error)
+ // Leave removes a RaftMember from the raft cluster.
+ Leave(ctx context.Context, in *LeaveRequest, opts ...grpc.CallOption) (*LeaveResponse, error)
+}
+
+type raftMembershipClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewRaftMembershipClient(cc *grpc.ClientConn) RaftMembershipClient {
+ return &raftMembershipClient{cc}
+}
+
+func (c *raftMembershipClient) Join(ctx context.Context, in *JoinRequest, opts ...grpc.CallOption) (*JoinResponse, error) {
+ out := new(JoinResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.RaftMembership/Join", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *raftMembershipClient) Leave(ctx context.Context, in *LeaveRequest, opts ...grpc.CallOption) (*LeaveResponse, error) {
+ out := new(LeaveResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.RaftMembership/Leave", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for RaftMembership service
+
+type RaftMembershipServer interface {
+ // Join adds a RaftMember to the raft cluster.
+ Join(context.Context, *JoinRequest) (*JoinResponse, error)
+ // Leave removes a RaftMember from the raft cluster.
+ Leave(context.Context, *LeaveRequest) (*LeaveResponse, error)
+}
+
+func RegisterRaftMembershipServer(s *grpc.Server, srv RaftMembershipServer) {
+ s.RegisterService(&_RaftMembership_serviceDesc, srv)
+}
+
+func _RaftMembership_Join_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(JoinRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(RaftMembershipServer).Join(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.RaftMembership/Join",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(RaftMembershipServer).Join(ctx, req.(*JoinRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _RaftMembership_Leave_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(LeaveRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(RaftMembershipServer).Leave(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.RaftMembership/Leave",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(RaftMembershipServer).Leave(ctx, req.(*LeaveRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _RaftMembership_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.RaftMembership",
+ HandlerType: (*RaftMembershipServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "Join",
+ Handler: _RaftMembership_Join_Handler,
+ },
+ {
+ MethodName: "Leave",
+ Handler: _RaftMembership_Leave_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "raft.proto",
+}
+
+func (m *RaftMember) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RaftMember) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.RaftID != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.RaftID))
+ }
+ if len(m.NodeID) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(len(m.NodeID)))
+ i += copy(dAtA[i:], m.NodeID)
+ }
+ if len(m.Addr) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(len(m.Addr)))
+ i += copy(dAtA[i:], m.Addr)
+ }
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Status.Size()))
+ n1, err := m.Status.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ return i, nil
+}
+
+func (m *JoinRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *JoinRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Addr) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(len(m.Addr)))
+ i += copy(dAtA[i:], m.Addr)
+ }
+ return i, nil
+}
+
+func (m *JoinResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *JoinResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.RaftID != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.RaftID))
+ }
+ if len(m.Members) > 0 {
+ for _, msg := range m.Members {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.RemovedMembers) > 0 {
+ for _, num := range m.RemovedMembers {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(num))
+ }
+ }
+ return i, nil
+}
+
+func (m *LeaveRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *LeaveRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Node != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Node.Size()))
+ n2, err := m.Node.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ }
+ return i, nil
+}
+
+func (m *LeaveResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *LeaveResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *ProcessRaftMessageRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ProcessRaftMessageRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Message != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Message.Size()))
+ n3, err := m.Message.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ }
+ return i, nil
+}
+
+func (m *ProcessRaftMessageResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ProcessRaftMessageResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *ResolveAddressRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ResolveAddressRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.RaftID != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.RaftID))
+ }
+ return i, nil
+}
+
+func (m *ResolveAddressResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ResolveAddressResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Addr) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(len(m.Addr)))
+ i += copy(dAtA[i:], m.Addr)
+ }
+ return i, nil
+}
+
+func (m *InternalRaftRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *InternalRaftRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.ID != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.ID))
+ }
+ if len(m.Action) > 0 {
+ for _, msg := range m.Action {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *StoreAction) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *StoreAction) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Action != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Action))
+ }
+ if m.Target != nil {
+ nn4, err := m.Target.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn4
+ }
+ return i, nil
+}
+
+func (m *StoreAction_Node) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Node != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Node.Size()))
+ n5, err := m.Node.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n5
+ }
+ return i, nil
+}
+func (m *StoreAction_Service) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Service != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Service.Size()))
+ n6, err := m.Service.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n6
+ }
+ return i, nil
+}
+func (m *StoreAction_Task) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Task != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Task.Size()))
+ n7, err := m.Task.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n7
+ }
+ return i, nil
+}
+func (m *StoreAction_Network) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Network != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Network.Size()))
+ n8, err := m.Network.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n8
+ }
+ return i, nil
+}
+func (m *StoreAction_Cluster) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Cluster != nil {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Cluster.Size()))
+ n9, err := m.Cluster.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n9
+ }
+ return i, nil
+}
+func (m *StoreAction_Secret) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Secret != nil {
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Secret.Size()))
+ n10, err := m.Secret.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n10
+ }
+ return i, nil
+}
+func (m *StoreAction_Resource) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Resource != nil {
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Resource.Size()))
+ n11, err := m.Resource.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n11
+ }
+ return i, nil
+}
+func (m *StoreAction_Extension) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Extension != nil {
+ dAtA[i] = 0x4a
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Extension.Size()))
+ n12, err := m.Extension.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n12
+ }
+ return i, nil
+}
+func (m *StoreAction_Config) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Config != nil {
+ dAtA[i] = 0x52
+ i++
+ i = encodeVarintRaft(dAtA, i, uint64(m.Config.Size()))
+ n13, err := m.Config.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n13
+ }
+ return i, nil
+}
+func encodeFixed64Raft(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Raft(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintRaft(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+type raftProxyRaftServer struct {
+ local RaftServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyRaftServer(local RaftServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) RaftServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyRaftServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyRaftServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyRaftServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+func (p *raftProxyRaftServer) ProcessRaftMessage(ctx context.Context, r *ProcessRaftMessageRequest) (*ProcessRaftMessageResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.ProcessRaftMessage(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewRaftClient(conn).ProcessRaftMessage(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.ProcessRaftMessage(ctx, r)
+ }
+ return nil, err
+ }
+ return NewRaftClient(conn).ProcessRaftMessage(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyRaftServer) ResolveAddress(ctx context.Context, r *ResolveAddressRequest) (*ResolveAddressResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.ResolveAddress(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewRaftClient(conn).ResolveAddress(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.ResolveAddress(ctx, r)
+ }
+ return nil, err
+ }
+ return NewRaftClient(conn).ResolveAddress(modCtx, r)
+ }
+ return resp, err
+}
+
+type raftProxyRaftMembershipServer struct {
+ local RaftMembershipServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyRaftMembershipServer(local RaftMembershipServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) RaftMembershipServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyRaftMembershipServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyRaftMembershipServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyRaftMembershipServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+func (p *raftProxyRaftMembershipServer) Join(ctx context.Context, r *JoinRequest) (*JoinResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.Join(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewRaftMembershipClient(conn).Join(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.Join(ctx, r)
+ }
+ return nil, err
+ }
+ return NewRaftMembershipClient(conn).Join(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyRaftMembershipServer) Leave(ctx context.Context, r *LeaveRequest) (*LeaveResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.Leave(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewRaftMembershipClient(conn).Leave(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.Leave(ctx, r)
+ }
+ return nil, err
+ }
+ return NewRaftMembershipClient(conn).Leave(modCtx, r)
+ }
+ return resp, err
+}
+
+func (m *RaftMember) Size() (n int) {
+ var l int
+ _ = l
+ if m.RaftID != 0 {
+ n += 1 + sovRaft(uint64(m.RaftID))
+ }
+ l = len(m.NodeID)
+ if l > 0 {
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ l = len(m.Addr)
+ if l > 0 {
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ l = m.Status.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ return n
+}
+
+func (m *JoinRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Addr)
+ if l > 0 {
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+
+func (m *JoinResponse) Size() (n int) {
+ var l int
+ _ = l
+ if m.RaftID != 0 {
+ n += 1 + sovRaft(uint64(m.RaftID))
+ }
+ if len(m.Members) > 0 {
+ for _, e := range m.Members {
+ l = e.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ }
+ if len(m.RemovedMembers) > 0 {
+ for _, e := range m.RemovedMembers {
+ n += 1 + sovRaft(uint64(e))
+ }
+ }
+ return n
+}
+
+func (m *LeaveRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Node != nil {
+ l = m.Node.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+
+func (m *LeaveResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *ProcessRaftMessageRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Message != nil {
+ l = m.Message.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+
+func (m *ProcessRaftMessageResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *ResolveAddressRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.RaftID != 0 {
+ n += 1 + sovRaft(uint64(m.RaftID))
+ }
+ return n
+}
+
+func (m *ResolveAddressResponse) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Addr)
+ if l > 0 {
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+
+func (m *InternalRaftRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.ID != 0 {
+ n += 1 + sovRaft(uint64(m.ID))
+ }
+ if len(m.Action) > 0 {
+ for _, e := range m.Action {
+ l = e.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *StoreAction) Size() (n int) {
+ var l int
+ _ = l
+ if m.Action != 0 {
+ n += 1 + sovRaft(uint64(m.Action))
+ }
+ if m.Target != nil {
+ n += m.Target.Size()
+ }
+ return n
+}
+
+func (m *StoreAction_Node) Size() (n int) {
+ var l int
+ _ = l
+ if m.Node != nil {
+ l = m.Node.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+func (m *StoreAction_Service) Size() (n int) {
+ var l int
+ _ = l
+ if m.Service != nil {
+ l = m.Service.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+func (m *StoreAction_Task) Size() (n int) {
+ var l int
+ _ = l
+ if m.Task != nil {
+ l = m.Task.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+func (m *StoreAction_Network) Size() (n int) {
+ var l int
+ _ = l
+ if m.Network != nil {
+ l = m.Network.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+func (m *StoreAction_Cluster) Size() (n int) {
+ var l int
+ _ = l
+ if m.Cluster != nil {
+ l = m.Cluster.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+func (m *StoreAction_Secret) Size() (n int) {
+ var l int
+ _ = l
+ if m.Secret != nil {
+ l = m.Secret.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+func (m *StoreAction_Resource) Size() (n int) {
+ var l int
+ _ = l
+ if m.Resource != nil {
+ l = m.Resource.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+func (m *StoreAction_Extension) Size() (n int) {
+ var l int
+ _ = l
+ if m.Extension != nil {
+ l = m.Extension.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+func (m *StoreAction_Config) Size() (n int) {
+ var l int
+ _ = l
+ if m.Config != nil {
+ l = m.Config.Size()
+ n += 1 + l + sovRaft(uint64(l))
+ }
+ return n
+}
+
+func sovRaft(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozRaft(x uint64) (n int) {
+ return sovRaft(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *RaftMember) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RaftMember{`,
+ `RaftID:` + fmt.Sprintf("%v", this.RaftID) + `,`,
+ `NodeID:` + fmt.Sprintf("%v", this.NodeID) + `,`,
+ `Addr:` + fmt.Sprintf("%v", this.Addr) + `,`,
+ `Status:` + strings.Replace(strings.Replace(this.Status.String(), "RaftMemberStatus", "RaftMemberStatus", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *JoinRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&JoinRequest{`,
+ `Addr:` + fmt.Sprintf("%v", this.Addr) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *JoinResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&JoinResponse{`,
+ `RaftID:` + fmt.Sprintf("%v", this.RaftID) + `,`,
+ `Members:` + strings.Replace(fmt.Sprintf("%v", this.Members), "RaftMember", "RaftMember", 1) + `,`,
+ `RemovedMembers:` + fmt.Sprintf("%v", this.RemovedMembers) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *LeaveRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&LeaveRequest{`,
+ `Node:` + strings.Replace(fmt.Sprintf("%v", this.Node), "RaftMember", "RaftMember", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *LeaveResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&LeaveResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ProcessRaftMessageRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ProcessRaftMessageRequest{`,
+ `Message:` + strings.Replace(fmt.Sprintf("%v", this.Message), "Message", "raftpb.Message", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ProcessRaftMessageResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ProcessRaftMessageResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ResolveAddressRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ResolveAddressRequest{`,
+ `RaftID:` + fmt.Sprintf("%v", this.RaftID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ResolveAddressResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ResolveAddressResponse{`,
+ `Addr:` + fmt.Sprintf("%v", this.Addr) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *InternalRaftRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&InternalRaftRequest{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Action:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Action), "StoreAction", "StoreAction", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreAction) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreAction{`,
+ `Action:` + fmt.Sprintf("%v", this.Action) + `,`,
+ `Target:` + fmt.Sprintf("%v", this.Target) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreAction_Node) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreAction_Node{`,
+ `Node:` + strings.Replace(fmt.Sprintf("%v", this.Node), "Node", "Node", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreAction_Service) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreAction_Service{`,
+ `Service:` + strings.Replace(fmt.Sprintf("%v", this.Service), "Service", "Service", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreAction_Task) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreAction_Task{`,
+ `Task:` + strings.Replace(fmt.Sprintf("%v", this.Task), "Task", "Task", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreAction_Network) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreAction_Network{`,
+ `Network:` + strings.Replace(fmt.Sprintf("%v", this.Network), "Network", "Network", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreAction_Cluster) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreAction_Cluster{`,
+ `Cluster:` + strings.Replace(fmt.Sprintf("%v", this.Cluster), "Cluster", "Cluster", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreAction_Secret) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreAction_Secret{`,
+ `Secret:` + strings.Replace(fmt.Sprintf("%v", this.Secret), "Secret", "Secret", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreAction_Resource) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreAction_Resource{`,
+ `Resource:` + strings.Replace(fmt.Sprintf("%v", this.Resource), "Resource", "Resource", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreAction_Extension) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreAction_Extension{`,
+ `Extension:` + strings.Replace(fmt.Sprintf("%v", this.Extension), "Extension", "Extension", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreAction_Config) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreAction_Config{`,
+ `Config:` + strings.Replace(fmt.Sprintf("%v", this.Config), "Config", "Config", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringRaft(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *RaftMember) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RaftMember: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RaftMember: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RaftID", wireType)
+ }
+ m.RaftID = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RaftID |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Addr", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Addr = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *JoinRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: JoinRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: JoinRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Addr", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Addr = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *JoinResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: JoinResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: JoinResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RaftID", wireType)
+ }
+ m.RaftID = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RaftID |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Members", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Members = append(m.Members, &RaftMember{})
+ if err := m.Members[len(m.Members)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType == 0 {
+ var v uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.RemovedMembers = append(m.RemovedMembers, v)
+ } else if wireType == 2 {
+ var packedLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ packedLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if packedLen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + packedLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ for iNdEx < postIndex {
+ var v uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.RemovedMembers = append(m.RemovedMembers, v)
+ }
+ } else {
+ return fmt.Errorf("proto: wrong wireType = %d for field RemovedMembers", wireType)
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *LeaveRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: LeaveRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: LeaveRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Node", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Node == nil {
+ m.Node = &RaftMember{}
+ }
+ if err := m.Node.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *LeaveResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: LeaveResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: LeaveResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ProcessRaftMessageRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ProcessRaftMessageRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ProcessRaftMessageRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Message == nil {
+ m.Message = &raftpb.Message{}
+ }
+ if err := m.Message.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ProcessRaftMessageResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ProcessRaftMessageResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ProcessRaftMessageResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ResolveAddressRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ResolveAddressRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ResolveAddressRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RaftID", wireType)
+ }
+ m.RaftID = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RaftID |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ResolveAddressResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ResolveAddressResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ResolveAddressResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Addr", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Addr = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *InternalRaftRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: InternalRaftRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: InternalRaftRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ m.ID = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ID |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Action", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Action = append(m.Action, StoreAction{})
+ if err := m.Action[len(m.Action)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *StoreAction) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: StoreAction: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: StoreAction: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Action", wireType)
+ }
+ m.Action = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Action |= (StoreActionKind(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Node", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Node{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &StoreAction_Node{v}
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Service", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Service{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &StoreAction_Service{v}
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Task", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Task{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &StoreAction_Task{v}
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Network", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Network{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &StoreAction_Network{v}
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Cluster", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Cluster{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &StoreAction_Cluster{v}
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Secret", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Secret{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &StoreAction_Secret{v}
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Resource{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &StoreAction_Resource{v}
+ iNdEx = postIndex
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Extension", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Extension{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &StoreAction_Extension{v}
+ iNdEx = postIndex
+ case 10:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthRaft
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Config{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &StoreAction_Config{v}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipRaft(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthRaft
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipRaft(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthRaft
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowRaft
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipRaft(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthRaft = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowRaft = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("raft.proto", fileDescriptorRaft) }
+
+var fileDescriptorRaft = []byte{
+ // 953 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x96, 0x4d, 0x6f, 0x1b, 0x45,
+ 0x18, 0xc7, 0x77, 0xd7, 0x5b, 0x27, 0x79, 0xdc, 0xbc, 0x68, 0x42, 0xc2, 0x76, 0x29, 0x8e, 0xbb,
+ 0x45, 0xc2, 0x2d, 0x64, 0x2d, 0x0c, 0x12, 0xa8, 0xd0, 0x43, 0xec, 0x58, 0xb2, 0x69, 0xeb, 0x54,
+ 0x9b, 0x04, 0x7a, 0x0b, 0xeb, 0xdd, 0x89, 0xbb, 0xd8, 0xde, 0x31, 0x33, 0x63, 0x07, 0x2e, 0xa8,
+ 0x47, 0x94, 0x2b, 0x07, 0x10, 0x52, 0x4f, 0x70, 0xee, 0x07, 0xe0, 0x03, 0xa0, 0x88, 0x13, 0x37,
+ 0x38, 0x45, 0xd4, 0x1f, 0x00, 0xbe, 0x02, 0x9a, 0xd9, 0x5d, 0x3b, 0x38, 0x6b, 0x37, 0x17, 0x7b,
+ 0x3c, 0xf3, 0xfb, 0x3f, 0xff, 0x79, 0xe6, 0xe5, 0x19, 0x03, 0x50, 0xf7, 0x98, 0xdb, 0x7d, 0x4a,
+ 0x38, 0x41, 0xc8, 0x27, 0x5e, 0x07, 0x53, 0x9b, 0x9d, 0xb8, 0xb4, 0xd7, 0x09, 0xb8, 0x3d, 0x7c,
+ 0xcf, 0x5c, 0x26, 0xad, 0x2f, 0xb1, 0xc7, 0x59, 0x84, 0x98, 0x39, 0xfe, 0x4d, 0x1f, 0x27, 0x3f,
+ 0xb6, 0xdb, 0x01, 0x7f, 0x3a, 0x68, 0xd9, 0x1e, 0xe9, 0x95, 0x3c, 0x42, 0x31, 0x61, 0x25, 0xcc,
+ 0x3d, 0xbf, 0x24, 0x42, 0xca, 0x8f, 0x7e, 0xab, 0x34, 0x09, 0x6f, 0xbe, 0xd6, 0x26, 0x6d, 0x22,
+ 0x9b, 0x25, 0xd1, 0x8a, 0x7b, 0xd7, 0xfb, 0xdd, 0x41, 0x3b, 0x08, 0x4b, 0xd1, 0x57, 0xd4, 0x69,
+ 0xbd, 0x50, 0x01, 0x1c, 0xf7, 0x98, 0x3f, 0xc2, 0xbd, 0x16, 0xa6, 0xe8, 0x36, 0x2c, 0x88, 0x38,
+ 0x47, 0x81, 0x6f, 0xa8, 0x05, 0xb5, 0xa8, 0x57, 0x60, 0x74, 0xbe, 0x95, 0x15, 0x40, 0x63, 0xd7,
+ 0xc9, 0x8a, 0xa1, 0x86, 0x2f, 0xa0, 0x90, 0xf8, 0x58, 0x40, 0x5a, 0x41, 0x2d, 0x2e, 0x45, 0x50,
+ 0x93, 0xf8, 0x58, 0x40, 0x62, 0xa8, 0xe1, 0x23, 0x04, 0xba, 0xeb, 0xfb, 0xd4, 0xc8, 0x08, 0xc2,
+ 0x91, 0x6d, 0x54, 0x81, 0x2c, 0xe3, 0x2e, 0x1f, 0x30, 0x43, 0x2f, 0xa8, 0xc5, 0x5c, 0xf9, 0x2d,
+ 0xfb, 0xf2, 0x3a, 0xd8, 0x93, 0xd9, 0xec, 0x4b, 0xb6, 0xa2, 0x9f, 0x9d, 0x6f, 0x29, 0x4e, 0xac,
+ 0xb4, 0x6e, 0x41, 0xee, 0x53, 0x12, 0x84, 0x0e, 0xfe, 0x6a, 0x80, 0x19, 0x1f, 0xdb, 0xa8, 0x13,
+ 0x1b, 0xeb, 0x27, 0x15, 0xae, 0x47, 0x0c, 0xeb, 0x93, 0x90, 0xe1, 0xab, 0x65, 0xf5, 0x11, 0x2c,
+ 0xf4, 0xa4, 0x2d, 0x33, 0xb4, 0x42, 0xa6, 0x98, 0x2b, 0xe7, 0xe7, 0xcf, 0xce, 0x49, 0x70, 0xf4,
+ 0x0e, 0xac, 0x52, 0xdc, 0x23, 0x43, 0xec, 0x1f, 0x25, 0x11, 0x32, 0x85, 0x4c, 0x51, 0xaf, 0x68,
+ 0x6b, 0x8a, 0xb3, 0x12, 0x0f, 0x45, 0x22, 0x66, 0x55, 0xe0, 0xfa, 0x43, 0xec, 0x0e, 0x71, 0x92,
+ 0x40, 0x19, 0x74, 0xb1, 0x62, 0x72, 0x62, 0xaf, 0xf6, 0x94, 0xac, 0xb5, 0x0a, 0xcb, 0x71, 0x8c,
+ 0x28, 0x41, 0xeb, 0x21, 0xdc, 0x78, 0x4c, 0x89, 0x87, 0x19, 0x8b, 0x58, 0xc6, 0xdc, 0xf6, 0xd8,
+ 0xe1, 0x8e, 0x48, 0x4c, 0xf6, 0xc4, 0x26, 0xab, 0x76, 0x74, 0x64, 0xec, 0x04, 0x4c, 0xc6, 0xef,
+ 0xe9, 0xcf, 0x7e, 0xb0, 0x14, 0xeb, 0x26, 0x98, 0x69, 0xd1, 0x62, 0xaf, 0x4f, 0x60, 0xc3, 0xc1,
+ 0x8c, 0x74, 0x87, 0x78, 0xc7, 0xf7, 0xa9, 0x80, 0x62, 0x9f, 0xab, 0xac, 0xb2, 0xf5, 0x2e, 0x6c,
+ 0x4e, 0xab, 0xe3, 0x4d, 0x4a, 0xdb, 0xc9, 0x2e, 0xac, 0x37, 0x42, 0x8e, 0x69, 0xe8, 0x76, 0x45,
+ 0x9c, 0xc4, 0x69, 0x13, 0xb4, 0xb1, 0x49, 0x76, 0x74, 0xbe, 0xa5, 0x35, 0x76, 0x1d, 0x2d, 0xf0,
+ 0xd1, 0x7d, 0xc8, 0xba, 0x1e, 0x0f, 0x48, 0x18, 0xef, 0xe0, 0x56, 0xda, 0x6a, 0xee, 0x73, 0x42,
+ 0xf1, 0x8e, 0xc4, 0x92, 0xa3, 0x15, 0x89, 0xac, 0xdf, 0x74, 0xc8, 0x5d, 0x18, 0x45, 0x1f, 0x8f,
+ 0xc3, 0x09, 0xab, 0x95, 0xf2, 0xed, 0x57, 0x84, 0x7b, 0x10, 0x84, 0x7e, 0x12, 0x0c, 0xd9, 0xf1,
+ 0xbe, 0x6a, 0x72, 0xc9, 0x8d, 0x34, 0xa9, 0xb8, 0x31, 0x75, 0x25, 0xda, 0x53, 0xf4, 0x21, 0x2c,
+ 0x30, 0x4c, 0x87, 0x81, 0x87, 0xe5, 0x95, 0xc9, 0x95, 0xdf, 0x48, 0x75, 0x8b, 0x90, 0xba, 0xe2,
+ 0x24, 0xb4, 0x30, 0xe2, 0x2e, 0xeb, 0xc4, 0x57, 0x2a, 0xd5, 0xe8, 0xc0, 0x65, 0x1d, 0x61, 0x24,
+ 0x38, 0x61, 0x14, 0x62, 0x7e, 0x42, 0x68, 0xc7, 0xb8, 0x36, 0xdb, 0xa8, 0x19, 0x21, 0xc2, 0x28,
+ 0xa6, 0x85, 0xd0, 0xeb, 0x0e, 0x18, 0xc7, 0xd4, 0xc8, 0xce, 0x16, 0x56, 0x23, 0x44, 0x08, 0x63,
+ 0x1a, 0x7d, 0x00, 0x59, 0x86, 0x3d, 0x8a, 0xb9, 0xb1, 0x20, 0x75, 0x66, 0x7a, 0x66, 0x82, 0xa8,
+ 0x8b, 0x8b, 0x2e, 0x5b, 0xe8, 0x1e, 0x2c, 0x52, 0xcc, 0xc8, 0x80, 0x7a, 0xd8, 0x58, 0x94, 0xba,
+ 0x9b, 0xa9, 0x97, 0x23, 0x66, 0xea, 0x8a, 0x33, 0xe6, 0xd1, 0x7d, 0x58, 0xc2, 0x5f, 0x73, 0x1c,
+ 0x32, 0xb1, 0x79, 0x4b, 0x52, 0xfc, 0x66, 0x9a, 0xb8, 0x96, 0x40, 0x75, 0xc5, 0x99, 0x28, 0xc4,
+ 0x84, 0x3d, 0x12, 0x1e, 0x07, 0x6d, 0x03, 0x66, 0x4f, 0xb8, 0x2a, 0x09, 0x31, 0xe1, 0x88, 0xad,
+ 0x2c, 0x42, 0x96, 0xbb, 0xb4, 0x8d, 0xf9, 0xdd, 0x7f, 0x55, 0x58, 0x9d, 0x3a, 0x17, 0xe8, 0x6d,
+ 0x58, 0x38, 0x6c, 0x3e, 0x68, 0xee, 0x7d, 0xde, 0x5c, 0x53, 0x4c, 0xf3, 0xf4, 0x79, 0x61, 0x73,
+ 0x8a, 0x38, 0x0c, 0x3b, 0x21, 0x39, 0x09, 0x51, 0x19, 0xd6, 0xf7, 0x0f, 0xf6, 0x9c, 0xda, 0xd1,
+ 0x4e, 0xf5, 0xa0, 0xb1, 0xd7, 0x3c, 0xaa, 0x3a, 0xb5, 0x9d, 0x83, 0xda, 0x9a, 0x6a, 0xde, 0x38,
+ 0x7d, 0x5e, 0xd8, 0x98, 0x12, 0x55, 0x29, 0x76, 0x39, 0xbe, 0xa4, 0x39, 0x7c, 0xbc, 0x2b, 0x34,
+ 0x5a, 0xaa, 0xe6, 0xb0, 0xef, 0xa7, 0x69, 0x9c, 0xda, 0xa3, 0xbd, 0xcf, 0x6a, 0x6b, 0x99, 0x54,
+ 0x8d, 0x23, 0x8b, 0x98, 0xf9, 0xfa, 0x77, 0x3f, 0xe7, 0x95, 0x5f, 0x7f, 0xc9, 0x4f, 0x67, 0x57,
+ 0xfe, 0x5e, 0x03, 0x5d, 0xdc, 0x50, 0x74, 0xaa, 0x02, 0xba, 0x5c, 0x3c, 0xd0, 0x76, 0xda, 0x0a,
+ 0xce, 0x2c, 0x59, 0xa6, 0x7d, 0x55, 0x3c, 0xae, 0x49, 0x1b, 0xbf, 0xbf, 0xf8, 0xe7, 0x47, 0x6d,
+ 0x15, 0x96, 0x25, 0xbf, 0xdd, 0x73, 0x43, 0xb7, 0x8d, 0x29, 0xfa, 0x16, 0x56, 0xfe, 0x5f, 0x6c,
+ 0xd0, 0x9d, 0x59, 0x47, 0xe8, 0x52, 0x39, 0x33, 0xef, 0x5e, 0x05, 0x9d, 0xeb, 0x5f, 0xfe, 0x53,
+ 0x85, 0x95, 0x49, 0xf1, 0x66, 0x4f, 0x83, 0x3e, 0xfa, 0x02, 0x74, 0xf1, 0x34, 0xa1, 0xd4, 0xd2,
+ 0x74, 0xe1, 0x61, 0x33, 0x0b, 0xb3, 0x81, 0xf9, 0x49, 0x7b, 0x70, 0x4d, 0x3e, 0x0e, 0x28, 0x35,
+ 0xc2, 0xc5, 0xb7, 0xc7, 0xbc, 0x35, 0x87, 0x98, 0x6b, 0x52, 0x31, 0xce, 0x5e, 0xe6, 0x95, 0xbf,
+ 0x5e, 0xe6, 0x95, 0x67, 0xa3, 0xbc, 0x7a, 0x36, 0xca, 0xab, 0x7f, 0x8c, 0xf2, 0xea, 0xdf, 0xa3,
+ 0xbc, 0xfa, 0x24, 0xf3, 0x44, 0x6f, 0x65, 0xe5, 0x7f, 0x8b, 0xf7, 0xff, 0x0b, 0x00, 0x00, 0xff,
+ 0xff, 0x9a, 0xef, 0x6e, 0xdb, 0xf3, 0x08, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/raft.proto b/vendor/github.com/docker/swarmkit/api/raft.proto
new file mode 100644
index 0000000..e464f3a
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/raft.proto
@@ -0,0 +1,132 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "objects.proto";
+import "types.proto";
+import "github.com/coreos/etcd/raft/raftpb/raft.proto";
+import weak "gogoproto/gogo.proto";
+import weak "plugin/plugin.proto";
+
+// Raft defines the RPC communication between raft nodes.
+service Raft {
+ // ProcessRaftMessage sends a raft message to be processed on a raft member, it is
+ // called from the RaftMember willing to send a message to its destination ('To' field)
+ rpc ProcessRaftMessage(ProcessRaftMessageRequest) returns (ProcessRaftMessageResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+
+ // ResolveAddress returns the address where the node with the given ID can be reached.
+ rpc ResolveAddress(ResolveAddressRequest) returns (ResolveAddressResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+}
+
+// RaftMembership defines RPCs for adding and removing members from the
+// cluster. These RPCs must always run on the leader, so they are in a separate
+// service to support the raft proxy.
+service RaftMembership {
+ // Join adds a RaftMember to the raft cluster.
+ rpc Join(JoinRequest) returns (JoinResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+
+ // Leave removes a RaftMember from the raft cluster.
+ rpc Leave(LeaveRequest) returns (LeaveResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+}
+
+message RaftMember {
+ // RaftID specifies the internal ID used by the manager in a raft context, it can never be modified
+ // and is used only for information purposes
+ uint64 raft_id = 1;
+
+ // NodeID is the node's ID.
+ string node_id = 2;
+
+ // Addr specifies the address of the member
+ string addr = 3;
+
+ // Status provides the current status of the manager from the perspective of another manager.
+ RaftMemberStatus status = 4 [(gogoproto.nullable) = false];
+}
+
+message JoinRequest {
+ // Addr specifies the address of the member
+ string addr = 1;
+}
+
+message JoinResponse {
+ // RaftID is the ID assigned to the new member.
+ uint64 raft_id = 1;
+
+ // Members is the membership set of the cluster.
+ repeated RaftMember members = 2;
+
+ // RemovedMembers is a list of members that have been removed from
+ // the cluster, so the new node can avoid communicating with them.
+ repeated uint64 removed_members = 3 [packed=false];
+}
+
+message LeaveRequest {
+ RaftMember node = 1;
+}
+
+message LeaveResponse {}
+
+message ProcessRaftMessageRequest {
+ option (docker.protobuf.plugin.deepcopy) = false;
+ raftpb.Message message = 1;
+}
+
+message ProcessRaftMessageResponse {}
+
+message ResolveAddressRequest {
+ // raft_id is the ID to resolve to an address.
+ uint64 raft_id = 1;
+}
+
+message ResolveAddressResponse {
+ // Addr specifies the address of the member
+ string addr = 1;
+}
+
+// Contains one of many protobuf encoded objects to replicate
+// over the raft backend with a request ID to track when the
+// action is effectively applied
+message InternalRaftRequest {
+ uint64 id = 1;
+
+ repeated StoreAction action = 2 [(gogoproto.nullable) = false];
+}
+
+// TODO(stevvooe): Storage actions may belong in another protobuf file. They
+// aren't necessarily first-class "types" in the cluster schema.
+
+// StoreActionKind defines the operation to take on the store for the target of
+// a storage action.
+enum StoreActionKind {
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "StoreActionKind";
+ UNKNOWN = 0 [(gogoproto.enumvalue_customname) = "StoreActionKindUnknown"]; // default value, invalid
+ STORE_ACTION_CREATE = 1 [(gogoproto.enumvalue_customname) = "StoreActionKindCreate"];
+ STORE_ACTION_UPDATE = 2 [(gogoproto.enumvalue_customname) = "StoreActionKindUpdate"];
+ STORE_ACTION_REMOVE = 3 [(gogoproto.enumvalue_customname) = "StoreActionKindRemove"];
+}
+
+// StoreAction defines a target and operation to apply on the storage system.
+message StoreAction {
+ StoreActionKind action = 1;
+ oneof target {
+ Node node = 2;
+ Service service = 3;
+ Task task = 4;
+ Network network = 5;
+ Cluster cluster = 6;
+ Secret secret = 7;
+ Resource resource = 8;
+ Extension extension = 9;
+ Config config = 10;
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/api/resource.pb.go b/vendor/github.com/docker/swarmkit/api/resource.pb.go
new file mode 100644
index 0000000..4afd800
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/resource.pb.go
@@ -0,0 +1,1091 @@
+// Code generated by protoc-gen-gogo.
+// source: resource.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+import _ "github.com/docker/swarmkit/protobuf/plugin"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+import raftselector "github.com/docker/swarmkit/manager/raftselector"
+import codes "google.golang.org/grpc/codes"
+import metadata "google.golang.org/grpc/metadata"
+import transport "google.golang.org/grpc/transport"
+import rafttime "time"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+type AttachNetworkRequest struct {
+ Config *NetworkAttachmentConfig `protobuf:"bytes,1,opt,name=config" json:"config,omitempty"`
+ ContainerID string `protobuf:"bytes,2,opt,name=container_id,json=containerId,proto3" json:"container_id,omitempty"`
+}
+
+func (m *AttachNetworkRequest) Reset() { *m = AttachNetworkRequest{} }
+func (*AttachNetworkRequest) ProtoMessage() {}
+func (*AttachNetworkRequest) Descriptor() ([]byte, []int) { return fileDescriptorResource, []int{0} }
+
+type AttachNetworkResponse struct {
+ AttachmentID string `protobuf:"bytes,1,opt,name=attachment_id,json=attachmentId,proto3" json:"attachment_id,omitempty"`
+}
+
+func (m *AttachNetworkResponse) Reset() { *m = AttachNetworkResponse{} }
+func (*AttachNetworkResponse) ProtoMessage() {}
+func (*AttachNetworkResponse) Descriptor() ([]byte, []int) { return fileDescriptorResource, []int{1} }
+
+type DetachNetworkRequest struct {
+ AttachmentID string `protobuf:"bytes,1,opt,name=attachment_id,json=attachmentId,proto3" json:"attachment_id,omitempty"`
+}
+
+func (m *DetachNetworkRequest) Reset() { *m = DetachNetworkRequest{} }
+func (*DetachNetworkRequest) ProtoMessage() {}
+func (*DetachNetworkRequest) Descriptor() ([]byte, []int) { return fileDescriptorResource, []int{2} }
+
+type DetachNetworkResponse struct {
+}
+
+func (m *DetachNetworkResponse) Reset() { *m = DetachNetworkResponse{} }
+func (*DetachNetworkResponse) ProtoMessage() {}
+func (*DetachNetworkResponse) Descriptor() ([]byte, []int) { return fileDescriptorResource, []int{3} }
+
+func init() {
+ proto.RegisterType((*AttachNetworkRequest)(nil), "docker.swarmkit.v1.AttachNetworkRequest")
+ proto.RegisterType((*AttachNetworkResponse)(nil), "docker.swarmkit.v1.AttachNetworkResponse")
+ proto.RegisterType((*DetachNetworkRequest)(nil), "docker.swarmkit.v1.DetachNetworkRequest")
+ proto.RegisterType((*DetachNetworkResponse)(nil), "docker.swarmkit.v1.DetachNetworkResponse")
+}
+
+type authenticatedWrapperResourceAllocatorServer struct {
+ local ResourceAllocatorServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperResourceAllocatorServer(local ResourceAllocatorServer, authorize func(context.Context, []string) error) ResourceAllocatorServer {
+ return &authenticatedWrapperResourceAllocatorServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperResourceAllocatorServer) AttachNetwork(ctx context.Context, r *AttachNetworkRequest) (*AttachNetworkResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-worker", "swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.AttachNetwork(ctx, r)
+}
+
+func (p *authenticatedWrapperResourceAllocatorServer) DetachNetwork(ctx context.Context, r *DetachNetworkRequest) (*DetachNetworkResponse, error) {
+
+ if err := p.authorize(ctx, []string{"swarm-worker", "swarm-manager"}); err != nil {
+ return nil, err
+ }
+ return p.local.DetachNetwork(ctx, r)
+}
+
+func (m *AttachNetworkRequest) Copy() *AttachNetworkRequest {
+ if m == nil {
+ return nil
+ }
+ o := &AttachNetworkRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *AttachNetworkRequest) CopyFrom(src interface{}) {
+
+ o := src.(*AttachNetworkRequest)
+ *m = *o
+ if o.Config != nil {
+ m.Config = &NetworkAttachmentConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Config, o.Config)
+ }
+}
+
+func (m *AttachNetworkResponse) Copy() *AttachNetworkResponse {
+ if m == nil {
+ return nil
+ }
+ o := &AttachNetworkResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *AttachNetworkResponse) CopyFrom(src interface{}) {
+
+ o := src.(*AttachNetworkResponse)
+ *m = *o
+}
+
+func (m *DetachNetworkRequest) Copy() *DetachNetworkRequest {
+ if m == nil {
+ return nil
+ }
+ o := &DetachNetworkRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *DetachNetworkRequest) CopyFrom(src interface{}) {
+
+ o := src.(*DetachNetworkRequest)
+ *m = *o
+}
+
+func (m *DetachNetworkResponse) Copy() *DetachNetworkResponse {
+ if m == nil {
+ return nil
+ }
+ o := &DetachNetworkResponse{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *DetachNetworkResponse) CopyFrom(src interface{}) {}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for ResourceAllocator service
+
+type ResourceAllocatorClient interface {
+ AttachNetwork(ctx context.Context, in *AttachNetworkRequest, opts ...grpc.CallOption) (*AttachNetworkResponse, error)
+ DetachNetwork(ctx context.Context, in *DetachNetworkRequest, opts ...grpc.CallOption) (*DetachNetworkResponse, error)
+}
+
+type resourceAllocatorClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewResourceAllocatorClient(cc *grpc.ClientConn) ResourceAllocatorClient {
+ return &resourceAllocatorClient{cc}
+}
+
+func (c *resourceAllocatorClient) AttachNetwork(ctx context.Context, in *AttachNetworkRequest, opts ...grpc.CallOption) (*AttachNetworkResponse, error) {
+ out := new(AttachNetworkResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.ResourceAllocator/AttachNetwork", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *resourceAllocatorClient) DetachNetwork(ctx context.Context, in *DetachNetworkRequest, opts ...grpc.CallOption) (*DetachNetworkResponse, error) {
+ out := new(DetachNetworkResponse)
+ err := grpc.Invoke(ctx, "/docker.swarmkit.v1.ResourceAllocator/DetachNetwork", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for ResourceAllocator service
+
+type ResourceAllocatorServer interface {
+ AttachNetwork(context.Context, *AttachNetworkRequest) (*AttachNetworkResponse, error)
+ DetachNetwork(context.Context, *DetachNetworkRequest) (*DetachNetworkResponse, error)
+}
+
+func RegisterResourceAllocatorServer(s *grpc.Server, srv ResourceAllocatorServer) {
+ s.RegisterService(&_ResourceAllocator_serviceDesc, srv)
+}
+
+func _ResourceAllocator_AttachNetwork_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(AttachNetworkRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ResourceAllocatorServer).AttachNetwork(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.ResourceAllocator/AttachNetwork",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ResourceAllocatorServer).AttachNetwork(ctx, req.(*AttachNetworkRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _ResourceAllocator_DetachNetwork_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(DetachNetworkRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ResourceAllocatorServer).DetachNetwork(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/docker.swarmkit.v1.ResourceAllocator/DetachNetwork",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ResourceAllocatorServer).DetachNetwork(ctx, req.(*DetachNetworkRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _ResourceAllocator_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.ResourceAllocator",
+ HandlerType: (*ResourceAllocatorServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "AttachNetwork",
+ Handler: _ResourceAllocator_AttachNetwork_Handler,
+ },
+ {
+ MethodName: "DetachNetwork",
+ Handler: _ResourceAllocator_DetachNetwork_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "resource.proto",
+}
+
+func (m *AttachNetworkRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *AttachNetworkRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Config != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintResource(dAtA, i, uint64(m.Config.Size()))
+ n1, err := m.Config.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ }
+ if len(m.ContainerID) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintResource(dAtA, i, uint64(len(m.ContainerID)))
+ i += copy(dAtA[i:], m.ContainerID)
+ }
+ return i, nil
+}
+
+func (m *AttachNetworkResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *AttachNetworkResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.AttachmentID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintResource(dAtA, i, uint64(len(m.AttachmentID)))
+ i += copy(dAtA[i:], m.AttachmentID)
+ }
+ return i, nil
+}
+
+func (m *DetachNetworkRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *DetachNetworkRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.AttachmentID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintResource(dAtA, i, uint64(len(m.AttachmentID)))
+ i += copy(dAtA[i:], m.AttachmentID)
+ }
+ return i, nil
+}
+
+func (m *DetachNetworkResponse) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *DetachNetworkResponse) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func encodeFixed64Resource(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Resource(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintResource(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+type raftProxyResourceAllocatorServer struct {
+ local ResourceAllocatorServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyResourceAllocatorServer(local ResourceAllocatorServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) ResourceAllocatorServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyResourceAllocatorServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyResourceAllocatorServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyResourceAllocatorServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+func (p *raftProxyResourceAllocatorServer) AttachNetwork(ctx context.Context, r *AttachNetworkRequest) (*AttachNetworkResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.AttachNetwork(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewResourceAllocatorClient(conn).AttachNetwork(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.AttachNetwork(ctx, r)
+ }
+ return nil, err
+ }
+ return NewResourceAllocatorClient(conn).AttachNetwork(modCtx, r)
+ }
+ return resp, err
+}
+
+func (p *raftProxyResourceAllocatorServer) DetachNetwork(ctx context.Context, r *DetachNetworkRequest) (*DetachNetworkResponse, error) {
+
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return nil, err
+ }
+ return p.local.DetachNetwork(ctx, r)
+ }
+ return nil, err
+ }
+ modCtx, err := p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := NewResourceAllocatorClient(conn).DetachNetwork(modCtx, r)
+ if err != nil {
+ if !strings.Contains(err.Error(), "is closing") && !strings.Contains(err.Error(), "the connection is unavailable") && !strings.Contains(err.Error(), "connection error") {
+ return resp, err
+ }
+ conn, err := p.pollNewLeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ return p.local.DetachNetwork(ctx, r)
+ }
+ return nil, err
+ }
+ return NewResourceAllocatorClient(conn).DetachNetwork(modCtx, r)
+ }
+ return resp, err
+}
+
+func (m *AttachNetworkRequest) Size() (n int) {
+ var l int
+ _ = l
+ if m.Config != nil {
+ l = m.Config.Size()
+ n += 1 + l + sovResource(uint64(l))
+ }
+ l = len(m.ContainerID)
+ if l > 0 {
+ n += 1 + l + sovResource(uint64(l))
+ }
+ return n
+}
+
+func (m *AttachNetworkResponse) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.AttachmentID)
+ if l > 0 {
+ n += 1 + l + sovResource(uint64(l))
+ }
+ return n
+}
+
+func (m *DetachNetworkRequest) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.AttachmentID)
+ if l > 0 {
+ n += 1 + l + sovResource(uint64(l))
+ }
+ return n
+}
+
+func (m *DetachNetworkResponse) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func sovResource(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozResource(x uint64) (n int) {
+ return sovResource(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *AttachNetworkRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&AttachNetworkRequest{`,
+ `Config:` + strings.Replace(fmt.Sprintf("%v", this.Config), "NetworkAttachmentConfig", "NetworkAttachmentConfig", 1) + `,`,
+ `ContainerID:` + fmt.Sprintf("%v", this.ContainerID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *AttachNetworkResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&AttachNetworkResponse{`,
+ `AttachmentID:` + fmt.Sprintf("%v", this.AttachmentID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *DetachNetworkRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&DetachNetworkRequest{`,
+ `AttachmentID:` + fmt.Sprintf("%v", this.AttachmentID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *DetachNetworkResponse) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&DetachNetworkResponse{`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringResource(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *AttachNetworkRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: AttachNetworkRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: AttachNetworkRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthResource
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Config == nil {
+ m.Config = &NetworkAttachmentConfig{}
+ }
+ if err := m.Config.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ContainerID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthResource
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ContainerID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipResource(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthResource
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *AttachNetworkResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: AttachNetworkResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: AttachNetworkResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field AttachmentID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthResource
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.AttachmentID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipResource(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthResource
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *DetachNetworkRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: DetachNetworkRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: DetachNetworkRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field AttachmentID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthResource
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.AttachmentID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipResource(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthResource
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *DetachNetworkResponse) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: DetachNetworkResponse: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: DetachNetworkResponse: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipResource(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthResource
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipResource(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthResource
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowResource
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipResource(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthResource = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowResource = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("resource.proto", fileDescriptorResource) }
+
+var fileDescriptorResource = []byte{
+ // 368 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2b, 0x4a, 0x2d, 0xce,
+ 0x2f, 0x2d, 0x4a, 0x4e, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x4a, 0xc9, 0x4f, 0xce,
+ 0x4e, 0x2d, 0xd2, 0x2b, 0x2e, 0x4f, 0x2c, 0xca, 0xcd, 0xce, 0x2c, 0xd1, 0x2b, 0x33, 0x94, 0xe2,
+ 0x2e, 0xa9, 0x2c, 0x48, 0x2d, 0x86, 0x28, 0x90, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x33, 0xf5,
+ 0x41, 0x2c, 0xa8, 0xa8, 0x70, 0x41, 0x4e, 0x69, 0x7a, 0x66, 0x9e, 0x3e, 0x84, 0x82, 0x08, 0x2a,
+ 0xf5, 0x33, 0x72, 0x89, 0x38, 0x96, 0x94, 0x24, 0x26, 0x67, 0xf8, 0xa5, 0x96, 0x94, 0xe7, 0x17,
+ 0x65, 0x07, 0xa5, 0x16, 0x96, 0xa6, 0x16, 0x97, 0x08, 0x39, 0x73, 0xb1, 0x25, 0xe7, 0xe7, 0xa5,
+ 0x65, 0xa6, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, 0x69, 0xeb, 0x61, 0xda, 0xaa, 0x07, 0xd5,
+ 0x03, 0x31, 0x20, 0x37, 0x35, 0xaf, 0xc4, 0x19, 0xac, 0x25, 0x08, 0xaa, 0x55, 0xc8, 0x88, 0x8b,
+ 0x27, 0x39, 0x3f, 0xaf, 0x24, 0x31, 0x33, 0x2f, 0xb5, 0x28, 0x3e, 0x33, 0x45, 0x82, 0x49, 0x81,
+ 0x51, 0x83, 0xd3, 0x89, 0xff, 0xd1, 0x3d, 0x79, 0x6e, 0x67, 0x98, 0xb8, 0xa7, 0x4b, 0x10, 0x37,
+ 0x5c, 0x91, 0x67, 0x8a, 0x92, 0x1f, 0x97, 0x28, 0x9a, 0x83, 0x8a, 0x0b, 0xf2, 0xf3, 0x8a, 0x53,
+ 0x85, 0x4c, 0xb9, 0x78, 0x13, 0xe1, 0x16, 0x81, 0x4c, 0x63, 0x04, 0x9b, 0x26, 0xf0, 0xe8, 0x9e,
+ 0x3c, 0x0f, 0xc2, 0x05, 0x9e, 0x2e, 0x41, 0x3c, 0x08, 0x65, 0x9e, 0x29, 0x4a, 0xbe, 0x5c, 0x22,
+ 0x2e, 0xa9, 0x58, 0x3c, 0x48, 0xa6, 0x71, 0xe2, 0x5c, 0xa2, 0x68, 0xc6, 0x41, 0x9c, 0x67, 0xb4,
+ 0x9a, 0x89, 0x4b, 0x30, 0x08, 0x1a, 0x51, 0x8e, 0x39, 0x39, 0xf9, 0xc9, 0x89, 0x25, 0xf9, 0x45,
+ 0x42, 0x9d, 0x8c, 0x5c, 0xbc, 0x28, 0xde, 0x11, 0xd2, 0xc0, 0x16, 0x90, 0xd8, 0xa2, 0x40, 0x4a,
+ 0x93, 0x08, 0x95, 0x10, 0xcb, 0x95, 0x94, 0x4f, 0xad, 0x7b, 0x37, 0x83, 0x49, 0x96, 0x8b, 0x07,
+ 0xac, 0x54, 0x17, 0x24, 0x97, 0x5a, 0xc4, 0xc5, 0x0b, 0xe1, 0xe5, 0x26, 0xe6, 0x25, 0xa6, 0xa7,
+ 0x42, 0xdc, 0x82, 0xe2, 0x76, 0xec, 0x6e, 0xc1, 0x16, 0x5a, 0xd8, 0xdd, 0x82, 0x35, 0x20, 0x88,
+ 0x72, 0x8b, 0x93, 0xc4, 0x89, 0x87, 0x72, 0x0c, 0x37, 0x1e, 0xca, 0x31, 0x34, 0x3c, 0x92, 0x63,
+ 0x3c, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x93, 0xd8, 0xc0,
+ 0x09, 0xd3, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x1c, 0x48, 0x12, 0x41, 0xf6, 0x02, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/resource.proto b/vendor/github.com/docker/swarmkit/api/resource.proto
new file mode 100644
index 0000000..92a8302
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/resource.proto
@@ -0,0 +1,34 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "types.proto";
+import "gogoproto/gogo.proto";
+import "plugin/plugin.proto";
+
+// Allocator is the API provided by a manager group for agents to control the allocation of certain entities.
+//
+// API methods on this service are used only by agent nodes.
+service ResourceAllocator {
+ rpc AttachNetwork(AttachNetworkRequest) returns (AttachNetworkResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-worker" roles: "swarm-manager" };
+ };
+ rpc DetachNetwork(DetachNetworkRequest) returns (DetachNetworkResponse) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-worker" roles: "swarm-manager" };
+ };
+}
+
+message AttachNetworkRequest {
+ NetworkAttachmentConfig config = 1;
+ string container_id = 2;
+}
+
+message AttachNetworkResponse {
+ string attachment_id = 1;
+}
+
+message DetachNetworkRequest {
+ string attachment_id = 1;
+}
+
+message DetachNetworkResponse {}
diff --git a/vendor/github.com/docker/swarmkit/api/snapshot.pb.go b/vendor/github.com/docker/swarmkit/api/snapshot.pb.go
new file mode 100644
index 0000000..928d1c7
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/snapshot.pb.go
@@ -0,0 +1,1342 @@
+// Code generated by protoc-gen-gogo.
+// source: snapshot.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// skipping weak import gogoproto "github.com/gogo/protobuf/gogoproto"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+type Snapshot_Version int32
+
+const (
+ // V0 is the initial version of the StoreSnapshot message.
+ Snapshot_V0 Snapshot_Version = 0
+)
+
+var Snapshot_Version_name = map[int32]string{
+ 0: "V0",
+}
+var Snapshot_Version_value = map[string]int32{
+ "V0": 0,
+}
+
+func (x Snapshot_Version) String() string {
+ return proto.EnumName(Snapshot_Version_name, int32(x))
+}
+func (Snapshot_Version) EnumDescriptor() ([]byte, []int) { return fileDescriptorSnapshot, []int{2, 0} }
+
+// StoreSnapshot is used to store snapshots of the store.
+type StoreSnapshot struct {
+ Nodes []*Node `protobuf:"bytes,1,rep,name=nodes" json:"nodes,omitempty"`
+ Services []*Service `protobuf:"bytes,2,rep,name=services" json:"services,omitempty"`
+ Networks []*Network `protobuf:"bytes,3,rep,name=networks" json:"networks,omitempty"`
+ Tasks []*Task `protobuf:"bytes,4,rep,name=tasks" json:"tasks,omitempty"`
+ Clusters []*Cluster `protobuf:"bytes,5,rep,name=clusters" json:"clusters,omitempty"`
+ Secrets []*Secret `protobuf:"bytes,6,rep,name=secrets" json:"secrets,omitempty"`
+ Resources []*Resource `protobuf:"bytes,7,rep,name=resources" json:"resources,omitempty"`
+ Extensions []*Extension `protobuf:"bytes,8,rep,name=extensions" json:"extensions,omitempty"`
+ Configs []*Config `protobuf:"bytes,9,rep,name=configs" json:"configs,omitempty"`
+}
+
+func (m *StoreSnapshot) Reset() { *m = StoreSnapshot{} }
+func (*StoreSnapshot) ProtoMessage() {}
+func (*StoreSnapshot) Descriptor() ([]byte, []int) { return fileDescriptorSnapshot, []int{0} }
+
+// ClusterSnapshot stores cluster membership information in snapshots.
+type ClusterSnapshot struct {
+ Members []*RaftMember `protobuf:"bytes,1,rep,name=members" json:"members,omitempty"`
+ Removed []uint64 `protobuf:"varint,2,rep,name=removed" json:"removed,omitempty"`
+}
+
+func (m *ClusterSnapshot) Reset() { *m = ClusterSnapshot{} }
+func (*ClusterSnapshot) ProtoMessage() {}
+func (*ClusterSnapshot) Descriptor() ([]byte, []int) { return fileDescriptorSnapshot, []int{1} }
+
+type Snapshot struct {
+ Version Snapshot_Version `protobuf:"varint,1,opt,name=version,proto3,enum=docker.swarmkit.v1.Snapshot_Version" json:"version,omitempty"`
+ Membership ClusterSnapshot `protobuf:"bytes,2,opt,name=membership" json:"membership"`
+ Store StoreSnapshot `protobuf:"bytes,3,opt,name=store" json:"store"`
+}
+
+func (m *Snapshot) Reset() { *m = Snapshot{} }
+func (*Snapshot) ProtoMessage() {}
+func (*Snapshot) Descriptor() ([]byte, []int) { return fileDescriptorSnapshot, []int{2} }
+
+func init() {
+ proto.RegisterType((*StoreSnapshot)(nil), "docker.swarmkit.v1.StoreSnapshot")
+ proto.RegisterType((*ClusterSnapshot)(nil), "docker.swarmkit.v1.ClusterSnapshot")
+ proto.RegisterType((*Snapshot)(nil), "docker.swarmkit.v1.Snapshot")
+ proto.RegisterEnum("docker.swarmkit.v1.Snapshot_Version", Snapshot_Version_name, Snapshot_Version_value)
+}
+
+func (m *StoreSnapshot) Copy() *StoreSnapshot {
+ if m == nil {
+ return nil
+ }
+ o := &StoreSnapshot{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *StoreSnapshot) CopyFrom(src interface{}) {
+
+ o := src.(*StoreSnapshot)
+ *m = *o
+ if o.Nodes != nil {
+ m.Nodes = make([]*Node, len(o.Nodes))
+ for i := range m.Nodes {
+ m.Nodes[i] = &Node{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Nodes[i], o.Nodes[i])
+ }
+ }
+
+ if o.Services != nil {
+ m.Services = make([]*Service, len(o.Services))
+ for i := range m.Services {
+ m.Services[i] = &Service{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Services[i], o.Services[i])
+ }
+ }
+
+ if o.Networks != nil {
+ m.Networks = make([]*Network, len(o.Networks))
+ for i := range m.Networks {
+ m.Networks[i] = &Network{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Networks[i], o.Networks[i])
+ }
+ }
+
+ if o.Tasks != nil {
+ m.Tasks = make([]*Task, len(o.Tasks))
+ for i := range m.Tasks {
+ m.Tasks[i] = &Task{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Tasks[i], o.Tasks[i])
+ }
+ }
+
+ if o.Clusters != nil {
+ m.Clusters = make([]*Cluster, len(o.Clusters))
+ for i := range m.Clusters {
+ m.Clusters[i] = &Cluster{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Clusters[i], o.Clusters[i])
+ }
+ }
+
+ if o.Secrets != nil {
+ m.Secrets = make([]*Secret, len(o.Secrets))
+ for i := range m.Secrets {
+ m.Secrets[i] = &Secret{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Secrets[i], o.Secrets[i])
+ }
+ }
+
+ if o.Resources != nil {
+ m.Resources = make([]*Resource, len(o.Resources))
+ for i := range m.Resources {
+ m.Resources[i] = &Resource{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Resources[i], o.Resources[i])
+ }
+ }
+
+ if o.Extensions != nil {
+ m.Extensions = make([]*Extension, len(o.Extensions))
+ for i := range m.Extensions {
+ m.Extensions[i] = &Extension{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Extensions[i], o.Extensions[i])
+ }
+ }
+
+ if o.Configs != nil {
+ m.Configs = make([]*Config, len(o.Configs))
+ for i := range m.Configs {
+ m.Configs[i] = &Config{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Configs[i], o.Configs[i])
+ }
+ }
+
+}
+
+func (m *ClusterSnapshot) Copy() *ClusterSnapshot {
+ if m == nil {
+ return nil
+ }
+ o := &ClusterSnapshot{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ClusterSnapshot) CopyFrom(src interface{}) {
+
+ o := src.(*ClusterSnapshot)
+ *m = *o
+ if o.Members != nil {
+ m.Members = make([]*RaftMember, len(o.Members))
+ for i := range m.Members {
+ m.Members[i] = &RaftMember{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Members[i], o.Members[i])
+ }
+ }
+
+ if o.Removed != nil {
+ m.Removed = make([]uint64, len(o.Removed))
+ copy(m.Removed, o.Removed)
+ }
+
+}
+
+func (m *Snapshot) Copy() *Snapshot {
+ if m == nil {
+ return nil
+ }
+ o := &Snapshot{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Snapshot) CopyFrom(src interface{}) {
+
+ o := src.(*Snapshot)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Membership, &o.Membership)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Store, &o.Store)
+}
+
+func (m *StoreSnapshot) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *StoreSnapshot) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Nodes) > 0 {
+ for _, msg := range m.Nodes {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Services) > 0 {
+ for _, msg := range m.Services {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Networks) > 0 {
+ for _, msg := range m.Networks {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Tasks) > 0 {
+ for _, msg := range m.Tasks {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Clusters) > 0 {
+ for _, msg := range m.Clusters {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Secrets) > 0 {
+ for _, msg := range m.Secrets {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Resources) > 0 {
+ for _, msg := range m.Resources {
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Extensions) > 0 {
+ for _, msg := range m.Extensions {
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Configs) > 0 {
+ for _, msg := range m.Configs {
+ dAtA[i] = 0x4a
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *ClusterSnapshot) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ClusterSnapshot) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Members) > 0 {
+ for _, msg := range m.Members {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Removed) > 0 {
+ for _, num := range m.Removed {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(num))
+ }
+ }
+ return i, nil
+}
+
+func (m *Snapshot) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Snapshot) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Version != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(m.Version))
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(m.Membership.Size()))
+ n1, err := m.Membership.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintSnapshot(dAtA, i, uint64(m.Store.Size()))
+ n2, err := m.Store.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ return i, nil
+}
+
+func encodeFixed64Snapshot(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Snapshot(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintSnapshot(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+func (m *StoreSnapshot) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Nodes) > 0 {
+ for _, e := range m.Nodes {
+ l = e.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ }
+ }
+ if len(m.Services) > 0 {
+ for _, e := range m.Services {
+ l = e.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ }
+ }
+ if len(m.Networks) > 0 {
+ for _, e := range m.Networks {
+ l = e.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ }
+ }
+ if len(m.Tasks) > 0 {
+ for _, e := range m.Tasks {
+ l = e.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ }
+ }
+ if len(m.Clusters) > 0 {
+ for _, e := range m.Clusters {
+ l = e.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ }
+ }
+ if len(m.Secrets) > 0 {
+ for _, e := range m.Secrets {
+ l = e.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ }
+ }
+ if len(m.Resources) > 0 {
+ for _, e := range m.Resources {
+ l = e.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ }
+ }
+ if len(m.Extensions) > 0 {
+ for _, e := range m.Extensions {
+ l = e.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ }
+ }
+ if len(m.Configs) > 0 {
+ for _, e := range m.Configs {
+ l = e.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *ClusterSnapshot) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Members) > 0 {
+ for _, e := range m.Members {
+ l = e.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ }
+ }
+ if len(m.Removed) > 0 {
+ for _, e := range m.Removed {
+ n += 1 + sovSnapshot(uint64(e))
+ }
+ }
+ return n
+}
+
+func (m *Snapshot) Size() (n int) {
+ var l int
+ _ = l
+ if m.Version != 0 {
+ n += 1 + sovSnapshot(uint64(m.Version))
+ }
+ l = m.Membership.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ l = m.Store.Size()
+ n += 1 + l + sovSnapshot(uint64(l))
+ return n
+}
+
+func sovSnapshot(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozSnapshot(x uint64) (n int) {
+ return sovSnapshot(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *StoreSnapshot) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreSnapshot{`,
+ `Nodes:` + strings.Replace(fmt.Sprintf("%v", this.Nodes), "Node", "Node", 1) + `,`,
+ `Services:` + strings.Replace(fmt.Sprintf("%v", this.Services), "Service", "Service", 1) + `,`,
+ `Networks:` + strings.Replace(fmt.Sprintf("%v", this.Networks), "Network", "Network", 1) + `,`,
+ `Tasks:` + strings.Replace(fmt.Sprintf("%v", this.Tasks), "Task", "Task", 1) + `,`,
+ `Clusters:` + strings.Replace(fmt.Sprintf("%v", this.Clusters), "Cluster", "Cluster", 1) + `,`,
+ `Secrets:` + strings.Replace(fmt.Sprintf("%v", this.Secrets), "Secret", "Secret", 1) + `,`,
+ `Resources:` + strings.Replace(fmt.Sprintf("%v", this.Resources), "Resource", "Resource", 1) + `,`,
+ `Extensions:` + strings.Replace(fmt.Sprintf("%v", this.Extensions), "Extension", "Extension", 1) + `,`,
+ `Configs:` + strings.Replace(fmt.Sprintf("%v", this.Configs), "Config", "Config", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ClusterSnapshot) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ClusterSnapshot{`,
+ `Members:` + strings.Replace(fmt.Sprintf("%v", this.Members), "RaftMember", "RaftMember", 1) + `,`,
+ `Removed:` + fmt.Sprintf("%v", this.Removed) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Snapshot) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Snapshot{`,
+ `Version:` + fmt.Sprintf("%v", this.Version) + `,`,
+ `Membership:` + strings.Replace(strings.Replace(this.Membership.String(), "ClusterSnapshot", "ClusterSnapshot", 1), `&`, ``, 1) + `,`,
+ `Store:` + strings.Replace(strings.Replace(this.Store.String(), "StoreSnapshot", "StoreSnapshot", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringSnapshot(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *StoreSnapshot) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: StoreSnapshot: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: StoreSnapshot: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Nodes", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Nodes = append(m.Nodes, &Node{})
+ if err := m.Nodes[len(m.Nodes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Services", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Services = append(m.Services, &Service{})
+ if err := m.Services[len(m.Services)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Networks", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Networks = append(m.Networks, &Network{})
+ if err := m.Networks[len(m.Networks)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Tasks", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Tasks = append(m.Tasks, &Task{})
+ if err := m.Tasks[len(m.Tasks)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Clusters", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Clusters = append(m.Clusters, &Cluster{})
+ if err := m.Clusters[len(m.Clusters)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Secrets", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Secrets = append(m.Secrets, &Secret{})
+ if err := m.Secrets[len(m.Secrets)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Resources", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Resources = append(m.Resources, &Resource{})
+ if err := m.Resources[len(m.Resources)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Extensions", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Extensions = append(m.Extensions, &Extension{})
+ if err := m.Extensions[len(m.Extensions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Configs", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Configs = append(m.Configs, &Config{})
+ if err := m.Configs[len(m.Configs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSnapshot(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ClusterSnapshot) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ClusterSnapshot: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ClusterSnapshot: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Members", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Members = append(m.Members, &RaftMember{})
+ if err := m.Members[len(m.Members)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType == 0 {
+ var v uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Removed = append(m.Removed, v)
+ } else if wireType == 2 {
+ var packedLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ packedLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if packedLen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + packedLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ for iNdEx < postIndex {
+ var v uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Removed = append(m.Removed, v)
+ }
+ } else {
+ return fmt.Errorf("proto: wrong wireType = %d for field Removed", wireType)
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSnapshot(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Snapshot) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Snapshot: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Snapshot: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType)
+ }
+ m.Version = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Version |= (Snapshot_Version(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Membership", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Membership.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Store", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Store.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSnapshot(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSnapshot
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipSnapshot(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthSnapshot
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSnapshot
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipSnapshot(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthSnapshot = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowSnapshot = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("snapshot.proto", fileDescriptorSnapshot) }
+
+var fileDescriptorSnapshot = []byte{
+ // 469 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x93, 0xbf, 0x6f, 0xd3, 0x40,
+ 0x14, 0xc7, 0x7d, 0xce, 0x0f, 0xa7, 0xaf, 0x6a, 0x29, 0x27, 0x86, 0x53, 0x28, 0x26, 0x04, 0x86,
+ 0x4c, 0x06, 0x02, 0x12, 0x08, 0xa9, 0x0c, 0xa9, 0x18, 0x18, 0xe8, 0x70, 0x41, 0x15, 0xab, 0xe3,
+ 0x5c, 0x52, 0x63, 0xe2, 0x8b, 0xee, 0x5d, 0x53, 0x46, 0xf8, 0xef, 0x32, 0x32, 0x32, 0x21, 0x92,
+ 0x85, 0x7f, 0x03, 0xdd, 0x9d, 0x6d, 0x22, 0xe1, 0x74, 0xb3, 0x4e, 0x9f, 0xcf, 0x7b, 0xdf, 0x3b,
+ 0xbf, 0x07, 0xc7, 0x98, 0xc7, 0x4b, 0xbc, 0x92, 0x3a, 0x5a, 0x2a, 0xa9, 0x25, 0xa5, 0x53, 0x99,
+ 0x64, 0x42, 0x45, 0x78, 0x13, 0xab, 0x45, 0x96, 0xea, 0x68, 0xf5, 0xbc, 0x7b, 0x24, 0x27, 0x9f,
+ 0x45, 0xa2, 0xd1, 0x21, 0x5d, 0x50, 0xf1, 0xac, 0xc0, 0xbb, 0xf7, 0xe6, 0x72, 0x2e, 0xed, 0xe7,
+ 0x53, 0xf3, 0xe5, 0x4e, 0xfb, 0xdf, 0x9b, 0x70, 0x34, 0xd6, 0x52, 0x89, 0x71, 0x51, 0x9c, 0x46,
+ 0xd0, 0xca, 0xe5, 0x54, 0x20, 0x23, 0xbd, 0xc6, 0xe0, 0x70, 0xc8, 0xa2, 0xff, 0xdb, 0x44, 0x17,
+ 0x72, 0x2a, 0xb8, 0xc3, 0xe8, 0x2b, 0xe8, 0xa0, 0x50, 0xab, 0x34, 0x11, 0xc8, 0x7c, 0xab, 0xdc,
+ 0xaf, 0x53, 0xc6, 0x8e, 0xe1, 0x15, 0x6c, 0xc4, 0x5c, 0xe8, 0x1b, 0xa9, 0x32, 0x64, 0x8d, 0xfd,
+ 0xe2, 0x85, 0x63, 0x78, 0x05, 0x9b, 0x84, 0x3a, 0xc6, 0x0c, 0x59, 0x73, 0x7f, 0xc2, 0x8f, 0x31,
+ 0x66, 0xdc, 0x61, 0xa6, 0x51, 0xf2, 0xe5, 0x1a, 0xb5, 0x50, 0xc8, 0x5a, 0xfb, 0x1b, 0x9d, 0x3b,
+ 0x86, 0x57, 0x30, 0x7d, 0x09, 0x01, 0x8a, 0x44, 0x09, 0x8d, 0xac, 0x6d, 0xbd, 0x6e, 0xfd, 0xcd,
+ 0x0c, 0xc2, 0x4b, 0x94, 0xbe, 0x81, 0x03, 0x25, 0x50, 0x5e, 0x2b, 0xf3, 0x22, 0x81, 0xf5, 0x4e,
+ 0xeb, 0x3c, 0x5e, 0x40, 0xfc, 0x1f, 0x4e, 0xcf, 0x00, 0xc4, 0x57, 0x2d, 0x72, 0x4c, 0x65, 0x8e,
+ 0xac, 0x63, 0xe5, 0x07, 0x75, 0xf2, 0xbb, 0x92, 0xe2, 0x3b, 0x82, 0x09, 0x9c, 0xc8, 0x7c, 0x96,
+ 0xce, 0x91, 0x1d, 0xec, 0x0f, 0x7c, 0x6e, 0x11, 0x5e, 0xa2, 0xfd, 0x14, 0xee, 0x14, 0x77, 0xaf,
+ 0x86, 0xe0, 0x35, 0x04, 0x0b, 0xb1, 0x98, 0x98, 0x17, 0x73, 0x63, 0x10, 0xd6, 0xde, 0x20, 0x9e,
+ 0xe9, 0x0f, 0x16, 0xe3, 0x25, 0x4e, 0x4f, 0x21, 0x50, 0x62, 0x21, 0x57, 0x62, 0x6a, 0xa7, 0xa1,
+ 0x39, 0xf2, 0x4f, 0x3c, 0x5e, 0x1e, 0xf5, 0xff, 0x10, 0xe8, 0x54, 0x4d, 0xde, 0x42, 0xb0, 0x12,
+ 0xca, 0x24, 0x67, 0xa4, 0x47, 0x06, 0xc7, 0xc3, 0x27, 0xb5, 0xcf, 0x5b, 0x4e, 0xfd, 0xa5, 0x63,
+ 0x79, 0x29, 0xd1, 0xf7, 0x00, 0x45, 0xd7, 0xab, 0x74, 0xc9, 0xfc, 0x1e, 0x19, 0x1c, 0x0e, 0x1f,
+ 0xdf, 0xf2, 0x67, 0xcb, 0x4a, 0xa3, 0xe6, 0xfa, 0xd7, 0x43, 0x8f, 0xef, 0xc8, 0xf4, 0x0c, 0x5a,
+ 0x68, 0xb6, 0x80, 0x35, 0x6c, 0x95, 0x47, 0xb5, 0x41, 0x76, 0xd7, 0xa4, 0xa8, 0xe1, 0xac, 0xfe,
+ 0x5d, 0x08, 0x8a, 0x74, 0xb4, 0x0d, 0xfe, 0xe5, 0xb3, 0x13, 0x6f, 0xc4, 0xd6, 0x9b, 0xd0, 0xfb,
+ 0xb9, 0x09, 0xbd, 0x6f, 0xdb, 0x90, 0xac, 0xb7, 0x21, 0xf9, 0xb1, 0x0d, 0xc9, 0xef, 0x6d, 0x48,
+ 0x3e, 0xf9, 0x93, 0xb6, 0xdd, 0xbd, 0x17, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x8d, 0x0f, 0xc4,
+ 0x6e, 0xd2, 0x03, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/snapshot.proto b/vendor/github.com/docker/swarmkit/api/snapshot.proto
new file mode 100644
index 0000000..713649c
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/snapshot.proto
@@ -0,0 +1,44 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "objects.proto";
+import "raft.proto";
+import weak "gogoproto/gogo.proto";
+
+// StoreSnapshot is used to store snapshots of the store.
+message StoreSnapshot {
+ // TODO(aaronl): The current method of assembling a StoreSnapshot
+ // structure and marshalling it is not optimal. It may be better to
+ // write out nodes, networks, tasks, etc. one at a time to an io.Writer
+ // using gogo-protobuf's io.DelimitedWriter. A new value of the version
+ // field could support this approach.
+
+ repeated Node nodes = 1;
+ repeated Service services = 2;
+ repeated Network networks = 3;
+ repeated Task tasks = 4;
+ repeated Cluster clusters = 5;
+ repeated Secret secrets = 6;
+ repeated Resource resources = 7;
+ repeated Extension extensions = 8;
+ repeated Config configs = 9;
+}
+
+// ClusterSnapshot stores cluster membership information in snapshots.
+message ClusterSnapshot {
+ repeated RaftMember members = 1;
+ repeated uint64 removed = 2 [packed=false];
+}
+
+message Snapshot {
+ enum Version {
+ // V0 is the initial version of the StoreSnapshot message.
+ V0 = 0;
+ }
+
+ Version version = 1;
+
+ ClusterSnapshot membership = 2 [(gogoproto.nullable) = false];
+ StoreSnapshot store = 3 [(gogoproto.nullable) = false];
+}
diff --git a/vendor/github.com/docker/swarmkit/api/specs.pb.go b/vendor/github.com/docker/swarmkit/api/specs.pb.go
new file mode 100644
index 0000000..8578cf3
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/specs.pb.go
@@ -0,0 +1,6277 @@
+// Code generated by protoc-gen-gogo.
+// source: specs.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+import google_protobuf1 "github.com/gogo/protobuf/types"
+import google_protobuf3 "github.com/gogo/protobuf/types"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import strings "strings"
+import reflect "reflect"
+import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+type NodeSpec_Membership int32
+
+const (
+ NodeMembershipPending NodeSpec_Membership = 0
+ NodeMembershipAccepted NodeSpec_Membership = 1
+)
+
+var NodeSpec_Membership_name = map[int32]string{
+ 0: "PENDING",
+ 1: "ACCEPTED",
+}
+var NodeSpec_Membership_value = map[string]int32{
+ "PENDING": 0,
+ "ACCEPTED": 1,
+}
+
+func (x NodeSpec_Membership) String() string {
+ return proto.EnumName(NodeSpec_Membership_name, int32(x))
+}
+func (NodeSpec_Membership) EnumDescriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{0, 0} }
+
+type NodeSpec_Availability int32
+
+const (
+ // Active nodes.
+ NodeAvailabilityActive NodeSpec_Availability = 0
+ // Paused nodes won't be considered by the scheduler, preventing any
+ // further task to run on them.
+ NodeAvailabilityPause NodeSpec_Availability = 1
+ // Drained nodes are paused and any task already running on them will
+ // be evicted.
+ NodeAvailabilityDrain NodeSpec_Availability = 2
+)
+
+var NodeSpec_Availability_name = map[int32]string{
+ 0: "ACTIVE",
+ 1: "PAUSE",
+ 2: "DRAIN",
+}
+var NodeSpec_Availability_value = map[string]int32{
+ "ACTIVE": 0,
+ "PAUSE": 1,
+ "DRAIN": 2,
+}
+
+func (x NodeSpec_Availability) String() string {
+ return proto.EnumName(NodeSpec_Availability_name, int32(x))
+}
+func (NodeSpec_Availability) EnumDescriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{0, 1} }
+
+// ResolutionMode specifies the mode of resolution to use for
+// internal loadbalancing between tasks which are all within
+// the cluster. This is sometimes calls east-west data path.
+type EndpointSpec_ResolutionMode int32
+
+const (
+ // VIP resolution mode specifies that the
+ // service resolves to a logical IP and the requests
+ // are sent to that logical IP. Packets hitting that
+ // logical IP are load balanced to a chosen backend.
+ ResolutionModeVirtualIP EndpointSpec_ResolutionMode = 0
+ // DNSRR resolution mode specifies that the
+ // service directly gets resolved to one of the
+ // backend IP and the client directly initiates a
+ // request towards the actual backend. This requires
+ // that the client does not cache the DNS responses
+ // when the DNS response TTL is 0.
+ ResolutionModeDNSRoundRobin EndpointSpec_ResolutionMode = 1
+)
+
+var EndpointSpec_ResolutionMode_name = map[int32]string{
+ 0: "VIP",
+ 1: "DNSRR",
+}
+var EndpointSpec_ResolutionMode_value = map[string]int32{
+ "VIP": 0,
+ "DNSRR": 1,
+}
+
+func (x EndpointSpec_ResolutionMode) String() string {
+ return proto.EnumName(EndpointSpec_ResolutionMode_name, int32(x))
+}
+func (EndpointSpec_ResolutionMode) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorSpecs, []int{8, 0}
+}
+
+type NodeSpec struct {
+ Annotations Annotations `protobuf:"bytes,1,opt,name=annotations" json:"annotations"`
+ // DesiredRole defines the role the node should have.
+ DesiredRole NodeRole `protobuf:"varint,2,opt,name=desired_role,json=desiredRole,proto3,enum=docker.swarmkit.v1.NodeRole" json:"desired_role,omitempty"`
+ // Membership controls the admission of the node into the cluster.
+ Membership NodeSpec_Membership `protobuf:"varint,3,opt,name=membership,proto3,enum=docker.swarmkit.v1.NodeSpec_Membership" json:"membership,omitempty"`
+ // Availability allows a user to control the current scheduling status of a
+ // node.
+ Availability NodeSpec_Availability `protobuf:"varint,4,opt,name=availability,proto3,enum=docker.swarmkit.v1.NodeSpec_Availability" json:"availability,omitempty"`
+}
+
+func (m *NodeSpec) Reset() { *m = NodeSpec{} }
+func (*NodeSpec) ProtoMessage() {}
+func (*NodeSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{0} }
+
+// ServiceSpec defines the properties of a service.
+//
+// A service instructs the cluster in orchestrating repeated instances of a
+// template, implemented as tasks. Based on the number of instances, scheduling
+// strategy and restart policy, a number of application-level behaviors can be
+// defined.
+type ServiceSpec struct {
+ Annotations Annotations `protobuf:"bytes,1,opt,name=annotations" json:"annotations"`
+ // Task defines the task template this service will spawn.
+ Task TaskSpec `protobuf:"bytes,2,opt,name=task" json:"task"`
+ // Types that are valid to be assigned to Mode:
+ // *ServiceSpec_Replicated
+ // *ServiceSpec_Global
+ Mode isServiceSpec_Mode `protobuf_oneof:"mode"`
+ // Update contains settings which affect updates.
+ Update *UpdateConfig `protobuf:"bytes,6,opt,name=update" json:"update,omitempty"`
+ // Rollback contains settings which affect rollbacks of updates.
+ Rollback *UpdateConfig `protobuf:"bytes,9,opt,name=rollback" json:"rollback,omitempty"`
+ // ServiceSpec.Networks has been deprecated and is replaced by
+ // Networks field in Task (TaskSpec.Networks).
+ // This field (ServiceSpec.Networks) is kept for compatibility.
+ // In case TaskSpec.Networks does not exist, ServiceSpec.Networks
+ // is still honored if it exists.
+ Networks []*NetworkAttachmentConfig `protobuf:"bytes,7,rep,name=networks" json:"networks,omitempty"`
+ // Service endpoint specifies the user provided configuration
+ // to properly discover and load balance a service.
+ Endpoint *EndpointSpec `protobuf:"bytes,8,opt,name=endpoint" json:"endpoint,omitempty"`
+}
+
+func (m *ServiceSpec) Reset() { *m = ServiceSpec{} }
+func (*ServiceSpec) ProtoMessage() {}
+func (*ServiceSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{1} }
+
+type isServiceSpec_Mode interface {
+ isServiceSpec_Mode()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type ServiceSpec_Replicated struct {
+ Replicated *ReplicatedService `protobuf:"bytes,3,opt,name=replicated,oneof"`
+}
+type ServiceSpec_Global struct {
+ Global *GlobalService `protobuf:"bytes,4,opt,name=global,oneof"`
+}
+
+func (*ServiceSpec_Replicated) isServiceSpec_Mode() {}
+func (*ServiceSpec_Global) isServiceSpec_Mode() {}
+
+func (m *ServiceSpec) GetMode() isServiceSpec_Mode {
+ if m != nil {
+ return m.Mode
+ }
+ return nil
+}
+
+func (m *ServiceSpec) GetReplicated() *ReplicatedService {
+ if x, ok := m.GetMode().(*ServiceSpec_Replicated); ok {
+ return x.Replicated
+ }
+ return nil
+}
+
+func (m *ServiceSpec) GetGlobal() *GlobalService {
+ if x, ok := m.GetMode().(*ServiceSpec_Global); ok {
+ return x.Global
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*ServiceSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _ServiceSpec_OneofMarshaler, _ServiceSpec_OneofUnmarshaler, _ServiceSpec_OneofSizer, []interface{}{
+ (*ServiceSpec_Replicated)(nil),
+ (*ServiceSpec_Global)(nil),
+ }
+}
+
+func _ServiceSpec_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*ServiceSpec)
+ // mode
+ switch x := m.Mode.(type) {
+ case *ServiceSpec_Replicated:
+ _ = b.EncodeVarint(3<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Replicated); err != nil {
+ return err
+ }
+ case *ServiceSpec_Global:
+ _ = b.EncodeVarint(4<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Global); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("ServiceSpec.Mode has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _ServiceSpec_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*ServiceSpec)
+ switch tag {
+ case 3: // mode.replicated
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(ReplicatedService)
+ err := b.DecodeMessage(msg)
+ m.Mode = &ServiceSpec_Replicated{msg}
+ return true, err
+ case 4: // mode.global
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(GlobalService)
+ err := b.DecodeMessage(msg)
+ m.Mode = &ServiceSpec_Global{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _ServiceSpec_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*ServiceSpec)
+ // mode
+ switch x := m.Mode.(type) {
+ case *ServiceSpec_Replicated:
+ s := proto.Size(x.Replicated)
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *ServiceSpec_Global:
+ s := proto.Size(x.Global)
+ n += proto.SizeVarint(4<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// ReplicatedService sets the reconciliation target to certain number of replicas.
+type ReplicatedService struct {
+ Replicas uint64 `protobuf:"varint,1,opt,name=replicas,proto3" json:"replicas,omitempty"`
+}
+
+func (m *ReplicatedService) Reset() { *m = ReplicatedService{} }
+func (*ReplicatedService) ProtoMessage() {}
+func (*ReplicatedService) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{2} }
+
+// GlobalService represents global service.
+type GlobalService struct {
+}
+
+func (m *GlobalService) Reset() { *m = GlobalService{} }
+func (*GlobalService) ProtoMessage() {}
+func (*GlobalService) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{3} }
+
+type TaskSpec struct {
+ // Types that are valid to be assigned to Runtime:
+ // *TaskSpec_Attachment
+ // *TaskSpec_Container
+ // *TaskSpec_Generic
+ Runtime isTaskSpec_Runtime `protobuf_oneof:"runtime"`
+ // Resource requirements for the container.
+ Resources *ResourceRequirements `protobuf:"bytes,2,opt,name=resources" json:"resources,omitempty"`
+ // RestartPolicy specifies what to do when a task fails or finishes.
+ Restart *RestartPolicy `protobuf:"bytes,4,opt,name=restart" json:"restart,omitempty"`
+ // Placement specifies node selection constraints
+ Placement *Placement `protobuf:"bytes,5,opt,name=placement" json:"placement,omitempty"`
+ // LogDriver specifies the log driver to use for the task. Any runtime will
+ // direct logs into the specified driver for the duration of the task.
+ LogDriver *Driver `protobuf:"bytes,6,opt,name=log_driver,json=logDriver" json:"log_driver,omitempty"`
+ // Networks specifies the list of network attachment
+ // configurations (which specify the network and per-network
+ // aliases) that this task spec is bound to.
+ Networks []*NetworkAttachmentConfig `protobuf:"bytes,7,rep,name=networks" json:"networks,omitempty"`
+ // ForceUpdate is a counter that triggers an update even if no relevant
+ // parameters have been changed. We do this to allow forced restarts
+ // using the same reconciliation-based mechanism that performs rolling
+ // updates.
+ ForceUpdate uint64 `protobuf:"varint,9,opt,name=force_update,json=forceUpdate,proto3" json:"force_update,omitempty"`
+}
+
+func (m *TaskSpec) Reset() { *m = TaskSpec{} }
+func (*TaskSpec) ProtoMessage() {}
+func (*TaskSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{4} }
+
+type isTaskSpec_Runtime interface {
+ isTaskSpec_Runtime()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type TaskSpec_Attachment struct {
+ Attachment *NetworkAttachmentSpec `protobuf:"bytes,8,opt,name=attachment,oneof"`
+}
+type TaskSpec_Container struct {
+ Container *ContainerSpec `protobuf:"bytes,1,opt,name=container,oneof"`
+}
+type TaskSpec_Generic struct {
+ Generic *GenericRuntimeSpec `protobuf:"bytes,10,opt,name=generic,oneof"`
+}
+
+func (*TaskSpec_Attachment) isTaskSpec_Runtime() {}
+func (*TaskSpec_Container) isTaskSpec_Runtime() {}
+func (*TaskSpec_Generic) isTaskSpec_Runtime() {}
+
+func (m *TaskSpec) GetRuntime() isTaskSpec_Runtime {
+ if m != nil {
+ return m.Runtime
+ }
+ return nil
+}
+
+func (m *TaskSpec) GetAttachment() *NetworkAttachmentSpec {
+ if x, ok := m.GetRuntime().(*TaskSpec_Attachment); ok {
+ return x.Attachment
+ }
+ return nil
+}
+
+func (m *TaskSpec) GetContainer() *ContainerSpec {
+ if x, ok := m.GetRuntime().(*TaskSpec_Container); ok {
+ return x.Container
+ }
+ return nil
+}
+
+func (m *TaskSpec) GetGeneric() *GenericRuntimeSpec {
+ if x, ok := m.GetRuntime().(*TaskSpec_Generic); ok {
+ return x.Generic
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*TaskSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _TaskSpec_OneofMarshaler, _TaskSpec_OneofUnmarshaler, _TaskSpec_OneofSizer, []interface{}{
+ (*TaskSpec_Attachment)(nil),
+ (*TaskSpec_Container)(nil),
+ (*TaskSpec_Generic)(nil),
+ }
+}
+
+func _TaskSpec_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*TaskSpec)
+ // runtime
+ switch x := m.Runtime.(type) {
+ case *TaskSpec_Attachment:
+ _ = b.EncodeVarint(8<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Attachment); err != nil {
+ return err
+ }
+ case *TaskSpec_Container:
+ _ = b.EncodeVarint(1<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Container); err != nil {
+ return err
+ }
+ case *TaskSpec_Generic:
+ _ = b.EncodeVarint(10<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Generic); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("TaskSpec.Runtime has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _TaskSpec_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*TaskSpec)
+ switch tag {
+ case 8: // runtime.attachment
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(NetworkAttachmentSpec)
+ err := b.DecodeMessage(msg)
+ m.Runtime = &TaskSpec_Attachment{msg}
+ return true, err
+ case 1: // runtime.container
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(ContainerSpec)
+ err := b.DecodeMessage(msg)
+ m.Runtime = &TaskSpec_Container{msg}
+ return true, err
+ case 10: // runtime.generic
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(GenericRuntimeSpec)
+ err := b.DecodeMessage(msg)
+ m.Runtime = &TaskSpec_Generic{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _TaskSpec_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*TaskSpec)
+ // runtime
+ switch x := m.Runtime.(type) {
+ case *TaskSpec_Attachment:
+ s := proto.Size(x.Attachment)
+ n += proto.SizeVarint(8<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *TaskSpec_Container:
+ s := proto.Size(x.Container)
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *TaskSpec_Generic:
+ s := proto.Size(x.Generic)
+ n += proto.SizeVarint(10<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type GenericRuntimeSpec struct {
+ Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
+ Payload *google_protobuf3.Any `protobuf:"bytes,2,opt,name=payload" json:"payload,omitempty"`
+}
+
+func (m *GenericRuntimeSpec) Reset() { *m = GenericRuntimeSpec{} }
+func (*GenericRuntimeSpec) ProtoMessage() {}
+func (*GenericRuntimeSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{5} }
+
+// NetworkAttachmentSpec specifies runtime parameters required to attach
+// a container to a network.
+type NetworkAttachmentSpec struct {
+ // ContainerID specifies a unique ID of the container for which
+ // this attachment is for.
+ ContainerID string `protobuf:"bytes,1,opt,name=container_id,json=containerId,proto3" json:"container_id,omitempty"`
+}
+
+func (m *NetworkAttachmentSpec) Reset() { *m = NetworkAttachmentSpec{} }
+func (*NetworkAttachmentSpec) ProtoMessage() {}
+func (*NetworkAttachmentSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{6} }
+
+// Container specifies runtime parameters for a container.
+type ContainerSpec struct {
+ // image defines the image reference, as specified in the
+ // distribution/reference package. This may include a registry host, name,
+ // tag or digest.
+ //
+ // The field will be directly passed to the engine pulling. Well-behaved
+ // service definitions will used immutable references, either through tags
+ // that don't change or verifiable digests.
+ Image string `protobuf:"bytes,1,opt,name=image,proto3" json:"image,omitempty"`
+ // Labels defines labels to be added to the container at creation time. If
+ // collisions with system labels occur, these labels will be overridden.
+ //
+ // This field *must* remain compatible with the Labels field of
+ // Annotations.
+ Labels map[string]string `protobuf:"bytes,2,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ // Command to run the the container. The first element is a path to the
+ // executable and the following elements are treated as arguments.
+ //
+ // If command is empty, execution will fall back to the image's entrypoint.
+ //
+ // Command should only be used when overriding entrypoint.
+ Command []string `protobuf:"bytes,3,rep,name=command" json:"command,omitempty"`
+ // Args specifies arguments provided to the image's entrypoint.
+ //
+ // If Command and Args are provided, Args will be appended to Command.
+ Args []string `protobuf:"bytes,4,rep,name=args" json:"args,omitempty"`
+ // Hostname specifies the hostname that will be set on containers created by docker swarm.
+ // All containers for a given service will have the same hostname
+ Hostname string `protobuf:"bytes,14,opt,name=hostname,proto3" json:"hostname,omitempty"`
+ // Env specifies the environment variables for the container in NAME=VALUE
+ // format. These must be compliant with [IEEE Std
+ // 1003.1-2001](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html).
+ Env []string `protobuf:"bytes,5,rep,name=env" json:"env,omitempty"`
+ // Dir defines the working directory to set for the container process.
+ Dir string `protobuf:"bytes,6,opt,name=dir,proto3" json:"dir,omitempty"`
+ // User specifies the user that should be employed to run the container.
+ //
+ // Note that the primary group may be specified by appending the group name
+ // or id to the user name, separated by a `:`. This syntax is
+ // `<user>:<group>`.
+ User string `protobuf:"bytes,7,opt,name=user,proto3" json:"user,omitempty"`
+ // Groups specifies supplementary groups available to the user.
+ Groups []string `protobuf:"bytes,11,rep,name=groups" json:"groups,omitempty"`
+ // Privileges specifies security configuration/permissions.
+ Privileges *Privileges `protobuf:"bytes,22,opt,name=privileges" json:"privileges,omitempty"`
+ // TTY declares that a TTY should be attached to the standard streams,
+ // including stdin if it is still open.
+ TTY bool `protobuf:"varint,13,opt,name=tty,proto3" json:"tty,omitempty"`
+ // OpenStdin declares that the standard input (stdin) should be open.
+ OpenStdin bool `protobuf:"varint,18,opt,name=open_stdin,json=openStdin,proto3" json:"open_stdin,omitempty"`
+ // ReadOnly declares that the container root filesystem is read-only.
+ // This only impacts the root filesystem, not additional mounts (including
+ // tmpfs). For additional mounts that are not part of the initial rootfs,
+ // they will be decided by the modes passed in the mount definition.
+ ReadOnly bool `protobuf:"varint,19,opt,name=read_only,json=readOnly,proto3" json:"read_only,omitempty"`
+ // StopSignal defines the signal to stop the container.
+ StopSignal string `protobuf:"bytes,20,opt,name=stop_signal,json=stopSignal,proto3" json:"stop_signal,omitempty"`
+ Mounts []Mount `protobuf:"bytes,8,rep,name=mounts" json:"mounts"`
+ // StopGracePeriod the grace period for stopping the container before
+ // forcefully killing the container.
+ // Note: Can't use stdduration here because this needs to be nullable.
+ StopGracePeriod *google_protobuf1.Duration `protobuf:"bytes,9,opt,name=stop_grace_period,json=stopGracePeriod" json:"stop_grace_period,omitempty"`
+ // PullOptions parameterize the behavior of image pulls.
+ PullOptions *ContainerSpec_PullOptions `protobuf:"bytes,10,opt,name=pull_options,json=pullOptions" json:"pull_options,omitempty"`
+ // SecretReference contains references to zero or more secrets that
+ // will be exposed to the container.
+ Secrets []*SecretReference `protobuf:"bytes,12,rep,name=secrets" json:"secrets,omitempty"`
+ // ConfigReference contains references to zero or more configs that
+ // will be exposed to the container.
+ Configs []*ConfigReference `protobuf:"bytes,21,rep,name=configs" json:"configs,omitempty"`
+ // Hosts allow additional entries to be specified in /etc/hosts
+ // that associates IP addresses with hostnames.
+ // Detailed documentation is available in:
+ // http://man7.org/linux/man-pages/man5/hosts.5.html
+ // IP_address canonical_hostname [aliases...]
+ //
+ // The format of the Hosts in swarmkit follows the same as
+ // above.
+ // This is different from `docker run --add-host <hostname>:<ip>`
+ // where format is `<hostname>:<ip>`
+ Hosts []string `protobuf:"bytes,17,rep,name=hosts" json:"hosts,omitempty"`
+ // DNSConfig allows one to specify DNS related configuration in resolv.conf
+ DNSConfig *ContainerSpec_DNSConfig `protobuf:"bytes,15,opt,name=dns_config,json=dnsConfig" json:"dns_config,omitempty"`
+ // Healthcheck describes how to check the container is healthy. If the
+ // container is considered unhealthy, it will be destroyed, its creating
+ // task will exit and a new task will be rescheduled elsewhere. A container
+ // is considered unhealthy after `Retries` number of consecutive failures.
+ Healthcheck *HealthConfig `protobuf:"bytes,16,opt,name=healthcheck" json:"healthcheck,omitempty"`
+}
+
+func (m *ContainerSpec) Reset() { *m = ContainerSpec{} }
+func (*ContainerSpec) ProtoMessage() {}
+func (*ContainerSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{7} }
+
+// PullOptions allows one to parameterize an image pull.
+type ContainerSpec_PullOptions struct {
+ // RegistryAuth is the registry auth token obtained from the client, required
+ // to pull private images. This is the unmodified JSON used as part of
+ // the `X-Registry-Auth` header.
+ // TODO(nishanttotla): This field will later be deprecated
+ RegistryAuth string `protobuf:"bytes,64,opt,name=registry_auth,json=registryAuth,proto3" json:"registry_auth,omitempty"`
+}
+
+func (m *ContainerSpec_PullOptions) Reset() { *m = ContainerSpec_PullOptions{} }
+func (*ContainerSpec_PullOptions) ProtoMessage() {}
+func (*ContainerSpec_PullOptions) Descriptor() ([]byte, []int) {
+ return fileDescriptorSpecs, []int{7, 1}
+}
+
+// DNSConfig specifies DNS related configurations in resolver configuration file (resolv.conf)
+// Detailed documentation is available in:
+// http://man7.org/linux/man-pages/man5/resolv.conf.5.html
+// TODO: domain is not supported yet
+type ContainerSpec_DNSConfig struct {
+ // Nameservers specifies the IP addresses of the name servers
+ Nameservers []string `protobuf:"bytes,1,rep,name=nameservers" json:"nameservers,omitempty"`
+ // Search specifies the search list for host-name lookup
+ Search []string `protobuf:"bytes,2,rep,name=search" json:"search,omitempty"`
+ // Options allows certain internal resolver variables to be modified
+ Options []string `protobuf:"bytes,3,rep,name=options" json:"options,omitempty"`
+}
+
+func (m *ContainerSpec_DNSConfig) Reset() { *m = ContainerSpec_DNSConfig{} }
+func (*ContainerSpec_DNSConfig) ProtoMessage() {}
+func (*ContainerSpec_DNSConfig) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{7, 2} }
+
+// EndpointSpec defines the properties that can be configured to
+// access and loadbalance the service.
+type EndpointSpec struct {
+ Mode EndpointSpec_ResolutionMode `protobuf:"varint,1,opt,name=mode,proto3,enum=docker.swarmkit.v1.EndpointSpec_ResolutionMode" json:"mode,omitempty"`
+ // List of exposed ports that this service is accessible from
+ // external to the cluster.
+ Ports []*PortConfig `protobuf:"bytes,2,rep,name=ports" json:"ports,omitempty"`
+}
+
+func (m *EndpointSpec) Reset() { *m = EndpointSpec{} }
+func (*EndpointSpec) ProtoMessage() {}
+func (*EndpointSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{8} }
+
+// NetworkSpec specifies user defined network parameters.
+type NetworkSpec struct {
+ Annotations Annotations `protobuf:"bytes,1,opt,name=annotations" json:"annotations"`
+ // DriverConfig specific configuration consumed by the network driver.
+ DriverConfig *Driver `protobuf:"bytes,2,opt,name=driver_config,json=driverConfig" json:"driver_config,omitempty"`
+ // IPv6Enabled enables support for IPv6 on the network.
+ Ipv6Enabled bool `protobuf:"varint,3,opt,name=ipv6_enabled,json=ipv6Enabled,proto3" json:"ipv6_enabled,omitempty"`
+ // internal restricts external access to the network. This may be
+ // accomplished by disabling the default gateway or through other means.
+ Internal bool `protobuf:"varint,4,opt,name=internal,proto3" json:"internal,omitempty"`
+ IPAM *IPAMOptions `protobuf:"bytes,5,opt,name=ipam" json:"ipam,omitempty"`
+ // Attachable allows external(to swarm) entities to manually
+ // attach to this network. With this flag enabled, external
+ // entities such as containers running in an worker node in
+ // the cluster can manually attach to this network and access
+ // the services attached to this network. If this flag is not
+ // enabled(default case) no manual attachment to this network
+ // can happen.
+ Attachable bool `protobuf:"varint,6,opt,name=attachable,proto3" json:"attachable,omitempty"`
+ // Ingress indicates this network will provide the routing-mesh.
+ // In older versions, the network providing the routing mesh was
+ // swarm internally created only and it was identified by the name
+ // "ingress" and the label "com.docker.swarm.internal": "true".
+ Ingress bool `protobuf:"varint,7,opt,name=ingress,proto3" json:"ingress,omitempty"`
+ // ConfigFrom is the source of the configuration for this network.
+ //
+ // Types that are valid to be assigned to ConfigFrom:
+ // *NetworkSpec_Network
+ ConfigFrom isNetworkSpec_ConfigFrom `protobuf_oneof:"config_from"`
+}
+
+func (m *NetworkSpec) Reset() { *m = NetworkSpec{} }
+func (*NetworkSpec) ProtoMessage() {}
+func (*NetworkSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{9} }
+
+type isNetworkSpec_ConfigFrom interface {
+ isNetworkSpec_ConfigFrom()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type NetworkSpec_Network struct {
+ Network string `protobuf:"bytes,8,opt,name=network,proto3,oneof"`
+}
+
+func (*NetworkSpec_Network) isNetworkSpec_ConfigFrom() {}
+
+func (m *NetworkSpec) GetConfigFrom() isNetworkSpec_ConfigFrom {
+ if m != nil {
+ return m.ConfigFrom
+ }
+ return nil
+}
+
+func (m *NetworkSpec) GetNetwork() string {
+ if x, ok := m.GetConfigFrom().(*NetworkSpec_Network); ok {
+ return x.Network
+ }
+ return ""
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*NetworkSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _NetworkSpec_OneofMarshaler, _NetworkSpec_OneofUnmarshaler, _NetworkSpec_OneofSizer, []interface{}{
+ (*NetworkSpec_Network)(nil),
+ }
+}
+
+func _NetworkSpec_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*NetworkSpec)
+ // config_from
+ switch x := m.ConfigFrom.(type) {
+ case *NetworkSpec_Network:
+ _ = b.EncodeVarint(8<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.Network)
+ case nil:
+ default:
+ return fmt.Errorf("NetworkSpec.ConfigFrom has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _NetworkSpec_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*NetworkSpec)
+ switch tag {
+ case 8: // config_from.network
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.ConfigFrom = &NetworkSpec_Network{x}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _NetworkSpec_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*NetworkSpec)
+ // config_from
+ switch x := m.ConfigFrom.(type) {
+ case *NetworkSpec_Network:
+ n += proto.SizeVarint(8<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Network)))
+ n += len(x.Network)
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// ClusterSpec specifies global cluster settings.
+type ClusterSpec struct {
+ Annotations Annotations `protobuf:"bytes,1,opt,name=annotations" json:"annotations"`
+ // DEPRECATED: AcceptancePolicy defines the certificate issuance policy.
+ // Acceptance policy is no longer customizable, and secrets have been
+ // replaced with join tokens.
+ AcceptancePolicy AcceptancePolicy `protobuf:"bytes,2,opt,name=acceptance_policy,json=acceptancePolicy" json:"acceptance_policy"`
+ // Orchestration defines cluster-level orchestration settings.
+ Orchestration OrchestrationConfig `protobuf:"bytes,3,opt,name=orchestration" json:"orchestration"`
+ // Raft defines the cluster's raft settings.
+ Raft RaftConfig `protobuf:"bytes,4,opt,name=raft" json:"raft"`
+ // Dispatcher defines cluster-level dispatcher settings.
+ Dispatcher DispatcherConfig `protobuf:"bytes,5,opt,name=dispatcher" json:"dispatcher"`
+ // CAConfig defines cluster-level certificate authority settings.
+ CAConfig CAConfig `protobuf:"bytes,6,opt,name=ca_config,json=caConfig" json:"ca_config"`
+ // TaskDefaults specifies the default values to use for task creation.
+ TaskDefaults TaskDefaults `protobuf:"bytes,7,opt,name=task_defaults,json=taskDefaults" json:"task_defaults"`
+ // EncryptionConfig defines the cluster's encryption settings.
+ EncryptionConfig EncryptionConfig `protobuf:"bytes,8,opt,name=encryption_config,json=encryptionConfig" json:"encryption_config"`
+}
+
+func (m *ClusterSpec) Reset() { *m = ClusterSpec{} }
+func (*ClusterSpec) ProtoMessage() {}
+func (*ClusterSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{10} }
+
+// SecretSpec specifies a user-provided secret.
+type SecretSpec struct {
+ Annotations Annotations `protobuf:"bytes,1,opt,name=annotations" json:"annotations"`
+ // Data is the secret payload - the maximum size is 500KB (that is, 500*1024 bytes)
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+ // Templating controls whether and how to evaluate the secret payload as
+ // a template. If it is not set, no templating is used.
+ //
+ // The currently recognized values are:
+ // - golang: Go templating
+ Templating *Driver `protobuf:"bytes,3,opt,name=templating" json:"templating,omitempty"`
+}
+
+func (m *SecretSpec) Reset() { *m = SecretSpec{} }
+func (*SecretSpec) ProtoMessage() {}
+func (*SecretSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{11} }
+
+// ConfigSpec specifies user-provided configuration files.
+type ConfigSpec struct {
+ Annotations Annotations `protobuf:"bytes,1,opt,name=annotations" json:"annotations"`
+ // Data is the config payload - the maximum size is 500KB (that is, 500*1024 bytes)
+ // TODO(aaronl): Do we want to revise this to include multiple payloads in a single
+ // ConfigSpec? Define this to be a tar? etc...
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+ // Templating controls whether and how to evaluate the secret payload as
+ // a template. If it is not set, no templating is used.
+ //
+ // The currently recognized values are:
+ // - golang: Go templating
+ Templating *Driver `protobuf:"bytes,3,opt,name=templating" json:"templating,omitempty"`
+}
+
+func (m *ConfigSpec) Reset() { *m = ConfigSpec{} }
+func (*ConfigSpec) ProtoMessage() {}
+func (*ConfigSpec) Descriptor() ([]byte, []int) { return fileDescriptorSpecs, []int{12} }
+
+func init() {
+ proto.RegisterType((*NodeSpec)(nil), "docker.swarmkit.v1.NodeSpec")
+ proto.RegisterType((*ServiceSpec)(nil), "docker.swarmkit.v1.ServiceSpec")
+ proto.RegisterType((*ReplicatedService)(nil), "docker.swarmkit.v1.ReplicatedService")
+ proto.RegisterType((*GlobalService)(nil), "docker.swarmkit.v1.GlobalService")
+ proto.RegisterType((*TaskSpec)(nil), "docker.swarmkit.v1.TaskSpec")
+ proto.RegisterType((*GenericRuntimeSpec)(nil), "docker.swarmkit.v1.GenericRuntimeSpec")
+ proto.RegisterType((*NetworkAttachmentSpec)(nil), "docker.swarmkit.v1.NetworkAttachmentSpec")
+ proto.RegisterType((*ContainerSpec)(nil), "docker.swarmkit.v1.ContainerSpec")
+ proto.RegisterType((*ContainerSpec_PullOptions)(nil), "docker.swarmkit.v1.ContainerSpec.PullOptions")
+ proto.RegisterType((*ContainerSpec_DNSConfig)(nil), "docker.swarmkit.v1.ContainerSpec.DNSConfig")
+ proto.RegisterType((*EndpointSpec)(nil), "docker.swarmkit.v1.EndpointSpec")
+ proto.RegisterType((*NetworkSpec)(nil), "docker.swarmkit.v1.NetworkSpec")
+ proto.RegisterType((*ClusterSpec)(nil), "docker.swarmkit.v1.ClusterSpec")
+ proto.RegisterType((*SecretSpec)(nil), "docker.swarmkit.v1.SecretSpec")
+ proto.RegisterType((*ConfigSpec)(nil), "docker.swarmkit.v1.ConfigSpec")
+ proto.RegisterEnum("docker.swarmkit.v1.NodeSpec_Membership", NodeSpec_Membership_name, NodeSpec_Membership_value)
+ proto.RegisterEnum("docker.swarmkit.v1.NodeSpec_Availability", NodeSpec_Availability_name, NodeSpec_Availability_value)
+ proto.RegisterEnum("docker.swarmkit.v1.EndpointSpec_ResolutionMode", EndpointSpec_ResolutionMode_name, EndpointSpec_ResolutionMode_value)
+}
+
+func (m *NodeSpec) Copy() *NodeSpec {
+ if m == nil {
+ return nil
+ }
+ o := &NodeSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *NodeSpec) CopyFrom(src interface{}) {
+
+ o := src.(*NodeSpec)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Annotations, &o.Annotations)
+}
+
+func (m *ServiceSpec) Copy() *ServiceSpec {
+ if m == nil {
+ return nil
+ }
+ o := &ServiceSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ServiceSpec) CopyFrom(src interface{}) {
+
+ o := src.(*ServiceSpec)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Annotations, &o.Annotations)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Task, &o.Task)
+ if o.Update != nil {
+ m.Update = &UpdateConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Update, o.Update)
+ }
+ if o.Rollback != nil {
+ m.Rollback = &UpdateConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Rollback, o.Rollback)
+ }
+ if o.Networks != nil {
+ m.Networks = make([]*NetworkAttachmentConfig, len(o.Networks))
+ for i := range m.Networks {
+ m.Networks[i] = &NetworkAttachmentConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Networks[i], o.Networks[i])
+ }
+ }
+
+ if o.Endpoint != nil {
+ m.Endpoint = &EndpointSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Endpoint, o.Endpoint)
+ }
+ if o.Mode != nil {
+ switch o.Mode.(type) {
+ case *ServiceSpec_Replicated:
+ v := ServiceSpec_Replicated{
+ Replicated: &ReplicatedService{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Replicated, o.GetReplicated())
+ m.Mode = &v
+ case *ServiceSpec_Global:
+ v := ServiceSpec_Global{
+ Global: &GlobalService{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Global, o.GetGlobal())
+ m.Mode = &v
+ }
+ }
+
+}
+
+func (m *ReplicatedService) Copy() *ReplicatedService {
+ if m == nil {
+ return nil
+ }
+ o := &ReplicatedService{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ReplicatedService) CopyFrom(src interface{}) {
+
+ o := src.(*ReplicatedService)
+ *m = *o
+}
+
+func (m *GlobalService) Copy() *GlobalService {
+ if m == nil {
+ return nil
+ }
+ o := &GlobalService{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GlobalService) CopyFrom(src interface{}) {}
+func (m *TaskSpec) Copy() *TaskSpec {
+ if m == nil {
+ return nil
+ }
+ o := &TaskSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *TaskSpec) CopyFrom(src interface{}) {
+
+ o := src.(*TaskSpec)
+ *m = *o
+ if o.Resources != nil {
+ m.Resources = &ResourceRequirements{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Resources, o.Resources)
+ }
+ if o.Restart != nil {
+ m.Restart = &RestartPolicy{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Restart, o.Restart)
+ }
+ if o.Placement != nil {
+ m.Placement = &Placement{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Placement, o.Placement)
+ }
+ if o.LogDriver != nil {
+ m.LogDriver = &Driver{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.LogDriver, o.LogDriver)
+ }
+ if o.Networks != nil {
+ m.Networks = make([]*NetworkAttachmentConfig, len(o.Networks))
+ for i := range m.Networks {
+ m.Networks[i] = &NetworkAttachmentConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Networks[i], o.Networks[i])
+ }
+ }
+
+ if o.Runtime != nil {
+ switch o.Runtime.(type) {
+ case *TaskSpec_Attachment:
+ v := TaskSpec_Attachment{
+ Attachment: &NetworkAttachmentSpec{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Attachment, o.GetAttachment())
+ m.Runtime = &v
+ case *TaskSpec_Container:
+ v := TaskSpec_Container{
+ Container: &ContainerSpec{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Container, o.GetContainer())
+ m.Runtime = &v
+ case *TaskSpec_Generic:
+ v := TaskSpec_Generic{
+ Generic: &GenericRuntimeSpec{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Generic, o.GetGeneric())
+ m.Runtime = &v
+ }
+ }
+
+}
+
+func (m *GenericRuntimeSpec) Copy() *GenericRuntimeSpec {
+ if m == nil {
+ return nil
+ }
+ o := &GenericRuntimeSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GenericRuntimeSpec) CopyFrom(src interface{}) {
+
+ o := src.(*GenericRuntimeSpec)
+ *m = *o
+ if o.Payload != nil {
+ m.Payload = &google_protobuf3.Any{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Payload, o.Payload)
+ }
+}
+
+func (m *NetworkAttachmentSpec) Copy() *NetworkAttachmentSpec {
+ if m == nil {
+ return nil
+ }
+ o := &NetworkAttachmentSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *NetworkAttachmentSpec) CopyFrom(src interface{}) {
+
+ o := src.(*NetworkAttachmentSpec)
+ *m = *o
+}
+
+func (m *ContainerSpec) Copy() *ContainerSpec {
+ if m == nil {
+ return nil
+ }
+ o := &ContainerSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ContainerSpec) CopyFrom(src interface{}) {
+
+ o := src.(*ContainerSpec)
+ *m = *o
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.Command != nil {
+ m.Command = make([]string, len(o.Command))
+ copy(m.Command, o.Command)
+ }
+
+ if o.Args != nil {
+ m.Args = make([]string, len(o.Args))
+ copy(m.Args, o.Args)
+ }
+
+ if o.Env != nil {
+ m.Env = make([]string, len(o.Env))
+ copy(m.Env, o.Env)
+ }
+
+ if o.Groups != nil {
+ m.Groups = make([]string, len(o.Groups))
+ copy(m.Groups, o.Groups)
+ }
+
+ if o.Privileges != nil {
+ m.Privileges = &Privileges{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Privileges, o.Privileges)
+ }
+ if o.Mounts != nil {
+ m.Mounts = make([]Mount, len(o.Mounts))
+ for i := range m.Mounts {
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Mounts[i], &o.Mounts[i])
+ }
+ }
+
+ if o.StopGracePeriod != nil {
+ m.StopGracePeriod = &google_protobuf1.Duration{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.StopGracePeriod, o.StopGracePeriod)
+ }
+ if o.PullOptions != nil {
+ m.PullOptions = &ContainerSpec_PullOptions{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.PullOptions, o.PullOptions)
+ }
+ if o.Secrets != nil {
+ m.Secrets = make([]*SecretReference, len(o.Secrets))
+ for i := range m.Secrets {
+ m.Secrets[i] = &SecretReference{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Secrets[i], o.Secrets[i])
+ }
+ }
+
+ if o.Configs != nil {
+ m.Configs = make([]*ConfigReference, len(o.Configs))
+ for i := range m.Configs {
+ m.Configs[i] = &ConfigReference{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Configs[i], o.Configs[i])
+ }
+ }
+
+ if o.Hosts != nil {
+ m.Hosts = make([]string, len(o.Hosts))
+ copy(m.Hosts, o.Hosts)
+ }
+
+ if o.DNSConfig != nil {
+ m.DNSConfig = &ContainerSpec_DNSConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.DNSConfig, o.DNSConfig)
+ }
+ if o.Healthcheck != nil {
+ m.Healthcheck = &HealthConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Healthcheck, o.Healthcheck)
+ }
+}
+
+func (m *ContainerSpec_PullOptions) Copy() *ContainerSpec_PullOptions {
+ if m == nil {
+ return nil
+ }
+ o := &ContainerSpec_PullOptions{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ContainerSpec_PullOptions) CopyFrom(src interface{}) {
+
+ o := src.(*ContainerSpec_PullOptions)
+ *m = *o
+}
+
+func (m *ContainerSpec_DNSConfig) Copy() *ContainerSpec_DNSConfig {
+ if m == nil {
+ return nil
+ }
+ o := &ContainerSpec_DNSConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ContainerSpec_DNSConfig) CopyFrom(src interface{}) {
+
+ o := src.(*ContainerSpec_DNSConfig)
+ *m = *o
+ if o.Nameservers != nil {
+ m.Nameservers = make([]string, len(o.Nameservers))
+ copy(m.Nameservers, o.Nameservers)
+ }
+
+ if o.Search != nil {
+ m.Search = make([]string, len(o.Search))
+ copy(m.Search, o.Search)
+ }
+
+ if o.Options != nil {
+ m.Options = make([]string, len(o.Options))
+ copy(m.Options, o.Options)
+ }
+
+}
+
+func (m *EndpointSpec) Copy() *EndpointSpec {
+ if m == nil {
+ return nil
+ }
+ o := &EndpointSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *EndpointSpec) CopyFrom(src interface{}) {
+
+ o := src.(*EndpointSpec)
+ *m = *o
+ if o.Ports != nil {
+ m.Ports = make([]*PortConfig, len(o.Ports))
+ for i := range m.Ports {
+ m.Ports[i] = &PortConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Ports[i], o.Ports[i])
+ }
+ }
+
+}
+
+func (m *NetworkSpec) Copy() *NetworkSpec {
+ if m == nil {
+ return nil
+ }
+ o := &NetworkSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *NetworkSpec) CopyFrom(src interface{}) {
+
+ o := src.(*NetworkSpec)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Annotations, &o.Annotations)
+ if o.DriverConfig != nil {
+ m.DriverConfig = &Driver{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.DriverConfig, o.DriverConfig)
+ }
+ if o.IPAM != nil {
+ m.IPAM = &IPAMOptions{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.IPAM, o.IPAM)
+ }
+ if o.ConfigFrom != nil {
+ switch o.ConfigFrom.(type) {
+ case *NetworkSpec_Network:
+ v := NetworkSpec_Network{
+ Network: o.GetNetwork(),
+ }
+ m.ConfigFrom = &v
+ }
+ }
+
+}
+
+func (m *ClusterSpec) Copy() *ClusterSpec {
+ if m == nil {
+ return nil
+ }
+ o := &ClusterSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ClusterSpec) CopyFrom(src interface{}) {
+
+ o := src.(*ClusterSpec)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Annotations, &o.Annotations)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.AcceptancePolicy, &o.AcceptancePolicy)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Orchestration, &o.Orchestration)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Raft, &o.Raft)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Dispatcher, &o.Dispatcher)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.CAConfig, &o.CAConfig)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.TaskDefaults, &o.TaskDefaults)
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.EncryptionConfig, &o.EncryptionConfig)
+}
+
+func (m *SecretSpec) Copy() *SecretSpec {
+ if m == nil {
+ return nil
+ }
+ o := &SecretSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SecretSpec) CopyFrom(src interface{}) {
+
+ o := src.(*SecretSpec)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Annotations, &o.Annotations)
+ if o.Data != nil {
+ m.Data = make([]byte, len(o.Data))
+ copy(m.Data, o.Data)
+ }
+ if o.Templating != nil {
+ m.Templating = &Driver{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Templating, o.Templating)
+ }
+}
+
+func (m *ConfigSpec) Copy() *ConfigSpec {
+ if m == nil {
+ return nil
+ }
+ o := &ConfigSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ConfigSpec) CopyFrom(src interface{}) {
+
+ o := src.(*ConfigSpec)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Annotations, &o.Annotations)
+ if o.Data != nil {
+ m.Data = make([]byte, len(o.Data))
+ copy(m.Data, o.Data)
+ }
+ if o.Templating != nil {
+ m.Templating = &Driver{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Templating, o.Templating)
+ }
+}
+
+func (m *NodeSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NodeSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Annotations.Size()))
+ n1, err := m.Annotations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ if m.DesiredRole != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.DesiredRole))
+ }
+ if m.Membership != 0 {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Membership))
+ }
+ if m.Availability != 0 {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Availability))
+ }
+ return i, nil
+}
+
+func (m *ServiceSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ServiceSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Annotations.Size()))
+ n2, err := m.Annotations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Task.Size()))
+ n3, err := m.Task.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ if m.Mode != nil {
+ nn4, err := m.Mode.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn4
+ }
+ if m.Update != nil {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Update.Size()))
+ n5, err := m.Update.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n5
+ }
+ if len(m.Networks) > 0 {
+ for _, msg := range m.Networks {
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if m.Endpoint != nil {
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Endpoint.Size()))
+ n6, err := m.Endpoint.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n6
+ }
+ if m.Rollback != nil {
+ dAtA[i] = 0x4a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Rollback.Size()))
+ n7, err := m.Rollback.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n7
+ }
+ return i, nil
+}
+
+func (m *ServiceSpec_Replicated) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Replicated != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Replicated.Size()))
+ n8, err := m.Replicated.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n8
+ }
+ return i, nil
+}
+func (m *ServiceSpec_Global) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Global != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Global.Size()))
+ n9, err := m.Global.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n9
+ }
+ return i, nil
+}
+func (m *ReplicatedService) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ReplicatedService) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Replicas != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Replicas))
+ }
+ return i, nil
+}
+
+func (m *GlobalService) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GlobalService) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func (m *TaskSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *TaskSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Runtime != nil {
+ nn10, err := m.Runtime.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn10
+ }
+ if m.Resources != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Resources.Size()))
+ n11, err := m.Resources.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n11
+ }
+ if m.Restart != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Restart.Size()))
+ n12, err := m.Restart.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n12
+ }
+ if m.Placement != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Placement.Size()))
+ n13, err := m.Placement.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n13
+ }
+ if m.LogDriver != nil {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.LogDriver.Size()))
+ n14, err := m.LogDriver.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n14
+ }
+ if len(m.Networks) > 0 {
+ for _, msg := range m.Networks {
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if m.ForceUpdate != 0 {
+ dAtA[i] = 0x48
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.ForceUpdate))
+ }
+ return i, nil
+}
+
+func (m *TaskSpec_Container) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Container != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Container.Size()))
+ n15, err := m.Container.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n15
+ }
+ return i, nil
+}
+func (m *TaskSpec_Attachment) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Attachment != nil {
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Attachment.Size()))
+ n16, err := m.Attachment.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n16
+ }
+ return i, nil
+}
+func (m *TaskSpec_Generic) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Generic != nil {
+ dAtA[i] = 0x52
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Generic.Size()))
+ n17, err := m.Generic.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n17
+ }
+ return i, nil
+}
+func (m *GenericRuntimeSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GenericRuntimeSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Kind) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.Kind)))
+ i += copy(dAtA[i:], m.Kind)
+ }
+ if m.Payload != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Payload.Size()))
+ n18, err := m.Payload.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n18
+ }
+ return i, nil
+}
+
+func (m *NetworkAttachmentSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NetworkAttachmentSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ContainerID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.ContainerID)))
+ i += copy(dAtA[i:], m.ContainerID)
+ }
+ return i, nil
+}
+
+func (m *ContainerSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ContainerSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Image) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.Image)))
+ i += copy(dAtA[i:], m.Image)
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x12
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovSpecs(uint64(len(k))) + 1 + len(v) + sovSpecs(uint64(len(v)))
+ i = encodeVarintSpecs(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.Command) > 0 {
+ for _, s := range m.Command {
+ dAtA[i] = 0x1a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Args) > 0 {
+ for _, s := range m.Args {
+ dAtA[i] = 0x22
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Env) > 0 {
+ for _, s := range m.Env {
+ dAtA[i] = 0x2a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Dir) > 0 {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.Dir)))
+ i += copy(dAtA[i:], m.Dir)
+ }
+ if len(m.User) > 0 {
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.User)))
+ i += copy(dAtA[i:], m.User)
+ }
+ if len(m.Mounts) > 0 {
+ for _, msg := range m.Mounts {
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if m.StopGracePeriod != nil {
+ dAtA[i] = 0x4a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.StopGracePeriod.Size()))
+ n19, err := m.StopGracePeriod.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n19
+ }
+ if m.PullOptions != nil {
+ dAtA[i] = 0x52
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.PullOptions.Size()))
+ n20, err := m.PullOptions.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n20
+ }
+ if len(m.Groups) > 0 {
+ for _, s := range m.Groups {
+ dAtA[i] = 0x5a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Secrets) > 0 {
+ for _, msg := range m.Secrets {
+ dAtA[i] = 0x62
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if m.TTY {
+ dAtA[i] = 0x68
+ i++
+ if m.TTY {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if len(m.Hostname) > 0 {
+ dAtA[i] = 0x72
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.Hostname)))
+ i += copy(dAtA[i:], m.Hostname)
+ }
+ if m.DNSConfig != nil {
+ dAtA[i] = 0x7a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.DNSConfig.Size()))
+ n21, err := m.DNSConfig.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n21
+ }
+ if m.Healthcheck != nil {
+ dAtA[i] = 0x82
+ i++
+ dAtA[i] = 0x1
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Healthcheck.Size()))
+ n22, err := m.Healthcheck.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n22
+ }
+ if len(m.Hosts) > 0 {
+ for _, s := range m.Hosts {
+ dAtA[i] = 0x8a
+ i++
+ dAtA[i] = 0x1
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if m.OpenStdin {
+ dAtA[i] = 0x90
+ i++
+ dAtA[i] = 0x1
+ i++
+ if m.OpenStdin {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.ReadOnly {
+ dAtA[i] = 0x98
+ i++
+ dAtA[i] = 0x1
+ i++
+ if m.ReadOnly {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if len(m.StopSignal) > 0 {
+ dAtA[i] = 0xa2
+ i++
+ dAtA[i] = 0x1
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.StopSignal)))
+ i += copy(dAtA[i:], m.StopSignal)
+ }
+ if len(m.Configs) > 0 {
+ for _, msg := range m.Configs {
+ dAtA[i] = 0xaa
+ i++
+ dAtA[i] = 0x1
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if m.Privileges != nil {
+ dAtA[i] = 0xb2
+ i++
+ dAtA[i] = 0x1
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Privileges.Size()))
+ n23, err := m.Privileges.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n23
+ }
+ return i, nil
+}
+
+func (m *ContainerSpec_PullOptions) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ContainerSpec_PullOptions) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.RegistryAuth) > 0 {
+ dAtA[i] = 0x82
+ i++
+ dAtA[i] = 0x4
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.RegistryAuth)))
+ i += copy(dAtA[i:], m.RegistryAuth)
+ }
+ return i, nil
+}
+
+func (m *ContainerSpec_DNSConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ContainerSpec_DNSConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Nameservers) > 0 {
+ for _, s := range m.Nameservers {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Search) > 0 {
+ for _, s := range m.Search {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Options) > 0 {
+ for _, s := range m.Options {
+ dAtA[i] = 0x1a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func (m *EndpointSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *EndpointSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Mode != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Mode))
+ }
+ if len(m.Ports) > 0 {
+ for _, msg := range m.Ports {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *NetworkSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NetworkSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Annotations.Size()))
+ n24, err := m.Annotations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n24
+ if m.DriverConfig != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.DriverConfig.Size()))
+ n25, err := m.DriverConfig.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n25
+ }
+ if m.Ipv6Enabled {
+ dAtA[i] = 0x18
+ i++
+ if m.Ipv6Enabled {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Internal {
+ dAtA[i] = 0x20
+ i++
+ if m.Internal {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.IPAM != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.IPAM.Size()))
+ n26, err := m.IPAM.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n26
+ }
+ if m.Attachable {
+ dAtA[i] = 0x30
+ i++
+ if m.Attachable {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Ingress {
+ dAtA[i] = 0x38
+ i++
+ if m.Ingress {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.ConfigFrom != nil {
+ nn27, err := m.ConfigFrom.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn27
+ }
+ return i, nil
+}
+
+func (m *NetworkSpec_Network) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.Network)))
+ i += copy(dAtA[i:], m.Network)
+ return i, nil
+}
+func (m *ClusterSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ClusterSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Annotations.Size()))
+ n28, err := m.Annotations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n28
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.AcceptancePolicy.Size()))
+ n29, err := m.AcceptancePolicy.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n29
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Orchestration.Size()))
+ n30, err := m.Orchestration.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n30
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Raft.Size()))
+ n31, err := m.Raft.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n31
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Dispatcher.Size()))
+ n32, err := m.Dispatcher.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n32
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.CAConfig.Size()))
+ n33, err := m.CAConfig.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n33
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.TaskDefaults.Size()))
+ n34, err := m.TaskDefaults.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n34
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.EncryptionConfig.Size()))
+ n35, err := m.EncryptionConfig.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n35
+ return i, nil
+}
+
+func (m *SecretSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SecretSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Annotations.Size()))
+ n36, err := m.Annotations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n36
+ if len(m.Data) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.Data)))
+ i += copy(dAtA[i:], m.Data)
+ }
+ if m.Templating != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Templating.Size()))
+ n37, err := m.Templating.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n37
+ }
+ return i, nil
+}
+
+func (m *ConfigSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ConfigSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Annotations.Size()))
+ n38, err := m.Annotations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n38
+ if len(m.Data) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(len(m.Data)))
+ i += copy(dAtA[i:], m.Data)
+ }
+ if m.Templating != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintSpecs(dAtA, i, uint64(m.Templating.Size()))
+ n39, err := m.Templating.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n39
+ }
+ return i, nil
+}
+
+func encodeFixed64Specs(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Specs(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintSpecs(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+func (m *NodeSpec) Size() (n int) {
+ var l int
+ _ = l
+ l = m.Annotations.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ if m.DesiredRole != 0 {
+ n += 1 + sovSpecs(uint64(m.DesiredRole))
+ }
+ if m.Membership != 0 {
+ n += 1 + sovSpecs(uint64(m.Membership))
+ }
+ if m.Availability != 0 {
+ n += 1 + sovSpecs(uint64(m.Availability))
+ }
+ return n
+}
+
+func (m *ServiceSpec) Size() (n int) {
+ var l int
+ _ = l
+ l = m.Annotations.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ l = m.Task.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ if m.Mode != nil {
+ n += m.Mode.Size()
+ }
+ if m.Update != nil {
+ l = m.Update.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if len(m.Networks) > 0 {
+ for _, e := range m.Networks {
+ l = e.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ if m.Endpoint != nil {
+ l = m.Endpoint.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.Rollback != nil {
+ l = m.Rollback.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+
+func (m *ServiceSpec_Replicated) Size() (n int) {
+ var l int
+ _ = l
+ if m.Replicated != nil {
+ l = m.Replicated.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+func (m *ServiceSpec_Global) Size() (n int) {
+ var l int
+ _ = l
+ if m.Global != nil {
+ l = m.Global.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+func (m *ReplicatedService) Size() (n int) {
+ var l int
+ _ = l
+ if m.Replicas != 0 {
+ n += 1 + sovSpecs(uint64(m.Replicas))
+ }
+ return n
+}
+
+func (m *GlobalService) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func (m *TaskSpec) Size() (n int) {
+ var l int
+ _ = l
+ if m.Runtime != nil {
+ n += m.Runtime.Size()
+ }
+ if m.Resources != nil {
+ l = m.Resources.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.Restart != nil {
+ l = m.Restart.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.Placement != nil {
+ l = m.Placement.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.LogDriver != nil {
+ l = m.LogDriver.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if len(m.Networks) > 0 {
+ for _, e := range m.Networks {
+ l = e.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ if m.ForceUpdate != 0 {
+ n += 1 + sovSpecs(uint64(m.ForceUpdate))
+ }
+ return n
+}
+
+func (m *TaskSpec_Container) Size() (n int) {
+ var l int
+ _ = l
+ if m.Container != nil {
+ l = m.Container.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+func (m *TaskSpec_Attachment) Size() (n int) {
+ var l int
+ _ = l
+ if m.Attachment != nil {
+ l = m.Attachment.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+func (m *TaskSpec_Generic) Size() (n int) {
+ var l int
+ _ = l
+ if m.Generic != nil {
+ l = m.Generic.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+func (m *GenericRuntimeSpec) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Kind)
+ if l > 0 {
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.Payload != nil {
+ l = m.Payload.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+
+func (m *NetworkAttachmentSpec) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ContainerID)
+ if l > 0 {
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+
+func (m *ContainerSpec) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Image)
+ if l > 0 {
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovSpecs(uint64(len(k))) + 1 + len(v) + sovSpecs(uint64(len(v)))
+ n += mapEntrySize + 1 + sovSpecs(uint64(mapEntrySize))
+ }
+ }
+ if len(m.Command) > 0 {
+ for _, s := range m.Command {
+ l = len(s)
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ if len(m.Args) > 0 {
+ for _, s := range m.Args {
+ l = len(s)
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ if len(m.Env) > 0 {
+ for _, s := range m.Env {
+ l = len(s)
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ l = len(m.Dir)
+ if l > 0 {
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ l = len(m.User)
+ if l > 0 {
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if len(m.Mounts) > 0 {
+ for _, e := range m.Mounts {
+ l = e.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ if m.StopGracePeriod != nil {
+ l = m.StopGracePeriod.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.PullOptions != nil {
+ l = m.PullOptions.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if len(m.Groups) > 0 {
+ for _, s := range m.Groups {
+ l = len(s)
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ if len(m.Secrets) > 0 {
+ for _, e := range m.Secrets {
+ l = e.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ if m.TTY {
+ n += 2
+ }
+ l = len(m.Hostname)
+ if l > 0 {
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.DNSConfig != nil {
+ l = m.DNSConfig.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.Healthcheck != nil {
+ l = m.Healthcheck.Size()
+ n += 2 + l + sovSpecs(uint64(l))
+ }
+ if len(m.Hosts) > 0 {
+ for _, s := range m.Hosts {
+ l = len(s)
+ n += 2 + l + sovSpecs(uint64(l))
+ }
+ }
+ if m.OpenStdin {
+ n += 3
+ }
+ if m.ReadOnly {
+ n += 3
+ }
+ l = len(m.StopSignal)
+ if l > 0 {
+ n += 2 + l + sovSpecs(uint64(l))
+ }
+ if len(m.Configs) > 0 {
+ for _, e := range m.Configs {
+ l = e.Size()
+ n += 2 + l + sovSpecs(uint64(l))
+ }
+ }
+ if m.Privileges != nil {
+ l = m.Privileges.Size()
+ n += 2 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+
+func (m *ContainerSpec_PullOptions) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.RegistryAuth)
+ if l > 0 {
+ n += 2 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+
+func (m *ContainerSpec_DNSConfig) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Nameservers) > 0 {
+ for _, s := range m.Nameservers {
+ l = len(s)
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ if len(m.Search) > 0 {
+ for _, s := range m.Search {
+ l = len(s)
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ if len(m.Options) > 0 {
+ for _, s := range m.Options {
+ l = len(s)
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *EndpointSpec) Size() (n int) {
+ var l int
+ _ = l
+ if m.Mode != 0 {
+ n += 1 + sovSpecs(uint64(m.Mode))
+ }
+ if len(m.Ports) > 0 {
+ for _, e := range m.Ports {
+ l = e.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *NetworkSpec) Size() (n int) {
+ var l int
+ _ = l
+ l = m.Annotations.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ if m.DriverConfig != nil {
+ l = m.DriverConfig.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.Ipv6Enabled {
+ n += 2
+ }
+ if m.Internal {
+ n += 2
+ }
+ if m.IPAM != nil {
+ l = m.IPAM.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.Attachable {
+ n += 2
+ }
+ if m.Ingress {
+ n += 2
+ }
+ if m.ConfigFrom != nil {
+ n += m.ConfigFrom.Size()
+ }
+ return n
+}
+
+func (m *NetworkSpec_Network) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Network)
+ n += 1 + l + sovSpecs(uint64(l))
+ return n
+}
+func (m *ClusterSpec) Size() (n int) {
+ var l int
+ _ = l
+ l = m.Annotations.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ l = m.AcceptancePolicy.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ l = m.Orchestration.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ l = m.Raft.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ l = m.Dispatcher.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ l = m.CAConfig.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ l = m.TaskDefaults.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ l = m.EncryptionConfig.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ return n
+}
+
+func (m *SecretSpec) Size() (n int) {
+ var l int
+ _ = l
+ l = m.Annotations.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ l = len(m.Data)
+ if l > 0 {
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.Templating != nil {
+ l = m.Templating.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+
+func (m *ConfigSpec) Size() (n int) {
+ var l int
+ _ = l
+ l = m.Annotations.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ l = len(m.Data)
+ if l > 0 {
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ if m.Templating != nil {
+ l = m.Templating.Size()
+ n += 1 + l + sovSpecs(uint64(l))
+ }
+ return n
+}
+
+func sovSpecs(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozSpecs(x uint64) (n int) {
+ return sovSpecs(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *NodeSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NodeSpec{`,
+ `Annotations:` + strings.Replace(strings.Replace(this.Annotations.String(), "Annotations", "Annotations", 1), `&`, ``, 1) + `,`,
+ `DesiredRole:` + fmt.Sprintf("%v", this.DesiredRole) + `,`,
+ `Membership:` + fmt.Sprintf("%v", this.Membership) + `,`,
+ `Availability:` + fmt.Sprintf("%v", this.Availability) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ServiceSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ServiceSpec{`,
+ `Annotations:` + strings.Replace(strings.Replace(this.Annotations.String(), "Annotations", "Annotations", 1), `&`, ``, 1) + `,`,
+ `Task:` + strings.Replace(strings.Replace(this.Task.String(), "TaskSpec", "TaskSpec", 1), `&`, ``, 1) + `,`,
+ `Mode:` + fmt.Sprintf("%v", this.Mode) + `,`,
+ `Update:` + strings.Replace(fmt.Sprintf("%v", this.Update), "UpdateConfig", "UpdateConfig", 1) + `,`,
+ `Networks:` + strings.Replace(fmt.Sprintf("%v", this.Networks), "NetworkAttachmentConfig", "NetworkAttachmentConfig", 1) + `,`,
+ `Endpoint:` + strings.Replace(fmt.Sprintf("%v", this.Endpoint), "EndpointSpec", "EndpointSpec", 1) + `,`,
+ `Rollback:` + strings.Replace(fmt.Sprintf("%v", this.Rollback), "UpdateConfig", "UpdateConfig", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ServiceSpec_Replicated) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ServiceSpec_Replicated{`,
+ `Replicated:` + strings.Replace(fmt.Sprintf("%v", this.Replicated), "ReplicatedService", "ReplicatedService", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ServiceSpec_Global) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ServiceSpec_Global{`,
+ `Global:` + strings.Replace(fmt.Sprintf("%v", this.Global), "GlobalService", "GlobalService", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ReplicatedService) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ReplicatedService{`,
+ `Replicas:` + fmt.Sprintf("%v", this.Replicas) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GlobalService) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GlobalService{`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TaskSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TaskSpec{`,
+ `Runtime:` + fmt.Sprintf("%v", this.Runtime) + `,`,
+ `Resources:` + strings.Replace(fmt.Sprintf("%v", this.Resources), "ResourceRequirements", "ResourceRequirements", 1) + `,`,
+ `Restart:` + strings.Replace(fmt.Sprintf("%v", this.Restart), "RestartPolicy", "RestartPolicy", 1) + `,`,
+ `Placement:` + strings.Replace(fmt.Sprintf("%v", this.Placement), "Placement", "Placement", 1) + `,`,
+ `LogDriver:` + strings.Replace(fmt.Sprintf("%v", this.LogDriver), "Driver", "Driver", 1) + `,`,
+ `Networks:` + strings.Replace(fmt.Sprintf("%v", this.Networks), "NetworkAttachmentConfig", "NetworkAttachmentConfig", 1) + `,`,
+ `ForceUpdate:` + fmt.Sprintf("%v", this.ForceUpdate) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TaskSpec_Container) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TaskSpec_Container{`,
+ `Container:` + strings.Replace(fmt.Sprintf("%v", this.Container), "ContainerSpec", "ContainerSpec", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TaskSpec_Attachment) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TaskSpec_Attachment{`,
+ `Attachment:` + strings.Replace(fmt.Sprintf("%v", this.Attachment), "NetworkAttachmentSpec", "NetworkAttachmentSpec", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TaskSpec_Generic) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TaskSpec_Generic{`,
+ `Generic:` + strings.Replace(fmt.Sprintf("%v", this.Generic), "GenericRuntimeSpec", "GenericRuntimeSpec", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GenericRuntimeSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GenericRuntimeSpec{`,
+ `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`,
+ `Payload:` + strings.Replace(fmt.Sprintf("%v", this.Payload), "Any", "google_protobuf3.Any", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NetworkAttachmentSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NetworkAttachmentSpec{`,
+ `ContainerID:` + fmt.Sprintf("%v", this.ContainerID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ContainerSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&ContainerSpec{`,
+ `Image:` + fmt.Sprintf("%v", this.Image) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `Command:` + fmt.Sprintf("%v", this.Command) + `,`,
+ `Args:` + fmt.Sprintf("%v", this.Args) + `,`,
+ `Env:` + fmt.Sprintf("%v", this.Env) + `,`,
+ `Dir:` + fmt.Sprintf("%v", this.Dir) + `,`,
+ `User:` + fmt.Sprintf("%v", this.User) + `,`,
+ `Mounts:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Mounts), "Mount", "Mount", 1), `&`, ``, 1) + `,`,
+ `StopGracePeriod:` + strings.Replace(fmt.Sprintf("%v", this.StopGracePeriod), "Duration", "google_protobuf1.Duration", 1) + `,`,
+ `PullOptions:` + strings.Replace(fmt.Sprintf("%v", this.PullOptions), "ContainerSpec_PullOptions", "ContainerSpec_PullOptions", 1) + `,`,
+ `Groups:` + fmt.Sprintf("%v", this.Groups) + `,`,
+ `Secrets:` + strings.Replace(fmt.Sprintf("%v", this.Secrets), "SecretReference", "SecretReference", 1) + `,`,
+ `TTY:` + fmt.Sprintf("%v", this.TTY) + `,`,
+ `Hostname:` + fmt.Sprintf("%v", this.Hostname) + `,`,
+ `DNSConfig:` + strings.Replace(fmt.Sprintf("%v", this.DNSConfig), "ContainerSpec_DNSConfig", "ContainerSpec_DNSConfig", 1) + `,`,
+ `Healthcheck:` + strings.Replace(fmt.Sprintf("%v", this.Healthcheck), "HealthConfig", "HealthConfig", 1) + `,`,
+ `Hosts:` + fmt.Sprintf("%v", this.Hosts) + `,`,
+ `OpenStdin:` + fmt.Sprintf("%v", this.OpenStdin) + `,`,
+ `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`,
+ `StopSignal:` + fmt.Sprintf("%v", this.StopSignal) + `,`,
+ `Configs:` + strings.Replace(fmt.Sprintf("%v", this.Configs), "ConfigReference", "ConfigReference", 1) + `,`,
+ `Privileges:` + strings.Replace(fmt.Sprintf("%v", this.Privileges), "Privileges", "Privileges", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ContainerSpec_PullOptions) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ContainerSpec_PullOptions{`,
+ `RegistryAuth:` + fmt.Sprintf("%v", this.RegistryAuth) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ContainerSpec_DNSConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ContainerSpec_DNSConfig{`,
+ `Nameservers:` + fmt.Sprintf("%v", this.Nameservers) + `,`,
+ `Search:` + fmt.Sprintf("%v", this.Search) + `,`,
+ `Options:` + fmt.Sprintf("%v", this.Options) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *EndpointSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&EndpointSpec{`,
+ `Mode:` + fmt.Sprintf("%v", this.Mode) + `,`,
+ `Ports:` + strings.Replace(fmt.Sprintf("%v", this.Ports), "PortConfig", "PortConfig", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NetworkSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NetworkSpec{`,
+ `Annotations:` + strings.Replace(strings.Replace(this.Annotations.String(), "Annotations", "Annotations", 1), `&`, ``, 1) + `,`,
+ `DriverConfig:` + strings.Replace(fmt.Sprintf("%v", this.DriverConfig), "Driver", "Driver", 1) + `,`,
+ `Ipv6Enabled:` + fmt.Sprintf("%v", this.Ipv6Enabled) + `,`,
+ `Internal:` + fmt.Sprintf("%v", this.Internal) + `,`,
+ `IPAM:` + strings.Replace(fmt.Sprintf("%v", this.IPAM), "IPAMOptions", "IPAMOptions", 1) + `,`,
+ `Attachable:` + fmt.Sprintf("%v", this.Attachable) + `,`,
+ `Ingress:` + fmt.Sprintf("%v", this.Ingress) + `,`,
+ `ConfigFrom:` + fmt.Sprintf("%v", this.ConfigFrom) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NetworkSpec_Network) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NetworkSpec_Network{`,
+ `Network:` + fmt.Sprintf("%v", this.Network) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ClusterSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ClusterSpec{`,
+ `Annotations:` + strings.Replace(strings.Replace(this.Annotations.String(), "Annotations", "Annotations", 1), `&`, ``, 1) + `,`,
+ `AcceptancePolicy:` + strings.Replace(strings.Replace(this.AcceptancePolicy.String(), "AcceptancePolicy", "AcceptancePolicy", 1), `&`, ``, 1) + `,`,
+ `Orchestration:` + strings.Replace(strings.Replace(this.Orchestration.String(), "OrchestrationConfig", "OrchestrationConfig", 1), `&`, ``, 1) + `,`,
+ `Raft:` + strings.Replace(strings.Replace(this.Raft.String(), "RaftConfig", "RaftConfig", 1), `&`, ``, 1) + `,`,
+ `Dispatcher:` + strings.Replace(strings.Replace(this.Dispatcher.String(), "DispatcherConfig", "DispatcherConfig", 1), `&`, ``, 1) + `,`,
+ `CAConfig:` + strings.Replace(strings.Replace(this.CAConfig.String(), "CAConfig", "CAConfig", 1), `&`, ``, 1) + `,`,
+ `TaskDefaults:` + strings.Replace(strings.Replace(this.TaskDefaults.String(), "TaskDefaults", "TaskDefaults", 1), `&`, ``, 1) + `,`,
+ `EncryptionConfig:` + strings.Replace(strings.Replace(this.EncryptionConfig.String(), "EncryptionConfig", "EncryptionConfig", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SecretSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SecretSpec{`,
+ `Annotations:` + strings.Replace(strings.Replace(this.Annotations.String(), "Annotations", "Annotations", 1), `&`, ``, 1) + `,`,
+ `Data:` + fmt.Sprintf("%v", this.Data) + `,`,
+ `Templating:` + strings.Replace(fmt.Sprintf("%v", this.Templating), "Driver", "Driver", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ConfigSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ConfigSpec{`,
+ `Annotations:` + strings.Replace(strings.Replace(this.Annotations.String(), "Annotations", "Annotations", 1), `&`, ``, 1) + `,`,
+ `Data:` + fmt.Sprintf("%v", this.Data) + `,`,
+ `Templating:` + strings.Replace(fmt.Sprintf("%v", this.Templating), "Driver", "Driver", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringSpecs(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *NodeSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NodeSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NodeSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Annotations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Annotations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field DesiredRole", wireType)
+ }
+ m.DesiredRole = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.DesiredRole |= (NodeRole(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Membership", wireType)
+ }
+ m.Membership = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Membership |= (NodeSpec_Membership(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Availability", wireType)
+ }
+ m.Availability = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Availability |= (NodeSpec_Availability(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ServiceSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ServiceSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ServiceSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Annotations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Annotations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Task", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Task.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Replicated", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &ReplicatedService{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Mode = &ServiceSpec_Replicated{v}
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Global", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &GlobalService{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Mode = &ServiceSpec_Global{v}
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Update", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Update == nil {
+ m.Update = &UpdateConfig{}
+ }
+ if err := m.Update.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Networks", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Networks = append(m.Networks, &NetworkAttachmentConfig{})
+ if err := m.Networks[len(m.Networks)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Endpoint", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Endpoint == nil {
+ m.Endpoint = &EndpointSpec{}
+ }
+ if err := m.Endpoint.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Rollback", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Rollback == nil {
+ m.Rollback = &UpdateConfig{}
+ }
+ if err := m.Rollback.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ReplicatedService) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ReplicatedService: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ReplicatedService: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Replicas", wireType)
+ }
+ m.Replicas = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Replicas |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GlobalService) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GlobalService: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GlobalService: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *TaskSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: TaskSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: TaskSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Container", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &ContainerSpec{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Runtime = &TaskSpec_Container{v}
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Resources", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Resources == nil {
+ m.Resources = &ResourceRequirements{}
+ }
+ if err := m.Resources.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Restart", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Restart == nil {
+ m.Restart = &RestartPolicy{}
+ }
+ if err := m.Restart.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Placement", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Placement == nil {
+ m.Placement = &Placement{}
+ }
+ if err := m.Placement.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LogDriver", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.LogDriver == nil {
+ m.LogDriver = &Driver{}
+ }
+ if err := m.LogDriver.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Networks", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Networks = append(m.Networks, &NetworkAttachmentConfig{})
+ if err := m.Networks[len(m.Networks)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Attachment", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &NetworkAttachmentSpec{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Runtime = &TaskSpec_Attachment{v}
+ iNdEx = postIndex
+ case 9:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ForceUpdate", wireType)
+ }
+ m.ForceUpdate = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ForceUpdate |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 10:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Generic", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &GenericRuntimeSpec{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Runtime = &TaskSpec_Generic{v}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GenericRuntimeSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GenericRuntimeSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GenericRuntimeSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Kind = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Payload == nil {
+ m.Payload = &google_protobuf3.Any{}
+ }
+ if err := m.Payload.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NetworkAttachmentSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NetworkAttachmentSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NetworkAttachmentSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ContainerID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ContainerID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ContainerSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ContainerSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ContainerSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Image", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Image = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Command", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Command = append(m.Command, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Args", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Args = append(m.Args, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Env", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Env = append(m.Env, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Dir", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Dir = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field User", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.User = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Mounts", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Mounts = append(m.Mounts, Mount{})
+ if err := m.Mounts[len(m.Mounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field StopGracePeriod", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.StopGracePeriod == nil {
+ m.StopGracePeriod = &google_protobuf1.Duration{}
+ }
+ if err := m.StopGracePeriod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 10:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PullOptions", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.PullOptions == nil {
+ m.PullOptions = &ContainerSpec_PullOptions{}
+ }
+ if err := m.PullOptions.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 11:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Groups", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Groups = append(m.Groups, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 12:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Secrets", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Secrets = append(m.Secrets, &SecretReference{})
+ if err := m.Secrets[len(m.Secrets)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 13:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TTY", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.TTY = bool(v != 0)
+ case 14:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Hostname", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Hostname = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 15:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field DNSConfig", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.DNSConfig == nil {
+ m.DNSConfig = &ContainerSpec_DNSConfig{}
+ }
+ if err := m.DNSConfig.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 16:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Healthcheck", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Healthcheck == nil {
+ m.Healthcheck = &HealthConfig{}
+ }
+ if err := m.Healthcheck.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 17:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Hosts", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Hosts = append(m.Hosts, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 18:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field OpenStdin", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.OpenStdin = bool(v != 0)
+ case 19:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ReadOnly", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.ReadOnly = bool(v != 0)
+ case 20:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field StopSignal", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.StopSignal = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 21:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Configs", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Configs = append(m.Configs, &ConfigReference{})
+ if err := m.Configs[len(m.Configs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 22:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Privileges", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Privileges == nil {
+ m.Privileges = &Privileges{}
+ }
+ if err := m.Privileges.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ContainerSpec_PullOptions) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PullOptions: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PullOptions: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 64:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RegistryAuth", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.RegistryAuth = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ContainerSpec_DNSConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: DNSConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: DNSConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Nameservers", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Nameservers = append(m.Nameservers, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Search", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Search = append(m.Search, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Options = append(m.Options, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *EndpointSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: EndpointSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: EndpointSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Mode", wireType)
+ }
+ m.Mode = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Mode |= (EndpointSpec_ResolutionMode(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Ports", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Ports = append(m.Ports, &PortConfig{})
+ if err := m.Ports[len(m.Ports)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NetworkSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NetworkSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NetworkSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Annotations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Annotations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field DriverConfig", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.DriverConfig == nil {
+ m.DriverConfig = &Driver{}
+ }
+ if err := m.DriverConfig.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Ipv6Enabled", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Ipv6Enabled = bool(v != 0)
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Internal", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Internal = bool(v != 0)
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IPAM", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.IPAM == nil {
+ m.IPAM = &IPAMOptions{}
+ }
+ if err := m.IPAM.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Attachable", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Attachable = bool(v != 0)
+ case 7:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Ingress", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Ingress = bool(v != 0)
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Network", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ConfigFrom = &NetworkSpec_Network{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ClusterSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ClusterSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ClusterSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Annotations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Annotations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field AcceptancePolicy", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.AcceptancePolicy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Orchestration", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Orchestration.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Raft", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Raft.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Dispatcher", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Dispatcher.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CAConfig", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.CAConfig.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TaskDefaults", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.TaskDefaults.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field EncryptionConfig", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.EncryptionConfig.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SecretSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SecretSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SecretSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Annotations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Annotations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Templating", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Templating == nil {
+ m.Templating = &Driver{}
+ }
+ if err := m.Templating.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ConfigSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ConfigSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ConfigSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Annotations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Annotations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Templating", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Templating == nil {
+ m.Templating = &Driver{}
+ }
+ if err := m.Templating.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipSpecs(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthSpecs
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipSpecs(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthSpecs
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowSpecs
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipSpecs(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthSpecs = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowSpecs = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("specs.proto", fileDescriptorSpecs) }
+
+var fileDescriptorSpecs = []byte{
+ // 1867 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x57, 0xcf, 0x73, 0x1b, 0x49,
+ 0x15, 0xb6, 0x6c, 0x59, 0x3f, 0xde, 0xc8, 0x89, 0xd2, 0x24, 0x61, 0xa2, 0xb0, 0xb2, 0xa2, 0x0d,
+ 0xc1, 0xcb, 0x16, 0x72, 0x61, 0xa8, 0x25, 0xbb, 0x61, 0x01, 0xc9, 0x12, 0x8e, 0x31, 0x76, 0x54,
+ 0x6d, 0x6f, 0x20, 0x27, 0x55, 0x7b, 0xa6, 0x3d, 0x9a, 0xf2, 0xa8, 0x7b, 0xe8, 0xe9, 0xd1, 0x96,
+ 0x6e, 0x1c, 0xb7, 0x72, 0xe5, 0xec, 0xe2, 0x40, 0xf1, 0xbf, 0xe4, 0x48, 0x71, 0xe2, 0xe4, 0x62,
+ 0xfd, 0x2f, 0x70, 0xe3, 0x02, 0xd5, 0x3d, 0x3d, 0xd2, 0x28, 0x19, 0x27, 0xa9, 0x22, 0x07, 0x6e,
+ 0xdd, 0xaf, 0xbf, 0xef, 0xcd, 0xeb, 0xd7, 0x5f, 0xf7, 0x7b, 0x03, 0x56, 0x14, 0x52, 0x27, 0xea,
+ 0x84, 0x82, 0x4b, 0x8e, 0x90, 0xcb, 0x9d, 0x73, 0x2a, 0x3a, 0xd1, 0xd7, 0x44, 0x4c, 0xce, 0x7d,
+ 0xd9, 0x99, 0xfe, 0xb8, 0x61, 0xc9, 0x59, 0x48, 0x0d, 0xa0, 0x71, 0xdb, 0xe3, 0x1e, 0xd7, 0xc3,
+ 0x6d, 0x35, 0x32, 0xd6, 0xa6, 0xc7, 0xb9, 0x17, 0xd0, 0x6d, 0x3d, 0x3b, 0x8d, 0xcf, 0xb6, 0xdd,
+ 0x58, 0x10, 0xe9, 0x73, 0x66, 0xd6, 0xef, 0xbd, 0xbe, 0x4e, 0xd8, 0x2c, 0x59, 0x6a, 0x5f, 0x14,
+ 0xa1, 0x72, 0xc4, 0x5d, 0x7a, 0x1c, 0x52, 0x07, 0xed, 0x81, 0x45, 0x18, 0xe3, 0x52, 0x73, 0x23,
+ 0xbb, 0xd0, 0x2a, 0x6c, 0x59, 0x3b, 0x9b, 0x9d, 0x37, 0x83, 0xea, 0x74, 0x17, 0xb0, 0x5e, 0xf1,
+ 0xd5, 0xe5, 0xe6, 0x0a, 0xce, 0x32, 0xd1, 0x2f, 0xa1, 0xe6, 0xd2, 0xc8, 0x17, 0xd4, 0x1d, 0x09,
+ 0x1e, 0x50, 0x7b, 0xb5, 0x55, 0xd8, 0xba, 0xb1, 0xf3, 0xbd, 0x3c, 0x4f, 0xea, 0xe3, 0x98, 0x07,
+ 0x14, 0x5b, 0x86, 0xa1, 0x26, 0x68, 0x0f, 0x60, 0x42, 0x27, 0xa7, 0x54, 0x44, 0x63, 0x3f, 0xb4,
+ 0xd7, 0x34, 0xfd, 0x07, 0xd7, 0xd1, 0x55, 0xec, 0x9d, 0xc3, 0x39, 0x1c, 0x67, 0xa8, 0xe8, 0x10,
+ 0x6a, 0x64, 0x4a, 0xfc, 0x80, 0x9c, 0xfa, 0x81, 0x2f, 0x67, 0x76, 0x51, 0xbb, 0xfa, 0xe4, 0xad,
+ 0xae, 0xba, 0x19, 0x02, 0x5e, 0xa2, 0xb7, 0x5d, 0x80, 0xc5, 0x87, 0xd0, 0x23, 0x28, 0x0f, 0x07,
+ 0x47, 0xfd, 0xfd, 0xa3, 0xbd, 0xfa, 0x4a, 0xe3, 0xde, 0xcb, 0x8b, 0xd6, 0x1d, 0xe5, 0x63, 0x01,
+ 0x18, 0x52, 0xe6, 0xfa, 0xcc, 0x43, 0x5b, 0x50, 0xe9, 0xee, 0xee, 0x0e, 0x86, 0x27, 0x83, 0x7e,
+ 0xbd, 0xd0, 0x68, 0xbc, 0xbc, 0x68, 0xdd, 0x5d, 0x06, 0x76, 0x1d, 0x87, 0x86, 0x92, 0xba, 0x8d,
+ 0xe2, 0x37, 0x7f, 0x69, 0xae, 0xb4, 0xbf, 0x29, 0x40, 0x2d, 0x1b, 0x04, 0x7a, 0x04, 0xa5, 0xee,
+ 0xee, 0xc9, 0xfe, 0xf3, 0x41, 0x7d, 0x65, 0x41, 0xcf, 0x22, 0xba, 0x8e, 0xf4, 0xa7, 0x14, 0x3d,
+ 0x84, 0xf5, 0x61, 0xf7, 0xab, 0xe3, 0x41, 0xbd, 0xb0, 0x08, 0x27, 0x0b, 0x1b, 0x92, 0x38, 0xd2,
+ 0xa8, 0x3e, 0xee, 0xee, 0x1f, 0xd5, 0x57, 0xf3, 0x51, 0x7d, 0x41, 0x7c, 0x66, 0x42, 0xf9, 0x73,
+ 0x11, 0xac, 0x63, 0x2a, 0xa6, 0xbe, 0xf3, 0x81, 0x25, 0xf2, 0x19, 0x14, 0x25, 0x89, 0xce, 0xb5,
+ 0x34, 0xac, 0x7c, 0x69, 0x9c, 0x90, 0xe8, 0x5c, 0x7d, 0xd4, 0xd0, 0x35, 0x5e, 0x29, 0x43, 0xd0,
+ 0x30, 0xf0, 0x1d, 0x22, 0xa9, 0xab, 0x95, 0x61, 0xed, 0x7c, 0x3f, 0x8f, 0x8d, 0xe7, 0x28, 0x13,
+ 0xff, 0xd3, 0x15, 0x9c, 0xa1, 0xa2, 0x27, 0x50, 0xf2, 0x02, 0x7e, 0x4a, 0x02, 0xad, 0x09, 0x6b,
+ 0xe7, 0x41, 0x9e, 0x93, 0x3d, 0x8d, 0x58, 0x38, 0x30, 0x14, 0xf4, 0x18, 0x4a, 0x71, 0xe8, 0x12,
+ 0x49, 0xed, 0x92, 0x26, 0xb7, 0xf2, 0xc8, 0x5f, 0x69, 0xc4, 0x2e, 0x67, 0x67, 0xbe, 0x87, 0x0d,
+ 0x1e, 0x1d, 0x40, 0x85, 0x51, 0xf9, 0x35, 0x17, 0xe7, 0x91, 0x5d, 0x6e, 0xad, 0x6d, 0x59, 0x3b,
+ 0x9f, 0xe6, 0x8a, 0x31, 0xc1, 0x74, 0xa5, 0x24, 0xce, 0x78, 0x42, 0x99, 0x4c, 0xdc, 0xf4, 0x56,
+ 0xed, 0x02, 0x9e, 0x3b, 0x40, 0x3f, 0x87, 0x0a, 0x65, 0x6e, 0xc8, 0x7d, 0x26, 0xed, 0xca, 0xf5,
+ 0x81, 0x0c, 0x0c, 0x46, 0x25, 0x13, 0xcf, 0x19, 0x8a, 0x2d, 0x78, 0x10, 0x9c, 0x12, 0xe7, 0xdc,
+ 0xae, 0xbe, 0xe7, 0x36, 0xe6, 0x8c, 0x5e, 0x09, 0x8a, 0x13, 0xee, 0xd2, 0xf6, 0x36, 0xdc, 0x7a,
+ 0x23, 0xd5, 0xa8, 0x01, 0x15, 0x93, 0xea, 0x44, 0x23, 0x45, 0x3c, 0x9f, 0xb7, 0x6f, 0xc2, 0xc6,
+ 0x52, 0x5a, 0xdb, 0x7f, 0x2f, 0x42, 0x25, 0x3d, 0x6b, 0xd4, 0x85, 0xaa, 0xc3, 0x99, 0x24, 0x3e,
+ 0xa3, 0xc2, 0xc8, 0x2b, 0xf7, 0x64, 0x76, 0x53, 0x90, 0x62, 0x3d, 0x5d, 0xc1, 0x0b, 0x16, 0xfa,
+ 0x35, 0x54, 0x05, 0x8d, 0x78, 0x2c, 0x1c, 0x1a, 0x19, 0x7d, 0x6d, 0xe5, 0x2b, 0x24, 0x01, 0x61,
+ 0xfa, 0x87, 0xd8, 0x17, 0x54, 0x65, 0x39, 0xc2, 0x0b, 0x2a, 0x7a, 0x02, 0x65, 0x41, 0x23, 0x49,
+ 0x84, 0x7c, 0x9b, 0x44, 0x70, 0x02, 0x19, 0xf2, 0xc0, 0x77, 0x66, 0x38, 0x65, 0xa0, 0x27, 0x50,
+ 0x0d, 0x03, 0xe2, 0x68, 0xaf, 0xf6, 0xba, 0xa6, 0x7f, 0x94, 0x47, 0x1f, 0xa6, 0x20, 0xbc, 0xc0,
+ 0xa3, 0xcf, 0x01, 0x02, 0xee, 0x8d, 0x5c, 0xe1, 0x4f, 0xa9, 0x30, 0x12, 0x6b, 0xe4, 0xb1, 0xfb,
+ 0x1a, 0x81, 0xab, 0x01, 0xf7, 0x92, 0x21, 0xda, 0xfb, 0x9f, 0xf4, 0x95, 0xd1, 0xd6, 0x01, 0x00,
+ 0x99, 0xaf, 0x1a, 0x75, 0x7d, 0xf2, 0x5e, 0xae, 0xcc, 0x89, 0x64, 0xe8, 0xe8, 0x01, 0xd4, 0xce,
+ 0xb8, 0x70, 0xe8, 0xc8, 0xdc, 0x9a, 0xaa, 0xd6, 0x84, 0xa5, 0x6d, 0x89, 0xbe, 0x50, 0x0f, 0xca,
+ 0x1e, 0x65, 0x54, 0xf8, 0x8e, 0x0d, 0xfa, 0x63, 0x8f, 0x72, 0x2f, 0x64, 0x02, 0xc1, 0x31, 0x93,
+ 0xfe, 0x84, 0x9a, 0x2f, 0xa5, 0xc4, 0x5e, 0x15, 0xca, 0x22, 0x59, 0x69, 0xff, 0x1e, 0xd0, 0x9b,
+ 0x58, 0x84, 0xa0, 0x78, 0xee, 0x33, 0x57, 0x0b, 0xab, 0x8a, 0xf5, 0x18, 0x75, 0xa0, 0x1c, 0x92,
+ 0x59, 0xc0, 0x89, 0x6b, 0xc4, 0x72, 0xbb, 0x93, 0xd4, 0xcb, 0x4e, 0x5a, 0x2f, 0x3b, 0x5d, 0x36,
+ 0xc3, 0x29, 0xa8, 0x7d, 0x00, 0x77, 0x72, 0xb7, 0x8c, 0x76, 0xa0, 0x36, 0x17, 0xe1, 0xc8, 0x37,
+ 0x1f, 0xe9, 0xdd, 0xbc, 0xba, 0xdc, 0xb4, 0xe6, 0x6a, 0xdd, 0xef, 0x63, 0x6b, 0x0e, 0xda, 0x77,
+ 0xdb, 0x7f, 0xaa, 0xc2, 0xc6, 0x92, 0x94, 0xd1, 0x6d, 0x58, 0xf7, 0x27, 0xc4, 0xa3, 0x26, 0xc6,
+ 0x64, 0x82, 0x06, 0x50, 0x0a, 0xc8, 0x29, 0x0d, 0x94, 0xa0, 0xd5, 0xa1, 0xfe, 0xe8, 0x9d, 0x77,
+ 0xa2, 0xf3, 0x5b, 0x8d, 0x1f, 0x30, 0x29, 0x66, 0xd8, 0x90, 0x91, 0x0d, 0x65, 0x87, 0x4f, 0x26,
+ 0x84, 0xa9, 0xa7, 0x73, 0x6d, 0xab, 0x8a, 0xd3, 0xa9, 0xca, 0x0c, 0x11, 0x5e, 0x64, 0x17, 0xb5,
+ 0x59, 0x8f, 0x51, 0x1d, 0xd6, 0x28, 0x9b, 0xda, 0xeb, 0xda, 0xa4, 0x86, 0xca, 0xe2, 0xfa, 0x89,
+ 0x22, 0xab, 0x58, 0x0d, 0x15, 0x2f, 0x8e, 0xa8, 0xb0, 0xcb, 0x49, 0x46, 0xd5, 0x18, 0xfd, 0x0c,
+ 0x4a, 0x13, 0x1e, 0x33, 0x19, 0xd9, 0x15, 0x1d, 0xec, 0xbd, 0xbc, 0x60, 0x0f, 0x15, 0xc2, 0x3c,
+ 0xed, 0x06, 0x8e, 0x06, 0x70, 0x2b, 0x92, 0x3c, 0x1c, 0x79, 0x82, 0x38, 0x74, 0x14, 0x52, 0xe1,
+ 0x73, 0xd7, 0x3c, 0x4d, 0xf7, 0xde, 0x38, 0x94, 0xbe, 0x69, 0x72, 0xf0, 0x4d, 0xc5, 0xd9, 0x53,
+ 0x94, 0xa1, 0x66, 0xa0, 0x21, 0xd4, 0xc2, 0x38, 0x08, 0x46, 0x3c, 0x4c, 0xaa, 0x54, 0xa2, 0xa7,
+ 0xf7, 0x48, 0xd9, 0x30, 0x0e, 0x82, 0x67, 0x09, 0x09, 0x5b, 0xe1, 0x62, 0x82, 0xee, 0x42, 0xc9,
+ 0x13, 0x3c, 0x0e, 0x23, 0xdb, 0xd2, 0xc9, 0x30, 0x33, 0xf4, 0x25, 0x94, 0x23, 0xea, 0x08, 0x2a,
+ 0x23, 0xbb, 0xa6, 0xb7, 0xfa, 0x71, 0xde, 0x47, 0x8e, 0x35, 0x04, 0xd3, 0x33, 0x2a, 0x28, 0x73,
+ 0x28, 0x4e, 0x39, 0xe8, 0x1e, 0xac, 0x49, 0x39, 0xb3, 0x37, 0x5a, 0x85, 0xad, 0x4a, 0xaf, 0x7c,
+ 0x75, 0xb9, 0xb9, 0x76, 0x72, 0xf2, 0x02, 0x2b, 0x9b, 0x7a, 0x41, 0xc7, 0x3c, 0x92, 0x8c, 0x4c,
+ 0xa8, 0x7d, 0x43, 0xe7, 0x76, 0x3e, 0x47, 0x2f, 0x00, 0x5c, 0x16, 0x8d, 0x1c, 0x7d, 0x65, 0xed,
+ 0x9b, 0x7a, 0x77, 0x9f, 0xbe, 0x7b, 0x77, 0xfd, 0xa3, 0x63, 0x53, 0x45, 0x36, 0xae, 0x2e, 0x37,
+ 0xab, 0xf3, 0x29, 0xae, 0xba, 0x2c, 0x4a, 0x86, 0xa8, 0x07, 0xd6, 0x98, 0x92, 0x40, 0x8e, 0x9d,
+ 0x31, 0x75, 0xce, 0xed, 0xfa, 0xf5, 0x65, 0xe1, 0xa9, 0x86, 0x19, 0x0f, 0x59, 0x92, 0x52, 0xb0,
+ 0x0a, 0x35, 0xb2, 0x6f, 0xe9, 0x5c, 0x25, 0x13, 0xf4, 0x11, 0x00, 0x0f, 0x29, 0x1b, 0x45, 0xd2,
+ 0xf5, 0x99, 0x8d, 0xd4, 0x96, 0x71, 0x55, 0x59, 0x8e, 0x95, 0x01, 0xdd, 0x57, 0x8f, 0x36, 0x71,
+ 0x47, 0x9c, 0x05, 0x33, 0xfb, 0x3b, 0x7a, 0xb5, 0xa2, 0x0c, 0xcf, 0x58, 0x30, 0x43, 0x9b, 0x60,
+ 0x69, 0x5d, 0x44, 0xbe, 0xc7, 0x48, 0x60, 0xdf, 0xd6, 0xf9, 0x00, 0x65, 0x3a, 0xd6, 0x16, 0x75,
+ 0x0e, 0x49, 0x36, 0x22, 0xfb, 0xce, 0xf5, 0xe7, 0x60, 0x82, 0x5d, 0x9c, 0x83, 0xe1, 0xa0, 0x5f,
+ 0x00, 0x84, 0xc2, 0x9f, 0xfa, 0x01, 0xf5, 0x68, 0x64, 0xdf, 0xd5, 0x9b, 0x6e, 0xe6, 0xbe, 0xd6,
+ 0x73, 0x14, 0xce, 0x30, 0x1a, 0x9f, 0x83, 0x95, 0xb9, 0x6d, 0xea, 0x96, 0x9c, 0xd3, 0x99, 0xb9,
+ 0xc0, 0x6a, 0xa8, 0x52, 0x32, 0x25, 0x41, 0x9c, 0x74, 0xc2, 0x55, 0x9c, 0x4c, 0xbe, 0x58, 0x7d,
+ 0x5c, 0x68, 0xec, 0x80, 0x95, 0x51, 0x1d, 0xfa, 0x18, 0x36, 0x04, 0xf5, 0xfc, 0x48, 0x8a, 0xd9,
+ 0x88, 0xc4, 0x72, 0x6c, 0xff, 0x4a, 0x13, 0x6a, 0xa9, 0xb1, 0x1b, 0xcb, 0x71, 0x63, 0x04, 0x8b,
+ 0xc3, 0x43, 0x2d, 0xb0, 0x94, 0x28, 0x22, 0x2a, 0xa6, 0x54, 0xa8, 0x6a, 0xab, 0x72, 0x9e, 0x35,
+ 0x29, 0xf1, 0x46, 0x94, 0x08, 0x67, 0xac, 0xdf, 0x8e, 0x2a, 0x36, 0x33, 0xf5, 0x18, 0xa4, 0x37,
+ 0xc4, 0x3c, 0x06, 0x66, 0xda, 0xfe, 0x57, 0x01, 0x6a, 0xd9, 0xa6, 0x01, 0xed, 0x26, 0xc5, 0x5e,
+ 0x6f, 0xe9, 0xc6, 0xce, 0xf6, 0xbb, 0x9a, 0x0c, 0x5d, 0x5a, 0x83, 0x58, 0x39, 0x3b, 0x54, 0xfd,
+ 0xbd, 0x26, 0xa3, 0x9f, 0xc2, 0x7a, 0xc8, 0x85, 0x4c, 0x9f, 0xb0, 0xfc, 0x04, 0x73, 0x91, 0x96,
+ 0xa2, 0x04, 0xdc, 0x1e, 0xc3, 0x8d, 0x65, 0x6f, 0xe8, 0x21, 0xac, 0x3d, 0xdf, 0x1f, 0xd6, 0x57,
+ 0x1a, 0xf7, 0x5f, 0x5e, 0xb4, 0xbe, 0xbb, 0xbc, 0xf8, 0xdc, 0x17, 0x32, 0x26, 0xc1, 0xfe, 0x10,
+ 0xfd, 0x10, 0xd6, 0xfb, 0x47, 0xc7, 0x18, 0xd7, 0x0b, 0x8d, 0xcd, 0x97, 0x17, 0xad, 0xfb, 0xcb,
+ 0x38, 0xb5, 0xc4, 0x63, 0xe6, 0x62, 0x7e, 0x3a, 0xef, 0x75, 0xff, 0xbd, 0x0a, 0x96, 0x79, 0xd9,
+ 0x3f, 0xf4, 0xef, 0xd0, 0x46, 0x52, 0xca, 0xd3, 0x2b, 0xbb, 0xfa, 0xce, 0x8a, 0x5e, 0x4b, 0x08,
+ 0xe6, 0x8c, 0x1f, 0x40, 0xcd, 0x0f, 0xa7, 0x9f, 0x8d, 0x28, 0x23, 0xa7, 0x81, 0x69, 0x7b, 0x2b,
+ 0xd8, 0x52, 0xb6, 0x41, 0x62, 0x52, 0xef, 0x85, 0xcf, 0x24, 0x15, 0xcc, 0x34, 0xb4, 0x15, 0x3c,
+ 0x9f, 0xa3, 0x2f, 0xa1, 0xe8, 0x87, 0x64, 0x62, 0xda, 0x90, 0xdc, 0x1d, 0xec, 0x0f, 0xbb, 0x87,
+ 0x46, 0x83, 0xbd, 0xca, 0xd5, 0xe5, 0x66, 0x51, 0x19, 0xb0, 0xa6, 0xa1, 0x66, 0xda, 0x09, 0xa8,
+ 0x2f, 0xe9, 0xb7, 0xbf, 0x82, 0x33, 0x16, 0xa5, 0x23, 0x9f, 0x79, 0x82, 0x46, 0x91, 0xae, 0x02,
+ 0x15, 0x9c, 0x4e, 0x51, 0x03, 0xca, 0xa6, 0x9f, 0xd0, 0x0d, 0x44, 0x55, 0xd5, 0x6a, 0x63, 0xe8,
+ 0x6d, 0x80, 0x95, 0x64, 0x63, 0x74, 0x26, 0xf8, 0xa4, 0xfd, 0x9f, 0x22, 0x58, 0xbb, 0x41, 0x1c,
+ 0x49, 0x53, 0x06, 0x3f, 0x58, 0xf2, 0x5f, 0xc0, 0x2d, 0xa2, 0x7f, 0xaf, 0x08, 0x53, 0x35, 0x45,
+ 0xb7, 0x69, 0xe6, 0x00, 0x1e, 0xe6, 0xba, 0x9b, 0x83, 0x93, 0x96, 0xae, 0x57, 0x52, 0x3e, 0xed,
+ 0x02, 0xae, 0x93, 0xd7, 0x56, 0xd0, 0x31, 0x6c, 0x70, 0xe1, 0x8c, 0x69, 0x24, 0x93, 0x4a, 0x64,
+ 0x7e, 0x47, 0x72, 0x7f, 0x54, 0x9f, 0x65, 0x81, 0xe6, 0x19, 0x4e, 0xa2, 0x5d, 0xf6, 0x81, 0x1e,
+ 0x43, 0x51, 0x90, 0xb3, 0xb4, 0xe5, 0xcc, 0xbd, 0x24, 0x98, 0x9c, 0xc9, 0x25, 0x17, 0x9a, 0x81,
+ 0x7e, 0x03, 0xe0, 0xfa, 0x51, 0x48, 0xa4, 0x33, 0xa6, 0xc2, 0x1c, 0x76, 0xee, 0x16, 0xfb, 0x73,
+ 0xd4, 0x92, 0x97, 0x0c, 0x1b, 0x1d, 0x40, 0xd5, 0x21, 0xa9, 0x5c, 0x4b, 0xd7, 0xff, 0xa3, 0xed,
+ 0x76, 0x8d, 0x8b, 0xba, 0x72, 0x71, 0x75, 0xb9, 0x59, 0x49, 0x2d, 0xb8, 0xe2, 0x10, 0x23, 0xdf,
+ 0x03, 0xd8, 0x50, 0xff, 0x6e, 0x23, 0x97, 0x9e, 0x91, 0x38, 0x90, 0x89, 0x4c, 0xae, 0x29, 0x2b,
+ 0xea, 0x47, 0xa0, 0x6f, 0x70, 0x26, 0xae, 0x9a, 0xcc, 0xd8, 0xd0, 0xef, 0xe0, 0x16, 0x65, 0x8e,
+ 0x98, 0x69, 0xb1, 0xa6, 0x11, 0x56, 0xae, 0xdf, 0xec, 0x60, 0x0e, 0x5e, 0xda, 0x6c, 0x9d, 0xbe,
+ 0x66, 0x6f, 0xff, 0xb5, 0x00, 0x90, 0x54, 0xea, 0x0f, 0x2b, 0x40, 0x04, 0x45, 0x97, 0x48, 0xa2,
+ 0x35, 0x57, 0xc3, 0x7a, 0x8c, 0xbe, 0x00, 0x90, 0x74, 0x12, 0x06, 0x44, 0xfa, 0xcc, 0x33, 0xb2,
+ 0x79, 0xdb, 0x73, 0x90, 0x41, 0xeb, 0x38, 0x93, 0x90, 0xff, 0xaf, 0xe3, 0xec, 0xd9, 0xaf, 0xbe,
+ 0x6d, 0xae, 0xfc, 0xe3, 0xdb, 0xe6, 0xca, 0x1f, 0xaf, 0x9a, 0x85, 0x57, 0x57, 0xcd, 0xc2, 0xdf,
+ 0xae, 0x9a, 0x85, 0x7f, 0x5e, 0x35, 0x0b, 0xa7, 0x25, 0xdd, 0xc3, 0xfd, 0xe4, 0xbf, 0x01, 0x00,
+ 0x00, 0xff, 0xff, 0x06, 0x93, 0x6e, 0xba, 0xfc, 0x12, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/specs.proto b/vendor/github.com/docker/swarmkit/api/specs.proto
new file mode 100644
index 0000000..13b52d4
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/specs.proto
@@ -0,0 +1,413 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "types.proto";
+import "gogoproto/gogo.proto";
+import "google/protobuf/duration.proto";
+import "google/protobuf/any.proto";
+
+// Specs are container objects for user provided input. All creations and
+// updates are done through spec types. As a convention, user input from a spec
+// is never touched in created objects. This allows one to verify that the
+// users intent has not been modified.
+//
+// Put differently, spec types can be said to represent the desired state of
+// the system. In situations where modifications need to be made to a
+// particular component, API objects will either contain a copy of the spec
+// component or a different representation to reflect allocation or resolution.
+
+message NodeSpec {
+ Annotations annotations = 1 [(gogoproto.nullable) = false];
+
+ enum Membership {
+ option (gogoproto.goproto_enum_prefix) = false;
+
+ PENDING = 0 [(gogoproto.enumvalue_customname) = "NodeMembershipPending"];
+ ACCEPTED = 1 [(gogoproto.enumvalue_customname) = "NodeMembershipAccepted"];
+ }
+
+ enum Availability {
+ option (gogoproto.goproto_enum_prefix) = false;
+
+ // Active nodes.
+ ACTIVE = 0 [(gogoproto.enumvalue_customname) = "NodeAvailabilityActive"];
+
+ // Paused nodes won't be considered by the scheduler, preventing any
+ // further task to run on them.
+ PAUSE = 1 [(gogoproto.enumvalue_customname) = "NodeAvailabilityPause"];
+
+ // Drained nodes are paused and any task already running on them will
+ // be evicted.
+ DRAIN = 2 [(gogoproto.enumvalue_customname) = "NodeAvailabilityDrain"];
+ }
+
+ // DesiredRole defines the role the node should have.
+ NodeRole desired_role = 2;
+
+ // Membership controls the admission of the node into the cluster.
+ Membership membership = 3;
+
+ // Availability allows a user to control the current scheduling status of a
+ // node.
+ Availability availability = 4;
+}
+
+// ServiceSpec defines the properties of a service.
+//
+// A service instructs the cluster in orchestrating repeated instances of a
+// template, implemented as tasks. Based on the number of instances, scheduling
+// strategy and restart policy, a number of application-level behaviors can be
+// defined.
+message ServiceSpec {
+ Annotations annotations = 1 [(gogoproto.nullable) = false];
+
+ // Task defines the task template this service will spawn.
+ TaskSpec task = 2 [(gogoproto.nullable) = false];
+
+ oneof mode {
+ ReplicatedService replicated = 3;
+ GlobalService global = 4;
+ }
+
+ // Update contains settings which affect updates.
+ UpdateConfig update = 6;
+
+ // Rollback contains settings which affect rollbacks of updates.
+ UpdateConfig rollback = 9;
+
+ // ServiceSpec.Networks has been deprecated and is replaced by
+ // Networks field in Task (TaskSpec.Networks).
+ // This field (ServiceSpec.Networks) is kept for compatibility.
+ // In case TaskSpec.Networks does not exist, ServiceSpec.Networks
+ // is still honored if it exists.
+ repeated NetworkAttachmentConfig networks = 7 [deprecated=true];
+
+ // Service endpoint specifies the user provided configuration
+ // to properly discover and load balance a service.
+ EndpointSpec endpoint = 8;
+}
+
+// ReplicatedService sets the reconciliation target to certain number of replicas.
+message ReplicatedService {
+ uint64 replicas = 1;
+}
+
+// GlobalService represents global service.
+message GlobalService {
+ // Empty message for now.
+}
+
+message TaskSpec {
+ oneof runtime {
+ NetworkAttachmentSpec attachment = 8;
+ ContainerSpec container = 1;
+ GenericRuntimeSpec generic = 10;
+ }
+
+ // Resource requirements for the container.
+ ResourceRequirements resources = 2;
+
+ // RestartPolicy specifies what to do when a task fails or finishes.
+ RestartPolicy restart = 4;
+
+ // Placement specifies node selection constraints
+ Placement placement = 5;
+
+ // LogDriver specifies the log driver to use for the task. Any runtime will
+ // direct logs into the specified driver for the duration of the task.
+ Driver log_driver = 6;
+
+ // Networks specifies the list of network attachment
+ // configurations (which specify the network and per-network
+ // aliases) that this task spec is bound to.
+ repeated NetworkAttachmentConfig networks = 7;
+
+ // ForceUpdate is a counter that triggers an update even if no relevant
+ // parameters have been changed. We do this to allow forced restarts
+ // using the same reconciliation-based mechanism that performs rolling
+ // updates.
+ uint64 force_update = 9;
+}
+
+message GenericRuntimeSpec {
+ string kind = 1;
+ google.protobuf.Any payload = 2;
+}
+
+// NetworkAttachmentSpec specifies runtime parameters required to attach
+// a container to a network.
+message NetworkAttachmentSpec {
+ // ContainerID specifies a unique ID of the container for which
+ // this attachment is for.
+ string container_id = 1;
+}
+
+
+// Container specifies runtime parameters for a container.
+message ContainerSpec {
+ // image defines the image reference, as specified in the
+ // distribution/reference package. This may include a registry host, name,
+ // tag or digest.
+ //
+ // The field will be directly passed to the engine pulling. Well-behaved
+ // service definitions will used immutable references, either through tags
+ // that don't change or verifiable digests.
+ string image = 1;
+
+ // Labels defines labels to be added to the container at creation time. If
+ // collisions with system labels occur, these labels will be overridden.
+ //
+ // This field *must* remain compatible with the Labels field of
+ // Annotations.
+ map<string, string> labels = 2;
+
+ // Command to run the the container. The first element is a path to the
+ // executable and the following elements are treated as arguments.
+ //
+ // If command is empty, execution will fall back to the image's entrypoint.
+ //
+ // Command should only be used when overriding entrypoint.
+ repeated string command = 3;
+
+ // Args specifies arguments provided to the image's entrypoint.
+ //
+ // If Command and Args are provided, Args will be appended to Command.
+ repeated string args = 4;
+
+ // Hostname specifies the hostname that will be set on containers created by docker swarm.
+ // All containers for a given service will have the same hostname
+ string hostname = 14;
+
+ // Env specifies the environment variables for the container in NAME=VALUE
+ // format. These must be compliant with [IEEE Std
+ // 1003.1-2001](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html).
+ repeated string env = 5;
+
+ // Dir defines the working directory to set for the container process.
+ string dir = 6;
+
+ // User specifies the user that should be employed to run the container.
+ //
+ // Note that the primary group may be specified by appending the group name
+ // or id to the user name, separated by a `:`. This syntax is
+ // `<user>:<group>`.
+ string user = 7;
+
+ // Groups specifies supplementary groups available to the user.
+ repeated string groups = 11;
+
+ // Privileges specifies security configuration/permissions.
+ Privileges privileges = 22;
+
+ // TTY declares that a TTY should be attached to the standard streams,
+ // including stdin if it is still open.
+ bool tty = 13 [(gogoproto.customname) = "TTY"];
+
+ // OpenStdin declares that the standard input (stdin) should be open.
+ bool open_stdin = 18;
+
+ // ReadOnly declares that the container root filesystem is read-only.
+ // This only impacts the root filesystem, not additional mounts (including
+ // tmpfs). For additional mounts that are not part of the initial rootfs,
+ // they will be decided by the modes passed in the mount definition.
+ bool read_only = 19;
+
+ // StopSignal defines the signal to stop the container.
+ string stop_signal = 20;
+
+ repeated Mount mounts = 8 [(gogoproto.nullable) = false];
+
+ // StopGracePeriod the grace period for stopping the container before
+ // forcefully killing the container.
+ // Note: Can't use stdduration here because this needs to be nullable.
+ google.protobuf.Duration stop_grace_period = 9;
+
+ // PullOptions allows one to parameterize an image pull.
+ message PullOptions {
+ // RegistryAuth is the registry auth token obtained from the client, required
+ // to pull private images. This is the unmodified JSON used as part of
+ // the `X-Registry-Auth` header.
+ // TODO(nishanttotla): This field will later be deprecated
+ string registry_auth = 64;
+ }
+
+ // PullOptions parameterize the behavior of image pulls.
+ PullOptions pull_options = 10;
+
+ // SecretReference contains references to zero or more secrets that
+ // will be exposed to the container.
+ repeated SecretReference secrets = 12;
+
+ // ConfigReference contains references to zero or more configs that
+ // will be exposed to the container.
+ repeated ConfigReference configs = 21;
+
+ // Hosts allow additional entries to be specified in /etc/hosts
+ // that associates IP addresses with hostnames.
+ // Detailed documentation is available in:
+ // http://man7.org/linux/man-pages/man5/hosts.5.html
+ // IP_address canonical_hostname [aliases...]
+ //
+ // The format of the Hosts in swarmkit follows the same as
+ // above.
+ // This is different from `docker run --add-host <hostname>:<ip>`
+ // where format is `<hostname>:<ip>`
+ repeated string hosts = 17;
+
+ // DNSConfig specifies DNS related configurations in resolver configuration file (resolv.conf)
+ // Detailed documentation is available in:
+ // http://man7.org/linux/man-pages/man5/resolv.conf.5.html
+ // TODO: domain is not supported yet
+ message DNSConfig {
+ // Nameservers specifies the IP addresses of the name servers
+ repeated string nameservers = 1;
+
+ // Search specifies the search list for host-name lookup
+ repeated string search = 2;
+
+ // Options allows certain internal resolver variables to be modified
+ repeated string options = 3;
+ }
+
+ // DNSConfig allows one to specify DNS related configuration in resolv.conf
+ DNSConfig dns_config = 15 [(gogoproto.customname) = "DNSConfig"];
+
+ // Healthcheck describes how to check the container is healthy. If the
+ // container is considered unhealthy, it will be destroyed, its creating
+ // task will exit and a new task will be rescheduled elsewhere. A container
+ // is considered unhealthy after `Retries` number of consecutive failures.
+ HealthConfig healthcheck = 16;
+}
+
+// EndpointSpec defines the properties that can be configured to
+// access and loadbalance the service.
+message EndpointSpec {
+ // ResolutionMode specifies the mode of resolution to use for
+ // internal loadbalancing between tasks which are all within
+ // the cluster. This is sometimes calls east-west data path.
+ enum ResolutionMode {
+ option (gogoproto.goproto_enum_prefix) = false;
+
+ // VIP resolution mode specifies that the
+ // service resolves to a logical IP and the requests
+ // are sent to that logical IP. Packets hitting that
+ // logical IP are load balanced to a chosen backend.
+ VIP = 0 [(gogoproto.enumvalue_customname) = "ResolutionModeVirtualIP"];
+
+ // DNSRR resolution mode specifies that the
+ // service directly gets resolved to one of the
+ // backend IP and the client directly initiates a
+ // request towards the actual backend. This requires
+ // that the client does not cache the DNS responses
+ // when the DNS response TTL is 0.
+ DNSRR = 1 [(gogoproto.enumvalue_customname) = "ResolutionModeDNSRoundRobin"];
+ }
+
+ ResolutionMode mode = 1;
+
+ // List of exposed ports that this service is accessible from
+ // external to the cluster.
+ repeated PortConfig ports = 2;
+}
+
+// NetworkSpec specifies user defined network parameters.
+message NetworkSpec {
+ Annotations annotations = 1 [(gogoproto.nullable) = false];
+
+ // DriverConfig specific configuration consumed by the network driver.
+ Driver driver_config = 2;
+
+ // IPv6Enabled enables support for IPv6 on the network.
+ bool ipv6_enabled = 3;
+
+ // internal restricts external access to the network. This may be
+ // accomplished by disabling the default gateway or through other means.
+ bool internal = 4;
+
+ IPAMOptions ipam = 5 [(gogoproto.customname) = "IPAM"];
+
+ // Attachable allows external(to swarm) entities to manually
+ // attach to this network. With this flag enabled, external
+ // entities such as containers running in an worker node in
+ // the cluster can manually attach to this network and access
+ // the services attached to this network. If this flag is not
+ // enabled(default case) no manual attachment to this network
+ // can happen.
+ bool attachable = 6;
+
+ // Ingress indicates this network will provide the routing-mesh.
+ // In older versions, the network providing the routing mesh was
+ // swarm internally created only and it was identified by the name
+ // "ingress" and the label "com.docker.swarm.internal": "true".
+ bool ingress = 7;
+
+ // ConfigFrom is the source of the configuration for this network.
+ oneof config_from {
+ // Network is the name of a network that provides the network
+ // specific configuration for this network, locally on the node
+ // where this network is being plumbed.
+ string network = 8;
+ }
+
+}
+
+// ClusterSpec specifies global cluster settings.
+message ClusterSpec {
+ Annotations annotations = 1 [(gogoproto.nullable) = false];
+
+ // DEPRECATED: AcceptancePolicy defines the certificate issuance policy.
+ // Acceptance policy is no longer customizable, and secrets have been
+ // replaced with join tokens.
+ AcceptancePolicy acceptance_policy = 2 [deprecated=true, (gogoproto.nullable) = false];
+
+ // Orchestration defines cluster-level orchestration settings.
+ OrchestrationConfig orchestration = 3 [(gogoproto.nullable) = false];
+
+ // Raft defines the cluster's raft settings.
+ RaftConfig raft = 4 [(gogoproto.nullable) = false];
+
+ // Dispatcher defines cluster-level dispatcher settings.
+ DispatcherConfig dispatcher = 5 [(gogoproto.nullable) = false];
+
+ // CAConfig defines cluster-level certificate authority settings.
+ CAConfig ca_config = 6 [(gogoproto.nullable) = false, (gogoproto.customname) = "CAConfig"];
+
+ // TaskDefaults specifies the default values to use for task creation.
+ TaskDefaults task_defaults = 7 [(gogoproto.nullable) = false];
+
+ // EncryptionConfig defines the cluster's encryption settings.
+ EncryptionConfig encryption_config = 8 [(gogoproto.nullable) = false];
+}
+
+// SecretSpec specifies a user-provided secret.
+message SecretSpec {
+ Annotations annotations = 1 [(gogoproto.nullable) = false];
+
+ // Data is the secret payload - the maximum size is 500KB (that is, 500*1024 bytes)
+ bytes data = 2;
+
+ // Templating controls whether and how to evaluate the secret payload as
+ // a template. If it is not set, no templating is used.
+ //
+ // The currently recognized values are:
+ // - golang: Go templating
+ Driver templating = 3;
+}
+
+// ConfigSpec specifies user-provided configuration files.
+message ConfigSpec {
+ Annotations annotations = 1 [(gogoproto.nullable) = false];
+
+ // Data is the config payload - the maximum size is 500KB (that is, 500*1024 bytes)
+ // TODO(aaronl): Do we want to revise this to include multiple payloads in a single
+ // ConfigSpec? Define this to be a tar? etc...
+ bytes data = 2;
+
+ // Templating controls whether and how to evaluate the secret payload as
+ // a template. If it is not set, no templating is used.
+ //
+ // The currently recognized values are:
+ // - golang: Go templating
+ Driver templating = 3;
+}
diff --git a/vendor/github.com/docker/swarmkit/api/storeobject.go b/vendor/github.com/docker/swarmkit/api/storeobject.go
new file mode 100644
index 0000000..48b50b7
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/storeobject.go
@@ -0,0 +1,108 @@
+package api
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/docker/go-events"
+)
+
+var (
+ errUnknownStoreAction = errors.New("unrecognized action type")
+ errConflictingFilters = errors.New("conflicting filters specified")
+ errNoKindSpecified = errors.New("no kind of object specified")
+ errUnrecognizedAction = errors.New("unrecognized action")
+)
+
+// StoreObject is an abstract object that can be handled by the store.
+type StoreObject interface {
+ GetID() string // Get ID
+ GetMeta() Meta // Retrieve metadata
+ SetMeta(Meta) // Set metadata
+ CopyStoreObject() StoreObject // Return a copy of this object
+ EventCreate() Event // Return a creation event
+ EventUpdate(oldObject StoreObject) Event // Return an update event
+ EventDelete() Event // Return a deletion event
+}
+
+// Event is the type used for events passed over watcher channels, and also
+// the type used to specify filtering in calls to Watch.
+type Event interface {
+ // TODO(stevvooe): Consider whether it makes sense to squish both the
+ // matcher type and the primary type into the same type. It might be better
+ // to build a matcher from an event prototype.
+
+ // Matches checks if this item in a watch queue Matches the event
+ // description.
+ Matches(events.Event) bool
+}
+
+func customIndexer(kind string, annotations *Annotations) (bool, [][]byte, error) {
+ var converted [][]byte
+
+ for _, entry := range annotations.Indices {
+ index := make([]byte, 0, len(kind)+1+len(entry.Key)+1+len(entry.Val)+1)
+ if kind != "" {
+ index = append(index, []byte(kind)...)
+ index = append(index, '|')
+ }
+ index = append(index, []byte(entry.Key)...)
+ index = append(index, '|')
+ index = append(index, []byte(entry.Val)...)
+ index = append(index, '\x00')
+ converted = append(converted, index)
+ }
+
+ // Add the null character as a terminator
+ return len(converted) != 0, converted, nil
+}
+
+func fromArgs(args ...interface{}) ([]byte, error) {
+ if len(args) != 1 {
+ return nil, fmt.Errorf("must provide only a single argument")
+ }
+ arg, ok := args[0].(string)
+ if !ok {
+ return nil, fmt.Errorf("argument must be a string: %#v", args[0])
+ }
+ // Add the null character as a terminator
+ arg += "\x00"
+ return []byte(arg), nil
+}
+
+func prefixFromArgs(args ...interface{}) ([]byte, error) {
+ val, err := fromArgs(args...)
+ if err != nil {
+ return nil, err
+ }
+
+ // Strip the null terminator, the rest is a prefix
+ n := len(val)
+ if n > 0 {
+ return val[:n-1], nil
+ }
+ return val, nil
+}
+
+func checkCustom(a1, a2 Annotations) bool {
+ if len(a1.Indices) == 1 {
+ for _, ind := range a2.Indices {
+ if ind.Key == a1.Indices[0].Key && ind.Val == a1.Indices[0].Val {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func checkCustomPrefix(a1, a2 Annotations) bool {
+ if len(a1.Indices) == 1 {
+ for _, ind := range a2.Indices {
+ if ind.Key == a1.Indices[0].Key && strings.HasPrefix(ind.Val, a1.Indices[0].Val) {
+ return true
+ }
+ }
+ }
+ return false
+}
diff --git a/vendor/github.com/docker/swarmkit/api/types.pb.go b/vendor/github.com/docker/swarmkit/api/types.pb.go
new file mode 100644
index 0000000..2befc03
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/types.pb.go
@@ -0,0 +1,17356 @@
+// Code generated by protoc-gen-gogo.
+// source: types.proto
+// DO NOT EDIT!
+
+/*
+ Package api is a generated protocol buffer package.
+
+ It is generated from these files:
+ types.proto
+ specs.proto
+ objects.proto
+ control.proto
+ dispatcher.proto
+ ca.proto
+ snapshot.proto
+ raft.proto
+ health.proto
+ resource.proto
+ logbroker.proto
+ watch.proto
+
+ It has these top-level messages:
+ Version
+ IndexEntry
+ Annotations
+ GenericString
+ GenericDiscrete
+ GenericResource
+ Resources
+ ResourceRequirements
+ Platform
+ PluginDescription
+ EngineDescription
+ NodeDescription
+ NodeTLSInfo
+ RaftMemberStatus
+ NodeStatus
+ Image
+ Mount
+ RestartPolicy
+ UpdateConfig
+ UpdateStatus
+ ContainerStatus
+ PortStatus
+ TaskStatus
+ NetworkAttachmentConfig
+ IPAMConfig
+ PortConfig
+ Driver
+ IPAMOptions
+ Peer
+ WeightedPeer
+ IssuanceStatus
+ AcceptancePolicy
+ ExternalCA
+ CAConfig
+ OrchestrationConfig
+ TaskDefaults
+ DispatcherConfig
+ RaftConfig
+ EncryptionConfig
+ SpreadOver
+ PlacementPreference
+ Placement
+ JoinTokens
+ RootCA
+ Certificate
+ EncryptionKey
+ ManagerStatus
+ FileTarget
+ SecretReference
+ ConfigReference
+ BlacklistedCertificate
+ HealthConfig
+ MaybeEncryptedRecord
+ RootRotation
+ Privileges
+ NodeSpec
+ ServiceSpec
+ ReplicatedService
+ GlobalService
+ TaskSpec
+ GenericRuntimeSpec
+ NetworkAttachmentSpec
+ ContainerSpec
+ EndpointSpec
+ NetworkSpec
+ ClusterSpec
+ SecretSpec
+ ConfigSpec
+ Meta
+ Node
+ Service
+ Endpoint
+ Task
+ NetworkAttachment
+ Network
+ Cluster
+ Secret
+ Config
+ Resource
+ Extension
+ GetNodeRequest
+ GetNodeResponse
+ ListNodesRequest
+ ListNodesResponse
+ UpdateNodeRequest
+ UpdateNodeResponse
+ RemoveNodeRequest
+ RemoveNodeResponse
+ GetTaskRequest
+ GetTaskResponse
+ RemoveTaskRequest
+ RemoveTaskResponse
+ ListTasksRequest
+ ListTasksResponse
+ CreateServiceRequest
+ CreateServiceResponse
+ GetServiceRequest
+ GetServiceResponse
+ UpdateServiceRequest
+ UpdateServiceResponse
+ RemoveServiceRequest
+ RemoveServiceResponse
+ ListServicesRequest
+ ListServicesResponse
+ CreateNetworkRequest
+ CreateNetworkResponse
+ GetNetworkRequest
+ GetNetworkResponse
+ RemoveNetworkRequest
+ RemoveNetworkResponse
+ ListNetworksRequest
+ ListNetworksResponse
+ GetClusterRequest
+ GetClusterResponse
+ ListClustersRequest
+ ListClustersResponse
+ KeyRotation
+ UpdateClusterRequest
+ UpdateClusterResponse
+ GetSecretRequest
+ GetSecretResponse
+ UpdateSecretRequest
+ UpdateSecretResponse
+ ListSecretsRequest
+ ListSecretsResponse
+ CreateSecretRequest
+ CreateSecretResponse
+ RemoveSecretRequest
+ RemoveSecretResponse
+ GetConfigRequest
+ GetConfigResponse
+ UpdateConfigRequest
+ UpdateConfigResponse
+ ListConfigsRequest
+ ListConfigsResponse
+ CreateConfigRequest
+ CreateConfigResponse
+ RemoveConfigRequest
+ RemoveConfigResponse
+ SessionRequest
+ SessionMessage
+ HeartbeatRequest
+ HeartbeatResponse
+ UpdateTaskStatusRequest
+ UpdateTaskStatusResponse
+ TasksRequest
+ TasksMessage
+ AssignmentsRequest
+ Assignment
+ AssignmentChange
+ AssignmentsMessage
+ NodeCertificateStatusRequest
+ NodeCertificateStatusResponse
+ IssueNodeCertificateRequest
+ IssueNodeCertificateResponse
+ GetRootCACertificateRequest
+ GetRootCACertificateResponse
+ GetUnlockKeyRequest
+ GetUnlockKeyResponse
+ StoreSnapshot
+ ClusterSnapshot
+ Snapshot
+ RaftMember
+ JoinRequest
+ JoinResponse
+ LeaveRequest
+ LeaveResponse
+ ProcessRaftMessageRequest
+ ProcessRaftMessageResponse
+ ResolveAddressRequest
+ ResolveAddressResponse
+ InternalRaftRequest
+ StoreAction
+ HealthCheckRequest
+ HealthCheckResponse
+ AttachNetworkRequest
+ AttachNetworkResponse
+ DetachNetworkRequest
+ DetachNetworkResponse
+ LogSubscriptionOptions
+ LogSelector
+ LogContext
+ LogAttr
+ LogMessage
+ SubscribeLogsRequest
+ SubscribeLogsMessage
+ ListenSubscriptionsRequest
+ SubscriptionMessage
+ PublishLogsMessage
+ PublishLogsResponse
+ Object
+ SelectBySlot
+ SelectByCustom
+ SelectBy
+ WatchRequest
+ WatchMessage
+*/
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_protobuf "github.com/gogo/protobuf/types"
+import google_protobuf1 "github.com/gogo/protobuf/types"
+import _ "github.com/gogo/protobuf/gogoproto"
+
+import os "os"
+import time "time"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import github_com_gogo_protobuf_types "github.com/gogo/protobuf/types"
+
+import strings "strings"
+import reflect "reflect"
+import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+var _ = time.Kitchen
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+// TaskState enumerates the states that a task progresses through within an
+// agent. States are designed to be monotonically increasing, such that if two
+// states are seen by a task, the greater of the new represents the true state.
+type TaskState int32
+
+const (
+ TaskStateNew TaskState = 0
+ TaskStatePending TaskState = 64
+ TaskStateAssigned TaskState = 192
+ TaskStateAccepted TaskState = 256
+ TaskStatePreparing TaskState = 320
+ TaskStateReady TaskState = 384
+ TaskStateStarting TaskState = 448
+ TaskStateRunning TaskState = 512
+ TaskStateCompleted TaskState = 576
+ TaskStateShutdown TaskState = 640
+ TaskStateFailed TaskState = 704
+ TaskStateRejected TaskState = 768
+ TaskStateOrphaned TaskState = 832
+)
+
+var TaskState_name = map[int32]string{
+ 0: "NEW",
+ 64: "PENDING",
+ 192: "ASSIGNED",
+ 256: "ACCEPTED",
+ 320: "PREPARING",
+ 384: "READY",
+ 448: "STARTING",
+ 512: "RUNNING",
+ 576: "COMPLETE",
+ 640: "SHUTDOWN",
+ 704: "FAILED",
+ 768: "REJECTED",
+ 832: "ORPHANED",
+}
+var TaskState_value = map[string]int32{
+ "NEW": 0,
+ "PENDING": 64,
+ "ASSIGNED": 192,
+ "ACCEPTED": 256,
+ "PREPARING": 320,
+ "READY": 384,
+ "STARTING": 448,
+ "RUNNING": 512,
+ "COMPLETE": 576,
+ "SHUTDOWN": 640,
+ "FAILED": 704,
+ "REJECTED": 768,
+ "ORPHANED": 832,
+}
+
+func (x TaskState) String() string {
+ return proto.EnumName(TaskState_name, int32(x))
+}
+func (TaskState) EnumDescriptor() ([]byte, []int) { return fileDescriptorTypes, []int{0} }
+
+type NodeRole int32
+
+const (
+ NodeRoleWorker NodeRole = 0
+ NodeRoleManager NodeRole = 1
+)
+
+var NodeRole_name = map[int32]string{
+ 0: "WORKER",
+ 1: "MANAGER",
+}
+var NodeRole_value = map[string]int32{
+ "WORKER": 0,
+ "MANAGER": 1,
+}
+
+func (x NodeRole) String() string {
+ return proto.EnumName(NodeRole_name, int32(x))
+}
+func (NodeRole) EnumDescriptor() ([]byte, []int) { return fileDescriptorTypes, []int{1} }
+
+type RaftMemberStatus_Reachability int32
+
+const (
+ // Unknown indicates that the manager state cannot be resolved
+ RaftMemberStatus_UNKNOWN RaftMemberStatus_Reachability = 0
+ // Unreachable indicates that the node cannot be contacted by other
+ // raft cluster members.
+ RaftMemberStatus_UNREACHABLE RaftMemberStatus_Reachability = 1
+ // Reachable indicates that the node is healthy and reachable
+ // by other members.
+ RaftMemberStatus_REACHABLE RaftMemberStatus_Reachability = 2
+)
+
+var RaftMemberStatus_Reachability_name = map[int32]string{
+ 0: "UNKNOWN",
+ 1: "UNREACHABLE",
+ 2: "REACHABLE",
+}
+var RaftMemberStatus_Reachability_value = map[string]int32{
+ "UNKNOWN": 0,
+ "UNREACHABLE": 1,
+ "REACHABLE": 2,
+}
+
+func (x RaftMemberStatus_Reachability) String() string {
+ return proto.EnumName(RaftMemberStatus_Reachability_name, int32(x))
+}
+func (RaftMemberStatus_Reachability) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{13, 0}
+}
+
+// TODO(aluzzardi) These should be using `gogoproto.enumvalue_customname`.
+type NodeStatus_State int32
+
+const (
+ // Unknown indicates the node state cannot be resolved.
+ NodeStatus_UNKNOWN NodeStatus_State = 0
+ // Down indicates the node is down.
+ NodeStatus_DOWN NodeStatus_State = 1
+ // Ready indicates the node is ready to accept tasks.
+ NodeStatus_READY NodeStatus_State = 2
+ // Disconnected indicates the node is currently trying to find new manager.
+ NodeStatus_DISCONNECTED NodeStatus_State = 3
+)
+
+var NodeStatus_State_name = map[int32]string{
+ 0: "UNKNOWN",
+ 1: "DOWN",
+ 2: "READY",
+ 3: "DISCONNECTED",
+}
+var NodeStatus_State_value = map[string]int32{
+ "UNKNOWN": 0,
+ "DOWN": 1,
+ "READY": 2,
+ "DISCONNECTED": 3,
+}
+
+func (x NodeStatus_State) String() string {
+ return proto.EnumName(NodeStatus_State_name, int32(x))
+}
+func (NodeStatus_State) EnumDescriptor() ([]byte, []int) { return fileDescriptorTypes, []int{14, 0} }
+
+type Mount_MountType int32
+
+const (
+ MountTypeBind Mount_MountType = 0
+ MountTypeVolume Mount_MountType = 1
+ MountTypeTmpfs Mount_MountType = 2
+)
+
+var Mount_MountType_name = map[int32]string{
+ 0: "BIND",
+ 1: "VOLUME",
+ 2: "TMPFS",
+}
+var Mount_MountType_value = map[string]int32{
+ "BIND": 0,
+ "VOLUME": 1,
+ "TMPFS": 2,
+}
+
+func (x Mount_MountType) String() string {
+ return proto.EnumName(Mount_MountType_name, int32(x))
+}
+func (Mount_MountType) EnumDescriptor() ([]byte, []int) { return fileDescriptorTypes, []int{16, 0} }
+
+type Mount_BindOptions_MountPropagation int32
+
+const (
+ MountPropagationRPrivate Mount_BindOptions_MountPropagation = 0
+ MountPropagationPrivate Mount_BindOptions_MountPropagation = 1
+ MountPropagationRShared Mount_BindOptions_MountPropagation = 2
+ MountPropagationShared Mount_BindOptions_MountPropagation = 3
+ MountPropagationRSlave Mount_BindOptions_MountPropagation = 4
+ MountPropagationSlave Mount_BindOptions_MountPropagation = 5
+)
+
+var Mount_BindOptions_MountPropagation_name = map[int32]string{
+ 0: "RPRIVATE",
+ 1: "PRIVATE",
+ 2: "RSHARED",
+ 3: "SHARED",
+ 4: "RSLAVE",
+ 5: "SLAVE",
+}
+var Mount_BindOptions_MountPropagation_value = map[string]int32{
+ "RPRIVATE": 0,
+ "PRIVATE": 1,
+ "RSHARED": 2,
+ "SHARED": 3,
+ "RSLAVE": 4,
+ "SLAVE": 5,
+}
+
+func (x Mount_BindOptions_MountPropagation) String() string {
+ return proto.EnumName(Mount_BindOptions_MountPropagation_name, int32(x))
+}
+func (Mount_BindOptions_MountPropagation) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{16, 0, 0}
+}
+
+type RestartPolicy_RestartCondition int32
+
+const (
+ RestartOnNone RestartPolicy_RestartCondition = 0
+ RestartOnFailure RestartPolicy_RestartCondition = 1
+ RestartOnAny RestartPolicy_RestartCondition = 2
+)
+
+var RestartPolicy_RestartCondition_name = map[int32]string{
+ 0: "NONE",
+ 1: "ON_FAILURE",
+ 2: "ANY",
+}
+var RestartPolicy_RestartCondition_value = map[string]int32{
+ "NONE": 0,
+ "ON_FAILURE": 1,
+ "ANY": 2,
+}
+
+func (x RestartPolicy_RestartCondition) String() string {
+ return proto.EnumName(RestartPolicy_RestartCondition_name, int32(x))
+}
+func (RestartPolicy_RestartCondition) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{17, 0}
+}
+
+type UpdateConfig_FailureAction int32
+
+const (
+ UpdateConfig_PAUSE UpdateConfig_FailureAction = 0
+ UpdateConfig_CONTINUE UpdateConfig_FailureAction = 1
+ UpdateConfig_ROLLBACK UpdateConfig_FailureAction = 2
+)
+
+var UpdateConfig_FailureAction_name = map[int32]string{
+ 0: "PAUSE",
+ 1: "CONTINUE",
+ 2: "ROLLBACK",
+}
+var UpdateConfig_FailureAction_value = map[string]int32{
+ "PAUSE": 0,
+ "CONTINUE": 1,
+ "ROLLBACK": 2,
+}
+
+func (x UpdateConfig_FailureAction) String() string {
+ return proto.EnumName(UpdateConfig_FailureAction_name, int32(x))
+}
+func (UpdateConfig_FailureAction) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{18, 0}
+}
+
+// UpdateOrder controls the order of operations when rolling out an
+// updated task. Either the old task is shut down before the new task
+// is started, or the new task is started before the old task is shut
+// down.
+type UpdateConfig_UpdateOrder int32
+
+const (
+ UpdateConfig_STOP_FIRST UpdateConfig_UpdateOrder = 0
+ UpdateConfig_START_FIRST UpdateConfig_UpdateOrder = 1
+)
+
+var UpdateConfig_UpdateOrder_name = map[int32]string{
+ 0: "STOP_FIRST",
+ 1: "START_FIRST",
+}
+var UpdateConfig_UpdateOrder_value = map[string]int32{
+ "STOP_FIRST": 0,
+ "START_FIRST": 1,
+}
+
+func (x UpdateConfig_UpdateOrder) String() string {
+ return proto.EnumName(UpdateConfig_UpdateOrder_name, int32(x))
+}
+func (UpdateConfig_UpdateOrder) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{18, 1}
+}
+
+type UpdateStatus_UpdateState int32
+
+const (
+ UpdateStatus_UNKNOWN UpdateStatus_UpdateState = 0
+ UpdateStatus_UPDATING UpdateStatus_UpdateState = 1
+ UpdateStatus_PAUSED UpdateStatus_UpdateState = 2
+ UpdateStatus_COMPLETED UpdateStatus_UpdateState = 3
+ UpdateStatus_ROLLBACK_STARTED UpdateStatus_UpdateState = 4
+ UpdateStatus_ROLLBACK_PAUSED UpdateStatus_UpdateState = 5
+ UpdateStatus_ROLLBACK_COMPLETED UpdateStatus_UpdateState = 6
+)
+
+var UpdateStatus_UpdateState_name = map[int32]string{
+ 0: "UNKNOWN",
+ 1: "UPDATING",
+ 2: "PAUSED",
+ 3: "COMPLETED",
+ 4: "ROLLBACK_STARTED",
+ 5: "ROLLBACK_PAUSED",
+ 6: "ROLLBACK_COMPLETED",
+}
+var UpdateStatus_UpdateState_value = map[string]int32{
+ "UNKNOWN": 0,
+ "UPDATING": 1,
+ "PAUSED": 2,
+ "COMPLETED": 3,
+ "ROLLBACK_STARTED": 4,
+ "ROLLBACK_PAUSED": 5,
+ "ROLLBACK_COMPLETED": 6,
+}
+
+func (x UpdateStatus_UpdateState) String() string {
+ return proto.EnumName(UpdateStatus_UpdateState_name, int32(x))
+}
+func (UpdateStatus_UpdateState) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{19, 0}
+}
+
+// AddressFamily specifies the network address family that
+// this IPAMConfig belongs to.
+type IPAMConfig_AddressFamily int32
+
+const (
+ IPAMConfig_UNKNOWN IPAMConfig_AddressFamily = 0
+ IPAMConfig_IPV4 IPAMConfig_AddressFamily = 4
+ IPAMConfig_IPV6 IPAMConfig_AddressFamily = 6
+)
+
+var IPAMConfig_AddressFamily_name = map[int32]string{
+ 0: "UNKNOWN",
+ 4: "IPV4",
+ 6: "IPV6",
+}
+var IPAMConfig_AddressFamily_value = map[string]int32{
+ "UNKNOWN": 0,
+ "IPV4": 4,
+ "IPV6": 6,
+}
+
+func (x IPAMConfig_AddressFamily) String() string {
+ return proto.EnumName(IPAMConfig_AddressFamily_name, int32(x))
+}
+func (IPAMConfig_AddressFamily) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{24, 0}
+}
+
+type PortConfig_Protocol int32
+
+const (
+ ProtocolTCP PortConfig_Protocol = 0
+ ProtocolUDP PortConfig_Protocol = 1
+)
+
+var PortConfig_Protocol_name = map[int32]string{
+ 0: "TCP",
+ 1: "UDP",
+}
+var PortConfig_Protocol_value = map[string]int32{
+ "TCP": 0,
+ "UDP": 1,
+}
+
+func (x PortConfig_Protocol) String() string {
+ return proto.EnumName(PortConfig_Protocol_name, int32(x))
+}
+func (PortConfig_Protocol) EnumDescriptor() ([]byte, []int) { return fileDescriptorTypes, []int{25, 0} }
+
+// PublishMode controls how ports are published on the swarm.
+type PortConfig_PublishMode int32
+
+const (
+ // PublishModeIngress exposes the port across the cluster on all nodes.
+ PublishModeIngress PortConfig_PublishMode = 0
+ // PublishModeHost exposes the port on just the target host. If the
+ // published port is undefined, an ephemeral port will be allocated. If
+ // the published port is defined, the node will attempt to allocate it,
+ // erroring the task if it fails.
+ PublishModeHost PortConfig_PublishMode = 1
+)
+
+var PortConfig_PublishMode_name = map[int32]string{
+ 0: "INGRESS",
+ 1: "HOST",
+}
+var PortConfig_PublishMode_value = map[string]int32{
+ "INGRESS": 0,
+ "HOST": 1,
+}
+
+func (x PortConfig_PublishMode) String() string {
+ return proto.EnumName(PortConfig_PublishMode_name, int32(x))
+}
+func (PortConfig_PublishMode) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{25, 1}
+}
+
+type IssuanceStatus_State int32
+
+const (
+ IssuanceStateUnknown IssuanceStatus_State = 0
+ // A new certificate should be issued
+ IssuanceStateRenew IssuanceStatus_State = 1
+ // Certificate is pending acceptance
+ IssuanceStatePending IssuanceStatus_State = 2
+ // successful completion certificate issuance
+ IssuanceStateIssued IssuanceStatus_State = 3
+ // Certificate issuance failed
+ IssuanceStateFailed IssuanceStatus_State = 4
+ // Signals workers to renew their certificate. From the CA's perspective
+ // this is equivalent to IssuanceStateIssued: a noop.
+ IssuanceStateRotate IssuanceStatus_State = 5
+)
+
+var IssuanceStatus_State_name = map[int32]string{
+ 0: "UNKNOWN",
+ 1: "RENEW",
+ 2: "PENDING",
+ 3: "ISSUED",
+ 4: "FAILED",
+ 5: "ROTATE",
+}
+var IssuanceStatus_State_value = map[string]int32{
+ "UNKNOWN": 0,
+ "RENEW": 1,
+ "PENDING": 2,
+ "ISSUED": 3,
+ "FAILED": 4,
+ "ROTATE": 5,
+}
+
+func (x IssuanceStatus_State) String() string {
+ return proto.EnumName(IssuanceStatus_State_name, int32(x))
+}
+func (IssuanceStatus_State) EnumDescriptor() ([]byte, []int) { return fileDescriptorTypes, []int{30, 0} }
+
+type ExternalCA_CAProtocol int32
+
+const (
+ ExternalCA_CAProtocolCFSSL ExternalCA_CAProtocol = 0
+)
+
+var ExternalCA_CAProtocol_name = map[int32]string{
+ 0: "CFSSL",
+}
+var ExternalCA_CAProtocol_value = map[string]int32{
+ "CFSSL": 0,
+}
+
+func (x ExternalCA_CAProtocol) String() string {
+ return proto.EnumName(ExternalCA_CAProtocol_name, int32(x))
+}
+func (ExternalCA_CAProtocol) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{32, 0}
+}
+
+// Encryption algorithm that can implemented using this key
+type EncryptionKey_Algorithm int32
+
+const (
+ AES_128_GCM EncryptionKey_Algorithm = 0
+)
+
+var EncryptionKey_Algorithm_name = map[int32]string{
+ 0: "AES_128_GCM",
+}
+var EncryptionKey_Algorithm_value = map[string]int32{
+ "AES_128_GCM": 0,
+}
+
+func (x EncryptionKey_Algorithm) String() string {
+ return proto.EnumName(EncryptionKey_Algorithm_name, int32(x))
+}
+func (EncryptionKey_Algorithm) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{45, 0}
+}
+
+type MaybeEncryptedRecord_Algorithm int32
+
+const (
+ MaybeEncryptedRecord_NotEncrypted MaybeEncryptedRecord_Algorithm = 0
+ MaybeEncryptedRecord_NACLSecretboxSalsa20Poly1305 MaybeEncryptedRecord_Algorithm = 1
+)
+
+var MaybeEncryptedRecord_Algorithm_name = map[int32]string{
+ 0: "NONE",
+ 1: "SECRETBOX_SALSA20_POLY1305",
+}
+var MaybeEncryptedRecord_Algorithm_value = map[string]int32{
+ "NONE": 0,
+ "SECRETBOX_SALSA20_POLY1305": 1,
+}
+
+func (x MaybeEncryptedRecord_Algorithm) String() string {
+ return proto.EnumName(MaybeEncryptedRecord_Algorithm_name, int32(x))
+}
+func (MaybeEncryptedRecord_Algorithm) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{52, 0}
+}
+
+// Version tracks the last time an object in the store was updated.
+type Version struct {
+ Index uint64 `protobuf:"varint,1,opt,name=index,proto3" json:"index,omitempty"`
+}
+
+func (m *Version) Reset() { *m = Version{} }
+func (*Version) ProtoMessage() {}
+func (*Version) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{0} }
+
+type IndexEntry struct {
+ Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
+ Val string `protobuf:"bytes,2,opt,name=val,proto3" json:"val,omitempty"`
+}
+
+func (m *IndexEntry) Reset() { *m = IndexEntry{} }
+func (*IndexEntry) ProtoMessage() {}
+func (*IndexEntry) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{1} }
+
+// Annotations provide useful information to identify API objects. They are
+// common to all API specs.
+type Annotations struct {
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ Labels map[string]string `protobuf:"bytes,2,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ // Indices provides keys and values for indexing this object.
+ // A single key may have multiple values.
+ Indices []IndexEntry `protobuf:"bytes,4,rep,name=indices" json:"indices"`
+}
+
+func (m *Annotations) Reset() { *m = Annotations{} }
+func (*Annotations) ProtoMessage() {}
+func (*Annotations) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{2} }
+
+type GenericString struct {
+ Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
+ Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *GenericString) Reset() { *m = GenericString{} }
+func (*GenericString) ProtoMessage() {}
+func (*GenericString) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{3} }
+
+type GenericDiscrete struct {
+ Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
+ Value int64 `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *GenericDiscrete) Reset() { *m = GenericDiscrete{} }
+func (*GenericDiscrete) ProtoMessage() {}
+func (*GenericDiscrete) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{4} }
+
+type GenericResource struct {
+ // Types that are valid to be assigned to Resource:
+ // *GenericResource_Str
+ // *GenericResource_Discrete
+ Resource isGenericResource_Resource `protobuf_oneof:"resource"`
+}
+
+func (m *GenericResource) Reset() { *m = GenericResource{} }
+func (*GenericResource) ProtoMessage() {}
+func (*GenericResource) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{5} }
+
+type isGenericResource_Resource interface {
+ isGenericResource_Resource()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type GenericResource_Str struct {
+ Str *GenericString `protobuf:"bytes,1,opt,name=str,oneof"`
+}
+type GenericResource_Discrete struct {
+ Discrete *GenericDiscrete `protobuf:"bytes,2,opt,name=discrete,oneof"`
+}
+
+func (*GenericResource_Str) isGenericResource_Resource() {}
+func (*GenericResource_Discrete) isGenericResource_Resource() {}
+
+func (m *GenericResource) GetResource() isGenericResource_Resource {
+ if m != nil {
+ return m.Resource
+ }
+ return nil
+}
+
+func (m *GenericResource) GetStr() *GenericString {
+ if x, ok := m.GetResource().(*GenericResource_Str); ok {
+ return x.Str
+ }
+ return nil
+}
+
+func (m *GenericResource) GetDiscrete() *GenericDiscrete {
+ if x, ok := m.GetResource().(*GenericResource_Discrete); ok {
+ return x.Discrete
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*GenericResource) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _GenericResource_OneofMarshaler, _GenericResource_OneofUnmarshaler, _GenericResource_OneofSizer, []interface{}{
+ (*GenericResource_Str)(nil),
+ (*GenericResource_Discrete)(nil),
+ }
+}
+
+func _GenericResource_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*GenericResource)
+ // resource
+ switch x := m.Resource.(type) {
+ case *GenericResource_Str:
+ _ = b.EncodeVarint(1<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Str); err != nil {
+ return err
+ }
+ case *GenericResource_Discrete:
+ _ = b.EncodeVarint(2<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Discrete); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("GenericResource.Resource has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _GenericResource_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*GenericResource)
+ switch tag {
+ case 1: // resource.str
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(GenericString)
+ err := b.DecodeMessage(msg)
+ m.Resource = &GenericResource_Str{msg}
+ return true, err
+ case 2: // resource.discrete
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(GenericDiscrete)
+ err := b.DecodeMessage(msg)
+ m.Resource = &GenericResource_Discrete{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _GenericResource_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*GenericResource)
+ // resource
+ switch x := m.Resource.(type) {
+ case *GenericResource_Str:
+ s := proto.Size(x.Str)
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *GenericResource_Discrete:
+ s := proto.Size(x.Discrete)
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type Resources struct {
+ // Amount of CPUs (e.g. 2000000000 = 2 CPU cores)
+ NanoCPUs int64 `protobuf:"varint,1,opt,name=nano_cpus,json=nanoCpus,proto3" json:"nano_cpus,omitempty"`
+ // Amount of memory in bytes.
+ MemoryBytes int64 `protobuf:"varint,2,opt,name=memory_bytes,json=memoryBytes,proto3" json:"memory_bytes,omitempty"`
+ // User specified resource (e.g: bananas=2;apple={red,yellow,green})
+ Generic []*GenericResource `protobuf:"bytes,3,rep,name=generic" json:"generic,omitempty"`
+}
+
+func (m *Resources) Reset() { *m = Resources{} }
+func (*Resources) ProtoMessage() {}
+func (*Resources) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{6} }
+
+type ResourceRequirements struct {
+ Limits *Resources `protobuf:"bytes,1,opt,name=limits" json:"limits,omitempty"`
+ Reservations *Resources `protobuf:"bytes,2,opt,name=reservations" json:"reservations,omitempty"`
+}
+
+func (m *ResourceRequirements) Reset() { *m = ResourceRequirements{} }
+func (*ResourceRequirements) ProtoMessage() {}
+func (*ResourceRequirements) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{7} }
+
+type Platform struct {
+ // Architecture (e.g. x86_64)
+ Architecture string `protobuf:"bytes,1,opt,name=architecture,proto3" json:"architecture,omitempty"`
+ // Operating System (e.g. linux)
+ OS string `protobuf:"bytes,2,opt,name=os,proto3" json:"os,omitempty"`
+}
+
+func (m *Platform) Reset() { *m = Platform{} }
+func (*Platform) ProtoMessage() {}
+func (*Platform) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{8} }
+
+// PluginDescription describes an engine plugin.
+type PluginDescription struct {
+ // Type of plugin. Canonical values for existing types are
+ // Volume, Network, and Authorization. More types could be
+ // supported in the future.
+ Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
+ // Name of the plugin
+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
+}
+
+func (m *PluginDescription) Reset() { *m = PluginDescription{} }
+func (*PluginDescription) ProtoMessage() {}
+func (*PluginDescription) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{9} }
+
+type EngineDescription struct {
+ // Docker daemon version running on the node.
+ EngineVersion string `protobuf:"bytes,1,opt,name=engine_version,json=engineVersion,proto3" json:"engine_version,omitempty"`
+ // Labels attached to the engine.
+ Labels map[string]string `protobuf:"bytes,2,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ // Volume, Network, and Auth plugins
+ Plugins []PluginDescription `protobuf:"bytes,3,rep,name=plugins" json:"plugins"`
+}
+
+func (m *EngineDescription) Reset() { *m = EngineDescription{} }
+func (*EngineDescription) ProtoMessage() {}
+func (*EngineDescription) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{10} }
+
+type NodeDescription struct {
+ // Hostname of the node as reported by the agent.
+ // This is different from spec.meta.name which is user-defined.
+ Hostname string `protobuf:"bytes,1,opt,name=hostname,proto3" json:"hostname,omitempty"`
+ // Platform of the node.
+ Platform *Platform `protobuf:"bytes,2,opt,name=platform" json:"platform,omitempty"`
+ // Total resources on the node.
+ Resources *Resources `protobuf:"bytes,3,opt,name=resources" json:"resources,omitempty"`
+ // Information about the Docker Engine on the node.
+ Engine *EngineDescription `protobuf:"bytes,4,opt,name=engine" json:"engine,omitempty"`
+ // Information on the node's TLS setup
+ TLSInfo *NodeTLSInfo `protobuf:"bytes,5,opt,name=tls_info,json=tlsInfo" json:"tls_info,omitempty"`
+}
+
+func (m *NodeDescription) Reset() { *m = NodeDescription{} }
+func (*NodeDescription) ProtoMessage() {}
+func (*NodeDescription) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{11} }
+
+type NodeTLSInfo struct {
+ // Information about which root certs the node trusts
+ TrustRoot []byte `protobuf:"bytes,1,opt,name=trust_root,json=trustRoot,proto3" json:"trust_root,omitempty"`
+ // Information about the node's current TLS certificate
+ CertIssuerSubject []byte `protobuf:"bytes,2,opt,name=cert_issuer_subject,json=certIssuerSubject,proto3" json:"cert_issuer_subject,omitempty"`
+ CertIssuerPublicKey []byte `protobuf:"bytes,3,opt,name=cert_issuer_public_key,json=certIssuerPublicKey,proto3" json:"cert_issuer_public_key,omitempty"`
+}
+
+func (m *NodeTLSInfo) Reset() { *m = NodeTLSInfo{} }
+func (*NodeTLSInfo) ProtoMessage() {}
+func (*NodeTLSInfo) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{12} }
+
+type RaftMemberStatus struct {
+ Leader bool `protobuf:"varint,1,opt,name=leader,proto3" json:"leader,omitempty"`
+ Reachability RaftMemberStatus_Reachability `protobuf:"varint,2,opt,name=reachability,proto3,enum=docker.swarmkit.v1.RaftMemberStatus_Reachability" json:"reachability,omitempty"`
+ Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"`
+}
+
+func (m *RaftMemberStatus) Reset() { *m = RaftMemberStatus{} }
+func (*RaftMemberStatus) ProtoMessage() {}
+func (*RaftMemberStatus) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{13} }
+
+type NodeStatus struct {
+ State NodeStatus_State `protobuf:"varint,1,opt,name=state,proto3,enum=docker.swarmkit.v1.NodeStatus_State" json:"state,omitempty"`
+ Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
+ // Addr is the node's IP address as observed by the manager
+ Addr string `protobuf:"bytes,3,opt,name=addr,proto3" json:"addr,omitempty"`
+}
+
+func (m *NodeStatus) Reset() { *m = NodeStatus{} }
+func (*NodeStatus) ProtoMessage() {}
+func (*NodeStatus) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{14} }
+
+type Image struct {
+ // reference is a docker image reference. This can include a rpository, tag
+ // or be fully qualified witha digest. The format is specified in the
+ // distribution/reference package.
+ Reference string `protobuf:"bytes,1,opt,name=reference,proto3" json:"reference,omitempty"`
+}
+
+func (m *Image) Reset() { *m = Image{} }
+func (*Image) ProtoMessage() {}
+func (*Image) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{15} }
+
+// Mount describes volume mounts for a container.
+//
+// The Mount type follows the structure of the mount syscall, including a type,
+// source, target. Top-level flags, such as writable, are common to all kinds
+// of mounts, where we also provide options that are specific to a type of
+// mount. This corresponds to flags and data, respectively, in the syscall.
+type Mount struct {
+ // Type defines the nature of the mount.
+ Type Mount_MountType `protobuf:"varint,1,opt,name=type,proto3,enum=docker.swarmkit.v1.Mount_MountType" json:"type,omitempty"`
+ // Source specifies the name of the mount. Depending on mount type, this
+ // may be a volume name or a host path, or even ignored.
+ Source string `protobuf:"bytes,2,opt,name=source,proto3" json:"source,omitempty"`
+ // Target path in container
+ Target string `protobuf:"bytes,3,opt,name=target,proto3" json:"target,omitempty"`
+ // ReadOnly should be set to true if the mount should not be writable.
+ ReadOnly bool `protobuf:"varint,4,opt,name=readonly,proto3" json:"readonly,omitempty"`
+ // BindOptions configures properties of a bind mount type.
+ //
+ // For mounts of type bind, the source must be an absolute host path.
+ BindOptions *Mount_BindOptions `protobuf:"bytes,5,opt,name=bind_options,json=bindOptions" json:"bind_options,omitempty"`
+ // VolumeOptions configures the properties specific to a volume mount type.
+ //
+ // For mounts of type volume, the source will be used as the volume name.
+ VolumeOptions *Mount_VolumeOptions `protobuf:"bytes,6,opt,name=volume_options,json=volumeOptions" json:"volume_options,omitempty"`
+ // TmpfsOptions allows one to set options for mounting a temporary
+ // filesystem.
+ //
+ // The source field will be ignored when using mounts of type tmpfs.
+ TmpfsOptions *Mount_TmpfsOptions `protobuf:"bytes,7,opt,name=tmpfs_options,json=tmpfsOptions" json:"tmpfs_options,omitempty"`
+}
+
+func (m *Mount) Reset() { *m = Mount{} }
+func (*Mount) ProtoMessage() {}
+func (*Mount) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{16} }
+
+// BindOptions specifies options that are specific to a bind mount.
+type Mount_BindOptions struct {
+ // Propagation mode of mount.
+ Propagation Mount_BindOptions_MountPropagation `protobuf:"varint,1,opt,name=propagation,proto3,enum=docker.swarmkit.v1.Mount_BindOptions_MountPropagation" json:"propagation,omitempty"`
+}
+
+func (m *Mount_BindOptions) Reset() { *m = Mount_BindOptions{} }
+func (*Mount_BindOptions) ProtoMessage() {}
+func (*Mount_BindOptions) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{16, 0} }
+
+// VolumeOptions contains parameters for mounting the volume.
+type Mount_VolumeOptions struct {
+ // nocopy prevents automatic copying of data to the volume with data from target
+ NoCopy bool `protobuf:"varint,1,opt,name=nocopy,proto3" json:"nocopy,omitempty"`
+ // labels to apply to the volume if creating
+ Labels map[string]string `protobuf:"bytes,2,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ // DriverConfig specifies the options that may be passed to the driver
+ // if the volume is created.
+ //
+ // If this is empty, no volume will be created if the volume is missing.
+ DriverConfig *Driver `protobuf:"bytes,3,opt,name=driver_config,json=driverConfig" json:"driver_config,omitempty"`
+}
+
+func (m *Mount_VolumeOptions) Reset() { *m = Mount_VolumeOptions{} }
+func (*Mount_VolumeOptions) ProtoMessage() {}
+func (*Mount_VolumeOptions) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{16, 1} }
+
+type Mount_TmpfsOptions struct {
+ // Size sets the size of the tmpfs, in bytes.
+ //
+ // This will be converted to an operating system specific value
+ // depending on the host. For example, on linux, it will be convered to
+ // use a 'k', 'm' or 'g' syntax. BSD, though not widely supported with
+ // docker, uses a straight byte value.
+ //
+ // Percentages are not supported.
+ SizeBytes int64 `protobuf:"varint,1,opt,name=size_bytes,json=sizeBytes,proto3" json:"size_bytes,omitempty"`
+ // Mode of the tmpfs upon creation
+ Mode os.FileMode `protobuf:"varint,2,opt,name=mode,proto3,customtype=os.FileMode" json:"mode"`
+}
+
+func (m *Mount_TmpfsOptions) Reset() { *m = Mount_TmpfsOptions{} }
+func (*Mount_TmpfsOptions) ProtoMessage() {}
+func (*Mount_TmpfsOptions) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{16, 2} }
+
+type RestartPolicy struct {
+ Condition RestartPolicy_RestartCondition `protobuf:"varint,1,opt,name=condition,proto3,enum=docker.swarmkit.v1.RestartPolicy_RestartCondition" json:"condition,omitempty"`
+ // Delay between restart attempts
+ // Note: can't use stdduration because this field needs to be nullable.
+ Delay *google_protobuf1.Duration `protobuf:"bytes,2,opt,name=delay" json:"delay,omitempty"`
+ // MaxAttempts is the maximum number of restarts to attempt on an
+ // instance before giving up. Ignored if 0.
+ MaxAttempts uint64 `protobuf:"varint,3,opt,name=max_attempts,json=maxAttempts,proto3" json:"max_attempts,omitempty"`
+ // Window is the time window used to evaluate the restart policy.
+ // The time window is unbounded if this is 0.
+ // Note: can't use stdduration because this field needs to be nullable.
+ Window *google_protobuf1.Duration `protobuf:"bytes,4,opt,name=window" json:"window,omitempty"`
+}
+
+func (m *RestartPolicy) Reset() { *m = RestartPolicy{} }
+func (*RestartPolicy) ProtoMessage() {}
+func (*RestartPolicy) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{17} }
+
+// UpdateConfig specifies the rate and policy of updates.
+// TODO(aluzzardi): Consider making this a oneof with RollingStrategy and LockstepStrategy.
+type UpdateConfig struct {
+ // Maximum number of tasks to be updated in one iteration.
+ // 0 means unlimited parallelism.
+ Parallelism uint64 `protobuf:"varint,1,opt,name=parallelism,proto3" json:"parallelism,omitempty"`
+ // Amount of time between updates.
+ Delay time.Duration `protobuf:"bytes,2,opt,name=delay,stdduration" json:"delay"`
+ // FailureAction is the action to take when an update failures.
+ FailureAction UpdateConfig_FailureAction `protobuf:"varint,3,opt,name=failure_action,json=failureAction,proto3,enum=docker.swarmkit.v1.UpdateConfig_FailureAction" json:"failure_action,omitempty"`
+ // Monitor indicates how long to monitor a task for failure after it is
+ // created. If the task fails by ending up in one of the states
+ // REJECTED, COMPLETED, or FAILED, within Monitor from its creation,
+ // this counts as a failure. If it fails after Monitor, it does not
+ // count as a failure. If Monitor is unspecified, a default value will
+ // be used.
+ // Note: can't use stdduration because this field needs to be nullable.
+ Monitor *google_protobuf1.Duration `protobuf:"bytes,4,opt,name=monitor" json:"monitor,omitempty"`
+ // MaxFailureRatio is the fraction of tasks that may fail during
+ // an update before the failure action is invoked. Any task created by
+ // the current update which ends up in one of the states REJECTED,
+ // COMPLETED or FAILED within Monitor from its creation counts as a
+ // failure. The number of failures is divided by the number of tasks
+ // being updated, and if this fraction is greater than
+ // MaxFailureRatio, the failure action is invoked.
+ //
+ // If the failure action is CONTINUE, there is no effect.
+ // If the failure action is PAUSE, no more tasks will be updated until
+ // another update is started.
+ // If the failure action is ROLLBACK, the orchestrator will attempt to
+ // roll back to the previous service spec. If the MaxFailureRatio
+ // threshold is hit during the rollback, the rollback will pause.
+ MaxFailureRatio float32 `protobuf:"fixed32,5,opt,name=max_failure_ratio,json=maxFailureRatio,proto3" json:"max_failure_ratio,omitempty"`
+ Order UpdateConfig_UpdateOrder `protobuf:"varint,6,opt,name=order,proto3,enum=docker.swarmkit.v1.UpdateConfig_UpdateOrder" json:"order,omitempty"`
+}
+
+func (m *UpdateConfig) Reset() { *m = UpdateConfig{} }
+func (*UpdateConfig) ProtoMessage() {}
+func (*UpdateConfig) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{18} }
+
+// UpdateStatus is the status of an update in progress.
+type UpdateStatus struct {
+ // State is the state of this update. It indicates whether the
+ // update is in progress, completed, paused, rolling back, or
+ // finished rolling back.
+ State UpdateStatus_UpdateState `protobuf:"varint,1,opt,name=state,proto3,enum=docker.swarmkit.v1.UpdateStatus_UpdateState" json:"state,omitempty"`
+ // StartedAt is the time at which the update was started.
+ // Note: can't use stdtime because this field is nullable.
+ StartedAt *google_protobuf.Timestamp `protobuf:"bytes,2,opt,name=started_at,json=startedAt" json:"started_at,omitempty"`
+ // CompletedAt is the time at which the update completed successfully,
+ // paused, or finished rolling back.
+ // Note: can't use stdtime because this field is nullable.
+ CompletedAt *google_protobuf.Timestamp `protobuf:"bytes,3,opt,name=completed_at,json=completedAt" json:"completed_at,omitempty"`
+ // Message explains how the update got into its current state. For
+ // example, if the update is paused, it will explain what is preventing
+ // the update from proceeding (typically the failure of a task to start up
+ // when OnFailure is PAUSE).
+ Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"`
+}
+
+func (m *UpdateStatus) Reset() { *m = UpdateStatus{} }
+func (*UpdateStatus) ProtoMessage() {}
+func (*UpdateStatus) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{19} }
+
+// Container specific status.
+type ContainerStatus struct {
+ ContainerID string `protobuf:"bytes,1,opt,name=container_id,json=containerId,proto3" json:"container_id,omitempty"`
+ PID int32 `protobuf:"varint,2,opt,name=pid,proto3" json:"pid,omitempty"`
+ ExitCode int32 `protobuf:"varint,3,opt,name=exit_code,json=exitCode,proto3" json:"exit_code,omitempty"`
+}
+
+func (m *ContainerStatus) Reset() { *m = ContainerStatus{} }
+func (*ContainerStatus) ProtoMessage() {}
+func (*ContainerStatus) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{20} }
+
+// PortStatus specifies the actual allocated runtime state of a list
+// of port configs.
+type PortStatus struct {
+ Ports []*PortConfig `protobuf:"bytes,1,rep,name=ports" json:"ports,omitempty"`
+}
+
+func (m *PortStatus) Reset() { *m = PortStatus{} }
+func (*PortStatus) ProtoMessage() {}
+func (*PortStatus) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{21} }
+
+type TaskStatus struct {
+ // Note: can't use stdtime because this field is nullable.
+ Timestamp *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=timestamp" json:"timestamp,omitempty"`
+ // State expresses the current state of the task.
+ State TaskState `protobuf:"varint,2,opt,name=state,proto3,enum=docker.swarmkit.v1.TaskState" json:"state,omitempty"`
+ // Message reports a message for the task status. This should provide a
+ // human readable message that can point to how the task actually arrived
+ // at a current state.
+ //
+ // As a convention, we place the a small message here that led to the
+ // current state. For example, if the task is in ready, because it was
+ // prepared, we'd place "prepared" in this field. If we skipped preparation
+ // because the task is prepared, we would put "already prepared" in this
+ // field.
+ Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"`
+ // Err is set if the task is in an error state.
+ //
+ // The following states should report a companion error:
+ //
+ // FAILED, REJECTED
+ //
+ // TODO(stevvooe) Integrate this field with the error interface.
+ Err string `protobuf:"bytes,4,opt,name=err,proto3" json:"err,omitempty"`
+ // Container status contains container specific status information.
+ //
+ // Types that are valid to be assigned to RuntimeStatus:
+ // *TaskStatus_Container
+ RuntimeStatus isTaskStatus_RuntimeStatus `protobuf_oneof:"runtime_status"`
+ // HostPorts provides a list of ports allocated at the host
+ // level.
+ PortStatus *PortStatus `protobuf:"bytes,6,opt,name=port_status,json=portStatus" json:"port_status,omitempty"`
+}
+
+func (m *TaskStatus) Reset() { *m = TaskStatus{} }
+func (*TaskStatus) ProtoMessage() {}
+func (*TaskStatus) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{22} }
+
+type isTaskStatus_RuntimeStatus interface {
+ isTaskStatus_RuntimeStatus()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type TaskStatus_Container struct {
+ Container *ContainerStatus `protobuf:"bytes,5,opt,name=container,oneof"`
+}
+
+func (*TaskStatus_Container) isTaskStatus_RuntimeStatus() {}
+
+func (m *TaskStatus) GetRuntimeStatus() isTaskStatus_RuntimeStatus {
+ if m != nil {
+ return m.RuntimeStatus
+ }
+ return nil
+}
+
+func (m *TaskStatus) GetContainer() *ContainerStatus {
+ if x, ok := m.GetRuntimeStatus().(*TaskStatus_Container); ok {
+ return x.Container
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*TaskStatus) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _TaskStatus_OneofMarshaler, _TaskStatus_OneofUnmarshaler, _TaskStatus_OneofSizer, []interface{}{
+ (*TaskStatus_Container)(nil),
+ }
+}
+
+func _TaskStatus_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*TaskStatus)
+ // runtime_status
+ switch x := m.RuntimeStatus.(type) {
+ case *TaskStatus_Container:
+ _ = b.EncodeVarint(5<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Container); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("TaskStatus.RuntimeStatus has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _TaskStatus_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*TaskStatus)
+ switch tag {
+ case 5: // runtime_status.container
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(ContainerStatus)
+ err := b.DecodeMessage(msg)
+ m.RuntimeStatus = &TaskStatus_Container{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _TaskStatus_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*TaskStatus)
+ // runtime_status
+ switch x := m.RuntimeStatus.(type) {
+ case *TaskStatus_Container:
+ s := proto.Size(x.Container)
+ n += proto.SizeVarint(5<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// NetworkAttachmentConfig specifies how a service should be attached to a particular network.
+//
+// For now, this is a simple struct, but this can include future information
+// instructing Swarm on how this service should work on the particular
+// network.
+type NetworkAttachmentConfig struct {
+ // Target specifies the target network for attachment. This value must be a
+ // network ID.
+ Target string `protobuf:"bytes,1,opt,name=target,proto3" json:"target,omitempty"`
+ // Aliases specifies a list of discoverable alternate names for the service on this Target.
+ Aliases []string `protobuf:"bytes,2,rep,name=aliases" json:"aliases,omitempty"`
+ // Addresses specifies a list of ipv4 and ipv6 addresses
+ // preferred. If these addresses are not available then the
+ // attachment might fail.
+ Addresses []string `protobuf:"bytes,3,rep,name=addresses" json:"addresses,omitempty"`
+ // DriverAttachmentOpts is a map of driver attachment options for the network target
+ DriverAttachmentOpts map[string]string `protobuf:"bytes,4,rep,name=driver_attachment_opts,json=driverAttachmentOpts" json:"driver_attachment_opts,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+}
+
+func (m *NetworkAttachmentConfig) Reset() { *m = NetworkAttachmentConfig{} }
+func (*NetworkAttachmentConfig) ProtoMessage() {}
+func (*NetworkAttachmentConfig) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{23} }
+
+// IPAMConfig specifies parameters for IP Address Management.
+type IPAMConfig struct {
+ Family IPAMConfig_AddressFamily `protobuf:"varint,1,opt,name=family,proto3,enum=docker.swarmkit.v1.IPAMConfig_AddressFamily" json:"family,omitempty"`
+ // Subnet defines a network as a CIDR address (ie network and mask
+ // 192.168.0.1/24).
+ Subnet string `protobuf:"bytes,2,opt,name=subnet,proto3" json:"subnet,omitempty"`
+ // Range defines the portion of the subnet to allocate to tasks. This is
+ // defined as a subnet within the primary subnet.
+ Range string `protobuf:"bytes,3,opt,name=range,proto3" json:"range,omitempty"`
+ // Gateway address within the subnet.
+ Gateway string `protobuf:"bytes,4,opt,name=gateway,proto3" json:"gateway,omitempty"`
+ // Reserved is a list of address from the master pool that should *not* be
+ // allocated. These addresses may have already been allocated or may be
+ // reserved for another allocation manager.
+ Reserved map[string]string `protobuf:"bytes,5,rep,name=reserved" json:"reserved,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+}
+
+func (m *IPAMConfig) Reset() { *m = IPAMConfig{} }
+func (*IPAMConfig) ProtoMessage() {}
+func (*IPAMConfig) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{24} }
+
+// PortConfig specifies an exposed port which can be
+// addressed using the given name. This can be later queried
+// using a service discovery api or a DNS SRV query. The node
+// port specifies a port that can be used to address this
+// service external to the cluster by sending a connection
+// request to this port to any node on the cluster.
+type PortConfig struct {
+ // Name for the port. If provided the port information can
+ // be queried using the name as in a DNS SRV query.
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ // Protocol for the port which is exposed.
+ Protocol PortConfig_Protocol `protobuf:"varint,2,opt,name=protocol,proto3,enum=docker.swarmkit.v1.PortConfig_Protocol" json:"protocol,omitempty"`
+ // The port which the application is exposing and is bound to.
+ TargetPort uint32 `protobuf:"varint,3,opt,name=target_port,json=targetPort,proto3" json:"target_port,omitempty"`
+ // PublishedPort specifies the port on which the service is exposed. If
+ // specified, the port must be within the available range. If not specified
+ // (value is zero), an available port is automatically assigned.
+ PublishedPort uint32 `protobuf:"varint,4,opt,name=published_port,json=publishedPort,proto3" json:"published_port,omitempty"`
+ // PublishMode controls how the port is published.
+ PublishMode PortConfig_PublishMode `protobuf:"varint,5,opt,name=publish_mode,json=publishMode,proto3,enum=docker.swarmkit.v1.PortConfig_PublishMode" json:"publish_mode,omitempty"`
+}
+
+func (m *PortConfig) Reset() { *m = PortConfig{} }
+func (*PortConfig) ProtoMessage() {}
+func (*PortConfig) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{25} }
+
+// Driver is a generic driver type to be used throughout the API. For now, a
+// driver is simply a name and set of options. The field contents depend on the
+// target use case and driver application. For example, a network driver may
+// have different rules than a volume driver.
+type Driver struct {
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ Options map[string]string `protobuf:"bytes,2,rep,name=options" json:"options,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+}
+
+func (m *Driver) Reset() { *m = Driver{} }
+func (*Driver) ProtoMessage() {}
+func (*Driver) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{26} }
+
+type IPAMOptions struct {
+ Driver *Driver `protobuf:"bytes,1,opt,name=driver" json:"driver,omitempty"`
+ Configs []*IPAMConfig `protobuf:"bytes,3,rep,name=configs" json:"configs,omitempty"`
+}
+
+func (m *IPAMOptions) Reset() { *m = IPAMOptions{} }
+func (*IPAMOptions) ProtoMessage() {}
+func (*IPAMOptions) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{27} }
+
+// Peer should be used anywhere where we are describing a remote peer.
+type Peer struct {
+ NodeID string `protobuf:"bytes,1,opt,name=node_id,json=nodeId,proto3" json:"node_id,omitempty"`
+ Addr string `protobuf:"bytes,2,opt,name=addr,proto3" json:"addr,omitempty"`
+}
+
+func (m *Peer) Reset() { *m = Peer{} }
+func (*Peer) ProtoMessage() {}
+func (*Peer) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{28} }
+
+// WeightedPeer should be used anywhere where we are describing a remote peer
+// with a weight.
+type WeightedPeer struct {
+ Peer *Peer `protobuf:"bytes,1,opt,name=peer" json:"peer,omitempty"`
+ Weight int64 `protobuf:"varint,2,opt,name=weight,proto3" json:"weight,omitempty"`
+}
+
+func (m *WeightedPeer) Reset() { *m = WeightedPeer{} }
+func (*WeightedPeer) ProtoMessage() {}
+func (*WeightedPeer) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{29} }
+
+type IssuanceStatus struct {
+ State IssuanceStatus_State `protobuf:"varint,1,opt,name=state,proto3,enum=docker.swarmkit.v1.IssuanceStatus_State" json:"state,omitempty"`
+ // Err is set if the Certificate Issuance is in an error state.
+ // The following states should report a companion error:
+ // FAILED
+ Err string `protobuf:"bytes,2,opt,name=err,proto3" json:"err,omitempty"`
+}
+
+func (m *IssuanceStatus) Reset() { *m = IssuanceStatus{} }
+func (*IssuanceStatus) ProtoMessage() {}
+func (*IssuanceStatus) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{30} }
+
+type AcceptancePolicy struct {
+ Policies []*AcceptancePolicy_RoleAdmissionPolicy `protobuf:"bytes,1,rep,name=policies" json:"policies,omitempty"`
+}
+
+func (m *AcceptancePolicy) Reset() { *m = AcceptancePolicy{} }
+func (*AcceptancePolicy) ProtoMessage() {}
+func (*AcceptancePolicy) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{31} }
+
+type AcceptancePolicy_RoleAdmissionPolicy struct {
+ Role NodeRole `protobuf:"varint,1,opt,name=role,proto3,enum=docker.swarmkit.v1.NodeRole" json:"role,omitempty"`
+ // Autoaccept controls which roles' certificates are automatically
+ // issued without administrator intervention.
+ Autoaccept bool `protobuf:"varint,2,opt,name=autoaccept,proto3" json:"autoaccept,omitempty"`
+ // Secret represents a user-provided string that is necessary for new
+ // nodes to join the cluster
+ Secret *AcceptancePolicy_RoleAdmissionPolicy_Secret `protobuf:"bytes,3,opt,name=secret" json:"secret,omitempty"`
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy) Reset() { *m = AcceptancePolicy_RoleAdmissionPolicy{} }
+func (*AcceptancePolicy_RoleAdmissionPolicy) ProtoMessage() {}
+func (*AcceptancePolicy_RoleAdmissionPolicy) Descriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{31, 0}
+}
+
+type AcceptancePolicy_RoleAdmissionPolicy_Secret struct {
+ // The actual content (possibly hashed)
+ Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
+ // The type of hash we are using, or "plaintext"
+ Alg string `protobuf:"bytes,2,opt,name=alg,proto3" json:"alg,omitempty"`
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy_Secret) Reset() {
+ *m = AcceptancePolicy_RoleAdmissionPolicy_Secret{}
+}
+func (*AcceptancePolicy_RoleAdmissionPolicy_Secret) ProtoMessage() {}
+func (*AcceptancePolicy_RoleAdmissionPolicy_Secret) Descriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{31, 0, 0}
+}
+
+type ExternalCA struct {
+ // Protocol is the protocol used by this external CA.
+ Protocol ExternalCA_CAProtocol `protobuf:"varint,1,opt,name=protocol,proto3,enum=docker.swarmkit.v1.ExternalCA_CAProtocol" json:"protocol,omitempty"`
+ // URL is the URL where the external CA can be reached.
+ URL string `protobuf:"bytes,2,opt,name=url,proto3" json:"url,omitempty"`
+ // Options is a set of additional key/value pairs whose interpretation
+ // depends on the specified CA type.
+ Options map[string]string `protobuf:"bytes,3,rep,name=options" json:"options,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ // CACert specifies which root CA is used by this external CA
+ CACert []byte `protobuf:"bytes,4,opt,name=ca_cert,json=caCert,proto3" json:"ca_cert,omitempty"`
+}
+
+func (m *ExternalCA) Reset() { *m = ExternalCA{} }
+func (*ExternalCA) ProtoMessage() {}
+func (*ExternalCA) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{32} }
+
+type CAConfig struct {
+ // NodeCertExpiry is the duration certificates should be issued for
+ // Note: can't use stdduration because this field needs to be nullable.
+ NodeCertExpiry *google_protobuf1.Duration `protobuf:"bytes,1,opt,name=node_cert_expiry,json=nodeCertExpiry" json:"node_cert_expiry,omitempty"`
+ // ExternalCAs is a list of CAs to which a manager node will make
+ // certificate signing requests for node certificates.
+ ExternalCAs []*ExternalCA `protobuf:"bytes,2,rep,name=external_cas,json=externalCas" json:"external_cas,omitempty"`
+ // SigningCACert is the desired CA certificate to be used as the root and
+ // signing CA for the swarm. If not provided, indicates that we are either happy
+ // with the current configuration, or (together with a bump in the ForceRotate value)
+ // that we want a certificate and key generated for us.
+ SigningCACert []byte `protobuf:"bytes,3,opt,name=signing_ca_cert,json=signingCaCert,proto3" json:"signing_ca_cert,omitempty"`
+ // SigningCAKey is the desired private key, matching the signing CA cert, to be used
+ // to sign certificates for the swarm
+ SigningCAKey []byte `protobuf:"bytes,4,opt,name=signing_ca_key,json=signingCaKey,proto3" json:"signing_ca_key,omitempty"`
+ // ForceRotate is a counter that triggers a root CA rotation even if no relevant
+ // parameters have been in the spec. This will force the manager to generate a new
+ // certificate and key, if none have been provided.
+ ForceRotate uint64 `protobuf:"varint,5,opt,name=force_rotate,json=forceRotate,proto3" json:"force_rotate,omitempty"`
+}
+
+func (m *CAConfig) Reset() { *m = CAConfig{} }
+func (*CAConfig) ProtoMessage() {}
+func (*CAConfig) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{33} }
+
+// OrchestrationConfig defines cluster-level orchestration settings.
+type OrchestrationConfig struct {
+ // TaskHistoryRetentionLimit is the number of historic tasks to keep per instance or
+ // node. If negative, never remove completed or failed tasks.
+ TaskHistoryRetentionLimit int64 `protobuf:"varint,1,opt,name=task_history_retention_limit,json=taskHistoryRetentionLimit,proto3" json:"task_history_retention_limit,omitempty"`
+}
+
+func (m *OrchestrationConfig) Reset() { *m = OrchestrationConfig{} }
+func (*OrchestrationConfig) ProtoMessage() {}
+func (*OrchestrationConfig) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{34} }
+
+// TaskDefaults specifies default values for task creation.
+type TaskDefaults struct {
+ // LogDriver specifies the log driver to use for the cluster if not
+ // specified for each task.
+ //
+ // If this is changed, only new tasks will pick up the new log driver.
+ // Existing tasks will continue to use the previous default until rescheduled.
+ LogDriver *Driver `protobuf:"bytes,1,opt,name=log_driver,json=logDriver" json:"log_driver,omitempty"`
+}
+
+func (m *TaskDefaults) Reset() { *m = TaskDefaults{} }
+func (*TaskDefaults) ProtoMessage() {}
+func (*TaskDefaults) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{35} }
+
+// DispatcherConfig defines cluster-level dispatcher settings.
+type DispatcherConfig struct {
+ // HeartbeatPeriod defines how often agent should send heartbeats to
+ // dispatcher.
+ // Note: can't use stdduration because this field needs to be nullable.
+ HeartbeatPeriod *google_protobuf1.Duration `protobuf:"bytes,1,opt,name=heartbeat_period,json=heartbeatPeriod" json:"heartbeat_period,omitempty"`
+}
+
+func (m *DispatcherConfig) Reset() { *m = DispatcherConfig{} }
+func (*DispatcherConfig) ProtoMessage() {}
+func (*DispatcherConfig) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{36} }
+
+// RaftConfig defines raft settings for the cluster.
+type RaftConfig struct {
+ // SnapshotInterval is the number of log entries between snapshots.
+ SnapshotInterval uint64 `protobuf:"varint,1,opt,name=snapshot_interval,json=snapshotInterval,proto3" json:"snapshot_interval,omitempty"`
+ // KeepOldSnapshots is the number of snapshots to keep beyond the
+ // current snapshot.
+ KeepOldSnapshots uint64 `protobuf:"varint,2,opt,name=keep_old_snapshots,json=keepOldSnapshots,proto3" json:"keep_old_snapshots,omitempty"`
+ // LogEntriesForSlowFollowers is the number of log entries to keep
+ // around to sync up slow followers after a snapshot is created.
+ LogEntriesForSlowFollowers uint64 `protobuf:"varint,3,opt,name=log_entries_for_slow_followers,json=logEntriesForSlowFollowers,proto3" json:"log_entries_for_slow_followers,omitempty"`
+ // HeartbeatTick defines the amount of ticks (in seconds) between
+ // each heartbeat message sent to other members for health-check.
+ HeartbeatTick uint32 `protobuf:"varint,4,opt,name=heartbeat_tick,json=heartbeatTick,proto3" json:"heartbeat_tick,omitempty"`
+ // ElectionTick defines the amount of ticks (in seconds) needed
+ // without a leader to trigger a new election.
+ ElectionTick uint32 `protobuf:"varint,5,opt,name=election_tick,json=electionTick,proto3" json:"election_tick,omitempty"`
+}
+
+func (m *RaftConfig) Reset() { *m = RaftConfig{} }
+func (*RaftConfig) ProtoMessage() {}
+func (*RaftConfig) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{37} }
+
+type EncryptionConfig struct {
+ // AutoLockManagers specifies whether or not managers TLS keys and raft data
+ // should be encrypted at rest in such a way that they must be unlocked
+ // before the manager node starts up again.
+ AutoLockManagers bool `protobuf:"varint,1,opt,name=auto_lock_managers,json=autoLockManagers,proto3" json:"auto_lock_managers,omitempty"`
+}
+
+func (m *EncryptionConfig) Reset() { *m = EncryptionConfig{} }
+func (*EncryptionConfig) ProtoMessage() {}
+func (*EncryptionConfig) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{38} }
+
+type SpreadOver struct {
+ SpreadDescriptor string `protobuf:"bytes,1,opt,name=spread_descriptor,json=spreadDescriptor,proto3" json:"spread_descriptor,omitempty"`
+}
+
+func (m *SpreadOver) Reset() { *m = SpreadOver{} }
+func (*SpreadOver) ProtoMessage() {}
+func (*SpreadOver) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{39} }
+
+type PlacementPreference struct {
+ // Types that are valid to be assigned to Preference:
+ // *PlacementPreference_Spread
+ Preference isPlacementPreference_Preference `protobuf_oneof:"Preference"`
+}
+
+func (m *PlacementPreference) Reset() { *m = PlacementPreference{} }
+func (*PlacementPreference) ProtoMessage() {}
+func (*PlacementPreference) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{40} }
+
+type isPlacementPreference_Preference interface {
+ isPlacementPreference_Preference()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type PlacementPreference_Spread struct {
+ Spread *SpreadOver `protobuf:"bytes,1,opt,name=spread,oneof"`
+}
+
+func (*PlacementPreference_Spread) isPlacementPreference_Preference() {}
+
+func (m *PlacementPreference) GetPreference() isPlacementPreference_Preference {
+ if m != nil {
+ return m.Preference
+ }
+ return nil
+}
+
+func (m *PlacementPreference) GetSpread() *SpreadOver {
+ if x, ok := m.GetPreference().(*PlacementPreference_Spread); ok {
+ return x.Spread
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*PlacementPreference) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _PlacementPreference_OneofMarshaler, _PlacementPreference_OneofUnmarshaler, _PlacementPreference_OneofSizer, []interface{}{
+ (*PlacementPreference_Spread)(nil),
+ }
+}
+
+func _PlacementPreference_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*PlacementPreference)
+ // Preference
+ switch x := m.Preference.(type) {
+ case *PlacementPreference_Spread:
+ _ = b.EncodeVarint(1<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Spread); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("PlacementPreference.Preference has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _PlacementPreference_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*PlacementPreference)
+ switch tag {
+ case 1: // Preference.spread
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(SpreadOver)
+ err := b.DecodeMessage(msg)
+ m.Preference = &PlacementPreference_Spread{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _PlacementPreference_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*PlacementPreference)
+ // Preference
+ switch x := m.Preference.(type) {
+ case *PlacementPreference_Spread:
+ s := proto.Size(x.Spread)
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// Placement specifies task distribution constraints.
+type Placement struct {
+ // Constraints specifies a set of requirements a node should meet for a task.
+ Constraints []string `protobuf:"bytes,1,rep,name=constraints" json:"constraints,omitempty"`
+ // Preferences provide a way to make the scheduler aware of factors
+ // such as topology. They are provided in order from highest to lowest
+ // precedence.
+ Preferences []*PlacementPreference `protobuf:"bytes,2,rep,name=preferences" json:"preferences,omitempty"`
+ // Platforms stores all the platforms that the image can run on.
+ // This field is used in the platform filter for scheduling. If empty,
+ // then the platform filter is off, meaning there are no scheduling restrictions.
+ Platforms []*Platform `protobuf:"bytes,3,rep,name=platforms" json:"platforms,omitempty"`
+}
+
+func (m *Placement) Reset() { *m = Placement{} }
+func (*Placement) ProtoMessage() {}
+func (*Placement) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{41} }
+
+// JoinToken contains the join tokens for workers and managers.
+type JoinTokens struct {
+ // Worker is the join token workers may use to join the swarm.
+ Worker string `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"`
+ // Manager is the join token workers may use to join the swarm.
+ Manager string `protobuf:"bytes,2,opt,name=manager,proto3" json:"manager,omitempty"`
+}
+
+func (m *JoinTokens) Reset() { *m = JoinTokens{} }
+func (*JoinTokens) ProtoMessage() {}
+func (*JoinTokens) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{42} }
+
+type RootCA struct {
+ // CAKey is the root CA private key.
+ CAKey []byte `protobuf:"bytes,1,opt,name=ca_key,json=caKey,proto3" json:"ca_key,omitempty"`
+ // CACert is the root CA certificate.
+ CACert []byte `protobuf:"bytes,2,opt,name=ca_cert,json=caCert,proto3" json:"ca_cert,omitempty"`
+ // CACertHash is the digest of the CA Certificate.
+ CACertHash string `protobuf:"bytes,3,opt,name=ca_cert_hash,json=caCertHash,proto3" json:"ca_cert_hash,omitempty"`
+ // JoinTokens contains the join tokens for workers and managers.
+ JoinTokens JoinTokens `protobuf:"bytes,4,opt,name=join_tokens,json=joinTokens" json:"join_tokens"`
+ // RootRotation contains the new root cert and key we want to rotate to - if this is nil, we are not in the
+ // middle of a root rotation
+ RootRotation *RootRotation `protobuf:"bytes,5,opt,name=root_rotation,json=rootRotation" json:"root_rotation,omitempty"`
+ // LastForcedRotation matches the Cluster Spec's CAConfig's ForceRotation counter.
+ // It indicates when the current CA cert and key were generated (or updated).
+ LastForcedRotation uint64 `protobuf:"varint,6,opt,name=last_forced_rotation,json=lastForcedRotation,proto3" json:"last_forced_rotation,omitempty"`
+}
+
+func (m *RootCA) Reset() { *m = RootCA{} }
+func (*RootCA) ProtoMessage() {}
+func (*RootCA) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{43} }
+
+type Certificate struct {
+ Role NodeRole `protobuf:"varint,1,opt,name=role,proto3,enum=docker.swarmkit.v1.NodeRole" json:"role,omitempty"`
+ CSR []byte `protobuf:"bytes,2,opt,name=csr,proto3" json:"csr,omitempty"`
+ Status IssuanceStatus `protobuf:"bytes,3,opt,name=status" json:"status"`
+ Certificate []byte `protobuf:"bytes,4,opt,name=certificate,proto3" json:"certificate,omitempty"`
+ // CN represents the node ID.
+ CN string `protobuf:"bytes,5,opt,name=cn,proto3" json:"cn,omitempty"`
+}
+
+func (m *Certificate) Reset() { *m = Certificate{} }
+func (*Certificate) ProtoMessage() {}
+func (*Certificate) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{44} }
+
+// Symmetric keys to encrypt inter-agent communication.
+type EncryptionKey struct {
+ // Agent subsystem the key is intended for. Example:
+ // networking:gossip
+ Subsystem string `protobuf:"bytes,1,opt,name=subsystem,proto3" json:"subsystem,omitempty"`
+ Algorithm EncryptionKey_Algorithm `protobuf:"varint,2,opt,name=algorithm,proto3,enum=docker.swarmkit.v1.EncryptionKey_Algorithm" json:"algorithm,omitempty"`
+ Key []byte `protobuf:"bytes,3,opt,name=key,proto3" json:"key,omitempty"`
+ // Time stamp from the lamport clock of the key allocator to
+ // identify the relative age of the key.
+ LamportTime uint64 `protobuf:"varint,4,opt,name=lamport_time,json=lamportTime,proto3" json:"lamport_time,omitempty"`
+}
+
+func (m *EncryptionKey) Reset() { *m = EncryptionKey{} }
+func (*EncryptionKey) ProtoMessage() {}
+func (*EncryptionKey) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{45} }
+
+// ManagerStatus provides informations about the state of a manager in the cluster.
+type ManagerStatus struct {
+ // RaftID specifies the internal ID used by the manager in a raft context, it can never be modified
+ // and is used only for information purposes
+ RaftID uint64 `protobuf:"varint,1,opt,name=raft_id,json=raftId,proto3" json:"raft_id,omitempty"`
+ // Addr is the address advertised to raft.
+ Addr string `protobuf:"bytes,2,opt,name=addr,proto3" json:"addr,omitempty"`
+ // Leader is set to true if this node is the raft leader.
+ Leader bool `protobuf:"varint,3,opt,name=leader,proto3" json:"leader,omitempty"`
+ // Reachability specifies whether this node is reachable.
+ Reachability RaftMemberStatus_Reachability `protobuf:"varint,4,opt,name=reachability,proto3,enum=docker.swarmkit.v1.RaftMemberStatus_Reachability" json:"reachability,omitempty"`
+}
+
+func (m *ManagerStatus) Reset() { *m = ManagerStatus{} }
+func (*ManagerStatus) ProtoMessage() {}
+func (*ManagerStatus) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{46} }
+
+// FileTarget represents a specific target that is backed by a file
+type FileTarget struct {
+ // Name represents the final filename in the filesystem
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ // UID represents the file UID
+ UID string `protobuf:"bytes,2,opt,name=uid,proto3" json:"uid,omitempty"`
+ // GID represents the file GID
+ GID string `protobuf:"bytes,3,opt,name=gid,proto3" json:"gid,omitempty"`
+ // Mode represents the FileMode of the file
+ Mode os.FileMode `protobuf:"varint,4,opt,name=mode,proto3,customtype=os.FileMode" json:"mode"`
+}
+
+func (m *FileTarget) Reset() { *m = FileTarget{} }
+func (*FileTarget) ProtoMessage() {}
+func (*FileTarget) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{47} }
+
+// SecretReference is the linkage between a service and a secret that it uses.
+type SecretReference struct {
+ // SecretID represents the ID of the specific Secret that we're
+ // referencing. This identifier exists so that SecretReferences don't leak
+ // any information about the secret contents.
+ SecretID string `protobuf:"bytes,1,opt,name=secret_id,json=secretId,proto3" json:"secret_id,omitempty"`
+ // SecretName is the name of the secret that this references, but this is just provided for
+ // lookup/display purposes. The secret in the reference will be identified by its ID.
+ SecretName string `protobuf:"bytes,2,opt,name=secret_name,json=secretName,proto3" json:"secret_name,omitempty"`
+ // Target specifies how this secret should be exposed to the task.
+ //
+ // Types that are valid to be assigned to Target:
+ // *SecretReference_File
+ Target isSecretReference_Target `protobuf_oneof:"target"`
+}
+
+func (m *SecretReference) Reset() { *m = SecretReference{} }
+func (*SecretReference) ProtoMessage() {}
+func (*SecretReference) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{48} }
+
+type isSecretReference_Target interface {
+ isSecretReference_Target()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type SecretReference_File struct {
+ File *FileTarget `protobuf:"bytes,3,opt,name=file,oneof"`
+}
+
+func (*SecretReference_File) isSecretReference_Target() {}
+
+func (m *SecretReference) GetTarget() isSecretReference_Target {
+ if m != nil {
+ return m.Target
+ }
+ return nil
+}
+
+func (m *SecretReference) GetFile() *FileTarget {
+ if x, ok := m.GetTarget().(*SecretReference_File); ok {
+ return x.File
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*SecretReference) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _SecretReference_OneofMarshaler, _SecretReference_OneofUnmarshaler, _SecretReference_OneofSizer, []interface{}{
+ (*SecretReference_File)(nil),
+ }
+}
+
+func _SecretReference_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*SecretReference)
+ // target
+ switch x := m.Target.(type) {
+ case *SecretReference_File:
+ _ = b.EncodeVarint(3<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.File); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("SecretReference.Target has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _SecretReference_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*SecretReference)
+ switch tag {
+ case 3: // target.file
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(FileTarget)
+ err := b.DecodeMessage(msg)
+ m.Target = &SecretReference_File{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _SecretReference_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*SecretReference)
+ // target
+ switch x := m.Target.(type) {
+ case *SecretReference_File:
+ s := proto.Size(x.File)
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// ConfigReference is the linkage between a service and a config that it uses.
+type ConfigReference struct {
+ // ConfigID represents the ID of the specific Config that we're
+ // referencing.
+ ConfigID string `protobuf:"bytes,1,opt,name=config_id,json=configId,proto3" json:"config_id,omitempty"`
+ // ConfigName is the name of the config that this references, but this is just provided for
+ // lookup/display purposes. The config in the reference will be identified by its ID.
+ ConfigName string `protobuf:"bytes,2,opt,name=config_name,json=configName,proto3" json:"config_name,omitempty"`
+ // Target specifies how this secret should be exposed to the task.
+ //
+ // Types that are valid to be assigned to Target:
+ // *ConfigReference_File
+ Target isConfigReference_Target `protobuf_oneof:"target"`
+}
+
+func (m *ConfigReference) Reset() { *m = ConfigReference{} }
+func (*ConfigReference) ProtoMessage() {}
+func (*ConfigReference) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{49} }
+
+type isConfigReference_Target interface {
+ isConfigReference_Target()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type ConfigReference_File struct {
+ File *FileTarget `protobuf:"bytes,3,opt,name=file,oneof"`
+}
+
+func (*ConfigReference_File) isConfigReference_Target() {}
+
+func (m *ConfigReference) GetTarget() isConfigReference_Target {
+ if m != nil {
+ return m.Target
+ }
+ return nil
+}
+
+func (m *ConfigReference) GetFile() *FileTarget {
+ if x, ok := m.GetTarget().(*ConfigReference_File); ok {
+ return x.File
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*ConfigReference) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _ConfigReference_OneofMarshaler, _ConfigReference_OneofUnmarshaler, _ConfigReference_OneofSizer, []interface{}{
+ (*ConfigReference_File)(nil),
+ }
+}
+
+func _ConfigReference_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*ConfigReference)
+ // target
+ switch x := m.Target.(type) {
+ case *ConfigReference_File:
+ _ = b.EncodeVarint(3<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.File); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("ConfigReference.Target has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _ConfigReference_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*ConfigReference)
+ switch tag {
+ case 3: // target.file
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(FileTarget)
+ err := b.DecodeMessage(msg)
+ m.Target = &ConfigReference_File{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _ConfigReference_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*ConfigReference)
+ // target
+ switch x := m.Target.(type) {
+ case *ConfigReference_File:
+ s := proto.Size(x.File)
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// BlacklistedCertificate is a record for a blacklisted certificate. It does not
+// contain the certificate's CN, because these records are indexed by CN.
+type BlacklistedCertificate struct {
+ // Expiry is the latest known expiration time of a certificate that
+ // was issued for the given CN.
+ // Note: can't use stdtime because this field is nullable.
+ Expiry *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=expiry" json:"expiry,omitempty"`
+}
+
+func (m *BlacklistedCertificate) Reset() { *m = BlacklistedCertificate{} }
+func (*BlacklistedCertificate) ProtoMessage() {}
+func (*BlacklistedCertificate) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{50} }
+
+// HealthConfig holds configuration settings for the HEALTHCHECK feature.
+type HealthConfig struct {
+ // Test is the test to perform to check that the container is healthy.
+ // An empty slice means to inherit the default.
+ // The options are:
+ // {} : inherit healthcheck
+ // {"NONE"} : disable healthcheck
+ // {"CMD", args...} : exec arguments directly
+ // {"CMD-SHELL", command} : run command with system's default shell
+ Test []string `protobuf:"bytes,1,rep,name=test" json:"test,omitempty"`
+ // Interval is the time to wait between checks. Zero means inherit.
+ // Note: can't use stdduration because this field needs to be nullable.
+ Interval *google_protobuf1.Duration `protobuf:"bytes,2,opt,name=interval" json:"interval,omitempty"`
+ // Timeout is the time to wait before considering the check to have hung.
+ // Zero means inherit.
+ // Note: can't use stdduration because this field needs to be nullable.
+ Timeout *google_protobuf1.Duration `protobuf:"bytes,3,opt,name=timeout" json:"timeout,omitempty"`
+ // Retries is the number of consecutive failures needed to consider a
+ // container as unhealthy. Zero means inherit.
+ Retries int32 `protobuf:"varint,4,opt,name=retries,proto3" json:"retries,omitempty"`
+ // Start period is the period for container initialization during
+ // which health check failures will note count towards the maximum
+ // number of retries.
+ StartPeriod *google_protobuf1.Duration `protobuf:"bytes,5,opt,name=start_period,json=startPeriod" json:"start_period,omitempty"`
+}
+
+func (m *HealthConfig) Reset() { *m = HealthConfig{} }
+func (*HealthConfig) ProtoMessage() {}
+func (*HealthConfig) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{51} }
+
+type MaybeEncryptedRecord struct {
+ Algorithm MaybeEncryptedRecord_Algorithm `protobuf:"varint,1,opt,name=algorithm,proto3,enum=docker.swarmkit.v1.MaybeEncryptedRecord_Algorithm" json:"algorithm,omitempty"`
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+ Nonce []byte `protobuf:"bytes,3,opt,name=nonce,proto3" json:"nonce,omitempty"`
+}
+
+func (m *MaybeEncryptedRecord) Reset() { *m = MaybeEncryptedRecord{} }
+func (*MaybeEncryptedRecord) ProtoMessage() {}
+func (*MaybeEncryptedRecord) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{52} }
+
+type RootRotation struct {
+ CACert []byte `protobuf:"bytes,1,opt,name=ca_cert,json=caCert,proto3" json:"ca_cert,omitempty"`
+ CAKey []byte `protobuf:"bytes,2,opt,name=ca_key,json=caKey,proto3" json:"ca_key,omitempty"`
+ // cross-signed CA cert is the CACert that has been cross-signed by the previous root
+ CrossSignedCACert []byte `protobuf:"bytes,3,opt,name=cross_signed_ca_cert,json=crossSignedCaCert,proto3" json:"cross_signed_ca_cert,omitempty"`
+}
+
+func (m *RootRotation) Reset() { *m = RootRotation{} }
+func (*RootRotation) ProtoMessage() {}
+func (*RootRotation) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{53} }
+
+// Privileges specifies security configuration/permissions.
+type Privileges struct {
+ CredentialSpec *Privileges_CredentialSpec `protobuf:"bytes,1,opt,name=credential_spec,json=credentialSpec" json:"credential_spec,omitempty"`
+ SELinuxContext *Privileges_SELinuxContext `protobuf:"bytes,2,opt,name=selinux_context,json=selinuxContext" json:"selinux_context,omitempty"`
+}
+
+func (m *Privileges) Reset() { *m = Privileges{} }
+func (*Privileges) ProtoMessage() {}
+func (*Privileges) Descriptor() ([]byte, []int) { return fileDescriptorTypes, []int{54} }
+
+// CredentialSpec for managed service account (Windows only).
+type Privileges_CredentialSpec struct {
+ // Types that are valid to be assigned to Source:
+ // *Privileges_CredentialSpec_File
+ // *Privileges_CredentialSpec_Registry
+ Source isPrivileges_CredentialSpec_Source `protobuf_oneof:"source"`
+}
+
+func (m *Privileges_CredentialSpec) Reset() { *m = Privileges_CredentialSpec{} }
+func (*Privileges_CredentialSpec) ProtoMessage() {}
+func (*Privileges_CredentialSpec) Descriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{54, 0}
+}
+
+type isPrivileges_CredentialSpec_Source interface {
+ isPrivileges_CredentialSpec_Source()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type Privileges_CredentialSpec_File struct {
+ File string `protobuf:"bytes,1,opt,name=file,proto3,oneof"`
+}
+type Privileges_CredentialSpec_Registry struct {
+ Registry string `protobuf:"bytes,2,opt,name=registry,proto3,oneof"`
+}
+
+func (*Privileges_CredentialSpec_File) isPrivileges_CredentialSpec_Source() {}
+func (*Privileges_CredentialSpec_Registry) isPrivileges_CredentialSpec_Source() {}
+
+func (m *Privileges_CredentialSpec) GetSource() isPrivileges_CredentialSpec_Source {
+ if m != nil {
+ return m.Source
+ }
+ return nil
+}
+
+func (m *Privileges_CredentialSpec) GetFile() string {
+ if x, ok := m.GetSource().(*Privileges_CredentialSpec_File); ok {
+ return x.File
+ }
+ return ""
+}
+
+func (m *Privileges_CredentialSpec) GetRegistry() string {
+ if x, ok := m.GetSource().(*Privileges_CredentialSpec_Registry); ok {
+ return x.Registry
+ }
+ return ""
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Privileges_CredentialSpec) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Privileges_CredentialSpec_OneofMarshaler, _Privileges_CredentialSpec_OneofUnmarshaler, _Privileges_CredentialSpec_OneofSizer, []interface{}{
+ (*Privileges_CredentialSpec_File)(nil),
+ (*Privileges_CredentialSpec_Registry)(nil),
+ }
+}
+
+func _Privileges_CredentialSpec_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Privileges_CredentialSpec)
+ // source
+ switch x := m.Source.(type) {
+ case *Privileges_CredentialSpec_File:
+ _ = b.EncodeVarint(1<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.File)
+ case *Privileges_CredentialSpec_Registry:
+ _ = b.EncodeVarint(2<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.Registry)
+ case nil:
+ default:
+ return fmt.Errorf("Privileges_CredentialSpec.Source has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Privileges_CredentialSpec_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Privileges_CredentialSpec)
+ switch tag {
+ case 1: // source.file
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Source = &Privileges_CredentialSpec_File{x}
+ return true, err
+ case 2: // source.registry
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Source = &Privileges_CredentialSpec_Registry{x}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Privileges_CredentialSpec_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Privileges_CredentialSpec)
+ // source
+ switch x := m.Source.(type) {
+ case *Privileges_CredentialSpec_File:
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.File)))
+ n += len(x.File)
+ case *Privileges_CredentialSpec_Registry:
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Registry)))
+ n += len(x.Registry)
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// SELinuxContext contains the SELinux labels for the container.
+type Privileges_SELinuxContext struct {
+ Disable bool `protobuf:"varint,1,opt,name=disable,proto3" json:"disable,omitempty"`
+ User string `protobuf:"bytes,2,opt,name=user,proto3" json:"user,omitempty"`
+ Role string `protobuf:"bytes,3,opt,name=role,proto3" json:"role,omitempty"`
+ Type string `protobuf:"bytes,4,opt,name=type,proto3" json:"type,omitempty"`
+ Level string `protobuf:"bytes,5,opt,name=level,proto3" json:"level,omitempty"`
+}
+
+func (m *Privileges_SELinuxContext) Reset() { *m = Privileges_SELinuxContext{} }
+func (*Privileges_SELinuxContext) ProtoMessage() {}
+func (*Privileges_SELinuxContext) Descriptor() ([]byte, []int) {
+ return fileDescriptorTypes, []int{54, 1}
+}
+
+func init() {
+ proto.RegisterType((*Version)(nil), "docker.swarmkit.v1.Version")
+ proto.RegisterType((*IndexEntry)(nil), "docker.swarmkit.v1.IndexEntry")
+ proto.RegisterType((*Annotations)(nil), "docker.swarmkit.v1.Annotations")
+ proto.RegisterType((*GenericString)(nil), "docker.swarmkit.v1.GenericString")
+ proto.RegisterType((*GenericDiscrete)(nil), "docker.swarmkit.v1.GenericDiscrete")
+ proto.RegisterType((*GenericResource)(nil), "docker.swarmkit.v1.GenericResource")
+ proto.RegisterType((*Resources)(nil), "docker.swarmkit.v1.Resources")
+ proto.RegisterType((*ResourceRequirements)(nil), "docker.swarmkit.v1.ResourceRequirements")
+ proto.RegisterType((*Platform)(nil), "docker.swarmkit.v1.Platform")
+ proto.RegisterType((*PluginDescription)(nil), "docker.swarmkit.v1.PluginDescription")
+ proto.RegisterType((*EngineDescription)(nil), "docker.swarmkit.v1.EngineDescription")
+ proto.RegisterType((*NodeDescription)(nil), "docker.swarmkit.v1.NodeDescription")
+ proto.RegisterType((*NodeTLSInfo)(nil), "docker.swarmkit.v1.NodeTLSInfo")
+ proto.RegisterType((*RaftMemberStatus)(nil), "docker.swarmkit.v1.RaftMemberStatus")
+ proto.RegisterType((*NodeStatus)(nil), "docker.swarmkit.v1.NodeStatus")
+ proto.RegisterType((*Image)(nil), "docker.swarmkit.v1.Image")
+ proto.RegisterType((*Mount)(nil), "docker.swarmkit.v1.Mount")
+ proto.RegisterType((*Mount_BindOptions)(nil), "docker.swarmkit.v1.Mount.BindOptions")
+ proto.RegisterType((*Mount_VolumeOptions)(nil), "docker.swarmkit.v1.Mount.VolumeOptions")
+ proto.RegisterType((*Mount_TmpfsOptions)(nil), "docker.swarmkit.v1.Mount.TmpfsOptions")
+ proto.RegisterType((*RestartPolicy)(nil), "docker.swarmkit.v1.RestartPolicy")
+ proto.RegisterType((*UpdateConfig)(nil), "docker.swarmkit.v1.UpdateConfig")
+ proto.RegisterType((*UpdateStatus)(nil), "docker.swarmkit.v1.UpdateStatus")
+ proto.RegisterType((*ContainerStatus)(nil), "docker.swarmkit.v1.ContainerStatus")
+ proto.RegisterType((*PortStatus)(nil), "docker.swarmkit.v1.PortStatus")
+ proto.RegisterType((*TaskStatus)(nil), "docker.swarmkit.v1.TaskStatus")
+ proto.RegisterType((*NetworkAttachmentConfig)(nil), "docker.swarmkit.v1.NetworkAttachmentConfig")
+ proto.RegisterType((*IPAMConfig)(nil), "docker.swarmkit.v1.IPAMConfig")
+ proto.RegisterType((*PortConfig)(nil), "docker.swarmkit.v1.PortConfig")
+ proto.RegisterType((*Driver)(nil), "docker.swarmkit.v1.Driver")
+ proto.RegisterType((*IPAMOptions)(nil), "docker.swarmkit.v1.IPAMOptions")
+ proto.RegisterType((*Peer)(nil), "docker.swarmkit.v1.Peer")
+ proto.RegisterType((*WeightedPeer)(nil), "docker.swarmkit.v1.WeightedPeer")
+ proto.RegisterType((*IssuanceStatus)(nil), "docker.swarmkit.v1.IssuanceStatus")
+ proto.RegisterType((*AcceptancePolicy)(nil), "docker.swarmkit.v1.AcceptancePolicy")
+ proto.RegisterType((*AcceptancePolicy_RoleAdmissionPolicy)(nil), "docker.swarmkit.v1.AcceptancePolicy.RoleAdmissionPolicy")
+ proto.RegisterType((*AcceptancePolicy_RoleAdmissionPolicy_Secret)(nil), "docker.swarmkit.v1.AcceptancePolicy.RoleAdmissionPolicy.Secret")
+ proto.RegisterType((*ExternalCA)(nil), "docker.swarmkit.v1.ExternalCA")
+ proto.RegisterType((*CAConfig)(nil), "docker.swarmkit.v1.CAConfig")
+ proto.RegisterType((*OrchestrationConfig)(nil), "docker.swarmkit.v1.OrchestrationConfig")
+ proto.RegisterType((*TaskDefaults)(nil), "docker.swarmkit.v1.TaskDefaults")
+ proto.RegisterType((*DispatcherConfig)(nil), "docker.swarmkit.v1.DispatcherConfig")
+ proto.RegisterType((*RaftConfig)(nil), "docker.swarmkit.v1.RaftConfig")
+ proto.RegisterType((*EncryptionConfig)(nil), "docker.swarmkit.v1.EncryptionConfig")
+ proto.RegisterType((*SpreadOver)(nil), "docker.swarmkit.v1.SpreadOver")
+ proto.RegisterType((*PlacementPreference)(nil), "docker.swarmkit.v1.PlacementPreference")
+ proto.RegisterType((*Placement)(nil), "docker.swarmkit.v1.Placement")
+ proto.RegisterType((*JoinTokens)(nil), "docker.swarmkit.v1.JoinTokens")
+ proto.RegisterType((*RootCA)(nil), "docker.swarmkit.v1.RootCA")
+ proto.RegisterType((*Certificate)(nil), "docker.swarmkit.v1.Certificate")
+ proto.RegisterType((*EncryptionKey)(nil), "docker.swarmkit.v1.EncryptionKey")
+ proto.RegisterType((*ManagerStatus)(nil), "docker.swarmkit.v1.ManagerStatus")
+ proto.RegisterType((*FileTarget)(nil), "docker.swarmkit.v1.FileTarget")
+ proto.RegisterType((*SecretReference)(nil), "docker.swarmkit.v1.SecretReference")
+ proto.RegisterType((*ConfigReference)(nil), "docker.swarmkit.v1.ConfigReference")
+ proto.RegisterType((*BlacklistedCertificate)(nil), "docker.swarmkit.v1.BlacklistedCertificate")
+ proto.RegisterType((*HealthConfig)(nil), "docker.swarmkit.v1.HealthConfig")
+ proto.RegisterType((*MaybeEncryptedRecord)(nil), "docker.swarmkit.v1.MaybeEncryptedRecord")
+ proto.RegisterType((*RootRotation)(nil), "docker.swarmkit.v1.RootRotation")
+ proto.RegisterType((*Privileges)(nil), "docker.swarmkit.v1.Privileges")
+ proto.RegisterType((*Privileges_CredentialSpec)(nil), "docker.swarmkit.v1.Privileges.CredentialSpec")
+ proto.RegisterType((*Privileges_SELinuxContext)(nil), "docker.swarmkit.v1.Privileges.SELinuxContext")
+ proto.RegisterEnum("docker.swarmkit.v1.TaskState", TaskState_name, TaskState_value)
+ proto.RegisterEnum("docker.swarmkit.v1.NodeRole", NodeRole_name, NodeRole_value)
+ proto.RegisterEnum("docker.swarmkit.v1.RaftMemberStatus_Reachability", RaftMemberStatus_Reachability_name, RaftMemberStatus_Reachability_value)
+ proto.RegisterEnum("docker.swarmkit.v1.NodeStatus_State", NodeStatus_State_name, NodeStatus_State_value)
+ proto.RegisterEnum("docker.swarmkit.v1.Mount_MountType", Mount_MountType_name, Mount_MountType_value)
+ proto.RegisterEnum("docker.swarmkit.v1.Mount_BindOptions_MountPropagation", Mount_BindOptions_MountPropagation_name, Mount_BindOptions_MountPropagation_value)
+ proto.RegisterEnum("docker.swarmkit.v1.RestartPolicy_RestartCondition", RestartPolicy_RestartCondition_name, RestartPolicy_RestartCondition_value)
+ proto.RegisterEnum("docker.swarmkit.v1.UpdateConfig_FailureAction", UpdateConfig_FailureAction_name, UpdateConfig_FailureAction_value)
+ proto.RegisterEnum("docker.swarmkit.v1.UpdateConfig_UpdateOrder", UpdateConfig_UpdateOrder_name, UpdateConfig_UpdateOrder_value)
+ proto.RegisterEnum("docker.swarmkit.v1.UpdateStatus_UpdateState", UpdateStatus_UpdateState_name, UpdateStatus_UpdateState_value)
+ proto.RegisterEnum("docker.swarmkit.v1.IPAMConfig_AddressFamily", IPAMConfig_AddressFamily_name, IPAMConfig_AddressFamily_value)
+ proto.RegisterEnum("docker.swarmkit.v1.PortConfig_Protocol", PortConfig_Protocol_name, PortConfig_Protocol_value)
+ proto.RegisterEnum("docker.swarmkit.v1.PortConfig_PublishMode", PortConfig_PublishMode_name, PortConfig_PublishMode_value)
+ proto.RegisterEnum("docker.swarmkit.v1.IssuanceStatus_State", IssuanceStatus_State_name, IssuanceStatus_State_value)
+ proto.RegisterEnum("docker.swarmkit.v1.ExternalCA_CAProtocol", ExternalCA_CAProtocol_name, ExternalCA_CAProtocol_value)
+ proto.RegisterEnum("docker.swarmkit.v1.EncryptionKey_Algorithm", EncryptionKey_Algorithm_name, EncryptionKey_Algorithm_value)
+ proto.RegisterEnum("docker.swarmkit.v1.MaybeEncryptedRecord_Algorithm", MaybeEncryptedRecord_Algorithm_name, MaybeEncryptedRecord_Algorithm_value)
+}
+
+func (m *Version) Copy() *Version {
+ if m == nil {
+ return nil
+ }
+ o := &Version{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Version) CopyFrom(src interface{}) {
+
+ o := src.(*Version)
+ *m = *o
+}
+
+func (m *IndexEntry) Copy() *IndexEntry {
+ if m == nil {
+ return nil
+ }
+ o := &IndexEntry{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *IndexEntry) CopyFrom(src interface{}) {
+
+ o := src.(*IndexEntry)
+ *m = *o
+}
+
+func (m *Annotations) Copy() *Annotations {
+ if m == nil {
+ return nil
+ }
+ o := &Annotations{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Annotations) CopyFrom(src interface{}) {
+
+ o := src.(*Annotations)
+ *m = *o
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.Indices != nil {
+ m.Indices = make([]IndexEntry, len(o.Indices))
+ for i := range m.Indices {
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Indices[i], &o.Indices[i])
+ }
+ }
+
+}
+
+func (m *GenericString) Copy() *GenericString {
+ if m == nil {
+ return nil
+ }
+ o := &GenericString{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GenericString) CopyFrom(src interface{}) {
+
+ o := src.(*GenericString)
+ *m = *o
+}
+
+func (m *GenericDiscrete) Copy() *GenericDiscrete {
+ if m == nil {
+ return nil
+ }
+ o := &GenericDiscrete{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GenericDiscrete) CopyFrom(src interface{}) {
+
+ o := src.(*GenericDiscrete)
+ *m = *o
+}
+
+func (m *GenericResource) Copy() *GenericResource {
+ if m == nil {
+ return nil
+ }
+ o := &GenericResource{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *GenericResource) CopyFrom(src interface{}) {
+
+ o := src.(*GenericResource)
+ *m = *o
+ if o.Resource != nil {
+ switch o.Resource.(type) {
+ case *GenericResource_Str:
+ v := GenericResource_Str{
+ Str: &GenericString{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Str, o.GetStr())
+ m.Resource = &v
+ case *GenericResource_Discrete:
+ v := GenericResource_Discrete{
+ Discrete: &GenericDiscrete{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Discrete, o.GetDiscrete())
+ m.Resource = &v
+ }
+ }
+
+}
+
+func (m *Resources) Copy() *Resources {
+ if m == nil {
+ return nil
+ }
+ o := &Resources{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Resources) CopyFrom(src interface{}) {
+
+ o := src.(*Resources)
+ *m = *o
+ if o.Generic != nil {
+ m.Generic = make([]*GenericResource, len(o.Generic))
+ for i := range m.Generic {
+ m.Generic[i] = &GenericResource{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Generic[i], o.Generic[i])
+ }
+ }
+
+}
+
+func (m *ResourceRequirements) Copy() *ResourceRequirements {
+ if m == nil {
+ return nil
+ }
+ o := &ResourceRequirements{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ResourceRequirements) CopyFrom(src interface{}) {
+
+ o := src.(*ResourceRequirements)
+ *m = *o
+ if o.Limits != nil {
+ m.Limits = &Resources{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Limits, o.Limits)
+ }
+ if o.Reservations != nil {
+ m.Reservations = &Resources{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Reservations, o.Reservations)
+ }
+}
+
+func (m *Platform) Copy() *Platform {
+ if m == nil {
+ return nil
+ }
+ o := &Platform{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Platform) CopyFrom(src interface{}) {
+
+ o := src.(*Platform)
+ *m = *o
+}
+
+func (m *PluginDescription) Copy() *PluginDescription {
+ if m == nil {
+ return nil
+ }
+ o := &PluginDescription{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *PluginDescription) CopyFrom(src interface{}) {
+
+ o := src.(*PluginDescription)
+ *m = *o
+}
+
+func (m *EngineDescription) Copy() *EngineDescription {
+ if m == nil {
+ return nil
+ }
+ o := &EngineDescription{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *EngineDescription) CopyFrom(src interface{}) {
+
+ o := src.(*EngineDescription)
+ *m = *o
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.Plugins != nil {
+ m.Plugins = make([]PluginDescription, len(o.Plugins))
+ for i := range m.Plugins {
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Plugins[i], &o.Plugins[i])
+ }
+ }
+
+}
+
+func (m *NodeDescription) Copy() *NodeDescription {
+ if m == nil {
+ return nil
+ }
+ o := &NodeDescription{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *NodeDescription) CopyFrom(src interface{}) {
+
+ o := src.(*NodeDescription)
+ *m = *o
+ if o.Platform != nil {
+ m.Platform = &Platform{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Platform, o.Platform)
+ }
+ if o.Resources != nil {
+ m.Resources = &Resources{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Resources, o.Resources)
+ }
+ if o.Engine != nil {
+ m.Engine = &EngineDescription{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Engine, o.Engine)
+ }
+ if o.TLSInfo != nil {
+ m.TLSInfo = &NodeTLSInfo{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.TLSInfo, o.TLSInfo)
+ }
+}
+
+func (m *NodeTLSInfo) Copy() *NodeTLSInfo {
+ if m == nil {
+ return nil
+ }
+ o := &NodeTLSInfo{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *NodeTLSInfo) CopyFrom(src interface{}) {
+
+ o := src.(*NodeTLSInfo)
+ *m = *o
+ if o.TrustRoot != nil {
+ m.TrustRoot = make([]byte, len(o.TrustRoot))
+ copy(m.TrustRoot, o.TrustRoot)
+ }
+ if o.CertIssuerSubject != nil {
+ m.CertIssuerSubject = make([]byte, len(o.CertIssuerSubject))
+ copy(m.CertIssuerSubject, o.CertIssuerSubject)
+ }
+ if o.CertIssuerPublicKey != nil {
+ m.CertIssuerPublicKey = make([]byte, len(o.CertIssuerPublicKey))
+ copy(m.CertIssuerPublicKey, o.CertIssuerPublicKey)
+ }
+}
+
+func (m *RaftMemberStatus) Copy() *RaftMemberStatus {
+ if m == nil {
+ return nil
+ }
+ o := &RaftMemberStatus{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RaftMemberStatus) CopyFrom(src interface{}) {
+
+ o := src.(*RaftMemberStatus)
+ *m = *o
+}
+
+func (m *NodeStatus) Copy() *NodeStatus {
+ if m == nil {
+ return nil
+ }
+ o := &NodeStatus{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *NodeStatus) CopyFrom(src interface{}) {
+
+ o := src.(*NodeStatus)
+ *m = *o
+}
+
+func (m *Image) Copy() *Image {
+ if m == nil {
+ return nil
+ }
+ o := &Image{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Image) CopyFrom(src interface{}) {
+
+ o := src.(*Image)
+ *m = *o
+}
+
+func (m *Mount) Copy() *Mount {
+ if m == nil {
+ return nil
+ }
+ o := &Mount{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Mount) CopyFrom(src interface{}) {
+
+ o := src.(*Mount)
+ *m = *o
+ if o.BindOptions != nil {
+ m.BindOptions = &Mount_BindOptions{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.BindOptions, o.BindOptions)
+ }
+ if o.VolumeOptions != nil {
+ m.VolumeOptions = &Mount_VolumeOptions{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.VolumeOptions, o.VolumeOptions)
+ }
+ if o.TmpfsOptions != nil {
+ m.TmpfsOptions = &Mount_TmpfsOptions{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.TmpfsOptions, o.TmpfsOptions)
+ }
+}
+
+func (m *Mount_BindOptions) Copy() *Mount_BindOptions {
+ if m == nil {
+ return nil
+ }
+ o := &Mount_BindOptions{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Mount_BindOptions) CopyFrom(src interface{}) {
+
+ o := src.(*Mount_BindOptions)
+ *m = *o
+}
+
+func (m *Mount_VolumeOptions) Copy() *Mount_VolumeOptions {
+ if m == nil {
+ return nil
+ }
+ o := &Mount_VolumeOptions{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Mount_VolumeOptions) CopyFrom(src interface{}) {
+
+ o := src.(*Mount_VolumeOptions)
+ *m = *o
+ if o.Labels != nil {
+ m.Labels = make(map[string]string, len(o.Labels))
+ for k, v := range o.Labels {
+ m.Labels[k] = v
+ }
+ }
+
+ if o.DriverConfig != nil {
+ m.DriverConfig = &Driver{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.DriverConfig, o.DriverConfig)
+ }
+}
+
+func (m *Mount_TmpfsOptions) Copy() *Mount_TmpfsOptions {
+ if m == nil {
+ return nil
+ }
+ o := &Mount_TmpfsOptions{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Mount_TmpfsOptions) CopyFrom(src interface{}) {
+
+ o := src.(*Mount_TmpfsOptions)
+ *m = *o
+}
+
+func (m *RestartPolicy) Copy() *RestartPolicy {
+ if m == nil {
+ return nil
+ }
+ o := &RestartPolicy{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RestartPolicy) CopyFrom(src interface{}) {
+
+ o := src.(*RestartPolicy)
+ *m = *o
+ if o.Delay != nil {
+ m.Delay = &google_protobuf1.Duration{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Delay, o.Delay)
+ }
+ if o.Window != nil {
+ m.Window = &google_protobuf1.Duration{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Window, o.Window)
+ }
+}
+
+func (m *UpdateConfig) Copy() *UpdateConfig {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateConfig) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateConfig)
+ *m = *o
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Delay, &o.Delay)
+ if o.Monitor != nil {
+ m.Monitor = &google_protobuf1.Duration{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Monitor, o.Monitor)
+ }
+}
+
+func (m *UpdateStatus) Copy() *UpdateStatus {
+ if m == nil {
+ return nil
+ }
+ o := &UpdateStatus{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *UpdateStatus) CopyFrom(src interface{}) {
+
+ o := src.(*UpdateStatus)
+ *m = *o
+ if o.StartedAt != nil {
+ m.StartedAt = &google_protobuf.Timestamp{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.StartedAt, o.StartedAt)
+ }
+ if o.CompletedAt != nil {
+ m.CompletedAt = &google_protobuf.Timestamp{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.CompletedAt, o.CompletedAt)
+ }
+}
+
+func (m *ContainerStatus) Copy() *ContainerStatus {
+ if m == nil {
+ return nil
+ }
+ o := &ContainerStatus{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ContainerStatus) CopyFrom(src interface{}) {
+
+ o := src.(*ContainerStatus)
+ *m = *o
+}
+
+func (m *PortStatus) Copy() *PortStatus {
+ if m == nil {
+ return nil
+ }
+ o := &PortStatus{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *PortStatus) CopyFrom(src interface{}) {
+
+ o := src.(*PortStatus)
+ *m = *o
+ if o.Ports != nil {
+ m.Ports = make([]*PortConfig, len(o.Ports))
+ for i := range m.Ports {
+ m.Ports[i] = &PortConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Ports[i], o.Ports[i])
+ }
+ }
+
+}
+
+func (m *TaskStatus) Copy() *TaskStatus {
+ if m == nil {
+ return nil
+ }
+ o := &TaskStatus{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *TaskStatus) CopyFrom(src interface{}) {
+
+ o := src.(*TaskStatus)
+ *m = *o
+ if o.Timestamp != nil {
+ m.Timestamp = &google_protobuf.Timestamp{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Timestamp, o.Timestamp)
+ }
+ if o.PortStatus != nil {
+ m.PortStatus = &PortStatus{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.PortStatus, o.PortStatus)
+ }
+ if o.RuntimeStatus != nil {
+ switch o.RuntimeStatus.(type) {
+ case *TaskStatus_Container:
+ v := TaskStatus_Container{
+ Container: &ContainerStatus{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Container, o.GetContainer())
+ m.RuntimeStatus = &v
+ }
+ }
+
+}
+
+func (m *NetworkAttachmentConfig) Copy() *NetworkAttachmentConfig {
+ if m == nil {
+ return nil
+ }
+ o := &NetworkAttachmentConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *NetworkAttachmentConfig) CopyFrom(src interface{}) {
+
+ o := src.(*NetworkAttachmentConfig)
+ *m = *o
+ if o.Aliases != nil {
+ m.Aliases = make([]string, len(o.Aliases))
+ copy(m.Aliases, o.Aliases)
+ }
+
+ if o.Addresses != nil {
+ m.Addresses = make([]string, len(o.Addresses))
+ copy(m.Addresses, o.Addresses)
+ }
+
+ if o.DriverAttachmentOpts != nil {
+ m.DriverAttachmentOpts = make(map[string]string, len(o.DriverAttachmentOpts))
+ for k, v := range o.DriverAttachmentOpts {
+ m.DriverAttachmentOpts[k] = v
+ }
+ }
+
+}
+
+func (m *IPAMConfig) Copy() *IPAMConfig {
+ if m == nil {
+ return nil
+ }
+ o := &IPAMConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *IPAMConfig) CopyFrom(src interface{}) {
+
+ o := src.(*IPAMConfig)
+ *m = *o
+ if o.Reserved != nil {
+ m.Reserved = make(map[string]string, len(o.Reserved))
+ for k, v := range o.Reserved {
+ m.Reserved[k] = v
+ }
+ }
+
+}
+
+func (m *PortConfig) Copy() *PortConfig {
+ if m == nil {
+ return nil
+ }
+ o := &PortConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *PortConfig) CopyFrom(src interface{}) {
+
+ o := src.(*PortConfig)
+ *m = *o
+}
+
+func (m *Driver) Copy() *Driver {
+ if m == nil {
+ return nil
+ }
+ o := &Driver{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Driver) CopyFrom(src interface{}) {
+
+ o := src.(*Driver)
+ *m = *o
+ if o.Options != nil {
+ m.Options = make(map[string]string, len(o.Options))
+ for k, v := range o.Options {
+ m.Options[k] = v
+ }
+ }
+
+}
+
+func (m *IPAMOptions) Copy() *IPAMOptions {
+ if m == nil {
+ return nil
+ }
+ o := &IPAMOptions{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *IPAMOptions) CopyFrom(src interface{}) {
+
+ o := src.(*IPAMOptions)
+ *m = *o
+ if o.Driver != nil {
+ m.Driver = &Driver{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Driver, o.Driver)
+ }
+ if o.Configs != nil {
+ m.Configs = make([]*IPAMConfig, len(o.Configs))
+ for i := range m.Configs {
+ m.Configs[i] = &IPAMConfig{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Configs[i], o.Configs[i])
+ }
+ }
+
+}
+
+func (m *Peer) Copy() *Peer {
+ if m == nil {
+ return nil
+ }
+ o := &Peer{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Peer) CopyFrom(src interface{}) {
+
+ o := src.(*Peer)
+ *m = *o
+}
+
+func (m *WeightedPeer) Copy() *WeightedPeer {
+ if m == nil {
+ return nil
+ }
+ o := &WeightedPeer{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *WeightedPeer) CopyFrom(src interface{}) {
+
+ o := src.(*WeightedPeer)
+ *m = *o
+ if o.Peer != nil {
+ m.Peer = &Peer{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Peer, o.Peer)
+ }
+}
+
+func (m *IssuanceStatus) Copy() *IssuanceStatus {
+ if m == nil {
+ return nil
+ }
+ o := &IssuanceStatus{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *IssuanceStatus) CopyFrom(src interface{}) {
+
+ o := src.(*IssuanceStatus)
+ *m = *o
+}
+
+func (m *AcceptancePolicy) Copy() *AcceptancePolicy {
+ if m == nil {
+ return nil
+ }
+ o := &AcceptancePolicy{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *AcceptancePolicy) CopyFrom(src interface{}) {
+
+ o := src.(*AcceptancePolicy)
+ *m = *o
+ if o.Policies != nil {
+ m.Policies = make([]*AcceptancePolicy_RoleAdmissionPolicy, len(o.Policies))
+ for i := range m.Policies {
+ m.Policies[i] = &AcceptancePolicy_RoleAdmissionPolicy{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Policies[i], o.Policies[i])
+ }
+ }
+
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy) Copy() *AcceptancePolicy_RoleAdmissionPolicy {
+ if m == nil {
+ return nil
+ }
+ o := &AcceptancePolicy_RoleAdmissionPolicy{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy) CopyFrom(src interface{}) {
+
+ o := src.(*AcceptancePolicy_RoleAdmissionPolicy)
+ *m = *o
+ if o.Secret != nil {
+ m.Secret = &AcceptancePolicy_RoleAdmissionPolicy_Secret{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Secret, o.Secret)
+ }
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy_Secret) Copy() *AcceptancePolicy_RoleAdmissionPolicy_Secret {
+ if m == nil {
+ return nil
+ }
+ o := &AcceptancePolicy_RoleAdmissionPolicy_Secret{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy_Secret) CopyFrom(src interface{}) {
+
+ o := src.(*AcceptancePolicy_RoleAdmissionPolicy_Secret)
+ *m = *o
+ if o.Data != nil {
+ m.Data = make([]byte, len(o.Data))
+ copy(m.Data, o.Data)
+ }
+}
+
+func (m *ExternalCA) Copy() *ExternalCA {
+ if m == nil {
+ return nil
+ }
+ o := &ExternalCA{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ExternalCA) CopyFrom(src interface{}) {
+
+ o := src.(*ExternalCA)
+ *m = *o
+ if o.Options != nil {
+ m.Options = make(map[string]string, len(o.Options))
+ for k, v := range o.Options {
+ m.Options[k] = v
+ }
+ }
+
+ if o.CACert != nil {
+ m.CACert = make([]byte, len(o.CACert))
+ copy(m.CACert, o.CACert)
+ }
+}
+
+func (m *CAConfig) Copy() *CAConfig {
+ if m == nil {
+ return nil
+ }
+ o := &CAConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *CAConfig) CopyFrom(src interface{}) {
+
+ o := src.(*CAConfig)
+ *m = *o
+ if o.NodeCertExpiry != nil {
+ m.NodeCertExpiry = &google_protobuf1.Duration{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.NodeCertExpiry, o.NodeCertExpiry)
+ }
+ if o.ExternalCAs != nil {
+ m.ExternalCAs = make([]*ExternalCA, len(o.ExternalCAs))
+ for i := range m.ExternalCAs {
+ m.ExternalCAs[i] = &ExternalCA{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.ExternalCAs[i], o.ExternalCAs[i])
+ }
+ }
+
+ if o.SigningCACert != nil {
+ m.SigningCACert = make([]byte, len(o.SigningCACert))
+ copy(m.SigningCACert, o.SigningCACert)
+ }
+ if o.SigningCAKey != nil {
+ m.SigningCAKey = make([]byte, len(o.SigningCAKey))
+ copy(m.SigningCAKey, o.SigningCAKey)
+ }
+}
+
+func (m *OrchestrationConfig) Copy() *OrchestrationConfig {
+ if m == nil {
+ return nil
+ }
+ o := &OrchestrationConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *OrchestrationConfig) CopyFrom(src interface{}) {
+
+ o := src.(*OrchestrationConfig)
+ *m = *o
+}
+
+func (m *TaskDefaults) Copy() *TaskDefaults {
+ if m == nil {
+ return nil
+ }
+ o := &TaskDefaults{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *TaskDefaults) CopyFrom(src interface{}) {
+
+ o := src.(*TaskDefaults)
+ *m = *o
+ if o.LogDriver != nil {
+ m.LogDriver = &Driver{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.LogDriver, o.LogDriver)
+ }
+}
+
+func (m *DispatcherConfig) Copy() *DispatcherConfig {
+ if m == nil {
+ return nil
+ }
+ o := &DispatcherConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *DispatcherConfig) CopyFrom(src interface{}) {
+
+ o := src.(*DispatcherConfig)
+ *m = *o
+ if o.HeartbeatPeriod != nil {
+ m.HeartbeatPeriod = &google_protobuf1.Duration{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.HeartbeatPeriod, o.HeartbeatPeriod)
+ }
+}
+
+func (m *RaftConfig) Copy() *RaftConfig {
+ if m == nil {
+ return nil
+ }
+ o := &RaftConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RaftConfig) CopyFrom(src interface{}) {
+
+ o := src.(*RaftConfig)
+ *m = *o
+}
+
+func (m *EncryptionConfig) Copy() *EncryptionConfig {
+ if m == nil {
+ return nil
+ }
+ o := &EncryptionConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *EncryptionConfig) CopyFrom(src interface{}) {
+
+ o := src.(*EncryptionConfig)
+ *m = *o
+}
+
+func (m *SpreadOver) Copy() *SpreadOver {
+ if m == nil {
+ return nil
+ }
+ o := &SpreadOver{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SpreadOver) CopyFrom(src interface{}) {
+
+ o := src.(*SpreadOver)
+ *m = *o
+}
+
+func (m *PlacementPreference) Copy() *PlacementPreference {
+ if m == nil {
+ return nil
+ }
+ o := &PlacementPreference{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *PlacementPreference) CopyFrom(src interface{}) {
+
+ o := src.(*PlacementPreference)
+ *m = *o
+ if o.Preference != nil {
+ switch o.Preference.(type) {
+ case *PlacementPreference_Spread:
+ v := PlacementPreference_Spread{
+ Spread: &SpreadOver{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Spread, o.GetSpread())
+ m.Preference = &v
+ }
+ }
+
+}
+
+func (m *Placement) Copy() *Placement {
+ if m == nil {
+ return nil
+ }
+ o := &Placement{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Placement) CopyFrom(src interface{}) {
+
+ o := src.(*Placement)
+ *m = *o
+ if o.Constraints != nil {
+ m.Constraints = make([]string, len(o.Constraints))
+ copy(m.Constraints, o.Constraints)
+ }
+
+ if o.Preferences != nil {
+ m.Preferences = make([]*PlacementPreference, len(o.Preferences))
+ for i := range m.Preferences {
+ m.Preferences[i] = &PlacementPreference{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Preferences[i], o.Preferences[i])
+ }
+ }
+
+ if o.Platforms != nil {
+ m.Platforms = make([]*Platform, len(o.Platforms))
+ for i := range m.Platforms {
+ m.Platforms[i] = &Platform{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Platforms[i], o.Platforms[i])
+ }
+ }
+
+}
+
+func (m *JoinTokens) Copy() *JoinTokens {
+ if m == nil {
+ return nil
+ }
+ o := &JoinTokens{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *JoinTokens) CopyFrom(src interface{}) {
+
+ o := src.(*JoinTokens)
+ *m = *o
+}
+
+func (m *RootCA) Copy() *RootCA {
+ if m == nil {
+ return nil
+ }
+ o := &RootCA{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RootCA) CopyFrom(src interface{}) {
+
+ o := src.(*RootCA)
+ *m = *o
+ if o.CAKey != nil {
+ m.CAKey = make([]byte, len(o.CAKey))
+ copy(m.CAKey, o.CAKey)
+ }
+ if o.CACert != nil {
+ m.CACert = make([]byte, len(o.CACert))
+ copy(m.CACert, o.CACert)
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.JoinTokens, &o.JoinTokens)
+ if o.RootRotation != nil {
+ m.RootRotation = &RootRotation{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.RootRotation, o.RootRotation)
+ }
+}
+
+func (m *Certificate) Copy() *Certificate {
+ if m == nil {
+ return nil
+ }
+ o := &Certificate{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Certificate) CopyFrom(src interface{}) {
+
+ o := src.(*Certificate)
+ *m = *o
+ if o.CSR != nil {
+ m.CSR = make([]byte, len(o.CSR))
+ copy(m.CSR, o.CSR)
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(&m.Status, &o.Status)
+ if o.Certificate != nil {
+ m.Certificate = make([]byte, len(o.Certificate))
+ copy(m.Certificate, o.Certificate)
+ }
+}
+
+func (m *EncryptionKey) Copy() *EncryptionKey {
+ if m == nil {
+ return nil
+ }
+ o := &EncryptionKey{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *EncryptionKey) CopyFrom(src interface{}) {
+
+ o := src.(*EncryptionKey)
+ *m = *o
+ if o.Key != nil {
+ m.Key = make([]byte, len(o.Key))
+ copy(m.Key, o.Key)
+ }
+}
+
+func (m *ManagerStatus) Copy() *ManagerStatus {
+ if m == nil {
+ return nil
+ }
+ o := &ManagerStatus{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ManagerStatus) CopyFrom(src interface{}) {
+
+ o := src.(*ManagerStatus)
+ *m = *o
+}
+
+func (m *FileTarget) Copy() *FileTarget {
+ if m == nil {
+ return nil
+ }
+ o := &FileTarget{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *FileTarget) CopyFrom(src interface{}) {
+
+ o := src.(*FileTarget)
+ *m = *o
+}
+
+func (m *SecretReference) Copy() *SecretReference {
+ if m == nil {
+ return nil
+ }
+ o := &SecretReference{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SecretReference) CopyFrom(src interface{}) {
+
+ o := src.(*SecretReference)
+ *m = *o
+ if o.Target != nil {
+ switch o.Target.(type) {
+ case *SecretReference_File:
+ v := SecretReference_File{
+ File: &FileTarget{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.File, o.GetFile())
+ m.Target = &v
+ }
+ }
+
+}
+
+func (m *ConfigReference) Copy() *ConfigReference {
+ if m == nil {
+ return nil
+ }
+ o := &ConfigReference{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *ConfigReference) CopyFrom(src interface{}) {
+
+ o := src.(*ConfigReference)
+ *m = *o
+ if o.Target != nil {
+ switch o.Target.(type) {
+ case *ConfigReference_File:
+ v := ConfigReference_File{
+ File: &FileTarget{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.File, o.GetFile())
+ m.Target = &v
+ }
+ }
+
+}
+
+func (m *BlacklistedCertificate) Copy() *BlacklistedCertificate {
+ if m == nil {
+ return nil
+ }
+ o := &BlacklistedCertificate{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *BlacklistedCertificate) CopyFrom(src interface{}) {
+
+ o := src.(*BlacklistedCertificate)
+ *m = *o
+ if o.Expiry != nil {
+ m.Expiry = &google_protobuf.Timestamp{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Expiry, o.Expiry)
+ }
+}
+
+func (m *HealthConfig) Copy() *HealthConfig {
+ if m == nil {
+ return nil
+ }
+ o := &HealthConfig{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *HealthConfig) CopyFrom(src interface{}) {
+
+ o := src.(*HealthConfig)
+ *m = *o
+ if o.Test != nil {
+ m.Test = make([]string, len(o.Test))
+ copy(m.Test, o.Test)
+ }
+
+ if o.Interval != nil {
+ m.Interval = &google_protobuf1.Duration{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Interval, o.Interval)
+ }
+ if o.Timeout != nil {
+ m.Timeout = &google_protobuf1.Duration{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Timeout, o.Timeout)
+ }
+ if o.StartPeriod != nil {
+ m.StartPeriod = &google_protobuf1.Duration{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.StartPeriod, o.StartPeriod)
+ }
+}
+
+func (m *MaybeEncryptedRecord) Copy() *MaybeEncryptedRecord {
+ if m == nil {
+ return nil
+ }
+ o := &MaybeEncryptedRecord{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *MaybeEncryptedRecord) CopyFrom(src interface{}) {
+
+ o := src.(*MaybeEncryptedRecord)
+ *m = *o
+ if o.Data != nil {
+ m.Data = make([]byte, len(o.Data))
+ copy(m.Data, o.Data)
+ }
+ if o.Nonce != nil {
+ m.Nonce = make([]byte, len(o.Nonce))
+ copy(m.Nonce, o.Nonce)
+ }
+}
+
+func (m *RootRotation) Copy() *RootRotation {
+ if m == nil {
+ return nil
+ }
+ o := &RootRotation{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *RootRotation) CopyFrom(src interface{}) {
+
+ o := src.(*RootRotation)
+ *m = *o
+ if o.CACert != nil {
+ m.CACert = make([]byte, len(o.CACert))
+ copy(m.CACert, o.CACert)
+ }
+ if o.CAKey != nil {
+ m.CAKey = make([]byte, len(o.CAKey))
+ copy(m.CAKey, o.CAKey)
+ }
+ if o.CrossSignedCACert != nil {
+ m.CrossSignedCACert = make([]byte, len(o.CrossSignedCACert))
+ copy(m.CrossSignedCACert, o.CrossSignedCACert)
+ }
+}
+
+func (m *Privileges) Copy() *Privileges {
+ if m == nil {
+ return nil
+ }
+ o := &Privileges{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Privileges) CopyFrom(src interface{}) {
+
+ o := src.(*Privileges)
+ *m = *o
+ if o.CredentialSpec != nil {
+ m.CredentialSpec = &Privileges_CredentialSpec{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.CredentialSpec, o.CredentialSpec)
+ }
+ if o.SELinuxContext != nil {
+ m.SELinuxContext = &Privileges_SELinuxContext{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.SELinuxContext, o.SELinuxContext)
+ }
+}
+
+func (m *Privileges_CredentialSpec) Copy() *Privileges_CredentialSpec {
+ if m == nil {
+ return nil
+ }
+ o := &Privileges_CredentialSpec{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Privileges_CredentialSpec) CopyFrom(src interface{}) {
+
+ o := src.(*Privileges_CredentialSpec)
+ *m = *o
+ if o.Source != nil {
+ switch o.Source.(type) {
+ case *Privileges_CredentialSpec_File:
+ v := Privileges_CredentialSpec_File{
+ File: o.GetFile(),
+ }
+ m.Source = &v
+ case *Privileges_CredentialSpec_Registry:
+ v := Privileges_CredentialSpec_Registry{
+ Registry: o.GetRegistry(),
+ }
+ m.Source = &v
+ }
+ }
+
+}
+
+func (m *Privileges_SELinuxContext) Copy() *Privileges_SELinuxContext {
+ if m == nil {
+ return nil
+ }
+ o := &Privileges_SELinuxContext{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Privileges_SELinuxContext) CopyFrom(src interface{}) {
+
+ o := src.(*Privileges_SELinuxContext)
+ *m = *o
+}
+
+func (m *Version) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Version) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Index != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Index))
+ }
+ return i, nil
+}
+
+func (m *IndexEntry) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *IndexEntry) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Key) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Key)))
+ i += copy(dAtA[i:], m.Key)
+ }
+ if len(m.Val) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Val)))
+ i += copy(dAtA[i:], m.Val)
+ }
+ return i, nil
+}
+
+func (m *Annotations) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Annotations) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Name) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Name)))
+ i += copy(dAtA[i:], m.Name)
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x12
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ i = encodeVarintTypes(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.Indices) > 0 {
+ for _, msg := range m.Indices {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *GenericString) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GenericString) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Kind) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Kind)))
+ i += copy(dAtA[i:], m.Kind)
+ }
+ if len(m.Value) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Value)))
+ i += copy(dAtA[i:], m.Value)
+ }
+ return i, nil
+}
+
+func (m *GenericDiscrete) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GenericDiscrete) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Kind) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Kind)))
+ i += copy(dAtA[i:], m.Kind)
+ }
+ if m.Value != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Value))
+ }
+ return i, nil
+}
+
+func (m *GenericResource) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *GenericResource) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Resource != nil {
+ nn1, err := m.Resource.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn1
+ }
+ return i, nil
+}
+
+func (m *GenericResource_Str) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Str != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Str.Size()))
+ n2, err := m.Str.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ }
+ return i, nil
+}
+func (m *GenericResource_Discrete) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Discrete != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Discrete.Size()))
+ n3, err := m.Discrete.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ }
+ return i, nil
+}
+func (m *Resources) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Resources) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.NanoCPUs != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.NanoCPUs))
+ }
+ if m.MemoryBytes != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.MemoryBytes))
+ }
+ if len(m.Generic) > 0 {
+ for _, msg := range m.Generic {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *ResourceRequirements) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ResourceRequirements) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Limits != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Limits.Size()))
+ n4, err := m.Limits.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n4
+ }
+ if m.Reservations != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Reservations.Size()))
+ n5, err := m.Reservations.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n5
+ }
+ return i, nil
+}
+
+func (m *Platform) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Platform) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Architecture) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Architecture)))
+ i += copy(dAtA[i:], m.Architecture)
+ }
+ if len(m.OS) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.OS)))
+ i += copy(dAtA[i:], m.OS)
+ }
+ return i, nil
+}
+
+func (m *PluginDescription) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *PluginDescription) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Type) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Type)))
+ i += copy(dAtA[i:], m.Type)
+ }
+ if len(m.Name) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Name)))
+ i += copy(dAtA[i:], m.Name)
+ }
+ return i, nil
+}
+
+func (m *EngineDescription) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *EngineDescription) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.EngineVersion) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.EngineVersion)))
+ i += copy(dAtA[i:], m.EngineVersion)
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x12
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ i = encodeVarintTypes(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.Plugins) > 0 {
+ for _, msg := range m.Plugins {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *NodeDescription) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NodeDescription) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Hostname) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Hostname)))
+ i += copy(dAtA[i:], m.Hostname)
+ }
+ if m.Platform != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Platform.Size()))
+ n6, err := m.Platform.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n6
+ }
+ if m.Resources != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Resources.Size()))
+ n7, err := m.Resources.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n7
+ }
+ if m.Engine != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Engine.Size()))
+ n8, err := m.Engine.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n8
+ }
+ if m.TLSInfo != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.TLSInfo.Size()))
+ n9, err := m.TLSInfo.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n9
+ }
+ return i, nil
+}
+
+func (m *NodeTLSInfo) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NodeTLSInfo) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.TrustRoot) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.TrustRoot)))
+ i += copy(dAtA[i:], m.TrustRoot)
+ }
+ if len(m.CertIssuerSubject) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CertIssuerSubject)))
+ i += copy(dAtA[i:], m.CertIssuerSubject)
+ }
+ if len(m.CertIssuerPublicKey) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CertIssuerPublicKey)))
+ i += copy(dAtA[i:], m.CertIssuerPublicKey)
+ }
+ return i, nil
+}
+
+func (m *RaftMemberStatus) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RaftMemberStatus) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Leader {
+ dAtA[i] = 0x8
+ i++
+ if m.Leader {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Reachability != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Reachability))
+ }
+ if len(m.Message) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Message)))
+ i += copy(dAtA[i:], m.Message)
+ }
+ return i, nil
+}
+
+func (m *NodeStatus) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NodeStatus) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.State != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.State))
+ }
+ if len(m.Message) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Message)))
+ i += copy(dAtA[i:], m.Message)
+ }
+ if len(m.Addr) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Addr)))
+ i += copy(dAtA[i:], m.Addr)
+ }
+ return i, nil
+}
+
+func (m *Image) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Image) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Reference) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Reference)))
+ i += copy(dAtA[i:], m.Reference)
+ }
+ return i, nil
+}
+
+func (m *Mount) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Mount) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Type != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Type))
+ }
+ if len(m.Source) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Source)))
+ i += copy(dAtA[i:], m.Source)
+ }
+ if len(m.Target) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Target)))
+ i += copy(dAtA[i:], m.Target)
+ }
+ if m.ReadOnly {
+ dAtA[i] = 0x20
+ i++
+ if m.ReadOnly {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.BindOptions != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.BindOptions.Size()))
+ n10, err := m.BindOptions.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n10
+ }
+ if m.VolumeOptions != nil {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.VolumeOptions.Size()))
+ n11, err := m.VolumeOptions.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n11
+ }
+ if m.TmpfsOptions != nil {
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.TmpfsOptions.Size()))
+ n12, err := m.TmpfsOptions.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n12
+ }
+ return i, nil
+}
+
+func (m *Mount_BindOptions) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Mount_BindOptions) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Propagation != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Propagation))
+ }
+ return i, nil
+}
+
+func (m *Mount_VolumeOptions) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Mount_VolumeOptions) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.NoCopy {
+ dAtA[i] = 0x8
+ i++
+ if m.NoCopy {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if len(m.Labels) > 0 {
+ for k, _ := range m.Labels {
+ dAtA[i] = 0x12
+ i++
+ v := m.Labels[k]
+ mapSize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ i = encodeVarintTypes(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if m.DriverConfig != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.DriverConfig.Size()))
+ n13, err := m.DriverConfig.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n13
+ }
+ return i, nil
+}
+
+func (m *Mount_TmpfsOptions) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Mount_TmpfsOptions) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.SizeBytes != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.SizeBytes))
+ }
+ if m.Mode != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Mode))
+ }
+ return i, nil
+}
+
+func (m *RestartPolicy) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RestartPolicy) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Condition != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Condition))
+ }
+ if m.Delay != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Delay.Size()))
+ n14, err := m.Delay.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n14
+ }
+ if m.MaxAttempts != 0 {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.MaxAttempts))
+ }
+ if m.Window != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Window.Size()))
+ n15, err := m.Window.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n15
+ }
+ return i, nil
+}
+
+func (m *UpdateConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Parallelism != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Parallelism))
+ }
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(github_com_gogo_protobuf_types.SizeOfStdDuration(m.Delay)))
+ n16, err := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.Delay, dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n16
+ if m.FailureAction != 0 {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.FailureAction))
+ }
+ if m.Monitor != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Monitor.Size()))
+ n17, err := m.Monitor.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n17
+ }
+ if m.MaxFailureRatio != 0 {
+ dAtA[i] = 0x2d
+ i++
+ i = encodeFixed32Types(dAtA, i, uint32(math.Float32bits(float32(m.MaxFailureRatio))))
+ }
+ if m.Order != 0 {
+ dAtA[i] = 0x30
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Order))
+ }
+ return i, nil
+}
+
+func (m *UpdateStatus) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UpdateStatus) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.State != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.State))
+ }
+ if m.StartedAt != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.StartedAt.Size()))
+ n18, err := m.StartedAt.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n18
+ }
+ if m.CompletedAt != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.CompletedAt.Size()))
+ n19, err := m.CompletedAt.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n19
+ }
+ if len(m.Message) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Message)))
+ i += copy(dAtA[i:], m.Message)
+ }
+ return i, nil
+}
+
+func (m *ContainerStatus) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ContainerStatus) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ContainerID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.ContainerID)))
+ i += copy(dAtA[i:], m.ContainerID)
+ }
+ if m.PID != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.PID))
+ }
+ if m.ExitCode != 0 {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.ExitCode))
+ }
+ return i, nil
+}
+
+func (m *PortStatus) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *PortStatus) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Ports) > 0 {
+ for _, msg := range m.Ports {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *TaskStatus) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *TaskStatus) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Timestamp != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Timestamp.Size()))
+ n20, err := m.Timestamp.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n20
+ }
+ if m.State != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.State))
+ }
+ if len(m.Message) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Message)))
+ i += copy(dAtA[i:], m.Message)
+ }
+ if len(m.Err) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Err)))
+ i += copy(dAtA[i:], m.Err)
+ }
+ if m.RuntimeStatus != nil {
+ nn21, err := m.RuntimeStatus.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn21
+ }
+ if m.PortStatus != nil {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.PortStatus.Size()))
+ n22, err := m.PortStatus.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n22
+ }
+ return i, nil
+}
+
+func (m *TaskStatus_Container) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Container != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Container.Size()))
+ n23, err := m.Container.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n23
+ }
+ return i, nil
+}
+func (m *NetworkAttachmentConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NetworkAttachmentConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Target) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Target)))
+ i += copy(dAtA[i:], m.Target)
+ }
+ if len(m.Aliases) > 0 {
+ for _, s := range m.Aliases {
+ dAtA[i] = 0x12
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Addresses) > 0 {
+ for _, s := range m.Addresses {
+ dAtA[i] = 0x1a
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.DriverAttachmentOpts) > 0 {
+ for k, _ := range m.DriverAttachmentOpts {
+ dAtA[i] = 0x22
+ i++
+ v := m.DriverAttachmentOpts[k]
+ mapSize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ i = encodeVarintTypes(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ return i, nil
+}
+
+func (m *IPAMConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *IPAMConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Family != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Family))
+ }
+ if len(m.Subnet) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Subnet)))
+ i += copy(dAtA[i:], m.Subnet)
+ }
+ if len(m.Range) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Range)))
+ i += copy(dAtA[i:], m.Range)
+ }
+ if len(m.Gateway) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Gateway)))
+ i += copy(dAtA[i:], m.Gateway)
+ }
+ if len(m.Reserved) > 0 {
+ for k, _ := range m.Reserved {
+ dAtA[i] = 0x2a
+ i++
+ v := m.Reserved[k]
+ mapSize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ i = encodeVarintTypes(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ return i, nil
+}
+
+func (m *PortConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *PortConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Name) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Name)))
+ i += copy(dAtA[i:], m.Name)
+ }
+ if m.Protocol != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Protocol))
+ }
+ if m.TargetPort != 0 {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.TargetPort))
+ }
+ if m.PublishedPort != 0 {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.PublishedPort))
+ }
+ if m.PublishMode != 0 {
+ dAtA[i] = 0x28
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.PublishMode))
+ }
+ return i, nil
+}
+
+func (m *Driver) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Driver) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Name) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Name)))
+ i += copy(dAtA[i:], m.Name)
+ }
+ if len(m.Options) > 0 {
+ for k, _ := range m.Options {
+ dAtA[i] = 0x12
+ i++
+ v := m.Options[k]
+ mapSize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ i = encodeVarintTypes(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ return i, nil
+}
+
+func (m *IPAMOptions) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *IPAMOptions) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Driver != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Driver.Size()))
+ n24, err := m.Driver.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n24
+ }
+ if len(m.Configs) > 0 {
+ for _, msg := range m.Configs {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *Peer) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Peer) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.NodeID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.NodeID)))
+ i += copy(dAtA[i:], m.NodeID)
+ }
+ if len(m.Addr) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Addr)))
+ i += copy(dAtA[i:], m.Addr)
+ }
+ return i, nil
+}
+
+func (m *WeightedPeer) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *WeightedPeer) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Peer != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Peer.Size()))
+ n25, err := m.Peer.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n25
+ }
+ if m.Weight != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Weight))
+ }
+ return i, nil
+}
+
+func (m *IssuanceStatus) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *IssuanceStatus) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.State != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.State))
+ }
+ if len(m.Err) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Err)))
+ i += copy(dAtA[i:], m.Err)
+ }
+ return i, nil
+}
+
+func (m *AcceptancePolicy) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *AcceptancePolicy) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Policies) > 0 {
+ for _, msg := range m.Policies {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Role != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Role))
+ }
+ if m.Autoaccept {
+ dAtA[i] = 0x10
+ i++
+ if m.Autoaccept {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Secret != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Secret.Size()))
+ n26, err := m.Secret.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n26
+ }
+ return i, nil
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy_Secret) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy_Secret) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Data) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Data)))
+ i += copy(dAtA[i:], m.Data)
+ }
+ if len(m.Alg) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Alg)))
+ i += copy(dAtA[i:], m.Alg)
+ }
+ return i, nil
+}
+
+func (m *ExternalCA) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ExternalCA) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Protocol != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Protocol))
+ }
+ if len(m.URL) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.URL)))
+ i += copy(dAtA[i:], m.URL)
+ }
+ if len(m.Options) > 0 {
+ for k, _ := range m.Options {
+ dAtA[i] = 0x1a
+ i++
+ v := m.Options[k]
+ mapSize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ i = encodeVarintTypes(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ if len(m.CACert) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CACert)))
+ i += copy(dAtA[i:], m.CACert)
+ }
+ return i, nil
+}
+
+func (m *CAConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CAConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.NodeCertExpiry != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.NodeCertExpiry.Size()))
+ n27, err := m.NodeCertExpiry.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n27
+ }
+ if len(m.ExternalCAs) > 0 {
+ for _, msg := range m.ExternalCAs {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.SigningCACert) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.SigningCACert)))
+ i += copy(dAtA[i:], m.SigningCACert)
+ }
+ if len(m.SigningCAKey) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.SigningCAKey)))
+ i += copy(dAtA[i:], m.SigningCAKey)
+ }
+ if m.ForceRotate != 0 {
+ dAtA[i] = 0x28
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.ForceRotate))
+ }
+ return i, nil
+}
+
+func (m *OrchestrationConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *OrchestrationConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.TaskHistoryRetentionLimit != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.TaskHistoryRetentionLimit))
+ }
+ return i, nil
+}
+
+func (m *TaskDefaults) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *TaskDefaults) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.LogDriver != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.LogDriver.Size()))
+ n28, err := m.LogDriver.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n28
+ }
+ return i, nil
+}
+
+func (m *DispatcherConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *DispatcherConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.HeartbeatPeriod != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.HeartbeatPeriod.Size()))
+ n29, err := m.HeartbeatPeriod.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n29
+ }
+ return i, nil
+}
+
+func (m *RaftConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RaftConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.SnapshotInterval != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.SnapshotInterval))
+ }
+ if m.KeepOldSnapshots != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.KeepOldSnapshots))
+ }
+ if m.LogEntriesForSlowFollowers != 0 {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.LogEntriesForSlowFollowers))
+ }
+ if m.HeartbeatTick != 0 {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.HeartbeatTick))
+ }
+ if m.ElectionTick != 0 {
+ dAtA[i] = 0x28
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.ElectionTick))
+ }
+ return i, nil
+}
+
+func (m *EncryptionConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *EncryptionConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.AutoLockManagers {
+ dAtA[i] = 0x8
+ i++
+ if m.AutoLockManagers {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ return i, nil
+}
+
+func (m *SpreadOver) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SpreadOver) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SpreadDescriptor) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.SpreadDescriptor)))
+ i += copy(dAtA[i:], m.SpreadDescriptor)
+ }
+ return i, nil
+}
+
+func (m *PlacementPreference) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *PlacementPreference) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Preference != nil {
+ nn30, err := m.Preference.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn30
+ }
+ return i, nil
+}
+
+func (m *PlacementPreference_Spread) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Spread != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Spread.Size()))
+ n31, err := m.Spread.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n31
+ }
+ return i, nil
+}
+func (m *Placement) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Placement) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Constraints) > 0 {
+ for _, s := range m.Constraints {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if len(m.Preferences) > 0 {
+ for _, msg := range m.Preferences {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if len(m.Platforms) > 0 {
+ for _, msg := range m.Platforms {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *JoinTokens) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *JoinTokens) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Worker) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Worker)))
+ i += copy(dAtA[i:], m.Worker)
+ }
+ if len(m.Manager) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Manager)))
+ i += copy(dAtA[i:], m.Manager)
+ }
+ return i, nil
+}
+
+func (m *RootCA) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RootCA) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.CAKey) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CAKey)))
+ i += copy(dAtA[i:], m.CAKey)
+ }
+ if len(m.CACert) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CACert)))
+ i += copy(dAtA[i:], m.CACert)
+ }
+ if len(m.CACertHash) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CACertHash)))
+ i += copy(dAtA[i:], m.CACertHash)
+ }
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.JoinTokens.Size()))
+ n32, err := m.JoinTokens.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n32
+ if m.RootRotation != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.RootRotation.Size()))
+ n33, err := m.RootRotation.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n33
+ }
+ if m.LastForcedRotation != 0 {
+ dAtA[i] = 0x30
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.LastForcedRotation))
+ }
+ return i, nil
+}
+
+func (m *Certificate) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Certificate) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Role != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Role))
+ }
+ if len(m.CSR) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CSR)))
+ i += copy(dAtA[i:], m.CSR)
+ }
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Status.Size()))
+ n34, err := m.Status.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n34
+ if len(m.Certificate) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Certificate)))
+ i += copy(dAtA[i:], m.Certificate)
+ }
+ if len(m.CN) > 0 {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CN)))
+ i += copy(dAtA[i:], m.CN)
+ }
+ return i, nil
+}
+
+func (m *EncryptionKey) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *EncryptionKey) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Subsystem) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Subsystem)))
+ i += copy(dAtA[i:], m.Subsystem)
+ }
+ if m.Algorithm != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Algorithm))
+ }
+ if len(m.Key) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Key)))
+ i += copy(dAtA[i:], m.Key)
+ }
+ if m.LamportTime != 0 {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.LamportTime))
+ }
+ return i, nil
+}
+
+func (m *ManagerStatus) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ManagerStatus) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.RaftID != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.RaftID))
+ }
+ if len(m.Addr) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Addr)))
+ i += copy(dAtA[i:], m.Addr)
+ }
+ if m.Leader {
+ dAtA[i] = 0x18
+ i++
+ if m.Leader {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Reachability != 0 {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Reachability))
+ }
+ return i, nil
+}
+
+func (m *FileTarget) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *FileTarget) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Name) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Name)))
+ i += copy(dAtA[i:], m.Name)
+ }
+ if len(m.UID) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.UID)))
+ i += copy(dAtA[i:], m.UID)
+ }
+ if len(m.GID) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.GID)))
+ i += copy(dAtA[i:], m.GID)
+ }
+ if m.Mode != 0 {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Mode))
+ }
+ return i, nil
+}
+
+func (m *SecretReference) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SecretReference) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.SecretID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.SecretID)))
+ i += copy(dAtA[i:], m.SecretID)
+ }
+ if len(m.SecretName) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.SecretName)))
+ i += copy(dAtA[i:], m.SecretName)
+ }
+ if m.Target != nil {
+ nn35, err := m.Target.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn35
+ }
+ return i, nil
+}
+
+func (m *SecretReference_File) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.File != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.File.Size()))
+ n36, err := m.File.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n36
+ }
+ return i, nil
+}
+func (m *ConfigReference) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ConfigReference) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ConfigID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.ConfigID)))
+ i += copy(dAtA[i:], m.ConfigID)
+ }
+ if len(m.ConfigName) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.ConfigName)))
+ i += copy(dAtA[i:], m.ConfigName)
+ }
+ if m.Target != nil {
+ nn37, err := m.Target.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn37
+ }
+ return i, nil
+}
+
+func (m *ConfigReference_File) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.File != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.File.Size()))
+ n38, err := m.File.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n38
+ }
+ return i, nil
+}
+func (m *BlacklistedCertificate) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *BlacklistedCertificate) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Expiry != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Expiry.Size()))
+ n39, err := m.Expiry.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n39
+ }
+ return i, nil
+}
+
+func (m *HealthConfig) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *HealthConfig) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Test) > 0 {
+ for _, s := range m.Test {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if m.Interval != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Interval.Size()))
+ n40, err := m.Interval.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n40
+ }
+ if m.Timeout != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Timeout.Size()))
+ n41, err := m.Timeout.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n41
+ }
+ if m.Retries != 0 {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Retries))
+ }
+ if m.StartPeriod != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.StartPeriod.Size()))
+ n42, err := m.StartPeriod.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n42
+ }
+ return i, nil
+}
+
+func (m *MaybeEncryptedRecord) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *MaybeEncryptedRecord) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Algorithm != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.Algorithm))
+ }
+ if len(m.Data) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Data)))
+ i += copy(dAtA[i:], m.Data)
+ }
+ if len(m.Nonce) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Nonce)))
+ i += copy(dAtA[i:], m.Nonce)
+ }
+ return i, nil
+}
+
+func (m *RootRotation) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RootRotation) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.CACert) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CACert)))
+ i += copy(dAtA[i:], m.CACert)
+ }
+ if len(m.CAKey) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CAKey)))
+ i += copy(dAtA[i:], m.CAKey)
+ }
+ if len(m.CrossSignedCACert) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.CrossSignedCACert)))
+ i += copy(dAtA[i:], m.CrossSignedCACert)
+ }
+ return i, nil
+}
+
+func (m *Privileges) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Privileges) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.CredentialSpec != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.CredentialSpec.Size()))
+ n43, err := m.CredentialSpec.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n43
+ }
+ if m.SELinuxContext != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(m.SELinuxContext.Size()))
+ n44, err := m.SELinuxContext.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n44
+ }
+ return i, nil
+}
+
+func (m *Privileges_CredentialSpec) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Privileges_CredentialSpec) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Source != nil {
+ nn45, err := m.Source.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn45
+ }
+ return i, nil
+}
+
+func (m *Privileges_CredentialSpec_File) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.File)))
+ i += copy(dAtA[i:], m.File)
+ return i, nil
+}
+func (m *Privileges_CredentialSpec_Registry) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Registry)))
+ i += copy(dAtA[i:], m.Registry)
+ return i, nil
+}
+func (m *Privileges_SELinuxContext) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Privileges_SELinuxContext) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Disable {
+ dAtA[i] = 0x8
+ i++
+ if m.Disable {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if len(m.User) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.User)))
+ i += copy(dAtA[i:], m.User)
+ }
+ if len(m.Role) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Role)))
+ i += copy(dAtA[i:], m.Role)
+ }
+ if len(m.Type) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Type)))
+ i += copy(dAtA[i:], m.Type)
+ }
+ if len(m.Level) > 0 {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintTypes(dAtA, i, uint64(len(m.Level)))
+ i += copy(dAtA[i:], m.Level)
+ }
+ return i, nil
+}
+
+func encodeFixed64Types(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Types(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintTypes(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+func (m *Version) Size() (n int) {
+ var l int
+ _ = l
+ if m.Index != 0 {
+ n += 1 + sovTypes(uint64(m.Index))
+ }
+ return n
+}
+
+func (m *IndexEntry) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Key)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Val)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *Annotations) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Name)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize))
+ }
+ }
+ if len(m.Indices) > 0 {
+ for _, e := range m.Indices {
+ l = e.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *GenericString) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Kind)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Value)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *GenericDiscrete) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Kind)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Value != 0 {
+ n += 1 + sovTypes(uint64(m.Value))
+ }
+ return n
+}
+
+func (m *GenericResource) Size() (n int) {
+ var l int
+ _ = l
+ if m.Resource != nil {
+ n += m.Resource.Size()
+ }
+ return n
+}
+
+func (m *GenericResource_Str) Size() (n int) {
+ var l int
+ _ = l
+ if m.Str != nil {
+ l = m.Str.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+func (m *GenericResource_Discrete) Size() (n int) {
+ var l int
+ _ = l
+ if m.Discrete != nil {
+ l = m.Discrete.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+func (m *Resources) Size() (n int) {
+ var l int
+ _ = l
+ if m.NanoCPUs != 0 {
+ n += 1 + sovTypes(uint64(m.NanoCPUs))
+ }
+ if m.MemoryBytes != 0 {
+ n += 1 + sovTypes(uint64(m.MemoryBytes))
+ }
+ if len(m.Generic) > 0 {
+ for _, e := range m.Generic {
+ l = e.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *ResourceRequirements) Size() (n int) {
+ var l int
+ _ = l
+ if m.Limits != nil {
+ l = m.Limits.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Reservations != nil {
+ l = m.Reservations.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *Platform) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Architecture)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.OS)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *PluginDescription) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Type)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Name)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *EngineDescription) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.EngineVersion)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize))
+ }
+ }
+ if len(m.Plugins) > 0 {
+ for _, e := range m.Plugins {
+ l = e.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *NodeDescription) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Hostname)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Platform != nil {
+ l = m.Platform.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Resources != nil {
+ l = m.Resources.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Engine != nil {
+ l = m.Engine.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.TLSInfo != nil {
+ l = m.TLSInfo.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *NodeTLSInfo) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.TrustRoot)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.CertIssuerSubject)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.CertIssuerPublicKey)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *RaftMemberStatus) Size() (n int) {
+ var l int
+ _ = l
+ if m.Leader {
+ n += 2
+ }
+ if m.Reachability != 0 {
+ n += 1 + sovTypes(uint64(m.Reachability))
+ }
+ l = len(m.Message)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *NodeStatus) Size() (n int) {
+ var l int
+ _ = l
+ if m.State != 0 {
+ n += 1 + sovTypes(uint64(m.State))
+ }
+ l = len(m.Message)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Addr)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *Image) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Reference)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *Mount) Size() (n int) {
+ var l int
+ _ = l
+ if m.Type != 0 {
+ n += 1 + sovTypes(uint64(m.Type))
+ }
+ l = len(m.Source)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Target)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.ReadOnly {
+ n += 2
+ }
+ if m.BindOptions != nil {
+ l = m.BindOptions.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.VolumeOptions != nil {
+ l = m.VolumeOptions.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.TmpfsOptions != nil {
+ l = m.TmpfsOptions.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *Mount_BindOptions) Size() (n int) {
+ var l int
+ _ = l
+ if m.Propagation != 0 {
+ n += 1 + sovTypes(uint64(m.Propagation))
+ }
+ return n
+}
+
+func (m *Mount_VolumeOptions) Size() (n int) {
+ var l int
+ _ = l
+ if m.NoCopy {
+ n += 2
+ }
+ if len(m.Labels) > 0 {
+ for k, v := range m.Labels {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize))
+ }
+ }
+ if m.DriverConfig != nil {
+ l = m.DriverConfig.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *Mount_TmpfsOptions) Size() (n int) {
+ var l int
+ _ = l
+ if m.SizeBytes != 0 {
+ n += 1 + sovTypes(uint64(m.SizeBytes))
+ }
+ if m.Mode != 0 {
+ n += 1 + sovTypes(uint64(m.Mode))
+ }
+ return n
+}
+
+func (m *RestartPolicy) Size() (n int) {
+ var l int
+ _ = l
+ if m.Condition != 0 {
+ n += 1 + sovTypes(uint64(m.Condition))
+ }
+ if m.Delay != nil {
+ l = m.Delay.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.MaxAttempts != 0 {
+ n += 1 + sovTypes(uint64(m.MaxAttempts))
+ }
+ if m.Window != nil {
+ l = m.Window.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *UpdateConfig) Size() (n int) {
+ var l int
+ _ = l
+ if m.Parallelism != 0 {
+ n += 1 + sovTypes(uint64(m.Parallelism))
+ }
+ l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.Delay)
+ n += 1 + l + sovTypes(uint64(l))
+ if m.FailureAction != 0 {
+ n += 1 + sovTypes(uint64(m.FailureAction))
+ }
+ if m.Monitor != nil {
+ l = m.Monitor.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.MaxFailureRatio != 0 {
+ n += 5
+ }
+ if m.Order != 0 {
+ n += 1 + sovTypes(uint64(m.Order))
+ }
+ return n
+}
+
+func (m *UpdateStatus) Size() (n int) {
+ var l int
+ _ = l
+ if m.State != 0 {
+ n += 1 + sovTypes(uint64(m.State))
+ }
+ if m.StartedAt != nil {
+ l = m.StartedAt.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.CompletedAt != nil {
+ l = m.CompletedAt.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Message)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *ContainerStatus) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ContainerID)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.PID != 0 {
+ n += 1 + sovTypes(uint64(m.PID))
+ }
+ if m.ExitCode != 0 {
+ n += 1 + sovTypes(uint64(m.ExitCode))
+ }
+ return n
+}
+
+func (m *PortStatus) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Ports) > 0 {
+ for _, e := range m.Ports {
+ l = e.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *TaskStatus) Size() (n int) {
+ var l int
+ _ = l
+ if m.Timestamp != nil {
+ l = m.Timestamp.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.State != 0 {
+ n += 1 + sovTypes(uint64(m.State))
+ }
+ l = len(m.Message)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Err)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.RuntimeStatus != nil {
+ n += m.RuntimeStatus.Size()
+ }
+ if m.PortStatus != nil {
+ l = m.PortStatus.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *TaskStatus_Container) Size() (n int) {
+ var l int
+ _ = l
+ if m.Container != nil {
+ l = m.Container.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+func (m *NetworkAttachmentConfig) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Target)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if len(m.Aliases) > 0 {
+ for _, s := range m.Aliases {
+ l = len(s)
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ if len(m.Addresses) > 0 {
+ for _, s := range m.Addresses {
+ l = len(s)
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ if len(m.DriverAttachmentOpts) > 0 {
+ for k, v := range m.DriverAttachmentOpts {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize))
+ }
+ }
+ return n
+}
+
+func (m *IPAMConfig) Size() (n int) {
+ var l int
+ _ = l
+ if m.Family != 0 {
+ n += 1 + sovTypes(uint64(m.Family))
+ }
+ l = len(m.Subnet)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Range)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Gateway)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if len(m.Reserved) > 0 {
+ for k, v := range m.Reserved {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize))
+ }
+ }
+ return n
+}
+
+func (m *PortConfig) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Name)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Protocol != 0 {
+ n += 1 + sovTypes(uint64(m.Protocol))
+ }
+ if m.TargetPort != 0 {
+ n += 1 + sovTypes(uint64(m.TargetPort))
+ }
+ if m.PublishedPort != 0 {
+ n += 1 + sovTypes(uint64(m.PublishedPort))
+ }
+ if m.PublishMode != 0 {
+ n += 1 + sovTypes(uint64(m.PublishMode))
+ }
+ return n
+}
+
+func (m *Driver) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Name)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if len(m.Options) > 0 {
+ for k, v := range m.Options {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize))
+ }
+ }
+ return n
+}
+
+func (m *IPAMOptions) Size() (n int) {
+ var l int
+ _ = l
+ if m.Driver != nil {
+ l = m.Driver.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if len(m.Configs) > 0 {
+ for _, e := range m.Configs {
+ l = e.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *Peer) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.NodeID)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Addr)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *WeightedPeer) Size() (n int) {
+ var l int
+ _ = l
+ if m.Peer != nil {
+ l = m.Peer.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Weight != 0 {
+ n += 1 + sovTypes(uint64(m.Weight))
+ }
+ return n
+}
+
+func (m *IssuanceStatus) Size() (n int) {
+ var l int
+ _ = l
+ if m.State != 0 {
+ n += 1 + sovTypes(uint64(m.State))
+ }
+ l = len(m.Err)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *AcceptancePolicy) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Policies) > 0 {
+ for _, e := range m.Policies {
+ l = e.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy) Size() (n int) {
+ var l int
+ _ = l
+ if m.Role != 0 {
+ n += 1 + sovTypes(uint64(m.Role))
+ }
+ if m.Autoaccept {
+ n += 2
+ }
+ if m.Secret != nil {
+ l = m.Secret.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *AcceptancePolicy_RoleAdmissionPolicy_Secret) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Data)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Alg)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *ExternalCA) Size() (n int) {
+ var l int
+ _ = l
+ if m.Protocol != 0 {
+ n += 1 + sovTypes(uint64(m.Protocol))
+ }
+ l = len(m.URL)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if len(m.Options) > 0 {
+ for k, v := range m.Options {
+ _ = k
+ _ = v
+ mapEntrySize := 1 + len(k) + sovTypes(uint64(len(k))) + 1 + len(v) + sovTypes(uint64(len(v)))
+ n += mapEntrySize + 1 + sovTypes(uint64(mapEntrySize))
+ }
+ }
+ l = len(m.CACert)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *CAConfig) Size() (n int) {
+ var l int
+ _ = l
+ if m.NodeCertExpiry != nil {
+ l = m.NodeCertExpiry.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if len(m.ExternalCAs) > 0 {
+ for _, e := range m.ExternalCAs {
+ l = e.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ l = len(m.SigningCACert)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.SigningCAKey)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.ForceRotate != 0 {
+ n += 1 + sovTypes(uint64(m.ForceRotate))
+ }
+ return n
+}
+
+func (m *OrchestrationConfig) Size() (n int) {
+ var l int
+ _ = l
+ if m.TaskHistoryRetentionLimit != 0 {
+ n += 1 + sovTypes(uint64(m.TaskHistoryRetentionLimit))
+ }
+ return n
+}
+
+func (m *TaskDefaults) Size() (n int) {
+ var l int
+ _ = l
+ if m.LogDriver != nil {
+ l = m.LogDriver.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *DispatcherConfig) Size() (n int) {
+ var l int
+ _ = l
+ if m.HeartbeatPeriod != nil {
+ l = m.HeartbeatPeriod.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *RaftConfig) Size() (n int) {
+ var l int
+ _ = l
+ if m.SnapshotInterval != 0 {
+ n += 1 + sovTypes(uint64(m.SnapshotInterval))
+ }
+ if m.KeepOldSnapshots != 0 {
+ n += 1 + sovTypes(uint64(m.KeepOldSnapshots))
+ }
+ if m.LogEntriesForSlowFollowers != 0 {
+ n += 1 + sovTypes(uint64(m.LogEntriesForSlowFollowers))
+ }
+ if m.HeartbeatTick != 0 {
+ n += 1 + sovTypes(uint64(m.HeartbeatTick))
+ }
+ if m.ElectionTick != 0 {
+ n += 1 + sovTypes(uint64(m.ElectionTick))
+ }
+ return n
+}
+
+func (m *EncryptionConfig) Size() (n int) {
+ var l int
+ _ = l
+ if m.AutoLockManagers {
+ n += 2
+ }
+ return n
+}
+
+func (m *SpreadOver) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SpreadDescriptor)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *PlacementPreference) Size() (n int) {
+ var l int
+ _ = l
+ if m.Preference != nil {
+ n += m.Preference.Size()
+ }
+ return n
+}
+
+func (m *PlacementPreference_Spread) Size() (n int) {
+ var l int
+ _ = l
+ if m.Spread != nil {
+ l = m.Spread.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+func (m *Placement) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Constraints) > 0 {
+ for _, s := range m.Constraints {
+ l = len(s)
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ if len(m.Preferences) > 0 {
+ for _, e := range m.Preferences {
+ l = e.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ if len(m.Platforms) > 0 {
+ for _, e := range m.Platforms {
+ l = e.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *JoinTokens) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Worker)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Manager)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *RootCA) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.CAKey)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.CACert)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.CACertHash)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = m.JoinTokens.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ if m.RootRotation != nil {
+ l = m.RootRotation.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.LastForcedRotation != 0 {
+ n += 1 + sovTypes(uint64(m.LastForcedRotation))
+ }
+ return n
+}
+
+func (m *Certificate) Size() (n int) {
+ var l int
+ _ = l
+ if m.Role != 0 {
+ n += 1 + sovTypes(uint64(m.Role))
+ }
+ l = len(m.CSR)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = m.Status.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ l = len(m.Certificate)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.CN)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *EncryptionKey) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Subsystem)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Algorithm != 0 {
+ n += 1 + sovTypes(uint64(m.Algorithm))
+ }
+ l = len(m.Key)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.LamportTime != 0 {
+ n += 1 + sovTypes(uint64(m.LamportTime))
+ }
+ return n
+}
+
+func (m *ManagerStatus) Size() (n int) {
+ var l int
+ _ = l
+ if m.RaftID != 0 {
+ n += 1 + sovTypes(uint64(m.RaftID))
+ }
+ l = len(m.Addr)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Leader {
+ n += 2
+ }
+ if m.Reachability != 0 {
+ n += 1 + sovTypes(uint64(m.Reachability))
+ }
+ return n
+}
+
+func (m *FileTarget) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Name)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.UID)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.GID)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Mode != 0 {
+ n += 1 + sovTypes(uint64(m.Mode))
+ }
+ return n
+}
+
+func (m *SecretReference) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.SecretID)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.SecretName)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Target != nil {
+ n += m.Target.Size()
+ }
+ return n
+}
+
+func (m *SecretReference_File) Size() (n int) {
+ var l int
+ _ = l
+ if m.File != nil {
+ l = m.File.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+func (m *ConfigReference) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ConfigID)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.ConfigName)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Target != nil {
+ n += m.Target.Size()
+ }
+ return n
+}
+
+func (m *ConfigReference_File) Size() (n int) {
+ var l int
+ _ = l
+ if m.File != nil {
+ l = m.File.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+func (m *BlacklistedCertificate) Size() (n int) {
+ var l int
+ _ = l
+ if m.Expiry != nil {
+ l = m.Expiry.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *HealthConfig) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Test) > 0 {
+ for _, s := range m.Test {
+ l = len(s)
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ }
+ if m.Interval != nil {
+ l = m.Interval.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Timeout != nil {
+ l = m.Timeout.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.Retries != 0 {
+ n += 1 + sovTypes(uint64(m.Retries))
+ }
+ if m.StartPeriod != nil {
+ l = m.StartPeriod.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *MaybeEncryptedRecord) Size() (n int) {
+ var l int
+ _ = l
+ if m.Algorithm != 0 {
+ n += 1 + sovTypes(uint64(m.Algorithm))
+ }
+ l = len(m.Data)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Nonce)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *RootRotation) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.CACert)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.CAKey)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.CrossSignedCACert)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *Privileges) Size() (n int) {
+ var l int
+ _ = l
+ if m.CredentialSpec != nil {
+ l = m.CredentialSpec.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ if m.SELinuxContext != nil {
+ l = m.SELinuxContext.Size()
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func (m *Privileges_CredentialSpec) Size() (n int) {
+ var l int
+ _ = l
+ if m.Source != nil {
+ n += m.Source.Size()
+ }
+ return n
+}
+
+func (m *Privileges_CredentialSpec_File) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.File)
+ n += 1 + l + sovTypes(uint64(l))
+ return n
+}
+func (m *Privileges_CredentialSpec_Registry) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Registry)
+ n += 1 + l + sovTypes(uint64(l))
+ return n
+}
+func (m *Privileges_SELinuxContext) Size() (n int) {
+ var l int
+ _ = l
+ if m.Disable {
+ n += 2
+ }
+ l = len(m.User)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Role)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Type)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ l = len(m.Level)
+ if l > 0 {
+ n += 1 + l + sovTypes(uint64(l))
+ }
+ return n
+}
+
+func sovTypes(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozTypes(x uint64) (n int) {
+ return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *Version) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Version{`,
+ `Index:` + fmt.Sprintf("%v", this.Index) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *IndexEntry) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&IndexEntry{`,
+ `Key:` + fmt.Sprintf("%v", this.Key) + `,`,
+ `Val:` + fmt.Sprintf("%v", this.Val) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Annotations) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&Annotations{`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `Indices:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Indices), "IndexEntry", "IndexEntry", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GenericString) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GenericString{`,
+ `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GenericDiscrete) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GenericDiscrete{`,
+ `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GenericResource) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GenericResource{`,
+ `Resource:` + fmt.Sprintf("%v", this.Resource) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GenericResource_Str) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GenericResource_Str{`,
+ `Str:` + strings.Replace(fmt.Sprintf("%v", this.Str), "GenericString", "GenericString", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *GenericResource_Discrete) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&GenericResource_Discrete{`,
+ `Discrete:` + strings.Replace(fmt.Sprintf("%v", this.Discrete), "GenericDiscrete", "GenericDiscrete", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Resources) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Resources{`,
+ `NanoCPUs:` + fmt.Sprintf("%v", this.NanoCPUs) + `,`,
+ `MemoryBytes:` + fmt.Sprintf("%v", this.MemoryBytes) + `,`,
+ `Generic:` + strings.Replace(fmt.Sprintf("%v", this.Generic), "GenericResource", "GenericResource", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ResourceRequirements) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ResourceRequirements{`,
+ `Limits:` + strings.Replace(fmt.Sprintf("%v", this.Limits), "Resources", "Resources", 1) + `,`,
+ `Reservations:` + strings.Replace(fmt.Sprintf("%v", this.Reservations), "Resources", "Resources", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Platform) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Platform{`,
+ `Architecture:` + fmt.Sprintf("%v", this.Architecture) + `,`,
+ `OS:` + fmt.Sprintf("%v", this.OS) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *PluginDescription) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PluginDescription{`,
+ `Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *EngineDescription) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&EngineDescription{`,
+ `EngineVersion:` + fmt.Sprintf("%v", this.EngineVersion) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `Plugins:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Plugins), "PluginDescription", "PluginDescription", 1), `&`, ``, 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NodeDescription) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NodeDescription{`,
+ `Hostname:` + fmt.Sprintf("%v", this.Hostname) + `,`,
+ `Platform:` + strings.Replace(fmt.Sprintf("%v", this.Platform), "Platform", "Platform", 1) + `,`,
+ `Resources:` + strings.Replace(fmt.Sprintf("%v", this.Resources), "Resources", "Resources", 1) + `,`,
+ `Engine:` + strings.Replace(fmt.Sprintf("%v", this.Engine), "EngineDescription", "EngineDescription", 1) + `,`,
+ `TLSInfo:` + strings.Replace(fmt.Sprintf("%v", this.TLSInfo), "NodeTLSInfo", "NodeTLSInfo", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NodeTLSInfo) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NodeTLSInfo{`,
+ `TrustRoot:` + fmt.Sprintf("%v", this.TrustRoot) + `,`,
+ `CertIssuerSubject:` + fmt.Sprintf("%v", this.CertIssuerSubject) + `,`,
+ `CertIssuerPublicKey:` + fmt.Sprintf("%v", this.CertIssuerPublicKey) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RaftMemberStatus) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RaftMemberStatus{`,
+ `Leader:` + fmt.Sprintf("%v", this.Leader) + `,`,
+ `Reachability:` + fmt.Sprintf("%v", this.Reachability) + `,`,
+ `Message:` + fmt.Sprintf("%v", this.Message) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NodeStatus) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NodeStatus{`,
+ `State:` + fmt.Sprintf("%v", this.State) + `,`,
+ `Message:` + fmt.Sprintf("%v", this.Message) + `,`,
+ `Addr:` + fmt.Sprintf("%v", this.Addr) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Image) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Image{`,
+ `Reference:` + fmt.Sprintf("%v", this.Reference) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Mount) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Mount{`,
+ `Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+ `Source:` + fmt.Sprintf("%v", this.Source) + `,`,
+ `Target:` + fmt.Sprintf("%v", this.Target) + `,`,
+ `ReadOnly:` + fmt.Sprintf("%v", this.ReadOnly) + `,`,
+ `BindOptions:` + strings.Replace(fmt.Sprintf("%v", this.BindOptions), "Mount_BindOptions", "Mount_BindOptions", 1) + `,`,
+ `VolumeOptions:` + strings.Replace(fmt.Sprintf("%v", this.VolumeOptions), "Mount_VolumeOptions", "Mount_VolumeOptions", 1) + `,`,
+ `TmpfsOptions:` + strings.Replace(fmt.Sprintf("%v", this.TmpfsOptions), "Mount_TmpfsOptions", "Mount_TmpfsOptions", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Mount_BindOptions) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Mount_BindOptions{`,
+ `Propagation:` + fmt.Sprintf("%v", this.Propagation) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Mount_VolumeOptions) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForLabels := make([]string, 0, len(this.Labels))
+ for k, _ := range this.Labels {
+ keysForLabels = append(keysForLabels, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForLabels)
+ mapStringForLabels := "map[string]string{"
+ for _, k := range keysForLabels {
+ mapStringForLabels += fmt.Sprintf("%v: %v,", k, this.Labels[k])
+ }
+ mapStringForLabels += "}"
+ s := strings.Join([]string{`&Mount_VolumeOptions{`,
+ `NoCopy:` + fmt.Sprintf("%v", this.NoCopy) + `,`,
+ `Labels:` + mapStringForLabels + `,`,
+ `DriverConfig:` + strings.Replace(fmt.Sprintf("%v", this.DriverConfig), "Driver", "Driver", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Mount_TmpfsOptions) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Mount_TmpfsOptions{`,
+ `SizeBytes:` + fmt.Sprintf("%v", this.SizeBytes) + `,`,
+ `Mode:` + fmt.Sprintf("%v", this.Mode) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RestartPolicy) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RestartPolicy{`,
+ `Condition:` + fmt.Sprintf("%v", this.Condition) + `,`,
+ `Delay:` + strings.Replace(fmt.Sprintf("%v", this.Delay), "Duration", "google_protobuf1.Duration", 1) + `,`,
+ `MaxAttempts:` + fmt.Sprintf("%v", this.MaxAttempts) + `,`,
+ `Window:` + strings.Replace(fmt.Sprintf("%v", this.Window), "Duration", "google_protobuf1.Duration", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateConfig{`,
+ `Parallelism:` + fmt.Sprintf("%v", this.Parallelism) + `,`,
+ `Delay:` + strings.Replace(strings.Replace(this.Delay.String(), "Duration", "google_protobuf1.Duration", 1), `&`, ``, 1) + `,`,
+ `FailureAction:` + fmt.Sprintf("%v", this.FailureAction) + `,`,
+ `Monitor:` + strings.Replace(fmt.Sprintf("%v", this.Monitor), "Duration", "google_protobuf1.Duration", 1) + `,`,
+ `MaxFailureRatio:` + fmt.Sprintf("%v", this.MaxFailureRatio) + `,`,
+ `Order:` + fmt.Sprintf("%v", this.Order) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UpdateStatus) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UpdateStatus{`,
+ `State:` + fmt.Sprintf("%v", this.State) + `,`,
+ `StartedAt:` + strings.Replace(fmt.Sprintf("%v", this.StartedAt), "Timestamp", "google_protobuf.Timestamp", 1) + `,`,
+ `CompletedAt:` + strings.Replace(fmt.Sprintf("%v", this.CompletedAt), "Timestamp", "google_protobuf.Timestamp", 1) + `,`,
+ `Message:` + fmt.Sprintf("%v", this.Message) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ContainerStatus) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ContainerStatus{`,
+ `ContainerID:` + fmt.Sprintf("%v", this.ContainerID) + `,`,
+ `PID:` + fmt.Sprintf("%v", this.PID) + `,`,
+ `ExitCode:` + fmt.Sprintf("%v", this.ExitCode) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *PortStatus) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PortStatus{`,
+ `Ports:` + strings.Replace(fmt.Sprintf("%v", this.Ports), "PortConfig", "PortConfig", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TaskStatus) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TaskStatus{`,
+ `Timestamp:` + strings.Replace(fmt.Sprintf("%v", this.Timestamp), "Timestamp", "google_protobuf.Timestamp", 1) + `,`,
+ `State:` + fmt.Sprintf("%v", this.State) + `,`,
+ `Message:` + fmt.Sprintf("%v", this.Message) + `,`,
+ `Err:` + fmt.Sprintf("%v", this.Err) + `,`,
+ `RuntimeStatus:` + fmt.Sprintf("%v", this.RuntimeStatus) + `,`,
+ `PortStatus:` + strings.Replace(fmt.Sprintf("%v", this.PortStatus), "PortStatus", "PortStatus", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TaskStatus_Container) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TaskStatus_Container{`,
+ `Container:` + strings.Replace(fmt.Sprintf("%v", this.Container), "ContainerStatus", "ContainerStatus", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NetworkAttachmentConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForDriverAttachmentOpts := make([]string, 0, len(this.DriverAttachmentOpts))
+ for k, _ := range this.DriverAttachmentOpts {
+ keysForDriverAttachmentOpts = append(keysForDriverAttachmentOpts, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForDriverAttachmentOpts)
+ mapStringForDriverAttachmentOpts := "map[string]string{"
+ for _, k := range keysForDriverAttachmentOpts {
+ mapStringForDriverAttachmentOpts += fmt.Sprintf("%v: %v,", k, this.DriverAttachmentOpts[k])
+ }
+ mapStringForDriverAttachmentOpts += "}"
+ s := strings.Join([]string{`&NetworkAttachmentConfig{`,
+ `Target:` + fmt.Sprintf("%v", this.Target) + `,`,
+ `Aliases:` + fmt.Sprintf("%v", this.Aliases) + `,`,
+ `Addresses:` + fmt.Sprintf("%v", this.Addresses) + `,`,
+ `DriverAttachmentOpts:` + mapStringForDriverAttachmentOpts + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *IPAMConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForReserved := make([]string, 0, len(this.Reserved))
+ for k, _ := range this.Reserved {
+ keysForReserved = append(keysForReserved, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForReserved)
+ mapStringForReserved := "map[string]string{"
+ for _, k := range keysForReserved {
+ mapStringForReserved += fmt.Sprintf("%v: %v,", k, this.Reserved[k])
+ }
+ mapStringForReserved += "}"
+ s := strings.Join([]string{`&IPAMConfig{`,
+ `Family:` + fmt.Sprintf("%v", this.Family) + `,`,
+ `Subnet:` + fmt.Sprintf("%v", this.Subnet) + `,`,
+ `Range:` + fmt.Sprintf("%v", this.Range) + `,`,
+ `Gateway:` + fmt.Sprintf("%v", this.Gateway) + `,`,
+ `Reserved:` + mapStringForReserved + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *PortConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PortConfig{`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `Protocol:` + fmt.Sprintf("%v", this.Protocol) + `,`,
+ `TargetPort:` + fmt.Sprintf("%v", this.TargetPort) + `,`,
+ `PublishedPort:` + fmt.Sprintf("%v", this.PublishedPort) + `,`,
+ `PublishMode:` + fmt.Sprintf("%v", this.PublishMode) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Driver) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForOptions := make([]string, 0, len(this.Options))
+ for k, _ := range this.Options {
+ keysForOptions = append(keysForOptions, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForOptions)
+ mapStringForOptions := "map[string]string{"
+ for _, k := range keysForOptions {
+ mapStringForOptions += fmt.Sprintf("%v: %v,", k, this.Options[k])
+ }
+ mapStringForOptions += "}"
+ s := strings.Join([]string{`&Driver{`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `Options:` + mapStringForOptions + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *IPAMOptions) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&IPAMOptions{`,
+ `Driver:` + strings.Replace(fmt.Sprintf("%v", this.Driver), "Driver", "Driver", 1) + `,`,
+ `Configs:` + strings.Replace(fmt.Sprintf("%v", this.Configs), "IPAMConfig", "IPAMConfig", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Peer) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Peer{`,
+ `NodeID:` + fmt.Sprintf("%v", this.NodeID) + `,`,
+ `Addr:` + fmt.Sprintf("%v", this.Addr) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *WeightedPeer) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&WeightedPeer{`,
+ `Peer:` + strings.Replace(fmt.Sprintf("%v", this.Peer), "Peer", "Peer", 1) + `,`,
+ `Weight:` + fmt.Sprintf("%v", this.Weight) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *IssuanceStatus) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&IssuanceStatus{`,
+ `State:` + fmt.Sprintf("%v", this.State) + `,`,
+ `Err:` + fmt.Sprintf("%v", this.Err) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *AcceptancePolicy) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&AcceptancePolicy{`,
+ `Policies:` + strings.Replace(fmt.Sprintf("%v", this.Policies), "AcceptancePolicy_RoleAdmissionPolicy", "AcceptancePolicy_RoleAdmissionPolicy", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *AcceptancePolicy_RoleAdmissionPolicy) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&AcceptancePolicy_RoleAdmissionPolicy{`,
+ `Role:` + fmt.Sprintf("%v", this.Role) + `,`,
+ `Autoaccept:` + fmt.Sprintf("%v", this.Autoaccept) + `,`,
+ `Secret:` + strings.Replace(fmt.Sprintf("%v", this.Secret), "AcceptancePolicy_RoleAdmissionPolicy_Secret", "AcceptancePolicy_RoleAdmissionPolicy_Secret", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *AcceptancePolicy_RoleAdmissionPolicy_Secret) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&AcceptancePolicy_RoleAdmissionPolicy_Secret{`,
+ `Data:` + fmt.Sprintf("%v", this.Data) + `,`,
+ `Alg:` + fmt.Sprintf("%v", this.Alg) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ExternalCA) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForOptions := make([]string, 0, len(this.Options))
+ for k, _ := range this.Options {
+ keysForOptions = append(keysForOptions, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForOptions)
+ mapStringForOptions := "map[string]string{"
+ for _, k := range keysForOptions {
+ mapStringForOptions += fmt.Sprintf("%v: %v,", k, this.Options[k])
+ }
+ mapStringForOptions += "}"
+ s := strings.Join([]string{`&ExternalCA{`,
+ `Protocol:` + fmt.Sprintf("%v", this.Protocol) + `,`,
+ `URL:` + fmt.Sprintf("%v", this.URL) + `,`,
+ `Options:` + mapStringForOptions + `,`,
+ `CACert:` + fmt.Sprintf("%v", this.CACert) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CAConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CAConfig{`,
+ `NodeCertExpiry:` + strings.Replace(fmt.Sprintf("%v", this.NodeCertExpiry), "Duration", "google_protobuf1.Duration", 1) + `,`,
+ `ExternalCAs:` + strings.Replace(fmt.Sprintf("%v", this.ExternalCAs), "ExternalCA", "ExternalCA", 1) + `,`,
+ `SigningCACert:` + fmt.Sprintf("%v", this.SigningCACert) + `,`,
+ `SigningCAKey:` + fmt.Sprintf("%v", this.SigningCAKey) + `,`,
+ `ForceRotate:` + fmt.Sprintf("%v", this.ForceRotate) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *OrchestrationConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&OrchestrationConfig{`,
+ `TaskHistoryRetentionLimit:` + fmt.Sprintf("%v", this.TaskHistoryRetentionLimit) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TaskDefaults) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TaskDefaults{`,
+ `LogDriver:` + strings.Replace(fmt.Sprintf("%v", this.LogDriver), "Driver", "Driver", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *DispatcherConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&DispatcherConfig{`,
+ `HeartbeatPeriod:` + strings.Replace(fmt.Sprintf("%v", this.HeartbeatPeriod), "Duration", "google_protobuf1.Duration", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RaftConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RaftConfig{`,
+ `SnapshotInterval:` + fmt.Sprintf("%v", this.SnapshotInterval) + `,`,
+ `KeepOldSnapshots:` + fmt.Sprintf("%v", this.KeepOldSnapshots) + `,`,
+ `LogEntriesForSlowFollowers:` + fmt.Sprintf("%v", this.LogEntriesForSlowFollowers) + `,`,
+ `HeartbeatTick:` + fmt.Sprintf("%v", this.HeartbeatTick) + `,`,
+ `ElectionTick:` + fmt.Sprintf("%v", this.ElectionTick) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *EncryptionConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&EncryptionConfig{`,
+ `AutoLockManagers:` + fmt.Sprintf("%v", this.AutoLockManagers) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SpreadOver) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SpreadOver{`,
+ `SpreadDescriptor:` + fmt.Sprintf("%v", this.SpreadDescriptor) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *PlacementPreference) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PlacementPreference{`,
+ `Preference:` + fmt.Sprintf("%v", this.Preference) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *PlacementPreference_Spread) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PlacementPreference_Spread{`,
+ `Spread:` + strings.Replace(fmt.Sprintf("%v", this.Spread), "SpreadOver", "SpreadOver", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Placement) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Placement{`,
+ `Constraints:` + fmt.Sprintf("%v", this.Constraints) + `,`,
+ `Preferences:` + strings.Replace(fmt.Sprintf("%v", this.Preferences), "PlacementPreference", "PlacementPreference", 1) + `,`,
+ `Platforms:` + strings.Replace(fmt.Sprintf("%v", this.Platforms), "Platform", "Platform", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *JoinTokens) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&JoinTokens{`,
+ `Worker:` + fmt.Sprintf("%v", this.Worker) + `,`,
+ `Manager:` + fmt.Sprintf("%v", this.Manager) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RootCA) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RootCA{`,
+ `CAKey:` + fmt.Sprintf("%v", this.CAKey) + `,`,
+ `CACert:` + fmt.Sprintf("%v", this.CACert) + `,`,
+ `CACertHash:` + fmt.Sprintf("%v", this.CACertHash) + `,`,
+ `JoinTokens:` + strings.Replace(strings.Replace(this.JoinTokens.String(), "JoinTokens", "JoinTokens", 1), `&`, ``, 1) + `,`,
+ `RootRotation:` + strings.Replace(fmt.Sprintf("%v", this.RootRotation), "RootRotation", "RootRotation", 1) + `,`,
+ `LastForcedRotation:` + fmt.Sprintf("%v", this.LastForcedRotation) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Certificate) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Certificate{`,
+ `Role:` + fmt.Sprintf("%v", this.Role) + `,`,
+ `CSR:` + fmt.Sprintf("%v", this.CSR) + `,`,
+ `Status:` + strings.Replace(strings.Replace(this.Status.String(), "IssuanceStatus", "IssuanceStatus", 1), `&`, ``, 1) + `,`,
+ `Certificate:` + fmt.Sprintf("%v", this.Certificate) + `,`,
+ `CN:` + fmt.Sprintf("%v", this.CN) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *EncryptionKey) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&EncryptionKey{`,
+ `Subsystem:` + fmt.Sprintf("%v", this.Subsystem) + `,`,
+ `Algorithm:` + fmt.Sprintf("%v", this.Algorithm) + `,`,
+ `Key:` + fmt.Sprintf("%v", this.Key) + `,`,
+ `LamportTime:` + fmt.Sprintf("%v", this.LamportTime) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ManagerStatus) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ManagerStatus{`,
+ `RaftID:` + fmt.Sprintf("%v", this.RaftID) + `,`,
+ `Addr:` + fmt.Sprintf("%v", this.Addr) + `,`,
+ `Leader:` + fmt.Sprintf("%v", this.Leader) + `,`,
+ `Reachability:` + fmt.Sprintf("%v", this.Reachability) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *FileTarget) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&FileTarget{`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `UID:` + fmt.Sprintf("%v", this.UID) + `,`,
+ `GID:` + fmt.Sprintf("%v", this.GID) + `,`,
+ `Mode:` + fmt.Sprintf("%v", this.Mode) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SecretReference) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SecretReference{`,
+ `SecretID:` + fmt.Sprintf("%v", this.SecretID) + `,`,
+ `SecretName:` + fmt.Sprintf("%v", this.SecretName) + `,`,
+ `Target:` + fmt.Sprintf("%v", this.Target) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SecretReference_File) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SecretReference_File{`,
+ `File:` + strings.Replace(fmt.Sprintf("%v", this.File), "FileTarget", "FileTarget", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ConfigReference) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ConfigReference{`,
+ `ConfigID:` + fmt.Sprintf("%v", this.ConfigID) + `,`,
+ `ConfigName:` + fmt.Sprintf("%v", this.ConfigName) + `,`,
+ `Target:` + fmt.Sprintf("%v", this.Target) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ConfigReference_File) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ConfigReference_File{`,
+ `File:` + strings.Replace(fmt.Sprintf("%v", this.File), "FileTarget", "FileTarget", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *BlacklistedCertificate) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&BlacklistedCertificate{`,
+ `Expiry:` + strings.Replace(fmt.Sprintf("%v", this.Expiry), "Timestamp", "google_protobuf.Timestamp", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *HealthConfig) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&HealthConfig{`,
+ `Test:` + fmt.Sprintf("%v", this.Test) + `,`,
+ `Interval:` + strings.Replace(fmt.Sprintf("%v", this.Interval), "Duration", "google_protobuf1.Duration", 1) + `,`,
+ `Timeout:` + strings.Replace(fmt.Sprintf("%v", this.Timeout), "Duration", "google_protobuf1.Duration", 1) + `,`,
+ `Retries:` + fmt.Sprintf("%v", this.Retries) + `,`,
+ `StartPeriod:` + strings.Replace(fmt.Sprintf("%v", this.StartPeriod), "Duration", "google_protobuf1.Duration", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *MaybeEncryptedRecord) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&MaybeEncryptedRecord{`,
+ `Algorithm:` + fmt.Sprintf("%v", this.Algorithm) + `,`,
+ `Data:` + fmt.Sprintf("%v", this.Data) + `,`,
+ `Nonce:` + fmt.Sprintf("%v", this.Nonce) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RootRotation) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RootRotation{`,
+ `CACert:` + fmt.Sprintf("%v", this.CACert) + `,`,
+ `CAKey:` + fmt.Sprintf("%v", this.CAKey) + `,`,
+ `CrossSignedCACert:` + fmt.Sprintf("%v", this.CrossSignedCACert) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Privileges) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Privileges{`,
+ `CredentialSpec:` + strings.Replace(fmt.Sprintf("%v", this.CredentialSpec), "Privileges_CredentialSpec", "Privileges_CredentialSpec", 1) + `,`,
+ `SELinuxContext:` + strings.Replace(fmt.Sprintf("%v", this.SELinuxContext), "Privileges_SELinuxContext", "Privileges_SELinuxContext", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Privileges_CredentialSpec) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Privileges_CredentialSpec{`,
+ `Source:` + fmt.Sprintf("%v", this.Source) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Privileges_CredentialSpec_File) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Privileges_CredentialSpec_File{`,
+ `File:` + fmt.Sprintf("%v", this.File) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Privileges_CredentialSpec_Registry) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Privileges_CredentialSpec_Registry{`,
+ `Registry:` + fmt.Sprintf("%v", this.Registry) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Privileges_SELinuxContext) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Privileges_SELinuxContext{`,
+ `Disable:` + fmt.Sprintf("%v", this.Disable) + `,`,
+ `User:` + fmt.Sprintf("%v", this.User) + `,`,
+ `Role:` + fmt.Sprintf("%v", this.Role) + `,`,
+ `Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+ `Level:` + fmt.Sprintf("%v", this.Level) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringTypes(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *Version) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Version: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Version: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
+ }
+ m.Index = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Index |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *IndexEntry) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: IndexEntry: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: IndexEntry: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Key = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Val", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Val = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Annotations) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Annotations: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Annotations: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Name = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Indices", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Indices = append(m.Indices, IndexEntry{})
+ if err := m.Indices[len(m.Indices)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GenericString) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GenericString: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GenericString: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Kind = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Value = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GenericDiscrete) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GenericDiscrete: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GenericDiscrete: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Kind = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ m.Value = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Value |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *GenericResource) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: GenericResource: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: GenericResource: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Str", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &GenericString{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Resource = &GenericResource_Str{v}
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Discrete", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &GenericDiscrete{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Resource = &GenericResource_Discrete{v}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Resources) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Resources: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Resources: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NanoCPUs", wireType)
+ }
+ m.NanoCPUs = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.NanoCPUs |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field MemoryBytes", wireType)
+ }
+ m.MemoryBytes = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.MemoryBytes |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Generic", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Generic = append(m.Generic, &GenericResource{})
+ if err := m.Generic[len(m.Generic)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ResourceRequirements) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ResourceRequirements: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ResourceRequirements: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Limits", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Limits == nil {
+ m.Limits = &Resources{}
+ }
+ if err := m.Limits.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Reservations", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Reservations == nil {
+ m.Reservations = &Resources{}
+ }
+ if err := m.Reservations.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Platform) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Platform: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Platform: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Architecture", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Architecture = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field OS", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.OS = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *PluginDescription) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PluginDescription: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PluginDescription: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Type = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Name = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *EngineDescription) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: EngineDescription: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: EngineDescription: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field EngineVersion", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.EngineVersion = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Plugins", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Plugins = append(m.Plugins, PluginDescription{})
+ if err := m.Plugins[len(m.Plugins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NodeDescription) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NodeDescription: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NodeDescription: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Hostname", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Hostname = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Platform", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Platform == nil {
+ m.Platform = &Platform{}
+ }
+ if err := m.Platform.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Resources", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Resources == nil {
+ m.Resources = &Resources{}
+ }
+ if err := m.Resources.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Engine", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Engine == nil {
+ m.Engine = &EngineDescription{}
+ }
+ if err := m.Engine.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TLSInfo", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.TLSInfo == nil {
+ m.TLSInfo = &NodeTLSInfo{}
+ }
+ if err := m.TLSInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NodeTLSInfo) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NodeTLSInfo: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NodeTLSInfo: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TrustRoot", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TrustRoot = append(m.TrustRoot[:0], dAtA[iNdEx:postIndex]...)
+ if m.TrustRoot == nil {
+ m.TrustRoot = []byte{}
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CertIssuerSubject", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CertIssuerSubject = append(m.CertIssuerSubject[:0], dAtA[iNdEx:postIndex]...)
+ if m.CertIssuerSubject == nil {
+ m.CertIssuerSubject = []byte{}
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CertIssuerPublicKey", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CertIssuerPublicKey = append(m.CertIssuerPublicKey[:0], dAtA[iNdEx:postIndex]...)
+ if m.CertIssuerPublicKey == nil {
+ m.CertIssuerPublicKey = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RaftMemberStatus) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RaftMemberStatus: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RaftMemberStatus: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Leader", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Leader = bool(v != 0)
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Reachability", wireType)
+ }
+ m.Reachability = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Reachability |= (RaftMemberStatus_Reachability(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Message = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NodeStatus) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NodeStatus: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NodeStatus: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field State", wireType)
+ }
+ m.State = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.State |= (NodeStatus_State(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Message = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Addr", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Addr = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Image) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Image: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Image: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Reference", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Reference = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Mount) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Mount: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Mount: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Type |= (Mount_MountType(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Source = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Target", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Target = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ReadOnly", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.ReadOnly = bool(v != 0)
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field BindOptions", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.BindOptions == nil {
+ m.BindOptions = &Mount_BindOptions{}
+ }
+ if err := m.BindOptions.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field VolumeOptions", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.VolumeOptions == nil {
+ m.VolumeOptions = &Mount_VolumeOptions{}
+ }
+ if err := m.VolumeOptions.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TmpfsOptions", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.TmpfsOptions == nil {
+ m.TmpfsOptions = &Mount_TmpfsOptions{}
+ }
+ if err := m.TmpfsOptions.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Mount_BindOptions) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: BindOptions: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: BindOptions: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Propagation", wireType)
+ }
+ m.Propagation = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Propagation |= (Mount_BindOptions_MountPropagation(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Mount_VolumeOptions) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: VolumeOptions: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: VolumeOptions: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NoCopy", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.NoCopy = bool(v != 0)
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Labels", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Labels == nil {
+ m.Labels = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Labels[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Labels[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field DriverConfig", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.DriverConfig == nil {
+ m.DriverConfig = &Driver{}
+ }
+ if err := m.DriverConfig.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Mount_TmpfsOptions) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: TmpfsOptions: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: TmpfsOptions: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SizeBytes", wireType)
+ }
+ m.SizeBytes = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.SizeBytes |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Mode", wireType)
+ }
+ m.Mode = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Mode |= (os.FileMode(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RestartPolicy) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RestartPolicy: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RestartPolicy: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Condition", wireType)
+ }
+ m.Condition = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Condition |= (RestartPolicy_RestartCondition(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Delay", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Delay == nil {
+ m.Delay = &google_protobuf1.Duration{}
+ }
+ if err := m.Delay.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field MaxAttempts", wireType)
+ }
+ m.MaxAttempts = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.MaxAttempts |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Window", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Window == nil {
+ m.Window = &google_protobuf1.Duration{}
+ }
+ if err := m.Window.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Parallelism", wireType)
+ }
+ m.Parallelism = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Parallelism |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Delay", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := github_com_gogo_protobuf_types.StdDurationUnmarshal(&m.Delay, dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field FailureAction", wireType)
+ }
+ m.FailureAction = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.FailureAction |= (UpdateConfig_FailureAction(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Monitor", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Monitor == nil {
+ m.Monitor = &google_protobuf1.Duration{}
+ }
+ if err := m.Monitor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 5 {
+ return fmt.Errorf("proto: wrong wireType = %d for field MaxFailureRatio", wireType)
+ }
+ var v uint32
+ if (iNdEx + 4) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += 4
+ v = uint32(dAtA[iNdEx-4])
+ v |= uint32(dAtA[iNdEx-3]) << 8
+ v |= uint32(dAtA[iNdEx-2]) << 16
+ v |= uint32(dAtA[iNdEx-1]) << 24
+ m.MaxFailureRatio = float32(math.Float32frombits(v))
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Order", wireType)
+ }
+ m.Order = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Order |= (UpdateConfig_UpdateOrder(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UpdateStatus) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UpdateStatus: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UpdateStatus: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field State", wireType)
+ }
+ m.State = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.State |= (UpdateStatus_UpdateState(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field StartedAt", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.StartedAt == nil {
+ m.StartedAt = &google_protobuf.Timestamp{}
+ }
+ if err := m.StartedAt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CompletedAt", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.CompletedAt == nil {
+ m.CompletedAt = &google_protobuf.Timestamp{}
+ }
+ if err := m.CompletedAt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Message = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ContainerStatus) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ContainerStatus: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ContainerStatus: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ContainerID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ContainerID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PID", wireType)
+ }
+ m.PID = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.PID |= (int32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ExitCode", wireType)
+ }
+ m.ExitCode = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ExitCode |= (int32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *PortStatus) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PortStatus: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PortStatus: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Ports", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Ports = append(m.Ports, &PortConfig{})
+ if err := m.Ports[len(m.Ports)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *TaskStatus) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: TaskStatus: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: TaskStatus: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Timestamp == nil {
+ m.Timestamp = &google_protobuf.Timestamp{}
+ }
+ if err := m.Timestamp.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field State", wireType)
+ }
+ m.State = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.State |= (TaskState(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Message = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Err", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Err = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Container", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &ContainerStatus{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.RuntimeStatus = &TaskStatus_Container{v}
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PortStatus", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.PortStatus == nil {
+ m.PortStatus = &PortStatus{}
+ }
+ if err := m.PortStatus.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NetworkAttachmentConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NetworkAttachmentConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NetworkAttachmentConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Target", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Target = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Aliases", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Aliases = append(m.Aliases, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Addresses", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Addresses = append(m.Addresses, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field DriverAttachmentOpts", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.DriverAttachmentOpts == nil {
+ m.DriverAttachmentOpts = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.DriverAttachmentOpts[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.DriverAttachmentOpts[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *IPAMConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: IPAMConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: IPAMConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Family", wireType)
+ }
+ m.Family = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Family |= (IPAMConfig_AddressFamily(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Subnet", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Subnet = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Range", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Range = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Gateway", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Gateway = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Reserved", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Reserved == nil {
+ m.Reserved = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Reserved[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Reserved[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *PortConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PortConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PortConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Name = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Protocol", wireType)
+ }
+ m.Protocol = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Protocol |= (PortConfig_Protocol(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TargetPort", wireType)
+ }
+ m.TargetPort = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TargetPort |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PublishedPort", wireType)
+ }
+ m.PublishedPort = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.PublishedPort |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PublishMode", wireType)
+ }
+ m.PublishMode = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.PublishMode |= (PortConfig_PublishMode(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Driver) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Driver: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Driver: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Name = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Options == nil {
+ m.Options = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Options[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Options[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *IPAMOptions) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: IPAMOptions: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: IPAMOptions: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Driver", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Driver == nil {
+ m.Driver = &Driver{}
+ }
+ if err := m.Driver.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Configs", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Configs = append(m.Configs, &IPAMConfig{})
+ if err := m.Configs[len(m.Configs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Peer) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Peer: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Peer: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.NodeID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Addr", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Addr = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *WeightedPeer) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: WeightedPeer: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: WeightedPeer: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Peer", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Peer == nil {
+ m.Peer = &Peer{}
+ }
+ if err := m.Peer.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Weight", wireType)
+ }
+ m.Weight = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Weight |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *IssuanceStatus) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: IssuanceStatus: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: IssuanceStatus: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field State", wireType)
+ }
+ m.State = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.State |= (IssuanceStatus_State(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Err", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Err = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *AcceptancePolicy) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: AcceptancePolicy: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: AcceptancePolicy: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Policies", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Policies = append(m.Policies, &AcceptancePolicy_RoleAdmissionPolicy{})
+ if err := m.Policies[len(m.Policies)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *AcceptancePolicy_RoleAdmissionPolicy) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RoleAdmissionPolicy: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RoleAdmissionPolicy: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Role", wireType)
+ }
+ m.Role = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Role |= (NodeRole(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Autoaccept", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Autoaccept = bool(v != 0)
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Secret", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Secret == nil {
+ m.Secret = &AcceptancePolicy_RoleAdmissionPolicy_Secret{}
+ }
+ if err := m.Secret.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *AcceptancePolicy_RoleAdmissionPolicy_Secret) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Secret: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Secret: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Alg", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Alg = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ExternalCA) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ExternalCA: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ExternalCA: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Protocol", wireType)
+ }
+ m.Protocol = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Protocol |= (ExternalCA_CAProtocol(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field URL", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.URL = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Options == nil {
+ m.Options = make(map[string]string)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapvalue uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapvalue |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapvalue := int(stringLenmapvalue)
+ if intStringLenmapvalue < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postStringIndexmapvalue := iNdEx + intStringLenmapvalue
+ if postStringIndexmapvalue > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := string(dAtA[iNdEx:postStringIndexmapvalue])
+ iNdEx = postStringIndexmapvalue
+ m.Options[mapkey] = mapvalue
+ } else {
+ var mapvalue string
+ m.Options[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CACert", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CACert = append(m.CACert[:0], dAtA[iNdEx:postIndex]...)
+ if m.CACert == nil {
+ m.CACert = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CAConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CAConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CAConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeCertExpiry", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.NodeCertExpiry == nil {
+ m.NodeCertExpiry = &google_protobuf1.Duration{}
+ }
+ if err := m.NodeCertExpiry.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ExternalCAs", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ExternalCAs = append(m.ExternalCAs, &ExternalCA{})
+ if err := m.ExternalCAs[len(m.ExternalCAs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SigningCACert", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SigningCACert = append(m.SigningCACert[:0], dAtA[iNdEx:postIndex]...)
+ if m.SigningCACert == nil {
+ m.SigningCACert = []byte{}
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SigningCAKey", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SigningCAKey = append(m.SigningCAKey[:0], dAtA[iNdEx:postIndex]...)
+ if m.SigningCAKey == nil {
+ m.SigningCAKey = []byte{}
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ForceRotate", wireType)
+ }
+ m.ForceRotate = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ForceRotate |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *OrchestrationConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: OrchestrationConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: OrchestrationConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TaskHistoryRetentionLimit", wireType)
+ }
+ m.TaskHistoryRetentionLimit = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TaskHistoryRetentionLimit |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *TaskDefaults) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: TaskDefaults: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: TaskDefaults: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LogDriver", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.LogDriver == nil {
+ m.LogDriver = &Driver{}
+ }
+ if err := m.LogDriver.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *DispatcherConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: DispatcherConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: DispatcherConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field HeartbeatPeriod", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.HeartbeatPeriod == nil {
+ m.HeartbeatPeriod = &google_protobuf1.Duration{}
+ }
+ if err := m.HeartbeatPeriod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RaftConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RaftConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RaftConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SnapshotInterval", wireType)
+ }
+ m.SnapshotInterval = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.SnapshotInterval |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field KeepOldSnapshots", wireType)
+ }
+ m.KeepOldSnapshots = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.KeepOldSnapshots |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LogEntriesForSlowFollowers", wireType)
+ }
+ m.LogEntriesForSlowFollowers = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.LogEntriesForSlowFollowers |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field HeartbeatTick", wireType)
+ }
+ m.HeartbeatTick = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.HeartbeatTick |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ElectionTick", wireType)
+ }
+ m.ElectionTick = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ElectionTick |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *EncryptionConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: EncryptionConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: EncryptionConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field AutoLockManagers", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.AutoLockManagers = bool(v != 0)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SpreadOver) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SpreadOver: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SpreadOver: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SpreadDescriptor", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SpreadDescriptor = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *PlacementPreference) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PlacementPreference: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PlacementPreference: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Spread", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &SpreadOver{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Preference = &PlacementPreference_Spread{v}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Placement) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Placement: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Placement: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Constraints", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Constraints = append(m.Constraints, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Preferences", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Preferences = append(m.Preferences, &PlacementPreference{})
+ if err := m.Preferences[len(m.Preferences)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Platforms", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Platforms = append(m.Platforms, &Platform{})
+ if err := m.Platforms[len(m.Platforms)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *JoinTokens) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: JoinTokens: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: JoinTokens: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Worker", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Worker = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Manager", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Manager = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RootCA) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RootCA: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RootCA: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CAKey", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CAKey = append(m.CAKey[:0], dAtA[iNdEx:postIndex]...)
+ if m.CAKey == nil {
+ m.CAKey = []byte{}
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CACert", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CACert = append(m.CACert[:0], dAtA[iNdEx:postIndex]...)
+ if m.CACert == nil {
+ m.CACert = []byte{}
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CACertHash", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CACertHash = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field JoinTokens", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.JoinTokens.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RootRotation", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.RootRotation == nil {
+ m.RootRotation = &RootRotation{}
+ }
+ if err := m.RootRotation.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LastForcedRotation", wireType)
+ }
+ m.LastForcedRotation = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.LastForcedRotation |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Certificate) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Certificate: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Certificate: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Role", wireType)
+ }
+ m.Role = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Role |= (NodeRole(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CSR", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CSR = append(m.CSR[:0], dAtA[iNdEx:postIndex]...)
+ if m.CSR == nil {
+ m.CSR = []byte{}
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if err := m.Status.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Certificate", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Certificate = append(m.Certificate[:0], dAtA[iNdEx:postIndex]...)
+ if m.Certificate == nil {
+ m.Certificate = []byte{}
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CN", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CN = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *EncryptionKey) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: EncryptionKey: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: EncryptionKey: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Subsystem", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Subsystem = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Algorithm", wireType)
+ }
+ m.Algorithm = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Algorithm |= (EncryptionKey_Algorithm(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...)
+ if m.Key == nil {
+ m.Key = []byte{}
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field LamportTime", wireType)
+ }
+ m.LamportTime = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.LamportTime |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ManagerStatus) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ManagerStatus: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ManagerStatus: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RaftID", wireType)
+ }
+ m.RaftID = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RaftID |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Addr", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Addr = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Leader", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Leader = bool(v != 0)
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Reachability", wireType)
+ }
+ m.Reachability = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Reachability |= (RaftMemberStatus_Reachability(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *FileTarget) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: FileTarget: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: FileTarget: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Name = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.UID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field GID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.GID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Mode", wireType)
+ }
+ m.Mode = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Mode |= (os.FileMode(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SecretReference) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SecretReference: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SecretReference: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SecretID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SecretID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SecretName", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SecretName = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field File", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &FileTarget{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &SecretReference_File{v}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ConfigReference) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ConfigReference: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ConfigReference: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ConfigID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ConfigID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ConfigName", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ConfigName = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field File", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &FileTarget{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Target = &ConfigReference_File{v}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *BlacklistedCertificate) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: BlacklistedCertificate: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: BlacklistedCertificate: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Expiry", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Expiry == nil {
+ m.Expiry = &google_protobuf.Timestamp{}
+ }
+ if err := m.Expiry.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *HealthConfig) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: HealthConfig: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: HealthConfig: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Test", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Test = append(m.Test, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Interval", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Interval == nil {
+ m.Interval = &google_protobuf1.Duration{}
+ }
+ if err := m.Interval.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Timeout", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Timeout == nil {
+ m.Timeout = &google_protobuf1.Duration{}
+ }
+ if err := m.Timeout.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Retries", wireType)
+ }
+ m.Retries = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Retries |= (int32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field StartPeriod", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.StartPeriod == nil {
+ m.StartPeriod = &google_protobuf1.Duration{}
+ }
+ if err := m.StartPeriod.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *MaybeEncryptedRecord) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: MaybeEncryptedRecord: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: MaybeEncryptedRecord: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Algorithm", wireType)
+ }
+ m.Algorithm = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Algorithm |= (MaybeEncryptedRecord_Algorithm(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Nonce", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Nonce = append(m.Nonce[:0], dAtA[iNdEx:postIndex]...)
+ if m.Nonce == nil {
+ m.Nonce = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RootRotation) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RootRotation: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RootRotation: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CACert", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CACert = append(m.CACert[:0], dAtA[iNdEx:postIndex]...)
+ if m.CACert == nil {
+ m.CACert = []byte{}
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CAKey", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CAKey = append(m.CAKey[:0], dAtA[iNdEx:postIndex]...)
+ if m.CAKey == nil {
+ m.CAKey = []byte{}
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CrossSignedCACert", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.CrossSignedCACert = append(m.CrossSignedCACert[:0], dAtA[iNdEx:postIndex]...)
+ if m.CrossSignedCACert == nil {
+ m.CrossSignedCACert = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Privileges) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Privileges: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Privileges: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CredentialSpec", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.CredentialSpec == nil {
+ m.CredentialSpec = &Privileges_CredentialSpec{}
+ }
+ if err := m.CredentialSpec.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SELinuxContext", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.SELinuxContext == nil {
+ m.SELinuxContext = &Privileges_SELinuxContext{}
+ }
+ if err := m.SELinuxContext.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Privileges_CredentialSpec) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CredentialSpec: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CredentialSpec: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field File", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Source = &Privileges_CredentialSpec_File{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Registry", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Source = &Privileges_CredentialSpec_Registry{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Privileges_SELinuxContext) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SELinuxContext: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SELinuxContext: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Disable", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Disable = bool(v != 0)
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field User", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.User = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Role", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Role = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Type = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Level", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthTypes
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Level = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTypes(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTypes
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipTypes(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthTypes
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowTypes
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipTypes(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("types.proto", fileDescriptorTypes) }
+
+var fileDescriptorTypes = []byte{
+ // 4808 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x7a, 0x4d, 0x6c, 0x24, 0x49,
+ 0x56, 0xbf, 0xeb, 0xd3, 0x55, 0xaf, 0xca, 0x76, 0x76, 0xb4, 0xb7, 0xd7, 0x5d, 0xd3, 0x63, 0xd7,
+ 0xe4, 0x4c, 0xef, 0x7c, 0xec, 0xfc, 0x6b, 0xba, 0xdd, 0x33, 0xa3, 0xee, 0xe9, 0xff, 0x7c, 0xd4,
+ 0x97, 0xdb, 0xb5, 0x6d, 0x57, 0x95, 0xa2, 0xca, 0xdd, 0x3b, 0x07, 0x48, 0xa5, 0x33, 0xc3, 0xe5,
+ 0x1c, 0x67, 0x65, 0x14, 0x99, 0x59, 0x76, 0x17, 0x0b, 0xa2, 0xc5, 0x01, 0x90, 0x4f, 0x70, 0x62,
+ 0x25, 0x64, 0x2e, 0x70, 0x42, 0x48, 0x1c, 0x40, 0x42, 0x70, 0x61, 0x90, 0x38, 0xcc, 0x8d, 0x05,
+ 0x24, 0xb4, 0x02, 0xc9, 0x30, 0x3e, 0x70, 0x43, 0x70, 0x59, 0x71, 0x01, 0x09, 0xc5, 0x47, 0x66,
+ 0x65, 0xb9, 0xd3, 0x76, 0x0f, 0xb3, 0x17, 0x3b, 0xe3, 0xbd, 0xdf, 0x7b, 0xf1, 0xe2, 0x45, 0xc4,
+ 0x8b, 0xf7, 0x22, 0x0a, 0x0a, 0xfe, 0x64, 0x44, 0xbc, 0xca, 0xc8, 0xa5, 0x3e, 0x45, 0xc8, 0xa4,
+ 0xc6, 0x01, 0x71, 0x2b, 0xde, 0x91, 0xee, 0x0e, 0x0f, 0x2c, 0xbf, 0x72, 0x78, 0xb7, 0xb4, 0x36,
+ 0xa0, 0x74, 0x60, 0x93, 0xf7, 0x38, 0x62, 0x77, 0xbc, 0xf7, 0x9e, 0x6f, 0x0d, 0x89, 0xe7, 0xeb,
+ 0xc3, 0x91, 0x10, 0x2a, 0xad, 0x9e, 0x07, 0x98, 0x63, 0x57, 0xf7, 0x2d, 0xea, 0x48, 0xfe, 0xf2,
+ 0x80, 0x0e, 0x28, 0xff, 0x7c, 0x8f, 0x7d, 0x09, 0xaa, 0xba, 0x06, 0xf3, 0x4f, 0x88, 0xeb, 0x59,
+ 0xd4, 0x41, 0xcb, 0x90, 0xb1, 0x1c, 0x93, 0x3c, 0x5b, 0x49, 0x94, 0x13, 0x6f, 0xa5, 0xb1, 0x68,
+ 0xa8, 0x77, 0x00, 0x5a, 0xec, 0xa3, 0xe9, 0xf8, 0xee, 0x04, 0x29, 0x90, 0x3a, 0x20, 0x13, 0x8e,
+ 0xc8, 0x63, 0xf6, 0xc9, 0x28, 0x87, 0xba, 0xbd, 0x92, 0x14, 0x94, 0x43, 0xdd, 0x56, 0xbf, 0x4e,
+ 0x40, 0xa1, 0xea, 0x38, 0xd4, 0xe7, 0xbd, 0x7b, 0x08, 0x41, 0xda, 0xd1, 0x87, 0x44, 0x0a, 0xf1,
+ 0x6f, 0x54, 0x87, 0xac, 0xad, 0xef, 0x12, 0xdb, 0x5b, 0x49, 0x96, 0x53, 0x6f, 0x15, 0xd6, 0xbf,
+ 0x5f, 0x79, 0x71, 0xc8, 0x95, 0x88, 0x92, 0xca, 0x16, 0x47, 0x73, 0x23, 0xb0, 0x14, 0x45, 0x9f,
+ 0xc0, 0xbc, 0xe5, 0x98, 0x96, 0x41, 0xbc, 0x95, 0x34, 0xd7, 0xb2, 0x1a, 0xa7, 0x65, 0x6a, 0x7d,
+ 0x2d, 0xfd, 0xd5, 0xe9, 0xda, 0x1c, 0x0e, 0x84, 0x4a, 0x0f, 0xa0, 0x10, 0x51, 0x1b, 0x33, 0xb6,
+ 0x65, 0xc8, 0x1c, 0xea, 0xf6, 0x98, 0xc8, 0xd1, 0x89, 0xc6, 0x47, 0xc9, 0xfb, 0x09, 0xf5, 0x01,
+ 0x2c, 0x3c, 0x22, 0x0e, 0x71, 0x2d, 0xa3, 0xe7, 0xbb, 0x96, 0x33, 0x60, 0x83, 0x3c, 0xb0, 0x1c,
+ 0x33, 0x18, 0x24, 0xfb, 0x8e, 0x17, 0x57, 0x1f, 0xc2, 0x92, 0x14, 0x6d, 0x58, 0x9e, 0xe1, 0x12,
+ 0x9f, 0x5c, 0x2d, 0x9c, 0x0a, 0x84, 0x7f, 0x37, 0x11, 0x4a, 0x63, 0xe2, 0xd1, 0xb1, 0x6b, 0x10,
+ 0xf4, 0x01, 0xa4, 0x3c, 0xdf, 0xe5, 0xc2, 0x85, 0xf5, 0xd7, 0xe2, 0x5c, 0x30, 0x63, 0xea, 0xe6,
+ 0x1c, 0x66, 0x78, 0x54, 0x85, 0x9c, 0x29, 0x0d, 0xe0, 0x7d, 0x14, 0xd6, 0x5f, 0xbf, 0x44, 0x36,
+ 0xb0, 0x75, 0x73, 0x0e, 0x87, 0x62, 0x35, 0x80, 0x9c, 0x2b, 0xad, 0x50, 0x7f, 0x9c, 0x80, 0x7c,
+ 0x60, 0x92, 0x87, 0xde, 0x86, 0xbc, 0xa3, 0x3b, 0x54, 0x33, 0x46, 0x63, 0x8f, 0x5b, 0x96, 0xaa,
+ 0x15, 0xcf, 0x4e, 0xd7, 0x72, 0x6d, 0xdd, 0xa1, 0xf5, 0xee, 0x8e, 0x87, 0x73, 0x8c, 0x5d, 0x1f,
+ 0x8d, 0x3d, 0xf4, 0x1a, 0x14, 0x87, 0x64, 0x48, 0xdd, 0x89, 0xb6, 0x3b, 0xf1, 0x89, 0x27, 0xc7,
+ 0x5b, 0x10, 0xb4, 0x1a, 0x23, 0xa1, 0x8f, 0x61, 0x7e, 0x20, 0xcc, 0x58, 0x49, 0xf1, 0x89, 0xbe,
+ 0xcc, 0xd2, 0xc0, 0x08, 0x1c, 0xc8, 0xa8, 0xbf, 0x9d, 0x80, 0xe5, 0x90, 0x4a, 0x7e, 0x69, 0x6c,
+ 0xb9, 0x64, 0x48, 0x1c, 0xdf, 0x43, 0x1f, 0x40, 0xd6, 0xb6, 0x86, 0x96, 0xef, 0x49, 0xe7, 0xbd,
+ 0x1a, 0xa7, 0x36, 0x1c, 0x14, 0x96, 0x60, 0x54, 0x85, 0xa2, 0x4b, 0x3c, 0xe2, 0x1e, 0x8a, 0xb5,
+ 0x29, 0xbd, 0x77, 0x85, 0xf0, 0x8c, 0x88, 0xba, 0x01, 0xb9, 0xae, 0xad, 0xfb, 0x7b, 0xd4, 0x1d,
+ 0x22, 0x15, 0x8a, 0xba, 0x6b, 0xec, 0x5b, 0x3e, 0x31, 0xfc, 0xb1, 0x1b, 0xec, 0x93, 0x19, 0x1a,
+ 0xba, 0x01, 0x49, 0x2a, 0x3a, 0xca, 0xd7, 0xb2, 0x67, 0xa7, 0x6b, 0xc9, 0x4e, 0x0f, 0x27, 0xa9,
+ 0xa7, 0x3e, 0x84, 0x6b, 0x5d, 0x7b, 0x3c, 0xb0, 0x9c, 0x06, 0xf1, 0x0c, 0xd7, 0x1a, 0x31, 0xed,
+ 0x6c, 0x39, 0xb1, 0x68, 0x12, 0x2c, 0x27, 0xf6, 0x1d, 0x6e, 0xc2, 0xe4, 0x74, 0x13, 0xaa, 0xbf,
+ 0x99, 0x84, 0x6b, 0x4d, 0x67, 0x60, 0x39, 0x24, 0x2a, 0x7d, 0x1b, 0x16, 0x09, 0x27, 0x6a, 0x87,
+ 0x22, 0x30, 0x48, 0x3d, 0x0b, 0x82, 0x1a, 0x44, 0x8b, 0xd6, 0xb9, 0x1d, 0x7c, 0x37, 0x6e, 0xf8,
+ 0x2f, 0x68, 0x8f, 0xdd, 0xc7, 0x4d, 0x98, 0x1f, 0xf1, 0x41, 0x78, 0x72, 0x7a, 0x6f, 0xc7, 0xe9,
+ 0x7a, 0x61, 0x9c, 0xc1, 0x76, 0x96, 0xb2, 0xdf, 0x66, 0x3b, 0xff, 0x71, 0x12, 0x96, 0xda, 0xd4,
+ 0x9c, 0xf1, 0x43, 0x09, 0x72, 0xfb, 0xd4, 0xf3, 0x23, 0xa1, 0x2b, 0x6c, 0xa3, 0xfb, 0x90, 0x1b,
+ 0xc9, 0xe9, 0x93, 0xb3, 0x7f, 0x2b, 0xde, 0x64, 0x81, 0xc1, 0x21, 0x1a, 0x3d, 0x84, 0x7c, 0xb0,
+ 0x65, 0xd8, 0x68, 0x5f, 0x62, 0xe1, 0x4c, 0xf1, 0xe8, 0x63, 0xc8, 0x8a, 0x49, 0x58, 0x49, 0x73,
+ 0xc9, 0xdb, 0x2f, 0xe5, 0x73, 0x2c, 0x85, 0xd0, 0x23, 0xc8, 0xf9, 0xb6, 0xa7, 0x59, 0xce, 0x1e,
+ 0x5d, 0xc9, 0x70, 0x05, 0x6b, 0x71, 0x0a, 0x98, 0x23, 0xfa, 0x5b, 0xbd, 0x96, 0xb3, 0x47, 0x6b,
+ 0x85, 0xb3, 0xd3, 0xb5, 0x79, 0xd9, 0xc0, 0xf3, 0xbe, 0xed, 0xb1, 0x0f, 0xf5, 0x77, 0x12, 0x50,
+ 0x88, 0xa0, 0xd0, 0xab, 0x00, 0xbe, 0x3b, 0xf6, 0x7c, 0xcd, 0xa5, 0xd4, 0xe7, 0xce, 0x2a, 0xe2,
+ 0x3c, 0xa7, 0x60, 0x4a, 0x7d, 0x54, 0x81, 0xeb, 0x06, 0x71, 0x7d, 0xcd, 0xf2, 0xbc, 0x31, 0x71,
+ 0x35, 0x6f, 0xbc, 0xfb, 0x05, 0x31, 0x7c, 0xee, 0xb8, 0x22, 0xbe, 0xc6, 0x58, 0x2d, 0xce, 0xe9,
+ 0x09, 0x06, 0xba, 0x07, 0x37, 0xa2, 0xf8, 0xd1, 0x78, 0xd7, 0xb6, 0x0c, 0x8d, 0x4d, 0x66, 0x8a,
+ 0x8b, 0x5c, 0x9f, 0x8a, 0x74, 0x39, 0xef, 0x31, 0x99, 0xa8, 0x3f, 0x4d, 0x80, 0x82, 0xf5, 0x3d,
+ 0x7f, 0x9b, 0x0c, 0x77, 0x89, 0xdb, 0xf3, 0x75, 0x7f, 0xec, 0xa1, 0x1b, 0x90, 0xb5, 0x89, 0x6e,
+ 0x12, 0x11, 0x1d, 0x73, 0x58, 0xb6, 0xd0, 0x0e, 0xdb, 0xc1, 0xba, 0xb1, 0xaf, 0xef, 0x5a, 0xb6,
+ 0xe5, 0x4f, 0xb8, 0x29, 0x8b, 0xf1, 0x4b, 0xf8, 0xbc, 0xce, 0x0a, 0x8e, 0x08, 0xe2, 0x19, 0x35,
+ 0x68, 0x05, 0xe6, 0x87, 0xc4, 0xf3, 0xf4, 0x01, 0xe1, 0x96, 0xe6, 0x71, 0xd0, 0x54, 0x1f, 0x42,
+ 0x31, 0x2a, 0x87, 0x0a, 0x30, 0xbf, 0xd3, 0x7e, 0xdc, 0xee, 0x3c, 0x6d, 0x2b, 0x73, 0x68, 0x09,
+ 0x0a, 0x3b, 0x6d, 0xdc, 0xac, 0xd6, 0x37, 0xab, 0xb5, 0xad, 0xa6, 0x92, 0x40, 0x0b, 0x90, 0x9f,
+ 0x36, 0x93, 0xea, 0x9f, 0x26, 0x00, 0x98, 0xbb, 0xe5, 0xa0, 0x3e, 0x82, 0x8c, 0xe7, 0xeb, 0xbe,
+ 0x58, 0x95, 0x8b, 0xeb, 0x6f, 0x5c, 0x34, 0x87, 0xd2, 0x5e, 0xf6, 0x8f, 0x60, 0x21, 0x12, 0xb5,
+ 0x30, 0x39, 0x63, 0x21, 0x0b, 0x10, 0xba, 0x69, 0xba, 0xd2, 0x70, 0xfe, 0xad, 0x3e, 0x84, 0x0c,
+ 0x97, 0x9e, 0x35, 0x37, 0x07, 0xe9, 0x06, 0xfb, 0x4a, 0xa0, 0x3c, 0x64, 0x70, 0xb3, 0xda, 0xf8,
+ 0x5c, 0x49, 0x22, 0x05, 0x8a, 0x8d, 0x56, 0xaf, 0xde, 0x69, 0xb7, 0x9b, 0xf5, 0x7e, 0xb3, 0xa1,
+ 0xa4, 0xd4, 0xdb, 0x90, 0x69, 0x0d, 0x99, 0xe6, 0x5b, 0x6c, 0xc9, 0xef, 0x11, 0x97, 0x38, 0x46,
+ 0xb0, 0x93, 0xa6, 0x04, 0xf5, 0x27, 0x79, 0xc8, 0x6c, 0xd3, 0xb1, 0xe3, 0xa3, 0xf5, 0x48, 0xd8,
+ 0x5a, 0x8c, 0x3f, 0xcb, 0x39, 0xb0, 0xd2, 0x9f, 0x8c, 0x88, 0x0c, 0x6b, 0x37, 0x20, 0x2b, 0x36,
+ 0x87, 0x1c, 0x8e, 0x6c, 0x31, 0xba, 0xaf, 0xbb, 0x03, 0xe2, 0xcb, 0xf1, 0xc8, 0x16, 0x7a, 0x8b,
+ 0x9d, 0x58, 0xba, 0x49, 0x1d, 0x7b, 0xc2, 0xf7, 0x50, 0x4e, 0x1c, 0x4b, 0x98, 0xe8, 0x66, 0xc7,
+ 0xb1, 0x27, 0x38, 0xe4, 0xa2, 0x4d, 0x28, 0xee, 0x5a, 0x8e, 0xa9, 0xd1, 0x91, 0x08, 0xf2, 0x99,
+ 0x8b, 0x77, 0x9c, 0xb0, 0xaa, 0x66, 0x39, 0x66, 0x47, 0x80, 0x71, 0x61, 0x77, 0xda, 0x40, 0x6d,
+ 0x58, 0x3c, 0xa4, 0xf6, 0x78, 0x48, 0x42, 0x5d, 0x59, 0xae, 0xeb, 0xcd, 0x8b, 0x75, 0x3d, 0xe1,
+ 0xf8, 0x40, 0xdb, 0xc2, 0x61, 0xb4, 0x89, 0x1e, 0xc3, 0x82, 0x3f, 0x1c, 0xed, 0x79, 0xa1, 0xba,
+ 0x79, 0xae, 0xee, 0x7b, 0x97, 0x38, 0x8c, 0xc1, 0x03, 0x6d, 0x45, 0x3f, 0xd2, 0x2a, 0xfd, 0x7a,
+ 0x0a, 0x0a, 0x11, 0xcb, 0x51, 0x0f, 0x0a, 0x23, 0x97, 0x8e, 0xf4, 0x01, 0x3f, 0xa8, 0xe4, 0x5c,
+ 0xdc, 0x7d, 0xa9, 0x51, 0x57, 0xba, 0x53, 0x41, 0x1c, 0xd5, 0xa2, 0x9e, 0x24, 0xa1, 0x10, 0x61,
+ 0xa2, 0x77, 0x20, 0x87, 0xbb, 0xb8, 0xf5, 0xa4, 0xda, 0x6f, 0x2a, 0x73, 0xa5, 0x5b, 0xc7, 0x27,
+ 0xe5, 0x15, 0xae, 0x2d, 0xaa, 0xa0, 0xeb, 0x5a, 0x87, 0x6c, 0xe9, 0xbd, 0x05, 0xf3, 0x01, 0x34,
+ 0x51, 0x7a, 0xe5, 0xf8, 0xa4, 0xfc, 0xdd, 0xf3, 0xd0, 0x08, 0x12, 0xf7, 0x36, 0xab, 0xb8, 0xd9,
+ 0x50, 0x92, 0xf1, 0x48, 0xdc, 0xdb, 0xd7, 0x5d, 0x62, 0xa2, 0xef, 0x41, 0x56, 0x02, 0x53, 0xa5,
+ 0xd2, 0xf1, 0x49, 0xf9, 0xc6, 0x79, 0xe0, 0x14, 0x87, 0x7b, 0x5b, 0xd5, 0x27, 0x4d, 0x25, 0x1d,
+ 0x8f, 0xc3, 0x3d, 0x5b, 0x3f, 0x24, 0xe8, 0x0d, 0xc8, 0x08, 0x58, 0xa6, 0x74, 0xf3, 0xf8, 0xa4,
+ 0xfc, 0x9d, 0x17, 0xd4, 0x31, 0x54, 0x69, 0xe5, 0xb7, 0xfe, 0x60, 0x75, 0xee, 0x2f, 0xff, 0x70,
+ 0x55, 0x39, 0xcf, 0x2e, 0xfd, 0x77, 0x02, 0x16, 0x66, 0xa6, 0x1c, 0xa9, 0x90, 0x75, 0xa8, 0x41,
+ 0x47, 0xe2, 0xfc, 0xca, 0xd5, 0xe0, 0xec, 0x74, 0x2d, 0xdb, 0xa6, 0x75, 0x3a, 0x9a, 0x60, 0xc9,
+ 0x41, 0x8f, 0xcf, 0x9d, 0xc0, 0xf7, 0x5e, 0x72, 0x3d, 0xc5, 0x9e, 0xc1, 0x9f, 0xc2, 0x82, 0xe9,
+ 0x5a, 0x87, 0xc4, 0xd5, 0x0c, 0xea, 0xec, 0x59, 0x03, 0x79, 0x36, 0x95, 0xe2, 0x74, 0x36, 0x38,
+ 0x10, 0x17, 0x85, 0x40, 0x9d, 0xe3, 0xbf, 0xc5, 0xe9, 0x5b, 0x7a, 0x02, 0xc5, 0xe8, 0x0a, 0x65,
+ 0xc7, 0x89, 0x67, 0xfd, 0x32, 0x91, 0xf9, 0x20, 0xcf, 0x1e, 0x71, 0x9e, 0x51, 0x44, 0x36, 0xf8,
+ 0x26, 0xa4, 0x87, 0xd4, 0x14, 0x7a, 0x16, 0x6a, 0xd7, 0x59, 0x12, 0xf0, 0x4f, 0xa7, 0x6b, 0x05,
+ 0xea, 0x55, 0x36, 0x2c, 0x9b, 0x6c, 0x53, 0x93, 0x60, 0x0e, 0x50, 0x0f, 0x21, 0xcd, 0x42, 0x05,
+ 0x7a, 0x05, 0xd2, 0xb5, 0x56, 0xbb, 0xa1, 0xcc, 0x95, 0xae, 0x1d, 0x9f, 0x94, 0x17, 0xb8, 0x4b,
+ 0x18, 0x83, 0xad, 0x5d, 0xb4, 0x06, 0xd9, 0x27, 0x9d, 0xad, 0x9d, 0x6d, 0xb6, 0xbc, 0xae, 0x1f,
+ 0x9f, 0x94, 0x97, 0x42, 0xb6, 0x70, 0x1a, 0x7a, 0x15, 0x32, 0xfd, 0xed, 0xee, 0x46, 0x4f, 0x49,
+ 0x96, 0xd0, 0xf1, 0x49, 0x79, 0x31, 0xe4, 0x73, 0x9b, 0x4b, 0xd7, 0xe4, 0xac, 0xe6, 0x43, 0xba,
+ 0xfa, 0xb3, 0x24, 0x2c, 0x60, 0x56, 0x9b, 0xb9, 0x7e, 0x97, 0xda, 0x96, 0x31, 0x41, 0x5d, 0xc8,
+ 0x1b, 0xd4, 0x31, 0xad, 0xc8, 0x9e, 0x5a, 0xbf, 0xe0, 0xd4, 0x9f, 0x4a, 0x05, 0xad, 0x7a, 0x20,
+ 0x89, 0xa7, 0x4a, 0xd0, 0x7b, 0x90, 0x31, 0x89, 0xad, 0x4f, 0x64, 0xfa, 0x71, 0xb3, 0x22, 0xaa,
+ 0xbf, 0x4a, 0x50, 0xfd, 0x55, 0x1a, 0xb2, 0xfa, 0xc3, 0x02, 0xc7, 0xd3, 0x6c, 0xfd, 0x99, 0xa6,
+ 0xfb, 0x3e, 0x19, 0x8e, 0x7c, 0x91, 0x7b, 0xa4, 0x71, 0x61, 0xa8, 0x3f, 0xab, 0x4a, 0x12, 0xba,
+ 0x0b, 0xd9, 0x23, 0xcb, 0x31, 0xe9, 0x91, 0x4c, 0x2f, 0x2e, 0x51, 0x2a, 0x81, 0xea, 0x31, 0x3b,
+ 0x75, 0xcf, 0x99, 0xc9, 0xfc, 0xdd, 0xee, 0xb4, 0x9b, 0x81, 0xbf, 0x25, 0xbf, 0xe3, 0xb4, 0xa9,
+ 0xc3, 0xf6, 0x0a, 0x74, 0xda, 0xda, 0x46, 0xb5, 0xb5, 0xb5, 0x83, 0x99, 0xcf, 0x97, 0x8f, 0x4f,
+ 0xca, 0x4a, 0x08, 0xd9, 0xd0, 0x2d, 0x9b, 0xe5, 0xbb, 0x37, 0x21, 0x55, 0x6d, 0x7f, 0xae, 0x24,
+ 0x4b, 0xca, 0xf1, 0x49, 0xb9, 0x18, 0xb2, 0xab, 0xce, 0x64, 0xba, 0x8d, 0xce, 0xf7, 0xab, 0xfe,
+ 0x6d, 0x0a, 0x8a, 0x3b, 0x23, 0x53, 0xf7, 0x89, 0x58, 0x93, 0xa8, 0x0c, 0x85, 0x91, 0xee, 0xea,
+ 0xb6, 0x4d, 0x6c, 0xcb, 0x1b, 0xca, 0xba, 0x36, 0x4a, 0x42, 0x0f, 0x5e, 0xd6, 0x8d, 0xb5, 0x1c,
+ 0x5b, 0x67, 0x3f, 0xfe, 0x97, 0xb5, 0x44, 0xe0, 0xd0, 0x1d, 0x58, 0xdc, 0x13, 0xd6, 0x6a, 0xba,
+ 0xc1, 0x27, 0x36, 0xc5, 0x27, 0xb6, 0x12, 0x37, 0xb1, 0x51, 0xb3, 0x2a, 0x72, 0x90, 0x55, 0x2e,
+ 0x85, 0x17, 0xf6, 0xa2, 0x4d, 0x74, 0x0f, 0xe6, 0x87, 0xd4, 0xb1, 0x7c, 0xea, 0x5e, 0x3d, 0x0b,
+ 0x01, 0x12, 0xbd, 0x03, 0xd7, 0xd8, 0xe4, 0x06, 0xf6, 0x70, 0x36, 0x3f, 0xb1, 0x92, 0x78, 0x69,
+ 0xa8, 0x3f, 0x93, 0x1d, 0x62, 0x46, 0x46, 0x35, 0xc8, 0x50, 0x97, 0xa5, 0x44, 0x59, 0x6e, 0xee,
+ 0xbb, 0x57, 0x9a, 0x2b, 0x1a, 0x1d, 0x26, 0x83, 0x85, 0xa8, 0xfa, 0x21, 0x2c, 0xcc, 0x0c, 0x82,
+ 0x65, 0x02, 0xdd, 0xea, 0x4e, 0xaf, 0xa9, 0xcc, 0xa1, 0x22, 0xe4, 0xea, 0x9d, 0x76, 0xbf, 0xd5,
+ 0xde, 0x61, 0xa9, 0x4c, 0x11, 0x72, 0xb8, 0xb3, 0xb5, 0x55, 0xab, 0xd6, 0x1f, 0x2b, 0x49, 0xb5,
+ 0x02, 0x85, 0x88, 0x36, 0xb4, 0x08, 0xd0, 0xeb, 0x77, 0xba, 0xda, 0x46, 0x0b, 0xf7, 0xfa, 0x22,
+ 0x11, 0xea, 0xf5, 0xab, 0xb8, 0x2f, 0x09, 0x09, 0xf5, 0x3f, 0x92, 0xc1, 0x8c, 0xca, 0xdc, 0xa7,
+ 0x36, 0x9b, 0xfb, 0x5c, 0x62, 0xbc, 0xcc, 0x7e, 0xa6, 0x8d, 0x30, 0x07, 0x7a, 0x00, 0xc0, 0x17,
+ 0x0e, 0x31, 0x35, 0xdd, 0x97, 0x13, 0x5f, 0x7a, 0xc1, 0xc9, 0xfd, 0xe0, 0x7a, 0x05, 0xe7, 0x25,
+ 0xba, 0xea, 0xa3, 0x8f, 0xa1, 0x68, 0xd0, 0xe1, 0xc8, 0x26, 0x52, 0x38, 0x75, 0xa5, 0x70, 0x21,
+ 0xc4, 0x57, 0xfd, 0x68, 0xf6, 0x95, 0x9e, 0xcd, 0x0f, 0x7f, 0x23, 0x11, 0x78, 0x26, 0x26, 0xe1,
+ 0x2a, 0x42, 0x6e, 0xa7, 0xdb, 0xa8, 0xf6, 0x5b, 0xed, 0x47, 0x4a, 0x02, 0x01, 0x64, 0xb9, 0xab,
+ 0x1b, 0x4a, 0x92, 0x25, 0x8a, 0xf5, 0xce, 0x76, 0x77, 0xab, 0xc9, 0x53, 0x2e, 0xb4, 0x0c, 0x4a,
+ 0xe0, 0x6c, 0x8d, 0x3b, 0xb2, 0xd9, 0x50, 0xd2, 0xe8, 0x3a, 0x2c, 0x85, 0x54, 0x29, 0x99, 0x41,
+ 0x37, 0x00, 0x85, 0xc4, 0xa9, 0x8a, 0xac, 0xfa, 0xab, 0xb0, 0x54, 0xa7, 0x8e, 0xaf, 0x5b, 0x4e,
+ 0x98, 0x44, 0xaf, 0xb3, 0x41, 0x4b, 0x92, 0x66, 0xc9, 0x5b, 0x8a, 0xda, 0xd2, 0xd9, 0xe9, 0x5a,
+ 0x21, 0x84, 0xb6, 0x1a, 0x6c, 0xa4, 0x41, 0xc3, 0x64, 0xfb, 0x77, 0x64, 0x99, 0xdc, 0xb9, 0x99,
+ 0xda, 0xfc, 0xd9, 0xe9, 0x5a, 0xaa, 0xdb, 0x6a, 0x60, 0x46, 0x43, 0xaf, 0x40, 0x9e, 0x3c, 0xb3,
+ 0x7c, 0xcd, 0x60, 0x31, 0x9c, 0x39, 0x30, 0x83, 0x73, 0x8c, 0x50, 0x67, 0x21, 0xbb, 0x06, 0xd0,
+ 0xa5, 0xae, 0x2f, 0x7b, 0x7e, 0x1f, 0x32, 0x23, 0xea, 0xf2, 0xf2, 0xfc, 0xc2, 0xeb, 0x1d, 0x06,
+ 0x17, 0x0b, 0x15, 0x0b, 0xb0, 0xfa, 0x57, 0x49, 0x80, 0xbe, 0xee, 0x1d, 0x48, 0x25, 0xf7, 0x21,
+ 0x1f, 0x5e, 0x95, 0xc9, 0x3a, 0xff, 0xd2, 0xd9, 0x0e, 0xc1, 0xe8, 0x5e, 0xb0, 0xd8, 0x44, 0x79,
+ 0x10, 0x5b, 0xa7, 0x05, 0x1d, 0xc5, 0x65, 0xd8, 0xb3, 0x35, 0x00, 0x3b, 0x12, 0x89, 0xeb, 0xca,
+ 0x99, 0x67, 0x9f, 0xa8, 0xce, 0x8f, 0x05, 0xe1, 0x34, 0x99, 0x60, 0xc6, 0xde, 0x6c, 0x9c, 0x9b,
+ 0x91, 0xcd, 0x39, 0x3c, 0x95, 0x43, 0x9f, 0x42, 0x81, 0x8d, 0x5b, 0xf3, 0x38, 0x4f, 0xe6, 0x96,
+ 0x17, 0xba, 0x4a, 0x68, 0xc0, 0x30, 0x0a, 0xbf, 0x6b, 0x0a, 0x2c, 0xba, 0x63, 0x87, 0x0d, 0x5b,
+ 0xea, 0x50, 0xff, 0x24, 0x09, 0xdf, 0x6d, 0x13, 0xff, 0x88, 0xba, 0x07, 0x55, 0xdf, 0xd7, 0x8d,
+ 0xfd, 0x21, 0x71, 0xa4, 0x93, 0x23, 0x99, 0x75, 0x62, 0x26, 0xb3, 0x5e, 0x81, 0x79, 0xdd, 0xb6,
+ 0x74, 0x8f, 0x88, 0x74, 0x24, 0x8f, 0x83, 0x26, 0xcb, 0xff, 0x59, 0x35, 0x41, 0x3c, 0x8f, 0x88,
+ 0x02, 0x3f, 0x8f, 0xa7, 0x04, 0xf4, 0x23, 0xb8, 0x21, 0x13, 0x0f, 0x3d, 0xec, 0x8a, 0x65, 0xb6,
+ 0xc1, 0x9d, 0x5e, 0x33, 0xb6, 0xbc, 0x89, 0x37, 0x4e, 0x66, 0x26, 0x53, 0x72, 0x67, 0xe4, 0xcb,
+ 0x3c, 0x67, 0xd9, 0x8c, 0x61, 0x95, 0x1e, 0xc1, 0xcd, 0x0b, 0x45, 0xbe, 0xd1, 0x05, 0xc2, 0x3f,
+ 0x24, 0x01, 0x5a, 0xdd, 0xea, 0xb6, 0x74, 0x52, 0x03, 0xb2, 0x7b, 0xfa, 0xd0, 0xb2, 0x27, 0x97,
+ 0xc5, 0xa9, 0x29, 0xbe, 0x52, 0x15, 0xee, 0xd8, 0xe0, 0x32, 0x58, 0xca, 0xf2, 0xe2, 0x66, 0xbc,
+ 0xeb, 0x10, 0x3f, 0x2c, 0x6e, 0x78, 0x8b, 0x99, 0xe1, 0xea, 0x4e, 0xb8, 0xc0, 0x44, 0x83, 0x4d,
+ 0xc0, 0x40, 0xf7, 0xc9, 0x91, 0x3e, 0x09, 0x82, 0x8b, 0x6c, 0xa2, 0x4d, 0x7e, 0x4d, 0x47, 0xdc,
+ 0x43, 0x62, 0xae, 0x64, 0xb8, 0x53, 0xaf, 0xb2, 0x07, 0x4b, 0xb8, 0xf0, 0x5d, 0x28, 0x5d, 0x7a,
+ 0xc8, 0x13, 0x9b, 0x29, 0xeb, 0x1b, 0xf9, 0xe8, 0x0e, 0x2c, 0xcc, 0x8c, 0xf3, 0x85, 0xaa, 0xb2,
+ 0xd5, 0x7d, 0xf2, 0xbe, 0x92, 0x96, 0x5f, 0x1f, 0x2a, 0x59, 0xf5, 0x8f, 0x52, 0x22, 0x1c, 0x48,
+ 0xaf, 0xc6, 0x5f, 0x24, 0xe7, 0xf8, 0x26, 0x36, 0xa8, 0x2d, 0xb7, 0xe9, 0x9b, 0x97, 0x47, 0x09,
+ 0x56, 0xa5, 0x70, 0x38, 0x0e, 0x05, 0xd1, 0x1a, 0x14, 0xc4, 0x2a, 0xd6, 0xd8, 0xb6, 0xe0, 0x6e,
+ 0x5d, 0xc0, 0x20, 0x48, 0x4c, 0x12, 0xdd, 0x86, 0x45, 0x7e, 0x0b, 0xe1, 0xed, 0x13, 0x53, 0x60,
+ 0xd2, 0x1c, 0xb3, 0x10, 0x52, 0x39, 0x6c, 0x1b, 0x8a, 0x92, 0xa0, 0xf1, 0x0c, 0x35, 0xc3, 0x0d,
+ 0x7a, 0xe7, 0x2a, 0x83, 0x84, 0x08, 0x4f, 0x5c, 0x0b, 0xa3, 0x69, 0x43, 0x6d, 0x40, 0x2e, 0x30,
+ 0x16, 0xad, 0x40, 0xaa, 0x5f, 0xef, 0x2a, 0x73, 0xa5, 0xa5, 0xe3, 0x93, 0x72, 0x21, 0x20, 0xf7,
+ 0xeb, 0x5d, 0xc6, 0xd9, 0x69, 0x74, 0x95, 0xc4, 0x2c, 0x67, 0xa7, 0xd1, 0x2d, 0xa5, 0x59, 0xa6,
+ 0xa4, 0xee, 0x41, 0x21, 0xd2, 0x03, 0x7a, 0x1d, 0xe6, 0x5b, 0xed, 0x47, 0xb8, 0xd9, 0xeb, 0x29,
+ 0x73, 0xa5, 0x1b, 0xc7, 0x27, 0x65, 0x14, 0xe1, 0xb6, 0x9c, 0x01, 0x9b, 0x1f, 0xf4, 0x2a, 0xa4,
+ 0x37, 0x3b, 0xec, 0x04, 0x16, 0x29, 0x71, 0x04, 0xb1, 0x49, 0x3d, 0xbf, 0x74, 0x5d, 0xa6, 0x60,
+ 0x51, 0xc5, 0xea, 0xef, 0x25, 0x20, 0x2b, 0x36, 0x53, 0xec, 0x44, 0x55, 0x61, 0x3e, 0xa8, 0x57,
+ 0x45, 0xb9, 0xf2, 0xe6, 0xc5, 0xa5, 0x45, 0x45, 0x56, 0x02, 0x62, 0xf9, 0x05, 0x72, 0xa5, 0x8f,
+ 0xa0, 0x18, 0x65, 0x7c, 0xa3, 0xc5, 0xf7, 0x23, 0x28, 0xb0, 0xf5, 0x1d, 0x94, 0x18, 0xeb, 0x90,
+ 0x15, 0x01, 0x21, 0x3c, 0x11, 0x2e, 0xae, 0x73, 0x24, 0x12, 0xdd, 0x87, 0x79, 0x51, 0x1b, 0x05,
+ 0xd7, 0x94, 0xab, 0x97, 0xef, 0x22, 0x1c, 0xc0, 0xd5, 0x4f, 0x21, 0xdd, 0x25, 0xc4, 0x65, 0xbe,
+ 0x77, 0xa8, 0x49, 0xa6, 0x87, 0xa8, 0x2c, 0xeb, 0x4c, 0xd2, 0x6a, 0xb0, 0xb2, 0xce, 0x24, 0x2d,
+ 0x33, 0xbc, 0x88, 0x49, 0x46, 0x2e, 0x62, 0xfa, 0x50, 0x7c, 0x4a, 0xac, 0xc1, 0xbe, 0x4f, 0x4c,
+ 0xae, 0xe8, 0x5d, 0x48, 0x8f, 0x48, 0x68, 0xfc, 0x4a, 0xec, 0x02, 0x23, 0xc4, 0xc5, 0x1c, 0xc5,
+ 0xe2, 0xc8, 0x11, 0x97, 0x96, 0x77, 0xeb, 0xb2, 0xa5, 0xfe, 0x7d, 0x12, 0x16, 0x5b, 0x9e, 0x37,
+ 0xd6, 0x1d, 0x23, 0xc8, 0xaf, 0x3e, 0x99, 0xcd, 0xaf, 0xde, 0x8a, 0x1d, 0xe1, 0x8c, 0xc8, 0xec,
+ 0xfd, 0x92, 0x3c, 0xe3, 0x92, 0xe1, 0x19, 0xa7, 0xfe, 0x7b, 0x22, 0xb8, 0x44, 0xba, 0x1d, 0xd9,
+ 0xee, 0xa5, 0x95, 0xe3, 0x93, 0xf2, 0x72, 0x54, 0x13, 0xd9, 0x71, 0x0e, 0x1c, 0x7a, 0xe4, 0xa0,
+ 0xd7, 0x20, 0x83, 0x9b, 0xed, 0xe6, 0x53, 0x25, 0x21, 0x96, 0xe7, 0x0c, 0x08, 0x13, 0x87, 0x1c,
+ 0x31, 0x4d, 0xdd, 0x66, 0xbb, 0xc1, 0xf2, 0xa1, 0x64, 0x8c, 0xa6, 0x2e, 0x71, 0x4c, 0xcb, 0x19,
+ 0xa0, 0xd7, 0x21, 0xdb, 0xea, 0xf5, 0x76, 0x78, 0x99, 0xff, 0xdd, 0xe3, 0x93, 0xf2, 0xf5, 0x19,
+ 0x14, 0xbf, 0x40, 0x34, 0x19, 0x88, 0x15, 0x23, 0x2c, 0x53, 0x8a, 0x01, 0xb1, 0x2c, 0x57, 0x80,
+ 0x70, 0xa7, 0x5f, 0xed, 0xb3, 0x0a, 0xff, 0x45, 0x10, 0xa6, 0xec, 0xaf, 0xdc, 0x6e, 0xff, 0x9c,
+ 0x04, 0xa5, 0x6a, 0x18, 0x64, 0xe4, 0x33, 0xbe, 0xac, 0xff, 0xfa, 0x90, 0x1b, 0xb1, 0x2f, 0x8b,
+ 0x04, 0xb9, 0xcc, 0xfd, 0xd8, 0x07, 0xaf, 0x73, 0x72, 0x15, 0x4c, 0x6d, 0x52, 0x35, 0x87, 0x96,
+ 0xe7, 0x59, 0xd4, 0x11, 0x34, 0x1c, 0x6a, 0x2a, 0xfd, 0x67, 0x02, 0xae, 0xc7, 0x20, 0xd0, 0x1d,
+ 0x48, 0xbb, 0xd4, 0x0e, 0xe6, 0xf0, 0xd6, 0x45, 0xf7, 0x83, 0x4c, 0x14, 0x73, 0x24, 0x5a, 0x05,
+ 0xd0, 0xc7, 0x3e, 0xd5, 0x79, 0xff, 0x7c, 0xf6, 0x72, 0x38, 0x42, 0x41, 0x4f, 0x21, 0xeb, 0x11,
+ 0xc3, 0x25, 0x41, 0xc6, 0xfb, 0xe9, 0xff, 0xd5, 0xfa, 0x4a, 0x8f, 0xab, 0xc1, 0x52, 0x5d, 0xa9,
+ 0x02, 0x59, 0x41, 0x61, 0xcb, 0xde, 0xd4, 0x7d, 0x5d, 0xde, 0x1e, 0xf3, 0x6f, 0xb6, 0x9a, 0x74,
+ 0x7b, 0x10, 0xac, 0x26, 0xdd, 0x1e, 0xa8, 0x7f, 0x93, 0x04, 0x68, 0x3e, 0xf3, 0x89, 0xeb, 0xe8,
+ 0x76, 0xbd, 0x8a, 0x9a, 0x91, 0xe8, 0x2f, 0x46, 0xfb, 0x76, 0xec, 0x95, 0x78, 0x28, 0x51, 0xa9,
+ 0x57, 0x63, 0xe2, 0xff, 0x4d, 0x48, 0x8d, 0x5d, 0xf9, 0x86, 0x29, 0xb2, 0xd5, 0x1d, 0xbc, 0x85,
+ 0x19, 0x0d, 0x35, 0xa7, 0x61, 0x2b, 0x75, 0xf1, 0x4b, 0x65, 0xa4, 0x83, 0xd8, 0xd0, 0xc5, 0x76,
+ 0xbe, 0xa1, 0x6b, 0x06, 0x91, 0x27, 0x47, 0x51, 0xec, 0xfc, 0x7a, 0xb5, 0x4e, 0x5c, 0x1f, 0x67,
+ 0x0d, 0x9d, 0xfd, 0xff, 0x56, 0xf1, 0xed, 0x5d, 0x80, 0xe9, 0xd0, 0xd0, 0x2a, 0x64, 0xea, 0x1b,
+ 0xbd, 0xde, 0x96, 0x32, 0x27, 0x02, 0xf8, 0x94, 0xc5, 0xc9, 0xea, 0x5f, 0x24, 0x21, 0x57, 0xaf,
+ 0xca, 0x63, 0xb5, 0x0e, 0x0a, 0x8f, 0x4a, 0xfc, 0xce, 0x9d, 0x3c, 0x1b, 0x59, 0xee, 0x44, 0x06,
+ 0x96, 0x4b, 0x4a, 0xcf, 0x45, 0x26, 0xc2, 0xac, 0x6e, 0x72, 0x01, 0x84, 0xa1, 0x48, 0xa4, 0x13,
+ 0x34, 0x43, 0x0f, 0x62, 0xfc, 0xea, 0xe5, 0xce, 0x12, 0x45, 0xc4, 0xb4, 0xed, 0xe1, 0x42, 0xa0,
+ 0xa4, 0xae, 0x7b, 0xe8, 0x01, 0x2c, 0x79, 0xd6, 0xc0, 0xb1, 0x9c, 0x81, 0x16, 0x38, 0x8f, 0x3f,
+ 0x00, 0xd4, 0xae, 0x9d, 0x9d, 0xae, 0x2d, 0xf4, 0x04, 0x4b, 0xfa, 0x70, 0x41, 0x22, 0xeb, 0xdc,
+ 0x95, 0xe8, 0x43, 0x58, 0x8c, 0x88, 0x32, 0x2f, 0x0a, 0xb7, 0x2b, 0x67, 0xa7, 0x6b, 0xc5, 0x50,
+ 0xf2, 0x31, 0x99, 0xe0, 0x62, 0x28, 0xf8, 0x98, 0xf0, 0x5b, 0x92, 0x3d, 0xea, 0x1a, 0x44, 0x73,
+ 0xf9, 0x9e, 0xe6, 0x27, 0x78, 0x1a, 0x17, 0x38, 0x4d, 0x6c, 0x73, 0xf5, 0x09, 0x5c, 0xef, 0xb8,
+ 0xc6, 0x3e, 0xf1, 0x7c, 0xe1, 0x0a, 0xe9, 0xc5, 0x4f, 0xe1, 0x96, 0xaf, 0x7b, 0x07, 0xda, 0xbe,
+ 0xe5, 0xf9, 0xd4, 0x9d, 0x68, 0x2e, 0xf1, 0x89, 0xc3, 0xf8, 0x1a, 0x7f, 0x35, 0x94, 0xd7, 0x58,
+ 0x37, 0x19, 0x66, 0x53, 0x40, 0x70, 0x80, 0xd8, 0x62, 0x00, 0xb5, 0x05, 0x45, 0x56, 0x4c, 0x34,
+ 0xc8, 0x9e, 0x3e, 0xb6, 0x7d, 0x36, 0x7a, 0xb0, 0xe9, 0x40, 0x7b, 0xe9, 0x63, 0x2a, 0x6f, 0xd3,
+ 0x81, 0xf8, 0x54, 0x7f, 0x08, 0x4a, 0xc3, 0xf2, 0x46, 0xba, 0x6f, 0xec, 0x07, 0xf7, 0x73, 0xa8,
+ 0x01, 0xca, 0x3e, 0xd1, 0x5d, 0x7f, 0x97, 0xe8, 0xbe, 0x36, 0x22, 0xae, 0x45, 0xcd, 0xab, 0x67,
+ 0x79, 0x29, 0x14, 0xe9, 0x72, 0x09, 0xf5, 0xbf, 0x12, 0x00, 0x58, 0xdf, 0x0b, 0x32, 0xb2, 0xef,
+ 0xc3, 0x35, 0xcf, 0xd1, 0x47, 0xde, 0x3e, 0xf5, 0x35, 0xcb, 0xf1, 0x89, 0x7b, 0xa8, 0xdb, 0xf2,
+ 0x9a, 0x45, 0x09, 0x18, 0x2d, 0x49, 0x47, 0xef, 0x02, 0x3a, 0x20, 0x64, 0xa4, 0x51, 0xdb, 0xd4,
+ 0x02, 0xa6, 0x78, 0xd3, 0x4c, 0x63, 0x85, 0x71, 0x3a, 0xb6, 0xd9, 0x0b, 0xe8, 0xa8, 0x06, 0xab,
+ 0x6c, 0xf8, 0xc4, 0xf1, 0x5d, 0x8b, 0x78, 0xda, 0x1e, 0x75, 0x35, 0xcf, 0xa6, 0x47, 0xda, 0x1e,
+ 0xb5, 0x6d, 0x7a, 0x44, 0xdc, 0xe0, 0x06, 0xab, 0x64, 0xd3, 0x41, 0x53, 0x80, 0x36, 0xa8, 0xdb,
+ 0xb3, 0xe9, 0xd1, 0x46, 0x80, 0x60, 0x69, 0xdb, 0x74, 0xcc, 0xbe, 0x65, 0x1c, 0x04, 0x69, 0x5b,
+ 0x48, 0xed, 0x5b, 0xc6, 0x01, 0x7a, 0x1d, 0x16, 0x88, 0x4d, 0xf8, 0x45, 0x86, 0x40, 0x65, 0x38,
+ 0xaa, 0x18, 0x10, 0x19, 0x48, 0xfd, 0x0c, 0x94, 0xa6, 0x63, 0xb8, 0x93, 0x51, 0x64, 0xce, 0xdf,
+ 0x05, 0xc4, 0x82, 0xa4, 0x66, 0x53, 0xe3, 0x40, 0x1b, 0xea, 0x8e, 0x3e, 0x60, 0x76, 0x89, 0xa7,
+ 0x26, 0x85, 0x71, 0xb6, 0xa8, 0x71, 0xb0, 0x2d, 0xe9, 0xea, 0x03, 0x80, 0xde, 0xc8, 0x25, 0xba,
+ 0xd9, 0x61, 0xd9, 0x04, 0x73, 0x1d, 0x6f, 0x69, 0xa6, 0x7c, 0xaa, 0xa3, 0xae, 0xdc, 0xea, 0x8a,
+ 0x60, 0x34, 0x42, 0xba, 0xfa, 0x0b, 0x70, 0xbd, 0x6b, 0xeb, 0x06, 0x7f, 0xb6, 0xee, 0x86, 0x6f,
+ 0x27, 0xe8, 0x3e, 0x64, 0x05, 0x54, 0xce, 0x64, 0xec, 0x76, 0x9b, 0xf6, 0xb9, 0x39, 0x87, 0x25,
+ 0xbe, 0x56, 0x04, 0x98, 0xea, 0x51, 0xff, 0x2c, 0x01, 0xf9, 0x50, 0x3f, 0x2a, 0x03, 0x2b, 0xe5,
+ 0xd9, 0xf2, 0xb6, 0x1c, 0x59, 0x7b, 0xe7, 0x71, 0x94, 0x84, 0x5a, 0x50, 0x18, 0x85, 0xd2, 0x97,
+ 0xe6, 0x73, 0x31, 0x56, 0xe3, 0xa8, 0x2c, 0xfa, 0x08, 0xf2, 0xc1, 0xdb, 0x68, 0x10, 0x61, 0x2f,
+ 0x7f, 0x4a, 0x9d, 0xc2, 0xd5, 0x4f, 0x00, 0x7e, 0x40, 0x2d, 0xa7, 0x4f, 0x0f, 0x88, 0xc3, 0xdf,
+ 0xfa, 0x58, 0x4d, 0x48, 0x02, 0x2f, 0xca, 0x16, 0x2f, 0xc8, 0xc5, 0x14, 0x84, 0x4f, 0x5e, 0xa2,
+ 0xa9, 0xfe, 0x75, 0x12, 0xb2, 0x98, 0x52, 0xbf, 0x5e, 0x45, 0x65, 0xc8, 0xca, 0x38, 0xc1, 0xcf,
+ 0x9f, 0x5a, 0xfe, 0xec, 0x74, 0x2d, 0x23, 0x02, 0x44, 0xc6, 0xe0, 0x91, 0x21, 0x12, 0xc1, 0x93,
+ 0x17, 0x45, 0x70, 0x74, 0x07, 0x8a, 0x12, 0xa4, 0xed, 0xeb, 0xde, 0xbe, 0x28, 0xd0, 0x6a, 0x8b,
+ 0x67, 0xa7, 0x6b, 0x20, 0x90, 0x9b, 0xba, 0xb7, 0x8f, 0x41, 0xa0, 0xd9, 0x37, 0x6a, 0x42, 0xe1,
+ 0x0b, 0x6a, 0x39, 0x9a, 0xcf, 0x07, 0x21, 0xaf, 0xfc, 0x62, 0xe7, 0x71, 0x3a, 0x54, 0xf9, 0xf0,
+ 0x0d, 0x5f, 0x4c, 0x07, 0xdf, 0x84, 0x05, 0x97, 0x52, 0x5f, 0x84, 0x2d, 0x8b, 0x3a, 0xf2, 0x36,
+ 0xa1, 0x1c, 0x7b, 0xc9, 0x4c, 0xa9, 0x8f, 0x25, 0x0e, 0x17, 0xdd, 0x48, 0x0b, 0xdd, 0x81, 0x65,
+ 0x5b, 0xf7, 0x7c, 0x8d, 0xc7, 0x3b, 0x73, 0xaa, 0x2d, 0xcb, 0xb7, 0x1a, 0x62, 0xbc, 0x0d, 0xce,
+ 0x0a, 0x24, 0xd4, 0x7f, 0x4c, 0x40, 0x81, 0x0d, 0xc6, 0xda, 0xb3, 0x0c, 0x96, 0xe4, 0x7d, 0xf3,
+ 0xdc, 0xe3, 0x26, 0xa4, 0x0c, 0xcf, 0x95, 0x4e, 0xe5, 0x87, 0x6f, 0xbd, 0x87, 0x31, 0xa3, 0xa1,
+ 0xcf, 0x20, 0x2b, 0x6f, 0x35, 0x44, 0xda, 0xa1, 0x5e, 0x9d, 0x8e, 0x4a, 0xdf, 0x48, 0x39, 0xbe,
+ 0x96, 0xa7, 0xd6, 0x89, 0x43, 0x00, 0x47, 0x49, 0xe8, 0x06, 0x24, 0x0d, 0xe1, 0x2e, 0xf9, 0xcb,
+ 0x8a, 0x7a, 0x1b, 0x27, 0x0d, 0x47, 0xfd, 0xbb, 0x04, 0x2c, 0x4c, 0x37, 0x3c, 0x5b, 0x01, 0xb7,
+ 0x20, 0xef, 0x8d, 0x77, 0xbd, 0x89, 0xe7, 0x93, 0x61, 0xf0, 0x8e, 0x19, 0x12, 0x50, 0x0b, 0xf2,
+ 0xba, 0x3d, 0xa0, 0xae, 0xe5, 0xef, 0x0f, 0x65, 0x25, 0x1a, 0x9f, 0x2a, 0x44, 0x75, 0x56, 0xaa,
+ 0x81, 0x08, 0x9e, 0x4a, 0x07, 0xe7, 0xbe, 0x78, 0xec, 0xe6, 0xe7, 0xfe, 0x6b, 0x50, 0xb4, 0xf5,
+ 0x21, 0xbf, 0xe6, 0xf1, 0xad, 0xa1, 0x18, 0x47, 0x1a, 0x17, 0x24, 0xad, 0x6f, 0x0d, 0x89, 0xaa,
+ 0x42, 0x3e, 0x54, 0x86, 0x96, 0xa0, 0x50, 0x6d, 0xf6, 0xb4, 0xbb, 0xeb, 0xf7, 0xb5, 0x47, 0xf5,
+ 0x6d, 0x65, 0x4e, 0xe6, 0xa6, 0x7f, 0x9e, 0x80, 0x05, 0x19, 0x8e, 0x64, 0xbe, 0xff, 0x3a, 0xcc,
+ 0xbb, 0xfa, 0x9e, 0x1f, 0x54, 0x24, 0x69, 0xb1, 0xaa, 0x59, 0x84, 0x67, 0x15, 0x09, 0x63, 0xc5,
+ 0x57, 0x24, 0x91, 0x97, 0xf5, 0xd4, 0xa5, 0x2f, 0xeb, 0xe9, 0x9f, 0xcb, 0xcb, 0xba, 0xfa, 0x6b,
+ 0x00, 0x1b, 0x96, 0x4d, 0xfa, 0xe2, 0xae, 0x29, 0xae, 0xbe, 0x64, 0x39, 0x9c, 0xbc, 0x71, 0x0c,
+ 0x72, 0xb8, 0x56, 0x03, 0x33, 0x1a, 0x63, 0x0d, 0x2c, 0x53, 0x6e, 0x46, 0xce, 0x7a, 0xc4, 0x58,
+ 0x03, 0xcb, 0x0c, 0xdf, 0x92, 0xd2, 0x57, 0xbd, 0x25, 0x9d, 0x24, 0x60, 0x49, 0xe6, 0xae, 0x61,
+ 0xf8, 0x7d, 0x1b, 0xf2, 0x22, 0x8d, 0x9d, 0x16, 0x74, 0xfc, 0x35, 0x59, 0xe0, 0x5a, 0x0d, 0x9c,
+ 0x13, 0xec, 0x96, 0x89, 0xd6, 0xa0, 0x20, 0xa1, 0x91, 0x5f, 0xe1, 0x80, 0x20, 0xb5, 0x99, 0xf9,
+ 0xef, 0x43, 0x7a, 0xcf, 0xb2, 0x89, 0x5c, 0xe8, 0xb1, 0x01, 0x60, 0xea, 0x80, 0xcd, 0x39, 0xcc,
+ 0xd1, 0xb5, 0x5c, 0x70, 0x19, 0xc7, 0xed, 0x93, 0x65, 0x67, 0xd4, 0x3e, 0x51, 0x81, 0x9e, 0xb3,
+ 0x4f, 0xe0, 0x98, 0x7d, 0x82, 0x2d, 0xec, 0x93, 0xd0, 0xa8, 0x7d, 0x82, 0xf4, 0x73, 0xb1, 0x6f,
+ 0x0b, 0x6e, 0xd4, 0x6c, 0xdd, 0x38, 0xb0, 0x2d, 0xcf, 0x27, 0x66, 0x34, 0x62, 0xac, 0x43, 0x76,
+ 0x26, 0xe9, 0xbc, 0xec, 0x72, 0x56, 0x22, 0xd5, 0x7f, 0x4b, 0x40, 0x71, 0x93, 0xe8, 0xb6, 0xbf,
+ 0x3f, 0xbd, 0x1a, 0xf2, 0x89, 0xe7, 0xcb, 0xc3, 0x8a, 0x7f, 0xa3, 0x0f, 0x20, 0x17, 0xe6, 0x24,
+ 0x57, 0xbe, 0x92, 0x85, 0x50, 0x74, 0x0f, 0xe6, 0xd9, 0x1e, 0xa3, 0xe3, 0xa0, 0xd8, 0xb9, 0xec,
+ 0x01, 0x46, 0x22, 0xd9, 0x21, 0xe3, 0x12, 0x9e, 0x84, 0xf0, 0xa5, 0x94, 0xc1, 0x41, 0x13, 0xfd,
+ 0x7f, 0x28, 0xf2, 0xf7, 0x83, 0x20, 0xe7, 0xca, 0x5c, 0xa5, 0xb3, 0x20, 0x9e, 0x00, 0x45, 0xbe,
+ 0xf5, 0x3f, 0x09, 0x58, 0xde, 0xd6, 0x27, 0xbb, 0x44, 0x86, 0x0d, 0x62, 0x62, 0x62, 0x50, 0xd7,
+ 0x44, 0xdd, 0x68, 0xb8, 0xb9, 0xe4, 0x45, 0x31, 0x4e, 0x38, 0x3e, 0xea, 0x04, 0x05, 0x58, 0x32,
+ 0x52, 0x80, 0x2d, 0x43, 0xc6, 0xa1, 0x8e, 0x41, 0x64, 0x2c, 0x12, 0x0d, 0xd5, 0x8a, 0x86, 0x9a,
+ 0x52, 0xf8, 0xd8, 0xc7, 0x9f, 0xea, 0xda, 0xd4, 0x0f, 0x7b, 0x43, 0x9f, 0x41, 0xa9, 0xd7, 0xac,
+ 0xe3, 0x66, 0xbf, 0xd6, 0xf9, 0xa1, 0xd6, 0xab, 0x6e, 0xf5, 0xaa, 0xeb, 0x77, 0xb4, 0x6e, 0x67,
+ 0xeb, 0xf3, 0xbb, 0xf7, 0xee, 0x7c, 0xa0, 0x24, 0x4a, 0xe5, 0xe3, 0x93, 0xf2, 0xad, 0x76, 0xb5,
+ 0xbe, 0x25, 0x76, 0xcc, 0x2e, 0x7d, 0xd6, 0xd3, 0x6d, 0x4f, 0x5f, 0xbf, 0xd3, 0xa5, 0xf6, 0x84,
+ 0x61, 0xd8, 0xb2, 0x2e, 0x46, 0xcf, 0xab, 0xe8, 0x31, 0x9c, 0xb8, 0xf0, 0x18, 0x9e, 0x9e, 0xe6,
+ 0xc9, 0x0b, 0x4e, 0xf3, 0x0d, 0x58, 0x36, 0x5c, 0xea, 0x79, 0x1a, 0xcb, 0xfe, 0x89, 0x79, 0xae,
+ 0xbe, 0xf8, 0xce, 0xd9, 0xe9, 0xda, 0xb5, 0x3a, 0xe3, 0xf7, 0x38, 0x5b, 0xaa, 0xbf, 0x66, 0x44,
+ 0x48, 0xbc, 0x27, 0xf5, 0xf7, 0x53, 0x2c, 0x91, 0xb2, 0x0e, 0x2d, 0x9b, 0x0c, 0x88, 0x87, 0x9e,
+ 0xc0, 0x92, 0xe1, 0x12, 0x93, 0xa5, 0xf5, 0xba, 0xad, 0x79, 0x23, 0x62, 0xc8, 0x45, 0xfd, 0xff,
+ 0x62, 0x73, 0x9a, 0x50, 0xb0, 0x52, 0x0f, 0xa5, 0x7a, 0x23, 0x62, 0xe0, 0x45, 0x63, 0xa6, 0x8d,
+ 0xbe, 0x80, 0x25, 0x8f, 0xd8, 0x96, 0x33, 0x7e, 0xa6, 0x19, 0xd4, 0xf1, 0xc9, 0xb3, 0xe0, 0xdd,
+ 0xea, 0x2a, 0xbd, 0xbd, 0xe6, 0x16, 0x93, 0xaa, 0x0b, 0xa1, 0x1a, 0x3a, 0x3b, 0x5d, 0x5b, 0x9c,
+ 0xa5, 0xe1, 0x45, 0xa9, 0x59, 0xb6, 0x4b, 0x6d, 0x58, 0x9c, 0xb5, 0x06, 0x2d, 0xcb, 0xbd, 0xcf,
+ 0x43, 0x48, 0xb0, 0xb7, 0xd1, 0x2d, 0xc8, 0xb9, 0x64, 0x60, 0x79, 0xbe, 0x2b, 0xdc, 0xcc, 0x38,
+ 0x21, 0x85, 0xed, 0x7c, 0xf1, 0x53, 0x9c, 0xd2, 0xaf, 0xc0, 0xb9, 0x1e, 0xd9, 0x66, 0x31, 0x2d,
+ 0x4f, 0xdf, 0x95, 0x2a, 0x73, 0x38, 0x68, 0xb2, 0x35, 0x38, 0xf6, 0xc2, 0x44, 0x8d, 0x7f, 0x33,
+ 0x1a, 0xcf, 0x28, 0xe4, 0x0f, 0x93, 0x78, 0xce, 0x10, 0xfc, 0xc2, 0x31, 0x1d, 0xf9, 0x85, 0xe3,
+ 0x32, 0x64, 0x6c, 0x72, 0x48, 0x6c, 0x71, 0x96, 0x63, 0xd1, 0x78, 0xe7, 0x67, 0x29, 0xc8, 0x87,
+ 0x6f, 0x34, 0xec, 0x24, 0x68, 0x37, 0x9f, 0x06, 0x6b, 0x35, 0xa4, 0xb7, 0xc9, 0x11, 0x7a, 0x6d,
+ 0x7a, 0xa7, 0xf4, 0x99, 0x78, 0x94, 0x0e, 0xd9, 0xc1, 0x7d, 0xd2, 0x1b, 0x90, 0xab, 0xf6, 0x7a,
+ 0xad, 0x47, 0xed, 0x66, 0x43, 0xf9, 0x32, 0x51, 0xfa, 0xce, 0xf1, 0x49, 0xf9, 0x5a, 0x08, 0xaa,
+ 0x7a, 0x62, 0x29, 0x71, 0x54, 0xbd, 0xde, 0xec, 0xf6, 0x9b, 0x0d, 0xe5, 0x79, 0xf2, 0x3c, 0x8a,
+ 0xdf, 0x91, 0xf0, 0x9f, 0x96, 0xe4, 0xbb, 0xb8, 0xd9, 0xad, 0x62, 0xd6, 0xe1, 0x97, 0x49, 0x71,
+ 0xd5, 0x35, 0xed, 0xd1, 0x25, 0x23, 0x9d, 0xff, 0xae, 0x78, 0x35, 0xf8, 0x89, 0xd5, 0xf3, 0x94,
+ 0xf8, 0xf9, 0xc1, 0xf4, 0xc1, 0x89, 0xe8, 0xe6, 0x84, 0xf5, 0xc6, 0x5f, 0xfa, 0xb8, 0x9a, 0xd4,
+ 0xb9, 0xde, 0x7a, 0x2c, 0x92, 0x30, 0x2d, 0x2a, 0xcc, 0xe3, 0x9d, 0x76, 0x9b, 0x81, 0x9e, 0xa7,
+ 0xcf, 0x8d, 0x0e, 0x8f, 0x1d, 0x56, 0xff, 0xa2, 0xdb, 0x90, 0x0b, 0x1e, 0x02, 0x95, 0x2f, 0xd3,
+ 0xe7, 0x0c, 0xaa, 0x07, 0xaf, 0x98, 0xbc, 0xc3, 0xcd, 0x9d, 0x3e, 0xff, 0x05, 0xd8, 0xf3, 0xcc,
+ 0xf9, 0x0e, 0xf7, 0xc7, 0xbe, 0x49, 0x8f, 0x1c, 0xb6, 0x03, 0xe5, 0xad, 0xda, 0x97, 0x19, 0x71,
+ 0x05, 0x11, 0x62, 0xe4, 0x95, 0xda, 0x1b, 0x90, 0xc3, 0xcd, 0x1f, 0x88, 0x1f, 0x8b, 0x3d, 0xcf,
+ 0x9e, 0xd3, 0x83, 0xc9, 0x17, 0xc4, 0x90, 0xbd, 0x75, 0x70, 0x77, 0xb3, 0xca, 0x5d, 0x7e, 0x1e,
+ 0xd5, 0x71, 0x47, 0xfb, 0xba, 0x43, 0xcc, 0xe9, 0x6f, 0x30, 0x42, 0xd6, 0x3b, 0xbf, 0x08, 0xb9,
+ 0x20, 0xcf, 0x44, 0xab, 0x90, 0x7d, 0xda, 0xc1, 0x8f, 0x9b, 0x58, 0x99, 0x13, 0x3e, 0x0c, 0x38,
+ 0x4f, 0x45, 0x85, 0x50, 0x86, 0xf9, 0xed, 0x6a, 0xbb, 0xfa, 0xa8, 0x89, 0x83, 0x0b, 0xef, 0x00,
+ 0x20, 0x93, 0xa5, 0x92, 0x22, 0x3b, 0x08, 0x75, 0xd6, 0x56, 0xbe, 0xfa, 0x7a, 0x75, 0xee, 0xa7,
+ 0x5f, 0xaf, 0xce, 0x3d, 0x3f, 0x5b, 0x4d, 0x7c, 0x75, 0xb6, 0x9a, 0xf8, 0xc9, 0xd9, 0x6a, 0xe2,
+ 0x5f, 0xcf, 0x56, 0x13, 0xbb, 0x59, 0x1e, 0xd2, 0xef, 0xfd, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff,
+ 0xdb, 0x9d, 0xe2, 0x3d, 0xd2, 0x2f, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/types.proto b/vendor/github.com/docker/swarmkit/api/types.proto
new file mode 100644
index 0000000..201bc35
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/types.proto
@@ -0,0 +1,1022 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "google/protobuf/timestamp.proto";
+import "google/protobuf/duration.proto";
+import "gogoproto/gogo.proto";
+
+// This file contains types that are common to objects and spec or that are not
+// considered first-class within the cluster object-model.
+
+// Version tracks the last time an object in the store was updated.
+message Version {
+ uint64 index = 1;
+}
+
+message IndexEntry {
+ string key = 1;
+ string val = 2;
+}
+
+// Annotations provide useful information to identify API objects. They are
+// common to all API specs.
+message Annotations {
+ string name = 1;
+ map<string, string> labels = 2;
+
+ // Indices provides keys and values for indexing this object.
+ // A single key may have multiple values.
+ repeated IndexEntry indices = 4 [(gogoproto.nullable) = false];
+}
+
+message GenericString {
+ string kind = 1;
+ string value = 2;
+}
+
+message GenericDiscrete {
+ string kind = 1;
+ int64 value = 2;
+}
+
+message GenericResource {
+ oneof resource {
+ GenericString str = 1;
+ GenericDiscrete discrete = 2;
+ }
+}
+
+message Resources {
+ // Amount of CPUs (e.g. 2000000000 = 2 CPU cores)
+ int64 nano_cpus = 1 [(gogoproto.customname) = "NanoCPUs"];
+
+ // Amount of memory in bytes.
+ int64 memory_bytes = 2;
+
+ // User specified resource (e.g: bananas=2;apple={red,yellow,green})
+ repeated GenericResource generic = 3;
+}
+
+message ResourceRequirements {
+ Resources limits = 1;
+ Resources reservations = 2;
+}
+
+message Platform {
+ // Architecture (e.g. x86_64)
+ string architecture = 1;
+
+ // Operating System (e.g. linux)
+ string os = 2 [(gogoproto.customname) = "OS"];
+}
+
+// PluginDescription describes an engine plugin.
+message PluginDescription {
+ // Type of plugin. Canonical values for existing types are
+ // Volume, Network, and Authorization. More types could be
+ // supported in the future.
+ string type = 1;
+
+ // Name of the plugin
+ string name = 2;
+}
+
+message EngineDescription {
+ // Docker daemon version running on the node.
+ string engine_version = 1;
+
+ // Labels attached to the engine.
+ map<string, string> labels = 2;
+
+ // Volume, Network, and Auth plugins
+ repeated PluginDescription plugins = 3 [(gogoproto.nullable) = false];
+}
+
+message NodeDescription {
+ // Hostname of the node as reported by the agent.
+ // This is different from spec.meta.name which is user-defined.
+ string hostname = 1;
+
+ // Platform of the node.
+ Platform platform = 2;
+
+ // Total resources on the node.
+ Resources resources = 3;
+
+ // Information about the Docker Engine on the node.
+ EngineDescription engine = 4;
+
+ // Information on the node's TLS setup
+ NodeTLSInfo tls_info = 5 [(gogoproto.customname) = "TLSInfo"];
+}
+
+message NodeTLSInfo {
+ // Information about which root certs the node trusts
+ bytes trust_root = 1;
+
+ // Information about the node's current TLS certificate
+ bytes cert_issuer_subject = 2;
+ bytes cert_issuer_public_key = 3;
+}
+
+message RaftMemberStatus {
+ bool leader = 1;
+
+ enum Reachability {
+ // Unknown indicates that the manager state cannot be resolved
+ UNKNOWN = 0;
+
+ // Unreachable indicates that the node cannot be contacted by other
+ // raft cluster members.
+ UNREACHABLE = 1;
+
+ // Reachable indicates that the node is healthy and reachable
+ // by other members.
+ REACHABLE = 2;
+ }
+
+ Reachability reachability = 2;
+ string message = 3;
+}
+
+message NodeStatus {
+ // TODO(aluzzardi) These should be using `gogoproto.enumvalue_customname`.
+ enum State {
+ // Unknown indicates the node state cannot be resolved.
+ UNKNOWN = 0;
+
+ // Down indicates the node is down.
+ DOWN = 1;
+
+ // Ready indicates the node is ready to accept tasks.
+ READY = 2;
+
+ // Disconnected indicates the node is currently trying to find new manager.
+ DISCONNECTED = 3;
+ }
+
+ State state = 1;
+ string message = 2;
+ // Addr is the node's IP address as observed by the manager
+ string addr = 3;
+}
+
+message Image {
+ // reference is a docker image reference. This can include a rpository, tag
+ // or be fully qualified witha digest. The format is specified in the
+ // distribution/reference package.
+ string reference = 1;
+}
+
+// Mount describes volume mounts for a container.
+//
+// The Mount type follows the structure of the mount syscall, including a type,
+// source, target. Top-level flags, such as writable, are common to all kinds
+// of mounts, where we also provide options that are specific to a type of
+// mount. This corresponds to flags and data, respectively, in the syscall.
+message Mount {
+ enum Type {
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "MountType";
+
+ BIND = 0 [(gogoproto.enumvalue_customname) = "MountTypeBind"]; // Bind mount host dir
+ VOLUME = 1 [(gogoproto.enumvalue_customname) = "MountTypeVolume"]; // Remote storage volumes
+ TMPFS = 2 [(gogoproto.enumvalue_customname) = "MountTypeTmpfs"]; // Mount a tmpfs
+ }
+
+ // Type defines the nature of the mount.
+ Type type = 1;
+
+ // Source specifies the name of the mount. Depending on mount type, this
+ // may be a volume name or a host path, or even ignored.
+ string source = 2;
+
+ // Target path in container
+ string target = 3;
+
+ // ReadOnly should be set to true if the mount should not be writable.
+ bool readonly = 4 [(gogoproto.customname) = "ReadOnly"];
+
+ // BindOptions specifies options that are specific to a bind mount.
+ message BindOptions {
+ enum Propagation {
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "MountPropagation";
+
+ RPRIVATE = 0 [(gogoproto.enumvalue_customname) = "MountPropagationRPrivate"];
+ PRIVATE = 1 [(gogoproto.enumvalue_customname) = "MountPropagationPrivate"];
+ RSHARED = 2 [(gogoproto.enumvalue_customname) = "MountPropagationRShared"];
+ SHARED = 3 [(gogoproto.enumvalue_customname) = "MountPropagationShared"];
+ RSLAVE = 4 [(gogoproto.enumvalue_customname) = "MountPropagationRSlave"];
+ SLAVE = 5 [(gogoproto.enumvalue_customname) = "MountPropagationSlave"];
+ }
+
+ // Propagation mode of mount.
+ Propagation propagation = 1;
+ }
+
+ // VolumeOptions contains parameters for mounting the volume.
+ message VolumeOptions {
+ // nocopy prevents automatic copying of data to the volume with data from target
+ bool nocopy = 1 [(gogoproto.customname) = "NoCopy"];
+
+ // labels to apply to the volume if creating
+ map<string, string> labels = 2;
+
+ // DriverConfig specifies the options that may be passed to the driver
+ // if the volume is created.
+ //
+ // If this is empty, no volume will be created if the volume is missing.
+ Driver driver_config = 3;
+ }
+
+ message TmpfsOptions {
+ // Size sets the size of the tmpfs, in bytes.
+ //
+ // This will be converted to an operating system specific value
+ // depending on the host. For example, on linux, it will be convered to
+ // use a 'k', 'm' or 'g' syntax. BSD, though not widely supported with
+ // docker, uses a straight byte value.
+ //
+ // Percentages are not supported.
+ int64 size_bytes = 1;
+
+ // Mode of the tmpfs upon creation
+ uint32 mode = 2 [(gogoproto.customtype) = "os.FileMode", (gogoproto.nullable) = false];
+
+ // TODO(stevvooe): There are several more tmpfs flags, specified in the
+ // daemon, that are accepted. Only the most basic are added for now.
+ //
+ // From docker/docker/pkg/mount/flags.go:
+ //
+ // var validFlags = map[string]bool{
+ // "": true,
+ // "size": true, X
+ // "mode": true, X
+ // "uid": true,
+ // "gid": true,
+ // "nr_inodes": true,
+ // "nr_blocks": true,
+ // "mpol": true,
+ // }
+ //
+ // Some of these may be straightforward to add, but others, such as
+ // uid/gid have implications in a clustered system.
+ }
+
+ // Depending on type, one of bind_options or volumes_options will be set.
+
+ // BindOptions configures properties of a bind mount type.
+ //
+ // For mounts of type bind, the source must be an absolute host path.
+ BindOptions bind_options = 5;
+
+ // VolumeOptions configures the properties specific to a volume mount type.
+ //
+ // For mounts of type volume, the source will be used as the volume name.
+ VolumeOptions volume_options = 6;
+
+ // TmpfsOptions allows one to set options for mounting a temporary
+ // filesystem.
+ //
+ // The source field will be ignored when using mounts of type tmpfs.
+ TmpfsOptions tmpfs_options = 7;
+
+ // TODO(stevvooe): It be better to use a oneof field above, although the
+ // type is enough to make the decision, while being primary to the
+ // datastructure.
+}
+
+message RestartPolicy {
+ enum RestartCondition {
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "RestartCondition";
+ NONE = 0 [(gogoproto.enumvalue_customname) = "RestartOnNone"];
+ ON_FAILURE = 1 [(gogoproto.enumvalue_customname) = "RestartOnFailure"];
+ ANY = 2 [(gogoproto.enumvalue_customname) = "RestartOnAny"];
+ }
+
+ RestartCondition condition = 1;
+
+ // Delay between restart attempts
+ // Note: can't use stdduration because this field needs to be nullable.
+ google.protobuf.Duration delay = 2;
+
+ // MaxAttempts is the maximum number of restarts to attempt on an
+ // instance before giving up. Ignored if 0.
+ uint64 max_attempts = 3;
+
+ // Window is the time window used to evaluate the restart policy.
+ // The time window is unbounded if this is 0.
+ // Note: can't use stdduration because this field needs to be nullable.
+ google.protobuf.Duration window = 4;
+}
+
+// UpdateConfig specifies the rate and policy of updates.
+// TODO(aluzzardi): Consider making this a oneof with RollingStrategy and LockstepStrategy.
+message UpdateConfig {
+ // Maximum number of tasks to be updated in one iteration.
+ // 0 means unlimited parallelism.
+ uint64 parallelism = 1;
+
+ // Amount of time between updates.
+ google.protobuf.Duration delay = 2 [(gogoproto.stdduration) = true, (gogoproto.nullable) = false];
+
+ enum FailureAction {
+ PAUSE = 0;
+ CONTINUE = 1;
+ ROLLBACK = 2;
+ }
+
+ // FailureAction is the action to take when an update failures.
+ FailureAction failure_action = 3;
+
+ // Monitor indicates how long to monitor a task for failure after it is
+ // created. If the task fails by ending up in one of the states
+ // REJECTED, COMPLETED, or FAILED, within Monitor from its creation,
+ // this counts as a failure. If it fails after Monitor, it does not
+ // count as a failure. If Monitor is unspecified, a default value will
+ // be used.
+ // Note: can't use stdduration because this field needs to be nullable.
+ google.protobuf.Duration monitor = 4;
+
+ // MaxFailureRatio is the fraction of tasks that may fail during
+ // an update before the failure action is invoked. Any task created by
+ // the current update which ends up in one of the states REJECTED,
+ // COMPLETED or FAILED within Monitor from its creation counts as a
+ // failure. The number of failures is divided by the number of tasks
+ // being updated, and if this fraction is greater than
+ // MaxFailureRatio, the failure action is invoked.
+ //
+ // If the failure action is CONTINUE, there is no effect.
+ // If the failure action is PAUSE, no more tasks will be updated until
+ // another update is started.
+ // If the failure action is ROLLBACK, the orchestrator will attempt to
+ // roll back to the previous service spec. If the MaxFailureRatio
+ // threshold is hit during the rollback, the rollback will pause.
+ float max_failure_ratio = 5;
+
+ // UpdateOrder controls the order of operations when rolling out an
+ // updated task. Either the old task is shut down before the new task
+ // is started, or the new task is started before the old task is shut
+ // down.
+ enum UpdateOrder {
+ STOP_FIRST = 0;
+ START_FIRST = 1;
+ }
+
+ UpdateOrder order = 6;
+}
+
+// UpdateStatus is the status of an update in progress.
+message UpdateStatus {
+ enum UpdateState {
+ UNKNOWN = 0;
+ UPDATING = 1;
+ PAUSED = 2;
+ COMPLETED = 3;
+ ROLLBACK_STARTED = 4;
+ ROLLBACK_PAUSED = 5; // if a rollback fails
+ ROLLBACK_COMPLETED = 6;
+ }
+
+ // State is the state of this update. It indicates whether the
+ // update is in progress, completed, paused, rolling back, or
+ // finished rolling back.
+ UpdateState state = 1;
+
+ // StartedAt is the time at which the update was started.
+ // Note: can't use stdtime because this field is nullable.
+ google.protobuf.Timestamp started_at = 2;
+
+ // CompletedAt is the time at which the update completed successfully,
+ // paused, or finished rolling back.
+ // Note: can't use stdtime because this field is nullable.
+ google.protobuf.Timestamp completed_at = 3;
+
+ // TODO(aaronl): Consider adding a timestamp showing when the most
+ // recent task update took place. Currently, this is nontrivial
+ // because each service update kicks off a replacement update, so
+ // updating the service object with a timestamp at every step along
+ // the rolling update would cause the rolling update to be constantly
+ // restarted.
+
+ // Message explains how the update got into its current state. For
+ // example, if the update is paused, it will explain what is preventing
+ // the update from proceeding (typically the failure of a task to start up
+ // when OnFailure is PAUSE).
+ string message = 4;
+}
+
+// TaskState enumerates the states that a task progresses through within an
+// agent. States are designed to be monotonically increasing, such that if two
+// states are seen by a task, the greater of the new represents the true state.
+enum TaskState {
+ // TODO(aluzzardi): Move it back into `TaskStatus` because of the naming
+ // collisions of enums.
+
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "TaskState";
+ NEW = 0 [(gogoproto.enumvalue_customname)="TaskStateNew"];
+ PENDING = 64 [(gogoproto.enumvalue_customname)="TaskStatePending"]; // waiting for scheduling decision
+ ASSIGNED = 192 [(gogoproto.enumvalue_customname)="TaskStateAssigned"];
+ ACCEPTED = 256 [(gogoproto.enumvalue_customname)="TaskStateAccepted"]; // task has been accepted by an agent.
+ PREPARING = 320 [(gogoproto.enumvalue_customname)="TaskStatePreparing"];
+ READY = 384 [(gogoproto.enumvalue_customname)="TaskStateReady"];
+ STARTING = 448 [(gogoproto.enumvalue_customname)="TaskStateStarting"];
+ RUNNING = 512 [(gogoproto.enumvalue_customname)="TaskStateRunning"];
+ COMPLETE = 576 [(gogoproto.enumvalue_customname)="TaskStateCompleted"]; // successful completion of task (not error code, just ran)
+ SHUTDOWN = 640 [(gogoproto.enumvalue_customname)="TaskStateShutdown"]; // orchestrator requested shutdown
+ FAILED = 704 [(gogoproto.enumvalue_customname)="TaskStateFailed"]; // task execution failed with error
+ REJECTED = 768 [(gogoproto.enumvalue_customname)="TaskStateRejected"]; // task could not be executed here.
+ ORPHANED = 832 [(gogoproto.enumvalue_customname)="TaskStateOrphaned"]; // The node on which this task is scheduled is Down for too long
+
+ // NOTE(stevvooe): The state of a task is actually a lamport clock, in that
+ // given two observations, the greater of the two can be considered
+ // correct. To enforce this, we only allow tasks to proceed to a greater
+ // state.
+ //
+ // A byproduct of this design decision is that we must also maintain this
+ // invariant in the protobuf enum values, such that when comparing two
+ // values, the one with the greater value is also the greater state.
+ //
+ // Because we may want to add intervening states a later date, we've left
+ // 64 spaces between each one. This should allow us to make 5 or 6
+ // insertions between each state if we find that we made a mistake and need
+ // another state.
+ //
+ // Remove this message when the states are deemed perfect.
+}
+
+// Container specific status.
+message ContainerStatus {
+ string container_id = 1;
+
+ int32 pid = 2 [(gogoproto.customname) = "PID"];
+ int32 exit_code = 3;
+}
+
+// PortStatus specifies the actual allocated runtime state of a list
+// of port configs.
+message PortStatus {
+ repeated PortConfig ports = 1;
+}
+
+message TaskStatus {
+ // Note: can't use stdtime because this field is nullable.
+ google.protobuf.Timestamp timestamp = 1;
+
+ // State expresses the current state of the task.
+ TaskState state = 2;
+
+ // Message reports a message for the task status. This should provide a
+ // human readable message that can point to how the task actually arrived
+ // at a current state.
+ //
+ // As a convention, we place the a small message here that led to the
+ // current state. For example, if the task is in ready, because it was
+ // prepared, we'd place "prepared" in this field. If we skipped preparation
+ // because the task is prepared, we would put "already prepared" in this
+ // field.
+ string message = 3;
+
+ // Err is set if the task is in an error state.
+ //
+ // The following states should report a companion error:
+ //
+ // FAILED, REJECTED
+ //
+ // TODO(stevvooe) Integrate this field with the error interface.
+ string err = 4;
+
+ // Container status contains container specific status information.
+ oneof runtime_status {
+ ContainerStatus container = 5;
+ }
+
+ // HostPorts provides a list of ports allocated at the host
+ // level.
+ PortStatus port_status = 6;
+}
+
+// NetworkAttachmentConfig specifies how a service should be attached to a particular network.
+//
+// For now, this is a simple struct, but this can include future information
+// instructing Swarm on how this service should work on the particular
+// network.
+message NetworkAttachmentConfig {
+ // Target specifies the target network for attachment. This value must be a
+ // network ID.
+ string target = 1;
+ // Aliases specifies a list of discoverable alternate names for the service on this Target.
+ repeated string aliases = 2;
+ // Addresses specifies a list of ipv4 and ipv6 addresses
+ // preferred. If these addresses are not available then the
+ // attachment might fail.
+ repeated string addresses = 3;
+ // DriverAttachmentOpts is a map of driver attachment options for the network target
+ map<string, string> driver_attachment_opts = 4;
+}
+
+// IPAMConfig specifies parameters for IP Address Management.
+message IPAMConfig {
+ // TODO(stevvooe): It may make more sense to manage IPAM and network
+ // definitions separately. This will allow multiple networks to share IPAM
+ // instances. For now, we will follow the conventions of libnetwork and
+ // specify this as part of the network specification.
+
+ // AddressFamily specifies the network address family that
+ // this IPAMConfig belongs to.
+ enum AddressFamily {
+ UNKNOWN = 0; // satisfy proto3
+ IPV4 = 4;
+ IPV6 = 6;
+ }
+
+ AddressFamily family = 1;
+
+ // Subnet defines a network as a CIDR address (ie network and mask
+ // 192.168.0.1/24).
+ string subnet = 2;
+
+ // Range defines the portion of the subnet to allocate to tasks. This is
+ // defined as a subnet within the primary subnet.
+ string range = 3;
+
+ // Gateway address within the subnet.
+ string gateway = 4;
+
+ // Reserved is a list of address from the master pool that should *not* be
+ // allocated. These addresses may have already been allocated or may be
+ // reserved for another allocation manager.
+ map<string, string> reserved = 5;
+}
+
+// PortConfig specifies an exposed port which can be
+// addressed using the given name. This can be later queried
+// using a service discovery api or a DNS SRV query. The node
+// port specifies a port that can be used to address this
+// service external to the cluster by sending a connection
+// request to this port to any node on the cluster.
+message PortConfig {
+ enum Protocol {
+ option (gogoproto.goproto_enum_prefix) = false;
+
+ TCP = 0 [(gogoproto.enumvalue_customname) = "ProtocolTCP"];
+ UDP = 1 [(gogoproto.enumvalue_customname) = "ProtocolUDP"];
+ }
+
+ // PublishMode controls how ports are published on the swarm.
+ enum PublishMode {
+ option (gogoproto.enum_customname) = "PublishMode";
+ option (gogoproto.goproto_enum_prefix) = false;
+
+ // PublishModeIngress exposes the port across the cluster on all nodes.
+ INGRESS = 0 [(gogoproto.enumvalue_customname) = "PublishModeIngress"];
+
+ // PublishModeHost exposes the port on just the target host. If the
+ // published port is undefined, an ephemeral port will be allocated. If
+ // the published port is defined, the node will attempt to allocate it,
+ // erroring the task if it fails.
+ HOST = 1 [(gogoproto.enumvalue_customname) = "PublishModeHost"];
+ }
+
+ // Name for the port. If provided the port information can
+ // be queried using the name as in a DNS SRV query.
+ string name = 1;
+
+ // Protocol for the port which is exposed.
+ Protocol protocol = 2;
+
+ // The port which the application is exposing and is bound to.
+ uint32 target_port = 3;
+
+ // PublishedPort specifies the port on which the service is exposed. If
+ // specified, the port must be within the available range. If not specified
+ // (value is zero), an available port is automatically assigned.
+ uint32 published_port = 4;
+
+ // PublishMode controls how the port is published.
+ PublishMode publish_mode = 5;
+}
+
+// Driver is a generic driver type to be used throughout the API. For now, a
+// driver is simply a name and set of options. The field contents depend on the
+// target use case and driver application. For example, a network driver may
+// have different rules than a volume driver.
+message Driver {
+ string name = 1;
+ map <string, string> options = 2;
+}
+
+message IPAMOptions {
+ Driver driver = 1;
+ repeated IPAMConfig configs = 3;
+}
+
+// Peer should be used anywhere where we are describing a remote peer.
+message Peer {
+ string node_id = 1;
+ string addr = 2;
+}
+
+// WeightedPeer should be used anywhere where we are describing a remote peer
+// with a weight.
+message WeightedPeer {
+ Peer peer = 1;
+ int64 weight = 2;
+}
+
+
+message IssuanceStatus {
+ enum State {
+ option (gogoproto.goproto_enum_prefix) = false;
+
+ UNKNOWN = 0 [(gogoproto.enumvalue_customname) = "IssuanceStateUnknown"];
+ // A new certificate should be issued
+ RENEW = 1 [(gogoproto.enumvalue_customname)="IssuanceStateRenew"];
+ // Certificate is pending acceptance
+ PENDING = 2 [(gogoproto.enumvalue_customname)="IssuanceStatePending"];
+ // successful completion certificate issuance
+ ISSUED = 3 [(gogoproto.enumvalue_customname)="IssuanceStateIssued"];
+ // Certificate issuance failed
+ FAILED = 4 [(gogoproto.enumvalue_customname)="IssuanceStateFailed"];
+ // Signals workers to renew their certificate. From the CA's perspective
+ // this is equivalent to IssuanceStateIssued: a noop.
+ ROTATE = 5 [(gogoproto.enumvalue_customname)="IssuanceStateRotate"];
+ }
+ State state = 1;
+
+ // Err is set if the Certificate Issuance is in an error state.
+ // The following states should report a companion error:
+ // FAILED
+ string err = 2;
+}
+
+message AcceptancePolicy {
+ message RoleAdmissionPolicy {
+ message Secret {
+ // The actual content (possibly hashed)
+ bytes data = 1;
+ // The type of hash we are using, or "plaintext"
+ string alg = 2;
+ }
+
+ NodeRole role = 1;
+ // Autoaccept controls which roles' certificates are automatically
+ // issued without administrator intervention.
+ bool autoaccept = 2;
+ // Secret represents a user-provided string that is necessary for new
+ // nodes to join the cluster
+ Secret secret = 3;
+ }
+
+ repeated RoleAdmissionPolicy policies = 1;
+}
+
+message ExternalCA {
+ enum CAProtocol {
+ CFSSL = 0 [(gogoproto.enumvalue_customname) = "CAProtocolCFSSL"];
+ }
+
+ // Protocol is the protocol used by this external CA.
+ CAProtocol protocol = 1;
+
+ // URL is the URL where the external CA can be reached.
+ string url = 2 [(gogoproto.customname) = "URL"];
+
+ // Options is a set of additional key/value pairs whose interpretation
+ // depends on the specified CA type.
+ map<string, string> options = 3;
+
+ // CACert specifies which root CA is used by this external CA
+ bytes ca_cert = 4 [(gogoproto.customname) = "CACert"];
+}
+
+message CAConfig {
+ // NodeCertExpiry is the duration certificates should be issued for
+ // Note: can't use stdduration because this field needs to be nullable.
+ google.protobuf.Duration node_cert_expiry = 1;
+
+ // ExternalCAs is a list of CAs to which a manager node will make
+ // certificate signing requests for node certificates.
+ repeated ExternalCA external_cas = 2 [(gogoproto.customname) = "ExternalCAs"];
+
+ // SigningCACert is the desired CA certificate to be used as the root and
+ // signing CA for the swarm. If not provided, indicates that we are either happy
+ // with the current configuration, or (together with a bump in the ForceRotate value)
+ // that we want a certificate and key generated for us.
+ bytes signing_ca_cert = 3 [(gogoproto.customname) = "SigningCACert"];
+
+ // SigningCAKey is the desired private key, matching the signing CA cert, to be used
+ // to sign certificates for the swarm
+ bytes signing_ca_key = 4 [(gogoproto.customname) = "SigningCAKey"];
+
+ // ForceRotate is a counter that triggers a root CA rotation even if no relevant
+ // parameters have been in the spec. This will force the manager to generate a new
+ // certificate and key, if none have been provided.
+ uint64 force_rotate = 5;
+}
+
+// OrchestrationConfig defines cluster-level orchestration settings.
+message OrchestrationConfig {
+ // TaskHistoryRetentionLimit is the number of historic tasks to keep per instance or
+ // node. If negative, never remove completed or failed tasks.
+ int64 task_history_retention_limit = 1;
+
+}
+
+// TaskDefaults specifies default values for task creation.
+message TaskDefaults {
+ // LogDriver specifies the log driver to use for the cluster if not
+ // specified for each task.
+ //
+ // If this is changed, only new tasks will pick up the new log driver.
+ // Existing tasks will continue to use the previous default until rescheduled.
+ Driver log_driver = 1;
+}
+
+// DispatcherConfig defines cluster-level dispatcher settings.
+message DispatcherConfig {
+ // HeartbeatPeriod defines how often agent should send heartbeats to
+ // dispatcher.
+ // Note: can't use stdduration because this field needs to be nullable.
+ google.protobuf.Duration heartbeat_period = 1;
+}
+
+// RaftConfig defines raft settings for the cluster.
+message RaftConfig {
+ // SnapshotInterval is the number of log entries between snapshots.
+ uint64 snapshot_interval = 1;
+ // KeepOldSnapshots is the number of snapshots to keep beyond the
+ // current snapshot.
+ uint64 keep_old_snapshots = 2;
+ // LogEntriesForSlowFollowers is the number of log entries to keep
+ // around to sync up slow followers after a snapshot is created.
+ uint64 log_entries_for_slow_followers = 3;
+ // HeartbeatTick defines the amount of ticks (in seconds) between
+ // each heartbeat message sent to other members for health-check.
+ uint32 heartbeat_tick = 4;
+ // ElectionTick defines the amount of ticks (in seconds) needed
+ // without a leader to trigger a new election.
+ uint32 election_tick = 5;
+}
+
+message EncryptionConfig {
+ // AutoLockManagers specifies whether or not managers TLS keys and raft data
+ // should be encrypted at rest in such a way that they must be unlocked
+ // before the manager node starts up again.
+ bool auto_lock_managers = 1;
+}
+
+message SpreadOver {
+ string spread_descriptor = 1; // label descriptor, such as engine.labels.az
+ // TODO: support node information beyond engine and node labels
+
+ // TODO: in the future, add a map that provides weights for weighted
+ // spreading.
+}
+
+message PlacementPreference {
+ oneof Preference {
+ SpreadOver spread = 1;
+ }
+}
+
+// Placement specifies task distribution constraints.
+message Placement {
+ // Constraints specifies a set of requirements a node should meet for a task.
+ repeated string constraints = 1;
+
+ // Preferences provide a way to make the scheduler aware of factors
+ // such as topology. They are provided in order from highest to lowest
+ // precedence.
+ repeated PlacementPreference preferences = 2;
+
+ // Platforms stores all the platforms that the image can run on.
+ // This field is used in the platform filter for scheduling. If empty,
+ // then the platform filter is off, meaning there are no scheduling restrictions.
+ repeated Platform platforms = 3;
+}
+
+// JoinToken contains the join tokens for workers and managers.
+message JoinTokens {
+ // Worker is the join token workers may use to join the swarm.
+ string worker = 1;
+
+ // Manager is the join token workers may use to join the swarm.
+ string manager = 2;
+}
+
+message RootCA {
+ // CAKey is the root CA private key.
+ bytes ca_key = 1 [(gogoproto.customname) = "CAKey"];
+
+ // CACert is the root CA certificate.
+ bytes ca_cert = 2 [(gogoproto.customname) = "CACert"];
+
+ // CACertHash is the digest of the CA Certificate.
+ string ca_cert_hash = 3 [(gogoproto.customname) = "CACertHash"];
+
+ // JoinTokens contains the join tokens for workers and managers.
+ JoinTokens join_tokens = 4 [(gogoproto.nullable) = false];
+
+ // RootRotation contains the new root cert and key we want to rotate to - if this is nil, we are not in the
+ // middle of a root rotation
+ RootRotation root_rotation = 5;
+
+ // LastForcedRotation matches the Cluster Spec's CAConfig's ForceRotation counter.
+ // It indicates when the current CA cert and key were generated (or updated).
+ uint64 last_forced_rotation = 6;
+}
+
+
+enum NodeRole {
+ option (gogoproto.enum_customname) = "NodeRole";
+ option (gogoproto.goproto_enum_prefix) = false;
+
+ WORKER = 0 [(gogoproto.enumvalue_customname) = "NodeRoleWorker"];
+ MANAGER = 1 [(gogoproto.enumvalue_customname) = "NodeRoleManager"];
+}
+
+message Certificate {
+ NodeRole role = 1;
+
+ bytes csr = 2 [(gogoproto.customname) = "CSR"];
+
+ IssuanceStatus status = 3 [(gogoproto.nullable) = false];
+
+ bytes certificate = 4;
+
+ // CN represents the node ID.
+ string cn = 5 [(gogoproto.customname) = "CN"];
+}
+
+
+// Symmetric keys to encrypt inter-agent communication.
+message EncryptionKey {
+ // Agent subsystem the key is intended for. Example:
+ // networking:gossip
+ string subsystem = 1;
+
+ // Encryption algorithm that can implemented using this key
+ enum Algorithm {
+ option (gogoproto.goproto_enum_prefix) = false;
+
+ AES_128_GCM = 0;
+ }
+
+ Algorithm algorithm = 2;
+
+ bytes key = 3;
+
+ // Time stamp from the lamport clock of the key allocator to
+ // identify the relative age of the key.
+ uint64 lamport_time = 4;
+}
+
+// ManagerStatus provides informations about the state of a manager in the cluster.
+message ManagerStatus {
+ // RaftID specifies the internal ID used by the manager in a raft context, it can never be modified
+ // and is used only for information purposes
+ uint64 raft_id = 1;
+
+ // Addr is the address advertised to raft.
+ string addr = 2;
+
+ // Leader is set to true if this node is the raft leader.
+ bool leader = 3;
+
+ // Reachability specifies whether this node is reachable.
+ RaftMemberStatus.Reachability reachability = 4;
+}
+
+// FileTarget represents a specific target that is backed by a file
+message FileTarget {
+ // Name represents the final filename in the filesystem
+ string name = 1;
+
+ // UID represents the file UID
+ string uid = 2 [(gogoproto.customname) = "UID"];
+
+ // GID represents the file GID
+ string gid = 3 [(gogoproto.customname) = "GID"];
+
+ // Mode represents the FileMode of the file
+ uint32 mode = 4 [(gogoproto.customtype) = "os.FileMode", (gogoproto.nullable) = false];
+}
+
+// SecretReference is the linkage between a service and a secret that it uses.
+message SecretReference {
+ // SecretID represents the ID of the specific Secret that we're
+ // referencing. This identifier exists so that SecretReferences don't leak
+ // any information about the secret contents.
+ string secret_id = 1;
+
+ // SecretName is the name of the secret that this references, but this is just provided for
+ // lookup/display purposes. The secret in the reference will be identified by its ID.
+ string secret_name = 2;
+
+ // Target specifies how this secret should be exposed to the task.
+ oneof target {
+ FileTarget file = 3;
+ }
+}
+
+// ConfigReference is the linkage between a service and a config that it uses.
+message ConfigReference {
+ // ConfigID represents the ID of the specific Config that we're
+ // referencing.
+ string config_id = 1;
+
+ // ConfigName is the name of the config that this references, but this is just provided for
+ // lookup/display purposes. The config in the reference will be identified by its ID.
+ string config_name = 2;
+
+ // Target specifies how this secret should be exposed to the task.
+ oneof target {
+ FileTarget file = 3;
+ }
+}
+
+// BlacklistedCertificate is a record for a blacklisted certificate. It does not
+// contain the certificate's CN, because these records are indexed by CN.
+message BlacklistedCertificate {
+ // Expiry is the latest known expiration time of a certificate that
+ // was issued for the given CN.
+ // Note: can't use stdtime because this field is nullable.
+ google.protobuf.Timestamp expiry = 1;
+}
+
+// HealthConfig holds configuration settings for the HEALTHCHECK feature.
+message HealthConfig {
+ // Test is the test to perform to check that the container is healthy.
+ // An empty slice means to inherit the default.
+ // The options are:
+ // {} : inherit healthcheck
+ // {"NONE"} : disable healthcheck
+ // {"CMD", args...} : exec arguments directly
+ // {"CMD-SHELL", command} : run command with system's default shell
+ repeated string test = 1;
+
+ // Interval is the time to wait between checks. Zero means inherit.
+ // Note: can't use stdduration because this field needs to be nullable.
+ google.protobuf.Duration interval = 2;
+
+ // Timeout is the time to wait before considering the check to have hung.
+ // Zero means inherit.
+ // Note: can't use stdduration because this field needs to be nullable.
+ google.protobuf.Duration timeout = 3;
+
+ // Retries is the number of consecutive failures needed to consider a
+ // container as unhealthy. Zero means inherit.
+ int32 retries = 4;
+
+ // Start period is the period for container initialization during
+ // which health check failures will note count towards the maximum
+ // number of retries.
+ google.protobuf.Duration start_period = 5;
+}
+
+message MaybeEncryptedRecord {
+ enum Algorithm {
+ NONE = 0 [(gogoproto.enumvalue_customname) = "NotEncrypted"];
+ SECRETBOX_SALSA20_POLY1305 = 1 [(gogoproto.enumvalue_customname) = "NACLSecretboxSalsa20Poly1305"];
+ }
+
+ Algorithm algorithm = 1;
+ bytes data = 2;
+ bytes nonce = 3;
+}
+
+
+message RootRotation {
+ bytes ca_cert = 1 [(gogoproto.customname) = "CACert"];
+ bytes ca_key = 2 [(gogoproto.customname) = "CAKey"];
+ // cross-signed CA cert is the CACert that has been cross-signed by the previous root
+ bytes cross_signed_ca_cert = 3 [(gogoproto.customname) = "CrossSignedCACert"];
+}
+
+// Privileges specifies security configuration/permissions.
+message Privileges {
+ // CredentialSpec for managed service account (Windows only).
+ message CredentialSpec {
+ oneof source {
+ string file = 1;
+ string registry = 2;
+ }
+ }
+ CredentialSpec credential_spec = 1;
+
+ // SELinuxContext contains the SELinux labels for the container.
+ message SELinuxContext {
+ bool disable = 1;
+
+ string user = 2;
+ string role = 3;
+ string type = 4;
+ string level = 5;
+ }
+ SELinuxContext selinux_context = 2 [(gogoproto.customname) = "SELinuxContext"];
+}
diff --git a/vendor/github.com/docker/swarmkit/api/watch.pb.go b/vendor/github.com/docker/swarmkit/api/watch.pb.go
new file mode 100644
index 0000000..db7e80f
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/watch.pb.go
@@ -0,0 +1,4599 @@
+// Code generated by protoc-gen-gogo.
+// source: watch.proto
+// DO NOT EDIT!
+
+package api
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/gogo/protobuf/gogoproto"
+import _ "github.com/docker/swarmkit/protobuf/plugin"
+
+import github_com_docker_swarmkit_api_deepcopy "github.com/docker/swarmkit/api/deepcopy"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+import raftselector "github.com/docker/swarmkit/manager/raftselector"
+import codes "google.golang.org/grpc/codes"
+import metadata "google.golang.org/grpc/metadata"
+import transport "google.golang.org/grpc/transport"
+import rafttime "time"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// WatchActionKind distinguishes between creations, updates, and removals. It
+// is structured as a bitmap so multiple kinds of events can be requested with
+// a mask.
+type WatchActionKind int32
+
+const (
+ WatchActionKindUnknown WatchActionKind = 0
+ WatchActionKindCreate WatchActionKind = 1
+ WatchActionKindUpdate WatchActionKind = 2
+ WatchActionKindRemove WatchActionKind = 4
+)
+
+var WatchActionKind_name = map[int32]string{
+ 0: "WATCH_ACTION_UNKNOWN",
+ 1: "WATCH_ACTION_CREATE",
+ 2: "WATCH_ACTION_UPDATE",
+ 4: "WATCH_ACTION_REMOVE",
+}
+var WatchActionKind_value = map[string]int32{
+ "WATCH_ACTION_UNKNOWN": 0,
+ "WATCH_ACTION_CREATE": 1,
+ "WATCH_ACTION_UPDATE": 2,
+ "WATCH_ACTION_REMOVE": 4,
+}
+
+func (x WatchActionKind) String() string {
+ return proto.EnumName(WatchActionKind_name, int32(x))
+}
+func (WatchActionKind) EnumDescriptor() ([]byte, []int) { return fileDescriptorWatch, []int{0} }
+
+type Object struct {
+ // Types that are valid to be assigned to Object:
+ // *Object_Node
+ // *Object_Service
+ // *Object_Network
+ // *Object_Task
+ // *Object_Cluster
+ // *Object_Secret
+ // *Object_Resource
+ // *Object_Extension
+ // *Object_Config
+ Object isObject_Object `protobuf_oneof:"Object"`
+}
+
+func (m *Object) Reset() { *m = Object{} }
+func (*Object) ProtoMessage() {}
+func (*Object) Descriptor() ([]byte, []int) { return fileDescriptorWatch, []int{0} }
+
+type isObject_Object interface {
+ isObject_Object()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type Object_Node struct {
+ Node *Node `protobuf:"bytes,1,opt,name=node,oneof"`
+}
+type Object_Service struct {
+ Service *Service `protobuf:"bytes,2,opt,name=service,oneof"`
+}
+type Object_Network struct {
+ Network *Network `protobuf:"bytes,3,opt,name=network,oneof"`
+}
+type Object_Task struct {
+ Task *Task `protobuf:"bytes,4,opt,name=task,oneof"`
+}
+type Object_Cluster struct {
+ Cluster *Cluster `protobuf:"bytes,5,opt,name=cluster,oneof"`
+}
+type Object_Secret struct {
+ Secret *Secret `protobuf:"bytes,6,opt,name=secret,oneof"`
+}
+type Object_Resource struct {
+ Resource *Resource `protobuf:"bytes,7,opt,name=resource,oneof"`
+}
+type Object_Extension struct {
+ Extension *Extension `protobuf:"bytes,8,opt,name=extension,oneof"`
+}
+type Object_Config struct {
+ Config *Config `protobuf:"bytes,9,opt,name=config,oneof"`
+}
+
+func (*Object_Node) isObject_Object() {}
+func (*Object_Service) isObject_Object() {}
+func (*Object_Network) isObject_Object() {}
+func (*Object_Task) isObject_Object() {}
+func (*Object_Cluster) isObject_Object() {}
+func (*Object_Secret) isObject_Object() {}
+func (*Object_Resource) isObject_Object() {}
+func (*Object_Extension) isObject_Object() {}
+func (*Object_Config) isObject_Object() {}
+
+func (m *Object) GetObject() isObject_Object {
+ if m != nil {
+ return m.Object
+ }
+ return nil
+}
+
+func (m *Object) GetNode() *Node {
+ if x, ok := m.GetObject().(*Object_Node); ok {
+ return x.Node
+ }
+ return nil
+}
+
+func (m *Object) GetService() *Service {
+ if x, ok := m.GetObject().(*Object_Service); ok {
+ return x.Service
+ }
+ return nil
+}
+
+func (m *Object) GetNetwork() *Network {
+ if x, ok := m.GetObject().(*Object_Network); ok {
+ return x.Network
+ }
+ return nil
+}
+
+func (m *Object) GetTask() *Task {
+ if x, ok := m.GetObject().(*Object_Task); ok {
+ return x.Task
+ }
+ return nil
+}
+
+func (m *Object) GetCluster() *Cluster {
+ if x, ok := m.GetObject().(*Object_Cluster); ok {
+ return x.Cluster
+ }
+ return nil
+}
+
+func (m *Object) GetSecret() *Secret {
+ if x, ok := m.GetObject().(*Object_Secret); ok {
+ return x.Secret
+ }
+ return nil
+}
+
+func (m *Object) GetResource() *Resource {
+ if x, ok := m.GetObject().(*Object_Resource); ok {
+ return x.Resource
+ }
+ return nil
+}
+
+func (m *Object) GetExtension() *Extension {
+ if x, ok := m.GetObject().(*Object_Extension); ok {
+ return x.Extension
+ }
+ return nil
+}
+
+func (m *Object) GetConfig() *Config {
+ if x, ok := m.GetObject().(*Object_Config); ok {
+ return x.Config
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Object) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Object_OneofMarshaler, _Object_OneofUnmarshaler, _Object_OneofSizer, []interface{}{
+ (*Object_Node)(nil),
+ (*Object_Service)(nil),
+ (*Object_Network)(nil),
+ (*Object_Task)(nil),
+ (*Object_Cluster)(nil),
+ (*Object_Secret)(nil),
+ (*Object_Resource)(nil),
+ (*Object_Extension)(nil),
+ (*Object_Config)(nil),
+ }
+}
+
+func _Object_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Object)
+ // Object
+ switch x := m.Object.(type) {
+ case *Object_Node:
+ _ = b.EncodeVarint(1<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Node); err != nil {
+ return err
+ }
+ case *Object_Service:
+ _ = b.EncodeVarint(2<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Service); err != nil {
+ return err
+ }
+ case *Object_Network:
+ _ = b.EncodeVarint(3<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Network); err != nil {
+ return err
+ }
+ case *Object_Task:
+ _ = b.EncodeVarint(4<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Task); err != nil {
+ return err
+ }
+ case *Object_Cluster:
+ _ = b.EncodeVarint(5<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Cluster); err != nil {
+ return err
+ }
+ case *Object_Secret:
+ _ = b.EncodeVarint(6<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Secret); err != nil {
+ return err
+ }
+ case *Object_Resource:
+ _ = b.EncodeVarint(7<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Resource); err != nil {
+ return err
+ }
+ case *Object_Extension:
+ _ = b.EncodeVarint(8<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Extension); err != nil {
+ return err
+ }
+ case *Object_Config:
+ _ = b.EncodeVarint(9<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Config); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("Object.Object has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Object_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Object)
+ switch tag {
+ case 1: // Object.node
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Node)
+ err := b.DecodeMessage(msg)
+ m.Object = &Object_Node{msg}
+ return true, err
+ case 2: // Object.service
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Service)
+ err := b.DecodeMessage(msg)
+ m.Object = &Object_Service{msg}
+ return true, err
+ case 3: // Object.network
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Network)
+ err := b.DecodeMessage(msg)
+ m.Object = &Object_Network{msg}
+ return true, err
+ case 4: // Object.task
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Task)
+ err := b.DecodeMessage(msg)
+ m.Object = &Object_Task{msg}
+ return true, err
+ case 5: // Object.cluster
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Cluster)
+ err := b.DecodeMessage(msg)
+ m.Object = &Object_Cluster{msg}
+ return true, err
+ case 6: // Object.secret
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Secret)
+ err := b.DecodeMessage(msg)
+ m.Object = &Object_Secret{msg}
+ return true, err
+ case 7: // Object.resource
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Resource)
+ err := b.DecodeMessage(msg)
+ m.Object = &Object_Resource{msg}
+ return true, err
+ case 8: // Object.extension
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Extension)
+ err := b.DecodeMessage(msg)
+ m.Object = &Object_Extension{msg}
+ return true, err
+ case 9: // Object.config
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Config)
+ err := b.DecodeMessage(msg)
+ m.Object = &Object_Config{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Object_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Object)
+ // Object
+ switch x := m.Object.(type) {
+ case *Object_Node:
+ s := proto.Size(x.Node)
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Object_Service:
+ s := proto.Size(x.Service)
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Object_Network:
+ s := proto.Size(x.Network)
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Object_Task:
+ s := proto.Size(x.Task)
+ n += proto.SizeVarint(4<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Object_Cluster:
+ s := proto.Size(x.Cluster)
+ n += proto.SizeVarint(5<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Object_Secret:
+ s := proto.Size(x.Secret)
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Object_Resource:
+ s := proto.Size(x.Resource)
+ n += proto.SizeVarint(7<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Object_Extension:
+ s := proto.Size(x.Extension)
+ n += proto.SizeVarint(8<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Object_Config:
+ s := proto.Size(x.Config)
+ n += proto.SizeVarint(9<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// FIXME(aaronl): These messages should ideally be embedded in SelectBy, but
+// protoc generates bad code for that.
+type SelectBySlot struct {
+ ServiceID string `protobuf:"bytes,1,opt,name=service_id,json=serviceId,proto3" json:"service_id,omitempty"`
+ Slot uint64 `protobuf:"varint,2,opt,name=slot,proto3" json:"slot,omitempty"`
+}
+
+func (m *SelectBySlot) Reset() { *m = SelectBySlot{} }
+func (*SelectBySlot) ProtoMessage() {}
+func (*SelectBySlot) Descriptor() ([]byte, []int) { return fileDescriptorWatch, []int{1} }
+
+type SelectByCustom struct {
+ Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
+ Index string `protobuf:"bytes,2,opt,name=index,proto3" json:"index,omitempty"`
+ Value string `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *SelectByCustom) Reset() { *m = SelectByCustom{} }
+func (*SelectByCustom) ProtoMessage() {}
+func (*SelectByCustom) Descriptor() ([]byte, []int) { return fileDescriptorWatch, []int{2} }
+
+type SelectBy struct {
+ // TODO(aaronl): Are all of these things we want to expose in
+ // the API? Exposing them may commit us to maintaining those
+ // internal indices going forward.
+ //
+ // Types that are valid to be assigned to By:
+ // *SelectBy_ID
+ // *SelectBy_IDPrefix
+ // *SelectBy_Name
+ // *SelectBy_NamePrefix
+ // *SelectBy_Custom
+ // *SelectBy_CustomPrefix
+ // *SelectBy_ServiceID
+ // *SelectBy_NodeID
+ // *SelectBy_Slot
+ // *SelectBy_DesiredState
+ // *SelectBy_Role
+ // *SelectBy_Membership
+ // *SelectBy_ReferencedNetworkID
+ // *SelectBy_ReferencedSecretID
+ // *SelectBy_ReferencedConfigID
+ // *SelectBy_Kind
+ By isSelectBy_By `protobuf_oneof:"By"`
+}
+
+func (m *SelectBy) Reset() { *m = SelectBy{} }
+func (*SelectBy) ProtoMessage() {}
+func (*SelectBy) Descriptor() ([]byte, []int) { return fileDescriptorWatch, []int{3} }
+
+type isSelectBy_By interface {
+ isSelectBy_By()
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type SelectBy_ID struct {
+ ID string `protobuf:"bytes,1,opt,name=id,proto3,oneof"`
+}
+type SelectBy_IDPrefix struct {
+ IDPrefix string `protobuf:"bytes,2,opt,name=id_prefix,json=idPrefix,proto3,oneof"`
+}
+type SelectBy_Name struct {
+ Name string `protobuf:"bytes,3,opt,name=name,proto3,oneof"`
+}
+type SelectBy_NamePrefix struct {
+ NamePrefix string `protobuf:"bytes,4,opt,name=name_prefix,json=namePrefix,proto3,oneof"`
+}
+type SelectBy_Custom struct {
+ Custom *SelectByCustom `protobuf:"bytes,5,opt,name=custom,oneof"`
+}
+type SelectBy_CustomPrefix struct {
+ CustomPrefix *SelectByCustom `protobuf:"bytes,6,opt,name=custom_prefix,json=customPrefix,oneof"`
+}
+type SelectBy_ServiceID struct {
+ ServiceID string `protobuf:"bytes,7,opt,name=service_id,json=serviceId,proto3,oneof"`
+}
+type SelectBy_NodeID struct {
+ NodeID string `protobuf:"bytes,8,opt,name=node_id,json=nodeId,proto3,oneof"`
+}
+type SelectBy_Slot struct {
+ Slot *SelectBySlot `protobuf:"bytes,9,opt,name=slot,oneof"`
+}
+type SelectBy_DesiredState struct {
+ DesiredState TaskState `protobuf:"varint,10,opt,name=desired_state,json=desiredState,proto3,enum=docker.swarmkit.v1.TaskState,oneof"`
+}
+type SelectBy_Role struct {
+ Role NodeRole `protobuf:"varint,11,opt,name=role,proto3,enum=docker.swarmkit.v1.NodeRole,oneof"`
+}
+type SelectBy_Membership struct {
+ Membership NodeSpec_Membership `protobuf:"varint,12,opt,name=membership,proto3,enum=docker.swarmkit.v1.NodeSpec_Membership,oneof"`
+}
+type SelectBy_ReferencedNetworkID struct {
+ ReferencedNetworkID string `protobuf:"bytes,13,opt,name=referenced_network_id,json=referencedNetworkId,proto3,oneof"`
+}
+type SelectBy_ReferencedSecretID struct {
+ ReferencedSecretID string `protobuf:"bytes,14,opt,name=referenced_secret_id,json=referencedSecretId,proto3,oneof"`
+}
+type SelectBy_ReferencedConfigID struct {
+ ReferencedConfigID string `protobuf:"bytes,16,opt,name=referenced_config_id,json=referencedConfigId,proto3,oneof"`
+}
+type SelectBy_Kind struct {
+ Kind string `protobuf:"bytes,15,opt,name=kind,proto3,oneof"`
+}
+
+func (*SelectBy_ID) isSelectBy_By() {}
+func (*SelectBy_IDPrefix) isSelectBy_By() {}
+func (*SelectBy_Name) isSelectBy_By() {}
+func (*SelectBy_NamePrefix) isSelectBy_By() {}
+func (*SelectBy_Custom) isSelectBy_By() {}
+func (*SelectBy_CustomPrefix) isSelectBy_By() {}
+func (*SelectBy_ServiceID) isSelectBy_By() {}
+func (*SelectBy_NodeID) isSelectBy_By() {}
+func (*SelectBy_Slot) isSelectBy_By() {}
+func (*SelectBy_DesiredState) isSelectBy_By() {}
+func (*SelectBy_Role) isSelectBy_By() {}
+func (*SelectBy_Membership) isSelectBy_By() {}
+func (*SelectBy_ReferencedNetworkID) isSelectBy_By() {}
+func (*SelectBy_ReferencedSecretID) isSelectBy_By() {}
+func (*SelectBy_ReferencedConfigID) isSelectBy_By() {}
+func (*SelectBy_Kind) isSelectBy_By() {}
+
+func (m *SelectBy) GetBy() isSelectBy_By {
+ if m != nil {
+ return m.By
+ }
+ return nil
+}
+
+func (m *SelectBy) GetID() string {
+ if x, ok := m.GetBy().(*SelectBy_ID); ok {
+ return x.ID
+ }
+ return ""
+}
+
+func (m *SelectBy) GetIDPrefix() string {
+ if x, ok := m.GetBy().(*SelectBy_IDPrefix); ok {
+ return x.IDPrefix
+ }
+ return ""
+}
+
+func (m *SelectBy) GetName() string {
+ if x, ok := m.GetBy().(*SelectBy_Name); ok {
+ return x.Name
+ }
+ return ""
+}
+
+func (m *SelectBy) GetNamePrefix() string {
+ if x, ok := m.GetBy().(*SelectBy_NamePrefix); ok {
+ return x.NamePrefix
+ }
+ return ""
+}
+
+func (m *SelectBy) GetCustom() *SelectByCustom {
+ if x, ok := m.GetBy().(*SelectBy_Custom); ok {
+ return x.Custom
+ }
+ return nil
+}
+
+func (m *SelectBy) GetCustomPrefix() *SelectByCustom {
+ if x, ok := m.GetBy().(*SelectBy_CustomPrefix); ok {
+ return x.CustomPrefix
+ }
+ return nil
+}
+
+func (m *SelectBy) GetServiceID() string {
+ if x, ok := m.GetBy().(*SelectBy_ServiceID); ok {
+ return x.ServiceID
+ }
+ return ""
+}
+
+func (m *SelectBy) GetNodeID() string {
+ if x, ok := m.GetBy().(*SelectBy_NodeID); ok {
+ return x.NodeID
+ }
+ return ""
+}
+
+func (m *SelectBy) GetSlot() *SelectBySlot {
+ if x, ok := m.GetBy().(*SelectBy_Slot); ok {
+ return x.Slot
+ }
+ return nil
+}
+
+func (m *SelectBy) GetDesiredState() TaskState {
+ if x, ok := m.GetBy().(*SelectBy_DesiredState); ok {
+ return x.DesiredState
+ }
+ return TaskStateNew
+}
+
+func (m *SelectBy) GetRole() NodeRole {
+ if x, ok := m.GetBy().(*SelectBy_Role); ok {
+ return x.Role
+ }
+ return NodeRoleWorker
+}
+
+func (m *SelectBy) GetMembership() NodeSpec_Membership {
+ if x, ok := m.GetBy().(*SelectBy_Membership); ok {
+ return x.Membership
+ }
+ return NodeMembershipPending
+}
+
+func (m *SelectBy) GetReferencedNetworkID() string {
+ if x, ok := m.GetBy().(*SelectBy_ReferencedNetworkID); ok {
+ return x.ReferencedNetworkID
+ }
+ return ""
+}
+
+func (m *SelectBy) GetReferencedSecretID() string {
+ if x, ok := m.GetBy().(*SelectBy_ReferencedSecretID); ok {
+ return x.ReferencedSecretID
+ }
+ return ""
+}
+
+func (m *SelectBy) GetReferencedConfigID() string {
+ if x, ok := m.GetBy().(*SelectBy_ReferencedConfigID); ok {
+ return x.ReferencedConfigID
+ }
+ return ""
+}
+
+func (m *SelectBy) GetKind() string {
+ if x, ok := m.GetBy().(*SelectBy_Kind); ok {
+ return x.Kind
+ }
+ return ""
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*SelectBy) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _SelectBy_OneofMarshaler, _SelectBy_OneofUnmarshaler, _SelectBy_OneofSizer, []interface{}{
+ (*SelectBy_ID)(nil),
+ (*SelectBy_IDPrefix)(nil),
+ (*SelectBy_Name)(nil),
+ (*SelectBy_NamePrefix)(nil),
+ (*SelectBy_Custom)(nil),
+ (*SelectBy_CustomPrefix)(nil),
+ (*SelectBy_ServiceID)(nil),
+ (*SelectBy_NodeID)(nil),
+ (*SelectBy_Slot)(nil),
+ (*SelectBy_DesiredState)(nil),
+ (*SelectBy_Role)(nil),
+ (*SelectBy_Membership)(nil),
+ (*SelectBy_ReferencedNetworkID)(nil),
+ (*SelectBy_ReferencedSecretID)(nil),
+ (*SelectBy_ReferencedConfigID)(nil),
+ (*SelectBy_Kind)(nil),
+ }
+}
+
+func _SelectBy_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*SelectBy)
+ // By
+ switch x := m.By.(type) {
+ case *SelectBy_ID:
+ _ = b.EncodeVarint(1<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.ID)
+ case *SelectBy_IDPrefix:
+ _ = b.EncodeVarint(2<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.IDPrefix)
+ case *SelectBy_Name:
+ _ = b.EncodeVarint(3<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.Name)
+ case *SelectBy_NamePrefix:
+ _ = b.EncodeVarint(4<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.NamePrefix)
+ case *SelectBy_Custom:
+ _ = b.EncodeVarint(5<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Custom); err != nil {
+ return err
+ }
+ case *SelectBy_CustomPrefix:
+ _ = b.EncodeVarint(6<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.CustomPrefix); err != nil {
+ return err
+ }
+ case *SelectBy_ServiceID:
+ _ = b.EncodeVarint(7<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.ServiceID)
+ case *SelectBy_NodeID:
+ _ = b.EncodeVarint(8<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.NodeID)
+ case *SelectBy_Slot:
+ _ = b.EncodeVarint(9<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Slot); err != nil {
+ return err
+ }
+ case *SelectBy_DesiredState:
+ _ = b.EncodeVarint(10<<3 | proto.WireVarint)
+ _ = b.EncodeVarint(uint64(x.DesiredState))
+ case *SelectBy_Role:
+ _ = b.EncodeVarint(11<<3 | proto.WireVarint)
+ _ = b.EncodeVarint(uint64(x.Role))
+ case *SelectBy_Membership:
+ _ = b.EncodeVarint(12<<3 | proto.WireVarint)
+ _ = b.EncodeVarint(uint64(x.Membership))
+ case *SelectBy_ReferencedNetworkID:
+ _ = b.EncodeVarint(13<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.ReferencedNetworkID)
+ case *SelectBy_ReferencedSecretID:
+ _ = b.EncodeVarint(14<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.ReferencedSecretID)
+ case *SelectBy_ReferencedConfigID:
+ _ = b.EncodeVarint(16<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.ReferencedConfigID)
+ case *SelectBy_Kind:
+ _ = b.EncodeVarint(15<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.Kind)
+ case nil:
+ default:
+ return fmt.Errorf("SelectBy.By has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _SelectBy_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*SelectBy)
+ switch tag {
+ case 1: // By.id
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.By = &SelectBy_ID{x}
+ return true, err
+ case 2: // By.id_prefix
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.By = &SelectBy_IDPrefix{x}
+ return true, err
+ case 3: // By.name
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.By = &SelectBy_Name{x}
+ return true, err
+ case 4: // By.name_prefix
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.By = &SelectBy_NamePrefix{x}
+ return true, err
+ case 5: // By.custom
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(SelectByCustom)
+ err := b.DecodeMessage(msg)
+ m.By = &SelectBy_Custom{msg}
+ return true, err
+ case 6: // By.custom_prefix
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(SelectByCustom)
+ err := b.DecodeMessage(msg)
+ m.By = &SelectBy_CustomPrefix{msg}
+ return true, err
+ case 7: // By.service_id
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.By = &SelectBy_ServiceID{x}
+ return true, err
+ case 8: // By.node_id
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.By = &SelectBy_NodeID{x}
+ return true, err
+ case 9: // By.slot
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(SelectBySlot)
+ err := b.DecodeMessage(msg)
+ m.By = &SelectBy_Slot{msg}
+ return true, err
+ case 10: // By.desired_state
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.By = &SelectBy_DesiredState{TaskState(x)}
+ return true, err
+ case 11: // By.role
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.By = &SelectBy_Role{NodeRole(x)}
+ return true, err
+ case 12: // By.membership
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.By = &SelectBy_Membership{NodeSpec_Membership(x)}
+ return true, err
+ case 13: // By.referenced_network_id
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.By = &SelectBy_ReferencedNetworkID{x}
+ return true, err
+ case 14: // By.referenced_secret_id
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.By = &SelectBy_ReferencedSecretID{x}
+ return true, err
+ case 16: // By.referenced_config_id
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.By = &SelectBy_ReferencedConfigID{x}
+ return true, err
+ case 15: // By.kind
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.By = &SelectBy_Kind{x}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _SelectBy_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*SelectBy)
+ // By
+ switch x := m.By.(type) {
+ case *SelectBy_ID:
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.ID)))
+ n += len(x.ID)
+ case *SelectBy_IDPrefix:
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.IDPrefix)))
+ n += len(x.IDPrefix)
+ case *SelectBy_Name:
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Name)))
+ n += len(x.Name)
+ case *SelectBy_NamePrefix:
+ n += proto.SizeVarint(4<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.NamePrefix)))
+ n += len(x.NamePrefix)
+ case *SelectBy_Custom:
+ s := proto.Size(x.Custom)
+ n += proto.SizeVarint(5<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *SelectBy_CustomPrefix:
+ s := proto.Size(x.CustomPrefix)
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *SelectBy_ServiceID:
+ n += proto.SizeVarint(7<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.ServiceID)))
+ n += len(x.ServiceID)
+ case *SelectBy_NodeID:
+ n += proto.SizeVarint(8<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.NodeID)))
+ n += len(x.NodeID)
+ case *SelectBy_Slot:
+ s := proto.Size(x.Slot)
+ n += proto.SizeVarint(9<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *SelectBy_DesiredState:
+ n += proto.SizeVarint(10<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.DesiredState))
+ case *SelectBy_Role:
+ n += proto.SizeVarint(11<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.Role))
+ case *SelectBy_Membership:
+ n += proto.SizeVarint(12<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.Membership))
+ case *SelectBy_ReferencedNetworkID:
+ n += proto.SizeVarint(13<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.ReferencedNetworkID)))
+ n += len(x.ReferencedNetworkID)
+ case *SelectBy_ReferencedSecretID:
+ n += proto.SizeVarint(14<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.ReferencedSecretID)))
+ n += len(x.ReferencedSecretID)
+ case *SelectBy_ReferencedConfigID:
+ n += proto.SizeVarint(16<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.ReferencedConfigID)))
+ n += len(x.ReferencedConfigID)
+ case *SelectBy_Kind:
+ n += proto.SizeVarint(15<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Kind)))
+ n += len(x.Kind)
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type WatchRequest struct {
+ // Multiple entries are combined using OR logic - i.e. if an event
+ // matches all of the selectors specified in any single watch entry,
+ // the event will be sent to the client.
+ Entries []*WatchRequest_WatchEntry `protobuf:"bytes,1,rep,name=entries" json:"entries,omitempty"`
+ // ResumeFrom provides an version to resume the watch from, if non-nil.
+ // The watch will return changes since this version, and continue to
+ // return new changes afterwards. Watch will return an error if the
+ // server has compacted its log and no longer has complete history to
+ // this point.
+ ResumeFrom *Version `protobuf:"bytes,2,opt,name=resume_from,json=resumeFrom" json:"resume_from,omitempty"`
+ // IncludeOldObject causes WatchMessages to include a copy of the
+ // previous version of the object on updates. Note that only live
+ // changes will include the old object (not historical changes
+ // retrieved using ResumeFrom).
+ IncludeOldObject bool `protobuf:"varint,3,opt,name=include_old_object,json=includeOldObject,proto3" json:"include_old_object,omitempty"`
+}
+
+func (m *WatchRequest) Reset() { *m = WatchRequest{} }
+func (*WatchRequest) ProtoMessage() {}
+func (*WatchRequest) Descriptor() ([]byte, []int) { return fileDescriptorWatch, []int{4} }
+
+type WatchRequest_WatchEntry struct {
+ // Kind can contain a builtin type such as "node", "secret", etc. or
+ // the kind specified by a custom-defined object.
+ Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
+ // Action (create/update/delete)
+ // This is a bitmask, so multiple actions may be OR'd together
+ Action WatchActionKind `protobuf:"varint,2,opt,name=action,proto3,enum=docker.swarmkit.v1.WatchActionKind" json:"action,omitempty"`
+ // Filters are combined using AND logic - an event must match
+ // all of them to pass the filter.
+ Filters []*SelectBy `protobuf:"bytes,3,rep,name=filters" json:"filters,omitempty"`
+}
+
+func (m *WatchRequest_WatchEntry) Reset() { *m = WatchRequest_WatchEntry{} }
+func (*WatchRequest_WatchEntry) ProtoMessage() {}
+func (*WatchRequest_WatchEntry) Descriptor() ([]byte, []int) { return fileDescriptorWatch, []int{4, 0} }
+
+// WatchMessage is the type of the stream that's returned to the client by
+// Watch. Note that the first item of this stream will always be a WatchMessage
+// with a nil Object, to signal that the stream has started.
+type WatchMessage struct {
+ Events []*WatchMessage_Event `protobuf:"bytes,1,rep,name=events" json:"events,omitempty"`
+ // Index versions this change to the data store. It can be used to
+ // resume the watch from this point.
+ Version *Version `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"`
+}
+
+func (m *WatchMessage) Reset() { *m = WatchMessage{} }
+func (*WatchMessage) ProtoMessage() {}
+func (*WatchMessage) Descriptor() ([]byte, []int) { return fileDescriptorWatch, []int{5} }
+
+type WatchMessage_Event struct {
+ // Action (create/update/delete)
+ // Note that WatchMessage does not expose "commit" events that
+ // mark transaction boundaries.
+ Action WatchActionKind `protobuf:"varint,1,opt,name=action,proto3,enum=docker.swarmkit.v1.WatchActionKind" json:"action,omitempty"`
+ // Matched object
+ Object *Object `protobuf:"bytes,2,opt,name=object" json:"object,omitempty"`
+ // For updates, OldObject will optionally be included in the
+ // watch message, containing the previous version of the
+ // object, if IncludeOldObject was set in WatchRequest.
+ OldObject *Object `protobuf:"bytes,3,opt,name=old_object,json=oldObject" json:"old_object,omitempty"`
+}
+
+func (m *WatchMessage_Event) Reset() { *m = WatchMessage_Event{} }
+func (*WatchMessage_Event) ProtoMessage() {}
+func (*WatchMessage_Event) Descriptor() ([]byte, []int) { return fileDescriptorWatch, []int{5, 0} }
+
+func init() {
+ proto.RegisterType((*Object)(nil), "docker.swarmkit.v1.Object")
+ proto.RegisterType((*SelectBySlot)(nil), "docker.swarmkit.v1.SelectBySlot")
+ proto.RegisterType((*SelectByCustom)(nil), "docker.swarmkit.v1.SelectByCustom")
+ proto.RegisterType((*SelectBy)(nil), "docker.swarmkit.v1.SelectBy")
+ proto.RegisterType((*WatchRequest)(nil), "docker.swarmkit.v1.WatchRequest")
+ proto.RegisterType((*WatchRequest_WatchEntry)(nil), "docker.swarmkit.v1.WatchRequest.WatchEntry")
+ proto.RegisterType((*WatchMessage)(nil), "docker.swarmkit.v1.WatchMessage")
+ proto.RegisterType((*WatchMessage_Event)(nil), "docker.swarmkit.v1.WatchMessage.Event")
+ proto.RegisterEnum("docker.swarmkit.v1.WatchActionKind", WatchActionKind_name, WatchActionKind_value)
+}
+
+type authenticatedWrapperWatchServer struct {
+ local WatchServer
+ authorize func(context.Context, []string) error
+}
+
+func NewAuthenticatedWrapperWatchServer(local WatchServer, authorize func(context.Context, []string) error) WatchServer {
+ return &authenticatedWrapperWatchServer{
+ local: local,
+ authorize: authorize,
+ }
+}
+
+func (p *authenticatedWrapperWatchServer) Watch(r *WatchRequest, stream Watch_WatchServer) error {
+
+ if err := p.authorize(stream.Context(), []string{"swarm-manager"}); err != nil {
+ return err
+ }
+ return p.local.Watch(r, stream)
+}
+
+func (m *Object) Copy() *Object {
+ if m == nil {
+ return nil
+ }
+ o := &Object{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *Object) CopyFrom(src interface{}) {
+
+ o := src.(*Object)
+ *m = *o
+ if o.Object != nil {
+ switch o.Object.(type) {
+ case *Object_Node:
+ v := Object_Node{
+ Node: &Node{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Node, o.GetNode())
+ m.Object = &v
+ case *Object_Service:
+ v := Object_Service{
+ Service: &Service{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Service, o.GetService())
+ m.Object = &v
+ case *Object_Network:
+ v := Object_Network{
+ Network: &Network{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Network, o.GetNetwork())
+ m.Object = &v
+ case *Object_Task:
+ v := Object_Task{
+ Task: &Task{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Task, o.GetTask())
+ m.Object = &v
+ case *Object_Cluster:
+ v := Object_Cluster{
+ Cluster: &Cluster{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Cluster, o.GetCluster())
+ m.Object = &v
+ case *Object_Secret:
+ v := Object_Secret{
+ Secret: &Secret{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Secret, o.GetSecret())
+ m.Object = &v
+ case *Object_Resource:
+ v := Object_Resource{
+ Resource: &Resource{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Resource, o.GetResource())
+ m.Object = &v
+ case *Object_Extension:
+ v := Object_Extension{
+ Extension: &Extension{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Extension, o.GetExtension())
+ m.Object = &v
+ case *Object_Config:
+ v := Object_Config{
+ Config: &Config{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Config, o.GetConfig())
+ m.Object = &v
+ }
+ }
+
+}
+
+func (m *SelectBySlot) Copy() *SelectBySlot {
+ if m == nil {
+ return nil
+ }
+ o := &SelectBySlot{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SelectBySlot) CopyFrom(src interface{}) {
+
+ o := src.(*SelectBySlot)
+ *m = *o
+}
+
+func (m *SelectByCustom) Copy() *SelectByCustom {
+ if m == nil {
+ return nil
+ }
+ o := &SelectByCustom{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SelectByCustom) CopyFrom(src interface{}) {
+
+ o := src.(*SelectByCustom)
+ *m = *o
+}
+
+func (m *SelectBy) Copy() *SelectBy {
+ if m == nil {
+ return nil
+ }
+ o := &SelectBy{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *SelectBy) CopyFrom(src interface{}) {
+
+ o := src.(*SelectBy)
+ *m = *o
+ if o.By != nil {
+ switch o.By.(type) {
+ case *SelectBy_ID:
+ v := SelectBy_ID{
+ ID: o.GetID(),
+ }
+ m.By = &v
+ case *SelectBy_IDPrefix:
+ v := SelectBy_IDPrefix{
+ IDPrefix: o.GetIDPrefix(),
+ }
+ m.By = &v
+ case *SelectBy_Name:
+ v := SelectBy_Name{
+ Name: o.GetName(),
+ }
+ m.By = &v
+ case *SelectBy_NamePrefix:
+ v := SelectBy_NamePrefix{
+ NamePrefix: o.GetNamePrefix(),
+ }
+ m.By = &v
+ case *SelectBy_Custom:
+ v := SelectBy_Custom{
+ Custom: &SelectByCustom{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Custom, o.GetCustom())
+ m.By = &v
+ case *SelectBy_CustomPrefix:
+ v := SelectBy_CustomPrefix{
+ CustomPrefix: &SelectByCustom{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.CustomPrefix, o.GetCustomPrefix())
+ m.By = &v
+ case *SelectBy_ServiceID:
+ v := SelectBy_ServiceID{
+ ServiceID: o.GetServiceID(),
+ }
+ m.By = &v
+ case *SelectBy_NodeID:
+ v := SelectBy_NodeID{
+ NodeID: o.GetNodeID(),
+ }
+ m.By = &v
+ case *SelectBy_Slot:
+ v := SelectBy_Slot{
+ Slot: &SelectBySlot{},
+ }
+ github_com_docker_swarmkit_api_deepcopy.Copy(v.Slot, o.GetSlot())
+ m.By = &v
+ case *SelectBy_DesiredState:
+ v := SelectBy_DesiredState{
+ DesiredState: o.GetDesiredState(),
+ }
+ m.By = &v
+ case *SelectBy_Role:
+ v := SelectBy_Role{
+ Role: o.GetRole(),
+ }
+ m.By = &v
+ case *SelectBy_Membership:
+ v := SelectBy_Membership{
+ Membership: o.GetMembership(),
+ }
+ m.By = &v
+ case *SelectBy_ReferencedNetworkID:
+ v := SelectBy_ReferencedNetworkID{
+ ReferencedNetworkID: o.GetReferencedNetworkID(),
+ }
+ m.By = &v
+ case *SelectBy_ReferencedSecretID:
+ v := SelectBy_ReferencedSecretID{
+ ReferencedSecretID: o.GetReferencedSecretID(),
+ }
+ m.By = &v
+ case *SelectBy_ReferencedConfigID:
+ v := SelectBy_ReferencedConfigID{
+ ReferencedConfigID: o.GetReferencedConfigID(),
+ }
+ m.By = &v
+ case *SelectBy_Kind:
+ v := SelectBy_Kind{
+ Kind: o.GetKind(),
+ }
+ m.By = &v
+ }
+ }
+
+}
+
+func (m *WatchRequest) Copy() *WatchRequest {
+ if m == nil {
+ return nil
+ }
+ o := &WatchRequest{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *WatchRequest) CopyFrom(src interface{}) {
+
+ o := src.(*WatchRequest)
+ *m = *o
+ if o.Entries != nil {
+ m.Entries = make([]*WatchRequest_WatchEntry, len(o.Entries))
+ for i := range m.Entries {
+ m.Entries[i] = &WatchRequest_WatchEntry{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Entries[i], o.Entries[i])
+ }
+ }
+
+ if o.ResumeFrom != nil {
+ m.ResumeFrom = &Version{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.ResumeFrom, o.ResumeFrom)
+ }
+}
+
+func (m *WatchRequest_WatchEntry) Copy() *WatchRequest_WatchEntry {
+ if m == nil {
+ return nil
+ }
+ o := &WatchRequest_WatchEntry{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *WatchRequest_WatchEntry) CopyFrom(src interface{}) {
+
+ o := src.(*WatchRequest_WatchEntry)
+ *m = *o
+ if o.Filters != nil {
+ m.Filters = make([]*SelectBy, len(o.Filters))
+ for i := range m.Filters {
+ m.Filters[i] = &SelectBy{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Filters[i], o.Filters[i])
+ }
+ }
+
+}
+
+func (m *WatchMessage) Copy() *WatchMessage {
+ if m == nil {
+ return nil
+ }
+ o := &WatchMessage{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *WatchMessage) CopyFrom(src interface{}) {
+
+ o := src.(*WatchMessage)
+ *m = *o
+ if o.Events != nil {
+ m.Events = make([]*WatchMessage_Event, len(o.Events))
+ for i := range m.Events {
+ m.Events[i] = &WatchMessage_Event{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Events[i], o.Events[i])
+ }
+ }
+
+ if o.Version != nil {
+ m.Version = &Version{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Version, o.Version)
+ }
+}
+
+func (m *WatchMessage_Event) Copy() *WatchMessage_Event {
+ if m == nil {
+ return nil
+ }
+ o := &WatchMessage_Event{}
+ o.CopyFrom(m)
+ return o
+}
+
+func (m *WatchMessage_Event) CopyFrom(src interface{}) {
+
+ o := src.(*WatchMessage_Event)
+ *m = *o
+ if o.Object != nil {
+ m.Object = &Object{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.Object, o.Object)
+ }
+ if o.OldObject != nil {
+ m.OldObject = &Object{}
+ github_com_docker_swarmkit_api_deepcopy.Copy(m.OldObject, o.OldObject)
+ }
+}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for Watch service
+
+type WatchClient interface {
+ // Watch starts a stream that returns any changes to objects that match
+ // the specified selectors. When the stream begins, it immediately sends
+ // an empty message back to the client. It is important to wait for
+ // this message before taking any actions that depend on an established
+ // stream of changes for consistency.
+ Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (Watch_WatchClient, error)
+}
+
+type watchClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewWatchClient(cc *grpc.ClientConn) WatchClient {
+ return &watchClient{cc}
+}
+
+func (c *watchClient) Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (Watch_WatchClient, error) {
+ stream, err := grpc.NewClientStream(ctx, &_Watch_serviceDesc.Streams[0], c.cc, "/docker.swarmkit.v1.Watch/Watch", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &watchWatchClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Watch_WatchClient interface {
+ Recv() (*WatchMessage, error)
+ grpc.ClientStream
+}
+
+type watchWatchClient struct {
+ grpc.ClientStream
+}
+
+func (x *watchWatchClient) Recv() (*WatchMessage, error) {
+ m := new(WatchMessage)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// Server API for Watch service
+
+type WatchServer interface {
+ // Watch starts a stream that returns any changes to objects that match
+ // the specified selectors. When the stream begins, it immediately sends
+ // an empty message back to the client. It is important to wait for
+ // this message before taking any actions that depend on an established
+ // stream of changes for consistency.
+ Watch(*WatchRequest, Watch_WatchServer) error
+}
+
+func RegisterWatchServer(s *grpc.Server, srv WatchServer) {
+ s.RegisterService(&_Watch_serviceDesc, srv)
+}
+
+func _Watch_Watch_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(WatchRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(WatchServer).Watch(m, &watchWatchServer{stream})
+}
+
+type Watch_WatchServer interface {
+ Send(*WatchMessage) error
+ grpc.ServerStream
+}
+
+type watchWatchServer struct {
+ grpc.ServerStream
+}
+
+func (x *watchWatchServer) Send(m *WatchMessage) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+var _Watch_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "docker.swarmkit.v1.Watch",
+ HandlerType: (*WatchServer)(nil),
+ Methods: []grpc.MethodDesc{},
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "Watch",
+ Handler: _Watch_Watch_Handler,
+ ServerStreams: true,
+ },
+ },
+ Metadata: "watch.proto",
+}
+
+func (m *Object) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Object) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Object != nil {
+ nn1, err := m.Object.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn1
+ }
+ return i, nil
+}
+
+func (m *Object_Node) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Node != nil {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Node.Size()))
+ n2, err := m.Node.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n2
+ }
+ return i, nil
+}
+func (m *Object_Service) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Service != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Service.Size()))
+ n3, err := m.Service.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ }
+ return i, nil
+}
+func (m *Object_Network) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Network != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Network.Size()))
+ n4, err := m.Network.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n4
+ }
+ return i, nil
+}
+func (m *Object_Task) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Task != nil {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Task.Size()))
+ n5, err := m.Task.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n5
+ }
+ return i, nil
+}
+func (m *Object_Cluster) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Cluster != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Cluster.Size()))
+ n6, err := m.Cluster.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n6
+ }
+ return i, nil
+}
+func (m *Object_Secret) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Secret != nil {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Secret.Size()))
+ n7, err := m.Secret.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n7
+ }
+ return i, nil
+}
+func (m *Object_Resource) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Resource != nil {
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Resource.Size()))
+ n8, err := m.Resource.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n8
+ }
+ return i, nil
+}
+func (m *Object_Extension) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Extension != nil {
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Extension.Size()))
+ n9, err := m.Extension.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n9
+ }
+ return i, nil
+}
+func (m *Object_Config) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Config != nil {
+ dAtA[i] = 0x4a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Config.Size()))
+ n10, err := m.Config.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n10
+ }
+ return i, nil
+}
+func (m *SelectBySlot) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SelectBySlot) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.ServiceID) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.ServiceID)))
+ i += copy(dAtA[i:], m.ServiceID)
+ }
+ if m.Slot != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Slot))
+ }
+ return i, nil
+}
+
+func (m *SelectByCustom) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SelectByCustom) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Kind) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.Kind)))
+ i += copy(dAtA[i:], m.Kind)
+ }
+ if len(m.Index) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.Index)))
+ i += copy(dAtA[i:], m.Index)
+ }
+ if len(m.Value) > 0 {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.Value)))
+ i += copy(dAtA[i:], m.Value)
+ }
+ return i, nil
+}
+
+func (m *SelectBy) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *SelectBy) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.By != nil {
+ nn11, err := m.By.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn11
+ }
+ return i, nil
+}
+
+func (m *SelectBy_ID) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.ID)))
+ i += copy(dAtA[i:], m.ID)
+ return i, nil
+}
+func (m *SelectBy_IDPrefix) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.IDPrefix)))
+ i += copy(dAtA[i:], m.IDPrefix)
+ return i, nil
+}
+func (m *SelectBy_Name) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.Name)))
+ i += copy(dAtA[i:], m.Name)
+ return i, nil
+}
+func (m *SelectBy_NamePrefix) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.NamePrefix)))
+ i += copy(dAtA[i:], m.NamePrefix)
+ return i, nil
+}
+func (m *SelectBy_Custom) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Custom != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Custom.Size()))
+ n12, err := m.Custom.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n12
+ }
+ return i, nil
+}
+func (m *SelectBy_CustomPrefix) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.CustomPrefix != nil {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.CustomPrefix.Size()))
+ n13, err := m.CustomPrefix.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n13
+ }
+ return i, nil
+}
+func (m *SelectBy_ServiceID) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.ServiceID)))
+ i += copy(dAtA[i:], m.ServiceID)
+ return i, nil
+}
+func (m *SelectBy_NodeID) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x42
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.NodeID)))
+ i += copy(dAtA[i:], m.NodeID)
+ return i, nil
+}
+func (m *SelectBy_Slot) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.Slot != nil {
+ dAtA[i] = 0x4a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Slot.Size()))
+ n14, err := m.Slot.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n14
+ }
+ return i, nil
+}
+func (m *SelectBy_DesiredState) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x50
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.DesiredState))
+ return i, nil
+}
+func (m *SelectBy_Role) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x58
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Role))
+ return i, nil
+}
+func (m *SelectBy_Membership) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x60
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Membership))
+ return i, nil
+}
+func (m *SelectBy_ReferencedNetworkID) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x6a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.ReferencedNetworkID)))
+ i += copy(dAtA[i:], m.ReferencedNetworkID)
+ return i, nil
+}
+func (m *SelectBy_ReferencedSecretID) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x72
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.ReferencedSecretID)))
+ i += copy(dAtA[i:], m.ReferencedSecretID)
+ return i, nil
+}
+func (m *SelectBy_Kind) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x7a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.Kind)))
+ i += copy(dAtA[i:], m.Kind)
+ return i, nil
+}
+func (m *SelectBy_ReferencedConfigID) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x82
+ i++
+ dAtA[i] = 0x1
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.ReferencedConfigID)))
+ i += copy(dAtA[i:], m.ReferencedConfigID)
+ return i, nil
+}
+func (m *WatchRequest) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *WatchRequest) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Entries) > 0 {
+ for _, msg := range m.Entries {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if m.ResumeFrom != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.ResumeFrom.Size()))
+ n15, err := m.ResumeFrom.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n15
+ }
+ if m.IncludeOldObject {
+ dAtA[i] = 0x18
+ i++
+ if m.IncludeOldObject {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ return i, nil
+}
+
+func (m *WatchRequest_WatchEntry) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *WatchRequest_WatchEntry) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Kind) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(len(m.Kind)))
+ i += copy(dAtA[i:], m.Kind)
+ }
+ if m.Action != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Action))
+ }
+ if len(m.Filters) > 0 {
+ for _, msg := range m.Filters {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func (m *WatchMessage) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *WatchMessage) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Events) > 0 {
+ for _, msg := range m.Events {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ if m.Version != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Version.Size()))
+ n16, err := m.Version.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n16
+ }
+ return i, nil
+}
+
+func (m *WatchMessage_Event) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *WatchMessage_Event) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Action != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Action))
+ }
+ if m.Object != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.Object.Size()))
+ n17, err := m.Object.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n17
+ }
+ if m.OldObject != nil {
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintWatch(dAtA, i, uint64(m.OldObject.Size()))
+ n18, err := m.OldObject.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n18
+ }
+ return i, nil
+}
+
+func encodeFixed64Watch(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Watch(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintWatch(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+
+type raftProxyWatchServer struct {
+ local WatchServer
+ connSelector raftselector.ConnProvider
+ localCtxMods, remoteCtxMods []func(context.Context) (context.Context, error)
+}
+
+func NewRaftProxyWatchServer(local WatchServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) WatchServer {
+ redirectChecker := func(ctx context.Context) (context.Context, error) {
+ s, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
+ }
+ addr := s.ServerTransport().RemoteAddr().String()
+ md, ok := metadata.FromContext(ctx)
+ if ok && len(md["redirect"]) != 0 {
+ return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
+ }
+ if !ok {
+ md = metadata.New(map[string]string{})
+ }
+ md["redirect"] = append(md["redirect"], addr)
+ return metadata.NewContext(ctx, md), nil
+ }
+ remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
+ remoteMods = append(remoteMods, remoteCtxMod)
+
+ var localMods []func(context.Context) (context.Context, error)
+ if localCtxMod != nil {
+ localMods = []func(context.Context) (context.Context, error){localCtxMod}
+ }
+
+ return &raftProxyWatchServer{
+ local: local,
+ connSelector: connSelector,
+ localCtxMods: localMods,
+ remoteCtxMods: remoteMods,
+ }
+}
+func (p *raftProxyWatchServer) runCtxMods(ctx context.Context, ctxMods []func(context.Context) (context.Context, error)) (context.Context, error) {
+ var err error
+ for _, mod := range ctxMods {
+ ctx, err = mod(ctx)
+ if err != nil {
+ return ctx, err
+ }
+ }
+ return ctx, nil
+}
+func (p *raftProxyWatchServer) pollNewLeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ ticker := rafttime.NewTicker(500 * rafttime.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ client := NewHealthClient(conn)
+
+ resp, err := client.Check(ctx, &HealthCheckRequest{Service: "Raft"})
+ if err != nil || resp.Status != HealthCheckResponse_SERVING {
+ continue
+ }
+ return conn, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+type Watch_WatchServerWrapper struct {
+ Watch_WatchServer
+ ctx context.Context
+}
+
+func (s Watch_WatchServerWrapper) Context() context.Context {
+ return s.ctx
+}
+
+func (p *raftProxyWatchServer) Watch(r *WatchRequest, stream Watch_WatchServer) error {
+ ctx := stream.Context()
+ conn, err := p.connSelector.LeaderConn(ctx)
+ if err != nil {
+ if err == raftselector.ErrIsLeader {
+ ctx, err = p.runCtxMods(ctx, p.localCtxMods)
+ if err != nil {
+ return err
+ }
+ streamWrapper := Watch_WatchServerWrapper{
+ Watch_WatchServer: stream,
+ ctx: ctx,
+ }
+ return p.local.Watch(r, streamWrapper)
+ }
+ return err
+ }
+ ctx, err = p.runCtxMods(ctx, p.remoteCtxMods)
+ if err != nil {
+ return err
+ }
+ clientStream, err := NewWatchClient(conn).Watch(ctx, r)
+
+ if err != nil {
+ return err
+ }
+
+ for {
+ msg, err := clientStream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return err
+ }
+ if err := stream.Send(msg); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (m *Object) Size() (n int) {
+ var l int
+ _ = l
+ if m.Object != nil {
+ n += m.Object.Size()
+ }
+ return n
+}
+
+func (m *Object_Node) Size() (n int) {
+ var l int
+ _ = l
+ if m.Node != nil {
+ l = m.Node.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *Object_Service) Size() (n int) {
+ var l int
+ _ = l
+ if m.Service != nil {
+ l = m.Service.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *Object_Network) Size() (n int) {
+ var l int
+ _ = l
+ if m.Network != nil {
+ l = m.Network.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *Object_Task) Size() (n int) {
+ var l int
+ _ = l
+ if m.Task != nil {
+ l = m.Task.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *Object_Cluster) Size() (n int) {
+ var l int
+ _ = l
+ if m.Cluster != nil {
+ l = m.Cluster.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *Object_Secret) Size() (n int) {
+ var l int
+ _ = l
+ if m.Secret != nil {
+ l = m.Secret.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *Object_Resource) Size() (n int) {
+ var l int
+ _ = l
+ if m.Resource != nil {
+ l = m.Resource.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *Object_Extension) Size() (n int) {
+ var l int
+ _ = l
+ if m.Extension != nil {
+ l = m.Extension.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *Object_Config) Size() (n int) {
+ var l int
+ _ = l
+ if m.Config != nil {
+ l = m.Config.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *SelectBySlot) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ServiceID)
+ if l > 0 {
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ if m.Slot != 0 {
+ n += 1 + sovWatch(uint64(m.Slot))
+ }
+ return n
+}
+
+func (m *SelectByCustom) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Kind)
+ if l > 0 {
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ l = len(m.Index)
+ if l > 0 {
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ l = len(m.Value)
+ if l > 0 {
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+
+func (m *SelectBy) Size() (n int) {
+ var l int
+ _ = l
+ if m.By != nil {
+ n += m.By.Size()
+ }
+ return n
+}
+
+func (m *SelectBy_ID) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ID)
+ n += 1 + l + sovWatch(uint64(l))
+ return n
+}
+func (m *SelectBy_IDPrefix) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.IDPrefix)
+ n += 1 + l + sovWatch(uint64(l))
+ return n
+}
+func (m *SelectBy_Name) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Name)
+ n += 1 + l + sovWatch(uint64(l))
+ return n
+}
+func (m *SelectBy_NamePrefix) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.NamePrefix)
+ n += 1 + l + sovWatch(uint64(l))
+ return n
+}
+func (m *SelectBy_Custom) Size() (n int) {
+ var l int
+ _ = l
+ if m.Custom != nil {
+ l = m.Custom.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *SelectBy_CustomPrefix) Size() (n int) {
+ var l int
+ _ = l
+ if m.CustomPrefix != nil {
+ l = m.CustomPrefix.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *SelectBy_ServiceID) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ServiceID)
+ n += 1 + l + sovWatch(uint64(l))
+ return n
+}
+func (m *SelectBy_NodeID) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.NodeID)
+ n += 1 + l + sovWatch(uint64(l))
+ return n
+}
+func (m *SelectBy_Slot) Size() (n int) {
+ var l int
+ _ = l
+ if m.Slot != nil {
+ l = m.Slot.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+func (m *SelectBy_DesiredState) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovWatch(uint64(m.DesiredState))
+ return n
+}
+func (m *SelectBy_Role) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovWatch(uint64(m.Role))
+ return n
+}
+func (m *SelectBy_Membership) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovWatch(uint64(m.Membership))
+ return n
+}
+func (m *SelectBy_ReferencedNetworkID) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ReferencedNetworkID)
+ n += 1 + l + sovWatch(uint64(l))
+ return n
+}
+func (m *SelectBy_ReferencedSecretID) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ReferencedSecretID)
+ n += 1 + l + sovWatch(uint64(l))
+ return n
+}
+func (m *SelectBy_Kind) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Kind)
+ n += 1 + l + sovWatch(uint64(l))
+ return n
+}
+func (m *SelectBy_ReferencedConfigID) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.ReferencedConfigID)
+ n += 2 + l + sovWatch(uint64(l))
+ return n
+}
+func (m *WatchRequest) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Entries) > 0 {
+ for _, e := range m.Entries {
+ l = e.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ }
+ if m.ResumeFrom != nil {
+ l = m.ResumeFrom.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ if m.IncludeOldObject {
+ n += 2
+ }
+ return n
+}
+
+func (m *WatchRequest_WatchEntry) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Kind)
+ if l > 0 {
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ if m.Action != 0 {
+ n += 1 + sovWatch(uint64(m.Action))
+ }
+ if len(m.Filters) > 0 {
+ for _, e := range m.Filters {
+ l = e.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ }
+ return n
+}
+
+func (m *WatchMessage) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Events) > 0 {
+ for _, e := range m.Events {
+ l = e.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ }
+ if m.Version != nil {
+ l = m.Version.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+
+func (m *WatchMessage_Event) Size() (n int) {
+ var l int
+ _ = l
+ if m.Action != 0 {
+ n += 1 + sovWatch(uint64(m.Action))
+ }
+ if m.Object != nil {
+ l = m.Object.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ if m.OldObject != nil {
+ l = m.OldObject.Size()
+ n += 1 + l + sovWatch(uint64(l))
+ }
+ return n
+}
+
+func sovWatch(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozWatch(x uint64) (n int) {
+ return sovWatch(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *Object) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Object{`,
+ `Object:` + fmt.Sprintf("%v", this.Object) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Object_Node) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Object_Node{`,
+ `Node:` + strings.Replace(fmt.Sprintf("%v", this.Node), "Node", "Node", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Object_Service) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Object_Service{`,
+ `Service:` + strings.Replace(fmt.Sprintf("%v", this.Service), "Service", "Service", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Object_Network) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Object_Network{`,
+ `Network:` + strings.Replace(fmt.Sprintf("%v", this.Network), "Network", "Network", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Object_Task) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Object_Task{`,
+ `Task:` + strings.Replace(fmt.Sprintf("%v", this.Task), "Task", "Task", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Object_Cluster) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Object_Cluster{`,
+ `Cluster:` + strings.Replace(fmt.Sprintf("%v", this.Cluster), "Cluster", "Cluster", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Object_Secret) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Object_Secret{`,
+ `Secret:` + strings.Replace(fmt.Sprintf("%v", this.Secret), "Secret", "Secret", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Object_Resource) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Object_Resource{`,
+ `Resource:` + strings.Replace(fmt.Sprintf("%v", this.Resource), "Resource", "Resource", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Object_Extension) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Object_Extension{`,
+ `Extension:` + strings.Replace(fmt.Sprintf("%v", this.Extension), "Extension", "Extension", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Object_Config) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Object_Config{`,
+ `Config:` + strings.Replace(fmt.Sprintf("%v", this.Config), "Config", "Config", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBySlot) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBySlot{`,
+ `ServiceID:` + fmt.Sprintf("%v", this.ServiceID) + `,`,
+ `Slot:` + fmt.Sprintf("%v", this.Slot) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectByCustom) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectByCustom{`,
+ `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`,
+ `Index:` + fmt.Sprintf("%v", this.Index) + `,`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy{`,
+ `By:` + fmt.Sprintf("%v", this.By) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_ID) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_ID{`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_IDPrefix) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_IDPrefix{`,
+ `IDPrefix:` + fmt.Sprintf("%v", this.IDPrefix) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_Name) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_Name{`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_NamePrefix) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_NamePrefix{`,
+ `NamePrefix:` + fmt.Sprintf("%v", this.NamePrefix) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_Custom) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_Custom{`,
+ `Custom:` + strings.Replace(fmt.Sprintf("%v", this.Custom), "SelectByCustom", "SelectByCustom", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_CustomPrefix) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_CustomPrefix{`,
+ `CustomPrefix:` + strings.Replace(fmt.Sprintf("%v", this.CustomPrefix), "SelectByCustom", "SelectByCustom", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_ServiceID) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_ServiceID{`,
+ `ServiceID:` + fmt.Sprintf("%v", this.ServiceID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_NodeID) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_NodeID{`,
+ `NodeID:` + fmt.Sprintf("%v", this.NodeID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_Slot) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_Slot{`,
+ `Slot:` + strings.Replace(fmt.Sprintf("%v", this.Slot), "SelectBySlot", "SelectBySlot", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_DesiredState) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_DesiredState{`,
+ `DesiredState:` + fmt.Sprintf("%v", this.DesiredState) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_Role) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_Role{`,
+ `Role:` + fmt.Sprintf("%v", this.Role) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_Membership) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_Membership{`,
+ `Membership:` + fmt.Sprintf("%v", this.Membership) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_ReferencedNetworkID) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_ReferencedNetworkID{`,
+ `ReferencedNetworkID:` + fmt.Sprintf("%v", this.ReferencedNetworkID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_ReferencedSecretID) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_ReferencedSecretID{`,
+ `ReferencedSecretID:` + fmt.Sprintf("%v", this.ReferencedSecretID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_Kind) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_Kind{`,
+ `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *SelectBy_ReferencedConfigID) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&SelectBy_ReferencedConfigID{`,
+ `ReferencedConfigID:` + fmt.Sprintf("%v", this.ReferencedConfigID) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *WatchRequest) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&WatchRequest{`,
+ `Entries:` + strings.Replace(fmt.Sprintf("%v", this.Entries), "WatchRequest_WatchEntry", "WatchRequest_WatchEntry", 1) + `,`,
+ `ResumeFrom:` + strings.Replace(fmt.Sprintf("%v", this.ResumeFrom), "Version", "Version", 1) + `,`,
+ `IncludeOldObject:` + fmt.Sprintf("%v", this.IncludeOldObject) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *WatchRequest_WatchEntry) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&WatchRequest_WatchEntry{`,
+ `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`,
+ `Action:` + fmt.Sprintf("%v", this.Action) + `,`,
+ `Filters:` + strings.Replace(fmt.Sprintf("%v", this.Filters), "SelectBy", "SelectBy", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *WatchMessage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&WatchMessage{`,
+ `Events:` + strings.Replace(fmt.Sprintf("%v", this.Events), "WatchMessage_Event", "WatchMessage_Event", 1) + `,`,
+ `Version:` + strings.Replace(fmt.Sprintf("%v", this.Version), "Version", "Version", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *WatchMessage_Event) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&WatchMessage_Event{`,
+ `Action:` + fmt.Sprintf("%v", this.Action) + `,`,
+ `Object:` + strings.Replace(fmt.Sprintf("%v", this.Object), "Object", "Object", 1) + `,`,
+ `OldObject:` + strings.Replace(fmt.Sprintf("%v", this.OldObject), "Object", "Object", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringWatch(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *Object) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Object: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Object: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Node", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Node{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Object = &Object_Node{v}
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Service", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Service{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Object = &Object_Service{v}
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Network", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Network{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Object = &Object_Network{v}
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Task", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Task{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Object = &Object_Task{v}
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Cluster", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Cluster{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Object = &Object_Cluster{v}
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Secret", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Secret{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Object = &Object_Secret{v}
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Resource{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Object = &Object_Resource{v}
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Extension", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Extension{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Object = &Object_Extension{v}
+ iNdEx = postIndex
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Config", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Config{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Object = &Object_Config{v}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWatch(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWatch
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SelectBySlot) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SelectBySlot: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SelectBySlot: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.ServiceID = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Slot", wireType)
+ }
+ m.Slot = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Slot |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWatch(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWatch
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SelectByCustom) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SelectByCustom: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SelectByCustom: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Kind = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Index = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Value = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWatch(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWatch
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *SelectBy) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: SelectBy: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: SelectBy: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.By = &SelectBy_ID{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IDPrefix", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.By = &SelectBy_IDPrefix{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.By = &SelectBy_Name{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NamePrefix", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.By = &SelectBy_NamePrefix{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Custom", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &SelectByCustom{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.By = &SelectBy_Custom{v}
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CustomPrefix", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &SelectByCustom{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.By = &SelectBy_CustomPrefix{v}
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.By = &SelectBy_ServiceID{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.By = &SelectBy_NodeID{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Slot", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &SelectBySlot{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.By = &SelectBy_Slot{v}
+ iNdEx = postIndex
+ case 10:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field DesiredState", wireType)
+ }
+ var v TaskState
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (TaskState(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.By = &SelectBy_DesiredState{v}
+ case 11:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Role", wireType)
+ }
+ var v NodeRole
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (NodeRole(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.By = &SelectBy_Role{v}
+ case 12:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Membership", wireType)
+ }
+ var v NodeSpec_Membership
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (NodeSpec_Membership(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.By = &SelectBy_Membership{v}
+ case 13:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ReferencedNetworkID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.By = &SelectBy_ReferencedNetworkID{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 14:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ReferencedSecretID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.By = &SelectBy_ReferencedSecretID{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 15:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.By = &SelectBy_Kind{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 16:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ReferencedConfigID", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.By = &SelectBy_ReferencedConfigID{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWatch(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWatch
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *WatchRequest) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: WatchRequest: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: WatchRequest: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Entries", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Entries = append(m.Entries, &WatchRequest_WatchEntry{})
+ if err := m.Entries[len(m.Entries)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ResumeFrom", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.ResumeFrom == nil {
+ m.ResumeFrom = &Version{}
+ }
+ if err := m.ResumeFrom.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IncludeOldObject", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.IncludeOldObject = bool(v != 0)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWatch(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWatch
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *WatchRequest_WatchEntry) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: WatchEntry: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: WatchEntry: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Kind = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Action", wireType)
+ }
+ m.Action = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Action |= (WatchActionKind(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Filters", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Filters = append(m.Filters, &SelectBy{})
+ if err := m.Filters[len(m.Filters)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWatch(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWatch
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *WatchMessage) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: WatchMessage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: WatchMessage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Events", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Events = append(m.Events, &WatchMessage_Event{})
+ if err := m.Events[len(m.Events)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Version == nil {
+ m.Version = &Version{}
+ }
+ if err := m.Version.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWatch(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWatch
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *WatchMessage_Event) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Event: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Event: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Action", wireType)
+ }
+ m.Action = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Action |= (WatchActionKind(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Object", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Object == nil {
+ m.Object = &Object{}
+ }
+ if err := m.Object.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field OldObject", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWatch
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.OldObject == nil {
+ m.OldObject = &Object{}
+ }
+ if err := m.OldObject.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWatch(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWatch
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipWatch(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthWatch
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWatch
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipWatch(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthWatch = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowWatch = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("watch.proto", fileDescriptorWatch) }
+
+var fileDescriptorWatch = []byte{
+ // 1155 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x96, 0xbb, 0x73, 0x1b, 0xd5,
+ 0x17, 0xc7, 0xb5, 0x8a, 0xbc, 0x92, 0x8e, 0xac, 0xc4, 0x73, 0xed, 0x24, 0xfb, 0xd3, 0x2f, 0x48,
+ 0x42, 0x0c, 0xe0, 0x21, 0x41, 0x01, 0x13, 0xc2, 0x00, 0x81, 0x19, 0x4b, 0x16, 0x23, 0x91, 0xb1,
+ 0xec, 0xb9, 0xb6, 0xe3, 0x52, 0xb3, 0xde, 0x3d, 0x56, 0x16, 0xed, 0x43, 0xdc, 0x5d, 0xc9, 0x71,
+ 0x47, 0x41, 0xc1, 0xa4, 0x67, 0x86, 0x26, 0x15, 0xd4, 0x34, 0x74, 0xf0, 0x0f, 0x64, 0xa8, 0x28,
+ 0xa1, 0xd1, 0x10, 0x95, 0x14, 0xfc, 0x05, 0x14, 0xcc, 0x7d, 0xac, 0x1f, 0xca, 0xca, 0x21, 0x95,
+ 0xee, 0xbd, 0xfb, 0xf9, 0x9e, 0x7b, 0xf6, 0xbc, 0x56, 0x50, 0x38, 0x32, 0x23, 0xeb, 0x61, 0x7d,
+ 0xc8, 0x82, 0x28, 0x20, 0xc4, 0x0e, 0xac, 0x01, 0xb2, 0x7a, 0x78, 0x64, 0x32, 0x6f, 0xe0, 0x44,
+ 0xf5, 0xf1, 0xbb, 0xa5, 0x42, 0x38, 0x44, 0x2b, 0x94, 0x40, 0xa9, 0x18, 0x1c, 0x7c, 0x81, 0x56,
+ 0x14, 0x6f, 0x0b, 0xd1, 0xf1, 0x10, 0xe3, 0xcd, 0x4a, 0x3f, 0xe8, 0x07, 0x62, 0x79, 0x9b, 0xaf,
+ 0xd4, 0xe9, 0xf2, 0xd0, 0x1d, 0xf5, 0x1d, 0xff, 0xb6, 0xfc, 0x91, 0x87, 0xb5, 0xaf, 0x33, 0xa0,
+ 0x6f, 0x09, 0x4b, 0xa4, 0x0e, 0x19, 0x3f, 0xb0, 0xd1, 0xd0, 0xaa, 0xda, 0x6a, 0x61, 0xcd, 0xa8,
+ 0x3f, 0xef, 0x41, 0xbd, 0x1b, 0xd8, 0xd8, 0x4e, 0x51, 0xc1, 0x91, 0x0f, 0x20, 0x1b, 0x22, 0x1b,
+ 0x3b, 0x16, 0x1a, 0x69, 0x21, 0xf9, 0x7f, 0x92, 0x64, 0x47, 0x22, 0xed, 0x14, 0x8d, 0x69, 0x2e,
+ 0xf4, 0x31, 0x3a, 0x0a, 0xd8, 0xc0, 0xb8, 0x34, 0x5f, 0xd8, 0x95, 0x08, 0x17, 0x2a, 0x9a, 0x7b,
+ 0x18, 0x99, 0xe1, 0xc0, 0xc8, 0xcc, 0xf7, 0x70, 0xd7, 0x0c, 0xb9, 0x44, 0x70, 0xfc, 0x22, 0xcb,
+ 0x1d, 0x85, 0x11, 0x32, 0x63, 0x61, 0xfe, 0x45, 0x4d, 0x89, 0xf0, 0x8b, 0x14, 0x4d, 0xee, 0x80,
+ 0x1e, 0xa2, 0xc5, 0x30, 0x32, 0x74, 0xa1, 0x2b, 0x25, 0xbf, 0x19, 0x27, 0xda, 0x29, 0xaa, 0x58,
+ 0xf2, 0x11, 0xe4, 0x18, 0x86, 0xc1, 0x88, 0x59, 0x68, 0x64, 0x85, 0xee, 0x46, 0x92, 0x8e, 0x2a,
+ 0xa6, 0x9d, 0xa2, 0x27, 0x3c, 0xf9, 0x04, 0xf2, 0xf8, 0x28, 0x42, 0x3f, 0x74, 0x02, 0xdf, 0xc8,
+ 0x09, 0xf1, 0x2b, 0x49, 0xe2, 0x56, 0x0c, 0xb5, 0x53, 0xf4, 0x54, 0xc1, 0x1d, 0xb6, 0x02, 0xff,
+ 0xd0, 0xe9, 0x1b, 0xf9, 0xf9, 0x0e, 0x37, 0x05, 0xc1, 0x1d, 0x96, 0x6c, 0x23, 0x17, 0xe7, 0xbe,
+ 0xb6, 0x0d, 0x8b, 0x3b, 0xe8, 0xa2, 0x15, 0x35, 0x8e, 0x77, 0xdc, 0x20, 0x22, 0xb7, 0x00, 0x54,
+ 0xb6, 0x7a, 0x8e, 0x2d, 0x2a, 0x22, 0xdf, 0x28, 0x4e, 0x27, 0x95, 0xbc, 0x4a, 0x67, 0x67, 0x83,
+ 0xe6, 0x15, 0xd0, 0xb1, 0x09, 0x81, 0x4c, 0xe8, 0x06, 0x91, 0x28, 0x83, 0x0c, 0x15, 0xeb, 0xda,
+ 0x36, 0x5c, 0x8e, 0x2d, 0x36, 0x47, 0x61, 0x14, 0x78, 0x9c, 0x1a, 0x38, 0xbe, 0xb2, 0x46, 0xc5,
+ 0x9a, 0xac, 0xc0, 0x82, 0xe3, 0xdb, 0xf8, 0x48, 0x48, 0xf3, 0x54, 0x6e, 0xf8, 0xe9, 0xd8, 0x74,
+ 0x47, 0x28, 0xca, 0x23, 0x4f, 0xe5, 0xa6, 0xf6, 0x97, 0x0e, 0xb9, 0xd8, 0x24, 0x31, 0x20, 0x7d,
+ 0xe2, 0x98, 0x3e, 0x9d, 0x54, 0xd2, 0x9d, 0x8d, 0x76, 0x8a, 0xa6, 0x1d, 0x9b, 0xdc, 0x84, 0xbc,
+ 0x63, 0xf7, 0x86, 0x0c, 0x0f, 0x1d, 0x65, 0xb6, 0xb1, 0x38, 0x9d, 0x54, 0x72, 0x9d, 0x8d, 0x6d,
+ 0x71, 0xc6, 0xc3, 0xee, 0xd8, 0x72, 0x4d, 0x56, 0x20, 0xe3, 0x9b, 0x9e, 0xba, 0x48, 0x54, 0xb6,
+ 0xe9, 0x21, 0x79, 0x15, 0x0a, 0xfc, 0x37, 0x36, 0x92, 0x51, 0x0f, 0x81, 0x1f, 0x2a, 0xe1, 0x3d,
+ 0xd0, 0x2d, 0xf1, 0x5a, 0xaa, 0xb2, 0x6a, 0xc9, 0x15, 0x72, 0x36, 0x00, 0x22, 0xf0, 0x32, 0x14,
+ 0x1d, 0x28, 0xca, 0x55, 0x7c, 0x85, 0xfe, 0x12, 0x46, 0x16, 0xa5, 0x54, 0x39, 0x52, 0x3f, 0x97,
+ 0xa9, 0x6c, 0x42, 0xa6, 0x78, 0xa5, 0x9c, 0xe6, 0xea, 0x75, 0xc8, 0xf2, 0xee, 0xe5, 0x70, 0x4e,
+ 0xc0, 0x30, 0x9d, 0x54, 0x74, 0xde, 0xd8, 0x82, 0xd4, 0xf9, 0xc3, 0x8e, 0x4d, 0xee, 0xaa, 0x94,
+ 0xca, 0x72, 0xaa, 0x5e, 0xe4, 0x18, 0x2f, 0x18, 0x1e, 0x3a, 0xce, 0x93, 0x0d, 0x28, 0xda, 0x18,
+ 0x3a, 0x0c, 0xed, 0x5e, 0x18, 0x99, 0x11, 0x1a, 0x50, 0xd5, 0x56, 0x2f, 0x27, 0xd7, 0x32, 0xef,
+ 0xd5, 0x1d, 0x0e, 0xf1, 0x97, 0x52, 0x2a, 0xb1, 0x27, 0x6b, 0x90, 0x61, 0x81, 0x8b, 0x46, 0x41,
+ 0x88, 0x6f, 0xcc, 0x1b, 0x45, 0x34, 0x70, 0xc5, 0x38, 0xe2, 0x2c, 0xe9, 0x00, 0x78, 0xe8, 0x1d,
+ 0x20, 0x0b, 0x1f, 0x3a, 0x43, 0x63, 0x51, 0x28, 0xdf, 0x9c, 0xa7, 0xdc, 0x19, 0xa2, 0x55, 0xdf,
+ 0x3c, 0xc1, 0x79, 0x72, 0x4f, 0xc5, 0x64, 0x13, 0xae, 0x32, 0x3c, 0x44, 0x86, 0xbe, 0x85, 0x76,
+ 0x4f, 0x4d, 0x1f, 0x1e, 0xb1, 0xa2, 0x88, 0xd8, 0xf5, 0xe9, 0xa4, 0xb2, 0x4c, 0x4f, 0x00, 0x35,
+ 0xa8, 0x44, 0xf8, 0x96, 0xd9, 0x73, 0xc7, 0x36, 0xf9, 0x1c, 0x56, 0xce, 0x98, 0x93, 0xc3, 0x82,
+ 0x5b, 0xbb, 0x2c, 0xac, 0x5d, 0x9b, 0x4e, 0x2a, 0xe4, 0xd4, 0x9a, 0x9c, 0x2a, 0xc2, 0x18, 0x61,
+ 0xb3, 0xa7, 0xbc, 0x61, 0x64, 0x13, 0x5d, 0x89, 0x0b, 0x56, 0xb4, 0xd1, 0xf9, 0x1b, 0x64, 0x77,
+ 0xf3, 0x1b, 0x96, 0x92, 0x6e, 0x90, 0x63, 0x60, 0xf6, 0x06, 0x75, 0x6a, 0x37, 0x32, 0x90, 0x6e,
+ 0x1c, 0xd7, 0xfe, 0x48, 0xc3, 0xe2, 0x3e, 0xff, 0x1e, 0x51, 0xfc, 0x72, 0x84, 0x61, 0x44, 0x5a,
+ 0x90, 0x45, 0x3f, 0x62, 0x0e, 0x86, 0x86, 0x56, 0xbd, 0xb4, 0x5a, 0x58, 0xbb, 0x99, 0x14, 0xdb,
+ 0xb3, 0x12, 0xb9, 0x69, 0xf9, 0x11, 0x3b, 0xa6, 0xb1, 0x96, 0xdc, 0x83, 0x02, 0xc3, 0x70, 0xe4,
+ 0x61, 0xef, 0x90, 0x05, 0xde, 0x45, 0x1f, 0x8e, 0x07, 0xc8, 0xf8, 0x68, 0xa3, 0x20, 0xf9, 0xcf,
+ 0x58, 0xe0, 0x91, 0x5b, 0x40, 0x1c, 0xdf, 0x72, 0x47, 0x36, 0xf6, 0x02, 0xd7, 0xee, 0xc9, 0x4f,
+ 0xa0, 0x68, 0xde, 0x1c, 0x5d, 0x52, 0x4f, 0xb6, 0x5c, 0x5b, 0x0e, 0xb5, 0xd2, 0xb7, 0x1a, 0xc0,
+ 0xa9, 0x0f, 0x89, 0xf3, 0xe7, 0x63, 0xd0, 0x4d, 0x2b, 0xe2, 0x33, 0x37, 0x2d, 0x0a, 0xe6, 0xb5,
+ 0xb9, 0x2f, 0xb5, 0x2e, 0xb0, 0xfb, 0x8e, 0x6f, 0x53, 0x25, 0x21, 0x77, 0x21, 0x7b, 0xe8, 0xb8,
+ 0x11, 0xb2, 0xd0, 0xb8, 0x24, 0x42, 0x72, 0xe3, 0xa2, 0x36, 0xa1, 0x31, 0x5c, 0xfb, 0x25, 0x8e,
+ 0xed, 0x26, 0x86, 0xa1, 0xd9, 0x47, 0xf2, 0x29, 0xe8, 0x38, 0x46, 0x3f, 0x8a, 0x43, 0xfb, 0xc6,
+ 0x5c, 0x2f, 0x94, 0xa2, 0xde, 0xe2, 0x38, 0x55, 0x2a, 0xf2, 0x3e, 0x64, 0xc7, 0x32, 0x5a, 0xff,
+ 0x25, 0xa0, 0x31, 0x5b, 0xfa, 0x49, 0x83, 0x05, 0x61, 0xe8, 0x4c, 0x18, 0xb4, 0x97, 0x0f, 0xc3,
+ 0x1a, 0xe8, 0x2a, 0x11, 0xe9, 0xf9, 0xdf, 0x1e, 0x99, 0x12, 0xaa, 0x48, 0xf2, 0x21, 0xc0, 0x4c,
+ 0x02, 0x2f, 0xd6, 0xe5, 0x83, 0x38, 0xab, 0x6f, 0xfd, 0xa3, 0xc1, 0x95, 0x19, 0x57, 0xc8, 0x1d,
+ 0x58, 0xd9, 0x5f, 0xdf, 0x6d, 0xb6, 0x7b, 0xeb, 0xcd, 0xdd, 0xce, 0x56, 0xb7, 0xb7, 0xd7, 0xbd,
+ 0xdf, 0xdd, 0xda, 0xef, 0x2e, 0xa5, 0x4a, 0xa5, 0xc7, 0x4f, 0xaa, 0xd7, 0x66, 0xf0, 0x3d, 0x7f,
+ 0xe0, 0x07, 0x47, 0xdc, 0xf1, 0xe5, 0x73, 0xaa, 0x26, 0x6d, 0xad, 0xef, 0xb6, 0x96, 0xb4, 0xd2,
+ 0xff, 0x1e, 0x3f, 0xa9, 0x5e, 0x9d, 0x11, 0x35, 0x19, 0xca, 0xc9, 0x74, 0x5e, 0xb3, 0xb7, 0xbd,
+ 0xc1, 0x35, 0xe9, 0x44, 0xcd, 0xde, 0xd0, 0x4e, 0xd2, 0xd0, 0xd6, 0xe6, 0xd6, 0x83, 0xd6, 0x52,
+ 0x26, 0x51, 0x43, 0xd1, 0x0b, 0xc6, 0x58, 0xba, 0xfe, 0xcd, 0xf7, 0xe5, 0xd4, 0xcf, 0x3f, 0x94,
+ 0x67, 0x5f, 0x75, 0xcd, 0x83, 0x05, 0x71, 0x44, 0xec, 0x78, 0x51, 0x7d, 0x51, 0x23, 0x96, 0xaa,
+ 0x2f, 0xaa, 0xa7, 0xda, 0xd5, 0x5f, 0x7f, 0xfc, 0xfb, 0xbb, 0xf4, 0x15, 0x28, 0x0a, 0xe2, 0x6d,
+ 0xcf, 0xf4, 0xcd, 0x3e, 0xb2, 0x77, 0xb4, 0x86, 0xf1, 0xf4, 0x59, 0x39, 0xf5, 0xfb, 0xb3, 0x72,
+ 0xea, 0xab, 0x69, 0x59, 0x7b, 0x3a, 0x2d, 0x6b, 0xbf, 0x4d, 0xcb, 0xda, 0x9f, 0xd3, 0xb2, 0x76,
+ 0xa0, 0x8b, 0x3f, 0x90, 0xef, 0xfd, 0x1b, 0x00, 0x00, 0xff, 0xff, 0xf8, 0x53, 0xd9, 0x73, 0xb7,
+ 0x0a, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/api/watch.proto b/vendor/github.com/docker/swarmkit/api/watch.proto
new file mode 100644
index 0000000..f84fd9e
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/api/watch.proto
@@ -0,0 +1,154 @@
+syntax = "proto3";
+
+package docker.swarmkit.v1;
+
+import "specs.proto";
+import "objects.proto";
+import "types.proto";
+import "gogoproto/gogo.proto";
+import "plugin/plugin.proto";
+
+message Object {
+ oneof Object {
+ Node node = 1;
+ Service service = 2;
+ Network network = 3;
+ Task task = 4;
+ Cluster cluster = 5;
+ Secret secret = 6;
+ Resource resource = 7;
+ Extension extension = 8;
+ Config config = 9;
+ }
+}
+
+// FIXME(aaronl): These messages should ideally be embedded in SelectBy, but
+// protoc generates bad code for that.
+message SelectBySlot {
+ string service_id = 1 [(gogoproto.customname) = "ServiceID"];
+ uint64 slot = 2;
+}
+
+message SelectByCustom {
+ string kind = 1;
+ string index = 2;
+ string value = 3;
+}
+
+message SelectBy {
+ // TODO(aaronl): Are all of these things we want to expose in
+ // the API? Exposing them may commit us to maintaining those
+ // internal indices going forward.
+ oneof By {
+ // supported by all object types
+ string id = 1 [(gogoproto.customname) = "ID"]; // not applicable for FindObjects - use GetObject instead
+ string id_prefix = 2 [(gogoproto.customname) = "IDPrefix"];
+ string name = 3;
+ string name_prefix = 4;
+ SelectByCustom custom = 5;
+ SelectByCustom custom_prefix = 6;
+
+ // supported by tasks only
+ string service_id = 7 [(gogoproto.customname) = "ServiceID"];
+ string node_id = 8 [(gogoproto.customname) = "NodeID"];
+ SelectBySlot slot = 9;
+ TaskState desired_state = 10;
+
+ // supported by nodes only
+ NodeRole role = 11;
+ NodeSpec.Membership membership = 12;
+
+ // supported by: service, task
+ string referenced_network_id = 13 [(gogoproto.customname) = "ReferencedNetworkID"];
+ string referenced_secret_id = 14 [(gogoproto.customname) = "ReferencedSecretID"];
+ string referenced_config_id = 16 [(gogoproto.customname) = "ReferencedConfigID"];
+
+ // supported by: resource
+ string kind = 15;
+ }
+}
+
+
+// Watch defines the RPC methods for monitoring data store change.
+service Watch {
+ // Watch starts a stream that returns any changes to objects that match
+ // the specified selectors. When the stream begins, it immediately sends
+ // an empty message back to the client. It is important to wait for
+ // this message before taking any actions that depend on an established
+ // stream of changes for consistency.
+ rpc Watch(WatchRequest) returns (stream WatchMessage) {
+ option (docker.protobuf.plugin.tls_authorization) = { roles: "swarm-manager" };
+ };
+}
+
+message WatchRequest {
+ message WatchEntry {
+ // Kind can contain a builtin type such as "node", "secret", etc. or
+ // the kind specified by a custom-defined object.
+ string kind = 1;
+
+ // Action (create/update/delete)
+ // This is a bitmask, so multiple actions may be OR'd together
+ WatchActionKind action = 2;
+
+ // Filters are combined using AND logic - an event must match
+ // all of them to pass the filter.
+ repeated SelectBy filters = 3;
+ }
+
+ // Multiple entries are combined using OR logic - i.e. if an event
+ // matches all of the selectors specified in any single watch entry,
+ // the event will be sent to the client.
+ repeated WatchEntry entries = 1;
+
+ // ResumeFrom provides an version to resume the watch from, if non-nil.
+ // The watch will return changes since this version, and continue to
+ // return new changes afterwards. Watch will return an error if the
+ // server has compacted its log and no longer has complete history to
+ // this point.
+ Version resume_from = 2;
+
+ // IncludeOldObject causes WatchMessages to include a copy of the
+ // previous version of the object on updates. Note that only live
+ // changes will include the old object (not historical changes
+ // retrieved using ResumeFrom).
+ bool include_old_object = 3;
+}
+
+// WatchMessage is the type of the stream that's returned to the client by
+// Watch. Note that the first item of this stream will always be a WatchMessage
+// with a nil Object, to signal that the stream has started.
+message WatchMessage {
+ message Event {
+ // Action (create/update/delete)
+ // Note that WatchMessage does not expose "commit" events that
+ // mark transaction boundaries.
+ WatchActionKind action = 1;
+
+ // Matched object
+ Object object = 2;
+
+ // For updates, OldObject will optionally be included in the
+ // watch message, containing the previous version of the
+ // object, if IncludeOldObject was set in WatchRequest.
+ Object old_object = 3;
+ }
+
+ repeated Event events = 1;
+
+ // Index versions this change to the data store. It can be used to
+ // resume the watch from this point.
+ Version version = 2;
+}
+
+// WatchActionKind distinguishes between creations, updates, and removals. It
+// is structured as a bitmap so multiple kinds of events can be requested with
+// a mask.
+enum WatchActionKind {
+ option (gogoproto.goproto_enum_prefix) = false;
+ option (gogoproto.enum_customname) = "WatchActionKind";
+ WATCH_ACTION_UNKNOWN = 0 [(gogoproto.enumvalue_customname) = "WatchActionKindUnknown"]; // default value, invalid
+ WATCH_ACTION_CREATE = 1 [(gogoproto.enumvalue_customname) = "WatchActionKindCreate"];
+ WATCH_ACTION_UPDATE = 2 [(gogoproto.enumvalue_customname) = "WatchActionKindUpdate"];
+ WATCH_ACTION_REMOVE = 4 [(gogoproto.enumvalue_customname) = "WatchActionKindRemove"];
+}
diff --git a/vendor/github.com/docker/swarmkit/ca/auth.go b/vendor/github.com/docker/swarmkit/ca/auth.go
new file mode 100644
index 0000000..10cb2c7
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ca/auth.go
@@ -0,0 +1,247 @@
+package ca
+
+import (
+ "crypto/tls"
+ "crypto/x509/pkix"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/peer"
+)
+
+type localRequestKeyType struct{}
+
+// LocalRequestKey is a context key to mark a request that originating on the
+// local node. The associated value is a RemoteNodeInfo structure describing the
+// local node.
+var LocalRequestKey = localRequestKeyType{}
+
+// LogTLSState logs information about the TLS connection and remote peers
+func LogTLSState(ctx context.Context, tlsState *tls.ConnectionState) {
+ if tlsState == nil {
+ log.G(ctx).Debugf("no TLS Chains found")
+ return
+ }
+
+ peerCerts := []string{}
+ verifiedChain := []string{}
+ for _, cert := range tlsState.PeerCertificates {
+ peerCerts = append(peerCerts, cert.Subject.CommonName)
+ }
+ for _, chain := range tlsState.VerifiedChains {
+ subjects := []string{}
+ for _, cert := range chain {
+ subjects = append(subjects, cert.Subject.CommonName)
+ }
+ verifiedChain = append(verifiedChain, strings.Join(subjects, ","))
+ }
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "peer.peerCert": peerCerts,
+ // "peer.verifiedChain": verifiedChain},
+ }).Debugf("")
+}
+
+// getCertificateSubject extracts the subject from a verified client certificate
+func getCertificateSubject(tlsState *tls.ConnectionState) (pkix.Name, error) {
+ if tlsState == nil {
+ return pkix.Name{}, grpc.Errorf(codes.PermissionDenied, "request is not using TLS")
+ }
+ if len(tlsState.PeerCertificates) == 0 {
+ return pkix.Name{}, grpc.Errorf(codes.PermissionDenied, "no client certificates in request")
+ }
+ if len(tlsState.VerifiedChains) == 0 {
+ return pkix.Name{}, grpc.Errorf(codes.PermissionDenied, "no verified chains for remote certificate")
+ }
+
+ return tlsState.VerifiedChains[0][0].Subject, nil
+}
+
+func tlsConnStateFromContext(ctx context.Context) (*tls.ConnectionState, error) {
+ peer, ok := peer.FromContext(ctx)
+ if !ok {
+ return nil, grpc.Errorf(codes.PermissionDenied, "Permission denied: no peer info")
+ }
+ tlsInfo, ok := peer.AuthInfo.(credentials.TLSInfo)
+ if !ok {
+ return nil, grpc.Errorf(codes.PermissionDenied, "Permission denied: peer didn't not present valid peer certificate")
+ }
+ return &tlsInfo.State, nil
+}
+
+// certSubjectFromContext extracts pkix.Name from context.
+func certSubjectFromContext(ctx context.Context) (pkix.Name, error) {
+ connState, err := tlsConnStateFromContext(ctx)
+ if err != nil {
+ return pkix.Name{}, err
+ }
+ return getCertificateSubject(connState)
+}
+
+// AuthorizeOrgAndRole takes in a context and a list of roles, and returns
+// the Node ID of the node.
+func AuthorizeOrgAndRole(ctx context.Context, org string, blacklistedCerts map[string]*api.BlacklistedCertificate, ou ...string) (string, error) {
+ certSubj, err := certSubjectFromContext(ctx)
+ if err != nil {
+ return "", err
+ }
+ // Check if the current certificate has an OU that authorizes
+ // access to this method
+ if intersectArrays(certSubj.OrganizationalUnit, ou) {
+ return authorizeOrg(certSubj, org, blacklistedCerts)
+ }
+
+ return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: remote certificate not part of OUs: %v", ou)
+}
+
+// authorizeOrg takes in a certificate subject and an organization, and returns
+// the Node ID of the node.
+func authorizeOrg(certSubj pkix.Name, org string, blacklistedCerts map[string]*api.BlacklistedCertificate) (string, error) {
+ if _, ok := blacklistedCerts[certSubj.CommonName]; ok {
+ return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: node %s was removed from swarm", certSubj.CommonName)
+ }
+
+ if len(certSubj.Organization) > 0 && certSubj.Organization[0] == org {
+ return certSubj.CommonName, nil
+ }
+
+ return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: remote certificate not part of organization: %s", org)
+}
+
+// AuthorizeForwardedRoleAndOrg checks for proper roles and organization of caller. The RPC may have
+// been proxied by a manager, in which case the manager is authenticated and
+// so is the certificate information that it forwarded. It returns the node ID
+// of the original client.
+func AuthorizeForwardedRoleAndOrg(ctx context.Context, authorizedRoles, forwarderRoles []string, org string, blacklistedCerts map[string]*api.BlacklistedCertificate) (string, error) {
+ if isForwardedRequest(ctx) {
+ _, err := AuthorizeOrgAndRole(ctx, org, blacklistedCerts, forwarderRoles...)
+ if err != nil {
+ return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarder role: %v", err)
+ }
+
+ // This was a forwarded request. Authorize the forwarder, and
+ // check if the forwarded role matches one of the authorized
+ // roles.
+ _, forwardedID, forwardedOrg, forwardedOUs := forwardedTLSInfoFromContext(ctx)
+
+ if len(forwardedOUs) == 0 || forwardedID == "" || forwardedOrg == "" {
+ return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: missing information in forwarded request")
+ }
+
+ if !intersectArrays(forwardedOUs, authorizedRoles) {
+ return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: unauthorized forwarded role, expecting: %v", authorizedRoles)
+ }
+
+ if forwardedOrg != org {
+ return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: organization mismatch, expecting: %s", org)
+ }
+
+ return forwardedID, nil
+ }
+
+ // There wasn't any node being forwarded, check if this is a direct call by the expected role
+ nodeID, err := AuthorizeOrgAndRole(ctx, org, blacklistedCerts, authorizedRoles...)
+ if err == nil {
+ return nodeID, nil
+ }
+
+ return "", grpc.Errorf(codes.PermissionDenied, "Permission denied: unauthorized peer role: %v", err)
+}
+
+// intersectArrays returns true when there is at least one element in common
+// between the two arrays
+func intersectArrays(orig, tgt []string) bool {
+ for _, i := range orig {
+ for _, x := range tgt {
+ if i == x {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// RemoteNodeInfo describes a node sending an RPC request.
+type RemoteNodeInfo struct {
+ // Roles is a list of roles contained in the node's certificate
+ // (or forwarded by a trusted node).
+ Roles []string
+
+ // Organization is the organization contained in the node's certificate
+ // (or forwarded by a trusted node).
+ Organization string
+
+ // NodeID is the node's ID, from the CN field in its certificate
+ // (or forwarded by a trusted node).
+ NodeID string
+
+ // ForwardedBy contains information for the node that forwarded this
+ // request. It is set to nil if the request was received directly.
+ ForwardedBy *RemoteNodeInfo
+
+ // RemoteAddr is the address that this node is connecting to the cluster
+ // from.
+ RemoteAddr string
+}
+
+// RemoteNode returns the node ID and role from the client's TLS certificate.
+// If the RPC was forwarded, the original client's ID and role is returned, as
+// well as the forwarder's ID. This function does not do authorization checks -
+// it only looks up the node ID.
+func RemoteNode(ctx context.Context) (RemoteNodeInfo, error) {
+ // If we have a value on the context that marks this as a local
+ // request, we return the node info from the context.
+ localNodeInfo := ctx.Value(LocalRequestKey)
+
+ if localNodeInfo != nil {
+ nodeInfo, ok := localNodeInfo.(RemoteNodeInfo)
+ if ok {
+ return nodeInfo, nil
+ }
+ }
+
+ certSubj, err := certSubjectFromContext(ctx)
+ if err != nil {
+ return RemoteNodeInfo{}, err
+ }
+
+ org := ""
+ if len(certSubj.Organization) > 0 {
+ org = certSubj.Organization[0]
+ }
+
+ peer, ok := peer.FromContext(ctx)
+ if !ok {
+ return RemoteNodeInfo{}, grpc.Errorf(codes.PermissionDenied, "Permission denied: no peer info")
+ }
+
+ directInfo := RemoteNodeInfo{
+ Roles: certSubj.OrganizationalUnit,
+ NodeID: certSubj.CommonName,
+ Organization: org,
+ RemoteAddr: peer.Addr.String(),
+ }
+
+ if isForwardedRequest(ctx) {
+ remoteAddr, cn, org, ous := forwardedTLSInfoFromContext(ctx)
+ if len(ous) == 0 || cn == "" || org == "" {
+ return RemoteNodeInfo{}, grpc.Errorf(codes.PermissionDenied, "Permission denied: missing information in forwarded request")
+ }
+ return RemoteNodeInfo{
+ Roles: ous,
+ NodeID: cn,
+ Organization: org,
+ ForwardedBy: &directInfo,
+ RemoteAddr: remoteAddr,
+ }, nil
+ }
+
+ return directInfo, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/ca/certificates.go b/vendor/github.com/docker/swarmkit/ca/certificates.go
new file mode 100644
index 0000000..7a638fe
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ca/certificates.go
@@ -0,0 +1,1008 @@
+package ca
+
+import (
+ "bytes"
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ cryptorand "crypto/rand"
+ "crypto/rsa"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/asn1"
+ "encoding/pem"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "time"
+
+ cfcsr "github.com/cloudflare/cfssl/csr"
+ "github.com/cloudflare/cfssl/helpers"
+ "github.com/cloudflare/cfssl/initca"
+ cflog "github.com/cloudflare/cfssl/log"
+ cfsigner "github.com/cloudflare/cfssl/signer"
+ "github.com/cloudflare/cfssl/signer/local"
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/connectionbroker"
+ "github.com/docker/swarmkit/ioutils"
+ "github.com/opencontainers/go-digest"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
+)
+
+const (
+ // Security Strength Equivalence
+ //-----------------------------------
+ //| ECC | DH/DSA/RSA |
+ //| 256 | 3072 |
+ //| 384 | 7680 |
+ //-----------------------------------
+
+ // RootKeySize is the default size of the root CA key
+ // It would be ideal for the root key to use P-384, but in P-384 is not optimized in go yet :(
+ RootKeySize = 256
+ // RootKeyAlgo defines the default algorithm for the root CA Key
+ RootKeyAlgo = "ecdsa"
+ // PassphraseENVVar defines the environment variable to look for the
+ // root CA private key material encryption key
+ PassphraseENVVar = "SWARM_ROOT_CA_PASSPHRASE"
+ // PassphraseENVVarPrev defines the alternate environment variable to look for the
+ // root CA private key material encryption key. It can be used for seamless
+ // KEK rotations.
+ PassphraseENVVarPrev = "SWARM_ROOT_CA_PASSPHRASE_PREV"
+ // RootCAExpiration represents the default expiration for the root CA in seconds (20 years)
+ RootCAExpiration = "630720000s"
+ // DefaultNodeCertExpiration represents the default expiration for node certificates (3 months)
+ DefaultNodeCertExpiration = 2160 * time.Hour
+ // CertBackdate represents the amount of time each certificate is backdated to try to avoid
+ // clock drift issues.
+ CertBackdate = 1 * time.Hour
+ // CertLowerRotationRange represents the minimum fraction of time that we will wait when randomly
+ // choosing our next certificate rotation
+ CertLowerRotationRange = 0.5
+ // CertUpperRotationRange represents the maximum fraction of time that we will wait when randomly
+ // choosing our next certificate rotation
+ CertUpperRotationRange = 0.8
+ // MinNodeCertExpiration represents the minimum expiration for node certificates
+ MinNodeCertExpiration = 1 * time.Hour
+)
+
+// BasicConstraintsOID is the ASN1 Object ID indicating a basic constraints extension
+var BasicConstraintsOID = asn1.ObjectIdentifier{2, 5, 29, 19}
+
+// A recoverableErr is a non-fatal error encountered signing a certificate,
+// which means that the certificate issuance may be retried at a later time.
+type recoverableErr struct {
+ err error
+}
+
+func (r recoverableErr) Error() string {
+ return r.err.Error()
+}
+
+// ErrNoLocalRootCA is an error type used to indicate that the local root CA
+// certificate file does not exist.
+var ErrNoLocalRootCA = errors.New("local root CA certificate does not exist")
+
+// ErrNoValidSigner is an error type used to indicate that our RootCA doesn't have the ability to
+// sign certificates.
+var ErrNoValidSigner = recoverableErr{err: errors.New("no valid signer found")}
+
+func init() {
+ cflog.Level = 5
+}
+
+// CertPaths is a helper struct that keeps track of the paths of a
+// Cert and corresponding Key
+type CertPaths struct {
+ Cert, Key string
+}
+
+// IssuerInfo contains the subject and public key of the issuer of a certificate
+type IssuerInfo struct {
+ Subject []byte
+ PublicKey []byte
+}
+
+// LocalSigner is a signer that can sign CSRs
+type LocalSigner struct {
+ cfsigner.Signer
+
+ // Key will only be used by the original manager to put the private
+ // key-material in raft, no signing operations depend on it.
+ Key []byte
+
+ // Cert is one PEM encoded Certificate used as the signing CA. It must correspond to the key.
+ Cert []byte
+
+ // just cached parsed values for validation, etc.
+ parsedCert *x509.Certificate
+ cryptoSigner crypto.Signer
+}
+
+type x509UnknownAuthError struct {
+ error
+ failedLeafCert *x509.Certificate
+}
+
+// RootCA is the representation of everything we need to sign certificates and/or to verify certificates
+//
+// RootCA.Cert: [CA cert1][CA cert2]
+// RootCA.Intermediates: [intermediate CA1][intermediate CA2][intermediate CA3]
+// RootCA.signer.Cert: [signing CA cert]
+// RootCA.signer.Key: [signing CA key]
+//
+// Requirements:
+//
+// - [signing CA key] must be the private key for [signing CA cert], and either both or none must be provided
+//
+// - [intermediate CA1] must have the same public key and subject as [signing CA cert], because otherwise when
+// appended to a leaf certificate, the intermediates will not form a chain (because [intermediate CA1] won't because
+// the signer of the leaf certificate)
+// - [intermediate CA1] must be signed by [intermediate CA2], which must be signed by [intermediate CA3]
+//
+// - When we issue a certificate, the intermediates will be appended so that the certificate looks like:
+// [leaf signed by signing CA cert][intermediate CA1][intermediate CA2][intermediate CA3]
+// - [leaf signed by signing CA cert][intermediate CA1][intermediate CA2][intermediate CA3] is guaranteed to form a
+// valid chain from [leaf signed by signing CA cert] to one of the root certs ([signing CA cert], [CA cert1], [CA cert2])
+// using zero or more of the intermediate certs ([intermediate CA1][intermediate CA2][intermediate CA3]) as intermediates
+//
+// Example 1: Simple root rotation
+// - Initial state:
+// - RootCA.Cert: [Root CA1 self-signed]
+// - RootCA.Intermediates: []
+// - RootCA.signer.Cert: [Root CA1 self-signed]
+// - Issued TLS cert: [leaf signed by Root CA1]
+//
+// - Intermediate state (during root rotation):
+// - RootCA.Cert: [Root CA1 self-signed]
+// - RootCA.Intermediates: [Root CA2 signed by Root CA1]
+// - RootCA.signer.Cert: [Root CA2 signed by Root CA1]
+// - Issued TLS cert: [leaf signed by Root CA2][Root CA2 signed by Root CA1]
+//
+// - Final state:
+// - RootCA.Cert: [Root CA2 self-signed]
+// - RootCA.Intermediates: []
+// - RootCA.signer.Cert: [Root CA2 self-signed]
+// - Issued TLS cert: [leaf signed by Root CA2]
+//
+type RootCA struct {
+ // Certs contains a bundle of self-signed, PEM encoded certificates for the Root CA to be used
+ // as the root of trust.
+ Certs []byte
+
+ // Intermediates contains a bundle of PEM encoded intermediate CA certificates to append to any
+ // issued TLS (leaf) certificates. The first one must have the same public key and subject as the
+ // signing root certificate, and the rest must form a chain, each one certifying the one above it,
+ // as per RFC5246 section 7.4.2.
+ Intermediates []byte
+
+ // Pool is the root pool used to validate TLS certificates
+ Pool *x509.CertPool
+
+ // Digest of the serialized bytes of the certificate(s)
+ Digest digest.Digest
+
+ // This signer will be nil if the node doesn't have the appropriate key material
+ signer *LocalSigner
+}
+
+// Signer is an accessor for the local signer that returns an error if this root cannot sign.
+func (rca *RootCA) Signer() (*LocalSigner, error) {
+ if rca.Pool == nil || rca.signer == nil || len(rca.signer.Cert) == 0 || rca.signer.Signer == nil {
+ return nil, ErrNoValidSigner
+ }
+
+ return rca.signer, nil
+}
+
+// IssueAndSaveNewCertificates generates a new key-pair, signs it with the local root-ca, and returns a
+// TLS certificate and the issuer information for the certificate.
+func (rca *RootCA) IssueAndSaveNewCertificates(kw KeyWriter, cn, ou, org string) (*tls.Certificate, *IssuerInfo, error) {
+ csr, key, err := GenerateNewCSR()
+ if err != nil {
+ return nil, nil, errors.Wrap(err, "error when generating new node certs")
+ }
+
+ // Obtain a signed Certificate
+ certChain, err := rca.ParseValidateAndSignCSR(csr, cn, ou, org)
+ if err != nil {
+ return nil, nil, errors.Wrap(err, "failed to sign node certificate")
+ }
+ signer, err := rca.Signer()
+ if err != nil { // should never happen, since if ParseValidateAndSignCSR did not fail this root CA must have a signer
+ return nil, nil, err
+ }
+
+ // Create a valid TLSKeyPair out of the PEM encoded private key and certificate
+ tlsKeyPair, err := tls.X509KeyPair(certChain, key)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ if err := kw.Write(NormalizePEMs(certChain), key, nil); err != nil {
+ return nil, nil, err
+ }
+
+ return &tlsKeyPair, &IssuerInfo{
+ PublicKey: signer.parsedCert.RawSubjectPublicKeyInfo,
+ Subject: signer.parsedCert.RawSubject,
+ }, nil
+}
+
+// RequestAndSaveNewCertificates gets new certificates issued, either by signing them locally if a signer is
+// available, or by requesting them from the remote server at remoteAddr. This function returns the TLS
+// certificate and the issuer information for the certificate.
+func (rca *RootCA) RequestAndSaveNewCertificates(ctx context.Context, kw KeyWriter, config CertificateRequestConfig) (*tls.Certificate, *IssuerInfo, error) {
+ // Create a new key/pair and CSR
+ csr, key, err := GenerateNewCSR()
+ if err != nil {
+ return nil, nil, errors.Wrap(err, "error when generating new node certs")
+ }
+
+ // Get the remote manager to issue a CA signed certificate for this node
+ // Retry up to 5 times in case the manager we first try to contact isn't
+ // responding properly (for example, it may have just been demoted).
+ var signedCert []byte
+ for i := 0; i != 5; i++ {
+ signedCert, err = GetRemoteSignedCertificate(ctx, csr, rca.Pool, config)
+ if err == nil {
+ break
+ }
+
+ // If the first attempt fails, we should try a remote
+ // connection. The local node may be a manager that was
+ // demoted, so the local connection (which is preferred) may
+ // not work. If we are successful in renewing the certificate,
+ // the local connection will not be returned by the connection
+ // broker anymore.
+ config.ForceRemote = true
+
+ // Wait a moment, in case a leader election was taking place.
+ select {
+ case <-time.After(config.RetryInterval):
+ case <-ctx.Done():
+ return nil, nil, ctx.Err()
+ }
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+
+ // Доверяй, но проверяй.
+ // Before we overwrite our local key + certificate, let's make sure the server gave us one that is valid
+ // Create an X509Cert so we can .Verify()
+ // Check to see if this certificate was signed by our CA, and isn't expired
+ parsedCerts, chains, err := ValidateCertChain(rca.Pool, signedCert, false)
+ // TODO(cyli): - right now we need the invalid certificate in order to determine whether or not we should
+ // download a new root, because we only want to do that in the case of workers. When we have a single
+ // codepath for updating the root CAs for both managers and workers, this snippet can go.
+ if _, ok := err.(x509.UnknownAuthorityError); ok {
+ if parsedCerts, parseErr := helpers.ParseCertificatesPEM(signedCert); parseErr == nil && len(parsedCerts) > 0 {
+ return nil, nil, x509UnknownAuthError{
+ error: err,
+ failedLeafCert: parsedCerts[0],
+ }
+ }
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+
+ // ValidateChain, if successful, will always return at least 1 parsed cert and at least 1 chain containing
+ // at least 2 certificates: the leaf and the root.
+ leafCert := parsedCerts[0]
+ issuer := chains[0][1]
+
+ // Create a valid TLSKeyPair out of the PEM encoded private key and certificate
+ tlsKeyPair, err := tls.X509KeyPair(signedCert, key)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ var kekUpdate *KEKData
+ for i := 0; i < 5; i++ {
+ // ValidateCertChain will always return at least 1 cert, so indexing at 0 is safe
+ kekUpdate, err = rca.getKEKUpdate(ctx, leafCert, tlsKeyPair, config)
+ if err == nil {
+ break
+ }
+
+ config.ForceRemote = true
+
+ // Wait a moment, in case a leader election was taking place.
+ select {
+ case <-time.After(config.RetryInterval):
+ case <-ctx.Done():
+ return nil, nil, ctx.Err()
+ }
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+
+ if err := kw.Write(NormalizePEMs(signedCert), key, kekUpdate); err != nil {
+ return nil, nil, err
+ }
+
+ return &tlsKeyPair, &IssuerInfo{
+ PublicKey: issuer.RawSubjectPublicKeyInfo,
+ Subject: issuer.RawSubject,
+ }, nil
+}
+
+func (rca *RootCA) getKEKUpdate(ctx context.Context, leafCert *x509.Certificate, keypair tls.Certificate, config CertificateRequestConfig) (*KEKData, error) {
+ var managerRole bool
+ for _, ou := range leafCert.Subject.OrganizationalUnit {
+ if ou == ManagerRole {
+ managerRole = true
+ break
+ }
+ }
+
+ if managerRole {
+ mtlsCreds := credentials.NewTLS(&tls.Config{ServerName: CARole, RootCAs: rca.Pool, Certificates: []tls.Certificate{keypair}})
+ conn, err := getGRPCConnection(mtlsCreds, config.ConnBroker, config.ForceRemote)
+ if err != nil {
+ return nil, err
+ }
+
+ client := api.NewCAClient(conn.ClientConn)
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ response, err := client.GetUnlockKey(ctx, &api.GetUnlockKeyRequest{})
+ if err != nil {
+ if grpc.Code(err) == codes.Unimplemented { // if the server does not support keks, return as if no encryption key was specified
+ conn.Close(true)
+ return &KEKData{}, nil
+ }
+
+ conn.Close(false)
+ return nil, err
+ }
+ conn.Close(true)
+ return &KEKData{KEK: response.UnlockKey, Version: response.Version.Index}, nil
+ }
+
+ // If this is a worker, set to never encrypt. We always want to set to the lock key to nil,
+ // in case this was a manager that was demoted to a worker.
+ return &KEKData{}, nil
+}
+
+// PrepareCSR creates a CFSSL Sign Request based on the given raw CSR and
+// overrides the Subject and Hosts with the given extra args.
+func PrepareCSR(csrBytes []byte, cn, ou, org string) cfsigner.SignRequest {
+ // All managers get added the subject-alt-name of CA, so they can be
+ // used for cert issuance.
+ hosts := []string{ou, cn}
+ if ou == ManagerRole {
+ hosts = append(hosts, CARole)
+ }
+
+ return cfsigner.SignRequest{
+ Request: string(csrBytes),
+ // OU is used for Authentication of the node type. The CN has the random
+ // node ID.
+ Subject: &cfsigner.Subject{CN: cn, Names: []cfcsr.Name{{OU: ou, O: org}}},
+ // Adding ou as DNS alt name, so clients can connect to ManagerRole and CARole
+ Hosts: hosts,
+ }
+}
+
+// ParseValidateAndSignCSR returns a signed certificate from a particular rootCA and a CSR.
+func (rca *RootCA) ParseValidateAndSignCSR(csrBytes []byte, cn, ou, org string) ([]byte, error) {
+ signRequest := PrepareCSR(csrBytes, cn, ou, org)
+ signer, err := rca.Signer()
+ if err != nil {
+ return nil, err
+ }
+ cert, err := signer.Sign(signRequest)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to sign node certificate")
+ }
+
+ return append(cert, rca.Intermediates...), nil
+}
+
+// CrossSignCACertificate takes a CA root certificate and generates an intermediate CA from it signed with the current root signer
+func (rca *RootCA) CrossSignCACertificate(otherCAPEM []byte) ([]byte, error) {
+ signer, err := rca.Signer()
+ if err != nil {
+ return nil, err
+ }
+
+ // create a new cert with exactly the same parameters, including the public key and exact NotBefore and NotAfter
+ template, err := helpers.ParseCertificatePEM(otherCAPEM)
+ if err != nil {
+ return nil, errors.New("could not parse new CA certificate")
+ }
+
+ if !template.IsCA {
+ return nil, errors.New("certificate not a CA")
+ }
+
+ template.SignatureAlgorithm = signer.parsedCert.SignatureAlgorithm // make sure we can sign with the signer key
+ derBytes, err := x509.CreateCertificate(cryptorand.Reader, template, signer.parsedCert, template.PublicKey, signer.cryptoSigner)
+ if err != nil {
+ return nil, errors.Wrap(err, "could not cross-sign new CA certificate using old CA material")
+ }
+
+ return pem.EncodeToMemory(&pem.Block{
+ Type: "CERTIFICATE",
+ Bytes: derBytes,
+ }), nil
+}
+
+func validateSignatureAlgorithm(cert *x509.Certificate) error {
+ switch cert.SignatureAlgorithm {
+ case x509.SHA256WithRSA, x509.SHA384WithRSA, x509.SHA512WithRSA, x509.ECDSAWithSHA256, x509.ECDSAWithSHA384, x509.ECDSAWithSHA512:
+ return nil
+ default:
+ return fmt.Errorf("unsupported signature algorithm: %s", cert.SignatureAlgorithm.String())
+ }
+}
+
+// NewRootCA creates a new RootCA object from unparsed PEM cert bundle and key byte
+// slices. key may be nil, and in this case NewRootCA will return a RootCA
+// without a signer.
+func NewRootCA(rootCertBytes, signCertBytes, signKeyBytes []byte, certExpiry time.Duration, intermediates []byte) (RootCA, error) {
+ // Parse all the certificates in the cert bundle
+ parsedCerts, err := helpers.ParseCertificatesPEM(rootCertBytes)
+ if err != nil {
+ return RootCA{}, errors.Wrap(err, "invalid root certificates")
+ }
+ // Check to see if we have at least one valid cert
+ if len(parsedCerts) < 1 {
+ return RootCA{}, errors.New("no valid root CA certificates found")
+ }
+
+ // Create a Pool with all of the certificates found
+ pool := x509.NewCertPool()
+ for _, cert := range parsedCerts {
+ if err := validateSignatureAlgorithm(cert); err != nil {
+ return RootCA{}, err
+ }
+ // Check to see if all of the certificates are valid, self-signed root CA certs
+ selfpool := x509.NewCertPool()
+ selfpool.AddCert(cert)
+ if _, err := cert.Verify(x509.VerifyOptions{Roots: selfpool}); err != nil {
+ return RootCA{}, errors.Wrap(err, "error while validating Root CA Certificate")
+ }
+ pool.AddCert(cert)
+ }
+
+ // Calculate the digest for our Root CA bundle
+ digest := digest.FromBytes(rootCertBytes)
+
+ // The intermediates supplied must be able to chain up to the root certificates, so that when they are appended to
+ // a leaf certificate, the leaf certificate can be validated through the intermediates to the root certificates.
+ var intermediatePool *x509.CertPool
+ var parsedIntermediates []*x509.Certificate
+ if len(intermediates) > 0 {
+ parsedIntermediates, _, err = ValidateCertChain(pool, intermediates, false)
+ if err != nil {
+ return RootCA{}, errors.Wrap(err, "invalid intermediate chain")
+ }
+ intermediatePool = x509.NewCertPool()
+ for _, cert := range parsedIntermediates {
+ intermediatePool.AddCert(cert)
+ }
+ }
+
+ var localSigner *LocalSigner
+ if len(signKeyBytes) != 0 || len(signCertBytes) != 0 {
+ localSigner, err = newLocalSigner(signKeyBytes, signCertBytes, certExpiry, pool, intermediatePool)
+ if err != nil {
+ return RootCA{}, err
+ }
+
+ // If a signer is provided and there are intermediates, then either the first intermediate would be the signer CA
+ // certificate (in which case it'd have the same subject and public key), or it would be a cross-signed
+ // intermediate with the same subject and public key as our signing CA certificate (which could be either an
+ // intermediate cert or a self-signed root cert).
+ if len(parsedIntermediates) > 0 && (!bytes.Equal(parsedIntermediates[0].RawSubject, localSigner.parsedCert.RawSubject) ||
+ !bytes.Equal(parsedIntermediates[0].RawSubjectPublicKeyInfo, localSigner.parsedCert.RawSubjectPublicKeyInfo)) {
+ return RootCA{}, errors.New(
+ "invalid intermediate chain - the first intermediate must have the same subject and public key as the signing cert")
+ }
+ }
+
+ return RootCA{signer: localSigner, Intermediates: intermediates, Digest: digest, Certs: rootCertBytes, Pool: pool}, nil
+}
+
+// ValidateCertChain checks checks that the certificates provided chain up to the root pool provided. In addition
+// it also enforces that every cert in the bundle certificates form a chain, each one certifying the one above,
+// as per RFC5246 section 7.4.2, and that every certificate (whether or not it is necessary to form a chain to the root
+// pool) is currently valid and not yet expired (unless allowExpiry is set to true).
+// This is additional validation not required by go's Certificate.Verify (which allows invalid certs in the
+// intermediate pool), because this function is intended to be used when reading certs from untrusted locations such as
+// from disk or over a network when a CSR is signed, so it is extra pedantic.
+// This function always returns all the parsed certificates in the bundle in order, which means there will always be
+// at least 1 certificate if there is no error, and the valid chains found by Certificate.Verify
+func ValidateCertChain(rootPool *x509.CertPool, certs []byte, allowExpired bool) ([]*x509.Certificate, [][]*x509.Certificate, error) {
+ // Parse all the certificates in the cert bundle
+ parsedCerts, err := helpers.ParseCertificatesPEM(certs)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(parsedCerts) == 0 {
+ return nil, nil, errors.New("no certificates to validate")
+ }
+ now := time.Now()
+ // ensure that they form a chain, each one being signed by the one after it
+ var intermediatePool *x509.CertPool
+ for i, cert := range parsedCerts {
+ // Manual expiry validation because we want more information on which certificate in the chain is expired, and
+ // because this is an easier way to allow expired certs.
+ if now.Before(cert.NotBefore) {
+ return nil, nil, errors.Wrapf(
+ x509.CertificateInvalidError{
+ Cert: cert,
+ Reason: x509.Expired,
+ },
+ "certificate (%d - %s) not valid before %s, and it is currently %s",
+ i+1, cert.Subject.CommonName, cert.NotBefore.UTC().Format(time.RFC1123), now.Format(time.RFC1123))
+ }
+ if !allowExpired && now.After(cert.NotAfter) {
+ return nil, nil, errors.Wrapf(
+ x509.CertificateInvalidError{
+ Cert: cert,
+ Reason: x509.Expired,
+ },
+ "certificate (%d - %s) not valid after %s, and it is currently %s",
+ i+1, cert.Subject.CommonName, cert.NotAfter.UTC().Format(time.RFC1123), now.Format(time.RFC1123))
+ }
+
+ if i > 0 {
+ // check that the previous cert was signed by this cert
+ prevCert := parsedCerts[i-1]
+ if err := prevCert.CheckSignatureFrom(cert); err != nil {
+ return nil, nil, errors.Wrapf(err, "certificates do not form a chain: (%d - %s) is not signed by (%d - %s)",
+ i, prevCert.Subject.CommonName, i+1, cert.Subject.CommonName)
+ }
+
+ if intermediatePool == nil {
+ intermediatePool = x509.NewCertPool()
+ }
+ intermediatePool.AddCert(cert)
+
+ }
+ }
+
+ verifyOpts := x509.VerifyOptions{
+ Roots: rootPool,
+ Intermediates: intermediatePool,
+ CurrentTime: now,
+ }
+
+ var chains [][]*x509.Certificate
+
+ // If we accept expired certs, try to build a valid cert chain using some subset of the certs. We start off using the
+ // first certificate's NotAfter as the current time, thus ensuring that the first cert is not expired. If the chain
+ // still fails to validate due to expiry issues, continue iterating over the rest of the certs.
+ // If any of the other certs has an earlier NotAfter time, use that time as the current time instead. This insures that
+ // particular cert, and any that came before it, are not expired. Note that the root that the certs chain up to
+ // should also not be expired at that "current" time.
+ if allowExpired {
+ verifyOpts.CurrentTime = parsedCerts[0].NotAfter.Add(time.Hour)
+ for _, cert := range parsedCerts {
+ if !cert.NotAfter.Before(verifyOpts.CurrentTime) {
+ continue
+ }
+ verifyOpts.CurrentTime = cert.NotAfter
+
+ chains, err = parsedCerts[0].Verify(verifyOpts)
+ if err == nil {
+ return parsedCerts, chains, nil
+ }
+ }
+ if invalid, ok := err.(x509.CertificateInvalidError); ok && invalid.Reason == x509.Expired {
+ return nil, nil, errors.New("there is no time span for which all of the certificates, including a root, are valid")
+ }
+ return nil, nil, err
+ }
+
+ chains, err = parsedCerts[0].Verify(verifyOpts)
+ if err != nil {
+ return nil, nil, err
+ }
+ return parsedCerts, chains, nil
+}
+
+// newLocalSigner validates the signing cert and signing key to create a local signer, which accepts a crypto signer and a cert
+func newLocalSigner(keyBytes, certBytes []byte, certExpiry time.Duration, rootPool, intermediatePool *x509.CertPool) (*LocalSigner, error) {
+ if len(keyBytes) == 0 || len(certBytes) == 0 {
+ return nil, errors.New("must provide both a signing key and a signing cert, or neither")
+ }
+
+ parsedCerts, err := helpers.ParseCertificatesPEM(certBytes)
+ if err != nil {
+ return nil, errors.Wrap(err, "invalid signing CA cert")
+ }
+ if len(parsedCerts) == 0 {
+ return nil, errors.New("no valid signing CA certificates found")
+ }
+ if err := validateSignatureAlgorithm(parsedCerts[0]); err != nil {
+ return nil, err
+ }
+ opts := x509.VerifyOptions{
+ Roots: rootPool,
+ Intermediates: intermediatePool,
+ }
+ if _, err := parsedCerts[0].Verify(opts); err != nil {
+ return nil, errors.Wrap(err, "error while validating signing CA certificate against roots and intermediates")
+ }
+
+ var (
+ passphraseStr string
+ passphrase, passphrasePrev []byte
+ priv crypto.Signer
+ )
+
+ // Attempt two distinct passphrases, so we can do a hitless passphrase rotation
+ if passphraseStr = os.Getenv(PassphraseENVVar); passphraseStr != "" {
+ passphrase = []byte(passphraseStr)
+ }
+
+ if p := os.Getenv(PassphraseENVVarPrev); p != "" {
+ passphrasePrev = []byte(p)
+ }
+
+ // Attempt to decrypt the current private-key with the passphrases provided
+ priv, err = helpers.ParsePrivateKeyPEMWithPassword(keyBytes, passphrase)
+ if err != nil {
+ priv, err = helpers.ParsePrivateKeyPEMWithPassword(keyBytes, passphrasePrev)
+ if err != nil {
+ return nil, errors.Wrap(err, "malformed private key")
+ }
+ }
+
+ // We will always use the first certificate inside of the root bundle as the active one
+ if err := ensureCertKeyMatch(parsedCerts[0], priv.Public()); err != nil {
+ return nil, err
+ }
+
+ signer, err := local.NewSigner(priv, parsedCerts[0], cfsigner.DefaultSigAlgo(priv), SigningPolicy(certExpiry))
+ if err != nil {
+ return nil, err
+ }
+
+ // If the key was loaded from disk unencrypted, but there is a passphrase set,
+ // ensure it is encrypted, so it doesn't hit raft in plain-text
+ // we don't have to check for nil, because if we couldn't pem-decode the bytes, then parsing above would have failed
+ keyBlock, _ := pem.Decode(keyBytes)
+ if passphraseStr != "" && !x509.IsEncryptedPEMBlock(keyBlock) {
+ keyBytes, err = EncryptECPrivateKey(keyBytes, passphraseStr)
+ if err != nil {
+ return nil, errors.Wrap(err, "unable to encrypt signing CA key material")
+ }
+ }
+
+ return &LocalSigner{Cert: certBytes, Key: keyBytes, Signer: signer, parsedCert: parsedCerts[0], cryptoSigner: priv}, nil
+}
+
+func ensureCertKeyMatch(cert *x509.Certificate, key crypto.PublicKey) error {
+ switch certPub := cert.PublicKey.(type) {
+ case *rsa.PublicKey:
+ if certPub.N.BitLen() < 2048 || certPub.E == 1 {
+ return errors.New("unsupported RSA key parameters")
+ }
+ rsaKey, ok := key.(*rsa.PublicKey)
+ if ok && certPub.E == rsaKey.E && certPub.N.Cmp(rsaKey.N) == 0 {
+ return nil
+ }
+ case *ecdsa.PublicKey:
+ switch certPub.Curve {
+ case elliptic.P256(), elliptic.P384(), elliptic.P521():
+ break
+ default:
+ return errors.New("unsupported ECDSA key parameters")
+ }
+
+ ecKey, ok := key.(*ecdsa.PublicKey)
+ if ok && certPub.X.Cmp(ecKey.X) == 0 && certPub.Y.Cmp(ecKey.Y) == 0 {
+ return nil
+ }
+ default:
+ return errors.New("unknown or unsupported certificate public key algorithm")
+ }
+
+ return errors.New("certificate key mismatch")
+}
+
+// GetLocalRootCA validates if the contents of the file are a valid self-signed
+// CA certificate, and returns the PEM-encoded Certificate if so
+func GetLocalRootCA(paths CertPaths) (RootCA, error) {
+ // Check if we have a Certificate file
+ cert, err := ioutil.ReadFile(paths.Cert)
+ if err != nil {
+ if os.IsNotExist(err) {
+ err = ErrNoLocalRootCA
+ }
+
+ return RootCA{}, err
+ }
+ signingCert := cert
+
+ key, err := ioutil.ReadFile(paths.Key)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ return RootCA{}, err
+ }
+ // There may not be a local key. It's okay to pass in a nil
+ // key. We'll get a root CA without a signer.
+ key = nil
+ signingCert = nil
+ }
+
+ return NewRootCA(cert, signingCert, key, DefaultNodeCertExpiration, nil)
+}
+
+func getGRPCConnection(creds credentials.TransportCredentials, connBroker *connectionbroker.Broker, forceRemote bool) (*connectionbroker.Conn, error) {
+ dialOpts := []grpc.DialOption{
+ grpc.WithTransportCredentials(creds),
+ grpc.WithTimeout(5 * time.Second),
+ grpc.WithBackoffMaxDelay(5 * time.Second),
+ }
+ if forceRemote {
+ return connBroker.SelectRemote(dialOpts...)
+ }
+ return connBroker.Select(dialOpts...)
+}
+
+// GetRemoteCA returns the remote endpoint's CA certificate bundle
+func GetRemoteCA(ctx context.Context, d digest.Digest, connBroker *connectionbroker.Broker) (RootCA, error) {
+ // This TLS Config is intentionally using InsecureSkipVerify. We use the
+ // digest instead to check the integrity of the CA certificate.
+ insecureCreds := credentials.NewTLS(&tls.Config{InsecureSkipVerify: true})
+ conn, err := getGRPCConnection(insecureCreds, connBroker, false)
+ if err != nil {
+ return RootCA{}, err
+ }
+
+ client := api.NewCAClient(conn.ClientConn)
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ defer func() {
+ conn.Close(err == nil)
+ }()
+ response, err := client.GetRootCACertificate(ctx, &api.GetRootCACertificateRequest{})
+ if err != nil {
+ return RootCA{}, err
+ }
+
+ // If a bundle of certificates are provided, the digest covers the entire bundle and not just
+ // one of the certificates in the bundle. Otherwise, a node can be MITMed while joining if
+ // the MITM CA provides a single certificate which matches the digest, and providing arbitrary
+ // other non-verified root certs that the manager certificate actually chains up to.
+ if d != "" {
+ verifier := d.Verifier()
+ if err != nil {
+ return RootCA{}, errors.Wrap(err, "unexpected error getting digest verifier")
+ }
+
+ io.Copy(verifier, bytes.NewReader(response.Certificate))
+
+ if !verifier.Verified() {
+ return RootCA{}, errors.Errorf("remote CA does not match fingerprint. Expected: %s", d.Hex())
+ }
+ }
+
+ // NewRootCA will validate that the certificates are otherwise valid and create a RootCA object.
+ // Since there is no key, the certificate expiry does not matter and will not be used.
+ return NewRootCA(response.Certificate, nil, nil, DefaultNodeCertExpiration, nil)
+}
+
+// CreateRootCA creates a Certificate authority for a new Swarm Cluster, potentially
+// overwriting any existing CAs.
+func CreateRootCA(rootCN string) (RootCA, error) {
+ // Create a simple CSR for the CA using the default CA validator and policy
+ req := cfcsr.CertificateRequest{
+ CN: rootCN,
+ KeyRequest: &cfcsr.BasicKeyRequest{A: RootKeyAlgo, S: RootKeySize},
+ CA: &cfcsr.CAConfig{Expiry: RootCAExpiration},
+ }
+
+ // Generate the CA and get the certificate and private key
+ cert, _, key, err := initca.New(&req)
+ if err != nil {
+ return RootCA{}, err
+ }
+
+ rootCA, err := NewRootCA(cert, cert, key, DefaultNodeCertExpiration, nil)
+ if err != nil {
+ return RootCA{}, err
+ }
+
+ return rootCA, nil
+}
+
+// GetRemoteSignedCertificate submits a CSR to a remote CA server address,
+// and that is part of a CA identified by a specific certificate pool.
+func GetRemoteSignedCertificate(ctx context.Context, csr []byte, rootCAPool *x509.CertPool, config CertificateRequestConfig) ([]byte, error) {
+ if rootCAPool == nil {
+ return nil, errors.New("valid root CA pool required")
+ }
+ creds := config.Credentials
+
+ if creds == nil {
+ // This is our only non-MTLS request, and it happens when we are boostraping our TLS certs
+ // We're using CARole as server name, so an external CA doesn't also have to have ManagerRole in the cert SANs
+ creds = credentials.NewTLS(&tls.Config{ServerName: CARole, RootCAs: rootCAPool})
+ }
+
+ conn, err := getGRPCConnection(creds, config.ConnBroker, config.ForceRemote)
+ if err != nil {
+ return nil, err
+ }
+
+ // Create a CAClient to retrieve a new Certificate
+ caClient := api.NewNodeCAClient(conn.ClientConn)
+
+ issueCtx, issueCancel := context.WithTimeout(ctx, 5*time.Second)
+ defer issueCancel()
+
+ // Send the Request and retrieve the request token
+ issueRequest := &api.IssueNodeCertificateRequest{CSR: csr, Token: config.Token, Availability: config.Availability}
+ issueResponse, err := caClient.IssueNodeCertificate(issueCtx, issueRequest)
+ if err != nil {
+ conn.Close(false)
+ return nil, err
+ }
+
+ statusRequest := &api.NodeCertificateStatusRequest{NodeID: issueResponse.NodeID}
+ expBackoff := events.NewExponentialBackoff(events.ExponentialBackoffConfig{
+ Base: time.Second,
+ Factor: time.Second,
+ Max: 30 * time.Second,
+ })
+
+ // Exponential backoff with Max of 30 seconds to wait for a new retry
+ for {
+ timeout := 5 * time.Second
+ if config.NodeCertificateStatusRequestTimeout > 0 {
+ timeout = config.NodeCertificateStatusRequestTimeout
+ }
+ // Send the Request and retrieve the certificate
+ stateCtx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ statusResponse, err := caClient.NodeCertificateStatus(stateCtx, statusRequest)
+ switch {
+ case err != nil && grpc.Code(err) != codes.DeadlineExceeded:
+ conn.Close(false)
+ // Because IssueNodeCertificate succeeded, if this call failed likely it is due to an issue with this
+ // particular connection, so we need to get another. We should try a remote connection - the local node
+ // may be a manager that was demoted, so the local connection (which is preferred) may not work.
+ config.ForceRemote = true
+ conn, err = getGRPCConnection(creds, config.ConnBroker, config.ForceRemote)
+ if err != nil {
+ return nil, err
+ }
+ caClient = api.NewNodeCAClient(conn.ClientConn)
+
+ // If there was no deadline exceeded error, and the certificate was issued, return
+ case err == nil && (statusResponse.Status.State == api.IssuanceStateIssued || statusResponse.Status.State == api.IssuanceStateRotate):
+ if statusResponse.Certificate == nil {
+ conn.Close(false)
+ return nil, errors.New("no certificate in CertificateStatus response")
+ }
+
+ // The certificate in the response must match the CSR
+ // we submitted. If we are getting a response for a
+ // certificate that was previously issued, we need to
+ // retry until the certificate gets updated per our
+ // current request.
+ if bytes.Equal(statusResponse.Certificate.CSR, csr) {
+ conn.Close(true)
+ return statusResponse.Certificate.Certificate, nil
+ }
+ }
+
+ // If NodeCertificateStatus timed out, we're still pending, the issuance failed, or
+ // the state is unknown let's continue trying after an exponential backoff
+ expBackoff.Failure(nil, nil)
+ select {
+ case <-ctx.Done():
+ conn.Close(true)
+ return nil, err
+ case <-time.After(expBackoff.Proceed(nil)):
+ }
+ }
+}
+
+// readCertValidity returns the certificate issue and expiration time
+func readCertValidity(kr KeyReader) (time.Time, time.Time, error) {
+ var zeroTime time.Time
+ // Read the Cert
+ cert, _, err := kr.Read()
+ if err != nil {
+ return zeroTime, zeroTime, err
+ }
+
+ // Create an x509 certificate out of the contents on disk
+ certBlock, _ := pem.Decode(cert)
+ if certBlock == nil {
+ return zeroTime, zeroTime, errors.New("failed to decode certificate block")
+ }
+ X509Cert, err := x509.ParseCertificate(certBlock.Bytes)
+ if err != nil {
+ return zeroTime, zeroTime, err
+ }
+
+ return X509Cert.NotBefore, X509Cert.NotAfter, nil
+
+}
+
+// SaveRootCA saves a RootCA object to disk
+func SaveRootCA(rootCA RootCA, paths CertPaths) error {
+ // Make sure the necessary dirs exist and they are writable
+ err := os.MkdirAll(filepath.Dir(paths.Cert), 0755)
+ if err != nil {
+ return err
+ }
+
+ // If the root certificate got returned successfully, save the rootCA to disk.
+ return ioutils.AtomicWriteFile(paths.Cert, rootCA.Certs, 0644)
+}
+
+// GenerateNewCSR returns a newly generated key and CSR signed with said key
+func GenerateNewCSR() ([]byte, []byte, error) {
+ req := &cfcsr.CertificateRequest{
+ KeyRequest: cfcsr.NewBasicKeyRequest(),
+ }
+ return cfcsr.ParseRequest(req)
+}
+
+// EncryptECPrivateKey receives a PEM encoded private key and returns an encrypted
+// AES256 version using a passphrase
+// TODO: Make this method generic to handle RSA keys
+func EncryptECPrivateKey(key []byte, passphraseStr string) ([]byte, error) {
+ passphrase := []byte(passphraseStr)
+ cipherType := x509.PEMCipherAES256
+
+ keyBlock, _ := pem.Decode(key)
+ if keyBlock == nil {
+ // This RootCA does not have a valid signer.
+ return nil, errors.New("error while decoding PEM key")
+ }
+
+ encryptedPEMBlock, err := x509.EncryptPEMBlock(cryptorand.Reader,
+ "EC PRIVATE KEY",
+ keyBlock.Bytes,
+ passphrase,
+ cipherType)
+ if err != nil {
+ return nil, err
+ }
+
+ if encryptedPEMBlock.Headers == nil {
+ return nil, errors.New("unable to encrypt key - invalid PEM file produced")
+ }
+
+ return pem.EncodeToMemory(encryptedPEMBlock), nil
+}
+
+// NormalizePEMs takes a bundle of PEM-encoded certificates in a certificate bundle,
+// decodes them, removes headers, and re-encodes them to make sure that they have
+// consistent whitespace. Note that this is intended to normalize x509 certificates
+// in PEM format, hence the stripping out of headers.
+func NormalizePEMs(certs []byte) []byte {
+ var (
+ results []byte
+ pemBlock *pem.Block
+ )
+ for {
+ pemBlock, certs = pem.Decode(bytes.TrimSpace(certs))
+ if pemBlock == nil {
+ return results
+ }
+ pemBlock.Headers = nil
+ results = append(results, pem.EncodeToMemory(pemBlock)...)
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/ca/config.go b/vendor/github.com/docker/swarmkit/ca/config.go
new file mode 100644
index 0000000..9dd84ec
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ca/config.go
@@ -0,0 +1,665 @@
+package ca
+
+import (
+ cryptorand "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "fmt"
+ "math/big"
+ "math/rand"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ cfconfig "github.com/cloudflare/cfssl/config"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/connectionbroker"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/watch"
+ "github.com/opencontainers/go-digest"
+ "github.com/pkg/errors"
+ "google.golang.org/grpc/credentials"
+
+ "golang.org/x/net/context"
+)
+
+const (
+ rootCACertFilename = "swarm-root-ca.crt"
+ rootCAKeyFilename = "swarm-root-ca.key"
+ nodeTLSCertFilename = "swarm-node.crt"
+ nodeTLSKeyFilename = "swarm-node.key"
+ nodeCSRFilename = "swarm-node.csr"
+
+ // DefaultRootCN represents the root CN that we should create roots CAs with by default
+ DefaultRootCN = "swarm-ca"
+ // ManagerRole represents the Manager node type, and is used for authorization to endpoints
+ ManagerRole = "swarm-manager"
+ // WorkerRole represents the Worker node type, and is used for authorization to endpoints
+ WorkerRole = "swarm-worker"
+ // CARole represents the CA node type, and is used for clients attempting to get new certificates issued
+ CARole = "swarm-ca"
+
+ generatedSecretEntropyBytes = 16
+ joinTokenBase = 36
+ // ceil(log(2^128-1, 36))
+ maxGeneratedSecretLength = 25
+ // ceil(log(2^256-1, 36))
+ base36DigestLen = 50
+)
+
+var (
+ // GetCertRetryInterval is how long to wait before retrying a node
+ // certificate or root certificate request.
+ GetCertRetryInterval = 2 * time.Second
+)
+
+// SecurityConfig is used to represent a node's security configuration. It includes information about
+// the RootCA and ServerTLSCreds/ClientTLSCreds transport authenticators to be used for MTLS
+type SecurityConfig struct {
+ // mu protects against concurrent access to fields inside the structure.
+ mu sync.Mutex
+
+ // renewalMu makes sure only one certificate renewal attempt happens at
+ // a time. It should never be locked after mu is already locked.
+ renewalMu sync.Mutex
+
+ rootCA *RootCA
+ externalCA *ExternalCA
+ keyReadWriter *KeyReadWriter
+
+ certificate *tls.Certificate
+ issuerInfo *IssuerInfo
+
+ externalCAClientRootPool *x509.CertPool
+
+ ServerTLSCreds *MutableTLSCreds
+ ClientTLSCreds *MutableTLSCreds
+
+ // An optional queue for anyone interested in subscribing to SecurityConfig updates
+ queue *watch.Queue
+}
+
+// CertificateUpdate represents a change in the underlying TLS configuration being returned by
+// a certificate renewal event.
+type CertificateUpdate struct {
+ Role string
+ Err error
+}
+
+func validateRootCAAndTLSCert(rootCA *RootCA, externalCARootPool *x509.CertPool, tlsKeyPair *tls.Certificate) error {
+ var (
+ leafCert *x509.Certificate
+ intermediatePool *x509.CertPool
+ )
+ for i, derBytes := range tlsKeyPair.Certificate {
+ parsed, err := x509.ParseCertificate(derBytes)
+ if err != nil {
+ return errors.Wrap(err, "could not validate new root certificates due to parse error")
+ }
+ if i == 0 {
+ leafCert = parsed
+ } else {
+ if intermediatePool == nil {
+ intermediatePool = x509.NewCertPool()
+ }
+ intermediatePool.AddCert(parsed)
+ }
+ }
+ opts := x509.VerifyOptions{
+ Roots: rootCA.Pool,
+ Intermediates: intermediatePool,
+ }
+ if _, err := leafCert.Verify(opts); err != nil {
+ return errors.Wrap(err, "new root CA does not match existing TLS credentials")
+ }
+ opts.Roots = externalCARootPool
+ if _, err := leafCert.Verify(opts); err != nil {
+ return errors.Wrap(err, "new external root pool does not match existing TLS credentials")
+ }
+ return nil
+}
+
+// NewSecurityConfig initializes and returns a new SecurityConfig.
+func NewSecurityConfig(rootCA *RootCA, krw *KeyReadWriter, tlsKeyPair *tls.Certificate, issuerInfo *IssuerInfo) (*SecurityConfig, error) {
+ // Create the Server TLS Credentials for this node. These will not be used by workers.
+ serverTLSCreds, err := rootCA.NewServerTLSCredentials(tlsKeyPair)
+ if err != nil {
+ return nil, err
+ }
+
+ // Create a TLSConfig to be used when this node connects as a client to another remote node.
+ // We're using ManagerRole as remote serverName for TLS host verification because both workers
+ // and managers always connect to remote managers.
+ clientTLSCreds, err := rootCA.NewClientTLSCredentials(tlsKeyPair, ManagerRole)
+ if err != nil {
+ return nil, err
+ }
+
+ // Make a new TLS config for the external CA client without a
+ // ServerName value set.
+ externalCATLSConfig := &tls.Config{
+ Certificates: []tls.Certificate{*tlsKeyPair},
+ RootCAs: rootCA.Pool,
+ MinVersion: tls.VersionTLS12,
+ }
+
+ return &SecurityConfig{
+ rootCA: rootCA,
+ keyReadWriter: krw,
+
+ certificate: tlsKeyPair,
+ issuerInfo: issuerInfo,
+
+ externalCA: NewExternalCA(rootCA, externalCATLSConfig),
+ ClientTLSCreds: clientTLSCreds,
+ ServerTLSCreds: serverTLSCreds,
+ externalCAClientRootPool: rootCA.Pool,
+ }, nil
+}
+
+// RootCA returns the root CA.
+func (s *SecurityConfig) RootCA() *RootCA {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ return s.rootCA
+}
+
+// ExternalCA returns the external CA.
+func (s *SecurityConfig) ExternalCA() *ExternalCA {
+ return s.externalCA
+}
+
+// KeyWriter returns the object that can write keys to disk
+func (s *SecurityConfig) KeyWriter() KeyWriter {
+ return s.keyReadWriter
+}
+
+// KeyReader returns the object that can read keys from disk
+func (s *SecurityConfig) KeyReader() KeyReader {
+ return s.keyReadWriter
+}
+
+// UpdateRootCA replaces the root CA with a new root CA
+func (s *SecurityConfig) UpdateRootCA(rootCA *RootCA, externalCARootPool *x509.CertPool) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ // refuse to update the root CA if the current TLS credentials do not validate against it
+ if err := validateRootCAAndTLSCert(rootCA, externalCARootPool, s.certificate); err != nil {
+ return err
+ }
+
+ s.rootCA = rootCA
+ s.externalCAClientRootPool = externalCARootPool
+ s.externalCA.UpdateRootCA(rootCA)
+
+ return s.updateTLSCredentials(s.certificate, s.issuerInfo)
+}
+
+// SetWatch allows you to set a watch on the security config, in order to be notified of any changes
+func (s *SecurityConfig) SetWatch(q *watch.Queue) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.queue = q
+}
+
+// IssuerInfo returns the issuer subject and issuer public key
+func (s *SecurityConfig) IssuerInfo() *IssuerInfo {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.issuerInfo
+}
+
+// This function expects something else to have taken out a lock on the SecurityConfig.
+func (s *SecurityConfig) updateTLSCredentials(certificate *tls.Certificate, issuerInfo *IssuerInfo) error {
+ certs := []tls.Certificate{*certificate}
+ clientConfig, err := NewClientTLSConfig(certs, s.rootCA.Pool, ManagerRole)
+ if err != nil {
+ return errors.Wrap(err, "failed to create a new client config using the new root CA")
+ }
+
+ serverConfig, err := NewServerTLSConfig(certs, s.rootCA.Pool)
+ if err != nil {
+ return errors.Wrap(err, "failed to create a new server config using the new root CA")
+ }
+
+ if err := s.ClientTLSCreds.loadNewTLSConfig(clientConfig); err != nil {
+ return errors.Wrap(err, "failed to update the client credentials")
+ }
+
+ // Update the external CA to use the new client TLS
+ // config using a copy without a serverName specified.
+ s.externalCA.UpdateTLSConfig(&tls.Config{
+ Certificates: certs,
+ RootCAs: s.externalCAClientRootPool,
+ MinVersion: tls.VersionTLS12,
+ })
+
+ if err := s.ServerTLSCreds.loadNewTLSConfig(serverConfig); err != nil {
+ return errors.Wrap(err, "failed to update the server TLS credentials")
+ }
+
+ s.certificate = certificate
+ s.issuerInfo = issuerInfo
+ if s.queue != nil {
+ s.queue.Publish(&api.NodeTLSInfo{
+ TrustRoot: s.rootCA.Certs,
+ CertIssuerPublicKey: s.issuerInfo.PublicKey,
+ CertIssuerSubject: s.issuerInfo.Subject,
+ })
+ }
+ return nil
+}
+
+// UpdateTLSCredentials updates the security config with an updated TLS certificate and issuer info
+func (s *SecurityConfig) UpdateTLSCredentials(certificate *tls.Certificate, issuerInfo *IssuerInfo) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.updateTLSCredentials(certificate, issuerInfo)
+}
+
+// SigningPolicy creates a policy used by the signer to ensure that the only fields
+// from the remote CSRs we trust are: PublicKey, PublicKeyAlgorithm and SignatureAlgorithm.
+// It receives the duration a certificate will be valid for
+func SigningPolicy(certExpiry time.Duration) *cfconfig.Signing {
+ // Force the minimum Certificate expiration to be fifteen minutes
+ if certExpiry < MinNodeCertExpiration {
+ certExpiry = DefaultNodeCertExpiration
+ }
+
+ // Add the backdate
+ certExpiry = certExpiry + CertBackdate
+
+ return &cfconfig.Signing{
+ Default: &cfconfig.SigningProfile{
+ Usage: []string{"signing", "key encipherment", "server auth", "client auth"},
+ Expiry: certExpiry,
+ Backdate: CertBackdate,
+ // Only trust the key components from the CSR. Everything else should
+ // come directly from API call params.
+ CSRWhitelist: &cfconfig.CSRWhitelist{
+ PublicKey: true,
+ PublicKeyAlgorithm: true,
+ SignatureAlgorithm: true,
+ },
+ },
+ }
+}
+
+// SecurityConfigPaths is used as a helper to hold all the paths of security relevant files
+type SecurityConfigPaths struct {
+ Node, RootCA CertPaths
+}
+
+// NewConfigPaths returns the absolute paths to all of the different types of files
+func NewConfigPaths(baseCertDir string) *SecurityConfigPaths {
+ return &SecurityConfigPaths{
+ Node: CertPaths{
+ Cert: filepath.Join(baseCertDir, nodeTLSCertFilename),
+ Key: filepath.Join(baseCertDir, nodeTLSKeyFilename)},
+ RootCA: CertPaths{
+ Cert: filepath.Join(baseCertDir, rootCACertFilename),
+ Key: filepath.Join(baseCertDir, rootCAKeyFilename)},
+ }
+}
+
+// GenerateJoinToken creates a new join token.
+func GenerateJoinToken(rootCA *RootCA) string {
+ var secretBytes [generatedSecretEntropyBytes]byte
+
+ if _, err := cryptorand.Read(secretBytes[:]); err != nil {
+ panic(fmt.Errorf("failed to read random bytes: %v", err))
+ }
+
+ var nn, digest big.Int
+ nn.SetBytes(secretBytes[:])
+ digest.SetString(rootCA.Digest.Hex(), 16)
+ return fmt.Sprintf("SWMTKN-1-%0[1]*s-%0[3]*s", base36DigestLen, digest.Text(joinTokenBase), maxGeneratedSecretLength, nn.Text(joinTokenBase))
+}
+
+func getCAHashFromToken(token string) (digest.Digest, error) {
+ split := strings.Split(token, "-")
+ if len(split) != 4 || split[0] != "SWMTKN" || split[1] != "1" || len(split[2]) != base36DigestLen || len(split[3]) != maxGeneratedSecretLength {
+ return "", errors.New("invalid join token")
+ }
+
+ var digestInt big.Int
+ digestInt.SetString(split[2], joinTokenBase)
+
+ return digest.Parse(fmt.Sprintf("sha256:%0[1]*s", 64, digestInt.Text(16)))
+}
+
+// DownloadRootCA tries to retrieve a remote root CA and matches the digest against the provided token.
+func DownloadRootCA(ctx context.Context, paths CertPaths, token string, connBroker *connectionbroker.Broker) (RootCA, error) {
+ var rootCA RootCA
+ // Get a digest for the optional CA hash string that we've been provided
+ // If we were provided a non-empty string, and it is an invalid hash, return
+ // otherwise, allow the invalid digest through.
+ var (
+ d digest.Digest
+ err error
+ )
+ if token != "" {
+ d, err = getCAHashFromToken(token)
+ if err != nil {
+ return RootCA{}, err
+ }
+ }
+ // Get the remote CA certificate, verify integrity with the
+ // hash provided. Retry up to 5 times, in case the manager we
+ // first try to contact is not responding properly (it may have
+ // just been demoted, for example).
+
+ for i := 0; i != 5; i++ {
+ rootCA, err = GetRemoteCA(ctx, d, connBroker)
+ if err == nil {
+ break
+ }
+ log.G(ctx).WithError(err).Errorf("failed to retrieve remote root CA certificate")
+
+ select {
+ case <-time.After(GetCertRetryInterval):
+ case <-ctx.Done():
+ return RootCA{}, ctx.Err()
+ }
+ }
+ if err != nil {
+ return RootCA{}, err
+ }
+
+ // Save root CA certificate to disk
+ if err = SaveRootCA(rootCA, paths); err != nil {
+ return RootCA{}, err
+ }
+
+ log.G(ctx).Debugf("retrieved remote CA certificate: %s", paths.Cert)
+ return rootCA, nil
+}
+
+// LoadSecurityConfig loads TLS credentials from disk, or returns an error if
+// these credentials do not exist or are unusable.
+func LoadSecurityConfig(ctx context.Context, rootCA RootCA, krw *KeyReadWriter, allowExpired bool) (*SecurityConfig, error) {
+ ctx = log.WithModule(ctx, "tls")
+
+ // At this point we've successfully loaded the CA details from disk, or
+ // successfully downloaded them remotely. The next step is to try to
+ // load our certificates.
+
+ // Read both the Cert and Key from disk
+ cert, key, err := krw.Read()
+ if err != nil {
+ return nil, err
+ }
+
+ // Check to see if this certificate was signed by our CA, and isn't expired
+ _, chains, err := ValidateCertChain(rootCA.Pool, cert, allowExpired)
+ if err != nil {
+ return nil, err
+ }
+ // ValidateChain, if successful, will always return at least 1 chain containing
+ // at least 2 certificates: the leaf and the root.
+ issuer := chains[0][1]
+
+ // Now that we know this certificate is valid, create a TLS Certificate for our
+ // credentials
+ keyPair, err := tls.X509KeyPair(cert, key)
+ if err != nil {
+ return nil, err
+ }
+
+ secConfig, err := NewSecurityConfig(&rootCA, krw, &keyPair, &IssuerInfo{
+ Subject: issuer.RawSubject,
+ PublicKey: issuer.RawSubjectPublicKeyInfo,
+ })
+ if err == nil {
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": secConfig.ClientTLSCreds.NodeID(),
+ "node.role": secConfig.ClientTLSCreds.Role(),
+ }).Debug("loaded node credentials")
+ }
+ return secConfig, err
+}
+
+// CertificateRequestConfig contains the information needed to request a
+// certificate from a remote CA.
+type CertificateRequestConfig struct {
+ // Token is the join token that authenticates us with the CA.
+ Token string
+ // Availability allows a user to control the current scheduling status of a node
+ Availability api.NodeSpec_Availability
+ // ConnBroker provides connections to CAs.
+ ConnBroker *connectionbroker.Broker
+ // Credentials provides transport credentials for communicating with the
+ // remote server.
+ Credentials credentials.TransportCredentials
+ // ForceRemote specifies that only a remote (TCP) connection should
+ // be used to request the certificate. This may be necessary in cases
+ // where the local node is running a manager, but is in the process of
+ // being demoted.
+ ForceRemote bool
+ // NodeCertificateStatusRequestTimeout determines how long to wait for a node
+ // status RPC result. If not provided (zero value), will default to 5 seconds.
+ NodeCertificateStatusRequestTimeout time.Duration
+ // RetryInterval specifies how long to delay between retries, if non-zero.
+ RetryInterval time.Duration
+}
+
+// CreateSecurityConfig creates a new key and cert for this node, either locally
+// or via a remote CA.
+func (rootCA RootCA) CreateSecurityConfig(ctx context.Context, krw *KeyReadWriter, config CertificateRequestConfig) (*SecurityConfig, error) {
+ ctx = log.WithModule(ctx, "tls")
+
+ // Create a new random ID for this certificate
+ cn := identity.NewID()
+ org := identity.NewID()
+
+ proposedRole := ManagerRole
+ tlsKeyPair, issuerInfo, err := rootCA.IssueAndSaveNewCertificates(krw, cn, proposedRole, org)
+ switch errors.Cause(err) {
+ case ErrNoValidSigner:
+ config.RetryInterval = GetCertRetryInterval
+ // Request certificate issuance from a remote CA.
+ // Last argument is nil because at this point we don't have any valid TLS creds
+ tlsKeyPair, issuerInfo, err = rootCA.RequestAndSaveNewCertificates(ctx, krw, config)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed to request and save new certificate")
+ return nil, err
+ }
+ case nil:
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": cn,
+ "node.role": proposedRole,
+ }).Debug("issued new TLS certificate")
+ default:
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": cn,
+ "node.role": proposedRole,
+ }).WithError(err).Errorf("failed to issue and save new certificate")
+ return nil, err
+ }
+
+ secConfig, err := NewSecurityConfig(&rootCA, krw, tlsKeyPair, issuerInfo)
+ if err == nil {
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": secConfig.ClientTLSCreds.NodeID(),
+ "node.role": secConfig.ClientTLSCreds.Role(),
+ }).Debugf("new node credentials generated: %s", krw.Target())
+ }
+ return secConfig, err
+}
+
+// TODO(cyli): currently we have to only update if it's a worker role - if we have a single root CA update path for
+// both managers and workers, we won't need to check any more.
+func updateRootThenUpdateCert(ctx context.Context, s *SecurityConfig, connBroker *connectionbroker.Broker, rootPaths CertPaths, failedCert *x509.Certificate) (*tls.Certificate, *IssuerInfo, error) {
+ if len(failedCert.Subject.OrganizationalUnit) == 0 || failedCert.Subject.OrganizationalUnit[0] != WorkerRole {
+ return nil, nil, errors.New("cannot update root CA since this is not a worker")
+ }
+ // try downloading a new root CA if it's an unknown authority issue, in case there was a root rotation completion
+ // and we just didn't get the new root
+ rootCA, err := GetRemoteCA(ctx, "", connBroker)
+ if err != nil {
+ return nil, nil, err
+ }
+ // validate against the existing security config creds
+ if err := s.UpdateRootCA(&rootCA, rootCA.Pool); err != nil {
+ return nil, nil, err
+ }
+ if err := SaveRootCA(rootCA, rootPaths); err != nil {
+ return nil, nil, err
+ }
+ return rootCA.RequestAndSaveNewCertificates(ctx, s.KeyWriter(),
+ CertificateRequestConfig{
+ ConnBroker: connBroker,
+ Credentials: s.ClientTLSCreds,
+ })
+}
+
+// RenewTLSConfigNow gets a new TLS cert and key, and updates the security config if provided. This is similar to
+// RenewTLSConfig, except while that monitors for expiry, and periodically renews, this renews once and is blocking
+func RenewTLSConfigNow(ctx context.Context, s *SecurityConfig, connBroker *connectionbroker.Broker, rootPaths CertPaths) error {
+ s.renewalMu.Lock()
+ defer s.renewalMu.Unlock()
+
+ ctx = log.WithModule(ctx, "tls")
+ log := log.G(ctx).WithFields(logrus.Fields{
+ "node.id": s.ClientTLSCreds.NodeID(),
+ "node.role": s.ClientTLSCreds.Role(),
+ })
+
+ // Let's request new certs. Renewals don't require a token.
+ rootCA := s.RootCA()
+ tlsKeyPair, issuerInfo, err := rootCA.RequestAndSaveNewCertificates(ctx,
+ s.KeyWriter(),
+ CertificateRequestConfig{
+ ConnBroker: connBroker,
+ Credentials: s.ClientTLSCreds,
+ })
+ if wrappedError, ok := err.(x509UnknownAuthError); ok {
+ var newErr error
+ tlsKeyPair, issuerInfo, newErr = updateRootThenUpdateCert(ctx, s, connBroker, rootPaths, wrappedError.failedLeafCert)
+ if newErr != nil {
+ err = wrappedError.error
+ } else {
+ err = nil
+ }
+ }
+ if err != nil {
+ log.WithError(err).Errorf("failed to renew the certificate")
+ return err
+ }
+
+ return s.UpdateTLSCredentials(tlsKeyPair, issuerInfo)
+}
+
+// calculateRandomExpiry returns a random duration between 50% and 80% of the
+// original validity period
+func calculateRandomExpiry(validFrom, validUntil time.Time) time.Duration {
+ duration := validUntil.Sub(validFrom)
+
+ var randomExpiry int
+ // Our lower bound of renewal will be half of the total expiration time
+ minValidity := int(duration.Minutes() * CertLowerRotationRange)
+ // Our upper bound of renewal will be 80% of the total expiration time
+ maxValidity := int(duration.Minutes() * CertUpperRotationRange)
+ // Let's select a random number of minutes between min and max, and set our retry for that
+ // Using randomly selected rotation allows us to avoid certificate thundering herds.
+ if maxValidity-minValidity < 1 {
+ randomExpiry = minValidity
+ } else {
+ randomExpiry = rand.Intn(maxValidity-minValidity) + int(minValidity)
+ }
+
+ expiry := validFrom.Add(time.Duration(randomExpiry) * time.Minute).Sub(time.Now())
+ if expiry < 0 {
+ return 0
+ }
+ return expiry
+}
+
+// NewServerTLSConfig returns a tls.Config configured for a TLS Server, given a tls.Certificate
+// and the PEM-encoded root CA Certificate
+func NewServerTLSConfig(certs []tls.Certificate, rootCAPool *x509.CertPool) (*tls.Config, error) {
+ if rootCAPool == nil {
+ return nil, errors.New("valid root CA pool required")
+ }
+
+ return &tls.Config{
+ Certificates: certs,
+ // Since we're using the same CA server to issue Certificates to new nodes, we can't
+ // use tls.RequireAndVerifyClientCert
+ ClientAuth: tls.VerifyClientCertIfGiven,
+ RootCAs: rootCAPool,
+ ClientCAs: rootCAPool,
+ PreferServerCipherSuites: true,
+ MinVersion: tls.VersionTLS12,
+ }, nil
+}
+
+// NewClientTLSConfig returns a tls.Config configured for a TLS Client, given a tls.Certificate
+// the PEM-encoded root CA Certificate, and the name of the remote server the client wants to connect to.
+func NewClientTLSConfig(certs []tls.Certificate, rootCAPool *x509.CertPool, serverName string) (*tls.Config, error) {
+ if rootCAPool == nil {
+ return nil, errors.New("valid root CA pool required")
+ }
+
+ return &tls.Config{
+ ServerName: serverName,
+ Certificates: certs,
+ RootCAs: rootCAPool,
+ MinVersion: tls.VersionTLS12,
+ }, nil
+}
+
+// NewClientTLSCredentials returns GRPC credentials for a TLS GRPC client, given a tls.Certificate
+// a PEM-Encoded root CA Certificate, and the name of the remote server the client wants to connect to.
+func (rootCA *RootCA) NewClientTLSCredentials(cert *tls.Certificate, serverName string) (*MutableTLSCreds, error) {
+ tlsConfig, err := NewClientTLSConfig([]tls.Certificate{*cert}, rootCA.Pool, serverName)
+ if err != nil {
+ return nil, err
+ }
+
+ mtls, err := NewMutableTLS(tlsConfig)
+
+ return mtls, err
+}
+
+// NewServerTLSCredentials returns GRPC credentials for a TLS GRPC client, given a tls.Certificate
+// a PEM-Encoded root CA Certificate, and the name of the remote server the client wants to connect to.
+func (rootCA *RootCA) NewServerTLSCredentials(cert *tls.Certificate) (*MutableTLSCreds, error) {
+ tlsConfig, err := NewServerTLSConfig([]tls.Certificate{*cert}, rootCA.Pool)
+ if err != nil {
+ return nil, err
+ }
+
+ mtls, err := NewMutableTLS(tlsConfig)
+
+ return mtls, err
+}
+
+// ParseRole parses an apiRole into an internal role string
+func ParseRole(apiRole api.NodeRole) (string, error) {
+ switch apiRole {
+ case api.NodeRoleManager:
+ return ManagerRole, nil
+ case api.NodeRoleWorker:
+ return WorkerRole, nil
+ default:
+ return "", errors.Errorf("failed to parse api role: %v", apiRole)
+ }
+}
+
+// FormatRole parses an internal role string into an apiRole
+func FormatRole(role string) (api.NodeRole, error) {
+ switch strings.ToLower(role) {
+ case strings.ToLower(ManagerRole):
+ return api.NodeRoleManager, nil
+ case strings.ToLower(WorkerRole):
+ return api.NodeRoleWorker, nil
+ default:
+ return 0, errors.Errorf("failed to parse role: %s", role)
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/ca/external.go b/vendor/github.com/docker/swarmkit/ca/external.go
new file mode 100644
index 0000000..d6a9421
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ca/external.go
@@ -0,0 +1,228 @@
+package ca
+
+import (
+ "bytes"
+ cryptorand "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/pem"
+ "io/ioutil"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/cloudflare/cfssl/api"
+ "github.com/cloudflare/cfssl/config"
+ "github.com/cloudflare/cfssl/csr"
+ "github.com/cloudflare/cfssl/signer"
+ "github.com/docker/swarmkit/log"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "golang.org/x/net/context/ctxhttp"
+)
+
+// ExternalCrossSignProfile is the profile that we will be sending cross-signing CSR sign requests with
+const ExternalCrossSignProfile = "CA"
+
+// ErrNoExternalCAURLs is an error used it indicate that an ExternalCA is
+// configured with no URLs to which it can proxy certificate signing requests.
+var ErrNoExternalCAURLs = errors.New("no external CA URLs")
+
+// ExternalCA is able to make certificate signing requests to one of a list
+// remote CFSSL API endpoints.
+type ExternalCA struct {
+ ExternalRequestTimeout time.Duration
+
+ mu sync.Mutex
+ rootCA *RootCA
+ urls []string
+ client *http.Client
+}
+
+// NewExternalCA creates a new ExternalCA which uses the given tlsConfig to
+// authenticate to any of the given URLS of CFSSL API endpoints.
+func NewExternalCA(rootCA *RootCA, tlsConfig *tls.Config, urls ...string) *ExternalCA {
+ return &ExternalCA{
+ ExternalRequestTimeout: 5 * time.Second,
+ rootCA: rootCA,
+ urls: urls,
+ client: &http.Client{
+ Transport: &http.Transport{
+ TLSClientConfig: tlsConfig,
+ },
+ },
+ }
+}
+
+// Copy returns a copy of the external CA that can be updated independently
+func (eca *ExternalCA) Copy() *ExternalCA {
+ eca.mu.Lock()
+ defer eca.mu.Unlock()
+
+ return &ExternalCA{
+ ExternalRequestTimeout: eca.ExternalRequestTimeout,
+ rootCA: eca.rootCA,
+ urls: eca.urls,
+ client: eca.client,
+ }
+}
+
+// UpdateTLSConfig updates the HTTP Client for this ExternalCA by creating
+// a new client which uses the given tlsConfig.
+func (eca *ExternalCA) UpdateTLSConfig(tlsConfig *tls.Config) {
+ eca.mu.Lock()
+ defer eca.mu.Unlock()
+
+ eca.client = &http.Client{
+ Transport: &http.Transport{
+ TLSClientConfig: tlsConfig,
+ },
+ }
+}
+
+// UpdateURLs updates the list of CSR API endpoints by setting it to the given urls.
+func (eca *ExternalCA) UpdateURLs(urls ...string) {
+ eca.mu.Lock()
+ defer eca.mu.Unlock()
+
+ eca.urls = urls
+}
+
+// UpdateRootCA changes the root CA used to append intermediates
+func (eca *ExternalCA) UpdateRootCA(rca *RootCA) {
+ eca.mu.Lock()
+ eca.rootCA = rca
+ eca.mu.Unlock()
+}
+
+// Sign signs a new certificate by proxying the given certificate signing
+// request to an external CFSSL API server.
+func (eca *ExternalCA) Sign(ctx context.Context, req signer.SignRequest) (cert []byte, err error) {
+ // Get the current HTTP client and list of URLs in a small critical
+ // section. We will use these to make certificate signing requests.
+ eca.mu.Lock()
+ urls := eca.urls
+ client := eca.client
+ intermediates := eca.rootCA.Intermediates
+ eca.mu.Unlock()
+
+ if len(urls) == 0 {
+ return nil, ErrNoExternalCAURLs
+ }
+
+ csrJSON, err := json.Marshal(req)
+ if err != nil {
+ return nil, errors.Wrap(err, "unable to JSON-encode CFSSL signing request")
+ }
+
+ // Try each configured proxy URL. Return after the first success. If
+ // all fail then the last error will be returned.
+ for _, url := range urls {
+ requestCtx, cancel := context.WithTimeout(ctx, eca.ExternalRequestTimeout)
+ cert, err = makeExternalSignRequest(requestCtx, client, url, csrJSON)
+ cancel()
+ if err == nil {
+ return append(cert, intermediates...), err
+ }
+ log.G(ctx).Debugf("unable to proxy certificate signing request to %s: %s", url, err)
+ }
+
+ return nil, err
+}
+
+// CrossSignRootCA takes a RootCA object, generates a CA CSR, sends a signing request with the CA CSR to the external
+// CFSSL API server in order to obtain a cross-signed root
+func (eca *ExternalCA) CrossSignRootCA(ctx context.Context, rca RootCA) ([]byte, error) {
+ // ExtractCertificateRequest generates a new key request, and we want to continue to use the old
+ // key. However, ExtractCertificateRequest will also convert the pkix.Name to csr.Name, which we
+ // need in order to generate a signing request
+ rcaSigner, err := rca.Signer()
+ if err != nil {
+ return nil, err
+ }
+ rootCert := rcaSigner.parsedCert
+ cfCSRObj := csr.ExtractCertificateRequest(rootCert)
+
+ der, err := x509.CreateCertificateRequest(cryptorand.Reader, &x509.CertificateRequest{
+ RawSubjectPublicKeyInfo: rootCert.RawSubjectPublicKeyInfo,
+ RawSubject: rootCert.RawSubject,
+ PublicKeyAlgorithm: rootCert.PublicKeyAlgorithm,
+ Subject: rootCert.Subject,
+ Extensions: rootCert.Extensions,
+ DNSNames: rootCert.DNSNames,
+ EmailAddresses: rootCert.EmailAddresses,
+ IPAddresses: rootCert.IPAddresses,
+ }, rcaSigner.cryptoSigner)
+ if err != nil {
+ return nil, err
+ }
+ req := signer.SignRequest{
+ Request: string(pem.EncodeToMemory(&pem.Block{
+ Type: "CERTIFICATE REQUEST",
+ Bytes: der,
+ })),
+ Subject: &signer.Subject{
+ CN: rootCert.Subject.CommonName,
+ Names: cfCSRObj.Names,
+ },
+ Profile: ExternalCrossSignProfile,
+ }
+ // cfssl actually ignores non subject alt name extensions in the CSR, so we have to add the CA extension in the signing
+ // request as well
+ for _, ext := range rootCert.Extensions {
+ if ext.Id.Equal(BasicConstraintsOID) {
+ req.Extensions = append(req.Extensions, signer.Extension{
+ ID: config.OID(ext.Id),
+ Critical: ext.Critical,
+ Value: hex.EncodeToString(ext.Value),
+ })
+ }
+ }
+ return eca.Sign(ctx, req)
+}
+
+func makeExternalSignRequest(ctx context.Context, client *http.Client, url string, csrJSON []byte) (cert []byte, err error) {
+ resp, err := ctxhttp.Post(ctx, client, url, "application/json", bytes.NewReader(csrJSON))
+ if err != nil {
+ return nil, recoverableErr{err: errors.Wrap(err, "unable to perform certificate signing request")}
+ }
+ defer resp.Body.Close()
+
+ body, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return nil, recoverableErr{err: errors.Wrap(err, "unable to read CSR response body")}
+ }
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, recoverableErr{err: errors.Errorf("unexpected status code in CSR response: %d - %s", resp.StatusCode, string(body))}
+ }
+
+ var apiResponse api.Response
+ if err := json.Unmarshal(body, &apiResponse); err != nil {
+ logrus.Debugf("unable to JSON-parse CFSSL API response body: %s", string(body))
+ return nil, recoverableErr{err: errors.Wrap(err, "unable to parse JSON response")}
+ }
+
+ if !apiResponse.Success || apiResponse.Result == nil {
+ if len(apiResponse.Errors) > 0 {
+ return nil, errors.Errorf("response errors: %v", apiResponse.Errors)
+ }
+
+ return nil, errors.New("certificate signing request failed")
+ }
+
+ result, ok := apiResponse.Result.(map[string]interface{})
+ if !ok {
+ return nil, errors.Errorf("invalid result type: %T", apiResponse.Result)
+ }
+
+ certPEM, ok := result["certificate"].(string)
+ if !ok {
+ return nil, errors.Errorf("invalid result certificate field type: %T", result["certificate"])
+ }
+
+ return []byte(certPEM), nil
+}
diff --git a/vendor/github.com/docker/swarmkit/ca/forward.go b/vendor/github.com/docker/swarmkit/ca/forward.go
new file mode 100644
index 0000000..617b151
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ca/forward.go
@@ -0,0 +1,77 @@
+package ca
+
+import (
+ "golang.org/x/net/context"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/peer"
+)
+
+const (
+ certForwardedKey = "forwarded_cert"
+ certCNKey = "forwarded_cert_cn"
+ certOUKey = "forwarded_cert_ou"
+ certOrgKey = "forwarded_cert_org"
+ remoteAddrKey = "remote_addr"
+)
+
+// forwardedTLSInfoFromContext obtains forwarded TLS CN/OU from the grpc.MD
+// object in ctx.
+func forwardedTLSInfoFromContext(ctx context.Context) (remoteAddr string, cn string, org string, ous []string) {
+ md, _ := metadata.FromContext(ctx)
+ if len(md[remoteAddrKey]) != 0 {
+ remoteAddr = md[remoteAddrKey][0]
+ }
+ if len(md[certCNKey]) != 0 {
+ cn = md[certCNKey][0]
+ }
+ if len(md[certOrgKey]) != 0 {
+ org = md[certOrgKey][0]
+ }
+ ous = md[certOUKey]
+ return
+}
+
+func isForwardedRequest(ctx context.Context) bool {
+ md, _ := metadata.FromContext(ctx)
+ if len(md[certForwardedKey]) != 1 {
+ return false
+ }
+ return md[certForwardedKey][0] == "true"
+}
+
+// WithMetadataForwardTLSInfo reads certificate from context and returns context where
+// ForwardCert is set based on original certificate.
+func WithMetadataForwardTLSInfo(ctx context.Context) (context.Context, error) {
+ md, ok := metadata.FromContext(ctx)
+ if !ok {
+ md = metadata.MD{}
+ }
+
+ ous := []string{}
+ org := ""
+ cn := ""
+
+ certSubj, err := certSubjectFromContext(ctx)
+ if err == nil {
+ cn = certSubj.CommonName
+ ous = certSubj.OrganizationalUnit
+ if len(certSubj.Organization) > 0 {
+ org = certSubj.Organization[0]
+ }
+ }
+
+ // If there's no TLS cert, forward with blank TLS metadata.
+ // Note that the presence of this blank metadata is extremely
+ // important. Without it, it would look like manager is making
+ // the request directly.
+ md[certForwardedKey] = []string{"true"}
+ md[certCNKey] = []string{cn}
+ md[certOrgKey] = []string{org}
+ md[certOUKey] = ous
+ peer, ok := peer.FromContext(ctx)
+ if ok {
+ md[remoteAddrKey] = []string{peer.Addr.String()}
+ }
+
+ return metadata.NewContext(ctx, md), nil
+}
diff --git a/vendor/github.com/docker/swarmkit/ca/keyreadwriter.go b/vendor/github.com/docker/swarmkit/ca/keyreadwriter.go
new file mode 100644
index 0000000..964cb3e
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ca/keyreadwriter.go
@@ -0,0 +1,388 @@
+package ca
+
+import (
+ cryptorand "crypto/rand"
+ "crypto/x509"
+ "encoding/pem"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+
+ "crypto/tls"
+
+ "github.com/docker/swarmkit/ioutils"
+ "github.com/pkg/errors"
+)
+
+const (
+ // keyPerms are the permissions used to write the TLS keys
+ keyPerms = 0600
+ // certPerms are the permissions used to write TLS certificates
+ certPerms = 0644
+ // versionHeader is the TLS PEM key header that contains the KEK version
+ versionHeader = "kek-version"
+)
+
+// PEMKeyHeaders is something that needs to know about PEM headers when reading
+// or writing TLS keys.
+type PEMKeyHeaders interface {
+ // UnmarshalHeaders loads the headers map given the current KEK
+ UnmarshalHeaders(map[string]string, KEKData) (PEMKeyHeaders, error)
+ // MarshalHeaders returns a header map given the current KEK
+ MarshalHeaders(KEKData) (map[string]string, error)
+ // UpdateKEK may get a new PEMKeyHeaders if the KEK changes
+ UpdateKEK(KEKData, KEKData) PEMKeyHeaders
+}
+
+// KeyReader reads a TLS cert and key from disk
+type KeyReader interface {
+ Read() ([]byte, []byte, error)
+ Target() string
+}
+
+// KeyWriter writes a TLS key and cert to disk
+type KeyWriter interface {
+ Write([]byte, []byte, *KEKData) error
+ ViewAndUpdateHeaders(func(PEMKeyHeaders) (PEMKeyHeaders, error)) error
+ ViewAndRotateKEK(func(KEKData, PEMKeyHeaders) (KEKData, PEMKeyHeaders, error)) error
+ GetCurrentState() (PEMKeyHeaders, KEKData)
+ Target() string
+}
+
+// KEKData provides an optional update to the kek when writing. The structure
+// is needed so that we can tell the difference between "do not encrypt anymore"
+// and there is "no update".
+type KEKData struct {
+ KEK []byte
+ Version uint64
+}
+
+// ErrInvalidKEK means that we cannot decrypt the TLS key for some reason
+type ErrInvalidKEK struct {
+ Wrapped error
+}
+
+func (e ErrInvalidKEK) Error() string {
+ return e.Wrapped.Error()
+}
+
+// KeyReadWriter is an object that knows how to read and write TLS keys and certs to disk,
+// optionally encrypted and optionally updating PEM headers.
+type KeyReadWriter struct {
+ mu sync.Mutex
+ kekData KEKData
+ paths CertPaths
+ headersObj PEMKeyHeaders
+}
+
+// NewKeyReadWriter creates a new KeyReadWriter
+func NewKeyReadWriter(paths CertPaths, kek []byte, headersObj PEMKeyHeaders) *KeyReadWriter {
+ return &KeyReadWriter{
+ kekData: KEKData{KEK: kek},
+ paths: paths,
+ headersObj: headersObj,
+ }
+}
+
+// Migrate checks to see if a temporary key file exists. Older versions of
+// swarmkit wrote temporary keys instead of temporary certificates, so
+// migrate that temporary key if it exists. We want to write temporary certificates,
+// instead of temporary keys, because we may need to periodically re-encrypt the
+// keys and modify the headers, and it's easier to have a single canonical key
+// location than two possible key locations.
+func (k *KeyReadWriter) Migrate() error {
+ tmpPaths := k.genTempPaths()
+ keyBytes, err := ioutil.ReadFile(tmpPaths.Key)
+ if err != nil {
+ return nil // no key? no migration
+ }
+
+ // it does exist - no need to decrypt, because previous versions of swarmkit
+ // which supported this temporary key did not support encrypting TLS keys
+ cert, err := ioutil.ReadFile(k.paths.Cert)
+ if err != nil {
+ return os.RemoveAll(tmpPaths.Key) // no cert? no migration
+ }
+
+ // nope, this does not match the cert
+ if _, err = tls.X509KeyPair(cert, keyBytes); err != nil {
+ return os.RemoveAll(tmpPaths.Key)
+ }
+
+ return os.Rename(tmpPaths.Key, k.paths.Key)
+}
+
+// Read will read a TLS cert and key from the given paths
+func (k *KeyReadWriter) Read() ([]byte, []byte, error) {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+ keyBlock, err := k.readKey()
+ if err != nil {
+ return nil, nil, err
+ }
+
+ if version, ok := keyBlock.Headers[versionHeader]; ok {
+ if versionInt, err := strconv.ParseUint(version, 10, 64); err == nil {
+ k.kekData.Version = versionInt
+ }
+ }
+ delete(keyBlock.Headers, versionHeader)
+
+ if k.headersObj != nil {
+ newHeaders, err := k.headersObj.UnmarshalHeaders(keyBlock.Headers, k.kekData)
+ if err != nil {
+ return nil, nil, errors.Wrap(err, "unable to read TLS key headers")
+ }
+ k.headersObj = newHeaders
+ }
+
+ keyBytes := pem.EncodeToMemory(keyBlock)
+ cert, err := ioutil.ReadFile(k.paths.Cert)
+ // The cert is written to a temporary file first, then the key, and then
+ // the cert gets renamed - so, if interrupted, it's possible to end up with
+ // a cert that only exists in the temporary location.
+ switch {
+ case err == nil:
+ _, err = tls.X509KeyPair(cert, keyBytes)
+ case os.IsNotExist(err): //continue to try temp location
+ break
+ default:
+ return nil, nil, err
+ }
+
+ // either the cert doesn't exist, or it doesn't match the key - try the temp file, if it exists
+ if err != nil {
+ var tempErr error
+ tmpPaths := k.genTempPaths()
+ cert, tempErr = ioutil.ReadFile(tmpPaths.Cert)
+ if tempErr != nil {
+ return nil, nil, err // return the original error
+ }
+ if _, tempErr := tls.X509KeyPair(cert, keyBytes); tempErr != nil {
+ os.RemoveAll(tmpPaths.Cert) // nope, it doesn't match either - remove and return the original error
+ return nil, nil, err
+ }
+ os.Rename(tmpPaths.Cert, k.paths.Cert) // try to move the temp cert back to the regular location
+
+ }
+
+ return cert, keyBytes, nil
+}
+
+// ViewAndRotateKEK re-encrypts the key with a new KEK
+func (k *KeyReadWriter) ViewAndRotateKEK(cb func(KEKData, PEMKeyHeaders) (KEKData, PEMKeyHeaders, error)) error {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+
+ updatedKEK, updatedHeaderObj, err := cb(k.kekData, k.headersObj)
+ if err != nil {
+ return err
+ }
+
+ keyBlock, err := k.readKey()
+ if err != nil {
+ return err
+ }
+
+ if err := k.writeKey(keyBlock, updatedKEK, updatedHeaderObj); err != nil {
+ return err
+ }
+ return nil
+}
+
+// ViewAndUpdateHeaders updates the header manager, and updates any headers on the existing key
+func (k *KeyReadWriter) ViewAndUpdateHeaders(cb func(PEMKeyHeaders) (PEMKeyHeaders, error)) error {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+
+ pkh, err := cb(k.headersObj)
+ if err != nil {
+ return err
+ }
+
+ keyBlock, err := k.readKeyblock()
+ if err != nil {
+ return err
+ }
+
+ headers := make(map[string]string)
+ if pkh != nil {
+ var err error
+ headers, err = pkh.MarshalHeaders(k.kekData)
+ if err != nil {
+ return err
+ }
+ }
+ // we WANT any original encryption headers
+ for key, value := range keyBlock.Headers {
+ normalizedKey := strings.TrimSpace(strings.ToLower(key))
+ if normalizedKey == "proc-type" || normalizedKey == "dek-info" {
+ headers[key] = value
+ }
+ }
+ headers[versionHeader] = strconv.FormatUint(k.kekData.Version, 10)
+ keyBlock.Headers = headers
+
+ if err = ioutils.AtomicWriteFile(k.paths.Key, pem.EncodeToMemory(keyBlock), keyPerms); err != nil {
+ return err
+ }
+ k.headersObj = pkh
+ return nil
+}
+
+// GetCurrentState returns the current KEK data, including version
+func (k *KeyReadWriter) GetCurrentState() (PEMKeyHeaders, KEKData) {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+ return k.headersObj, k.kekData
+}
+
+// Write attempts write a cert and key to text. This can also optionally update
+// the KEK while writing, if an updated KEK is provided. If the pointer to the
+// update KEK is nil, then we don't update. If the updated KEK itself is nil,
+// then we update the KEK to be nil (data should be unencrypted).
+func (k *KeyReadWriter) Write(certBytes, plaintextKeyBytes []byte, kekData *KEKData) error {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+
+ // current assumption is that the cert and key will be in the same directory
+ if err := os.MkdirAll(filepath.Dir(k.paths.Key), 0755); err != nil {
+ return err
+ }
+
+ // Ensure that we will have a keypair on disk at all times by writing the cert to a
+ // temp path first. This is because we want to have only a single copy of the key
+ // for rotation and header modification.
+ tmpPaths := k.genTempPaths()
+ if err := ioutils.AtomicWriteFile(tmpPaths.Cert, certBytes, certPerms); err != nil {
+ return err
+ }
+
+ keyBlock, _ := pem.Decode(plaintextKeyBytes)
+ if keyBlock == nil {
+ return errors.New("invalid PEM-encoded private key")
+ }
+
+ if kekData == nil {
+ kekData = &k.kekData
+ }
+ pkh := k.headersObj
+ if k.headersObj != nil {
+ pkh = k.headersObj.UpdateKEK(k.kekData, *kekData)
+ }
+
+ if err := k.writeKey(keyBlock, *kekData, pkh); err != nil {
+ return err
+ }
+ return os.Rename(tmpPaths.Cert, k.paths.Cert)
+}
+
+func (k *KeyReadWriter) genTempPaths() CertPaths {
+ return CertPaths{
+ Key: filepath.Join(filepath.Dir(k.paths.Key), "."+filepath.Base(k.paths.Key)),
+ Cert: filepath.Join(filepath.Dir(k.paths.Cert), "."+filepath.Base(k.paths.Cert)),
+ }
+}
+
+// Target returns a string representation of this KeyReadWriter, namely where
+// it is writing to
+func (k *KeyReadWriter) Target() string {
+ return k.paths.Cert
+}
+
+func (k *KeyReadWriter) readKeyblock() (*pem.Block, error) {
+ key, err := ioutil.ReadFile(k.paths.Key)
+ if err != nil {
+ return nil, err
+ }
+
+ // Decode the PEM private key
+ keyBlock, _ := pem.Decode(key)
+ if keyBlock == nil {
+ return nil, errors.New("invalid PEM-encoded private key")
+ }
+
+ return keyBlock, nil
+}
+
+// readKey returns the decrypted key pem bytes, and enforces the KEK if applicable
+// (writes it back with the correct encryption if it is not correctly encrypted)
+func (k *KeyReadWriter) readKey() (*pem.Block, error) {
+ keyBlock, err := k.readKeyblock()
+ if err != nil {
+ return nil, err
+ }
+
+ if !x509.IsEncryptedPEMBlock(keyBlock) {
+ return keyBlock, nil
+ }
+
+ // If it's encrypted, we can't read without a passphrase (we're assuming
+ // empty passphrases are invalid)
+ if k.kekData.KEK == nil {
+ return nil, ErrInvalidKEK{Wrapped: x509.IncorrectPasswordError}
+ }
+
+ derBytes, err := x509.DecryptPEMBlock(keyBlock, k.kekData.KEK)
+ if err != nil {
+ return nil, ErrInvalidKEK{Wrapped: err}
+ }
+ // remove encryption PEM headers
+ headers := make(map[string]string)
+ mergePEMHeaders(headers, keyBlock.Headers)
+
+ return &pem.Block{
+ Type: keyBlock.Type, // the key type doesn't change
+ Bytes: derBytes,
+ Headers: headers,
+ }, nil
+}
+
+// writeKey takes an unencrypted keyblock and, if the kek is not nil, encrypts it before
+// writing it to disk. If the kek is nil, writes it to disk unencrypted.
+func (k *KeyReadWriter) writeKey(keyBlock *pem.Block, kekData KEKData, pkh PEMKeyHeaders) error {
+ if kekData.KEK != nil {
+ encryptedPEMBlock, err := x509.EncryptPEMBlock(cryptorand.Reader,
+ keyBlock.Type,
+ keyBlock.Bytes,
+ kekData.KEK,
+ x509.PEMCipherAES256)
+ if err != nil {
+ return err
+ }
+ if encryptedPEMBlock.Headers == nil {
+ return errors.New("unable to encrypt key - invalid PEM file produced")
+ }
+ keyBlock = encryptedPEMBlock
+ }
+
+ if pkh != nil {
+ headers, err := pkh.MarshalHeaders(kekData)
+ if err != nil {
+ return err
+ }
+ mergePEMHeaders(keyBlock.Headers, headers)
+ }
+ keyBlock.Headers[versionHeader] = strconv.FormatUint(kekData.Version, 10)
+
+ if err := ioutils.AtomicWriteFile(k.paths.Key, pem.EncodeToMemory(keyBlock), keyPerms); err != nil {
+ return err
+ }
+ k.kekData = kekData
+ k.headersObj = pkh
+ return nil
+}
+
+// merges one set of PEM headers onto another, excepting for key encryption value
+// "proc-type" and "dek-info"
+func mergePEMHeaders(original, newSet map[string]string) {
+ for key, value := range newSet {
+ normalizedKey := strings.TrimSpace(strings.ToLower(key))
+ if normalizedKey != "proc-type" && normalizedKey != "dek-info" {
+ original[key] = value
+ }
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/ca/reconciler.go b/vendor/github.com/docker/swarmkit/ca/reconciler.go
new file mode 100644
index 0000000..6daec76
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ca/reconciler.go
@@ -0,0 +1,259 @@
+package ca
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "reflect"
+ "sync"
+ "time"
+
+ "github.com/cloudflare/cfssl/helpers"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/equality"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/pkg/errors"
+)
+
+// IssuanceStateRotateMaxBatchSize is the maximum number of nodes we'll tell to rotate their certificates in any given update
+const IssuanceStateRotateMaxBatchSize = 30
+
+func hasIssuer(n *api.Node, info *IssuerInfo) bool {
+ if n.Description == nil || n.Description.TLSInfo == nil {
+ return false
+ }
+ return bytes.Equal(info.Subject, n.Description.TLSInfo.CertIssuerSubject) && bytes.Equal(info.PublicKey, n.Description.TLSInfo.CertIssuerPublicKey)
+}
+
+var errRootRotationChanged = errors.New("target root rotation has changed")
+
+// rootRotationReconciler keeps track of all the nodes in the store so that we can determine which ones need reconciliation when nodes are updated
+// or the root CA is updated. This is meant to be used with watches on nodes and the cluster, and provides functions to be called when the
+// cluster's RootCA has changed and when a node is added, updated, or removed.
+type rootRotationReconciler struct {
+ mu sync.Mutex
+ clusterID string
+ batchUpdateInterval time.Duration
+ ctx context.Context
+ store *store.MemoryStore
+
+ currentRootCA *api.RootCA
+ currentIssuer IssuerInfo
+ unconvergedNodes map[string]*api.Node
+
+ wg sync.WaitGroup
+ cancel func()
+}
+
+// IssuerFromAPIRootCA returns the desired issuer given an API root CA object
+func IssuerFromAPIRootCA(rootCA *api.RootCA) (*IssuerInfo, error) {
+ wantedIssuer := rootCA.CACert
+ if rootCA.RootRotation != nil {
+ wantedIssuer = rootCA.RootRotation.CACert
+ }
+ issuerCerts, err := helpers.ParseCertificatesPEM(wantedIssuer)
+ if err != nil {
+ return nil, errors.Wrap(err, "invalid certificate in cluster root CA object")
+ }
+ if len(issuerCerts) == 0 {
+ return nil, errors.New("invalid certificate in cluster root CA object")
+ }
+ return &IssuerInfo{
+ Subject: issuerCerts[0].RawSubject,
+ PublicKey: issuerCerts[0].RawSubjectPublicKeyInfo,
+ }, nil
+}
+
+// assumption: UpdateRootCA will never be called with a `nil` root CA because the caller will be acting in response to
+// a store update event
+func (r *rootRotationReconciler) UpdateRootCA(newRootCA *api.RootCA) {
+ issuerInfo, err := IssuerFromAPIRootCA(newRootCA)
+ if err != nil {
+ log.G(r.ctx).WithError(err).Error("unable to update process the current root CA")
+ return
+ }
+
+ var (
+ shouldStartNewLoop, waitForPrevLoop bool
+ loopCtx context.Context
+ )
+ r.mu.Lock()
+ defer func() {
+ r.mu.Unlock()
+ if shouldStartNewLoop {
+ if waitForPrevLoop {
+ r.wg.Wait()
+ }
+ r.wg.Add(1)
+ go r.runReconcilerLoop(loopCtx, newRootCA)
+ }
+ }()
+
+ // check if the issuer has changed, first
+ if reflect.DeepEqual(&r.currentIssuer, issuerInfo) {
+ r.currentRootCA = newRootCA
+ return
+ }
+ // If the issuer has changed, iterate through all the nodes to figure out which ones need rotation
+ if newRootCA.RootRotation != nil {
+ var nodes []*api.Node
+ r.store.View(func(tx store.ReadTx) {
+ nodes, err = store.FindNodes(tx, store.All)
+ })
+ if err != nil {
+ log.G(r.ctx).WithError(err).Error("unable to list nodes, so unable to process the current root CA")
+ return
+ }
+
+ // from here on out, there will be no more errors that cause us to have to abandon updating the Root CA,
+ // so we can start making changes to r's fields
+ r.unconvergedNodes = make(map[string]*api.Node)
+ for _, n := range nodes {
+ if !hasIssuer(n, issuerInfo) {
+ r.unconvergedNodes[n.ID] = n
+ }
+ }
+ shouldStartNewLoop = true
+ if r.cancel != nil { // there's already a loop going, so cancel it
+ r.cancel()
+ waitForPrevLoop = true
+ }
+ loopCtx, r.cancel = context.WithCancel(r.ctx)
+ } else {
+ r.unconvergedNodes = nil
+ }
+ r.currentRootCA = newRootCA
+ r.currentIssuer = *issuerInfo
+}
+
+// assumption: UpdateNode will never be called with a `nil` node because the caller will be acting in response to
+// a store update event
+func (r *rootRotationReconciler) UpdateNode(node *api.Node) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ // if we're not in the middle of a root rotation ignore the update
+ if r.currentRootCA == nil || r.currentRootCA.RootRotation == nil {
+ return
+ }
+ if hasIssuer(node, &r.currentIssuer) {
+ delete(r.unconvergedNodes, node.ID)
+ } else {
+ r.unconvergedNodes[node.ID] = node
+ }
+}
+
+// assumption: DeleteNode will never be called with a `nil` node because the caller will be acting in response to
+// a store update event
+func (r *rootRotationReconciler) DeleteNode(node *api.Node) {
+ r.mu.Lock()
+ delete(r.unconvergedNodes, node.ID)
+ r.mu.Unlock()
+}
+
+func (r *rootRotationReconciler) runReconcilerLoop(ctx context.Context, loopRootCA *api.RootCA) {
+ defer r.wg.Done()
+ for {
+ r.mu.Lock()
+ if len(r.unconvergedNodes) == 0 {
+ r.mu.Unlock()
+
+ err := r.store.Update(func(tx store.Tx) error {
+ return r.finishRootRotation(tx, loopRootCA)
+ })
+ if err == nil {
+ log.G(r.ctx).Info("completed root rotation")
+ return
+ }
+ log.G(r.ctx).WithError(err).Error("could not complete root rotation")
+ if err == errRootRotationChanged {
+ // if the root rotation has changed, this loop will be cancelled anyway, so may as well abort early
+ return
+ }
+ } else {
+ var toUpdate []*api.Node
+ for _, n := range r.unconvergedNodes {
+ iState := n.Certificate.Status.State
+ if iState != api.IssuanceStateRenew && iState != api.IssuanceStatePending && iState != api.IssuanceStateRotate {
+ n = n.Copy()
+ n.Certificate.Status.State = api.IssuanceStateRotate
+ toUpdate = append(toUpdate, n)
+ if len(toUpdate) >= IssuanceStateRotateMaxBatchSize {
+ break
+ }
+ }
+ }
+ r.mu.Unlock()
+
+ if err := r.batchUpdateNodes(toUpdate); err != nil {
+ log.G(r.ctx).WithError(err).Errorf("store error when trying to batch update %d nodes to request certificate rotation", len(toUpdate))
+ }
+ }
+
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(r.batchUpdateInterval):
+ }
+ }
+}
+
+// This function assumes that the expected root CA has root rotation. This is intended to be used by
+// `reconcileNodeRootsAndCerts`, which uses the root CA from the `lastSeenClusterRootCA`, and checks
+// that it has a root rotation before calling this function.
+func (r *rootRotationReconciler) finishRootRotation(tx store.Tx, expectedRootCA *api.RootCA) error {
+ cluster := store.GetCluster(tx, r.clusterID)
+ if cluster == nil {
+ return fmt.Errorf("unable to get cluster %s", r.clusterID)
+ }
+
+ // If the RootCA object has changed (because another root rotation was started or because some other node
+ // had finished the root rotation), we cannot finish the root rotation that we were working on.
+ if !equality.RootCAEqualStable(expectedRootCA, &cluster.RootCA) {
+ return errRootRotationChanged
+ }
+
+ var signerCert []byte
+ if len(cluster.RootCA.RootRotation.CAKey) > 0 {
+ signerCert = cluster.RootCA.RootRotation.CACert
+ }
+ // we don't actually have to parse out the default node expiration from the cluster - we are just using
+ // the ca.RootCA object to generate new tokens and the digest
+ updatedRootCA, err := NewRootCA(cluster.RootCA.RootRotation.CACert, signerCert, cluster.RootCA.RootRotation.CAKey,
+ DefaultNodeCertExpiration, nil)
+ if err != nil {
+ return errors.Wrap(err, "invalid cluster root rotation object")
+ }
+ cluster.RootCA = api.RootCA{
+ CACert: cluster.RootCA.RootRotation.CACert,
+ CAKey: cluster.RootCA.RootRotation.CAKey,
+ CACertHash: updatedRootCA.Digest.String(),
+ JoinTokens: api.JoinTokens{
+ Worker: GenerateJoinToken(&updatedRootCA),
+ Manager: GenerateJoinToken(&updatedRootCA),
+ },
+ LastForcedRotation: cluster.RootCA.LastForcedRotation,
+ }
+ return store.UpdateCluster(tx, cluster)
+}
+
+func (r *rootRotationReconciler) batchUpdateNodes(toUpdate []*api.Node) error {
+ if len(toUpdate) == 0 {
+ return nil
+ }
+ err := r.store.Batch(func(batch *store.Batch) error {
+ // Directly update the nodes rather than get + update, and ignore version errors. Since
+ // `rootRotationReconciler` should be hooked up to all node update/delete/create events, we should have
+ // close to the latest versions of all the nodes. If not, the node will updated later and the
+ // next batch of updates should catch it.
+ for _, n := range toUpdate {
+ if err := batch.Update(func(tx store.Tx) error {
+ return store.UpdateNode(tx, n)
+ }); err != nil && err != store.ErrSequenceConflict {
+ log.G(r.ctx).WithError(err).Errorf("unable to update node %s to request a certificate rotation", n.ID)
+ }
+ }
+ return nil
+ })
+ return err
+}
diff --git a/vendor/github.com/docker/swarmkit/ca/renewer.go b/vendor/github.com/docker/swarmkit/ca/renewer.go
new file mode 100644
index 0000000..6d0229b
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ca/renewer.go
@@ -0,0 +1,168 @@
+package ca
+
+import (
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/connectionbroker"
+ "github.com/docker/swarmkit/log"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+// RenewTLSExponentialBackoff sets the exponential backoff when trying to renew TLS certificates that have expired
+var RenewTLSExponentialBackoff = events.ExponentialBackoffConfig{
+ Base: time.Second * 5,
+ Factor: time.Second * 5,
+ Max: 1 * time.Hour,
+}
+
+// TLSRenewer handles renewing TLS certificates, either automatically or upon
+// request.
+type TLSRenewer struct {
+ mu sync.Mutex
+ s *SecurityConfig
+ connBroker *connectionbroker.Broker
+ renew chan struct{}
+ expectedRole string
+ rootPaths CertPaths
+}
+
+// NewTLSRenewer creates a new TLS renewer. It must be started with Start.
+func NewTLSRenewer(s *SecurityConfig, connBroker *connectionbroker.Broker, rootPaths CertPaths) *TLSRenewer {
+ return &TLSRenewer{
+ s: s,
+ connBroker: connBroker,
+ renew: make(chan struct{}, 1),
+ rootPaths: rootPaths,
+ }
+}
+
+// SetExpectedRole sets the expected role. If a renewal is forced, and the role
+// doesn't match this expectation, renewal will be retried with exponential
+// backoff until it does match.
+func (t *TLSRenewer) SetExpectedRole(role string) {
+ t.mu.Lock()
+ t.expectedRole = role
+ t.mu.Unlock()
+}
+
+// Renew causes the TLSRenewer to renew the certificate (nearly) right away,
+// instead of waiting for the next automatic renewal.
+func (t *TLSRenewer) Renew() {
+ select {
+ case t.renew <- struct{}{}:
+ default:
+ }
+}
+
+// Start will continuously monitor for the necessity of renewing the local certificates, either by
+// issuing them locally if key-material is available, or requesting them from a remote CA.
+func (t *TLSRenewer) Start(ctx context.Context) <-chan CertificateUpdate {
+ updates := make(chan CertificateUpdate)
+
+ go func() {
+ var (
+ retry time.Duration
+ forceRetry bool
+ )
+ expBackoff := events.NewExponentialBackoff(RenewTLSExponentialBackoff)
+ defer close(updates)
+ for {
+ ctx = log.WithModule(ctx, "tls")
+ log := log.G(ctx).WithFields(logrus.Fields{
+ "node.id": t.s.ClientTLSCreds.NodeID(),
+ "node.role": t.s.ClientTLSCreds.Role(),
+ })
+ // Our starting default will be 5 minutes
+ retry = 5 * time.Minute
+
+ // Since the expiration of the certificate is managed remotely we should update our
+ // retry timer on every iteration of this loop.
+ // Retrieve the current certificate expiration information.
+ validFrom, validUntil, err := readCertValidity(t.s.KeyReader())
+ if err != nil {
+ // We failed to read the expiration, let's stick with the starting default
+ log.Errorf("failed to read the expiration of the TLS certificate in: %s", t.s.KeyReader().Target())
+
+ select {
+ case updates <- CertificateUpdate{Err: errors.New("failed to read certificate expiration")}:
+ case <-ctx.Done():
+ log.Info("shutting down certificate renewal routine")
+ return
+ }
+ } else {
+ // If we have an expired certificate, try to renew immediately: the hope that this is a temporary clock skew, or
+ // we can issue our own TLS certs.
+ if validUntil.Before(time.Now()) {
+ log.Warn("the current TLS certificate is expired, so an attempt to renew it will be made immediately")
+ // retry immediately(ish) with exponential backoff
+ retry = expBackoff.Proceed(nil)
+ } else if forceRetry {
+ // A forced renewal was requested, but did not succeed yet.
+ // retry immediately(ish) with exponential backoff
+ retry = expBackoff.Proceed(nil)
+ } else {
+ // Random retry time between 50% and 80% of the total time to expiration
+ retry = calculateRandomExpiry(validFrom, validUntil)
+ }
+ }
+
+ log.WithFields(logrus.Fields{
+ "time": time.Now().Add(retry),
+ }).Debugf("next certificate renewal scheduled for %v from now", retry)
+
+ select {
+ case <-time.After(retry):
+ log.Info("renewing certificate")
+ case <-t.renew:
+ forceRetry = true
+ log.Info("forced certificate renewal")
+
+ // Pause briefly before attempting the renewal,
+ // to give the CA a chance to reconcile the
+ // desired role.
+ select {
+ case <-time.After(500 * time.Millisecond):
+ case <-ctx.Done():
+ log.Info("shutting down certificate renewal routine")
+ return
+ }
+ case <-ctx.Done():
+ log.Info("shutting down certificate renewal routine")
+ return
+ }
+
+ // ignore errors - it will just try again later
+ var certUpdate CertificateUpdate
+ if err := RenewTLSConfigNow(ctx, t.s, t.connBroker, t.rootPaths); err != nil {
+ certUpdate.Err = err
+ expBackoff.Failure(nil, nil)
+ } else {
+ newRole := t.s.ClientTLSCreds.Role()
+ t.mu.Lock()
+ expectedRole := t.expectedRole
+ t.mu.Unlock()
+ if expectedRole != "" && expectedRole != newRole {
+ expBackoff.Failure(nil, nil)
+ continue
+ }
+
+ certUpdate.Role = newRole
+ expBackoff.Success(nil)
+ forceRetry = false
+ }
+
+ select {
+ case updates <- certUpdate:
+ case <-ctx.Done():
+ log.Info("shutting down certificate renewal routine")
+ return
+ }
+ }
+ }()
+
+ return updates
+}
diff --git a/vendor/github.com/docker/swarmkit/ca/server.go b/vendor/github.com/docker/swarmkit/ca/server.go
new file mode 100644
index 0000000..cb3b6ac
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ca/server.go
@@ -0,0 +1,849 @@
+package ca
+
+import (
+ "bytes"
+ "crypto/subtle"
+ "crypto/x509"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/equality"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state/store"
+ gogotypes "github.com/gogo/protobuf/types"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+const (
+ defaultReconciliationRetryInterval = 10 * time.Second
+ defaultRootReconciliationInterval = 3 * time.Second
+)
+
+// APISecurityConfigUpdater knows how to update a SecurityConfig from an api.Cluster object
+type APISecurityConfigUpdater interface {
+ UpdateRootCA(ctx context.Context, cluster *api.Cluster) error
+}
+
+var _ APISecurityConfigUpdater = &Server{}
+
+// Server is the CA and NodeCA API gRPC server.
+// TODO(aaronl): At some point we may want to have separate implementations of
+// CA, NodeCA, and other hypothetical future CA services. At the moment,
+// breaking it apart doesn't seem worth it.
+type Server struct {
+ mu sync.Mutex
+ wg sync.WaitGroup
+ ctx context.Context
+ cancel func()
+ store *store.MemoryStore
+ securityConfig *SecurityConfig
+ joinTokens *api.JoinTokens
+ reconciliationRetryInterval time.Duration
+
+ // pending is a map of nodes with pending certificates issuance or
+ // renewal. They are indexed by node ID.
+ pending map[string]*api.Node
+
+ // started is a channel which gets closed once the server is running
+ // and able to service RPCs.
+ started chan struct{}
+
+ // these are cached values to ensure we only update the security config when
+ // the cluster root CA and external CAs have changed - the cluster object
+ // can change for other reasons, and it would not be necessary to update
+ // the security config as a result
+ lastSeenClusterRootCA *api.RootCA
+ lastSeenExternalCAs []*api.ExternalCA
+ secConfigMu sync.Mutex
+
+ // before we update the security config with the new root CA, we need to be able to save the root certs
+ rootPaths CertPaths
+
+ // lets us monitor and finish root rotations
+ rootReconciler *rootRotationReconciler
+ rootReconciliationRetryInterval time.Duration
+}
+
+// DefaultCAConfig returns the default CA Config, with a default expiration.
+func DefaultCAConfig() api.CAConfig {
+ return api.CAConfig{
+ NodeCertExpiry: gogotypes.DurationProto(DefaultNodeCertExpiration),
+ }
+}
+
+// NewServer creates a CA API server.
+func NewServer(store *store.MemoryStore, securityConfig *SecurityConfig, rootCAPaths CertPaths) *Server {
+ return &Server{
+ store: store,
+ securityConfig: securityConfig,
+ pending: make(map[string]*api.Node),
+ started: make(chan struct{}),
+ reconciliationRetryInterval: defaultReconciliationRetryInterval,
+ rootReconciliationRetryInterval: defaultRootReconciliationInterval,
+ rootPaths: rootCAPaths,
+ }
+}
+
+// SetReconciliationRetryInterval changes the time interval between
+// reconciliation attempts. This function must be called before Run.
+func (s *Server) SetReconciliationRetryInterval(reconciliationRetryInterval time.Duration) {
+ s.reconciliationRetryInterval = reconciliationRetryInterval
+}
+
+// SetRootReconciliationInterval changes the time interval between root rotation
+// reconciliation attempts. This function must be called before Run.
+func (s *Server) SetRootReconciliationInterval(interval time.Duration) {
+ s.rootReconciliationRetryInterval = interval
+}
+
+// GetUnlockKey is responsible for returning the current unlock key used for encrypting TLS private keys and
+// other at rest data. Access to this RPC call should only be allowed via mutual TLS from managers.
+func (s *Server) GetUnlockKey(ctx context.Context, request *api.GetUnlockKeyRequest) (*api.GetUnlockKeyResponse, error) {
+ // This directly queries the store, rather than storing the unlock key and version on
+ // the `Server` object and updating it `updateCluster` is called, because we need this
+ // API to return the latest version of the key. Otherwise, there might be a slight delay
+ // between when the cluster gets updated, and when this function returns the latest key.
+ // This delay is currently unacceptable because this RPC call is the only way, after a
+ // cluster update, to get the actual value of the unlock key, and we don't want to return
+ // a cached value.
+ resp := api.GetUnlockKeyResponse{}
+ s.store.View(func(tx store.ReadTx) {
+ cluster := store.GetCluster(tx, s.securityConfig.ClientTLSCreds.Organization())
+ resp.Version = cluster.Meta.Version
+ if cluster.Spec.EncryptionConfig.AutoLockManagers {
+ for _, encryptionKey := range cluster.UnlockKeys {
+ if encryptionKey.Subsystem == ManagerRole {
+ resp.UnlockKey = encryptionKey.Key
+ return
+ }
+ }
+ }
+ })
+
+ return &resp, nil
+}
+
+// NodeCertificateStatus returns the current issuance status of an issuance request identified by the nodeID
+func (s *Server) NodeCertificateStatus(ctx context.Context, request *api.NodeCertificateStatusRequest) (*api.NodeCertificateStatusResponse, error) {
+ if request.NodeID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, codes.InvalidArgument.String())
+ }
+
+ serverCtx, err := s.isRunningLocked()
+ if err != nil {
+ return nil, err
+ }
+
+ var node *api.Node
+
+ event := api.EventUpdateNode{
+ Node: &api.Node{ID: request.NodeID},
+ Checks: []api.NodeCheckFunc{api.NodeCheckID},
+ }
+
+ // Retrieve the current value of the certificate with this token, and create a watcher
+ updates, cancel, err := store.ViewAndWatch(
+ s.store,
+ func(tx store.ReadTx) error {
+ node = store.GetNode(tx, request.NodeID)
+ return nil
+ },
+ event,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer cancel()
+
+ // This node ID doesn't exist
+ if node == nil {
+ return nil, grpc.Errorf(codes.NotFound, codes.NotFound.String())
+ }
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": node.ID,
+ "status": node.Certificate.Status,
+ "method": "NodeCertificateStatus",
+ })
+
+ // If this certificate has a final state, return it immediately (both pending and renew are transition states)
+ if isFinalState(node.Certificate.Status) {
+ return &api.NodeCertificateStatusResponse{
+ Status: &node.Certificate.Status,
+ Certificate: &node.Certificate,
+ }, nil
+ }
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": node.ID,
+ "status": node.Certificate.Status,
+ "method": "NodeCertificateStatus",
+ }).Debugf("started watching for certificate updates")
+
+ // Certificate is Pending or in an Unknown state, let's wait for changes.
+ for {
+ select {
+ case event := <-updates:
+ switch v := event.(type) {
+ case api.EventUpdateNode:
+ // We got an update on the certificate record. If the status is a final state,
+ // return the certificate.
+ if isFinalState(v.Node.Certificate.Status) {
+ cert := v.Node.Certificate.Copy()
+ return &api.NodeCertificateStatusResponse{
+ Status: &cert.Status,
+ Certificate: cert,
+ }, nil
+ }
+ }
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-serverCtx.Done():
+ return nil, s.ctx.Err()
+ }
+ }
+}
+
+// IssueNodeCertificate is responsible for gatekeeping both certificate requests from new nodes in the swarm,
+// and authorizing certificate renewals.
+// If a node presented a valid certificate, the corresponding certificate is set in a RENEW state.
+// If a node failed to present a valid certificate, we check for a valid join token and set the
+// role accordingly. A new random node ID is generated, and the corresponding node entry is created.
+// IssueNodeCertificate is the only place where new node entries to raft should be created.
+func (s *Server) IssueNodeCertificate(ctx context.Context, request *api.IssueNodeCertificateRequest) (*api.IssueNodeCertificateResponse, error) {
+ // First, let's see if the remote node is presenting a non-empty CSR
+ if len(request.CSR) == 0 {
+ return nil, grpc.Errorf(codes.InvalidArgument, codes.InvalidArgument.String())
+ }
+
+ if _, err := s.isRunningLocked(); err != nil {
+ return nil, err
+ }
+
+ var (
+ blacklistedCerts map[string]*api.BlacklistedCertificate
+ clusters []*api.Cluster
+ err error
+ )
+
+ s.store.View(func(readTx store.ReadTx) {
+ clusters, err = store.FindClusters(readTx, store.ByName("default"))
+
+ })
+
+ // Not having a cluster object yet means we can't check
+ // the blacklist.
+ if err == nil && len(clusters) == 1 {
+ blacklistedCerts = clusters[0].BlacklistedCertificates
+ }
+
+ // Renewing the cert with a local (unix socket) is always valid.
+ localNodeInfo := ctx.Value(LocalRequestKey)
+ if localNodeInfo != nil {
+ nodeInfo, ok := localNodeInfo.(RemoteNodeInfo)
+ if ok && nodeInfo.NodeID != "" {
+ return s.issueRenewCertificate(ctx, nodeInfo.NodeID, request.CSR)
+ }
+ }
+
+ // If the remote node is a worker (either forwarded by a manager, or calling directly),
+ // issue a renew worker certificate entry with the correct ID
+ nodeID, err := AuthorizeForwardedRoleAndOrg(ctx, []string{WorkerRole}, []string{ManagerRole}, s.securityConfig.ClientTLSCreds.Organization(), blacklistedCerts)
+ if err == nil {
+ return s.issueRenewCertificate(ctx, nodeID, request.CSR)
+ }
+
+ // If the remote node is a manager (either forwarded by another manager, or calling directly),
+ // issue a renew certificate entry with the correct ID
+ nodeID, err = AuthorizeForwardedRoleAndOrg(ctx, []string{ManagerRole}, []string{ManagerRole}, s.securityConfig.ClientTLSCreds.Organization(), blacklistedCerts)
+ if err == nil {
+ return s.issueRenewCertificate(ctx, nodeID, request.CSR)
+ }
+
+ // The remote node didn't successfully present a valid MTLS certificate, let's issue a
+ // certificate with a new random ID
+ role := api.NodeRole(-1)
+
+ s.mu.Lock()
+ if subtle.ConstantTimeCompare([]byte(s.joinTokens.Manager), []byte(request.Token)) == 1 {
+ role = api.NodeRoleManager
+ } else if subtle.ConstantTimeCompare([]byte(s.joinTokens.Worker), []byte(request.Token)) == 1 {
+ role = api.NodeRoleWorker
+ }
+ s.mu.Unlock()
+
+ if role < 0 {
+ return nil, grpc.Errorf(codes.InvalidArgument, "A valid join token is necessary to join this cluster")
+ }
+
+ // Max number of collisions of ID or CN to tolerate before giving up
+ maxRetries := 3
+ // Generate a random ID for this new node
+ for i := 0; ; i++ {
+ nodeID = identity.NewID()
+
+ // Create a new node
+ err := s.store.Update(func(tx store.Tx) error {
+ node := &api.Node{
+ Role: role,
+ ID: nodeID,
+ Certificate: api.Certificate{
+ CSR: request.CSR,
+ CN: nodeID,
+ Role: role,
+ Status: api.IssuanceStatus{
+ State: api.IssuanceStatePending,
+ },
+ },
+ Spec: api.NodeSpec{
+ DesiredRole: role,
+ Membership: api.NodeMembershipAccepted,
+ Availability: request.Availability,
+ },
+ }
+
+ return store.CreateNode(tx, node)
+ })
+ if err == nil {
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": nodeID,
+ "node.role": role,
+ "method": "IssueNodeCertificate",
+ }).Debugf("new certificate entry added")
+ break
+ }
+ if err != store.ErrExist {
+ return nil, err
+ }
+ if i == maxRetries {
+ return nil, err
+ }
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": nodeID,
+ "node.role": role,
+ "method": "IssueNodeCertificate",
+ }).Errorf("randomly generated node ID collided with an existing one - retrying")
+ }
+
+ return &api.IssueNodeCertificateResponse{
+ NodeID: nodeID,
+ NodeMembership: api.NodeMembershipAccepted,
+ }, nil
+}
+
+// issueRenewCertificate receives a nodeID and a CSR and modifies the node's certificate entry with the new CSR
+// and changes the state to RENEW, so it can be picked up and signed by the signing reconciliation loop
+func (s *Server) issueRenewCertificate(ctx context.Context, nodeID string, csr []byte) (*api.IssueNodeCertificateResponse, error) {
+ var (
+ cert api.Certificate
+ node *api.Node
+ )
+ err := s.store.Update(func(tx store.Tx) error {
+ // Attempt to retrieve the node with nodeID
+ node = store.GetNode(tx, nodeID)
+ if node == nil {
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": nodeID,
+ "method": "issueRenewCertificate",
+ }).Warnf("node does not exist")
+ // If this node doesn't exist, we shouldn't be renewing a certificate for it
+ return grpc.Errorf(codes.NotFound, "node %s not found when attempting to renew certificate", nodeID)
+ }
+
+ // Create a new Certificate entry for this node with the new CSR and a RENEW state
+ cert = api.Certificate{
+ CSR: csr,
+ CN: node.ID,
+ Role: node.Role,
+ Status: api.IssuanceStatus{
+ State: api.IssuanceStateRenew,
+ },
+ }
+
+ node.Certificate = cert
+ return store.UpdateNode(tx, node)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "cert.cn": cert.CN,
+ "cert.role": cert.Role,
+ "method": "issueRenewCertificate",
+ }).Debugf("node certificate updated")
+
+ return &api.IssueNodeCertificateResponse{
+ NodeID: nodeID,
+ NodeMembership: node.Spec.Membership,
+ }, nil
+}
+
+// GetRootCACertificate returns the certificate of the Root CA. It is used as a convenience for distributing
+// the root of trust for the swarm. Clients should be using the CA hash to verify if they weren't target to
+// a MiTM. If they fail to do so, node bootstrap works with TOFU semantics.
+func (s *Server) GetRootCACertificate(ctx context.Context, request *api.GetRootCACertificateRequest) (*api.GetRootCACertificateResponse, error) {
+ log.G(ctx).WithFields(logrus.Fields{
+ "method": "GetRootCACertificate",
+ })
+
+ return &api.GetRootCACertificateResponse{
+ Certificate: s.securityConfig.RootCA().Certs,
+ }, nil
+}
+
+// Run runs the CA signer main loop.
+// The CA signer can be stopped with cancelling ctx or calling Stop().
+func (s *Server) Run(ctx context.Context) error {
+ s.mu.Lock()
+ if s.isRunning() {
+ s.mu.Unlock()
+ return errors.New("CA signer is already running")
+ }
+ s.wg.Add(1)
+ s.ctx, s.cancel = context.WithCancel(log.WithModule(ctx, "ca"))
+ ctx = s.ctx
+ // we need to set it on the server, because `Server.UpdateRootCA` can be called from outside the Run function
+ s.rootReconciler = &rootRotationReconciler{
+ ctx: log.WithField(ctx, "method", "(*Server).rootRotationReconciler"),
+ clusterID: s.securityConfig.ClientTLSCreds.Organization(),
+ store: s.store,
+ batchUpdateInterval: s.rootReconciliationRetryInterval,
+ }
+ rootReconciler := s.rootReconciler
+ s.mu.Unlock()
+ defer s.wg.Done()
+ defer func() {
+ s.mu.Lock()
+ s.rootReconciler = nil
+ s.mu.Unlock()
+ }()
+
+ // Retrieve the channels to keep track of changes in the cluster
+ // Retrieve all the currently registered nodes
+ var nodes []*api.Node
+
+ updates, cancel, err := store.ViewAndWatch(
+ s.store,
+ func(readTx store.ReadTx) error {
+ clusters, err := store.FindClusters(readTx, store.ByName(store.DefaultClusterName))
+ if err != nil {
+ return err
+ }
+ if len(clusters) != 1 {
+ return errors.New("could not find cluster object")
+ }
+ s.UpdateRootCA(ctx, clusters[0]) // call once to ensure that the join tokens are always set
+ nodes, err = store.FindNodes(readTx, store.All)
+ return err
+ },
+ api.EventCreateNode{},
+ api.EventUpdateNode{},
+ api.EventDeleteNode{},
+ )
+
+ // Do this after updateCluster has been called, so isRunning never
+ // returns true without joinTokens being set correctly.
+ s.mu.Lock()
+ close(s.started)
+ s.mu.Unlock()
+
+ if err != nil {
+ log.G(ctx).WithFields(logrus.Fields{
+ "method": "(*Server).Run",
+ }).WithError(err).Errorf("snapshot store view failed")
+ return err
+ }
+ defer cancel()
+
+ // We might have missed some updates if there was a leader election,
+ // so let's pick up the slack.
+ if err := s.reconcileNodeCertificates(ctx, nodes); err != nil {
+ // We don't return here because that means the Run loop would
+ // never run. Log an error instead.
+ log.G(ctx).WithFields(logrus.Fields{
+ "method": "(*Server).Run",
+ }).WithError(err).Errorf("error attempting to reconcile certificates")
+ }
+
+ ticker := time.NewTicker(s.reconciliationRetryInterval)
+ defer ticker.Stop()
+
+ // Watch for new nodes being created, new nodes being updated, and changes
+ // to the cluster
+ for {
+ select {
+ case <-ctx.Done():
+ return nil
+ default:
+ }
+
+ select {
+ case event := <-updates:
+ switch v := event.(type) {
+ case api.EventCreateNode:
+ s.evaluateAndSignNodeCert(ctx, v.Node)
+ rootReconciler.UpdateNode(v.Node)
+ case api.EventUpdateNode:
+ // If this certificate is already at a final state
+ // no need to evaluate and sign it.
+ if !isFinalState(v.Node.Certificate.Status) {
+ s.evaluateAndSignNodeCert(ctx, v.Node)
+ }
+ rootReconciler.UpdateNode(v.Node)
+ case api.EventDeleteNode:
+ rootReconciler.DeleteNode(v.Node)
+ }
+
+ case <-ticker.C:
+ for _, node := range s.pending {
+ if err := s.evaluateAndSignNodeCert(ctx, node); err != nil {
+ // If this sign operation did not succeed, the rest are
+ // unlikely to. Yield so that we don't hammer an external CA.
+ // Since the map iteration order is randomized, there is no
+ // risk of getting stuck on a problematic CSR.
+ break
+ }
+ }
+ case <-ctx.Done():
+ return nil
+ }
+ }
+}
+
+// Stop stops the CA and closes all grpc streams.
+func (s *Server) Stop() error {
+ s.mu.Lock()
+
+ if !s.isRunning() {
+ s.mu.Unlock()
+ return errors.New("CA signer is already stopped")
+ }
+ s.cancel()
+ s.started = make(chan struct{})
+ s.mu.Unlock()
+
+ // Wait for Run to complete
+ s.wg.Wait()
+
+ return nil
+}
+
+// Ready waits on the ready channel and returns when the server is ready to serve.
+func (s *Server) Ready() <-chan struct{} {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.started
+}
+
+func (s *Server) isRunningLocked() (context.Context, error) {
+ s.mu.Lock()
+ if !s.isRunning() {
+ s.mu.Unlock()
+ return nil, grpc.Errorf(codes.Aborted, "CA signer is stopped")
+ }
+ ctx := s.ctx
+ s.mu.Unlock()
+ return ctx, nil
+}
+
+func (s *Server) isRunning() bool {
+ if s.ctx == nil {
+ return false
+ }
+ select {
+ case <-s.ctx.Done():
+ return false
+ default:
+ }
+ return true
+}
+
+// UpdateRootCA is called when there are cluster changes, and it ensures that the local RootCA is
+// always aware of changes in clusterExpiry and the Root CA key material - this can be called by
+// anything to update the root CA material
+func (s *Server) UpdateRootCA(ctx context.Context, cluster *api.Cluster) error {
+ s.mu.Lock()
+ s.joinTokens = cluster.RootCA.JoinTokens.Copy()
+ reconciler := s.rootReconciler
+ s.mu.Unlock()
+ rCA := cluster.RootCA.Copy()
+ if reconciler != nil {
+ reconciler.UpdateRootCA(rCA)
+ }
+
+ s.secConfigMu.Lock()
+ defer s.secConfigMu.Unlock()
+ firstSeenCluster := s.lastSeenClusterRootCA == nil && s.lastSeenExternalCAs == nil
+ rootCAChanged := len(rCA.CACert) != 0 && !equality.RootCAEqualStable(s.lastSeenClusterRootCA, rCA)
+ externalCAChanged := !equality.ExternalCAsEqualStable(s.lastSeenExternalCAs, cluster.Spec.CAConfig.ExternalCAs)
+ logger := log.G(ctx).WithFields(logrus.Fields{
+ "cluster.id": cluster.ID,
+ "method": "(*Server).UpdateRootCA",
+ })
+
+ if rootCAChanged {
+ setOrUpdate := "set"
+ if !firstSeenCluster {
+ logger.Debug("Updating security config due to change in cluster Root CA")
+ setOrUpdate = "updated"
+ }
+ expiry := DefaultNodeCertExpiration
+ if cluster.Spec.CAConfig.NodeCertExpiry != nil {
+ // NodeCertExpiry exists, let's try to parse the duration out of it
+ clusterExpiry, err := gogotypes.DurationFromProto(cluster.Spec.CAConfig.NodeCertExpiry)
+ if err != nil {
+ logger.WithError(err).Warn("failed to parse certificate expiration, using default")
+ } else {
+ // We were able to successfully parse the expiration out of the cluster.
+ expiry = clusterExpiry
+ }
+ } else {
+ // NodeCertExpiry seems to be nil
+ logger.Warn("no certificate expiration specified, using default")
+ }
+ // Attempt to update our local RootCA with the new parameters
+ var intermediates []byte
+ signingCert := rCA.CACert
+ signingKey := rCA.CAKey
+ if rCA.RootRotation != nil {
+ signingCert = rCA.RootRotation.CrossSignedCACert
+ signingKey = rCA.RootRotation.CAKey
+ intermediates = rCA.RootRotation.CrossSignedCACert
+ }
+ if signingKey == nil {
+ signingCert = nil
+ }
+ updatedRootCA, err := NewRootCA(rCA.CACert, signingCert, signingKey, expiry, intermediates)
+ if err != nil {
+ return errors.Wrap(err, "invalid Root CA object in cluster")
+ }
+ externalCARootPool := updatedRootCA.Pool
+ if rCA.RootRotation != nil {
+ // the external CA has to trust the new CA cert
+ externalCARootPool = x509.NewCertPool()
+ externalCARootPool.AppendCertsFromPEM(rCA.CACert)
+ externalCARootPool.AppendCertsFromPEM(rCA.RootRotation.CACert)
+ }
+
+ // Attempt to update our local RootCA with the new parameters
+ if err := s.securityConfig.UpdateRootCA(&updatedRootCA, externalCARootPool); err != nil {
+ return errors.Wrap(err, "updating Root CA failed")
+ }
+ if err := SaveRootCA(updatedRootCA, s.rootPaths); err != nil {
+ return errors.Wrap(err, "unable to save new root CA certificates")
+ }
+ // only update the server cache if we've successfully updated the root CA
+ logger.Debugf("Root CA %s successfully", setOrUpdate)
+ s.lastSeenClusterRootCA = rCA
+ }
+
+ // we want to update if the external CA changed, or if the root CA changed because the root CA could affect what
+ // certificate for external CAs we want to filter by
+ if rootCAChanged || externalCAChanged {
+ if !firstSeenCluster {
+ logger.Debug("Updating security config external CA URLs due to change in cluster Root CA or cluster spec")
+ }
+ wantedExternalCACert := rCA.CACert // we want to only add external CA URLs that use this cert
+ if rCA.RootRotation != nil {
+ // we're rotating to a new root, so we only want external CAs with the new root cert
+ wantedExternalCACert = rCA.RootRotation.CACert
+ }
+ wantedExternalCACert = NormalizePEMs(wantedExternalCACert)
+ // Update our security config with the list of External CA URLs
+ // from the new cluster state.
+
+ // TODO(aaronl): In the future, this will be abstracted with an
+ // ExternalCA interface that has different implementations for
+ // different CA types. At the moment, only CFSSL is supported.
+ var cfsslURLs []string
+ for i, extCA := range cluster.Spec.CAConfig.ExternalCAs {
+ // We want to support old external CA specifications which did not have a CA cert. If there is no cert specified,
+ // we assume it's the old cert
+ certForExtCA := extCA.CACert
+ if len(certForExtCA) == 0 {
+ certForExtCA = rCA.CACert
+ }
+ certForExtCA = NormalizePEMs(certForExtCA)
+ if extCA.Protocol != api.ExternalCA_CAProtocolCFSSL {
+ logger.Debugf("skipping external CA %d (url: %s) due to unknown protocol type", i, extCA.URL)
+ continue
+ }
+ if !bytes.Equal(certForExtCA, wantedExternalCACert) {
+ logger.Debugf("skipping external CA %d (url: %s) because it has the wrong CA cert", i, extCA.URL)
+ continue
+ }
+ cfsslURLs = append(cfsslURLs, extCA.URL)
+ }
+
+ s.securityConfig.externalCA.UpdateURLs(cfsslURLs...)
+ s.lastSeenExternalCAs = cluster.Spec.CAConfig.Copy().ExternalCAs
+ }
+ return nil
+}
+
+// evaluateAndSignNodeCert implements the logic of which certificates to sign
+func (s *Server) evaluateAndSignNodeCert(ctx context.Context, node *api.Node) error {
+ // If the desired membership and actual state are in sync, there's
+ // nothing to do.
+ certState := node.Certificate.Status.State
+ if node.Spec.Membership == api.NodeMembershipAccepted &&
+ (certState == api.IssuanceStateIssued || certState == api.IssuanceStateRotate) {
+ return nil
+ }
+
+ // If the certificate state is renew, then it is a server-sided accepted cert (cert renewals)
+ if certState == api.IssuanceStateRenew {
+ return s.signNodeCert(ctx, node)
+ }
+
+ // Sign this certificate if a user explicitly changed it to Accepted, and
+ // the certificate is in pending state
+ if node.Spec.Membership == api.NodeMembershipAccepted && certState == api.IssuanceStatePending {
+ return s.signNodeCert(ctx, node)
+ }
+
+ return nil
+}
+
+// signNodeCert does the bulk of the work for signing a certificate
+func (s *Server) signNodeCert(ctx context.Context, node *api.Node) error {
+ rootCA := s.securityConfig.RootCA()
+ externalCA := s.securityConfig.externalCA
+
+ node = node.Copy()
+ nodeID := node.ID
+ // Convert the role from proto format
+ role, err := ParseRole(node.Certificate.Role)
+ if err != nil {
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": node.ID,
+ "method": "(*Server).signNodeCert",
+ }).WithError(err).Errorf("failed to parse role")
+ return errors.New("failed to parse role")
+ }
+
+ s.pending[node.ID] = node
+
+ // Attempt to sign the CSR
+ var (
+ rawCSR = node.Certificate.CSR
+ cn = node.Certificate.CN
+ ou = role
+ org = s.securityConfig.ClientTLSCreds.Organization()
+ )
+
+ // Try using the external CA first.
+ cert, err := externalCA.Sign(ctx, PrepareCSR(rawCSR, cn, ou, org))
+ if err == ErrNoExternalCAURLs {
+ // No external CA servers configured. Try using the local CA.
+ cert, err = rootCA.ParseValidateAndSignCSR(rawCSR, cn, ou, org)
+ }
+
+ if err != nil {
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": node.ID,
+ "method": "(*Server).signNodeCert",
+ }).WithError(err).Errorf("failed to sign CSR")
+
+ // If the current state is already Failed, no need to change it
+ if node.Certificate.Status.State == api.IssuanceStateFailed {
+ delete(s.pending, node.ID)
+ return errors.New("failed to sign CSR")
+ }
+
+ if _, ok := err.(recoverableErr); ok {
+ // Return without changing the state of the certificate. We may
+ // retry signing it in the future.
+ return errors.New("failed to sign CSR")
+ }
+
+ // We failed to sign this CSR, change the state to FAILED
+ err = s.store.Update(func(tx store.Tx) error {
+ node := store.GetNode(tx, nodeID)
+ if node == nil {
+ return errors.Errorf("node %s not found", nodeID)
+ }
+
+ node.Certificate.Status = api.IssuanceStatus{
+ State: api.IssuanceStateFailed,
+ Err: err.Error(),
+ }
+
+ return store.UpdateNode(tx, node)
+ })
+ if err != nil {
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": nodeID,
+ "method": "(*Server).signNodeCert",
+ }).WithError(err).Errorf("transaction failed when setting state to FAILED")
+ }
+
+ delete(s.pending, node.ID)
+ return errors.New("failed to sign CSR")
+ }
+
+ // We were able to successfully sign the new CSR. Let's try to update the nodeStore
+ for {
+ err = s.store.Update(func(tx store.Tx) error {
+ node.Certificate.Certificate = cert
+ node.Certificate.Status = api.IssuanceStatus{
+ State: api.IssuanceStateIssued,
+ }
+
+ err := store.UpdateNode(tx, node)
+ if err != nil {
+ node = store.GetNode(tx, nodeID)
+ if node == nil {
+ err = errors.Errorf("node %s does not exist", nodeID)
+ }
+ }
+ return err
+ })
+ if err == nil {
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": node.ID,
+ "node.role": node.Certificate.Role,
+ "method": "(*Server).signNodeCert",
+ }).Debugf("certificate issued")
+ delete(s.pending, node.ID)
+ break
+ }
+ if err == store.ErrSequenceConflict {
+ continue
+ }
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": nodeID,
+ "method": "(*Server).signNodeCert",
+ }).WithError(err).Errorf("transaction failed")
+ return errors.New("transaction failed")
+ }
+ return nil
+}
+
+// reconcileNodeCertificates is a helper method that calls evaluateAndSignNodeCert on all the
+// nodes.
+func (s *Server) reconcileNodeCertificates(ctx context.Context, nodes []*api.Node) error {
+ for _, node := range nodes {
+ s.evaluateAndSignNodeCert(ctx, node)
+ }
+
+ return nil
+}
+
+// A successfully issued certificate and a failed certificate are our current final states
+func isFinalState(status api.IssuanceStatus) bool {
+ if status.State == api.IssuanceStateIssued || status.State == api.IssuanceStateFailed ||
+ status.State == api.IssuanceStateRotate {
+ return true
+ }
+
+ return false
+}
diff --git a/vendor/github.com/docker/swarmkit/ca/transport.go b/vendor/github.com/docker/swarmkit/ca/transport.go
new file mode 100644
index 0000000..6a6309a
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ca/transport.go
@@ -0,0 +1,213 @@
+package ca
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "net"
+ "strings"
+ "sync"
+
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc/credentials"
+)
+
+var (
+ // alpnProtoStr is the specified application level protocols for gRPC.
+ alpnProtoStr = []string{"h2"}
+)
+
+type timeoutError struct{}
+
+func (timeoutError) Error() string { return "mutablecredentials: Dial timed out" }
+func (timeoutError) Timeout() bool { return true }
+func (timeoutError) Temporary() bool { return true }
+
+// MutableTLSCreds is the credentials required for authenticating a connection using TLS.
+type MutableTLSCreds struct {
+ // Mutex for the tls config
+ sync.Mutex
+ // TLS configuration
+ config *tls.Config
+ // TLS Credentials
+ tlsCreds credentials.TransportCredentials
+ // store the subject for easy access
+ subject pkix.Name
+}
+
+// Info implements the credentials.TransportCredentials interface
+func (c *MutableTLSCreds) Info() credentials.ProtocolInfo {
+ return credentials.ProtocolInfo{
+ SecurityProtocol: "tls",
+ SecurityVersion: "1.2",
+ }
+}
+
+// Clone returns new MutableTLSCreds created from underlying *tls.Config.
+// It panics if validation of underlying config fails.
+func (c *MutableTLSCreds) Clone() credentials.TransportCredentials {
+ c.Lock()
+ newCfg, err := NewMutableTLS(c.config)
+ if err != nil {
+ panic("validation error on Clone")
+ }
+ c.Unlock()
+ return newCfg
+}
+
+// OverrideServerName overrides *tls.Config.ServerName.
+func (c *MutableTLSCreds) OverrideServerName(name string) error {
+ c.Lock()
+ c.config.ServerName = name
+ c.Unlock()
+ return nil
+}
+
+// GetRequestMetadata implements the credentials.TransportCredentials interface
+func (c *MutableTLSCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
+ return nil, nil
+}
+
+// RequireTransportSecurity implements the credentials.TransportCredentials interface
+func (c *MutableTLSCreds) RequireTransportSecurity() bool {
+ return true
+}
+
+// ClientHandshake implements the credentials.TransportCredentials interface
+func (c *MutableTLSCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
+ // borrow all the code from the original TLS credentials
+ c.Lock()
+ if c.config.ServerName == "" {
+ colonPos := strings.LastIndex(addr, ":")
+ if colonPos == -1 {
+ colonPos = len(addr)
+ }
+ c.config.ServerName = addr[:colonPos]
+ }
+
+ conn := tls.Client(rawConn, c.config)
+ // Need to allow conn.Handshake to have access to config,
+ // would create a deadlock otherwise
+ c.Unlock()
+ var err error
+ errChannel := make(chan error, 1)
+ go func() {
+ errChannel <- conn.Handshake()
+ }()
+ select {
+ case err = <-errChannel:
+ case <-ctx.Done():
+ err = ctx.Err()
+ }
+ if err != nil {
+ rawConn.Close()
+ return nil, nil, err
+ }
+ return conn, nil, nil
+}
+
+// ServerHandshake implements the credentials.TransportCredentials interface
+func (c *MutableTLSCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
+ c.Lock()
+ conn := tls.Server(rawConn, c.config)
+ c.Unlock()
+ if err := conn.Handshake(); err != nil {
+ rawConn.Close()
+ return nil, nil, err
+ }
+
+ return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil
+}
+
+// loadNewTLSConfig replaces the currently loaded TLS config with a new one
+func (c *MutableTLSCreds) loadNewTLSConfig(newConfig *tls.Config) error {
+ newSubject, err := GetAndValidateCertificateSubject(newConfig.Certificates)
+ if err != nil {
+ return err
+ }
+
+ c.Lock()
+ defer c.Unlock()
+ c.subject = newSubject
+ c.config = newConfig
+
+ return nil
+}
+
+// Config returns the current underlying TLS config.
+func (c *MutableTLSCreds) Config() *tls.Config {
+ c.Lock()
+ defer c.Unlock()
+
+ return c.config
+}
+
+// Role returns the OU for the certificate encapsulated in this TransportCredentials
+func (c *MutableTLSCreds) Role() string {
+ c.Lock()
+ defer c.Unlock()
+
+ return c.subject.OrganizationalUnit[0]
+}
+
+// Organization returns the O for the certificate encapsulated in this TransportCredentials
+func (c *MutableTLSCreds) Organization() string {
+ c.Lock()
+ defer c.Unlock()
+
+ return c.subject.Organization[0]
+}
+
+// NodeID returns the CN for the certificate encapsulated in this TransportCredentials
+func (c *MutableTLSCreds) NodeID() string {
+ c.Lock()
+ defer c.Unlock()
+
+ return c.subject.CommonName
+}
+
+// NewMutableTLS uses c to construct a mutable TransportCredentials based on TLS.
+func NewMutableTLS(c *tls.Config) (*MutableTLSCreds, error) {
+ originalTC := credentials.NewTLS(c)
+
+ if len(c.Certificates) < 1 {
+ return nil, errors.New("invalid configuration: needs at least one certificate")
+ }
+
+ subject, err := GetAndValidateCertificateSubject(c.Certificates)
+ if err != nil {
+ return nil, err
+ }
+
+ tc := &MutableTLSCreds{config: c, tlsCreds: originalTC, subject: subject}
+ tc.config.NextProtos = alpnProtoStr
+
+ return tc, nil
+}
+
+// GetAndValidateCertificateSubject is a helper method to retrieve and validate the subject
+// from the x509 certificate underlying a tls.Certificate
+func GetAndValidateCertificateSubject(certs []tls.Certificate) (pkix.Name, error) {
+ for i := range certs {
+ cert := &certs[i]
+ x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
+ if err != nil {
+ continue
+ }
+ if len(x509Cert.Subject.OrganizationalUnit) < 1 {
+ return pkix.Name{}, errors.New("no OU found in certificate subject")
+ }
+
+ if len(x509Cert.Subject.Organization) < 1 {
+ return pkix.Name{}, errors.New("no organization found in certificate subject")
+ }
+ if x509Cert.Subject.CommonName == "" {
+ return pkix.Name{}, errors.New("no valid subject names found for TLS configuration")
+ }
+
+ return x509Cert.Subject, nil
+ }
+
+ return pkix.Name{}, errors.New("no valid certificates found for TLS configuration")
+}
diff --git a/vendor/github.com/docker/swarmkit/connectionbroker/broker.go b/vendor/github.com/docker/swarmkit/connectionbroker/broker.go
new file mode 100644
index 0000000..a0ba7cf
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/connectionbroker/broker.go
@@ -0,0 +1,110 @@
+// Package connectionbroker is a layer on top of remotes that returns
+// a gRPC connection to a manager. The connection may be a local connection
+// using a local socket such as a UNIX socket.
+package connectionbroker
+
+import (
+ "sync"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/remotes"
+ grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
+ "google.golang.org/grpc"
+)
+
+// Broker is a simple connection broker. It can either return a fresh
+// connection to a remote manager selected with weighted randomization, or a
+// local gRPC connection to the local manager.
+type Broker struct {
+ mu sync.Mutex
+ remotes remotes.Remotes
+ localConn *grpc.ClientConn
+}
+
+// New creates a new connection broker.
+func New(remotes remotes.Remotes) *Broker {
+ return &Broker{
+ remotes: remotes,
+ }
+}
+
+// SetLocalConn changes the local gRPC connection used by the connection broker.
+func (b *Broker) SetLocalConn(localConn *grpc.ClientConn) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+
+ b.localConn = localConn
+}
+
+// Select a manager from the set of available managers, and return a connection.
+func (b *Broker) Select(dialOpts ...grpc.DialOption) (*Conn, error) {
+ b.mu.Lock()
+ localConn := b.localConn
+ b.mu.Unlock()
+
+ if localConn != nil {
+ return &Conn{
+ ClientConn: localConn,
+ isLocal: true,
+ }, nil
+ }
+
+ return b.SelectRemote(dialOpts...)
+}
+
+// SelectRemote chooses a manager from the remotes, and returns a TCP
+// connection.
+func (b *Broker) SelectRemote(dialOpts ...grpc.DialOption) (*Conn, error) {
+ peer, err := b.remotes.Select()
+ if err != nil {
+ return nil, err
+ }
+
+ dialOpts = append(dialOpts,
+ grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
+ grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor))
+
+ cc, err := grpc.Dial(peer.Addr, dialOpts...)
+ if err != nil {
+ b.remotes.ObserveIfExists(peer, -remotes.DefaultObservationWeight)
+ return nil, err
+ }
+
+ return &Conn{
+ ClientConn: cc,
+ remotes: b.remotes,
+ peer: peer,
+ }, nil
+}
+
+// Remotes returns the remotes interface used by the broker, so the caller
+// can make observations or see weights directly.
+func (b *Broker) Remotes() remotes.Remotes {
+ return b.remotes
+}
+
+// Conn is a wrapper around a gRPC client connection.
+type Conn struct {
+ *grpc.ClientConn
+ isLocal bool
+ remotes remotes.Remotes
+ peer api.Peer
+}
+
+// Close closes the client connection if it is a remote connection. It also
+// records a positive experience with the remote peer if success is true,
+// otherwise it records a negative experience. If a local connection is in use,
+// Close is a noop.
+func (c *Conn) Close(success bool) error {
+ if c.isLocal {
+ return nil
+ }
+
+ if success {
+ c.remotes.ObserveIfExists(c.peer, remotes.DefaultObservationWeight)
+ } else {
+ c.remotes.ObserveIfExists(c.peer, -remotes.DefaultObservationWeight)
+ }
+
+ return c.ClientConn.Close()
+}
diff --git a/vendor/github.com/docker/swarmkit/identity/doc.go b/vendor/github.com/docker/swarmkit/identity/doc.go
new file mode 100644
index 0000000..b91aca7
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/identity/doc.go
@@ -0,0 +1,16 @@
+// Package identity provides functionality for generating and managing
+// identifiers within a swarm. This includes entity identification, such as for
+// Services, Tasks and Networks but also cryptographically-secure Node identities.
+//
+// Random Identifiers
+//
+// Identifiers provided by this package are cryptographically-strong, random
+// 128 bit numbers encoded in Base36. This method is preferred over UUID4 since
+// it requires less storage and leverages the full 128 bits of entropy.
+//
+// Generating an identifier is simple. Simply call the `NewID` function:
+//
+// id := NewID()
+//
+// If an error occurs while generating the ID, it will panic.
+package identity
diff --git a/vendor/github.com/docker/swarmkit/identity/randomid.go b/vendor/github.com/docker/swarmkit/identity/randomid.go
new file mode 100644
index 0000000..0eb1352
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/identity/randomid.go
@@ -0,0 +1,53 @@
+package identity
+
+import (
+ cryptorand "crypto/rand"
+ "fmt"
+ "io"
+ "math/big"
+)
+
+var (
+ // idReader is used for random id generation. This declaration allows us to
+ // replace it for testing.
+ idReader = cryptorand.Reader
+)
+
+// parameters for random identifier generation. We can tweak this when there is
+// time for further analysis.
+const (
+ randomIDEntropyBytes = 17
+ randomIDBase = 36
+
+ // To ensure that all identifiers are fixed length, we make sure they
+ // get padded out or truncated to 25 characters.
+ //
+ // For academics, f5lxx1zz5pnorynqglhzmsp33 == 2^128 - 1. This value
+ // was calculated from floor(log(2^128-1, 36)) + 1.
+ //
+ // While 128 bits is the largest whole-byte size that fits into 25
+ // base-36 characters, we generate an extra byte of entropy to fill
+ // in the high bits, which would otherwise be 0. This gives us a more
+ // even distribution of the first character.
+ //
+ // See http://mathworld.wolfram.com/NumberLength.html for more information.
+ maxRandomIDLength = 25
+)
+
+// NewID generates a new identifier for use where random identifiers with low
+// collision probability are required.
+//
+// With the parameters in this package, the generated identifier will provide
+// ~129 bits of entropy encoded with base36. Leading padding is added if the
+// string is less 25 bytes. We do not intend to maintain this interface, so
+// identifiers should be treated opaquely.
+func NewID() string {
+ var p [randomIDEntropyBytes]byte
+
+ if _, err := io.ReadFull(idReader, p[:]); err != nil {
+ panic(fmt.Errorf("failed to read random bytes: %v", err))
+ }
+
+ p[0] |= 0x80 // set high bit to avoid the need for padding
+ return (&big.Int{}).SetBytes(p[:]).Text(randomIDBase)[1 : maxRandomIDLength+1]
+}
diff --git a/vendor/github.com/docker/swarmkit/ioutils/ioutils.go b/vendor/github.com/docker/swarmkit/ioutils/ioutils.go
new file mode 100644
index 0000000..25e2a78
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/ioutils/ioutils.go
@@ -0,0 +1,40 @@
+package ioutils
+
+import (
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+)
+
+// todo: split docker/pkg/ioutils into a separate repo
+
+// AtomicWriteFile atomically writes data to a file specified by filename.
+func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error {
+ f, err := ioutil.TempFile(filepath.Dir(filename), ".tmp-"+filepath.Base(filename))
+ if err != nil {
+ return err
+ }
+ err = os.Chmod(f.Name(), perm)
+ if err != nil {
+ f.Close()
+ return err
+ }
+ n, err := f.Write(data)
+ if err == nil && n < len(data) {
+ f.Close()
+ return io.ErrShortWrite
+ }
+ if err != nil {
+ f.Close()
+ return err
+ }
+ if err := f.Sync(); err != nil {
+ f.Close()
+ return err
+ }
+ if err := f.Close(); err != nil {
+ return err
+ }
+ return os.Rename(f.Name(), filename)
+}
diff --git a/vendor/github.com/docker/swarmkit/log/context.go b/vendor/github.com/docker/swarmkit/log/context.go
new file mode 100644
index 0000000..ce7da93
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/log/context.go
@@ -0,0 +1,96 @@
+package log
+
+import (
+ "path"
+
+ "github.com/Sirupsen/logrus"
+ "golang.org/x/net/context"
+)
+
+var (
+ // G is an alias for GetLogger.
+ //
+ // We may want to define this locally to a package to get package tagged log
+ // messages.
+ G = GetLogger
+
+ // L is an alias for the the standard logger.
+ L = logrus.NewEntry(logrus.StandardLogger())
+)
+
+type (
+ loggerKey struct{}
+ moduleKey struct{}
+)
+
+// WithLogger returns a new context with the provided logger. Use in
+// combination with logger.WithField(s) for great effect.
+func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {
+ return context.WithValue(ctx, loggerKey{}, logger)
+}
+
+// WithFields returns a new context with added fields to logger.
+func WithFields(ctx context.Context, fields logrus.Fields) context.Context {
+ logger := ctx.Value(loggerKey{})
+
+ if logger == nil {
+ logger = L
+ }
+ return WithLogger(ctx, logger.(*logrus.Entry).WithFields(fields))
+}
+
+// WithField is convenience wrapper around WithFields.
+func WithField(ctx context.Context, key, value string) context.Context {
+ return WithFields(ctx, logrus.Fields{key: value})
+}
+
+// GetLogger retrieves the current logger from the context. If no logger is
+// available, the default logger is returned.
+func GetLogger(ctx context.Context) *logrus.Entry {
+ logger := ctx.Value(loggerKey{})
+
+ if logger == nil {
+ return L
+ }
+
+ return logger.(*logrus.Entry)
+}
+
+// WithModule adds the module to the context, appending it with a slash if a
+// module already exists. A module is just a roughly correlated defined by the
+// call tree for a given context.
+//
+// As an example, we might have a "node" module already part of a context. If
+// this function is called with "tls", the new value of module will be
+// "node/tls".
+//
+// Modules represent the call path. If the new module and last module are the
+// same, a new module entry will not be created. If the new module and old
+// older module are the same but separated by other modules, the cycle will be
+// represented by the module path.
+func WithModule(ctx context.Context, module string) context.Context {
+ parent := GetModulePath(ctx)
+
+ if parent != "" {
+ // don't re-append module when module is the same.
+ if path.Base(parent) == module {
+ return ctx
+ }
+
+ module = path.Join(parent, module)
+ }
+
+ ctx = WithLogger(ctx, GetLogger(ctx).WithField("module", module))
+ return context.WithValue(ctx, moduleKey{}, module)
+}
+
+// GetModulePath returns the module path for the provided context. If no module
+// is set, an empty string is returned.
+func GetModulePath(ctx context.Context) string {
+ module := ctx.Value(moduleKey{})
+ if module == nil {
+ return ""
+ }
+
+ return module.(string)
+}
diff --git a/vendor/github.com/docker/swarmkit/log/grpc.go b/vendor/github.com/docker/swarmkit/log/grpc.go
new file mode 100644
index 0000000..4978d49
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/log/grpc.go
@@ -0,0 +1,13 @@
+package log
+
+import (
+ "golang.org/x/net/context"
+ "google.golang.org/grpc/grpclog"
+)
+
+func init() {
+ ctx := WithModule(context.Background(), "grpc")
+
+ // completely replace the grpc logger with the logrus logger.
+ grpclog.SetLogger(G(ctx))
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/allocator.go b/vendor/github.com/docker/swarmkit/manager/allocator/allocator.go
new file mode 100644
index 0000000..5ca5062
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/allocator.go
@@ -0,0 +1,231 @@
+package allocator
+
+import (
+ "sync"
+
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+)
+
+// Allocator controls how the allocation stage in the manager is handled.
+type Allocator struct {
+ // The manager store.
+ store *store.MemoryStore
+
+ // the ballot used to synchronize across all allocators to ensure
+ // all of them have completed their respective allocations so that the
+ // task can be moved to ALLOCATED state.
+ taskBallot *taskBallot
+
+ // context for the network allocator that will be needed by
+ // network allocator.
+ netCtx *networkContext
+
+ // stopChan signals to the allocator to stop running.
+ stopChan chan struct{}
+ // doneChan is closed when the allocator is finished running.
+ doneChan chan struct{}
+
+ // pluginGetter provides access to docker's plugin inventory.
+ pluginGetter plugingetter.PluginGetter
+}
+
+// taskBallot controls how the voting for task allocation is
+// coordinated b/w different allocators. This the only structure that
+// will be written by all allocator goroutines concurrently. Hence the
+// mutex.
+type taskBallot struct {
+ sync.Mutex
+
+ // List of registered voters who have to cast their vote to
+ // indicate their allocation complete
+ voters []string
+
+ // List of votes collected for every task so far from different voters.
+ votes map[string][]string
+}
+
+// allocActor controls the various phases in the lifecycle of one kind of allocator.
+type allocActor struct {
+ // Task voter identity of the allocator.
+ taskVoter string
+
+ // Action routine which is called for every event that the
+ // allocator received.
+ action func(context.Context, events.Event)
+
+ // Init routine which is called during the initialization of
+ // the allocator.
+ init func(ctx context.Context) error
+}
+
+// New returns a new instance of Allocator for use during allocation
+// stage of the manager.
+func New(store *store.MemoryStore, pg plugingetter.PluginGetter) (*Allocator, error) {
+ a := &Allocator{
+ store: store,
+ taskBallot: &taskBallot{
+ votes: make(map[string][]string),
+ },
+ stopChan: make(chan struct{}),
+ doneChan: make(chan struct{}),
+ pluginGetter: pg,
+ }
+
+ return a, nil
+}
+
+// Run starts all allocator go-routines and waits for Stop to be called.
+func (a *Allocator) Run(ctx context.Context) error {
+ // Setup cancel context for all goroutines to use.
+ ctx, cancel := context.WithCancel(ctx)
+ var (
+ wg sync.WaitGroup
+ actors []func() error
+ )
+
+ defer func() {
+ cancel()
+ wg.Wait()
+ close(a.doneChan)
+ }()
+
+ for _, aa := range []allocActor{
+ {
+ taskVoter: networkVoter,
+ init: a.doNetworkInit,
+ action: a.doNetworkAlloc,
+ },
+ } {
+ if aa.taskVoter != "" {
+ a.registerToVote(aa.taskVoter)
+ }
+
+ // Assign a pointer for variable capture
+ aaPtr := &aa
+ actor := func() error {
+ wg.Add(1)
+ defer wg.Done()
+
+ // init might return an allocator specific context
+ // which is a child of the passed in context to hold
+ // allocator specific state
+ watch, watchCancel, err := a.init(ctx, aaPtr)
+ if err != nil {
+ return err
+ }
+
+ wg.Add(1)
+ go func(watch <-chan events.Event, watchCancel func()) {
+ defer func() {
+ wg.Done()
+ watchCancel()
+ }()
+ a.run(ctx, *aaPtr, watch)
+ }(watch, watchCancel)
+ return nil
+ }
+
+ actors = append(actors, actor)
+ }
+
+ for _, actor := range actors {
+ if err := actor(); err != nil {
+ return err
+ }
+ }
+
+ <-a.stopChan
+ return nil
+}
+
+// Stop stops the allocator
+func (a *Allocator) Stop() {
+ close(a.stopChan)
+ // Wait for all allocator goroutines to truly exit
+ <-a.doneChan
+}
+
+func (a *Allocator) init(ctx context.Context, aa *allocActor) (<-chan events.Event, func(), error) {
+ watch, watchCancel := state.Watch(a.store.WatchQueue(),
+ api.EventCreateNetwork{},
+ api.EventDeleteNetwork{},
+ api.EventCreateService{},
+ api.EventUpdateService{},
+ api.EventDeleteService{},
+ api.EventCreateTask{},
+ api.EventUpdateTask{},
+ api.EventDeleteTask{},
+ api.EventCreateNode{},
+ api.EventUpdateNode{},
+ api.EventDeleteNode{},
+ state.EventCommit{},
+ )
+
+ if err := aa.init(ctx); err != nil {
+ watchCancel()
+ return nil, nil, err
+ }
+
+ return watch, watchCancel, nil
+}
+
+func (a *Allocator) run(ctx context.Context, aa allocActor, watch <-chan events.Event) {
+ for {
+ select {
+ case ev, ok := <-watch:
+ if !ok {
+ return
+ }
+
+ aa.action(ctx, ev)
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (a *Allocator) registerToVote(name string) {
+ a.taskBallot.Lock()
+ defer a.taskBallot.Unlock()
+
+ a.taskBallot.voters = append(a.taskBallot.voters, name)
+}
+
+func (a *Allocator) taskAllocateVote(voter string, id string) bool {
+ a.taskBallot.Lock()
+ defer a.taskBallot.Unlock()
+
+ // If voter has already voted, return false
+ for _, v := range a.taskBallot.votes[id] {
+ // check if voter is in x
+ if v == voter {
+ return false
+ }
+ }
+
+ a.taskBallot.votes[id] = append(a.taskBallot.votes[id], voter)
+
+ // We haven't gotten enough votes yet
+ if len(a.taskBallot.voters) > len(a.taskBallot.votes[id]) {
+ return false
+ }
+
+nextVoter:
+ for _, voter := range a.taskBallot.voters {
+ for _, vote := range a.taskBallot.votes[id] {
+ if voter == vote {
+ continue nextVoter
+ }
+ }
+
+ // Not every registered voter has registered a vote.
+ return false
+ }
+
+ return true
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_darwin.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_darwin.go
new file mode 100644
index 0000000..8cbedbd
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_darwin.go
@@ -0,0 +1,17 @@
+package cnmallocator
+
+import (
+ "github.com/docker/libnetwork/drivers/overlay/ovmanager"
+ "github.com/docker/libnetwork/drivers/remote"
+ "github.com/docker/swarmkit/manager/allocator/networkallocator"
+)
+
+var initializers = []initializer{
+ {remote.Init, "remote"},
+ {ovmanager.Init, "overlay"},
+}
+
+// PredefinedNetworks returns the list of predefined network structures
+func PredefinedNetworks() []networkallocator.PredefinedNetworkData {
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_ipam.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_ipam.go
new file mode 100644
index 0000000..eb854c5
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_ipam.go
@@ -0,0 +1,23 @@
+package cnmallocator
+
+import (
+ "github.com/docker/libnetwork/drvregistry"
+ "github.com/docker/libnetwork/ipamapi"
+ builtinIpam "github.com/docker/libnetwork/ipams/builtin"
+ nullIpam "github.com/docker/libnetwork/ipams/null"
+ remoteIpam "github.com/docker/libnetwork/ipams/remote"
+)
+
+func initIPAMDrivers(r *drvregistry.DrvRegistry) error {
+ for _, fn := range [](func(ipamapi.Callback, interface{}, interface{}) error){
+ builtinIpam.Init,
+ remoteIpam.Init,
+ nullIpam.Init,
+ } {
+ if err := fn(r, nil, nil); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_linux.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_linux.go
new file mode 100644
index 0000000..5d6a0e7
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_linux.go
@@ -0,0 +1,28 @@
+package cnmallocator
+
+import (
+ "github.com/docker/libnetwork/drivers/bridge/brmanager"
+ "github.com/docker/libnetwork/drivers/host"
+ "github.com/docker/libnetwork/drivers/ipvlan/ivmanager"
+ "github.com/docker/libnetwork/drivers/macvlan/mvmanager"
+ "github.com/docker/libnetwork/drivers/overlay/ovmanager"
+ "github.com/docker/libnetwork/drivers/remote"
+ "github.com/docker/swarmkit/manager/allocator/networkallocator"
+)
+
+var initializers = []initializer{
+ {remote.Init, "remote"},
+ {ovmanager.Init, "overlay"},
+ {mvmanager.Init, "macvlan"},
+ {brmanager.Init, "bridge"},
+ {ivmanager.Init, "ipvlan"},
+ {host.Init, "host"},
+}
+
+// PredefinedNetworks returns the list of predefined network structures
+func PredefinedNetworks() []networkallocator.PredefinedNetworkData {
+ return []networkallocator.PredefinedNetworkData{
+ {Name: "bridge", Driver: "bridge"},
+ {Name: "host", Driver: "host"},
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_windows.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_windows.go
new file mode 100644
index 0000000..8cbedbd
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_network_windows.go
@@ -0,0 +1,17 @@
+package cnmallocator
+
+import (
+ "github.com/docker/libnetwork/drivers/overlay/ovmanager"
+ "github.com/docker/libnetwork/drivers/remote"
+ "github.com/docker/swarmkit/manager/allocator/networkallocator"
+)
+
+var initializers = []initializer{
+ {remote.Init, "remote"},
+ {ovmanager.Init, "overlay"},
+}
+
+// PredefinedNetworks returns the list of predefined network structures
+func PredefinedNetworks() []networkallocator.PredefinedNetworkData {
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_unsupported.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_unsupported.go
new file mode 100644
index 0000000..f9de277
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/drivers_unsupported.go
@@ -0,0 +1,14 @@
+// +build !linux,!darwin,!windows
+
+package cnmallocator
+
+import (
+ "github.com/docker/swarmkit/manager/allocator/networkallocator"
+)
+
+const initializers = nil
+
+// PredefinedNetworks returns the list of predefined network structures
+func PredefinedNetworks() []networkallocator.PredefinedNetworkData {
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/networkallocator.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/networkallocator.go
new file mode 100644
index 0000000..2cfc951
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/networkallocator.go
@@ -0,0 +1,961 @@
+package cnmallocator
+
+import (
+ "fmt"
+ "net"
+ "strings"
+
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/libnetwork/datastore"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/drvregistry"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/libnetwork/netlabel"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/allocator/networkallocator"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+const (
+ // DefaultDriver defines the name of the driver to be used by
+ // default if a network without any driver name specified is
+ // created.
+ DefaultDriver = "overlay"
+)
+
+// cnmNetworkAllocator acts as the controller for all network related operations
+// like managing network and IPAM drivers and also creating and
+// deleting networks and the associated resources.
+type cnmNetworkAllocator struct {
+ // The driver register which manages all internal and external
+ // IPAM and network drivers.
+ drvRegistry *drvregistry.DrvRegistry
+
+ // The port allocator instance for allocating node ports
+ portAllocator *portAllocator
+
+ // Local network state used by cnmNetworkAllocator to do network management.
+ networks map[string]*network
+
+ // Allocator state to indicate if allocation has been
+ // successfully completed for this service.
+ services map[string]struct{}
+
+ // Allocator state to indicate if allocation has been
+ // successfully completed for this task.
+ tasks map[string]struct{}
+
+ // Allocator state to indicate if allocation has been
+ // successfully completed for this node.
+ nodes map[string]struct{}
+}
+
+// Local in-memory state related to network that need to be tracked by cnmNetworkAllocator
+type network struct {
+ // A local cache of the store object.
+ nw *api.Network
+
+ // pools is used to save the internal poolIDs needed when
+ // releasing the pool.
+ pools map[string]string
+
+ // endpoints is a map of endpoint IP to the poolID from which it
+ // was allocated.
+ endpoints map[string]string
+
+ // isNodeLocal indicates whether the scope of the network's resources
+ // is local to the node. If true, it means the resources can only be
+ // allocated locally by the node where the network will be deployed.
+ // In this the swarm manager will skip the allocations.
+ isNodeLocal bool
+}
+
+type networkDriver struct {
+ driver driverapi.Driver
+ name string
+ capability *driverapi.Capability
+}
+
+type initializer struct {
+ fn drvregistry.InitFunc
+ ntype string
+}
+
+// New returns a new NetworkAllocator handle
+func New(pg plugingetter.PluginGetter) (networkallocator.NetworkAllocator, error) {
+ na := &cnmNetworkAllocator{
+ networks: make(map[string]*network),
+ services: make(map[string]struct{}),
+ tasks: make(map[string]struct{}),
+ nodes: make(map[string]struct{}),
+ }
+
+ // There are no driver configurations and notification
+ // functions as of now.
+ reg, err := drvregistry.New(nil, nil, nil, nil, pg)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := initializeDrivers(reg); err != nil {
+ return nil, err
+ }
+
+ if err = initIPAMDrivers(reg); err != nil {
+ return nil, err
+ }
+
+ pa, err := newPortAllocator()
+ if err != nil {
+ return nil, err
+ }
+
+ na.portAllocator = pa
+ na.drvRegistry = reg
+ return na, nil
+}
+
+// Allocate allocates all the necessary resources both general
+// and driver-specific which may be specified in the NetworkSpec
+func (na *cnmNetworkAllocator) Allocate(n *api.Network) error {
+ if _, ok := na.networks[n.ID]; ok {
+ return fmt.Errorf("network %s already allocated", n.ID)
+ }
+
+ d, err := na.resolveDriver(n)
+ if err != nil {
+ return err
+ }
+
+ nw := &network{
+ nw: n,
+ endpoints: make(map[string]string),
+ isNodeLocal: d.capability.DataScope == datastore.LocalScope,
+ }
+
+ // No swarm-level allocation can be provided by the network driver for
+ // node-local networks. Only thing needed is populating the driver's name
+ // in the driver's state.
+ if nw.isNodeLocal {
+ n.DriverState = &api.Driver{
+ Name: d.name,
+ }
+ // In order to support backward compatibility with older daemon
+ // versions which assumes the network attachment to contains
+ // non nil IPAM attribute, passing an empty object
+ n.IPAM = &api.IPAMOptions{Driver: &api.Driver{}}
+ } else {
+ nw.pools, err = na.allocatePools(n)
+ if err != nil {
+ return errors.Wrapf(err, "failed allocating pools and gateway IP for network %s", n.ID)
+ }
+
+ if err := na.allocateDriverState(n); err != nil {
+ na.freePools(n, nw.pools)
+ return errors.Wrapf(err, "failed while allocating driver state for network %s", n.ID)
+ }
+ }
+
+ na.networks[n.ID] = nw
+
+ return nil
+}
+
+func (na *cnmNetworkAllocator) getNetwork(id string) *network {
+ return na.networks[id]
+}
+
+// Deallocate frees all the general and driver specific resources
+// which were assigned to the passed network.
+func (na *cnmNetworkAllocator) Deallocate(n *api.Network) error {
+ localNet := na.getNetwork(n.ID)
+ if localNet == nil {
+ return fmt.Errorf("could not get networker state for network %s", n.ID)
+ }
+
+ // No swarm-level resource deallocation needed for node-local networks
+ if localNet.isNodeLocal {
+ delete(na.networks, n.ID)
+ return nil
+ }
+
+ if err := na.freeDriverState(n); err != nil {
+ return errors.Wrapf(err, "failed to free driver state for network %s", n.ID)
+ }
+
+ delete(na.networks, n.ID)
+
+ return na.freePools(n, localNet.pools)
+}
+
+// AllocateService allocates all the network resources such as virtual
+// IP and ports needed by the service.
+func (na *cnmNetworkAllocator) AllocateService(s *api.Service) (err error) {
+ if err = na.portAllocator.serviceAllocatePorts(s); err != nil {
+ return err
+ }
+ defer func() {
+ if err != nil {
+ na.DeallocateService(s)
+ }
+ }()
+
+ if s.Endpoint == nil {
+ s.Endpoint = &api.Endpoint{}
+ }
+ s.Endpoint.Spec = s.Spec.Endpoint.Copy()
+
+ // If ResolutionMode is DNSRR do not try allocating VIPs, but
+ // free any VIP from previous state.
+ if s.Spec.Endpoint != nil && s.Spec.Endpoint.Mode == api.ResolutionModeDNSRoundRobin {
+ for _, vip := range s.Endpoint.VirtualIPs {
+ if err := na.deallocateVIP(vip); err != nil {
+ // don't bail here, deallocate as many as possible.
+ log.L.WithError(err).
+ WithField("vip.network", vip.NetworkID).
+ WithField("vip.addr", vip.Addr).Error("error deallocating vip")
+ }
+ }
+
+ s.Endpoint.VirtualIPs = nil
+
+ delete(na.services, s.ID)
+ return nil
+ }
+
+ specNetworks := serviceNetworks(s)
+
+ // Allocate VIPs for all the pre-populated endpoint attachments
+ eVIPs := s.Endpoint.VirtualIPs[:0]
+
+vipLoop:
+ for _, eAttach := range s.Endpoint.VirtualIPs {
+ if na.IsVIPOnIngressNetwork(eAttach) && networkallocator.IsIngressNetworkNeeded(s) {
+ if err = na.allocateVIP(eAttach); err != nil {
+ return err
+ }
+ eVIPs = append(eVIPs, eAttach)
+ continue vipLoop
+
+ }
+ for _, nAttach := range specNetworks {
+ if nAttach.Target == eAttach.NetworkID {
+ if err = na.allocateVIP(eAttach); err != nil {
+ return err
+ }
+ eVIPs = append(eVIPs, eAttach)
+ continue vipLoop
+ }
+ }
+ // If the network of the VIP is not part of the service spec,
+ // deallocate the vip
+ na.deallocateVIP(eAttach)
+ }
+
+networkLoop:
+ for _, nAttach := range specNetworks {
+ for _, vip := range s.Endpoint.VirtualIPs {
+ if vip.NetworkID == nAttach.Target {
+ continue networkLoop
+ }
+ }
+
+ vip := &api.Endpoint_VirtualIP{NetworkID: nAttach.Target}
+ if err = na.allocateVIP(vip); err != nil {
+ return err
+ }
+
+ eVIPs = append(eVIPs, vip)
+ }
+
+ if len(eVIPs) > 0 {
+ na.services[s.ID] = struct{}{}
+ } else {
+ delete(na.services, s.ID)
+ }
+
+ s.Endpoint.VirtualIPs = eVIPs
+ return nil
+}
+
+// DeallocateService de-allocates all the network resources such as
+// virtual IP and ports associated with the service.
+func (na *cnmNetworkAllocator) DeallocateService(s *api.Service) error {
+ if s.Endpoint == nil {
+ return nil
+ }
+
+ for _, vip := range s.Endpoint.VirtualIPs {
+ if err := na.deallocateVIP(vip); err != nil {
+ // don't bail here, deallocate as many as possible.
+ log.L.WithError(err).
+ WithField("vip.network", vip.NetworkID).
+ WithField("vip.addr", vip.Addr).Error("error deallocating vip")
+ }
+ }
+ s.Endpoint.VirtualIPs = nil
+
+ na.portAllocator.serviceDeallocatePorts(s)
+ delete(na.services, s.ID)
+
+ return nil
+}
+
+// IsAllocated returns if the passed network has been allocated or not.
+func (na *cnmNetworkAllocator) IsAllocated(n *api.Network) bool {
+ _, ok := na.networks[n.ID]
+ return ok
+}
+
+// IsTaskAllocated returns if the passed task has its network resources allocated or not.
+func (na *cnmNetworkAllocator) IsTaskAllocated(t *api.Task) bool {
+ // If the task is not found in the allocated set, then it is
+ // not allocated.
+ if _, ok := na.tasks[t.ID]; !ok {
+ return false
+ }
+
+ // If Networks is empty there is no way this Task is allocated.
+ if len(t.Networks) == 0 {
+ return false
+ }
+
+ // To determine whether the task has its resources allocated,
+ // we just need to look at one global scope network (in case of
+ // multi-network attachment). This is because we make sure we
+ // allocate for every network or we allocate for none.
+
+ // Find the first global scope network
+ for _, nAttach := range t.Networks {
+ // If the network is not allocated, the task cannot be allocated.
+ localNet, ok := na.networks[nAttach.Network.ID]
+ if !ok {
+ return false
+ }
+
+ // Nothing else to check for local scope network
+ if localNet.isNodeLocal {
+ continue
+ }
+
+ // Addresses empty. Task is not allocated.
+ if len(nAttach.Addresses) == 0 {
+ return false
+ }
+
+ // The allocated IP address not found in local endpoint state. Not allocated.
+ if _, ok := localNet.endpoints[nAttach.Addresses[0]]; !ok {
+ return false
+ }
+ }
+
+ return true
+}
+
+// HostPublishPortsNeedUpdate returns true if the passed service needs
+// allocations for its published ports in host (non ingress) mode
+func (na *cnmNetworkAllocator) HostPublishPortsNeedUpdate(s *api.Service) bool {
+ return na.portAllocator.hostPublishPortsNeedUpdate(s)
+}
+
+// IsServiceAllocated returns false if the passed service needs to have network resources allocated/updated.
+func (na *cnmNetworkAllocator) IsServiceAllocated(s *api.Service, flags ...func(*networkallocator.ServiceAllocationOpts)) bool {
+ var options networkallocator.ServiceAllocationOpts
+ for _, flag := range flags {
+ flag(&options)
+ }
+
+ specNetworks := serviceNetworks(s)
+
+ // If endpoint mode is VIP and allocator does not have the
+ // service in VIP allocated set then it needs to be allocated.
+ if len(specNetworks) != 0 &&
+ (s.Spec.Endpoint == nil ||
+ s.Spec.Endpoint.Mode == api.ResolutionModeVirtualIP) {
+
+ if _, ok := na.services[s.ID]; !ok {
+ return false
+ }
+
+ if s.Endpoint == nil || len(s.Endpoint.VirtualIPs) == 0 {
+ return false
+ }
+
+ // If the spec has networks which don't have a corresponding VIP,
+ // the service needs to be allocated.
+ networkLoop:
+ for _, net := range specNetworks {
+ for _, vip := range s.Endpoint.VirtualIPs {
+ if vip.NetworkID == net.Target {
+ continue networkLoop
+ }
+ }
+ return false
+ }
+ }
+
+ // If the spec no longer has networks attached and has a vip allocated
+ // from previous spec the service needs to allocated.
+ if s.Endpoint != nil {
+ vipLoop:
+ for _, vip := range s.Endpoint.VirtualIPs {
+ if na.IsVIPOnIngressNetwork(vip) && networkallocator.IsIngressNetworkNeeded(s) {
+ continue vipLoop
+ }
+ for _, net := range specNetworks {
+ if vip.NetworkID == net.Target {
+ continue vipLoop
+ }
+ }
+ return false
+ }
+ }
+
+ // If the endpoint mode is DNSRR and allocator has the service
+ // in VIP allocated set then we return to be allocated to make
+ // sure the allocator triggers networkallocator to free up the
+ // resources if any.
+ if s.Spec.Endpoint != nil && s.Spec.Endpoint.Mode == api.ResolutionModeDNSRoundRobin {
+ if _, ok := na.services[s.ID]; ok {
+ return false
+ }
+ }
+
+ if (s.Spec.Endpoint != nil && len(s.Spec.Endpoint.Ports) != 0) ||
+ (s.Endpoint != nil && len(s.Endpoint.Ports) != 0) {
+ return na.portAllocator.isPortsAllocatedOnInit(s, options.OnInit)
+ }
+ return true
+}
+
+// IsNodeAllocated returns if the passed node has its network resources allocated or not.
+func (na *cnmNetworkAllocator) IsNodeAllocated(node *api.Node) bool {
+ // If the node is not found in the allocated set, then it is
+ // not allocated.
+ if _, ok := na.nodes[node.ID]; !ok {
+ return false
+ }
+
+ // If no attachment, not allocated.
+ if node.Attachment == nil {
+ return false
+ }
+
+ // If the network is not allocated, the node cannot be allocated.
+ localNet, ok := na.networks[node.Attachment.Network.ID]
+ if !ok {
+ return false
+ }
+
+ // Addresses empty, not allocated.
+ if len(node.Attachment.Addresses) == 0 {
+ return false
+ }
+
+ // The allocated IP address not found in local endpoint state. Not allocated.
+ if _, ok := localNet.endpoints[node.Attachment.Addresses[0]]; !ok {
+ return false
+ }
+
+ return true
+}
+
+// AllocateNode allocates the IP addresses for the network to which
+// the node is attached.
+func (na *cnmNetworkAllocator) AllocateNode(node *api.Node) error {
+ if err := na.allocateNetworkIPs(node.Attachment); err != nil {
+ return err
+ }
+
+ na.nodes[node.ID] = struct{}{}
+ return nil
+}
+
+// DeallocateNode deallocates the IP addresses for the network to
+// which the node is attached.
+func (na *cnmNetworkAllocator) DeallocateNode(node *api.Node) error {
+ delete(na.nodes, node.ID)
+ return na.releaseEndpoints([]*api.NetworkAttachment{node.Attachment})
+}
+
+// AllocateTask allocates all the endpoint resources for all the
+// networks that a task is attached to.
+func (na *cnmNetworkAllocator) AllocateTask(t *api.Task) error {
+ for i, nAttach := range t.Networks {
+ if localNet := na.getNetwork(nAttach.Network.ID); localNet != nil && localNet.isNodeLocal {
+ continue
+ }
+ if err := na.allocateNetworkIPs(nAttach); err != nil {
+ if err := na.releaseEndpoints(t.Networks[:i]); err != nil {
+ log.G(context.TODO()).WithError(err).Errorf("Failed to release IP addresses while rolling back allocation for task %s network %s", t.ID, nAttach.Network.ID)
+ }
+ return errors.Wrapf(err, "failed to allocate network IP for task %s network %s", t.ID, nAttach.Network.ID)
+ }
+ }
+
+ na.tasks[t.ID] = struct{}{}
+
+ return nil
+}
+
+// DeallocateTask releases all the endpoint resources for all the
+// networks that a task is attached to.
+func (na *cnmNetworkAllocator) DeallocateTask(t *api.Task) error {
+ delete(na.tasks, t.ID)
+ return na.releaseEndpoints(t.Networks)
+}
+
+func (na *cnmNetworkAllocator) releaseEndpoints(networks []*api.NetworkAttachment) error {
+ for _, nAttach := range networks {
+ localNet := na.getNetwork(nAttach.Network.ID)
+ if localNet == nil {
+ return fmt.Errorf("could not find network allocator state for network %s", nAttach.Network.ID)
+ }
+
+ if localNet.isNodeLocal {
+ continue
+ }
+
+ ipam, _, _, err := na.resolveIPAM(nAttach.Network)
+ if err != nil {
+ return errors.Wrap(err, "failed to resolve IPAM while releasing")
+ }
+
+ // Do not fail and bail out if we fail to release IP
+ // address here. Keep going and try releasing as many
+ // addresses as possible.
+ for _, addr := range nAttach.Addresses {
+ // Retrieve the poolID and immediately nuke
+ // out the mapping.
+ poolID := localNet.endpoints[addr]
+ delete(localNet.endpoints, addr)
+
+ ip, _, err := net.ParseCIDR(addr)
+ if err != nil {
+ log.G(context.TODO()).Errorf("Could not parse IP address %s while releasing", addr)
+ continue
+ }
+
+ if err := ipam.ReleaseAddress(poolID, ip); err != nil {
+ log.G(context.TODO()).WithError(err).Errorf("IPAM failure while releasing IP address %s", addr)
+ }
+ }
+
+ // Clear out the address list when we are done with
+ // this network.
+ nAttach.Addresses = nil
+ }
+
+ return nil
+}
+
+// allocate virtual IP for a single endpoint attachment of the service.
+func (na *cnmNetworkAllocator) allocateVIP(vip *api.Endpoint_VirtualIP) error {
+ localNet := na.getNetwork(vip.NetworkID)
+ if localNet == nil {
+ return errors.New("networkallocator: could not find local network state")
+ }
+
+ if localNet.isNodeLocal {
+ return nil
+ }
+
+ // If this IP is already allocated in memory we don't need to
+ // do anything.
+ if _, ok := localNet.endpoints[vip.Addr]; ok {
+ return nil
+ }
+
+ ipam, _, _, err := na.resolveIPAM(localNet.nw)
+ if err != nil {
+ return errors.Wrap(err, "failed to resolve IPAM while allocating")
+ }
+
+ var addr net.IP
+ if vip.Addr != "" {
+ var err error
+
+ addr, _, err = net.ParseCIDR(vip.Addr)
+ if err != nil {
+ return err
+ }
+ }
+
+ for _, poolID := range localNet.pools {
+ ip, _, err := ipam.RequestAddress(poolID, addr, nil)
+ if err != nil && err != ipamapi.ErrNoAvailableIPs && err != ipamapi.ErrIPOutOfRange {
+ return errors.Wrap(err, "could not allocate VIP from IPAM")
+ }
+
+ // If we got an address then we are done.
+ if err == nil {
+ ipStr := ip.String()
+ localNet.endpoints[ipStr] = poolID
+ vip.Addr = ipStr
+ return nil
+ }
+ }
+
+ return errors.New("could not find an available IP while allocating VIP")
+}
+
+func (na *cnmNetworkAllocator) deallocateVIP(vip *api.Endpoint_VirtualIP) error {
+ localNet := na.getNetwork(vip.NetworkID)
+ if localNet == nil {
+ return errors.New("networkallocator: could not find local network state")
+ }
+ if localNet.isNodeLocal {
+ return nil
+ }
+ ipam, _, _, err := na.resolveIPAM(localNet.nw)
+ if err != nil {
+ return errors.Wrap(err, "failed to resolve IPAM while allocating")
+ }
+
+ // Retrieve the poolID and immediately nuke
+ // out the mapping.
+ poolID := localNet.endpoints[vip.Addr]
+ delete(localNet.endpoints, vip.Addr)
+
+ ip, _, err := net.ParseCIDR(vip.Addr)
+ if err != nil {
+ log.G(context.TODO()).Errorf("Could not parse VIP address %s while releasing", vip.Addr)
+ return err
+ }
+
+ if err := ipam.ReleaseAddress(poolID, ip); err != nil {
+ log.G(context.TODO()).WithError(err).Errorf("IPAM failure while releasing VIP address %s", vip.Addr)
+ return err
+ }
+
+ return nil
+}
+
+// allocate the IP addresses for a single network attachment of the task.
+func (na *cnmNetworkAllocator) allocateNetworkIPs(nAttach *api.NetworkAttachment) error {
+ var ip *net.IPNet
+
+ ipam, _, _, err := na.resolveIPAM(nAttach.Network)
+ if err != nil {
+ return errors.Wrap(err, "failed to resolve IPAM while allocating")
+ }
+
+ localNet := na.getNetwork(nAttach.Network.ID)
+ if localNet == nil {
+ return fmt.Errorf("could not find network allocator state for network %s", nAttach.Network.ID)
+ }
+
+ addresses := nAttach.Addresses
+ if len(addresses) == 0 {
+ addresses = []string{""}
+ }
+
+ for i, rawAddr := range addresses {
+ var addr net.IP
+ if rawAddr != "" {
+ var err error
+ addr, _, err = net.ParseCIDR(rawAddr)
+ if err != nil {
+ addr = net.ParseIP(rawAddr)
+
+ if addr == nil {
+ return errors.Wrapf(err, "could not parse address string %s", rawAddr)
+ }
+ }
+ }
+
+ for _, poolID := range localNet.pools {
+ var err error
+
+ ip, _, err = ipam.RequestAddress(poolID, addr, nil)
+ if err != nil && err != ipamapi.ErrNoAvailableIPs && err != ipamapi.ErrIPOutOfRange {
+ return errors.Wrap(err, "could not allocate IP from IPAM")
+ }
+
+ // If we got an address then we are done.
+ if err == nil {
+ ipStr := ip.String()
+ localNet.endpoints[ipStr] = poolID
+ addresses[i] = ipStr
+ nAttach.Addresses = addresses
+ return nil
+ }
+ }
+ }
+
+ return errors.New("could not find an available IP")
+}
+
+func (na *cnmNetworkAllocator) freeDriverState(n *api.Network) error {
+ d, err := na.resolveDriver(n)
+ if err != nil {
+ return err
+ }
+
+ return d.driver.NetworkFree(n.ID)
+}
+
+func (na *cnmNetworkAllocator) allocateDriverState(n *api.Network) error {
+ d, err := na.resolveDriver(n)
+ if err != nil {
+ return err
+ }
+
+ options := make(map[string]string)
+ // reconcile the driver specific options from the network spec
+ // and from the operational state retrieved from the store
+ if n.Spec.DriverConfig != nil {
+ for k, v := range n.Spec.DriverConfig.Options {
+ options[k] = v
+ }
+ }
+ if n.DriverState != nil {
+ for k, v := range n.DriverState.Options {
+ options[k] = v
+ }
+ }
+
+ // Construct IPAM data for driver consumption.
+ ipv4Data := make([]driverapi.IPAMData, 0, len(n.IPAM.Configs))
+ for _, ic := range n.IPAM.Configs {
+ if ic.Family == api.IPAMConfig_IPV6 {
+ continue
+ }
+
+ _, subnet, err := net.ParseCIDR(ic.Subnet)
+ if err != nil {
+ return errors.Wrapf(err, "error parsing subnet %s while allocating driver state", ic.Subnet)
+ }
+
+ gwIP := net.ParseIP(ic.Gateway)
+ gwNet := &net.IPNet{
+ IP: gwIP,
+ Mask: subnet.Mask,
+ }
+
+ data := driverapi.IPAMData{
+ Pool: subnet,
+ Gateway: gwNet,
+ }
+
+ ipv4Data = append(ipv4Data, data)
+ }
+
+ ds, err := d.driver.NetworkAllocate(n.ID, options, ipv4Data, nil)
+ if err != nil {
+ return err
+ }
+
+ // Update network object with the obtained driver state.
+ n.DriverState = &api.Driver{
+ Name: d.name,
+ Options: ds,
+ }
+
+ return nil
+}
+
+// Resolve network driver
+func (na *cnmNetworkAllocator) resolveDriver(n *api.Network) (*networkDriver, error) {
+ dName := DefaultDriver
+ if n.Spec.DriverConfig != nil && n.Spec.DriverConfig.Name != "" {
+ dName = n.Spec.DriverConfig.Name
+ }
+
+ d, drvcap := na.drvRegistry.Driver(dName)
+ if d == nil {
+ var err error
+ err = na.loadDriver(dName)
+ if err != nil {
+ return nil, err
+ }
+
+ d, drvcap = na.drvRegistry.Driver(dName)
+ if d == nil {
+ return nil, fmt.Errorf("could not resolve network driver %s", dName)
+ }
+ }
+
+ return &networkDriver{driver: d, capability: drvcap, name: dName}, nil
+}
+
+func (na *cnmNetworkAllocator) loadDriver(name string) error {
+ pg := na.drvRegistry.GetPluginGetter()
+ if pg == nil {
+ return errors.New("plugin store is uninitialized")
+ }
+ _, err := pg.Get(name, driverapi.NetworkPluginEndpointType, plugingetter.Lookup)
+ return err
+}
+
+// Resolve the IPAM driver
+func (na *cnmNetworkAllocator) resolveIPAM(n *api.Network) (ipamapi.Ipam, string, map[string]string, error) {
+ dName := ipamapi.DefaultIPAM
+ if n.Spec.IPAM != nil && n.Spec.IPAM.Driver != nil && n.Spec.IPAM.Driver.Name != "" {
+ dName = n.Spec.IPAM.Driver.Name
+ }
+
+ var dOptions map[string]string
+ if n.Spec.IPAM != nil && n.Spec.IPAM.Driver != nil && len(n.Spec.IPAM.Driver.Options) != 0 {
+ dOptions = n.Spec.IPAM.Driver.Options
+ }
+
+ ipam, _ := na.drvRegistry.IPAM(dName)
+ if ipam == nil {
+ return nil, "", nil, fmt.Errorf("could not resolve IPAM driver %s", dName)
+ }
+
+ return ipam, dName, dOptions, nil
+}
+
+func (na *cnmNetworkAllocator) freePools(n *api.Network, pools map[string]string) error {
+ ipam, _, _, err := na.resolveIPAM(n)
+ if err != nil {
+ return errors.Wrapf(err, "failed to resolve IPAM while freeing pools for network %s", n.ID)
+ }
+
+ releasePools(ipam, n.IPAM.Configs, pools)
+ return nil
+}
+
+func releasePools(ipam ipamapi.Ipam, icList []*api.IPAMConfig, pools map[string]string) {
+ for _, ic := range icList {
+ if err := ipam.ReleaseAddress(pools[ic.Subnet], net.ParseIP(ic.Gateway)); err != nil {
+ log.G(context.TODO()).WithError(err).Errorf("Failed to release address %s", ic.Subnet)
+ }
+ }
+
+ for k, p := range pools {
+ if err := ipam.ReleasePool(p); err != nil {
+ log.G(context.TODO()).WithError(err).Errorf("Failed to release pool %s", k)
+ }
+ }
+}
+
+func (na *cnmNetworkAllocator) allocatePools(n *api.Network) (map[string]string, error) {
+ ipam, dName, dOptions, err := na.resolveIPAM(n)
+ if err != nil {
+ return nil, err
+ }
+
+ // We don't support user defined address spaces yet so just
+ // retrieve default address space names for the driver.
+ _, asName, err := na.drvRegistry.IPAMDefaultAddressSpaces(dName)
+ if err != nil {
+ return nil, err
+ }
+
+ pools := make(map[string]string)
+
+ var ipamConfigs []*api.IPAMConfig
+
+ // If there is non-nil IPAM state always prefer those subnet
+ // configs over Spec configs.
+ if n.IPAM != nil {
+ ipamConfigs = n.IPAM.Configs
+ } else if n.Spec.IPAM != nil {
+ ipamConfigs = make([]*api.IPAMConfig, len(n.Spec.IPAM.Configs))
+ copy(ipamConfigs, n.Spec.IPAM.Configs)
+ }
+
+ // Append an empty slot for subnet allocation if there are no
+ // IPAM configs from either spec or state.
+ if len(ipamConfigs) == 0 {
+ ipamConfigs = append(ipamConfigs, &api.IPAMConfig{Family: api.IPAMConfig_IPV4})
+ }
+
+ // Update the runtime IPAM configurations with initial state
+ n.IPAM = &api.IPAMOptions{
+ Driver: &api.Driver{Name: dName, Options: dOptions},
+ Configs: ipamConfigs,
+ }
+
+ for i, ic := range ipamConfigs {
+ poolID, poolIP, meta, err := ipam.RequestPool(asName, ic.Subnet, ic.Range, dOptions, false)
+ if err != nil {
+ // Rollback by releasing all the resources allocated so far.
+ releasePools(ipam, ipamConfigs[:i], pools)
+ return nil, err
+ }
+ pools[poolIP.String()] = poolID
+
+ // The IPAM contract allows the IPAM driver to autonomously
+ // provide a network gateway in response to the pool request.
+ // But if the network spec contains a gateway, we will allocate
+ // it irrespective of whether the ipam driver returned one already.
+ // If none of the above is true, we need to allocate one now, and
+ // let the driver know this request is for the network gateway.
+ var (
+ gwIP *net.IPNet
+ ip net.IP
+ )
+ if gws, ok := meta[netlabel.Gateway]; ok {
+ if ip, gwIP, err = net.ParseCIDR(gws); err != nil {
+ return nil, fmt.Errorf("failed to parse gateway address (%v) returned by ipam driver: %v", gws, err)
+ }
+ gwIP.IP = ip
+ }
+ if ic.Gateway != "" || gwIP == nil {
+ gwIP, _, err = ipam.RequestAddress(poolID, net.ParseIP(ic.Gateway), map[string]string{ipamapi.RequestAddressType: netlabel.Gateway})
+ if err != nil {
+ // Rollback by releasing all the resources allocated so far.
+ releasePools(ipam, ipamConfigs[:i], pools)
+ return nil, err
+ }
+ }
+
+ if ic.Subnet == "" {
+ ic.Subnet = poolIP.String()
+ }
+
+ if ic.Gateway == "" {
+ ic.Gateway = gwIP.IP.String()
+ }
+
+ }
+
+ return pools, nil
+}
+
+func initializeDrivers(reg *drvregistry.DrvRegistry) error {
+ for _, i := range initializers {
+ if err := reg.AddDriver(i.ntype, i.fn, nil); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func serviceNetworks(s *api.Service) []*api.NetworkAttachmentConfig {
+ // Always prefer NetworkAttachmentConfig in the TaskSpec
+ if len(s.Spec.Task.Networks) == 0 && len(s.Spec.Networks) != 0 {
+ return s.Spec.Networks
+ }
+ return s.Spec.Task.Networks
+}
+
+// IsVIPOnIngressNetwork check if the vip is in ingress network
+func (na *cnmNetworkAllocator) IsVIPOnIngressNetwork(vip *api.Endpoint_VirtualIP) bool {
+ if vip == nil {
+ return false
+ }
+
+ localNet := na.getNetwork(vip.NetworkID)
+ if localNet != nil && localNet.nw != nil {
+ return networkallocator.IsIngressNetwork(localNet.nw)
+ }
+ return false
+}
+
+// IsBuiltInDriver returns whether the passed driver is an internal network driver
+func IsBuiltInDriver(name string) bool {
+ n := strings.ToLower(name)
+ for _, d := range initializers {
+ if n == d.ntype {
+ return true
+ }
+ }
+ return false
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/portallocator.go b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/portallocator.go
new file mode 100644
index 0000000..b09ac47
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/cnmallocator/portallocator.go
@@ -0,0 +1,410 @@
+package cnmallocator
+
+import (
+ "fmt"
+
+ "github.com/docker/libnetwork/idm"
+ "github.com/docker/swarmkit/api"
+)
+
+const (
+ // Start of the dynamic port range from which node ports will
+ // be allocated when the user did not specify a port.
+ dynamicPortStart = 30000
+
+ // End of the dynamic port range from which node ports will be
+ // allocated when the user did not specify a port.
+ dynamicPortEnd = 32767
+
+ // The start of master port range which will hold all the
+ // allocation state of ports allocated so far regardless of
+ // whether it was user defined or not.
+ masterPortStart = 1
+
+ // The end of master port range which will hold all the
+ // allocation state of ports allocated so far regardless of
+ // whether it was user defined or not.
+ masterPortEnd = 65535
+)
+
+type portAllocator struct {
+ // portspace definition per protocol
+ portSpaces map[api.PortConfig_Protocol]*portSpace
+}
+
+type portSpace struct {
+ protocol api.PortConfig_Protocol
+ masterPortSpace *idm.Idm
+ dynamicPortSpace *idm.Idm
+}
+
+type allocatedPorts map[api.PortConfig]map[uint32]*api.PortConfig
+
+// addState add the state of an allocated port to the collection.
+// `allocatedPorts` is a map of portKey:publishedPort:portState.
+// In case the value of the portKey is missing, the map
+// publishedPort:portState is created automatically
+func (ps allocatedPorts) addState(p *api.PortConfig) {
+ portKey := getPortConfigKey(p)
+ if _, ok := ps[portKey]; !ok {
+ ps[portKey] = make(map[uint32]*api.PortConfig)
+ }
+ ps[portKey][p.PublishedPort] = p
+}
+
+// delState delete the state of an allocated port from the collection.
+// `allocatedPorts` is a map of portKey:publishedPort:portState.
+//
+// If publishedPort is non-zero, then it is user defined. We will try to
+// remove the portState from `allocatedPorts` directly and return
+// the portState (or nil if no portState exists)
+//
+// If publishedPort is zero, then it is dynamically allocated. We will try
+// to remove the portState from `allocatedPorts`, as long as there is
+// a portState associated with a non-zero publishedPort.
+// Note multiple dynamically allocated ports might exists. In this case,
+// we will remove only at a time so both allocated ports are tracked.
+//
+// Note because of the potential co-existence of user-defined and dynamically
+// allocated ports, delState has to be called for user-defined port first.
+// dynamically allocated ports should be removed later.
+func (ps allocatedPorts) delState(p *api.PortConfig) *api.PortConfig {
+ portKey := getPortConfigKey(p)
+
+ portStateMap, ok := ps[portKey]
+
+ // If name, port, protocol values don't match then we
+ // are not allocated.
+ if !ok {
+ return nil
+ }
+
+ if p.PublishedPort != 0 {
+ // If SwarmPort was user defined but the port state
+ // SwarmPort doesn't match we are not allocated.
+ v := portStateMap[p.PublishedPort]
+
+ // Delete state from allocatedPorts
+ delete(portStateMap, p.PublishedPort)
+
+ return v
+ }
+
+ // If PublishedPort == 0 and we don't have non-zero port
+ // then we are not allocated
+ for publishedPort, v := range portStateMap {
+ if publishedPort != 0 {
+ // Delete state from allocatedPorts
+ delete(portStateMap, publishedPort)
+ return v
+ }
+ }
+
+ return nil
+}
+
+func newPortAllocator() (*portAllocator, error) {
+ portSpaces := make(map[api.PortConfig_Protocol]*portSpace)
+ for _, protocol := range []api.PortConfig_Protocol{api.ProtocolTCP, api.ProtocolUDP} {
+ ps, err := newPortSpace(protocol)
+ if err != nil {
+ return nil, err
+ }
+
+ portSpaces[protocol] = ps
+ }
+
+ return &portAllocator{portSpaces: portSpaces}, nil
+}
+
+func newPortSpace(protocol api.PortConfig_Protocol) (*portSpace, error) {
+ masterName := fmt.Sprintf("%s-master-ports", protocol)
+ dynamicName := fmt.Sprintf("%s-dynamic-ports", protocol)
+
+ master, err := idm.New(nil, masterName, masterPortStart, masterPortEnd)
+ if err != nil {
+ return nil, err
+ }
+
+ dynamic, err := idm.New(nil, dynamicName, dynamicPortStart, dynamicPortEnd)
+ if err != nil {
+ return nil, err
+ }
+
+ return &portSpace{
+ protocol: protocol,
+ masterPortSpace: master,
+ dynamicPortSpace: dynamic,
+ }, nil
+}
+
+// getPortConfigKey returns a map key for doing set operations with
+// ports. The key consists of name, protocol and target port which
+// uniquely identifies a port within a single Endpoint.
+func getPortConfigKey(p *api.PortConfig) api.PortConfig {
+ return api.PortConfig{
+ Name: p.Name,
+ Protocol: p.Protocol,
+ TargetPort: p.TargetPort,
+ }
+}
+
+func reconcilePortConfigs(s *api.Service) []*api.PortConfig {
+ // If runtime state hasn't been created or if port config has
+ // changed from port state return the port config from Spec.
+ if s.Endpoint == nil || len(s.Spec.Endpoint.Ports) != len(s.Endpoint.Ports) {
+ return s.Spec.Endpoint.Ports
+ }
+
+ portStates := allocatedPorts{}
+ for _, portState := range s.Endpoint.Ports {
+ if portState.PublishMode == api.PublishModeIngress {
+ portStates.addState(portState)
+ }
+ }
+
+ var portConfigs []*api.PortConfig
+
+ // Process the portConfig with portConfig.PublishMode != api.PublishModeIngress
+ // and PublishedPort != 0 (high priority)
+ for _, portConfig := range s.Spec.Endpoint.Ports {
+ if portConfig.PublishMode != api.PublishModeIngress {
+ // If the PublishMode is not Ingress simply pick up the port config.
+ portConfigs = append(portConfigs, portConfig)
+ } else if portConfig.PublishedPort != 0 {
+ // Otherwise we only process PublishedPort != 0 in this round
+
+ // Remove record from portState
+ portStates.delState(portConfig)
+
+ // For PublishedPort != 0 prefer the portConfig
+ portConfigs = append(portConfigs, portConfig)
+ }
+ }
+
+ // Iterate portConfigs with PublishedPort == 0 (low priority)
+ for _, portConfig := range s.Spec.Endpoint.Ports {
+ // Ignore ports which are not PublishModeIngress (already processed)
+ // And we only process PublishedPort == 0 in this round
+ // So the following:
+ // `portConfig.PublishMode == api.PublishModeIngress && portConfig.PublishedPort == 0`
+ if portConfig.PublishMode == api.PublishModeIngress && portConfig.PublishedPort == 0 {
+ // If the portConfig is exactly the same as portState
+ // except if SwarmPort is not user-define then prefer
+ // portState to ensure sticky allocation of the same
+ // port that was allocated before.
+
+ // Remove record from portState
+ if portState := portStates.delState(portConfig); portState != nil {
+ portConfigs = append(portConfigs, portState)
+ continue
+ }
+
+ // For all other cases prefer the portConfig
+ portConfigs = append(portConfigs, portConfig)
+ }
+ }
+
+ return portConfigs
+}
+
+func (pa *portAllocator) serviceAllocatePorts(s *api.Service) (err error) {
+ if s.Spec.Endpoint == nil {
+ return nil
+ }
+
+ // We might have previous allocations which we want to stick
+ // to if possible. So instead of strictly going by port
+ // configs in the Spec reconcile the list of port configs from
+ // both the Spec and runtime state.
+ portConfigs := reconcilePortConfigs(s)
+
+ // Port configuration might have changed. Cleanup all old allocations first.
+ pa.serviceDeallocatePorts(s)
+
+ defer func() {
+ if err != nil {
+ // Free all the ports allocated so far which
+ // should be present in s.Endpoints.ExposedPorts
+ pa.serviceDeallocatePorts(s)
+ }
+ }()
+
+ for _, portConfig := range portConfigs {
+ // Make a copy of port config to create runtime state
+ portState := portConfig.Copy()
+
+ // Do an actual allocation only if the PublishMode is Ingress
+ if portConfig.PublishMode == api.PublishModeIngress {
+ if err = pa.portSpaces[portState.Protocol].allocate(portState); err != nil {
+ return
+ }
+ }
+
+ if s.Endpoint == nil {
+ s.Endpoint = &api.Endpoint{}
+ }
+
+ s.Endpoint.Ports = append(s.Endpoint.Ports, portState)
+ }
+
+ return nil
+}
+
+func (pa *portAllocator) serviceDeallocatePorts(s *api.Service) {
+ if s.Endpoint == nil {
+ return
+ }
+
+ for _, portState := range s.Endpoint.Ports {
+ // Do an actual free only if the PublishMode is
+ // Ingress
+ if portState.PublishMode != api.PublishModeIngress {
+ continue
+ }
+
+ pa.portSpaces[portState.Protocol].free(portState)
+ }
+
+ s.Endpoint.Ports = nil
+}
+
+func (pa *portAllocator) hostPublishPortsNeedUpdate(s *api.Service) bool {
+ if s.Endpoint == nil && s.Spec.Endpoint == nil {
+ return false
+ }
+
+ portStates := allocatedPorts{}
+ if s.Endpoint != nil {
+ for _, portState := range s.Endpoint.Ports {
+ if portState.PublishMode == api.PublishModeHost {
+ portStates.addState(portState)
+ }
+ }
+ }
+
+ if s.Spec.Endpoint != nil {
+ for _, portConfig := range s.Spec.Endpoint.Ports {
+ if portConfig.PublishMode == api.PublishModeHost &&
+ portConfig.PublishedPort != 0 {
+ if portStates.delState(portConfig) == nil {
+ return true
+ }
+ }
+ }
+ }
+
+ return false
+}
+
+func (pa *portAllocator) isPortsAllocated(s *api.Service) bool {
+ return pa.isPortsAllocatedOnInit(s, false)
+}
+
+func (pa *portAllocator) isPortsAllocatedOnInit(s *api.Service, onInit bool) bool {
+ // If service has no user-defined endpoint and allocated endpoint,
+ // we assume it is allocated and return true.
+ if s.Endpoint == nil && s.Spec.Endpoint == nil {
+ return true
+ }
+
+ // If service has allocated endpoint while has no user-defined endpoint,
+ // we assume allocated endpoints are redundant, and they need deallocated.
+ // If service has no allocated endpoint while has user-defined endpoint,
+ // we assume it is not allocated.
+ if (s.Endpoint != nil && s.Spec.Endpoint == nil) ||
+ (s.Endpoint == nil && s.Spec.Endpoint != nil) {
+ return false
+ }
+
+ // If we don't have same number of port states as port configs
+ // we assume it is not allocated.
+ if len(s.Spec.Endpoint.Ports) != len(s.Endpoint.Ports) {
+ return false
+ }
+
+ portStates := allocatedPorts{}
+ for _, portState := range s.Endpoint.Ports {
+ if portState.PublishMode == api.PublishModeIngress {
+ portStates.addState(portState)
+ }
+ }
+
+ // Iterate portConfigs with PublishedPort != 0 (high priority)
+ for _, portConfig := range s.Spec.Endpoint.Ports {
+ // Ignore ports which are not PublishModeIngress
+ if portConfig.PublishMode != api.PublishModeIngress {
+ continue
+ }
+ if portConfig.PublishedPort != 0 && portStates.delState(portConfig) == nil {
+ return false
+ }
+ }
+
+ // Iterate portConfigs with PublishedPort == 0 (low priority)
+ for _, portConfig := range s.Spec.Endpoint.Ports {
+ // Ignore ports which are not PublishModeIngress
+ if portConfig.PublishMode != api.PublishModeIngress {
+ continue
+ }
+ if portConfig.PublishedPort == 0 && portStates.delState(portConfig) == nil {
+ return false
+ }
+
+ // If SwarmPort was not defined by user and the func
+ // is called during allocator initialization state then
+ // we are not allocated.
+ if portConfig.PublishedPort == 0 && onInit {
+ return false
+ }
+ }
+
+ return true
+}
+
+func (ps *portSpace) allocate(p *api.PortConfig) (err error) {
+ if p.PublishedPort != 0 {
+ // If it falls in the dynamic port range check out
+ // from dynamic port space first.
+ if p.PublishedPort >= dynamicPortStart && p.PublishedPort <= dynamicPortEnd {
+ if err = ps.dynamicPortSpace.GetSpecificID(uint64(p.PublishedPort)); err != nil {
+ return err
+ }
+
+ defer func() {
+ if err != nil {
+ ps.dynamicPortSpace.Release(uint64(p.PublishedPort))
+ }
+ }()
+ }
+
+ return ps.masterPortSpace.GetSpecificID(uint64(p.PublishedPort))
+ }
+
+ // Check out an arbitrary port from dynamic port space.
+ swarmPort, err := ps.dynamicPortSpace.GetID()
+ if err != nil {
+ return
+ }
+ defer func() {
+ if err != nil {
+ ps.dynamicPortSpace.Release(uint64(swarmPort))
+ }
+ }()
+
+ // Make sure we allocate the same port from the master space.
+ if err = ps.masterPortSpace.GetSpecificID(uint64(swarmPort)); err != nil {
+ return
+ }
+
+ p.PublishedPort = uint32(swarmPort)
+ return nil
+}
+
+func (ps *portSpace) free(p *api.PortConfig) {
+ if p.PublishedPort >= dynamicPortStart && p.PublishedPort <= dynamicPortEnd {
+ ps.dynamicPortSpace.Release(uint64(p.PublishedPort))
+ }
+
+ ps.masterPortSpace.Release(uint64(p.PublishedPort))
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/doc.go b/vendor/github.com/docker/swarmkit/manager/allocator/doc.go
new file mode 100644
index 0000000..0579c66
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/doc.go
@@ -0,0 +1,18 @@
+// Package allocator aims to manage allocation of different
+// cluster-wide resources on behalf of the manager. In particular, it
+// manages a set of independent allocator processes which can mostly
+// execute concurrently with only a minimal need for coordination.
+//
+// One of the instances where it needs coordination is when deciding to
+// move a task to the PENDING state. Since a task can move to the
+// PENDING state only when all the task allocators have completed,
+// they must cooperate. The way `allocator` achieves this is by creating
+// a `taskBallot` to which all task allocators register themselves as
+// mandatory voters. For each task that needs allocation, each allocator
+// independently votes to indicate the completion of their allocation.
+// Once all registered voters have voted then the task is moved to the
+// PENDING state.
+//
+// Other than the coordination needed for task PENDING state, all
+// the allocators function fairly independently.
+package allocator
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/network.go b/vendor/github.com/docker/swarmkit/manager/allocator/network.go
new file mode 100644
index 0000000..c760ad5
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/network.go
@@ -0,0 +1,1193 @@
+package allocator
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/allocator/cnmallocator"
+ "github.com/docker/swarmkit/manager/allocator/networkallocator"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/protobuf/ptypes"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+const (
+ // Network allocator Voter ID for task allocation vote.
+ networkVoter = "network"
+ allocatedStatusMessage = "pending task scheduling"
+)
+
+var (
+ // ErrNoIngress is returned when no ingress network is found in store
+ ErrNoIngress = errors.New("no ingress network found")
+ errNoChanges = errors.New("task unchanged")
+
+ retryInterval = 5 * time.Minute
+)
+
+// Network context information which is used throughout the network allocation code.
+type networkContext struct {
+ ingressNetwork *api.Network
+ // Instance of the low-level network allocator which performs
+ // the actual network allocation.
+ nwkAllocator networkallocator.NetworkAllocator
+
+ // A set of tasks which are ready to be allocated as a batch. This is
+ // distinct from "unallocatedTasks" which are tasks that failed to
+ // allocate on the first try, being held for a future retry.
+ pendingTasks map[string]*api.Task
+
+ // A set of unallocated tasks which will be revisited if any thing
+ // changes in system state that might help task allocation.
+ unallocatedTasks map[string]*api.Task
+
+ // A set of unallocated services which will be revisited if
+ // any thing changes in system state that might help service
+ // allocation.
+ unallocatedServices map[string]*api.Service
+
+ // A set of unallocated networks which will be revisited if
+ // any thing changes in system state that might help network
+ // allocation.
+ unallocatedNetworks map[string]*api.Network
+
+ // lastRetry is the last timestamp when unallocated
+ // tasks/services/networks were retried.
+ lastRetry time.Time
+
+ // somethingWasDeallocated indicates that we just deallocated at
+ // least one service/task/network, so we should retry failed
+ // allocations (in we are experiencing IP exhaustion and an IP was
+ // released).
+ somethingWasDeallocated bool
+}
+
+func (a *Allocator) doNetworkInit(ctx context.Context) (err error) {
+ na, err := cnmallocator.New(a.pluginGetter)
+ if err != nil {
+ return err
+ }
+
+ nc := &networkContext{
+ nwkAllocator: na,
+ pendingTasks: make(map[string]*api.Task),
+ unallocatedTasks: make(map[string]*api.Task),
+ unallocatedServices: make(map[string]*api.Service),
+ unallocatedNetworks: make(map[string]*api.Network),
+ lastRetry: time.Now(),
+ }
+ a.netCtx = nc
+ defer func() {
+ // Clear a.netCtx if initialization was unsuccessful.
+ if err != nil {
+ a.netCtx = nil
+ }
+ }()
+
+ // Ingress network is now created at cluster's first time creation.
+ // Check if we have the ingress network. If found, make sure it is
+ // allocated, before reading all network objects for allocation.
+ // If not found, it means it was removed by user, nothing to do here.
+ ingressNetwork, err := GetIngressNetwork(a.store)
+ switch err {
+ case nil:
+ // Try to complete ingress network allocation before anything else so
+ // that the we can get the preferred subnet for ingress network.
+ nc.ingressNetwork = ingressNetwork
+ if !na.IsAllocated(nc.ingressNetwork) {
+ if err := a.allocateNetwork(ctx, nc.ingressNetwork); err != nil {
+ log.G(ctx).WithError(err).Error("failed allocating ingress network during init")
+ } else if err := a.store.Batch(func(batch *store.Batch) error {
+ if err := a.commitAllocatedNetwork(ctx, batch, nc.ingressNetwork); err != nil {
+ log.G(ctx).WithError(err).Error("failed committing allocation of ingress network during init")
+ }
+ return nil
+ }); err != nil {
+ log.G(ctx).WithError(err).Error("failed committing allocation of ingress network during init")
+ }
+ }
+ case ErrNoIngress:
+ // Ingress network is not present in store, It means user removed it
+ // and did not create a new one.
+ default:
+ return errors.Wrap(err, "failure while looking for ingress network during init")
+ }
+
+ // Allocate networks in the store so far before we started
+ // watching.
+ var networks []*api.Network
+ a.store.View(func(tx store.ReadTx) {
+ networks, err = store.FindNetworks(tx, store.All)
+ })
+ if err != nil {
+ return errors.Wrap(err, "error listing all networks in store while trying to allocate during init")
+ }
+
+ var allocatedNetworks []*api.Network
+ for _, n := range networks {
+ if na.IsAllocated(n) {
+ continue
+ }
+
+ if err := a.allocateNetwork(ctx, n); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed allocating network %s during init", n.ID)
+ continue
+ }
+ allocatedNetworks = append(allocatedNetworks, n)
+ }
+
+ if err := a.store.Batch(func(batch *store.Batch) error {
+ for _, n := range allocatedNetworks {
+ if err := a.commitAllocatedNetwork(ctx, batch, n); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed committing allocation of network %s during init", n.ID)
+ }
+ }
+ return nil
+ }); err != nil {
+ log.G(ctx).WithError(err).Error("failed committing allocation of networks during init")
+ }
+
+ // First, allocate objects that already have addresses associated with
+ // them, to reserve these IP addresses in internal state.
+ if nc.ingressNetwork != nil {
+ if err := a.allocateNodes(ctx, true); err != nil {
+ return err
+ }
+ }
+ if err := a.allocateServices(ctx, true); err != nil {
+ return err
+ }
+ if err := a.allocateTasks(ctx, true); err != nil {
+ return err
+ }
+
+ // Now allocate objects that don't have addresses yet.
+ if nc.ingressNetwork != nil {
+ if err := a.allocateNodes(ctx, false); err != nil {
+ return err
+ }
+ }
+ if err := a.allocateServices(ctx, false); err != nil {
+ return err
+ }
+ if err := a.allocateTasks(ctx, false); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (a *Allocator) doNetworkAlloc(ctx context.Context, ev events.Event) {
+ nc := a.netCtx
+
+ switch v := ev.(type) {
+ case api.EventCreateNetwork:
+ n := v.Network.Copy()
+ if nc.nwkAllocator.IsAllocated(n) {
+ break
+ }
+
+ if IsIngressNetwork(n) && nc.ingressNetwork != nil {
+ log.G(ctx).Errorf("Cannot allocate ingress network %s (%s) because another ingress network is already present: %s (%s)",
+ n.ID, n.Spec.Annotations.Name, nc.ingressNetwork.ID, nc.ingressNetwork.Spec.Annotations)
+ break
+ }
+
+ if err := a.allocateNetwork(ctx, n); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed allocation for network %s", n.ID)
+ break
+ }
+
+ if err := a.store.Batch(func(batch *store.Batch) error {
+ return a.commitAllocatedNetwork(ctx, batch, n)
+ }); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed to commit allocation for network %s", n.ID)
+ }
+
+ if IsIngressNetwork(n) {
+ nc.ingressNetwork = n
+ err := a.allocateNodes(ctx, false)
+ if err != nil {
+ log.G(ctx).WithError(err).Error(err)
+ }
+ }
+ case api.EventDeleteNetwork:
+ n := v.Network.Copy()
+
+ if IsIngressNetwork(n) && nc.ingressNetwork != nil && nc.ingressNetwork.ID == n.ID {
+ nc.ingressNetwork = nil
+ if err := a.deallocateNodes(ctx); err != nil {
+ log.G(ctx).WithError(err).Error(err)
+ }
+ }
+
+ // The assumption here is that all dependent objects
+ // have been cleaned up when we are here so the only
+ // thing that needs to happen is free the network
+ // resources.
+ if err := nc.nwkAllocator.Deallocate(n); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed during network free for network %s", n.ID)
+ } else {
+ nc.somethingWasDeallocated = true
+ }
+
+ delete(nc.unallocatedNetworks, n.ID)
+ case api.EventCreateService:
+ var s *api.Service
+ a.store.View(func(tx store.ReadTx) {
+ s = store.GetService(tx, v.Service.ID)
+ })
+
+ if s == nil {
+ break
+ }
+
+ if nc.nwkAllocator.IsServiceAllocated(s) {
+ break
+ }
+
+ if err := a.allocateService(ctx, s); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed allocation for service %s", s.ID)
+ break
+ }
+
+ if err := a.store.Batch(func(batch *store.Batch) error {
+ return a.commitAllocatedService(ctx, batch, s)
+ }); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed to commit allocation for service %s", s.ID)
+ }
+ case api.EventUpdateService:
+ // We may have already allocated this service. If a create or
+ // update event is older than the current version in the store,
+ // we run the risk of allocating the service a second time.
+ // Only operate on the latest version of the service.
+ var s *api.Service
+ a.store.View(func(tx store.ReadTx) {
+ s = store.GetService(tx, v.Service.ID)
+ })
+
+ if s == nil {
+ break
+ }
+
+ if nc.nwkAllocator.IsServiceAllocated(s) {
+ if !nc.nwkAllocator.HostPublishPortsNeedUpdate(s) {
+ break
+ }
+ updatePortsInHostPublishMode(s)
+ } else {
+ if err := a.allocateService(ctx, s); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed allocation during update of service %s", s.ID)
+ break
+ }
+ }
+
+ if err := a.store.Batch(func(batch *store.Batch) error {
+ return a.commitAllocatedService(ctx, batch, s)
+ }); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed to commit allocation during update for service %s", s.ID)
+ nc.unallocatedServices[s.ID] = s
+ } else {
+ delete(nc.unallocatedServices, s.ID)
+ }
+ case api.EventDeleteService:
+ s := v.Service.Copy()
+
+ if err := nc.nwkAllocator.DeallocateService(s); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed deallocation during delete of service %s", s.ID)
+ } else {
+ nc.somethingWasDeallocated = true
+ }
+
+ // Remove it from unallocatedServices just in case
+ // it's still there.
+ delete(nc.unallocatedServices, s.ID)
+ case api.EventCreateNode, api.EventUpdateNode, api.EventDeleteNode:
+ a.doNodeAlloc(ctx, ev)
+ case api.EventCreateTask, api.EventUpdateTask, api.EventDeleteTask:
+ a.doTaskAlloc(ctx, ev)
+ case state.EventCommit:
+ a.procTasksNetwork(ctx, false)
+
+ if time.Since(nc.lastRetry) > retryInterval || nc.somethingWasDeallocated {
+ a.procUnallocatedNetworks(ctx)
+ a.procUnallocatedServices(ctx)
+ a.procTasksNetwork(ctx, true)
+ nc.lastRetry = time.Now()
+ nc.somethingWasDeallocated = false
+ }
+
+ // Any left over tasks are moved to the unallocated set
+ for _, t := range nc.pendingTasks {
+ nc.unallocatedTasks[t.ID] = t
+ }
+ nc.pendingTasks = make(map[string]*api.Task)
+ }
+}
+
+func (a *Allocator) doNodeAlloc(ctx context.Context, ev events.Event) {
+ var (
+ isDelete bool
+ node *api.Node
+ )
+
+ // We may have already allocated this node. If a create or update
+ // event is older than the current version in the store, we run the
+ // risk of allocating the node a second time. Only operate on the
+ // latest version of the node.
+ switch v := ev.(type) {
+ case api.EventCreateNode:
+ a.store.View(func(tx store.ReadTx) {
+ node = store.GetNode(tx, v.Node.ID)
+ })
+ case api.EventUpdateNode:
+ a.store.View(func(tx store.ReadTx) {
+ node = store.GetNode(tx, v.Node.ID)
+ })
+ case api.EventDeleteNode:
+ isDelete = true
+ node = v.Node.Copy()
+ }
+
+ if node == nil {
+ return
+ }
+
+ nc := a.netCtx
+
+ if isDelete {
+ if nc.nwkAllocator.IsNodeAllocated(node) {
+ if err := nc.nwkAllocator.DeallocateNode(node); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed freeing network resources for node %s", node.ID)
+ } else {
+ nc.somethingWasDeallocated = true
+ }
+ }
+ return
+ }
+
+ if !nc.nwkAllocator.IsNodeAllocated(node) && nc.ingressNetwork != nil {
+ if node.Attachment == nil {
+ node.Attachment = &api.NetworkAttachment{}
+ }
+
+ node.Attachment.Network = nc.ingressNetwork.Copy()
+ if err := a.allocateNode(ctx, node); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed to allocate network resources for node %s", node.ID)
+ return
+ }
+
+ if err := a.store.Batch(func(batch *store.Batch) error {
+ return a.commitAllocatedNode(ctx, batch, node)
+ }); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed to commit allocation of network resources for node %s", node.ID)
+ }
+ }
+}
+
+func (a *Allocator) allocateNodes(ctx context.Context, existingAddressesOnly bool) error {
+ // Allocate nodes in the store so far before we process watched events.
+ var (
+ allocatedNodes []*api.Node
+ nodes []*api.Node
+ err error
+ nc = a.netCtx
+ )
+
+ a.store.View(func(tx store.ReadTx) {
+ nodes, err = store.FindNodes(tx, store.All)
+ })
+ if err != nil {
+ return errors.Wrap(err, "error listing all nodes in store while trying to allocate network resources")
+ }
+
+ for _, node := range nodes {
+ if nc.nwkAllocator.IsNodeAllocated(node) {
+ continue
+ }
+
+ if node.Attachment == nil {
+ node.Attachment = &api.NetworkAttachment{}
+ }
+
+ if existingAddressesOnly && len(node.Attachment.Addresses) == 0 {
+ continue
+ }
+
+ node.Attachment.Network = nc.ingressNetwork.Copy()
+ if err := a.allocateNode(ctx, node); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed to allocate network resources for node %s", node.ID)
+ continue
+ }
+
+ allocatedNodes = append(allocatedNodes, node)
+ }
+
+ if err := a.store.Batch(func(batch *store.Batch) error {
+ for _, node := range allocatedNodes {
+ if err := a.commitAllocatedNode(ctx, batch, node); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed to commit allocation of network resources for node %s", node.ID)
+ }
+ }
+ return nil
+ }); err != nil {
+ log.G(ctx).WithError(err).Error("Failed to commit allocation of network resources for nodes")
+ }
+
+ return nil
+}
+
+func (a *Allocator) deallocateNodes(ctx context.Context) error {
+ var (
+ nodes []*api.Node
+ nc = a.netCtx
+ err error
+ )
+
+ a.store.View(func(tx store.ReadTx) {
+ nodes, err = store.FindNodes(tx, store.All)
+ })
+ if err != nil {
+ return fmt.Errorf("error listing all nodes in store while trying to free network resources")
+ }
+
+ for _, node := range nodes {
+ if nc.nwkAllocator.IsNodeAllocated(node) {
+ if err := nc.nwkAllocator.DeallocateNode(node); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed freeing network resources for node %s", node.ID)
+ } else {
+ nc.somethingWasDeallocated = true
+ }
+ node.Attachment = nil
+ if err := a.store.Batch(func(batch *store.Batch) error {
+ return a.commitAllocatedNode(ctx, batch, node)
+ }); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed to commit deallocation of network resources for node %s", node.ID)
+ }
+ }
+ }
+
+ return nil
+}
+
+// allocateServices allocates services in the store so far before we process
+// watched events.
+func (a *Allocator) allocateServices(ctx context.Context, existingAddressesOnly bool) error {
+ var (
+ nc = a.netCtx
+ services []*api.Service
+ err error
+ )
+ a.store.View(func(tx store.ReadTx) {
+ services, err = store.FindServices(tx, store.All)
+ })
+ if err != nil {
+ return errors.Wrap(err, "error listing all services in store while trying to allocate during init")
+ }
+
+ var allocatedServices []*api.Service
+ for _, s := range services {
+ if nc.nwkAllocator.IsServiceAllocated(s, networkallocator.OnInit) {
+ continue
+ }
+
+ if existingAddressesOnly &&
+ (s.Endpoint == nil ||
+ len(s.Endpoint.VirtualIPs) == 0) {
+ continue
+ }
+
+ if err := a.allocateService(ctx, s); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed allocating service %s during init", s.ID)
+ continue
+ }
+ allocatedServices = append(allocatedServices, s)
+ }
+
+ if err := a.store.Batch(func(batch *store.Batch) error {
+ for _, s := range allocatedServices {
+ if err := a.commitAllocatedService(ctx, batch, s); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed committing allocation of service %s during init", s.ID)
+ }
+ }
+ return nil
+ }); err != nil {
+ log.G(ctx).WithError(err).Error("failed committing allocation of services during init")
+ }
+
+ return nil
+}
+
+// allocateTasks allocates tasks in the store so far before we started watching.
+func (a *Allocator) allocateTasks(ctx context.Context, existingAddressesOnly bool) error {
+ var (
+ nc = a.netCtx
+ tasks []*api.Task
+ allocatedTasks []*api.Task
+ err error
+ )
+ a.store.View(func(tx store.ReadTx) {
+ tasks, err = store.FindTasks(tx, store.All)
+ })
+ if err != nil {
+ return errors.Wrap(err, "error listing all tasks in store while trying to allocate during init")
+ }
+
+ for _, t := range tasks {
+ if t.Status.State > api.TaskStateRunning {
+ continue
+ }
+
+ if existingAddressesOnly {
+ hasAddresses := false
+ for _, nAttach := range t.Networks {
+ if len(nAttach.Addresses) != 0 {
+ hasAddresses = true
+ break
+ }
+ }
+ if !hasAddresses {
+ continue
+ }
+ }
+
+ var s *api.Service
+ if t.ServiceID != "" {
+ a.store.View(func(tx store.ReadTx) {
+ s = store.GetService(tx, t.ServiceID)
+ })
+ }
+
+ // Populate network attachments in the task
+ // based on service spec.
+ a.taskCreateNetworkAttachments(t, s)
+
+ if taskReadyForNetworkVote(t, s, nc) {
+ if t.Status.State >= api.TaskStatePending {
+ continue
+ }
+
+ if a.taskAllocateVote(networkVoter, t.ID) {
+ // If the task is not attached to any network, network
+ // allocators job is done. Immediately cast a vote so
+ // that the task can be moved to the PENDING state as
+ // soon as possible.
+ updateTaskStatus(t, api.TaskStatePending, allocatedStatusMessage)
+ allocatedTasks = append(allocatedTasks, t)
+ }
+ continue
+ }
+
+ err := a.allocateTask(ctx, t)
+ if err == nil {
+ allocatedTasks = append(allocatedTasks, t)
+ } else if err != errNoChanges {
+ log.G(ctx).WithError(err).Errorf("failed allocating task %s during init", t.ID)
+ nc.unallocatedTasks[t.ID] = t
+ }
+ }
+
+ if err := a.store.Batch(func(batch *store.Batch) error {
+ for _, t := range allocatedTasks {
+ if err := a.commitAllocatedTask(ctx, batch, t); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed committing allocation of task %s during init", t.ID)
+ }
+ }
+
+ return nil
+ }); err != nil {
+ log.G(ctx).WithError(err).Error("failed committing allocation of tasks during init")
+ }
+
+ return nil
+}
+
+// taskReadyForNetworkVote checks if the task is ready for a network
+// vote to move it to PENDING state.
+func taskReadyForNetworkVote(t *api.Task, s *api.Service, nc *networkContext) bool {
+ // Task is ready for vote if the following is true:
+ //
+ // Task has no network attached or networks attached but all
+ // of them allocated AND Task's service has no endpoint or
+ // network configured or service endpoints have been
+ // allocated.
+ return (len(t.Networks) == 0 || nc.nwkAllocator.IsTaskAllocated(t)) &&
+ (s == nil || nc.nwkAllocator.IsServiceAllocated(s))
+}
+
+func taskUpdateNetworks(t *api.Task, networks []*api.NetworkAttachment) {
+ networksCopy := make([]*api.NetworkAttachment, 0, len(networks))
+ for _, n := range networks {
+ networksCopy = append(networksCopy, n.Copy())
+ }
+
+ t.Networks = networksCopy
+}
+
+func taskUpdateEndpoint(t *api.Task, endpoint *api.Endpoint) {
+ t.Endpoint = endpoint.Copy()
+}
+
+// IsIngressNetworkNeeded checks whether the service requires the routing-mesh
+func IsIngressNetworkNeeded(s *api.Service) bool {
+ return networkallocator.IsIngressNetworkNeeded(s)
+}
+
+func (a *Allocator) taskCreateNetworkAttachments(t *api.Task, s *api.Service) {
+ // If task network attachments have already been filled in no
+ // need to do anything else.
+ if len(t.Networks) != 0 {
+ return
+ }
+
+ var networks []*api.NetworkAttachment
+ if IsIngressNetworkNeeded(s) && a.netCtx.ingressNetwork != nil {
+ networks = append(networks, &api.NetworkAttachment{Network: a.netCtx.ingressNetwork})
+ }
+
+ a.store.View(func(tx store.ReadTx) {
+ // Always prefer NetworkAttachmentConfig in the TaskSpec
+ specNetworks := t.Spec.Networks
+ if len(specNetworks) == 0 && s != nil && len(s.Spec.Networks) != 0 {
+ specNetworks = s.Spec.Networks
+ }
+
+ for _, na := range specNetworks {
+ n := store.GetNetwork(tx, na.Target)
+ if n == nil {
+ continue
+ }
+
+ attachment := api.NetworkAttachment{Network: n}
+ attachment.Aliases = append(attachment.Aliases, na.Aliases...)
+ attachment.Addresses = append(attachment.Addresses, na.Addresses...)
+ attachment.DriverAttachmentOpts = na.DriverAttachmentOpts
+ networks = append(networks, &attachment)
+ }
+ })
+
+ taskUpdateNetworks(t, networks)
+}
+
+func (a *Allocator) doTaskAlloc(ctx context.Context, ev events.Event) {
+ var (
+ isDelete bool
+ t *api.Task
+ )
+
+ // We may have already allocated this task. If a create or update
+ // event is older than the current version in the store, we run the
+ // risk of allocating the task a second time. Only operate on the
+ // latest version of the task.
+ switch v := ev.(type) {
+ case api.EventCreateTask:
+ a.store.View(func(tx store.ReadTx) {
+ t = store.GetTask(tx, v.Task.ID)
+ })
+ case api.EventUpdateTask:
+ a.store.View(func(tx store.ReadTx) {
+ t = store.GetTask(tx, v.Task.ID)
+ })
+ case api.EventDeleteTask:
+ isDelete = true
+ t = v.Task.Copy()
+ }
+
+ if t == nil {
+ return
+ }
+
+ nc := a.netCtx
+
+ // If the task has stopped running then we should free the network
+ // resources associated with the task right away.
+ if t.Status.State > api.TaskStateRunning || isDelete {
+ if nc.nwkAllocator.IsTaskAllocated(t) {
+ if err := nc.nwkAllocator.DeallocateTask(t); err != nil {
+ log.G(ctx).WithError(err).Errorf("Failed freeing network resources for task %s", t.ID)
+ } else {
+ nc.somethingWasDeallocated = true
+ }
+ }
+
+ // Cleanup any task references that might exist
+ delete(nc.pendingTasks, t.ID)
+ delete(nc.unallocatedTasks, t.ID)
+
+ return
+ }
+
+ // If we are already in allocated state, there is
+ // absolutely nothing else to do.
+ if t.Status.State >= api.TaskStatePending {
+ delete(nc.pendingTasks, t.ID)
+ delete(nc.unallocatedTasks, t.ID)
+ return
+ }
+
+ var s *api.Service
+ if t.ServiceID != "" {
+ a.store.View(func(tx store.ReadTx) {
+ s = store.GetService(tx, t.ServiceID)
+ })
+ if s == nil {
+ // If the task is running it is not normal to
+ // not be able to find the associated
+ // service. If the task is not running (task
+ // is either dead or the desired state is set
+ // to dead) then the service may not be
+ // available in store. But we still need to
+ // cleanup network resources associated with
+ // the task.
+ if t.Status.State <= api.TaskStateRunning && !isDelete {
+ log.G(ctx).Errorf("Event %T: Failed to get service %s for task %s state %s: could not find service %s", ev, t.ServiceID, t.ID, t.Status.State, t.ServiceID)
+ return
+ }
+ }
+ }
+
+ // Populate network attachments in the task
+ // based on service spec.
+ a.taskCreateNetworkAttachments(t, s)
+
+ nc.pendingTasks[t.ID] = t
+}
+
+func (a *Allocator) allocateNode(ctx context.Context, node *api.Node) error {
+ return a.netCtx.nwkAllocator.AllocateNode(node)
+}
+
+func (a *Allocator) commitAllocatedNode(ctx context.Context, batch *store.Batch, node *api.Node) error {
+ if err := batch.Update(func(tx store.Tx) error {
+ err := store.UpdateNode(tx, node)
+
+ if err == store.ErrSequenceConflict {
+ storeNode := store.GetNode(tx, node.ID)
+ storeNode.Attachment = node.Attachment.Copy()
+ err = store.UpdateNode(tx, storeNode)
+ }
+
+ return errors.Wrapf(err, "failed updating state in store transaction for node %s", node.ID)
+ }); err != nil {
+ if err := a.netCtx.nwkAllocator.DeallocateNode(node); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed rolling back allocation of node %s", node.ID)
+ }
+
+ return err
+ }
+
+ return nil
+}
+
+// This function prepares the service object for being updated when the change regards
+// the published ports in host mode: It resets the runtime state ports (s.Endpoint.Ports)
+// to the current ingress mode runtime state ports plus the newly configured publish mode ports,
+// so that the service allocation invoked on this new service object will trigger the deallocation
+// of any old publish mode port and allocation of any new one.
+func updatePortsInHostPublishMode(s *api.Service) {
+ // First, remove all host-mode ports from s.Endpoint.Ports
+ if s.Endpoint != nil {
+ var portConfigs []*api.PortConfig
+ for _, portConfig := range s.Endpoint.Ports {
+ if portConfig.PublishMode != api.PublishModeHost {
+ portConfigs = append(portConfigs, portConfig)
+ }
+ }
+ s.Endpoint.Ports = portConfigs
+ }
+
+ // Add back all host-mode ports
+ if s.Spec.Endpoint != nil {
+ if s.Endpoint == nil {
+ s.Endpoint = &api.Endpoint{}
+ }
+ for _, portConfig := range s.Spec.Endpoint.Ports {
+ if portConfig.PublishMode == api.PublishModeHost {
+ s.Endpoint.Ports = append(s.Endpoint.Ports, portConfig.Copy())
+ }
+ }
+ }
+ s.Endpoint.Spec = s.Spec.Endpoint.Copy()
+}
+
+func (a *Allocator) allocateService(ctx context.Context, s *api.Service) error {
+ nc := a.netCtx
+
+ if s.Spec.Endpoint != nil {
+ // service has user-defined endpoint
+ if s.Endpoint == nil {
+ // service currently has no allocated endpoint, need allocated.
+ s.Endpoint = &api.Endpoint{
+ Spec: s.Spec.Endpoint.Copy(),
+ }
+ }
+
+ // The service is trying to expose ports to the external
+ // world. Automatically attach the service to the ingress
+ // network only if it is not already done.
+ if IsIngressNetworkNeeded(s) {
+ if nc.ingressNetwork == nil {
+ return fmt.Errorf("ingress network is missing")
+ }
+ var found bool
+ for _, vip := range s.Endpoint.VirtualIPs {
+ if vip.NetworkID == nc.ingressNetwork.ID {
+ found = true
+ break
+ }
+ }
+
+ if !found {
+ s.Endpoint.VirtualIPs = append(s.Endpoint.VirtualIPs,
+ &api.Endpoint_VirtualIP{NetworkID: nc.ingressNetwork.ID})
+ }
+ }
+ } else if s.Endpoint != nil {
+ // service has no user-defined endpoints while has already allocated network resources,
+ // need deallocated.
+ if err := nc.nwkAllocator.DeallocateService(s); err != nil {
+ return err
+ }
+ nc.somethingWasDeallocated = true
+ }
+
+ if err := nc.nwkAllocator.AllocateService(s); err != nil {
+ nc.unallocatedServices[s.ID] = s
+ return err
+ }
+
+ // If the service doesn't expose ports any more and if we have
+ // any lingering virtual IP references for ingress network
+ // clean them up here.
+ if !IsIngressNetworkNeeded(s) && nc.ingressNetwork != nil {
+ if s.Endpoint != nil {
+ for i, vip := range s.Endpoint.VirtualIPs {
+ if vip.NetworkID == nc.ingressNetwork.ID {
+ n := len(s.Endpoint.VirtualIPs)
+ s.Endpoint.VirtualIPs[i], s.Endpoint.VirtualIPs[n-1] = s.Endpoint.VirtualIPs[n-1], nil
+ s.Endpoint.VirtualIPs = s.Endpoint.VirtualIPs[:n-1]
+ break
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (a *Allocator) commitAllocatedService(ctx context.Context, batch *store.Batch, s *api.Service) error {
+ if err := batch.Update(func(tx store.Tx) error {
+ err := store.UpdateService(tx, s)
+
+ if err == store.ErrSequenceConflict {
+ storeService := store.GetService(tx, s.ID)
+ storeService.Endpoint = s.Endpoint
+ err = store.UpdateService(tx, storeService)
+ }
+
+ return errors.Wrapf(err, "failed updating state in store transaction for service %s", s.ID)
+ }); err != nil {
+ if err := a.netCtx.nwkAllocator.DeallocateService(s); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed rolling back allocation of service %s", s.ID)
+ }
+
+ return err
+ }
+
+ return nil
+}
+
+func (a *Allocator) allocateNetwork(ctx context.Context, n *api.Network) error {
+ nc := a.netCtx
+
+ if err := nc.nwkAllocator.Allocate(n); err != nil {
+ nc.unallocatedNetworks[n.ID] = n
+ return err
+ }
+
+ return nil
+}
+
+func (a *Allocator) commitAllocatedNetwork(ctx context.Context, batch *store.Batch, n *api.Network) error {
+ if err := batch.Update(func(tx store.Tx) error {
+ if err := store.UpdateNetwork(tx, n); err != nil {
+ return errors.Wrapf(err, "failed updating state in store transaction for network %s", n.ID)
+ }
+ return nil
+ }); err != nil {
+ if err := a.netCtx.nwkAllocator.Deallocate(n); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed rolling back allocation of network %s", n.ID)
+ }
+
+ return err
+ }
+
+ return nil
+}
+
+func (a *Allocator) allocateTask(ctx context.Context, t *api.Task) (err error) {
+ taskUpdated := false
+ nc := a.netCtx
+
+ // We might be here even if a task allocation has already
+ // happened but wasn't successfully committed to store. In such
+ // cases skip allocation and go straight ahead to updating the
+ // store.
+ if !nc.nwkAllocator.IsTaskAllocated(t) {
+ a.store.View(func(tx store.ReadTx) {
+ if t.ServiceID != "" {
+ s := store.GetService(tx, t.ServiceID)
+ if s == nil {
+ err = fmt.Errorf("could not find service %s", t.ServiceID)
+ return
+ }
+
+ if !nc.nwkAllocator.IsServiceAllocated(s) {
+ err = fmt.Errorf("service %s to which this task %s belongs has pending allocations", s.ID, t.ID)
+ return
+ }
+
+ if s.Endpoint != nil {
+ taskUpdateEndpoint(t, s.Endpoint)
+ taskUpdated = true
+ }
+ }
+
+ for _, na := range t.Networks {
+ n := store.GetNetwork(tx, na.Network.ID)
+ if n == nil {
+ err = fmt.Errorf("failed to retrieve network %s while allocating task %s", na.Network.ID, t.ID)
+ return
+ }
+
+ if !nc.nwkAllocator.IsAllocated(n) {
+ err = fmt.Errorf("network %s attached to task %s not allocated yet", n.ID, t.ID)
+ return
+ }
+
+ na.Network = n
+ }
+
+ if err = nc.nwkAllocator.AllocateTask(t); err != nil {
+ return
+ }
+ if nc.nwkAllocator.IsTaskAllocated(t) {
+ taskUpdated = true
+ }
+ })
+
+ if err != nil {
+ return err
+ }
+ }
+
+ // Update the network allocations and moving to
+ // PENDING state on top of the latest store state.
+ if a.taskAllocateVote(networkVoter, t.ID) {
+ if t.Status.State < api.TaskStatePending {
+ updateTaskStatus(t, api.TaskStatePending, allocatedStatusMessage)
+ taskUpdated = true
+ }
+ }
+
+ if !taskUpdated {
+ return errNoChanges
+ }
+
+ return nil
+}
+
+func (a *Allocator) commitAllocatedTask(ctx context.Context, batch *store.Batch, t *api.Task) error {
+ return batch.Update(func(tx store.Tx) error {
+ err := store.UpdateTask(tx, t)
+
+ if err == store.ErrSequenceConflict {
+ storeTask := store.GetTask(tx, t.ID)
+ taskUpdateNetworks(storeTask, t.Networks)
+ taskUpdateEndpoint(storeTask, t.Endpoint)
+ if storeTask.Status.State < api.TaskStatePending {
+ storeTask.Status = t.Status
+ }
+ err = store.UpdateTask(tx, storeTask)
+ }
+
+ return errors.Wrapf(err, "failed updating state in store transaction for task %s", t.ID)
+ })
+}
+
+func (a *Allocator) procUnallocatedNetworks(ctx context.Context) {
+ nc := a.netCtx
+ var allocatedNetworks []*api.Network
+ for _, n := range nc.unallocatedNetworks {
+ if !nc.nwkAllocator.IsAllocated(n) {
+ if err := a.allocateNetwork(ctx, n); err != nil {
+ log.G(ctx).WithError(err).Debugf("Failed allocation of unallocated network %s", n.ID)
+ continue
+ }
+ allocatedNetworks = append(allocatedNetworks, n)
+ }
+ }
+
+ if len(allocatedNetworks) == 0 {
+ return
+ }
+
+ err := a.store.Batch(func(batch *store.Batch) error {
+ for _, n := range allocatedNetworks {
+ if err := a.commitAllocatedNetwork(ctx, batch, n); err != nil {
+ log.G(ctx).WithError(err).Debugf("Failed to commit allocation of unallocated network %s", n.ID)
+ continue
+ }
+ delete(nc.unallocatedNetworks, n.ID)
+ }
+ return nil
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Error("Failed to commit allocation of unallocated networks")
+ // We optimistically removed these from nc.unallocatedNetworks
+ // above in anticipation of successfully committing the batch,
+ // but since the transaction has failed, we requeue them here.
+ for _, n := range allocatedNetworks {
+ nc.unallocatedNetworks[n.ID] = n
+ }
+ }
+}
+
+func (a *Allocator) procUnallocatedServices(ctx context.Context) {
+ nc := a.netCtx
+ var allocatedServices []*api.Service
+ for _, s := range nc.unallocatedServices {
+ if !nc.nwkAllocator.IsServiceAllocated(s) {
+ if err := a.allocateService(ctx, s); err != nil {
+ log.G(ctx).WithError(err).Debugf("Failed allocation of unallocated service %s", s.ID)
+ continue
+ }
+ allocatedServices = append(allocatedServices, s)
+ }
+ }
+
+ if len(allocatedServices) == 0 {
+ return
+ }
+
+ err := a.store.Batch(func(batch *store.Batch) error {
+ for _, s := range allocatedServices {
+ if err := a.commitAllocatedService(ctx, batch, s); err != nil {
+ log.G(ctx).WithError(err).Debugf("Failed to commit allocation of unallocated service %s", s.ID)
+ continue
+ }
+ delete(nc.unallocatedServices, s.ID)
+ }
+ return nil
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Error("Failed to commit allocation of unallocated services")
+ // We optimistically removed these from nc.unallocatedServices
+ // above in anticipation of successfully committing the batch,
+ // but since the transaction has failed, we requeue them here.
+ for _, s := range allocatedServices {
+ nc.unallocatedServices[s.ID] = s
+ }
+ }
+}
+
+func (a *Allocator) procTasksNetwork(ctx context.Context, onRetry bool) {
+ nc := a.netCtx
+ quiet := false
+ toAllocate := nc.pendingTasks
+ if onRetry {
+ toAllocate = nc.unallocatedTasks
+ quiet = true
+ }
+ allocatedTasks := make([]*api.Task, 0, len(toAllocate))
+
+ for _, t := range toAllocate {
+ if err := a.allocateTask(ctx, t); err == nil {
+ allocatedTasks = append(allocatedTasks, t)
+ } else if err != errNoChanges {
+ if quiet {
+ log.G(ctx).WithError(err).Debug("task allocation failure")
+ } else {
+ log.G(ctx).WithError(err).Error("task allocation failure")
+ }
+ }
+ }
+
+ if len(allocatedTasks) == 0 {
+ return
+ }
+
+ err := a.store.Batch(func(batch *store.Batch) error {
+ for _, t := range allocatedTasks {
+ err := a.commitAllocatedTask(ctx, batch, t)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("task allocation commit failure")
+ continue
+ }
+ delete(toAllocate, t.ID)
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed a store batch operation while processing tasks")
+ // We optimistically removed these from toAllocate above in
+ // anticipation of successfully committing the batch, but since
+ // the transaction has failed, we requeue them here.
+ for _, t := range allocatedTasks {
+ toAllocate[t.ID] = t
+ }
+ }
+}
+
+// IsBuiltInNetworkDriver returns whether the passed driver is an internal network driver
+func IsBuiltInNetworkDriver(name string) bool {
+ return cnmallocator.IsBuiltInDriver(name)
+}
+
+// PredefinedNetworks returns the list of predefined network structures for a given network model
+func PredefinedNetworks() []networkallocator.PredefinedNetworkData {
+ return cnmallocator.PredefinedNetworks()
+}
+
+// updateTaskStatus sets TaskStatus and updates timestamp.
+func updateTaskStatus(t *api.Task, newStatus api.TaskState, message string) {
+ t.Status.State = newStatus
+ t.Status.Message = message
+ t.Status.Timestamp = ptypes.MustTimestampProto(time.Now())
+}
+
+// IsIngressNetwork returns whether the passed network is an ingress network.
+func IsIngressNetwork(nw *api.Network) bool {
+ return networkallocator.IsIngressNetwork(nw)
+}
+
+// GetIngressNetwork fetches the ingress network from store.
+// ErrNoIngress will be returned if the ingress network is not present,
+// nil otherwise. In case of any other failure in accessing the store,
+// the respective error will be reported as is.
+func GetIngressNetwork(s *store.MemoryStore) (*api.Network, error) {
+ var (
+ networks []*api.Network
+ err error
+ )
+ s.View(func(tx store.ReadTx) {
+ networks, err = store.FindNetworks(tx, store.All)
+ })
+ if err != nil {
+ return nil, err
+ }
+ for _, n := range networks {
+ if IsIngressNetwork(n) {
+ return n, nil
+ }
+ }
+ return nil, ErrNoIngress
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/allocator/networkallocator/networkallocator.go b/vendor/github.com/docker/swarmkit/manager/allocator/networkallocator/networkallocator.go
new file mode 100644
index 0000000..04dd168
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/allocator/networkallocator/networkallocator.go
@@ -0,0 +1,132 @@
+package networkallocator
+
+import (
+ "github.com/docker/swarmkit/api"
+)
+
+const (
+ // PredefinedLabel identifies internally allocated swarm networks
+ // corresponding to the node-local predefined networks on the host.
+ PredefinedLabel = "com.docker.swarm.predefined"
+)
+
+// PredefinedNetworkData contains the minimum set of data needed
+// to create the correspondent predefined network object in the store.
+type PredefinedNetworkData struct {
+ Name string
+ Driver string
+}
+
+// ServiceAllocationOpts is struct used for functional options in
+// IsServiceAllocated
+type ServiceAllocationOpts struct {
+ OnInit bool
+}
+
+// OnInit is called for allocator initialization stage
+func OnInit(options *ServiceAllocationOpts) {
+ options.OnInit = true
+}
+
+// NetworkAllocator provides network model specific allocation functionality.
+type NetworkAllocator interface {
+ //
+ // Network Allocation
+ //
+
+ // IsAllocated returns if the passed network has been allocated or not.
+ IsAllocated(n *api.Network) bool
+
+ // Allocate allocates all the necessary resources both general
+ // and driver-specific which may be specified in the NetworkSpec
+ Allocate(n *api.Network) error
+
+ // Deallocate frees all the general and driver specific resources
+ // which were assigned to the passed network.
+ Deallocate(n *api.Network) error
+
+ //
+ // Service Allocation
+ //
+
+ // IsServiceAllocated returns false if the passed service
+ // needs to have network resources allocated/updated.
+ IsServiceAllocated(s *api.Service, flags ...func(*ServiceAllocationOpts)) bool
+
+ // AllocateService allocates all the network resources such as virtual
+ // IP and ports needed by the service.
+ AllocateService(s *api.Service) (err error)
+
+ // DeallocateService de-allocates all the network resources such as
+ // virtual IP and ports associated with the service.
+ DeallocateService(s *api.Service) error
+
+ // HostPublishPortsNeedUpdate returns true if the passed service needs
+ // allocations for its published ports in host (non ingress) mode
+ HostPublishPortsNeedUpdate(s *api.Service) bool
+
+ //
+ // Node Allocation
+ //
+
+ // IsNodeAllocated returns if the passed node has its network
+ // resources allocated or not.
+ IsNodeAllocated(node *api.Node) bool
+
+ // AllocateNode allocates the IP addresses for the network to which
+ // the node is attached.
+ AllocateNode(node *api.Node) error
+
+ // DeallocateNode deallocates the IP addresses for the network to
+ // which the node is attached.
+ DeallocateNode(node *api.Node) error
+
+ //
+ // Task Allocation
+ //
+
+ // IsTaskAllocated returns if the passed task has its network
+ // resources allocated or not.
+ IsTaskAllocated(t *api.Task) bool
+
+ // AllocateTask allocates all the endpoint resources for all the
+ // networks that a task is attached to.
+ AllocateTask(t *api.Task) error
+
+ // DeallocateTask releases all the endpoint resources for all the
+ // networks that a task is attached to.
+ DeallocateTask(t *api.Task) error
+}
+
+// IsIngressNetwork check if the network is an ingress network
+func IsIngressNetwork(nw *api.Network) bool {
+ if nw.Spec.Ingress {
+ return true
+ }
+ // Check if legacy defined ingress network
+ _, ok := nw.Spec.Annotations.Labels["com.docker.swarm.internal"]
+ return ok && nw.Spec.Annotations.Name == "ingress"
+}
+
+// IsIngressNetworkNeeded checks whether the service requires the routing-mesh
+func IsIngressNetworkNeeded(s *api.Service) bool {
+ if s == nil {
+ return false
+ }
+
+ if s.Spec.Endpoint == nil {
+ return false
+ }
+
+ for _, p := range s.Spec.Endpoint.Ports {
+ // The service to which this task belongs is trying to
+ // expose ports with PublishMode as Ingress to the
+ // external world. Automatically attach the task to
+ // the ingress network.
+ if p.PublishMode == api.PublishModeIngress {
+ return true
+ }
+ }
+
+ return false
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/constraint/constraint.go b/vendor/github.com/docker/swarmkit/manager/constraint/constraint.go
new file mode 100644
index 0000000..9f13217
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/constraint/constraint.go
@@ -0,0 +1,207 @@
+package constraint
+
+import (
+ "fmt"
+ "net"
+ "regexp"
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+)
+
+const (
+ eq = iota
+ noteq
+
+ // NodeLabelPrefix is the constraint key prefix for node labels.
+ NodeLabelPrefix = "node.labels."
+ // EngineLabelPrefix is the constraint key prefix for engine labels.
+ EngineLabelPrefix = "engine.labels."
+)
+
+var (
+ alphaNumeric = regexp.MustCompile(`^(?i)[a-z_][a-z0-9\-_.]+$`)
+ // value can be alphanumeric and some special characters. it shouldn't container
+ // current or future operators like '>, <, ~', etc.
+ valuePattern = regexp.MustCompile(`^(?i)[a-z0-9:\-_\s\.\*\(\)\?\+\[\]\\\^\$\|\/]+$`)
+
+ // operators defines list of accepted operators
+ operators = []string{"==", "!="}
+)
+
+// Constraint defines a constraint.
+type Constraint struct {
+ key string
+ operator int
+ exp string
+}
+
+// Parse parses list of constraints.
+func Parse(env []string) ([]Constraint, error) {
+ exprs := []Constraint{}
+ for _, e := range env {
+ found := false
+ // each expr is in the form of "key op value"
+ for i, op := range operators {
+ if !strings.Contains(e, op) {
+ continue
+ }
+ // split with the op
+ parts := strings.SplitN(e, op, 2)
+
+ if len(parts) < 2 {
+ return nil, fmt.Errorf("invalid expr: %s", e)
+ }
+
+ part0 := strings.TrimSpace(parts[0])
+ // validate key
+ matched := alphaNumeric.MatchString(part0)
+ if matched == false {
+ return nil, fmt.Errorf("key '%s' is invalid", part0)
+ }
+
+ part1 := strings.TrimSpace(parts[1])
+
+ // validate Value
+ matched = valuePattern.MatchString(part1)
+ if matched == false {
+ return nil, fmt.Errorf("value '%s' is invalid", part1)
+ }
+ // TODO(dongluochen): revisit requirements to see if globing or regex are useful
+ exprs = append(exprs, Constraint{key: part0, operator: i, exp: part1})
+
+ found = true
+ break // found an op, move to next entry
+ }
+ if !found {
+ return nil, fmt.Errorf("constraint expected one operator from %s", strings.Join(operators, ", "))
+ }
+ }
+ return exprs, nil
+}
+
+// Match checks if the Constraint matches the target strings.
+func (c *Constraint) Match(whats ...string) bool {
+ var match bool
+
+ // full string match
+ for _, what := range whats {
+ // case insensitive compare
+ if strings.EqualFold(c.exp, what) {
+ match = true
+ break
+ }
+ }
+
+ switch c.operator {
+ case eq:
+ return match
+ case noteq:
+ return !match
+ }
+
+ return false
+}
+
+// NodeMatches returns true if the node satisfies the given constraints.
+func NodeMatches(constraints []Constraint, n *api.Node) bool {
+ for _, constraint := range constraints {
+ switch {
+ case strings.EqualFold(constraint.key, "node.id"):
+ if !constraint.Match(n.ID) {
+ return false
+ }
+ case strings.EqualFold(constraint.key, "node.hostname"):
+ // if this node doesn't have hostname
+ // it's equivalent to match an empty hostname
+ // where '==' would fail, '!=' matches
+ if n.Description == nil {
+ if !constraint.Match("") {
+ return false
+ }
+ continue
+ }
+ if !constraint.Match(n.Description.Hostname) {
+ return false
+ }
+ case strings.EqualFold(constraint.key, "node.ip"):
+ nodeIP := net.ParseIP(n.Status.Addr)
+ // single IP address, node.ip == 2001:db8::2
+ if ip := net.ParseIP(constraint.exp); ip != nil {
+ ipEq := ip.Equal(nodeIP)
+ if (ipEq && constraint.operator != eq) || (!ipEq && constraint.operator == eq) {
+ return false
+ }
+ continue
+ }
+ // CIDR subnet, node.ip != 210.8.4.0/24
+ if _, subnet, err := net.ParseCIDR(constraint.exp); err == nil {
+ within := subnet.Contains(nodeIP)
+ if (within && constraint.operator != eq) || (!within && constraint.operator == eq) {
+ return false
+ }
+ continue
+ }
+ // reject constraint with malformed address/network
+ return false
+ case strings.EqualFold(constraint.key, "node.role"):
+ if !constraint.Match(n.Role.String()) {
+ return false
+ }
+ case strings.EqualFold(constraint.key, "node.platform.os"):
+ if n.Description == nil || n.Description.Platform == nil {
+ if !constraint.Match("") {
+ return false
+ }
+ continue
+ }
+ if !constraint.Match(n.Description.Platform.OS) {
+ return false
+ }
+ case strings.EqualFold(constraint.key, "node.platform.arch"):
+ if n.Description == nil || n.Description.Platform == nil {
+ if !constraint.Match("") {
+ return false
+ }
+ continue
+ }
+ if !constraint.Match(n.Description.Platform.Architecture) {
+ return false
+ }
+
+ // node labels constraint in form like 'node.labels.key==value'
+ case len(constraint.key) > len(NodeLabelPrefix) && strings.EqualFold(constraint.key[:len(NodeLabelPrefix)], NodeLabelPrefix):
+ if n.Spec.Annotations.Labels == nil {
+ if !constraint.Match("") {
+ return false
+ }
+ continue
+ }
+ label := constraint.key[len(NodeLabelPrefix):]
+ // label itself is case sensitive
+ val := n.Spec.Annotations.Labels[label]
+ if !constraint.Match(val) {
+ return false
+ }
+
+ // engine labels constraint in form like 'engine.labels.key!=value'
+ case len(constraint.key) > len(EngineLabelPrefix) && strings.EqualFold(constraint.key[:len(EngineLabelPrefix)], EngineLabelPrefix):
+ if n.Description == nil || n.Description.Engine == nil || n.Description.Engine.Labels == nil {
+ if !constraint.Match("") {
+ return false
+ }
+ continue
+ }
+ label := constraint.key[len(EngineLabelPrefix):]
+ val := n.Description.Engine.Labels[label]
+ if !constraint.Match(val) {
+ return false
+ }
+ default:
+ // key doesn't match predefined syntax
+ return false
+ }
+ }
+
+ return true
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/ca_rotation.go b/vendor/github.com/docker/swarmkit/manager/controlapi/ca_rotation.go
new file mode 100644
index 0000000..41e9a4d
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/controlapi/ca_rotation.go
@@ -0,0 +1,282 @@
+package controlapi
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "crypto/x509"
+ "errors"
+ "net"
+ "net/url"
+ "time"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+
+ "github.com/cloudflare/cfssl/helpers"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/ca"
+ "github.com/docker/swarmkit/log"
+)
+
+var minRootExpiration = 1 * helpers.OneYear
+
+// determines whether an api.RootCA, api.RootRotation, or api.CAConfig has a signing key (local signer)
+func hasSigningKey(a interface{}) bool {
+ switch b := a.(type) {
+ case *api.RootCA:
+ return len(b.CAKey) > 0
+ case *api.RootRotation:
+ return b != nil && len(b.CAKey) > 0
+ case *api.CAConfig:
+ return len(b.SigningCACert) > 0 && len(b.SigningCAKey) > 0
+ default:
+ panic("needsExternalCAs should be called something of type *api.RootCA, *api.RootRotation, or *api.CAConfig")
+ }
+}
+
+// Creates a cross-signed intermediate and new api.RootRotation object.
+// This function assumes that the root cert and key and the external CAs have already been validated.
+func newRootRotationObject(ctx context.Context, securityConfig *ca.SecurityConfig, apiRootCA *api.RootCA, newCARootCA ca.RootCA, extCAs []*api.ExternalCA, version uint64) (*api.RootCA, error) {
+ var (
+ rootCert, rootKey, crossSignedCert []byte
+ newRootHasSigner bool
+ err error
+ )
+
+ rootCert = newCARootCA.Certs
+ if s, err := newCARootCA.Signer(); err == nil {
+ rootCert, rootKey = s.Cert, s.Key
+ newRootHasSigner = true
+ }
+
+ // we have to sign with the original signer, not whatever is in the SecurityConfig's RootCA (which may have an intermediate signer, if
+ // a root rotation is already in progress)
+ switch {
+ case hasSigningKey(apiRootCA):
+ var oldRootCA ca.RootCA
+ oldRootCA, err = ca.NewRootCA(apiRootCA.CACert, apiRootCA.CACert, apiRootCA.CAKey, ca.DefaultNodeCertExpiration, nil)
+ if err == nil {
+ crossSignedCert, err = oldRootCA.CrossSignCACertificate(rootCert)
+ }
+ case !newRootHasSigner: // the original CA and the new CA both require external CAs
+ return nil, grpc.Errorf(codes.InvalidArgument, "rotating from one external CA to a different external CA is not supported")
+ default:
+ // We need the same credentials but to connect to the original URLs (in case we are in the middle of a root rotation already)
+ externalCA := securityConfig.ExternalCA().Copy()
+ var urls []string
+ for _, c := range extCAs {
+ if c.Protocol == api.ExternalCA_CAProtocolCFSSL {
+ urls = append(urls, c.URL)
+ }
+ }
+ if len(urls) == 0 {
+ return nil, grpc.Errorf(codes.InvalidArgument,
+ "must provide an external CA for the current external root CA to generate a cross-signed certificate")
+ }
+ externalCA.UpdateURLs(urls...)
+ crossSignedCert, err = externalCA.CrossSignRootCA(ctx, newCARootCA)
+ }
+
+ if err != nil {
+ log.G(ctx).WithError(err).Error("unable to generate a cross-signed certificate for root rotation")
+ return nil, grpc.Errorf(codes.Internal, "unable to generate a cross-signed certificate for root rotation")
+ }
+
+ copied := apiRootCA.Copy()
+ copied.RootRotation = &api.RootRotation{
+ CACert: rootCert,
+ CAKey: rootKey,
+ CrossSignedCACert: ca.NormalizePEMs(crossSignedCert),
+ }
+ copied.LastForcedRotation = version
+ return copied, nil
+}
+
+// Checks that a CA URL is connectable using the credentials we have and that its server certificate is signed by the
+// root CA that we expect. This uses a TCP dialer rather than an HTTP client; because we have custom TLS configuration,
+// if we wanted to use an HTTP client we'd have to create a new transport for every connection. The docs specify that
+// Transports cache connections for future re-use, which could cause many open connections.
+func validateExternalCAURL(dialer *net.Dialer, tlsOpts *tls.Config, caURL string) error {
+ parsed, err := url.Parse(caURL)
+ if err != nil {
+ return err
+ }
+ if parsed.Scheme != "https" {
+ return errors.New("invalid HTTP scheme")
+ }
+ host, port, err := net.SplitHostPort(parsed.Host)
+ if err != nil {
+ // It either has no port or is otherwise invalid (e.g. too many colons). If it's otherwise invalid the dialer
+ // will error later, so just assume it's no port and set the port to the default HTTPS port.
+ host = parsed.Host
+ port = "443"
+ }
+
+ conn, err := tls.DialWithDialer(dialer, "tcp", net.JoinHostPort(host, port), tlsOpts)
+ if conn != nil {
+ conn.Close()
+ }
+ return err
+}
+
+// Validates that there is at least 1 reachable, valid external CA for the given CA certificate. Returns true if there is, false otherwise.
+// Requires that the wanted cert is already normalized.
+func validateHasAtLeastOneExternalCA(ctx context.Context, externalCAs map[string][]*api.ExternalCA, securityConfig *ca.SecurityConfig,
+ wantedCert []byte, desc string) ([]*api.ExternalCA, error) {
+ specific, ok := externalCAs[string(wantedCert)]
+ if ok {
+ pool := x509.NewCertPool()
+ pool.AppendCertsFromPEM(wantedCert)
+ dialer := net.Dialer{Timeout: 5 * time.Second}
+ opts := tls.Config{
+ RootCAs: pool,
+ Certificates: securityConfig.ClientTLSCreds.Config().Certificates,
+ }
+ for i, ca := range specific {
+ if ca.Protocol == api.ExternalCA_CAProtocolCFSSL {
+ if err := validateExternalCAURL(&dialer, &opts, ca.URL); err != nil {
+ log.G(ctx).WithError(err).Warnf("external CA # %d is unreachable or invalid", i+1)
+ } else {
+ return specific, nil
+ }
+ }
+ }
+ }
+ return nil, grpc.Errorf(codes.InvalidArgument, "there must be at least one valid, reachable external CA corresponding to the %s CA certificate", desc)
+}
+
+// validates that the list of external CAs have valid certs associated with them, and produce a mapping of subject/pubkey:external
+// for later validation of required external CAs
+func getNormalizedExtCAs(caConfig *api.CAConfig, normalizedCurrentRootCACert []byte) (map[string][]*api.ExternalCA, error) {
+ extCAs := make(map[string][]*api.ExternalCA)
+
+ for _, extCA := range caConfig.ExternalCAs {
+ associatedCert := normalizedCurrentRootCACert
+ // if no associated cert is provided, assume it's the current root cert
+ if len(extCA.CACert) > 0 {
+ associatedCert = ca.NormalizePEMs(extCA.CACert)
+ }
+ certKey := string(associatedCert)
+ extCAs[certKey] = append(extCAs[certKey], extCA)
+ }
+
+ return extCAs, nil
+}
+
+// validateAndUpdateCA validates a cluster's desired CA configuration spec, and returns a RootCA value on success representing
+// current RootCA as it should be. Validation logic and return values are as follows:
+// 1. Validates that the contents are complete - e.g. a signing key is not provided without a signing cert, and that external
+// CAs are not removed if they are needed. Otherwise, returns an error.
+// 2. If no desired signing cert or key are provided, then either:
+// - we are happy with the current CA configuration (force rotation value has not changed), and we return the current RootCA
+// object as is
+// - we want to generate a new internal CA cert and key (force rotation value has changed), and we return the updated RootCA
+// object
+// 3. Signing cert and key have been provided: validate that these match (the cert and key match). Otherwise, return an error.
+// 4. Return the updated RootCA object according to the following criteria:
+// - If the desired cert is the same as the current CA cert then abort any outstanding rotations. The current signing key
+// is replaced with the desired signing key (this could lets us switch between external->internal or internal->external
+// without an actual CA rotation, which is not needed because any leaf cert issued with one CA cert can be validated using
+// the second CA certificate).
+// - If the desired cert is the same as the current to-be-rotated-to CA cert then a new root rotation is not needed. The
+// current to-be-rotated-to signing key is replaced with the desired signing key (this could lets us switch between
+// external->internal or internal->external without an actual CA rotation, which is not needed because any leaf cert
+// issued with one CA cert can be validated using the second CA certificate).
+// - Otherwise, start a new root rotation using the desired signing cert and desired signing key as the root rotation
+// signing cert and key. If a root rotation is already in progress, just replace it and start over.
+func validateCAConfig(ctx context.Context, securityConfig *ca.SecurityConfig, cluster *api.Cluster) (*api.RootCA, error) {
+ newConfig := cluster.Spec.CAConfig.Copy()
+ newConfig.SigningCACert = ca.NormalizePEMs(newConfig.SigningCACert) // ensure this is normalized before we use it
+
+ if len(newConfig.SigningCAKey) > 0 && len(newConfig.SigningCACert) == 0 {
+ return nil, grpc.Errorf(codes.InvalidArgument, "if a signing CA key is provided, the signing CA cert must also be provided")
+ }
+
+ normalizedRootCA := ca.NormalizePEMs(cluster.RootCA.CACert)
+ extCAs, err := getNormalizedExtCAs(newConfig, normalizedRootCA) // validate that the list of external CAs is not malformed
+ if err != nil {
+ return nil, err
+ }
+
+ var oldCertExtCAs []*api.ExternalCA
+ if !hasSigningKey(&cluster.RootCA) {
+ oldCertExtCAs, err = validateHasAtLeastOneExternalCA(ctx, extCAs, securityConfig, normalizedRootCA, "current")
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ // if the desired CA cert and key are not set, then we are happy with the current root CA configuration, unless
+ // the ForceRotate version has changed
+ if len(newConfig.SigningCACert) == 0 {
+ if cluster.RootCA.LastForcedRotation != newConfig.ForceRotate {
+ newRootCA, err := ca.CreateRootCA(ca.DefaultRootCN)
+ if err != nil {
+ return nil, grpc.Errorf(codes.Internal, err.Error())
+ }
+ return newRootRotationObject(ctx, securityConfig, &cluster.RootCA, newRootCA, oldCertExtCAs, newConfig.ForceRotate)
+ }
+
+ // we also need to make sure that if the current root rotation requires an external CA, those external CAs are
+ // still valid
+ if cluster.RootCA.RootRotation != nil && !hasSigningKey(cluster.RootCA.RootRotation) {
+ _, err := validateHasAtLeastOneExternalCA(ctx, extCAs, securityConfig, ca.NormalizePEMs(cluster.RootCA.RootRotation.CACert), "next")
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ return &cluster.RootCA, nil // no change, return as is
+ }
+
+ // A desired cert and maybe key were provided - we need to make sure the cert and key (if provided) match.
+ var signingCert []byte
+ if hasSigningKey(newConfig) {
+ signingCert = newConfig.SigningCACert
+ }
+ newRootCA, err := ca.NewRootCA(newConfig.SigningCACert, signingCert, newConfig.SigningCAKey, ca.DefaultNodeCertExpiration, nil)
+ if err != nil {
+ return nil, grpc.Errorf(codes.InvalidArgument, err.Error())
+ }
+
+ if len(newRootCA.Pool.Subjects()) != 1 {
+ return nil, grpc.Errorf(codes.InvalidArgument, "the desired CA certificate cannot contain multiple certificates")
+ }
+
+ parsedCert, err := helpers.ParseCertificatePEM(newConfig.SigningCACert)
+ if err != nil {
+ return nil, grpc.Errorf(codes.InvalidArgument, "could not parse the desired CA certificate")
+ }
+
+ // The new certificate's expiry must be at least one year away
+ if parsedCert.NotAfter.Before(time.Now().Add(minRootExpiration)) {
+ return nil, grpc.Errorf(codes.InvalidArgument, "CA certificate expires too soon")
+ }
+
+ if !hasSigningKey(newConfig) {
+ if _, err := validateHasAtLeastOneExternalCA(ctx, extCAs, securityConfig, newConfig.SigningCACert, "desired"); err != nil {
+ return nil, err
+ }
+ }
+
+ // check if we can abort any existing root rotations
+ if bytes.Equal(normalizedRootCA, newConfig.SigningCACert) {
+ copied := cluster.RootCA.Copy()
+ copied.CAKey = newConfig.SigningCAKey
+ copied.RootRotation = nil
+ copied.LastForcedRotation = newConfig.ForceRotate
+ return copied, nil
+ }
+
+ // check if this is the same desired cert as an existing root rotation
+ if r := cluster.RootCA.RootRotation; r != nil && bytes.Equal(ca.NormalizePEMs(r.CACert), newConfig.SigningCACert) {
+ copied := cluster.RootCA.Copy()
+ copied.RootRotation.CAKey = newConfig.SigningCAKey
+ copied.LastForcedRotation = newConfig.ForceRotate
+ return copied, nil
+ }
+
+ // ok, everything's different; we have to begin a new root rotation which means generating a new cross-signed cert
+ return newRootRotationObject(ctx, securityConfig, &cluster.RootCA, newRootCA, oldCertExtCAs, newConfig.ForceRotate)
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/cluster.go b/vendor/github.com/docker/swarmkit/manager/controlapi/cluster.go
new file mode 100644
index 0000000..7e9dea2
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/controlapi/cluster.go
@@ -0,0 +1,287 @@
+package controlapi
+
+import (
+ "strings"
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/ca"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/encryption"
+ "github.com/docker/swarmkit/manager/state/store"
+ gogotypes "github.com/gogo/protobuf/types"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+const (
+ // expiredCertGrace is the amount of time to keep a node in the
+ // blacklist beyond its certificate expiration timestamp.
+ expiredCertGrace = 24 * time.Hour * 7
+)
+
+func validateClusterSpec(spec *api.ClusterSpec) error {
+ if spec == nil {
+ return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ // Validate that expiry time being provided is valid, and over our minimum
+ if spec.CAConfig.NodeCertExpiry != nil {
+ expiry, err := gogotypes.DurationFromProto(spec.CAConfig.NodeCertExpiry)
+ if err != nil {
+ return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+ if expiry < ca.MinNodeCertExpiration {
+ return grpc.Errorf(codes.InvalidArgument, "minimum certificate expiry time is: %s", ca.MinNodeCertExpiration)
+ }
+ }
+
+ // Validate that AcceptancePolicies only include Secrets that are bcrypted
+ // TODO(diogo): Add a global list of acceptance algorithms. We only support bcrypt for now.
+ if len(spec.AcceptancePolicy.Policies) > 0 {
+ for _, policy := range spec.AcceptancePolicy.Policies {
+ if policy.Secret != nil && strings.ToLower(policy.Secret.Alg) != "bcrypt" {
+ return grpc.Errorf(codes.InvalidArgument, "hashing algorithm is not supported: %s", policy.Secret.Alg)
+ }
+ }
+ }
+
+ // Validate that heartbeatPeriod time being provided is valid
+ if spec.Dispatcher.HeartbeatPeriod != nil {
+ heartbeatPeriod, err := gogotypes.DurationFromProto(spec.Dispatcher.HeartbeatPeriod)
+ if err != nil {
+ return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+ if heartbeatPeriod < 0 {
+ return grpc.Errorf(codes.InvalidArgument, "heartbeat time period cannot be a negative duration")
+ }
+ }
+
+ return nil
+}
+
+// GetCluster returns a Cluster given a ClusterID.
+// - Returns `InvalidArgument` if ClusterID is not provided.
+// - Returns `NotFound` if the Cluster is not found.
+func (s *Server) GetCluster(ctx context.Context, request *api.GetClusterRequest) (*api.GetClusterResponse, error) {
+ if request.ClusterID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ var cluster *api.Cluster
+ s.store.View(func(tx store.ReadTx) {
+ cluster = store.GetCluster(tx, request.ClusterID)
+ })
+ if cluster == nil {
+ return nil, grpc.Errorf(codes.NotFound, "cluster %s not found", request.ClusterID)
+ }
+
+ redactedClusters := redactClusters([]*api.Cluster{cluster})
+
+ // WARN: we should never return cluster here. We need to redact the private fields first.
+ return &api.GetClusterResponse{
+ Cluster: redactedClusters[0],
+ }, nil
+}
+
+// UpdateCluster updates a Cluster referenced by ClusterID with the given ClusterSpec.
+// - Returns `NotFound` if the Cluster is not found.
+// - Returns `InvalidArgument` if the ClusterSpec is malformed.
+// - Returns `Unimplemented` if the ClusterSpec references unimplemented features.
+// - Returns an error if the update fails.
+func (s *Server) UpdateCluster(ctx context.Context, request *api.UpdateClusterRequest) (*api.UpdateClusterResponse, error) {
+ if request.ClusterID == "" || request.ClusterVersion == nil {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+ if err := validateClusterSpec(request.Spec); err != nil {
+ return nil, err
+ }
+
+ var cluster *api.Cluster
+ err := s.store.Update(func(tx store.Tx) error {
+ cluster = store.GetCluster(tx, request.ClusterID)
+ if cluster == nil {
+ return grpc.Errorf(codes.NotFound, "cluster %s not found", request.ClusterID)
+ }
+ // This ensures that we always have the latest security config, so our ca.SecurityConfig.RootCA and
+ // ca.SecurityConfig.externalCA objects are up-to-date with the current api.Cluster.RootCA and
+ // api.Cluster.Spec.ExternalCA objects, respectively. Note that if, during this update, the cluster gets
+ // updated again with different CA info and the security config gets changed under us, that's still fine because
+ // this cluster update would fail anyway due to its version being too low on write.
+ if err := s.scu.UpdateRootCA(ctx, cluster); err != nil {
+ log.G(ctx).WithField(
+ "method", "(*controlapi.Server).UpdateCluster").WithError(err).Error("could not update security config")
+ return grpc.Errorf(codes.Internal, "could not update security config")
+ }
+ rootCA := s.securityConfig.RootCA()
+
+ cluster.Meta.Version = *request.ClusterVersion
+ cluster.Spec = *request.Spec.Copy()
+
+ expireBlacklistedCerts(cluster)
+
+ if request.Rotation.WorkerJoinToken {
+ cluster.RootCA.JoinTokens.Worker = ca.GenerateJoinToken(rootCA)
+ }
+ if request.Rotation.ManagerJoinToken {
+ cluster.RootCA.JoinTokens.Manager = ca.GenerateJoinToken(rootCA)
+ }
+
+ updatedRootCA, err := validateCAConfig(ctx, s.securityConfig, cluster)
+ if err != nil {
+ return err
+ }
+ cluster.RootCA = *updatedRootCA
+
+ var unlockKeys []*api.EncryptionKey
+ var managerKey *api.EncryptionKey
+ for _, eKey := range cluster.UnlockKeys {
+ if eKey.Subsystem == ca.ManagerRole {
+ if !cluster.Spec.EncryptionConfig.AutoLockManagers {
+ continue
+ }
+ managerKey = eKey
+ }
+ unlockKeys = append(unlockKeys, eKey)
+ }
+
+ switch {
+ case !cluster.Spec.EncryptionConfig.AutoLockManagers:
+ break
+ case managerKey == nil:
+ unlockKeys = append(unlockKeys, &api.EncryptionKey{
+ Subsystem: ca.ManagerRole,
+ Key: encryption.GenerateSecretKey(),
+ })
+ case request.Rotation.ManagerUnlockKey:
+ managerKey.Key = encryption.GenerateSecretKey()
+ }
+ cluster.UnlockKeys = unlockKeys
+
+ return store.UpdateCluster(tx, cluster)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ redactedClusters := redactClusters([]*api.Cluster{cluster})
+
+ // WARN: we should never return cluster here. We need to redact the private fields first.
+ return &api.UpdateClusterResponse{
+ Cluster: redactedClusters[0],
+ }, nil
+}
+
+func filterClusters(candidates []*api.Cluster, filters ...func(*api.Cluster) bool) []*api.Cluster {
+ result := []*api.Cluster{}
+
+ for _, c := range candidates {
+ match := true
+ for _, f := range filters {
+ if !f(c) {
+ match = false
+ break
+ }
+ }
+ if match {
+ result = append(result, c)
+ }
+ }
+
+ return result
+}
+
+// ListClusters returns a list of all clusters.
+func (s *Server) ListClusters(ctx context.Context, request *api.ListClustersRequest) (*api.ListClustersResponse, error) {
+ var (
+ clusters []*api.Cluster
+ err error
+ )
+ s.store.View(func(tx store.ReadTx) {
+ switch {
+ case request.Filters != nil && len(request.Filters.Names) > 0:
+ clusters, err = store.FindClusters(tx, buildFilters(store.ByName, request.Filters.Names))
+ case request.Filters != nil && len(request.Filters.NamePrefixes) > 0:
+ clusters, err = store.FindClusters(tx, buildFilters(store.ByNamePrefix, request.Filters.NamePrefixes))
+ case request.Filters != nil && len(request.Filters.IDPrefixes) > 0:
+ clusters, err = store.FindClusters(tx, buildFilters(store.ByIDPrefix, request.Filters.IDPrefixes))
+ default:
+ clusters, err = store.FindClusters(tx, store.All)
+ }
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ if request.Filters != nil {
+ clusters = filterClusters(clusters,
+ func(e *api.Cluster) bool {
+ return filterContains(e.Spec.Annotations.Name, request.Filters.Names)
+ },
+ func(e *api.Cluster) bool {
+ return filterContainsPrefix(e.Spec.Annotations.Name, request.Filters.NamePrefixes)
+ },
+ func(e *api.Cluster) bool {
+ return filterContainsPrefix(e.ID, request.Filters.IDPrefixes)
+ },
+ func(e *api.Cluster) bool {
+ return filterMatchLabels(e.Spec.Annotations.Labels, request.Filters.Labels)
+ },
+ )
+ }
+
+ // WARN: we should never return cluster here. We need to redact the private fields first.
+ return &api.ListClustersResponse{
+ Clusters: redactClusters(clusters),
+ }, nil
+}
+
+// redactClusters is a method that enforces a whitelist of fields that are ok to be
+// returned in the Cluster object. It should filter out all sensitive information.
+func redactClusters(clusters []*api.Cluster) []*api.Cluster {
+ var redactedClusters []*api.Cluster
+ // Only add public fields to the new clusters
+ for _, cluster := range clusters {
+ // Copy all the mandatory fields
+ // Do not copy secret keys
+ redactedSpec := cluster.Spec.Copy()
+ redactedSpec.CAConfig.SigningCAKey = nil
+ // the cert is not a secret, but if API users get the cluster spec and then update,
+ // then because the cert is included but not the key, the user can get update errors
+ // or unintended consequences (such as telling swarm to forget about the key so long
+ // as there is a corresponding external CA)
+ redactedSpec.CAConfig.SigningCACert = nil
+
+ redactedRootCA := cluster.RootCA.Copy()
+ redactedRootCA.CAKey = nil
+ if r := redactedRootCA.RootRotation; r != nil {
+ r.CAKey = nil
+ }
+ newCluster := &api.Cluster{
+ ID: cluster.ID,
+ Meta: cluster.Meta,
+ Spec: *redactedSpec,
+ RootCA: *redactedRootCA,
+ BlacklistedCertificates: cluster.BlacklistedCertificates,
+ }
+ redactedClusters = append(redactedClusters, newCluster)
+ }
+
+ return redactedClusters
+}
+
+func expireBlacklistedCerts(cluster *api.Cluster) {
+ nowMinusGrace := time.Now().Add(-expiredCertGrace)
+
+ for cn, blacklistedCert := range cluster.BlacklistedCertificates {
+ if blacklistedCert.Expiry == nil {
+ continue
+ }
+
+ expiry, err := gogotypes.TimestampFromProto(blacklistedCert.Expiry)
+ if err == nil && nowMinusGrace.After(expiry) {
+ delete(cluster.BlacklistedCertificates, cn)
+ }
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/common.go b/vendor/github.com/docker/swarmkit/manager/controlapi/common.go
new file mode 100644
index 0000000..c016623
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/controlapi/common.go
@@ -0,0 +1,135 @@
+package controlapi
+
+import (
+ "regexp"
+ "strings"
+
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/allocator"
+ "github.com/docker/swarmkit/manager/state/store"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+var isValidDNSName = regexp.MustCompile(`^[a-zA-Z0-9](?:[-_]*[A-Za-z0-9]+)*$`)
+
+// configs and secrets have different naming requirements from tasks and services
+var isValidConfigOrSecretName = regexp.MustCompile(`^[a-zA-Z0-9]+(?:[a-zA-Z0-9-_.]*[a-zA-Z0-9])?$`)
+
+func buildFilters(by func(string) store.By, values []string) store.By {
+ filters := make([]store.By, 0, len(values))
+ for _, v := range values {
+ filters = append(filters, by(v))
+ }
+ return store.Or(filters...)
+}
+
+func filterContains(match string, candidates []string) bool {
+ if len(candidates) == 0 {
+ return true
+ }
+ for _, c := range candidates {
+ if c == match {
+ return true
+ }
+ }
+ return false
+}
+
+func filterContainsPrefix(match string, candidates []string) bool {
+ if len(candidates) == 0 {
+ return true
+ }
+ for _, c := range candidates {
+ if strings.HasPrefix(match, c) {
+ return true
+ }
+ }
+ return false
+}
+
+func filterMatchLabels(match map[string]string, candidates map[string]string) bool {
+ if len(candidates) == 0 {
+ return true
+ }
+
+ for k, v := range candidates {
+ c, ok := match[k]
+ if !ok {
+ return false
+ }
+ if v != "" && v != c {
+ return false
+ }
+ }
+ return true
+}
+
+func validateAnnotations(m api.Annotations) error {
+ if m.Name == "" {
+ return grpc.Errorf(codes.InvalidArgument, "meta: name must be provided")
+ }
+ if !isValidDNSName.MatchString(m.Name) {
+ // if the name doesn't match the regex
+ return grpc.Errorf(codes.InvalidArgument, "name must be valid as a DNS name component")
+ }
+ if len(m.Name) > 63 {
+ // DNS labels are limited to 63 characters
+ return grpc.Errorf(codes.InvalidArgument, "name must be 63 characters or fewer")
+ }
+ return nil
+}
+
+func validateConfigOrSecretAnnotations(m api.Annotations) error {
+ if m.Name == "" {
+ return grpc.Errorf(codes.InvalidArgument, "name must be provided")
+ } else if len(m.Name) > 64 || !isValidConfigOrSecretName.MatchString(m.Name) {
+ // if the name doesn't match the regex
+ return grpc.Errorf(codes.InvalidArgument,
+ "invalid name, only 64 [a-zA-Z0-9-_.] characters allowed, and the start and end character must be [a-zA-Z0-9]")
+ }
+ return nil
+}
+
+func validateDriver(driver *api.Driver, pg plugingetter.PluginGetter, pluginType string) error {
+ if driver == nil {
+ // It is ok to not specify the driver. We will choose
+ // a default driver.
+ return nil
+ }
+
+ if driver.Name == "" {
+ return grpc.Errorf(codes.InvalidArgument, "driver name: if driver is specified name is required")
+ }
+
+ // First check against the known drivers
+ switch pluginType {
+ case ipamapi.PluginEndpointType:
+ if strings.ToLower(driver.Name) == ipamapi.DefaultIPAM {
+ return nil
+ }
+ case driverapi.NetworkPluginEndpointType:
+ if allocator.IsBuiltInNetworkDriver(driver.Name) {
+ return nil
+ }
+ default:
+ }
+
+ if pg == nil {
+ return grpc.Errorf(codes.InvalidArgument, "plugin %s not supported", driver.Name)
+ }
+
+ p, err := pg.Get(driver.Name, pluginType, plugingetter.Lookup)
+ if err != nil {
+ return grpc.Errorf(codes.InvalidArgument, "error during lookup of plugin %s", driver.Name)
+ }
+
+ if p.IsV1() {
+ return grpc.Errorf(codes.InvalidArgument, "legacy plugin %s of type %s is not supported in swarm mode", driver.Name, pluginType)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/config.go b/vendor/github.com/docker/swarmkit/manager/controlapi/config.go
new file mode 100644
index 0000000..3a6f6a1
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/controlapi/config.go
@@ -0,0 +1,248 @@
+package controlapi
+
+import (
+ "bytes"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+// MaxConfigSize is the maximum byte length of the `Config.Spec.Data` field.
+const MaxConfigSize = 500 * 1024 // 500KB
+
+// assumes spec is not nil
+func configFromConfigSpec(spec *api.ConfigSpec) *api.Config {
+ return &api.Config{
+ ID: identity.NewID(),
+ Spec: *spec,
+ }
+}
+
+// GetConfig returns a `GetConfigResponse` with a `Config` with the same
+// id as `GetConfigRequest.ConfigID`
+// - Returns `NotFound` if the Config with the given id is not found.
+// - Returns `InvalidArgument` if the `GetConfigRequest.ConfigID` is empty.
+// - Returns an error if getting fails.
+func (s *Server) GetConfig(ctx context.Context, request *api.GetConfigRequest) (*api.GetConfigResponse, error) {
+ if request.ConfigID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, "config ID must be provided")
+ }
+
+ var config *api.Config
+ s.store.View(func(tx store.ReadTx) {
+ config = store.GetConfig(tx, request.ConfigID)
+ })
+
+ if config == nil {
+ return nil, grpc.Errorf(codes.NotFound, "config %s not found", request.ConfigID)
+ }
+
+ return &api.GetConfigResponse{Config: config}, nil
+}
+
+// UpdateConfig updates a Config referenced by ConfigID with the given ConfigSpec.
+// - Returns `NotFound` if the Config is not found.
+// - Returns `InvalidArgument` if the ConfigSpec is malformed or anything other than Labels is changed
+// - Returns an error if the update fails.
+func (s *Server) UpdateConfig(ctx context.Context, request *api.UpdateConfigRequest) (*api.UpdateConfigResponse, error) {
+ if request.ConfigID == "" || request.ConfigVersion == nil {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ var config *api.Config
+ err := s.store.Update(func(tx store.Tx) error {
+ config = store.GetConfig(tx, request.ConfigID)
+ if config == nil {
+ return grpc.Errorf(codes.NotFound, "config %s not found", request.ConfigID)
+ }
+
+ // Check if the Name is different than the current name, or the config is non-nil and different
+ // than the current config
+ if config.Spec.Annotations.Name != request.Spec.Annotations.Name ||
+ (request.Spec.Data != nil && !bytes.Equal(request.Spec.Data, config.Spec.Data)) {
+ return grpc.Errorf(codes.InvalidArgument, "only updates to Labels are allowed")
+ }
+
+ // We only allow updating Labels
+ config.Meta.Version = *request.ConfigVersion
+ config.Spec.Annotations.Labels = request.Spec.Annotations.Labels
+
+ return store.UpdateConfig(tx, config)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "config.ID": request.ConfigID,
+ "config.Name": request.Spec.Annotations.Name,
+ "method": "UpdateConfig",
+ }).Debugf("config updated")
+
+ return &api.UpdateConfigResponse{
+ Config: config,
+ }, nil
+}
+
+// ListConfigs returns a `ListConfigResponse` with a list all non-internal `Config`s being
+// managed, or all configs matching any name in `ListConfigsRequest.Names`, any
+// name prefix in `ListConfigsRequest.NamePrefixes`, any id in
+// `ListConfigsRequest.ConfigIDs`, or any id prefix in `ListConfigsRequest.IDPrefixes`.
+// - Returns an error if listing fails.
+func (s *Server) ListConfigs(ctx context.Context, request *api.ListConfigsRequest) (*api.ListConfigsResponse, error) {
+ var (
+ configs []*api.Config
+ respConfigs []*api.Config
+ err error
+ byFilters []store.By
+ by store.By
+ labels map[string]string
+ )
+
+ // return all configs that match either any of the names or any of the name prefixes (why would you give both?)
+ if request.Filters != nil {
+ for _, name := range request.Filters.Names {
+ byFilters = append(byFilters, store.ByName(name))
+ }
+ for _, prefix := range request.Filters.NamePrefixes {
+ byFilters = append(byFilters, store.ByNamePrefix(prefix))
+ }
+ for _, prefix := range request.Filters.IDPrefixes {
+ byFilters = append(byFilters, store.ByIDPrefix(prefix))
+ }
+ labels = request.Filters.Labels
+ }
+
+ switch len(byFilters) {
+ case 0:
+ by = store.All
+ case 1:
+ by = byFilters[0]
+ default:
+ by = store.Or(byFilters...)
+ }
+
+ s.store.View(func(tx store.ReadTx) {
+ configs, err = store.FindConfigs(tx, by)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ // filter by label
+ for _, config := range configs {
+ if !filterMatchLabels(config.Spec.Annotations.Labels, labels) {
+ continue
+ }
+ respConfigs = append(respConfigs, config)
+ }
+
+ return &api.ListConfigsResponse{Configs: respConfigs}, nil
+}
+
+// CreateConfig creates and returns a `CreateConfigResponse` with a `Config` based
+// on the provided `CreateConfigRequest.ConfigSpec`.
+// - Returns `InvalidArgument` if the `CreateConfigRequest.ConfigSpec` is malformed,
+// or if the config data is too long or contains invalid characters.
+// - Returns an error if the creation fails.
+func (s *Server) CreateConfig(ctx context.Context, request *api.CreateConfigRequest) (*api.CreateConfigResponse, error) {
+ if err := validateConfigSpec(request.Spec); err != nil {
+ return nil, err
+ }
+
+ config := configFromConfigSpec(request.Spec) // the store will handle name conflicts
+ err := s.store.Update(func(tx store.Tx) error {
+ return store.CreateConfig(tx, config)
+ })
+
+ switch err {
+ case store.ErrNameConflict:
+ return nil, grpc.Errorf(codes.AlreadyExists, "config %s already exists", request.Spec.Annotations.Name)
+ case nil:
+ log.G(ctx).WithFields(logrus.Fields{
+ "config.Name": request.Spec.Annotations.Name,
+ "method": "CreateConfig",
+ }).Debugf("config created")
+
+ return &api.CreateConfigResponse{Config: config}, nil
+ default:
+ return nil, err
+ }
+}
+
+// RemoveConfig removes the config referenced by `RemoveConfigRequest.ID`.
+// - Returns `InvalidArgument` if `RemoveConfigRequest.ID` is empty.
+// - Returns `NotFound` if the a config named `RemoveConfigRequest.ID` is not found.
+// - Returns `ConfigInUse` if the config is currently in use
+// - Returns an error if the deletion fails.
+func (s *Server) RemoveConfig(ctx context.Context, request *api.RemoveConfigRequest) (*api.RemoveConfigResponse, error) {
+ if request.ConfigID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, "config ID must be provided")
+ }
+
+ err := s.store.Update(func(tx store.Tx) error {
+ // Check if the config exists
+ config := store.GetConfig(tx, request.ConfigID)
+ if config == nil {
+ return grpc.Errorf(codes.NotFound, "could not find config %s", request.ConfigID)
+ }
+
+ // Check if any services currently reference this config, return error if so
+ services, err := store.FindServices(tx, store.ByReferencedConfigID(request.ConfigID))
+ if err != nil {
+ return grpc.Errorf(codes.Internal, "could not find services using config %s: %v", request.ConfigID, err)
+ }
+
+ if len(services) != 0 {
+ serviceNames := make([]string, 0, len(services))
+ for _, service := range services {
+ serviceNames = append(serviceNames, service.Spec.Annotations.Name)
+ }
+
+ configName := config.Spec.Annotations.Name
+ serviceNameStr := strings.Join(serviceNames, ", ")
+ serviceStr := "services"
+ if len(serviceNames) == 1 {
+ serviceStr = "service"
+ }
+
+ return grpc.Errorf(codes.InvalidArgument, "config '%s' is in use by the following %s: %v", configName, serviceStr, serviceNameStr)
+ }
+
+ return store.DeleteConfig(tx, request.ConfigID)
+ })
+ switch err {
+ case store.ErrNotExist:
+ return nil, grpc.Errorf(codes.NotFound, "config %s not found", request.ConfigID)
+ case nil:
+ log.G(ctx).WithFields(logrus.Fields{
+ "config.ID": request.ConfigID,
+ "method": "RemoveConfig",
+ }).Debugf("config removed")
+
+ return &api.RemoveConfigResponse{}, nil
+ default:
+ return nil, err
+ }
+}
+
+func validateConfigSpec(spec *api.ConfigSpec) error {
+ if spec == nil {
+ return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+ if err := validateConfigOrSecretAnnotations(spec.Annotations); err != nil {
+ return err
+ }
+
+ if len(spec.Data) >= MaxConfigSize || len(spec.Data) < 1 {
+ return grpc.Errorf(codes.InvalidArgument, "config data must be larger than 0 and less than %d bytes", MaxConfigSize)
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/network.go b/vendor/github.com/docker/swarmkit/manager/controlapi/network.go
new file mode 100644
index 0000000..708f36b
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/controlapi/network.go
@@ -0,0 +1,302 @@
+package controlapi
+
+import (
+ "net"
+
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/libnetwork/driverapi"
+ "github.com/docker/libnetwork/ipamapi"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/manager/allocator"
+ "github.com/docker/swarmkit/manager/allocator/networkallocator"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+func validateIPAMConfiguration(ipamConf *api.IPAMConfig) error {
+ if ipamConf == nil {
+ return grpc.Errorf(codes.InvalidArgument, "ipam configuration: cannot be empty")
+ }
+
+ _, subnet, err := net.ParseCIDR(ipamConf.Subnet)
+ if err != nil {
+ return grpc.Errorf(codes.InvalidArgument, "ipam configuration: invalid subnet %s", ipamConf.Subnet)
+ }
+
+ if ipamConf.Range != "" {
+ ip, _, err := net.ParseCIDR(ipamConf.Range)
+ if err != nil {
+ return grpc.Errorf(codes.InvalidArgument, "ipam configuration: invalid range %s", ipamConf.Range)
+ }
+
+ if !subnet.Contains(ip) {
+ return grpc.Errorf(codes.InvalidArgument, "ipam configuration: subnet %s does not contain range %s", ipamConf.Subnet, ipamConf.Range)
+ }
+ }
+
+ if ipamConf.Gateway != "" {
+ ip := net.ParseIP(ipamConf.Gateway)
+ if ip == nil {
+ return grpc.Errorf(codes.InvalidArgument, "ipam configuration: invalid gateway %s", ipamConf.Gateway)
+ }
+
+ if !subnet.Contains(ip) {
+ return grpc.Errorf(codes.InvalidArgument, "ipam configuration: subnet %s does not contain gateway %s", ipamConf.Subnet, ipamConf.Gateway)
+ }
+ }
+
+ return nil
+}
+
+func validateIPAM(ipam *api.IPAMOptions, pg plugingetter.PluginGetter) error {
+ if ipam == nil {
+ // It is ok to not specify any IPAM configurations. We
+ // will choose good defaults.
+ return nil
+ }
+
+ if err := validateDriver(ipam.Driver, pg, ipamapi.PluginEndpointType); err != nil {
+ return err
+ }
+
+ for _, ipamConf := range ipam.Configs {
+ if err := validateIPAMConfiguration(ipamConf); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func validateNetworkSpec(spec *api.NetworkSpec, pg plugingetter.PluginGetter) error {
+ if spec == nil {
+ return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ if spec.Ingress && spec.DriverConfig != nil && spec.DriverConfig.Name != "overlay" {
+ return grpc.Errorf(codes.Unimplemented, "only overlay driver is currently supported for ingress network")
+ }
+
+ if spec.Attachable && spec.Ingress {
+ return grpc.Errorf(codes.InvalidArgument, "ingress network cannot be attachable")
+ }
+
+ if err := validateAnnotations(spec.Annotations); err != nil {
+ return err
+ }
+
+ if _, ok := spec.Annotations.Labels[networkallocator.PredefinedLabel]; ok {
+ return grpc.Errorf(codes.PermissionDenied, "label %s is for internally created predefined networks and cannot be applied by users",
+ networkallocator.PredefinedLabel)
+ }
+ if err := validateDriver(spec.DriverConfig, pg, driverapi.NetworkPluginEndpointType); err != nil {
+ return err
+ }
+
+ if err := validateIPAM(spec.IPAM, pg); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// CreateNetwork creates and returns a Network based on the provided NetworkSpec.
+// - Returns `InvalidArgument` if the NetworkSpec is malformed.
+// - Returns an error if the creation fails.
+func (s *Server) CreateNetwork(ctx context.Context, request *api.CreateNetworkRequest) (*api.CreateNetworkResponse, error) {
+ if err := validateNetworkSpec(request.Spec, s.pg); err != nil {
+ return nil, err
+ }
+
+ // TODO(mrjana): Consider using `Name` as a primary key to handle
+ // duplicate creations. See #65
+ n := &api.Network{
+ ID: identity.NewID(),
+ Spec: *request.Spec,
+ }
+
+ err := s.store.Update(func(tx store.Tx) error {
+ if request.Spec.Ingress {
+ if n, err := allocator.GetIngressNetwork(s.store); err == nil {
+ return grpc.Errorf(codes.AlreadyExists, "ingress network (%s) is already present", n.ID)
+ } else if err != allocator.ErrNoIngress {
+ return grpc.Errorf(codes.Internal, "failed ingress network presence check: %v", err)
+ }
+ }
+ return store.CreateNetwork(tx, n)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return &api.CreateNetworkResponse{
+ Network: n,
+ }, nil
+}
+
+// GetNetwork returns a Network given a NetworkID.
+// - Returns `InvalidArgument` if NetworkID is not provided.
+// - Returns `NotFound` if the Network is not found.
+func (s *Server) GetNetwork(ctx context.Context, request *api.GetNetworkRequest) (*api.GetNetworkResponse, error) {
+ if request.NetworkID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ var n *api.Network
+ s.store.View(func(tx store.ReadTx) {
+ n = store.GetNetwork(tx, request.NetworkID)
+ })
+ if n == nil {
+ return nil, grpc.Errorf(codes.NotFound, "network %s not found", request.NetworkID)
+ }
+ return &api.GetNetworkResponse{
+ Network: n,
+ }, nil
+}
+
+// RemoveNetwork removes a Network referenced by NetworkID.
+// - Returns `InvalidArgument` if NetworkID is not provided.
+// - Returns `NotFound` if the Network is not found.
+// - Returns an error if the deletion fails.
+func (s *Server) RemoveNetwork(ctx context.Context, request *api.RemoveNetworkRequest) (*api.RemoveNetworkResponse, error) {
+ if request.NetworkID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ var (
+ n *api.Network
+ rm = s.removeNetwork
+ )
+
+ s.store.View(func(tx store.ReadTx) {
+ n = store.GetNetwork(tx, request.NetworkID)
+ })
+ if n == nil {
+ return nil, grpc.Errorf(codes.NotFound, "network %s not found", request.NetworkID)
+ }
+
+ if allocator.IsIngressNetwork(n) {
+ rm = s.removeIngressNetwork
+ }
+
+ if v, ok := n.Spec.Annotations.Labels[networkallocator.PredefinedLabel]; ok && v == "true" {
+ return nil, grpc.Errorf(codes.FailedPrecondition, "network %s (%s) is a swarm predefined network and cannot be removed",
+ request.NetworkID, n.Spec.Annotations.Name)
+ }
+
+ if err := rm(n.ID); err != nil {
+ if err == store.ErrNotExist {
+ return nil, grpc.Errorf(codes.NotFound, "network %s not found", request.NetworkID)
+ }
+ return nil, err
+ }
+ return &api.RemoveNetworkResponse{}, nil
+}
+
+func (s *Server) removeNetwork(id string) error {
+ return s.store.Update(func(tx store.Tx) error {
+ services, err := store.FindServices(tx, store.ByReferencedNetworkID(id))
+ if err != nil {
+ return grpc.Errorf(codes.Internal, "could not find services using network %s: %v", id, err)
+ }
+
+ if len(services) != 0 {
+ return grpc.Errorf(codes.FailedPrecondition, "network %s is in use by service %s", id, services[0].ID)
+ }
+
+ tasks, err := store.FindTasks(tx, store.ByReferencedNetworkID(id))
+ if err != nil {
+ return grpc.Errorf(codes.Internal, "could not find tasks using network %s: %v", id, err)
+ }
+
+ for _, t := range tasks {
+ if t.DesiredState <= api.TaskStateRunning && t.Status.State <= api.TaskStateRunning {
+ return grpc.Errorf(codes.FailedPrecondition, "network %s is in use by task %s", id, t.ID)
+ }
+ }
+
+ return store.DeleteNetwork(tx, id)
+ })
+}
+
+func (s *Server) removeIngressNetwork(id string) error {
+ return s.store.Update(func(tx store.Tx) error {
+ services, err := store.FindServices(tx, store.All)
+ if err != nil {
+ return grpc.Errorf(codes.Internal, "could not find services using network %s: %v", id, err)
+ }
+ for _, srv := range services {
+ if allocator.IsIngressNetworkNeeded(srv) {
+ return grpc.Errorf(codes.FailedPrecondition, "ingress network cannot be removed because service %s depends on it", srv.ID)
+ }
+ }
+ return store.DeleteNetwork(tx, id)
+ })
+}
+
+func filterNetworks(candidates []*api.Network, filters ...func(*api.Network) bool) []*api.Network {
+ result := []*api.Network{}
+
+ for _, c := range candidates {
+ match := true
+ for _, f := range filters {
+ if !f(c) {
+ match = false
+ break
+ }
+ }
+ if match {
+ result = append(result, c)
+ }
+ }
+
+ return result
+}
+
+// ListNetworks returns a list of all networks.
+func (s *Server) ListNetworks(ctx context.Context, request *api.ListNetworksRequest) (*api.ListNetworksResponse, error) {
+ var (
+ networks []*api.Network
+ err error
+ )
+
+ s.store.View(func(tx store.ReadTx) {
+ switch {
+ case request.Filters != nil && len(request.Filters.Names) > 0:
+ networks, err = store.FindNetworks(tx, buildFilters(store.ByName, request.Filters.Names))
+ case request.Filters != nil && len(request.Filters.NamePrefixes) > 0:
+ networks, err = store.FindNetworks(tx, buildFilters(store.ByNamePrefix, request.Filters.NamePrefixes))
+ case request.Filters != nil && len(request.Filters.IDPrefixes) > 0:
+ networks, err = store.FindNetworks(tx, buildFilters(store.ByIDPrefix, request.Filters.IDPrefixes))
+ default:
+ networks, err = store.FindNetworks(tx, store.All)
+ }
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ if request.Filters != nil {
+ networks = filterNetworks(networks,
+ func(e *api.Network) bool {
+ return filterContains(e.Spec.Annotations.Name, request.Filters.Names)
+ },
+ func(e *api.Network) bool {
+ return filterContainsPrefix(e.Spec.Annotations.Name, request.Filters.NamePrefixes)
+ },
+ func(e *api.Network) bool {
+ return filterContainsPrefix(e.ID, request.Filters.IDPrefixes)
+ },
+ func(e *api.Network) bool {
+ return filterMatchLabels(e.Spec.Annotations.Labels, request.Filters.Labels)
+ },
+ )
+ }
+
+ return &api.ListNetworksResponse{
+ Networks: networks,
+ }, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/node.go b/vendor/github.com/docker/swarmkit/manager/controlapi/node.go
new file mode 100644
index 0000000..f3ee9e4
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/controlapi/node.go
@@ -0,0 +1,322 @@
+package controlapi
+
+import (
+ "crypto/x509"
+ "encoding/pem"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/state/raft/membership"
+ "github.com/docker/swarmkit/manager/state/store"
+ gogotypes "github.com/gogo/protobuf/types"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+func validateNodeSpec(spec *api.NodeSpec) error {
+ if spec == nil {
+ return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+ return nil
+}
+
+// GetNode returns a Node given a NodeID.
+// - Returns `InvalidArgument` if NodeID is not provided.
+// - Returns `NotFound` if the Node is not found.
+func (s *Server) GetNode(ctx context.Context, request *api.GetNodeRequest) (*api.GetNodeResponse, error) {
+ if request.NodeID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ var node *api.Node
+ s.store.View(func(tx store.ReadTx) {
+ node = store.GetNode(tx, request.NodeID)
+ })
+ if node == nil {
+ return nil, grpc.Errorf(codes.NotFound, "node %s not found", request.NodeID)
+ }
+
+ if s.raft != nil {
+ memberlist := s.raft.GetMemberlist()
+ for _, member := range memberlist {
+ if member.NodeID == node.ID {
+ node.ManagerStatus = &api.ManagerStatus{
+ RaftID: member.RaftID,
+ Addr: member.Addr,
+ Leader: member.Status.Leader,
+ Reachability: member.Status.Reachability,
+ }
+ break
+ }
+ }
+ }
+
+ return &api.GetNodeResponse{
+ Node: node,
+ }, nil
+}
+
+func filterNodes(candidates []*api.Node, filters ...func(*api.Node) bool) []*api.Node {
+ result := []*api.Node{}
+
+ for _, c := range candidates {
+ match := true
+ for _, f := range filters {
+ if !f(c) {
+ match = false
+ break
+ }
+ }
+ if match {
+ result = append(result, c)
+ }
+ }
+
+ return result
+}
+
+// ListNodes returns a list of all nodes.
+func (s *Server) ListNodes(ctx context.Context, request *api.ListNodesRequest) (*api.ListNodesResponse, error) {
+ var (
+ nodes []*api.Node
+ err error
+ )
+ s.store.View(func(tx store.ReadTx) {
+ switch {
+ case request.Filters != nil && len(request.Filters.Names) > 0:
+ nodes, err = store.FindNodes(tx, buildFilters(store.ByName, request.Filters.Names))
+ case request.Filters != nil && len(request.Filters.NamePrefixes) > 0:
+ nodes, err = store.FindNodes(tx, buildFilters(store.ByNamePrefix, request.Filters.NamePrefixes))
+ case request.Filters != nil && len(request.Filters.IDPrefixes) > 0:
+ nodes, err = store.FindNodes(tx, buildFilters(store.ByIDPrefix, request.Filters.IDPrefixes))
+ case request.Filters != nil && len(request.Filters.Roles) > 0:
+ filters := make([]store.By, 0, len(request.Filters.Roles))
+ for _, v := range request.Filters.Roles {
+ filters = append(filters, store.ByRole(v))
+ }
+ nodes, err = store.FindNodes(tx, store.Or(filters...))
+ case request.Filters != nil && len(request.Filters.Memberships) > 0:
+ filters := make([]store.By, 0, len(request.Filters.Memberships))
+ for _, v := range request.Filters.Memberships {
+ filters = append(filters, store.ByMembership(v))
+ }
+ nodes, err = store.FindNodes(tx, store.Or(filters...))
+ default:
+ nodes, err = store.FindNodes(tx, store.All)
+ }
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ if request.Filters != nil {
+ nodes = filterNodes(nodes,
+ func(e *api.Node) bool {
+ if len(request.Filters.Names) == 0 {
+ return true
+ }
+ if e.Description == nil {
+ return false
+ }
+ return filterContains(e.Description.Hostname, request.Filters.Names)
+ },
+ func(e *api.Node) bool {
+ if len(request.Filters.NamePrefixes) == 0 {
+ return true
+ }
+ if e.Description == nil {
+ return false
+ }
+ return filterContainsPrefix(e.Description.Hostname, request.Filters.NamePrefixes)
+ },
+ func(e *api.Node) bool {
+ return filterContainsPrefix(e.ID, request.Filters.IDPrefixes)
+ },
+ func(e *api.Node) bool {
+ if len(request.Filters.Labels) == 0 {
+ return true
+ }
+ if e.Description == nil {
+ return false
+ }
+ return filterMatchLabels(e.Description.Engine.Labels, request.Filters.Labels)
+ },
+ func(e *api.Node) bool {
+ if len(request.Filters.Roles) == 0 {
+ return true
+ }
+ for _, c := range request.Filters.Roles {
+ if c == e.Role {
+ return true
+ }
+ }
+ return false
+ },
+ func(e *api.Node) bool {
+ if len(request.Filters.Memberships) == 0 {
+ return true
+ }
+ for _, c := range request.Filters.Memberships {
+ if c == e.Spec.Membership {
+ return true
+ }
+ }
+ return false
+ },
+ )
+ }
+
+ // Add in manager information on nodes that are managers
+ if s.raft != nil {
+ memberlist := s.raft.GetMemberlist()
+
+ for _, node := range nodes {
+ for _, member := range memberlist {
+ if member.NodeID == node.ID {
+ node.ManagerStatus = &api.ManagerStatus{
+ RaftID: member.RaftID,
+ Addr: member.Addr,
+ Leader: member.Status.Leader,
+ Reachability: member.Status.Reachability,
+ }
+ break
+ }
+ }
+ }
+ }
+
+ return &api.ListNodesResponse{
+ Nodes: nodes,
+ }, nil
+}
+
+// UpdateNode updates a Node referenced by NodeID with the given NodeSpec.
+// - Returns `NotFound` if the Node is not found.
+// - Returns `InvalidArgument` if the NodeSpec is malformed.
+// - Returns an error if the update fails.
+func (s *Server) UpdateNode(ctx context.Context, request *api.UpdateNodeRequest) (*api.UpdateNodeResponse, error) {
+ if request.NodeID == "" || request.NodeVersion == nil {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+ if err := validateNodeSpec(request.Spec); err != nil {
+ return nil, err
+ }
+
+ var (
+ node *api.Node
+ member *membership.Member
+ )
+
+ err := s.store.Update(func(tx store.Tx) error {
+ node = store.GetNode(tx, request.NodeID)
+ if node == nil {
+ return grpc.Errorf(codes.NotFound, "node %s not found", request.NodeID)
+ }
+
+ // Demotion sanity checks.
+ if node.Spec.DesiredRole == api.NodeRoleManager && request.Spec.DesiredRole == api.NodeRoleWorker {
+ // Check for manager entries in Store.
+ managers, err := store.FindNodes(tx, store.ByRole(api.NodeRoleManager))
+ if err != nil {
+ return grpc.Errorf(codes.Internal, "internal store error: %v", err)
+ }
+ if len(managers) == 1 && managers[0].ID == node.ID {
+ return grpc.Errorf(codes.FailedPrecondition, "attempting to demote the last manager of the swarm")
+ }
+
+ // Check for node in memberlist
+ if member = s.raft.GetMemberByNodeID(request.NodeID); member == nil {
+ return grpc.Errorf(codes.NotFound, "can't find manager in raft memberlist")
+ }
+
+ // Quorum safeguard
+ if !s.raft.CanRemoveMember(member.RaftID) {
+ return grpc.Errorf(codes.FailedPrecondition, "can't remove member from the raft: this would result in a loss of quorum")
+ }
+ }
+
+ node.Meta.Version = *request.NodeVersion
+ node.Spec = *request.Spec.Copy()
+ return store.UpdateNode(tx, node)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return &api.UpdateNodeResponse{
+ Node: node,
+ }, nil
+}
+
+// RemoveNode removes a Node referenced by NodeID with the given NodeSpec.
+// - Returns NotFound if the Node is not found.
+// - Returns FailedPrecondition if the Node has manager role (and is part of the memberlist) or is not shut down.
+// - Returns InvalidArgument if NodeID or NodeVersion is not valid.
+// - Returns an error if the delete fails.
+func (s *Server) RemoveNode(ctx context.Context, request *api.RemoveNodeRequest) (*api.RemoveNodeResponse, error) {
+ if request.NodeID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ err := s.store.Update(func(tx store.Tx) error {
+ node := store.GetNode(tx, request.NodeID)
+ if node == nil {
+ return grpc.Errorf(codes.NotFound, "node %s not found", request.NodeID)
+ }
+ if node.Spec.DesiredRole == api.NodeRoleManager {
+ if s.raft == nil {
+ return grpc.Errorf(codes.FailedPrecondition, "node %s is a manager but cannot access node information from the raft memberlist", request.NodeID)
+ }
+ if member := s.raft.GetMemberByNodeID(request.NodeID); member != nil {
+ return grpc.Errorf(codes.FailedPrecondition, "node %s is a cluster manager and is a member of the raft cluster. It must be demoted to worker before removal", request.NodeID)
+ }
+ }
+ if !request.Force && node.Status.State == api.NodeStatus_READY {
+ return grpc.Errorf(codes.FailedPrecondition, "node %s is not down and can't be removed", request.NodeID)
+ }
+
+ // lookup the cluster
+ clusters, err := store.FindClusters(tx, store.ByName("default"))
+ if err != nil {
+ return err
+ }
+ if len(clusters) != 1 {
+ return grpc.Errorf(codes.Internal, "could not fetch cluster object")
+ }
+ cluster := clusters[0]
+
+ blacklistedCert := &api.BlacklistedCertificate{}
+
+ // Set an expiry time for this RemovedNode if a certificate
+ // exists and can be parsed.
+ if len(node.Certificate.Certificate) != 0 {
+ certBlock, _ := pem.Decode(node.Certificate.Certificate)
+ if certBlock != nil {
+ X509Cert, err := x509.ParseCertificate(certBlock.Bytes)
+ if err == nil && !X509Cert.NotAfter.IsZero() {
+ expiry, err := gogotypes.TimestampProto(X509Cert.NotAfter)
+ if err == nil {
+ blacklistedCert.Expiry = expiry
+ }
+ }
+ }
+ }
+
+ if cluster.BlacklistedCertificates == nil {
+ cluster.BlacklistedCertificates = make(map[string]*api.BlacklistedCertificate)
+ }
+ cluster.BlacklistedCertificates[node.ID] = blacklistedCert
+
+ expireBlacklistedCerts(cluster)
+
+ if err := store.UpdateCluster(tx, cluster); err != nil {
+ return err
+ }
+
+ return store.DeleteNode(tx, request.NodeID)
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &api.RemoveNodeResponse{}, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/secret.go b/vendor/github.com/docker/swarmkit/manager/controlapi/secret.go
new file mode 100644
index 0000000..5f125e9
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/controlapi/secret.go
@@ -0,0 +1,253 @@
+package controlapi
+
+import (
+ "crypto/subtle"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+// MaxSecretSize is the maximum byte length of the `Secret.Spec.Data` field.
+const MaxSecretSize = 500 * 1024 // 500KB
+
+// assumes spec is not nil
+func secretFromSecretSpec(spec *api.SecretSpec) *api.Secret {
+ return &api.Secret{
+ ID: identity.NewID(),
+ Spec: *spec,
+ }
+}
+
+// GetSecret returns a `GetSecretResponse` with a `Secret` with the same
+// id as `GetSecretRequest.SecretID`
+// - Returns `NotFound` if the Secret with the given id is not found.
+// - Returns `InvalidArgument` if the `GetSecretRequest.SecretID` is empty.
+// - Returns an error if getting fails.
+func (s *Server) GetSecret(ctx context.Context, request *api.GetSecretRequest) (*api.GetSecretResponse, error) {
+ if request.SecretID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, "secret ID must be provided")
+ }
+
+ var secret *api.Secret
+ s.store.View(func(tx store.ReadTx) {
+ secret = store.GetSecret(tx, request.SecretID)
+ })
+
+ if secret == nil {
+ return nil, grpc.Errorf(codes.NotFound, "secret %s not found", request.SecretID)
+ }
+
+ secret.Spec.Data = nil // clean the actual secret data so it's never returned
+ return &api.GetSecretResponse{Secret: secret}, nil
+}
+
+// UpdateSecret updates a Secret referenced by SecretID with the given SecretSpec.
+// - Returns `NotFound` if the Secret is not found.
+// - Returns `InvalidArgument` if the SecretSpec is malformed or anything other than Labels is changed
+// - Returns an error if the update fails.
+func (s *Server) UpdateSecret(ctx context.Context, request *api.UpdateSecretRequest) (*api.UpdateSecretResponse, error) {
+ if request.SecretID == "" || request.SecretVersion == nil {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ var secret *api.Secret
+ err := s.store.Update(func(tx store.Tx) error {
+ secret = store.GetSecret(tx, request.SecretID)
+ if secret == nil {
+ return grpc.Errorf(codes.NotFound, "secret %s not found", request.SecretID)
+ }
+
+ // Check if the Name is different than the current name, or the secret is non-nil and different
+ // than the current secret
+ if secret.Spec.Annotations.Name != request.Spec.Annotations.Name ||
+ (request.Spec.Data != nil && subtle.ConstantTimeCompare(request.Spec.Data, secret.Spec.Data) == 0) {
+ return grpc.Errorf(codes.InvalidArgument, "only updates to Labels are allowed")
+ }
+
+ // We only allow updating Labels
+ secret.Meta.Version = *request.SecretVersion
+ secret.Spec.Annotations.Labels = request.Spec.Annotations.Labels
+
+ return store.UpdateSecret(tx, secret)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ log.G(ctx).WithFields(logrus.Fields{
+ "secret.ID": request.SecretID,
+ "secret.Name": request.Spec.Annotations.Name,
+ "method": "UpdateSecret",
+ }).Debugf("secret updated")
+
+ // WARN: we should never return the actual secret data here. We need to redact the private fields first.
+ secret.Spec.Data = nil
+ return &api.UpdateSecretResponse{
+ Secret: secret,
+ }, nil
+}
+
+// ListSecrets returns a `ListSecretResponse` with a list all non-internal `Secret`s being
+// managed, or all secrets matching any name in `ListSecretsRequest.Names`, any
+// name prefix in `ListSecretsRequest.NamePrefixes`, any id in
+// `ListSecretsRequest.SecretIDs`, or any id prefix in `ListSecretsRequest.IDPrefixes`.
+// - Returns an error if listing fails.
+func (s *Server) ListSecrets(ctx context.Context, request *api.ListSecretsRequest) (*api.ListSecretsResponse, error) {
+ var (
+ secrets []*api.Secret
+ respSecrets []*api.Secret
+ err error
+ byFilters []store.By
+ by store.By
+ labels map[string]string
+ )
+
+ // return all secrets that match either any of the names or any of the name prefixes (why would you give both?)
+ if request.Filters != nil {
+ for _, name := range request.Filters.Names {
+ byFilters = append(byFilters, store.ByName(name))
+ }
+ for _, prefix := range request.Filters.NamePrefixes {
+ byFilters = append(byFilters, store.ByNamePrefix(prefix))
+ }
+ for _, prefix := range request.Filters.IDPrefixes {
+ byFilters = append(byFilters, store.ByIDPrefix(prefix))
+ }
+ labels = request.Filters.Labels
+ }
+
+ switch len(byFilters) {
+ case 0:
+ by = store.All
+ case 1:
+ by = byFilters[0]
+ default:
+ by = store.Or(byFilters...)
+ }
+
+ s.store.View(func(tx store.ReadTx) {
+ secrets, err = store.FindSecrets(tx, by)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ // strip secret data from the secret, filter by label, and filter out all internal secrets
+ for _, secret := range secrets {
+ if secret.Internal || !filterMatchLabels(secret.Spec.Annotations.Labels, labels) {
+ continue
+ }
+ secret.Spec.Data = nil // clean the actual secret data so it's never returned
+ respSecrets = append(respSecrets, secret)
+ }
+
+ return &api.ListSecretsResponse{Secrets: respSecrets}, nil
+}
+
+// CreateSecret creates and returns a `CreateSecretResponse` with a `Secret` based
+// on the provided `CreateSecretRequest.SecretSpec`.
+// - Returns `InvalidArgument` if the `CreateSecretRequest.SecretSpec` is malformed,
+// or if the secret data is too long or contains invalid characters.
+// - Returns an error if the creation fails.
+func (s *Server) CreateSecret(ctx context.Context, request *api.CreateSecretRequest) (*api.CreateSecretResponse, error) {
+ if err := validateSecretSpec(request.Spec); err != nil {
+ return nil, err
+ }
+
+ secret := secretFromSecretSpec(request.Spec) // the store will handle name conflicts
+ err := s.store.Update(func(tx store.Tx) error {
+ return store.CreateSecret(tx, secret)
+ })
+
+ switch err {
+ case store.ErrNameConflict:
+ return nil, grpc.Errorf(codes.AlreadyExists, "secret %s already exists", request.Spec.Annotations.Name)
+ case nil:
+ secret.Spec.Data = nil // clean the actual secret data so it's never returned
+ log.G(ctx).WithFields(logrus.Fields{
+ "secret.Name": request.Spec.Annotations.Name,
+ "method": "CreateSecret",
+ }).Debugf("secret created")
+
+ return &api.CreateSecretResponse{Secret: secret}, nil
+ default:
+ return nil, err
+ }
+}
+
+// RemoveSecret removes the secret referenced by `RemoveSecretRequest.ID`.
+// - Returns `InvalidArgument` if `RemoveSecretRequest.ID` is empty.
+// - Returns `NotFound` if the a secret named `RemoveSecretRequest.ID` is not found.
+// - Returns `SecretInUse` if the secret is currently in use
+// - Returns an error if the deletion fails.
+func (s *Server) RemoveSecret(ctx context.Context, request *api.RemoveSecretRequest) (*api.RemoveSecretResponse, error) {
+ if request.SecretID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, "secret ID must be provided")
+ }
+
+ err := s.store.Update(func(tx store.Tx) error {
+ // Check if the secret exists
+ secret := store.GetSecret(tx, request.SecretID)
+ if secret == nil {
+ return grpc.Errorf(codes.NotFound, "could not find secret %s", request.SecretID)
+ }
+
+ // Check if any services currently reference this secret, return error if so
+ services, err := store.FindServices(tx, store.ByReferencedSecretID(request.SecretID))
+ if err != nil {
+ return grpc.Errorf(codes.Internal, "could not find services using secret %s: %v", request.SecretID, err)
+ }
+
+ if len(services) != 0 {
+ serviceNames := make([]string, 0, len(services))
+ for _, service := range services {
+ serviceNames = append(serviceNames, service.Spec.Annotations.Name)
+ }
+
+ secretName := secret.Spec.Annotations.Name
+ serviceNameStr := strings.Join(serviceNames, ", ")
+ serviceStr := "services"
+ if len(serviceNames) == 1 {
+ serviceStr = "service"
+ }
+
+ return grpc.Errorf(codes.InvalidArgument, "secret '%s' is in use by the following %s: %v", secretName, serviceStr, serviceNameStr)
+ }
+
+ return store.DeleteSecret(tx, request.SecretID)
+ })
+ switch err {
+ case store.ErrNotExist:
+ return nil, grpc.Errorf(codes.NotFound, "secret %s not found", request.SecretID)
+ case nil:
+ log.G(ctx).WithFields(logrus.Fields{
+ "secret.ID": request.SecretID,
+ "method": "RemoveSecret",
+ }).Debugf("secret removed")
+
+ return &api.RemoveSecretResponse{}, nil
+ default:
+ return nil, err
+ }
+}
+
+func validateSecretSpec(spec *api.SecretSpec) error {
+ if spec == nil {
+ return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+ if err := validateConfigOrSecretAnnotations(spec.Annotations); err != nil {
+ return err
+ }
+
+ if len(spec.Data) >= MaxSecretSize || len(spec.Data) < 1 {
+ return grpc.Errorf(codes.InvalidArgument, "secret data must be larger than 0 and less than %d bytes", MaxSecretSize)
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/server.go b/vendor/github.com/docker/swarmkit/manager/controlapi/server.go
new file mode 100644
index 0000000..3d49ef9
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/controlapi/server.go
@@ -0,0 +1,36 @@
+package controlapi
+
+import (
+ "errors"
+
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/swarmkit/ca"
+ "github.com/docker/swarmkit/manager/state/raft"
+ "github.com/docker/swarmkit/manager/state/store"
+)
+
+var (
+ errNotImplemented = errors.New("not implemented")
+ errInvalidArgument = errors.New("invalid argument")
+)
+
+// Server is the Cluster API gRPC server.
+type Server struct {
+ store *store.MemoryStore
+ raft *raft.Node
+ securityConfig *ca.SecurityConfig
+ scu ca.APISecurityConfigUpdater
+ pg plugingetter.PluginGetter
+}
+
+// NewServer creates a Cluster API server.
+func NewServer(store *store.MemoryStore, raft *raft.Node, securityConfig *ca.SecurityConfig,
+ scu ca.APISecurityConfigUpdater, pg plugingetter.PluginGetter) *Server {
+ return &Server{
+ store: store,
+ raft: raft,
+ securityConfig: securityConfig,
+ scu: scu,
+ pg: pg,
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/service.go b/vendor/github.com/docker/swarmkit/manager/controlapi/service.go
new file mode 100644
index 0000000..d556b6c
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/controlapi/service.go
@@ -0,0 +1,933 @@
+package controlapi
+
+import (
+ "errors"
+ "reflect"
+ "strings"
+ "time"
+
+ "github.com/docker/distribution/reference"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/defaults"
+ "github.com/docker/swarmkit/api/genericresource"
+ "github.com/docker/swarmkit/api/naming"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/manager/allocator"
+ "github.com/docker/swarmkit/manager/constraint"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/protobuf/ptypes"
+ "github.com/docker/swarmkit/template"
+ gogotypes "github.com/gogo/protobuf/types"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+var (
+ errNetworkUpdateNotSupported = errors.New("networks must be migrated to TaskSpec before being changed")
+ errRenameNotSupported = errors.New("renaming services is not supported")
+ errModeChangeNotAllowed = errors.New("service mode change is not allowed")
+)
+
+const minimumDuration = 1 * time.Millisecond
+
+func validateResources(r *api.Resources) error {
+ if r == nil {
+ return nil
+ }
+
+ if r.NanoCPUs != 0 && r.NanoCPUs < 1e6 {
+ return grpc.Errorf(codes.InvalidArgument, "invalid cpu value %g: Must be at least %g", float64(r.NanoCPUs)/1e9, 1e6/1e9)
+ }
+
+ if r.MemoryBytes != 0 && r.MemoryBytes < 4*1024*1024 {
+ return grpc.Errorf(codes.InvalidArgument, "invalid memory value %d: Must be at least 4MiB", r.MemoryBytes)
+ }
+ if err := genericresource.ValidateTask(r); err != nil {
+ return nil
+ }
+ return nil
+}
+
+func validateResourceRequirements(r *api.ResourceRequirements) error {
+ if r == nil {
+ return nil
+ }
+ if err := validateResources(r.Limits); err != nil {
+ return err
+ }
+ if err := validateResources(r.Reservations); err != nil {
+ return err
+ }
+ return nil
+}
+
+func validateRestartPolicy(rp *api.RestartPolicy) error {
+ if rp == nil {
+ return nil
+ }
+
+ if rp.Delay != nil {
+ delay, err := gogotypes.DurationFromProto(rp.Delay)
+ if err != nil {
+ return err
+ }
+ if delay < 0 {
+ return grpc.Errorf(codes.InvalidArgument, "TaskSpec: restart-delay cannot be negative")
+ }
+ }
+
+ if rp.Window != nil {
+ win, err := gogotypes.DurationFromProto(rp.Window)
+ if err != nil {
+ return err
+ }
+ if win < 0 {
+ return grpc.Errorf(codes.InvalidArgument, "TaskSpec: restart-window cannot be negative")
+ }
+ }
+
+ return nil
+}
+
+func validatePlacement(placement *api.Placement) error {
+ if placement == nil {
+ return nil
+ }
+ _, err := constraint.Parse(placement.Constraints)
+ return err
+}
+
+func validateUpdate(uc *api.UpdateConfig) error {
+ if uc == nil {
+ return nil
+ }
+
+ if uc.Delay < 0 {
+ return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-delay cannot be negative")
+ }
+
+ if uc.Monitor != nil {
+ monitor, err := gogotypes.DurationFromProto(uc.Monitor)
+ if err != nil {
+ return err
+ }
+ if monitor < 0 {
+ return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-monitor cannot be negative")
+ }
+ }
+
+ if uc.MaxFailureRatio < 0 || uc.MaxFailureRatio > 1 {
+ return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-maxfailureratio cannot be less than 0 or bigger than 1")
+ }
+
+ return nil
+}
+
+func validateContainerSpec(taskSpec api.TaskSpec) error {
+ // Building a empty/dummy Task to validate the templating and
+ // the resulting container spec as well. This is a *best effort*
+ // validation.
+ container, err := template.ExpandContainerSpec(&api.Task{
+ Spec: taskSpec,
+ ServiceID: "serviceid",
+ Slot: 1,
+ NodeID: "nodeid",
+ Networks: []*api.NetworkAttachment{},
+ Annotations: api.Annotations{
+ Name: "taskname",
+ },
+ ServiceAnnotations: api.Annotations{
+ Name: "servicename",
+ },
+ Endpoint: &api.Endpoint{},
+ LogDriver: taskSpec.LogDriver,
+ })
+ if err != nil {
+ return grpc.Errorf(codes.InvalidArgument, err.Error())
+ }
+
+ if err := validateImage(container.Image); err != nil {
+ return err
+ }
+
+ if err := validateMounts(container.Mounts); err != nil {
+ return err
+ }
+
+ if err := validateHealthCheck(container.Healthcheck); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// validateImage validates image name in containerSpec
+func validateImage(image string) error {
+ if image == "" {
+ return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: image reference must be provided")
+ }
+
+ if _, err := reference.ParseNormalizedNamed(image); err != nil {
+ return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: %q is not a valid repository/tag", image)
+ }
+ return nil
+}
+
+// validateMounts validates if there are duplicate mounts in containerSpec
+func validateMounts(mounts []api.Mount) error {
+ mountMap := make(map[string]bool)
+ for _, mount := range mounts {
+ if _, exists := mountMap[mount.Target]; exists {
+ return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: duplicate mount point: %s", mount.Target)
+ }
+ mountMap[mount.Target] = true
+ }
+
+ return nil
+}
+
+// validateHealthCheck validates configs about container's health check
+func validateHealthCheck(hc *api.HealthConfig) error {
+ if hc == nil {
+ return nil
+ }
+
+ if hc.Interval != nil {
+ interval, err := gogotypes.DurationFromProto(hc.Interval)
+ if err != nil {
+ return err
+ }
+ if interval != 0 && interval < time.Duration(minimumDuration) {
+ return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: Interval in HealthConfig cannot be less than %s", minimumDuration)
+ }
+ }
+
+ if hc.Timeout != nil {
+ timeout, err := gogotypes.DurationFromProto(hc.Timeout)
+ if err != nil {
+ return err
+ }
+ if timeout != 0 && timeout < time.Duration(minimumDuration) {
+ return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: Timeout in HealthConfig cannot be less than %s", minimumDuration)
+ }
+ }
+
+ if hc.StartPeriod != nil {
+ sp, err := gogotypes.DurationFromProto(hc.StartPeriod)
+ if err != nil {
+ return err
+ }
+ if sp != 0 && sp < time.Duration(minimumDuration) {
+ return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: StartPeriod in HealthConfig cannot be less than %s", minimumDuration)
+ }
+ }
+
+ if hc.Retries < 0 {
+ return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: Retries in HealthConfig cannot be negative")
+ }
+
+ return nil
+}
+
+func validateGenericRuntimeSpec(taskSpec api.TaskSpec) error {
+ generic := taskSpec.GetGeneric()
+
+ if len(generic.Kind) < 3 {
+ return grpc.Errorf(codes.InvalidArgument, "Generic runtime: Invalid name %q", generic.Kind)
+ }
+
+ reservedNames := []string{"container", "attachment"}
+ for _, n := range reservedNames {
+ if strings.ToLower(generic.Kind) == n {
+ return grpc.Errorf(codes.InvalidArgument, "Generic runtime: %q is a reserved name", generic.Kind)
+ }
+ }
+
+ payload := generic.Payload
+
+ if payload == nil {
+ return grpc.Errorf(codes.InvalidArgument, "Generic runtime is missing payload")
+ }
+
+ if payload.TypeUrl == "" {
+ return grpc.Errorf(codes.InvalidArgument, "Generic runtime is missing payload type")
+ }
+
+ if len(payload.Value) == 0 {
+ return grpc.Errorf(codes.InvalidArgument, "Generic runtime has an empty payload")
+ }
+
+ return nil
+}
+
+func validateTaskSpec(taskSpec api.TaskSpec) error {
+ if err := validateResourceRequirements(taskSpec.Resources); err != nil {
+ return err
+ }
+
+ if err := validateRestartPolicy(taskSpec.Restart); err != nil {
+ return err
+ }
+
+ if err := validatePlacement(taskSpec.Placement); err != nil {
+ return err
+ }
+
+ // Check to see if the secret reference portion of the spec is valid
+ if err := validateSecretRefsSpec(taskSpec); err != nil {
+ return err
+ }
+
+ // Check to see if the config reference portion of the spec is valid
+ if err := validateConfigRefsSpec(taskSpec); err != nil {
+ return err
+ }
+
+ if taskSpec.GetRuntime() == nil {
+ return grpc.Errorf(codes.InvalidArgument, "TaskSpec: missing runtime")
+ }
+
+ switch taskSpec.GetRuntime().(type) {
+ case *api.TaskSpec_Container:
+ if err := validateContainerSpec(taskSpec); err != nil {
+ return err
+ }
+ case *api.TaskSpec_Generic:
+ if err := validateGenericRuntimeSpec(taskSpec); err != nil {
+ return err
+ }
+ default:
+ return grpc.Errorf(codes.Unimplemented, "RuntimeSpec: unimplemented runtime in service spec")
+ }
+
+ return nil
+}
+
+func validateEndpointSpec(epSpec *api.EndpointSpec) error {
+ // Endpoint spec is optional
+ if epSpec == nil {
+ return nil
+ }
+
+ type portSpec struct {
+ publishedPort uint32
+ protocol api.PortConfig_Protocol
+ }
+
+ portSet := make(map[portSpec]struct{})
+ for _, port := range epSpec.Ports {
+ // Publish mode = "ingress" represents Routing-Mesh and current implementation
+ // of routing-mesh relies on IPVS based load-balancing with input=published-port.
+ // But Endpoint-Spec mode of DNSRR relies on multiple A records and cannot be used
+ // with routing-mesh (PublishMode="ingress") which cannot rely on DNSRR.
+ // But PublishMode="host" doesn't provide Routing-Mesh and the DNSRR is applicable
+ // for the backend network and hence we accept that configuration.
+
+ if epSpec.Mode == api.ResolutionModeDNSRoundRobin && port.PublishMode == api.PublishModeIngress {
+ return grpc.Errorf(codes.InvalidArgument, "EndpointSpec: port published with ingress mode can't be used with dnsrr mode")
+ }
+
+ // If published port is not specified, it does not conflict
+ // with any others.
+ if port.PublishedPort == 0 {
+ continue
+ }
+
+ portSpec := portSpec{publishedPort: port.PublishedPort, protocol: port.Protocol}
+ if _, ok := portSet[portSpec]; ok {
+ return grpc.Errorf(codes.InvalidArgument, "EndpointSpec: duplicate published ports provided")
+ }
+
+ portSet[portSpec] = struct{}{}
+ }
+
+ return nil
+}
+
+// validateSecretRefsSpec finds if the secrets passed in spec are valid and have no
+// conflicting targets.
+func validateSecretRefsSpec(spec api.TaskSpec) error {
+ container := spec.GetContainer()
+ if container == nil {
+ return nil
+ }
+
+ // Keep a map to track all the targets that will be exposed
+ // The string returned is only used for logging. It could as well be struct{}{}
+ existingTargets := make(map[string]string)
+ for _, secretRef := range container.Secrets {
+ // SecretID and SecretName are mandatory, we have invalid references without them
+ if secretRef.SecretID == "" || secretRef.SecretName == "" {
+ return grpc.Errorf(codes.InvalidArgument, "malformed secret reference")
+ }
+
+ // Every secret reference requires a Target
+ if secretRef.GetTarget() == nil {
+ return grpc.Errorf(codes.InvalidArgument, "malformed secret reference, no target provided")
+ }
+
+ // If this is a file target, we will ensure filename uniqueness
+ if secretRef.GetFile() != nil {
+ fileName := secretRef.GetFile().Name
+ if fileName == "" {
+ return grpc.Errorf(codes.InvalidArgument, "malformed file secret reference, invalid target file name provided")
+ }
+ // If this target is already in use, we have conflicting targets
+ if prevSecretName, ok := existingTargets[fileName]; ok {
+ return grpc.Errorf(codes.InvalidArgument, "secret references '%s' and '%s' have a conflicting target: '%s'", prevSecretName, secretRef.SecretName, fileName)
+ }
+
+ existingTargets[fileName] = secretRef.SecretName
+ }
+ }
+
+ return nil
+}
+
+// validateConfigRefsSpec finds if the configs passed in spec are valid and have no
+// conflicting targets.
+func validateConfigRefsSpec(spec api.TaskSpec) error {
+ container := spec.GetContainer()
+ if container == nil {
+ return nil
+ }
+
+ // Keep a map to track all the targets that will be exposed
+ // The string returned is only used for logging. It could as well be struct{}{}
+ existingTargets := make(map[string]string)
+ for _, configRef := range container.Configs {
+ // ConfigID and ConfigName are mandatory, we have invalid references without them
+ if configRef.ConfigID == "" || configRef.ConfigName == "" {
+ return grpc.Errorf(codes.InvalidArgument, "malformed config reference")
+ }
+
+ // Every config reference requires a Target
+ if configRef.GetTarget() == nil {
+ return grpc.Errorf(codes.InvalidArgument, "malformed config reference, no target provided")
+ }
+
+ // If this is a file target, we will ensure filename uniqueness
+ if configRef.GetFile() != nil {
+ fileName := configRef.GetFile().Name
+ // Validate the file name
+ if fileName == "" {
+ return grpc.Errorf(codes.InvalidArgument, "malformed file config reference, invalid target file name provided")
+ }
+
+ // If this target is already in use, we have conflicting targets
+ if prevConfigName, ok := existingTargets[fileName]; ok {
+ return grpc.Errorf(codes.InvalidArgument, "config references '%s' and '%s' have a conflicting target: '%s'", prevConfigName, configRef.ConfigName, fileName)
+ }
+
+ existingTargets[fileName] = configRef.ConfigName
+ }
+ }
+
+ return nil
+}
+
+func (s *Server) validateNetworks(networks []*api.NetworkAttachmentConfig) error {
+ for _, na := range networks {
+ var network *api.Network
+ s.store.View(func(tx store.ReadTx) {
+ network = store.GetNetwork(tx, na.Target)
+ })
+ if network == nil {
+ continue
+ }
+ if allocator.IsIngressNetwork(network) {
+ return grpc.Errorf(codes.InvalidArgument,
+ "Service cannot be explicitly attached to the ingress network %q", network.Spec.Annotations.Name)
+ }
+ }
+ return nil
+}
+
+func validateMode(s *api.ServiceSpec) error {
+ m := s.GetMode()
+ switch m.(type) {
+ case *api.ServiceSpec_Replicated:
+ if int64(m.(*api.ServiceSpec_Replicated).Replicated.Replicas) < 0 {
+ return grpc.Errorf(codes.InvalidArgument, "Number of replicas must be non-negative")
+ }
+ case *api.ServiceSpec_Global:
+ default:
+ return grpc.Errorf(codes.InvalidArgument, "Unrecognized service mode")
+ }
+
+ return nil
+}
+
+func validateServiceSpec(spec *api.ServiceSpec) error {
+ if spec == nil {
+ return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+ if err := validateAnnotations(spec.Annotations); err != nil {
+ return err
+ }
+ if err := validateTaskSpec(spec.Task); err != nil {
+ return err
+ }
+ if err := validateUpdate(spec.Update); err != nil {
+ return err
+ }
+ if err := validateEndpointSpec(spec.Endpoint); err != nil {
+ return err
+ }
+ if err := validateMode(spec); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// checkPortConflicts does a best effort to find if the passed in spec has port
+// conflicts with existing services.
+// `serviceID string` is the service ID of the spec in service update. If
+// `serviceID` is not "", then conflicts check will be skipped against this
+// service (the service being updated).
+func (s *Server) checkPortConflicts(spec *api.ServiceSpec, serviceID string) error {
+ if spec.Endpoint == nil {
+ return nil
+ }
+
+ type portSpec struct {
+ protocol api.PortConfig_Protocol
+ publishedPort uint32
+ }
+
+ pcToStruct := func(pc *api.PortConfig) portSpec {
+ return portSpec{
+ protocol: pc.Protocol,
+ publishedPort: pc.PublishedPort,
+ }
+ }
+
+ ingressPorts := make(map[portSpec]struct{})
+ hostModePorts := make(map[portSpec]struct{})
+ for _, pc := range spec.Endpoint.Ports {
+ if pc.PublishedPort == 0 {
+ continue
+ }
+ switch pc.PublishMode {
+ case api.PublishModeIngress:
+ ingressPorts[pcToStruct(pc)] = struct{}{}
+ case api.PublishModeHost:
+ hostModePorts[pcToStruct(pc)] = struct{}{}
+ }
+ }
+ if len(ingressPorts) == 0 && len(hostModePorts) == 0 {
+ return nil
+ }
+
+ var (
+ services []*api.Service
+ err error
+ )
+
+ s.store.View(func(tx store.ReadTx) {
+ services, err = store.FindServices(tx, store.All)
+ })
+ if err != nil {
+ return err
+ }
+
+ isPortInUse := func(pc *api.PortConfig, service *api.Service) error {
+ if pc.PublishedPort == 0 {
+ return nil
+ }
+
+ switch pc.PublishMode {
+ case api.PublishModeHost:
+ if _, ok := ingressPorts[pcToStruct(pc)]; ok {
+ return grpc.Errorf(codes.InvalidArgument, "port '%d' is already in use by service '%s' (%s) as a host-published port", pc.PublishedPort, service.Spec.Annotations.Name, service.ID)
+ }
+
+ // Multiple services with same port in host publish mode can
+ // coexist - this is handled by the scheduler.
+ return nil
+ case api.PublishModeIngress:
+ _, ingressConflict := ingressPorts[pcToStruct(pc)]
+ _, hostModeConflict := hostModePorts[pcToStruct(pc)]
+ if ingressConflict || hostModeConflict {
+ return grpc.Errorf(codes.InvalidArgument, "port '%d' is already in use by service '%s' (%s) as an ingress port", pc.PublishedPort, service.Spec.Annotations.Name, service.ID)
+ }
+ }
+
+ return nil
+ }
+
+ for _, service := range services {
+ // If service ID is the same (and not "") then this is an update
+ if serviceID != "" && serviceID == service.ID {
+ continue
+ }
+ if service.Spec.Endpoint != nil {
+ for _, pc := range service.Spec.Endpoint.Ports {
+ if err := isPortInUse(pc, service); err != nil {
+ return err
+ }
+ }
+ }
+ if service.Endpoint != nil {
+ for _, pc := range service.Endpoint.Ports {
+ if err := isPortInUse(pc, service); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ return nil
+}
+
+// checkSecretExistence finds if the secret exists
+func (s *Server) checkSecretExistence(tx store.Tx, spec *api.ServiceSpec) error {
+ container := spec.Task.GetContainer()
+ if container == nil {
+ return nil
+ }
+
+ var failedSecrets []string
+ for _, secretRef := range container.Secrets {
+ secret := store.GetSecret(tx, secretRef.SecretID)
+ // Check to see if the secret exists and secretRef.SecretName matches the actual secretName
+ if secret == nil || secret.Spec.Annotations.Name != secretRef.SecretName {
+ failedSecrets = append(failedSecrets, secretRef.SecretName)
+ }
+ }
+
+ if len(failedSecrets) > 0 {
+ secretStr := "secrets"
+ if len(failedSecrets) == 1 {
+ secretStr = "secret"
+ }
+
+ return grpc.Errorf(codes.InvalidArgument, "%s not found: %v", secretStr, strings.Join(failedSecrets, ", "))
+
+ }
+
+ return nil
+}
+
+// checkConfigExistence finds if the config exists
+func (s *Server) checkConfigExistence(tx store.Tx, spec *api.ServiceSpec) error {
+ container := spec.Task.GetContainer()
+ if container == nil {
+ return nil
+ }
+
+ var failedConfigs []string
+ for _, configRef := range container.Configs {
+ config := store.GetConfig(tx, configRef.ConfigID)
+ // Check to see if the config exists and configRef.ConfigName matches the actual configName
+ if config == nil || config.Spec.Annotations.Name != configRef.ConfigName {
+ failedConfigs = append(failedConfigs, configRef.ConfigName)
+ }
+ }
+
+ if len(failedConfigs) > 0 {
+ configStr := "configs"
+ if len(failedConfigs) == 1 {
+ configStr = "config"
+ }
+
+ return grpc.Errorf(codes.InvalidArgument, "%s not found: %v", configStr, strings.Join(failedConfigs, ", "))
+
+ }
+
+ return nil
+}
+
+// CreateService creates and returns a Service based on the provided ServiceSpec.
+// - Returns `InvalidArgument` if the ServiceSpec is malformed.
+// - Returns `Unimplemented` if the ServiceSpec references unimplemented features.
+// - Returns `AlreadyExists` if the ServiceID conflicts.
+// - Returns an error if the creation fails.
+func (s *Server) CreateService(ctx context.Context, request *api.CreateServiceRequest) (*api.CreateServiceResponse, error) {
+ if err := validateServiceSpec(request.Spec); err != nil {
+ return nil, err
+ }
+
+ if err := s.validateNetworks(request.Spec.Networks); err != nil {
+ return nil, err
+ }
+
+ if err := s.checkPortConflicts(request.Spec, ""); err != nil {
+ return nil, err
+ }
+
+ // TODO(aluzzardi): Consider using `Name` as a primary key to handle
+ // duplicate creations. See #65
+ service := &api.Service{
+ ID: identity.NewID(),
+ Spec: *request.Spec,
+ SpecVersion: &api.Version{},
+ }
+
+ if allocator.IsIngressNetworkNeeded(service) {
+ if _, err := allocator.GetIngressNetwork(s.store); err == allocator.ErrNoIngress {
+ return nil, grpc.Errorf(codes.FailedPrecondition, "service needs ingress network, but no ingress network is present")
+ }
+ }
+
+ err := s.store.Update(func(tx store.Tx) error {
+ // Check to see if all the secrets being added exist as objects
+ // in our datastore
+ err := s.checkSecretExistence(tx, request.Spec)
+ if err != nil {
+ return err
+ }
+ err = s.checkConfigExistence(tx, request.Spec)
+ if err != nil {
+ return err
+ }
+
+ return store.CreateService(tx, service)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return &api.CreateServiceResponse{
+ Service: service,
+ }, nil
+}
+
+// GetService returns a Service given a ServiceID.
+// - Returns `InvalidArgument` if ServiceID is not provided.
+// - Returns `NotFound` if the Service is not found.
+func (s *Server) GetService(ctx context.Context, request *api.GetServiceRequest) (*api.GetServiceResponse, error) {
+ if request.ServiceID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ var service *api.Service
+ s.store.View(func(tx store.ReadTx) {
+ service = store.GetService(tx, request.ServiceID)
+ })
+ if service == nil {
+ return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
+ }
+
+ if request.InsertDefaults {
+ service.Spec = *defaults.InterpolateService(&service.Spec)
+ }
+
+ return &api.GetServiceResponse{
+ Service: service,
+ }, nil
+}
+
+// UpdateService updates a Service referenced by ServiceID with the given ServiceSpec.
+// - Returns `NotFound` if the Service is not found.
+// - Returns `InvalidArgument` if the ServiceSpec is malformed.
+// - Returns `Unimplemented` if the ServiceSpec references unimplemented features.
+// - Returns an error if the update fails.
+func (s *Server) UpdateService(ctx context.Context, request *api.UpdateServiceRequest) (*api.UpdateServiceResponse, error) {
+ if request.ServiceID == "" || request.ServiceVersion == nil {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+ if err := validateServiceSpec(request.Spec); err != nil {
+ return nil, err
+ }
+
+ var service *api.Service
+ s.store.View(func(tx store.ReadTx) {
+ service = store.GetService(tx, request.ServiceID)
+ })
+ if service == nil {
+ return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
+ }
+
+ if request.Spec.Endpoint != nil && !reflect.DeepEqual(request.Spec.Endpoint, service.Spec.Endpoint) {
+ if err := s.checkPortConflicts(request.Spec, request.ServiceID); err != nil {
+ return nil, err
+ }
+ }
+
+ err := s.store.Update(func(tx store.Tx) error {
+ service = store.GetService(tx, request.ServiceID)
+ if service == nil {
+ return grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
+ }
+
+ // It's not okay to update Service.Spec.Networks on its own.
+ // However, if Service.Spec.Task.Networks is also being
+ // updated, that's okay (for example when migrating from the
+ // deprecated Spec.Networks field to Spec.Task.Networks).
+ if (len(request.Spec.Networks) != 0 || len(service.Spec.Networks) != 0) &&
+ !reflect.DeepEqual(request.Spec.Networks, service.Spec.Networks) &&
+ reflect.DeepEqual(request.Spec.Task.Networks, service.Spec.Task.Networks) {
+ return grpc.Errorf(codes.Unimplemented, errNetworkUpdateNotSupported.Error())
+ }
+
+ // Check to see if all the secrets being added exist as objects
+ // in our datastore
+ err := s.checkSecretExistence(tx, request.Spec)
+ if err != nil {
+ return err
+ }
+
+ err = s.checkConfigExistence(tx, request.Spec)
+ if err != nil {
+ return err
+ }
+
+ // orchestrator is designed to be stateless, so it should not deal
+ // with service mode change (comparing current config with previous config).
+ // proper way to change service mode is to delete and re-add.
+ if reflect.TypeOf(service.Spec.Mode) != reflect.TypeOf(request.Spec.Mode) {
+ return grpc.Errorf(codes.Unimplemented, errModeChangeNotAllowed.Error())
+ }
+
+ if service.Spec.Annotations.Name != request.Spec.Annotations.Name {
+ return grpc.Errorf(codes.Unimplemented, errRenameNotSupported.Error())
+ }
+
+ service.Meta.Version = *request.ServiceVersion
+
+ if request.Rollback == api.UpdateServiceRequest_PREVIOUS {
+ if service.PreviousSpec == nil {
+ return grpc.Errorf(codes.FailedPrecondition, "service %s does not have a previous spec", request.ServiceID)
+ }
+
+ curSpec := service.Spec.Copy()
+ curSpecVersion := service.SpecVersion
+ service.Spec = *service.PreviousSpec.Copy()
+ service.SpecVersion = service.PreviousSpecVersion.Copy()
+ service.PreviousSpec = curSpec
+ service.PreviousSpecVersion = curSpecVersion
+
+ service.UpdateStatus = &api.UpdateStatus{
+ State: api.UpdateStatus_ROLLBACK_STARTED,
+ Message: "manually requested rollback",
+ StartedAt: ptypes.MustTimestampProto(time.Now()),
+ }
+ } else {
+ service.PreviousSpec = service.Spec.Copy()
+ service.PreviousSpecVersion = service.SpecVersion
+ service.Spec = *request.Spec.Copy()
+ // Set spec version. Note that this will not match the
+ // service's Meta.Version after the store update. The
+ // versions for the spec and the service itself are not
+ // meant to be directly comparable.
+ service.SpecVersion = service.Meta.Version.Copy()
+
+ // Reset update status
+ service.UpdateStatus = nil
+ }
+
+ if allocator.IsIngressNetworkNeeded(service) {
+ if _, err := allocator.GetIngressNetwork(s.store); err == allocator.ErrNoIngress {
+ return grpc.Errorf(codes.FailedPrecondition, "service needs ingress network, but no ingress network is present")
+ }
+ }
+
+ return store.UpdateService(tx, service)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return &api.UpdateServiceResponse{
+ Service: service,
+ }, nil
+}
+
+// RemoveService removes a Service referenced by ServiceID.
+// - Returns `InvalidArgument` if ServiceID is not provided.
+// - Returns `NotFound` if the Service is not found.
+// - Returns an error if the deletion fails.
+func (s *Server) RemoveService(ctx context.Context, request *api.RemoveServiceRequest) (*api.RemoveServiceResponse, error) {
+ if request.ServiceID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ err := s.store.Update(func(tx store.Tx) error {
+ return store.DeleteService(tx, request.ServiceID)
+ })
+ if err != nil {
+ if err == store.ErrNotExist {
+ return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
+ }
+ return nil, err
+ }
+ return &api.RemoveServiceResponse{}, nil
+}
+
+func filterServices(candidates []*api.Service, filters ...func(*api.Service) bool) []*api.Service {
+ result := []*api.Service{}
+
+ for _, c := range candidates {
+ match := true
+ for _, f := range filters {
+ if !f(c) {
+ match = false
+ break
+ }
+ }
+ if match {
+ result = append(result, c)
+ }
+ }
+
+ return result
+}
+
+// ListServices returns a list of all services.
+func (s *Server) ListServices(ctx context.Context, request *api.ListServicesRequest) (*api.ListServicesResponse, error) {
+ var (
+ services []*api.Service
+ err error
+ )
+
+ s.store.View(func(tx store.ReadTx) {
+ switch {
+ case request.Filters != nil && len(request.Filters.Names) > 0:
+ services, err = store.FindServices(tx, buildFilters(store.ByName, request.Filters.Names))
+ case request.Filters != nil && len(request.Filters.NamePrefixes) > 0:
+ services, err = store.FindServices(tx, buildFilters(store.ByNamePrefix, request.Filters.NamePrefixes))
+ case request.Filters != nil && len(request.Filters.IDPrefixes) > 0:
+ services, err = store.FindServices(tx, buildFilters(store.ByIDPrefix, request.Filters.IDPrefixes))
+ case request.Filters != nil && len(request.Filters.Runtimes) > 0:
+ services, err = store.FindServices(tx, buildFilters(store.ByRuntime, request.Filters.Runtimes))
+ default:
+ services, err = store.FindServices(tx, store.All)
+ }
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ if request.Filters != nil {
+ services = filterServices(services,
+ func(e *api.Service) bool {
+ return filterContains(e.Spec.Annotations.Name, request.Filters.Names)
+ },
+ func(e *api.Service) bool {
+ return filterContainsPrefix(e.Spec.Annotations.Name, request.Filters.NamePrefixes)
+ },
+ func(e *api.Service) bool {
+ return filterContainsPrefix(e.ID, request.Filters.IDPrefixes)
+ },
+ func(e *api.Service) bool {
+ return filterMatchLabels(e.Spec.Annotations.Labels, request.Filters.Labels)
+ },
+ func(e *api.Service) bool {
+ if len(request.Filters.Runtimes) == 0 {
+ return true
+ }
+ r, err := naming.Runtime(e.Spec.Task)
+ if err != nil {
+ return false
+ }
+ return filterContains(r, request.Filters.Runtimes)
+ },
+ )
+ }
+
+ return &api.ListServicesResponse{
+ Services: services,
+ }, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/controlapi/task.go b/vendor/github.com/docker/swarmkit/manager/controlapi/task.go
new file mode 100644
index 0000000..d2ae215
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/controlapi/task.go
@@ -0,0 +1,170 @@
+package controlapi
+
+import (
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/naming"
+ "github.com/docker/swarmkit/manager/orchestrator"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+// GetTask returns a Task given a TaskID.
+// - Returns `InvalidArgument` if TaskID is not provided.
+// - Returns `NotFound` if the Task is not found.
+func (s *Server) GetTask(ctx context.Context, request *api.GetTaskRequest) (*api.GetTaskResponse, error) {
+ if request.TaskID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ var task *api.Task
+ s.store.View(func(tx store.ReadTx) {
+ task = store.GetTask(tx, request.TaskID)
+ })
+ if task == nil {
+ return nil, grpc.Errorf(codes.NotFound, "task %s not found", request.TaskID)
+ }
+ return &api.GetTaskResponse{
+ Task: task,
+ }, nil
+}
+
+// RemoveTask removes a Task referenced by TaskID.
+// - Returns `InvalidArgument` if TaskID is not provided.
+// - Returns `NotFound` if the Task is not found.
+// - Returns an error if the deletion fails.
+func (s *Server) RemoveTask(ctx context.Context, request *api.RemoveTaskRequest) (*api.RemoveTaskResponse, error) {
+ if request.TaskID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ err := s.store.Update(func(tx store.Tx) error {
+ return store.DeleteTask(tx, request.TaskID)
+ })
+ if err != nil {
+ if err == store.ErrNotExist {
+ return nil, grpc.Errorf(codes.NotFound, "task %s not found", request.TaskID)
+ }
+ return nil, err
+ }
+ return &api.RemoveTaskResponse{}, nil
+}
+
+func filterTasks(candidates []*api.Task, filters ...func(*api.Task) bool) []*api.Task {
+ result := []*api.Task{}
+
+ for _, c := range candidates {
+ match := true
+ for _, f := range filters {
+ if !f(c) {
+ match = false
+ break
+ }
+ }
+ if match {
+ result = append(result, c)
+ }
+ }
+
+ return result
+}
+
+// ListTasks returns a list of all tasks.
+func (s *Server) ListTasks(ctx context.Context, request *api.ListTasksRequest) (*api.ListTasksResponse, error) {
+ var (
+ tasks []*api.Task
+ err error
+ )
+
+ s.store.View(func(tx store.ReadTx) {
+ switch {
+ case request.Filters != nil && len(request.Filters.Names) > 0:
+ tasks, err = store.FindTasks(tx, buildFilters(store.ByName, request.Filters.Names))
+ case request.Filters != nil && len(request.Filters.NamePrefixes) > 0:
+ tasks, err = store.FindTasks(tx, buildFilters(store.ByNamePrefix, request.Filters.NamePrefixes))
+ case request.Filters != nil && len(request.Filters.IDPrefixes) > 0:
+ tasks, err = store.FindTasks(tx, buildFilters(store.ByIDPrefix, request.Filters.IDPrefixes))
+ case request.Filters != nil && len(request.Filters.ServiceIDs) > 0:
+ tasks, err = store.FindTasks(tx, buildFilters(store.ByServiceID, request.Filters.ServiceIDs))
+ case request.Filters != nil && len(request.Filters.Runtimes) > 0:
+ tasks, err = store.FindTasks(tx, buildFilters(store.ByRuntime, request.Filters.Runtimes))
+ case request.Filters != nil && len(request.Filters.NodeIDs) > 0:
+ tasks, err = store.FindTasks(tx, buildFilters(store.ByNodeID, request.Filters.NodeIDs))
+ case request.Filters != nil && len(request.Filters.DesiredStates) > 0:
+ filters := make([]store.By, 0, len(request.Filters.DesiredStates))
+ for _, v := range request.Filters.DesiredStates {
+ filters = append(filters, store.ByDesiredState(v))
+ }
+ tasks, err = store.FindTasks(tx, store.Or(filters...))
+ default:
+ tasks, err = store.FindTasks(tx, store.All)
+ }
+
+ if err != nil || request.Filters == nil {
+ return
+ }
+
+ tasks = filterTasks(tasks,
+ func(e *api.Task) bool {
+ return filterContains(naming.Task(e), request.Filters.Names)
+ },
+ func(e *api.Task) bool {
+ return filterContainsPrefix(naming.Task(e), request.Filters.NamePrefixes)
+ },
+ func(e *api.Task) bool {
+ return filterContainsPrefix(e.ID, request.Filters.IDPrefixes)
+ },
+ func(e *api.Task) bool {
+ return filterMatchLabels(e.ServiceAnnotations.Labels, request.Filters.Labels)
+ },
+ func(e *api.Task) bool {
+ return filterContains(e.ServiceID, request.Filters.ServiceIDs)
+ },
+ func(e *api.Task) bool {
+ return filterContains(e.NodeID, request.Filters.NodeIDs)
+ },
+ func(e *api.Task) bool {
+ if len(request.Filters.Runtimes) == 0 {
+ return true
+ }
+ r, err := naming.Runtime(e.Spec)
+ if err != nil {
+ return false
+ }
+ return filterContains(r, request.Filters.Runtimes)
+ },
+ func(e *api.Task) bool {
+ if len(request.Filters.DesiredStates) == 0 {
+ return true
+ }
+ for _, c := range request.Filters.DesiredStates {
+ if c == e.DesiredState {
+ return true
+ }
+ }
+ return false
+ },
+ func(e *api.Task) bool {
+ if !request.Filters.UpToDate {
+ return true
+ }
+
+ service := store.GetService(tx, e.ServiceID)
+ if service == nil {
+ return false
+ }
+
+ return !orchestrator.IsTaskDirty(service, e)
+ },
+ )
+ })
+
+ if err != nil {
+ return nil, err
+ }
+
+ return &api.ListTasksResponse{
+ Tasks: tasks,
+ }, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/deks.go b/vendor/github.com/docker/swarmkit/manager/deks.go
new file mode 100644
index 0000000..4813a67
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/deks.go
@@ -0,0 +1,269 @@
+package manager
+
+import (
+ "crypto/subtle"
+ "encoding/base64"
+ "fmt"
+
+ "github.com/docker/swarmkit/ca"
+ "github.com/docker/swarmkit/manager/encryption"
+ "github.com/docker/swarmkit/manager/state/raft"
+)
+
+const (
+ // the raft DEK (data encryption key) is stored in the TLS key as a header
+ // these are the header values
+ pemHeaderRaftDEK = "raft-dek"
+ pemHeaderRaftPendingDEK = "raft-dek-pending"
+ pemHeaderRaftDEKNeedsRotation = "raft-dek-needs-rotation"
+)
+
+// RaftDEKData contains all the data stored in TLS pem headers
+type RaftDEKData struct {
+ raft.EncryptionKeys
+ NeedsRotation bool
+}
+
+// UnmarshalHeaders loads the state of the DEK manager given the current TLS headers
+func (r RaftDEKData) UnmarshalHeaders(headers map[string]string, kekData ca.KEKData) (ca.PEMKeyHeaders, error) {
+ var (
+ currentDEK, pendingDEK []byte
+ err error
+ )
+
+ if currentDEKStr, ok := headers[pemHeaderRaftDEK]; ok {
+ currentDEK, err = decodePEMHeaderValue(currentDEKStr, kekData.KEK)
+ if err != nil {
+ return nil, err
+ }
+ }
+ if pendingDEKStr, ok := headers[pemHeaderRaftPendingDEK]; ok {
+ pendingDEK, err = decodePEMHeaderValue(pendingDEKStr, kekData.KEK)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ if pendingDEK != nil && currentDEK == nil {
+ return nil, fmt.Errorf("there is a pending DEK, but no current DEK")
+ }
+
+ _, ok := headers[pemHeaderRaftDEKNeedsRotation]
+ return RaftDEKData{
+ NeedsRotation: ok,
+ EncryptionKeys: raft.EncryptionKeys{
+ CurrentDEK: currentDEK,
+ PendingDEK: pendingDEK,
+ },
+ }, nil
+}
+
+// MarshalHeaders returns new headers given the current KEK
+func (r RaftDEKData) MarshalHeaders(kekData ca.KEKData) (map[string]string, error) {
+ headers := make(map[string]string)
+ for headerKey, contents := range map[string][]byte{
+ pemHeaderRaftDEK: r.CurrentDEK,
+ pemHeaderRaftPendingDEK: r.PendingDEK,
+ } {
+ if contents != nil {
+ dekStr, err := encodePEMHeaderValue(contents, kekData.KEK)
+ if err != nil {
+ return nil, err
+ }
+ headers[headerKey] = dekStr
+ }
+ }
+
+ if r.NeedsRotation {
+ headers[pemHeaderRaftDEKNeedsRotation] = "true"
+ }
+
+ // return a function that updates the dek data on write success
+ return headers, nil
+}
+
+// UpdateKEK optionally sets NeedRotation to true if we go from unlocked to locked
+func (r RaftDEKData) UpdateKEK(oldKEK, candidateKEK ca.KEKData) ca.PEMKeyHeaders {
+ if _, unlockedToLocked, err := compareKEKs(oldKEK, candidateKEK); err == nil && unlockedToLocked {
+ return RaftDEKData{
+ EncryptionKeys: r.EncryptionKeys,
+ NeedsRotation: true,
+ }
+ }
+ return r
+}
+
+// Returns whether the old KEK should be replaced with the new KEK, whether we went from
+// unlocked to locked, and whether there was an error (the versions are the same, but the
+// keks are different)
+func compareKEKs(oldKEK, candidateKEK ca.KEKData) (bool, bool, error) {
+ keksEqual := subtle.ConstantTimeCompare(oldKEK.KEK, candidateKEK.KEK) == 1
+ switch {
+ case oldKEK.Version == candidateKEK.Version && !keksEqual:
+ return false, false, fmt.Errorf("candidate KEK has the same version as the current KEK, but a different KEK value")
+ case oldKEK.Version >= candidateKEK.Version || keksEqual:
+ return false, false, nil
+ default:
+ return true, oldKEK.KEK == nil, nil
+ }
+}
+
+// RaftDEKManager manages the raft DEK keys using TLS headers
+type RaftDEKManager struct {
+ kw ca.KeyWriter
+ rotationCh chan struct{}
+}
+
+var errNoUpdateNeeded = fmt.Errorf("don't need to rotate or update")
+
+// this error is returned if the KeyReadWriter's PEMKeyHeaders object is no longer a RaftDEKData object -
+// this can happen if the node is no longer a manager, for example
+var errNotUsingRaftDEKData = fmt.Errorf("RaftDEKManager can no longer store and manage TLS key headers")
+
+// NewRaftDEKManager returns a RaftDEKManager that uses the current key writer
+// and header manager
+func NewRaftDEKManager(kw ca.KeyWriter) (*RaftDEKManager, error) {
+ // If there is no current DEK, generate one and write it to disk
+ err := kw.ViewAndUpdateHeaders(func(h ca.PEMKeyHeaders) (ca.PEMKeyHeaders, error) {
+ dekData, ok := h.(RaftDEKData)
+ // it wasn't a raft DEK manager before - just replace it
+ if !ok || dekData.CurrentDEK == nil {
+ return RaftDEKData{
+ EncryptionKeys: raft.EncryptionKeys{
+ CurrentDEK: encryption.GenerateSecretKey(),
+ },
+ }, nil
+ }
+ return nil, errNoUpdateNeeded
+ })
+ if err != nil && err != errNoUpdateNeeded {
+ return nil, err
+ }
+ return &RaftDEKManager{
+ kw: kw,
+ rotationCh: make(chan struct{}, 1),
+ }, nil
+}
+
+// NeedsRotation returns a boolean about whether we should do a rotation
+func (r *RaftDEKManager) NeedsRotation() bool {
+ h, _ := r.kw.GetCurrentState()
+ data, ok := h.(RaftDEKData)
+ if !ok {
+ return false
+ }
+ return data.NeedsRotation || data.EncryptionKeys.PendingDEK != nil
+}
+
+// GetKeys returns the current set of DEKs. If NeedsRotation is true, and there
+// is no existing PendingDEK, it will try to create one. If there are any errors
+// doing so, just return the original.
+func (r *RaftDEKManager) GetKeys() raft.EncryptionKeys {
+ var newKeys, originalKeys raft.EncryptionKeys
+ err := r.kw.ViewAndUpdateHeaders(func(h ca.PEMKeyHeaders) (ca.PEMKeyHeaders, error) {
+ data, ok := h.(RaftDEKData)
+ if !ok {
+ return nil, errNotUsingRaftDEKData
+ }
+ originalKeys = data.EncryptionKeys
+ if !data.NeedsRotation || data.PendingDEK != nil {
+ return nil, errNoUpdateNeeded
+ }
+ newKeys = raft.EncryptionKeys{
+ CurrentDEK: data.CurrentDEK,
+ PendingDEK: encryption.GenerateSecretKey(),
+ }
+ return RaftDEKData{EncryptionKeys: newKeys}, nil
+ })
+ if err != nil {
+ return originalKeys
+ }
+ return newKeys
+}
+
+// RotationNotify the channel used to notify subscribers as to whether there
+// should be a rotation done
+func (r *RaftDEKManager) RotationNotify() chan struct{} {
+ return r.rotationCh
+}
+
+// UpdateKeys will set the updated encryption keys in the headers. This finishes
+// a rotation, and is expected to set the CurrentDEK to the previous PendingDEK.
+func (r *RaftDEKManager) UpdateKeys(newKeys raft.EncryptionKeys) error {
+ return r.kw.ViewAndUpdateHeaders(func(h ca.PEMKeyHeaders) (ca.PEMKeyHeaders, error) {
+ data, ok := h.(RaftDEKData)
+ if !ok {
+ return nil, errNotUsingRaftDEKData
+ }
+ // If there is no current DEK, we are basically wiping out all DEKs (no header object)
+ if newKeys.CurrentDEK == nil {
+ return nil, nil
+ }
+ return RaftDEKData{
+ EncryptionKeys: newKeys,
+ NeedsRotation: data.NeedsRotation,
+ }, nil
+ })
+}
+
+// MaybeUpdateKEK does a KEK rotation if one is required. Returns whether
+// the kek was updated, whether it went from unlocked to locked, and any errors.
+func (r *RaftDEKManager) MaybeUpdateKEK(candidateKEK ca.KEKData) (bool, bool, error) {
+ var updated, unlockedToLocked bool
+ err := r.kw.ViewAndRotateKEK(func(currentKEK ca.KEKData, h ca.PEMKeyHeaders) (ca.KEKData, ca.PEMKeyHeaders, error) {
+ var err error
+ updated, unlockedToLocked, err = compareKEKs(currentKEK, candidateKEK)
+ if err == nil && !updated { // if we don't need to rotate the KEK, don't bother updating
+ err = errNoUpdateNeeded
+ }
+ if err != nil {
+ return ca.KEKData{}, nil, err
+ }
+
+ data, ok := h.(RaftDEKData)
+ if !ok {
+ return ca.KEKData{}, nil, errNotUsingRaftDEKData
+ }
+
+ if unlockedToLocked {
+ data.NeedsRotation = true
+ }
+ return candidateKEK, data, nil
+ })
+ if err == errNoUpdateNeeded {
+ err = nil
+ }
+
+ if err == nil && unlockedToLocked {
+ r.rotationCh <- struct{}{}
+ }
+ return updated, unlockedToLocked, err
+}
+
+func decodePEMHeaderValue(headerValue string, kek []byte) ([]byte, error) {
+ var decrypter encryption.Decrypter = encryption.NoopCrypter
+ if kek != nil {
+ _, decrypter = encryption.Defaults(kek)
+ }
+ valueBytes, err := base64.StdEncoding.DecodeString(headerValue)
+ if err != nil {
+ return nil, err
+ }
+ result, err := encryption.Decrypt(valueBytes, decrypter)
+ if err != nil {
+ return nil, ca.ErrInvalidKEK{Wrapped: err}
+ }
+ return result, nil
+}
+
+func encodePEMHeaderValue(headerValue []byte, kek []byte) (string, error) {
+ var encrypter encryption.Encrypter = encryption.NoopCrypter
+ if kek != nil {
+ encrypter, _ = encryption.Defaults(kek)
+ }
+ encrypted, err := encryption.Encrypt(headerValue, encrypter)
+ if err != nil {
+ return "", err
+ }
+ return base64.StdEncoding.EncodeToString(encrypted), nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/dirty.go b/vendor/github.com/docker/swarmkit/manager/dirty.go
new file mode 100644
index 0000000..c989ec2
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/dirty.go
@@ -0,0 +1,57 @@
+package manager
+
+import (
+ "reflect"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/state/store"
+)
+
+// IsStateDirty returns true if any objects have been added to raft which make
+// the state "dirty". Currently, the existence of any object other than the
+// default cluster or the local node implies a dirty state.
+func (m *Manager) IsStateDirty() (bool, error) {
+ var (
+ storeSnapshot *api.StoreSnapshot
+ err error
+ )
+ m.raftNode.MemoryStore().View(func(readTx store.ReadTx) {
+ storeSnapshot, err = m.raftNode.MemoryStore().Save(readTx)
+ })
+
+ if err != nil {
+ return false, err
+ }
+
+ // Check Nodes and Clusters fields.
+ nodeID := m.config.SecurityConfig.ClientTLSCreds.NodeID()
+ if len(storeSnapshot.Nodes) > 1 || (len(storeSnapshot.Nodes) == 1 && storeSnapshot.Nodes[0].ID != nodeID) {
+ return true, nil
+ }
+
+ clusterID := m.config.SecurityConfig.ClientTLSCreds.Organization()
+ if len(storeSnapshot.Clusters) > 1 || (len(storeSnapshot.Clusters) == 1 && storeSnapshot.Clusters[0].ID != clusterID) {
+ return true, nil
+ }
+
+ // Use reflection to check that other fields don't have values. This
+ // lets us implement a whitelist-type approach, where we don't need to
+ // remember to add individual types here.
+
+ val := reflect.ValueOf(*storeSnapshot)
+ numFields := val.NumField()
+
+ for i := 0; i != numFields; i++ {
+ field := val.Field(i)
+ structField := val.Type().Field(i)
+ if structField.Type.Kind() != reflect.Slice {
+ panic("unexpected field type in StoreSnapshot")
+ }
+ if structField.Name != "Nodes" && structField.Name != "Clusters" && structField.Name != "Networks" && field.Len() != 0 {
+ // One of the other data types has an entry
+ return true, nil
+ }
+ }
+
+ return false, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/dispatcher/assignments.go b/vendor/github.com/docker/swarmkit/manager/dispatcher/assignments.go
new file mode 100644
index 0000000..871519e
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/dispatcher/assignments.go
@@ -0,0 +1,247 @@
+package dispatcher
+
+import (
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/equality"
+ "github.com/docker/swarmkit/manager/state/store"
+)
+
+// Used as a key in tasksUsingDependency and changes. Only using the
+// ID could cause (rare) collisions between different types of
+// objects, so we also include the type of object in the key.
+type objectType int
+
+const (
+ typeTask objectType = iota
+ typeSecret
+ typeConfig
+)
+
+type typeAndID struct {
+ id string
+ objType objectType
+}
+
+type assignmentSet struct {
+ tasksMap map[string]*api.Task
+ tasksUsingDependency map[typeAndID]map[string]struct{}
+ changes map[typeAndID]*api.AssignmentChange
+
+ log *logrus.Entry
+}
+
+func newAssignmentSet(log *logrus.Entry) *assignmentSet {
+ return &assignmentSet{
+ changes: make(map[typeAndID]*api.AssignmentChange),
+ tasksMap: make(map[string]*api.Task),
+ tasksUsingDependency: make(map[typeAndID]map[string]struct{}),
+ log: log,
+ }
+}
+
+func (a *assignmentSet) addTaskDependencies(readTx store.ReadTx, t *api.Task) {
+ var secrets []*api.SecretReference
+ container := t.Spec.GetContainer()
+ if container != nil {
+ secrets = container.Secrets
+ }
+ for _, secretRef := range secrets {
+ secretID := secretRef.SecretID
+ mapKey := typeAndID{objType: typeSecret, id: secretID}
+
+ if len(a.tasksUsingDependency[mapKey]) == 0 {
+ a.tasksUsingDependency[mapKey] = make(map[string]struct{})
+
+ secret := store.GetSecret(readTx, secretID)
+ if secret == nil {
+ a.log.WithFields(logrus.Fields{
+ "secret.id": secretID,
+ "secret.name": secretRef.SecretName,
+ }).Debug("secret not found")
+ continue
+ }
+
+ // If the secret was found, add this secret to
+ // our set that we send down.
+ a.changes[mapKey] = &api.AssignmentChange{
+ Assignment: &api.Assignment{
+ Item: &api.Assignment_Secret{
+ Secret: secret,
+ },
+ },
+ Action: api.AssignmentChange_AssignmentActionUpdate,
+ }
+ }
+ a.tasksUsingDependency[mapKey][t.ID] = struct{}{}
+ }
+
+ var configs []*api.ConfigReference
+ if container != nil {
+ configs = container.Configs
+ }
+ for _, configRef := range configs {
+ configID := configRef.ConfigID
+ mapKey := typeAndID{objType: typeConfig, id: configID}
+
+ if len(a.tasksUsingDependency[mapKey]) == 0 {
+ a.tasksUsingDependency[mapKey] = make(map[string]struct{})
+
+ config := store.GetConfig(readTx, configID)
+ if config == nil {
+ a.log.WithFields(logrus.Fields{
+ "config.id": configID,
+ "config.name": configRef.ConfigName,
+ }).Debug("config not found")
+ continue
+ }
+
+ // If the config was found, add this config to
+ // our set that we send down.
+ a.changes[mapKey] = &api.AssignmentChange{
+ Assignment: &api.Assignment{
+ Item: &api.Assignment_Config{
+ Config: config,
+ },
+ },
+ Action: api.AssignmentChange_AssignmentActionUpdate,
+ }
+ }
+ a.tasksUsingDependency[mapKey][t.ID] = struct{}{}
+ }
+}
+
+func (a *assignmentSet) releaseDependency(mapKey typeAndID, assignment *api.Assignment, taskID string) bool {
+ delete(a.tasksUsingDependency[mapKey], taskID)
+ if len(a.tasksUsingDependency[mapKey]) != 0 {
+ return false
+ }
+ // No tasks are using the dependency anymore
+ delete(a.tasksUsingDependency, mapKey)
+ a.changes[mapKey] = &api.AssignmentChange{
+ Assignment: assignment,
+ Action: api.AssignmentChange_AssignmentActionRemove,
+ }
+ return true
+}
+
+func (a *assignmentSet) releaseTaskDependencies(t *api.Task) bool {
+ var modified bool
+ container := t.Spec.GetContainer()
+
+ var secrets []*api.SecretReference
+ if container != nil {
+ secrets = container.Secrets
+ }
+
+ for _, secretRef := range secrets {
+ secretID := secretRef.SecretID
+ mapKey := typeAndID{objType: typeSecret, id: secretID}
+ assignment := &api.Assignment{
+ Item: &api.Assignment_Secret{
+ Secret: &api.Secret{ID: secretID},
+ },
+ }
+ if a.releaseDependency(mapKey, assignment, t.ID) {
+ modified = true
+ }
+ }
+
+ var configs []*api.ConfigReference
+ if container != nil {
+ configs = container.Configs
+ }
+
+ for _, configRef := range configs {
+ configID := configRef.ConfigID
+ mapKey := typeAndID{objType: typeConfig, id: configID}
+ assignment := &api.Assignment{
+ Item: &api.Assignment_Config{
+ Config: &api.Config{ID: configID},
+ },
+ }
+ if a.releaseDependency(mapKey, assignment, t.ID) {
+ modified = true
+ }
+ }
+
+ return modified
+}
+
+func (a *assignmentSet) addOrUpdateTask(readTx store.ReadTx, t *api.Task) bool {
+ // We only care about tasks that are ASSIGNED or higher.
+ if t.Status.State < api.TaskStateAssigned {
+ return false
+ }
+
+ if oldTask, exists := a.tasksMap[t.ID]; exists {
+ // States ASSIGNED and below are set by the orchestrator/scheduler,
+ // not the agent, so tasks in these states need to be sent to the
+ // agent even if nothing else has changed.
+ if equality.TasksEqualStable(oldTask, t) && t.Status.State > api.TaskStateAssigned {
+ // this update should not trigger a task change for the agent
+ a.tasksMap[t.ID] = t
+ // If this task got updated to a final state, let's release
+ // the dependencies that are being used by the task
+ if t.Status.State > api.TaskStateRunning {
+ // If releasing the dependencies caused us to
+ // remove something from the assignment set,
+ // mark one modification.
+ return a.releaseTaskDependencies(t)
+ }
+ return false
+ }
+ } else if t.Status.State <= api.TaskStateRunning {
+ // If this task wasn't part of the assignment set before, and it's <= RUNNING
+ // add the dependencies it references to the assignment.
+ // Task states > RUNNING are worker reported only, are never created in
+ // a > RUNNING state.
+ a.addTaskDependencies(readTx, t)
+ }
+ a.tasksMap[t.ID] = t
+ a.changes[typeAndID{objType: typeTask, id: t.ID}] = &api.AssignmentChange{
+ Assignment: &api.Assignment{
+ Item: &api.Assignment_Task{
+ Task: t,
+ },
+ },
+ Action: api.AssignmentChange_AssignmentActionUpdate,
+ }
+ return true
+}
+
+func (a *assignmentSet) removeTask(t *api.Task) bool {
+ if _, exists := a.tasksMap[t.ID]; !exists {
+ return false
+ }
+
+ a.changes[typeAndID{objType: typeTask, id: t.ID}] = &api.AssignmentChange{
+ Assignment: &api.Assignment{
+ Item: &api.Assignment_Task{
+ Task: &api.Task{ID: t.ID},
+ },
+ },
+ Action: api.AssignmentChange_AssignmentActionRemove,
+ }
+
+ delete(a.tasksMap, t.ID)
+
+ // Release the dependencies being used by this task.
+ // Ignoring the return here. We will always mark this as a
+ // modification, since a task is being removed.
+ a.releaseTaskDependencies(t)
+ return true
+}
+
+func (a *assignmentSet) message() api.AssignmentsMessage {
+ var message api.AssignmentsMessage
+ for _, change := range a.changes {
+ message.Changes = append(message.Changes, change)
+ }
+
+ // The the set of changes is reinitialized to prepare for formation
+ // of the next message.
+ a.changes = make(map[typeAndID]*api.AssignmentChange)
+
+ return message
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/dispatcher/dispatcher.go b/vendor/github.com/docker/swarmkit/manager/dispatcher/dispatcher.go
new file mode 100644
index 0000000..33275f4
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/dispatcher/dispatcher.go
@@ -0,0 +1,1250 @@
+package dispatcher
+
+import (
+ "fmt"
+ "net"
+ "strconv"
+ "sync"
+ "time"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/transport"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/equality"
+ "github.com/docker/swarmkit/ca"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/remotes"
+ "github.com/docker/swarmkit/watch"
+ gogotypes "github.com/gogo/protobuf/types"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+const (
+ // DefaultHeartBeatPeriod is used for setting default value in cluster config
+ // and in case if cluster config is missing.
+ DefaultHeartBeatPeriod = 5 * time.Second
+ defaultHeartBeatEpsilon = 500 * time.Millisecond
+ defaultGracePeriodMultiplier = 3
+ defaultRateLimitPeriod = 8 * time.Second
+
+ // maxBatchItems is the threshold of queued writes that should
+ // trigger an actual transaction to commit them to the shared store.
+ maxBatchItems = 10000
+
+ // maxBatchInterval needs to strike a balance between keeping
+ // latency low, and realizing opportunities to combine many writes
+ // into a single transaction. A fraction of a second feels about
+ // right.
+ maxBatchInterval = 100 * time.Millisecond
+
+ modificationBatchLimit = 100
+ batchingWaitTime = 100 * time.Millisecond
+
+ // defaultNodeDownPeriod specifies the default time period we
+ // wait before moving tasks assigned to down nodes to ORPHANED
+ // state.
+ defaultNodeDownPeriod = 24 * time.Hour
+)
+
+var (
+ // ErrNodeAlreadyRegistered returned if node with same ID was already
+ // registered with this dispatcher.
+ ErrNodeAlreadyRegistered = errors.New("node already registered")
+ // ErrNodeNotRegistered returned if node with such ID wasn't registered
+ // with this dispatcher.
+ ErrNodeNotRegistered = errors.New("node not registered")
+ // ErrSessionInvalid returned when the session in use is no longer valid.
+ // The node should re-register and start a new session.
+ ErrSessionInvalid = errors.New("session invalid")
+ // ErrNodeNotFound returned when the Node doesn't exist in raft.
+ ErrNodeNotFound = errors.New("node not found")
+)
+
+// Config is configuration for Dispatcher. For default you should use
+// DefaultConfig.
+type Config struct {
+ HeartbeatPeriod time.Duration
+ HeartbeatEpsilon time.Duration
+ // RateLimitPeriod specifies how often node with same ID can try to register
+ // new session.
+ RateLimitPeriod time.Duration
+ GracePeriodMultiplier int
+}
+
+// DefaultConfig returns default config for Dispatcher.
+func DefaultConfig() *Config {
+ return &Config{
+ HeartbeatPeriod: DefaultHeartBeatPeriod,
+ HeartbeatEpsilon: defaultHeartBeatEpsilon,
+ RateLimitPeriod: defaultRateLimitPeriod,
+ GracePeriodMultiplier: defaultGracePeriodMultiplier,
+ }
+}
+
+// Cluster is interface which represent raft cluster. manager/state/raft.Node
+// is implements it. This interface needed only for easier unit-testing.
+type Cluster interface {
+ GetMemberlist() map[uint64]*api.RaftMember
+ SubscribePeers() (chan events.Event, func())
+ MemoryStore() *store.MemoryStore
+}
+
+// nodeUpdate provides a new status and/or description to apply to a node
+// object.
+type nodeUpdate struct {
+ status *api.NodeStatus
+ description *api.NodeDescription
+}
+
+// clusterUpdate is an object that stores an update to the cluster that should trigger
+// a new session message. These are pointers to indicate the difference between
+// "there is no update" and "update this to nil"
+type clusterUpdate struct {
+ managerUpdate *[]*api.WeightedPeer
+ bootstrapKeyUpdate *[]*api.EncryptionKey
+ rootCAUpdate *[]byte
+}
+
+// Dispatcher is responsible for dispatching tasks and tracking agent health.
+type Dispatcher struct {
+ mu sync.Mutex
+ wg sync.WaitGroup
+ nodes *nodeStore
+ store *store.MemoryStore
+ lastSeenManagers []*api.WeightedPeer
+ networkBootstrapKeys []*api.EncryptionKey
+ lastSeenRootCert []byte
+ config *Config
+ cluster Cluster
+ ctx context.Context
+ cancel context.CancelFunc
+ clusterUpdateQueue *watch.Queue
+
+ taskUpdates map[string]*api.TaskStatus // indexed by task ID
+ taskUpdatesLock sync.Mutex
+
+ nodeUpdates map[string]nodeUpdate // indexed by node ID
+ nodeUpdatesLock sync.Mutex
+
+ downNodes *nodeStore
+
+ processUpdatesTrigger chan struct{}
+
+ // for waiting for the next task/node batch update
+ processUpdatesLock sync.Mutex
+ processUpdatesCond *sync.Cond
+}
+
+// New returns Dispatcher with cluster interface(usually raft.Node).
+func New(cluster Cluster, c *Config) *Dispatcher {
+ d := &Dispatcher{
+ nodes: newNodeStore(c.HeartbeatPeriod, c.HeartbeatEpsilon, c.GracePeriodMultiplier, c.RateLimitPeriod),
+ downNodes: newNodeStore(defaultNodeDownPeriod, 0, 1, 0),
+ store: cluster.MemoryStore(),
+ cluster: cluster,
+ processUpdatesTrigger: make(chan struct{}, 1),
+ config: c,
+ }
+
+ d.processUpdatesCond = sync.NewCond(&d.processUpdatesLock)
+
+ return d
+}
+
+func getWeightedPeers(cluster Cluster) []*api.WeightedPeer {
+ members := cluster.GetMemberlist()
+ var mgrs []*api.WeightedPeer
+ for _, m := range members {
+ mgrs = append(mgrs, &api.WeightedPeer{
+ Peer: &api.Peer{
+ NodeID: m.NodeID,
+ Addr: m.Addr,
+ },
+
+ // TODO(stevvooe): Calculate weight of manager selection based on
+ // cluster-level observations, such as number of connections and
+ // load.
+ Weight: remotes.DefaultObservationWeight,
+ })
+ }
+ return mgrs
+}
+
+// Run runs dispatcher tasks which should be run on leader dispatcher.
+// Dispatcher can be stopped with cancelling ctx or calling Stop().
+func (d *Dispatcher) Run(ctx context.Context) error {
+ d.taskUpdatesLock.Lock()
+ d.taskUpdates = make(map[string]*api.TaskStatus)
+ d.taskUpdatesLock.Unlock()
+
+ d.nodeUpdatesLock.Lock()
+ d.nodeUpdates = make(map[string]nodeUpdate)
+ d.nodeUpdatesLock.Unlock()
+
+ d.mu.Lock()
+ if d.isRunning() {
+ d.mu.Unlock()
+ return errors.New("dispatcher is already running")
+ }
+ ctx = log.WithModule(ctx, "dispatcher")
+ if err := d.markNodesUnknown(ctx); err != nil {
+ log.G(ctx).Errorf(`failed to move all nodes to "unknown" state: %v`, err)
+ }
+ configWatcher, cancel, err := store.ViewAndWatch(
+ d.store,
+ func(readTx store.ReadTx) error {
+ clusters, err := store.FindClusters(readTx, store.ByName(store.DefaultClusterName))
+ if err != nil {
+ return err
+ }
+ if err == nil && len(clusters) == 1 {
+ heartbeatPeriod, err := gogotypes.DurationFromProto(clusters[0].Spec.Dispatcher.HeartbeatPeriod)
+ if err == nil && heartbeatPeriod > 0 {
+ d.config.HeartbeatPeriod = heartbeatPeriod
+ }
+ if clusters[0].NetworkBootstrapKeys != nil {
+ d.networkBootstrapKeys = clusters[0].NetworkBootstrapKeys
+ }
+ d.lastSeenRootCert = clusters[0].RootCA.CACert
+ }
+ return nil
+ },
+ api.EventUpdateCluster{},
+ )
+ if err != nil {
+ d.mu.Unlock()
+ return err
+ }
+ // set queue here to guarantee that Close will close it
+ d.clusterUpdateQueue = watch.NewQueue()
+
+ peerWatcher, peerCancel := d.cluster.SubscribePeers()
+ defer peerCancel()
+ d.lastSeenManagers = getWeightedPeers(d.cluster)
+
+ defer cancel()
+ d.ctx, d.cancel = context.WithCancel(ctx)
+ ctx = d.ctx
+ d.wg.Add(1)
+ defer d.wg.Done()
+ d.mu.Unlock()
+
+ publishManagers := func(peers []*api.Peer) {
+ var mgrs []*api.WeightedPeer
+ for _, p := range peers {
+ mgrs = append(mgrs, &api.WeightedPeer{
+ Peer: p,
+ Weight: remotes.DefaultObservationWeight,
+ })
+ }
+ d.mu.Lock()
+ d.lastSeenManagers = mgrs
+ d.mu.Unlock()
+ d.clusterUpdateQueue.Publish(clusterUpdate{managerUpdate: &mgrs})
+ }
+
+ batchTimer := time.NewTimer(maxBatchInterval)
+ defer batchTimer.Stop()
+
+ for {
+ select {
+ case ev := <-peerWatcher:
+ publishManagers(ev.([]*api.Peer))
+ case <-d.processUpdatesTrigger:
+ d.processUpdates(ctx)
+ batchTimer.Reset(maxBatchInterval)
+ case <-batchTimer.C:
+ d.processUpdates(ctx)
+ batchTimer.Reset(maxBatchInterval)
+ case v := <-configWatcher:
+ cluster := v.(api.EventUpdateCluster)
+ d.mu.Lock()
+ if cluster.Cluster.Spec.Dispatcher.HeartbeatPeriod != nil {
+ // ignore error, since Spec has passed validation before
+ heartbeatPeriod, _ := gogotypes.DurationFromProto(cluster.Cluster.Spec.Dispatcher.HeartbeatPeriod)
+ if heartbeatPeriod != d.config.HeartbeatPeriod {
+ // only call d.nodes.updatePeriod when heartbeatPeriod changes
+ d.config.HeartbeatPeriod = heartbeatPeriod
+ d.nodes.updatePeriod(d.config.HeartbeatPeriod, d.config.HeartbeatEpsilon, d.config.GracePeriodMultiplier)
+ }
+ }
+ d.lastSeenRootCert = cluster.Cluster.RootCA.CACert
+ d.networkBootstrapKeys = cluster.Cluster.NetworkBootstrapKeys
+ d.mu.Unlock()
+ d.clusterUpdateQueue.Publish(clusterUpdate{
+ bootstrapKeyUpdate: &cluster.Cluster.NetworkBootstrapKeys,
+ rootCAUpdate: &cluster.Cluster.RootCA.CACert,
+ })
+ case <-ctx.Done():
+ return nil
+ }
+ }
+}
+
+// Stop stops dispatcher and closes all grpc streams.
+func (d *Dispatcher) Stop() error {
+ d.mu.Lock()
+ if !d.isRunning() {
+ d.mu.Unlock()
+ return errors.New("dispatcher is already stopped")
+ }
+ d.cancel()
+ d.mu.Unlock()
+ d.nodes.Clean()
+
+ d.processUpdatesLock.Lock()
+ // In case there are any waiters. There is no chance of any starting
+ // after this point, because they check if the context is canceled
+ // before waiting.
+ d.processUpdatesCond.Broadcast()
+ d.processUpdatesLock.Unlock()
+
+ d.clusterUpdateQueue.Close()
+
+ d.wg.Wait()
+
+ return nil
+}
+
+func (d *Dispatcher) isRunningLocked() (context.Context, error) {
+ d.mu.Lock()
+ if !d.isRunning() {
+ d.mu.Unlock()
+ return nil, grpc.Errorf(codes.Aborted, "dispatcher is stopped")
+ }
+ ctx := d.ctx
+ d.mu.Unlock()
+ return ctx, nil
+}
+
+func (d *Dispatcher) markNodesUnknown(ctx context.Context) error {
+ log := log.G(ctx).WithField("method", "(*Dispatcher).markNodesUnknown")
+ var nodes []*api.Node
+ var err error
+ d.store.View(func(tx store.ReadTx) {
+ nodes, err = store.FindNodes(tx, store.All)
+ })
+ if err != nil {
+ return errors.Wrap(err, "failed to get list of nodes")
+ }
+ err = d.store.Batch(func(batch *store.Batch) error {
+ for _, n := range nodes {
+ err := batch.Update(func(tx store.Tx) error {
+ // check if node is still here
+ node := store.GetNode(tx, n.ID)
+ if node == nil {
+ return nil
+ }
+ // do not try to resurrect down nodes
+ if node.Status.State == api.NodeStatus_DOWN {
+ nodeCopy := node
+ expireFunc := func() {
+ if err := d.moveTasksToOrphaned(nodeCopy.ID); err != nil {
+ log.WithError(err).Error(`failed to move all tasks to "ORPHANED" state`)
+ }
+
+ d.downNodes.Delete(nodeCopy.ID)
+ }
+
+ d.downNodes.Add(nodeCopy, expireFunc)
+ return nil
+ }
+
+ node.Status.State = api.NodeStatus_UNKNOWN
+ node.Status.Message = `Node moved to "unknown" state due to leadership change in cluster`
+
+ nodeID := node.ID
+
+ expireFunc := func() {
+ log := log.WithField("node", nodeID)
+ log.Debug("heartbeat expiration for unknown node")
+ if err := d.markNodeNotReady(nodeID, api.NodeStatus_DOWN, `heartbeat failure for node in "unknown" state`); err != nil {
+ log.WithError(err).Error(`failed deregistering node after heartbeat expiration for node in "unknown" state`)
+ }
+ }
+ if err := d.nodes.AddUnknown(node, expireFunc); err != nil {
+ return errors.Wrap(err, `adding node in "unknown" state to node store failed`)
+ }
+ if err := store.UpdateNode(tx, node); err != nil {
+ return errors.Wrap(err, "update failed")
+ }
+ return nil
+ })
+ if err != nil {
+ log.WithField("node", n.ID).WithError(err).Error(`failed to move node to "unknown" state`)
+ }
+ }
+ return nil
+ })
+ return err
+}
+
+func (d *Dispatcher) isRunning() bool {
+ if d.ctx == nil {
+ return false
+ }
+ select {
+ case <-d.ctx.Done():
+ return false
+ default:
+ }
+ return true
+}
+
+// markNodeReady updates the description of a node, updates its address, and sets status to READY
+// this is used during registration when a new node description is provided
+// and during node updates when the node description changes
+func (d *Dispatcher) markNodeReady(ctx context.Context, nodeID string, description *api.NodeDescription, addr string) error {
+ d.nodeUpdatesLock.Lock()
+ d.nodeUpdates[nodeID] = nodeUpdate{
+ status: &api.NodeStatus{
+ State: api.NodeStatus_READY,
+ Addr: addr,
+ },
+ description: description,
+ }
+ numUpdates := len(d.nodeUpdates)
+ d.nodeUpdatesLock.Unlock()
+
+ // Node is marked ready. Remove the node from down nodes if it
+ // is there.
+ d.downNodes.Delete(nodeID)
+
+ if numUpdates >= maxBatchItems {
+ select {
+ case d.processUpdatesTrigger <- struct{}{}:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+
+ }
+
+ // Wait until the node update batch happens before unblocking register.
+ d.processUpdatesLock.Lock()
+ defer d.processUpdatesLock.Unlock()
+
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+ d.processUpdatesCond.Wait()
+
+ return nil
+}
+
+// gets the node IP from the context of a grpc call
+func nodeIPFromContext(ctx context.Context) (string, error) {
+ nodeInfo, err := ca.RemoteNode(ctx)
+ if err != nil {
+ return "", err
+ }
+ addr, _, err := net.SplitHostPort(nodeInfo.RemoteAddr)
+ if err != nil {
+ return "", errors.Wrap(err, "unable to get ip from addr:port")
+ }
+ return addr, nil
+}
+
+// register is used for registration of node with particular dispatcher.
+func (d *Dispatcher) register(ctx context.Context, nodeID string, description *api.NodeDescription) (string, error) {
+ // prevent register until we're ready to accept it
+ dctx, err := d.isRunningLocked()
+ if err != nil {
+ return "", err
+ }
+
+ if err := d.nodes.CheckRateLimit(nodeID); err != nil {
+ return "", err
+ }
+
+ // TODO(stevvooe): Validate node specification.
+ var node *api.Node
+ d.store.View(func(tx store.ReadTx) {
+ node = store.GetNode(tx, nodeID)
+ })
+ if node == nil {
+ return "", ErrNodeNotFound
+ }
+
+ addr, err := nodeIPFromContext(ctx)
+ if err != nil {
+ log.G(ctx).Debug(err.Error())
+ }
+
+ if err := d.markNodeReady(dctx, nodeID, description, addr); err != nil {
+ return "", err
+ }
+
+ expireFunc := func() {
+ log.G(ctx).Debugf("heartbeat expiration")
+ if err := d.markNodeNotReady(nodeID, api.NodeStatus_DOWN, "heartbeat failure"); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed deregistering node after heartbeat expiration")
+ }
+ }
+
+ rn := d.nodes.Add(node, expireFunc)
+
+ // NOTE(stevvooe): We need be a little careful with re-registration. The
+ // current implementation just matches the node id and then gives away the
+ // sessionID. If we ever want to use sessionID as a secret, which we may
+ // want to, this is giving away the keys to the kitchen.
+ //
+ // The right behavior is going to be informed by identity. Basically, each
+ // time a node registers, we invalidate the session and issue a new
+ // session, once identity is proven. This will cause misbehaved agents to
+ // be kicked when multiple connections are made.
+ return rn.SessionID, nil
+}
+
+// UpdateTaskStatus updates status of task. Node should send such updates
+// on every status change of its tasks.
+func (d *Dispatcher) UpdateTaskStatus(ctx context.Context, r *api.UpdateTaskStatusRequest) (*api.UpdateTaskStatusResponse, error) {
+ nodeInfo, err := ca.RemoteNode(ctx)
+ if err != nil {
+ return nil, err
+ }
+ nodeID := nodeInfo.NodeID
+ fields := logrus.Fields{
+ "node.id": nodeID,
+ "node.session": r.SessionID,
+ "method": "(*Dispatcher).UpdateTaskStatus",
+ }
+ if nodeInfo.ForwardedBy != nil {
+ fields["forwarder.id"] = nodeInfo.ForwardedBy.NodeID
+ }
+ log := log.G(ctx).WithFields(fields)
+
+ dctx, err := d.isRunningLocked()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := d.nodes.GetWithSession(nodeID, r.SessionID); err != nil {
+ return nil, err
+ }
+
+ validTaskUpdates := make([]*api.UpdateTaskStatusRequest_TaskStatusUpdate, 0, len(r.Updates))
+
+ // Validate task updates
+ for _, u := range r.Updates {
+ if u.Status == nil {
+ log.WithField("task.id", u.TaskID).Warn("task report has nil status")
+ continue
+ }
+
+ var t *api.Task
+ d.store.View(func(tx store.ReadTx) {
+ t = store.GetTask(tx, u.TaskID)
+ })
+ if t == nil {
+ // Task may have been deleted
+ log.WithField("task.id", u.TaskID).Debug("cannot find target task in store")
+ continue
+ }
+
+ if t.NodeID != nodeID {
+ err := grpc.Errorf(codes.PermissionDenied, "cannot update a task not assigned this node")
+ log.WithField("task.id", u.TaskID).Error(err)
+ return nil, err
+ }
+
+ validTaskUpdates = append(validTaskUpdates, u)
+ }
+
+ d.taskUpdatesLock.Lock()
+ // Enqueue task updates
+ for _, u := range validTaskUpdates {
+ d.taskUpdates[u.TaskID] = u.Status
+ }
+
+ numUpdates := len(d.taskUpdates)
+ d.taskUpdatesLock.Unlock()
+
+ if numUpdates >= maxBatchItems {
+ select {
+ case d.processUpdatesTrigger <- struct{}{}:
+ case <-dctx.Done():
+ }
+ }
+ return nil, nil
+}
+
+func (d *Dispatcher) processUpdates(ctx context.Context) {
+ var (
+ taskUpdates map[string]*api.TaskStatus
+ nodeUpdates map[string]nodeUpdate
+ )
+ d.taskUpdatesLock.Lock()
+ if len(d.taskUpdates) != 0 {
+ taskUpdates = d.taskUpdates
+ d.taskUpdates = make(map[string]*api.TaskStatus)
+ }
+ d.taskUpdatesLock.Unlock()
+
+ d.nodeUpdatesLock.Lock()
+ if len(d.nodeUpdates) != 0 {
+ nodeUpdates = d.nodeUpdates
+ d.nodeUpdates = make(map[string]nodeUpdate)
+ }
+ d.nodeUpdatesLock.Unlock()
+
+ if len(taskUpdates) == 0 && len(nodeUpdates) == 0 {
+ return
+ }
+
+ log := log.G(ctx).WithFields(logrus.Fields{
+ "method": "(*Dispatcher).processUpdates",
+ })
+
+ err := d.store.Batch(func(batch *store.Batch) error {
+ for taskID, status := range taskUpdates {
+ err := batch.Update(func(tx store.Tx) error {
+ logger := log.WithField("task.id", taskID)
+ task := store.GetTask(tx, taskID)
+ if task == nil {
+ // Task may have been deleted
+ logger.Debug("cannot find target task in store")
+ return nil
+ }
+
+ logger = logger.WithField("state.transition", fmt.Sprintf("%v->%v", task.Status.State, status.State))
+
+ if task.Status == *status {
+ logger.Debug("task status identical, ignoring")
+ return nil
+ }
+
+ if task.Status.State > status.State {
+ logger.Debug("task status invalid transition")
+ return nil
+ }
+
+ task.Status = *status
+ if err := store.UpdateTask(tx, task); err != nil {
+ logger.WithError(err).Error("failed to update task status")
+ return nil
+ }
+ logger.Debug("dispatcher committed status update to store")
+ return nil
+ })
+ if err != nil {
+ log.WithError(err).Error("dispatcher task update transaction failed")
+ }
+ }
+
+ for nodeID, nodeUpdate := range nodeUpdates {
+ err := batch.Update(func(tx store.Tx) error {
+ logger := log.WithField("node.id", nodeID)
+ node := store.GetNode(tx, nodeID)
+ if node == nil {
+ logger.Errorf("node unavailable")
+ return nil
+ }
+
+ if nodeUpdate.status != nil {
+ node.Status.State = nodeUpdate.status.State
+ node.Status.Message = nodeUpdate.status.Message
+ if nodeUpdate.status.Addr != "" {
+ node.Status.Addr = nodeUpdate.status.Addr
+ }
+ }
+ if nodeUpdate.description != nil {
+ node.Description = nodeUpdate.description
+ }
+
+ if err := store.UpdateNode(tx, node); err != nil {
+ logger.WithError(err).Error("failed to update node status")
+ return nil
+ }
+ logger.Debug("node status updated")
+ return nil
+ })
+ if err != nil {
+ log.WithError(err).Error("dispatcher node update transaction failed")
+ }
+ }
+
+ return nil
+ })
+ if err != nil {
+ log.WithError(err).Error("dispatcher batch failed")
+ }
+
+ d.processUpdatesCond.Broadcast()
+}
+
+// Tasks is a stream of tasks state for node. Each message contains full list
+// of tasks which should be run on node, if task is not present in that list,
+// it should be terminated.
+func (d *Dispatcher) Tasks(r *api.TasksRequest, stream api.Dispatcher_TasksServer) error {
+ nodeInfo, err := ca.RemoteNode(stream.Context())
+ if err != nil {
+ return err
+ }
+ nodeID := nodeInfo.NodeID
+
+ dctx, err := d.isRunningLocked()
+ if err != nil {
+ return err
+ }
+
+ fields := logrus.Fields{
+ "node.id": nodeID,
+ "node.session": r.SessionID,
+ "method": "(*Dispatcher).Tasks",
+ }
+ if nodeInfo.ForwardedBy != nil {
+ fields["forwarder.id"] = nodeInfo.ForwardedBy.NodeID
+ }
+ log.G(stream.Context()).WithFields(fields).Debugf("")
+
+ if _, err = d.nodes.GetWithSession(nodeID, r.SessionID); err != nil {
+ return err
+ }
+
+ tasksMap := make(map[string]*api.Task)
+ nodeTasks, cancel, err := store.ViewAndWatch(
+ d.store,
+ func(readTx store.ReadTx) error {
+ tasks, err := store.FindTasks(readTx, store.ByNodeID(nodeID))
+ if err != nil {
+ return err
+ }
+ for _, t := range tasks {
+ tasksMap[t.ID] = t
+ }
+ return nil
+ },
+ api.EventCreateTask{Task: &api.Task{NodeID: nodeID},
+ Checks: []api.TaskCheckFunc{api.TaskCheckNodeID}},
+ api.EventUpdateTask{Task: &api.Task{NodeID: nodeID},
+ Checks: []api.TaskCheckFunc{api.TaskCheckNodeID}},
+ api.EventDeleteTask{Task: &api.Task{NodeID: nodeID},
+ Checks: []api.TaskCheckFunc{api.TaskCheckNodeID}},
+ )
+ if err != nil {
+ return err
+ }
+ defer cancel()
+
+ for {
+ if _, err := d.nodes.GetWithSession(nodeID, r.SessionID); err != nil {
+ return err
+ }
+
+ var tasks []*api.Task
+ for _, t := range tasksMap {
+ // dispatcher only sends tasks that have been assigned to a node
+ if t != nil && t.Status.State >= api.TaskStateAssigned {
+ tasks = append(tasks, t)
+ }
+ }
+
+ if err := stream.Send(&api.TasksMessage{Tasks: tasks}); err != nil {
+ return err
+ }
+
+ // bursty events should be processed in batches and sent out snapshot
+ var (
+ modificationCnt int
+ batchingTimer *time.Timer
+ batchingTimeout <-chan time.Time
+ )
+
+ batchingLoop:
+ for modificationCnt < modificationBatchLimit {
+ select {
+ case event := <-nodeTasks:
+ switch v := event.(type) {
+ case api.EventCreateTask:
+ tasksMap[v.Task.ID] = v.Task
+ modificationCnt++
+ case api.EventUpdateTask:
+ if oldTask, exists := tasksMap[v.Task.ID]; exists {
+ // States ASSIGNED and below are set by the orchestrator/scheduler,
+ // not the agent, so tasks in these states need to be sent to the
+ // agent even if nothing else has changed.
+ if equality.TasksEqualStable(oldTask, v.Task) && v.Task.Status.State > api.TaskStateAssigned {
+ // this update should not trigger action at agent
+ tasksMap[v.Task.ID] = v.Task
+ continue
+ }
+ }
+ tasksMap[v.Task.ID] = v.Task
+ modificationCnt++
+ case api.EventDeleteTask:
+ delete(tasksMap, v.Task.ID)
+ modificationCnt++
+ }
+ if batchingTimer != nil {
+ batchingTimer.Reset(batchingWaitTime)
+ } else {
+ batchingTimer = time.NewTimer(batchingWaitTime)
+ batchingTimeout = batchingTimer.C
+ }
+ case <-batchingTimeout:
+ break batchingLoop
+ case <-stream.Context().Done():
+ return stream.Context().Err()
+ case <-dctx.Done():
+ return dctx.Err()
+ }
+ }
+
+ if batchingTimer != nil {
+ batchingTimer.Stop()
+ }
+ }
+}
+
+// Assignments is a stream of assignments for a node. Each message contains
+// either full list of tasks and secrets for the node, or an incremental update.
+func (d *Dispatcher) Assignments(r *api.AssignmentsRequest, stream api.Dispatcher_AssignmentsServer) error {
+ nodeInfo, err := ca.RemoteNode(stream.Context())
+ if err != nil {
+ return err
+ }
+ nodeID := nodeInfo.NodeID
+
+ dctx, err := d.isRunningLocked()
+ if err != nil {
+ return err
+ }
+
+ fields := logrus.Fields{
+ "node.id": nodeID,
+ "node.session": r.SessionID,
+ "method": "(*Dispatcher).Assignments",
+ }
+ if nodeInfo.ForwardedBy != nil {
+ fields["forwarder.id"] = nodeInfo.ForwardedBy.NodeID
+ }
+ log := log.G(stream.Context()).WithFields(fields)
+ log.Debugf("")
+
+ if _, err = d.nodes.GetWithSession(nodeID, r.SessionID); err != nil {
+ return err
+ }
+
+ var (
+ sequence int64
+ appliesTo string
+ assignments = newAssignmentSet(log)
+ )
+
+ sendMessage := func(msg api.AssignmentsMessage, assignmentType api.AssignmentsMessage_Type) error {
+ sequence++
+ msg.AppliesTo = appliesTo
+ msg.ResultsIn = strconv.FormatInt(sequence, 10)
+ appliesTo = msg.ResultsIn
+ msg.Type = assignmentType
+
+ if err := stream.Send(&msg); err != nil {
+ return err
+ }
+ return nil
+ }
+
+ // TODO(aaronl): Also send node secrets that should be exposed to
+ // this node.
+ nodeTasks, cancel, err := store.ViewAndWatch(
+ d.store,
+ func(readTx store.ReadTx) error {
+ tasks, err := store.FindTasks(readTx, store.ByNodeID(nodeID))
+ if err != nil {
+ return err
+ }
+
+ for _, t := range tasks {
+ assignments.addOrUpdateTask(readTx, t)
+ }
+
+ return nil
+ },
+ api.EventUpdateTask{Task: &api.Task{NodeID: nodeID},
+ Checks: []api.TaskCheckFunc{api.TaskCheckNodeID}},
+ api.EventDeleteTask{Task: &api.Task{NodeID: nodeID},
+ Checks: []api.TaskCheckFunc{api.TaskCheckNodeID}},
+ )
+ if err != nil {
+ return err
+ }
+ defer cancel()
+
+ if err := sendMessage(assignments.message(), api.AssignmentsMessage_COMPLETE); err != nil {
+ return err
+ }
+
+ for {
+ // Check for session expiration
+ if _, err := d.nodes.GetWithSession(nodeID, r.SessionID); err != nil {
+ return err
+ }
+
+ // bursty events should be processed in batches and sent out together
+ var (
+ modificationCnt int
+ batchingTimer *time.Timer
+ batchingTimeout <-chan time.Time
+ )
+
+ oneModification := func() {
+ modificationCnt++
+
+ if batchingTimer != nil {
+ batchingTimer.Reset(batchingWaitTime)
+ } else {
+ batchingTimer = time.NewTimer(batchingWaitTime)
+ batchingTimeout = batchingTimer.C
+ }
+ }
+
+ // The batching loop waits for 50 ms after the most recent
+ // change, or until modificationBatchLimit is reached. The
+ // worst case latency is modificationBatchLimit * batchingWaitTime,
+ // which is 10 seconds.
+ batchingLoop:
+ for modificationCnt < modificationBatchLimit {
+ select {
+ case event := <-nodeTasks:
+ switch v := event.(type) {
+ // We don't monitor EventCreateTask because tasks are
+ // never created in the ASSIGNED state. First tasks are
+ // created by the orchestrator, then the scheduler moves
+ // them to ASSIGNED. If this ever changes, we will need
+ // to monitor task creations as well.
+ case api.EventUpdateTask:
+ d.store.View(func(readTx store.ReadTx) {
+ if assignments.addOrUpdateTask(readTx, v.Task) {
+ oneModification()
+ }
+ })
+ case api.EventDeleteTask:
+ if assignments.removeTask(v.Task) {
+ oneModification()
+ }
+ // TODO(aaronl): For node secrets, we'll need to handle
+ // EventCreateSecret.
+ }
+ case <-batchingTimeout:
+ break batchingLoop
+ case <-stream.Context().Done():
+ return stream.Context().Err()
+ case <-dctx.Done():
+ return dctx.Err()
+ }
+ }
+
+ if batchingTimer != nil {
+ batchingTimer.Stop()
+ }
+
+ if modificationCnt > 0 {
+ if err := sendMessage(assignments.message(), api.AssignmentsMessage_INCREMENTAL); err != nil {
+ return err
+ }
+ }
+ }
+}
+
+func (d *Dispatcher) moveTasksToOrphaned(nodeID string) error {
+ err := d.store.Batch(func(batch *store.Batch) error {
+ var (
+ tasks []*api.Task
+ err error
+ )
+
+ d.store.View(func(tx store.ReadTx) {
+ tasks, err = store.FindTasks(tx, store.ByNodeID(nodeID))
+ })
+ if err != nil {
+ return err
+ }
+
+ for _, task := range tasks {
+ // Tasks running on an unreachable node need to be marked as
+ // orphaned since we have no idea whether the task is still running
+ // or not.
+ //
+ // This only applies for tasks that could have made progress since
+ // the agent became unreachable (assigned<->running)
+ //
+ // Tasks in a final state (e.g. rejected) *cannot* have made
+ // progress, therefore there's no point in marking them as orphaned
+ if task.Status.State >= api.TaskStateAssigned && task.Status.State <= api.TaskStateRunning {
+ task.Status.State = api.TaskStateOrphaned
+ }
+
+ if err := batch.Update(func(tx store.Tx) error {
+ err := store.UpdateTask(tx, task)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ }); err != nil {
+ return err
+ }
+
+ }
+
+ return nil
+ })
+
+ return err
+}
+
+// markNodeNotReady sets the node state to some state other than READY
+func (d *Dispatcher) markNodeNotReady(id string, state api.NodeStatus_State, message string) error {
+ dctx, err := d.isRunningLocked()
+ if err != nil {
+ return err
+ }
+
+ // Node is down. Add it to down nodes so that we can keep
+ // track of tasks assigned to the node.
+ var node *api.Node
+ d.store.View(func(readTx store.ReadTx) {
+ node = store.GetNode(readTx, id)
+ if node == nil {
+ err = fmt.Errorf("could not find node %s while trying to add to down nodes store", id)
+ }
+ })
+ if err != nil {
+ return err
+ }
+
+ expireFunc := func() {
+ if err := d.moveTasksToOrphaned(id); err != nil {
+ log.G(dctx).WithError(err).Error(`failed to move all tasks to "ORPHANED" state`)
+ }
+
+ d.downNodes.Delete(id)
+ }
+
+ d.downNodes.Add(node, expireFunc)
+
+ status := &api.NodeStatus{
+ State: state,
+ Message: message,
+ }
+
+ d.nodeUpdatesLock.Lock()
+ // pluck the description out of nodeUpdates. this protects against a case
+ // where a node is marked ready and a description is added, but then the
+ // node is immediately marked not ready. this preserves that description
+ d.nodeUpdates[id] = nodeUpdate{status: status, description: d.nodeUpdates[id].description}
+ numUpdates := len(d.nodeUpdates)
+ d.nodeUpdatesLock.Unlock()
+
+ if numUpdates >= maxBatchItems {
+ select {
+ case d.processUpdatesTrigger <- struct{}{}:
+ case <-dctx.Done():
+ }
+ }
+
+ if rn := d.nodes.Delete(id); rn == nil {
+ return errors.Errorf("node %s is not found in local storage", id)
+ }
+
+ return nil
+}
+
+// Heartbeat is heartbeat method for nodes. It returns new TTL in response.
+// Node should send new heartbeat earlier than now + TTL, otherwise it will
+// be deregistered from dispatcher and its status will be updated to NodeStatus_DOWN
+func (d *Dispatcher) Heartbeat(ctx context.Context, r *api.HeartbeatRequest) (*api.HeartbeatResponse, error) {
+ nodeInfo, err := ca.RemoteNode(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ period, err := d.nodes.Heartbeat(nodeInfo.NodeID, r.SessionID)
+ return &api.HeartbeatResponse{Period: period}, err
+}
+
+func (d *Dispatcher) getManagers() []*api.WeightedPeer {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.lastSeenManagers
+}
+
+func (d *Dispatcher) getNetworkBootstrapKeys() []*api.EncryptionKey {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.networkBootstrapKeys
+}
+
+func (d *Dispatcher) getRootCACert() []byte {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.lastSeenRootCert
+}
+
+// Session is a stream which controls agent connection.
+// Each message contains list of backup Managers with weights. Also there is
+// a special boolean field Disconnect which if true indicates that node should
+// reconnect to another Manager immediately.
+func (d *Dispatcher) Session(r *api.SessionRequest, stream api.Dispatcher_SessionServer) error {
+ ctx := stream.Context()
+ nodeInfo, err := ca.RemoteNode(ctx)
+ if err != nil {
+ return err
+ }
+ nodeID := nodeInfo.NodeID
+
+ dctx, err := d.isRunningLocked()
+ if err != nil {
+ return err
+ }
+
+ var sessionID string
+ if _, err := d.nodes.GetWithSession(nodeID, r.SessionID); err != nil {
+ // register the node.
+ sessionID, err = d.register(ctx, nodeID, r.Description)
+ if err != nil {
+ return err
+ }
+ } else {
+ sessionID = r.SessionID
+ // get the node IP addr
+ addr, err := nodeIPFromContext(stream.Context())
+ if err != nil {
+ log.G(ctx).Debugf(err.Error())
+ }
+ // update the node description
+ if err := d.markNodeReady(dctx, nodeID, r.Description, addr); err != nil {
+ return err
+ }
+ }
+
+ fields := logrus.Fields{
+ "node.id": nodeID,
+ "node.session": sessionID,
+ "method": "(*Dispatcher).Session",
+ }
+ if nodeInfo.ForwardedBy != nil {
+ fields["forwarder.id"] = nodeInfo.ForwardedBy.NodeID
+ }
+ log := log.G(ctx).WithFields(fields)
+
+ var nodeObj *api.Node
+ nodeUpdates, cancel, err := store.ViewAndWatch(d.store, func(readTx store.ReadTx) error {
+ nodeObj = store.GetNode(readTx, nodeID)
+ return nil
+ }, api.EventUpdateNode{Node: &api.Node{ID: nodeID},
+ Checks: []api.NodeCheckFunc{api.NodeCheckID}},
+ )
+ if cancel != nil {
+ defer cancel()
+ }
+
+ if err != nil {
+ log.WithError(err).Error("ViewAndWatch Node failed")
+ }
+
+ if _, err = d.nodes.GetWithSession(nodeID, sessionID); err != nil {
+ return err
+ }
+
+ clusterUpdatesCh, clusterCancel := d.clusterUpdateQueue.Watch()
+ defer clusterCancel()
+
+ if err := stream.Send(&api.SessionMessage{
+ SessionID: sessionID,
+ Node: nodeObj,
+ Managers: d.getManagers(),
+ NetworkBootstrapKeys: d.getNetworkBootstrapKeys(),
+ RootCA: d.getRootCACert(),
+ }); err != nil {
+ return err
+ }
+
+ // disconnectNode is a helper forcibly shutdown connection
+ disconnectNode := func() error {
+ // force disconnect by shutting down the stream.
+ transportStream, ok := transport.StreamFromContext(stream.Context())
+ if ok {
+ // if we have the transport stream, we can signal a disconnect
+ // in the client.
+ if err := transportStream.ServerTransport().Close(); err != nil {
+ log.WithError(err).Error("session end")
+ }
+ }
+
+ if err := d.markNodeNotReady(nodeID, api.NodeStatus_DISCONNECTED, "node is currently trying to find new manager"); err != nil {
+ log.WithError(err).Error("failed to remove node")
+ }
+ // still return an abort if the transport closure was ineffective.
+ return grpc.Errorf(codes.Aborted, "node must disconnect")
+ }
+
+ for {
+ // After each message send, we need to check the nodes sessionID hasn't
+ // changed. If it has, we will shut down the stream and make the node
+ // re-register.
+ node, err := d.nodes.GetWithSession(nodeID, sessionID)
+ if err != nil {
+ return err
+ }
+
+ var (
+ disconnect bool
+ mgrs []*api.WeightedPeer
+ netKeys []*api.EncryptionKey
+ rootCert []byte
+ )
+
+ select {
+ case ev := <-clusterUpdatesCh:
+ update := ev.(clusterUpdate)
+ if update.managerUpdate != nil {
+ mgrs = *update.managerUpdate
+ }
+ if update.bootstrapKeyUpdate != nil {
+ netKeys = *update.bootstrapKeyUpdate
+ }
+ if update.rootCAUpdate != nil {
+ rootCert = *update.rootCAUpdate
+ }
+ case ev := <-nodeUpdates:
+ nodeObj = ev.(api.EventUpdateNode).Node
+ case <-stream.Context().Done():
+ return stream.Context().Err()
+ case <-node.Disconnect:
+ disconnect = true
+ case <-dctx.Done():
+ disconnect = true
+ }
+ if mgrs == nil {
+ mgrs = d.getManagers()
+ }
+ if netKeys == nil {
+ netKeys = d.getNetworkBootstrapKeys()
+ }
+ if rootCert == nil {
+ rootCert = d.getRootCACert()
+ }
+
+ if err := stream.Send(&api.SessionMessage{
+ SessionID: sessionID,
+ Node: nodeObj,
+ Managers: mgrs,
+ NetworkBootstrapKeys: netKeys,
+ RootCA: rootCert,
+ }); err != nil {
+ return err
+ }
+ if disconnect {
+ return disconnectNode()
+ }
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/dispatcher/heartbeat/heartbeat.go b/vendor/github.com/docker/swarmkit/manager/dispatcher/heartbeat/heartbeat.go
new file mode 100644
index 0000000..b591868
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/dispatcher/heartbeat/heartbeat.go
@@ -0,0 +1,39 @@
+package heartbeat
+
+import (
+ "sync/atomic"
+ "time"
+)
+
+// Heartbeat is simple way to track heartbeats.
+type Heartbeat struct {
+ timeout int64
+ timer *time.Timer
+}
+
+// New creates new Heartbeat with specified duration. timeoutFunc will be called
+// if timeout for heartbeat is expired. Note that in case of timeout you need to
+// call Beat() to reactivate Heartbeat.
+func New(timeout time.Duration, timeoutFunc func()) *Heartbeat {
+ hb := &Heartbeat{
+ timeout: int64(timeout),
+ timer: time.AfterFunc(timeout, timeoutFunc),
+ }
+ return hb
+}
+
+// Beat resets internal timer to zero. It also can be used to reactivate
+// Heartbeat after timeout.
+func (hb *Heartbeat) Beat() {
+ hb.timer.Reset(time.Duration(atomic.LoadInt64(&hb.timeout)))
+}
+
+// Update updates internal timeout to d. It does not do Beat.
+func (hb *Heartbeat) Update(d time.Duration) {
+ atomic.StoreInt64(&hb.timeout, int64(d))
+}
+
+// Stop stops Heartbeat timer.
+func (hb *Heartbeat) Stop() {
+ hb.timer.Stop()
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/dispatcher/nodes.go b/vendor/github.com/docker/swarmkit/manager/dispatcher/nodes.go
new file mode 100644
index 0000000..8a0de55
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/dispatcher/nodes.go
@@ -0,0 +1,198 @@
+package dispatcher
+
+import (
+ "sync"
+ "time"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/manager/dispatcher/heartbeat"
+)
+
+const rateLimitCount = 3
+
+type registeredNode struct {
+ SessionID string
+ Heartbeat *heartbeat.Heartbeat
+ Registered time.Time
+ Attempts int
+ Node *api.Node
+ Disconnect chan struct{} // signal to disconnect
+ mu sync.Mutex
+}
+
+// checkSessionID determines if the SessionID has changed and returns the
+// appropriate GRPC error code.
+//
+// This may not belong here in the future.
+func (rn *registeredNode) checkSessionID(sessionID string) error {
+ rn.mu.Lock()
+ defer rn.mu.Unlock()
+
+ // Before each message send, we need to check the nodes sessionID hasn't
+ // changed. If it has, we will the stream and make the node
+ // re-register.
+ if sessionID == "" || rn.SessionID != sessionID {
+ return grpc.Errorf(codes.InvalidArgument, ErrSessionInvalid.Error())
+ }
+
+ return nil
+}
+
+type nodeStore struct {
+ periodChooser *periodChooser
+ gracePeriodMultiplierNormal time.Duration
+ gracePeriodMultiplierUnknown time.Duration
+ rateLimitPeriod time.Duration
+ nodes map[string]*registeredNode
+ mu sync.RWMutex
+}
+
+func newNodeStore(hbPeriod, hbEpsilon time.Duration, graceMultiplier int, rateLimitPeriod time.Duration) *nodeStore {
+ return &nodeStore{
+ nodes: make(map[string]*registeredNode),
+ periodChooser: newPeriodChooser(hbPeriod, hbEpsilon),
+ gracePeriodMultiplierNormal: time.Duration(graceMultiplier),
+ gracePeriodMultiplierUnknown: time.Duration(graceMultiplier) * 2,
+ rateLimitPeriod: rateLimitPeriod,
+ }
+}
+
+func (s *nodeStore) updatePeriod(hbPeriod, hbEpsilon time.Duration, gracePeriodMultiplier int) {
+ s.mu.Lock()
+ s.periodChooser = newPeriodChooser(hbPeriod, hbEpsilon)
+ s.gracePeriodMultiplierNormal = time.Duration(gracePeriodMultiplier)
+ s.gracePeriodMultiplierUnknown = s.gracePeriodMultiplierNormal * 2
+ s.mu.Unlock()
+}
+
+func (s *nodeStore) Len() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return len(s.nodes)
+}
+
+func (s *nodeStore) AddUnknown(n *api.Node, expireFunc func()) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ rn := &registeredNode{
+ Node: n,
+ }
+ s.nodes[n.ID] = rn
+ rn.Heartbeat = heartbeat.New(s.periodChooser.Choose()*s.gracePeriodMultiplierUnknown, expireFunc)
+ return nil
+}
+
+// CheckRateLimit returns error if node with specified id is allowed to re-register
+// again.
+func (s *nodeStore) CheckRateLimit(id string) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if existRn, ok := s.nodes[id]; ok {
+ if time.Since(existRn.Registered) > s.rateLimitPeriod {
+ existRn.Attempts = 0
+ }
+ existRn.Attempts++
+ if existRn.Attempts > rateLimitCount {
+ return grpc.Errorf(codes.Unavailable, "node %s exceeded rate limit count of registrations", id)
+ }
+ existRn.Registered = time.Now()
+ }
+ return nil
+}
+
+// Add adds new node and returns it, it replaces existing without notification.
+func (s *nodeStore) Add(n *api.Node, expireFunc func()) *registeredNode {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ var attempts int
+ var registered time.Time
+ if existRn, ok := s.nodes[n.ID]; ok {
+ attempts = existRn.Attempts
+ registered = existRn.Registered
+ existRn.Heartbeat.Stop()
+ delete(s.nodes, n.ID)
+ }
+ if registered.IsZero() {
+ registered = time.Now()
+ }
+ rn := &registeredNode{
+ SessionID: identity.NewID(), // session ID is local to the dispatcher.
+ Node: n,
+ Registered: registered,
+ Attempts: attempts,
+ Disconnect: make(chan struct{}),
+ }
+ s.nodes[n.ID] = rn
+ rn.Heartbeat = heartbeat.New(s.periodChooser.Choose()*s.gracePeriodMultiplierNormal, expireFunc)
+ return rn
+}
+
+func (s *nodeStore) Get(id string) (*registeredNode, error) {
+ s.mu.RLock()
+ rn, ok := s.nodes[id]
+ s.mu.RUnlock()
+ if !ok {
+ return nil, grpc.Errorf(codes.NotFound, ErrNodeNotRegistered.Error())
+ }
+ return rn, nil
+}
+
+func (s *nodeStore) GetWithSession(id, sid string) (*registeredNode, error) {
+ s.mu.RLock()
+ rn, ok := s.nodes[id]
+ s.mu.RUnlock()
+ if !ok {
+ return nil, grpc.Errorf(codes.NotFound, ErrNodeNotRegistered.Error())
+ }
+ return rn, rn.checkSessionID(sid)
+}
+
+func (s *nodeStore) Heartbeat(id, sid string) (time.Duration, error) {
+ rn, err := s.GetWithSession(id, sid)
+ if err != nil {
+ return 0, err
+ }
+ period := s.periodChooser.Choose() // base period for node
+ grace := period * time.Duration(s.gracePeriodMultiplierNormal)
+ rn.mu.Lock()
+ rn.Heartbeat.Update(grace)
+ rn.Heartbeat.Beat()
+ rn.mu.Unlock()
+ return period, nil
+}
+
+func (s *nodeStore) Delete(id string) *registeredNode {
+ s.mu.Lock()
+ var node *registeredNode
+ if rn, ok := s.nodes[id]; ok {
+ delete(s.nodes, id)
+ rn.Heartbeat.Stop()
+ node = rn
+ }
+ s.mu.Unlock()
+ return node
+}
+
+func (s *nodeStore) Disconnect(id string) {
+ s.mu.Lock()
+ if rn, ok := s.nodes[id]; ok {
+ close(rn.Disconnect)
+ rn.Heartbeat.Stop()
+ }
+ s.mu.Unlock()
+}
+
+// Clean removes all nodes and stops their heartbeats.
+// It's equivalent to invalidate all sessions.
+func (s *nodeStore) Clean() {
+ s.mu.Lock()
+ for _, rn := range s.nodes {
+ rn.Heartbeat.Stop()
+ }
+ s.nodes = make(map[string]*registeredNode)
+ s.mu.Unlock()
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/dispatcher/period.go b/vendor/github.com/docker/swarmkit/manager/dispatcher/period.go
new file mode 100644
index 0000000..d445775
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/dispatcher/period.go
@@ -0,0 +1,28 @@
+package dispatcher
+
+import (
+ "math/rand"
+ "time"
+)
+
+type periodChooser struct {
+ period time.Duration
+ epsilon time.Duration
+ rand *rand.Rand
+}
+
+func newPeriodChooser(period, eps time.Duration) *periodChooser {
+ return &periodChooser{
+ period: period,
+ epsilon: eps,
+ rand: rand.New(rand.NewSource(time.Now().UnixNano())),
+ }
+}
+
+func (pc *periodChooser) Choose() time.Duration {
+ var adj int64
+ if pc.epsilon > 0 {
+ adj = rand.Int63n(int64(2*pc.epsilon)) - int64(pc.epsilon)
+ }
+ return pc.period + time.Duration(adj)
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/doc.go b/vendor/github.com/docker/swarmkit/manager/doc.go
new file mode 100644
index 0000000..5d04392
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/doc.go
@@ -0,0 +1 @@
+package manager
diff --git a/vendor/github.com/docker/swarmkit/manager/encryption/encryption.go b/vendor/github.com/docker/swarmkit/manager/encryption/encryption.go
new file mode 100644
index 0000000..7461631
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/encryption/encryption.go
@@ -0,0 +1,132 @@
+package encryption
+
+import (
+ cryptorand "crypto/rand"
+ "encoding/base64"
+ "fmt"
+ "io"
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/gogo/protobuf/proto"
+ "github.com/pkg/errors"
+)
+
+// This package defines the interfaces and encryption package
+
+const humanReadablePrefix = "SWMKEY-1-"
+
+// ErrCannotDecrypt is the type of error returned when some data cannot be decryptd as plaintext
+type ErrCannotDecrypt struct {
+ msg string
+}
+
+func (e ErrCannotDecrypt) Error() string {
+ return e.msg
+}
+
+// A Decrypter can decrypt an encrypted record
+type Decrypter interface {
+ Decrypt(api.MaybeEncryptedRecord) ([]byte, error)
+}
+
+// A Encrypter can encrypt some bytes into an encrypted record
+type Encrypter interface {
+ Encrypt(data []byte) (*api.MaybeEncryptedRecord, error)
+}
+
+type noopCrypter struct{}
+
+func (n noopCrypter) Decrypt(e api.MaybeEncryptedRecord) ([]byte, error) {
+ if e.Algorithm != n.Algorithm() {
+ return nil, fmt.Errorf("record is encrypted")
+ }
+ return e.Data, nil
+}
+
+func (n noopCrypter) Encrypt(data []byte) (*api.MaybeEncryptedRecord, error) {
+ return &api.MaybeEncryptedRecord{
+ Algorithm: n.Algorithm(),
+ Data: data,
+ }, nil
+}
+
+func (n noopCrypter) Algorithm() api.MaybeEncryptedRecord_Algorithm {
+ return api.MaybeEncryptedRecord_NotEncrypted
+}
+
+// NoopCrypter is just a pass-through crypter - it does not actually encrypt or
+// decrypt any data
+var NoopCrypter = noopCrypter{}
+
+// Decrypt turns a slice of bytes serialized as an MaybeEncryptedRecord into a slice of plaintext bytes
+func Decrypt(encryptd []byte, decrypter Decrypter) ([]byte, error) {
+ if decrypter == nil {
+ return nil, ErrCannotDecrypt{msg: "no decrypter specified"}
+ }
+ r := api.MaybeEncryptedRecord{}
+ if err := proto.Unmarshal(encryptd, &r); err != nil {
+ // nope, this wasn't marshalled as a MaybeEncryptedRecord
+ return nil, ErrCannotDecrypt{msg: "unable to unmarshal as MaybeEncryptedRecord"}
+ }
+ plaintext, err := decrypter.Decrypt(r)
+ if err != nil {
+ return nil, ErrCannotDecrypt{msg: err.Error()}
+ }
+ return plaintext, nil
+}
+
+// Encrypt turns a slice of bytes into a serialized MaybeEncryptedRecord slice of bytes
+func Encrypt(plaintext []byte, encrypter Encrypter) ([]byte, error) {
+ if encrypter == nil {
+ return nil, fmt.Errorf("no encrypter specified")
+ }
+
+ encryptedRecord, err := encrypter.Encrypt(plaintext)
+ if err != nil {
+ return nil, errors.Wrap(err, "unable to encrypt data")
+ }
+
+ data, err := proto.Marshal(encryptedRecord)
+ if err != nil {
+ return nil, errors.Wrap(err, "unable to marshal as MaybeEncryptedRecord")
+ }
+
+ return data, nil
+}
+
+// Defaults returns a default encrypter and decrypter
+func Defaults(key []byte) (Encrypter, Decrypter) {
+ n := NewNACLSecretbox(key)
+ return n, n
+}
+
+// GenerateSecretKey generates a secret key that can be used for encrypting data
+// using this package
+func GenerateSecretKey() []byte {
+ secretData := make([]byte, naclSecretboxKeySize)
+ if _, err := io.ReadFull(cryptorand.Reader, secretData); err != nil {
+ // panic if we can't read random data
+ panic(errors.Wrap(err, "failed to read random bytes"))
+ }
+ return secretData
+}
+
+// HumanReadableKey displays a secret key in a human readable way
+func HumanReadableKey(key []byte) string {
+ // base64-encode the key
+ return humanReadablePrefix + base64.RawStdEncoding.EncodeToString(key)
+}
+
+// ParseHumanReadableKey returns a key as bytes from recognized serializations of
+// said keys
+func ParseHumanReadableKey(key string) ([]byte, error) {
+ if !strings.HasPrefix(key, humanReadablePrefix) {
+ return nil, fmt.Errorf("invalid key string")
+ }
+ keyBytes, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(key, humanReadablePrefix))
+ if err != nil {
+ return nil, fmt.Errorf("invalid key string")
+ }
+ return keyBytes, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/encryption/nacl.go b/vendor/github.com/docker/swarmkit/manager/encryption/nacl.go
new file mode 100644
index 0000000..6efb685
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/encryption/nacl.go
@@ -0,0 +1,73 @@
+package encryption
+
+import (
+ cryptorand "crypto/rand"
+ "fmt"
+ "io"
+
+ "github.com/docker/swarmkit/api"
+
+ "golang.org/x/crypto/nacl/secretbox"
+)
+
+const naclSecretboxKeySize = 32
+const naclSecretboxNonceSize = 24
+
+// This provides the default implementation of an encrypter and decrypter, as well
+// as the default KDF function.
+
+// NACLSecretbox is an implementation of an encrypter/decrypter. Encrypting
+// generates random Nonces.
+type NACLSecretbox struct {
+ key [naclSecretboxKeySize]byte
+}
+
+// NewNACLSecretbox returns a new NACL secretbox encrypter/decrypter with the given key
+func NewNACLSecretbox(key []byte) NACLSecretbox {
+ secretbox := NACLSecretbox{}
+ copy(secretbox.key[:], key)
+ return secretbox
+}
+
+// Algorithm returns the type of algorithm this is (NACL Secretbox using XSalsa20 and Poly1305)
+func (n NACLSecretbox) Algorithm() api.MaybeEncryptedRecord_Algorithm {
+ return api.MaybeEncryptedRecord_NACLSecretboxSalsa20Poly1305
+}
+
+// Encrypt encrypts some bytes and returns an encrypted record
+func (n NACLSecretbox) Encrypt(data []byte) (*api.MaybeEncryptedRecord, error) {
+ var nonce [24]byte
+ if _, err := io.ReadFull(cryptorand.Reader, nonce[:]); err != nil {
+ return nil, err
+ }
+
+ // Seal's first argument is an "out", the data that the new encrypted message should be
+ // appended to. Since we don't want to append anything, we pass nil.
+ encrypted := secretbox.Seal(nil, data, &nonce, &n.key)
+ return &api.MaybeEncryptedRecord{
+ Algorithm: n.Algorithm(),
+ Data: encrypted,
+ Nonce: nonce[:],
+ }, nil
+}
+
+// Decrypt decrypts a MaybeEncryptedRecord and returns some bytes
+func (n NACLSecretbox) Decrypt(record api.MaybeEncryptedRecord) ([]byte, error) {
+ if record.Algorithm != n.Algorithm() {
+ return nil, fmt.Errorf("not a NACL secretbox record")
+ }
+ if len(record.Nonce) != naclSecretboxNonceSize {
+ return nil, fmt.Errorf("invalid nonce size for NACL secretbox: require 24, got %d", len(record.Nonce))
+ }
+
+ var decryptNonce [naclSecretboxNonceSize]byte
+ copy(decryptNonce[:], record.Nonce[:naclSecretboxNonceSize])
+
+ // Open's first argument is an "out", the data that the decrypted message should be
+ // appended to. Since we don't want to append anything, we pass nil.
+ decrypted, ok := secretbox.Open(nil, record.Data, &decryptNonce, &n.key)
+ if !ok {
+ return nil, fmt.Errorf("decryption error using NACL secretbox")
+ }
+ return decrypted, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/health/health.go b/vendor/github.com/docker/swarmkit/manager/health/health.go
new file mode 100644
index 0000000..bf220bd
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/health/health.go
@@ -0,0 +1,58 @@
+// Package health provides some utility functions to health-check a server. The implementation
+// is based on protobuf. Users need to write their own implementations if other IDLs are used.
+//
+// See original source: https://github.com/grpc/grpc-go/blob/master/health/health.go
+//
+// We use our own implementation of grpc server health check to include the authorization
+// wrapper necessary for the Managers.
+package health
+
+import (
+ "sync"
+
+ "github.com/docker/swarmkit/api"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+// Server represents a Health Check server to check
+// if a service is running or not on some host.
+type Server struct {
+ mu sync.Mutex
+ // statusMap stores the serving status of the services this HealthServer monitors.
+ statusMap map[string]api.HealthCheckResponse_ServingStatus
+}
+
+// NewHealthServer creates a new health check server for grpc services.
+func NewHealthServer() *Server {
+ return &Server{
+ statusMap: make(map[string]api.HealthCheckResponse_ServingStatus),
+ }
+}
+
+// Check checks if the grpc server is healthy and running.
+func (s *Server) Check(ctx context.Context, in *api.HealthCheckRequest) (*api.HealthCheckResponse, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if in.Service == "" {
+ // check the server overall health status.
+ return &api.HealthCheckResponse{
+ Status: api.HealthCheckResponse_SERVING,
+ }, nil
+ }
+ if status, ok := s.statusMap[in.Service]; ok {
+ return &api.HealthCheckResponse{
+ Status: status,
+ }, nil
+ }
+ return nil, grpc.Errorf(codes.NotFound, "unknown service")
+}
+
+// SetServingStatus is called when need to reset the serving status of a service
+// or insert a new service entry into the statusMap.
+func (s *Server) SetServingStatus(service string, status api.HealthCheckResponse_ServingStatus) {
+ s.mu.Lock()
+ s.statusMap[service] = status
+ s.mu.Unlock()
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/keymanager/keymanager.go b/vendor/github.com/docker/swarmkit/manager/keymanager/keymanager.go
new file mode 100644
index 0000000..e61979c
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/keymanager/keymanager.go
@@ -0,0 +1,239 @@
+package keymanager
+
+// keymanager does the allocation, rotation and distribution of symmetric
+// keys to the agents. This is to securely bootstrap network communication
+// between agents. It can be used for encrypting gossip between the agents
+// which is used to exchange service discovery and overlay network control
+// plane information. It can also be used to encrypt overlay data traffic.
+import (
+ cryptorand "crypto/rand"
+ "encoding/binary"
+ "sync"
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+const (
+ // DefaultKeyLen is the default length (in bytes) of the key allocated
+ DefaultKeyLen = 16
+
+ // DefaultKeyRotationInterval used by key manager
+ DefaultKeyRotationInterval = 12 * time.Hour
+
+ // SubsystemGossip handles gossip protocol between the agents
+ SubsystemGossip = "networking:gossip"
+
+ // SubsystemIPSec is overlay network data encryption subsystem
+ SubsystemIPSec = "networking:ipsec"
+
+ // DefaultSubsystem is gossip
+ DefaultSubsystem = SubsystemGossip
+ // number of keys to mainrain in the key ring.
+ keyringSize = 3
+)
+
+// map of subsystems and corresponding encryption algorithm. Initially only
+// AES_128 in GCM mode is supported.
+var subsysToAlgo = map[string]api.EncryptionKey_Algorithm{
+ SubsystemGossip: api.AES_128_GCM,
+ SubsystemIPSec: api.AES_128_GCM,
+}
+
+type keyRing struct {
+ lClock uint64
+ keys []*api.EncryptionKey
+}
+
+// Config for the keymanager that can be modified
+type Config struct {
+ ClusterName string
+ Keylen int
+ RotationInterval time.Duration
+ Subsystems []string
+}
+
+// KeyManager handles key allocation, rotation & distribution
+type KeyManager struct {
+ config *Config
+ store *store.MemoryStore
+ keyRing *keyRing
+ ctx context.Context
+ cancel context.CancelFunc
+
+ mu sync.Mutex
+}
+
+// DefaultConfig provides the default config for keymanager
+func DefaultConfig() *Config {
+ return &Config{
+ ClusterName: store.DefaultClusterName,
+ Keylen: DefaultKeyLen,
+ RotationInterval: DefaultKeyRotationInterval,
+ Subsystems: []string{SubsystemGossip, SubsystemIPSec},
+ }
+}
+
+// New creates an instance of keymanager with the given config
+func New(store *store.MemoryStore, config *Config) *KeyManager {
+ for _, subsys := range config.Subsystems {
+ if subsys != SubsystemGossip && subsys != SubsystemIPSec {
+ return nil
+ }
+ }
+ return &KeyManager{
+ config: config,
+ store: store,
+ keyRing: &keyRing{lClock: genSkew()},
+ }
+}
+
+func (k *KeyManager) allocateKey(ctx context.Context, subsys string) *api.EncryptionKey {
+ key := make([]byte, k.config.Keylen)
+
+ _, err := cryptorand.Read(key)
+ if err != nil {
+ panic(errors.Wrap(err, "key generated failed"))
+ }
+ k.keyRing.lClock++
+
+ return &api.EncryptionKey{
+ Subsystem: subsys,
+ Algorithm: subsysToAlgo[subsys],
+ Key: key,
+ LamportTime: k.keyRing.lClock,
+ }
+}
+
+func (k *KeyManager) updateKey(cluster *api.Cluster) error {
+ return k.store.Update(func(tx store.Tx) error {
+ cluster = store.GetCluster(tx, cluster.ID)
+ if cluster == nil {
+ return nil
+ }
+ cluster.EncryptionKeyLamportClock = k.keyRing.lClock
+ cluster.NetworkBootstrapKeys = k.keyRing.keys
+ return store.UpdateCluster(tx, cluster)
+ })
+}
+
+func (k *KeyManager) rotateKey(ctx context.Context) error {
+ var (
+ clusters []*api.Cluster
+ err error
+ )
+ k.store.View(func(readTx store.ReadTx) {
+ clusters, err = store.FindClusters(readTx, store.ByName(k.config.ClusterName))
+ })
+
+ if err != nil {
+ log.G(ctx).Errorf("reading cluster config failed, %v", err)
+ return err
+ }
+
+ cluster := clusters[0]
+ if len(cluster.NetworkBootstrapKeys) == 0 {
+ panic(errors.New("no key in the cluster config"))
+ }
+
+ subsysKeys := map[string][]*api.EncryptionKey{}
+ for _, key := range k.keyRing.keys {
+ subsysKeys[key.Subsystem] = append(subsysKeys[key.Subsystem], key)
+ }
+ k.keyRing.keys = []*api.EncryptionKey{}
+
+ // We maintain the latest key and the one before in the key ring to allow
+ // agents to communicate without disruption on key change.
+ for subsys, keys := range subsysKeys {
+ if len(keys) == keyringSize {
+ min := 0
+ for i, key := range keys[1:] {
+ if key.LamportTime < keys[min].LamportTime {
+ min = i
+ }
+ }
+ keys = append(keys[0:min], keys[min+1:]...)
+ }
+ keys = append(keys, k.allocateKey(ctx, subsys))
+ subsysKeys[subsys] = keys
+ }
+
+ for _, keys := range subsysKeys {
+ k.keyRing.keys = append(k.keyRing.keys, keys...)
+ }
+
+ return k.updateKey(cluster)
+}
+
+// Run starts the keymanager, it doesn't return
+func (k *KeyManager) Run(ctx context.Context) error {
+ k.mu.Lock()
+ ctx = log.WithModule(ctx, "keymanager")
+ var (
+ clusters []*api.Cluster
+ err error
+ )
+ k.store.View(func(readTx store.ReadTx) {
+ clusters, err = store.FindClusters(readTx, store.ByName(k.config.ClusterName))
+ })
+
+ if err != nil {
+ log.G(ctx).Errorf("reading cluster config failed, %v", err)
+ k.mu.Unlock()
+ return err
+ }
+
+ cluster := clusters[0]
+ if len(cluster.NetworkBootstrapKeys) == 0 {
+ for _, subsys := range k.config.Subsystems {
+ for i := 0; i < keyringSize; i++ {
+ k.keyRing.keys = append(k.keyRing.keys, k.allocateKey(ctx, subsys))
+ }
+ }
+ if err := k.updateKey(cluster); err != nil {
+ log.G(ctx).Errorf("store update failed %v", err)
+ }
+ } else {
+ k.keyRing.lClock = cluster.EncryptionKeyLamportClock
+ k.keyRing.keys = cluster.NetworkBootstrapKeys
+ }
+
+ ticker := time.NewTicker(k.config.RotationInterval)
+ defer ticker.Stop()
+
+ k.ctx, k.cancel = context.WithCancel(ctx)
+ k.mu.Unlock()
+
+ for {
+ select {
+ case <-ticker.C:
+ k.rotateKey(ctx)
+ case <-k.ctx.Done():
+ return nil
+ }
+ }
+}
+
+// Stop stops the running instance of key manager
+func (k *KeyManager) Stop() error {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+ if k.cancel == nil {
+ return errors.New("keymanager is not started")
+ }
+ k.cancel()
+ return nil
+}
+
+// genSkew generates a random uint64 number between 0 and 65535
+func genSkew() uint64 {
+ b := make([]byte, 2)
+ if _, err := cryptorand.Read(b); err != nil {
+ panic(err)
+ }
+ return uint64(binary.BigEndian.Uint16(b))
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/logbroker/broker.go b/vendor/github.com/docker/swarmkit/manager/logbroker/broker.go
new file mode 100644
index 0000000..f5ec2b3
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/logbroker/broker.go
@@ -0,0 +1,427 @@
+package logbroker
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "sync"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/ca"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/watch"
+ "golang.org/x/net/context"
+)
+
+var (
+ errAlreadyRunning = errors.New("broker is already running")
+ errNotRunning = errors.New("broker is not running")
+)
+
+type logMessage struct {
+ *api.PublishLogsMessage
+ completed bool
+ err error
+}
+
+// LogBroker coordinates log subscriptions to services and tasks. Clients can
+// publish and subscribe to logs channels.
+//
+// Log subscriptions are pushed to the work nodes by creating log subscsription
+// tasks. As such, the LogBroker also acts as an orchestrator of these tasks.
+type LogBroker struct {
+ mu sync.RWMutex
+ logQueue *watch.Queue
+ subscriptionQueue *watch.Queue
+
+ registeredSubscriptions map[string]*subscription
+ subscriptionsByNode map[string]map[*subscription]struct{}
+
+ pctx context.Context
+ cancelAll context.CancelFunc
+
+ store *store.MemoryStore
+}
+
+// New initializes and returns a new LogBroker
+func New(store *store.MemoryStore) *LogBroker {
+ return &LogBroker{
+ store: store,
+ }
+}
+
+// Run the log broker
+func (lb *LogBroker) Run(ctx context.Context) error {
+ lb.mu.Lock()
+
+ if lb.cancelAll != nil {
+ lb.mu.Unlock()
+ return errAlreadyRunning
+ }
+
+ lb.pctx, lb.cancelAll = context.WithCancel(ctx)
+ lb.logQueue = watch.NewQueue()
+ lb.subscriptionQueue = watch.NewQueue()
+ lb.registeredSubscriptions = make(map[string]*subscription)
+ lb.subscriptionsByNode = make(map[string]map[*subscription]struct{})
+ lb.mu.Unlock()
+
+ select {
+ case <-lb.pctx.Done():
+ return lb.pctx.Err()
+ }
+}
+
+// Stop stops the log broker
+func (lb *LogBroker) Stop() error {
+ lb.mu.Lock()
+ defer lb.mu.Unlock()
+
+ if lb.cancelAll == nil {
+ return errNotRunning
+ }
+ lb.cancelAll()
+ lb.cancelAll = nil
+
+ lb.logQueue.Close()
+ lb.subscriptionQueue.Close()
+
+ return nil
+}
+
+func validateSelector(selector *api.LogSelector) error {
+ if selector == nil {
+ return grpc.Errorf(codes.InvalidArgument, "log selector must be provided")
+ }
+
+ if len(selector.ServiceIDs) == 0 && len(selector.TaskIDs) == 0 && len(selector.NodeIDs) == 0 {
+ return grpc.Errorf(codes.InvalidArgument, "log selector must not be empty")
+ }
+
+ return nil
+}
+
+func (lb *LogBroker) newSubscription(selector *api.LogSelector, options *api.LogSubscriptionOptions) *subscription {
+ lb.mu.RLock()
+ defer lb.mu.RUnlock()
+
+ subscription := newSubscription(lb.store, &api.SubscriptionMessage{
+ ID: identity.NewID(),
+ Selector: selector,
+ Options: options,
+ }, lb.subscriptionQueue)
+
+ return subscription
+}
+
+func (lb *LogBroker) getSubscription(id string) *subscription {
+ lb.mu.RLock()
+ defer lb.mu.RUnlock()
+
+ subscription, ok := lb.registeredSubscriptions[id]
+ if !ok {
+ return nil
+ }
+ return subscription
+}
+
+func (lb *LogBroker) registerSubscription(subscription *subscription) {
+ lb.mu.Lock()
+ defer lb.mu.Unlock()
+
+ lb.registeredSubscriptions[subscription.message.ID] = subscription
+ lb.subscriptionQueue.Publish(subscription)
+
+ for _, node := range subscription.Nodes() {
+ if _, ok := lb.subscriptionsByNode[node]; !ok {
+ // Mark nodes that won't receive the message as done.
+ subscription.Done(node, fmt.Errorf("node %s is not available", node))
+ } else {
+ // otherwise, add the subscription to the node's subscriptions list
+ lb.subscriptionsByNode[node][subscription] = struct{}{}
+ }
+ }
+}
+
+func (lb *LogBroker) unregisterSubscription(subscription *subscription) {
+ lb.mu.Lock()
+ defer lb.mu.Unlock()
+
+ delete(lb.registeredSubscriptions, subscription.message.ID)
+
+ // remove the subscription from all of the nodes
+ for _, node := range subscription.Nodes() {
+ // but only if a node exists
+ if _, ok := lb.subscriptionsByNode[node]; ok {
+ delete(lb.subscriptionsByNode[node], subscription)
+ }
+ }
+
+ subscription.Close()
+ lb.subscriptionQueue.Publish(subscription)
+}
+
+// watchSubscriptions grabs all current subscriptions and notifies of any
+// subscription change for this node.
+//
+// Subscriptions may fire multiple times and the caller has to protect against
+// dupes.
+func (lb *LogBroker) watchSubscriptions(nodeID string) ([]*subscription, chan events.Event, func()) {
+ lb.mu.RLock()
+ defer lb.mu.RUnlock()
+
+ // Watch for subscription changes for this node.
+ ch, cancel := lb.subscriptionQueue.CallbackWatch(events.MatcherFunc(func(event events.Event) bool {
+ s := event.(*subscription)
+ return s.Contains(nodeID)
+ }))
+
+ // Grab current subscriptions.
+ var subscriptions []*subscription
+ for _, s := range lb.registeredSubscriptions {
+ if s.Contains(nodeID) {
+ subscriptions = append(subscriptions, s)
+ }
+ }
+
+ return subscriptions, ch, cancel
+}
+
+func (lb *LogBroker) subscribe(id string) (chan events.Event, func()) {
+ lb.mu.RLock()
+ defer lb.mu.RUnlock()
+
+ return lb.logQueue.CallbackWatch(events.MatcherFunc(func(event events.Event) bool {
+ publish := event.(*logMessage)
+ return publish.SubscriptionID == id
+ }))
+}
+
+func (lb *LogBroker) publish(log *api.PublishLogsMessage) {
+ lb.mu.RLock()
+ defer lb.mu.RUnlock()
+
+ lb.logQueue.Publish(&logMessage{PublishLogsMessage: log})
+}
+
+// markDone wraps (*Subscription).Done() so that the removal of the sub from
+// the node's subscription list is possible
+func (lb *LogBroker) markDone(sub *subscription, nodeID string, err error) {
+ lb.mu.Lock()
+ defer lb.mu.Unlock()
+
+ // remove the subscription from the node's subscription list, if it exists
+ if _, ok := lb.subscriptionsByNode[nodeID]; ok {
+ delete(lb.subscriptionsByNode[nodeID], sub)
+ }
+
+ // mark the sub as done
+ sub.Done(nodeID, err)
+}
+
+// SubscribeLogs creates a log subscription and streams back logs
+func (lb *LogBroker) SubscribeLogs(request *api.SubscribeLogsRequest, stream api.Logs_SubscribeLogsServer) error {
+ ctx := stream.Context()
+
+ if err := validateSelector(request.Selector); err != nil {
+ return err
+ }
+
+ subscription := lb.newSubscription(request.Selector, request.Options)
+ subscription.Run(lb.pctx)
+ defer subscription.Stop()
+
+ log := log.G(ctx).WithFields(
+ logrus.Fields{
+ "method": "(*LogBroker).SubscribeLogs",
+ "subscription.id": subscription.message.ID,
+ },
+ )
+ log.Debug("subscribed")
+
+ publishCh, publishCancel := lb.subscribe(subscription.message.ID)
+ defer publishCancel()
+
+ lb.registerSubscription(subscription)
+ defer lb.unregisterSubscription(subscription)
+
+ completed := subscription.Wait(ctx)
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-lb.pctx.Done():
+ return lb.pctx.Err()
+ case event := <-publishCh:
+ publish := event.(*logMessage)
+ if publish.completed {
+ return publish.err
+ }
+ if err := stream.Send(&api.SubscribeLogsMessage{
+ Messages: publish.Messages,
+ }); err != nil {
+ return err
+ }
+ case <-completed:
+ completed = nil
+ lb.logQueue.Publish(&logMessage{
+ PublishLogsMessage: &api.PublishLogsMessage{
+ SubscriptionID: subscription.message.ID,
+ },
+ completed: true,
+ err: subscription.Err(),
+ })
+ }
+ }
+}
+
+func (lb *LogBroker) nodeConnected(nodeID string) {
+ lb.mu.Lock()
+ defer lb.mu.Unlock()
+
+ if _, ok := lb.subscriptionsByNode[nodeID]; !ok {
+ lb.subscriptionsByNode[nodeID] = make(map[*subscription]struct{})
+ }
+}
+
+func (lb *LogBroker) nodeDisconnected(nodeID string) {
+ lb.mu.Lock()
+ defer lb.mu.Unlock()
+
+ for sub := range lb.subscriptionsByNode[nodeID] {
+ sub.Done(nodeID, fmt.Errorf("node %s disconnected unexpectedly", nodeID))
+ }
+ delete(lb.subscriptionsByNode, nodeID)
+}
+
+// ListenSubscriptions returns a stream of matching subscriptions for the current node
+func (lb *LogBroker) ListenSubscriptions(request *api.ListenSubscriptionsRequest, stream api.LogBroker_ListenSubscriptionsServer) error {
+ remote, err := ca.RemoteNode(stream.Context())
+ if err != nil {
+ return err
+ }
+
+ lb.nodeConnected(remote.NodeID)
+ defer lb.nodeDisconnected(remote.NodeID)
+
+ log := log.G(stream.Context()).WithFields(
+ logrus.Fields{
+ "method": "(*LogBroker).ListenSubscriptions",
+ "node": remote.NodeID,
+ },
+ )
+ subscriptions, subscriptionCh, subscriptionCancel := lb.watchSubscriptions(remote.NodeID)
+ defer subscriptionCancel()
+
+ log.Debug("node registered")
+
+ activeSubscriptions := make(map[string]*subscription)
+
+ // Start by sending down all active subscriptions.
+ for _, subscription := range subscriptions {
+ select {
+ case <-stream.Context().Done():
+ return stream.Context().Err()
+ case <-lb.pctx.Done():
+ return nil
+ default:
+ }
+
+ if err := stream.Send(subscription.message); err != nil {
+ log.Error(err)
+ return err
+ }
+ activeSubscriptions[subscription.message.ID] = subscription
+ }
+
+ // Send down new subscriptions.
+ for {
+ select {
+ case v := <-subscriptionCh:
+ subscription := v.(*subscription)
+
+ if subscription.Closed() {
+ delete(activeSubscriptions, subscription.message.ID)
+ } else {
+ // Avoid sending down the same subscription multiple times
+ if _, ok := activeSubscriptions[subscription.message.ID]; ok {
+ continue
+ }
+ activeSubscriptions[subscription.message.ID] = subscription
+ }
+ if err := stream.Send(subscription.message); err != nil {
+ log.Error(err)
+ return err
+ }
+ case <-stream.Context().Done():
+ return stream.Context().Err()
+ case <-lb.pctx.Done():
+ return nil
+ }
+ }
+}
+
+// PublishLogs publishes log messages for a given subscription
+func (lb *LogBroker) PublishLogs(stream api.LogBroker_PublishLogsServer) (err error) {
+ remote, err := ca.RemoteNode(stream.Context())
+ if err != nil {
+ return err
+ }
+
+ var currentSubscription *subscription
+ defer func() {
+ if currentSubscription != nil {
+ lb.markDone(currentSubscription, remote.NodeID, err)
+ }
+ }()
+
+ for {
+ logMsg, err := stream.Recv()
+ if err == io.EOF {
+ return stream.SendAndClose(&api.PublishLogsResponse{})
+ }
+ if err != nil {
+ return err
+ }
+
+ if logMsg.SubscriptionID == "" {
+ return grpc.Errorf(codes.InvalidArgument, "missing subscription ID")
+ }
+
+ if currentSubscription == nil {
+ currentSubscription = lb.getSubscription(logMsg.SubscriptionID)
+ if currentSubscription == nil {
+ return grpc.Errorf(codes.NotFound, "unknown subscription ID")
+ }
+ } else {
+ if logMsg.SubscriptionID != currentSubscription.message.ID {
+ return grpc.Errorf(codes.InvalidArgument, "different subscription IDs in the same session")
+ }
+ }
+
+ // if we have a close message, close out the subscription
+ if logMsg.Close {
+ // Mark done and then set to nil so if we error after this point,
+ // we don't try to close again in the defer
+ lb.markDone(currentSubscription, remote.NodeID, err)
+ currentSubscription = nil
+ return nil
+ }
+
+ // Make sure logs are emitted using the right Node ID to avoid impersonation.
+ for _, msg := range logMsg.Messages {
+ if msg.Context.NodeID != remote.NodeID {
+ return grpc.Errorf(codes.PermissionDenied, "invalid NodeID: expected=%s;received=%s", remote.NodeID, msg.Context.NodeID)
+ }
+ }
+
+ lb.publish(logMsg)
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/logbroker/subscription.go b/vendor/github.com/docker/swarmkit/manager/logbroker/subscription.go
new file mode 100644
index 0000000..b9c9c7b
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/logbroker/subscription.go
@@ -0,0 +1,248 @@
+package logbroker
+
+import (
+ "fmt"
+ "strings"
+ "sync"
+
+ events "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/watch"
+ "golang.org/x/net/context"
+)
+
+type subscription struct {
+ mu sync.RWMutex
+ wg sync.WaitGroup
+
+ store *store.MemoryStore
+ message *api.SubscriptionMessage
+ changed *watch.Queue
+
+ ctx context.Context
+ cancel context.CancelFunc
+
+ errors []error
+ nodes map[string]struct{}
+ pendingTasks map[string]struct{}
+}
+
+func newSubscription(store *store.MemoryStore, message *api.SubscriptionMessage, changed *watch.Queue) *subscription {
+ return &subscription{
+ store: store,
+ message: message,
+ changed: changed,
+ nodes: make(map[string]struct{}),
+ pendingTasks: make(map[string]struct{}),
+ }
+}
+
+func (s *subscription) follow() bool {
+ return s.message.Options != nil && s.message.Options.Follow
+}
+
+func (s *subscription) Contains(nodeID string) bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ _, ok := s.nodes[nodeID]
+ return ok
+}
+
+func (s *subscription) Nodes() []string {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ nodes := make([]string, 0, len(s.nodes))
+ for node := range s.nodes {
+ nodes = append(nodes, node)
+ }
+ return nodes
+}
+
+func (s *subscription) Run(ctx context.Context) {
+ s.ctx, s.cancel = context.WithCancel(ctx)
+
+ if s.follow() {
+ wq := s.store.WatchQueue()
+ ch, cancel := state.Watch(wq, api.EventCreateTask{}, api.EventUpdateTask{})
+ go func() {
+ defer cancel()
+ s.watch(ch)
+ }()
+ }
+
+ s.match()
+}
+
+func (s *subscription) Stop() {
+ if s.cancel != nil {
+ s.cancel()
+ }
+}
+
+func (s *subscription) Wait(ctx context.Context) <-chan struct{} {
+ // Follow subscriptions never end
+ if s.follow() {
+ return nil
+ }
+
+ ch := make(chan struct{})
+ go func() {
+ defer close(ch)
+ s.wg.Wait()
+ }()
+ return ch
+}
+
+func (s *subscription) Done(nodeID string, err error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if err != nil {
+ s.errors = append(s.errors, err)
+ }
+
+ if s.follow() {
+ return
+ }
+
+ if _, ok := s.nodes[nodeID]; !ok {
+ return
+ }
+
+ delete(s.nodes, nodeID)
+ s.wg.Done()
+}
+
+func (s *subscription) Err() error {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if len(s.errors) == 0 && len(s.pendingTasks) == 0 {
+ return nil
+ }
+
+ messages := make([]string, 0, len(s.errors))
+ for _, err := range s.errors {
+ messages = append(messages, err.Error())
+ }
+ for t := range s.pendingTasks {
+ messages = append(messages, fmt.Sprintf("task %s has not been scheduled", t))
+ }
+
+ return fmt.Errorf("warning: incomplete log stream. some logs could not be retrieved for the following reasons: %s", strings.Join(messages, ", "))
+}
+
+func (s *subscription) Close() {
+ s.mu.Lock()
+ s.message.Close = true
+ s.mu.Unlock()
+}
+
+func (s *subscription) Closed() bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.message.Close
+}
+
+func (s *subscription) match() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ add := func(t *api.Task) {
+ if t.NodeID == "" {
+ s.pendingTasks[t.ID] = struct{}{}
+ return
+ }
+ if _, ok := s.nodes[t.NodeID]; !ok {
+ s.nodes[t.NodeID] = struct{}{}
+ s.wg.Add(1)
+ }
+ }
+
+ s.store.View(func(tx store.ReadTx) {
+ for _, nid := range s.message.Selector.NodeIDs {
+ s.nodes[nid] = struct{}{}
+ }
+
+ for _, tid := range s.message.Selector.TaskIDs {
+ if task := store.GetTask(tx, tid); task != nil {
+ add(task)
+ }
+ }
+
+ for _, sid := range s.message.Selector.ServiceIDs {
+ tasks, err := store.FindTasks(tx, store.ByServiceID(sid))
+ if err != nil {
+ log.L.Warning(err)
+ continue
+ }
+ for _, task := range tasks {
+ // if we're not following, don't add tasks that aren't running yet
+ if !s.follow() && task.Status.State < api.TaskStateRunning {
+ continue
+ }
+ add(task)
+ }
+ }
+ })
+}
+
+func (s *subscription) watch(ch <-chan events.Event) error {
+ matchTasks := map[string]struct{}{}
+ for _, tid := range s.message.Selector.TaskIDs {
+ matchTasks[tid] = struct{}{}
+ }
+
+ matchServices := map[string]struct{}{}
+ for _, sid := range s.message.Selector.ServiceIDs {
+ matchServices[sid] = struct{}{}
+ }
+
+ add := func(t *api.Task) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ // Un-allocated task.
+ if t.NodeID == "" {
+ s.pendingTasks[t.ID] = struct{}{}
+ return
+ }
+
+ delete(s.pendingTasks, t.ID)
+ if _, ok := s.nodes[t.NodeID]; !ok {
+ s.nodes[t.NodeID] = struct{}{}
+ s.changed.Publish(s)
+ }
+ }
+
+ for {
+ var t *api.Task
+ select {
+ case <-s.ctx.Done():
+ return s.ctx.Err()
+ case event := <-ch:
+ switch v := event.(type) {
+ case api.EventCreateTask:
+ t = v.Task
+ case api.EventUpdateTask:
+ t = v.Task
+ }
+ }
+
+ if t == nil {
+ panic("received invalid task from the watch queue")
+ }
+
+ if _, ok := matchTasks[t.ID]; ok {
+ add(t)
+ }
+ if _, ok := matchServices[t.ServiceID]; ok {
+ add(t)
+ }
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/manager.go b/vendor/github.com/docker/swarmkit/manager/manager.go
new file mode 100644
index 0000000..d17e8ec
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/manager.go
@@ -0,0 +1,1197 @@
+package manager
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/pem"
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/cloudflare/cfssl/helpers"
+ "github.com/docker/docker/pkg/plugingetter"
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/ca"
+ "github.com/docker/swarmkit/connectionbroker"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/allocator"
+ "github.com/docker/swarmkit/manager/allocator/networkallocator"
+ "github.com/docker/swarmkit/manager/controlapi"
+ "github.com/docker/swarmkit/manager/dispatcher"
+ "github.com/docker/swarmkit/manager/health"
+ "github.com/docker/swarmkit/manager/keymanager"
+ "github.com/docker/swarmkit/manager/logbroker"
+ "github.com/docker/swarmkit/manager/metrics"
+ "github.com/docker/swarmkit/manager/orchestrator/constraintenforcer"
+ "github.com/docker/swarmkit/manager/orchestrator/global"
+ "github.com/docker/swarmkit/manager/orchestrator/replicated"
+ "github.com/docker/swarmkit/manager/orchestrator/taskreaper"
+ "github.com/docker/swarmkit/manager/resourceapi"
+ "github.com/docker/swarmkit/manager/scheduler"
+ "github.com/docker/swarmkit/manager/state/raft"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/manager/watchapi"
+ "github.com/docker/swarmkit/remotes"
+ "github.com/docker/swarmkit/xnet"
+ gogotypes "github.com/gogo/protobuf/types"
+ grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials"
+)
+
+const (
+ // defaultTaskHistoryRetentionLimit is the number of tasks to keep.
+ defaultTaskHistoryRetentionLimit = 5
+)
+
+// RemoteAddrs provides a listening address and an optional advertise address
+// for serving the remote API.
+type RemoteAddrs struct {
+ // Address to bind
+ ListenAddr string
+
+ // Address to advertise to remote nodes (optional).
+ AdvertiseAddr string
+}
+
+// Config is used to tune the Manager.
+type Config struct {
+ SecurityConfig *ca.SecurityConfig
+
+ // RootCAPaths is the path to which new root certs should be save
+ RootCAPaths ca.CertPaths
+
+ // ExternalCAs is a list of initial CAs to which a manager node
+ // will make certificate signing requests for node certificates.
+ ExternalCAs []*api.ExternalCA
+
+ // ControlAPI is an address for serving the control API.
+ ControlAPI string
+
+ // RemoteAPI is a listening address for serving the remote API, and
+ // an optional advertise address.
+ RemoteAPI *RemoteAddrs
+
+ // JoinRaft is an optional address of a node in an existing raft
+ // cluster to join.
+ JoinRaft string
+
+ // Top-level state directory
+ StateDir string
+
+ // ForceNewCluster defines if we have to force a new cluster
+ // because we are recovering from a backup data directory.
+ ForceNewCluster bool
+
+ // ElectionTick defines the amount of ticks needed without
+ // leader to trigger a new election
+ ElectionTick uint32
+
+ // HeartbeatTick defines the amount of ticks between each
+ // heartbeat sent to other members for health-check purposes
+ HeartbeatTick uint32
+
+ // AutoLockManagers determines whether or not managers require an unlock key
+ // when starting from a stopped state. This configuration parameter is only
+ // applicable when bootstrapping a new cluster for the first time.
+ AutoLockManagers bool
+
+ // UnlockKey is the key to unlock a node - used for decrypting manager TLS keys
+ // as well as the raft data encryption key (DEK). It is applicable when
+ // bootstrapping a cluster for the first time (it's a cluster-wide setting),
+ // and also when loading up any raft data on disk (as a KEK for the raft DEK).
+ UnlockKey []byte
+
+ // Availability allows a user to control the current scheduling status of a node
+ Availability api.NodeSpec_Availability
+
+ // PluginGetter provides access to docker's plugin inventory.
+ PluginGetter plugingetter.PluginGetter
+}
+
+// Manager is the cluster manager for Swarm.
+// This is the high-level object holding and initializing all the manager
+// subsystems.
+type Manager struct {
+ config Config
+
+ collector *metrics.Collector
+ caserver *ca.Server
+ dispatcher *dispatcher.Dispatcher
+ logbroker *logbroker.LogBroker
+ replicatedOrchestrator *replicated.Orchestrator
+ globalOrchestrator *global.Orchestrator
+ taskReaper *taskreaper.TaskReaper
+ constraintEnforcer *constraintenforcer.ConstraintEnforcer
+ scheduler *scheduler.Scheduler
+ allocator *allocator.Allocator
+ keyManager *keymanager.KeyManager
+ server *grpc.Server
+ localserver *grpc.Server
+ raftNode *raft.Node
+ dekRotator *RaftDEKManager
+ roleManager *roleManager
+
+ cancelFunc context.CancelFunc
+
+ // mu is a general mutex used to coordinate starting/stopping and
+ // leadership events.
+ mu sync.Mutex
+ // addrMu is a mutex that protects config.ControlAPI and config.RemoteAPI
+ addrMu sync.Mutex
+
+ started chan struct{}
+ stopped bool
+
+ remoteListener chan net.Listener
+ controlListener chan net.Listener
+ errServe chan error
+}
+
+type closeOnceListener struct {
+ once sync.Once
+ net.Listener
+}
+
+func (l *closeOnceListener) Close() error {
+ var err error
+ l.once.Do(func() {
+ err = l.Listener.Close()
+ })
+ return err
+}
+
+// New creates a Manager which has not started to accept requests yet.
+func New(config *Config) (*Manager, error) {
+ err := os.MkdirAll(config.StateDir, 0700)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create state directory")
+ }
+
+ raftStateDir := filepath.Join(config.StateDir, "raft")
+ err = os.MkdirAll(raftStateDir, 0700)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create raft state directory")
+ }
+
+ raftCfg := raft.DefaultNodeConfig()
+
+ if config.ElectionTick > 0 {
+ raftCfg.ElectionTick = int(config.ElectionTick)
+ }
+ if config.HeartbeatTick > 0 {
+ raftCfg.HeartbeatTick = int(config.HeartbeatTick)
+ }
+
+ dekRotator, err := NewRaftDEKManager(config.SecurityConfig.KeyWriter())
+ if err != nil {
+ return nil, err
+ }
+
+ newNodeOpts := raft.NodeOptions{
+ ID: config.SecurityConfig.ClientTLSCreds.NodeID(),
+ JoinAddr: config.JoinRaft,
+ Config: raftCfg,
+ StateDir: raftStateDir,
+ ForceNewCluster: config.ForceNewCluster,
+ TLSCredentials: config.SecurityConfig.ClientTLSCreds,
+ KeyRotator: dekRotator,
+ }
+ raftNode := raft.NewNode(newNodeOpts)
+
+ opts := []grpc.ServerOption{
+ grpc.Creds(config.SecurityConfig.ServerTLSCreds),
+ grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
+ grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
+ }
+
+ m := &Manager{
+ config: *config,
+ caserver: ca.NewServer(raftNode.MemoryStore(), config.SecurityConfig, config.RootCAPaths),
+ dispatcher: dispatcher.New(raftNode, dispatcher.DefaultConfig()),
+ logbroker: logbroker.New(raftNode.MemoryStore()),
+ server: grpc.NewServer(opts...),
+ localserver: grpc.NewServer(opts...),
+ raftNode: raftNode,
+ started: make(chan struct{}),
+ dekRotator: dekRotator,
+ remoteListener: make(chan net.Listener, 1),
+ controlListener: make(chan net.Listener, 1),
+ errServe: make(chan error, 2),
+ }
+
+ if config.ControlAPI != "" {
+ m.config.ControlAPI = ""
+ if err := m.BindControl(config.ControlAPI); err != nil {
+ return nil, err
+ }
+ }
+
+ if config.RemoteAPI != nil {
+ m.config.RemoteAPI = nil
+ // The context isn't used in this case (before (*Manager).Run).
+ if err := m.BindRemote(context.Background(), *config.RemoteAPI); err != nil {
+ if config.ControlAPI != "" {
+ l := <-m.controlListener
+ l.Close()
+ }
+ return nil, err
+ }
+ }
+
+ return m, nil
+}
+
+// BindControl binds a local socket for the control API.
+func (m *Manager) BindControl(addr string) error {
+ m.addrMu.Lock()
+ defer m.addrMu.Unlock()
+
+ if m.config.ControlAPI != "" {
+ return errors.New("manager already has a control API address")
+ }
+
+ // don't create a socket directory if we're on windows. we used named pipe
+ if runtime.GOOS != "windows" {
+ err := os.MkdirAll(filepath.Dir(addr), 0700)
+ if err != nil {
+ return errors.Wrap(err, "failed to create socket directory")
+ }
+ }
+
+ l, err := xnet.ListenLocal(addr)
+
+ // A unix socket may fail to bind if the file already
+ // exists. Try replacing the file.
+ if runtime.GOOS != "windows" {
+ unwrappedErr := err
+ if op, ok := unwrappedErr.(*net.OpError); ok {
+ unwrappedErr = op.Err
+ }
+ if sys, ok := unwrappedErr.(*os.SyscallError); ok {
+ unwrappedErr = sys.Err
+ }
+ if unwrappedErr == syscall.EADDRINUSE {
+ os.Remove(addr)
+ l, err = xnet.ListenLocal(addr)
+ }
+ }
+ if err != nil {
+ return errors.Wrap(err, "failed to listen on control API address")
+ }
+
+ m.config.ControlAPI = addr
+ m.controlListener <- l
+ return nil
+}
+
+// BindRemote binds a port for the remote API.
+func (m *Manager) BindRemote(ctx context.Context, addrs RemoteAddrs) error {
+ m.addrMu.Lock()
+ defer m.addrMu.Unlock()
+
+ if m.config.RemoteAPI != nil {
+ return errors.New("manager already has remote API address")
+ }
+
+ // If an AdvertiseAddr was specified, we use that as our
+ // externally-reachable address.
+ advertiseAddr := addrs.AdvertiseAddr
+
+ var advertiseAddrPort string
+ if advertiseAddr == "" {
+ // Otherwise, we know we are joining an existing swarm. Use a
+ // wildcard address to trigger remote autodetection of our
+ // address.
+ var err error
+ _, advertiseAddrPort, err = net.SplitHostPort(addrs.ListenAddr)
+ if err != nil {
+ return fmt.Errorf("missing or invalid listen address %s", addrs.ListenAddr)
+ }
+
+ // Even with an IPv6 listening address, it's okay to use
+ // 0.0.0.0 here. Any "unspecified" (wildcard) IP will
+ // be substituted with the actual source address.
+ advertiseAddr = net.JoinHostPort("0.0.0.0", advertiseAddrPort)
+ }
+
+ l, err := net.Listen("tcp", addrs.ListenAddr)
+ if err != nil {
+ return errors.Wrap(err, "failed to listen on remote API address")
+ }
+ if advertiseAddrPort == "0" {
+ advertiseAddr = l.Addr().String()
+ addrs.ListenAddr = advertiseAddr
+ }
+
+ m.config.RemoteAPI = &addrs
+
+ m.raftNode.SetAddr(ctx, advertiseAddr)
+ m.remoteListener <- l
+
+ return nil
+}
+
+// RemovedFromRaft returns a channel that's closed if the manager is removed
+// from the raft cluster. This should be used to trigger a manager shutdown.
+func (m *Manager) RemovedFromRaft() <-chan struct{} {
+ return m.raftNode.RemovedFromRaft
+}
+
+// Addr returns tcp address on which remote api listens.
+func (m *Manager) Addr() string {
+ m.addrMu.Lock()
+ defer m.addrMu.Unlock()
+
+ if m.config.RemoteAPI == nil {
+ return ""
+ }
+ return m.config.RemoteAPI.ListenAddr
+}
+
+// Run starts all manager sub-systems and the gRPC server at the configured
+// address.
+// The call never returns unless an error occurs or `Stop()` is called.
+func (m *Manager) Run(parent context.Context) error {
+ ctx, ctxCancel := context.WithCancel(parent)
+ defer ctxCancel()
+
+ m.cancelFunc = ctxCancel
+
+ leadershipCh, cancel := m.raftNode.SubscribeLeadership()
+ defer cancel()
+
+ go m.handleLeadershipEvents(ctx, leadershipCh)
+
+ authorize := func(ctx context.Context, roles []string) error {
+ var (
+ blacklistedCerts map[string]*api.BlacklistedCertificate
+ clusters []*api.Cluster
+ err error
+ )
+
+ m.raftNode.MemoryStore().View(func(readTx store.ReadTx) {
+ clusters, err = store.FindClusters(readTx, store.ByName("default"))
+
+ })
+
+ // Not having a cluster object yet means we can't check
+ // the blacklist.
+ if err == nil && len(clusters) == 1 {
+ blacklistedCerts = clusters[0].BlacklistedCertificates
+ }
+
+ // Authorize the remote roles, ensure they can only be forwarded by managers
+ _, err = ca.AuthorizeForwardedRoleAndOrg(ctx, roles, []string{ca.ManagerRole}, m.config.SecurityConfig.ClientTLSCreds.Organization(), blacklistedCerts)
+ return err
+ }
+
+ baseControlAPI := controlapi.NewServer(m.raftNode.MemoryStore(), m.raftNode, m.config.SecurityConfig, m.caserver, m.config.PluginGetter)
+ baseWatchAPI := watchapi.NewServer(m.raftNode.MemoryStore())
+ baseResourceAPI := resourceapi.New(m.raftNode.MemoryStore())
+ healthServer := health.NewHealthServer()
+ localHealthServer := health.NewHealthServer()
+
+ authenticatedControlAPI := api.NewAuthenticatedWrapperControlServer(baseControlAPI, authorize)
+ authenticatedWatchAPI := api.NewAuthenticatedWrapperWatchServer(baseWatchAPI, authorize)
+ authenticatedResourceAPI := api.NewAuthenticatedWrapperResourceAllocatorServer(baseResourceAPI, authorize)
+ authenticatedLogsServerAPI := api.NewAuthenticatedWrapperLogsServer(m.logbroker, authorize)
+ authenticatedLogBrokerAPI := api.NewAuthenticatedWrapperLogBrokerServer(m.logbroker, authorize)
+ authenticatedDispatcherAPI := api.NewAuthenticatedWrapperDispatcherServer(m.dispatcher, authorize)
+ authenticatedCAAPI := api.NewAuthenticatedWrapperCAServer(m.caserver, authorize)
+ authenticatedNodeCAAPI := api.NewAuthenticatedWrapperNodeCAServer(m.caserver, authorize)
+ authenticatedRaftAPI := api.NewAuthenticatedWrapperRaftServer(m.raftNode, authorize)
+ authenticatedHealthAPI := api.NewAuthenticatedWrapperHealthServer(healthServer, authorize)
+ authenticatedRaftMembershipAPI := api.NewAuthenticatedWrapperRaftMembershipServer(m.raftNode, authorize)
+
+ proxyDispatcherAPI := api.NewRaftProxyDispatcherServer(authenticatedDispatcherAPI, m.raftNode, nil, ca.WithMetadataForwardTLSInfo)
+ proxyCAAPI := api.NewRaftProxyCAServer(authenticatedCAAPI, m.raftNode, nil, ca.WithMetadataForwardTLSInfo)
+ proxyNodeCAAPI := api.NewRaftProxyNodeCAServer(authenticatedNodeCAAPI, m.raftNode, nil, ca.WithMetadataForwardTLSInfo)
+ proxyRaftMembershipAPI := api.NewRaftProxyRaftMembershipServer(authenticatedRaftMembershipAPI, m.raftNode, nil, ca.WithMetadataForwardTLSInfo)
+ proxyResourceAPI := api.NewRaftProxyResourceAllocatorServer(authenticatedResourceAPI, m.raftNode, nil, ca.WithMetadataForwardTLSInfo)
+ proxyLogBrokerAPI := api.NewRaftProxyLogBrokerServer(authenticatedLogBrokerAPI, m.raftNode, nil, ca.WithMetadataForwardTLSInfo)
+
+ // The following local proxies are only wired up to receive requests
+ // from a trusted local socket, and these requests don't use TLS,
+ // therefore the requests they handle locally should bypass
+ // authorization. When requests are proxied from these servers, they
+ // are sent as requests from this manager rather than forwarded
+ // requests (it has no TLS information to put in the metadata map).
+ forwardAsOwnRequest := func(ctx context.Context) (context.Context, error) { return ctx, nil }
+ handleRequestLocally := func(ctx context.Context) (context.Context, error) {
+ remoteAddr := "127.0.0.1:0"
+
+ m.addrMu.Lock()
+ if m.config.RemoteAPI != nil {
+ if m.config.RemoteAPI.AdvertiseAddr != "" {
+ remoteAddr = m.config.RemoteAPI.AdvertiseAddr
+ } else {
+ remoteAddr = m.config.RemoteAPI.ListenAddr
+ }
+ }
+ m.addrMu.Unlock()
+
+ creds := m.config.SecurityConfig.ClientTLSCreds
+
+ nodeInfo := ca.RemoteNodeInfo{
+ Roles: []string{creds.Role()},
+ Organization: creds.Organization(),
+ NodeID: creds.NodeID(),
+ RemoteAddr: remoteAddr,
+ }
+
+ return context.WithValue(ctx, ca.LocalRequestKey, nodeInfo), nil
+ }
+ localProxyControlAPI := api.NewRaftProxyControlServer(baseControlAPI, m.raftNode, handleRequestLocally, forwardAsOwnRequest)
+ localProxyLogsAPI := api.NewRaftProxyLogsServer(m.logbroker, m.raftNode, handleRequestLocally, forwardAsOwnRequest)
+ localProxyDispatcherAPI := api.NewRaftProxyDispatcherServer(m.dispatcher, m.raftNode, handleRequestLocally, forwardAsOwnRequest)
+ localProxyCAAPI := api.NewRaftProxyCAServer(m.caserver, m.raftNode, handleRequestLocally, forwardAsOwnRequest)
+ localProxyNodeCAAPI := api.NewRaftProxyNodeCAServer(m.caserver, m.raftNode, handleRequestLocally, forwardAsOwnRequest)
+ localProxyResourceAPI := api.NewRaftProxyResourceAllocatorServer(baseResourceAPI, m.raftNode, handleRequestLocally, forwardAsOwnRequest)
+ localProxyLogBrokerAPI := api.NewRaftProxyLogBrokerServer(m.logbroker, m.raftNode, handleRequestLocally, forwardAsOwnRequest)
+
+ // Everything registered on m.server should be an authenticated
+ // wrapper, or a proxy wrapping an authenticated wrapper!
+ api.RegisterCAServer(m.server, proxyCAAPI)
+ api.RegisterNodeCAServer(m.server, proxyNodeCAAPI)
+ api.RegisterRaftServer(m.server, authenticatedRaftAPI)
+ api.RegisterHealthServer(m.server, authenticatedHealthAPI)
+ api.RegisterRaftMembershipServer(m.server, proxyRaftMembershipAPI)
+ api.RegisterControlServer(m.server, authenticatedControlAPI)
+ api.RegisterWatchServer(m.server, authenticatedWatchAPI)
+ api.RegisterLogsServer(m.server, authenticatedLogsServerAPI)
+ api.RegisterLogBrokerServer(m.server, proxyLogBrokerAPI)
+ api.RegisterResourceAllocatorServer(m.server, proxyResourceAPI)
+ api.RegisterDispatcherServer(m.server, proxyDispatcherAPI)
+ grpc_prometheus.Register(m.server)
+
+ api.RegisterControlServer(m.localserver, localProxyControlAPI)
+ api.RegisterWatchServer(m.localserver, baseWatchAPI)
+ api.RegisterLogsServer(m.localserver, localProxyLogsAPI)
+ api.RegisterHealthServer(m.localserver, localHealthServer)
+ api.RegisterDispatcherServer(m.localserver, localProxyDispatcherAPI)
+ api.RegisterCAServer(m.localserver, localProxyCAAPI)
+ api.RegisterNodeCAServer(m.localserver, localProxyNodeCAAPI)
+ api.RegisterResourceAllocatorServer(m.localserver, localProxyResourceAPI)
+ api.RegisterLogBrokerServer(m.localserver, localProxyLogBrokerAPI)
+ grpc_prometheus.Register(m.localserver)
+
+ healthServer.SetServingStatus("Raft", api.HealthCheckResponse_NOT_SERVING)
+ localHealthServer.SetServingStatus("ControlAPI", api.HealthCheckResponse_NOT_SERVING)
+
+ go m.serveListener(ctx, m.remoteListener)
+ go m.serveListener(ctx, m.controlListener)
+
+ defer func() {
+ m.server.Stop()
+ m.localserver.Stop()
+ }()
+
+ // Set the raft server as serving for the health server
+ healthServer.SetServingStatus("Raft", api.HealthCheckResponse_SERVING)
+
+ if err := m.raftNode.JoinAndStart(ctx); err != nil {
+ // Don't block future calls to Stop.
+ close(m.started)
+ return errors.Wrap(err, "can't initialize raft node")
+ }
+
+ localHealthServer.SetServingStatus("ControlAPI", api.HealthCheckResponse_SERVING)
+
+ // Start metrics collection.
+
+ m.collector = metrics.NewCollector(m.raftNode.MemoryStore())
+ go func(collector *metrics.Collector) {
+ if err := collector.Run(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("collector failed with an error")
+ }
+ }(m.collector)
+
+ close(m.started)
+
+ go func() {
+ err := m.raftNode.Run(ctx)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("raft node stopped")
+ m.Stop(ctx, false)
+ }
+ }()
+
+ if err := raft.WaitForLeader(ctx, m.raftNode); err != nil {
+ return err
+ }
+
+ c, err := raft.WaitForCluster(ctx, m.raftNode)
+ if err != nil {
+ return err
+ }
+ raftConfig := c.Spec.Raft
+
+ if err := m.watchForClusterChanges(ctx); err != nil {
+ return err
+ }
+
+ if int(raftConfig.ElectionTick) != m.raftNode.Config.ElectionTick {
+ log.G(ctx).Warningf("election tick value (%ds) is different from the one defined in the cluster config (%vs), the cluster may be unstable", m.raftNode.Config.ElectionTick, raftConfig.ElectionTick)
+ }
+ if int(raftConfig.HeartbeatTick) != m.raftNode.Config.HeartbeatTick {
+ log.G(ctx).Warningf("heartbeat tick value (%ds) is different from the one defined in the cluster config (%vs), the cluster may be unstable", m.raftNode.Config.HeartbeatTick, raftConfig.HeartbeatTick)
+ }
+
+ // wait for an error in serving.
+ err = <-m.errServe
+ m.mu.Lock()
+ if m.stopped {
+ m.mu.Unlock()
+ return nil
+ }
+ m.mu.Unlock()
+ m.Stop(ctx, false)
+
+ return err
+}
+
+const stopTimeout = 8 * time.Second
+
+// Stop stops the manager. It immediately closes all open connections and
+// active RPCs as well as stopping the scheduler. If clearData is set, the
+// raft logs, snapshots, and keys will be erased.
+func (m *Manager) Stop(ctx context.Context, clearData bool) {
+ log.G(ctx).Info("Stopping manager")
+ // It's not safe to start shutting down while the manager is still
+ // starting up.
+ <-m.started
+
+ // the mutex stops us from trying to stop while we're already stopping, or
+ // from returning before we've finished stopping.
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.stopped {
+ return
+ }
+ m.stopped = true
+
+ srvDone, localSrvDone := make(chan struct{}), make(chan struct{})
+ go func() {
+ m.server.GracefulStop()
+ close(srvDone)
+ }()
+ go func() {
+ m.localserver.GracefulStop()
+ close(localSrvDone)
+ }()
+
+ m.raftNode.Cancel()
+
+ if m.collector != nil {
+ m.collector.Stop()
+ }
+
+ m.dispatcher.Stop()
+ m.logbroker.Stop()
+ m.caserver.Stop()
+
+ if m.allocator != nil {
+ m.allocator.Stop()
+ }
+ if m.replicatedOrchestrator != nil {
+ m.replicatedOrchestrator.Stop()
+ }
+ if m.globalOrchestrator != nil {
+ m.globalOrchestrator.Stop()
+ }
+ if m.taskReaper != nil {
+ m.taskReaper.Stop()
+ }
+ if m.constraintEnforcer != nil {
+ m.constraintEnforcer.Stop()
+ }
+ if m.scheduler != nil {
+ m.scheduler.Stop()
+ }
+ if m.roleManager != nil {
+ m.roleManager.Stop()
+ }
+ if m.keyManager != nil {
+ m.keyManager.Stop()
+ }
+
+ if clearData {
+ m.raftNode.ClearData()
+ }
+ m.cancelFunc()
+ <-m.raftNode.Done()
+
+ timer := time.AfterFunc(stopTimeout, func() {
+ m.server.Stop()
+ m.localserver.Stop()
+ })
+ defer timer.Stop()
+ // TODO: we're not waiting on ctx because it very well could be passed from Run,
+ // which is already cancelled here. We need to refactor that.
+ select {
+ case <-srvDone:
+ <-localSrvDone
+ case <-localSrvDone:
+ <-srvDone
+ }
+
+ log.G(ctx).Info("Manager shut down")
+ // mutex is released and Run can return now
+}
+
+func (m *Manager) updateKEK(ctx context.Context, cluster *api.Cluster) error {
+ securityConfig := m.config.SecurityConfig
+ nodeID := m.config.SecurityConfig.ClientTLSCreds.NodeID()
+ logger := log.G(ctx).WithFields(logrus.Fields{
+ "node.id": nodeID,
+ "node.role": ca.ManagerRole,
+ })
+
+ kekData := ca.KEKData{Version: cluster.Meta.Version.Index}
+ for _, encryptionKey := range cluster.UnlockKeys {
+ if encryptionKey.Subsystem == ca.ManagerRole {
+ kekData.KEK = encryptionKey.Key
+ break
+ }
+ }
+ updated, unlockedToLocked, err := m.dekRotator.MaybeUpdateKEK(kekData)
+ if err != nil {
+ logger.WithError(err).Errorf("failed to re-encrypt TLS key with a new KEK")
+ return err
+ }
+ if updated {
+ logger.Debug("successfully rotated KEK")
+ }
+ if unlockedToLocked {
+ // a best effort attempt to update the TLS certificate - if it fails, it'll be updated the next time it renews;
+ // don't wait because it might take a bit
+ go func() {
+ insecureCreds := credentials.NewTLS(&tls.Config{InsecureSkipVerify: true})
+
+ conn, err := grpc.Dial(
+ m.config.ControlAPI,
+ grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
+ grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor),
+ grpc.WithTransportCredentials(insecureCreds),
+ grpc.WithDialer(
+ func(addr string, timeout time.Duration) (net.Conn, error) {
+ return xnet.DialTimeoutLocal(addr, timeout)
+ }),
+ )
+ if err != nil {
+ logger.WithError(err).Error("failed to connect to local manager socket after locking the cluster")
+ return
+ }
+
+ defer conn.Close()
+
+ connBroker := connectionbroker.New(remotes.NewRemotes())
+ connBroker.SetLocalConn(conn)
+ if err := ca.RenewTLSConfigNow(ctx, securityConfig, connBroker, m.config.RootCAPaths); err != nil {
+ logger.WithError(err).Error("failed to download new TLS certificate after locking the cluster")
+ }
+ }()
+ }
+ return nil
+}
+
+func (m *Manager) watchForClusterChanges(ctx context.Context) error {
+ clusterID := m.config.SecurityConfig.ClientTLSCreds.Organization()
+ clusterWatch, clusterWatchCancel, err := store.ViewAndWatch(m.raftNode.MemoryStore(),
+ func(tx store.ReadTx) error {
+ cluster := store.GetCluster(tx, clusterID)
+ if cluster == nil {
+ return fmt.Errorf("unable to get current cluster")
+ }
+ if err := m.caserver.UpdateRootCA(ctx, cluster); err != nil {
+ log.G(ctx).WithError(err).Error("could not update security config")
+ }
+ return m.updateKEK(ctx, cluster)
+ },
+ api.EventUpdateCluster{
+ Cluster: &api.Cluster{ID: clusterID},
+ Checks: []api.ClusterCheckFunc{api.ClusterCheckID},
+ },
+ )
+ if err != nil {
+ return err
+ }
+ go func() {
+ for {
+ select {
+ case event := <-clusterWatch:
+ clusterEvent := event.(api.EventUpdateCluster)
+ if err := m.caserver.UpdateRootCA(ctx, clusterEvent.Cluster); err != nil {
+ log.G(ctx).WithError(err).Error("could not update security config")
+ }
+ m.updateKEK(ctx, clusterEvent.Cluster)
+ case <-ctx.Done():
+ clusterWatchCancel()
+ return
+ }
+ }
+ }()
+ return nil
+}
+
+// rotateRootCAKEK will attempt to rotate the key-encryption-key for root CA key-material in raft.
+// If there is no passphrase set in ENV, it returns.
+// If there is plain-text root key-material, and a passphrase set, it encrypts it.
+// If there is encrypted root key-material and it is using the current passphrase, it returns.
+// If there is encrypted root key-material, and it is using the previous passphrase, it
+// re-encrypts it with the current passphrase.
+func (m *Manager) rotateRootCAKEK(ctx context.Context, clusterID string) error {
+ // If we don't have a KEK, we won't ever be rotating anything
+ strPassphrase := os.Getenv(ca.PassphraseENVVar)
+ strPassphrasePrev := os.Getenv(ca.PassphraseENVVarPrev)
+ if strPassphrase == "" && strPassphrasePrev == "" {
+ return nil
+ }
+ if strPassphrase != "" {
+ log.G(ctx).Warn("Encrypting the root CA key in swarm using environment variables is deprecated. " +
+ "Support for decrypting or rotating the key will be removed in the future.")
+ }
+
+ passphrase := []byte(strPassphrase)
+ passphrasePrev := []byte(strPassphrasePrev)
+
+ s := m.raftNode.MemoryStore()
+ var (
+ cluster *api.Cluster
+ err error
+ finalKey []byte
+ )
+ // Retrieve the cluster identified by ClusterID
+ return s.Update(func(tx store.Tx) error {
+ cluster = store.GetCluster(tx, clusterID)
+ if cluster == nil {
+ return fmt.Errorf("cluster not found: %s", clusterID)
+ }
+
+ // Try to get the private key from the cluster
+ privKeyPEM := cluster.RootCA.CAKey
+ if len(privKeyPEM) == 0 {
+ // We have no PEM root private key in this cluster.
+ log.G(ctx).Warnf("cluster %s does not have private key material", clusterID)
+ return nil
+ }
+
+ // Decode the PEM private key
+ keyBlock, _ := pem.Decode(privKeyPEM)
+ if keyBlock == nil {
+ return fmt.Errorf("invalid PEM-encoded private key inside of cluster %s", clusterID)
+ }
+
+ if x509.IsEncryptedPEMBlock(keyBlock) {
+ // PEM encryption does not have a digest, so sometimes decryption doesn't
+ // error even with the wrong passphrase. So actually try to parse it into a valid key.
+ _, err := helpers.ParsePrivateKeyPEMWithPassword(privKeyPEM, []byte(passphrase))
+ if err == nil {
+ // This key is already correctly encrypted with the correct KEK, nothing to do here
+ return nil
+ }
+
+ // This key is already encrypted, but failed with current main passphrase.
+ // Let's try to decrypt with the previous passphrase, and parse into a valid key, for the
+ // same reason as above.
+ _, err = helpers.ParsePrivateKeyPEMWithPassword(privKeyPEM, []byte(passphrasePrev))
+ if err != nil {
+ // We were not able to decrypt either with the main or backup passphrase, error
+ return err
+ }
+ // ok the above passphrase is correct, so decrypt the PEM block so we can re-encrypt -
+ // since the key was successfully decrypted above, there will be no error doing PEM
+ // decryption
+ unencryptedDER, _ := x509.DecryptPEMBlock(keyBlock, []byte(passphrasePrev))
+ unencryptedKeyBlock := &pem.Block{
+ Type: keyBlock.Type,
+ Bytes: unencryptedDER,
+ }
+
+ // we were able to decrypt the key with the previous passphrase - if the current passphrase is empty,
+ // the we store the decrypted key in raft
+ finalKey = pem.EncodeToMemory(unencryptedKeyBlock)
+
+ // the current passphrase is not empty, so let's encrypt with the new one and store it in raft
+ if strPassphrase != "" {
+ finalKey, err = ca.EncryptECPrivateKey(finalKey, strPassphrase)
+ if err != nil {
+ log.G(ctx).WithError(err).Debugf("failed to rotate the key-encrypting-key for the root key material of cluster %s", clusterID)
+ return err
+ }
+ }
+ } else if strPassphrase != "" {
+ // If this key is not encrypted, and the passphrase is not nil, then we have to encrypt it
+ finalKey, err = ca.EncryptECPrivateKey(privKeyPEM, strPassphrase)
+ if err != nil {
+ log.G(ctx).WithError(err).Debugf("failed to rotate the key-encrypting-key for the root key material of cluster %s", clusterID)
+ return err
+ }
+ } else {
+ return nil // don't update if it's not encrypted and we don't want it encrypted
+ }
+
+ log.G(ctx).Infof("Updating the encryption on the root key material of cluster %s", clusterID)
+ cluster.RootCA.CAKey = finalKey
+ return store.UpdateCluster(tx, cluster)
+ })
+}
+
+// handleLeadershipEvents handles the is leader event or is follower event.
+func (m *Manager) handleLeadershipEvents(ctx context.Context, leadershipCh chan events.Event) {
+ for {
+ select {
+ case leadershipEvent := <-leadershipCh:
+ m.mu.Lock()
+ if m.stopped {
+ m.mu.Unlock()
+ return
+ }
+ newState := leadershipEvent.(raft.LeadershipState)
+
+ if newState == raft.IsLeader {
+ m.becomeLeader(ctx)
+ } else if newState == raft.IsFollower {
+ m.becomeFollower()
+ }
+ m.mu.Unlock()
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+// serveListener serves a listener for local and non local connections.
+func (m *Manager) serveListener(ctx context.Context, lCh <-chan net.Listener) {
+ var l net.Listener
+ select {
+ case l = <-lCh:
+ case <-ctx.Done():
+ return
+ }
+ ctx = log.WithLogger(ctx, log.G(ctx).WithFields(
+ logrus.Fields{
+ "proto": l.Addr().Network(),
+ "addr": l.Addr().String(),
+ }))
+ if _, ok := l.(*net.TCPListener); !ok {
+ log.G(ctx).Info("Listening for local connections")
+ // we need to disallow double closes because UnixListener.Close
+ // can delete unix-socket file of newer listener. grpc calls
+ // Close twice indeed: in Serve and in Stop.
+ m.errServe <- m.localserver.Serve(&closeOnceListener{Listener: l})
+ } else {
+ log.G(ctx).Info("Listening for connections")
+ m.errServe <- m.server.Serve(l)
+ }
+}
+
+// becomeLeader starts the subsystems that are run on the leader.
+func (m *Manager) becomeLeader(ctx context.Context) {
+ s := m.raftNode.MemoryStore()
+
+ rootCA := m.config.SecurityConfig.RootCA()
+ nodeID := m.config.SecurityConfig.ClientTLSCreds.NodeID()
+
+ raftCfg := raft.DefaultRaftConfig()
+ raftCfg.ElectionTick = uint32(m.raftNode.Config.ElectionTick)
+ raftCfg.HeartbeatTick = uint32(m.raftNode.Config.HeartbeatTick)
+
+ clusterID := m.config.SecurityConfig.ClientTLSCreds.Organization()
+
+ initialCAConfig := ca.DefaultCAConfig()
+ initialCAConfig.ExternalCAs = m.config.ExternalCAs
+
+ var unlockKeys []*api.EncryptionKey
+ if m.config.AutoLockManagers {
+ unlockKeys = []*api.EncryptionKey{{
+ Subsystem: ca.ManagerRole,
+ Key: m.config.UnlockKey,
+ }}
+ }
+
+ s.Update(func(tx store.Tx) error {
+ // Add a default cluster object to the
+ // store. Don't check the error because
+ // we expect this to fail unless this
+ // is a brand new cluster.
+ store.CreateCluster(tx, defaultClusterObject(
+ clusterID,
+ initialCAConfig,
+ raftCfg,
+ api.EncryptionConfig{AutoLockManagers: m.config.AutoLockManagers},
+ unlockKeys,
+ rootCA))
+ // Add Node entry for ourself, if one
+ // doesn't exist already.
+ freshCluster := nil == store.CreateNode(tx, managerNode(nodeID, m.config.Availability))
+
+ if freshCluster {
+ // This is a fresh swarm cluster. Add to store now any initial
+ // cluster resource, like the default ingress network which
+ // provides the routing mesh for this cluster.
+ log.G(ctx).Info("Creating default ingress network")
+ if err := store.CreateNetwork(tx, newIngressNetwork()); err != nil {
+ log.G(ctx).WithError(err).Error("failed to create default ingress network")
+ }
+ }
+ // Create now the static predefined if the store does not contain predefined
+ //networks like bridge/host node-local networks which
+ // are known to be present in each cluster node. This is needed
+ // in order to allow running services on the predefined docker
+ // networks like `bridge` and `host`.
+ for _, p := range allocator.PredefinedNetworks() {
+ if store.GetNetwork(tx, p.Name) == nil {
+ if err := store.CreateNetwork(tx, newPredefinedNetwork(p.Name, p.Driver)); err != nil {
+ log.G(ctx).WithError(err).Error("failed to create predefined network " + p.Name)
+ }
+ }
+ }
+ return nil
+ })
+
+ // Attempt to rotate the key-encrypting-key of the root CA key-material
+ err := m.rotateRootCAKEK(ctx, clusterID)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("root key-encrypting-key rotation failed")
+ }
+
+ m.replicatedOrchestrator = replicated.NewReplicatedOrchestrator(s)
+ m.constraintEnforcer = constraintenforcer.New(s)
+ m.globalOrchestrator = global.NewGlobalOrchestrator(s)
+ m.taskReaper = taskreaper.New(s)
+ m.scheduler = scheduler.New(s)
+ m.keyManager = keymanager.New(s, keymanager.DefaultConfig())
+ m.roleManager = newRoleManager(s, m.raftNode)
+
+ // TODO(stevvooe): Allocate a context that can be used to
+ // shutdown underlying manager processes when leadership is
+ // lost.
+
+ m.allocator, err = allocator.New(s, m.config.PluginGetter)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed to create allocator")
+ // TODO(stevvooe): It doesn't seem correct here to fail
+ // creating the allocator but then use it anyway.
+ }
+
+ if m.keyManager != nil {
+ go func(keyManager *keymanager.KeyManager) {
+ if err := keyManager.Run(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("keymanager failed with an error")
+ }
+ }(m.keyManager)
+ }
+
+ go func(d *dispatcher.Dispatcher) {
+ if err := d.Run(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("Dispatcher exited with an error")
+ }
+ }(m.dispatcher)
+
+ go func(lb *logbroker.LogBroker) {
+ if err := lb.Run(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("LogBroker exited with an error")
+ }
+ }(m.logbroker)
+
+ go func(server *ca.Server) {
+ if err := server.Run(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("CA signer exited with an error")
+ }
+ }(m.caserver)
+
+ // Start all sub-components in separate goroutines.
+ // TODO(aluzzardi): This should have some kind of error handling so that
+ // any component that goes down would bring the entire manager down.
+ if m.allocator != nil {
+ go func(allocator *allocator.Allocator) {
+ if err := allocator.Run(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("allocator exited with an error")
+ }
+ }(m.allocator)
+ }
+
+ go func(scheduler *scheduler.Scheduler) {
+ if err := scheduler.Run(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("scheduler exited with an error")
+ }
+ }(m.scheduler)
+
+ go func(constraintEnforcer *constraintenforcer.ConstraintEnforcer) {
+ constraintEnforcer.Run()
+ }(m.constraintEnforcer)
+
+ go func(taskReaper *taskreaper.TaskReaper) {
+ taskReaper.Run(ctx)
+ }(m.taskReaper)
+
+ go func(orchestrator *replicated.Orchestrator) {
+ if err := orchestrator.Run(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("replicated orchestrator exited with an error")
+ }
+ }(m.replicatedOrchestrator)
+
+ go func(globalOrchestrator *global.Orchestrator) {
+ if err := globalOrchestrator.Run(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("global orchestrator exited with an error")
+ }
+ }(m.globalOrchestrator)
+
+ go func(roleManager *roleManager) {
+ roleManager.Run(ctx)
+ }(m.roleManager)
+}
+
+// becomeFollower shuts down the subsystems that are only run by the leader.
+func (m *Manager) becomeFollower() {
+ m.dispatcher.Stop()
+ m.logbroker.Stop()
+ m.caserver.Stop()
+
+ if m.allocator != nil {
+ m.allocator.Stop()
+ m.allocator = nil
+ }
+
+ m.constraintEnforcer.Stop()
+ m.constraintEnforcer = nil
+
+ m.replicatedOrchestrator.Stop()
+ m.replicatedOrchestrator = nil
+
+ m.globalOrchestrator.Stop()
+ m.globalOrchestrator = nil
+
+ m.taskReaper.Stop()
+ m.taskReaper = nil
+
+ m.scheduler.Stop()
+ m.scheduler = nil
+
+ m.roleManager.Stop()
+ m.roleManager = nil
+
+ if m.keyManager != nil {
+ m.keyManager.Stop()
+ m.keyManager = nil
+ }
+}
+
+// defaultClusterObject creates a default cluster.
+func defaultClusterObject(
+ clusterID string,
+ initialCAConfig api.CAConfig,
+ raftCfg api.RaftConfig,
+ encryptionConfig api.EncryptionConfig,
+ initialUnlockKeys []*api.EncryptionKey,
+ rootCA *ca.RootCA) *api.Cluster {
+ var caKey []byte
+ if rcaSigner, err := rootCA.Signer(); err == nil {
+ caKey = rcaSigner.Key
+ }
+
+ return &api.Cluster{
+ ID: clusterID,
+ Spec: api.ClusterSpec{
+ Annotations: api.Annotations{
+ Name: store.DefaultClusterName,
+ },
+ Orchestration: api.OrchestrationConfig{
+ TaskHistoryRetentionLimit: defaultTaskHistoryRetentionLimit,
+ },
+ Dispatcher: api.DispatcherConfig{
+ HeartbeatPeriod: gogotypes.DurationProto(dispatcher.DefaultHeartBeatPeriod),
+ },
+ Raft: raftCfg,
+ CAConfig: initialCAConfig,
+ EncryptionConfig: encryptionConfig,
+ },
+ RootCA: api.RootCA{
+ CAKey: caKey,
+ CACert: rootCA.Certs,
+ CACertHash: rootCA.Digest.String(),
+ JoinTokens: api.JoinTokens{
+ Worker: ca.GenerateJoinToken(rootCA),
+ Manager: ca.GenerateJoinToken(rootCA),
+ },
+ },
+ UnlockKeys: initialUnlockKeys,
+ }
+}
+
+// managerNode creates a new node with NodeRoleManager role.
+func managerNode(nodeID string, availability api.NodeSpec_Availability) *api.Node {
+ return &api.Node{
+ ID: nodeID,
+ Certificate: api.Certificate{
+ CN: nodeID,
+ Role: api.NodeRoleManager,
+ Status: api.IssuanceStatus{
+ State: api.IssuanceStateIssued,
+ },
+ },
+ Spec: api.NodeSpec{
+ DesiredRole: api.NodeRoleManager,
+ Membership: api.NodeMembershipAccepted,
+ Availability: availability,
+ },
+ }
+}
+
+// newIngressNetwork returns the network object for the default ingress
+// network, the network which provides the routing mesh. Caller will save to
+// store this object once, at fresh cluster creation. It is expected to
+// call this function inside a store update transaction.
+func newIngressNetwork() *api.Network {
+ return &api.Network{
+ ID: identity.NewID(),
+ Spec: api.NetworkSpec{
+ Ingress: true,
+ Annotations: api.Annotations{
+ Name: "ingress",
+ },
+ DriverConfig: &api.Driver{},
+ IPAM: &api.IPAMOptions{
+ Driver: &api.Driver{},
+ Configs: []*api.IPAMConfig{
+ {
+ Subnet: "10.255.0.0/16",
+ },
+ },
+ },
+ },
+ }
+}
+
+// Creates a network object representing one of the predefined networks
+// known to be statically created on the cluster nodes. These objects
+// are populated in the store at cluster creation solely in order to
+// support running services on the nodes' predefined networks.
+// External clients can filter these predefined networks by looking
+// at the predefined label.
+func newPredefinedNetwork(name, driver string) *api.Network {
+ return &api.Network{
+ ID: identity.NewID(),
+ Spec: api.NetworkSpec{
+ Annotations: api.Annotations{
+ Name: name,
+ Labels: map[string]string{
+ networkallocator.PredefinedLabel: "true",
+ },
+ },
+ DriverConfig: &api.Driver{Name: driver},
+ },
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/metrics/collector.go b/vendor/github.com/docker/swarmkit/manager/metrics/collector.go
new file mode 100644
index 0000000..d5adcb8
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/metrics/collector.go
@@ -0,0 +1,104 @@
+package metrics
+
+import (
+ "context"
+
+ "strings"
+
+ metrics "github.com/docker/go-metrics"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/state/store"
+)
+
+var (
+ ns = metrics.NewNamespace("swarm", "manager", nil)
+ nodesMetric metrics.LabeledGauge
+)
+
+func init() {
+ nodesMetric = ns.NewLabeledGauge("nodes", "The number of nodes", "", "state")
+ for _, state := range api.NodeStatus_State_name {
+ nodesMetric.WithValues(strings.ToLower(state)).Set(0)
+ }
+ metrics.Register(ns)
+}
+
+// Collector collects swarmkit metrics
+type Collector struct {
+ store *store.MemoryStore
+
+ // stopChan signals to the state machine to stop running.
+ stopChan chan struct{}
+ // doneChan is closed when the state machine terminates.
+ doneChan chan struct{}
+}
+
+// NewCollector creates a new metrics collector
+func NewCollector(store *store.MemoryStore) *Collector {
+ return &Collector{
+ store: store,
+ stopChan: make(chan struct{}),
+ doneChan: make(chan struct{}),
+ }
+}
+
+func (c *Collector) updateNodeState(prevNode, newNode *api.Node) {
+ // Skip updates if nothing changed.
+ if prevNode != nil && newNode != nil && prevNode.Status.State == newNode.Status.State {
+ return
+ }
+
+ if prevNode != nil {
+ nodesMetric.WithValues(strings.ToLower(prevNode.Status.State.String())).Dec(1)
+ }
+ if newNode != nil {
+ nodesMetric.WithValues(strings.ToLower(newNode.Status.State.String())).Inc(1)
+ }
+}
+
+// Run contains the collector event loop
+func (c *Collector) Run(ctx context.Context) error {
+ defer close(c.doneChan)
+
+ watcher, cancel, err := store.ViewAndWatch(c.store, func(readTx store.ReadTx) error {
+ nodes, err := store.FindNodes(readTx, store.All)
+ if err != nil {
+ return err
+ }
+ for _, node := range nodes {
+ c.updateNodeState(nil, node)
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ defer cancel()
+
+ for {
+ select {
+ case event := <-watcher:
+ switch v := event.(type) {
+ case api.EventCreateNode:
+ c.updateNodeState(nil, v.Node)
+ case api.EventUpdateNode:
+ c.updateNodeState(v.OldNode, v.Node)
+ case api.EventDeleteNode:
+ c.updateNodeState(v.Node, nil)
+ }
+ case <-c.stopChan:
+ return nil
+ }
+ }
+}
+
+// Stop stops the collector.
+func (c *Collector) Stop() {
+ close(c.stopChan)
+ <-c.doneChan
+
+ // Clean the metrics on exit.
+ for _, state := range api.NodeStatus_State_name {
+ nodesMetric.WithValues(strings.ToLower(state)).Set(0)
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/constraintenforcer/constraint_enforcer.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/constraintenforcer/constraint_enforcer.go
new file mode 100644
index 0000000..2978898
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/constraintenforcer/constraint_enforcer.go
@@ -0,0 +1,183 @@
+package constraintenforcer
+
+import (
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/genericresource"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/constraint"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/protobuf/ptypes"
+)
+
+// ConstraintEnforcer watches for updates to nodes and shuts down tasks that no
+// longer satisfy scheduling constraints or resource limits.
+type ConstraintEnforcer struct {
+ store *store.MemoryStore
+ stopChan chan struct{}
+ doneChan chan struct{}
+}
+
+// New creates a new ConstraintEnforcer.
+func New(store *store.MemoryStore) *ConstraintEnforcer {
+ return &ConstraintEnforcer{
+ store: store,
+ stopChan: make(chan struct{}),
+ doneChan: make(chan struct{}),
+ }
+}
+
+// Run is the ConstraintEnforcer's main loop.
+func (ce *ConstraintEnforcer) Run() {
+ defer close(ce.doneChan)
+
+ watcher, cancelWatch := state.Watch(ce.store.WatchQueue(), api.EventUpdateNode{})
+ defer cancelWatch()
+
+ var (
+ nodes []*api.Node
+ err error
+ )
+ ce.store.View(func(readTx store.ReadTx) {
+ nodes, err = store.FindNodes(readTx, store.All)
+ })
+ if err != nil {
+ log.L.WithError(err).Error("failed to check nodes for noncompliant tasks")
+ } else {
+ for _, node := range nodes {
+ ce.rejectNoncompliantTasks(node)
+ }
+ }
+
+ for {
+ select {
+ case event := <-watcher:
+ node := event.(api.EventUpdateNode).Node
+ ce.rejectNoncompliantTasks(node)
+ case <-ce.stopChan:
+ return
+ }
+ }
+}
+
+func (ce *ConstraintEnforcer) rejectNoncompliantTasks(node *api.Node) {
+ // If the availability is "drain", the orchestrator will
+ // shut down all tasks.
+ // If the availability is "pause", we shouldn't touch
+ // the tasks on this node.
+ if node.Spec.Availability != api.NodeAvailabilityActive {
+ return
+ }
+
+ var (
+ tasks []*api.Task
+ err error
+ )
+
+ ce.store.View(func(tx store.ReadTx) {
+ tasks, err = store.FindTasks(tx, store.ByNodeID(node.ID))
+ })
+
+ if err != nil {
+ log.L.WithError(err).Errorf("failed to list tasks for node ID %s", node.ID)
+ }
+
+ available := &api.Resources{}
+ var fakeStore []*api.GenericResource
+
+ if node.Description != nil && node.Description.Resources != nil {
+ available = node.Description.Resources.Copy()
+ }
+
+ removeTasks := make(map[string]*api.Task)
+
+ // TODO(aaronl): The set of tasks removed will be
+ // nondeterministic because it depends on the order of
+ // the slice returned from FindTasks. We could do
+ // a separate pass over the tasks for each type of
+ // resource, and sort by the size of the reservation
+ // to remove the most resource-intensive tasks.
+loop:
+ for _, t := range tasks {
+ if t.DesiredState < api.TaskStateAssigned || t.DesiredState > api.TaskStateRunning {
+ continue
+ }
+
+ // Ensure that the task still meets scheduling
+ // constraints.
+ if t.Spec.Placement != nil && len(t.Spec.Placement.Constraints) != 0 {
+ constraints, _ := constraint.Parse(t.Spec.Placement.Constraints)
+ if !constraint.NodeMatches(constraints, node) {
+ removeTasks[t.ID] = t
+ continue
+ }
+ }
+
+ // Ensure that the task assigned to the node
+ // still satisfies the resource limits.
+ if t.Spec.Resources != nil && t.Spec.Resources.Reservations != nil {
+ if t.Spec.Resources.Reservations.MemoryBytes > available.MemoryBytes {
+ removeTasks[t.ID] = t
+ continue
+ }
+ if t.Spec.Resources.Reservations.NanoCPUs > available.NanoCPUs {
+ removeTasks[t.ID] = t
+ continue
+ }
+ for _, ta := range t.AssignedGenericResources {
+ // Type change or no longer available
+ if genericresource.HasResource(ta, available.Generic) {
+ removeTasks[t.ID] = t
+ break loop
+ }
+ }
+
+ available.MemoryBytes -= t.Spec.Resources.Reservations.MemoryBytes
+ available.NanoCPUs -= t.Spec.Resources.Reservations.NanoCPUs
+
+ genericresource.ClaimResources(&available.Generic,
+ &fakeStore, t.AssignedGenericResources)
+ }
+ }
+
+ if len(removeTasks) != 0 {
+ err := ce.store.Batch(func(batch *store.Batch) error {
+ for _, t := range removeTasks {
+ err := batch.Update(func(tx store.Tx) error {
+ t = store.GetTask(tx, t.ID)
+ if t == nil || t.DesiredState > api.TaskStateRunning {
+ return nil
+ }
+
+ // We set the observed state to
+ // REJECTED, rather than the desired
+ // state. Desired state is owned by the
+ // orchestrator, and setting it directly
+ // will bypass actions such as
+ // restarting the task on another node
+ // (if applicable).
+ t.Status.State = api.TaskStateRejected
+ t.Status.Message = "assigned node no longer meets constraints"
+ t.Status.Timestamp = ptypes.MustTimestampProto(time.Now())
+ return store.UpdateTask(tx, t)
+ })
+ if err != nil {
+ log.L.WithError(err).Errorf("failed to shut down task %s", t.ID)
+ }
+ }
+ return nil
+ })
+
+ if err != nil {
+ log.L.WithError(err).Errorf("failed to shut down tasks")
+ }
+ }
+}
+
+// Stop stops the ConstraintEnforcer and waits for the main loop to exit.
+func (ce *ConstraintEnforcer) Stop() {
+ close(ce.stopChan)
+ <-ce.doneChan
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/global/global.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/global/global.go
new file mode 100644
index 0000000..f5e6b3a
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/global/global.go
@@ -0,0 +1,592 @@
+package global
+
+import (
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/constraint"
+ "github.com/docker/swarmkit/manager/orchestrator"
+ "github.com/docker/swarmkit/manager/orchestrator/restart"
+ "github.com/docker/swarmkit/manager/orchestrator/taskinit"
+ "github.com/docker/swarmkit/manager/orchestrator/update"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+)
+
+type globalService struct {
+ *api.Service
+
+ // Compiled constraints
+ constraints []constraint.Constraint
+}
+
+// Orchestrator runs a reconciliation loop to create and destroy tasks as
+// necessary for global services.
+type Orchestrator struct {
+ store *store.MemoryStore
+ // nodes is the set of non-drained nodes in the cluster, indexed by node ID
+ nodes map[string]*api.Node
+ // globalServices has all the global services in the cluster, indexed by ServiceID
+ globalServices map[string]globalService
+ restartTasks map[string]struct{}
+
+ // stopChan signals to the state machine to stop running.
+ stopChan chan struct{}
+ // doneChan is closed when the state machine terminates.
+ doneChan chan struct{}
+
+ updater *update.Supervisor
+ restarts *restart.Supervisor
+
+ cluster *api.Cluster // local instance of the cluster
+}
+
+// NewGlobalOrchestrator creates a new global Orchestrator
+func NewGlobalOrchestrator(store *store.MemoryStore) *Orchestrator {
+ restartSupervisor := restart.NewSupervisor(store)
+ updater := update.NewSupervisor(store, restartSupervisor)
+ return &Orchestrator{
+ store: store,
+ nodes: make(map[string]*api.Node),
+ globalServices: make(map[string]globalService),
+ stopChan: make(chan struct{}),
+ doneChan: make(chan struct{}),
+ updater: updater,
+ restarts: restartSupervisor,
+ restartTasks: make(map[string]struct{}),
+ }
+}
+
+func (g *Orchestrator) initTasks(ctx context.Context, readTx store.ReadTx) error {
+ return taskinit.CheckTasks(ctx, g.store, readTx, g, g.restarts)
+}
+
+// Run contains the global orchestrator event loop
+func (g *Orchestrator) Run(ctx context.Context) error {
+ defer close(g.doneChan)
+
+ // Watch changes to services and tasks
+ queue := g.store.WatchQueue()
+ watcher, cancel := queue.Watch()
+ defer cancel()
+
+ // lookup the cluster
+ var err error
+ g.store.View(func(readTx store.ReadTx) {
+ var clusters []*api.Cluster
+ clusters, err = store.FindClusters(readTx, store.ByName("default"))
+
+ if len(clusters) != 1 {
+ return // just pick up the cluster when it is created.
+ }
+ g.cluster = clusters[0]
+ })
+ if err != nil {
+ return err
+ }
+
+ // Get list of nodes
+ var nodes []*api.Node
+ g.store.View(func(readTx store.ReadTx) {
+ nodes, err = store.FindNodes(readTx, store.All)
+ })
+ if err != nil {
+ return err
+ }
+ for _, n := range nodes {
+ g.updateNode(n)
+ }
+
+ // Lookup global services
+ var existingServices []*api.Service
+ g.store.View(func(readTx store.ReadTx) {
+ existingServices, err = store.FindServices(readTx, store.All)
+ })
+ if err != nil {
+ return err
+ }
+
+ var reconcileServiceIDs []string
+ for _, s := range existingServices {
+ if orchestrator.IsGlobalService(s) {
+ g.updateService(s)
+ reconcileServiceIDs = append(reconcileServiceIDs, s.ID)
+ }
+ }
+
+ // fix tasks in store before reconciliation loop
+ g.store.View(func(readTx store.ReadTx) {
+ err = g.initTasks(ctx, readTx)
+ })
+ if err != nil {
+ return err
+ }
+
+ g.tickTasks(ctx)
+ g.reconcileServices(ctx, reconcileServiceIDs)
+
+ for {
+ select {
+ case event := <-watcher:
+ // TODO(stevvooe): Use ctx to limit running time of operation.
+ switch v := event.(type) {
+ case api.EventUpdateCluster:
+ g.cluster = v.Cluster
+ case api.EventCreateService:
+ if !orchestrator.IsGlobalService(v.Service) {
+ continue
+ }
+ g.updateService(v.Service)
+ g.reconcileServices(ctx, []string{v.Service.ID})
+ case api.EventUpdateService:
+ if !orchestrator.IsGlobalService(v.Service) {
+ continue
+ }
+ g.updateService(v.Service)
+ g.reconcileServices(ctx, []string{v.Service.ID})
+ case api.EventDeleteService:
+ if !orchestrator.IsGlobalService(v.Service) {
+ continue
+ }
+ orchestrator.DeleteServiceTasks(ctx, g.store, v.Service)
+ // delete the service from service map
+ delete(g.globalServices, v.Service.ID)
+ g.restarts.ClearServiceHistory(v.Service.ID)
+ case api.EventCreateNode:
+ g.updateNode(v.Node)
+ g.reconcileOneNode(ctx, v.Node)
+ case api.EventUpdateNode:
+ g.updateNode(v.Node)
+ switch v.Node.Status.State {
+ // NodeStatus_DISCONNECTED is a transient state, no need to make any change
+ case api.NodeStatus_DOWN:
+ g.removeTasksFromNode(ctx, v.Node)
+ case api.NodeStatus_READY:
+ // node could come back to READY from DOWN or DISCONNECT
+ g.reconcileOneNode(ctx, v.Node)
+ }
+ case api.EventDeleteNode:
+ g.removeTasksFromNode(ctx, v.Node)
+ delete(g.nodes, v.Node.ID)
+ case api.EventUpdateTask:
+ g.handleTaskChange(ctx, v.Task)
+ case api.EventDeleteTask:
+ // CLI allows deleting task
+ if _, exists := g.globalServices[v.Task.ServiceID]; !exists {
+ continue
+ }
+ g.reconcileServicesOneNode(ctx, []string{v.Task.ServiceID}, v.Task.NodeID)
+ }
+ case <-g.stopChan:
+ return nil
+ }
+ g.tickTasks(ctx)
+ }
+}
+
+// FixTask validates a task with the current cluster settings, and takes
+// action to make it conformant to node state and service constraint
+// it's called at orchestrator initialization
+func (g *Orchestrator) FixTask(ctx context.Context, batch *store.Batch, t *api.Task) {
+ if _, exists := g.globalServices[t.ServiceID]; !exists {
+ return
+ }
+ // if a task's DesiredState has past running, the task has been processed
+ if t.DesiredState > api.TaskStateRunning {
+ return
+ }
+
+ var node *api.Node
+ if t.NodeID != "" {
+ node = g.nodes[t.NodeID]
+ }
+ // if the node no longer valid, remove the task
+ if t.NodeID == "" || orchestrator.InvalidNode(node) {
+ g.removeTask(ctx, batch, t)
+ return
+ }
+
+ // restart a task if it fails
+ if t.Status.State > api.TaskStateRunning {
+ g.restartTasks[t.ID] = struct{}{}
+ }
+}
+
+// handleTaskChange defines what orchestrator does when a task is updated by agent
+func (g *Orchestrator) handleTaskChange(ctx context.Context, t *api.Task) {
+ if _, exists := g.globalServices[t.ServiceID]; !exists {
+ return
+ }
+ // if a task's DesiredState has past running, which
+ // means the task has been processed
+ if t.DesiredState > api.TaskStateRunning {
+ return
+ }
+
+ // if a task has passed running, restart it
+ if t.Status.State > api.TaskStateRunning {
+ g.restartTasks[t.ID] = struct{}{}
+ }
+}
+
+// Stop stops the orchestrator.
+func (g *Orchestrator) Stop() {
+ close(g.stopChan)
+ <-g.doneChan
+ g.updater.CancelAll()
+ g.restarts.CancelAll()
+}
+
+func (g *Orchestrator) removeTasksFromNode(ctx context.Context, node *api.Node) {
+ var (
+ tasks []*api.Task
+ err error
+ )
+ g.store.View(func(tx store.ReadTx) {
+ tasks, err = store.FindTasks(tx, store.ByNodeID(node.ID))
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("global orchestrator: removeTasksFromNode failed finding tasks")
+ return
+ }
+
+ err = g.store.Batch(func(batch *store.Batch) error {
+ for _, t := range tasks {
+ // Global orchestrator only removes tasks from globalServices
+ if _, exists := g.globalServices[t.ServiceID]; exists {
+ g.removeTask(ctx, batch, t)
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("global orchestrator: removeTasksFromNode failed batching tasks")
+ }
+}
+
+func (g *Orchestrator) reconcileServices(ctx context.Context, serviceIDs []string) {
+ nodeCompleted := make(map[string]map[string]struct{})
+ nodeTasks := make(map[string]map[string][]*api.Task)
+
+ g.store.View(func(tx store.ReadTx) {
+ for _, serviceID := range serviceIDs {
+ tasks, err := store.FindTasks(tx, store.ByServiceID(serviceID))
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("global orchestrator: reconcileServices failed finding tasks for service %s", serviceID)
+ continue
+ }
+
+ // a node may have completed this service
+ nodeCompleted[serviceID] = make(map[string]struct{})
+ // nodeID -> task list
+ nodeTasks[serviceID] = make(map[string][]*api.Task)
+
+ for _, t := range tasks {
+ if t.DesiredState <= api.TaskStateRunning {
+ // Collect all running instances of this service
+ nodeTasks[serviceID][t.NodeID] = append(nodeTasks[serviceID][t.NodeID], t)
+ } else {
+ // for finished tasks, check restartPolicy
+ if isTaskCompleted(t, orchestrator.RestartCondition(t)) {
+ nodeCompleted[serviceID][t.NodeID] = struct{}{}
+ }
+ }
+ }
+ }
+ })
+
+ updates := make(map[*api.Service][]orchestrator.Slot)
+
+ err := g.store.Batch(func(batch *store.Batch) error {
+ for _, serviceID := range serviceIDs {
+ var updateTasks []orchestrator.Slot
+
+ if _, exists := nodeTasks[serviceID]; !exists {
+ continue
+ }
+
+ service := g.globalServices[serviceID]
+
+ for nodeID, node := range g.nodes {
+ meetsConstraints := constraint.NodeMatches(service.constraints, node)
+ ntasks := nodeTasks[serviceID][nodeID]
+ delete(nodeTasks[serviceID], nodeID)
+
+ // if restart policy considers this node has finished its task
+ // it should remove all running tasks
+ if _, exists := nodeCompleted[serviceID][nodeID]; exists || !meetsConstraints {
+ g.removeTasks(ctx, batch, ntasks)
+ continue
+ }
+
+ if node.Spec.Availability == api.NodeAvailabilityPause {
+ // the node is paused, so we won't add or update
+ // any tasks
+ continue
+ }
+
+ // this node needs to run 1 copy of the task
+ if len(ntasks) == 0 {
+ g.addTask(ctx, batch, service.Service, nodeID)
+ } else {
+ updateTasks = append(updateTasks, ntasks)
+ }
+ }
+
+ if len(updateTasks) > 0 {
+ updates[service.Service] = updateTasks
+ }
+
+ // Remove any tasks assigned to nodes not found in g.nodes.
+ // These must be associated with nodes that are drained, or
+ // nodes that no longer exist.
+ for _, ntasks := range nodeTasks[serviceID] {
+ g.removeTasks(ctx, batch, ntasks)
+ }
+ }
+ return nil
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("global orchestrator: reconcileServices transaction failed")
+ }
+
+ for service, updateTasks := range updates {
+ g.updater.Update(ctx, g.cluster, service, updateTasks)
+ }
+}
+
+// updateNode updates g.nodes based on the current node value
+func (g *Orchestrator) updateNode(node *api.Node) {
+ if node.Spec.Availability == api.NodeAvailabilityDrain {
+ delete(g.nodes, node.ID)
+ } else {
+ g.nodes[node.ID] = node
+ }
+}
+
+// updateService updates g.globalServices based on the current service value
+func (g *Orchestrator) updateService(service *api.Service) {
+ var constraints []constraint.Constraint
+
+ if service.Spec.Task.Placement != nil && len(service.Spec.Task.Placement.Constraints) != 0 {
+ constraints, _ = constraint.Parse(service.Spec.Task.Placement.Constraints)
+ }
+
+ g.globalServices[service.ID] = globalService{
+ Service: service,
+ constraints: constraints,
+ }
+}
+
+// reconcileOneNode checks all global services on one node
+func (g *Orchestrator) reconcileOneNode(ctx context.Context, node *api.Node) {
+ if node.Spec.Availability == api.NodeAvailabilityDrain {
+ log.G(ctx).Debugf("global orchestrator: node %s in drain state, removing tasks from it", node.ID)
+ g.removeTasksFromNode(ctx, node)
+ return
+ }
+
+ var serviceIDs []string
+ for id := range g.globalServices {
+ serviceIDs = append(serviceIDs, id)
+ }
+ g.reconcileServicesOneNode(ctx, serviceIDs, node.ID)
+}
+
+// reconcileServicesOneNode checks the specified services on one node
+func (g *Orchestrator) reconcileServicesOneNode(ctx context.Context, serviceIDs []string, nodeID string) {
+ node, exists := g.nodes[nodeID]
+ if !exists {
+ return
+ }
+
+ // whether each service has completed on the node
+ completed := make(map[string]bool)
+ // tasks by service
+ tasks := make(map[string][]*api.Task)
+
+ var (
+ tasksOnNode []*api.Task
+ err error
+ )
+
+ g.store.View(func(tx store.ReadTx) {
+ tasksOnNode, err = store.FindTasks(tx, store.ByNodeID(nodeID))
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("global orchestrator: reconcile failed finding tasks on node %s", nodeID)
+ return
+ }
+
+ for _, serviceID := range serviceIDs {
+ for _, t := range tasksOnNode {
+ if t.ServiceID != serviceID {
+ continue
+ }
+ if t.DesiredState <= api.TaskStateRunning {
+ tasks[serviceID] = append(tasks[serviceID], t)
+ } else {
+ if isTaskCompleted(t, orchestrator.RestartCondition(t)) {
+ completed[serviceID] = true
+ }
+ }
+ }
+ }
+
+ err = g.store.Batch(func(batch *store.Batch) error {
+ for _, serviceID := range serviceIDs {
+ service, exists := g.globalServices[serviceID]
+ if !exists {
+ continue
+ }
+
+ if !constraint.NodeMatches(service.constraints, node) {
+ continue
+ }
+
+ // if restart policy considers this node has finished its task
+ // it should remove all running tasks
+ if completed[serviceID] {
+ g.removeTasks(ctx, batch, tasks[serviceID])
+ continue
+ }
+
+ if node.Spec.Availability == api.NodeAvailabilityPause {
+ // the node is paused, so we won't add or update tasks
+ continue
+ }
+
+ if len(tasks) == 0 {
+ g.addTask(ctx, batch, service.Service, nodeID)
+ } else {
+ // If task is out of date, update it. This can happen
+ // on node reconciliation if, for example, we pause a
+ // node, update the service, and then activate the node
+ // later.
+
+ // We don't use g.updater here for two reasons:
+ // - This is not a rolling update. Since it was not
+ // triggered directly by updating the service, it
+ // should not observe the rolling update parameters
+ // or show status in UpdateStatus.
+ // - Calling Update cancels any current rolling updates
+ // for the service, such as one triggered by service
+ // reconciliation.
+
+ var (
+ dirtyTasks []*api.Task
+ cleanTasks []*api.Task
+ )
+
+ for _, t := range tasks[serviceID] {
+ if orchestrator.IsTaskDirty(service.Service, t) {
+ dirtyTasks = append(dirtyTasks, t)
+ } else {
+ cleanTasks = append(cleanTasks, t)
+ }
+ }
+
+ if len(cleanTasks) == 0 {
+ g.addTask(ctx, batch, service.Service, nodeID)
+ } else {
+ dirtyTasks = append(dirtyTasks, cleanTasks[1:]...)
+ }
+ g.removeTasks(ctx, batch, dirtyTasks)
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("global orchestrator: reconcileServiceOneNode batch failed")
+ }
+}
+
+func (g *Orchestrator) tickTasks(ctx context.Context) {
+ if len(g.restartTasks) == 0 {
+ return
+ }
+ err := g.store.Batch(func(batch *store.Batch) error {
+ for taskID := range g.restartTasks {
+ err := batch.Update(func(tx store.Tx) error {
+ t := store.GetTask(tx, taskID)
+ if t == nil || t.DesiredState > api.TaskStateRunning {
+ return nil
+ }
+
+ service := store.GetService(tx, t.ServiceID)
+ if service == nil {
+ return nil
+ }
+
+ node, nodeExists := g.nodes[t.NodeID]
+ serviceEntry, serviceExists := g.globalServices[t.ServiceID]
+ if !nodeExists || !serviceExists {
+ return nil
+ }
+ if !constraint.NodeMatches(serviceEntry.constraints, node) {
+ t.DesiredState = api.TaskStateShutdown
+ return store.UpdateTask(tx, t)
+ }
+
+ return g.restarts.Restart(ctx, tx, g.cluster, service, *t)
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("orchestrator restartTask transaction failed")
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("global orchestrator: restartTask transaction failed")
+ }
+ g.restartTasks = make(map[string]struct{})
+}
+
+func (g *Orchestrator) removeTask(ctx context.Context, batch *store.Batch, t *api.Task) {
+ // set existing task DesiredState to TaskStateShutdown
+ // TODO(aaronl): optimistic update?
+ err := batch.Update(func(tx store.Tx) error {
+ t = store.GetTask(tx, t.ID)
+ if t != nil && t.DesiredState < api.TaskStateShutdown {
+ t.DesiredState = api.TaskStateShutdown
+ return store.UpdateTask(tx, t)
+ }
+ return nil
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("global orchestrator: removeTask failed to remove %s", t.ID)
+ }
+}
+
+func (g *Orchestrator) addTask(ctx context.Context, batch *store.Batch, service *api.Service, nodeID string) {
+ task := orchestrator.NewTask(g.cluster, service, 0, nodeID)
+
+ err := batch.Update(func(tx store.Tx) error {
+ if store.GetService(tx, service.ID) == nil {
+ return nil
+ }
+ return store.CreateTask(tx, task)
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("global orchestrator: failed to create task")
+ }
+}
+
+func (g *Orchestrator) removeTasks(ctx context.Context, batch *store.Batch, tasks []*api.Task) {
+ for _, t := range tasks {
+ g.removeTask(ctx, batch, t)
+ }
+}
+
+// IsRelatedService returns true if the service should be governed by this orchestrator
+func (g *Orchestrator) IsRelatedService(service *api.Service) bool {
+ return orchestrator.IsGlobalService(service)
+}
+
+func isTaskCompleted(t *api.Task, restartPolicy api.RestartPolicy_RestartCondition) bool {
+ if t == nil || t.DesiredState <= api.TaskStateRunning {
+ return false
+ }
+ return restartPolicy == api.RestartOnNone ||
+ (restartPolicy == api.RestartOnFailure && t.Status.State == api.TaskStateCompleted)
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/replicated.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/replicated.go
new file mode 100644
index 0000000..18b8e24
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/replicated.go
@@ -0,0 +1,108 @@
+package replicated
+
+import (
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/orchestrator/restart"
+ "github.com/docker/swarmkit/manager/orchestrator/update"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+)
+
+// An Orchestrator runs a reconciliation loop to create and destroy
+// tasks as necessary for the replicated services.
+type Orchestrator struct {
+ store *store.MemoryStore
+
+ reconcileServices map[string]*api.Service
+ restartTasks map[string]struct{}
+
+ // stopChan signals to the state machine to stop running.
+ stopChan chan struct{}
+ // doneChan is closed when the state machine terminates.
+ doneChan chan struct{}
+
+ updater *update.Supervisor
+ restarts *restart.Supervisor
+
+ cluster *api.Cluster // local cluster instance
+}
+
+// NewReplicatedOrchestrator creates a new replicated Orchestrator.
+func NewReplicatedOrchestrator(store *store.MemoryStore) *Orchestrator {
+ restartSupervisor := restart.NewSupervisor(store)
+ updater := update.NewSupervisor(store, restartSupervisor)
+ return &Orchestrator{
+ store: store,
+ stopChan: make(chan struct{}),
+ doneChan: make(chan struct{}),
+ reconcileServices: make(map[string]*api.Service),
+ restartTasks: make(map[string]struct{}),
+ updater: updater,
+ restarts: restartSupervisor,
+ }
+}
+
+// Run contains the orchestrator event loop. It runs until Stop is called.
+func (r *Orchestrator) Run(ctx context.Context) error {
+ defer close(r.doneChan)
+
+ // Watch changes to services and tasks
+ queue := r.store.WatchQueue()
+ watcher, cancel := queue.Watch()
+ defer cancel()
+
+ // Balance existing services and drain initial tasks attached to invalid
+ // nodes
+ var err error
+ r.store.View(func(readTx store.ReadTx) {
+ if err = r.initTasks(ctx, readTx); err != nil {
+ return
+ }
+
+ if err = r.initServices(readTx); err != nil {
+ return
+ }
+
+ if err = r.initCluster(readTx); err != nil {
+ return
+ }
+ })
+ if err != nil {
+ return err
+ }
+
+ r.tick(ctx)
+
+ for {
+ select {
+ case event := <-watcher:
+ // TODO(stevvooe): Use ctx to limit running time of operation.
+ r.handleTaskEvent(ctx, event)
+ r.handleServiceEvent(ctx, event)
+ switch v := event.(type) {
+ case state.EventCommit:
+ r.tick(ctx)
+ case api.EventUpdateCluster:
+ r.cluster = v.Cluster
+ }
+ case <-r.stopChan:
+ return nil
+ }
+ }
+}
+
+// Stop stops the orchestrator.
+func (r *Orchestrator) Stop() {
+ close(r.stopChan)
+ <-r.doneChan
+ r.updater.CancelAll()
+ r.restarts.CancelAll()
+}
+
+func (r *Orchestrator) tick(ctx context.Context) {
+ // tickTasks must be called first, so we respond to task-level changes
+ // before performing service reconciliation.
+ r.tickTasks(ctx)
+ r.tickServices(ctx)
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/services.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/services.go
new file mode 100644
index 0000000..101976d
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/services.go
@@ -0,0 +1,229 @@
+package replicated
+
+import (
+ "sort"
+
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/orchestrator"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+)
+
+// This file provices service-level orchestration. It observes changes to
+// services and creates and destroys tasks as necessary to match the service
+// specifications. This is different from task-level orchestration, which
+// responds to changes in individual tasks (or nodes which run them).
+
+func (r *Orchestrator) initCluster(readTx store.ReadTx) error {
+ clusters, err := store.FindClusters(readTx, store.ByName("default"))
+ if err != nil {
+ return err
+ }
+
+ if len(clusters) != 1 {
+ // we'll just pick it when it is created.
+ return nil
+ }
+
+ r.cluster = clusters[0]
+ return nil
+}
+
+func (r *Orchestrator) initServices(readTx store.ReadTx) error {
+ services, err := store.FindServices(readTx, store.All)
+ if err != nil {
+ return err
+ }
+ for _, s := range services {
+ if orchestrator.IsReplicatedService(s) {
+ r.reconcileServices[s.ID] = s
+ }
+ }
+ return nil
+}
+
+func (r *Orchestrator) handleServiceEvent(ctx context.Context, event events.Event) {
+ switch v := event.(type) {
+ case api.EventDeleteService:
+ if !orchestrator.IsReplicatedService(v.Service) {
+ return
+ }
+ orchestrator.DeleteServiceTasks(ctx, r.store, v.Service)
+ r.restarts.ClearServiceHistory(v.Service.ID)
+ delete(r.reconcileServices, v.Service.ID)
+ case api.EventCreateService:
+ if !orchestrator.IsReplicatedService(v.Service) {
+ return
+ }
+ r.reconcileServices[v.Service.ID] = v.Service
+ case api.EventUpdateService:
+ if !orchestrator.IsReplicatedService(v.Service) {
+ return
+ }
+ r.reconcileServices[v.Service.ID] = v.Service
+ }
+}
+
+func (r *Orchestrator) tickServices(ctx context.Context) {
+ if len(r.reconcileServices) > 0 {
+ for _, s := range r.reconcileServices {
+ r.reconcile(ctx, s)
+ }
+ r.reconcileServices = make(map[string]*api.Service)
+ }
+}
+
+func (r *Orchestrator) resolveService(ctx context.Context, task *api.Task) *api.Service {
+ if task.ServiceID == "" {
+ return nil
+ }
+ var service *api.Service
+ r.store.View(func(tx store.ReadTx) {
+ service = store.GetService(tx, task.ServiceID)
+ })
+ return service
+}
+
+func (r *Orchestrator) reconcile(ctx context.Context, service *api.Service) {
+ runningSlots, deadSlots, err := orchestrator.GetRunnableAndDeadSlots(r.store, service.ID)
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("reconcile failed finding tasks")
+ return
+ }
+
+ numSlots := len(runningSlots)
+
+ slotsSlice := make([]orchestrator.Slot, 0, numSlots)
+ for _, slot := range runningSlots {
+ slotsSlice = append(slotsSlice, slot)
+ }
+
+ deploy := service.Spec.GetMode().(*api.ServiceSpec_Replicated)
+ specifiedSlots := deploy.Replicated.Replicas
+
+ switch {
+ case specifiedSlots > uint64(numSlots):
+ log.G(ctx).Debugf("Service %s was scaled up from %d to %d instances", service.ID, numSlots, specifiedSlots)
+ // Update all current tasks then add missing tasks
+ r.updater.Update(ctx, r.cluster, service, slotsSlice)
+ err = r.store.Batch(func(batch *store.Batch) error {
+ r.addTasks(ctx, batch, service, runningSlots, deadSlots, specifiedSlots-uint64(numSlots))
+ r.deleteTasksMap(ctx, batch, deadSlots)
+ return nil
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("reconcile batch failed")
+ }
+
+ case specifiedSlots < uint64(numSlots):
+ // Update up to N tasks then remove the extra
+ log.G(ctx).Debugf("Service %s was scaled down from %d to %d instances", service.ID, numSlots, specifiedSlots)
+
+ // Preferentially remove tasks on the nodes that have the most
+ // copies of this service, to leave a more balanced result.
+
+ // First sort tasks such that tasks which are currently running
+ // (in terms of observed state) appear before non-running tasks.
+ // This will cause us to prefer to remove non-running tasks, all
+ // other things being equal in terms of node balance.
+
+ sort.Sort(slotsByRunningState(slotsSlice))
+
+ // Assign each task an index that counts it as the nth copy of
+ // of the service on its node (1, 2, 3, ...), and sort the
+ // tasks by this counter value.
+
+ slotsByNode := make(map[string]int)
+ slotsWithIndices := make(slotsByIndex, 0, numSlots)
+
+ for _, slot := range slotsSlice {
+ if len(slot) == 1 && slot[0].NodeID != "" {
+ slotsByNode[slot[0].NodeID]++
+ slotsWithIndices = append(slotsWithIndices, slotWithIndex{slot: slot, index: slotsByNode[slot[0].NodeID]})
+ } else {
+ slotsWithIndices = append(slotsWithIndices, slotWithIndex{slot: slot, index: -1})
+ }
+ }
+
+ sort.Sort(slotsWithIndices)
+
+ sortedSlots := make([]orchestrator.Slot, 0, numSlots)
+ for _, slot := range slotsWithIndices {
+ sortedSlots = append(sortedSlots, slot.slot)
+ }
+
+ r.updater.Update(ctx, r.cluster, service, sortedSlots[:specifiedSlots])
+ err = r.store.Batch(func(batch *store.Batch) error {
+ r.deleteTasksMap(ctx, batch, deadSlots)
+ r.deleteTasks(ctx, batch, sortedSlots[specifiedSlots:])
+ return nil
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("reconcile batch failed")
+ }
+
+ case specifiedSlots == uint64(numSlots):
+ err = r.store.Batch(func(batch *store.Batch) error {
+ r.deleteTasksMap(ctx, batch, deadSlots)
+ return nil
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("reconcile batch failed")
+ }
+ // Simple update, no scaling - update all tasks.
+ r.updater.Update(ctx, r.cluster, service, slotsSlice)
+ }
+}
+
+func (r *Orchestrator) addTasks(ctx context.Context, batch *store.Batch, service *api.Service, runningSlots map[uint64]orchestrator.Slot, deadSlots map[uint64]orchestrator.Slot, count uint64) {
+ slot := uint64(0)
+ for i := uint64(0); i < count; i++ {
+ // Find a slot number that is missing a running task
+ for {
+ slot++
+ if _, ok := runningSlots[slot]; !ok {
+ break
+ }
+ }
+
+ delete(deadSlots, slot)
+ err := batch.Update(func(tx store.Tx) error {
+ return store.CreateTask(tx, orchestrator.NewTask(r.cluster, service, slot, ""))
+ })
+ if err != nil {
+ log.G(ctx).Errorf("Failed to create task: %v", err)
+ }
+ }
+}
+
+func (r *Orchestrator) deleteTasks(ctx context.Context, batch *store.Batch, slots []orchestrator.Slot) {
+ for _, slot := range slots {
+ for _, t := range slot {
+ r.deleteTask(ctx, batch, t)
+ }
+ }
+}
+
+func (r *Orchestrator) deleteTasksMap(ctx context.Context, batch *store.Batch, slots map[uint64]orchestrator.Slot) {
+ for _, slot := range slots {
+ for _, t := range slot {
+ r.deleteTask(ctx, batch, t)
+ }
+ }
+}
+
+func (r *Orchestrator) deleteTask(ctx context.Context, batch *store.Batch, t *api.Task) {
+ err := batch.Update(func(tx store.Tx) error {
+ return store.DeleteTask(tx, t.ID)
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("deleting task %s failed", t.ID)
+ }
+}
+
+// IsRelatedService returns true if the service should be governed by this orchestrator
+func (r *Orchestrator) IsRelatedService(service *api.Service) bool {
+ return orchestrator.IsReplicatedService(service)
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/slot.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/slot.go
new file mode 100644
index 0000000..1f1fd3e
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/slot.go
@@ -0,0 +1,55 @@
+package replicated
+
+import (
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/orchestrator"
+)
+
+type slotsByRunningState []orchestrator.Slot
+
+func (is slotsByRunningState) Len() int { return len(is) }
+func (is slotsByRunningState) Swap(i, j int) { is[i], is[j] = is[j], is[i] }
+
+func (is slotsByRunningState) Less(i, j int) bool {
+ iRunning := false
+ jRunning := false
+
+ for _, ii := range is[i] {
+ if ii.Status.State == api.TaskStateRunning {
+ iRunning = true
+ break
+ }
+ }
+ for _, ij := range is[j] {
+ if ij.Status.State == api.TaskStateRunning {
+ jRunning = true
+ break
+ }
+ }
+
+ return iRunning && !jRunning
+}
+
+type slotWithIndex struct {
+ slot orchestrator.Slot
+
+ // index is a counter that counts this task as the nth instance of
+ // the service on its node. This is used for sorting the tasks so that
+ // when scaling down we leave tasks more evenly balanced.
+ index int
+}
+
+type slotsByIndex []slotWithIndex
+
+func (is slotsByIndex) Len() int { return len(is) }
+func (is slotsByIndex) Swap(i, j int) { is[i], is[j] = is[j], is[i] }
+
+func (is slotsByIndex) Less(i, j int) bool {
+ if is[i].index < 0 && is[j].index >= 0 {
+ return false
+ }
+ if is[j].index < 0 && is[i].index >= 0 {
+ return true
+ }
+ return is[i].index < is[j].index
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/tasks.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/tasks.go
new file mode 100644
index 0000000..66000e5
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/replicated/tasks.go
@@ -0,0 +1,180 @@
+package replicated
+
+import (
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/orchestrator"
+ "github.com/docker/swarmkit/manager/orchestrator/taskinit"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+)
+
+// This file provides task-level orchestration. It observes changes to task
+// and node state and kills/recreates tasks if necessary. This is distinct from
+// service-level reconciliation, which observes changes to services and creates
+// and/or kills tasks to match the service definition.
+
+func (r *Orchestrator) initTasks(ctx context.Context, readTx store.ReadTx) error {
+ return taskinit.CheckTasks(ctx, r.store, readTx, r, r.restarts)
+}
+
+func (r *Orchestrator) handleTaskEvent(ctx context.Context, event events.Event) {
+ switch v := event.(type) {
+ case api.EventDeleteNode:
+ r.restartTasksByNodeID(ctx, v.Node.ID)
+ case api.EventCreateNode:
+ r.handleNodeChange(ctx, v.Node)
+ case api.EventUpdateNode:
+ r.handleNodeChange(ctx, v.Node)
+ case api.EventDeleteTask:
+ if v.Task.DesiredState <= api.TaskStateRunning {
+ service := r.resolveService(ctx, v.Task)
+ if !orchestrator.IsReplicatedService(service) {
+ return
+ }
+ r.reconcileServices[service.ID] = service
+ }
+ r.restarts.Cancel(v.Task.ID)
+ case api.EventUpdateTask:
+ r.handleTaskChange(ctx, v.Task)
+ case api.EventCreateTask:
+ r.handleTaskChange(ctx, v.Task)
+ }
+}
+
+func (r *Orchestrator) tickTasks(ctx context.Context) {
+ if len(r.restartTasks) > 0 {
+ err := r.store.Batch(func(batch *store.Batch) error {
+ for taskID := range r.restartTasks {
+ err := batch.Update(func(tx store.Tx) error {
+ // TODO(aaronl): optimistic update?
+ t := store.GetTask(tx, taskID)
+ if t != nil {
+ if t.DesiredState > api.TaskStateRunning {
+ return nil
+ }
+
+ service := store.GetService(tx, t.ServiceID)
+ if !orchestrator.IsReplicatedService(service) {
+ return nil
+ }
+
+ // Restart task if applicable
+ if err := r.restarts.Restart(ctx, tx, r.cluster, service, *t); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("Orchestrator task reaping transaction failed")
+ }
+ }
+ return nil
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("orchestrator task removal batch failed")
+ }
+
+ r.restartTasks = make(map[string]struct{})
+ }
+}
+
+func (r *Orchestrator) restartTasksByNodeID(ctx context.Context, nodeID string) {
+ var err error
+ r.store.View(func(tx store.ReadTx) {
+ var tasks []*api.Task
+ tasks, err = store.FindTasks(tx, store.ByNodeID(nodeID))
+ if err != nil {
+ return
+ }
+
+ for _, t := range tasks {
+ if t.DesiredState > api.TaskStateRunning {
+ continue
+ }
+ service := store.GetService(tx, t.ServiceID)
+ if orchestrator.IsReplicatedService(service) {
+ r.restartTasks[t.ID] = struct{}{}
+ }
+ }
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to list tasks to remove")
+ }
+}
+
+func (r *Orchestrator) handleNodeChange(ctx context.Context, n *api.Node) {
+ if !orchestrator.InvalidNode(n) {
+ return
+ }
+
+ r.restartTasksByNodeID(ctx, n.ID)
+}
+
+// handleTaskChange defines what orchestrator does when a task is updated by agent.
+func (r *Orchestrator) handleTaskChange(ctx context.Context, t *api.Task) {
+ // If we already set the desired state past TaskStateRunning, there is no
+ // further action necessary.
+ if t.DesiredState > api.TaskStateRunning {
+ return
+ }
+
+ var (
+ n *api.Node
+ service *api.Service
+ )
+ r.store.View(func(tx store.ReadTx) {
+ if t.NodeID != "" {
+ n = store.GetNode(tx, t.NodeID)
+ }
+ if t.ServiceID != "" {
+ service = store.GetService(tx, t.ServiceID)
+ }
+ })
+
+ if !orchestrator.IsReplicatedService(service) {
+ return
+ }
+
+ if t.Status.State > api.TaskStateRunning ||
+ (t.NodeID != "" && orchestrator.InvalidNode(n)) {
+ r.restartTasks[t.ID] = struct{}{}
+ }
+}
+
+// FixTask validates a task with the current cluster settings, and takes
+// action to make it conformant. it's called at orchestrator initialization.
+func (r *Orchestrator) FixTask(ctx context.Context, batch *store.Batch, t *api.Task) {
+ // If we already set the desired state past TaskStateRunning, there is no
+ // further action necessary.
+ if t.DesiredState > api.TaskStateRunning {
+ return
+ }
+
+ var (
+ n *api.Node
+ service *api.Service
+ )
+ batch.Update(func(tx store.Tx) error {
+ if t.NodeID != "" {
+ n = store.GetNode(tx, t.NodeID)
+ }
+ if t.ServiceID != "" {
+ service = store.GetService(tx, t.ServiceID)
+ }
+ return nil
+ })
+
+ if !orchestrator.IsReplicatedService(service) {
+ return
+ }
+
+ if t.Status.State > api.TaskStateRunning ||
+ (t.NodeID != "" && orchestrator.InvalidNode(n)) {
+ r.restartTasks[t.ID] = struct{}{}
+ return
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/restart/restart.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/restart/restart.go
new file mode 100644
index 0000000..6167552
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/restart/restart.go
@@ -0,0 +1,447 @@
+package restart
+
+import (
+ "container/list"
+ "errors"
+ "sync"
+ "time"
+
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/defaults"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/orchestrator"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+ gogotypes "github.com/gogo/protobuf/types"
+ "golang.org/x/net/context"
+)
+
+const defaultOldTaskTimeout = time.Minute
+
+type restartedInstance struct {
+ timestamp time.Time
+}
+
+type instanceRestartInfo struct {
+ // counter of restarts for this instance.
+ totalRestarts uint64
+ // Linked list of restartedInstance structs. Only used when
+ // Restart.MaxAttempts and Restart.Window are both
+ // nonzero.
+ restartedInstances *list.List
+}
+
+type delayedStart struct {
+ // cancel is called to cancel the delayed start.
+ cancel func()
+ doneCh chan struct{}
+
+ // waiter is set to true if the next restart is waiting for this delay
+ // to complete.
+ waiter bool
+}
+
+type instanceTuple struct {
+ instance uint64 // unset for global tasks
+ serviceID string
+ nodeID string // unset for replicated tasks
+}
+
+// Supervisor initiates and manages restarts. It's responsible for
+// delaying restarts when applicable.
+type Supervisor struct {
+ mu sync.Mutex
+ store *store.MemoryStore
+ delays map[string]*delayedStart
+ history map[instanceTuple]*instanceRestartInfo
+ historyByService map[string]map[instanceTuple]struct{}
+ TaskTimeout time.Duration
+}
+
+// NewSupervisor creates a new RestartSupervisor.
+func NewSupervisor(store *store.MemoryStore) *Supervisor {
+ return &Supervisor{
+ store: store,
+ delays: make(map[string]*delayedStart),
+ history: make(map[instanceTuple]*instanceRestartInfo),
+ historyByService: make(map[string]map[instanceTuple]struct{}),
+ TaskTimeout: defaultOldTaskTimeout,
+ }
+}
+
+func (r *Supervisor) waitRestart(ctx context.Context, oldDelay *delayedStart, cluster *api.Cluster, taskID string) {
+ // Wait for the last restart delay to elapse.
+ select {
+ case <-oldDelay.doneCh:
+ case <-ctx.Done():
+ return
+ }
+
+ // Start the next restart
+ err := r.store.Update(func(tx store.Tx) error {
+ t := store.GetTask(tx, taskID)
+ if t == nil {
+ return nil
+ }
+ if t.DesiredState > api.TaskStateRunning {
+ return nil
+ }
+ service := store.GetService(tx, t.ServiceID)
+ if service == nil {
+ return nil
+ }
+ return r.Restart(ctx, tx, cluster, service, *t)
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to restart task after waiting for previous restart")
+ }
+}
+
+// Restart initiates a new task to replace t if appropriate under the service's
+// restart policy.
+func (r *Supervisor) Restart(ctx context.Context, tx store.Tx, cluster *api.Cluster, service *api.Service, t api.Task) error {
+ // TODO(aluzzardi): This function should not depend on `service`.
+
+ // Is the old task still in the process of restarting? If so, wait for
+ // its restart delay to elapse, to avoid tight restart loops (for
+ // example, when the image doesn't exist).
+ r.mu.Lock()
+ oldDelay, ok := r.delays[t.ID]
+ if ok {
+ if !oldDelay.waiter {
+ oldDelay.waiter = true
+ go r.waitRestart(ctx, oldDelay, cluster, t.ID)
+ }
+ r.mu.Unlock()
+ return nil
+ }
+ r.mu.Unlock()
+
+ // Sanity check: was the task shut down already by a separate call to
+ // Restart? If so, we must avoid restarting it, because this will create
+ // an extra task. This should never happen unless there is a bug.
+ if t.DesiredState > api.TaskStateRunning {
+ return errors.New("Restart called on task that was already shut down")
+ }
+
+ t.DesiredState = api.TaskStateShutdown
+ err := store.UpdateTask(tx, &t)
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to set task desired state to dead")
+ return err
+ }
+
+ if !r.shouldRestart(ctx, &t, service) {
+ return nil
+ }
+
+ var restartTask *api.Task
+
+ if orchestrator.IsReplicatedService(service) {
+ restartTask = orchestrator.NewTask(cluster, service, t.Slot, "")
+ } else if orchestrator.IsGlobalService(service) {
+ restartTask = orchestrator.NewTask(cluster, service, 0, t.NodeID)
+ } else {
+ log.G(ctx).Error("service not supported by restart supervisor")
+ return nil
+ }
+
+ n := store.GetNode(tx, t.NodeID)
+
+ restartTask.DesiredState = api.TaskStateReady
+
+ var restartDelay time.Duration
+ // Restart delay is not applied to drained nodes
+ if n == nil || n.Spec.Availability != api.NodeAvailabilityDrain {
+ if t.Spec.Restart != nil && t.Spec.Restart.Delay != nil {
+ var err error
+ restartDelay, err = gogotypes.DurationFromProto(t.Spec.Restart.Delay)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("invalid restart delay; using default")
+ restartDelay, _ = gogotypes.DurationFromProto(defaults.Service.Task.Restart.Delay)
+ }
+ } else {
+ restartDelay, _ = gogotypes.DurationFromProto(defaults.Service.Task.Restart.Delay)
+ }
+ }
+
+ waitStop := true
+
+ // Normally we wait for the old task to stop running, but we skip this
+ // if the old task is already dead or the node it's assigned to is down.
+ if (n != nil && n.Status.State == api.NodeStatus_DOWN) || t.Status.State > api.TaskStateRunning {
+ waitStop = false
+ }
+
+ if err := store.CreateTask(tx, restartTask); err != nil {
+ log.G(ctx).WithError(err).WithField("task.id", restartTask.ID).Error("task create failed")
+ return err
+ }
+
+ r.recordRestartHistory(restartTask)
+
+ r.DelayStart(ctx, tx, &t, restartTask.ID, restartDelay, waitStop)
+ return nil
+}
+
+func (r *Supervisor) shouldRestart(ctx context.Context, t *api.Task, service *api.Service) bool {
+ // TODO(aluzzardi): This function should not depend on `service`.
+
+ condition := orchestrator.RestartCondition(t)
+
+ if condition != api.RestartOnAny &&
+ (condition != api.RestartOnFailure || t.Status.State == api.TaskStateCompleted) {
+ return false
+ }
+
+ if t.Spec.Restart == nil || t.Spec.Restart.MaxAttempts == 0 {
+ return true
+ }
+
+ instanceTuple := instanceTuple{
+ instance: t.Slot,
+ serviceID: t.ServiceID,
+ }
+
+ // Instance is not meaningful for "global" tasks, so they need to be
+ // indexed by NodeID.
+ if orchestrator.IsGlobalService(service) {
+ instanceTuple.nodeID = t.NodeID
+ }
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ restartInfo := r.history[instanceTuple]
+ if restartInfo == nil {
+ return true
+ }
+
+ if t.Spec.Restart.Window == nil || (t.Spec.Restart.Window.Seconds == 0 && t.Spec.Restart.Window.Nanos == 0) {
+ return restartInfo.totalRestarts < t.Spec.Restart.MaxAttempts
+ }
+
+ if restartInfo.restartedInstances == nil {
+ return true
+ }
+
+ window, err := gogotypes.DurationFromProto(t.Spec.Restart.Window)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("invalid restart lookback window")
+ return restartInfo.totalRestarts < t.Spec.Restart.MaxAttempts
+ }
+ lookback := time.Now().Add(-window)
+
+ var next *list.Element
+ for e := restartInfo.restartedInstances.Front(); e != nil; e = next {
+ next = e.Next()
+
+ if e.Value.(restartedInstance).timestamp.After(lookback) {
+ break
+ }
+ restartInfo.restartedInstances.Remove(e)
+ }
+
+ numRestarts := uint64(restartInfo.restartedInstances.Len())
+
+ if numRestarts == 0 {
+ restartInfo.restartedInstances = nil
+ }
+
+ return numRestarts < t.Spec.Restart.MaxAttempts
+}
+
+func (r *Supervisor) recordRestartHistory(restartTask *api.Task) {
+ if restartTask.Spec.Restart == nil || restartTask.Spec.Restart.MaxAttempts == 0 {
+ // No limit on the number of restarts, so no need to record
+ // history.
+ return
+ }
+ tuple := instanceTuple{
+ instance: restartTask.Slot,
+ serviceID: restartTask.ServiceID,
+ nodeID: restartTask.NodeID,
+ }
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ if r.history[tuple] == nil {
+ r.history[tuple] = &instanceRestartInfo{}
+ }
+
+ restartInfo := r.history[tuple]
+ restartInfo.totalRestarts++
+
+ if r.historyByService[restartTask.ServiceID] == nil {
+ r.historyByService[restartTask.ServiceID] = make(map[instanceTuple]struct{})
+ }
+ r.historyByService[restartTask.ServiceID][tuple] = struct{}{}
+
+ if restartTask.Spec.Restart.Window != nil && (restartTask.Spec.Restart.Window.Seconds != 0 || restartTask.Spec.Restart.Window.Nanos != 0) {
+ if restartInfo.restartedInstances == nil {
+ restartInfo.restartedInstances = list.New()
+ }
+
+ restartedInstance := restartedInstance{
+ timestamp: time.Now(),
+ }
+
+ restartInfo.restartedInstances.PushBack(restartedInstance)
+ }
+}
+
+// DelayStart starts a timer that moves the task from READY to RUNNING once:
+// - The restart delay has elapsed (if applicable)
+// - The old task that it's replacing has stopped running (or this times out)
+// It must be called during an Update transaction to ensure that it does not
+// miss events. The purpose of the store.Tx argument is to avoid accidental
+// calls outside an Update transaction.
+func (r *Supervisor) DelayStart(ctx context.Context, _ store.Tx, oldTask *api.Task, newTaskID string, delay time.Duration, waitStop bool) <-chan struct{} {
+ ctx, cancel := context.WithCancel(context.Background())
+ doneCh := make(chan struct{})
+
+ r.mu.Lock()
+ for {
+ oldDelay, ok := r.delays[newTaskID]
+ if !ok {
+ break
+ }
+ oldDelay.cancel()
+ r.mu.Unlock()
+ // Note that this channel read should only block for a very
+ // short time, because we cancelled the existing delay and
+ // that should cause it to stop immediately.
+ <-oldDelay.doneCh
+ r.mu.Lock()
+ }
+ r.delays[newTaskID] = &delayedStart{cancel: cancel, doneCh: doneCh}
+ r.mu.Unlock()
+
+ var watch chan events.Event
+ cancelWatch := func() {}
+
+ if waitStop && oldTask != nil {
+ // Wait for either the old task to complete, or the old task's
+ // node to become unavailable.
+ watch, cancelWatch = state.Watch(
+ r.store.WatchQueue(),
+ api.EventUpdateTask{
+ Task: &api.Task{ID: oldTask.ID, Status: api.TaskStatus{State: api.TaskStateRunning}},
+ Checks: []api.TaskCheckFunc{api.TaskCheckID, state.TaskCheckStateGreaterThan},
+ },
+ api.EventUpdateNode{
+ Node: &api.Node{ID: oldTask.NodeID, Status: api.NodeStatus{State: api.NodeStatus_DOWN}},
+ Checks: []api.NodeCheckFunc{api.NodeCheckID, state.NodeCheckState},
+ },
+ api.EventDeleteNode{
+ Node: &api.Node{ID: oldTask.NodeID},
+ Checks: []api.NodeCheckFunc{api.NodeCheckID},
+ },
+ )
+ }
+
+ go func() {
+ defer func() {
+ cancelWatch()
+ r.mu.Lock()
+ delete(r.delays, newTaskID)
+ r.mu.Unlock()
+ close(doneCh)
+ }()
+
+ oldTaskTimer := time.NewTimer(r.TaskTimeout)
+ defer oldTaskTimer.Stop()
+
+ // Wait for the delay to elapse, if one is specified.
+ if delay != 0 {
+ select {
+ case <-time.After(delay):
+ case <-ctx.Done():
+ return
+ }
+ }
+
+ if waitStop && oldTask != nil {
+ select {
+ case <-watch:
+ case <-oldTaskTimer.C:
+ case <-ctx.Done():
+ return
+ }
+ }
+
+ err := r.store.Update(func(tx store.Tx) error {
+ err := r.StartNow(tx, newTaskID)
+ if err != nil {
+ log.G(ctx).WithError(err).WithField("task.id", newTaskID).Error("moving task out of delayed state failed")
+ }
+ return nil
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).WithField("task.id", newTaskID).Error("task restart transaction failed")
+ }
+ }()
+
+ return doneCh
+}
+
+// StartNow moves the task into the RUNNING state so it will proceed to start
+// up.
+func (r *Supervisor) StartNow(tx store.Tx, taskID string) error {
+ t := store.GetTask(tx, taskID)
+ if t == nil || t.DesiredState >= api.TaskStateRunning {
+ return nil
+ }
+ t.DesiredState = api.TaskStateRunning
+ return store.UpdateTask(tx, t)
+}
+
+// Cancel cancels a pending restart.
+func (r *Supervisor) Cancel(taskID string) {
+ r.mu.Lock()
+ delay, ok := r.delays[taskID]
+ r.mu.Unlock()
+
+ if !ok {
+ return
+ }
+
+ delay.cancel()
+ <-delay.doneCh
+}
+
+// CancelAll aborts all pending restarts and waits for any instances of
+// StartNow that have already triggered to complete.
+func (r *Supervisor) CancelAll() {
+ var cancelled []delayedStart
+
+ r.mu.Lock()
+ for _, delay := range r.delays {
+ delay.cancel()
+ }
+ r.mu.Unlock()
+
+ for _, delay := range cancelled {
+ <-delay.doneCh
+ }
+}
+
+// ClearServiceHistory forgets restart history related to a given service ID.
+func (r *Supervisor) ClearServiceHistory(serviceID string) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ tuples := r.historyByService[serviceID]
+ if tuples == nil {
+ return
+ }
+
+ delete(r.historyByService, serviceID)
+
+ for t := range tuples {
+ delete(r.history, t)
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/service.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/service.go
new file mode 100644
index 0000000..4e52c83
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/service.go
@@ -0,0 +1,61 @@
+package orchestrator
+
+import (
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+)
+
+// IsReplicatedService checks if a service is a replicated service.
+func IsReplicatedService(service *api.Service) bool {
+ // service nil validation is required as there are scenarios
+ // where service is removed from store
+ if service == nil {
+ return false
+ }
+ _, ok := service.Spec.GetMode().(*api.ServiceSpec_Replicated)
+ return ok
+}
+
+// IsGlobalService checks if the service is a global service.
+func IsGlobalService(service *api.Service) bool {
+ if service == nil {
+ return false
+ }
+ _, ok := service.Spec.GetMode().(*api.ServiceSpec_Global)
+ return ok
+}
+
+// DeleteServiceTasks deletes the tasks associated with a service.
+func DeleteServiceTasks(ctx context.Context, s *store.MemoryStore, service *api.Service) {
+ var (
+ tasks []*api.Task
+ err error
+ )
+ s.View(func(tx store.ReadTx) {
+ tasks, err = store.FindTasks(tx, store.ByServiceID(service.ID))
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to list tasks")
+ return
+ }
+
+ err = s.Batch(func(batch *store.Batch) error {
+ for _, t := range tasks {
+ err := batch.Update(func(tx store.Tx) error {
+ if err := store.DeleteTask(tx, t.ID); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to delete task")
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("task search transaction failed")
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/slot.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/slot.go
new file mode 100644
index 0000000..ce34713
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/slot.go
@@ -0,0 +1,46 @@
+package orchestrator
+
+import (
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/state/store"
+)
+
+// Slot is a list of the running tasks occupying a certain slot. Generally this
+// will only be one task, but some rolling update situations involve
+// temporarily having two running tasks in the same slot. Note that this use of
+// "slot" is more generic than the Slot number for replicated services - a node
+// is also considered a slot for global services.
+type Slot []*api.Task
+
+// GetRunnableAndDeadSlots returns two maps of slots. The first contains slots
+// that have at least one task with a desired state above NEW and lesser or
+// equal to RUNNING. The second is for slots that only contain tasks with a
+// desired state above RUNNING.
+func GetRunnableAndDeadSlots(s *store.MemoryStore, serviceID string) (map[uint64]Slot, map[uint64]Slot, error) {
+ var (
+ tasks []*api.Task
+ err error
+ )
+ s.View(func(tx store.ReadTx) {
+ tasks, err = store.FindTasks(tx, store.ByServiceID(serviceID))
+ })
+ if err != nil {
+ return nil, nil, err
+ }
+
+ runningSlots := make(map[uint64]Slot)
+ for _, t := range tasks {
+ if t.DesiredState <= api.TaskStateRunning {
+ runningSlots[t.Slot] = append(runningSlots[t.Slot], t)
+ }
+ }
+
+ deadSlots := make(map[uint64]Slot)
+ for _, t := range tasks {
+ if _, exists := runningSlots[t.Slot]; !exists {
+ deadSlots[t.Slot] = append(deadSlots[t.Slot], t)
+ }
+ }
+
+ return runningSlots, deadSlots, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/task.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/task.go
new file mode 100644
index 0000000..32a22d5
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/task.go
@@ -0,0 +1,79 @@
+package orchestrator
+
+import (
+ "reflect"
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/defaults"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/protobuf/ptypes"
+)
+
+// NewTask creates a new task.
+func NewTask(cluster *api.Cluster, service *api.Service, slot uint64, nodeID string) *api.Task {
+ var logDriver *api.Driver
+ if service.Spec.Task.LogDriver != nil {
+ // use the log driver specific to the task, if we have it.
+ logDriver = service.Spec.Task.LogDriver
+ } else if cluster != nil {
+ // pick up the cluster default, if available.
+ logDriver = cluster.Spec.TaskDefaults.LogDriver // nil is okay here.
+ }
+
+ taskID := identity.NewID()
+ task := api.Task{
+ ID: taskID,
+ ServiceAnnotations: service.Spec.Annotations,
+ Spec: service.Spec.Task,
+ SpecVersion: service.SpecVersion,
+ ServiceID: service.ID,
+ Slot: slot,
+ Status: api.TaskStatus{
+ State: api.TaskStateNew,
+ Timestamp: ptypes.MustTimestampProto(time.Now()),
+ Message: "created",
+ },
+ Endpoint: &api.Endpoint{
+ Spec: service.Spec.Endpoint.Copy(),
+ },
+ DesiredState: api.TaskStateRunning,
+ LogDriver: logDriver,
+ }
+
+ // In global mode we also set the NodeID
+ if nodeID != "" {
+ task.NodeID = nodeID
+ }
+
+ return &task
+}
+
+// RestartCondition returns the restart condition to apply to this task.
+func RestartCondition(task *api.Task) api.RestartPolicy_RestartCondition {
+ restartCondition := defaults.Service.Task.Restart.Condition
+ if task.Spec.Restart != nil {
+ restartCondition = task.Spec.Restart.Condition
+ }
+ return restartCondition
+}
+
+// IsTaskDirty determines whether a task matches the given service's spec.
+func IsTaskDirty(s *api.Service, t *api.Task) bool {
+ // If the spec version matches, we know the task is not dirty. However,
+ // if it does not match, that doesn't mean the task is dirty, since
+ // only a portion of the spec is included in the comparison.
+ if t.SpecVersion != nil && s.SpecVersion != nil && *s.SpecVersion == *t.SpecVersion {
+ return false
+ }
+
+ return !reflect.DeepEqual(s.Spec.Task, t.Spec) ||
+ (t.Endpoint != nil && !reflect.DeepEqual(s.Spec.Endpoint, t.Endpoint.Spec))
+}
+
+// InvalidNode is true if the node is nil, down, or drained
+func InvalidNode(n *api.Node) bool {
+ return n == nil ||
+ n.Status.State == api.NodeStatus_DOWN ||
+ n.Spec.Availability == api.NodeAvailabilityDrain
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/taskinit/init.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/taskinit/init.go
new file mode 100644
index 0000000..33558a4
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/taskinit/init.go
@@ -0,0 +1,103 @@
+package taskinit
+
+import (
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/defaults"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/orchestrator/restart"
+ "github.com/docker/swarmkit/manager/state/store"
+ gogotypes "github.com/gogo/protobuf/types"
+ "golang.org/x/net/context"
+)
+
+// InitHandler defines orchestrator's action to fix tasks at start.
+type InitHandler interface {
+ IsRelatedService(service *api.Service) bool
+ FixTask(ctx context.Context, batch *store.Batch, t *api.Task)
+}
+
+// CheckTasks fixes tasks in the store before orchestrator runs. The previous leader might
+// not have finished processing their updates and left them in an inconsistent state.
+func CheckTasks(ctx context.Context, s *store.MemoryStore, readTx store.ReadTx, initHandler InitHandler, startSupervisor *restart.Supervisor) error {
+ err := s.Batch(func(batch *store.Batch) error {
+ tasks, err := store.FindTasks(readTx, store.All)
+ if err != nil {
+ return err
+ }
+ for _, t := range tasks {
+ if t.ServiceID == "" {
+ continue
+ }
+
+ // TODO(aluzzardi): We should NOT retrieve the service here.
+ service := store.GetService(readTx, t.ServiceID)
+ if service == nil {
+ // Service was deleted
+ err := batch.Update(func(tx store.Tx) error {
+ return store.DeleteTask(tx, t.ID)
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed to delete task")
+ }
+ continue
+ }
+ if !initHandler.IsRelatedService(service) {
+ continue
+ }
+
+ // handle task updates from agent which should have been triggered by task update events
+ initHandler.FixTask(ctx, batch, t)
+
+ // desired state ready is a transient state that it should be started.
+ // however previous leader may not have started it, retry start here
+ if t.DesiredState != api.TaskStateReady || t.Status.State > api.TaskStateRunning {
+ continue
+ }
+ restartDelay, _ := gogotypes.DurationFromProto(defaults.Service.Task.Restart.Delay)
+ if t.Spec.Restart != nil && t.Spec.Restart.Delay != nil {
+ var err error
+ restartDelay, err = gogotypes.DurationFromProto(t.Spec.Restart.Delay)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("invalid restart delay")
+ restartDelay, _ = gogotypes.DurationFromProto(defaults.Service.Task.Restart.Delay)
+ }
+ }
+ if restartDelay != 0 {
+ timestamp, err := gogotypes.TimestampFromProto(t.Status.Timestamp)
+ if err == nil {
+ restartTime := timestamp.Add(restartDelay)
+ calculatedRestartDelay := restartTime.Sub(time.Now())
+ if calculatedRestartDelay < restartDelay {
+ restartDelay = calculatedRestartDelay
+ }
+ if restartDelay > 0 {
+ _ = batch.Update(func(tx store.Tx) error {
+ t := store.GetTask(tx, t.ID)
+ // TODO(aluzzardi): This is shady as well. We should have a more generic condition.
+ if t == nil || t.DesiredState != api.TaskStateReady {
+ return nil
+ }
+ startSupervisor.DelayStart(ctx, tx, nil, t.ID, restartDelay, true)
+ return nil
+ })
+ continue
+ }
+ } else {
+ log.G(ctx).WithError(err).Error("invalid status timestamp")
+ }
+ }
+
+ // Start now
+ err := batch.Update(func(tx store.Tx) error {
+ return startSupervisor.StartNow(tx, t.ID)
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).WithField("task.id", t.ID).Error("moving task out of delayed state failed")
+ }
+ }
+ return nil
+ })
+ return err
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/taskreaper/task_reaper.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/taskreaper/task_reaper.go
new file mode 100644
index 0000000..edb771c
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/taskreaper/task_reaper.go
@@ -0,0 +1,245 @@
+package taskreaper
+
+import (
+ "sort"
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+)
+
+const (
+ // maxDirty is the size threshold for running a task pruning operation.
+ maxDirty = 1000
+ // reaperBatchingInterval is how often to prune old tasks.
+ reaperBatchingInterval = 250 * time.Millisecond
+)
+
+type instanceTuple struct {
+ instance uint64 // unset for global tasks
+ serviceID string
+ nodeID string // unset for replicated tasks
+}
+
+// A TaskReaper deletes old tasks when more than TaskHistoryRetentionLimit tasks
+// exist for the same service/instance or service/nodeid combination.
+type TaskReaper struct {
+ store *store.MemoryStore
+ // taskHistory is the number of tasks to keep
+ taskHistory int64
+ dirty map[instanceTuple]struct{}
+ orphaned []string
+ stopChan chan struct{}
+ doneChan chan struct{}
+}
+
+// New creates a new TaskReaper.
+func New(store *store.MemoryStore) *TaskReaper {
+ return &TaskReaper{
+ store: store,
+ dirty: make(map[instanceTuple]struct{}),
+ stopChan: make(chan struct{}),
+ doneChan: make(chan struct{}),
+ }
+}
+
+// Run is the TaskReaper's main loop.
+func (tr *TaskReaper) Run(ctx context.Context) {
+ watcher, watchCancel := state.Watch(tr.store.WatchQueue(), api.EventCreateTask{}, api.EventUpdateTask{}, api.EventUpdateCluster{})
+
+ defer func() {
+ close(tr.doneChan)
+ watchCancel()
+ }()
+
+ var tasks []*api.Task
+ tr.store.View(func(readTx store.ReadTx) {
+ var err error
+
+ clusters, err := store.FindClusters(readTx, store.ByName(store.DefaultClusterName))
+ if err == nil && len(clusters) == 1 {
+ tr.taskHistory = clusters[0].Spec.Orchestration.TaskHistoryRetentionLimit
+ }
+
+ tasks, err = store.FindTasks(readTx, store.ByTaskState(api.TaskStateOrphaned))
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed to find Orphaned tasks in task reaper init")
+ }
+ })
+
+ if len(tasks) > 0 {
+ for _, t := range tasks {
+ // Do not reap service tasks immediately
+ if t.ServiceID != "" {
+ continue
+ }
+
+ tr.orphaned = append(tr.orphaned, t.ID)
+ }
+
+ if len(tr.orphaned) > 0 {
+ tr.tick()
+ }
+ }
+
+ timer := time.NewTimer(reaperBatchingInterval)
+
+ for {
+ select {
+ case event := <-watcher:
+ switch v := event.(type) {
+ case api.EventCreateTask:
+ t := v.Task
+ tr.dirty[instanceTuple{
+ instance: t.Slot,
+ serviceID: t.ServiceID,
+ nodeID: t.NodeID,
+ }] = struct{}{}
+ case api.EventUpdateTask:
+ t := v.Task
+ if t.Status.State >= api.TaskStateOrphaned && t.ServiceID == "" {
+ tr.orphaned = append(tr.orphaned, t.ID)
+ }
+ case api.EventUpdateCluster:
+ tr.taskHistory = v.Cluster.Spec.Orchestration.TaskHistoryRetentionLimit
+ }
+
+ if len(tr.dirty)+len(tr.orphaned) > maxDirty {
+ timer.Stop()
+ tr.tick()
+ } else {
+ timer.Reset(reaperBatchingInterval)
+ }
+ case <-timer.C:
+ timer.Stop()
+ tr.tick()
+ case <-tr.stopChan:
+ timer.Stop()
+ return
+ }
+ }
+}
+
+func (tr *TaskReaper) tick() {
+ if len(tr.dirty) == 0 && len(tr.orphaned) == 0 {
+ return
+ }
+
+ defer func() {
+ tr.orphaned = nil
+ }()
+
+ deleteTasks := make(map[string]struct{})
+ for _, tID := range tr.orphaned {
+ deleteTasks[tID] = struct{}{}
+ }
+ tr.store.View(func(tx store.ReadTx) {
+ for dirty := range tr.dirty {
+ service := store.GetService(tx, dirty.serviceID)
+ if service == nil {
+ continue
+ }
+
+ taskHistory := tr.taskHistory
+
+ if taskHistory < 0 {
+ continue
+ }
+
+ var historicTasks []*api.Task
+
+ switch service.Spec.GetMode().(type) {
+ case *api.ServiceSpec_Replicated:
+ var err error
+ historicTasks, err = store.FindTasks(tx, store.BySlot(dirty.serviceID, dirty.instance))
+ if err != nil {
+ continue
+ }
+
+ case *api.ServiceSpec_Global:
+ tasksByNode, err := store.FindTasks(tx, store.ByNodeID(dirty.nodeID))
+ if err != nil {
+ continue
+ }
+
+ for _, t := range tasksByNode {
+ if t.ServiceID == dirty.serviceID {
+ historicTasks = append(historicTasks, t)
+ }
+ }
+ }
+
+ if int64(len(historicTasks)) <= taskHistory {
+ continue
+ }
+
+ // TODO(aaronl): This could filter for non-running tasks and use quickselect
+ // instead of sorting the whole slice.
+ sort.Sort(tasksByTimestamp(historicTasks))
+
+ runningTasks := 0
+ for _, t := range historicTasks {
+ if t.DesiredState <= api.TaskStateRunning || t.Status.State <= api.TaskStateRunning {
+ // Don't delete running tasks
+ runningTasks++
+ continue
+ }
+
+ deleteTasks[t.ID] = struct{}{}
+
+ taskHistory++
+ if int64(len(historicTasks)) <= taskHistory {
+ break
+ }
+ }
+
+ if runningTasks <= 1 {
+ delete(tr.dirty, dirty)
+ }
+ }
+ })
+
+ if len(deleteTasks) > 0 {
+ tr.store.Batch(func(batch *store.Batch) error {
+ for taskID := range deleteTasks {
+ batch.Update(func(tx store.Tx) error {
+ return store.DeleteTask(tx, taskID)
+ })
+ }
+ return nil
+ })
+ }
+}
+
+// Stop stops the TaskReaper and waits for the main loop to exit.
+func (tr *TaskReaper) Stop() {
+ close(tr.stopChan)
+ <-tr.doneChan
+}
+
+type tasksByTimestamp []*api.Task
+
+func (t tasksByTimestamp) Len() int {
+ return len(t)
+}
+func (t tasksByTimestamp) Swap(i, j int) {
+ t[i], t[j] = t[j], t[i]
+}
+func (t tasksByTimestamp) Less(i, j int) bool {
+ if t[i].Status.Timestamp == nil {
+ return true
+ }
+ if t[j].Status.Timestamp == nil {
+ return false
+ }
+ if t[i].Status.Timestamp.Seconds < t[j].Status.Timestamp.Seconds {
+ return true
+ }
+ if t[i].Status.Timestamp.Seconds > t[j].Status.Timestamp.Seconds {
+ return false
+ }
+ return t[i].Status.Timestamp.Nanos < t[j].Status.Timestamp.Nanos
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/orchestrator/update/updater.go b/vendor/github.com/docker/swarmkit/manager/orchestrator/update/updater.go
new file mode 100644
index 0000000..2b1f55d
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/orchestrator/update/updater.go
@@ -0,0 +1,642 @@
+package update
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/defaults"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/orchestrator"
+ "github.com/docker/swarmkit/manager/orchestrator/restart"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/protobuf/ptypes"
+ "github.com/docker/swarmkit/watch"
+ gogotypes "github.com/gogo/protobuf/types"
+)
+
+// Supervisor supervises a set of updates. It's responsible for keeping track of updates,
+// shutting them down and replacing them.
+type Supervisor struct {
+ store *store.MemoryStore
+ restarts *restart.Supervisor
+ updates map[string]*Updater
+ l sync.Mutex
+}
+
+// NewSupervisor creates a new UpdateSupervisor.
+func NewSupervisor(store *store.MemoryStore, restartSupervisor *restart.Supervisor) *Supervisor {
+ return &Supervisor{
+ store: store,
+ updates: make(map[string]*Updater),
+ restarts: restartSupervisor,
+ }
+}
+
+// Update starts an Update of `slots` belonging to `service` in the background
+// and returns immediately. Each slot contains a group of one or more tasks
+// occupying the same slot (replicated service) or node (global service). There
+// may be more than one task per slot in cases where an update is in progress
+// and the new task was started before the old one was shut down. If an update
+// for that service was already in progress, it will be cancelled before the
+// new one starts.
+func (u *Supervisor) Update(ctx context.Context, cluster *api.Cluster, service *api.Service, slots []orchestrator.Slot) {
+ u.l.Lock()
+ defer u.l.Unlock()
+
+ id := service.ID
+
+ if update, ok := u.updates[id]; ok {
+ if reflect.DeepEqual(service.Spec, update.newService.Spec) {
+ // There's already an update working towards this goal.
+ return
+ }
+ update.Cancel()
+ }
+
+ update := NewUpdater(u.store, u.restarts, cluster, service)
+ u.updates[id] = update
+ go func() {
+ update.Run(ctx, slots)
+ u.l.Lock()
+ if u.updates[id] == update {
+ delete(u.updates, id)
+ }
+ u.l.Unlock()
+ }()
+}
+
+// CancelAll cancels all current updates.
+func (u *Supervisor) CancelAll() {
+ u.l.Lock()
+ defer u.l.Unlock()
+
+ for _, update := range u.updates {
+ update.Cancel()
+ }
+}
+
+// Updater updates a set of tasks to a new version.
+type Updater struct {
+ store *store.MemoryStore
+ watchQueue *watch.Queue
+ restarts *restart.Supervisor
+
+ cluster *api.Cluster
+ newService *api.Service
+
+ updatedTasks map[string]time.Time // task ID to creation time
+ updatedTasksMu sync.Mutex
+
+ // stopChan signals to the state machine to stop running.
+ stopChan chan struct{}
+ // doneChan is closed when the state machine terminates.
+ doneChan chan struct{}
+}
+
+// NewUpdater creates a new Updater.
+func NewUpdater(store *store.MemoryStore, restartSupervisor *restart.Supervisor, cluster *api.Cluster, newService *api.Service) *Updater {
+ return &Updater{
+ store: store,
+ watchQueue: store.WatchQueue(),
+ restarts: restartSupervisor,
+ cluster: cluster.Copy(),
+ newService: newService.Copy(),
+ updatedTasks: make(map[string]time.Time),
+ stopChan: make(chan struct{}),
+ doneChan: make(chan struct{}),
+ }
+}
+
+// Cancel cancels the current update immediately. It blocks until the cancellation is confirmed.
+func (u *Updater) Cancel() {
+ close(u.stopChan)
+ <-u.doneChan
+}
+
+// Run starts the update and returns only once its complete or cancelled.
+func (u *Updater) Run(ctx context.Context, slots []orchestrator.Slot) {
+ defer close(u.doneChan)
+
+ service := u.newService
+
+ // If the update is in a PAUSED state, we should not do anything.
+ if service.UpdateStatus != nil &&
+ (service.UpdateStatus.State == api.UpdateStatus_PAUSED ||
+ service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_PAUSED) {
+ return
+ }
+
+ var dirtySlots []orchestrator.Slot
+ for _, slot := range slots {
+ if u.isSlotDirty(slot) {
+ dirtySlots = append(dirtySlots, slot)
+ }
+ }
+ // Abort immediately if all tasks are clean.
+ if len(dirtySlots) == 0 {
+ if service.UpdateStatus != nil &&
+ (service.UpdateStatus.State == api.UpdateStatus_UPDATING ||
+ service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_STARTED) {
+ u.completeUpdate(ctx, service.ID)
+ }
+ return
+ }
+
+ // If there's no update in progress, we are starting one.
+ if service.UpdateStatus == nil {
+ u.startUpdate(ctx, service.ID)
+ }
+
+ var (
+ monitoringPeriod time.Duration
+ updateConfig *api.UpdateConfig
+ )
+
+ if service.UpdateStatus != nil && service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_STARTED {
+ monitoringPeriod, _ = gogotypes.DurationFromProto(defaults.Service.Rollback.Monitor)
+ updateConfig = service.Spec.Rollback
+ if updateConfig == nil {
+ updateConfig = defaults.Service.Rollback
+ }
+ } else {
+ monitoringPeriod, _ = gogotypes.DurationFromProto(defaults.Service.Update.Monitor)
+ updateConfig = service.Spec.Update
+ if updateConfig == nil {
+ updateConfig = defaults.Service.Update
+ }
+ }
+
+ parallelism := int(updateConfig.Parallelism)
+ if updateConfig.Monitor != nil {
+ newMonitoringPeriod, err := gogotypes.DurationFromProto(updateConfig.Monitor)
+ if err == nil {
+ monitoringPeriod = newMonitoringPeriod
+ }
+ }
+
+ if parallelism == 0 {
+ // TODO(aluzzardi): We could try to optimize unlimited parallelism by performing updates in a single
+ // goroutine using a batch transaction.
+ parallelism = len(dirtySlots)
+ }
+
+ // Start the workers.
+ slotQueue := make(chan orchestrator.Slot)
+ wg := sync.WaitGroup{}
+ wg.Add(parallelism)
+ for i := 0; i < parallelism; i++ {
+ go func() {
+ u.worker(ctx, slotQueue, updateConfig)
+ wg.Done()
+ }()
+ }
+
+ var failedTaskWatch chan events.Event
+
+ if updateConfig.FailureAction != api.UpdateConfig_CONTINUE {
+ var cancelWatch func()
+ failedTaskWatch, cancelWatch = state.Watch(
+ u.store.WatchQueue(),
+ api.EventUpdateTask{
+ Task: &api.Task{ServiceID: service.ID, Status: api.TaskStatus{State: api.TaskStateRunning}},
+ Checks: []api.TaskCheckFunc{api.TaskCheckServiceID, state.TaskCheckStateGreaterThan},
+ },
+ )
+ defer cancelWatch()
+ }
+
+ stopped := false
+ failedTasks := make(map[string]struct{})
+ totalFailures := 0
+
+ failureTriggersAction := func(failedTask *api.Task) bool {
+ // Ignore tasks we have already seen as failures.
+ if _, found := failedTasks[failedTask.ID]; found {
+ return false
+ }
+
+ // If this failed/completed task is one that we
+ // created as part of this update, we should
+ // follow the failure action.
+ u.updatedTasksMu.Lock()
+ startedAt, found := u.updatedTasks[failedTask.ID]
+ u.updatedTasksMu.Unlock()
+
+ if found && (startedAt.IsZero() || time.Since(startedAt) <= monitoringPeriod) {
+ failedTasks[failedTask.ID] = struct{}{}
+ totalFailures++
+ if float32(totalFailures)/float32(len(dirtySlots)) > updateConfig.MaxFailureRatio {
+ switch updateConfig.FailureAction {
+ case api.UpdateConfig_PAUSE:
+ stopped = true
+ message := fmt.Sprintf("update paused due to failure or early termination of task %s", failedTask.ID)
+ u.pauseUpdate(ctx, service.ID, message)
+ return true
+ case api.UpdateConfig_ROLLBACK:
+ // Never roll back a rollback
+ if service.UpdateStatus != nil && service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_STARTED {
+ message := fmt.Sprintf("rollback paused due to failure or early termination of task %s", failedTask.ID)
+ u.pauseUpdate(ctx, service.ID, message)
+ return true
+ }
+ stopped = true
+ message := fmt.Sprintf("update rolled back due to failure or early termination of task %s", failedTask.ID)
+ u.rollbackUpdate(ctx, service.ID, message)
+ return true
+ }
+ }
+ }
+
+ return false
+ }
+
+slotsLoop:
+ for _, slot := range dirtySlots {
+ retryLoop:
+ for {
+ // Wait for a worker to pick up the task or abort the update, whichever comes first.
+ select {
+ case <-u.stopChan:
+ stopped = true
+ break slotsLoop
+ case ev := <-failedTaskWatch:
+ if failureTriggersAction(ev.(api.EventUpdateTask).Task) {
+ break slotsLoop
+ }
+ case slotQueue <- slot:
+ break retryLoop
+ }
+ }
+ }
+
+ close(slotQueue)
+ wg.Wait()
+
+ if !stopped {
+ // Keep watching for task failures for one more monitoringPeriod,
+ // before declaring the update complete.
+ doneMonitoring := time.After(monitoringPeriod)
+ monitorLoop:
+ for {
+ select {
+ case <-u.stopChan:
+ stopped = true
+ break monitorLoop
+ case <-doneMonitoring:
+ break monitorLoop
+ case ev := <-failedTaskWatch:
+ if failureTriggersAction(ev.(api.EventUpdateTask).Task) {
+ break monitorLoop
+ }
+ }
+ }
+ }
+
+ // TODO(aaronl): Potentially roll back the service if not enough tasks
+ // have reached RUNNING by this point.
+
+ if !stopped {
+ u.completeUpdate(ctx, service.ID)
+ }
+}
+
+func (u *Updater) worker(ctx context.Context, queue <-chan orchestrator.Slot, updateConfig *api.UpdateConfig) {
+ for slot := range queue {
+ // Do we have a task with the new spec in desired state = RUNNING?
+ // If so, all we have to do to complete the update is remove the
+ // other tasks. Or if we have a task with the new spec that has
+ // desired state < RUNNING, advance it to running and remove the
+ // other tasks.
+ var (
+ runningTask *api.Task
+ cleanTask *api.Task
+ )
+ for _, t := range slot {
+ if !u.isTaskDirty(t) {
+ if t.DesiredState == api.TaskStateRunning {
+ runningTask = t
+ break
+ }
+ if t.DesiredState < api.TaskStateRunning {
+ cleanTask = t
+ }
+ }
+ }
+ if runningTask != nil {
+ if err := u.useExistingTask(ctx, slot, runningTask); err != nil {
+ log.G(ctx).WithError(err).Error("update failed")
+ }
+ } else if cleanTask != nil {
+ if err := u.useExistingTask(ctx, slot, cleanTask); err != nil {
+ log.G(ctx).WithError(err).Error("update failed")
+ }
+ } else {
+ updated := orchestrator.NewTask(u.cluster, u.newService, slot[0].Slot, "")
+ if orchestrator.IsGlobalService(u.newService) {
+ updated = orchestrator.NewTask(u.cluster, u.newService, slot[0].Slot, slot[0].NodeID)
+ }
+ updated.DesiredState = api.TaskStateReady
+
+ if err := u.updateTask(ctx, slot, updated, updateConfig.Order); err != nil {
+ log.G(ctx).WithError(err).WithField("task.id", updated.ID).Error("update failed")
+ }
+ }
+
+ if updateConfig.Delay != 0 {
+ select {
+ case <-time.After(updateConfig.Delay):
+ case <-u.stopChan:
+ return
+ }
+ }
+ }
+}
+
+func (u *Updater) updateTask(ctx context.Context, slot orchestrator.Slot, updated *api.Task, order api.UpdateConfig_UpdateOrder) error {
+ // Kick off the watch before even creating the updated task. This is in order to avoid missing any event.
+ taskUpdates, cancel := state.Watch(u.watchQueue, api.EventUpdateTask{
+ Task: &api.Task{ID: updated.ID},
+ Checks: []api.TaskCheckFunc{api.TaskCheckID},
+ })
+ defer cancel()
+
+ // Create an empty entry for this task, so the updater knows a failure
+ // should count towards the failure count. The timestamp is added
+ // if/when the task reaches RUNNING.
+ u.updatedTasksMu.Lock()
+ u.updatedTasks[updated.ID] = time.Time{}
+ u.updatedTasksMu.Unlock()
+
+ startThenStop := false
+ var delayStartCh <-chan struct{}
+ // Atomically create the updated task and bring down the old one.
+ err := u.store.Batch(func(batch *store.Batch) error {
+ err := batch.Update(func(tx store.Tx) error {
+ if store.GetService(tx, updated.ServiceID) == nil {
+ return errors.New("service was deleted")
+ }
+
+ if err := store.CreateTask(tx, updated); err != nil {
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ if order == api.UpdateConfig_START_FIRST {
+ delayStartCh = u.restarts.DelayStart(ctx, nil, nil, updated.ID, 0, false)
+ startThenStop = true
+ } else {
+ oldTask, err := u.removeOldTasks(ctx, batch, slot)
+ if err != nil {
+ return err
+ }
+ delayStartCh = u.restarts.DelayStart(ctx, nil, oldTask, updated.ID, 0, true)
+ }
+
+ return nil
+
+ })
+ if err != nil {
+ return err
+ }
+
+ if delayStartCh != nil {
+ select {
+ case <-delayStartCh:
+ case <-u.stopChan:
+ return nil
+ }
+ }
+
+ // Wait for the new task to come up.
+ // TODO(aluzzardi): Consider adding a timeout here.
+ for {
+ select {
+ case e := <-taskUpdates:
+ updated = e.(api.EventUpdateTask).Task
+ if updated.Status.State >= api.TaskStateRunning {
+ u.updatedTasksMu.Lock()
+ u.updatedTasks[updated.ID] = time.Now()
+ u.updatedTasksMu.Unlock()
+
+ if startThenStop {
+ err := u.store.Batch(func(batch *store.Batch) error {
+ _, err := u.removeOldTasks(ctx, batch, slot)
+ if err != nil {
+ log.G(ctx).WithError(err).WithField("task.id", updated.ID).Warning("failed to remove old task after starting replacement")
+ }
+ return nil
+ })
+ return err
+ }
+ return nil
+ }
+ case <-u.stopChan:
+ return nil
+ }
+ }
+}
+
+func (u *Updater) useExistingTask(ctx context.Context, slot orchestrator.Slot, existing *api.Task) error {
+ var removeTasks []*api.Task
+ for _, t := range slot {
+ if t != existing {
+ removeTasks = append(removeTasks, t)
+ }
+ }
+ if len(removeTasks) != 0 || existing.DesiredState != api.TaskStateRunning {
+ var delayStartCh <-chan struct{}
+ err := u.store.Batch(func(batch *store.Batch) error {
+ var oldTask *api.Task
+ if len(removeTasks) != 0 {
+ var err error
+ oldTask, err = u.removeOldTasks(ctx, batch, removeTasks)
+ if err != nil {
+ return err
+ }
+ }
+
+ if existing.DesiredState != api.TaskStateRunning {
+ delayStartCh = u.restarts.DelayStart(ctx, nil, oldTask, existing.ID, 0, true)
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ if delayStartCh != nil {
+ select {
+ case <-delayStartCh:
+ case <-u.stopChan:
+ return nil
+ }
+ }
+ }
+
+ return nil
+}
+
+// removeOldTasks shuts down the given tasks and returns one of the tasks that
+// was shut down, or an error.
+func (u *Updater) removeOldTasks(ctx context.Context, batch *store.Batch, removeTasks []*api.Task) (*api.Task, error) {
+ var (
+ lastErr error
+ removedTask *api.Task
+ )
+ for _, original := range removeTasks {
+ err := batch.Update(func(tx store.Tx) error {
+ t := store.GetTask(tx, original.ID)
+ if t == nil {
+ return fmt.Errorf("task %s not found while trying to shut it down", original.ID)
+ }
+ if t.DesiredState > api.TaskStateRunning {
+ return fmt.Errorf("task %s was already shut down when reached by updater", original.ID)
+ }
+ t.DesiredState = api.TaskStateShutdown
+ return store.UpdateTask(tx, t)
+ })
+ if err != nil {
+ lastErr = err
+ } else {
+ removedTask = original
+ }
+ }
+
+ if removedTask == nil {
+ return nil, lastErr
+ }
+ return removedTask, nil
+}
+
+func (u *Updater) isTaskDirty(t *api.Task) bool {
+ return orchestrator.IsTaskDirty(u.newService, t)
+}
+
+func (u *Updater) isSlotDirty(slot orchestrator.Slot) bool {
+ return len(slot) > 1 || (len(slot) == 1 && u.isTaskDirty(slot[0]))
+}
+
+func (u *Updater) startUpdate(ctx context.Context, serviceID string) {
+ err := u.store.Update(func(tx store.Tx) error {
+ service := store.GetService(tx, serviceID)
+ if service == nil {
+ return nil
+ }
+ if service.UpdateStatus != nil {
+ return nil
+ }
+
+ service.UpdateStatus = &api.UpdateStatus{
+ State: api.UpdateStatus_UPDATING,
+ Message: "update in progress",
+ StartedAt: ptypes.MustTimestampProto(time.Now()),
+ }
+
+ return store.UpdateService(tx, service)
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to mark update of service %s in progress", serviceID)
+ }
+}
+
+func (u *Updater) pauseUpdate(ctx context.Context, serviceID, message string) {
+ log.G(ctx).Debugf("pausing update of service %s", serviceID)
+
+ err := u.store.Update(func(tx store.Tx) error {
+ service := store.GetService(tx, serviceID)
+ if service == nil {
+ return nil
+ }
+ if service.UpdateStatus == nil {
+ // The service was updated since we started this update
+ return nil
+ }
+
+ if service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_STARTED {
+ service.UpdateStatus.State = api.UpdateStatus_ROLLBACK_PAUSED
+ } else {
+ service.UpdateStatus.State = api.UpdateStatus_PAUSED
+ }
+ service.UpdateStatus.Message = message
+
+ return store.UpdateService(tx, service)
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to pause update of service %s", serviceID)
+ }
+}
+
+func (u *Updater) rollbackUpdate(ctx context.Context, serviceID, message string) {
+ log.G(ctx).Debugf("starting rollback of service %s", serviceID)
+
+ var service *api.Service
+ err := u.store.Update(func(tx store.Tx) error {
+ service = store.GetService(tx, serviceID)
+ if service == nil {
+ return nil
+ }
+ if service.UpdateStatus == nil {
+ // The service was updated since we started this update
+ return nil
+ }
+
+ service.UpdateStatus.State = api.UpdateStatus_ROLLBACK_STARTED
+ service.UpdateStatus.Message = message
+
+ if service.PreviousSpec == nil {
+ return errors.New("cannot roll back service because no previous spec is available")
+ }
+ service.Spec = *service.PreviousSpec
+ service.PreviousSpec = nil
+
+ return store.UpdateService(tx, service)
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to start rollback of service %s", serviceID)
+ return
+ }
+}
+
+func (u *Updater) completeUpdate(ctx context.Context, serviceID string) {
+ log.G(ctx).Debugf("update of service %s complete", serviceID)
+
+ err := u.store.Update(func(tx store.Tx) error {
+ service := store.GetService(tx, serviceID)
+ if service == nil {
+ return nil
+ }
+ if service.UpdateStatus == nil {
+ // The service was changed since we started this update
+ return nil
+ }
+ if service.UpdateStatus.State == api.UpdateStatus_ROLLBACK_STARTED {
+ service.UpdateStatus.State = api.UpdateStatus_ROLLBACK_COMPLETED
+ service.UpdateStatus.Message = "rollback completed"
+ } else {
+ service.UpdateStatus.State = api.UpdateStatus_COMPLETED
+ service.UpdateStatus.Message = "update completed"
+ }
+ service.UpdateStatus.CompletedAt = ptypes.MustTimestampProto(time.Now())
+
+ return store.UpdateService(tx, service)
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to mark update of service %s complete", serviceID)
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/raftselector/raftselector.go b/vendor/github.com/docker/swarmkit/manager/raftselector/raftselector.go
new file mode 100644
index 0000000..89e7918
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/raftselector/raftselector.go
@@ -0,0 +1,20 @@
+package raftselector
+
+import (
+ "errors"
+
+ "golang.org/x/net/context"
+
+ "google.golang.org/grpc"
+)
+
+// ConnProvider is basic interface for connecting API package(raft proxy in particular)
+// to manager/state/raft package without import cycles. It provides only one
+// method for obtaining connection to leader.
+type ConnProvider interface {
+ LeaderConn(ctx context.Context) (*grpc.ClientConn, error)
+}
+
+// ErrIsLeader is returned from LeaderConn method when current machine is leader.
+// It's just shim between packages to avoid import cycles.
+var ErrIsLeader = errors.New("current node is leader")
diff --git a/vendor/github.com/docker/swarmkit/manager/resourceapi/allocator.go b/vendor/github.com/docker/swarmkit/manager/resourceapi/allocator.go
new file mode 100644
index 0000000..87b01eb
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/resourceapi/allocator.go
@@ -0,0 +1,124 @@
+package resourceapi
+
+import (
+ "errors"
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/ca"
+ "github.com/docker/swarmkit/identity"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/protobuf/ptypes"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+var (
+ errInvalidArgument = errors.New("invalid argument")
+)
+
+// ResourceAllocator handles resource allocation of cluster entities.
+type ResourceAllocator struct {
+ store *store.MemoryStore
+}
+
+// New returns an instance of the allocator
+func New(store *store.MemoryStore) *ResourceAllocator {
+ return &ResourceAllocator{store: store}
+}
+
+// AttachNetwork allows the node to request the resources
+// allocation needed for a network attachment on the specific node.
+// - Returns `InvalidArgument` if the Spec is malformed.
+// - Returns `NotFound` if the Network is not found.
+// - Returns `PermissionDenied` if the Network is not manually attachable.
+// - Returns an error if the creation fails.
+func (ra *ResourceAllocator) AttachNetwork(ctx context.Context, request *api.AttachNetworkRequest) (*api.AttachNetworkResponse, error) {
+ nodeInfo, err := ca.RemoteNode(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ var network *api.Network
+ ra.store.View(func(tx store.ReadTx) {
+ network = store.GetNetwork(tx, request.Config.Target)
+ if network == nil {
+ if networks, err := store.FindNetworks(tx, store.ByName(request.Config.Target)); err == nil && len(networks) == 1 {
+ network = networks[0]
+ }
+ }
+ })
+ if network == nil {
+ return nil, grpc.Errorf(codes.NotFound, "network %s not found", request.Config.Target)
+ }
+
+ if !network.Spec.Attachable {
+ return nil, grpc.Errorf(codes.PermissionDenied, "network %s not manually attachable", request.Config.Target)
+ }
+
+ t := &api.Task{
+ ID: identity.NewID(),
+ NodeID: nodeInfo.NodeID,
+ Spec: api.TaskSpec{
+ Runtime: &api.TaskSpec_Attachment{
+ Attachment: &api.NetworkAttachmentSpec{
+ ContainerID: request.ContainerID,
+ },
+ },
+ Networks: []*api.NetworkAttachmentConfig{
+ {
+ Target: network.ID,
+ Addresses: request.Config.Addresses,
+ },
+ },
+ },
+ Status: api.TaskStatus{
+ State: api.TaskStateNew,
+ Timestamp: ptypes.MustTimestampProto(time.Now()),
+ Message: "created",
+ },
+ DesiredState: api.TaskStateRunning,
+ // TODO: Add Network attachment.
+ }
+
+ if err := ra.store.Update(func(tx store.Tx) error {
+ return store.CreateTask(tx, t)
+ }); err != nil {
+ return nil, err
+ }
+
+ return &api.AttachNetworkResponse{AttachmentID: t.ID}, nil
+}
+
+// DetachNetwork allows the node to request the release of
+// the resources associated to the network attachment.
+// - Returns `InvalidArgument` if attachment ID is not provided.
+// - Returns `NotFound` if the attachment is not found.
+// - Returns an error if the deletion fails.
+func (ra *ResourceAllocator) DetachNetwork(ctx context.Context, request *api.DetachNetworkRequest) (*api.DetachNetworkResponse, error) {
+ if request.AttachmentID == "" {
+ return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
+ }
+
+ nodeInfo, err := ca.RemoteNode(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := ra.store.Update(func(tx store.Tx) error {
+ t := store.GetTask(tx, request.AttachmentID)
+ if t == nil {
+ return grpc.Errorf(codes.NotFound, "attachment %s not found", request.AttachmentID)
+ }
+ if t.NodeID != nodeInfo.NodeID {
+ return grpc.Errorf(codes.PermissionDenied, "attachment %s doesn't belong to this node", request.AttachmentID)
+ }
+
+ return store.DeleteTask(tx, request.AttachmentID)
+ }); err != nil {
+ return nil, err
+ }
+
+ return &api.DetachNetworkResponse{}, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/role_manager.go b/vendor/github.com/docker/swarmkit/manager/role_manager.go
new file mode 100644
index 0000000..c2e4f1a
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/role_manager.go
@@ -0,0 +1,177 @@
+package manager
+
+import (
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state/raft"
+ "github.com/docker/swarmkit/manager/state/store"
+ "golang.org/x/net/context"
+)
+
+const roleReconcileInterval = 5 * time.Second
+
+// roleManager reconciles the raft member list with desired role changes.
+type roleManager struct {
+ ctx context.Context
+ cancel func()
+
+ store *store.MemoryStore
+ raft *raft.Node
+ doneChan chan struct{}
+
+ // pending contains changed nodes that have not yet been reconciled in
+ // the raft member list.
+ pending map[string]*api.Node
+}
+
+// newRoleManager creates a new roleManager.
+func newRoleManager(store *store.MemoryStore, raftNode *raft.Node) *roleManager {
+ ctx, cancel := context.WithCancel(context.Background())
+ return &roleManager{
+ ctx: ctx,
+ cancel: cancel,
+ store: store,
+ raft: raftNode,
+ doneChan: make(chan struct{}),
+ pending: make(map[string]*api.Node),
+ }
+}
+
+// Run is roleManager's main loop.
+// ctx is only used for logging.
+func (rm *roleManager) Run(ctx context.Context) {
+ defer close(rm.doneChan)
+
+ var (
+ nodes []*api.Node
+ ticker *time.Ticker
+ tickerCh <-chan time.Time
+ )
+
+ watcher, cancelWatch, err := store.ViewAndWatch(rm.store,
+ func(readTx store.ReadTx) error {
+ var err error
+ nodes, err = store.FindNodes(readTx, store.All)
+ return err
+ },
+ api.EventUpdateNode{})
+ defer cancelWatch()
+
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed to check nodes for role changes")
+ } else {
+ for _, node := range nodes {
+ rm.pending[node.ID] = node
+ rm.reconcileRole(ctx, node)
+ }
+ if len(rm.pending) != 0 {
+ ticker = time.NewTicker(roleReconcileInterval)
+ tickerCh = ticker.C
+ }
+ }
+
+ for {
+ select {
+ case event := <-watcher:
+ node := event.(api.EventUpdateNode).Node
+ rm.pending[node.ID] = node
+ rm.reconcileRole(ctx, node)
+ if len(rm.pending) != 0 && ticker == nil {
+ ticker = time.NewTicker(roleReconcileInterval)
+ tickerCh = ticker.C
+ }
+ case <-tickerCh:
+ for _, node := range rm.pending {
+ rm.reconcileRole(ctx, node)
+ }
+ if len(rm.pending) == 0 {
+ ticker.Stop()
+ ticker = nil
+ tickerCh = nil
+ }
+ case <-rm.ctx.Done():
+ if ticker != nil {
+ ticker.Stop()
+ }
+ return
+ }
+ }
+}
+
+func (rm *roleManager) reconcileRole(ctx context.Context, node *api.Node) {
+ if node.Role == node.Spec.DesiredRole {
+ // Nothing to do.
+ delete(rm.pending, node.ID)
+ return
+ }
+
+ // Promotion can proceed right away.
+ if node.Spec.DesiredRole == api.NodeRoleManager && node.Role == api.NodeRoleWorker {
+ err := rm.store.Update(func(tx store.Tx) error {
+ updatedNode := store.GetNode(tx, node.ID)
+ if updatedNode == nil || updatedNode.Spec.DesiredRole != node.Spec.DesiredRole || updatedNode.Role != node.Role {
+ return nil
+ }
+ updatedNode.Role = api.NodeRoleManager
+ return store.UpdateNode(tx, updatedNode)
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to promote node %s", node.ID)
+ } else {
+ delete(rm.pending, node.ID)
+ }
+ } else if node.Spec.DesiredRole == api.NodeRoleWorker && node.Role == api.NodeRoleManager {
+ // Check for node in memberlist
+ member := rm.raft.GetMemberByNodeID(node.ID)
+ if member != nil {
+ // Quorum safeguard
+ if !rm.raft.CanRemoveMember(member.RaftID) {
+ // TODO(aaronl): Retry later
+ log.G(ctx).Debugf("can't demote node %s at this time: removing member from raft would result in a loss of quorum", node.ID)
+ return
+ }
+
+ rmCtx, rmCancel := context.WithTimeout(rm.ctx, 5*time.Second)
+ defer rmCancel()
+
+ if member.RaftID == rm.raft.Config.ID {
+ // Don't use rmCtx, because we expect to lose
+ // leadership, which will cancel this context.
+ log.G(ctx).Info("demoted; transferring leadership")
+ err := rm.raft.TransferLeadership(context.Background())
+ if err == nil {
+ return
+ }
+ log.G(ctx).WithError(err).Info("failed to transfer leadership")
+ }
+ if err := rm.raft.RemoveMember(rmCtx, member.RaftID); err != nil {
+ // TODO(aaronl): Retry later
+ log.G(ctx).WithError(err).Debugf("can't demote node %s at this time", node.ID)
+ }
+ return
+ }
+
+ err := rm.store.Update(func(tx store.Tx) error {
+ updatedNode := store.GetNode(tx, node.ID)
+ if updatedNode == nil || updatedNode.Spec.DesiredRole != node.Spec.DesiredRole || updatedNode.Role != node.Role {
+ return nil
+ }
+ updatedNode.Role = api.NodeRoleWorker
+
+ return store.UpdateNode(tx, updatedNode)
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to demote node %s", node.ID)
+ } else {
+ delete(rm.pending, node.ID)
+ }
+ }
+}
+
+// Stop stops the roleManager and waits for the main loop to exit.
+func (rm *roleManager) Stop() {
+ rm.cancel()
+ <-rm.doneChan
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/scheduler/decision_tree.go b/vendor/github.com/docker/swarmkit/manager/scheduler/decision_tree.go
new file mode 100644
index 0000000..4567753
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/scheduler/decision_tree.go
@@ -0,0 +1,55 @@
+package scheduler
+
+import (
+ "container/heap"
+)
+
+type decisionTree struct {
+ // Count of tasks for the service scheduled to this subtree
+ tasks int
+
+ // Non-leaf point to the next level of the tree. The key is the
+ // value that the subtree covers.
+ next map[string]*decisionTree
+
+ // Leaf nodes contain a list of nodes
+ nodeHeap nodeMaxHeap
+}
+
+// orderedNodes returns the nodes in this decision tree entry, sorted best
+// (lowest) first according to the sorting function. Must be called on a leaf
+// of the decision tree.
+//
+// The caller may modify the nodes in the returned slice. This has the effect
+// of changing the nodes in the decision tree entry. The next node to
+// findBestNodes on this decisionTree entry will take into account the changes
+// that were made to the nodes.
+func (dt *decisionTree) orderedNodes(meetsConstraints func(*NodeInfo) bool, nodeLess func(*NodeInfo, *NodeInfo) bool) []NodeInfo {
+ if dt.nodeHeap.length != len(dt.nodeHeap.nodes) {
+ // We already collapsed the heap into a sorted slice, so
+ // re-heapify. There may have been modifications to the nodes
+ // so we can't return dt.nodeHeap.nodes as-is. We also need to
+ // reevaluate constraints because of the possible modifications.
+ for i := 0; i < len(dt.nodeHeap.nodes); {
+ if meetsConstraints(&dt.nodeHeap.nodes[i]) {
+ i++
+ } else {
+ last := len(dt.nodeHeap.nodes) - 1
+ dt.nodeHeap.nodes[i] = dt.nodeHeap.nodes[last]
+ dt.nodeHeap.nodes = dt.nodeHeap.nodes[:last]
+ }
+ }
+ dt.nodeHeap.length = len(dt.nodeHeap.nodes)
+ heap.Init(&dt.nodeHeap)
+ }
+
+ // Popping every element orders the nodes from best to worst. The
+ // first pop gets the worst node (since this a max-heap), and puts it
+ // at position n-1. Then the next pop puts the next-worst at n-2, and
+ // so on.
+ for dt.nodeHeap.Len() > 0 {
+ heap.Pop(&dt.nodeHeap)
+ }
+
+ return dt.nodeHeap.nodes
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/scheduler/filter.go b/vendor/github.com/docker/swarmkit/manager/scheduler/filter.go
new file mode 100644
index 0000000..36b601c
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/scheduler/filter.go
@@ -0,0 +1,350 @@
+package scheduler
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/genericresource"
+ "github.com/docker/swarmkit/manager/constraint"
+)
+
+// Filter checks whether the given task can run on the given node.
+// A filter may only operate
+type Filter interface {
+ // SetTask returns true when the filter is enabled for a given task
+ // and assigns the task to the filter. It returns false if the filter
+ // isn't applicable to this task. For instance, a constraints filter
+ // would return `false` if the task doesn't contain any constraints.
+ SetTask(*api.Task) bool
+
+ // Check returns true if the task assigned by SetTask can be scheduled
+ // into the given node. This function should not be called if SetTask
+ // returned false.
+ Check(*NodeInfo) bool
+
+ // Explain what a failure of this filter means
+ Explain(nodes int) string
+}
+
+// ReadyFilter checks that the node is ready to schedule tasks.
+type ReadyFilter struct {
+}
+
+// SetTask returns true when the filter is enabled for a given task.
+func (f *ReadyFilter) SetTask(_ *api.Task) bool {
+ return true
+}
+
+// Check returns true if the task can be scheduled into the given node.
+func (f *ReadyFilter) Check(n *NodeInfo) bool {
+ return n.Status.State == api.NodeStatus_READY &&
+ n.Spec.Availability == api.NodeAvailabilityActive
+}
+
+// Explain returns an explanation of a failure.
+func (f *ReadyFilter) Explain(nodes int) string {
+ if nodes == 1 {
+ return "1 node not available for new tasks"
+ }
+ return fmt.Sprintf("%d nodes not available for new tasks", nodes)
+}
+
+// ResourceFilter checks that the node has enough resources available to run
+// the task.
+type ResourceFilter struct {
+ reservations *api.Resources
+}
+
+// SetTask returns true when the filter is enabled for a given task.
+func (f *ResourceFilter) SetTask(t *api.Task) bool {
+ r := t.Spec.Resources
+ if r == nil || r.Reservations == nil {
+ return false
+ }
+
+ res := r.Reservations
+ if res.NanoCPUs == 0 && res.MemoryBytes == 0 && len(res.Generic) == 0 {
+ return false
+ }
+
+ f.reservations = r.Reservations
+ return true
+}
+
+// Check returns true if the task can be scheduled into the given node.
+func (f *ResourceFilter) Check(n *NodeInfo) bool {
+ if f.reservations.NanoCPUs > n.AvailableResources.NanoCPUs {
+ return false
+ }
+
+ if f.reservations.MemoryBytes > n.AvailableResources.MemoryBytes {
+ return false
+ }
+
+ for _, v := range f.reservations.Generic {
+ enough, err := genericresource.HasEnough(n.AvailableResources.Generic, v)
+ if err != nil || !enough {
+ return false
+ }
+ }
+
+ return true
+}
+
+// Explain returns an explanation of a failure.
+func (f *ResourceFilter) Explain(nodes int) string {
+ if nodes == 1 {
+ return "insufficient resources on 1 node"
+ }
+ return fmt.Sprintf("insufficient resources on %d nodes", nodes)
+}
+
+// PluginFilter checks that the node has a specific volume plugin installed
+type PluginFilter struct {
+ t *api.Task
+}
+
+func referencesVolumePlugin(mount api.Mount) bool {
+ return mount.Type == api.MountTypeVolume &&
+ mount.VolumeOptions != nil &&
+ mount.VolumeOptions.DriverConfig != nil &&
+ mount.VolumeOptions.DriverConfig.Name != "" &&
+ mount.VolumeOptions.DriverConfig.Name != "local"
+
+}
+
+// SetTask returns true when the filter is enabled for a given task.
+func (f *PluginFilter) SetTask(t *api.Task) bool {
+ c := t.Spec.GetContainer()
+
+ var volumeTemplates bool
+ if c != nil {
+ for _, mount := range c.Mounts {
+ if referencesVolumePlugin(mount) {
+ volumeTemplates = true
+ break
+ }
+ }
+ }
+
+ if (c != nil && volumeTemplates) || len(t.Networks) > 0 || t.Spec.LogDriver != nil {
+ f.t = t
+ return true
+ }
+
+ return false
+}
+
+// Check returns true if the task can be scheduled into the given node.
+// TODO(amitshukla): investigate storing Plugins as a map so it can be easily probed
+func (f *PluginFilter) Check(n *NodeInfo) bool {
+ if n.Description == nil || n.Description.Engine == nil {
+ // If the node is not running Engine, plugins are not
+ // supported.
+ return true
+ }
+
+ // Get list of plugins on the node
+ nodePlugins := n.Description.Engine.Plugins
+
+ // Check if all volume plugins required by task are installed on node
+ container := f.t.Spec.GetContainer()
+ if container != nil {
+ for _, mount := range container.Mounts {
+ if referencesVolumePlugin(mount) {
+ if _, exists := f.pluginExistsOnNode("Volume", mount.VolumeOptions.DriverConfig.Name, nodePlugins); !exists {
+ return false
+ }
+ }
+ }
+ }
+
+ // Check if all network plugins required by task are installed on node
+ for _, tn := range f.t.Networks {
+ if tn.Network != nil && tn.Network.DriverState != nil && tn.Network.DriverState.Name != "" {
+ if _, exists := f.pluginExistsOnNode("Network", tn.Network.DriverState.Name, nodePlugins); !exists {
+ return false
+ }
+ }
+ }
+
+ if f.t.Spec.LogDriver != nil {
+ // If there are no log driver types in the list at all, most likely this is
+ // an older daemon that did not report this information. In this case don't filter
+ if typeFound, exists := f.pluginExistsOnNode("Log", f.t.Spec.LogDriver.Name, nodePlugins); !exists && typeFound {
+ return false
+ }
+ }
+ return true
+}
+
+// pluginExistsOnNode returns true if the (pluginName, pluginType) pair is present in nodePlugins
+func (f *PluginFilter) pluginExistsOnNode(pluginType string, pluginName string, nodePlugins []api.PluginDescription) (bool, bool) {
+ var typeFound bool
+
+ for _, np := range nodePlugins {
+ if pluginType != np.Type {
+ continue
+ }
+ typeFound = true
+
+ if pluginName == np.Name {
+ return true, true
+ }
+ // This does not use the reference package to avoid the
+ // overhead of parsing references as part of the scheduling
+ // loop. This is okay only because plugin names are a very
+ // strict subset of the reference grammar that is always
+ // name:tag.
+ if strings.HasPrefix(np.Name, pluginName) && np.Name[len(pluginName):] == ":latest" {
+ return true, true
+ }
+ }
+ return typeFound, false
+}
+
+// Explain returns an explanation of a failure.
+func (f *PluginFilter) Explain(nodes int) string {
+ if nodes == 1 {
+ return "missing plugin on 1 node"
+ }
+ return fmt.Sprintf("missing plugin on %d nodes", nodes)
+}
+
+// ConstraintFilter selects only nodes that match certain labels.
+type ConstraintFilter struct {
+ constraints []constraint.Constraint
+}
+
+// SetTask returns true when the filter is enable for a given task.
+func (f *ConstraintFilter) SetTask(t *api.Task) bool {
+ if t.Spec.Placement == nil || len(t.Spec.Placement.Constraints) == 0 {
+ return false
+ }
+
+ constraints, err := constraint.Parse(t.Spec.Placement.Constraints)
+ if err != nil {
+ // constraints have been validated at controlapi
+ // if in any case it finds an error here, treat this task
+ // as constraint filter disabled.
+ return false
+ }
+ f.constraints = constraints
+ return true
+}
+
+// Check returns true if the task's constraint is supported by the given node.
+func (f *ConstraintFilter) Check(n *NodeInfo) bool {
+ return constraint.NodeMatches(f.constraints, n.Node)
+}
+
+// Explain returns an explanation of a failure.
+func (f *ConstraintFilter) Explain(nodes int) string {
+ if nodes == 1 {
+ return "scheduling constraints not satisfied on 1 node"
+ }
+ return fmt.Sprintf("scheduling constraints not satisfied on %d nodes", nodes)
+}
+
+// PlatformFilter selects only nodes that run the required platform.
+type PlatformFilter struct {
+ supportedPlatforms []*api.Platform
+}
+
+// SetTask returns true when the filter is enabled for a given task.
+func (f *PlatformFilter) SetTask(t *api.Task) bool {
+ placement := t.Spec.Placement
+ if placement != nil {
+ // copy the platform information
+ f.supportedPlatforms = placement.Platforms
+ if len(placement.Platforms) > 0 {
+ return true
+ }
+ }
+ return false
+}
+
+// Check returns true if the task can be scheduled into the given node.
+func (f *PlatformFilter) Check(n *NodeInfo) bool {
+ // if the supportedPlatforms field is empty, then either it wasn't
+ // provided or there are no constraints
+ if len(f.supportedPlatforms) == 0 {
+ return true
+ }
+ // check if the platform for the node is supported
+ if n.Description != nil {
+ if nodePlatform := n.Description.Platform; nodePlatform != nil {
+ for _, p := range f.supportedPlatforms {
+ if f.platformEqual(*p, *nodePlatform) {
+ return true
+ }
+ }
+ }
+ }
+ return false
+}
+
+func (f *PlatformFilter) platformEqual(imgPlatform, nodePlatform api.Platform) bool {
+ // normalize "x86_64" architectures to "amd64"
+ if imgPlatform.Architecture == "x86_64" {
+ imgPlatform.Architecture = "amd64"
+ }
+ if nodePlatform.Architecture == "x86_64" {
+ nodePlatform.Architecture = "amd64"
+ }
+
+ if (imgPlatform.Architecture == "" || imgPlatform.Architecture == nodePlatform.Architecture) && (imgPlatform.OS == "" || imgPlatform.OS == nodePlatform.OS) {
+ return true
+ }
+ return false
+}
+
+// Explain returns an explanation of a failure.
+func (f *PlatformFilter) Explain(nodes int) string {
+ if nodes == 1 {
+ return "unsupported platform on 1 node"
+ }
+ return fmt.Sprintf("unsupported platform on %d nodes", nodes)
+}
+
+// HostPortFilter checks that the node has a specific port available.
+type HostPortFilter struct {
+ t *api.Task
+}
+
+// SetTask returns true when the filter is enabled for a given task.
+func (f *HostPortFilter) SetTask(t *api.Task) bool {
+ if t.Endpoint != nil {
+ for _, port := range t.Endpoint.Ports {
+ if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 {
+ f.t = t
+ return true
+ }
+ }
+ }
+
+ return false
+}
+
+// Check returns true if the task can be scheduled into the given node.
+func (f *HostPortFilter) Check(n *NodeInfo) bool {
+ for _, port := range f.t.Endpoint.Ports {
+ if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 {
+ portSpec := hostPortSpec{protocol: port.Protocol, publishedPort: port.PublishedPort}
+ if _, ok := n.usedHostPorts[portSpec]; ok {
+ return false
+ }
+ }
+ }
+
+ return true
+}
+
+// Explain returns an explanation of a failure.
+func (f *HostPortFilter) Explain(nodes int) string {
+ if nodes == 1 {
+ return "host-mode port already in use on 1 node"
+ }
+ return fmt.Sprintf("host-mode port already in use on %d nodes", nodes)
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/scheduler/nodeheap.go b/vendor/github.com/docker/swarmkit/manager/scheduler/nodeheap.go
new file mode 100644
index 0000000..ca6db8e
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/scheduler/nodeheap.go
@@ -0,0 +1,31 @@
+package scheduler
+
+type nodeMaxHeap struct {
+ nodes []NodeInfo
+ lessFunc func(*NodeInfo, *NodeInfo) bool
+ length int
+}
+
+func (h nodeMaxHeap) Len() int {
+ return h.length
+}
+
+func (h nodeMaxHeap) Swap(i, j int) {
+ h.nodes[i], h.nodes[j] = h.nodes[j], h.nodes[i]
+}
+
+func (h nodeMaxHeap) Less(i, j int) bool {
+ // reversed to make a max-heap
+ return h.lessFunc(&h.nodes[j], &h.nodes[i])
+}
+
+func (h *nodeMaxHeap) Push(x interface{}) {
+ h.nodes = append(h.nodes, x.(NodeInfo))
+ h.length++
+}
+
+func (h *nodeMaxHeap) Pop() interface{} {
+ h.length--
+ // return value is never used
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/scheduler/nodeinfo.go b/vendor/github.com/docker/swarmkit/manager/scheduler/nodeinfo.go
new file mode 100644
index 0000000..a375ed9
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/scheduler/nodeinfo.go
@@ -0,0 +1,181 @@
+package scheduler
+
+import (
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/genericresource"
+ "github.com/docker/swarmkit/log"
+ "golang.org/x/net/context"
+)
+
+// hostPortSpec specifies a used host port.
+type hostPortSpec struct {
+ protocol api.PortConfig_Protocol
+ publishedPort uint32
+}
+
+// NodeInfo contains a node and some additional metadata.
+type NodeInfo struct {
+ *api.Node
+ Tasks map[string]*api.Task
+ ActiveTasksCount int
+ ActiveTasksCountByService map[string]int
+ AvailableResources *api.Resources
+ usedHostPorts map[hostPortSpec]struct{}
+
+ // recentFailures is a map from service ID to the timestamps of the
+ // most recent failures the node has experienced from replicas of that
+ // service.
+ // TODO(aaronl): When spec versioning is supported, this should track
+ // the version of the spec that failed.
+ recentFailures map[string][]time.Time
+}
+
+func newNodeInfo(n *api.Node, tasks map[string]*api.Task, availableResources api.Resources) NodeInfo {
+ nodeInfo := NodeInfo{
+ Node: n,
+ Tasks: make(map[string]*api.Task),
+ ActiveTasksCountByService: make(map[string]int),
+ AvailableResources: availableResources.Copy(),
+ usedHostPorts: make(map[hostPortSpec]struct{}),
+ recentFailures: make(map[string][]time.Time),
+ }
+
+ for _, t := range tasks {
+ nodeInfo.addTask(t)
+ }
+
+ return nodeInfo
+}
+
+// removeTask removes a task from nodeInfo if it's tracked there, and returns true
+// if nodeInfo was modified.
+func (nodeInfo *NodeInfo) removeTask(t *api.Task) bool {
+ oldTask, ok := nodeInfo.Tasks[t.ID]
+ if !ok {
+ return false
+ }
+
+ delete(nodeInfo.Tasks, t.ID)
+ if oldTask.DesiredState <= api.TaskStateRunning {
+ nodeInfo.ActiveTasksCount--
+ nodeInfo.ActiveTasksCountByService[t.ServiceID]--
+ }
+
+ if t.Endpoint != nil {
+ for _, port := range t.Endpoint.Ports {
+ if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 {
+ portSpec := hostPortSpec{protocol: port.Protocol, publishedPort: port.PublishedPort}
+ delete(nodeInfo.usedHostPorts, portSpec)
+ }
+ }
+ }
+
+ reservations := taskReservations(t.Spec)
+ resources := nodeInfo.AvailableResources
+
+ resources.MemoryBytes += reservations.MemoryBytes
+ resources.NanoCPUs += reservations.NanoCPUs
+
+ if nodeInfo.Description == nil || nodeInfo.Description.Resources == nil ||
+ nodeInfo.Description.Resources.Generic == nil {
+ return true
+ }
+
+ taskAssigned := t.AssignedGenericResources
+ nodeAvailableResources := &resources.Generic
+ nodeRes := nodeInfo.Description.Resources.Generic
+ genericresource.Reclaim(nodeAvailableResources, taskAssigned, nodeRes)
+
+ return true
+}
+
+// addTask adds or updates a task on nodeInfo, and returns true if nodeInfo was
+// modified.
+func (nodeInfo *NodeInfo) addTask(t *api.Task) bool {
+ oldTask, ok := nodeInfo.Tasks[t.ID]
+ if ok {
+ if t.DesiredState <= api.TaskStateRunning && oldTask.DesiredState > api.TaskStateRunning {
+ nodeInfo.Tasks[t.ID] = t
+ nodeInfo.ActiveTasksCount++
+ nodeInfo.ActiveTasksCountByService[t.ServiceID]++
+ return true
+ } else if t.DesiredState > api.TaskStateRunning && oldTask.DesiredState <= api.TaskStateRunning {
+ nodeInfo.Tasks[t.ID] = t
+ nodeInfo.ActiveTasksCount--
+ nodeInfo.ActiveTasksCountByService[t.ServiceID]--
+ return true
+ }
+ return false
+ }
+
+ nodeInfo.Tasks[t.ID] = t
+
+ reservations := taskReservations(t.Spec)
+ resources := nodeInfo.AvailableResources
+
+ resources.MemoryBytes -= reservations.MemoryBytes
+ resources.NanoCPUs -= reservations.NanoCPUs
+
+ // minimum size required
+ t.AssignedGenericResources = make([]*api.GenericResource, 0, len(resources.Generic))
+ taskAssigned := &t.AssignedGenericResources
+
+ genericresource.Claim(&resources.Generic, taskAssigned, reservations.Generic)
+
+ if t.Endpoint != nil {
+ for _, port := range t.Endpoint.Ports {
+ if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 {
+ portSpec := hostPortSpec{protocol: port.Protocol, publishedPort: port.PublishedPort}
+ nodeInfo.usedHostPorts[portSpec] = struct{}{}
+ }
+ }
+ }
+
+ if t.DesiredState <= api.TaskStateRunning {
+ nodeInfo.ActiveTasksCount++
+ nodeInfo.ActiveTasksCountByService[t.ServiceID]++
+ }
+
+ return true
+}
+
+func taskReservations(spec api.TaskSpec) (reservations api.Resources) {
+ if spec.Resources != nil && spec.Resources.Reservations != nil {
+ reservations = *spec.Resources.Reservations
+ }
+ return
+}
+
+// taskFailed records a task failure from a given service.
+func (nodeInfo *NodeInfo) taskFailed(ctx context.Context, serviceID string) {
+ expired := 0
+ now := time.Now()
+ for _, timestamp := range nodeInfo.recentFailures[serviceID] {
+ if now.Sub(timestamp) < monitorFailures {
+ break
+ }
+ expired++
+ }
+
+ if len(nodeInfo.recentFailures[serviceID])-expired == maxFailures-1 {
+ log.G(ctx).Warnf("underweighting node %s for service %s because it experienced %d failures or rejections within %s", nodeInfo.ID, serviceID, maxFailures, monitorFailures.String())
+ }
+
+ nodeInfo.recentFailures[serviceID] = append(nodeInfo.recentFailures[serviceID][expired:], now)
+}
+
+// countRecentFailures returns the number of times the service has failed on
+// this node within the lookback window monitorFailures.
+func (nodeInfo *NodeInfo) countRecentFailures(now time.Time, serviceID string) int {
+ recentFailureCount := len(nodeInfo.recentFailures[serviceID])
+ for i := recentFailureCount - 1; i >= 0; i-- {
+ if now.Sub(nodeInfo.recentFailures[serviceID][i]) > monitorFailures {
+ recentFailureCount -= i + 1
+ break
+ }
+ }
+
+ return recentFailureCount
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/scheduler/nodeset.go b/vendor/github.com/docker/swarmkit/manager/scheduler/nodeset.go
new file mode 100644
index 0000000..b83704a
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/scheduler/nodeset.go
@@ -0,0 +1,124 @@
+package scheduler
+
+import (
+ "container/heap"
+ "errors"
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/constraint"
+)
+
+var errNodeNotFound = errors.New("node not found in scheduler dataset")
+
+type nodeSet struct {
+ nodes map[string]NodeInfo // map from node id to node info
+}
+
+func (ns *nodeSet) alloc(n int) {
+ ns.nodes = make(map[string]NodeInfo, n)
+}
+
+// nodeInfo returns the NodeInfo struct for a given node identified by its ID.
+func (ns *nodeSet) nodeInfo(nodeID string) (NodeInfo, error) {
+ node, ok := ns.nodes[nodeID]
+ if ok {
+ return node, nil
+ }
+ return NodeInfo{}, errNodeNotFound
+}
+
+// addOrUpdateNode sets the number of tasks for a given node. It adds the node
+// to the set if it wasn't already tracked.
+func (ns *nodeSet) addOrUpdateNode(n NodeInfo) {
+ ns.nodes[n.ID] = n
+}
+
+// updateNode sets the number of tasks for a given node. It ignores the update
+// if the node isn't already tracked in the set.
+func (ns *nodeSet) updateNode(n NodeInfo) {
+ _, ok := ns.nodes[n.ID]
+ if ok {
+ ns.nodes[n.ID] = n
+ }
+}
+
+func (ns *nodeSet) remove(nodeID string) {
+ delete(ns.nodes, nodeID)
+}
+
+func (ns *nodeSet) tree(serviceID string, preferences []*api.PlacementPreference, maxAssignments int, meetsConstraints func(*NodeInfo) bool, nodeLess func(*NodeInfo, *NodeInfo) bool) decisionTree {
+ var root decisionTree
+
+ if maxAssignments == 0 {
+ return root
+ }
+
+ for _, node := range ns.nodes {
+ tree := &root
+ for _, pref := range preferences {
+ // Only spread is supported so far
+ spread := pref.GetSpread()
+ if spread == nil {
+ continue
+ }
+
+ descriptor := spread.SpreadDescriptor
+ var value string
+ switch {
+ case len(descriptor) > len(constraint.NodeLabelPrefix) && strings.EqualFold(descriptor[:len(constraint.NodeLabelPrefix)], constraint.NodeLabelPrefix):
+ if node.Spec.Annotations.Labels != nil {
+ value = node.Spec.Annotations.Labels[descriptor[len(constraint.NodeLabelPrefix):]]
+ }
+ case len(descriptor) > len(constraint.EngineLabelPrefix) && strings.EqualFold(descriptor[:len(constraint.EngineLabelPrefix)], constraint.EngineLabelPrefix):
+ if node.Description != nil && node.Description.Engine != nil && node.Description.Engine.Labels != nil {
+ value = node.Description.Engine.Labels[descriptor[len(constraint.EngineLabelPrefix):]]
+ }
+ // TODO(aaronl): Support other items from constraint
+ // syntax like node ID, hostname, os/arch, etc?
+ default:
+ continue
+ }
+
+ // If value is still uninitialized, the value used for
+ // the node at this level of the tree is "". This makes
+ // sure that the tree structure is not affected by
+ // which properties nodes have and don't have.
+
+ if node.ActiveTasksCountByService != nil {
+ tree.tasks += node.ActiveTasksCountByService[serviceID]
+ }
+
+ if tree.next == nil {
+ tree.next = make(map[string]*decisionTree)
+ }
+ next := tree.next[value]
+ if next == nil {
+ next = &decisionTree{}
+ tree.next[value] = next
+ }
+ tree = next
+ }
+
+ if node.ActiveTasksCountByService != nil {
+ tree.tasks += node.ActiveTasksCountByService[serviceID]
+ }
+
+ if tree.nodeHeap.lessFunc == nil {
+ tree.nodeHeap.lessFunc = nodeLess
+ }
+
+ if tree.nodeHeap.Len() < maxAssignments {
+ if meetsConstraints(&node) {
+ heap.Push(&tree.nodeHeap, node)
+ }
+ } else if nodeLess(&node, &tree.nodeHeap.nodes[0]) {
+ if meetsConstraints(&node) {
+ tree.nodeHeap.nodes[0] = node
+ heap.Fix(&tree.nodeHeap, 0)
+ }
+ }
+ }
+
+ return root
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/scheduler/pipeline.go b/vendor/github.com/docker/swarmkit/manager/scheduler/pipeline.go
new file mode 100644
index 0000000..c577fbc
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/scheduler/pipeline.go
@@ -0,0 +1,98 @@
+package scheduler
+
+import (
+ "sort"
+
+ "github.com/docker/swarmkit/api"
+)
+
+var (
+ defaultFilters = []Filter{
+ // Always check for readiness first.
+ &ReadyFilter{},
+ &ResourceFilter{},
+ &PluginFilter{},
+ &ConstraintFilter{},
+ &PlatformFilter{},
+ &HostPortFilter{},
+ }
+)
+
+type checklistEntry struct {
+ f Filter
+ enabled bool
+
+ // failureCount counts the number of nodes that this filter failed
+ // against.
+ failureCount int
+}
+
+type checklistByFailures []checklistEntry
+
+func (c checklistByFailures) Len() int { return len(c) }
+func (c checklistByFailures) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
+func (c checklistByFailures) Less(i, j int) bool { return c[i].failureCount < c[j].failureCount }
+
+// Pipeline runs a set of filters against nodes.
+type Pipeline struct {
+ // checklist is a slice of filters to run
+ checklist []checklistEntry
+}
+
+// NewPipeline returns a pipeline with the default set of filters.
+func NewPipeline() *Pipeline {
+ p := &Pipeline{}
+
+ for _, f := range defaultFilters {
+ p.checklist = append(p.checklist, checklistEntry{f: f})
+ }
+
+ return p
+}
+
+// Process a node through the filter pipeline.
+// Returns true if all filters pass, false otherwise.
+func (p *Pipeline) Process(n *NodeInfo) bool {
+ for i, entry := range p.checklist {
+ if entry.enabled && !entry.f.Check(n) {
+ // Immediately stop on first failure.
+ p.checklist[i].failureCount++
+ return false
+ }
+ }
+ for i := range p.checklist {
+ p.checklist[i].failureCount = 0
+ }
+ return true
+}
+
+// SetTask sets up the filters to process a new task. Once this is called,
+// Process can be called repeatedly to try to assign the task various nodes.
+func (p *Pipeline) SetTask(t *api.Task) {
+ for i := range p.checklist {
+ p.checklist[i].enabled = p.checklist[i].f.SetTask(t)
+ p.checklist[i].failureCount = 0
+ }
+}
+
+// Explain returns a string explaining why a task could not be scheduled.
+func (p *Pipeline) Explain() string {
+ var explanation string
+
+ // Sort from most failures to least
+
+ sortedByFailures := make([]checklistEntry, len(p.checklist))
+ copy(sortedByFailures, p.checklist)
+ sort.Sort(sort.Reverse(checklistByFailures(sortedByFailures)))
+
+ for _, entry := range sortedByFailures {
+ if entry.failureCount > 0 {
+ if len(explanation) > 0 {
+ explanation += "; "
+ }
+ explanation += entry.f.Explain(entry.failureCount)
+ }
+ }
+
+ return explanation
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/scheduler/scheduler.go b/vendor/github.com/docker/swarmkit/manager/scheduler/scheduler.go
new file mode 100644
index 0000000..07d9b04
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/scheduler/scheduler.go
@@ -0,0 +1,737 @@
+package scheduler
+
+import (
+ "time"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/genericresource"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/protobuf/ptypes"
+ "golang.org/x/net/context"
+)
+
+const (
+ // monitorFailures is the lookback period for counting failures of
+ // a task to determine if a node is faulty for a particular service.
+ monitorFailures = 5 * time.Minute
+
+ // maxFailures is the number of failures within monitorFailures that
+ // triggers downweighting of a node in the sorting function.
+ maxFailures = 5
+)
+
+type schedulingDecision struct {
+ old *api.Task
+ new *api.Task
+}
+
+// Scheduler assigns tasks to nodes.
+type Scheduler struct {
+ store *store.MemoryStore
+ unassignedTasks map[string]*api.Task
+ // pendingPreassignedTasks already have NodeID, need resource validation
+ pendingPreassignedTasks map[string]*api.Task
+ // preassignedTasks tracks tasks that were preassigned, including those
+ // past the pending state.
+ preassignedTasks map[string]struct{}
+ nodeSet nodeSet
+ allTasks map[string]*api.Task
+ pipeline *Pipeline
+
+ // stopChan signals to the state machine to stop running
+ stopChan chan struct{}
+ // doneChan is closed when the state machine terminates
+ doneChan chan struct{}
+}
+
+// New creates a new scheduler.
+func New(store *store.MemoryStore) *Scheduler {
+ return &Scheduler{
+ store: store,
+ unassignedTasks: make(map[string]*api.Task),
+ pendingPreassignedTasks: make(map[string]*api.Task),
+ preassignedTasks: make(map[string]struct{}),
+ allTasks: make(map[string]*api.Task),
+ stopChan: make(chan struct{}),
+ doneChan: make(chan struct{}),
+ pipeline: NewPipeline(),
+ }
+}
+
+func (s *Scheduler) setupTasksList(tx store.ReadTx) error {
+ tasks, err := store.FindTasks(tx, store.All)
+ if err != nil {
+ return err
+ }
+
+ tasksByNode := make(map[string]map[string]*api.Task)
+ for _, t := range tasks {
+ // Ignore all tasks that have not reached PENDING
+ // state and tasks that no longer consume resources.
+ if t.Status.State < api.TaskStatePending || t.Status.State > api.TaskStateRunning {
+ continue
+ }
+
+ s.allTasks[t.ID] = t
+ if t.NodeID == "" {
+ s.enqueue(t)
+ continue
+ }
+ // preassigned tasks need to validate resource requirement on corresponding node
+ if t.Status.State == api.TaskStatePending {
+ s.preassignedTasks[t.ID] = struct{}{}
+ s.pendingPreassignedTasks[t.ID] = t
+ continue
+ }
+
+ if tasksByNode[t.NodeID] == nil {
+ tasksByNode[t.NodeID] = make(map[string]*api.Task)
+ }
+ tasksByNode[t.NodeID][t.ID] = t
+ }
+
+ if err := s.buildNodeSet(tx, tasksByNode); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Run is the scheduler event loop.
+func (s *Scheduler) Run(ctx context.Context) error {
+ defer close(s.doneChan)
+
+ updates, cancel, err := store.ViewAndWatch(s.store, s.setupTasksList)
+ if err != nil {
+ log.G(ctx).WithError(err).Errorf("snapshot store update failed")
+ return err
+ }
+ defer cancel()
+
+ // Validate resource for tasks from preassigned tasks
+ // do this before other tasks because preassigned tasks like
+ // global service should start before other tasks
+ s.processPreassignedTasks(ctx)
+
+ // Queue all unassigned tasks before processing changes.
+ s.tick(ctx)
+
+ const (
+ // commitDebounceGap is the amount of time to wait between
+ // commit events to debounce them.
+ commitDebounceGap = 50 * time.Millisecond
+ // maxLatency is a time limit on the debouncing.
+ maxLatency = time.Second
+ )
+ var (
+ debouncingStarted time.Time
+ commitDebounceTimer *time.Timer
+ commitDebounceTimeout <-chan time.Time
+ )
+
+ tickRequired := false
+
+ schedule := func() {
+ if len(s.pendingPreassignedTasks) > 0 {
+ s.processPreassignedTasks(ctx)
+ }
+ if tickRequired {
+ s.tick(ctx)
+ tickRequired = false
+ }
+ }
+
+ // Watch for changes.
+ for {
+ select {
+ case event := <-updates:
+ switch v := event.(type) {
+ case api.EventCreateTask:
+ if s.createTask(ctx, v.Task) {
+ tickRequired = true
+ }
+ case api.EventUpdateTask:
+ if s.updateTask(ctx, v.Task) {
+ tickRequired = true
+ }
+ case api.EventDeleteTask:
+ if s.deleteTask(v.Task) {
+ // deleting tasks may free up node resource, pending tasks should be re-evaluated.
+ tickRequired = true
+ }
+ case api.EventCreateNode:
+ s.createOrUpdateNode(v.Node)
+ tickRequired = true
+ case api.EventUpdateNode:
+ s.createOrUpdateNode(v.Node)
+ tickRequired = true
+ case api.EventDeleteNode:
+ s.nodeSet.remove(v.Node.ID)
+ case state.EventCommit:
+ if commitDebounceTimer != nil {
+ if time.Since(debouncingStarted) > maxLatency {
+ commitDebounceTimer.Stop()
+ commitDebounceTimer = nil
+ commitDebounceTimeout = nil
+ schedule()
+ } else {
+ commitDebounceTimer.Reset(commitDebounceGap)
+ }
+ } else {
+ commitDebounceTimer = time.NewTimer(commitDebounceGap)
+ commitDebounceTimeout = commitDebounceTimer.C
+ debouncingStarted = time.Now()
+ }
+ }
+ case <-commitDebounceTimeout:
+ schedule()
+ commitDebounceTimer = nil
+ commitDebounceTimeout = nil
+ case <-s.stopChan:
+ return nil
+ }
+ }
+}
+
+// Stop causes the scheduler event loop to stop running.
+func (s *Scheduler) Stop() {
+ close(s.stopChan)
+ <-s.doneChan
+}
+
+// enqueue queues a task for scheduling.
+func (s *Scheduler) enqueue(t *api.Task) {
+ s.unassignedTasks[t.ID] = t
+}
+
+func (s *Scheduler) createTask(ctx context.Context, t *api.Task) bool {
+ // Ignore all tasks that have not reached PENDING
+ // state, and tasks that no longer consume resources.
+ if t.Status.State < api.TaskStatePending || t.Status.State > api.TaskStateRunning {
+ return false
+ }
+
+ s.allTasks[t.ID] = t
+ if t.NodeID == "" {
+ // unassigned task
+ s.enqueue(t)
+ return true
+ }
+
+ if t.Status.State == api.TaskStatePending {
+ s.preassignedTasks[t.ID] = struct{}{}
+ s.pendingPreassignedTasks[t.ID] = t
+ // preassigned tasks do not contribute to running tasks count
+ return false
+ }
+
+ nodeInfo, err := s.nodeSet.nodeInfo(t.NodeID)
+ if err == nil && nodeInfo.addTask(t) {
+ s.nodeSet.updateNode(nodeInfo)
+ }
+
+ return false
+}
+
+func (s *Scheduler) updateTask(ctx context.Context, t *api.Task) bool {
+ // Ignore all tasks that have not reached PENDING
+ // state.
+ if t.Status.State < api.TaskStatePending {
+ return false
+ }
+
+ oldTask := s.allTasks[t.ID]
+
+ // Ignore all tasks that have not reached Pending
+ // state, and tasks that no longer consume resources.
+ if t.Status.State > api.TaskStateRunning {
+ if oldTask == nil {
+ return false
+ }
+
+ if t.Status.State != oldTask.Status.State &&
+ (t.Status.State == api.TaskStateFailed || t.Status.State == api.TaskStateRejected) {
+ // Keep track of task failures, so other nodes can be preferred
+ // for scheduling this service if it looks like the service is
+ // failing in a loop on this node. However, skip this for
+ // preassigned tasks, because the scheduler does not choose
+ // which nodes those run on.
+ if _, wasPreassigned := s.preassignedTasks[t.ID]; !wasPreassigned {
+ nodeInfo, err := s.nodeSet.nodeInfo(t.NodeID)
+ if err == nil {
+ nodeInfo.taskFailed(ctx, t.ServiceID)
+ s.nodeSet.updateNode(nodeInfo)
+ }
+ }
+ }
+
+ s.deleteTask(oldTask)
+
+ return true
+ }
+
+ if t.NodeID == "" {
+ // unassigned task
+ if oldTask != nil {
+ s.deleteTask(oldTask)
+ }
+ s.allTasks[t.ID] = t
+ s.enqueue(t)
+ return true
+ }
+
+ if t.Status.State == api.TaskStatePending {
+ if oldTask != nil {
+ s.deleteTask(oldTask)
+ }
+ s.preassignedTasks[t.ID] = struct{}{}
+ s.allTasks[t.ID] = t
+ s.pendingPreassignedTasks[t.ID] = t
+ // preassigned tasks do not contribute to running tasks count
+ return false
+ }
+
+ s.allTasks[t.ID] = t
+ nodeInfo, err := s.nodeSet.nodeInfo(t.NodeID)
+ if err == nil && nodeInfo.addTask(t) {
+ s.nodeSet.updateNode(nodeInfo)
+ }
+
+ return false
+}
+
+func (s *Scheduler) deleteTask(t *api.Task) bool {
+ delete(s.allTasks, t.ID)
+ delete(s.preassignedTasks, t.ID)
+ delete(s.pendingPreassignedTasks, t.ID)
+ nodeInfo, err := s.nodeSet.nodeInfo(t.NodeID)
+ if err == nil && nodeInfo.removeTask(t) {
+ s.nodeSet.updateNode(nodeInfo)
+ return true
+ }
+ return false
+}
+
+func (s *Scheduler) createOrUpdateNode(n *api.Node) {
+ nodeInfo, nodeInfoErr := s.nodeSet.nodeInfo(n.ID)
+ var resources *api.Resources
+ if n.Description != nil && n.Description.Resources != nil {
+ resources = n.Description.Resources.Copy()
+ // reconcile resources by looping over all tasks in this node
+ if nodeInfoErr == nil {
+ for _, task := range nodeInfo.Tasks {
+ reservations := taskReservations(task.Spec)
+
+ resources.MemoryBytes -= reservations.MemoryBytes
+ resources.NanoCPUs -= reservations.NanoCPUs
+
+ genericresource.ConsumeNodeResources(&resources.Generic,
+ task.AssignedGenericResources)
+ }
+ }
+ } else {
+ resources = &api.Resources{}
+ }
+
+ if nodeInfoErr != nil {
+ nodeInfo = newNodeInfo(n, nil, *resources)
+ } else {
+ nodeInfo.Node = n
+ nodeInfo.AvailableResources = resources
+ }
+ s.nodeSet.addOrUpdateNode(nodeInfo)
+}
+
+func (s *Scheduler) processPreassignedTasks(ctx context.Context) {
+ schedulingDecisions := make(map[string]schedulingDecision, len(s.pendingPreassignedTasks))
+ for _, t := range s.pendingPreassignedTasks {
+ newT := s.taskFitNode(ctx, t, t.NodeID)
+ if newT == nil {
+ continue
+ }
+ schedulingDecisions[t.ID] = schedulingDecision{old: t, new: newT}
+ }
+
+ successful, failed := s.applySchedulingDecisions(ctx, schedulingDecisions)
+
+ for _, decision := range successful {
+ if decision.new.Status.State == api.TaskStateAssigned {
+ delete(s.pendingPreassignedTasks, decision.old.ID)
+ }
+ }
+ for _, decision := range failed {
+ s.allTasks[decision.old.ID] = decision.old
+ nodeInfo, err := s.nodeSet.nodeInfo(decision.new.NodeID)
+ if err == nil && nodeInfo.removeTask(decision.new) {
+ s.nodeSet.updateNode(nodeInfo)
+ }
+ }
+}
+
+// tick attempts to schedule the queue.
+func (s *Scheduler) tick(ctx context.Context) {
+ type commonSpecKey struct {
+ serviceID string
+ specVersion api.Version
+ }
+ tasksByCommonSpec := make(map[commonSpecKey]map[string]*api.Task)
+ var oneOffTasks []*api.Task
+ schedulingDecisions := make(map[string]schedulingDecision, len(s.unassignedTasks))
+
+ for taskID, t := range s.unassignedTasks {
+ if t == nil || t.NodeID != "" {
+ // task deleted or already assigned
+ delete(s.unassignedTasks, taskID)
+ continue
+ }
+
+ // Group tasks with common specs
+ if t.SpecVersion != nil {
+ taskGroupKey := commonSpecKey{
+ serviceID: t.ServiceID,
+ specVersion: *t.SpecVersion,
+ }
+
+ if tasksByCommonSpec[taskGroupKey] == nil {
+ tasksByCommonSpec[taskGroupKey] = make(map[string]*api.Task)
+ }
+ tasksByCommonSpec[taskGroupKey][taskID] = t
+ } else {
+ // This task doesn't have a spec version. We have to
+ // schedule it as a one-off.
+ oneOffTasks = append(oneOffTasks, t)
+ }
+ delete(s.unassignedTasks, taskID)
+ }
+
+ for _, taskGroup := range tasksByCommonSpec {
+ s.scheduleTaskGroup(ctx, taskGroup, schedulingDecisions)
+ }
+ for _, t := range oneOffTasks {
+ s.scheduleTaskGroup(ctx, map[string]*api.Task{t.ID: t}, schedulingDecisions)
+ }
+
+ _, failed := s.applySchedulingDecisions(ctx, schedulingDecisions)
+ for _, decision := range failed {
+ s.allTasks[decision.old.ID] = decision.old
+
+ nodeInfo, err := s.nodeSet.nodeInfo(decision.new.NodeID)
+ if err == nil && nodeInfo.removeTask(decision.new) {
+ s.nodeSet.updateNode(nodeInfo)
+ }
+
+ // enqueue task for next scheduling attempt
+ s.enqueue(decision.old)
+ }
+}
+
+func (s *Scheduler) applySchedulingDecisions(ctx context.Context, schedulingDecisions map[string]schedulingDecision) (successful, failed []schedulingDecision) {
+ if len(schedulingDecisions) == 0 {
+ return
+ }
+
+ successful = make([]schedulingDecision, 0, len(schedulingDecisions))
+
+ // Apply changes to master store
+ err := s.store.Batch(func(batch *store.Batch) error {
+ for len(schedulingDecisions) > 0 {
+ err := batch.Update(func(tx store.Tx) error {
+ // Update exactly one task inside this Update
+ // callback.
+ for taskID, decision := range schedulingDecisions {
+ delete(schedulingDecisions, taskID)
+
+ t := store.GetTask(tx, taskID)
+ if t == nil {
+ // Task no longer exists
+ s.deleteTask(decision.new)
+ continue
+ }
+
+ if t.Status.State == decision.new.Status.State && t.Status.Message == decision.new.Status.Message {
+ // No changes, ignore
+ continue
+ }
+
+ if t.Status.State >= api.TaskStateAssigned {
+ nodeInfo, err := s.nodeSet.nodeInfo(decision.new.NodeID)
+ if err != nil {
+ failed = append(failed, decision)
+ continue
+ }
+ node := store.GetNode(tx, decision.new.NodeID)
+ if node == nil || node.Meta.Version != nodeInfo.Meta.Version {
+ // node is out of date
+ failed = append(failed, decision)
+ continue
+ }
+ }
+
+ if err := store.UpdateTask(tx, decision.new); err != nil {
+ log.G(ctx).Debugf("scheduler failed to update task %s; will retry", taskID)
+ failed = append(failed, decision)
+ continue
+ }
+ successful = append(successful, decision)
+ return nil
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+
+ if err != nil {
+ log.G(ctx).WithError(err).Error("scheduler tick transaction failed")
+ failed = append(failed, successful...)
+ successful = nil
+ }
+ return
+}
+
+// taskFitNode checks if a node has enough resources to accommodate a task.
+func (s *Scheduler) taskFitNode(ctx context.Context, t *api.Task, nodeID string) *api.Task {
+ nodeInfo, err := s.nodeSet.nodeInfo(nodeID)
+ if err != nil {
+ // node does not exist in set (it may have been deleted)
+ return nil
+ }
+ newT := *t
+ s.pipeline.SetTask(t)
+ if !s.pipeline.Process(&nodeInfo) {
+ // this node cannot accommodate this task
+ newT.Status.Timestamp = ptypes.MustTimestampProto(time.Now())
+ newT.Status.Message = s.pipeline.Explain()
+ s.allTasks[t.ID] = &newT
+
+ return &newT
+ }
+ newT.Status = api.TaskStatus{
+ State: api.TaskStateAssigned,
+ Timestamp: ptypes.MustTimestampProto(time.Now()),
+ Message: "scheduler confirmed task can run on preassigned node",
+ }
+ s.allTasks[t.ID] = &newT
+
+ if nodeInfo.addTask(&newT) {
+ s.nodeSet.updateNode(nodeInfo)
+ }
+ return &newT
+}
+
+// scheduleTaskGroup schedules a batch of tasks that are part of the same
+// service and share the same version of the spec.
+func (s *Scheduler) scheduleTaskGroup(ctx context.Context, taskGroup map[string]*api.Task, schedulingDecisions map[string]schedulingDecision) {
+ // Pick at task at random from taskGroup to use for constraint
+ // evaluation. It doesn't matter which one we pick because all the
+ // tasks in the group are equal in terms of the fields the constraint
+ // filters consider.
+ var t *api.Task
+ for _, t = range taskGroup {
+ break
+ }
+
+ s.pipeline.SetTask(t)
+
+ now := time.Now()
+
+ nodeLess := func(a *NodeInfo, b *NodeInfo) bool {
+ // If either node has at least maxFailures recent failures,
+ // that's the deciding factor.
+ recentFailuresA := a.countRecentFailures(now, t.ServiceID)
+ recentFailuresB := b.countRecentFailures(now, t.ServiceID)
+
+ if recentFailuresA >= maxFailures || recentFailuresB >= maxFailures {
+ if recentFailuresA > recentFailuresB {
+ return false
+ }
+ if recentFailuresB > recentFailuresA {
+ return true
+ }
+ }
+
+ tasksByServiceA := a.ActiveTasksCountByService[t.ServiceID]
+ tasksByServiceB := b.ActiveTasksCountByService[t.ServiceID]
+
+ if tasksByServiceA < tasksByServiceB {
+ return true
+ }
+ if tasksByServiceA > tasksByServiceB {
+ return false
+ }
+
+ // Total number of tasks breaks ties.
+ return a.ActiveTasksCount < b.ActiveTasksCount
+ }
+
+ var prefs []*api.PlacementPreference
+ if t.Spec.Placement != nil {
+ prefs = t.Spec.Placement.Preferences
+ }
+
+ tree := s.nodeSet.tree(t.ServiceID, prefs, len(taskGroup), s.pipeline.Process, nodeLess)
+
+ s.scheduleNTasksOnSubtree(ctx, len(taskGroup), taskGroup, &tree, schedulingDecisions, nodeLess)
+ if len(taskGroup) != 0 {
+ s.noSuitableNode(ctx, taskGroup, schedulingDecisions)
+ }
+}
+
+func (s *Scheduler) scheduleNTasksOnSubtree(ctx context.Context, n int, taskGroup map[string]*api.Task, tree *decisionTree, schedulingDecisions map[string]schedulingDecision, nodeLess func(a *NodeInfo, b *NodeInfo) bool) int {
+ if tree.next == nil {
+ nodes := tree.orderedNodes(s.pipeline.Process, nodeLess)
+ if len(nodes) == 0 {
+ return 0
+ }
+
+ return s.scheduleNTasksOnNodes(ctx, n, taskGroup, nodes, schedulingDecisions, nodeLess)
+ }
+
+ // Walk the tree and figure out how the tasks should be split at each
+ // level.
+ tasksScheduled := 0
+ tasksInUsableBranches := tree.tasks
+ var noRoom map[*decisionTree]struct{}
+
+ // Try to make branches even until either all branches are
+ // full, or all tasks have been scheduled.
+ for tasksScheduled != n && len(noRoom) != len(tree.next) {
+ desiredTasksPerBranch := (tasksInUsableBranches + n - tasksScheduled) / (len(tree.next) - len(noRoom))
+ remainder := (tasksInUsableBranches + n - tasksScheduled) % (len(tree.next) - len(noRoom))
+
+ for _, subtree := range tree.next {
+ if noRoom != nil {
+ if _, ok := noRoom[subtree]; ok {
+ continue
+ }
+ }
+ subtreeTasks := subtree.tasks
+ if subtreeTasks < desiredTasksPerBranch || (subtreeTasks == desiredTasksPerBranch && remainder > 0) {
+ tasksToAssign := desiredTasksPerBranch - subtreeTasks
+ if remainder > 0 {
+ tasksToAssign++
+ }
+ res := s.scheduleNTasksOnSubtree(ctx, tasksToAssign, taskGroup, subtree, schedulingDecisions, nodeLess)
+ if res < tasksToAssign {
+ if noRoom == nil {
+ noRoom = make(map[*decisionTree]struct{})
+ }
+ noRoom[subtree] = struct{}{}
+ tasksInUsableBranches -= subtreeTasks
+ } else if remainder > 0 {
+ remainder--
+ }
+ tasksScheduled += res
+ }
+ }
+ }
+
+ return tasksScheduled
+}
+
+func (s *Scheduler) scheduleNTasksOnNodes(ctx context.Context, n int, taskGroup map[string]*api.Task, nodes []NodeInfo, schedulingDecisions map[string]schedulingDecision, nodeLess func(a *NodeInfo, b *NodeInfo) bool) int {
+ tasksScheduled := 0
+ failedConstraints := make(map[int]bool) // key is index in nodes slice
+ nodeIter := 0
+ nodeCount := len(nodes)
+ for taskID, t := range taskGroup {
+ // Skip tasks which were already scheduled because they ended
+ // up in two groups at once.
+ if _, exists := schedulingDecisions[taskID]; exists {
+ continue
+ }
+
+ node := &nodes[nodeIter%nodeCount]
+
+ log.G(ctx).WithField("task.id", t.ID).Debugf("assigning to node %s", node.ID)
+ newT := *t
+ newT.NodeID = node.ID
+ newT.Status = api.TaskStatus{
+ State: api.TaskStateAssigned,
+ Timestamp: ptypes.MustTimestampProto(time.Now()),
+ Message: "scheduler assigned task to node",
+ }
+ s.allTasks[t.ID] = &newT
+
+ nodeInfo, err := s.nodeSet.nodeInfo(node.ID)
+ if err == nil && nodeInfo.addTask(&newT) {
+ s.nodeSet.updateNode(nodeInfo)
+ nodes[nodeIter%nodeCount] = nodeInfo
+ }
+
+ schedulingDecisions[taskID] = schedulingDecision{old: t, new: &newT}
+ delete(taskGroup, taskID)
+ tasksScheduled++
+ if tasksScheduled == n {
+ return tasksScheduled
+ }
+
+ if nodeIter+1 < nodeCount {
+ // First pass fills the nodes until they have the same
+ // number of tasks from this service.
+ nextNode := nodes[(nodeIter+1)%nodeCount]
+ if nodeLess(&nextNode, &nodeInfo) {
+ nodeIter++
+ }
+ } else {
+ // In later passes, we just assign one task at a time
+ // to each node that still meets the constraints.
+ nodeIter++
+ }
+
+ origNodeIter := nodeIter
+ for failedConstraints[nodeIter%nodeCount] || !s.pipeline.Process(&nodes[nodeIter%nodeCount]) {
+ failedConstraints[nodeIter%nodeCount] = true
+ nodeIter++
+ if nodeIter-origNodeIter == nodeCount {
+ // None of the nodes meet the constraints anymore.
+ return tasksScheduled
+ }
+ }
+ }
+
+ return tasksScheduled
+}
+
+func (s *Scheduler) noSuitableNode(ctx context.Context, taskGroup map[string]*api.Task, schedulingDecisions map[string]schedulingDecision) {
+ explanation := s.pipeline.Explain()
+ for _, t := range taskGroup {
+ log.G(ctx).WithField("task.id", t.ID).Debug("no suitable node available for task")
+
+ newT := *t
+ newT.Status.Timestamp = ptypes.MustTimestampProto(time.Now())
+ if explanation != "" {
+ newT.Status.Message = "no suitable node (" + explanation + ")"
+ } else {
+ newT.Status.Message = "no suitable node"
+ }
+ s.allTasks[t.ID] = &newT
+ schedulingDecisions[t.ID] = schedulingDecision{old: t, new: &newT}
+
+ s.enqueue(&newT)
+ }
+}
+
+func (s *Scheduler) buildNodeSet(tx store.ReadTx, tasksByNode map[string]map[string]*api.Task) error {
+ nodes, err := store.FindNodes(tx, store.All)
+ if err != nil {
+ return err
+ }
+
+ s.nodeSet.alloc(len(nodes))
+
+ for _, n := range nodes {
+ var resources api.Resources
+ if n.Description != nil && n.Description.Resources != nil {
+ resources = *n.Description.Resources
+ }
+ s.nodeSet.addOrUpdateNode(newNodeInfo(n, tasksByNode[n.ID], resources))
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/proposer.go b/vendor/github.com/docker/swarmkit/manager/state/proposer.go
new file mode 100644
index 0000000..4967f98
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/proposer.go
@@ -0,0 +1,30 @@
+package state
+
+import (
+ "github.com/docker/swarmkit/api"
+ "golang.org/x/net/context"
+)
+
+// A Change includes a version number and a set of store actions from a
+// particular log entry.
+type Change struct {
+ StoreActions []api.StoreAction
+ Version api.Version
+}
+
+// A Proposer can propose actions to a cluster.
+type Proposer interface {
+ // ProposeValue adds storeAction to the distributed log. If this
+ // completes successfully, ProposeValue calls cb to commit the
+ // proposed changes. The callback is necessary for the Proposer to make
+ // sure that the changes are committed before it interacts further
+ // with the store.
+ ProposeValue(ctx context.Context, storeAction []api.StoreAction, cb func()) error
+ // GetVersion returns the monotonic index of the most recent item in
+ // the distributed log.
+ GetVersion() *api.Version
+ // ChangesBetween returns the changes starting after "from", up to and
+ // including "to". If these changes are not available because the log
+ // has been compacted, an error will be returned.
+ ChangesBetween(from, to api.Version) ([]Change, error)
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/raft/membership/cluster.go b/vendor/github.com/docker/swarmkit/manager/state/raft/membership/cluster.go
new file mode 100644
index 0000000..4b9c98d
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/raft/membership/cluster.go
@@ -0,0 +1,213 @@
+package membership
+
+import (
+ "errors"
+ "sync"
+
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/watch"
+ "github.com/gogo/protobuf/proto"
+)
+
+var (
+ // ErrIDExists is thrown when a node wants to join the existing cluster but its ID already exists
+ ErrIDExists = errors.New("membership: can't add node to cluster, node id is a duplicate")
+ // ErrIDRemoved is thrown when a node tries to perform an operation on an existing cluster but was removed
+ ErrIDRemoved = errors.New("membership: node was removed during cluster lifetime")
+ // ErrIDNotFound is thrown when we try an operation on a member that does not exist in the cluster list
+ ErrIDNotFound = errors.New("membership: member not found in cluster list")
+ // ErrConfigChangeInvalid is thrown when a configuration change we received looks invalid in form
+ ErrConfigChangeInvalid = errors.New("membership: ConfChange type should be either AddNode, RemoveNode or UpdateNode")
+ // ErrCannotUnmarshalConfig is thrown when a node cannot unmarshal a configuration change
+ ErrCannotUnmarshalConfig = errors.New("membership: cannot unmarshal configuration change")
+ // ErrMemberRemoved is thrown when a node was removed from the cluster
+ ErrMemberRemoved = errors.New("raft: member was removed from the cluster")
+)
+
+// Cluster represents a set of active
+// raft Members
+type Cluster struct {
+ mu sync.RWMutex
+ members map[uint64]*Member
+
+ // removed contains the list of removed Members,
+ // those ids cannot be reused
+ removed map[uint64]bool
+
+ PeersBroadcast *watch.Queue
+}
+
+// Member represents a raft Cluster Member
+type Member struct {
+ *api.RaftMember
+}
+
+// NewCluster creates a new Cluster neighbors list for a raft Member.
+func NewCluster() *Cluster {
+ // TODO(abronan): generate Cluster ID for federation
+
+ return &Cluster{
+ members: make(map[uint64]*Member),
+ removed: make(map[uint64]bool),
+ PeersBroadcast: watch.NewQueue(),
+ }
+}
+
+// Members returns the list of raft Members in the Cluster.
+func (c *Cluster) Members() map[uint64]*Member {
+ members := make(map[uint64]*Member)
+ c.mu.RLock()
+ for k, v := range c.members {
+ members[k] = v
+ }
+ c.mu.RUnlock()
+ return members
+}
+
+// Removed returns the list of raft Members removed from the Cluster.
+func (c *Cluster) Removed() []uint64 {
+ c.mu.RLock()
+ removed := make([]uint64, 0, len(c.removed))
+ for k := range c.removed {
+ removed = append(removed, k)
+ }
+ c.mu.RUnlock()
+ return removed
+}
+
+// GetMember returns informations on a given Member.
+func (c *Cluster) GetMember(id uint64) *Member {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ return c.members[id]
+}
+
+func (c *Cluster) broadcastUpdate() {
+ peers := make([]*api.Peer, 0, len(c.members))
+ for _, m := range c.members {
+ peers = append(peers, &api.Peer{
+ NodeID: m.NodeID,
+ Addr: m.Addr,
+ })
+ }
+ c.PeersBroadcast.Publish(peers)
+}
+
+// AddMember adds a node to the Cluster Memberlist.
+func (c *Cluster) AddMember(member *Member) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if c.removed[member.RaftID] {
+ return ErrIDRemoved
+ }
+
+ c.members[member.RaftID] = member
+
+ c.broadcastUpdate()
+ return nil
+}
+
+// RemoveMember removes a node from the Cluster Memberlist, and adds it to
+// the removed list.
+func (c *Cluster) RemoveMember(id uint64) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.removed[id] = true
+
+ return c.clearMember(id)
+}
+
+// UpdateMember updates member address.
+func (c *Cluster) UpdateMember(id uint64, m *api.RaftMember) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if c.removed[id] {
+ return ErrIDRemoved
+ }
+
+ oldMember, ok := c.members[id]
+ if !ok {
+ return ErrIDNotFound
+ }
+
+ if oldMember.NodeID != m.NodeID {
+ // Should never happen; this is a sanity check
+ return errors.New("node ID mismatch match on node update")
+ }
+
+ if oldMember.Addr == m.Addr {
+ // nothing to do
+ return nil
+ }
+ oldMember.RaftMember = m
+ c.broadcastUpdate()
+ return nil
+}
+
+// ClearMember removes a node from the Cluster Memberlist, but does NOT add it
+// to the removed list.
+func (c *Cluster) ClearMember(id uint64) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ return c.clearMember(id)
+}
+
+func (c *Cluster) clearMember(id uint64) error {
+ if _, ok := c.members[id]; ok {
+ delete(c.members, id)
+ c.broadcastUpdate()
+ }
+ return nil
+}
+
+// IsIDRemoved checks if a Member is in the remove set.
+func (c *Cluster) IsIDRemoved(id uint64) bool {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ return c.removed[id]
+}
+
+// Clear resets the list of active Members and removed Members.
+func (c *Cluster) Clear() {
+ c.mu.Lock()
+
+ c.members = make(map[uint64]*Member)
+ c.removed = make(map[uint64]bool)
+ c.mu.Unlock()
+}
+
+// ValidateConfigurationChange takes a proposed ConfChange and
+// ensures that it is valid.
+func (c *Cluster) ValidateConfigurationChange(cc raftpb.ConfChange) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ if c.removed[cc.NodeID] {
+ return ErrIDRemoved
+ }
+ switch cc.Type {
+ case raftpb.ConfChangeAddNode:
+ if c.members[cc.NodeID] != nil {
+ return ErrIDExists
+ }
+ case raftpb.ConfChangeRemoveNode:
+ if c.members[cc.NodeID] == nil {
+ return ErrIDNotFound
+ }
+ case raftpb.ConfChangeUpdateNode:
+ if c.members[cc.NodeID] == nil {
+ return ErrIDNotFound
+ }
+ default:
+ return ErrConfigChangeInvalid
+ }
+ m := &api.RaftMember{}
+ if err := proto.Unmarshal(cc.Context, m); err != nil {
+ return ErrCannotUnmarshalConfig
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/raft/raft.go b/vendor/github.com/docker/swarmkit/manager/state/raft/raft.go
new file mode 100644
index 0000000..b793374
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/raft/raft.go
@@ -0,0 +1,1974 @@
+package raft
+
+import (
+ "fmt"
+ "math"
+ "math/rand"
+ "net"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/coreos/etcd/pkg/idutil"
+ "github.com/coreos/etcd/raft"
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/docker/docker/pkg/signal"
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/ca"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/raftselector"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/raft/membership"
+ "github.com/docker/swarmkit/manager/state/raft/storage"
+ "github.com/docker/swarmkit/manager/state/raft/transport"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/docker/swarmkit/watch"
+ "github.com/gogo/protobuf/proto"
+ "github.com/pivotal-golang/clock"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "golang.org/x/time/rate"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/peer"
+)
+
+var (
+ // ErrNoRaftMember is thrown when the node is not yet part of a raft cluster
+ ErrNoRaftMember = errors.New("raft: node is not yet part of a raft cluster")
+ // ErrConfChangeRefused is returned when there is an issue with the configuration change
+ ErrConfChangeRefused = errors.New("raft: propose configuration change refused")
+ // ErrApplyNotSpecified is returned during the creation of a raft node when no apply method was provided
+ ErrApplyNotSpecified = errors.New("raft: apply method was not specified")
+ // ErrSetHardState is returned when the node fails to set the hard state
+ ErrSetHardState = errors.New("raft: failed to set the hard state for log append entry")
+ // ErrStopped is returned when an operation was submitted but the node was stopped in the meantime
+ ErrStopped = errors.New("raft: failed to process the request: node is stopped")
+ // ErrLostLeadership is returned when an operation was submitted but the node lost leader status before it became committed
+ ErrLostLeadership = errors.New("raft: failed to process the request: node lost leader status")
+ // ErrRequestTooLarge is returned when a raft internal message is too large to be sent
+ ErrRequestTooLarge = errors.New("raft: raft message is too large and can't be sent")
+ // ErrCannotRemoveMember is thrown when we try to remove a member from the cluster but this would result in a loss of quorum
+ ErrCannotRemoveMember = errors.New("raft: member cannot be removed, because removing it may result in loss of quorum")
+ // ErrNoClusterLeader is thrown when the cluster has no elected leader
+ ErrNoClusterLeader = errors.New("raft: no elected cluster leader")
+ // ErrMemberUnknown is sent in response to a message from an
+ // unrecognized peer.
+ ErrMemberUnknown = errors.New("raft: member unknown")
+
+ // work around lint
+ lostQuorumMessage = "The swarm does not have a leader. It's possible that too few managers are online. Make sure more than half of the managers are online."
+ errLostQuorum = errors.New(lostQuorumMessage)
+)
+
+// LeadershipState indicates whether the node is a leader or follower.
+type LeadershipState int
+
+const (
+ // IsLeader indicates that the node is a raft leader.
+ IsLeader LeadershipState = iota
+ // IsFollower indicates that the node is a raft follower.
+ IsFollower
+
+ // lostQuorumTimeout is the number of ticks that can elapse with no
+ // leader before LeaderConn starts returning an error right away.
+ lostQuorumTimeout = 10
+)
+
+// EncryptionKeys are the current and, if necessary, pending DEKs with which to
+// encrypt raft data
+type EncryptionKeys struct {
+ CurrentDEK []byte
+ PendingDEK []byte
+}
+
+// EncryptionKeyRotator is an interface to find out if any keys need rotating.
+type EncryptionKeyRotator interface {
+ GetKeys() EncryptionKeys
+ UpdateKeys(EncryptionKeys) error
+ NeedsRotation() bool
+ RotationNotify() chan struct{}
+}
+
+// Node represents the Raft Node useful
+// configuration.
+type Node struct {
+ raftNode raft.Node
+ cluster *membership.Cluster
+ transport *transport.Transport
+
+ raftStore *raft.MemoryStorage
+ memoryStore *store.MemoryStore
+ Config *raft.Config
+ opts NodeOptions
+ reqIDGen *idutil.Generator
+ wait *wait
+ campaignWhenAble bool
+ signalledLeadership uint32
+ isMember uint32
+ bootstrapMembers []*api.RaftMember
+
+ // waitProp waits for all the proposals to be terminated before
+ // shutting down the node.
+ waitProp sync.WaitGroup
+
+ confState raftpb.ConfState
+ appliedIndex uint64
+ snapshotMeta raftpb.SnapshotMetadata
+ writtenWALIndex uint64
+
+ ticker clock.Ticker
+ doneCh chan struct{}
+ // RemovedFromRaft notifies about node deletion from raft cluster
+ RemovedFromRaft chan struct{}
+ cancelFunc func()
+ // removeRaftCh notifies about node deletion from raft cluster
+ removeRaftCh chan struct{}
+ removeRaftOnce sync.Once
+ leadershipBroadcast *watch.Queue
+
+ // used to coordinate shutdown
+ // Lock should be used only in stop(), all other functions should use RLock.
+ stopMu sync.RWMutex
+ // used for membership management checks
+ membershipLock sync.Mutex
+ // synchronizes access to n.opts.Addr, and makes sure the address is not
+ // updated concurrently with JoinAndStart.
+ addrLock sync.Mutex
+
+ snapshotInProgress chan raftpb.SnapshotMetadata
+ asyncTasks sync.WaitGroup
+
+ // stopped chan is used for notifying grpc handlers that raft node going
+ // to stop.
+ stopped chan struct{}
+
+ raftLogger *storage.EncryptedRaftLogger
+ keyRotator EncryptionKeyRotator
+ rotationQueued bool
+ clearData bool
+ waitForAppliedIndex uint64
+ ticksWithNoLeader uint32
+}
+
+// NodeOptions provides node-level options.
+type NodeOptions struct {
+ // ID is the node's ID, from its certificate's CN field.
+ ID string
+ // Addr is the address of this node's listener
+ Addr string
+ // ForceNewCluster defines if we have to force a new cluster
+ // because we are recovering from a backup data directory.
+ ForceNewCluster bool
+ // JoinAddr is the cluster to join. May be an empty string to create
+ // a standalone cluster.
+ JoinAddr string
+ // Config is the raft config.
+ Config *raft.Config
+ // StateDir is the directory to store durable state.
+ StateDir string
+ // TickInterval interval is the time interval between raft ticks.
+ TickInterval time.Duration
+ // ClockSource is a Clock interface to use as a time base.
+ // Leave this nil except for tests that are designed not to run in real
+ // time.
+ ClockSource clock.Clock
+ // SendTimeout is the timeout on the sending messages to other raft
+ // nodes. Leave this as 0 to get the default value.
+ SendTimeout time.Duration
+ TLSCredentials credentials.TransportCredentials
+ KeyRotator EncryptionKeyRotator
+ // DisableStackDump prevents Run from dumping goroutine stacks when the
+ // store becomes stuck.
+ DisableStackDump bool
+}
+
+func init() {
+ rand.Seed(time.Now().UnixNano())
+}
+
+// NewNode generates a new Raft node
+func NewNode(opts NodeOptions) *Node {
+ cfg := opts.Config
+ if cfg == nil {
+ cfg = DefaultNodeConfig()
+ }
+ if opts.TickInterval == 0 {
+ opts.TickInterval = time.Second
+ }
+ if opts.SendTimeout == 0 {
+ opts.SendTimeout = 2 * time.Second
+ }
+
+ raftStore := raft.NewMemoryStorage()
+
+ n := &Node{
+ cluster: membership.NewCluster(),
+ raftStore: raftStore,
+ opts: opts,
+ Config: &raft.Config{
+ ElectionTick: cfg.ElectionTick,
+ HeartbeatTick: cfg.HeartbeatTick,
+ Storage: raftStore,
+ MaxSizePerMsg: cfg.MaxSizePerMsg,
+ MaxInflightMsgs: cfg.MaxInflightMsgs,
+ Logger: cfg.Logger,
+ CheckQuorum: cfg.CheckQuorum,
+ },
+ doneCh: make(chan struct{}),
+ RemovedFromRaft: make(chan struct{}),
+ stopped: make(chan struct{}),
+ leadershipBroadcast: watch.NewQueue(),
+ keyRotator: opts.KeyRotator,
+ }
+ n.memoryStore = store.NewMemoryStore(n)
+
+ if opts.ClockSource == nil {
+ n.ticker = clock.NewClock().NewTicker(opts.TickInterval)
+ } else {
+ n.ticker = opts.ClockSource.NewTicker(opts.TickInterval)
+ }
+
+ n.reqIDGen = idutil.NewGenerator(uint16(n.Config.ID), time.Now())
+ n.wait = newWait()
+
+ n.cancelFunc = func(n *Node) func() {
+ var cancelOnce sync.Once
+ return func() {
+ cancelOnce.Do(func() {
+ close(n.stopped)
+ })
+ }
+ }(n)
+
+ return n
+}
+
+// IsIDRemoved reports if member with id was removed from cluster.
+// Part of transport.Raft interface.
+func (n *Node) IsIDRemoved(id uint64) bool {
+ return n.cluster.IsIDRemoved(id)
+}
+
+// NodeRemoved signals that node was removed from cluster and should stop.
+// Part of transport.Raft interface.
+func (n *Node) NodeRemoved() {
+ n.removeRaftOnce.Do(func() {
+ atomic.StoreUint32(&n.isMember, 0)
+ close(n.RemovedFromRaft)
+ })
+}
+
+// ReportSnapshot reports snapshot status to underlying raft node.
+// Part of transport.Raft interface.
+func (n *Node) ReportSnapshot(id uint64, status raft.SnapshotStatus) {
+ n.raftNode.ReportSnapshot(id, status)
+}
+
+// ReportUnreachable reports to underlying raft node that member with id is
+// unreachable.
+// Part of transport.Raft interface.
+func (n *Node) ReportUnreachable(id uint64) {
+ n.raftNode.ReportUnreachable(id)
+}
+
+// SetAddr provides the raft node's address. This can be used in cases where
+// opts.Addr was not provided to NewNode, for example when a port was not bound
+// until after the raft node was created.
+func (n *Node) SetAddr(ctx context.Context, addr string) error {
+ n.addrLock.Lock()
+ defer n.addrLock.Unlock()
+
+ n.opts.Addr = addr
+
+ if !n.IsMember() {
+ return nil
+ }
+
+ newRaftMember := &api.RaftMember{
+ RaftID: n.Config.ID,
+ NodeID: n.opts.ID,
+ Addr: addr,
+ }
+ if err := n.cluster.UpdateMember(n.Config.ID, newRaftMember); err != nil {
+ return err
+ }
+
+ // If the raft node is running, submit a configuration change
+ // with the new address.
+
+ // TODO(aaronl): Currently, this node must be the leader to
+ // submit this configuration change. This works for the initial
+ // use cases (single-node cluster late binding ports, or calling
+ // SetAddr before joining a cluster). In the future, we may want
+ // to support having a follower proactively change its remote
+ // address.
+
+ leadershipCh, cancelWatch := n.SubscribeLeadership()
+ defer cancelWatch()
+
+ ctx, cancelCtx := n.WithContext(ctx)
+ defer cancelCtx()
+
+ isLeader := atomic.LoadUint32(&n.signalledLeadership) == 1
+ for !isLeader {
+ select {
+ case leadershipChange := <-leadershipCh:
+ if leadershipChange == IsLeader {
+ isLeader = true
+ }
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+
+ return n.updateNodeBlocking(ctx, n.Config.ID, addr)
+}
+
+// WithContext returns context which is cancelled when parent context cancelled
+// or node is stopped.
+func (n *Node) WithContext(ctx context.Context) (context.Context, context.CancelFunc) {
+ ctx, cancel := context.WithCancel(ctx)
+
+ go func() {
+ select {
+ case <-ctx.Done():
+ case <-n.stopped:
+ cancel()
+ }
+ }()
+ return ctx, cancel
+}
+
+func (n *Node) initTransport() {
+ transportConfig := &transport.Config{
+ HeartbeatInterval: time.Duration(n.Config.ElectionTick) * n.opts.TickInterval,
+ SendTimeout: n.opts.SendTimeout,
+ Credentials: n.opts.TLSCredentials,
+ Raft: n,
+ }
+ n.transport = transport.New(transportConfig)
+}
+
+// JoinAndStart joins and starts the raft server
+func (n *Node) JoinAndStart(ctx context.Context) (err error) {
+ ctx, cancel := n.WithContext(ctx)
+ defer func() {
+ cancel()
+ if err != nil {
+ n.stopMu.Lock()
+ // to shutdown transport
+ n.cancelFunc()
+ n.stopMu.Unlock()
+ n.done()
+ } else {
+ atomic.StoreUint32(&n.isMember, 1)
+ }
+ }()
+
+ loadAndStartErr := n.loadAndStart(ctx, n.opts.ForceNewCluster)
+ if loadAndStartErr != nil && loadAndStartErr != storage.ErrNoWAL {
+ return loadAndStartErr
+ }
+
+ snapshot, err := n.raftStore.Snapshot()
+ // Snapshot never returns an error
+ if err != nil {
+ panic("could not get snapshot of raft store")
+ }
+
+ n.confState = snapshot.Metadata.ConfState
+ n.appliedIndex = snapshot.Metadata.Index
+ n.snapshotMeta = snapshot.Metadata
+ n.writtenWALIndex, _ = n.raftStore.LastIndex() // lastIndex always returns nil as an error
+
+ n.addrLock.Lock()
+ defer n.addrLock.Unlock()
+
+ // override the module field entirely, since etcd/raft is not exactly a submodule
+ n.Config.Logger = log.G(ctx).WithField("module", "raft")
+
+ // restore from snapshot
+ if loadAndStartErr == nil {
+ if n.opts.JoinAddr != "" {
+ log.G(ctx).Warning("ignoring request to join cluster, because raft state already exists")
+ }
+ n.campaignWhenAble = true
+ n.initTransport()
+ n.raftNode = raft.RestartNode(n.Config)
+ return nil
+ }
+
+ // first member of cluster
+ if n.opts.JoinAddr == "" {
+ // First member in the cluster, self-assign ID
+ n.Config.ID = uint64(rand.Int63()) + 1
+ peer, err := n.newRaftLogs(n.opts.ID)
+ if err != nil {
+ return err
+ }
+ n.campaignWhenAble = true
+ n.initTransport()
+ n.raftNode = raft.StartNode(n.Config, []raft.Peer{peer})
+ return nil
+ }
+
+ // join to existing cluster
+ if n.opts.Addr == "" {
+ return errors.New("attempted to join raft cluster without knowing own address")
+ }
+
+ conn, err := dial(n.opts.JoinAddr, "tcp", n.opts.TLSCredentials, 10*time.Second)
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+ client := api.NewRaftMembershipClient(conn)
+
+ joinCtx, joinCancel := context.WithTimeout(ctx, n.reqTimeout())
+ defer joinCancel()
+ resp, err := client.Join(joinCtx, &api.JoinRequest{
+ Addr: n.opts.Addr,
+ })
+ if err != nil {
+ return err
+ }
+
+ n.Config.ID = resp.RaftID
+
+ if _, err := n.newRaftLogs(n.opts.ID); err != nil {
+ return err
+ }
+ n.bootstrapMembers = resp.Members
+
+ n.initTransport()
+ n.raftNode = raft.StartNode(n.Config, nil)
+
+ return nil
+}
+
+// DefaultNodeConfig returns the default config for a
+// raft node that can be modified and customized
+func DefaultNodeConfig() *raft.Config {
+ return &raft.Config{
+ HeartbeatTick: 1,
+ ElectionTick: 3,
+ MaxSizePerMsg: math.MaxUint16,
+ MaxInflightMsgs: 256,
+ Logger: log.L,
+ CheckQuorum: true,
+ }
+}
+
+// DefaultRaftConfig returns a default api.RaftConfig.
+func DefaultRaftConfig() api.RaftConfig {
+ return api.RaftConfig{
+ KeepOldSnapshots: 0,
+ SnapshotInterval: 10000,
+ LogEntriesForSlowFollowers: 500,
+ ElectionTick: 3,
+ HeartbeatTick: 1,
+ }
+}
+
+// MemoryStore returns the memory store that is kept in sync with the raft log.
+func (n *Node) MemoryStore() *store.MemoryStore {
+ return n.memoryStore
+}
+
+func (n *Node) done() {
+ n.cluster.Clear()
+
+ n.ticker.Stop()
+ n.leadershipBroadcast.Close()
+ n.cluster.PeersBroadcast.Close()
+ n.memoryStore.Close()
+ if n.transport != nil {
+ n.transport.Stop()
+ }
+
+ close(n.doneCh)
+}
+
+// ClearData tells the raft node to delete its WALs, snapshots, and keys on
+// shutdown.
+func (n *Node) ClearData() {
+ n.clearData = true
+}
+
+// Run is the main loop for a Raft node, it goes along the state machine,
+// acting on the messages received from other Raft nodes in the cluster.
+//
+// Before running the main loop, it first starts the raft node based on saved
+// cluster state. If no saved state exists, it starts a single-node cluster.
+func (n *Node) Run(ctx context.Context) error {
+ ctx = log.WithLogger(ctx, logrus.WithField("raft_id", fmt.Sprintf("%x", n.Config.ID)))
+ ctx, cancel := context.WithCancel(ctx)
+
+ for _, node := range n.bootstrapMembers {
+ if err := n.registerNode(node); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to register member %x", node.RaftID)
+ }
+ }
+
+ defer func() {
+ cancel()
+ n.stop(ctx)
+ if n.clearData {
+ // Delete WAL and snapshots, since they are no longer
+ // usable.
+ if err := n.raftLogger.Clear(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("failed to move wal after node removal")
+ }
+ // clear out the DEKs
+ if err := n.keyRotator.UpdateKeys(EncryptionKeys{}); err != nil {
+ log.G(ctx).WithError(err).Error("could not remove DEKs")
+ }
+ }
+ n.done()
+ }()
+
+ wasLeader := false
+ transferLeadershipLimit := rate.NewLimiter(rate.Every(time.Minute), 1)
+
+ for {
+ select {
+ case <-n.ticker.C():
+ n.raftNode.Tick()
+
+ if n.leader() == raft.None {
+ atomic.AddUint32(&n.ticksWithNoLeader, 1)
+ } else {
+ atomic.StoreUint32(&n.ticksWithNoLeader, 0)
+ }
+ case rd := <-n.raftNode.Ready():
+ raftConfig := n.getCurrentRaftConfig()
+
+ // Save entries to storage
+ if err := n.saveToStorage(ctx, &raftConfig, rd.HardState, rd.Entries, rd.Snapshot); err != nil {
+ return errors.Wrap(err, "failed to save entries to storage")
+ }
+
+ if wasLeader &&
+ (rd.SoftState == nil || rd.SoftState.RaftState == raft.StateLeader) &&
+ n.memoryStore.Wedged() &&
+ transferLeadershipLimit.Allow() {
+ if !n.opts.DisableStackDump {
+ signal.DumpStacks("")
+ }
+ transferee, err := n.transport.LongestActive()
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed to get longest-active member")
+ } else {
+ log.G(ctx).Error("data store lock held too long - transferring leadership")
+ n.raftNode.TransferLeadership(ctx, n.Config.ID, transferee)
+ }
+ }
+
+ for _, msg := range rd.Messages {
+ // Send raft messages to peers
+ if err := n.transport.Send(msg); err != nil {
+ log.G(ctx).WithError(err).Error("failed to send message to member")
+ }
+ }
+
+ // Apply snapshot to memory store. The snapshot
+ // was applied to the raft store in
+ // saveToStorage.
+ if !raft.IsEmptySnap(rd.Snapshot) {
+ // Load the snapshot data into the store
+ if err := n.restoreFromSnapshot(ctx, rd.Snapshot.Data); err != nil {
+ log.G(ctx).WithError(err).Error("failed to restore cluster from snapshot")
+ }
+ n.appliedIndex = rd.Snapshot.Metadata.Index
+ n.snapshotMeta = rd.Snapshot.Metadata
+ n.confState = rd.Snapshot.Metadata.ConfState
+ }
+
+ // If we cease to be the leader, we must cancel any
+ // proposals that are currently waiting for a quorum to
+ // acknowledge them. It is still possible for these to
+ // become committed, but if that happens we will apply
+ // them as any follower would.
+
+ // It is important that we cancel these proposals before
+ // calling processCommitted, so processCommitted does
+ // not deadlock.
+
+ if rd.SoftState != nil {
+ if wasLeader && rd.SoftState.RaftState != raft.StateLeader {
+ wasLeader = false
+ if atomic.LoadUint32(&n.signalledLeadership) == 1 {
+ atomic.StoreUint32(&n.signalledLeadership, 0)
+ n.leadershipBroadcast.Publish(IsFollower)
+ }
+
+ // It is important that we set n.signalledLeadership to 0
+ // before calling n.wait.cancelAll. When a new raft
+ // request is registered, it checks n.signalledLeadership
+ // afterwards, and cancels the registration if it is 0.
+ // If cancelAll was called first, this call might run
+ // before the new request registers, but
+ // signalledLeadership would be set after the check.
+ // Setting signalledLeadership before calling cancelAll
+ // ensures that if a new request is registered during
+ // this transition, it will either be cancelled by
+ // cancelAll, or by its own check of signalledLeadership.
+ n.wait.cancelAll()
+ } else if !wasLeader && rd.SoftState.RaftState == raft.StateLeader {
+ wasLeader = true
+ }
+ }
+
+ // Process committed entries
+ for _, entry := range rd.CommittedEntries {
+ if err := n.processCommitted(ctx, entry); err != nil {
+ log.G(ctx).WithError(err).Error("failed to process committed entries")
+ }
+ }
+
+ // in case the previous attempt to update the key failed
+ n.maybeMarkRotationFinished(ctx)
+
+ // Trigger a snapshot every once in awhile
+ if n.snapshotInProgress == nil &&
+ (n.needsSnapshot(ctx) || raftConfig.SnapshotInterval > 0 &&
+ n.appliedIndex-n.snapshotMeta.Index >= raftConfig.SnapshotInterval) {
+ n.doSnapshot(ctx, raftConfig)
+ }
+
+ if wasLeader && atomic.LoadUint32(&n.signalledLeadership) != 1 {
+ // If all the entries in the log have become
+ // committed, broadcast our leadership status.
+ if n.caughtUp() {
+ atomic.StoreUint32(&n.signalledLeadership, 1)
+ n.leadershipBroadcast.Publish(IsLeader)
+ }
+ }
+
+ // Advance the state machine
+ n.raftNode.Advance()
+
+ // On the first startup, or if we are the only
+ // registered member after restoring from the state,
+ // campaign to be the leader.
+ if n.campaignWhenAble {
+ members := n.cluster.Members()
+ if len(members) >= 1 {
+ n.campaignWhenAble = false
+ }
+ if len(members) == 1 && members[n.Config.ID] != nil {
+ n.raftNode.Campaign(ctx)
+ }
+ }
+
+ case snapshotMeta := <-n.snapshotInProgress:
+ raftConfig := n.getCurrentRaftConfig()
+ if snapshotMeta.Index > n.snapshotMeta.Index {
+ n.snapshotMeta = snapshotMeta
+ if err := n.raftLogger.GC(snapshotMeta.Index, snapshotMeta.Term, raftConfig.KeepOldSnapshots); err != nil {
+ log.G(ctx).WithError(err).Error("failed to clean up old snapshots and WALs")
+ }
+ }
+ n.snapshotInProgress = nil
+ n.maybeMarkRotationFinished(ctx)
+ if n.rotationQueued && n.needsSnapshot(ctx) {
+ // there was a key rotation that took place before while the snapshot
+ // was in progress - we have to take another snapshot and encrypt with the new key
+ n.rotationQueued = false
+ n.doSnapshot(ctx, raftConfig)
+ }
+ case <-n.keyRotator.RotationNotify():
+ // There are 2 separate checks: rotationQueued, and n.needsSnapshot().
+ // We set rotationQueued so that when we are notified of a rotation, we try to
+ // do a snapshot as soon as possible. However, if there is an error while doing
+ // the snapshot, we don't want to hammer the node attempting to do snapshots over
+ // and over. So if doing a snapshot fails, wait until the next entry comes in to
+ // try again.
+ switch {
+ case n.snapshotInProgress != nil:
+ n.rotationQueued = true
+ case n.needsSnapshot(ctx):
+ n.doSnapshot(ctx, n.getCurrentRaftConfig())
+ }
+ case <-ctx.Done():
+ return nil
+ }
+ }
+}
+
+func (n *Node) restoreFromSnapshot(ctx context.Context, data []byte) error {
+ snapCluster, err := n.clusterSnapshot(data)
+ if err != nil {
+ return err
+ }
+
+ oldMembers := n.cluster.Members()
+
+ for _, member := range snapCluster.Members {
+ delete(oldMembers, member.RaftID)
+ }
+
+ for _, removedMember := range snapCluster.Removed {
+ n.cluster.RemoveMember(removedMember)
+ n.transport.RemovePeer(removedMember)
+ delete(oldMembers, removedMember)
+ }
+
+ for id, member := range oldMembers {
+ n.cluster.ClearMember(id)
+ if err := n.transport.RemovePeer(member.RaftID); err != nil {
+ log.G(ctx).WithError(err).Errorf("failed to remove peer %x from transport", member.RaftID)
+ }
+ }
+ for _, node := range snapCluster.Members {
+ if err := n.registerNode(&api.RaftMember{RaftID: node.RaftID, NodeID: node.NodeID, Addr: node.Addr}); err != nil {
+ log.G(ctx).WithError(err).Error("failed to register node from snapshot")
+ }
+ }
+ return nil
+}
+
+func (n *Node) needsSnapshot(ctx context.Context) bool {
+ if n.waitForAppliedIndex == 0 && n.keyRotator.NeedsRotation() {
+ keys := n.keyRotator.GetKeys()
+ if keys.PendingDEK != nil {
+ n.raftLogger.RotateEncryptionKey(keys.PendingDEK)
+ // we want to wait for the last index written with the old DEK to be committed, else a snapshot taken
+ // may have an index less than the index of a WAL written with an old DEK. We want the next snapshot
+ // written with the new key to supercede any WAL written with an old DEK.
+ n.waitForAppliedIndex = n.writtenWALIndex
+ // if there is already a snapshot at this index or higher, bump the wait index up to 1 higher than the current
+ // snapshot index, because the rotation cannot be completed until the next snapshot
+ if n.waitForAppliedIndex <= n.snapshotMeta.Index {
+ n.waitForAppliedIndex = n.snapshotMeta.Index + 1
+ }
+ log.G(ctx).Debugf(
+ "beginning raft DEK rotation - last indices written with the old key are (snapshot: %d, WAL: %d) - waiting for snapshot of index %d to be written before rotation can be completed", n.snapshotMeta.Index, n.writtenWALIndex, n.waitForAppliedIndex)
+ }
+ }
+
+ result := n.waitForAppliedIndex > 0 && n.waitForAppliedIndex <= n.appliedIndex
+ if result {
+ log.G(ctx).Debugf(
+ "a snapshot at index %d is needed in order to complete raft DEK rotation - a snapshot with index >= %d can now be triggered",
+ n.waitForAppliedIndex, n.appliedIndex)
+ }
+ return result
+}
+
+func (n *Node) maybeMarkRotationFinished(ctx context.Context) {
+ if n.waitForAppliedIndex > 0 && n.waitForAppliedIndex <= n.snapshotMeta.Index {
+ // this means we tried to rotate - so finish the rotation
+ if err := n.keyRotator.UpdateKeys(EncryptionKeys{CurrentDEK: n.raftLogger.EncryptionKey}); err != nil {
+ log.G(ctx).WithError(err).Error("failed to update encryption keys after a successful rotation")
+ } else {
+ log.G(ctx).Debugf(
+ "a snapshot with index %d is available, which completes the DEK rotation requiring a snapshot of at least index %d - throwing away DEK and older snapshots encrypted with the old key",
+ n.snapshotMeta.Index, n.waitForAppliedIndex)
+ n.waitForAppliedIndex = 0
+
+ if err := n.raftLogger.GC(n.snapshotMeta.Index, n.snapshotMeta.Term, 0); err != nil {
+ log.G(ctx).WithError(err).Error("failed to remove old snapshots and WALs that were written with the previous raft DEK")
+ }
+ }
+ }
+}
+
+func (n *Node) getCurrentRaftConfig() api.RaftConfig {
+ raftConfig := DefaultRaftConfig()
+ n.memoryStore.View(func(readTx store.ReadTx) {
+ clusters, err := store.FindClusters(readTx, store.ByName(store.DefaultClusterName))
+ if err == nil && len(clusters) == 1 {
+ raftConfig = clusters[0].Spec.Raft
+ }
+ })
+ return raftConfig
+}
+
+// Cancel interrupts all ongoing proposals, and prevents new ones from
+// starting. This is useful for the shutdown sequence because it allows
+// the manager to shut down raft-dependent services that might otherwise
+// block on shutdown if quorum isn't met. Then the raft node can be completely
+// shut down once no more code is using it.
+func (n *Node) Cancel() {
+ n.cancelFunc()
+}
+
+// Done returns channel which is closed when raft node is fully stopped.
+func (n *Node) Done() <-chan struct{} {
+ return n.doneCh
+}
+
+func (n *Node) stop(ctx context.Context) {
+ n.stopMu.Lock()
+ defer n.stopMu.Unlock()
+
+ n.Cancel()
+ n.waitProp.Wait()
+ n.asyncTasks.Wait()
+
+ n.raftNode.Stop()
+ n.ticker.Stop()
+ n.raftLogger.Close(ctx)
+ atomic.StoreUint32(&n.isMember, 0)
+ // TODO(stevvooe): Handle ctx.Done()
+}
+
+// isLeader checks if we are the leader or not, without the protection of lock
+func (n *Node) isLeader() bool {
+ if !n.IsMember() {
+ return false
+ }
+
+ if n.Status().Lead == n.Config.ID {
+ return true
+ }
+ return false
+}
+
+// IsLeader checks if we are the leader or not, with the protection of lock
+func (n *Node) IsLeader() bool {
+ n.stopMu.RLock()
+ defer n.stopMu.RUnlock()
+
+ return n.isLeader()
+}
+
+// leader returns the id of the leader, without the protection of lock and
+// membership check, so it's caller task.
+func (n *Node) leader() uint64 {
+ return n.Status().Lead
+}
+
+// Leader returns the id of the leader, with the protection of lock
+func (n *Node) Leader() (uint64, error) {
+ n.stopMu.RLock()
+ defer n.stopMu.RUnlock()
+
+ if !n.IsMember() {
+ return raft.None, ErrNoRaftMember
+ }
+ leader := n.leader()
+ if leader == raft.None {
+ return raft.None, ErrNoClusterLeader
+ }
+
+ return leader, nil
+}
+
+// ReadyForProposals returns true if the node has broadcasted a message
+// saying that it has become the leader. This means it is ready to accept
+// proposals.
+func (n *Node) ReadyForProposals() bool {
+ return atomic.LoadUint32(&n.signalledLeadership) == 1
+}
+
+func (n *Node) caughtUp() bool {
+ // obnoxious function that always returns a nil error
+ lastIndex, _ := n.raftStore.LastIndex()
+ return n.appliedIndex >= lastIndex
+}
+
+// Join asks to a member of the raft to propose
+// a configuration change and add us as a member thus
+// beginning the log replication process. This method
+// is called from an aspiring member to an existing member
+func (n *Node) Join(ctx context.Context, req *api.JoinRequest) (*api.JoinResponse, error) {
+ nodeInfo, err := ca.RemoteNode(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ fields := logrus.Fields{
+ "node.id": nodeInfo.NodeID,
+ "method": "(*Node).Join",
+ "raft_id": fmt.Sprintf("%x", n.Config.ID),
+ }
+ if nodeInfo.ForwardedBy != nil {
+ fields["forwarder.id"] = nodeInfo.ForwardedBy.NodeID
+ }
+ log := log.G(ctx).WithFields(fields)
+ log.Debug("")
+
+ // can't stop the raft node while an async RPC is in progress
+ n.stopMu.RLock()
+ defer n.stopMu.RUnlock()
+
+ n.membershipLock.Lock()
+ defer n.membershipLock.Unlock()
+
+ if !n.IsMember() {
+ return nil, grpc.Errorf(codes.FailedPrecondition, "%s", ErrNoRaftMember.Error())
+ }
+
+ if !n.isLeader() {
+ return nil, grpc.Errorf(codes.FailedPrecondition, "%s", ErrLostLeadership.Error())
+ }
+
+ // A single manager must not be able to join the raft cluster twice. If
+ // it did, that would cause the quorum to be computed incorrectly. This
+ // could happen if the WAL was deleted from an active manager.
+ for _, m := range n.cluster.Members() {
+ if m.NodeID == nodeInfo.NodeID {
+ return nil, grpc.Errorf(codes.AlreadyExists, "%s", "a raft member with this node ID already exists")
+ }
+ }
+
+ // Find a unique ID for the joining member.
+ var raftID uint64
+ for {
+ raftID = uint64(rand.Int63()) + 1
+ if n.cluster.GetMember(raftID) == nil && !n.cluster.IsIDRemoved(raftID) {
+ break
+ }
+ }
+
+ remoteAddr := req.Addr
+
+ // If the joining node sent an address like 0.0.0.0:4242, automatically
+ // determine its actual address based on the GRPC connection. This
+ // avoids the need for a prospective member to know its own address.
+
+ requestHost, requestPort, err := net.SplitHostPort(remoteAddr)
+ if err != nil {
+ return nil, grpc.Errorf(codes.InvalidArgument, "invalid address %s in raft join request", remoteAddr)
+ }
+
+ requestIP := net.ParseIP(requestHost)
+ if requestIP != nil && requestIP.IsUnspecified() {
+ remoteHost, _, err := net.SplitHostPort(nodeInfo.RemoteAddr)
+ if err != nil {
+ return nil, err
+ }
+ remoteAddr = net.JoinHostPort(remoteHost, requestPort)
+ }
+
+ // We do not bother submitting a configuration change for the
+ // new member if we can't contact it back using its address
+ if err := n.checkHealth(ctx, remoteAddr, 5*time.Second); err != nil {
+ return nil, err
+ }
+
+ err = n.addMember(ctx, remoteAddr, raftID, nodeInfo.NodeID)
+ if err != nil {
+ log.WithError(err).Errorf("failed to add member %x", raftID)
+ return nil, err
+ }
+
+ var nodes []*api.RaftMember
+ for _, node := range n.cluster.Members() {
+ nodes = append(nodes, &api.RaftMember{
+ RaftID: node.RaftID,
+ NodeID: node.NodeID,
+ Addr: node.Addr,
+ })
+ }
+ log.Debugf("node joined")
+
+ return &api.JoinResponse{Members: nodes, RaftID: raftID}, nil
+}
+
+// checkHealth tries to contact an aspiring member through its advertised address
+// and checks if its raft server is running.
+func (n *Node) checkHealth(ctx context.Context, addr string, timeout time.Duration) error {
+ conn, err := dial(addr, "tcp", n.opts.TLSCredentials, timeout)
+ if err != nil {
+ return err
+ }
+
+ defer conn.Close()
+
+ if timeout != 0 {
+ tctx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ ctx = tctx
+ }
+
+ healthClient := api.NewHealthClient(conn)
+ resp, err := healthClient.Check(ctx, &api.HealthCheckRequest{Service: "Raft"})
+ if err != nil {
+ return errors.Wrap(err, "could not connect to prospective new cluster member using its advertised address")
+ }
+ if resp.Status != api.HealthCheckResponse_SERVING {
+ return fmt.Errorf("health check returned status %s", resp.Status.String())
+ }
+
+ return nil
+}
+
+// addMember submits a configuration change to add a new member on the raft cluster.
+func (n *Node) addMember(ctx context.Context, addr string, raftID uint64, nodeID string) error {
+ node := api.RaftMember{
+ RaftID: raftID,
+ NodeID: nodeID,
+ Addr: addr,
+ }
+
+ meta, err := node.Marshal()
+ if err != nil {
+ return err
+ }
+
+ cc := raftpb.ConfChange{
+ Type: raftpb.ConfChangeAddNode,
+ NodeID: raftID,
+ Context: meta,
+ }
+
+ // Wait for a raft round to process the configuration change
+ return n.configure(ctx, cc)
+}
+
+// updateNodeBlocking runs synchronous job to update node address in whole cluster.
+func (n *Node) updateNodeBlocking(ctx context.Context, id uint64, addr string) error {
+ m := n.cluster.GetMember(id)
+ if m == nil {
+ return errors.Errorf("member %x is not found for update", id)
+ }
+ node := api.RaftMember{
+ RaftID: m.RaftID,
+ NodeID: m.NodeID,
+ Addr: addr,
+ }
+
+ meta, err := node.Marshal()
+ if err != nil {
+ return err
+ }
+
+ cc := raftpb.ConfChange{
+ Type: raftpb.ConfChangeUpdateNode,
+ NodeID: id,
+ Context: meta,
+ }
+
+ // Wait for a raft round to process the configuration change
+ return n.configure(ctx, cc)
+}
+
+// UpdateNode submits a configuration change to change a member's address.
+func (n *Node) UpdateNode(id uint64, addr string) {
+ ctx, cancel := n.WithContext(context.Background())
+ defer cancel()
+ // spawn updating info in raft in background to unblock transport
+ go func() {
+ if err := n.updateNodeBlocking(ctx, id, addr); err != nil {
+ log.G(ctx).WithFields(logrus.Fields{"raft_id": n.Config.ID, "update_id": id}).WithError(err).Error("failed to update member address in cluster")
+ }
+ }()
+}
+
+// Leave asks to a member of the raft to remove
+// us from the raft cluster. This method is called
+// from a member who is willing to leave its raft
+// membership to an active member of the raft
+func (n *Node) Leave(ctx context.Context, req *api.LeaveRequest) (*api.LeaveResponse, error) {
+ if req.Node == nil {
+ return nil, grpc.Errorf(codes.InvalidArgument, "no node information provided")
+ }
+
+ nodeInfo, err := ca.RemoteNode(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ ctx, cancel := n.WithContext(ctx)
+ defer cancel()
+
+ fields := logrus.Fields{
+ "node.id": nodeInfo.NodeID,
+ "method": "(*Node).Leave",
+ "raft_id": fmt.Sprintf("%x", n.Config.ID),
+ }
+ if nodeInfo.ForwardedBy != nil {
+ fields["forwarder.id"] = nodeInfo.ForwardedBy.NodeID
+ }
+ log.G(ctx).WithFields(fields).Debug("")
+
+ if err := n.removeMember(ctx, req.Node.RaftID); err != nil {
+ return nil, err
+ }
+
+ return &api.LeaveResponse{}, nil
+}
+
+// CanRemoveMember checks if a member can be removed from
+// the context of the current node.
+func (n *Node) CanRemoveMember(id uint64) bool {
+ members := n.cluster.Members()
+ nreachable := 0 // reachable managers after removal
+
+ for _, m := range members {
+ if m.RaftID == id {
+ continue
+ }
+
+ // Local node from where the remove is issued
+ if m.RaftID == n.Config.ID {
+ nreachable++
+ continue
+ }
+
+ if n.transport.Active(m.RaftID) {
+ nreachable++
+ }
+ }
+
+ nquorum := (len(members)-1)/2 + 1
+ if nreachable < nquorum {
+ return false
+ }
+
+ return true
+}
+
+func (n *Node) removeMember(ctx context.Context, id uint64) error {
+ // can't stop the raft node while an async RPC is in progress
+ n.stopMu.RLock()
+ defer n.stopMu.RUnlock()
+
+ if !n.IsMember() {
+ return ErrNoRaftMember
+ }
+
+ if !n.isLeader() {
+ return ErrLostLeadership
+ }
+
+ n.membershipLock.Lock()
+ defer n.membershipLock.Unlock()
+ if !n.CanRemoveMember(id) {
+ return ErrCannotRemoveMember
+ }
+
+ cc := raftpb.ConfChange{
+ ID: id,
+ Type: raftpb.ConfChangeRemoveNode,
+ NodeID: id,
+ Context: []byte(""),
+ }
+ return n.configure(ctx, cc)
+}
+
+// TransferLeadership attempts to transfer leadership to a different node,
+// and wait for the transfer to happen.
+func (n *Node) TransferLeadership(ctx context.Context) error {
+ ctx, cancelTransfer := context.WithTimeout(ctx, n.reqTimeout())
+ defer cancelTransfer()
+
+ n.stopMu.RLock()
+ defer n.stopMu.RUnlock()
+
+ if !n.IsMember() {
+ return ErrNoRaftMember
+ }
+
+ if !n.isLeader() {
+ return ErrLostLeadership
+ }
+
+ transferee, err := n.transport.LongestActive()
+ if err != nil {
+ return errors.Wrap(err, "failed to get longest-active member")
+ }
+ start := time.Now()
+ n.raftNode.TransferLeadership(ctx, n.Config.ID, transferee)
+ ticker := time.NewTicker(n.opts.TickInterval / 10)
+ defer ticker.Stop()
+ var leader uint64
+ for {
+ leader = n.leader()
+ if leader != raft.None && leader != n.Config.ID {
+ break
+ }
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-ticker.C:
+ }
+ }
+ log.G(ctx).Infof("raft: transfer leadership %x -> %x finished in %v", n.Config.ID, leader, time.Since(start))
+ return nil
+}
+
+// RemoveMember submits a configuration change to remove a member from the raft cluster
+// after checking if the operation would not result in a loss of quorum.
+func (n *Node) RemoveMember(ctx context.Context, id uint64) error {
+ ctx, cancel := n.WithContext(ctx)
+ defer cancel()
+ return n.removeMember(ctx, id)
+}
+
+// processRaftMessageLogger is used to lazily create a logger for
+// ProcessRaftMessage. Usually nothing will be logged, so it is useful to avoid
+// formatting strings and allocating a logger when it won't be used.
+func (n *Node) processRaftMessageLogger(ctx context.Context, msg *api.ProcessRaftMessageRequest) *logrus.Entry {
+ fields := logrus.Fields{
+ "method": "(*Node).ProcessRaftMessage",
+ }
+
+ if n.IsMember() {
+ fields["raft_id"] = fmt.Sprintf("%x", n.Config.ID)
+ }
+
+ if msg != nil && msg.Message != nil {
+ fields["from"] = fmt.Sprintf("%x", msg.Message.From)
+ }
+
+ return log.G(ctx).WithFields(fields)
+}
+
+func (n *Node) reportNewAddress(ctx context.Context, id uint64) error {
+ // too early
+ if !n.IsMember() {
+ return nil
+ }
+ p, ok := peer.FromContext(ctx)
+ if !ok {
+ return nil
+ }
+ oldAddr, err := n.transport.PeerAddr(id)
+ if err != nil {
+ return err
+ }
+ if oldAddr == "" {
+ // Don't know the address of the peer yet, so can't report an
+ // update.
+ return nil
+ }
+ newHost, _, err := net.SplitHostPort(p.Addr.String())
+ if err != nil {
+ return err
+ }
+ _, officialPort, err := net.SplitHostPort(oldAddr)
+ if err != nil {
+ return err
+ }
+ newAddr := net.JoinHostPort(newHost, officialPort)
+ if err := n.transport.UpdatePeerAddr(id, newAddr); err != nil {
+ return err
+ }
+ return nil
+}
+
+// ProcessRaftMessage calls 'Step' which advances the
+// raft state machine with the provided message on the
+// receiving node
+func (n *Node) ProcessRaftMessage(ctx context.Context, msg *api.ProcessRaftMessageRequest) (*api.ProcessRaftMessageResponse, error) {
+ if msg == nil || msg.Message == nil {
+ n.processRaftMessageLogger(ctx, msg).Debug("received empty message")
+ return &api.ProcessRaftMessageResponse{}, nil
+ }
+
+ // Don't process the message if this comes from
+ // a node in the remove set
+ if n.cluster.IsIDRemoved(msg.Message.From) {
+ n.processRaftMessageLogger(ctx, msg).Debug("received message from removed member")
+ return nil, grpc.Errorf(codes.NotFound, "%s", membership.ErrMemberRemoved.Error())
+ }
+
+ ctx, cancel := n.WithContext(ctx)
+ defer cancel()
+
+ // TODO(aaronl): Address changes are temporarily disabled.
+ // See https://github.com/docker/docker/issues/30455.
+ // This should be reenabled in the future with additional
+ // safeguards (perhaps storing multiple addresses per node).
+ //if err := n.reportNewAddress(ctx, msg.Message.From); err != nil {
+ // log.G(ctx).WithError(err).Errorf("failed to report new address of %x to transport", msg.Message.From)
+ //}
+
+ // Reject vote requests from unreachable peers
+ if msg.Message.Type == raftpb.MsgVote {
+ member := n.cluster.GetMember(msg.Message.From)
+ if member == nil {
+ n.processRaftMessageLogger(ctx, msg).Debug("received message from unknown member")
+ return &api.ProcessRaftMessageResponse{}, nil
+ }
+
+ if err := n.transport.HealthCheck(ctx, msg.Message.From); err != nil {
+ n.processRaftMessageLogger(ctx, msg).WithError(err).Debug("member which sent vote request failed health check")
+ return &api.ProcessRaftMessageResponse{}, nil
+ }
+ }
+
+ if msg.Message.Type == raftpb.MsgProp {
+ // We don't accept forwarded proposals. Our
+ // current architecture depends on only the leader
+ // making proposals, so in-flight proposals can be
+ // guaranteed not to conflict.
+ n.processRaftMessageLogger(ctx, msg).Debug("dropped forwarded proposal")
+ return &api.ProcessRaftMessageResponse{}, nil
+ }
+
+ // can't stop the raft node while an async RPC is in progress
+ n.stopMu.RLock()
+ defer n.stopMu.RUnlock()
+
+ if n.IsMember() {
+ if msg.Message.To != n.Config.ID {
+ n.processRaftMessageLogger(ctx, msg).Errorf("received message intended for raft_id %x", msg.Message.To)
+ return &api.ProcessRaftMessageResponse{}, nil
+ }
+
+ if err := n.raftNode.Step(ctx, *msg.Message); err != nil {
+ n.processRaftMessageLogger(ctx, msg).WithError(err).Debug("raft Step failed")
+ }
+ }
+
+ return &api.ProcessRaftMessageResponse{}, nil
+}
+
+// ResolveAddress returns the address reaching for a given node ID.
+func (n *Node) ResolveAddress(ctx context.Context, msg *api.ResolveAddressRequest) (*api.ResolveAddressResponse, error) {
+ if !n.IsMember() {
+ return nil, ErrNoRaftMember
+ }
+
+ nodeInfo, err := ca.RemoteNode(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ fields := logrus.Fields{
+ "node.id": nodeInfo.NodeID,
+ "method": "(*Node).ResolveAddress",
+ "raft_id": fmt.Sprintf("%x", n.Config.ID),
+ }
+ if nodeInfo.ForwardedBy != nil {
+ fields["forwarder.id"] = nodeInfo.ForwardedBy.NodeID
+ }
+ log.G(ctx).WithFields(fields).Debug("")
+
+ member := n.cluster.GetMember(msg.RaftID)
+ if member == nil {
+ return nil, grpc.Errorf(codes.NotFound, "member %x not found", msg.RaftID)
+ }
+ return &api.ResolveAddressResponse{Addr: member.Addr}, nil
+}
+
+func (n *Node) getLeaderConn() (*grpc.ClientConn, error) {
+ leader, err := n.Leader()
+ if err != nil {
+ return nil, err
+ }
+
+ if leader == n.Config.ID {
+ return nil, raftselector.ErrIsLeader
+ }
+ conn, err := n.transport.PeerConn(leader)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get connection to leader")
+ }
+ return conn, nil
+}
+
+// LeaderConn returns current connection to cluster leader or raftselector.ErrIsLeader
+// if current machine is leader.
+func (n *Node) LeaderConn(ctx context.Context) (*grpc.ClientConn, error) {
+ cc, err := n.getLeaderConn()
+ if err == nil {
+ return cc, nil
+ }
+ if err == raftselector.ErrIsLeader {
+ return nil, err
+ }
+ if atomic.LoadUint32(&n.ticksWithNoLeader) > lostQuorumTimeout {
+ return nil, errLostQuorum
+ }
+
+ ticker := time.NewTicker(1 * time.Second)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ cc, err := n.getLeaderConn()
+ if err == nil {
+ return cc, nil
+ }
+ if err == raftselector.ErrIsLeader {
+ return nil, err
+ }
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+// registerNode registers a new node on the cluster memberlist
+func (n *Node) registerNode(node *api.RaftMember) error {
+ if n.cluster.IsIDRemoved(node.RaftID) {
+ return nil
+ }
+
+ member := &membership.Member{}
+
+ existingMember := n.cluster.GetMember(node.RaftID)
+ if existingMember != nil {
+ // Member already exists
+
+ // If the address is different from what we thought it was,
+ // update it. This can happen if we just joined a cluster
+ // and are adding ourself now with the remotely-reachable
+ // address.
+ if existingMember.Addr != node.Addr {
+ if node.RaftID != n.Config.ID {
+ if err := n.transport.UpdatePeer(node.RaftID, node.Addr); err != nil {
+ return err
+ }
+ }
+ member.RaftMember = node
+ n.cluster.AddMember(member)
+ }
+
+ return nil
+ }
+
+ // Avoid opening a connection to the local node
+ if node.RaftID != n.Config.ID {
+ if err := n.transport.AddPeer(node.RaftID, node.Addr); err != nil {
+ return err
+ }
+ }
+
+ member.RaftMember = node
+ err := n.cluster.AddMember(member)
+ if err != nil {
+ if rerr := n.transport.RemovePeer(node.RaftID); rerr != nil {
+ return errors.Wrapf(rerr, "failed to remove peer after error %v", err)
+ }
+ return err
+ }
+
+ return nil
+}
+
+// ProposeValue calls Propose on the raft and waits
+// on the commit log action before returning a result
+func (n *Node) ProposeValue(ctx context.Context, storeAction []api.StoreAction, cb func()) error {
+ ctx, cancel := n.WithContext(ctx)
+ defer cancel()
+ _, err := n.processInternalRaftRequest(ctx, &api.InternalRaftRequest{Action: storeAction}, cb)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+// GetVersion returns the sequence information for the current raft round.
+func (n *Node) GetVersion() *api.Version {
+ n.stopMu.RLock()
+ defer n.stopMu.RUnlock()
+
+ if !n.IsMember() {
+ return nil
+ }
+
+ status := n.Status()
+ return &api.Version{Index: status.Commit}
+}
+
+// ChangesBetween returns the changes starting after "from", up to and
+// including "to". If these changes are not available because the log
+// has been compacted, an error will be returned.
+func (n *Node) ChangesBetween(from, to api.Version) ([]state.Change, error) {
+ n.stopMu.RLock()
+ defer n.stopMu.RUnlock()
+
+ if from.Index > to.Index {
+ return nil, errors.New("versions are out of order")
+ }
+
+ if !n.IsMember() {
+ return nil, ErrNoRaftMember
+ }
+
+ // never returns error
+ last, _ := n.raftStore.LastIndex()
+
+ if to.Index > last {
+ return nil, errors.New("last version is out of bounds")
+ }
+
+ pbs, err := n.raftStore.Entries(from.Index+1, to.Index+1, math.MaxUint64)
+ if err != nil {
+ return nil, err
+ }
+
+ var changes []state.Change
+ for _, pb := range pbs {
+ if pb.Type != raftpb.EntryNormal || pb.Data == nil {
+ continue
+ }
+ r := &api.InternalRaftRequest{}
+ err := proto.Unmarshal(pb.Data, r)
+ if err != nil {
+ return nil, errors.Wrap(err, "error umarshalling internal raft request")
+ }
+
+ if r.Action != nil {
+ changes = append(changes, state.Change{StoreActions: r.Action, Version: api.Version{Index: pb.Index}})
+ }
+ }
+
+ return changes, nil
+}
+
+// SubscribePeers subscribes to peer updates in cluster. It sends always full
+// list of peers.
+func (n *Node) SubscribePeers() (q chan events.Event, cancel func()) {
+ return n.cluster.PeersBroadcast.Watch()
+}
+
+// GetMemberlist returns the current list of raft members in the cluster.
+func (n *Node) GetMemberlist() map[uint64]*api.RaftMember {
+ memberlist := make(map[uint64]*api.RaftMember)
+ members := n.cluster.Members()
+ leaderID, err := n.Leader()
+ if err != nil {
+ leaderID = raft.None
+ }
+
+ for id, member := range members {
+ reachability := api.RaftMemberStatus_REACHABLE
+ leader := false
+
+ if member.RaftID != n.Config.ID {
+ if !n.transport.Active(member.RaftID) {
+ reachability = api.RaftMemberStatus_UNREACHABLE
+ }
+ }
+
+ if member.RaftID == leaderID {
+ leader = true
+ }
+
+ memberlist[id] = &api.RaftMember{
+ RaftID: member.RaftID,
+ NodeID: member.NodeID,
+ Addr: member.Addr,
+ Status: api.RaftMemberStatus{
+ Leader: leader,
+ Reachability: reachability,
+ },
+ }
+ }
+
+ return memberlist
+}
+
+// Status returns status of underlying etcd.Node.
+func (n *Node) Status() raft.Status {
+ return n.raftNode.Status()
+}
+
+// GetMemberByNodeID returns member information based
+// on its generic Node ID.
+func (n *Node) GetMemberByNodeID(nodeID string) *membership.Member {
+ members := n.cluster.Members()
+ for _, member := range members {
+ if member.NodeID == nodeID {
+ return member
+ }
+ }
+ return nil
+}
+
+// IsMember checks if the raft node has effectively joined
+// a cluster of existing members.
+func (n *Node) IsMember() bool {
+ return atomic.LoadUint32(&n.isMember) == 1
+}
+
+// Saves a log entry to our Store
+func (n *Node) saveToStorage(
+ ctx context.Context,
+ raftConfig *api.RaftConfig,
+ hardState raftpb.HardState,
+ entries []raftpb.Entry,
+ snapshot raftpb.Snapshot,
+) (err error) {
+
+ if !raft.IsEmptySnap(snapshot) {
+ if err := n.raftLogger.SaveSnapshot(snapshot); err != nil {
+ return errors.Wrap(err, "failed to save snapshot")
+ }
+ if err := n.raftLogger.GC(snapshot.Metadata.Index, snapshot.Metadata.Term, raftConfig.KeepOldSnapshots); err != nil {
+ log.G(ctx).WithError(err).Error("unable to clean old snapshots and WALs")
+ }
+ if err = n.raftStore.ApplySnapshot(snapshot); err != nil {
+ return errors.Wrap(err, "failed to apply snapshot on raft node")
+ }
+ }
+
+ if err := n.raftLogger.SaveEntries(hardState, entries); err != nil {
+ return errors.Wrap(err, "failed to save raft log entries")
+ }
+
+ if len(entries) > 0 {
+ lastIndex := entries[len(entries)-1].Index
+ if lastIndex > n.writtenWALIndex {
+ n.writtenWALIndex = lastIndex
+ }
+ }
+
+ if err = n.raftStore.Append(entries); err != nil {
+ return errors.Wrap(err, "failed to append raft log entries")
+ }
+
+ return nil
+}
+
+// processInternalRaftRequest sends a message to nodes participating
+// in the raft to apply a log entry and then waits for it to be applied
+// on the server. It will block until the update is performed, there is
+// an error or until the raft node finalizes all the proposals on node
+// shutdown.
+func (n *Node) processInternalRaftRequest(ctx context.Context, r *api.InternalRaftRequest, cb func()) (proto.Message, error) {
+ n.stopMu.RLock()
+ if !n.IsMember() {
+ n.stopMu.RUnlock()
+ return nil, ErrStopped
+ }
+ n.waitProp.Add(1)
+ defer n.waitProp.Done()
+ n.stopMu.RUnlock()
+
+ r.ID = n.reqIDGen.Next()
+
+ // This must be derived from the context which is cancelled by stop()
+ // to avoid a deadlock on shutdown.
+ waitCtx, cancel := context.WithCancel(ctx)
+
+ ch := n.wait.register(r.ID, cb, cancel)
+
+ // Do this check after calling register to avoid a race.
+ if atomic.LoadUint32(&n.signalledLeadership) != 1 {
+ n.wait.cancel(r.ID)
+ return nil, ErrLostLeadership
+ }
+
+ data, err := r.Marshal()
+ if err != nil {
+ n.wait.cancel(r.ID)
+ return nil, err
+ }
+
+ if len(data) > store.MaxTransactionBytes {
+ n.wait.cancel(r.ID)
+ return nil, ErrRequestTooLarge
+ }
+
+ err = n.raftNode.Propose(waitCtx, data)
+ if err != nil {
+ n.wait.cancel(r.ID)
+ return nil, err
+ }
+
+ select {
+ case x, ok := <-ch:
+ if !ok {
+ return nil, ErrLostLeadership
+ }
+ return x.(proto.Message), nil
+ case <-waitCtx.Done():
+ n.wait.cancel(r.ID)
+ // if channel is closed, wait item was canceled, otherwise it was triggered
+ x, ok := <-ch
+ if !ok {
+ return nil, ErrLostLeadership
+ }
+ return x.(proto.Message), nil
+ case <-ctx.Done():
+ n.wait.cancel(r.ID)
+ // if channel is closed, wait item was canceled, otherwise it was triggered
+ x, ok := <-ch
+ if !ok {
+ return nil, ctx.Err()
+ }
+ return x.(proto.Message), nil
+ }
+}
+
+// configure sends a configuration change through consensus and
+// then waits for it to be applied to the server. It will block
+// until the change is performed or there is an error.
+func (n *Node) configure(ctx context.Context, cc raftpb.ConfChange) error {
+ cc.ID = n.reqIDGen.Next()
+
+ ctx, cancel := context.WithCancel(ctx)
+ ch := n.wait.register(cc.ID, nil, cancel)
+
+ if err := n.raftNode.ProposeConfChange(ctx, cc); err != nil {
+ n.wait.cancel(cc.ID)
+ return err
+ }
+
+ select {
+ case x := <-ch:
+ if err, ok := x.(error); ok {
+ return err
+ }
+ if x != nil {
+ log.G(ctx).Panic("raft: configuration change error, return type should always be error")
+ }
+ return nil
+ case <-ctx.Done():
+ n.wait.cancel(cc.ID)
+ return ctx.Err()
+ }
+}
+
+func (n *Node) processCommitted(ctx context.Context, entry raftpb.Entry) error {
+ // Process a normal entry
+ if entry.Type == raftpb.EntryNormal && entry.Data != nil {
+ if err := n.processEntry(ctx, entry); err != nil {
+ return err
+ }
+ }
+
+ // Process a configuration change (add/remove node)
+ if entry.Type == raftpb.EntryConfChange {
+ n.processConfChange(ctx, entry)
+ }
+
+ n.appliedIndex = entry.Index
+ return nil
+}
+
+func (n *Node) processEntry(ctx context.Context, entry raftpb.Entry) error {
+ r := &api.InternalRaftRequest{}
+ err := proto.Unmarshal(entry.Data, r)
+ if err != nil {
+ return err
+ }
+
+ if !n.wait.trigger(r.ID, r) {
+ // There was no wait on this ID, meaning we don't have a
+ // transaction in progress that would be committed to the
+ // memory store by the "trigger" call. Either a different node
+ // wrote this to raft, or we wrote it before losing the leader
+ // position and cancelling the transaction. Create a new
+ // transaction to commit the data.
+
+ // It should not be possible for processInternalRaftRequest
+ // to be running in this situation, but out of caution we
+ // cancel any current invocations to avoid a deadlock.
+ n.wait.cancelAll()
+
+ err := n.memoryStore.ApplyStoreActions(r.Action)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed to apply actions from raft")
+ }
+ }
+ return nil
+}
+
+func (n *Node) processConfChange(ctx context.Context, entry raftpb.Entry) {
+ var (
+ err error
+ cc raftpb.ConfChange
+ )
+
+ if err := proto.Unmarshal(entry.Data, &cc); err != nil {
+ n.wait.trigger(cc.ID, err)
+ }
+
+ if err := n.cluster.ValidateConfigurationChange(cc); err != nil {
+ n.wait.trigger(cc.ID, err)
+ }
+
+ switch cc.Type {
+ case raftpb.ConfChangeAddNode:
+ err = n.applyAddNode(cc)
+ case raftpb.ConfChangeUpdateNode:
+ err = n.applyUpdateNode(ctx, cc)
+ case raftpb.ConfChangeRemoveNode:
+ err = n.applyRemoveNode(ctx, cc)
+ }
+
+ if err != nil {
+ n.wait.trigger(cc.ID, err)
+ }
+
+ n.confState = *n.raftNode.ApplyConfChange(cc)
+ n.wait.trigger(cc.ID, nil)
+}
+
+// applyAddNode is called when we receive a ConfChange
+// from a member in the raft cluster, this adds a new
+// node to the existing raft cluster
+func (n *Node) applyAddNode(cc raftpb.ConfChange) error {
+ member := &api.RaftMember{}
+ err := proto.Unmarshal(cc.Context, member)
+ if err != nil {
+ return err
+ }
+
+ // ID must be non zero
+ if member.RaftID == 0 {
+ return nil
+ }
+
+ if err = n.registerNode(member); err != nil {
+ return err
+ }
+ return nil
+}
+
+// applyUpdateNode is called when we receive a ConfChange from a member in the
+// raft cluster which update the address of an existing node.
+func (n *Node) applyUpdateNode(ctx context.Context, cc raftpb.ConfChange) error {
+ newMember := &api.RaftMember{}
+ err := proto.Unmarshal(cc.Context, newMember)
+ if err != nil {
+ return err
+ }
+
+ if newMember.RaftID == n.Config.ID {
+ return nil
+ }
+ if err := n.transport.UpdatePeer(newMember.RaftID, newMember.Addr); err != nil {
+ return err
+ }
+ return n.cluster.UpdateMember(newMember.RaftID, newMember)
+}
+
+// applyRemoveNode is called when we receive a ConfChange
+// from a member in the raft cluster, this removes a node
+// from the existing raft cluster
+func (n *Node) applyRemoveNode(ctx context.Context, cc raftpb.ConfChange) (err error) {
+ // If the node from where the remove is issued is
+ // a follower and the leader steps down, Campaign
+ // to be the leader.
+
+ if cc.NodeID == n.leader() && !n.isLeader() {
+ if err = n.raftNode.Campaign(ctx); err != nil {
+ return err
+ }
+ }
+
+ if cc.NodeID == n.Config.ID {
+ // wait for the commit ack to be sent before closing connection
+ n.asyncTasks.Wait()
+
+ n.NodeRemoved()
+ } else if err := n.transport.RemovePeer(cc.NodeID); err != nil {
+ return err
+ }
+
+ return n.cluster.RemoveMember(cc.NodeID)
+}
+
+// SubscribeLeadership returns channel to which events about leadership change
+// will be sent in form of raft.LeadershipState. Also cancel func is returned -
+// it should be called when listener is no longer interested in events.
+func (n *Node) SubscribeLeadership() (q chan events.Event, cancel func()) {
+ return n.leadershipBroadcast.Watch()
+}
+
+// createConfigChangeEnts creates a series of Raft entries (i.e.
+// EntryConfChange) to remove the set of given IDs from the cluster. The ID
+// `self` is _not_ removed, even if present in the set.
+// If `self` is not inside the given ids, it creates a Raft entry to add a
+// default member with the given `self`.
+func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
+ var ents []raftpb.Entry
+ next := index + 1
+ found := false
+ for _, id := range ids {
+ if id == self {
+ found = true
+ continue
+ }
+ cc := &raftpb.ConfChange{
+ Type: raftpb.ConfChangeRemoveNode,
+ NodeID: id,
+ }
+ data, err := cc.Marshal()
+ if err != nil {
+ log.L.WithError(err).Panic("marshal configuration change should never fail")
+ }
+ e := raftpb.Entry{
+ Type: raftpb.EntryConfChange,
+ Data: data,
+ Term: term,
+ Index: next,
+ }
+ ents = append(ents, e)
+ next++
+ }
+ if !found {
+ node := &api.RaftMember{RaftID: self}
+ meta, err := node.Marshal()
+ if err != nil {
+ log.L.WithError(err).Panic("marshal member should never fail")
+ }
+ cc := &raftpb.ConfChange{
+ Type: raftpb.ConfChangeAddNode,
+ NodeID: self,
+ Context: meta,
+ }
+ data, err := cc.Marshal()
+ if err != nil {
+ log.L.WithError(err).Panic("marshal configuration change should never fail")
+ }
+ e := raftpb.Entry{
+ Type: raftpb.EntryConfChange,
+ Data: data,
+ Term: term,
+ Index: next,
+ }
+ ents = append(ents, e)
+ }
+ return ents
+}
+
+// getIDs returns an ordered set of IDs included in the given snapshot and
+// the entries. The given snapshot/entries can contain two kinds of
+// ID-related entry:
+// - ConfChangeAddNode, in which case the contained ID will be added into the set.
+// - ConfChangeRemoveNode, in which case the contained ID will be removed from the set.
+func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
+ ids := make(map[uint64]struct{})
+ if snap != nil {
+ for _, id := range snap.Metadata.ConfState.Nodes {
+ ids[id] = struct{}{}
+ }
+ }
+ for _, e := range ents {
+ if e.Type != raftpb.EntryConfChange {
+ continue
+ }
+ if snap != nil && e.Index < snap.Metadata.Index {
+ continue
+ }
+ var cc raftpb.ConfChange
+ if err := cc.Unmarshal(e.Data); err != nil {
+ log.L.WithError(err).Panic("unmarshal configuration change should never fail")
+ }
+ switch cc.Type {
+ case raftpb.ConfChangeAddNode:
+ ids[cc.NodeID] = struct{}{}
+ case raftpb.ConfChangeRemoveNode:
+ delete(ids, cc.NodeID)
+ case raftpb.ConfChangeUpdateNode:
+ // do nothing
+ default:
+ log.L.Panic("ConfChange Type should be either ConfChangeAddNode, or ConfChangeRemoveNode, or ConfChangeUpdateNode!")
+ }
+ }
+ var sids []uint64
+ for id := range ids {
+ sids = append(sids, id)
+ }
+ return sids
+}
+
+func (n *Node) reqTimeout() time.Duration {
+ return 5*time.Second + 2*time.Duration(n.Config.ElectionTick)*n.opts.TickInterval
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/raft/storage.go b/vendor/github.com/docker/swarmkit/manager/state/raft/storage.go
new file mode 100644
index 0000000..d12c43a
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/raft/storage.go
@@ -0,0 +1,248 @@
+package raft
+
+import (
+ "fmt"
+
+ "github.com/coreos/etcd/raft"
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/encryption"
+ "github.com/docker/swarmkit/manager/state/raft/membership"
+ "github.com/docker/swarmkit/manager/state/raft/storage"
+ "github.com/docker/swarmkit/manager/state/store"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+func (n *Node) readFromDisk(ctx context.Context) (*raftpb.Snapshot, storage.WALData, error) {
+ keys := n.keyRotator.GetKeys()
+
+ n.raftLogger = &storage.EncryptedRaftLogger{
+ StateDir: n.opts.StateDir,
+ EncryptionKey: keys.CurrentDEK,
+ }
+ if keys.PendingDEK != nil {
+ n.raftLogger.EncryptionKey = keys.PendingDEK
+ }
+
+ snap, walData, err := n.raftLogger.BootstrapFromDisk(ctx)
+
+ if keys.PendingDEK != nil {
+ switch errors.Cause(err).(type) {
+ case nil:
+ if err = n.keyRotator.UpdateKeys(EncryptionKeys{CurrentDEK: keys.PendingDEK}); err != nil {
+ err = errors.Wrap(err, "previous key rotation was successful, but unable mark rotation as complete")
+ }
+ case encryption.ErrCannotDecrypt:
+ snap, walData, err = n.raftLogger.BootstrapFromDisk(ctx, keys.CurrentDEK)
+ }
+ }
+
+ if err != nil {
+ return nil, storage.WALData{}, err
+ }
+ return snap, walData, nil
+}
+
+// bootstraps a node's raft store from the raft logs and snapshots on disk
+func (n *Node) loadAndStart(ctx context.Context, forceNewCluster bool) error {
+ snapshot, waldata, err := n.readFromDisk(ctx)
+ if err != nil {
+ return err
+ }
+
+ // Read logs to fully catch up store
+ var raftNode api.RaftMember
+ if err := raftNode.Unmarshal(waldata.Metadata); err != nil {
+ return errors.Wrap(err, "failed to unmarshal WAL metadata")
+ }
+ n.Config.ID = raftNode.RaftID
+
+ if snapshot != nil {
+ snapCluster, err := n.clusterSnapshot(snapshot.Data)
+ if err != nil {
+ return err
+ }
+ var bootstrapMembers []*api.RaftMember
+ if forceNewCluster {
+ for _, m := range snapCluster.Members {
+ if m.RaftID != n.Config.ID {
+ n.cluster.RemoveMember(m.RaftID)
+ continue
+ }
+ bootstrapMembers = append(bootstrapMembers, m)
+ }
+ } else {
+ bootstrapMembers = snapCluster.Members
+ }
+ n.bootstrapMembers = bootstrapMembers
+ for _, removedMember := range snapCluster.Removed {
+ n.cluster.RemoveMember(removedMember)
+ }
+ }
+
+ ents, st := waldata.Entries, waldata.HardState
+
+ // All members that are no longer part of the cluster must be added to
+ // the removed list right away, so that we don't try to connect to them
+ // before processing the configuration change entries, which could make
+ // us get stuck.
+ for _, ent := range ents {
+ if ent.Index <= st.Commit && ent.Type == raftpb.EntryConfChange {
+ var cc raftpb.ConfChange
+ if err := cc.Unmarshal(ent.Data); err != nil {
+ return errors.Wrap(err, "failed to unmarshal config change")
+ }
+ if cc.Type == raftpb.ConfChangeRemoveNode {
+ n.cluster.RemoveMember(cc.NodeID)
+ }
+ }
+ }
+
+ if forceNewCluster {
+ // discard the previously uncommitted entries
+ for i, ent := range ents {
+ if ent.Index > st.Commit {
+ log.G(ctx).Infof("discarding %d uncommitted WAL entries", len(ents)-i)
+ ents = ents[:i]
+ break
+ }
+ }
+
+ // force append the configuration change entries
+ toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), n.Config.ID, st.Term, st.Commit)
+
+ // All members that are being removed as part of the
+ // force-new-cluster process must be added to the
+ // removed list right away, so that we don't try to
+ // connect to them before processing the configuration
+ // change entries, which could make us get stuck.
+ for _, ccEnt := range toAppEnts {
+ if ccEnt.Type == raftpb.EntryConfChange {
+ var cc raftpb.ConfChange
+ if err := cc.Unmarshal(ccEnt.Data); err != nil {
+ return errors.Wrap(err, "error unmarshalling force-new-cluster config change")
+ }
+ if cc.Type == raftpb.ConfChangeRemoveNode {
+ n.cluster.RemoveMember(cc.NodeID)
+ }
+ }
+ }
+ ents = append(ents, toAppEnts...)
+
+ // force commit newly appended entries
+ err := n.raftLogger.SaveEntries(st, toAppEnts)
+ if err != nil {
+ log.G(ctx).WithError(err).Fatal("failed to save WAL while forcing new cluster")
+ }
+ if len(toAppEnts) != 0 {
+ st.Commit = toAppEnts[len(toAppEnts)-1].Index
+ }
+ }
+
+ if snapshot != nil {
+ if err := n.raftStore.ApplySnapshot(*snapshot); err != nil {
+ return err
+ }
+ }
+ if err := n.raftStore.SetHardState(st); err != nil {
+ return err
+ }
+ return n.raftStore.Append(ents)
+}
+
+func (n *Node) newRaftLogs(nodeID string) (raft.Peer, error) {
+ raftNode := &api.RaftMember{
+ RaftID: n.Config.ID,
+ NodeID: nodeID,
+ Addr: n.opts.Addr,
+ }
+ metadata, err := raftNode.Marshal()
+ if err != nil {
+ return raft.Peer{}, errors.Wrap(err, "error marshalling raft node")
+ }
+ if err := n.raftLogger.BootstrapNew(metadata); err != nil {
+ return raft.Peer{}, err
+ }
+ n.cluster.AddMember(&membership.Member{RaftMember: raftNode})
+ return raft.Peer{ID: n.Config.ID, Context: metadata}, nil
+}
+
+func (n *Node) doSnapshot(ctx context.Context, raftConfig api.RaftConfig) {
+ snapshot := api.Snapshot{Version: api.Snapshot_V0}
+ for _, member := range n.cluster.Members() {
+ snapshot.Membership.Members = append(snapshot.Membership.Members,
+ &api.RaftMember{
+ NodeID: member.NodeID,
+ RaftID: member.RaftID,
+ Addr: member.Addr,
+ })
+ }
+ snapshot.Membership.Removed = n.cluster.Removed()
+
+ viewStarted := make(chan struct{})
+ n.asyncTasks.Add(1)
+ n.snapshotInProgress = make(chan raftpb.SnapshotMetadata, 1) // buffered in case Shutdown is called during the snapshot
+ go func(appliedIndex uint64, snapshotMeta raftpb.SnapshotMetadata) {
+ defer func() {
+ n.asyncTasks.Done()
+ n.snapshotInProgress <- snapshotMeta
+ }()
+ var err error
+ n.memoryStore.View(func(tx store.ReadTx) {
+ close(viewStarted)
+
+ var storeSnapshot *api.StoreSnapshot
+ storeSnapshot, err = n.memoryStore.Save(tx)
+ snapshot.Store = *storeSnapshot
+ })
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed to read snapshot from store")
+ return
+ }
+
+ d, err := snapshot.Marshal()
+ if err != nil {
+ log.G(ctx).WithError(err).Error("failed to marshal snapshot")
+ return
+ }
+ snap, err := n.raftStore.CreateSnapshot(appliedIndex, &n.confState, d)
+ if err == nil {
+ if err := n.raftLogger.SaveSnapshot(snap); err != nil {
+ log.G(ctx).WithError(err).Error("failed to save snapshot")
+ return
+ }
+ snapshotMeta = snap.Metadata
+
+ if appliedIndex > raftConfig.LogEntriesForSlowFollowers {
+ err := n.raftStore.Compact(appliedIndex - raftConfig.LogEntriesForSlowFollowers)
+ if err != nil && err != raft.ErrCompacted {
+ log.G(ctx).WithError(err).Error("failed to compact snapshot")
+ }
+ }
+ } else if err != raft.ErrSnapOutOfDate {
+ log.G(ctx).WithError(err).Error("failed to create snapshot")
+ }
+ }(n.appliedIndex, n.snapshotMeta)
+
+ // Wait for the goroutine to establish a read transaction, to make
+ // sure it sees the state as of this moment.
+ <-viewStarted
+}
+
+func (n *Node) clusterSnapshot(data []byte) (api.ClusterSnapshot, error) {
+ var snapshot api.Snapshot
+ if err := snapshot.Unmarshal(data); err != nil {
+ return snapshot.Membership, err
+ }
+ if snapshot.Version != api.Snapshot_V0 {
+ return snapshot.Membership, fmt.Errorf("unrecognized snapshot version %d", snapshot.Version)
+ }
+
+ if err := n.memoryStore.Restore(&snapshot.Store); err != nil {
+ return snapshot.Membership, err
+ }
+
+ return snapshot.Membership, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/raft/storage/snapwrap.go b/vendor/github.com/docker/swarmkit/manager/state/raft/storage/snapwrap.go
new file mode 100644
index 0000000..641f7e1
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/raft/storage/snapwrap.go
@@ -0,0 +1,158 @@
+package storage
+
+import (
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/coreos/etcd/pkg/fileutil"
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/coreos/etcd/snap"
+ "github.com/docker/swarmkit/manager/encryption"
+ "github.com/pkg/errors"
+)
+
+// This package wraps the github.com/coreos/etcd/snap package, and encrypts
+// the bytes of whatever snapshot is passed to it, and decrypts the bytes of
+// whatever snapshot it reads.
+
+// Snapshotter is the interface presented by github.com/coreos/etcd/snap.Snapshotter that we depend upon
+type Snapshotter interface {
+ SaveSnap(snapshot raftpb.Snapshot) error
+ Load() (*raftpb.Snapshot, error)
+}
+
+// SnapFactory provides an interface for the different ways to get a Snapshotter object.
+// For instance, the etcd/snap package itself provides this
+type SnapFactory interface {
+ New(dirpath string) Snapshotter
+}
+
+var _ Snapshotter = &wrappedSnap{}
+var _ Snapshotter = &snap.Snapshotter{}
+var _ SnapFactory = snapCryptor{}
+
+// wrappedSnap wraps a github.com/coreos/etcd/snap.Snapshotter, and handles
+// encrypting/decrypting.
+type wrappedSnap struct {
+ *snap.Snapshotter
+ encrypter encryption.Encrypter
+ decrypter encryption.Decrypter
+}
+
+// SaveSnap encrypts the snapshot data (if an encrypter is exists) before passing it onto the
+// wrapped snap.Snapshotter's SaveSnap function.
+func (s *wrappedSnap) SaveSnap(snapshot raftpb.Snapshot) error {
+ toWrite := snapshot
+ var err error
+ toWrite.Data, err = encryption.Encrypt(snapshot.Data, s.encrypter)
+ if err != nil {
+ return err
+ }
+ return s.Snapshotter.SaveSnap(toWrite)
+}
+
+// Load decrypts the snapshot data (if a decrypter is exists) after reading it using the
+// wrapped snap.Snapshotter's Load function.
+func (s *wrappedSnap) Load() (*raftpb.Snapshot, error) {
+ snapshot, err := s.Snapshotter.Load()
+ if err != nil {
+ return nil, err
+ }
+ snapshot.Data, err = encryption.Decrypt(snapshot.Data, s.decrypter)
+ if err != nil {
+ return nil, err
+ }
+
+ return snapshot, nil
+}
+
+// snapCryptor is an object that provides the same functions as `etcd/wal`
+// and `etcd/snap` that we need to open a WAL object or Snapshotter object
+type snapCryptor struct {
+ encrypter encryption.Encrypter
+ decrypter encryption.Decrypter
+}
+
+// NewSnapFactory returns a new object that can read from and write to encrypted
+// snapshots on disk
+func NewSnapFactory(encrypter encryption.Encrypter, decrypter encryption.Decrypter) SnapFactory {
+ return snapCryptor{
+ encrypter: encrypter,
+ decrypter: decrypter,
+ }
+}
+
+// NewSnapshotter returns a new Snapshotter with the given encrypters and decrypters
+func (sc snapCryptor) New(dirpath string) Snapshotter {
+ return &wrappedSnap{
+ Snapshotter: snap.New(dirpath),
+ encrypter: sc.encrypter,
+ decrypter: sc.decrypter,
+ }
+}
+
+type originalSnap struct{}
+
+func (o originalSnap) New(dirpath string) Snapshotter {
+ return snap.New(dirpath)
+}
+
+// OriginalSnap is the original `snap` package as an implementation of the SnapFactory interface
+var OriginalSnap SnapFactory = originalSnap{}
+
+// MigrateSnapshot reads the latest existing snapshot from one directory, encoded one way, and writes
+// it to a new directory, encoded a different way
+func MigrateSnapshot(oldDir, newDir string, oldFactory, newFactory SnapFactory) error {
+ // use temporary snapshot directory so initialization appears atomic
+ oldSnapshotter := oldFactory.New(oldDir)
+ snapshot, err := oldSnapshotter.Load()
+ switch err {
+ case snap.ErrNoSnapshot: // if there's no snapshot, the migration succeeded
+ return nil
+ case nil:
+ break
+ default:
+ return err
+ }
+
+ tmpdirpath := filepath.Clean(newDir) + ".tmp"
+ if fileutil.Exist(tmpdirpath) {
+ if err := os.RemoveAll(tmpdirpath); err != nil {
+ return errors.Wrap(err, "could not remove temporary snapshot directory")
+ }
+ }
+ if err := fileutil.CreateDirAll(tmpdirpath); err != nil {
+ return errors.Wrap(err, "could not create temporary snapshot directory")
+ }
+ tmpSnapshotter := newFactory.New(tmpdirpath)
+
+ // write the new snapshot to the temporary location
+ if err = tmpSnapshotter.SaveSnap(*snapshot); err != nil {
+ return err
+ }
+
+ return os.Rename(tmpdirpath, newDir)
+}
+
+// ListSnapshots lists all the snapshot files in a particular directory and returns
+// the snapshot files in reverse lexical order (newest first)
+func ListSnapshots(dirpath string) ([]string, error) {
+ dirents, err := ioutil.ReadDir(dirpath)
+ if err != nil {
+ return nil, err
+ }
+
+ var snapshots []string
+ for _, dirent := range dirents {
+ if strings.HasSuffix(dirent.Name(), ".snap") {
+ snapshots = append(snapshots, dirent.Name())
+ }
+ }
+
+ // Sort snapshot filenames in reverse lexical order
+ sort.Sort(sort.Reverse(sort.StringSlice(snapshots)))
+ return snapshots, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/raft/storage/storage.go b/vendor/github.com/docker/swarmkit/manager/state/raft/storage/storage.go
new file mode 100644
index 0000000..a737aab
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/raft/storage/storage.go
@@ -0,0 +1,375 @@
+package storage
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+
+ "golang.org/x/net/context"
+
+ "github.com/coreos/etcd/pkg/fileutil"
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/coreos/etcd/snap"
+ "github.com/coreos/etcd/wal"
+ "github.com/coreos/etcd/wal/walpb"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/encryption"
+ "github.com/pkg/errors"
+)
+
+// ErrNoWAL is returned if there are no WALs on disk
+var ErrNoWAL = errors.New("no WAL present")
+
+type walSnapDirs struct {
+ wal string
+ snap string
+}
+
+// the wal/snap directories in decreasing order of preference/version
+var versionedWALSnapDirs = []walSnapDirs{
+ {wal: "wal-v3-encrypted", snap: "snap-v3-encrypted"},
+ {wal: "wal-v3", snap: "snap-v3"},
+ {wal: "wal", snap: "snap"},
+}
+
+// MultiDecrypter attempts to decrypt with a list of decrypters
+type MultiDecrypter []encryption.Decrypter
+
+// Decrypt tries to decrypt using all the decrypters
+func (m MultiDecrypter) Decrypt(r api.MaybeEncryptedRecord) (result []byte, err error) {
+ for _, d := range m {
+ result, err = d.Decrypt(r)
+ if err == nil {
+ return
+ }
+ }
+ return
+}
+
+// EncryptedRaftLogger saves raft data to disk
+type EncryptedRaftLogger struct {
+ StateDir string
+ EncryptionKey []byte
+
+ // mutex is locked for writing only when we need to replace the wal object and snapshotter
+ // object, not when we're writing snapshots or wals (in which case it's locked for reading)
+ encoderMu sync.RWMutex
+ wal WAL
+ snapshotter Snapshotter
+}
+
+// BootstrapFromDisk creates a new snapshotter and wal, and also reads the latest snapshot and WALs from disk
+func (e *EncryptedRaftLogger) BootstrapFromDisk(ctx context.Context, oldEncryptionKeys ...[]byte) (*raftpb.Snapshot, WALData, error) {
+ e.encoderMu.Lock()
+ defer e.encoderMu.Unlock()
+
+ walDir := e.walDir()
+ snapDir := e.snapDir()
+
+ encrypter, decrypter := encryption.Defaults(e.EncryptionKey)
+ if oldEncryptionKeys != nil {
+ decrypters := []encryption.Decrypter{decrypter}
+ for _, key := range oldEncryptionKeys {
+ _, d := encryption.Defaults(key)
+ decrypters = append(decrypters, d)
+ }
+ decrypter = MultiDecrypter(decrypters)
+ }
+
+ snapFactory := NewSnapFactory(encrypter, decrypter)
+
+ if !fileutil.Exist(snapDir) {
+ // If snapshots created by the etcd-v2 code exist, or by swarmkit development version,
+ // read the latest snapshot and write it encoded to the new path. The new path
+ // prevents etc-v2 creating snapshots that are visible to us, but not encoded and
+ // out of sync with our WALs, after a downgrade.
+ for _, dirs := range versionedWALSnapDirs[1:] {
+ legacySnapDir := filepath.Join(e.StateDir, dirs.snap)
+ if fileutil.Exist(legacySnapDir) {
+ if err := MigrateSnapshot(legacySnapDir, snapDir, OriginalSnap, snapFactory); err != nil {
+ return nil, WALData{}, err
+ }
+ break
+ }
+ }
+ }
+ // ensure the new directory exists
+ if err := os.MkdirAll(snapDir, 0700); err != nil {
+ return nil, WALData{}, errors.Wrap(err, "failed to create snapshot directory")
+ }
+
+ var (
+ snapshotter Snapshotter
+ walObj WAL
+ err error
+ )
+
+ // Create a snapshotter and load snapshot data
+ snapshotter = snapFactory.New(snapDir)
+ snapshot, err := snapshotter.Load()
+ if err != nil && err != snap.ErrNoSnapshot {
+ return nil, WALData{}, err
+ }
+
+ walFactory := NewWALFactory(encrypter, decrypter)
+ var walsnap walpb.Snapshot
+ if snapshot != nil {
+ walsnap.Index = snapshot.Metadata.Index
+ walsnap.Term = snapshot.Metadata.Term
+ }
+
+ if !wal.Exist(walDir) {
+ var walExists bool
+ // If wals created by the etcd-v2 wal code exist, read the latest ones based
+ // on this snapshot and encode them to wals in the new path to avoid adding
+ // backwards-incompatible entries to those files.
+ for _, dirs := range versionedWALSnapDirs[1:] {
+ legacyWALDir := filepath.Join(e.StateDir, dirs.wal)
+ if !wal.Exist(legacyWALDir) {
+ continue
+ }
+ if err = MigrateWALs(ctx, legacyWALDir, walDir, OriginalWAL, walFactory, walsnap); err != nil {
+ return nil, WALData{}, err
+ }
+ walExists = true
+ break
+ }
+ if !walExists {
+ return nil, WALData{}, ErrNoWAL
+ }
+ }
+
+ walObj, waldata, err := ReadRepairWAL(ctx, walDir, walsnap, walFactory)
+ if err != nil {
+ return nil, WALData{}, err
+ }
+
+ e.snapshotter = snapshotter
+ e.wal = walObj
+
+ return snapshot, waldata, nil
+}
+
+// BootstrapNew creates a new snapshotter and WAL writer, expecting that there is nothing on disk
+func (e *EncryptedRaftLogger) BootstrapNew(metadata []byte) error {
+ e.encoderMu.Lock()
+ defer e.encoderMu.Unlock()
+ encrypter, decrypter := encryption.Defaults(e.EncryptionKey)
+ walFactory := NewWALFactory(encrypter, decrypter)
+
+ for _, dirpath := range []string{filepath.Dir(e.walDir()), e.snapDir()} {
+ if err := os.MkdirAll(dirpath, 0700); err != nil {
+ return errors.Wrapf(err, "failed to create %s", dirpath)
+ }
+ }
+ var err error
+ // the wal directory must not already exist upon creation
+ e.wal, err = walFactory.Create(e.walDir(), metadata)
+ if err != nil {
+ return errors.Wrap(err, "failed to create WAL")
+ }
+
+ e.snapshotter = NewSnapFactory(encrypter, decrypter).New(e.snapDir())
+ return nil
+}
+
+func (e *EncryptedRaftLogger) walDir() string {
+ return filepath.Join(e.StateDir, versionedWALSnapDirs[0].wal)
+}
+
+func (e *EncryptedRaftLogger) snapDir() string {
+ return filepath.Join(e.StateDir, versionedWALSnapDirs[0].snap)
+}
+
+// RotateEncryptionKey swaps out the encoders and decoders used by the wal and snapshotter
+func (e *EncryptedRaftLogger) RotateEncryptionKey(newKey []byte) {
+ e.encoderMu.Lock()
+ defer e.encoderMu.Unlock()
+
+ if e.wal != nil { // if the wal exists, the snapshotter exists
+ // We don't want to have to close the WAL, because we can't open a new one.
+ // We need to know the previous snapshot, because when you open a WAL you
+ // have to read out all the entries from a particular snapshot, or you can't
+ // write. So just rotate the encoders out from under it. We already
+ // have a lock on writing to snapshots and WALs.
+ wrapped, ok := e.wal.(*wrappedWAL)
+ if !ok {
+ panic(fmt.Errorf("EncryptedRaftLogger's WAL is not a wrappedWAL"))
+ }
+
+ wrapped.encrypter, wrapped.decrypter = encryption.Defaults(newKey)
+
+ e.snapshotter = NewSnapFactory(wrapped.encrypter, wrapped.decrypter).New(e.snapDir())
+ }
+ e.EncryptionKey = newKey
+}
+
+// SaveSnapshot actually saves a given snapshot to both the WAL and the snapshot.
+func (e *EncryptedRaftLogger) SaveSnapshot(snapshot raftpb.Snapshot) error {
+
+ walsnap := walpb.Snapshot{
+ Index: snapshot.Metadata.Index,
+ Term: snapshot.Metadata.Term,
+ }
+
+ e.encoderMu.RLock()
+ if err := e.wal.SaveSnapshot(walsnap); err != nil {
+ e.encoderMu.RUnlock()
+ return err
+ }
+
+ snapshotter := e.snapshotter
+ e.encoderMu.RUnlock()
+
+ if err := snapshotter.SaveSnap(snapshot); err != nil {
+ return err
+ }
+ if err := e.wal.ReleaseLockTo(snapshot.Metadata.Index); err != nil {
+ return err
+ }
+ return nil
+}
+
+// GC garbage collects snapshots and wals older than the provided index and term
+func (e *EncryptedRaftLogger) GC(index uint64, term uint64, keepOldSnapshots uint64) error {
+ // Delete any older snapshots
+ curSnapshot := fmt.Sprintf("%016x-%016x%s", term, index, ".snap")
+
+ snapshots, err := ListSnapshots(e.snapDir())
+ if err != nil {
+ return err
+ }
+
+ // Ignore any snapshots that are older than the current snapshot.
+ // Delete the others. Rather than doing lexical comparisons, we look
+ // at what exists before/after the current snapshot in the slice.
+ // This means that if the current snapshot doesn't appear in the
+ // directory for some strange reason, we won't delete anything, which
+ // is the safe behavior.
+ curSnapshotIdx := -1
+ var (
+ removeErr error
+ oldestSnapshot string
+ )
+
+ for i, snapFile := range snapshots {
+ if curSnapshotIdx >= 0 && i > curSnapshotIdx {
+ if uint64(i-curSnapshotIdx) > keepOldSnapshots {
+ err := os.Remove(filepath.Join(e.snapDir(), snapFile))
+ if err != nil && removeErr == nil {
+ removeErr = err
+ }
+ continue
+ }
+ } else if snapFile == curSnapshot {
+ curSnapshotIdx = i
+ }
+ oldestSnapshot = snapFile
+ }
+
+ if removeErr != nil {
+ return removeErr
+ }
+
+ // Remove any WAL files that only contain data from before the oldest
+ // remaining snapshot.
+
+ if oldestSnapshot == "" {
+ return nil
+ }
+
+ // Parse index out of oldest snapshot's filename
+ var snapTerm, snapIndex uint64
+ _, err = fmt.Sscanf(oldestSnapshot, "%016x-%016x.snap", &snapTerm, &snapIndex)
+ if err != nil {
+ return errors.Wrapf(err, "malformed snapshot filename %s", oldestSnapshot)
+ }
+
+ wals, err := ListWALs(e.walDir())
+ if err != nil {
+ return err
+ }
+
+ found := false
+ deleteUntil := -1
+
+ for i, walName := range wals {
+ var walSeq, walIndex uint64
+ _, err = fmt.Sscanf(walName, "%016x-%016x.wal", &walSeq, &walIndex)
+ if err != nil {
+ return errors.Wrapf(err, "could not parse WAL name %s", walName)
+ }
+
+ if walIndex >= snapIndex {
+ deleteUntil = i - 1
+ found = true
+ break
+ }
+ }
+
+ // If all WAL files started with indices below the oldest snapshot's
+ // index, we can delete all but the newest WAL file.
+ if !found && len(wals) != 0 {
+ deleteUntil = len(wals) - 1
+ }
+
+ for i := 0; i < deleteUntil; i++ {
+ walPath := filepath.Join(e.walDir(), wals[i])
+ l, err := fileutil.TryLockFile(walPath, os.O_WRONLY, fileutil.PrivateFileMode)
+ if err != nil {
+ return errors.Wrapf(err, "could not lock old WAL file %s for removal", wals[i])
+ }
+ err = os.Remove(walPath)
+ l.Close()
+ if err != nil {
+ return errors.Wrapf(err, "error removing old WAL file %s", wals[i])
+ }
+ }
+
+ return nil
+}
+
+// SaveEntries saves only entries to disk
+func (e *EncryptedRaftLogger) SaveEntries(st raftpb.HardState, entries []raftpb.Entry) error {
+ e.encoderMu.RLock()
+ defer e.encoderMu.RUnlock()
+
+ if e.wal == nil {
+ return fmt.Errorf("raft WAL has either been closed or has never been created")
+ }
+ return e.wal.Save(st, entries)
+}
+
+// Close closes the logger - it will have to be bootstrapped again to start writing
+func (e *EncryptedRaftLogger) Close(ctx context.Context) {
+ e.encoderMu.Lock()
+ defer e.encoderMu.Unlock()
+
+ if e.wal != nil {
+ if err := e.wal.Close(); err != nil {
+ log.G(ctx).WithError(err).Error("error closing raft WAL")
+ }
+ }
+
+ e.wal = nil
+ e.snapshotter = nil
+}
+
+// Clear closes the existing WAL and removes the WAL and snapshot.
+func (e *EncryptedRaftLogger) Clear(ctx context.Context) error {
+ e.encoderMu.Lock()
+ defer e.encoderMu.Unlock()
+
+ if e.wal != nil {
+ if err := e.wal.Close(); err != nil {
+ log.G(ctx).WithError(err).Error("error closing raft WAL")
+ }
+ }
+ e.snapshotter = nil
+
+ os.RemoveAll(e.walDir())
+ os.RemoveAll(e.snapDir())
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/raft/storage/walwrap.go b/vendor/github.com/docker/swarmkit/manager/state/raft/storage/walwrap.go
new file mode 100644
index 0000000..3c1208c
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/raft/storage/walwrap.go
@@ -0,0 +1,255 @@
+package storage
+
+import (
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/coreos/etcd/wal"
+ "github.com/coreos/etcd/wal/walpb"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/encryption"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+// This package wraps the github.com/coreos/etcd/wal package, and encrypts
+// the bytes of whatever entry is passed to it, and decrypts the bytes of
+// whatever entry it reads.
+
+// WAL is the interface presented by github.com/coreos/etcd/wal.WAL that we depend upon
+type WAL interface {
+ ReadAll() ([]byte, raftpb.HardState, []raftpb.Entry, error)
+ ReleaseLockTo(index uint64) error
+ Close() error
+ Save(st raftpb.HardState, ents []raftpb.Entry) error
+ SaveSnapshot(e walpb.Snapshot) error
+}
+
+// WALFactory provides an interface for the different ways to get a WAL object.
+// For instance, the etcd/wal package itself provides this
+type WALFactory interface {
+ Create(dirpath string, metadata []byte) (WAL, error)
+ Open(dirpath string, walsnap walpb.Snapshot) (WAL, error)
+}
+
+var _ WAL = &wrappedWAL{}
+var _ WAL = &wal.WAL{}
+var _ WALFactory = walCryptor{}
+
+// wrappedWAL wraps a github.com/coreos/etcd/wal.WAL, and handles encrypting/decrypting
+type wrappedWAL struct {
+ *wal.WAL
+ encrypter encryption.Encrypter
+ decrypter encryption.Decrypter
+}
+
+// ReadAll wraps the wal.WAL.ReadAll() function, but it first checks to see if the
+// metadata indicates that the entries are encryptd, and if so, decrypts them.
+func (w *wrappedWAL) ReadAll() ([]byte, raftpb.HardState, []raftpb.Entry, error) {
+ metadata, state, ents, err := w.WAL.ReadAll()
+ if err != nil {
+ return metadata, state, ents, err
+ }
+ for i, ent := range ents {
+ ents[i].Data, err = encryption.Decrypt(ent.Data, w.decrypter)
+ if err != nil {
+ return nil, raftpb.HardState{}, nil, err
+ }
+ }
+
+ return metadata, state, ents, nil
+}
+
+// Save encrypts the entry data (if an encrypter is exists) before passing it onto the
+// wrapped wal.WAL's Save function.
+func (w *wrappedWAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
+ var writeEnts []raftpb.Entry
+ for _, ent := range ents {
+ data, err := encryption.Encrypt(ent.Data, w.encrypter)
+ if err != nil {
+ return err
+ }
+ writeEnts = append(writeEnts, raftpb.Entry{
+ Index: ent.Index,
+ Term: ent.Term,
+ Type: ent.Type,
+ Data: data,
+ })
+ }
+
+ return w.WAL.Save(st, writeEnts)
+}
+
+// walCryptor is an object that provides the same functions as `etcd/wal`
+// and `etcd/snap` that we need to open a WAL object or Snapshotter object
+type walCryptor struct {
+ encrypter encryption.Encrypter
+ decrypter encryption.Decrypter
+}
+
+// NewWALFactory returns an object that can be used to produce objects that
+// will read from and write to encrypted WALs on disk.
+func NewWALFactory(encrypter encryption.Encrypter, decrypter encryption.Decrypter) WALFactory {
+ return walCryptor{
+ encrypter: encrypter,
+ decrypter: decrypter,
+ }
+}
+
+// Create returns a new WAL object with the given encrypters and decrypters.
+func (wc walCryptor) Create(dirpath string, metadata []byte) (WAL, error) {
+ w, err := wal.Create(dirpath, metadata)
+ if err != nil {
+ return nil, err
+ }
+ return &wrappedWAL{
+ WAL: w,
+ encrypter: wc.encrypter,
+ decrypter: wc.decrypter,
+ }, nil
+}
+
+// Open returns a new WAL object with the given encrypters and decrypters.
+func (wc walCryptor) Open(dirpath string, snap walpb.Snapshot) (WAL, error) {
+ w, err := wal.Open(dirpath, snap)
+ if err != nil {
+ return nil, err
+ }
+ return &wrappedWAL{
+ WAL: w,
+ encrypter: wc.encrypter,
+ decrypter: wc.decrypter,
+ }, nil
+}
+
+type originalWAL struct{}
+
+func (o originalWAL) Create(dirpath string, metadata []byte) (WAL, error) {
+ return wal.Create(dirpath, metadata)
+}
+func (o originalWAL) Open(dirpath string, walsnap walpb.Snapshot) (WAL, error) {
+ return wal.Open(dirpath, walsnap)
+}
+
+// OriginalWAL is the original `wal` package as an implementation of the WALFactory interface
+var OriginalWAL WALFactory = originalWAL{}
+
+// WALData contains all the data returned by a WAL's ReadAll() function
+// (metadata, hardwate, and entries)
+type WALData struct {
+ Metadata []byte
+ HardState raftpb.HardState
+ Entries []raftpb.Entry
+}
+
+// ReadRepairWAL opens a WAL for reading, and attempts to read it. If we can't read it, attempts to repair
+// and read again.
+func ReadRepairWAL(
+ ctx context.Context,
+ walDir string,
+ walsnap walpb.Snapshot,
+ factory WALFactory,
+) (WAL, WALData, error) {
+ var (
+ reader WAL
+ metadata []byte
+ st raftpb.HardState
+ ents []raftpb.Entry
+ err error
+ )
+ repaired := false
+ for {
+ if reader, err = factory.Open(walDir, walsnap); err != nil {
+ return nil, WALData{}, errors.Wrap(err, "failed to open WAL")
+ }
+ if metadata, st, ents, err = reader.ReadAll(); err != nil {
+ if closeErr := reader.Close(); closeErr != nil {
+ return nil, WALData{}, closeErr
+ }
+ if _, ok := err.(encryption.ErrCannotDecrypt); ok {
+ return nil, WALData{}, errors.Wrap(err, "failed to decrypt WAL")
+ }
+ // we can only repair ErrUnexpectedEOF and we never repair twice.
+ if repaired || err != io.ErrUnexpectedEOF {
+ return nil, WALData{}, errors.Wrap(err, "irreparable WAL error")
+ }
+ if !wal.Repair(walDir) {
+ return nil, WALData{}, errors.Wrap(err, "WAL error cannot be repaired")
+ }
+ log.G(ctx).WithError(err).Info("repaired WAL error")
+ repaired = true
+ continue
+ }
+ break
+ }
+ return reader, WALData{
+ Metadata: metadata,
+ HardState: st,
+ Entries: ents,
+ }, nil
+}
+
+// MigrateWALs reads existing WALs (from a particular snapshot and beyond) from one directory, encoded one way,
+// and writes them to a new directory, encoded a different way
+func MigrateWALs(ctx context.Context, oldDir, newDir string, oldFactory, newFactory WALFactory, snapshot walpb.Snapshot) error {
+ oldReader, waldata, err := ReadRepairWAL(ctx, oldDir, snapshot, oldFactory)
+ if err != nil {
+ return err
+ }
+ oldReader.Close()
+
+ if err := os.MkdirAll(filepath.Dir(newDir), 0700); err != nil {
+ return errors.Wrap(err, "could not create parent directory")
+ }
+
+ // keep temporary wal directory so WAL initialization appears atomic
+ tmpdirpath := filepath.Clean(newDir) + ".tmp"
+ if err := os.RemoveAll(tmpdirpath); err != nil {
+ return errors.Wrap(err, "could not remove temporary WAL directory")
+ }
+ defer os.RemoveAll(tmpdirpath)
+
+ tmpWAL, err := newFactory.Create(tmpdirpath, waldata.Metadata)
+ if err != nil {
+ return errors.Wrap(err, "could not create new WAL in temporary WAL directory")
+ }
+ defer tmpWAL.Close()
+
+ if err := tmpWAL.SaveSnapshot(snapshot); err != nil {
+ return errors.Wrap(err, "could not write WAL snapshot in temporary directory")
+ }
+
+ if err := tmpWAL.Save(waldata.HardState, waldata.Entries); err != nil {
+ return errors.Wrap(err, "could not migrate WALs to temporary directory")
+ }
+ if err := tmpWAL.Close(); err != nil {
+ return err
+ }
+
+ return os.Rename(tmpdirpath, newDir)
+}
+
+// ListWALs lists all the wals in a directory and returns the list in lexical
+// order (oldest first)
+func ListWALs(dirpath string) ([]string, error) {
+ dirents, err := ioutil.ReadDir(dirpath)
+ if err != nil {
+ return nil, err
+ }
+
+ var wals []string
+ for _, dirent := range dirents {
+ if strings.HasSuffix(dirent.Name(), ".wal") {
+ wals = append(wals, dirent.Name())
+ }
+ }
+
+ // Sort WAL filenames in lexical order
+ sort.Sort(sort.StringSlice(wals))
+ return wals, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/raft/transport/peer.go b/vendor/github.com/docker/swarmkit/manager/state/raft/transport/peer.go
new file mode 100644
index 0000000..55639af
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/raft/transport/peer.go
@@ -0,0 +1,291 @@
+package transport
+
+import (
+ "fmt"
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+
+ "github.com/coreos/etcd/raft"
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager/state/raft/membership"
+ "github.com/pkg/errors"
+)
+
+type peer struct {
+ id uint64
+
+ tr *Transport
+
+ msgc chan raftpb.Message
+
+ ctx context.Context
+ cancel context.CancelFunc
+ done chan struct{}
+
+ mu sync.Mutex
+ cc *grpc.ClientConn
+ addr string
+ newAddr string
+
+ active bool
+ becameActive time.Time
+}
+
+func newPeer(id uint64, addr string, tr *Transport) (*peer, error) {
+ cc, err := tr.dial(addr)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to create conn for %x with addr %s", id, addr)
+ }
+ ctx, cancel := context.WithCancel(tr.ctx)
+ ctx = log.WithField(ctx, "peer_id", fmt.Sprintf("%x", id))
+ p := &peer{
+ id: id,
+ addr: addr,
+ cc: cc,
+ tr: tr,
+ ctx: ctx,
+ cancel: cancel,
+ msgc: make(chan raftpb.Message, 4096),
+ done: make(chan struct{}),
+ }
+ go p.run(ctx)
+ return p, nil
+}
+
+func (p *peer) send(m raftpb.Message) (err error) {
+ p.mu.Lock()
+ defer func() {
+ if err != nil {
+ p.active = false
+ p.becameActive = time.Time{}
+ }
+ p.mu.Unlock()
+ }()
+ select {
+ case <-p.ctx.Done():
+ return p.ctx.Err()
+ default:
+ }
+ select {
+ case p.msgc <- m:
+ case <-p.ctx.Done():
+ return p.ctx.Err()
+ default:
+ p.tr.config.ReportUnreachable(p.id)
+ return errors.Errorf("peer is unreachable")
+ }
+ return nil
+}
+
+func (p *peer) update(addr string) error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.addr == addr {
+ return nil
+ }
+ cc, err := p.tr.dial(addr)
+ if err != nil {
+ return err
+ }
+
+ p.cc.Close()
+ p.cc = cc
+ p.addr = addr
+ return nil
+}
+
+func (p *peer) updateAddr(addr string) error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.addr == addr {
+ return nil
+ }
+ log.G(p.ctx).Debugf("peer %x updated to address %s, it will be used if old failed", p.id, addr)
+ p.newAddr = addr
+ return nil
+}
+
+func (p *peer) conn() *grpc.ClientConn {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return p.cc
+}
+
+func (p *peer) address() string {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return p.addr
+}
+
+func (p *peer) resolveAddr(ctx context.Context, id uint64) (string, error) {
+ resp, err := api.NewRaftClient(p.conn()).ResolveAddress(ctx, &api.ResolveAddressRequest{RaftID: id})
+ if err != nil {
+ return "", errors.Wrap(err, "failed to resolve address")
+ }
+ return resp.Addr, nil
+}
+
+func (p *peer) sendProcessMessage(ctx context.Context, m raftpb.Message) error {
+ ctx, cancel := context.WithTimeout(ctx, p.tr.config.SendTimeout)
+ defer cancel()
+ _, err := api.NewRaftClient(p.conn()).ProcessRaftMessage(ctx, &api.ProcessRaftMessageRequest{Message: &m})
+ if grpc.Code(err) == codes.NotFound && grpc.ErrorDesc(err) == membership.ErrMemberRemoved.Error() {
+ p.tr.config.NodeRemoved()
+ }
+ if m.Type == raftpb.MsgSnap {
+ if err != nil {
+ p.tr.config.ReportSnapshot(m.To, raft.SnapshotFailure)
+ } else {
+ p.tr.config.ReportSnapshot(m.To, raft.SnapshotFinish)
+ }
+ }
+ if err != nil {
+ p.tr.config.ReportUnreachable(m.To)
+ return err
+ }
+ return nil
+}
+
+func healthCheckConn(ctx context.Context, cc *grpc.ClientConn) error {
+ resp, err := api.NewHealthClient(cc).Check(ctx, &api.HealthCheckRequest{Service: "Raft"})
+ if err != nil {
+ return errors.Wrap(err, "failed to check health")
+ }
+ if resp.Status != api.HealthCheckResponse_SERVING {
+ return errors.Errorf("health check returned status %s", resp.Status)
+ }
+ return nil
+}
+
+func (p *peer) healthCheck(ctx context.Context) error {
+ ctx, cancel := context.WithTimeout(ctx, p.tr.config.SendTimeout)
+ defer cancel()
+ return healthCheckConn(ctx, p.conn())
+}
+
+func (p *peer) setActive() {
+ p.mu.Lock()
+ if !p.active {
+ p.active = true
+ p.becameActive = time.Now()
+ }
+ p.mu.Unlock()
+}
+
+func (p *peer) setInactive() {
+ p.mu.Lock()
+ p.active = false
+ p.becameActive = time.Time{}
+ p.mu.Unlock()
+}
+
+func (p *peer) activeTime() time.Time {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return p.becameActive
+}
+
+func (p *peer) drain() error {
+ ctx, cancel := context.WithTimeout(context.Background(), 16*time.Second)
+ defer cancel()
+ for {
+ select {
+ case m, ok := <-p.msgc:
+ if !ok {
+ // all messages proceeded
+ return nil
+ }
+ if err := p.sendProcessMessage(ctx, m); err != nil {
+ return errors.Wrap(err, "send drain message")
+ }
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+}
+
+func (p *peer) handleAddressChange(ctx context.Context) error {
+ p.mu.Lock()
+ newAddr := p.newAddr
+ p.newAddr = ""
+ p.mu.Unlock()
+ if newAddr == "" {
+ return nil
+ }
+ cc, err := p.tr.dial(newAddr)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(ctx, p.tr.config.SendTimeout)
+ defer cancel()
+ if err := healthCheckConn(ctx, cc); err != nil {
+ cc.Close()
+ return err
+ }
+ // there is possibility of race if host changing address too fast, but
+ // it's unlikely and eventually thing should be settled
+ p.mu.Lock()
+ p.cc.Close()
+ p.cc = cc
+ p.addr = newAddr
+ p.tr.config.UpdateNode(p.id, p.addr)
+ p.mu.Unlock()
+ return nil
+}
+
+func (p *peer) run(ctx context.Context) {
+ defer func() {
+ p.mu.Lock()
+ p.active = false
+ p.becameActive = time.Time{}
+ // at this point we can be sure that nobody will write to msgc
+ if p.msgc != nil {
+ close(p.msgc)
+ }
+ p.mu.Unlock()
+ if err := p.drain(); err != nil {
+ log.G(ctx).WithError(err).Error("failed to drain message queue")
+ }
+ close(p.done)
+ }()
+ if err := p.healthCheck(ctx); err == nil {
+ p.setActive()
+ }
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+
+ select {
+ case m := <-p.msgc:
+ // we do not propagate context here, because this operation should be finished
+ // or timed out for correct raft work.
+ err := p.sendProcessMessage(context.Background(), m)
+ if err != nil {
+ log.G(ctx).WithError(err).Debugf("failed to send message %s", m.Type)
+ p.setInactive()
+ if err := p.handleAddressChange(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("failed to change address after failure")
+ }
+ continue
+ }
+ p.setActive()
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (p *peer) stop() {
+ p.cancel()
+ <-p.done
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/raft/transport/transport.go b/vendor/github.com/docker/swarmkit/manager/state/raft/transport/transport.go
new file mode 100644
index 0000000..69057f6
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/raft/transport/transport.go
@@ -0,0 +1,398 @@
+// Package transport provides grpc transport layer for raft.
+// All methods are non-blocking.
+package transport
+
+import (
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+
+ grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials"
+
+ "github.com/coreos/etcd/raft"
+ "github.com/coreos/etcd/raft/raftpb"
+ "github.com/docker/swarmkit/log"
+ "github.com/pkg/errors"
+)
+
+// ErrIsNotFound indicates that peer was never added to transport.
+var ErrIsNotFound = errors.New("peer not found")
+
+// Raft is interface which represents Raft API for transport package.
+type Raft interface {
+ ReportUnreachable(id uint64)
+ ReportSnapshot(id uint64, status raft.SnapshotStatus)
+ IsIDRemoved(id uint64) bool
+ UpdateNode(id uint64, addr string)
+
+ NodeRemoved()
+}
+
+// Config for Transport
+type Config struct {
+ HeartbeatInterval time.Duration
+ SendTimeout time.Duration
+ Credentials credentials.TransportCredentials
+ RaftID string
+
+ Raft
+}
+
+// Transport is structure which manages remote raft peers and sends messages
+// to them.
+type Transport struct {
+ config *Config
+
+ unknownc chan raftpb.Message
+
+ mu sync.Mutex
+ peers map[uint64]*peer
+ stopped bool
+
+ ctx context.Context
+ cancel context.CancelFunc
+ done chan struct{}
+
+ deferredConns map[*grpc.ClientConn]*time.Timer
+}
+
+// New returns new Transport with specified Config.
+func New(cfg *Config) *Transport {
+ ctx, cancel := context.WithCancel(context.Background())
+ if cfg.RaftID != "" {
+ ctx = log.WithField(ctx, "raft_id", cfg.RaftID)
+ }
+ t := &Transport{
+ peers: make(map[uint64]*peer),
+ config: cfg,
+ unknownc: make(chan raftpb.Message),
+ done: make(chan struct{}),
+ ctx: ctx,
+ cancel: cancel,
+
+ deferredConns: make(map[*grpc.ClientConn]*time.Timer),
+ }
+ go t.run(ctx)
+ return t
+}
+
+func (t *Transport) run(ctx context.Context) {
+ defer func() {
+ log.G(ctx).Debug("stop transport")
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ t.stopped = true
+ for _, p := range t.peers {
+ p.stop()
+ p.cc.Close()
+ }
+ for cc, timer := range t.deferredConns {
+ timer.Stop()
+ cc.Close()
+ }
+ t.deferredConns = nil
+ close(t.done)
+ }()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+
+ select {
+ case m := <-t.unknownc:
+ if err := t.sendUnknownMessage(ctx, m); err != nil {
+ log.G(ctx).WithError(err).Warnf("ignored message %s to unknown peer %x", m.Type, m.To)
+ }
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+// Stop stops transport and waits until it finished
+func (t *Transport) Stop() {
+ t.cancel()
+ <-t.done
+}
+
+// Send sends raft message to remote peers.
+func (t *Transport) Send(m raftpb.Message) error {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.stopped {
+ return errors.New("transport stopped")
+ }
+ if t.config.IsIDRemoved(m.To) {
+ return errors.Errorf("refusing to send message %s to removed member %x", m.Type, m.To)
+ }
+ p, ok := t.peers[m.To]
+ if !ok {
+ log.G(t.ctx).Warningf("sending message %s to an unrecognized member ID %x", m.Type, m.To)
+ select {
+ // we need to process messages to unknown peers in separate goroutine
+ // to not block sender
+ case t.unknownc <- m:
+ case <-t.ctx.Done():
+ return t.ctx.Err()
+ default:
+ return errors.New("unknown messages queue is full")
+ }
+ return nil
+ }
+ if err := p.send(m); err != nil {
+ return errors.Wrapf(err, "failed to send message %x to %x", m.Type, m.To)
+ }
+ return nil
+}
+
+// AddPeer adds new peer with id and address addr to Transport.
+// If there is already peer with such id in Transport it will return error if
+// address is different (UpdatePeer should be used) or nil otherwise.
+func (t *Transport) AddPeer(id uint64, addr string) error {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.stopped {
+ return errors.New("transport stopped")
+ }
+ if ep, ok := t.peers[id]; ok {
+ if ep.address() == addr {
+ return nil
+ }
+ return errors.Errorf("peer %x already added with addr %s", id, ep.addr)
+ }
+ log.G(t.ctx).Debugf("transport: add peer %x with address %s", id, addr)
+ p, err := newPeer(id, addr, t)
+ if err != nil {
+ return errors.Wrapf(err, "failed to create peer %x with addr %s", id, addr)
+ }
+ t.peers[id] = p
+ return nil
+}
+
+// RemovePeer removes peer from Transport and wait for it to stop.
+func (t *Transport) RemovePeer(id uint64) error {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+
+ if t.stopped {
+ return errors.New("transport stopped")
+ }
+ p, ok := t.peers[id]
+ if !ok {
+ return ErrIsNotFound
+ }
+ delete(t.peers, id)
+ cc := p.conn()
+ p.stop()
+ timer := time.AfterFunc(8*time.Second, func() {
+ t.mu.Lock()
+ if !t.stopped {
+ delete(t.deferredConns, cc)
+ cc.Close()
+ }
+ t.mu.Unlock()
+ })
+ // store connection and timer for cleaning up on stop
+ t.deferredConns[cc] = timer
+
+ return nil
+}
+
+// UpdatePeer updates peer with new address. It replaces connection immediately.
+func (t *Transport) UpdatePeer(id uint64, addr string) error {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+
+ if t.stopped {
+ return errors.New("transport stopped")
+ }
+ p, ok := t.peers[id]
+ if !ok {
+ return ErrIsNotFound
+ }
+ if err := p.update(addr); err != nil {
+ return err
+ }
+ log.G(t.ctx).Debugf("peer %x updated to address %s", id, addr)
+ return nil
+}
+
+// UpdatePeerAddr updates peer with new address, but delays connection creation.
+// New address won't be used until first failure on old address.
+func (t *Transport) UpdatePeerAddr(id uint64, addr string) error {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+
+ if t.stopped {
+ return errors.New("transport stopped")
+ }
+ p, ok := t.peers[id]
+ if !ok {
+ return ErrIsNotFound
+ }
+ if err := p.updateAddr(addr); err != nil {
+ return err
+ }
+ return nil
+}
+
+// PeerConn returns raw grpc connection to peer.
+func (t *Transport) PeerConn(id uint64) (*grpc.ClientConn, error) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ p, ok := t.peers[id]
+ if !ok {
+ return nil, ErrIsNotFound
+ }
+ p.mu.Lock()
+ active := p.active
+ p.mu.Unlock()
+ if !active {
+ return nil, errors.New("peer is inactive")
+ }
+ return p.conn(), nil
+}
+
+// PeerAddr returns address of peer with id.
+func (t *Transport) PeerAddr(id uint64) (string, error) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ p, ok := t.peers[id]
+ if !ok {
+ return "", ErrIsNotFound
+ }
+ return p.address(), nil
+}
+
+// HealthCheck checks health of particular peer.
+func (t *Transport) HealthCheck(ctx context.Context, id uint64) error {
+ t.mu.Lock()
+ p, ok := t.peers[id]
+ t.mu.Unlock()
+ if !ok {
+ return ErrIsNotFound
+ }
+ ctx, cancel := t.withContext(ctx)
+ defer cancel()
+ return p.healthCheck(ctx)
+}
+
+// Active returns true if node was recently active and false otherwise.
+func (t *Transport) Active(id uint64) bool {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ p, ok := t.peers[id]
+ if !ok {
+ return false
+ }
+ p.mu.Lock()
+ active := p.active
+ p.mu.Unlock()
+ return active
+}
+
+// LongestActive returns the ID of the peer that has been active for the longest
+// length of time.
+func (t *Transport) LongestActive() (uint64, error) {
+ p, err := t.longestActive()
+ if err != nil {
+ return 0, err
+ }
+
+ return p.id, nil
+}
+
+// longestActive returns the peer that has been active for the longest length of
+// time.
+func (t *Transport) longestActive() (*peer, error) {
+ var longest *peer
+ var longestTime time.Time
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ for _, p := range t.peers {
+ becameActive := p.activeTime()
+ if becameActive.IsZero() {
+ continue
+ }
+ if longest == nil {
+ longest = p
+ continue
+ }
+ if becameActive.Before(longestTime) {
+ longest = p
+ longestTime = becameActive
+ }
+ }
+ if longest == nil {
+ return nil, errors.New("failed to find longest active peer")
+ }
+ return longest, nil
+}
+
+func (t *Transport) dial(addr string) (*grpc.ClientConn, error) {
+ grpcOptions := []grpc.DialOption{
+ grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
+ grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor),
+ grpc.WithBackoffMaxDelay(8 * time.Second),
+ }
+ if t.config.Credentials != nil {
+ grpcOptions = append(grpcOptions, grpc.WithTransportCredentials(t.config.Credentials))
+ } else {
+ grpcOptions = append(grpcOptions, grpc.WithInsecure())
+ }
+
+ if t.config.SendTimeout > 0 {
+ grpcOptions = append(grpcOptions, grpc.WithTimeout(t.config.SendTimeout))
+ }
+
+ cc, err := grpc.Dial(addr, grpcOptions...)
+ if err != nil {
+ return nil, err
+ }
+
+ return cc, nil
+}
+
+func (t *Transport) withContext(ctx context.Context) (context.Context, context.CancelFunc) {
+ ctx, cancel := context.WithCancel(ctx)
+
+ go func() {
+ select {
+ case <-ctx.Done():
+ case <-t.ctx.Done():
+ cancel()
+ }
+ }()
+ return ctx, cancel
+}
+
+func (t *Transport) resolvePeer(ctx context.Context, id uint64) (*peer, error) {
+ longestActive, err := t.longestActive()
+ if err != nil {
+ return nil, err
+ }
+ ctx, cancel := context.WithTimeout(ctx, t.config.SendTimeout)
+ defer cancel()
+ addr, err := longestActive.resolveAddr(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ return newPeer(id, addr, t)
+}
+
+func (t *Transport) sendUnknownMessage(ctx context.Context, m raftpb.Message) error {
+ p, err := t.resolvePeer(ctx, m.To)
+ if err != nil {
+ return errors.Wrapf(err, "failed to resolve peer")
+ }
+ defer p.cancel()
+ if err := p.sendProcessMessage(ctx, m); err != nil {
+ return errors.Wrapf(err, "failed to send message")
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/raft/util.go b/vendor/github.com/docker/swarmkit/manager/state/raft/util.go
new file mode 100644
index 0000000..da44dca
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/raft/util.go
@@ -0,0 +1,86 @@
+package raft
+
+import (
+ "time"
+
+ "golang.org/x/net/context"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+ grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials"
+)
+
+// dial returns a grpc client connection
+func dial(addr string, protocol string, creds credentials.TransportCredentials, timeout time.Duration) (*grpc.ClientConn, error) {
+ grpcOptions := []grpc.DialOption{
+ grpc.WithBackoffMaxDelay(2 * time.Second),
+ grpc.WithTransportCredentials(creds),
+ grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
+ grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor),
+ }
+
+ if timeout != 0 {
+ grpcOptions = append(grpcOptions, grpc.WithTimeout(timeout))
+ }
+
+ return grpc.Dial(addr, grpcOptions...)
+}
+
+// Register registers the node raft server
+func Register(server *grpc.Server, node *Node) {
+ api.RegisterRaftServer(server, node)
+ api.RegisterRaftMembershipServer(server, node)
+}
+
+// WaitForLeader waits until node observe some leader in cluster. It returns
+// error if ctx was cancelled before leader appeared.
+func WaitForLeader(ctx context.Context, n *Node) error {
+ _, err := n.Leader()
+ if err == nil {
+ return nil
+ }
+ ticker := time.NewTicker(50 * time.Millisecond)
+ defer ticker.Stop()
+ for err != nil {
+ select {
+ case <-ticker.C:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ _, err = n.Leader()
+ }
+ return nil
+}
+
+// WaitForCluster waits until node observes that the cluster wide config is
+// committed to raft. This ensures that we can see and serve informations
+// related to the cluster.
+func WaitForCluster(ctx context.Context, n *Node) (cluster *api.Cluster, err error) {
+ watch, cancel := state.Watch(n.MemoryStore().WatchQueue(), api.EventCreateCluster{})
+ defer cancel()
+
+ var clusters []*api.Cluster
+ n.MemoryStore().View(func(readTx store.ReadTx) {
+ clusters, err = store.FindClusters(readTx, store.ByName(store.DefaultClusterName))
+ })
+
+ if err != nil {
+ return nil, err
+ }
+
+ if len(clusters) == 1 {
+ cluster = clusters[0]
+ } else {
+ select {
+ case e := <-watch:
+ cluster = e.(api.EventCreateCluster).Cluster
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+
+ return cluster, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/raft/wait.go b/vendor/github.com/docker/swarmkit/manager/state/raft/wait.go
new file mode 100644
index 0000000..6a003c2
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/raft/wait.go
@@ -0,0 +1,77 @@
+package raft
+
+import (
+ "fmt"
+ "sync"
+)
+
+type waitItem struct {
+ // channel to wait up the waiter
+ ch chan interface{}
+ // callback which is called synchronously when the wait is triggered
+ cb func()
+ // callback which is called to cancel a waiter
+ cancel func()
+}
+
+type wait struct {
+ l sync.Mutex
+ m map[uint64]waitItem
+}
+
+func newWait() *wait {
+ return &wait{m: make(map[uint64]waitItem)}
+}
+
+func (w *wait) register(id uint64, cb func(), cancel func()) <-chan interface{} {
+ w.l.Lock()
+ defer w.l.Unlock()
+ _, ok := w.m[id]
+ if !ok {
+ ch := make(chan interface{}, 1)
+ w.m[id] = waitItem{ch: ch, cb: cb, cancel: cancel}
+ return ch
+ }
+ panic(fmt.Sprintf("duplicate id %x", id))
+}
+
+func (w *wait) trigger(id uint64, x interface{}) bool {
+ w.l.Lock()
+ waitItem, ok := w.m[id]
+ delete(w.m, id)
+ w.l.Unlock()
+ if ok {
+ if waitItem.cb != nil {
+ waitItem.cb()
+ }
+ waitItem.ch <- x
+ return true
+ }
+ return false
+}
+
+func (w *wait) cancel(id uint64) {
+ w.l.Lock()
+ waitItem, ok := w.m[id]
+ delete(w.m, id)
+ w.l.Unlock()
+ if ok {
+ if waitItem.cancel != nil {
+ waitItem.cancel()
+ }
+ close(waitItem.ch)
+ }
+}
+
+func (w *wait) cancelAll() {
+ w.l.Lock()
+ defer w.l.Unlock()
+
+ for id, waitItem := range w.m {
+ delete(w.m, id)
+ if waitItem.cancel != nil {
+ waitItem.cancel()
+ }
+ close(waitItem.ch)
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/apply.go b/vendor/github.com/docker/swarmkit/manager/state/store/apply.go
new file mode 100644
index 0000000..e5f5c49
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/apply.go
@@ -0,0 +1,49 @@
+package store
+
+import (
+ "errors"
+
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/state"
+)
+
+// Apply takes an item from the event stream of one Store and applies it to
+// a second Store.
+func Apply(store *MemoryStore, item events.Event) (err error) {
+ return store.Update(func(tx Tx) error {
+ switch v := item.(type) {
+ case api.EventCreateTask:
+ return CreateTask(tx, v.Task)
+ case api.EventUpdateTask:
+ return UpdateTask(tx, v.Task)
+ case api.EventDeleteTask:
+ return DeleteTask(tx, v.Task.ID)
+
+ case api.EventCreateService:
+ return CreateService(tx, v.Service)
+ case api.EventUpdateService:
+ return UpdateService(tx, v.Service)
+ case api.EventDeleteService:
+ return DeleteService(tx, v.Service.ID)
+
+ case api.EventCreateNetwork:
+ return CreateNetwork(tx, v.Network)
+ case api.EventUpdateNetwork:
+ return UpdateNetwork(tx, v.Network)
+ case api.EventDeleteNetwork:
+ return DeleteNetwork(tx, v.Network.ID)
+
+ case api.EventCreateNode:
+ return CreateNode(tx, v.Node)
+ case api.EventUpdateNode:
+ return UpdateNode(tx, v.Node)
+ case api.EventDeleteNode:
+ return DeleteNode(tx, v.Node.ID)
+
+ case state.EventCommit:
+ return nil
+ }
+ return errors.New("unrecognized event type")
+ })
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/by.go b/vendor/github.com/docker/swarmkit/manager/state/store/by.go
new file mode 100644
index 0000000..f785d79
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/by.go
@@ -0,0 +1,214 @@
+package store
+
+import "github.com/docker/swarmkit/api"
+
+// By is an interface type passed to Find methods. Implementations must be
+// defined in this package.
+type By interface {
+ // isBy allows this interface to only be satisfied by certain internal
+ // types.
+ isBy()
+}
+
+type byAll struct{}
+
+func (a byAll) isBy() {
+}
+
+// All is an argument that can be passed to find to list all items in the
+// set.
+var All byAll
+
+type byNamePrefix string
+
+func (b byNamePrefix) isBy() {
+}
+
+// ByNamePrefix creates an object to pass to Find to select by query.
+func ByNamePrefix(namePrefix string) By {
+ return byNamePrefix(namePrefix)
+}
+
+type byIDPrefix string
+
+func (b byIDPrefix) isBy() {
+}
+
+// ByIDPrefix creates an object to pass to Find to select by query.
+func ByIDPrefix(idPrefix string) By {
+ return byIDPrefix(idPrefix)
+}
+
+type byName string
+
+func (b byName) isBy() {
+}
+
+// ByName creates an object to pass to Find to select by name.
+func ByName(name string) By {
+ return byName(name)
+}
+
+type byService string
+
+func (b byService) isBy() {
+}
+
+type byRuntime string
+
+func (b byRuntime) isBy() {
+}
+
+// ByRuntime creates an object to pass to Find to select by runtime.
+func ByRuntime(runtime string) By {
+ return byRuntime(runtime)
+}
+
+// ByServiceID creates an object to pass to Find to select by service.
+func ByServiceID(serviceID string) By {
+ return byService(serviceID)
+}
+
+type byNode string
+
+func (b byNode) isBy() {
+}
+
+// ByNodeID creates an object to pass to Find to select by node.
+func ByNodeID(nodeID string) By {
+ return byNode(nodeID)
+}
+
+type bySlot struct {
+ serviceID string
+ slot uint64
+}
+
+func (b bySlot) isBy() {
+}
+
+// BySlot creates an object to pass to Find to select by slot.
+func BySlot(serviceID string, slot uint64) By {
+ return bySlot{serviceID: serviceID, slot: slot}
+}
+
+type byDesiredState api.TaskState
+
+func (b byDesiredState) isBy() {
+}
+
+// ByDesiredState creates an object to pass to Find to select by desired state.
+func ByDesiredState(state api.TaskState) By {
+ return byDesiredState(state)
+}
+
+type byTaskState api.TaskState
+
+func (b byTaskState) isBy() {
+}
+
+// ByTaskState creates an object to pass to Find to select by task state.
+func ByTaskState(state api.TaskState) By {
+ return byTaskState(state)
+}
+
+type byRole api.NodeRole
+
+func (b byRole) isBy() {
+}
+
+// ByRole creates an object to pass to Find to select by role.
+func ByRole(role api.NodeRole) By {
+ return byRole(role)
+}
+
+type byMembership api.NodeSpec_Membership
+
+func (b byMembership) isBy() {
+}
+
+// ByMembership creates an object to pass to Find to select by Membership.
+func ByMembership(membership api.NodeSpec_Membership) By {
+ return byMembership(membership)
+}
+
+type byReferencedNetworkID string
+
+func (b byReferencedNetworkID) isBy() {
+}
+
+// ByReferencedNetworkID creates an object to pass to Find to search for a
+// service or task that references a network with the given ID.
+func ByReferencedNetworkID(networkID string) By {
+ return byReferencedNetworkID(networkID)
+}
+
+type byReferencedSecretID string
+
+func (b byReferencedSecretID) isBy() {
+}
+
+// ByReferencedSecretID creates an object to pass to Find to search for a
+// service or task that references a secret with the given ID.
+func ByReferencedSecretID(secretID string) By {
+ return byReferencedSecretID(secretID)
+}
+
+type byReferencedConfigID string
+
+func (b byReferencedConfigID) isBy() {
+}
+
+// ByReferencedConfigID creates an object to pass to Find to search for a
+// service or task that references a config with the given ID.
+func ByReferencedConfigID(configID string) By {
+ return byReferencedConfigID(configID)
+}
+
+type byKind string
+
+func (b byKind) isBy() {
+}
+
+// ByKind creates an object to pass to Find to search for a Resource of a
+// particular kind.
+func ByKind(kind string) By {
+ return byKind(kind)
+}
+
+type byCustom struct {
+ objType string
+ index string
+ value string
+}
+
+func (b byCustom) isBy() {
+}
+
+// ByCustom creates an object to pass to Find to search a custom index.
+func ByCustom(objType, index, value string) By {
+ return byCustom{
+ objType: objType,
+ index: index,
+ value: value,
+ }
+}
+
+type byCustomPrefix struct {
+ objType string
+ index string
+ value string
+}
+
+func (b byCustomPrefix) isBy() {
+}
+
+// ByCustomPrefix creates an object to pass to Find to search a custom index by
+// a value prefix.
+func ByCustomPrefix(objType, index, value string) By {
+ return byCustomPrefix{
+ objType: objType,
+ index: index,
+ value: value,
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/clusters.go b/vendor/github.com/docker/swarmkit/manager/state/store/clusters.go
new file mode 100644
index 0000000..a495dac
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/clusters.go
@@ -0,0 +1,138 @@
+package store
+
+import (
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ memdb "github.com/hashicorp/go-memdb"
+)
+
+const (
+ tableCluster = "cluster"
+
+ // DefaultClusterName is the default name to use for the cluster
+ // object.
+ DefaultClusterName = "default"
+)
+
+func init() {
+ register(ObjectStoreConfig{
+ Table: &memdb.TableSchema{
+ Name: tableCluster,
+ Indexes: map[string]*memdb.IndexSchema{
+ indexID: {
+ Name: indexID,
+ Unique: true,
+ Indexer: api.ClusterIndexerByID{},
+ },
+ indexName: {
+ Name: indexName,
+ Unique: true,
+ Indexer: api.ClusterIndexerByName{},
+ },
+ indexCustom: {
+ Name: indexCustom,
+ Indexer: api.ClusterCustomIndexer{},
+ AllowMissing: true,
+ },
+ },
+ },
+ Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
+ var err error
+ snapshot.Clusters, err = FindClusters(tx, All)
+ return err
+ },
+ Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
+ clusters, err := FindClusters(tx, All)
+ if err != nil {
+ return err
+ }
+ for _, n := range clusters {
+ if err := DeleteCluster(tx, n.ID); err != nil {
+ return err
+ }
+ }
+ for _, n := range snapshot.Clusters {
+ if err := CreateCluster(tx, n); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ ApplyStoreAction: func(tx Tx, sa api.StoreAction) error {
+ switch v := sa.Target.(type) {
+ case *api.StoreAction_Cluster:
+ obj := v.Cluster
+ switch sa.Action {
+ case api.StoreActionKindCreate:
+ return CreateCluster(tx, obj)
+ case api.StoreActionKindUpdate:
+ return UpdateCluster(tx, obj)
+ case api.StoreActionKindRemove:
+ return DeleteCluster(tx, obj.ID)
+ }
+ }
+ return errUnknownStoreAction
+ },
+ })
+}
+
+// CreateCluster adds a new cluster to the store.
+// Returns ErrExist if the ID is already taken.
+func CreateCluster(tx Tx, c *api.Cluster) error {
+ // Ensure the name is not already in use.
+ if tx.lookup(tableCluster, indexName, strings.ToLower(c.Spec.Annotations.Name)) != nil {
+ return ErrNameConflict
+ }
+
+ return tx.create(tableCluster, c)
+}
+
+// UpdateCluster updates an existing cluster in the store.
+// Returns ErrNotExist if the cluster doesn't exist.
+func UpdateCluster(tx Tx, c *api.Cluster) error {
+ // Ensure the name is either not in use or already used by this same Cluster.
+ if existing := tx.lookup(tableCluster, indexName, strings.ToLower(c.Spec.Annotations.Name)); existing != nil {
+ if existing.GetID() != c.ID {
+ return ErrNameConflict
+ }
+ }
+
+ return tx.update(tableCluster, c)
+}
+
+// DeleteCluster removes a cluster from the store.
+// Returns ErrNotExist if the cluster doesn't exist.
+func DeleteCluster(tx Tx, id string) error {
+ return tx.delete(tableCluster, id)
+}
+
+// GetCluster looks up a cluster by ID.
+// Returns nil if the cluster doesn't exist.
+func GetCluster(tx ReadTx, id string) *api.Cluster {
+ n := tx.get(tableCluster, id)
+ if n == nil {
+ return nil
+ }
+ return n.(*api.Cluster)
+}
+
+// FindClusters selects a set of clusters and returns them.
+func FindClusters(tx ReadTx, by By) ([]*api.Cluster, error) {
+ checkType := func(by By) error {
+ switch by.(type) {
+ case byName, byNamePrefix, byIDPrefix, byCustom, byCustomPrefix:
+ return nil
+ default:
+ return ErrInvalidFindBy
+ }
+ }
+
+ clusterList := []*api.Cluster{}
+ appendResult := func(o api.StoreObject) {
+ clusterList = append(clusterList, o.(*api.Cluster))
+ }
+
+ err := tx.find(tableCluster, by, checkType, appendResult)
+ return clusterList, err
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/combinators.go b/vendor/github.com/docker/swarmkit/manager/state/store/combinators.go
new file mode 100644
index 0000000..7cea6b4
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/combinators.go
@@ -0,0 +1,14 @@
+package store
+
+type orCombinator struct {
+ bys []By
+}
+
+func (b orCombinator) isBy() {
+}
+
+// Or returns a combinator that applies OR logic on all the supplied By
+// arguments.
+func Or(bys ...By) By {
+ return orCombinator{bys: bys}
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/configs.go b/vendor/github.com/docker/swarmkit/manager/state/store/configs.go
new file mode 100644
index 0000000..2bd44ae
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/configs.go
@@ -0,0 +1,132 @@
+package store
+
+import (
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ memdb "github.com/hashicorp/go-memdb"
+)
+
+const tableConfig = "config"
+
+func init() {
+ register(ObjectStoreConfig{
+ Table: &memdb.TableSchema{
+ Name: tableConfig,
+ Indexes: map[string]*memdb.IndexSchema{
+ indexID: {
+ Name: indexID,
+ Unique: true,
+ Indexer: api.ConfigIndexerByID{},
+ },
+ indexName: {
+ Name: indexName,
+ Unique: true,
+ Indexer: api.ConfigIndexerByName{},
+ },
+ indexCustom: {
+ Name: indexCustom,
+ Indexer: api.ConfigCustomIndexer{},
+ AllowMissing: true,
+ },
+ },
+ },
+ Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
+ var err error
+ snapshot.Configs, err = FindConfigs(tx, All)
+ return err
+ },
+ Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
+ configs, err := FindConfigs(tx, All)
+ if err != nil {
+ return err
+ }
+ for _, s := range configs {
+ if err := DeleteConfig(tx, s.ID); err != nil {
+ return err
+ }
+ }
+ for _, s := range snapshot.Configs {
+ if err := CreateConfig(tx, s); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ ApplyStoreAction: func(tx Tx, sa api.StoreAction) error {
+ switch v := sa.Target.(type) {
+ case *api.StoreAction_Config:
+ obj := v.Config
+ switch sa.Action {
+ case api.StoreActionKindCreate:
+ return CreateConfig(tx, obj)
+ case api.StoreActionKindUpdate:
+ return UpdateConfig(tx, obj)
+ case api.StoreActionKindRemove:
+ return DeleteConfig(tx, obj.ID)
+ }
+ }
+ return errUnknownStoreAction
+ },
+ })
+}
+
+// CreateConfig adds a new config to the store.
+// Returns ErrExist if the ID is already taken.
+func CreateConfig(tx Tx, c *api.Config) error {
+ // Ensure the name is not already in use.
+ if tx.lookup(tableConfig, indexName, strings.ToLower(c.Spec.Annotations.Name)) != nil {
+ return ErrNameConflict
+ }
+
+ return tx.create(tableConfig, c)
+}
+
+// UpdateConfig updates an existing config in the store.
+// Returns ErrNotExist if the config doesn't exist.
+func UpdateConfig(tx Tx, c *api.Config) error {
+ // Ensure the name is either not in use or already used by this same Config.
+ if existing := tx.lookup(tableConfig, indexName, strings.ToLower(c.Spec.Annotations.Name)); existing != nil {
+ if existing.GetID() != c.ID {
+ return ErrNameConflict
+ }
+ }
+
+ return tx.update(tableConfig, c)
+}
+
+// DeleteConfig removes a config from the store.
+// Returns ErrNotExist if the config doesn't exist.
+func DeleteConfig(tx Tx, id string) error {
+ return tx.delete(tableConfig, id)
+}
+
+// GetConfig looks up a config by ID.
+// Returns nil if the config doesn't exist.
+func GetConfig(tx ReadTx, id string) *api.Config {
+ c := tx.get(tableConfig, id)
+ if c == nil {
+ return nil
+ }
+ return c.(*api.Config)
+}
+
+// FindConfigs selects a set of configs and returns them.
+func FindConfigs(tx ReadTx, by By) ([]*api.Config, error) {
+ checkType := func(by By) error {
+ switch by.(type) {
+ case byName, byNamePrefix, byIDPrefix, byCustom, byCustomPrefix:
+ return nil
+ default:
+ return ErrInvalidFindBy
+ }
+ }
+
+ configList := []*api.Config{}
+ appendResult := func(o api.StoreObject) {
+ configList = append(configList, o.(*api.Config))
+ }
+
+ err := tx.find(tableConfig, by, checkType, appendResult)
+ return configList, err
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/doc.go b/vendor/github.com/docker/swarmkit/manager/state/store/doc.go
new file mode 100644
index 0000000..660c7c6
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/doc.go
@@ -0,0 +1,32 @@
+// Package store provides interfaces to work with swarm cluster state.
+//
+// The primary interface is MemoryStore, which abstracts storage of this cluster
+// state. MemoryStore exposes a transactional interface for both reads and writes.
+// To perform a read transaction, View accepts a callback function that it
+// will invoke with a ReadTx object that gives it a consistent view of the
+// state. Similarly, Update accepts a callback function that it will invoke with
+// a Tx object that allows reads and writes to happen without interference from
+// other transactions.
+//
+// This is an example of making an update to a MemoryStore:
+//
+// err := store.Update(func(tx store.Tx) {
+// if err := tx.Nodes().Update(newNode); err != nil {
+// return err
+// }
+// return nil
+// })
+// if err != nil {
+// return fmt.Errorf("transaction failed: %v", err)
+// }
+//
+// MemoryStore exposes watch functionality.
+// It exposes a publish/subscribe queue where code can subscribe to
+// changes of interest. This can be combined with the ViewAndWatch function to
+// "fork" a store, by making a snapshot and then applying future changes
+// to keep the copy in sync. This approach lets consumers of the data
+// use their own data structures and implement their own concurrency
+// strategies. It can lead to more efficient code because data consumers
+// don't necessarily have to lock the main data store if they are
+// maintaining their own copies of the state.
+package store
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/extensions.go b/vendor/github.com/docker/swarmkit/manager/state/store/extensions.go
new file mode 100644
index 0000000..627d87d
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/extensions.go
@@ -0,0 +1,190 @@
+package store
+
+import (
+ "errors"
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ memdb "github.com/hashicorp/go-memdb"
+)
+
+const tableExtension = "extension"
+
+func init() {
+ register(ObjectStoreConfig{
+ Table: &memdb.TableSchema{
+ Name: tableExtension,
+ Indexes: map[string]*memdb.IndexSchema{
+ indexID: {
+ Name: indexID,
+ Unique: true,
+ Indexer: extensionIndexerByID{},
+ },
+ indexName: {
+ Name: indexName,
+ Unique: true,
+ Indexer: extensionIndexerByName{},
+ },
+ indexCustom: {
+ Name: indexCustom,
+ Indexer: extensionCustomIndexer{},
+ AllowMissing: true,
+ },
+ },
+ },
+ Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
+ var err error
+ snapshot.Extensions, err = FindExtensions(tx, All)
+ return err
+ },
+ Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
+ extensions, err := FindExtensions(tx, All)
+ if err != nil {
+ return err
+ }
+ for _, e := range extensions {
+ if err := DeleteExtension(tx, e.ID); err != nil {
+ return err
+ }
+ }
+ for _, e := range snapshot.Extensions {
+ if err := CreateExtension(tx, e); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ ApplyStoreAction: func(tx Tx, sa api.StoreAction) error {
+ switch v := sa.Target.(type) {
+ case *api.StoreAction_Extension:
+ obj := v.Extension
+ switch sa.Action {
+ case api.StoreActionKindCreate:
+ return CreateExtension(tx, obj)
+ case api.StoreActionKindUpdate:
+ return UpdateExtension(tx, obj)
+ case api.StoreActionKindRemove:
+ return DeleteExtension(tx, obj.ID)
+ }
+ }
+ return errUnknownStoreAction
+ },
+ })
+}
+
+type extensionEntry struct {
+ *api.Extension
+}
+
+func (e extensionEntry) CopyStoreObject() api.StoreObject {
+ return extensionEntry{Extension: e.Extension.Copy()}
+}
+
+// CreateExtension adds a new extension to the store.
+// Returns ErrExist if the ID is already taken.
+func CreateExtension(tx Tx, e *api.Extension) error {
+ // Ensure the name is not already in use.
+ if tx.lookup(tableExtension, indexName, strings.ToLower(e.Annotations.Name)) != nil {
+ return ErrNameConflict
+ }
+
+ // It can't conflict with built-in kinds either.
+ if _, ok := schema.Tables[e.Annotations.Name]; ok {
+ return ErrNameConflict
+ }
+
+ return tx.create(tableExtension, extensionEntry{e})
+}
+
+// UpdateExtension updates an existing extension in the store.
+// Returns ErrNotExist if the object doesn't exist.
+func UpdateExtension(tx Tx, e *api.Extension) error {
+ // TODO(aaronl): For the moment, extensions are immutable
+ return errors.New("extensions are immutable")
+}
+
+// DeleteExtension removes an extension from the store.
+// Returns ErrNotExist if the object doesn't exist.
+func DeleteExtension(tx Tx, id string) error {
+ e := tx.get(tableExtension, id)
+ if e == nil {
+ return ErrNotExist
+ }
+
+ resources, err := FindResources(tx, ByKind(e.(extensionEntry).Annotations.Name))
+ if err != nil {
+ return err
+ }
+
+ if len(resources) != 0 {
+ return errors.New("cannot delete extension because objects of this type exist in the data store")
+ }
+
+ return tx.delete(tableExtension, id)
+}
+
+// GetExtension looks up an extension by ID.
+// Returns nil if the object doesn't exist.
+func GetExtension(tx ReadTx, id string) *api.Extension {
+ e := tx.get(tableExtension, id)
+ if e == nil {
+ return nil
+ }
+ return e.(extensionEntry).Extension
+}
+
+// FindExtensions selects a set of extensions and returns them.
+func FindExtensions(tx ReadTx, by By) ([]*api.Extension, error) {
+ checkType := func(by By) error {
+ switch by.(type) {
+ case byIDPrefix, byName, byCustom, byCustomPrefix:
+ return nil
+ default:
+ return ErrInvalidFindBy
+ }
+ }
+
+ extensionList := []*api.Extension{}
+ appendResult := func(o api.StoreObject) {
+ extensionList = append(extensionList, o.(extensionEntry).Extension)
+ }
+
+ err := tx.find(tableExtension, by, checkType, appendResult)
+ return extensionList, err
+}
+
+type extensionIndexerByID struct{}
+
+func (indexer extensionIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return api.ExtensionIndexerByID{}.FromArgs(args...)
+}
+func (indexer extensionIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return api.ExtensionIndexerByID{}.PrefixFromArgs(args...)
+}
+func (indexer extensionIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ return api.ExtensionIndexerByID{}.FromObject(obj.(extensionEntry).Extension)
+}
+
+type extensionIndexerByName struct{}
+
+func (indexer extensionIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return api.ExtensionIndexerByName{}.FromArgs(args...)
+}
+func (indexer extensionIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return api.ExtensionIndexerByName{}.PrefixFromArgs(args...)
+}
+func (indexer extensionIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ return api.ExtensionIndexerByName{}.FromObject(obj.(extensionEntry).Extension)
+}
+
+type extensionCustomIndexer struct{}
+
+func (indexer extensionCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return api.ExtensionCustomIndexer{}.FromArgs(args...)
+}
+func (indexer extensionCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return api.ExtensionCustomIndexer{}.PrefixFromArgs(args...)
+}
+func (indexer extensionCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ return api.ExtensionCustomIndexer{}.FromObject(obj.(extensionEntry).Extension)
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/memory.go b/vendor/github.com/docker/swarmkit/manager/state/store/memory.go
new file mode 100644
index 0000000..62ab927
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/memory.go
@@ -0,0 +1,941 @@
+package store
+
+import (
+ "errors"
+ "fmt"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ pb "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/watch"
+ gogotypes "github.com/gogo/protobuf/types"
+ memdb "github.com/hashicorp/go-memdb"
+ "golang.org/x/net/context"
+)
+
+const (
+ indexID = "id"
+ indexName = "name"
+ indexRuntime = "runtime"
+ indexServiceID = "serviceid"
+ indexNodeID = "nodeid"
+ indexSlot = "slot"
+ indexDesiredState = "desiredstate"
+ indexTaskState = "taskstate"
+ indexRole = "role"
+ indexMembership = "membership"
+ indexNetwork = "network"
+ indexSecret = "secret"
+ indexConfig = "config"
+ indexKind = "kind"
+ indexCustom = "custom"
+
+ prefix = "_prefix"
+
+ // MaxChangesPerTransaction is the number of changes after which a new
+ // transaction should be started within Batch.
+ MaxChangesPerTransaction = 200
+
+ // MaxTransactionBytes is the maximum serialized transaction size.
+ MaxTransactionBytes = 1.5 * 1024 * 1024
+)
+
+var (
+ // ErrExist is returned by create operations if the provided ID is already
+ // taken.
+ ErrExist = errors.New("object already exists")
+
+ // ErrNotExist is returned by altering operations (update, delete) if the
+ // provided ID is not found.
+ ErrNotExist = errors.New("object does not exist")
+
+ // ErrNameConflict is returned by create/update if the object name is
+ // already in use by another object.
+ ErrNameConflict = errors.New("name conflicts with an existing object")
+
+ // ErrInvalidFindBy is returned if an unrecognized type is passed to Find.
+ ErrInvalidFindBy = errors.New("invalid find argument type")
+
+ // ErrSequenceConflict is returned when trying to update an object
+ // whose sequence information does not match the object in the store's.
+ ErrSequenceConflict = errors.New("update out of sequence")
+
+ objectStorers []ObjectStoreConfig
+ schema = &memdb.DBSchema{
+ Tables: map[string]*memdb.TableSchema{},
+ }
+ errUnknownStoreAction = errors.New("unknown store action")
+
+ // WedgeTimeout is the maximum amount of time the store lock may be
+ // held before declaring a suspected deadlock.
+ WedgeTimeout = 30 * time.Second
+)
+
+func register(os ObjectStoreConfig) {
+ objectStorers = append(objectStorers, os)
+ schema.Tables[os.Table.Name] = os.Table
+}
+
+// timedMutex wraps a sync.Mutex, and keeps track of how long it has been
+// locked.
+type timedMutex struct {
+ sync.Mutex
+ lockedAt atomic.Value
+}
+
+func (m *timedMutex) Lock() {
+ m.Mutex.Lock()
+ m.lockedAt.Store(time.Now())
+}
+
+func (m *timedMutex) Unlock() {
+ m.Mutex.Unlock()
+ m.lockedAt.Store(time.Time{})
+}
+
+func (m *timedMutex) LockedAt() time.Time {
+ lockedTimestamp := m.lockedAt.Load()
+ if lockedTimestamp == nil {
+ return time.Time{}
+ }
+ return lockedTimestamp.(time.Time)
+}
+
+// MemoryStore is a concurrency-safe, in-memory implementation of the Store
+// interface.
+type MemoryStore struct {
+ // updateLock must be held during an update transaction.
+ updateLock timedMutex
+
+ memDB *memdb.MemDB
+ queue *watch.Queue
+
+ proposer state.Proposer
+}
+
+// NewMemoryStore returns an in-memory store. The argument is an optional
+// Proposer which will be used to propagate changes to other members in a
+// cluster.
+func NewMemoryStore(proposer state.Proposer) *MemoryStore {
+ memDB, err := memdb.NewMemDB(schema)
+ if err != nil {
+ // This shouldn't fail
+ panic(err)
+ }
+
+ return &MemoryStore{
+ memDB: memDB,
+ queue: watch.NewQueue(),
+ proposer: proposer,
+ }
+}
+
+// Close closes the memory store and frees its associated resources.
+func (s *MemoryStore) Close() error {
+ return s.queue.Close()
+}
+
+func fromArgs(args ...interface{}) ([]byte, error) {
+ if len(args) != 1 {
+ return nil, fmt.Errorf("must provide only a single argument")
+ }
+ arg, ok := args[0].(string)
+ if !ok {
+ return nil, fmt.Errorf("argument must be a string: %#v", args[0])
+ }
+ // Add the null character as a terminator
+ arg += "\x00"
+ return []byte(arg), nil
+}
+
+func prefixFromArgs(args ...interface{}) ([]byte, error) {
+ val, err := fromArgs(args...)
+ if err != nil {
+ return nil, err
+ }
+
+ // Strip the null terminator, the rest is a prefix
+ n := len(val)
+ if n > 0 {
+ return val[:n-1], nil
+ }
+ return val, nil
+}
+
+// ReadTx is a read transaction. Note that transaction does not imply
+// any internal batching. It only means that the transaction presents a
+// consistent view of the data that cannot be affected by other
+// transactions.
+type ReadTx interface {
+ lookup(table, index, id string) api.StoreObject
+ get(table, id string) api.StoreObject
+ find(table string, by By, checkType func(By) error, appendResult func(api.StoreObject)) error
+}
+
+type readTx struct {
+ memDBTx *memdb.Txn
+}
+
+// View executes a read transaction.
+func (s *MemoryStore) View(cb func(ReadTx)) {
+ memDBTx := s.memDB.Txn(false)
+
+ readTx := readTx{
+ memDBTx: memDBTx,
+ }
+ cb(readTx)
+ memDBTx.Commit()
+}
+
+// Tx is a read/write transaction. Note that transaction does not imply
+// any internal batching. The purpose of this transaction is to give the
+// user a guarantee that its changes won't be visible to other transactions
+// until the transaction is over.
+type Tx interface {
+ ReadTx
+ create(table string, o api.StoreObject) error
+ update(table string, o api.StoreObject) error
+ delete(table, id string) error
+}
+
+type tx struct {
+ readTx
+ curVersion *api.Version
+ changelist []api.Event
+}
+
+// changelistBetweenVersions returns the changes after "from" up to and
+// including "to".
+func (s *MemoryStore) changelistBetweenVersions(from, to api.Version) ([]api.Event, error) {
+ if s.proposer == nil {
+ return nil, errors.New("store does not support versioning")
+ }
+ changes, err := s.proposer.ChangesBetween(from, to)
+ if err != nil {
+ return nil, err
+ }
+
+ var changelist []api.Event
+
+ for _, change := range changes {
+ for _, sa := range change.StoreActions {
+ event, err := api.EventFromStoreAction(sa, nil)
+ if err != nil {
+ return nil, err
+ }
+ changelist = append(changelist, event)
+ }
+ changelist = append(changelist, state.EventCommit{Version: change.Version.Copy()})
+ }
+
+ return changelist, nil
+}
+
+// ApplyStoreActions updates a store based on StoreAction messages.
+func (s *MemoryStore) ApplyStoreActions(actions []api.StoreAction) error {
+ s.updateLock.Lock()
+ memDBTx := s.memDB.Txn(true)
+
+ tx := tx{
+ readTx: readTx{
+ memDBTx: memDBTx,
+ },
+ }
+
+ for _, sa := range actions {
+ if err := applyStoreAction(&tx, sa); err != nil {
+ memDBTx.Abort()
+ s.updateLock.Unlock()
+ return err
+ }
+ }
+
+ memDBTx.Commit()
+
+ for _, c := range tx.changelist {
+ s.queue.Publish(c)
+ }
+ if len(tx.changelist) != 0 {
+ s.queue.Publish(state.EventCommit{})
+ }
+ s.updateLock.Unlock()
+ return nil
+}
+
+func applyStoreAction(tx Tx, sa api.StoreAction) error {
+ for _, os := range objectStorers {
+ err := os.ApplyStoreAction(tx, sa)
+ if err != errUnknownStoreAction {
+ return err
+ }
+ }
+
+ return errors.New("unrecognized action type")
+}
+
+func (s *MemoryStore) update(proposer state.Proposer, cb func(Tx) error) error {
+ s.updateLock.Lock()
+ memDBTx := s.memDB.Txn(true)
+
+ var curVersion *api.Version
+
+ if proposer != nil {
+ curVersion = proposer.GetVersion()
+ }
+
+ var tx tx
+ tx.init(memDBTx, curVersion)
+
+ err := cb(&tx)
+
+ if err == nil {
+ if proposer == nil {
+ memDBTx.Commit()
+ } else {
+ var sa []api.StoreAction
+ sa, err = tx.changelistStoreActions()
+
+ if err == nil {
+ if len(sa) != 0 {
+ err = proposer.ProposeValue(context.Background(), sa, func() {
+ memDBTx.Commit()
+ })
+ } else {
+ memDBTx.Commit()
+ }
+ }
+ }
+ }
+
+ if err == nil {
+ for _, c := range tx.changelist {
+ s.queue.Publish(c)
+ }
+ if len(tx.changelist) != 0 {
+ if proposer != nil {
+ curVersion = proposer.GetVersion()
+ }
+
+ s.queue.Publish(state.EventCommit{Version: curVersion})
+ }
+ } else {
+ memDBTx.Abort()
+ }
+ s.updateLock.Unlock()
+ return err
+
+}
+
+func (s *MemoryStore) updateLocal(cb func(Tx) error) error {
+ return s.update(nil, cb)
+}
+
+// Update executes a read/write transaction.
+func (s *MemoryStore) Update(cb func(Tx) error) error {
+ return s.update(s.proposer, cb)
+}
+
+// Batch provides a mechanism to batch updates to a store.
+type Batch struct {
+ tx tx
+ store *MemoryStore
+ // applied counts the times Update has run successfully
+ applied int
+ // transactionSizeEstimate is the running count of the size of the
+ // current transaction.
+ transactionSizeEstimate int
+ // changelistLen is the last known length of the transaction's
+ // changelist.
+ changelistLen int
+ err error
+}
+
+// Update adds a single change to a batch. Each call to Update is atomic, but
+// different calls to Update may be spread across multiple transactions to
+// circumvent transaction size limits.
+func (batch *Batch) Update(cb func(Tx) error) error {
+ if batch.err != nil {
+ return batch.err
+ }
+
+ if err := cb(&batch.tx); err != nil {
+ return err
+ }
+
+ batch.applied++
+
+ for batch.changelistLen < len(batch.tx.changelist) {
+ sa, err := api.NewStoreAction(batch.tx.changelist[batch.changelistLen])
+ if err != nil {
+ return err
+ }
+ batch.transactionSizeEstimate += sa.Size()
+ batch.changelistLen++
+ }
+
+ if batch.changelistLen >= MaxChangesPerTransaction || batch.transactionSizeEstimate >= (MaxTransactionBytes*3)/4 {
+ if err := batch.commit(); err != nil {
+ return err
+ }
+
+ // Yield the update lock
+ batch.store.updateLock.Unlock()
+ runtime.Gosched()
+ batch.store.updateLock.Lock()
+
+ batch.newTx()
+ }
+
+ return nil
+}
+
+func (batch *Batch) newTx() {
+ var curVersion *api.Version
+
+ if batch.store.proposer != nil {
+ curVersion = batch.store.proposer.GetVersion()
+ }
+
+ batch.tx.init(batch.store.memDB.Txn(true), curVersion)
+ batch.transactionSizeEstimate = 0
+ batch.changelistLen = 0
+}
+
+func (batch *Batch) commit() error {
+ if batch.store.proposer != nil {
+ var sa []api.StoreAction
+ sa, batch.err = batch.tx.changelistStoreActions()
+
+ if batch.err == nil {
+ if len(sa) != 0 {
+ batch.err = batch.store.proposer.ProposeValue(context.Background(), sa, func() {
+ batch.tx.memDBTx.Commit()
+ })
+ } else {
+ batch.tx.memDBTx.Commit()
+ }
+ }
+ } else {
+ batch.tx.memDBTx.Commit()
+ }
+
+ if batch.err != nil {
+ batch.tx.memDBTx.Abort()
+ return batch.err
+ }
+
+ for _, c := range batch.tx.changelist {
+ batch.store.queue.Publish(c)
+ }
+ if len(batch.tx.changelist) != 0 {
+ batch.store.queue.Publish(state.EventCommit{})
+ }
+
+ return nil
+}
+
+// Batch performs one or more transactions that allow reads and writes
+// It invokes a callback that is passed a Batch object. The callback may
+// call batch.Update for each change it wants to make as part of the
+// batch. The changes in the batch may be split over multiple
+// transactions if necessary to keep transactions below the size limit.
+// Batch holds a lock over the state, but will yield this lock every
+// it creates a new transaction to allow other writers to proceed.
+// Thus, unrelated changes to the state may occur between calls to
+// batch.Update.
+//
+// This method allows the caller to iterate over a data set and apply
+// changes in sequence without holding the store write lock for an
+// excessive time, or producing a transaction that exceeds the maximum
+// size.
+//
+// If Batch returns an error, no guarantees are made about how many updates
+// were committed successfully.
+func (s *MemoryStore) Batch(cb func(*Batch) error) error {
+ s.updateLock.Lock()
+
+ batch := Batch{
+ store: s,
+ }
+ batch.newTx()
+
+ if err := cb(&batch); err != nil {
+ batch.tx.memDBTx.Abort()
+ s.updateLock.Unlock()
+ return err
+ }
+
+ err := batch.commit()
+ s.updateLock.Unlock()
+ return err
+}
+
+func (tx *tx) init(memDBTx *memdb.Txn, curVersion *api.Version) {
+ tx.memDBTx = memDBTx
+ tx.curVersion = curVersion
+ tx.changelist = nil
+}
+
+func (tx tx) changelistStoreActions() ([]api.StoreAction, error) {
+ var actions []api.StoreAction
+
+ for _, c := range tx.changelist {
+ sa, err := api.NewStoreAction(c)
+ if err != nil {
+ return nil, err
+ }
+ actions = append(actions, sa)
+ }
+
+ return actions, nil
+}
+
+// lookup is an internal typed wrapper around memdb.
+func (tx readTx) lookup(table, index, id string) api.StoreObject {
+ j, err := tx.memDBTx.First(table, index, id)
+ if err != nil {
+ return nil
+ }
+ if j != nil {
+ return j.(api.StoreObject)
+ }
+ return nil
+}
+
+// create adds a new object to the store.
+// Returns ErrExist if the ID is already taken.
+func (tx *tx) create(table string, o api.StoreObject) error {
+ if tx.lookup(table, indexID, o.GetID()) != nil {
+ return ErrExist
+ }
+
+ copy := o.CopyStoreObject()
+ meta := copy.GetMeta()
+ if err := touchMeta(&meta, tx.curVersion); err != nil {
+ return err
+ }
+ copy.SetMeta(meta)
+
+ err := tx.memDBTx.Insert(table, copy)
+ if err == nil {
+ tx.changelist = append(tx.changelist, copy.EventCreate())
+ o.SetMeta(meta)
+ }
+ return err
+}
+
+// Update updates an existing object in the store.
+// Returns ErrNotExist if the object doesn't exist.
+func (tx *tx) update(table string, o api.StoreObject) error {
+ oldN := tx.lookup(table, indexID, o.GetID())
+ if oldN == nil {
+ return ErrNotExist
+ }
+
+ meta := o.GetMeta()
+
+ if tx.curVersion != nil {
+ if oldN.GetMeta().Version != meta.Version {
+ return ErrSequenceConflict
+ }
+ }
+
+ copy := o.CopyStoreObject()
+ if err := touchMeta(&meta, tx.curVersion); err != nil {
+ return err
+ }
+ copy.SetMeta(meta)
+
+ err := tx.memDBTx.Insert(table, copy)
+ if err == nil {
+ tx.changelist = append(tx.changelist, copy.EventUpdate(oldN))
+ o.SetMeta(meta)
+ }
+ return err
+}
+
+// Delete removes an object from the store.
+// Returns ErrNotExist if the object doesn't exist.
+func (tx *tx) delete(table, id string) error {
+ n := tx.lookup(table, indexID, id)
+ if n == nil {
+ return ErrNotExist
+ }
+
+ err := tx.memDBTx.Delete(table, n)
+ if err == nil {
+ tx.changelist = append(tx.changelist, n.EventDelete())
+ }
+ return err
+}
+
+// Get looks up an object by ID.
+// Returns nil if the object doesn't exist.
+func (tx readTx) get(table, id string) api.StoreObject {
+ o := tx.lookup(table, indexID, id)
+ if o == nil {
+ return nil
+ }
+ return o.CopyStoreObject()
+}
+
+// findIterators returns a slice of iterators. The union of items from these
+// iterators provides the result of the query.
+func (tx readTx) findIterators(table string, by By, checkType func(By) error) ([]memdb.ResultIterator, error) {
+ switch by.(type) {
+ case byAll, orCombinator: // generic types
+ default: // all other types
+ if err := checkType(by); err != nil {
+ return nil, err
+ }
+ }
+
+ switch v := by.(type) {
+ case byAll:
+ it, err := tx.memDBTx.Get(table, indexID)
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case orCombinator:
+ var iters []memdb.ResultIterator
+ for _, subBy := range v.bys {
+ it, err := tx.findIterators(table, subBy, checkType)
+ if err != nil {
+ return nil, err
+ }
+ iters = append(iters, it...)
+ }
+ return iters, nil
+ case byName:
+ it, err := tx.memDBTx.Get(table, indexName, strings.ToLower(string(v)))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byIDPrefix:
+ it, err := tx.memDBTx.Get(table, indexID+prefix, string(v))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byNamePrefix:
+ it, err := tx.memDBTx.Get(table, indexName+prefix, strings.ToLower(string(v)))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byRuntime:
+ it, err := tx.memDBTx.Get(table, indexRuntime, string(v))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byNode:
+ it, err := tx.memDBTx.Get(table, indexNodeID, string(v))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byService:
+ it, err := tx.memDBTx.Get(table, indexServiceID, string(v))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case bySlot:
+ it, err := tx.memDBTx.Get(table, indexSlot, v.serviceID+"\x00"+strconv.FormatUint(uint64(v.slot), 10))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byDesiredState:
+ it, err := tx.memDBTx.Get(table, indexDesiredState, strconv.FormatInt(int64(v), 10))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byTaskState:
+ it, err := tx.memDBTx.Get(table, indexTaskState, strconv.FormatInt(int64(v), 10))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byRole:
+ it, err := tx.memDBTx.Get(table, indexRole, strconv.FormatInt(int64(v), 10))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byMembership:
+ it, err := tx.memDBTx.Get(table, indexMembership, strconv.FormatInt(int64(v), 10))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byReferencedNetworkID:
+ it, err := tx.memDBTx.Get(table, indexNetwork, string(v))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byReferencedSecretID:
+ it, err := tx.memDBTx.Get(table, indexSecret, string(v))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byReferencedConfigID:
+ it, err := tx.memDBTx.Get(table, indexConfig, string(v))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byKind:
+ it, err := tx.memDBTx.Get(table, indexKind, string(v))
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byCustom:
+ var key string
+ if v.objType != "" {
+ key = v.objType + "|" + v.index + "|" + v.value
+ } else {
+ key = v.index + "|" + v.value
+ }
+ it, err := tx.memDBTx.Get(table, indexCustom, key)
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ case byCustomPrefix:
+ var key string
+ if v.objType != "" {
+ key = v.objType + "|" + v.index + "|" + v.value
+ } else {
+ key = v.index + "|" + v.value
+ }
+ it, err := tx.memDBTx.Get(table, indexCustom+prefix, key)
+ if err != nil {
+ return nil, err
+ }
+ return []memdb.ResultIterator{it}, nil
+ default:
+ return nil, ErrInvalidFindBy
+ }
+}
+
+// find selects a set of objects calls a callback for each matching object.
+func (tx readTx) find(table string, by By, checkType func(By) error, appendResult func(api.StoreObject)) error {
+ fromResultIterators := func(its ...memdb.ResultIterator) {
+ ids := make(map[string]struct{})
+ for _, it := range its {
+ for {
+ obj := it.Next()
+ if obj == nil {
+ break
+ }
+ o := obj.(api.StoreObject)
+ id := o.GetID()
+ if _, exists := ids[id]; !exists {
+ appendResult(o.CopyStoreObject())
+ ids[id] = struct{}{}
+ }
+ }
+ }
+ }
+
+ iters, err := tx.findIterators(table, by, checkType)
+ if err != nil {
+ return err
+ }
+
+ fromResultIterators(iters...)
+
+ return nil
+}
+
+// Save serializes the data in the store.
+func (s *MemoryStore) Save(tx ReadTx) (*pb.StoreSnapshot, error) {
+ var snapshot pb.StoreSnapshot
+ for _, os := range objectStorers {
+ if err := os.Save(tx, &snapshot); err != nil {
+ return nil, err
+ }
+ }
+
+ return &snapshot, nil
+}
+
+// Restore sets the contents of the store to the serialized data in the
+// argument.
+func (s *MemoryStore) Restore(snapshot *pb.StoreSnapshot) error {
+ return s.updateLocal(func(tx Tx) error {
+ for _, os := range objectStorers {
+ if err := os.Restore(tx, snapshot); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
+
+// WatchQueue returns the publish/subscribe queue.
+func (s *MemoryStore) WatchQueue() *watch.Queue {
+ return s.queue
+}
+
+// ViewAndWatch calls a callback which can observe the state of this
+// MemoryStore. It also returns a channel that will return further events from
+// this point so the snapshot can be kept up to date. The watch channel must be
+// released with watch.StopWatch when it is no longer needed. The channel is
+// guaranteed to get all events after the moment of the snapshot, and only
+// those events.
+func ViewAndWatch(store *MemoryStore, cb func(ReadTx) error, specifiers ...api.Event) (watch chan events.Event, cancel func(), err error) {
+ // Using Update to lock the store and guarantee consistency between
+ // the watcher and the the state seen by the callback. snapshotReadTx
+ // exposes this Tx as a ReadTx so the callback can't modify it.
+ err = store.Update(func(tx Tx) error {
+ if err := cb(tx); err != nil {
+ return err
+ }
+ watch, cancel = state.Watch(store.WatchQueue(), specifiers...)
+ return nil
+ })
+ if watch != nil && err != nil {
+ cancel()
+ cancel = nil
+ watch = nil
+ }
+ return
+}
+
+// WatchFrom returns a channel that will return past events from starting
+// from "version", and new events until the channel is closed. If "version"
+// is nil, this function is equivalent to
+//
+// state.Watch(store.WatchQueue(), specifiers...).
+//
+// If the log has been compacted and it's not possible to produce the exact
+// set of events leading from "version" to the current state, this function
+// will return an error, and the caller should re-sync.
+//
+// The watch channel must be released with watch.StopWatch when it is no
+// longer needed.
+func WatchFrom(store *MemoryStore, version *api.Version, specifiers ...api.Event) (chan events.Event, func(), error) {
+ if version == nil {
+ ch, cancel := state.Watch(store.WatchQueue(), specifiers...)
+ return ch, cancel, nil
+ }
+
+ if store.proposer == nil {
+ return nil, nil, errors.New("store does not support versioning")
+ }
+
+ var (
+ curVersion *api.Version
+ watch chan events.Event
+ cancelWatch func()
+ )
+ // Using Update to lock the store
+ err := store.Update(func(tx Tx) error {
+ // Get current version
+ curVersion = store.proposer.GetVersion()
+ // Start the watch with the store locked so events cannot be
+ // missed
+ watch, cancelWatch = state.Watch(store.WatchQueue(), specifiers...)
+ return nil
+ })
+ if watch != nil && err != nil {
+ cancelWatch()
+ return nil, nil, err
+ }
+
+ if curVersion == nil {
+ cancelWatch()
+ return nil, nil, errors.New("could not get current version from store")
+ }
+
+ changelist, err := store.changelistBetweenVersions(*version, *curVersion)
+ if err != nil {
+ cancelWatch()
+ return nil, nil, err
+ }
+
+ ch := make(chan events.Event)
+ stop := make(chan struct{})
+ cancel := func() {
+ close(stop)
+ }
+
+ go func() {
+ defer cancelWatch()
+
+ matcher := state.Matcher(specifiers...)
+ for _, change := range changelist {
+ if matcher(change) {
+ select {
+ case ch <- change:
+ case <-stop:
+ return
+ }
+ }
+ }
+
+ for {
+ select {
+ case <-stop:
+ return
+ case e := <-watch:
+ ch <- e
+ }
+ }
+ }()
+
+ return ch, cancel, nil
+}
+
+// touchMeta updates an object's timestamps when necessary and bumps the version
+// if provided.
+func touchMeta(meta *api.Meta, version *api.Version) error {
+ // Skip meta update if version is not defined as it means we're applying
+ // from raft or restoring from a snapshot.
+ if version == nil {
+ return nil
+ }
+
+ now, err := gogotypes.TimestampProto(time.Now())
+ if err != nil {
+ return err
+ }
+
+ meta.Version = *version
+
+ // Updated CreatedAt if not defined
+ if meta.CreatedAt == nil {
+ meta.CreatedAt = now
+ }
+
+ meta.UpdatedAt = now
+
+ return nil
+}
+
+// Wedged returns true if the store lock has been held for a long time,
+// possibly indicating a deadlock.
+func (s *MemoryStore) Wedged() bool {
+ lockedAt := s.updateLock.LockedAt()
+ if lockedAt.IsZero() {
+ return false
+ }
+
+ return time.Since(lockedAt) > WedgeTimeout
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/networks.go b/vendor/github.com/docker/swarmkit/manager/state/store/networks.go
new file mode 100644
index 0000000..df549d4
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/networks.go
@@ -0,0 +1,132 @@
+package store
+
+import (
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ memdb "github.com/hashicorp/go-memdb"
+)
+
+const tableNetwork = "network"
+
+func init() {
+ register(ObjectStoreConfig{
+ Table: &memdb.TableSchema{
+ Name: tableNetwork,
+ Indexes: map[string]*memdb.IndexSchema{
+ indexID: {
+ Name: indexID,
+ Unique: true,
+ Indexer: api.NetworkIndexerByID{},
+ },
+ indexName: {
+ Name: indexName,
+ Unique: true,
+ Indexer: api.NetworkIndexerByName{},
+ },
+ indexCustom: {
+ Name: indexCustom,
+ Indexer: api.NetworkCustomIndexer{},
+ AllowMissing: true,
+ },
+ },
+ },
+ Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
+ var err error
+ snapshot.Networks, err = FindNetworks(tx, All)
+ return err
+ },
+ Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
+ networks, err := FindNetworks(tx, All)
+ if err != nil {
+ return err
+ }
+ for _, n := range networks {
+ if err := DeleteNetwork(tx, n.ID); err != nil {
+ return err
+ }
+ }
+ for _, n := range snapshot.Networks {
+ if err := CreateNetwork(tx, n); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ ApplyStoreAction: func(tx Tx, sa api.StoreAction) error {
+ switch v := sa.Target.(type) {
+ case *api.StoreAction_Network:
+ obj := v.Network
+ switch sa.Action {
+ case api.StoreActionKindCreate:
+ return CreateNetwork(tx, obj)
+ case api.StoreActionKindUpdate:
+ return UpdateNetwork(tx, obj)
+ case api.StoreActionKindRemove:
+ return DeleteNetwork(tx, obj.ID)
+ }
+ }
+ return errUnknownStoreAction
+ },
+ })
+}
+
+// CreateNetwork adds a new network to the store.
+// Returns ErrExist if the ID is already taken.
+func CreateNetwork(tx Tx, n *api.Network) error {
+ // Ensure the name is not already in use.
+ if tx.lookup(tableNetwork, indexName, strings.ToLower(n.Spec.Annotations.Name)) != nil {
+ return ErrNameConflict
+ }
+
+ return tx.create(tableNetwork, n)
+}
+
+// UpdateNetwork updates an existing network in the store.
+// Returns ErrNotExist if the network doesn't exist.
+func UpdateNetwork(tx Tx, n *api.Network) error {
+ // Ensure the name is either not in use or already used by this same Network.
+ if existing := tx.lookup(tableNetwork, indexName, strings.ToLower(n.Spec.Annotations.Name)); existing != nil {
+ if existing.GetID() != n.ID {
+ return ErrNameConflict
+ }
+ }
+
+ return tx.update(tableNetwork, n)
+}
+
+// DeleteNetwork removes a network from the store.
+// Returns ErrNotExist if the network doesn't exist.
+func DeleteNetwork(tx Tx, id string) error {
+ return tx.delete(tableNetwork, id)
+}
+
+// GetNetwork looks up a network by ID.
+// Returns nil if the network doesn't exist.
+func GetNetwork(tx ReadTx, id string) *api.Network {
+ n := tx.get(tableNetwork, id)
+ if n == nil {
+ return nil
+ }
+ return n.(*api.Network)
+}
+
+// FindNetworks selects a set of networks and returns them.
+func FindNetworks(tx ReadTx, by By) ([]*api.Network, error) {
+ checkType := func(by By) error {
+ switch by.(type) {
+ case byName, byNamePrefix, byIDPrefix, byCustom, byCustomPrefix:
+ return nil
+ default:
+ return ErrInvalidFindBy
+ }
+ }
+
+ networkList := []*api.Network{}
+ appendResult := func(o api.StoreObject) {
+ networkList = append(networkList, o.(*api.Network))
+ }
+
+ err := tx.find(tableNetwork, by, checkType, appendResult)
+ return networkList, err
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/nodes.go b/vendor/github.com/docker/swarmkit/manager/state/store/nodes.go
new file mode 100644
index 0000000..0661a16
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/nodes.go
@@ -0,0 +1,176 @@
+package store
+
+import (
+ "strconv"
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ memdb "github.com/hashicorp/go-memdb"
+)
+
+const tableNode = "node"
+
+func init() {
+ register(ObjectStoreConfig{
+ Table: &memdb.TableSchema{
+ Name: tableNode,
+ Indexes: map[string]*memdb.IndexSchema{
+ indexID: {
+ Name: indexID,
+ Unique: true,
+ Indexer: api.NodeIndexerByID{},
+ },
+ // TODO(aluzzardi): Use `indexHostname` instead.
+ indexName: {
+ Name: indexName,
+ AllowMissing: true,
+ Indexer: nodeIndexerByHostname{},
+ },
+ indexRole: {
+ Name: indexRole,
+ Indexer: nodeIndexerByRole{},
+ },
+ indexMembership: {
+ Name: indexMembership,
+ Indexer: nodeIndexerByMembership{},
+ },
+ indexCustom: {
+ Name: indexCustom,
+ Indexer: api.NodeCustomIndexer{},
+ AllowMissing: true,
+ },
+ },
+ },
+ Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
+ var err error
+ snapshot.Nodes, err = FindNodes(tx, All)
+ return err
+ },
+ Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
+ nodes, err := FindNodes(tx, All)
+ if err != nil {
+ return err
+ }
+ for _, n := range nodes {
+ if err := DeleteNode(tx, n.ID); err != nil {
+ return err
+ }
+ }
+ for _, n := range snapshot.Nodes {
+ if err := CreateNode(tx, n); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ ApplyStoreAction: func(tx Tx, sa api.StoreAction) error {
+ switch v := sa.Target.(type) {
+ case *api.StoreAction_Node:
+ obj := v.Node
+ switch sa.Action {
+ case api.StoreActionKindCreate:
+ return CreateNode(tx, obj)
+ case api.StoreActionKindUpdate:
+ return UpdateNode(tx, obj)
+ case api.StoreActionKindRemove:
+ return DeleteNode(tx, obj.ID)
+ }
+ }
+ return errUnknownStoreAction
+ },
+ })
+}
+
+// CreateNode adds a new node to the store.
+// Returns ErrExist if the ID is already taken.
+func CreateNode(tx Tx, n *api.Node) error {
+ return tx.create(tableNode, n)
+}
+
+// UpdateNode updates an existing node in the store.
+// Returns ErrNotExist if the node doesn't exist.
+func UpdateNode(tx Tx, n *api.Node) error {
+ return tx.update(tableNode, n)
+}
+
+// DeleteNode removes a node from the store.
+// Returns ErrNotExist if the node doesn't exist.
+func DeleteNode(tx Tx, id string) error {
+ return tx.delete(tableNode, id)
+}
+
+// GetNode looks up a node by ID.
+// Returns nil if the node doesn't exist.
+func GetNode(tx ReadTx, id string) *api.Node {
+ n := tx.get(tableNode, id)
+ if n == nil {
+ return nil
+ }
+ return n.(*api.Node)
+}
+
+// FindNodes selects a set of nodes and returns them.
+func FindNodes(tx ReadTx, by By) ([]*api.Node, error) {
+ checkType := func(by By) error {
+ switch by.(type) {
+ case byName, byNamePrefix, byIDPrefix, byRole, byMembership, byCustom, byCustomPrefix:
+ return nil
+ default:
+ return ErrInvalidFindBy
+ }
+ }
+
+ nodeList := []*api.Node{}
+ appendResult := func(o api.StoreObject) {
+ nodeList = append(nodeList, o.(*api.Node))
+ }
+
+ err := tx.find(tableNode, by, checkType, appendResult)
+ return nodeList, err
+}
+
+type nodeIndexerByHostname struct{}
+
+func (ni nodeIndexerByHostname) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ni nodeIndexerByHostname) FromObject(obj interface{}) (bool, []byte, error) {
+ n := obj.(*api.Node)
+
+ if n.Description == nil {
+ return false, nil, nil
+ }
+ // Add the null character as a terminator
+ return true, []byte(strings.ToLower(n.Description.Hostname) + "\x00"), nil
+}
+
+func (ni nodeIndexerByHostname) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+
+type nodeIndexerByRole struct{}
+
+func (ni nodeIndexerByRole) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ni nodeIndexerByRole) FromObject(obj interface{}) (bool, []byte, error) {
+ n := obj.(*api.Node)
+
+ // Add the null character as a terminator
+ return true, []byte(strconv.FormatInt(int64(n.Role), 10) + "\x00"), nil
+}
+
+type nodeIndexerByMembership struct{}
+
+func (ni nodeIndexerByMembership) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ni nodeIndexerByMembership) FromObject(obj interface{}) (bool, []byte, error) {
+ n := obj.(*api.Node)
+
+ // Add the null character as a terminator
+ return true, []byte(strconv.FormatInt(int64(n.Spec.Membership), 10) + "\x00"), nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/object.go b/vendor/github.com/docker/swarmkit/manager/state/store/object.go
new file mode 100644
index 0000000..5f495fd
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/object.go
@@ -0,0 +1,15 @@
+package store
+
+import (
+ "github.com/docker/swarmkit/api"
+ memdb "github.com/hashicorp/go-memdb"
+)
+
+// ObjectStoreConfig provides the necessary methods to store a particular object
+// type inside MemoryStore.
+type ObjectStoreConfig struct {
+ Table *memdb.TableSchema
+ Save func(ReadTx, *api.StoreSnapshot) error
+ Restore func(Tx, *api.StoreSnapshot) error
+ ApplyStoreAction func(Tx, api.StoreAction) error
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/resources.go b/vendor/github.com/docker/swarmkit/manager/state/store/resources.go
new file mode 100644
index 0000000..4e1ec71
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/resources.go
@@ -0,0 +1,199 @@
+package store
+
+import (
+ "github.com/docker/swarmkit/api"
+ memdb "github.com/hashicorp/go-memdb"
+ "github.com/pkg/errors"
+)
+
+const tableResource = "resource"
+
+func init() {
+ register(ObjectStoreConfig{
+ Table: &memdb.TableSchema{
+ Name: tableResource,
+ Indexes: map[string]*memdb.IndexSchema{
+ indexID: {
+ Name: indexID,
+ Unique: true,
+ Indexer: resourceIndexerByID{},
+ },
+ indexName: {
+ Name: indexName,
+ Unique: true,
+ Indexer: resourceIndexerByName{},
+ },
+ indexKind: {
+ Name: indexKind,
+ Indexer: resourceIndexerByKind{},
+ },
+ indexCustom: {
+ Name: indexCustom,
+ Indexer: resourceCustomIndexer{},
+ AllowMissing: true,
+ },
+ },
+ },
+ Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
+ var err error
+ snapshot.Resources, err = FindResources(tx, All)
+ return err
+ },
+ Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
+ resources, err := FindResources(tx, All)
+ if err != nil {
+ return err
+ }
+ for _, r := range resources {
+ if err := DeleteResource(tx, r.ID); err != nil {
+ return err
+ }
+ }
+ for _, r := range snapshot.Resources {
+ if err := CreateResource(tx, r); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ ApplyStoreAction: func(tx Tx, sa api.StoreAction) error {
+ switch v := sa.Target.(type) {
+ case *api.StoreAction_Resource:
+ obj := v.Resource
+ switch sa.Action {
+ case api.StoreActionKindCreate:
+ return CreateResource(tx, obj)
+ case api.StoreActionKindUpdate:
+ return UpdateResource(tx, obj)
+ case api.StoreActionKindRemove:
+ return DeleteResource(tx, obj.ID)
+ }
+ }
+ return errUnknownStoreAction
+ },
+ })
+}
+
+type resourceEntry struct {
+ *api.Resource
+}
+
+func (r resourceEntry) CopyStoreObject() api.StoreObject {
+ return resourceEntry{Resource: r.Resource.Copy()}
+}
+
+func confirmExtension(tx Tx, r *api.Resource) error {
+ // There must be an extension corresponding to the Kind field.
+ extensions, err := FindExtensions(tx, ByName(r.Kind))
+ if err != nil {
+ return errors.Wrap(err, "failed to query extensions")
+ }
+ if len(extensions) == 0 {
+ return errors.Errorf("object kind %s is unregistered", r.Kind)
+ }
+ return nil
+}
+
+// CreateResource adds a new resource object to the store.
+// Returns ErrExist if the ID is already taken.
+func CreateResource(tx Tx, r *api.Resource) error {
+ if err := confirmExtension(tx, r); err != nil {
+ return err
+ }
+ return tx.create(tableResource, resourceEntry{r})
+}
+
+// UpdateResource updates an existing resource object in the store.
+// Returns ErrNotExist if the object doesn't exist.
+func UpdateResource(tx Tx, r *api.Resource) error {
+ if err := confirmExtension(tx, r); err != nil {
+ return err
+ }
+ return tx.update(tableResource, resourceEntry{r})
+}
+
+// DeleteResource removes a resource object from the store.
+// Returns ErrNotExist if the object doesn't exist.
+func DeleteResource(tx Tx, id string) error {
+ return tx.delete(tableResource, id)
+}
+
+// GetResource looks up a resource object by ID.
+// Returns nil if the object doesn't exist.
+func GetResource(tx ReadTx, id string) *api.Resource {
+ r := tx.get(tableResource, id)
+ if r == nil {
+ return nil
+ }
+ return r.(resourceEntry).Resource
+}
+
+// FindResources selects a set of resource objects and returns them.
+func FindResources(tx ReadTx, by By) ([]*api.Resource, error) {
+ checkType := func(by By) error {
+ switch by.(type) {
+ case byIDPrefix, byName, byKind, byCustom, byCustomPrefix:
+ return nil
+ default:
+ return ErrInvalidFindBy
+ }
+ }
+
+ resourceList := []*api.Resource{}
+ appendResult := func(o api.StoreObject) {
+ resourceList = append(resourceList, o.(resourceEntry).Resource)
+ }
+
+ err := tx.find(tableResource, by, checkType, appendResult)
+ return resourceList, err
+}
+
+type resourceIndexerByKind struct{}
+
+func (ri resourceIndexerByKind) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ri resourceIndexerByKind) FromObject(obj interface{}) (bool, []byte, error) {
+ r := obj.(resourceEntry)
+
+ // Add the null character as a terminator
+ val := r.Resource.Kind + "\x00"
+ return true, []byte(val), nil
+}
+
+type resourceIndexerByID struct{}
+
+func (indexer resourceIndexerByID) FromArgs(args ...interface{}) ([]byte, error) {
+ return api.ResourceIndexerByID{}.FromArgs(args...)
+}
+func (indexer resourceIndexerByID) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return api.ResourceIndexerByID{}.PrefixFromArgs(args...)
+}
+func (indexer resourceIndexerByID) FromObject(obj interface{}) (bool, []byte, error) {
+ return api.ResourceIndexerByID{}.FromObject(obj.(resourceEntry).Resource)
+}
+
+type resourceIndexerByName struct{}
+
+func (indexer resourceIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return api.ResourceIndexerByName{}.FromArgs(args...)
+}
+func (indexer resourceIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return api.ResourceIndexerByName{}.PrefixFromArgs(args...)
+}
+func (indexer resourceIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ return api.ResourceIndexerByName{}.FromObject(obj.(resourceEntry).Resource)
+}
+
+type resourceCustomIndexer struct{}
+
+func (indexer resourceCustomIndexer) FromArgs(args ...interface{}) ([]byte, error) {
+ return api.ResourceCustomIndexer{}.FromArgs(args...)
+}
+func (indexer resourceCustomIndexer) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return api.ResourceCustomIndexer{}.PrefixFromArgs(args...)
+}
+func (indexer resourceCustomIndexer) FromObject(obj interface{}) (bool, [][]byte, error) {
+ return api.ResourceCustomIndexer{}.FromObject(obj.(resourceEntry).Resource)
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/secrets.go b/vendor/github.com/docker/swarmkit/manager/state/store/secrets.go
new file mode 100644
index 0000000..203c94c
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/secrets.go
@@ -0,0 +1,132 @@
+package store
+
+import (
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ memdb "github.com/hashicorp/go-memdb"
+)
+
+const tableSecret = "secret"
+
+func init() {
+ register(ObjectStoreConfig{
+ Table: &memdb.TableSchema{
+ Name: tableSecret,
+ Indexes: map[string]*memdb.IndexSchema{
+ indexID: {
+ Name: indexID,
+ Unique: true,
+ Indexer: api.SecretIndexerByID{},
+ },
+ indexName: {
+ Name: indexName,
+ Unique: true,
+ Indexer: api.SecretIndexerByName{},
+ },
+ indexCustom: {
+ Name: indexCustom,
+ Indexer: api.SecretCustomIndexer{},
+ AllowMissing: true,
+ },
+ },
+ },
+ Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
+ var err error
+ snapshot.Secrets, err = FindSecrets(tx, All)
+ return err
+ },
+ Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
+ secrets, err := FindSecrets(tx, All)
+ if err != nil {
+ return err
+ }
+ for _, s := range secrets {
+ if err := DeleteSecret(tx, s.ID); err != nil {
+ return err
+ }
+ }
+ for _, s := range snapshot.Secrets {
+ if err := CreateSecret(tx, s); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ ApplyStoreAction: func(tx Tx, sa api.StoreAction) error {
+ switch v := sa.Target.(type) {
+ case *api.StoreAction_Secret:
+ obj := v.Secret
+ switch sa.Action {
+ case api.StoreActionKindCreate:
+ return CreateSecret(tx, obj)
+ case api.StoreActionKindUpdate:
+ return UpdateSecret(tx, obj)
+ case api.StoreActionKindRemove:
+ return DeleteSecret(tx, obj.ID)
+ }
+ }
+ return errUnknownStoreAction
+ },
+ })
+}
+
+// CreateSecret adds a new secret to the store.
+// Returns ErrExist if the ID is already taken.
+func CreateSecret(tx Tx, s *api.Secret) error {
+ // Ensure the name is not already in use.
+ if tx.lookup(tableSecret, indexName, strings.ToLower(s.Spec.Annotations.Name)) != nil {
+ return ErrNameConflict
+ }
+
+ return tx.create(tableSecret, s)
+}
+
+// UpdateSecret updates an existing secret in the store.
+// Returns ErrNotExist if the secret doesn't exist.
+func UpdateSecret(tx Tx, s *api.Secret) error {
+ // Ensure the name is either not in use or already used by this same Secret.
+ if existing := tx.lookup(tableSecret, indexName, strings.ToLower(s.Spec.Annotations.Name)); existing != nil {
+ if existing.GetID() != s.ID {
+ return ErrNameConflict
+ }
+ }
+
+ return tx.update(tableSecret, s)
+}
+
+// DeleteSecret removes a secret from the store.
+// Returns ErrNotExist if the secret doesn't exist.
+func DeleteSecret(tx Tx, id string) error {
+ return tx.delete(tableSecret, id)
+}
+
+// GetSecret looks up a secret by ID.
+// Returns nil if the secret doesn't exist.
+func GetSecret(tx ReadTx, id string) *api.Secret {
+ n := tx.get(tableSecret, id)
+ if n == nil {
+ return nil
+ }
+ return n.(*api.Secret)
+}
+
+// FindSecrets selects a set of secrets and returns them.
+func FindSecrets(tx ReadTx, by By) ([]*api.Secret, error) {
+ checkType := func(by By) error {
+ switch by.(type) {
+ case byName, byNamePrefix, byIDPrefix, byCustom, byCustomPrefix:
+ return nil
+ default:
+ return ErrInvalidFindBy
+ }
+ }
+
+ secretList := []*api.Secret{}
+ appendResult := func(o api.StoreObject) {
+ secretList = append(secretList, o.(*api.Secret))
+ }
+
+ err := tx.find(tableSecret, by, checkType, appendResult)
+ return secretList, err
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/services.go b/vendor/github.com/docker/swarmkit/manager/state/store/services.go
new file mode 100644
index 0000000..884bc35
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/services.go
@@ -0,0 +1,248 @@
+package store
+
+import (
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/naming"
+ memdb "github.com/hashicorp/go-memdb"
+)
+
+const tableService = "service"
+
+func init() {
+ register(ObjectStoreConfig{
+ Table: &memdb.TableSchema{
+ Name: tableService,
+ Indexes: map[string]*memdb.IndexSchema{
+ indexID: {
+ Name: indexID,
+ Unique: true,
+ Indexer: api.ServiceIndexerByID{},
+ },
+ indexName: {
+ Name: indexName,
+ Unique: true,
+ Indexer: api.ServiceIndexerByName{},
+ },
+ indexRuntime: {
+ Name: indexRuntime,
+ AllowMissing: true,
+ Indexer: serviceIndexerByRuntime{},
+ },
+ indexNetwork: {
+ Name: indexNetwork,
+ AllowMissing: true,
+ Indexer: serviceIndexerByNetwork{},
+ },
+ indexSecret: {
+ Name: indexSecret,
+ AllowMissing: true,
+ Indexer: serviceIndexerBySecret{},
+ },
+ indexConfig: {
+ Name: indexConfig,
+ AllowMissing: true,
+ Indexer: serviceIndexerByConfig{},
+ },
+ indexCustom: {
+ Name: indexCustom,
+ Indexer: api.ServiceCustomIndexer{},
+ AllowMissing: true,
+ },
+ },
+ },
+ Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
+ var err error
+ snapshot.Services, err = FindServices(tx, All)
+ return err
+ },
+ Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
+ services, err := FindServices(tx, All)
+ if err != nil {
+ return err
+ }
+ for _, s := range services {
+ if err := DeleteService(tx, s.ID); err != nil {
+ return err
+ }
+ }
+ for _, s := range snapshot.Services {
+ if err := CreateService(tx, s); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ ApplyStoreAction: func(tx Tx, sa api.StoreAction) error {
+ switch v := sa.Target.(type) {
+ case *api.StoreAction_Service:
+ obj := v.Service
+ switch sa.Action {
+ case api.StoreActionKindCreate:
+ return CreateService(tx, obj)
+ case api.StoreActionKindUpdate:
+ return UpdateService(tx, obj)
+ case api.StoreActionKindRemove:
+ return DeleteService(tx, obj.ID)
+ }
+ }
+ return errUnknownStoreAction
+ },
+ })
+}
+
+// CreateService adds a new service to the store.
+// Returns ErrExist if the ID is already taken.
+func CreateService(tx Tx, s *api.Service) error {
+ // Ensure the name is not already in use.
+ if tx.lookup(tableService, indexName, strings.ToLower(s.Spec.Annotations.Name)) != nil {
+ return ErrNameConflict
+ }
+
+ return tx.create(tableService, s)
+}
+
+// UpdateService updates an existing service in the store.
+// Returns ErrNotExist if the service doesn't exist.
+func UpdateService(tx Tx, s *api.Service) error {
+ // Ensure the name is either not in use or already used by this same Service.
+ if existing := tx.lookup(tableService, indexName, strings.ToLower(s.Spec.Annotations.Name)); existing != nil {
+ if existing.GetID() != s.ID {
+ return ErrNameConflict
+ }
+ }
+
+ return tx.update(tableService, s)
+}
+
+// DeleteService removes a service from the store.
+// Returns ErrNotExist if the service doesn't exist.
+func DeleteService(tx Tx, id string) error {
+ return tx.delete(tableService, id)
+}
+
+// GetService looks up a service by ID.
+// Returns nil if the service doesn't exist.
+func GetService(tx ReadTx, id string) *api.Service {
+ s := tx.get(tableService, id)
+ if s == nil {
+ return nil
+ }
+ return s.(*api.Service)
+}
+
+// FindServices selects a set of services and returns them.
+func FindServices(tx ReadTx, by By) ([]*api.Service, error) {
+ checkType := func(by By) error {
+ switch by.(type) {
+ case byName, byNamePrefix, byIDPrefix, byRuntime, byReferencedNetworkID, byReferencedSecretID, byReferencedConfigID, byCustom, byCustomPrefix:
+ return nil
+ default:
+ return ErrInvalidFindBy
+ }
+ }
+
+ serviceList := []*api.Service{}
+ appendResult := func(o api.StoreObject) {
+ serviceList = append(serviceList, o.(*api.Service))
+ }
+
+ err := tx.find(tableService, by, checkType, appendResult)
+ return serviceList, err
+}
+
+type serviceIndexerByRuntime struct{}
+
+func (si serviceIndexerByRuntime) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (si serviceIndexerByRuntime) FromObject(obj interface{}) (bool, []byte, error) {
+ s := obj.(*api.Service)
+ r, err := naming.Runtime(s.Spec.Task)
+ if err != nil {
+ return false, nil, nil
+ }
+ return true, []byte(r + "\x00"), nil
+}
+
+func (si serviceIndexerByRuntime) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+
+type serviceIndexerByNetwork struct{}
+
+func (si serviceIndexerByNetwork) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (si serviceIndexerByNetwork) FromObject(obj interface{}) (bool, [][]byte, error) {
+ s := obj.(*api.Service)
+
+ var networkIDs [][]byte
+
+ specNetworks := s.Spec.Task.Networks
+
+ if len(specNetworks) == 0 {
+ specNetworks = s.Spec.Networks
+ }
+
+ for _, na := range specNetworks {
+ // Add the null character as a terminator
+ networkIDs = append(networkIDs, []byte(na.Target+"\x00"))
+ }
+
+ return len(networkIDs) != 0, networkIDs, nil
+}
+
+type serviceIndexerBySecret struct{}
+
+func (si serviceIndexerBySecret) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (si serviceIndexerBySecret) FromObject(obj interface{}) (bool, [][]byte, error) {
+ s := obj.(*api.Service)
+
+ container := s.Spec.Task.GetContainer()
+ if container == nil {
+ return false, nil, nil
+ }
+
+ var secretIDs [][]byte
+
+ for _, secretRef := range container.Secrets {
+ // Add the null character as a terminator
+ secretIDs = append(secretIDs, []byte(secretRef.SecretID+"\x00"))
+ }
+
+ return len(secretIDs) != 0, secretIDs, nil
+}
+
+type serviceIndexerByConfig struct{}
+
+func (si serviceIndexerByConfig) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (si serviceIndexerByConfig) FromObject(obj interface{}) (bool, [][]byte, error) {
+ s, ok := obj.(*api.Service)
+ if !ok {
+ panic("unexpected type passed to FromObject")
+ }
+
+ container := s.Spec.Task.GetContainer()
+ if container == nil {
+ return false, nil, nil
+ }
+
+ var configIDs [][]byte
+
+ for _, configRef := range container.Configs {
+ // Add the null character as a terminator
+ configIDs = append(configIDs, []byte(configRef.ConfigID+"\x00"))
+ }
+
+ return len(configIDs) != 0, configIDs, nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/store/tasks.go b/vendor/github.com/docker/swarmkit/manager/state/store/tasks.go
new file mode 100644
index 0000000..b8d8a73
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/store/tasks.go
@@ -0,0 +1,341 @@
+package store
+
+import (
+ "strconv"
+ "strings"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/naming"
+ memdb "github.com/hashicorp/go-memdb"
+)
+
+const tableTask = "task"
+
+func init() {
+ register(ObjectStoreConfig{
+ Table: &memdb.TableSchema{
+ Name: tableTask,
+ Indexes: map[string]*memdb.IndexSchema{
+ indexID: {
+ Name: indexID,
+ Unique: true,
+ Indexer: api.TaskIndexerByID{},
+ },
+ indexName: {
+ Name: indexName,
+ AllowMissing: true,
+ Indexer: taskIndexerByName{},
+ },
+ indexRuntime: {
+ Name: indexRuntime,
+ AllowMissing: true,
+ Indexer: taskIndexerByRuntime{},
+ },
+ indexServiceID: {
+ Name: indexServiceID,
+ AllowMissing: true,
+ Indexer: taskIndexerByServiceID{},
+ },
+ indexNodeID: {
+ Name: indexNodeID,
+ AllowMissing: true,
+ Indexer: taskIndexerByNodeID{},
+ },
+ indexSlot: {
+ Name: indexSlot,
+ AllowMissing: true,
+ Indexer: taskIndexerBySlot{},
+ },
+ indexDesiredState: {
+ Name: indexDesiredState,
+ Indexer: taskIndexerByDesiredState{},
+ },
+ indexTaskState: {
+ Name: indexTaskState,
+ Indexer: taskIndexerByTaskState{},
+ },
+ indexNetwork: {
+ Name: indexNetwork,
+ AllowMissing: true,
+ Indexer: taskIndexerByNetwork{},
+ },
+ indexSecret: {
+ Name: indexSecret,
+ AllowMissing: true,
+ Indexer: taskIndexerBySecret{},
+ },
+ indexConfig: {
+ Name: indexConfig,
+ AllowMissing: true,
+ Indexer: taskIndexerByConfig{},
+ },
+ indexCustom: {
+ Name: indexCustom,
+ Indexer: api.TaskCustomIndexer{},
+ AllowMissing: true,
+ },
+ },
+ },
+ Save: func(tx ReadTx, snapshot *api.StoreSnapshot) error {
+ var err error
+ snapshot.Tasks, err = FindTasks(tx, All)
+ return err
+ },
+ Restore: func(tx Tx, snapshot *api.StoreSnapshot) error {
+ tasks, err := FindTasks(tx, All)
+ if err != nil {
+ return err
+ }
+ for _, t := range tasks {
+ if err := DeleteTask(tx, t.ID); err != nil {
+ return err
+ }
+ }
+ for _, t := range snapshot.Tasks {
+ if err := CreateTask(tx, t); err != nil {
+ return err
+ }
+ }
+ return nil
+ },
+ ApplyStoreAction: func(tx Tx, sa api.StoreAction) error {
+ switch v := sa.Target.(type) {
+ case *api.StoreAction_Task:
+ obj := v.Task
+ switch sa.Action {
+ case api.StoreActionKindCreate:
+ return CreateTask(tx, obj)
+ case api.StoreActionKindUpdate:
+ return UpdateTask(tx, obj)
+ case api.StoreActionKindRemove:
+ return DeleteTask(tx, obj.ID)
+ }
+ }
+ return errUnknownStoreAction
+ },
+ })
+}
+
+// CreateTask adds a new task to the store.
+// Returns ErrExist if the ID is already taken.
+func CreateTask(tx Tx, t *api.Task) error {
+ return tx.create(tableTask, t)
+}
+
+// UpdateTask updates an existing task in the store.
+// Returns ErrNotExist if the node doesn't exist.
+func UpdateTask(tx Tx, t *api.Task) error {
+ return tx.update(tableTask, t)
+}
+
+// DeleteTask removes a task from the store.
+// Returns ErrNotExist if the task doesn't exist.
+func DeleteTask(tx Tx, id string) error {
+ return tx.delete(tableTask, id)
+}
+
+// GetTask looks up a task by ID.
+// Returns nil if the task doesn't exist.
+func GetTask(tx ReadTx, id string) *api.Task {
+ t := tx.get(tableTask, id)
+ if t == nil {
+ return nil
+ }
+ return t.(*api.Task)
+}
+
+// FindTasks selects a set of tasks and returns them.
+func FindTasks(tx ReadTx, by By) ([]*api.Task, error) {
+ checkType := func(by By) error {
+ switch by.(type) {
+ case byName, byNamePrefix, byIDPrefix, byRuntime, byDesiredState, byTaskState, byNode, byService, bySlot, byReferencedNetworkID, byReferencedSecretID, byReferencedConfigID, byCustom, byCustomPrefix:
+ return nil
+ default:
+ return ErrInvalidFindBy
+ }
+ }
+
+ taskList := []*api.Task{}
+ appendResult := func(o api.StoreObject) {
+ taskList = append(taskList, o.(*api.Task))
+ }
+
+ err := tx.find(tableTask, by, checkType, appendResult)
+ return taskList, err
+}
+
+type taskIndexerByName struct{}
+
+func (ti taskIndexerByName) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ti taskIndexerByName) FromObject(obj interface{}) (bool, []byte, error) {
+ t := obj.(*api.Task)
+
+ name := naming.Task(t)
+
+ // Add the null character as a terminator
+ return true, []byte(strings.ToLower(name) + "\x00"), nil
+}
+
+func (ti taskIndexerByName) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+
+type taskIndexerByRuntime struct{}
+
+func (ti taskIndexerByRuntime) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ti taskIndexerByRuntime) FromObject(obj interface{}) (bool, []byte, error) {
+ t := obj.(*api.Task)
+ r, err := naming.Runtime(t.Spec)
+ if err != nil {
+ return false, nil, nil
+ }
+ return true, []byte(r + "\x00"), nil
+}
+
+func (ti taskIndexerByRuntime) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ return prefixFromArgs(args...)
+}
+
+type taskIndexerByServiceID struct{}
+
+func (ti taskIndexerByServiceID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ti taskIndexerByServiceID) FromObject(obj interface{}) (bool, []byte, error) {
+ t := obj.(*api.Task)
+
+ // Add the null character as a terminator
+ val := t.ServiceID + "\x00"
+ return true, []byte(val), nil
+}
+
+type taskIndexerByNodeID struct{}
+
+func (ti taskIndexerByNodeID) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ti taskIndexerByNodeID) FromObject(obj interface{}) (bool, []byte, error) {
+ t := obj.(*api.Task)
+
+ // Add the null character as a terminator
+ val := t.NodeID + "\x00"
+ return true, []byte(val), nil
+}
+
+type taskIndexerBySlot struct{}
+
+func (ti taskIndexerBySlot) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ti taskIndexerBySlot) FromObject(obj interface{}) (bool, []byte, error) {
+ t := obj.(*api.Task)
+
+ // Add the null character as a terminator
+ val := t.ServiceID + "\x00" + strconv.FormatUint(t.Slot, 10) + "\x00"
+ return true, []byte(val), nil
+}
+
+type taskIndexerByDesiredState struct{}
+
+func (ti taskIndexerByDesiredState) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ti taskIndexerByDesiredState) FromObject(obj interface{}) (bool, []byte, error) {
+ t := obj.(*api.Task)
+
+ // Add the null character as a terminator
+ return true, []byte(strconv.FormatInt(int64(t.DesiredState), 10) + "\x00"), nil
+}
+
+type taskIndexerByNetwork struct{}
+
+func (ti taskIndexerByNetwork) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ti taskIndexerByNetwork) FromObject(obj interface{}) (bool, [][]byte, error) {
+ t := obj.(*api.Task)
+
+ var networkIDs [][]byte
+
+ for _, na := range t.Spec.Networks {
+ // Add the null character as a terminator
+ networkIDs = append(networkIDs, []byte(na.Target+"\x00"))
+ }
+
+ return len(networkIDs) != 0, networkIDs, nil
+}
+
+type taskIndexerBySecret struct{}
+
+func (ti taskIndexerBySecret) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ti taskIndexerBySecret) FromObject(obj interface{}) (bool, [][]byte, error) {
+ t := obj.(*api.Task)
+
+ container := t.Spec.GetContainer()
+ if container == nil {
+ return false, nil, nil
+ }
+
+ var secretIDs [][]byte
+
+ for _, secretRef := range container.Secrets {
+ // Add the null character as a terminator
+ secretIDs = append(secretIDs, []byte(secretRef.SecretID+"\x00"))
+ }
+
+ return len(secretIDs) != 0, secretIDs, nil
+}
+
+type taskIndexerByConfig struct{}
+
+func (ti taskIndexerByConfig) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ti taskIndexerByConfig) FromObject(obj interface{}) (bool, [][]byte, error) {
+ t, ok := obj.(*api.Task)
+ if !ok {
+ panic("unexpected type passed to FromObject")
+ }
+
+ container := t.Spec.GetContainer()
+ if container == nil {
+ return false, nil, nil
+ }
+
+ var configIDs [][]byte
+
+ for _, configRef := range container.Configs {
+ // Add the null character as a terminator
+ configIDs = append(configIDs, []byte(configRef.ConfigID+"\x00"))
+ }
+
+ return len(configIDs) != 0, configIDs, nil
+}
+
+type taskIndexerByTaskState struct{}
+
+func (ts taskIndexerByTaskState) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromArgs(args...)
+}
+
+func (ts taskIndexerByTaskState) FromObject(obj interface{}) (bool, []byte, error) {
+ t := obj.(*api.Task)
+
+ // Add the null character as a terminator
+ return true, []byte(strconv.FormatInt(int64(t.Status.State), 10) + "\x00"), nil
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/state/watch.go b/vendor/github.com/docker/swarmkit/manager/state/watch.go
new file mode 100644
index 0000000..ad0ebd7
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/state/watch.go
@@ -0,0 +1,74 @@
+package state
+
+import (
+ "github.com/docker/go-events"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/watch"
+)
+
+// EventCommit delineates a transaction boundary.
+type EventCommit struct {
+ Version *api.Version
+}
+
+// Matches returns true if this event is a commit event.
+func (e EventCommit) Matches(watchEvent events.Event) bool {
+ _, ok := watchEvent.(EventCommit)
+ return ok
+}
+
+// TaskCheckStateGreaterThan is a TaskCheckFunc for checking task state.
+func TaskCheckStateGreaterThan(t1, t2 *api.Task) bool {
+ return t2.Status.State > t1.Status.State
+}
+
+// NodeCheckState is a NodeCheckFunc for matching node state.
+func NodeCheckState(n1, n2 *api.Node) bool {
+ return n1.Status.State == n2.Status.State
+}
+
+// Watch takes a variable number of events to match against. The subscriber
+// will receive events that match any of the arguments passed to Watch.
+//
+// Examples:
+//
+// // subscribe to all events
+// Watch(q)
+//
+// // subscribe to all UpdateTask events
+// Watch(q, EventUpdateTask{})
+//
+// // subscribe to all task-related events
+// Watch(q, EventUpdateTask{}, EventCreateTask{}, EventDeleteTask{})
+//
+// // subscribe to UpdateTask for node 123
+// Watch(q, EventUpdateTask{Task: &api.Task{NodeID: 123},
+// Checks: []TaskCheckFunc{TaskCheckNodeID}})
+//
+// // subscribe to UpdateTask for node 123, as well as CreateTask
+// // for node 123 that also has ServiceID set to "abc"
+// Watch(q, EventUpdateTask{Task: &api.Task{NodeID: 123},
+// Checks: []TaskCheckFunc{TaskCheckNodeID}},
+// EventCreateTask{Task: &api.Task{NodeID: 123, ServiceID: "abc"},
+// Checks: []TaskCheckFunc{TaskCheckNodeID,
+// func(t1, t2 *api.Task) bool {
+// return t1.ServiceID == t2.ServiceID
+// }}})
+func Watch(queue *watch.Queue, specifiers ...api.Event) (eventq chan events.Event, cancel func()) {
+ if len(specifiers) == 0 {
+ return queue.Watch()
+ }
+ return queue.CallbackWatch(Matcher(specifiers...))
+}
+
+// Matcher returns an events.Matcher that Matches the specifiers with OR logic.
+func Matcher(specifiers ...api.Event) events.MatcherFunc {
+ return events.MatcherFunc(func(event events.Event) bool {
+ for _, s := range specifiers {
+ if s.Matches(event) {
+ return true
+ }
+ }
+ return false
+ })
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/watchapi/server.go b/vendor/github.com/docker/swarmkit/manager/watchapi/server.go
new file mode 100644
index 0000000..07cdedb
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/watchapi/server.go
@@ -0,0 +1,17 @@
+package watchapi
+
+import (
+ "github.com/docker/swarmkit/manager/state/store"
+)
+
+// Server is the store API gRPC server.
+type Server struct {
+ store *store.MemoryStore
+}
+
+// NewServer creates a store API server.
+func NewServer(store *store.MemoryStore) *Server {
+ return &Server{
+ store: store,
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/manager/watchapi/watch.go b/vendor/github.com/docker/swarmkit/manager/watchapi/watch.go
new file mode 100644
index 0000000..555b899
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/manager/watchapi/watch.go
@@ -0,0 +1,56 @@
+package watchapi
+
+import (
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/manager/state"
+ "github.com/docker/swarmkit/manager/state/store"
+)
+
+// Watch starts a stream that returns any changes to objects that match
+// the specified selectors. When the stream begins, it immediately sends
+// an empty message back to the client. It is important to wait for
+// this message before taking any actions that depend on an established
+// stream of changes for consistency.
+func (s *Server) Watch(request *api.WatchRequest, stream api.Watch_WatchServer) error {
+ ctx := stream.Context()
+
+ watchArgs, err := api.ConvertWatchArgs(request.Entries)
+ if err != nil {
+ return grpc.Errorf(codes.InvalidArgument, "%s", err.Error())
+ }
+
+ watchArgs = append(watchArgs, state.EventCommit{})
+ watch, cancel, err := store.WatchFrom(s.store, request.ResumeFrom, watchArgs...)
+ if err != nil {
+ return err
+ }
+ defer cancel()
+
+ // TODO(aaronl): Send current version in this WatchMessage?
+ if err := stream.Send(&api.WatchMessage{}); err != nil {
+ return err
+ }
+
+ var events []*api.WatchMessage_Event
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case event := <-watch:
+ if commitEvent, ok := event.(state.EventCommit); ok && len(events) > 0 {
+ if err := stream.Send(&api.WatchMessage{Events: events, Version: commitEvent.Version}); err != nil {
+ return err
+ }
+ events = nil
+ } else if eventMessage := api.WatchMessageEvent(event.(api.Event)); eventMessage != nil {
+ if !request.IncludeOldObject {
+ eventMessage.OldObject = nil
+ }
+ events = append(events, eventMessage)
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/docker/swarmkit/node/node.go b/vendor/github.com/docker/swarmkit/node/node.go
new file mode 100644
index 0000000..29badd0
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/node/node.go
@@ -0,0 +1,1100 @@
+package node
+
+import (
+ "bytes"
+ "crypto/tls"
+ "encoding/json"
+ "io/ioutil"
+ "net"
+ "os"
+ "path/filepath"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/boltdb/bolt"
+ "github.com/docker/docker/pkg/plugingetter"
+ metrics "github.com/docker/go-metrics"
+ "github.com/docker/swarmkit/agent"
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/ca"
+ "github.com/docker/swarmkit/connectionbroker"
+ "github.com/docker/swarmkit/ioutils"
+ "github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/manager"
+ "github.com/docker/swarmkit/manager/encryption"
+ "github.com/docker/swarmkit/remotes"
+ "github.com/docker/swarmkit/watch"
+ "github.com/docker/swarmkit/xnet"
+ grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
+)
+
+const (
+ stateFilename = "state.json"
+ roleChangeTimeout = 16 * time.Second
+)
+
+var (
+ nodeInfo metrics.LabeledGauge
+ nodeManager metrics.Gauge
+
+ errNodeStarted = errors.New("node: already started")
+ errNodeNotStarted = errors.New("node: not started")
+ certDirectory = "certificates"
+
+ // ErrInvalidUnlockKey is returned when we can't decrypt the TLS certificate
+ ErrInvalidUnlockKey = errors.New("node is locked, and needs a valid unlock key")
+)
+
+func init() {
+ ns := metrics.NewNamespace("swarm", "node", nil)
+ nodeInfo = ns.NewLabeledGauge("info", "Information related to the swarm", "",
+ "swarm_id",
+ "node_id",
+ )
+ nodeManager = ns.NewGauge("manager", "Whether this node is a manager or not", "")
+ metrics.Register(ns)
+}
+
+// Config provides values for a Node.
+type Config struct {
+ // Hostname is the name of host for agent instance.
+ Hostname string
+
+ // JoinAddr specifies node that should be used for the initial connection to
+ // other manager in cluster. This should be only one address and optional,
+ // the actual remotes come from the stored state.
+ JoinAddr string
+
+ // StateDir specifies the directory the node uses to keep the state of the
+ // remote managers and certificates.
+ StateDir string
+
+ // JoinToken is the token to be used on the first certificate request.
+ JoinToken string
+
+ // ExternalCAs is a list of CAs to which a manager node
+ // will make certificate signing requests for node certificates.
+ ExternalCAs []*api.ExternalCA
+
+ // ForceNewCluster creates a new cluster from current raft state.
+ ForceNewCluster bool
+
+ // ListenControlAPI specifies address the control API should listen on.
+ ListenControlAPI string
+
+ // ListenRemoteAPI specifies the address for the remote API that agents
+ // and raft members connect to.
+ ListenRemoteAPI string
+
+ // AdvertiseRemoteAPI specifies the address that should be advertised
+ // for connections to the remote API (including the raft service).
+ AdvertiseRemoteAPI string
+
+ // Executor specifies the executor to use for the agent.
+ Executor exec.Executor
+
+ // ElectionTick defines the amount of ticks needed without
+ // leader to trigger a new election
+ ElectionTick uint32
+
+ // HeartbeatTick defines the amount of ticks between each
+ // heartbeat sent to other members for health-check purposes
+ HeartbeatTick uint32
+
+ // AutoLockManagers determines whether or not an unlock key will be generated
+ // when bootstrapping a new cluster for the first time
+ AutoLockManagers bool
+
+ // UnlockKey is the key to unlock a node - used for decrypting at rest. This
+ // only applies to nodes that have already joined a cluster.
+ UnlockKey []byte
+
+ // Availability allows a user to control the current scheduling status of a node
+ Availability api.NodeSpec_Availability
+
+ // PluginGetter provides access to docker's plugin inventory.
+ PluginGetter plugingetter.PluginGetter
+}
+
+// Node implements the primary node functionality for a member of a swarm
+// cluster. Node handles workloads and may also run as a manager.
+type Node struct {
+ sync.RWMutex
+ config *Config
+ remotes *persistentRemotes
+ connBroker *connectionbroker.Broker
+ role string
+ roleCond *sync.Cond
+ conn *grpc.ClientConn
+ connCond *sync.Cond
+ nodeID string
+ started chan struct{}
+ startOnce sync.Once
+ stopped chan struct{}
+ stopOnce sync.Once
+ ready chan struct{} // closed when agent has completed registration and manager(if enabled) is ready to receive control requests
+ closed chan struct{}
+ err error
+ agent *agent.Agent
+ manager *manager.Manager
+ notifyNodeChange chan *agent.NodeChanges // used by the agent to relay node updates from the dispatcher Session stream to (*Node).run
+ unlockKey []byte
+}
+
+type lastSeenRole struct {
+ role api.NodeRole
+}
+
+// observe notes the latest value of this node role, and returns true if it
+// is the first seen value, or is different from the most recently seen value.
+func (l *lastSeenRole) observe(newRole api.NodeRole) bool {
+ changed := l.role != newRole
+ l.role = newRole
+ return changed
+}
+
+// RemoteAPIAddr returns address on which remote manager api listens.
+// Returns nil if node is not manager.
+func (n *Node) RemoteAPIAddr() (string, error) {
+ n.RLock()
+ defer n.RUnlock()
+ if n.manager == nil {
+ return "", errors.New("manager is not running")
+ }
+ addr := n.manager.Addr()
+ if addr == "" {
+ return "", errors.New("manager addr is not set")
+ }
+ return addr, nil
+}
+
+// New returns new Node instance.
+func New(c *Config) (*Node, error) {
+ if err := os.MkdirAll(c.StateDir, 0700); err != nil {
+ return nil, err
+ }
+ stateFile := filepath.Join(c.StateDir, stateFilename)
+ dt, err := ioutil.ReadFile(stateFile)
+ var p []api.Peer
+ if err != nil && !os.IsNotExist(err) {
+ return nil, err
+ }
+ if err == nil {
+ if err := json.Unmarshal(dt, &p); err != nil {
+ return nil, err
+ }
+ }
+ n := &Node{
+ remotes: newPersistentRemotes(stateFile, p...),
+ role: ca.WorkerRole,
+ config: c,
+ started: make(chan struct{}),
+ stopped: make(chan struct{}),
+ closed: make(chan struct{}),
+ ready: make(chan struct{}),
+ notifyNodeChange: make(chan *agent.NodeChanges, 1),
+ unlockKey: c.UnlockKey,
+ }
+
+ if n.config.JoinAddr != "" || n.config.ForceNewCluster {
+ n.remotes = newPersistentRemotes(filepath.Join(n.config.StateDir, stateFilename))
+ if n.config.JoinAddr != "" {
+ n.remotes.Observe(api.Peer{Addr: n.config.JoinAddr}, remotes.DefaultObservationWeight)
+ }
+ }
+
+ n.connBroker = connectionbroker.New(n.remotes)
+
+ n.roleCond = sync.NewCond(n.RLocker())
+ n.connCond = sync.NewCond(n.RLocker())
+ return n, nil
+}
+
+// BindRemote starts a listener that exposes the remote API.
+func (n *Node) BindRemote(ctx context.Context, listenAddr string, advertiseAddr string) error {
+ n.RLock()
+ defer n.RUnlock()
+
+ if n.manager == nil {
+ return errors.New("manager is not running")
+ }
+
+ return n.manager.BindRemote(ctx, manager.RemoteAddrs{
+ ListenAddr: listenAddr,
+ AdvertiseAddr: advertiseAddr,
+ })
+}
+
+// Start starts a node instance.
+func (n *Node) Start(ctx context.Context) error {
+ err := errNodeStarted
+
+ n.startOnce.Do(func() {
+ close(n.started)
+ go n.run(ctx)
+ err = nil // clear error above, only once.
+ })
+
+ return err
+}
+
+func (n *Node) currentRole() api.NodeRole {
+ n.Lock()
+ currentRole := api.NodeRoleWorker
+ if n.role == ca.ManagerRole {
+ currentRole = api.NodeRoleManager
+ }
+ n.Unlock()
+ return currentRole
+}
+
+func (n *Node) run(ctx context.Context) (err error) {
+ defer func() {
+ n.err = err
+ close(n.closed)
+ }()
+ ctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ ctx = log.WithModule(ctx, "node")
+
+ go func(ctx context.Context) {
+ select {
+ case <-ctx.Done():
+ case <-n.stopped:
+ cancel()
+ }
+ }(ctx)
+
+ paths := ca.NewConfigPaths(filepath.Join(n.config.StateDir, certDirectory))
+ securityConfig, err := n.loadSecurityConfig(ctx, paths)
+ if err != nil {
+ return err
+ }
+
+ renewer := ca.NewTLSRenewer(securityConfig, n.connBroker, paths.RootCA)
+
+ ctx = log.WithLogger(ctx, log.G(ctx).WithField("node.id", n.NodeID()))
+
+ taskDBPath := filepath.Join(n.config.StateDir, "worker", "tasks.db")
+ if err := os.MkdirAll(filepath.Dir(taskDBPath), 0777); err != nil {
+ return err
+ }
+
+ db, err := bolt.Open(taskDBPath, 0666, nil)
+ if err != nil {
+ return err
+ }
+ defer db.Close()
+
+ agentDone := make(chan struct{})
+
+ go func() {
+ // lastNodeDesiredRole is the last-seen value of Node.Spec.DesiredRole,
+ // used to make role changes "edge triggered" and avoid renewal loops.
+ lastNodeDesiredRole := lastSeenRole{role: n.currentRole()}
+
+ for {
+ select {
+ case <-agentDone:
+ return
+ case nodeChanges := <-n.notifyNodeChange:
+ currentRole := n.currentRole()
+
+ if nodeChanges.Node != nil {
+ // This is a bit complex to be backward compatible with older CAs that
+ // don't support the Node.Role field. They only use what's presently
+ // called DesiredRole.
+ // 1) If DesiredRole changes, kick off a certificate renewal. The renewal
+ // is delayed slightly to give Role time to change as well if this is
+ // a newer CA. If the certificate we get back doesn't have the expected
+ // role, we continue renewing with exponential backoff.
+ // 2) If the server is sending us IssuanceStateRotate, renew the cert as
+ // requested by the CA.
+ desiredRoleChanged := lastNodeDesiredRole.observe(nodeChanges.Node.Spec.DesiredRole)
+ if desiredRoleChanged {
+ switch nodeChanges.Node.Spec.DesiredRole {
+ case api.NodeRoleManager:
+ renewer.SetExpectedRole(ca.ManagerRole)
+ case api.NodeRoleWorker:
+ renewer.SetExpectedRole(ca.WorkerRole)
+ }
+ }
+ if desiredRoleChanged || nodeChanges.Node.Certificate.Status.State == api.IssuanceStateRotate {
+ renewer.Renew()
+ }
+ }
+
+ if nodeChanges.RootCert != nil {
+ // We only want to update the root CA if this is a worker node. Manager nodes directly watch the raft
+ // store and update the root CA, with the necessary signer, from the raft store (since the managers
+ // need the CA key as well to potentially issue new TLS certificates).
+ if currentRole == api.NodeRoleManager || bytes.Equal(nodeChanges.RootCert, securityConfig.RootCA().Certs) {
+ continue
+ }
+ newRootCA, err := ca.NewRootCA(nodeChanges.RootCert, nil, nil, ca.DefaultNodeCertExpiration, nil)
+ if err != nil {
+ log.G(ctx).WithError(err).Error("invalid new root certificate from the dispatcher")
+ continue
+ }
+ if err := securityConfig.UpdateRootCA(&newRootCA, newRootCA.Pool); err != nil {
+ log.G(ctx).WithError(err).Error("could not use new root CA from dispatcher")
+ continue
+ }
+ if err := ca.SaveRootCA(newRootCA, paths.RootCA); err != nil {
+ log.G(ctx).WithError(err).Error("could not save new root certificate from the dispatcher")
+ continue
+ }
+ }
+ }
+ }
+ }()
+
+ var wg sync.WaitGroup
+ wg.Add(3)
+
+ nodeInfo.WithValues(
+ securityConfig.ClientTLSCreds.Organization(),
+ securityConfig.ClientTLSCreds.NodeID(),
+ ).Set(1)
+
+ if n.currentRole() == api.NodeRoleManager {
+ nodeManager.Set(1)
+ } else {
+ nodeManager.Set(0)
+ }
+
+ updates := renewer.Start(ctx)
+ go func() {
+ for certUpdate := range updates {
+ if certUpdate.Err != nil {
+ logrus.Warnf("error renewing TLS certificate: %v", certUpdate.Err)
+ continue
+ }
+ n.Lock()
+ n.role = certUpdate.Role
+ n.roleCond.Broadcast()
+ n.Unlock()
+
+ // Export the new role.
+ if n.currentRole() == api.NodeRoleManager {
+ nodeManager.Set(1)
+ } else {
+ nodeManager.Set(0)
+ }
+ }
+
+ wg.Done()
+ }()
+
+ role := n.role
+
+ managerReady := make(chan struct{})
+ agentReady := make(chan struct{})
+ var managerErr error
+ var agentErr error
+ go func() {
+ managerErr = n.superviseManager(ctx, securityConfig, paths.RootCA, managerReady, renewer) // store err and loop
+ wg.Done()
+ cancel()
+ }()
+ go func() {
+ agentErr = n.runAgent(ctx, db, securityConfig, agentReady)
+ wg.Done()
+ cancel()
+ close(agentDone)
+ }()
+
+ go func() {
+ <-agentReady
+ if role == ca.ManagerRole {
+ workerRole := make(chan struct{})
+ waitRoleCtx, waitRoleCancel := context.WithCancel(ctx)
+ go func() {
+ if n.waitRole(waitRoleCtx, ca.WorkerRole) == nil {
+ close(workerRole)
+ }
+ }()
+ select {
+ case <-managerReady:
+ case <-workerRole:
+ }
+ waitRoleCancel()
+ }
+ close(n.ready)
+ }()
+
+ wg.Wait()
+ if managerErr != nil && errors.Cause(managerErr) != context.Canceled {
+ return managerErr
+ }
+ if agentErr != nil && errors.Cause(agentErr) != context.Canceled {
+ return agentErr
+ }
+ return err
+}
+
+// Stop stops node execution
+func (n *Node) Stop(ctx context.Context) error {
+ select {
+ case <-n.started:
+ default:
+ return errNodeNotStarted
+ }
+ // ask agent to clean up assignments
+ n.Lock()
+ if n.agent != nil {
+ if err := n.agent.Leave(ctx); err != nil {
+ log.G(ctx).WithError(err).Error("agent failed to clean up assignments")
+ }
+ }
+ n.Unlock()
+
+ n.stopOnce.Do(func() {
+ close(n.stopped)
+ })
+
+ select {
+ case <-n.closed:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+// Err returns the error that caused the node to shutdown or nil. Err blocks
+// until the node has fully shut down.
+func (n *Node) Err(ctx context.Context) error {
+ select {
+ case <-n.closed:
+ return n.err
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+func (n *Node) runAgent(ctx context.Context, db *bolt.DB, securityConfig *ca.SecurityConfig, ready chan<- struct{}) error {
+ waitCtx, waitCancel := context.WithCancel(ctx)
+ remotesCh := n.remotes.WaitSelect(ctx)
+ controlCh := n.ListenControlSocket(waitCtx)
+
+waitPeer:
+ for {
+ select {
+ case <-ctx.Done():
+ break waitPeer
+ case <-remotesCh:
+ break waitPeer
+ case conn := <-controlCh:
+ if conn != nil {
+ break waitPeer
+ }
+ }
+ }
+
+ waitCancel()
+
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+
+ secChangeQueue := watch.NewQueue()
+ defer secChangeQueue.Close()
+ secChangesCh, secChangesCancel := secChangeQueue.Watch()
+ defer secChangesCancel()
+ securityConfig.SetWatch(secChangeQueue)
+
+ rootCA := securityConfig.RootCA()
+ issuer := securityConfig.IssuerInfo()
+
+ agentConfig := &agent.Config{
+ Hostname: n.config.Hostname,
+ ConnBroker: n.connBroker,
+ Executor: n.config.Executor,
+ DB: db,
+ NotifyNodeChange: n.notifyNodeChange,
+ NotifyTLSChange: secChangesCh,
+ Credentials: securityConfig.ClientTLSCreds,
+ NodeTLSInfo: &api.NodeTLSInfo{
+ TrustRoot: rootCA.Certs,
+ CertIssuerPublicKey: issuer.PublicKey,
+ CertIssuerSubject: issuer.Subject,
+ },
+ }
+ // if a join address has been specified, then if the agent fails to connect due to a TLS error, fail fast - don't
+ // keep re-trying to join
+ if n.config.JoinAddr != "" {
+ agentConfig.SessionTracker = &firstSessionErrorTracker{}
+ }
+
+ a, err := agent.New(agentConfig)
+ if err != nil {
+ return err
+ }
+ if err := a.Start(ctx); err != nil {
+ return err
+ }
+
+ n.Lock()
+ n.agent = a
+ n.Unlock()
+
+ defer func() {
+ n.Lock()
+ n.agent = nil
+ n.Unlock()
+ }()
+
+ go func() {
+ <-a.Ready()
+ close(ready)
+ }()
+
+ // todo: manually call stop on context cancellation?
+
+ return a.Err(context.Background())
+}
+
+// Ready returns a channel that is closed after node's initialization has
+// completes for the first time.
+func (n *Node) Ready() <-chan struct{} {
+ return n.ready
+}
+
+func (n *Node) setControlSocket(conn *grpc.ClientConn) {
+ n.Lock()
+ if n.conn != nil {
+ n.conn.Close()
+ }
+ n.conn = conn
+ n.connBroker.SetLocalConn(conn)
+ n.connCond.Broadcast()
+ n.Unlock()
+}
+
+// ListenControlSocket listens changes of a connection for managing the
+// cluster control api
+func (n *Node) ListenControlSocket(ctx context.Context) <-chan *grpc.ClientConn {
+ c := make(chan *grpc.ClientConn, 1)
+ n.RLock()
+ conn := n.conn
+ c <- conn
+ done := make(chan struct{})
+ go func() {
+ select {
+ case <-ctx.Done():
+ n.connCond.Broadcast()
+ case <-done:
+ }
+ }()
+ go func() {
+ defer close(c)
+ defer close(done)
+ defer n.RUnlock()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+ if conn == n.conn {
+ n.connCond.Wait()
+ continue
+ }
+ conn = n.conn
+ select {
+ case c <- conn:
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ return c
+}
+
+// NodeID returns current node's ID. May be empty if not set.
+func (n *Node) NodeID() string {
+ n.RLock()
+ defer n.RUnlock()
+ return n.nodeID
+}
+
+// Manager returns manager instance started by node. May be nil.
+func (n *Node) Manager() *manager.Manager {
+ n.RLock()
+ defer n.RUnlock()
+ return n.manager
+}
+
+// Agent returns agent instance started by node. May be nil.
+func (n *Node) Agent() *agent.Agent {
+ n.RLock()
+ defer n.RUnlock()
+ return n.agent
+}
+
+// IsStateDirty returns true if any objects have been added to raft which make
+// the state "dirty". Currently, the existence of any object other than the
+// default cluster or the local node implies a dirty state.
+func (n *Node) IsStateDirty() (bool, error) {
+ n.RLock()
+ defer n.RUnlock()
+
+ if n.manager == nil {
+ return false, errors.New("node is not a manager")
+ }
+
+ return n.manager.IsStateDirty()
+}
+
+// Remotes returns a list of known peers known to node.
+func (n *Node) Remotes() []api.Peer {
+ weights := n.remotes.Weights()
+ remotes := make([]api.Peer, 0, len(weights))
+ for p := range weights {
+ remotes = append(remotes, p)
+ }
+ return remotes
+}
+
+func (n *Node) loadSecurityConfig(ctx context.Context, paths *ca.SecurityConfigPaths) (*ca.SecurityConfig, error) {
+ var securityConfig *ca.SecurityConfig
+
+ krw := ca.NewKeyReadWriter(paths.Node, n.unlockKey, &manager.RaftDEKData{})
+ if err := krw.Migrate(); err != nil {
+ return nil, err
+ }
+
+ // Check if we already have a valid certificates on disk.
+ rootCA, err := ca.GetLocalRootCA(paths.RootCA)
+ if err != nil && err != ca.ErrNoLocalRootCA {
+ return nil, err
+ }
+ if err == nil {
+ // if forcing a new cluster, we allow the certificates to be expired - a new set will be generated
+ securityConfig, err = ca.LoadSecurityConfig(ctx, rootCA, krw, n.config.ForceNewCluster)
+ if err != nil {
+ _, isInvalidKEK := errors.Cause(err).(ca.ErrInvalidKEK)
+ if isInvalidKEK {
+ return nil, ErrInvalidUnlockKey
+ } else if !os.IsNotExist(err) {
+ return nil, errors.Wrapf(err, "error while loading TLS certificate in %s", paths.Node.Cert)
+ }
+ }
+ }
+
+ if securityConfig == nil {
+ if n.config.JoinAddr == "" {
+ // if we're not joining a cluster, bootstrap a new one - and we have to set the unlock key
+ n.unlockKey = nil
+ if n.config.AutoLockManagers {
+ n.unlockKey = encryption.GenerateSecretKey()
+ }
+ krw = ca.NewKeyReadWriter(paths.Node, n.unlockKey, &manager.RaftDEKData{})
+ rootCA, err = ca.CreateRootCA(ca.DefaultRootCN)
+ if err != nil {
+ return nil, err
+ }
+ if err := ca.SaveRootCA(rootCA, paths.RootCA); err != nil {
+ return nil, err
+ }
+ log.G(ctx).Debug("generated CA key and certificate")
+ } else if err == ca.ErrNoLocalRootCA { // from previous error loading the root CA from disk
+ rootCA, err = ca.DownloadRootCA(ctx, paths.RootCA, n.config.JoinToken, n.connBroker)
+ if err != nil {
+ return nil, err
+ }
+ log.G(ctx).Debug("downloaded CA certificate")
+ }
+
+ // Obtain new certs and setup TLS certificates renewal for this node:
+ // - If certificates weren't present on disk, we call CreateSecurityConfig, which blocks
+ // until a valid certificate has been issued.
+ // - We wait for CreateSecurityConfig to finish since we need a certificate to operate.
+
+ // Attempt to load certificate from disk
+ securityConfig, err = ca.LoadSecurityConfig(ctx, rootCA, krw, n.config.ForceNewCluster)
+ if err == nil {
+ log.G(ctx).WithFields(logrus.Fields{
+ "node.id": securityConfig.ClientTLSCreds.NodeID(),
+ }).Debugf("loaded TLS certificate")
+ } else {
+ if _, ok := errors.Cause(err).(ca.ErrInvalidKEK); ok {
+ return nil, ErrInvalidUnlockKey
+ }
+ log.G(ctx).WithError(err).Debugf("no node credentials found in: %s", krw.Target())
+
+ securityConfig, err = rootCA.CreateSecurityConfig(ctx, krw, ca.CertificateRequestConfig{
+ Token: n.config.JoinToken,
+ Availability: n.config.Availability,
+ ConnBroker: n.connBroker,
+ })
+
+ if err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ n.Lock()
+ n.role = securityConfig.ClientTLSCreds.Role()
+ n.nodeID = securityConfig.ClientTLSCreds.NodeID()
+ n.roleCond.Broadcast()
+ n.Unlock()
+
+ return securityConfig, nil
+}
+
+func (n *Node) initManagerConnection(ctx context.Context, ready chan<- struct{}) error {
+ opts := []grpc.DialOption{
+ grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
+ grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor),
+ }
+ insecureCreds := credentials.NewTLS(&tls.Config{InsecureSkipVerify: true})
+ opts = append(opts, grpc.WithTransportCredentials(insecureCreds))
+ addr := n.config.ListenControlAPI
+ opts = append(opts, grpc.WithDialer(
+ func(addr string, timeout time.Duration) (net.Conn, error) {
+ return xnet.DialTimeoutLocal(addr, timeout)
+ }))
+ conn, err := grpc.Dial(addr, opts...)
+ if err != nil {
+ return err
+ }
+ client := api.NewHealthClient(conn)
+ for {
+ resp, err := client.Check(ctx, &api.HealthCheckRequest{Service: "ControlAPI"})
+ if err != nil {
+ return err
+ }
+ if resp.Status == api.HealthCheckResponse_SERVING {
+ break
+ }
+ time.Sleep(500 * time.Millisecond)
+ }
+ n.setControlSocket(conn)
+ if ready != nil {
+ close(ready)
+ }
+ return nil
+}
+
+func (n *Node) waitRole(ctx context.Context, role string) error {
+ n.roleCond.L.Lock()
+ if role == n.role {
+ n.roleCond.L.Unlock()
+ return nil
+ }
+ finishCh := make(chan struct{})
+ defer close(finishCh)
+ go func() {
+ select {
+ case <-finishCh:
+ case <-ctx.Done():
+ // call broadcast to shutdown this function
+ n.roleCond.Broadcast()
+ }
+ }()
+ defer n.roleCond.L.Unlock()
+ for role != n.role {
+ n.roleCond.Wait()
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+ }
+
+ return nil
+}
+
+func (n *Node) runManager(ctx context.Context, securityConfig *ca.SecurityConfig, rootPaths ca.CertPaths, ready chan struct{}, workerRole <-chan struct{}) (bool, error) {
+ var remoteAPI *manager.RemoteAddrs
+ if n.config.ListenRemoteAPI != "" {
+ remoteAPI = &manager.RemoteAddrs{
+ ListenAddr: n.config.ListenRemoteAPI,
+ AdvertiseAddr: n.config.AdvertiseRemoteAPI,
+ }
+ }
+
+ remoteAddr, _ := n.remotes.Select(n.NodeID())
+ m, err := manager.New(&manager.Config{
+ ForceNewCluster: n.config.ForceNewCluster,
+ RemoteAPI: remoteAPI,
+ ControlAPI: n.config.ListenControlAPI,
+ SecurityConfig: securityConfig,
+ ExternalCAs: n.config.ExternalCAs,
+ JoinRaft: remoteAddr.Addr,
+ StateDir: n.config.StateDir,
+ HeartbeatTick: n.config.HeartbeatTick,
+ ElectionTick: n.config.ElectionTick,
+ AutoLockManagers: n.config.AutoLockManagers,
+ UnlockKey: n.unlockKey,
+ Availability: n.config.Availability,
+ PluginGetter: n.config.PluginGetter,
+ RootCAPaths: rootPaths,
+ })
+ if err != nil {
+ return false, err
+ }
+ done := make(chan struct{})
+ var runErr error
+ go func(logger *logrus.Entry) {
+ if err := m.Run(log.WithLogger(context.Background(), logger)); err != nil {
+ runErr = err
+ }
+ close(done)
+ }(log.G(ctx))
+
+ var clearData bool
+ defer func() {
+ n.Lock()
+ n.manager = nil
+ n.Unlock()
+ m.Stop(ctx, clearData)
+ <-done
+ n.setControlSocket(nil)
+ }()
+
+ n.Lock()
+ n.manager = m
+ n.Unlock()
+
+ connCtx, connCancel := context.WithCancel(ctx)
+ defer connCancel()
+
+ go n.initManagerConnection(connCtx, ready)
+
+ // wait for manager stop or for role change
+ select {
+ case <-done:
+ return false, runErr
+ case <-workerRole:
+ log.G(ctx).Info("role changed to worker, stopping manager")
+ clearData = true
+ case <-m.RemovedFromRaft():
+ log.G(ctx).Info("manager removed from raft cluster, stopping manager")
+ clearData = true
+ case <-ctx.Done():
+ return false, ctx.Err()
+ }
+ return clearData, nil
+}
+
+func (n *Node) superviseManager(ctx context.Context, securityConfig *ca.SecurityConfig, rootPaths ca.CertPaths, ready chan struct{}, renewer *ca.TLSRenewer) error {
+ for {
+ if err := n.waitRole(ctx, ca.ManagerRole); err != nil {
+ return err
+ }
+
+ workerRole := make(chan struct{})
+ waitRoleCtx, waitRoleCancel := context.WithCancel(ctx)
+ go func() {
+ if n.waitRole(waitRoleCtx, ca.WorkerRole) == nil {
+ close(workerRole)
+ }
+ }()
+
+ wasRemoved, err := n.runManager(ctx, securityConfig, rootPaths, ready, workerRole)
+ if err != nil {
+ waitRoleCancel()
+ return errors.Wrap(err, "manager stopped")
+ }
+
+ // If the manager stopped running and our role is still
+ // "manager", it's possible that the manager was demoted and
+ // the agent hasn't realized this yet. We should wait for the
+ // role to change instead of restarting the manager immediately.
+ err = func() error {
+ timer := time.NewTimer(roleChangeTimeout)
+ defer timer.Stop()
+ defer waitRoleCancel()
+
+ select {
+ case <-timer.C:
+ case <-workerRole:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+
+ if !wasRemoved {
+ log.G(ctx).Warn("failed to get worker role after manager stop, restarting manager")
+ return nil
+ }
+ // We need to be extra careful about restarting the
+ // manager. It may cause the node to wrongly join under
+ // a new Raft ID. Since we didn't see a role change
+ // yet, force a certificate renewal. If the certificate
+ // comes back with a worker role, we know we shouldn't
+ // restart the manager. However, if we don't see
+ // workerRole get closed, it means we didn't switch to
+ // a worker certificate, either because we couldn't
+ // contact a working CA, or because we've been
+ // re-promoted. In this case, we must assume we were
+ // re-promoted, and restart the manager.
+ log.G(ctx).Warn("failed to get worker role after manager stop, forcing certificate renewal")
+ timer.Reset(roleChangeTimeout)
+
+ renewer.Renew()
+
+ // Now that the renewal request has been sent to the
+ // renewal goroutine, wait for a change in role.
+ select {
+ case <-timer.C:
+ log.G(ctx).Warn("failed to get worker role after manager stop, restarting manager")
+ case <-workerRole:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ return nil
+ }()
+ if err != nil {
+ return err
+ }
+
+ ready = nil
+ }
+}
+
+type persistentRemotes struct {
+ sync.RWMutex
+ c *sync.Cond
+ remotes.Remotes
+ storePath string
+ lastSavedState []api.Peer
+}
+
+func newPersistentRemotes(f string, peers ...api.Peer) *persistentRemotes {
+ pr := &persistentRemotes{
+ storePath: f,
+ Remotes: remotes.NewRemotes(peers...),
+ }
+ pr.c = sync.NewCond(pr.RLocker())
+ return pr
+}
+
+func (s *persistentRemotes) Observe(peer api.Peer, weight int) {
+ s.Lock()
+ defer s.Unlock()
+ s.Remotes.Observe(peer, weight)
+ s.c.Broadcast()
+ if err := s.save(); err != nil {
+ logrus.Errorf("error writing cluster state file: %v", err)
+ return
+ }
+ return
+}
+func (s *persistentRemotes) Remove(peers ...api.Peer) {
+ s.Lock()
+ defer s.Unlock()
+ s.Remotes.Remove(peers...)
+ if err := s.save(); err != nil {
+ logrus.Errorf("error writing cluster state file: %v", err)
+ return
+ }
+ return
+}
+
+func (s *persistentRemotes) save() error {
+ weights := s.Weights()
+ remotes := make([]api.Peer, 0, len(weights))
+ for r := range weights {
+ remotes = append(remotes, r)
+ }
+ sort.Sort(sortablePeers(remotes))
+ if reflect.DeepEqual(remotes, s.lastSavedState) {
+ return nil
+ }
+ dt, err := json.Marshal(remotes)
+ if err != nil {
+ return err
+ }
+ s.lastSavedState = remotes
+ return ioutils.AtomicWriteFile(s.storePath, dt, 0600)
+}
+
+// WaitSelect waits until at least one remote becomes available and then selects one.
+func (s *persistentRemotes) WaitSelect(ctx context.Context) <-chan api.Peer {
+ c := make(chan api.Peer, 1)
+ s.RLock()
+ done := make(chan struct{})
+ go func() {
+ select {
+ case <-ctx.Done():
+ s.c.Broadcast()
+ case <-done:
+ }
+ }()
+ go func() {
+ defer s.RUnlock()
+ defer close(c)
+ defer close(done)
+ for {
+ if ctx.Err() != nil {
+ return
+ }
+ p, err := s.Select()
+ if err == nil {
+ c <- p
+ return
+ }
+ s.c.Wait()
+ }
+ }()
+ return c
+}
+
+// sortablePeers is a sort wrapper for []api.Peer
+type sortablePeers []api.Peer
+
+func (sp sortablePeers) Less(i, j int) bool { return sp[i].NodeID < sp[j].NodeID }
+
+func (sp sortablePeers) Len() int { return len(sp) }
+
+func (sp sortablePeers) Swap(i, j int) { sp[i], sp[j] = sp[j], sp[i] }
+
+// firstSessionErrorTracker is a utility that helps determine whether the agent should exit after
+// a TLS failure on establishing the first session. This should only happen if a join address
+// is specified. If establishing the first session succeeds, but later on some session fails
+// because of a TLS error, we don't want to exit the agent because a previously successful
+// session indicates that the TLS error may be a transient issue.
+type firstSessionErrorTracker struct {
+ mu sync.Mutex
+ pastFirstSession bool
+ err error
+}
+
+func (fs *firstSessionErrorTracker) SessionEstablished() {
+ fs.mu.Lock()
+ fs.pastFirstSession = true
+ fs.mu.Unlock()
+}
+
+func (fs *firstSessionErrorTracker) SessionError(err error) {
+ fs.mu.Lock()
+ fs.err = err
+ fs.mu.Unlock()
+}
+
+func (fs *firstSessionErrorTracker) SessionClosed() error {
+ fs.mu.Lock()
+ defer fs.mu.Unlock()
+ // unfortunately grpc connection errors are type grpc.rpcError, which are not exposed, and we can't get at the underlying error type
+ if !fs.pastFirstSession && grpc.Code(fs.err) == codes.Internal &&
+ strings.HasPrefix(grpc.ErrorDesc(fs.err), "connection error") && strings.Contains(grpc.ErrorDesc(fs.err), "transport: x509:") {
+ return fs.err
+ }
+ return nil
+}
diff --git a/vendor/github.com/docker/swarmkit/protobuf/plugin/gen.go b/vendor/github.com/docker/swarmkit/protobuf/plugin/gen.go
new file mode 100644
index 0000000..b68b837
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/protobuf/plugin/gen.go
@@ -0,0 +1,3 @@
+package plugin
+
+//go:generate protoc -I.:/usr/local --gogoswarm_out=import_path=github.com/docker/swarmkit/protobuf/plugin,Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor:. plugin.proto
diff --git a/vendor/github.com/docker/swarmkit/protobuf/plugin/helpers.go b/vendor/github.com/docker/swarmkit/protobuf/plugin/helpers.go
new file mode 100644
index 0000000..daea795
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/protobuf/plugin/helpers.go
@@ -0,0 +1,11 @@
+package plugin
+
+import (
+ "github.com/gogo/protobuf/proto"
+ google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
+)
+
+// DeepcopyEnabled returns true if deepcopy is enabled for the descriptor.
+func DeepcopyEnabled(options *google_protobuf.MessageOptions) bool {
+ return proto.GetBoolExtension(options, E_Deepcopy, true)
+}
diff --git a/vendor/github.com/docker/swarmkit/protobuf/plugin/plugin.pb.go b/vendor/github.com/docker/swarmkit/protobuf/plugin/plugin.pb.go
new file mode 100644
index 0000000..9cafe73
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/protobuf/plugin/plugin.pb.go
@@ -0,0 +1,1185 @@
+// Code generated by protoc-gen-gogo.
+// source: plugin.proto
+// DO NOT EDIT!
+
+/*
+ Package plugin is a generated protocol buffer package.
+
+ It is generated from these files:
+ plugin.proto
+
+ It has these top-level messages:
+ WatchSelectors
+ StoreObject
+ TLSAuthorization
+*/
+package plugin
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
+
+import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+type WatchSelectors struct {
+ // supported by all object types
+ ID *bool `protobuf:"varint,1,opt,name=id" json:"id,omitempty"`
+ IDPrefix *bool `protobuf:"varint,2,opt,name=id_prefix,json=idPrefix" json:"id_prefix,omitempty"`
+ Name *bool `protobuf:"varint,3,opt,name=name" json:"name,omitempty"`
+ NamePrefix *bool `protobuf:"varint,4,opt,name=name_prefix,json=namePrefix" json:"name_prefix,omitempty"`
+ Custom *bool `protobuf:"varint,5,opt,name=custom" json:"custom,omitempty"`
+ CustomPrefix *bool `protobuf:"varint,6,opt,name=custom_prefix,json=customPrefix" json:"custom_prefix,omitempty"`
+ // supported by tasks only
+ ServiceID *bool `protobuf:"varint,7,opt,name=service_id,json=serviceId" json:"service_id,omitempty"`
+ NodeID *bool `protobuf:"varint,8,opt,name=node_id,json=nodeId" json:"node_id,omitempty"`
+ Slot *bool `protobuf:"varint,9,opt,name=slot" json:"slot,omitempty"`
+ DesiredState *bool `protobuf:"varint,10,opt,name=desired_state,json=desiredState" json:"desired_state,omitempty"`
+ // supported by nodes only
+ Role *bool `protobuf:"varint,11,opt,name=role" json:"role,omitempty"`
+ Membership *bool `protobuf:"varint,12,opt,name=membership" json:"membership,omitempty"`
+ // supported by: resource
+ Kind *bool `protobuf:"varint,13,opt,name=kind" json:"kind,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *WatchSelectors) Reset() { *m = WatchSelectors{} }
+func (*WatchSelectors) ProtoMessage() {}
+func (*WatchSelectors) Descriptor() ([]byte, []int) { return fileDescriptorPlugin, []int{0} }
+
+type StoreObject struct {
+ WatchSelectors *WatchSelectors `protobuf:"bytes,1,req,name=watch_selectors,json=watchSelectors" json:"watch_selectors,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *StoreObject) Reset() { *m = StoreObject{} }
+func (*StoreObject) ProtoMessage() {}
+func (*StoreObject) Descriptor() ([]byte, []int) { return fileDescriptorPlugin, []int{1} }
+
+type TLSAuthorization struct {
+ // Roles contains the acceptable TLS OU roles for the handler.
+ Roles []string `protobuf:"bytes,1,rep,name=roles" json:"roles,omitempty"`
+ // Insecure is set to true if this method does not require
+ // authorization. NOTE: Specifying both "insecure" and a nonempty
+ // list of roles is invalid. This would fail at codegen time.
+ Insecure *bool `protobuf:"varint,2,opt,name=insecure" json:"insecure,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *TLSAuthorization) Reset() { *m = TLSAuthorization{} }
+func (*TLSAuthorization) ProtoMessage() {}
+func (*TLSAuthorization) Descriptor() ([]byte, []int) { return fileDescriptorPlugin, []int{2} }
+
+var E_Deepcopy = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 70000,
+ Name: "docker.protobuf.plugin.deepcopy",
+ Tag: "varint,70000,opt,name=deepcopy,def=1",
+ Filename: "plugin.proto",
+}
+
+var E_StoreObject = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*StoreObject)(nil),
+ Field: 70001,
+ Name: "docker.protobuf.plugin.store_object",
+ Tag: "bytes,70001,opt,name=store_object,json=storeObject",
+ Filename: "plugin.proto",
+}
+
+var E_TlsAuthorization = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MethodOptions)(nil),
+ ExtensionType: (*TLSAuthorization)(nil),
+ Field: 73626345,
+ Name: "docker.protobuf.plugin.tls_authorization",
+ Tag: "bytes,73626345,opt,name=tls_authorization,json=tlsAuthorization",
+ Filename: "plugin.proto",
+}
+
+func init() {
+ proto.RegisterType((*WatchSelectors)(nil), "docker.protobuf.plugin.WatchSelectors")
+ proto.RegisterType((*StoreObject)(nil), "docker.protobuf.plugin.StoreObject")
+ proto.RegisterType((*TLSAuthorization)(nil), "docker.protobuf.plugin.TLSAuthorization")
+ proto.RegisterExtension(E_Deepcopy)
+ proto.RegisterExtension(E_StoreObject)
+ proto.RegisterExtension(E_TlsAuthorization)
+}
+func (m *WatchSelectors) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *WatchSelectors) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.ID != nil {
+ dAtA[i] = 0x8
+ i++
+ if *m.ID {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.IDPrefix != nil {
+ dAtA[i] = 0x10
+ i++
+ if *m.IDPrefix {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Name != nil {
+ dAtA[i] = 0x18
+ i++
+ if *m.Name {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.NamePrefix != nil {
+ dAtA[i] = 0x20
+ i++
+ if *m.NamePrefix {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Custom != nil {
+ dAtA[i] = 0x28
+ i++
+ if *m.Custom {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.CustomPrefix != nil {
+ dAtA[i] = 0x30
+ i++
+ if *m.CustomPrefix {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.ServiceID != nil {
+ dAtA[i] = 0x38
+ i++
+ if *m.ServiceID {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.NodeID != nil {
+ dAtA[i] = 0x40
+ i++
+ if *m.NodeID {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Slot != nil {
+ dAtA[i] = 0x48
+ i++
+ if *m.Slot {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.DesiredState != nil {
+ dAtA[i] = 0x50
+ i++
+ if *m.DesiredState {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Role != nil {
+ dAtA[i] = 0x58
+ i++
+ if *m.Role {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Membership != nil {
+ dAtA[i] = 0x60
+ i++
+ if *m.Membership {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.Kind != nil {
+ dAtA[i] = 0x68
+ i++
+ if *m.Kind {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func (m *StoreObject) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *StoreObject) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.WatchSelectors == nil {
+ return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("watch_selectors")
+ } else {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintPlugin(dAtA, i, uint64(m.WatchSelectors.Size()))
+ n1, err := m.WatchSelectors.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ }
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func (m *TLSAuthorization) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *TLSAuthorization) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Roles) > 0 {
+ for _, s := range m.Roles {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ if m.Insecure != nil {
+ dAtA[i] = 0x10
+ i++
+ if *m.Insecure {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ if m.XXX_unrecognized != nil {
+ i += copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ return i, nil
+}
+
+func encodeFixed64Plugin(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Plugin(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintPlugin(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func (m *WatchSelectors) Size() (n int) {
+ var l int
+ _ = l
+ if m.ID != nil {
+ n += 2
+ }
+ if m.IDPrefix != nil {
+ n += 2
+ }
+ if m.Name != nil {
+ n += 2
+ }
+ if m.NamePrefix != nil {
+ n += 2
+ }
+ if m.Custom != nil {
+ n += 2
+ }
+ if m.CustomPrefix != nil {
+ n += 2
+ }
+ if m.ServiceID != nil {
+ n += 2
+ }
+ if m.NodeID != nil {
+ n += 2
+ }
+ if m.Slot != nil {
+ n += 2
+ }
+ if m.DesiredState != nil {
+ n += 2
+ }
+ if m.Role != nil {
+ n += 2
+ }
+ if m.Membership != nil {
+ n += 2
+ }
+ if m.Kind != nil {
+ n += 2
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *StoreObject) Size() (n int) {
+ var l int
+ _ = l
+ if m.WatchSelectors != nil {
+ l = m.WatchSelectors.Size()
+ n += 1 + l + sovPlugin(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *TLSAuthorization) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Roles) > 0 {
+ for _, s := range m.Roles {
+ l = len(s)
+ n += 1 + l + sovPlugin(uint64(l))
+ }
+ }
+ if m.Insecure != nil {
+ n += 2
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func sovPlugin(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozPlugin(x uint64) (n int) {
+ return sovPlugin(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *WatchSelectors) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&WatchSelectors{`,
+ `ID:` + valueToStringPlugin(this.ID) + `,`,
+ `IDPrefix:` + valueToStringPlugin(this.IDPrefix) + `,`,
+ `Name:` + valueToStringPlugin(this.Name) + `,`,
+ `NamePrefix:` + valueToStringPlugin(this.NamePrefix) + `,`,
+ `Custom:` + valueToStringPlugin(this.Custom) + `,`,
+ `CustomPrefix:` + valueToStringPlugin(this.CustomPrefix) + `,`,
+ `ServiceID:` + valueToStringPlugin(this.ServiceID) + `,`,
+ `NodeID:` + valueToStringPlugin(this.NodeID) + `,`,
+ `Slot:` + valueToStringPlugin(this.Slot) + `,`,
+ `DesiredState:` + valueToStringPlugin(this.DesiredState) + `,`,
+ `Role:` + valueToStringPlugin(this.Role) + `,`,
+ `Membership:` + valueToStringPlugin(this.Membership) + `,`,
+ `Kind:` + valueToStringPlugin(this.Kind) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StoreObject) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StoreObject{`,
+ `WatchSelectors:` + strings.Replace(fmt.Sprintf("%v", this.WatchSelectors), "WatchSelectors", "WatchSelectors", 1) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *TLSAuthorization) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&TLSAuthorization{`,
+ `Roles:` + fmt.Sprintf("%v", this.Roles) + `,`,
+ `Insecure:` + valueToStringPlugin(this.Insecure) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringPlugin(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *WatchSelectors) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: WatchSelectors: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: WatchSelectors: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.ID = &b
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IDPrefix", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.IDPrefix = &b
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.Name = &b
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NamePrefix", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.NamePrefix = &b
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Custom", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.Custom = &b
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CustomPrefix", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.CustomPrefix = &b
+ case 7:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ServiceID", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.ServiceID = &b
+ case 8:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NodeID", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.NodeID = &b
+ case 9:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Slot", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.Slot = &b
+ case 10:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field DesiredState", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.DesiredState = &b
+ case 11:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Role", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.Role = &b
+ case 12:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Membership", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.Membership = &b
+ case 13:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.Kind = &b
+ default:
+ iNdEx = preIndex
+ skippy, err := skipPlugin(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthPlugin
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *StoreObject) Unmarshal(dAtA []byte) error {
+ var hasFields [1]uint64
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: StoreObject: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: StoreObject: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field WatchSelectors", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthPlugin
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.WatchSelectors == nil {
+ m.WatchSelectors = &WatchSelectors{}
+ }
+ if err := m.WatchSelectors.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ hasFields[0] |= uint64(0x00000001)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipPlugin(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthPlugin
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+ if hasFields[0]&uint64(0x00000001) == 0 {
+ return github_com_gogo_protobuf_proto.NewRequiredNotSetError("watch_selectors")
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *TLSAuthorization) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: TLSAuthorization: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: TLSAuthorization: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Roles", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthPlugin
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Roles = append(m.Roles, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Insecure", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.Insecure = &b
+ default:
+ iNdEx = preIndex
+ skippy, err := skipPlugin(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthPlugin
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipPlugin(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthPlugin
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowPlugin
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipPlugin(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthPlugin = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowPlugin = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("plugin.proto", fileDescriptorPlugin) }
+
+var fileDescriptorPlugin = []byte{
+ // 551 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x52, 0xc1, 0x6e, 0xd3, 0x40,
+ 0x10, 0xad, 0xd3, 0x36, 0x4d, 0xc6, 0x69, 0x29, 0x2b, 0x54, 0xad, 0x7a, 0xb0, 0xab, 0x46, 0x42,
+ 0x41, 0x42, 0xa9, 0xd4, 0x63, 0x6e, 0x94, 0x5c, 0x22, 0x01, 0x45, 0x0e, 0x12, 0x37, 0x2c, 0xd7,
+ 0x3b, 0x4d, 0x96, 0x3a, 0x5e, 0x6b, 0x77, 0x4d, 0x0b, 0x27, 0x7e, 0x80, 0x0f, 0xe0, 0xca, 0xd7,
+ 0xf4, 0xc8, 0x91, 0x53, 0x44, 0x2d, 0x71, 0xe0, 0x06, 0x7f, 0x80, 0x76, 0xd7, 0x69, 0x09, 0x6a,
+ 0xc5, 0xc9, 0x33, 0x6f, 0xe6, 0xcd, 0xcc, 0xdb, 0x67, 0xe8, 0x14, 0x59, 0x39, 0xe1, 0x79, 0xbf,
+ 0x90, 0x42, 0x0b, 0xb2, 0xc3, 0x44, 0x7a, 0x86, 0xd2, 0x65, 0x27, 0xe5, 0x69, 0xdf, 0x55, 0x77,
+ 0xf7, 0x26, 0x42, 0x4c, 0x32, 0x3c, 0x58, 0xe0, 0x07, 0x0c, 0x55, 0x2a, 0x79, 0xa1, 0x45, 0xdd,
+ 0xbb, 0xff, 0x79, 0x15, 0xb6, 0x5e, 0x27, 0x3a, 0x9d, 0x8e, 0x31, 0xc3, 0x54, 0x0b, 0xa9, 0xc8,
+ 0x0e, 0x34, 0x38, 0xa3, 0xde, 0x9e, 0xd7, 0x6b, 0x1d, 0x35, 0xab, 0x79, 0xd8, 0x18, 0x0d, 0xa3,
+ 0x06, 0x67, 0xe4, 0x11, 0xb4, 0x39, 0x8b, 0x0b, 0x89, 0xa7, 0xfc, 0x82, 0x36, 0x6c, 0xb9, 0x53,
+ 0xcd, 0xc3, 0xd6, 0x68, 0xf8, 0xd2, 0x62, 0x51, 0x8b, 0x33, 0x17, 0x11, 0x02, 0x6b, 0x79, 0x32,
+ 0x43, 0xba, 0x6a, 0xba, 0x22, 0x1b, 0x93, 0x10, 0x7c, 0xf3, 0x5d, 0x0c, 0x58, 0xb3, 0x25, 0x30,
+ 0x50, 0x4d, 0xda, 0x81, 0x66, 0x5a, 0x2a, 0x2d, 0x66, 0x74, 0xdd, 0xd6, 0xea, 0x8c, 0x74, 0x61,
+ 0xd3, 0x45, 0x0b, 0x6a, 0xd3, 0x96, 0x3b, 0x0e, 0xac, 0xc9, 0x8f, 0x01, 0x14, 0xca, 0x77, 0x3c,
+ 0xc5, 0x98, 0x33, 0xba, 0x61, 0xaf, 0xdb, 0xac, 0xe6, 0x61, 0x7b, 0xec, 0xd0, 0xd1, 0x30, 0x6a,
+ 0xd7, 0x0d, 0x23, 0x46, 0xba, 0xb0, 0x91, 0x0b, 0x66, 0x5b, 0x5b, 0xb6, 0x15, 0xaa, 0x79, 0xd8,
+ 0x7c, 0x21, 0x98, 0xe9, 0x6b, 0x9a, 0xd2, 0x88, 0x19, 0x11, 0x2a, 0x13, 0x9a, 0xb6, 0x9d, 0x08,
+ 0x13, 0x9b, 0x5b, 0x18, 0x2a, 0x2e, 0x91, 0xc5, 0x4a, 0x27, 0x1a, 0x29, 0xb8, 0x5b, 0x6a, 0x70,
+ 0x6c, 0x30, 0x43, 0x94, 0x22, 0x43, 0xea, 0x3b, 0xa2, 0x89, 0x49, 0x00, 0x30, 0xc3, 0xd9, 0x09,
+ 0x4a, 0x35, 0xe5, 0x05, 0xed, 0x38, 0xf1, 0x37, 0x88, 0xe1, 0x9c, 0xf1, 0x9c, 0xd1, 0x4d, 0xc7,
+ 0x31, 0xf1, 0xfe, 0x1b, 0xf0, 0xc7, 0x5a, 0x48, 0x3c, 0x3e, 0x79, 0x8b, 0xa9, 0x26, 0xc7, 0x70,
+ 0xef, 0xdc, 0x38, 0x15, 0xab, 0x85, 0x55, 0xd4, 0xdb, 0x6b, 0xf4, 0xfc, 0xc3, 0x87, 0xfd, 0xdb,
+ 0xed, 0xef, 0x2f, 0x1b, 0x1b, 0x6d, 0x9d, 0x2f, 0xe5, 0xfb, 0x43, 0xd8, 0x7e, 0xf5, 0x6c, 0xfc,
+ 0xa4, 0xd4, 0x53, 0x21, 0xf9, 0x87, 0x44, 0x73, 0x91, 0x93, 0x07, 0xb0, 0x6e, 0xee, 0x35, 0xa3,
+ 0x57, 0x7b, 0xed, 0xc8, 0x25, 0x64, 0x17, 0x5a, 0x3c, 0x57, 0x98, 0x96, 0x12, 0x9d, 0xf3, 0xd1,
+ 0x75, 0x3e, 0x78, 0x0a, 0x2d, 0x86, 0x58, 0xa4, 0xa2, 0x78, 0x4f, 0xc2, 0xbe, 0xfb, 0xe1, 0x6e,
+ 0x2e, 0x79, 0x8e, 0x4a, 0x25, 0x13, 0x3c, 0x2e, 0xcc, 0x74, 0x45, 0x7f, 0x7d, 0xb1, 0xbe, 0x0f,
+ 0xd6, 0xb4, 0x2c, 0x31, 0xba, 0x26, 0x0e, 0x38, 0x74, 0x94, 0x91, 0x1a, 0x0b, 0xa7, 0xf5, 0xbf,
+ 0x83, 0x7e, 0xdb, 0x41, 0xfe, 0x61, 0xf7, 0x2e, 0xed, 0x7f, 0xbd, 0x5c, 0xe4, 0xab, 0x9b, 0x64,
+ 0x70, 0x01, 0xf7, 0x75, 0xa6, 0xe2, 0x64, 0x49, 0x76, 0x70, 0xcb, 0x3e, 0x3d, 0x15, 0x6c, 0xb1,
+ 0xee, 0xe7, 0x8f, 0x4f, 0x5d, 0xbb, 0xaf, 0x77, 0xd7, 0xbe, 0x7f, 0x5f, 0x32, 0xda, 0xd6, 0x99,
+ 0x5a, 0x42, 0x8e, 0xe8, 0xe5, 0x55, 0xb0, 0xf2, 0xed, 0x2a, 0x58, 0xf9, 0x58, 0x05, 0xde, 0x65,
+ 0x15, 0x78, 0x5f, 0xab, 0xc0, 0xfb, 0x5e, 0x05, 0xde, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x94,
+ 0xd6, 0x21, 0x73, 0xce, 0x03, 0x00, 0x00,
+}
diff --git a/vendor/github.com/docker/swarmkit/protobuf/plugin/plugin.proto b/vendor/github.com/docker/swarmkit/protobuf/plugin/plugin.proto
new file mode 100644
index 0000000..312517d
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/protobuf/plugin/plugin.proto
@@ -0,0 +1,53 @@
+syntax = "proto2";
+
+package docker.protobuf.plugin;
+
+import "google/protobuf/descriptor.proto";
+
+message WatchSelectors {
+ // supported by all object types
+ optional bool id = 1;
+ optional bool id_prefix = 2;
+ optional bool name = 3;
+ optional bool name_prefix = 4;
+ optional bool custom = 5;
+ optional bool custom_prefix = 6;
+
+ // supported by tasks only
+ optional bool service_id = 7;
+ optional bool node_id = 8;
+ optional bool slot = 9;
+ optional bool desired_state = 10;
+
+ // supported by nodes only
+ optional bool role = 11;
+ optional bool membership = 12;
+
+ // supported by: resource
+ optional bool kind = 13;
+}
+
+message StoreObject {
+ required WatchSelectors watch_selectors = 1;
+}
+
+extend google.protobuf.MessageOptions {
+ optional bool deepcopy = 70000 [default=true];
+ optional StoreObject store_object = 70001;
+}
+
+message TLSAuthorization {
+ // Roles contains the acceptable TLS OU roles for the handler.
+ repeated string roles = 1;
+
+ // Insecure is set to true if this method does not require
+ // authorization. NOTE: Specifying both "insecure" and a nonempty
+ // list of roles is invalid. This would fail at codegen time.
+ optional bool insecure = 2;
+}
+
+extend google.protobuf.MethodOptions {
+ // TLSAuthorization contains the authorization parameters for this
+ // method.
+ optional TLSAuthorization tls_authorization = 73626345;
+}
diff --git a/vendor/github.com/docker/swarmkit/protobuf/ptypes/doc.go b/vendor/github.com/docker/swarmkit/protobuf/ptypes/doc.go
new file mode 100644
index 0000000..b997ca1
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/protobuf/ptypes/doc.go
@@ -0,0 +1,3 @@
+// Package ptypes provides utility functions for use with
+// gogo/protobuf/ptypes.
+package ptypes
diff --git a/vendor/github.com/docker/swarmkit/protobuf/ptypes/timestamp.go b/vendor/github.com/docker/swarmkit/protobuf/ptypes/timestamp.go
new file mode 100644
index 0000000..3890384
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/protobuf/ptypes/timestamp.go
@@ -0,0 +1,17 @@
+package ptypes
+
+import (
+ "time"
+
+ gogotypes "github.com/gogo/protobuf/types"
+)
+
+// MustTimestampProto converts time.Time to a google.protobuf.Timestamp proto.
+// It panics if input timestamp is invalid.
+func MustTimestampProto(t time.Time) *gogotypes.Timestamp {
+ ts, err := gogotypes.TimestampProto(t)
+ if err != nil {
+ panic(err.Error())
+ }
+ return ts
+}
diff --git a/vendor/github.com/docker/swarmkit/remotes/remotes.go b/vendor/github.com/docker/swarmkit/remotes/remotes.go
new file mode 100644
index 0000000..e79ed3f
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/remotes/remotes.go
@@ -0,0 +1,203 @@
+package remotes
+
+import (
+ "fmt"
+ "math"
+ "math/rand"
+ "sort"
+ "sync"
+
+ "github.com/docker/swarmkit/api"
+)
+
+var errRemotesUnavailable = fmt.Errorf("no remote hosts provided")
+
+// DefaultObservationWeight provides a weight to use for positive observations
+// that will balance well under repeated observations.
+const DefaultObservationWeight = 10
+
+// Remotes keeps track of remote addresses by weight, informed by
+// observations.
+type Remotes interface {
+ // Weight returns the remotes with their current weights.
+ Weights() map[api.Peer]int
+
+ // Select a remote from the set of available remotes with optionally
+ // excluding ID or address.
+ Select(...string) (api.Peer, error)
+
+ // Observe records an experience with a particular remote. A positive weight
+ // indicates a good experience and a negative weight a bad experience.
+ //
+ // The observation will be used to calculate a moving weight, which is
+ // implementation dependent. This method will be called such that repeated
+ // observations of the same master in each session request are favored.
+ Observe(peer api.Peer, weight int)
+
+ // ObserveIfExists records an experience with a particular remote if when a
+ // remote exists.
+ ObserveIfExists(peer api.Peer, weight int)
+
+ // Remove the remote from the list completely.
+ Remove(addrs ...api.Peer)
+}
+
+// NewRemotes returns a Remotes instance with the provided set of addresses.
+// Entries provided are heavily weighted initially.
+func NewRemotes(peers ...api.Peer) Remotes {
+ mwr := &remotesWeightedRandom{
+ remotes: make(map[api.Peer]int),
+ }
+
+ for _, peer := range peers {
+ mwr.Observe(peer, DefaultObservationWeight)
+ }
+
+ return mwr
+}
+
+type remotesWeightedRandom struct {
+ remotes map[api.Peer]int
+ mu sync.Mutex
+
+ // workspace to avoid reallocation. these get lazily allocated when
+ // selecting values.
+ cdf []float64
+ peers []api.Peer
+}
+
+func (mwr *remotesWeightedRandom) Weights() map[api.Peer]int {
+ mwr.mu.Lock()
+ defer mwr.mu.Unlock()
+
+ ms := make(map[api.Peer]int, len(mwr.remotes))
+ for addr, weight := range mwr.remotes {
+ ms[addr] = weight
+ }
+
+ return ms
+}
+
+func (mwr *remotesWeightedRandom) Select(excludes ...string) (api.Peer, error) {
+ mwr.mu.Lock()
+ defer mwr.mu.Unlock()
+
+ // NOTE(stevvooe): We then use a weighted random selection algorithm
+ // (http://stackoverflow.com/questions/4463561/weighted-random-selection-from-array)
+ // to choose the master to connect to.
+ //
+ // It is possible that this is insufficient. The following may inform a
+ // better solution:
+
+ // https://github.com/LK4D4/sample
+ //
+ // The first link applies exponential distribution weight choice reservoir
+ // sampling. This may be relevant if we view the master selection as a
+ // distributed reservoir sampling problem.
+
+ // bias to zero-weighted remotes have same probability. otherwise, we
+ // always select first entry when all are zero.
+ const bias = 0.001
+
+ // clear out workspace
+ mwr.cdf = mwr.cdf[:0]
+ mwr.peers = mwr.peers[:0]
+
+ cum := 0.0
+ // calculate CDF over weights
+Loop:
+ for peer, weight := range mwr.remotes {
+ for _, exclude := range excludes {
+ if peer.NodeID == exclude || peer.Addr == exclude {
+ // if this peer is excluded, ignore it by continuing the loop to label Loop
+ continue Loop
+ }
+ }
+ if weight < 0 {
+ // treat these as zero, to keep there selection unlikely.
+ weight = 0
+ }
+
+ cum += float64(weight) + bias
+ mwr.cdf = append(mwr.cdf, cum)
+ mwr.peers = append(mwr.peers, peer)
+ }
+
+ if len(mwr.peers) == 0 {
+ return api.Peer{}, errRemotesUnavailable
+ }
+
+ r := mwr.cdf[len(mwr.cdf)-1] * rand.Float64()
+ i := sort.SearchFloat64s(mwr.cdf, r)
+
+ return mwr.peers[i], nil
+}
+
+func (mwr *remotesWeightedRandom) Observe(peer api.Peer, weight int) {
+ mwr.mu.Lock()
+ defer mwr.mu.Unlock()
+
+ mwr.observe(peer, float64(weight))
+}
+
+func (mwr *remotesWeightedRandom) ObserveIfExists(peer api.Peer, weight int) {
+ mwr.mu.Lock()
+ defer mwr.mu.Unlock()
+
+ if _, ok := mwr.remotes[peer]; !ok {
+ return
+ }
+
+ mwr.observe(peer, float64(weight))
+}
+
+func (mwr *remotesWeightedRandom) Remove(addrs ...api.Peer) {
+ mwr.mu.Lock()
+ defer mwr.mu.Unlock()
+
+ for _, addr := range addrs {
+ delete(mwr.remotes, addr)
+ }
+}
+
+const (
+ // remoteWeightSmoothingFactor for exponential smoothing. This adjusts how
+ // much of the // observation and old value we are using to calculate the new value.
+ // See
+ // https://en.wikipedia.org/wiki/Exponential_smoothing#Basic_exponential_smoothing
+ // for details.
+ remoteWeightSmoothingFactor = 0.5
+ remoteWeightMax = 1 << 8
+)
+
+func clip(x float64) float64 {
+ if math.IsNaN(x) {
+ // treat garbage as such
+ // acts like a no-op for us.
+ return 0
+ }
+ return math.Max(math.Min(remoteWeightMax, x), -remoteWeightMax)
+}
+
+func (mwr *remotesWeightedRandom) observe(peer api.Peer, weight float64) {
+
+ // While we have a decent, ad-hoc approach here to weight subsequent
+ // observations, we may want to look into applying forward decay:
+ //
+ // http://dimacs.rutgers.edu/~graham/pubs/papers/fwddecay.pdf
+ //
+ // We need to get better data from behavior in a cluster.
+
+ // makes the math easier to read below
+ var (
+ w0 = float64(mwr.remotes[peer])
+ w1 = clip(weight)
+ )
+ const α = remoteWeightSmoothingFactor
+
+ // Multiply the new value to current value, and appy smoothing against the old
+ // value.
+ wn := clip(α*w1 + (1-α)*w0)
+
+ mwr.remotes[peer] = int(math.Ceil(wn))
+}
diff --git a/vendor/github.com/docker/swarmkit/template/context.go b/vendor/github.com/docker/swarmkit/template/context.go
new file mode 100644
index 0000000..d26e155
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/template/context.go
@@ -0,0 +1,192 @@
+package template
+
+import (
+ "bytes"
+ "fmt"
+ "strings"
+ "text/template"
+
+ "github.com/docker/swarmkit/agent/configs"
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/agent/secrets"
+ "github.com/docker/swarmkit/api"
+ "github.com/docker/swarmkit/api/naming"
+ "github.com/pkg/errors"
+)
+
+// Context defines the strict set of values that can be injected into a
+// template expression in SwarmKit data structure.
+// NOTE: Be very careful adding any fields to this structure with types
+// that have methods defined on them. The template would be able to
+// invoke those methods.
+type Context struct {
+ Service struct {
+ ID string
+ Name string
+ Labels map[string]string
+ }
+
+ Node struct {
+ ID string
+ }
+
+ Task struct {
+ ID string
+ Name string
+ Slot string
+
+ // NOTE(stevvooe): Why no labels here? Tasks don't actually have labels
+ // (from a user perspective). The labels are part of the container! If
+ // one wants to use labels for templating, use service labels!
+ }
+}
+
+// NewContextFromTask returns a new template context from the data available in
+// task. The provided context can then be used to populate runtime values in a
+// ContainerSpec.
+func NewContextFromTask(t *api.Task) (ctx Context) {
+ ctx.Service.ID = t.ServiceID
+ ctx.Service.Name = t.ServiceAnnotations.Name
+ ctx.Service.Labels = t.ServiceAnnotations.Labels
+
+ ctx.Node.ID = t.NodeID
+
+ ctx.Task.ID = t.ID
+ ctx.Task.Name = naming.Task(t)
+
+ if t.Slot != 0 {
+ ctx.Task.Slot = fmt.Sprint(t.Slot)
+ } else {
+ // fall back to node id for slot when there is no slot
+ ctx.Task.Slot = t.NodeID
+ }
+
+ return
+}
+
+// Expand treats the string s as a template and populates it with values from
+// the context.
+func (ctx *Context) Expand(s string) (string, error) {
+ tmpl, err := newTemplate(s, nil)
+ if err != nil {
+ return s, err
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, ctx); err != nil {
+ return s, err
+ }
+
+ return buf.String(), nil
+}
+
+// PayloadContext provides a context for expanding a config or secret payload.
+// NOTE: Be very careful adding any fields to this structure with types
+// that have methods defined on them. The template would be able to
+// invoke those methods.
+type PayloadContext struct {
+ Context
+
+ t *api.Task
+ restrictedSecrets exec.SecretGetter
+ restrictedConfigs exec.ConfigGetter
+}
+
+func (ctx PayloadContext) secretGetter(target string) (string, error) {
+ if ctx.restrictedSecrets == nil {
+ return "", errors.New("secrets unavailable")
+ }
+
+ container := ctx.t.Spec.GetContainer()
+ if container == nil {
+ return "", errors.New("task is not a container")
+ }
+
+ for _, secretRef := range container.Secrets {
+ file := secretRef.GetFile()
+ if file != nil && file.Name == target {
+ secret, err := ctx.restrictedSecrets.Get(secretRef.SecretID)
+ if err != nil {
+ return "", err
+ }
+ return string(secret.Spec.Data), nil
+ }
+ }
+
+ return "", errors.Errorf("secret target %s not found", target)
+}
+
+func (ctx PayloadContext) configGetter(target string) (string, error) {
+ if ctx.restrictedConfigs == nil {
+ return "", errors.New("configs unavailable")
+ }
+
+ container := ctx.t.Spec.GetContainer()
+ if container == nil {
+ return "", errors.New("task is not a container")
+ }
+
+ for _, configRef := range container.Configs {
+ file := configRef.GetFile()
+ if file != nil && file.Name == target {
+ config, err := ctx.restrictedConfigs.Get(configRef.ConfigID)
+ if err != nil {
+ return "", err
+ }
+ return string(config.Spec.Data), nil
+ }
+ }
+
+ return "", errors.Errorf("config target %s not found", target)
+}
+
+func (ctx PayloadContext) envGetter(variable string) (string, error) {
+ container := ctx.t.Spec.GetContainer()
+ if container == nil {
+ return "", errors.New("task is not a container")
+ }
+
+ for _, env := range container.Env {
+ parts := strings.SplitN(env, "=", 2)
+
+ if len(parts) > 1 && parts[0] == variable {
+ return parts[1], nil
+ }
+ }
+ return "", nil
+}
+
+// NewPayloadContextFromTask returns a new template context from the data
+// available in the task. This context also provides access to the configs
+// and secrets that the task has access to. The provided context can then
+// be used to populate runtime values in a templated config or secret.
+func NewPayloadContextFromTask(t *api.Task, dependencies exec.DependencyGetter) (ctx PayloadContext) {
+ return PayloadContext{
+ Context: NewContextFromTask(t),
+ t: t,
+ restrictedSecrets: secrets.Restrict(dependencies.Secrets(), t),
+ restrictedConfigs: configs.Restrict(dependencies.Configs(), t),
+ }
+}
+
+// Expand treats the string s as a template and populates it with values from
+// the context.
+func (ctx *PayloadContext) Expand(s string) (string, error) {
+ funcMap := template.FuncMap{
+ "secret": ctx.secretGetter,
+ "config": ctx.configGetter,
+ "env": ctx.envGetter,
+ }
+
+ tmpl, err := newTemplate(s, funcMap)
+ if err != nil {
+ return s, err
+ }
+
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, ctx); err != nil {
+ return s, err
+ }
+
+ return buf.String(), nil
+}
diff --git a/vendor/github.com/docker/swarmkit/template/expand.go b/vendor/github.com/docker/swarmkit/template/expand.go
new file mode 100644
index 0000000..e45c362
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/template/expand.go
@@ -0,0 +1,161 @@
+package template
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/api"
+ "github.com/pkg/errors"
+)
+
+// ExpandContainerSpec expands templated fields in the runtime using the task
+// state. Templating is all evaluated on the agent-side, before execution.
+//
+// Note that these are projected only on runtime values, since active task
+// values are typically manipulated in the manager.
+func ExpandContainerSpec(t *api.Task) (*api.ContainerSpec, error) {
+ container := t.Spec.GetContainer()
+ if container == nil {
+ return nil, errors.Errorf("task missing ContainerSpec to expand")
+ }
+
+ container = container.Copy()
+ ctx := NewContextFromTask(t)
+
+ var err error
+ container.Env, err = expandEnv(ctx, container.Env)
+ if err != nil {
+ return container, errors.Wrap(err, "expanding env failed")
+ }
+
+ // For now, we only allow templating of string-based mount fields
+ container.Mounts, err = expandMounts(ctx, container.Mounts)
+ if err != nil {
+ return container, errors.Wrap(err, "expanding mounts failed")
+ }
+
+ container.Hostname, err = ctx.Expand(container.Hostname)
+ return container, errors.Wrap(err, "expanding hostname failed")
+}
+
+func expandMounts(ctx Context, mounts []api.Mount) ([]api.Mount, error) {
+ if len(mounts) == 0 {
+ return mounts, nil
+ }
+
+ expanded := make([]api.Mount, len(mounts))
+ for i, mount := range mounts {
+ var err error
+ mount.Source, err = ctx.Expand(mount.Source)
+ if err != nil {
+ return mounts, errors.Wrapf(err, "expanding mount source %q", mount.Source)
+ }
+
+ mount.Target, err = ctx.Expand(mount.Target)
+ if err != nil {
+ return mounts, errors.Wrapf(err, "expanding mount target %q", mount.Target)
+ }
+
+ if mount.VolumeOptions != nil {
+ mount.VolumeOptions.Labels, err = expandMap(ctx, mount.VolumeOptions.Labels)
+ if err != nil {
+ return mounts, errors.Wrap(err, "expanding volume labels")
+ }
+
+ if mount.VolumeOptions.DriverConfig != nil {
+ mount.VolumeOptions.DriverConfig.Options, err = expandMap(ctx, mount.VolumeOptions.DriverConfig.Options)
+ if err != nil {
+ return mounts, errors.Wrap(err, "expanding volume driver config")
+ }
+ }
+ }
+
+ expanded[i] = mount
+ }
+
+ return expanded, nil
+}
+
+func expandMap(ctx Context, m map[string]string) (map[string]string, error) {
+ var (
+ n = make(map[string]string, len(m))
+ err error
+ )
+
+ for k, v := range m {
+ v, err = ctx.Expand(v)
+ if err != nil {
+ return m, errors.Wrapf(err, "expanding map entry %q=%q", k, v)
+ }
+
+ n[k] = v
+ }
+
+ return n, nil
+}
+
+func expandEnv(ctx Context, values []string) ([]string, error) {
+ var result []string
+ for _, value := range values {
+ var (
+ parts = strings.SplitN(value, "=", 2)
+ entry = parts[0]
+ )
+
+ if len(parts) > 1 {
+ expanded, err := ctx.Expand(parts[1])
+ if err != nil {
+ return values, errors.Wrapf(err, "expanding env %q", value)
+ }
+
+ entry = fmt.Sprintf("%s=%s", entry, expanded)
+ }
+
+ result = append(result, entry)
+ }
+
+ return result, nil
+}
+
+func expandPayload(ctx PayloadContext, payload []byte) ([]byte, error) {
+ result, err := ctx.Expand(string(payload))
+ if err != nil {
+ return payload, err
+ }
+ return []byte(result), nil
+}
+
+// ExpandSecretSpec expands the template inside the secret payload, if any.
+// Templating is evaluated on the agent-side.
+func ExpandSecretSpec(s *api.Secret, t *api.Task, dependencies exec.DependencyGetter) (*api.SecretSpec, error) {
+ if s.Spec.Templating == nil {
+ return &s.Spec, nil
+ }
+ if s.Spec.Templating.Name == "golang" {
+ ctx := NewPayloadContextFromTask(t, dependencies)
+ secretSpec := s.Spec.Copy()
+
+ var err error
+ secretSpec.Data, err = expandPayload(ctx, secretSpec.Data)
+ return secretSpec, err
+ }
+ return &s.Spec, errors.New("unrecognized template type")
+}
+
+// ExpandConfigSpec expands the template inside the config payload, if any.
+// Templating is evaluated on the agent-side.
+func ExpandConfigSpec(c *api.Config, t *api.Task, dependencies exec.DependencyGetter) (*api.ConfigSpec, error) {
+ if c.Spec.Templating == nil {
+ return &c.Spec, nil
+ }
+ if c.Spec.Templating.Name == "golang" {
+ ctx := NewPayloadContextFromTask(t, dependencies)
+ configSpec := c.Spec.Copy()
+
+ var err error
+ configSpec.Data, err = expandPayload(ctx, configSpec.Data)
+ return configSpec, err
+ }
+ return &c.Spec, errors.New("unrecognized template type")
+}
diff --git a/vendor/github.com/docker/swarmkit/template/getter.go b/vendor/github.com/docker/swarmkit/template/getter.go
new file mode 100644
index 0000000..f06c438
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/template/getter.go
@@ -0,0 +1,98 @@
+package template
+
+import (
+ "github.com/docker/swarmkit/agent/exec"
+ "github.com/docker/swarmkit/api"
+ "github.com/pkg/errors"
+)
+
+type templatedSecretGetter struct {
+ dependencies exec.DependencyGetter
+ t *api.Task
+}
+
+// NewTemplatedSecretGetter returns a SecretGetter that evaluates templates.
+func NewTemplatedSecretGetter(dependencies exec.DependencyGetter, t *api.Task) exec.SecretGetter {
+ return templatedSecretGetter{dependencies: dependencies, t: t}
+}
+
+func (t templatedSecretGetter) Get(secretID string) (*api.Secret, error) {
+ if t.dependencies == nil {
+ return nil, errors.New("no secret provider available")
+ }
+
+ secrets := t.dependencies.Secrets()
+ if secrets == nil {
+ return nil, errors.New("no secret provider available")
+ }
+
+ secret, err := secrets.Get(secretID)
+ if err != nil {
+ return secret, err
+ }
+
+ newSpec, err := ExpandSecretSpec(secret, t.t, t.dependencies)
+ if err != nil {
+ return secret, errors.Wrapf(err, "failed to expand templated secret %s", secretID)
+ }
+
+ secretCopy := *secret
+ secretCopy.Spec = *newSpec
+ return &secretCopy, nil
+}
+
+type templatedConfigGetter struct {
+ dependencies exec.DependencyGetter
+ t *api.Task
+}
+
+// NewTemplatedConfigGetter returns a ConfigGetter that evaluates templates.
+func NewTemplatedConfigGetter(dependencies exec.DependencyGetter, t *api.Task) exec.ConfigGetter {
+ return templatedConfigGetter{dependencies: dependencies, t: t}
+}
+
+func (t templatedConfigGetter) Get(configID string) (*api.Config, error) {
+ if t.dependencies == nil {
+ return nil, errors.New("no config provider available")
+ }
+
+ configs := t.dependencies.Configs()
+ if configs == nil {
+ return nil, errors.New("no config provider available")
+ }
+
+ config, err := configs.Get(configID)
+ if err != nil {
+ return config, err
+ }
+
+ newSpec, err := ExpandConfigSpec(config, t.t, t.dependencies)
+ if err != nil {
+ return config, errors.Wrapf(err, "failed to expand templated config %s", configID)
+ }
+
+ configCopy := *config
+ configCopy.Spec = *newSpec
+ return &configCopy, nil
+}
+
+type templatedDependencyGetter struct {
+ secrets exec.SecretGetter
+ configs exec.ConfigGetter
+}
+
+// NewTemplatedDependencyGetter returns a DependencyGetter that evaluates templates.
+func NewTemplatedDependencyGetter(dependencies exec.DependencyGetter, t *api.Task) exec.DependencyGetter {
+ return templatedDependencyGetter{
+ secrets: NewTemplatedSecretGetter(dependencies, t),
+ configs: NewTemplatedConfigGetter(dependencies, t),
+ }
+}
+
+func (t templatedDependencyGetter) Secrets() exec.SecretGetter {
+ return t.secrets
+}
+
+func (t templatedDependencyGetter) Configs() exec.ConfigGetter {
+ return t.configs
+}
diff --git a/vendor/github.com/docker/swarmkit/template/template.go b/vendor/github.com/docker/swarmkit/template/template.go
new file mode 100644
index 0000000..fc375b8
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/template/template.go
@@ -0,0 +1,22 @@
+package template
+
+import (
+ "strings"
+ "text/template"
+)
+
+// funcMap defines functions for our template system.
+var funcMap = template.FuncMap{
+ "join": func(s ...string) string {
+ // first arg is sep, remaining args are strings to join
+ return strings.Join(s[1:], s[0])
+ },
+}
+
+func newTemplate(s string, extraFuncs template.FuncMap) (*template.Template, error) {
+ tmpl := template.New("expansion").Option("missingkey=error").Funcs(funcMap)
+ if len(extraFuncs) != 0 {
+ tmpl = tmpl.Funcs(extraFuncs)
+ }
+ return tmpl.Parse(s)
+}
diff --git a/vendor/github.com/docker/swarmkit/vendor.conf b/vendor/github.com/docker/swarmkit/vendor.conf
new file mode 100644
index 0000000..4f5d293
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/vendor.conf
@@ -0,0 +1,65 @@
+# grpc and protobuf
+google.golang.org/grpc v1.3.0
+github.com/gogo/protobuf v0.4
+github.com/golang/protobuf 7a211bcf3bce0e3f1d74f9894916e6f116ae83b4
+github.com/matttproud/golang_protobuf_extensions v1.0.0
+google.golang.org/genproto d80a6e20e776b0b17a324d0ba1ab50a39c8e8944
+
+# metrics
+github.com/grpc-ecosystem/go-grpc-prometheus 6b7015e65d366bf3f19b2b2a000a831940f0f7e0
+github.com/docker/go-metrics d466d4f6fd960e01820085bd7e1a24426ee7ef18
+
+# etcd/raft
+github.com/coreos/etcd ea5389a79f40206170582c1ea076191b8622cb8e https://github.com/aaronlehmann/etcd # for https://github.com/coreos/etcd/pull/7830
+github.com/coreos/go-systemd v12
+github.com/coreos/pkg v3
+github.com/prometheus/client_golang 52437c81da6b127a9925d17eb3a382a2e5fd395e
+github.com/prometheus/client_model fa8ad6fec33561be4280a8f0514318c79d7f6cb6
+github.com/prometheus/common ebdfc6da46522d58825777cf1f90490a5b1ef1d8
+github.com/prometheus/procfs abf152e5f3e97f2fafac028d2cc06c1feb87ffa5
+
+github.com/docker/distribution b38e5838b7b2f2ad48e06ec4b500011976080621
+github.com/docker/docker 77c9728847358a3ed3581d828fb0753017e1afd3
+github.com/docker/go-connections 34b5052da6b11e27f5f2e357b38b571ddddd3928
+github.com/docker/go-events 37d35add5005832485c0225ec870121b78fcff1c
+github.com/docker/go-units 954fed01cc617c55d838fa2230073f2cb17386c8
+github.com/docker/libkv 9fd56606e928ff1f309808f5d5a0b7a2ef73f9a8
+github.com/docker/libnetwork 37e20af882e13dd01ade3658b7aabdae3412118b
+github.com/docker/libtrust 9cbd2a1374f46905c68a4eb3694a130610adc62a
+github.com/opencontainers/runc b6b70e53451794e8333e9b602cc096b47a20bd0f
+github.com/opencontainers/go-digest a6d0ee40d4207ea02364bd3b9e8e77b9159ba1eb
+github.com/opencontainers/image-spec f03dbe35d449c54915d235f1a3cf8f585a24babe
+
+# containerd executor
+github.com/containerd/containerd 7fc91b05917e93d474fab9465547d44eacd10ce3
+github.com/containerd/continuity f4ad4294c92f596c9241947c416d1297f9faf3ea
+github.com/containerd/fifo 69b99525e472735860a5269b75af1970142b3062
+github.com/opencontainers/runtime-spec v1.0.0-rc5
+github.com/nightlyone/lockfile 1d49c987357a327b5b03aa84cbddd582c328615d
+golang.org/x/sync 450f422ab23cf9881c94e2db30cac0eb1b7cf80c
+
+github.com/davecgh/go-spew 5215b55f46b2b919f50a1df0eaa5886afe4e3b3d
+github.com/Microsoft/go-winio f778f05015353be65d242f3fedc18695756153bb
+github.com/Sirupsen/logrus v0.11.0
+github.com/beorn7/perks 4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9
+github.com/boltdb/bolt e72f08ddb5a52992c0a44c7dda9316c7333938b2
+github.com/cloudflare/cfssl 7fb22c8cba7ecaf98e4082d22d65800cf45e042a
+github.com/dustin/go-humanize 8929fe90cee4b2cb9deb468b51fb34eba64d1bf0
+github.com/google/certificate-transparency 0f6e3d1d1ba4d03fdaab7cd716f36255c2e48341
+github.com/hashicorp/go-immutable-radix 8e8ed81f8f0bf1bdd829593fdd5c29922c1ea990
+github.com/hashicorp/go-memdb cb9a474f84cc5e41b273b20c6927680b2a8776ad
+github.com/hashicorp/golang-lru a0d98a5f288019575c6d1f4bb1573fef2d1fcdc4
+github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75
+github.com/phayes/permbits f7e3ac5e859d0b919c5068d581cc4c5d4f4f9bc5
+github.com/pivotal-golang/clock 3fd3c1944c59d9742e1cd333672181cd1a6f9fa0
+github.com/pkg/errors 01fa4104b9c248c8945d14d9f128454d5b28d595
+github.com/pmezard/go-difflib 792786c7400a136282c1664665ae0a8db921c6c2
+github.com/rcrowley/go-metrics 51425a2415d21afadfd55cd93432c0bc69e9598d
+github.com/spf13/cobra 8e91712f174ced10270cf66615e0a9127e7c4de5
+github.com/spf13/pflag 7f60f83a2c81bc3c3c0d5297f61ddfa68da9d3b7
+github.com/stretchr/testify v1.1.4
+golang.org/x/crypto 3fbbcd23f1cb824e69491a5930cfeff09b12f4d2
+golang.org/x/net 7dcfb8076726a3fdd9353b6b8a1f1b6be6811bd6
+golang.org/x/sys 5eaf0df67e70d6997a9fe0ed24383fa1b01638d3
+golang.org/x/text f72d8390a633d5dfb0cc84043294db9f6c935756
+golang.org/x/time a4bde12657593d5e90d0533a3e4fd95e635124cb
diff --git a/vendor/github.com/docker/swarmkit/watch/watch.go b/vendor/github.com/docker/swarmkit/watch/watch.go
new file mode 100644
index 0000000..a468237
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/watch/watch.go
@@ -0,0 +1,107 @@
+package watch
+
+import (
+ "sync"
+
+ "github.com/docker/go-events"
+)
+
+// dropErrClosed is a sink that suppresses ErrSinkClosed from Write, to avoid
+// debug log messages that may be confusing. It is possible that the queue
+// will try to write an event to its destination channel while the queue is
+// being removed from the broadcaster. Since the channel is closed before the
+// queue, there is a narrow window when this is possible. In some event-based
+// dropping events when a sink is removed from a broadcaster is a problem, but
+// for the usage in this watch package that's the expected behavior.
+type dropErrClosed struct {
+ sink events.Sink
+}
+
+func (s dropErrClosed) Write(event events.Event) error {
+ err := s.sink.Write(event)
+ if err == events.ErrSinkClosed {
+ return nil
+ }
+ return err
+}
+
+func (s dropErrClosed) Close() error {
+ return s.sink.Close()
+}
+
+// Queue is the structure used to publish events and watch for them.
+type Queue struct {
+ mu sync.Mutex
+ broadcast *events.Broadcaster
+ cancelFuncs map[*events.Channel]func()
+}
+
+// NewQueue creates a new publish/subscribe queue which supports watchers.
+// The channels that it will create for subscriptions will have the buffer
+// size specified by buffer.
+func NewQueue() *Queue {
+ return &Queue{
+ broadcast: events.NewBroadcaster(),
+ cancelFuncs: make(map[*events.Channel]func()),
+ }
+}
+
+// Watch returns a channel which will receive all items published to the
+// queue from this point, until cancel is called.
+func (q *Queue) Watch() (eventq chan events.Event, cancel func()) {
+ return q.CallbackWatch(nil)
+}
+
+// CallbackWatch returns a channel which will receive all events published to
+// the queue from this point that pass the check in the provided callback
+// function. The returned cancel function will stop the flow of events and
+// close the channel.
+func (q *Queue) CallbackWatch(matcher events.Matcher) (eventq chan events.Event, cancel func()) {
+ ch := events.NewChannel(0)
+ sink := events.Sink(events.NewQueue(dropErrClosed{sink: ch}))
+
+ if matcher != nil {
+ sink = events.NewFilter(sink, matcher)
+ }
+
+ q.broadcast.Add(sink)
+
+ cancelFunc := func() {
+ q.broadcast.Remove(sink)
+ ch.Close()
+ sink.Close()
+ }
+
+ q.mu.Lock()
+ q.cancelFuncs[ch] = cancelFunc
+ q.mu.Unlock()
+ return ch.C, func() {
+ q.mu.Lock()
+ cancelFunc := q.cancelFuncs[ch]
+ delete(q.cancelFuncs, ch)
+ q.mu.Unlock()
+
+ if cancelFunc != nil {
+ cancelFunc()
+ }
+ }
+}
+
+// Publish adds an item to the queue.
+func (q *Queue) Publish(item events.Event) {
+ q.broadcast.Write(item)
+}
+
+// Close closes the queue and frees the associated resources.
+func (q *Queue) Close() error {
+ // Make sure all watchers have been closed to avoid a deadlock when
+ // closing the broadcaster.
+ q.mu.Lock()
+ for _, cancelFunc := range q.cancelFuncs {
+ cancelFunc()
+ }
+ q.cancelFuncs = make(map[*events.Channel]func())
+ q.mu.Unlock()
+
+ return q.broadcast.Close()
+}
diff --git a/vendor/github.com/docker/swarmkit/xnet/xnet_unix.go b/vendor/github.com/docker/swarmkit/xnet/xnet_unix.go
new file mode 100644
index 0000000..7dc7732
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/xnet/xnet_unix.go
@@ -0,0 +1,20 @@
+// +build !windows
+
+package xnet
+
+import (
+ "net"
+ "time"
+)
+
+// ListenLocal opens a local socket for control communication
+func ListenLocal(socket string) (net.Listener, error) {
+ // on unix it's just a unix socket
+ return net.Listen("unix", socket)
+}
+
+// DialTimeoutLocal is a DialTimeout function for local sockets
+func DialTimeoutLocal(socket string, timeout time.Duration) (net.Conn, error) {
+ // on unix, we dial a unix socket
+ return net.DialTimeout("unix", socket, timeout)
+}
diff --git a/vendor/github.com/docker/swarmkit/xnet/xnet_windows.go b/vendor/github.com/docker/swarmkit/xnet/xnet_windows.go
new file mode 100644
index 0000000..38385a7
--- /dev/null
+++ b/vendor/github.com/docker/swarmkit/xnet/xnet_windows.go
@@ -0,0 +1,31 @@
+// +build windows
+
+package xnet
+
+import (
+ "net"
+ "time"
+
+ "github.com/Microsoft/go-winio"
+)
+
+// ListenLocal opens a local socket for control communication
+func ListenLocal(socket string) (net.Listener, error) {
+ // set up ACL for the named pipe
+ // allow Administrators and SYSTEM
+ sddl := "D:P(A;;GA;;;BA)(A;;GA;;;SY)"
+ c := winio.PipeConfig{
+ SecurityDescriptor: sddl,
+ MessageMode: true, // Use message mode so that CloseWrite() is supported
+ InputBufferSize: 65536, // Use 64KB buffers to improve performance
+ OutputBufferSize: 65536,
+ }
+ // on windows, our socket is actually a named pipe
+ return winio.ListenPipe(socket, &c)
+}
+
+// DialTimeoutLocal is a DialTimeout function for local sockets
+func DialTimeoutLocal(socket string, timeout time.Duration) (net.Conn, error) {
+ // On windows, we dial a named pipe
+ return winio.DialPipe(socket, &timeout)
+}
diff --git a/vendor/github.com/fluent/fluent-logger-golang/LICENSE b/vendor/github.com/fluent/fluent-logger-golang/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/vendor/github.com/fluent/fluent-logger-golang/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/fluent/fluent-logger-golang/README.md b/vendor/github.com/fluent/fluent-logger-golang/README.md
new file mode 100644
index 0000000..a6b9902
--- /dev/null
+++ b/vendor/github.com/fluent/fluent-logger-golang/README.md
@@ -0,0 +1,65 @@
+fluent-logger-golang
+====
+
+[![Build Status](https://travis-ci.org/fluent/fluent-logger-golang.png?branch=master)](https://travis-ci.org/fluent/fluent-logger-golang)
+
+## A structured event logger for Fluentd (Golang)
+
+## How to install
+
+```
+go get github.com/fluent/fluent-logger-golang/fluent
+```
+
+## Usage
+
+Install the package with `go get` and use `import` to include it in your project.
+
+```
+import "github.com/fluent/fluent-logger-golang/fluent"
+```
+
+GoDoc: http://godoc.org/github.com/fluent/fluent-logger-golang/fluent
+
+##Example
+
+```go
+package main
+
+import (
+ "github.com/fluent/fluent-logger-golang/fluent"
+ "fmt"
+ "time"
+)
+
+func main() {
+ logger, err := fluent.New(fluent.Config{})
+ if err != nil {
+ fmt.Println(err)
+ }
+ defer logger.Close()
+ tag := "myapp.access"
+ var data = map[string]string{
+ "foo": "bar",
+ "hoge": "hoge",
+ }
+ error := logger.Post(tag, data)
+ // error := logger.Post(tag, time.Time.Now(), data)
+ if error != nil {
+ panic(error)
+ }
+}
+```
+
+`data` must be a value like `map[string]literal`, `map[string]interface{}` or `struct`. Logger refers tags `msg` or `codec` of each fields of structs.
+
+## Setting config values
+
+```go
+f := fluent.New(fluent.Config{FluentPort: 80, FluentHost: "example.com"})
+```
+
+## Tests
+```
+go test
+```
diff --git a/vendor/github.com/fluent/fluent-logger-golang/fluent/fluent.go b/vendor/github.com/fluent/fluent-logger-golang/fluent/fluent.go
new file mode 100644
index 0000000..655f623
--- /dev/null
+++ b/vendor/github.com/fluent/fluent-logger-golang/fluent/fluent.go
@@ -0,0 +1,309 @@
+package fluent
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "net"
+ "reflect"
+ "strconv"
+ "sync"
+ "time"
+)
+
+const (
+ defaultHost = "127.0.0.1"
+ defaultNetwork = "tcp"
+ defaultSocketPath = ""
+ defaultPort = 24224
+ defaultTimeout = 3 * time.Second
+ defaultBufferLimit = 8 * 1024 * 1024
+ defaultRetryWait = 500
+ defaultMaxRetry = 13
+ defaultReconnectWaitIncreRate = 1.5
+)
+
+type Config struct {
+ FluentPort int `json:"fluent_port"`
+ FluentHost string `json:"fluent_host"`
+ FluentNetwork string `json:"fluent_network"`
+ FluentSocketPath string `json:"fluent_socket_path"`
+ Timeout time.Duration `json:"timeout"`
+ BufferLimit int `json:"buffer_limit"`
+ RetryWait int `json:"retry_wait"`
+ MaxRetry int `json:"max_retry"`
+ TagPrefix string `json:"tag_prefix"`
+ AsyncConnect bool `json:"async_connect"`
+ MarshalAsJSON bool `json:"marshal_as_json"`
+}
+
+type Fluent struct {
+ Config
+
+ mubuff sync.Mutex
+ pending []byte
+
+ muconn sync.Mutex
+ conn io.WriteCloser
+ reconnecting bool
+}
+
+// New creates a new Logger.
+func New(config Config) (f *Fluent, err error) {
+ if config.FluentNetwork == "" {
+ config.FluentNetwork = defaultNetwork
+ }
+ if config.FluentHost == "" {
+ config.FluentHost = defaultHost
+ }
+ if config.FluentPort == 0 {
+ config.FluentPort = defaultPort
+ }
+ if config.FluentSocketPath == "" {
+ config.FluentSocketPath = defaultSocketPath
+ }
+ if config.Timeout == 0 {
+ config.Timeout = defaultTimeout
+ }
+ if config.BufferLimit == 0 {
+ config.BufferLimit = defaultBufferLimit
+ }
+ if config.RetryWait == 0 {
+ config.RetryWait = defaultRetryWait
+ }
+ if config.MaxRetry == 0 {
+ config.MaxRetry = defaultMaxRetry
+ }
+ if config.AsyncConnect {
+ f = &Fluent{Config: config, reconnecting: true}
+ go f.reconnect()
+ } else {
+ f = &Fluent{Config: config, reconnecting: false}
+ err = f.connect()
+ }
+ return
+}
+
+// Post writes the output for a logging event.
+//
+// Examples:
+//
+// // send string
+// f.Post("tag_name", "data")
+//
+// // send map[string]
+// mapStringData := map[string]string{
+// "foo": "bar",
+// }
+// f.Post("tag_name", mapStringData)
+//
+// // send message with specified time
+// mapStringData := map[string]string{
+// "foo": "bar",
+// }
+// tm := time.Now()
+// f.PostWithTime("tag_name", tm, mapStringData)
+//
+// // send struct
+// structData := struct {
+// Name string `msg:"name"`
+// } {
+// "john smith",
+// }
+// f.Post("tag_name", structData)
+//
+func (f *Fluent) Post(tag string, message interface{}) error {
+ timeNow := time.Now()
+ return f.PostWithTime(tag, timeNow, message)
+}
+
+func (f *Fluent) PostWithTime(tag string, tm time.Time, message interface{}) error {
+ if len(f.TagPrefix) > 0 {
+ tag = f.TagPrefix + "." + tag
+ }
+
+ msg := reflect.ValueOf(message)
+ msgtype := msg.Type()
+
+ if msgtype.Kind() == reflect.Struct {
+ // message should be tagged by "codec" or "msg"
+ kv := make(map[string]interface{})
+ fields := msgtype.NumField()
+ for i := 0; i < fields; i++ {
+ field := msgtype.Field(i)
+ name := field.Name
+ if n1 := field.Tag.Get("msg"); n1 != "" {
+ name = n1
+ } else if n2 := field.Tag.Get("codec"); n2 != "" {
+ name = n2
+ }
+ kv[name] = msg.FieldByIndex(field.Index).Interface()
+ }
+ return f.EncodeAndPostData(tag, tm, kv)
+ }
+
+ if msgtype.Kind() != reflect.Map {
+ return errors.New("fluent#PostWithTime: message must be a map")
+ } else if msgtype.Key().Kind() != reflect.String {
+ return errors.New("fluent#PostWithTime: map keys must be strings")
+ }
+
+ kv := make(map[string]interface{})
+ for _, k := range msg.MapKeys() {
+ kv[k.String()] = msg.MapIndex(k).Interface()
+ }
+
+ return f.EncodeAndPostData(tag, tm, kv)
+}
+
+func (f *Fluent) EncodeAndPostData(tag string, tm time.Time, message interface{}) error {
+ var data []byte
+ var err error
+ if data, err = f.EncodeData(tag, tm, message); err != nil {
+ return fmt.Errorf("fluent#EncodeAndPostData: can't convert '%#v' to msgpack:%v", message, err)
+ }
+ return f.postRawData(data)
+}
+
+// Deprecated: Use EncodeAndPostData instead
+func (f *Fluent) PostRawData(data []byte) {
+ f.postRawData(data)
+}
+
+func (f *Fluent) postRawData(data []byte) error {
+ if err := f.appendBuffer(data); err != nil {
+ return err
+ }
+ if err := f.send(); err != nil {
+ f.close()
+ return err
+ }
+ return nil
+}
+
+// For sending forward protocol adopted JSON
+type MessageChunk struct {
+ message Message
+}
+
+// Golang default marshaler does not support
+// ["value", "value2", {"key":"value"}] style marshaling.
+// So, it should write JSON marshaler by hand.
+func (chunk *MessageChunk) MarshalJSON() ([]byte, error) {
+ data, err := json.Marshal(chunk.message.Record)
+ return []byte(fmt.Sprintf("[\"%s\",%d,%s,null]", chunk.message.Tag,
+ chunk.message.Time, data)), err
+}
+
+func (f *Fluent) EncodeData(tag string, tm time.Time, message interface{}) (data []byte, err error) {
+ timeUnix := tm.Unix()
+ if f.Config.MarshalAsJSON {
+ msg := Message{Tag: tag, Time: timeUnix, Record: message}
+ chunk := &MessageChunk{message: msg}
+ data, err = json.Marshal(chunk)
+ } else {
+ msg := &Message{Tag: tag, Time: timeUnix, Record: message}
+ data, err = msg.MarshalMsg(nil)
+ }
+ return
+}
+
+// Close closes the connection.
+func (f *Fluent) Close() (err error) {
+ if len(f.pending) > 0 {
+ err = f.send()
+ }
+ f.close()
+ return
+}
+
+// appendBuffer appends data to buffer with lock.
+func (f *Fluent) appendBuffer(data []byte) error {
+ f.mubuff.Lock()
+ defer f.mubuff.Unlock()
+ if len(f.pending)+len(data) > f.Config.BufferLimit {
+ return errors.New(fmt.Sprintf("fluent#appendBuffer: Buffer full, limit %v", f.Config.BufferLimit))
+ }
+ f.pending = append(f.pending, data...)
+ return nil
+}
+
+// close closes the connection.
+func (f *Fluent) close() {
+ f.muconn.Lock()
+ if f.conn != nil {
+ f.conn.Close()
+ f.conn = nil
+ }
+ f.muconn.Unlock()
+}
+
+// connect establishes a new connection using the specified transport.
+func (f *Fluent) connect() (err error) {
+ f.muconn.Lock()
+ defer f.muconn.Unlock()
+
+ switch f.Config.FluentNetwork {
+ case "tcp":
+ f.conn, err = net.DialTimeout(f.Config.FluentNetwork, f.Config.FluentHost+":"+strconv.Itoa(f.Config.FluentPort), f.Config.Timeout)
+ case "unix":
+ f.conn, err = net.DialTimeout(f.Config.FluentNetwork, f.Config.FluentSocketPath, f.Config.Timeout)
+ default:
+ err = net.UnknownNetworkError(f.Config.FluentNetwork)
+ }
+
+ if err == nil {
+ f.reconnecting = false
+ }
+ return
+}
+
+func e(x, y float64) int {
+ return int(math.Pow(x, y))
+}
+
+func (f *Fluent) reconnect() {
+ for i := 0; ; i++ {
+ err := f.connect()
+ if err == nil {
+ f.send()
+ return
+ }
+ if i == f.Config.MaxRetry {
+ // TODO: What we can do when connection failed MaxRetry times?
+ panic("fluent#reconnect: failed to reconnect!")
+ }
+ waitTime := f.Config.RetryWait * e(defaultReconnectWaitIncreRate, float64(i-1))
+ time.Sleep(time.Duration(waitTime) * time.Millisecond)
+ }
+}
+
+func (f *Fluent) send() error {
+ f.muconn.Lock()
+ defer f.muconn.Unlock()
+
+ if f.conn == nil {
+ if f.reconnecting == false {
+ f.reconnecting = true
+ go f.reconnect()
+ }
+ return errors.New("fluent#send: can't send logs, client is reconnecting")
+ }
+
+ f.mubuff.Lock()
+ defer f.mubuff.Unlock()
+
+ var err error
+ if len(f.pending) > 0 {
+ _, err = f.conn.Write(f.pending)
+ if err != nil {
+ f.conn.Close()
+ f.conn = nil
+ } else {
+ f.pending = f.pending[:0]
+ }
+ }
+ return err
+}
diff --git a/vendor/github.com/fluent/fluent-logger-golang/fluent/proto.go b/vendor/github.com/fluent/fluent-logger-golang/fluent/proto.go
new file mode 100644
index 0000000..268d614
--- /dev/null
+++ b/vendor/github.com/fluent/fluent-logger-golang/fluent/proto.go
@@ -0,0 +1,24 @@
+//go:generate msgp
+
+package fluent
+
+//msgp:tuple Entry
+type Entry struct {
+ Time int64 `msg:"time"`
+ Record interface{} `msg:"record"`
+}
+
+//msgp:tuple Forward
+type Forward struct {
+ Tag string `msg:"tag"`
+ Entries []Entry `msg:"entries"`
+ Option interface{} `msg:"option"`
+}
+
+//msgp:tuple Message
+type Message struct {
+ Tag string `msg:"tag"`
+ Time int64 `msg:"time"`
+ Record interface{} `msg:"record"`
+ Option interface{} `msg:"option"`
+}
diff --git a/vendor/github.com/fluent/fluent-logger-golang/fluent/proto_gen.go b/vendor/github.com/fluent/fluent-logger-golang/fluent/proto_gen.go
new file mode 100644
index 0000000..afb9d6d
--- /dev/null
+++ b/vendor/github.com/fluent/fluent-logger-golang/fluent/proto_gen.go
@@ -0,0 +1,372 @@
+package fluent
+
+// NOTE: THIS FILE WAS PRODUCED BY THE
+// MSGP CODE GENERATION TOOL (github.com/tinylib/msgp)
+// DO NOT EDIT
+
+import (
+ "github.com/tinylib/msgp/msgp"
+)
+
+// DecodeMsg implements msgp.Decodable
+func (z *Entry) DecodeMsg(dc *msgp.Reader) (err error) {
+ var ssz uint32
+ ssz, err = dc.ReadArrayHeader()
+ if err != nil {
+ return
+ }
+ if ssz != 2 {
+ err = msgp.ArrayError{Wanted: 2, Got: ssz}
+ return
+ }
+ z.Time, err = dc.ReadInt64()
+ if err != nil {
+ return
+ }
+ z.Record, err = dc.ReadIntf()
+ if err != nil {
+ return
+ }
+ return
+}
+
+// EncodeMsg implements msgp.Encodable
+func (z Entry) EncodeMsg(en *msgp.Writer) (err error) {
+ err = en.WriteArrayHeader(2)
+ if err != nil {
+ return
+ }
+ err = en.WriteInt64(z.Time)
+ if err != nil {
+ return
+ }
+ err = en.WriteIntf(z.Record)
+ if err != nil {
+ return
+ }
+ return
+}
+
+// MarshalMsg implements msgp.Marshaler
+func (z Entry) MarshalMsg(b []byte) (o []byte, err error) {
+ o = msgp.Require(b, z.Msgsize())
+ o = msgp.AppendArrayHeader(o, 2)
+ o = msgp.AppendInt64(o, z.Time)
+ o, err = msgp.AppendIntf(o, z.Record)
+ if err != nil {
+ return
+ }
+ return
+}
+
+// UnmarshalMsg implements msgp.Unmarshaler
+func (z *Entry) UnmarshalMsg(bts []byte) (o []byte, err error) {
+ {
+ var ssz uint32
+ ssz, bts, err = msgp.ReadArrayHeaderBytes(bts)
+ if err != nil {
+ return
+ }
+ if ssz != 2 {
+ err = msgp.ArrayError{Wanted: 2, Got: ssz}
+ return
+ }
+ }
+ z.Time, bts, err = msgp.ReadInt64Bytes(bts)
+ if err != nil {
+ return
+ }
+ z.Record, bts, err = msgp.ReadIntfBytes(bts)
+ if err != nil {
+ return
+ }
+ o = bts
+ return
+}
+
+func (z Entry) Msgsize() (s int) {
+ s = msgp.ArrayHeaderSize + msgp.Int64Size + msgp.GuessSize(z.Record)
+ return
+}
+
+// DecodeMsg implements msgp.Decodable
+func (z *Forward) DecodeMsg(dc *msgp.Reader) (err error) {
+ var ssz uint32
+ ssz, err = dc.ReadArrayHeader()
+ if err != nil {
+ return
+ }
+ if ssz != 3 {
+ err = msgp.ArrayError{Wanted: 3, Got: ssz}
+ return
+ }
+ z.Tag, err = dc.ReadString()
+ if err != nil {
+ return
+ }
+ var xsz uint32
+ xsz, err = dc.ReadArrayHeader()
+ if err != nil {
+ return
+ }
+ if cap(z.Entries) >= int(xsz) {
+ z.Entries = z.Entries[:xsz]
+ } else {
+ z.Entries = make([]Entry, xsz)
+ }
+ for xvk := range z.Entries {
+ var ssz uint32
+ ssz, err = dc.ReadArrayHeader()
+ if err != nil {
+ return
+ }
+ if ssz != 2 {
+ err = msgp.ArrayError{Wanted: 2, Got: ssz}
+ return
+ }
+ z.Entries[xvk].Time, err = dc.ReadInt64()
+ if err != nil {
+ return
+ }
+ z.Entries[xvk].Record, err = dc.ReadIntf()
+ if err != nil {
+ return
+ }
+ }
+ z.Option, err = dc.ReadIntf()
+ if err != nil {
+ return
+ }
+ return
+}
+
+// EncodeMsg implements msgp.Encodable
+func (z *Forward) EncodeMsg(en *msgp.Writer) (err error) {
+ err = en.WriteArrayHeader(3)
+ if err != nil {
+ return
+ }
+ err = en.WriteString(z.Tag)
+ if err != nil {
+ return
+ }
+ err = en.WriteArrayHeader(uint32(len(z.Entries)))
+ if err != nil {
+ return
+ }
+ for xvk := range z.Entries {
+ err = en.WriteArrayHeader(2)
+ if err != nil {
+ return
+ }
+ err = en.WriteInt64(z.Entries[xvk].Time)
+ if err != nil {
+ return
+ }
+ err = en.WriteIntf(z.Entries[xvk].Record)
+ if err != nil {
+ return
+ }
+ }
+ err = en.WriteIntf(z.Option)
+ if err != nil {
+ return
+ }
+ return
+}
+
+// MarshalMsg implements msgp.Marshaler
+func (z *Forward) MarshalMsg(b []byte) (o []byte, err error) {
+ o = msgp.Require(b, z.Msgsize())
+ o = msgp.AppendArrayHeader(o, 3)
+ o = msgp.AppendString(o, z.Tag)
+ o = msgp.AppendArrayHeader(o, uint32(len(z.Entries)))
+ for xvk := range z.Entries {
+ o = msgp.AppendArrayHeader(o, 2)
+ o = msgp.AppendInt64(o, z.Entries[xvk].Time)
+ o, err = msgp.AppendIntf(o, z.Entries[xvk].Record)
+ if err != nil {
+ return
+ }
+ }
+ o, err = msgp.AppendIntf(o, z.Option)
+ if err != nil {
+ return
+ }
+ return
+}
+
+// UnmarshalMsg implements msgp.Unmarshaler
+func (z *Forward) UnmarshalMsg(bts []byte) (o []byte, err error) {
+ {
+ var ssz uint32
+ ssz, bts, err = msgp.ReadArrayHeaderBytes(bts)
+ if err != nil {
+ return
+ }
+ if ssz != 3 {
+ err = msgp.ArrayError{Wanted: 3, Got: ssz}
+ return
+ }
+ }
+ z.Tag, bts, err = msgp.ReadStringBytes(bts)
+ if err != nil {
+ return
+ }
+ var xsz uint32
+ xsz, bts, err = msgp.ReadArrayHeaderBytes(bts)
+ if err != nil {
+ return
+ }
+ if cap(z.Entries) >= int(xsz) {
+ z.Entries = z.Entries[:xsz]
+ } else {
+ z.Entries = make([]Entry, xsz)
+ }
+ for xvk := range z.Entries {
+ {
+ var ssz uint32
+ ssz, bts, err = msgp.ReadArrayHeaderBytes(bts)
+ if err != nil {
+ return
+ }
+ if ssz != 2 {
+ err = msgp.ArrayError{Wanted: 2, Got: ssz}
+ return
+ }
+ }
+ z.Entries[xvk].Time, bts, err = msgp.ReadInt64Bytes(bts)
+ if err != nil {
+ return
+ }
+ z.Entries[xvk].Record, bts, err = msgp.ReadIntfBytes(bts)
+ if err != nil {
+ return
+ }
+ }
+ z.Option, bts, err = msgp.ReadIntfBytes(bts)
+ if err != nil {
+ return
+ }
+ o = bts
+ return
+}
+
+func (z *Forward) Msgsize() (s int) {
+ s = msgp.ArrayHeaderSize + msgp.StringPrefixSize + len(z.Tag) + msgp.ArrayHeaderSize
+ for xvk := range z.Entries {
+ s += msgp.ArrayHeaderSize + msgp.Int64Size + msgp.GuessSize(z.Entries[xvk].Record)
+ }
+ s += msgp.GuessSize(z.Option)
+ return
+}
+
+// DecodeMsg implements msgp.Decodable
+func (z *Message) DecodeMsg(dc *msgp.Reader) (err error) {
+ var ssz uint32
+ ssz, err = dc.ReadArrayHeader()
+ if err != nil {
+ return
+ }
+ if ssz != 4 {
+ err = msgp.ArrayError{Wanted: 4, Got: ssz}
+ return
+ }
+ z.Tag, err = dc.ReadString()
+ if err != nil {
+ return
+ }
+ z.Time, err = dc.ReadInt64()
+ if err != nil {
+ return
+ }
+ z.Record, err = dc.ReadIntf()
+ if err != nil {
+ return
+ }
+ z.Option, err = dc.ReadIntf()
+ if err != nil {
+ return
+ }
+ return
+}
+
+// EncodeMsg implements msgp.Encodable
+func (z *Message) EncodeMsg(en *msgp.Writer) (err error) {
+ err = en.WriteArrayHeader(4)
+ if err != nil {
+ return
+ }
+ err = en.WriteString(z.Tag)
+ if err != nil {
+ return
+ }
+ err = en.WriteInt64(z.Time)
+ if err != nil {
+ return
+ }
+ err = en.WriteIntf(z.Record)
+ if err != nil {
+ return
+ }
+ err = en.WriteIntf(z.Option)
+ if err != nil {
+ return
+ }
+ return
+}
+
+// MarshalMsg implements msgp.Marshaler
+func (z *Message) MarshalMsg(b []byte) (o []byte, err error) {
+ o = msgp.Require(b, z.Msgsize())
+ o = msgp.AppendArrayHeader(o, 4)
+ o = msgp.AppendString(o, z.Tag)
+ o = msgp.AppendInt64(o, z.Time)
+ o, err = msgp.AppendIntf(o, z.Record)
+ if err != nil {
+ return
+ }
+ o, err = msgp.AppendIntf(o, z.Option)
+ if err != nil {
+ return
+ }
+ return
+}
+
+// UnmarshalMsg implements msgp.Unmarshaler
+func (z *Message) UnmarshalMsg(bts []byte) (o []byte, err error) {
+ {
+ var ssz uint32
+ ssz, bts, err = msgp.ReadArrayHeaderBytes(bts)
+ if err != nil {
+ return
+ }
+ if ssz != 4 {
+ err = msgp.ArrayError{Wanted: 4, Got: ssz}
+ return
+ }
+ }
+ z.Tag, bts, err = msgp.ReadStringBytes(bts)
+ if err != nil {
+ return
+ }
+ z.Time, bts, err = msgp.ReadInt64Bytes(bts)
+ if err != nil {
+ return
+ }
+ z.Record, bts, err = msgp.ReadIntfBytes(bts)
+ if err != nil {
+ return
+ }
+ z.Option, bts, err = msgp.ReadIntfBytes(bts)
+ if err != nil {
+ return
+ }
+ o = bts
+ return
+}
+
+func (z *Message) Msgsize() (s int) {
+ s = msgp.ArrayHeaderSize + msgp.StringPrefixSize + len(z.Tag) + msgp.Int64Size + msgp.GuessSize(z.Record) + msgp.GuessSize(z.Option)
+ return
+}
diff --git a/vendor/github.com/fluent/fluent-logger-golang/fluent/version.go b/vendor/github.com/fluent/fluent-logger-golang/fluent/version.go
new file mode 100644
index 0000000..8904726
--- /dev/null
+++ b/vendor/github.com/fluent/fluent-logger-golang/fluent/version.go
@@ -0,0 +1,3 @@
+package fluent
+
+const Version = "1.2.1"
diff --git a/vendor/github.com/fsnotify/fsnotify/LICENSE b/vendor/github.com/fsnotify/fsnotify/LICENSE
new file mode 100644
index 0000000..f21e540
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/LICENSE
@@ -0,0 +1,28 @@
+Copyright (c) 2012 The Go Authors. All rights reserved.
+Copyright (c) 2012 fsnotify 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/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md
new file mode 100644
index 0000000..fee2a36
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/README.md
@@ -0,0 +1,46 @@
+# File system notifications for Go
+
+[![GoDoc](https://godoc.org/github.com/fsnotify/fsnotify?status.svg)](https://godoc.org/github.com/fsnotify/fsnotify) [![Go Report Card](https://goreportcard.com/badge/github.com/fsnotify/fsnotify)](https://goreportcard.com/report/github.com/fsnotify/fsnotify) [![Coverage](http://gocover.io/_badge/github.com/fsnotify/fsnotify)](http://gocover.io/github.com/fsnotify/fsnotify)
+
+Go 1.3+ required.
+
+Cross platform: Windows, Linux, BSD and OS X.
+
+|Adapter |OS |Status |
+|----------|----------|----------|
+|inotify |Linux 2.6.27 or later, Android\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)|
+|kqueue |BSD, OS X, iOS\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)|
+|ReadDirectoryChangesW|Windows|Supported [![Build status](https://ci.appveyor.com/api/projects/status/ivwjubaih4r0udeh/branch/master?svg=true)](https://ci.appveyor.com/project/NathanYoungman/fsnotify/branch/master)|
+|FSEvents |OS X |[Planned](https://github.com/fsnotify/fsnotify/issues/11)|
+|FEN |Solaris 11 |[In Progress](https://github.com/fsnotify/fsnotify/issues/12)|
+|fanotify |Linux 2.6.37+ | |
+|USN Journals |Windows |[Maybe](https://github.com/fsnotify/fsnotify/issues/53)|
+|Polling |*All* |[Maybe](https://github.com/fsnotify/fsnotify/issues/9)|
+
+\* Android and iOS are untested.
+
+Please see [the documentation](https://godoc.org/github.com/fsnotify/fsnotify) for usage. Consult the [Wiki](https://github.com/fsnotify/fsnotify/wiki) for the FAQ and further information.
+
+## API stability
+
+fsnotify is a fork of [howeyc/fsnotify](https://godoc.org/github.com/howeyc/fsnotify) with a new API as of v1.0. The API is based on [this design document](http://goo.gl/MrYxyA).
+
+All [releases](https://github.com/fsnotify/fsnotify/releases) are tagged based on [Semantic Versioning](http://semver.org/). Further API changes are [planned](https://github.com/fsnotify/fsnotify/milestones), and will be tagged with a new major revision number.
+
+Go 1.6 supports dependencies located in the `vendor/` folder. Unless you are creating a library, it is recommended that you copy fsnotify into `vendor/github.com/fsnotify/fsnotify` within your project.
+
+## Contributing
+
+Please refer to [CONTRIBUTING][] before opening an issue or pull request.
+
+## Example
+
+See [example_test.go](https://github.com/fsnotify/fsnotify/blob/master/example_test.go).
+
+[contributing]: https://github.com/fsnotify/fsnotify/blob/master/CONTRIBUTING.md
+
+## Related Projects
+
+* [notify](https://github.com/rjeczalik/notify)
+* [fsevents](https://github.com/fsnotify/fsevents)
+
diff --git a/vendor/github.com/fsnotify/fsnotify/fen.go b/vendor/github.com/fsnotify/fsnotify/fen.go
new file mode 100644
index 0000000..ced39cb
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/fen.go
@@ -0,0 +1,37 @@
+// 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.
+
+// +build solaris
+
+package fsnotify
+
+import (
+ "errors"
+)
+
+// Watcher watches a set of files, delivering events to a channel.
+type Watcher struct {
+ Events chan Event
+ Errors chan error
+}
+
+// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
+func NewWatcher() (*Watcher, error) {
+ return nil, errors.New("FEN based watcher not yet supported for fsnotify\n")
+}
+
+// Close removes all watches and closes the events channel.
+func (w *Watcher) Close() error {
+ return nil
+}
+
+// Add starts watching the named file or directory (non-recursively).
+func (w *Watcher) Add(name string) error {
+ return nil
+}
+
+// Remove stops watching the the named file or directory (non-recursively).
+func (w *Watcher) Remove(name string) error {
+ return nil
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go
new file mode 100644
index 0000000..d1d39a0
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go
@@ -0,0 +1,62 @@
+// 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 !plan9
+
+// Package fsnotify provides a platform-independent interface for file system notifications.
+package fsnotify
+
+import (
+ "bytes"
+ "fmt"
+)
+
+// Event represents a single file system notification.
+type Event struct {
+ Name string // Relative path to the file or directory.
+ Op Op // File operation that triggered the event.
+}
+
+// Op describes a set of file operations.
+type Op uint32
+
+// These are the generalized file operations that can trigger a notification.
+const (
+ Create Op = 1 << iota
+ Write
+ Remove
+ Rename
+ Chmod
+)
+
+// String returns a string representation of the event in the form
+// "file: REMOVE|WRITE|..."
+func (e Event) String() string {
+ // Use a buffer for efficient string concatenation
+ var buffer bytes.Buffer
+
+ if e.Op&Create == Create {
+ buffer.WriteString("|CREATE")
+ }
+ if e.Op&Remove == Remove {
+ buffer.WriteString("|REMOVE")
+ }
+ if e.Op&Write == Write {
+ buffer.WriteString("|WRITE")
+ }
+ if e.Op&Rename == Rename {
+ buffer.WriteString("|RENAME")
+ }
+ if e.Op&Chmod == Chmod {
+ buffer.WriteString("|CHMOD")
+ }
+
+ // If buffer remains empty, return no event names
+ if buffer.Len() == 0 {
+ return fmt.Sprintf("%q: ", e.Name)
+ }
+
+ // Return a list of event names, with leading pipe character stripped
+ return fmt.Sprintf("%q: %s", e.Name, buffer.String()[1:])
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify.go b/vendor/github.com/fsnotify/fsnotify/inotify.go
new file mode 100644
index 0000000..780b2a0
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/inotify.go
@@ -0,0 +1,324 @@
+// 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.
+
+// +build linux
+
+package fsnotify
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "syscall"
+ "unsafe"
+)
+
+// Watcher watches a set of files, delivering events to a channel.
+type Watcher struct {
+ Events chan Event
+ Errors chan error
+ mu sync.Mutex // Map access
+ cv *sync.Cond // sync removing on rm_watch with IN_IGNORE
+ fd int
+ poller *fdPoller
+ watches map[string]*watch // Map of inotify watches (key: path)
+ paths map[int]string // Map of watched paths (key: watch descriptor)
+ done chan struct{} // Channel for sending a "quit message" to the reader goroutine
+ doneResp chan struct{} // Channel to respond to Close
+}
+
+// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
+func NewWatcher() (*Watcher, error) {
+ // Create inotify fd
+ fd, errno := syscall.InotifyInit()
+ if fd == -1 {
+ return nil, errno
+ }
+ // Create epoll
+ poller, err := newFdPoller(fd)
+ if err != nil {
+ syscall.Close(fd)
+ return nil, err
+ }
+ w := &Watcher{
+ fd: fd,
+ poller: poller,
+ watches: make(map[string]*watch),
+ paths: make(map[int]string),
+ Events: make(chan Event),
+ Errors: make(chan error),
+ done: make(chan struct{}),
+ doneResp: make(chan struct{}),
+ }
+ w.cv = sync.NewCond(&w.mu)
+
+ go w.readEvents()
+ return w, nil
+}
+
+func (w *Watcher) isClosed() bool {
+ select {
+ case <-w.done:
+ return true
+ default:
+ return false
+ }
+}
+
+// Close removes all watches and closes the events channel.
+func (w *Watcher) Close() error {
+ if w.isClosed() {
+ return nil
+ }
+
+ // Send 'close' signal to goroutine, and set the Watcher to closed.
+ close(w.done)
+
+ // Wake up goroutine
+ w.poller.wake()
+
+ // Wait for goroutine to close
+ <-w.doneResp
+
+ return nil
+}
+
+// Add starts watching the named file or directory (non-recursively).
+func (w *Watcher) Add(name string) error {
+ name = filepath.Clean(name)
+ if w.isClosed() {
+ return errors.New("inotify instance already closed")
+ }
+
+ const agnosticEvents = syscall.IN_MOVED_TO | syscall.IN_MOVED_FROM |
+ syscall.IN_CREATE | syscall.IN_ATTRIB | syscall.IN_MODIFY |
+ syscall.IN_MOVE_SELF | syscall.IN_DELETE | syscall.IN_DELETE_SELF
+
+ var flags uint32 = agnosticEvents
+
+ w.mu.Lock()
+ watchEntry, found := w.watches[name]
+ w.mu.Unlock()
+ if found {
+ watchEntry.flags |= flags
+ flags |= syscall.IN_MASK_ADD
+ }
+ wd, errno := syscall.InotifyAddWatch(w.fd, name, flags)
+ if wd == -1 {
+ return errno
+ }
+
+ w.mu.Lock()
+ w.watches[name] = &watch{wd: uint32(wd), flags: flags}
+ w.paths[wd] = name
+ w.mu.Unlock()
+
+ return nil
+}
+
+// Remove stops watching the named file or directory (non-recursively).
+func (w *Watcher) Remove(name string) error {
+ name = filepath.Clean(name)
+
+ // Fetch the watch.
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ watch, ok := w.watches[name]
+
+ // Remove it from inotify.
+ if !ok {
+ return fmt.Errorf("can't remove non-existent inotify watch for: %s", name)
+ }
+ // inotify_rm_watch will return EINVAL if the file has been deleted;
+ // the inotify will already have been removed.
+ // watches and pathes are deleted in ignoreLinux() implicitly and asynchronously
+ // by calling inotify_rm_watch() below. e.g. readEvents() goroutine receives IN_IGNORE
+ // so that EINVAL means that the wd is being rm_watch()ed or its file removed
+ // by another thread and we have not received IN_IGNORE event.
+ success, errno := syscall.InotifyRmWatch(w.fd, watch.wd)
+ if success == -1 {
+ // TODO: Perhaps it's not helpful to return an error here in every case.
+ // the only two possible errors are:
+ // EBADF, which happens when w.fd is not a valid file descriptor of any kind.
+ // EINVAL, which is when fd is not an inotify descriptor or wd is not a valid watch descriptor.
+ // Watch descriptors are invalidated when they are removed explicitly or implicitly;
+ // explicitly by inotify_rm_watch, implicitly when the file they are watching is deleted.
+ return errno
+ }
+
+ // wait until ignoreLinux() deleting maps
+ exists := true
+ for exists {
+ w.cv.Wait()
+ _, exists = w.watches[name]
+ }
+
+ return nil
+}
+
+type watch struct {
+ wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall)
+ flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags)
+}
+
+// readEvents reads from the inotify file descriptor, converts the
+// received events into Event objects and sends them via the Events channel
+func (w *Watcher) readEvents() {
+ var (
+ buf [syscall.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events
+ n int // Number of bytes read with read()
+ errno error // Syscall errno
+ ok bool // For poller.wait
+ )
+
+ defer close(w.doneResp)
+ defer close(w.Errors)
+ defer close(w.Events)
+ defer syscall.Close(w.fd)
+ defer w.poller.close()
+
+ for {
+ // See if we have been closed.
+ if w.isClosed() {
+ return
+ }
+
+ ok, errno = w.poller.wait()
+ if errno != nil {
+ select {
+ case w.Errors <- errno:
+ case <-w.done:
+ return
+ }
+ continue
+ }
+
+ if !ok {
+ continue
+ }
+
+ n, errno = syscall.Read(w.fd, buf[:])
+ // If a signal interrupted execution, see if we've been asked to close, and try again.
+ // http://man7.org/linux/man-pages/man7/signal.7.html :
+ // "Before Linux 3.8, reads from an inotify(7) file descriptor were not restartable"
+ if errno == syscall.EINTR {
+ continue
+ }
+
+ // syscall.Read might have been woken up by Close. If so, we're done.
+ if w.isClosed() {
+ return
+ }
+
+ if n < syscall.SizeofInotifyEvent {
+ var err error
+ if n == 0 {
+ // If EOF is received. This should really never happen.
+ err = io.EOF
+ } else if n < 0 {
+ // If an error occurred while reading.
+ err = errno
+ } else {
+ // Read was too short.
+ err = errors.New("notify: short read in readEvents()")
+ }
+ select {
+ case w.Errors <- err:
+ case <-w.done:
+ return
+ }
+ continue
+ }
+
+ var offset uint32
+ // We don't know how many events we just read into the buffer
+ // While the offset points to at least one whole event...
+ for offset <= uint32(n-syscall.SizeofInotifyEvent) {
+ // Point "raw" to the event in the buffer
+ raw := (*syscall.InotifyEvent)(unsafe.Pointer(&buf[offset]))
+
+ mask := uint32(raw.Mask)
+ nameLen := uint32(raw.Len)
+ // 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
+ // the "paths" map.
+ w.mu.Lock()
+ name := w.paths[int(raw.Wd)]
+ w.mu.Unlock()
+ if nameLen > 0 {
+ // Point "bytes" at the first byte of the filename
+ bytes := (*[syscall.PathMax]byte)(unsafe.Pointer(&buf[offset+syscall.SizeofInotifyEvent]))
+ // The filename is padded with NULL bytes. TrimRight() gets rid of those.
+ name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000")
+ }
+
+ event := newEvent(name, mask)
+
+ // Send the events that are not ignored on the events channel
+ if !event.ignoreLinux(w, raw.Wd, mask) {
+ select {
+ case w.Events <- event:
+ case <-w.done:
+ return
+ }
+ }
+
+ // Move to the next event in the buffer
+ offset += syscall.SizeofInotifyEvent + nameLen
+ }
+ }
+}
+
+// Certain types of events can be "ignored" and not sent over the Events
+// channel. Such as events marked ignore by the kernel, or MODIFY events
+// against files that do not exist.
+func (e *Event) ignoreLinux(w *Watcher, wd int32, mask uint32) bool {
+ // Ignore anything the inotify API says to ignore
+ if mask&syscall.IN_IGNORED == syscall.IN_IGNORED {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ name := w.paths[int(wd)]
+ delete(w.paths, int(wd))
+ delete(w.watches, name)
+ w.cv.Broadcast()
+ return true
+ }
+
+ // If the event is not a DELETE or RENAME, the file must exist.
+ // Otherwise the event is ignored.
+ // *Note*: this was put in place because it was seen that a MODIFY
+ // event was sent after the DELETE. This ignores that MODIFY and
+ // assumes a DELETE will come or has come if the file doesn't exist.
+ if !(e.Op&Remove == Remove || e.Op&Rename == Rename) {
+ _, statErr := os.Lstat(e.Name)
+ return os.IsNotExist(statErr)
+ }
+ return false
+}
+
+// newEvent returns an platform-independent Event based on an inotify mask.
+func newEvent(name string, mask uint32) Event {
+ e := Event{Name: name}
+ if mask&syscall.IN_CREATE == syscall.IN_CREATE || mask&syscall.IN_MOVED_TO == syscall.IN_MOVED_TO {
+ e.Op |= Create
+ }
+ if mask&syscall.IN_DELETE_SELF == syscall.IN_DELETE_SELF || mask&syscall.IN_DELETE == syscall.IN_DELETE {
+ e.Op |= Remove
+ }
+ if mask&syscall.IN_MODIFY == syscall.IN_MODIFY {
+ e.Op |= Write
+ }
+ if mask&syscall.IN_MOVE_SELF == syscall.IN_MOVE_SELF || mask&syscall.IN_MOVED_FROM == syscall.IN_MOVED_FROM {
+ e.Op |= Rename
+ }
+ if mask&syscall.IN_ATTRIB == syscall.IN_ATTRIB {
+ e.Op |= Chmod
+ }
+ return e
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_poller.go b/vendor/github.com/fsnotify/fsnotify/inotify_poller.go
new file mode 100644
index 0000000..23a5ca1
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/inotify_poller.go
@@ -0,0 +1,186 @@
+// Copyright 2015 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
+
+package fsnotify
+
+import (
+ "errors"
+ "syscall"
+)
+
+type fdPoller struct {
+ fd int // File descriptor (as returned by the inotify_init() syscall)
+ epfd int // Epoll file descriptor
+ pipe [2]int // Pipe for waking up
+}
+
+func emptyPoller(fd int) *fdPoller {
+ poller := new(fdPoller)
+ poller.fd = fd
+ poller.epfd = -1
+ poller.pipe[0] = -1
+ poller.pipe[1] = -1
+ return poller
+}
+
+// Create a new inotify poller.
+// This creates an inotify handler, and an epoll handler.
+func newFdPoller(fd int) (*fdPoller, error) {
+ var errno error
+ poller := emptyPoller(fd)
+ defer func() {
+ if errno != nil {
+ poller.close()
+ }
+ }()
+ poller.fd = fd
+
+ // Create epoll fd
+ poller.epfd, errno = syscall.EpollCreate1(0)
+ if poller.epfd == -1 {
+ return nil, errno
+ }
+ // Create pipe; pipe[0] is the read end, pipe[1] the write end.
+ errno = syscall.Pipe2(poller.pipe[:], syscall.O_NONBLOCK)
+ if errno != nil {
+ return nil, errno
+ }
+
+ // Register inotify fd with epoll
+ event := syscall.EpollEvent{
+ Fd: int32(poller.fd),
+ Events: syscall.EPOLLIN,
+ }
+ errno = syscall.EpollCtl(poller.epfd, syscall.EPOLL_CTL_ADD, poller.fd, &event)
+ if errno != nil {
+ return nil, errno
+ }
+
+ // Register pipe fd with epoll
+ event = syscall.EpollEvent{
+ Fd: int32(poller.pipe[0]),
+ Events: syscall.EPOLLIN,
+ }
+ errno = syscall.EpollCtl(poller.epfd, syscall.EPOLL_CTL_ADD, poller.pipe[0], &event)
+ if errno != nil {
+ return nil, errno
+ }
+
+ return poller, nil
+}
+
+// Wait using epoll.
+// Returns true if something is ready to be read,
+// false if there is not.
+func (poller *fdPoller) wait() (bool, error) {
+ // 3 possible events per fd, and 2 fds, makes a maximum of 6 events.
+ // I don't know whether epoll_wait returns the number of events returned,
+ // or the total number of events ready.
+ // I decided to catch both by making the buffer one larger than the maximum.
+ events := make([]syscall.EpollEvent, 7)
+ for {
+ n, errno := syscall.EpollWait(poller.epfd, events, -1)
+ if n == -1 {
+ if errno == syscall.EINTR {
+ continue
+ }
+ return false, errno
+ }
+ if n == 0 {
+ // If there are no events, try again.
+ continue
+ }
+ if n > 6 {
+ // This should never happen. More events were returned than should be possible.
+ return false, errors.New("epoll_wait returned more events than I know what to do with")
+ }
+ ready := events[:n]
+ epollhup := false
+ epollerr := false
+ epollin := false
+ for _, event := range ready {
+ if event.Fd == int32(poller.fd) {
+ if event.Events&syscall.EPOLLHUP != 0 {
+ // This should not happen, but if it does, treat it as a wakeup.
+ epollhup = true
+ }
+ if event.Events&syscall.EPOLLERR != 0 {
+ // If an error is waiting on the file descriptor, we should pretend
+ // something is ready to read, and let syscall.Read pick up the error.
+ epollerr = true
+ }
+ if event.Events&syscall.EPOLLIN != 0 {
+ // There is data to read.
+ epollin = true
+ }
+ }
+ if event.Fd == int32(poller.pipe[0]) {
+ if event.Events&syscall.EPOLLHUP != 0 {
+ // Write pipe descriptor was closed, by us. This means we're closing down the
+ // watcher, and we should wake up.
+ }
+ if event.Events&syscall.EPOLLERR != 0 {
+ // If an error is waiting on the pipe file descriptor.
+ // This is an absolute mystery, and should never ever happen.
+ return false, errors.New("Error on the pipe descriptor.")
+ }
+ if event.Events&syscall.EPOLLIN != 0 {
+ // This is a regular wakeup, so we have to clear the buffer.
+ err := poller.clearWake()
+ if err != nil {
+ return false, err
+ }
+ }
+ }
+ }
+
+ if epollhup || epollerr || epollin {
+ return true, nil
+ }
+ return false, nil
+ }
+}
+
+// Close the write end of the poller.
+func (poller *fdPoller) wake() error {
+ buf := make([]byte, 1)
+ n, errno := syscall.Write(poller.pipe[1], buf)
+ if n == -1 {
+ if errno == syscall.EAGAIN {
+ // Buffer is full, poller will wake.
+ return nil
+ }
+ return errno
+ }
+ return nil
+}
+
+func (poller *fdPoller) clearWake() error {
+ // You have to be woken up a LOT in order to get to 100!
+ buf := make([]byte, 100)
+ n, errno := syscall.Read(poller.pipe[0], buf)
+ if n == -1 {
+ if errno == syscall.EAGAIN {
+ // Buffer is empty, someone else cleared our wake.
+ return nil
+ }
+ return errno
+ }
+ return nil
+}
+
+// Close all poller file descriptors, but not the one passed to it.
+func (poller *fdPoller) close() {
+ if poller.pipe[1] != -1 {
+ syscall.Close(poller.pipe[1])
+ }
+ if poller.pipe[0] != -1 {
+ syscall.Close(poller.pipe[0])
+ }
+ if poller.epfd != -1 {
+ syscall.Close(poller.epfd)
+ }
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/kqueue.go b/vendor/github.com/fsnotify/fsnotify/kqueue.go
new file mode 100644
index 0000000..b8ea308
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/kqueue.go
@@ -0,0 +1,502 @@
+// 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.
+
+// +build freebsd openbsd netbsd dragonfly darwin
+
+package fsnotify
+
+import (
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "sync"
+ "syscall"
+ "time"
+)
+
+// Watcher watches a set of files, delivering events to a channel.
+type Watcher struct {
+ Events chan Event
+ Errors chan error
+ done chan bool // Channel for sending a "quit message" to the reader goroutine
+
+ kq int // File descriptor (as returned by the kqueue() syscall).
+
+ mu sync.Mutex // Protects access to watcher data
+ watches map[string]int // Map of watched file descriptors (key: path).
+ externalWatches map[string]bool // Map of watches added by user of the library.
+ dirFlags map[string]uint32 // Map of watched directories to fflags used in kqueue.
+ paths map[int]pathInfo // Map file descriptors to path names for processing kqueue events.
+ fileExists map[string]bool // Keep track of if we know this file exists (to stop duplicate create events).
+ isClosed bool // Set to true when Close() is first called
+}
+
+type pathInfo struct {
+ name string
+ isDir bool
+}
+
+// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
+func NewWatcher() (*Watcher, error) {
+ kq, err := kqueue()
+ if err != nil {
+ return nil, err
+ }
+
+ w := &Watcher{
+ kq: kq,
+ watches: make(map[string]int),
+ dirFlags: make(map[string]uint32),
+ paths: make(map[int]pathInfo),
+ fileExists: make(map[string]bool),
+ externalWatches: make(map[string]bool),
+ Events: make(chan Event),
+ Errors: make(chan error),
+ done: make(chan bool),
+ }
+
+ go w.readEvents()
+ return w, nil
+}
+
+// Close removes all watches and closes the events channel.
+func (w *Watcher) Close() error {
+ w.mu.Lock()
+ if w.isClosed {
+ w.mu.Unlock()
+ return nil
+ }
+ w.isClosed = true
+ w.mu.Unlock()
+
+ // copy paths to remove while locked
+ w.mu.Lock()
+ var pathsToRemove = make([]string, 0, len(w.watches))
+ for name := range w.watches {
+ pathsToRemove = append(pathsToRemove, name)
+ }
+ w.mu.Unlock()
+ // unlock before calling Remove, which also locks
+
+ var err error
+ for _, name := range pathsToRemove {
+ if e := w.Remove(name); e != nil && err == nil {
+ err = e
+ }
+ }
+
+ // Send "quit" message to the reader goroutine:
+ w.done <- true
+
+ return nil
+}
+
+// Add starts watching the named file or directory (non-recursively).
+func (w *Watcher) Add(name string) error {
+ w.mu.Lock()
+ w.externalWatches[name] = true
+ w.mu.Unlock()
+ _, err := w.addWatch(name, noteAllEvents)
+ return err
+}
+
+// Remove stops watching the the named file or directory (non-recursively).
+func (w *Watcher) Remove(name string) error {
+ name = filepath.Clean(name)
+ w.mu.Lock()
+ watchfd, ok := w.watches[name]
+ w.mu.Unlock()
+ if !ok {
+ return fmt.Errorf("can't remove non-existent kevent watch for: %s", name)
+ }
+
+ const registerRemove = syscall.EV_DELETE
+ if err := register(w.kq, []int{watchfd}, registerRemove, 0); err != nil {
+ return err
+ }
+
+ syscall.Close(watchfd)
+
+ w.mu.Lock()
+ isDir := w.paths[watchfd].isDir
+ delete(w.watches, name)
+ delete(w.paths, watchfd)
+ delete(w.dirFlags, name)
+ w.mu.Unlock()
+
+ // Find all watched paths that are in this directory that are not external.
+ if isDir {
+ var pathsToRemove []string
+ w.mu.Lock()
+ for _, path := range w.paths {
+ wdir, _ := filepath.Split(path.name)
+ if filepath.Clean(wdir) == name {
+ if !w.externalWatches[path.name] {
+ pathsToRemove = append(pathsToRemove, path.name)
+ }
+ }
+ }
+ w.mu.Unlock()
+ for _, name := range pathsToRemove {
+ // Since these are internal, not much sense in propagating error
+ // to the user, as that will just confuse them with an error about
+ // a path they did not explicitly watch themselves.
+ w.Remove(name)
+ }
+ }
+
+ return nil
+}
+
+// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE)
+const noteAllEvents = syscall.NOTE_DELETE | syscall.NOTE_WRITE | syscall.NOTE_ATTRIB | syscall.NOTE_RENAME
+
+// keventWaitTime to block on each read from kevent
+var keventWaitTime = durationToTimespec(100 * time.Millisecond)
+
+// addWatch adds name to the watched file set.
+// The flags are interpreted as described in kevent(2).
+// Returns the real path to the file which was added, if any, which may be different from the one passed in the case of symlinks.
+func (w *Watcher) addWatch(name string, flags uint32) (string, error) {
+ var isDir bool
+ // Make ./name and name equivalent
+ name = filepath.Clean(name)
+
+ w.mu.Lock()
+ if w.isClosed {
+ w.mu.Unlock()
+ return "", errors.New("kevent instance already closed")
+ }
+ watchfd, alreadyWatching := w.watches[name]
+ // We already have a watch, but we can still override flags.
+ if alreadyWatching {
+ isDir = w.paths[watchfd].isDir
+ }
+ w.mu.Unlock()
+
+ if !alreadyWatching {
+ fi, err := os.Lstat(name)
+ if err != nil {
+ return "", err
+ }
+
+ // Don't watch sockets.
+ if fi.Mode()&os.ModeSocket == os.ModeSocket {
+ return "", nil
+ }
+
+ // Don't watch named pipes.
+ if fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe {
+ return "", nil
+ }
+
+ // Follow Symlinks
+ // Unfortunately, Linux can add bogus symlinks to watch list without
+ // issue, and Windows can't do symlinks period (AFAIK). To maintain
+ // consistency, we will act like everything is fine. There will simply
+ // be no file events for broken symlinks.
+ // Hence the returns of nil on errors.
+ if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
+ name, err = filepath.EvalSymlinks(name)
+ if err != nil {
+ return "", nil
+ }
+
+ w.mu.Lock()
+ _, alreadyWatching = w.watches[name]
+ w.mu.Unlock()
+
+ if alreadyWatching {
+ return name, nil
+ }
+
+ fi, err = os.Lstat(name)
+ if err != nil {
+ return "", nil
+ }
+ }
+
+ watchfd, err = syscall.Open(name, openMode, 0700)
+ if watchfd == -1 {
+ return "", err
+ }
+
+ isDir = fi.IsDir()
+ }
+
+ const registerAdd = syscall.EV_ADD | syscall.EV_CLEAR | syscall.EV_ENABLE
+ if err := register(w.kq, []int{watchfd}, registerAdd, flags); err != nil {
+ syscall.Close(watchfd)
+ return "", err
+ }
+
+ if !alreadyWatching {
+ w.mu.Lock()
+ w.watches[name] = watchfd
+ w.paths[watchfd] = pathInfo{name: name, isDir: isDir}
+ w.mu.Unlock()
+ }
+
+ if isDir {
+ // Watch the directory if it has not been watched before,
+ // or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles)
+ w.mu.Lock()
+
+ watchDir := (flags&syscall.NOTE_WRITE) == syscall.NOTE_WRITE &&
+ (!alreadyWatching || (w.dirFlags[name]&syscall.NOTE_WRITE) != syscall.NOTE_WRITE)
+ // Store flags so this watch can be updated later
+ w.dirFlags[name] = flags
+ w.mu.Unlock()
+
+ if watchDir {
+ if err := w.watchDirectoryFiles(name); err != nil {
+ return "", err
+ }
+ }
+ }
+ return name, nil
+}
+
+// readEvents reads from kqueue and converts the received kevents into
+// Event values that it sends down the Events channel.
+func (w *Watcher) readEvents() {
+ eventBuffer := make([]syscall.Kevent_t, 10)
+
+ for {
+ // See if there is a message on the "done" channel
+ select {
+ case <-w.done:
+ err := syscall.Close(w.kq)
+ if err != nil {
+ w.Errors <- err
+ }
+ close(w.Events)
+ close(w.Errors)
+ return
+ default:
+ }
+
+ // Get new events
+ kevents, err := read(w.kq, eventBuffer, &keventWaitTime)
+ // EINTR is okay, the syscall was interrupted before timeout expired.
+ if err != nil && err != syscall.EINTR {
+ w.Errors <- err
+ continue
+ }
+
+ // Flush the events we received to the Events channel
+ for len(kevents) > 0 {
+ kevent := &kevents[0]
+ watchfd := int(kevent.Ident)
+ mask := uint32(kevent.Fflags)
+ w.mu.Lock()
+ path := w.paths[watchfd]
+ w.mu.Unlock()
+ event := newEvent(path.name, mask)
+
+ if path.isDir && !(event.Op&Remove == Remove) {
+ // Double check to make sure the directory exists. This can happen when
+ // we do a rm -fr on a recursively watched folders and we receive a
+ // modification event first but the folder has been deleted and later
+ // receive the delete event
+ if _, err := os.Lstat(event.Name); os.IsNotExist(err) {
+ // mark is as delete event
+ event.Op |= Remove
+ }
+ }
+
+ if event.Op&Rename == Rename || event.Op&Remove == Remove {
+ w.Remove(event.Name)
+ w.mu.Lock()
+ delete(w.fileExists, event.Name)
+ w.mu.Unlock()
+ }
+
+ if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) {
+ w.sendDirectoryChangeEvents(event.Name)
+ } else {
+ // Send the event on the Events channel
+ w.Events <- event
+ }
+
+ if event.Op&Remove == Remove {
+ // Look for a file that may have overwritten this.
+ // For example, mv f1 f2 will delete f2, then create f2.
+ if path.isDir {
+ fileDir := filepath.Clean(event.Name)
+ w.mu.Lock()
+ _, found := w.watches[fileDir]
+ w.mu.Unlock()
+ if found {
+ // make sure the directory exists before we watch for changes. When we
+ // do a recursive watch and perform rm -fr, the parent directory might
+ // have gone missing, ignore the missing directory and let the
+ // upcoming delete event remove the watch from the parent directory.
+ if _, err := os.Lstat(fileDir); err == nil {
+ w.sendDirectoryChangeEvents(fileDir)
+ }
+ }
+ } else {
+ filePath := filepath.Clean(event.Name)
+ if fileInfo, err := os.Lstat(filePath); err == nil {
+ w.sendFileCreatedEventIfNew(filePath, fileInfo)
+ }
+ }
+ }
+
+ // Move to next event
+ kevents = kevents[1:]
+ }
+ }
+}
+
+// newEvent returns an platform-independent Event based on kqueue Fflags.
+func newEvent(name string, mask uint32) Event {
+ e := Event{Name: name}
+ if mask&syscall.NOTE_DELETE == syscall.NOTE_DELETE {
+ e.Op |= Remove
+ }
+ if mask&syscall.NOTE_WRITE == syscall.NOTE_WRITE {
+ e.Op |= Write
+ }
+ if mask&syscall.NOTE_RENAME == syscall.NOTE_RENAME {
+ e.Op |= Rename
+ }
+ if mask&syscall.NOTE_ATTRIB == syscall.NOTE_ATTRIB {
+ e.Op |= Chmod
+ }
+ return e
+}
+
+func newCreateEvent(name string) Event {
+ return Event{Name: name, Op: Create}
+}
+
+// watchDirectoryFiles to mimic inotify when adding a watch on a directory
+func (w *Watcher) watchDirectoryFiles(dirPath string) error {
+ // Get all files
+ files, err := ioutil.ReadDir(dirPath)
+ if err != nil {
+ return err
+ }
+
+ for _, fileInfo := range files {
+ filePath := filepath.Join(dirPath, fileInfo.Name())
+ filePath, err = w.internalWatch(filePath, fileInfo)
+ if err != nil {
+ return err
+ }
+
+ w.mu.Lock()
+ w.fileExists[filePath] = true
+ w.mu.Unlock()
+ }
+
+ return nil
+}
+
+// sendDirectoryEvents searches the directory for newly created files
+// and sends them over the event channel. This functionality is to have
+// the BSD version of fsnotify match Linux inotify which provides a
+// create event for files created in a watched directory.
+func (w *Watcher) sendDirectoryChangeEvents(dirPath string) {
+ // Get all files
+ files, err := ioutil.ReadDir(dirPath)
+ if err != nil {
+ w.Errors <- err
+ }
+
+ // Search for new files
+ for _, fileInfo := range files {
+ filePath := filepath.Join(dirPath, fileInfo.Name())
+ err := w.sendFileCreatedEventIfNew(filePath, fileInfo)
+
+ if err != nil {
+ return
+ }
+ }
+}
+
+// sendFileCreatedEvent sends a create event if the file isn't already being tracked.
+func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) {
+ w.mu.Lock()
+ _, doesExist := w.fileExists[filePath]
+ w.mu.Unlock()
+ if !doesExist {
+ // Send create event
+ w.Events <- newCreateEvent(filePath)
+ }
+
+ // like watchDirectoryFiles (but without doing another ReadDir)
+ filePath, err = w.internalWatch(filePath, fileInfo)
+ if err != nil {
+ return err
+ }
+
+ w.mu.Lock()
+ w.fileExists[filePath] = true
+ w.mu.Unlock()
+
+ return nil
+}
+
+func (w *Watcher) internalWatch(name string, fileInfo os.FileInfo) (string, error) {
+ if fileInfo.IsDir() {
+ // mimic Linux providing delete events for subdirectories
+ // but preserve the flags used if currently watching subdirectory
+ w.mu.Lock()
+ flags := w.dirFlags[name]
+ w.mu.Unlock()
+
+ flags |= syscall.NOTE_DELETE | syscall.NOTE_RENAME
+ return w.addWatch(name, flags)
+ }
+
+ // watch file to mimic Linux inotify
+ return w.addWatch(name, noteAllEvents)
+}
+
+// kqueue creates a new kernel event queue and returns a descriptor.
+func kqueue() (kq int, err error) {
+ kq, err = syscall.Kqueue()
+ if kq == -1 {
+ return kq, err
+ }
+ return kq, nil
+}
+
+// register events with the queue
+func register(kq int, fds []int, flags int, fflags uint32) error {
+ changes := make([]syscall.Kevent_t, len(fds))
+
+ for i, fd := range fds {
+ // SetKevent converts int to the platform-specific types:
+ syscall.SetKevent(&changes[i], fd, syscall.EVFILT_VNODE, flags)
+ changes[i].Fflags = fflags
+ }
+
+ // register the events
+ success, err := syscall.Kevent(kq, changes, nil, nil)
+ if success == -1 {
+ return err
+ }
+ return nil
+}
+
+// read retrieves pending events, or waits until an event occurs.
+// A timeout of nil blocks indefinitely, while 0 polls the queue.
+func read(kq int, events []syscall.Kevent_t, timeout *syscall.Timespec) ([]syscall.Kevent_t, error) {
+ n, err := syscall.Kevent(kq, nil, events, timeout)
+ if err != nil {
+ return nil, err
+ }
+ return events[0:n], nil
+}
+
+// durationToTimespec prepares a timeout value
+func durationToTimespec(d time.Duration) syscall.Timespec {
+ return syscall.NsecToTimespec(d.Nanoseconds())
+}
diff --git a/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go b/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go
new file mode 100644
index 0000000..c57ccb4
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go
@@ -0,0 +1,11 @@
+// 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.
+
+// +build freebsd openbsd netbsd dragonfly
+
+package fsnotify
+
+import "syscall"
+
+const openMode = syscall.O_NONBLOCK | syscall.O_RDONLY
diff --git a/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go b/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go
new file mode 100644
index 0000000..174b2c3
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go
@@ -0,0 +1,12 @@
+// 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.
+
+// +build darwin
+
+package fsnotify
+
+import "syscall"
+
+// note: this constant is not defined on BSD
+const openMode = syscall.O_EVTONLY
diff --git a/vendor/github.com/fsnotify/fsnotify/windows.go b/vendor/github.com/fsnotify/fsnotify/windows.go
new file mode 100644
index 0000000..c836bdb
--- /dev/null
+++ b/vendor/github.com/fsnotify/fsnotify/windows.go
@@ -0,0 +1,561 @@
+// 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.
+
+// +build windows
+
+package fsnotify
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sync"
+ "syscall"
+ "unsafe"
+)
+
+// Watcher watches a set of files, delivering events to a channel.
+type Watcher struct {
+ Events chan Event
+ Errors chan error
+ isClosed bool // Set to true when Close() is first called
+ mu sync.Mutex // Map access
+ port syscall.Handle // Handle to completion port
+ watches watchMap // Map of watches (key: i-number)
+ input chan *input // Inputs to the reader are sent on this channel
+ quit chan chan<- error
+}
+
+// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
+func NewWatcher() (*Watcher, error) {
+ port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0)
+ if e != nil {
+ return nil, os.NewSyscallError("CreateIoCompletionPort", e)
+ }
+ w := &Watcher{
+ port: port,
+ watches: make(watchMap),
+ input: make(chan *input, 1),
+ Events: make(chan Event, 50),
+ Errors: make(chan error),
+ quit: make(chan chan<- error, 1),
+ }
+ go w.readEvents()
+ return w, nil
+}
+
+// Close removes all watches and closes the events channel.
+func (w *Watcher) Close() error {
+ if w.isClosed {
+ return nil
+ }
+ w.isClosed = true
+
+ // Send "quit" message to the reader goroutine
+ ch := make(chan error)
+ w.quit <- ch
+ if err := w.wakeupReader(); err != nil {
+ return err
+ }
+ return <-ch
+}
+
+// Add starts watching the named file or directory (non-recursively).
+func (w *Watcher) Add(name string) error {
+ if w.isClosed {
+ return errors.New("watcher already closed")
+ }
+ in := &input{
+ op: opAddWatch,
+ path: filepath.Clean(name),
+ flags: sysFSALLEVENTS,
+ reply: make(chan error),
+ }
+ w.input <- in
+ if err := w.wakeupReader(); err != nil {
+ return err
+ }
+ return <-in.reply
+}
+
+// Remove stops watching the the named file or directory (non-recursively).
+func (w *Watcher) Remove(name string) error {
+ in := &input{
+ op: opRemoveWatch,
+ path: filepath.Clean(name),
+ reply: make(chan error),
+ }
+ w.input <- in
+ if err := w.wakeupReader(); err != nil {
+ return err
+ }
+ return <-in.reply
+}
+
+const (
+ // Options for AddWatch
+ sysFSONESHOT = 0x80000000
+ sysFSONLYDIR = 0x1000000
+
+ // Events
+ sysFSACCESS = 0x1
+ sysFSALLEVENTS = 0xfff
+ sysFSATTRIB = 0x4
+ sysFSCLOSE = 0x18
+ sysFSCREATE = 0x100
+ sysFSDELETE = 0x200
+ sysFSDELETESELF = 0x400
+ sysFSMODIFY = 0x2
+ sysFSMOVE = 0xc0
+ sysFSMOVEDFROM = 0x40
+ sysFSMOVEDTO = 0x80
+ sysFSMOVESELF = 0x800
+
+ // Special events
+ sysFSIGNORED = 0x8000
+ sysFSQOVERFLOW = 0x4000
+)
+
+func newEvent(name string, mask uint32) Event {
+ e := Event{Name: name}
+ if mask&sysFSCREATE == sysFSCREATE || mask&sysFSMOVEDTO == sysFSMOVEDTO {
+ e.Op |= Create
+ }
+ if mask&sysFSDELETE == sysFSDELETE || mask&sysFSDELETESELF == sysFSDELETESELF {
+ e.Op |= Remove
+ }
+ if mask&sysFSMODIFY == sysFSMODIFY {
+ e.Op |= Write
+ }
+ if mask&sysFSMOVE == sysFSMOVE || mask&sysFSMOVESELF == sysFSMOVESELF || mask&sysFSMOVEDFROM == sysFSMOVEDFROM {
+ e.Op |= Rename
+ }
+ if mask&sysFSATTRIB == sysFSATTRIB {
+ e.Op |= Chmod
+ }
+ return e
+}
+
+const (
+ opAddWatch = iota
+ opRemoveWatch
+)
+
+const (
+ provisional uint64 = 1 << (32 + iota)
+)
+
+type input struct {
+ op int
+ path string
+ flags uint32
+ reply chan error
+}
+
+type inode struct {
+ handle syscall.Handle
+ volume uint32
+ index uint64
+}
+
+type watch struct {
+ ov syscall.Overlapped
+ ino *inode // i-number
+ path string // Directory path
+ mask uint64 // Directory itself is being watched with these notify flags
+ names map[string]uint64 // Map of names being watched and their notify flags
+ rename string // Remembers the old name while renaming a file
+ buf [4096]byte
+}
+
+type indexMap map[uint64]*watch
+type watchMap map[uint32]indexMap
+
+func (w *Watcher) wakeupReader() error {
+ e := syscall.PostQueuedCompletionStatus(w.port, 0, 0, nil)
+ if e != nil {
+ return os.NewSyscallError("PostQueuedCompletionStatus", e)
+ }
+ return nil
+}
+
+func getDir(pathname string) (dir string, err error) {
+ attr, e := syscall.GetFileAttributes(syscall.StringToUTF16Ptr(pathname))
+ if e != nil {
+ return "", os.NewSyscallError("GetFileAttributes", e)
+ }
+ if attr&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 {
+ dir = pathname
+ } else {
+ dir, _ = filepath.Split(pathname)
+ dir = filepath.Clean(dir)
+ }
+ return
+}
+
+func getIno(path string) (ino *inode, err error) {
+ h, e := syscall.CreateFile(syscall.StringToUTF16Ptr(path),
+ syscall.FILE_LIST_DIRECTORY,
+ syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
+ nil, syscall.OPEN_EXISTING,
+ syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OVERLAPPED, 0)
+ if e != nil {
+ return nil, os.NewSyscallError("CreateFile", e)
+ }
+ var fi syscall.ByHandleFileInformation
+ if e = syscall.GetFileInformationByHandle(h, &fi); e != nil {
+ syscall.CloseHandle(h)
+ return nil, os.NewSyscallError("GetFileInformationByHandle", e)
+ }
+ ino = &inode{
+ handle: h,
+ volume: fi.VolumeSerialNumber,
+ index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow),
+ }
+ return ino, nil
+}
+
+// Must run within the I/O thread.
+func (m watchMap) get(ino *inode) *watch {
+ if i := m[ino.volume]; i != nil {
+ return i[ino.index]
+ }
+ return nil
+}
+
+// Must run within the I/O thread.
+func (m watchMap) set(ino *inode, watch *watch) {
+ i := m[ino.volume]
+ if i == nil {
+ i = make(indexMap)
+ m[ino.volume] = i
+ }
+ i[ino.index] = watch
+}
+
+// Must run within the I/O thread.
+func (w *Watcher) addWatch(pathname string, flags uint64) error {
+ dir, err := getDir(pathname)
+ if err != nil {
+ return err
+ }
+ if flags&sysFSONLYDIR != 0 && pathname != dir {
+ return nil
+ }
+ ino, err := getIno(dir)
+ if err != nil {
+ return err
+ }
+ w.mu.Lock()
+ watchEntry := w.watches.get(ino)
+ w.mu.Unlock()
+ if watchEntry == nil {
+ if _, e := syscall.CreateIoCompletionPort(ino.handle, w.port, 0, 0); e != nil {
+ syscall.CloseHandle(ino.handle)
+ return os.NewSyscallError("CreateIoCompletionPort", e)
+ }
+ watchEntry = &watch{
+ ino: ino,
+ path: dir,
+ names: make(map[string]uint64),
+ }
+ w.mu.Lock()
+ w.watches.set(ino, watchEntry)
+ w.mu.Unlock()
+ flags |= provisional
+ } else {
+ syscall.CloseHandle(ino.handle)
+ }
+ if pathname == dir {
+ watchEntry.mask |= flags
+ } else {
+ watchEntry.names[filepath.Base(pathname)] |= flags
+ }
+ if err = w.startRead(watchEntry); err != nil {
+ return err
+ }
+ if pathname == dir {
+ watchEntry.mask &= ^provisional
+ } else {
+ watchEntry.names[filepath.Base(pathname)] &= ^provisional
+ }
+ return nil
+}
+
+// Must run within the I/O thread.
+func (w *Watcher) remWatch(pathname string) error {
+ dir, err := getDir(pathname)
+ if err != nil {
+ return err
+ }
+ ino, err := getIno(dir)
+ if err != nil {
+ return err
+ }
+ w.mu.Lock()
+ watch := w.watches.get(ino)
+ w.mu.Unlock()
+ if watch == nil {
+ return fmt.Errorf("can't remove non-existent watch for: %s", pathname)
+ }
+ if pathname == dir {
+ w.sendEvent(watch.path, watch.mask&sysFSIGNORED)
+ watch.mask = 0
+ } else {
+ name := filepath.Base(pathname)
+ w.sendEvent(watch.path+"\\"+name, watch.names[name]&sysFSIGNORED)
+ delete(watch.names, name)
+ }
+ return w.startRead(watch)
+}
+
+// Must run within the I/O thread.
+func (w *Watcher) deleteWatch(watch *watch) {
+ for name, mask := range watch.names {
+ if mask&provisional == 0 {
+ w.sendEvent(watch.path+"\\"+name, mask&sysFSIGNORED)
+ }
+ delete(watch.names, name)
+ }
+ if watch.mask != 0 {
+ if watch.mask&provisional == 0 {
+ w.sendEvent(watch.path, watch.mask&sysFSIGNORED)
+ }
+ watch.mask = 0
+ }
+}
+
+// Must run within the I/O thread.
+func (w *Watcher) startRead(watch *watch) error {
+ if e := syscall.CancelIo(watch.ino.handle); e != nil {
+ w.Errors <- os.NewSyscallError("CancelIo", e)
+ w.deleteWatch(watch)
+ }
+ mask := toWindowsFlags(watch.mask)
+ for _, m := range watch.names {
+ mask |= toWindowsFlags(m)
+ }
+ if mask == 0 {
+ if e := syscall.CloseHandle(watch.ino.handle); e != nil {
+ w.Errors <- os.NewSyscallError("CloseHandle", e)
+ }
+ w.mu.Lock()
+ delete(w.watches[watch.ino.volume], watch.ino.index)
+ w.mu.Unlock()
+ return nil
+ }
+ e := syscall.ReadDirectoryChanges(watch.ino.handle, &watch.buf[0],
+ uint32(unsafe.Sizeof(watch.buf)), false, mask, nil, &watch.ov, 0)
+ if e != nil {
+ err := os.NewSyscallError("ReadDirectoryChanges", e)
+ if e == syscall.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 {
+ // Watched directory was probably removed
+ if w.sendEvent(watch.path, watch.mask&sysFSDELETESELF) {
+ if watch.mask&sysFSONESHOT != 0 {
+ watch.mask = 0
+ }
+ }
+ err = nil
+ }
+ w.deleteWatch(watch)
+ w.startRead(watch)
+ return err
+ }
+ return nil
+}
+
+// readEvents reads from the I/O completion port, converts the
+// received events into Event objects and sends them via the Events channel.
+// Entry point to the I/O thread.
+func (w *Watcher) readEvents() {
+ var (
+ n, key uint32
+ ov *syscall.Overlapped
+ )
+ runtime.LockOSThread()
+
+ for {
+ e := syscall.GetQueuedCompletionStatus(w.port, &n, &key, &ov, syscall.INFINITE)
+ watch := (*watch)(unsafe.Pointer(ov))
+
+ if watch == nil {
+ select {
+ case ch := <-w.quit:
+ w.mu.Lock()
+ var indexes []indexMap
+ for _, index := range w.watches {
+ indexes = append(indexes, index)
+ }
+ w.mu.Unlock()
+ for _, index := range indexes {
+ for _, watch := range index {
+ w.deleteWatch(watch)
+ w.startRead(watch)
+ }
+ }
+ var err error
+ if e := syscall.CloseHandle(w.port); e != nil {
+ err = os.NewSyscallError("CloseHandle", e)
+ }
+ close(w.Events)
+ close(w.Errors)
+ ch <- err
+ return
+ case in := <-w.input:
+ switch in.op {
+ case opAddWatch:
+ in.reply <- w.addWatch(in.path, uint64(in.flags))
+ case opRemoveWatch:
+ in.reply <- w.remWatch(in.path)
+ }
+ default:
+ }
+ continue
+ }
+
+ switch e {
+ case syscall.ERROR_MORE_DATA:
+ if watch == nil {
+ w.Errors <- errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer")
+ } else {
+ // The i/o succeeded but the buffer is full.
+ // In theory we should be building up a full packet.
+ // In practice we can get away with just carrying on.
+ n = uint32(unsafe.Sizeof(watch.buf))
+ }
+ case syscall.ERROR_ACCESS_DENIED:
+ // Watched directory was probably removed
+ w.sendEvent(watch.path, watch.mask&sysFSDELETESELF)
+ w.deleteWatch(watch)
+ w.startRead(watch)
+ continue
+ case syscall.ERROR_OPERATION_ABORTED:
+ // CancelIo was called on this handle
+ continue
+ default:
+ w.Errors <- os.NewSyscallError("GetQueuedCompletionPort", e)
+ continue
+ case nil:
+ }
+
+ var offset uint32
+ for {
+ if n == 0 {
+ w.Events <- newEvent("", sysFSQOVERFLOW)
+ w.Errors <- errors.New("short read in readEvents()")
+ break
+ }
+
+ // Point "raw" to the event in the buffer
+ raw := (*syscall.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset]))
+ buf := (*[syscall.MAX_PATH]uint16)(unsafe.Pointer(&raw.FileName))
+ name := syscall.UTF16ToString(buf[:raw.FileNameLength/2])
+ fullname := watch.path + "\\" + name
+
+ var mask uint64
+ switch raw.Action {
+ case syscall.FILE_ACTION_REMOVED:
+ mask = sysFSDELETESELF
+ case syscall.FILE_ACTION_MODIFIED:
+ mask = sysFSMODIFY
+ case syscall.FILE_ACTION_RENAMED_OLD_NAME:
+ watch.rename = name
+ case syscall.FILE_ACTION_RENAMED_NEW_NAME:
+ if watch.names[watch.rename] != 0 {
+ watch.names[name] |= watch.names[watch.rename]
+ delete(watch.names, watch.rename)
+ mask = sysFSMOVESELF
+ }
+ }
+
+ sendNameEvent := func() {
+ if w.sendEvent(fullname, watch.names[name]&mask) {
+ if watch.names[name]&sysFSONESHOT != 0 {
+ delete(watch.names, name)
+ }
+ }
+ }
+ if raw.Action != syscall.FILE_ACTION_RENAMED_NEW_NAME {
+ sendNameEvent()
+ }
+ if raw.Action == syscall.FILE_ACTION_REMOVED {
+ w.sendEvent(fullname, watch.names[name]&sysFSIGNORED)
+ delete(watch.names, name)
+ }
+ if w.sendEvent(fullname, watch.mask&toFSnotifyFlags(raw.Action)) {
+ if watch.mask&sysFSONESHOT != 0 {
+ watch.mask = 0
+ }
+ }
+ if raw.Action == syscall.FILE_ACTION_RENAMED_NEW_NAME {
+ fullname = watch.path + "\\" + watch.rename
+ sendNameEvent()
+ }
+
+ // Move to the next event in the buffer
+ if raw.NextEntryOffset == 0 {
+ break
+ }
+ offset += raw.NextEntryOffset
+
+ // Error!
+ if offset >= n {
+ w.Errors <- errors.New("Windows system assumed buffer larger than it is, events have likely been missed.")
+ break
+ }
+ }
+
+ if err := w.startRead(watch); err != nil {
+ w.Errors <- err
+ }
+ }
+}
+
+func (w *Watcher) sendEvent(name string, mask uint64) bool {
+ if mask == 0 {
+ return false
+ }
+ event := newEvent(name, uint32(mask))
+ select {
+ case ch := <-w.quit:
+ w.quit <- ch
+ case w.Events <- event:
+ }
+ return true
+}
+
+func toWindowsFlags(mask uint64) uint32 {
+ var m uint32
+ if mask&sysFSACCESS != 0 {
+ m |= syscall.FILE_NOTIFY_CHANGE_LAST_ACCESS
+ }
+ if mask&sysFSMODIFY != 0 {
+ m |= syscall.FILE_NOTIFY_CHANGE_LAST_WRITE
+ }
+ if mask&sysFSATTRIB != 0 {
+ m |= syscall.FILE_NOTIFY_CHANGE_ATTRIBUTES
+ }
+ if mask&(sysFSMOVE|sysFSCREATE|sysFSDELETE) != 0 {
+ m |= syscall.FILE_NOTIFY_CHANGE_FILE_NAME | syscall.FILE_NOTIFY_CHANGE_DIR_NAME
+ }
+ return m
+}
+
+func toFSnotifyFlags(action uint32) uint64 {
+ switch action {
+ case syscall.FILE_ACTION_ADDED:
+ return sysFSCREATE
+ case syscall.FILE_ACTION_REMOVED:
+ return sysFSDELETE
+ case syscall.FILE_ACTION_MODIFIED:
+ return sysFSMODIFY
+ case syscall.FILE_ACTION_RENAMED_OLD_NAME:
+ return sysFSMOVEDFROM
+ case syscall.FILE_ACTION_RENAMED_NEW_NAME:
+ return sysFSMOVEDTO
+ }
+ return 0
+}
diff --git a/vendor/github.com/go-check/check/LICENSE b/vendor/github.com/go-check/check/LICENSE
new file mode 100644
index 0000000..545cf2d
--- /dev/null
+++ b/vendor/github.com/go-check/check/LICENSE
@@ -0,0 +1,25 @@
+Gocheck - A rich testing framework for Go
+
+Copyright (c) 2010-2013 Gustavo Niemeyer <gustavo@niemeyer.net>
+
+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/github.com/go-check/check/README.md b/vendor/github.com/go-check/check/README.md
new file mode 100644
index 0000000..0ca78d9
--- /dev/null
+++ b/vendor/github.com/go-check/check/README.md
@@ -0,0 +1,10 @@
+Go-check
+========
+
+This is a fork of https://github.com/go-check/check
+
+The intention of this fork is not to change any of the original behavior, but add
+some specific behaviors needed for some of my projects already using this test suite.
+For documentation on the main behavior of go-check see the aforementioned repo.
+
+The original branch is intact at `orig_v1`
diff --git a/vendor/github.com/go-check/check/benchmark.go b/vendor/github.com/go-check/check/benchmark.go
new file mode 100644
index 0000000..46ea9dc
--- /dev/null
+++ b/vendor/github.com/go-check/check/benchmark.go
@@ -0,0 +1,187 @@
+// 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.
+
+package check
+
+import (
+ "fmt"
+ "runtime"
+ "time"
+)
+
+var memStats runtime.MemStats
+
+// testingB is a type passed to Benchmark functions to manage benchmark
+// timing and to specify the number of iterations to run.
+type timer struct {
+ start time.Time // Time test or benchmark started
+ duration time.Duration
+ N int
+ bytes int64
+ timerOn bool
+ benchTime time.Duration
+ // The initial states of memStats.Mallocs and memStats.TotalAlloc.
+ startAllocs uint64
+ startBytes uint64
+ // The net total of this test after being run.
+ netAllocs uint64
+ netBytes uint64
+}
+
+// StartTimer starts timing a test. This function is called automatically
+// before a benchmark starts, but it can also used to resume timing after
+// a call to StopTimer.
+func (c *C) StartTimer() {
+ if !c.timerOn {
+ c.start = time.Now()
+ c.timerOn = true
+
+ runtime.ReadMemStats(&memStats)
+ c.startAllocs = memStats.Mallocs
+ c.startBytes = memStats.TotalAlloc
+ }
+}
+
+// StopTimer stops timing a test. This can be used to pause the timer
+// while performing complex initialization that you don't
+// want to measure.
+func (c *C) StopTimer() {
+ if c.timerOn {
+ c.duration += time.Now().Sub(c.start)
+ c.timerOn = false
+ runtime.ReadMemStats(&memStats)
+ c.netAllocs += memStats.Mallocs - c.startAllocs
+ c.netBytes += memStats.TotalAlloc - c.startBytes
+ }
+}
+
+// ResetTimer sets the elapsed benchmark time to zero.
+// It does not affect whether the timer is running.
+func (c *C) ResetTimer() {
+ if c.timerOn {
+ c.start = time.Now()
+ runtime.ReadMemStats(&memStats)
+ c.startAllocs = memStats.Mallocs
+ c.startBytes = memStats.TotalAlloc
+ }
+ c.duration = 0
+ c.netAllocs = 0
+ c.netBytes = 0
+}
+
+// SetBytes informs the number of bytes that the benchmark processes
+// on each iteration. If this is called in a benchmark it will also
+// report MB/s.
+func (c *C) SetBytes(n int64) {
+ c.bytes = n
+}
+
+func (c *C) nsPerOp() int64 {
+ if c.N <= 0 {
+ return 0
+ }
+ return c.duration.Nanoseconds() / int64(c.N)
+}
+
+func (c *C) mbPerSec() float64 {
+ if c.bytes <= 0 || c.duration <= 0 || c.N <= 0 {
+ return 0
+ }
+ return (float64(c.bytes) * float64(c.N) / 1e6) / c.duration.Seconds()
+}
+
+func (c *C) timerString() string {
+ if c.N <= 0 {
+ return fmt.Sprintf("%3.3fs", float64(c.duration.Nanoseconds())/1e9)
+ }
+ mbs := c.mbPerSec()
+ mb := ""
+ if mbs != 0 {
+ mb = fmt.Sprintf("\t%7.2f MB/s", mbs)
+ }
+ nsop := c.nsPerOp()
+ ns := fmt.Sprintf("%10d ns/op", nsop)
+ if c.N > 0 && nsop < 100 {
+ // The format specifiers here make sure that
+ // the ones digits line up for all three possible formats.
+ if nsop < 10 {
+ ns = fmt.Sprintf("%13.2f ns/op", float64(c.duration.Nanoseconds())/float64(c.N))
+ } else {
+ ns = fmt.Sprintf("%12.1f ns/op", float64(c.duration.Nanoseconds())/float64(c.N))
+ }
+ }
+ memStats := ""
+ if c.benchMem {
+ allocedBytes := fmt.Sprintf("%8d B/op", int64(c.netBytes)/int64(c.N))
+ allocs := fmt.Sprintf("%8d allocs/op", int64(c.netAllocs)/int64(c.N))
+ memStats = fmt.Sprintf("\t%s\t%s", allocedBytes, allocs)
+ }
+ return fmt.Sprintf("%8d\t%s%s%s", c.N, ns, mb, memStats)
+}
+
+func min(x, y int) int {
+ if x > y {
+ return y
+ }
+ return x
+}
+
+func max(x, y int) int {
+ if x < y {
+ return y
+ }
+ return x
+}
+
+// roundDown10 rounds a number down to the nearest power of 10.
+func roundDown10(n int) int {
+ var tens = 0
+ // tens = floor(log_10(n))
+ for n > 10 {
+ n = n / 10
+ tens++
+ }
+ // result = 10^tens
+ result := 1
+ for i := 0; i < tens; i++ {
+ result *= 10
+ }
+ return result
+}
+
+// roundUp rounds x up to a number of the form [1eX, 2eX, 5eX].
+func roundUp(n int) int {
+ base := roundDown10(n)
+ if n < (2 * base) {
+ return 2 * base
+ }
+ if n < (5 * base) {
+ return 5 * base
+ }
+ return 10 * base
+}
diff --git a/vendor/github.com/go-check/check/check.go b/vendor/github.com/go-check/check/check.go
new file mode 100644
index 0000000..a4e6090
--- /dev/null
+++ b/vendor/github.com/go-check/check/check.go
@@ -0,0 +1,939 @@
+// Package check is a rich testing extension for Go's testing package.
+//
+// For details about the project, see:
+//
+// http://labix.org/gocheck
+//
+package check
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "math/rand"
+ "os"
+ "path"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+// -----------------------------------------------------------------------
+// Internal type which deals with suite method calling.
+
+const (
+ fixtureKd = iota
+ testKd
+)
+
+type funcKind int
+
+const (
+ succeededSt = iota
+ failedSt
+ skippedSt
+ panickedSt
+ fixturePanickedSt
+ missedSt
+)
+
+type funcStatus uint32
+
+// A method value can't reach its own Method structure.
+type methodType struct {
+ reflect.Value
+ Info reflect.Method
+}
+
+func newMethod(receiver reflect.Value, i int) *methodType {
+ return &methodType{receiver.Method(i), receiver.Type().Method(i)}
+}
+
+func (method *methodType) PC() uintptr {
+ return method.Info.Func.Pointer()
+}
+
+func (method *methodType) suiteName() string {
+ t := method.Info.Type.In(0)
+ if t.Kind() == reflect.Ptr {
+ t = t.Elem()
+ }
+ return t.Name()
+}
+
+func (method *methodType) String() string {
+ return method.suiteName() + "." + method.Info.Name
+}
+
+func (method *methodType) matches(re *regexp.Regexp) bool {
+ return (re.MatchString(method.Info.Name) ||
+ re.MatchString(method.suiteName()) ||
+ re.MatchString(method.String()))
+}
+
+type C struct {
+ method *methodType
+ kind funcKind
+ testName string
+ _status funcStatus
+ logb *logger
+ logw io.Writer
+ done chan *C
+ reason string
+ mustFail bool
+ tempDir *tempDir
+ benchMem bool
+ startTime time.Time
+ timer
+}
+
+func (c *C) status() funcStatus {
+ return funcStatus(atomic.LoadUint32((*uint32)(&c._status)))
+}
+
+func (c *C) setStatus(s funcStatus) {
+ atomic.StoreUint32((*uint32)(&c._status), uint32(s))
+}
+
+func (c *C) stopNow() {
+ runtime.Goexit()
+}
+
+// logger is a concurrency safe byte.Buffer
+type logger struct {
+ sync.Mutex
+ writer bytes.Buffer
+}
+
+func (l *logger) Write(buf []byte) (int, error) {
+ l.Lock()
+ defer l.Unlock()
+ return l.writer.Write(buf)
+}
+
+func (l *logger) WriteTo(w io.Writer) (int64, error) {
+ l.Lock()
+ defer l.Unlock()
+ return l.writer.WriteTo(w)
+}
+
+func (l *logger) String() string {
+ l.Lock()
+ defer l.Unlock()
+ return l.writer.String()
+}
+
+// -----------------------------------------------------------------------
+// Handling of temporary files and directories.
+
+type tempDir struct {
+ sync.Mutex
+ path string
+ counter int
+}
+
+func (td *tempDir) newPath() string {
+ td.Lock()
+ defer td.Unlock()
+ if td.path == "" {
+ var err error
+ for i := 0; i != 100; i++ {
+ path := fmt.Sprintf("%s%ccheck-%d", os.TempDir(), os.PathSeparator, rand.Int())
+ if err = os.Mkdir(path, 0700); err == nil {
+ td.path = path
+ break
+ }
+ }
+ if td.path == "" {
+ panic("Couldn't create temporary directory: " + err.Error())
+ }
+ }
+ result := filepath.Join(td.path, strconv.Itoa(td.counter))
+ td.counter += 1
+ return result
+}
+
+func (td *tempDir) removeAll() {
+ td.Lock()
+ defer td.Unlock()
+ if td.path != "" {
+ err := os.RemoveAll(td.path)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "WARNING: Error cleaning up temporaries: "+err.Error())
+ }
+ }
+}
+
+// Create a new temporary directory which is automatically removed after
+// the suite finishes running.
+func (c *C) MkDir() string {
+ path := c.tempDir.newPath()
+ if err := os.Mkdir(path, 0700); err != nil {
+ panic(fmt.Sprintf("Couldn't create temporary directory %s: %s", path, err.Error()))
+ }
+ return path
+}
+
+// -----------------------------------------------------------------------
+// Low-level logging functions.
+
+func (c *C) log(args ...interface{}) {
+ c.writeLog([]byte(fmt.Sprint(args...) + "\n"))
+}
+
+func (c *C) logf(format string, args ...interface{}) {
+ c.writeLog([]byte(fmt.Sprintf(format+"\n", args...)))
+}
+
+func (c *C) logNewLine() {
+ c.writeLog([]byte{'\n'})
+}
+
+func (c *C) writeLog(buf []byte) {
+ c.logb.Write(buf)
+ if c.logw != nil {
+ c.logw.Write(buf)
+ }
+}
+
+func hasStringOrError(x interface{}) (ok bool) {
+ _, ok = x.(fmt.Stringer)
+ if ok {
+ return
+ }
+ _, ok = x.(error)
+ return
+}
+
+func (c *C) logValue(label string, value interface{}) {
+ if label == "" {
+ if hasStringOrError(value) {
+ c.logf("... %#v (%q)", value, value)
+ } else {
+ c.logf("... %#v", value)
+ }
+ } else if value == nil {
+ c.logf("... %s = nil", label)
+ } else {
+ if hasStringOrError(value) {
+ fv := fmt.Sprintf("%#v", value)
+ qv := fmt.Sprintf("%q", value)
+ if fv != qv {
+ c.logf("... %s %s = %s (%s)", label, reflect.TypeOf(value), fv, qv)
+ return
+ }
+ }
+ if s, ok := value.(string); ok && isMultiLine(s) {
+ c.logf(`... %s %s = "" +`, label, reflect.TypeOf(value))
+ c.logMultiLine(s)
+ } else {
+ c.logf("... %s %s = %#v", label, reflect.TypeOf(value), value)
+ }
+ }
+}
+
+func (c *C) logMultiLine(s string) {
+ b := make([]byte, 0, len(s)*2)
+ i := 0
+ n := len(s)
+ for i < n {
+ j := i + 1
+ for j < n && s[j-1] != '\n' {
+ j++
+ }
+ b = append(b, "... "...)
+ b = strconv.AppendQuote(b, s[i:j])
+ if j < n {
+ b = append(b, " +"...)
+ }
+ b = append(b, '\n')
+ i = j
+ }
+ c.writeLog(b)
+}
+
+func isMultiLine(s string) bool {
+ for i := 0; i+1 < len(s); i++ {
+ if s[i] == '\n' {
+ return true
+ }
+ }
+ return false
+}
+
+func (c *C) logString(issue string) {
+ c.log("... ", issue)
+}
+
+func (c *C) logCaller(skip int) {
+ // This is a bit heavier than it ought to be.
+ skip += 1 // Our own frame.
+ pc, callerFile, callerLine, ok := runtime.Caller(skip)
+ if !ok {
+ return
+ }
+ var testFile string
+ var testLine int
+ testFunc := runtime.FuncForPC(c.method.PC())
+ if runtime.FuncForPC(pc) != testFunc {
+ for {
+ skip += 1
+ if pc, file, line, ok := runtime.Caller(skip); ok {
+ // Note that the test line may be different on
+ // distinct calls for the same test. Showing
+ // the "internal" line is helpful when debugging.
+ if runtime.FuncForPC(pc) == testFunc {
+ testFile, testLine = file, line
+ break
+ }
+ } else {
+ break
+ }
+ }
+ }
+ if testFile != "" && (testFile != callerFile || testLine != callerLine) {
+ c.logCode(testFile, testLine)
+ }
+ c.logCode(callerFile, callerLine)
+}
+
+func (c *C) logCode(path string, line int) {
+ c.logf("%s:%d:", nicePath(path), line)
+ code, err := printLine(path, line)
+ if code == "" {
+ code = "..." // XXX Open the file and take the raw line.
+ if err != nil {
+ code += err.Error()
+ }
+ }
+ c.log(indent(code, " "))
+}
+
+var valueGo = filepath.Join("reflect", "value.go")
+var asmGo = filepath.Join("runtime", "asm_")
+
+func (c *C) logPanic(skip int, value interface{}) {
+ skip++ // Our own frame.
+ initialSkip := skip
+ for ; ; skip++ {
+ if pc, file, line, ok := runtime.Caller(skip); ok {
+ if skip == initialSkip {
+ c.logf("... Panic: %s (PC=0x%X)\n", value, pc)
+ }
+ name := niceFuncName(pc)
+ path := nicePath(file)
+ if strings.Contains(path, "/gopkg.in/check.v") {
+ continue
+ }
+ if name == "Value.call" && strings.HasSuffix(path, valueGo) {
+ continue
+ }
+ if (name == "call16" || name == "call32") && strings.Contains(path, asmGo) {
+ continue
+ }
+ c.logf("%s:%d\n in %s", nicePath(file), line, name)
+ } else {
+ break
+ }
+ }
+}
+
+func (c *C) logSoftPanic(issue string) {
+ c.log("... Panic: ", issue)
+}
+
+func (c *C) logArgPanic(method *methodType, expectedType string) {
+ c.logf("... Panic: %s argument should be %s",
+ niceFuncName(method.PC()), expectedType)
+}
+
+// -----------------------------------------------------------------------
+// Some simple formatting helpers.
+
+var initWD, initWDErr = os.Getwd()
+
+func init() {
+ if initWDErr == nil {
+ initWD = strings.Replace(initWD, "\\", "/", -1) + "/"
+ }
+}
+
+func nicePath(path string) string {
+ if initWDErr == nil {
+ if strings.HasPrefix(path, initWD) {
+ return path[len(initWD):]
+ }
+ }
+ return path
+}
+
+func niceFuncPath(pc uintptr) string {
+ function := runtime.FuncForPC(pc)
+ if function != nil {
+ filename, line := function.FileLine(pc)
+ return fmt.Sprintf("%s:%d", nicePath(filename), line)
+ }
+ return "<unknown path>"
+}
+
+func niceFuncName(pc uintptr) string {
+ function := runtime.FuncForPC(pc)
+ if function != nil {
+ name := path.Base(function.Name())
+ if i := strings.Index(name, "."); i > 0 {
+ name = name[i+1:]
+ }
+ if strings.HasPrefix(name, "(*") {
+ if i := strings.Index(name, ")"); i > 0 {
+ name = name[2:i] + name[i+1:]
+ }
+ }
+ if i := strings.LastIndex(name, ".*"); i != -1 {
+ name = name[:i] + "." + name[i+2:]
+ }
+ if i := strings.LastIndex(name, "·"); i != -1 {
+ name = name[:i] + "." + name[i+2:]
+ }
+ return name
+ }
+ return "<unknown function>"
+}
+
+// -----------------------------------------------------------------------
+// Result tracker to aggregate call results.
+
+type Result struct {
+ Succeeded int
+ Failed int
+ Skipped int
+ Panicked int
+ FixturePanicked int
+ ExpectedFailures int
+ Missed int // Not even tried to run, related to a panic in the fixture.
+ RunError error // Houston, we've got a problem.
+ WorkDir string // If KeepWorkDir is true
+}
+
+type resultTracker struct {
+ result Result
+ _lastWasProblem bool
+ _waiting int
+ _missed int
+ _expectChan chan *C
+ _doneChan chan *C
+ _stopChan chan bool
+}
+
+func newResultTracker() *resultTracker {
+ return &resultTracker{_expectChan: make(chan *C), // Synchronous
+ _doneChan: make(chan *C, 32), // Asynchronous
+ _stopChan: make(chan bool)} // Synchronous
+}
+
+func (tracker *resultTracker) start() {
+ go tracker._loopRoutine()
+}
+
+func (tracker *resultTracker) waitAndStop() {
+ <-tracker._stopChan
+}
+
+func (tracker *resultTracker) expectCall(c *C) {
+ tracker._expectChan <- c
+}
+
+func (tracker *resultTracker) callDone(c *C) {
+ tracker._doneChan <- c
+}
+
+func (tracker *resultTracker) _loopRoutine() {
+ for {
+ var c *C
+ if tracker._waiting > 0 {
+ // Calls still running. Can't stop.
+ select {
+ // XXX Reindent this (not now to make diff clear)
+ case c = <-tracker._expectChan:
+ tracker._waiting += 1
+ case c = <-tracker._doneChan:
+ tracker._waiting -= 1
+ switch c.status() {
+ case succeededSt:
+ if c.kind == testKd {
+ if c.mustFail {
+ tracker.result.ExpectedFailures++
+ } else {
+ tracker.result.Succeeded++
+ }
+ }
+ case failedSt:
+ tracker.result.Failed++
+ case panickedSt:
+ if c.kind == fixtureKd {
+ tracker.result.FixturePanicked++
+ } else {
+ tracker.result.Panicked++
+ }
+ case fixturePanickedSt:
+ // Track it as missed, since the panic
+ // was on the fixture, not on the test.
+ tracker.result.Missed++
+ case missedSt:
+ tracker.result.Missed++
+ case skippedSt:
+ if c.kind == testKd {
+ tracker.result.Skipped++
+ }
+ }
+ }
+ } else {
+ // No calls. Can stop, but no done calls here.
+ select {
+ case tracker._stopChan <- true:
+ return
+ case c = <-tracker._expectChan:
+ tracker._waiting += 1
+ case c = <-tracker._doneChan:
+ panic("Tracker got an unexpected done call.")
+ }
+ }
+ }
+}
+
+// -----------------------------------------------------------------------
+// The underlying suite runner.
+
+type suiteRunner struct {
+ suite interface{}
+ setUpSuite, tearDownSuite *methodType
+ setUpTest, tearDownTest *methodType
+ onTimeout *methodType
+ tests []*methodType
+ tracker *resultTracker
+ tempDir *tempDir
+ keepDir bool
+ output *outputWriter
+ reportedProblemLast bool
+ benchTime time.Duration
+ benchMem bool
+ checkTimeout time.Duration
+}
+
+type RunConf struct {
+ Output io.Writer
+ Stream bool
+ Verbose bool
+ Filter string
+ Benchmark bool
+ BenchmarkTime time.Duration // Defaults to 1 second
+ BenchmarkMem bool
+ KeepWorkDir bool
+ CheckTimeout time.Duration
+}
+
+// Create a new suiteRunner able to run all methods in the given suite.
+func newSuiteRunner(suite interface{}, runConf *RunConf) *suiteRunner {
+ var conf RunConf
+ if runConf != nil {
+ conf = *runConf
+ }
+ if conf.Output == nil {
+ conf.Output = os.Stdout
+ }
+ if conf.Benchmark {
+ conf.Verbose = true
+ }
+
+ suiteType := reflect.TypeOf(suite)
+ suiteNumMethods := suiteType.NumMethod()
+ suiteValue := reflect.ValueOf(suite)
+
+ runner := &suiteRunner{
+ suite: suite,
+ output: newOutputWriter(conf.Output, conf.Stream, conf.Verbose),
+ tracker: newResultTracker(),
+ benchTime: conf.BenchmarkTime,
+ benchMem: conf.BenchmarkMem,
+ tempDir: &tempDir{},
+ keepDir: conf.KeepWorkDir,
+ tests: make([]*methodType, 0, suiteNumMethods),
+ checkTimeout: conf.CheckTimeout,
+ }
+ if runner.benchTime == 0 {
+ runner.benchTime = 1 * time.Second
+ }
+
+ var filterRegexp *regexp.Regexp
+ if conf.Filter != "" {
+ if regexp, err := regexp.Compile(conf.Filter); err != nil {
+ msg := "Bad filter expression: " + err.Error()
+ runner.tracker.result.RunError = errors.New(msg)
+ return runner
+ } else {
+ filterRegexp = regexp
+ }
+ }
+
+ for i := 0; i != suiteNumMethods; i++ {
+ method := newMethod(suiteValue, i)
+ switch method.Info.Name {
+ case "SetUpSuite":
+ runner.setUpSuite = method
+ case "TearDownSuite":
+ runner.tearDownSuite = method
+ case "SetUpTest":
+ runner.setUpTest = method
+ case "TearDownTest":
+ runner.tearDownTest = method
+ case "OnTimeout":
+ runner.onTimeout = method
+ default:
+ prefix := "Test"
+ if conf.Benchmark {
+ prefix = "Benchmark"
+ }
+ if !strings.HasPrefix(method.Info.Name, prefix) {
+ continue
+ }
+ if filterRegexp == nil || method.matches(filterRegexp) {
+ runner.tests = append(runner.tests, method)
+ }
+ }
+ }
+ return runner
+}
+
+// Run all methods in the given suite.
+func (runner *suiteRunner) run() *Result {
+ if runner.tracker.result.RunError == nil && len(runner.tests) > 0 {
+ runner.tracker.start()
+ if runner.checkFixtureArgs() {
+ c := runner.runFixture(runner.setUpSuite, "", nil)
+ if c == nil || c.status() == succeededSt {
+ for i := 0; i != len(runner.tests); i++ {
+ c := runner.runTest(runner.tests[i])
+ if c.status() == fixturePanickedSt {
+ runner.skipTests(missedSt, runner.tests[i+1:])
+ break
+ }
+ }
+ } else if c != nil && c.status() == skippedSt {
+ runner.skipTests(skippedSt, runner.tests)
+ } else {
+ runner.skipTests(missedSt, runner.tests)
+ }
+ runner.runFixture(runner.tearDownSuite, "", nil)
+ } else {
+ runner.skipTests(missedSt, runner.tests)
+ }
+ runner.tracker.waitAndStop()
+ if runner.keepDir {
+ runner.tracker.result.WorkDir = runner.tempDir.path
+ } else {
+ runner.tempDir.removeAll()
+ }
+ }
+ return &runner.tracker.result
+}
+
+// Create a call object with the given suite method, and fork a
+// goroutine with the provided dispatcher for running it.
+func (runner *suiteRunner) forkCall(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C {
+ var logw io.Writer
+ if runner.output.Stream {
+ logw = runner.output
+ }
+ if logb == nil {
+ logb = new(logger)
+ }
+ c := &C{
+ method: method,
+ kind: kind,
+ testName: testName,
+ logb: logb,
+ logw: logw,
+ tempDir: runner.tempDir,
+ done: make(chan *C, 1),
+ timer: timer{benchTime: runner.benchTime},
+ startTime: time.Now(),
+ benchMem: runner.benchMem,
+ }
+ runner.tracker.expectCall(c)
+ go (func() {
+ runner.reportCallStarted(c)
+ defer runner.callDone(c)
+ dispatcher(c)
+ })()
+ return c
+}
+
+type timeoutErr struct {
+ method *methodType
+ t time.Duration
+}
+
+func (e timeoutErr) Error() string {
+ return fmt.Sprintf("%s test timed out after %v", e.method.String(), e.t)
+}
+
+func isTimeout(e error) bool {
+ if e == nil {
+ return false
+ }
+ _, ok := e.(timeoutErr)
+ return ok
+}
+
+// Same as forkCall(), but wait for call to finish before returning.
+func (runner *suiteRunner) runFunc(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C {
+ var timeout <-chan time.Time
+ if runner.checkTimeout != 0 {
+ timeout = time.After(runner.checkTimeout)
+ }
+ c := runner.forkCall(method, kind, testName, logb, dispatcher)
+ select {
+ case <-c.done:
+ case <-timeout:
+ if runner.onTimeout != nil {
+ // run the OnTimeout callback, allowing the suite to collect any sort of debug information it can
+ // `runFixture` is syncronous, so run this in a separate goroutine with a timeout
+ cChan := make(chan *C)
+ go func() {
+ cChan <- runner.runFixture(runner.onTimeout, c.testName, c.logb)
+ }()
+ select {
+ case <-cChan:
+ case <-time.After(runner.checkTimeout):
+ }
+ }
+ panic(timeoutErr{method, runner.checkTimeout})
+ }
+ return c
+}
+
+// Handle a finished call. If there were any panics, update the call status
+// accordingly. Then, mark the call as done and report to the tracker.
+func (runner *suiteRunner) callDone(c *C) {
+ value := recover()
+ if value != nil {
+ switch v := value.(type) {
+ case *fixturePanic:
+ if v.status == skippedSt {
+ c.setStatus(skippedSt)
+ } else {
+ c.logSoftPanic("Fixture has panicked (see related PANIC)")
+ c.setStatus(fixturePanickedSt)
+ }
+ default:
+ c.logPanic(1, value)
+ c.setStatus(panickedSt)
+ }
+ }
+ if c.mustFail {
+ switch c.status() {
+ case failedSt:
+ c.setStatus(succeededSt)
+ case succeededSt:
+ c.setStatus(failedSt)
+ c.logString("Error: Test succeeded, but was expected to fail")
+ c.logString("Reason: " + c.reason)
+ }
+ }
+
+ runner.reportCallDone(c)
+ c.done <- c
+}
+
+// Runs a fixture call synchronously. The fixture will still be run in a
+// goroutine like all suite methods, but this method will not return
+// while the fixture goroutine is not done, because the fixture must be
+// run in a desired order.
+func (runner *suiteRunner) runFixture(method *methodType, testName string, logb *logger) *C {
+ if method != nil {
+ c := runner.runFunc(method, fixtureKd, testName, logb, func(c *C) {
+ c.ResetTimer()
+ c.StartTimer()
+ defer c.StopTimer()
+ c.method.Call([]reflect.Value{reflect.ValueOf(c)})
+ })
+ return c
+ }
+ return nil
+}
+
+// Run the fixture method with runFixture(), but panic with a fixturePanic{}
+// in case the fixture method panics. This makes it easier to track the
+// fixture panic together with other call panics within forkTest().
+func (runner *suiteRunner) runFixtureWithPanic(method *methodType, testName string, logb *logger, skipped *bool) *C {
+ if skipped != nil && *skipped {
+ return nil
+ }
+ c := runner.runFixture(method, testName, logb)
+ if c != nil && c.status() != succeededSt {
+ if skipped != nil {
+ *skipped = c.status() == skippedSt
+ }
+ panic(&fixturePanic{c.status(), method})
+ }
+ return c
+}
+
+type fixturePanic struct {
+ status funcStatus
+ method *methodType
+}
+
+// Run the suite test method, together with the test-specific fixture,
+// asynchronously.
+func (runner *suiteRunner) forkTest(method *methodType) *C {
+ testName := method.String()
+ return runner.forkCall(method, testKd, testName, nil, func(c *C) {
+ var skipped bool
+ defer runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, &skipped)
+ defer c.StopTimer()
+ benchN := 1
+ for {
+ runner.runFixtureWithPanic(runner.setUpTest, testName, c.logb, &skipped)
+ mt := c.method.Type()
+ if mt.NumIn() != 1 || mt.In(0) != reflect.TypeOf(c) {
+ // Rather than a plain panic, provide a more helpful message when
+ // the argument type is incorrect.
+ c.setStatus(panickedSt)
+ c.logArgPanic(c.method, "*check.C")
+ return
+ }
+
+ if strings.HasPrefix(c.method.Info.Name, "Test") {
+ c.ResetTimer()
+ c.StartTimer()
+ c.method.Call([]reflect.Value{reflect.ValueOf(c)})
+ return
+ }
+
+ if !strings.HasPrefix(c.method.Info.Name, "Benchmark") {
+ panic("unexpected method prefix: " + c.method.Info.Name)
+ }
+
+ runtime.GC()
+ c.N = benchN
+ c.ResetTimer()
+ c.StartTimer()
+
+ c.method.Call([]reflect.Value{reflect.ValueOf(c)})
+ c.StopTimer()
+ if c.status() != succeededSt || c.duration >= c.benchTime || benchN >= 1e9 {
+ return
+ }
+ perOpN := int(1e9)
+ if c.nsPerOp() != 0 {
+ perOpN = int(c.benchTime.Nanoseconds() / c.nsPerOp())
+ }
+
+ // Logic taken from the stock testing package:
+ // - Run more iterations than we think we'll need for a second (1.5x).
+ // - Don't grow too fast in case we had timing errors previously.
+ // - Be sure to run at least one more than last time.
+ benchN = max(min(perOpN+perOpN/2, 100*benchN), benchN+1)
+ benchN = roundUp(benchN)
+
+ skipped = true // Don't run the deferred one if this panics.
+ runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, nil)
+ skipped = false
+ }
+ })
+}
+
+// Same as forkTest(), but wait for the test to finish before returning.
+func (runner *suiteRunner) runTest(method *methodType) *C {
+ var timeout <-chan time.Time
+ if runner.checkTimeout != 0 {
+ timeout = time.After(runner.checkTimeout)
+ }
+ c := runner.forkTest(method)
+ select {
+ case <-c.done:
+ case <-timeout:
+ if runner.onTimeout != nil {
+ // run the OnTimeout callback, allowing the suite to collect any sort of debug information it can
+ // `runFixture` is syncronous, so run this in a separate goroutine with a timeout
+ cChan := make(chan *C)
+ go func() {
+ cChan <- runner.runFixture(runner.onTimeout, c.testName, c.logb)
+ }()
+ select {
+ case <-cChan:
+ case <-time.After(runner.checkTimeout):
+ }
+ }
+ panic(timeoutErr{method, runner.checkTimeout})
+ }
+ return c
+}
+
+// Helper to mark tests as skipped or missed. A bit heavy for what
+// it does, but it enables homogeneous handling of tracking, including
+// nice verbose output.
+func (runner *suiteRunner) skipTests(status funcStatus, methods []*methodType) {
+ for _, method := range methods {
+ runner.runFunc(method, testKd, "", nil, func(c *C) {
+ c.setStatus(status)
+ })
+ }
+}
+
+// Verify if the fixture arguments are *check.C. In case of errors,
+// log the error as a panic in the fixture method call, and return false.
+func (runner *suiteRunner) checkFixtureArgs() bool {
+ succeeded := true
+ argType := reflect.TypeOf(&C{})
+ for _, method := range []*methodType{runner.setUpSuite, runner.tearDownSuite, runner.setUpTest, runner.tearDownTest, runner.onTimeout} {
+ if method != nil {
+ mt := method.Type()
+ if mt.NumIn() != 1 || mt.In(0) != argType {
+ succeeded = false
+ runner.runFunc(method, fixtureKd, "", nil, func(c *C) {
+ c.logArgPanic(method, "*check.C")
+ c.setStatus(panickedSt)
+ })
+ }
+ }
+ }
+ return succeeded
+}
+
+func (runner *suiteRunner) reportCallStarted(c *C) {
+ runner.output.WriteCallStarted("START", c)
+}
+
+func (runner *suiteRunner) reportCallDone(c *C) {
+ runner.tracker.callDone(c)
+ switch c.status() {
+ case succeededSt:
+ if c.mustFail {
+ runner.output.WriteCallSuccess("FAIL EXPECTED", c)
+ } else {
+ runner.output.WriteCallSuccess("PASS", c)
+ }
+ case skippedSt:
+ runner.output.WriteCallSuccess("SKIP", c)
+ case failedSt:
+ runner.output.WriteCallProblem("FAIL", c)
+ case panickedSt:
+ runner.output.WriteCallProblem("PANIC", c)
+ case fixturePanickedSt:
+ // That's a testKd call reporting that its fixture
+ // has panicked. The fixture call which caused the
+ // panic itself was tracked above. We'll report to
+ // aid debugging.
+ runner.output.WriteCallProblem("PANIC", c)
+ case missedSt:
+ runner.output.WriteCallSuccess("MISS", c)
+ }
+}
diff --git a/vendor/github.com/go-check/check/checkers.go b/vendor/github.com/go-check/check/checkers.go
new file mode 100644
index 0000000..bac3387
--- /dev/null
+++ b/vendor/github.com/go-check/check/checkers.go
@@ -0,0 +1,458 @@
+package check
+
+import (
+ "fmt"
+ "reflect"
+ "regexp"
+)
+
+// -----------------------------------------------------------------------
+// CommentInterface and Commentf helper, to attach extra information to checks.
+
+type comment struct {
+ format string
+ args []interface{}
+}
+
+// Commentf returns an infomational value to use with Assert or Check calls.
+// If the checker test fails, the provided arguments will be passed to
+// fmt.Sprintf, and will be presented next to the logged failure.
+//
+// For example:
+//
+// c.Assert(v, Equals, 42, Commentf("Iteration #%d failed.", i))
+//
+// Note that if the comment is constant, a better option is to
+// simply use a normal comment right above or next to the line, as
+// it will also get printed with any errors:
+//
+// c.Assert(l, Equals, 8192) // Ensure buffer size is correct (bug #123)
+//
+func Commentf(format string, args ...interface{}) CommentInterface {
+ return &comment{format, args}
+}
+
+// CommentInterface must be implemented by types that attach extra
+// information to failed checks. See the Commentf function for details.
+type CommentInterface interface {
+ CheckCommentString() string
+}
+
+func (c *comment) CheckCommentString() string {
+ return fmt.Sprintf(c.format, c.args...)
+}
+
+// -----------------------------------------------------------------------
+// The Checker interface.
+
+// The Checker interface must be provided by checkers used with
+// the Assert and Check verification methods.
+type Checker interface {
+ Info() *CheckerInfo
+ Check(params []interface{}, names []string) (result bool, error string)
+}
+
+// See the Checker interface.
+type CheckerInfo struct {
+ Name string
+ Params []string
+}
+
+func (info *CheckerInfo) Info() *CheckerInfo {
+ return info
+}
+
+// -----------------------------------------------------------------------
+// Not checker logic inverter.
+
+// The Not checker inverts the logic of the provided checker. The
+// resulting checker will succeed where the original one failed, and
+// vice-versa.
+//
+// For example:
+//
+// c.Assert(a, Not(Equals), b)
+//
+func Not(checker Checker) Checker {
+ return &notChecker{checker}
+}
+
+type notChecker struct {
+ sub Checker
+}
+
+func (checker *notChecker) Info() *CheckerInfo {
+ info := *checker.sub.Info()
+ info.Name = "Not(" + info.Name + ")"
+ return &info
+}
+
+func (checker *notChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ result, error = checker.sub.Check(params, names)
+ result = !result
+ return
+}
+
+// -----------------------------------------------------------------------
+// IsNil checker.
+
+type isNilChecker struct {
+ *CheckerInfo
+}
+
+// The IsNil checker tests whether the obtained value is nil.
+//
+// For example:
+//
+// c.Assert(err, IsNil)
+//
+var IsNil Checker = &isNilChecker{
+ &CheckerInfo{Name: "IsNil", Params: []string{"value"}},
+}
+
+func (checker *isNilChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ return isNil(params[0]), ""
+}
+
+func isNil(obtained interface{}) (result bool) {
+ if obtained == nil {
+ result = true
+ } else {
+ switch v := reflect.ValueOf(obtained); v.Kind() {
+ case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ return v.IsNil()
+ }
+ }
+ return
+}
+
+// -----------------------------------------------------------------------
+// NotNil checker. Alias for Not(IsNil), since it's so common.
+
+type notNilChecker struct {
+ *CheckerInfo
+}
+
+// The NotNil checker verifies that the obtained value is not nil.
+//
+// For example:
+//
+// c.Assert(iface, NotNil)
+//
+// This is an alias for Not(IsNil), made available since it's a
+// fairly common check.
+//
+var NotNil Checker = &notNilChecker{
+ &CheckerInfo{Name: "NotNil", Params: []string{"value"}},
+}
+
+func (checker *notNilChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ return !isNil(params[0]), ""
+}
+
+// -----------------------------------------------------------------------
+// Equals checker.
+
+type equalsChecker struct {
+ *CheckerInfo
+}
+
+// The Equals checker verifies that the obtained value is equal to
+// the expected value, according to usual Go semantics for ==.
+//
+// For example:
+//
+// c.Assert(value, Equals, 42)
+//
+var Equals Checker = &equalsChecker{
+ &CheckerInfo{Name: "Equals", Params: []string{"obtained", "expected"}},
+}
+
+func (checker *equalsChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ defer func() {
+ if v := recover(); v != nil {
+ result = false
+ error = fmt.Sprint(v)
+ }
+ }()
+ return params[0] == params[1], ""
+}
+
+// -----------------------------------------------------------------------
+// DeepEquals checker.
+
+type deepEqualsChecker struct {
+ *CheckerInfo
+}
+
+// The DeepEquals checker verifies that the obtained value is deep-equal to
+// the expected value. The check will work correctly even when facing
+// slices, interfaces, and values of different types (which always fail
+// the test).
+//
+// For example:
+//
+// c.Assert(value, DeepEquals, 42)
+// c.Assert(array, DeepEquals, []string{"hi", "there"})
+//
+var DeepEquals Checker = &deepEqualsChecker{
+ &CheckerInfo{Name: "DeepEquals", Params: []string{"obtained", "expected"}},
+}
+
+func (checker *deepEqualsChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ return reflect.DeepEqual(params[0], params[1]), ""
+}
+
+// -----------------------------------------------------------------------
+// HasLen checker.
+
+type hasLenChecker struct {
+ *CheckerInfo
+}
+
+// The HasLen checker verifies that the obtained value has the
+// provided length. In many cases this is superior to using Equals
+// in conjuction with the len function because in case the check
+// fails the value itself will be printed, instead of its length,
+// providing more details for figuring the problem.
+//
+// For example:
+//
+// c.Assert(list, HasLen, 5)
+//
+var HasLen Checker = &hasLenChecker{
+ &CheckerInfo{Name: "HasLen", Params: []string{"obtained", "n"}},
+}
+
+func (checker *hasLenChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ n, ok := params[1].(int)
+ if !ok {
+ return false, "n must be an int"
+ }
+ value := reflect.ValueOf(params[0])
+ switch value.Kind() {
+ case reflect.Map, reflect.Array, reflect.Slice, reflect.Chan, reflect.String:
+ default:
+ return false, "obtained value type has no length"
+ }
+ return value.Len() == n, ""
+}
+
+// -----------------------------------------------------------------------
+// ErrorMatches checker.
+
+type errorMatchesChecker struct {
+ *CheckerInfo
+}
+
+// The ErrorMatches checker verifies that the error value
+// is non nil and matches the regular expression provided.
+//
+// For example:
+//
+// c.Assert(err, ErrorMatches, "perm.*denied")
+//
+var ErrorMatches Checker = errorMatchesChecker{
+ &CheckerInfo{Name: "ErrorMatches", Params: []string{"value", "regex"}},
+}
+
+func (checker errorMatchesChecker) Check(params []interface{}, names []string) (result bool, errStr string) {
+ if params[0] == nil {
+ return false, "Error value is nil"
+ }
+ err, ok := params[0].(error)
+ if !ok {
+ return false, "Value is not an error"
+ }
+ params[0] = err.Error()
+ names[0] = "error"
+ return matches(params[0], params[1])
+}
+
+// -----------------------------------------------------------------------
+// Matches checker.
+
+type matchesChecker struct {
+ *CheckerInfo
+}
+
+// The Matches checker verifies that the string provided as the obtained
+// value (or the string resulting from obtained.String()) matches the
+// regular expression provided.
+//
+// For example:
+//
+// c.Assert(err, Matches, "perm.*denied")
+//
+var Matches Checker = &matchesChecker{
+ &CheckerInfo{Name: "Matches", Params: []string{"value", "regex"}},
+}
+
+func (checker *matchesChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ return matches(params[0], params[1])
+}
+
+func matches(value, regex interface{}) (result bool, error string) {
+ reStr, ok := regex.(string)
+ if !ok {
+ return false, "Regex must be a string"
+ }
+ valueStr, valueIsStr := value.(string)
+ if !valueIsStr {
+ if valueWithStr, valueHasStr := value.(fmt.Stringer); valueHasStr {
+ valueStr, valueIsStr = valueWithStr.String(), true
+ }
+ }
+ if valueIsStr {
+ matches, err := regexp.MatchString("^"+reStr+"$", valueStr)
+ if err != nil {
+ return false, "Can't compile regex: " + err.Error()
+ }
+ return matches, ""
+ }
+ return false, "Obtained value is not a string and has no .String()"
+}
+
+// -----------------------------------------------------------------------
+// Panics checker.
+
+type panicsChecker struct {
+ *CheckerInfo
+}
+
+// The Panics checker verifies that calling the provided zero-argument
+// function will cause a panic which is deep-equal to the provided value.
+//
+// For example:
+//
+// c.Assert(func() { f(1, 2) }, Panics, &SomeErrorType{"BOOM"}).
+//
+//
+var Panics Checker = &panicsChecker{
+ &CheckerInfo{Name: "Panics", Params: []string{"function", "expected"}},
+}
+
+func (checker *panicsChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ f := reflect.ValueOf(params[0])
+ if f.Kind() != reflect.Func || f.Type().NumIn() != 0 {
+ return false, "Function must take zero arguments"
+ }
+ defer func() {
+ // If the function has not panicked, then don't do the check.
+ if error != "" {
+ return
+ }
+ params[0] = recover()
+ names[0] = "panic"
+ result = reflect.DeepEqual(params[0], params[1])
+ }()
+ f.Call(nil)
+ return false, "Function has not panicked"
+}
+
+type panicMatchesChecker struct {
+ *CheckerInfo
+}
+
+// The PanicMatches checker verifies that calling the provided zero-argument
+// function will cause a panic with an error value matching
+// the regular expression provided.
+//
+// For example:
+//
+// c.Assert(func() { f(1, 2) }, PanicMatches, `open.*: no such file or directory`).
+//
+//
+var PanicMatches Checker = &panicMatchesChecker{
+ &CheckerInfo{Name: "PanicMatches", Params: []string{"function", "expected"}},
+}
+
+func (checker *panicMatchesChecker) Check(params []interface{}, names []string) (result bool, errmsg string) {
+ f := reflect.ValueOf(params[0])
+ if f.Kind() != reflect.Func || f.Type().NumIn() != 0 {
+ return false, "Function must take zero arguments"
+ }
+ defer func() {
+ // If the function has not panicked, then don't do the check.
+ if errmsg != "" {
+ return
+ }
+ obtained := recover()
+ names[0] = "panic"
+ if e, ok := obtained.(error); ok {
+ params[0] = e.Error()
+ } else if _, ok := obtained.(string); ok {
+ params[0] = obtained
+ } else {
+ errmsg = "Panic value is not a string or an error"
+ return
+ }
+ result, errmsg = matches(params[0], params[1])
+ }()
+ f.Call(nil)
+ return false, "Function has not panicked"
+}
+
+// -----------------------------------------------------------------------
+// FitsTypeOf checker.
+
+type fitsTypeChecker struct {
+ *CheckerInfo
+}
+
+// The FitsTypeOf checker verifies that the obtained value is
+// assignable to a variable with the same type as the provided
+// sample value.
+//
+// For example:
+//
+// c.Assert(value, FitsTypeOf, int64(0))
+// c.Assert(value, FitsTypeOf, os.Error(nil))
+//
+var FitsTypeOf Checker = &fitsTypeChecker{
+ &CheckerInfo{Name: "FitsTypeOf", Params: []string{"obtained", "sample"}},
+}
+
+func (checker *fitsTypeChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ obtained := reflect.ValueOf(params[0])
+ sample := reflect.ValueOf(params[1])
+ if !obtained.IsValid() {
+ return false, ""
+ }
+ if !sample.IsValid() {
+ return false, "Invalid sample value"
+ }
+ return obtained.Type().AssignableTo(sample.Type()), ""
+}
+
+// -----------------------------------------------------------------------
+// Implements checker.
+
+type implementsChecker struct {
+ *CheckerInfo
+}
+
+// The Implements checker verifies that the obtained value
+// implements the interface specified via a pointer to an interface
+// variable.
+//
+// For example:
+//
+// var e os.Error
+// c.Assert(err, Implements, &e)
+//
+var Implements Checker = &implementsChecker{
+ &CheckerInfo{Name: "Implements", Params: []string{"obtained", "ifaceptr"}},
+}
+
+func (checker *implementsChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ obtained := reflect.ValueOf(params[0])
+ ifaceptr := reflect.ValueOf(params[1])
+ if !obtained.IsValid() {
+ return false, ""
+ }
+ if !ifaceptr.IsValid() || ifaceptr.Kind() != reflect.Ptr || ifaceptr.Elem().Kind() != reflect.Interface {
+ return false, "ifaceptr should be a pointer to an interface variable"
+ }
+ return obtained.Type().Implements(ifaceptr.Elem().Type()), ""
+}
diff --git a/vendor/github.com/go-check/check/helpers.go b/vendor/github.com/go-check/check/helpers.go
new file mode 100644
index 0000000..58a733b
--- /dev/null
+++ b/vendor/github.com/go-check/check/helpers.go
@@ -0,0 +1,231 @@
+package check
+
+import (
+ "fmt"
+ "strings"
+ "time"
+)
+
+// TestName returns the current test name in the form "SuiteName.TestName"
+func (c *C) TestName() string {
+ return c.testName
+}
+
+// -----------------------------------------------------------------------
+// Basic succeeding/failing logic.
+
+// Failed returns whether the currently running test has already failed.
+func (c *C) Failed() bool {
+ return c.status() == failedSt
+}
+
+// Fail marks the currently running test as failed.
+//
+// Something ought to have been previously logged so the developer can tell
+// what went wrong. The higher level helper functions will fail the test
+// and do the logging properly.
+func (c *C) Fail() {
+ c.setStatus(failedSt)
+}
+
+// FailNow marks the currently running test as failed and stops running it.
+// Something ought to have been previously logged so the developer can tell
+// what went wrong. The higher level helper functions will fail the test
+// and do the logging properly.
+func (c *C) FailNow() {
+ c.Fail()
+ c.stopNow()
+}
+
+// Succeed marks the currently running test as succeeded, undoing any
+// previous failures.
+func (c *C) Succeed() {
+ c.setStatus(succeededSt)
+}
+
+// SucceedNow marks the currently running test as succeeded, undoing any
+// previous failures, and stops running the test.
+func (c *C) SucceedNow() {
+ c.Succeed()
+ c.stopNow()
+}
+
+// ExpectFailure informs that the running test is knowingly broken for
+// the provided reason. If the test does not fail, an error will be reported
+// to raise attention to this fact. This method is useful to temporarily
+// disable tests which cover well known problems until a better time to
+// fix the problem is found, without forgetting about the fact that a
+// failure still exists.
+func (c *C) ExpectFailure(reason string) {
+ if reason == "" {
+ panic("Missing reason why the test is expected to fail")
+ }
+ c.mustFail = true
+ c.reason = reason
+}
+
+// Skip skips the running test for the provided reason. If run from within
+// SetUpTest, the individual test being set up will be skipped, and if run
+// from within SetUpSuite, the whole suite is skipped.
+func (c *C) Skip(reason string) {
+ if reason == "" {
+ panic("Missing reason why the test is being skipped")
+ }
+ c.reason = reason
+ c.setStatus(skippedSt)
+ c.stopNow()
+}
+
+// -----------------------------------------------------------------------
+// Basic logging.
+
+// GetTestLog returns the current test error output.
+func (c *C) GetTestLog() string {
+ return c.logb.String()
+}
+
+// Log logs some information into the test error output.
+// The provided arguments are assembled together into a string with fmt.Sprint.
+func (c *C) Log(args ...interface{}) {
+ c.log(args...)
+}
+
+// Log logs some information into the test error output.
+// The provided arguments are assembled together into a string with fmt.Sprintf.
+func (c *C) Logf(format string, args ...interface{}) {
+ c.logf(format, args...)
+}
+
+// Output enables *C to be used as a logger in functions that require only
+// the minimum interface of *log.Logger.
+func (c *C) Output(calldepth int, s string) error {
+ d := time.Now().Sub(c.startTime)
+ msec := d / time.Millisecond
+ sec := d / time.Second
+ min := d / time.Minute
+
+ c.Logf("[LOG] %d:%02d.%03d %s", min, sec%60, msec%1000, s)
+ return nil
+}
+
+// Error logs an error into the test error output and marks the test as failed.
+// The provided arguments are assembled together into a string with fmt.Sprint.
+func (c *C) Error(args ...interface{}) {
+ c.logCaller(1)
+ c.logString(fmt.Sprint("Error: ", fmt.Sprint(args...)))
+ c.logNewLine()
+ c.Fail()
+}
+
+// Errorf logs an error into the test error output and marks the test as failed.
+// The provided arguments are assembled together into a string with fmt.Sprintf.
+func (c *C) Errorf(format string, args ...interface{}) {
+ c.logCaller(1)
+ c.logString(fmt.Sprintf("Error: "+format, args...))
+ c.logNewLine()
+ c.Fail()
+}
+
+// Fatal logs an error into the test error output, marks the test as failed, and
+// stops the test execution. The provided arguments are assembled together into
+// a string with fmt.Sprint.
+func (c *C) Fatal(args ...interface{}) {
+ c.logCaller(1)
+ c.logString(fmt.Sprint("Error: ", fmt.Sprint(args...)))
+ c.logNewLine()
+ c.FailNow()
+}
+
+// Fatlaf logs an error into the test error output, marks the test as failed, and
+// stops the test execution. The provided arguments are assembled together into
+// a string with fmt.Sprintf.
+func (c *C) Fatalf(format string, args ...interface{}) {
+ c.logCaller(1)
+ c.logString(fmt.Sprint("Error: ", fmt.Sprintf(format, args...)))
+ c.logNewLine()
+ c.FailNow()
+}
+
+// -----------------------------------------------------------------------
+// Generic checks and assertions based on checkers.
+
+// Check verifies if the first value matches the expected value according
+// to the provided checker. If they do not match, an error is logged, the
+// test is marked as failed, and the test execution continues.
+//
+// Some checkers may not need the expected argument (e.g. IsNil).
+//
+// Extra arguments provided to the function are logged next to the reported
+// problem when the matching fails.
+func (c *C) Check(obtained interface{}, checker Checker, args ...interface{}) bool {
+ return c.internalCheck("Check", obtained, checker, args...)
+}
+
+// Assert ensures that the first value matches the expected value according
+// to the provided checker. If they do not match, an error is logged, the
+// test is marked as failed, and the test execution stops.
+//
+// Some checkers may not need the expected argument (e.g. IsNil).
+//
+// Extra arguments provided to the function are logged next to the reported
+// problem when the matching fails.
+func (c *C) Assert(obtained interface{}, checker Checker, args ...interface{}) {
+ if !c.internalCheck("Assert", obtained, checker, args...) {
+ c.stopNow()
+ }
+}
+
+func (c *C) internalCheck(funcName string, obtained interface{}, checker Checker, args ...interface{}) bool {
+ if checker == nil {
+ c.logCaller(2)
+ c.logString(fmt.Sprintf("%s(obtained, nil!?, ...):", funcName))
+ c.logString("Oops.. you've provided a nil checker!")
+ c.logNewLine()
+ c.Fail()
+ return false
+ }
+
+ // If the last argument is a bug info, extract it out.
+ var comment CommentInterface
+ if len(args) > 0 {
+ if c, ok := args[len(args)-1].(CommentInterface); ok {
+ comment = c
+ args = args[:len(args)-1]
+ }
+ }
+
+ params := append([]interface{}{obtained}, args...)
+ info := checker.Info()
+
+ if len(params) != len(info.Params) {
+ names := append([]string{info.Params[0], info.Name}, info.Params[1:]...)
+ c.logCaller(2)
+ c.logString(fmt.Sprintf("%s(%s):", funcName, strings.Join(names, ", ")))
+ c.logString(fmt.Sprintf("Wrong number of parameters for %s: want %d, got %d", info.Name, len(names), len(params)+1))
+ c.logNewLine()
+ c.Fail()
+ return false
+ }
+
+ // Copy since it may be mutated by Check.
+ names := append([]string{}, info.Params...)
+
+ // Do the actual check.
+ result, error := checker.Check(params, names)
+ if !result || error != "" {
+ c.logCaller(2)
+ for i := 0; i != len(params); i++ {
+ c.logValue(names[i], params[i])
+ }
+ if comment != nil {
+ c.logString(comment.CheckCommentString())
+ }
+ if error != "" {
+ c.logString(error)
+ }
+ c.logNewLine()
+ c.Fail()
+ return false
+ }
+ return true
+}
diff --git a/vendor/github.com/go-check/check/printer.go b/vendor/github.com/go-check/check/printer.go
new file mode 100644
index 0000000..e0f7557
--- /dev/null
+++ b/vendor/github.com/go-check/check/printer.go
@@ -0,0 +1,168 @@
+package check
+
+import (
+ "bytes"
+ "go/ast"
+ "go/parser"
+ "go/printer"
+ "go/token"
+ "os"
+)
+
+func indent(s, with string) (r string) {
+ eol := true
+ for i := 0; i != len(s); i++ {
+ c := s[i]
+ switch {
+ case eol && c == '\n' || c == '\r':
+ case c == '\n' || c == '\r':
+ eol = true
+ case eol:
+ eol = false
+ s = s[:i] + with + s[i:]
+ i += len(with)
+ }
+ }
+ return s
+}
+
+func printLine(filename string, line int) (string, error) {
+ fset := token.NewFileSet()
+ file, err := os.Open(filename)
+ if err != nil {
+ return "", err
+ }
+ fnode, err := parser.ParseFile(fset, filename, file, parser.ParseComments)
+ if err != nil {
+ return "", err
+ }
+ config := &printer.Config{Mode: printer.UseSpaces, Tabwidth: 4}
+ lp := &linePrinter{fset: fset, fnode: fnode, line: line, config: config}
+ ast.Walk(lp, fnode)
+ result := lp.output.Bytes()
+ // Comments leave \n at the end.
+ n := len(result)
+ for n > 0 && result[n-1] == '\n' {
+ n--
+ }
+ return string(result[:n]), nil
+}
+
+type linePrinter struct {
+ config *printer.Config
+ fset *token.FileSet
+ fnode *ast.File
+ line int
+ output bytes.Buffer
+ stmt ast.Stmt
+}
+
+func (lp *linePrinter) emit() bool {
+ if lp.stmt != nil {
+ lp.trim(lp.stmt)
+ lp.printWithComments(lp.stmt)
+ lp.stmt = nil
+ return true
+ }
+ return false
+}
+
+func (lp *linePrinter) printWithComments(n ast.Node) {
+ nfirst := lp.fset.Position(n.Pos()).Line
+ nlast := lp.fset.Position(n.End()).Line
+ for _, g := range lp.fnode.Comments {
+ cfirst := lp.fset.Position(g.Pos()).Line
+ clast := lp.fset.Position(g.End()).Line
+ if clast == nfirst-1 && lp.fset.Position(n.Pos()).Column == lp.fset.Position(g.Pos()).Column {
+ for _, c := range g.List {
+ lp.output.WriteString(c.Text)
+ lp.output.WriteByte('\n')
+ }
+ }
+ if cfirst >= nfirst && cfirst <= nlast && n.End() <= g.List[0].Slash {
+ // The printer will not include the comment if it starts past
+ // the node itself. Trick it into printing by overlapping the
+ // slash with the end of the statement.
+ g.List[0].Slash = n.End() - 1
+ }
+ }
+ node := &printer.CommentedNode{n, lp.fnode.Comments}
+ lp.config.Fprint(&lp.output, lp.fset, node)
+}
+
+func (lp *linePrinter) Visit(n ast.Node) (w ast.Visitor) {
+ if n == nil {
+ if lp.output.Len() == 0 {
+ lp.emit()
+ }
+ return nil
+ }
+ first := lp.fset.Position(n.Pos()).Line
+ last := lp.fset.Position(n.End()).Line
+ if first <= lp.line && last >= lp.line {
+ // Print the innermost statement containing the line.
+ if stmt, ok := n.(ast.Stmt); ok {
+ if _, ok := n.(*ast.BlockStmt); !ok {
+ lp.stmt = stmt
+ }
+ }
+ if first == lp.line && lp.emit() {
+ return nil
+ }
+ return lp
+ }
+ return nil
+}
+
+func (lp *linePrinter) trim(n ast.Node) bool {
+ stmt, ok := n.(ast.Stmt)
+ if !ok {
+ return true
+ }
+ line := lp.fset.Position(n.Pos()).Line
+ if line != lp.line {
+ return false
+ }
+ switch stmt := stmt.(type) {
+ case *ast.IfStmt:
+ stmt.Body = lp.trimBlock(stmt.Body)
+ case *ast.SwitchStmt:
+ stmt.Body = lp.trimBlock(stmt.Body)
+ case *ast.TypeSwitchStmt:
+ stmt.Body = lp.trimBlock(stmt.Body)
+ case *ast.CaseClause:
+ stmt.Body = lp.trimList(stmt.Body)
+ case *ast.CommClause:
+ stmt.Body = lp.trimList(stmt.Body)
+ case *ast.BlockStmt:
+ stmt.List = lp.trimList(stmt.List)
+ }
+ return true
+}
+
+func (lp *linePrinter) trimBlock(stmt *ast.BlockStmt) *ast.BlockStmt {
+ if !lp.trim(stmt) {
+ return lp.emptyBlock(stmt)
+ }
+ stmt.Rbrace = stmt.Lbrace
+ return stmt
+}
+
+func (lp *linePrinter) trimList(stmts []ast.Stmt) []ast.Stmt {
+ for i := 0; i != len(stmts); i++ {
+ if !lp.trim(stmts[i]) {
+ stmts[i] = lp.emptyStmt(stmts[i])
+ break
+ }
+ }
+ return stmts
+}
+
+func (lp *linePrinter) emptyStmt(n ast.Node) *ast.ExprStmt {
+ return &ast.ExprStmt{&ast.Ellipsis{n.Pos(), nil}}
+}
+
+func (lp *linePrinter) emptyBlock(n ast.Node) *ast.BlockStmt {
+ p := n.Pos()
+ return &ast.BlockStmt{p, []ast.Stmt{lp.emptyStmt(n)}, p}
+}
diff --git a/vendor/github.com/go-check/check/reporter.go b/vendor/github.com/go-check/check/reporter.go
new file mode 100644
index 0000000..fb04f76
--- /dev/null
+++ b/vendor/github.com/go-check/check/reporter.go
@@ -0,0 +1,88 @@
+package check
+
+import (
+ "fmt"
+ "io"
+ "sync"
+)
+
+// -----------------------------------------------------------------------
+// Output writer manages atomic output writing according to settings.
+
+type outputWriter struct {
+ m sync.Mutex
+ writer io.Writer
+ wroteCallProblemLast bool
+ Stream bool
+ Verbose bool
+}
+
+func newOutputWriter(writer io.Writer, stream, verbose bool) *outputWriter {
+ return &outputWriter{writer: writer, Stream: stream, Verbose: verbose}
+}
+
+func (ow *outputWriter) Write(content []byte) (n int, err error) {
+ ow.m.Lock()
+ n, err = ow.writer.Write(content)
+ ow.m.Unlock()
+ return
+}
+
+func (ow *outputWriter) WriteCallStarted(label string, c *C) {
+ if ow.Stream {
+ header := renderCallHeader(label, c, "", "\n")
+ ow.m.Lock()
+ ow.writer.Write([]byte(header))
+ ow.m.Unlock()
+ }
+}
+
+func (ow *outputWriter) WriteCallProblem(label string, c *C) {
+ var prefix string
+ if !ow.Stream {
+ prefix = "\n-----------------------------------" +
+ "-----------------------------------\n"
+ }
+ header := renderCallHeader(label, c, prefix, "\n\n")
+ ow.m.Lock()
+ ow.wroteCallProblemLast = true
+ ow.writer.Write([]byte(header))
+ if !ow.Stream {
+ c.logb.WriteTo(ow.writer)
+ }
+ ow.m.Unlock()
+}
+
+func (ow *outputWriter) WriteCallSuccess(label string, c *C) {
+ if ow.Stream || (ow.Verbose && c.kind == testKd) {
+ // TODO Use a buffer here.
+ var suffix string
+ if c.reason != "" {
+ suffix = " (" + c.reason + ")"
+ }
+ if c.status() == succeededSt {
+ suffix += "\t" + c.timerString()
+ }
+ suffix += "\n"
+ if ow.Stream {
+ suffix += "\n"
+ }
+ header := renderCallHeader(label, c, "", suffix)
+ ow.m.Lock()
+ // Resist temptation of using line as prefix above due to race.
+ if !ow.Stream && ow.wroteCallProblemLast {
+ header = "\n-----------------------------------" +
+ "-----------------------------------\n" +
+ header
+ }
+ ow.wroteCallProblemLast = false
+ ow.writer.Write([]byte(header))
+ ow.m.Unlock()
+ }
+}
+
+func renderCallHeader(label string, c *C, prefix, suffix string) string {
+ pc := c.method.PC()
+ return fmt.Sprintf("%s%s: %s: %s%s", prefix, label, niceFuncPath(pc),
+ niceFuncName(pc), suffix)
+}
diff --git a/vendor/github.com/go-check/check/run.go b/vendor/github.com/go-check/check/run.go
new file mode 100644
index 0000000..f721196
--- /dev/null
+++ b/vendor/github.com/go-check/check/run.go
@@ -0,0 +1,183 @@
+package check
+
+import (
+ "bufio"
+ "flag"
+ "fmt"
+ "os"
+ "testing"
+ "time"
+)
+
+// -----------------------------------------------------------------------
+// Test suite registry.
+
+var allSuites []interface{}
+
+// Suite registers the given value as a test suite to be run. Any methods
+// starting with the Test prefix in the given value will be considered as
+// a test method.
+func Suite(suite interface{}) interface{} {
+ allSuites = append(allSuites, suite)
+ return suite
+}
+
+// -----------------------------------------------------------------------
+// Public running interface.
+
+var (
+ oldFilterFlag = flag.String("gocheck.f", "", "Regular expression selecting which tests and/or suites to run")
+ oldVerboseFlag = flag.Bool("gocheck.v", false, "Verbose mode")
+ oldStreamFlag = flag.Bool("gocheck.vv", false, "Super verbose mode (disables output caching)")
+ oldBenchFlag = flag.Bool("gocheck.b", false, "Run benchmarks")
+ oldBenchTime = flag.Duration("gocheck.btime", 1*time.Second, "approximate run time for each benchmark")
+ oldListFlag = flag.Bool("gocheck.list", false, "List the names of all tests that will be run")
+ oldWorkFlag = flag.Bool("gocheck.work", false, "Display and do not remove the test working directory")
+
+ newFilterFlag = flag.String("check.f", "", "Regular expression selecting which tests and/or suites to run")
+ newVerboseFlag = flag.Bool("check.v", false, "Verbose mode")
+ newStreamFlag = flag.Bool("check.vv", false, "Super verbose mode (disables output caching)")
+ newBenchFlag = flag.Bool("check.b", false, "Run benchmarks")
+ newBenchTime = flag.Duration("check.btime", 1*time.Second, "approximate run time for each benchmark")
+ newBenchMem = flag.Bool("check.bmem", false, "Report memory benchmarks")
+ newListFlag = flag.Bool("check.list", false, "List the names of all tests that will be run")
+ newWorkFlag = flag.Bool("check.work", false, "Display and do not remove the test working directory")
+ checkTimeout = flag.String("check.timeout", "", "Panic if test runs longer than specified duration")
+)
+
+// TestingT runs all test suites registered with the Suite function,
+// printing results to stdout, and reporting any failures back to
+// the "testing" package.
+func TestingT(testingT *testing.T) {
+ benchTime := *newBenchTime
+ if benchTime == 1*time.Second {
+ benchTime = *oldBenchTime
+ }
+ conf := &RunConf{
+ Filter: *oldFilterFlag + *newFilterFlag,
+ Verbose: *oldVerboseFlag || *newVerboseFlag,
+ Stream: *oldStreamFlag || *newStreamFlag,
+ Benchmark: *oldBenchFlag || *newBenchFlag,
+ BenchmarkTime: benchTime,
+ BenchmarkMem: *newBenchMem,
+ KeepWorkDir: *oldWorkFlag || *newWorkFlag,
+ }
+ if *checkTimeout != "" {
+ timeout, err := time.ParseDuration(*checkTimeout)
+ if err != nil {
+ testingT.Fatalf("error parsing specified timeout flag: %v", err)
+ }
+ conf.CheckTimeout = timeout
+ }
+ if *oldListFlag || *newListFlag {
+ w := bufio.NewWriter(os.Stdout)
+ for _, name := range ListAll(conf) {
+ fmt.Fprintln(w, name)
+ }
+ w.Flush()
+ return
+ }
+ result := RunAll(conf)
+ println(result.String())
+ if !result.Passed() {
+ testingT.Fail()
+ }
+}
+
+// RunAll runs all test suites registered with the Suite function, using the
+// provided run configuration.
+func RunAll(runConf *RunConf) *Result {
+ result := Result{}
+ for _, suite := range allSuites {
+ result.Add(Run(suite, runConf))
+ }
+ return &result
+}
+
+// Run runs the provided test suite using the provided run configuration.
+func Run(suite interface{}, runConf *RunConf) *Result {
+ runner := newSuiteRunner(suite, runConf)
+ return runner.run()
+}
+
+// ListAll returns the names of all the test functions registered with the
+// Suite function that will be run with the provided run configuration.
+func ListAll(runConf *RunConf) []string {
+ var names []string
+ for _, suite := range allSuites {
+ names = append(names, List(suite, runConf)...)
+ }
+ return names
+}
+
+// List returns the names of the test functions in the given
+// suite that will be run with the provided run configuration.
+func List(suite interface{}, runConf *RunConf) []string {
+ var names []string
+ runner := newSuiteRunner(suite, runConf)
+ for _, t := range runner.tests {
+ names = append(names, t.String())
+ }
+ return names
+}
+
+// -----------------------------------------------------------------------
+// Result methods.
+
+func (r *Result) Add(other *Result) {
+ r.Succeeded += other.Succeeded
+ r.Skipped += other.Skipped
+ r.Failed += other.Failed
+ r.Panicked += other.Panicked
+ r.FixturePanicked += other.FixturePanicked
+ r.ExpectedFailures += other.ExpectedFailures
+ r.Missed += other.Missed
+ if r.WorkDir != "" && other.WorkDir != "" {
+ r.WorkDir += ":" + other.WorkDir
+ } else if other.WorkDir != "" {
+ r.WorkDir = other.WorkDir
+ }
+}
+
+func (r *Result) Passed() bool {
+ return (r.Failed == 0 && r.Panicked == 0 &&
+ r.FixturePanicked == 0 && r.Missed == 0 &&
+ r.RunError == nil)
+}
+
+func (r *Result) String() string {
+ if r.RunError != nil {
+ return "ERROR: " + r.RunError.Error()
+ }
+
+ var value string
+ if r.Failed == 0 && r.Panicked == 0 && r.FixturePanicked == 0 &&
+ r.Missed == 0 {
+ value = "OK: "
+ } else {
+ value = "OOPS: "
+ }
+ value += fmt.Sprintf("%d passed", r.Succeeded)
+ if r.Skipped != 0 {
+ value += fmt.Sprintf(", %d skipped", r.Skipped)
+ }
+ if r.ExpectedFailures != 0 {
+ value += fmt.Sprintf(", %d expected failures", r.ExpectedFailures)
+ }
+ if r.Failed != 0 {
+ value += fmt.Sprintf(", %d FAILED", r.Failed)
+ }
+ if r.Panicked != 0 {
+ value += fmt.Sprintf(", %d PANICKED", r.Panicked)
+ }
+ if r.FixturePanicked != 0 {
+ value += fmt.Sprintf(", %d FIXTURE-PANICKED", r.FixturePanicked)
+ }
+ if r.Missed != 0 {
+ value += fmt.Sprintf(", %d MISSED", r.Missed)
+ }
+ if r.WorkDir != "" {
+ value += "\nWORK=" + r.WorkDir
+ }
+ return value
+}
diff --git a/vendor/github.com/go-ini/ini/LICENSE b/vendor/github.com/go-ini/ini/LICENSE
new file mode 100644
index 0000000..37ec93a
--- /dev/null
+++ b/vendor/github.com/go-ini/ini/LICENSE
@@ -0,0 +1,191 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and
+distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright
+owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities
+that control, are controlled by, or are under common control with that entity.
+For the purposes of this definition, "control" means (i) the power, direct or
+indirect, to cause the direction or management of such entity, whether by
+contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
+outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising
+permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including
+but not limited to software source code, documentation source, and configuration
+files.
+
+"Object" form shall mean any form resulting from mechanical transformation or
+translation of a Source form, including but not limited to compiled object code,
+generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made
+available under the License, as indicated by a copyright notice that is included
+in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that
+is based on (or derived from) the Work and for which the editorial revisions,
+annotations, elaborations, or other modifications represent, as a whole, an
+original work of authorship. For the purposes of this License, Derivative Works
+shall not include works that remain separable from, or merely link (or bind by
+name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version
+of the Work and any modifications or additions to that Work or Derivative Works
+thereof, that is intentionally submitted to Licensor for inclusion in the Work
+by the copyright owner or by an individual or Legal Entity authorized to submit
+on behalf of the copyright owner. For the purposes of this definition,
+"submitted" means any form of electronic, verbal, or written communication sent
+to the Licensor or its representatives, including but not limited to
+communication on electronic mailing lists, source code control systems, and
+issue tracking systems that are managed by, or on behalf of, the Licensor for
+the purpose of discussing and improving the Work, but excluding communication
+that is conspicuously marked or otherwise designated in writing by the copyright
+owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
+of whom a Contribution has been received by Licensor and subsequently
+incorporated within the Work.
+
+2. Grant of Copyright License.
+
+Subject to the terms and conditions of this License, each Contributor hereby
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+irrevocable copyright license to reproduce, prepare Derivative Works of,
+publicly display, publicly perform, sublicense, and distribute the Work and such
+Derivative Works in Source or Object form.
+
+3. Grant of Patent License.
+
+Subject to the terms and conditions of this License, each Contributor hereby
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+irrevocable (except as stated in this section) patent license to make, have
+made, use, offer to sell, sell, import, and otherwise transfer the Work, where
+such license applies only to those patent claims licensable by such Contributor
+that are necessarily infringed by their Contribution(s) alone or by combination
+of their Contribution(s) with the Work to which such Contribution(s) was
+submitted. If You institute patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Work or a
+Contribution incorporated within the Work constitutes direct or contributory
+patent infringement, then any patent licenses granted to You under this License
+for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution.
+
+You may reproduce and distribute copies of the Work or Derivative Works thereof
+in any medium, with or without modifications, and in Source or Object form,
+provided that You meet the following conditions:
+
+You must give any other recipients of the Work or Derivative Works a copy of
+this License; and
+You must cause any modified files to carry prominent notices stating that You
+changed the files; and
+You must retain, in the Source form of any Derivative Works that You distribute,
+all copyright, patent, trademark, and attribution notices from the Source form
+of the Work, excluding those notices that do not pertain to any part of the
+Derivative Works; and
+If the Work includes a "NOTICE" text file as part of its distribution, then any
+Derivative Works that You distribute must include a readable copy of the
+attribution notices contained within such NOTICE file, excluding those notices
+that do not pertain to any part of the Derivative Works, in at least one of the
+following places: within a NOTICE text file distributed as part of the
+Derivative Works; within the Source form or documentation, if provided along
+with the Derivative Works; or, within a display generated by the Derivative
+Works, if and wherever such third-party notices normally appear. The contents of
+the NOTICE file are for informational purposes only and do not modify the
+License. You may add Your own attribution notices within Derivative Works that
+You distribute, alongside or as an addendum to the NOTICE text from the Work,
+provided that such additional attribution notices cannot be construed as
+modifying the License.
+You may add Your own copyright statement to Your modifications and may provide
+additional or different license terms and conditions for use, reproduction, or
+distribution of Your modifications, or for any such Derivative Works as a whole,
+provided Your use, reproduction, and distribution of the Work otherwise complies
+with the conditions stated in this License.
+
+5. Submission of Contributions.
+
+Unless You explicitly state otherwise, any Contribution intentionally submitted
+for inclusion in the Work by You to the Licensor shall be under the terms and
+conditions of this License, without any additional terms or conditions.
+Notwithstanding the above, nothing herein shall supersede or modify the terms of
+any separate license agreement you may have executed with Licensor regarding
+such Contributions.
+
+6. Trademarks.
+
+This License does not grant permission to use the trade names, trademarks,
+service marks, or product names of the Licensor, except as required for
+reasonable and customary use in describing the origin of the Work and
+reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty.
+
+Unless required by applicable law or agreed to in writing, Licensor provides the
+Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
+including, without limitation, any warranties or conditions of TITLE,
+NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
+solely responsible for determining the appropriateness of using or
+redistributing the Work and assume any risks associated with Your exercise of
+permissions under this License.
+
+8. Limitation of Liability.
+
+In no event and under no legal theory, whether in tort (including negligence),
+contract, or otherwise, unless required by applicable law (such as deliberate
+and grossly negligent acts) or agreed to in writing, shall any Contributor be
+liable to You for damages, including any direct, indirect, special, incidental,
+or consequential damages of any character arising as a result of this License or
+out of the use or inability to use the Work (including but not limited to
+damages for loss of goodwill, work stoppage, computer failure or malfunction, or
+any and all other commercial damages or losses), even if such Contributor has
+been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability.
+
+While redistributing the Work or Derivative Works thereof, You may choose to
+offer, and charge a fee for, acceptance of support, warranty, indemnity, or
+other liability obligations and/or rights consistent with this License. However,
+in accepting such obligations, You may act only on Your own behalf and on Your
+sole responsibility, not on behalf of any other Contributor, and only if You
+agree to indemnify, defend, and hold each Contributor harmless for any liability
+incurred by, or claims asserted against, such Contributor by reason of your
+accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work
+
+To apply the Apache License to your work, attach the following boilerplate
+notice, with the fields enclosed by brackets "[]" replaced with your own
+identifying information. (Don't include the brackets!) The text should be
+enclosed in the appropriate comment syntax for the file format. We also
+recommend that a file or class name and description of purpose be included on
+the same "printed page" as the copyright notice for easier identification within
+third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/go-ini/ini/README.md b/vendor/github.com/go-ini/ini/README.md
new file mode 100644
index 0000000..1272038
--- /dev/null
+++ b/vendor/github.com/go-ini/ini/README.md
@@ -0,0 +1,560 @@
+ini [![Build Status](https://drone.io/github.com/go-ini/ini/status.png)](https://drone.io/github.com/go-ini/ini/latest) [![](http://gocover.io/_badge/github.com/go-ini/ini)](http://gocover.io/github.com/go-ini/ini)
+===
+
+![](https://avatars0.githubusercontent.com/u/10216035?v=3&s=200)
+
+Package ini provides INI file read and write functionality in Go.
+
+[简体中文](README_ZH.md)
+
+## Feature
+
+- Load multiple data sources(`[]byte` or file) with overwrites.
+- Read with recursion values.
+- Read with parent-child sections.
+- Read with auto-increment key names.
+- Read with multiple-line values.
+- Read with tons of helper methods.
+- Read and convert values to Go types.
+- Read and **WRITE** comments of sections and keys.
+- Manipulate sections, keys and comments with ease.
+- Keep sections and keys in order as you parse and save.
+
+## Installation
+
+ go get gopkg.in/ini.v1
+
+## Getting Started
+
+### Loading from data sources
+
+A **Data Source** is either raw data in type `[]byte` or a file name with type `string` and you can load **as many as** data sources you want. Passing other types will simply return an error.
+
+```go
+cfg, err := ini.Load([]byte("raw data"), "filename")
+```
+
+Or start with an empty object:
+
+```go
+cfg := ini.Empty()
+```
+
+When you cannot decide how many data sources to load at the beginning, you still able to **Append()** them later.
+
+```go
+err := cfg.Append("other file", []byte("other raw data"))
+```
+
+### Working with sections
+
+To get a section, you would need to:
+
+```go
+section, err := cfg.GetSection("section name")
+```
+
+For a shortcut for default section, just give an empty string as name:
+
+```go
+section, err := cfg.GetSection("")
+```
+
+When you're pretty sure the section exists, following code could make your life easier:
+
+```go
+section := cfg.Section("")
+```
+
+What happens when the section somehow does not exist? Don't panic, it automatically creates and returns a new section to you.
+
+To create a new section:
+
+```go
+err := cfg.NewSection("new section")
+```
+
+To get a list of sections or section names:
+
+```go
+sections := cfg.Sections()
+names := cfg.SectionStrings()
+```
+
+### Working with keys
+
+To get a key under a section:
+
+```go
+key, err := cfg.Section("").GetKey("key name")
+```
+
+Same rule applies to key operations:
+
+```go
+key := cfg.Section("").Key("key name")
+```
+
+To create a new key:
+
+```go
+err := cfg.Section("").NewKey("name", "value")
+```
+
+To get a list of keys or key names:
+
+```go
+keys := cfg.Section("").Keys()
+names := cfg.Section("").KeyStrings()
+```
+
+To get a clone hash of keys and corresponding values:
+
+```go
+hash := cfg.GetSection("").KeysHash()
+```
+
+### Working with values
+
+To get a string value:
+
+```go
+val := cfg.Section("").Key("key name").String()
+```
+
+To validate key value on the fly:
+
+```go
+val := cfg.Section("").Key("key name").Validate(func(in string) string {
+ if len(in) == 0 {
+ return "default"
+ }
+ return in
+})
+```
+
+To get value with types:
+
+```go
+// For boolean values:
+// true when value is: 1, t, T, TRUE, true, True, YES, yes, Yes, ON, on, On
+// false when value is: 0, f, F, FALSE, false, False, NO, no, No, OFF, off, Off
+v, err = cfg.Section("").Key("BOOL").Bool()
+v, err = cfg.Section("").Key("FLOAT64").Float64()
+v, err = cfg.Section("").Key("INT").Int()
+v, err = cfg.Section("").Key("INT64").Int64()
+v, err = cfg.Section("").Key("UINT").Uint()
+v, err = cfg.Section("").Key("UINT64").Uint64()
+v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339)
+v, err = cfg.Section("").Key("TIME").Time() // RFC3339
+
+v = cfg.Section("").Key("BOOL").MustBool()
+v = cfg.Section("").Key("FLOAT64").MustFloat64()
+v = cfg.Section("").Key("INT").MustInt()
+v = cfg.Section("").Key("INT64").MustInt64()
+v = cfg.Section("").Key("UINT").MustUint()
+v = cfg.Section("").Key("UINT64").MustUint64()
+v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339)
+v = cfg.Section("").Key("TIME").MustTime() // RFC3339
+
+// Methods start with Must also accept one argument for default value
+// when key not found or fail to parse value to given type.
+// Except method MustString, which you have to pass a default value.
+
+v = cfg.Section("").Key("String").MustString("default")
+v = cfg.Section("").Key("BOOL").MustBool(true)
+v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25)
+v = cfg.Section("").Key("INT").MustInt(10)
+v = cfg.Section("").Key("INT64").MustInt64(99)
+v = cfg.Section("").Key("UINT").MustUint(3)
+v = cfg.Section("").Key("UINT64").MustUint64(6)
+v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now())
+v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339
+```
+
+What if my value is three-line long?
+
+```ini
+[advance]
+ADDRESS = """404 road,
+NotFound, State, 5000
+Earth"""
+```
+
+Not a problem!
+
+```go
+cfg.Section("advance").Key("ADDRESS").String()
+
+/* --- start ---
+404 road,
+NotFound, State, 5000
+Earth
+------ end --- */
+```
+
+That's cool, how about continuation lines?
+
+```ini
+[advance]
+two_lines = how about \
+ continuation lines?
+lots_of_lines = 1 \
+ 2 \
+ 3 \
+ 4
+```
+
+Piece of cake!
+
+```go
+cfg.Section("advance").Key("two_lines").String() // how about continuation lines?
+cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4
+```
+
+Note that single quotes around values will be stripped:
+
+```ini
+foo = "some value" // foo: some value
+bar = 'some value' // bar: some value
+```
+
+That's all? Hmm, no.
+
+#### Helper methods of working with values
+
+To get value with given candidates:
+
+```go
+v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"})
+v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75})
+v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30})
+v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30})
+v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9})
+v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9})
+v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3})
+v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339
+```
+
+Default value will be presented if value of key is not in candidates you given, and default value does not need be one of candidates.
+
+To validate value in a given range:
+
+```go
+vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2)
+vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20)
+vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20)
+vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9)
+vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9)
+vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime)
+vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339
+```
+
+To auto-split value into slice:
+
+```go
+vals = cfg.Section("").Key("STRINGS").Strings(",")
+vals = cfg.Section("").Key("FLOAT64S").Float64s(",")
+vals = cfg.Section("").Key("INTS").Ints(",")
+vals = cfg.Section("").Key("INT64S").Int64s(",")
+vals = cfg.Section("").Key("UINTS").Uints(",")
+vals = cfg.Section("").Key("UINT64S").Uint64s(",")
+vals = cfg.Section("").Key("TIMES").Times(",")
+```
+
+### Save your configuration
+
+Finally, it's time to save your configuration to somewhere.
+
+A typical way to save configuration is writing it to a file:
+
+```go
+// ...
+err = cfg.SaveTo("my.ini")
+err = cfg.SaveToIndent("my.ini", "\t")
+```
+
+Another way to save is writing to a `io.Writer` interface:
+
+```go
+// ...
+cfg.WriteTo(writer)
+cfg.WriteToIndent(writer, "\t")
+```
+
+## Advanced Usage
+
+### Recursive Values
+
+For all value of keys, there is a special syntax `%(<name>)s`, where `<name>` is the key name in same section or default section, and `%(<name>)s` will be replaced by corresponding value(empty string if key not found). You can use this syntax at most 99 level of recursions.
+
+```ini
+NAME = ini
+
+[author]
+NAME = Unknwon
+GITHUB = https://github.com/%(NAME)s
+
+[package]
+FULL_NAME = github.com/go-ini/%(NAME)s
+```
+
+```go
+cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon
+cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini
+```
+
+### Parent-child Sections
+
+You can use `.` in section name to indicate parent-child relationship between two or more sections. If the key not found in the child section, library will try again on its parent section until there is no parent section.
+
+```ini
+NAME = ini
+VERSION = v1
+IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s
+
+[package]
+CLONE_URL = https://%(IMPORT_PATH)s
+
+[package.sub]
+```
+
+```go
+cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1
+```
+
+### Auto-increment Key Names
+
+If key name is `-` in data source, then it would be seen as special syntax for auto-increment key name start from 1, and every section is independent on counter.
+
+```ini
+[features]
+-: Support read/write comments of keys and sections
+-: Support auto-increment of key names
+-: Support load multiple files to overwrite key values
+```
+
+```go
+cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"}
+```
+
+### Map To Struct
+
+Want more objective way to play with INI? Cool.
+
+```ini
+Name = Unknwon
+age = 21
+Male = true
+Born = 1993-01-01T20:17:05Z
+
+[Note]
+Content = Hi is a good man!
+Cities = HangZhou, Boston
+```
+
+```go
+type Note struct {
+ Content string
+ Cities []string
+}
+
+type Person struct {
+ Name string
+ Age int `ini:"age"`
+ Male bool
+ Born time.Time
+ Note
+ Created time.Time `ini:"-"`
+}
+
+func main() {
+ cfg, err := ini.Load("path/to/ini")
+ // ...
+ p := new(Person)
+ err = cfg.MapTo(p)
+ // ...
+
+ // Things can be simpler.
+ err = ini.MapTo(p, "path/to/ini")
+ // ...
+
+ // Just map a section? Fine.
+ n := new(Note)
+ err = cfg.Section("Note").MapTo(n)
+ // ...
+}
+```
+
+Can I have default value for field? Absolutely.
+
+Assign it before you map to struct. It will keep the value as it is if the key is not presented or got wrong type.
+
+```go
+// ...
+p := &Person{
+ Name: "Joe",
+}
+// ...
+```
+
+It's really cool, but what's the point if you can't give me my file back from struct?
+
+### Reflect From Struct
+
+Why not?
+
+```go
+type Embeded struct {
+ Dates []time.Time `delim:"|"`
+ Places []string
+ None []int
+}
+
+type Author struct {
+ Name string `ini:"NAME"`
+ Male bool
+ Age int
+ GPA float64
+ NeverMind string `ini:"-"`
+ *Embeded
+}
+
+func main() {
+ a := &Author{"Unknwon", true, 21, 2.8, "",
+ &Embeded{
+ []time.Time{time.Now(), time.Now()},
+ []string{"HangZhou", "Boston"},
+ []int{},
+ }}
+ cfg := ini.Empty()
+ err = ini.ReflectFrom(cfg, a)
+ // ...
+}
+```
+
+So, what do I get?
+
+```ini
+NAME = Unknwon
+Male = true
+Age = 21
+GPA = 2.8
+
+[Embeded]
+Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00
+Places = HangZhou,Boston
+None =
+```
+
+#### Name Mapper
+
+To save your time and make your code cleaner, this library supports [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) between struct field and actual section and key name.
+
+There are 2 built-in name mappers:
+
+- `AllCapsUnderscore`: it converts to format `ALL_CAPS_UNDERSCORE` then match section or key.
+- `TitleUnderscore`: it converts to format `title_underscore` then match section or key.
+
+To use them:
+
+```go
+type Info struct {
+ PackageName string
+}
+
+func main() {
+ err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("packag_name=ini"))
+ // ...
+
+ cfg, err := ini.Load([]byte("PACKAGE_NAME=ini"))
+ // ...
+ info := new(Info)
+ cfg.NameMapper = ini.AllCapsUnderscore
+ err = cfg.MapTo(info)
+ // ...
+}
+```
+
+Same rules of name mapper apply to `ini.ReflectFromWithMapper` function.
+
+#### Other Notes On Map/Reflect
+
+Any embedded struct is treated as a section by default, and there is no automatic parent-child relations in map/reflect feature:
+
+```go
+type Child struct {
+ Age string
+}
+
+type Parent struct {
+ Name string
+ Child
+}
+
+type Config struct {
+ City string
+ Parent
+}
+```
+
+Example configuration:
+
+```ini
+City = Boston
+
+[Parent]
+Name = Unknwon
+
+[Child]
+Age = 21
+```
+
+What if, yes, I'm paranoid, I want embedded struct to be in the same section. Well, all roads lead to Rome.
+
+```go
+type Child struct {
+ Age string
+}
+
+type Parent struct {
+ Name string
+ Child `ini:"Parent"`
+}
+
+type Config struct {
+ City string
+ Parent
+}
+```
+
+Example configuration:
+
+```ini
+City = Boston
+
+[Parent]
+Name = Unknwon
+Age = 21
+```
+
+## Getting Help
+
+- [API Documentation](https://gowalker.org/gopkg.in/ini.v1)
+- [File An Issue](https://github.com/go-ini/ini/issues/new)
+
+## FAQs
+
+### What does `BlockMode` field do?
+
+By default, library lets you read and write values so we need a locker to make sure your data is safe. But in cases that you are very sure about only reading data through the library, you can set `cfg.BlockMode = false` to speed up read operations about **50-70%** faster.
+
+### Why another INI library?
+
+Many people are using my another INI library [goconfig](https://github.com/Unknwon/goconfig), so the reason for this one is I would like to make more Go style code. Also when you set `cfg.BlockMode = false`, this one is about **10-30%** faster.
+
+To make those changes I have to confirm API broken, so it's safer to keep it in another place and start using `gopkg.in` to version my package at this time.(PS: shorter import path)
+
+## License
+
+This project is under Apache v2 License. See the [LICENSE](LICENSE) file for the full license text.
diff --git a/vendor/github.com/go-ini/ini/README_ZH.md b/vendor/github.com/go-ini/ini/README_ZH.md
new file mode 100644
index 0000000..45e19ed
--- /dev/null
+++ b/vendor/github.com/go-ini/ini/README_ZH.md
@@ -0,0 +1,547 @@
+本包提供了 Go 语言中读写 INI 文件的功能。
+
+## 功能特性
+
+- 支持覆盖加载多个数据源(`[]byte` 或文件)
+- 支持递归读取键值
+- 支持读取父子分区
+- 支持读取自增键名
+- 支持读取多行的键值
+- 支持大量辅助方法
+- 支持在读取时直接转换为 Go 语言类型
+- 支持读取和 **写入** 分区和键的注释
+- 轻松操作分区、键值和注释
+- 在保存文件时分区和键值会保持原有的顺序
+
+## 下载安装
+
+ go get gopkg.in/ini.v1
+
+## 开始使用
+
+### 从数据源加载
+
+一个 **数据源** 可以是 `[]byte` 类型的原始数据,或 `string` 类型的文件路径。您可以加载 **任意多个** 数据源。如果您传递其它类型的数据源,则会直接返回错误。
+
+```go
+cfg, err := ini.Load([]byte("raw data"), "filename")
+```
+
+或者从一个空白的文件开始:
+
+```go
+cfg := ini.Empty()
+```
+
+当您在一开始无法决定需要加载哪些数据源时,仍可以使用 **Append()** 在需要的时候加载它们。
+
+```go
+err := cfg.Append("other file", []byte("other raw data"))
+```
+
+### 操作分区(Section)
+
+获取指定分区:
+
+```go
+section, err := cfg.GetSection("section name")
+```
+
+如果您想要获取默认分区,则可以用空字符串代替分区名:
+
+```go
+section, err := cfg.GetSection("")
+```
+
+当您非常确定某个分区是存在的,可以使用以下简便方法:
+
+```go
+section := cfg.Section("")
+```
+
+如果不小心判断错了,要获取的分区其实是不存在的,那会发生什么呢?没事的,它会自动创建并返回一个对应的分区对象给您。
+
+创建一个分区:
+
+```go
+err := cfg.NewSection("new section")
+```
+
+获取所有分区对象或名称:
+
+```go
+sections := cfg.Sections()
+names := cfg.SectionStrings()
+```
+
+### 操作键(Key)
+
+获取某个分区下的键:
+
+```go
+key, err := cfg.Section("").GetKey("key name")
+```
+
+和分区一样,您也可以直接获取键而忽略错误处理:
+
+```go
+key := cfg.Section("").Key("key name")
+```
+
+创建一个新的键:
+
+```go
+err := cfg.Section("").NewKey("name", "value")
+```
+
+获取分区下的所有键或键名:
+
+```go
+keys := cfg.Section("").Keys()
+names := cfg.Section("").KeyStrings()
+```
+
+获取分区下的所有键值对的克隆:
+
+```go
+hash := cfg.GetSection("").KeysHash()
+```
+
+### 操作键值(Value)
+
+获取一个类型为字符串(string)的值:
+
+```go
+val := cfg.Section("").Key("key name").String()
+```
+
+获取值的同时通过自定义函数进行处理验证:
+
+```go
+val := cfg.Section("").Key("key name").Validate(func(in string) string {
+ if len(in) == 0 {
+ return "default"
+ }
+ return in
+})
+```
+
+获取其它类型的值:
+
+```go
+// 布尔值的规则:
+// true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, ON, on, On
+// false 当值为:0, f, F, FALSE, false, False, NO, no, No, OFF, off, Off
+v, err = cfg.Section("").Key("BOOL").Bool()
+v, err = cfg.Section("").Key("FLOAT64").Float64()
+v, err = cfg.Section("").Key("INT").Int()
+v, err = cfg.Section("").Key("INT64").Int64()
+v, err = cfg.Section("").Key("UINT").Uint()
+v, err = cfg.Section("").Key("UINT64").Uint64()
+v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339)
+v, err = cfg.Section("").Key("TIME").Time() // RFC3339
+
+v = cfg.Section("").Key("BOOL").MustBool()
+v = cfg.Section("").Key("FLOAT64").MustFloat64()
+v = cfg.Section("").Key("INT").MustInt()
+v = cfg.Section("").Key("INT64").MustInt64()
+v = cfg.Section("").Key("UINT").MustUint()
+v = cfg.Section("").Key("UINT64").MustUint64()
+v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339)
+v = cfg.Section("").Key("TIME").MustTime() // RFC3339
+
+// 由 Must 开头的方法名允许接收一个相同类型的参数来作为默认值,
+// 当键不存在或者转换失败时,则会直接返回该默认值。
+// 但是,MustString 方法必须传递一个默认值。
+
+v = cfg.Seciont("").Key("String").MustString("default")
+v = cfg.Section("").Key("BOOL").MustBool(true)
+v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25)
+v = cfg.Section("").Key("INT").MustInt(10)
+v = cfg.Section("").Key("INT64").MustInt64(99)
+v = cfg.Section("").Key("UINT").MustUint(3)
+v = cfg.Section("").Key("UINT64").MustUint64(6)
+v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now())
+v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339
+```
+
+如果我的值有好多行怎么办?
+
+```ini
+[advance]
+ADDRESS = """404 road,
+NotFound, State, 5000
+Earth"""
+```
+
+嗯哼?小 case!
+
+```go
+cfg.Section("advance").Key("ADDRESS").String()
+
+/* --- start ---
+404 road,
+NotFound, State, 5000
+Earth
+------ end --- */
+```
+
+赞爆了!那要是我属于一行的内容写不下想要写到第二行怎么办?
+
+```ini
+[advance]
+two_lines = how about \
+ continuation lines?
+lots_of_lines = 1 \
+ 2 \
+ 3 \
+ 4
+```
+
+简直是小菜一碟!
+
+```go
+cfg.Section("advance").Key("two_lines").String() // how about continuation lines?
+cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4
+```
+
+需要注意的是,值两侧的单引号会被自动剔除:
+
+```ini
+foo = "some value" // foo: some value
+bar = 'some value' // bar: some value
+```
+
+这就是全部了?哈哈,当然不是。
+
+#### 操作键值的辅助方法
+
+获取键值时设定候选值:
+
+```go
+v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"})
+v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75})
+v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30})
+v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30})
+v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9})
+v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9})
+v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3})
+v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339
+```
+
+如果获取到的值不是候选值的任意一个,则会返回默认值,而默认值不需要是候选值中的一员。
+
+验证获取的值是否在指定范围内:
+
+```go
+vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2)
+vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20)
+vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20)
+vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9)
+vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9)
+vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime)
+vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339
+```
+
+自动分割键值为切片(slice):
+
+```go
+vals = cfg.Section("").Key("STRINGS").Strings(",")
+vals = cfg.Section("").Key("FLOAT64S").Float64s(",")
+vals = cfg.Section("").Key("INTS").Ints(",")
+vals = cfg.Section("").Key("INT64S").Int64s(",")
+vals = cfg.Section("").Key("UINTS").Uints(",")
+vals = cfg.Section("").Key("UINT64S").Uint64s(",")
+vals = cfg.Section("").Key("TIMES").Times(",")
+```
+
+### 保存配置
+
+终于到了这个时刻,是时候保存一下配置了。
+
+比较原始的做法是输出配置到某个文件:
+
+```go
+// ...
+err = cfg.SaveTo("my.ini")
+err = cfg.SaveToIndent("my.ini", "\t")
+```
+
+另一个比较高级的做法是写入到任何实现 `io.Writer` 接口的对象中:
+
+```go
+// ...
+cfg.WriteTo(writer)
+cfg.WriteToIndent(writer, "\t")
+```
+
+### 高级用法
+
+#### 递归读取键值
+
+在获取所有键值的过程中,特殊语法 `%(<name>)s` 会被应用,其中 `<name>` 可以是相同分区或者默认分区下的键名。字符串 `%(<name>)s` 会被相应的键值所替代,如果指定的键不存在,则会用空字符串替代。您可以最多使用 99 层的递归嵌套。
+
+```ini
+NAME = ini
+
+[author]
+NAME = Unknwon
+GITHUB = https://github.com/%(NAME)s
+
+[package]
+FULL_NAME = github.com/go-ini/%(NAME)s
+```
+
+```go
+cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon
+cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini
+```
+
+#### 读取父子分区
+
+您可以在分区名称中使用 `.` 来表示两个或多个分区之间的父子关系。如果某个键在子分区中不存在,则会去它的父分区中再次寻找,直到没有父分区为止。
+
+```ini
+NAME = ini
+VERSION = v1
+IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s
+
+[package]
+CLONE_URL = https://%(IMPORT_PATH)s
+
+[package.sub]
+```
+
+```go
+cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1
+```
+
+#### 读取自增键名
+
+如果数据源中的键名为 `-`,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。
+
+```ini
+[features]
+-: Support read/write comments of keys and sections
+-: Support auto-increment of key names
+-: Support load multiple files to overwrite key values
+```
+
+```go
+cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"}
+```
+
+### 映射到结构
+
+想要使用更加面向对象的方式玩转 INI 吗?好主意。
+
+```ini
+Name = Unknwon
+age = 21
+Male = true
+Born = 1993-01-01T20:17:05Z
+
+[Note]
+Content = Hi is a good man!
+Cities = HangZhou, Boston
+```
+
+```go
+type Note struct {
+ Content string
+ Cities []string
+}
+
+type Person struct {
+ Name string
+ Age int `ini:"age"`
+ Male bool
+ Born time.Time
+ Note
+ Created time.Time `ini:"-"`
+}
+
+func main() {
+ cfg, err := ini.Load("path/to/ini")
+ // ...
+ p := new(Person)
+ err = cfg.MapTo(p)
+ // ...
+
+ // 一切竟可以如此的简单。
+ err = ini.MapTo(p, "path/to/ini")
+ // ...
+
+ // 嗯哼?只需要映射一个分区吗?
+ n := new(Note)
+ err = cfg.Section("Note").MapTo(n)
+ // ...
+}
+```
+
+结构的字段怎么设置默认值呢?很简单,只要在映射之前对指定字段进行赋值就可以了。如果键未找到或者类型错误,该值不会发生改变。
+
+```go
+// ...
+p := &Person{
+ Name: "Joe",
+}
+// ...
+```
+
+这样玩 INI 真的好酷啊!然而,如果不能还给我原来的配置文件,有什么卵用?
+
+### 从结构反射
+
+可是,我有说不能吗?
+
+```go
+type Embeded struct {
+ Dates []time.Time `delim:"|"`
+ Places []string
+ None []int
+}
+
+type Author struct {
+ Name string `ini:"NAME"`
+ Male bool
+ Age int
+ GPA float64
+ NeverMind string `ini:"-"`
+ *Embeded
+}
+
+func main() {
+ a := &Author{"Unknwon", true, 21, 2.8, "",
+ &Embeded{
+ []time.Time{time.Now(), time.Now()},
+ []string{"HangZhou", "Boston"},
+ []int{},
+ }}
+ cfg := ini.Empty()
+ err = ini.ReflectFrom(cfg, a)
+ // ...
+}
+```
+
+瞧瞧,奇迹发生了。
+
+```ini
+NAME = Unknwon
+Male = true
+Age = 21
+GPA = 2.8
+
+[Embeded]
+Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00
+Places = HangZhou,Boston
+None =
+```
+
+#### 名称映射器(Name Mapper)
+
+为了节省您的时间并简化代码,本库支持类型为 [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) 的名称映射器,该映射器负责结构字段名与分区名和键名之间的映射。
+
+目前有 2 款内置的映射器:
+
+- `AllCapsUnderscore`:该映射器将字段名转换至格式 `ALL_CAPS_UNDERSCORE` 后再去匹配分区名和键名。
+- `TitleUnderscore`:该映射器将字段名转换至格式 `title_underscore` 后再去匹配分区名和键名。
+
+使用方法:
+
+```go
+type Info struct{
+ PackageName string
+}
+
+func main() {
+ err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("packag_name=ini"))
+ // ...
+
+ cfg, err := ini.Load([]byte("PACKAGE_NAME=ini"))
+ // ...
+ info := new(Info)
+ cfg.NameMapper = ini.AllCapsUnderscore
+ err = cfg.MapTo(info)
+ // ...
+}
+```
+
+使用函数 `ini.ReflectFromWithMapper` 时也可应用相同的规则。
+
+#### 映射/反射的其它说明
+
+任何嵌入的结构都会被默认认作一个不同的分区,并且不会自动产生所谓的父子分区关联:
+
+```go
+type Child struct {
+ Age string
+}
+
+type Parent struct {
+ Name string
+ Child
+}
+
+type Config struct {
+ City string
+ Parent
+}
+```
+
+示例配置文件:
+
+```ini
+City = Boston
+
+[Parent]
+Name = Unknwon
+
+[Child]
+Age = 21
+```
+
+很好,但是,我就是要嵌入结构也在同一个分区。好吧,你爹是李刚!
+
+```go
+type Child struct {
+ Age string
+}
+
+type Parent struct {
+ Name string
+ Child `ini:"Parent"`
+}
+
+type Config struct {
+ City string
+ Parent
+}
+```
+
+示例配置文件:
+
+```ini
+City = Boston
+
+[Parent]
+Name = Unknwon
+Age = 21
+```
+
+## 获取帮助
+
+- [API 文档](https://gowalker.org/gopkg.in/ini.v1)
+- [创建工单](https://github.com/go-ini/ini/issues/new)
+
+## 常见问题
+
+### 字段 `BlockMode` 是什么?
+
+默认情况下,本库会在您进行读写操作时采用锁机制来确保数据时间。但在某些情况下,您非常确定只进行读操作。此时,您可以通过设置 `cfg.BlockMode = false` 来将读操作提升大约 **50-70%** 的性能。
+
+### 为什么要写另一个 INI 解析库?
+
+许多人都在使用我的 [goconfig](https://github.com/Unknwon/goconfig) 来完成对 INI 文件的操作,但我希望使用更加 Go 风格的代码。并且当您设置 `cfg.BlockMode = false` 时,会有大约 **10-30%** 的性能提升。
+
+为了做出这些改变,我必须对 API 进行破坏,所以新开一个仓库是最安全的做法。除此之外,本库直接使用 `gopkg.in` 来进行版本化发布。(其实真相是导入路径更短了)
diff --git a/vendor/github.com/go-ini/ini/ini.go b/vendor/github.com/go-ini/ini/ini.go
new file mode 100644
index 0000000..1fee789
--- /dev/null
+++ b/vendor/github.com/go-ini/ini/ini.go
@@ -0,0 +1,1226 @@
+// Copyright 2014 Unknwon
+//
+// 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 ini provides INI file read and write functionality in Go.
+package ini
+
+import (
+ "bufio"
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "regexp"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+const (
+ DEFAULT_SECTION = "DEFAULT"
+ // Maximum allowed depth when recursively substituing variable names.
+ _DEPTH_VALUES = 99
+
+ _VERSION = "1.6.0"
+)
+
+func Version() string {
+ return _VERSION
+}
+
+var (
+ LineBreak = "\n"
+
+ // Variable regexp pattern: %(variable)s
+ varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`)
+
+ // Write spaces around "=" to look better.
+ PrettyFormat = true
+)
+
+func init() {
+ if runtime.GOOS == "windows" {
+ LineBreak = "\r\n"
+ }
+}
+
+func inSlice(str string, s []string) bool {
+ for _, v := range s {
+ if str == v {
+ return true
+ }
+ }
+ return false
+}
+
+// dataSource is a interface that returns file content.
+type dataSource interface {
+ ReadCloser() (io.ReadCloser, error)
+}
+
+type sourceFile struct {
+ name string
+}
+
+func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) {
+ return os.Open(s.name)
+}
+
+type bytesReadCloser struct {
+ reader io.Reader
+}
+
+func (rc *bytesReadCloser) Read(p []byte) (n int, err error) {
+ return rc.reader.Read(p)
+}
+
+func (rc *bytesReadCloser) Close() error {
+ return nil
+}
+
+type sourceData struct {
+ data []byte
+}
+
+func (s *sourceData) ReadCloser() (io.ReadCloser, error) {
+ return &bytesReadCloser{bytes.NewReader(s.data)}, nil
+}
+
+// ____ __.
+// | |/ _|____ ___.__.
+// | <_/ __ < | |
+// | | \ ___/\___ |
+// |____|__ \___ > ____|
+// \/ \/\/
+
+// Key represents a key under a section.
+type Key struct {
+ s *Section
+ Comment string
+ name string
+ value string
+ isAutoIncr bool
+}
+
+// Name returns name of key.
+func (k *Key) Name() string {
+ return k.name
+}
+
+// Value returns raw value of key for performance purpose.
+func (k *Key) Value() string {
+ return k.value
+}
+
+// String returns string representation of value.
+func (k *Key) String() string {
+ val := k.value
+ if strings.Index(val, "%") == -1 {
+ return val
+ }
+
+ for i := 0; i < _DEPTH_VALUES; i++ {
+ vr := varPattern.FindString(val)
+ if len(vr) == 0 {
+ break
+ }
+
+ // Take off leading '%(' and trailing ')s'.
+ noption := strings.TrimLeft(vr, "%(")
+ noption = strings.TrimRight(noption, ")s")
+
+ // Search in the same section.
+ nk, err := k.s.GetKey(noption)
+ if err != nil {
+ // Search again in default section.
+ nk, _ = k.s.f.Section("").GetKey(noption)
+ }
+
+ // Substitute by new value and take off leading '%(' and trailing ')s'.
+ val = strings.Replace(val, vr, nk.value, -1)
+ }
+ return val
+}
+
+// Validate accepts a validate function which can
+// return modifed result as key value.
+func (k *Key) Validate(fn func(string) string) string {
+ return fn(k.String())
+}
+
+// parseBool returns the boolean value represented by the string.
+//
+// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, ON, on, On,
+// 0, f, F, FALSE, false, False, NO, no, No, OFF, off, Off.
+// Any other value returns an error.
+func parseBool(str string) (value bool, err error) {
+ switch str {
+ case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "ON", "on", "On":
+ return true, nil
+ case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "OFF", "off", "Off":
+ return false, nil
+ }
+ return false, fmt.Errorf("parsing \"%s\": invalid syntax", str)
+}
+
+// Bool returns bool type value.
+func (k *Key) Bool() (bool, error) {
+ return parseBool(k.String())
+}
+
+// Float64 returns float64 type value.
+func (k *Key) Float64() (float64, error) {
+ return strconv.ParseFloat(k.String(), 64)
+}
+
+// Int returns int type value.
+func (k *Key) Int() (int, error) {
+ return strconv.Atoi(k.String())
+}
+
+// Int64 returns int64 type value.
+func (k *Key) Int64() (int64, error) {
+ return strconv.ParseInt(k.String(), 10, 64)
+}
+
+// Uint returns uint type valued.
+func (k *Key) Uint() (uint, error) {
+ u, e := strconv.ParseUint(k.String(), 10, 64)
+ return uint(u), e
+}
+
+// Uint64 returns uint64 type value.
+func (k *Key) Uint64() (uint64, error) {
+ return strconv.ParseUint(k.String(), 10, 64)
+}
+
+// Duration returns time.Duration type value.
+func (k *Key) Duration() (time.Duration, error) {
+ return time.ParseDuration(k.String())
+}
+
+// TimeFormat parses with given format and returns time.Time type value.
+func (k *Key) TimeFormat(format string) (time.Time, error) {
+ return time.Parse(format, k.String())
+}
+
+// Time parses with RFC3339 format and returns time.Time type value.
+func (k *Key) Time() (time.Time, error) {
+ return k.TimeFormat(time.RFC3339)
+}
+
+// MustString returns default value if key value is empty.
+func (k *Key) MustString(defaultVal string) string {
+ val := k.String()
+ if len(val) == 0 {
+ return defaultVal
+ }
+ return val
+}
+
+// MustBool always returns value without error,
+// it returns false if error occurs.
+func (k *Key) MustBool(defaultVal ...bool) bool {
+ val, err := k.Bool()
+ if len(defaultVal) > 0 && err != nil {
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustFloat64 always returns value without error,
+// it returns 0.0 if error occurs.
+func (k *Key) MustFloat64(defaultVal ...float64) float64 {
+ val, err := k.Float64()
+ if len(defaultVal) > 0 && err != nil {
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustInt always returns value without error,
+// it returns 0 if error occurs.
+func (k *Key) MustInt(defaultVal ...int) int {
+ val, err := k.Int()
+ if len(defaultVal) > 0 && err != nil {
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustInt64 always returns value without error,
+// it returns 0 if error occurs.
+func (k *Key) MustInt64(defaultVal ...int64) int64 {
+ val, err := k.Int64()
+ if len(defaultVal) > 0 && err != nil {
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustUint always returns value without error,
+// it returns 0 if error occurs.
+func (k *Key) MustUint(defaultVal ...uint) uint {
+ val, err := k.Uint()
+ if len(defaultVal) > 0 && err != nil {
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustUint64 always returns value without error,
+// it returns 0 if error occurs.
+func (k *Key) MustUint64(defaultVal ...uint64) uint64 {
+ val, err := k.Uint64()
+ if len(defaultVal) > 0 && err != nil {
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustDuration always returns value without error,
+// it returns zero value if error occurs.
+func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration {
+ val, err := k.Duration()
+ if len(defaultVal) > 0 && err != nil {
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustTimeFormat always parses with given format and returns value without error,
+// it returns zero value if error occurs.
+func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time {
+ val, err := k.TimeFormat(format)
+ if len(defaultVal) > 0 && err != nil {
+ return defaultVal[0]
+ }
+ return val
+}
+
+// MustTime always parses with RFC3339 format and returns value without error,
+// it returns zero value if error occurs.
+func (k *Key) MustTime(defaultVal ...time.Time) time.Time {
+ return k.MustTimeFormat(time.RFC3339, defaultVal...)
+}
+
+// In always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) In(defaultVal string, candidates []string) string {
+ val := k.String()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InFloat64 always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 {
+ val := k.MustFloat64()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InInt always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InInt(defaultVal int, candidates []int) int {
+ val := k.MustInt()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InInt64 always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 {
+ val := k.MustInt64()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InUint always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InUint(defaultVal uint, candidates []uint) uint {
+ val := k.MustUint()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InUint64 always returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 {
+ val := k.MustUint64()
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InTimeFormat always parses with given format and returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time {
+ val := k.MustTimeFormat(format)
+ for _, cand := range candidates {
+ if val == cand {
+ return val
+ }
+ }
+ return defaultVal
+}
+
+// InTime always parses with RFC3339 format and returns value without error,
+// it returns default value if error occurs or doesn't fit into candidates.
+func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time {
+ return k.InTimeFormat(time.RFC3339, defaultVal, candidates)
+}
+
+// RangeFloat64 checks if value is in given range inclusively,
+// and returns default value if it's not.
+func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 {
+ val := k.MustFloat64()
+ if val < min || val > max {
+ return defaultVal
+ }
+ return val
+}
+
+// RangeInt checks if value is in given range inclusively,
+// and returns default value if it's not.
+func (k *Key) RangeInt(defaultVal, min, max int) int {
+ val := k.MustInt()
+ if val < min || val > max {
+ return defaultVal
+ }
+ return val
+}
+
+// RangeInt64 checks if value is in given range inclusively,
+// and returns default value if it's not.
+func (k *Key) RangeInt64(defaultVal, min, max int64) int64 {
+ val := k.MustInt64()
+ if val < min || val > max {
+ return defaultVal
+ }
+ return val
+}
+
+// RangeTimeFormat checks if value with given format is in given range inclusively,
+// and returns default value if it's not.
+func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time {
+ val := k.MustTimeFormat(format)
+ if val.Unix() < min.Unix() || val.Unix() > max.Unix() {
+ return defaultVal
+ }
+ return val
+}
+
+// RangeTime checks if value with RFC3339 format is in given range inclusively,
+// and returns default value if it's not.
+func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time {
+ return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max)
+}
+
+// Strings returns list of string devide by given delimiter.
+func (k *Key) Strings(delim string) []string {
+ str := k.String()
+ if len(str) == 0 {
+ return []string{}
+ }
+
+ vals := strings.Split(str, delim)
+ for i := range vals {
+ vals[i] = strings.TrimSpace(vals[i])
+ }
+ return vals
+}
+
+// Float64s returns list of float64 devide by given delimiter.
+func (k *Key) Float64s(delim string) []float64 {
+ strs := k.Strings(delim)
+ vals := make([]float64, len(strs))
+ for i := range strs {
+ vals[i], _ = strconv.ParseFloat(strs[i], 64)
+ }
+ return vals
+}
+
+// Ints returns list of int devide by given delimiter.
+func (k *Key) Ints(delim string) []int {
+ strs := k.Strings(delim)
+ vals := make([]int, len(strs))
+ for i := range strs {
+ vals[i], _ = strconv.Atoi(strs[i])
+ }
+ return vals
+}
+
+// Int64s returns list of int64 devide by given delimiter.
+func (k *Key) Int64s(delim string) []int64 {
+ strs := k.Strings(delim)
+ vals := make([]int64, len(strs))
+ for i := range strs {
+ vals[i], _ = strconv.ParseInt(strs[i], 10, 64)
+ }
+ return vals
+}
+
+// Uints returns list of uint devide by given delimiter.
+func (k *Key) Uints(delim string) []uint {
+ strs := k.Strings(delim)
+ vals := make([]uint, len(strs))
+ for i := range strs {
+ u, _ := strconv.ParseUint(strs[i], 10, 64)
+ vals[i] = uint(u)
+ }
+ return vals
+}
+
+// Uint64s returns list of uint64 devide by given delimiter.
+func (k *Key) Uint64s(delim string) []uint64 {
+ strs := k.Strings(delim)
+ vals := make([]uint64, len(strs))
+ for i := range strs {
+ vals[i], _ = strconv.ParseUint(strs[i], 10, 64)
+ }
+ return vals
+}
+
+// TimesFormat parses with given format and returns list of time.Time devide by given delimiter.
+func (k *Key) TimesFormat(format, delim string) []time.Time {
+ strs := k.Strings(delim)
+ vals := make([]time.Time, len(strs))
+ for i := range strs {
+ vals[i], _ = time.Parse(format, strs[i])
+ }
+ return vals
+}
+
+// Times parses with RFC3339 format and returns list of time.Time devide by given delimiter.
+func (k *Key) Times(delim string) []time.Time {
+ return k.TimesFormat(time.RFC3339, delim)
+}
+
+// SetValue changes key value.
+func (k *Key) SetValue(v string) {
+ k.value = v
+}
+
+// _________ __ .__
+// / _____/ ____ _____/ |_|__| ____ ____
+// \_____ \_/ __ \_/ ___\ __\ |/ _ \ / \
+// / \ ___/\ \___| | | ( <_> ) | \
+// /_______ /\___ >\___ >__| |__|\____/|___| /
+// \/ \/ \/ \/
+
+// Section represents a config section.
+type Section struct {
+ f *File
+ Comment string
+ name string
+ keys map[string]*Key
+ keyList []string
+ keysHash map[string]string
+}
+
+func newSection(f *File, name string) *Section {
+ return &Section{f, "", name, make(map[string]*Key), make([]string, 0, 10), make(map[string]string)}
+}
+
+// Name returns name of Section.
+func (s *Section) Name() string {
+ return s.name
+}
+
+// NewKey creates a new key to given section.
+func (s *Section) NewKey(name, val string) (*Key, error) {
+ if len(name) == 0 {
+ return nil, errors.New("error creating new key: empty key name")
+ }
+
+ if s.f.BlockMode {
+ s.f.lock.Lock()
+ defer s.f.lock.Unlock()
+ }
+
+ if inSlice(name, s.keyList) {
+ s.keys[name].value = val
+ return s.keys[name], nil
+ }
+
+ s.keyList = append(s.keyList, name)
+ s.keys[name] = &Key{s, "", name, val, false}
+ s.keysHash[name] = val
+ return s.keys[name], nil
+}
+
+// GetKey returns key in section by given name.
+func (s *Section) GetKey(name string) (*Key, error) {
+ // FIXME: change to section level lock?
+ if s.f.BlockMode {
+ s.f.lock.RLock()
+ }
+ key := s.keys[name]
+ if s.f.BlockMode {
+ s.f.lock.RUnlock()
+ }
+
+ if key == nil {
+ // Check if it is a child-section.
+ sname := s.name
+ for {
+ if i := strings.LastIndex(sname, "."); i > -1 {
+ sname = sname[:i]
+ sec, err := s.f.GetSection(sname)
+ if err != nil {
+ continue
+ }
+ return sec.GetKey(name)
+ } else {
+ break
+ }
+ }
+ return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name)
+ }
+ return key, nil
+}
+
+// Key assumes named Key exists in section and returns a zero-value when not.
+func (s *Section) Key(name string) *Key {
+ key, err := s.GetKey(name)
+ if err != nil {
+ // It's OK here because the only possible error is empty key name,
+ // but if it's empty, this piece of code won't be executed.
+ key, _ = s.NewKey(name, "")
+ return key
+ }
+ return key
+}
+
+// Keys returns list of keys of section.
+func (s *Section) Keys() []*Key {
+ keys := make([]*Key, len(s.keyList))
+ for i := range s.keyList {
+ keys[i] = s.Key(s.keyList[i])
+ }
+ return keys
+}
+
+// KeyStrings returns list of key names of section.
+func (s *Section) KeyStrings() []string {
+ list := make([]string, len(s.keyList))
+ copy(list, s.keyList)
+ return list
+}
+
+// KeysHash returns keys hash consisting of names and values.
+func (s *Section) KeysHash() map[string]string {
+ if s.f.BlockMode {
+ s.f.lock.RLock()
+ defer s.f.lock.RUnlock()
+ }
+
+ hash := map[string]string{}
+ for key, value := range s.keysHash {
+ hash[key] = value
+ }
+ return hash
+}
+
+// DeleteKey deletes a key from section.
+func (s *Section) DeleteKey(name string) {
+ if s.f.BlockMode {
+ s.f.lock.Lock()
+ defer s.f.lock.Unlock()
+ }
+
+ for i, k := range s.keyList {
+ if k == name {
+ s.keyList = append(s.keyList[:i], s.keyList[i+1:]...)
+ delete(s.keys, name)
+ return
+ }
+ }
+}
+
+// ___________.__.__
+// \_ _____/|__| | ____
+// | __) | | | _/ __ \
+// | \ | | |_\ ___/
+// \___ / |__|____/\___ >
+// \/ \/
+
+// File represents a combination of a or more INI file(s) in memory.
+type File struct {
+ // Should make things safe, but sometimes doesn't matter.
+ BlockMode bool
+ // Make sure data is safe in multiple goroutines.
+ lock sync.RWMutex
+
+ // Allow combination of multiple data sources.
+ dataSources []dataSource
+ // Actual data is stored here.
+ sections map[string]*Section
+
+ // To keep data in order.
+ sectionList []string
+
+ NameMapper
+}
+
+// newFile initializes File object with given data sources.
+func newFile(dataSources []dataSource) *File {
+ return &File{
+ BlockMode: true,
+ dataSources: dataSources,
+ sections: make(map[string]*Section),
+ sectionList: make([]string, 0, 10),
+ }
+}
+
+func parseDataSource(source interface{}) (dataSource, error) {
+ switch s := source.(type) {
+ case string:
+ return sourceFile{s}, nil
+ case []byte:
+ return &sourceData{s}, nil
+ default:
+ return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s)
+ }
+}
+
+// Load loads and parses from INI data sources.
+// Arguments can be mixed of file name with string type, or raw data in []byte.
+func Load(source interface{}, others ...interface{}) (_ *File, err error) {
+ sources := make([]dataSource, len(others)+1)
+ sources[0], err = parseDataSource(source)
+ if err != nil {
+ return nil, err
+ }
+ for i := range others {
+ sources[i+1], err = parseDataSource(others[i])
+ if err != nil {
+ return nil, err
+ }
+ }
+ f := newFile(sources)
+ return f, f.Reload()
+}
+
+// Empty returns an empty file object.
+func Empty() *File {
+ // Ignore error here, we sure our data is good.
+ f, _ := Load([]byte(""))
+ return f
+}
+
+// NewSection creates a new section.
+func (f *File) NewSection(name string) (*Section, error) {
+ if len(name) == 0 {
+ return nil, errors.New("error creating new section: empty section name")
+ }
+
+ if f.BlockMode {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+ }
+
+ if inSlice(name, f.sectionList) {
+ return f.sections[name], nil
+ }
+
+ f.sectionList = append(f.sectionList, name)
+ f.sections[name] = newSection(f, name)
+ return f.sections[name], nil
+}
+
+// NewSections creates a list of sections.
+func (f *File) NewSections(names ...string) (err error) {
+ for _, name := range names {
+ if _, err = f.NewSection(name); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// GetSection returns section by given name.
+func (f *File) GetSection(name string) (*Section, error) {
+ if len(name) == 0 {
+ name = DEFAULT_SECTION
+ }
+
+ if f.BlockMode {
+ f.lock.RLock()
+ defer f.lock.RUnlock()
+ }
+
+ sec := f.sections[name]
+ if sec == nil {
+ return nil, fmt.Errorf("error when getting section: section '%s' not exists", name)
+ }
+ return sec, nil
+}
+
+// Section assumes named section exists and returns a zero-value when not.
+func (f *File) Section(name string) *Section {
+ sec, err := f.GetSection(name)
+ if err != nil {
+ // Note: It's OK here because the only possible error is empty section name,
+ // but if it's empty, this piece of code won't be executed.
+ sec, _ = f.NewSection(name)
+ return sec
+ }
+ return sec
+}
+
+// Section returns list of Section.
+func (f *File) Sections() []*Section {
+ sections := make([]*Section, len(f.sectionList))
+ for i := range f.sectionList {
+ sections[i] = f.Section(f.sectionList[i])
+ }
+ return sections
+}
+
+// SectionStrings returns list of section names.
+func (f *File) SectionStrings() []string {
+ list := make([]string, len(f.sectionList))
+ copy(list, f.sectionList)
+ return list
+}
+
+// DeleteSection deletes a section.
+func (f *File) DeleteSection(name string) {
+ if f.BlockMode {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+ }
+
+ if len(name) == 0 {
+ name = DEFAULT_SECTION
+ }
+
+ for i, s := range f.sectionList {
+ if s == name {
+ f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...)
+ delete(f.sections, name)
+ return
+ }
+ }
+}
+
+func cutComment(str string) string {
+ i := strings.Index(str, "#")
+ if i == -1 {
+ return str
+ }
+ return str[:i]
+}
+
+func checkMultipleLines(buf *bufio.Reader, line, val, valQuote string) (string, error) {
+ isEnd := false
+ for {
+ next, err := buf.ReadString('\n')
+ if err != nil {
+ if err != io.EOF {
+ return "", err
+ }
+ isEnd = true
+ }
+ pos := strings.LastIndex(next, valQuote)
+ if pos > -1 {
+ val += next[:pos]
+ break
+ }
+ val += next
+ if isEnd {
+ return "", fmt.Errorf("error parsing line: missing closing key quote from '%s' to '%s'", line, next)
+ }
+ }
+ return val, nil
+}
+
+func checkContinuationLines(buf *bufio.Reader, val string) (string, bool, error) {
+ isEnd := false
+ for {
+ valLen := len(val)
+ if valLen == 0 || val[valLen-1] != '\\' {
+ break
+ }
+ val = val[:valLen-1]
+
+ next, err := buf.ReadString('\n')
+ if err != nil {
+ if err != io.EOF {
+ return "", isEnd, err
+ }
+ isEnd = true
+ }
+
+ next = strings.TrimSpace(next)
+ if len(next) == 0 {
+ break
+ }
+ val += next
+ }
+ return val, isEnd, nil
+}
+
+// parse parses data through an io.Reader.
+func (f *File) parse(reader io.Reader) error {
+ buf := bufio.NewReader(reader)
+
+ // Handle BOM-UTF8.
+ // http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding
+ mask, err := buf.Peek(3)
+ if err == nil && len(mask) >= 3 && mask[0] == 239 && mask[1] == 187 && mask[2] == 191 {
+ buf.Read(mask)
+ }
+
+ count := 1
+ comments := ""
+ isEnd := false
+
+ section, err := f.NewSection(DEFAULT_SECTION)
+ if err != nil {
+ return err
+ }
+
+ for {
+ line, err := buf.ReadString('\n')
+ line = strings.TrimSpace(line)
+ length := len(line)
+
+ // Check error and ignore io.EOF just for a moment.
+ if err != nil {
+ if err != io.EOF {
+ return fmt.Errorf("error reading next line: %v", err)
+ }
+ // The last line of file could be an empty line.
+ if length == 0 {
+ break
+ }
+ isEnd = true
+ }
+
+ // Skip empty lines.
+ if length == 0 {
+ continue
+ }
+
+ switch {
+ case line[0] == '#' || line[0] == ';': // Comments.
+ if len(comments) == 0 {
+ comments = line
+ } else {
+ comments += LineBreak + line
+ }
+ continue
+ case line[0] == '[' && line[length-1] == ']': // New sction.
+ section, err = f.NewSection(strings.TrimSpace(line[1 : length-1]))
+ if err != nil {
+ return err
+ }
+
+ if len(comments) > 0 {
+ section.Comment = comments
+ comments = ""
+ }
+ // Reset counter.
+ count = 1
+ continue
+ }
+
+ // Other possibilities.
+ var (
+ i int
+ keyQuote string
+ kname string
+ valQuote string
+ val string
+ )
+
+ // Key name surrounded by quotes.
+ if line[0] == '"' {
+ if length > 6 && line[0:3] == `"""` {
+ keyQuote = `"""`
+ } else {
+ keyQuote = `"`
+ }
+ } else if line[0] == '`' {
+ keyQuote = "`"
+ }
+ if len(keyQuote) > 0 {
+ qLen := len(keyQuote)
+ pos := strings.Index(line[qLen:], keyQuote)
+ if pos == -1 {
+ return fmt.Errorf("error parsing line: missing closing key quote: %s", line)
+ }
+ pos = pos + qLen
+ i = strings.IndexAny(line[pos:], "=:")
+ if i < 0 {
+ return fmt.Errorf("error parsing line: key-value delimiter not found: %s", line)
+ } else if i == pos {
+ return fmt.Errorf("error parsing line: key is empty: %s", line)
+ }
+ i = i + pos
+ kname = line[qLen:pos] // Just keep spaces inside quotes.
+ } else {
+ i = strings.IndexAny(line, "=:")
+ if i < 0 {
+ return fmt.Errorf("error parsing line: key-value delimiter not found: %s", line)
+ } else if i == 0 {
+ return fmt.Errorf("error parsing line: key is empty: %s", line)
+ }
+ kname = strings.TrimSpace(line[0:i])
+ }
+
+ isAutoIncr := false
+ // Auto increment.
+ if kname == "-" {
+ isAutoIncr = true
+ kname = "#" + fmt.Sprint(count)
+ count++
+ }
+
+ lineRight := strings.TrimSpace(line[i+1:])
+ lineRightLength := len(lineRight)
+ firstChar := ""
+ if lineRightLength >= 2 {
+ firstChar = lineRight[0:1]
+ }
+ if firstChar == "`" {
+ valQuote = "`"
+ } else if firstChar == `"` {
+ if lineRightLength >= 3 && lineRight[0:3] == `"""` {
+ valQuote = `"""`
+ } else {
+ valQuote = `"`
+ }
+ } else if firstChar == `'` {
+ valQuote = `'`
+ }
+
+ if len(valQuote) > 0 {
+ qLen := len(valQuote)
+ pos := strings.LastIndex(lineRight[qLen:], valQuote)
+ // For multiple-line value check.
+ if pos == -1 {
+ if valQuote == `"` || valQuote == `'` {
+ return fmt.Errorf("error parsing line: single quote does not allow multiple-line value: %s", line)
+ }
+
+ val = lineRight[qLen:] + "\n"
+ val, err = checkMultipleLines(buf, line, val, valQuote)
+ if err != nil {
+ return err
+ }
+ } else {
+ val = lineRight[qLen : pos+qLen]
+ }
+ } else {
+ val = strings.TrimSpace(cutComment(lineRight))
+ val, isEnd, err = checkContinuationLines(buf, val)
+ if err != nil {
+ return err
+ }
+ }
+
+ k, err := section.NewKey(kname, val)
+ if err != nil {
+ return err
+ }
+ k.isAutoIncr = isAutoIncr
+ if len(comments) > 0 {
+ k.Comment = comments
+ comments = ""
+ }
+
+ if isEnd {
+ break
+ }
+ }
+ return nil
+}
+
+func (f *File) reload(s dataSource) error {
+ r, err := s.ReadCloser()
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+
+ return f.parse(r)
+}
+
+// Reload reloads and parses all data sources.
+func (f *File) Reload() (err error) {
+ for _, s := range f.dataSources {
+ if err = f.reload(s); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Append appends one or more data sources and reloads automatically.
+func (f *File) Append(source interface{}, others ...interface{}) error {
+ ds, err := parseDataSource(source)
+ if err != nil {
+ return err
+ }
+ f.dataSources = append(f.dataSources, ds)
+ for _, s := range others {
+ ds, err = parseDataSource(s)
+ if err != nil {
+ return err
+ }
+ f.dataSources = append(f.dataSources, ds)
+ }
+ return f.Reload()
+}
+
+// WriteToIndent writes file content into io.Writer with given value indention.
+func (f *File) WriteToIndent(w io.Writer, indent string) (n int64, err error) {
+ equalSign := "="
+ if PrettyFormat {
+ equalSign = " = "
+ }
+
+ // Use buffer to make sure target is safe until finish encoding.
+ buf := bytes.NewBuffer(nil)
+ for i, sname := range f.sectionList {
+ sec := f.Section(sname)
+ if len(sec.Comment) > 0 {
+ if sec.Comment[0] != '#' && sec.Comment[0] != ';' {
+ sec.Comment = "; " + sec.Comment
+ }
+ if _, err = buf.WriteString(sec.Comment + LineBreak); err != nil {
+ return 0, err
+ }
+ }
+
+ if i > 0 {
+ if _, err = buf.WriteString("[" + sname + "]" + LineBreak); err != nil {
+ return 0, err
+ }
+ } else {
+ // Write nothing if default section is empty.
+ if len(sec.keyList) == 0 {
+ continue
+ }
+ }
+
+ for _, kname := range sec.keyList {
+ key := sec.Key(kname)
+ if len(key.Comment) > 0 {
+ if len(indent) > 0 && sname != DEFAULT_SECTION {
+ buf.WriteString(indent)
+ }
+ if key.Comment[0] != '#' && key.Comment[0] != ';' {
+ key.Comment = "; " + key.Comment
+ }
+ if _, err = buf.WriteString(key.Comment + LineBreak); err != nil {
+ return 0, err
+ }
+ }
+
+ if len(indent) > 0 && sname != DEFAULT_SECTION {
+ buf.WriteString(indent)
+ }
+
+ switch {
+ case key.isAutoIncr:
+ kname = "-"
+ case strings.Contains(kname, "`") || strings.Contains(kname, `"`):
+ kname = `"""` + kname + `"""`
+ case strings.Contains(kname, `=`) || strings.Contains(kname, `:`):
+ kname = "`" + kname + "`"
+ }
+
+ val := key.value
+ // In case key value contains "\n", "`" or "\"".
+ if strings.Contains(val, "\n") || strings.Contains(val, "`") || strings.Contains(val, `"`) ||
+ strings.Contains(val, "#") {
+ val = `"""` + val + `"""`
+ }
+ if _, err = buf.WriteString(kname + equalSign + val + LineBreak); err != nil {
+ return 0, err
+ }
+ }
+
+ // Put a line between sections.
+ if _, err = buf.WriteString(LineBreak); err != nil {
+ return 0, err
+ }
+ }
+
+ return buf.WriteTo(w)
+}
+
+// WriteTo writes file content into io.Writer.
+func (f *File) WriteTo(w io.Writer) (int64, error) {
+ return f.WriteToIndent(w, "")
+}
+
+// SaveToIndent writes content to file system with given value indention.
+func (f *File) SaveToIndent(filename, indent string) error {
+ // Note: Because we are truncating with os.Create,
+ // so it's safer to save to a temporary file location and rename afte done.
+ tmpPath := filename + "." + strconv.Itoa(time.Now().Nanosecond()) + ".tmp"
+ defer os.Remove(tmpPath)
+
+ fw, err := os.Create(tmpPath)
+ if err != nil {
+ return err
+ }
+
+ if _, err = f.WriteToIndent(fw, indent); err != nil {
+ fw.Close()
+ return err
+ }
+ fw.Close()
+
+ // Remove old file and rename the new one.
+ os.Remove(filename)
+ return os.Rename(tmpPath, filename)
+}
+
+// SaveTo writes content to file system.
+func (f *File) SaveTo(filename string) error {
+ return f.SaveToIndent(filename, "")
+}
diff --git a/vendor/github.com/go-ini/ini/struct.go b/vendor/github.com/go-ini/ini/struct.go
new file mode 100644
index 0000000..c118437
--- /dev/null
+++ b/vendor/github.com/go-ini/ini/struct.go
@@ -0,0 +1,350 @@
+// Copyright 2014 Unknwon
+//
+// 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 ini
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "reflect"
+ "time"
+ "unicode"
+)
+
+// NameMapper represents a ini tag name mapper.
+type NameMapper func(string) string
+
+// Built-in name getters.
+var (
+ // AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE.
+ AllCapsUnderscore NameMapper = func(raw string) string {
+ newstr := make([]rune, 0, len(raw))
+ for i, chr := range raw {
+ if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
+ if i > 0 {
+ newstr = append(newstr, '_')
+ }
+ }
+ newstr = append(newstr, unicode.ToUpper(chr))
+ }
+ return string(newstr)
+ }
+ // TitleUnderscore converts to format title_underscore.
+ TitleUnderscore NameMapper = func(raw string) string {
+ newstr := make([]rune, 0, len(raw))
+ for i, chr := range raw {
+ if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
+ if i > 0 {
+ newstr = append(newstr, '_')
+ }
+ chr -= ('A' - 'a')
+ }
+ newstr = append(newstr, chr)
+ }
+ return string(newstr)
+ }
+)
+
+func (s *Section) parseFieldName(raw, actual string) string {
+ if len(actual) > 0 {
+ return actual
+ }
+ if s.f.NameMapper != nil {
+ return s.f.NameMapper(raw)
+ }
+ return raw
+}
+
+func parseDelim(actual string) string {
+ if len(actual) > 0 {
+ return actual
+ }
+ return ","
+}
+
+var reflectTime = reflect.TypeOf(time.Now()).Kind()
+
+// setWithProperType sets proper value to field based on its type,
+// but it does not return error for failing parsing,
+// because we want to use default value that is already assigned to strcut.
+func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error {
+ switch t.Kind() {
+ case reflect.String:
+ if len(key.String()) == 0 {
+ return nil
+ }
+ field.SetString(key.String())
+ case reflect.Bool:
+ boolVal, err := key.Bool()
+ if err != nil {
+ return nil
+ }
+ field.SetBool(boolVal)
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ durationVal, err := key.Duration()
+ if err == nil {
+ field.Set(reflect.ValueOf(durationVal))
+ return nil
+ }
+
+ intVal, err := key.Int64()
+ if err != nil {
+ return nil
+ }
+ field.SetInt(intVal)
+ // byte is an alias for uint8, so supporting uint8 breaks support for byte
+ case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ durationVal, err := key.Duration()
+ if err == nil {
+ field.Set(reflect.ValueOf(durationVal))
+ return nil
+ }
+
+ uintVal, err := key.Uint64()
+ if err != nil {
+ return nil
+ }
+ field.SetUint(uintVal)
+
+ case reflect.Float64:
+ floatVal, err := key.Float64()
+ if err != nil {
+ return nil
+ }
+ field.SetFloat(floatVal)
+ case reflectTime:
+ timeVal, err := key.Time()
+ if err != nil {
+ return nil
+ }
+ field.Set(reflect.ValueOf(timeVal))
+ case reflect.Slice:
+ vals := key.Strings(delim)
+ numVals := len(vals)
+ if numVals == 0 {
+ return nil
+ }
+
+ sliceOf := field.Type().Elem().Kind()
+
+ var times []time.Time
+ if sliceOf == reflectTime {
+ times = key.Times(delim)
+ }
+
+ slice := reflect.MakeSlice(field.Type(), numVals, numVals)
+ for i := 0; i < numVals; i++ {
+ switch sliceOf {
+ case reflectTime:
+ slice.Index(i).Set(reflect.ValueOf(times[i]))
+ default:
+ slice.Index(i).Set(reflect.ValueOf(vals[i]))
+ }
+ }
+ field.Set(slice)
+ default:
+ return fmt.Errorf("unsupported type '%s'", t)
+ }
+ return nil
+}
+
+func (s *Section) mapTo(val reflect.Value) error {
+ if val.Kind() == reflect.Ptr {
+ val = val.Elem()
+ }
+ typ := val.Type()
+
+ for i := 0; i < typ.NumField(); i++ {
+ field := val.Field(i)
+ tpField := typ.Field(i)
+
+ tag := tpField.Tag.Get("ini")
+ if tag == "-" {
+ continue
+ }
+
+ fieldName := s.parseFieldName(tpField.Name, tag)
+ if len(fieldName) == 0 || !field.CanSet() {
+ continue
+ }
+
+ isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous
+ isStruct := tpField.Type.Kind() == reflect.Struct
+ if isAnonymous {
+ field.Set(reflect.New(tpField.Type.Elem()))
+ }
+
+ if isAnonymous || isStruct {
+ if sec, err := s.f.GetSection(fieldName); err == nil {
+ if err = sec.mapTo(field); err != nil {
+ return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
+ }
+ continue
+ }
+ }
+
+ if key, err := s.GetKey(fieldName); err == nil {
+ if err = setWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil {
+ return fmt.Errorf("error mapping field(%s): %v", fieldName, err)
+ }
+ }
+ }
+ return nil
+}
+
+// MapTo maps section to given struct.
+func (s *Section) MapTo(v interface{}) error {
+ typ := reflect.TypeOf(v)
+ val := reflect.ValueOf(v)
+ if typ.Kind() == reflect.Ptr {
+ typ = typ.Elem()
+ val = val.Elem()
+ } else {
+ return errors.New("cannot map to non-pointer struct")
+ }
+
+ return s.mapTo(val)
+}
+
+// MapTo maps file to given struct.
+func (f *File) MapTo(v interface{}) error {
+ return f.Section("").MapTo(v)
+}
+
+// MapTo maps data sources to given struct with name mapper.
+func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error {
+ cfg, err := Load(source, others...)
+ if err != nil {
+ return err
+ }
+ cfg.NameMapper = mapper
+ return cfg.MapTo(v)
+}
+
+// MapTo maps data sources to given struct.
+func MapTo(v, source interface{}, others ...interface{}) error {
+ return MapToWithMapper(v, nil, source, others...)
+}
+
+// reflectWithProperType does the opposite thing with setWithProperType.
+func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error {
+ switch t.Kind() {
+ case reflect.String:
+ key.SetValue(field.String())
+ case reflect.Bool,
+ reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
+ reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
+ reflect.Float64,
+ reflectTime:
+ key.SetValue(fmt.Sprint(field))
+ case reflect.Slice:
+ vals := field.Slice(0, field.Len())
+ if field.Len() == 0 {
+ return nil
+ }
+
+ var buf bytes.Buffer
+ isTime := fmt.Sprint(field.Type()) == "[]time.Time"
+ for i := 0; i < field.Len(); i++ {
+ if isTime {
+ buf.WriteString(vals.Index(i).Interface().(time.Time).Format(time.RFC3339))
+ } else {
+ buf.WriteString(fmt.Sprint(vals.Index(i)))
+ }
+ buf.WriteString(delim)
+ }
+ key.SetValue(buf.String()[:buf.Len()-1])
+ default:
+ return fmt.Errorf("unsupported type '%s'", t)
+ }
+ return nil
+}
+
+func (s *Section) reflectFrom(val reflect.Value) error {
+ if val.Kind() == reflect.Ptr {
+ val = val.Elem()
+ }
+ typ := val.Type()
+
+ for i := 0; i < typ.NumField(); i++ {
+ field := val.Field(i)
+ tpField := typ.Field(i)
+
+ tag := tpField.Tag.Get("ini")
+ if tag == "-" {
+ continue
+ }
+
+ fieldName := s.parseFieldName(tpField.Name, tag)
+ if len(fieldName) == 0 || !field.CanSet() {
+ continue
+ }
+
+ if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) ||
+ (tpField.Type.Kind() == reflect.Struct) {
+ // Note: The only error here is section doesn't exist.
+ sec, err := s.f.GetSection(fieldName)
+ if err != nil {
+ // Note: fieldName can never be empty here, ignore error.
+ sec, _ = s.f.NewSection(fieldName)
+ }
+ if err = sec.reflectFrom(field); err != nil {
+ return fmt.Errorf("error reflecting field(%s): %v", fieldName, err)
+ }
+ continue
+ }
+
+ // Note: Same reason as secion.
+ key, err := s.GetKey(fieldName)
+ if err != nil {
+ key, _ = s.NewKey(fieldName, "")
+ }
+ if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil {
+ return fmt.Errorf("error reflecting field(%s): %v", fieldName, err)
+ }
+
+ }
+ return nil
+}
+
+// ReflectFrom reflects secion from given struct.
+func (s *Section) ReflectFrom(v interface{}) error {
+ typ := reflect.TypeOf(v)
+ val := reflect.ValueOf(v)
+ if typ.Kind() == reflect.Ptr {
+ typ = typ.Elem()
+ val = val.Elem()
+ } else {
+ return errors.New("cannot reflect from non-pointer struct")
+ }
+
+ return s.reflectFrom(val)
+}
+
+// ReflectFrom reflects file from given struct.
+func (f *File) ReflectFrom(v interface{}) error {
+ return f.Section("").ReflectFrom(v)
+}
+
+// ReflectFrom reflects data sources from given struct with name mapper.
+func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error {
+ cfg.NameMapper = mapper
+ return cfg.ReflectFrom(v)
+}
+
+// ReflectFrom reflects data sources from given struct.
+func ReflectFrom(cfg *File, v interface{}) error {
+ return ReflectFromWithMapper(cfg, v, nil)
+}
diff --git a/vendor/github.com/godbus/dbus/LICENSE b/vendor/github.com/godbus/dbus/LICENSE
new file mode 100644
index 0000000..670d88f
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/LICENSE
@@ -0,0 +1,25 @@
+Copyright (c) 2013, Georg Reinke (<guelfey at gmail dot com>), Google
+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
+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/godbus/dbus/README.markdown b/vendor/github.com/godbus/dbus/README.markdown
new file mode 100644
index 0000000..0a6e7e5
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/README.markdown
@@ -0,0 +1,41 @@
+dbus
+----
+
+dbus is a simple library that implements native Go client bindings for the
+D-Bus message bus system.
+
+### Features
+
+* Complete native implementation of the D-Bus message protocol
+* Go-like API (channels for signals / asynchronous method calls, Goroutine-safe connections)
+* Subpackages that help with the introspection / property interfaces
+
+### Installation
+
+This packages requires Go 1.1. If you installed it and set up your GOPATH, just run:
+
+```
+go get github.com/godbus/dbus
+```
+
+If you want to use the subpackages, you can install them the same way.
+
+### Usage
+
+The complete package documentation and some simple examples are available at
+[godoc.org](http://godoc.org/github.com/godbus/dbus). Also, the
+[_examples](https://github.com/godbus/dbus/tree/master/_examples) directory
+gives a short overview over the basic usage.
+
+#### Projects using godbus
+- [notify](https://github.com/esiqveland/notify) provides desktop notifications over dbus into a library.
+
+Please note that the API is considered unstable for now and may change without
+further notice.
+
+### License
+
+go.dbus is available under the Simplified BSD License; see LICENSE for the full
+text.
+
+Nearly all of the credit for this library goes to github.com/guelfey/go.dbus.
diff --git a/vendor/github.com/godbus/dbus/auth.go b/vendor/github.com/godbus/dbus/auth.go
new file mode 100644
index 0000000..98017b6
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/auth.go
@@ -0,0 +1,253 @@
+package dbus
+
+import (
+ "bufio"
+ "bytes"
+ "errors"
+ "io"
+ "os"
+ "strconv"
+)
+
+// AuthStatus represents the Status of an authentication mechanism.
+type AuthStatus byte
+
+const (
+ // AuthOk signals that authentication is finished; the next command
+ // from the server should be an OK.
+ AuthOk AuthStatus = iota
+
+ // AuthContinue signals that additional data is needed; the next command
+ // from the server should be a DATA.
+ AuthContinue
+
+ // AuthError signals an error; the server sent invalid data or some
+ // other unexpected thing happened and the current authentication
+ // process should be aborted.
+ AuthError
+)
+
+type authState byte
+
+const (
+ waitingForData authState = iota
+ waitingForOk
+ waitingForReject
+)
+
+// Auth defines the behaviour of an authentication mechanism.
+type Auth interface {
+ // Return the name of the mechnism, the argument to the first AUTH command
+ // and the next status.
+ FirstData() (name, resp []byte, status AuthStatus)
+
+ // Process the given DATA command, and return the argument to the DATA
+ // command and the next status. If len(resp) == 0, no DATA command is sent.
+ HandleData(data []byte) (resp []byte, status AuthStatus)
+}
+
+// Auth authenticates the connection, trying the given list of authentication
+// mechanisms (in that order). If nil is passed, the EXTERNAL and
+// DBUS_COOKIE_SHA1 mechanisms are tried for the current user. For private
+// connections, this method must be called before sending any messages to the
+// bus. Auth must not be called on shared connections.
+func (conn *Conn) Auth(methods []Auth) error {
+ if methods == nil {
+ uid := strconv.Itoa(os.Getuid())
+ methods = []Auth{AuthExternal(uid), AuthCookieSha1(uid, getHomeDir())}
+ }
+ in := bufio.NewReader(conn.transport)
+ err := conn.transport.SendNullByte()
+ if err != nil {
+ return err
+ }
+ err = authWriteLine(conn.transport, []byte("AUTH"))
+ if err != nil {
+ return err
+ }
+ s, err := authReadLine(in)
+ if err != nil {
+ return err
+ }
+ if len(s) < 2 || !bytes.Equal(s[0], []byte("REJECTED")) {
+ return errors.New("dbus: authentication protocol error")
+ }
+ s = s[1:]
+ for _, v := range s {
+ for _, m := range methods {
+ if name, data, status := m.FirstData(); bytes.Equal(v, name) {
+ var ok bool
+ err = authWriteLine(conn.transport, []byte("AUTH"), []byte(v), data)
+ if err != nil {
+ return err
+ }
+ switch status {
+ case AuthOk:
+ err, ok = conn.tryAuth(m, waitingForOk, in)
+ case AuthContinue:
+ err, ok = conn.tryAuth(m, waitingForData, in)
+ default:
+ panic("dbus: invalid authentication status")
+ }
+ if err != nil {
+ return err
+ }
+ if ok {
+ if conn.transport.SupportsUnixFDs() {
+ err = authWriteLine(conn, []byte("NEGOTIATE_UNIX_FD"))
+ if err != nil {
+ return err
+ }
+ line, err := authReadLine(in)
+ if err != nil {
+ return err
+ }
+ switch {
+ case bytes.Equal(line[0], []byte("AGREE_UNIX_FD")):
+ conn.EnableUnixFDs()
+ conn.unixFD = true
+ case bytes.Equal(line[0], []byte("ERROR")):
+ default:
+ return errors.New("dbus: authentication protocol error")
+ }
+ }
+ err = authWriteLine(conn.transport, []byte("BEGIN"))
+ if err != nil {
+ return err
+ }
+ go conn.inWorker()
+ go conn.outWorker()
+ return nil
+ }
+ }
+ }
+ }
+ return errors.New("dbus: authentication failed")
+}
+
+// tryAuth tries to authenticate with m as the mechanism, using state as the
+// initial authState and in for reading input. It returns (nil, true) on
+// success, (nil, false) on a REJECTED and (someErr, false) if some other
+// error occured.
+func (conn *Conn) tryAuth(m Auth, state authState, in *bufio.Reader) (error, bool) {
+ for {
+ s, err := authReadLine(in)
+ if err != nil {
+ return err, false
+ }
+ switch {
+ case state == waitingForData && string(s[0]) == "DATA":
+ if len(s) != 2 {
+ err = authWriteLine(conn.transport, []byte("ERROR"))
+ if err != nil {
+ return err, false
+ }
+ continue
+ }
+ data, status := m.HandleData(s[1])
+ switch status {
+ case AuthOk, AuthContinue:
+ if len(data) != 0 {
+ err = authWriteLine(conn.transport, []byte("DATA"), data)
+ if err != nil {
+ return err, false
+ }
+ }
+ if status == AuthOk {
+ state = waitingForOk
+ }
+ case AuthError:
+ err = authWriteLine(conn.transport, []byte("ERROR"))
+ if err != nil {
+ return err, false
+ }
+ }
+ case state == waitingForData && string(s[0]) == "REJECTED":
+ return nil, false
+ case state == waitingForData && string(s[0]) == "ERROR":
+ err = authWriteLine(conn.transport, []byte("CANCEL"))
+ if err != nil {
+ return err, false
+ }
+ state = waitingForReject
+ case state == waitingForData && string(s[0]) == "OK":
+ if len(s) != 2 {
+ err = authWriteLine(conn.transport, []byte("CANCEL"))
+ if err != nil {
+ return err, false
+ }
+ state = waitingForReject
+ }
+ conn.uuid = string(s[1])
+ return nil, true
+ case state == waitingForData:
+ err = authWriteLine(conn.transport, []byte("ERROR"))
+ if err != nil {
+ return err, false
+ }
+ case state == waitingForOk && string(s[0]) == "OK":
+ if len(s) != 2 {
+ err = authWriteLine(conn.transport, []byte("CANCEL"))
+ if err != nil {
+ return err, false
+ }
+ state = waitingForReject
+ }
+ conn.uuid = string(s[1])
+ return nil, true
+ case state == waitingForOk && string(s[0]) == "REJECTED":
+ return nil, false
+ case state == waitingForOk && (string(s[0]) == "DATA" ||
+ string(s[0]) == "ERROR"):
+
+ err = authWriteLine(conn.transport, []byte("CANCEL"))
+ if err != nil {
+ return err, false
+ }
+ state = waitingForReject
+ case state == waitingForOk:
+ err = authWriteLine(conn.transport, []byte("ERROR"))
+ if err != nil {
+ return err, false
+ }
+ case state == waitingForReject && string(s[0]) == "REJECTED":
+ return nil, false
+ case state == waitingForReject:
+ return errors.New("dbus: authentication protocol error"), false
+ default:
+ panic("dbus: invalid auth state")
+ }
+ }
+}
+
+// authReadLine reads a line and separates it into its fields.
+func authReadLine(in *bufio.Reader) ([][]byte, error) {
+ data, err := in.ReadBytes('\n')
+ if err != nil {
+ return nil, err
+ }
+ data = bytes.TrimSuffix(data, []byte("\r\n"))
+ return bytes.Split(data, []byte{' '}), nil
+}
+
+// authWriteLine writes the given line in the authentication protocol format
+// (elements of data separated by a " " and terminated by "\r\n").
+func authWriteLine(out io.Writer, data ...[]byte) error {
+ buf := make([]byte, 0)
+ for i, v := range data {
+ buf = append(buf, v...)
+ if i != len(data)-1 {
+ buf = append(buf, ' ')
+ }
+ }
+ buf = append(buf, '\r')
+ buf = append(buf, '\n')
+ n, err := out.Write(buf)
+ if err != nil {
+ return err
+ }
+ if n != len(buf) {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
diff --git a/vendor/github.com/godbus/dbus/auth_external.go b/vendor/github.com/godbus/dbus/auth_external.go
new file mode 100644
index 0000000..7e376d3
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/auth_external.go
@@ -0,0 +1,26 @@
+package dbus
+
+import (
+ "encoding/hex"
+)
+
+// AuthExternal returns an Auth that authenticates as the given user with the
+// EXTERNAL mechanism.
+func AuthExternal(user string) Auth {
+ return authExternal{user}
+}
+
+// AuthExternal implements the EXTERNAL authentication mechanism.
+type authExternal struct {
+ user string
+}
+
+func (a authExternal) FirstData() ([]byte, []byte, AuthStatus) {
+ b := make([]byte, 2*len(a.user))
+ hex.Encode(b, []byte(a.user))
+ return []byte("EXTERNAL"), b, AuthOk
+}
+
+func (a authExternal) HandleData(b []byte) ([]byte, AuthStatus) {
+ return nil, AuthError
+}
diff --git a/vendor/github.com/godbus/dbus/auth_sha1.go b/vendor/github.com/godbus/dbus/auth_sha1.go
new file mode 100644
index 0000000..df15b46
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/auth_sha1.go
@@ -0,0 +1,102 @@
+package dbus
+
+import (
+ "bufio"
+ "bytes"
+ "crypto/rand"
+ "crypto/sha1"
+ "encoding/hex"
+ "os"
+)
+
+// AuthCookieSha1 returns an Auth that authenticates as the given user with the
+// DBUS_COOKIE_SHA1 mechanism. The home parameter should specify the home
+// directory of the user.
+func AuthCookieSha1(user, home string) Auth {
+ return authCookieSha1{user, home}
+}
+
+type authCookieSha1 struct {
+ user, home string
+}
+
+func (a authCookieSha1) FirstData() ([]byte, []byte, AuthStatus) {
+ b := make([]byte, 2*len(a.user))
+ hex.Encode(b, []byte(a.user))
+ return []byte("DBUS_COOKIE_SHA1"), b, AuthContinue
+}
+
+func (a authCookieSha1) HandleData(data []byte) ([]byte, AuthStatus) {
+ challenge := make([]byte, len(data)/2)
+ _, err := hex.Decode(challenge, data)
+ if err != nil {
+ return nil, AuthError
+ }
+ b := bytes.Split(challenge, []byte{' '})
+ if len(b) != 3 {
+ return nil, AuthError
+ }
+ context := b[0]
+ id := b[1]
+ svchallenge := b[2]
+ cookie := a.getCookie(context, id)
+ if cookie == nil {
+ return nil, AuthError
+ }
+ clchallenge := a.generateChallenge()
+ if clchallenge == nil {
+ return nil, AuthError
+ }
+ hash := sha1.New()
+ hash.Write(bytes.Join([][]byte{svchallenge, clchallenge, cookie}, []byte{':'}))
+ hexhash := make([]byte, 2*hash.Size())
+ hex.Encode(hexhash, hash.Sum(nil))
+ data = append(clchallenge, ' ')
+ data = append(data, hexhash...)
+ resp := make([]byte, 2*len(data))
+ hex.Encode(resp, data)
+ return resp, AuthOk
+}
+
+// getCookie searches for the cookie identified by id in context and returns
+// the cookie content or nil. (Since HandleData can't return a specific error,
+// but only whether an error occured, this function also doesn't bother to
+// return an error.)
+func (a authCookieSha1) getCookie(context, id []byte) []byte {
+ file, err := os.Open(a.home + "/.dbus-keyrings/" + string(context))
+ if err != nil {
+ return nil
+ }
+ defer file.Close()
+ rd := bufio.NewReader(file)
+ for {
+ line, err := rd.ReadBytes('\n')
+ if err != nil {
+ return nil
+ }
+ line = line[:len(line)-1]
+ b := bytes.Split(line, []byte{' '})
+ if len(b) != 3 {
+ return nil
+ }
+ if bytes.Equal(b[0], id) {
+ return b[2]
+ }
+ }
+}
+
+// generateChallenge returns a random, hex-encoded challenge, or nil on error
+// (see above).
+func (a authCookieSha1) generateChallenge() []byte {
+ b := make([]byte, 16)
+ n, err := rand.Read(b)
+ if err != nil {
+ return nil
+ }
+ if n != 16 {
+ return nil
+ }
+ enc := make([]byte, 32)
+ hex.Encode(enc, b)
+ return enc
+}
diff --git a/vendor/github.com/godbus/dbus/call.go b/vendor/github.com/godbus/dbus/call.go
new file mode 100644
index 0000000..ba6e73f
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/call.go
@@ -0,0 +1,36 @@
+package dbus
+
+import (
+ "errors"
+)
+
+// Call represents a pending or completed method call.
+type Call struct {
+ Destination string
+ Path ObjectPath
+ Method string
+ Args []interface{}
+
+ // Strobes when the call is complete.
+ Done chan *Call
+
+ // After completion, the error status. If this is non-nil, it may be an
+ // error message from the peer (with Error as its type) or some other error.
+ Err error
+
+ // Holds the response once the call is done.
+ Body []interface{}
+}
+
+var errSignature = errors.New("dbus: mismatched signature")
+
+// Store stores the body of the reply into the provided pointers. It returns
+// an error if the signatures of the body and retvalues don't match, or if
+// the error status is not nil.
+func (c *Call) Store(retvalues ...interface{}) error {
+ if c.Err != nil {
+ return c.Err
+ }
+
+ return Store(c.Body, retvalues...)
+}
diff --git a/vendor/github.com/godbus/dbus/conn.go b/vendor/github.com/godbus/dbus/conn.go
new file mode 100644
index 0000000..a4f5394
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/conn.go
@@ -0,0 +1,625 @@
+package dbus
+
+import (
+ "errors"
+ "io"
+ "os"
+ "reflect"
+ "strings"
+ "sync"
+)
+
+const defaultSystemBusAddress = "unix:path=/var/run/dbus/system_bus_socket"
+
+var (
+ systemBus *Conn
+ systemBusLck sync.Mutex
+ sessionBus *Conn
+ sessionBusLck sync.Mutex
+)
+
+// ErrClosed is the error returned by calls on a closed connection.
+var ErrClosed = errors.New("dbus: connection closed by user")
+
+// Conn represents a connection to a message bus (usually, the system or
+// session bus).
+//
+// Connections are either shared or private. Shared connections
+// are shared between calls to the functions that return them. As a result,
+// the methods Close, Auth and Hello must not be called on them.
+//
+// Multiple goroutines may invoke methods on a connection simultaneously.
+type Conn struct {
+ transport
+
+ busObj BusObject
+ unixFD bool
+ uuid string
+
+ names []string
+ namesLck sync.RWMutex
+
+ serialLck sync.Mutex
+ nextSerial uint32
+ serialUsed map[uint32]bool
+
+ calls map[uint32]*Call
+ callsLck sync.RWMutex
+
+ handlers map[ObjectPath]map[string]exportWithMapping
+ handlersLck sync.RWMutex
+
+ out chan *Message
+ closed bool
+ outLck sync.RWMutex
+
+ signals []chan<- *Signal
+ signalsLck sync.Mutex
+
+ eavesdropped chan<- *Message
+ eavesdroppedLck sync.Mutex
+}
+
+// SessionBus returns a shared connection to the session bus, connecting to it
+// if not already done.
+func SessionBus() (conn *Conn, err error) {
+ sessionBusLck.Lock()
+ defer sessionBusLck.Unlock()
+ if sessionBus != nil {
+ return sessionBus, nil
+ }
+ defer func() {
+ if conn != nil {
+ sessionBus = conn
+ }
+ }()
+ conn, err = SessionBusPrivate()
+ if err != nil {
+ return
+ }
+ if err = conn.Auth(nil); err != nil {
+ conn.Close()
+ conn = nil
+ return
+ }
+ if err = conn.Hello(); err != nil {
+ conn.Close()
+ conn = nil
+ }
+ return
+}
+
+// SessionBusPrivate returns a new private connection to the session bus.
+func SessionBusPrivate() (*Conn, error) {
+ address := os.Getenv("DBUS_SESSION_BUS_ADDRESS")
+ if address != "" && address != "autolaunch:" {
+ return Dial(address)
+ }
+
+ return sessionBusPlatform()
+}
+
+// SystemBus returns a shared connection to the system bus, connecting to it if
+// not already done.
+func SystemBus() (conn *Conn, err error) {
+ systemBusLck.Lock()
+ defer systemBusLck.Unlock()
+ if systemBus != nil {
+ return systemBus, nil
+ }
+ defer func() {
+ if conn != nil {
+ systemBus = conn
+ }
+ }()
+ conn, err = SystemBusPrivate()
+ if err != nil {
+ return
+ }
+ if err = conn.Auth(nil); err != nil {
+ conn.Close()
+ conn = nil
+ return
+ }
+ if err = conn.Hello(); err != nil {
+ conn.Close()
+ conn = nil
+ }
+ return
+}
+
+// SystemBusPrivate returns a new private connection to the system bus.
+func SystemBusPrivate() (*Conn, error) {
+ address := os.Getenv("DBUS_SYSTEM_BUS_ADDRESS")
+ if address != "" {
+ return Dial(address)
+ }
+ return Dial(defaultSystemBusAddress)
+}
+
+// Dial establishes a new private connection to the message bus specified by address.
+func Dial(address string) (*Conn, error) {
+ tr, err := getTransport(address)
+ if err != nil {
+ return nil, err
+ }
+ return newConn(tr)
+}
+
+// NewConn creates a new private *Conn from an already established connection.
+func NewConn(conn io.ReadWriteCloser) (*Conn, error) {
+ return newConn(genericTransport{conn})
+}
+
+// newConn creates a new *Conn from a transport.
+func newConn(tr transport) (*Conn, error) {
+ conn := new(Conn)
+ conn.transport = tr
+ conn.calls = make(map[uint32]*Call)
+ conn.out = make(chan *Message, 10)
+ conn.handlers = make(map[ObjectPath]map[string]exportWithMapping)
+ conn.nextSerial = 1
+ conn.serialUsed = map[uint32]bool{0: true}
+ conn.busObj = conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus")
+ return conn, nil
+}
+
+// BusObject returns the object owned by the bus daemon which handles
+// administrative requests.
+func (conn *Conn) BusObject() BusObject {
+ return conn.busObj
+}
+
+// Close closes the connection. Any blocked operations will return with errors
+// and the channels passed to Eavesdrop and Signal are closed. This method must
+// not be called on shared connections.
+func (conn *Conn) Close() error {
+ conn.outLck.Lock()
+ if conn.closed {
+ // inWorker calls Close on read error, the read error may
+ // be caused by another caller calling Close to shutdown the
+ // dbus connection, a double-close scenario we prevent here.
+ conn.outLck.Unlock()
+ return nil
+ }
+ close(conn.out)
+ conn.closed = true
+ conn.outLck.Unlock()
+ conn.signalsLck.Lock()
+ for _, ch := range conn.signals {
+ close(ch)
+ }
+ conn.signalsLck.Unlock()
+ conn.eavesdroppedLck.Lock()
+ if conn.eavesdropped != nil {
+ close(conn.eavesdropped)
+ }
+ conn.eavesdroppedLck.Unlock()
+ return conn.transport.Close()
+}
+
+// Eavesdrop causes conn to send all incoming messages to the given channel
+// without further processing. Method replies, errors and signals will not be
+// sent to the appropiate channels and method calls will not be handled. If nil
+// is passed, the normal behaviour is restored.
+//
+// The caller has to make sure that ch is sufficiently buffered;
+// if a message arrives when a write to ch is not possible, the message is
+// discarded.
+func (conn *Conn) Eavesdrop(ch chan<- *Message) {
+ conn.eavesdroppedLck.Lock()
+ conn.eavesdropped = ch
+ conn.eavesdroppedLck.Unlock()
+}
+
+// getSerial returns an unused serial.
+func (conn *Conn) getSerial() uint32 {
+ conn.serialLck.Lock()
+ defer conn.serialLck.Unlock()
+ n := conn.nextSerial
+ for conn.serialUsed[n] {
+ n++
+ }
+ conn.serialUsed[n] = true
+ conn.nextSerial = n + 1
+ return n
+}
+
+// Hello sends the initial org.freedesktop.DBus.Hello call. This method must be
+// called after authentication, but before sending any other messages to the
+// bus. Hello must not be called for shared connections.
+func (conn *Conn) Hello() error {
+ var s string
+ err := conn.busObj.Call("org.freedesktop.DBus.Hello", 0).Store(&s)
+ if err != nil {
+ return err
+ }
+ conn.namesLck.Lock()
+ conn.names = make([]string, 1)
+ conn.names[0] = s
+ conn.namesLck.Unlock()
+ return nil
+}
+
+// inWorker runs in an own goroutine, reading incoming messages from the
+// transport and dispatching them appropiately.
+func (conn *Conn) inWorker() {
+ for {
+ msg, err := conn.ReadMessage()
+ if err == nil {
+ conn.eavesdroppedLck.Lock()
+ if conn.eavesdropped != nil {
+ select {
+ case conn.eavesdropped <- msg:
+ default:
+ }
+ conn.eavesdroppedLck.Unlock()
+ continue
+ }
+ conn.eavesdroppedLck.Unlock()
+ dest, _ := msg.Headers[FieldDestination].value.(string)
+ found := false
+ if dest == "" {
+ found = true
+ } else {
+ conn.namesLck.RLock()
+ if len(conn.names) == 0 {
+ found = true
+ }
+ for _, v := range conn.names {
+ if dest == v {
+ found = true
+ break
+ }
+ }
+ conn.namesLck.RUnlock()
+ }
+ if !found {
+ // Eavesdropped a message, but no channel for it is registered.
+ // Ignore it.
+ continue
+ }
+ switch msg.Type {
+ case TypeMethodReply, TypeError:
+ serial := msg.Headers[FieldReplySerial].value.(uint32)
+ conn.callsLck.Lock()
+ if c, ok := conn.calls[serial]; ok {
+ if msg.Type == TypeError {
+ name, _ := msg.Headers[FieldErrorName].value.(string)
+ c.Err = Error{name, msg.Body}
+ } else {
+ c.Body = msg.Body
+ }
+ c.Done <- c
+ conn.serialLck.Lock()
+ delete(conn.serialUsed, serial)
+ conn.serialLck.Unlock()
+ delete(conn.calls, serial)
+ }
+ conn.callsLck.Unlock()
+ case TypeSignal:
+ iface := msg.Headers[FieldInterface].value.(string)
+ member := msg.Headers[FieldMember].value.(string)
+ // as per http://dbus.freedesktop.org/doc/dbus-specification.html ,
+ // sender is optional for signals.
+ sender, _ := msg.Headers[FieldSender].value.(string)
+ if iface == "org.freedesktop.DBus" && sender == "org.freedesktop.DBus" {
+ if member == "NameLost" {
+ // If we lost the name on the bus, remove it from our
+ // tracking list.
+ name, ok := msg.Body[0].(string)
+ if !ok {
+ panic("Unable to read the lost name")
+ }
+ conn.namesLck.Lock()
+ for i, v := range conn.names {
+ if v == name {
+ conn.names = append(conn.names[:i],
+ conn.names[i+1:]...)
+ }
+ }
+ conn.namesLck.Unlock()
+ } else if member == "NameAcquired" {
+ // If we acquired the name on the bus, add it to our
+ // tracking list.
+ name, ok := msg.Body[0].(string)
+ if !ok {
+ panic("Unable to read the acquired name")
+ }
+ conn.namesLck.Lock()
+ conn.names = append(conn.names, name)
+ conn.namesLck.Unlock()
+ }
+ }
+ signal := &Signal{
+ Sender: sender,
+ Path: msg.Headers[FieldPath].value.(ObjectPath),
+ Name: iface + "." + member,
+ Body: msg.Body,
+ }
+ conn.signalsLck.Lock()
+ for _, ch := range conn.signals {
+ ch <- signal
+ }
+ conn.signalsLck.Unlock()
+ case TypeMethodCall:
+ go conn.handleCall(msg)
+ }
+ } else if _, ok := err.(InvalidMessageError); !ok {
+ // Some read error occured (usually EOF); we can't really do
+ // anything but to shut down all stuff and returns errors to all
+ // pending replies.
+ conn.Close()
+ conn.callsLck.RLock()
+ for _, v := range conn.calls {
+ v.Err = err
+ v.Done <- v
+ }
+ conn.callsLck.RUnlock()
+ return
+ }
+ // invalid messages are ignored
+ }
+}
+
+// Names returns the list of all names that are currently owned by this
+// connection. The slice is always at least one element long, the first element
+// being the unique name of the connection.
+func (conn *Conn) Names() []string {
+ conn.namesLck.RLock()
+ // copy the slice so it can't be modified
+ s := make([]string, len(conn.names))
+ copy(s, conn.names)
+ conn.namesLck.RUnlock()
+ return s
+}
+
+// Object returns the object identified by the given destination name and path.
+func (conn *Conn) Object(dest string, path ObjectPath) BusObject {
+ return &Object{conn, dest, path}
+}
+
+// outWorker runs in an own goroutine, encoding and sending messages that are
+// sent to conn.out.
+func (conn *Conn) outWorker() {
+ for msg := range conn.out {
+ err := conn.SendMessage(msg)
+ conn.callsLck.RLock()
+ if err != nil {
+ if c := conn.calls[msg.serial]; c != nil {
+ c.Err = err
+ c.Done <- c
+ }
+ conn.serialLck.Lock()
+ delete(conn.serialUsed, msg.serial)
+ conn.serialLck.Unlock()
+ } else if msg.Type != TypeMethodCall {
+ conn.serialLck.Lock()
+ delete(conn.serialUsed, msg.serial)
+ conn.serialLck.Unlock()
+ }
+ conn.callsLck.RUnlock()
+ }
+}
+
+// Send sends the given message to the message bus. You usually don't need to
+// use this; use the higher-level equivalents (Call / Go, Emit and Export)
+// instead. If msg is a method call and NoReplyExpected is not set, a non-nil
+// call is returned and the same value is sent to ch (which must be buffered)
+// once the call is complete. Otherwise, ch is ignored and a Call structure is
+// returned of which only the Err member is valid.
+func (conn *Conn) Send(msg *Message, ch chan *Call) *Call {
+ var call *Call
+
+ msg.serial = conn.getSerial()
+ if msg.Type == TypeMethodCall && msg.Flags&FlagNoReplyExpected == 0 {
+ if ch == nil {
+ ch = make(chan *Call, 5)
+ } else if cap(ch) == 0 {
+ panic("dbus: unbuffered channel passed to (*Conn).Send")
+ }
+ call = new(Call)
+ call.Destination, _ = msg.Headers[FieldDestination].value.(string)
+ call.Path, _ = msg.Headers[FieldPath].value.(ObjectPath)
+ iface, _ := msg.Headers[FieldInterface].value.(string)
+ member, _ := msg.Headers[FieldMember].value.(string)
+ call.Method = iface + "." + member
+ call.Args = msg.Body
+ call.Done = ch
+ conn.callsLck.Lock()
+ conn.calls[msg.serial] = call
+ conn.callsLck.Unlock()
+ conn.outLck.RLock()
+ if conn.closed {
+ call.Err = ErrClosed
+ call.Done <- call
+ } else {
+ conn.out <- msg
+ }
+ conn.outLck.RUnlock()
+ } else {
+ conn.outLck.RLock()
+ if conn.closed {
+ call = &Call{Err: ErrClosed}
+ } else {
+ conn.out <- msg
+ call = &Call{Err: nil}
+ }
+ conn.outLck.RUnlock()
+ }
+ return call
+}
+
+// sendError creates an error message corresponding to the parameters and sends
+// it to conn.out.
+func (conn *Conn) sendError(e Error, dest string, serial uint32) {
+ msg := new(Message)
+ msg.Type = TypeError
+ msg.serial = conn.getSerial()
+ msg.Headers = make(map[HeaderField]Variant)
+ if dest != "" {
+ msg.Headers[FieldDestination] = MakeVariant(dest)
+ }
+ msg.Headers[FieldErrorName] = MakeVariant(e.Name)
+ msg.Headers[FieldReplySerial] = MakeVariant(serial)
+ msg.Body = e.Body
+ if len(e.Body) > 0 {
+ msg.Headers[FieldSignature] = MakeVariant(SignatureOf(e.Body...))
+ }
+ conn.outLck.RLock()
+ if !conn.closed {
+ conn.out <- msg
+ }
+ conn.outLck.RUnlock()
+}
+
+// sendReply creates a method reply message corresponding to the parameters and
+// sends it to conn.out.
+func (conn *Conn) sendReply(dest string, serial uint32, values ...interface{}) {
+ msg := new(Message)
+ msg.Type = TypeMethodReply
+ msg.serial = conn.getSerial()
+ msg.Headers = make(map[HeaderField]Variant)
+ if dest != "" {
+ msg.Headers[FieldDestination] = MakeVariant(dest)
+ }
+ msg.Headers[FieldReplySerial] = MakeVariant(serial)
+ msg.Body = values
+ if len(values) > 0 {
+ msg.Headers[FieldSignature] = MakeVariant(SignatureOf(values...))
+ }
+ conn.outLck.RLock()
+ if !conn.closed {
+ conn.out <- msg
+ }
+ conn.outLck.RUnlock()
+}
+
+// Signal registers the given channel to be passed all received signal messages.
+// The caller has to make sure that ch is sufficiently buffered; if a message
+// arrives when a write to c is not possible, it is discarded.
+//
+// Multiple of these channels can be registered at the same time. Passing a
+// channel that already is registered will remove it from the list of the
+// registered channels.
+//
+// These channels are "overwritten" by Eavesdrop; i.e., if there currently is a
+// channel for eavesdropped messages, this channel receives all signals, and
+// none of the channels passed to Signal will receive any signals.
+func (conn *Conn) Signal(ch chan<- *Signal) {
+ conn.signalsLck.Lock()
+ conn.signals = append(conn.signals, ch)
+ conn.signalsLck.Unlock()
+}
+
+// SupportsUnixFDs returns whether the underlying transport supports passing of
+// unix file descriptors. If this is false, method calls containing unix file
+// descriptors will return an error and emitted signals containing them will
+// not be sent.
+func (conn *Conn) SupportsUnixFDs() bool {
+ return conn.unixFD
+}
+
+// Error represents a D-Bus message of type Error.
+type Error struct {
+ Name string
+ Body []interface{}
+}
+
+func NewError(name string, body []interface{}) *Error {
+ return &Error{name, body}
+}
+
+func (e Error) Error() string {
+ if len(e.Body) >= 1 {
+ s, ok := e.Body[0].(string)
+ if ok {
+ return s
+ }
+ }
+ return e.Name
+}
+
+// Signal represents a D-Bus message of type Signal. The name member is given in
+// "interface.member" notation, e.g. org.freedesktop.D-Bus.NameLost.
+type Signal struct {
+ Sender string
+ Path ObjectPath
+ Name string
+ Body []interface{}
+}
+
+// transport is a D-Bus transport.
+type transport interface {
+ // Read and Write raw data (for example, for the authentication protocol).
+ io.ReadWriteCloser
+
+ // Send the initial null byte used for the EXTERNAL mechanism.
+ SendNullByte() error
+
+ // Returns whether this transport supports passing Unix FDs.
+ SupportsUnixFDs() bool
+
+ // Signal the transport that Unix FD passing is enabled for this connection.
+ EnableUnixFDs()
+
+ // Read / send a message, handling things like Unix FDs.
+ ReadMessage() (*Message, error)
+ SendMessage(*Message) error
+}
+
+var (
+ transports = make(map[string]func(string) (transport, error))
+)
+
+func getTransport(address string) (transport, error) {
+ var err error
+ var t transport
+
+ addresses := strings.Split(address, ";")
+ for _, v := range addresses {
+ i := strings.IndexRune(v, ':')
+ if i == -1 {
+ err = errors.New("dbus: invalid bus address (no transport)")
+ continue
+ }
+ f := transports[v[:i]]
+ if f == nil {
+ err = errors.New("dbus: invalid bus address (invalid or unsupported transport)")
+ continue
+ }
+ t, err = f(v[i+1:])
+ if err == nil {
+ return t, nil
+ }
+ }
+ return nil, err
+}
+
+// dereferenceAll returns a slice that, assuming that vs is a slice of pointers
+// of arbitrary types, containes the values that are obtained from dereferencing
+// all elements in vs.
+func dereferenceAll(vs []interface{}) []interface{} {
+ for i := range vs {
+ v := reflect.ValueOf(vs[i])
+ v = v.Elem()
+ vs[i] = v.Interface()
+ }
+ return vs
+}
+
+// getKey gets a key from a the list of keys. Returns "" on error / not found...
+func getKey(s, key string) string {
+ i := strings.Index(s, key)
+ if i == -1 {
+ return ""
+ }
+ if i+len(key)+1 >= len(s) || s[i+len(key)] != '=' {
+ return ""
+ }
+ j := strings.Index(s, ",")
+ if j == -1 {
+ j = len(s)
+ }
+ return s[i+len(key)+1 : j]
+}
diff --git a/vendor/github.com/godbus/dbus/conn_darwin.go b/vendor/github.com/godbus/dbus/conn_darwin.go
new file mode 100644
index 0000000..b67bb1b
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/conn_darwin.go
@@ -0,0 +1,21 @@
+package dbus
+
+import (
+ "errors"
+ "os/exec"
+)
+
+func sessionBusPlatform() (*Conn, error) {
+ cmd := exec.Command("launchctl", "getenv", "DBUS_LAUNCHD_SESSION_BUS_SOCKET")
+ b, err := cmd.CombinedOutput()
+
+ if err != nil {
+ return nil, err
+ }
+
+ if len(b) == 0 {
+ return nil, errors.New("dbus: couldn't determine address of session bus")
+ }
+
+ return Dial("unix:path=" + string(b[:len(b)-1]))
+}
diff --git a/vendor/github.com/godbus/dbus/conn_other.go b/vendor/github.com/godbus/dbus/conn_other.go
new file mode 100644
index 0000000..f74b875
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/conn_other.go
@@ -0,0 +1,27 @@
+// +build !darwin
+
+package dbus
+
+import (
+ "bytes"
+ "errors"
+ "os/exec"
+)
+
+func sessionBusPlatform() (*Conn, error) {
+ cmd := exec.Command("dbus-launch")
+ b, err := cmd.CombinedOutput()
+
+ if err != nil {
+ return nil, err
+ }
+
+ i := bytes.IndexByte(b, '=')
+ j := bytes.IndexByte(b, '\n')
+
+ if i == -1 || j == -1 {
+ return nil, errors.New("dbus: couldn't determine address of session bus")
+ }
+
+ return Dial(string(b[i+1 : j]))
+}
diff --git a/vendor/github.com/godbus/dbus/dbus.go b/vendor/github.com/godbus/dbus/dbus.go
new file mode 100644
index 0000000..2ce6873
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/dbus.go
@@ -0,0 +1,258 @@
+package dbus
+
+import (
+ "errors"
+ "reflect"
+ "strings"
+)
+
+var (
+ byteType = reflect.TypeOf(byte(0))
+ boolType = reflect.TypeOf(false)
+ uint8Type = reflect.TypeOf(uint8(0))
+ int16Type = reflect.TypeOf(int16(0))
+ uint16Type = reflect.TypeOf(uint16(0))
+ int32Type = reflect.TypeOf(int32(0))
+ uint32Type = reflect.TypeOf(uint32(0))
+ int64Type = reflect.TypeOf(int64(0))
+ uint64Type = reflect.TypeOf(uint64(0))
+ float64Type = reflect.TypeOf(float64(0))
+ stringType = reflect.TypeOf("")
+ signatureType = reflect.TypeOf(Signature{""})
+ objectPathType = reflect.TypeOf(ObjectPath(""))
+ variantType = reflect.TypeOf(Variant{Signature{""}, nil})
+ interfacesType = reflect.TypeOf([]interface{}{})
+ unixFDType = reflect.TypeOf(UnixFD(0))
+ unixFDIndexType = reflect.TypeOf(UnixFDIndex(0))
+)
+
+// An InvalidTypeError signals that a value which cannot be represented in the
+// D-Bus wire format was passed to a function.
+type InvalidTypeError struct {
+ Type reflect.Type
+}
+
+func (e InvalidTypeError) Error() string {
+ return "dbus: invalid type " + e.Type.String()
+}
+
+// Store copies the values contained in src to dest, which must be a slice of
+// pointers. It converts slices of interfaces from src to corresponding structs
+// in dest. An error is returned if the lengths of src and dest or the types of
+// their elements don't match.
+func Store(src []interface{}, dest ...interface{}) error {
+ if len(src) != len(dest) {
+ return errors.New("dbus.Store: length mismatch")
+ }
+
+ for i := range src {
+ if err := store(src[i], dest[i]); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func store(src, dest interface{}) error {
+ if reflect.TypeOf(dest).Elem() == reflect.TypeOf(src) {
+ reflect.ValueOf(dest).Elem().Set(reflect.ValueOf(src))
+ return nil
+ } else if hasStruct(dest) {
+ rv := reflect.ValueOf(dest).Elem()
+ switch rv.Kind() {
+ case reflect.Struct:
+ vs, ok := src.([]interface{})
+ if !ok {
+ return errors.New("dbus.Store: type mismatch")
+ }
+ t := rv.Type()
+ ndest := make([]interface{}, 0, rv.NumField())
+ for i := 0; i < rv.NumField(); i++ {
+ field := t.Field(i)
+ if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
+ ndest = append(ndest, rv.Field(i).Addr().Interface())
+ }
+ }
+ if len(vs) != len(ndest) {
+ return errors.New("dbus.Store: type mismatch")
+ }
+ err := Store(vs, ndest...)
+ if err != nil {
+ return errors.New("dbus.Store: type mismatch")
+ }
+ case reflect.Slice:
+ sv := reflect.ValueOf(src)
+ if sv.Kind() != reflect.Slice {
+ return errors.New("dbus.Store: type mismatch")
+ }
+ rv.Set(reflect.MakeSlice(rv.Type(), sv.Len(), sv.Len()))
+ for i := 0; i < sv.Len(); i++ {
+ if err := store(sv.Index(i).Interface(), rv.Index(i).Addr().Interface()); err != nil {
+ return err
+ }
+ }
+ case reflect.Map:
+ sv := reflect.ValueOf(src)
+ if sv.Kind() != reflect.Map {
+ return errors.New("dbus.Store: type mismatch")
+ }
+ keys := sv.MapKeys()
+ rv.Set(reflect.MakeMap(sv.Type()))
+ for _, key := range keys {
+ v := reflect.New(sv.Type().Elem())
+ if err := store(v, sv.MapIndex(key).Interface()); err != nil {
+ return err
+ }
+ rv.SetMapIndex(key, v.Elem())
+ }
+ default:
+ return errors.New("dbus.Store: type mismatch")
+ }
+ return nil
+ } else {
+ return errors.New("dbus.Store: type mismatch")
+ }
+}
+
+func hasStruct(v interface{}) bool {
+ t := reflect.TypeOf(v)
+ for {
+ switch t.Kind() {
+ case reflect.Struct:
+ return true
+ case reflect.Slice, reflect.Ptr, reflect.Map:
+ t = t.Elem()
+ default:
+ return false
+ }
+ }
+}
+
+// An ObjectPath is an object path as defined by the D-Bus spec.
+type ObjectPath string
+
+// IsValid returns whether the object path is valid.
+func (o ObjectPath) IsValid() bool {
+ s := string(o)
+ if len(s) == 0 {
+ return false
+ }
+ if s[0] != '/' {
+ return false
+ }
+ if s[len(s)-1] == '/' && len(s) != 1 {
+ return false
+ }
+ // probably not used, but technically possible
+ if s == "/" {
+ return true
+ }
+ split := strings.Split(s[1:], "/")
+ for _, v := range split {
+ if len(v) == 0 {
+ return false
+ }
+ for _, c := range v {
+ if !isMemberChar(c) {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// A UnixFD is a Unix file descriptor sent over the wire. See the package-level
+// documentation for more information about Unix file descriptor passsing.
+type UnixFD int32
+
+// A UnixFDIndex is the representation of a Unix file descriptor in a message.
+type UnixFDIndex uint32
+
+// alignment returns the alignment of values of type t.
+func alignment(t reflect.Type) int {
+ switch t {
+ case variantType:
+ return 1
+ case objectPathType:
+ return 4
+ case signatureType:
+ return 1
+ case interfacesType: // sometimes used for structs
+ return 8
+ }
+ switch t.Kind() {
+ case reflect.Uint8:
+ return 1
+ case reflect.Uint16, reflect.Int16:
+ return 2
+ case reflect.Uint32, reflect.Int32, reflect.String, reflect.Array, reflect.Slice, reflect.Map:
+ return 4
+ case reflect.Uint64, reflect.Int64, reflect.Float64, reflect.Struct:
+ return 8
+ case reflect.Ptr:
+ return alignment(t.Elem())
+ }
+ return 1
+}
+
+// isKeyType returns whether t is a valid type for a D-Bus dict.
+func isKeyType(t reflect.Type) bool {
+ switch t.Kind() {
+ case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
+ reflect.Int16, reflect.Int32, reflect.Int64, reflect.Float64,
+ reflect.String:
+
+ return true
+ }
+ return false
+}
+
+// isValidInterface returns whether s is a valid name for an interface.
+func isValidInterface(s string) bool {
+ if len(s) == 0 || len(s) > 255 || s[0] == '.' {
+ return false
+ }
+ elem := strings.Split(s, ".")
+ if len(elem) < 2 {
+ return false
+ }
+ for _, v := range elem {
+ if len(v) == 0 {
+ return false
+ }
+ if v[0] >= '0' && v[0] <= '9' {
+ return false
+ }
+ for _, c := range v {
+ if !isMemberChar(c) {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// isValidMember returns whether s is a valid name for a member.
+func isValidMember(s string) bool {
+ if len(s) == 0 || len(s) > 255 {
+ return false
+ }
+ i := strings.Index(s, ".")
+ if i != -1 {
+ return false
+ }
+ if s[0] >= '0' && s[0] <= '9' {
+ return false
+ }
+ for _, c := range s {
+ if !isMemberChar(c) {
+ return false
+ }
+ }
+ return true
+}
+
+func isMemberChar(c rune) bool {
+ return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
+ (c >= 'a' && c <= 'z') || c == '_'
+}
diff --git a/vendor/github.com/godbus/dbus/decoder.go b/vendor/github.com/godbus/dbus/decoder.go
new file mode 100644
index 0000000..ef50dca
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/decoder.go
@@ -0,0 +1,228 @@
+package dbus
+
+import (
+ "encoding/binary"
+ "io"
+ "reflect"
+)
+
+type decoder struct {
+ in io.Reader
+ order binary.ByteOrder
+ pos int
+}
+
+// newDecoder returns a new decoder that reads values from in. The input is
+// expected to be in the given byte order.
+func newDecoder(in io.Reader, order binary.ByteOrder) *decoder {
+ dec := new(decoder)
+ dec.in = in
+ dec.order = order
+ return dec
+}
+
+// align aligns the input to the given boundary and panics on error.
+func (dec *decoder) align(n int) {
+ if dec.pos%n != 0 {
+ newpos := (dec.pos + n - 1) & ^(n - 1)
+ empty := make([]byte, newpos-dec.pos)
+ if _, err := io.ReadFull(dec.in, empty); err != nil {
+ panic(err)
+ }
+ dec.pos = newpos
+ }
+}
+
+// Calls binary.Read(dec.in, dec.order, v) and panics on read errors.
+func (dec *decoder) binread(v interface{}) {
+ if err := binary.Read(dec.in, dec.order, v); err != nil {
+ panic(err)
+ }
+}
+
+func (dec *decoder) Decode(sig Signature) (vs []interface{}, err error) {
+ defer func() {
+ var ok bool
+ v := recover()
+ if err, ok = v.(error); ok {
+ if err == io.EOF || err == io.ErrUnexpectedEOF {
+ err = FormatError("unexpected EOF")
+ }
+ }
+ }()
+ vs = make([]interface{}, 0)
+ s := sig.str
+ for s != "" {
+ err, rem := validSingle(s, 0)
+ if err != nil {
+ return nil, err
+ }
+ v := dec.decode(s[:len(s)-len(rem)], 0)
+ vs = append(vs, v)
+ s = rem
+ }
+ return vs, nil
+}
+
+func (dec *decoder) decode(s string, depth int) interface{} {
+ dec.align(alignment(typeFor(s)))
+ switch s[0] {
+ case 'y':
+ var b [1]byte
+ if _, err := dec.in.Read(b[:]); err != nil {
+ panic(err)
+ }
+ dec.pos++
+ return b[0]
+ case 'b':
+ i := dec.decode("u", depth).(uint32)
+ switch {
+ case i == 0:
+ return false
+ case i == 1:
+ return true
+ default:
+ panic(FormatError("invalid value for boolean"))
+ }
+ case 'n':
+ var i int16
+ dec.binread(&i)
+ dec.pos += 2
+ return i
+ case 'i':
+ var i int32
+ dec.binread(&i)
+ dec.pos += 4
+ return i
+ case 'x':
+ var i int64
+ dec.binread(&i)
+ dec.pos += 8
+ return i
+ case 'q':
+ var i uint16
+ dec.binread(&i)
+ dec.pos += 2
+ return i
+ case 'u':
+ var i uint32
+ dec.binread(&i)
+ dec.pos += 4
+ return i
+ case 't':
+ var i uint64
+ dec.binread(&i)
+ dec.pos += 8
+ return i
+ case 'd':
+ var f float64
+ dec.binread(&f)
+ dec.pos += 8
+ return f
+ case 's':
+ length := dec.decode("u", depth).(uint32)
+ b := make([]byte, int(length)+1)
+ if _, err := io.ReadFull(dec.in, b); err != nil {
+ panic(err)
+ }
+ dec.pos += int(length) + 1
+ return string(b[:len(b)-1])
+ case 'o':
+ return ObjectPath(dec.decode("s", depth).(string))
+ case 'g':
+ length := dec.decode("y", depth).(byte)
+ b := make([]byte, int(length)+1)
+ if _, err := io.ReadFull(dec.in, b); err != nil {
+ panic(err)
+ }
+ dec.pos += int(length) + 1
+ sig, err := ParseSignature(string(b[:len(b)-1]))
+ if err != nil {
+ panic(err)
+ }
+ return sig
+ case 'v':
+ if depth >= 64 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ var variant Variant
+ sig := dec.decode("g", depth).(Signature)
+ if len(sig.str) == 0 {
+ panic(FormatError("variant signature is empty"))
+ }
+ err, rem := validSingle(sig.str, 0)
+ if err != nil {
+ panic(err)
+ }
+ if rem != "" {
+ panic(FormatError("variant signature has multiple types"))
+ }
+ variant.sig = sig
+ variant.value = dec.decode(sig.str, depth+1)
+ return variant
+ case 'h':
+ return UnixFDIndex(dec.decode("u", depth).(uint32))
+ case 'a':
+ if len(s) > 1 && s[1] == '{' {
+ ksig := s[2:3]
+ vsig := s[3 : len(s)-1]
+ v := reflect.MakeMap(reflect.MapOf(typeFor(ksig), typeFor(vsig)))
+ if depth >= 63 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ length := dec.decode("u", depth).(uint32)
+ // Even for empty maps, the correct padding must be included
+ dec.align(8)
+ spos := dec.pos
+ for dec.pos < spos+int(length) {
+ dec.align(8)
+ if !isKeyType(v.Type().Key()) {
+ panic(InvalidTypeError{v.Type()})
+ }
+ kv := dec.decode(ksig, depth+2)
+ vv := dec.decode(vsig, depth+2)
+ v.SetMapIndex(reflect.ValueOf(kv), reflect.ValueOf(vv))
+ }
+ return v.Interface()
+ }
+ if depth >= 64 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ length := dec.decode("u", depth).(uint32)
+ v := reflect.MakeSlice(reflect.SliceOf(typeFor(s[1:])), 0, int(length))
+ // Even for empty arrays, the correct padding must be included
+ dec.align(alignment(typeFor(s[1:])))
+ spos := dec.pos
+ for dec.pos < spos+int(length) {
+ ev := dec.decode(s[1:], depth+1)
+ v = reflect.Append(v, reflect.ValueOf(ev))
+ }
+ return v.Interface()
+ case '(':
+ if depth >= 64 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ dec.align(8)
+ v := make([]interface{}, 0)
+ s = s[1 : len(s)-1]
+ for s != "" {
+ err, rem := validSingle(s, 0)
+ if err != nil {
+ panic(err)
+ }
+ ev := dec.decode(s[:len(s)-len(rem)], depth+1)
+ v = append(v, ev)
+ s = rem
+ }
+ return v
+ default:
+ panic(SignatureError{Sig: s})
+ }
+}
+
+// A FormatError is an error in the wire format.
+type FormatError string
+
+func (e FormatError) Error() string {
+ return "dbus: wire format error: " + string(e)
+}
diff --git a/vendor/github.com/godbus/dbus/doc.go b/vendor/github.com/godbus/dbus/doc.go
new file mode 100644
index 0000000..deff554
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/doc.go
@@ -0,0 +1,63 @@
+/*
+Package dbus implements bindings to the D-Bus message bus system.
+
+To use the message bus API, you first need to connect to a bus (usually the
+session or system bus). The acquired connection then can be used to call methods
+on remote objects and emit or receive signals. Using the Export method, you can
+arrange D-Bus methods calls to be directly translated to method calls on a Go
+value.
+
+Conversion Rules
+
+For outgoing messages, Go types are automatically converted to the
+corresponding D-Bus types. The following types are directly encoded as their
+respective D-Bus equivalents:
+
+ Go type | D-Bus type
+ ------------+-----------
+ byte | BYTE
+ bool | BOOLEAN
+ int16 | INT16
+ uint16 | UINT16
+ int32 | INT32
+ uint32 | UINT32
+ int64 | INT64
+ uint64 | UINT64
+ float64 | DOUBLE
+ string | STRING
+ ObjectPath | OBJECT_PATH
+ Signature | SIGNATURE
+ Variant | VARIANT
+ UnixFDIndex | UNIX_FD
+
+Slices and arrays encode as ARRAYs of their element type.
+
+Maps encode as DICTs, provided that their key type can be used as a key for
+a DICT.
+
+Structs other than Variant and Signature encode as a STRUCT containing their
+exported fields. Fields whose tags contain `dbus:"-"` and unexported fields will
+be skipped.
+
+Pointers encode as the value they're pointed to.
+
+Trying to encode any other type or a slice, map or struct containing an
+unsupported type will result in an InvalidTypeError.
+
+For incoming messages, the inverse of these rules are used, with the exception
+of STRUCTs. Incoming STRUCTS are represented as a slice of empty interfaces
+containing the struct fields in the correct order. The Store function can be
+used to convert such values to Go structs.
+
+Unix FD passing
+
+Handling Unix file descriptors deserves special mention. To use them, you should
+first check that they are supported on a connection by calling SupportsUnixFDs.
+If it returns true, all method of Connection will translate messages containing
+UnixFD's to messages that are accompanied by the given file descriptors with the
+UnixFD values being substituted by the correct indices. Similarily, the indices
+of incoming messages are automatically resolved. It shouldn't be necessary to use
+UnixFDIndex.
+
+*/
+package dbus
diff --git a/vendor/github.com/godbus/dbus/encoder.go b/vendor/github.com/godbus/dbus/encoder.go
new file mode 100644
index 0000000..9f0a9e8
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/encoder.go
@@ -0,0 +1,208 @@
+package dbus
+
+import (
+ "bytes"
+ "encoding/binary"
+ "io"
+ "reflect"
+)
+
+// An encoder encodes values to the D-Bus wire format.
+type encoder struct {
+ out io.Writer
+ order binary.ByteOrder
+ pos int
+}
+
+// NewEncoder returns a new encoder that writes to out in the given byte order.
+func newEncoder(out io.Writer, order binary.ByteOrder) *encoder {
+ return newEncoderAtOffset(out, 0, order)
+}
+
+// newEncoderAtOffset returns a new encoder that writes to out in the given
+// byte order. Specify the offset to initialize pos for proper alignment
+// computation.
+func newEncoderAtOffset(out io.Writer, offset int, order binary.ByteOrder) *encoder {
+ enc := new(encoder)
+ enc.out = out
+ enc.order = order
+ enc.pos = offset
+ return enc
+}
+
+// Aligns the next output to be on a multiple of n. Panics on write errors.
+func (enc *encoder) align(n int) {
+ pad := enc.padding(0, n)
+ if pad > 0 {
+ empty := make([]byte, pad)
+ if _, err := enc.out.Write(empty); err != nil {
+ panic(err)
+ }
+ enc.pos += pad
+ }
+}
+
+// pad returns the number of bytes of padding, based on current position and additional offset.
+// and alignment.
+func (enc *encoder) padding(offset, algn int) int {
+ abs := enc.pos + offset
+ if abs%algn != 0 {
+ newabs := (abs + algn - 1) & ^(algn - 1)
+ return newabs - abs
+ }
+ return 0
+}
+
+// Calls binary.Write(enc.out, enc.order, v) and panics on write errors.
+func (enc *encoder) binwrite(v interface{}) {
+ if err := binary.Write(enc.out, enc.order, v); err != nil {
+ panic(err)
+ }
+}
+
+// Encode encodes the given values to the underyling reader. All written values
+// are aligned properly as required by the D-Bus spec.
+func (enc *encoder) Encode(vs ...interface{}) (err error) {
+ defer func() {
+ err, _ = recover().(error)
+ }()
+ for _, v := range vs {
+ enc.encode(reflect.ValueOf(v), 0)
+ }
+ return nil
+}
+
+// encode encodes the given value to the writer and panics on error. depth holds
+// the depth of the container nesting.
+func (enc *encoder) encode(v reflect.Value, depth int) {
+ enc.align(alignment(v.Type()))
+ switch v.Kind() {
+ case reflect.Uint8:
+ var b [1]byte
+ b[0] = byte(v.Uint())
+ if _, err := enc.out.Write(b[:]); err != nil {
+ panic(err)
+ }
+ enc.pos++
+ case reflect.Bool:
+ if v.Bool() {
+ enc.encode(reflect.ValueOf(uint32(1)), depth)
+ } else {
+ enc.encode(reflect.ValueOf(uint32(0)), depth)
+ }
+ case reflect.Int16:
+ enc.binwrite(int16(v.Int()))
+ enc.pos += 2
+ case reflect.Uint16:
+ enc.binwrite(uint16(v.Uint()))
+ enc.pos += 2
+ case reflect.Int32:
+ enc.binwrite(int32(v.Int()))
+ enc.pos += 4
+ case reflect.Uint32:
+ enc.binwrite(uint32(v.Uint()))
+ enc.pos += 4
+ case reflect.Int64:
+ enc.binwrite(v.Int())
+ enc.pos += 8
+ case reflect.Uint64:
+ enc.binwrite(v.Uint())
+ enc.pos += 8
+ case reflect.Float64:
+ enc.binwrite(v.Float())
+ enc.pos += 8
+ case reflect.String:
+ enc.encode(reflect.ValueOf(uint32(len(v.String()))), depth)
+ b := make([]byte, v.Len()+1)
+ copy(b, v.String())
+ b[len(b)-1] = 0
+ n, err := enc.out.Write(b)
+ if err != nil {
+ panic(err)
+ }
+ enc.pos += n
+ case reflect.Ptr:
+ enc.encode(v.Elem(), depth)
+ case reflect.Slice, reflect.Array:
+ if depth >= 64 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ // Lookahead offset: 4 bytes for uint32 length (with alignment),
+ // plus alignment for elements.
+ n := enc.padding(0, 4) + 4
+ offset := enc.pos + n + enc.padding(n, alignment(v.Type().Elem()))
+
+ var buf bytes.Buffer
+ bufenc := newEncoderAtOffset(&buf, offset, enc.order)
+
+ for i := 0; i < v.Len(); i++ {
+ bufenc.encode(v.Index(i), depth+1)
+ }
+ enc.encode(reflect.ValueOf(uint32(buf.Len())), depth)
+ length := buf.Len()
+ enc.align(alignment(v.Type().Elem()))
+ if _, err := buf.WriteTo(enc.out); err != nil {
+ panic(err)
+ }
+ enc.pos += length
+ case reflect.Struct:
+ if depth >= 64 && v.Type() != signatureType {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ switch t := v.Type(); t {
+ case signatureType:
+ str := v.Field(0)
+ enc.encode(reflect.ValueOf(byte(str.Len())), depth+1)
+ b := make([]byte, str.Len()+1)
+ copy(b, str.String())
+ b[len(b)-1] = 0
+ n, err := enc.out.Write(b)
+ if err != nil {
+ panic(err)
+ }
+ enc.pos += n
+ case variantType:
+ variant := v.Interface().(Variant)
+ enc.encode(reflect.ValueOf(variant.sig), depth+1)
+ enc.encode(reflect.ValueOf(variant.value), depth+1)
+ default:
+ for i := 0; i < v.Type().NumField(); i++ {
+ field := t.Field(i)
+ if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
+ enc.encode(v.Field(i), depth+1)
+ }
+ }
+ }
+ case reflect.Map:
+ // Maps are arrays of structures, so they actually increase the depth by
+ // 2.
+ if depth >= 63 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ if !isKeyType(v.Type().Key()) {
+ panic(InvalidTypeError{v.Type()})
+ }
+ keys := v.MapKeys()
+ // Lookahead offset: 4 bytes for uint32 length (with alignment),
+ // plus 8-byte alignment
+ n := enc.padding(0, 4) + 4
+ offset := enc.pos + n + enc.padding(n, 8)
+
+ var buf bytes.Buffer
+ bufenc := newEncoderAtOffset(&buf, offset, enc.order)
+ for _, k := range keys {
+ bufenc.align(8)
+ bufenc.encode(k, depth+2)
+ bufenc.encode(v.MapIndex(k), depth+2)
+ }
+ enc.encode(reflect.ValueOf(uint32(buf.Len())), depth)
+ length := buf.Len()
+ enc.align(8)
+ if _, err := buf.WriteTo(enc.out); err != nil {
+ panic(err)
+ }
+ enc.pos += length
+ default:
+ panic(InvalidTypeError{v.Type()})
+ }
+}
diff --git a/vendor/github.com/godbus/dbus/export.go b/vendor/github.com/godbus/dbus/export.go
new file mode 100644
index 0000000..c6440a7
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/export.go
@@ -0,0 +1,411 @@
+package dbus
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "strings"
+)
+
+var (
+ errmsgInvalidArg = Error{
+ "org.freedesktop.DBus.Error.InvalidArgs",
+ []interface{}{"Invalid type / number of args"},
+ }
+ errmsgNoObject = Error{
+ "org.freedesktop.DBus.Error.NoSuchObject",
+ []interface{}{"No such object"},
+ }
+ errmsgUnknownMethod = Error{
+ "org.freedesktop.DBus.Error.UnknownMethod",
+ []interface{}{"Unknown / invalid method"},
+ }
+)
+
+// exportWithMapping represents an exported struct along with a method name
+// mapping to allow for exporting lower-case methods, etc.
+type exportWithMapping struct {
+ export interface{}
+
+ // Method name mapping; key -> struct method, value -> dbus method.
+ mapping map[string]string
+
+ // Whether or not this export is for the entire subtree
+ includeSubtree bool
+}
+
+// Sender is a type which can be used in exported methods to receive the message
+// sender.
+type Sender string
+
+func exportedMethod(export exportWithMapping, name string) reflect.Value {
+ if export.export == nil {
+ return reflect.Value{}
+ }
+
+ // If a mapping was included in the export, check the map to see if we
+ // should be looking for a different method in the export.
+ if export.mapping != nil {
+ for key, value := range export.mapping {
+ if value == name {
+ name = key
+ break
+ }
+
+ // Catch the case where a method is aliased but the client is calling
+ // the original, e.g. the "Foo" method was exported mapped to
+ // "foo," and dbus client called the original "Foo."
+ if key == name {
+ return reflect.Value{}
+ }
+ }
+ }
+
+ value := reflect.ValueOf(export.export)
+ m := value.MethodByName(name)
+
+ // Catch the case of attempting to call an unexported method
+ method, ok := value.Type().MethodByName(name)
+
+ if !m.IsValid() || !ok || method.PkgPath != "" {
+ return reflect.Value{}
+ }
+ t := m.Type()
+ if t.NumOut() == 0 ||
+ t.Out(t.NumOut()-1) != reflect.TypeOf(&errmsgInvalidArg) {
+
+ return reflect.Value{}
+ }
+ return m
+}
+
+// searchHandlers will look through all registered handlers looking for one
+// to handle the given path. If a verbatim one isn't found, it will check for
+// a subtree registration for the path as well.
+func (conn *Conn) searchHandlers(path ObjectPath) (map[string]exportWithMapping, bool) {
+ conn.handlersLck.RLock()
+ defer conn.handlersLck.RUnlock()
+
+ handlers, ok := conn.handlers[path]
+ if ok {
+ return handlers, ok
+ }
+
+ // If handlers weren't found for this exact path, look for a matching subtree
+ // registration
+ handlers = make(map[string]exportWithMapping)
+ path = path[:strings.LastIndex(string(path), "/")]
+ for len(path) > 0 {
+ var subtreeHandlers map[string]exportWithMapping
+ subtreeHandlers, ok = conn.handlers[path]
+ if ok {
+ for iface, handler := range subtreeHandlers {
+ // Only include this handler if it registered for the subtree
+ if handler.includeSubtree {
+ handlers[iface] = handler
+ }
+ }
+
+ break
+ }
+
+ path = path[:strings.LastIndex(string(path), "/")]
+ }
+
+ return handlers, ok
+}
+
+// handleCall handles the given method call (i.e. looks if it's one of the
+// pre-implemented ones and searches for a corresponding handler if not).
+func (conn *Conn) handleCall(msg *Message) {
+ name := msg.Headers[FieldMember].value.(string)
+ path := msg.Headers[FieldPath].value.(ObjectPath)
+ ifaceName, hasIface := msg.Headers[FieldInterface].value.(string)
+ sender, hasSender := msg.Headers[FieldSender].value.(string)
+ serial := msg.serial
+ if ifaceName == "org.freedesktop.DBus.Peer" {
+ switch name {
+ case "Ping":
+ conn.sendReply(sender, serial)
+ case "GetMachineId":
+ conn.sendReply(sender, serial, conn.uuid)
+ default:
+ conn.sendError(errmsgUnknownMethod, sender, serial)
+ }
+ return
+ }
+ if len(name) == 0 {
+ conn.sendError(errmsgUnknownMethod, sender, serial)
+ }
+
+ // Find the exported handler (if any) for this path
+ handlers, ok := conn.searchHandlers(path)
+ if !ok {
+ conn.sendError(errmsgNoObject, sender, serial)
+ return
+ }
+
+ var m reflect.Value
+ if hasIface {
+ iface := handlers[ifaceName]
+ m = exportedMethod(iface, name)
+ } else {
+ for _, v := range handlers {
+ m = exportedMethod(v, name)
+ if m.IsValid() {
+ break
+ }
+ }
+ }
+
+ if !m.IsValid() {
+ conn.sendError(errmsgUnknownMethod, sender, serial)
+ return
+ }
+
+ t := m.Type()
+ vs := msg.Body
+ pointers := make([]interface{}, t.NumIn())
+ decode := make([]interface{}, 0, len(vs))
+ for i := 0; i < t.NumIn(); i++ {
+ tp := t.In(i)
+ val := reflect.New(tp)
+ pointers[i] = val.Interface()
+ if tp == reflect.TypeOf((*Sender)(nil)).Elem() {
+ val.Elem().SetString(sender)
+ } else if tp == reflect.TypeOf((*Message)(nil)).Elem() {
+ val.Elem().Set(reflect.ValueOf(*msg))
+ } else {
+ decode = append(decode, pointers[i])
+ }
+ }
+
+ if len(decode) != len(vs) {
+ conn.sendError(errmsgInvalidArg, sender, serial)
+ return
+ }
+
+ if err := Store(vs, decode...); err != nil {
+ conn.sendError(errmsgInvalidArg, sender, serial)
+ return
+ }
+
+ // Extract parameters
+ params := make([]reflect.Value, len(pointers))
+ for i := 0; i < len(pointers); i++ {
+ params[i] = reflect.ValueOf(pointers[i]).Elem()
+ }
+
+ // Call method
+ ret := m.Call(params)
+ if em := ret[t.NumOut()-1].Interface().(*Error); em != nil {
+ conn.sendError(*em, sender, serial)
+ return
+ }
+
+ if msg.Flags&FlagNoReplyExpected == 0 {
+ reply := new(Message)
+ reply.Type = TypeMethodReply
+ reply.serial = conn.getSerial()
+ reply.Headers = make(map[HeaderField]Variant)
+ if hasSender {
+ reply.Headers[FieldDestination] = msg.Headers[FieldSender]
+ }
+ reply.Headers[FieldReplySerial] = MakeVariant(msg.serial)
+ reply.Body = make([]interface{}, len(ret)-1)
+ for i := 0; i < len(ret)-1; i++ {
+ reply.Body[i] = ret[i].Interface()
+ }
+ if len(ret) != 1 {
+ reply.Headers[FieldSignature] = MakeVariant(SignatureOf(reply.Body...))
+ }
+ conn.outLck.RLock()
+ if !conn.closed {
+ conn.out <- reply
+ }
+ conn.outLck.RUnlock()
+ }
+}
+
+// Emit emits the given signal on the message bus. The name parameter must be
+// formatted as "interface.member", e.g., "org.freedesktop.DBus.NameLost".
+func (conn *Conn) Emit(path ObjectPath, name string, values ...interface{}) error {
+ if !path.IsValid() {
+ return errors.New("dbus: invalid object path")
+ }
+ i := strings.LastIndex(name, ".")
+ if i == -1 {
+ return errors.New("dbus: invalid method name")
+ }
+ iface := name[:i]
+ member := name[i+1:]
+ if !isValidMember(member) {
+ return errors.New("dbus: invalid method name")
+ }
+ if !isValidInterface(iface) {
+ return errors.New("dbus: invalid interface name")
+ }
+ msg := new(Message)
+ msg.Type = TypeSignal
+ msg.serial = conn.getSerial()
+ msg.Headers = make(map[HeaderField]Variant)
+ msg.Headers[FieldInterface] = MakeVariant(iface)
+ msg.Headers[FieldMember] = MakeVariant(member)
+ msg.Headers[FieldPath] = MakeVariant(path)
+ msg.Body = values
+ if len(values) > 0 {
+ msg.Headers[FieldSignature] = MakeVariant(SignatureOf(values...))
+ }
+ conn.outLck.RLock()
+ defer conn.outLck.RUnlock()
+ if conn.closed {
+ return ErrClosed
+ }
+ conn.out <- msg
+ return nil
+}
+
+// Export registers the given value to be exported as an object on the
+// message bus.
+//
+// If a method call on the given path and interface is received, an exported
+// method with the same name is called with v as the receiver if the
+// parameters match and the last return value is of type *Error. If this
+// *Error is not nil, it is sent back to the caller as an error.
+// Otherwise, a method reply is sent with the other return values as its body.
+//
+// Any parameters with the special type Sender are set to the sender of the
+// dbus message when the method is called. Parameters of this type do not
+// contribute to the dbus signature of the method (i.e. the method is exposed
+// as if the parameters of type Sender were not there).
+//
+// Similarly, any parameters with the type Message are set to the raw message
+// received on the bus. Again, parameters of this type do not contribute to the
+// dbus signature of the method.
+//
+// Every method call is executed in a new goroutine, so the method may be called
+// in multiple goroutines at once.
+//
+// Method calls on the interface org.freedesktop.DBus.Peer will be automatically
+// handled for every object.
+//
+// Passing nil as the first parameter will cause conn to cease handling calls on
+// the given combination of path and interface.
+//
+// Export returns an error if path is not a valid path name.
+func (conn *Conn) Export(v interface{}, path ObjectPath, iface string) error {
+ return conn.ExportWithMap(v, nil, path, iface)
+}
+
+// ExportWithMap works exactly like Export but provides the ability to remap
+// method names (e.g. export a lower-case method).
+//
+// The keys in the map are the real method names (exported on the struct), and
+// the values are the method names to be exported on DBus.
+func (conn *Conn) ExportWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string) error {
+ return conn.exportWithMap(v, mapping, path, iface, false)
+}
+
+// ExportSubtree works exactly like Export but registers the given value for
+// an entire subtree rather under the root path provided.
+//
+// In order to make this useful, one parameter in each of the value's exported
+// methods should be a Message, in which case it will contain the raw message
+// (allowing one to get access to the path that caused the method to be called).
+//
+// Note that more specific export paths take precedence over less specific. For
+// example, a method call using the ObjectPath /foo/bar/baz will call a method
+// exported on /foo/bar before a method exported on /foo.
+func (conn *Conn) ExportSubtree(v interface{}, path ObjectPath, iface string) error {
+ return conn.ExportSubtreeWithMap(v, nil, path, iface)
+}
+
+// ExportSubtreeWithMap works exactly like ExportSubtree but provides the
+// ability to remap method names (e.g. export a lower-case method).
+//
+// The keys in the map are the real method names (exported on the struct), and
+// the values are the method names to be exported on DBus.
+func (conn *Conn) ExportSubtreeWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string) error {
+ return conn.exportWithMap(v, mapping, path, iface, true)
+}
+
+// exportWithMap is the worker function for all exports/registrations.
+func (conn *Conn) exportWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string, includeSubtree bool) error {
+ if !path.IsValid() {
+ return fmt.Errorf(`dbus: Invalid path name: "%s"`, path)
+ }
+
+ conn.handlersLck.Lock()
+ defer conn.handlersLck.Unlock()
+
+ // Remove a previous export if the interface is nil
+ if v == nil {
+ if _, ok := conn.handlers[path]; ok {
+ delete(conn.handlers[path], iface)
+ if len(conn.handlers[path]) == 0 {
+ delete(conn.handlers, path)
+ }
+ }
+
+ return nil
+ }
+
+ // If this is the first handler for this path, make a new map to hold all
+ // handlers for this path.
+ if _, ok := conn.handlers[path]; !ok {
+ conn.handlers[path] = make(map[string]exportWithMapping)
+ }
+
+ // Finally, save this handler
+ conn.handlers[path][iface] = exportWithMapping{export: v, mapping: mapping, includeSubtree: includeSubtree}
+
+ return nil
+}
+
+// ReleaseName calls org.freedesktop.DBus.ReleaseName and awaits a response.
+func (conn *Conn) ReleaseName(name string) (ReleaseNameReply, error) {
+ var r uint32
+ err := conn.busObj.Call("org.freedesktop.DBus.ReleaseName", 0, name).Store(&r)
+ if err != nil {
+ return 0, err
+ }
+ return ReleaseNameReply(r), nil
+}
+
+// RequestName calls org.freedesktop.DBus.RequestName and awaits a response.
+func (conn *Conn) RequestName(name string, flags RequestNameFlags) (RequestNameReply, error) {
+ var r uint32
+ err := conn.busObj.Call("org.freedesktop.DBus.RequestName", 0, name, flags).Store(&r)
+ if err != nil {
+ return 0, err
+ }
+ return RequestNameReply(r), nil
+}
+
+// ReleaseNameReply is the reply to a ReleaseName call.
+type ReleaseNameReply uint32
+
+const (
+ ReleaseNameReplyReleased ReleaseNameReply = 1 + iota
+ ReleaseNameReplyNonExistent
+ ReleaseNameReplyNotOwner
+)
+
+// RequestNameFlags represents the possible flags for a RequestName call.
+type RequestNameFlags uint32
+
+const (
+ NameFlagAllowReplacement RequestNameFlags = 1 << iota
+ NameFlagReplaceExisting
+ NameFlagDoNotQueue
+)
+
+// RequestNameReply is the reply to a RequestName call.
+type RequestNameReply uint32
+
+const (
+ RequestNameReplyPrimaryOwner RequestNameReply = 1 + iota
+ RequestNameReplyInQueue
+ RequestNameReplyExists
+ RequestNameReplyAlreadyOwner
+)
diff --git a/vendor/github.com/godbus/dbus/homedir.go b/vendor/github.com/godbus/dbus/homedir.go
new file mode 100644
index 0000000..0b745f9
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/homedir.go
@@ -0,0 +1,28 @@
+package dbus
+
+import (
+ "os"
+ "sync"
+)
+
+var (
+ homeDir string
+ homeDirLock sync.Mutex
+)
+
+func getHomeDir() string {
+ homeDirLock.Lock()
+ defer homeDirLock.Unlock()
+
+ if homeDir != "" {
+ return homeDir
+ }
+
+ homeDir = os.Getenv("HOME")
+ if homeDir != "" {
+ return homeDir
+ }
+
+ homeDir = lookupHomeDir()
+ return homeDir
+}
diff --git a/vendor/github.com/godbus/dbus/homedir_dynamic.go b/vendor/github.com/godbus/dbus/homedir_dynamic.go
new file mode 100644
index 0000000..2732081
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/homedir_dynamic.go
@@ -0,0 +1,15 @@
+// +build !static_build
+
+package dbus
+
+import (
+ "os/user"
+)
+
+func lookupHomeDir() string {
+ u, err := user.Current()
+ if err != nil {
+ return "/"
+ }
+ return u.HomeDir
+}
diff --git a/vendor/github.com/godbus/dbus/homedir_static.go b/vendor/github.com/godbus/dbus/homedir_static.go
new file mode 100644
index 0000000..b9d9cb5
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/homedir_static.go
@@ -0,0 +1,45 @@
+// +build static_build
+
+package dbus
+
+import (
+ "bufio"
+ "os"
+ "strconv"
+ "strings"
+)
+
+func lookupHomeDir() string {
+ myUid := os.Getuid()
+
+ f, err := os.Open("/etc/passwd")
+ if err != nil {
+ return "/"
+ }
+ defer f.Close()
+
+ s := bufio.NewScanner(f)
+
+ for s.Scan() {
+ if err := s.Err(); err != nil {
+ break
+ }
+
+ line := strings.TrimSpace(s.Text())
+ if line == "" {
+ continue
+ }
+
+ parts := strings.Split(line, ":")
+
+ if len(parts) >= 6 {
+ uid, err := strconv.Atoi(parts[2])
+ if err == nil && uid == myUid {
+ return parts[5]
+ }
+ }
+ }
+
+ // Default to / if we can't get a better value
+ return "/"
+}
diff --git a/vendor/github.com/godbus/dbus/message.go b/vendor/github.com/godbus/dbus/message.go
new file mode 100644
index 0000000..075d6e3
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/message.go
@@ -0,0 +1,346 @@
+package dbus
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "io"
+ "reflect"
+ "strconv"
+)
+
+const protoVersion byte = 1
+
+// Flags represents the possible flags of a D-Bus message.
+type Flags byte
+
+const (
+ // FlagNoReplyExpected signals that the message is not expected to generate
+ // a reply. If this flag is set on outgoing messages, any possible reply
+ // will be discarded.
+ FlagNoReplyExpected Flags = 1 << iota
+ // FlagNoAutoStart signals that the message bus should not automatically
+ // start an application when handling this message.
+ FlagNoAutoStart
+)
+
+// Type represents the possible types of a D-Bus message.
+type Type byte
+
+const (
+ TypeMethodCall Type = 1 + iota
+ TypeMethodReply
+ TypeError
+ TypeSignal
+ typeMax
+)
+
+func (t Type) String() string {
+ switch t {
+ case TypeMethodCall:
+ return "method call"
+ case TypeMethodReply:
+ return "reply"
+ case TypeError:
+ return "error"
+ case TypeSignal:
+ return "signal"
+ }
+ return "invalid"
+}
+
+// HeaderField represents the possible byte codes for the headers
+// of a D-Bus message.
+type HeaderField byte
+
+const (
+ FieldPath HeaderField = 1 + iota
+ FieldInterface
+ FieldMember
+ FieldErrorName
+ FieldReplySerial
+ FieldDestination
+ FieldSender
+ FieldSignature
+ FieldUnixFDs
+ fieldMax
+)
+
+// An InvalidMessageError describes the reason why a D-Bus message is regarded as
+// invalid.
+type InvalidMessageError string
+
+func (e InvalidMessageError) Error() string {
+ return "dbus: invalid message: " + string(e)
+}
+
+// fieldType are the types of the various header fields.
+var fieldTypes = [fieldMax]reflect.Type{
+ FieldPath: objectPathType,
+ FieldInterface: stringType,
+ FieldMember: stringType,
+ FieldErrorName: stringType,
+ FieldReplySerial: uint32Type,
+ FieldDestination: stringType,
+ FieldSender: stringType,
+ FieldSignature: signatureType,
+ FieldUnixFDs: uint32Type,
+}
+
+// requiredFields lists the header fields that are required by the different
+// message types.
+var requiredFields = [typeMax][]HeaderField{
+ TypeMethodCall: {FieldPath, FieldMember},
+ TypeMethodReply: {FieldReplySerial},
+ TypeError: {FieldErrorName, FieldReplySerial},
+ TypeSignal: {FieldPath, FieldInterface, FieldMember},
+}
+
+// Message represents a single D-Bus message.
+type Message struct {
+ Type
+ Flags
+ Headers map[HeaderField]Variant
+ Body []interface{}
+
+ serial uint32
+}
+
+type header struct {
+ Field byte
+ Variant
+}
+
+// DecodeMessage tries to decode a single message in the D-Bus wire format
+// from the given reader. The byte order is figured out from the first byte.
+// The possibly returned error can be an error of the underlying reader, an
+// InvalidMessageError or a FormatError.
+func DecodeMessage(rd io.Reader) (msg *Message, err error) {
+ var order binary.ByteOrder
+ var hlength, length uint32
+ var typ, flags, proto byte
+ var headers []header
+
+ b := make([]byte, 1)
+ _, err = rd.Read(b)
+ if err != nil {
+ return
+ }
+ switch b[0] {
+ case 'l':
+ order = binary.LittleEndian
+ case 'B':
+ order = binary.BigEndian
+ default:
+ return nil, InvalidMessageError("invalid byte order")
+ }
+
+ dec := newDecoder(rd, order)
+ dec.pos = 1
+
+ msg = new(Message)
+ vs, err := dec.Decode(Signature{"yyyuu"})
+ if err != nil {
+ return nil, err
+ }
+ if err = Store(vs, &typ, &flags, &proto, &length, &msg.serial); err != nil {
+ return nil, err
+ }
+ msg.Type = Type(typ)
+ msg.Flags = Flags(flags)
+
+ // get the header length separately because we need it later
+ b = make([]byte, 4)
+ _, err = io.ReadFull(rd, b)
+ if err != nil {
+ return nil, err
+ }
+ binary.Read(bytes.NewBuffer(b), order, &hlength)
+ if hlength+length+16 > 1<<27 {
+ return nil, InvalidMessageError("message is too long")
+ }
+ dec = newDecoder(io.MultiReader(bytes.NewBuffer(b), rd), order)
+ dec.pos = 12
+ vs, err = dec.Decode(Signature{"a(yv)"})
+ if err != nil {
+ return nil, err
+ }
+ if err = Store(vs, &headers); err != nil {
+ return nil, err
+ }
+
+ msg.Headers = make(map[HeaderField]Variant)
+ for _, v := range headers {
+ msg.Headers[HeaderField(v.Field)] = v.Variant
+ }
+
+ dec.align(8)
+ body := make([]byte, int(length))
+ if length != 0 {
+ _, err := io.ReadFull(rd, body)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ if err = msg.IsValid(); err != nil {
+ return nil, err
+ }
+ sig, _ := msg.Headers[FieldSignature].value.(Signature)
+ if sig.str != "" {
+ buf := bytes.NewBuffer(body)
+ dec = newDecoder(buf, order)
+ vs, err := dec.Decode(sig)
+ if err != nil {
+ return nil, err
+ }
+ msg.Body = vs
+ }
+
+ return
+}
+
+// EncodeTo encodes and sends a message to the given writer. The byte order must
+// be either binary.LittleEndian or binary.BigEndian. If the message is not
+// valid or an error occurs when writing, an error is returned.
+func (msg *Message) EncodeTo(out io.Writer, order binary.ByteOrder) error {
+ if err := msg.IsValid(); err != nil {
+ return err
+ }
+ var vs [7]interface{}
+ switch order {
+ case binary.LittleEndian:
+ vs[0] = byte('l')
+ case binary.BigEndian:
+ vs[0] = byte('B')
+ default:
+ return errors.New("dbus: invalid byte order")
+ }
+ body := new(bytes.Buffer)
+ enc := newEncoder(body, order)
+ if len(msg.Body) != 0 {
+ enc.Encode(msg.Body...)
+ }
+ vs[1] = msg.Type
+ vs[2] = msg.Flags
+ vs[3] = protoVersion
+ vs[4] = uint32(len(body.Bytes()))
+ vs[5] = msg.serial
+ headers := make([]header, 0, len(msg.Headers))
+ for k, v := range msg.Headers {
+ headers = append(headers, header{byte(k), v})
+ }
+ vs[6] = headers
+ var buf bytes.Buffer
+ enc = newEncoder(&buf, order)
+ enc.Encode(vs[:]...)
+ enc.align(8)
+ body.WriteTo(&buf)
+ if buf.Len() > 1<<27 {
+ return InvalidMessageError("message is too long")
+ }
+ if _, err := buf.WriteTo(out); err != nil {
+ return err
+ }
+ return nil
+}
+
+// IsValid checks whether msg is a valid message and returns an
+// InvalidMessageError if it is not.
+func (msg *Message) IsValid() error {
+ if msg.Flags & ^(FlagNoAutoStart|FlagNoReplyExpected) != 0 {
+ return InvalidMessageError("invalid flags")
+ }
+ if msg.Type == 0 || msg.Type >= typeMax {
+ return InvalidMessageError("invalid message type")
+ }
+ for k, v := range msg.Headers {
+ if k == 0 || k >= fieldMax {
+ return InvalidMessageError("invalid header")
+ }
+ if reflect.TypeOf(v.value) != fieldTypes[k] {
+ return InvalidMessageError("invalid type of header field")
+ }
+ }
+ for _, v := range requiredFields[msg.Type] {
+ if _, ok := msg.Headers[v]; !ok {
+ return InvalidMessageError("missing required header")
+ }
+ }
+ if path, ok := msg.Headers[FieldPath]; ok {
+ if !path.value.(ObjectPath).IsValid() {
+ return InvalidMessageError("invalid path name")
+ }
+ }
+ if iface, ok := msg.Headers[FieldInterface]; ok {
+ if !isValidInterface(iface.value.(string)) {
+ return InvalidMessageError("invalid interface name")
+ }
+ }
+ if member, ok := msg.Headers[FieldMember]; ok {
+ if !isValidMember(member.value.(string)) {
+ return InvalidMessageError("invalid member name")
+ }
+ }
+ if errname, ok := msg.Headers[FieldErrorName]; ok {
+ if !isValidInterface(errname.value.(string)) {
+ return InvalidMessageError("invalid error name")
+ }
+ }
+ if len(msg.Body) != 0 {
+ if _, ok := msg.Headers[FieldSignature]; !ok {
+ return InvalidMessageError("missing signature")
+ }
+ }
+ return nil
+}
+
+// Serial returns the message's serial number. The returned value is only valid
+// for messages received by eavesdropping.
+func (msg *Message) Serial() uint32 {
+ return msg.serial
+}
+
+// String returns a string representation of a message similar to the format of
+// dbus-monitor.
+func (msg *Message) String() string {
+ if err := msg.IsValid(); err != nil {
+ return "<invalid>"
+ }
+ s := msg.Type.String()
+ if v, ok := msg.Headers[FieldSender]; ok {
+ s += " from " + v.value.(string)
+ }
+ if v, ok := msg.Headers[FieldDestination]; ok {
+ s += " to " + v.value.(string)
+ }
+ s += " serial " + strconv.FormatUint(uint64(msg.serial), 10)
+ if v, ok := msg.Headers[FieldReplySerial]; ok {
+ s += " reply_serial " + strconv.FormatUint(uint64(v.value.(uint32)), 10)
+ }
+ if v, ok := msg.Headers[FieldUnixFDs]; ok {
+ s += " unixfds " + strconv.FormatUint(uint64(v.value.(uint32)), 10)
+ }
+ if v, ok := msg.Headers[FieldPath]; ok {
+ s += " path " + string(v.value.(ObjectPath))
+ }
+ if v, ok := msg.Headers[FieldInterface]; ok {
+ s += " interface " + v.value.(string)
+ }
+ if v, ok := msg.Headers[FieldErrorName]; ok {
+ s += " error " + v.value.(string)
+ }
+ if v, ok := msg.Headers[FieldMember]; ok {
+ s += " member " + v.value.(string)
+ }
+ if len(msg.Body) != 0 {
+ s += "\n"
+ }
+ for i, v := range msg.Body {
+ s += " " + MakeVariant(v).String()
+ if i != len(msg.Body)-1 {
+ s += "\n"
+ }
+ }
+ return s
+}
diff --git a/vendor/github.com/godbus/dbus/object.go b/vendor/github.com/godbus/dbus/object.go
new file mode 100644
index 0000000..7ef45da
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/object.go
@@ -0,0 +1,126 @@
+package dbus
+
+import (
+ "errors"
+ "strings"
+)
+
+// BusObject is the interface of a remote object on which methods can be
+// invoked.
+type BusObject interface {
+ Call(method string, flags Flags, args ...interface{}) *Call
+ Go(method string, flags Flags, ch chan *Call, args ...interface{}) *Call
+ GetProperty(p string) (Variant, error)
+ Destination() string
+ Path() ObjectPath
+}
+
+// Object represents a remote object on which methods can be invoked.
+type Object struct {
+ conn *Conn
+ dest string
+ path ObjectPath
+}
+
+// Call calls a method with (*Object).Go and waits for its reply.
+func (o *Object) Call(method string, flags Flags, args ...interface{}) *Call {
+ return <-o.Go(method, flags, make(chan *Call, 1), args...).Done
+}
+
+// Go calls a method with the given arguments asynchronously. It returns a
+// Call structure representing this method call. The passed channel will
+// return the same value once the call is done. If ch is nil, a new channel
+// will be allocated. Otherwise, ch has to be buffered or Go will panic.
+//
+// If the flags include FlagNoReplyExpected, ch is ignored and a Call structure
+// is returned of which only the Err member is valid.
+//
+// If the method parameter contains a dot ('.'), the part before the last dot
+// specifies the interface on which the method is called.
+func (o *Object) Go(method string, flags Flags, ch chan *Call, args ...interface{}) *Call {
+ iface := ""
+ i := strings.LastIndex(method, ".")
+ if i != -1 {
+ iface = method[:i]
+ }
+ method = method[i+1:]
+ msg := new(Message)
+ msg.Type = TypeMethodCall
+ msg.serial = o.conn.getSerial()
+ msg.Flags = flags & (FlagNoAutoStart | FlagNoReplyExpected)
+ msg.Headers = make(map[HeaderField]Variant)
+ msg.Headers[FieldPath] = MakeVariant(o.path)
+ msg.Headers[FieldDestination] = MakeVariant(o.dest)
+ msg.Headers[FieldMember] = MakeVariant(method)
+ if iface != "" {
+ msg.Headers[FieldInterface] = MakeVariant(iface)
+ }
+ msg.Body = args
+ if len(args) > 0 {
+ msg.Headers[FieldSignature] = MakeVariant(SignatureOf(args...))
+ }
+ if msg.Flags&FlagNoReplyExpected == 0 {
+ if ch == nil {
+ ch = make(chan *Call, 10)
+ } else if cap(ch) == 0 {
+ panic("dbus: unbuffered channel passed to (*Object).Go")
+ }
+ call := &Call{
+ Destination: o.dest,
+ Path: o.path,
+ Method: method,
+ Args: args,
+ Done: ch,
+ }
+ o.conn.callsLck.Lock()
+ o.conn.calls[msg.serial] = call
+ o.conn.callsLck.Unlock()
+ o.conn.outLck.RLock()
+ if o.conn.closed {
+ call.Err = ErrClosed
+ call.Done <- call
+ } else {
+ o.conn.out <- msg
+ }
+ o.conn.outLck.RUnlock()
+ return call
+ }
+ o.conn.outLck.RLock()
+ defer o.conn.outLck.RUnlock()
+ if o.conn.closed {
+ return &Call{Err: ErrClosed}
+ }
+ o.conn.out <- msg
+ return &Call{Err: nil}
+}
+
+// GetProperty calls org.freedesktop.DBus.Properties.GetProperty on the given
+// object. The property name must be given in interface.member notation.
+func (o *Object) GetProperty(p string) (Variant, error) {
+ idx := strings.LastIndex(p, ".")
+ if idx == -1 || idx+1 == len(p) {
+ return Variant{}, errors.New("dbus: invalid property " + p)
+ }
+
+ iface := p[:idx]
+ prop := p[idx+1:]
+
+ result := Variant{}
+ err := o.Call("org.freedesktop.DBus.Properties.Get", 0, iface, prop).Store(&result)
+
+ if err != nil {
+ return Variant{}, err
+ }
+
+ return result, nil
+}
+
+// Destination returns the destination that calls on o are sent to.
+func (o *Object) Destination() string {
+ return o.dest
+}
+
+// Path returns the path that calls on o are sent to.
+func (o *Object) Path() ObjectPath {
+ return o.path
+}
diff --git a/vendor/github.com/godbus/dbus/sig.go b/vendor/github.com/godbus/dbus/sig.go
new file mode 100644
index 0000000..f45b53c
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/sig.go
@@ -0,0 +1,257 @@
+package dbus
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+)
+
+var sigToType = map[byte]reflect.Type{
+ 'y': byteType,
+ 'b': boolType,
+ 'n': int16Type,
+ 'q': uint16Type,
+ 'i': int32Type,
+ 'u': uint32Type,
+ 'x': int64Type,
+ 't': uint64Type,
+ 'd': float64Type,
+ 's': stringType,
+ 'g': signatureType,
+ 'o': objectPathType,
+ 'v': variantType,
+ 'h': unixFDIndexType,
+}
+
+// Signature represents a correct type signature as specified by the D-Bus
+// specification. The zero value represents the empty signature, "".
+type Signature struct {
+ str string
+}
+
+// SignatureOf returns the concatenation of all the signatures of the given
+// values. It panics if one of them is not representable in D-Bus.
+func SignatureOf(vs ...interface{}) Signature {
+ var s string
+ for _, v := range vs {
+ s += getSignature(reflect.TypeOf(v))
+ }
+ return Signature{s}
+}
+
+// SignatureOfType returns the signature of the given type. It panics if the
+// type is not representable in D-Bus.
+func SignatureOfType(t reflect.Type) Signature {
+ return Signature{getSignature(t)}
+}
+
+// getSignature returns the signature of the given type and panics on unknown types.
+func getSignature(t reflect.Type) string {
+ // handle simple types first
+ switch t.Kind() {
+ case reflect.Uint8:
+ return "y"
+ case reflect.Bool:
+ return "b"
+ case reflect.Int16:
+ return "n"
+ case reflect.Uint16:
+ return "q"
+ case reflect.Int32:
+ if t == unixFDType {
+ return "h"
+ }
+ return "i"
+ case reflect.Uint32:
+ if t == unixFDIndexType {
+ return "h"
+ }
+ return "u"
+ case reflect.Int64:
+ return "x"
+ case reflect.Uint64:
+ return "t"
+ case reflect.Float64:
+ return "d"
+ case reflect.Ptr:
+ return getSignature(t.Elem())
+ case reflect.String:
+ if t == objectPathType {
+ return "o"
+ }
+ return "s"
+ case reflect.Struct:
+ if t == variantType {
+ return "v"
+ } else if t == signatureType {
+ return "g"
+ }
+ var s string
+ for i := 0; i < t.NumField(); i++ {
+ field := t.Field(i)
+ if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
+ s += getSignature(t.Field(i).Type)
+ }
+ }
+ return "(" + s + ")"
+ case reflect.Array, reflect.Slice:
+ return "a" + getSignature(t.Elem())
+ case reflect.Map:
+ if !isKeyType(t.Key()) {
+ panic(InvalidTypeError{t})
+ }
+ return "a{" + getSignature(t.Key()) + getSignature(t.Elem()) + "}"
+ }
+ panic(InvalidTypeError{t})
+}
+
+// ParseSignature returns the signature represented by this string, or a
+// SignatureError if the string is not a valid signature.
+func ParseSignature(s string) (sig Signature, err error) {
+ if len(s) == 0 {
+ return
+ }
+ if len(s) > 255 {
+ return Signature{""}, SignatureError{s, "too long"}
+ }
+ sig.str = s
+ for err == nil && len(s) != 0 {
+ err, s = validSingle(s, 0)
+ }
+ if err != nil {
+ sig = Signature{""}
+ }
+
+ return
+}
+
+// ParseSignatureMust behaves like ParseSignature, except that it panics if s
+// is not valid.
+func ParseSignatureMust(s string) Signature {
+ sig, err := ParseSignature(s)
+ if err != nil {
+ panic(err)
+ }
+ return sig
+}
+
+// Empty retruns whether the signature is the empty signature.
+func (s Signature) Empty() bool {
+ return s.str == ""
+}
+
+// Single returns whether the signature represents a single, complete type.
+func (s Signature) Single() bool {
+ err, r := validSingle(s.str, 0)
+ return err != nil && r == ""
+}
+
+// String returns the signature's string representation.
+func (s Signature) String() string {
+ return s.str
+}
+
+// A SignatureError indicates that a signature passed to a function or received
+// on a connection is not a valid signature.
+type SignatureError struct {
+ Sig string
+ Reason string
+}
+
+func (e SignatureError) Error() string {
+ return fmt.Sprintf("dbus: invalid signature: %q (%s)", e.Sig, e.Reason)
+}
+
+// Try to read a single type from this string. If it was successfull, err is nil
+// and rem is the remaining unparsed part. Otherwise, err is a non-nil
+// SignatureError and rem is "". depth is the current recursion depth which may
+// not be greater than 64 and should be given as 0 on the first call.
+func validSingle(s string, depth int) (err error, rem string) {
+ if s == "" {
+ return SignatureError{Sig: s, Reason: "empty signature"}, ""
+ }
+ if depth > 64 {
+ return SignatureError{Sig: s, Reason: "container nesting too deep"}, ""
+ }
+ switch s[0] {
+ case 'y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 'd', 's', 'g', 'o', 'v', 'h':
+ return nil, s[1:]
+ case 'a':
+ if len(s) > 1 && s[1] == '{' {
+ i := findMatching(s[1:], '{', '}')
+ if i == -1 {
+ return SignatureError{Sig: s, Reason: "unmatched '{'"}, ""
+ }
+ i++
+ rem = s[i+1:]
+ s = s[2:i]
+ if err, _ = validSingle(s[:1], depth+1); err != nil {
+ return err, ""
+ }
+ err, nr := validSingle(s[1:], depth+1)
+ if err != nil {
+ return err, ""
+ }
+ if nr != "" {
+ return SignatureError{Sig: s, Reason: "too many types in dict"}, ""
+ }
+ return nil, rem
+ }
+ return validSingle(s[1:], depth+1)
+ case '(':
+ i := findMatching(s, '(', ')')
+ if i == -1 {
+ return SignatureError{Sig: s, Reason: "unmatched ')'"}, ""
+ }
+ rem = s[i+1:]
+ s = s[1:i]
+ for err == nil && s != "" {
+ err, s = validSingle(s, depth+1)
+ }
+ if err != nil {
+ rem = ""
+ }
+ return
+ }
+ return SignatureError{Sig: s, Reason: "invalid type character"}, ""
+}
+
+func findMatching(s string, left, right rune) int {
+ n := 0
+ for i, v := range s {
+ if v == left {
+ n++
+ } else if v == right {
+ n--
+ }
+ if n == 0 {
+ return i
+ }
+ }
+ return -1
+}
+
+// typeFor returns the type of the given signature. It ignores any left over
+// characters and panics if s doesn't start with a valid type signature.
+func typeFor(s string) (t reflect.Type) {
+ err, _ := validSingle(s, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ if t, ok := sigToType[s[0]]; ok {
+ return t
+ }
+ switch s[0] {
+ case 'a':
+ if s[1] == '{' {
+ i := strings.LastIndex(s, "}")
+ t = reflect.MapOf(sigToType[s[2]], typeFor(s[3:i]))
+ } else {
+ t = reflect.SliceOf(typeFor(s[1:]))
+ }
+ case '(':
+ t = interfacesType
+ }
+ return
+}
diff --git a/vendor/github.com/godbus/dbus/transport_darwin.go b/vendor/github.com/godbus/dbus/transport_darwin.go
new file mode 100644
index 0000000..1bba0d6
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/transport_darwin.go
@@ -0,0 +1,6 @@
+package dbus
+
+func (t *unixTransport) SendNullByte() error {
+ _, err := t.Write([]byte{0})
+ return err
+}
diff --git a/vendor/github.com/godbus/dbus/transport_generic.go b/vendor/github.com/godbus/dbus/transport_generic.go
new file mode 100644
index 0000000..46f8f49
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/transport_generic.go
@@ -0,0 +1,35 @@
+package dbus
+
+import (
+ "encoding/binary"
+ "errors"
+ "io"
+)
+
+type genericTransport struct {
+ io.ReadWriteCloser
+}
+
+func (t genericTransport) SendNullByte() error {
+ _, err := t.Write([]byte{0})
+ return err
+}
+
+func (t genericTransport) SupportsUnixFDs() bool {
+ return false
+}
+
+func (t genericTransport) EnableUnixFDs() {}
+
+func (t genericTransport) ReadMessage() (*Message, error) {
+ return DecodeMessage(t)
+}
+
+func (t genericTransport) SendMessage(msg *Message) error {
+ for _, v := range msg.Body {
+ if _, ok := v.(UnixFD); ok {
+ return errors.New("dbus: unix fd passing not enabled")
+ }
+ }
+ return msg.EncodeTo(t, binary.LittleEndian)
+}
diff --git a/vendor/github.com/godbus/dbus/transport_unix.go b/vendor/github.com/godbus/dbus/transport_unix.go
new file mode 100644
index 0000000..3fafeab
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/transport_unix.go
@@ -0,0 +1,196 @@
+//+build !windows
+
+package dbus
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "io"
+ "net"
+ "syscall"
+)
+
+type oobReader struct {
+ conn *net.UnixConn
+ oob []byte
+ buf [4096]byte
+}
+
+func (o *oobReader) Read(b []byte) (n int, err error) {
+ n, oobn, flags, _, err := o.conn.ReadMsgUnix(b, o.buf[:])
+ if err != nil {
+ return n, err
+ }
+ if flags&syscall.MSG_CTRUNC != 0 {
+ return n, errors.New("dbus: control data truncated (too many fds received)")
+ }
+ o.oob = append(o.oob, o.buf[:oobn]...)
+ return n, nil
+}
+
+type unixTransport struct {
+ *net.UnixConn
+ hasUnixFDs bool
+}
+
+func newUnixTransport(keys string) (transport, error) {
+ var err error
+
+ t := new(unixTransport)
+ abstract := getKey(keys, "abstract")
+ path := getKey(keys, "path")
+ switch {
+ case abstract == "" && path == "":
+ return nil, errors.New("dbus: invalid address (neither path nor abstract set)")
+ case abstract != "" && path == "":
+ t.UnixConn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: "@" + abstract, Net: "unix"})
+ if err != nil {
+ return nil, err
+ }
+ return t, nil
+ case abstract == "" && path != "":
+ t.UnixConn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: path, Net: "unix"})
+ if err != nil {
+ return nil, err
+ }
+ return t, nil
+ default:
+ return nil, errors.New("dbus: invalid address (both path and abstract set)")
+ }
+}
+
+func init() {
+ transports["unix"] = newUnixTransport
+}
+
+func (t *unixTransport) EnableUnixFDs() {
+ t.hasUnixFDs = true
+}
+
+func (t *unixTransport) ReadMessage() (*Message, error) {
+ var (
+ blen, hlen uint32
+ csheader [16]byte
+ headers []header
+ order binary.ByteOrder
+ unixfds uint32
+ )
+ // To be sure that all bytes of out-of-band data are read, we use a special
+ // reader that uses ReadUnix on the underlying connection instead of Read
+ // and gathers the out-of-band data in a buffer.
+ rd := &oobReader{conn: t.UnixConn}
+ // read the first 16 bytes (the part of the header that has a constant size),
+ // from which we can figure out the length of the rest of the message
+ if _, err := io.ReadFull(rd, csheader[:]); err != nil {
+ return nil, err
+ }
+ switch csheader[0] {
+ case 'l':
+ order = binary.LittleEndian
+ case 'B':
+ order = binary.BigEndian
+ default:
+ return nil, InvalidMessageError("invalid byte order")
+ }
+ // csheader[4:8] -> length of message body, csheader[12:16] -> length of
+ // header fields (without alignment)
+ binary.Read(bytes.NewBuffer(csheader[4:8]), order, &blen)
+ binary.Read(bytes.NewBuffer(csheader[12:]), order, &hlen)
+ if hlen%8 != 0 {
+ hlen += 8 - (hlen % 8)
+ }
+
+ // decode headers and look for unix fds
+ headerdata := make([]byte, hlen+4)
+ copy(headerdata, csheader[12:])
+ if _, err := io.ReadFull(t, headerdata[4:]); err != nil {
+ return nil, err
+ }
+ dec := newDecoder(bytes.NewBuffer(headerdata), order)
+ dec.pos = 12
+ vs, err := dec.Decode(Signature{"a(yv)"})
+ if err != nil {
+ return nil, err
+ }
+ Store(vs, &headers)
+ for _, v := range headers {
+ if v.Field == byte(FieldUnixFDs) {
+ unixfds, _ = v.Variant.value.(uint32)
+ }
+ }
+ all := make([]byte, 16+hlen+blen)
+ copy(all, csheader[:])
+ copy(all[16:], headerdata[4:])
+ if _, err := io.ReadFull(rd, all[16+hlen:]); err != nil {
+ return nil, err
+ }
+ if unixfds != 0 {
+ if !t.hasUnixFDs {
+ return nil, errors.New("dbus: got unix fds on unsupported transport")
+ }
+ // read the fds from the OOB data
+ scms, err := syscall.ParseSocketControlMessage(rd.oob)
+ if err != nil {
+ return nil, err
+ }
+ if len(scms) != 1 {
+ return nil, errors.New("dbus: received more than one socket control message")
+ }
+ fds, err := syscall.ParseUnixRights(&scms[0])
+ if err != nil {
+ return nil, err
+ }
+ msg, err := DecodeMessage(bytes.NewBuffer(all))
+ if err != nil {
+ return nil, err
+ }
+ // substitute the values in the message body (which are indices for the
+ // array receiver via OOB) with the actual values
+ for i, v := range msg.Body {
+ if j, ok := v.(UnixFDIndex); ok {
+ if uint32(j) >= unixfds {
+ return nil, InvalidMessageError("invalid index for unix fd")
+ }
+ msg.Body[i] = UnixFD(fds[j])
+ }
+ }
+ return msg, nil
+ }
+ return DecodeMessage(bytes.NewBuffer(all))
+}
+
+func (t *unixTransport) SendMessage(msg *Message) error {
+ fds := make([]int, 0)
+ for i, v := range msg.Body {
+ if fd, ok := v.(UnixFD); ok {
+ msg.Body[i] = UnixFDIndex(len(fds))
+ fds = append(fds, int(fd))
+ }
+ }
+ if len(fds) != 0 {
+ if !t.hasUnixFDs {
+ return errors.New("dbus: unix fd passing not enabled")
+ }
+ msg.Headers[FieldUnixFDs] = MakeVariant(uint32(len(fds)))
+ oob := syscall.UnixRights(fds...)
+ buf := new(bytes.Buffer)
+ msg.EncodeTo(buf, binary.LittleEndian)
+ n, oobn, err := t.UnixConn.WriteMsgUnix(buf.Bytes(), oob, nil)
+ if err != nil {
+ return err
+ }
+ if n != buf.Len() || oobn != len(oob) {
+ return io.ErrShortWrite
+ }
+ } else {
+ if err := msg.EncodeTo(t, binary.LittleEndian); err != nil {
+ return nil
+ }
+ }
+ return nil
+}
+
+func (t *unixTransport) SupportsUnixFDs() bool {
+ return true
+}
diff --git a/vendor/github.com/godbus/dbus/transport_unixcred_dragonfly.go b/vendor/github.com/godbus/dbus/transport_unixcred_dragonfly.go
new file mode 100644
index 0000000..a8cd393
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/transport_unixcred_dragonfly.go
@@ -0,0 +1,95 @@
+// The UnixCredentials system call is currently only implemented on Linux
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// https://golang.org/s/go1.4-syscall
+// http://code.google.com/p/go/source/browse/unix/sockcmsg_linux.go?repo=sys
+
+// Local implementation of the UnixCredentials system call for DragonFly BSD
+
+package dbus
+
+/*
+#include <sys/ucred.h>
+*/
+import "C"
+
+import (
+ "io"
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+// http://golang.org/src/pkg/syscall/ztypes_linux_amd64.go
+// http://golang.org/src/pkg/syscall/ztypes_dragonfly_amd64.go
+type Ucred struct {
+ Pid int32
+ Uid uint32
+ Gid uint32
+}
+
+// http://golang.org/src/pkg/syscall/types_linux.go
+// http://golang.org/src/pkg/syscall/types_dragonfly.go
+// https://github.com/DragonFlyBSD/DragonFlyBSD/blob/master/sys/sys/ucred.h
+const (
+ SizeofUcred = C.sizeof_struct_ucred
+)
+
+// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
+func cmsgAlignOf(salen int) int {
+ // From http://golang.org/src/pkg/syscall/sockcmsg_unix.go
+ //salign := sizeofPtr
+ // NOTE: It seems like 64-bit Darwin and DragonFly BSD kernels
+ // still require 32-bit aligned access to network subsystem.
+ //if darwin64Bit || dragonfly64Bit {
+ // salign = 4
+ //}
+ salign := 4
+ return (salen + salign - 1) & ^(salign - 1)
+}
+
+// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
+func cmsgData(h *syscall.Cmsghdr) unsafe.Pointer {
+ return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(syscall.SizeofCmsghdr)))
+}
+
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// UnixCredentials encodes credentials into a socket control message
+// for sending to another process. This can be used for
+// authentication.
+func UnixCredentials(ucred *Ucred) []byte {
+ b := make([]byte, syscall.CmsgSpace(SizeofUcred))
+ h := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
+ h.Level = syscall.SOL_SOCKET
+ h.Type = syscall.SCM_CREDS
+ h.SetLen(syscall.CmsgLen(SizeofUcred))
+ *((*Ucred)(cmsgData(h))) = *ucred
+ return b
+}
+
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// ParseUnixCredentials decodes a socket control message that contains
+// credentials in a Ucred structure. To receive such a message, the
+// SO_PASSCRED option must be enabled on the socket.
+func ParseUnixCredentials(m *syscall.SocketControlMessage) (*Ucred, error) {
+ if m.Header.Level != syscall.SOL_SOCKET {
+ return nil, syscall.EINVAL
+ }
+ if m.Header.Type != syscall.SCM_CREDS {
+ return nil, syscall.EINVAL
+ }
+ ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0]))
+ return &ucred, nil
+}
+
+func (t *unixTransport) SendNullByte() error {
+ ucred := &Ucred{Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid())}
+ b := UnixCredentials(ucred)
+ _, oobn, err := t.UnixConn.WriteMsgUnix([]byte{0}, b, nil)
+ if err != nil {
+ return err
+ }
+ if oobn != len(b) {
+ return io.ErrShortWrite
+ }
+ return nil
+}
diff --git a/vendor/github.com/godbus/dbus/transport_unixcred_linux.go b/vendor/github.com/godbus/dbus/transport_unixcred_linux.go
new file mode 100644
index 0000000..d9dfdf6
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/transport_unixcred_linux.go
@@ -0,0 +1,25 @@
+// The UnixCredentials system call is currently only implemented on Linux
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// https://golang.org/s/go1.4-syscall
+// http://code.google.com/p/go/source/browse/unix/sockcmsg_linux.go?repo=sys
+
+package dbus
+
+import (
+ "io"
+ "os"
+ "syscall"
+)
+
+func (t *unixTransport) SendNullByte() error {
+ ucred := &syscall.Ucred{Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid())}
+ b := syscall.UnixCredentials(ucred)
+ _, oobn, err := t.UnixConn.WriteMsgUnix([]byte{0}, b, nil)
+ if err != nil {
+ return err
+ }
+ if oobn != len(b) {
+ return io.ErrShortWrite
+ }
+ return nil
+}
diff --git a/vendor/github.com/godbus/dbus/variant.go b/vendor/github.com/godbus/dbus/variant.go
new file mode 100644
index 0000000..b7b13ae
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/variant.go
@@ -0,0 +1,139 @@
+package dbus
+
+import (
+ "bytes"
+ "fmt"
+ "reflect"
+ "sort"
+ "strconv"
+)
+
+// Variant represents the D-Bus variant type.
+type Variant struct {
+ sig Signature
+ value interface{}
+}
+
+// MakeVariant converts the given value to a Variant. It panics if v cannot be
+// represented as a D-Bus type.
+func MakeVariant(v interface{}) Variant {
+ return Variant{SignatureOf(v), v}
+}
+
+// ParseVariant parses the given string as a variant as described at
+// https://developer.gnome.org/glib/unstable/gvariant-text.html. If sig is not
+// empty, it is taken to be the expected signature for the variant.
+func ParseVariant(s string, sig Signature) (Variant, error) {
+ tokens := varLex(s)
+ p := &varParser{tokens: tokens}
+ n, err := varMakeNode(p)
+ if err != nil {
+ return Variant{}, err
+ }
+ if sig.str == "" {
+ sig, err = varInfer(n)
+ if err != nil {
+ return Variant{}, err
+ }
+ }
+ v, err := n.Value(sig)
+ if err != nil {
+ return Variant{}, err
+ }
+ return MakeVariant(v), nil
+}
+
+// format returns a formatted version of v and whether this string can be parsed
+// unambigously.
+func (v Variant) format() (string, bool) {
+ switch v.sig.str[0] {
+ case 'b', 'i':
+ return fmt.Sprint(v.value), true
+ case 'n', 'q', 'u', 'x', 't', 'd', 'h':
+ return fmt.Sprint(v.value), false
+ case 's':
+ return strconv.Quote(v.value.(string)), true
+ case 'o':
+ return strconv.Quote(string(v.value.(ObjectPath))), false
+ case 'g':
+ return strconv.Quote(v.value.(Signature).str), false
+ case 'v':
+ s, unamb := v.value.(Variant).format()
+ if !unamb {
+ return "<@" + v.value.(Variant).sig.str + " " + s + ">", true
+ }
+ return "<" + s + ">", true
+ case 'y':
+ return fmt.Sprintf("%#x", v.value.(byte)), false
+ }
+ rv := reflect.ValueOf(v.value)
+ switch rv.Kind() {
+ case reflect.Slice:
+ if rv.Len() == 0 {
+ return "[]", false
+ }
+ unamb := true
+ buf := bytes.NewBuffer([]byte("["))
+ for i := 0; i < rv.Len(); i++ {
+ // TODO: slooow
+ s, b := MakeVariant(rv.Index(i).Interface()).format()
+ unamb = unamb && b
+ buf.WriteString(s)
+ if i != rv.Len()-1 {
+ buf.WriteString(", ")
+ }
+ }
+ buf.WriteByte(']')
+ return buf.String(), unamb
+ case reflect.Map:
+ if rv.Len() == 0 {
+ return "{}", false
+ }
+ unamb := true
+ var buf bytes.Buffer
+ kvs := make([]string, rv.Len())
+ for i, k := range rv.MapKeys() {
+ s, b := MakeVariant(k.Interface()).format()
+ unamb = unamb && b
+ buf.Reset()
+ buf.WriteString(s)
+ buf.WriteString(": ")
+ s, b = MakeVariant(rv.MapIndex(k).Interface()).format()
+ unamb = unamb && b
+ buf.WriteString(s)
+ kvs[i] = buf.String()
+ }
+ buf.Reset()
+ buf.WriteByte('{')
+ sort.Strings(kvs)
+ for i, kv := range kvs {
+ if i > 0 {
+ buf.WriteString(", ")
+ }
+ buf.WriteString(kv)
+ }
+ buf.WriteByte('}')
+ return buf.String(), unamb
+ }
+ return `"INVALID"`, true
+}
+
+// Signature returns the D-Bus signature of the underlying value of v.
+func (v Variant) Signature() Signature {
+ return v.sig
+}
+
+// String returns the string representation of the underlying value of v as
+// described at https://developer.gnome.org/glib/unstable/gvariant-text.html.
+func (v Variant) String() string {
+ s, unamb := v.format()
+ if !unamb {
+ return "@" + v.sig.str + " " + s
+ }
+ return s
+}
+
+// Value returns the underlying value of v.
+func (v Variant) Value() interface{} {
+ return v.value
+}
diff --git a/vendor/github.com/godbus/dbus/variant_lexer.go b/vendor/github.com/godbus/dbus/variant_lexer.go
new file mode 100644
index 0000000..332007d
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/variant_lexer.go
@@ -0,0 +1,284 @@
+package dbus
+
+import (
+ "fmt"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+// Heavily inspired by the lexer from text/template.
+
+type varToken struct {
+ typ varTokenType
+ val string
+}
+
+type varTokenType byte
+
+const (
+ tokEOF varTokenType = iota
+ tokError
+ tokNumber
+ tokString
+ tokBool
+ tokArrayStart
+ tokArrayEnd
+ tokDictStart
+ tokDictEnd
+ tokVariantStart
+ tokVariantEnd
+ tokComma
+ tokColon
+ tokType
+ tokByteString
+)
+
+type varLexer struct {
+ input string
+ start int
+ pos int
+ width int
+ tokens []varToken
+}
+
+type lexState func(*varLexer) lexState
+
+func varLex(s string) []varToken {
+ l := &varLexer{input: s}
+ l.run()
+ return l.tokens
+}
+
+func (l *varLexer) accept(valid string) bool {
+ if strings.IndexRune(valid, l.next()) >= 0 {
+ return true
+ }
+ l.backup()
+ return false
+}
+
+func (l *varLexer) backup() {
+ l.pos -= l.width
+}
+
+func (l *varLexer) emit(t varTokenType) {
+ l.tokens = append(l.tokens, varToken{t, l.input[l.start:l.pos]})
+ l.start = l.pos
+}
+
+func (l *varLexer) errorf(format string, v ...interface{}) lexState {
+ l.tokens = append(l.tokens, varToken{
+ tokError,
+ fmt.Sprintf(format, v...),
+ })
+ return nil
+}
+
+func (l *varLexer) ignore() {
+ l.start = l.pos
+}
+
+func (l *varLexer) next() rune {
+ var r rune
+
+ if l.pos >= len(l.input) {
+ l.width = 0
+ return -1
+ }
+ r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
+ l.pos += l.width
+ return r
+}
+
+func (l *varLexer) run() {
+ for state := varLexNormal; state != nil; {
+ state = state(l)
+ }
+}
+
+func (l *varLexer) peek() rune {
+ r := l.next()
+ l.backup()
+ return r
+}
+
+func varLexNormal(l *varLexer) lexState {
+ for {
+ r := l.next()
+ switch {
+ case r == -1:
+ l.emit(tokEOF)
+ return nil
+ case r == '[':
+ l.emit(tokArrayStart)
+ case r == ']':
+ l.emit(tokArrayEnd)
+ case r == '{':
+ l.emit(tokDictStart)
+ case r == '}':
+ l.emit(tokDictEnd)
+ case r == '<':
+ l.emit(tokVariantStart)
+ case r == '>':
+ l.emit(tokVariantEnd)
+ case r == ':':
+ l.emit(tokColon)
+ case r == ',':
+ l.emit(tokComma)
+ case r == '\'' || r == '"':
+ l.backup()
+ return varLexString
+ case r == '@':
+ l.backup()
+ return varLexType
+ case unicode.IsSpace(r):
+ l.ignore()
+ case unicode.IsNumber(r) || r == '+' || r == '-':
+ l.backup()
+ return varLexNumber
+ case r == 'b':
+ pos := l.start
+ if n := l.peek(); n == '"' || n == '\'' {
+ return varLexByteString
+ }
+ // not a byte string; try to parse it as a type or bool below
+ l.pos = pos + 1
+ l.width = 1
+ fallthrough
+ default:
+ // either a bool or a type. Try bools first.
+ l.backup()
+ if l.pos+4 <= len(l.input) {
+ if l.input[l.pos:l.pos+4] == "true" {
+ l.pos += 4
+ l.emit(tokBool)
+ continue
+ }
+ }
+ if l.pos+5 <= len(l.input) {
+ if l.input[l.pos:l.pos+5] == "false" {
+ l.pos += 5
+ l.emit(tokBool)
+ continue
+ }
+ }
+ // must be a type.
+ return varLexType
+ }
+ }
+}
+
+var varTypeMap = map[string]string{
+ "boolean": "b",
+ "byte": "y",
+ "int16": "n",
+ "uint16": "q",
+ "int32": "i",
+ "uint32": "u",
+ "int64": "x",
+ "uint64": "t",
+ "double": "f",
+ "string": "s",
+ "objectpath": "o",
+ "signature": "g",
+}
+
+func varLexByteString(l *varLexer) lexState {
+ q := l.next()
+Loop:
+ for {
+ switch l.next() {
+ case '\\':
+ if r := l.next(); r != -1 {
+ break
+ }
+ fallthrough
+ case -1:
+ return l.errorf("unterminated bytestring")
+ case q:
+ break Loop
+ }
+ }
+ l.emit(tokByteString)
+ return varLexNormal
+}
+
+func varLexNumber(l *varLexer) lexState {
+ l.accept("+-")
+ digits := "0123456789"
+ if l.accept("0") {
+ if l.accept("x") {
+ digits = "0123456789abcdefABCDEF"
+ } else {
+ digits = "01234567"
+ }
+ }
+ for strings.IndexRune(digits, l.next()) >= 0 {
+ }
+ l.backup()
+ if l.accept(".") {
+ for strings.IndexRune(digits, l.next()) >= 0 {
+ }
+ l.backup()
+ }
+ if l.accept("eE") {
+ l.accept("+-")
+ for strings.IndexRune("0123456789", l.next()) >= 0 {
+ }
+ l.backup()
+ }
+ if r := l.peek(); unicode.IsLetter(r) {
+ l.next()
+ return l.errorf("bad number syntax: %q", l.input[l.start:l.pos])
+ }
+ l.emit(tokNumber)
+ return varLexNormal
+}
+
+func varLexString(l *varLexer) lexState {
+ q := l.next()
+Loop:
+ for {
+ switch l.next() {
+ case '\\':
+ if r := l.next(); r != -1 {
+ break
+ }
+ fallthrough
+ case -1:
+ return l.errorf("unterminated string")
+ case q:
+ break Loop
+ }
+ }
+ l.emit(tokString)
+ return varLexNormal
+}
+
+func varLexType(l *varLexer) lexState {
+ at := l.accept("@")
+ for {
+ r := l.next()
+ if r == -1 {
+ break
+ }
+ if unicode.IsSpace(r) {
+ l.backup()
+ break
+ }
+ }
+ if at {
+ if _, err := ParseSignature(l.input[l.start+1 : l.pos]); err != nil {
+ return l.errorf("%s", err)
+ }
+ } else {
+ if _, ok := varTypeMap[l.input[l.start:l.pos]]; ok {
+ l.emit(tokType)
+ return varLexNormal
+ }
+ return l.errorf("unrecognized type %q", l.input[l.start:l.pos])
+ }
+ l.emit(tokType)
+ return varLexNormal
+}
diff --git a/vendor/github.com/godbus/dbus/variant_parser.go b/vendor/github.com/godbus/dbus/variant_parser.go
new file mode 100644
index 0000000..d20f5da
--- /dev/null
+++ b/vendor/github.com/godbus/dbus/variant_parser.go
@@ -0,0 +1,817 @@
+package dbus
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "reflect"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+)
+
+type varParser struct {
+ tokens []varToken
+ i int
+}
+
+func (p *varParser) backup() {
+ p.i--
+}
+
+func (p *varParser) next() varToken {
+ if p.i < len(p.tokens) {
+ t := p.tokens[p.i]
+ p.i++
+ return t
+ }
+ return varToken{typ: tokEOF}
+}
+
+type varNode interface {
+ Infer() (Signature, error)
+ String() string
+ Sigs() sigSet
+ Value(Signature) (interface{}, error)
+}
+
+func varMakeNode(p *varParser) (varNode, error) {
+ var sig Signature
+
+ for {
+ t := p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ case tokNumber:
+ return varMakeNumNode(t, sig)
+ case tokString:
+ return varMakeStringNode(t, sig)
+ case tokBool:
+ if sig.str != "" && sig.str != "b" {
+ return nil, varTypeError{t.val, sig}
+ }
+ b, err := strconv.ParseBool(t.val)
+ if err != nil {
+ return nil, err
+ }
+ return boolNode(b), nil
+ case tokArrayStart:
+ return varMakeArrayNode(p, sig)
+ case tokVariantStart:
+ return varMakeVariantNode(p, sig)
+ case tokDictStart:
+ return varMakeDictNode(p, sig)
+ case tokType:
+ if sig.str != "" {
+ return nil, errors.New("unexpected type annotation")
+ }
+ if t.val[0] == '@' {
+ sig.str = t.val[1:]
+ } else {
+ sig.str = varTypeMap[t.val]
+ }
+ case tokByteString:
+ if sig.str != "" && sig.str != "ay" {
+ return nil, varTypeError{t.val, sig}
+ }
+ b, err := varParseByteString(t.val)
+ if err != nil {
+ return nil, err
+ }
+ return byteStringNode(b), nil
+ default:
+ return nil, fmt.Errorf("unexpected %q", t.val)
+ }
+ }
+}
+
+type varTypeError struct {
+ val string
+ sig Signature
+}
+
+func (e varTypeError) Error() string {
+ return fmt.Sprintf("dbus: can't parse %q as type %q", e.val, e.sig.str)
+}
+
+type sigSet map[Signature]bool
+
+func (s sigSet) Empty() bool {
+ return len(s) == 0
+}
+
+func (s sigSet) Intersect(s2 sigSet) sigSet {
+ r := make(sigSet)
+ for k := range s {
+ if s2[k] {
+ r[k] = true
+ }
+ }
+ return r
+}
+
+func (s sigSet) Single() (Signature, bool) {
+ if len(s) == 1 {
+ for k := range s {
+ return k, true
+ }
+ }
+ return Signature{}, false
+}
+
+func (s sigSet) ToArray() sigSet {
+ r := make(sigSet, len(s))
+ for k := range s {
+ r[Signature{"a" + k.str}] = true
+ }
+ return r
+}
+
+type numNode struct {
+ sig Signature
+ str string
+ val interface{}
+}
+
+var numSigSet = sigSet{
+ Signature{"y"}: true,
+ Signature{"n"}: true,
+ Signature{"q"}: true,
+ Signature{"i"}: true,
+ Signature{"u"}: true,
+ Signature{"x"}: true,
+ Signature{"t"}: true,
+ Signature{"d"}: true,
+}
+
+func (n numNode) Infer() (Signature, error) {
+ if strings.ContainsAny(n.str, ".e") {
+ return Signature{"d"}, nil
+ }
+ return Signature{"i"}, nil
+}
+
+func (n numNode) String() string {
+ return n.str
+}
+
+func (n numNode) Sigs() sigSet {
+ if n.sig.str != "" {
+ return sigSet{n.sig: true}
+ }
+ if strings.ContainsAny(n.str, ".e") {
+ return sigSet{Signature{"d"}: true}
+ }
+ return numSigSet
+}
+
+func (n numNode) Value(sig Signature) (interface{}, error) {
+ if n.sig.str != "" && n.sig != sig {
+ return nil, varTypeError{n.str, sig}
+ }
+ if n.val != nil {
+ return n.val, nil
+ }
+ return varNumAs(n.str, sig)
+}
+
+func varMakeNumNode(tok varToken, sig Signature) (varNode, error) {
+ if sig.str == "" {
+ return numNode{str: tok.val}, nil
+ }
+ num, err := varNumAs(tok.val, sig)
+ if err != nil {
+ return nil, err
+ }
+ return numNode{sig: sig, val: num}, nil
+}
+
+func varNumAs(s string, sig Signature) (interface{}, error) {
+ isUnsigned := false
+ size := 32
+ switch sig.str {
+ case "n":
+ size = 16
+ case "i":
+ case "x":
+ size = 64
+ case "y":
+ size = 8
+ isUnsigned = true
+ case "q":
+ size = 16
+ isUnsigned = true
+ case "u":
+ isUnsigned = true
+ case "t":
+ size = 64
+ isUnsigned = true
+ case "d":
+ d, err := strconv.ParseFloat(s, 64)
+ if err != nil {
+ return nil, err
+ }
+ return d, nil
+ default:
+ return nil, varTypeError{s, sig}
+ }
+ base := 10
+ if strings.HasPrefix(s, "0x") {
+ base = 16
+ s = s[2:]
+ }
+ if strings.HasPrefix(s, "0") && len(s) != 1 {
+ base = 8
+ s = s[1:]
+ }
+ if isUnsigned {
+ i, err := strconv.ParseUint(s, base, size)
+ if err != nil {
+ return nil, err
+ }
+ var v interface{} = i
+ switch sig.str {
+ case "y":
+ v = byte(i)
+ case "q":
+ v = uint16(i)
+ case "u":
+ v = uint32(i)
+ }
+ return v, nil
+ }
+ i, err := strconv.ParseInt(s, base, size)
+ if err != nil {
+ return nil, err
+ }
+ var v interface{} = i
+ switch sig.str {
+ case "n":
+ v = int16(i)
+ case "i":
+ v = int32(i)
+ }
+ return v, nil
+}
+
+type stringNode struct {
+ sig Signature
+ str string // parsed
+ val interface{} // has correct type
+}
+
+var stringSigSet = sigSet{
+ Signature{"s"}: true,
+ Signature{"g"}: true,
+ Signature{"o"}: true,
+}
+
+func (n stringNode) Infer() (Signature, error) {
+ return Signature{"s"}, nil
+}
+
+func (n stringNode) String() string {
+ return n.str
+}
+
+func (n stringNode) Sigs() sigSet {
+ if n.sig.str != "" {
+ return sigSet{n.sig: true}
+ }
+ return stringSigSet
+}
+
+func (n stringNode) Value(sig Signature) (interface{}, error) {
+ if n.sig.str != "" && n.sig != sig {
+ return nil, varTypeError{n.str, sig}
+ }
+ if n.val != nil {
+ return n.val, nil
+ }
+ switch {
+ case sig.str == "g":
+ return Signature{n.str}, nil
+ case sig.str == "o":
+ return ObjectPath(n.str), nil
+ case sig.str == "s":
+ return n.str, nil
+ default:
+ return nil, varTypeError{n.str, sig}
+ }
+}
+
+func varMakeStringNode(tok varToken, sig Signature) (varNode, error) {
+ if sig.str != "" && sig.str != "s" && sig.str != "g" && sig.str != "o" {
+ return nil, fmt.Errorf("invalid type %q for string", sig.str)
+ }
+ s, err := varParseString(tok.val)
+ if err != nil {
+ return nil, err
+ }
+ n := stringNode{str: s}
+ if sig.str == "" {
+ return stringNode{str: s}, nil
+ }
+ n.sig = sig
+ switch sig.str {
+ case "o":
+ n.val = ObjectPath(s)
+ case "g":
+ n.val = Signature{s}
+ case "s":
+ n.val = s
+ }
+ return n, nil
+}
+
+func varParseString(s string) (string, error) {
+ // quotes are guaranteed to be there
+ s = s[1 : len(s)-1]
+ buf := new(bytes.Buffer)
+ for len(s) != 0 {
+ r, size := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && size == 1 {
+ return "", errors.New("invalid UTF-8")
+ }
+ s = s[size:]
+ if r != '\\' {
+ buf.WriteRune(r)
+ continue
+ }
+ r, size = utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && size == 1 {
+ return "", errors.New("invalid UTF-8")
+ }
+ s = s[size:]
+ switch r {
+ case 'a':
+ buf.WriteRune(0x7)
+ case 'b':
+ buf.WriteRune(0x8)
+ case 'f':
+ buf.WriteRune(0xc)
+ case 'n':
+ buf.WriteRune('\n')
+ case 'r':
+ buf.WriteRune('\r')
+ case 't':
+ buf.WriteRune('\t')
+ case '\n':
+ case 'u':
+ if len(s) < 4 {
+ return "", errors.New("short unicode escape")
+ }
+ r, err := strconv.ParseUint(s[:4], 16, 32)
+ if err != nil {
+ return "", err
+ }
+ buf.WriteRune(rune(r))
+ s = s[4:]
+ case 'U':
+ if len(s) < 8 {
+ return "", errors.New("short unicode escape")
+ }
+ r, err := strconv.ParseUint(s[:8], 16, 32)
+ if err != nil {
+ return "", err
+ }
+ buf.WriteRune(rune(r))
+ s = s[8:]
+ default:
+ buf.WriteRune(r)
+ }
+ }
+ return buf.String(), nil
+}
+
+var boolSigSet = sigSet{Signature{"b"}: true}
+
+type boolNode bool
+
+func (boolNode) Infer() (Signature, error) {
+ return Signature{"b"}, nil
+}
+
+func (b boolNode) String() string {
+ if b {
+ return "true"
+ }
+ return "false"
+}
+
+func (boolNode) Sigs() sigSet {
+ return boolSigSet
+}
+
+func (b boolNode) Value(sig Signature) (interface{}, error) {
+ if sig.str != "b" {
+ return nil, varTypeError{b.String(), sig}
+ }
+ return bool(b), nil
+}
+
+type arrayNode struct {
+ set sigSet
+ children []varNode
+ val interface{}
+}
+
+func (n arrayNode) Infer() (Signature, error) {
+ for _, v := range n.children {
+ csig, err := varInfer(v)
+ if err != nil {
+ continue
+ }
+ return Signature{"a" + csig.str}, nil
+ }
+ return Signature{}, fmt.Errorf("can't infer type for %q", n.String())
+}
+
+func (n arrayNode) String() string {
+ s := "["
+ for i, v := range n.children {
+ s += v.String()
+ if i != len(n.children)-1 {
+ s += ", "
+ }
+ }
+ return s + "]"
+}
+
+func (n arrayNode) Sigs() sigSet {
+ return n.set
+}
+
+func (n arrayNode) Value(sig Signature) (interface{}, error) {
+ if n.set.Empty() {
+ // no type information whatsoever, so this must be an empty slice
+ return reflect.MakeSlice(typeFor(sig.str), 0, 0).Interface(), nil
+ }
+ if !n.set[sig] {
+ return nil, varTypeError{n.String(), sig}
+ }
+ s := reflect.MakeSlice(typeFor(sig.str), len(n.children), len(n.children))
+ for i, v := range n.children {
+ rv, err := v.Value(Signature{sig.str[1:]})
+ if err != nil {
+ return nil, err
+ }
+ s.Index(i).Set(reflect.ValueOf(rv))
+ }
+ return s.Interface(), nil
+}
+
+func varMakeArrayNode(p *varParser, sig Signature) (varNode, error) {
+ var n arrayNode
+ if sig.str != "" {
+ n.set = sigSet{sig: true}
+ }
+ if t := p.next(); t.typ == tokArrayEnd {
+ return n, nil
+ } else {
+ p.backup()
+ }
+Loop:
+ for {
+ t := p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ }
+ p.backup()
+ cn, err := varMakeNode(p)
+ if err != nil {
+ return nil, err
+ }
+ if cset := cn.Sigs(); !cset.Empty() {
+ if n.set.Empty() {
+ n.set = cset.ToArray()
+ } else {
+ nset := cset.ToArray().Intersect(n.set)
+ if nset.Empty() {
+ return nil, fmt.Errorf("can't parse %q with given type information", cn.String())
+ }
+ n.set = nset
+ }
+ }
+ n.children = append(n.children, cn)
+ switch t := p.next(); t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ case tokArrayEnd:
+ break Loop
+ case tokComma:
+ continue
+ default:
+ return nil, fmt.Errorf("unexpected %q", t.val)
+ }
+ }
+ return n, nil
+}
+
+type variantNode struct {
+ n varNode
+}
+
+var variantSet = sigSet{
+ Signature{"v"}: true,
+}
+
+func (variantNode) Infer() (Signature, error) {
+ return Signature{"v"}, nil
+}
+
+func (n variantNode) String() string {
+ return "<" + n.n.String() + ">"
+}
+
+func (variantNode) Sigs() sigSet {
+ return variantSet
+}
+
+func (n variantNode) Value(sig Signature) (interface{}, error) {
+ if sig.str != "v" {
+ return nil, varTypeError{n.String(), sig}
+ }
+ sig, err := varInfer(n.n)
+ if err != nil {
+ return nil, err
+ }
+ v, err := n.n.Value(sig)
+ if err != nil {
+ return nil, err
+ }
+ return MakeVariant(v), nil
+}
+
+func varMakeVariantNode(p *varParser, sig Signature) (varNode, error) {
+ n, err := varMakeNode(p)
+ if err != nil {
+ return nil, err
+ }
+ if t := p.next(); t.typ != tokVariantEnd {
+ return nil, fmt.Errorf("unexpected %q", t.val)
+ }
+ vn := variantNode{n}
+ if sig.str != "" && sig.str != "v" {
+ return nil, varTypeError{vn.String(), sig}
+ }
+ return variantNode{n}, nil
+}
+
+type dictEntry struct {
+ key, val varNode
+}
+
+type dictNode struct {
+ kset, vset sigSet
+ children []dictEntry
+ val interface{}
+}
+
+func (n dictNode) Infer() (Signature, error) {
+ for _, v := range n.children {
+ ksig, err := varInfer(v.key)
+ if err != nil {
+ continue
+ }
+ vsig, err := varInfer(v.val)
+ if err != nil {
+ continue
+ }
+ return Signature{"a{" + ksig.str + vsig.str + "}"}, nil
+ }
+ return Signature{}, fmt.Errorf("can't infer type for %q", n.String())
+}
+
+func (n dictNode) String() string {
+ s := "{"
+ for i, v := range n.children {
+ s += v.key.String() + ": " + v.val.String()
+ if i != len(n.children)-1 {
+ s += ", "
+ }
+ }
+ return s + "}"
+}
+
+func (n dictNode) Sigs() sigSet {
+ r := sigSet{}
+ for k := range n.kset {
+ for v := range n.vset {
+ sig := "a{" + k.str + v.str + "}"
+ r[Signature{sig}] = true
+ }
+ }
+ return r
+}
+
+func (n dictNode) Value(sig Signature) (interface{}, error) {
+ set := n.Sigs()
+ if set.Empty() {
+ // no type information -> empty dict
+ return reflect.MakeMap(typeFor(sig.str)).Interface(), nil
+ }
+ if !set[sig] {
+ return nil, varTypeError{n.String(), sig}
+ }
+ m := reflect.MakeMap(typeFor(sig.str))
+ ksig := Signature{sig.str[2:3]}
+ vsig := Signature{sig.str[3 : len(sig.str)-1]}
+ for _, v := range n.children {
+ kv, err := v.key.Value(ksig)
+ if err != nil {
+ return nil, err
+ }
+ vv, err := v.val.Value(vsig)
+ if err != nil {
+ return nil, err
+ }
+ m.SetMapIndex(reflect.ValueOf(kv), reflect.ValueOf(vv))
+ }
+ return m.Interface(), nil
+}
+
+func varMakeDictNode(p *varParser, sig Signature) (varNode, error) {
+ var n dictNode
+
+ if sig.str != "" {
+ if len(sig.str) < 5 {
+ return nil, fmt.Errorf("invalid signature %q for dict type", sig)
+ }
+ ksig := Signature{string(sig.str[2])}
+ vsig := Signature{sig.str[3 : len(sig.str)-1]}
+ n.kset = sigSet{ksig: true}
+ n.vset = sigSet{vsig: true}
+ }
+ if t := p.next(); t.typ == tokDictEnd {
+ return n, nil
+ } else {
+ p.backup()
+ }
+Loop:
+ for {
+ t := p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ }
+ p.backup()
+ kn, err := varMakeNode(p)
+ if err != nil {
+ return nil, err
+ }
+ if kset := kn.Sigs(); !kset.Empty() {
+ if n.kset.Empty() {
+ n.kset = kset
+ } else {
+ n.kset = kset.Intersect(n.kset)
+ if n.kset.Empty() {
+ return nil, fmt.Errorf("can't parse %q with given type information", kn.String())
+ }
+ }
+ }
+ t = p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ case tokColon:
+ default:
+ return nil, fmt.Errorf("unexpected %q", t.val)
+ }
+ t = p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ }
+ p.backup()
+ vn, err := varMakeNode(p)
+ if err != nil {
+ return nil, err
+ }
+ if vset := vn.Sigs(); !vset.Empty() {
+ if n.vset.Empty() {
+ n.vset = vset
+ } else {
+ n.vset = n.vset.Intersect(vset)
+ if n.vset.Empty() {
+ return nil, fmt.Errorf("can't parse %q with given type information", vn.String())
+ }
+ }
+ }
+ n.children = append(n.children, dictEntry{kn, vn})
+ t = p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ case tokDictEnd:
+ break Loop
+ case tokComma:
+ continue
+ default:
+ return nil, fmt.Errorf("unexpected %q", t.val)
+ }
+ }
+ return n, nil
+}
+
+type byteStringNode []byte
+
+var byteStringSet = sigSet{
+ Signature{"ay"}: true,
+}
+
+func (byteStringNode) Infer() (Signature, error) {
+ return Signature{"ay"}, nil
+}
+
+func (b byteStringNode) String() string {
+ return string(b)
+}
+
+func (b byteStringNode) Sigs() sigSet {
+ return byteStringSet
+}
+
+func (b byteStringNode) Value(sig Signature) (interface{}, error) {
+ if sig.str != "ay" {
+ return nil, varTypeError{b.String(), sig}
+ }
+ return []byte(b), nil
+}
+
+func varParseByteString(s string) ([]byte, error) {
+ // quotes and b at start are guaranteed to be there
+ b := make([]byte, 0, 1)
+ s = s[2 : len(s)-1]
+ for len(s) != 0 {
+ c := s[0]
+ s = s[1:]
+ if c != '\\' {
+ b = append(b, c)
+ continue
+ }
+ c = s[0]
+ s = s[1:]
+ switch c {
+ case 'a':
+ b = append(b, 0x7)
+ case 'b':
+ b = append(b, 0x8)
+ case 'f':
+ b = append(b, 0xc)
+ case 'n':
+ b = append(b, '\n')
+ case 'r':
+ b = append(b, '\r')
+ case 't':
+ b = append(b, '\t')
+ case 'x':
+ if len(s) < 2 {
+ return nil, errors.New("short escape")
+ }
+ n, err := strconv.ParseUint(s[:2], 16, 8)
+ if err != nil {
+ return nil, err
+ }
+ b = append(b, byte(n))
+ s = s[2:]
+ case '0':
+ if len(s) < 3 {
+ return nil, errors.New("short escape")
+ }
+ n, err := strconv.ParseUint(s[:3], 8, 8)
+ if err != nil {
+ return nil, err
+ }
+ b = append(b, byte(n))
+ s = s[3:]
+ default:
+ b = append(b, c)
+ }
+ }
+ return append(b, 0), nil
+}
+
+func varInfer(n varNode) (Signature, error) {
+ if sig, ok := n.Sigs().Single(); ok {
+ return sig, nil
+ }
+ return n.Infer()
+}
diff --git a/vendor/github.com/gogo/protobuf/LICENSE b/vendor/github.com/gogo/protobuf/LICENSE
new file mode 100644
index 0000000..7be0cc7
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/LICENSE
@@ -0,0 +1,36 @@
+Protocol Buffers for Go with Gadgets
+
+Copyright (c) 2013, The GoGo Authors. All rights reserved.
+http://github.com/gogo/protobuf
+
+Go support for Protocol Buffers - Google's data interchange format
+
+Copyright 2010 The Go Authors. All rights reserved.
+https://github.com/golang/protobuf
+
+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/gogo/protobuf/README b/vendor/github.com/gogo/protobuf/README
new file mode 100644
index 0000000..0ad5136
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/README
@@ -0,0 +1,258 @@
+GoGoProtobuf http://github.com/gogo/protobuf extends
+GoProtobuf http://github.com/golang/protobuf
+
+# Go support for Protocol Buffers
+
+Google's data interchange format.
+Copyright 2010 The Go Authors.
+https://github.com/golang/protobuf
+
+This package and the code it generates requires at least Go 1.4.
+
+This software implements Go bindings for protocol buffers. For
+information about protocol buffers themselves, see
+ https://developers.google.com/protocol-buffers/
+
+## Installation ##
+
+To use this software, you must:
+- Install the standard C++ implementation of protocol buffers from
+ https://developers.google.com/protocol-buffers/
+- Of course, install the Go compiler and tools from
+ https://golang.org/
+ See
+ https://golang.org/doc/install
+ for details or, if you are using gccgo, follow the instructions at
+ https://golang.org/doc/install/gccgo
+- Grab the code from the repository and install the proto package.
+ The simplest way is to run `go get -u github.com/golang/protobuf/{proto,protoc-gen-go}`.
+ The compiler plugin, protoc-gen-go, will be installed in $GOBIN,
+ defaulting to $GOPATH/bin. It must be in your $PATH for the protocol
+ compiler, protoc, to find it.
+
+This software has two parts: a 'protocol compiler plugin' that
+generates Go source files that, once compiled, can access and manage
+protocol buffers; and a library that implements run-time support for
+encoding (marshaling), decoding (unmarshaling), and accessing protocol
+buffers.
+
+There is support for gRPC in Go using protocol buffers.
+See the note at the bottom of this file for details.
+
+There are no insertion points in the plugin.
+
+GoGoProtobuf provides extensions for protocol buffers and GoProtobuf
+see http://github.com/gogo/protobuf/gogoproto/doc.go
+
+## Using protocol buffers with Go ##
+
+Once the software is installed, there are two steps to using it.
+First you must compile the protocol buffer definitions and then import
+them, with the support library, into your program.
+
+To compile the protocol buffer definition, run protoc with the --gogo_out
+parameter set to the directory you want to output the Go code to.
+
+ protoc --gogo_out=. *.proto
+
+The generated files will be suffixed .pb.go. See the Test code below
+for an example using such a file.
+
+The package comment for the proto library contains text describing
+the interface provided in Go for protocol buffers. Here is an edited
+version.
+
+If you are using any gogo.proto extensions you will need to specify the
+proto_path to include the descriptor.proto and gogo.proto.
+gogo.proto is located in github.com/gogo/protobuf/gogoproto
+This should be fine, since your import is the same.
+descriptor.proto is located in either github.com/gogo/protobuf/protobuf
+or code.google.com/p/protobuf/trunk/src/
+Its import is google/protobuf/descriptor.proto so it might need some help.
+
+ protoc --gogo_out=. -I=.:github.com/gogo/protobuf/protobuf *.proto
+
+==========
+
+The proto package converts data structures to and from the
+wire format of protocol buffers. It works in concert with the
+Go source code generated for .proto files by the protocol compiler.
+
+A summary of the properties of the protocol buffer interface
+for a protocol buffer variable v:
+
+ - Names are turned from camel_case to CamelCase for export.
+ - There are no methods on v to set fields; just treat
+ them as structure fields.
+ - There are getters that return a field's value if set,
+ and return the field's default value if unset.
+ The getters work even if the receiver is a nil message.
+ - The zero value for a struct is its correct initialization state.
+ All desired fields must be set before marshaling.
+ - A Reset() method will restore a protobuf struct to its zero state.
+ - Non-repeated fields are pointers to the values; nil means unset.
+ That is, optional or required field int32 f becomes F *int32.
+ - Repeated fields are slices.
+ - Helper functions are available to aid the setting of fields.
+ Helpers for getting values are superseded by the
+ GetFoo methods and their use is deprecated.
+ msg.Foo = proto.String("hello") // set field
+ - Constants are defined to hold the default values of all fields that
+ have them. They have the form Default_StructName_FieldName.
+ Because the getter methods handle defaulted values,
+ direct use of these constants should be rare.
+ - Enums are given type names and maps from names to values.
+ Enum values are prefixed with the enum's type name. Enum types have
+ a String method, and a Enum method to assist in message construction.
+ - Nested groups and enums have type names prefixed with the name of
+ the surrounding message type.
+ - Extensions are given descriptor names that start with E_,
+ followed by an underscore-delimited list of the nested messages
+ that contain it (if any) followed by the CamelCased name of the
+ extension field itself. HasExtension, ClearExtension, GetExtension
+ and SetExtension are functions for manipulating extensions.
+ - Oneof field sets are given a single field in their message,
+ with distinguished wrapper types for each possible field value.
+ - Marshal and Unmarshal are functions to encode and decode the wire format.
+
+When the .proto file specifies `syntax="proto3"`, there are some differences:
+
+ - Non-repeated fields of non-message type are values instead of pointers.
+ - Getters are only generated for message and oneof fields.
+ - Enum types do not get an Enum method.
+
+Consider file test.proto, containing
+
+```proto
+ package example;
+
+ enum FOO { X = 17; };
+
+ message Test {
+ required string label = 1;
+ optional int32 type = 2 [default=77];
+ repeated int64 reps = 3;
+ optional group OptionalGroup = 4 {
+ required string RequiredField = 5;
+ }
+ }
+```
+
+To create and play with a Test object from the example package,
+
+```go
+ package main
+
+ import (
+ "log"
+
+ "github.com/gogo/protobuf/proto"
+ "path/to/example"
+ )
+
+ func main() {
+ test := &example.Test {
+ Label: proto.String("hello"),
+ Type: proto.Int32(17),
+ Reps: []int64{1, 2, 3},
+ Optionalgroup: &example.Test_OptionalGroup {
+ RequiredField: proto.String("good bye"),
+ },
+ }
+ data, err := proto.Marshal(test)
+ if err != nil {
+ log.Fatal("marshaling error: ", err)
+ }
+ newTest := &example.Test{}
+ err = proto.Unmarshal(data, newTest)
+ if err != nil {
+ log.Fatal("unmarshaling error: ", err)
+ }
+ // Now test and newTest contain the same data.
+ if test.GetLabel() != newTest.GetLabel() {
+ log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
+ }
+ // etc.
+ }
+```
+
+
+## Parameters ##
+
+To pass extra parameters to the plugin, use a comma-separated
+parameter list separated from the output directory by a colon:
+
+
+ protoc --gogo_out=plugins=grpc,import_path=mypackage:. *.proto
+
+
+- `import_prefix=xxx` - a prefix that is added onto the beginning of
+ all imports. Useful for things like generating protos in a
+ subdirectory, or regenerating vendored protobufs in-place.
+- `import_path=foo/bar` - used as the package if no input files
+ declare `go_package`. If it contains slashes, everything up to the
+ rightmost slash is ignored.
+- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to
+ load. The only plugin in this repo is `grpc`.
+- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is
+ associated with Go package quux/shme. This is subject to the
+ import_prefix parameter.
+
+## gRPC Support ##
+
+If a proto file specifies RPC services, protoc-gen-go can be instructed to
+generate code compatible with gRPC (http://www.grpc.io/). To do this, pass
+the `plugins` parameter to protoc-gen-go; the usual way is to insert it into
+the --go_out argument to protoc:
+
+ protoc --gogo_out=plugins=grpc:. *.proto
+
+## Compatibility ##
+
+The library and the generated code are expected to be stable over time.
+However, we reserve the right to make breaking changes without notice for the
+following reasons:
+
+- Security. A security issue in the specification or implementation may come to
+ light whose resolution requires breaking compatibility. We reserve the right
+ to address such security issues.
+- Unspecified behavior. There are some aspects of the Protocol Buffers
+ specification that are undefined. Programs that depend on such unspecified
+ behavior may break in future releases.
+- Specification errors or changes. If it becomes necessary to address an
+ inconsistency, incompleteness, or change in the Protocol Buffers
+ specification, resolving the issue could affect the meaning or legality of
+ existing programs. We reserve the right to address such issues, including
+ updating the implementations.
+- Bugs. If the library has a bug that violates the specification, a program
+ that depends on the buggy behavior may break if the bug is fixed. We reserve
+ the right to fix such bugs.
+- Adding methods or fields to generated structs. These may conflict with field
+ names that already exist in a schema, causing applications to break. When the
+ code generator encounters a field in the schema that would collide with a
+ generated field or method name, the code generator will append an underscore
+ to the generated field or method name.
+- Adding, removing, or changing methods or fields in generated structs that
+ start with `XXX`. These parts of the generated code are exported out of
+ necessity, but should not be considered part of the public API.
+- Adding, removing, or changing unexported symbols in generated code.
+
+Any breaking changes outside of these will be announced 6 months in advance to
+protobuf@googlegroups.com.
+
+You should, whenever possible, use generated code created by the `protoc-gen-go`
+tool built at the same commit as the `proto` package. The `proto` package
+declares package-level constants in the form `ProtoPackageIsVersionX`.
+Application code and generated code may depend on one of these constants to
+ensure that compilation will fail if the available version of the proto library
+is too old. Whenever we make a change to the generated code that requires newer
+library support, in the same commit we will increment the version number of the
+generated code and declare a new package-level constant whose name incorporates
+the latest version number. Removing a compatibility constant is considered a
+breaking change and would be subject to the announcement policy stated above.
+
+## Plugins ##
+
+The `protoc-gen-go/generator` package exposes a plugin interface,
+which is used by the gRPC code generation. This interface is not
+supported and is subject to incompatible changes without notice.
diff --git a/vendor/github.com/gogo/protobuf/Readme.md b/vendor/github.com/gogo/protobuf/Readme.md
new file mode 100644
index 0000000..d31c13f
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/Readme.md
@@ -0,0 +1,117 @@
+# Protocol Buffers for Go with Gadgets
+
+[![Build Status](https://travis-ci.org/gogo/protobuf.svg?branch=master)](https://travis-ci.org/gogo/protobuf)
+
+gogoprotobuf is a fork of <a href="https://github.com/golang/protobuf">golang/protobuf</a> with extra code generation features.
+
+This code generation is used to achieve:
+
+ - fast marshalling and unmarshalling
+ - more canonical Go structures
+ - goprotobuf compatibility
+ - less typing by optionally generating extra helper code
+ - peace of mind by optionally generating test and benchmark code
+ - other serialization formats
+
+Keeping track of how up to date gogoprotobuf is relative to golang/protobuf is done in this
+<a href="https://github.com/gogo/protobuf/issues/191">issue</a>
+
+## Users
+
+These projects use gogoprotobuf:
+
+ - <a href="http://godoc.org/github.com/coreos/etcd">etcd</a> - <a href="https://blog.gopheracademy.com/advent-2015/etcd-distributed-key-value-store-with-grpc-http2/">blog</a> - <a href="https://github.com/coreos/etcd/blob/master/etcdserver/etcdserverpb/etcdserver.proto">sample proto file</a>
+ - <a href="https://www.spacemonkey.com/">spacemonkey</a> - <a href="https://www.spacemonkey.com/blog/posts/go-space-monkey">blog</a>
+ - <a href="http://badoo.com">badoo</a> - <a href="https://github.com/badoo/lsd/blob/32061f501c5eca9c76c596d790b450501ba27b2f/proto/lsd.proto">sample proto file</a>
+ - <a href="https://github.com/mesos/mesos-go">mesos-go</a> - <a href="https://github.com/mesos/mesos-go/blob/f9e5fb7c2f50ab5f23299f26b6b07c5d6afdd252/api/v0/mesosproto/authentication.proto">sample proto file</a>
+ - <a href="https://github.com/mozilla-services/heka">heka</a> - <a href="https://github.com/mozilla-services/heka/commit/eb72fbf7d2d28249fbaf8d8dc6607f4eb6f03351">the switch from golang/protobuf to gogo/protobuf when it was still on code.google.com</a>
+ - <a href="https://github.com/cockroachdb/cockroach">cockroachdb</a> - <a href="https://github.com/cockroachdb/cockroach/blob/651d54d393e391a30154e9117ab4b18d9ee6d845/roachpb/metadata.proto">sample proto file</a>
+ - <a href="https://github.com/jbenet/go-ipfs">go-ipfs</a> - <a href="https://github.com/ipfs/go-ipfs/blob/2b6da0c024f28abeb16947fb452787196a6b56a2/merkledag/pb/merkledag.proto">sample proto file</a>
+ - <a href="https://github.com/philhofer/rkive">rkive-go</a> - <a href="https://github.com/philhofer/rkive/blob/e5dd884d3ea07b341321073882ae28aa16dd11be/rpbc/riak_dt.proto">sample proto file</a>
+ - <a href="https://www.dropbox.com">dropbox</a>
+ - <a href="https://srclib.org/">srclib</a> - <a href="https://github.com/sourcegraph/srclib/blob/6538858f0c410cac5c63440317b8d009e889d3fb/graph/def.proto">sample proto file</a>
+ - <a href="http://www.adyoulike.com/">adyoulike</a>
+ - <a href="http://www.cloudfoundry.org/">cloudfoundry</a> - <a href="https://github.com/cloudfoundry/bbs/blob/d673710b8c4211037805129944ee4c5373d6588a/models/events.proto">sample proto file</a>
+ - <a href="http://kubernetes.io/">kubernetes</a> - <a href="https://github.com/kubernetes/kubernetes/tree/88d8628137f94ee816aaa6606ae8cd045dee0bff/cmd/libs/go2idl">go2idl built on top of gogoprotobuf</a>
+ - <a href="https://dgraph.io/">dgraph</a> - <a href="https://github.com/dgraph-io/dgraph/releases/tag/v0.4.3">release notes</a> - <a href="https://discuss.dgraph.io/t/gogoprotobuf-is-extremely-fast/639">benchmarks</a></a>
+ - <a href="https://github.com/centrifugal/centrifugo">centrifugo</a> - <a href="https://forum.golangbridge.org/t/centrifugo-real-time-messaging-websocket-or-sockjs-server-v1-5-0-released/2861">release notes</a> - <a href="https://medium.com/@fzambia/centrifugo-protobuf-inside-json-outside-21d39bdabd68#.o3icmgjqd">blog</a>
+ - <a href="https://github.com/docker/swarmkit">docker swarmkit</a> - <a href="https://github.com/docker/swarmkit/blob/63600e01af3b8da2a0ed1c9fa6e1ae4299d75edb/api/objects.proto">sample proto file</a>
+ - <a href="https://nats.io/">nats.io</a> - <a href="https://github.com/nats-io/go-nats-streaming/blob/master/pb/protocol.proto">go-nats-streaming</a>
+ - <a href="https://github.com/pingcap/tidb">tidb</a> - Communication between <a href="https://github.com/pingcap/tipb/blob/master/generate-go.sh#L4">tidb</a> and <a href="https://github.com/pingcap/kvproto/blob/master/generate_go.sh#L3">tikv</a>
+ - <a href="https://github.com/AsynkronIT/protoactor-go">protoactor-go</a> - <a href="https://github.com/AsynkronIT/protoactor-go/blob/dev/protobuf/protoc-gen-protoactor/main.go">vanity command</a> that also generates actors from service definitions
+
+Please lets us know if you are using gogoprotobuf by posting on our <a href="https://groups.google.com/forum/#!topic/gogoprotobuf/Brw76BxmFpQ">GoogleGroup</a>.
+
+### Mentioned
+
+ - <a href="http://www.slideshare.net/albertstrasheim/serialization-in-go">Cloudflare - go serialization talk - Albert Strasheim</a>
+ - <a href="http://gophercon.sourcegraph.com/post/83747547505/writing-a-high-performance-database-in-go">gophercon</a>
+ - <a href="https://github.com/alecthomas/go_serialization_benchmarks">alecthomas' go serialization benchmarks</a>
+
+## Getting Started
+
+There are several ways to use gogoprotobuf, but for all you need to install go and protoc.
+After that you can choose:
+
+ - Speed
+ - More Speed and more generated code
+ - Most Speed and most customization
+
+### Installation
+
+To install it, you must first have Go (at least version 1.6.3) installed (see [http://golang.org/doc/install](http://golang.org/doc/install)). Go 1.7.1 and 1.8 is continuously tested.
+
+Next, install the standard protocol buffer implementation from [https://github.com/google/protobuf](https://github.com/google/protobuf).
+Most versions from 2.3.1 should not give any problems, but 2.6.1, 3.0.2 and 3.1.0 are continuously tested.
+
+### Speed
+
+Install the protoc-gen-gofast binary
+
+ go get github.com/gogo/protobuf/protoc-gen-gofast
+
+Use it to generate faster marshaling and unmarshaling go code for your protocol buffers.
+
+ protoc --gofast_out=. myproto.proto
+
+This does not allow you to use any of the other gogoprotobuf [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md).
+
+### More Speed and more generated code
+
+Fields without pointers cause less time in the garbage collector.
+More code generation results in more convenient methods.
+
+Other binaries are also included:
+
+ protoc-gen-gogofast (same as gofast, but imports gogoprotobuf)
+ protoc-gen-gogofaster (same as gogofast, without XXX_unrecognized, less pointer fields)
+ protoc-gen-gogoslick (same as gogofaster, but with generated string, gostring and equal methods)
+
+Installing any of these binaries is easy. Simply run:
+
+ go get github.com/gogo/protobuf/proto
+ go get github.com/gogo/protobuf/{binary}
+ go get github.com/gogo/protobuf/gogoproto
+
+These binaries allow you to using gogoprotobuf [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md).
+
+### Most Speed and most customization
+
+Customizing the fields of the messages to be the fields that you actually want to use removes the need to copy between the structs you use and structs you use to serialize.
+gogoprotobuf also offers more serialization formats and generation of tests and even more methods.
+
+Please visit the [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md) page for more documentation.
+
+Install protoc-gen-gogo:
+
+ go get github.com/gogo/protobuf/proto
+ go get github.com/gogo/protobuf/jsonpb
+ go get github.com/gogo/protobuf/protoc-gen-gogo
+ go get github.com/gogo/protobuf/gogoproto
+
+## GRPC
+
+It works the same as golang/protobuf, simply specify the plugin.
+Here is an example using gofast:
+
+ protoc --gofast_out=plugins=grpc:. my.proto
diff --git a/vendor/github.com/gogo/protobuf/gogoproto/doc.go b/vendor/github.com/gogo/protobuf/gogoproto/doc.go
new file mode 100644
index 0000000..147b5ec
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/gogoproto/doc.go
@@ -0,0 +1,169 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 gogoproto provides extensions for protocol buffers to achieve:
+
+ - fast marshalling and unmarshalling.
+ - peace of mind by optionally generating test and benchmark code.
+ - more canonical Go structures.
+ - less typing by optionally generating extra helper code.
+ - goprotobuf compatibility
+
+More Canonical Go Structures
+
+A lot of time working with a goprotobuf struct will lead you to a place where you create another struct that is easier to work with and then have a function to copy the values between the two structs.
+You might also find that basic structs that started their life as part of an API need to be sent over the wire. With gob, you could just send it. With goprotobuf, you need to make a parallel struct.
+Gogoprotobuf tries to fix these problems with the nullable, embed, customtype and customname field extensions.
+
+ - nullable, if false, a field is generated without a pointer (see warning below).
+ - embed, if true, the field is generated as an embedded field.
+ - customtype, It works with the Marshal and Unmarshal methods, to allow you to have your own types in your struct, but marshal to bytes. For example, custom.Uuid or custom.Fixed128
+ - customname (beta), Changes the generated fieldname. This is especially useful when generated methods conflict with fieldnames.
+ - casttype (beta), Changes the generated fieldtype. All generated code assumes that this type is castable to the protocol buffer field type. It does not work for structs or enums.
+ - castkey (beta), Changes the generated fieldtype for a map key. All generated code assumes that this type is castable to the protocol buffer field type. Only supported on maps.
+ - castvalue (beta), Changes the generated fieldtype for a map value. All generated code assumes that this type is castable to the protocol buffer field type. Only supported on maps.
+
+Warning about nullable: According to the Protocol Buffer specification, you should be able to tell whether a field is set or unset. With the option nullable=false this feature is lost, since your non-nullable fields will always be set. It can be seen as a layer on top of Protocol Buffers, where before and after marshalling all non-nullable fields are set and they cannot be unset.
+
+Let us look at:
+
+ github.com/gogo/protobuf/test/example/example.proto
+
+for a quicker overview.
+
+The following message:
+
+ package test;
+
+ import "github.com/gogo/protobuf/gogoproto/gogo.proto";
+
+ message A {
+ optional string Description = 1 [(gogoproto.nullable) = false];
+ optional int64 Number = 2 [(gogoproto.nullable) = false];
+ optional bytes Id = 3 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uuid", (gogoproto.nullable) = false];
+ }
+
+Will generate a go struct which looks a lot like this:
+
+ type A struct {
+ Description string
+ Number int64
+ Id github_com_gogo_protobuf_test_custom.Uuid
+ }
+
+You will see there are no pointers, since all fields are non-nullable.
+You will also see a custom type which marshals to a string.
+Be warned it is your responsibility to test your custom types thoroughly.
+You should think of every possible empty and nil case for your marshaling, unmarshaling and size methods.
+
+Next we will embed the message A in message B.
+
+ message B {
+ optional A A = 1 [(gogoproto.nullable) = false, (gogoproto.embed) = true];
+ repeated bytes G = 2 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uint128", (gogoproto.nullable) = false];
+ }
+
+See below that A is embedded in B.
+
+ type B struct {
+ A
+ G []github_com_gogo_protobuf_test_custom.Uint128
+ }
+
+Also see the repeated custom type.
+
+ type Uint128 [2]uint64
+
+Next we will create a custom name for one of our fields.
+
+ message C {
+ optional int64 size = 1 [(gogoproto.customname) = "MySize"];
+ }
+
+See below that the field's name is MySize and not Size.
+
+ type C struct {
+ MySize *int64
+ }
+
+The is useful when having a protocol buffer message with a field name which conflicts with a generated method.
+As an example, having a field name size and using the sizer plugin to generate a Size method will cause a go compiler error.
+Using customname you can fix this error without changing the field name.
+This is typically useful when working with a protocol buffer that was designed before these methods and/or the go language were avialable.
+
+Gogoprotobuf also has some more subtle changes, these could be changed back:
+
+ - the generated package name for imports do not have the extra /filename.pb,
+ but are actually the imports specified in the .proto file.
+
+Gogoprotobuf also has lost some features which should be brought back with time:
+
+ - Marshalling and unmarshalling with reflect and without the unsafe package,
+ this requires work in pointer_reflect.go
+
+Why does nullable break protocol buffer specifications:
+
+The protocol buffer specification states, somewhere, that you should be able to tell whether a
+field is set or unset. With the option nullable=false this feature is lost,
+since your non-nullable fields will always be set. It can be seen as a layer on top of
+protocol buffers, where before and after marshalling all non-nullable fields are set
+and they cannot be unset.
+
+Goprotobuf Compatibility:
+
+Gogoprotobuf is compatible with Goprotobuf, because it is compatible with protocol buffers.
+Gogoprotobuf generates the same code as goprotobuf if no extensions are used.
+The enumprefix, getters and stringer extensions can be used to remove some of the unnecessary code generated by goprotobuf:
+
+ - gogoproto_import, if false, the generated code imports github.com/golang/protobuf/proto instead of github.com/gogo/protobuf/proto.
+ - goproto_enum_prefix, if false, generates the enum constant names without the messagetype prefix
+ - goproto_enum_stringer (experimental), if false, the enum is generated without the default string method, this is useful for rather using enum_stringer, or allowing you to write your own string method.
+ - goproto_getters, if false, the message is generated without get methods, this is useful when you would rather want to use face
+ - goproto_stringer, if false, the message is generated without the default string method, this is useful for rather using stringer, or allowing you to write your own string method.
+ - goproto_extensions_map (beta), if false, the extensions field is generated as type []byte instead of type map[int32]proto.Extension
+ - goproto_unrecognized (beta), if false, XXX_unrecognized field is not generated. This is useful in conjunction with gogoproto.nullable=false, to generate structures completely devoid of pointers and reduce GC pressure at the cost of losing information about unrecognized fields.
+ - goproto_registration (beta), if true, the generated files will register all messages and types against both gogo/protobuf and golang/protobuf. This is necessary when using third-party packages which read registrations from golang/protobuf (such as the grpc-gateway).
+
+Less Typing and Peace of Mind is explained in their specific plugin folders godoc:
+
+ - github.com/gogo/protobuf/plugin/<extension_name>
+
+If you do not use any of these extension the code that is generated
+will be the same as if goprotobuf has generated it.
+
+The most complete way to see examples is to look at
+
+ github.com/gogo/protobuf/test/thetest.proto
+
+Gogoprototest is a seperate project,
+because we want to keep gogoprotobuf independant of goprotobuf,
+but we still want to test it thoroughly.
+
+*/
+package gogoproto
diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go
new file mode 100644
index 0000000..9506b6f
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go
@@ -0,0 +1,804 @@
+// Code generated by protoc-gen-gogo.
+// source: gogo.proto
+// DO NOT EDIT!
+
+/*
+Package gogoproto is a generated protocol buffer package.
+
+It is generated from these files:
+ gogo.proto
+
+It has these top-level messages:
+*/
+package gogoproto
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+var E_GoprotoEnumPrefix = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.EnumOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 62001,
+ Name: "gogoproto.goproto_enum_prefix",
+ Tag: "varint,62001,opt,name=goproto_enum_prefix,json=goprotoEnumPrefix",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoEnumStringer = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.EnumOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 62021,
+ Name: "gogoproto.goproto_enum_stringer",
+ Tag: "varint,62021,opt,name=goproto_enum_stringer,json=goprotoEnumStringer",
+ Filename: "gogo.proto",
+}
+
+var E_EnumStringer = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.EnumOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 62022,
+ Name: "gogoproto.enum_stringer",
+ Tag: "varint,62022,opt,name=enum_stringer,json=enumStringer",
+ Filename: "gogo.proto",
+}
+
+var E_EnumCustomname = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.EnumOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 62023,
+ Name: "gogoproto.enum_customname",
+ Tag: "bytes,62023,opt,name=enum_customname,json=enumCustomname",
+ Filename: "gogo.proto",
+}
+
+var E_Enumdecl = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.EnumOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 62024,
+ Name: "gogoproto.enumdecl",
+ Tag: "varint,62024,opt,name=enumdecl",
+ Filename: "gogo.proto",
+}
+
+var E_EnumvalueCustomname = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.EnumValueOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 66001,
+ Name: "gogoproto.enumvalue_customname",
+ Tag: "bytes,66001,opt,name=enumvalue_customname,json=enumvalueCustomname",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoGettersAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63001,
+ Name: "gogoproto.goproto_getters_all",
+ Tag: "varint,63001,opt,name=goproto_getters_all,json=goprotoGettersAll",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoEnumPrefixAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63002,
+ Name: "gogoproto.goproto_enum_prefix_all",
+ Tag: "varint,63002,opt,name=goproto_enum_prefix_all,json=goprotoEnumPrefixAll",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoStringerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63003,
+ Name: "gogoproto.goproto_stringer_all",
+ Tag: "varint,63003,opt,name=goproto_stringer_all,json=goprotoStringerAll",
+ Filename: "gogo.proto",
+}
+
+var E_VerboseEqualAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63004,
+ Name: "gogoproto.verbose_equal_all",
+ Tag: "varint,63004,opt,name=verbose_equal_all,json=verboseEqualAll",
+ Filename: "gogo.proto",
+}
+
+var E_FaceAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63005,
+ Name: "gogoproto.face_all",
+ Tag: "varint,63005,opt,name=face_all,json=faceAll",
+ Filename: "gogo.proto",
+}
+
+var E_GostringAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63006,
+ Name: "gogoproto.gostring_all",
+ Tag: "varint,63006,opt,name=gostring_all,json=gostringAll",
+ Filename: "gogo.proto",
+}
+
+var E_PopulateAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63007,
+ Name: "gogoproto.populate_all",
+ Tag: "varint,63007,opt,name=populate_all,json=populateAll",
+ Filename: "gogo.proto",
+}
+
+var E_StringerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63008,
+ Name: "gogoproto.stringer_all",
+ Tag: "varint,63008,opt,name=stringer_all,json=stringerAll",
+ Filename: "gogo.proto",
+}
+
+var E_OnlyoneAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63009,
+ Name: "gogoproto.onlyone_all",
+ Tag: "varint,63009,opt,name=onlyone_all,json=onlyoneAll",
+ Filename: "gogo.proto",
+}
+
+var E_EqualAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63013,
+ Name: "gogoproto.equal_all",
+ Tag: "varint,63013,opt,name=equal_all,json=equalAll",
+ Filename: "gogo.proto",
+}
+
+var E_DescriptionAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63014,
+ Name: "gogoproto.description_all",
+ Tag: "varint,63014,opt,name=description_all,json=descriptionAll",
+ Filename: "gogo.proto",
+}
+
+var E_TestgenAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63015,
+ Name: "gogoproto.testgen_all",
+ Tag: "varint,63015,opt,name=testgen_all,json=testgenAll",
+ Filename: "gogo.proto",
+}
+
+var E_BenchgenAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63016,
+ Name: "gogoproto.benchgen_all",
+ Tag: "varint,63016,opt,name=benchgen_all,json=benchgenAll",
+ Filename: "gogo.proto",
+}
+
+var E_MarshalerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63017,
+ Name: "gogoproto.marshaler_all",
+ Tag: "varint,63017,opt,name=marshaler_all,json=marshalerAll",
+ Filename: "gogo.proto",
+}
+
+var E_UnmarshalerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63018,
+ Name: "gogoproto.unmarshaler_all",
+ Tag: "varint,63018,opt,name=unmarshaler_all,json=unmarshalerAll",
+ Filename: "gogo.proto",
+}
+
+var E_StableMarshalerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63019,
+ Name: "gogoproto.stable_marshaler_all",
+ Tag: "varint,63019,opt,name=stable_marshaler_all,json=stableMarshalerAll",
+ Filename: "gogo.proto",
+}
+
+var E_SizerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63020,
+ Name: "gogoproto.sizer_all",
+ Tag: "varint,63020,opt,name=sizer_all,json=sizerAll",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoEnumStringerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63021,
+ Name: "gogoproto.goproto_enum_stringer_all",
+ Tag: "varint,63021,opt,name=goproto_enum_stringer_all,json=goprotoEnumStringerAll",
+ Filename: "gogo.proto",
+}
+
+var E_EnumStringerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63022,
+ Name: "gogoproto.enum_stringer_all",
+ Tag: "varint,63022,opt,name=enum_stringer_all,json=enumStringerAll",
+ Filename: "gogo.proto",
+}
+
+var E_UnsafeMarshalerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63023,
+ Name: "gogoproto.unsafe_marshaler_all",
+ Tag: "varint,63023,opt,name=unsafe_marshaler_all,json=unsafeMarshalerAll",
+ Filename: "gogo.proto",
+}
+
+var E_UnsafeUnmarshalerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63024,
+ Name: "gogoproto.unsafe_unmarshaler_all",
+ Tag: "varint,63024,opt,name=unsafe_unmarshaler_all,json=unsafeUnmarshalerAll",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoExtensionsMapAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63025,
+ Name: "gogoproto.goproto_extensions_map_all",
+ Tag: "varint,63025,opt,name=goproto_extensions_map_all,json=goprotoExtensionsMapAll",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoUnrecognizedAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63026,
+ Name: "gogoproto.goproto_unrecognized_all",
+ Tag: "varint,63026,opt,name=goproto_unrecognized_all,json=goprotoUnrecognizedAll",
+ Filename: "gogo.proto",
+}
+
+var E_GogoprotoImport = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63027,
+ Name: "gogoproto.gogoproto_import",
+ Tag: "varint,63027,opt,name=gogoproto_import,json=gogoprotoImport",
+ Filename: "gogo.proto",
+}
+
+var E_ProtosizerAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63028,
+ Name: "gogoproto.protosizer_all",
+ Tag: "varint,63028,opt,name=protosizer_all,json=protosizerAll",
+ Filename: "gogo.proto",
+}
+
+var E_CompareAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63029,
+ Name: "gogoproto.compare_all",
+ Tag: "varint,63029,opt,name=compare_all,json=compareAll",
+ Filename: "gogo.proto",
+}
+
+var E_TypedeclAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63030,
+ Name: "gogoproto.typedecl_all",
+ Tag: "varint,63030,opt,name=typedecl_all,json=typedeclAll",
+ Filename: "gogo.proto",
+}
+
+var E_EnumdeclAll = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63031,
+ Name: "gogoproto.enumdecl_all",
+ Tag: "varint,63031,opt,name=enumdecl_all,json=enumdeclAll",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoRegistration = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63032,
+ Name: "gogoproto.goproto_registration",
+ Tag: "varint,63032,opt,name=goproto_registration,json=goprotoRegistration",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoGetters = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64001,
+ Name: "gogoproto.goproto_getters",
+ Tag: "varint,64001,opt,name=goproto_getters,json=goprotoGetters",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoStringer = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64003,
+ Name: "gogoproto.goproto_stringer",
+ Tag: "varint,64003,opt,name=goproto_stringer,json=goprotoStringer",
+ Filename: "gogo.proto",
+}
+
+var E_VerboseEqual = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64004,
+ Name: "gogoproto.verbose_equal",
+ Tag: "varint,64004,opt,name=verbose_equal,json=verboseEqual",
+ Filename: "gogo.proto",
+}
+
+var E_Face = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64005,
+ Name: "gogoproto.face",
+ Tag: "varint,64005,opt,name=face",
+ Filename: "gogo.proto",
+}
+
+var E_Gostring = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64006,
+ Name: "gogoproto.gostring",
+ Tag: "varint,64006,opt,name=gostring",
+ Filename: "gogo.proto",
+}
+
+var E_Populate = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64007,
+ Name: "gogoproto.populate",
+ Tag: "varint,64007,opt,name=populate",
+ Filename: "gogo.proto",
+}
+
+var E_Stringer = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 67008,
+ Name: "gogoproto.stringer",
+ Tag: "varint,67008,opt,name=stringer",
+ Filename: "gogo.proto",
+}
+
+var E_Onlyone = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64009,
+ Name: "gogoproto.onlyone",
+ Tag: "varint,64009,opt,name=onlyone",
+ Filename: "gogo.proto",
+}
+
+var E_Equal = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64013,
+ Name: "gogoproto.equal",
+ Tag: "varint,64013,opt,name=equal",
+ Filename: "gogo.proto",
+}
+
+var E_Description = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64014,
+ Name: "gogoproto.description",
+ Tag: "varint,64014,opt,name=description",
+ Filename: "gogo.proto",
+}
+
+var E_Testgen = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64015,
+ Name: "gogoproto.testgen",
+ Tag: "varint,64015,opt,name=testgen",
+ Filename: "gogo.proto",
+}
+
+var E_Benchgen = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64016,
+ Name: "gogoproto.benchgen",
+ Tag: "varint,64016,opt,name=benchgen",
+ Filename: "gogo.proto",
+}
+
+var E_Marshaler = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64017,
+ Name: "gogoproto.marshaler",
+ Tag: "varint,64017,opt,name=marshaler",
+ Filename: "gogo.proto",
+}
+
+var E_Unmarshaler = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64018,
+ Name: "gogoproto.unmarshaler",
+ Tag: "varint,64018,opt,name=unmarshaler",
+ Filename: "gogo.proto",
+}
+
+var E_StableMarshaler = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64019,
+ Name: "gogoproto.stable_marshaler",
+ Tag: "varint,64019,opt,name=stable_marshaler,json=stableMarshaler",
+ Filename: "gogo.proto",
+}
+
+var E_Sizer = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64020,
+ Name: "gogoproto.sizer",
+ Tag: "varint,64020,opt,name=sizer",
+ Filename: "gogo.proto",
+}
+
+var E_UnsafeMarshaler = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64023,
+ Name: "gogoproto.unsafe_marshaler",
+ Tag: "varint,64023,opt,name=unsafe_marshaler,json=unsafeMarshaler",
+ Filename: "gogo.proto",
+}
+
+var E_UnsafeUnmarshaler = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64024,
+ Name: "gogoproto.unsafe_unmarshaler",
+ Tag: "varint,64024,opt,name=unsafe_unmarshaler,json=unsafeUnmarshaler",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoExtensionsMap = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64025,
+ Name: "gogoproto.goproto_extensions_map",
+ Tag: "varint,64025,opt,name=goproto_extensions_map,json=goprotoExtensionsMap",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoUnrecognized = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64026,
+ Name: "gogoproto.goproto_unrecognized",
+ Tag: "varint,64026,opt,name=goproto_unrecognized,json=goprotoUnrecognized",
+ Filename: "gogo.proto",
+}
+
+var E_Protosizer = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64028,
+ Name: "gogoproto.protosizer",
+ Tag: "varint,64028,opt,name=protosizer",
+ Filename: "gogo.proto",
+}
+
+var E_Compare = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64029,
+ Name: "gogoproto.compare",
+ Tag: "varint,64029,opt,name=compare",
+ Filename: "gogo.proto",
+}
+
+var E_Typedecl = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64030,
+ Name: "gogoproto.typedecl",
+ Tag: "varint,64030,opt,name=typedecl",
+ Filename: "gogo.proto",
+}
+
+var E_Nullable = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 65001,
+ Name: "gogoproto.nullable",
+ Tag: "varint,65001,opt,name=nullable",
+ Filename: "gogo.proto",
+}
+
+var E_Embed = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 65002,
+ Name: "gogoproto.embed",
+ Tag: "varint,65002,opt,name=embed",
+ Filename: "gogo.proto",
+}
+
+var E_Customtype = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65003,
+ Name: "gogoproto.customtype",
+ Tag: "bytes,65003,opt,name=customtype",
+ Filename: "gogo.proto",
+}
+
+var E_Customname = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65004,
+ Name: "gogoproto.customname",
+ Tag: "bytes,65004,opt,name=customname",
+ Filename: "gogo.proto",
+}
+
+var E_Jsontag = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65005,
+ Name: "gogoproto.jsontag",
+ Tag: "bytes,65005,opt,name=jsontag",
+ Filename: "gogo.proto",
+}
+
+var E_Moretags = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65006,
+ Name: "gogoproto.moretags",
+ Tag: "bytes,65006,opt,name=moretags",
+ Filename: "gogo.proto",
+}
+
+var E_Casttype = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65007,
+ Name: "gogoproto.casttype",
+ Tag: "bytes,65007,opt,name=casttype",
+ Filename: "gogo.proto",
+}
+
+var E_Castkey = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65008,
+ Name: "gogoproto.castkey",
+ Tag: "bytes,65008,opt,name=castkey",
+ Filename: "gogo.proto",
+}
+
+var E_Castvalue = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65009,
+ Name: "gogoproto.castvalue",
+ Tag: "bytes,65009,opt,name=castvalue",
+ Filename: "gogo.proto",
+}
+
+var E_Stdtime = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 65010,
+ Name: "gogoproto.stdtime",
+ Tag: "varint,65010,opt,name=stdtime",
+ Filename: "gogo.proto",
+}
+
+var E_Stdduration = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 65011,
+ Name: "gogoproto.stdduration",
+ Tag: "varint,65011,opt,name=stdduration",
+ Filename: "gogo.proto",
+}
+
+func init() {
+ proto.RegisterExtension(E_GoprotoEnumPrefix)
+ proto.RegisterExtension(E_GoprotoEnumStringer)
+ proto.RegisterExtension(E_EnumStringer)
+ proto.RegisterExtension(E_EnumCustomname)
+ proto.RegisterExtension(E_Enumdecl)
+ proto.RegisterExtension(E_EnumvalueCustomname)
+ proto.RegisterExtension(E_GoprotoGettersAll)
+ proto.RegisterExtension(E_GoprotoEnumPrefixAll)
+ proto.RegisterExtension(E_GoprotoStringerAll)
+ proto.RegisterExtension(E_VerboseEqualAll)
+ proto.RegisterExtension(E_FaceAll)
+ proto.RegisterExtension(E_GostringAll)
+ proto.RegisterExtension(E_PopulateAll)
+ proto.RegisterExtension(E_StringerAll)
+ proto.RegisterExtension(E_OnlyoneAll)
+ proto.RegisterExtension(E_EqualAll)
+ proto.RegisterExtension(E_DescriptionAll)
+ proto.RegisterExtension(E_TestgenAll)
+ proto.RegisterExtension(E_BenchgenAll)
+ proto.RegisterExtension(E_MarshalerAll)
+ proto.RegisterExtension(E_UnmarshalerAll)
+ proto.RegisterExtension(E_StableMarshalerAll)
+ proto.RegisterExtension(E_SizerAll)
+ proto.RegisterExtension(E_GoprotoEnumStringerAll)
+ proto.RegisterExtension(E_EnumStringerAll)
+ proto.RegisterExtension(E_UnsafeMarshalerAll)
+ proto.RegisterExtension(E_UnsafeUnmarshalerAll)
+ proto.RegisterExtension(E_GoprotoExtensionsMapAll)
+ proto.RegisterExtension(E_GoprotoUnrecognizedAll)
+ proto.RegisterExtension(E_GogoprotoImport)
+ proto.RegisterExtension(E_ProtosizerAll)
+ proto.RegisterExtension(E_CompareAll)
+ proto.RegisterExtension(E_TypedeclAll)
+ proto.RegisterExtension(E_EnumdeclAll)
+ proto.RegisterExtension(E_GoprotoRegistration)
+ proto.RegisterExtension(E_GoprotoGetters)
+ proto.RegisterExtension(E_GoprotoStringer)
+ proto.RegisterExtension(E_VerboseEqual)
+ proto.RegisterExtension(E_Face)
+ proto.RegisterExtension(E_Gostring)
+ proto.RegisterExtension(E_Populate)
+ proto.RegisterExtension(E_Stringer)
+ proto.RegisterExtension(E_Onlyone)
+ proto.RegisterExtension(E_Equal)
+ proto.RegisterExtension(E_Description)
+ proto.RegisterExtension(E_Testgen)
+ proto.RegisterExtension(E_Benchgen)
+ proto.RegisterExtension(E_Marshaler)
+ proto.RegisterExtension(E_Unmarshaler)
+ proto.RegisterExtension(E_StableMarshaler)
+ proto.RegisterExtension(E_Sizer)
+ proto.RegisterExtension(E_UnsafeMarshaler)
+ proto.RegisterExtension(E_UnsafeUnmarshaler)
+ proto.RegisterExtension(E_GoprotoExtensionsMap)
+ proto.RegisterExtension(E_GoprotoUnrecognized)
+ proto.RegisterExtension(E_Protosizer)
+ proto.RegisterExtension(E_Compare)
+ proto.RegisterExtension(E_Typedecl)
+ proto.RegisterExtension(E_Nullable)
+ proto.RegisterExtension(E_Embed)
+ proto.RegisterExtension(E_Customtype)
+ proto.RegisterExtension(E_Customname)
+ proto.RegisterExtension(E_Jsontag)
+ proto.RegisterExtension(E_Moretags)
+ proto.RegisterExtension(E_Casttype)
+ proto.RegisterExtension(E_Castkey)
+ proto.RegisterExtension(E_Castvalue)
+ proto.RegisterExtension(E_Stdtime)
+ proto.RegisterExtension(E_Stdduration)
+}
+
+func init() { proto.RegisterFile("gogo.proto", fileDescriptorGogo) }
+
+var fileDescriptorGogo = []byte{
+ // 1201 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x98, 0xcb, 0x6f, 0x1c, 0x45,
+ 0x13, 0xc0, 0xf5, 0xe9, 0x73, 0x64, 0x6f, 0xf9, 0x85, 0xd7, 0xc6, 0x84, 0x08, 0x44, 0x72, 0xe3,
+ 0xe4, 0x9c, 0x22, 0x94, 0xb6, 0x22, 0xcb, 0xb1, 0x1c, 0x2b, 0x11, 0x06, 0x63, 0xe2, 0x00, 0xe2,
+ 0xb0, 0x9a, 0xdd, 0x6d, 0x4f, 0x06, 0x66, 0xa6, 0x87, 0x99, 0x9e, 0x28, 0xce, 0x0d, 0x85, 0x87,
+ 0x10, 0xe2, 0x8d, 0x04, 0x09, 0x49, 0x80, 0x03, 0xef, 0x67, 0x78, 0x1f, 0xb9, 0xf0, 0xb8, 0xf2,
+ 0x3f, 0x70, 0x01, 0xcc, 0xdb, 0x37, 0x5f, 0x50, 0xcd, 0x56, 0xcd, 0xf6, 0xac, 0x57, 0xea, 0xde,
+ 0xdb, 0xec, 0xba, 0x7f, 0xbf, 0xad, 0xa9, 0x9a, 0xae, 0xea, 0x31, 0x80, 0xaf, 0x7c, 0x35, 0x97,
+ 0xa4, 0x4a, 0xab, 0x7a, 0x0d, 0xaf, 0x8b, 0xcb, 0x03, 0x07, 0x7d, 0xa5, 0xfc, 0x50, 0x1e, 0x2e,
+ 0x3e, 0x35, 0xf3, 0xcd, 0xc3, 0x6d, 0x99, 0xb5, 0xd2, 0x20, 0xd1, 0x2a, 0xed, 0x2c, 0x16, 0x77,
+ 0xc1, 0x34, 0x2d, 0x6e, 0xc8, 0x38, 0x8f, 0x1a, 0x49, 0x2a, 0x37, 0x83, 0xf3, 0xf5, 0x5b, 0xe6,
+ 0x3a, 0xe4, 0x1c, 0x93, 0x73, 0xcb, 0x71, 0x1e, 0xdd, 0x9d, 0xe8, 0x40, 0xc5, 0xd9, 0xfe, 0xeb,
+ 0x3f, 0xff, 0xff, 0xe0, 0xff, 0x6e, 0x1f, 0x59, 0x9f, 0x22, 0x14, 0xff, 0xb6, 0x56, 0x80, 0x62,
+ 0x1d, 0x6e, 0xac, 0xf8, 0x32, 0x9d, 0x06, 0xb1, 0x2f, 0x53, 0x8b, 0xf1, 0x3b, 0x32, 0x4e, 0x1b,
+ 0xc6, 0x7b, 0x09, 0x15, 0x4b, 0x30, 0x3e, 0x88, 0xeb, 0x7b, 0x72, 0x8d, 0x49, 0x53, 0xb2, 0x02,
+ 0x93, 0x85, 0xa4, 0x95, 0x67, 0x5a, 0x45, 0xb1, 0x17, 0x49, 0x8b, 0xe6, 0x87, 0x42, 0x53, 0x5b,
+ 0x9f, 0x40, 0x6c, 0xa9, 0xa4, 0x84, 0x80, 0x11, 0xfc, 0xa6, 0x2d, 0x5b, 0xa1, 0xc5, 0xf0, 0x23,
+ 0x05, 0x52, 0xae, 0x17, 0x67, 0x60, 0x06, 0xaf, 0xcf, 0x79, 0x61, 0x2e, 0xcd, 0x48, 0x0e, 0xf5,
+ 0xf5, 0x9c, 0xc1, 0x65, 0x2c, 0xfb, 0xe9, 0xe2, 0x50, 0x11, 0xce, 0x74, 0x29, 0x30, 0x62, 0x32,
+ 0xaa, 0xe8, 0x4b, 0xad, 0x65, 0x9a, 0x35, 0xbc, 0xb0, 0x5f, 0x78, 0x27, 0x82, 0xb0, 0x34, 0x5e,
+ 0xda, 0xae, 0x56, 0x71, 0xa5, 0x43, 0x2e, 0x86, 0xa1, 0xd8, 0x80, 0x9b, 0xfa, 0x3c, 0x15, 0x0e,
+ 0xce, 0xcb, 0xe4, 0x9c, 0xd9, 0xf3, 0x64, 0xa0, 0x76, 0x0d, 0xf8, 0xfb, 0xb2, 0x96, 0x0e, 0xce,
+ 0xd7, 0xc8, 0x59, 0x27, 0x96, 0x4b, 0x8a, 0xc6, 0x53, 0x30, 0x75, 0x4e, 0xa6, 0x4d, 0x95, 0xc9,
+ 0x86, 0x7c, 0x24, 0xf7, 0x42, 0x07, 0xdd, 0x15, 0xd2, 0x4d, 0x12, 0xb8, 0x8c, 0x1c, 0xba, 0x8e,
+ 0xc2, 0xc8, 0xa6, 0xd7, 0x92, 0x0e, 0x8a, 0xab, 0xa4, 0x18, 0xc6, 0xf5, 0x88, 0x2e, 0xc2, 0x98,
+ 0xaf, 0x3a, 0xb7, 0xe4, 0x80, 0x5f, 0x23, 0x7c, 0x94, 0x19, 0x52, 0x24, 0x2a, 0xc9, 0x43, 0x4f,
+ 0xbb, 0x44, 0xf0, 0x3a, 0x2b, 0x98, 0x21, 0xc5, 0x00, 0x69, 0x7d, 0x83, 0x15, 0x99, 0x91, 0xcf,
+ 0x05, 0x18, 0x55, 0x71, 0xb8, 0xa5, 0x62, 0x97, 0x20, 0xde, 0x24, 0x03, 0x10, 0x82, 0x82, 0x79,
+ 0xa8, 0xb9, 0x16, 0xe2, 0xad, 0x6d, 0xde, 0x1e, 0x5c, 0x81, 0x15, 0x98, 0xe4, 0x06, 0x15, 0xa8,
+ 0xd8, 0x41, 0xf1, 0x36, 0x29, 0x26, 0x0c, 0x8c, 0x6e, 0x43, 0xcb, 0x4c, 0xfb, 0xd2, 0x45, 0xf2,
+ 0x0e, 0xdf, 0x06, 0x21, 0x94, 0xca, 0xa6, 0x8c, 0x5b, 0x67, 0xdd, 0x0c, 0xef, 0x72, 0x2a, 0x99,
+ 0x41, 0xc5, 0x12, 0x8c, 0x47, 0x5e, 0x9a, 0x9d, 0xf5, 0x42, 0xa7, 0x72, 0xbc, 0x47, 0x8e, 0xb1,
+ 0x12, 0xa2, 0x8c, 0xe4, 0xf1, 0x20, 0x9a, 0xf7, 0x39, 0x23, 0x06, 0x46, 0x5b, 0x2f, 0xd3, 0x5e,
+ 0x33, 0x94, 0x8d, 0x41, 0x6c, 0x1f, 0xf0, 0xd6, 0xeb, 0xb0, 0xab, 0xa6, 0x71, 0x1e, 0x6a, 0x59,
+ 0x70, 0xc1, 0x49, 0xf3, 0x21, 0x57, 0xba, 0x00, 0x10, 0x7e, 0x00, 0x6e, 0xee, 0x3b, 0x26, 0x1c,
+ 0x64, 0x1f, 0x91, 0x6c, 0xb6, 0xcf, 0xa8, 0xa0, 0x96, 0x30, 0xa8, 0xf2, 0x63, 0x6e, 0x09, 0xb2,
+ 0xc7, 0xb5, 0x06, 0x33, 0x79, 0x9c, 0x79, 0x9b, 0x83, 0x65, 0xed, 0x13, 0xce, 0x5a, 0x87, 0xad,
+ 0x64, 0xed, 0x34, 0xcc, 0x92, 0x71, 0xb0, 0xba, 0x7e, 0xca, 0x8d, 0xb5, 0x43, 0x6f, 0x54, 0xab,
+ 0xfb, 0x20, 0x1c, 0x28, 0xd3, 0x79, 0x5e, 0xcb, 0x38, 0x43, 0xa6, 0x11, 0x79, 0x89, 0x83, 0xf9,
+ 0x3a, 0x99, 0xb9, 0xe3, 0x2f, 0x97, 0x82, 0x55, 0x2f, 0x41, 0xf9, 0xfd, 0xb0, 0x9f, 0xe5, 0x79,
+ 0x9c, 0xca, 0x96, 0xf2, 0xe3, 0xe0, 0x82, 0x6c, 0x3b, 0xa8, 0x3f, 0xeb, 0x29, 0xd5, 0x86, 0x81,
+ 0xa3, 0xf9, 0x24, 0xdc, 0x50, 0x9e, 0x55, 0x1a, 0x41, 0x94, 0xa8, 0x54, 0x5b, 0x8c, 0x9f, 0x73,
+ 0xa5, 0x4a, 0xee, 0x64, 0x81, 0x89, 0x65, 0x98, 0x28, 0x3e, 0xba, 0x3e, 0x92, 0x5f, 0x90, 0x68,
+ 0xbc, 0x4b, 0x51, 0xe3, 0x68, 0xa9, 0x28, 0xf1, 0x52, 0x97, 0xfe, 0xf7, 0x25, 0x37, 0x0e, 0x42,
+ 0xa8, 0x71, 0xe8, 0xad, 0x44, 0xe2, 0xb4, 0x77, 0x30, 0x7c, 0xc5, 0x8d, 0x83, 0x19, 0x52, 0xf0,
+ 0x81, 0xc1, 0x41, 0xf1, 0x35, 0x2b, 0x98, 0x41, 0xc5, 0x3d, 0xdd, 0x41, 0x9b, 0x4a, 0x3f, 0xc8,
+ 0x74, 0xea, 0xe1, 0x6a, 0x8b, 0xea, 0x9b, 0xed, 0xea, 0x21, 0x6c, 0xdd, 0x40, 0xc5, 0x29, 0x98,
+ 0xec, 0x39, 0x62, 0xd4, 0x6f, 0xdb, 0x63, 0x5b, 0x95, 0x59, 0xe6, 0xf9, 0xa5, 0xf0, 0xd1, 0x1d,
+ 0x6a, 0x46, 0xd5, 0x13, 0x86, 0xb8, 0x13, 0xeb, 0x5e, 0x3d, 0x07, 0xd8, 0x65, 0x17, 0x77, 0xca,
+ 0xd2, 0x57, 0x8e, 0x01, 0xe2, 0x04, 0x8c, 0x57, 0xce, 0x00, 0x76, 0xd5, 0x63, 0xa4, 0x1a, 0x33,
+ 0x8f, 0x00, 0xe2, 0x08, 0x0c, 0xe1, 0x3c, 0xb7, 0xe3, 0x8f, 0x13, 0x5e, 0x2c, 0x17, 0xc7, 0x60,
+ 0x84, 0xe7, 0xb8, 0x1d, 0x7d, 0x82, 0xd0, 0x12, 0x41, 0x9c, 0x67, 0xb8, 0x1d, 0x7f, 0x92, 0x71,
+ 0x46, 0x10, 0x77, 0x4f, 0xe1, 0xb7, 0x4f, 0x0f, 0x51, 0x1f, 0xe6, 0xdc, 0xcd, 0xc3, 0x30, 0x0d,
+ 0x6f, 0x3b, 0xfd, 0x14, 0xfd, 0x38, 0x13, 0xe2, 0x0e, 0xd8, 0xe7, 0x98, 0xf0, 0x67, 0x08, 0xed,
+ 0xac, 0x17, 0x4b, 0x30, 0x6a, 0x0c, 0x6c, 0x3b, 0xfe, 0x2c, 0xe1, 0x26, 0x85, 0xa1, 0xd3, 0xc0,
+ 0xb6, 0x0b, 0x9e, 0xe3, 0xd0, 0x89, 0xc0, 0xb4, 0xf1, 0xac, 0xb6, 0xd3, 0xcf, 0x73, 0xd6, 0x19,
+ 0x11, 0x0b, 0x50, 0x2b, 0xfb, 0xaf, 0x9d, 0x7f, 0x81, 0xf8, 0x2e, 0x83, 0x19, 0x30, 0xfa, 0xbf,
+ 0x5d, 0xf1, 0x22, 0x67, 0xc0, 0xa0, 0x70, 0x1b, 0xf5, 0xce, 0x74, 0xbb, 0xe9, 0x25, 0xde, 0x46,
+ 0x3d, 0x23, 0x1d, 0xab, 0x59, 0xb4, 0x41, 0xbb, 0xe2, 0x65, 0xae, 0x66, 0xb1, 0x1e, 0xc3, 0xe8,
+ 0x1d, 0x92, 0x76, 0xc7, 0x2b, 0x1c, 0x46, 0xcf, 0x8c, 0x14, 0x6b, 0x50, 0xdf, 0x3b, 0x20, 0xed,
+ 0xbe, 0x57, 0xc9, 0x37, 0xb5, 0x67, 0x3e, 0x8a, 0xfb, 0x60, 0xb6, 0xff, 0x70, 0xb4, 0x5b, 0x2f,
+ 0xed, 0xf4, 0xbc, 0xce, 0x98, 0xb3, 0x51, 0x9c, 0xee, 0x76, 0x59, 0x73, 0x30, 0xda, 0xb5, 0x97,
+ 0x77, 0xaa, 0x8d, 0xd6, 0x9c, 0x8b, 0x62, 0x11, 0xa0, 0x3b, 0x93, 0xec, 0xae, 0x2b, 0xe4, 0x32,
+ 0x20, 0xdc, 0x1a, 0x34, 0x92, 0xec, 0xfc, 0x55, 0xde, 0x1a, 0x44, 0xe0, 0xd6, 0xe0, 0x69, 0x64,
+ 0xa7, 0xaf, 0xf1, 0xd6, 0x60, 0x44, 0xcc, 0xc3, 0x48, 0x9c, 0x87, 0x21, 0x3e, 0x5b, 0xf5, 0x5b,
+ 0xfb, 0x8c, 0x1b, 0x19, 0xb6, 0x19, 0xfe, 0x65, 0x97, 0x60, 0x06, 0xc4, 0x11, 0xd8, 0x27, 0xa3,
+ 0xa6, 0x6c, 0xdb, 0xc8, 0x5f, 0x77, 0xb9, 0x9f, 0xe0, 0x6a, 0xb1, 0x00, 0xd0, 0x79, 0x99, 0xc6,
+ 0x28, 0x6c, 0xec, 0x6f, 0xbb, 0x9d, 0xf7, 0x7a, 0x03, 0xe9, 0x0a, 0x8a, 0xb7, 0x71, 0x8b, 0x60,
+ 0xbb, 0x2a, 0x28, 0x5e, 0xc0, 0x8f, 0xc2, 0xf0, 0x43, 0x99, 0x8a, 0xb5, 0xe7, 0xdb, 0xe8, 0xdf,
+ 0x89, 0xe6, 0xf5, 0x98, 0xb0, 0x48, 0xa5, 0x52, 0x7b, 0x7e, 0x66, 0x63, 0xff, 0x20, 0xb6, 0x04,
+ 0x10, 0x6e, 0x79, 0x99, 0x76, 0xb9, 0xef, 0x3f, 0x19, 0x66, 0x00, 0x83, 0xc6, 0xeb, 0x87, 0xe5,
+ 0x96, 0x8d, 0xfd, 0x8b, 0x83, 0xa6, 0xf5, 0xe2, 0x18, 0xd4, 0xf0, 0xb2, 0xf8, 0x3f, 0x84, 0x0d,
+ 0xfe, 0x9b, 0xe0, 0x2e, 0x81, 0xbf, 0x9c, 0xe9, 0xb6, 0x0e, 0xec, 0xc9, 0xfe, 0x87, 0x2a, 0xcd,
+ 0xeb, 0xc5, 0x22, 0x8c, 0x66, 0xba, 0xdd, 0xce, 0xe9, 0x44, 0x63, 0xc1, 0xff, 0xdd, 0x2d, 0x5f,
+ 0x72, 0x4b, 0xe6, 0xf8, 0x21, 0x98, 0x6e, 0xa9, 0xa8, 0x17, 0x3c, 0x0e, 0x2b, 0x6a, 0x45, 0xad,
+ 0x15, 0xbb, 0xe8, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x0a, 0x9c, 0xec, 0xd8, 0x50, 0x13, 0x00,
+ 0x00,
+}
diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto b/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto
new file mode 100644
index 0000000..fbca44c
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto
@@ -0,0 +1,132 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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.
+
+syntax = "proto2";
+package gogoproto;
+
+import "google/protobuf/descriptor.proto";
+
+option java_package = "com.google.protobuf";
+option java_outer_classname = "GoGoProtos";
+
+extend google.protobuf.EnumOptions {
+ optional bool goproto_enum_prefix = 62001;
+ optional bool goproto_enum_stringer = 62021;
+ optional bool enum_stringer = 62022;
+ optional string enum_customname = 62023;
+ optional bool enumdecl = 62024;
+}
+
+extend google.protobuf.EnumValueOptions {
+ optional string enumvalue_customname = 66001;
+}
+
+extend google.protobuf.FileOptions {
+ optional bool goproto_getters_all = 63001;
+ optional bool goproto_enum_prefix_all = 63002;
+ optional bool goproto_stringer_all = 63003;
+ optional bool verbose_equal_all = 63004;
+ optional bool face_all = 63005;
+ optional bool gostring_all = 63006;
+ optional bool populate_all = 63007;
+ optional bool stringer_all = 63008;
+ optional bool onlyone_all = 63009;
+
+ optional bool equal_all = 63013;
+ optional bool description_all = 63014;
+ optional bool testgen_all = 63015;
+ optional bool benchgen_all = 63016;
+ optional bool marshaler_all = 63017;
+ optional bool unmarshaler_all = 63018;
+ optional bool stable_marshaler_all = 63019;
+
+ optional bool sizer_all = 63020;
+
+ optional bool goproto_enum_stringer_all = 63021;
+ optional bool enum_stringer_all = 63022;
+
+ optional bool unsafe_marshaler_all = 63023;
+ optional bool unsafe_unmarshaler_all = 63024;
+
+ optional bool goproto_extensions_map_all = 63025;
+ optional bool goproto_unrecognized_all = 63026;
+ optional bool gogoproto_import = 63027;
+ optional bool protosizer_all = 63028;
+ optional bool compare_all = 63029;
+ optional bool typedecl_all = 63030;
+ optional bool enumdecl_all = 63031;
+
+ optional bool goproto_registration = 63032;
+}
+
+extend google.protobuf.MessageOptions {
+ optional bool goproto_getters = 64001;
+ optional bool goproto_stringer = 64003;
+ optional bool verbose_equal = 64004;
+ optional bool face = 64005;
+ optional bool gostring = 64006;
+ optional bool populate = 64007;
+ optional bool stringer = 67008;
+ optional bool onlyone = 64009;
+
+ optional bool equal = 64013;
+ optional bool description = 64014;
+ optional bool testgen = 64015;
+ optional bool benchgen = 64016;
+ optional bool marshaler = 64017;
+ optional bool unmarshaler = 64018;
+ optional bool stable_marshaler = 64019;
+
+ optional bool sizer = 64020;
+
+ optional bool unsafe_marshaler = 64023;
+ optional bool unsafe_unmarshaler = 64024;
+
+ optional bool goproto_extensions_map = 64025;
+ optional bool goproto_unrecognized = 64026;
+
+ optional bool protosizer = 64028;
+ optional bool compare = 64029;
+
+ optional bool typedecl = 64030;
+}
+
+extend google.protobuf.FieldOptions {
+ optional bool nullable = 65001;
+ optional bool embed = 65002;
+ optional string customtype = 65003;
+ optional string customname = 65004;
+ optional string jsontag = 65005;
+ optional string moretags = 65006;
+ optional string casttype = 65007;
+ optional string castkey = 65008;
+ optional string castvalue = 65009;
+
+ optional bool stdtime = 65010;
+ optional bool stdduration = 65011;
+}
diff --git a/vendor/github.com/gogo/protobuf/gogoproto/helper.go b/vendor/github.com/gogo/protobuf/gogoproto/helper.go
new file mode 100644
index 0000000..6b851c5
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/gogoproto/helper.go
@@ -0,0 +1,357 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 gogoproto
+
+import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
+import proto "github.com/gogo/protobuf/proto"
+
+func IsEmbed(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Embed, false)
+}
+
+func IsNullable(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Nullable, true)
+}
+
+func IsStdTime(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Stdtime, false)
+}
+
+func IsStdDuration(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Stdduration, false)
+}
+
+func NeedsNilCheck(proto3 bool, field *google_protobuf.FieldDescriptorProto) bool {
+ nullable := IsNullable(field)
+ if field.IsMessage() || IsCustomType(field) {
+ return nullable
+ }
+ if proto3 {
+ return false
+ }
+ return nullable || *field.Type == google_protobuf.FieldDescriptorProto_TYPE_BYTES
+}
+
+func IsCustomType(field *google_protobuf.FieldDescriptorProto) bool {
+ typ := GetCustomType(field)
+ if len(typ) > 0 {
+ return true
+ }
+ return false
+}
+
+func IsCastType(field *google_protobuf.FieldDescriptorProto) bool {
+ typ := GetCastType(field)
+ if len(typ) > 0 {
+ return true
+ }
+ return false
+}
+
+func IsCastKey(field *google_protobuf.FieldDescriptorProto) bool {
+ typ := GetCastKey(field)
+ if len(typ) > 0 {
+ return true
+ }
+ return false
+}
+
+func IsCastValue(field *google_protobuf.FieldDescriptorProto) bool {
+ typ := GetCastValue(field)
+ if len(typ) > 0 {
+ return true
+ }
+ return false
+}
+
+func HasEnumDecl(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool {
+ return proto.GetBoolExtension(enum.Options, E_Enumdecl, proto.GetBoolExtension(file.Options, E_EnumdeclAll, true))
+}
+
+func HasTypeDecl(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Typedecl, proto.GetBoolExtension(file.Options, E_TypedeclAll, true))
+}
+
+func GetCustomType(field *google_protobuf.FieldDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Customtype)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetCastType(field *google_protobuf.FieldDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Casttype)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetCastKey(field *google_protobuf.FieldDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Castkey)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetCastValue(field *google_protobuf.FieldDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Castvalue)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func IsCustomName(field *google_protobuf.FieldDescriptorProto) bool {
+ name := GetCustomName(field)
+ if len(name) > 0 {
+ return true
+ }
+ return false
+}
+
+func IsEnumCustomName(field *google_protobuf.EnumDescriptorProto) bool {
+ name := GetEnumCustomName(field)
+ if len(name) > 0 {
+ return true
+ }
+ return false
+}
+
+func IsEnumValueCustomName(field *google_protobuf.EnumValueDescriptorProto) bool {
+ name := GetEnumValueCustomName(field)
+ if len(name) > 0 {
+ return true
+ }
+ return false
+}
+
+func GetCustomName(field *google_protobuf.FieldDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Customname)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetEnumCustomName(field *google_protobuf.EnumDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_EnumCustomname)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetEnumValueCustomName(field *google_protobuf.EnumValueDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_EnumvalueCustomname)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetJsonTag(field *google_protobuf.FieldDescriptorProto) *string {
+ if field == nil {
+ return nil
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Jsontag)
+ if err == nil && v.(*string) != nil {
+ return (v.(*string))
+ }
+ }
+ return nil
+}
+
+func GetMoreTags(field *google_protobuf.FieldDescriptorProto) *string {
+ if field == nil {
+ return nil
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Moretags)
+ if err == nil && v.(*string) != nil {
+ return (v.(*string))
+ }
+ }
+ return nil
+}
+
+type EnableFunc func(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool
+
+func EnabledGoEnumPrefix(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool {
+ return proto.GetBoolExtension(enum.Options, E_GoprotoEnumPrefix, proto.GetBoolExtension(file.Options, E_GoprotoEnumPrefixAll, true))
+}
+
+func EnabledGoStringer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_GoprotoStringer, proto.GetBoolExtension(file.Options, E_GoprotoStringerAll, true))
+}
+
+func HasGoGetters(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_GoprotoGetters, proto.GetBoolExtension(file.Options, E_GoprotoGettersAll, true))
+}
+
+func IsUnion(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Onlyone, proto.GetBoolExtension(file.Options, E_OnlyoneAll, false))
+}
+
+func HasGoString(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Gostring, proto.GetBoolExtension(file.Options, E_GostringAll, false))
+}
+
+func HasEqual(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Equal, proto.GetBoolExtension(file.Options, E_EqualAll, false))
+}
+
+func HasVerboseEqual(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_VerboseEqual, proto.GetBoolExtension(file.Options, E_VerboseEqualAll, false))
+}
+
+func IsStringer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Stringer, proto.GetBoolExtension(file.Options, E_StringerAll, false))
+}
+
+func IsFace(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Face, proto.GetBoolExtension(file.Options, E_FaceAll, false))
+}
+
+func HasDescription(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Description, proto.GetBoolExtension(file.Options, E_DescriptionAll, false))
+}
+
+func HasPopulate(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Populate, proto.GetBoolExtension(file.Options, E_PopulateAll, false))
+}
+
+func HasTestGen(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Testgen, proto.GetBoolExtension(file.Options, E_TestgenAll, false))
+}
+
+func HasBenchGen(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Benchgen, proto.GetBoolExtension(file.Options, E_BenchgenAll, false))
+}
+
+func IsMarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Marshaler, proto.GetBoolExtension(file.Options, E_MarshalerAll, false))
+}
+
+func IsUnmarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Unmarshaler, proto.GetBoolExtension(file.Options, E_UnmarshalerAll, false))
+}
+
+func IsStableMarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_StableMarshaler, proto.GetBoolExtension(file.Options, E_StableMarshalerAll, false))
+}
+
+func IsSizer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Sizer, proto.GetBoolExtension(file.Options, E_SizerAll, false))
+}
+
+func IsProtoSizer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Protosizer, proto.GetBoolExtension(file.Options, E_ProtosizerAll, false))
+}
+
+func IsGoEnumStringer(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool {
+ return proto.GetBoolExtension(enum.Options, E_GoprotoEnumStringer, proto.GetBoolExtension(file.Options, E_GoprotoEnumStringerAll, true))
+}
+
+func IsEnumStringer(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool {
+ return proto.GetBoolExtension(enum.Options, E_EnumStringer, proto.GetBoolExtension(file.Options, E_EnumStringerAll, false))
+}
+
+func IsUnsafeMarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_UnsafeMarshaler, proto.GetBoolExtension(file.Options, E_UnsafeMarshalerAll, false))
+}
+
+func IsUnsafeUnmarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_UnsafeUnmarshaler, proto.GetBoolExtension(file.Options, E_UnsafeUnmarshalerAll, false))
+}
+
+func HasExtensionsMap(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_GoprotoExtensionsMap, proto.GetBoolExtension(file.Options, E_GoprotoExtensionsMapAll, true))
+}
+
+func HasUnrecognized(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ if IsProto3(file) {
+ return false
+ }
+ return proto.GetBoolExtension(message.Options, E_GoprotoUnrecognized, proto.GetBoolExtension(file.Options, E_GoprotoUnrecognizedAll, true))
+}
+
+func IsProto3(file *google_protobuf.FileDescriptorProto) bool {
+ return file.GetSyntax() == "proto3"
+}
+
+func ImportsGoGoProto(file *google_protobuf.FileDescriptorProto) bool {
+ return proto.GetBoolExtension(file.Options, E_GogoprotoImport, true)
+}
+
+func HasCompare(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Compare, proto.GetBoolExtension(file.Options, E_CompareAll, false))
+}
+
+func RegistersGolangProto(file *google_protobuf.FileDescriptorProto) bool {
+ return proto.GetBoolExtension(file.Options, E_GoprotoRegistration, false)
+}
diff --git a/vendor/github.com/gogo/protobuf/io/full.go b/vendor/github.com/gogo/protobuf/io/full.go
new file mode 100644
index 0000000..550726a
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/io/full.go
@@ -0,0 +1,102 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 io
+
+import (
+ "github.com/gogo/protobuf/proto"
+ "io"
+)
+
+func NewFullWriter(w io.Writer) WriteCloser {
+ return &fullWriter{w, nil}
+}
+
+type fullWriter struct {
+ w io.Writer
+ buffer []byte
+}
+
+func (this *fullWriter) WriteMsg(msg proto.Message) (err error) {
+ var data []byte
+ if m, ok := msg.(marshaler); ok {
+ n, ok := getSize(m)
+ if !ok {
+ data, err = proto.Marshal(msg)
+ if err != nil {
+ return err
+ }
+ }
+ if n >= len(this.buffer) {
+ this.buffer = make([]byte, n)
+ }
+ _, err = m.MarshalTo(this.buffer)
+ if err != nil {
+ return err
+ }
+ data = this.buffer[:n]
+ } else {
+ data, err = proto.Marshal(msg)
+ if err != nil {
+ return err
+ }
+ }
+ _, err = this.w.Write(data)
+ return err
+}
+
+func (this *fullWriter) Close() error {
+ if closer, ok := this.w.(io.Closer); ok {
+ return closer.Close()
+ }
+ return nil
+}
+
+type fullReader struct {
+ r io.Reader
+ buf []byte
+}
+
+func NewFullReader(r io.Reader, maxSize int) ReadCloser {
+ return &fullReader{r, make([]byte, maxSize)}
+}
+
+func (this *fullReader) ReadMsg(msg proto.Message) error {
+ length, err := this.r.Read(this.buf)
+ if err != nil {
+ return err
+ }
+ return proto.Unmarshal(this.buf[:length], msg)
+}
+
+func (this *fullReader) Close() error {
+ if closer, ok := this.r.(io.Closer); ok {
+ return closer.Close()
+ }
+ return nil
+}
diff --git a/vendor/github.com/gogo/protobuf/io/io.go b/vendor/github.com/gogo/protobuf/io/io.go
new file mode 100644
index 0000000..6dca519
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/io/io.go
@@ -0,0 +1,70 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 io
+
+import (
+ "github.com/gogo/protobuf/proto"
+ "io"
+)
+
+type Writer interface {
+ WriteMsg(proto.Message) error
+}
+
+type WriteCloser interface {
+ Writer
+ io.Closer
+}
+
+type Reader interface {
+ ReadMsg(msg proto.Message) error
+}
+
+type ReadCloser interface {
+ Reader
+ io.Closer
+}
+
+type marshaler interface {
+ MarshalTo(data []byte) (n int, err error)
+}
+
+func getSize(v interface{}) (int, bool) {
+ if sz, ok := v.(interface {
+ Size() (n int)
+ }); ok {
+ return sz.Size(), true
+ } else if sz, ok := v.(interface {
+ ProtoSize() (n int)
+ }); ok {
+ return sz.ProtoSize(), true
+ } else {
+ return 0, false
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/io/uint32.go b/vendor/github.com/gogo/protobuf/io/uint32.go
new file mode 100644
index 0000000..c3dad1a
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/io/uint32.go
@@ -0,0 +1,126 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 io
+
+import (
+ "encoding/binary"
+ "github.com/gogo/protobuf/proto"
+ "io"
+)
+
+func NewUint32DelimitedWriter(w io.Writer, byteOrder binary.ByteOrder) WriteCloser {
+ return &uint32Writer{w, byteOrder, nil}
+}
+
+func NewSizeUint32DelimitedWriter(w io.Writer, byteOrder binary.ByteOrder, size int) WriteCloser {
+ return &uint32Writer{w, byteOrder, make([]byte, size)}
+}
+
+type uint32Writer struct {
+ w io.Writer
+ byteOrder binary.ByteOrder
+ buffer []byte
+}
+
+func (this *uint32Writer) WriteMsg(msg proto.Message) (err error) {
+ var data []byte
+ if m, ok := msg.(marshaler); ok {
+ n, ok := getSize(m)
+ if !ok {
+ data, err = proto.Marshal(msg)
+ if err != nil {
+ return err
+ }
+ }
+ if n >= len(this.buffer) {
+ this.buffer = make([]byte, n)
+ }
+ _, err = m.MarshalTo(this.buffer)
+ if err != nil {
+ return err
+ }
+ data = this.buffer[:n]
+ } else {
+ data, err = proto.Marshal(msg)
+ if err != nil {
+ return err
+ }
+ }
+ length := uint32(len(data))
+ if err = binary.Write(this.w, this.byteOrder, &length); err != nil {
+ return err
+ }
+ _, err = this.w.Write(data)
+ return err
+}
+
+func (this *uint32Writer) Close() error {
+ if closer, ok := this.w.(io.Closer); ok {
+ return closer.Close()
+ }
+ return nil
+}
+
+type uint32Reader struct {
+ r io.Reader
+ byteOrder binary.ByteOrder
+ lenBuf []byte
+ buf []byte
+ maxSize int
+}
+
+func NewUint32DelimitedReader(r io.Reader, byteOrder binary.ByteOrder, maxSize int) ReadCloser {
+ return &uint32Reader{r, byteOrder, make([]byte, 4), nil, maxSize}
+}
+
+func (this *uint32Reader) ReadMsg(msg proto.Message) error {
+ if _, err := io.ReadFull(this.r, this.lenBuf); err != nil {
+ return err
+ }
+ length32 := this.byteOrder.Uint32(this.lenBuf)
+ length := int(length32)
+ if length < 0 || length > this.maxSize {
+ return io.ErrShortBuffer
+ }
+ if length >= len(this.buf) {
+ this.buf = make([]byte, length)
+ }
+ _, err := io.ReadFull(this.r, this.buf[:length])
+ if err != nil {
+ return err
+ }
+ return proto.Unmarshal(this.buf[:length], msg)
+}
+
+func (this *uint32Reader) Close() error {
+ if closer, ok := this.r.(io.Closer); ok {
+ return closer.Close()
+ }
+ return nil
+}
diff --git a/vendor/github.com/gogo/protobuf/io/varint.go b/vendor/github.com/gogo/protobuf/io/varint.go
new file mode 100644
index 0000000..a72e14a
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/io/varint.go
@@ -0,0 +1,134 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 io
+
+import (
+ "bufio"
+ "encoding/binary"
+ "errors"
+ "github.com/gogo/protobuf/proto"
+ "io"
+)
+
+var (
+ errSmallBuffer = errors.New("Buffer Too Small")
+ errLargeValue = errors.New("Value is Larger than 64 bits")
+)
+
+func NewDelimitedWriter(w io.Writer) WriteCloser {
+ return &varintWriter{w, make([]byte, 10), nil}
+}
+
+type varintWriter struct {
+ w io.Writer
+ lenBuf []byte
+ buffer []byte
+}
+
+func (this *varintWriter) WriteMsg(msg proto.Message) (err error) {
+ var data []byte
+ if m, ok := msg.(marshaler); ok {
+ n, ok := getSize(m)
+ if !ok {
+ data, err = proto.Marshal(msg)
+ if err != nil {
+ return err
+ }
+ }
+ if n >= len(this.buffer) {
+ this.buffer = make([]byte, n)
+ }
+ _, err = m.MarshalTo(this.buffer)
+ if err != nil {
+ return err
+ }
+ data = this.buffer[:n]
+ } else {
+ data, err = proto.Marshal(msg)
+ if err != nil {
+ return err
+ }
+ }
+ length := uint64(len(data))
+ n := binary.PutUvarint(this.lenBuf, length)
+ _, err = this.w.Write(this.lenBuf[:n])
+ if err != nil {
+ return err
+ }
+ _, err = this.w.Write(data)
+ return err
+}
+
+func (this *varintWriter) Close() error {
+ if closer, ok := this.w.(io.Closer); ok {
+ return closer.Close()
+ }
+ return nil
+}
+
+func NewDelimitedReader(r io.Reader, maxSize int) ReadCloser {
+ var closer io.Closer
+ if c, ok := r.(io.Closer); ok {
+ closer = c
+ }
+ return &varintReader{bufio.NewReader(r), nil, maxSize, closer}
+}
+
+type varintReader struct {
+ r *bufio.Reader
+ buf []byte
+ maxSize int
+ closer io.Closer
+}
+
+func (this *varintReader) ReadMsg(msg proto.Message) error {
+ length64, err := binary.ReadUvarint(this.r)
+ if err != nil {
+ return err
+ }
+ length := int(length64)
+ if length < 0 || length > this.maxSize {
+ return io.ErrShortBuffer
+ }
+ if len(this.buf) < length {
+ this.buf = make([]byte, length)
+ }
+ buf := this.buf[:length]
+ if _, err := io.ReadFull(this.r, buf); err != nil {
+ return err
+ }
+ return proto.Unmarshal(buf, msg)
+}
+
+func (this *varintReader) Close() error {
+ if this.closer != nil {
+ return this.closer.Close()
+ }
+ return nil
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/clone.go b/vendor/github.com/gogo/protobuf/proto/clone.go
new file mode 100644
index 0000000..5d4cba4
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/clone.go
@@ -0,0 +1,234 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2011 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// Protocol buffer deep copy and merge.
+// TODO: RawMessage.
+
+package proto
+
+import (
+ "log"
+ "reflect"
+ "strings"
+)
+
+// Clone returns a deep copy of a protocol buffer.
+func Clone(pb Message) Message {
+ in := reflect.ValueOf(pb)
+ if in.IsNil() {
+ return pb
+ }
+
+ out := reflect.New(in.Type().Elem())
+ // out is empty so a merge is a deep copy.
+ mergeStruct(out.Elem(), in.Elem())
+ return out.Interface().(Message)
+}
+
+// Merge merges src into dst.
+// Required and optional fields that are set in src will be set to that value in dst.
+// Elements of repeated fields will be appended.
+// Merge panics if src and dst are not the same type, or if dst is nil.
+func Merge(dst, src Message) {
+ in := reflect.ValueOf(src)
+ out := reflect.ValueOf(dst)
+ if out.IsNil() {
+ panic("proto: nil destination")
+ }
+ if in.Type() != out.Type() {
+ // Explicit test prior to mergeStruct so that mistyped nils will fail
+ panic("proto: type mismatch")
+ }
+ if in.IsNil() {
+ // Merging nil into non-nil is a quiet no-op
+ return
+ }
+ mergeStruct(out.Elem(), in.Elem())
+}
+
+func mergeStruct(out, in reflect.Value) {
+ sprop := GetProperties(in.Type())
+ for i := 0; i < in.NumField(); i++ {
+ f := in.Type().Field(i)
+ if strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+ mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
+ }
+
+ if emIn, ok := in.Addr().Interface().(extensionsBytes); ok {
+ emOut := out.Addr().Interface().(extensionsBytes)
+ bIn := emIn.GetExtensions()
+ bOut := emOut.GetExtensions()
+ *bOut = append(*bOut, *bIn...)
+ } else if emIn, ok := extendable(in.Addr().Interface()); ok {
+ emOut, _ := extendable(out.Addr().Interface())
+ mIn, muIn := emIn.extensionsRead()
+ if mIn != nil {
+ mOut := emOut.extensionsWrite()
+ muIn.Lock()
+ mergeExtension(mOut, mIn)
+ muIn.Unlock()
+ }
+ }
+
+ uf := in.FieldByName("XXX_unrecognized")
+ if !uf.IsValid() {
+ return
+ }
+ uin := uf.Bytes()
+ if len(uin) > 0 {
+ out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
+ }
+}
+
+// mergeAny performs a merge between two values of the same type.
+// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
+// prop is set if this is a struct field (it may be nil).
+func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
+ if in.Type() == protoMessageType {
+ if !in.IsNil() {
+ if out.IsNil() {
+ out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
+ } else {
+ Merge(out.Interface().(Message), in.Interface().(Message))
+ }
+ }
+ return
+ }
+ switch in.Kind() {
+ case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
+ reflect.String, reflect.Uint32, reflect.Uint64:
+ if !viaPtr && isProto3Zero(in) {
+ return
+ }
+ out.Set(in)
+ case reflect.Interface:
+ // Probably a oneof field; copy non-nil values.
+ if in.IsNil() {
+ return
+ }
+ // Allocate destination if it is not set, or set to a different type.
+ // Otherwise we will merge as normal.
+ if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
+ out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
+ }
+ mergeAny(out.Elem(), in.Elem(), false, nil)
+ case reflect.Map:
+ if in.Len() == 0 {
+ return
+ }
+ if out.IsNil() {
+ out.Set(reflect.MakeMap(in.Type()))
+ }
+ // For maps with value types of *T or []byte we need to deep copy each value.
+ elemKind := in.Type().Elem().Kind()
+ for _, key := range in.MapKeys() {
+ var val reflect.Value
+ switch elemKind {
+ case reflect.Ptr:
+ val = reflect.New(in.Type().Elem().Elem())
+ mergeAny(val, in.MapIndex(key), false, nil)
+ case reflect.Slice:
+ val = in.MapIndex(key)
+ val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
+ default:
+ val = in.MapIndex(key)
+ }
+ out.SetMapIndex(key, val)
+ }
+ case reflect.Ptr:
+ if in.IsNil() {
+ return
+ }
+ if out.IsNil() {
+ out.Set(reflect.New(in.Elem().Type()))
+ }
+ mergeAny(out.Elem(), in.Elem(), true, nil)
+ case reflect.Slice:
+ if in.IsNil() {
+ return
+ }
+ if in.Type().Elem().Kind() == reflect.Uint8 {
+ // []byte is a scalar bytes field, not a repeated field.
+
+ // Edge case: if this is in a proto3 message, a zero length
+ // bytes field is considered the zero value, and should not
+ // be merged.
+ if prop != nil && prop.proto3 && in.Len() == 0 {
+ return
+ }
+
+ // Make a deep copy.
+ // Append to []byte{} instead of []byte(nil) so that we never end up
+ // with a nil result.
+ out.SetBytes(append([]byte{}, in.Bytes()...))
+ return
+ }
+ n := in.Len()
+ if out.IsNil() {
+ out.Set(reflect.MakeSlice(in.Type(), 0, n))
+ }
+ switch in.Type().Elem().Kind() {
+ case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
+ reflect.String, reflect.Uint32, reflect.Uint64:
+ out.Set(reflect.AppendSlice(out, in))
+ default:
+ for i := 0; i < n; i++ {
+ x := reflect.Indirect(reflect.New(in.Type().Elem()))
+ mergeAny(x, in.Index(i), false, nil)
+ out.Set(reflect.Append(out, x))
+ }
+ }
+ case reflect.Struct:
+ mergeStruct(out, in)
+ default:
+ // unknown type, so not a protocol buffer
+ log.Printf("proto: don't know how to copy %v", in)
+ }
+}
+
+func mergeExtension(out, in map[int32]Extension) {
+ for extNum, eIn := range in {
+ eOut := Extension{desc: eIn.desc}
+ if eIn.value != nil {
+ v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
+ mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
+ eOut.value = v.Interface()
+ }
+ if eIn.enc != nil {
+ eOut.enc = make([]byte, len(eIn.enc))
+ copy(eOut.enc, eIn.enc)
+ }
+
+ out[extNum] = eOut
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/decode.go b/vendor/github.com/gogo/protobuf/proto/decode.go
new file mode 100644
index 0000000..737f273
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/decode.go
@@ -0,0 +1,978 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Routines for decoding protocol buffer data to construct in-memory representations.
+ */
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "reflect"
+)
+
+// errOverflow is returned when an integer is too large to be represented.
+var errOverflow = errors.New("proto: integer overflow")
+
+// ErrInternalBadWireType is returned by generated code when an incorrect
+// wire type is encountered. It does not get returned to user code.
+var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
+
+// The fundamental decoders that interpret bytes on the wire.
+// Those that take integer types all return uint64 and are
+// therefore of type valueDecoder.
+
+// DecodeVarint reads a varint-encoded integer from the slice.
+// It returns the integer and the number of bytes consumed, or
+// zero if there is not enough.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func DecodeVarint(buf []byte) (x uint64, n int) {
+ for shift := uint(0); shift < 64; shift += 7 {
+ if n >= len(buf) {
+ return 0, 0
+ }
+ b := uint64(buf[n])
+ n++
+ x |= (b & 0x7F) << shift
+ if (b & 0x80) == 0 {
+ return x, n
+ }
+ }
+
+ // The number is too large to represent in a 64-bit value.
+ return 0, 0
+}
+
+func (p *Buffer) decodeVarintSlow() (x uint64, err error) {
+ i := p.index
+ l := len(p.buf)
+
+ for shift := uint(0); shift < 64; shift += 7 {
+ if i >= l {
+ err = io.ErrUnexpectedEOF
+ return
+ }
+ b := p.buf[i]
+ i++
+ x |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ p.index = i
+ return
+ }
+ }
+
+ // The number is too large to represent in a 64-bit value.
+ err = errOverflow
+ 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.
+func (p *Buffer) DecodeFixed64() (x uint64, err error) {
+ // x, err already 0
+ i := p.index + 8
+ if i < 0 || i > len(p.buf) {
+ err = io.ErrUnexpectedEOF
+ return
+ }
+ p.index = i
+
+ x = uint64(p.buf[i-8])
+ x |= uint64(p.buf[i-7]) << 8
+ x |= uint64(p.buf[i-6]) << 16
+ x |= uint64(p.buf[i-5]) << 24
+ x |= uint64(p.buf[i-4]) << 32
+ x |= uint64(p.buf[i-3]) << 40
+ x |= uint64(p.buf[i-2]) << 48
+ x |= uint64(p.buf[i-1]) << 56
+ return
+}
+
+// DecodeFixed32 reads a 32-bit integer from the Buffer.
+// This is the format for the
+// fixed32, sfixed32, and float protocol buffer types.
+func (p *Buffer) DecodeFixed32() (x uint64, err error) {
+ // x, err already 0
+ i := p.index + 4
+ if i < 0 || i > len(p.buf) {
+ err = io.ErrUnexpectedEOF
+ return
+ }
+ p.index = i
+
+ x = uint64(p.buf[i-4])
+ x |= uint64(p.buf[i-3]) << 8
+ x |= uint64(p.buf[i-2]) << 16
+ x |= uint64(p.buf[i-1]) << 24
+ return
+}
+
+// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
+// from the Buffer.
+// This is the format used for the sint64 protocol buffer type.
+func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
+ x, err = p.DecodeVarint()
+ if err != nil {
+ return
+ }
+ x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
+ return
+}
+
+// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
+// from the Buffer.
+// This is the format used for the sint32 protocol buffer type.
+func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
+ x, err = p.DecodeVarint()
+ if err != nil {
+ return
+ }
+ x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
+ return
+}
+
+// These are not ValueDecoders: they produce an array of bytes or a string.
+// bytes, embedded messages
+
+// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
+// This is the format used for the bytes protocol buffer
+// type and for embedded messages.
+func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
+ n, err := p.DecodeVarint()
+ if err != nil {
+ return nil, err
+ }
+
+ nb := int(n)
+ if nb < 0 {
+ return nil, fmt.Errorf("proto: bad byte length %d", nb)
+ }
+ end := p.index + nb
+ if end < p.index || end > len(p.buf) {
+ return nil, io.ErrUnexpectedEOF
+ }
+
+ if !alloc {
+ // todo: check if can get more uses of alloc=false
+ buf = p.buf[p.index:end]
+ p.index += nb
+ return
+ }
+
+ buf = make([]byte, nb)
+ copy(buf, p.buf[p.index:])
+ p.index += nb
+ return
+}
+
+// DecodeStringBytes reads an encoded string from the Buffer.
+// This is the format used for the proto2 string type.
+func (p *Buffer) DecodeStringBytes() (s string, err error) {
+ buf, err := p.DecodeRawBytes(false)
+ if err != nil {
+ return
+ }
+ return string(buf), nil
+}
+
+// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
+// If the protocol buffer has extensions, and the field matches, add it as an extension.
+// Otherwise, if the XXX_unrecognized field exists, append the skipped data there.
+func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error {
+ oi := o.index
+
+ err := o.skip(t, tag, wire)
+ if err != nil {
+ return err
+ }
+
+ if !unrecField.IsValid() {
+ return nil
+ }
+
+ ptr := structPointer_Bytes(base, unrecField)
+
+ // Add the skipped field to struct field
+ obuf := o.buf
+
+ o.buf = *ptr
+ o.EncodeVarint(uint64(tag<<3 | wire))
+ *ptr = append(o.buf, obuf[oi:o.index]...)
+
+ o.buf = obuf
+
+ return nil
+}
+
+// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
+func (o *Buffer) skip(t reflect.Type, tag, wire int) error {
+
+ var u uint64
+ var err error
+
+ switch wire {
+ case WireVarint:
+ _, err = o.DecodeVarint()
+ case WireFixed64:
+ _, err = o.DecodeFixed64()
+ case WireBytes:
+ _, err = o.DecodeRawBytes(false)
+ case WireFixed32:
+ _, err = o.DecodeFixed32()
+ case WireStartGroup:
+ for {
+ u, err = o.DecodeVarint()
+ if err != nil {
+ break
+ }
+ fwire := int(u & 0x7)
+ if fwire == WireEndGroup {
+ break
+ }
+ ftag := int(u >> 3)
+ err = o.skip(t, ftag, fwire)
+ if err != nil {
+ break
+ }
+ }
+ default:
+ err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t)
+ }
+ return err
+}
+
+// Unmarshaler is the interface representing objects that can
+// unmarshal themselves. The method should reset the receiver before
+// decoding starts. The argument points to data that may be
+// overwritten, so implementations should not keep references to the
+// buffer.
+type Unmarshaler interface {
+ Unmarshal([]byte) error
+}
+
+// Unmarshal parses the protocol buffer representation in buf and places the
+// decoded result in pb. If the struct underlying pb does not match
+// the data in buf, the results can be unpredictable.
+//
+// Unmarshal resets pb before starting to unmarshal, so any
+// existing data in pb is always removed. Use UnmarshalMerge
+// to preserve and append to existing data.
+func Unmarshal(buf []byte, pb Message) error {
+ pb.Reset()
+ return UnmarshalMerge(buf, pb)
+}
+
+// UnmarshalMerge parses the protocol buffer representation in buf and
+// writes the decoded result to pb. If the struct underlying pb does not match
+// the data in buf, the results can be unpredictable.
+//
+// UnmarshalMerge merges into existing data in pb.
+// Most code should use Unmarshal instead.
+func UnmarshalMerge(buf []byte, pb Message) error {
+ // If the object can unmarshal itself, let it.
+ if u, ok := pb.(Unmarshaler); ok {
+ return u.Unmarshal(buf)
+ }
+ return NewBuffer(buf).Unmarshal(pb)
+}
+
+// DecodeMessage reads a count-delimited message from the Buffer.
+func (p *Buffer) DecodeMessage(pb Message) error {
+ enc, err := p.DecodeRawBytes(false)
+ if err != nil {
+ return err
+ }
+ return NewBuffer(enc).Unmarshal(pb)
+}
+
+// DecodeGroup reads a tag-delimited group from the Buffer.
+func (p *Buffer) DecodeGroup(pb Message) error {
+ typ, base, err := getbase(pb)
+ if err != nil {
+ return err
+ }
+ return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base)
+}
+
+// Unmarshal parses the protocol buffer representation in the
+// 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 {
+ err := u.Unmarshal(p.buf[p.index:])
+ p.index = len(p.buf)
+ return err
+ }
+
+ typ, base, err := getbase(pb)
+ if err != nil {
+ return err
+ }
+
+ err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base)
+
+ if collectStats {
+ stats.Decode++
+ }
+
+ return err
+}
+
+// unmarshalType does the work of unmarshaling a structure.
+func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error {
+ var state errorState
+ required, reqFields := prop.reqCount, uint64(0)
+
+ var err error
+ for err == nil && o.index < len(o.buf) {
+ oi := o.index
+ var u uint64
+ u, err = o.DecodeVarint()
+ if err != nil {
+ break
+ }
+ 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)
+ }
+ tag := int(u >> 3)
+ if tag <= 0 {
+ return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire)
+ }
+ fieldnum, ok := prop.decoderTags.get(tag)
+ if !ok {
+ // Maybe it's an extension?
+ if prop.extendable {
+ if e, eok := structPointer_Interface(base, st).(extensionsBytes); eok {
+ if isExtensionField(e, int32(tag)) {
+ if err = o.skip(st, tag, wire); err == nil {
+ ext := e.GetExtensions()
+ *ext = append(*ext, o.buf[oi:o.index]...)
+ }
+ continue
+ }
+ } else if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) {
+ if err = o.skip(st, tag, wire); err == nil {
+ extmap := e.extensionsWrite()
+ ext := extmap[int32(tag)] // may be missing
+ ext.enc = append(ext.enc, o.buf[oi:o.index]...)
+ extmap[int32(tag)] = ext
+ }
+ continue
+ }
+ }
+ // Maybe it's a oneof?
+ if prop.oneofUnmarshaler != nil {
+ m := structPointer_Interface(base, st).(Message)
+ // First return value indicates whether tag is a oneof field.
+ ok, err = prop.oneofUnmarshaler(m, tag, wire, o)
+ if err == ErrInternalBadWireType {
+ // Map the error to something more descriptive.
+ // Do the formatting here to save generated code space.
+ err = fmt.Errorf("bad wiretype for oneof field in %T", m)
+ }
+ if ok {
+ continue
+ }
+ }
+ err = o.skipAndSave(st, tag, wire, base, prop.unrecField)
+ continue
+ }
+ p := prop.Prop[fieldnum]
+
+ if p.dec == nil {
+ fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name)
+ continue
+ }
+ dec := p.dec
+ if wire != WireStartGroup && wire != p.WireType {
+ if wire == WireBytes && p.packedDec != nil {
+ // a packable field
+ dec = p.packedDec
+ } else {
+ err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType)
+ continue
+ }
+ }
+ decErr := dec(o, p, base)
+ if decErr != nil && !state.shouldContinue(decErr, p) {
+ err = decErr
+ }
+ if err == nil && p.Required {
+ // Successfully decoded a required field.
+ if tag <= 64 {
+ // use bitmap for fields 1-64 to catch field reuse.
+ var mask uint64 = 1 << uint64(tag-1)
+ if reqFields&mask == 0 {
+ // new required field
+ reqFields |= mask
+ required--
+ }
+ } else {
+ // This is imprecise. It can be fooled by a required field
+ // with a tag > 64 that is encoded twice; that's very rare.
+ // A fully correct implementation would require allocating
+ // a data structure, which we would like to avoid.
+ required--
+ }
+ }
+ }
+ if err == nil {
+ if is_group {
+ return io.ErrUnexpectedEOF
+ }
+ if state.err != nil {
+ return state.err
+ }
+ if required > 0 {
+ // Not enough information to determine the exact field. If we use extra
+ // CPU, we could determine the field only if the missing required field
+ // has a tag <= 64 and we check reqFields.
+ return &RequiredNotSetError{"{Unknown}"}
+ }
+ }
+ return err
+}
+
+// Individual type decoders
+// For each,
+// u is the decoded value,
+// v is a pointer to the field (pointer) in the struct
+
+// Sizes of the pools to allocate inside the Buffer.
+// The goal is modest amortization and allocation
+// on at least 16-byte boundaries.
+const (
+ boolPoolSize = 16
+ uint32PoolSize = 8
+ uint64PoolSize = 4
+)
+
+// Decode a bool.
+func (o *Buffer) dec_bool(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ if len(o.bools) == 0 {
+ o.bools = make([]bool, boolPoolSize)
+ }
+ o.bools[0] = u != 0
+ *structPointer_Bool(base, p.field) = &o.bools[0]
+ o.bools = o.bools[1:]
+ return nil
+}
+
+func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ *structPointer_BoolVal(base, p.field) = u != 0
+ return nil
+}
+
+// Decode an int32.
+func (o *Buffer) dec_int32(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ word32_Set(structPointer_Word32(base, p.field), o, uint32(u))
+ return nil
+}
+
+func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u))
+ return nil
+}
+
+// Decode an int64.
+func (o *Buffer) dec_int64(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ word64_Set(structPointer_Word64(base, p.field), o, u)
+ return nil
+}
+
+func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ word64Val_Set(structPointer_Word64Val(base, p.field), o, u)
+ return nil
+}
+
+// Decode a string.
+func (o *Buffer) dec_string(p *Properties, base structPointer) error {
+ s, err := o.DecodeStringBytes()
+ if err != nil {
+ return err
+ }
+ *structPointer_String(base, p.field) = &s
+ return nil
+}
+
+func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error {
+ s, err := o.DecodeStringBytes()
+ if err != nil {
+ return err
+ }
+ *structPointer_StringVal(base, p.field) = s
+ return nil
+}
+
+// Decode a slice of bytes ([]byte).
+func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error {
+ b, err := o.DecodeRawBytes(true)
+ if err != nil {
+ return err
+ }
+ *structPointer_Bytes(base, p.field) = b
+ return nil
+}
+
+// Decode a slice of bools ([]bool).
+func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ v := structPointer_BoolSlice(base, p.field)
+ *v = append(*v, u != 0)
+ return nil
+}
+
+// Decode a slice of bools ([]bool) in packed format.
+func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error {
+ v := structPointer_BoolSlice(base, p.field)
+
+ nn, err := o.DecodeVarint()
+ if err != nil {
+ return err
+ }
+ nb := int(nn) // number of bytes of encoded bools
+ fin := o.index + nb
+ if fin < o.index {
+ return errOverflow
+ }
+
+ y := *v
+ for o.index < fin {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ y = append(y, u != 0)
+ }
+
+ *v = y
+ return nil
+}
+
+// Decode a slice of int32s ([]int32).
+func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ structPointer_Word32Slice(base, p.field).Append(uint32(u))
+ return nil
+}
+
+// Decode a slice of int32s ([]int32) in packed format.
+func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error {
+ v := structPointer_Word32Slice(base, p.field)
+
+ nn, err := o.DecodeVarint()
+ if err != nil {
+ return err
+ }
+ nb := int(nn) // number of bytes of encoded int32s
+
+ fin := o.index + nb
+ if fin < o.index {
+ return errOverflow
+ }
+ for o.index < fin {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ v.Append(uint32(u))
+ }
+ return nil
+}
+
+// Decode a slice of int64s ([]int64).
+func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+
+ structPointer_Word64Slice(base, p.field).Append(u)
+ return nil
+}
+
+// Decode a slice of int64s ([]int64) in packed format.
+func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error {
+ v := structPointer_Word64Slice(base, p.field)
+
+ nn, err := o.DecodeVarint()
+ if err != nil {
+ return err
+ }
+ nb := int(nn) // number of bytes of encoded int64s
+
+ fin := o.index + nb
+ if fin < o.index {
+ return errOverflow
+ }
+ for o.index < fin {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ v.Append(u)
+ }
+ return nil
+}
+
+// Decode a slice of strings ([]string).
+func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error {
+ s, err := o.DecodeStringBytes()
+ if err != nil {
+ return err
+ }
+ v := structPointer_StringSlice(base, p.field)
+ *v = append(*v, s)
+ return nil
+}
+
+// Decode a slice of slice of bytes ([][]byte).
+func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error {
+ b, err := o.DecodeRawBytes(true)
+ if err != nil {
+ return err
+ }
+ v := structPointer_BytesSlice(base, p.field)
+ *v = append(*v, b)
+ return nil
+}
+
+// Decode a map field.
+func (o *Buffer) dec_new_map(p *Properties, base structPointer) error {
+ raw, err := o.DecodeRawBytes(false)
+ if err != nil {
+ return err
+ }
+ oi := o.index // index at the end of this map entry
+ o.index -= len(raw) // move buffer back to start of map entry
+
+ mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V
+ if mptr.Elem().IsNil() {
+ mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem()))
+ }
+ v := mptr.Elem() // map[K]V
+
+ // Prepare addressable doubly-indirect placeholders for the key and value types.
+ // See enc_new_map for why.
+ keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K
+ keybase := toStructPointer(keyptr.Addr()) // **K
+
+ var valbase structPointer
+ var valptr reflect.Value
+ switch p.mtype.Elem().Kind() {
+ case reflect.Slice:
+ // []byte
+ var dummy []byte
+ valptr = reflect.ValueOf(&dummy) // *[]byte
+ valbase = toStructPointer(valptr) // *[]byte
+ case reflect.Ptr:
+ // message; valptr is **Msg; need to allocate the intermediate pointer
+ valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V
+ valptr.Set(reflect.New(valptr.Type().Elem()))
+ valbase = toStructPointer(valptr)
+ default:
+ // everything else
+ valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V
+ valbase = toStructPointer(valptr.Addr()) // **V
+ }
+
+ // Decode.
+ // This parses a restricted wire format, namely the encoding of a message
+ // with two fields. See enc_new_map for the format.
+ for o.index < oi {
+ // tagcode for key and value properties are always a single byte
+ // because they have tags 1 and 2.
+ tagcode := o.buf[o.index]
+ o.index++
+ switch tagcode {
+ case p.mkeyprop.tagcode[0]:
+ if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil {
+ return err
+ }
+ case p.mvalprop.tagcode[0]:
+ if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil {
+ return err
+ }
+ default:
+ // TODO: Should we silently skip this instead?
+ return fmt.Errorf("proto: bad map data tag %d", raw[0])
+ }
+ }
+ keyelem, valelem := keyptr.Elem(), valptr.Elem()
+ if !keyelem.IsValid() {
+ keyelem = reflect.Zero(p.mtype.Key())
+ }
+ if !valelem.IsValid() {
+ valelem = reflect.Zero(p.mtype.Elem())
+ }
+
+ v.SetMapIndex(keyelem, valelem)
+ return nil
+}
+
+// Decode a group.
+func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error {
+ bas := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(bas) {
+ // allocate new nested message
+ bas = toStructPointer(reflect.New(p.stype))
+ structPointer_SetStructPointer(base, p.field, bas)
+ }
+ return o.unmarshalType(p.stype, p.sprop, true, bas)
+}
+
+// Decode an embedded message.
+func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) {
+ raw, e := o.DecodeRawBytes(false)
+ if e != nil {
+ return e
+ }
+
+ bas := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(bas) {
+ // allocate new nested message
+ bas = toStructPointer(reflect.New(p.stype))
+ structPointer_SetStructPointer(base, p.field, bas)
+ }
+
+ // If the object can unmarshal itself, let it.
+ if p.isUnmarshaler {
+ iv := structPointer_Interface(bas, p.stype)
+ return iv.(Unmarshaler).Unmarshal(raw)
+ }
+
+ obuf := o.buf
+ oi := o.index
+ o.buf = raw
+ o.index = 0
+
+ err = o.unmarshalType(p.stype, p.sprop, false, bas)
+ o.buf = obuf
+ o.index = oi
+
+ return err
+}
+
+// Decode a slice of embedded messages.
+func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error {
+ return o.dec_slice_struct(p, false, base)
+}
+
+// Decode a slice of embedded groups.
+func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error {
+ return o.dec_slice_struct(p, true, base)
+}
+
+// Decode a slice of structs ([]*struct).
+func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error {
+ v := reflect.New(p.stype)
+ bas := toStructPointer(v)
+ structPointer_StructPointerSlice(base, p.field).Append(bas)
+
+ if is_group {
+ err := o.unmarshalType(p.stype, p.sprop, is_group, bas)
+ return err
+ }
+
+ raw, err := o.DecodeRawBytes(false)
+ if err != nil {
+ return err
+ }
+
+ // If the object can unmarshal itself, let it.
+ if p.isUnmarshaler {
+ iv := v.Interface()
+ return iv.(Unmarshaler).Unmarshal(raw)
+ }
+
+ obuf := o.buf
+ oi := o.index
+ o.buf = raw
+ o.index = 0
+
+ err = o.unmarshalType(p.stype, p.sprop, is_group, bas)
+
+ o.buf = obuf
+ o.index = oi
+
+ return err
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/decode_gogo.go b/vendor/github.com/gogo/protobuf/proto/decode_gogo.go
new file mode 100644
index 0000000..6fb74de
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/decode_gogo.go
@@ -0,0 +1,172 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 proto
+
+import (
+ "reflect"
+)
+
+// Decode a reference to a struct pointer.
+func (o *Buffer) dec_ref_struct_message(p *Properties, base structPointer) (err error) {
+ raw, e := o.DecodeRawBytes(false)
+ if e != nil {
+ return e
+ }
+
+ // If the object can unmarshal itself, let it.
+ if p.isUnmarshaler {
+ panic("not supported, since this is a pointer receiver")
+ }
+
+ obuf := o.buf
+ oi := o.index
+ o.buf = raw
+ o.index = 0
+
+ bas := structPointer_FieldPointer(base, p.field)
+
+ err = o.unmarshalType(p.stype, p.sprop, false, bas)
+ o.buf = obuf
+ o.index = oi
+
+ return err
+}
+
+// Decode a slice of references to struct pointers ([]struct).
+func (o *Buffer) dec_slice_ref_struct(p *Properties, is_group bool, base structPointer) error {
+ newBas := appendStructPointer(base, p.field, p.sstype)
+
+ if is_group {
+ panic("not supported, maybe in future, if requested.")
+ }
+
+ raw, err := o.DecodeRawBytes(false)
+ if err != nil {
+ return err
+ }
+
+ // If the object can unmarshal itself, let it.
+ if p.isUnmarshaler {
+ panic("not supported, since this is not a pointer receiver.")
+ }
+
+ obuf := o.buf
+ oi := o.index
+ o.buf = raw
+ o.index = 0
+
+ err = o.unmarshalType(p.stype, p.sprop, is_group, newBas)
+
+ o.buf = obuf
+ o.index = oi
+
+ return err
+}
+
+// Decode a slice of references to struct pointers.
+func (o *Buffer) dec_slice_ref_struct_message(p *Properties, base structPointer) error {
+ return o.dec_slice_ref_struct(p, false, base)
+}
+
+func setPtrCustomType(base structPointer, f field, v interface{}) {
+ if v == nil {
+ return
+ }
+ structPointer_SetStructPointer(base, f, toStructPointer(reflect.ValueOf(v)))
+}
+
+func setCustomType(base structPointer, f field, value interface{}) {
+ if value == nil {
+ return
+ }
+ v := reflect.ValueOf(value).Elem()
+ t := reflect.TypeOf(value).Elem()
+ kind := t.Kind()
+ switch kind {
+ case reflect.Slice:
+ slice := reflect.MakeSlice(t, v.Len(), v.Cap())
+ reflect.Copy(slice, v)
+ oldHeader := structPointer_GetSliceHeader(base, f)
+ oldHeader.Data = slice.Pointer()
+ oldHeader.Len = v.Len()
+ oldHeader.Cap = v.Cap()
+ default:
+ size := reflect.TypeOf(value).Elem().Size()
+ structPointer_Copy(toStructPointer(reflect.ValueOf(value)), structPointer_Add(base, f), int(size))
+ }
+}
+
+func (o *Buffer) dec_custom_bytes(p *Properties, base structPointer) error {
+ b, err := o.DecodeRawBytes(true)
+ if err != nil {
+ return err
+ }
+ i := reflect.New(p.ctype.Elem()).Interface()
+ custom := (i).(Unmarshaler)
+ if err := custom.Unmarshal(b); err != nil {
+ return err
+ }
+ setPtrCustomType(base, p.field, custom)
+ return nil
+}
+
+func (o *Buffer) dec_custom_ref_bytes(p *Properties, base structPointer) error {
+ b, err := o.DecodeRawBytes(true)
+ if err != nil {
+ return err
+ }
+ i := reflect.New(p.ctype).Interface()
+ custom := (i).(Unmarshaler)
+ if err := custom.Unmarshal(b); err != nil {
+ return err
+ }
+ if custom != nil {
+ setCustomType(base, p.field, custom)
+ }
+ return nil
+}
+
+// Decode a slice of bytes ([]byte) into a slice of custom types.
+func (o *Buffer) dec_custom_slice_bytes(p *Properties, base structPointer) error {
+ b, err := o.DecodeRawBytes(true)
+ if err != nil {
+ return err
+ }
+ i := reflect.New(p.ctype.Elem()).Interface()
+ custom := (i).(Unmarshaler)
+ if err := custom.Unmarshal(b); err != nil {
+ return err
+ }
+ newBas := appendStructPointer(base, p.field, p.ctype)
+
+ var zero field
+ setCustomType(newBas, zero, custom)
+
+ return nil
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/duration.go b/vendor/github.com/gogo/protobuf/proto/duration.go
new file mode 100644
index 0000000..93464c9
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/duration.go
@@ -0,0 +1,100 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+// This file implements conversions between google.protobuf.Duration
+// and time.Duration.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+)
+
+const (
+ // Range of a Duration in seconds, as specified in
+ // google/protobuf/duration.proto. This is about 10,000 years in seconds.
+ maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
+ minSeconds = -maxSeconds
+)
+
+// validateDuration determines whether the Duration is valid according to the
+// definition in google/protobuf/duration.proto. A valid Duration
+// may still be too large to fit into a time.Duration (the range of Duration
+// is about 10,000 years, and the range of time.Duration is about 290).
+func validateDuration(d *duration) error {
+ if d == nil {
+ return errors.New("duration: nil Duration")
+ }
+ if d.Seconds < minSeconds || d.Seconds > maxSeconds {
+ return fmt.Errorf("duration: %#v: seconds out of range", d)
+ }
+ if d.Nanos <= -1e9 || d.Nanos >= 1e9 {
+ return fmt.Errorf("duration: %#v: nanos out of range", d)
+ }
+ // Seconds and Nanos must have the same sign, unless d.Nanos is zero.
+ if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) {
+ return fmt.Errorf("duration: %#v: seconds and nanos have different signs", d)
+ }
+ return nil
+}
+
+// DurationFromProto converts a Duration to a time.Duration. DurationFromProto
+// returns an error if the Duration is invalid or is too large to be
+// represented in a time.Duration.
+func durationFromProto(p *duration) (time.Duration, error) {
+ if err := validateDuration(p); err != nil {
+ return 0, err
+ }
+ d := time.Duration(p.Seconds) * time.Second
+ if int64(d/time.Second) != p.Seconds {
+ return 0, fmt.Errorf("duration: %#v is out of range for time.Duration", p)
+ }
+ if p.Nanos != 0 {
+ d += time.Duration(p.Nanos)
+ if (d < 0) != (p.Nanos < 0) {
+ return 0, fmt.Errorf("duration: %#v is out of range for time.Duration", p)
+ }
+ }
+ return d, nil
+}
+
+// DurationProto converts a time.Duration to a Duration.
+func durationProto(d time.Duration) *duration {
+ nanos := d.Nanoseconds()
+ secs := nanos / 1e9
+ nanos -= secs * 1e9
+ return &duration{
+ Seconds: secs,
+ Nanos: int32(nanos),
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/duration_gogo.go b/vendor/github.com/gogo/protobuf/proto/duration_gogo.go
new file mode 100644
index 0000000..18e2a5f
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/duration_gogo.go
@@ -0,0 +1,203 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2016, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 proto
+
+import (
+ "reflect"
+ "time"
+)
+
+var durationType = reflect.TypeOf((*time.Duration)(nil)).Elem()
+
+type duration struct {
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
+}
+
+func (m *duration) Reset() { *m = duration{} }
+func (*duration) ProtoMessage() {}
+func (*duration) String() string { return "duration<string>" }
+
+func init() {
+ RegisterType((*duration)(nil), "gogo.protobuf.proto.duration")
+}
+
+func (o *Buffer) decDuration() (time.Duration, error) {
+ b, err := o.DecodeRawBytes(true)
+ if err != nil {
+ return 0, err
+ }
+ dproto := &duration{}
+ if err := Unmarshal(b, dproto); err != nil {
+ return 0, err
+ }
+ return durationFromProto(dproto)
+}
+
+func (o *Buffer) dec_duration(p *Properties, base structPointer) error {
+ d, err := o.decDuration()
+ if err != nil {
+ return err
+ }
+ word64_Set(structPointer_Word64(base, p.field), o, uint64(d))
+ return nil
+}
+
+func (o *Buffer) dec_ref_duration(p *Properties, base structPointer) error {
+ d, err := o.decDuration()
+ if err != nil {
+ return err
+ }
+ word64Val_Set(structPointer_Word64Val(base, p.field), o, uint64(d))
+ return nil
+}
+
+func (o *Buffer) dec_slice_duration(p *Properties, base structPointer) error {
+ d, err := o.decDuration()
+ if err != nil {
+ return err
+ }
+ newBas := appendStructPointer(base, p.field, reflect.SliceOf(reflect.PtrTo(durationType)))
+ var zero field
+ setPtrCustomType(newBas, zero, &d)
+ return nil
+}
+
+func (o *Buffer) dec_slice_ref_duration(p *Properties, base structPointer) error {
+ d, err := o.decDuration()
+ if err != nil {
+ return err
+ }
+ structPointer_Word64Slice(base, p.field).Append(uint64(d))
+ return nil
+}
+
+func size_duration(p *Properties, base structPointer) (n int) {
+ structp := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(structp) {
+ return 0
+ }
+ dur := structPointer_Interface(structp, durationType).(*time.Duration)
+ d := durationProto(*dur)
+ size := Size(d)
+ return size + sizeVarint(uint64(size)) + len(p.tagcode)
+}
+
+func (o *Buffer) enc_duration(p *Properties, base structPointer) error {
+ structp := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(structp) {
+ return ErrNil
+ }
+ dur := structPointer_Interface(structp, durationType).(*time.Duration)
+ d := durationProto(*dur)
+ data, err := Marshal(d)
+ if err != nil {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ return nil
+}
+
+func size_ref_duration(p *Properties, base structPointer) (n int) {
+ dur := structPointer_InterfaceAt(base, p.field, durationType).(*time.Duration)
+ d := durationProto(*dur)
+ size := Size(d)
+ return size + sizeVarint(uint64(size)) + len(p.tagcode)
+}
+
+func (o *Buffer) enc_ref_duration(p *Properties, base structPointer) error {
+ dur := structPointer_InterfaceAt(base, p.field, durationType).(*time.Duration)
+ d := durationProto(*dur)
+ data, err := Marshal(d)
+ if err != nil {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ return nil
+}
+
+func size_slice_duration(p *Properties, base structPointer) (n int) {
+ pdurs := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(reflect.PtrTo(durationType))).(*[]*time.Duration)
+ durs := *pdurs
+ for i := 0; i < len(durs); i++ {
+ if durs[i] == nil {
+ return 0
+ }
+ dproto := durationProto(*durs[i])
+ size := Size(dproto)
+ n += len(p.tagcode) + size + sizeVarint(uint64(size))
+ }
+ return n
+}
+
+func (o *Buffer) enc_slice_duration(p *Properties, base structPointer) error {
+ pdurs := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(reflect.PtrTo(durationType))).(*[]*time.Duration)
+ durs := *pdurs
+ for i := 0; i < len(durs); i++ {
+ if durs[i] == nil {
+ return errRepeatedHasNil
+ }
+ dproto := durationProto(*durs[i])
+ data, err := Marshal(dproto)
+ if err != nil {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ }
+ return nil
+}
+
+func size_slice_ref_duration(p *Properties, base structPointer) (n int) {
+ pdurs := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(durationType)).(*[]time.Duration)
+ durs := *pdurs
+ for i := 0; i < len(durs); i++ {
+ dproto := durationProto(durs[i])
+ size := Size(dproto)
+ n += len(p.tagcode) + size + sizeVarint(uint64(size))
+ }
+ return n
+}
+
+func (o *Buffer) enc_slice_ref_duration(p *Properties, base structPointer) error {
+ pdurs := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(durationType)).(*[]time.Duration)
+ durs := *pdurs
+ for i := 0; i < len(durs); i++ {
+ dproto := durationProto(durs[i])
+ data, err := Marshal(dproto)
+ if err != nil {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ }
+ return nil
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/encode.go b/vendor/github.com/gogo/protobuf/proto/encode.go
new file mode 100644
index 0000000..2b30f84
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/encode.go
@@ -0,0 +1,1362 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Routines for encoding data into the wire format for protocol buffers.
+ */
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "sort"
+)
+
+// RequiredNotSetError is the error returned if Marshal is called with
+// a protocol buffer struct whose required fields have not
+// all been initialized. It is also the error returned if Unmarshal is
+// called with an encoded protocol buffer that does not include all the
+// required fields.
+//
+// When printed, RequiredNotSetError reports the first unset required field in a
+// message. If the field cannot be precisely determined, it is reported as
+// "{Unknown}".
+type RequiredNotSetError struct {
+ field string
+}
+
+func (e *RequiredNotSetError) Error() string {
+ return fmt.Sprintf("proto: required field %q not set", e.field)
+}
+
+var (
+ // errRepeatedHasNil is the error returned if Marshal is called with
+ // a struct with a repeated field containing a nil element.
+ errRepeatedHasNil = errors.New("proto: repeated field has nil element")
+
+ // errOneofHasNil is the error returned if Marshal is called with
+ // a struct with a oneof field containing a nil element.
+ errOneofHasNil = errors.New("proto: oneof field has nil value")
+
+ // ErrNil is the error returned if Marshal is called with nil.
+ ErrNil = errors.New("proto: Marshal called with nil")
+
+ // ErrTooLarge is the error returned if Marshal is called with a
+ // message that encodes to >2GB.
+ ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
+)
+
+// The fundamental encoders that put bytes on the wire.
+// Those that take integer types all accept uint64 and are
+// therefore of type valueEncoder.
+
+const maxVarintBytes = 10 // maximum length of a varint
+
+// maxMarshalSize is the largest allowed size of an encoded protobuf,
+// since C++ and Java use signed int32s for the size.
+const maxMarshalSize = 1<<31 - 1
+
+// EncodeVarint returns the varint encoding of x.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+// Not used by the package itself, but helpful to clients
+// wishing to use the same encoding.
+func EncodeVarint(x uint64) []byte {
+ var buf [maxVarintBytes]byte
+ var n int
+ for n = 0; x > 127; n++ {
+ buf[n] = 0x80 | uint8(x&0x7F)
+ x >>= 7
+ }
+ buf[n] = uint8(x)
+ n++
+ return buf[0:n]
+}
+
+// EncodeVarint writes a varint-encoded integer to the Buffer.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func (p *Buffer) EncodeVarint(x uint64) error {
+ for x >= 1<<7 {
+ p.buf = append(p.buf, uint8(x&0x7f|0x80))
+ x >>= 7
+ }
+ p.buf = append(p.buf, uint8(x))
+ return nil
+}
+
+// SizeVarint returns the varint encoding size of an integer.
+func SizeVarint(x uint64) int {
+ return sizeVarint(x)
+}
+
+func sizeVarint(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+
+// EncodeFixed64 writes a 64-bit integer to the Buffer.
+// This is the format for the
+// fixed64, sfixed64, and double protocol buffer types.
+func (p *Buffer) EncodeFixed64(x uint64) error {
+ p.buf = append(p.buf,
+ uint8(x),
+ uint8(x>>8),
+ uint8(x>>16),
+ uint8(x>>24),
+ uint8(x>>32),
+ uint8(x>>40),
+ uint8(x>>48),
+ uint8(x>>56))
+ return nil
+}
+
+func sizeFixed64(x uint64) int {
+ return 8
+}
+
+// EncodeFixed32 writes a 32-bit integer to the Buffer.
+// This is the format for the
+// fixed32, sfixed32, and float protocol buffer types.
+func (p *Buffer) EncodeFixed32(x uint64) error {
+ p.buf = append(p.buf,
+ uint8(x),
+ uint8(x>>8),
+ uint8(x>>16),
+ uint8(x>>24))
+ return nil
+}
+
+func sizeFixed32(x uint64) int {
+ return 4
+}
+
+// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
+// to the Buffer.
+// This is the format used for the sint64 protocol buffer type.
+func (p *Buffer) EncodeZigzag64(x uint64) error {
+ // use signed number to get arithmetic right shift.
+ return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+
+func sizeZigzag64(x uint64) int {
+ return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+
+// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
+// to the Buffer.
+// This is the format used for the sint32 protocol buffer type.
+func (p *Buffer) EncodeZigzag32(x uint64) error {
+ // use signed number to get arithmetic right shift.
+ return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
+}
+
+func sizeZigzag32(x uint64) int {
+ return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
+}
+
+// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
+// This is the format used for the bytes protocol buffer
+// type and for embedded messages.
+func (p *Buffer) EncodeRawBytes(b []byte) error {
+ p.EncodeVarint(uint64(len(b)))
+ p.buf = append(p.buf, b...)
+ return nil
+}
+
+func sizeRawBytes(b []byte) int {
+ return sizeVarint(uint64(len(b))) +
+ len(b)
+}
+
+// EncodeStringBytes writes an encoded string to the Buffer.
+// This is the format used for the proto2 string type.
+func (p *Buffer) EncodeStringBytes(s string) error {
+ p.EncodeVarint(uint64(len(s)))
+ p.buf = append(p.buf, s...)
+ return nil
+}
+
+func sizeStringBytes(s string) int {
+ return sizeVarint(uint64(len(s))) +
+ len(s)
+}
+
+// Marshaler is the interface representing objects that can marshal themselves.
+type Marshaler interface {
+ Marshal() ([]byte, error)
+}
+
+// Marshal takes the protocol buffer
+// and encodes it into the wire format, returning the data.
+func Marshal(pb Message) ([]byte, error) {
+ // Can the object marshal itself?
+ if m, ok := pb.(Marshaler); ok {
+ return m.Marshal()
+ }
+ p := NewBuffer(nil)
+ err := p.Marshal(pb)
+ if p.buf == nil && err == nil {
+ // Return a non-nil slice on success.
+ return []byte{}, nil
+ }
+ return p.buf, err
+}
+
+// EncodeMessage writes the protocol buffer to the Buffer,
+// prefixed by a varint-encoded length.
+func (p *Buffer) EncodeMessage(pb Message) error {
+ t, base, err := getbase(pb)
+ if structPointer_IsNil(base) {
+ return ErrNil
+ }
+ if err == nil {
+ var state errorState
+ err = p.enc_len_struct(GetProperties(t.Elem()), base, &state)
+ }
+ return err
+}
+
+// Marshal takes the protocol buffer
+// and encodes it into the wire format, writing the result to the
+// Buffer.
+func (p *Buffer) Marshal(pb Message) error {
+ // Can the object marshal itself?
+ if m, ok := pb.(Marshaler); ok {
+ data, err := m.Marshal()
+ p.buf = append(p.buf, data...)
+ return err
+ }
+
+ t, base, err := getbase(pb)
+ if structPointer_IsNil(base) {
+ return ErrNil
+ }
+ if err == nil {
+ err = p.enc_struct(GetProperties(t.Elem()), base)
+ }
+
+ if collectStats {
+ (stats).Encode++ // Parens are to work around a goimports bug.
+ }
+
+ if len(p.buf) > maxMarshalSize {
+ return ErrTooLarge
+ }
+ return err
+}
+
+// Size returns the encoded size of a protocol buffer.
+func Size(pb Message) (n int) {
+ // Can the object marshal itself? If so, Size is slow.
+ // TODO: add Size to Marshaler, or add a Sizer interface.
+ if m, ok := pb.(Marshaler); ok {
+ b, _ := m.Marshal()
+ return len(b)
+ }
+
+ t, base, err := getbase(pb)
+ if structPointer_IsNil(base) {
+ return 0
+ }
+ if err == nil {
+ n = size_struct(GetProperties(t.Elem()), base)
+ }
+
+ if collectStats {
+ (stats).Size++ // Parens are to work around a goimports bug.
+ }
+
+ return
+}
+
+// Individual type encoders.
+
+// Encode a bool.
+func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
+ v := *structPointer_Bool(base, p.field)
+ if v == nil {
+ return ErrNil
+ }
+ x := 0
+ if *v {
+ x = 1
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error {
+ v := *structPointer_BoolVal(base, p.field)
+ if !v {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, 1)
+ return nil
+}
+
+func size_bool(p *Properties, base structPointer) int {
+ v := *structPointer_Bool(base, p.field)
+ if v == nil {
+ return 0
+ }
+ return len(p.tagcode) + 1 // each bool takes exactly one byte
+}
+
+func size_proto3_bool(p *Properties, base structPointer) int {
+ v := *structPointer_BoolVal(base, p.field)
+ if !v && !p.oneof {
+ return 0
+ }
+ return len(p.tagcode) + 1 // each bool takes exactly one byte
+}
+
+// Encode an int32.
+func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
+ v := structPointer_Word32(base, p.field)
+ if word32_IsNil(v) {
+ return ErrNil
+ }
+ x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error {
+ v := structPointer_Word32Val(base, p.field)
+ x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
+ if x == 0 {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func size_int32(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word32(base, p.field)
+ if word32_IsNil(v) {
+ return 0
+ }
+ x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
+ n += len(p.tagcode)
+ n += p.valSize(uint64(x))
+ return
+}
+
+func size_proto3_int32(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word32Val(base, p.field)
+ x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
+ if x == 0 && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += p.valSize(uint64(x))
+ return
+}
+
+// Encode a uint32.
+// Exactly the same as int32, except for no sign extension.
+func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
+ v := structPointer_Word32(base, p.field)
+ if word32_IsNil(v) {
+ return ErrNil
+ }
+ x := word32_Get(v)
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error {
+ v := structPointer_Word32Val(base, p.field)
+ x := word32Val_Get(v)
+ if x == 0 {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func size_uint32(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word32(base, p.field)
+ if word32_IsNil(v) {
+ return 0
+ }
+ x := word32_Get(v)
+ n += len(p.tagcode)
+ n += p.valSize(uint64(x))
+ return
+}
+
+func size_proto3_uint32(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word32Val(base, p.field)
+ x := word32Val_Get(v)
+ if x == 0 && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += p.valSize(uint64(x))
+ return
+}
+
+// Encode an int64.
+func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
+ v := structPointer_Word64(base, p.field)
+ if word64_IsNil(v) {
+ return ErrNil
+ }
+ x := word64_Get(v)
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, x)
+ return nil
+}
+
+func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error {
+ v := structPointer_Word64Val(base, p.field)
+ x := word64Val_Get(v)
+ if x == 0 {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, x)
+ return nil
+}
+
+func size_int64(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word64(base, p.field)
+ if word64_IsNil(v) {
+ return 0
+ }
+ x := word64_Get(v)
+ n += len(p.tagcode)
+ n += p.valSize(x)
+ return
+}
+
+func size_proto3_int64(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word64Val(base, p.field)
+ x := word64Val_Get(v)
+ if x == 0 && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += p.valSize(x)
+ return
+}
+
+// Encode a string.
+func (o *Buffer) enc_string(p *Properties, base structPointer) error {
+ v := *structPointer_String(base, p.field)
+ if v == nil {
+ return ErrNil
+ }
+ x := *v
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeStringBytes(x)
+ return nil
+}
+
+func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error {
+ v := *structPointer_StringVal(base, p.field)
+ if v == "" {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeStringBytes(v)
+ return nil
+}
+
+func size_string(p *Properties, base structPointer) (n int) {
+ v := *structPointer_String(base, p.field)
+ if v == nil {
+ return 0
+ }
+ x := *v
+ n += len(p.tagcode)
+ n += sizeStringBytes(x)
+ return
+}
+
+func size_proto3_string(p *Properties, base structPointer) (n int) {
+ v := *structPointer_StringVal(base, p.field)
+ if v == "" && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += sizeStringBytes(v)
+ return
+}
+
+// All protocol buffer fields are nillable, but be careful.
+func isNil(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ return v.IsNil()
+ }
+ return false
+}
+
+// Encode a message struct.
+func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
+ var state errorState
+ structp := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(structp) {
+ return ErrNil
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, err := m.Marshal()
+ if err != nil && !state.shouldContinue(err, nil) {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ return state.err
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ return o.enc_len_struct(p.sprop, structp, &state)
+}
+
+func size_struct_message(p *Properties, base structPointer) int {
+ structp := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(structp) {
+ return 0
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, _ := m.Marshal()
+ n0 := len(p.tagcode)
+ n1 := sizeRawBytes(data)
+ return n0 + n1
+ }
+
+ n0 := len(p.tagcode)
+ n1 := size_struct(p.sprop, structp)
+ n2 := sizeVarint(uint64(n1)) // size of encoded length
+ return n0 + n1 + n2
+}
+
+// Encode a group struct.
+func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
+ var state errorState
+ b := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(b) {
+ return ErrNil
+ }
+
+ o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
+ err := o.enc_struct(p.sprop, b)
+ if err != nil && !state.shouldContinue(err, nil) {
+ return err
+ }
+ o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
+ return state.err
+}
+
+func size_struct_group(p *Properties, base structPointer) (n int) {
+ b := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(b) {
+ return 0
+ }
+
+ n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
+ n += size_struct(p.sprop, b)
+ n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
+ return
+}
+
+// Encode a slice of bools ([]bool).
+func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
+ s := *structPointer_BoolSlice(base, p.field)
+ l := len(s)
+ if l == 0 {
+ return ErrNil
+ }
+ for _, x := range s {
+ o.buf = append(o.buf, p.tagcode...)
+ v := uint64(0)
+ if x {
+ v = 1
+ }
+ p.valEnc(o, v)
+ }
+ return nil
+}
+
+func size_slice_bool(p *Properties, base structPointer) int {
+ s := *structPointer_BoolSlice(base, p.field)
+ l := len(s)
+ if l == 0 {
+ return 0
+ }
+ return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
+}
+
+// Encode a slice of bools ([]bool) in packed format.
+func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
+ s := *structPointer_BoolSlice(base, p.field)
+ l := len(s)
+ if l == 0 {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
+ for _, x := range s {
+ v := uint64(0)
+ if x {
+ v = 1
+ }
+ p.valEnc(o, v)
+ }
+ return nil
+}
+
+func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
+ s := *structPointer_BoolSlice(base, p.field)
+ l := len(s)
+ if l == 0 {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += sizeVarint(uint64(l))
+ n += l // each bool takes exactly one byte
+ return
+}
+
+// Encode a slice of bytes ([]byte).
+func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
+ s := *structPointer_Bytes(base, p.field)
+ if s == nil {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(s)
+ return nil
+}
+
+func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error {
+ s := *structPointer_Bytes(base, p.field)
+ if len(s) == 0 {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(s)
+ return nil
+}
+
+func size_slice_byte(p *Properties, base structPointer) (n int) {
+ s := *structPointer_Bytes(base, p.field)
+ if s == nil && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += sizeRawBytes(s)
+ return
+}
+
+func size_proto3_slice_byte(p *Properties, base structPointer) (n int) {
+ s := *structPointer_Bytes(base, p.field)
+ if len(s) == 0 && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += sizeRawBytes(s)
+ return
+}
+
+// Encode a slice of int32s ([]int32).
+func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ for i := 0; i < l; i++ {
+ o.buf = append(o.buf, p.tagcode...)
+ x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+ p.valEnc(o, uint64(x))
+ }
+ return nil
+}
+
+func size_slice_int32(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ for i := 0; i < l; i++ {
+ n += len(p.tagcode)
+ x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+ n += p.valSize(uint64(x))
+ }
+ return
+}
+
+// Encode a slice of int32s ([]int32) in packed format.
+func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ // TODO: Reuse a Buffer.
+ buf := NewBuffer(nil)
+ for i := 0; i < l; i++ {
+ x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+ p.valEnc(buf, uint64(x))
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeVarint(uint64(len(buf.buf)))
+ o.buf = append(o.buf, buf.buf...)
+ return nil
+}
+
+func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ var bufSize int
+ for i := 0; i < l; i++ {
+ x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+ bufSize += p.valSize(uint64(x))
+ }
+
+ n += len(p.tagcode)
+ n += sizeVarint(uint64(bufSize))
+ n += bufSize
+ return
+}
+
+// Encode a slice of uint32s ([]uint32).
+// Exactly the same as int32, except for no sign extension.
+func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ for i := 0; i < l; i++ {
+ o.buf = append(o.buf, p.tagcode...)
+ x := s.Index(i)
+ p.valEnc(o, uint64(x))
+ }
+ return nil
+}
+
+func size_slice_uint32(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ for i := 0; i < l; i++ {
+ n += len(p.tagcode)
+ x := s.Index(i)
+ n += p.valSize(uint64(x))
+ }
+ return
+}
+
+// Encode a slice of uint32s ([]uint32) in packed format.
+// Exactly the same as int32, except for no sign extension.
+func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ // TODO: Reuse a Buffer.
+ buf := NewBuffer(nil)
+ for i := 0; i < l; i++ {
+ p.valEnc(buf, uint64(s.Index(i)))
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeVarint(uint64(len(buf.buf)))
+ o.buf = append(o.buf, buf.buf...)
+ return nil
+}
+
+func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ var bufSize int
+ for i := 0; i < l; i++ {
+ bufSize += p.valSize(uint64(s.Index(i)))
+ }
+
+ n += len(p.tagcode)
+ n += sizeVarint(uint64(bufSize))
+ n += bufSize
+ return
+}
+
+// Encode a slice of int64s ([]int64).
+func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
+ s := structPointer_Word64Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ for i := 0; i < l; i++ {
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, s.Index(i))
+ }
+ return nil
+}
+
+func size_slice_int64(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word64Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ for i := 0; i < l; i++ {
+ n += len(p.tagcode)
+ n += p.valSize(s.Index(i))
+ }
+ return
+}
+
+// Encode a slice of int64s ([]int64) in packed format.
+func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
+ s := structPointer_Word64Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ // TODO: Reuse a Buffer.
+ buf := NewBuffer(nil)
+ for i := 0; i < l; i++ {
+ p.valEnc(buf, s.Index(i))
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeVarint(uint64(len(buf.buf)))
+ o.buf = append(o.buf, buf.buf...)
+ return nil
+}
+
+func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word64Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ var bufSize int
+ for i := 0; i < l; i++ {
+ bufSize += p.valSize(s.Index(i))
+ }
+
+ n += len(p.tagcode)
+ n += sizeVarint(uint64(bufSize))
+ n += bufSize
+ return
+}
+
+// Encode a slice of slice of bytes ([][]byte).
+func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
+ ss := *structPointer_BytesSlice(base, p.field)
+ l := len(ss)
+ if l == 0 {
+ return ErrNil
+ }
+ for i := 0; i < l; i++ {
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(ss[i])
+ }
+ return nil
+}
+
+func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
+ ss := *structPointer_BytesSlice(base, p.field)
+ l := len(ss)
+ if l == 0 {
+ return 0
+ }
+ n += l * len(p.tagcode)
+ for i := 0; i < l; i++ {
+ n += sizeRawBytes(ss[i])
+ }
+ return
+}
+
+// Encode a slice of strings ([]string).
+func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
+ ss := *structPointer_StringSlice(base, p.field)
+ l := len(ss)
+ for i := 0; i < l; i++ {
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeStringBytes(ss[i])
+ }
+ return nil
+}
+
+func size_slice_string(p *Properties, base structPointer) (n int) {
+ ss := *structPointer_StringSlice(base, p.field)
+ l := len(ss)
+ n += l * len(p.tagcode)
+ for i := 0; i < l; i++ {
+ n += sizeStringBytes(ss[i])
+ }
+ return
+}
+
+// Encode a slice of message structs ([]*struct).
+func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
+ var state errorState
+ s := structPointer_StructPointerSlice(base, p.field)
+ l := s.Len()
+
+ for i := 0; i < l; i++ {
+ structp := s.Index(i)
+ if structPointer_IsNil(structp) {
+ return errRepeatedHasNil
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, err := m.Marshal()
+ if err != nil && !state.shouldContinue(err, nil) {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ continue
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ err := o.enc_len_struct(p.sprop, structp, &state)
+ if err != nil && !state.shouldContinue(err, nil) {
+ if err == ErrNil {
+ return errRepeatedHasNil
+ }
+ return err
+ }
+ }
+ return state.err
+}
+
+func size_slice_struct_message(p *Properties, base structPointer) (n int) {
+ s := structPointer_StructPointerSlice(base, p.field)
+ l := s.Len()
+ n += l * len(p.tagcode)
+ for i := 0; i < l; i++ {
+ structp := s.Index(i)
+ if structPointer_IsNil(structp) {
+ return // return the size up to this point
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, _ := m.Marshal()
+ n += sizeRawBytes(data)
+ continue
+ }
+
+ n0 := size_struct(p.sprop, structp)
+ n1 := sizeVarint(uint64(n0)) // size of encoded length
+ n += n0 + n1
+ }
+ return
+}
+
+// Encode a slice of group structs ([]*struct).
+func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
+ var state errorState
+ s := structPointer_StructPointerSlice(base, p.field)
+ l := s.Len()
+
+ for i := 0; i < l; i++ {
+ b := s.Index(i)
+ if structPointer_IsNil(b) {
+ return errRepeatedHasNil
+ }
+
+ o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
+
+ err := o.enc_struct(p.sprop, b)
+
+ if err != nil && !state.shouldContinue(err, nil) {
+ if err == ErrNil {
+ return errRepeatedHasNil
+ }
+ return err
+ }
+
+ o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
+ }
+ return state.err
+}
+
+func size_slice_struct_group(p *Properties, base structPointer) (n int) {
+ s := structPointer_StructPointerSlice(base, p.field)
+ l := s.Len()
+
+ n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup))
+ n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup))
+ for i := 0; i < l; i++ {
+ b := s.Index(i)
+ if structPointer_IsNil(b) {
+ return // return size up to this point
+ }
+
+ n += size_struct(p.sprop, b)
+ }
+ return
+}
+
+// Encode an extension map.
+func (o *Buffer) enc_map(p *Properties, base structPointer) error {
+ exts := structPointer_ExtMap(base, p.field)
+ if err := encodeExtensionsMap(*exts); err != nil {
+ return err
+ }
+
+ return o.enc_map_body(*exts)
+}
+
+func (o *Buffer) enc_exts(p *Properties, base structPointer) error {
+ exts := structPointer_Extensions(base, p.field)
+
+ v, mu := exts.extensionsRead()
+ if v == nil {
+ return nil
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ if err := encodeExtensionsMap(v); err != nil {
+ return err
+ }
+
+ return o.enc_map_body(v)
+}
+
+func (o *Buffer) enc_map_body(v map[int32]Extension) error {
+ // Fast-path for common cases: zero or one extensions.
+ if len(v) <= 1 {
+ for _, e := range v {
+ o.buf = append(o.buf, e.enc...)
+ }
+ return nil
+ }
+
+ // Sort keys to provide a deterministic encoding.
+ keys := make([]int, 0, len(v))
+ for k := range v {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+
+ for _, k := range keys {
+ o.buf = append(o.buf, v[int32(k)].enc...)
+ }
+ return nil
+}
+
+func size_map(p *Properties, base structPointer) int {
+ v := structPointer_ExtMap(base, p.field)
+ return extensionsMapSize(*v)
+}
+
+func size_exts(p *Properties, base structPointer) int {
+ v := structPointer_Extensions(base, p.field)
+ return extensionsSize(v)
+}
+
+// Encode a map field.
+func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
+ var state errorState // XXX: or do we need to plumb this through?
+
+ /*
+ A map defined as
+ map<key_type, value_type> map_field = N;
+ is encoded in the same way as
+ message MapFieldEntry {
+ key_type key = 1;
+ value_type value = 2;
+ }
+ repeated MapFieldEntry map_field = N;
+ */
+
+ v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
+ if v.Len() == 0 {
+ return nil
+ }
+
+ keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
+
+ enc := func() error {
+ if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil {
+ return err
+ }
+ if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil {
+ return err
+ }
+ return nil
+ }
+
+ // Don't sort map keys. It is not required by the spec, and C++ doesn't do it.
+ for _, key := range v.MapKeys() {
+ val := v.MapIndex(key)
+
+ keycopy.Set(key)
+ valcopy.Set(val)
+
+ o.buf = append(o.buf, p.tagcode...)
+ if err := o.enc_len_thing(enc, &state); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func size_new_map(p *Properties, base structPointer) int {
+ v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
+
+ keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
+
+ n := 0
+ for _, key := range v.MapKeys() {
+ val := v.MapIndex(key)
+ keycopy.Set(key)
+ valcopy.Set(val)
+
+ // Tag codes for key and val are the responsibility of the sub-sizer.
+ keysize := p.mkeyprop.size(p.mkeyprop, keybase)
+ valsize := p.mvalprop.size(p.mvalprop, valbase)
+ entry := keysize + valsize
+ // Add on tag code and length of map entry itself.
+ n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry
+ }
+ return n
+}
+
+// mapEncodeScratch returns a new reflect.Value matching the map's value type,
+// and a structPointer suitable for passing to an encoder or sizer.
+func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
+ // Prepare addressable doubly-indirect placeholders for the key and value types.
+ // This is needed because the element-type encoders expect **T, but the map iteration produces T.
+
+ keycopy = reflect.New(mapType.Key()).Elem() // addressable K
+ keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
+ keyptr.Set(keycopy.Addr()) //
+ keybase = toStructPointer(keyptr.Addr()) // **K
+
+ // Value types are more varied and require special handling.
+ switch mapType.Elem().Kind() {
+ case reflect.Slice:
+ // []byte
+ var dummy []byte
+ valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
+ valbase = toStructPointer(valcopy.Addr())
+ case reflect.Ptr:
+ // message; the generated field type is map[K]*Msg (so V is *Msg),
+ // so we only need one level of indirection.
+ valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
+ valbase = toStructPointer(valcopy.Addr())
+ default:
+ // everything else
+ valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
+ valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
+ valptr.Set(valcopy.Addr()) //
+ valbase = toStructPointer(valptr.Addr()) // **V
+ }
+ return
+}
+
+// Encode a struct.
+func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
+ var state errorState
+ // Encode fields in tag order so that decoders may use optimizations
+ // that depend on the ordering.
+ // https://developers.google.com/protocol-buffers/docs/encoding#order
+ for _, i := range prop.order {
+ p := prop.Prop[i]
+ if p.enc != nil {
+ err := p.enc(o, p, base)
+ if err != nil {
+ if err == ErrNil {
+ if p.Required && state.err == nil {
+ state.err = &RequiredNotSetError{p.Name}
+ }
+ } else if err == errRepeatedHasNil {
+ // Give more context to nil values in repeated fields.
+ return errors.New("repeated field " + p.OrigName + " has nil element")
+ } else if !state.shouldContinue(err, p) {
+ return err
+ }
+ }
+ if len(o.buf) > maxMarshalSize {
+ return ErrTooLarge
+ }
+ }
+ }
+
+ // Do oneof fields.
+ if prop.oneofMarshaler != nil {
+ m := structPointer_Interface(base, prop.stype).(Message)
+ if err := prop.oneofMarshaler(m, o); err == ErrNil {
+ return errOneofHasNil
+ } else if err != nil {
+ return err
+ }
+ }
+
+ // Add unrecognized fields at the end.
+ if prop.unrecField.IsValid() {
+ v := *structPointer_Bytes(base, prop.unrecField)
+ if len(o.buf)+len(v) > maxMarshalSize {
+ return ErrTooLarge
+ }
+ if len(v) > 0 {
+ o.buf = append(o.buf, v...)
+ }
+ }
+
+ return state.err
+}
+
+func size_struct(prop *StructProperties, base structPointer) (n int) {
+ for _, i := range prop.order {
+ p := prop.Prop[i]
+ if p.size != nil {
+ n += p.size(p, base)
+ }
+ }
+
+ // Add unrecognized fields at the end.
+ if prop.unrecField.IsValid() {
+ v := *structPointer_Bytes(base, prop.unrecField)
+ n += len(v)
+ }
+
+ // Factor in any oneof fields.
+ if prop.oneofSizer != nil {
+ m := structPointer_Interface(base, prop.stype).(Message)
+ n += prop.oneofSizer(m)
+ }
+
+ return
+}
+
+var zeroes [20]byte // longer than any conceivable sizeVarint
+
+// Encode a struct, preceded by its encoded length (as a varint).
+func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error {
+ return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state)
+}
+
+// Encode something, preceded by its encoded length (as a varint).
+func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error {
+ iLen := len(o.buf)
+ o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
+ iMsg := len(o.buf)
+ err := enc()
+ if err != nil && !state.shouldContinue(err, nil) {
+ return err
+ }
+ lMsg := len(o.buf) - iMsg
+ lLen := sizeVarint(uint64(lMsg))
+ switch x := lLen - (iMsg - iLen); {
+ case x > 0: // actual length is x bytes larger than the space we reserved
+ // Move msg x bytes right.
+ o.buf = append(o.buf, zeroes[:x]...)
+ copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
+ case x < 0: // actual length is x bytes smaller than the space we reserved
+ // Move msg x bytes left.
+ copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
+ o.buf = o.buf[:len(o.buf)+x] // x is negative
+ }
+ // Encode the length in the reserved space.
+ o.buf = o.buf[:iLen]
+ o.EncodeVarint(uint64(lMsg))
+ o.buf = o.buf[:len(o.buf)+lMsg]
+ return state.err
+}
+
+// errorState maintains the first error that occurs and updates that error
+// with additional context.
+type errorState struct {
+ err error
+}
+
+// shouldContinue reports whether encoding should continue upon encountering the
+// given error. If the error is RequiredNotSetError, shouldContinue returns true
+// and, if this is the first appearance of that error, remembers it for future
+// reporting.
+//
+// If prop is not nil, it may update any error with additional context about the
+// field with the error.
+func (s *errorState) shouldContinue(err error, prop *Properties) bool {
+ // Ignore unset required fields.
+ reqNotSet, ok := err.(*RequiredNotSetError)
+ if !ok {
+ return false
+ }
+ if s.err == nil {
+ if prop != nil {
+ err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
+ }
+ s.err = err
+ }
+ return true
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/encode_gogo.go b/vendor/github.com/gogo/protobuf/proto/encode_gogo.go
new file mode 100644
index 0000000..32111b7
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/encode_gogo.go
@@ -0,0 +1,350 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// http://github.com/golang/protobuf/
+//
+// 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.
+
+package proto
+
+import (
+ "reflect"
+)
+
+func NewRequiredNotSetError(field string) *RequiredNotSetError {
+ return &RequiredNotSetError{field}
+}
+
+type Sizer interface {
+ Size() int
+}
+
+func (o *Buffer) enc_ext_slice_byte(p *Properties, base structPointer) error {
+ s := *structPointer_Bytes(base, p.field)
+ if s == nil {
+ return ErrNil
+ }
+ o.buf = append(o.buf, s...)
+ return nil
+}
+
+func size_ext_slice_byte(p *Properties, base structPointer) (n int) {
+ s := *structPointer_Bytes(base, p.field)
+ if s == nil {
+ return 0
+ }
+ n += len(s)
+ return
+}
+
+// Encode a reference to bool pointer.
+func (o *Buffer) enc_ref_bool(p *Properties, base structPointer) error {
+ v := *structPointer_BoolVal(base, p.field)
+ x := 0
+ if v {
+ x = 1
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func size_ref_bool(p *Properties, base structPointer) int {
+ return len(p.tagcode) + 1 // each bool takes exactly one byte
+}
+
+// Encode a reference to int32 pointer.
+func (o *Buffer) enc_ref_int32(p *Properties, base structPointer) error {
+ v := structPointer_Word32Val(base, p.field)
+ x := int32(word32Val_Get(v))
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func size_ref_int32(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word32Val(base, p.field)
+ x := int32(word32Val_Get(v))
+ n += len(p.tagcode)
+ n += p.valSize(uint64(x))
+ return
+}
+
+func (o *Buffer) enc_ref_uint32(p *Properties, base structPointer) error {
+ v := structPointer_Word32Val(base, p.field)
+ x := word32Val_Get(v)
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func size_ref_uint32(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word32Val(base, p.field)
+ x := word32Val_Get(v)
+ n += len(p.tagcode)
+ n += p.valSize(uint64(x))
+ return
+}
+
+// Encode a reference to an int64 pointer.
+func (o *Buffer) enc_ref_int64(p *Properties, base structPointer) error {
+ v := structPointer_Word64Val(base, p.field)
+ x := word64Val_Get(v)
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, x)
+ return nil
+}
+
+func size_ref_int64(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word64Val(base, p.field)
+ x := word64Val_Get(v)
+ n += len(p.tagcode)
+ n += p.valSize(x)
+ return
+}
+
+// Encode a reference to a string pointer.
+func (o *Buffer) enc_ref_string(p *Properties, base structPointer) error {
+ v := *structPointer_StringVal(base, p.field)
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeStringBytes(v)
+ return nil
+}
+
+func size_ref_string(p *Properties, base structPointer) (n int) {
+ v := *structPointer_StringVal(base, p.field)
+ n += len(p.tagcode)
+ n += sizeStringBytes(v)
+ return
+}
+
+// Encode a reference to a message struct.
+func (o *Buffer) enc_ref_struct_message(p *Properties, base structPointer) error {
+ var state errorState
+ structp := structPointer_GetRefStructPointer(base, p.field)
+ if structPointer_IsNil(structp) {
+ return ErrNil
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, err := m.Marshal()
+ if err != nil && !state.shouldContinue(err, nil) {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ return nil
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ return o.enc_len_struct(p.sprop, structp, &state)
+}
+
+//TODO this is only copied, please fix this
+func size_ref_struct_message(p *Properties, base structPointer) int {
+ structp := structPointer_GetRefStructPointer(base, p.field)
+ if structPointer_IsNil(structp) {
+ return 0
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, _ := m.Marshal()
+ n0 := len(p.tagcode)
+ n1 := sizeRawBytes(data)
+ return n0 + n1
+ }
+
+ n0 := len(p.tagcode)
+ n1 := size_struct(p.sprop, structp)
+ n2 := sizeVarint(uint64(n1)) // size of encoded length
+ return n0 + n1 + n2
+}
+
+// Encode a slice of references to message struct pointers ([]struct).
+func (o *Buffer) enc_slice_ref_struct_message(p *Properties, base structPointer) error {
+ var state errorState
+ ss := structPointer_StructRefSlice(base, p.field, p.stype.Size())
+ l := ss.Len()
+ for i := 0; i < l; i++ {
+ structp := ss.Index(i)
+ if structPointer_IsNil(structp) {
+ return errRepeatedHasNil
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, err := m.Marshal()
+ if err != nil && !state.shouldContinue(err, nil) {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ continue
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ err := o.enc_len_struct(p.sprop, structp, &state)
+ if err != nil && !state.shouldContinue(err, nil) {
+ if err == ErrNil {
+ return errRepeatedHasNil
+ }
+ return err
+ }
+
+ }
+ return state.err
+}
+
+//TODO this is only copied, please fix this
+func size_slice_ref_struct_message(p *Properties, base structPointer) (n int) {
+ ss := structPointer_StructRefSlice(base, p.field, p.stype.Size())
+ l := ss.Len()
+ n += l * len(p.tagcode)
+ for i := 0; i < l; i++ {
+ structp := ss.Index(i)
+ if structPointer_IsNil(structp) {
+ return // return the size up to this point
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, _ := m.Marshal()
+ n += len(p.tagcode)
+ n += sizeRawBytes(data)
+ continue
+ }
+
+ n0 := size_struct(p.sprop, structp)
+ n1 := sizeVarint(uint64(n0)) // size of encoded length
+ n += n0 + n1
+ }
+ return
+}
+
+func (o *Buffer) enc_custom_bytes(p *Properties, base structPointer) error {
+ i := structPointer_InterfaceRef(base, p.field, p.ctype)
+ if i == nil {
+ return ErrNil
+ }
+ custom := i.(Marshaler)
+ data, err := custom.Marshal()
+ if err != nil {
+ return err
+ }
+ if data == nil {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ return nil
+}
+
+func size_custom_bytes(p *Properties, base structPointer) (n int) {
+ n += len(p.tagcode)
+ i := structPointer_InterfaceRef(base, p.field, p.ctype)
+ if i == nil {
+ return 0
+ }
+ custom := i.(Marshaler)
+ data, _ := custom.Marshal()
+ n += sizeRawBytes(data)
+ return
+}
+
+func (o *Buffer) enc_custom_ref_bytes(p *Properties, base structPointer) error {
+ custom := structPointer_InterfaceAt(base, p.field, p.ctype).(Marshaler)
+ data, err := custom.Marshal()
+ if err != nil {
+ return err
+ }
+ if data == nil {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ return nil
+}
+
+func size_custom_ref_bytes(p *Properties, base structPointer) (n int) {
+ n += len(p.tagcode)
+ i := structPointer_InterfaceAt(base, p.field, p.ctype)
+ if i == nil {
+ return 0
+ }
+ custom := i.(Marshaler)
+ data, _ := custom.Marshal()
+ n += sizeRawBytes(data)
+ return
+}
+
+func (o *Buffer) enc_custom_slice_bytes(p *Properties, base structPointer) error {
+ inter := structPointer_InterfaceRef(base, p.field, p.ctype)
+ if inter == nil {
+ return ErrNil
+ }
+ slice := reflect.ValueOf(inter)
+ l := slice.Len()
+ for i := 0; i < l; i++ {
+ v := slice.Index(i)
+ custom := v.Interface().(Marshaler)
+ data, err := custom.Marshal()
+ if err != nil {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ }
+ return nil
+}
+
+func size_custom_slice_bytes(p *Properties, base structPointer) (n int) {
+ inter := structPointer_InterfaceRef(base, p.field, p.ctype)
+ if inter == nil {
+ return 0
+ }
+ slice := reflect.ValueOf(inter)
+ l := slice.Len()
+ n += l * len(p.tagcode)
+ for i := 0; i < l; i++ {
+ v := slice.Index(i)
+ custom := v.Interface().(Marshaler)
+ data, _ := custom.Marshal()
+ n += sizeRawBytes(data)
+ }
+ return
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/equal.go b/vendor/github.com/gogo/protobuf/proto/equal.go
new file mode 100644
index 0000000..2ed1cf5
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/equal.go
@@ -0,0 +1,300 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2011 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// Protocol buffer comparison.
+
+package proto
+
+import (
+ "bytes"
+ "log"
+ "reflect"
+ "strings"
+)
+
+/*
+Equal returns true iff protocol buffers a and b are equal.
+The arguments must both be pointers to protocol buffer structs.
+
+Equality is defined in this way:
+ - Two messages are equal iff they are the same type,
+ corresponding fields are equal, unknown field sets
+ are equal, and extensions sets are equal.
+ - Two set scalar fields are equal iff their values are equal.
+ If the fields are of a floating-point type, remember that
+ NaN != x for all x, including NaN. If the message is defined
+ 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. 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.
+*/
+func Equal(a, b Message) bool {
+ if a == nil || b == nil {
+ return a == b
+ }
+ v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
+ if v1.Type() != v2.Type() {
+ return false
+ }
+ if v1.Kind() == reflect.Ptr {
+ if v1.IsNil() {
+ return v2.IsNil()
+ }
+ if v2.IsNil() {
+ return false
+ }
+ v1, v2 = v1.Elem(), v2.Elem()
+ }
+ if v1.Kind() != reflect.Struct {
+ return false
+ }
+ return equalStruct(v1, v2)
+}
+
+// v1 and v2 are known to have the same type.
+func equalStruct(v1, v2 reflect.Value) bool {
+ sprop := GetProperties(v1.Type())
+ for i := 0; i < v1.NumField(); i++ {
+ f := v1.Type().Field(i)
+ if strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+ f1, f2 := v1.Field(i), v2.Field(i)
+ if f.Type.Kind() == reflect.Ptr {
+ if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
+ // both unset
+ continue
+ } else if n1 != n2 {
+ // set/unset mismatch
+ return false
+ }
+ b1, ok := f1.Interface().(raw)
+ if ok {
+ b2 := f2.Interface().(raw)
+ // RawMessage
+ if !bytes.Equal(b1.Bytes(), b2.Bytes()) {
+ return false
+ }
+ continue
+ }
+ f1, f2 = f1.Elem(), f2.Elem()
+ }
+ if !equalAny(f1, f2, sprop.Prop[i]) {
+ return false
+ }
+ }
+
+ if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() {
+ em2 := v2.FieldByName("XXX_InternalExtensions")
+ if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) {
+ return false
+ }
+ }
+
+ if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
+ em2 := v2.FieldByName("XXX_extensions")
+ if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
+ return false
+ }
+ }
+
+ uf := v1.FieldByName("XXX_unrecognized")
+ if !uf.IsValid() {
+ return true
+ }
+
+ u1 := uf.Bytes()
+ u2 := v2.FieldByName("XXX_unrecognized").Bytes()
+ if !bytes.Equal(u1, u2) {
+ return false
+ }
+
+ return true
+}
+
+// v1 and v2 are known to have the same type.
+// prop may be nil.
+func equalAny(v1, v2 reflect.Value, prop *Properties) bool {
+ if v1.Type() == protoMessageType {
+ m1, _ := v1.Interface().(Message)
+ m2, _ := v2.Interface().(Message)
+ return Equal(m1, m2)
+ }
+ switch v1.Kind() {
+ case reflect.Bool:
+ return v1.Bool() == v2.Bool()
+ case reflect.Float32, reflect.Float64:
+ return v1.Float() == v2.Float()
+ case reflect.Int32, reflect.Int64:
+ return v1.Int() == v2.Int()
+ case reflect.Interface:
+ // Probably a oneof field; compare the inner values.
+ n1, n2 := v1.IsNil(), v2.IsNil()
+ if n1 || n2 {
+ return n1 == n2
+ }
+ e1, e2 := v1.Elem(), v2.Elem()
+ if e1.Type() != e2.Type() {
+ return false
+ }
+ return equalAny(e1, e2, nil)
+ case reflect.Map:
+ if v1.Len() != v2.Len() {
+ return false
+ }
+ for _, key := range v1.MapKeys() {
+ val2 := v2.MapIndex(key)
+ if !val2.IsValid() {
+ // This key was not found in the second map.
+ return false
+ }
+ if !equalAny(v1.MapIndex(key), val2, nil) {
+ return false
+ }
+ }
+ return true
+ case reflect.Ptr:
+ // Maps may have nil values in them, so check for nil.
+ if v1.IsNil() && v2.IsNil() {
+ return true
+ }
+ if v1.IsNil() != v2.IsNil() {
+ return false
+ }
+ return equalAny(v1.Elem(), v2.Elem(), prop)
+ case reflect.Slice:
+ if v1.Type().Elem().Kind() == reflect.Uint8 {
+ // short circuit: []byte
+
+ // Edge case: if this is in a proto3 message, a zero length
+ // bytes field is considered the zero value.
+ if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 {
+ return true
+ }
+ if v1.IsNil() != v2.IsNil() {
+ return false
+ }
+ return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
+ }
+
+ if v1.Len() != v2.Len() {
+ return false
+ }
+ for i := 0; i < v1.Len(); i++ {
+ if !equalAny(v1.Index(i), v2.Index(i), prop) {
+ return false
+ }
+ }
+ return true
+ case reflect.String:
+ return v1.Interface().(string) == v2.Interface().(string)
+ case reflect.Struct:
+ return equalStruct(v1, v2)
+ case reflect.Uint32, reflect.Uint64:
+ return v1.Uint() == v2.Uint()
+ }
+
+ // unknown type, so not a protocol buffer
+ log.Printf("proto: don't know how to compare %v", v1)
+ return false
+}
+
+// base is the struct type that the extensions are based on.
+// x1 and x2 are InternalExtensions.
+func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool {
+ em1, _ := x1.extensionsRead()
+ em2, _ := x2.extensionsRead()
+ return equalExtMap(base, em1, em2)
+}
+
+func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool {
+ if len(em1) != len(em2) {
+ return false
+ }
+
+ for extNum, e1 := range em1 {
+ e2, ok := em2[extNum]
+ if !ok {
+ return false
+ }
+
+ m1, m2 := e1.value, e2.value
+
+ if m1 != nil && m2 != nil {
+ // Both are unencoded.
+ if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
+ return false
+ }
+ continue
+ }
+
+ // At least one is encoded. To do a semantically correct comparison
+ // we need to unmarshal them first.
+ var desc *ExtensionDesc
+ if m := extensionMaps[base]; m != nil {
+ desc = m[extNum]
+ }
+ if desc == nil {
+ log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
+ continue
+ }
+ var err error
+ if m1 == nil {
+ m1, err = decodeExtension(e1.enc, desc)
+ }
+ if m2 == nil && err == nil {
+ m2, err = decodeExtension(e2.enc, desc)
+ }
+ if err != nil {
+ // The encoded form is invalid.
+ log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
+ return false
+ }
+ if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
+ return false
+ }
+ }
+
+ return true
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/extensions.go b/vendor/github.com/gogo/protobuf/proto/extensions.go
new file mode 100644
index 0000000..0dfcb53
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/extensions.go
@@ -0,0 +1,693 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Types and routines for supporting protocol buffer extensions.
+ */
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "strconv"
+ "sync"
+)
+
+// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
+var ErrMissingExtension = errors.New("proto: missing extension")
+
+// ExtensionRange represents a range of message extensions for a protocol buffer.
+// Used in code generated by the protocol compiler.
+type ExtensionRange struct {
+ Start, End int32 // both inclusive
+}
+
+// extendableProto is an interface implemented by any protocol buffer generated by the current
+// proto compiler that may be extended.
+type extendableProto interface {
+ Message
+ ExtensionRangeArray() []ExtensionRange
+ extensionsWrite() map[int32]Extension
+ extensionsRead() (map[int32]Extension, sync.Locker)
+}
+
+// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous
+// version of the proto compiler that may be extended.
+type extendableProtoV1 interface {
+ Message
+ ExtensionRangeArray() []ExtensionRange
+ ExtensionMap() map[int32]Extension
+}
+
+type extensionsBytes interface {
+ Message
+ ExtensionRangeArray() []ExtensionRange
+ GetExtensions() *[]byte
+}
+
+// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto.
+type extensionAdapter struct {
+ extendableProtoV1
+}
+
+func (e extensionAdapter) extensionsWrite() map[int32]Extension {
+ return e.ExtensionMap()
+}
+
+func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) {
+ return e.ExtensionMap(), notLocker{}
+}
+
+// notLocker is a sync.Locker whose Lock and Unlock methods are nops.
+type notLocker struct{}
+
+func (n notLocker) Lock() {}
+func (n notLocker) Unlock() {}
+
+// extendable returns the extendableProto interface for the given generated proto message.
+// If the proto message has the old extension format, it returns a wrapper that implements
+// the extendableProto interface.
+func extendable(p interface{}) (extendableProto, bool) {
+ if ep, ok := p.(extendableProto); ok {
+ return ep, ok
+ }
+ if ep, ok := p.(extendableProtoV1); ok {
+ return extensionAdapter{ep}, ok
+ }
+ return nil, false
+}
+
+// XXX_InternalExtensions is an internal representation of proto extensions.
+//
+// Each generated message struct type embeds an anonymous XXX_InternalExtensions field,
+// thus gaining the unexported 'extensions' method, which can be called only from the proto package.
+//
+// The methods of XXX_InternalExtensions are not concurrency safe in general,
+// but calls to logically read-only methods such as has and get may be executed concurrently.
+type XXX_InternalExtensions struct {
+ // The struct must be indirect so that if a user inadvertently copies a
+ // generated message and its embedded XXX_InternalExtensions, they
+ // avoid the mayhem of a copied mutex.
+ //
+ // The mutex serializes all logically read-only operations to p.extensionMap.
+ // It is up to the client to ensure that write operations to p.extensionMap are
+ // mutually exclusive with other accesses.
+ p *struct {
+ mu sync.Mutex
+ extensionMap map[int32]Extension
+ }
+}
+
+// extensionsWrite returns the extension map, creating it on first use.
+func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension {
+ if e.p == nil {
+ e.p = new(struct {
+ mu sync.Mutex
+ extensionMap map[int32]Extension
+ })
+ e.p.extensionMap = make(map[int32]Extension)
+ }
+ return e.p.extensionMap
+}
+
+// extensionsRead returns the extensions map for read-only use. It may be nil.
+// The caller must hold the returned mutex's lock when accessing Elements within the map.
+func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) {
+ if e.p == nil {
+ return nil, nil
+ }
+ return e.p.extensionMap, &e.p.mu
+}
+
+type extensionRange interface {
+ Message
+ ExtensionRangeArray() []ExtensionRange
+}
+
+var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem()
+var extendableProtoV1Type = reflect.TypeOf((*extendableProtoV1)(nil)).Elem()
+var extendableBytesType = reflect.TypeOf((*extensionsBytes)(nil)).Elem()
+var extensionRangeType = reflect.TypeOf((*extensionRange)(nil)).Elem()
+
+// ExtensionDesc represents an extension specification.
+// Used in generated code from the protocol compiler.
+type ExtensionDesc struct {
+ ExtendedType Message // nil pointer to the type that is being extended
+ ExtensionType interface{} // nil pointer to the extension type
+ 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 {
+ t := reflect.TypeOf(ed.ExtensionType)
+ return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
+}
+
+// Extension represents an extension in a message.
+type Extension struct {
+ // When an extension is stored in a message using SetExtension
+ // only desc and value are set. When the message is marshaled
+ // enc will be set to the encoded form of the message.
+ //
+ // When a message is unmarshaled and contains extensions, each
+ // extension will have only enc set. When such an extension is
+ // accessed using GetExtension (or GetExtensions) desc and value
+ // will be set.
+ desc *ExtensionDesc
+ value interface{}
+ enc []byte
+}
+
+// SetRawExtension is for testing only.
+func SetRawExtension(base Message, id int32, b []byte) {
+ if ebase, ok := base.(extensionsBytes); ok {
+ clearExtension(base, id)
+ ext := ebase.GetExtensions()
+ *ext = append(*ext, b...)
+ return
+ }
+ epb, ok := extendable(base)
+ if !ok {
+ return
+ }
+ extmap := epb.extensionsWrite()
+ extmap[id] = Extension{enc: b}
+}
+
+// isExtensionField returns true iff the given field number is in an extension range.
+func isExtensionField(pb extensionRange, field int32) bool {
+ for _, er := range pb.ExtensionRangeArray() {
+ if er.Start <= field && field <= er.End {
+ return true
+ }
+ }
+ return false
+}
+
+// checkExtensionTypes checks that the given extension is valid for pb.
+func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
+ var pbi interface{} = pb
+ // Check the extended type.
+ if ea, ok := pbi.(extensionAdapter); ok {
+ pbi = ea.extendableProtoV1
+ }
+ if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b {
+ return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String())
+ }
+ // Check the range.
+ if !isExtensionField(pb, extension.Field) {
+ return errors.New("proto: bad extension number; not in declared ranges")
+ }
+ return nil
+}
+
+// extPropKey is sufficient to uniquely identify an extension.
+type extPropKey struct {
+ base reflect.Type
+ field int32
+}
+
+var extProp = struct {
+ sync.RWMutex
+ m map[extPropKey]*Properties
+}{
+ m: make(map[extPropKey]*Properties),
+}
+
+func extensionProperties(ed *ExtensionDesc) *Properties {
+ key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
+
+ extProp.RLock()
+ if prop, ok := extProp.m[key]; ok {
+ extProp.RUnlock()
+ return prop
+ }
+ extProp.RUnlock()
+
+ extProp.Lock()
+ defer extProp.Unlock()
+ // Check again.
+ if prop, ok := extProp.m[key]; ok {
+ return prop
+ }
+
+ prop := new(Properties)
+ prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
+ extProp.m[key] = prop
+ return prop
+}
+
+// encode encodes any unmarshaled (unencoded) extensions in e.
+func encodeExtensions(e *XXX_InternalExtensions) error {
+ m, mu := e.extensionsRead()
+ if m == nil {
+ return nil // fast path
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ return encodeExtensionsMap(m)
+}
+
+// encode encodes any unmarshaled (unencoded) extensions in e.
+func encodeExtensionsMap(m map[int32]Extension) error {
+ for k, e := range m {
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ et := reflect.TypeOf(e.desc.ExtensionType)
+ props := extensionProperties(e.desc)
+
+ p := NewBuffer(nil)
+ // If e.value has type T, the encoder expects a *struct{ X T }.
+ // Pass a *T with a zero field and hope it all works out.
+ x := reflect.New(et)
+ x.Elem().Set(reflect.ValueOf(e.value))
+ if err := props.enc(p, props, toStructPointer(x)); err != nil {
+ return err
+ }
+ e.enc = p.buf
+ m[k] = e
+ }
+ return nil
+}
+
+func extensionsSize(e *XXX_InternalExtensions) (n int) {
+ m, mu := e.extensionsRead()
+ if m == nil {
+ return 0
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ return extensionsMapSize(m)
+}
+
+func extensionsMapSize(m map[int32]Extension) (n int) {
+ for _, e := range m {
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ n += len(e.enc)
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ et := reflect.TypeOf(e.desc.ExtensionType)
+ props := extensionProperties(e.desc)
+
+ // If e.value has type T, the encoder expects a *struct{ X T }.
+ // Pass a *T with a zero field and hope it all works out.
+ x := reflect.New(et)
+ x.Elem().Set(reflect.ValueOf(e.value))
+ n += props.size(props, toStructPointer(x))
+ }
+ return
+}
+
+// HasExtension returns whether the given extension is present in pb.
+func HasExtension(pb Message, extension *ExtensionDesc) bool {
+ if epb, doki := pb.(extensionsBytes); doki {
+ ext := epb.GetExtensions()
+ buf := *ext
+ o := 0
+ for o < len(buf) {
+ tag, n := DecodeVarint(buf[o:])
+ fieldNum := int32(tag >> 3)
+ if int32(fieldNum) == extension.Field {
+ return true
+ }
+ wireType := int(tag & 0x7)
+ o += n
+ l, err := size(buf[o:], wireType)
+ if err != nil {
+ return false
+ }
+ o += l
+ }
+ return false
+ }
+ // TODO: Check types, field numbers, etc.?
+ epb, ok := extendable(pb)
+ if !ok {
+ return false
+ }
+ extmap, mu := epb.extensionsRead()
+ if extmap == nil {
+ return false
+ }
+ mu.Lock()
+ _, ok = extmap[extension.Field]
+ mu.Unlock()
+ return ok
+}
+
+func deleteExtension(pb extensionsBytes, theFieldNum int32, offset int) int {
+ ext := pb.GetExtensions()
+ for offset < len(*ext) {
+ tag, n1 := DecodeVarint((*ext)[offset:])
+ fieldNum := int32(tag >> 3)
+ wireType := int(tag & 0x7)
+ n2, err := size((*ext)[offset+n1:], wireType)
+ if err != nil {
+ panic(err)
+ }
+ newOffset := offset + n1 + n2
+ if fieldNum == theFieldNum {
+ *ext = append((*ext)[:offset], (*ext)[newOffset:]...)
+ return offset
+ }
+ offset = newOffset
+ }
+ return -1
+}
+
+// ClearExtension removes the given extension from pb.
+func ClearExtension(pb Message, extension *ExtensionDesc) {
+ clearExtension(pb, extension.Field)
+}
+
+func clearExtension(pb Message, fieldNum int32) {
+ if epb, doki := pb.(extensionsBytes); doki {
+ offset := 0
+ for offset != -1 {
+ offset = deleteExtension(epb, fieldNum, offset)
+ }
+ return
+ }
+ epb, ok := extendable(pb)
+ if !ok {
+ return
+ }
+ // TODO: Check types, field numbers, etc.?
+ extmap := epb.extensionsWrite()
+ delete(extmap, fieldNum)
+}
+
+// GetExtension parses and returns the given extension of pb.
+// If the extension is not present and has no default value it returns ErrMissingExtension.
+func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) {
+ if epb, doki := pb.(extensionsBytes); doki {
+ ext := epb.GetExtensions()
+ o := 0
+ for o < len(*ext) {
+ tag, n := DecodeVarint((*ext)[o:])
+ fieldNum := int32(tag >> 3)
+ wireType := int(tag & 0x7)
+ l, err := size((*ext)[o+n:], wireType)
+ if err != nil {
+ return nil, err
+ }
+ if int32(fieldNum) == extension.Field {
+ v, err := decodeExtension((*ext)[o:o+n+l], extension)
+ if err != nil {
+ return nil, err
+ }
+ return v, nil
+ }
+ o += n + l
+ }
+ return defaultExtensionValue(extension)
+ }
+ epb, ok := extendable(pb)
+ if !ok {
+ return nil, errors.New("proto: not an extendable proto")
+ }
+ if err := checkExtensionTypes(epb, extension); err != nil {
+ return nil, err
+ }
+
+ emap, mu := epb.extensionsRead()
+ if emap == nil {
+ return defaultExtensionValue(extension)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ e, ok := emap[extension.Field]
+ if !ok {
+ // defaultExtensionValue returns the default value or
+ // ErrMissingExtension if there is no default.
+ return defaultExtensionValue(extension)
+ }
+
+ if e.value != nil {
+ // Already decoded. Check the descriptor, though.
+ if e.desc != extension {
+ // This shouldn't happen. If it does, it means that
+ // GetExtension was called twice with two different
+ // descriptors with the same field number.
+ return nil, errors.New("proto: descriptor conflict")
+ }
+ return e.value, nil
+ }
+
+ v, err := decodeExtension(e.enc, extension)
+ if err != nil {
+ return nil, err
+ }
+
+ // Remember the decoded version and drop the encoded version.
+ // That way it is safe to mutate what we return.
+ e.value = v
+ e.desc = extension
+ e.enc = nil
+ emap[extension.Field] = e
+ return e.value, nil
+}
+
+// defaultExtensionValue returns the default value for extension.
+// If no default for an extension is defined ErrMissingExtension is returned.
+func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) {
+ t := reflect.TypeOf(extension.ExtensionType)
+ props := extensionProperties(extension)
+
+ sf, _, err := fieldDefault(t, props)
+ if err != nil {
+ return nil, err
+ }
+
+ if sf == nil || sf.value == nil {
+ // There is no default value.
+ return nil, ErrMissingExtension
+ }
+
+ if t.Kind() != reflect.Ptr {
+ // We do not need to return a Ptr, we can directly return sf.value.
+ return sf.value, nil
+ }
+
+ // We need to return an interface{} that is a pointer to sf.value.
+ value := reflect.New(t).Elem()
+ value.Set(reflect.New(value.Type().Elem()))
+ if sf.kind == reflect.Int32 {
+ // We may have an int32 or an enum, but the underlying data is int32.
+ // Since we can't set an int32 into a non int32 reflect.value directly
+ // set it as a int32.
+ value.Elem().SetInt(int64(sf.value.(int32)))
+ } else {
+ value.Elem().Set(reflect.ValueOf(sf.value))
+ }
+ return value.Interface(), nil
+}
+
+// decodeExtension decodes an extension encoded in b.
+func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
+ o := NewBuffer(b)
+
+ t := reflect.TypeOf(extension.ExtensionType)
+
+ props := extensionProperties(extension)
+
+ // t is a pointer to a struct, pointer to basic type or a slice.
+ // Allocate a "field" to store the pointer/slice itself; the
+ // pointer/slice will be stored here. We pass
+ // the address of this field to props.dec.
+ // This passes a zero field and a *t and lets props.dec
+ // interpret it as a *struct{ x t }.
+ value := reflect.New(t).Elem()
+
+ for {
+ // Discard wire type and field number varint. It isn't needed.
+ if _, err := o.DecodeVarint(); err != nil {
+ return nil, err
+ }
+
+ if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil {
+ return nil, err
+ }
+
+ if o.index >= len(o.buf) {
+ break
+ }
+ }
+ return value.Interface(), nil
+}
+
+// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
+// The returned slice has the same length as es; missing extensions will appear as nil elements.
+func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
+ extensions = make([]interface{}, len(es))
+ for i, e := range es {
+ extensions[i], err = GetExtension(pb, e)
+ if err == ErrMissingExtension {
+ err = nil
+ }
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
+// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
+// just the Field field, which defines the extension's field number.
+func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
+ epb, ok := extendable(pb)
+ if !ok {
+ return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb)
+ }
+ registeredExtensions := RegisteredExtensions(pb)
+
+ emap, mu := epb.extensionsRead()
+ if emap == nil {
+ return nil, nil
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ extensions := make([]*ExtensionDesc, 0, len(emap))
+ for extid, e := range emap {
+ desc := e.desc
+ if desc == nil {
+ desc = registeredExtensions[extid]
+ if desc == nil {
+ desc = &ExtensionDesc{Field: extid}
+ }
+ }
+
+ extensions = append(extensions, desc)
+ }
+ return extensions, nil
+}
+
+// SetExtension sets the specified extension of pb to the specified value.
+func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
+ if epb, doki := pb.(extensionsBytes); doki {
+ ClearExtension(pb, extension)
+ ext := epb.GetExtensions()
+ et := reflect.TypeOf(extension.ExtensionType)
+ props := extensionProperties(extension)
+ p := NewBuffer(nil)
+ x := reflect.New(et)
+ x.Elem().Set(reflect.ValueOf(value))
+ if err := props.enc(p, props, toStructPointer(x)); err != nil {
+ return err
+ }
+ *ext = append(*ext, p.buf...)
+ return nil
+ }
+ epb, ok := extendable(pb)
+ if !ok {
+ return errors.New("proto: not an extendable proto")
+ }
+ if err := checkExtensionTypes(epb, extension); err != nil {
+ return err
+ }
+ typ := reflect.TypeOf(extension.ExtensionType)
+ if typ != reflect.TypeOf(value) {
+ return errors.New("proto: bad extension value type")
+ }
+ // nil extension values need to be caught early, because the
+ // encoder can't distinguish an ErrNil due to a nil extension
+ // from an ErrNil due to a missing field. Extensions are
+ // always optional, so the encoder would just swallow the error
+ // and drop all the extensions from the encoded message.
+ if reflect.ValueOf(value).IsNil() {
+ return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
+ }
+
+ extmap := epb.extensionsWrite()
+ extmap[extension.Field] = Extension{desc: extension, value: value}
+ return nil
+}
+
+// ClearAllExtensions clears all extensions from pb.
+func ClearAllExtensions(pb Message) {
+ if epb, doki := pb.(extensionsBytes); doki {
+ ext := epb.GetExtensions()
+ *ext = []byte{}
+ return
+ }
+ epb, ok := extendable(pb)
+ if !ok {
+ return
+ }
+ m := epb.extensionsWrite()
+ for k := range m {
+ delete(m, k)
+ }
+}
+
+// A global registry of extensions.
+// The generated code will register the generated descriptors by calling RegisterExtension.
+
+var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
+
+// RegisterExtension is called from the generated code.
+func RegisterExtension(desc *ExtensionDesc) {
+ st := reflect.TypeOf(desc.ExtendedType).Elem()
+ m := extensionMaps[st]
+ if m == nil {
+ m = make(map[int32]*ExtensionDesc)
+ extensionMaps[st] = m
+ }
+ if _, ok := m[desc.Field]; ok {
+ panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
+ }
+ m[desc.Field] = desc
+}
+
+// RegisteredExtensions returns a map of the registered extensions of a
+// protocol buffer struct, indexed by the extension number.
+// The argument pb should be a nil pointer to the struct type.
+func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
+ return extensionMaps[reflect.TypeOf(pb).Elem()]
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go b/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go
new file mode 100644
index 0000000..ea6478f
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go
@@ -0,0 +1,294 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 proto
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+)
+
+func GetBoolExtension(pb Message, extension *ExtensionDesc, ifnotset bool) bool {
+ if reflect.ValueOf(pb).IsNil() {
+ return ifnotset
+ }
+ value, err := GetExtension(pb, extension)
+ if err != nil {
+ return ifnotset
+ }
+ if value == nil {
+ return ifnotset
+ }
+ if value.(*bool) == nil {
+ return ifnotset
+ }
+ return *(value.(*bool))
+}
+
+func (this *Extension) Equal(that *Extension) bool {
+ return bytes.Equal(this.enc, that.enc)
+}
+
+func (this *Extension) Compare(that *Extension) int {
+ return bytes.Compare(this.enc, that.enc)
+}
+
+func SizeOfInternalExtension(m extendableProto) (n int) {
+ return SizeOfExtensionMap(m.extensionsWrite())
+}
+
+func SizeOfExtensionMap(m map[int32]Extension) (n int) {
+ return extensionsMapSize(m)
+}
+
+type sortableMapElem struct {
+ field int32
+ ext Extension
+}
+
+func newSortableExtensionsFromMap(m map[int32]Extension) sortableExtensions {
+ s := make(sortableExtensions, 0, len(m))
+ for k, v := range m {
+ s = append(s, &sortableMapElem{field: k, ext: v})
+ }
+ return s
+}
+
+type sortableExtensions []*sortableMapElem
+
+func (this sortableExtensions) Len() int { return len(this) }
+
+func (this sortableExtensions) Swap(i, j int) { this[i], this[j] = this[j], this[i] }
+
+func (this sortableExtensions) Less(i, j int) bool { return this[i].field < this[j].field }
+
+func (this sortableExtensions) String() string {
+ sort.Sort(this)
+ ss := make([]string, len(this))
+ for i := range this {
+ ss[i] = fmt.Sprintf("%d: %v", this[i].field, this[i].ext)
+ }
+ return "map[" + strings.Join(ss, ",") + "]"
+}
+
+func StringFromInternalExtension(m extendableProto) string {
+ return StringFromExtensionsMap(m.extensionsWrite())
+}
+
+func StringFromExtensionsMap(m map[int32]Extension) string {
+ return newSortableExtensionsFromMap(m).String()
+}
+
+func StringFromExtensionsBytes(ext []byte) string {
+ m, err := BytesToExtensionsMap(ext)
+ if err != nil {
+ panic(err)
+ }
+ return StringFromExtensionsMap(m)
+}
+
+func EncodeInternalExtension(m extendableProto, data []byte) (n int, err error) {
+ return EncodeExtensionMap(m.extensionsWrite(), data)
+}
+
+func EncodeExtensionMap(m map[int32]Extension, data []byte) (n int, err error) {
+ if err := encodeExtensionsMap(m); err != nil {
+ return 0, err
+ }
+ keys := make([]int, 0, len(m))
+ for k := range m {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+ for _, k := range keys {
+ n += copy(data[n:], m[int32(k)].enc)
+ }
+ return n, nil
+}
+
+func GetRawExtension(m map[int32]Extension, id int32) ([]byte, error) {
+ if m[id].value == nil || m[id].desc == nil {
+ return m[id].enc, nil
+ }
+ if err := encodeExtensionsMap(m); err != nil {
+ return nil, err
+ }
+ return m[id].enc, nil
+}
+
+func size(buf []byte, wire int) (int, error) {
+ switch wire {
+ case WireVarint:
+ _, n := DecodeVarint(buf)
+ return n, nil
+ case WireFixed64:
+ return 8, nil
+ case WireBytes:
+ v, n := DecodeVarint(buf)
+ return int(v) + n, nil
+ case WireFixed32:
+ return 4, nil
+ case WireStartGroup:
+ offset := 0
+ for {
+ u, n := DecodeVarint(buf[offset:])
+ fwire := int(u & 0x7)
+ offset += n
+ if fwire == WireEndGroup {
+ return offset, nil
+ }
+ s, err := size(buf[offset:], wire)
+ if err != nil {
+ return 0, err
+ }
+ offset += s
+ }
+ }
+ return 0, fmt.Errorf("proto: can't get size for unknown wire type %d", wire)
+}
+
+func BytesToExtensionsMap(buf []byte) (map[int32]Extension, error) {
+ m := make(map[int32]Extension)
+ i := 0
+ for i < len(buf) {
+ tag, n := DecodeVarint(buf[i:])
+ if n <= 0 {
+ return nil, fmt.Errorf("unable to decode varint")
+ }
+ fieldNum := int32(tag >> 3)
+ wireType := int(tag & 0x7)
+ l, err := size(buf[i+n:], wireType)
+ if err != nil {
+ return nil, err
+ }
+ end := i + int(l) + n
+ m[int32(fieldNum)] = Extension{enc: buf[i:end]}
+ i = end
+ }
+ return m, nil
+}
+
+func NewExtension(e []byte) Extension {
+ ee := Extension{enc: make([]byte, len(e))}
+ copy(ee.enc, e)
+ return ee
+}
+
+func AppendExtension(e Message, tag int32, buf []byte) {
+ if ee, eok := e.(extensionsBytes); eok {
+ ext := ee.GetExtensions()
+ *ext = append(*ext, buf...)
+ return
+ }
+ if ee, eok := e.(extendableProto); eok {
+ m := ee.extensionsWrite()
+ ext := m[int32(tag)] // may be missing
+ ext.enc = append(ext.enc, buf...)
+ m[int32(tag)] = ext
+ }
+}
+
+func encodeExtension(e *Extension) error {
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ return nil
+ }
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ et := reflect.TypeOf(e.desc.ExtensionType)
+ props := extensionProperties(e.desc)
+
+ p := NewBuffer(nil)
+ // If e.value has type T, the encoder expects a *struct{ X T }.
+ // Pass a *T with a zero field and hope it all works out.
+ x := reflect.New(et)
+ x.Elem().Set(reflect.ValueOf(e.value))
+ if err := props.enc(p, props, toStructPointer(x)); err != nil {
+ return err
+ }
+ e.enc = p.buf
+ return nil
+}
+
+func (this Extension) GoString() string {
+ if this.enc == nil {
+ if err := encodeExtension(&this); err != nil {
+ panic(err)
+ }
+ }
+ return fmt.Sprintf("proto.NewExtension(%#v)", this.enc)
+}
+
+func SetUnsafeExtension(pb Message, fieldNum int32, value interface{}) error {
+ typ := reflect.TypeOf(pb).Elem()
+ ext, ok := extensionMaps[typ]
+ if !ok {
+ return fmt.Errorf("proto: bad extended type; %s is not extendable", typ.String())
+ }
+ desc, ok := ext[fieldNum]
+ if !ok {
+ return errors.New("proto: bad extension number; not in declared ranges")
+ }
+ return SetExtension(pb, desc, value)
+}
+
+func GetUnsafeExtension(pb Message, fieldNum int32) (interface{}, error) {
+ typ := reflect.TypeOf(pb).Elem()
+ ext, ok := extensionMaps[typ]
+ if !ok {
+ return nil, fmt.Errorf("proto: bad extended type; %s is not extendable", typ.String())
+ }
+ desc, ok := ext[fieldNum]
+ if !ok {
+ return nil, fmt.Errorf("unregistered field number %d", fieldNum)
+ }
+ return GetExtension(pb, desc)
+}
+
+func NewUnsafeXXX_InternalExtensions(m map[int32]Extension) XXX_InternalExtensions {
+ x := &XXX_InternalExtensions{
+ p: new(struct {
+ mu sync.Mutex
+ extensionMap map[int32]Extension
+ }),
+ }
+ x.p.extensionMap = m
+ return *x
+}
+
+func GetUnsafeExtensionsMap(extendable Message) map[int32]Extension {
+ pb := extendable.(extendableProto)
+ return pb.extensionsWrite()
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/lib.go b/vendor/github.com/gogo/protobuf/proto/lib.go
new file mode 100644
index 0000000..7580bb4
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/lib.go
@@ -0,0 +1,898 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+/*
+Package proto converts data structures to and from the wire format of
+protocol buffers. It works in concert with the Go source code generated
+for .proto files by the protocol compiler.
+
+A summary of the properties of the protocol buffer interface
+for a protocol buffer variable v:
+
+ - Names are turned from camel_case to CamelCase for export.
+ - There are no methods on v to set fields; just treat
+ them as structure fields.
+ - There are getters that return a field's value if set,
+ and return the field's default value if unset.
+ The getters work even if the receiver is a nil message.
+ - The zero value for a struct is its correct initialization state.
+ All desired fields must be set before marshaling.
+ - A Reset() method will restore a protobuf struct to its zero state.
+ - Non-repeated fields are pointers to the values; nil means unset.
+ That is, optional or required field int32 f becomes F *int32.
+ - Repeated fields are slices.
+ - Helper functions are available to aid the setting of fields.
+ msg.Foo = proto.String("hello") // set field
+ - Constants are defined to hold the default values of all fields that
+ have them. They have the form Default_StructName_FieldName.
+ Because the getter methods handle defaulted values,
+ direct use of these constants should be rare.
+ - Enums are given type names and maps from names to values.
+ Enum values are prefixed by the enclosing message's name, or by the
+ enum's type name if it is a top-level enum. Enum types have a String
+ method, and a Enum method to assist in message construction.
+ - Nested messages, groups and enums have type names prefixed with the name of
+ the surrounding message type.
+ - Extensions are given descriptor names that start with E_,
+ followed by an underscore-delimited list of the nested messages
+ that contain it (if any) followed by the CamelCased name of the
+ extension field itself. HasExtension, ClearExtension, GetExtension
+ and SetExtension are functions for manipulating extensions.
+ - Oneof field sets are given a single field in their message,
+ with distinguished wrapper types for each possible field value.
+ - Marshal and Unmarshal are functions to encode and decode the wire format.
+
+When the .proto file specifies `syntax="proto3"`, there are some differences:
+
+ - Non-repeated fields of non-message type are values instead of pointers.
+ - Getters are only generated for message and oneof fields.
+ - Enum types do not get an Enum method.
+
+The simplest way to describe this is to see an example.
+Given file test.proto, containing
+
+ package example;
+
+ enum FOO { X = 17; }
+
+ message Test {
+ required string label = 1;
+ optional int32 type = 2 [default=77];
+ repeated int64 reps = 3;
+ optional group OptionalGroup = 4 {
+ required string RequiredField = 5;
+ }
+ oneof union {
+ int32 number = 6;
+ string name = 7;
+ }
+ }
+
+The resulting file, test.pb.go, is:
+
+ package example
+
+ import proto "github.com/gogo/protobuf/proto"
+ import math "math"
+
+ type FOO int32
+ const (
+ FOO_X FOO = 17
+ )
+ var FOO_name = map[int32]string{
+ 17: "X",
+ }
+ var FOO_value = map[string]int32{
+ "X": 17,
+ }
+
+ func (x FOO) Enum() *FOO {
+ p := new(FOO)
+ *p = x
+ return p
+ }
+ func (x FOO) String() string {
+ return proto.EnumName(FOO_name, int32(x))
+ }
+ func (x *FOO) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FOO_value, data)
+ if err != nil {
+ return err
+ }
+ *x = FOO(value)
+ return nil
+ }
+
+ type Test struct {
+ Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
+ Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
+ Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
+ Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
+ // Types that are valid to be assigned to Union:
+ // *Test_Number
+ // *Test_Name
+ Union isTest_Union `protobuf_oneof:"union"`
+ XXX_unrecognized []byte `json:"-"`
+ }
+ func (m *Test) Reset() { *m = Test{} }
+ func (m *Test) String() string { return proto.CompactTextString(m) }
+ func (*Test) ProtoMessage() {}
+
+ type isTest_Union interface {
+ isTest_Union()
+ }
+
+ type Test_Number struct {
+ Number int32 `protobuf:"varint,6,opt,name=number"`
+ }
+ type Test_Name struct {
+ Name string `protobuf:"bytes,7,opt,name=name"`
+ }
+
+ func (*Test_Number) isTest_Union() {}
+ func (*Test_Name) isTest_Union() {}
+
+ func (m *Test) GetUnion() isTest_Union {
+ if m != nil {
+ return m.Union
+ }
+ return nil
+ }
+ const Default_Test_Type int32 = 77
+
+ func (m *Test) GetLabel() string {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return ""
+ }
+
+ func (m *Test) GetType() int32 {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return Default_Test_Type
+ }
+
+ func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
+ if m != nil {
+ return m.Optionalgroup
+ }
+ return nil
+ }
+
+ type Test_OptionalGroup struct {
+ RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
+ }
+ func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
+ func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
+
+ func (m *Test_OptionalGroup) GetRequiredField() string {
+ if m != nil && m.RequiredField != nil {
+ return *m.RequiredField
+ }
+ return ""
+ }
+
+ func (m *Test) GetNumber() int32 {
+ if x, ok := m.GetUnion().(*Test_Number); ok {
+ return x.Number
+ }
+ return 0
+ }
+
+ func (m *Test) GetName() string {
+ if x, ok := m.GetUnion().(*Test_Name); ok {
+ return x.Name
+ }
+ return ""
+ }
+
+ func init() {
+ proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
+ }
+
+To create and play with a Test object:
+
+ package main
+
+ import (
+ "log"
+
+ "github.com/gogo/protobuf/proto"
+ pb "./example.pb"
+ )
+
+ func main() {
+ test := &pb.Test{
+ Label: proto.String("hello"),
+ Type: proto.Int32(17),
+ Reps: []int64{1, 2, 3},
+ Optionalgroup: &pb.Test_OptionalGroup{
+ RequiredField: proto.String("good bye"),
+ },
+ Union: &pb.Test_Name{"fred"},
+ }
+ data, err := proto.Marshal(test)
+ if err != nil {
+ log.Fatal("marshaling error: ", err)
+ }
+ newTest := &pb.Test{}
+ err = proto.Unmarshal(data, newTest)
+ if err != nil {
+ log.Fatal("unmarshaling error: ", err)
+ }
+ // Now test and newTest contain the same data.
+ if test.GetLabel() != newTest.GetLabel() {
+ log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
+ }
+ // Use a type switch to determine which oneof was set.
+ switch u := test.Union.(type) {
+ case *pb.Test_Number: // u.Number contains the number.
+ case *pb.Test_Name: // u.Name contains the string.
+ }
+ // etc.
+ }
+*/
+package proto
+
+import (
+ "encoding/json"
+ "fmt"
+ "log"
+ "reflect"
+ "sort"
+ "strconv"
+ "sync"
+)
+
+// Message is implemented by generated protocol buffer messages.
+type Message interface {
+ Reset()
+ String() string
+ ProtoMessage()
+}
+
+// Stats records allocation details about the protocol buffer encoders
+// and decoders. Useful for tuning the library itself.
+type Stats struct {
+ Emalloc uint64 // mallocs in encode
+ Dmalloc uint64 // mallocs in decode
+ Encode uint64 // number of encodes
+ Decode uint64 // number of decodes
+ Chit uint64 // number of cache hits
+ Cmiss uint64 // number of cache misses
+ Size uint64 // number of sizes
+}
+
+// Set to true to enable stats collection.
+const collectStats = false
+
+var stats Stats
+
+// GetStats returns a copy of the global Stats structure.
+func GetStats() Stats { return stats }
+
+// A Buffer is a buffer manager for marshaling and unmarshaling
+// protocol buffers. It may be reused between invocations to
+// reduce memory usage. It is not necessary to use a Buffer;
+// the global functions Marshal and Unmarshal create a
+// temporary Buffer and are fine for most applications.
+type Buffer struct {
+ buf []byte // encode/decode byte stream
+ index int // read point
+
+ // pools of basic types to amortize allocation.
+ bools []bool
+ uint32s []uint32
+ uint64s []uint64
+
+ // extra pools, only used with pointer_reflect.go
+ int32s []int32
+ int64s []int64
+ float32s []float32
+ float64s []float64
+}
+
+// NewBuffer allocates a new Buffer and initializes its internal data to
+// the contents of the argument slice.
+func NewBuffer(e []byte) *Buffer {
+ return &Buffer{buf: e}
+}
+
+// Reset resets the Buffer, ready for marshaling a new protocol buffer.
+func (p *Buffer) Reset() {
+ p.buf = p.buf[0:0] // for reading/writing
+ p.index = 0 // for reading
+}
+
+// SetBuf replaces the internal buffer with the slice,
+// ready for unmarshaling the contents of the slice.
+func (p *Buffer) SetBuf(s []byte) {
+ p.buf = s
+ p.index = 0
+}
+
+// Bytes returns the contents of the Buffer.
+func (p *Buffer) Bytes() []byte { return p.buf }
+
+/*
+ * Helper routines for simplifying the creation of optional fields of basic type.
+ */
+
+// Bool is a helper routine that allocates a new bool value
+// to store v and returns a pointer to it.
+func Bool(v bool) *bool {
+ return &v
+}
+
+// Int32 is a helper routine that allocates a new int32 value
+// to store v and returns a pointer to it.
+func Int32(v int32) *int32 {
+ return &v
+}
+
+// Int is a helper routine that allocates a new int32 value
+// to store v and returns a pointer to it, but unlike Int32
+// its argument value is an int.
+func Int(v int) *int32 {
+ p := new(int32)
+ *p = int32(v)
+ return p
+}
+
+// Int64 is a helper routine that allocates a new int64 value
+// to store v and returns a pointer to it.
+func Int64(v int64) *int64 {
+ return &v
+}
+
+// Float32 is a helper routine that allocates a new float32 value
+// to store v and returns a pointer to it.
+func Float32(v float32) *float32 {
+ return &v
+}
+
+// Float64 is a helper routine that allocates a new float64 value
+// to store v and returns a pointer to it.
+func Float64(v float64) *float64 {
+ return &v
+}
+
+// Uint32 is a helper routine that allocates a new uint32 value
+// to store v and returns a pointer to it.
+func Uint32(v uint32) *uint32 {
+ return &v
+}
+
+// Uint64 is a helper routine that allocates a new uint64 value
+// to store v and returns a pointer to it.
+func Uint64(v uint64) *uint64 {
+ return &v
+}
+
+// String is a helper routine that allocates a new string value
+// to store v and returns a pointer to it.
+func String(v string) *string {
+ return &v
+}
+
+// EnumName is a helper function to simplify printing protocol buffer enums
+// by name. Given an enum map and a value, it returns a useful string.
+func EnumName(m map[int32]string, v int32) string {
+ s, ok := m[v]
+ if ok {
+ return s
+ }
+ return strconv.Itoa(int(v))
+}
+
+// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
+// from their JSON-encoded representation. Given a map from the enum's symbolic
+// names to its int values, and a byte buffer containing the JSON-encoded
+// value, it returns an int32 that can be cast to the enum type by the caller.
+//
+// The function can deal with both JSON representations, numeric and symbolic.
+func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
+ if data[0] == '"' {
+ // New style: enums are strings.
+ var repr string
+ if err := json.Unmarshal(data, &repr); err != nil {
+ return -1, err
+ }
+ val, ok := m[repr]
+ if !ok {
+ return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
+ }
+ return val, nil
+ }
+ // Old style: enums are ints.
+ var val int32
+ if err := json.Unmarshal(data, &val); err != nil {
+ return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
+ }
+ return val, nil
+}
+
+// DebugPrint dumps the encoded data in b in a debugging format with a header
+// including the string s. Used in testing but made available for general debugging.
+func (p *Buffer) DebugPrint(s string, b []byte) {
+ var u uint64
+
+ obuf := p.buf
+ sindex := p.index
+ p.buf = b
+ p.index = 0
+ depth := 0
+
+ fmt.Printf("\n--- %s ---\n", s)
+
+out:
+ for {
+ for i := 0; i < depth; i++ {
+ fmt.Print(" ")
+ }
+
+ index := p.index
+ if index == len(p.buf) {
+ break
+ }
+
+ op, err := p.DecodeVarint()
+ if err != nil {
+ fmt.Printf("%3d: fetching op err %v\n", index, err)
+ break out
+ }
+ tag := op >> 3
+ wire := op & 7
+
+ switch wire {
+ default:
+ fmt.Printf("%3d: t=%3d unknown wire=%d\n",
+ index, tag, wire)
+ break out
+
+ case WireBytes:
+ var r []byte
+
+ r, err = p.DecodeRawBytes(false)
+ if err != nil {
+ break out
+ }
+ fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
+ if len(r) <= 6 {
+ for i := 0; i < len(r); i++ {
+ fmt.Printf(" %.2x", r[i])
+ }
+ } else {
+ for i := 0; i < 3; i++ {
+ fmt.Printf(" %.2x", r[i])
+ }
+ fmt.Printf(" ..")
+ for i := len(r) - 3; i < len(r); i++ {
+ fmt.Printf(" %.2x", r[i])
+ }
+ }
+ fmt.Printf("\n")
+
+ case WireFixed32:
+ u, err = p.DecodeFixed32()
+ if err != nil {
+ fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
+ break out
+ }
+ fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
+
+ case WireFixed64:
+ u, err = p.DecodeFixed64()
+ if err != nil {
+ fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
+ break out
+ }
+ fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
+
+ case WireVarint:
+ u, err = p.DecodeVarint()
+ if err != nil {
+ fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
+ break out
+ }
+ fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
+
+ case WireStartGroup:
+ fmt.Printf("%3d: t=%3d start\n", index, tag)
+ depth++
+
+ case WireEndGroup:
+ depth--
+ fmt.Printf("%3d: t=%3d end\n", index, tag)
+ }
+ }
+
+ if depth != 0 {
+ fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
+ }
+ fmt.Printf("\n")
+
+ p.buf = obuf
+ p.index = sindex
+}
+
+// SetDefaults sets unset protocol buffer fields to their default values.
+// It only modifies fields that are both unset and have defined defaults.
+// It recursively sets default values in any non-nil sub-messages.
+func SetDefaults(pb Message) {
+ setDefaults(reflect.ValueOf(pb), true, false)
+}
+
+// v is a pointer to a struct.
+func setDefaults(v reflect.Value, recur, zeros bool) {
+ v = v.Elem()
+
+ defaultMu.RLock()
+ dm, ok := defaults[v.Type()]
+ defaultMu.RUnlock()
+ if !ok {
+ dm = buildDefaultMessage(v.Type())
+ defaultMu.Lock()
+ defaults[v.Type()] = dm
+ defaultMu.Unlock()
+ }
+
+ for _, sf := range dm.scalars {
+ f := v.Field(sf.index)
+ if !f.IsNil() {
+ // field already set
+ continue
+ }
+ dv := sf.value
+ if dv == nil && !zeros {
+ // no explicit default, and don't want to set zeros
+ continue
+ }
+ fptr := f.Addr().Interface() // **T
+ // TODO: Consider batching the allocations we do here.
+ switch sf.kind {
+ case reflect.Bool:
+ b := new(bool)
+ if dv != nil {
+ *b = dv.(bool)
+ }
+ *(fptr.(**bool)) = b
+ case reflect.Float32:
+ f := new(float32)
+ if dv != nil {
+ *f = dv.(float32)
+ }
+ *(fptr.(**float32)) = f
+ case reflect.Float64:
+ f := new(float64)
+ if dv != nil {
+ *f = dv.(float64)
+ }
+ *(fptr.(**float64)) = f
+ case reflect.Int32:
+ // might be an enum
+ if ft := f.Type(); ft != int32PtrType {
+ // enum
+ f.Set(reflect.New(ft.Elem()))
+ if dv != nil {
+ f.Elem().SetInt(int64(dv.(int32)))
+ }
+ } else {
+ // int32 field
+ i := new(int32)
+ if dv != nil {
+ *i = dv.(int32)
+ }
+ *(fptr.(**int32)) = i
+ }
+ case reflect.Int64:
+ i := new(int64)
+ if dv != nil {
+ *i = dv.(int64)
+ }
+ *(fptr.(**int64)) = i
+ case reflect.String:
+ s := new(string)
+ if dv != nil {
+ *s = dv.(string)
+ }
+ *(fptr.(**string)) = s
+ case reflect.Uint8:
+ // exceptional case: []byte
+ var b []byte
+ if dv != nil {
+ db := dv.([]byte)
+ b = make([]byte, len(db))
+ copy(b, db)
+ } else {
+ b = []byte{}
+ }
+ *(fptr.(*[]byte)) = b
+ case reflect.Uint32:
+ u := new(uint32)
+ if dv != nil {
+ *u = dv.(uint32)
+ }
+ *(fptr.(**uint32)) = u
+ case reflect.Uint64:
+ u := new(uint64)
+ if dv != nil {
+ *u = dv.(uint64)
+ }
+ *(fptr.(**uint64)) = u
+ default:
+ log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
+ }
+ }
+
+ for _, ni := range dm.nested {
+ f := v.Field(ni)
+ // f is *T or []*T or map[T]*T
+ switch f.Kind() {
+ case reflect.Ptr:
+ if f.IsNil() {
+ continue
+ }
+ setDefaults(f, recur, zeros)
+
+ case reflect.Slice:
+ for i := 0; i < f.Len(); i++ {
+ e := f.Index(i)
+ if e.IsNil() {
+ continue
+ }
+ setDefaults(e, recur, zeros)
+ }
+
+ case reflect.Map:
+ for _, k := range f.MapKeys() {
+ e := f.MapIndex(k)
+ if e.IsNil() {
+ continue
+ }
+ setDefaults(e, recur, zeros)
+ }
+ }
+ }
+}
+
+var (
+ // defaults maps a protocol buffer struct type to a slice of the fields,
+ // with its scalar fields set to their proto-declared non-zero default values.
+ defaultMu sync.RWMutex
+ defaults = make(map[reflect.Type]defaultMessage)
+
+ int32PtrType = reflect.TypeOf((*int32)(nil))
+)
+
+// defaultMessage represents information about the default values of a message.
+type defaultMessage struct {
+ scalars []scalarField
+ nested []int // struct field index of nested messages
+}
+
+type scalarField struct {
+ index int // struct field index
+ kind reflect.Kind // element type (the T in *T or []T)
+ value interface{} // the proto-declared default value, or nil
+}
+
+// t is a struct type.
+func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
+ sprop := GetProperties(t)
+ for _, prop := range sprop.Prop {
+ fi, ok := sprop.decoderTags.get(prop.Tag)
+ if !ok {
+ // XXX_unrecognized
+ continue
+ }
+ ft := t.Field(fi).Type
+
+ sf, nested, err := fieldDefault(ft, prop)
+ switch {
+ case err != nil:
+ log.Print(err)
+ case nested:
+ dm.nested = append(dm.nested, fi)
+ case sf != nil:
+ sf.index = fi
+ dm.scalars = append(dm.scalars, *sf)
+ }
+ }
+
+ return dm
+}
+
+// fieldDefault returns the scalarField for field type ft.
+// sf will be nil if the field can not have a default.
+// nestedMessage will be true if this is a nested message.
+// Note that sf.index is not set on return.
+func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
+ var canHaveDefault bool
+ switch ft.Kind() {
+ case reflect.Ptr:
+ if ft.Elem().Kind() == reflect.Struct {
+ nestedMessage = true
+ } else {
+ canHaveDefault = true // proto2 scalar field
+ }
+
+ case reflect.Slice:
+ switch ft.Elem().Kind() {
+ case reflect.Ptr:
+ nestedMessage = true // repeated message
+ case reflect.Uint8:
+ canHaveDefault = true // bytes field
+ }
+
+ case reflect.Map:
+ if ft.Elem().Kind() == reflect.Ptr {
+ nestedMessage = true // map with message values
+ }
+ }
+
+ if !canHaveDefault {
+ if nestedMessage {
+ return nil, true, nil
+ }
+ return nil, false, nil
+ }
+
+ // We now know that ft is a pointer or slice.
+ sf = &scalarField{kind: ft.Elem().Kind()}
+
+ // scalar fields without defaults
+ if !prop.HasDefault {
+ return sf, false, nil
+ }
+
+ // a scalar field: either *T or []byte
+ switch ft.Elem().Kind() {
+ case reflect.Bool:
+ x, err := strconv.ParseBool(prop.Default)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ case reflect.Float32:
+ x, err := strconv.ParseFloat(prop.Default, 32)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
+ }
+ sf.value = float32(x)
+ case reflect.Float64:
+ x, err := strconv.ParseFloat(prop.Default, 64)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ case reflect.Int32:
+ x, err := strconv.ParseInt(prop.Default, 10, 32)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
+ }
+ sf.value = int32(x)
+ case reflect.Int64:
+ x, err := strconv.ParseInt(prop.Default, 10, 64)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ case reflect.String:
+ sf.value = prop.Default
+ case reflect.Uint8:
+ // []byte (not *uint8)
+ sf.value = []byte(prop.Default)
+ case reflect.Uint32:
+ x, err := strconv.ParseUint(prop.Default, 10, 32)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
+ }
+ sf.value = uint32(x)
+ case reflect.Uint64:
+ x, err := strconv.ParseUint(prop.Default, 10, 64)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ default:
+ return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
+ }
+
+ return sf, false, nil
+}
+
+// Map fields may have key types of non-float scalars, strings and enums.
+// The easiest way to sort them in some deterministic order is to use fmt.
+// If this turns out to be inefficient we can always consider other options,
+// such as doing a Schwartzian transform.
+
+func mapKeys(vs []reflect.Value) sort.Interface {
+ s := mapKeySorter{
+ vs: vs,
+ // default Less function: textual comparison
+ less: func(a, b reflect.Value) bool {
+ return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface())
+ },
+ }
+
+ // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps;
+ // numeric keys are sorted numerically.
+ if len(vs) == 0 {
+ return s
+ }
+ switch vs[0].Kind() {
+ case reflect.Int32, reflect.Int64:
+ s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
+ case reflect.Uint32, reflect.Uint64:
+ s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
+ }
+
+ return s
+}
+
+type mapKeySorter struct {
+ vs []reflect.Value
+ less func(a, b reflect.Value) bool
+}
+
+func (s mapKeySorter) Len() int { return len(s.vs) }
+func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
+func (s mapKeySorter) Less(i, j int) bool {
+ return s.less(s.vs[i], s.vs[j])
+}
+
+// isProto3Zero reports whether v is a zero proto3 value.
+func isProto3Zero(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Bool:
+ return !v.Bool()
+ case reflect.Int32, reflect.Int64:
+ return v.Int() == 0
+ case reflect.Uint32, reflect.Uint64:
+ return v.Uint() == 0
+ case reflect.Float32, reflect.Float64:
+ return v.Float() == 0
+ case reflect.String:
+ return v.String() == ""
+ }
+ return false
+}
+
+// ProtoPackageIsVersion2 is referenced from generated protocol buffer files
+// to assert that that code is compatible with this version of the proto package.
+const GoGoProtoPackageIsVersion2 = true
+
+// ProtoPackageIsVersion1 is referenced from generated protocol buffer files
+// to assert that that code is compatible with this version of the proto package.
+const GoGoProtoPackageIsVersion1 = true
diff --git a/vendor/github.com/gogo/protobuf/proto/lib_gogo.go b/vendor/github.com/gogo/protobuf/proto/lib_gogo.go
new file mode 100644
index 0000000..4b4f7c9
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/lib_gogo.go
@@ -0,0 +1,42 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 proto
+
+import (
+ "encoding/json"
+ "strconv"
+)
+
+func MarshalJSONEnum(m map[int32]string, value int32) ([]byte, error) {
+ s, ok := m[value]
+ if !ok {
+ s = strconv.Itoa(int(value))
+ }
+ return json.Marshal(s)
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/message_set.go b/vendor/github.com/gogo/protobuf/proto/message_set.go
new file mode 100644
index 0000000..fd982de
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/message_set.go
@@ -0,0 +1,311 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Support for message sets.
+ */
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "reflect"
+ "sort"
+)
+
+// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
+// A message type ID is required for storing a protocol buffer in a message set.
+var errNoMessageTypeID = errors.New("proto does not have a message type ID")
+
+// The first two types (_MessageSet_Item and messageSet)
+// model what the protocol compiler produces for the following protocol message:
+// message MessageSet {
+// repeated group Item = 1 {
+// required int32 type_id = 2;
+// required string message = 3;
+// };
+// }
+// That is the MessageSet wire format. We can't use a proto to generate these
+// because that would introduce a circular dependency between it and this package.
+
+type _MessageSet_Item struct {
+ TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
+ Message []byte `protobuf:"bytes,3,req,name=message"`
+}
+
+type messageSet struct {
+ Item []*_MessageSet_Item `protobuf:"group,1,rep"`
+ XXX_unrecognized []byte
+ // TODO: caching?
+}
+
+// Make sure messageSet is a Message.
+var _ Message = (*messageSet)(nil)
+
+// messageTypeIder is an interface satisfied by a protocol buffer type
+// that may be stored in a MessageSet.
+type messageTypeIder interface {
+ MessageTypeId() int32
+}
+
+func (ms *messageSet) find(pb Message) *_MessageSet_Item {
+ mti, ok := pb.(messageTypeIder)
+ if !ok {
+ return nil
+ }
+ id := mti.MessageTypeId()
+ for _, item := range ms.Item {
+ if *item.TypeId == id {
+ return item
+ }
+ }
+ return nil
+}
+
+func (ms *messageSet) Has(pb Message) bool {
+ if ms.find(pb) != nil {
+ return true
+ }
+ return false
+}
+
+func (ms *messageSet) Unmarshal(pb Message) error {
+ if item := ms.find(pb); item != nil {
+ return Unmarshal(item.Message, pb)
+ }
+ if _, ok := pb.(messageTypeIder); !ok {
+ return errNoMessageTypeID
+ }
+ return nil // TODO: return error instead?
+}
+
+func (ms *messageSet) Marshal(pb Message) error {
+ msg, err := Marshal(pb)
+ if err != nil {
+ return err
+ }
+ if item := ms.find(pb); item != nil {
+ // reuse existing item
+ item.Message = msg
+ return nil
+ }
+
+ mti, ok := pb.(messageTypeIder)
+ if !ok {
+ return errNoMessageTypeID
+ }
+
+ mtid := mti.MessageTypeId()
+ ms.Item = append(ms.Item, &_MessageSet_Item{
+ TypeId: &mtid,
+ Message: msg,
+ })
+ return nil
+}
+
+func (ms *messageSet) Reset() { *ms = messageSet{} }
+func (ms *messageSet) String() string { return CompactTextString(ms) }
+func (*messageSet) ProtoMessage() {}
+
+// Support for the message_set_wire_format message option.
+
+func skipVarint(buf []byte) []byte {
+ i := 0
+ for ; buf[i]&0x80 != 0; i++ {
+ }
+ return buf[i+1:]
+}
+
+// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
+// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
+func MarshalMessageSet(exts interface{}) ([]byte, error) {
+ var m map[int32]Extension
+ switch exts := exts.(type) {
+ case *XXX_InternalExtensions:
+ if err := encodeExtensions(exts); err != nil {
+ return nil, err
+ }
+ m, _ = exts.extensionsRead()
+ case map[int32]Extension:
+ if err := encodeExtensionsMap(exts); err != nil {
+ return nil, err
+ }
+ m = exts
+ default:
+ return nil, errors.New("proto: not an extension map")
+ }
+
+ // Sort extension IDs to provide a deterministic encoding.
+ // See also enc_map in encode.go.
+ ids := make([]int, 0, len(m))
+ for id := range m {
+ ids = append(ids, int(id))
+ }
+ sort.Ints(ids)
+
+ ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
+ for _, id := range ids {
+ e := m[int32(id)]
+ // Remove the wire type and field number varint, as well as the length varint.
+ msg := skipVarint(skipVarint(e.enc))
+
+ ms.Item = append(ms.Item, &_MessageSet_Item{
+ TypeId: Int32(int32(id)),
+ Message: msg,
+ })
+ }
+ return Marshal(ms)
+}
+
+// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
+// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
+func UnmarshalMessageSet(buf []byte, exts interface{}) error {
+ var m map[int32]Extension
+ switch exts := exts.(type) {
+ case *XXX_InternalExtensions:
+ m = exts.extensionsWrite()
+ case map[int32]Extension:
+ m = exts
+ default:
+ return errors.New("proto: not an extension map")
+ }
+
+ ms := new(messageSet)
+ if err := Unmarshal(buf, ms); err != nil {
+ return err
+ }
+ for _, item := range ms.Item {
+ id := *item.TypeId
+ msg := item.Message
+
+ // Restore wire type and field number varint, plus length varint.
+ // Be careful to preserve duplicate items.
+ b := EncodeVarint(uint64(id)<<3 | WireBytes)
+ if ext, ok := m[id]; ok {
+ // Existing data; rip off the tag and length varint
+ // so we join the new data correctly.
+ // We can assume that ext.enc is set because we are unmarshaling.
+ o := ext.enc[len(b):] // skip wire type and field number
+ _, n := DecodeVarint(o) // calculate length of length varint
+ o = o[n:] // skip length varint
+ msg = append(o, msg...) // join old data and new data
+ }
+ b = append(b, EncodeVarint(uint64(len(msg)))...)
+ b = append(b, msg...)
+
+ m[id] = Extension{enc: b}
+ }
+ return nil
+}
+
+// MarshalMessageSetJSON encodes the extension map represented by m in JSON format.
+// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
+func MarshalMessageSetJSON(exts interface{}) ([]byte, error) {
+ var m map[int32]Extension
+ switch exts := exts.(type) {
+ case *XXX_InternalExtensions:
+ m, _ = exts.extensionsRead()
+ case map[int32]Extension:
+ m = exts
+ default:
+ return nil, errors.New("proto: not an extension map")
+ }
+ var b bytes.Buffer
+ b.WriteByte('{')
+
+ // Process the map in key order for deterministic output.
+ ids := make([]int32, 0, len(m))
+ for id := range m {
+ ids = append(ids, id)
+ }
+ sort.Sort(int32Slice(ids)) // int32Slice defined in text.go
+
+ for i, id := range ids {
+ ext := m[id]
+ if i > 0 {
+ b.WriteByte(',')
+ }
+
+ msd, ok := messageSetMap[id]
+ if !ok {
+ // Unknown type; we can't render it, so skip it.
+ continue
+ }
+ fmt.Fprintf(&b, `"[%s]":`, msd.name)
+
+ x := ext.value
+ if x == nil {
+ x = reflect.New(msd.t.Elem()).Interface()
+ if err := Unmarshal(ext.enc, x.(Message)); err != nil {
+ return nil, err
+ }
+ }
+ d, err := json.Marshal(x)
+ if err != nil {
+ return nil, err
+ }
+ b.Write(d)
+ }
+ b.WriteByte('}')
+ return b.Bytes(), nil
+}
+
+// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format.
+// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
+func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error {
+ // Common-case fast path.
+ if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) {
+ return nil
+ }
+
+ // This is fairly tricky, and it's not clear that it is needed.
+ return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented")
+}
+
+// A global registry of types that can be used in a MessageSet.
+
+var messageSetMap = make(map[int32]messageSetDesc)
+
+type messageSetDesc struct {
+ t reflect.Type // pointer to struct
+ name string
+}
+
+// RegisterMessageSetType is called from the generated code.
+func RegisterMessageSetType(m Message, fieldNum int32, name string) {
+ messageSetMap[fieldNum] = messageSetDesc{
+ t: reflect.TypeOf(m),
+ name: name,
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go b/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go
new file mode 100644
index 0000000..fb512e2
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go
@@ -0,0 +1,484 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2012 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// +build appengine js
+
+// This file contains an implementation of proto field accesses using package reflect.
+// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
+// be used on App Engine.
+
+package proto
+
+import (
+ "math"
+ "reflect"
+)
+
+// A structPointer is a pointer to a struct.
+type structPointer struct {
+ v reflect.Value
+}
+
+// toStructPointer returns a structPointer equivalent to the given reflect value.
+// The reflect value must itself be a pointer to a struct.
+func toStructPointer(v reflect.Value) structPointer {
+ return structPointer{v}
+}
+
+// IsNil reports whether p is nil.
+func structPointer_IsNil(p structPointer) bool {
+ return p.v.IsNil()
+}
+
+// Interface returns the struct pointer as an interface value.
+func structPointer_Interface(p structPointer, _ reflect.Type) interface{} {
+ return p.v.Interface()
+}
+
+// A field identifies a field in a struct, accessible from a structPointer.
+// In this implementation, a field is identified by the sequence of field indices
+// passed to reflect's FieldByIndex.
+type field []int
+
+// toField returns a field equivalent to the given reflect field.
+func toField(f *reflect.StructField) field {
+ return f.Index
+}
+
+// invalidField is an invalid field identifier.
+var invalidField = field(nil)
+
+// IsValid reports whether the field identifier is valid.
+func (f field) IsValid() bool { return f != nil }
+
+// field returns the given field in the struct as a reflect value.
+func structPointer_field(p structPointer, f field) reflect.Value {
+ // Special case: an extension map entry with a value of type T
+ // passes a *T to the struct-handling code with a zero field,
+ // expecting that it will be treated as equivalent to *struct{ X T },
+ // which has the same memory layout. We have to handle that case
+ // specially, because reflect will panic if we call FieldByIndex on a
+ // non-struct.
+ if f == nil {
+ return p.v.Elem()
+ }
+
+ return p.v.Elem().FieldByIndex(f)
+}
+
+// ifield returns the given field in the struct as an interface value.
+func structPointer_ifield(p structPointer, f field) interface{} {
+ return structPointer_field(p, f).Addr().Interface()
+}
+
+// Bytes returns the address of a []byte field in the struct.
+func structPointer_Bytes(p structPointer, f field) *[]byte {
+ return structPointer_ifield(p, f).(*[]byte)
+}
+
+// BytesSlice returns the address of a [][]byte field in the struct.
+func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
+ return structPointer_ifield(p, f).(*[][]byte)
+}
+
+// Bool returns the address of a *bool field in the struct.
+func structPointer_Bool(p structPointer, f field) **bool {
+ return structPointer_ifield(p, f).(**bool)
+}
+
+// BoolVal returns the address of a bool field in the struct.
+func structPointer_BoolVal(p structPointer, f field) *bool {
+ return structPointer_ifield(p, f).(*bool)
+}
+
+// BoolSlice returns the address of a []bool field in the struct.
+func structPointer_BoolSlice(p structPointer, f field) *[]bool {
+ return structPointer_ifield(p, f).(*[]bool)
+}
+
+// String returns the address of a *string field in the struct.
+func structPointer_String(p structPointer, f field) **string {
+ return structPointer_ifield(p, f).(**string)
+}
+
+// StringVal returns the address of a string field in the struct.
+func structPointer_StringVal(p structPointer, f field) *string {
+ return structPointer_ifield(p, f).(*string)
+}
+
+// StringSlice returns the address of a []string field in the struct.
+func structPointer_StringSlice(p structPointer, f field) *[]string {
+ return structPointer_ifield(p, f).(*[]string)
+}
+
+// Extensions returns the address of an extension map field in the struct.
+func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions {
+ return structPointer_ifield(p, f).(*XXX_InternalExtensions)
+}
+
+// ExtMap returns the address of an extension map field in the struct.
+func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
+ return structPointer_ifield(p, f).(*map[int32]Extension)
+}
+
+// NewAt returns the reflect.Value for a pointer to a field in the struct.
+func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value {
+ return structPointer_field(p, f).Addr()
+}
+
+// SetStructPointer writes a *struct field in the struct.
+func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
+ structPointer_field(p, f).Set(q.v)
+}
+
+// GetStructPointer reads a *struct field in the struct.
+func structPointer_GetStructPointer(p structPointer, f field) structPointer {
+ return structPointer{structPointer_field(p, f)}
+}
+
+// StructPointerSlice the address of a []*struct field in the struct.
+func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice {
+ return structPointerSlice{structPointer_field(p, f)}
+}
+
+// A structPointerSlice represents the address of a slice of pointers to structs
+// (themselves messages or groups). That is, v.Type() is *[]*struct{...}.
+type structPointerSlice struct {
+ v reflect.Value
+}
+
+func (p structPointerSlice) Len() int { return p.v.Len() }
+func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} }
+func (p structPointerSlice) Append(q structPointer) {
+ p.v.Set(reflect.Append(p.v, q.v))
+}
+
+var (
+ int32Type = reflect.TypeOf(int32(0))
+ uint32Type = reflect.TypeOf(uint32(0))
+ float32Type = reflect.TypeOf(float32(0))
+ int64Type = reflect.TypeOf(int64(0))
+ uint64Type = reflect.TypeOf(uint64(0))
+ float64Type = reflect.TypeOf(float64(0))
+)
+
+// A word32 represents a field of type *int32, *uint32, *float32, or *enum.
+// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable.
+type word32 struct {
+ v reflect.Value
+}
+
+// IsNil reports whether p is nil.
+func word32_IsNil(p word32) bool {
+ return p.v.IsNil()
+}
+
+// Set sets p to point at a newly allocated word with bits set to x.
+func word32_Set(p word32, o *Buffer, x uint32) {
+ t := p.v.Type().Elem()
+ switch t {
+ case int32Type:
+ if len(o.int32s) == 0 {
+ o.int32s = make([]int32, uint32PoolSize)
+ }
+ o.int32s[0] = int32(x)
+ p.v.Set(reflect.ValueOf(&o.int32s[0]))
+ o.int32s = o.int32s[1:]
+ return
+ case uint32Type:
+ if len(o.uint32s) == 0 {
+ o.uint32s = make([]uint32, uint32PoolSize)
+ }
+ o.uint32s[0] = x
+ p.v.Set(reflect.ValueOf(&o.uint32s[0]))
+ o.uint32s = o.uint32s[1:]
+ return
+ case float32Type:
+ if len(o.float32s) == 0 {
+ o.float32s = make([]float32, uint32PoolSize)
+ }
+ o.float32s[0] = math.Float32frombits(x)
+ p.v.Set(reflect.ValueOf(&o.float32s[0]))
+ o.float32s = o.float32s[1:]
+ return
+ }
+
+ // must be enum
+ p.v.Set(reflect.New(t))
+ p.v.Elem().SetInt(int64(int32(x)))
+}
+
+// Get gets the bits pointed at by p, as a uint32.
+func word32_Get(p word32) uint32 {
+ elem := p.v.Elem()
+ switch elem.Kind() {
+ case reflect.Int32:
+ return uint32(elem.Int())
+ case reflect.Uint32:
+ return uint32(elem.Uint())
+ case reflect.Float32:
+ return math.Float32bits(float32(elem.Float()))
+ }
+ panic("unreachable")
+}
+
+// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct.
+func structPointer_Word32(p structPointer, f field) word32 {
+ return word32{structPointer_field(p, f)}
+}
+
+// A word32Val represents a field of type int32, uint32, float32, or enum.
+// That is, v.Type() is int32, uint32, float32, or enum and v is assignable.
+type word32Val struct {
+ v reflect.Value
+}
+
+// Set sets *p to x.
+func word32Val_Set(p word32Val, x uint32) {
+ switch p.v.Type() {
+ case int32Type:
+ p.v.SetInt(int64(x))
+ return
+ case uint32Type:
+ p.v.SetUint(uint64(x))
+ return
+ case float32Type:
+ p.v.SetFloat(float64(math.Float32frombits(x)))
+ return
+ }
+
+ // must be enum
+ p.v.SetInt(int64(int32(x)))
+}
+
+// Get gets the bits pointed at by p, as a uint32.
+func word32Val_Get(p word32Val) uint32 {
+ elem := p.v
+ switch elem.Kind() {
+ case reflect.Int32:
+ return uint32(elem.Int())
+ case reflect.Uint32:
+ return uint32(elem.Uint())
+ case reflect.Float32:
+ return math.Float32bits(float32(elem.Float()))
+ }
+ panic("unreachable")
+}
+
+// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct.
+func structPointer_Word32Val(p structPointer, f field) word32Val {
+ return word32Val{structPointer_field(p, f)}
+}
+
+// A word32Slice is a slice of 32-bit values.
+// That is, v.Type() is []int32, []uint32, []float32, or []enum.
+type word32Slice struct {
+ v reflect.Value
+}
+
+func (p word32Slice) Append(x uint32) {
+ n, m := p.v.Len(), p.v.Cap()
+ if n < m {
+ p.v.SetLen(n + 1)
+ } else {
+ t := p.v.Type().Elem()
+ p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
+ }
+ elem := p.v.Index(n)
+ switch elem.Kind() {
+ case reflect.Int32:
+ elem.SetInt(int64(int32(x)))
+ case reflect.Uint32:
+ elem.SetUint(uint64(x))
+ case reflect.Float32:
+ elem.SetFloat(float64(math.Float32frombits(x)))
+ }
+}
+
+func (p word32Slice) Len() int {
+ return p.v.Len()
+}
+
+func (p word32Slice) Index(i int) uint32 {
+ elem := p.v.Index(i)
+ switch elem.Kind() {
+ case reflect.Int32:
+ return uint32(elem.Int())
+ case reflect.Uint32:
+ return uint32(elem.Uint())
+ case reflect.Float32:
+ return math.Float32bits(float32(elem.Float()))
+ }
+ panic("unreachable")
+}
+
+// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct.
+func structPointer_Word32Slice(p structPointer, f field) word32Slice {
+ return word32Slice{structPointer_field(p, f)}
+}
+
+// word64 is like word32 but for 64-bit values.
+type word64 struct {
+ v reflect.Value
+}
+
+func word64_Set(p word64, o *Buffer, x uint64) {
+ t := p.v.Type().Elem()
+ switch t {
+ case int64Type:
+ if len(o.int64s) == 0 {
+ o.int64s = make([]int64, uint64PoolSize)
+ }
+ o.int64s[0] = int64(x)
+ p.v.Set(reflect.ValueOf(&o.int64s[0]))
+ o.int64s = o.int64s[1:]
+ return
+ case uint64Type:
+ if len(o.uint64s) == 0 {
+ o.uint64s = make([]uint64, uint64PoolSize)
+ }
+ o.uint64s[0] = x
+ p.v.Set(reflect.ValueOf(&o.uint64s[0]))
+ o.uint64s = o.uint64s[1:]
+ return
+ case float64Type:
+ if len(o.float64s) == 0 {
+ o.float64s = make([]float64, uint64PoolSize)
+ }
+ o.float64s[0] = math.Float64frombits(x)
+ p.v.Set(reflect.ValueOf(&o.float64s[0]))
+ o.float64s = o.float64s[1:]
+ return
+ }
+ panic("unreachable")
+}
+
+func word64_IsNil(p word64) bool {
+ return p.v.IsNil()
+}
+
+func word64_Get(p word64) uint64 {
+ elem := p.v.Elem()
+ switch elem.Kind() {
+ case reflect.Int64:
+ return uint64(elem.Int())
+ case reflect.Uint64:
+ return elem.Uint()
+ case reflect.Float64:
+ return math.Float64bits(elem.Float())
+ }
+ panic("unreachable")
+}
+
+func structPointer_Word64(p structPointer, f field) word64 {
+ return word64{structPointer_field(p, f)}
+}
+
+// word64Val is like word32Val but for 64-bit values.
+type word64Val struct {
+ v reflect.Value
+}
+
+func word64Val_Set(p word64Val, o *Buffer, x uint64) {
+ switch p.v.Type() {
+ case int64Type:
+ p.v.SetInt(int64(x))
+ return
+ case uint64Type:
+ p.v.SetUint(x)
+ return
+ case float64Type:
+ p.v.SetFloat(math.Float64frombits(x))
+ return
+ }
+ panic("unreachable")
+}
+
+func word64Val_Get(p word64Val) uint64 {
+ elem := p.v
+ switch elem.Kind() {
+ case reflect.Int64:
+ return uint64(elem.Int())
+ case reflect.Uint64:
+ return elem.Uint()
+ case reflect.Float64:
+ return math.Float64bits(elem.Float())
+ }
+ panic("unreachable")
+}
+
+func structPointer_Word64Val(p structPointer, f field) word64Val {
+ return word64Val{structPointer_field(p, f)}
+}
+
+type word64Slice struct {
+ v reflect.Value
+}
+
+func (p word64Slice) Append(x uint64) {
+ n, m := p.v.Len(), p.v.Cap()
+ if n < m {
+ p.v.SetLen(n + 1)
+ } else {
+ t := p.v.Type().Elem()
+ p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
+ }
+ elem := p.v.Index(n)
+ switch elem.Kind() {
+ case reflect.Int64:
+ elem.SetInt(int64(int64(x)))
+ case reflect.Uint64:
+ elem.SetUint(uint64(x))
+ case reflect.Float64:
+ elem.SetFloat(float64(math.Float64frombits(x)))
+ }
+}
+
+func (p word64Slice) Len() int {
+ return p.v.Len()
+}
+
+func (p word64Slice) Index(i int) uint64 {
+ elem := p.v.Index(i)
+ switch elem.Kind() {
+ case reflect.Int64:
+ return uint64(elem.Int())
+ case reflect.Uint64:
+ return uint64(elem.Uint())
+ case reflect.Float64:
+ return math.Float64bits(float64(elem.Float()))
+ }
+ panic("unreachable")
+}
+
+func structPointer_Word64Slice(p structPointer, f field) word64Slice {
+ return word64Slice{structPointer_field(p, f)}
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go b/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go
new file mode 100644
index 0000000..1763a5f
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go
@@ -0,0 +1,85 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2016, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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.
+
+// +build appengine js
+
+package proto
+
+import (
+ "reflect"
+)
+
+func structPointer_FieldPointer(p structPointer, f field) structPointer {
+ panic("not implemented")
+}
+
+func appendStructPointer(base structPointer, f field, typ reflect.Type) structPointer {
+ panic("not implemented")
+}
+
+func structPointer_InterfaceAt(p structPointer, f field, t reflect.Type) interface{} {
+ panic("not implemented")
+}
+
+func structPointer_InterfaceRef(p structPointer, f field, t reflect.Type) interface{} {
+ panic("not implemented")
+}
+
+func structPointer_GetRefStructPointer(p structPointer, f field) structPointer {
+ panic("not implemented")
+}
+
+func structPointer_Add(p structPointer, size field) structPointer {
+ panic("not implemented")
+}
+
+func structPointer_Len(p structPointer, f field) int {
+ panic("not implemented")
+}
+
+func structPointer_GetSliceHeader(p structPointer, f field) *reflect.SliceHeader {
+ panic("not implemented")
+}
+
+func structPointer_Copy(oldptr structPointer, newptr structPointer, size int) {
+ panic("not implemented")
+}
+
+func structPointer_StructRefSlice(p structPointer, f field, size uintptr) *structRefSlice {
+ panic("not implemented")
+}
+
+type structRefSlice struct{}
+
+func (v *structRefSlice) Len() int {
+ panic("not implemented")
+}
+
+func (v *structRefSlice) Index(i int) structPointer {
+ panic("not implemented")
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go
new file mode 100644
index 0000000..6b5567d
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go
@@ -0,0 +1,270 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2012 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// +build !appengine,!js
+
+// This file contains the implementation of the proto field accesses using package unsafe.
+
+package proto
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+// NOTE: These type_Foo functions would more idiomatically be methods,
+// but Go does not allow methods on pointer types, and we must preserve
+// some pointer type for the garbage collector. We use these
+// funcs with clunky names as our poor approximation to methods.
+//
+// An alternative would be
+// type structPointer struct { p unsafe.Pointer }
+// but that does not registerize as well.
+
+// A structPointer is a pointer to a struct.
+type structPointer unsafe.Pointer
+
+// toStructPointer returns a structPointer equivalent to the given reflect value.
+func toStructPointer(v reflect.Value) structPointer {
+ return structPointer(unsafe.Pointer(v.Pointer()))
+}
+
+// IsNil reports whether p is nil.
+func structPointer_IsNil(p structPointer) bool {
+ return p == nil
+}
+
+// Interface returns the struct pointer, assumed to have element type t,
+// as an interface value.
+func structPointer_Interface(p structPointer, t reflect.Type) interface{} {
+ return reflect.NewAt(t, unsafe.Pointer(p)).Interface()
+}
+
+// A field identifies a field in a struct, accessible from a structPointer.
+// In this implementation, a field is identified by its byte offset from the start of the struct.
+type field uintptr
+
+// toField returns a field equivalent to the given reflect field.
+func toField(f *reflect.StructField) field {
+ return field(f.Offset)
+}
+
+// invalidField is an invalid field identifier.
+const invalidField = ^field(0)
+
+// IsValid reports whether the field identifier is valid.
+func (f field) IsValid() bool {
+ return f != ^field(0)
+}
+
+// Bytes returns the address of a []byte field in the struct.
+func structPointer_Bytes(p structPointer, f field) *[]byte {
+ return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// BytesSlice returns the address of a [][]byte field in the struct.
+func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
+ return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// Bool returns the address of a *bool field in the struct.
+func structPointer_Bool(p structPointer, f field) **bool {
+ return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// BoolVal returns the address of a bool field in the struct.
+func structPointer_BoolVal(p structPointer, f field) *bool {
+ return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// BoolSlice returns the address of a []bool field in the struct.
+func structPointer_BoolSlice(p structPointer, f field) *[]bool {
+ return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// String returns the address of a *string field in the struct.
+func structPointer_String(p structPointer, f field) **string {
+ return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// StringVal returns the address of a string field in the struct.
+func structPointer_StringVal(p structPointer, f field) *string {
+ return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// StringSlice returns the address of a []string field in the struct.
+func structPointer_StringSlice(p structPointer, f field) *[]string {
+ return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// ExtMap returns the address of an extension map field in the struct.
+func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions {
+ return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
+ return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// NewAt returns the reflect.Value for a pointer to a field in the struct.
+func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value {
+ return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f)))
+}
+
+// SetStructPointer writes a *struct field in the struct.
+func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
+ *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q
+}
+
+// GetStructPointer reads a *struct field in the struct.
+func structPointer_GetStructPointer(p structPointer, f field) structPointer {
+ return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// StructPointerSlice the address of a []*struct field in the struct.
+func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice {
+ return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups).
+type structPointerSlice []structPointer
+
+func (v *structPointerSlice) Len() int { return len(*v) }
+func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] }
+func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) }
+
+// A word32 is the address of a "pointer to 32-bit value" field.
+type word32 **uint32
+
+// IsNil reports whether *v is nil.
+func word32_IsNil(p word32) bool {
+ return *p == nil
+}
+
+// Set sets *v to point at a newly allocated word set to x.
+func word32_Set(p word32, o *Buffer, x uint32) {
+ if len(o.uint32s) == 0 {
+ o.uint32s = make([]uint32, uint32PoolSize)
+ }
+ o.uint32s[0] = x
+ *p = &o.uint32s[0]
+ o.uint32s = o.uint32s[1:]
+}
+
+// Get gets the value pointed at by *v.
+func word32_Get(p word32) uint32 {
+ return **p
+}
+
+// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct.
+func structPointer_Word32(p structPointer, f field) word32 {
+ return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// A word32Val is the address of a 32-bit value field.
+type word32Val *uint32
+
+// Set sets *p to x.
+func word32Val_Set(p word32Val, x uint32) {
+ *p = x
+}
+
+// Get gets the value pointed at by p.
+func word32Val_Get(p word32Val) uint32 {
+ return *p
+}
+
+// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct.
+func structPointer_Word32Val(p structPointer, f field) word32Val {
+ return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// A word32Slice is a slice of 32-bit values.
+type word32Slice []uint32
+
+func (v *word32Slice) Append(x uint32) { *v = append(*v, x) }
+func (v *word32Slice) Len() int { return len(*v) }
+func (v *word32Slice) Index(i int) uint32 { return (*v)[i] }
+
+// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct.
+func structPointer_Word32Slice(p structPointer, f field) *word32Slice {
+ return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// word64 is like word32 but for 64-bit values.
+type word64 **uint64
+
+func word64_Set(p word64, o *Buffer, x uint64) {
+ if len(o.uint64s) == 0 {
+ o.uint64s = make([]uint64, uint64PoolSize)
+ }
+ o.uint64s[0] = x
+ *p = &o.uint64s[0]
+ o.uint64s = o.uint64s[1:]
+}
+
+func word64_IsNil(p word64) bool {
+ return *p == nil
+}
+
+func word64_Get(p word64) uint64 {
+ return **p
+}
+
+func structPointer_Word64(p structPointer, f field) word64 {
+ return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// word64Val is like word32Val but for 64-bit values.
+type word64Val *uint64
+
+func word64Val_Set(p word64Val, o *Buffer, x uint64) {
+ *p = x
+}
+
+func word64Val_Get(p word64Val) uint64 {
+ return *p
+}
+
+func structPointer_Word64Val(p structPointer, f field) word64Val {
+ return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// word64Slice is like word32Slice but for 64-bit values.
+type word64Slice []uint64
+
+func (v *word64Slice) Append(x uint64) { *v = append(*v, x) }
+func (v *word64Slice) Len() int { return len(*v) }
+func (v *word64Slice) Index(i int) uint64 { return (*v)[i] }
+
+func structPointer_Word64Slice(p structPointer, f field) *word64Slice {
+ return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go
new file mode 100644
index 0000000..f156a29
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go
@@ -0,0 +1,128 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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.
+
+// +build !appengine,!js
+
+// This file contains the implementation of the proto field accesses using package unsafe.
+
+package proto
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+func structPointer_InterfaceAt(p structPointer, f field, t reflect.Type) interface{} {
+ point := unsafe.Pointer(uintptr(p) + uintptr(f))
+ r := reflect.NewAt(t, point)
+ return r.Interface()
+}
+
+func structPointer_InterfaceRef(p structPointer, f field, t reflect.Type) interface{} {
+ point := unsafe.Pointer(uintptr(p) + uintptr(f))
+ r := reflect.NewAt(t, point)
+ if r.Elem().IsNil() {
+ return nil
+ }
+ return r.Elem().Interface()
+}
+
+func copyUintPtr(oldptr, newptr uintptr, size int) {
+ oldbytes := make([]byte, 0)
+ oldslice := (*reflect.SliceHeader)(unsafe.Pointer(&oldbytes))
+ oldslice.Data = oldptr
+ oldslice.Len = size
+ oldslice.Cap = size
+ newbytes := make([]byte, 0)
+ newslice := (*reflect.SliceHeader)(unsafe.Pointer(&newbytes))
+ newslice.Data = newptr
+ newslice.Len = size
+ newslice.Cap = size
+ copy(newbytes, oldbytes)
+}
+
+func structPointer_Copy(oldptr structPointer, newptr structPointer, size int) {
+ copyUintPtr(uintptr(oldptr), uintptr(newptr), size)
+}
+
+func appendStructPointer(base structPointer, f field, typ reflect.Type) structPointer {
+ size := typ.Elem().Size()
+
+ oldHeader := structPointer_GetSliceHeader(base, f)
+ oldSlice := reflect.NewAt(typ, unsafe.Pointer(oldHeader)).Elem()
+ newLen := oldHeader.Len + 1
+ newSlice := reflect.MakeSlice(typ, newLen, newLen)
+ reflect.Copy(newSlice, oldSlice)
+ bas := toStructPointer(newSlice)
+ oldHeader.Data = uintptr(bas)
+ oldHeader.Len = newLen
+ oldHeader.Cap = newLen
+
+ return structPointer(unsafe.Pointer(uintptr(unsafe.Pointer(bas)) + uintptr(uintptr(newLen-1)*size)))
+}
+
+func structPointer_FieldPointer(p structPointer, f field) structPointer {
+ return structPointer(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+func structPointer_GetRefStructPointer(p structPointer, f field) structPointer {
+ return structPointer((*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+func structPointer_GetSliceHeader(p structPointer, f field) *reflect.SliceHeader {
+ return (*reflect.SliceHeader)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+func structPointer_Add(p structPointer, size field) structPointer {
+ return structPointer(unsafe.Pointer(uintptr(p) + uintptr(size)))
+}
+
+func structPointer_Len(p structPointer, f field) int {
+ return len(*(*[]interface{})(unsafe.Pointer(structPointer_GetRefStructPointer(p, f))))
+}
+
+func structPointer_StructRefSlice(p structPointer, f field, size uintptr) *structRefSlice {
+ return &structRefSlice{p: p, f: f, size: size}
+}
+
+// A structRefSlice represents a slice of structs (themselves submessages or groups).
+type structRefSlice struct {
+ p structPointer
+ f field
+ size uintptr
+}
+
+func (v *structRefSlice) Len() int {
+ return structPointer_Len(v.p, v.f)
+}
+
+func (v *structRefSlice) Index(i int) structPointer {
+ ss := structPointer_GetStructPointer(v.p, v.f)
+ ss1 := structPointer_GetRefStructPointer(ss, 0)
+ return structPointer_Add(ss1, field(uintptr(i)*v.size))
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/properties.go b/vendor/github.com/gogo/protobuf/proto/properties.go
new file mode 100644
index 0000000..44b3320
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/properties.go
@@ -0,0 +1,968 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Routines for encoding data into the wire format for protocol buffers.
+ */
+
+import (
+ "fmt"
+ "log"
+ "os"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+)
+
+const debug bool = false
+
+// Constants that identify the encoding of a value on the wire.
+const (
+ WireVarint = 0
+ WireFixed64 = 1
+ WireBytes = 2
+ WireStartGroup = 3
+ WireEndGroup = 4
+ WireFixed32 = 5
+)
+
+const startSize = 10 // initial slice/string sizes
+
+// Encoders are defined in encode.go
+// An encoder outputs the full representation of a field, including its
+// tag and encoder type.
+type encoder func(p *Buffer, prop *Properties, base structPointer) error
+
+// A valueEncoder encodes a single integer in a particular encoding.
+type valueEncoder func(o *Buffer, x uint64) error
+
+// Sizers are defined in encode.go
+// A sizer returns the encoded size of a field, including its tag and encoder
+// type.
+type sizer func(prop *Properties, base structPointer) int
+
+// A valueSizer returns the encoded size of a single integer in a particular
+// encoding.
+type valueSizer func(x uint64) int
+
+// Decoders are defined in decode.go
+// A decoder creates a value from its wire representation.
+// Unrecognized subelements are saved in unrec.
+type decoder func(p *Buffer, prop *Properties, base structPointer) error
+
+// A valueDecoder decodes a single integer in a particular encoding.
+type valueDecoder func(o *Buffer) (x uint64, err error)
+
+// A oneofMarshaler does the marshaling for all oneof fields in a message.
+type oneofMarshaler func(Message, *Buffer) error
+
+// A oneofUnmarshaler does the unmarshaling for a oneof field in a message.
+type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error)
+
+// A oneofSizer does the sizing for all oneof fields in a message.
+type oneofSizer func(Message) int
+
+// tagMap is an optimization over map[int]int for typical protocol buffer
+// use-cases. Encoded protocol buffers are often in tag order with small tag
+// numbers.
+type tagMap struct {
+ fastTags []int
+ slowTags map[int]int
+}
+
+// tagMapFastLimit is the upper bound on the tag number that will be stored in
+// the tagMap slice rather than its map.
+const tagMapFastLimit = 1024
+
+func (p *tagMap) get(t int) (int, bool) {
+ if t > 0 && t < tagMapFastLimit {
+ if t >= len(p.fastTags) {
+ return 0, false
+ }
+ fi := p.fastTags[t]
+ return fi, fi >= 0
+ }
+ fi, ok := p.slowTags[t]
+ return fi, ok
+}
+
+func (p *tagMap) put(t int, fi int) {
+ if t > 0 && t < tagMapFastLimit {
+ for len(p.fastTags) < t+1 {
+ p.fastTags = append(p.fastTags, -1)
+ }
+ p.fastTags[t] = fi
+ return
+ }
+ if p.slowTags == nil {
+ p.slowTags = make(map[int]int)
+ }
+ p.slowTags[t] = fi
+}
+
+// StructProperties represents properties for all the fields of a struct.
+// decoderTags and decoderOrigNames should only be used by the decoder.
+type StructProperties struct {
+ Prop []*Properties // properties for each field
+ reqCount int // required count
+ decoderTags tagMap // map from proto tag to struct field number
+ decoderOrigNames map[string]int // map from original name to struct field number
+ order []int // list of struct field numbers in tag order
+ unrecField field // field id of the XXX_unrecognized []byte field
+ extendable bool // is this an extendable proto
+
+ oneofMarshaler oneofMarshaler
+ oneofUnmarshaler oneofUnmarshaler
+ oneofSizer oneofSizer
+ stype reflect.Type
+
+ // OneofTypes contains information about the oneof fields in this message.
+ // It is keyed by the original name of a field.
+ OneofTypes map[string]*OneofProperties
+}
+
+// OneofProperties represents information about a specific field in a oneof.
+type OneofProperties struct {
+ Type reflect.Type // pointer to generated struct type for this oneof field
+ Field int // struct field number of the containing oneof in the message
+ Prop *Properties
+}
+
+// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
+// See encode.go, (*Buffer).enc_struct.
+
+func (sp *StructProperties) Len() int { return len(sp.order) }
+func (sp *StructProperties) Less(i, j int) bool {
+ return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
+}
+func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
+
+// Properties represents the protocol-specific behavior of a single struct field.
+type Properties struct {
+ Name string // name of the field, for error messages
+ OrigName string // original name before protocol compiler (always set)
+ JSONName string // name to use for JSON; determined by protoc
+ Wire string
+ WireType int
+ Tag int
+ Required bool
+ Optional bool
+ Repeated bool
+ Packed bool // relevant for repeated primitives only
+ Enum string // set for enum types only
+ proto3 bool // whether this is known to be a proto3 field; set for []byte only
+ oneof bool // whether this is a oneof field
+
+ Default string // default value
+ HasDefault bool // whether an explicit default was provided
+ CustomType string
+ StdTime bool
+ StdDuration bool
+
+ enc encoder
+ valEnc valueEncoder // set for bool and numeric types only
+ field field
+ tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType)
+ tagbuf [8]byte
+ stype reflect.Type // set for struct types only
+ sstype reflect.Type // set for slices of structs types only
+ ctype reflect.Type // set for custom types only
+ sprop *StructProperties // set for struct types only
+ isMarshaler bool
+ isUnmarshaler bool
+
+ mtype reflect.Type // set for map types only
+ mkeyprop *Properties // set for map types only
+ mvalprop *Properties // set for map types only
+
+ size sizer
+ valSize valueSizer // set for bool and numeric types only
+
+ dec decoder
+ valDec valueDecoder // set for bool and numeric types only
+
+ // If this is a packable field, this will be the decoder for the packed version of the field.
+ packedDec decoder
+}
+
+// String formats the properties in the protobuf struct field tag style.
+func (p *Properties) String() string {
+ s := p.Wire
+ s = ","
+ s += strconv.Itoa(p.Tag)
+ if p.Required {
+ s += ",req"
+ }
+ if p.Optional {
+ s += ",opt"
+ }
+ if p.Repeated {
+ s += ",rep"
+ }
+ if p.Packed {
+ s += ",packed"
+ }
+ s += ",name=" + p.OrigName
+ if p.JSONName != p.OrigName {
+ s += ",json=" + p.JSONName
+ }
+ if p.proto3 {
+ s += ",proto3"
+ }
+ if p.oneof {
+ s += ",oneof"
+ }
+ if len(p.Enum) > 0 {
+ s += ",enum=" + p.Enum
+ }
+ if p.HasDefault {
+ s += ",def=" + p.Default
+ }
+ return s
+}
+
+// Parse populates p by parsing a string in the protobuf struct field tag style.
+func (p *Properties) Parse(s string) {
+ // "bytes,49,opt,name=foo,def=hello!"
+ fields := strings.Split(s, ",") // breaks def=, but handled below.
+ if len(fields) < 2 {
+ fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
+ return
+ }
+
+ p.Wire = fields[0]
+ switch p.Wire {
+ case "varint":
+ p.WireType = WireVarint
+ p.valEnc = (*Buffer).EncodeVarint
+ p.valDec = (*Buffer).DecodeVarint
+ p.valSize = sizeVarint
+ case "fixed32":
+ p.WireType = WireFixed32
+ p.valEnc = (*Buffer).EncodeFixed32
+ p.valDec = (*Buffer).DecodeFixed32
+ p.valSize = sizeFixed32
+ case "fixed64":
+ p.WireType = WireFixed64
+ p.valEnc = (*Buffer).EncodeFixed64
+ p.valDec = (*Buffer).DecodeFixed64
+ p.valSize = sizeFixed64
+ case "zigzag32":
+ p.WireType = WireVarint
+ p.valEnc = (*Buffer).EncodeZigzag32
+ p.valDec = (*Buffer).DecodeZigzag32
+ p.valSize = sizeZigzag32
+ case "zigzag64":
+ p.WireType = WireVarint
+ p.valEnc = (*Buffer).EncodeZigzag64
+ p.valDec = (*Buffer).DecodeZigzag64
+ p.valSize = sizeZigzag64
+ case "bytes", "group":
+ p.WireType = WireBytes
+ // no numeric converter for non-numeric types
+ default:
+ fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
+ return
+ }
+
+ var err error
+ p.Tag, err = strconv.Atoi(fields[1])
+ if err != nil {
+ return
+ }
+
+ for i := 2; i < len(fields); i++ {
+ f := fields[i]
+ switch {
+ case f == "req":
+ p.Required = true
+ case f == "opt":
+ p.Optional = true
+ case f == "rep":
+ p.Repeated = true
+ case f == "packed":
+ p.Packed = true
+ case strings.HasPrefix(f, "name="):
+ p.OrigName = f[5:]
+ case strings.HasPrefix(f, "json="):
+ p.JSONName = f[5:]
+ case strings.HasPrefix(f, "enum="):
+ p.Enum = f[5:]
+ case f == "proto3":
+ p.proto3 = true
+ case f == "oneof":
+ p.oneof = true
+ case strings.HasPrefix(f, "def="):
+ p.HasDefault = true
+ p.Default = f[4:] // rest of string
+ if i+1 < len(fields) {
+ // Commas aren't escaped, and def is always last.
+ p.Default += "," + strings.Join(fields[i+1:], ",")
+ break
+ }
+ case strings.HasPrefix(f, "embedded="):
+ p.OrigName = strings.Split(f, "=")[1]
+ case strings.HasPrefix(f, "customtype="):
+ p.CustomType = strings.Split(f, "=")[1]
+ case f == "stdtime":
+ p.StdTime = true
+ case f == "stdduration":
+ p.StdDuration = true
+ }
+ }
+}
+
+func logNoSliceEnc(t1, t2 reflect.Type) {
+ fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2)
+}
+
+var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
+
+// Initialize the fields for encoding and decoding.
+func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
+ p.enc = nil
+ p.dec = nil
+ p.size = nil
+ isMap := typ.Kind() == reflect.Map
+ if len(p.CustomType) > 0 && !isMap {
+ p.setCustomEncAndDec(typ)
+ p.setTag(lockGetProp)
+ return
+ }
+ if p.StdTime && !isMap {
+ p.setTimeEncAndDec(typ)
+ p.setTag(lockGetProp)
+ return
+ }
+ if p.StdDuration && !isMap {
+ p.setDurationEncAndDec(typ)
+ p.setTag(lockGetProp)
+ return
+ }
+ switch t1 := typ; t1.Kind() {
+ default:
+ fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1)
+
+ // proto3 scalar types
+
+ case reflect.Bool:
+ if p.proto3 {
+ p.enc = (*Buffer).enc_proto3_bool
+ p.dec = (*Buffer).dec_proto3_bool
+ p.size = size_proto3_bool
+ } else {
+ p.enc = (*Buffer).enc_ref_bool
+ p.dec = (*Buffer).dec_proto3_bool
+ p.size = size_ref_bool
+ }
+ case reflect.Int32:
+ if p.proto3 {
+ p.enc = (*Buffer).enc_proto3_int32
+ p.dec = (*Buffer).dec_proto3_int32
+ p.size = size_proto3_int32
+ } else {
+ p.enc = (*Buffer).enc_ref_int32
+ p.dec = (*Buffer).dec_proto3_int32
+ p.size = size_ref_int32
+ }
+ case reflect.Uint32:
+ if p.proto3 {
+ p.enc = (*Buffer).enc_proto3_uint32
+ p.dec = (*Buffer).dec_proto3_int32 // can reuse
+ p.size = size_proto3_uint32
+ } else {
+ p.enc = (*Buffer).enc_ref_uint32
+ p.dec = (*Buffer).dec_proto3_int32 // can reuse
+ p.size = size_ref_uint32
+ }
+ case reflect.Int64, reflect.Uint64:
+ if p.proto3 {
+ p.enc = (*Buffer).enc_proto3_int64
+ p.dec = (*Buffer).dec_proto3_int64
+ p.size = size_proto3_int64
+ } else {
+ p.enc = (*Buffer).enc_ref_int64
+ p.dec = (*Buffer).dec_proto3_int64
+ p.size = size_ref_int64
+ }
+ case reflect.Float32:
+ if p.proto3 {
+ p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits
+ p.dec = (*Buffer).dec_proto3_int32
+ p.size = size_proto3_uint32
+ } else {
+ p.enc = (*Buffer).enc_ref_uint32 // can just treat them as bits
+ p.dec = (*Buffer).dec_proto3_int32
+ p.size = size_ref_uint32
+ }
+ case reflect.Float64:
+ if p.proto3 {
+ p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits
+ p.dec = (*Buffer).dec_proto3_int64
+ p.size = size_proto3_int64
+ } else {
+ p.enc = (*Buffer).enc_ref_int64 // can just treat them as bits
+ p.dec = (*Buffer).dec_proto3_int64
+ p.size = size_ref_int64
+ }
+ case reflect.String:
+ if p.proto3 {
+ p.enc = (*Buffer).enc_proto3_string
+ p.dec = (*Buffer).dec_proto3_string
+ p.size = size_proto3_string
+ } else {
+ p.enc = (*Buffer).enc_ref_string
+ p.dec = (*Buffer).dec_proto3_string
+ p.size = size_ref_string
+ }
+ case reflect.Struct:
+ p.stype = typ
+ p.isMarshaler = isMarshaler(typ)
+ p.isUnmarshaler = isUnmarshaler(typ)
+ if p.Wire == "bytes" {
+ p.enc = (*Buffer).enc_ref_struct_message
+ p.dec = (*Buffer).dec_ref_struct_message
+ p.size = size_ref_struct_message
+ } else {
+ fmt.Fprintf(os.Stderr, "proto: no coders for struct %T\n", typ)
+ }
+
+ case reflect.Ptr:
+ switch t2 := t1.Elem(); t2.Kind() {
+ default:
+ fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2)
+ break
+ case reflect.Bool:
+ p.enc = (*Buffer).enc_bool
+ p.dec = (*Buffer).dec_bool
+ p.size = size_bool
+ case reflect.Int32:
+ p.enc = (*Buffer).enc_int32
+ p.dec = (*Buffer).dec_int32
+ p.size = size_int32
+ case reflect.Uint32:
+ p.enc = (*Buffer).enc_uint32
+ p.dec = (*Buffer).dec_int32 // can reuse
+ p.size = size_uint32
+ case reflect.Int64, reflect.Uint64:
+ p.enc = (*Buffer).enc_int64
+ p.dec = (*Buffer).dec_int64
+ p.size = size_int64
+ case reflect.Float32:
+ p.enc = (*Buffer).enc_uint32 // can just treat them as bits
+ p.dec = (*Buffer).dec_int32
+ p.size = size_uint32
+ case reflect.Float64:
+ p.enc = (*Buffer).enc_int64 // can just treat them as bits
+ p.dec = (*Buffer).dec_int64
+ p.size = size_int64
+ case reflect.String:
+ p.enc = (*Buffer).enc_string
+ p.dec = (*Buffer).dec_string
+ p.size = size_string
+ case reflect.Struct:
+ p.stype = t1.Elem()
+ p.isMarshaler = isMarshaler(t1)
+ p.isUnmarshaler = isUnmarshaler(t1)
+ if p.Wire == "bytes" {
+ p.enc = (*Buffer).enc_struct_message
+ p.dec = (*Buffer).dec_struct_message
+ p.size = size_struct_message
+ } else {
+ p.enc = (*Buffer).enc_struct_group
+ p.dec = (*Buffer).dec_struct_group
+ p.size = size_struct_group
+ }
+ }
+
+ case reflect.Slice:
+ switch t2 := t1.Elem(); t2.Kind() {
+ default:
+ logNoSliceEnc(t1, t2)
+ break
+ case reflect.Bool:
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_bool
+ p.size = size_slice_packed_bool
+ } else {
+ p.enc = (*Buffer).enc_slice_bool
+ p.size = size_slice_bool
+ }
+ p.dec = (*Buffer).dec_slice_bool
+ p.packedDec = (*Buffer).dec_slice_packed_bool
+ case reflect.Int32:
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_int32
+ p.size = size_slice_packed_int32
+ } else {
+ p.enc = (*Buffer).enc_slice_int32
+ p.size = size_slice_int32
+ }
+ p.dec = (*Buffer).dec_slice_int32
+ p.packedDec = (*Buffer).dec_slice_packed_int32
+ case reflect.Uint32:
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_uint32
+ p.size = size_slice_packed_uint32
+ } else {
+ p.enc = (*Buffer).enc_slice_uint32
+ p.size = size_slice_uint32
+ }
+ p.dec = (*Buffer).dec_slice_int32
+ p.packedDec = (*Buffer).dec_slice_packed_int32
+ case reflect.Int64, reflect.Uint64:
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_int64
+ p.size = size_slice_packed_int64
+ } else {
+ p.enc = (*Buffer).enc_slice_int64
+ p.size = size_slice_int64
+ }
+ p.dec = (*Buffer).dec_slice_int64
+ p.packedDec = (*Buffer).dec_slice_packed_int64
+ case reflect.Uint8:
+ p.dec = (*Buffer).dec_slice_byte
+ if p.proto3 {
+ p.enc = (*Buffer).enc_proto3_slice_byte
+ p.size = size_proto3_slice_byte
+ } else {
+ p.enc = (*Buffer).enc_slice_byte
+ p.size = size_slice_byte
+ }
+ case reflect.Float32, reflect.Float64:
+ switch t2.Bits() {
+ case 32:
+ // can just treat them as bits
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_uint32
+ p.size = size_slice_packed_uint32
+ } else {
+ p.enc = (*Buffer).enc_slice_uint32
+ p.size = size_slice_uint32
+ }
+ p.dec = (*Buffer).dec_slice_int32
+ p.packedDec = (*Buffer).dec_slice_packed_int32
+ case 64:
+ // can just treat them as bits
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_int64
+ p.size = size_slice_packed_int64
+ } else {
+ p.enc = (*Buffer).enc_slice_int64
+ p.size = size_slice_int64
+ }
+ p.dec = (*Buffer).dec_slice_int64
+ p.packedDec = (*Buffer).dec_slice_packed_int64
+ default:
+ logNoSliceEnc(t1, t2)
+ break
+ }
+ case reflect.String:
+ p.enc = (*Buffer).enc_slice_string
+ p.dec = (*Buffer).dec_slice_string
+ p.size = size_slice_string
+ case reflect.Ptr:
+ switch t3 := t2.Elem(); t3.Kind() {
+ default:
+ fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3)
+ break
+ case reflect.Struct:
+ p.stype = t2.Elem()
+ p.isMarshaler = isMarshaler(t2)
+ p.isUnmarshaler = isUnmarshaler(t2)
+ if p.Wire == "bytes" {
+ p.enc = (*Buffer).enc_slice_struct_message
+ p.dec = (*Buffer).dec_slice_struct_message
+ p.size = size_slice_struct_message
+ } else {
+ p.enc = (*Buffer).enc_slice_struct_group
+ p.dec = (*Buffer).dec_slice_struct_group
+ p.size = size_slice_struct_group
+ }
+ }
+ case reflect.Slice:
+ switch t2.Elem().Kind() {
+ default:
+ fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem())
+ break
+ case reflect.Uint8:
+ p.enc = (*Buffer).enc_slice_slice_byte
+ p.dec = (*Buffer).dec_slice_slice_byte
+ p.size = size_slice_slice_byte
+ }
+ case reflect.Struct:
+ p.setSliceOfNonPointerStructs(t1)
+ }
+
+ case reflect.Map:
+ p.enc = (*Buffer).enc_new_map
+ p.dec = (*Buffer).dec_new_map
+ p.size = size_new_map
+
+ p.mtype = t1
+ p.mkeyprop = &Properties{}
+ p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
+ p.mvalprop = &Properties{}
+ vtype := p.mtype.Elem()
+ if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
+ // The value type is not a message (*T) or bytes ([]byte),
+ // so we need encoders for the pointer to this type.
+ vtype = reflect.PtrTo(vtype)
+ }
+
+ p.mvalprop.CustomType = p.CustomType
+ p.mvalprop.StdDuration = p.StdDuration
+ p.mvalprop.StdTime = p.StdTime
+ p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
+ }
+ p.setTag(lockGetProp)
+}
+
+func (p *Properties) setTag(lockGetProp bool) {
+ // precalculate tag code
+ wire := p.WireType
+ if p.Packed {
+ wire = WireBytes
+ }
+ x := uint32(p.Tag)<<3 | uint32(wire)
+ i := 0
+ for i = 0; x > 127; i++ {
+ p.tagbuf[i] = 0x80 | uint8(x&0x7F)
+ x >>= 7
+ }
+ p.tagbuf[i] = uint8(x)
+ p.tagcode = p.tagbuf[0 : i+1]
+
+ if p.stype != nil {
+ if lockGetProp {
+ p.sprop = GetProperties(p.stype)
+ } else {
+ p.sprop = getPropertiesLocked(p.stype)
+ }
+ }
+}
+
+var (
+ marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
+ unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
+)
+
+// isMarshaler reports whether type t implements Marshaler.
+func isMarshaler(t reflect.Type) bool {
+ return t.Implements(marshalerType)
+}
+
+// isUnmarshaler reports whether type t implements Unmarshaler.
+func isUnmarshaler(t reflect.Type) bool {
+ return t.Implements(unmarshalerType)
+}
+
+// Init populates the properties from a protocol buffer struct tag.
+func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
+ p.init(typ, name, tag, f, true)
+}
+
+func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
+ // "bytes,49,opt,def=hello!"
+ p.Name = name
+ p.OrigName = name
+ if f != nil {
+ p.field = toField(f)
+ }
+ if tag == "" {
+ return
+ }
+ p.Parse(tag)
+ p.setEncAndDec(typ, f, lockGetProp)
+}
+
+var (
+ propertiesMu sync.RWMutex
+ propertiesMap = make(map[reflect.Type]*StructProperties)
+)
+
+// GetProperties returns the list of properties for the type represented by t.
+// t must represent a generated struct type of a protocol message.
+func GetProperties(t reflect.Type) *StructProperties {
+ if t.Kind() != reflect.Struct {
+ panic("proto: type must have kind struct")
+ }
+
+ // Most calls to GetProperties in a long-running program will be
+ // retrieving details for types we have seen before.
+ propertiesMu.RLock()
+ sprop, ok := propertiesMap[t]
+ propertiesMu.RUnlock()
+ if ok {
+ if collectStats {
+ stats.Chit++
+ }
+ return sprop
+ }
+
+ propertiesMu.Lock()
+ sprop = getPropertiesLocked(t)
+ propertiesMu.Unlock()
+ return sprop
+}
+
+// getPropertiesLocked requires that propertiesMu is held.
+func getPropertiesLocked(t reflect.Type) *StructProperties {
+ if prop, ok := propertiesMap[t]; ok {
+ if collectStats {
+ stats.Chit++
+ }
+ return prop
+ }
+ if collectStats {
+ stats.Cmiss++
+ }
+
+ prop := new(StructProperties)
+ // in case of recursive protos, fill this in now.
+ propertiesMap[t] = prop
+
+ // build properties
+ prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) ||
+ reflect.PtrTo(t).Implements(extendableProtoV1Type) ||
+ reflect.PtrTo(t).Implements(extendableBytesType)
+ prop.unrecField = invalidField
+ prop.Prop = make([]*Properties, t.NumField())
+ prop.order = make([]int, t.NumField())
+
+ isOneofMessage := false
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ p := new(Properties)
+ name := f.Name
+ p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
+
+ if f.Name == "XXX_InternalExtensions" { // special case
+ p.enc = (*Buffer).enc_exts
+ p.dec = nil // not needed
+ p.size = size_exts
+ } else if f.Name == "XXX_extensions" { // special case
+ if len(f.Tag.Get("protobuf")) > 0 {
+ p.enc = (*Buffer).enc_ext_slice_byte
+ p.dec = nil // not needed
+ p.size = size_ext_slice_byte
+ } else {
+ p.enc = (*Buffer).enc_map
+ p.dec = nil // not needed
+ p.size = size_map
+ }
+ } else if f.Name == "XXX_unrecognized" { // special case
+ prop.unrecField = toField(&f)
+ }
+ oneof := f.Tag.Get("protobuf_oneof") // special case
+ if oneof != "" {
+ isOneofMessage = true
+ // Oneof fields don't use the traditional protobuf tag.
+ p.OrigName = oneof
+ }
+ prop.Prop[i] = p
+ prop.order[i] = i
+ if debug {
+ print(i, " ", f.Name, " ", t.String(), " ")
+ if p.Tag > 0 {
+ print(p.String())
+ }
+ print("\n")
+ }
+ if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" {
+ fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
+ }
+ }
+
+ // Re-order prop.order.
+ sort.Sort(prop)
+
+ type oneofMessage interface {
+ XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
+ }
+ if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); isOneofMessage && ok {
+ var oots []interface{}
+ prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs()
+ prop.stype = t
+
+ // Interpret oneof metadata.
+ prop.OneofTypes = make(map[string]*OneofProperties)
+ for _, oot := range oots {
+ oop := &OneofProperties{
+ Type: reflect.ValueOf(oot).Type(), // *T
+ Prop: new(Properties),
+ }
+ sft := oop.Type.Elem().Field(0)
+ oop.Prop.Name = sft.Name
+ oop.Prop.Parse(sft.Tag.Get("protobuf"))
+ // There will be exactly one interface field that
+ // this new value is assignable to.
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ if f.Type.Kind() != reflect.Interface {
+ continue
+ }
+ if !oop.Type.AssignableTo(f.Type) {
+ continue
+ }
+ oop.Field = i
+ break
+ }
+ prop.OneofTypes[oop.Prop.OrigName] = oop
+ }
+ }
+
+ // build required counts
+ // build tags
+ reqCount := 0
+ prop.decoderOrigNames = make(map[string]int)
+ for i, p := range prop.Prop {
+ if strings.HasPrefix(p.Name, "XXX_") {
+ // Internal fields should not appear in tags/origNames maps.
+ // They are handled specially when encoding and decoding.
+ continue
+ }
+ if p.Required {
+ reqCount++
+ }
+ prop.decoderTags.put(p.Tag, i)
+ prop.decoderOrigNames[p.OrigName] = i
+ }
+ prop.reqCount = reqCount
+
+ return prop
+}
+
+// Return the Properties object for the x[0]'th field of the structure.
+func propByIndex(t reflect.Type, x []int) *Properties {
+ if len(x) != 1 {
+ fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t)
+ return nil
+ }
+ prop := GetProperties(t)
+ return prop.Prop[x[0]]
+}
+
+// Get the address and type of a pointer to a struct from an interface.
+func getbase(pb Message) (t reflect.Type, b structPointer, err error) {
+ if pb == nil {
+ err = ErrNil
+ return
+ }
+ // get the reflect type of the pointer to the struct.
+ t = reflect.TypeOf(pb)
+ // get the address of the struct.
+ value := reflect.ValueOf(pb)
+ b = toStructPointer(value)
+ return
+}
+
+// A global registry of enum types.
+// The generated code will register the generated maps by calling RegisterEnum.
+
+var enumValueMaps = make(map[string]map[string]int32)
+var enumStringMaps = make(map[string]map[int32]string)
+
+// RegisterEnum is called from the generated code to install the enum descriptor
+// maps into the global table to aid parsing text format protocol buffers.
+func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
+ if _, ok := enumValueMaps[typeName]; ok {
+ panic("proto: duplicate enum registered: " + typeName)
+ }
+ enumValueMaps[typeName] = valueMap
+ if _, ok := enumStringMaps[typeName]; ok {
+ panic("proto: duplicate enum registered: " + typeName)
+ }
+ enumStringMaps[typeName] = unusedNameMap
+}
+
+// EnumValueMap returns the mapping from names to integers of the
+// enum type enumType, or a nil if not found.
+func EnumValueMap(enumType string) map[string]int32 {
+ return enumValueMaps[enumType]
+}
+
+// A registry of all linked message types.
+// The string is a fully-qualified proto name ("pkg.Message").
+var (
+ protoTypes = make(map[string]reflect.Type)
+ revProtoTypes = make(map[reflect.Type]string)
+)
+
+// RegisterType is called from generated code and maps from the fully qualified
+// proto name to the type (pointer to struct) of the protocol buffer.
+func RegisterType(x Message, name string) {
+ if _, ok := protoTypes[name]; ok {
+ // TODO: Some day, make this a panic.
+ log.Printf("proto: duplicate proto type registered: %s", name)
+ return
+ }
+ t := reflect.TypeOf(x)
+ protoTypes[name] = t
+ revProtoTypes[t] = name
+}
+
+// MessageName returns the fully-qualified proto name for the given message type.
+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] }
+
+// A registry of all linked proto files.
+var (
+ protoFiles = make(map[string][]byte) // file name => fileDescriptor
+)
+
+// RegisterFile is called from generated code and maps from the
+// full file name of a .proto file to its compressed FileDescriptorProto.
+func RegisterFile(filename string, fileDescriptor []byte) {
+ protoFiles[filename] = fileDescriptor
+}
+
+// FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
+func FileDescriptor(filename string) []byte { return protoFiles[filename] }
diff --git a/vendor/github.com/gogo/protobuf/proto/properties_gogo.go b/vendor/github.com/gogo/protobuf/proto/properties_gogo.go
new file mode 100644
index 0000000..b6b7176
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/properties_gogo.go
@@ -0,0 +1,111 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 proto
+
+import (
+ "fmt"
+ "os"
+ "reflect"
+)
+
+func (p *Properties) setCustomEncAndDec(typ reflect.Type) {
+ p.ctype = typ
+ if p.Repeated {
+ p.enc = (*Buffer).enc_custom_slice_bytes
+ p.dec = (*Buffer).dec_custom_slice_bytes
+ p.size = size_custom_slice_bytes
+ } else if typ.Kind() == reflect.Ptr {
+ p.enc = (*Buffer).enc_custom_bytes
+ p.dec = (*Buffer).dec_custom_bytes
+ p.size = size_custom_bytes
+ } else {
+ p.enc = (*Buffer).enc_custom_ref_bytes
+ p.dec = (*Buffer).dec_custom_ref_bytes
+ p.size = size_custom_ref_bytes
+ }
+}
+
+func (p *Properties) setDurationEncAndDec(typ reflect.Type) {
+ if p.Repeated {
+ if typ.Elem().Kind() == reflect.Ptr {
+ p.enc = (*Buffer).enc_slice_duration
+ p.dec = (*Buffer).dec_slice_duration
+ p.size = size_slice_duration
+ } else {
+ p.enc = (*Buffer).enc_slice_ref_duration
+ p.dec = (*Buffer).dec_slice_ref_duration
+ p.size = size_slice_ref_duration
+ }
+ } else if typ.Kind() == reflect.Ptr {
+ p.enc = (*Buffer).enc_duration
+ p.dec = (*Buffer).dec_duration
+ p.size = size_duration
+ } else {
+ p.enc = (*Buffer).enc_ref_duration
+ p.dec = (*Buffer).dec_ref_duration
+ p.size = size_ref_duration
+ }
+}
+
+func (p *Properties) setTimeEncAndDec(typ reflect.Type) {
+ if p.Repeated {
+ if typ.Elem().Kind() == reflect.Ptr {
+ p.enc = (*Buffer).enc_slice_time
+ p.dec = (*Buffer).dec_slice_time
+ p.size = size_slice_time
+ } else {
+ p.enc = (*Buffer).enc_slice_ref_time
+ p.dec = (*Buffer).dec_slice_ref_time
+ p.size = size_slice_ref_time
+ }
+ } else if typ.Kind() == reflect.Ptr {
+ p.enc = (*Buffer).enc_time
+ p.dec = (*Buffer).dec_time
+ p.size = size_time
+ } else {
+ p.enc = (*Buffer).enc_ref_time
+ p.dec = (*Buffer).dec_ref_time
+ p.size = size_ref_time
+ }
+
+}
+
+func (p *Properties) setSliceOfNonPointerStructs(typ reflect.Type) {
+ t2 := typ.Elem()
+ p.sstype = typ
+ p.stype = t2
+ p.isMarshaler = isMarshaler(t2)
+ p.isUnmarshaler = isUnmarshaler(t2)
+ p.enc = (*Buffer).enc_slice_ref_struct_message
+ p.dec = (*Buffer).dec_slice_ref_struct_message
+ p.size = size_slice_ref_struct_message
+ if p.Wire != "bytes" {
+ fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T \n", typ, t2)
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/skip_gogo.go b/vendor/github.com/gogo/protobuf/proto/skip_gogo.go
new file mode 100644
index 0000000..5a5fd93
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/skip_gogo.go
@@ -0,0 +1,119 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 proto
+
+import (
+ "fmt"
+ "io"
+)
+
+func Skip(data []byte) (n int, err error) {
+ l := len(data)
+ index := 0
+ for index < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if index >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[index]
+ index++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for {
+ if index >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ index++
+ if data[index-1] < 0x80 {
+ break
+ }
+ }
+ return index, nil
+ case 1:
+ index += 8
+ return index, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if index >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[index]
+ index++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ index += length
+ return index, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = index
+ for shift := uint(0); ; shift += 7 {
+ if index >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[index]
+ index++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := Skip(data[start:])
+ if err != nil {
+ return 0, err
+ }
+ index = start + next
+ }
+ return index, nil
+ case 4:
+ return index, nil
+ case 5:
+ index += 4
+ return index, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/text.go b/vendor/github.com/gogo/protobuf/proto/text.go
new file mode 100644
index 0000000..d63732f
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/text.go
@@ -0,0 +1,928 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+// Functions for writing the text protocol buffer format.
+
+import (
+ "bufio"
+ "bytes"
+ "encoding"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "math"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+)
+
+var (
+ newline = []byte("\n")
+ spaces = []byte(" ")
+ gtNewline = []byte(">\n")
+ endBraceNewline = []byte("}\n")
+ backslashN = []byte{'\\', 'n'}
+ backslashR = []byte{'\\', 'r'}
+ backslashT = []byte{'\\', 't'}
+ backslashDQ = []byte{'\\', '"'}
+ backslashBS = []byte{'\\', '\\'}
+ posInf = []byte("inf")
+ negInf = []byte("-inf")
+ nan = []byte("nan")
+)
+
+type writer interface {
+ io.Writer
+ WriteByte(byte) error
+}
+
+// textWriter is an io.Writer that tracks its indentation level.
+type textWriter struct {
+ ind int
+ complete bool // if the current position is a complete line
+ compact bool // whether to write out as a one-liner
+ w writer
+}
+
+func (w *textWriter) WriteString(s string) (n int, err error) {
+ if !strings.Contains(s, "\n") {
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ w.complete = false
+ return io.WriteString(w.w, s)
+ }
+ // WriteString is typically called without newlines, so this
+ // codepath and its copy are rare. We copy to avoid
+ // duplicating all of Write's logic here.
+ return w.Write([]byte(s))
+}
+
+func (w *textWriter) Write(p []byte) (n int, err error) {
+ newlines := bytes.Count(p, newline)
+ if newlines == 0 {
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ n, err = w.w.Write(p)
+ w.complete = false
+ return n, err
+ }
+
+ frags := bytes.SplitN(p, newline, newlines+1)
+ if w.compact {
+ for i, frag := range frags {
+ if i > 0 {
+ if err := w.w.WriteByte(' '); err != nil {
+ return n, err
+ }
+ n++
+ }
+ nn, err := w.w.Write(frag)
+ n += nn
+ if err != nil {
+ return n, err
+ }
+ }
+ return n, nil
+ }
+
+ for i, frag := range frags {
+ if w.complete {
+ w.writeIndent()
+ }
+ nn, err := w.w.Write(frag)
+ n += nn
+ if err != nil {
+ return n, err
+ }
+ if i+1 < len(frags) {
+ if err := w.w.WriteByte('\n'); err != nil {
+ return n, err
+ }
+ n++
+ }
+ }
+ w.complete = len(frags[len(frags)-1]) == 0
+ return n, nil
+}
+
+func (w *textWriter) WriteByte(c byte) error {
+ if w.compact && c == '\n' {
+ c = ' '
+ }
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ err := w.w.WriteByte(c)
+ w.complete = c == '\n'
+ return err
+}
+
+func (w *textWriter) indent() { w.ind++ }
+
+func (w *textWriter) unindent() {
+ if w.ind == 0 {
+ log.Print("proto: textWriter unindented too far")
+ return
+ }
+ w.ind--
+}
+
+func writeName(w *textWriter, props *Properties) error {
+ if _, err := w.WriteString(props.OrigName); err != nil {
+ return err
+ }
+ if props.Wire != "group" {
+ return w.WriteByte(':')
+ }
+ return nil
+}
+
+// raw is the interface satisfied by RawMessage.
+type raw interface {
+ Bytes() []byte
+}
+
+func requiresQuotes(u string) bool {
+ // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
+ for _, ch := range u {
+ switch {
+ case ch == '.' || ch == '/' || ch == '_':
+ continue
+ case '0' <= ch && ch <= '9':
+ continue
+ case 'A' <= ch && ch <= 'Z':
+ continue
+ case 'a' <= ch && ch <= 'z':
+ continue
+ default:
+ return true
+ }
+ }
+ return false
+}
+
+// isAny reports whether sv is a google.protobuf.Any message
+func isAny(sv reflect.Value) bool {
+ type wkt interface {
+ XXX_WellKnownType() string
+ }
+ t, ok := sv.Addr().Interface().(wkt)
+ return ok && t.XXX_WellKnownType() == "Any"
+}
+
+// writeProto3Any writes an expanded google.protobuf.Any message.
+//
+// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
+// required messages are not linked in).
+//
+// It returns (true, error) when sv was written in expanded format or an error
+// was encountered.
+func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
+ turl := sv.FieldByName("TypeUrl")
+ val := sv.FieldByName("Value")
+ if !turl.IsValid() || !val.IsValid() {
+ return true, errors.New("proto: invalid google.protobuf.Any message")
+ }
+
+ b, ok := val.Interface().([]byte)
+ if !ok {
+ return true, errors.New("proto: invalid google.protobuf.Any message")
+ }
+
+ parts := strings.Split(turl.String(), "/")
+ mt := MessageType(parts[len(parts)-1])
+ if mt == nil {
+ return false, nil
+ }
+ m := reflect.New(mt.Elem())
+ if err := Unmarshal(b, m.Interface().(Message)); err != nil {
+ return false, nil
+ }
+ w.Write([]byte("["))
+ u := turl.String()
+ if requiresQuotes(u) {
+ writeString(w, u)
+ } else {
+ w.Write([]byte(u))
+ }
+ if w.compact {
+ w.Write([]byte("]:<"))
+ } else {
+ w.Write([]byte("]: <\n"))
+ w.ind++
+ }
+ if err := tm.writeStruct(w, m.Elem()); err != nil {
+ return true, err
+ }
+ if w.compact {
+ w.Write([]byte("> "))
+ } else {
+ w.ind--
+ w.Write([]byte(">\n"))
+ }
+ return true, nil
+}
+
+func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
+ if tm.ExpandAny && isAny(sv) {
+ if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
+ return err
+ }
+ }
+ st := sv.Type()
+ sprops := GetProperties(st)
+ for i := 0; i < sv.NumField(); i++ {
+ fv := sv.Field(i)
+ props := sprops.Prop[i]
+ name := st.Field(i).Name
+
+ if strings.HasPrefix(name, "XXX_") {
+ // There are two XXX_ fields:
+ // XXX_unrecognized []byte
+ // XXX_extensions map[int32]proto.Extension
+ // The first is handled here;
+ // the second is handled at the bottom of this function.
+ if name == "XXX_unrecognized" && !fv.IsNil() {
+ if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if fv.Kind() == reflect.Ptr && fv.IsNil() {
+ // Field not filled in. This could be an optional field or
+ // a required field that wasn't filled in. Either way, there
+ // isn't anything we can show for it.
+ continue
+ }
+ if fv.Kind() == reflect.Slice && fv.IsNil() {
+ // Repeated field that is empty, or a bytes field that is unused.
+ continue
+ }
+
+ if props.Repeated && fv.Kind() == reflect.Slice {
+ // Repeated field.
+ for j := 0; j < fv.Len(); j++ {
+ if err := writeName(w, props); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ v := fv.Index(j)
+ if v.Kind() == reflect.Ptr && v.IsNil() {
+ // A nil message in a repeated field is not valid,
+ // but we can handle that more gracefully than panicking.
+ if _, err := w.Write([]byte("<nil>\n")); err != nil {
+ return err
+ }
+ continue
+ }
+ if len(props.Enum) > 0 {
+ if err := tm.writeEnum(w, v, props); err != nil {
+ return err
+ }
+ } else if err := tm.writeAny(w, v, props); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if fv.Kind() == reflect.Map {
+ // Map fields are rendered as a repeated struct with key/value fields.
+ keys := fv.MapKeys()
+ sort.Sort(mapKeys(keys))
+ for _, key := range keys {
+ val := fv.MapIndex(key)
+ if err := writeName(w, props); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ // open struct
+ if err := w.WriteByte('<'); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ w.indent()
+ // key
+ if _, err := w.WriteString("key:"); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if err := tm.writeAny(w, key, props.mkeyprop); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ // nil values aren't legal, but we can avoid panicking because of them.
+ if val.Kind() != reflect.Ptr || !val.IsNil() {
+ // value
+ if _, err := w.WriteString("value:"); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if err := tm.writeAny(w, val, props.mvalprop); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ // close struct
+ w.unindent()
+ if err := w.WriteByte('>'); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
+ // empty bytes field
+ continue
+ }
+ if props.proto3 && fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
+ // proto3 non-repeated scalar field; skip if zero value
+ if isProto3Zero(fv) {
+ continue
+ }
+ }
+
+ if fv.Kind() == reflect.Interface {
+ // Check if it is a oneof.
+ if st.Field(i).Tag.Get("protobuf_oneof") != "" {
+ // fv is nil, or holds a pointer to generated struct.
+ // That generated struct has exactly one field,
+ // which has a protobuf struct tag.
+ if fv.IsNil() {
+ continue
+ }
+ inner := fv.Elem().Elem() // interface -> *T -> T
+ tag := inner.Type().Field(0).Tag.Get("protobuf")
+ props = new(Properties) // Overwrite the outer props var, but not its pointee.
+ props.Parse(tag)
+ // Write the value in the oneof, not the oneof itself.
+ fv = inner.Field(0)
+
+ // Special case to cope with malformed messages gracefully:
+ // If the value in the oneof is a nil pointer, don't panic
+ // in writeAny.
+ if fv.Kind() == reflect.Ptr && fv.IsNil() {
+ // Use errors.New so writeAny won't render quotes.
+ msg := errors.New("/* nil */")
+ fv = reflect.ValueOf(&msg).Elem()
+ }
+ }
+ }
+
+ if err := writeName(w, props); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if b, ok := fv.Interface().(raw); ok {
+ if err := writeRaw(w, b.Bytes()); err != nil {
+ return err
+ }
+ continue
+ }
+
+ if len(props.Enum) > 0 {
+ if err := tm.writeEnum(w, fv, props); err != nil {
+ return err
+ }
+ } else if err := tm.writeAny(w, fv, props); err != nil {
+ return err
+ }
+
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+
+ // Extensions (the XXX_extensions field).
+ pv := sv
+ if pv.CanAddr() {
+ pv = sv.Addr()
+ } else {
+ pv = reflect.New(sv.Type())
+ pv.Elem().Set(sv)
+ }
+ if pv.Type().Implements(extensionRangeType) {
+ if err := tm.writeExtensions(w, pv); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+// writeRaw writes an uninterpreted raw message.
+func writeRaw(w *textWriter, b []byte) error {
+ if err := w.WriteByte('<'); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ w.indent()
+ if err := writeUnknownStruct(w, b); err != nil {
+ return err
+ }
+ w.unindent()
+ if err := w.WriteByte('>'); err != nil {
+ return err
+ }
+ return nil
+}
+
+// writeAny writes an arbitrary field.
+func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
+ v = reflect.Indirect(v)
+
+ if props != nil {
+ if len(props.CustomType) > 0 {
+ custom, ok := v.Interface().(Marshaler)
+ if ok {
+ data, err := custom.Marshal()
+ if err != nil {
+ return err
+ }
+ if err := writeString(w, string(data)); err != nil {
+ return err
+ }
+ return nil
+ }
+ } else if props.StdTime {
+ t, ok := v.Interface().(time.Time)
+ if !ok {
+ return fmt.Errorf("stdtime is not time.Time, but %T", v.Interface())
+ }
+ tproto, err := timestampProto(t)
+ if err != nil {
+ return err
+ }
+ props.StdTime = false
+ err = tm.writeAny(w, reflect.ValueOf(tproto), props)
+ props.StdTime = true
+ return err
+ } else if props.StdDuration {
+ d, ok := v.Interface().(time.Duration)
+ if !ok {
+ return fmt.Errorf("stdtime is not time.Duration, but %T", v.Interface())
+ }
+ dproto := durationProto(d)
+ props.StdDuration = false
+ err := tm.writeAny(w, reflect.ValueOf(dproto), props)
+ props.StdDuration = true
+ return err
+ }
+ }
+
+ // Floats have special cases.
+ if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
+ x := v.Float()
+ var b []byte
+ switch {
+ case math.IsInf(x, 1):
+ b = posInf
+ case math.IsInf(x, -1):
+ b = negInf
+ case math.IsNaN(x):
+ b = nan
+ }
+ if b != nil {
+ _, err := w.Write(b)
+ return err
+ }
+ // Other values are handled below.
+ }
+
+ // We don't attempt to serialise every possible value type; only those
+ // that can occur in protocol buffers.
+ switch v.Kind() {
+ case reflect.Slice:
+ // Should only be a []byte; repeated fields are handled in writeStruct.
+ if err := writeString(w, string(v.Bytes())); err != nil {
+ return err
+ }
+ case reflect.String:
+ if err := writeString(w, v.String()); err != nil {
+ return err
+ }
+ case reflect.Struct:
+ // Required/optional group/message.
+ var bra, ket byte = '<', '>'
+ if props != nil && props.Wire == "group" {
+ bra, ket = '{', '}'
+ }
+ if err := w.WriteByte(bra); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ w.indent()
+ if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
+ text, err := etm.MarshalText()
+ if err != nil {
+ return err
+ }
+ if _, err = w.Write(text); err != nil {
+ return err
+ }
+ } else if err := tm.writeStruct(w, v); err != nil {
+ return err
+ }
+ w.unindent()
+ if err := w.WriteByte(ket); err != nil {
+ return err
+ }
+ default:
+ _, err := fmt.Fprint(w, v.Interface())
+ return err
+ }
+ return nil
+}
+
+// equivalent to C's isprint.
+func isprint(c byte) bool {
+ return c >= 0x20 && c < 0x7f
+}
+
+// writeString writes a string in the protocol buffer text format.
+// It is similar to strconv.Quote except we don't use Go escape sequences,
+// we treat the string as a byte sequence, and we use octal escapes.
+// These differences are to maintain interoperability with the other
+// languages' implementations of the text format.
+func writeString(w *textWriter, s string) error {
+ // use WriteByte here to get any needed indent
+ if err := w.WriteByte('"'); err != nil {
+ return err
+ }
+ // Loop over the bytes, not the runes.
+ for i := 0; i < len(s); i++ {
+ var err error
+ // Divergence from C++: we don't escape apostrophes.
+ // There's no need to escape them, and the C++ parser
+ // copes with a naked apostrophe.
+ switch c := s[i]; c {
+ case '\n':
+ _, err = w.w.Write(backslashN)
+ case '\r':
+ _, err = w.w.Write(backslashR)
+ case '\t':
+ _, err = w.w.Write(backslashT)
+ case '"':
+ _, err = w.w.Write(backslashDQ)
+ case '\\':
+ _, err = w.w.Write(backslashBS)
+ default:
+ if isprint(c) {
+ err = w.w.WriteByte(c)
+ } else {
+ _, err = fmt.Fprintf(w.w, "\\%03o", c)
+ }
+ }
+ if err != nil {
+ return err
+ }
+ }
+ return w.WriteByte('"')
+}
+
+func writeUnknownStruct(w *textWriter, data []byte) (err error) {
+ if !w.compact {
+ if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
+ return err
+ }
+ }
+ b := NewBuffer(data)
+ for b.index < len(b.buf) {
+ x, err := b.DecodeVarint()
+ if err != nil {
+ _, ferr := fmt.Fprintf(w, "/* %v */\n", err)
+ return ferr
+ }
+ wire, tag := x&7, x>>3
+ if wire == WireEndGroup {
+ w.unindent()
+ if _, werr := w.Write(endBraceNewline); werr != nil {
+ return werr
+ }
+ continue
+ }
+ if _, ferr := fmt.Fprint(w, tag); ferr != nil {
+ return ferr
+ }
+ if wire != WireStartGroup {
+ if err = w.WriteByte(':'); err != nil {
+ return err
+ }
+ }
+ if !w.compact || wire == WireStartGroup {
+ if err = w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ switch wire {
+ case WireBytes:
+ buf, e := b.DecodeRawBytes(false)
+ if e == nil {
+ _, err = fmt.Fprintf(w, "%q", buf)
+ } else {
+ _, err = fmt.Fprintf(w, "/* %v */", e)
+ }
+ case WireFixed32:
+ x, err = b.DecodeFixed32()
+ err = writeUnknownInt(w, x, err)
+ case WireFixed64:
+ x, err = b.DecodeFixed64()
+ err = writeUnknownInt(w, x, err)
+ case WireStartGroup:
+ err = w.WriteByte('{')
+ w.indent()
+ case WireVarint:
+ x, err = b.DecodeVarint()
+ err = writeUnknownInt(w, x, err)
+ default:
+ _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
+ }
+ if err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeUnknownInt(w *textWriter, x uint64, err error) error {
+ if err == nil {
+ _, err = fmt.Fprint(w, x)
+ } else {
+ _, err = fmt.Fprintf(w, "/* %v */", err)
+ }
+ return err
+}
+
+type int32Slice []int32
+
+func (s int32Slice) Len() int { return len(s) }
+func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
+func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+// writeExtensions writes all the extensions in pv.
+// pv is assumed to be a pointer to a protocol message struct that is extendable.
+func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
+ emap := extensionMaps[pv.Type().Elem()]
+ e := pv.Interface().(Message)
+
+ var m map[int32]Extension
+ var mu sync.Locker
+ if em, ok := e.(extensionsBytes); ok {
+ eb := em.GetExtensions()
+ var err error
+ m, err = BytesToExtensionsMap(*eb)
+ if err != nil {
+ return err
+ }
+ mu = notLocker{}
+ } else if _, ok := e.(extendableProto); ok {
+ ep, _ := extendable(e)
+ m, mu = ep.extensionsRead()
+ if m == nil {
+ return nil
+ }
+ }
+
+ // Order the extensions by ID.
+ // This isn't strictly necessary, but it will give us
+ // canonical output, which will also make testing easier.
+
+ mu.Lock()
+ ids := make([]int32, 0, len(m))
+ for id := range m {
+ ids = append(ids, id)
+ }
+ sort.Sort(int32Slice(ids))
+ mu.Unlock()
+
+ for _, extNum := range ids {
+ ext := m[extNum]
+ var desc *ExtensionDesc
+ if emap != nil {
+ desc = emap[extNum]
+ }
+ if desc == nil {
+ // Unknown extension.
+ if err := writeUnknownStruct(w, ext.enc); err != nil {
+ return err
+ }
+ continue
+ }
+
+ pb, err := GetExtension(e, desc)
+ if err != nil {
+ return fmt.Errorf("failed getting extension: %v", err)
+ }
+
+ // Repeated extensions will appear as a slice.
+ if !desc.repeated() {
+ if err := tm.writeExtension(w, desc.Name, pb); err != nil {
+ return err
+ }
+ } else {
+ v := reflect.ValueOf(pb)
+ for i := 0; i < v.Len(); i++ {
+ if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
+ if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (w *textWriter) writeIndent() {
+ if !w.complete {
+ return
+ }
+ remain := w.ind * 2
+ for remain > 0 {
+ n := remain
+ if n > len(spaces) {
+ n = len(spaces)
+ }
+ w.w.Write(spaces[:n])
+ remain -= n
+ }
+ w.complete = false
+}
+
+// TextMarshaler is a configurable text format marshaler.
+type TextMarshaler struct {
+ Compact bool // use compact text format (one line).
+ ExpandAny bool // expand google.protobuf.Any messages of known types
+}
+
+// Marshal writes a given protocol buffer in text format.
+// The only errors returned are from w.
+func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
+ val := reflect.ValueOf(pb)
+ if pb == nil || val.IsNil() {
+ w.Write([]byte("<nil>"))
+ return nil
+ }
+ var bw *bufio.Writer
+ ww, ok := w.(writer)
+ if !ok {
+ bw = bufio.NewWriter(w)
+ ww = bw
+ }
+ aw := &textWriter{
+ w: ww,
+ complete: true,
+ compact: tm.Compact,
+ }
+
+ if etm, ok := pb.(encoding.TextMarshaler); ok {
+ text, err := etm.MarshalText()
+ if err != nil {
+ return err
+ }
+ if _, err = aw.Write(text); err != nil {
+ return err
+ }
+ if bw != nil {
+ return bw.Flush()
+ }
+ return nil
+ }
+ // Dereference the received pointer so we don't have outer < and >.
+ v := reflect.Indirect(val)
+ if err := tm.writeStruct(aw, v); err != nil {
+ return err
+ }
+ if bw != nil {
+ return bw.Flush()
+ }
+ return nil
+}
+
+// Text is the same as Marshal, but returns the string directly.
+func (tm *TextMarshaler) Text(pb Message) string {
+ var buf bytes.Buffer
+ tm.Marshal(&buf, pb)
+ return buf.String()
+}
+
+var (
+ defaultTextMarshaler = TextMarshaler{}
+ compactTextMarshaler = TextMarshaler{Compact: true}
+)
+
+// TODO: consider removing some of the Marshal functions below.
+
+// MarshalText writes a given protocol buffer in text format.
+// The only errors returned are from w.
+func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
+
+// MarshalTextString is the same as MarshalText, but returns the string directly.
+func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
+
+// CompactText writes a given protocol buffer in compact text format (one line).
+func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
+
+// CompactTextString is the same as CompactText, but returns the string directly.
+func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }
diff --git a/vendor/github.com/gogo/protobuf/proto/text_gogo.go b/vendor/github.com/gogo/protobuf/proto/text_gogo.go
new file mode 100644
index 0000000..1d6c6aa
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/text_gogo.go
@@ -0,0 +1,57 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 proto
+
+import (
+ "fmt"
+ "reflect"
+)
+
+func (tm *TextMarshaler) writeEnum(w *textWriter, v reflect.Value, props *Properties) error {
+ m, ok := enumStringMaps[props.Enum]
+ if !ok {
+ if err := tm.writeAny(w, v, props); err != nil {
+ return err
+ }
+ }
+ key := int32(0)
+ if v.Kind() == reflect.Ptr {
+ key = int32(v.Elem().Int())
+ } else {
+ key = int32(v.Int())
+ }
+ s, ok := m[key]
+ if !ok {
+ if err := tm.writeAny(w, v, props); err != nil {
+ return err
+ }
+ }
+ _, err := fmt.Fprint(w, s)
+ return err
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/text_parser.go b/vendor/github.com/gogo/protobuf/proto/text_parser.go
new file mode 100644
index 0000000..9db12e9
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/text_parser.go
@@ -0,0 +1,1013 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+// Functions for parsing the Text protocol buffer format.
+// TODO: message sets.
+
+import (
+ "encoding"
+ "errors"
+ "fmt"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+ "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
+ Offset int // 0-based byte offset from start of input
+}
+
+func (p *ParseError) Error() string {
+ if p.Line == 1 {
+ // show offset only for first line
+ return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
+ }
+ return fmt.Sprintf("line %d: %v", p.Line, p.Message)
+}
+
+type token struct {
+ value string
+ err *ParseError
+ line int // line number
+ offset int // byte number from start of input, not start of line
+ unquoted string // the unquoted version of value, if it was a quoted string
+}
+
+func (t *token) String() string {
+ if t.err == nil {
+ return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
+ }
+ return fmt.Sprintf("parse error: %v", t.err)
+}
+
+type textParser struct {
+ s string // remaining input
+ done bool // whether the parsing is finished (success or error)
+ backed bool // whether back() was called
+ offset, line int
+ cur token
+}
+
+func newTextParser(s string) *textParser {
+ p := new(textParser)
+ p.s = s
+ p.line = 1
+ p.cur.line = 1
+ return p
+}
+
+func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
+ pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
+ p.cur.err = pe
+ p.done = true
+ return pe
+}
+
+// Numbers and identifiers are matched by [-+._A-Za-z0-9]
+func isIdentOrNumberChar(c byte) bool {
+ switch {
+ case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
+ return true
+ case '0' <= c && c <= '9':
+ return true
+ }
+ switch c {
+ case '-', '+', '.', '_':
+ return true
+ }
+ return false
+}
+
+func isWhitespace(c byte) bool {
+ switch c {
+ case ' ', '\t', '\n', '\r':
+ return true
+ }
+ return false
+}
+
+func isQuote(c byte) bool {
+ switch c {
+ case '"', '\'':
+ return true
+ }
+ return false
+}
+
+func (p *textParser) skipWhitespace() {
+ i := 0
+ for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
+ if p.s[i] == '#' {
+ // comment; skip to end of line or input
+ for i < len(p.s) && p.s[i] != '\n' {
+ i++
+ }
+ if i == len(p.s) {
+ break
+ }
+ }
+ if p.s[i] == '\n' {
+ p.line++
+ }
+ i++
+ }
+ p.offset += i
+ p.s = p.s[i:len(p.s)]
+ if len(p.s) == 0 {
+ p.done = true
+ }
+}
+
+func (p *textParser) advance() {
+ // Skip whitespace
+ p.skipWhitespace()
+ if p.done {
+ return
+ }
+
+ // Start of non-whitespace
+ p.cur.err = nil
+ p.cur.offset, p.cur.line = p.offset, p.line
+ p.cur.unquoted = ""
+ switch p.s[0] {
+ case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
+ // Single symbol
+ p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
+ case '"', '\'':
+ // Quoted string
+ i := 1
+ for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
+ if p.s[i] == '\\' && i+1 < len(p.s) {
+ // skip escaped char
+ i++
+ }
+ i++
+ }
+ if i >= len(p.s) || p.s[i] != p.s[0] {
+ p.errorf("unmatched quote")
+ return
+ }
+ unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
+ if err != nil {
+ p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
+ return
+ }
+ p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
+ p.cur.unquoted = unq
+ default:
+ i := 0
+ for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
+ i++
+ }
+ if i == 0 {
+ p.errorf("unexpected byte %#x", p.s[0])
+ return
+ }
+ p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
+ }
+ p.offset += len(p.cur.value)
+}
+
+var (
+ errBadUTF8 = errors.New("proto: bad UTF-8")
+ errBadHex = errors.New("proto: bad hexadecimal")
+)
+
+func unquoteC(s string, quote rune) (string, error) {
+ // This is based on C++'s tokenizer.cc.
+ // Despite its name, this is *not* parsing C syntax.
+ // For instance, "\0" is an invalid quoted string.
+
+ // Avoid allocation in trivial cases.
+ simple := true
+ for _, r := range s {
+ if r == '\\' || r == quote {
+ simple = false
+ break
+ }
+ }
+ if simple {
+ return s, nil
+ }
+
+ buf := make([]byte, 0, 3*len(s)/2)
+ for len(s) > 0 {
+ r, n := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && n == 1 {
+ return "", errBadUTF8
+ }
+ s = s[n:]
+ if r != '\\' {
+ if r < utf8.RuneSelf {
+ buf = append(buf, byte(r))
+ } else {
+ buf = append(buf, string(r)...)
+ }
+ continue
+ }
+
+ ch, tail, err := unescape(s)
+ if err != nil {
+ return "", err
+ }
+ buf = append(buf, ch...)
+ s = tail
+ }
+ return string(buf), nil
+}
+
+func unescape(s string) (ch string, tail string, err error) {
+ r, n := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && n == 1 {
+ return "", "", errBadUTF8
+ }
+ s = s[n:]
+ switch r {
+ case 'a':
+ return "\a", s, nil
+ case 'b':
+ return "\b", s, nil
+ case 'f':
+ return "\f", s, nil
+ case 'n':
+ return "\n", s, nil
+ case 'r':
+ return "\r", s, nil
+ case 't':
+ return "\t", s, nil
+ case 'v':
+ return "\v", s, nil
+ case '?':
+ return "?", s, nil // trigraph workaround
+ case '\'', '"', '\\':
+ return string(r), s, nil
+ case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X':
+ if len(s) < 2 {
+ return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
+ }
+ base := 8
+ ss := s[:2]
+ s = s[2:]
+ if r == 'x' || r == 'X' {
+ base = 16
+ } else {
+ ss = string(r) + ss
+ }
+ i, err := strconv.ParseUint(ss, base, 8)
+ if err != nil {
+ return "", "", err
+ }
+ return string([]byte{byte(i)}), s, nil
+ case 'u', 'U':
+ n := 4
+ if r == 'U' {
+ n = 8
+ }
+ if len(s) < n {
+ return "", "", fmt.Errorf(`\%c requires %d digits`, r, n)
+ }
+
+ bs := make([]byte, n/2)
+ for i := 0; i < n; i += 2 {
+ a, ok1 := unhex(s[i])
+ b, ok2 := unhex(s[i+1])
+ if !ok1 || !ok2 {
+ return "", "", errBadHex
+ }
+ bs[i/2] = a<<4 | b
+ }
+ s = s[n:]
+ return string(bs), s, nil
+ }
+ return "", "", fmt.Errorf(`unknown escape \%c`, r)
+}
+
+// Adapted from src/pkg/strconv/quote.go.
+func unhex(b byte) (v byte, ok bool) {
+ switch {
+ case '0' <= b && b <= '9':
+ return b - '0', true
+ case 'a' <= b && b <= 'f':
+ return b - 'a' + 10, true
+ case 'A' <= b && b <= 'F':
+ return b - 'A' + 10, true
+ }
+ return 0, false
+}
+
+// Back off the parser by one token. Can only be done between calls to next().
+// It makes the next advance() a no-op.
+func (p *textParser) back() { p.backed = true }
+
+// Advances the parser and returns the new current token.
+func (p *textParser) next() *token {
+ if p.backed || p.done {
+ p.backed = false
+ return &p.cur
+ }
+ p.advance()
+ if p.done {
+ p.cur.value = ""
+ } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
+ // Look for multiple quoted strings separated by whitespace,
+ // and concatenate them.
+ cat := p.cur
+ for {
+ p.skipWhitespace()
+ if p.done || !isQuote(p.s[0]) {
+ break
+ }
+ p.advance()
+ if p.cur.err != nil {
+ return &p.cur
+ }
+ cat.value += " " + p.cur.value
+ cat.unquoted += p.cur.unquoted
+ }
+ p.done = false // parser may have seen EOF, but we want to return cat
+ p.cur = cat
+ }
+ return &p.cur
+}
+
+func (p *textParser) consumeToken(s string) error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != s {
+ p.back()
+ return p.errorf("expected %q, found %q", s, tok.value)
+ }
+ return nil
+}
+
+// Return a RequiredNotSetError indicating which required field was not set.
+func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
+ st := sv.Type()
+ sprops := GetProperties(st)
+ for i := 0; i < st.NumField(); i++ {
+ if !isNil(sv.Field(i)) {
+ continue
+ }
+
+ props := sprops.Prop[i]
+ if props.Required {
+ return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
+ }
+ }
+ return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen
+}
+
+// Returns the index in the struct for the named field, as well as the parsed tag properties.
+func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
+ i, ok := sprops.decoderOrigNames[name]
+ if ok {
+ return i, sprops.Prop[i], true
+ }
+ return -1, nil, false
+}
+
+// Consume a ':' from the input stream (if the next token is a colon),
+// returning an error if a colon is needed but not present.
+func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != ":" {
+ // Colon is optional when the field is a group or message.
+ needColon := true
+ switch props.Wire {
+ case "group":
+ needColon = false
+ case "bytes":
+ // A "bytes" field is either a message, a string, or a repeated field;
+ // those three become *T, *string and []T respectively, so we can check for
+ // this field being a pointer to a non-string.
+ if typ.Kind() == reflect.Ptr {
+ // *T or *string
+ if typ.Elem().Kind() == reflect.String {
+ break
+ }
+ } else if typ.Kind() == reflect.Slice {
+ // []T or []*T
+ if typ.Elem().Kind() != reflect.Ptr {
+ break
+ }
+ } else if typ.Kind() == reflect.String {
+ // The proto3 exception is for a string field,
+ // which requires a colon.
+ break
+ }
+ needColon = false
+ }
+ if needColon {
+ return p.errorf("expected ':', found %q", tok.value)
+ }
+ p.back()
+ }
+ return nil
+}
+
+func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
+ st := sv.Type()
+ sprops := GetProperties(st)
+ reqCount := sprops.reqCount
+ var reqFieldErr error
+ fieldSet := make(map[string]bool)
+ // A struct is a sequence of "name: value", terminated by one of
+ // '>' or '}', or the end of the input. A name may also be
+ // "[extension]" or "[type/url]".
+ //
+ // The whole struct can also be an expanded Any message, like:
+ // [type/url] < ... struct contents ... >
+ for {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == terminator {
+ break
+ }
+ if tok.value == "[" {
+ // Looks like an extension or an Any.
+ //
+ // TODO: Check whether we need to handle
+ // namespace rooted names (e.g. ".something.Foo").
+ extName, err := p.consumeExtName()
+ if err != nil {
+ return err
+ }
+
+ if s := strings.LastIndex(extName, "/"); s >= 0 {
+ // If it contains a slash, it's an Any type URL.
+ messageName := extName[s+1:]
+ mt := MessageType(messageName)
+ if mt == nil {
+ return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
+ }
+ tok = p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ // consume an optional colon
+ if tok.value == ":" {
+ tok = p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ }
+ var terminator string
+ switch tok.value {
+ case "<":
+ terminator = ">"
+ case "{":
+ terminator = "}"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ v := reflect.New(mt.Elem())
+ if pe := p.readStruct(v.Elem(), terminator); pe != nil {
+ return pe
+ }
+ b, err := Marshal(v.Interface().(Message))
+ 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
+ }
+
+ var desc *ExtensionDesc
+ // This could be faster, but it's functional.
+ // TODO: Do something smarter than a linear scan.
+ for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
+ if d.Name == extName {
+ desc = d
+ break
+ }
+ }
+ if desc == nil {
+ return p.errorf("unrecognized extension %q", extName)
+ }
+
+ props := &Properties{}
+ props.Parse(desc.Tag)
+
+ typ := reflect.TypeOf(desc.ExtensionType)
+ if err := p.checkForColon(props, typ); err != nil {
+ return err
+ }
+
+ rep := desc.repeated()
+
+ // Read the extension structure, and set it in
+ // the value we're constructing.
+ var ext reflect.Value
+ if !rep {
+ ext = reflect.New(typ).Elem()
+ } else {
+ ext = reflect.New(typ.Elem()).Elem()
+ }
+ if err := p.readAny(ext, props); err != nil {
+ if _, ok := err.(*RequiredNotSetError); !ok {
+ return err
+ }
+ reqFieldErr = err
+ }
+ ep := sv.Addr().Interface().(Message)
+ if !rep {
+ SetExtension(ep, desc, ext.Interface())
+ } else {
+ old, err := GetExtension(ep, desc)
+ var sl reflect.Value
+ if err == nil {
+ sl = reflect.ValueOf(old) // existing slice
+ } else {
+ sl = reflect.MakeSlice(typ, 0, 1)
+ }
+ sl = reflect.Append(sl, ext)
+ SetExtension(ep, desc, sl.Interface())
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ continue
+ }
+
+ // This is a normal, non-extension field.
+ name := tok.value
+ var dst reflect.Value
+ fi, props, ok := structFieldByName(sprops, name)
+ if ok {
+ dst = sv.Field(fi)
+ } else if oop, ok := sprops.OneofTypes[name]; ok {
+ // It is a oneof.
+ props = oop.Prop
+ nv := reflect.New(oop.Type.Elem())
+ dst = nv.Elem().Field(0)
+ 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)
+ }
+
+ if dst.Kind() == reflect.Map {
+ // Consume any colon.
+ if err := p.checkForColon(props, dst.Type()); err != nil {
+ return err
+ }
+
+ // Construct the map if it doesn't already exist.
+ if dst.IsNil() {
+ dst.Set(reflect.MakeMap(dst.Type()))
+ }
+ key := reflect.New(dst.Type().Key()).Elem()
+ val := reflect.New(dst.Type().Elem()).Elem()
+
+ // The map entry should be this sequence of tokens:
+ // < key : KEY value : VALUE >
+ // However, implementations may omit key or value, and technically
+ // we should support them in any order. See b/28924776 for a time
+ // this went wrong.
+
+ tok := p.next()
+ var terminator string
+ switch tok.value {
+ case "<":
+ terminator = ">"
+ case "{":
+ terminator = "}"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ for {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == terminator {
+ break
+ }
+ switch tok.value {
+ case "key":
+ if err := p.consumeToken(":"); err != nil {
+ return err
+ }
+ if err := p.readAny(key, props.mkeyprop); err != nil {
+ return err
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ case "value":
+ if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
+ return err
+ }
+ if err := p.readAny(val, props.mvalprop); err != nil {
+ return err
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ default:
+ p.back()
+ return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
+ }
+ }
+
+ dst.SetMapIndex(key, val)
+ continue
+ }
+
+ // Check that it's not already set if it's not a repeated field.
+ if !props.Repeated && fieldSet[name] {
+ return p.errorf("non-repeated field %q was repeated", name)
+ }
+
+ if err := p.checkForColon(props, dst.Type()); err != nil {
+ return err
+ }
+
+ // Parse into the field.
+ fieldSet[name] = true
+ if err := p.readAny(dst, props); err != nil {
+ if _, ok := err.(*RequiredNotSetError); !ok {
+ return err
+ }
+ reqFieldErr = err
+ }
+ if props.Required {
+ reqCount--
+ }
+
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+
+ }
+
+ if reqCount > 0 {
+ return p.missingRequiredFieldError(sv)
+ }
+ return reqFieldErr
+}
+
+// consumeExtName consumes extension name or expanded Any type URL and the
+// following ']'. It returns the name or URL consumed.
+func (p *textParser) consumeExtName() (string, error) {
+ tok := p.next()
+ if tok.err != nil {
+ return "", tok.err
+ }
+
+ // If extension name or type url is quoted, it's a single token.
+ if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
+ name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
+ if err != nil {
+ return "", err
+ }
+ return name, p.consumeToken("]")
+ }
+
+ // Consume everything up to "]"
+ var parts []string
+ for tok.value != "]" {
+ parts = append(parts, tok.value)
+ tok = p.next()
+ if tok.err != nil {
+ return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
+ }
+ }
+ return strings.Join(parts, ""), nil
+}
+
+// consumeOptionalSeparator consumes an optional semicolon or comma.
+// It is used in readStruct to provide backward compatibility.
+func (p *textParser) consumeOptionalSeparator() error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != ";" && tok.value != "," {
+ p.back()
+ }
+ return nil
+}
+
+func (p *textParser) readAny(v reflect.Value, props *Properties) error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == "" {
+ return p.errorf("unexpected EOF")
+ }
+ if len(props.CustomType) > 0 {
+ if props.Repeated {
+ t := reflect.TypeOf(v.Interface())
+ if t.Kind() == reflect.Slice {
+ tc := reflect.TypeOf(new(Marshaler))
+ ok := t.Elem().Implements(tc.Elem())
+ if ok {
+ fv := v
+ flen := fv.Len()
+ if flen == fv.Cap() {
+ nav := reflect.MakeSlice(v.Type(), flen, 2*flen+1)
+ reflect.Copy(nav, fv)
+ fv.Set(nav)
+ }
+ fv.SetLen(flen + 1)
+
+ // Read one.
+ p.back()
+ return p.readAny(fv.Index(flen), props)
+ }
+ }
+ }
+ if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr {
+ custom := reflect.New(props.ctype.Elem()).Interface().(Unmarshaler)
+ err := custom.Unmarshal([]byte(tok.unquoted))
+ if err != nil {
+ return p.errorf("%v %v: %v", err, v.Type(), tok.value)
+ }
+ v.Set(reflect.ValueOf(custom))
+ } else {
+ custom := reflect.New(reflect.TypeOf(v.Interface())).Interface().(Unmarshaler)
+ err := custom.Unmarshal([]byte(tok.unquoted))
+ if err != nil {
+ return p.errorf("%v %v: %v", err, v.Type(), tok.value)
+ }
+ v.Set(reflect.Indirect(reflect.ValueOf(custom)))
+ }
+ return nil
+ }
+ if props.StdTime {
+ fv := v
+ p.back()
+ props.StdTime = false
+ tproto := &timestamp{}
+ err := p.readAny(reflect.ValueOf(tproto).Elem(), props)
+ props.StdTime = true
+ if err != nil {
+ return err
+ }
+ tim, err := timestampFromProto(tproto)
+ if err != nil {
+ return err
+ }
+ if props.Repeated {
+ t := reflect.TypeOf(v.Interface())
+ if t.Kind() == reflect.Slice {
+ if t.Elem().Kind() == reflect.Ptr {
+ ts := fv.Interface().([]*time.Time)
+ ts = append(ts, &tim)
+ fv.Set(reflect.ValueOf(ts))
+ return nil
+ } else {
+ ts := fv.Interface().([]time.Time)
+ ts = append(ts, tim)
+ fv.Set(reflect.ValueOf(ts))
+ return nil
+ }
+ }
+ }
+ if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr {
+ v.Set(reflect.ValueOf(&tim))
+ } else {
+ v.Set(reflect.Indirect(reflect.ValueOf(&tim)))
+ }
+ return nil
+ }
+ if props.StdDuration {
+ fv := v
+ p.back()
+ props.StdDuration = false
+ dproto := &duration{}
+ err := p.readAny(reflect.ValueOf(dproto).Elem(), props)
+ props.StdDuration = true
+ if err != nil {
+ return err
+ }
+ dur, err := durationFromProto(dproto)
+ if err != nil {
+ return err
+ }
+ if props.Repeated {
+ t := reflect.TypeOf(v.Interface())
+ if t.Kind() == reflect.Slice {
+ if t.Elem().Kind() == reflect.Ptr {
+ ds := fv.Interface().([]*time.Duration)
+ ds = append(ds, &dur)
+ fv.Set(reflect.ValueOf(ds))
+ return nil
+ } else {
+ ds := fv.Interface().([]time.Duration)
+ ds = append(ds, dur)
+ fv.Set(reflect.ValueOf(ds))
+ return nil
+ }
+ }
+ }
+ if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr {
+ v.Set(reflect.ValueOf(&dur))
+ } else {
+ v.Set(reflect.Indirect(reflect.ValueOf(&dur)))
+ }
+ return nil
+ }
+ switch fv := v; fv.Kind() {
+ case reflect.Slice:
+ at := v.Type()
+ if at.Elem().Kind() == reflect.Uint8 {
+ // Special case for []byte
+ if tok.value[0] != '"' && tok.value[0] != '\'' {
+ // Deliberately written out here, as the error after
+ // this switch statement would write "invalid []byte: ...",
+ // which is not as user-friendly.
+ return p.errorf("invalid string: %v", tok.value)
+ }
+ bytes := []byte(tok.unquoted)
+ fv.Set(reflect.ValueOf(bytes))
+ return nil
+ }
+ // Repeated field.
+ if tok.value == "[" {
+ // Repeated field with list notation, like [1,2,3].
+ for {
+ fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
+ err := p.readAny(fv.Index(fv.Len()-1), props)
+ if err != nil {
+ return err
+ }
+ ntok := p.next()
+ if ntok.err != nil {
+ return ntok.err
+ }
+ if ntok.value == "]" {
+ break
+ }
+ if ntok.value != "," {
+ return p.errorf("Expected ']' or ',' found %q", ntok.value)
+ }
+ }
+ return nil
+ }
+ // One value of the repeated field.
+ p.back()
+ fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
+ return p.readAny(fv.Index(fv.Len()-1), props)
+ case reflect.Bool:
+ // true/1/t/True or false/f/0/False.
+ switch tok.value {
+ case "true", "1", "t", "True":
+ fv.SetBool(true)
+ return nil
+ case "false", "0", "f", "False":
+ fv.SetBool(false)
+ return nil
+ }
+ case reflect.Float32, reflect.Float64:
+ v := tok.value
+ // Ignore 'f' for compatibility with output generated by C++, but don't
+ // remove 'f' when the value is "-inf" or "inf".
+ if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
+ v = v[:len(v)-1]
+ }
+ if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
+ fv.SetFloat(f)
+ return nil
+ }
+ case reflect.Int32:
+ if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
+ fv.SetInt(x)
+ return nil
+ }
+
+ if len(props.Enum) == 0 {
+ break
+ }
+ m, ok := enumValueMaps[props.Enum]
+ if !ok {
+ break
+ }
+ x, ok := m[tok.value]
+ if !ok {
+ break
+ }
+ fv.SetInt(int64(x))
+ return nil
+ case reflect.Int64:
+ if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
+ fv.SetInt(x)
+ return nil
+ }
+
+ case reflect.Ptr:
+ // A basic field (indirected through pointer), or a repeated message/group
+ p.back()
+ fv.Set(reflect.New(fv.Type().Elem()))
+ return p.readAny(fv.Elem(), props)
+ case reflect.String:
+ if tok.value[0] == '"' || tok.value[0] == '\'' {
+ fv.SetString(tok.unquoted)
+ return nil
+ }
+ case reflect.Struct:
+ var terminator string
+ switch tok.value {
+ case "{":
+ terminator = "}"
+ case "<":
+ terminator = ">"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
+ return p.readStruct(fv, terminator)
+ case reflect.Uint32:
+ if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
+ fv.SetUint(uint64(x))
+ return nil
+ }
+ case reflect.Uint64:
+ if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
+ fv.SetUint(x)
+ return nil
+ }
+ }
+ return p.errorf("invalid %v: %v", v.Type(), tok.value)
+}
+
+// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
+// before starting to unmarshal, so any existing data in pb is always removed.
+// If a required field is not set and no other error occurs,
+// UnmarshalText returns *RequiredNotSetError.
+func UnmarshalText(s string, pb Message) error {
+ if um, ok := pb.(encoding.TextUnmarshaler); ok {
+ err := um.UnmarshalText([]byte(s))
+ return err
+ }
+ pb.Reset()
+ v := reflect.ValueOf(pb)
+ if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
+ return pe
+ }
+ return nil
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/timestamp.go b/vendor/github.com/gogo/protobuf/proto/timestamp.go
new file mode 100644
index 0000000..9324f65
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/timestamp.go
@@ -0,0 +1,113 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+// This file implements operations on google.protobuf.Timestamp.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+)
+
+const (
+ // Seconds field of the earliest valid Timestamp.
+ // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
+ minValidSeconds = -62135596800
+ // Seconds field just after the latest valid Timestamp.
+ // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
+ maxValidSeconds = 253402300800
+)
+
+// validateTimestamp determines whether a Timestamp is valid.
+// A valid timestamp represents a time in the range
+// [0001-01-01, 10000-01-01) and has a Nanos field
+// in the range [0, 1e9).
+//
+// If the Timestamp is valid, validateTimestamp returns nil.
+// Otherwise, it returns an error that describes
+// the problem.
+//
+// Every valid Timestamp can be represented by a time.Time, but the converse is not true.
+func validateTimestamp(ts *timestamp) error {
+ if ts == nil {
+ return errors.New("timestamp: nil Timestamp")
+ }
+ if ts.Seconds < minValidSeconds {
+ return fmt.Errorf("timestamp: %#v before 0001-01-01", ts)
+ }
+ if ts.Seconds >= maxValidSeconds {
+ return fmt.Errorf("timestamp: %#v after 10000-01-01", ts)
+ }
+ if ts.Nanos < 0 || ts.Nanos >= 1e9 {
+ return fmt.Errorf("timestamp: %#v: nanos not in range [0, 1e9)", ts)
+ }
+ return nil
+}
+
+// TimestampFromProto converts a google.protobuf.Timestamp proto to a time.Time.
+// It returns an error if the argument is invalid.
+//
+// Unlike most Go functions, if Timestamp returns an error, the first return value
+// is not the zero time.Time. Instead, it is the value obtained from the
+// time.Unix function when passed the contents of the Timestamp, in the UTC
+// locale. This may or may not be a meaningful time; many invalid Timestamps
+// do map to valid time.Times.
+//
+// A nil Timestamp returns an error. The first return value in that case is
+// undefined.
+func timestampFromProto(ts *timestamp) (time.Time, error) {
+ // Don't return the zero value on error, because corresponds to a valid
+ // timestamp. Instead return whatever time.Unix gives us.
+ var t time.Time
+ if ts == nil {
+ t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp
+ } else {
+ t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
+ }
+ return t, validateTimestamp(ts)
+}
+
+// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
+// It returns an error if the resulting Timestamp is invalid.
+func timestampProto(t time.Time) (*timestamp, error) {
+ seconds := t.Unix()
+ nanos := int32(t.Sub(time.Unix(seconds, 0)))
+ ts := &timestamp{
+ Seconds: seconds,
+ Nanos: nanos,
+ }
+ if err := validateTimestamp(ts); err != nil {
+ return nil, err
+ }
+ return ts, nil
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go b/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go
new file mode 100644
index 0000000..d427647
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go
@@ -0,0 +1,229 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2016, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 proto
+
+import (
+ "reflect"
+ "time"
+)
+
+var timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
+
+type timestamp struct {
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
+}
+
+func (m *timestamp) Reset() { *m = timestamp{} }
+func (*timestamp) ProtoMessage() {}
+func (*timestamp) String() string { return "timestamp<string>" }
+
+func init() {
+ RegisterType((*timestamp)(nil), "gogo.protobuf.proto.timestamp")
+}
+
+func (o *Buffer) decTimestamp() (time.Time, error) {
+ b, err := o.DecodeRawBytes(true)
+ if err != nil {
+ return time.Time{}, err
+ }
+ tproto := &timestamp{}
+ if err := Unmarshal(b, tproto); err != nil {
+ return time.Time{}, err
+ }
+ return timestampFromProto(tproto)
+}
+
+func (o *Buffer) dec_time(p *Properties, base structPointer) error {
+ t, err := o.decTimestamp()
+ if err != nil {
+ return err
+ }
+ setPtrCustomType(base, p.field, &t)
+ return nil
+}
+
+func (o *Buffer) dec_ref_time(p *Properties, base structPointer) error {
+ t, err := o.decTimestamp()
+ if err != nil {
+ return err
+ }
+ setCustomType(base, p.field, &t)
+ return nil
+}
+
+func (o *Buffer) dec_slice_time(p *Properties, base structPointer) error {
+ t, err := o.decTimestamp()
+ if err != nil {
+ return err
+ }
+ newBas := appendStructPointer(base, p.field, reflect.SliceOf(reflect.PtrTo(timeType)))
+ var zero field
+ setPtrCustomType(newBas, zero, &t)
+ return nil
+}
+
+func (o *Buffer) dec_slice_ref_time(p *Properties, base structPointer) error {
+ t, err := o.decTimestamp()
+ if err != nil {
+ return err
+ }
+ newBas := appendStructPointer(base, p.field, reflect.SliceOf(timeType))
+ var zero field
+ setCustomType(newBas, zero, &t)
+ return nil
+}
+
+func size_time(p *Properties, base structPointer) (n int) {
+ structp := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(structp) {
+ return 0
+ }
+ tim := structPointer_Interface(structp, timeType).(*time.Time)
+ t, err := timestampProto(*tim)
+ if err != nil {
+ return 0
+ }
+ size := Size(t)
+ return size + sizeVarint(uint64(size)) + len(p.tagcode)
+}
+
+func (o *Buffer) enc_time(p *Properties, base structPointer) error {
+ structp := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(structp) {
+ return ErrNil
+ }
+ tim := structPointer_Interface(structp, timeType).(*time.Time)
+ t, err := timestampProto(*tim)
+ if err != nil {
+ return err
+ }
+ data, err := Marshal(t)
+ if err != nil {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ return nil
+}
+
+func size_ref_time(p *Properties, base structPointer) (n int) {
+ tim := structPointer_InterfaceAt(base, p.field, timeType).(*time.Time)
+ t, err := timestampProto(*tim)
+ if err != nil {
+ return 0
+ }
+ size := Size(t)
+ return size + sizeVarint(uint64(size)) + len(p.tagcode)
+}
+
+func (o *Buffer) enc_ref_time(p *Properties, base structPointer) error {
+ tim := structPointer_InterfaceAt(base, p.field, timeType).(*time.Time)
+ t, err := timestampProto(*tim)
+ if err != nil {
+ return err
+ }
+ data, err := Marshal(t)
+ if err != nil {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ return nil
+}
+
+func size_slice_time(p *Properties, base structPointer) (n int) {
+ ptims := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(reflect.PtrTo(timeType))).(*[]*time.Time)
+ tims := *ptims
+ for i := 0; i < len(tims); i++ {
+ if tims[i] == nil {
+ return 0
+ }
+ tproto, err := timestampProto(*tims[i])
+ if err != nil {
+ return 0
+ }
+ size := Size(tproto)
+ n += len(p.tagcode) + size + sizeVarint(uint64(size))
+ }
+ return n
+}
+
+func (o *Buffer) enc_slice_time(p *Properties, base structPointer) error {
+ ptims := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(reflect.PtrTo(timeType))).(*[]*time.Time)
+ tims := *ptims
+ for i := 0; i < len(tims); i++ {
+ if tims[i] == nil {
+ return errRepeatedHasNil
+ }
+ tproto, err := timestampProto(*tims[i])
+ if err != nil {
+ return err
+ }
+ data, err := Marshal(tproto)
+ if err != nil {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ }
+ return nil
+}
+
+func size_slice_ref_time(p *Properties, base structPointer) (n int) {
+ ptims := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(timeType)).(*[]time.Time)
+ tims := *ptims
+ for i := 0; i < len(tims); i++ {
+ tproto, err := timestampProto(tims[i])
+ if err != nil {
+ return 0
+ }
+ size := Size(tproto)
+ n += len(p.tagcode) + size + sizeVarint(uint64(size))
+ }
+ return n
+}
+
+func (o *Buffer) enc_slice_ref_time(p *Properties, base structPointer) error {
+ ptims := structPointer_InterfaceAt(base, p.field, reflect.SliceOf(timeType)).(*[]time.Time)
+ tims := *ptims
+ for i := 0; i < len(tims); i++ {
+ tproto, err := timestampProto(tims[i])
+ if err != nil {
+ return err
+ }
+ data, err := Marshal(tproto)
+ if err != nil {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ }
+ return nil
+}
diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/any.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/any.proto
new file mode 100644
index 0000000..8152a34
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/any.proto
@@ -0,0 +1,140 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option go_package = "types";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "AnyProto";
+option java_multiple_files = true;
+option java_generate_equals_and_hash = true;
+option objc_class_prefix = "GPB";
+
+// `Any` contains an arbitrary serialized protocol buffer message along with a
+// URL that describes the type of the serialized message.
+//
+// Protobuf library provides support to pack/unpack Any values in the form
+// of utility functions or additional generated methods of the Any type.
+//
+// Example 1: Pack and unpack a message in C++.
+//
+// Foo foo = ...;
+// Any any;
+// any.PackFrom(foo);
+// ...
+// if (any.UnpackTo(&foo)) {
+// ...
+// }
+//
+// Example 2: Pack and unpack a message in Java.
+//
+// Foo foo = ...;
+// Any any = Any.pack(foo);
+// ...
+// if (any.is(Foo.class)) {
+// foo = any.unpack(Foo.class);
+// }
+//
+// Example 3: Pack and unpack a message in Python.
+//
+// foo = Foo(...)
+// any = Any()
+// any.Pack(foo)
+// ...
+// if any.Is(Foo.DESCRIPTOR):
+// any.Unpack(foo)
+// ...
+//
+// The pack methods provided by protobuf library will by default use
+// 'type.googleapis.com/full.type.name' as the type URL and the unpack
+// methods only use the fully qualified type name after the last '/'
+// in the type URL, for example "foo.bar.com/x/y.z" will yield type
+// name "y.z".
+//
+//
+// JSON
+// ====
+// The JSON representation of an `Any` value uses the regular
+// representation of the deserialized, embedded message, with an
+// additional field `@type` which contains the type URL. Example:
+//
+// package google.profile;
+// message Person {
+// string first_name = 1;
+// string last_name = 2;
+// }
+//
+// {
+// "@type": "type.googleapis.com/google.profile.Person",
+// "firstName": <string>,
+// "lastName": <string>
+// }
+//
+// If the embedded message type is well-known and has a custom JSON
+// representation, that representation will be embedded adding a field
+// `value` which holds the custom JSON in addition to the `@type`
+// field. Example (for message [google.protobuf.Duration][]):
+//
+// {
+// "@type": "type.googleapis.com/google.protobuf.Duration",
+// "value": "1.212s"
+// }
+//
+message Any {
+ // A URL/resource name whose content describes the type of the
+ // serialized protocol buffer message.
+ //
+ // For URLs which use the scheme `http`, `https`, or no scheme, the
+ // following restrictions and interpretations apply:
+ //
+ // * If no scheme is provided, `https` is assumed.
+ // * The last segment of the URL's path must represent the fully
+ // qualified name of the type (as in `path/google.protobuf.Duration`).
+ // The name should be in a canonical form (e.g., leading "." is
+ // not accepted).
+ // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ // value in binary format, or produce an error.
+ // * Applications are allowed to cache lookup results based on the
+ // URL, or have them precompiled into a binary to avoid any
+ // lookup. Therefore, binary compatibility needs to be preserved
+ // on changes to types. (Use versioned type names to manage
+ // breaking changes.)
+ //
+ // Schemes other than `http`, `https` (or the empty scheme) might be
+ // used with implementation specific semantics.
+ //
+ string type_url = 1;
+
+ // Must be a valid serialized protocol buffer of the above specified type.
+ bytes value = 2;
+}
diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/compiler/plugin.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/compiler/plugin.proto
new file mode 100644
index 0000000..acaee1f
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/compiler/plugin.proto
@@ -0,0 +1,150 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+// Author: kenton@google.com (Kenton Varda)
+//
+// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to
+// change.
+//
+// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is
+// just a program that reads a CodeGeneratorRequest from stdin and writes a
+// CodeGeneratorResponse to stdout.
+//
+// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
+// of dealing with the raw protocol defined here.
+//
+// A plugin executable needs only to be placed somewhere in the path. The
+// plugin should be named "protoc-gen-$NAME", and will then be used when the
+// flag "--${NAME}_out" is passed to protoc.
+
+syntax = "proto2";
+package google.protobuf.compiler;
+option java_package = "com.google.protobuf.compiler";
+option java_outer_classname = "PluginProtos";
+
+option go_package = "plugin_go";
+
+import "google/protobuf/descriptor.proto";
+
+// An encoded CodeGeneratorRequest is written to the plugin's stdin.
+message CodeGeneratorRequest {
+ // The .proto files that were explicitly listed on the command-line. The
+ // code generator should generate code only for these files. Each file's
+ // descriptor will be included in proto_file, below.
+ repeated string file_to_generate = 1;
+
+ // The generator parameter passed on the command-line.
+ optional string parameter = 2;
+
+ // FileDescriptorProtos for all files in files_to_generate and everything
+ // they import. The files will appear in topological order, so each file
+ // appears before any file that imports it.
+ //
+ // protoc guarantees that all proto_files will be written after
+ // the fields above, even though this is not technically guaranteed by the
+ // protobuf wire format. This theoretically could allow a plugin to stream
+ // in the FileDescriptorProtos and handle them one by one rather than read
+ // the entire set into memory at once. However, as of this writing, this
+ // is not similarly optimized on protoc's end -- it will store all fields in
+ // memory at once before sending them to the plugin.
+ repeated FileDescriptorProto proto_file = 15;
+}
+
+// The plugin writes an encoded CodeGeneratorResponse to stdout.
+message CodeGeneratorResponse {
+ // Error message. If non-empty, code generation failed. The plugin process
+ // should exit with status code zero even if it reports an error in this way.
+ //
+ // This should be used to indicate errors in .proto files which prevent the
+ // code generator from generating correct code. Errors which indicate a
+ // problem in protoc itself -- such as the input CodeGeneratorRequest being
+ // unparseable -- should be reported by writing a message to stderr and
+ // exiting with a non-zero status code.
+ optional string error = 1;
+
+ // Represents a single generated file.
+ message File {
+ // The file name, relative to the output directory. The name must not
+ // contain "." or ".." components and must be relative, not be absolute (so,
+ // the file cannot lie outside the output directory). "/" must be used as
+ // the path separator, not "\".
+ //
+ // If the name is omitted, the content will be appended to the previous
+ // file. This allows the generator to break large files into small chunks,
+ // and allows the generated text to be streamed back to protoc so that large
+ // files need not reside completely in memory at one time. Note that as of
+ // this writing protoc does not optimize for this -- it will read the entire
+ // CodeGeneratorResponse before writing files to disk.
+ optional string name = 1;
+
+ // If non-empty, indicates that the named file should already exist, and the
+ // content here is to be inserted into that file at a defined insertion
+ // point. This feature allows a code generator to extend the output
+ // produced by another code generator. The original generator may provide
+ // insertion points by placing special annotations in the file that look
+ // like:
+ // @@protoc_insertion_point(NAME)
+ // The annotation can have arbitrary text before and after it on the line,
+ // which allows it to be placed in a comment. NAME should be replaced with
+ // an identifier naming the point -- this is what other generators will use
+ // as the insertion_point. Code inserted at this point will be placed
+ // immediately above the line containing the insertion point (thus multiple
+ // insertions to the same point will come out in the order they were added).
+ // The double-@ is intended to make it unlikely that the generated code
+ // could contain things that look like insertion points by accident.
+ //
+ // For example, the C++ code generator places the following line in the
+ // .pb.h files that it generates:
+ // // @@protoc_insertion_point(namespace_scope)
+ // This line appears within the scope of the file's package namespace, but
+ // outside of any particular class. Another plugin can then specify the
+ // insertion_point "namespace_scope" to generate additional classes or
+ // other declarations that should be placed in this scope.
+ //
+ // Note that if the line containing the insertion point begins with
+ // whitespace, the same whitespace will be added to every line of the
+ // inserted text. This is useful for languages like Python, where
+ // indentation matters. In these languages, the insertion point comment
+ // should be indented the same amount as any inserted code will need to be
+ // in order to work correctly in that context.
+ //
+ // The code generator that generates the initial file and the one which
+ // inserts into it must both run as part of a single invocation of protoc.
+ // Code generators are executed in the order in which they appear on the
+ // command line.
+ //
+ // If |insertion_point| is present, |name| must also be present.
+ optional string insertion_point = 2;
+
+ // The file contents.
+ optional string content = 15;
+ }
+ repeated File file = 15;
+}
diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/descriptor.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/descriptor.proto
new file mode 100644
index 0000000..9aefdef
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/descriptor.proto
@@ -0,0 +1,813 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+// Author: kenton@google.com (Kenton Varda)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// The messages in this file describe the definitions found in .proto files.
+// A valid .proto file can be translated directly to a FileDescriptorProto
+// without any other information (e.g. without reading its imports).
+
+
+syntax = "proto2";
+
+package google.protobuf;
+option go_package = "descriptor";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "DescriptorProtos";
+option csharp_namespace = "Google.Protobuf.Reflection";
+option objc_class_prefix = "GPB";
+option java_generate_equals_and_hash = true;
+
+// descriptor.proto must be optimized for speed because reflection-based
+// algorithms don't work during bootstrapping.
+option optimize_for = SPEED;
+
+// The protocol compiler can output a FileDescriptorSet containing the .proto
+// files it parses.
+message FileDescriptorSet {
+ repeated FileDescriptorProto file = 1;
+}
+
+// Describes a complete .proto file.
+message FileDescriptorProto {
+ optional string name = 1; // file name, relative to root of source tree
+ optional string package = 2; // e.g. "foo", "foo.bar", etc.
+
+ // Names of files imported by this file.
+ repeated string dependency = 3;
+ // Indexes of the public imported files in the dependency list above.
+ repeated int32 public_dependency = 10;
+ // Indexes of the weak imported files in the dependency list.
+ // For Google-internal migration only. Do not use.
+ repeated int32 weak_dependency = 11;
+
+ // All top-level definitions in this file.
+ repeated DescriptorProto message_type = 4;
+ repeated EnumDescriptorProto enum_type = 5;
+ repeated ServiceDescriptorProto service = 6;
+ repeated FieldDescriptorProto extension = 7;
+
+ optional FileOptions options = 8;
+
+ // This field contains optional information about the original source code.
+ // You may safely remove this entire field without harming runtime
+ // functionality of the descriptors -- the information is needed only by
+ // development tools.
+ optional SourceCodeInfo source_code_info = 9;
+
+ // The syntax of the proto file.
+ // The supported values are "proto2" and "proto3".
+ optional string syntax = 12;
+}
+
+// Describes a message type.
+message DescriptorProto {
+ optional string name = 1;
+
+ repeated FieldDescriptorProto field = 2;
+ repeated FieldDescriptorProto extension = 6;
+
+ repeated DescriptorProto nested_type = 3;
+ repeated EnumDescriptorProto enum_type = 4;
+
+ message ExtensionRange {
+ optional int32 start = 1;
+ optional int32 end = 2;
+ }
+ repeated ExtensionRange extension_range = 5;
+
+ repeated OneofDescriptorProto oneof_decl = 8;
+
+ optional MessageOptions options = 7;
+
+ // Range of reserved tag numbers. Reserved tag numbers may not be used by
+ // fields or extension ranges in the same message. Reserved ranges may
+ // not overlap.
+ message ReservedRange {
+ optional int32 start = 1; // Inclusive.
+ optional int32 end = 2; // Exclusive.
+ }
+ repeated ReservedRange reserved_range = 9;
+ // Reserved field names, which may not be used by fields in the same message.
+ // A given name may only be reserved once.
+ repeated string reserved_name = 10;
+}
+
+// Describes a field within a message.
+message FieldDescriptorProto {
+ enum Type {
+ // 0 is reserved for errors.
+ // Order is weird for historical reasons.
+ TYPE_DOUBLE = 1;
+ TYPE_FLOAT = 2;
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
+ // negative values are likely.
+ TYPE_INT64 = 3;
+ TYPE_UINT64 = 4;
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
+ // negative values are likely.
+ TYPE_INT32 = 5;
+ TYPE_FIXED64 = 6;
+ TYPE_FIXED32 = 7;
+ TYPE_BOOL = 8;
+ TYPE_STRING = 9;
+ TYPE_GROUP = 10; // Tag-delimited aggregate.
+ TYPE_MESSAGE = 11; // Length-delimited aggregate.
+
+ // New in version 2.
+ TYPE_BYTES = 12;
+ TYPE_UINT32 = 13;
+ TYPE_ENUM = 14;
+ TYPE_SFIXED32 = 15;
+ TYPE_SFIXED64 = 16;
+ TYPE_SINT32 = 17; // Uses ZigZag encoding.
+ TYPE_SINT64 = 18; // Uses ZigZag encoding.
+ };
+
+ enum Label {
+ // 0 is reserved for errors
+ LABEL_OPTIONAL = 1;
+ LABEL_REQUIRED = 2;
+ LABEL_REPEATED = 3;
+ // TODO(sanjay): Should we add LABEL_MAP?
+ };
+
+ optional string name = 1;
+ optional int32 number = 3;
+ optional Label label = 4;
+
+ // If type_name is set, this need not be set. If both this and type_name
+ // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
+ optional Type type = 5;
+
+ // For message and enum types, this is the name of the type. If the name
+ // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
+ // rules are used to find the type (i.e. first the nested types within this
+ // message are searched, then within the parent, on up to the root
+ // namespace).
+ optional string type_name = 6;
+
+ // For extensions, this is the name of the type being extended. It is
+ // resolved in the same manner as type_name.
+ optional string extendee = 2;
+
+ // For numeric types, contains the original text representation of the value.
+ // For booleans, "true" or "false".
+ // For strings, contains the default text contents (not escaped in any way).
+ // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
+ // TODO(kenton): Base-64 encode?
+ optional string default_value = 7;
+
+ // If set, gives the index of a oneof in the containing type's oneof_decl
+ // list. This field is a member of that oneof.
+ optional int32 oneof_index = 9;
+
+ // JSON name of this field. The value is set by protocol compiler. If the
+ // user has set a "json_name" option on this field, that option's value
+ // will be used. Otherwise, it's deduced from the field's name by converting
+ // it to camelCase.
+ optional string json_name = 10;
+
+ optional FieldOptions options = 8;
+}
+
+// Describes a oneof.
+message OneofDescriptorProto {
+ optional string name = 1;
+ optional OneofOptions options = 2;
+}
+
+// Describes an enum type.
+message EnumDescriptorProto {
+ optional string name = 1;
+
+ repeated EnumValueDescriptorProto value = 2;
+
+ optional EnumOptions options = 3;
+}
+
+// Describes a value within an enum.
+message EnumValueDescriptorProto {
+ optional string name = 1;
+ optional int32 number = 2;
+
+ optional EnumValueOptions options = 3;
+}
+
+// Describes a service.
+message ServiceDescriptorProto {
+ optional string name = 1;
+ repeated MethodDescriptorProto method = 2;
+
+ optional ServiceOptions options = 3;
+}
+
+// Describes a method of a service.
+message MethodDescriptorProto {
+ optional string name = 1;
+
+ // Input and output type names. These are resolved in the same way as
+ // FieldDescriptorProto.type_name, but must refer to a message type.
+ optional string input_type = 2;
+ optional string output_type = 3;
+
+ optional MethodOptions options = 4;
+
+ // Identifies if client streams multiple client messages
+ optional bool client_streaming = 5 [default=false];
+ // Identifies if server streams multiple server messages
+ optional bool server_streaming = 6 [default=false];
+}
+
+
+// ===================================================================
+// Options
+
+// Each of the definitions above may have "options" attached. These are
+// just annotations which may cause code to be generated slightly differently
+// or may contain hints for code that manipulates protocol messages.
+//
+// Clients may define custom options as extensions of the *Options messages.
+// These extensions may not yet be known at parsing time, so the parser cannot
+// store the values in them. Instead it stores them in a field in the *Options
+// message called uninterpreted_option. This field must have the same name
+// across all *Options messages. We then use this field to populate the
+// extensions when we build a descriptor, at which point all protos have been
+// parsed and so all extensions are known.
+//
+// Extension numbers for custom options may be chosen as follows:
+// * For options which will only be used within a single application or
+// organization, or for experimental options, use field numbers 50000
+// through 99999. It is up to you to ensure that you do not use the
+// same number for multiple options.
+// * For options which will be published and used publicly by multiple
+// independent entities, e-mail protobuf-global-extension-registry@google.com
+// to reserve extension numbers. Simply provide your project name (e.g.
+// Objective-C plugin) and your project website (if available) -- there's no
+// need to explain how you intend to use them. Usually you only need one
+// extension number. You can declare multiple options with only one extension
+// number by putting them in a sub-message. See the Custom Options section of
+// the docs for examples:
+// https://developers.google.com/protocol-buffers/docs/proto#options
+// If this turns out to be popular, a web service will be set up
+// to automatically assign option numbers.
+
+
+message FileOptions {
+
+ // Sets the Java package where classes generated from this .proto will be
+ // placed. By default, the proto package is used, but this is often
+ // inappropriate because proto packages do not normally start with backwards
+ // domain names.
+ optional string java_package = 1;
+
+
+ // If set, all the classes from the .proto file are wrapped in a single
+ // outer class with the given name. This applies to both Proto1
+ // (equivalent to the old "--one_java_file" option) and Proto2 (where
+ // a .proto always translates to a single class, but you may want to
+ // explicitly choose the class name).
+ optional string java_outer_classname = 8;
+
+ // If set true, then the Java code generator will generate a separate .java
+ // file for each top-level message, enum, and service defined in the .proto
+ // file. Thus, these types will *not* be nested inside the outer class
+ // named by java_outer_classname. However, the outer class will still be
+ // generated to contain the file's getDescriptor() method as well as any
+ // top-level extensions defined in the file.
+ optional bool java_multiple_files = 10 [default=false];
+
+ // If set true, then the Java code generator will generate equals() and
+ // hashCode() methods for all messages defined in the .proto file.
+ // This increases generated code size, potentially substantially for large
+ // protos, which may harm a memory-constrained application.
+ // - In the full runtime this is a speed optimization, as the
+ // AbstractMessage base class includes reflection-based implementations of
+ // these methods.
+ // - In the lite runtime, setting this option changes the semantics of
+ // equals() and hashCode() to more closely match those of the full runtime;
+ // the generated methods compute their results based on field values rather
+ // than object identity. (Implementations should not assume that hashcodes
+ // will be consistent across runtimes or versions of the protocol compiler.)
+ optional bool java_generate_equals_and_hash = 20 [default=false];
+
+ // If set true, then the Java2 code generator will generate code that
+ // throws an exception whenever an attempt is made to assign a non-UTF-8
+ // byte sequence to a string field.
+ // Message reflection will do the same.
+ // However, an extension field still accepts non-UTF-8 byte sequences.
+ // This option has no effect on when used with the lite runtime.
+ optional bool java_string_check_utf8 = 27 [default=false];
+
+
+ // Generated classes can be optimized for speed or code size.
+ enum OptimizeMode {
+ SPEED = 1; // Generate complete code for parsing, serialization,
+ // etc.
+ CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
+ LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
+ }
+ optional OptimizeMode optimize_for = 9 [default=SPEED];
+
+ // Sets the Go package where structs generated from this .proto will be
+ // placed. If omitted, the Go package will be derived from the following:
+ // - The basename of the package import path, if provided.
+ // - Otherwise, the package statement in the .proto file, if present.
+ // - Otherwise, the basename of the .proto file, without extension.
+ optional string go_package = 11;
+
+
+
+ // Should generic services be generated in each language? "Generic" services
+ // are not specific to any particular RPC system. They are generated by the
+ // main code generators in each language (without additional plugins).
+ // Generic services were the only kind of service generation supported by
+ // early versions of google.protobuf.
+ //
+ // Generic services are now considered deprecated in favor of using plugins
+ // that generate code specific to your particular RPC system. Therefore,
+ // these default to false. Old code which depends on generic services should
+ // explicitly set them to true.
+ optional bool cc_generic_services = 16 [default=false];
+ optional bool java_generic_services = 17 [default=false];
+ optional bool py_generic_services = 18 [default=false];
+
+ // Is this file deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for everything in the file, or it will be completely ignored; in the very
+ // least, this is a formalization for deprecating files.
+ optional bool deprecated = 23 [default=false];
+
+ // Enables the use of arenas for the proto messages in this file. This applies
+ // only to generated classes for C++.
+ optional bool cc_enable_arenas = 31 [default=false];
+
+
+ // Sets the objective c class prefix which is prepended to all objective c
+ // generated classes from this .proto. There is no default.
+ optional string objc_class_prefix = 36;
+
+ // Namespace for generated classes; defaults to the package.
+ optional string csharp_namespace = 37;
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+
+ //reserved 38;
+}
+
+message MessageOptions {
+ // Set true to use the old proto1 MessageSet wire format for extensions.
+ // This is provided for backwards-compatibility with the MessageSet wire
+ // format. You should not use this for any other reason: It's less
+ // efficient, has fewer features, and is more complicated.
+ //
+ // The message must be defined exactly as follows:
+ // message Foo {
+ // option message_set_wire_format = true;
+ // extensions 4 to max;
+ // }
+ // Note that the message cannot have any defined fields; MessageSets only
+ // have extensions.
+ //
+ // All extensions of your type must be singular messages; e.g. they cannot
+ // be int32s, enums, or repeated messages.
+ //
+ // Because this is an option, the above two restrictions are not enforced by
+ // the protocol compiler.
+ optional bool message_set_wire_format = 1 [default=false];
+
+ // Disables the generation of the standard "descriptor()" accessor, which can
+ // conflict with a field of the same name. This is meant to make migration
+ // from proto1 easier; new code should avoid fields named "descriptor".
+ optional bool no_standard_descriptor_accessor = 2 [default=false];
+
+ // Is this message deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the message, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating messages.
+ optional bool deprecated = 3 [default=false];
+
+ // Whether the message is an automatically generated map entry type for the
+ // maps field.
+ //
+ // For maps fields:
+ // map<KeyType, ValueType> map_field = 1;
+ // The parsed descriptor looks like:
+ // message MapFieldEntry {
+ // option map_entry = true;
+ // optional KeyType key = 1;
+ // optional ValueType value = 2;
+ // }
+ // repeated MapFieldEntry map_field = 1;
+ //
+ // Implementations may choose not to generate the map_entry=true message, but
+ // use a native map in the target language to hold the keys and values.
+ // The reflection APIs in such implementions still need to work as
+ // if the field is a repeated message field.
+ //
+ // NOTE: Do not set the option in .proto files. Always use the maps syntax
+ // instead. The option should only be implicitly set by the proto compiler
+ // parser.
+ optional bool map_entry = 7;
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message FieldOptions {
+ // The ctype option instructs the C++ code generator to use a different
+ // representation of the field than it normally would. See the specific
+ // options below. This option is not yet implemented in the open source
+ // release -- sorry, we'll try to include it in a future version!
+ optional CType ctype = 1 [default = STRING];
+ enum CType {
+ // Default mode.
+ STRING = 0;
+
+ CORD = 1;
+
+ STRING_PIECE = 2;
+ }
+ // The packed option can be enabled for repeated primitive fields to enable
+ // a more efficient representation on the wire. Rather than repeatedly
+ // writing the tag and type for each element, the entire array is encoded as
+ // a single length-delimited blob. In proto3, only explicit setting it to
+ // false will avoid using packed encoding.
+ optional bool packed = 2;
+
+
+ // The jstype option determines the JavaScript type used for values of the
+ // field. The option is permitted only for 64 bit integral and fixed types
+ // (int64, uint64, sint64, fixed64, sfixed64). By default these types are
+ // represented as JavaScript strings. This avoids loss of precision that can
+ // happen when a large value is converted to a floating point JavaScript
+ // numbers. Specifying JS_NUMBER for the jstype causes the generated
+ // JavaScript code to use the JavaScript "number" type instead of strings.
+ // This option is an enum to permit additional types to be added,
+ // e.g. goog.math.Integer.
+ optional JSType jstype = 6 [default = JS_NORMAL];
+ enum JSType {
+ // Use the default type.
+ JS_NORMAL = 0;
+
+ // Use JavaScript strings.
+ JS_STRING = 1;
+
+ // Use JavaScript numbers.
+ JS_NUMBER = 2;
+ }
+
+ // Should this field be parsed lazily? Lazy applies only to message-type
+ // fields. It means that when the outer message is initially parsed, the
+ // inner message's contents will not be parsed but instead stored in encoded
+ // form. The inner message will actually be parsed when it is first accessed.
+ //
+ // This is only a hint. Implementations are free to choose whether to use
+ // eager or lazy parsing regardless of the value of this option. However,
+ // setting this option true suggests that the protocol author believes that
+ // using lazy parsing on this field is worth the additional bookkeeping
+ // overhead typically needed to implement it.
+ //
+ // This option does not affect the public interface of any generated code;
+ // all method signatures remain the same. Furthermore, thread-safety of the
+ // interface is not affected by this option; const methods remain safe to
+ // call from multiple threads concurrently, while non-const methods continue
+ // to require exclusive access.
+ //
+ //
+ // Note that implementations may choose not to check required fields within
+ // a lazy sub-message. That is, calling IsInitialized() on the outher message
+ // may return true even if the inner message has missing required fields.
+ // This is necessary because otherwise the inner message would have to be
+ // parsed in order to perform the check, defeating the purpose of lazy
+ // parsing. An implementation which chooses not to check required fields
+ // must be consistent about it. That is, for any particular sub-message, the
+ // implementation must either *always* check its required fields, or *never*
+ // check its required fields, regardless of whether or not the message has
+ // been parsed.
+ optional bool lazy = 5 [default=false];
+
+ // Is this field deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for accessors, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating fields.
+ optional bool deprecated = 3 [default=false];
+
+ // For Google-internal migration only. Do not use.
+ optional bool weak = 10 [default=false];
+
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message OneofOptions {
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message EnumOptions {
+
+ // Set this option to true to allow mapping different tag names to the same
+ // value.
+ optional bool allow_alias = 2;
+
+ // Is this enum deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating enums.
+ optional bool deprecated = 3 [default=false];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message EnumValueOptions {
+ // Is this enum value deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum value, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating enum values.
+ optional bool deprecated = 1 [default=false];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message ServiceOptions {
+
+ // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
+ // framework. We apologize for hoarding these numbers to ourselves, but
+ // we were already using them long before we decided to release Protocol
+ // Buffers.
+
+ // Is this service deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the service, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating services.
+ optional bool deprecated = 33 [default=false];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message MethodOptions {
+
+ // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
+ // framework. We apologize for hoarding these numbers to ourselves, but
+ // we were already using them long before we decided to release Protocol
+ // Buffers.
+
+ // Is this method deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the method, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating methods.
+ optional bool deprecated = 33 [default=false];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+
+// A message representing a option the parser does not recognize. This only
+// appears in options protos created by the compiler::Parser class.
+// DescriptorPool resolves these when building Descriptor objects. Therefore,
+// options protos in descriptor objects (e.g. returned by Descriptor::options(),
+// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
+// in them.
+message UninterpretedOption {
+ // The name of the uninterpreted option. Each string represents a segment in
+ // a dot-separated name. is_extension is true iff a segment represents an
+ // extension (denoted with parentheses in options specs in .proto files).
+ // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
+ // "foo.(bar.baz).qux".
+ message NamePart {
+ required string name_part = 1;
+ required bool is_extension = 2;
+ }
+ repeated NamePart name = 2;
+
+ // The value of the uninterpreted option, in whatever type the tokenizer
+ // identified it as during parsing. Exactly one of these should be set.
+ optional string identifier_value = 3;
+ optional uint64 positive_int_value = 4;
+ optional int64 negative_int_value = 5;
+ optional double double_value = 6;
+ optional bytes string_value = 7;
+ optional string aggregate_value = 8;
+}
+
+// ===================================================================
+// Optional source code info
+
+// Encapsulates information about the original source file from which a
+// FileDescriptorProto was generated.
+message SourceCodeInfo {
+ // A Location identifies a piece of source code in a .proto file which
+ // corresponds to a particular definition. This information is intended
+ // to be useful to IDEs, code indexers, documentation generators, and similar
+ // tools.
+ //
+ // For example, say we have a file like:
+ // message Foo {
+ // optional string foo = 1;
+ // }
+ // Let's look at just the field definition:
+ // optional string foo = 1;
+ // ^ ^^ ^^ ^ ^^^
+ // a bc de f ghi
+ // We have the following locations:
+ // span path represents
+ // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
+ // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
+ // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
+ // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
+ // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
+ //
+ // Notes:
+ // - A location may refer to a repeated field itself (i.e. not to any
+ // particular index within it). This is used whenever a set of elements are
+ // logically enclosed in a single code segment. For example, an entire
+ // extend block (possibly containing multiple extension definitions) will
+ // have an outer location whose path refers to the "extensions" repeated
+ // field without an index.
+ // - Multiple locations may have the same path. This happens when a single
+ // logical declaration is spread out across multiple places. The most
+ // obvious example is the "extend" block again -- there may be multiple
+ // extend blocks in the same scope, each of which will have the same path.
+ // - A location's span is not always a subset of its parent's span. For
+ // example, the "extendee" of an extension declaration appears at the
+ // beginning of the "extend" block and is shared by all extensions within
+ // the block.
+ // - Just because a location's span is a subset of some other location's span
+ // does not mean that it is a descendent. For example, a "group" defines
+ // both a type and a field in a single declaration. Thus, the locations
+ // corresponding to the type and field and their components will overlap.
+ // - Code which tries to interpret locations should probably be designed to
+ // ignore those that it doesn't understand, as more types of locations could
+ // be recorded in the future.
+ repeated Location location = 1;
+ message Location {
+ // Identifies which part of the FileDescriptorProto was defined at this
+ // location.
+ //
+ // Each element is a field number or an index. They form a path from
+ // the root FileDescriptorProto to the place where the definition. For
+ // example, this path:
+ // [ 4, 3, 2, 7, 1 ]
+ // refers to:
+ // file.message_type(3) // 4, 3
+ // .field(7) // 2, 7
+ // .name() // 1
+ // This is because FileDescriptorProto.message_type has field number 4:
+ // repeated DescriptorProto message_type = 4;
+ // and DescriptorProto.field has field number 2:
+ // repeated FieldDescriptorProto field = 2;
+ // and FieldDescriptorProto.name has field number 1:
+ // optional string name = 1;
+ //
+ // Thus, the above path gives the location of a field name. If we removed
+ // the last element:
+ // [ 4, 3, 2, 7 ]
+ // this path refers to the whole field declaration (from the beginning
+ // of the label to the terminating semicolon).
+ repeated int32 path = 1 [packed=true];
+
+ // Always has exactly three or four elements: start line, start column,
+ // end line (optional, otherwise assumed same as start line), end column.
+ // These are packed into a single field for efficiency. Note that line
+ // and column numbers are zero-based -- typically you will want to add
+ // 1 to each before displaying to a user.
+ repeated int32 span = 2 [packed=true];
+
+ // If this SourceCodeInfo represents a complete declaration, these are any
+ // comments appearing before and after the declaration which appear to be
+ // attached to the declaration.
+ //
+ // A series of line comments appearing on consecutive lines, with no other
+ // tokens appearing on those lines, will be treated as a single comment.
+ //
+ // leading_detached_comments will keep paragraphs of comments that appear
+ // before (but not connected to) the current element. Each paragraph,
+ // separated by empty lines, will be one comment element in the repeated
+ // field.
+ //
+ // Only the comment content is provided; comment markers (e.g. //) are
+ // stripped out. For block comments, leading whitespace and an asterisk
+ // will be stripped from the beginning of each line other than the first.
+ // Newlines are included in the output.
+ //
+ // Examples:
+ //
+ // optional int32 foo = 1; // Comment attached to foo.
+ // // Comment attached to bar.
+ // optional int32 bar = 2;
+ //
+ // optional string baz = 3;
+ // // Comment attached to baz.
+ // // Another line attached to baz.
+ //
+ // // Comment attached to qux.
+ // //
+ // // Another line attached to qux.
+ // optional double qux = 4;
+ //
+ // // Detached comment for corge. This is not leading or trailing comments
+ // // to qux or corge because there are blank lines separating it from
+ // // both.
+ //
+ // // Detached comment for corge paragraph 2.
+ //
+ // optional string corge = 5;
+ // /* Block comment attached
+ // * to corge. Leading asterisks
+ // * will be removed. */
+ // /* Block comment attached to
+ // * grault. */
+ // optional int32 grault = 6;
+ //
+ // // ignored detached comments.
+ optional string leading_comments = 3;
+ optional string trailing_comments = 4;
+ repeated string leading_detached_comments = 6;
+ }
+}
+
+// Describes the relationship between generated code and its original source
+// file. A GeneratedCodeInfo message is associated with only one generated
+// source file, but may contain references to different source .proto files.
+message GeneratedCodeInfo {
+ // An Annotation connects some span of text in generated code to an element
+ // of its generating .proto file.
+ repeated Annotation annotation = 1;
+ message Annotation {
+ // Identifies the element in the original source .proto file. This field
+ // is formatted the same as SourceCodeInfo.Location.path.
+ repeated int32 path = 1 [packed=true];
+
+ // Identifies the filesystem path to the original source .proto.
+ optional string source_file = 2;
+
+ // Identifies the starting offset in bytes in the generated code
+ // that relates to the identified object.
+ optional int32 begin = 3;
+
+ // Identifies the ending offset in bytes in the generated code that
+ // relates to the identified offset. The end offset should be one past
+ // the last relevant byte (so the length of the text = end - begin).
+ optional int32 end = 4;
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/duration.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/duration.proto
new file mode 100644
index 0000000..c4359db
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/duration.proto
@@ -0,0 +1,98 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option go_package = "types";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "DurationProto";
+option java_multiple_files = true;
+option java_generate_equals_and_hash = true;
+option objc_class_prefix = "GPB";
+
+// A Duration represents a signed, fixed-length span of time represented
+// as a count of seconds and fractions of seconds at nanosecond
+// resolution. It is independent of any calendar and concepts like "day"
+// or "month". It is related to Timestamp in that the difference between
+// two Timestamp values is a Duration and it can be added or subtracted
+// from a Timestamp. Range is approximately +-10,000 years.
+//
+// Example 1: Compute Duration from two Timestamps in pseudo code.
+//
+// Timestamp start = ...;
+// Timestamp end = ...;
+// Duration duration = ...;
+//
+// duration.seconds = end.seconds - start.seconds;
+// duration.nanos = end.nanos - start.nanos;
+//
+// if (duration.seconds < 0 && duration.nanos > 0) {
+// duration.seconds += 1;
+// duration.nanos -= 1000000000;
+// } else if (durations.seconds > 0 && duration.nanos < 0) {
+// duration.seconds -= 1;
+// duration.nanos += 1000000000;
+// }
+//
+// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
+//
+// Timestamp start = ...;
+// Duration duration = ...;
+// Timestamp end = ...;
+//
+// end.seconds = start.seconds + duration.seconds;
+// end.nanos = start.nanos + duration.nanos;
+//
+// if (end.nanos < 0) {
+// end.seconds -= 1;
+// end.nanos += 1000000000;
+// } else if (end.nanos >= 1000000000) {
+// end.seconds += 1;
+// end.nanos -= 1000000000;
+// }
+//
+//
+message Duration {
+
+ // Signed seconds of the span of time. Must be from -315,576,000,000
+ // to +315,576,000,000 inclusive.
+ int64 seconds = 1;
+
+ // Signed fractions of a second at nanosecond resolution of the span
+ // of time. Durations less than one second are represented with a 0
+ // `seconds` field and a positive or negative `nanos` field. For durations
+ // of one second or more, a non-zero value for the `nanos` field must be
+ // of the same sign as the `seconds` field. Must be from -999,999,999
+ // to +999,999,999 inclusive.
+ int32 nanos = 2;
+}
diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/empty.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/empty.proto
new file mode 100644
index 0000000..61a574b
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/empty.proto
@@ -0,0 +1,53 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option go_package = "types";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "EmptyProto";
+option java_multiple_files = true;
+option java_generate_equals_and_hash = true;
+option objc_class_prefix = "GPB";
+option cc_enable_arenas = true;
+
+// A generic empty message that you can re-use to avoid defining duplicated
+// empty messages in your APIs. A typical example is to use it as the request
+// or the response type of an API method. For instance:
+//
+// service Foo {
+// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+// }
+//
+// The JSON representation for `Empty` is empty JSON object `{}`.
+message Empty {}
diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/field_mask.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/field_mask.proto
new file mode 100644
index 0000000..fd25288
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/field_mask.proto
@@ -0,0 +1,246 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "types";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "FieldMaskProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+option java_generate_equals_and_hash = true;
+
+// `FieldMask` represents a set of symbolic field paths, for example:
+//
+// paths: "f.a"
+// paths: "f.b.d"
+//
+// Here `f` represents a field in some root message, `a` and `b`
+// fields in the message found in `f`, and `d` a field found in the
+// message in `f.b`.
+//
+// Field masks are used to specify a subset of fields that should be
+// returned by a get operation or modified by an update operation.
+// Field masks also have a custom JSON encoding (see below).
+//
+// # Field Masks in Projections
+//
+// When used in the context of a projection, a response message or
+// sub-message is filtered by the API to only contain those fields as
+// specified in the mask. For example, if the mask in the previous
+// example is applied to a response message as follows:
+//
+// f {
+// a : 22
+// b {
+// d : 1
+// x : 2
+// }
+// y : 13
+// }
+// z: 8
+//
+// The result will not contain specific values for fields x,y and z
+// (their value will be set to the default, and omitted in proto text
+// output):
+//
+//
+// f {
+// a : 22
+// b {
+// d : 1
+// }
+// }
+//
+// A repeated field is not allowed except at the last position of a
+// field mask.
+//
+// If a FieldMask object is not present in a get operation, the
+// operation applies to all fields (as if a FieldMask of all fields
+// had been specified).
+//
+// Note that a field mask does not necessarily apply to the
+// top-level response message. In case of a REST get operation, the
+// field mask applies directly to the response, but in case of a REST
+// list operation, the mask instead applies to each individual message
+// in the returned resource list. In case of a REST custom method,
+// other definitions may be used. Where the mask applies will be
+// clearly documented together with its declaration in the API. In
+// any case, the effect on the returned resource/resources is required
+// behavior for APIs.
+//
+// # Field Masks in Update Operations
+//
+// A field mask in update operations specifies which fields of the
+// targeted resource are going to be updated. The API is required
+// to only change the values of the fields as specified in the mask
+// and leave the others untouched. If a resource is passed in to
+// describe the updated values, the API ignores the values of all
+// fields not covered by the mask.
+//
+// If a repeated field is specified for an update operation, the existing
+// repeated values in the target resource will be overwritten by the new values.
+// Note that a repeated field is only allowed in the last position of a field
+// mask.
+//
+// If a sub-message is specified in the last position of the field mask for an
+// update operation, then the existing sub-message in the target resource is
+// overwritten. Given the target message:
+//
+// f {
+// b {
+// d : 1
+// x : 2
+// }
+// c : 1
+// }
+//
+// And an update message:
+//
+// f {
+// b {
+// d : 10
+// }
+// }
+//
+// then if the field mask is:
+//
+// paths: "f.b"
+//
+// then the result will be:
+//
+// f {
+// b {
+// d : 10
+// }
+// c : 1
+// }
+//
+// However, if the update mask was:
+//
+// paths: "f.b.d"
+//
+// then the result would be:
+//
+// f {
+// b {
+// d : 10
+// x : 2
+// }
+// c : 1
+// }
+//
+// In order to reset a field's value to the default, the field must
+// be in the mask and set to the default value in the provided resource.
+// Hence, in order to reset all fields of a resource, provide a default
+// instance of the resource and set all fields in the mask, or do
+// not provide a mask as described below.
+//
+// If a field mask is not present on update, the operation applies to
+// all fields (as if a field mask of all fields has been specified).
+// Note that in the presence of schema evolution, this may mean that
+// fields the client does not know and has therefore not filled into
+// the request will be reset to their default. If this is unwanted
+// behavior, a specific service may require a client to always specify
+// a field mask, producing an error if not.
+//
+// As with get operations, the location of the resource which
+// describes the updated values in the request message depends on the
+// operation kind. In any case, the effect of the field mask is
+// required to be honored by the API.
+//
+// ## Considerations for HTTP REST
+//
+// The HTTP kind of an update operation which uses a field mask must
+// be set to PATCH instead of PUT in order to satisfy HTTP semantics
+// (PUT must only be used for full updates).
+//
+// # JSON Encoding of Field Masks
+//
+// In JSON, a field mask is encoded as a single string where paths are
+// separated by a comma. Fields name in each path are converted
+// to/from lower-camel naming conventions.
+//
+// As an example, consider the following message declarations:
+//
+// message Profile {
+// User user = 1;
+// Photo photo = 2;
+// }
+// message User {
+// string display_name = 1;
+// string address = 2;
+// }
+//
+// In proto a field mask for `Profile` may look as such:
+//
+// mask {
+// paths: "user.display_name"
+// paths: "photo"
+// }
+//
+// In JSON, the same mask is represented as below:
+//
+// {
+// mask: "user.displayName,photo"
+// }
+//
+// # Field Masks and Oneof Fields
+//
+// Field masks treat fields in oneofs just as regular fields. Consider the
+// following message:
+//
+// message SampleMessage {
+// oneof test_oneof {
+// string name = 4;
+// SubMessage sub_message = 9;
+// }
+// }
+//
+// The field mask can be:
+//
+// mask {
+// paths: "name"
+// }
+//
+// Or:
+//
+// mask {
+// paths: "sub_message"
+// }
+//
+// Note that oneof type names ("test_oneof" in this case) cannot be used in
+// paths.
+message FieldMask {
+ // The set of field mask paths.
+ repeated string paths = 1;
+}
diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/struct.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/struct.proto
new file mode 100644
index 0000000..27fdb91
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/struct.proto
@@ -0,0 +1,96 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option go_package = "types";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "StructProto";
+option java_multiple_files = true;
+option java_generate_equals_and_hash = true;
+option objc_class_prefix = "GPB";
+
+
+// `Struct` represents a structured data value, consisting of fields
+// which map to dynamically typed values. In some languages, `Struct`
+// might be supported by a native representation. For example, in
+// scripting languages like JS a struct is represented as an
+// object. The details of that representation are described together
+// with the proto support for the language.
+//
+// The JSON representation for `Struct` is JSON object.
+message Struct {
+ // Unordered map of dynamically typed values.
+ map<string, Value> fields = 1;
+}
+
+// `Value` represents a dynamically typed value which can be either
+// null, a number, a string, a boolean, a recursive struct value, or a
+// list of values. A producer of value is expected to set one of that
+// variants, absence of any variant indicates an error.
+//
+// The JSON representation for `Value` is JSON value.
+message Value {
+ // The kind of value.
+ oneof kind {
+ // Represents a null value.
+ NullValue null_value = 1;
+ // Represents a double value.
+ double number_value = 2;
+ // Represents a string value.
+ string string_value = 3;
+ // Represents a boolean value.
+ bool bool_value = 4;
+ // Represents a structured value.
+ Struct struct_value = 5;
+ // Represents a repeated `Value`.
+ ListValue list_value = 6;
+ }
+}
+
+// `NullValue` is a singleton enumeration to represent the null value for the
+// `Value` type union.
+//
+// The JSON representation for `NullValue` is JSON `null`.
+enum NullValue {
+ // Null value.
+ NULL_VALUE = 0;
+}
+
+// `ListValue` is a wrapper around a repeated field of values.
+//
+// The JSON representation for `ListValue` is JSON array.
+message ListValue {
+ // Repeated field of dynamically typed values.
+ repeated Value values = 1;
+}
diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/timestamp.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/timestamp.proto
new file mode 100644
index 0000000..c85024a
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/timestamp.proto
@@ -0,0 +1,111 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
+option go_package = "types";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "TimestampProto";
+option java_multiple_files = true;
+option java_generate_equals_and_hash = true;
+option objc_class_prefix = "GPB";
+
+// A Timestamp represents a point in time independent of any time zone
+// or calendar, represented as seconds and fractions of seconds at
+// nanosecond resolution in UTC Epoch time. It is encoded using the
+// Proleptic Gregorian Calendar which extends the Gregorian calendar
+// backwards to year one. It is encoded assuming all minutes are 60
+// seconds long, i.e. leap seconds are "smeared" so that no leap second
+// table is needed for interpretation. Range is from
+// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
+// By restricting to that range, we ensure that we can convert to
+// and from RFC 3339 date strings.
+// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
+//
+// Example 1: Compute Timestamp from POSIX `time()`.
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(time(NULL));
+// timestamp.set_nanos(0);
+//
+// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
+//
+// struct timeval tv;
+// gettimeofday(&tv, NULL);
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(tv.tv_sec);
+// timestamp.set_nanos(tv.tv_usec * 1000);
+//
+// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
+//
+// FILETIME ft;
+// GetSystemTimeAsFileTime(&ft);
+// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+//
+// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
+// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
+// Timestamp timestamp;
+// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
+// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
+//
+// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
+//
+// long millis = System.currentTimeMillis();
+//
+// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
+// .setNanos((int) ((millis % 1000) * 1000000)).build();
+//
+//
+// Example 5: Compute Timestamp from current time in Python.
+//
+// now = time.time()
+// seconds = int(now)
+// nanos = int((now - seconds) * 10**9)
+// timestamp = Timestamp(seconds=seconds, nanos=nanos)
+//
+//
+message Timestamp {
+
+ // Represents seconds of UTC time since Unix epoch
+ // 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to
+ // 9999-12-31T23:59:59Z inclusive.
+ int64 seconds = 1;
+
+ // Non-negative fractions of a second at nanosecond resolution. Negative
+ // second values with fractions must still have non-negative nanos values
+ // that count forward in time. Must be from 0 to 999,999,999
+ // inclusive.
+ int32 nanos = 2;
+}
diff --git a/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/wrappers.proto b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/wrappers.proto
new file mode 100644
index 0000000..f685dc0
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protobuf/google/protobuf/wrappers.proto
@@ -0,0 +1,119 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+// Wrappers for primitive (non-message) types. These types are useful
+// for embedding primitives in the `google.protobuf.Any` type and for places
+// where we need to distinguish between the absence of a primitive
+// typed field and its default value.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
+option go_package = "types";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "WrappersProto";
+option java_multiple_files = true;
+option java_generate_equals_and_hash = true;
+option objc_class_prefix = "GPB";
+
+// Wrapper message for `double`.
+//
+// The JSON representation for `DoubleValue` is JSON number.
+message DoubleValue {
+ // The double value.
+ double value = 1;
+}
+
+// Wrapper message for `float`.
+//
+// The JSON representation for `FloatValue` is JSON number.
+message FloatValue {
+ // The float value.
+ float value = 1;
+}
+
+// Wrapper message for `int64`.
+//
+// The JSON representation for `Int64Value` is JSON string.
+message Int64Value {
+ // The int64 value.
+ int64 value = 1;
+}
+
+// Wrapper message for `uint64`.
+//
+// The JSON representation for `UInt64Value` is JSON string.
+message UInt64Value {
+ // The uint64 value.
+ uint64 value = 1;
+}
+
+// Wrapper message for `int32`.
+//
+// The JSON representation for `Int32Value` is JSON number.
+message Int32Value {
+ // The int32 value.
+ int32 value = 1;
+}
+
+// Wrapper message for `uint32`.
+//
+// The JSON representation for `UInt32Value` is JSON number.
+message UInt32Value {
+ // The uint32 value.
+ uint32 value = 1;
+}
+
+// Wrapper message for `bool`.
+//
+// The JSON representation for `BoolValue` is JSON `true` and `false`.
+message BoolValue {
+ // The bool value.
+ bool value = 1;
+}
+
+// Wrapper message for `string`.
+//
+// The JSON representation for `StringValue` is JSON string.
+message StringValue {
+ // The string value.
+ string value = 1;
+}
+
+// Wrapper message for `bytes`.
+//
+// The JSON representation for `BytesValue` is JSON string.
+message BytesValue {
+ // The bytes value.
+ bytes value = 1;
+}
diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go
new file mode 100644
index 0000000..a85bf19
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go
@@ -0,0 +1,118 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// Package descriptor provides functions for obtaining protocol buffer
+// descriptors for generated Go types.
+//
+// These functions cannot go in package proto because they depend on the
+// generated protobuf descriptor messages, which themselves depend on proto.
+package descriptor
+
+import (
+ "bytes"
+ "compress/gzip"
+ "fmt"
+ "io/ioutil"
+
+ "github.com/gogo/protobuf/proto"
+)
+
+// extractFile extracts a FileDescriptorProto from a gzip'd buffer.
+func extractFile(gz []byte) (*FileDescriptorProto, error) {
+ r, err := gzip.NewReader(bytes.NewReader(gz))
+ if err != nil {
+ return nil, fmt.Errorf("failed to open gzip reader: %v", err)
+ }
+ defer r.Close()
+
+ b, err := ioutil.ReadAll(r)
+ if err != nil {
+ return nil, fmt.Errorf("failed to uncompress descriptor: %v", err)
+ }
+
+ fd := new(FileDescriptorProto)
+ if err := proto.Unmarshal(b, fd); err != nil {
+ return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err)
+ }
+
+ return fd, nil
+}
+
+// Message is a proto.Message with a method to return its descriptor.
+//
+// Message types generated by the protocol compiler always satisfy
+// the Message interface.
+type Message interface {
+ proto.Message
+ Descriptor() ([]byte, []int)
+}
+
+// ForMessage returns a FileDescriptorProto and a DescriptorProto from within it
+// describing the given message.
+func ForMessage(msg Message) (fd *FileDescriptorProto, md *DescriptorProto) {
+ gz, path := msg.Descriptor()
+ fd, err := extractFile(gz)
+ if err != nil {
+ panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err))
+ }
+
+ md = fd.MessageType[path[0]]
+ for _, i := range path[1:] {
+ md = md.NestedType[i]
+ }
+ return fd, md
+}
+
+// Is this field a scalar numeric type?
+func (field *FieldDescriptorProto) IsScalar() bool {
+ if field.Type == nil {
+ return false
+ }
+ switch *field.Type {
+ case FieldDescriptorProto_TYPE_DOUBLE,
+ FieldDescriptorProto_TYPE_FLOAT,
+ FieldDescriptorProto_TYPE_INT64,
+ FieldDescriptorProto_TYPE_UINT64,
+ FieldDescriptorProto_TYPE_INT32,
+ FieldDescriptorProto_TYPE_FIXED64,
+ FieldDescriptorProto_TYPE_FIXED32,
+ FieldDescriptorProto_TYPE_BOOL,
+ FieldDescriptorProto_TYPE_UINT32,
+ FieldDescriptorProto_TYPE_ENUM,
+ FieldDescriptorProto_TYPE_SFIXED32,
+ FieldDescriptorProto_TYPE_SFIXED64,
+ FieldDescriptorProto_TYPE_SINT32,
+ FieldDescriptorProto_TYPE_SINT64:
+ return true
+ default:
+ return false
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go
new file mode 100644
index 0000000..1427b03
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go
@@ -0,0 +1,2088 @@
+// Code generated by protoc-gen-gogo.
+// source: descriptor.proto
+// DO NOT EDIT!
+
+/*
+Package descriptor is a generated protocol buffer package.
+
+It is generated from these files:
+ descriptor.proto
+
+It has these top-level messages:
+ FileDescriptorSet
+ FileDescriptorProto
+ DescriptorProto
+ FieldDescriptorProto
+ OneofDescriptorProto
+ EnumDescriptorProto
+ EnumValueDescriptorProto
+ ServiceDescriptorProto
+ MethodDescriptorProto
+ FileOptions
+ MessageOptions
+ FieldOptions
+ OneofOptions
+ EnumOptions
+ EnumValueOptions
+ ServiceOptions
+ MethodOptions
+ UninterpretedOption
+ SourceCodeInfo
+ GeneratedCodeInfo
+*/
+package descriptor
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+type FieldDescriptorProto_Type int32
+
+const (
+ // 0 is reserved for errors.
+ // Order is weird for historical reasons.
+ FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1
+ FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
+ // negative values are likely.
+ FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3
+ FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
+ // negative values are likely.
+ FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5
+ FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6
+ FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7
+ FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8
+ FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9
+ FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10
+ FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11
+ // New in version 2.
+ FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12
+ FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13
+ FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14
+ FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15
+ FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16
+ FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17
+ FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18
+)
+
+var FieldDescriptorProto_Type_name = map[int32]string{
+ 1: "TYPE_DOUBLE",
+ 2: "TYPE_FLOAT",
+ 3: "TYPE_INT64",
+ 4: "TYPE_UINT64",
+ 5: "TYPE_INT32",
+ 6: "TYPE_FIXED64",
+ 7: "TYPE_FIXED32",
+ 8: "TYPE_BOOL",
+ 9: "TYPE_STRING",
+ 10: "TYPE_GROUP",
+ 11: "TYPE_MESSAGE",
+ 12: "TYPE_BYTES",
+ 13: "TYPE_UINT32",
+ 14: "TYPE_ENUM",
+ 15: "TYPE_SFIXED32",
+ 16: "TYPE_SFIXED64",
+ 17: "TYPE_SINT32",
+ 18: "TYPE_SINT64",
+}
+var FieldDescriptorProto_Type_value = map[string]int32{
+ "TYPE_DOUBLE": 1,
+ "TYPE_FLOAT": 2,
+ "TYPE_INT64": 3,
+ "TYPE_UINT64": 4,
+ "TYPE_INT32": 5,
+ "TYPE_FIXED64": 6,
+ "TYPE_FIXED32": 7,
+ "TYPE_BOOL": 8,
+ "TYPE_STRING": 9,
+ "TYPE_GROUP": 10,
+ "TYPE_MESSAGE": 11,
+ "TYPE_BYTES": 12,
+ "TYPE_UINT32": 13,
+ "TYPE_ENUM": 14,
+ "TYPE_SFIXED32": 15,
+ "TYPE_SFIXED64": 16,
+ "TYPE_SINT32": 17,
+ "TYPE_SINT64": 18,
+}
+
+func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type {
+ p := new(FieldDescriptorProto_Type)
+ *p = x
+ return p
+}
+func (x FieldDescriptorProto_Type) String() string {
+ return proto.EnumName(FieldDescriptorProto_Type_name, int32(x))
+}
+func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type")
+ if err != nil {
+ return err
+ }
+ *x = FieldDescriptorProto_Type(value)
+ return nil
+}
+func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{3, 0}
+}
+
+type FieldDescriptorProto_Label int32
+
+const (
+ // 0 is reserved for errors
+ FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1
+ FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2
+ FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3
+)
+
+var FieldDescriptorProto_Label_name = map[int32]string{
+ 1: "LABEL_OPTIONAL",
+ 2: "LABEL_REQUIRED",
+ 3: "LABEL_REPEATED",
+}
+var FieldDescriptorProto_Label_value = map[string]int32{
+ "LABEL_OPTIONAL": 1,
+ "LABEL_REQUIRED": 2,
+ "LABEL_REPEATED": 3,
+}
+
+func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label {
+ p := new(FieldDescriptorProto_Label)
+ *p = x
+ return p
+}
+func (x FieldDescriptorProto_Label) String() string {
+ return proto.EnumName(FieldDescriptorProto_Label_name, int32(x))
+}
+func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label")
+ if err != nil {
+ return err
+ }
+ *x = FieldDescriptorProto_Label(value)
+ return nil
+}
+func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{3, 1}
+}
+
+// Generated classes can be optimized for speed or code size.
+type FileOptions_OptimizeMode int32
+
+const (
+ FileOptions_SPEED FileOptions_OptimizeMode = 1
+ // etc.
+ FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2
+ FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3
+)
+
+var FileOptions_OptimizeMode_name = map[int32]string{
+ 1: "SPEED",
+ 2: "CODE_SIZE",
+ 3: "LITE_RUNTIME",
+}
+var FileOptions_OptimizeMode_value = map[string]int32{
+ "SPEED": 1,
+ "CODE_SIZE": 2,
+ "LITE_RUNTIME": 3,
+}
+
+func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode {
+ p := new(FileOptions_OptimizeMode)
+ *p = x
+ return p
+}
+func (x FileOptions_OptimizeMode) String() string {
+ return proto.EnumName(FileOptions_OptimizeMode_name, int32(x))
+}
+func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode")
+ if err != nil {
+ return err
+ }
+ *x = FileOptions_OptimizeMode(value)
+ return nil
+}
+func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{9, 0}
+}
+
+type FieldOptions_CType int32
+
+const (
+ // Default mode.
+ FieldOptions_STRING FieldOptions_CType = 0
+ FieldOptions_CORD FieldOptions_CType = 1
+ FieldOptions_STRING_PIECE FieldOptions_CType = 2
+)
+
+var FieldOptions_CType_name = map[int32]string{
+ 0: "STRING",
+ 1: "CORD",
+ 2: "STRING_PIECE",
+}
+var FieldOptions_CType_value = map[string]int32{
+ "STRING": 0,
+ "CORD": 1,
+ "STRING_PIECE": 2,
+}
+
+func (x FieldOptions_CType) Enum() *FieldOptions_CType {
+ p := new(FieldOptions_CType)
+ *p = x
+ return p
+}
+func (x FieldOptions_CType) String() string {
+ return proto.EnumName(FieldOptions_CType_name, int32(x))
+}
+func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType")
+ if err != nil {
+ return err
+ }
+ *x = FieldOptions_CType(value)
+ return nil
+}
+func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{11, 0}
+}
+
+type FieldOptions_JSType int32
+
+const (
+ // Use the default type.
+ FieldOptions_JS_NORMAL FieldOptions_JSType = 0
+ // Use JavaScript strings.
+ FieldOptions_JS_STRING FieldOptions_JSType = 1
+ // Use JavaScript numbers.
+ FieldOptions_JS_NUMBER FieldOptions_JSType = 2
+)
+
+var FieldOptions_JSType_name = map[int32]string{
+ 0: "JS_NORMAL",
+ 1: "JS_STRING",
+ 2: "JS_NUMBER",
+}
+var FieldOptions_JSType_value = map[string]int32{
+ "JS_NORMAL": 0,
+ "JS_STRING": 1,
+ "JS_NUMBER": 2,
+}
+
+func (x FieldOptions_JSType) Enum() *FieldOptions_JSType {
+ p := new(FieldOptions_JSType)
+ *p = x
+ return p
+}
+func (x FieldOptions_JSType) String() string {
+ return proto.EnumName(FieldOptions_JSType_name, int32(x))
+}
+func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType")
+ if err != nil {
+ return err
+ }
+ *x = FieldOptions_JSType(value)
+ return nil
+}
+func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{11, 1}
+}
+
+// The protocol compiler can output a FileDescriptorSet containing the .proto
+// files it parses.
+type FileDescriptorSet struct {
+ File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} }
+func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) }
+func (*FileDescriptorSet) ProtoMessage() {}
+func (*FileDescriptorSet) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{0} }
+
+func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto {
+ if m != nil {
+ return m.File
+ }
+ return nil
+}
+
+// Describes a complete .proto file.
+type FileDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"`
+ // Names of files imported by this file.
+ Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"`
+ // Indexes of the public imported files in the dependency list above.
+ PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"`
+ // Indexes of the weak imported files in the dependency list.
+ // For Google-internal migration only. Do not use.
+ WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"`
+ // All top-level definitions in this file.
+ MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"`
+ EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
+ Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"`
+ Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"`
+ Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
+ // This field contains optional information about the original source code.
+ // You may safely remove this entire field without harming runtime
+ // functionality of the descriptors -- the information is needed only by
+ // development tools.
+ SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"`
+ // The syntax of the proto file.
+ // The supported values are "proto2" and "proto3".
+ Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} }
+func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*FileDescriptorProto) ProtoMessage() {}
+func (*FileDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{1} }
+
+func (m *FileDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *FileDescriptorProto) GetPackage() string {
+ if m != nil && m.Package != nil {
+ return *m.Package
+ }
+ return ""
+}
+
+func (m *FileDescriptorProto) GetDependency() []string {
+ if m != nil {
+ return m.Dependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetPublicDependency() []int32 {
+ if m != nil {
+ return m.PublicDependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetWeakDependency() []int32 {
+ if m != nil {
+ return m.WeakDependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto {
+ if m != nil {
+ return m.MessageType
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto {
+ if m != nil {
+ return m.EnumType
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto {
+ if m != nil {
+ return m.Service
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Extension
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetOptions() *FileOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo {
+ if m != nil {
+ return m.SourceCodeInfo
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetSyntax() string {
+ if m != nil && m.Syntax != nil {
+ return *m.Syntax
+ }
+ return ""
+}
+
+// Describes a message type.
+type DescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"`
+ Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"`
+ NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"`
+ EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
+ ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"`
+ OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"`
+ Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"`
+ ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
+ // Reserved field names, which may not be used by fields in the same message.
+ // A given name may only be reserved once.
+ ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *DescriptorProto) Reset() { *m = DescriptorProto{} }
+func (m *DescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto) ProtoMessage() {}
+func (*DescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{2} }
+
+func (m *DescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *DescriptorProto) GetField() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Field
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Extension
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetNestedType() []*DescriptorProto {
+ if m != nil {
+ return m.NestedType
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto {
+ if m != nil {
+ return m.EnumType
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange {
+ if m != nil {
+ return m.ExtensionRange
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto {
+ if m != nil {
+ return m.OneofDecl
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetOptions() *MessageOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange {
+ if m != nil {
+ return m.ReservedRange
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetReservedName() []string {
+ if m != nil {
+ return m.ReservedName
+ }
+ return nil
+}
+
+type DescriptorProto_ExtensionRange struct {
+ Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
+ End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} }
+func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto_ExtensionRange) ProtoMessage() {}
+func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{2, 0}
+}
+
+func (m *DescriptorProto_ExtensionRange) GetStart() int32 {
+ if m != nil && m.Start != nil {
+ return *m.Start
+ }
+ return 0
+}
+
+func (m *DescriptorProto_ExtensionRange) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+// Range of reserved tag numbers. Reserved tag numbers may not be used by
+// fields or extension ranges in the same message. Reserved ranges may
+// not overlap.
+type DescriptorProto_ReservedRange struct {
+ Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
+ End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} }
+func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto_ReservedRange) ProtoMessage() {}
+func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{2, 1}
+}
+
+func (m *DescriptorProto_ReservedRange) GetStart() int32 {
+ if m != nil && m.Start != nil {
+ return *m.Start
+ }
+ return 0
+}
+
+func (m *DescriptorProto_ReservedRange) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+// Describes a field within a message.
+type FieldDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"`
+ Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"`
+ // If type_name is set, this need not be set. If both this and type_name
+ // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
+ Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"`
+ // For message and enum types, this is the name of the type. If the name
+ // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
+ // rules are used to find the type (i.e. first the nested types within this
+ // message are searched, then within the parent, on up to the root
+ // namespace).
+ TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"`
+ // For extensions, this is the name of the type being extended. It is
+ // resolved in the same manner as type_name.
+ Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"`
+ // For numeric types, contains the original text representation of the value.
+ // For booleans, "true" or "false".
+ // For strings, contains the default text contents (not escaped in any way).
+ // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
+ // TODO(kenton): Base-64 encode?
+ DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"`
+ // If set, gives the index of a oneof in the containing type's oneof_decl
+ // list. This field is a member of that oneof.
+ OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"`
+ // JSON name of this field. The value is set by protocol compiler. If the
+ // user has set a "json_name" option on this field, that option's value
+ // will be used. Otherwise, it's deduced from the field's name by converting
+ // it to camelCase.
+ JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"`
+ Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} }
+func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*FieldDescriptorProto) ProtoMessage() {}
+func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{3} }
+
+func (m *FieldDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetNumber() int32 {
+ if m != nil && m.Number != nil {
+ return *m.Number
+ }
+ return 0
+}
+
+func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return FieldDescriptorProto_LABEL_OPTIONAL
+}
+
+func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return FieldDescriptorProto_TYPE_DOUBLE
+}
+
+func (m *FieldDescriptorProto) GetTypeName() string {
+ if m != nil && m.TypeName != nil {
+ return *m.TypeName
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetExtendee() string {
+ if m != nil && m.Extendee != nil {
+ return *m.Extendee
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetDefaultValue() string {
+ if m != nil && m.DefaultValue != nil {
+ return *m.DefaultValue
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetOneofIndex() int32 {
+ if m != nil && m.OneofIndex != nil {
+ return *m.OneofIndex
+ }
+ return 0
+}
+
+func (m *FieldDescriptorProto) GetJsonName() string {
+ if m != nil && m.JsonName != nil {
+ return *m.JsonName
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetOptions() *FieldOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a oneof.
+type OneofDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} }
+func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*OneofDescriptorProto) ProtoMessage() {}
+func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{4} }
+
+func (m *OneofDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *OneofDescriptorProto) GetOptions() *OneofOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes an enum type.
+type EnumDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"`
+ Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} }
+func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*EnumDescriptorProto) ProtoMessage() {}
+func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{5} }
+
+func (m *EnumDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func (m *EnumDescriptorProto) GetOptions() *EnumOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a value within an enum.
+type EnumValueDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"`
+ Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} }
+func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*EnumValueDescriptorProto) ProtoMessage() {}
+func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{6}
+}
+
+func (m *EnumValueDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *EnumValueDescriptorProto) GetNumber() int32 {
+ if m != nil && m.Number != nil {
+ return *m.Number
+ }
+ return 0
+}
+
+func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a service.
+type ServiceDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"`
+ Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} }
+func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*ServiceDescriptorProto) ProtoMessage() {}
+func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{7} }
+
+func (m *ServiceDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto {
+ if m != nil {
+ return m.Method
+ }
+ return nil
+}
+
+func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a method of a service.
+type MethodDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ // Input and output type names. These are resolved in the same way as
+ // FieldDescriptorProto.type_name, but must refer to a message type.
+ InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"`
+ OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"`
+ Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"`
+ // Identifies if client streams multiple client messages
+ ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"`
+ // Identifies if server streams multiple server messages
+ ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} }
+func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*MethodDescriptorProto) ProtoMessage() {}
+func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{8} }
+
+const Default_MethodDescriptorProto_ClientStreaming bool = false
+const Default_MethodDescriptorProto_ServerStreaming bool = false
+
+func (m *MethodDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetInputType() string {
+ if m != nil && m.InputType != nil {
+ return *m.InputType
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetOutputType() string {
+ if m != nil && m.OutputType != nil {
+ return *m.OutputType
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetOptions() *MethodOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *MethodDescriptorProto) GetClientStreaming() bool {
+ if m != nil && m.ClientStreaming != nil {
+ return *m.ClientStreaming
+ }
+ return Default_MethodDescriptorProto_ClientStreaming
+}
+
+func (m *MethodDescriptorProto) GetServerStreaming() bool {
+ if m != nil && m.ServerStreaming != nil {
+ return *m.ServerStreaming
+ }
+ return Default_MethodDescriptorProto_ServerStreaming
+}
+
+type FileOptions struct {
+ // Sets the Java package where classes generated from this .proto will be
+ // placed. By default, the proto package is used, but this is often
+ // inappropriate because proto packages do not normally start with backwards
+ // domain names.
+ JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"`
+ // If set, all the classes from the .proto file are wrapped in a single
+ // outer class with the given name. This applies to both Proto1
+ // (equivalent to the old "--one_java_file" option) and Proto2 (where
+ // a .proto always translates to a single class, but you may want to
+ // explicitly choose the class name).
+ JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"`
+ // If set true, then the Java code generator will generate a separate .java
+ // file for each top-level message, enum, and service defined in the .proto
+ // file. Thus, these types will *not* be nested inside the outer class
+ // named by java_outer_classname. However, the outer class will still be
+ // generated to contain the file's getDescriptor() method as well as any
+ // top-level extensions defined in the file.
+ JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"`
+ // If set true, then the Java code generator will generate equals() and
+ // hashCode() methods for all messages defined in the .proto file.
+ // This increases generated code size, potentially substantially for large
+ // protos, which may harm a memory-constrained application.
+ // - In the full runtime this is a speed optimization, as the
+ // AbstractMessage base class includes reflection-based implementations of
+ // these methods.
+ // - In the lite runtime, setting this option changes the semantics of
+ // equals() and hashCode() to more closely match those of the full runtime;
+ // the generated methods compute their results based on field values rather
+ // than object identity. (Implementations should not assume that hashcodes
+ // will be consistent across runtimes or versions of the protocol compiler.)
+ JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash,def=0" json:"java_generate_equals_and_hash,omitempty"`
+ // If set true, then the Java2 code generator will generate code that
+ // throws an exception whenever an attempt is made to assign a non-UTF-8
+ // byte sequence to a string field.
+ // Message reflection will do the same.
+ // However, an extension field still accepts non-UTF-8 byte sequences.
+ // This option has no effect on when used with the lite runtime.
+ JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"`
+ OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"`
+ // Sets the Go package where structs generated from this .proto will be
+ // placed. If omitted, the Go package will be derived from the following:
+ // - The basename of the package import path, if provided.
+ // - Otherwise, the package statement in the .proto file, if present.
+ // - Otherwise, the basename of the .proto file, without extension.
+ GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"`
+ // Should generic services be generated in each language? "Generic" services
+ // are not specific to any particular RPC system. They are generated by the
+ // main code generators in each language (without additional plugins).
+ // Generic services were the only kind of service generation supported by
+ // early versions of google.protobuf.
+ //
+ // Generic services are now considered deprecated in favor of using plugins
+ // that generate code specific to your particular RPC system. Therefore,
+ // these default to false. Old code which depends on generic services should
+ // explicitly set them to true.
+ CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"`
+ JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"`
+ PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"`
+ // Is this file deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for everything in the file, or it will be completely ignored; in the very
+ // least, this is a formalization for deprecating files.
+ Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // Enables the use of arenas for the proto messages in this file. This applies
+ // only to generated classes for C++.
+ CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"`
+ // Sets the objective c class prefix which is prepended to all objective c
+ // generated classes from this .proto. There is no default.
+ ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"`
+ // Namespace for generated classes; defaults to the package.
+ CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FileOptions) Reset() { *m = FileOptions{} }
+func (m *FileOptions) String() string { return proto.CompactTextString(m) }
+func (*FileOptions) ProtoMessage() {}
+func (*FileOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{9} }
+
+var extRange_FileOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_FileOptions
+}
+
+const Default_FileOptions_JavaMultipleFiles bool = false
+const Default_FileOptions_JavaGenerateEqualsAndHash bool = false
+const Default_FileOptions_JavaStringCheckUtf8 bool = false
+const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED
+const Default_FileOptions_CcGenericServices bool = false
+const Default_FileOptions_JavaGenericServices bool = false
+const Default_FileOptions_PyGenericServices bool = false
+const Default_FileOptions_Deprecated bool = false
+const Default_FileOptions_CcEnableArenas bool = false
+
+func (m *FileOptions) GetJavaPackage() string {
+ if m != nil && m.JavaPackage != nil {
+ return *m.JavaPackage
+ }
+ return ""
+}
+
+func (m *FileOptions) GetJavaOuterClassname() string {
+ if m != nil && m.JavaOuterClassname != nil {
+ return *m.JavaOuterClassname
+ }
+ return ""
+}
+
+func (m *FileOptions) GetJavaMultipleFiles() bool {
+ if m != nil && m.JavaMultipleFiles != nil {
+ return *m.JavaMultipleFiles
+ }
+ return Default_FileOptions_JavaMultipleFiles
+}
+
+func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool {
+ if m != nil && m.JavaGenerateEqualsAndHash != nil {
+ return *m.JavaGenerateEqualsAndHash
+ }
+ return Default_FileOptions_JavaGenerateEqualsAndHash
+}
+
+func (m *FileOptions) GetJavaStringCheckUtf8() bool {
+ if m != nil && m.JavaStringCheckUtf8 != nil {
+ return *m.JavaStringCheckUtf8
+ }
+ return Default_FileOptions_JavaStringCheckUtf8
+}
+
+func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode {
+ if m != nil && m.OptimizeFor != nil {
+ return *m.OptimizeFor
+ }
+ return Default_FileOptions_OptimizeFor
+}
+
+func (m *FileOptions) GetGoPackage() string {
+ if m != nil && m.GoPackage != nil {
+ return *m.GoPackage
+ }
+ return ""
+}
+
+func (m *FileOptions) GetCcGenericServices() bool {
+ if m != nil && m.CcGenericServices != nil {
+ return *m.CcGenericServices
+ }
+ return Default_FileOptions_CcGenericServices
+}
+
+func (m *FileOptions) GetJavaGenericServices() bool {
+ if m != nil && m.JavaGenericServices != nil {
+ return *m.JavaGenericServices
+ }
+ return Default_FileOptions_JavaGenericServices
+}
+
+func (m *FileOptions) GetPyGenericServices() bool {
+ if m != nil && m.PyGenericServices != nil {
+ return *m.PyGenericServices
+ }
+ return Default_FileOptions_PyGenericServices
+}
+
+func (m *FileOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_FileOptions_Deprecated
+}
+
+func (m *FileOptions) GetCcEnableArenas() bool {
+ if m != nil && m.CcEnableArenas != nil {
+ return *m.CcEnableArenas
+ }
+ return Default_FileOptions_CcEnableArenas
+}
+
+func (m *FileOptions) GetObjcClassPrefix() string {
+ if m != nil && m.ObjcClassPrefix != nil {
+ return *m.ObjcClassPrefix
+ }
+ return ""
+}
+
+func (m *FileOptions) GetCsharpNamespace() string {
+ if m != nil && m.CsharpNamespace != nil {
+ return *m.CsharpNamespace
+ }
+ return ""
+}
+
+func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type MessageOptions struct {
+ // Set true to use the old proto1 MessageSet wire format for extensions.
+ // This is provided for backwards-compatibility with the MessageSet wire
+ // format. You should not use this for any other reason: It's less
+ // efficient, has fewer features, and is more complicated.
+ //
+ // The message must be defined exactly as follows:
+ // message Foo {
+ // option message_set_wire_format = true;
+ // extensions 4 to max;
+ // }
+ // Note that the message cannot have any defined fields; MessageSets only
+ // have extensions.
+ //
+ // All extensions of your type must be singular messages; e.g. they cannot
+ // be int32s, enums, or repeated messages.
+ //
+ // Because this is an option, the above two restrictions are not enforced by
+ // the protocol compiler.
+ MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"`
+ // Disables the generation of the standard "descriptor()" accessor, which can
+ // conflict with a field of the same name. This is meant to make migration
+ // from proto1 easier; new code should avoid fields named "descriptor".
+ NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"`
+ // Is this message deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the message, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating messages.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // Whether the message is an automatically generated map entry type for the
+ // maps field.
+ //
+ // For maps fields:
+ // map<KeyType, ValueType> map_field = 1;
+ // The parsed descriptor looks like:
+ // message MapFieldEntry {
+ // option map_entry = true;
+ // optional KeyType key = 1;
+ // optional ValueType value = 2;
+ // }
+ // repeated MapFieldEntry map_field = 1;
+ //
+ // Implementations may choose not to generate the map_entry=true message, but
+ // use a native map in the target language to hold the keys and values.
+ // The reflection APIs in such implementions still need to work as
+ // if the field is a repeated message field.
+ //
+ // NOTE: Do not set the option in .proto files. Always use the maps syntax
+ // instead. The option should only be implicitly set by the proto compiler
+ // parser.
+ MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MessageOptions) Reset() { *m = MessageOptions{} }
+func (m *MessageOptions) String() string { return proto.CompactTextString(m) }
+func (*MessageOptions) ProtoMessage() {}
+func (*MessageOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{10} }
+
+var extRange_MessageOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_MessageOptions
+}
+
+const Default_MessageOptions_MessageSetWireFormat bool = false
+const Default_MessageOptions_NoStandardDescriptorAccessor bool = false
+const Default_MessageOptions_Deprecated bool = false
+
+func (m *MessageOptions) GetMessageSetWireFormat() bool {
+ if m != nil && m.MessageSetWireFormat != nil {
+ return *m.MessageSetWireFormat
+ }
+ return Default_MessageOptions_MessageSetWireFormat
+}
+
+func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool {
+ if m != nil && m.NoStandardDescriptorAccessor != nil {
+ return *m.NoStandardDescriptorAccessor
+ }
+ return Default_MessageOptions_NoStandardDescriptorAccessor
+}
+
+func (m *MessageOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_MessageOptions_Deprecated
+}
+
+func (m *MessageOptions) GetMapEntry() bool {
+ if m != nil && m.MapEntry != nil {
+ return *m.MapEntry
+ }
+ return false
+}
+
+func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type FieldOptions struct {
+ // The ctype option instructs the C++ code generator to use a different
+ // representation of the field than it normally would. See the specific
+ // options below. This option is not yet implemented in the open source
+ // release -- sorry, we'll try to include it in a future version!
+ Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"`
+ // The packed option can be enabled for repeated primitive fields to enable
+ // a more efficient representation on the wire. Rather than repeatedly
+ // writing the tag and type for each element, the entire array is encoded as
+ // a single length-delimited blob. In proto3, only explicit setting it to
+ // false will avoid using packed encoding.
+ Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"`
+ // The jstype option determines the JavaScript type used for values of the
+ // field. The option is permitted only for 64 bit integral and fixed types
+ // (int64, uint64, sint64, fixed64, sfixed64). By default these types are
+ // represented as JavaScript strings. This avoids loss of precision that can
+ // happen when a large value is converted to a floating point JavaScript
+ // numbers. Specifying JS_NUMBER for the jstype causes the generated
+ // JavaScript code to use the JavaScript "number" type instead of strings.
+ // This option is an enum to permit additional types to be added,
+ // e.g. goog.math.Integer.
+ Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"`
+ // Should this field be parsed lazily? Lazy applies only to message-type
+ // fields. It means that when the outer message is initially parsed, the
+ // inner message's contents will not be parsed but instead stored in encoded
+ // form. The inner message will actually be parsed when it is first accessed.
+ //
+ // This is only a hint. Implementations are free to choose whether to use
+ // eager or lazy parsing regardless of the value of this option. However,
+ // setting this option true suggests that the protocol author believes that
+ // using lazy parsing on this field is worth the additional bookkeeping
+ // overhead typically needed to implement it.
+ //
+ // This option does not affect the public interface of any generated code;
+ // all method signatures remain the same. Furthermore, thread-safety of the
+ // interface is not affected by this option; const methods remain safe to
+ // call from multiple threads concurrently, while non-const methods continue
+ // to require exclusive access.
+ //
+ //
+ // Note that implementations may choose not to check required fields within
+ // a lazy sub-message. That is, calling IsInitialized() on the outher message
+ // may return true even if the inner message has missing required fields.
+ // This is necessary because otherwise the inner message would have to be
+ // parsed in order to perform the check, defeating the purpose of lazy
+ // parsing. An implementation which chooses not to check required fields
+ // must be consistent about it. That is, for any particular sub-message, the
+ // implementation must either *always* check its required fields, or *never*
+ // check its required fields, regardless of whether or not the message has
+ // been parsed.
+ Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"`
+ // Is this field deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for accessors, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating fields.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // For Google-internal migration only. Do not use.
+ Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FieldOptions) Reset() { *m = FieldOptions{} }
+func (m *FieldOptions) String() string { return proto.CompactTextString(m) }
+func (*FieldOptions) ProtoMessage() {}
+func (*FieldOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{11} }
+
+var extRange_FieldOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_FieldOptions
+}
+
+const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING
+const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL
+const Default_FieldOptions_Lazy bool = false
+const Default_FieldOptions_Deprecated bool = false
+const Default_FieldOptions_Weak bool = false
+
+func (m *FieldOptions) GetCtype() FieldOptions_CType {
+ if m != nil && m.Ctype != nil {
+ return *m.Ctype
+ }
+ return Default_FieldOptions_Ctype
+}
+
+func (m *FieldOptions) GetPacked() bool {
+ if m != nil && m.Packed != nil {
+ return *m.Packed
+ }
+ return false
+}
+
+func (m *FieldOptions) GetJstype() FieldOptions_JSType {
+ if m != nil && m.Jstype != nil {
+ return *m.Jstype
+ }
+ return Default_FieldOptions_Jstype
+}
+
+func (m *FieldOptions) GetLazy() bool {
+ if m != nil && m.Lazy != nil {
+ return *m.Lazy
+ }
+ return Default_FieldOptions_Lazy
+}
+
+func (m *FieldOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_FieldOptions_Deprecated
+}
+
+func (m *FieldOptions) GetWeak() bool {
+ if m != nil && m.Weak != nil {
+ return *m.Weak
+ }
+ return Default_FieldOptions_Weak
+}
+
+func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type OneofOptions struct {
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OneofOptions) Reset() { *m = OneofOptions{} }
+func (m *OneofOptions) String() string { return proto.CompactTextString(m) }
+func (*OneofOptions) ProtoMessage() {}
+func (*OneofOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{12} }
+
+var extRange_OneofOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_OneofOptions
+}
+
+func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type EnumOptions struct {
+ // Set this option to true to allow mapping different tag names to the same
+ // value.
+ AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"`
+ // Is this enum deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating enums.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumOptions) Reset() { *m = EnumOptions{} }
+func (m *EnumOptions) String() string { return proto.CompactTextString(m) }
+func (*EnumOptions) ProtoMessage() {}
+func (*EnumOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{13} }
+
+var extRange_EnumOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_EnumOptions
+}
+
+const Default_EnumOptions_Deprecated bool = false
+
+func (m *EnumOptions) GetAllowAlias() bool {
+ if m != nil && m.AllowAlias != nil {
+ return *m.AllowAlias
+ }
+ return false
+}
+
+func (m *EnumOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_EnumOptions_Deprecated
+}
+
+func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type EnumValueOptions struct {
+ // Is this enum value deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum value, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating enum values.
+ Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} }
+func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) }
+func (*EnumValueOptions) ProtoMessage() {}
+func (*EnumValueOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{14} }
+
+var extRange_EnumValueOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_EnumValueOptions
+}
+
+const Default_EnumValueOptions_Deprecated bool = false
+
+func (m *EnumValueOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_EnumValueOptions_Deprecated
+}
+
+func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type ServiceOptions struct {
+ // Is this service deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the service, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating services.
+ Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ServiceOptions) Reset() { *m = ServiceOptions{} }
+func (m *ServiceOptions) String() string { return proto.CompactTextString(m) }
+func (*ServiceOptions) ProtoMessage() {}
+func (*ServiceOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{15} }
+
+var extRange_ServiceOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_ServiceOptions
+}
+
+const Default_ServiceOptions_Deprecated bool = false
+
+func (m *ServiceOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_ServiceOptions_Deprecated
+}
+
+func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type MethodOptions struct {
+ // Is this method deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the method, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating methods.
+ Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MethodOptions) Reset() { *m = MethodOptions{} }
+func (m *MethodOptions) String() string { return proto.CompactTextString(m) }
+func (*MethodOptions) ProtoMessage() {}
+func (*MethodOptions) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{16} }
+
+var extRange_MethodOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_MethodOptions
+}
+
+const Default_MethodOptions_Deprecated bool = false
+
+func (m *MethodOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_MethodOptions_Deprecated
+}
+
+func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+// A message representing a option the parser does not recognize. This only
+// appears in options protos created by the compiler::Parser class.
+// DescriptorPool resolves these when building Descriptor objects. Therefore,
+// options protos in descriptor objects (e.g. returned by Descriptor::options(),
+// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
+// in them.
+type UninterpretedOption struct {
+ Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"`
+ // The value of the uninterpreted option, in whatever type the tokenizer
+ // identified it as during parsing. Exactly one of these should be set.
+ IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"`
+ PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"`
+ NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"`
+ DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"`
+ StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"`
+ AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} }
+func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) }
+func (*UninterpretedOption) ProtoMessage() {}
+func (*UninterpretedOption) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{17} }
+
+func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart {
+ if m != nil {
+ return m.Name
+ }
+ return nil
+}
+
+func (m *UninterpretedOption) GetIdentifierValue() string {
+ if m != nil && m.IdentifierValue != nil {
+ return *m.IdentifierValue
+ }
+ return ""
+}
+
+func (m *UninterpretedOption) GetPositiveIntValue() uint64 {
+ if m != nil && m.PositiveIntValue != nil {
+ return *m.PositiveIntValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetNegativeIntValue() int64 {
+ if m != nil && m.NegativeIntValue != nil {
+ return *m.NegativeIntValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetDoubleValue() float64 {
+ if m != nil && m.DoubleValue != nil {
+ return *m.DoubleValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetStringValue() []byte {
+ if m != nil {
+ return m.StringValue
+ }
+ return nil
+}
+
+func (m *UninterpretedOption) GetAggregateValue() string {
+ if m != nil && m.AggregateValue != nil {
+ return *m.AggregateValue
+ }
+ return ""
+}
+
+// The name of the uninterpreted option. Each string represents a segment in
+// a dot-separated name. is_extension is true iff a segment represents an
+// extension (denoted with parentheses in options specs in .proto files).
+// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
+// "foo.(bar.baz).qux".
+type UninterpretedOption_NamePart struct {
+ NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"`
+ IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} }
+func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) }
+func (*UninterpretedOption_NamePart) ProtoMessage() {}
+func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{17, 0}
+}
+
+func (m *UninterpretedOption_NamePart) GetNamePart() string {
+ if m != nil && m.NamePart != nil {
+ return *m.NamePart
+ }
+ return ""
+}
+
+func (m *UninterpretedOption_NamePart) GetIsExtension() bool {
+ if m != nil && m.IsExtension != nil {
+ return *m.IsExtension
+ }
+ return false
+}
+
+// Encapsulates information about the original source file from which a
+// FileDescriptorProto was generated.
+type SourceCodeInfo struct {
+ // A Location identifies a piece of source code in a .proto file which
+ // corresponds to a particular definition. This information is intended
+ // to be useful to IDEs, code indexers, documentation generators, and similar
+ // tools.
+ //
+ // For example, say we have a file like:
+ // message Foo {
+ // optional string foo = 1;
+ // }
+ // Let's look at just the field definition:
+ // optional string foo = 1;
+ // ^ ^^ ^^ ^ ^^^
+ // a bc de f ghi
+ // We have the following locations:
+ // span path represents
+ // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
+ // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
+ // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
+ // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
+ // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
+ //
+ // Notes:
+ // - A location may refer to a repeated field itself (i.e. not to any
+ // particular index within it). This is used whenever a set of elements are
+ // logically enclosed in a single code segment. For example, an entire
+ // extend block (possibly containing multiple extension definitions) will
+ // have an outer location whose path refers to the "extensions" repeated
+ // field without an index.
+ // - Multiple locations may have the same path. This happens when a single
+ // logical declaration is spread out across multiple places. The most
+ // obvious example is the "extend" block again -- there may be multiple
+ // extend blocks in the same scope, each of which will have the same path.
+ // - A location's span is not always a subset of its parent's span. For
+ // example, the "extendee" of an extension declaration appears at the
+ // beginning of the "extend" block and is shared by all extensions within
+ // the block.
+ // - Just because a location's span is a subset of some other location's span
+ // does not mean that it is a descendent. For example, a "group" defines
+ // both a type and a field in a single declaration. Thus, the locations
+ // corresponding to the type and field and their components will overlap.
+ // - Code which tries to interpret locations should probably be designed to
+ // ignore those that it doesn't understand, as more types of locations could
+ // be recorded in the future.
+ Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} }
+func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) }
+func (*SourceCodeInfo) ProtoMessage() {}
+func (*SourceCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{18} }
+
+func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location {
+ if m != nil {
+ return m.Location
+ }
+ return nil
+}
+
+type SourceCodeInfo_Location struct {
+ // Identifies which part of the FileDescriptorProto was defined at this
+ // location.
+ //
+ // Each element is a field number or an index. They form a path from
+ // the root FileDescriptorProto to the place where the definition. For
+ // example, this path:
+ // [ 4, 3, 2, 7, 1 ]
+ // refers to:
+ // file.message_type(3) // 4, 3
+ // .field(7) // 2, 7
+ // .name() // 1
+ // This is because FileDescriptorProto.message_type has field number 4:
+ // repeated DescriptorProto message_type = 4;
+ // and DescriptorProto.field has field number 2:
+ // repeated FieldDescriptorProto field = 2;
+ // and FieldDescriptorProto.name has field number 1:
+ // optional string name = 1;
+ //
+ // Thus, the above path gives the location of a field name. If we removed
+ // the last element:
+ // [ 4, 3, 2, 7 ]
+ // this path refers to the whole field declaration (from the beginning
+ // of the label to the terminating semicolon).
+ Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
+ // Always has exactly three or four elements: start line, start column,
+ // end line (optional, otherwise assumed same as start line), end column.
+ // These are packed into a single field for efficiency. Note that line
+ // and column numbers are zero-based -- typically you will want to add
+ // 1 to each before displaying to a user.
+ Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"`
+ // If this SourceCodeInfo represents a complete declaration, these are any
+ // comments appearing before and after the declaration which appear to be
+ // attached to the declaration.
+ //
+ // A series of line comments appearing on consecutive lines, with no other
+ // tokens appearing on those lines, will be treated as a single comment.
+ //
+ // leading_detached_comments will keep paragraphs of comments that appear
+ // before (but not connected to) the current element. Each paragraph,
+ // separated by empty lines, will be one comment element in the repeated
+ // field.
+ //
+ // Only the comment content is provided; comment markers (e.g. //) are
+ // stripped out. For block comments, leading whitespace and an asterisk
+ // will be stripped from the beginning of each line other than the first.
+ // Newlines are included in the output.
+ //
+ // Examples:
+ //
+ // optional int32 foo = 1; // Comment attached to foo.
+ // // Comment attached to bar.
+ // optional int32 bar = 2;
+ //
+ // optional string baz = 3;
+ // // Comment attached to baz.
+ // // Another line attached to baz.
+ //
+ // // Comment attached to qux.
+ // //
+ // // Another line attached to qux.
+ // optional double qux = 4;
+ //
+ // // Detached comment for corge. This is not leading or trailing comments
+ // // to qux or corge because there are blank lines separating it from
+ // // both.
+ //
+ // // Detached comment for corge paragraph 2.
+ //
+ // optional string corge = 5;
+ // /* Block comment attached
+ // * to corge. Leading asterisks
+ // * will be removed. */
+ // /* Block comment attached to
+ // * grault. */
+ // optional int32 grault = 6;
+ //
+ // // ignored detached comments.
+ LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"`
+ TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"`
+ LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} }
+func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) }
+func (*SourceCodeInfo_Location) ProtoMessage() {}
+func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{18, 0}
+}
+
+func (m *SourceCodeInfo_Location) GetPath() []int32 {
+ if m != nil {
+ return m.Path
+ }
+ return nil
+}
+
+func (m *SourceCodeInfo_Location) GetSpan() []int32 {
+ if m != nil {
+ return m.Span
+ }
+ return nil
+}
+
+func (m *SourceCodeInfo_Location) GetLeadingComments() string {
+ if m != nil && m.LeadingComments != nil {
+ return *m.LeadingComments
+ }
+ return ""
+}
+
+func (m *SourceCodeInfo_Location) GetTrailingComments() string {
+ if m != nil && m.TrailingComments != nil {
+ return *m.TrailingComments
+ }
+ return ""
+}
+
+func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string {
+ if m != nil {
+ return m.LeadingDetachedComments
+ }
+ return nil
+}
+
+// Describes the relationship between generated code and its original source
+// file. A GeneratedCodeInfo message is associated with only one generated
+// source file, but may contain references to different source .proto files.
+type GeneratedCodeInfo struct {
+ // An Annotation connects some span of text in generated code to an element
+ // of its generating .proto file.
+ Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} }
+func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) }
+func (*GeneratedCodeInfo) ProtoMessage() {}
+func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptorDescriptor, []int{19} }
+
+func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation {
+ if m != nil {
+ return m.Annotation
+ }
+ return nil
+}
+
+type GeneratedCodeInfo_Annotation struct {
+ // Identifies the element in the original source .proto file. This field
+ // is formatted the same as SourceCodeInfo.Location.path.
+ Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
+ // Identifies the filesystem path to the original source .proto.
+ SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"`
+ // Identifies the starting offset in bytes in the generated code
+ // that relates to the identified object.
+ Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"`
+ // Identifies the ending offset in bytes in the generated code that
+ // relates to the identified offset. The end offset should be one past
+ // the last relevant byte (so the length of the text = end - begin).
+ End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} }
+func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) }
+func (*GeneratedCodeInfo_Annotation) ProtoMessage() {}
+func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) {
+ return fileDescriptorDescriptor, []int{19, 0}
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 {
+ if m != nil {
+ return m.Path
+ }
+ return nil
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string {
+ if m != nil && m.SourceFile != nil {
+ return *m.SourceFile
+ }
+ return ""
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 {
+ if m != nil && m.Begin != nil {
+ return *m.Begin
+ }
+ return 0
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet")
+ proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto")
+ proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto")
+ proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange")
+ proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange")
+ proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto")
+ proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto")
+ proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto")
+ proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto")
+ proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto")
+ proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto")
+ proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions")
+ proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions")
+ proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions")
+ proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions")
+ proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions")
+ proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions")
+ proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions")
+ proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions")
+ proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption")
+ proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart")
+ proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo")
+ proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location")
+ proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo")
+ proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation")
+ proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value)
+ proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value)
+ proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value)
+ proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value)
+ proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value)
+}
+
+func init() { proto.RegisterFile("descriptor.proto", fileDescriptorDescriptor) }
+
+var fileDescriptorDescriptor = []byte{
+ // 2273 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x59, 0xcd, 0x6f, 0xdb, 0xc8,
+ 0x15, 0x5f, 0xea, 0xcb, 0xd2, 0x93, 0x2c, 0x8f, 0xc7, 0xde, 0x84, 0x71, 0x36, 0x1b, 0x47, 0x9b,
+ 0x34, 0x4e, 0xd2, 0x3a, 0x0b, 0xe7, 0x63, 0xb3, 0xde, 0x62, 0x0b, 0x59, 0x62, 0xbc, 0x0a, 0x64,
+ 0x4b, 0xa5, 0xec, 0x36, 0xbb, 0x3d, 0x10, 0x63, 0x72, 0x24, 0x33, 0xa1, 0x86, 0x2c, 0x49, 0x25,
+ 0xf1, 0x9e, 0x02, 0xf4, 0x54, 0xf4, 0x1f, 0x28, 0xda, 0xa2, 0x28, 0xf6, 0xb2, 0x40, 0xff, 0x80,
+ 0x1e, 0x7a, 0xef, 0xb5, 0x40, 0xef, 0x3d, 0x16, 0x68, 0xff, 0x83, 0x5e, 0x8b, 0x99, 0x21, 0x29,
+ 0xea, 0x6b, 0xe3, 0x2e, 0xb0, 0x1f, 0x27, 0x6b, 0x7e, 0xef, 0xf7, 0x1e, 0xdf, 0xbc, 0x79, 0x7c,
+ 0xef, 0x71, 0x0c, 0xc8, 0xa2, 0x81, 0xe9, 0xdb, 0x5e, 0xe8, 0xfa, 0xdb, 0x9e, 0xef, 0x86, 0x2e,
+ 0x5e, 0x19, 0xb8, 0xee, 0xc0, 0xa1, 0x72, 0x75, 0x32, 0xea, 0xd7, 0x0e, 0x60, 0xf5, 0xb1, 0xed,
+ 0xd0, 0x66, 0x42, 0xec, 0xd1, 0x10, 0x3f, 0x82, 0x5c, 0xdf, 0x76, 0xa8, 0xaa, 0x6c, 0x66, 0xb7,
+ 0xca, 0x3b, 0xd7, 0xb7, 0xa7, 0x94, 0xb6, 0x27, 0x35, 0xba, 0x1c, 0xd6, 0x85, 0x46, 0xed, 0x5f,
+ 0x39, 0x58, 0x9b, 0x23, 0xc5, 0x18, 0x72, 0x8c, 0x0c, 0xb9, 0x45, 0x65, 0xab, 0xa4, 0x8b, 0xdf,
+ 0x58, 0x85, 0x25, 0x8f, 0x98, 0xcf, 0xc9, 0x80, 0xaa, 0x19, 0x01, 0xc7, 0x4b, 0xfc, 0x2e, 0x80,
+ 0x45, 0x3d, 0xca, 0x2c, 0xca, 0xcc, 0x33, 0x35, 0xbb, 0x99, 0xdd, 0x2a, 0xe9, 0x29, 0x04, 0xdf,
+ 0x81, 0x55, 0x6f, 0x74, 0xe2, 0xd8, 0xa6, 0x91, 0xa2, 0xc1, 0x66, 0x76, 0x2b, 0xaf, 0x23, 0x29,
+ 0x68, 0x8e, 0xc9, 0x37, 0x61, 0xe5, 0x25, 0x25, 0xcf, 0xd3, 0xd4, 0xb2, 0xa0, 0x56, 0x39, 0x9c,
+ 0x22, 0x36, 0xa0, 0x32, 0xa4, 0x41, 0x40, 0x06, 0xd4, 0x08, 0xcf, 0x3c, 0xaa, 0xe6, 0xc4, 0xee,
+ 0x37, 0x67, 0x76, 0x3f, 0xbd, 0xf3, 0x72, 0xa4, 0x75, 0x74, 0xe6, 0x51, 0x5c, 0x87, 0x12, 0x65,
+ 0xa3, 0xa1, 0xb4, 0x90, 0x5f, 0x10, 0x3f, 0x8d, 0x8d, 0x86, 0xd3, 0x56, 0x8a, 0x5c, 0x2d, 0x32,
+ 0xb1, 0x14, 0x50, 0xff, 0x85, 0x6d, 0x52, 0xb5, 0x20, 0x0c, 0xdc, 0x9c, 0x31, 0xd0, 0x93, 0xf2,
+ 0x69, 0x1b, 0xb1, 0x1e, 0x6e, 0x40, 0x89, 0xbe, 0x0a, 0x29, 0x0b, 0x6c, 0x97, 0xa9, 0x4b, 0xc2,
+ 0xc8, 0x8d, 0x39, 0xa7, 0x48, 0x1d, 0x6b, 0xda, 0xc4, 0x58, 0x0f, 0x3f, 0x84, 0x25, 0xd7, 0x0b,
+ 0x6d, 0x97, 0x05, 0x6a, 0x71, 0x53, 0xd9, 0x2a, 0xef, 0xbc, 0x33, 0x37, 0x11, 0x3a, 0x92, 0xa3,
+ 0xc7, 0x64, 0xdc, 0x02, 0x14, 0xb8, 0x23, 0xdf, 0xa4, 0x86, 0xe9, 0x5a, 0xd4, 0xb0, 0x59, 0xdf,
+ 0x55, 0x4b, 0xc2, 0xc0, 0xd5, 0xd9, 0x8d, 0x08, 0x62, 0xc3, 0xb5, 0x68, 0x8b, 0xf5, 0x5d, 0xbd,
+ 0x1a, 0x4c, 0xac, 0xf1, 0x05, 0x28, 0x04, 0x67, 0x2c, 0x24, 0xaf, 0xd4, 0x8a, 0xc8, 0x90, 0x68,
+ 0x55, 0xfb, 0x6f, 0x1e, 0x56, 0xce, 0x93, 0x62, 0x1f, 0x41, 0xbe, 0xcf, 0x77, 0xa9, 0x66, 0xfe,
+ 0x9f, 0x18, 0x48, 0x9d, 0xc9, 0x20, 0x16, 0xbe, 0x66, 0x10, 0xeb, 0x50, 0x66, 0x34, 0x08, 0xa9,
+ 0x25, 0x33, 0x22, 0x7b, 0xce, 0x9c, 0x02, 0xa9, 0x34, 0x9b, 0x52, 0xb9, 0xaf, 0x95, 0x52, 0x4f,
+ 0x61, 0x25, 0x71, 0xc9, 0xf0, 0x09, 0x1b, 0xc4, 0xb9, 0x79, 0xf7, 0x4d, 0x9e, 0x6c, 0x6b, 0xb1,
+ 0x9e, 0xce, 0xd5, 0xf4, 0x2a, 0x9d, 0x58, 0xe3, 0x26, 0x80, 0xcb, 0xa8, 0xdb, 0x37, 0x2c, 0x6a,
+ 0x3a, 0x6a, 0x71, 0x41, 0x94, 0x3a, 0x9c, 0x32, 0x13, 0x25, 0x57, 0xa2, 0xa6, 0x83, 0x3f, 0x1c,
+ 0xa7, 0xda, 0xd2, 0x82, 0x4c, 0x39, 0x90, 0x2f, 0xd9, 0x4c, 0xb6, 0x1d, 0x43, 0xd5, 0xa7, 0x3c,
+ 0xef, 0xa9, 0x15, 0xed, 0xac, 0x24, 0x9c, 0xd8, 0x7e, 0xe3, 0xce, 0xf4, 0x48, 0x4d, 0x6e, 0x6c,
+ 0xd9, 0x4f, 0x2f, 0xf1, 0x7b, 0x90, 0x00, 0x86, 0x48, 0x2b, 0x10, 0x55, 0xa8, 0x12, 0x83, 0x87,
+ 0x64, 0x48, 0x37, 0x1e, 0x41, 0x75, 0x32, 0x3c, 0x78, 0x1d, 0xf2, 0x41, 0x48, 0xfc, 0x50, 0x64,
+ 0x61, 0x5e, 0x97, 0x0b, 0x8c, 0x20, 0x4b, 0x99, 0x25, 0xaa, 0x5c, 0x5e, 0xe7, 0x3f, 0x37, 0x3e,
+ 0x80, 0xe5, 0x89, 0xc7, 0x9f, 0x57, 0xb1, 0xf6, 0xdb, 0x02, 0xac, 0xcf, 0xcb, 0xb9, 0xb9, 0xe9,
+ 0x7f, 0x01, 0x0a, 0x6c, 0x34, 0x3c, 0xa1, 0xbe, 0x9a, 0x15, 0x16, 0xa2, 0x15, 0xae, 0x43, 0xde,
+ 0x21, 0x27, 0xd4, 0x51, 0x73, 0x9b, 0xca, 0x56, 0x75, 0xe7, 0xce, 0xb9, 0xb2, 0x7a, 0xbb, 0xcd,
+ 0x55, 0x74, 0xa9, 0x89, 0x3f, 0x86, 0x5c, 0x54, 0xe2, 0xb8, 0x85, 0xdb, 0xe7, 0xb3, 0xc0, 0x73,
+ 0x51, 0x17, 0x7a, 0xf8, 0x32, 0x94, 0xf8, 0x5f, 0x19, 0xdb, 0x82, 0xf0, 0xb9, 0xc8, 0x01, 0x1e,
+ 0x57, 0xbc, 0x01, 0x45, 0x91, 0x66, 0x16, 0x8d, 0x5b, 0x43, 0xb2, 0xe6, 0x07, 0x63, 0xd1, 0x3e,
+ 0x19, 0x39, 0xa1, 0xf1, 0x82, 0x38, 0x23, 0x2a, 0x12, 0xa6, 0xa4, 0x57, 0x22, 0xf0, 0x67, 0x1c,
+ 0xc3, 0x57, 0xa1, 0x2c, 0xb3, 0xd2, 0x66, 0x16, 0x7d, 0x25, 0xaa, 0x4f, 0x5e, 0x97, 0x89, 0xda,
+ 0xe2, 0x08, 0x7f, 0xfc, 0xb3, 0xc0, 0x65, 0xf1, 0xd1, 0x8a, 0x47, 0x70, 0x40, 0x3c, 0xfe, 0x83,
+ 0xe9, 0xc2, 0x77, 0x65, 0xfe, 0xf6, 0xa6, 0x73, 0xb1, 0xf6, 0x97, 0x0c, 0xe4, 0xc4, 0xfb, 0xb6,
+ 0x02, 0xe5, 0xa3, 0x4f, 0xbb, 0x9a, 0xd1, 0xec, 0x1c, 0xef, 0xb5, 0x35, 0xa4, 0xe0, 0x2a, 0x80,
+ 0x00, 0x1e, 0xb7, 0x3b, 0xf5, 0x23, 0x94, 0x49, 0xd6, 0xad, 0xc3, 0xa3, 0x87, 0xf7, 0x51, 0x36,
+ 0x51, 0x38, 0x96, 0x40, 0x2e, 0x4d, 0xb8, 0xb7, 0x83, 0xf2, 0x18, 0x41, 0x45, 0x1a, 0x68, 0x3d,
+ 0xd5, 0x9a, 0x0f, 0xef, 0xa3, 0xc2, 0x24, 0x72, 0x6f, 0x07, 0x2d, 0xe1, 0x65, 0x28, 0x09, 0x64,
+ 0xaf, 0xd3, 0x69, 0xa3, 0x62, 0x62, 0xb3, 0x77, 0xa4, 0xb7, 0x0e, 0xf7, 0x51, 0x29, 0xb1, 0xb9,
+ 0xaf, 0x77, 0x8e, 0xbb, 0x08, 0x12, 0x0b, 0x07, 0x5a, 0xaf, 0x57, 0xdf, 0xd7, 0x50, 0x39, 0x61,
+ 0xec, 0x7d, 0x7a, 0xa4, 0xf5, 0x50, 0x65, 0xc2, 0xad, 0x7b, 0x3b, 0x68, 0x39, 0x79, 0x84, 0x76,
+ 0x78, 0x7c, 0x80, 0xaa, 0x78, 0x15, 0x96, 0xe5, 0x23, 0x62, 0x27, 0x56, 0xa6, 0xa0, 0x87, 0xf7,
+ 0x11, 0x1a, 0x3b, 0x22, 0xad, 0xac, 0x4e, 0x00, 0x0f, 0xef, 0x23, 0x5c, 0x6b, 0x40, 0x5e, 0x64,
+ 0x17, 0xc6, 0x50, 0x6d, 0xd7, 0xf7, 0xb4, 0xb6, 0xd1, 0xe9, 0x1e, 0xb5, 0x3a, 0x87, 0xf5, 0x36,
+ 0x52, 0xc6, 0x98, 0xae, 0xfd, 0xf4, 0xb8, 0xa5, 0x6b, 0x4d, 0x94, 0x49, 0x63, 0x5d, 0xad, 0x7e,
+ 0xa4, 0x35, 0x51, 0xb6, 0x66, 0xc2, 0xfa, 0xbc, 0x3a, 0x33, 0xf7, 0xcd, 0x48, 0x1d, 0x71, 0x66,
+ 0xc1, 0x11, 0x0b, 0x5b, 0x33, 0x47, 0xfc, 0x85, 0x02, 0x6b, 0x73, 0x6a, 0xed, 0xdc, 0x87, 0xfc,
+ 0x04, 0xf2, 0x32, 0x45, 0x65, 0xf7, 0xb9, 0x35, 0xb7, 0x68, 0x8b, 0x84, 0x9d, 0xe9, 0x40, 0x42,
+ 0x2f, 0xdd, 0x81, 0xb3, 0x0b, 0x3a, 0x30, 0x37, 0x31, 0xe3, 0xe4, 0xaf, 0x14, 0x50, 0x17, 0xd9,
+ 0x7e, 0x43, 0xa1, 0xc8, 0x4c, 0x14, 0x8a, 0x8f, 0xa6, 0x1d, 0xb8, 0xb6, 0x78, 0x0f, 0x33, 0x5e,
+ 0x7c, 0xa9, 0xc0, 0x85, 0xf9, 0x83, 0xca, 0x5c, 0x1f, 0x3e, 0x86, 0xc2, 0x90, 0x86, 0xa7, 0x6e,
+ 0xdc, 0xac, 0x7f, 0x30, 0xa7, 0x05, 0x70, 0xf1, 0x74, 0xac, 0x22, 0xad, 0x74, 0x0f, 0xc9, 0x2e,
+ 0x9a, 0x36, 0xa4, 0x37, 0x33, 0x9e, 0xfe, 0x3a, 0x03, 0x6f, 0xcf, 0x35, 0x3e, 0xd7, 0xd1, 0x2b,
+ 0x00, 0x36, 0xf3, 0x46, 0xa1, 0x6c, 0xc8, 0xb2, 0x3e, 0x95, 0x04, 0x22, 0xde, 0x7d, 0x5e, 0x7b,
+ 0x46, 0x61, 0x22, 0xcf, 0x0a, 0x39, 0x48, 0x48, 0x10, 0x1e, 0x8d, 0x1d, 0xcd, 0x09, 0x47, 0xdf,
+ 0x5d, 0xb0, 0xd3, 0x99, 0x5e, 0xf7, 0x3e, 0x20, 0xd3, 0xb1, 0x29, 0x0b, 0x8d, 0x20, 0xf4, 0x29,
+ 0x19, 0xda, 0x6c, 0x20, 0x0a, 0x70, 0x71, 0x37, 0xdf, 0x27, 0x4e, 0x40, 0xf5, 0x15, 0x29, 0xee,
+ 0xc5, 0x52, 0xae, 0x21, 0xba, 0x8c, 0x9f, 0xd2, 0x28, 0x4c, 0x68, 0x48, 0x71, 0xa2, 0x51, 0xfb,
+ 0xcd, 0x12, 0x94, 0x53, 0x63, 0x1d, 0xbe, 0x06, 0x95, 0x67, 0xe4, 0x05, 0x31, 0xe2, 0x51, 0x5d,
+ 0x46, 0xa2, 0xcc, 0xb1, 0x6e, 0x34, 0xae, 0xbf, 0x0f, 0xeb, 0x82, 0xe2, 0x8e, 0x42, 0xea, 0x1b,
+ 0xa6, 0x43, 0x82, 0x40, 0x04, 0xad, 0x28, 0xa8, 0x98, 0xcb, 0x3a, 0x5c, 0xd4, 0x88, 0x25, 0xf8,
+ 0x01, 0xac, 0x09, 0x8d, 0xe1, 0xc8, 0x09, 0x6d, 0xcf, 0xa1, 0x06, 0xff, 0x78, 0x08, 0x44, 0x21,
+ 0x4e, 0x3c, 0x5b, 0xe5, 0x8c, 0x83, 0x88, 0xc0, 0x3d, 0x0a, 0xf0, 0x3e, 0x5c, 0x11, 0x6a, 0x03,
+ 0xca, 0xa8, 0x4f, 0x42, 0x6a, 0xd0, 0x5f, 0x8e, 0x88, 0x13, 0x18, 0x84, 0x59, 0xc6, 0x29, 0x09,
+ 0x4e, 0xd5, 0xf5, 0xb4, 0x81, 0x4b, 0x9c, 0xbb, 0x1f, 0x51, 0x35, 0xc1, 0xac, 0x33, 0xeb, 0x13,
+ 0x12, 0x9c, 0xe2, 0x5d, 0xb8, 0x20, 0x0c, 0x05, 0xa1, 0x6f, 0xb3, 0x81, 0x61, 0x9e, 0x52, 0xf3,
+ 0xb9, 0x31, 0x0a, 0xfb, 0x8f, 0xd4, 0xcb, 0x69, 0x0b, 0xc2, 0xc9, 0x9e, 0xe0, 0x34, 0x38, 0xe5,
+ 0x38, 0xec, 0x3f, 0xc2, 0x3d, 0xa8, 0xf0, 0xf3, 0x18, 0xda, 0x9f, 0x53, 0xa3, 0xef, 0xfa, 0xa2,
+ 0xb9, 0x54, 0xe7, 0xbc, 0xdc, 0xa9, 0x20, 0x6e, 0x77, 0x22, 0x85, 0x03, 0xd7, 0xa2, 0xbb, 0xf9,
+ 0x5e, 0x57, 0xd3, 0x9a, 0x7a, 0x39, 0xb6, 0xf2, 0xd8, 0xf5, 0x79, 0x4e, 0x0d, 0xdc, 0x24, 0xc6,
+ 0x65, 0x99, 0x53, 0x03, 0x37, 0x8e, 0xf0, 0x03, 0x58, 0x33, 0x4d, 0xb9, 0x6d, 0xdb, 0x34, 0xa2,
+ 0x29, 0x3f, 0x50, 0xd1, 0x44, 0xbc, 0x4c, 0x73, 0x5f, 0x12, 0xa2, 0x34, 0x0f, 0xf0, 0x87, 0xf0,
+ 0xf6, 0x38, 0x5e, 0x69, 0xc5, 0xd5, 0x99, 0x5d, 0x4e, 0xab, 0x3e, 0x80, 0x35, 0xef, 0x6c, 0x56,
+ 0x11, 0x4f, 0x3c, 0xd1, 0x3b, 0x9b, 0x56, 0xbb, 0x21, 0xbe, 0xdc, 0x7c, 0x6a, 0x92, 0x90, 0x5a,
+ 0xea, 0xc5, 0x34, 0x3b, 0x25, 0xc0, 0x77, 0x01, 0x99, 0xa6, 0x41, 0x19, 0x39, 0x71, 0xa8, 0x41,
+ 0x7c, 0xca, 0x48, 0xa0, 0x5e, 0x4d, 0x93, 0xab, 0xa6, 0xa9, 0x09, 0x69, 0x5d, 0x08, 0xf1, 0x6d,
+ 0x58, 0x75, 0x4f, 0x9e, 0x99, 0x32, 0xb9, 0x0c, 0xcf, 0xa7, 0x7d, 0xfb, 0x95, 0x7a, 0x5d, 0x84,
+ 0x69, 0x85, 0x0b, 0x44, 0x6a, 0x75, 0x05, 0x8c, 0x6f, 0x01, 0x32, 0x83, 0x53, 0xe2, 0x7b, 0xa2,
+ 0xbb, 0x07, 0x1e, 0x31, 0xa9, 0x7a, 0x43, 0x52, 0x25, 0x7e, 0x18, 0xc3, 0xf8, 0x29, 0xac, 0x8f,
+ 0x98, 0xcd, 0x42, 0xea, 0x7b, 0x3e, 0xe5, 0x43, 0xba, 0x7c, 0xd3, 0xd4, 0x7f, 0x2f, 0x2d, 0x18,
+ 0xb3, 0x8f, 0xd3, 0x6c, 0x79, 0xba, 0xfa, 0xda, 0x68, 0x16, 0xac, 0xed, 0x42, 0x25, 0x7d, 0xe8,
+ 0xb8, 0x04, 0xf2, 0xd8, 0x91, 0xc2, 0x7b, 0x68, 0xa3, 0xd3, 0xe4, 0xdd, 0xef, 0x33, 0x0d, 0x65,
+ 0x78, 0x17, 0x6e, 0xb7, 0x8e, 0x34, 0x43, 0x3f, 0x3e, 0x3c, 0x6a, 0x1d, 0x68, 0x28, 0x7b, 0xbb,
+ 0x54, 0xfc, 0xcf, 0x12, 0x7a, 0xfd, 0xfa, 0xf5, 0xeb, 0x4c, 0xed, 0x6f, 0x19, 0xa8, 0x4e, 0x4e,
+ 0xbe, 0xf8, 0xc7, 0x70, 0x31, 0xfe, 0x4c, 0x0d, 0x68, 0x68, 0xbc, 0xb4, 0x7d, 0x91, 0x87, 0x43,
+ 0x22, 0x67, 0xc7, 0x24, 0x84, 0xeb, 0x11, 0xab, 0x47, 0xc3, 0x9f, 0xdb, 0x3e, 0xcf, 0xb2, 0x21,
+ 0x09, 0x71, 0x1b, 0xae, 0x32, 0xd7, 0x08, 0x42, 0xc2, 0x2c, 0xe2, 0x5b, 0xc6, 0xf8, 0x82, 0xc0,
+ 0x20, 0xa6, 0x49, 0x83, 0xc0, 0x95, 0x2d, 0x20, 0xb1, 0xf2, 0x0e, 0x73, 0x7b, 0x11, 0x79, 0x5c,
+ 0x1b, 0xeb, 0x11, 0x75, 0xea, 0xb8, 0xb3, 0x8b, 0x8e, 0xfb, 0x32, 0x94, 0x86, 0xc4, 0x33, 0x28,
+ 0x0b, 0xfd, 0x33, 0x31, 0xaf, 0x15, 0xf5, 0xe2, 0x90, 0x78, 0x1a, 0x5f, 0x7f, 0x73, 0x67, 0x90,
+ 0x8e, 0xe3, 0x3f, 0xb3, 0x50, 0x49, 0xcf, 0x6c, 0x7c, 0x04, 0x36, 0x45, 0x7d, 0x56, 0xc4, 0xeb,
+ 0xfb, 0xde, 0x57, 0x4e, 0x78, 0xdb, 0x0d, 0x5e, 0xb8, 0x77, 0x0b, 0x72, 0x92, 0xd2, 0xa5, 0x26,
+ 0x6f, 0x9a, 0xfc, 0x85, 0xa5, 0x72, 0x3e, 0x2f, 0xea, 0xd1, 0x0a, 0xef, 0x43, 0xe1, 0x59, 0x20,
+ 0x6c, 0x17, 0x84, 0xed, 0xeb, 0x5f, 0x6d, 0xfb, 0x49, 0x4f, 0x18, 0x2f, 0x3d, 0xe9, 0x19, 0x87,
+ 0x1d, 0xfd, 0xa0, 0xde, 0xd6, 0x23, 0x75, 0x7c, 0x09, 0x72, 0x0e, 0xf9, 0xfc, 0x6c, 0xb2, 0xc4,
+ 0x0b, 0xe8, 0xbc, 0x81, 0xbf, 0x04, 0xb9, 0x97, 0x94, 0x3c, 0x9f, 0x2c, 0xac, 0x02, 0xfa, 0x06,
+ 0x53, 0xff, 0x2e, 0xe4, 0x45, 0xbc, 0x30, 0x40, 0x14, 0x31, 0xf4, 0x16, 0x2e, 0x42, 0xae, 0xd1,
+ 0xd1, 0x79, 0xfa, 0x23, 0xa8, 0x48, 0xd4, 0xe8, 0xb6, 0xb4, 0x86, 0x86, 0x32, 0xb5, 0x07, 0x50,
+ 0x90, 0x41, 0xe0, 0xaf, 0x46, 0x12, 0x06, 0xf4, 0x56, 0xb4, 0x8c, 0x6c, 0x28, 0xb1, 0xf4, 0xf8,
+ 0x60, 0x4f, 0xd3, 0x51, 0x26, 0x7d, 0xbc, 0x01, 0x54, 0xd2, 0xe3, 0xda, 0xb7, 0x93, 0x53, 0x7f,
+ 0x55, 0xa0, 0x9c, 0x1a, 0xbf, 0x78, 0xe3, 0x27, 0x8e, 0xe3, 0xbe, 0x34, 0x88, 0x63, 0x93, 0x20,
+ 0x4a, 0x0a, 0x10, 0x50, 0x9d, 0x23, 0xe7, 0x3d, 0xb4, 0x6f, 0xc5, 0xf9, 0x3f, 0x2a, 0x80, 0xa6,
+ 0x47, 0xb7, 0x29, 0x07, 0x95, 0xef, 0xd4, 0xc1, 0x3f, 0x28, 0x50, 0x9d, 0x9c, 0xd7, 0xa6, 0xdc,
+ 0xbb, 0xf6, 0x9d, 0xba, 0xf7, 0x7b, 0x05, 0x96, 0x27, 0xa6, 0xb4, 0xef, 0x95, 0x77, 0xbf, 0xcb,
+ 0xc2, 0xda, 0x1c, 0x3d, 0x5c, 0x8f, 0xc6, 0x59, 0x39, 0x61, 0xff, 0xe8, 0x3c, 0xcf, 0xda, 0xe6,
+ 0xdd, 0xb2, 0x4b, 0xfc, 0x30, 0x9a, 0x7e, 0x6f, 0x01, 0xb2, 0x2d, 0xca, 0x42, 0xbb, 0x6f, 0x53,
+ 0x3f, 0xfa, 0x04, 0x97, 0x33, 0xee, 0xca, 0x18, 0x97, 0x5f, 0xe1, 0x3f, 0x04, 0xec, 0xb9, 0x81,
+ 0x1d, 0xda, 0x2f, 0xa8, 0x61, 0xb3, 0xf8, 0x7b, 0x9d, 0xcf, 0xbc, 0x39, 0x1d, 0xc5, 0x92, 0x16,
+ 0x0b, 0x13, 0x36, 0xa3, 0x03, 0x32, 0xc5, 0xe6, 0xb5, 0x2f, 0xab, 0xa3, 0x58, 0x92, 0xb0, 0xaf,
+ 0x41, 0xc5, 0x72, 0x47, 0x7c, 0x7c, 0x90, 0x3c, 0x5e, 0x6a, 0x15, 0xbd, 0x2c, 0xb1, 0x84, 0x12,
+ 0xcd, 0x77, 0xe3, 0x8b, 0x82, 0x8a, 0x5e, 0x96, 0x98, 0xa4, 0xdc, 0x84, 0x15, 0x32, 0x18, 0xf8,
+ 0xdc, 0x78, 0x6c, 0x48, 0x0e, 0xad, 0xd5, 0x04, 0x16, 0xc4, 0x8d, 0x27, 0x50, 0x8c, 0xe3, 0xc0,
+ 0xbb, 0x19, 0x8f, 0x84, 0xe1, 0xc9, 0xeb, 0x9a, 0xcc, 0x56, 0x49, 0x2f, 0xb2, 0x58, 0x78, 0x0d,
+ 0x2a, 0x76, 0x60, 0x8c, 0xef, 0x0d, 0x33, 0x9b, 0x99, 0xad, 0xa2, 0x5e, 0xb6, 0x83, 0xe4, 0xa2,
+ 0xa8, 0xf6, 0x65, 0x06, 0xaa, 0x93, 0xf7, 0x9e, 0xb8, 0x09, 0x45, 0xc7, 0x35, 0x89, 0x48, 0x04,
+ 0x79, 0xe9, 0xbe, 0xf5, 0x86, 0xab, 0xd2, 0xed, 0x76, 0xc4, 0xd7, 0x13, 0xcd, 0x8d, 0xbf, 0x2b,
+ 0x50, 0x8c, 0x61, 0x7c, 0x01, 0x72, 0x1e, 0x09, 0x4f, 0x85, 0xb9, 0xfc, 0x5e, 0x06, 0x29, 0xba,
+ 0x58, 0x73, 0x3c, 0xf0, 0x08, 0x13, 0x29, 0x10, 0xe1, 0x7c, 0xcd, 0xcf, 0xd5, 0xa1, 0xc4, 0x12,
+ 0xe3, 0xb0, 0x3b, 0x1c, 0x52, 0x16, 0x06, 0xf1, 0xb9, 0x46, 0x78, 0x23, 0x82, 0xf1, 0x1d, 0x58,
+ 0x0d, 0x7d, 0x62, 0x3b, 0x13, 0xdc, 0x9c, 0xe0, 0xa2, 0x58, 0x90, 0x90, 0x77, 0xe1, 0x52, 0x6c,
+ 0xd7, 0xa2, 0x21, 0x31, 0x4f, 0xa9, 0x35, 0x56, 0x2a, 0x88, 0x4b, 0xb5, 0x8b, 0x11, 0xa1, 0x19,
+ 0xc9, 0x63, 0xdd, 0xda, 0x3f, 0x14, 0x58, 0x8d, 0x07, 0x78, 0x2b, 0x09, 0xd6, 0x01, 0x00, 0x61,
+ 0xcc, 0x0d, 0xd3, 0xe1, 0x9a, 0x4d, 0xe5, 0x19, 0xbd, 0xed, 0x7a, 0xa2, 0xa4, 0xa7, 0x0c, 0x6c,
+ 0x0c, 0x01, 0xc6, 0x92, 0x85, 0x61, 0xbb, 0x0a, 0xe5, 0xe8, 0x52, 0x5b, 0xfc, 0x67, 0x44, 0x7e,
+ 0xf5, 0x81, 0x84, 0xf8, 0xa4, 0x8f, 0xd7, 0x21, 0x7f, 0x42, 0x07, 0x36, 0x8b, 0xae, 0xda, 0xe4,
+ 0x22, 0xbe, 0xc0, 0xcb, 0x25, 0x17, 0x78, 0x7b, 0xbf, 0x80, 0x35, 0xd3, 0x1d, 0x4e, 0xbb, 0xbb,
+ 0x87, 0xa6, 0xbe, 0x3c, 0x83, 0x4f, 0x94, 0xcf, 0x60, 0x3c, 0x9d, 0xfd, 0x49, 0x51, 0xbe, 0xc8,
+ 0x64, 0xf7, 0xbb, 0x7b, 0x7f, 0xce, 0x6c, 0xec, 0x4b, 0xd5, 0x6e, 0xbc, 0x53, 0x9d, 0xf6, 0x1d,
+ 0x6a, 0x72, 0xef, 0xff, 0x17, 0x00, 0x00, 0xff, 0xff, 0xd0, 0xf2, 0xf3, 0xa9, 0xf1, 0x19, 0x00,
+ 0x00,
+}
diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go
new file mode 100644
index 0000000..785d6f9
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go
@@ -0,0 +1,715 @@
+// Code generated by protoc-gen-gogo.
+// source: descriptor.proto
+// DO NOT EDIT!
+
+/*
+Package descriptor is a generated protocol buffer package.
+
+It is generated from these files:
+ descriptor.proto
+
+It has these top-level messages:
+ FileDescriptorSet
+ FileDescriptorProto
+ DescriptorProto
+ FieldDescriptorProto
+ OneofDescriptorProto
+ EnumDescriptorProto
+ EnumValueDescriptorProto
+ ServiceDescriptorProto
+ MethodDescriptorProto
+ FileOptions
+ MessageOptions
+ FieldOptions
+ OneofOptions
+ EnumOptions
+ EnumValueOptions
+ ServiceOptions
+ MethodOptions
+ UninterpretedOption
+ SourceCodeInfo
+ GeneratedCodeInfo
+*/
+package descriptor
+
+import fmt "fmt"
+import strings "strings"
+import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
+import sort "sort"
+import strconv "strconv"
+import reflect "reflect"
+import proto "github.com/gogo/protobuf/proto"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+func (this *FileDescriptorSet) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&descriptor.FileDescriptorSet{")
+ if this.File != nil {
+ s = append(s, "File: "+fmt.Sprintf("%#v", this.File)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *FileDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 16)
+ s = append(s, "&descriptor.FileDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Package != nil {
+ s = append(s, "Package: "+valueToGoStringDescriptor(this.Package, "string")+",\n")
+ }
+ if this.Dependency != nil {
+ s = append(s, "Dependency: "+fmt.Sprintf("%#v", this.Dependency)+",\n")
+ }
+ if this.PublicDependency != nil {
+ s = append(s, "PublicDependency: "+fmt.Sprintf("%#v", this.PublicDependency)+",\n")
+ }
+ if this.WeakDependency != nil {
+ s = append(s, "WeakDependency: "+fmt.Sprintf("%#v", this.WeakDependency)+",\n")
+ }
+ if this.MessageType != nil {
+ s = append(s, "MessageType: "+fmt.Sprintf("%#v", this.MessageType)+",\n")
+ }
+ if this.EnumType != nil {
+ s = append(s, "EnumType: "+fmt.Sprintf("%#v", this.EnumType)+",\n")
+ }
+ if this.Service != nil {
+ s = append(s, "Service: "+fmt.Sprintf("%#v", this.Service)+",\n")
+ }
+ if this.Extension != nil {
+ s = append(s, "Extension: "+fmt.Sprintf("%#v", this.Extension)+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.SourceCodeInfo != nil {
+ s = append(s, "SourceCodeInfo: "+fmt.Sprintf("%#v", this.SourceCodeInfo)+",\n")
+ }
+ if this.Syntax != nil {
+ s = append(s, "Syntax: "+valueToGoStringDescriptor(this.Syntax, "string")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *DescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 14)
+ s = append(s, "&descriptor.DescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Field != nil {
+ s = append(s, "Field: "+fmt.Sprintf("%#v", this.Field)+",\n")
+ }
+ if this.Extension != nil {
+ s = append(s, "Extension: "+fmt.Sprintf("%#v", this.Extension)+",\n")
+ }
+ if this.NestedType != nil {
+ s = append(s, "NestedType: "+fmt.Sprintf("%#v", this.NestedType)+",\n")
+ }
+ if this.EnumType != nil {
+ s = append(s, "EnumType: "+fmt.Sprintf("%#v", this.EnumType)+",\n")
+ }
+ if this.ExtensionRange != nil {
+ s = append(s, "ExtensionRange: "+fmt.Sprintf("%#v", this.ExtensionRange)+",\n")
+ }
+ if this.OneofDecl != nil {
+ s = append(s, "OneofDecl: "+fmt.Sprintf("%#v", this.OneofDecl)+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.ReservedRange != nil {
+ s = append(s, "ReservedRange: "+fmt.Sprintf("%#v", this.ReservedRange)+",\n")
+ }
+ if this.ReservedName != nil {
+ s = append(s, "ReservedName: "+fmt.Sprintf("%#v", this.ReservedName)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *DescriptorProto_ExtensionRange) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.DescriptorProto_ExtensionRange{")
+ if this.Start != nil {
+ s = append(s, "Start: "+valueToGoStringDescriptor(this.Start, "int32")+",\n")
+ }
+ if this.End != nil {
+ s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *DescriptorProto_ReservedRange) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.DescriptorProto_ReservedRange{")
+ if this.Start != nil {
+ s = append(s, "Start: "+valueToGoStringDescriptor(this.Start, "int32")+",\n")
+ }
+ if this.End != nil {
+ s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *FieldDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 14)
+ s = append(s, "&descriptor.FieldDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Number != nil {
+ s = append(s, "Number: "+valueToGoStringDescriptor(this.Number, "int32")+",\n")
+ }
+ if this.Label != nil {
+ s = append(s, "Label: "+valueToGoStringDescriptor(this.Label, "descriptor.FieldDescriptorProto_Label")+",\n")
+ }
+ if this.Type != nil {
+ s = append(s, "Type: "+valueToGoStringDescriptor(this.Type, "descriptor.FieldDescriptorProto_Type")+",\n")
+ }
+ if this.TypeName != nil {
+ s = append(s, "TypeName: "+valueToGoStringDescriptor(this.TypeName, "string")+",\n")
+ }
+ if this.Extendee != nil {
+ s = append(s, "Extendee: "+valueToGoStringDescriptor(this.Extendee, "string")+",\n")
+ }
+ if this.DefaultValue != nil {
+ s = append(s, "DefaultValue: "+valueToGoStringDescriptor(this.DefaultValue, "string")+",\n")
+ }
+ if this.OneofIndex != nil {
+ s = append(s, "OneofIndex: "+valueToGoStringDescriptor(this.OneofIndex, "int32")+",\n")
+ }
+ if this.JsonName != nil {
+ s = append(s, "JsonName: "+valueToGoStringDescriptor(this.JsonName, "string")+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *OneofDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.OneofDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *EnumDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&descriptor.EnumDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Value != nil {
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *EnumValueDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&descriptor.EnumValueDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Number != nil {
+ s = append(s, "Number: "+valueToGoStringDescriptor(this.Number, "int32")+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *ServiceDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&descriptor.ServiceDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Method != nil {
+ s = append(s, "Method: "+fmt.Sprintf("%#v", this.Method)+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *MethodDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 10)
+ s = append(s, "&descriptor.MethodDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.InputType != nil {
+ s = append(s, "InputType: "+valueToGoStringDescriptor(this.InputType, "string")+",\n")
+ }
+ if this.OutputType != nil {
+ s = append(s, "OutputType: "+valueToGoStringDescriptor(this.OutputType, "string")+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.ClientStreaming != nil {
+ s = append(s, "ClientStreaming: "+valueToGoStringDescriptor(this.ClientStreaming, "bool")+",\n")
+ }
+ if this.ServerStreaming != nil {
+ s = append(s, "ServerStreaming: "+valueToGoStringDescriptor(this.ServerStreaming, "bool")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *FileOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 19)
+ s = append(s, "&descriptor.FileOptions{")
+ if this.JavaPackage != nil {
+ s = append(s, "JavaPackage: "+valueToGoStringDescriptor(this.JavaPackage, "string")+",\n")
+ }
+ if this.JavaOuterClassname != nil {
+ s = append(s, "JavaOuterClassname: "+valueToGoStringDescriptor(this.JavaOuterClassname, "string")+",\n")
+ }
+ if this.JavaMultipleFiles != nil {
+ s = append(s, "JavaMultipleFiles: "+valueToGoStringDescriptor(this.JavaMultipleFiles, "bool")+",\n")
+ }
+ if this.JavaGenerateEqualsAndHash != nil {
+ s = append(s, "JavaGenerateEqualsAndHash: "+valueToGoStringDescriptor(this.JavaGenerateEqualsAndHash, "bool")+",\n")
+ }
+ if this.JavaStringCheckUtf8 != nil {
+ s = append(s, "JavaStringCheckUtf8: "+valueToGoStringDescriptor(this.JavaStringCheckUtf8, "bool")+",\n")
+ }
+ if this.OptimizeFor != nil {
+ s = append(s, "OptimizeFor: "+valueToGoStringDescriptor(this.OptimizeFor, "descriptor.FileOptions_OptimizeMode")+",\n")
+ }
+ if this.GoPackage != nil {
+ s = append(s, "GoPackage: "+valueToGoStringDescriptor(this.GoPackage, "string")+",\n")
+ }
+ if this.CcGenericServices != nil {
+ s = append(s, "CcGenericServices: "+valueToGoStringDescriptor(this.CcGenericServices, "bool")+",\n")
+ }
+ if this.JavaGenericServices != nil {
+ s = append(s, "JavaGenericServices: "+valueToGoStringDescriptor(this.JavaGenericServices, "bool")+",\n")
+ }
+ if this.PyGenericServices != nil {
+ s = append(s, "PyGenericServices: "+valueToGoStringDescriptor(this.PyGenericServices, "bool")+",\n")
+ }
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.CcEnableArenas != nil {
+ s = append(s, "CcEnableArenas: "+valueToGoStringDescriptor(this.CcEnableArenas, "bool")+",\n")
+ }
+ if this.ObjcClassPrefix != nil {
+ s = append(s, "ObjcClassPrefix: "+valueToGoStringDescriptor(this.ObjcClassPrefix, "string")+",\n")
+ }
+ if this.CsharpNamespace != nil {
+ s = append(s, "CsharpNamespace: "+valueToGoStringDescriptor(this.CsharpNamespace, "string")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *MessageOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 9)
+ s = append(s, "&descriptor.MessageOptions{")
+ if this.MessageSetWireFormat != nil {
+ s = append(s, "MessageSetWireFormat: "+valueToGoStringDescriptor(this.MessageSetWireFormat, "bool")+",\n")
+ }
+ if this.NoStandardDescriptorAccessor != nil {
+ s = append(s, "NoStandardDescriptorAccessor: "+valueToGoStringDescriptor(this.NoStandardDescriptorAccessor, "bool")+",\n")
+ }
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.MapEntry != nil {
+ s = append(s, "MapEntry: "+valueToGoStringDescriptor(this.MapEntry, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *FieldOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 11)
+ s = append(s, "&descriptor.FieldOptions{")
+ if this.Ctype != nil {
+ s = append(s, "Ctype: "+valueToGoStringDescriptor(this.Ctype, "descriptor.FieldOptions_CType")+",\n")
+ }
+ if this.Packed != nil {
+ s = append(s, "Packed: "+valueToGoStringDescriptor(this.Packed, "bool")+",\n")
+ }
+ if this.Jstype != nil {
+ s = append(s, "Jstype: "+valueToGoStringDescriptor(this.Jstype, "descriptor.FieldOptions_JSType")+",\n")
+ }
+ if this.Lazy != nil {
+ s = append(s, "Lazy: "+valueToGoStringDescriptor(this.Lazy, "bool")+",\n")
+ }
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.Weak != nil {
+ s = append(s, "Weak: "+valueToGoStringDescriptor(this.Weak, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *OneofOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&descriptor.OneofOptions{")
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *EnumOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&descriptor.EnumOptions{")
+ if this.AllowAlias != nil {
+ s = append(s, "AllowAlias: "+valueToGoStringDescriptor(this.AllowAlias, "bool")+",\n")
+ }
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *EnumValueOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.EnumValueOptions{")
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *ServiceOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.ServiceOptions{")
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *MethodOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.MethodOptions{")
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *UninterpretedOption) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 11)
+ s = append(s, "&descriptor.UninterpretedOption{")
+ if this.Name != nil {
+ s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n")
+ }
+ if this.IdentifierValue != nil {
+ s = append(s, "IdentifierValue: "+valueToGoStringDescriptor(this.IdentifierValue, "string")+",\n")
+ }
+ if this.PositiveIntValue != nil {
+ s = append(s, "PositiveIntValue: "+valueToGoStringDescriptor(this.PositiveIntValue, "uint64")+",\n")
+ }
+ if this.NegativeIntValue != nil {
+ s = append(s, "NegativeIntValue: "+valueToGoStringDescriptor(this.NegativeIntValue, "int64")+",\n")
+ }
+ if this.DoubleValue != nil {
+ s = append(s, "DoubleValue: "+valueToGoStringDescriptor(this.DoubleValue, "float64")+",\n")
+ }
+ if this.StringValue != nil {
+ s = append(s, "StringValue: "+valueToGoStringDescriptor(this.StringValue, "byte")+",\n")
+ }
+ if this.AggregateValue != nil {
+ s = append(s, "AggregateValue: "+valueToGoStringDescriptor(this.AggregateValue, "string")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *UninterpretedOption_NamePart) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.UninterpretedOption_NamePart{")
+ if this.NamePart != nil {
+ s = append(s, "NamePart: "+valueToGoStringDescriptor(this.NamePart, "string")+",\n")
+ }
+ if this.IsExtension != nil {
+ s = append(s, "IsExtension: "+valueToGoStringDescriptor(this.IsExtension, "bool")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *SourceCodeInfo) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&descriptor.SourceCodeInfo{")
+ if this.Location != nil {
+ s = append(s, "Location: "+fmt.Sprintf("%#v", this.Location)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *SourceCodeInfo_Location) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 9)
+ s = append(s, "&descriptor.SourceCodeInfo_Location{")
+ if this.Path != nil {
+ s = append(s, "Path: "+fmt.Sprintf("%#v", this.Path)+",\n")
+ }
+ if this.Span != nil {
+ s = append(s, "Span: "+fmt.Sprintf("%#v", this.Span)+",\n")
+ }
+ if this.LeadingComments != nil {
+ s = append(s, "LeadingComments: "+valueToGoStringDescriptor(this.LeadingComments, "string")+",\n")
+ }
+ if this.TrailingComments != nil {
+ s = append(s, "TrailingComments: "+valueToGoStringDescriptor(this.TrailingComments, "string")+",\n")
+ }
+ if this.LeadingDetachedComments != nil {
+ s = append(s, "LeadingDetachedComments: "+fmt.Sprintf("%#v", this.LeadingDetachedComments)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *GeneratedCodeInfo) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&descriptor.GeneratedCodeInfo{")
+ if this.Annotation != nil {
+ s = append(s, "Annotation: "+fmt.Sprintf("%#v", this.Annotation)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *GeneratedCodeInfo_Annotation) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 8)
+ s = append(s, "&descriptor.GeneratedCodeInfo_Annotation{")
+ if this.Path != nil {
+ s = append(s, "Path: "+fmt.Sprintf("%#v", this.Path)+",\n")
+ }
+ if this.SourceFile != nil {
+ s = append(s, "SourceFile: "+valueToGoStringDescriptor(this.SourceFile, "string")+",\n")
+ }
+ if this.Begin != nil {
+ s = append(s, "Begin: "+valueToGoStringDescriptor(this.Begin, "int32")+",\n")
+ }
+ if this.End != nil {
+ s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringDescriptor(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func extensionToGoStringDescriptor(m github_com_gogo_protobuf_proto.Message) string {
+ e := github_com_gogo_protobuf_proto.GetUnsafeExtensionsMap(m)
+ if e == nil {
+ return "nil"
+ }
+ s := "proto.NewUnsafeXXX_InternalExtensions(map[int32]proto.Extension{"
+ keys := make([]int, 0, len(e))
+ for k := range e {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+ ss := []string{}
+ for _, k := range keys {
+ ss = append(ss, strconv.Itoa(k)+": "+e[int32(k)].GoString())
+ }
+ s += strings.Join(ss, ",") + "})"
+ return s
+}
diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/helper.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/helper.go
new file mode 100644
index 0000000..e0846a3
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/helper.go
@@ -0,0 +1,390 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 descriptor
+
+import (
+ "strings"
+)
+
+func (msg *DescriptorProto) GetMapFields() (*FieldDescriptorProto, *FieldDescriptorProto) {
+ if !msg.GetOptions().GetMapEntry() {
+ return nil, nil
+ }
+ return msg.GetField()[0], msg.GetField()[1]
+}
+
+func dotToUnderscore(r rune) rune {
+ if r == '.' {
+ return '_'
+ }
+ return r
+}
+
+func (field *FieldDescriptorProto) WireType() (wire int) {
+ switch *field.Type {
+ case FieldDescriptorProto_TYPE_DOUBLE:
+ return 1
+ case FieldDescriptorProto_TYPE_FLOAT:
+ return 5
+ case FieldDescriptorProto_TYPE_INT64:
+ return 0
+ case FieldDescriptorProto_TYPE_UINT64:
+ return 0
+ case FieldDescriptorProto_TYPE_INT32:
+ return 0
+ case FieldDescriptorProto_TYPE_UINT32:
+ return 0
+ case FieldDescriptorProto_TYPE_FIXED64:
+ return 1
+ case FieldDescriptorProto_TYPE_FIXED32:
+ return 5
+ case FieldDescriptorProto_TYPE_BOOL:
+ return 0
+ case FieldDescriptorProto_TYPE_STRING:
+ return 2
+ case FieldDescriptorProto_TYPE_GROUP:
+ return 2
+ case FieldDescriptorProto_TYPE_MESSAGE:
+ return 2
+ case FieldDescriptorProto_TYPE_BYTES:
+ return 2
+ case FieldDescriptorProto_TYPE_ENUM:
+ return 0
+ case FieldDescriptorProto_TYPE_SFIXED32:
+ return 5
+ case FieldDescriptorProto_TYPE_SFIXED64:
+ return 1
+ case FieldDescriptorProto_TYPE_SINT32:
+ return 0
+ case FieldDescriptorProto_TYPE_SINT64:
+ return 0
+ }
+ panic("unreachable")
+}
+
+func (field *FieldDescriptorProto) GetKeyUint64() (x uint64) {
+ packed := field.IsPacked()
+ wireType := field.WireType()
+ fieldNumber := field.GetNumber()
+ if packed {
+ wireType = 2
+ }
+ x = uint64(uint32(fieldNumber)<<3 | uint32(wireType))
+ return x
+}
+
+func (field *FieldDescriptorProto) GetKey3Uint64() (x uint64) {
+ packed := field.IsPacked3()
+ wireType := field.WireType()
+ fieldNumber := field.GetNumber()
+ if packed {
+ wireType = 2
+ }
+ x = uint64(uint32(fieldNumber)<<3 | uint32(wireType))
+ return x
+}
+
+func (field *FieldDescriptorProto) GetKey() []byte {
+ x := field.GetKeyUint64()
+ i := 0
+ keybuf := make([]byte, 0)
+ for i = 0; x > 127; i++ {
+ keybuf = append(keybuf, 0x80|uint8(x&0x7F))
+ x >>= 7
+ }
+ keybuf = append(keybuf, uint8(x))
+ return keybuf
+}
+
+func (field *FieldDescriptorProto) GetKey3() []byte {
+ x := field.GetKey3Uint64()
+ i := 0
+ keybuf := make([]byte, 0)
+ for i = 0; x > 127; i++ {
+ keybuf = append(keybuf, 0x80|uint8(x&0x7F))
+ x >>= 7
+ }
+ keybuf = append(keybuf, uint8(x))
+ return keybuf
+}
+
+func (desc *FileDescriptorSet) GetField(packageName, messageName, fieldName string) *FieldDescriptorProto {
+ msg := desc.GetMessage(packageName, messageName)
+ if msg == nil {
+ return nil
+ }
+ for _, field := range msg.GetField() {
+ if field.GetName() == fieldName {
+ return field
+ }
+ }
+ return nil
+}
+
+func (file *FileDescriptorProto) GetMessage(typeName string) *DescriptorProto {
+ for _, msg := range file.GetMessageType() {
+ if msg.GetName() == typeName {
+ return msg
+ }
+ nes := file.GetNestedMessage(msg, strings.TrimPrefix(typeName, msg.GetName()+"."))
+ if nes != nil {
+ return nes
+ }
+ }
+ return nil
+}
+
+func (file *FileDescriptorProto) GetNestedMessage(msg *DescriptorProto, typeName string) *DescriptorProto {
+ for _, nes := range msg.GetNestedType() {
+ if nes.GetName() == typeName {
+ return nes
+ }
+ res := file.GetNestedMessage(nes, strings.TrimPrefix(typeName, nes.GetName()+"."))
+ if res != nil {
+ return res
+ }
+ }
+ return nil
+}
+
+func (desc *FileDescriptorSet) GetMessage(packageName string, typeName string) *DescriptorProto {
+ for _, file := range desc.GetFile() {
+ if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) {
+ continue
+ }
+ for _, msg := range file.GetMessageType() {
+ if msg.GetName() == typeName {
+ return msg
+ }
+ }
+ for _, msg := range file.GetMessageType() {
+ for _, nes := range msg.GetNestedType() {
+ if nes.GetName() == typeName {
+ return nes
+ }
+ if msg.GetName()+"."+nes.GetName() == typeName {
+ return nes
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (desc *FileDescriptorSet) IsProto3(packageName string, typeName string) bool {
+ for _, file := range desc.GetFile() {
+ if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) {
+ continue
+ }
+ for _, msg := range file.GetMessageType() {
+ if msg.GetName() == typeName {
+ return file.GetSyntax() == "proto3"
+ }
+ }
+ for _, msg := range file.GetMessageType() {
+ for _, nes := range msg.GetNestedType() {
+ if nes.GetName() == typeName {
+ return file.GetSyntax() == "proto3"
+ }
+ if msg.GetName()+"."+nes.GetName() == typeName {
+ return file.GetSyntax() == "proto3"
+ }
+ }
+ }
+ }
+ return false
+}
+
+func (msg *DescriptorProto) IsExtendable() bool {
+ return len(msg.GetExtensionRange()) > 0
+}
+
+func (desc *FileDescriptorSet) FindExtension(packageName string, typeName string, fieldName string) (extPackageName string, field *FieldDescriptorProto) {
+ parent := desc.GetMessage(packageName, typeName)
+ if parent == nil {
+ return "", nil
+ }
+ if !parent.IsExtendable() {
+ return "", nil
+ }
+ extendee := "." + packageName + "." + typeName
+ for _, file := range desc.GetFile() {
+ for _, ext := range file.GetExtension() {
+ if strings.Map(dotToUnderscore, file.GetPackage()) == strings.Map(dotToUnderscore, packageName) {
+ if !(ext.GetExtendee() == typeName || ext.GetExtendee() == extendee) {
+ continue
+ }
+ } else {
+ if ext.GetExtendee() != extendee {
+ continue
+ }
+ }
+ if ext.GetName() == fieldName {
+ return file.GetPackage(), ext
+ }
+ }
+ }
+ return "", nil
+}
+
+func (desc *FileDescriptorSet) FindExtensionByFieldNumber(packageName string, typeName string, fieldNum int32) (extPackageName string, field *FieldDescriptorProto) {
+ parent := desc.GetMessage(packageName, typeName)
+ if parent == nil {
+ return "", nil
+ }
+ if !parent.IsExtendable() {
+ return "", nil
+ }
+ extendee := "." + packageName + "." + typeName
+ for _, file := range desc.GetFile() {
+ for _, ext := range file.GetExtension() {
+ if strings.Map(dotToUnderscore, file.GetPackage()) == strings.Map(dotToUnderscore, packageName) {
+ if !(ext.GetExtendee() == typeName || ext.GetExtendee() == extendee) {
+ continue
+ }
+ } else {
+ if ext.GetExtendee() != extendee {
+ continue
+ }
+ }
+ if ext.GetNumber() == fieldNum {
+ return file.GetPackage(), ext
+ }
+ }
+ }
+ return "", nil
+}
+
+func (desc *FileDescriptorSet) FindMessage(packageName string, typeName string, fieldName string) (msgPackageName string, msgName string) {
+ parent := desc.GetMessage(packageName, typeName)
+ if parent == nil {
+ return "", ""
+ }
+ field := parent.GetFieldDescriptor(fieldName)
+ if field == nil {
+ var extPackageName string
+ extPackageName, field = desc.FindExtension(packageName, typeName, fieldName)
+ if field == nil {
+ return "", ""
+ }
+ packageName = extPackageName
+ }
+ typeNames := strings.Split(field.GetTypeName(), ".")
+ if len(typeNames) == 1 {
+ msg := desc.GetMessage(packageName, typeName)
+ if msg == nil {
+ return "", ""
+ }
+ return packageName, msg.GetName()
+ }
+ if len(typeNames) > 2 {
+ for i := 1; i < len(typeNames)-1; i++ {
+ packageName = strings.Join(typeNames[1:len(typeNames)-i], ".")
+ typeName = strings.Join(typeNames[len(typeNames)-i:], ".")
+ msg := desc.GetMessage(packageName, typeName)
+ if msg != nil {
+ typeNames := strings.Split(msg.GetName(), ".")
+ if len(typeNames) == 1 {
+ return packageName, msg.GetName()
+ }
+ return strings.Join(typeNames[1:len(typeNames)-1], "."), typeNames[len(typeNames)-1]
+ }
+ }
+ }
+ return "", ""
+}
+
+func (msg *DescriptorProto) GetFieldDescriptor(fieldName string) *FieldDescriptorProto {
+ for _, field := range msg.GetField() {
+ if field.GetName() == fieldName {
+ return field
+ }
+ }
+ return nil
+}
+
+func (desc *FileDescriptorSet) GetEnum(packageName string, typeName string) *EnumDescriptorProto {
+ for _, file := range desc.GetFile() {
+ if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) {
+ continue
+ }
+ for _, enum := range file.GetEnumType() {
+ if enum.GetName() == typeName {
+ return enum
+ }
+ }
+ }
+ return nil
+}
+
+func (f *FieldDescriptorProto) IsEnum() bool {
+ return *f.Type == FieldDescriptorProto_TYPE_ENUM
+}
+
+func (f *FieldDescriptorProto) IsMessage() bool {
+ return *f.Type == FieldDescriptorProto_TYPE_MESSAGE
+}
+
+func (f *FieldDescriptorProto) IsBytes() bool {
+ return *f.Type == FieldDescriptorProto_TYPE_BYTES
+}
+
+func (f *FieldDescriptorProto) IsRepeated() bool {
+ return f.Label != nil && *f.Label == FieldDescriptorProto_LABEL_REPEATED
+}
+
+func (f *FieldDescriptorProto) IsString() bool {
+ return *f.Type == FieldDescriptorProto_TYPE_STRING
+}
+
+func (f *FieldDescriptorProto) IsBool() bool {
+ return *f.Type == FieldDescriptorProto_TYPE_BOOL
+}
+
+func (f *FieldDescriptorProto) IsRequired() bool {
+ return f.Label != nil && *f.Label == FieldDescriptorProto_LABEL_REQUIRED
+}
+
+func (f *FieldDescriptorProto) IsPacked() bool {
+ return f.Options != nil && f.GetOptions().GetPacked()
+}
+
+func (f *FieldDescriptorProto) IsPacked3() bool {
+ if f.IsRepeated() && f.IsScalar() {
+ if f.Options == nil || f.GetOptions().Packed == nil {
+ return true
+ }
+ return f.Options != nil && f.GetOptions().GetPacked()
+ }
+ return false
+}
+
+func (m *DescriptorProto) HasExtension() bool {
+ return len(m.ExtensionRange) > 0
+}
diff --git a/vendor/github.com/gogo/protobuf/sortkeys/sortkeys.go b/vendor/github.com/gogo/protobuf/sortkeys/sortkeys.go
new file mode 100644
index 0000000..ceadde6
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/sortkeys/sortkeys.go
@@ -0,0 +1,101 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 sortkeys
+
+import (
+ "sort"
+)
+
+func Strings(l []string) {
+ sort.Strings(l)
+}
+
+func Float64s(l []float64) {
+ sort.Float64s(l)
+}
+
+func Float32s(l []float32) {
+ sort.Sort(Float32Slice(l))
+}
+
+func Int64s(l []int64) {
+ sort.Sort(Int64Slice(l))
+}
+
+func Int32s(l []int32) {
+ sort.Sort(Int32Slice(l))
+}
+
+func Uint64s(l []uint64) {
+ sort.Sort(Uint64Slice(l))
+}
+
+func Uint32s(l []uint32) {
+ sort.Sort(Uint32Slice(l))
+}
+
+func Bools(l []bool) {
+ sort.Sort(BoolSlice(l))
+}
+
+type BoolSlice []bool
+
+func (p BoolSlice) Len() int { return len(p) }
+func (p BoolSlice) Less(i, j int) bool { return p[j] }
+func (p BoolSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+
+type Int64Slice []int64
+
+func (p Int64Slice) Len() int { return len(p) }
+func (p Int64Slice) Less(i, j int) bool { return p[i] < p[j] }
+func (p Int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+
+type Int32Slice []int32
+
+func (p Int32Slice) Len() int { return len(p) }
+func (p Int32Slice) Less(i, j int) bool { return p[i] < p[j] }
+func (p Int32Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+
+type Uint64Slice []uint64
+
+func (p Uint64Slice) Len() int { return len(p) }
+func (p Uint64Slice) Less(i, j int) bool { return p[i] < p[j] }
+func (p Uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+
+type Uint32Slice []uint32
+
+func (p Uint32Slice) Len() int { return len(p) }
+func (p Uint32Slice) Less(i, j int) bool { return p[i] < p[j] }
+func (p Uint32Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+
+type Float32Slice []float32
+
+func (p Float32Slice) Len() int { return len(p) }
+func (p Float32Slice) Less(i, j int) bool { return p[i] < p[j] }
+func (p Float32Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
diff --git a/vendor/github.com/gogo/protobuf/types/any.go b/vendor/github.com/gogo/protobuf/types/any.go
new file mode 100644
index 0000000..c10caf4
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/any.go
@@ -0,0 +1,135 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package types
+
+// This file implements functions to marshal proto.Message to/from
+// google.protobuf.Any message.
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+
+ "github.com/gogo/protobuf/proto"
+)
+
+const googleApis = "type.googleapis.com/"
+
+// AnyMessageName returns the name of the message contained in a google.protobuf.Any message.
+//
+// Note that regular type assertions should be done using the Is
+// function. AnyMessageName is provided for less common use cases like filtering a
+// sequence of Any messages based on a set of allowed message type names.
+func AnyMessageName(any *Any) (string, error) {
+ slash := strings.LastIndex(any.TypeUrl, "/")
+ if slash < 0 {
+ return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl)
+ }
+ return any.TypeUrl[slash+1:], nil
+}
+
+// MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any.
+func MarshalAny(pb proto.Message) (*Any, error) {
+ value, err := proto.Marshal(pb)
+ if err != nil {
+ return nil, err
+ }
+ return &Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil
+}
+
+// DynamicAny is a value that can be passed to UnmarshalAny to automatically
+// allocate a proto.Message for the type specified in a google.protobuf.Any
+// message. The allocated message is stored in the embedded proto.Message.
+//
+// Example:
+//
+// var x ptypes.DynamicAny
+// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... }
+// fmt.Printf("unmarshaled message: %v", x.Message)
+type DynamicAny struct {
+ proto.Message
+}
+
+// Empty returns a new proto.Message of the type specified in a
+// google.protobuf.Any message. It returns an error if corresponding message
+// type isn't linked in.
+func EmptyAny(any *Any) (proto.Message, error) {
+ aname, err := AnyMessageName(any)
+ if err != nil {
+ return nil, err
+ }
+
+ t := proto.MessageType(aname)
+ if t == nil {
+ return nil, fmt.Errorf("any: message type %q isn't linked in", aname)
+ }
+ return reflect.New(t.Elem()).Interface().(proto.Message), nil
+}
+
+// UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any
+// message and places the decoded result in pb. It returns an error if type of
+// contents of Any message does not match type of pb message.
+//
+// pb can be a proto.Message, or a *DynamicAny.
+func UnmarshalAny(any *Any, pb proto.Message) error {
+ if d, ok := pb.(*DynamicAny); ok {
+ if d.Message == nil {
+ var err error
+ d.Message, err = EmptyAny(any)
+ if err != nil {
+ return err
+ }
+ }
+ return UnmarshalAny(any, d.Message)
+ }
+
+ aname, err := AnyMessageName(any)
+ if err != nil {
+ return err
+ }
+
+ mname := proto.MessageName(pb)
+ if aname != mname {
+ return fmt.Errorf("mismatched message type: got %q want %q", aname, mname)
+ }
+ return proto.Unmarshal(any.Value, pb)
+}
+
+// Is returns true if any value contains a given message type.
+func Is(any *Any, pb proto.Message) bool {
+ aname, err := AnyMessageName(any)
+ if err != nil {
+ return false
+ }
+
+ return aname == proto.MessageName(pb)
+}
diff --git a/vendor/github.com/gogo/protobuf/types/any.pb.go b/vendor/github.com/gogo/protobuf/types/any.pb.go
new file mode 100644
index 0000000..50e9b36
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/any.pb.go
@@ -0,0 +1,666 @@
+// Code generated by protoc-gen-gogo.
+// source: any.proto
+// DO NOT EDIT!
+
+/*
+ Package types is a generated protocol buffer package.
+
+ It is generated from these files:
+ any.proto
+
+ It has these top-level messages:
+ Any
+*/
+package types
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+import bytes "bytes"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+// `Any` contains an arbitrary serialized protocol buffer message along with a
+// URL that describes the type of the serialized message.
+//
+// Protobuf library provides support to pack/unpack Any values in the form
+// of utility functions or additional generated methods of the Any type.
+//
+// Example 1: Pack and unpack a message in C++.
+//
+// Foo foo = ...;
+// Any any;
+// any.PackFrom(foo);
+// ...
+// if (any.UnpackTo(&foo)) {
+// ...
+// }
+//
+// Example 2: Pack and unpack a message in Java.
+//
+// Foo foo = ...;
+// Any any = Any.pack(foo);
+// ...
+// if (any.is(Foo.class)) {
+// foo = any.unpack(Foo.class);
+// }
+//
+// Example 3: Pack and unpack a message in Python.
+//
+// foo = Foo(...)
+// any = Any()
+// any.Pack(foo)
+// ...
+// if any.Is(Foo.DESCRIPTOR):
+// any.Unpack(foo)
+// ...
+//
+// The pack methods provided by protobuf library will by default use
+// 'type.googleapis.com/full.type.name' as the type URL and the unpack
+// methods only use the fully qualified type name after the last '/'
+// in the type URL, for example "foo.bar.com/x/y.z" will yield type
+// name "y.z".
+//
+//
+// JSON
+// ====
+// The JSON representation of an `Any` value uses the regular
+// representation of the deserialized, embedded message, with an
+// additional field `@type` which contains the type URL. Example:
+//
+// package google.profile;
+// message Person {
+// string first_name = 1;
+// string last_name = 2;
+// }
+//
+// {
+// "@type": "type.googleapis.com/google.profile.Person",
+// "firstName": <string>,
+// "lastName": <string>
+// }
+//
+// If the embedded message type is well-known and has a custom JSON
+// representation, that representation will be embedded adding a field
+// `value` which holds the custom JSON in addition to the `@type`
+// field. Example (for message [google.protobuf.Duration][]):
+//
+// {
+// "@type": "type.googleapis.com/google.protobuf.Duration",
+// "value": "1.212s"
+// }
+//
+type Any struct {
+ // A URL/resource name whose content describes the type of the
+ // serialized protocol buffer message.
+ //
+ // For URLs which use the scheme `http`, `https`, or no scheme, the
+ // following restrictions and interpretations apply:
+ //
+ // * If no scheme is provided, `https` is assumed.
+ // * The last segment of the URL's path must represent the fully
+ // qualified name of the type (as in `path/google.protobuf.Duration`).
+ // The name should be in a canonical form (e.g., leading "." is
+ // not accepted).
+ // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ // value in binary format, or produce an error.
+ // * Applications are allowed to cache lookup results based on the
+ // URL, or have them precompiled into a binary to avoid any
+ // lookup. Therefore, binary compatibility needs to be preserved
+ // on changes to types. (Use versioned type names to manage
+ // breaking changes.)
+ //
+ // Schemes other than `http`, `https` (or the empty scheme) might be
+ // used with implementation specific semantics.
+ //
+ TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"`
+ // Must be a valid serialized protocol buffer of the above specified type.
+ Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *Any) Reset() { *m = Any{} }
+func (*Any) ProtoMessage() {}
+func (*Any) Descriptor() ([]byte, []int) { return fileDescriptorAny, []int{0} }
+func (*Any) XXX_WellKnownType() string { return "Any" }
+
+func (m *Any) GetTypeUrl() string {
+ if m != nil {
+ return m.TypeUrl
+ }
+ return ""
+}
+
+func (m *Any) GetValue() []byte {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Any)(nil), "google.protobuf.Any")
+}
+func (this *Any) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*Any)
+ if !ok {
+ that2, ok := that.(Any)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.TypeUrl != that1.TypeUrl {
+ if this.TypeUrl < that1.TypeUrl {
+ return -1
+ }
+ return 1
+ }
+ if c := bytes.Compare(this.Value, that1.Value); c != 0 {
+ return c
+ }
+ return 0
+}
+func (this *Any) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Any)
+ if !ok {
+ that2, ok := that.(Any)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.TypeUrl != that1.TypeUrl {
+ return false
+ }
+ if !bytes.Equal(this.Value, that1.Value) {
+ return false
+ }
+ return true
+}
+func (this *Any) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&types.Any{")
+ s = append(s, "TypeUrl: "+fmt.Sprintf("%#v", this.TypeUrl)+",\n")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringAny(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func (m *Any) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Any) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.TypeUrl) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintAny(dAtA, i, uint64(len(m.TypeUrl)))
+ i += copy(dAtA[i:], m.TypeUrl)
+ }
+ if len(m.Value) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintAny(dAtA, i, uint64(len(m.Value)))
+ i += copy(dAtA[i:], m.Value)
+ }
+ return i, nil
+}
+
+func encodeFixed64Any(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Any(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintAny(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func NewPopulatedAny(r randyAny, easy bool) *Any {
+ this := &Any{}
+ this.TypeUrl = string(randStringAny(r))
+ v1 := r.Intn(100)
+ this.Value = make([]byte, v1)
+ for i := 0; i < v1; i++ {
+ this.Value[i] = byte(r.Intn(256))
+ }
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+type randyAny interface {
+ Float32() float32
+ Float64() float64
+ Int63() int64
+ Int31() int32
+ Uint32() uint32
+ Intn(n int) int
+}
+
+func randUTF8RuneAny(r randyAny) rune {
+ ru := r.Intn(62)
+ if ru < 10 {
+ return rune(ru + 48)
+ } else if ru < 36 {
+ return rune(ru + 55)
+ }
+ return rune(ru + 61)
+}
+func randStringAny(r randyAny) string {
+ v2 := r.Intn(100)
+ tmps := make([]rune, v2)
+ for i := 0; i < v2; i++ {
+ tmps[i] = randUTF8RuneAny(r)
+ }
+ return string(tmps)
+}
+func randUnrecognizedAny(r randyAny, maxFieldNumber int) (dAtA []byte) {
+ l := r.Intn(5)
+ for i := 0; i < l; i++ {
+ wire := r.Intn(4)
+ if wire == 3 {
+ wire = 5
+ }
+ fieldNumber := maxFieldNumber + r.Intn(100)
+ dAtA = randFieldAny(dAtA, r, fieldNumber, wire)
+ }
+ return dAtA
+}
+func randFieldAny(dAtA []byte, r randyAny, fieldNumber int, wire int) []byte {
+ key := uint32(fieldNumber)<<3 | uint32(wire)
+ switch wire {
+ case 0:
+ dAtA = encodeVarintPopulateAny(dAtA, uint64(key))
+ v3 := r.Int63()
+ if r.Intn(2) == 0 {
+ v3 *= -1
+ }
+ dAtA = encodeVarintPopulateAny(dAtA, uint64(v3))
+ case 1:
+ dAtA = encodeVarintPopulateAny(dAtA, uint64(key))
+ dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
+ case 2:
+ dAtA = encodeVarintPopulateAny(dAtA, uint64(key))
+ ll := r.Intn(100)
+ dAtA = encodeVarintPopulateAny(dAtA, uint64(ll))
+ for j := 0; j < ll; j++ {
+ dAtA = append(dAtA, byte(r.Intn(256)))
+ }
+ default:
+ dAtA = encodeVarintPopulateAny(dAtA, uint64(key))
+ dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
+ }
+ return dAtA
+}
+func encodeVarintPopulateAny(dAtA []byte, v uint64) []byte {
+ for v >= 1<<7 {
+ dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
+ v >>= 7
+ }
+ dAtA = append(dAtA, uint8(v))
+ return dAtA
+}
+func (m *Any) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.TypeUrl)
+ if l > 0 {
+ n += 1 + l + sovAny(uint64(l))
+ }
+ l = len(m.Value)
+ if l > 0 {
+ n += 1 + l + sovAny(uint64(l))
+ }
+ return n
+}
+
+func sovAny(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozAny(x uint64) (n int) {
+ return sovAny(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *Any) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Any{`,
+ `TypeUrl:` + fmt.Sprintf("%v", this.TypeUrl) + `,`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringAny(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *Any) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAny
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Any: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Any: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TypeUrl", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAny
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthAny
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.TypeUrl = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowAny
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthAny
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
+ if m.Value == nil {
+ m.Value = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipAny(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthAny
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipAny(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowAny
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowAny
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowAny
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthAny
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowAny
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipAny(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthAny = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowAny = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("any.proto", fileDescriptorAny) }
+
+var fileDescriptorAny = []byte{
+ // 208 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4c, 0xcc, 0xab, 0xd4,
+ 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0x85, 0xf0, 0x92,
+ 0x4a, 0xd3, 0x94, 0xcc, 0xb8, 0x98, 0x1d, 0xf3, 0x2a, 0x85, 0x24, 0xb9, 0x38, 0x4a, 0x2a, 0x0b,
+ 0x52, 0xe3, 0x4b, 0x8b, 0x72, 0x24, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0xd8, 0x41, 0xfc, 0xd0,
+ 0xa2, 0x1c, 0x21, 0x11, 0x2e, 0xd6, 0xb2, 0xc4, 0x9c, 0xd2, 0x54, 0x09, 0x26, 0x05, 0x46, 0x0d,
+ 0x9e, 0x20, 0x08, 0xc7, 0xa9, 0x89, 0xf1, 0xc2, 0x43, 0x39, 0x86, 0x1b, 0x0f, 0xe5, 0x18, 0x3e,
+ 0x3c, 0x94, 0x63, 0xfc, 0xf1, 0x50, 0x8e, 0xb1, 0xe1, 0x91, 0x1c, 0xe3, 0x8a, 0x47, 0x72, 0x8c,
+ 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x8b, 0x47, 0x72,
+ 0x0c, 0x1f, 0x40, 0xe2, 0x8f, 0xe5, 0x18, 0xb9, 0x84, 0x93, 0xf3, 0x73, 0xf5, 0xd0, 0xec, 0x77,
+ 0xe2, 0x70, 0xcc, 0xab, 0x0c, 0x00, 0x71, 0x02, 0x18, 0xa3, 0x58, 0x41, 0x56, 0x16, 0x2f, 0x60,
+ 0x64, 0x5c, 0xc4, 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0xa2, 0x3a, 0x00, 0xaa,
+ 0x5a, 0x2f, 0x3c, 0x35, 0x27, 0xc7, 0x3b, 0x2f, 0xbf, 0x3c, 0x2f, 0x04, 0xa4, 0x32, 0x89, 0x0d,
+ 0x6c, 0x8c, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x63, 0x5d, 0x2d, 0x27, 0xe1, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/gogo/protobuf/types/doc.go b/vendor/github.com/gogo/protobuf/types/doc.go
new file mode 100644
index 0000000..ff2810a
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/doc.go
@@ -0,0 +1,35 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+/*
+Package types contains code for interacting with well-known types.
+*/
+package types
diff --git a/vendor/github.com/gogo/protobuf/types/duration.go b/vendor/github.com/gogo/protobuf/types/duration.go
new file mode 100644
index 0000000..475d61f
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/duration.go
@@ -0,0 +1,100 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package types
+
+// This file implements conversions between google.protobuf.Duration
+// and time.Duration.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+)
+
+const (
+ // Range of a Duration in seconds, as specified in
+ // google/protobuf/duration.proto. This is about 10,000 years in seconds.
+ maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
+ minSeconds = -maxSeconds
+)
+
+// validateDuration determines whether the Duration is valid according to the
+// definition in google/protobuf/duration.proto. A valid Duration
+// may still be too large to fit into a time.Duration (the range of Duration
+// is about 10,000 years, and the range of time.Duration is about 290).
+func validateDuration(d *Duration) error {
+ if d == nil {
+ return errors.New("duration: nil Duration")
+ }
+ if d.Seconds < minSeconds || d.Seconds > maxSeconds {
+ return fmt.Errorf("duration: %#v: seconds out of range", d)
+ }
+ if d.Nanos <= -1e9 || d.Nanos >= 1e9 {
+ return fmt.Errorf("duration: %#v: nanos out of range", d)
+ }
+ // Seconds and Nanos must have the same sign, unless d.Nanos is zero.
+ if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) {
+ return fmt.Errorf("duration: %#v: seconds and nanos have different signs", d)
+ }
+ return nil
+}
+
+// DurationFromProto converts a Duration to a time.Duration. DurationFromProto
+// returns an error if the Duration is invalid or is too large to be
+// represented in a time.Duration.
+func DurationFromProto(p *Duration) (time.Duration, error) {
+ if err := validateDuration(p); err != nil {
+ return 0, err
+ }
+ d := time.Duration(p.Seconds) * time.Second
+ if int64(d/time.Second) != p.Seconds {
+ return 0, fmt.Errorf("duration: %#v is out of range for time.Duration", p)
+ }
+ if p.Nanos != 0 {
+ d += time.Duration(p.Nanos)
+ if (d < 0) != (p.Nanos < 0) {
+ return 0, fmt.Errorf("duration: %#v is out of range for time.Duration", p)
+ }
+ }
+ return d, nil
+}
+
+// DurationProto converts a time.Duration to a Duration.
+func DurationProto(d time.Duration) *Duration {
+ nanos := d.Nanoseconds()
+ secs := nanos / 1e9
+ nanos -= secs * 1e9
+ return &Duration{
+ Seconds: secs,
+ Nanos: int32(nanos),
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/types/duration.pb.go b/vendor/github.com/gogo/protobuf/types/duration.pb.go
new file mode 100644
index 0000000..06b7aea
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/duration.pb.go
@@ -0,0 +1,494 @@
+// Code generated by protoc-gen-gogo.
+// source: duration.proto
+// DO NOT EDIT!
+
+/*
+ Package types is a generated protocol buffer package.
+
+ It is generated from these files:
+ duration.proto
+
+ It has these top-level messages:
+ Duration
+*/
+package types
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+// A Duration represents a signed, fixed-length span of time represented
+// as a count of seconds and fractions of seconds at nanosecond
+// resolution. It is independent of any calendar and concepts like "day"
+// or "month". It is related to Timestamp in that the difference between
+// two Timestamp values is a Duration and it can be added or subtracted
+// from a Timestamp. Range is approximately +-10,000 years.
+//
+// Example 1: Compute Duration from two Timestamps in pseudo code.
+//
+// Timestamp start = ...;
+// Timestamp end = ...;
+// Duration duration = ...;
+//
+// duration.seconds = end.seconds - start.seconds;
+// duration.nanos = end.nanos - start.nanos;
+//
+// if (duration.seconds < 0 && duration.nanos > 0) {
+// duration.seconds += 1;
+// duration.nanos -= 1000000000;
+// } else if (durations.seconds > 0 && duration.nanos < 0) {
+// duration.seconds -= 1;
+// duration.nanos += 1000000000;
+// }
+//
+// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
+//
+// Timestamp start = ...;
+// Duration duration = ...;
+// Timestamp end = ...;
+//
+// end.seconds = start.seconds + duration.seconds;
+// end.nanos = start.nanos + duration.nanos;
+//
+// if (end.nanos < 0) {
+// end.seconds -= 1;
+// end.nanos += 1000000000;
+// } else if (end.nanos >= 1000000000) {
+// end.seconds += 1;
+// end.nanos -= 1000000000;
+// }
+//
+//
+type Duration struct {
+ // Signed seconds of the span of time. Must be from -315,576,000,000
+ // to +315,576,000,000 inclusive.
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
+ // Signed fractions of a second at nanosecond resolution of the span
+ // of time. Durations less than one second are represented with a 0
+ // `seconds` field and a positive or negative `nanos` field. For durations
+ // of one second or more, a non-zero value for the `nanos` field must be
+ // of the same sign as the `seconds` field. Must be from -999,999,999
+ // to +999,999,999 inclusive.
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
+}
+
+func (m *Duration) Reset() { *m = Duration{} }
+func (*Duration) ProtoMessage() {}
+func (*Duration) Descriptor() ([]byte, []int) { return fileDescriptorDuration, []int{0} }
+func (*Duration) XXX_WellKnownType() string { return "Duration" }
+
+func (m *Duration) GetSeconds() int64 {
+ if m != nil {
+ return m.Seconds
+ }
+ return 0
+}
+
+func (m *Duration) GetNanos() int32 {
+ if m != nil {
+ return m.Nanos
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*Duration)(nil), "google.protobuf.Duration")
+}
+func (this *Duration) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*Duration)
+ if !ok {
+ that2, ok := that.(Duration)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.Seconds != that1.Seconds {
+ if this.Seconds < that1.Seconds {
+ return -1
+ }
+ return 1
+ }
+ if this.Nanos != that1.Nanos {
+ if this.Nanos < that1.Nanos {
+ return -1
+ }
+ return 1
+ }
+ return 0
+}
+func (this *Duration) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Duration)
+ if !ok {
+ that2, ok := that.(Duration)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Seconds != that1.Seconds {
+ return false
+ }
+ if this.Nanos != that1.Nanos {
+ return false
+ }
+ return true
+}
+func (this *Duration) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&types.Duration{")
+ s = append(s, "Seconds: "+fmt.Sprintf("%#v", this.Seconds)+",\n")
+ s = append(s, "Nanos: "+fmt.Sprintf("%#v", this.Nanos)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringDuration(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func (m *Duration) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Duration) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Seconds != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintDuration(dAtA, i, uint64(m.Seconds))
+ }
+ if m.Nanos != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintDuration(dAtA, i, uint64(m.Nanos))
+ }
+ return i, nil
+}
+
+func encodeFixed64Duration(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Duration(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintDuration(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func (m *Duration) Size() (n int) {
+ var l int
+ _ = l
+ if m.Seconds != 0 {
+ n += 1 + sovDuration(uint64(m.Seconds))
+ }
+ if m.Nanos != 0 {
+ n += 1 + sovDuration(uint64(m.Nanos))
+ }
+ return n
+}
+
+func sovDuration(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozDuration(x uint64) (n int) {
+ return sovDuration(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (m *Duration) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDuration
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Duration: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Duration: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Seconds", wireType)
+ }
+ m.Seconds = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDuration
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Seconds |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Nanos", wireType)
+ }
+ m.Nanos = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowDuration
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Nanos |= (int32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipDuration(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthDuration
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipDuration(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowDuration
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowDuration
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowDuration
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthDuration
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowDuration
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipDuration(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthDuration = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowDuration = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("duration.proto", fileDescriptorDuration) }
+
+var fileDescriptorDuration = []byte{
+ // 203 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4b, 0x29, 0x2d, 0x4a,
+ 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0x85, 0xf0, 0x92, 0x4a, 0xd3, 0x94, 0xac, 0xb8, 0x38, 0x5c, 0xa0, 0x4a, 0x84, 0x24,
+ 0xb8, 0xd8, 0x8b, 0x53, 0x93, 0xf3, 0xf3, 0x52, 0x8a, 0x25, 0x18, 0x15, 0x18, 0x35, 0x98, 0x83,
+ 0x60, 0x5c, 0x21, 0x11, 0x2e, 0xd6, 0xbc, 0xc4, 0xbc, 0xfc, 0x62, 0x09, 0x26, 0x05, 0x46, 0x0d,
+ 0xd6, 0x20, 0x08, 0xc7, 0xa9, 0xfe, 0xc2, 0x43, 0x39, 0x86, 0x1b, 0x0f, 0xe5, 0x18, 0x3e, 0x3c,
+ 0x94, 0x63, 0x5c, 0xf1, 0x48, 0x8e, 0xf1, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f,
+ 0x3c, 0x92, 0x63, 0x7c, 0xf1, 0x48, 0x8e, 0xe1, 0xc3, 0x23, 0x39, 0xc6, 0x15, 0x8f, 0xe5, 0x18,
+ 0xb9, 0x84, 0x93, 0xf3, 0x73, 0xf5, 0xd0, 0xac, 0x76, 0xe2, 0x85, 0x59, 0x1c, 0x00, 0x12, 0x09,
+ 0x60, 0x8c, 0x62, 0x2d, 0xa9, 0x2c, 0x48, 0x2d, 0x5e, 0xc0, 0xc8, 0xb8, 0x88, 0x89, 0xd9, 0x3d,
+ 0xc0, 0x69, 0x15, 0x93, 0x9c, 0x3b, 0x44, 0x4b, 0x00, 0x54, 0x8b, 0x5e, 0x78, 0x6a, 0x4e, 0x8e,
+ 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x65, 0x12, 0x1b, 0xd8, 0x2c, 0x63, 0x40, 0x00, 0x00,
+ 0x00, 0xff, 0xff, 0xba, 0xfb, 0x15, 0xc9, 0xe6, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/gogo/protobuf/types/duration_gogo.go b/vendor/github.com/gogo/protobuf/types/duration_gogo.go
new file mode 100644
index 0000000..90e7670
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/duration_gogo.go
@@ -0,0 +1,100 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2016, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 types
+
+import (
+ "fmt"
+ "time"
+)
+
+func NewPopulatedDuration(r interface {
+ Int63() int64
+}, easy bool) *Duration {
+ this := &Duration{}
+ maxSecs := time.Hour.Nanoseconds() / 1e9
+ max := 2 * maxSecs
+ s := int64(r.Int63()) % max
+ s -= maxSecs
+ neg := int64(1)
+ if s < 0 {
+ neg = -1
+ }
+ this.Seconds = s
+ this.Nanos = int32(neg * (r.Int63() % 1e9))
+ return this
+}
+
+func (d *Duration) String() string {
+ td, err := DurationFromProto(d)
+ if err != nil {
+ return fmt.Sprintf("(%v)", err)
+ }
+ return td.String()
+}
+
+func NewPopulatedStdDuration(r interface {
+ Int63() int64
+}, easy bool) *time.Duration {
+ dur := NewPopulatedDuration(r, easy)
+ d, err := DurationFromProto(dur)
+ if err != nil {
+ return nil
+ }
+ return &d
+}
+
+func SizeOfStdDuration(d time.Duration) int {
+ dur := DurationProto(d)
+ return dur.Size()
+}
+
+func StdDurationMarshal(d time.Duration) ([]byte, error) {
+ size := SizeOfStdDuration(d)
+ buf := make([]byte, size)
+ _, err := StdDurationMarshalTo(d, buf)
+ return buf, err
+}
+
+func StdDurationMarshalTo(d time.Duration, data []byte) (int, error) {
+ dur := DurationProto(d)
+ return dur.MarshalTo(data)
+}
+
+func StdDurationUnmarshal(d *time.Duration, data []byte) error {
+ dur := &Duration{}
+ if err := dur.Unmarshal(data); err != nil {
+ return err
+ }
+ dd, err := DurationFromProto(dur)
+ if err != nil {
+ return err
+ }
+ *d = dd
+ return nil
+}
diff --git a/vendor/github.com/gogo/protobuf/types/empty.pb.go b/vendor/github.com/gogo/protobuf/types/empty.pb.go
new file mode 100644
index 0000000..33f9bdd
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/empty.pb.go
@@ -0,0 +1,457 @@
+// Code generated by protoc-gen-gogo.
+// source: empty.proto
+// DO NOT EDIT!
+
+/*
+Package types is a generated protocol buffer package.
+
+It is generated from these files:
+ empty.proto
+
+It has these top-level messages:
+ Empty
+*/
+package types
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+// A generic empty message that you can re-use to avoid defining duplicated
+// empty messages in your APIs. A typical example is to use it as the request
+// or the response type of an API method. For instance:
+//
+// service Foo {
+// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+// }
+//
+// The JSON representation for `Empty` is empty JSON object `{}`.
+type Empty struct {
+}
+
+func (m *Empty) Reset() { *m = Empty{} }
+func (*Empty) ProtoMessage() {}
+func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptorEmpty, []int{0} }
+func (*Empty) XXX_WellKnownType() string { return "Empty" }
+
+func init() {
+ proto.RegisterType((*Empty)(nil), "google.protobuf.Empty")
+}
+func (this *Empty) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*Empty)
+ if !ok {
+ that2, ok := that.(Empty)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ return 0
+}
+func (this *Empty) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Empty)
+ if !ok {
+ that2, ok := that.(Empty)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ return true
+}
+func (this *Empty) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 4)
+ s = append(s, "&types.Empty{")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringEmpty(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func (m *Empty) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Empty) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ return i, nil
+}
+
+func encodeFixed64Empty(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Empty(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintEmpty(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func NewPopulatedEmpty(r randyEmpty, easy bool) *Empty {
+ this := &Empty{}
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+type randyEmpty interface {
+ Float32() float32
+ Float64() float64
+ Int63() int64
+ Int31() int32
+ Uint32() uint32
+ Intn(n int) int
+}
+
+func randUTF8RuneEmpty(r randyEmpty) rune {
+ ru := r.Intn(62)
+ if ru < 10 {
+ return rune(ru + 48)
+ } else if ru < 36 {
+ return rune(ru + 55)
+ }
+ return rune(ru + 61)
+}
+func randStringEmpty(r randyEmpty) string {
+ v1 := r.Intn(100)
+ tmps := make([]rune, v1)
+ for i := 0; i < v1; i++ {
+ tmps[i] = randUTF8RuneEmpty(r)
+ }
+ return string(tmps)
+}
+func randUnrecognizedEmpty(r randyEmpty, maxFieldNumber int) (dAtA []byte) {
+ l := r.Intn(5)
+ for i := 0; i < l; i++ {
+ wire := r.Intn(4)
+ if wire == 3 {
+ wire = 5
+ }
+ fieldNumber := maxFieldNumber + r.Intn(100)
+ dAtA = randFieldEmpty(dAtA, r, fieldNumber, wire)
+ }
+ return dAtA
+}
+func randFieldEmpty(dAtA []byte, r randyEmpty, fieldNumber int, wire int) []byte {
+ key := uint32(fieldNumber)<<3 | uint32(wire)
+ switch wire {
+ case 0:
+ dAtA = encodeVarintPopulateEmpty(dAtA, uint64(key))
+ v2 := r.Int63()
+ if r.Intn(2) == 0 {
+ v2 *= -1
+ }
+ dAtA = encodeVarintPopulateEmpty(dAtA, uint64(v2))
+ case 1:
+ dAtA = encodeVarintPopulateEmpty(dAtA, uint64(key))
+ dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
+ case 2:
+ dAtA = encodeVarintPopulateEmpty(dAtA, uint64(key))
+ ll := r.Intn(100)
+ dAtA = encodeVarintPopulateEmpty(dAtA, uint64(ll))
+ for j := 0; j < ll; j++ {
+ dAtA = append(dAtA, byte(r.Intn(256)))
+ }
+ default:
+ dAtA = encodeVarintPopulateEmpty(dAtA, uint64(key))
+ dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
+ }
+ return dAtA
+}
+func encodeVarintPopulateEmpty(dAtA []byte, v uint64) []byte {
+ for v >= 1<<7 {
+ dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
+ v >>= 7
+ }
+ dAtA = append(dAtA, uint8(v))
+ return dAtA
+}
+func (m *Empty) Size() (n int) {
+ var l int
+ _ = l
+ return n
+}
+
+func sovEmpty(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozEmpty(x uint64) (n int) {
+ return sovEmpty(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *Empty) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Empty{`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringEmpty(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *Empty) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowEmpty
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Empty: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Empty: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ default:
+ iNdEx = preIndex
+ skippy, err := skipEmpty(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthEmpty
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipEmpty(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowEmpty
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowEmpty
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowEmpty
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthEmpty
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowEmpty
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipEmpty(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthEmpty = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowEmpty = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("empty.proto", fileDescriptorEmpty) }
+
+var fileDescriptorEmpty = []byte{
+ // 172 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4e, 0xcd, 0x2d, 0x28,
+ 0xa9, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0x85,
+ 0xf0, 0x92, 0x4a, 0xd3, 0x94, 0xd8, 0xb9, 0x58, 0x5d, 0x41, 0xf2, 0x4e, 0xed, 0x8c, 0x17, 0x1e,
+ 0xca, 0x31, 0xdc, 0x78, 0x28, 0xc7, 0xf0, 0xe1, 0xa1, 0x1c, 0xe3, 0x8f, 0x87, 0x72, 0x8c, 0x0d,
+ 0x8f, 0xe4, 0x18, 0x57, 0x3c, 0x92, 0x63, 0x3c, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6,
+ 0x07, 0x8f, 0xe4, 0x18, 0x5f, 0x3c, 0x92, 0x63, 0xf8, 0x00, 0x12, 0x7f, 0x2c, 0xc7, 0xc8, 0x25,
+ 0x9c, 0x9c, 0x9f, 0xab, 0x87, 0x66, 0xa0, 0x13, 0x17, 0xd8, 0xb8, 0x00, 0x10, 0x37, 0x80, 0x31,
+ 0x8a, 0xb5, 0xa4, 0xb2, 0x20, 0xb5, 0x78, 0x01, 0x23, 0xe3, 0x0f, 0x46, 0xc6, 0x45, 0x4c, 0xcc,
+ 0xee, 0x01, 0x4e, 0xab, 0x98, 0xe4, 0xdc, 0x21, 0x5a, 0x02, 0xa0, 0x5a, 0xf4, 0xc2, 0x53, 0x73,
+ 0x72, 0xbc, 0xf3, 0xf2, 0xcb, 0xf3, 0x42, 0x40, 0x8a, 0x93, 0xd8, 0xc0, 0x66, 0x19, 0x03, 0x02,
+ 0x00, 0x00, 0xff, 0xff, 0x97, 0x6c, 0x95, 0xdd, 0xb9, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/gogo/protobuf/types/field_mask.pb.go b/vendor/github.com/gogo/protobuf/types/field_mask.pb.go
new file mode 100644
index 0000000..9ea5bd7
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/field_mask.pb.go
@@ -0,0 +1,738 @@
+// Code generated by protoc-gen-gogo.
+// source: field_mask.proto
+// DO NOT EDIT!
+
+/*
+Package types is a generated protocol buffer package.
+
+It is generated from these files:
+ field_mask.proto
+
+It has these top-level messages:
+ FieldMask
+*/
+package types
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+// `FieldMask` represents a set of symbolic field paths, for example:
+//
+// paths: "f.a"
+// paths: "f.b.d"
+//
+// Here `f` represents a field in some root message, `a` and `b`
+// fields in the message found in `f`, and `d` a field found in the
+// message in `f.b`.
+//
+// Field masks are used to specify a subset of fields that should be
+// returned by a get operation or modified by an update operation.
+// Field masks also have a custom JSON encoding (see below).
+//
+// # Field Masks in Projections
+//
+// When used in the context of a projection, a response message or
+// sub-message is filtered by the API to only contain those fields as
+// specified in the mask. For example, if the mask in the previous
+// example is applied to a response message as follows:
+//
+// f {
+// a : 22
+// b {
+// d : 1
+// x : 2
+// }
+// y : 13
+// }
+// z: 8
+//
+// The result will not contain specific values for fields x,y and z
+// (their value will be set to the default, and omitted in proto text
+// output):
+//
+//
+// f {
+// a : 22
+// b {
+// d : 1
+// }
+// }
+//
+// A repeated field is not allowed except at the last position of a
+// field mask.
+//
+// If a FieldMask object is not present in a get operation, the
+// operation applies to all fields (as if a FieldMask of all fields
+// had been specified).
+//
+// Note that a field mask does not necessarily apply to the
+// top-level response message. In case of a REST get operation, the
+// field mask applies directly to the response, but in case of a REST
+// list operation, the mask instead applies to each individual message
+// in the returned resource list. In case of a REST custom method,
+// other definitions may be used. Where the mask applies will be
+// clearly documented together with its declaration in the API. In
+// any case, the effect on the returned resource/resources is required
+// behavior for APIs.
+//
+// # Field Masks in Update Operations
+//
+// A field mask in update operations specifies which fields of the
+// targeted resource are going to be updated. The API is required
+// to only change the values of the fields as specified in the mask
+// and leave the others untouched. If a resource is passed in to
+// describe the updated values, the API ignores the values of all
+// fields not covered by the mask.
+//
+// If a repeated field is specified for an update operation, the existing
+// repeated values in the target resource will be overwritten by the new values.
+// Note that a repeated field is only allowed in the last position of a field
+// mask.
+//
+// If a sub-message is specified in the last position of the field mask for an
+// update operation, then the existing sub-message in the target resource is
+// overwritten. Given the target message:
+//
+// f {
+// b {
+// d : 1
+// x : 2
+// }
+// c : 1
+// }
+//
+// And an update message:
+//
+// f {
+// b {
+// d : 10
+// }
+// }
+//
+// then if the field mask is:
+//
+// paths: "f.b"
+//
+// then the result will be:
+//
+// f {
+// b {
+// d : 10
+// }
+// c : 1
+// }
+//
+// However, if the update mask was:
+//
+// paths: "f.b.d"
+//
+// then the result would be:
+//
+// f {
+// b {
+// d : 10
+// x : 2
+// }
+// c : 1
+// }
+//
+// In order to reset a field's value to the default, the field must
+// be in the mask and set to the default value in the provided resource.
+// Hence, in order to reset all fields of a resource, provide a default
+// instance of the resource and set all fields in the mask, or do
+// not provide a mask as described below.
+//
+// If a field mask is not present on update, the operation applies to
+// all fields (as if a field mask of all fields has been specified).
+// Note that in the presence of schema evolution, this may mean that
+// fields the client does not know and has therefore not filled into
+// the request will be reset to their default. If this is unwanted
+// behavior, a specific service may require a client to always specify
+// a field mask, producing an error if not.
+//
+// As with get operations, the location of the resource which
+// describes the updated values in the request message depends on the
+// operation kind. In any case, the effect of the field mask is
+// required to be honored by the API.
+//
+// ## Considerations for HTTP REST
+//
+// The HTTP kind of an update operation which uses a field mask must
+// be set to PATCH instead of PUT in order to satisfy HTTP semantics
+// (PUT must only be used for full updates).
+//
+// # JSON Encoding of Field Masks
+//
+// In JSON, a field mask is encoded as a single string where paths are
+// separated by a comma. Fields name in each path are converted
+// to/from lower-camel naming conventions.
+//
+// As an example, consider the following message declarations:
+//
+// message Profile {
+// User user = 1;
+// Photo photo = 2;
+// }
+// message User {
+// string display_name = 1;
+// string address = 2;
+// }
+//
+// In proto a field mask for `Profile` may look as such:
+//
+// mask {
+// paths: "user.display_name"
+// paths: "photo"
+// }
+//
+// In JSON, the same mask is represented as below:
+//
+// {
+// mask: "user.displayName,photo"
+// }
+//
+// # Field Masks and Oneof Fields
+//
+// Field masks treat fields in oneofs just as regular fields. Consider the
+// following message:
+//
+// message SampleMessage {
+// oneof test_oneof {
+// string name = 4;
+// SubMessage sub_message = 9;
+// }
+// }
+//
+// The field mask can be:
+//
+// mask {
+// paths: "name"
+// }
+//
+// Or:
+//
+// mask {
+// paths: "sub_message"
+// }
+//
+// Note that oneof type names ("test_oneof" in this case) cannot be used in
+// paths.
+type FieldMask struct {
+ // The set of field mask paths.
+ Paths []string `protobuf:"bytes,1,rep,name=paths" json:"paths,omitempty"`
+}
+
+func (m *FieldMask) Reset() { *m = FieldMask{} }
+func (*FieldMask) ProtoMessage() {}
+func (*FieldMask) Descriptor() ([]byte, []int) { return fileDescriptorFieldMask, []int{0} }
+
+func (m *FieldMask) GetPaths() []string {
+ if m != nil {
+ return m.Paths
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*FieldMask)(nil), "google.protobuf.FieldMask")
+}
+func (this *FieldMask) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*FieldMask)
+ if !ok {
+ that2, ok := that.(FieldMask)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if len(this.Paths) != len(that1.Paths) {
+ if len(this.Paths) < len(that1.Paths) {
+ return -1
+ }
+ return 1
+ }
+ for i := range this.Paths {
+ if this.Paths[i] != that1.Paths[i] {
+ if this.Paths[i] < that1.Paths[i] {
+ return -1
+ }
+ return 1
+ }
+ }
+ return 0
+}
+func (this *FieldMask) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*FieldMask)
+ if !ok {
+ that2, ok := that.(FieldMask)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if len(this.Paths) != len(that1.Paths) {
+ return false
+ }
+ for i := range this.Paths {
+ if this.Paths[i] != that1.Paths[i] {
+ return false
+ }
+ }
+ return true
+}
+func (this *FieldMask) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.FieldMask{")
+ s = append(s, "Paths: "+fmt.Sprintf("%#v", this.Paths)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringFieldMask(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func (m *FieldMask) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *FieldMask) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Paths) > 0 {
+ for _, s := range m.Paths {
+ dAtA[i] = 0xa
+ i++
+ l = len(s)
+ for l >= 1<<7 {
+ dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
+ l >>= 7
+ i++
+ }
+ dAtA[i] = uint8(l)
+ i++
+ i += copy(dAtA[i:], s)
+ }
+ }
+ return i, nil
+}
+
+func encodeFixed64FieldMask(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32FieldMask(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintFieldMask(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func NewPopulatedFieldMask(r randyFieldMask, easy bool) *FieldMask {
+ this := &FieldMask{}
+ v1 := r.Intn(10)
+ this.Paths = make([]string, v1)
+ for i := 0; i < v1; i++ {
+ this.Paths[i] = string(randStringFieldMask(r))
+ }
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+type randyFieldMask interface {
+ Float32() float32
+ Float64() float64
+ Int63() int64
+ Int31() int32
+ Uint32() uint32
+ Intn(n int) int
+}
+
+func randUTF8RuneFieldMask(r randyFieldMask) rune {
+ ru := r.Intn(62)
+ if ru < 10 {
+ return rune(ru + 48)
+ } else if ru < 36 {
+ return rune(ru + 55)
+ }
+ return rune(ru + 61)
+}
+func randStringFieldMask(r randyFieldMask) string {
+ v2 := r.Intn(100)
+ tmps := make([]rune, v2)
+ for i := 0; i < v2; i++ {
+ tmps[i] = randUTF8RuneFieldMask(r)
+ }
+ return string(tmps)
+}
+func randUnrecognizedFieldMask(r randyFieldMask, maxFieldNumber int) (dAtA []byte) {
+ l := r.Intn(5)
+ for i := 0; i < l; i++ {
+ wire := r.Intn(4)
+ if wire == 3 {
+ wire = 5
+ }
+ fieldNumber := maxFieldNumber + r.Intn(100)
+ dAtA = randFieldFieldMask(dAtA, r, fieldNumber, wire)
+ }
+ return dAtA
+}
+func randFieldFieldMask(dAtA []byte, r randyFieldMask, fieldNumber int, wire int) []byte {
+ key := uint32(fieldNumber)<<3 | uint32(wire)
+ switch wire {
+ case 0:
+ dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key))
+ v3 := r.Int63()
+ if r.Intn(2) == 0 {
+ v3 *= -1
+ }
+ dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(v3))
+ case 1:
+ dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key))
+ dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
+ case 2:
+ dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key))
+ ll := r.Intn(100)
+ dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(ll))
+ for j := 0; j < ll; j++ {
+ dAtA = append(dAtA, byte(r.Intn(256)))
+ }
+ default:
+ dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key))
+ dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
+ }
+ return dAtA
+}
+func encodeVarintPopulateFieldMask(dAtA []byte, v uint64) []byte {
+ for v >= 1<<7 {
+ dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
+ v >>= 7
+ }
+ dAtA = append(dAtA, uint8(v))
+ return dAtA
+}
+func (m *FieldMask) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Paths) > 0 {
+ for _, s := range m.Paths {
+ l = len(s)
+ n += 1 + l + sovFieldMask(uint64(l))
+ }
+ }
+ return n
+}
+
+func sovFieldMask(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozFieldMask(x uint64) (n int) {
+ return sovFieldMask(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *FieldMask) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&FieldMask{`,
+ `Paths:` + fmt.Sprintf("%v", this.Paths) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringFieldMask(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *FieldMask) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowFieldMask
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: FieldMask: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: FieldMask: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Paths", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowFieldMask
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthFieldMask
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Paths = append(m.Paths, string(dAtA[iNdEx:postIndex]))
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipFieldMask(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthFieldMask
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipFieldMask(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowFieldMask
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowFieldMask
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowFieldMask
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthFieldMask
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowFieldMask
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipFieldMask(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthFieldMask = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowFieldMask = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("field_mask.proto", fileDescriptorFieldMask) }
+
+var fileDescriptorFieldMask = []byte{
+ // 196 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x48, 0xcb, 0x4c, 0xcd,
+ 0x49, 0x89, 0xcf, 0x4d, 0x2c, 0xce, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf,
+ 0xcf, 0x4f, 0xcf, 0x49, 0x85, 0xf0, 0x92, 0x4a, 0xd3, 0x94, 0x14, 0xb9, 0x38, 0xdd, 0x40, 0x8a,
+ 0x7c, 0x13, 0x8b, 0xb3, 0x85, 0x44, 0xb8, 0x58, 0x0b, 0x12, 0x4b, 0x32, 0x8a, 0x25, 0x18, 0x15,
+ 0x98, 0x35, 0x38, 0x83, 0x20, 0x1c, 0xa7, 0x0e, 0xc6, 0x0b, 0x0f, 0xe5, 0x18, 0x6e, 0x3c, 0x94,
+ 0x63, 0xf8, 0xf0, 0x50, 0x8e, 0xf1, 0xc7, 0x43, 0x39, 0xc6, 0x86, 0x47, 0x72, 0x8c, 0x2b, 0x1e,
+ 0xc9, 0x31, 0x9e, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x2f,
+ 0x1e, 0xc9, 0x31, 0x7c, 0x00, 0x89, 0x3f, 0x96, 0x63, 0xe4, 0x12, 0x4e, 0xce, 0xcf, 0xd5, 0x43,
+ 0xb3, 0xca, 0x89, 0x0f, 0x6e, 0x51, 0x00, 0x48, 0x28, 0x80, 0x31, 0x8a, 0xb5, 0xa4, 0xb2, 0x20,
+ 0xb5, 0x78, 0x01, 0x23, 0xe3, 0x22, 0x26, 0x66, 0xf7, 0x00, 0xa7, 0x55, 0x4c, 0x72, 0xee, 0x10,
+ 0x3d, 0x01, 0x50, 0x3d, 0x7a, 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20,
+ 0x95, 0x49, 0x6c, 0x60, 0xc3, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xea, 0xb1, 0x3a, 0xd5,
+ 0xd9, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/gogo/protobuf/types/struct.pb.go b/vendor/github.com/gogo/protobuf/types/struct.pb.go
new file mode 100644
index 0000000..f81a433
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/struct.pb.go
@@ -0,0 +1,1888 @@
+// Code generated by protoc-gen-gogo.
+// source: struct.proto
+// DO NOT EDIT!
+
+/*
+ Package types is a generated protocol buffer package.
+
+ It is generated from these files:
+ struct.proto
+
+ It has these top-level messages:
+ Struct
+ Value
+ ListValue
+*/
+package types
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+import strconv "strconv"
+
+import strings "strings"
+import reflect "reflect"
+import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+// `NullValue` is a singleton enumeration to represent the null value for the
+// `Value` type union.
+//
+// The JSON representation for `NullValue` is JSON `null`.
+type NullValue int32
+
+const (
+ // Null value.
+ NULL_VALUE NullValue = 0
+)
+
+var NullValue_name = map[int32]string{
+ 0: "NULL_VALUE",
+}
+var NullValue_value = map[string]int32{
+ "NULL_VALUE": 0,
+}
+
+func (NullValue) EnumDescriptor() ([]byte, []int) { return fileDescriptorStruct, []int{0} }
+func (NullValue) XXX_WellKnownType() string { return "NullValue" }
+
+// `Struct` represents a structured data value, consisting of fields
+// which map to dynamically typed values. In some languages, `Struct`
+// might be supported by a native representation. For example, in
+// scripting languages like JS a struct is represented as an
+// object. The details of that representation are described together
+// with the proto support for the language.
+//
+// The JSON representation for `Struct` is JSON object.
+type Struct struct {
+ // Unordered map of dynamically typed values.
+ Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"`
+}
+
+func (m *Struct) Reset() { *m = Struct{} }
+func (*Struct) ProtoMessage() {}
+func (*Struct) Descriptor() ([]byte, []int) { return fileDescriptorStruct, []int{0} }
+func (*Struct) XXX_WellKnownType() string { return "Struct" }
+
+func (m *Struct) GetFields() map[string]*Value {
+ if m != nil {
+ return m.Fields
+ }
+ return nil
+}
+
+// `Value` represents a dynamically typed value which can be either
+// null, a number, a string, a boolean, a recursive struct value, or a
+// list of values. A producer of value is expected to set one of that
+// variants, absence of any variant indicates an error.
+//
+// The JSON representation for `Value` is JSON value.
+type Value struct {
+ // The kind of value.
+ //
+ // Types that are valid to be assigned to Kind:
+ // *Value_NullValue
+ // *Value_NumberValue
+ // *Value_StringValue
+ // *Value_BoolValue
+ // *Value_StructValue
+ // *Value_ListValue
+ Kind isValue_Kind `protobuf_oneof:"kind"`
+}
+
+func (m *Value) Reset() { *m = Value{} }
+func (*Value) ProtoMessage() {}
+func (*Value) Descriptor() ([]byte, []int) { return fileDescriptorStruct, []int{1} }
+func (*Value) XXX_WellKnownType() string { return "Value" }
+
+type isValue_Kind interface {
+ isValue_Kind()
+ Equal(interface{}) bool
+ MarshalTo([]byte) (int, error)
+ Size() int
+}
+
+type Value_NullValue struct {
+ NullValue NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,proto3,enum=google.protobuf.NullValue,oneof"`
+}
+type Value_NumberValue struct {
+ NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,proto3,oneof"`
+}
+type Value_StringValue struct {
+ StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,proto3,oneof"`
+}
+type Value_BoolValue struct {
+ BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,proto3,oneof"`
+}
+type Value_StructValue struct {
+ StructValue *Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,oneof"`
+}
+type Value_ListValue struct {
+ ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,oneof"`
+}
+
+func (*Value_NullValue) isValue_Kind() {}
+func (*Value_NumberValue) isValue_Kind() {}
+func (*Value_StringValue) isValue_Kind() {}
+func (*Value_BoolValue) isValue_Kind() {}
+func (*Value_StructValue) isValue_Kind() {}
+func (*Value_ListValue) isValue_Kind() {}
+
+func (m *Value) GetKind() isValue_Kind {
+ if m != nil {
+ return m.Kind
+ }
+ return nil
+}
+
+func (m *Value) GetNullValue() NullValue {
+ if x, ok := m.GetKind().(*Value_NullValue); ok {
+ return x.NullValue
+ }
+ return NULL_VALUE
+}
+
+func (m *Value) GetNumberValue() float64 {
+ if x, ok := m.GetKind().(*Value_NumberValue); ok {
+ return x.NumberValue
+ }
+ return 0
+}
+
+func (m *Value) GetStringValue() string {
+ if x, ok := m.GetKind().(*Value_StringValue); ok {
+ return x.StringValue
+ }
+ return ""
+}
+
+func (m *Value) GetBoolValue() bool {
+ if x, ok := m.GetKind().(*Value_BoolValue); ok {
+ return x.BoolValue
+ }
+ return false
+}
+
+func (m *Value) GetStructValue() *Struct {
+ if x, ok := m.GetKind().(*Value_StructValue); ok {
+ return x.StructValue
+ }
+ return nil
+}
+
+func (m *Value) GetListValue() *ListValue {
+ if x, ok := m.GetKind().(*Value_ListValue); ok {
+ return x.ListValue
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Value) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Value_OneofMarshaler, _Value_OneofUnmarshaler, _Value_OneofSizer, []interface{}{
+ (*Value_NullValue)(nil),
+ (*Value_NumberValue)(nil),
+ (*Value_StringValue)(nil),
+ (*Value_BoolValue)(nil),
+ (*Value_StructValue)(nil),
+ (*Value_ListValue)(nil),
+ }
+}
+
+func _Value_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Value)
+ // kind
+ switch x := m.Kind.(type) {
+ case *Value_NullValue:
+ _ = b.EncodeVarint(1<<3 | proto.WireVarint)
+ _ = b.EncodeVarint(uint64(x.NullValue))
+ case *Value_NumberValue:
+ _ = b.EncodeVarint(2<<3 | proto.WireFixed64)
+ _ = b.EncodeFixed64(math.Float64bits(x.NumberValue))
+ case *Value_StringValue:
+ _ = b.EncodeVarint(3<<3 | proto.WireBytes)
+ _ = b.EncodeStringBytes(x.StringValue)
+ case *Value_BoolValue:
+ t := uint64(0)
+ if x.BoolValue {
+ t = 1
+ }
+ _ = b.EncodeVarint(4<<3 | proto.WireVarint)
+ _ = b.EncodeVarint(t)
+ case *Value_StructValue:
+ _ = b.EncodeVarint(5<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.StructValue); err != nil {
+ return err
+ }
+ case *Value_ListValue:
+ _ = b.EncodeVarint(6<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.ListValue); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("Value.Kind has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Value_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Value)
+ switch tag {
+ case 1: // kind.null_value
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Kind = &Value_NullValue{NullValue(x)}
+ return true, err
+ case 2: // kind.number_value
+ if wire != proto.WireFixed64 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed64()
+ m.Kind = &Value_NumberValue{math.Float64frombits(x)}
+ return true, err
+ case 3: // kind.string_value
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Kind = &Value_StringValue{x}
+ return true, err
+ case 4: // kind.bool_value
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Kind = &Value_BoolValue{x != 0}
+ return true, err
+ case 5: // kind.struct_value
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Struct)
+ err := b.DecodeMessage(msg)
+ m.Kind = &Value_StructValue{msg}
+ return true, err
+ case 6: // kind.list_value
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(ListValue)
+ err := b.DecodeMessage(msg)
+ m.Kind = &Value_ListValue{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Value_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Value)
+ // kind
+ switch x := m.Kind.(type) {
+ case *Value_NullValue:
+ n += proto.SizeVarint(1<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.NullValue))
+ case *Value_NumberValue:
+ n += proto.SizeVarint(2<<3 | proto.WireFixed64)
+ n += 8
+ case *Value_StringValue:
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.StringValue)))
+ n += len(x.StringValue)
+ case *Value_BoolValue:
+ n += proto.SizeVarint(4<<3 | proto.WireVarint)
+ n += 1
+ case *Value_StructValue:
+ s := proto.Size(x.StructValue)
+ n += proto.SizeVarint(5<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Value_ListValue:
+ s := proto.Size(x.ListValue)
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// `ListValue` is a wrapper around a repeated field of values.
+//
+// The JSON representation for `ListValue` is JSON array.
+type ListValue struct {
+ // Repeated field of dynamically typed values.
+ Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"`
+}
+
+func (m *ListValue) Reset() { *m = ListValue{} }
+func (*ListValue) ProtoMessage() {}
+func (*ListValue) Descriptor() ([]byte, []int) { return fileDescriptorStruct, []int{2} }
+func (*ListValue) XXX_WellKnownType() string { return "ListValue" }
+
+func (m *ListValue) GetValues() []*Value {
+ if m != nil {
+ return m.Values
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Struct)(nil), "google.protobuf.Struct")
+ proto.RegisterType((*Value)(nil), "google.protobuf.Value")
+ proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue")
+ proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value)
+}
+func (x NullValue) String() string {
+ s, ok := NullValue_name[int32(x)]
+ if ok {
+ return s
+ }
+ return strconv.Itoa(int(x))
+}
+func (this *Struct) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Struct)
+ if !ok {
+ that2, ok := that.(Struct)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if len(this.Fields) != len(that1.Fields) {
+ return false
+ }
+ for i := range this.Fields {
+ if !this.Fields[i].Equal(that1.Fields[i]) {
+ return false
+ }
+ }
+ return true
+}
+func (this *Value) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Value)
+ if !ok {
+ that2, ok := that.(Value)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if that1.Kind == nil {
+ if this.Kind != nil {
+ return false
+ }
+ } else if this.Kind == nil {
+ return false
+ } else if !this.Kind.Equal(that1.Kind) {
+ return false
+ }
+ return true
+}
+func (this *Value_NullValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Value_NullValue)
+ if !ok {
+ that2, ok := that.(Value_NullValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.NullValue != that1.NullValue {
+ return false
+ }
+ return true
+}
+func (this *Value_NumberValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Value_NumberValue)
+ if !ok {
+ that2, ok := that.(Value_NumberValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.NumberValue != that1.NumberValue {
+ return false
+ }
+ return true
+}
+func (this *Value_StringValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Value_StringValue)
+ if !ok {
+ that2, ok := that.(Value_StringValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.StringValue != that1.StringValue {
+ return false
+ }
+ return true
+}
+func (this *Value_BoolValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Value_BoolValue)
+ if !ok {
+ that2, ok := that.(Value_BoolValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.BoolValue != that1.BoolValue {
+ return false
+ }
+ return true
+}
+func (this *Value_StructValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Value_StructValue)
+ if !ok {
+ that2, ok := that.(Value_StructValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if !this.StructValue.Equal(that1.StructValue) {
+ return false
+ }
+ return true
+}
+func (this *Value_ListValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Value_ListValue)
+ if !ok {
+ that2, ok := that.(Value_ListValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if !this.ListValue.Equal(that1.ListValue) {
+ return false
+ }
+ return true
+}
+func (this *ListValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*ListValue)
+ if !ok {
+ that2, ok := that.(ListValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if len(this.Values) != len(that1.Values) {
+ return false
+ }
+ for i := range this.Values {
+ if !this.Values[i].Equal(that1.Values[i]) {
+ return false
+ }
+ }
+ return true
+}
+func (this *Struct) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.Struct{")
+ keysForFields := make([]string, 0, len(this.Fields))
+ for k := range this.Fields {
+ keysForFields = append(keysForFields, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForFields)
+ mapStringForFields := "map[string]*Value{"
+ for _, k := range keysForFields {
+ mapStringForFields += fmt.Sprintf("%#v: %#v,", k, this.Fields[k])
+ }
+ mapStringForFields += "}"
+ if this.Fields != nil {
+ s = append(s, "Fields: "+mapStringForFields+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *Value) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 10)
+ s = append(s, "&types.Value{")
+ if this.Kind != nil {
+ s = append(s, "Kind: "+fmt.Sprintf("%#v", this.Kind)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *Value_NullValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&types.Value_NullValue{` +
+ `NullValue:` + fmt.Sprintf("%#v", this.NullValue) + `}`}, ", ")
+ return s
+}
+func (this *Value_NumberValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&types.Value_NumberValue{` +
+ `NumberValue:` + fmt.Sprintf("%#v", this.NumberValue) + `}`}, ", ")
+ return s
+}
+func (this *Value_StringValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&types.Value_StringValue{` +
+ `StringValue:` + fmt.Sprintf("%#v", this.StringValue) + `}`}, ", ")
+ return s
+}
+func (this *Value_BoolValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&types.Value_BoolValue{` +
+ `BoolValue:` + fmt.Sprintf("%#v", this.BoolValue) + `}`}, ", ")
+ return s
+}
+func (this *Value_StructValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&types.Value_StructValue{` +
+ `StructValue:` + fmt.Sprintf("%#v", this.StructValue) + `}`}, ", ")
+ return s
+}
+func (this *Value_ListValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&types.Value_ListValue{` +
+ `ListValue:` + fmt.Sprintf("%#v", this.ListValue) + `}`}, ", ")
+ return s
+}
+func (this *ListValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.ListValue{")
+ if this.Values != nil {
+ s = append(s, "Values: "+fmt.Sprintf("%#v", this.Values)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringStruct(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func (m *Struct) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Struct) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Fields) > 0 {
+ for k := range m.Fields {
+ dAtA[i] = 0xa
+ i++
+ v := m.Fields[k]
+ msgSize := 0
+ if v != nil {
+ msgSize = v.Size()
+ msgSize += 1 + sovStruct(uint64(msgSize))
+ }
+ mapSize := 1 + len(k) + sovStruct(uint64(len(k))) + msgSize
+ i = encodeVarintStruct(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintStruct(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ if v != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintStruct(dAtA, i, uint64(v.Size()))
+ n1, err := v.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ }
+ }
+ }
+ return i, nil
+}
+
+func (m *Value) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Value) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Kind != nil {
+ nn2, err := m.Kind.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += nn2
+ }
+ return i, nil
+}
+
+func (m *Value_NullValue) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintStruct(dAtA, i, uint64(m.NullValue))
+ return i, nil
+}
+func (m *Value_NumberValue) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x11
+ i++
+ i = encodeFixed64Struct(dAtA, i, uint64(math.Float64bits(float64(m.NumberValue))))
+ return i, nil
+}
+func (m *Value_StringValue) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x1a
+ i++
+ i = encodeVarintStruct(dAtA, i, uint64(len(m.StringValue)))
+ i += copy(dAtA[i:], m.StringValue)
+ return i, nil
+}
+func (m *Value_BoolValue) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ dAtA[i] = 0x20
+ i++
+ if m.BoolValue {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ return i, nil
+}
+func (m *Value_StructValue) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.StructValue != nil {
+ dAtA[i] = 0x2a
+ i++
+ i = encodeVarintStruct(dAtA, i, uint64(m.StructValue.Size()))
+ n3, err := m.StructValue.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n3
+ }
+ return i, nil
+}
+func (m *Value_ListValue) MarshalTo(dAtA []byte) (int, error) {
+ i := 0
+ if m.ListValue != nil {
+ dAtA[i] = 0x32
+ i++
+ i = encodeVarintStruct(dAtA, i, uint64(m.ListValue.Size()))
+ n4, err := m.ListValue.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n4
+ }
+ return i, nil
+}
+func (m *ListValue) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *ListValue) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Values) > 0 {
+ for _, msg := range m.Values {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintStruct(dAtA, i, uint64(msg.Size()))
+ n, err := msg.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n
+ }
+ }
+ return i, nil
+}
+
+func encodeFixed64Struct(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Struct(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintStruct(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func NewPopulatedStruct(r randyStruct, easy bool) *Struct {
+ this := &Struct{}
+ if r.Intn(10) == 0 {
+ v1 := r.Intn(10)
+ this.Fields = make(map[string]*Value)
+ for i := 0; i < v1; i++ {
+ this.Fields[randStringStruct(r)] = NewPopulatedValue(r, easy)
+ }
+ }
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+func NewPopulatedValue(r randyStruct, easy bool) *Value {
+ this := &Value{}
+ oneofNumber_Kind := []int32{1, 2, 3, 4, 5, 6}[r.Intn(6)]
+ switch oneofNumber_Kind {
+ case 1:
+ this.Kind = NewPopulatedValue_NullValue(r, easy)
+ case 2:
+ this.Kind = NewPopulatedValue_NumberValue(r, easy)
+ case 3:
+ this.Kind = NewPopulatedValue_StringValue(r, easy)
+ case 4:
+ this.Kind = NewPopulatedValue_BoolValue(r, easy)
+ case 5:
+ this.Kind = NewPopulatedValue_StructValue(r, easy)
+ case 6:
+ this.Kind = NewPopulatedValue_ListValue(r, easy)
+ }
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+func NewPopulatedValue_NullValue(r randyStruct, easy bool) *Value_NullValue {
+ this := &Value_NullValue{}
+ this.NullValue = NullValue([]int32{0}[r.Intn(1)])
+ return this
+}
+func NewPopulatedValue_NumberValue(r randyStruct, easy bool) *Value_NumberValue {
+ this := &Value_NumberValue{}
+ this.NumberValue = float64(r.Float64())
+ if r.Intn(2) == 0 {
+ this.NumberValue *= -1
+ }
+ return this
+}
+func NewPopulatedValue_StringValue(r randyStruct, easy bool) *Value_StringValue {
+ this := &Value_StringValue{}
+ this.StringValue = string(randStringStruct(r))
+ return this
+}
+func NewPopulatedValue_BoolValue(r randyStruct, easy bool) *Value_BoolValue {
+ this := &Value_BoolValue{}
+ this.BoolValue = bool(bool(r.Intn(2) == 0))
+ return this
+}
+func NewPopulatedValue_StructValue(r randyStruct, easy bool) *Value_StructValue {
+ this := &Value_StructValue{}
+ this.StructValue = NewPopulatedStruct(r, easy)
+ return this
+}
+func NewPopulatedValue_ListValue(r randyStruct, easy bool) *Value_ListValue {
+ this := &Value_ListValue{}
+ this.ListValue = NewPopulatedListValue(r, easy)
+ return this
+}
+func NewPopulatedListValue(r randyStruct, easy bool) *ListValue {
+ this := &ListValue{}
+ if r.Intn(10) == 0 {
+ v2 := r.Intn(5)
+ this.Values = make([]*Value, v2)
+ for i := 0; i < v2; i++ {
+ this.Values[i] = NewPopulatedValue(r, easy)
+ }
+ }
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+type randyStruct interface {
+ Float32() float32
+ Float64() float64
+ Int63() int64
+ Int31() int32
+ Uint32() uint32
+ Intn(n int) int
+}
+
+func randUTF8RuneStruct(r randyStruct) rune {
+ ru := r.Intn(62)
+ if ru < 10 {
+ return rune(ru + 48)
+ } else if ru < 36 {
+ return rune(ru + 55)
+ }
+ return rune(ru + 61)
+}
+func randStringStruct(r randyStruct) string {
+ v3 := r.Intn(100)
+ tmps := make([]rune, v3)
+ for i := 0; i < v3; i++ {
+ tmps[i] = randUTF8RuneStruct(r)
+ }
+ return string(tmps)
+}
+func randUnrecognizedStruct(r randyStruct, maxFieldNumber int) (dAtA []byte) {
+ l := r.Intn(5)
+ for i := 0; i < l; i++ {
+ wire := r.Intn(4)
+ if wire == 3 {
+ wire = 5
+ }
+ fieldNumber := maxFieldNumber + r.Intn(100)
+ dAtA = randFieldStruct(dAtA, r, fieldNumber, wire)
+ }
+ return dAtA
+}
+func randFieldStruct(dAtA []byte, r randyStruct, fieldNumber int, wire int) []byte {
+ key := uint32(fieldNumber)<<3 | uint32(wire)
+ switch wire {
+ case 0:
+ dAtA = encodeVarintPopulateStruct(dAtA, uint64(key))
+ v4 := r.Int63()
+ if r.Intn(2) == 0 {
+ v4 *= -1
+ }
+ dAtA = encodeVarintPopulateStruct(dAtA, uint64(v4))
+ case 1:
+ dAtA = encodeVarintPopulateStruct(dAtA, uint64(key))
+ dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
+ case 2:
+ dAtA = encodeVarintPopulateStruct(dAtA, uint64(key))
+ ll := r.Intn(100)
+ dAtA = encodeVarintPopulateStruct(dAtA, uint64(ll))
+ for j := 0; j < ll; j++ {
+ dAtA = append(dAtA, byte(r.Intn(256)))
+ }
+ default:
+ dAtA = encodeVarintPopulateStruct(dAtA, uint64(key))
+ dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
+ }
+ return dAtA
+}
+func encodeVarintPopulateStruct(dAtA []byte, v uint64) []byte {
+ for v >= 1<<7 {
+ dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
+ v >>= 7
+ }
+ dAtA = append(dAtA, uint8(v))
+ return dAtA
+}
+func (m *Struct) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Fields) > 0 {
+ for k, v := range m.Fields {
+ _ = k
+ _ = v
+ l = 0
+ if v != nil {
+ l = v.Size()
+ l += 1 + sovStruct(uint64(l))
+ }
+ mapEntrySize := 1 + len(k) + sovStruct(uint64(len(k))) + l
+ n += mapEntrySize + 1 + sovStruct(uint64(mapEntrySize))
+ }
+ }
+ return n
+}
+
+func (m *Value) Size() (n int) {
+ var l int
+ _ = l
+ if m.Kind != nil {
+ n += m.Kind.Size()
+ }
+ return n
+}
+
+func (m *Value_NullValue) Size() (n int) {
+ var l int
+ _ = l
+ n += 1 + sovStruct(uint64(m.NullValue))
+ return n
+}
+func (m *Value_NumberValue) Size() (n int) {
+ var l int
+ _ = l
+ n += 9
+ return n
+}
+func (m *Value_StringValue) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.StringValue)
+ n += 1 + l + sovStruct(uint64(l))
+ return n
+}
+func (m *Value_BoolValue) Size() (n int) {
+ var l int
+ _ = l
+ n += 2
+ return n
+}
+func (m *Value_StructValue) Size() (n int) {
+ var l int
+ _ = l
+ if m.StructValue != nil {
+ l = m.StructValue.Size()
+ n += 1 + l + sovStruct(uint64(l))
+ }
+ return n
+}
+func (m *Value_ListValue) Size() (n int) {
+ var l int
+ _ = l
+ if m.ListValue != nil {
+ l = m.ListValue.Size()
+ n += 1 + l + sovStruct(uint64(l))
+ }
+ return n
+}
+func (m *ListValue) Size() (n int) {
+ var l int
+ _ = l
+ if len(m.Values) > 0 {
+ for _, e := range m.Values {
+ l = e.Size()
+ n += 1 + l + sovStruct(uint64(l))
+ }
+ }
+ return n
+}
+
+func sovStruct(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozStruct(x uint64) (n int) {
+ return sovStruct(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *Struct) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForFields := make([]string, 0, len(this.Fields))
+ for k := range this.Fields {
+ keysForFields = append(keysForFields, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForFields)
+ mapStringForFields := "map[string]*Value{"
+ for _, k := range keysForFields {
+ mapStringForFields += fmt.Sprintf("%v: %v,", k, this.Fields[k])
+ }
+ mapStringForFields += "}"
+ s := strings.Join([]string{`&Struct{`,
+ `Fields:` + mapStringForFields + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Value) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Value{`,
+ `Kind:` + fmt.Sprintf("%v", this.Kind) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Value_NullValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Value_NullValue{`,
+ `NullValue:` + fmt.Sprintf("%v", this.NullValue) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Value_NumberValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Value_NumberValue{`,
+ `NumberValue:` + fmt.Sprintf("%v", this.NumberValue) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Value_StringValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Value_StringValue{`,
+ `StringValue:` + fmt.Sprintf("%v", this.StringValue) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Value_BoolValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Value_BoolValue{`,
+ `BoolValue:` + fmt.Sprintf("%v", this.BoolValue) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Value_StructValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Value_StructValue{`,
+ `StructValue:` + strings.Replace(fmt.Sprintf("%v", this.StructValue), "Struct", "Struct", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Value_ListValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Value_ListValue{`,
+ `ListValue:` + strings.Replace(fmt.Sprintf("%v", this.ListValue), "ListValue", "ListValue", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *ListValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&ListValue{`,
+ `Values:` + strings.Replace(fmt.Sprintf("%v", this.Values), "Value", "Value", 1) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringStruct(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *Struct) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Struct: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Struct: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Fields", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthStruct
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthStruct
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Fields == nil {
+ m.Fields = make(map[string]*Value)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var mapmsglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ mapmsglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if mapmsglen < 0 {
+ return ErrInvalidLengthStruct
+ }
+ postmsgIndex := iNdEx + mapmsglen
+ if mapmsglen < 0 {
+ return ErrInvalidLengthStruct
+ }
+ if postmsgIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := &Value{}
+ if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil {
+ return err
+ }
+ iNdEx = postmsgIndex
+ m.Fields[mapkey] = mapvalue
+ } else {
+ var mapvalue *Value
+ m.Fields[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipStruct(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthStruct
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Value) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Value: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Value: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NullValue", wireType)
+ }
+ var v NullValue
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (NullValue(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Kind = &Value_NullValue{v}
+ case 2:
+ if wireType != 1 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NumberValue", wireType)
+ }
+ var v uint64
+ if (iNdEx + 8) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += 8
+ v = uint64(dAtA[iNdEx-8])
+ v |= uint64(dAtA[iNdEx-7]) << 8
+ v |= uint64(dAtA[iNdEx-6]) << 16
+ v |= uint64(dAtA[iNdEx-5]) << 24
+ v |= uint64(dAtA[iNdEx-4]) << 32
+ v |= uint64(dAtA[iNdEx-3]) << 40
+ v |= uint64(dAtA[iNdEx-2]) << 48
+ v |= uint64(dAtA[iNdEx-1]) << 56
+ m.Kind = &Value_NumberValue{float64(math.Float64frombits(v))}
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field StringValue", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthStruct
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Kind = &Value_StringValue{string(dAtA[iNdEx:postIndex])}
+ iNdEx = postIndex
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field BoolValue", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ b := bool(v != 0)
+ m.Kind = &Value_BoolValue{b}
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field StructValue", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthStruct
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &Struct{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Kind = &Value_StructValue{v}
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ListValue", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthStruct
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ v := &ListValue{}
+ if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ m.Kind = &Value_ListValue{v}
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipStruct(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthStruct
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *ListValue) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: ListValue: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: ListValue: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Values", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthStruct
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Values = append(m.Values, &Value{})
+ if err := m.Values[len(m.Values)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipStruct(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthStruct
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipStruct(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthStruct
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowStruct
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipStruct(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthStruct = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowStruct = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("struct.proto", fileDescriptorStruct) }
+
+var fileDescriptorStruct = []byte{
+ // 432 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0xc1, 0x6b, 0xd4, 0x40,
+ 0x14, 0xc6, 0xf3, 0xb2, 0xdd, 0xe0, 0xbe, 0x94, 0x5a, 0x46, 0xd0, 0xa5, 0xc2, 0xb8, 0x6c, 0x2f,
+ 0x41, 0x24, 0x87, 0xf5, 0x22, 0xae, 0x17, 0x03, 0xb5, 0x05, 0x43, 0x89, 0xd1, 0x56, 0xf0, 0xb2,
+ 0x98, 0x6d, 0xba, 0x84, 0x4e, 0x67, 0x4a, 0x32, 0x51, 0xf6, 0xa6, 0xff, 0x85, 0x47, 0xf1, 0x24,
+ 0x1e, 0xfd, 0x2b, 0x3c, 0xf6, 0xe8, 0xd1, 0xe4, 0xe4, 0xb1, 0x47, 0x8f, 0x32, 0x33, 0x49, 0x94,
+ 0x2e, 0x7b, 0xcb, 0xfb, 0xf2, 0x7b, 0xdf, 0x7b, 0xdf, 0x1b, 0xdc, 0x2c, 0x64, 0x5e, 0xce, 0xa5,
+ 0x7f, 0x91, 0x0b, 0x29, 0xc8, 0xcd, 0x85, 0x10, 0x0b, 0x96, 0x9a, 0x2a, 0x29, 0x4f, 0xc7, 0x9f,
+ 0x00, 0x9d, 0x97, 0x9a, 0x20, 0x53, 0x74, 0x4e, 0xb3, 0x94, 0x9d, 0x14, 0x43, 0x18, 0xf5, 0x3c,
+ 0x77, 0xb2, 0xeb, 0x5f, 0x83, 0x7d, 0x03, 0xfa, 0xcf, 0x34, 0xb5, 0xc7, 0x65, 0xbe, 0x8c, 0x9b,
+ 0x96, 0x9d, 0x17, 0xe8, 0xfe, 0x27, 0x93, 0x6d, 0xec, 0x9d, 0xa5, 0xcb, 0x21, 0x8c, 0xc0, 0x1b,
+ 0xc4, 0xea, 0x93, 0x3c, 0xc0, 0xfe, 0xbb, 0xb7, 0xac, 0x4c, 0x87, 0xf6, 0x08, 0x3c, 0x77, 0x72,
+ 0x7b, 0xc5, 0xfc, 0x58, 0xfd, 0x8d, 0x0d, 0xf4, 0xd8, 0x7e, 0x04, 0xe3, 0xef, 0x36, 0xf6, 0xb5,
+ 0x48, 0xa6, 0x88, 0xbc, 0x64, 0x6c, 0x66, 0x0c, 0x94, 0xe9, 0xd6, 0x64, 0x67, 0xc5, 0xe0, 0xb0,
+ 0x64, 0x4c, 0xf3, 0x07, 0x56, 0x3c, 0xe0, 0x6d, 0x41, 0x76, 0x71, 0x93, 0x97, 0xe7, 0x49, 0x9a,
+ 0xcf, 0xfe, 0xcd, 0x87, 0x03, 0x2b, 0x76, 0x8d, 0xda, 0x41, 0x85, 0xcc, 0x33, 0xbe, 0x68, 0xa0,
+ 0x9e, 0x5a, 0x5c, 0x41, 0x46, 0x35, 0xd0, 0x3d, 0xc4, 0x44, 0x88, 0x76, 0x8d, 0x8d, 0x11, 0x78,
+ 0x37, 0xd4, 0x28, 0xa5, 0x19, 0xe0, 0x49, 0x7b, 0xed, 0x06, 0xe9, 0xeb, 0xa8, 0x77, 0xd6, 0xdc,
+ 0xb1, 0xb1, 0x2f, 0xe7, 0xb2, 0x4b, 0xc9, 0xb2, 0xa2, 0xed, 0x75, 0x74, 0xef, 0x6a, 0xca, 0x30,
+ 0x2b, 0x64, 0x97, 0x92, 0xb5, 0x45, 0xe0, 0xe0, 0xc6, 0x59, 0xc6, 0x4f, 0xc6, 0x53, 0x1c, 0x74,
+ 0x04, 0xf1, 0xd1, 0xd1, 0x66, 0xed, 0x8b, 0xae, 0x3b, 0x7a, 0x43, 0xdd, 0xbf, 0x8b, 0x83, 0xee,
+ 0x88, 0x64, 0x0b, 0xf1, 0xf0, 0x28, 0x0c, 0x67, 0xc7, 0x4f, 0xc3, 0xa3, 0xbd, 0x6d, 0x2b, 0xf8,
+ 0x08, 0x97, 0x15, 0xb5, 0x7e, 0x56, 0xd4, 0xba, 0xaa, 0x28, 0xfc, 0xa9, 0x28, 0x7c, 0xa8, 0x29,
+ 0x7c, 0xad, 0x29, 0xfc, 0xa8, 0x29, 0x5c, 0xd6, 0x14, 0x7e, 0xd5, 0x14, 0x7e, 0xd7, 0xd4, 0xba,
+ 0xaa, 0x29, 0xe0, 0xad, 0xb9, 0x38, 0xbf, 0x3e, 0x2e, 0x70, 0x4d, 0xf2, 0x48, 0xd5, 0x11, 0xbc,
+ 0xe9, 0xcb, 0xe5, 0x45, 0x5a, 0x7c, 0x06, 0xf8, 0x62, 0xf7, 0xf6, 0xa3, 0xe0, 0x9b, 0x4d, 0xf7,
+ 0x4d, 0x43, 0xd4, 0xee, 0xf7, 0x3a, 0x65, 0xec, 0x39, 0x17, 0xef, 0xf9, 0x2b, 0x45, 0x26, 0x8e,
+ 0x76, 0x7a, 0xf8, 0x37, 0x00, 0x00, 0xff, 0xff, 0x52, 0x64, 0x2c, 0x57, 0xd5, 0x02, 0x00, 0x00,
+}
diff --git a/vendor/github.com/gogo/protobuf/types/timestamp.go b/vendor/github.com/gogo/protobuf/types/timestamp.go
new file mode 100644
index 0000000..521b62d
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/timestamp.go
@@ -0,0 +1,123 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package types
+
+// This file implements operations on google.protobuf.Timestamp.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+)
+
+const (
+ // Seconds field of the earliest valid Timestamp.
+ // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
+ minValidSeconds = -62135596800
+ // Seconds field just after the latest valid Timestamp.
+ // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
+ maxValidSeconds = 253402300800
+)
+
+// validateTimestamp determines whether a Timestamp is valid.
+// A valid timestamp represents a time in the range
+// [0001-01-01, 10000-01-01) and has a Nanos field
+// in the range [0, 1e9).
+//
+// If the Timestamp is valid, validateTimestamp returns nil.
+// Otherwise, it returns an error that describes
+// the problem.
+//
+// Every valid Timestamp can be represented by a time.Time, but the converse is not true.
+func validateTimestamp(ts *Timestamp) error {
+ if ts == nil {
+ return errors.New("timestamp: nil Timestamp")
+ }
+ if ts.Seconds < minValidSeconds {
+ return fmt.Errorf("timestamp: %#v before 0001-01-01", ts)
+ }
+ if ts.Seconds >= maxValidSeconds {
+ return fmt.Errorf("timestamp: %#v after 10000-01-01", ts)
+ }
+ if ts.Nanos < 0 || ts.Nanos >= 1e9 {
+ return fmt.Errorf("timestamp: %#v: nanos not in range [0, 1e9)", ts)
+ }
+ return nil
+}
+
+// TimestampFromProto converts a google.protobuf.Timestamp proto to a time.Time.
+// It returns an error if the argument is invalid.
+//
+// Unlike most Go functions, if Timestamp returns an error, the first return value
+// is not the zero time.Time. Instead, it is the value obtained from the
+// time.Unix function when passed the contents of the Timestamp, in the UTC
+// locale. This may or may not be a meaningful time; many invalid Timestamps
+// do map to valid time.Times.
+//
+// A nil Timestamp returns an error. The first return value in that case is
+// undefined.
+func TimestampFromProto(ts *Timestamp) (time.Time, error) {
+ // Don't return the zero value on error, because corresponds to a valid
+ // timestamp. Instead return whatever time.Unix gives us.
+ var t time.Time
+ if ts == nil {
+ t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp
+ } else {
+ t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
+ }
+ return t, validateTimestamp(ts)
+}
+
+// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
+// It returns an error if the resulting Timestamp is invalid.
+func TimestampProto(t time.Time) (*Timestamp, error) {
+ seconds := t.Unix()
+ nanos := int32(t.Sub(time.Unix(seconds, 0)))
+ ts := &Timestamp{
+ Seconds: seconds,
+ Nanos: nanos,
+ }
+ if err := validateTimestamp(ts); err != nil {
+ return nil, err
+ }
+ return ts, nil
+}
+
+// TimestampString returns the RFC 3339 string for valid Timestamps. For invalid
+// Timestamps, it returns an error message in parentheses.
+func TimestampString(ts *Timestamp) string {
+ t, err := TimestampFromProto(ts)
+ if err != nil {
+ return fmt.Sprintf("(%v)", err)
+ }
+ return t.Format(time.RFC3339Nano)
+}
diff --git a/vendor/github.com/gogo/protobuf/types/timestamp.pb.go b/vendor/github.com/gogo/protobuf/types/timestamp.pb.go
new file mode 100644
index 0000000..5642421
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/timestamp.pb.go
@@ -0,0 +1,506 @@
+// Code generated by protoc-gen-gogo.
+// source: timestamp.proto
+// DO NOT EDIT!
+
+/*
+ Package types is a generated protocol buffer package.
+
+ It is generated from these files:
+ timestamp.proto
+
+ It has these top-level messages:
+ Timestamp
+*/
+package types
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+// A Timestamp represents a point in time independent of any time zone
+// or calendar, represented as seconds and fractions of seconds at
+// nanosecond resolution in UTC Epoch time. It is encoded using the
+// Proleptic Gregorian Calendar which extends the Gregorian calendar
+// backwards to year one. It is encoded assuming all minutes are 60
+// seconds long, i.e. leap seconds are "smeared" so that no leap second
+// table is needed for interpretation. Range is from
+// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
+// By restricting to that range, we ensure that we can convert to
+// and from RFC 3339 date strings.
+// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
+//
+// Example 1: Compute Timestamp from POSIX `time()`.
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(time(NULL));
+// timestamp.set_nanos(0);
+//
+// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
+//
+// struct timeval tv;
+// gettimeofday(&tv, NULL);
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(tv.tv_sec);
+// timestamp.set_nanos(tv.tv_usec * 1000);
+//
+// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
+//
+// FILETIME ft;
+// GetSystemTimeAsFileTime(&ft);
+// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+//
+// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
+// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
+// Timestamp timestamp;
+// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
+// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
+//
+// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
+//
+// long millis = System.currentTimeMillis();
+//
+// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
+// .setNanos((int) ((millis % 1000) * 1000000)).build();
+//
+//
+// Example 5: Compute Timestamp from current time in Python.
+//
+// now = time.time()
+// seconds = int(now)
+// nanos = int((now - seconds) * 10**9)
+// timestamp = Timestamp(seconds=seconds, nanos=nanos)
+//
+//
+type Timestamp struct {
+ // Represents seconds of UTC time since Unix epoch
+ // 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to
+ // 9999-12-31T23:59:59Z inclusive.
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
+ // Non-negative fractions of a second at nanosecond resolution. Negative
+ // second values with fractions must still have non-negative nanos values
+ // that count forward in time. Must be from 0 to 999,999,999
+ // inclusive.
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
+}
+
+func (m *Timestamp) Reset() { *m = Timestamp{} }
+func (*Timestamp) ProtoMessage() {}
+func (*Timestamp) Descriptor() ([]byte, []int) { return fileDescriptorTimestamp, []int{0} }
+func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" }
+
+func (m *Timestamp) GetSeconds() int64 {
+ if m != nil {
+ return m.Seconds
+ }
+ return 0
+}
+
+func (m *Timestamp) GetNanos() int32 {
+ if m != nil {
+ return m.Nanos
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp")
+}
+func (this *Timestamp) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*Timestamp)
+ if !ok {
+ that2, ok := that.(Timestamp)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.Seconds != that1.Seconds {
+ if this.Seconds < that1.Seconds {
+ return -1
+ }
+ return 1
+ }
+ if this.Nanos != that1.Nanos {
+ if this.Nanos < that1.Nanos {
+ return -1
+ }
+ return 1
+ }
+ return 0
+}
+func (this *Timestamp) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Timestamp)
+ if !ok {
+ that2, ok := that.(Timestamp)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Seconds != that1.Seconds {
+ return false
+ }
+ if this.Nanos != that1.Nanos {
+ return false
+ }
+ return true
+}
+func (this *Timestamp) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&types.Timestamp{")
+ s = append(s, "Seconds: "+fmt.Sprintf("%#v", this.Seconds)+",\n")
+ s = append(s, "Nanos: "+fmt.Sprintf("%#v", this.Nanos)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringTimestamp(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func (m *Timestamp) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Timestamp) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Seconds != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintTimestamp(dAtA, i, uint64(m.Seconds))
+ }
+ if m.Nanos != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintTimestamp(dAtA, i, uint64(m.Nanos))
+ }
+ return i, nil
+}
+
+func encodeFixed64Timestamp(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Timestamp(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintTimestamp(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func (m *Timestamp) Size() (n int) {
+ var l int
+ _ = l
+ if m.Seconds != 0 {
+ n += 1 + sovTimestamp(uint64(m.Seconds))
+ }
+ if m.Nanos != 0 {
+ n += 1 + sovTimestamp(uint64(m.Nanos))
+ }
+ return n
+}
+
+func sovTimestamp(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozTimestamp(x uint64) (n int) {
+ return sovTimestamp(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (m *Timestamp) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTimestamp
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Timestamp: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Timestamp: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Seconds", wireType)
+ }
+ m.Seconds = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTimestamp
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Seconds |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Nanos", wireType)
+ }
+ m.Nanos = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowTimestamp
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Nanos |= (int32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipTimestamp(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthTimestamp
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipTimestamp(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowTimestamp
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowTimestamp
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowTimestamp
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthTimestamp
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowTimestamp
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipTimestamp(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthTimestamp = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowTimestamp = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("timestamp.proto", fileDescriptorTimestamp) }
+
+var fileDescriptorTimestamp = []byte{
+ // 208 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2f, 0xc9, 0xcc, 0x4d,
+ 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, 0xcf,
+ 0x4f, 0xcf, 0x49, 0x85, 0xf0, 0x92, 0x4a, 0xd3, 0x94, 0xac, 0xb9, 0x38, 0x43, 0x60, 0x6a, 0x84,
+ 0x24, 0xb8, 0xd8, 0x8b, 0x53, 0x93, 0xf3, 0xf3, 0x52, 0x8a, 0x25, 0x18, 0x15, 0x18, 0x35, 0x98,
+ 0x83, 0x60, 0x5c, 0x21, 0x11, 0x2e, 0xd6, 0xbc, 0xc4, 0xbc, 0xfc, 0x62, 0x09, 0x26, 0x05, 0x46,
+ 0x0d, 0xd6, 0x20, 0x08, 0xc7, 0xa9, 0x99, 0xf1, 0xc2, 0x43, 0x39, 0x86, 0x1b, 0x0f, 0xe5, 0x18,
+ 0x3e, 0x3c, 0x94, 0x63, 0x5c, 0xf1, 0x48, 0x8e, 0xf1, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4,
+ 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x7c, 0xf1, 0x48, 0x8e, 0xe1, 0xc3, 0x23, 0x39, 0xc6, 0x15, 0x8f,
+ 0xe5, 0x18, 0xb9, 0x84, 0x93, 0xf3, 0x73, 0xf5, 0xd0, 0x2c, 0x77, 0xe2, 0x83, 0x5b, 0x1d, 0x00,
+ 0x12, 0x0a, 0x60, 0x8c, 0x62, 0x2d, 0xa9, 0x2c, 0x48, 0x2d, 0x5e, 0xc0, 0xc8, 0xf8, 0x83, 0x91,
+ 0x71, 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xb6, 0x00, 0xa8, 0x36,
+ 0xbd, 0xf0, 0xd4, 0x9c, 0x1c, 0xef, 0xbc, 0xfc, 0xf2, 0xbc, 0x10, 0x90, 0xe2, 0x24, 0x36, 0xb0,
+ 0x79, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7c, 0x4d, 0xbd, 0x9c, 0xed, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/gogo/protobuf/types/timestamp_gogo.go b/vendor/github.com/gogo/protobuf/types/timestamp_gogo.go
new file mode 100644
index 0000000..e03fa13
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/timestamp_gogo.go
@@ -0,0 +1,94 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2016, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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
+// 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 types
+
+import (
+ "time"
+)
+
+func NewPopulatedTimestamp(r interface {
+ Int63() int64
+}, easy bool) *Timestamp {
+ this := &Timestamp{}
+ ns := int64(r.Int63())
+ this.Seconds = ns / 1e9
+ this.Nanos = int32(ns % 1e9)
+ return this
+}
+
+func (ts *Timestamp) String() string {
+ return TimestampString(ts)
+}
+
+func NewPopulatedStdTime(r interface {
+ Int63() int64
+}, easy bool) *time.Time {
+ timestamp := NewPopulatedTimestamp(r, easy)
+ t, err := TimestampFromProto(timestamp)
+ if err != nil {
+ return nil
+ }
+ return &t
+}
+
+func SizeOfStdTime(t time.Time) int {
+ ts, err := TimestampProto(t)
+ if err != nil {
+ return 0
+ }
+ return ts.Size()
+}
+
+func StdTimeMarshal(t time.Time) ([]byte, error) {
+ size := SizeOfStdTime(t)
+ buf := make([]byte, size)
+ _, err := StdTimeMarshalTo(t, buf)
+ return buf, err
+}
+
+func StdTimeMarshalTo(t time.Time, data []byte) (int, error) {
+ ts, err := TimestampProto(t)
+ if err != nil {
+ return 0, err
+ }
+ return ts.MarshalTo(data)
+}
+
+func StdTimeUnmarshal(t *time.Time, data []byte) error {
+ ts := &Timestamp{}
+ if err := ts.Unmarshal(data); err != nil {
+ return err
+ }
+ tt, err := TimestampFromProto(ts)
+ if err != nil {
+ return err
+ }
+ *t = tt
+ return nil
+}
diff --git a/vendor/github.com/gogo/protobuf/types/wrappers.pb.go b/vendor/github.com/gogo/protobuf/types/wrappers.pb.go
new file mode 100644
index 0000000..bdffe4e
--- /dev/null
+++ b/vendor/github.com/gogo/protobuf/types/wrappers.pb.go
@@ -0,0 +1,2259 @@
+// Code generated by protoc-gen-gogo.
+// source: wrappers.proto
+// DO NOT EDIT!
+
+/*
+Package types is a generated protocol buffer package.
+
+It is generated from these files:
+ wrappers.proto
+
+It has these top-level messages:
+ DoubleValue
+ FloatValue
+ Int64Value
+ UInt64Value
+ Int32Value
+ UInt32Value
+ BoolValue
+ StringValue
+ BytesValue
+*/
+package types
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+import bytes "bytes"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+// Wrapper message for `double`.
+//
+// The JSON representation for `DoubleValue` is JSON number.
+type DoubleValue struct {
+ // The double value.
+ Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *DoubleValue) Reset() { *m = DoubleValue{} }
+func (*DoubleValue) ProtoMessage() {}
+func (*DoubleValue) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{0} }
+func (*DoubleValue) XXX_WellKnownType() string { return "DoubleValue" }
+
+func (m *DoubleValue) GetValue() float64 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `float`.
+//
+// The JSON representation for `FloatValue` is JSON number.
+type FloatValue struct {
+ // The float value.
+ Value float32 `protobuf:"fixed32,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *FloatValue) Reset() { *m = FloatValue{} }
+func (*FloatValue) ProtoMessage() {}
+func (*FloatValue) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{1} }
+func (*FloatValue) XXX_WellKnownType() string { return "FloatValue" }
+
+func (m *FloatValue) GetValue() float32 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `int64`.
+//
+// The JSON representation for `Int64Value` is JSON string.
+type Int64Value struct {
+ // The int64 value.
+ Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *Int64Value) Reset() { *m = Int64Value{} }
+func (*Int64Value) ProtoMessage() {}
+func (*Int64Value) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{2} }
+func (*Int64Value) XXX_WellKnownType() string { return "Int64Value" }
+
+func (m *Int64Value) GetValue() int64 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `uint64`.
+//
+// The JSON representation for `UInt64Value` is JSON string.
+type UInt64Value struct {
+ // The uint64 value.
+ Value uint64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *UInt64Value) Reset() { *m = UInt64Value{} }
+func (*UInt64Value) ProtoMessage() {}
+func (*UInt64Value) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{3} }
+func (*UInt64Value) XXX_WellKnownType() string { return "UInt64Value" }
+
+func (m *UInt64Value) GetValue() uint64 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `int32`.
+//
+// The JSON representation for `Int32Value` is JSON number.
+type Int32Value struct {
+ // The int32 value.
+ Value int32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *Int32Value) Reset() { *m = Int32Value{} }
+func (*Int32Value) ProtoMessage() {}
+func (*Int32Value) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{4} }
+func (*Int32Value) XXX_WellKnownType() string { return "Int32Value" }
+
+func (m *Int32Value) GetValue() int32 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `uint32`.
+//
+// The JSON representation for `UInt32Value` is JSON number.
+type UInt32Value struct {
+ // The uint32 value.
+ Value uint32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *UInt32Value) Reset() { *m = UInt32Value{} }
+func (*UInt32Value) ProtoMessage() {}
+func (*UInt32Value) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{5} }
+func (*UInt32Value) XXX_WellKnownType() string { return "UInt32Value" }
+
+func (m *UInt32Value) GetValue() uint32 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `bool`.
+//
+// The JSON representation for `BoolValue` is JSON `true` and `false`.
+type BoolValue struct {
+ // The bool value.
+ Value bool `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *BoolValue) Reset() { *m = BoolValue{} }
+func (*BoolValue) ProtoMessage() {}
+func (*BoolValue) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{6} }
+func (*BoolValue) XXX_WellKnownType() string { return "BoolValue" }
+
+func (m *BoolValue) GetValue() bool {
+ if m != nil {
+ return m.Value
+ }
+ return false
+}
+
+// Wrapper message for `string`.
+//
+// The JSON representation for `StringValue` is JSON string.
+type StringValue struct {
+ // The string value.
+ Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *StringValue) Reset() { *m = StringValue{} }
+func (*StringValue) ProtoMessage() {}
+func (*StringValue) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{7} }
+func (*StringValue) XXX_WellKnownType() string { return "StringValue" }
+
+func (m *StringValue) GetValue() string {
+ if m != nil {
+ return m.Value
+ }
+ return ""
+}
+
+// Wrapper message for `bytes`.
+//
+// The JSON representation for `BytesValue` is JSON string.
+type BytesValue struct {
+ // The bytes value.
+ Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *BytesValue) Reset() { *m = BytesValue{} }
+func (*BytesValue) ProtoMessage() {}
+func (*BytesValue) Descriptor() ([]byte, []int) { return fileDescriptorWrappers, []int{8} }
+func (*BytesValue) XXX_WellKnownType() string { return "BytesValue" }
+
+func (m *BytesValue) GetValue() []byte {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*DoubleValue)(nil), "google.protobuf.DoubleValue")
+ proto.RegisterType((*FloatValue)(nil), "google.protobuf.FloatValue")
+ proto.RegisterType((*Int64Value)(nil), "google.protobuf.Int64Value")
+ proto.RegisterType((*UInt64Value)(nil), "google.protobuf.UInt64Value")
+ proto.RegisterType((*Int32Value)(nil), "google.protobuf.Int32Value")
+ proto.RegisterType((*UInt32Value)(nil), "google.protobuf.UInt32Value")
+ proto.RegisterType((*BoolValue)(nil), "google.protobuf.BoolValue")
+ proto.RegisterType((*StringValue)(nil), "google.protobuf.StringValue")
+ proto.RegisterType((*BytesValue)(nil), "google.protobuf.BytesValue")
+}
+func (this *DoubleValue) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*DoubleValue)
+ if !ok {
+ that2, ok := that.(DoubleValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.Value != that1.Value {
+ if this.Value < that1.Value {
+ return -1
+ }
+ return 1
+ }
+ return 0
+}
+func (this *FloatValue) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*FloatValue)
+ if !ok {
+ that2, ok := that.(FloatValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.Value != that1.Value {
+ if this.Value < that1.Value {
+ return -1
+ }
+ return 1
+ }
+ return 0
+}
+func (this *Int64Value) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*Int64Value)
+ if !ok {
+ that2, ok := that.(Int64Value)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.Value != that1.Value {
+ if this.Value < that1.Value {
+ return -1
+ }
+ return 1
+ }
+ return 0
+}
+func (this *UInt64Value) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*UInt64Value)
+ if !ok {
+ that2, ok := that.(UInt64Value)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.Value != that1.Value {
+ if this.Value < that1.Value {
+ return -1
+ }
+ return 1
+ }
+ return 0
+}
+func (this *Int32Value) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*Int32Value)
+ if !ok {
+ that2, ok := that.(Int32Value)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.Value != that1.Value {
+ if this.Value < that1.Value {
+ return -1
+ }
+ return 1
+ }
+ return 0
+}
+func (this *UInt32Value) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*UInt32Value)
+ if !ok {
+ that2, ok := that.(UInt32Value)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.Value != that1.Value {
+ if this.Value < that1.Value {
+ return -1
+ }
+ return 1
+ }
+ return 0
+}
+func (this *BoolValue) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*BoolValue)
+ if !ok {
+ that2, ok := that.(BoolValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.Value != that1.Value {
+ if !this.Value {
+ return -1
+ }
+ return 1
+ }
+ return 0
+}
+func (this *StringValue) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*StringValue)
+ if !ok {
+ that2, ok := that.(StringValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if this.Value != that1.Value {
+ if this.Value < that1.Value {
+ return -1
+ }
+ return 1
+ }
+ return 0
+}
+func (this *BytesValue) Compare(that interface{}) int {
+ if that == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ }
+
+ that1, ok := that.(*BytesValue)
+ if !ok {
+ that2, ok := that.(BytesValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return 1
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return 0
+ }
+ return 1
+ } else if this == nil {
+ return -1
+ }
+ if c := bytes.Compare(this.Value, that1.Value); c != 0 {
+ return c
+ }
+ return 0
+}
+func (this *DoubleValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*DoubleValue)
+ if !ok {
+ that2, ok := that.(DoubleValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Value != that1.Value {
+ return false
+ }
+ return true
+}
+func (this *FloatValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*FloatValue)
+ if !ok {
+ that2, ok := that.(FloatValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Value != that1.Value {
+ return false
+ }
+ return true
+}
+func (this *Int64Value) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Int64Value)
+ if !ok {
+ that2, ok := that.(Int64Value)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Value != that1.Value {
+ return false
+ }
+ return true
+}
+func (this *UInt64Value) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*UInt64Value)
+ if !ok {
+ that2, ok := that.(UInt64Value)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Value != that1.Value {
+ return false
+ }
+ return true
+}
+func (this *Int32Value) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Int32Value)
+ if !ok {
+ that2, ok := that.(Int32Value)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Value != that1.Value {
+ return false
+ }
+ return true
+}
+func (this *UInt32Value) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*UInt32Value)
+ if !ok {
+ that2, ok := that.(UInt32Value)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Value != that1.Value {
+ return false
+ }
+ return true
+}
+func (this *BoolValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*BoolValue)
+ if !ok {
+ that2, ok := that.(BoolValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Value != that1.Value {
+ return false
+ }
+ return true
+}
+func (this *StringValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*StringValue)
+ if !ok {
+ that2, ok := that.(StringValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Value != that1.Value {
+ return false
+ }
+ return true
+}
+func (this *BytesValue) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*BytesValue)
+ if !ok {
+ that2, ok := that.(BytesValue)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if !bytes.Equal(this.Value, that1.Value) {
+ return false
+ }
+ return true
+}
+func (this *DoubleValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.DoubleValue{")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *FloatValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.FloatValue{")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *Int64Value) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.Int64Value{")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *UInt64Value) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.UInt64Value{")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *Int32Value) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.Int32Value{")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *UInt32Value) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.UInt32Value{")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *BoolValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.BoolValue{")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *StringValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.StringValue{")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *BytesValue) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&types.BytesValue{")
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringWrappers(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func (m *DoubleValue) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *DoubleValue) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Value != 0 {
+ dAtA[i] = 0x9
+ i++
+ i = encodeFixed64Wrappers(dAtA, i, uint64(math.Float64bits(float64(m.Value))))
+ }
+ return i, nil
+}
+
+func (m *FloatValue) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *FloatValue) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Value != 0 {
+ dAtA[i] = 0xd
+ i++
+ i = encodeFixed32Wrappers(dAtA, i, uint32(math.Float32bits(float32(m.Value))))
+ }
+ return i, nil
+}
+
+func (m *Int64Value) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Int64Value) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Value != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintWrappers(dAtA, i, uint64(m.Value))
+ }
+ return i, nil
+}
+
+func (m *UInt64Value) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UInt64Value) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Value != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintWrappers(dAtA, i, uint64(m.Value))
+ }
+ return i, nil
+}
+
+func (m *Int32Value) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Int32Value) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Value != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintWrappers(dAtA, i, uint64(m.Value))
+ }
+ return i, nil
+}
+
+func (m *UInt32Value) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *UInt32Value) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Value != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintWrappers(dAtA, i, uint64(m.Value))
+ }
+ return i, nil
+}
+
+func (m *BoolValue) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *BoolValue) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Value {
+ dAtA[i] = 0x8
+ i++
+ if m.Value {
+ dAtA[i] = 1
+ } else {
+ dAtA[i] = 0
+ }
+ i++
+ }
+ return i, nil
+}
+
+func (m *StringValue) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *StringValue) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Value) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintWrappers(dAtA, i, uint64(len(m.Value)))
+ i += copy(dAtA[i:], m.Value)
+ }
+ return i, nil
+}
+
+func (m *BytesValue) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *BytesValue) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Value) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintWrappers(dAtA, i, uint64(len(m.Value)))
+ i += copy(dAtA[i:], m.Value)
+ }
+ return i, nil
+}
+
+func encodeFixed64Wrappers(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Wrappers(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintWrappers(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func NewPopulatedDoubleValue(r randyWrappers, easy bool) *DoubleValue {
+ this := &DoubleValue{}
+ this.Value = float64(r.Float64())
+ if r.Intn(2) == 0 {
+ this.Value *= -1
+ }
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+func NewPopulatedFloatValue(r randyWrappers, easy bool) *FloatValue {
+ this := &FloatValue{}
+ this.Value = float32(r.Float32())
+ if r.Intn(2) == 0 {
+ this.Value *= -1
+ }
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+func NewPopulatedInt64Value(r randyWrappers, easy bool) *Int64Value {
+ this := &Int64Value{}
+ this.Value = int64(r.Int63())
+ if r.Intn(2) == 0 {
+ this.Value *= -1
+ }
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+func NewPopulatedUInt64Value(r randyWrappers, easy bool) *UInt64Value {
+ this := &UInt64Value{}
+ this.Value = uint64(uint64(r.Uint32()))
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+func NewPopulatedInt32Value(r randyWrappers, easy bool) *Int32Value {
+ this := &Int32Value{}
+ this.Value = int32(r.Int31())
+ if r.Intn(2) == 0 {
+ this.Value *= -1
+ }
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+func NewPopulatedUInt32Value(r randyWrappers, easy bool) *UInt32Value {
+ this := &UInt32Value{}
+ this.Value = uint32(r.Uint32())
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+func NewPopulatedBoolValue(r randyWrappers, easy bool) *BoolValue {
+ this := &BoolValue{}
+ this.Value = bool(bool(r.Intn(2) == 0))
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+func NewPopulatedStringValue(r randyWrappers, easy bool) *StringValue {
+ this := &StringValue{}
+ this.Value = string(randStringWrappers(r))
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+func NewPopulatedBytesValue(r randyWrappers, easy bool) *BytesValue {
+ this := &BytesValue{}
+ v1 := r.Intn(100)
+ this.Value = make([]byte, v1)
+ for i := 0; i < v1; i++ {
+ this.Value[i] = byte(r.Intn(256))
+ }
+ if !easy && r.Intn(10) != 0 {
+ }
+ return this
+}
+
+type randyWrappers interface {
+ Float32() float32
+ Float64() float64
+ Int63() int64
+ Int31() int32
+ Uint32() uint32
+ Intn(n int) int
+}
+
+func randUTF8RuneWrappers(r randyWrappers) rune {
+ ru := r.Intn(62)
+ if ru < 10 {
+ return rune(ru + 48)
+ } else if ru < 36 {
+ return rune(ru + 55)
+ }
+ return rune(ru + 61)
+}
+func randStringWrappers(r randyWrappers) string {
+ v2 := r.Intn(100)
+ tmps := make([]rune, v2)
+ for i := 0; i < v2; i++ {
+ tmps[i] = randUTF8RuneWrappers(r)
+ }
+ return string(tmps)
+}
+func randUnrecognizedWrappers(r randyWrappers, maxFieldNumber int) (dAtA []byte) {
+ l := r.Intn(5)
+ for i := 0; i < l; i++ {
+ wire := r.Intn(4)
+ if wire == 3 {
+ wire = 5
+ }
+ fieldNumber := maxFieldNumber + r.Intn(100)
+ dAtA = randFieldWrappers(dAtA, r, fieldNumber, wire)
+ }
+ return dAtA
+}
+func randFieldWrappers(dAtA []byte, r randyWrappers, fieldNumber int, wire int) []byte {
+ key := uint32(fieldNumber)<<3 | uint32(wire)
+ switch wire {
+ case 0:
+ dAtA = encodeVarintPopulateWrappers(dAtA, uint64(key))
+ v3 := r.Int63()
+ if r.Intn(2) == 0 {
+ v3 *= -1
+ }
+ dAtA = encodeVarintPopulateWrappers(dAtA, uint64(v3))
+ case 1:
+ dAtA = encodeVarintPopulateWrappers(dAtA, uint64(key))
+ dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
+ case 2:
+ dAtA = encodeVarintPopulateWrappers(dAtA, uint64(key))
+ ll := r.Intn(100)
+ dAtA = encodeVarintPopulateWrappers(dAtA, uint64(ll))
+ for j := 0; j < ll; j++ {
+ dAtA = append(dAtA, byte(r.Intn(256)))
+ }
+ default:
+ dAtA = encodeVarintPopulateWrappers(dAtA, uint64(key))
+ dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
+ }
+ return dAtA
+}
+func encodeVarintPopulateWrappers(dAtA []byte, v uint64) []byte {
+ for v >= 1<<7 {
+ dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
+ v >>= 7
+ }
+ dAtA = append(dAtA, uint8(v))
+ return dAtA
+}
+func (m *DoubleValue) Size() (n int) {
+ var l int
+ _ = l
+ if m.Value != 0 {
+ n += 9
+ }
+ return n
+}
+
+func (m *FloatValue) Size() (n int) {
+ var l int
+ _ = l
+ if m.Value != 0 {
+ n += 5
+ }
+ return n
+}
+
+func (m *Int64Value) Size() (n int) {
+ var l int
+ _ = l
+ if m.Value != 0 {
+ n += 1 + sovWrappers(uint64(m.Value))
+ }
+ return n
+}
+
+func (m *UInt64Value) Size() (n int) {
+ var l int
+ _ = l
+ if m.Value != 0 {
+ n += 1 + sovWrappers(uint64(m.Value))
+ }
+ return n
+}
+
+func (m *Int32Value) Size() (n int) {
+ var l int
+ _ = l
+ if m.Value != 0 {
+ n += 1 + sovWrappers(uint64(m.Value))
+ }
+ return n
+}
+
+func (m *UInt32Value) Size() (n int) {
+ var l int
+ _ = l
+ if m.Value != 0 {
+ n += 1 + sovWrappers(uint64(m.Value))
+ }
+ return n
+}
+
+func (m *BoolValue) Size() (n int) {
+ var l int
+ _ = l
+ if m.Value {
+ n += 2
+ }
+ return n
+}
+
+func (m *StringValue) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Value)
+ if l > 0 {
+ n += 1 + l + sovWrappers(uint64(l))
+ }
+ return n
+}
+
+func (m *BytesValue) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Value)
+ if l > 0 {
+ n += 1 + l + sovWrappers(uint64(l))
+ }
+ return n
+}
+
+func sovWrappers(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozWrappers(x uint64) (n int) {
+ return sovWrappers(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *DoubleValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&DoubleValue{`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *FloatValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&FloatValue{`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Int64Value) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Int64Value{`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UInt64Value) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UInt64Value{`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Int32Value) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Int32Value{`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *UInt32Value) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&UInt32Value{`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *BoolValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&BoolValue{`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *StringValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&StringValue{`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *BytesValue) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&BytesValue{`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringWrappers(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *DoubleValue) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: DoubleValue: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: DoubleValue: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 1 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ var v uint64
+ if (iNdEx + 8) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += 8
+ v = uint64(dAtA[iNdEx-8])
+ v |= uint64(dAtA[iNdEx-7]) << 8
+ v |= uint64(dAtA[iNdEx-6]) << 16
+ v |= uint64(dAtA[iNdEx-5]) << 24
+ v |= uint64(dAtA[iNdEx-4]) << 32
+ v |= uint64(dAtA[iNdEx-3]) << 40
+ v |= uint64(dAtA[iNdEx-2]) << 48
+ v |= uint64(dAtA[iNdEx-1]) << 56
+ m.Value = float64(math.Float64frombits(v))
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWrappers(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *FloatValue) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: FloatValue: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: FloatValue: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 5 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ var v uint32
+ if (iNdEx + 4) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += 4
+ v = uint32(dAtA[iNdEx-4])
+ v |= uint32(dAtA[iNdEx-3]) << 8
+ v |= uint32(dAtA[iNdEx-2]) << 16
+ v |= uint32(dAtA[iNdEx-1]) << 24
+ m.Value = float32(math.Float32frombits(v))
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWrappers(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Int64Value) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Int64Value: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Int64Value: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ m.Value = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Value |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWrappers(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UInt64Value) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UInt64Value: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UInt64Value: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ m.Value = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Value |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWrappers(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Int32Value) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Int32Value: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Int32Value: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ m.Value = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Value |= (int32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWrappers(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *UInt32Value) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: UInt32Value: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: UInt32Value: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ m.Value = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Value |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWrappers(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *BoolValue) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: BoolValue: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: BoolValue: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ var v int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.Value = bool(v != 0)
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWrappers(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *StringValue) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: StringValue: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: StringValue: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Value = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWrappers(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *BytesValue) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: BytesValue: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: BytesValue: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...)
+ if m.Value == nil {
+ m.Value = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWrappers(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWrappers
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipWrappers(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthWrappers
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWrappers
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipWrappers(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthWrappers = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowWrappers = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("wrappers.proto", fileDescriptorWrappers) }
+
+var fileDescriptorWrappers = []byte{
+ // 281 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2b, 0x2f, 0x4a, 0x2c,
+ 0x28, 0x48, 0x2d, 0x2a, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4f, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0x85, 0xf0, 0x92, 0x4a, 0xd3, 0x94, 0x94, 0xb9, 0xb8, 0x5d, 0xf2, 0x4b, 0x93, 0x72,
+ 0x52, 0xc3, 0x12, 0x73, 0x4a, 0x53, 0x85, 0x44, 0xb8, 0x58, 0xcb, 0x40, 0x0c, 0x09, 0x46, 0x05,
+ 0x46, 0x0d, 0xc6, 0x20, 0x08, 0x47, 0x49, 0x89, 0x8b, 0xcb, 0x2d, 0x27, 0x3f, 0xb1, 0x04, 0x8b,
+ 0x1a, 0x26, 0x24, 0x35, 0x9e, 0x79, 0x25, 0x66, 0x26, 0x58, 0xd4, 0x30, 0xc3, 0xd4, 0x28, 0x73,
+ 0x71, 0x87, 0xe2, 0x52, 0xc4, 0x82, 0x6a, 0x90, 0xb1, 0x11, 0x16, 0x35, 0xac, 0x68, 0x06, 0x61,
+ 0x55, 0xc4, 0x0b, 0x53, 0xa4, 0xc8, 0xc5, 0xe9, 0x94, 0x9f, 0x9f, 0x83, 0x45, 0x09, 0x07, 0x92,
+ 0x39, 0xc1, 0x25, 0x45, 0x99, 0x79, 0xe9, 0x58, 0x14, 0x71, 0x22, 0x39, 0xc8, 0xa9, 0xb2, 0x24,
+ 0xb5, 0x18, 0x8b, 0x1a, 0x1e, 0xa8, 0x1a, 0xa7, 0x2e, 0xc6, 0x0b, 0x0f, 0xe5, 0x18, 0x6e, 0x3c,
+ 0x94, 0x63, 0xf8, 0xf0, 0x50, 0x8e, 0xf1, 0xc7, 0x43, 0x39, 0xc6, 0x86, 0x47, 0x72, 0x8c, 0x2b,
+ 0x1e, 0xc9, 0x31, 0x9e, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c,
+ 0x2f, 0x1e, 0xc9, 0x31, 0x7c, 0x00, 0x89, 0x3f, 0x96, 0x63, 0xe4, 0x12, 0x4e, 0xce, 0xcf, 0xd5,
+ 0x43, 0x8b, 0x0e, 0x27, 0xde, 0x70, 0x68, 0x7c, 0x05, 0x80, 0x44, 0x02, 0x18, 0xa3, 0x58, 0x4b,
+ 0x2a, 0x0b, 0x52, 0x8b, 0x17, 0x30, 0x32, 0xfe, 0x60, 0x64, 0x5c, 0xc4, 0xc4, 0xec, 0x1e, 0xe0,
+ 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0xa2, 0x2b, 0x00, 0xaa, 0x4b, 0x2f, 0x3c, 0x35, 0x27, 0xc7, 0x3b,
+ 0x2f, 0xbf, 0x3c, 0x2f, 0x04, 0xa4, 0x38, 0x89, 0x0d, 0x6c, 0x9c, 0x31, 0x20, 0x00, 0x00, 0xff,
+ 0xff, 0xac, 0x8b, 0x9f, 0x55, 0xfd, 0x01, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/LICENSE b/vendor/github.com/golang/protobuf/LICENSE
new file mode 100644
index 0000000..1b1b192
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/LICENSE
@@ -0,0 +1,31 @@
+Go support for Protocol Buffers - Google's data interchange format
+
+Copyright 2010 The Go Authors. All rights reserved.
+https://github.com/golang/protobuf
+
+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/golang/protobuf/README.md b/vendor/github.com/golang/protobuf/README.md
new file mode 100644
index 0000000..aa933d7
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/README.md
@@ -0,0 +1,241 @@
+# Go support for Protocol Buffers
+
+Google's data interchange format.
+Copyright 2010 The Go Authors.
+https://github.com/golang/protobuf
+
+This package and the code it generates requires at least Go 1.4.
+
+This software implements Go bindings for protocol buffers. For
+information about protocol buffers themselves, see
+ https://developers.google.com/protocol-buffers/
+
+## Installation ##
+
+To use this software, you must:
+- Install the standard C++ implementation of protocol buffers from
+ https://developers.google.com/protocol-buffers/
+- Of course, install the Go compiler and tools from
+ https://golang.org/
+ See
+ https://golang.org/doc/install
+ for details or, if you are using gccgo, follow the instructions at
+ https://golang.org/doc/install/gccgo
+- Grab the code from the repository and install the proto package.
+ The simplest way is to run `go get -u github.com/golang/protobuf/protoc-gen-go`.
+ The compiler plugin, protoc-gen-go, will be installed in $GOBIN,
+ defaulting to $GOPATH/bin. It must be in your $PATH for the protocol
+ compiler, protoc, to find it.
+
+This software has two parts: a 'protocol compiler plugin' that
+generates Go source files that, once compiled, can access and manage
+protocol buffers; and a library that implements run-time support for
+encoding (marshaling), decoding (unmarshaling), and accessing protocol
+buffers.
+
+There is support for gRPC in Go using protocol buffers.
+See the note at the bottom of this file for details.
+
+There are no insertion points in the plugin.
+
+
+## Using protocol buffers with Go ##
+
+Once the software is installed, there are two steps to using it.
+First you must compile the protocol buffer definitions and then import
+them, with the support library, into your program.
+
+To compile the protocol buffer definition, run protoc with the --go_out
+parameter set to the directory you want to output the Go code to.
+
+ protoc --go_out=. *.proto
+
+The generated files will be suffixed .pb.go. See the Test code below
+for an example using such a file.
+
+
+The package comment for the proto library contains text describing
+the interface provided in Go for protocol buffers. Here is an edited
+version.
+
+==========
+
+The proto package converts data structures to and from the
+wire format of protocol buffers. It works in concert with the
+Go source code generated for .proto files by the protocol compiler.
+
+A summary of the properties of the protocol buffer interface
+for a protocol buffer variable v:
+
+ - Names are turned from camel_case to CamelCase for export.
+ - There are no methods on v to set fields; just treat
+ them as structure fields.
+ - There are getters that return a field's value if set,
+ and return the field's default value if unset.
+ The getters work even if the receiver is a nil message.
+ - The zero value for a struct is its correct initialization state.
+ All desired fields must be set before marshaling.
+ - A Reset() method will restore a protobuf struct to its zero state.
+ - Non-repeated fields are pointers to the values; nil means unset.
+ That is, optional or required field int32 f becomes F *int32.
+ - Repeated fields are slices.
+ - Helper functions are available to aid the setting of fields.
+ Helpers for getting values are superseded by the
+ GetFoo methods and their use is deprecated.
+ msg.Foo = proto.String("hello") // set field
+ - Constants are defined to hold the default values of all fields that
+ have them. They have the form Default_StructName_FieldName.
+ Because the getter methods handle defaulted values,
+ direct use of these constants should be rare.
+ - Enums are given type names and maps from names to values.
+ Enum values are prefixed with the enum's type name. Enum types have
+ a String method, and a Enum method to assist in message construction.
+ - Nested groups and enums have type names prefixed with the name of
+ the surrounding message type.
+ - Extensions are given descriptor names that start with E_,
+ followed by an underscore-delimited list of the nested messages
+ that contain it (if any) followed by the CamelCased name of the
+ extension field itself. HasExtension, ClearExtension, GetExtension
+ and SetExtension are functions for manipulating extensions.
+ - Oneof field sets are given a single field in their message,
+ with distinguished wrapper types for each possible field value.
+ - Marshal and Unmarshal are functions to encode and decode the wire format.
+
+When the .proto file specifies `syntax="proto3"`, there are some differences:
+
+ - Non-repeated fields of non-message type are values instead of pointers.
+ - Getters are only generated for message and oneof fields.
+ - Enum types do not get an Enum method.
+
+Consider file test.proto, containing
+
+```proto
+ package example;
+
+ enum FOO { X = 17; };
+
+ message Test {
+ required string label = 1;
+ optional int32 type = 2 [default=77];
+ repeated int64 reps = 3;
+ optional group OptionalGroup = 4 {
+ required string RequiredField = 5;
+ }
+ }
+```
+
+To create and play with a Test object from the example package,
+
+```go
+ package main
+
+ import (
+ "log"
+
+ "github.com/golang/protobuf/proto"
+ "path/to/example"
+ )
+
+ func main() {
+ test := &example.Test {
+ Label: proto.String("hello"),
+ Type: proto.Int32(17),
+ Reps: []int64{1, 2, 3},
+ Optionalgroup: &example.Test_OptionalGroup {
+ RequiredField: proto.String("good bye"),
+ },
+ }
+ data, err := proto.Marshal(test)
+ if err != nil {
+ log.Fatal("marshaling error: ", err)
+ }
+ newTest := &example.Test{}
+ err = proto.Unmarshal(data, newTest)
+ if err != nil {
+ log.Fatal("unmarshaling error: ", err)
+ }
+ // Now test and newTest contain the same data.
+ if test.GetLabel() != newTest.GetLabel() {
+ log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
+ }
+ // etc.
+ }
+```
+
+## Parameters ##
+
+To pass extra parameters to the plugin, use a comma-separated
+parameter list separated from the output directory by a colon:
+
+
+ protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto
+
+
+- `import_prefix=xxx` - a prefix that is added onto the beginning of
+ all imports. Useful for things like generating protos in a
+ subdirectory, or regenerating vendored protobufs in-place.
+- `import_path=foo/bar` - used as the package if no input files
+ declare `go_package`. If it contains slashes, everything up to the
+ rightmost slash is ignored.
+- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to
+ load. The only plugin in this repo is `grpc`.
+- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is
+ associated with Go package quux/shme. This is subject to the
+ import_prefix parameter.
+
+## gRPC Support ##
+
+If a proto file specifies RPC services, protoc-gen-go can be instructed to
+generate code compatible with gRPC (http://www.grpc.io/). To do this, pass
+the `plugins` parameter to protoc-gen-go; the usual way is to insert it into
+the --go_out argument to protoc:
+
+ protoc --go_out=plugins=grpc:. *.proto
+
+## Compatibility ##
+
+The library and the generated code are expected to be stable over time.
+However, we reserve the right to make breaking changes without notice for the
+following reasons:
+
+- Security. A security issue in the specification or implementation may come to
+ light whose resolution requires breaking compatibility. We reserve the right
+ to address such security issues.
+- Unspecified behavior. There are some aspects of the Protocol Buffers
+ specification that are undefined. Programs that depend on such unspecified
+ behavior may break in future releases.
+- Specification errors or changes. If it becomes necessary to address an
+ inconsistency, incompleteness, or change in the Protocol Buffers
+ specification, resolving the issue could affect the meaning or legality of
+ existing programs. We reserve the right to address such issues, including
+ updating the implementations.
+- Bugs. If the library has a bug that violates the specification, a program
+ that depends on the buggy behavior may break if the bug is fixed. We reserve
+ the right to fix such bugs.
+- Adding methods or fields to generated structs. These may conflict with field
+ names that already exist in a schema, causing applications to break. When the
+ code generator encounters a field in the schema that would collide with a
+ generated field or method name, the code generator will append an underscore
+ to the generated field or method name.
+- Adding, removing, or changing methods or fields in generated structs that
+ start with `XXX`. These parts of the generated code are exported out of
+ necessity, but should not be considered part of the public API.
+- Adding, removing, or changing unexported symbols in generated code.
+
+Any breaking changes outside of these will be announced 6 months in advance to
+protobuf@googlegroups.com.
+
+You should, whenever possible, use generated code created by the `protoc-gen-go`
+tool built at the same commit as the `proto` package. The `proto` package
+declares package-level constants in the form `ProtoPackageIsVersionX`.
+Application code and generated code may depend on one of these constants to
+ensure that compilation will fail if the available version of the proto library
+is too old. Whenever we make a change to the generated code that requires newer
+library support, in the same commit we will increment the version number of the
+generated code and declare a new package-level constant whose name incorporates
+the latest version number. Removing a compatibility constant is considered a
+breaking change and would be subject to the announcement policy stated above.
+
+The `protoc-gen-go/generator` package exposes a plugin interface,
+which is used by the gRPC code generation. This interface is not
+supported and is subject to incompatible changes without notice.
diff --git a/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go
new file mode 100644
index 0000000..e392575
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/clone.go
@@ -0,0 +1,229 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2011 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// Protocol buffer deep copy and merge.
+// TODO: RawMessage.
+
+package proto
+
+import (
+ "log"
+ "reflect"
+ "strings"
+)
+
+// Clone returns a deep copy of a protocol buffer.
+func Clone(pb Message) Message {
+ in := reflect.ValueOf(pb)
+ if in.IsNil() {
+ return pb
+ }
+
+ out := reflect.New(in.Type().Elem())
+ // out is empty so a merge is a deep copy.
+ mergeStruct(out.Elem(), in.Elem())
+ return out.Interface().(Message)
+}
+
+// Merge merges src into dst.
+// Required and optional fields that are set in src will be set to that value in dst.
+// Elements of repeated fields will be appended.
+// Merge panics if src and dst are not the same type, or if dst is nil.
+func Merge(dst, src Message) {
+ in := reflect.ValueOf(src)
+ out := reflect.ValueOf(dst)
+ if out.IsNil() {
+ panic("proto: nil destination")
+ }
+ if in.Type() != out.Type() {
+ // Explicit test prior to mergeStruct so that mistyped nils will fail
+ panic("proto: type mismatch")
+ }
+ if in.IsNil() {
+ // Merging nil into non-nil is a quiet no-op
+ return
+ }
+ mergeStruct(out.Elem(), in.Elem())
+}
+
+func mergeStruct(out, in reflect.Value) {
+ sprop := GetProperties(in.Type())
+ for i := 0; i < in.NumField(); i++ {
+ f := in.Type().Field(i)
+ if strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+ mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
+ }
+
+ if emIn, ok := extendable(in.Addr().Interface()); ok {
+ emOut, _ := extendable(out.Addr().Interface())
+ mIn, muIn := emIn.extensionsRead()
+ if mIn != nil {
+ mOut := emOut.extensionsWrite()
+ muIn.Lock()
+ mergeExtension(mOut, mIn)
+ muIn.Unlock()
+ }
+ }
+
+ uf := in.FieldByName("XXX_unrecognized")
+ if !uf.IsValid() {
+ return
+ }
+ uin := uf.Bytes()
+ if len(uin) > 0 {
+ out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
+ }
+}
+
+// mergeAny performs a merge between two values of the same type.
+// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
+// prop is set if this is a struct field (it may be nil).
+func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
+ if in.Type() == protoMessageType {
+ if !in.IsNil() {
+ if out.IsNil() {
+ out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
+ } else {
+ Merge(out.Interface().(Message), in.Interface().(Message))
+ }
+ }
+ return
+ }
+ switch in.Kind() {
+ case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
+ reflect.String, reflect.Uint32, reflect.Uint64:
+ if !viaPtr && isProto3Zero(in) {
+ return
+ }
+ out.Set(in)
+ case reflect.Interface:
+ // Probably a oneof field; copy non-nil values.
+ if in.IsNil() {
+ return
+ }
+ // Allocate destination if it is not set, or set to a different type.
+ // Otherwise we will merge as normal.
+ if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
+ out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
+ }
+ mergeAny(out.Elem(), in.Elem(), false, nil)
+ case reflect.Map:
+ if in.Len() == 0 {
+ return
+ }
+ if out.IsNil() {
+ out.Set(reflect.MakeMap(in.Type()))
+ }
+ // For maps with value types of *T or []byte we need to deep copy each value.
+ elemKind := in.Type().Elem().Kind()
+ for _, key := range in.MapKeys() {
+ var val reflect.Value
+ switch elemKind {
+ case reflect.Ptr:
+ val = reflect.New(in.Type().Elem().Elem())
+ mergeAny(val, in.MapIndex(key), false, nil)
+ case reflect.Slice:
+ val = in.MapIndex(key)
+ val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
+ default:
+ val = in.MapIndex(key)
+ }
+ out.SetMapIndex(key, val)
+ }
+ case reflect.Ptr:
+ if in.IsNil() {
+ return
+ }
+ if out.IsNil() {
+ out.Set(reflect.New(in.Elem().Type()))
+ }
+ mergeAny(out.Elem(), in.Elem(), true, nil)
+ case reflect.Slice:
+ if in.IsNil() {
+ return
+ }
+ if in.Type().Elem().Kind() == reflect.Uint8 {
+ // []byte is a scalar bytes field, not a repeated field.
+
+ // Edge case: if this is in a proto3 message, a zero length
+ // bytes field is considered the zero value, and should not
+ // be merged.
+ if prop != nil && prop.proto3 && in.Len() == 0 {
+ return
+ }
+
+ // Make a deep copy.
+ // Append to []byte{} instead of []byte(nil) so that we never end up
+ // with a nil result.
+ out.SetBytes(append([]byte{}, in.Bytes()...))
+ return
+ }
+ n := in.Len()
+ if out.IsNil() {
+ out.Set(reflect.MakeSlice(in.Type(), 0, n))
+ }
+ switch in.Type().Elem().Kind() {
+ case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
+ reflect.String, reflect.Uint32, reflect.Uint64:
+ out.Set(reflect.AppendSlice(out, in))
+ default:
+ for i := 0; i < n; i++ {
+ x := reflect.Indirect(reflect.New(in.Type().Elem()))
+ mergeAny(x, in.Index(i), false, nil)
+ out.Set(reflect.Append(out, x))
+ }
+ }
+ case reflect.Struct:
+ mergeStruct(out, in)
+ default:
+ // unknown type, so not a protocol buffer
+ log.Printf("proto: don't know how to copy %v", in)
+ }
+}
+
+func mergeExtension(out, in map[int32]Extension) {
+ for extNum, eIn := range in {
+ eOut := Extension{desc: eIn.desc}
+ if eIn.value != nil {
+ v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
+ mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
+ eOut.value = v.Interface()
+ }
+ if eIn.enc != nil {
+ eOut.enc = make([]byte, len(eIn.enc))
+ copy(eOut.enc, eIn.enc)
+ }
+
+ out[extNum] = eOut
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go
new file mode 100644
index 0000000..aa20729
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/decode.go
@@ -0,0 +1,970 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Routines for decoding protocol buffer data to construct in-memory representations.
+ */
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "reflect"
+)
+
+// errOverflow is returned when an integer is too large to be represented.
+var errOverflow = errors.New("proto: integer overflow")
+
+// ErrInternalBadWireType is returned by generated code when an incorrect
+// wire type is encountered. It does not get returned to user code.
+var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
+
+// The fundamental decoders that interpret bytes on the wire.
+// Those that take integer types all return uint64 and are
+// therefore of type valueDecoder.
+
+// DecodeVarint reads a varint-encoded integer from the slice.
+// It returns the integer and the number of bytes consumed, or
+// zero if there is not enough.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func DecodeVarint(buf []byte) (x uint64, n int) {
+ for shift := uint(0); shift < 64; shift += 7 {
+ if n >= len(buf) {
+ return 0, 0
+ }
+ b := uint64(buf[n])
+ n++
+ x |= (b & 0x7F) << shift
+ if (b & 0x80) == 0 {
+ return x, n
+ }
+ }
+
+ // The number is too large to represent in a 64-bit value.
+ return 0, 0
+}
+
+func (p *Buffer) decodeVarintSlow() (x uint64, err error) {
+ i := p.index
+ l := len(p.buf)
+
+ for shift := uint(0); shift < 64; shift += 7 {
+ if i >= l {
+ err = io.ErrUnexpectedEOF
+ return
+ }
+ b := p.buf[i]
+ i++
+ x |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ p.index = i
+ return
+ }
+ }
+
+ // The number is too large to represent in a 64-bit value.
+ err = errOverflow
+ 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.
+func (p *Buffer) DecodeFixed64() (x uint64, err error) {
+ // x, err already 0
+ i := p.index + 8
+ if i < 0 || i > len(p.buf) {
+ err = io.ErrUnexpectedEOF
+ return
+ }
+ p.index = i
+
+ x = uint64(p.buf[i-8])
+ x |= uint64(p.buf[i-7]) << 8
+ x |= uint64(p.buf[i-6]) << 16
+ x |= uint64(p.buf[i-5]) << 24
+ x |= uint64(p.buf[i-4]) << 32
+ x |= uint64(p.buf[i-3]) << 40
+ x |= uint64(p.buf[i-2]) << 48
+ x |= uint64(p.buf[i-1]) << 56
+ return
+}
+
+// DecodeFixed32 reads a 32-bit integer from the Buffer.
+// This is the format for the
+// fixed32, sfixed32, and float protocol buffer types.
+func (p *Buffer) DecodeFixed32() (x uint64, err error) {
+ // x, err already 0
+ i := p.index + 4
+ if i < 0 || i > len(p.buf) {
+ err = io.ErrUnexpectedEOF
+ return
+ }
+ p.index = i
+
+ x = uint64(p.buf[i-4])
+ x |= uint64(p.buf[i-3]) << 8
+ x |= uint64(p.buf[i-2]) << 16
+ x |= uint64(p.buf[i-1]) << 24
+ return
+}
+
+// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
+// from the Buffer.
+// This is the format used for the sint64 protocol buffer type.
+func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
+ x, err = p.DecodeVarint()
+ if err != nil {
+ return
+ }
+ x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
+ return
+}
+
+// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
+// from the Buffer.
+// This is the format used for the sint32 protocol buffer type.
+func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
+ x, err = p.DecodeVarint()
+ if err != nil {
+ return
+ }
+ x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
+ return
+}
+
+// These are not ValueDecoders: they produce an array of bytes or a string.
+// bytes, embedded messages
+
+// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
+// This is the format used for the bytes protocol buffer
+// type and for embedded messages.
+func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
+ n, err := p.DecodeVarint()
+ if err != nil {
+ return nil, err
+ }
+
+ nb := int(n)
+ if nb < 0 {
+ return nil, fmt.Errorf("proto: bad byte length %d", nb)
+ }
+ end := p.index + nb
+ if end < p.index || end > len(p.buf) {
+ return nil, io.ErrUnexpectedEOF
+ }
+
+ if !alloc {
+ // todo: check if can get more uses of alloc=false
+ buf = p.buf[p.index:end]
+ p.index += nb
+ return
+ }
+
+ buf = make([]byte, nb)
+ copy(buf, p.buf[p.index:])
+ p.index += nb
+ return
+}
+
+// DecodeStringBytes reads an encoded string from the Buffer.
+// This is the format used for the proto2 string type.
+func (p *Buffer) DecodeStringBytes() (s string, err error) {
+ buf, err := p.DecodeRawBytes(false)
+ if err != nil {
+ return
+ }
+ return string(buf), nil
+}
+
+// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
+// If the protocol buffer has extensions, and the field matches, add it as an extension.
+// Otherwise, if the XXX_unrecognized field exists, append the skipped data there.
+func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error {
+ oi := o.index
+
+ err := o.skip(t, tag, wire)
+ if err != nil {
+ return err
+ }
+
+ if !unrecField.IsValid() {
+ return nil
+ }
+
+ ptr := structPointer_Bytes(base, unrecField)
+
+ // Add the skipped field to struct field
+ obuf := o.buf
+
+ o.buf = *ptr
+ o.EncodeVarint(uint64(tag<<3 | wire))
+ *ptr = append(o.buf, obuf[oi:o.index]...)
+
+ o.buf = obuf
+
+ return nil
+}
+
+// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
+func (o *Buffer) skip(t reflect.Type, tag, wire int) error {
+
+ var u uint64
+ var err error
+
+ switch wire {
+ case WireVarint:
+ _, err = o.DecodeVarint()
+ case WireFixed64:
+ _, err = o.DecodeFixed64()
+ case WireBytes:
+ _, err = o.DecodeRawBytes(false)
+ case WireFixed32:
+ _, err = o.DecodeFixed32()
+ case WireStartGroup:
+ for {
+ u, err = o.DecodeVarint()
+ if err != nil {
+ break
+ }
+ fwire := int(u & 0x7)
+ if fwire == WireEndGroup {
+ break
+ }
+ ftag := int(u >> 3)
+ err = o.skip(t, ftag, fwire)
+ if err != nil {
+ break
+ }
+ }
+ default:
+ err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t)
+ }
+ return err
+}
+
+// Unmarshaler is the interface representing objects that can
+// unmarshal themselves. The method should reset the receiver before
+// decoding starts. The argument points to data that may be
+// overwritten, so implementations should not keep references to the
+// buffer.
+type Unmarshaler interface {
+ Unmarshal([]byte) error
+}
+
+// Unmarshal parses the protocol buffer representation in buf and places the
+// decoded result in pb. If the struct underlying pb does not match
+// the data in buf, the results can be unpredictable.
+//
+// Unmarshal resets pb before starting to unmarshal, so any
+// existing data in pb is always removed. Use UnmarshalMerge
+// to preserve and append to existing data.
+func Unmarshal(buf []byte, pb Message) error {
+ pb.Reset()
+ return UnmarshalMerge(buf, pb)
+}
+
+// UnmarshalMerge parses the protocol buffer representation in buf and
+// writes the decoded result to pb. If the struct underlying pb does not match
+// the data in buf, the results can be unpredictable.
+//
+// UnmarshalMerge merges into existing data in pb.
+// Most code should use Unmarshal instead.
+func UnmarshalMerge(buf []byte, pb Message) error {
+ // If the object can unmarshal itself, let it.
+ if u, ok := pb.(Unmarshaler); ok {
+ return u.Unmarshal(buf)
+ }
+ return NewBuffer(buf).Unmarshal(pb)
+}
+
+// DecodeMessage reads a count-delimited message from the Buffer.
+func (p *Buffer) DecodeMessage(pb Message) error {
+ enc, err := p.DecodeRawBytes(false)
+ if err != nil {
+ return err
+ }
+ return NewBuffer(enc).Unmarshal(pb)
+}
+
+// DecodeGroup reads a tag-delimited group from the Buffer.
+func (p *Buffer) DecodeGroup(pb Message) error {
+ typ, base, err := getbase(pb)
+ if err != nil {
+ return err
+ }
+ return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base)
+}
+
+// Unmarshal parses the protocol buffer representation in the
+// 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 {
+ err := u.Unmarshal(p.buf[p.index:])
+ p.index = len(p.buf)
+ return err
+ }
+
+ typ, base, err := getbase(pb)
+ if err != nil {
+ return err
+ }
+
+ err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base)
+
+ if collectStats {
+ stats.Decode++
+ }
+
+ return err
+}
+
+// unmarshalType does the work of unmarshaling a structure.
+func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error {
+ var state errorState
+ required, reqFields := prop.reqCount, uint64(0)
+
+ var err error
+ for err == nil && o.index < len(o.buf) {
+ oi := o.index
+ var u uint64
+ u, err = o.DecodeVarint()
+ if err != nil {
+ break
+ }
+ 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)
+ }
+ tag := int(u >> 3)
+ if tag <= 0 {
+ return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire)
+ }
+ fieldnum, ok := prop.decoderTags.get(tag)
+ if !ok {
+ // Maybe it's an extension?
+ if prop.extendable {
+ if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) {
+ if err = o.skip(st, tag, wire); err == nil {
+ extmap := e.extensionsWrite()
+ ext := extmap[int32(tag)] // may be missing
+ ext.enc = append(ext.enc, o.buf[oi:o.index]...)
+ extmap[int32(tag)] = ext
+ }
+ continue
+ }
+ }
+ // Maybe it's a oneof?
+ if prop.oneofUnmarshaler != nil {
+ m := structPointer_Interface(base, st).(Message)
+ // First return value indicates whether tag is a oneof field.
+ ok, err = prop.oneofUnmarshaler(m, tag, wire, o)
+ if err == ErrInternalBadWireType {
+ // Map the error to something more descriptive.
+ // Do the formatting here to save generated code space.
+ err = fmt.Errorf("bad wiretype for oneof field in %T", m)
+ }
+ if ok {
+ continue
+ }
+ }
+ err = o.skipAndSave(st, tag, wire, base, prop.unrecField)
+ continue
+ }
+ p := prop.Prop[fieldnum]
+
+ if p.dec == nil {
+ fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name)
+ continue
+ }
+ dec := p.dec
+ if wire != WireStartGroup && wire != p.WireType {
+ if wire == WireBytes && p.packedDec != nil {
+ // a packable field
+ dec = p.packedDec
+ } else {
+ err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType)
+ continue
+ }
+ }
+ decErr := dec(o, p, base)
+ if decErr != nil && !state.shouldContinue(decErr, p) {
+ err = decErr
+ }
+ if err == nil && p.Required {
+ // Successfully decoded a required field.
+ if tag <= 64 {
+ // use bitmap for fields 1-64 to catch field reuse.
+ var mask uint64 = 1 << uint64(tag-1)
+ if reqFields&mask == 0 {
+ // new required field
+ reqFields |= mask
+ required--
+ }
+ } else {
+ // This is imprecise. It can be fooled by a required field
+ // with a tag > 64 that is encoded twice; that's very rare.
+ // A fully correct implementation would require allocating
+ // a data structure, which we would like to avoid.
+ required--
+ }
+ }
+ }
+ if err == nil {
+ if is_group {
+ return io.ErrUnexpectedEOF
+ }
+ if state.err != nil {
+ return state.err
+ }
+ if required > 0 {
+ // Not enough information to determine the exact field. If we use extra
+ // CPU, we could determine the field only if the missing required field
+ // has a tag <= 64 and we check reqFields.
+ return &RequiredNotSetError{"{Unknown}"}
+ }
+ }
+ return err
+}
+
+// Individual type decoders
+// For each,
+// u is the decoded value,
+// v is a pointer to the field (pointer) in the struct
+
+// Sizes of the pools to allocate inside the Buffer.
+// The goal is modest amortization and allocation
+// on at least 16-byte boundaries.
+const (
+ boolPoolSize = 16
+ uint32PoolSize = 8
+ uint64PoolSize = 4
+)
+
+// Decode a bool.
+func (o *Buffer) dec_bool(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ if len(o.bools) == 0 {
+ o.bools = make([]bool, boolPoolSize)
+ }
+ o.bools[0] = u != 0
+ *structPointer_Bool(base, p.field) = &o.bools[0]
+ o.bools = o.bools[1:]
+ return nil
+}
+
+func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ *structPointer_BoolVal(base, p.field) = u != 0
+ return nil
+}
+
+// Decode an int32.
+func (o *Buffer) dec_int32(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ word32_Set(structPointer_Word32(base, p.field), o, uint32(u))
+ return nil
+}
+
+func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u))
+ return nil
+}
+
+// Decode an int64.
+func (o *Buffer) dec_int64(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ word64_Set(structPointer_Word64(base, p.field), o, u)
+ return nil
+}
+
+func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ word64Val_Set(structPointer_Word64Val(base, p.field), o, u)
+ return nil
+}
+
+// Decode a string.
+func (o *Buffer) dec_string(p *Properties, base structPointer) error {
+ s, err := o.DecodeStringBytes()
+ if err != nil {
+ return err
+ }
+ *structPointer_String(base, p.field) = &s
+ return nil
+}
+
+func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error {
+ s, err := o.DecodeStringBytes()
+ if err != nil {
+ return err
+ }
+ *structPointer_StringVal(base, p.field) = s
+ return nil
+}
+
+// Decode a slice of bytes ([]byte).
+func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error {
+ b, err := o.DecodeRawBytes(true)
+ if err != nil {
+ return err
+ }
+ *structPointer_Bytes(base, p.field) = b
+ return nil
+}
+
+// Decode a slice of bools ([]bool).
+func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ v := structPointer_BoolSlice(base, p.field)
+ *v = append(*v, u != 0)
+ return nil
+}
+
+// Decode a slice of bools ([]bool) in packed format.
+func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error {
+ v := structPointer_BoolSlice(base, p.field)
+
+ nn, err := o.DecodeVarint()
+ if err != nil {
+ return err
+ }
+ nb := int(nn) // number of bytes of encoded bools
+ fin := o.index + nb
+ if fin < o.index {
+ return errOverflow
+ }
+
+ y := *v
+ for o.index < fin {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ y = append(y, u != 0)
+ }
+
+ *v = y
+ return nil
+}
+
+// Decode a slice of int32s ([]int32).
+func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ structPointer_Word32Slice(base, p.field).Append(uint32(u))
+ return nil
+}
+
+// Decode a slice of int32s ([]int32) in packed format.
+func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error {
+ v := structPointer_Word32Slice(base, p.field)
+
+ nn, err := o.DecodeVarint()
+ if err != nil {
+ return err
+ }
+ nb := int(nn) // number of bytes of encoded int32s
+
+ fin := o.index + nb
+ if fin < o.index {
+ return errOverflow
+ }
+ for o.index < fin {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ v.Append(uint32(u))
+ }
+ return nil
+}
+
+// Decode a slice of int64s ([]int64).
+func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+
+ structPointer_Word64Slice(base, p.field).Append(u)
+ return nil
+}
+
+// Decode a slice of int64s ([]int64) in packed format.
+func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error {
+ v := structPointer_Word64Slice(base, p.field)
+
+ nn, err := o.DecodeVarint()
+ if err != nil {
+ return err
+ }
+ nb := int(nn) // number of bytes of encoded int64s
+
+ fin := o.index + nb
+ if fin < o.index {
+ return errOverflow
+ }
+ for o.index < fin {
+ u, err := p.valDec(o)
+ if err != nil {
+ return err
+ }
+ v.Append(u)
+ }
+ return nil
+}
+
+// Decode a slice of strings ([]string).
+func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error {
+ s, err := o.DecodeStringBytes()
+ if err != nil {
+ return err
+ }
+ v := structPointer_StringSlice(base, p.field)
+ *v = append(*v, s)
+ return nil
+}
+
+// Decode a slice of slice of bytes ([][]byte).
+func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error {
+ b, err := o.DecodeRawBytes(true)
+ if err != nil {
+ return err
+ }
+ v := structPointer_BytesSlice(base, p.field)
+ *v = append(*v, b)
+ return nil
+}
+
+// Decode a map field.
+func (o *Buffer) dec_new_map(p *Properties, base structPointer) error {
+ raw, err := o.DecodeRawBytes(false)
+ if err != nil {
+ return err
+ }
+ oi := o.index // index at the end of this map entry
+ o.index -= len(raw) // move buffer back to start of map entry
+
+ mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V
+ if mptr.Elem().IsNil() {
+ mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem()))
+ }
+ v := mptr.Elem() // map[K]V
+
+ // Prepare addressable doubly-indirect placeholders for the key and value types.
+ // See enc_new_map for why.
+ keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K
+ keybase := toStructPointer(keyptr.Addr()) // **K
+
+ var valbase structPointer
+ var valptr reflect.Value
+ switch p.mtype.Elem().Kind() {
+ case reflect.Slice:
+ // []byte
+ var dummy []byte
+ valptr = reflect.ValueOf(&dummy) // *[]byte
+ valbase = toStructPointer(valptr) // *[]byte
+ case reflect.Ptr:
+ // message; valptr is **Msg; need to allocate the intermediate pointer
+ valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V
+ valptr.Set(reflect.New(valptr.Type().Elem()))
+ valbase = toStructPointer(valptr)
+ default:
+ // everything else
+ valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V
+ valbase = toStructPointer(valptr.Addr()) // **V
+ }
+
+ // Decode.
+ // This parses a restricted wire format, namely the encoding of a message
+ // with two fields. See enc_new_map for the format.
+ for o.index < oi {
+ // tagcode for key and value properties are always a single byte
+ // because they have tags 1 and 2.
+ tagcode := o.buf[o.index]
+ o.index++
+ switch tagcode {
+ case p.mkeyprop.tagcode[0]:
+ if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil {
+ return err
+ }
+ case p.mvalprop.tagcode[0]:
+ if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil {
+ return err
+ }
+ default:
+ // TODO: Should we silently skip this instead?
+ return fmt.Errorf("proto: bad map data tag %d", raw[0])
+ }
+ }
+ keyelem, valelem := keyptr.Elem(), valptr.Elem()
+ if !keyelem.IsValid() {
+ keyelem = reflect.Zero(p.mtype.Key())
+ }
+ if !valelem.IsValid() {
+ valelem = reflect.Zero(p.mtype.Elem())
+ }
+
+ v.SetMapIndex(keyelem, valelem)
+ return nil
+}
+
+// Decode a group.
+func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error {
+ bas := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(bas) {
+ // allocate new nested message
+ bas = toStructPointer(reflect.New(p.stype))
+ structPointer_SetStructPointer(base, p.field, bas)
+ }
+ return o.unmarshalType(p.stype, p.sprop, true, bas)
+}
+
+// Decode an embedded message.
+func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) {
+ raw, e := o.DecodeRawBytes(false)
+ if e != nil {
+ return e
+ }
+
+ bas := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(bas) {
+ // allocate new nested message
+ bas = toStructPointer(reflect.New(p.stype))
+ structPointer_SetStructPointer(base, p.field, bas)
+ }
+
+ // If the object can unmarshal itself, let it.
+ if p.isUnmarshaler {
+ iv := structPointer_Interface(bas, p.stype)
+ return iv.(Unmarshaler).Unmarshal(raw)
+ }
+
+ obuf := o.buf
+ oi := o.index
+ o.buf = raw
+ o.index = 0
+
+ err = o.unmarshalType(p.stype, p.sprop, false, bas)
+ o.buf = obuf
+ o.index = oi
+
+ return err
+}
+
+// Decode a slice of embedded messages.
+func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error {
+ return o.dec_slice_struct(p, false, base)
+}
+
+// Decode a slice of embedded groups.
+func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error {
+ return o.dec_slice_struct(p, true, base)
+}
+
+// Decode a slice of structs ([]*struct).
+func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error {
+ v := reflect.New(p.stype)
+ bas := toStructPointer(v)
+ structPointer_StructPointerSlice(base, p.field).Append(bas)
+
+ if is_group {
+ err := o.unmarshalType(p.stype, p.sprop, is_group, bas)
+ return err
+ }
+
+ raw, err := o.DecodeRawBytes(false)
+ if err != nil {
+ return err
+ }
+
+ // If the object can unmarshal itself, let it.
+ if p.isUnmarshaler {
+ iv := v.Interface()
+ return iv.(Unmarshaler).Unmarshal(raw)
+ }
+
+ obuf := o.buf
+ oi := o.index
+ o.buf = raw
+ o.index = 0
+
+ err = o.unmarshalType(p.stype, p.sprop, is_group, bas)
+
+ o.buf = obuf
+ o.index = oi
+
+ return err
+}
diff --git a/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/golang/protobuf/proto/encode.go
new file mode 100644
index 0000000..2b30f84
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/encode.go
@@ -0,0 +1,1362 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Routines for encoding data into the wire format for protocol buffers.
+ */
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "sort"
+)
+
+// RequiredNotSetError is the error returned if Marshal is called with
+// a protocol buffer struct whose required fields have not
+// all been initialized. It is also the error returned if Unmarshal is
+// called with an encoded protocol buffer that does not include all the
+// required fields.
+//
+// When printed, RequiredNotSetError reports the first unset required field in a
+// message. If the field cannot be precisely determined, it is reported as
+// "{Unknown}".
+type RequiredNotSetError struct {
+ field string
+}
+
+func (e *RequiredNotSetError) Error() string {
+ return fmt.Sprintf("proto: required field %q not set", e.field)
+}
+
+var (
+ // errRepeatedHasNil is the error returned if Marshal is called with
+ // a struct with a repeated field containing a nil element.
+ errRepeatedHasNil = errors.New("proto: repeated field has nil element")
+
+ // errOneofHasNil is the error returned if Marshal is called with
+ // a struct with a oneof field containing a nil element.
+ errOneofHasNil = errors.New("proto: oneof field has nil value")
+
+ // ErrNil is the error returned if Marshal is called with nil.
+ ErrNil = errors.New("proto: Marshal called with nil")
+
+ // ErrTooLarge is the error returned if Marshal is called with a
+ // message that encodes to >2GB.
+ ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
+)
+
+// The fundamental encoders that put bytes on the wire.
+// Those that take integer types all accept uint64 and are
+// therefore of type valueEncoder.
+
+const maxVarintBytes = 10 // maximum length of a varint
+
+// maxMarshalSize is the largest allowed size of an encoded protobuf,
+// since C++ and Java use signed int32s for the size.
+const maxMarshalSize = 1<<31 - 1
+
+// EncodeVarint returns the varint encoding of x.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+// Not used by the package itself, but helpful to clients
+// wishing to use the same encoding.
+func EncodeVarint(x uint64) []byte {
+ var buf [maxVarintBytes]byte
+ var n int
+ for n = 0; x > 127; n++ {
+ buf[n] = 0x80 | uint8(x&0x7F)
+ x >>= 7
+ }
+ buf[n] = uint8(x)
+ n++
+ return buf[0:n]
+}
+
+// EncodeVarint writes a varint-encoded integer to the Buffer.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func (p *Buffer) EncodeVarint(x uint64) error {
+ for x >= 1<<7 {
+ p.buf = append(p.buf, uint8(x&0x7f|0x80))
+ x >>= 7
+ }
+ p.buf = append(p.buf, uint8(x))
+ return nil
+}
+
+// SizeVarint returns the varint encoding size of an integer.
+func SizeVarint(x uint64) int {
+ return sizeVarint(x)
+}
+
+func sizeVarint(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+
+// EncodeFixed64 writes a 64-bit integer to the Buffer.
+// This is the format for the
+// fixed64, sfixed64, and double protocol buffer types.
+func (p *Buffer) EncodeFixed64(x uint64) error {
+ p.buf = append(p.buf,
+ uint8(x),
+ uint8(x>>8),
+ uint8(x>>16),
+ uint8(x>>24),
+ uint8(x>>32),
+ uint8(x>>40),
+ uint8(x>>48),
+ uint8(x>>56))
+ return nil
+}
+
+func sizeFixed64(x uint64) int {
+ return 8
+}
+
+// EncodeFixed32 writes a 32-bit integer to the Buffer.
+// This is the format for the
+// fixed32, sfixed32, and float protocol buffer types.
+func (p *Buffer) EncodeFixed32(x uint64) error {
+ p.buf = append(p.buf,
+ uint8(x),
+ uint8(x>>8),
+ uint8(x>>16),
+ uint8(x>>24))
+ return nil
+}
+
+func sizeFixed32(x uint64) int {
+ return 4
+}
+
+// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
+// to the Buffer.
+// This is the format used for the sint64 protocol buffer type.
+func (p *Buffer) EncodeZigzag64(x uint64) error {
+ // use signed number to get arithmetic right shift.
+ return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+
+func sizeZigzag64(x uint64) int {
+ return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+
+// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
+// to the Buffer.
+// This is the format used for the sint32 protocol buffer type.
+func (p *Buffer) EncodeZigzag32(x uint64) error {
+ // use signed number to get arithmetic right shift.
+ return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
+}
+
+func sizeZigzag32(x uint64) int {
+ return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
+}
+
+// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
+// This is the format used for the bytes protocol buffer
+// type and for embedded messages.
+func (p *Buffer) EncodeRawBytes(b []byte) error {
+ p.EncodeVarint(uint64(len(b)))
+ p.buf = append(p.buf, b...)
+ return nil
+}
+
+func sizeRawBytes(b []byte) int {
+ return sizeVarint(uint64(len(b))) +
+ len(b)
+}
+
+// EncodeStringBytes writes an encoded string to the Buffer.
+// This is the format used for the proto2 string type.
+func (p *Buffer) EncodeStringBytes(s string) error {
+ p.EncodeVarint(uint64(len(s)))
+ p.buf = append(p.buf, s...)
+ return nil
+}
+
+func sizeStringBytes(s string) int {
+ return sizeVarint(uint64(len(s))) +
+ len(s)
+}
+
+// Marshaler is the interface representing objects that can marshal themselves.
+type Marshaler interface {
+ Marshal() ([]byte, error)
+}
+
+// Marshal takes the protocol buffer
+// and encodes it into the wire format, returning the data.
+func Marshal(pb Message) ([]byte, error) {
+ // Can the object marshal itself?
+ if m, ok := pb.(Marshaler); ok {
+ return m.Marshal()
+ }
+ p := NewBuffer(nil)
+ err := p.Marshal(pb)
+ if p.buf == nil && err == nil {
+ // Return a non-nil slice on success.
+ return []byte{}, nil
+ }
+ return p.buf, err
+}
+
+// EncodeMessage writes the protocol buffer to the Buffer,
+// prefixed by a varint-encoded length.
+func (p *Buffer) EncodeMessage(pb Message) error {
+ t, base, err := getbase(pb)
+ if structPointer_IsNil(base) {
+ return ErrNil
+ }
+ if err == nil {
+ var state errorState
+ err = p.enc_len_struct(GetProperties(t.Elem()), base, &state)
+ }
+ return err
+}
+
+// Marshal takes the protocol buffer
+// and encodes it into the wire format, writing the result to the
+// Buffer.
+func (p *Buffer) Marshal(pb Message) error {
+ // Can the object marshal itself?
+ if m, ok := pb.(Marshaler); ok {
+ data, err := m.Marshal()
+ p.buf = append(p.buf, data...)
+ return err
+ }
+
+ t, base, err := getbase(pb)
+ if structPointer_IsNil(base) {
+ return ErrNil
+ }
+ if err == nil {
+ err = p.enc_struct(GetProperties(t.Elem()), base)
+ }
+
+ if collectStats {
+ (stats).Encode++ // Parens are to work around a goimports bug.
+ }
+
+ if len(p.buf) > maxMarshalSize {
+ return ErrTooLarge
+ }
+ return err
+}
+
+// Size returns the encoded size of a protocol buffer.
+func Size(pb Message) (n int) {
+ // Can the object marshal itself? If so, Size is slow.
+ // TODO: add Size to Marshaler, or add a Sizer interface.
+ if m, ok := pb.(Marshaler); ok {
+ b, _ := m.Marshal()
+ return len(b)
+ }
+
+ t, base, err := getbase(pb)
+ if structPointer_IsNil(base) {
+ return 0
+ }
+ if err == nil {
+ n = size_struct(GetProperties(t.Elem()), base)
+ }
+
+ if collectStats {
+ (stats).Size++ // Parens are to work around a goimports bug.
+ }
+
+ return
+}
+
+// Individual type encoders.
+
+// Encode a bool.
+func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
+ v := *structPointer_Bool(base, p.field)
+ if v == nil {
+ return ErrNil
+ }
+ x := 0
+ if *v {
+ x = 1
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error {
+ v := *structPointer_BoolVal(base, p.field)
+ if !v {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, 1)
+ return nil
+}
+
+func size_bool(p *Properties, base structPointer) int {
+ v := *structPointer_Bool(base, p.field)
+ if v == nil {
+ return 0
+ }
+ return len(p.tagcode) + 1 // each bool takes exactly one byte
+}
+
+func size_proto3_bool(p *Properties, base structPointer) int {
+ v := *structPointer_BoolVal(base, p.field)
+ if !v && !p.oneof {
+ return 0
+ }
+ return len(p.tagcode) + 1 // each bool takes exactly one byte
+}
+
+// Encode an int32.
+func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
+ v := structPointer_Word32(base, p.field)
+ if word32_IsNil(v) {
+ return ErrNil
+ }
+ x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error {
+ v := structPointer_Word32Val(base, p.field)
+ x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
+ if x == 0 {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func size_int32(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word32(base, p.field)
+ if word32_IsNil(v) {
+ return 0
+ }
+ x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
+ n += len(p.tagcode)
+ n += p.valSize(uint64(x))
+ return
+}
+
+func size_proto3_int32(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word32Val(base, p.field)
+ x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
+ if x == 0 && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += p.valSize(uint64(x))
+ return
+}
+
+// Encode a uint32.
+// Exactly the same as int32, except for no sign extension.
+func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
+ v := structPointer_Word32(base, p.field)
+ if word32_IsNil(v) {
+ return ErrNil
+ }
+ x := word32_Get(v)
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error {
+ v := structPointer_Word32Val(base, p.field)
+ x := word32Val_Get(v)
+ if x == 0 {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, uint64(x))
+ return nil
+}
+
+func size_uint32(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word32(base, p.field)
+ if word32_IsNil(v) {
+ return 0
+ }
+ x := word32_Get(v)
+ n += len(p.tagcode)
+ n += p.valSize(uint64(x))
+ return
+}
+
+func size_proto3_uint32(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word32Val(base, p.field)
+ x := word32Val_Get(v)
+ if x == 0 && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += p.valSize(uint64(x))
+ return
+}
+
+// Encode an int64.
+func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
+ v := structPointer_Word64(base, p.field)
+ if word64_IsNil(v) {
+ return ErrNil
+ }
+ x := word64_Get(v)
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, x)
+ return nil
+}
+
+func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error {
+ v := structPointer_Word64Val(base, p.field)
+ x := word64Val_Get(v)
+ if x == 0 {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, x)
+ return nil
+}
+
+func size_int64(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word64(base, p.field)
+ if word64_IsNil(v) {
+ return 0
+ }
+ x := word64_Get(v)
+ n += len(p.tagcode)
+ n += p.valSize(x)
+ return
+}
+
+func size_proto3_int64(p *Properties, base structPointer) (n int) {
+ v := structPointer_Word64Val(base, p.field)
+ x := word64Val_Get(v)
+ if x == 0 && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += p.valSize(x)
+ return
+}
+
+// Encode a string.
+func (o *Buffer) enc_string(p *Properties, base structPointer) error {
+ v := *structPointer_String(base, p.field)
+ if v == nil {
+ return ErrNil
+ }
+ x := *v
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeStringBytes(x)
+ return nil
+}
+
+func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error {
+ v := *structPointer_StringVal(base, p.field)
+ if v == "" {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeStringBytes(v)
+ return nil
+}
+
+func size_string(p *Properties, base structPointer) (n int) {
+ v := *structPointer_String(base, p.field)
+ if v == nil {
+ return 0
+ }
+ x := *v
+ n += len(p.tagcode)
+ n += sizeStringBytes(x)
+ return
+}
+
+func size_proto3_string(p *Properties, base structPointer) (n int) {
+ v := *structPointer_StringVal(base, p.field)
+ if v == "" && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += sizeStringBytes(v)
+ return
+}
+
+// All protocol buffer fields are nillable, but be careful.
+func isNil(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ return v.IsNil()
+ }
+ return false
+}
+
+// Encode a message struct.
+func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
+ var state errorState
+ structp := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(structp) {
+ return ErrNil
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, err := m.Marshal()
+ if err != nil && !state.shouldContinue(err, nil) {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ return state.err
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ return o.enc_len_struct(p.sprop, structp, &state)
+}
+
+func size_struct_message(p *Properties, base structPointer) int {
+ structp := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(structp) {
+ return 0
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, _ := m.Marshal()
+ n0 := len(p.tagcode)
+ n1 := sizeRawBytes(data)
+ return n0 + n1
+ }
+
+ n0 := len(p.tagcode)
+ n1 := size_struct(p.sprop, structp)
+ n2 := sizeVarint(uint64(n1)) // size of encoded length
+ return n0 + n1 + n2
+}
+
+// Encode a group struct.
+func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
+ var state errorState
+ b := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(b) {
+ return ErrNil
+ }
+
+ o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
+ err := o.enc_struct(p.sprop, b)
+ if err != nil && !state.shouldContinue(err, nil) {
+ return err
+ }
+ o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
+ return state.err
+}
+
+func size_struct_group(p *Properties, base structPointer) (n int) {
+ b := structPointer_GetStructPointer(base, p.field)
+ if structPointer_IsNil(b) {
+ return 0
+ }
+
+ n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
+ n += size_struct(p.sprop, b)
+ n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
+ return
+}
+
+// Encode a slice of bools ([]bool).
+func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
+ s := *structPointer_BoolSlice(base, p.field)
+ l := len(s)
+ if l == 0 {
+ return ErrNil
+ }
+ for _, x := range s {
+ o.buf = append(o.buf, p.tagcode...)
+ v := uint64(0)
+ if x {
+ v = 1
+ }
+ p.valEnc(o, v)
+ }
+ return nil
+}
+
+func size_slice_bool(p *Properties, base structPointer) int {
+ s := *structPointer_BoolSlice(base, p.field)
+ l := len(s)
+ if l == 0 {
+ return 0
+ }
+ return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
+}
+
+// Encode a slice of bools ([]bool) in packed format.
+func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
+ s := *structPointer_BoolSlice(base, p.field)
+ l := len(s)
+ if l == 0 {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
+ for _, x := range s {
+ v := uint64(0)
+ if x {
+ v = 1
+ }
+ p.valEnc(o, v)
+ }
+ return nil
+}
+
+func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
+ s := *structPointer_BoolSlice(base, p.field)
+ l := len(s)
+ if l == 0 {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += sizeVarint(uint64(l))
+ n += l // each bool takes exactly one byte
+ return
+}
+
+// Encode a slice of bytes ([]byte).
+func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
+ s := *structPointer_Bytes(base, p.field)
+ if s == nil {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(s)
+ return nil
+}
+
+func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error {
+ s := *structPointer_Bytes(base, p.field)
+ if len(s) == 0 {
+ return ErrNil
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(s)
+ return nil
+}
+
+func size_slice_byte(p *Properties, base structPointer) (n int) {
+ s := *structPointer_Bytes(base, p.field)
+ if s == nil && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += sizeRawBytes(s)
+ return
+}
+
+func size_proto3_slice_byte(p *Properties, base structPointer) (n int) {
+ s := *structPointer_Bytes(base, p.field)
+ if len(s) == 0 && !p.oneof {
+ return 0
+ }
+ n += len(p.tagcode)
+ n += sizeRawBytes(s)
+ return
+}
+
+// Encode a slice of int32s ([]int32).
+func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ for i := 0; i < l; i++ {
+ o.buf = append(o.buf, p.tagcode...)
+ x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+ p.valEnc(o, uint64(x))
+ }
+ return nil
+}
+
+func size_slice_int32(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ for i := 0; i < l; i++ {
+ n += len(p.tagcode)
+ x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+ n += p.valSize(uint64(x))
+ }
+ return
+}
+
+// Encode a slice of int32s ([]int32) in packed format.
+func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ // TODO: Reuse a Buffer.
+ buf := NewBuffer(nil)
+ for i := 0; i < l; i++ {
+ x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+ p.valEnc(buf, uint64(x))
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeVarint(uint64(len(buf.buf)))
+ o.buf = append(o.buf, buf.buf...)
+ return nil
+}
+
+func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ var bufSize int
+ for i := 0; i < l; i++ {
+ x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+ bufSize += p.valSize(uint64(x))
+ }
+
+ n += len(p.tagcode)
+ n += sizeVarint(uint64(bufSize))
+ n += bufSize
+ return
+}
+
+// Encode a slice of uint32s ([]uint32).
+// Exactly the same as int32, except for no sign extension.
+func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ for i := 0; i < l; i++ {
+ o.buf = append(o.buf, p.tagcode...)
+ x := s.Index(i)
+ p.valEnc(o, uint64(x))
+ }
+ return nil
+}
+
+func size_slice_uint32(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ for i := 0; i < l; i++ {
+ n += len(p.tagcode)
+ x := s.Index(i)
+ n += p.valSize(uint64(x))
+ }
+ return
+}
+
+// Encode a slice of uint32s ([]uint32) in packed format.
+// Exactly the same as int32, except for no sign extension.
+func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ // TODO: Reuse a Buffer.
+ buf := NewBuffer(nil)
+ for i := 0; i < l; i++ {
+ p.valEnc(buf, uint64(s.Index(i)))
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeVarint(uint64(len(buf.buf)))
+ o.buf = append(o.buf, buf.buf...)
+ return nil
+}
+
+func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word32Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ var bufSize int
+ for i := 0; i < l; i++ {
+ bufSize += p.valSize(uint64(s.Index(i)))
+ }
+
+ n += len(p.tagcode)
+ n += sizeVarint(uint64(bufSize))
+ n += bufSize
+ return
+}
+
+// Encode a slice of int64s ([]int64).
+func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
+ s := structPointer_Word64Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ for i := 0; i < l; i++ {
+ o.buf = append(o.buf, p.tagcode...)
+ p.valEnc(o, s.Index(i))
+ }
+ return nil
+}
+
+func size_slice_int64(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word64Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ for i := 0; i < l; i++ {
+ n += len(p.tagcode)
+ n += p.valSize(s.Index(i))
+ }
+ return
+}
+
+// Encode a slice of int64s ([]int64) in packed format.
+func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
+ s := structPointer_Word64Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return ErrNil
+ }
+ // TODO: Reuse a Buffer.
+ buf := NewBuffer(nil)
+ for i := 0; i < l; i++ {
+ p.valEnc(buf, s.Index(i))
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeVarint(uint64(len(buf.buf)))
+ o.buf = append(o.buf, buf.buf...)
+ return nil
+}
+
+func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
+ s := structPointer_Word64Slice(base, p.field)
+ l := s.Len()
+ if l == 0 {
+ return 0
+ }
+ var bufSize int
+ for i := 0; i < l; i++ {
+ bufSize += p.valSize(s.Index(i))
+ }
+
+ n += len(p.tagcode)
+ n += sizeVarint(uint64(bufSize))
+ n += bufSize
+ return
+}
+
+// Encode a slice of slice of bytes ([][]byte).
+func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
+ ss := *structPointer_BytesSlice(base, p.field)
+ l := len(ss)
+ if l == 0 {
+ return ErrNil
+ }
+ for i := 0; i < l; i++ {
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(ss[i])
+ }
+ return nil
+}
+
+func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
+ ss := *structPointer_BytesSlice(base, p.field)
+ l := len(ss)
+ if l == 0 {
+ return 0
+ }
+ n += l * len(p.tagcode)
+ for i := 0; i < l; i++ {
+ n += sizeRawBytes(ss[i])
+ }
+ return
+}
+
+// Encode a slice of strings ([]string).
+func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
+ ss := *structPointer_StringSlice(base, p.field)
+ l := len(ss)
+ for i := 0; i < l; i++ {
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeStringBytes(ss[i])
+ }
+ return nil
+}
+
+func size_slice_string(p *Properties, base structPointer) (n int) {
+ ss := *structPointer_StringSlice(base, p.field)
+ l := len(ss)
+ n += l * len(p.tagcode)
+ for i := 0; i < l; i++ {
+ n += sizeStringBytes(ss[i])
+ }
+ return
+}
+
+// Encode a slice of message structs ([]*struct).
+func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
+ var state errorState
+ s := structPointer_StructPointerSlice(base, p.field)
+ l := s.Len()
+
+ for i := 0; i < l; i++ {
+ structp := s.Index(i)
+ if structPointer_IsNil(structp) {
+ return errRepeatedHasNil
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, err := m.Marshal()
+ if err != nil && !state.shouldContinue(err, nil) {
+ return err
+ }
+ o.buf = append(o.buf, p.tagcode...)
+ o.EncodeRawBytes(data)
+ continue
+ }
+
+ o.buf = append(o.buf, p.tagcode...)
+ err := o.enc_len_struct(p.sprop, structp, &state)
+ if err != nil && !state.shouldContinue(err, nil) {
+ if err == ErrNil {
+ return errRepeatedHasNil
+ }
+ return err
+ }
+ }
+ return state.err
+}
+
+func size_slice_struct_message(p *Properties, base structPointer) (n int) {
+ s := structPointer_StructPointerSlice(base, p.field)
+ l := s.Len()
+ n += l * len(p.tagcode)
+ for i := 0; i < l; i++ {
+ structp := s.Index(i)
+ if structPointer_IsNil(structp) {
+ return // return the size up to this point
+ }
+
+ // Can the object marshal itself?
+ if p.isMarshaler {
+ m := structPointer_Interface(structp, p.stype).(Marshaler)
+ data, _ := m.Marshal()
+ n += sizeRawBytes(data)
+ continue
+ }
+
+ n0 := size_struct(p.sprop, structp)
+ n1 := sizeVarint(uint64(n0)) // size of encoded length
+ n += n0 + n1
+ }
+ return
+}
+
+// Encode a slice of group structs ([]*struct).
+func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
+ var state errorState
+ s := structPointer_StructPointerSlice(base, p.field)
+ l := s.Len()
+
+ for i := 0; i < l; i++ {
+ b := s.Index(i)
+ if structPointer_IsNil(b) {
+ return errRepeatedHasNil
+ }
+
+ o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
+
+ err := o.enc_struct(p.sprop, b)
+
+ if err != nil && !state.shouldContinue(err, nil) {
+ if err == ErrNil {
+ return errRepeatedHasNil
+ }
+ return err
+ }
+
+ o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
+ }
+ return state.err
+}
+
+func size_slice_struct_group(p *Properties, base structPointer) (n int) {
+ s := structPointer_StructPointerSlice(base, p.field)
+ l := s.Len()
+
+ n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup))
+ n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup))
+ for i := 0; i < l; i++ {
+ b := s.Index(i)
+ if structPointer_IsNil(b) {
+ return // return size up to this point
+ }
+
+ n += size_struct(p.sprop, b)
+ }
+ return
+}
+
+// Encode an extension map.
+func (o *Buffer) enc_map(p *Properties, base structPointer) error {
+ exts := structPointer_ExtMap(base, p.field)
+ if err := encodeExtensionsMap(*exts); err != nil {
+ return err
+ }
+
+ return o.enc_map_body(*exts)
+}
+
+func (o *Buffer) enc_exts(p *Properties, base structPointer) error {
+ exts := structPointer_Extensions(base, p.field)
+
+ v, mu := exts.extensionsRead()
+ if v == nil {
+ return nil
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ if err := encodeExtensionsMap(v); err != nil {
+ return err
+ }
+
+ return o.enc_map_body(v)
+}
+
+func (o *Buffer) enc_map_body(v map[int32]Extension) error {
+ // Fast-path for common cases: zero or one extensions.
+ if len(v) <= 1 {
+ for _, e := range v {
+ o.buf = append(o.buf, e.enc...)
+ }
+ return nil
+ }
+
+ // Sort keys to provide a deterministic encoding.
+ keys := make([]int, 0, len(v))
+ for k := range v {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+
+ for _, k := range keys {
+ o.buf = append(o.buf, v[int32(k)].enc...)
+ }
+ return nil
+}
+
+func size_map(p *Properties, base structPointer) int {
+ v := structPointer_ExtMap(base, p.field)
+ return extensionsMapSize(*v)
+}
+
+func size_exts(p *Properties, base structPointer) int {
+ v := structPointer_Extensions(base, p.field)
+ return extensionsSize(v)
+}
+
+// Encode a map field.
+func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
+ var state errorState // XXX: or do we need to plumb this through?
+
+ /*
+ A map defined as
+ map<key_type, value_type> map_field = N;
+ is encoded in the same way as
+ message MapFieldEntry {
+ key_type key = 1;
+ value_type value = 2;
+ }
+ repeated MapFieldEntry map_field = N;
+ */
+
+ v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
+ if v.Len() == 0 {
+ return nil
+ }
+
+ keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
+
+ enc := func() error {
+ if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil {
+ return err
+ }
+ if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil {
+ return err
+ }
+ return nil
+ }
+
+ // Don't sort map keys. It is not required by the spec, and C++ doesn't do it.
+ for _, key := range v.MapKeys() {
+ val := v.MapIndex(key)
+
+ keycopy.Set(key)
+ valcopy.Set(val)
+
+ o.buf = append(o.buf, p.tagcode...)
+ if err := o.enc_len_thing(enc, &state); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func size_new_map(p *Properties, base structPointer) int {
+ v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
+
+ keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
+
+ n := 0
+ for _, key := range v.MapKeys() {
+ val := v.MapIndex(key)
+ keycopy.Set(key)
+ valcopy.Set(val)
+
+ // Tag codes for key and val are the responsibility of the sub-sizer.
+ keysize := p.mkeyprop.size(p.mkeyprop, keybase)
+ valsize := p.mvalprop.size(p.mvalprop, valbase)
+ entry := keysize + valsize
+ // Add on tag code and length of map entry itself.
+ n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry
+ }
+ return n
+}
+
+// mapEncodeScratch returns a new reflect.Value matching the map's value type,
+// and a structPointer suitable for passing to an encoder or sizer.
+func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
+ // Prepare addressable doubly-indirect placeholders for the key and value types.
+ // This is needed because the element-type encoders expect **T, but the map iteration produces T.
+
+ keycopy = reflect.New(mapType.Key()).Elem() // addressable K
+ keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
+ keyptr.Set(keycopy.Addr()) //
+ keybase = toStructPointer(keyptr.Addr()) // **K
+
+ // Value types are more varied and require special handling.
+ switch mapType.Elem().Kind() {
+ case reflect.Slice:
+ // []byte
+ var dummy []byte
+ valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
+ valbase = toStructPointer(valcopy.Addr())
+ case reflect.Ptr:
+ // message; the generated field type is map[K]*Msg (so V is *Msg),
+ // so we only need one level of indirection.
+ valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
+ valbase = toStructPointer(valcopy.Addr())
+ default:
+ // everything else
+ valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
+ valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
+ valptr.Set(valcopy.Addr()) //
+ valbase = toStructPointer(valptr.Addr()) // **V
+ }
+ return
+}
+
+// Encode a struct.
+func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
+ var state errorState
+ // Encode fields in tag order so that decoders may use optimizations
+ // that depend on the ordering.
+ // https://developers.google.com/protocol-buffers/docs/encoding#order
+ for _, i := range prop.order {
+ p := prop.Prop[i]
+ if p.enc != nil {
+ err := p.enc(o, p, base)
+ if err != nil {
+ if err == ErrNil {
+ if p.Required && state.err == nil {
+ state.err = &RequiredNotSetError{p.Name}
+ }
+ } else if err == errRepeatedHasNil {
+ // Give more context to nil values in repeated fields.
+ return errors.New("repeated field " + p.OrigName + " has nil element")
+ } else if !state.shouldContinue(err, p) {
+ return err
+ }
+ }
+ if len(o.buf) > maxMarshalSize {
+ return ErrTooLarge
+ }
+ }
+ }
+
+ // Do oneof fields.
+ if prop.oneofMarshaler != nil {
+ m := structPointer_Interface(base, prop.stype).(Message)
+ if err := prop.oneofMarshaler(m, o); err == ErrNil {
+ return errOneofHasNil
+ } else if err != nil {
+ return err
+ }
+ }
+
+ // Add unrecognized fields at the end.
+ if prop.unrecField.IsValid() {
+ v := *structPointer_Bytes(base, prop.unrecField)
+ if len(o.buf)+len(v) > maxMarshalSize {
+ return ErrTooLarge
+ }
+ if len(v) > 0 {
+ o.buf = append(o.buf, v...)
+ }
+ }
+
+ return state.err
+}
+
+func size_struct(prop *StructProperties, base structPointer) (n int) {
+ for _, i := range prop.order {
+ p := prop.Prop[i]
+ if p.size != nil {
+ n += p.size(p, base)
+ }
+ }
+
+ // Add unrecognized fields at the end.
+ if prop.unrecField.IsValid() {
+ v := *structPointer_Bytes(base, prop.unrecField)
+ n += len(v)
+ }
+
+ // Factor in any oneof fields.
+ if prop.oneofSizer != nil {
+ m := structPointer_Interface(base, prop.stype).(Message)
+ n += prop.oneofSizer(m)
+ }
+
+ return
+}
+
+var zeroes [20]byte // longer than any conceivable sizeVarint
+
+// Encode a struct, preceded by its encoded length (as a varint).
+func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error {
+ return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state)
+}
+
+// Encode something, preceded by its encoded length (as a varint).
+func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error {
+ iLen := len(o.buf)
+ o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
+ iMsg := len(o.buf)
+ err := enc()
+ if err != nil && !state.shouldContinue(err, nil) {
+ return err
+ }
+ lMsg := len(o.buf) - iMsg
+ lLen := sizeVarint(uint64(lMsg))
+ switch x := lLen - (iMsg - iLen); {
+ case x > 0: // actual length is x bytes larger than the space we reserved
+ // Move msg x bytes right.
+ o.buf = append(o.buf, zeroes[:x]...)
+ copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
+ case x < 0: // actual length is x bytes smaller than the space we reserved
+ // Move msg x bytes left.
+ copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
+ o.buf = o.buf[:len(o.buf)+x] // x is negative
+ }
+ // Encode the length in the reserved space.
+ o.buf = o.buf[:iLen]
+ o.EncodeVarint(uint64(lMsg))
+ o.buf = o.buf[:len(o.buf)+lMsg]
+ return state.err
+}
+
+// errorState maintains the first error that occurs and updates that error
+// with additional context.
+type errorState struct {
+ err error
+}
+
+// shouldContinue reports whether encoding should continue upon encountering the
+// given error. If the error is RequiredNotSetError, shouldContinue returns true
+// and, if this is the first appearance of that error, remembers it for future
+// reporting.
+//
+// If prop is not nil, it may update any error with additional context about the
+// field with the error.
+func (s *errorState) shouldContinue(err error, prop *Properties) bool {
+ // Ignore unset required fields.
+ reqNotSet, ok := err.(*RequiredNotSetError)
+ if !ok {
+ return false
+ }
+ if s.err == nil {
+ if prop != nil {
+ err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
+ }
+ s.err = err
+ }
+ return true
+}
diff --git a/vendor/github.com/golang/protobuf/proto/equal.go b/vendor/github.com/golang/protobuf/proto/equal.go
new file mode 100644
index 0000000..2ed1cf5
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/equal.go
@@ -0,0 +1,300 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2011 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// Protocol buffer comparison.
+
+package proto
+
+import (
+ "bytes"
+ "log"
+ "reflect"
+ "strings"
+)
+
+/*
+Equal returns true iff protocol buffers a and b are equal.
+The arguments must both be pointers to protocol buffer structs.
+
+Equality is defined in this way:
+ - Two messages are equal iff they are the same type,
+ corresponding fields are equal, unknown field sets
+ are equal, and extensions sets are equal.
+ - Two set scalar fields are equal iff their values are equal.
+ If the fields are of a floating-point type, remember that
+ NaN != x for all x, including NaN. If the message is defined
+ 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. 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.
+*/
+func Equal(a, b Message) bool {
+ if a == nil || b == nil {
+ return a == b
+ }
+ v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
+ if v1.Type() != v2.Type() {
+ return false
+ }
+ if v1.Kind() == reflect.Ptr {
+ if v1.IsNil() {
+ return v2.IsNil()
+ }
+ if v2.IsNil() {
+ return false
+ }
+ v1, v2 = v1.Elem(), v2.Elem()
+ }
+ if v1.Kind() != reflect.Struct {
+ return false
+ }
+ return equalStruct(v1, v2)
+}
+
+// v1 and v2 are known to have the same type.
+func equalStruct(v1, v2 reflect.Value) bool {
+ sprop := GetProperties(v1.Type())
+ for i := 0; i < v1.NumField(); i++ {
+ f := v1.Type().Field(i)
+ if strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+ f1, f2 := v1.Field(i), v2.Field(i)
+ if f.Type.Kind() == reflect.Ptr {
+ if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
+ // both unset
+ continue
+ } else if n1 != n2 {
+ // set/unset mismatch
+ return false
+ }
+ b1, ok := f1.Interface().(raw)
+ if ok {
+ b2 := f2.Interface().(raw)
+ // RawMessage
+ if !bytes.Equal(b1.Bytes(), b2.Bytes()) {
+ return false
+ }
+ continue
+ }
+ f1, f2 = f1.Elem(), f2.Elem()
+ }
+ if !equalAny(f1, f2, sprop.Prop[i]) {
+ return false
+ }
+ }
+
+ if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() {
+ em2 := v2.FieldByName("XXX_InternalExtensions")
+ if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) {
+ return false
+ }
+ }
+
+ if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
+ em2 := v2.FieldByName("XXX_extensions")
+ if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
+ return false
+ }
+ }
+
+ uf := v1.FieldByName("XXX_unrecognized")
+ if !uf.IsValid() {
+ return true
+ }
+
+ u1 := uf.Bytes()
+ u2 := v2.FieldByName("XXX_unrecognized").Bytes()
+ if !bytes.Equal(u1, u2) {
+ return false
+ }
+
+ return true
+}
+
+// v1 and v2 are known to have the same type.
+// prop may be nil.
+func equalAny(v1, v2 reflect.Value, prop *Properties) bool {
+ if v1.Type() == protoMessageType {
+ m1, _ := v1.Interface().(Message)
+ m2, _ := v2.Interface().(Message)
+ return Equal(m1, m2)
+ }
+ switch v1.Kind() {
+ case reflect.Bool:
+ return v1.Bool() == v2.Bool()
+ case reflect.Float32, reflect.Float64:
+ return v1.Float() == v2.Float()
+ case reflect.Int32, reflect.Int64:
+ return v1.Int() == v2.Int()
+ case reflect.Interface:
+ // Probably a oneof field; compare the inner values.
+ n1, n2 := v1.IsNil(), v2.IsNil()
+ if n1 || n2 {
+ return n1 == n2
+ }
+ e1, e2 := v1.Elem(), v2.Elem()
+ if e1.Type() != e2.Type() {
+ return false
+ }
+ return equalAny(e1, e2, nil)
+ case reflect.Map:
+ if v1.Len() != v2.Len() {
+ return false
+ }
+ for _, key := range v1.MapKeys() {
+ val2 := v2.MapIndex(key)
+ if !val2.IsValid() {
+ // This key was not found in the second map.
+ return false
+ }
+ if !equalAny(v1.MapIndex(key), val2, nil) {
+ return false
+ }
+ }
+ return true
+ case reflect.Ptr:
+ // Maps may have nil values in them, so check for nil.
+ if v1.IsNil() && v2.IsNil() {
+ return true
+ }
+ if v1.IsNil() != v2.IsNil() {
+ return false
+ }
+ return equalAny(v1.Elem(), v2.Elem(), prop)
+ case reflect.Slice:
+ if v1.Type().Elem().Kind() == reflect.Uint8 {
+ // short circuit: []byte
+
+ // Edge case: if this is in a proto3 message, a zero length
+ // bytes field is considered the zero value.
+ if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 {
+ return true
+ }
+ if v1.IsNil() != v2.IsNil() {
+ return false
+ }
+ return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
+ }
+
+ if v1.Len() != v2.Len() {
+ return false
+ }
+ for i := 0; i < v1.Len(); i++ {
+ if !equalAny(v1.Index(i), v2.Index(i), prop) {
+ return false
+ }
+ }
+ return true
+ case reflect.String:
+ return v1.Interface().(string) == v2.Interface().(string)
+ case reflect.Struct:
+ return equalStruct(v1, v2)
+ case reflect.Uint32, reflect.Uint64:
+ return v1.Uint() == v2.Uint()
+ }
+
+ // unknown type, so not a protocol buffer
+ log.Printf("proto: don't know how to compare %v", v1)
+ return false
+}
+
+// base is the struct type that the extensions are based on.
+// x1 and x2 are InternalExtensions.
+func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool {
+ em1, _ := x1.extensionsRead()
+ em2, _ := x2.extensionsRead()
+ return equalExtMap(base, em1, em2)
+}
+
+func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool {
+ if len(em1) != len(em2) {
+ return false
+ }
+
+ for extNum, e1 := range em1 {
+ e2, ok := em2[extNum]
+ if !ok {
+ return false
+ }
+
+ m1, m2 := e1.value, e2.value
+
+ if m1 != nil && m2 != nil {
+ // Both are unencoded.
+ if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
+ return false
+ }
+ continue
+ }
+
+ // At least one is encoded. To do a semantically correct comparison
+ // we need to unmarshal them first.
+ var desc *ExtensionDesc
+ if m := extensionMaps[base]; m != nil {
+ desc = m[extNum]
+ }
+ if desc == nil {
+ log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
+ continue
+ }
+ var err error
+ if m1 == nil {
+ m1, err = decodeExtension(e1.enc, desc)
+ }
+ if m2 == nil && err == nil {
+ m2, err = decodeExtension(e2.enc, desc)
+ }
+ if err != nil {
+ // The encoded form is invalid.
+ log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
+ return false
+ }
+ if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
+ return false
+ }
+ }
+
+ return true
+}
diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go
new file mode 100644
index 0000000..eaad218
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/extensions.go
@@ -0,0 +1,587 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Types and routines for supporting protocol buffer extensions.
+ */
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "strconv"
+ "sync"
+)
+
+// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
+var ErrMissingExtension = errors.New("proto: missing extension")
+
+// ExtensionRange represents a range of message extensions for a protocol buffer.
+// Used in code generated by the protocol compiler.
+type ExtensionRange struct {
+ Start, End int32 // both inclusive
+}
+
+// extendableProto is an interface implemented by any protocol buffer generated by the current
+// proto compiler that may be extended.
+type extendableProto interface {
+ Message
+ ExtensionRangeArray() []ExtensionRange
+ extensionsWrite() map[int32]Extension
+ extensionsRead() (map[int32]Extension, sync.Locker)
+}
+
+// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous
+// version of the proto compiler that may be extended.
+type extendableProtoV1 interface {
+ Message
+ ExtensionRangeArray() []ExtensionRange
+ ExtensionMap() map[int32]Extension
+}
+
+// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto.
+type extensionAdapter struct {
+ extendableProtoV1
+}
+
+func (e extensionAdapter) extensionsWrite() map[int32]Extension {
+ return e.ExtensionMap()
+}
+
+func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) {
+ return e.ExtensionMap(), notLocker{}
+}
+
+// notLocker is a sync.Locker whose Lock and Unlock methods are nops.
+type notLocker struct{}
+
+func (n notLocker) Lock() {}
+func (n notLocker) Unlock() {}
+
+// extendable returns the extendableProto interface for the given generated proto message.
+// If the proto message has the old extension format, it returns a wrapper that implements
+// the extendableProto interface.
+func extendable(p interface{}) (extendableProto, bool) {
+ if ep, ok := p.(extendableProto); ok {
+ return ep, ok
+ }
+ if ep, ok := p.(extendableProtoV1); ok {
+ return extensionAdapter{ep}, ok
+ }
+ return nil, false
+}
+
+// XXX_InternalExtensions is an internal representation of proto extensions.
+//
+// Each generated message struct type embeds an anonymous XXX_InternalExtensions field,
+// thus gaining the unexported 'extensions' method, which can be called only from the proto package.
+//
+// The methods of XXX_InternalExtensions are not concurrency safe in general,
+// but calls to logically read-only methods such as has and get may be executed concurrently.
+type XXX_InternalExtensions struct {
+ // The struct must be indirect so that if a user inadvertently copies a
+ // generated message and its embedded XXX_InternalExtensions, they
+ // avoid the mayhem of a copied mutex.
+ //
+ // The mutex serializes all logically read-only operations to p.extensionMap.
+ // It is up to the client to ensure that write operations to p.extensionMap are
+ // mutually exclusive with other accesses.
+ p *struct {
+ mu sync.Mutex
+ extensionMap map[int32]Extension
+ }
+}
+
+// extensionsWrite returns the extension map, creating it on first use.
+func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension {
+ if e.p == nil {
+ e.p = new(struct {
+ mu sync.Mutex
+ extensionMap map[int32]Extension
+ })
+ e.p.extensionMap = make(map[int32]Extension)
+ }
+ return e.p.extensionMap
+}
+
+// extensionsRead returns the extensions map for read-only use. It may be nil.
+// The caller must hold the returned mutex's lock when accessing Elements within the map.
+func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) {
+ if e.p == nil {
+ return nil, nil
+ }
+ return e.p.extensionMap, &e.p.mu
+}
+
+var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem()
+var extendableProtoV1Type = reflect.TypeOf((*extendableProtoV1)(nil)).Elem()
+
+// ExtensionDesc represents an extension specification.
+// Used in generated code from the protocol compiler.
+type ExtensionDesc struct {
+ ExtendedType Message // nil pointer to the type that is being extended
+ ExtensionType interface{} // nil pointer to the extension type
+ 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 {
+ t := reflect.TypeOf(ed.ExtensionType)
+ return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
+}
+
+// Extension represents an extension in a message.
+type Extension struct {
+ // When an extension is stored in a message using SetExtension
+ // only desc and value are set. When the message is marshaled
+ // enc will be set to the encoded form of the message.
+ //
+ // When a message is unmarshaled and contains extensions, each
+ // extension will have only enc set. When such an extension is
+ // accessed using GetExtension (or GetExtensions) desc and value
+ // will be set.
+ desc *ExtensionDesc
+ value interface{}
+ enc []byte
+}
+
+// SetRawExtension is for testing only.
+func SetRawExtension(base Message, id int32, b []byte) {
+ epb, ok := extendable(base)
+ if !ok {
+ return
+ }
+ extmap := epb.extensionsWrite()
+ extmap[id] = Extension{enc: b}
+}
+
+// isExtensionField returns true iff the given field number is in an extension range.
+func isExtensionField(pb extendableProto, field int32) bool {
+ for _, er := range pb.ExtensionRangeArray() {
+ if er.Start <= field && field <= er.End {
+ return true
+ }
+ }
+ return false
+}
+
+// checkExtensionTypes checks that the given extension is valid for pb.
+func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
+ var pbi interface{} = pb
+ // Check the extended type.
+ if ea, ok := pbi.(extensionAdapter); ok {
+ pbi = ea.extendableProtoV1
+ }
+ if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b {
+ return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String())
+ }
+ // Check the range.
+ if !isExtensionField(pb, extension.Field) {
+ return errors.New("proto: bad extension number; not in declared ranges")
+ }
+ return nil
+}
+
+// extPropKey is sufficient to uniquely identify an extension.
+type extPropKey struct {
+ base reflect.Type
+ field int32
+}
+
+var extProp = struct {
+ sync.RWMutex
+ m map[extPropKey]*Properties
+}{
+ m: make(map[extPropKey]*Properties),
+}
+
+func extensionProperties(ed *ExtensionDesc) *Properties {
+ key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
+
+ extProp.RLock()
+ if prop, ok := extProp.m[key]; ok {
+ extProp.RUnlock()
+ return prop
+ }
+ extProp.RUnlock()
+
+ extProp.Lock()
+ defer extProp.Unlock()
+ // Check again.
+ if prop, ok := extProp.m[key]; ok {
+ return prop
+ }
+
+ prop := new(Properties)
+ prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
+ extProp.m[key] = prop
+ return prop
+}
+
+// encode encodes any unmarshaled (unencoded) extensions in e.
+func encodeExtensions(e *XXX_InternalExtensions) error {
+ m, mu := e.extensionsRead()
+ if m == nil {
+ return nil // fast path
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ return encodeExtensionsMap(m)
+}
+
+// encode encodes any unmarshaled (unencoded) extensions in e.
+func encodeExtensionsMap(m map[int32]Extension) error {
+ for k, e := range m {
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ et := reflect.TypeOf(e.desc.ExtensionType)
+ props := extensionProperties(e.desc)
+
+ p := NewBuffer(nil)
+ // If e.value has type T, the encoder expects a *struct{ X T }.
+ // Pass a *T with a zero field and hope it all works out.
+ x := reflect.New(et)
+ x.Elem().Set(reflect.ValueOf(e.value))
+ if err := props.enc(p, props, toStructPointer(x)); err != nil {
+ return err
+ }
+ e.enc = p.buf
+ m[k] = e
+ }
+ return nil
+}
+
+func extensionsSize(e *XXX_InternalExtensions) (n int) {
+ m, mu := e.extensionsRead()
+ if m == nil {
+ return 0
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ return extensionsMapSize(m)
+}
+
+func extensionsMapSize(m map[int32]Extension) (n int) {
+ for _, e := range m {
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ n += len(e.enc)
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ et := reflect.TypeOf(e.desc.ExtensionType)
+ props := extensionProperties(e.desc)
+
+ // If e.value has type T, the encoder expects a *struct{ X T }.
+ // Pass a *T with a zero field and hope it all works out.
+ x := reflect.New(et)
+ x.Elem().Set(reflect.ValueOf(e.value))
+ n += props.size(props, toStructPointer(x))
+ }
+ return
+}
+
+// HasExtension returns whether the given extension is present in pb.
+func HasExtension(pb Message, extension *ExtensionDesc) bool {
+ // TODO: Check types, field numbers, etc.?
+ epb, ok := extendable(pb)
+ if !ok {
+ return false
+ }
+ extmap, mu := epb.extensionsRead()
+ if extmap == nil {
+ return false
+ }
+ mu.Lock()
+ _, ok = extmap[extension.Field]
+ mu.Unlock()
+ return ok
+}
+
+// ClearExtension removes the given extension from pb.
+func ClearExtension(pb Message, extension *ExtensionDesc) {
+ epb, ok := extendable(pb)
+ if !ok {
+ return
+ }
+ // TODO: Check types, field numbers, etc.?
+ extmap := epb.extensionsWrite()
+ delete(extmap, extension.Field)
+}
+
+// GetExtension parses and returns the given extension of pb.
+// If the extension is not present and has no default value it returns ErrMissingExtension.
+func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) {
+ epb, ok := extendable(pb)
+ if !ok {
+ return nil, errors.New("proto: not an extendable proto")
+ }
+
+ if err := checkExtensionTypes(epb, extension); err != nil {
+ return nil, err
+ }
+
+ emap, mu := epb.extensionsRead()
+ if emap == nil {
+ return defaultExtensionValue(extension)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ e, ok := emap[extension.Field]
+ if !ok {
+ // defaultExtensionValue returns the default value or
+ // ErrMissingExtension if there is no default.
+ return defaultExtensionValue(extension)
+ }
+
+ if e.value != nil {
+ // Already decoded. Check the descriptor, though.
+ if e.desc != extension {
+ // This shouldn't happen. If it does, it means that
+ // GetExtension was called twice with two different
+ // descriptors with the same field number.
+ return nil, errors.New("proto: descriptor conflict")
+ }
+ return e.value, nil
+ }
+
+ v, err := decodeExtension(e.enc, extension)
+ if err != nil {
+ return nil, err
+ }
+
+ // Remember the decoded version and drop the encoded version.
+ // That way it is safe to mutate what we return.
+ e.value = v
+ e.desc = extension
+ e.enc = nil
+ emap[extension.Field] = e
+ return e.value, nil
+}
+
+// defaultExtensionValue returns the default value for extension.
+// If no default for an extension is defined ErrMissingExtension is returned.
+func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) {
+ t := reflect.TypeOf(extension.ExtensionType)
+ props := extensionProperties(extension)
+
+ sf, _, err := fieldDefault(t, props)
+ if err != nil {
+ return nil, err
+ }
+
+ if sf == nil || sf.value == nil {
+ // There is no default value.
+ return nil, ErrMissingExtension
+ }
+
+ if t.Kind() != reflect.Ptr {
+ // We do not need to return a Ptr, we can directly return sf.value.
+ return sf.value, nil
+ }
+
+ // We need to return an interface{} that is a pointer to sf.value.
+ value := reflect.New(t).Elem()
+ value.Set(reflect.New(value.Type().Elem()))
+ if sf.kind == reflect.Int32 {
+ // We may have an int32 or an enum, but the underlying data is int32.
+ // Since we can't set an int32 into a non int32 reflect.value directly
+ // set it as a int32.
+ value.Elem().SetInt(int64(sf.value.(int32)))
+ } else {
+ value.Elem().Set(reflect.ValueOf(sf.value))
+ }
+ return value.Interface(), nil
+}
+
+// decodeExtension decodes an extension encoded in b.
+func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
+ o := NewBuffer(b)
+
+ t := reflect.TypeOf(extension.ExtensionType)
+
+ props := extensionProperties(extension)
+
+ // t is a pointer to a struct, pointer to basic type or a slice.
+ // Allocate a "field" to store the pointer/slice itself; the
+ // pointer/slice will be stored here. We pass
+ // the address of this field to props.dec.
+ // This passes a zero field and a *t and lets props.dec
+ // interpret it as a *struct{ x t }.
+ value := reflect.New(t).Elem()
+
+ for {
+ // Discard wire type and field number varint. It isn't needed.
+ if _, err := o.DecodeVarint(); err != nil {
+ return nil, err
+ }
+
+ if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil {
+ return nil, err
+ }
+
+ if o.index >= len(o.buf) {
+ break
+ }
+ }
+ return value.Interface(), nil
+}
+
+// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
+// The returned slice has the same length as es; missing extensions will appear as nil elements.
+func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
+ epb, ok := extendable(pb)
+ if !ok {
+ return nil, errors.New("proto: not an extendable proto")
+ }
+ extensions = make([]interface{}, len(es))
+ for i, e := range es {
+ extensions[i], err = GetExtension(epb, e)
+ if err == ErrMissingExtension {
+ err = nil
+ }
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
+// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
+// just the Field field, which defines the extension's field number.
+func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
+ epb, ok := extendable(pb)
+ if !ok {
+ return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb)
+ }
+ registeredExtensions := RegisteredExtensions(pb)
+
+ emap, mu := epb.extensionsRead()
+ if emap == nil {
+ return nil, nil
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ extensions := make([]*ExtensionDesc, 0, len(emap))
+ for extid, e := range emap {
+ desc := e.desc
+ if desc == nil {
+ desc = registeredExtensions[extid]
+ if desc == nil {
+ desc = &ExtensionDesc{Field: extid}
+ }
+ }
+
+ extensions = append(extensions, desc)
+ }
+ return extensions, nil
+}
+
+// SetExtension sets the specified extension of pb to the specified value.
+func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
+ epb, ok := extendable(pb)
+ if !ok {
+ return errors.New("proto: not an extendable proto")
+ }
+ if err := checkExtensionTypes(epb, extension); err != nil {
+ return err
+ }
+ typ := reflect.TypeOf(extension.ExtensionType)
+ if typ != reflect.TypeOf(value) {
+ return errors.New("proto: bad extension value type")
+ }
+ // nil extension values need to be caught early, because the
+ // encoder can't distinguish an ErrNil due to a nil extension
+ // from an ErrNil due to a missing field. Extensions are
+ // always optional, so the encoder would just swallow the error
+ // and drop all the extensions from the encoded message.
+ if reflect.ValueOf(value).IsNil() {
+ return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
+ }
+
+ extmap := epb.extensionsWrite()
+ extmap[extension.Field] = Extension{desc: extension, value: value}
+ return nil
+}
+
+// ClearAllExtensions clears all extensions from pb.
+func ClearAllExtensions(pb Message) {
+ epb, ok := extendable(pb)
+ if !ok {
+ return
+ }
+ m := epb.extensionsWrite()
+ for k := range m {
+ delete(m, k)
+ }
+}
+
+// A global registry of extensions.
+// The generated code will register the generated descriptors by calling RegisterExtension.
+
+var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
+
+// RegisterExtension is called from the generated code.
+func RegisterExtension(desc *ExtensionDesc) {
+ st := reflect.TypeOf(desc.ExtendedType).Elem()
+ m := extensionMaps[st]
+ if m == nil {
+ m = make(map[int32]*ExtensionDesc)
+ extensionMaps[st] = m
+ }
+ if _, ok := m[desc.Field]; ok {
+ panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
+ }
+ m[desc.Field] = desc
+}
+
+// RegisteredExtensions returns a map of the registered extensions of a
+// protocol buffer struct, indexed by the extension number.
+// The argument pb should be a nil pointer to the struct type.
+func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
+ return extensionMaps[reflect.TypeOf(pb).Elem()]
+}
diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go
new file mode 100644
index 0000000..ac4ddbc
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/lib.go
@@ -0,0 +1,898 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+/*
+Package proto converts data structures to and from the wire format of
+protocol buffers. It works in concert with the Go source code generated
+for .proto files by the protocol compiler.
+
+A summary of the properties of the protocol buffer interface
+for a protocol buffer variable v:
+
+ - Names are turned from camel_case to CamelCase for export.
+ - There are no methods on v to set fields; just treat
+ them as structure fields.
+ - There are getters that return a field's value if set,
+ and return the field's default value if unset.
+ The getters work even if the receiver is a nil message.
+ - The zero value for a struct is its correct initialization state.
+ All desired fields must be set before marshaling.
+ - A Reset() method will restore a protobuf struct to its zero state.
+ - Non-repeated fields are pointers to the values; nil means unset.
+ That is, optional or required field int32 f becomes F *int32.
+ - Repeated fields are slices.
+ - Helper functions are available to aid the setting of fields.
+ msg.Foo = proto.String("hello") // set field
+ - Constants are defined to hold the default values of all fields that
+ have them. They have the form Default_StructName_FieldName.
+ Because the getter methods handle defaulted values,
+ direct use of these constants should be rare.
+ - Enums are given type names and maps from names to values.
+ Enum values are prefixed by the enclosing message's name, or by the
+ enum's type name if it is a top-level enum. Enum types have a String
+ method, and a Enum method to assist in message construction.
+ - Nested messages, groups and enums have type names prefixed with the name of
+ the surrounding message type.
+ - Extensions are given descriptor names that start with E_,
+ followed by an underscore-delimited list of the nested messages
+ that contain it (if any) followed by the CamelCased name of the
+ extension field itself. HasExtension, ClearExtension, GetExtension
+ and SetExtension are functions for manipulating extensions.
+ - Oneof field sets are given a single field in their message,
+ with distinguished wrapper types for each possible field value.
+ - Marshal and Unmarshal are functions to encode and decode the wire format.
+
+When the .proto file specifies `syntax="proto3"`, there are some differences:
+
+ - Non-repeated fields of non-message type are values instead of pointers.
+ - Getters are only generated for message and oneof fields.
+ - Enum types do not get an Enum method.
+
+The simplest way to describe this is to see an example.
+Given file test.proto, containing
+
+ package example;
+
+ enum FOO { X = 17; }
+
+ message Test {
+ required string label = 1;
+ optional int32 type = 2 [default=77];
+ repeated int64 reps = 3;
+ optional group OptionalGroup = 4 {
+ required string RequiredField = 5;
+ }
+ oneof union {
+ int32 number = 6;
+ string name = 7;
+ }
+ }
+
+The resulting file, test.pb.go, is:
+
+ package example
+
+ import proto "github.com/golang/protobuf/proto"
+ import math "math"
+
+ type FOO int32
+ const (
+ FOO_X FOO = 17
+ )
+ var FOO_name = map[int32]string{
+ 17: "X",
+ }
+ var FOO_value = map[string]int32{
+ "X": 17,
+ }
+
+ func (x FOO) Enum() *FOO {
+ p := new(FOO)
+ *p = x
+ return p
+ }
+ func (x FOO) String() string {
+ return proto.EnumName(FOO_name, int32(x))
+ }
+ func (x *FOO) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FOO_value, data)
+ if err != nil {
+ return err
+ }
+ *x = FOO(value)
+ return nil
+ }
+
+ type Test struct {
+ Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
+ Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
+ Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
+ Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
+ // Types that are valid to be assigned to Union:
+ // *Test_Number
+ // *Test_Name
+ Union isTest_Union `protobuf_oneof:"union"`
+ XXX_unrecognized []byte `json:"-"`
+ }
+ func (m *Test) Reset() { *m = Test{} }
+ func (m *Test) String() string { return proto.CompactTextString(m) }
+ func (*Test) ProtoMessage() {}
+
+ type isTest_Union interface {
+ isTest_Union()
+ }
+
+ type Test_Number struct {
+ Number int32 `protobuf:"varint,6,opt,name=number"`
+ }
+ type Test_Name struct {
+ Name string `protobuf:"bytes,7,opt,name=name"`
+ }
+
+ func (*Test_Number) isTest_Union() {}
+ func (*Test_Name) isTest_Union() {}
+
+ func (m *Test) GetUnion() isTest_Union {
+ if m != nil {
+ return m.Union
+ }
+ return nil
+ }
+ const Default_Test_Type int32 = 77
+
+ func (m *Test) GetLabel() string {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return ""
+ }
+
+ func (m *Test) GetType() int32 {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return Default_Test_Type
+ }
+
+ func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
+ if m != nil {
+ return m.Optionalgroup
+ }
+ return nil
+ }
+
+ type Test_OptionalGroup struct {
+ RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
+ }
+ func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
+ func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
+
+ func (m *Test_OptionalGroup) GetRequiredField() string {
+ if m != nil && m.RequiredField != nil {
+ return *m.RequiredField
+ }
+ return ""
+ }
+
+ func (m *Test) GetNumber() int32 {
+ if x, ok := m.GetUnion().(*Test_Number); ok {
+ return x.Number
+ }
+ return 0
+ }
+
+ func (m *Test) GetName() string {
+ if x, ok := m.GetUnion().(*Test_Name); ok {
+ return x.Name
+ }
+ return ""
+ }
+
+ func init() {
+ proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
+ }
+
+To create and play with a Test object:
+
+ package main
+
+ import (
+ "log"
+
+ "github.com/golang/protobuf/proto"
+ pb "./example.pb"
+ )
+
+ func main() {
+ test := &pb.Test{
+ Label: proto.String("hello"),
+ Type: proto.Int32(17),
+ Reps: []int64{1, 2, 3},
+ Optionalgroup: &pb.Test_OptionalGroup{
+ RequiredField: proto.String("good bye"),
+ },
+ Union: &pb.Test_Name{"fred"},
+ }
+ data, err := proto.Marshal(test)
+ if err != nil {
+ log.Fatal("marshaling error: ", err)
+ }
+ newTest := &pb.Test{}
+ err = proto.Unmarshal(data, newTest)
+ if err != nil {
+ log.Fatal("unmarshaling error: ", err)
+ }
+ // Now test and newTest contain the same data.
+ if test.GetLabel() != newTest.GetLabel() {
+ log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
+ }
+ // Use a type switch to determine which oneof was set.
+ switch u := test.Union.(type) {
+ case *pb.Test_Number: // u.Number contains the number.
+ case *pb.Test_Name: // u.Name contains the string.
+ }
+ // etc.
+ }
+*/
+package proto
+
+import (
+ "encoding/json"
+ "fmt"
+ "log"
+ "reflect"
+ "sort"
+ "strconv"
+ "sync"
+)
+
+// Message is implemented by generated protocol buffer messages.
+type Message interface {
+ Reset()
+ String() string
+ ProtoMessage()
+}
+
+// Stats records allocation details about the protocol buffer encoders
+// and decoders. Useful for tuning the library itself.
+type Stats struct {
+ Emalloc uint64 // mallocs in encode
+ Dmalloc uint64 // mallocs in decode
+ Encode uint64 // number of encodes
+ Decode uint64 // number of decodes
+ Chit uint64 // number of cache hits
+ Cmiss uint64 // number of cache misses
+ Size uint64 // number of sizes
+}
+
+// Set to true to enable stats collection.
+const collectStats = false
+
+var stats Stats
+
+// GetStats returns a copy of the global Stats structure.
+func GetStats() Stats { return stats }
+
+// A Buffer is a buffer manager for marshaling and unmarshaling
+// protocol buffers. It may be reused between invocations to
+// reduce memory usage. It is not necessary to use a Buffer;
+// the global functions Marshal and Unmarshal create a
+// temporary Buffer and are fine for most applications.
+type Buffer struct {
+ buf []byte // encode/decode byte stream
+ index int // read point
+
+ // pools of basic types to amortize allocation.
+ bools []bool
+ uint32s []uint32
+ uint64s []uint64
+
+ // extra pools, only used with pointer_reflect.go
+ int32s []int32
+ int64s []int64
+ float32s []float32
+ float64s []float64
+}
+
+// NewBuffer allocates a new Buffer and initializes its internal data to
+// the contents of the argument slice.
+func NewBuffer(e []byte) *Buffer {
+ return &Buffer{buf: e}
+}
+
+// Reset resets the Buffer, ready for marshaling a new protocol buffer.
+func (p *Buffer) Reset() {
+ p.buf = p.buf[0:0] // for reading/writing
+ p.index = 0 // for reading
+}
+
+// SetBuf replaces the internal buffer with the slice,
+// ready for unmarshaling the contents of the slice.
+func (p *Buffer) SetBuf(s []byte) {
+ p.buf = s
+ p.index = 0
+}
+
+// Bytes returns the contents of the Buffer.
+func (p *Buffer) Bytes() []byte { return p.buf }
+
+/*
+ * Helper routines for simplifying the creation of optional fields of basic type.
+ */
+
+// Bool is a helper routine that allocates a new bool value
+// to store v and returns a pointer to it.
+func Bool(v bool) *bool {
+ return &v
+}
+
+// Int32 is a helper routine that allocates a new int32 value
+// to store v and returns a pointer to it.
+func Int32(v int32) *int32 {
+ return &v
+}
+
+// Int is a helper routine that allocates a new int32 value
+// to store v and returns a pointer to it, but unlike Int32
+// its argument value is an int.
+func Int(v int) *int32 {
+ p := new(int32)
+ *p = int32(v)
+ return p
+}
+
+// Int64 is a helper routine that allocates a new int64 value
+// to store v and returns a pointer to it.
+func Int64(v int64) *int64 {
+ return &v
+}
+
+// Float32 is a helper routine that allocates a new float32 value
+// to store v and returns a pointer to it.
+func Float32(v float32) *float32 {
+ return &v
+}
+
+// Float64 is a helper routine that allocates a new float64 value
+// to store v and returns a pointer to it.
+func Float64(v float64) *float64 {
+ return &v
+}
+
+// Uint32 is a helper routine that allocates a new uint32 value
+// to store v and returns a pointer to it.
+func Uint32(v uint32) *uint32 {
+ return &v
+}
+
+// Uint64 is a helper routine that allocates a new uint64 value
+// to store v and returns a pointer to it.
+func Uint64(v uint64) *uint64 {
+ return &v
+}
+
+// String is a helper routine that allocates a new string value
+// to store v and returns a pointer to it.
+func String(v string) *string {
+ return &v
+}
+
+// EnumName is a helper function to simplify printing protocol buffer enums
+// by name. Given an enum map and a value, it returns a useful string.
+func EnumName(m map[int32]string, v int32) string {
+ s, ok := m[v]
+ if ok {
+ return s
+ }
+ return strconv.Itoa(int(v))
+}
+
+// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
+// from their JSON-encoded representation. Given a map from the enum's symbolic
+// names to its int values, and a byte buffer containing the JSON-encoded
+// value, it returns an int32 that can be cast to the enum type by the caller.
+//
+// The function can deal with both JSON representations, numeric and symbolic.
+func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
+ if data[0] == '"' {
+ // New style: enums are strings.
+ var repr string
+ if err := json.Unmarshal(data, &repr); err != nil {
+ return -1, err
+ }
+ val, ok := m[repr]
+ if !ok {
+ return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
+ }
+ return val, nil
+ }
+ // Old style: enums are ints.
+ var val int32
+ if err := json.Unmarshal(data, &val); err != nil {
+ return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
+ }
+ return val, nil
+}
+
+// DebugPrint dumps the encoded data in b in a debugging format with a header
+// including the string s. Used in testing but made available for general debugging.
+func (p *Buffer) DebugPrint(s string, b []byte) {
+ var u uint64
+
+ obuf := p.buf
+ index := p.index
+ p.buf = b
+ p.index = 0
+ depth := 0
+
+ fmt.Printf("\n--- %s ---\n", s)
+
+out:
+ for {
+ for i := 0; i < depth; i++ {
+ fmt.Print(" ")
+ }
+
+ index := p.index
+ if index == len(p.buf) {
+ break
+ }
+
+ op, err := p.DecodeVarint()
+ if err != nil {
+ fmt.Printf("%3d: fetching op err %v\n", index, err)
+ break out
+ }
+ tag := op >> 3
+ wire := op & 7
+
+ switch wire {
+ default:
+ fmt.Printf("%3d: t=%3d unknown wire=%d\n",
+ index, tag, wire)
+ break out
+
+ case WireBytes:
+ var r []byte
+
+ r, err = p.DecodeRawBytes(false)
+ if err != nil {
+ break out
+ }
+ fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
+ if len(r) <= 6 {
+ for i := 0; i < len(r); i++ {
+ fmt.Printf(" %.2x", r[i])
+ }
+ } else {
+ for i := 0; i < 3; i++ {
+ fmt.Printf(" %.2x", r[i])
+ }
+ fmt.Printf(" ..")
+ for i := len(r) - 3; i < len(r); i++ {
+ fmt.Printf(" %.2x", r[i])
+ }
+ }
+ fmt.Printf("\n")
+
+ case WireFixed32:
+ u, err = p.DecodeFixed32()
+ if err != nil {
+ fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
+ break out
+ }
+ fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
+
+ case WireFixed64:
+ u, err = p.DecodeFixed64()
+ if err != nil {
+ fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
+ break out
+ }
+ fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
+
+ case WireVarint:
+ u, err = p.DecodeVarint()
+ if err != nil {
+ fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
+ break out
+ }
+ fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
+
+ case WireStartGroup:
+ fmt.Printf("%3d: t=%3d start\n", index, tag)
+ depth++
+
+ case WireEndGroup:
+ depth--
+ fmt.Printf("%3d: t=%3d end\n", index, tag)
+ }
+ }
+
+ if depth != 0 {
+ fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
+ }
+ fmt.Printf("\n")
+
+ p.buf = obuf
+ p.index = index
+}
+
+// SetDefaults sets unset protocol buffer fields to their default values.
+// It only modifies fields that are both unset and have defined defaults.
+// It recursively sets default values in any non-nil sub-messages.
+func SetDefaults(pb Message) {
+ setDefaults(reflect.ValueOf(pb), true, false)
+}
+
+// v is a pointer to a struct.
+func setDefaults(v reflect.Value, recur, zeros bool) {
+ v = v.Elem()
+
+ defaultMu.RLock()
+ dm, ok := defaults[v.Type()]
+ defaultMu.RUnlock()
+ if !ok {
+ dm = buildDefaultMessage(v.Type())
+ defaultMu.Lock()
+ defaults[v.Type()] = dm
+ defaultMu.Unlock()
+ }
+
+ for _, sf := range dm.scalars {
+ f := v.Field(sf.index)
+ if !f.IsNil() {
+ // field already set
+ continue
+ }
+ dv := sf.value
+ if dv == nil && !zeros {
+ // no explicit default, and don't want to set zeros
+ continue
+ }
+ fptr := f.Addr().Interface() // **T
+ // TODO: Consider batching the allocations we do here.
+ switch sf.kind {
+ case reflect.Bool:
+ b := new(bool)
+ if dv != nil {
+ *b = dv.(bool)
+ }
+ *(fptr.(**bool)) = b
+ case reflect.Float32:
+ f := new(float32)
+ if dv != nil {
+ *f = dv.(float32)
+ }
+ *(fptr.(**float32)) = f
+ case reflect.Float64:
+ f := new(float64)
+ if dv != nil {
+ *f = dv.(float64)
+ }
+ *(fptr.(**float64)) = f
+ case reflect.Int32:
+ // might be an enum
+ if ft := f.Type(); ft != int32PtrType {
+ // enum
+ f.Set(reflect.New(ft.Elem()))
+ if dv != nil {
+ f.Elem().SetInt(int64(dv.(int32)))
+ }
+ } else {
+ // int32 field
+ i := new(int32)
+ if dv != nil {
+ *i = dv.(int32)
+ }
+ *(fptr.(**int32)) = i
+ }
+ case reflect.Int64:
+ i := new(int64)
+ if dv != nil {
+ *i = dv.(int64)
+ }
+ *(fptr.(**int64)) = i
+ case reflect.String:
+ s := new(string)
+ if dv != nil {
+ *s = dv.(string)
+ }
+ *(fptr.(**string)) = s
+ case reflect.Uint8:
+ // exceptional case: []byte
+ var b []byte
+ if dv != nil {
+ db := dv.([]byte)
+ b = make([]byte, len(db))
+ copy(b, db)
+ } else {
+ b = []byte{}
+ }
+ *(fptr.(*[]byte)) = b
+ case reflect.Uint32:
+ u := new(uint32)
+ if dv != nil {
+ *u = dv.(uint32)
+ }
+ *(fptr.(**uint32)) = u
+ case reflect.Uint64:
+ u := new(uint64)
+ if dv != nil {
+ *u = dv.(uint64)
+ }
+ *(fptr.(**uint64)) = u
+ default:
+ log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
+ }
+ }
+
+ for _, ni := range dm.nested {
+ f := v.Field(ni)
+ // f is *T or []*T or map[T]*T
+ switch f.Kind() {
+ case reflect.Ptr:
+ if f.IsNil() {
+ continue
+ }
+ setDefaults(f, recur, zeros)
+
+ case reflect.Slice:
+ for i := 0; i < f.Len(); i++ {
+ e := f.Index(i)
+ if e.IsNil() {
+ continue
+ }
+ setDefaults(e, recur, zeros)
+ }
+
+ case reflect.Map:
+ for _, k := range f.MapKeys() {
+ e := f.MapIndex(k)
+ if e.IsNil() {
+ continue
+ }
+ setDefaults(e, recur, zeros)
+ }
+ }
+ }
+}
+
+var (
+ // defaults maps a protocol buffer struct type to a slice of the fields,
+ // with its scalar fields set to their proto-declared non-zero default values.
+ defaultMu sync.RWMutex
+ defaults = make(map[reflect.Type]defaultMessage)
+
+ int32PtrType = reflect.TypeOf((*int32)(nil))
+)
+
+// defaultMessage represents information about the default values of a message.
+type defaultMessage struct {
+ scalars []scalarField
+ nested []int // struct field index of nested messages
+}
+
+type scalarField struct {
+ index int // struct field index
+ kind reflect.Kind // element type (the T in *T or []T)
+ value interface{} // the proto-declared default value, or nil
+}
+
+// t is a struct type.
+func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
+ sprop := GetProperties(t)
+ for _, prop := range sprop.Prop {
+ fi, ok := sprop.decoderTags.get(prop.Tag)
+ if !ok {
+ // XXX_unrecognized
+ continue
+ }
+ ft := t.Field(fi).Type
+
+ sf, nested, err := fieldDefault(ft, prop)
+ switch {
+ case err != nil:
+ log.Print(err)
+ case nested:
+ dm.nested = append(dm.nested, fi)
+ case sf != nil:
+ sf.index = fi
+ dm.scalars = append(dm.scalars, *sf)
+ }
+ }
+
+ return dm
+}
+
+// fieldDefault returns the scalarField for field type ft.
+// sf will be nil if the field can not have a default.
+// nestedMessage will be true if this is a nested message.
+// Note that sf.index is not set on return.
+func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
+ var canHaveDefault bool
+ switch ft.Kind() {
+ case reflect.Ptr:
+ if ft.Elem().Kind() == reflect.Struct {
+ nestedMessage = true
+ } else {
+ canHaveDefault = true // proto2 scalar field
+ }
+
+ case reflect.Slice:
+ switch ft.Elem().Kind() {
+ case reflect.Ptr:
+ nestedMessage = true // repeated message
+ case reflect.Uint8:
+ canHaveDefault = true // bytes field
+ }
+
+ case reflect.Map:
+ if ft.Elem().Kind() == reflect.Ptr {
+ nestedMessage = true // map with message values
+ }
+ }
+
+ if !canHaveDefault {
+ if nestedMessage {
+ return nil, true, nil
+ }
+ return nil, false, nil
+ }
+
+ // We now know that ft is a pointer or slice.
+ sf = &scalarField{kind: ft.Elem().Kind()}
+
+ // scalar fields without defaults
+ if !prop.HasDefault {
+ return sf, false, nil
+ }
+
+ // a scalar field: either *T or []byte
+ switch ft.Elem().Kind() {
+ case reflect.Bool:
+ x, err := strconv.ParseBool(prop.Default)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ case reflect.Float32:
+ x, err := strconv.ParseFloat(prop.Default, 32)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
+ }
+ sf.value = float32(x)
+ case reflect.Float64:
+ x, err := strconv.ParseFloat(prop.Default, 64)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ case reflect.Int32:
+ x, err := strconv.ParseInt(prop.Default, 10, 32)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
+ }
+ sf.value = int32(x)
+ case reflect.Int64:
+ x, err := strconv.ParseInt(prop.Default, 10, 64)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ case reflect.String:
+ sf.value = prop.Default
+ case reflect.Uint8:
+ // []byte (not *uint8)
+ sf.value = []byte(prop.Default)
+ case reflect.Uint32:
+ x, err := strconv.ParseUint(prop.Default, 10, 32)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
+ }
+ sf.value = uint32(x)
+ case reflect.Uint64:
+ x, err := strconv.ParseUint(prop.Default, 10, 64)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ default:
+ return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
+ }
+
+ return sf, false, nil
+}
+
+// Map fields may have key types of non-float scalars, strings and enums.
+// The easiest way to sort them in some deterministic order is to use fmt.
+// If this turns out to be inefficient we can always consider other options,
+// such as doing a Schwartzian transform.
+
+func mapKeys(vs []reflect.Value) sort.Interface {
+ s := mapKeySorter{
+ vs: vs,
+ // default Less function: textual comparison
+ less: func(a, b reflect.Value) bool {
+ return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface())
+ },
+ }
+
+ // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps;
+ // numeric keys are sorted numerically.
+ if len(vs) == 0 {
+ return s
+ }
+ switch vs[0].Kind() {
+ case reflect.Int32, reflect.Int64:
+ s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
+ case reflect.Uint32, reflect.Uint64:
+ s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
+ }
+
+ return s
+}
+
+type mapKeySorter struct {
+ vs []reflect.Value
+ less func(a, b reflect.Value) bool
+}
+
+func (s mapKeySorter) Len() int { return len(s.vs) }
+func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
+func (s mapKeySorter) Less(i, j int) bool {
+ return s.less(s.vs[i], s.vs[j])
+}
+
+// isProto3Zero reports whether v is a zero proto3 value.
+func isProto3Zero(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Bool:
+ return !v.Bool()
+ case reflect.Int32, reflect.Int64:
+ return v.Int() == 0
+ case reflect.Uint32, reflect.Uint64:
+ return v.Uint() == 0
+ case reflect.Float32, reflect.Float64:
+ return v.Float() == 0
+ case reflect.String:
+ return v.String() == ""
+ }
+ return false
+}
+
+// ProtoPackageIsVersion2 is referenced from generated protocol buffer files
+// to assert that that code is compatible with this version of the proto package.
+const ProtoPackageIsVersion2 = true
+
+// ProtoPackageIsVersion1 is referenced from generated protocol buffer files
+// to assert that that code is compatible with this version of the proto package.
+const ProtoPackageIsVersion1 = true
diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go
new file mode 100644
index 0000000..fd982de
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/message_set.go
@@ -0,0 +1,311 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Support for message sets.
+ */
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "reflect"
+ "sort"
+)
+
+// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
+// A message type ID is required for storing a protocol buffer in a message set.
+var errNoMessageTypeID = errors.New("proto does not have a message type ID")
+
+// The first two types (_MessageSet_Item and messageSet)
+// model what the protocol compiler produces for the following protocol message:
+// message MessageSet {
+// repeated group Item = 1 {
+// required int32 type_id = 2;
+// required string message = 3;
+// };
+// }
+// That is the MessageSet wire format. We can't use a proto to generate these
+// because that would introduce a circular dependency between it and this package.
+
+type _MessageSet_Item struct {
+ TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
+ Message []byte `protobuf:"bytes,3,req,name=message"`
+}
+
+type messageSet struct {
+ Item []*_MessageSet_Item `protobuf:"group,1,rep"`
+ XXX_unrecognized []byte
+ // TODO: caching?
+}
+
+// Make sure messageSet is a Message.
+var _ Message = (*messageSet)(nil)
+
+// messageTypeIder is an interface satisfied by a protocol buffer type
+// that may be stored in a MessageSet.
+type messageTypeIder interface {
+ MessageTypeId() int32
+}
+
+func (ms *messageSet) find(pb Message) *_MessageSet_Item {
+ mti, ok := pb.(messageTypeIder)
+ if !ok {
+ return nil
+ }
+ id := mti.MessageTypeId()
+ for _, item := range ms.Item {
+ if *item.TypeId == id {
+ return item
+ }
+ }
+ return nil
+}
+
+func (ms *messageSet) Has(pb Message) bool {
+ if ms.find(pb) != nil {
+ return true
+ }
+ return false
+}
+
+func (ms *messageSet) Unmarshal(pb Message) error {
+ if item := ms.find(pb); item != nil {
+ return Unmarshal(item.Message, pb)
+ }
+ if _, ok := pb.(messageTypeIder); !ok {
+ return errNoMessageTypeID
+ }
+ return nil // TODO: return error instead?
+}
+
+func (ms *messageSet) Marshal(pb Message) error {
+ msg, err := Marshal(pb)
+ if err != nil {
+ return err
+ }
+ if item := ms.find(pb); item != nil {
+ // reuse existing item
+ item.Message = msg
+ return nil
+ }
+
+ mti, ok := pb.(messageTypeIder)
+ if !ok {
+ return errNoMessageTypeID
+ }
+
+ mtid := mti.MessageTypeId()
+ ms.Item = append(ms.Item, &_MessageSet_Item{
+ TypeId: &mtid,
+ Message: msg,
+ })
+ return nil
+}
+
+func (ms *messageSet) Reset() { *ms = messageSet{} }
+func (ms *messageSet) String() string { return CompactTextString(ms) }
+func (*messageSet) ProtoMessage() {}
+
+// Support for the message_set_wire_format message option.
+
+func skipVarint(buf []byte) []byte {
+ i := 0
+ for ; buf[i]&0x80 != 0; i++ {
+ }
+ return buf[i+1:]
+}
+
+// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
+// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
+func MarshalMessageSet(exts interface{}) ([]byte, error) {
+ var m map[int32]Extension
+ switch exts := exts.(type) {
+ case *XXX_InternalExtensions:
+ if err := encodeExtensions(exts); err != nil {
+ return nil, err
+ }
+ m, _ = exts.extensionsRead()
+ case map[int32]Extension:
+ if err := encodeExtensionsMap(exts); err != nil {
+ return nil, err
+ }
+ m = exts
+ default:
+ return nil, errors.New("proto: not an extension map")
+ }
+
+ // Sort extension IDs to provide a deterministic encoding.
+ // See also enc_map in encode.go.
+ ids := make([]int, 0, len(m))
+ for id := range m {
+ ids = append(ids, int(id))
+ }
+ sort.Ints(ids)
+
+ ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
+ for _, id := range ids {
+ e := m[int32(id)]
+ // Remove the wire type and field number varint, as well as the length varint.
+ msg := skipVarint(skipVarint(e.enc))
+
+ ms.Item = append(ms.Item, &_MessageSet_Item{
+ TypeId: Int32(int32(id)),
+ Message: msg,
+ })
+ }
+ return Marshal(ms)
+}
+
+// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
+// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
+func UnmarshalMessageSet(buf []byte, exts interface{}) error {
+ var m map[int32]Extension
+ switch exts := exts.(type) {
+ case *XXX_InternalExtensions:
+ m = exts.extensionsWrite()
+ case map[int32]Extension:
+ m = exts
+ default:
+ return errors.New("proto: not an extension map")
+ }
+
+ ms := new(messageSet)
+ if err := Unmarshal(buf, ms); err != nil {
+ return err
+ }
+ for _, item := range ms.Item {
+ id := *item.TypeId
+ msg := item.Message
+
+ // Restore wire type and field number varint, plus length varint.
+ // Be careful to preserve duplicate items.
+ b := EncodeVarint(uint64(id)<<3 | WireBytes)
+ if ext, ok := m[id]; ok {
+ // Existing data; rip off the tag and length varint
+ // so we join the new data correctly.
+ // We can assume that ext.enc is set because we are unmarshaling.
+ o := ext.enc[len(b):] // skip wire type and field number
+ _, n := DecodeVarint(o) // calculate length of length varint
+ o = o[n:] // skip length varint
+ msg = append(o, msg...) // join old data and new data
+ }
+ b = append(b, EncodeVarint(uint64(len(msg)))...)
+ b = append(b, msg...)
+
+ m[id] = Extension{enc: b}
+ }
+ return nil
+}
+
+// MarshalMessageSetJSON encodes the extension map represented by m in JSON format.
+// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
+func MarshalMessageSetJSON(exts interface{}) ([]byte, error) {
+ var m map[int32]Extension
+ switch exts := exts.(type) {
+ case *XXX_InternalExtensions:
+ m, _ = exts.extensionsRead()
+ case map[int32]Extension:
+ m = exts
+ default:
+ return nil, errors.New("proto: not an extension map")
+ }
+ var b bytes.Buffer
+ b.WriteByte('{')
+
+ // Process the map in key order for deterministic output.
+ ids := make([]int32, 0, len(m))
+ for id := range m {
+ ids = append(ids, id)
+ }
+ sort.Sort(int32Slice(ids)) // int32Slice defined in text.go
+
+ for i, id := range ids {
+ ext := m[id]
+ if i > 0 {
+ b.WriteByte(',')
+ }
+
+ msd, ok := messageSetMap[id]
+ if !ok {
+ // Unknown type; we can't render it, so skip it.
+ continue
+ }
+ fmt.Fprintf(&b, `"[%s]":`, msd.name)
+
+ x := ext.value
+ if x == nil {
+ x = reflect.New(msd.t.Elem()).Interface()
+ if err := Unmarshal(ext.enc, x.(Message)); err != nil {
+ return nil, err
+ }
+ }
+ d, err := json.Marshal(x)
+ if err != nil {
+ return nil, err
+ }
+ b.Write(d)
+ }
+ b.WriteByte('}')
+ return b.Bytes(), nil
+}
+
+// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format.
+// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
+func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error {
+ // Common-case fast path.
+ if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) {
+ return nil
+ }
+
+ // This is fairly tricky, and it's not clear that it is needed.
+ return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented")
+}
+
+// A global registry of types that can be used in a MessageSet.
+
+var messageSetMap = make(map[int32]messageSetDesc)
+
+type messageSetDesc struct {
+ t reflect.Type // pointer to struct
+ name string
+}
+
+// RegisterMessageSetType is called from the generated code.
+func RegisterMessageSetType(m Message, fieldNum int32, name string) {
+ messageSetMap[fieldNum] = messageSetDesc{
+ t: reflect.TypeOf(m),
+ name: name,
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
new file mode 100644
index 0000000..fb512e2
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
@@ -0,0 +1,484 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2012 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// +build appengine js
+
+// This file contains an implementation of proto field accesses using package reflect.
+// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
+// be used on App Engine.
+
+package proto
+
+import (
+ "math"
+ "reflect"
+)
+
+// A structPointer is a pointer to a struct.
+type structPointer struct {
+ v reflect.Value
+}
+
+// toStructPointer returns a structPointer equivalent to the given reflect value.
+// The reflect value must itself be a pointer to a struct.
+func toStructPointer(v reflect.Value) structPointer {
+ return structPointer{v}
+}
+
+// IsNil reports whether p is nil.
+func structPointer_IsNil(p structPointer) bool {
+ return p.v.IsNil()
+}
+
+// Interface returns the struct pointer as an interface value.
+func structPointer_Interface(p structPointer, _ reflect.Type) interface{} {
+ return p.v.Interface()
+}
+
+// A field identifies a field in a struct, accessible from a structPointer.
+// In this implementation, a field is identified by the sequence of field indices
+// passed to reflect's FieldByIndex.
+type field []int
+
+// toField returns a field equivalent to the given reflect field.
+func toField(f *reflect.StructField) field {
+ return f.Index
+}
+
+// invalidField is an invalid field identifier.
+var invalidField = field(nil)
+
+// IsValid reports whether the field identifier is valid.
+func (f field) IsValid() bool { return f != nil }
+
+// field returns the given field in the struct as a reflect value.
+func structPointer_field(p structPointer, f field) reflect.Value {
+ // Special case: an extension map entry with a value of type T
+ // passes a *T to the struct-handling code with a zero field,
+ // expecting that it will be treated as equivalent to *struct{ X T },
+ // which has the same memory layout. We have to handle that case
+ // specially, because reflect will panic if we call FieldByIndex on a
+ // non-struct.
+ if f == nil {
+ return p.v.Elem()
+ }
+
+ return p.v.Elem().FieldByIndex(f)
+}
+
+// ifield returns the given field in the struct as an interface value.
+func structPointer_ifield(p structPointer, f field) interface{} {
+ return structPointer_field(p, f).Addr().Interface()
+}
+
+// Bytes returns the address of a []byte field in the struct.
+func structPointer_Bytes(p structPointer, f field) *[]byte {
+ return structPointer_ifield(p, f).(*[]byte)
+}
+
+// BytesSlice returns the address of a [][]byte field in the struct.
+func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
+ return structPointer_ifield(p, f).(*[][]byte)
+}
+
+// Bool returns the address of a *bool field in the struct.
+func structPointer_Bool(p structPointer, f field) **bool {
+ return structPointer_ifield(p, f).(**bool)
+}
+
+// BoolVal returns the address of a bool field in the struct.
+func structPointer_BoolVal(p structPointer, f field) *bool {
+ return structPointer_ifield(p, f).(*bool)
+}
+
+// BoolSlice returns the address of a []bool field in the struct.
+func structPointer_BoolSlice(p structPointer, f field) *[]bool {
+ return structPointer_ifield(p, f).(*[]bool)
+}
+
+// String returns the address of a *string field in the struct.
+func structPointer_String(p structPointer, f field) **string {
+ return structPointer_ifield(p, f).(**string)
+}
+
+// StringVal returns the address of a string field in the struct.
+func structPointer_StringVal(p structPointer, f field) *string {
+ return structPointer_ifield(p, f).(*string)
+}
+
+// StringSlice returns the address of a []string field in the struct.
+func structPointer_StringSlice(p structPointer, f field) *[]string {
+ return structPointer_ifield(p, f).(*[]string)
+}
+
+// Extensions returns the address of an extension map field in the struct.
+func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions {
+ return structPointer_ifield(p, f).(*XXX_InternalExtensions)
+}
+
+// ExtMap returns the address of an extension map field in the struct.
+func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
+ return structPointer_ifield(p, f).(*map[int32]Extension)
+}
+
+// NewAt returns the reflect.Value for a pointer to a field in the struct.
+func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value {
+ return structPointer_field(p, f).Addr()
+}
+
+// SetStructPointer writes a *struct field in the struct.
+func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
+ structPointer_field(p, f).Set(q.v)
+}
+
+// GetStructPointer reads a *struct field in the struct.
+func structPointer_GetStructPointer(p structPointer, f field) structPointer {
+ return structPointer{structPointer_field(p, f)}
+}
+
+// StructPointerSlice the address of a []*struct field in the struct.
+func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice {
+ return structPointerSlice{structPointer_field(p, f)}
+}
+
+// A structPointerSlice represents the address of a slice of pointers to structs
+// (themselves messages or groups). That is, v.Type() is *[]*struct{...}.
+type structPointerSlice struct {
+ v reflect.Value
+}
+
+func (p structPointerSlice) Len() int { return p.v.Len() }
+func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} }
+func (p structPointerSlice) Append(q structPointer) {
+ p.v.Set(reflect.Append(p.v, q.v))
+}
+
+var (
+ int32Type = reflect.TypeOf(int32(0))
+ uint32Type = reflect.TypeOf(uint32(0))
+ float32Type = reflect.TypeOf(float32(0))
+ int64Type = reflect.TypeOf(int64(0))
+ uint64Type = reflect.TypeOf(uint64(0))
+ float64Type = reflect.TypeOf(float64(0))
+)
+
+// A word32 represents a field of type *int32, *uint32, *float32, or *enum.
+// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable.
+type word32 struct {
+ v reflect.Value
+}
+
+// IsNil reports whether p is nil.
+func word32_IsNil(p word32) bool {
+ return p.v.IsNil()
+}
+
+// Set sets p to point at a newly allocated word with bits set to x.
+func word32_Set(p word32, o *Buffer, x uint32) {
+ t := p.v.Type().Elem()
+ switch t {
+ case int32Type:
+ if len(o.int32s) == 0 {
+ o.int32s = make([]int32, uint32PoolSize)
+ }
+ o.int32s[0] = int32(x)
+ p.v.Set(reflect.ValueOf(&o.int32s[0]))
+ o.int32s = o.int32s[1:]
+ return
+ case uint32Type:
+ if len(o.uint32s) == 0 {
+ o.uint32s = make([]uint32, uint32PoolSize)
+ }
+ o.uint32s[0] = x
+ p.v.Set(reflect.ValueOf(&o.uint32s[0]))
+ o.uint32s = o.uint32s[1:]
+ return
+ case float32Type:
+ if len(o.float32s) == 0 {
+ o.float32s = make([]float32, uint32PoolSize)
+ }
+ o.float32s[0] = math.Float32frombits(x)
+ p.v.Set(reflect.ValueOf(&o.float32s[0]))
+ o.float32s = o.float32s[1:]
+ return
+ }
+
+ // must be enum
+ p.v.Set(reflect.New(t))
+ p.v.Elem().SetInt(int64(int32(x)))
+}
+
+// Get gets the bits pointed at by p, as a uint32.
+func word32_Get(p word32) uint32 {
+ elem := p.v.Elem()
+ switch elem.Kind() {
+ case reflect.Int32:
+ return uint32(elem.Int())
+ case reflect.Uint32:
+ return uint32(elem.Uint())
+ case reflect.Float32:
+ return math.Float32bits(float32(elem.Float()))
+ }
+ panic("unreachable")
+}
+
+// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct.
+func structPointer_Word32(p structPointer, f field) word32 {
+ return word32{structPointer_field(p, f)}
+}
+
+// A word32Val represents a field of type int32, uint32, float32, or enum.
+// That is, v.Type() is int32, uint32, float32, or enum and v is assignable.
+type word32Val struct {
+ v reflect.Value
+}
+
+// Set sets *p to x.
+func word32Val_Set(p word32Val, x uint32) {
+ switch p.v.Type() {
+ case int32Type:
+ p.v.SetInt(int64(x))
+ return
+ case uint32Type:
+ p.v.SetUint(uint64(x))
+ return
+ case float32Type:
+ p.v.SetFloat(float64(math.Float32frombits(x)))
+ return
+ }
+
+ // must be enum
+ p.v.SetInt(int64(int32(x)))
+}
+
+// Get gets the bits pointed at by p, as a uint32.
+func word32Val_Get(p word32Val) uint32 {
+ elem := p.v
+ switch elem.Kind() {
+ case reflect.Int32:
+ return uint32(elem.Int())
+ case reflect.Uint32:
+ return uint32(elem.Uint())
+ case reflect.Float32:
+ return math.Float32bits(float32(elem.Float()))
+ }
+ panic("unreachable")
+}
+
+// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct.
+func structPointer_Word32Val(p structPointer, f field) word32Val {
+ return word32Val{structPointer_field(p, f)}
+}
+
+// A word32Slice is a slice of 32-bit values.
+// That is, v.Type() is []int32, []uint32, []float32, or []enum.
+type word32Slice struct {
+ v reflect.Value
+}
+
+func (p word32Slice) Append(x uint32) {
+ n, m := p.v.Len(), p.v.Cap()
+ if n < m {
+ p.v.SetLen(n + 1)
+ } else {
+ t := p.v.Type().Elem()
+ p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
+ }
+ elem := p.v.Index(n)
+ switch elem.Kind() {
+ case reflect.Int32:
+ elem.SetInt(int64(int32(x)))
+ case reflect.Uint32:
+ elem.SetUint(uint64(x))
+ case reflect.Float32:
+ elem.SetFloat(float64(math.Float32frombits(x)))
+ }
+}
+
+func (p word32Slice) Len() int {
+ return p.v.Len()
+}
+
+func (p word32Slice) Index(i int) uint32 {
+ elem := p.v.Index(i)
+ switch elem.Kind() {
+ case reflect.Int32:
+ return uint32(elem.Int())
+ case reflect.Uint32:
+ return uint32(elem.Uint())
+ case reflect.Float32:
+ return math.Float32bits(float32(elem.Float()))
+ }
+ panic("unreachable")
+}
+
+// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct.
+func structPointer_Word32Slice(p structPointer, f field) word32Slice {
+ return word32Slice{structPointer_field(p, f)}
+}
+
+// word64 is like word32 but for 64-bit values.
+type word64 struct {
+ v reflect.Value
+}
+
+func word64_Set(p word64, o *Buffer, x uint64) {
+ t := p.v.Type().Elem()
+ switch t {
+ case int64Type:
+ if len(o.int64s) == 0 {
+ o.int64s = make([]int64, uint64PoolSize)
+ }
+ o.int64s[0] = int64(x)
+ p.v.Set(reflect.ValueOf(&o.int64s[0]))
+ o.int64s = o.int64s[1:]
+ return
+ case uint64Type:
+ if len(o.uint64s) == 0 {
+ o.uint64s = make([]uint64, uint64PoolSize)
+ }
+ o.uint64s[0] = x
+ p.v.Set(reflect.ValueOf(&o.uint64s[0]))
+ o.uint64s = o.uint64s[1:]
+ return
+ case float64Type:
+ if len(o.float64s) == 0 {
+ o.float64s = make([]float64, uint64PoolSize)
+ }
+ o.float64s[0] = math.Float64frombits(x)
+ p.v.Set(reflect.ValueOf(&o.float64s[0]))
+ o.float64s = o.float64s[1:]
+ return
+ }
+ panic("unreachable")
+}
+
+func word64_IsNil(p word64) bool {
+ return p.v.IsNil()
+}
+
+func word64_Get(p word64) uint64 {
+ elem := p.v.Elem()
+ switch elem.Kind() {
+ case reflect.Int64:
+ return uint64(elem.Int())
+ case reflect.Uint64:
+ return elem.Uint()
+ case reflect.Float64:
+ return math.Float64bits(elem.Float())
+ }
+ panic("unreachable")
+}
+
+func structPointer_Word64(p structPointer, f field) word64 {
+ return word64{structPointer_field(p, f)}
+}
+
+// word64Val is like word32Val but for 64-bit values.
+type word64Val struct {
+ v reflect.Value
+}
+
+func word64Val_Set(p word64Val, o *Buffer, x uint64) {
+ switch p.v.Type() {
+ case int64Type:
+ p.v.SetInt(int64(x))
+ return
+ case uint64Type:
+ p.v.SetUint(x)
+ return
+ case float64Type:
+ p.v.SetFloat(math.Float64frombits(x))
+ return
+ }
+ panic("unreachable")
+}
+
+func word64Val_Get(p word64Val) uint64 {
+ elem := p.v
+ switch elem.Kind() {
+ case reflect.Int64:
+ return uint64(elem.Int())
+ case reflect.Uint64:
+ return elem.Uint()
+ case reflect.Float64:
+ return math.Float64bits(elem.Float())
+ }
+ panic("unreachable")
+}
+
+func structPointer_Word64Val(p structPointer, f field) word64Val {
+ return word64Val{structPointer_field(p, f)}
+}
+
+type word64Slice struct {
+ v reflect.Value
+}
+
+func (p word64Slice) Append(x uint64) {
+ n, m := p.v.Len(), p.v.Cap()
+ if n < m {
+ p.v.SetLen(n + 1)
+ } else {
+ t := p.v.Type().Elem()
+ p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
+ }
+ elem := p.v.Index(n)
+ switch elem.Kind() {
+ case reflect.Int64:
+ elem.SetInt(int64(int64(x)))
+ case reflect.Uint64:
+ elem.SetUint(uint64(x))
+ case reflect.Float64:
+ elem.SetFloat(float64(math.Float64frombits(x)))
+ }
+}
+
+func (p word64Slice) Len() int {
+ return p.v.Len()
+}
+
+func (p word64Slice) Index(i int) uint64 {
+ elem := p.v.Index(i)
+ switch elem.Kind() {
+ case reflect.Int64:
+ return uint64(elem.Int())
+ case reflect.Uint64:
+ return uint64(elem.Uint())
+ case reflect.Float64:
+ return math.Float64bits(float64(elem.Float()))
+ }
+ panic("unreachable")
+}
+
+func structPointer_Word64Slice(p structPointer, f field) word64Slice {
+ return word64Slice{structPointer_field(p, f)}
+}
diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
new file mode 100644
index 0000000..6b5567d
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
@@ -0,0 +1,270 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2012 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// +build !appengine,!js
+
+// This file contains the implementation of the proto field accesses using package unsafe.
+
+package proto
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+// NOTE: These type_Foo functions would more idiomatically be methods,
+// but Go does not allow methods on pointer types, and we must preserve
+// some pointer type for the garbage collector. We use these
+// funcs with clunky names as our poor approximation to methods.
+//
+// An alternative would be
+// type structPointer struct { p unsafe.Pointer }
+// but that does not registerize as well.
+
+// A structPointer is a pointer to a struct.
+type structPointer unsafe.Pointer
+
+// toStructPointer returns a structPointer equivalent to the given reflect value.
+func toStructPointer(v reflect.Value) structPointer {
+ return structPointer(unsafe.Pointer(v.Pointer()))
+}
+
+// IsNil reports whether p is nil.
+func structPointer_IsNil(p structPointer) bool {
+ return p == nil
+}
+
+// Interface returns the struct pointer, assumed to have element type t,
+// as an interface value.
+func structPointer_Interface(p structPointer, t reflect.Type) interface{} {
+ return reflect.NewAt(t, unsafe.Pointer(p)).Interface()
+}
+
+// A field identifies a field in a struct, accessible from a structPointer.
+// In this implementation, a field is identified by its byte offset from the start of the struct.
+type field uintptr
+
+// toField returns a field equivalent to the given reflect field.
+func toField(f *reflect.StructField) field {
+ return field(f.Offset)
+}
+
+// invalidField is an invalid field identifier.
+const invalidField = ^field(0)
+
+// IsValid reports whether the field identifier is valid.
+func (f field) IsValid() bool {
+ return f != ^field(0)
+}
+
+// Bytes returns the address of a []byte field in the struct.
+func structPointer_Bytes(p structPointer, f field) *[]byte {
+ return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// BytesSlice returns the address of a [][]byte field in the struct.
+func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
+ return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// Bool returns the address of a *bool field in the struct.
+func structPointer_Bool(p structPointer, f field) **bool {
+ return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// BoolVal returns the address of a bool field in the struct.
+func structPointer_BoolVal(p structPointer, f field) *bool {
+ return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// BoolSlice returns the address of a []bool field in the struct.
+func structPointer_BoolSlice(p structPointer, f field) *[]bool {
+ return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// String returns the address of a *string field in the struct.
+func structPointer_String(p structPointer, f field) **string {
+ return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// StringVal returns the address of a string field in the struct.
+func structPointer_StringVal(p structPointer, f field) *string {
+ return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// StringSlice returns the address of a []string field in the struct.
+func structPointer_StringSlice(p structPointer, f field) *[]string {
+ return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// ExtMap returns the address of an extension map field in the struct.
+func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions {
+ return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
+ return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// NewAt returns the reflect.Value for a pointer to a field in the struct.
+func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value {
+ return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f)))
+}
+
+// SetStructPointer writes a *struct field in the struct.
+func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
+ *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q
+}
+
+// GetStructPointer reads a *struct field in the struct.
+func structPointer_GetStructPointer(p structPointer, f field) structPointer {
+ return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// StructPointerSlice the address of a []*struct field in the struct.
+func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice {
+ return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups).
+type structPointerSlice []structPointer
+
+func (v *structPointerSlice) Len() int { return len(*v) }
+func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] }
+func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) }
+
+// A word32 is the address of a "pointer to 32-bit value" field.
+type word32 **uint32
+
+// IsNil reports whether *v is nil.
+func word32_IsNil(p word32) bool {
+ return *p == nil
+}
+
+// Set sets *v to point at a newly allocated word set to x.
+func word32_Set(p word32, o *Buffer, x uint32) {
+ if len(o.uint32s) == 0 {
+ o.uint32s = make([]uint32, uint32PoolSize)
+ }
+ o.uint32s[0] = x
+ *p = &o.uint32s[0]
+ o.uint32s = o.uint32s[1:]
+}
+
+// Get gets the value pointed at by *v.
+func word32_Get(p word32) uint32 {
+ return **p
+}
+
+// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct.
+func structPointer_Word32(p structPointer, f field) word32 {
+ return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// A word32Val is the address of a 32-bit value field.
+type word32Val *uint32
+
+// Set sets *p to x.
+func word32Val_Set(p word32Val, x uint32) {
+ *p = x
+}
+
+// Get gets the value pointed at by p.
+func word32Val_Get(p word32Val) uint32 {
+ return *p
+}
+
+// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct.
+func structPointer_Word32Val(p structPointer, f field) word32Val {
+ return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// A word32Slice is a slice of 32-bit values.
+type word32Slice []uint32
+
+func (v *word32Slice) Append(x uint32) { *v = append(*v, x) }
+func (v *word32Slice) Len() int { return len(*v) }
+func (v *word32Slice) Index(i int) uint32 { return (*v)[i] }
+
+// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct.
+func structPointer_Word32Slice(p structPointer, f field) *word32Slice {
+ return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// word64 is like word32 but for 64-bit values.
+type word64 **uint64
+
+func word64_Set(p word64, o *Buffer, x uint64) {
+ if len(o.uint64s) == 0 {
+ o.uint64s = make([]uint64, uint64PoolSize)
+ }
+ o.uint64s[0] = x
+ *p = &o.uint64s[0]
+ o.uint64s = o.uint64s[1:]
+}
+
+func word64_IsNil(p word64) bool {
+ return *p == nil
+}
+
+func word64_Get(p word64) uint64 {
+ return **p
+}
+
+func structPointer_Word64(p structPointer, f field) word64 {
+ return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// word64Val is like word32Val but for 64-bit values.
+type word64Val *uint64
+
+func word64Val_Set(p word64Val, o *Buffer, x uint64) {
+ *p = x
+}
+
+func word64Val_Get(p word64Val) uint64 {
+ return *p
+}
+
+func structPointer_Word64Val(p structPointer, f field) word64Val {
+ return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// word64Slice is like word32Slice but for 64-bit values.
+type word64Slice []uint64
+
+func (v *word64Slice) Append(x uint64) { *v = append(*v, x) }
+func (v *word64Slice) Len() int { return len(*v) }
+func (v *word64Slice) Index(i int) uint64 { return (*v)[i] }
+
+func structPointer_Word64Slice(p structPointer, f field) *word64Slice {
+ return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go
new file mode 100644
index 0000000..ec2289c
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/properties.go
@@ -0,0 +1,872 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Routines for encoding data into the wire format for protocol buffers.
+ */
+
+import (
+ "fmt"
+ "log"
+ "os"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+)
+
+const debug bool = false
+
+// Constants that identify the encoding of a value on the wire.
+const (
+ WireVarint = 0
+ WireFixed64 = 1
+ WireBytes = 2
+ WireStartGroup = 3
+ WireEndGroup = 4
+ WireFixed32 = 5
+)
+
+const startSize = 10 // initial slice/string sizes
+
+// Encoders are defined in encode.go
+// An encoder outputs the full representation of a field, including its
+// tag and encoder type.
+type encoder func(p *Buffer, prop *Properties, base structPointer) error
+
+// A valueEncoder encodes a single integer in a particular encoding.
+type valueEncoder func(o *Buffer, x uint64) error
+
+// Sizers are defined in encode.go
+// A sizer returns the encoded size of a field, including its tag and encoder
+// type.
+type sizer func(prop *Properties, base structPointer) int
+
+// A valueSizer returns the encoded size of a single integer in a particular
+// encoding.
+type valueSizer func(x uint64) int
+
+// Decoders are defined in decode.go
+// A decoder creates a value from its wire representation.
+// Unrecognized subelements are saved in unrec.
+type decoder func(p *Buffer, prop *Properties, base structPointer) error
+
+// A valueDecoder decodes a single integer in a particular encoding.
+type valueDecoder func(o *Buffer) (x uint64, err error)
+
+// A oneofMarshaler does the marshaling for all oneof fields in a message.
+type oneofMarshaler func(Message, *Buffer) error
+
+// A oneofUnmarshaler does the unmarshaling for a oneof field in a message.
+type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error)
+
+// A oneofSizer does the sizing for all oneof fields in a message.
+type oneofSizer func(Message) int
+
+// tagMap is an optimization over map[int]int for typical protocol buffer
+// use-cases. Encoded protocol buffers are often in tag order with small tag
+// numbers.
+type tagMap struct {
+ fastTags []int
+ slowTags map[int]int
+}
+
+// tagMapFastLimit is the upper bound on the tag number that will be stored in
+// the tagMap slice rather than its map.
+const tagMapFastLimit = 1024
+
+func (p *tagMap) get(t int) (int, bool) {
+ if t > 0 && t < tagMapFastLimit {
+ if t >= len(p.fastTags) {
+ return 0, false
+ }
+ fi := p.fastTags[t]
+ return fi, fi >= 0
+ }
+ fi, ok := p.slowTags[t]
+ return fi, ok
+}
+
+func (p *tagMap) put(t int, fi int) {
+ if t > 0 && t < tagMapFastLimit {
+ for len(p.fastTags) < t+1 {
+ p.fastTags = append(p.fastTags, -1)
+ }
+ p.fastTags[t] = fi
+ return
+ }
+ if p.slowTags == nil {
+ p.slowTags = make(map[int]int)
+ }
+ p.slowTags[t] = fi
+}
+
+// StructProperties represents properties for all the fields of a struct.
+// decoderTags and decoderOrigNames should only be used by the decoder.
+type StructProperties struct {
+ Prop []*Properties // properties for each field
+ reqCount int // required count
+ decoderTags tagMap // map from proto tag to struct field number
+ decoderOrigNames map[string]int // map from original name to struct field number
+ order []int // list of struct field numbers in tag order
+ unrecField field // field id of the XXX_unrecognized []byte field
+ extendable bool // is this an extendable proto
+
+ oneofMarshaler oneofMarshaler
+ oneofUnmarshaler oneofUnmarshaler
+ oneofSizer oneofSizer
+ stype reflect.Type
+
+ // OneofTypes contains information about the oneof fields in this message.
+ // It is keyed by the original name of a field.
+ OneofTypes map[string]*OneofProperties
+}
+
+// OneofProperties represents information about a specific field in a oneof.
+type OneofProperties struct {
+ Type reflect.Type // pointer to generated struct type for this oneof field
+ Field int // struct field number of the containing oneof in the message
+ Prop *Properties
+}
+
+// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
+// See encode.go, (*Buffer).enc_struct.
+
+func (sp *StructProperties) Len() int { return len(sp.order) }
+func (sp *StructProperties) Less(i, j int) bool {
+ return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
+}
+func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
+
+// Properties represents the protocol-specific behavior of a single struct field.
+type Properties struct {
+ Name string // name of the field, for error messages
+ OrigName string // original name before protocol compiler (always set)
+ JSONName string // name to use for JSON; determined by protoc
+ Wire string
+ WireType int
+ Tag int
+ Required bool
+ Optional bool
+ Repeated bool
+ Packed bool // relevant for repeated primitives only
+ Enum string // set for enum types only
+ proto3 bool // whether this is known to be a proto3 field; set for []byte only
+ oneof bool // whether this is a oneof field
+
+ Default string // default value
+ HasDefault bool // whether an explicit default was provided
+ def_uint64 uint64
+
+ enc encoder
+ valEnc valueEncoder // set for bool and numeric types only
+ field field
+ tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType)
+ tagbuf [8]byte
+ stype reflect.Type // set for struct types only
+ sprop *StructProperties // set for struct types only
+ isMarshaler bool
+ isUnmarshaler bool
+
+ mtype reflect.Type // set for map types only
+ mkeyprop *Properties // set for map types only
+ mvalprop *Properties // set for map types only
+
+ size sizer
+ valSize valueSizer // set for bool and numeric types only
+
+ dec decoder
+ valDec valueDecoder // set for bool and numeric types only
+
+ // If this is a packable field, this will be the decoder for the packed version of the field.
+ packedDec decoder
+}
+
+// String formats the properties in the protobuf struct field tag style.
+func (p *Properties) String() string {
+ s := p.Wire
+ s = ","
+ s += strconv.Itoa(p.Tag)
+ if p.Required {
+ s += ",req"
+ }
+ if p.Optional {
+ s += ",opt"
+ }
+ if p.Repeated {
+ s += ",rep"
+ }
+ if p.Packed {
+ s += ",packed"
+ }
+ s += ",name=" + p.OrigName
+ if p.JSONName != p.OrigName {
+ s += ",json=" + p.JSONName
+ }
+ if p.proto3 {
+ s += ",proto3"
+ }
+ if p.oneof {
+ s += ",oneof"
+ }
+ if len(p.Enum) > 0 {
+ s += ",enum=" + p.Enum
+ }
+ if p.HasDefault {
+ s += ",def=" + p.Default
+ }
+ return s
+}
+
+// Parse populates p by parsing a string in the protobuf struct field tag style.
+func (p *Properties) Parse(s string) {
+ // "bytes,49,opt,name=foo,def=hello!"
+ fields := strings.Split(s, ",") // breaks def=, but handled below.
+ if len(fields) < 2 {
+ fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
+ return
+ }
+
+ p.Wire = fields[0]
+ switch p.Wire {
+ case "varint":
+ p.WireType = WireVarint
+ p.valEnc = (*Buffer).EncodeVarint
+ p.valDec = (*Buffer).DecodeVarint
+ p.valSize = sizeVarint
+ case "fixed32":
+ p.WireType = WireFixed32
+ p.valEnc = (*Buffer).EncodeFixed32
+ p.valDec = (*Buffer).DecodeFixed32
+ p.valSize = sizeFixed32
+ case "fixed64":
+ p.WireType = WireFixed64
+ p.valEnc = (*Buffer).EncodeFixed64
+ p.valDec = (*Buffer).DecodeFixed64
+ p.valSize = sizeFixed64
+ case "zigzag32":
+ p.WireType = WireVarint
+ p.valEnc = (*Buffer).EncodeZigzag32
+ p.valDec = (*Buffer).DecodeZigzag32
+ p.valSize = sizeZigzag32
+ case "zigzag64":
+ p.WireType = WireVarint
+ p.valEnc = (*Buffer).EncodeZigzag64
+ p.valDec = (*Buffer).DecodeZigzag64
+ p.valSize = sizeZigzag64
+ case "bytes", "group":
+ p.WireType = WireBytes
+ // no numeric converter for non-numeric types
+ default:
+ fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
+ return
+ }
+
+ var err error
+ p.Tag, err = strconv.Atoi(fields[1])
+ if err != nil {
+ return
+ }
+
+ for i := 2; i < len(fields); i++ {
+ f := fields[i]
+ switch {
+ case f == "req":
+ p.Required = true
+ case f == "opt":
+ p.Optional = true
+ case f == "rep":
+ p.Repeated = true
+ case f == "packed":
+ p.Packed = true
+ case strings.HasPrefix(f, "name="):
+ p.OrigName = f[5:]
+ case strings.HasPrefix(f, "json="):
+ p.JSONName = f[5:]
+ case strings.HasPrefix(f, "enum="):
+ p.Enum = f[5:]
+ case f == "proto3":
+ p.proto3 = true
+ case f == "oneof":
+ p.oneof = true
+ case strings.HasPrefix(f, "def="):
+ p.HasDefault = true
+ p.Default = f[4:] // rest of string
+ if i+1 < len(fields) {
+ // Commas aren't escaped, and def is always last.
+ p.Default += "," + strings.Join(fields[i+1:], ",")
+ break
+ }
+ }
+ }
+}
+
+func logNoSliceEnc(t1, t2 reflect.Type) {
+ fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2)
+}
+
+var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
+
+// Initialize the fields for encoding and decoding.
+func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
+ p.enc = nil
+ p.dec = nil
+ p.size = nil
+
+ switch t1 := typ; t1.Kind() {
+ default:
+ fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1)
+
+ // proto3 scalar types
+
+ case reflect.Bool:
+ p.enc = (*Buffer).enc_proto3_bool
+ p.dec = (*Buffer).dec_proto3_bool
+ p.size = size_proto3_bool
+ case reflect.Int32:
+ p.enc = (*Buffer).enc_proto3_int32
+ p.dec = (*Buffer).dec_proto3_int32
+ p.size = size_proto3_int32
+ case reflect.Uint32:
+ p.enc = (*Buffer).enc_proto3_uint32
+ p.dec = (*Buffer).dec_proto3_int32 // can reuse
+ p.size = size_proto3_uint32
+ case reflect.Int64, reflect.Uint64:
+ p.enc = (*Buffer).enc_proto3_int64
+ p.dec = (*Buffer).dec_proto3_int64
+ p.size = size_proto3_int64
+ case reflect.Float32:
+ p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits
+ p.dec = (*Buffer).dec_proto3_int32
+ p.size = size_proto3_uint32
+ case reflect.Float64:
+ p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits
+ p.dec = (*Buffer).dec_proto3_int64
+ p.size = size_proto3_int64
+ case reflect.String:
+ p.enc = (*Buffer).enc_proto3_string
+ p.dec = (*Buffer).dec_proto3_string
+ p.size = size_proto3_string
+
+ case reflect.Ptr:
+ switch t2 := t1.Elem(); t2.Kind() {
+ default:
+ fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2)
+ break
+ case reflect.Bool:
+ p.enc = (*Buffer).enc_bool
+ p.dec = (*Buffer).dec_bool
+ p.size = size_bool
+ case reflect.Int32:
+ p.enc = (*Buffer).enc_int32
+ p.dec = (*Buffer).dec_int32
+ p.size = size_int32
+ case reflect.Uint32:
+ p.enc = (*Buffer).enc_uint32
+ p.dec = (*Buffer).dec_int32 // can reuse
+ p.size = size_uint32
+ case reflect.Int64, reflect.Uint64:
+ p.enc = (*Buffer).enc_int64
+ p.dec = (*Buffer).dec_int64
+ p.size = size_int64
+ case reflect.Float32:
+ p.enc = (*Buffer).enc_uint32 // can just treat them as bits
+ p.dec = (*Buffer).dec_int32
+ p.size = size_uint32
+ case reflect.Float64:
+ p.enc = (*Buffer).enc_int64 // can just treat them as bits
+ p.dec = (*Buffer).dec_int64
+ p.size = size_int64
+ case reflect.String:
+ p.enc = (*Buffer).enc_string
+ p.dec = (*Buffer).dec_string
+ p.size = size_string
+ case reflect.Struct:
+ p.stype = t1.Elem()
+ p.isMarshaler = isMarshaler(t1)
+ p.isUnmarshaler = isUnmarshaler(t1)
+ if p.Wire == "bytes" {
+ p.enc = (*Buffer).enc_struct_message
+ p.dec = (*Buffer).dec_struct_message
+ p.size = size_struct_message
+ } else {
+ p.enc = (*Buffer).enc_struct_group
+ p.dec = (*Buffer).dec_struct_group
+ p.size = size_struct_group
+ }
+ }
+
+ case reflect.Slice:
+ switch t2 := t1.Elem(); t2.Kind() {
+ default:
+ logNoSliceEnc(t1, t2)
+ break
+ case reflect.Bool:
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_bool
+ p.size = size_slice_packed_bool
+ } else {
+ p.enc = (*Buffer).enc_slice_bool
+ p.size = size_slice_bool
+ }
+ p.dec = (*Buffer).dec_slice_bool
+ p.packedDec = (*Buffer).dec_slice_packed_bool
+ case reflect.Int32:
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_int32
+ p.size = size_slice_packed_int32
+ } else {
+ p.enc = (*Buffer).enc_slice_int32
+ p.size = size_slice_int32
+ }
+ p.dec = (*Buffer).dec_slice_int32
+ p.packedDec = (*Buffer).dec_slice_packed_int32
+ case reflect.Uint32:
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_uint32
+ p.size = size_slice_packed_uint32
+ } else {
+ p.enc = (*Buffer).enc_slice_uint32
+ p.size = size_slice_uint32
+ }
+ p.dec = (*Buffer).dec_slice_int32
+ p.packedDec = (*Buffer).dec_slice_packed_int32
+ case reflect.Int64, reflect.Uint64:
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_int64
+ p.size = size_slice_packed_int64
+ } else {
+ p.enc = (*Buffer).enc_slice_int64
+ p.size = size_slice_int64
+ }
+ p.dec = (*Buffer).dec_slice_int64
+ p.packedDec = (*Buffer).dec_slice_packed_int64
+ case reflect.Uint8:
+ p.dec = (*Buffer).dec_slice_byte
+ if p.proto3 {
+ p.enc = (*Buffer).enc_proto3_slice_byte
+ p.size = size_proto3_slice_byte
+ } else {
+ p.enc = (*Buffer).enc_slice_byte
+ p.size = size_slice_byte
+ }
+ case reflect.Float32, reflect.Float64:
+ switch t2.Bits() {
+ case 32:
+ // can just treat them as bits
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_uint32
+ p.size = size_slice_packed_uint32
+ } else {
+ p.enc = (*Buffer).enc_slice_uint32
+ p.size = size_slice_uint32
+ }
+ p.dec = (*Buffer).dec_slice_int32
+ p.packedDec = (*Buffer).dec_slice_packed_int32
+ case 64:
+ // can just treat them as bits
+ if p.Packed {
+ p.enc = (*Buffer).enc_slice_packed_int64
+ p.size = size_slice_packed_int64
+ } else {
+ p.enc = (*Buffer).enc_slice_int64
+ p.size = size_slice_int64
+ }
+ p.dec = (*Buffer).dec_slice_int64
+ p.packedDec = (*Buffer).dec_slice_packed_int64
+ default:
+ logNoSliceEnc(t1, t2)
+ break
+ }
+ case reflect.String:
+ p.enc = (*Buffer).enc_slice_string
+ p.dec = (*Buffer).dec_slice_string
+ p.size = size_slice_string
+ case reflect.Ptr:
+ switch t3 := t2.Elem(); t3.Kind() {
+ default:
+ fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3)
+ break
+ case reflect.Struct:
+ p.stype = t2.Elem()
+ p.isMarshaler = isMarshaler(t2)
+ p.isUnmarshaler = isUnmarshaler(t2)
+ if p.Wire == "bytes" {
+ p.enc = (*Buffer).enc_slice_struct_message
+ p.dec = (*Buffer).dec_slice_struct_message
+ p.size = size_slice_struct_message
+ } else {
+ p.enc = (*Buffer).enc_slice_struct_group
+ p.dec = (*Buffer).dec_slice_struct_group
+ p.size = size_slice_struct_group
+ }
+ }
+ case reflect.Slice:
+ switch t2.Elem().Kind() {
+ default:
+ fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem())
+ break
+ case reflect.Uint8:
+ p.enc = (*Buffer).enc_slice_slice_byte
+ p.dec = (*Buffer).dec_slice_slice_byte
+ p.size = size_slice_slice_byte
+ }
+ }
+
+ case reflect.Map:
+ p.enc = (*Buffer).enc_new_map
+ p.dec = (*Buffer).dec_new_map
+ p.size = size_new_map
+
+ p.mtype = t1
+ p.mkeyprop = &Properties{}
+ p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
+ p.mvalprop = &Properties{}
+ vtype := p.mtype.Elem()
+ if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
+ // The value type is not a message (*T) or bytes ([]byte),
+ // so we need encoders for the pointer to this type.
+ vtype = reflect.PtrTo(vtype)
+ }
+ p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
+ }
+
+ // precalculate tag code
+ wire := p.WireType
+ if p.Packed {
+ wire = WireBytes
+ }
+ x := uint32(p.Tag)<<3 | uint32(wire)
+ i := 0
+ for i = 0; x > 127; i++ {
+ p.tagbuf[i] = 0x80 | uint8(x&0x7F)
+ x >>= 7
+ }
+ p.tagbuf[i] = uint8(x)
+ p.tagcode = p.tagbuf[0 : i+1]
+
+ if p.stype != nil {
+ if lockGetProp {
+ p.sprop = GetProperties(p.stype)
+ } else {
+ p.sprop = getPropertiesLocked(p.stype)
+ }
+ }
+}
+
+var (
+ marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
+ unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
+)
+
+// isMarshaler reports whether type t implements Marshaler.
+func isMarshaler(t reflect.Type) bool {
+ // We're checking for (likely) pointer-receiver methods
+ // so if t is not a pointer, something is very wrong.
+ // The calls above only invoke isMarshaler on pointer types.
+ if t.Kind() != reflect.Ptr {
+ panic("proto: misuse of isMarshaler")
+ }
+ return t.Implements(marshalerType)
+}
+
+// isUnmarshaler reports whether type t implements Unmarshaler.
+func isUnmarshaler(t reflect.Type) bool {
+ // We're checking for (likely) pointer-receiver methods
+ // so if t is not a pointer, something is very wrong.
+ // The calls above only invoke isUnmarshaler on pointer types.
+ if t.Kind() != reflect.Ptr {
+ panic("proto: misuse of isUnmarshaler")
+ }
+ return t.Implements(unmarshalerType)
+}
+
+// Init populates the properties from a protocol buffer struct tag.
+func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
+ p.init(typ, name, tag, f, true)
+}
+
+func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
+ // "bytes,49,opt,def=hello!"
+ p.Name = name
+ p.OrigName = name
+ if f != nil {
+ p.field = toField(f)
+ }
+ if tag == "" {
+ return
+ }
+ p.Parse(tag)
+ p.setEncAndDec(typ, f, lockGetProp)
+}
+
+var (
+ propertiesMu sync.RWMutex
+ propertiesMap = make(map[reflect.Type]*StructProperties)
+)
+
+// GetProperties returns the list of properties for the type represented by t.
+// t must represent a generated struct type of a protocol message.
+func GetProperties(t reflect.Type) *StructProperties {
+ if t.Kind() != reflect.Struct {
+ panic("proto: type must have kind struct")
+ }
+
+ // Most calls to GetProperties in a long-running program will be
+ // retrieving details for types we have seen before.
+ propertiesMu.RLock()
+ sprop, ok := propertiesMap[t]
+ propertiesMu.RUnlock()
+ if ok {
+ if collectStats {
+ stats.Chit++
+ }
+ return sprop
+ }
+
+ propertiesMu.Lock()
+ sprop = getPropertiesLocked(t)
+ propertiesMu.Unlock()
+ return sprop
+}
+
+// getPropertiesLocked requires that propertiesMu is held.
+func getPropertiesLocked(t reflect.Type) *StructProperties {
+ if prop, ok := propertiesMap[t]; ok {
+ if collectStats {
+ stats.Chit++
+ }
+ return prop
+ }
+ if collectStats {
+ stats.Cmiss++
+ }
+
+ prop := new(StructProperties)
+ // in case of recursive protos, fill this in now.
+ propertiesMap[t] = prop
+
+ // build properties
+ prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) ||
+ reflect.PtrTo(t).Implements(extendableProtoV1Type)
+ prop.unrecField = invalidField
+ prop.Prop = make([]*Properties, t.NumField())
+ prop.order = make([]int, t.NumField())
+
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ p := new(Properties)
+ name := f.Name
+ p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
+
+ if f.Name == "XXX_InternalExtensions" { // special case
+ p.enc = (*Buffer).enc_exts
+ p.dec = nil // not needed
+ p.size = size_exts
+ } else if f.Name == "XXX_extensions" { // special case
+ p.enc = (*Buffer).enc_map
+ p.dec = nil // not needed
+ p.size = size_map
+ } else if f.Name == "XXX_unrecognized" { // special case
+ prop.unrecField = toField(&f)
+ }
+ oneof := f.Tag.Get("protobuf_oneof") // special case
+ if oneof != "" {
+ // Oneof fields don't use the traditional protobuf tag.
+ p.OrigName = oneof
+ }
+ prop.Prop[i] = p
+ prop.order[i] = i
+ if debug {
+ print(i, " ", f.Name, " ", t.String(), " ")
+ if p.Tag > 0 {
+ print(p.String())
+ }
+ print("\n")
+ }
+ if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" {
+ fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
+ }
+ }
+
+ // Re-order prop.order.
+ sort.Sort(prop)
+
+ type oneofMessage interface {
+ XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
+ }
+ if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok {
+ var oots []interface{}
+ prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs()
+ prop.stype = t
+
+ // Interpret oneof metadata.
+ prop.OneofTypes = make(map[string]*OneofProperties)
+ for _, oot := range oots {
+ oop := &OneofProperties{
+ Type: reflect.ValueOf(oot).Type(), // *T
+ Prop: new(Properties),
+ }
+ sft := oop.Type.Elem().Field(0)
+ oop.Prop.Name = sft.Name
+ oop.Prop.Parse(sft.Tag.Get("protobuf"))
+ // There will be exactly one interface field that
+ // this new value is assignable to.
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ if f.Type.Kind() != reflect.Interface {
+ continue
+ }
+ if !oop.Type.AssignableTo(f.Type) {
+ continue
+ }
+ oop.Field = i
+ break
+ }
+ prop.OneofTypes[oop.Prop.OrigName] = oop
+ }
+ }
+
+ // build required counts
+ // build tags
+ reqCount := 0
+ prop.decoderOrigNames = make(map[string]int)
+ for i, p := range prop.Prop {
+ if strings.HasPrefix(p.Name, "XXX_") {
+ // Internal fields should not appear in tags/origNames maps.
+ // They are handled specially when encoding and decoding.
+ continue
+ }
+ if p.Required {
+ reqCount++
+ }
+ prop.decoderTags.put(p.Tag, i)
+ prop.decoderOrigNames[p.OrigName] = i
+ }
+ prop.reqCount = reqCount
+
+ return prop
+}
+
+// Return the Properties object for the x[0]'th field of the structure.
+func propByIndex(t reflect.Type, x []int) *Properties {
+ if len(x) != 1 {
+ fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t)
+ return nil
+ }
+ prop := GetProperties(t)
+ return prop.Prop[x[0]]
+}
+
+// Get the address and type of a pointer to a struct from an interface.
+func getbase(pb Message) (t reflect.Type, b structPointer, err error) {
+ if pb == nil {
+ err = ErrNil
+ return
+ }
+ // get the reflect type of the pointer to the struct.
+ t = reflect.TypeOf(pb)
+ // get the address of the struct.
+ value := reflect.ValueOf(pb)
+ b = toStructPointer(value)
+ return
+}
+
+// A global registry of enum types.
+// The generated code will register the generated maps by calling RegisterEnum.
+
+var enumValueMaps = make(map[string]map[string]int32)
+
+// RegisterEnum is called from the generated code to install the enum descriptor
+// maps into the global table to aid parsing text format protocol buffers.
+func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
+ if _, ok := enumValueMaps[typeName]; ok {
+ panic("proto: duplicate enum registered: " + typeName)
+ }
+ enumValueMaps[typeName] = valueMap
+}
+
+// EnumValueMap returns the mapping from names to integers of the
+// enum type enumType, or a nil if not found.
+func EnumValueMap(enumType string) map[string]int32 {
+ return enumValueMaps[enumType]
+}
+
+// A registry of all linked message types.
+// The string is a fully-qualified proto name ("pkg.Message").
+var (
+ protoTypes = make(map[string]reflect.Type)
+ revProtoTypes = make(map[reflect.Type]string)
+)
+
+// RegisterType is called from generated code and maps from the fully qualified
+// proto name to the type (pointer to struct) of the protocol buffer.
+func RegisterType(x Message, name string) {
+ if _, ok := protoTypes[name]; ok {
+ // TODO: Some day, make this a panic.
+ log.Printf("proto: duplicate proto type registered: %s", name)
+ return
+ }
+ t := reflect.TypeOf(x)
+ protoTypes[name] = t
+ revProtoTypes[t] = name
+}
+
+// MessageName returns the fully-qualified proto name for the given message type.
+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] }
+
+// A registry of all linked proto files.
+var (
+ protoFiles = make(map[string][]byte) // file name => fileDescriptor
+)
+
+// RegisterFile is called from generated code and maps from the
+// full file name of a .proto file to its compressed FileDescriptorProto.
+func RegisterFile(filename string, fileDescriptor []byte) {
+ protoFiles[filename] = fileDescriptor
+}
+
+// FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
+func FileDescriptor(filename string) []byte { return protoFiles[filename] }
diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go
new file mode 100644
index 0000000..965876b
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/text.go
@@ -0,0 +1,854 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+// Functions for writing the text protocol buffer format.
+
+import (
+ "bufio"
+ "bytes"
+ "encoding"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "math"
+ "reflect"
+ "sort"
+ "strings"
+)
+
+var (
+ newline = []byte("\n")
+ spaces = []byte(" ")
+ gtNewline = []byte(">\n")
+ endBraceNewline = []byte("}\n")
+ backslashN = []byte{'\\', 'n'}
+ backslashR = []byte{'\\', 'r'}
+ backslashT = []byte{'\\', 't'}
+ backslashDQ = []byte{'\\', '"'}
+ backslashBS = []byte{'\\', '\\'}
+ posInf = []byte("inf")
+ negInf = []byte("-inf")
+ nan = []byte("nan")
+)
+
+type writer interface {
+ io.Writer
+ WriteByte(byte) error
+}
+
+// textWriter is an io.Writer that tracks its indentation level.
+type textWriter struct {
+ ind int
+ complete bool // if the current position is a complete line
+ compact bool // whether to write out as a one-liner
+ w writer
+}
+
+func (w *textWriter) WriteString(s string) (n int, err error) {
+ if !strings.Contains(s, "\n") {
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ w.complete = false
+ return io.WriteString(w.w, s)
+ }
+ // WriteString is typically called without newlines, so this
+ // codepath and its copy are rare. We copy to avoid
+ // duplicating all of Write's logic here.
+ return w.Write([]byte(s))
+}
+
+func (w *textWriter) Write(p []byte) (n int, err error) {
+ newlines := bytes.Count(p, newline)
+ if newlines == 0 {
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ n, err = w.w.Write(p)
+ w.complete = false
+ return n, err
+ }
+
+ frags := bytes.SplitN(p, newline, newlines+1)
+ if w.compact {
+ for i, frag := range frags {
+ if i > 0 {
+ if err := w.w.WriteByte(' '); err != nil {
+ return n, err
+ }
+ n++
+ }
+ nn, err := w.w.Write(frag)
+ n += nn
+ if err != nil {
+ return n, err
+ }
+ }
+ return n, nil
+ }
+
+ for i, frag := range frags {
+ if w.complete {
+ w.writeIndent()
+ }
+ nn, err := w.w.Write(frag)
+ n += nn
+ if err != nil {
+ return n, err
+ }
+ if i+1 < len(frags) {
+ if err := w.w.WriteByte('\n'); err != nil {
+ return n, err
+ }
+ n++
+ }
+ }
+ w.complete = len(frags[len(frags)-1]) == 0
+ return n, nil
+}
+
+func (w *textWriter) WriteByte(c byte) error {
+ if w.compact && c == '\n' {
+ c = ' '
+ }
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ err := w.w.WriteByte(c)
+ w.complete = c == '\n'
+ return err
+}
+
+func (w *textWriter) indent() { w.ind++ }
+
+func (w *textWriter) unindent() {
+ if w.ind == 0 {
+ log.Print("proto: textWriter unindented too far")
+ return
+ }
+ w.ind--
+}
+
+func writeName(w *textWriter, props *Properties) error {
+ if _, err := w.WriteString(props.OrigName); err != nil {
+ return err
+ }
+ if props.Wire != "group" {
+ return w.WriteByte(':')
+ }
+ return nil
+}
+
+// raw is the interface satisfied by RawMessage.
+type raw interface {
+ Bytes() []byte
+}
+
+func requiresQuotes(u string) bool {
+ // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
+ for _, ch := range u {
+ switch {
+ case ch == '.' || ch == '/' || ch == '_':
+ continue
+ case '0' <= ch && ch <= '9':
+ continue
+ case 'A' <= ch && ch <= 'Z':
+ continue
+ case 'a' <= ch && ch <= 'z':
+ continue
+ default:
+ return true
+ }
+ }
+ return false
+}
+
+// isAny reports whether sv is a google.protobuf.Any message
+func isAny(sv reflect.Value) bool {
+ type wkt interface {
+ XXX_WellKnownType() string
+ }
+ t, ok := sv.Addr().Interface().(wkt)
+ return ok && t.XXX_WellKnownType() == "Any"
+}
+
+// writeProto3Any writes an expanded google.protobuf.Any message.
+//
+// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
+// required messages are not linked in).
+//
+// It returns (true, error) when sv was written in expanded format or an error
+// was encountered.
+func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
+ turl := sv.FieldByName("TypeUrl")
+ val := sv.FieldByName("Value")
+ if !turl.IsValid() || !val.IsValid() {
+ return true, errors.New("proto: invalid google.protobuf.Any message")
+ }
+
+ b, ok := val.Interface().([]byte)
+ if !ok {
+ return true, errors.New("proto: invalid google.protobuf.Any message")
+ }
+
+ parts := strings.Split(turl.String(), "/")
+ mt := MessageType(parts[len(parts)-1])
+ if mt == nil {
+ return false, nil
+ }
+ m := reflect.New(mt.Elem())
+ if err := Unmarshal(b, m.Interface().(Message)); err != nil {
+ return false, nil
+ }
+ w.Write([]byte("["))
+ u := turl.String()
+ if requiresQuotes(u) {
+ writeString(w, u)
+ } else {
+ w.Write([]byte(u))
+ }
+ if w.compact {
+ w.Write([]byte("]:<"))
+ } else {
+ w.Write([]byte("]: <\n"))
+ w.ind++
+ }
+ if err := tm.writeStruct(w, m.Elem()); err != nil {
+ return true, err
+ }
+ if w.compact {
+ w.Write([]byte("> "))
+ } else {
+ w.ind--
+ w.Write([]byte(">\n"))
+ }
+ return true, nil
+}
+
+func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
+ if tm.ExpandAny && isAny(sv) {
+ if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
+ return err
+ }
+ }
+ st := sv.Type()
+ sprops := GetProperties(st)
+ for i := 0; i < sv.NumField(); i++ {
+ fv := sv.Field(i)
+ props := sprops.Prop[i]
+ name := st.Field(i).Name
+
+ if strings.HasPrefix(name, "XXX_") {
+ // There are two XXX_ fields:
+ // XXX_unrecognized []byte
+ // XXX_extensions map[int32]proto.Extension
+ // The first is handled here;
+ // the second is handled at the bottom of this function.
+ if name == "XXX_unrecognized" && !fv.IsNil() {
+ if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if fv.Kind() == reflect.Ptr && fv.IsNil() {
+ // Field not filled in. This could be an optional field or
+ // a required field that wasn't filled in. Either way, there
+ // isn't anything we can show for it.
+ continue
+ }
+ if fv.Kind() == reflect.Slice && fv.IsNil() {
+ // Repeated field that is empty, or a bytes field that is unused.
+ continue
+ }
+
+ if props.Repeated && fv.Kind() == reflect.Slice {
+ // Repeated field.
+ for j := 0; j < fv.Len(); j++ {
+ if err := writeName(w, props); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ v := fv.Index(j)
+ if v.Kind() == reflect.Ptr && v.IsNil() {
+ // A nil message in a repeated field is not valid,
+ // but we can handle that more gracefully than panicking.
+ if _, err := w.Write([]byte("<nil>\n")); err != nil {
+ return err
+ }
+ continue
+ }
+ if err := tm.writeAny(w, v, props); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if fv.Kind() == reflect.Map {
+ // Map fields are rendered as a repeated struct with key/value fields.
+ keys := fv.MapKeys()
+ sort.Sort(mapKeys(keys))
+ for _, key := range keys {
+ val := fv.MapIndex(key)
+ if err := writeName(w, props); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ // open struct
+ if err := w.WriteByte('<'); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ w.indent()
+ // key
+ if _, err := w.WriteString("key:"); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if err := tm.writeAny(w, key, props.mkeyprop); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ // nil values aren't legal, but we can avoid panicking because of them.
+ if val.Kind() != reflect.Ptr || !val.IsNil() {
+ // value
+ if _, err := w.WriteString("value:"); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if err := tm.writeAny(w, val, props.mvalprop); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ // close struct
+ w.unindent()
+ if err := w.WriteByte('>'); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
+ // empty bytes field
+ continue
+ }
+ if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
+ // proto3 non-repeated scalar field; skip if zero value
+ if isProto3Zero(fv) {
+ continue
+ }
+ }
+
+ if fv.Kind() == reflect.Interface {
+ // Check if it is a oneof.
+ if st.Field(i).Tag.Get("protobuf_oneof") != "" {
+ // fv is nil, or holds a pointer to generated struct.
+ // That generated struct has exactly one field,
+ // which has a protobuf struct tag.
+ if fv.IsNil() {
+ continue
+ }
+ inner := fv.Elem().Elem() // interface -> *T -> T
+ tag := inner.Type().Field(0).Tag.Get("protobuf")
+ props = new(Properties) // Overwrite the outer props var, but not its pointee.
+ props.Parse(tag)
+ // Write the value in the oneof, not the oneof itself.
+ fv = inner.Field(0)
+
+ // Special case to cope with malformed messages gracefully:
+ // If the value in the oneof is a nil pointer, don't panic
+ // in writeAny.
+ if fv.Kind() == reflect.Ptr && fv.IsNil() {
+ // Use errors.New so writeAny won't render quotes.
+ msg := errors.New("/* nil */")
+ fv = reflect.ValueOf(&msg).Elem()
+ }
+ }
+ }
+
+ if err := writeName(w, props); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if b, ok := fv.Interface().(raw); ok {
+ if err := writeRaw(w, b.Bytes()); err != nil {
+ return err
+ }
+ continue
+ }
+
+ // Enums have a String method, so writeAny will work fine.
+ if err := tm.writeAny(w, fv, props); err != nil {
+ return err
+ }
+
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+
+ // Extensions (the XXX_extensions field).
+ pv := sv.Addr()
+ if _, ok := extendable(pv.Interface()); ok {
+ if err := tm.writeExtensions(w, pv); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+// writeRaw writes an uninterpreted raw message.
+func writeRaw(w *textWriter, b []byte) error {
+ if err := w.WriteByte('<'); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ w.indent()
+ if err := writeUnknownStruct(w, b); err != nil {
+ return err
+ }
+ w.unindent()
+ if err := w.WriteByte('>'); err != nil {
+ return err
+ }
+ return nil
+}
+
+// writeAny writes an arbitrary field.
+func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
+ v = reflect.Indirect(v)
+
+ // Floats have special cases.
+ if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
+ x := v.Float()
+ var b []byte
+ switch {
+ case math.IsInf(x, 1):
+ b = posInf
+ case math.IsInf(x, -1):
+ b = negInf
+ case math.IsNaN(x):
+ b = nan
+ }
+ if b != nil {
+ _, err := w.Write(b)
+ return err
+ }
+ // Other values are handled below.
+ }
+
+ // We don't attempt to serialise every possible value type; only those
+ // that can occur in protocol buffers.
+ switch v.Kind() {
+ case reflect.Slice:
+ // Should only be a []byte; repeated fields are handled in writeStruct.
+ if err := writeString(w, string(v.Bytes())); err != nil {
+ return err
+ }
+ case reflect.String:
+ if err := writeString(w, v.String()); err != nil {
+ return err
+ }
+ case reflect.Struct:
+ // Required/optional group/message.
+ var bra, ket byte = '<', '>'
+ if props != nil && props.Wire == "group" {
+ bra, ket = '{', '}'
+ }
+ if err := w.WriteByte(bra); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ w.indent()
+ if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
+ text, err := etm.MarshalText()
+ if err != nil {
+ return err
+ }
+ if _, err = w.Write(text); err != nil {
+ return err
+ }
+ } else if err := tm.writeStruct(w, v); err != nil {
+ return err
+ }
+ w.unindent()
+ if err := w.WriteByte(ket); err != nil {
+ return err
+ }
+ default:
+ _, err := fmt.Fprint(w, v.Interface())
+ return err
+ }
+ return nil
+}
+
+// equivalent to C's isprint.
+func isprint(c byte) bool {
+ return c >= 0x20 && c < 0x7f
+}
+
+// writeString writes a string in the protocol buffer text format.
+// It is similar to strconv.Quote except we don't use Go escape sequences,
+// we treat the string as a byte sequence, and we use octal escapes.
+// These differences are to maintain interoperability with the other
+// languages' implementations of the text format.
+func writeString(w *textWriter, s string) error {
+ // use WriteByte here to get any needed indent
+ if err := w.WriteByte('"'); err != nil {
+ return err
+ }
+ // Loop over the bytes, not the runes.
+ for i := 0; i < len(s); i++ {
+ var err error
+ // Divergence from C++: we don't escape apostrophes.
+ // There's no need to escape them, and the C++ parser
+ // copes with a naked apostrophe.
+ switch c := s[i]; c {
+ case '\n':
+ _, err = w.w.Write(backslashN)
+ case '\r':
+ _, err = w.w.Write(backslashR)
+ case '\t':
+ _, err = w.w.Write(backslashT)
+ case '"':
+ _, err = w.w.Write(backslashDQ)
+ case '\\':
+ _, err = w.w.Write(backslashBS)
+ default:
+ if isprint(c) {
+ err = w.w.WriteByte(c)
+ } else {
+ _, err = fmt.Fprintf(w.w, "\\%03o", c)
+ }
+ }
+ if err != nil {
+ return err
+ }
+ }
+ return w.WriteByte('"')
+}
+
+func writeUnknownStruct(w *textWriter, data []byte) (err error) {
+ if !w.compact {
+ if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
+ return err
+ }
+ }
+ b := NewBuffer(data)
+ for b.index < len(b.buf) {
+ x, err := b.DecodeVarint()
+ if err != nil {
+ _, err := fmt.Fprintf(w, "/* %v */\n", err)
+ return err
+ }
+ wire, tag := x&7, x>>3
+ if wire == WireEndGroup {
+ w.unindent()
+ if _, err := w.Write(endBraceNewline); err != nil {
+ return err
+ }
+ continue
+ }
+ if _, err := fmt.Fprint(w, tag); err != nil {
+ return err
+ }
+ if wire != WireStartGroup {
+ if err := w.WriteByte(':'); err != nil {
+ return err
+ }
+ }
+ if !w.compact || wire == WireStartGroup {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ switch wire {
+ case WireBytes:
+ buf, e := b.DecodeRawBytes(false)
+ if e == nil {
+ _, err = fmt.Fprintf(w, "%q", buf)
+ } else {
+ _, err = fmt.Fprintf(w, "/* %v */", e)
+ }
+ case WireFixed32:
+ x, err = b.DecodeFixed32()
+ err = writeUnknownInt(w, x, err)
+ case WireFixed64:
+ x, err = b.DecodeFixed64()
+ err = writeUnknownInt(w, x, err)
+ case WireStartGroup:
+ err = w.WriteByte('{')
+ w.indent()
+ case WireVarint:
+ x, err = b.DecodeVarint()
+ err = writeUnknownInt(w, x, err)
+ default:
+ _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
+ }
+ if err != nil {
+ return err
+ }
+ if err = w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeUnknownInt(w *textWriter, x uint64, err error) error {
+ if err == nil {
+ _, err = fmt.Fprint(w, x)
+ } else {
+ _, err = fmt.Fprintf(w, "/* %v */", err)
+ }
+ return err
+}
+
+type int32Slice []int32
+
+func (s int32Slice) Len() int { return len(s) }
+func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
+func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+// writeExtensions writes all the extensions in pv.
+// pv is assumed to be a pointer to a protocol message struct that is extendable.
+func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
+ emap := extensionMaps[pv.Type().Elem()]
+ ep, _ := extendable(pv.Interface())
+
+ // Order the extensions by ID.
+ // This isn't strictly necessary, but it will give us
+ // canonical output, which will also make testing easier.
+ m, mu := ep.extensionsRead()
+ if m == nil {
+ return nil
+ }
+ mu.Lock()
+ ids := make([]int32, 0, len(m))
+ for id := range m {
+ ids = append(ids, id)
+ }
+ sort.Sort(int32Slice(ids))
+ mu.Unlock()
+
+ for _, extNum := range ids {
+ ext := m[extNum]
+ var desc *ExtensionDesc
+ if emap != nil {
+ desc = emap[extNum]
+ }
+ if desc == nil {
+ // Unknown extension.
+ if err := writeUnknownStruct(w, ext.enc); err != nil {
+ return err
+ }
+ continue
+ }
+
+ pb, err := GetExtension(ep, desc)
+ if err != nil {
+ return fmt.Errorf("failed getting extension: %v", err)
+ }
+
+ // Repeated extensions will appear as a slice.
+ if !desc.repeated() {
+ if err := tm.writeExtension(w, desc.Name, pb); err != nil {
+ return err
+ }
+ } else {
+ v := reflect.ValueOf(pb)
+ for i := 0; i < v.Len(); i++ {
+ if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
+ if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (w *textWriter) writeIndent() {
+ if !w.complete {
+ return
+ }
+ remain := w.ind * 2
+ for remain > 0 {
+ n := remain
+ if n > len(spaces) {
+ n = len(spaces)
+ }
+ w.w.Write(spaces[:n])
+ remain -= n
+ }
+ w.complete = false
+}
+
+// TextMarshaler is a configurable text format marshaler.
+type TextMarshaler struct {
+ Compact bool // use compact text format (one line).
+ ExpandAny bool // expand google.protobuf.Any messages of known types
+}
+
+// Marshal writes a given protocol buffer in text format.
+// The only errors returned are from w.
+func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
+ val := reflect.ValueOf(pb)
+ if pb == nil || val.IsNil() {
+ w.Write([]byte("<nil>"))
+ return nil
+ }
+ var bw *bufio.Writer
+ ww, ok := w.(writer)
+ if !ok {
+ bw = bufio.NewWriter(w)
+ ww = bw
+ }
+ aw := &textWriter{
+ w: ww,
+ complete: true,
+ compact: tm.Compact,
+ }
+
+ if etm, ok := pb.(encoding.TextMarshaler); ok {
+ text, err := etm.MarshalText()
+ if err != nil {
+ return err
+ }
+ if _, err = aw.Write(text); err != nil {
+ return err
+ }
+ if bw != nil {
+ return bw.Flush()
+ }
+ return nil
+ }
+ // Dereference the received pointer so we don't have outer < and >.
+ v := reflect.Indirect(val)
+ if err := tm.writeStruct(aw, v); err != nil {
+ return err
+ }
+ if bw != nil {
+ return bw.Flush()
+ }
+ return nil
+}
+
+// Text is the same as Marshal, but returns the string directly.
+func (tm *TextMarshaler) Text(pb Message) string {
+ var buf bytes.Buffer
+ tm.Marshal(&buf, pb)
+ return buf.String()
+}
+
+var (
+ defaultTextMarshaler = TextMarshaler{}
+ compactTextMarshaler = TextMarshaler{Compact: true}
+)
+
+// TODO: consider removing some of the Marshal functions below.
+
+// MarshalText writes a given protocol buffer in text format.
+// The only errors returned are from w.
+func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
+
+// MarshalTextString is the same as MarshalText, but returns the string directly.
+func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
+
+// CompactText writes a given protocol buffer in compact text format (one line).
+func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
+
+// CompactTextString is the same as CompactText, but returns the string directly.
+func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }
diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go
new file mode 100644
index 0000000..61f83c1
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/text_parser.go
@@ -0,0 +1,895 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+// Functions for parsing the Text protocol buffer format.
+// TODO: message sets.
+
+import (
+ "encoding"
+ "errors"
+ "fmt"
+ "reflect"
+ "strconv"
+ "strings"
+ "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
+ Offset int // 0-based byte offset from start of input
+}
+
+func (p *ParseError) Error() string {
+ if p.Line == 1 {
+ // show offset only for first line
+ return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
+ }
+ return fmt.Sprintf("line %d: %v", p.Line, p.Message)
+}
+
+type token struct {
+ value string
+ err *ParseError
+ line int // line number
+ offset int // byte number from start of input, not start of line
+ unquoted string // the unquoted version of value, if it was a quoted string
+}
+
+func (t *token) String() string {
+ if t.err == nil {
+ return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
+ }
+ return fmt.Sprintf("parse error: %v", t.err)
+}
+
+type textParser struct {
+ s string // remaining input
+ done bool // whether the parsing is finished (success or error)
+ backed bool // whether back() was called
+ offset, line int
+ cur token
+}
+
+func newTextParser(s string) *textParser {
+ p := new(textParser)
+ p.s = s
+ p.line = 1
+ p.cur.line = 1
+ return p
+}
+
+func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
+ pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
+ p.cur.err = pe
+ p.done = true
+ return pe
+}
+
+// Numbers and identifiers are matched by [-+._A-Za-z0-9]
+func isIdentOrNumberChar(c byte) bool {
+ switch {
+ case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
+ return true
+ case '0' <= c && c <= '9':
+ return true
+ }
+ switch c {
+ case '-', '+', '.', '_':
+ return true
+ }
+ return false
+}
+
+func isWhitespace(c byte) bool {
+ switch c {
+ case ' ', '\t', '\n', '\r':
+ return true
+ }
+ return false
+}
+
+func isQuote(c byte) bool {
+ switch c {
+ case '"', '\'':
+ return true
+ }
+ return false
+}
+
+func (p *textParser) skipWhitespace() {
+ i := 0
+ for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
+ if p.s[i] == '#' {
+ // comment; skip to end of line or input
+ for i < len(p.s) && p.s[i] != '\n' {
+ i++
+ }
+ if i == len(p.s) {
+ break
+ }
+ }
+ if p.s[i] == '\n' {
+ p.line++
+ }
+ i++
+ }
+ p.offset += i
+ p.s = p.s[i:len(p.s)]
+ if len(p.s) == 0 {
+ p.done = true
+ }
+}
+
+func (p *textParser) advance() {
+ // Skip whitespace
+ p.skipWhitespace()
+ if p.done {
+ return
+ }
+
+ // Start of non-whitespace
+ p.cur.err = nil
+ p.cur.offset, p.cur.line = p.offset, p.line
+ p.cur.unquoted = ""
+ switch p.s[0] {
+ case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
+ // Single symbol
+ p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
+ case '"', '\'':
+ // Quoted string
+ i := 1
+ for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
+ if p.s[i] == '\\' && i+1 < len(p.s) {
+ // skip escaped char
+ i++
+ }
+ i++
+ }
+ if i >= len(p.s) || p.s[i] != p.s[0] {
+ p.errorf("unmatched quote")
+ return
+ }
+ unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
+ if err != nil {
+ p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
+ return
+ }
+ p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
+ p.cur.unquoted = unq
+ default:
+ i := 0
+ for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
+ i++
+ }
+ if i == 0 {
+ p.errorf("unexpected byte %#x", p.s[0])
+ return
+ }
+ p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
+ }
+ p.offset += len(p.cur.value)
+}
+
+var (
+ errBadUTF8 = errors.New("proto: bad UTF-8")
+ errBadHex = errors.New("proto: bad hexadecimal")
+)
+
+func unquoteC(s string, quote rune) (string, error) {
+ // This is based on C++'s tokenizer.cc.
+ // Despite its name, this is *not* parsing C syntax.
+ // For instance, "\0" is an invalid quoted string.
+
+ // Avoid allocation in trivial cases.
+ simple := true
+ for _, r := range s {
+ if r == '\\' || r == quote {
+ simple = false
+ break
+ }
+ }
+ if simple {
+ return s, nil
+ }
+
+ buf := make([]byte, 0, 3*len(s)/2)
+ for len(s) > 0 {
+ r, n := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && n == 1 {
+ return "", errBadUTF8
+ }
+ s = s[n:]
+ if r != '\\' {
+ if r < utf8.RuneSelf {
+ buf = append(buf, byte(r))
+ } else {
+ buf = append(buf, string(r)...)
+ }
+ continue
+ }
+
+ ch, tail, err := unescape(s)
+ if err != nil {
+ return "", err
+ }
+ buf = append(buf, ch...)
+ s = tail
+ }
+ return string(buf), nil
+}
+
+func unescape(s string) (ch string, tail string, err error) {
+ r, n := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && n == 1 {
+ return "", "", errBadUTF8
+ }
+ s = s[n:]
+ switch r {
+ case 'a':
+ return "\a", s, nil
+ case 'b':
+ return "\b", s, nil
+ case 'f':
+ return "\f", s, nil
+ case 'n':
+ return "\n", s, nil
+ case 'r':
+ return "\r", s, nil
+ case 't':
+ return "\t", s, nil
+ case 'v':
+ return "\v", s, nil
+ case '?':
+ return "?", s, nil // trigraph workaround
+ case '\'', '"', '\\':
+ return string(r), s, nil
+ case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X':
+ if len(s) < 2 {
+ return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
+ }
+ base := 8
+ ss := s[:2]
+ s = s[2:]
+ if r == 'x' || r == 'X' {
+ base = 16
+ } else {
+ ss = string(r) + ss
+ }
+ i, err := strconv.ParseUint(ss, base, 8)
+ if err != nil {
+ return "", "", err
+ }
+ return string([]byte{byte(i)}), s, nil
+ case 'u', 'U':
+ n := 4
+ if r == 'U' {
+ n = 8
+ }
+ if len(s) < n {
+ return "", "", fmt.Errorf(`\%c requires %d digits`, r, n)
+ }
+
+ bs := make([]byte, n/2)
+ for i := 0; i < n; i += 2 {
+ a, ok1 := unhex(s[i])
+ b, ok2 := unhex(s[i+1])
+ if !ok1 || !ok2 {
+ return "", "", errBadHex
+ }
+ bs[i/2] = a<<4 | b
+ }
+ s = s[n:]
+ return string(bs), s, nil
+ }
+ return "", "", fmt.Errorf(`unknown escape \%c`, r)
+}
+
+// Adapted from src/pkg/strconv/quote.go.
+func unhex(b byte) (v byte, ok bool) {
+ switch {
+ case '0' <= b && b <= '9':
+ return b - '0', true
+ case 'a' <= b && b <= 'f':
+ return b - 'a' + 10, true
+ case 'A' <= b && b <= 'F':
+ return b - 'A' + 10, true
+ }
+ return 0, false
+}
+
+// Back off the parser by one token. Can only be done between calls to next().
+// It makes the next advance() a no-op.
+func (p *textParser) back() { p.backed = true }
+
+// Advances the parser and returns the new current token.
+func (p *textParser) next() *token {
+ if p.backed || p.done {
+ p.backed = false
+ return &p.cur
+ }
+ p.advance()
+ if p.done {
+ p.cur.value = ""
+ } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
+ // Look for multiple quoted strings separated by whitespace,
+ // and concatenate them.
+ cat := p.cur
+ for {
+ p.skipWhitespace()
+ if p.done || !isQuote(p.s[0]) {
+ break
+ }
+ p.advance()
+ if p.cur.err != nil {
+ return &p.cur
+ }
+ cat.value += " " + p.cur.value
+ cat.unquoted += p.cur.unquoted
+ }
+ p.done = false // parser may have seen EOF, but we want to return cat
+ p.cur = cat
+ }
+ return &p.cur
+}
+
+func (p *textParser) consumeToken(s string) error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != s {
+ p.back()
+ return p.errorf("expected %q, found %q", s, tok.value)
+ }
+ return nil
+}
+
+// Return a RequiredNotSetError indicating which required field was not set.
+func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
+ st := sv.Type()
+ sprops := GetProperties(st)
+ for i := 0; i < st.NumField(); i++ {
+ if !isNil(sv.Field(i)) {
+ continue
+ }
+
+ props := sprops.Prop[i]
+ if props.Required {
+ return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
+ }
+ }
+ return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen
+}
+
+// Returns the index in the struct for the named field, as well as the parsed tag properties.
+func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
+ i, ok := sprops.decoderOrigNames[name]
+ if ok {
+ return i, sprops.Prop[i], true
+ }
+ return -1, nil, false
+}
+
+// Consume a ':' from the input stream (if the next token is a colon),
+// returning an error if a colon is needed but not present.
+func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != ":" {
+ // Colon is optional when the field is a group or message.
+ needColon := true
+ switch props.Wire {
+ case "group":
+ needColon = false
+ case "bytes":
+ // A "bytes" field is either a message, a string, or a repeated field;
+ // those three become *T, *string and []T respectively, so we can check for
+ // this field being a pointer to a non-string.
+ if typ.Kind() == reflect.Ptr {
+ // *T or *string
+ if typ.Elem().Kind() == reflect.String {
+ break
+ }
+ } else if typ.Kind() == reflect.Slice {
+ // []T or []*T
+ if typ.Elem().Kind() != reflect.Ptr {
+ break
+ }
+ } else if typ.Kind() == reflect.String {
+ // The proto3 exception is for a string field,
+ // which requires a colon.
+ break
+ }
+ needColon = false
+ }
+ if needColon {
+ return p.errorf("expected ':', found %q", tok.value)
+ }
+ p.back()
+ }
+ return nil
+}
+
+func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
+ st := sv.Type()
+ sprops := GetProperties(st)
+ reqCount := sprops.reqCount
+ var reqFieldErr error
+ fieldSet := make(map[string]bool)
+ // A struct is a sequence of "name: value", terminated by one of
+ // '>' or '}', or the end of the input. A name may also be
+ // "[extension]" or "[type/url]".
+ //
+ // The whole struct can also be an expanded Any message, like:
+ // [type/url] < ... struct contents ... >
+ for {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == terminator {
+ break
+ }
+ if tok.value == "[" {
+ // Looks like an extension or an Any.
+ //
+ // TODO: Check whether we need to handle
+ // namespace rooted names (e.g. ".something.Foo").
+ extName, err := p.consumeExtName()
+ if err != nil {
+ return err
+ }
+
+ if s := strings.LastIndex(extName, "/"); s >= 0 {
+ // If it contains a slash, it's an Any type URL.
+ messageName := extName[s+1:]
+ mt := MessageType(messageName)
+ if mt == nil {
+ return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
+ }
+ tok = p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ // consume an optional colon
+ if tok.value == ":" {
+ tok = p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ }
+ var terminator string
+ switch tok.value {
+ case "<":
+ terminator = ">"
+ case "{":
+ terminator = "}"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ v := reflect.New(mt.Elem())
+ if pe := p.readStruct(v.Elem(), terminator); pe != nil {
+ return pe
+ }
+ b, err := Marshal(v.Interface().(Message))
+ 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
+ }
+
+ var desc *ExtensionDesc
+ // This could be faster, but it's functional.
+ // TODO: Do something smarter than a linear scan.
+ for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
+ if d.Name == extName {
+ desc = d
+ break
+ }
+ }
+ if desc == nil {
+ return p.errorf("unrecognized extension %q", extName)
+ }
+
+ props := &Properties{}
+ props.Parse(desc.Tag)
+
+ typ := reflect.TypeOf(desc.ExtensionType)
+ if err := p.checkForColon(props, typ); err != nil {
+ return err
+ }
+
+ rep := desc.repeated()
+
+ // Read the extension structure, and set it in
+ // the value we're constructing.
+ var ext reflect.Value
+ if !rep {
+ ext = reflect.New(typ).Elem()
+ } else {
+ ext = reflect.New(typ.Elem()).Elem()
+ }
+ if err := p.readAny(ext, props); err != nil {
+ if _, ok := err.(*RequiredNotSetError); !ok {
+ return err
+ }
+ reqFieldErr = err
+ }
+ ep := sv.Addr().Interface().(Message)
+ if !rep {
+ SetExtension(ep, desc, ext.Interface())
+ } else {
+ old, err := GetExtension(ep, desc)
+ var sl reflect.Value
+ if err == nil {
+ sl = reflect.ValueOf(old) // existing slice
+ } else {
+ sl = reflect.MakeSlice(typ, 0, 1)
+ }
+ sl = reflect.Append(sl, ext)
+ SetExtension(ep, desc, sl.Interface())
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ continue
+ }
+
+ // This is a normal, non-extension field.
+ name := tok.value
+ var dst reflect.Value
+ fi, props, ok := structFieldByName(sprops, name)
+ if ok {
+ dst = sv.Field(fi)
+ } else if oop, ok := sprops.OneofTypes[name]; ok {
+ // It is a oneof.
+ props = oop.Prop
+ nv := reflect.New(oop.Type.Elem())
+ dst = nv.Elem().Field(0)
+ 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)
+ }
+
+ if dst.Kind() == reflect.Map {
+ // Consume any colon.
+ if err := p.checkForColon(props, dst.Type()); err != nil {
+ return err
+ }
+
+ // Construct the map if it doesn't already exist.
+ if dst.IsNil() {
+ dst.Set(reflect.MakeMap(dst.Type()))
+ }
+ key := reflect.New(dst.Type().Key()).Elem()
+ val := reflect.New(dst.Type().Elem()).Elem()
+
+ // The map entry should be this sequence of tokens:
+ // < key : KEY value : VALUE >
+ // However, implementations may omit key or value, and technically
+ // we should support them in any order. See b/28924776 for a time
+ // this went wrong.
+
+ tok := p.next()
+ var terminator string
+ switch tok.value {
+ case "<":
+ terminator = ">"
+ case "{":
+ terminator = "}"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ for {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == terminator {
+ break
+ }
+ switch tok.value {
+ case "key":
+ if err := p.consumeToken(":"); err != nil {
+ return err
+ }
+ if err := p.readAny(key, props.mkeyprop); err != nil {
+ return err
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ case "value":
+ if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
+ return err
+ }
+ if err := p.readAny(val, props.mvalprop); err != nil {
+ return err
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ default:
+ p.back()
+ return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
+ }
+ }
+
+ dst.SetMapIndex(key, val)
+ continue
+ }
+
+ // Check that it's not already set if it's not a repeated field.
+ if !props.Repeated && fieldSet[name] {
+ return p.errorf("non-repeated field %q was repeated", name)
+ }
+
+ if err := p.checkForColon(props, dst.Type()); err != nil {
+ return err
+ }
+
+ // Parse into the field.
+ fieldSet[name] = true
+ if err := p.readAny(dst, props); err != nil {
+ if _, ok := err.(*RequiredNotSetError); !ok {
+ return err
+ }
+ reqFieldErr = err
+ }
+ if props.Required {
+ reqCount--
+ }
+
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+
+ }
+
+ if reqCount > 0 {
+ return p.missingRequiredFieldError(sv)
+ }
+ return reqFieldErr
+}
+
+// consumeExtName consumes extension name or expanded Any type URL and the
+// following ']'. It returns the name or URL consumed.
+func (p *textParser) consumeExtName() (string, error) {
+ tok := p.next()
+ if tok.err != nil {
+ return "", tok.err
+ }
+
+ // If extension name or type url is quoted, it's a single token.
+ if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
+ name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
+ if err != nil {
+ return "", err
+ }
+ return name, p.consumeToken("]")
+ }
+
+ // Consume everything up to "]"
+ var parts []string
+ for tok.value != "]" {
+ parts = append(parts, tok.value)
+ tok = p.next()
+ if tok.err != nil {
+ return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
+ }
+ }
+ return strings.Join(parts, ""), nil
+}
+
+// consumeOptionalSeparator consumes an optional semicolon or comma.
+// It is used in readStruct to provide backward compatibility.
+func (p *textParser) consumeOptionalSeparator() error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != ";" && tok.value != "," {
+ p.back()
+ }
+ return nil
+}
+
+func (p *textParser) readAny(v reflect.Value, props *Properties) error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == "" {
+ return p.errorf("unexpected EOF")
+ }
+
+ switch fv := v; fv.Kind() {
+ case reflect.Slice:
+ at := v.Type()
+ if at.Elem().Kind() == reflect.Uint8 {
+ // Special case for []byte
+ if tok.value[0] != '"' && tok.value[0] != '\'' {
+ // Deliberately written out here, as the error after
+ // this switch statement would write "invalid []byte: ...",
+ // which is not as user-friendly.
+ return p.errorf("invalid string: %v", tok.value)
+ }
+ bytes := []byte(tok.unquoted)
+ fv.Set(reflect.ValueOf(bytes))
+ return nil
+ }
+ // Repeated field.
+ if tok.value == "[" {
+ // Repeated field with list notation, like [1,2,3].
+ for {
+ fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
+ err := p.readAny(fv.Index(fv.Len()-1), props)
+ if err != nil {
+ return err
+ }
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == "]" {
+ break
+ }
+ if tok.value != "," {
+ return p.errorf("Expected ']' or ',' found %q", tok.value)
+ }
+ }
+ return nil
+ }
+ // One value of the repeated field.
+ p.back()
+ fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
+ return p.readAny(fv.Index(fv.Len()-1), props)
+ case reflect.Bool:
+ // true/1/t/True or false/f/0/False.
+ switch tok.value {
+ case "true", "1", "t", "True":
+ fv.SetBool(true)
+ return nil
+ case "false", "0", "f", "False":
+ fv.SetBool(false)
+ return nil
+ }
+ case reflect.Float32, reflect.Float64:
+ v := tok.value
+ // Ignore 'f' for compatibility with output generated by C++, but don't
+ // remove 'f' when the value is "-inf" or "inf".
+ if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
+ v = v[:len(v)-1]
+ }
+ if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
+ fv.SetFloat(f)
+ return nil
+ }
+ case reflect.Int32:
+ if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
+ fv.SetInt(x)
+ return nil
+ }
+
+ if len(props.Enum) == 0 {
+ break
+ }
+ m, ok := enumValueMaps[props.Enum]
+ if !ok {
+ break
+ }
+ x, ok := m[tok.value]
+ if !ok {
+ break
+ }
+ fv.SetInt(int64(x))
+ return nil
+ case reflect.Int64:
+ if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
+ fv.SetInt(x)
+ return nil
+ }
+
+ case reflect.Ptr:
+ // A basic field (indirected through pointer), or a repeated message/group
+ p.back()
+ fv.Set(reflect.New(fv.Type().Elem()))
+ return p.readAny(fv.Elem(), props)
+ case reflect.String:
+ if tok.value[0] == '"' || tok.value[0] == '\'' {
+ fv.SetString(tok.unquoted)
+ return nil
+ }
+ case reflect.Struct:
+ var terminator string
+ switch tok.value {
+ case "{":
+ terminator = "}"
+ case "<":
+ terminator = ">"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
+ return p.readStruct(fv, terminator)
+ case reflect.Uint32:
+ if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
+ fv.SetUint(uint64(x))
+ return nil
+ }
+ case reflect.Uint64:
+ if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
+ fv.SetUint(x)
+ return nil
+ }
+ }
+ return p.errorf("invalid %v: %v", v.Type(), tok.value)
+}
+
+// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
+// before starting to unmarshal, so any existing data in pb is always removed.
+// If a required field is not set and no other error occurs,
+// UnmarshalText returns *RequiredNotSetError.
+func UnmarshalText(s string, pb Message) error {
+ if um, ok := pb.(encoding.TextUnmarshaler); ok {
+ err := um.UnmarshalText([]byte(s))
+ return err
+ }
+ pb.Reset()
+ v := reflect.ValueOf(pb)
+ if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
+ return pe
+ }
+ return nil
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
new file mode 100644
index 0000000..63cf2c8
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
@@ -0,0 +1,2152 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: google/protobuf/descriptor.proto
+
+/*
+Package descriptor is a generated protocol buffer package.
+
+It is generated from these files:
+ google/protobuf/descriptor.proto
+
+It has these top-level messages:
+ FileDescriptorSet
+ FileDescriptorProto
+ DescriptorProto
+ FieldDescriptorProto
+ OneofDescriptorProto
+ EnumDescriptorProto
+ EnumValueDescriptorProto
+ ServiceDescriptorProto
+ MethodDescriptorProto
+ FileOptions
+ MessageOptions
+ FieldOptions
+ OneofOptions
+ EnumOptions
+ EnumValueOptions
+ ServiceOptions
+ MethodOptions
+ UninterpretedOption
+ SourceCodeInfo
+ GeneratedCodeInfo
+*/
+package descriptor
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+type FieldDescriptorProto_Type int32
+
+const (
+ // 0 is reserved for errors.
+ // Order is weird for historical reasons.
+ FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1
+ FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
+ // negative values are likely.
+ FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3
+ FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
+ // negative values are likely.
+ FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5
+ FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6
+ FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7
+ FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8
+ FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9
+ // Tag-delimited aggregate.
+ // Group type is deprecated and not supported in proto3. However, Proto3
+ // implementations should still be able to parse the group wire format and
+ // treat group fields as unknown fields.
+ FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10
+ FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11
+ // New in version 2.
+ FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12
+ FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13
+ FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14
+ FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15
+ FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16
+ FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17
+ FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18
+)
+
+var FieldDescriptorProto_Type_name = map[int32]string{
+ 1: "TYPE_DOUBLE",
+ 2: "TYPE_FLOAT",
+ 3: "TYPE_INT64",
+ 4: "TYPE_UINT64",
+ 5: "TYPE_INT32",
+ 6: "TYPE_FIXED64",
+ 7: "TYPE_FIXED32",
+ 8: "TYPE_BOOL",
+ 9: "TYPE_STRING",
+ 10: "TYPE_GROUP",
+ 11: "TYPE_MESSAGE",
+ 12: "TYPE_BYTES",
+ 13: "TYPE_UINT32",
+ 14: "TYPE_ENUM",
+ 15: "TYPE_SFIXED32",
+ 16: "TYPE_SFIXED64",
+ 17: "TYPE_SINT32",
+ 18: "TYPE_SINT64",
+}
+var FieldDescriptorProto_Type_value = map[string]int32{
+ "TYPE_DOUBLE": 1,
+ "TYPE_FLOAT": 2,
+ "TYPE_INT64": 3,
+ "TYPE_UINT64": 4,
+ "TYPE_INT32": 5,
+ "TYPE_FIXED64": 6,
+ "TYPE_FIXED32": 7,
+ "TYPE_BOOL": 8,
+ "TYPE_STRING": 9,
+ "TYPE_GROUP": 10,
+ "TYPE_MESSAGE": 11,
+ "TYPE_BYTES": 12,
+ "TYPE_UINT32": 13,
+ "TYPE_ENUM": 14,
+ "TYPE_SFIXED32": 15,
+ "TYPE_SFIXED64": 16,
+ "TYPE_SINT32": 17,
+ "TYPE_SINT64": 18,
+}
+
+func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type {
+ p := new(FieldDescriptorProto_Type)
+ *p = x
+ return p
+}
+func (x FieldDescriptorProto_Type) String() string {
+ return proto.EnumName(FieldDescriptorProto_Type_name, int32(x))
+}
+func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type")
+ if err != nil {
+ return err
+ }
+ *x = FieldDescriptorProto_Type(value)
+ return nil
+}
+func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{3, 0} }
+
+type FieldDescriptorProto_Label int32
+
+const (
+ // 0 is reserved for errors
+ FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1
+ FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2
+ FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3
+)
+
+var FieldDescriptorProto_Label_name = map[int32]string{
+ 1: "LABEL_OPTIONAL",
+ 2: "LABEL_REQUIRED",
+ 3: "LABEL_REPEATED",
+}
+var FieldDescriptorProto_Label_value = map[string]int32{
+ "LABEL_OPTIONAL": 1,
+ "LABEL_REQUIRED": 2,
+ "LABEL_REPEATED": 3,
+}
+
+func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label {
+ p := new(FieldDescriptorProto_Label)
+ *p = x
+ return p
+}
+func (x FieldDescriptorProto_Label) String() string {
+ return proto.EnumName(FieldDescriptorProto_Label_name, int32(x))
+}
+func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label")
+ if err != nil {
+ return err
+ }
+ *x = FieldDescriptorProto_Label(value)
+ return nil
+}
+func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{3, 1}
+}
+
+// Generated classes can be optimized for speed or code size.
+type FileOptions_OptimizeMode int32
+
+const (
+ FileOptions_SPEED FileOptions_OptimizeMode = 1
+ // etc.
+ FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2
+ FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3
+)
+
+var FileOptions_OptimizeMode_name = map[int32]string{
+ 1: "SPEED",
+ 2: "CODE_SIZE",
+ 3: "LITE_RUNTIME",
+}
+var FileOptions_OptimizeMode_value = map[string]int32{
+ "SPEED": 1,
+ "CODE_SIZE": 2,
+ "LITE_RUNTIME": 3,
+}
+
+func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode {
+ p := new(FileOptions_OptimizeMode)
+ *p = x
+ return p
+}
+func (x FileOptions_OptimizeMode) String() string {
+ return proto.EnumName(FileOptions_OptimizeMode_name, int32(x))
+}
+func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode")
+ if err != nil {
+ return err
+ }
+ *x = FileOptions_OptimizeMode(value)
+ return nil
+}
+func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{9, 0} }
+
+type FieldOptions_CType int32
+
+const (
+ // Default mode.
+ FieldOptions_STRING FieldOptions_CType = 0
+ FieldOptions_CORD FieldOptions_CType = 1
+ FieldOptions_STRING_PIECE FieldOptions_CType = 2
+)
+
+var FieldOptions_CType_name = map[int32]string{
+ 0: "STRING",
+ 1: "CORD",
+ 2: "STRING_PIECE",
+}
+var FieldOptions_CType_value = map[string]int32{
+ "STRING": 0,
+ "CORD": 1,
+ "STRING_PIECE": 2,
+}
+
+func (x FieldOptions_CType) Enum() *FieldOptions_CType {
+ p := new(FieldOptions_CType)
+ *p = x
+ return p
+}
+func (x FieldOptions_CType) String() string {
+ return proto.EnumName(FieldOptions_CType_name, int32(x))
+}
+func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType")
+ if err != nil {
+ return err
+ }
+ *x = FieldOptions_CType(value)
+ return nil
+}
+func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{11, 0} }
+
+type FieldOptions_JSType int32
+
+const (
+ // Use the default type.
+ FieldOptions_JS_NORMAL FieldOptions_JSType = 0
+ // Use JavaScript strings.
+ FieldOptions_JS_STRING FieldOptions_JSType = 1
+ // Use JavaScript numbers.
+ FieldOptions_JS_NUMBER FieldOptions_JSType = 2
+)
+
+var FieldOptions_JSType_name = map[int32]string{
+ 0: "JS_NORMAL",
+ 1: "JS_STRING",
+ 2: "JS_NUMBER",
+}
+var FieldOptions_JSType_value = map[string]int32{
+ "JS_NORMAL": 0,
+ "JS_STRING": 1,
+ "JS_NUMBER": 2,
+}
+
+func (x FieldOptions_JSType) Enum() *FieldOptions_JSType {
+ p := new(FieldOptions_JSType)
+ *p = x
+ return p
+}
+func (x FieldOptions_JSType) String() string {
+ return proto.EnumName(FieldOptions_JSType_name, int32(x))
+}
+func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType")
+ if err != nil {
+ return err
+ }
+ *x = FieldOptions_JSType(value)
+ return nil
+}
+func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{11, 1} }
+
+// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
+// or neither? HTTP based RPC implementation may choose GET verb for safe
+// methods, and PUT verb for idempotent methods instead of the default POST.
+type MethodOptions_IdempotencyLevel int32
+
+const (
+ MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0
+ MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1
+ MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2
+)
+
+var MethodOptions_IdempotencyLevel_name = map[int32]string{
+ 0: "IDEMPOTENCY_UNKNOWN",
+ 1: "NO_SIDE_EFFECTS",
+ 2: "IDEMPOTENT",
+}
+var MethodOptions_IdempotencyLevel_value = map[string]int32{
+ "IDEMPOTENCY_UNKNOWN": 0,
+ "NO_SIDE_EFFECTS": 1,
+ "IDEMPOTENT": 2,
+}
+
+func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel {
+ p := new(MethodOptions_IdempotencyLevel)
+ *p = x
+ return p
+}
+func (x MethodOptions_IdempotencyLevel) String() string {
+ return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x))
+}
+func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel")
+ if err != nil {
+ return err
+ }
+ *x = MethodOptions_IdempotencyLevel(value)
+ return nil
+}
+func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{16, 0}
+}
+
+// The protocol compiler can output a FileDescriptorSet containing the .proto
+// files it parses.
+type FileDescriptorSet struct {
+ File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} }
+func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) }
+func (*FileDescriptorSet) ProtoMessage() {}
+func (*FileDescriptorSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto {
+ if m != nil {
+ return m.File
+ }
+ return nil
+}
+
+// Describes a complete .proto file.
+type FileDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"`
+ // Names of files imported by this file.
+ Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"`
+ // Indexes of the public imported files in the dependency list above.
+ PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"`
+ // Indexes of the weak imported files in the dependency list.
+ // For Google-internal migration only. Do not use.
+ WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"`
+ // All top-level definitions in this file.
+ MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"`
+ EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
+ Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"`
+ Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"`
+ Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
+ // This field contains optional information about the original source code.
+ // You may safely remove this entire field without harming runtime
+ // functionality of the descriptors -- the information is needed only by
+ // development tools.
+ SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"`
+ // The syntax of the proto file.
+ // The supported values are "proto2" and "proto3".
+ Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} }
+func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*FileDescriptorProto) ProtoMessage() {}
+func (*FileDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *FileDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *FileDescriptorProto) GetPackage() string {
+ if m != nil && m.Package != nil {
+ return *m.Package
+ }
+ return ""
+}
+
+func (m *FileDescriptorProto) GetDependency() []string {
+ if m != nil {
+ return m.Dependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetPublicDependency() []int32 {
+ if m != nil {
+ return m.PublicDependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetWeakDependency() []int32 {
+ if m != nil {
+ return m.WeakDependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto {
+ if m != nil {
+ return m.MessageType
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto {
+ if m != nil {
+ return m.EnumType
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto {
+ if m != nil {
+ return m.Service
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Extension
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetOptions() *FileOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo {
+ if m != nil {
+ return m.SourceCodeInfo
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetSyntax() string {
+ if m != nil && m.Syntax != nil {
+ return *m.Syntax
+ }
+ return ""
+}
+
+// Describes a message type.
+type DescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"`
+ Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"`
+ NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"`
+ EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
+ ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"`
+ OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"`
+ Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"`
+ ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
+ // Reserved field names, which may not be used by fields in the same message.
+ // A given name may only be reserved once.
+ ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *DescriptorProto) Reset() { *m = DescriptorProto{} }
+func (m *DescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto) ProtoMessage() {}
+func (*DescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+
+func (m *DescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *DescriptorProto) GetField() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Field
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Extension
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetNestedType() []*DescriptorProto {
+ if m != nil {
+ return m.NestedType
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto {
+ if m != nil {
+ return m.EnumType
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange {
+ if m != nil {
+ return m.ExtensionRange
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto {
+ if m != nil {
+ return m.OneofDecl
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetOptions() *MessageOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange {
+ if m != nil {
+ return m.ReservedRange
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetReservedName() []string {
+ if m != nil {
+ return m.ReservedName
+ }
+ return nil
+}
+
+type DescriptorProto_ExtensionRange struct {
+ Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
+ End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} }
+func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto_ExtensionRange) ProtoMessage() {}
+func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{2, 0}
+}
+
+func (m *DescriptorProto_ExtensionRange) GetStart() int32 {
+ if m != nil && m.Start != nil {
+ return *m.Start
+ }
+ return 0
+}
+
+func (m *DescriptorProto_ExtensionRange) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+// Range of reserved tag numbers. Reserved tag numbers may not be used by
+// fields or extension ranges in the same message. Reserved ranges may
+// not overlap.
+type DescriptorProto_ReservedRange struct {
+ Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
+ End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} }
+func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto_ReservedRange) ProtoMessage() {}
+func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{2, 1}
+}
+
+func (m *DescriptorProto_ReservedRange) GetStart() int32 {
+ if m != nil && m.Start != nil {
+ return *m.Start
+ }
+ return 0
+}
+
+func (m *DescriptorProto_ReservedRange) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+// Describes a field within a message.
+type FieldDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"`
+ Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"`
+ // If type_name is set, this need not be set. If both this and type_name
+ // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
+ Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"`
+ // For message and enum types, this is the name of the type. If the name
+ // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
+ // rules are used to find the type (i.e. first the nested types within this
+ // message are searched, then within the parent, on up to the root
+ // namespace).
+ TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"`
+ // For extensions, this is the name of the type being extended. It is
+ // resolved in the same manner as type_name.
+ Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"`
+ // For numeric types, contains the original text representation of the value.
+ // For booleans, "true" or "false".
+ // For strings, contains the default text contents (not escaped in any way).
+ // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
+ // TODO(kenton): Base-64 encode?
+ DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"`
+ // If set, gives the index of a oneof in the containing type's oneof_decl
+ // list. This field is a member of that oneof.
+ OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"`
+ // JSON name of this field. The value is set by protocol compiler. If the
+ // user has set a "json_name" option on this field, that option's value
+ // will be used. Otherwise, it's deduced from the field's name by converting
+ // it to camelCase.
+ JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"`
+ Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} }
+func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*FieldDescriptorProto) ProtoMessage() {}
+func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
+
+func (m *FieldDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetNumber() int32 {
+ if m != nil && m.Number != nil {
+ return *m.Number
+ }
+ return 0
+}
+
+func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return FieldDescriptorProto_LABEL_OPTIONAL
+}
+
+func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return FieldDescriptorProto_TYPE_DOUBLE
+}
+
+func (m *FieldDescriptorProto) GetTypeName() string {
+ if m != nil && m.TypeName != nil {
+ return *m.TypeName
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetExtendee() string {
+ if m != nil && m.Extendee != nil {
+ return *m.Extendee
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetDefaultValue() string {
+ if m != nil && m.DefaultValue != nil {
+ return *m.DefaultValue
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetOneofIndex() int32 {
+ if m != nil && m.OneofIndex != nil {
+ return *m.OneofIndex
+ }
+ return 0
+}
+
+func (m *FieldDescriptorProto) GetJsonName() string {
+ if m != nil && m.JsonName != nil {
+ return *m.JsonName
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetOptions() *FieldOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a oneof.
+type OneofDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} }
+func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*OneofDescriptorProto) ProtoMessage() {}
+func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
+
+func (m *OneofDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *OneofDescriptorProto) GetOptions() *OneofOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes an enum type.
+type EnumDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"`
+ Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} }
+func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*EnumDescriptorProto) ProtoMessage() {}
+func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
+
+func (m *EnumDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func (m *EnumDescriptorProto) GetOptions() *EnumOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a value within an enum.
+type EnumValueDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"`
+ Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} }
+func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*EnumValueDescriptorProto) ProtoMessage() {}
+func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
+
+func (m *EnumValueDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *EnumValueDescriptorProto) GetNumber() int32 {
+ if m != nil && m.Number != nil {
+ return *m.Number
+ }
+ return 0
+}
+
+func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a service.
+type ServiceDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"`
+ Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} }
+func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*ServiceDescriptorProto) ProtoMessage() {}
+func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
+
+func (m *ServiceDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto {
+ if m != nil {
+ return m.Method
+ }
+ return nil
+}
+
+func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a method of a service.
+type MethodDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ // Input and output type names. These are resolved in the same way as
+ // FieldDescriptorProto.type_name, but must refer to a message type.
+ InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"`
+ OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"`
+ Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"`
+ // Identifies if client streams multiple client messages
+ ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"`
+ // Identifies if server streams multiple server messages
+ ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} }
+func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*MethodDescriptorProto) ProtoMessage() {}
+func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
+
+const Default_MethodDescriptorProto_ClientStreaming bool = false
+const Default_MethodDescriptorProto_ServerStreaming bool = false
+
+func (m *MethodDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetInputType() string {
+ if m != nil && m.InputType != nil {
+ return *m.InputType
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetOutputType() string {
+ if m != nil && m.OutputType != nil {
+ return *m.OutputType
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetOptions() *MethodOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *MethodDescriptorProto) GetClientStreaming() bool {
+ if m != nil && m.ClientStreaming != nil {
+ return *m.ClientStreaming
+ }
+ return Default_MethodDescriptorProto_ClientStreaming
+}
+
+func (m *MethodDescriptorProto) GetServerStreaming() bool {
+ if m != nil && m.ServerStreaming != nil {
+ return *m.ServerStreaming
+ }
+ return Default_MethodDescriptorProto_ServerStreaming
+}
+
+type FileOptions struct {
+ // Sets the Java package where classes generated from this .proto will be
+ // placed. By default, the proto package is used, but this is often
+ // inappropriate because proto packages do not normally start with backwards
+ // domain names.
+ JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"`
+ // If set, all the classes from the .proto file are wrapped in a single
+ // outer class with the given name. This applies to both Proto1
+ // (equivalent to the old "--one_java_file" option) and Proto2 (where
+ // a .proto always translates to a single class, but you may want to
+ // explicitly choose the class name).
+ JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"`
+ // If set true, then the Java code generator will generate a separate .java
+ // file for each top-level message, enum, and service defined in the .proto
+ // file. Thus, these types will *not* be nested inside the outer class
+ // named by java_outer_classname. However, the outer class will still be
+ // generated to contain the file's getDescriptor() method as well as any
+ // top-level extensions defined in the file.
+ JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"`
+ // This option does nothing.
+ JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"`
+ // If set true, then the Java2 code generator will generate code that
+ // throws an exception whenever an attempt is made to assign a non-UTF-8
+ // byte sequence to a string field.
+ // Message reflection will do the same.
+ // However, an extension field still accepts non-UTF-8 byte sequences.
+ // This option has no effect on when used with the lite runtime.
+ JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"`
+ OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"`
+ // Sets the Go package where structs generated from this .proto will be
+ // placed. If omitted, the Go package will be derived from the following:
+ // - The basename of the package import path, if provided.
+ // - Otherwise, the package statement in the .proto file, if present.
+ // - Otherwise, the basename of the .proto file, without extension.
+ GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"`
+ // Should generic services be generated in each language? "Generic" services
+ // are not specific to any particular RPC system. They are generated by the
+ // main code generators in each language (without additional plugins).
+ // Generic services were the only kind of service generation supported by
+ // early versions of google.protobuf.
+ //
+ // Generic services are now considered deprecated in favor of using plugins
+ // that generate code specific to your particular RPC system. Therefore,
+ // these default to false. Old code which depends on generic services should
+ // explicitly set them to true.
+ CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"`
+ JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"`
+ PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"`
+ // Is this file deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for everything in the file, or it will be completely ignored; in the very
+ // least, this is a formalization for deprecating files.
+ Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // Enables the use of arenas for the proto messages in this file. This applies
+ // only to generated classes for C++.
+ CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"`
+ // Sets the objective c class prefix which is prepended to all objective c
+ // generated classes from this .proto. There is no default.
+ ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"`
+ // Namespace for generated classes; defaults to the package.
+ CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"`
+ // By default Swift generators will take the proto package and CamelCase it
+ // replacing '.' with underscore and use that to prefix the types/symbols
+ // defined. When this options is provided, they will use this value instead
+ // to prefix the types/symbols defined.
+ SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"`
+ // Sets the php class prefix which is prepended to all php generated classes
+ // from this .proto. Default is empty.
+ PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FileOptions) Reset() { *m = FileOptions{} }
+func (m *FileOptions) String() string { return proto.CompactTextString(m) }
+func (*FileOptions) ProtoMessage() {}
+func (*FileOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} }
+
+var extRange_FileOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_FileOptions
+}
+
+const Default_FileOptions_JavaMultipleFiles bool = false
+const Default_FileOptions_JavaStringCheckUtf8 bool = false
+const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED
+const Default_FileOptions_CcGenericServices bool = false
+const Default_FileOptions_JavaGenericServices bool = false
+const Default_FileOptions_PyGenericServices bool = false
+const Default_FileOptions_Deprecated bool = false
+const Default_FileOptions_CcEnableArenas bool = false
+
+func (m *FileOptions) GetJavaPackage() string {
+ if m != nil && m.JavaPackage != nil {
+ return *m.JavaPackage
+ }
+ return ""
+}
+
+func (m *FileOptions) GetJavaOuterClassname() string {
+ if m != nil && m.JavaOuterClassname != nil {
+ return *m.JavaOuterClassname
+ }
+ return ""
+}
+
+func (m *FileOptions) GetJavaMultipleFiles() bool {
+ if m != nil && m.JavaMultipleFiles != nil {
+ return *m.JavaMultipleFiles
+ }
+ return Default_FileOptions_JavaMultipleFiles
+}
+
+func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool {
+ if m != nil && m.JavaGenerateEqualsAndHash != nil {
+ return *m.JavaGenerateEqualsAndHash
+ }
+ return false
+}
+
+func (m *FileOptions) GetJavaStringCheckUtf8() bool {
+ if m != nil && m.JavaStringCheckUtf8 != nil {
+ return *m.JavaStringCheckUtf8
+ }
+ return Default_FileOptions_JavaStringCheckUtf8
+}
+
+func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode {
+ if m != nil && m.OptimizeFor != nil {
+ return *m.OptimizeFor
+ }
+ return Default_FileOptions_OptimizeFor
+}
+
+func (m *FileOptions) GetGoPackage() string {
+ if m != nil && m.GoPackage != nil {
+ return *m.GoPackage
+ }
+ return ""
+}
+
+func (m *FileOptions) GetCcGenericServices() bool {
+ if m != nil && m.CcGenericServices != nil {
+ return *m.CcGenericServices
+ }
+ return Default_FileOptions_CcGenericServices
+}
+
+func (m *FileOptions) GetJavaGenericServices() bool {
+ if m != nil && m.JavaGenericServices != nil {
+ return *m.JavaGenericServices
+ }
+ return Default_FileOptions_JavaGenericServices
+}
+
+func (m *FileOptions) GetPyGenericServices() bool {
+ if m != nil && m.PyGenericServices != nil {
+ return *m.PyGenericServices
+ }
+ return Default_FileOptions_PyGenericServices
+}
+
+func (m *FileOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_FileOptions_Deprecated
+}
+
+func (m *FileOptions) GetCcEnableArenas() bool {
+ if m != nil && m.CcEnableArenas != nil {
+ return *m.CcEnableArenas
+ }
+ return Default_FileOptions_CcEnableArenas
+}
+
+func (m *FileOptions) GetObjcClassPrefix() string {
+ if m != nil && m.ObjcClassPrefix != nil {
+ return *m.ObjcClassPrefix
+ }
+ return ""
+}
+
+func (m *FileOptions) GetCsharpNamespace() string {
+ if m != nil && m.CsharpNamespace != nil {
+ return *m.CsharpNamespace
+ }
+ return ""
+}
+
+func (m *FileOptions) GetSwiftPrefix() string {
+ if m != nil && m.SwiftPrefix != nil {
+ return *m.SwiftPrefix
+ }
+ return ""
+}
+
+func (m *FileOptions) GetPhpClassPrefix() string {
+ if m != nil && m.PhpClassPrefix != nil {
+ return *m.PhpClassPrefix
+ }
+ return ""
+}
+
+func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type MessageOptions struct {
+ // Set true to use the old proto1 MessageSet wire format for extensions.
+ // This is provided for backwards-compatibility with the MessageSet wire
+ // format. You should not use this for any other reason: It's less
+ // efficient, has fewer features, and is more complicated.
+ //
+ // The message must be defined exactly as follows:
+ // message Foo {
+ // option message_set_wire_format = true;
+ // extensions 4 to max;
+ // }
+ // Note that the message cannot have any defined fields; MessageSets only
+ // have extensions.
+ //
+ // All extensions of your type must be singular messages; e.g. they cannot
+ // be int32s, enums, or repeated messages.
+ //
+ // Because this is an option, the above two restrictions are not enforced by
+ // the protocol compiler.
+ MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"`
+ // Disables the generation of the standard "descriptor()" accessor, which can
+ // conflict with a field of the same name. This is meant to make migration
+ // from proto1 easier; new code should avoid fields named "descriptor".
+ NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"`
+ // Is this message deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the message, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating messages.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // Whether the message is an automatically generated map entry type for the
+ // maps field.
+ //
+ // For maps fields:
+ // map<KeyType, ValueType> map_field = 1;
+ // The parsed descriptor looks like:
+ // message MapFieldEntry {
+ // option map_entry = true;
+ // optional KeyType key = 1;
+ // optional ValueType value = 2;
+ // }
+ // repeated MapFieldEntry map_field = 1;
+ //
+ // Implementations may choose not to generate the map_entry=true message, but
+ // use a native map in the target language to hold the keys and values.
+ // The reflection APIs in such implementions still need to work as
+ // if the field is a repeated message field.
+ //
+ // NOTE: Do not set the option in .proto files. Always use the maps syntax
+ // instead. The option should only be implicitly set by the proto compiler
+ // parser.
+ MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MessageOptions) Reset() { *m = MessageOptions{} }
+func (m *MessageOptions) String() string { return proto.CompactTextString(m) }
+func (*MessageOptions) ProtoMessage() {}
+func (*MessageOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} }
+
+var extRange_MessageOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_MessageOptions
+}
+
+const Default_MessageOptions_MessageSetWireFormat bool = false
+const Default_MessageOptions_NoStandardDescriptorAccessor bool = false
+const Default_MessageOptions_Deprecated bool = false
+
+func (m *MessageOptions) GetMessageSetWireFormat() bool {
+ if m != nil && m.MessageSetWireFormat != nil {
+ return *m.MessageSetWireFormat
+ }
+ return Default_MessageOptions_MessageSetWireFormat
+}
+
+func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool {
+ if m != nil && m.NoStandardDescriptorAccessor != nil {
+ return *m.NoStandardDescriptorAccessor
+ }
+ return Default_MessageOptions_NoStandardDescriptorAccessor
+}
+
+func (m *MessageOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_MessageOptions_Deprecated
+}
+
+func (m *MessageOptions) GetMapEntry() bool {
+ if m != nil && m.MapEntry != nil {
+ return *m.MapEntry
+ }
+ return false
+}
+
+func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type FieldOptions struct {
+ // The ctype option instructs the C++ code generator to use a different
+ // representation of the field than it normally would. See the specific
+ // options below. This option is not yet implemented in the open source
+ // release -- sorry, we'll try to include it in a future version!
+ Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"`
+ // The packed option can be enabled for repeated primitive fields to enable
+ // a more efficient representation on the wire. Rather than repeatedly
+ // writing the tag and type for each element, the entire array is encoded as
+ // a single length-delimited blob. In proto3, only explicit setting it to
+ // false will avoid using packed encoding.
+ Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"`
+ // The jstype option determines the JavaScript type used for values of the
+ // field. The option is permitted only for 64 bit integral and fixed types
+ // (int64, uint64, sint64, fixed64, sfixed64). By default these types are
+ // represented as JavaScript strings. This avoids loss of precision that can
+ // happen when a large value is converted to a floating point JavaScript
+ // numbers. Specifying JS_NUMBER for the jstype causes the generated
+ // JavaScript code to use the JavaScript "number" type instead of strings.
+ // This option is an enum to permit additional types to be added,
+ // e.g. goog.math.Integer.
+ Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"`
+ // Should this field be parsed lazily? Lazy applies only to message-type
+ // fields. It means that when the outer message is initially parsed, the
+ // inner message's contents will not be parsed but instead stored in encoded
+ // form. The inner message will actually be parsed when it is first accessed.
+ //
+ // This is only a hint. Implementations are free to choose whether to use
+ // eager or lazy parsing regardless of the value of this option. However,
+ // setting this option true suggests that the protocol author believes that
+ // using lazy parsing on this field is worth the additional bookkeeping
+ // overhead typically needed to implement it.
+ //
+ // This option does not affect the public interface of any generated code;
+ // all method signatures remain the same. Furthermore, thread-safety of the
+ // interface is not affected by this option; const methods remain safe to
+ // call from multiple threads concurrently, while non-const methods continue
+ // to require exclusive access.
+ //
+ //
+ // Note that implementations may choose not to check required fields within
+ // a lazy sub-message. That is, calling IsInitialized() on the outer message
+ // may return true even if the inner message has missing required fields.
+ // This is necessary because otherwise the inner message would have to be
+ // parsed in order to perform the check, defeating the purpose of lazy
+ // parsing. An implementation which chooses not to check required fields
+ // must be consistent about it. That is, for any particular sub-message, the
+ // implementation must either *always* check its required fields, or *never*
+ // check its required fields, regardless of whether or not the message has
+ // been parsed.
+ Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"`
+ // Is this field deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for accessors, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating fields.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // For Google-internal migration only. Do not use.
+ Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FieldOptions) Reset() { *m = FieldOptions{} }
+func (m *FieldOptions) String() string { return proto.CompactTextString(m) }
+func (*FieldOptions) ProtoMessage() {}
+func (*FieldOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} }
+
+var extRange_FieldOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_FieldOptions
+}
+
+const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING
+const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL
+const Default_FieldOptions_Lazy bool = false
+const Default_FieldOptions_Deprecated bool = false
+const Default_FieldOptions_Weak bool = false
+
+func (m *FieldOptions) GetCtype() FieldOptions_CType {
+ if m != nil && m.Ctype != nil {
+ return *m.Ctype
+ }
+ return Default_FieldOptions_Ctype
+}
+
+func (m *FieldOptions) GetPacked() bool {
+ if m != nil && m.Packed != nil {
+ return *m.Packed
+ }
+ return false
+}
+
+func (m *FieldOptions) GetJstype() FieldOptions_JSType {
+ if m != nil && m.Jstype != nil {
+ return *m.Jstype
+ }
+ return Default_FieldOptions_Jstype
+}
+
+func (m *FieldOptions) GetLazy() bool {
+ if m != nil && m.Lazy != nil {
+ return *m.Lazy
+ }
+ return Default_FieldOptions_Lazy
+}
+
+func (m *FieldOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_FieldOptions_Deprecated
+}
+
+func (m *FieldOptions) GetWeak() bool {
+ if m != nil && m.Weak != nil {
+ return *m.Weak
+ }
+ return Default_FieldOptions_Weak
+}
+
+func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type OneofOptions struct {
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OneofOptions) Reset() { *m = OneofOptions{} }
+func (m *OneofOptions) String() string { return proto.CompactTextString(m) }
+func (*OneofOptions) ProtoMessage() {}
+func (*OneofOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} }
+
+var extRange_OneofOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_OneofOptions
+}
+
+func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type EnumOptions struct {
+ // Set this option to true to allow mapping different tag names to the same
+ // value.
+ AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"`
+ // Is this enum deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating enums.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumOptions) Reset() { *m = EnumOptions{} }
+func (m *EnumOptions) String() string { return proto.CompactTextString(m) }
+func (*EnumOptions) ProtoMessage() {}
+func (*EnumOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} }
+
+var extRange_EnumOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_EnumOptions
+}
+
+const Default_EnumOptions_Deprecated bool = false
+
+func (m *EnumOptions) GetAllowAlias() bool {
+ if m != nil && m.AllowAlias != nil {
+ return *m.AllowAlias
+ }
+ return false
+}
+
+func (m *EnumOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_EnumOptions_Deprecated
+}
+
+func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type EnumValueOptions struct {
+ // Is this enum value deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum value, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating enum values.
+ Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} }
+func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) }
+func (*EnumValueOptions) ProtoMessage() {}
+func (*EnumValueOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} }
+
+var extRange_EnumValueOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_EnumValueOptions
+}
+
+const Default_EnumValueOptions_Deprecated bool = false
+
+func (m *EnumValueOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_EnumValueOptions_Deprecated
+}
+
+func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type ServiceOptions struct {
+ // Is this service deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the service, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating services.
+ Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ServiceOptions) Reset() { *m = ServiceOptions{} }
+func (m *ServiceOptions) String() string { return proto.CompactTextString(m) }
+func (*ServiceOptions) ProtoMessage() {}
+func (*ServiceOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} }
+
+var extRange_ServiceOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_ServiceOptions
+}
+
+const Default_ServiceOptions_Deprecated bool = false
+
+func (m *ServiceOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_ServiceOptions_Deprecated
+}
+
+func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type MethodOptions struct {
+ // Is this method deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the method, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating methods.
+ Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MethodOptions) Reset() { *m = MethodOptions{} }
+func (m *MethodOptions) String() string { return proto.CompactTextString(m) }
+func (*MethodOptions) ProtoMessage() {}
+func (*MethodOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} }
+
+var extRange_MethodOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_MethodOptions
+}
+
+const Default_MethodOptions_Deprecated bool = false
+const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN
+
+func (m *MethodOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_MethodOptions_Deprecated
+}
+
+func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel {
+ if m != nil && m.IdempotencyLevel != nil {
+ return *m.IdempotencyLevel
+ }
+ return Default_MethodOptions_IdempotencyLevel
+}
+
+func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+// A message representing a option the parser does not recognize. This only
+// appears in options protos created by the compiler::Parser class.
+// DescriptorPool resolves these when building Descriptor objects. Therefore,
+// options protos in descriptor objects (e.g. returned by Descriptor::options(),
+// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
+// in them.
+type UninterpretedOption struct {
+ Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"`
+ // The value of the uninterpreted option, in whatever type the tokenizer
+ // identified it as during parsing. Exactly one of these should be set.
+ IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"`
+ PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"`
+ NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"`
+ DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"`
+ StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"`
+ AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} }
+func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) }
+func (*UninterpretedOption) ProtoMessage() {}
+func (*UninterpretedOption) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} }
+
+func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart {
+ if m != nil {
+ return m.Name
+ }
+ return nil
+}
+
+func (m *UninterpretedOption) GetIdentifierValue() string {
+ if m != nil && m.IdentifierValue != nil {
+ return *m.IdentifierValue
+ }
+ return ""
+}
+
+func (m *UninterpretedOption) GetPositiveIntValue() uint64 {
+ if m != nil && m.PositiveIntValue != nil {
+ return *m.PositiveIntValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetNegativeIntValue() int64 {
+ if m != nil && m.NegativeIntValue != nil {
+ return *m.NegativeIntValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetDoubleValue() float64 {
+ if m != nil && m.DoubleValue != nil {
+ return *m.DoubleValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetStringValue() []byte {
+ if m != nil {
+ return m.StringValue
+ }
+ return nil
+}
+
+func (m *UninterpretedOption) GetAggregateValue() string {
+ if m != nil && m.AggregateValue != nil {
+ return *m.AggregateValue
+ }
+ return ""
+}
+
+// The name of the uninterpreted option. Each string represents a segment in
+// a dot-separated name. is_extension is true iff a segment represents an
+// extension (denoted with parentheses in options specs in .proto files).
+// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
+// "foo.(bar.baz).qux".
+type UninterpretedOption_NamePart struct {
+ NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"`
+ IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} }
+func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) }
+func (*UninterpretedOption_NamePart) ProtoMessage() {}
+func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{17, 0}
+}
+
+func (m *UninterpretedOption_NamePart) GetNamePart() string {
+ if m != nil && m.NamePart != nil {
+ return *m.NamePart
+ }
+ return ""
+}
+
+func (m *UninterpretedOption_NamePart) GetIsExtension() bool {
+ if m != nil && m.IsExtension != nil {
+ return *m.IsExtension
+ }
+ return false
+}
+
+// Encapsulates information about the original source file from which a
+// FileDescriptorProto was generated.
+type SourceCodeInfo struct {
+ // A Location identifies a piece of source code in a .proto file which
+ // corresponds to a particular definition. This information is intended
+ // to be useful to IDEs, code indexers, documentation generators, and similar
+ // tools.
+ //
+ // For example, say we have a file like:
+ // message Foo {
+ // optional string foo = 1;
+ // }
+ // Let's look at just the field definition:
+ // optional string foo = 1;
+ // ^ ^^ ^^ ^ ^^^
+ // a bc de f ghi
+ // We have the following locations:
+ // span path represents
+ // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
+ // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
+ // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
+ // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
+ // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
+ //
+ // Notes:
+ // - A location may refer to a repeated field itself (i.e. not to any
+ // particular index within it). This is used whenever a set of elements are
+ // logically enclosed in a single code segment. For example, an entire
+ // extend block (possibly containing multiple extension definitions) will
+ // have an outer location whose path refers to the "extensions" repeated
+ // field without an index.
+ // - Multiple locations may have the same path. This happens when a single
+ // logical declaration is spread out across multiple places. The most
+ // obvious example is the "extend" block again -- there may be multiple
+ // extend blocks in the same scope, each of which will have the same path.
+ // - A location's span is not always a subset of its parent's span. For
+ // example, the "extendee" of an extension declaration appears at the
+ // beginning of the "extend" block and is shared by all extensions within
+ // the block.
+ // - Just because a location's span is a subset of some other location's span
+ // does not mean that it is a descendent. For example, a "group" defines
+ // both a type and a field in a single declaration. Thus, the locations
+ // corresponding to the type and field and their components will overlap.
+ // - Code which tries to interpret locations should probably be designed to
+ // ignore those that it doesn't understand, as more types of locations could
+ // be recorded in the future.
+ Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} }
+func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) }
+func (*SourceCodeInfo) ProtoMessage() {}
+func (*SourceCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} }
+
+func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location {
+ if m != nil {
+ return m.Location
+ }
+ return nil
+}
+
+type SourceCodeInfo_Location struct {
+ // Identifies which part of the FileDescriptorProto was defined at this
+ // location.
+ //
+ // Each element is a field number or an index. They form a path from
+ // the root FileDescriptorProto to the place where the definition. For
+ // example, this path:
+ // [ 4, 3, 2, 7, 1 ]
+ // refers to:
+ // file.message_type(3) // 4, 3
+ // .field(7) // 2, 7
+ // .name() // 1
+ // This is because FileDescriptorProto.message_type has field number 4:
+ // repeated DescriptorProto message_type = 4;
+ // and DescriptorProto.field has field number 2:
+ // repeated FieldDescriptorProto field = 2;
+ // and FieldDescriptorProto.name has field number 1:
+ // optional string name = 1;
+ //
+ // Thus, the above path gives the location of a field name. If we removed
+ // the last element:
+ // [ 4, 3, 2, 7 ]
+ // this path refers to the whole field declaration (from the beginning
+ // of the label to the terminating semicolon).
+ Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
+ // Always has exactly three or four elements: start line, start column,
+ // end line (optional, otherwise assumed same as start line), end column.
+ // These are packed into a single field for efficiency. Note that line
+ // and column numbers are zero-based -- typically you will want to add
+ // 1 to each before displaying to a user.
+ Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"`
+ // If this SourceCodeInfo represents a complete declaration, these are any
+ // comments appearing before and after the declaration which appear to be
+ // attached to the declaration.
+ //
+ // A series of line comments appearing on consecutive lines, with no other
+ // tokens appearing on those lines, will be treated as a single comment.
+ //
+ // leading_detached_comments will keep paragraphs of comments that appear
+ // before (but not connected to) the current element. Each paragraph,
+ // separated by empty lines, will be one comment element in the repeated
+ // field.
+ //
+ // Only the comment content is provided; comment markers (e.g. //) are
+ // stripped out. For block comments, leading whitespace and an asterisk
+ // will be stripped from the beginning of each line other than the first.
+ // Newlines are included in the output.
+ //
+ // Examples:
+ //
+ // optional int32 foo = 1; // Comment attached to foo.
+ // // Comment attached to bar.
+ // optional int32 bar = 2;
+ //
+ // optional string baz = 3;
+ // // Comment attached to baz.
+ // // Another line attached to baz.
+ //
+ // // Comment attached to qux.
+ // //
+ // // Another line attached to qux.
+ // optional double qux = 4;
+ //
+ // // Detached comment for corge. This is not leading or trailing comments
+ // // to qux or corge because there are blank lines separating it from
+ // // both.
+ //
+ // // Detached comment for corge paragraph 2.
+ //
+ // optional string corge = 5;
+ // /* Block comment attached
+ // * to corge. Leading asterisks
+ // * will be removed. */
+ // /* Block comment attached to
+ // * grault. */
+ // optional int32 grault = 6;
+ //
+ // // ignored detached comments.
+ LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"`
+ TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"`
+ LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} }
+func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) }
+func (*SourceCodeInfo_Location) ProtoMessage() {}
+func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18, 0} }
+
+func (m *SourceCodeInfo_Location) GetPath() []int32 {
+ if m != nil {
+ return m.Path
+ }
+ return nil
+}
+
+func (m *SourceCodeInfo_Location) GetSpan() []int32 {
+ if m != nil {
+ return m.Span
+ }
+ return nil
+}
+
+func (m *SourceCodeInfo_Location) GetLeadingComments() string {
+ if m != nil && m.LeadingComments != nil {
+ return *m.LeadingComments
+ }
+ return ""
+}
+
+func (m *SourceCodeInfo_Location) GetTrailingComments() string {
+ if m != nil && m.TrailingComments != nil {
+ return *m.TrailingComments
+ }
+ return ""
+}
+
+func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string {
+ if m != nil {
+ return m.LeadingDetachedComments
+ }
+ return nil
+}
+
+// Describes the relationship between generated code and its original source
+// file. A GeneratedCodeInfo message is associated with only one generated
+// source file, but may contain references to different source .proto files.
+type GeneratedCodeInfo struct {
+ // An Annotation connects some span of text in generated code to an element
+ // of its generating .proto file.
+ Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} }
+func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) }
+func (*GeneratedCodeInfo) ProtoMessage() {}
+func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} }
+
+func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation {
+ if m != nil {
+ return m.Annotation
+ }
+ return nil
+}
+
+type GeneratedCodeInfo_Annotation struct {
+ // Identifies the element in the original source .proto file. This field
+ // is formatted the same as SourceCodeInfo.Location.path.
+ Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
+ // Identifies the filesystem path to the original source .proto.
+ SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"`
+ // Identifies the starting offset in bytes in the generated code
+ // that relates to the identified object.
+ Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"`
+ // Identifies the ending offset in bytes in the generated code that
+ // relates to the identified offset. The end offset should be one past
+ // the last relevant byte (so the length of the text = end - begin).
+ End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} }
+func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) }
+func (*GeneratedCodeInfo_Annotation) ProtoMessage() {}
+func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{19, 0}
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 {
+ if m != nil {
+ return m.Path
+ }
+ return nil
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string {
+ if m != nil && m.SourceFile != nil {
+ return *m.SourceFile
+ }
+ return ""
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 {
+ if m != nil && m.Begin != nil {
+ return *m.Begin
+ }
+ return 0
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet")
+ proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto")
+ proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto")
+ proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange")
+ proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange")
+ proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto")
+ proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto")
+ proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto")
+ proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto")
+ proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto")
+ proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto")
+ proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions")
+ proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions")
+ proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions")
+ proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions")
+ proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions")
+ proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions")
+ proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions")
+ proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions")
+ proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption")
+ proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart")
+ proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo")
+ proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location")
+ proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo")
+ proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation")
+ proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value)
+ proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value)
+ proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value)
+ proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value)
+ proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value)
+ proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value)
+}
+
+func init() { proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 2460 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0x5b, 0x6f, 0xdb, 0xc8,
+ 0x15, 0x5e, 0x5d, 0x2d, 0x1d, 0xc9, 0xf2, 0x78, 0xec, 0x4d, 0x18, 0xef, 0x25, 0x8e, 0xf6, 0x12,
+ 0x6f, 0xd2, 0xc8, 0x0b, 0xe7, 0xb2, 0x59, 0xa7, 0x48, 0x21, 0x4b, 0x8c, 0x57, 0xa9, 0x2c, 0xa9,
+ 0x94, 0xdc, 0x4d, 0xf6, 0x85, 0x18, 0x93, 0x23, 0x99, 0x09, 0x45, 0x72, 0x49, 0x2a, 0x89, 0xf7,
+ 0x29, 0x40, 0x9f, 0x0a, 0xf4, 0x07, 0x14, 0x45, 0xd1, 0x87, 0x7d, 0x59, 0xa0, 0x3f, 0xa0, 0xcf,
+ 0xfd, 0x05, 0x05, 0xf6, 0xb9, 0x2f, 0x45, 0x51, 0xa0, 0xfd, 0x07, 0x7d, 0x2d, 0x66, 0x86, 0xa4,
+ 0x48, 0x5d, 0x12, 0x77, 0x81, 0xec, 0x3e, 0xd9, 0x73, 0xce, 0x77, 0x0e, 0xcf, 0x9c, 0xf9, 0x66,
+ 0xce, 0x99, 0x11, 0x6c, 0x8f, 0x6c, 0x7b, 0x64, 0xd2, 0x5d, 0xc7, 0xb5, 0x7d, 0xfb, 0x64, 0x32,
+ 0xdc, 0xd5, 0xa9, 0xa7, 0xb9, 0x86, 0xe3, 0xdb, 0x6e, 0x8d, 0xcb, 0xf0, 0x9a, 0x40, 0xd4, 0x42,
+ 0x44, 0xf5, 0x08, 0xd6, 0x1f, 0x18, 0x26, 0x6d, 0x46, 0xc0, 0x3e, 0xf5, 0xf1, 0x5d, 0xc8, 0x0e,
+ 0x0d, 0x93, 0x4a, 0xa9, 0xed, 0xcc, 0x4e, 0x69, 0xef, 0xc3, 0xda, 0x8c, 0x51, 0x2d, 0x69, 0xd1,
+ 0x63, 0x62, 0x85, 0x5b, 0x54, 0xff, 0x95, 0x85, 0x8d, 0x05, 0x5a, 0x8c, 0x21, 0x6b, 0x91, 0x31,
+ 0xf3, 0x98, 0xda, 0x29, 0x2a, 0xfc, 0x7f, 0x2c, 0xc1, 0x8a, 0x43, 0xb4, 0xa7, 0x64, 0x44, 0xa5,
+ 0x34, 0x17, 0x87, 0x43, 0xfc, 0x3e, 0x80, 0x4e, 0x1d, 0x6a, 0xe9, 0xd4, 0xd2, 0xce, 0xa4, 0xcc,
+ 0x76, 0x66, 0xa7, 0xa8, 0xc4, 0x24, 0xf8, 0x3a, 0xac, 0x3b, 0x93, 0x13, 0xd3, 0xd0, 0xd4, 0x18,
+ 0x0c, 0xb6, 0x33, 0x3b, 0x39, 0x05, 0x09, 0x45, 0x73, 0x0a, 0xbe, 0x0a, 0x6b, 0xcf, 0x29, 0x79,
+ 0x1a, 0x87, 0x96, 0x38, 0xb4, 0xc2, 0xc4, 0x31, 0x60, 0x03, 0xca, 0x63, 0xea, 0x79, 0x64, 0x44,
+ 0x55, 0xff, 0xcc, 0xa1, 0x52, 0x96, 0xcf, 0x7e, 0x7b, 0x6e, 0xf6, 0xb3, 0x33, 0x2f, 0x05, 0x56,
+ 0x83, 0x33, 0x87, 0xe2, 0x3a, 0x14, 0xa9, 0x35, 0x19, 0x0b, 0x0f, 0xb9, 0x25, 0xf9, 0x93, 0xad,
+ 0xc9, 0x78, 0xd6, 0x4b, 0x81, 0x99, 0x05, 0x2e, 0x56, 0x3c, 0xea, 0x3e, 0x33, 0x34, 0x2a, 0xe5,
+ 0xb9, 0x83, 0xab, 0x73, 0x0e, 0xfa, 0x42, 0x3f, 0xeb, 0x23, 0xb4, 0xc3, 0x0d, 0x28, 0xd2, 0x17,
+ 0x3e, 0xb5, 0x3c, 0xc3, 0xb6, 0xa4, 0x15, 0xee, 0xe4, 0xa3, 0x05, 0xab, 0x48, 0x4d, 0x7d, 0xd6,
+ 0xc5, 0xd4, 0x0e, 0xdf, 0x81, 0x15, 0xdb, 0xf1, 0x0d, 0xdb, 0xf2, 0xa4, 0xc2, 0x76, 0x6a, 0xa7,
+ 0xb4, 0xf7, 0xee, 0x42, 0x22, 0x74, 0x05, 0x46, 0x09, 0xc1, 0xb8, 0x05, 0xc8, 0xb3, 0x27, 0xae,
+ 0x46, 0x55, 0xcd, 0xd6, 0xa9, 0x6a, 0x58, 0x43, 0x5b, 0x2a, 0x72, 0x07, 0x97, 0xe7, 0x27, 0xc2,
+ 0x81, 0x0d, 0x5b, 0xa7, 0x2d, 0x6b, 0x68, 0x2b, 0x15, 0x2f, 0x31, 0xc6, 0x17, 0x20, 0xef, 0x9d,
+ 0x59, 0x3e, 0x79, 0x21, 0x95, 0x39, 0x43, 0x82, 0x51, 0xf5, 0xbf, 0x39, 0x58, 0x3b, 0x0f, 0xc5,
+ 0xee, 0x41, 0x6e, 0xc8, 0x66, 0x29, 0xa5, 0xff, 0x9f, 0x1c, 0x08, 0x9b, 0x64, 0x12, 0xf3, 0x3f,
+ 0x30, 0x89, 0x75, 0x28, 0x59, 0xd4, 0xf3, 0xa9, 0x2e, 0x18, 0x91, 0x39, 0x27, 0xa7, 0x40, 0x18,
+ 0xcd, 0x53, 0x2a, 0xfb, 0x83, 0x28, 0xf5, 0x08, 0xd6, 0xa2, 0x90, 0x54, 0x97, 0x58, 0xa3, 0x90,
+ 0x9b, 0xbb, 0xaf, 0x8b, 0xa4, 0x26, 0x87, 0x76, 0x0a, 0x33, 0x53, 0x2a, 0x34, 0x31, 0xc6, 0x4d,
+ 0x00, 0xdb, 0xa2, 0xf6, 0x50, 0xd5, 0xa9, 0x66, 0x4a, 0x85, 0x25, 0x59, 0xea, 0x32, 0xc8, 0x5c,
+ 0x96, 0x6c, 0x21, 0xd5, 0x4c, 0xfc, 0xf9, 0x94, 0x6a, 0x2b, 0x4b, 0x98, 0x72, 0x24, 0x36, 0xd9,
+ 0x1c, 0xdb, 0x8e, 0xa1, 0xe2, 0x52, 0xc6, 0x7b, 0xaa, 0x07, 0x33, 0x2b, 0xf2, 0x20, 0x6a, 0xaf,
+ 0x9d, 0x99, 0x12, 0x98, 0x89, 0x89, 0xad, 0xba, 0xf1, 0x21, 0xfe, 0x00, 0x22, 0x81, 0xca, 0x69,
+ 0x05, 0xfc, 0x14, 0x2a, 0x87, 0xc2, 0x0e, 0x19, 0xd3, 0xad, 0xbb, 0x50, 0x49, 0xa6, 0x07, 0x6f,
+ 0x42, 0xce, 0xf3, 0x89, 0xeb, 0x73, 0x16, 0xe6, 0x14, 0x31, 0xc0, 0x08, 0x32, 0xd4, 0xd2, 0xf9,
+ 0x29, 0x97, 0x53, 0xd8, 0xbf, 0x5b, 0x9f, 0xc1, 0x6a, 0xe2, 0xf3, 0xe7, 0x35, 0xac, 0xfe, 0x3e,
+ 0x0f, 0x9b, 0x8b, 0x38, 0xb7, 0x90, 0xfe, 0x17, 0x20, 0x6f, 0x4d, 0xc6, 0x27, 0xd4, 0x95, 0x32,
+ 0xdc, 0x43, 0x30, 0xc2, 0x75, 0xc8, 0x99, 0xe4, 0x84, 0x9a, 0x52, 0x76, 0x3b, 0xb5, 0x53, 0xd9,
+ 0xbb, 0x7e, 0x2e, 0x56, 0xd7, 0xda, 0xcc, 0x44, 0x11, 0x96, 0xf8, 0x3e, 0x64, 0x83, 0x23, 0x8e,
+ 0x79, 0xb8, 0x76, 0x3e, 0x0f, 0x8c, 0x8b, 0x0a, 0xb7, 0xc3, 0xef, 0x40, 0x91, 0xfd, 0x15, 0xb9,
+ 0xcd, 0xf3, 0x98, 0x0b, 0x4c, 0xc0, 0xf2, 0x8a, 0xb7, 0xa0, 0xc0, 0x69, 0xa6, 0xd3, 0xb0, 0x34,
+ 0x44, 0x63, 0xb6, 0x30, 0x3a, 0x1d, 0x92, 0x89, 0xe9, 0xab, 0xcf, 0x88, 0x39, 0xa1, 0x9c, 0x30,
+ 0x45, 0xa5, 0x1c, 0x08, 0x7f, 0xcd, 0x64, 0xf8, 0x32, 0x94, 0x04, 0x2b, 0x0d, 0x4b, 0xa7, 0x2f,
+ 0xf8, 0xe9, 0x93, 0x53, 0x04, 0x51, 0x5b, 0x4c, 0xc2, 0x3e, 0xff, 0xc4, 0xb3, 0xad, 0x70, 0x69,
+ 0xf9, 0x27, 0x98, 0x80, 0x7f, 0xfe, 0xb3, 0xd9, 0x83, 0xef, 0xbd, 0xc5, 0xd3, 0x9b, 0xe5, 0x62,
+ 0xf5, 0x2f, 0x69, 0xc8, 0xf2, 0xfd, 0xb6, 0x06, 0xa5, 0xc1, 0xe3, 0x9e, 0xac, 0x36, 0xbb, 0xc7,
+ 0x07, 0x6d, 0x19, 0xa5, 0x70, 0x05, 0x80, 0x0b, 0x1e, 0xb4, 0xbb, 0xf5, 0x01, 0x4a, 0x47, 0xe3,
+ 0x56, 0x67, 0x70, 0xe7, 0x16, 0xca, 0x44, 0x06, 0xc7, 0x42, 0x90, 0x8d, 0x03, 0x6e, 0xee, 0xa1,
+ 0x1c, 0x46, 0x50, 0x16, 0x0e, 0x5a, 0x8f, 0xe4, 0xe6, 0x9d, 0x5b, 0x28, 0x9f, 0x94, 0xdc, 0xdc,
+ 0x43, 0x2b, 0x78, 0x15, 0x8a, 0x5c, 0x72, 0xd0, 0xed, 0xb6, 0x51, 0x21, 0xf2, 0xd9, 0x1f, 0x28,
+ 0xad, 0xce, 0x21, 0x2a, 0x46, 0x3e, 0x0f, 0x95, 0xee, 0x71, 0x0f, 0x41, 0xe4, 0xe1, 0x48, 0xee,
+ 0xf7, 0xeb, 0x87, 0x32, 0x2a, 0x45, 0x88, 0x83, 0xc7, 0x03, 0xb9, 0x8f, 0xca, 0x89, 0xb0, 0x6e,
+ 0xee, 0xa1, 0xd5, 0xe8, 0x13, 0x72, 0xe7, 0xf8, 0x08, 0x55, 0xf0, 0x3a, 0xac, 0x8a, 0x4f, 0x84,
+ 0x41, 0xac, 0xcd, 0x88, 0xee, 0xdc, 0x42, 0x68, 0x1a, 0x88, 0xf0, 0xb2, 0x9e, 0x10, 0xdc, 0xb9,
+ 0x85, 0x70, 0xb5, 0x01, 0x39, 0xce, 0x2e, 0x8c, 0xa1, 0xd2, 0xae, 0x1f, 0xc8, 0x6d, 0xb5, 0xdb,
+ 0x1b, 0xb4, 0xba, 0x9d, 0x7a, 0x1b, 0xa5, 0xa6, 0x32, 0x45, 0xfe, 0xd5, 0x71, 0x4b, 0x91, 0x9b,
+ 0x28, 0x1d, 0x97, 0xf5, 0xe4, 0xfa, 0x40, 0x6e, 0xa2, 0x4c, 0x55, 0x83, 0xcd, 0x45, 0xe7, 0xcc,
+ 0xc2, 0x9d, 0x11, 0x5b, 0xe2, 0xf4, 0x92, 0x25, 0xe6, 0xbe, 0xe6, 0x96, 0xf8, 0xdb, 0x14, 0x6c,
+ 0x2c, 0x38, 0x6b, 0x17, 0x7e, 0xe4, 0x17, 0x90, 0x13, 0x14, 0x15, 0xd5, 0xe7, 0x93, 0x85, 0x87,
+ 0x36, 0x27, 0xec, 0x5c, 0x05, 0xe2, 0x76, 0xf1, 0x0a, 0x9c, 0x59, 0x52, 0x81, 0x99, 0x8b, 0xb9,
+ 0x20, 0x7f, 0x93, 0x02, 0x69, 0x99, 0xef, 0xd7, 0x1c, 0x14, 0xe9, 0xc4, 0x41, 0x71, 0x6f, 0x36,
+ 0x80, 0x2b, 0xcb, 0xe7, 0x30, 0x17, 0xc5, 0x77, 0x29, 0xb8, 0xb0, 0xb8, 0x51, 0x59, 0x18, 0xc3,
+ 0x7d, 0xc8, 0x8f, 0xa9, 0x7f, 0x6a, 0x87, 0xc5, 0xfa, 0xe3, 0x05, 0x25, 0x80, 0xa9, 0x67, 0x73,
+ 0x15, 0x58, 0xc5, 0x6b, 0x48, 0x66, 0x59, 0xb7, 0x21, 0xa2, 0x99, 0x8b, 0xf4, 0xb7, 0x69, 0x78,
+ 0x7b, 0xa1, 0xf3, 0x85, 0x81, 0xbe, 0x07, 0x60, 0x58, 0xce, 0xc4, 0x17, 0x05, 0x59, 0x9c, 0x4f,
+ 0x45, 0x2e, 0xe1, 0x7b, 0x9f, 0x9d, 0x3d, 0x13, 0x3f, 0xd2, 0x67, 0xb8, 0x1e, 0x84, 0x88, 0x03,
+ 0xee, 0x4e, 0x03, 0xcd, 0xf2, 0x40, 0xdf, 0x5f, 0x32, 0xd3, 0xb9, 0x5a, 0xf7, 0x29, 0x20, 0xcd,
+ 0x34, 0xa8, 0xe5, 0xab, 0x9e, 0xef, 0x52, 0x32, 0x36, 0xac, 0x11, 0x3f, 0x80, 0x0b, 0xfb, 0xb9,
+ 0x21, 0x31, 0x3d, 0xaa, 0xac, 0x09, 0x75, 0x3f, 0xd4, 0x32, 0x0b, 0x5e, 0x65, 0xdc, 0x98, 0x45,
+ 0x3e, 0x61, 0x21, 0xd4, 0x91, 0x45, 0xf5, 0xef, 0x2b, 0x50, 0x8a, 0xb5, 0x75, 0xf8, 0x0a, 0x94,
+ 0x9f, 0x90, 0x67, 0x44, 0x0d, 0x5b, 0x75, 0x91, 0x89, 0x12, 0x93, 0xf5, 0x82, 0x76, 0xfd, 0x53,
+ 0xd8, 0xe4, 0x10, 0x7b, 0xe2, 0x53, 0x57, 0xd5, 0x4c, 0xe2, 0x79, 0x3c, 0x69, 0x05, 0x0e, 0xc5,
+ 0x4c, 0xd7, 0x65, 0xaa, 0x46, 0xa8, 0xc1, 0xb7, 0x61, 0x83, 0x5b, 0x8c, 0x27, 0xa6, 0x6f, 0x38,
+ 0x26, 0x55, 0xd9, 0xe5, 0xc1, 0xe3, 0x07, 0x71, 0x14, 0xd9, 0x3a, 0x43, 0x1c, 0x05, 0x00, 0x16,
+ 0x91, 0x87, 0x9b, 0xf0, 0x1e, 0x37, 0x1b, 0x51, 0x8b, 0xba, 0xc4, 0xa7, 0x2a, 0xfd, 0x7a, 0x42,
+ 0x4c, 0x4f, 0x25, 0x96, 0xae, 0x9e, 0x12, 0xef, 0x54, 0xda, 0x64, 0x0e, 0x0e, 0xd2, 0x52, 0x4a,
+ 0xb9, 0xc4, 0x80, 0x87, 0x01, 0x4e, 0xe6, 0xb0, 0xba, 0xa5, 0x7f, 0x41, 0xbc, 0x53, 0xbc, 0x0f,
+ 0x17, 0xb8, 0x17, 0xcf, 0x77, 0x0d, 0x6b, 0xa4, 0x6a, 0xa7, 0x54, 0x7b, 0xaa, 0x4e, 0xfc, 0xe1,
+ 0x5d, 0xe9, 0x9d, 0xf8, 0xf7, 0x79, 0x84, 0x7d, 0x8e, 0x69, 0x30, 0xc8, 0xb1, 0x3f, 0xbc, 0x8b,
+ 0xfb, 0x50, 0x66, 0x8b, 0x31, 0x36, 0xbe, 0xa1, 0xea, 0xd0, 0x76, 0x79, 0x65, 0xa9, 0x2c, 0xd8,
+ 0xd9, 0xb1, 0x0c, 0xd6, 0xba, 0x81, 0xc1, 0x91, 0xad, 0xd3, 0xfd, 0x5c, 0xbf, 0x27, 0xcb, 0x4d,
+ 0xa5, 0x14, 0x7a, 0x79, 0x60, 0xbb, 0x8c, 0x50, 0x23, 0x3b, 0x4a, 0x70, 0x49, 0x10, 0x6a, 0x64,
+ 0x87, 0xe9, 0xbd, 0x0d, 0x1b, 0x9a, 0x26, 0xe6, 0x6c, 0x68, 0x6a, 0xd0, 0xe2, 0x7b, 0x12, 0x4a,
+ 0x24, 0x4b, 0xd3, 0x0e, 0x05, 0x20, 0xe0, 0xb8, 0x87, 0x3f, 0x87, 0xb7, 0xa7, 0xc9, 0x8a, 0x1b,
+ 0xae, 0xcf, 0xcd, 0x72, 0xd6, 0xf4, 0x36, 0x6c, 0x38, 0x67, 0xf3, 0x86, 0x38, 0xf1, 0x45, 0xe7,
+ 0x6c, 0xd6, 0xec, 0x23, 0x7e, 0x6d, 0x73, 0xa9, 0x46, 0x7c, 0xaa, 0x4b, 0x17, 0xe3, 0xe8, 0x98,
+ 0x02, 0xef, 0x02, 0xd2, 0x34, 0x95, 0x5a, 0xe4, 0xc4, 0xa4, 0x2a, 0x71, 0xa9, 0x45, 0x3c, 0xe9,
+ 0x72, 0x1c, 0x5c, 0xd1, 0x34, 0x99, 0x6b, 0xeb, 0x5c, 0x89, 0xaf, 0xc1, 0xba, 0x7d, 0xf2, 0x44,
+ 0x13, 0xcc, 0x52, 0x1d, 0x97, 0x0e, 0x8d, 0x17, 0xd2, 0x87, 0x3c, 0x4d, 0x6b, 0x4c, 0xc1, 0x79,
+ 0xd5, 0xe3, 0x62, 0xfc, 0x09, 0x20, 0xcd, 0x3b, 0x25, 0xae, 0xc3, 0x4b, 0xbb, 0xe7, 0x10, 0x8d,
+ 0x4a, 0x1f, 0x09, 0xa8, 0x90, 0x77, 0x42, 0x31, 0x63, 0xb6, 0xf7, 0xdc, 0x18, 0xfa, 0xa1, 0xc7,
+ 0xab, 0x82, 0xd9, 0x5c, 0x16, 0x78, 0xdb, 0x01, 0xe4, 0x9c, 0x3a, 0xc9, 0x0f, 0xef, 0x70, 0x58,
+ 0xc5, 0x39, 0x75, 0xe2, 0xdf, 0x7d, 0x04, 0x9b, 0x13, 0xcb, 0xb0, 0x7c, 0xea, 0x3a, 0x2e, 0x65,
+ 0xed, 0xbe, 0xd8, 0xb3, 0xd2, 0xbf, 0x57, 0x96, 0x34, 0xec, 0xc7, 0x71, 0xb4, 0xa0, 0x8a, 0xb2,
+ 0x31, 0x99, 0x17, 0x56, 0xf7, 0xa1, 0x1c, 0x67, 0x10, 0x2e, 0x82, 0xe0, 0x10, 0x4a, 0xb1, 0x6a,
+ 0xdc, 0xe8, 0x36, 0x59, 0x1d, 0xfd, 0x4a, 0x46, 0x69, 0x56, 0xcf, 0xdb, 0xad, 0x81, 0xac, 0x2a,
+ 0xc7, 0x9d, 0x41, 0xeb, 0x48, 0x46, 0x99, 0x6b, 0xc5, 0xc2, 0x7f, 0x56, 0xd0, 0xcb, 0x97, 0x2f,
+ 0x5f, 0xa6, 0x1f, 0x66, 0x0b, 0x1f, 0xa3, 0xab, 0xd5, 0xef, 0xd3, 0x50, 0x49, 0x76, 0xd2, 0xf8,
+ 0xe7, 0x70, 0x31, 0xbc, 0xf6, 0x7a, 0xd4, 0x57, 0x9f, 0x1b, 0x2e, 0xa7, 0xf6, 0x98, 0x88, 0x5e,
+ 0x34, 0x5a, 0x95, 0xcd, 0x00, 0xd5, 0xa7, 0xfe, 0x97, 0x86, 0xcb, 0x88, 0x3b, 0x26, 0x3e, 0x6e,
+ 0xc3, 0x65, 0xcb, 0x56, 0x3d, 0x9f, 0x58, 0x3a, 0x71, 0x75, 0x75, 0xfa, 0xe0, 0xa0, 0x12, 0x4d,
+ 0xa3, 0x9e, 0x67, 0x8b, 0x92, 0x12, 0x79, 0x79, 0xd7, 0xb2, 0xfb, 0x01, 0x78, 0x7a, 0xd6, 0xd6,
+ 0x03, 0xe8, 0x0c, 0x83, 0x32, 0xcb, 0x18, 0xf4, 0x0e, 0x14, 0xc7, 0xc4, 0x51, 0xa9, 0xe5, 0xbb,
+ 0x67, 0xbc, 0xff, 0x2b, 0x28, 0x85, 0x31, 0x71, 0x64, 0x36, 0x7e, 0x73, 0x2b, 0x91, 0xcc, 0x66,
+ 0x01, 0x15, 0x1f, 0x66, 0x0b, 0x45, 0x04, 0xd5, 0x7f, 0x66, 0xa0, 0x1c, 0xef, 0x07, 0x59, 0x7b,
+ 0xad, 0xf1, 0xb3, 0x3f, 0xc5, 0x4f, 0x87, 0x0f, 0x5e, 0xd9, 0x3d, 0xd6, 0x1a, 0xac, 0x28, 0xec,
+ 0xe7, 0x45, 0x97, 0xa6, 0x08, 0x4b, 0x56, 0x90, 0xd9, 0x79, 0x40, 0x45, 0xef, 0x5f, 0x50, 0x82,
+ 0x11, 0x3e, 0x84, 0xfc, 0x13, 0x8f, 0xfb, 0xce, 0x73, 0xdf, 0x1f, 0xbe, 0xda, 0xf7, 0xc3, 0x3e,
+ 0x77, 0x5e, 0x7c, 0xd8, 0x57, 0x3b, 0x5d, 0xe5, 0xa8, 0xde, 0x56, 0x02, 0x73, 0x7c, 0x09, 0xb2,
+ 0x26, 0xf9, 0xe6, 0x2c, 0x59, 0x3e, 0xb8, 0xe8, 0xbc, 0x8b, 0x70, 0x09, 0xb2, 0xcf, 0x29, 0x79,
+ 0x9a, 0x3c, 0xb4, 0xb9, 0xe8, 0x0d, 0x6e, 0x86, 0x5d, 0xc8, 0xf1, 0x7c, 0x61, 0x80, 0x20, 0x63,
+ 0xe8, 0x2d, 0x5c, 0x80, 0x6c, 0xa3, 0xab, 0xb0, 0x0d, 0x81, 0xa0, 0x2c, 0xa4, 0x6a, 0xaf, 0x25,
+ 0x37, 0x64, 0x94, 0xae, 0xde, 0x86, 0xbc, 0x48, 0x02, 0xdb, 0x2c, 0x51, 0x1a, 0xd0, 0x5b, 0xc1,
+ 0x30, 0xf0, 0x91, 0x0a, 0xb5, 0xc7, 0x47, 0x07, 0xb2, 0x82, 0xd2, 0xc9, 0xa5, 0xce, 0xa2, 0x5c,
+ 0xd5, 0x83, 0x72, 0xbc, 0x21, 0xfc, 0x51, 0x58, 0x56, 0xfd, 0x6b, 0x0a, 0x4a, 0xb1, 0x06, 0x8f,
+ 0xb5, 0x16, 0xc4, 0x34, 0xed, 0xe7, 0x2a, 0x31, 0x0d, 0xe2, 0x05, 0xd4, 0x00, 0x2e, 0xaa, 0x33,
+ 0xc9, 0x79, 0x97, 0xee, 0x47, 0xda, 0x22, 0x39, 0x94, 0xaf, 0xfe, 0x29, 0x05, 0x68, 0xb6, 0x45,
+ 0x9c, 0x09, 0x33, 0xf5, 0x53, 0x86, 0x59, 0xfd, 0x63, 0x0a, 0x2a, 0xc9, 0xbe, 0x70, 0x26, 0xbc,
+ 0x2b, 0x3f, 0x69, 0x78, 0xff, 0x48, 0xc3, 0x6a, 0xa2, 0x1b, 0x3c, 0x6f, 0x74, 0x5f, 0xc3, 0xba,
+ 0xa1, 0xd3, 0xb1, 0x63, 0xfb, 0xd4, 0xd2, 0xce, 0x54, 0x93, 0x3e, 0xa3, 0xa6, 0x54, 0xe5, 0x87,
+ 0xc6, 0xee, 0xab, 0xfb, 0xcd, 0x5a, 0x6b, 0x6a, 0xd7, 0x66, 0x66, 0xfb, 0x1b, 0xad, 0xa6, 0x7c,
+ 0xd4, 0xeb, 0x0e, 0xe4, 0x4e, 0xe3, 0xb1, 0x7a, 0xdc, 0xf9, 0x65, 0xa7, 0xfb, 0x65, 0x47, 0x41,
+ 0xc6, 0x0c, 0xec, 0x0d, 0x6e, 0xfb, 0x1e, 0xa0, 0xd9, 0xa0, 0xf0, 0x45, 0x58, 0x14, 0x16, 0x7a,
+ 0x0b, 0x6f, 0xc0, 0x5a, 0xa7, 0xab, 0xf6, 0x5b, 0x4d, 0x59, 0x95, 0x1f, 0x3c, 0x90, 0x1b, 0x83,
+ 0xbe, 0xb8, 0x80, 0x47, 0xe8, 0x41, 0x62, 0x83, 0x57, 0xff, 0x90, 0x81, 0x8d, 0x05, 0x91, 0xe0,
+ 0x7a, 0xd0, 0xfb, 0x8b, 0xeb, 0xc8, 0x8d, 0xf3, 0x44, 0x5f, 0x63, 0xdd, 0x45, 0x8f, 0xb8, 0x7e,
+ 0x70, 0x55, 0xf8, 0x04, 0x58, 0x96, 0x2c, 0xdf, 0x18, 0x1a, 0xd4, 0x0d, 0xde, 0x2b, 0xc4, 0x85,
+ 0x60, 0x6d, 0x2a, 0x17, 0x4f, 0x16, 0x3f, 0x03, 0xec, 0xd8, 0x9e, 0xe1, 0x1b, 0xcf, 0xa8, 0x6a,
+ 0x58, 0xe1, 0xe3, 0x06, 0xbb, 0x20, 0x64, 0x15, 0x14, 0x6a, 0x5a, 0x96, 0x1f, 0xa1, 0x2d, 0x3a,
+ 0x22, 0x33, 0x68, 0x76, 0x98, 0x67, 0x14, 0x14, 0x6a, 0x22, 0xf4, 0x15, 0x28, 0xeb, 0xf6, 0x84,
+ 0xb5, 0x5b, 0x02, 0xc7, 0x6a, 0x47, 0x4a, 0x29, 0x09, 0x59, 0x04, 0x09, 0xfa, 0xe1, 0xe9, 0xab,
+ 0x4a, 0x59, 0x29, 0x09, 0x99, 0x80, 0x5c, 0x85, 0x35, 0x32, 0x1a, 0xb9, 0xcc, 0x79, 0xe8, 0x48,
+ 0x74, 0xf8, 0x95, 0x48, 0xcc, 0x81, 0x5b, 0x0f, 0xa1, 0x10, 0xe6, 0x81, 0x95, 0x6a, 0x96, 0x09,
+ 0xd5, 0x11, 0x6f, 0x5b, 0xe9, 0x9d, 0xa2, 0x52, 0xb0, 0x42, 0xe5, 0x15, 0x28, 0x1b, 0x9e, 0x3a,
+ 0x7d, 0x64, 0x4d, 0x6f, 0xa7, 0x77, 0x0a, 0x4a, 0xc9, 0xf0, 0xa2, 0x57, 0xb5, 0xea, 0x77, 0x69,
+ 0xa8, 0x24, 0x1f, 0x89, 0x71, 0x13, 0x0a, 0xa6, 0xad, 0x11, 0x4e, 0x2d, 0xf1, 0x0b, 0xc5, 0xce,
+ 0x6b, 0xde, 0x95, 0x6b, 0xed, 0x00, 0xaf, 0x44, 0x96, 0x5b, 0x7f, 0x4b, 0x41, 0x21, 0x14, 0xe3,
+ 0x0b, 0x90, 0x75, 0x88, 0x7f, 0xca, 0xdd, 0xe5, 0x0e, 0xd2, 0x28, 0xa5, 0xf0, 0x31, 0x93, 0x7b,
+ 0x0e, 0xb1, 0x38, 0x05, 0x02, 0x39, 0x1b, 0xb3, 0x75, 0x35, 0x29, 0xd1, 0xf9, 0xf5, 0xc1, 0x1e,
+ 0x8f, 0xa9, 0xe5, 0x7b, 0xe1, 0xba, 0x06, 0xf2, 0x46, 0x20, 0xc6, 0xd7, 0x61, 0xdd, 0x77, 0x89,
+ 0x61, 0x26, 0xb0, 0x59, 0x8e, 0x45, 0xa1, 0x22, 0x02, 0xef, 0xc3, 0xa5, 0xd0, 0xaf, 0x4e, 0x7d,
+ 0xa2, 0x9d, 0x52, 0x7d, 0x6a, 0x94, 0xe7, 0x2f, 0x90, 0x17, 0x03, 0x40, 0x33, 0xd0, 0x87, 0xb6,
+ 0xd5, 0xef, 0x53, 0xb0, 0x1e, 0x5e, 0x78, 0xf4, 0x28, 0x59, 0x47, 0x00, 0xc4, 0xb2, 0x6c, 0x3f,
+ 0x9e, 0xae, 0x79, 0x2a, 0xcf, 0xd9, 0xd5, 0xea, 0x91, 0x91, 0x12, 0x73, 0xb0, 0x35, 0x06, 0x98,
+ 0x6a, 0x96, 0xa6, 0xed, 0x32, 0x94, 0x82, 0x5f, 0x00, 0xf8, 0xcf, 0x48, 0xe2, 0x8a, 0x0c, 0x42,
+ 0xc4, 0x6e, 0x46, 0x78, 0x13, 0x72, 0x27, 0x74, 0x64, 0x58, 0xc1, 0xbb, 0xa4, 0x18, 0x84, 0xaf,
+ 0x9d, 0xd9, 0xe8, 0xb5, 0xf3, 0xe0, 0x77, 0x29, 0xd8, 0xd0, 0xec, 0xf1, 0x6c, 0xbc, 0x07, 0x68,
+ 0xe6, 0x9e, 0xee, 0x7d, 0x91, 0xfa, 0xea, 0xfe, 0xc8, 0xf0, 0x4f, 0x27, 0x27, 0x35, 0xcd, 0x1e,
+ 0xef, 0x8e, 0x6c, 0x93, 0x58, 0xa3, 0xe9, 0xef, 0x60, 0xfc, 0x1f, 0xed, 0xc6, 0x88, 0x5a, 0x37,
+ 0x46, 0x76, 0xec, 0x57, 0xb1, 0x7b, 0xd3, 0x7f, 0xbf, 0x4d, 0x67, 0x0e, 0x7b, 0x07, 0x7f, 0x4e,
+ 0x6f, 0x1d, 0x8a, 0x6f, 0xf5, 0xc2, 0xdc, 0x28, 0x74, 0x68, 0x52, 0x8d, 0xcd, 0xf7, 0x7f, 0x01,
+ 0x00, 0x00, 0xff, 0xff, 0x8e, 0x54, 0xe7, 0xef, 0x60, 0x1b, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any.go b/vendor/github.com/golang/protobuf/ptypes/any.go
new file mode 100644
index 0000000..89e07ae
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/any.go
@@ -0,0 +1,136 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package ptypes
+
+// This file implements functions to marshal proto.Message to/from
+// google.protobuf.Any message.
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+
+ "github.com/golang/protobuf/proto"
+ "github.com/golang/protobuf/ptypes/any"
+)
+
+const googleApis = "type.googleapis.com/"
+
+// AnyMessageName returns the name of the message contained in a google.protobuf.Any message.
+//
+// Note that regular type assertions should be done using the Is
+// function. AnyMessageName is provided for less common use cases like filtering a
+// sequence of Any messages based on a set of allowed message type names.
+func AnyMessageName(any *any.Any) (string, error) {
+ slash := strings.LastIndex(any.TypeUrl, "/")
+ if slash < 0 {
+ return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl)
+ }
+ return any.TypeUrl[slash+1:], nil
+}
+
+// MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any.
+func MarshalAny(pb proto.Message) (*any.Any, error) {
+ value, err := proto.Marshal(pb)
+ if err != nil {
+ return nil, err
+ }
+ return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil
+}
+
+// DynamicAny is a value that can be passed to UnmarshalAny to automatically
+// allocate a proto.Message for the type specified in a google.protobuf.Any
+// message. The allocated message is stored in the embedded proto.Message.
+//
+// Example:
+//
+// var x ptypes.DynamicAny
+// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... }
+// fmt.Printf("unmarshaled message: %v", x.Message)
+type DynamicAny struct {
+ proto.Message
+}
+
+// Empty returns a new proto.Message of the type specified in a
+// google.protobuf.Any message. It returns an error if corresponding message
+// type isn't linked in.
+func Empty(any *any.Any) (proto.Message, error) {
+ aname, err := AnyMessageName(any)
+ if err != nil {
+ return nil, err
+ }
+
+ t := proto.MessageType(aname)
+ if t == nil {
+ return nil, fmt.Errorf("any: message type %q isn't linked in", aname)
+ }
+ return reflect.New(t.Elem()).Interface().(proto.Message), nil
+}
+
+// UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any
+// message and places the decoded result in pb. It returns an error if type of
+// contents of Any message does not match type of pb message.
+//
+// pb can be a proto.Message, or a *DynamicAny.
+func UnmarshalAny(any *any.Any, pb proto.Message) error {
+ if d, ok := pb.(*DynamicAny); ok {
+ if d.Message == nil {
+ var err error
+ d.Message, err = Empty(any)
+ if err != nil {
+ return err
+ }
+ }
+ return UnmarshalAny(any, d.Message)
+ }
+
+ aname, err := AnyMessageName(any)
+ if err != nil {
+ return err
+ }
+
+ mname := proto.MessageName(pb)
+ if aname != mname {
+ return fmt.Errorf("mismatched message type: got %q want %q", aname, mname)
+ }
+ return proto.Unmarshal(any.Value, pb)
+}
+
+// Is returns true if any value contains a given message type.
+func Is(any *any.Any, pb proto.Message) bool {
+ aname, err := AnyMessageName(any)
+ if err != nil {
+ return false
+ }
+
+ return aname == proto.MessageName(pb)
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go
new file mode 100644
index 0000000..1fbaa44
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go
@@ -0,0 +1,168 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: github.com/golang/protobuf/ptypes/any/any.proto
+
+/*
+Package any is a generated protocol buffer package.
+
+It is generated from these files:
+ github.com/golang/protobuf/ptypes/any/any.proto
+
+It has these top-level messages:
+ Any
+*/
+package any
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// `Any` contains an arbitrary serialized protocol buffer message along with a
+// URL that describes the type of the serialized message.
+//
+// Protobuf library provides support to pack/unpack Any values in the form
+// of utility functions or additional generated methods of the Any type.
+//
+// Example 1: Pack and unpack a message in C++.
+//
+// Foo foo = ...;
+// Any any;
+// any.PackFrom(foo);
+// ...
+// if (any.UnpackTo(&foo)) {
+// ...
+// }
+//
+// Example 2: Pack and unpack a message in Java.
+//
+// Foo foo = ...;
+// Any any = Any.pack(foo);
+// ...
+// if (any.is(Foo.class)) {
+// foo = any.unpack(Foo.class);
+// }
+//
+// Example 3: Pack and unpack a message in Python.
+//
+// foo = Foo(...)
+// any = Any()
+// any.Pack(foo)
+// ...
+// if any.Is(Foo.DESCRIPTOR):
+// any.Unpack(foo)
+// ...
+//
+// The pack methods provided by protobuf library will by default use
+// 'type.googleapis.com/full.type.name' as the type URL and the unpack
+// methods only use the fully qualified type name after the last '/'
+// in the type URL, for example "foo.bar.com/x/y.z" will yield type
+// name "y.z".
+//
+//
+// JSON
+// ====
+// The JSON representation of an `Any` value uses the regular
+// representation of the deserialized, embedded message, with an
+// additional field `@type` which contains the type URL. Example:
+//
+// package google.profile;
+// message Person {
+// string first_name = 1;
+// string last_name = 2;
+// }
+//
+// {
+// "@type": "type.googleapis.com/google.profile.Person",
+// "firstName": <string>,
+// "lastName": <string>
+// }
+//
+// If the embedded message type is well-known and has a custom JSON
+// representation, that representation will be embedded adding a field
+// `value` which holds the custom JSON in addition to the `@type`
+// field. Example (for message [google.protobuf.Duration][]):
+//
+// {
+// "@type": "type.googleapis.com/google.protobuf.Duration",
+// "value": "1.212s"
+// }
+//
+type Any struct {
+ // A URL/resource name whose content describes the type of the
+ // serialized protocol buffer message.
+ //
+ // For URLs which use the scheme `http`, `https`, or no scheme, the
+ // following restrictions and interpretations apply:
+ //
+ // * If no scheme is provided, `https` is assumed.
+ // * The last segment of the URL's path must represent the fully
+ // qualified name of the type (as in `path/google.protobuf.Duration`).
+ // The name should be in a canonical form (e.g., leading "." is
+ // not accepted).
+ // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ // value in binary format, or produce an error.
+ // * Applications are allowed to cache lookup results based on the
+ // URL, or have them precompiled into a binary to avoid any
+ // lookup. Therefore, binary compatibility needs to be preserved
+ // on changes to types. (Use versioned type names to manage
+ // breaking changes.)
+ //
+ // Schemes other than `http`, `https` (or the empty scheme) might be
+ // used with implementation specific semantics.
+ //
+ TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl" json:"type_url,omitempty"`
+ // Must be a valid serialized protocol buffer of the above specified type.
+ Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *Any) Reset() { *m = Any{} }
+func (m *Any) String() string { return proto.CompactTextString(m) }
+func (*Any) ProtoMessage() {}
+func (*Any) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*Any) XXX_WellKnownType() string { return "Any" }
+
+func (m *Any) GetTypeUrl() string {
+ if m != nil {
+ return m.TypeUrl
+ }
+ return ""
+}
+
+func (m *Any) GetValue() []byte {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Any)(nil), "google.protobuf.Any")
+}
+
+func init() { proto.RegisterFile("github.com/golang/protobuf/ptypes/any/any.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 184 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x4f, 0xcf, 0x2c, 0xc9,
+ 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x2f, 0x28,
+ 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x28, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0xcc,
+ 0xab, 0x04, 0x61, 0x3d, 0xb0, 0xb8, 0x10, 0x7f, 0x7a, 0x7e, 0x7e, 0x7a, 0x4e, 0xaa, 0x1e, 0x4c,
+ 0x95, 0x92, 0x19, 0x17, 0xb3, 0x63, 0x5e, 0xa5, 0x90, 0x24, 0x17, 0x07, 0x48, 0x79, 0x7c, 0x69,
+ 0x51, 0x8e, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x67, 0x10, 0x3b, 0x88, 0x1f, 0x5a, 0x94, 0x23, 0x24,
+ 0xc2, 0xc5, 0x5a, 0x96, 0x98, 0x53, 0x9a, 0x2a, 0xc1, 0xa4, 0xc0, 0xa8, 0xc1, 0x13, 0x04, 0xe1,
+ 0x38, 0xe5, 0x73, 0x09, 0x27, 0xe7, 0xe7, 0xea, 0xa1, 0x19, 0xe7, 0xc4, 0xe1, 0x98, 0x57, 0x19,
+ 0x00, 0xe2, 0x04, 0x30, 0x46, 0xa9, 0x12, 0xe5, 0xb8, 0x45, 0x4c, 0xcc, 0xee, 0x01, 0x4e, 0xab,
+ 0x98, 0xe4, 0xdc, 0x21, 0x46, 0x05, 0x40, 0x95, 0xe8, 0x85, 0xa7, 0xe6, 0xe4, 0x78, 0xe7, 0xe5,
+ 0x97, 0xe7, 0x85, 0x80, 0x94, 0x26, 0xb1, 0x81, 0xf5, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff,
+ 0x45, 0x1f, 0x1a, 0xf2, 0xf3, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.proto b/vendor/github.com/golang/protobuf/ptypes/any/any.proto
new file mode 100644
index 0000000..9bd3f50
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/any/any.proto
@@ -0,0 +1,139 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option go_package = "github.com/golang/protobuf/ptypes/any";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "AnyProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+
+// `Any` contains an arbitrary serialized protocol buffer message along with a
+// URL that describes the type of the serialized message.
+//
+// Protobuf library provides support to pack/unpack Any values in the form
+// of utility functions or additional generated methods of the Any type.
+//
+// Example 1: Pack and unpack a message in C++.
+//
+// Foo foo = ...;
+// Any any;
+// any.PackFrom(foo);
+// ...
+// if (any.UnpackTo(&foo)) {
+// ...
+// }
+//
+// Example 2: Pack and unpack a message in Java.
+//
+// Foo foo = ...;
+// Any any = Any.pack(foo);
+// ...
+// if (any.is(Foo.class)) {
+// foo = any.unpack(Foo.class);
+// }
+//
+// Example 3: Pack and unpack a message in Python.
+//
+// foo = Foo(...)
+// any = Any()
+// any.Pack(foo)
+// ...
+// if any.Is(Foo.DESCRIPTOR):
+// any.Unpack(foo)
+// ...
+//
+// The pack methods provided by protobuf library will by default use
+// 'type.googleapis.com/full.type.name' as the type URL and the unpack
+// methods only use the fully qualified type name after the last '/'
+// in the type URL, for example "foo.bar.com/x/y.z" will yield type
+// name "y.z".
+//
+//
+// JSON
+// ====
+// The JSON representation of an `Any` value uses the regular
+// representation of the deserialized, embedded message, with an
+// additional field `@type` which contains the type URL. Example:
+//
+// package google.profile;
+// message Person {
+// string first_name = 1;
+// string last_name = 2;
+// }
+//
+// {
+// "@type": "type.googleapis.com/google.profile.Person",
+// "firstName": <string>,
+// "lastName": <string>
+// }
+//
+// If the embedded message type is well-known and has a custom JSON
+// representation, that representation will be embedded adding a field
+// `value` which holds the custom JSON in addition to the `@type`
+// field. Example (for message [google.protobuf.Duration][]):
+//
+// {
+// "@type": "type.googleapis.com/google.protobuf.Duration",
+// "value": "1.212s"
+// }
+//
+message Any {
+ // A URL/resource name whose content describes the type of the
+ // serialized protocol buffer message.
+ //
+ // For URLs which use the scheme `http`, `https`, or no scheme, the
+ // following restrictions and interpretations apply:
+ //
+ // * If no scheme is provided, `https` is assumed.
+ // * The last segment of the URL's path must represent the fully
+ // qualified name of the type (as in `path/google.protobuf.Duration`).
+ // The name should be in a canonical form (e.g., leading "." is
+ // not accepted).
+ // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ // value in binary format, or produce an error.
+ // * Applications are allowed to cache lookup results based on the
+ // URL, or have them precompiled into a binary to avoid any
+ // lookup. Therefore, binary compatibility needs to be preserved
+ // on changes to types. (Use versioned type names to manage
+ // breaking changes.)
+ //
+ // Schemes other than `http`, `https` (or the empty scheme) might be
+ // used with implementation specific semantics.
+ //
+ string type_url = 1;
+
+ // Must be a valid serialized protocol buffer of the above specified type.
+ bytes value = 2;
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/doc.go b/vendor/github.com/golang/protobuf/ptypes/doc.go
new file mode 100644
index 0000000..c0d595d
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/doc.go
@@ -0,0 +1,35 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+/*
+Package ptypes contains code for interacting with well-known types.
+*/
+package ptypes
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration.go b/vendor/github.com/golang/protobuf/ptypes/duration.go
new file mode 100644
index 0000000..65cb0f8
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/duration.go
@@ -0,0 +1,102 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package ptypes
+
+// This file implements conversions between google.protobuf.Duration
+// and time.Duration.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+
+ durpb "github.com/golang/protobuf/ptypes/duration"
+)
+
+const (
+ // Range of a durpb.Duration in seconds, as specified in
+ // google/protobuf/duration.proto. This is about 10,000 years in seconds.
+ maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
+ minSeconds = -maxSeconds
+)
+
+// validateDuration determines whether the durpb.Duration is valid according to the
+// definition in google/protobuf/duration.proto. A valid durpb.Duration
+// may still be too large to fit into a time.Duration (the range of durpb.Duration
+// is about 10,000 years, and the range of time.Duration is about 290).
+func validateDuration(d *durpb.Duration) error {
+ if d == nil {
+ return errors.New("duration: nil Duration")
+ }
+ if d.Seconds < minSeconds || d.Seconds > maxSeconds {
+ return fmt.Errorf("duration: %v: seconds out of range", d)
+ }
+ if d.Nanos <= -1e9 || d.Nanos >= 1e9 {
+ return fmt.Errorf("duration: %v: nanos out of range", d)
+ }
+ // Seconds and Nanos must have the same sign, unless d.Nanos is zero.
+ if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) {
+ return fmt.Errorf("duration: %v: seconds and nanos have different signs", d)
+ }
+ return nil
+}
+
+// Duration converts a durpb.Duration to a time.Duration. Duration
+// returns an error if the durpb.Duration is invalid or is too large to be
+// represented in a time.Duration.
+func Duration(p *durpb.Duration) (time.Duration, error) {
+ if err := validateDuration(p); err != nil {
+ return 0, err
+ }
+ d := time.Duration(p.Seconds) * time.Second
+ if int64(d/time.Second) != p.Seconds {
+ return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p)
+ }
+ if p.Nanos != 0 {
+ d += time.Duration(p.Nanos)
+ if (d < 0) != (p.Nanos < 0) {
+ return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p)
+ }
+ }
+ return d, nil
+}
+
+// DurationProto converts a time.Duration to a durpb.Duration.
+func DurationProto(d time.Duration) *durpb.Duration {
+ nanos := d.Nanoseconds()
+ secs := nanos / 1e9
+ nanos -= secs * 1e9
+ return &durpb.Duration{
+ Seconds: secs,
+ Nanos: int32(nanos),
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go
new file mode 100644
index 0000000..fe3350b
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go
@@ -0,0 +1,146 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: github.com/golang/protobuf/ptypes/duration/duration.proto
+
+/*
+Package duration is a generated protocol buffer package.
+
+It is generated from these files:
+ github.com/golang/protobuf/ptypes/duration/duration.proto
+
+It has these top-level messages:
+ Duration
+*/
+package duration
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// A Duration represents a signed, fixed-length span of time represented
+// as a count of seconds and fractions of seconds at nanosecond
+// resolution. It is independent of any calendar and concepts like "day"
+// or "month". It is related to Timestamp in that the difference between
+// two Timestamp values is a Duration and it can be added or subtracted
+// from a Timestamp. Range is approximately +-10,000 years.
+//
+// # Examples
+//
+// Example 1: Compute Duration from two Timestamps in pseudo code.
+//
+// Timestamp start = ...;
+// Timestamp end = ...;
+// Duration duration = ...;
+//
+// duration.seconds = end.seconds - start.seconds;
+// duration.nanos = end.nanos - start.nanos;
+//
+// if (duration.seconds < 0 && duration.nanos > 0) {
+// duration.seconds += 1;
+// duration.nanos -= 1000000000;
+// } else if (durations.seconds > 0 && duration.nanos < 0) {
+// duration.seconds -= 1;
+// duration.nanos += 1000000000;
+// }
+//
+// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
+//
+// Timestamp start = ...;
+// Duration duration = ...;
+// Timestamp end = ...;
+//
+// end.seconds = start.seconds + duration.seconds;
+// end.nanos = start.nanos + duration.nanos;
+//
+// if (end.nanos < 0) {
+// end.seconds -= 1;
+// end.nanos += 1000000000;
+// } else if (end.nanos >= 1000000000) {
+// end.seconds += 1;
+// end.nanos -= 1000000000;
+// }
+//
+// Example 3: Compute Duration from datetime.timedelta in Python.
+//
+// td = datetime.timedelta(days=3, minutes=10)
+// duration = Duration()
+// duration.FromTimedelta(td)
+//
+// # JSON Mapping
+//
+// In JSON format, the Duration type is encoded as a string rather than an
+// object, where the string ends in the suffix "s" (indicating seconds) and
+// is preceded by the number of seconds, with nanoseconds expressed as
+// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
+// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
+// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
+// microsecond should be expressed in JSON format as "3.000001s".
+//
+//
+type Duration struct {
+ // Signed seconds of the span of time. Must be from -315,576,000,000
+ // to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"`
+ // Signed fractions of a second at nanosecond resolution of the span
+ // of time. Durations less than one second are represented with a 0
+ // `seconds` field and a positive or negative `nanos` field. For durations
+ // of one second or more, a non-zero value for the `nanos` field must be
+ // of the same sign as the `seconds` field. Must be from -999,999,999
+ // to +999,999,999 inclusive.
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"`
+}
+
+func (m *Duration) Reset() { *m = Duration{} }
+func (m *Duration) String() string { return proto.CompactTextString(m) }
+func (*Duration) ProtoMessage() {}
+func (*Duration) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*Duration) XXX_WellKnownType() string { return "Duration" }
+
+func (m *Duration) GetSeconds() int64 {
+ if m != nil {
+ return m.Seconds
+ }
+ return 0
+}
+
+func (m *Duration) GetNanos() int32 {
+ if m != nil {
+ return m.Nanos
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*Duration)(nil), "google.protobuf.Duration")
+}
+
+func init() {
+ proto.RegisterFile("github.com/golang/protobuf/ptypes/duration/duration.proto", fileDescriptor0)
+}
+
+var fileDescriptor0 = []byte{
+ // 189 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x4c, 0xcf, 0x2c, 0xc9,
+ 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x2f, 0x28,
+ 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x28, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x29,
+ 0x2d, 0x4a, 0x2c, 0xc9, 0xcc, 0xcf, 0x83, 0x33, 0xf4, 0xc0, 0x2a, 0x84, 0xf8, 0xd3, 0xf3, 0xf3,
+ 0xd3, 0x73, 0x52, 0xf5, 0x60, 0xea, 0x95, 0xac, 0xb8, 0x38, 0x5c, 0xa0, 0x4a, 0x84, 0x24, 0xb8,
+ 0xd8, 0x8b, 0x53, 0x93, 0xf3, 0xf3, 0x52, 0x8a, 0x25, 0x18, 0x15, 0x18, 0x35, 0x98, 0x83, 0x60,
+ 0x5c, 0x21, 0x11, 0x2e, 0xd6, 0xbc, 0xc4, 0xbc, 0xfc, 0x62, 0x09, 0x26, 0x05, 0x46, 0x0d, 0xd6,
+ 0x20, 0x08, 0xc7, 0xa9, 0x86, 0x4b, 0x38, 0x39, 0x3f, 0x57, 0x0f, 0xcd, 0x48, 0x27, 0x5e, 0x98,
+ 0x81, 0x01, 0x20, 0x91, 0x00, 0xc6, 0x28, 0x2d, 0xe2, 0xdd, 0xfb, 0x83, 0x91, 0x71, 0x11, 0x13,
+ 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xb9, 0x01, 0x50, 0xa5, 0x7a, 0xe1, 0xa9,
+ 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x2d, 0x49, 0x6c, 0x60, 0x33, 0x8c, 0x01,
+ 0x01, 0x00, 0x00, 0xff, 0xff, 0x45, 0x5a, 0x81, 0x3d, 0x0e, 0x01, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto b/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto
new file mode 100644
index 0000000..975fce4
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto
@@ -0,0 +1,117 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
+option go_package = "github.com/golang/protobuf/ptypes/duration";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "DurationProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+
+// A Duration represents a signed, fixed-length span of time represented
+// as a count of seconds and fractions of seconds at nanosecond
+// resolution. It is independent of any calendar and concepts like "day"
+// or "month". It is related to Timestamp in that the difference between
+// two Timestamp values is a Duration and it can be added or subtracted
+// from a Timestamp. Range is approximately +-10,000 years.
+//
+// # Examples
+//
+// Example 1: Compute Duration from two Timestamps in pseudo code.
+//
+// Timestamp start = ...;
+// Timestamp end = ...;
+// Duration duration = ...;
+//
+// duration.seconds = end.seconds - start.seconds;
+// duration.nanos = end.nanos - start.nanos;
+//
+// if (duration.seconds < 0 && duration.nanos > 0) {
+// duration.seconds += 1;
+// duration.nanos -= 1000000000;
+// } else if (durations.seconds > 0 && duration.nanos < 0) {
+// duration.seconds -= 1;
+// duration.nanos += 1000000000;
+// }
+//
+// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
+//
+// Timestamp start = ...;
+// Duration duration = ...;
+// Timestamp end = ...;
+//
+// end.seconds = start.seconds + duration.seconds;
+// end.nanos = start.nanos + duration.nanos;
+//
+// if (end.nanos < 0) {
+// end.seconds -= 1;
+// end.nanos += 1000000000;
+// } else if (end.nanos >= 1000000000) {
+// end.seconds += 1;
+// end.nanos -= 1000000000;
+// }
+//
+// Example 3: Compute Duration from datetime.timedelta in Python.
+//
+// td = datetime.timedelta(days=3, minutes=10)
+// duration = Duration()
+// duration.FromTimedelta(td)
+//
+// # JSON Mapping
+//
+// In JSON format, the Duration type is encoded as a string rather than an
+// object, where the string ends in the suffix "s" (indicating seconds) and
+// is preceded by the number of seconds, with nanoseconds expressed as
+// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
+// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
+// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
+// microsecond should be expressed in JSON format as "3.000001s".
+//
+//
+message Duration {
+
+ // Signed seconds of the span of time. Must be from -315,576,000,000
+ // to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
+ int64 seconds = 1;
+
+ // Signed fractions of a second at nanosecond resolution of the span
+ // of time. Durations less than one second are represented with a 0
+ // `seconds` field and a positive or negative `nanos` field. For durations
+ // of one second or more, a non-zero value for the `nanos` field must be
+ // of the same sign as the `seconds` field. Must be from -999,999,999
+ // to +999,999,999 inclusive.
+ int32 nanos = 2;
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go
new file mode 100644
index 0000000..ae15941
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go
@@ -0,0 +1,68 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: github.com/golang/protobuf/ptypes/empty/empty.proto
+
+/*
+Package empty is a generated protocol buffer package.
+
+It is generated from these files:
+ github.com/golang/protobuf/ptypes/empty/empty.proto
+
+It has these top-level messages:
+ Empty
+*/
+package empty
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// A generic empty message that you can re-use to avoid defining duplicated
+// empty messages in your APIs. A typical example is to use it as the request
+// or the response type of an API method. For instance:
+//
+// service Foo {
+// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+// }
+//
+// The JSON representation for `Empty` is empty JSON object `{}`.
+type Empty struct {
+}
+
+func (m *Empty) Reset() { *m = Empty{} }
+func (m *Empty) String() string { return proto.CompactTextString(m) }
+func (*Empty) ProtoMessage() {}
+func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*Empty) XXX_WellKnownType() string { return "Empty" }
+
+func init() {
+ proto.RegisterType((*Empty)(nil), "google.protobuf.Empty")
+}
+
+func init() {
+ proto.RegisterFile("github.com/golang/protobuf/ptypes/empty/empty.proto", fileDescriptor0)
+}
+
+var fileDescriptor0 = []byte{
+ // 147 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x4e, 0xcf, 0x2c, 0xc9,
+ 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x2f, 0x28,
+ 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x28, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0xcd,
+ 0x2d, 0x28, 0xa9, 0x84, 0x90, 0x7a, 0x60, 0x39, 0x21, 0xfe, 0xf4, 0xfc, 0xfc, 0xf4, 0x9c, 0x54,
+ 0x3d, 0x98, 0x4a, 0x25, 0x76, 0x2e, 0x56, 0x57, 0x90, 0xbc, 0x53, 0x19, 0x97, 0x70, 0x72, 0x7e,
+ 0xae, 0x1e, 0x9a, 0xbc, 0x13, 0x17, 0x58, 0x36, 0x00, 0xc4, 0x0d, 0x60, 0x8c, 0x52, 0x27, 0xd2,
+ 0xce, 0x1f, 0x8c, 0x8c, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c, 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x4c,
+ 0x0c, 0x80, 0xaa, 0xd3, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce, 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0xa9,
+ 0x4f, 0x62, 0x03, 0x1b, 0x60, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x6e, 0x8e, 0x0a, 0x06, 0xcf,
+ 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/empty/empty.proto b/vendor/github.com/golang/protobuf/ptypes/empty/empty.proto
new file mode 100644
index 0000000..03cacd2
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/empty/empty.proto
@@ -0,0 +1,52 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option go_package = "github.com/golang/protobuf/ptypes/empty";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "EmptyProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+option cc_enable_arenas = true;
+
+// A generic empty message that you can re-use to avoid defining duplicated
+// empty messages in your APIs. A typical example is to use it as the request
+// or the response type of an API method. For instance:
+//
+// service Foo {
+// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+// }
+//
+// The JSON representation for `Empty` is empty JSON object `{}`.
+message Empty {}
diff --git a/vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go b/vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go
new file mode 100644
index 0000000..35a8ec5
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go
@@ -0,0 +1,382 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: github.com/golang/protobuf/ptypes/struct/struct.proto
+
+/*
+Package structpb is a generated protocol buffer package.
+
+It is generated from these files:
+ github.com/golang/protobuf/ptypes/struct/struct.proto
+
+It has these top-level messages:
+ Struct
+ Value
+ ListValue
+*/
+package structpb
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// `NullValue` is a singleton enumeration to represent the null value for the
+// `Value` type union.
+//
+// The JSON representation for `NullValue` is JSON `null`.
+type NullValue int32
+
+const (
+ // Null value.
+ NullValue_NULL_VALUE NullValue = 0
+)
+
+var NullValue_name = map[int32]string{
+ 0: "NULL_VALUE",
+}
+var NullValue_value = map[string]int32{
+ "NULL_VALUE": 0,
+}
+
+func (x NullValue) String() string {
+ return proto.EnumName(NullValue_name, int32(x))
+}
+func (NullValue) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (NullValue) XXX_WellKnownType() string { return "NullValue" }
+
+// `Struct` represents a structured data value, consisting of fields
+// which map to dynamically typed values. In some languages, `Struct`
+// might be supported by a native representation. For example, in
+// scripting languages like JS a struct is represented as an
+// object. The details of that representation are described together
+// with the proto support for the language.
+//
+// The JSON representation for `Struct` is JSON object.
+type Struct struct {
+ // Unordered map of dynamically typed values.
+ Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+}
+
+func (m *Struct) Reset() { *m = Struct{} }
+func (m *Struct) String() string { return proto.CompactTextString(m) }
+func (*Struct) ProtoMessage() {}
+func (*Struct) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*Struct) XXX_WellKnownType() string { return "Struct" }
+
+func (m *Struct) GetFields() map[string]*Value {
+ if m != nil {
+ return m.Fields
+ }
+ return nil
+}
+
+// `Value` represents a dynamically typed value which can be either
+// null, a number, a string, a boolean, a recursive struct value, or a
+// list of values. A producer of value is expected to set one of that
+// variants, absence of any variant indicates an error.
+//
+// The JSON representation for `Value` is JSON value.
+type Value struct {
+ // The kind of value.
+ //
+ // Types that are valid to be assigned to Kind:
+ // *Value_NullValue
+ // *Value_NumberValue
+ // *Value_StringValue
+ // *Value_BoolValue
+ // *Value_StructValue
+ // *Value_ListValue
+ Kind isValue_Kind `protobuf_oneof:"kind"`
+}
+
+func (m *Value) Reset() { *m = Value{} }
+func (m *Value) String() string { return proto.CompactTextString(m) }
+func (*Value) ProtoMessage() {}
+func (*Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+func (*Value) XXX_WellKnownType() string { return "Value" }
+
+type isValue_Kind interface {
+ isValue_Kind()
+}
+
+type Value_NullValue struct {
+ NullValue NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,enum=google.protobuf.NullValue,oneof"`
+}
+type Value_NumberValue struct {
+ NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,oneof"`
+}
+type Value_StringValue struct {
+ StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,oneof"`
+}
+type Value_BoolValue struct {
+ BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,oneof"`
+}
+type Value_StructValue struct {
+ StructValue *Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,oneof"`
+}
+type Value_ListValue struct {
+ ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,oneof"`
+}
+
+func (*Value_NullValue) isValue_Kind() {}
+func (*Value_NumberValue) isValue_Kind() {}
+func (*Value_StringValue) isValue_Kind() {}
+func (*Value_BoolValue) isValue_Kind() {}
+func (*Value_StructValue) isValue_Kind() {}
+func (*Value_ListValue) isValue_Kind() {}
+
+func (m *Value) GetKind() isValue_Kind {
+ if m != nil {
+ return m.Kind
+ }
+ return nil
+}
+
+func (m *Value) GetNullValue() NullValue {
+ if x, ok := m.GetKind().(*Value_NullValue); ok {
+ return x.NullValue
+ }
+ return NullValue_NULL_VALUE
+}
+
+func (m *Value) GetNumberValue() float64 {
+ if x, ok := m.GetKind().(*Value_NumberValue); ok {
+ return x.NumberValue
+ }
+ return 0
+}
+
+func (m *Value) GetStringValue() string {
+ if x, ok := m.GetKind().(*Value_StringValue); ok {
+ return x.StringValue
+ }
+ return ""
+}
+
+func (m *Value) GetBoolValue() bool {
+ if x, ok := m.GetKind().(*Value_BoolValue); ok {
+ return x.BoolValue
+ }
+ return false
+}
+
+func (m *Value) GetStructValue() *Struct {
+ if x, ok := m.GetKind().(*Value_StructValue); ok {
+ return x.StructValue
+ }
+ return nil
+}
+
+func (m *Value) GetListValue() *ListValue {
+ if x, ok := m.GetKind().(*Value_ListValue); ok {
+ return x.ListValue
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Value) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Value_OneofMarshaler, _Value_OneofUnmarshaler, _Value_OneofSizer, []interface{}{
+ (*Value_NullValue)(nil),
+ (*Value_NumberValue)(nil),
+ (*Value_StringValue)(nil),
+ (*Value_BoolValue)(nil),
+ (*Value_StructValue)(nil),
+ (*Value_ListValue)(nil),
+ }
+}
+
+func _Value_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Value)
+ // kind
+ switch x := m.Kind.(type) {
+ case *Value_NullValue:
+ b.EncodeVarint(1<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.NullValue))
+ case *Value_NumberValue:
+ b.EncodeVarint(2<<3 | proto.WireFixed64)
+ b.EncodeFixed64(math.Float64bits(x.NumberValue))
+ case *Value_StringValue:
+ b.EncodeVarint(3<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.StringValue)
+ case *Value_BoolValue:
+ t := uint64(0)
+ if x.BoolValue {
+ t = 1
+ }
+ b.EncodeVarint(4<<3 | proto.WireVarint)
+ b.EncodeVarint(t)
+ case *Value_StructValue:
+ b.EncodeVarint(5<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.StructValue); err != nil {
+ return err
+ }
+ case *Value_ListValue:
+ b.EncodeVarint(6<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.ListValue); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("Value.Kind has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Value_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Value)
+ switch tag {
+ case 1: // kind.null_value
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Kind = &Value_NullValue{NullValue(x)}
+ return true, err
+ case 2: // kind.number_value
+ if wire != proto.WireFixed64 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed64()
+ m.Kind = &Value_NumberValue{math.Float64frombits(x)}
+ return true, err
+ case 3: // kind.string_value
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Kind = &Value_StringValue{x}
+ return true, err
+ case 4: // kind.bool_value
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Kind = &Value_BoolValue{x != 0}
+ return true, err
+ case 5: // kind.struct_value
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Struct)
+ err := b.DecodeMessage(msg)
+ m.Kind = &Value_StructValue{msg}
+ return true, err
+ case 6: // kind.list_value
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(ListValue)
+ err := b.DecodeMessage(msg)
+ m.Kind = &Value_ListValue{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Value_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Value)
+ // kind
+ switch x := m.Kind.(type) {
+ case *Value_NullValue:
+ n += proto.SizeVarint(1<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.NullValue))
+ case *Value_NumberValue:
+ n += proto.SizeVarint(2<<3 | proto.WireFixed64)
+ n += 8
+ case *Value_StringValue:
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.StringValue)))
+ n += len(x.StringValue)
+ case *Value_BoolValue:
+ n += proto.SizeVarint(4<<3 | proto.WireVarint)
+ n += 1
+ case *Value_StructValue:
+ s := proto.Size(x.StructValue)
+ n += proto.SizeVarint(5<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Value_ListValue:
+ s := proto.Size(x.ListValue)
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// `ListValue` is a wrapper around a repeated field of values.
+//
+// The JSON representation for `ListValue` is JSON array.
+type ListValue struct {
+ // Repeated field of dynamically typed values.
+ Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"`
+}
+
+func (m *ListValue) Reset() { *m = ListValue{} }
+func (m *ListValue) String() string { return proto.CompactTextString(m) }
+func (*ListValue) ProtoMessage() {}
+func (*ListValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+func (*ListValue) XXX_WellKnownType() string { return "ListValue" }
+
+func (m *ListValue) GetValues() []*Value {
+ if m != nil {
+ return m.Values
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Struct)(nil), "google.protobuf.Struct")
+ proto.RegisterType((*Value)(nil), "google.protobuf.Value")
+ proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue")
+ proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value)
+}
+
+func init() {
+ proto.RegisterFile("github.com/golang/protobuf/ptypes/struct/struct.proto", fileDescriptor0)
+}
+
+var fileDescriptor0 = []byte{
+ // 417 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0x41, 0x8b, 0xd3, 0x40,
+ 0x14, 0x80, 0x3b, 0xc9, 0x36, 0x98, 0x17, 0x59, 0x97, 0x11, 0xb4, 0xac, 0xa0, 0xa1, 0x7b, 0x09,
+ 0x22, 0x09, 0x56, 0x04, 0x31, 0x5e, 0x0c, 0xac, 0xbb, 0x60, 0x58, 0x62, 0x74, 0x57, 0xf0, 0x52,
+ 0x9a, 0x34, 0x8d, 0xa1, 0xd3, 0x99, 0x90, 0xcc, 0x28, 0x3d, 0xfa, 0x2f, 0x3c, 0x7b, 0xf4, 0xe8,
+ 0xaf, 0xf3, 0x28, 0x33, 0x93, 0x44, 0x69, 0x29, 0x78, 0x9a, 0xbe, 0x37, 0xdf, 0xfb, 0xe6, 0xbd,
+ 0xd7, 0xc0, 0xf3, 0xb2, 0xe2, 0x9f, 0x45, 0xe6, 0xe7, 0x6c, 0x13, 0x94, 0x8c, 0x2c, 0x68, 0x19,
+ 0xd4, 0x0d, 0xe3, 0x2c, 0x13, 0xab, 0xa0, 0xe6, 0xdb, 0xba, 0x68, 0x83, 0x96, 0x37, 0x22, 0xe7,
+ 0xdd, 0xe1, 0xab, 0x5b, 0x7c, 0xa7, 0x64, 0xac, 0x24, 0x85, 0xdf, 0xb3, 0xd3, 0xef, 0x08, 0xac,
+ 0xf7, 0x8a, 0xc0, 0x21, 0x58, 0xab, 0xaa, 0x20, 0xcb, 0x76, 0x82, 0x5c, 0xd3, 0x73, 0x66, 0x67,
+ 0xfe, 0x0e, 0xec, 0x6b, 0xd0, 0x7f, 0xa3, 0xa8, 0x73, 0xca, 0x9b, 0x6d, 0xda, 0x95, 0x9c, 0xbe,
+ 0x03, 0xe7, 0x9f, 0x34, 0x3e, 0x01, 0x73, 0x5d, 0x6c, 0x27, 0xc8, 0x45, 0x9e, 0x9d, 0xca, 0x9f,
+ 0xf8, 0x09, 0x8c, 0xbf, 0x2c, 0x88, 0x28, 0x26, 0x86, 0x8b, 0x3c, 0x67, 0x76, 0x6f, 0x4f, 0x7e,
+ 0x23, 0x6f, 0x53, 0x0d, 0xbd, 0x34, 0x5e, 0xa0, 0xe9, 0x2f, 0x03, 0xc6, 0x2a, 0x89, 0x43, 0x00,
+ 0x2a, 0x08, 0x99, 0x6b, 0x81, 0x94, 0x1e, 0xcf, 0x4e, 0xf7, 0x04, 0x57, 0x82, 0x10, 0xc5, 0x5f,
+ 0x8e, 0x52, 0x9b, 0xf6, 0x01, 0x3e, 0x83, 0xdb, 0x54, 0x6c, 0xb2, 0xa2, 0x99, 0xff, 0x7d, 0x1f,
+ 0x5d, 0x8e, 0x52, 0x47, 0x67, 0x07, 0xa8, 0xe5, 0x4d, 0x45, 0xcb, 0x0e, 0x32, 0x65, 0xe3, 0x12,
+ 0xd2, 0x59, 0x0d, 0x3d, 0x02, 0xc8, 0x18, 0xeb, 0xdb, 0x38, 0x72, 0x91, 0x77, 0x4b, 0x3e, 0x25,
+ 0x73, 0x1a, 0x78, 0xa5, 0x2c, 0x22, 0xe7, 0x1d, 0x32, 0x56, 0xa3, 0xde, 0x3f, 0xb0, 0xc7, 0x4e,
+ 0x2f, 0x72, 0x3e, 0x4c, 0x49, 0xaa, 0xb6, 0xaf, 0xb5, 0x54, 0xed, 0xfe, 0x94, 0x71, 0xd5, 0xf2,
+ 0x61, 0x4a, 0xd2, 0x07, 0x91, 0x05, 0x47, 0xeb, 0x8a, 0x2e, 0xa7, 0x21, 0xd8, 0x03, 0x81, 0x7d,
+ 0xb0, 0x94, 0xac, 0xff, 0x47, 0x0f, 0x2d, 0xbd, 0xa3, 0x1e, 0x3f, 0x00, 0x7b, 0x58, 0x22, 0x3e,
+ 0x06, 0xb8, 0xba, 0x8e, 0xe3, 0xf9, 0xcd, 0xeb, 0xf8, 0xfa, 0xfc, 0x64, 0x14, 0x7d, 0x43, 0x70,
+ 0x37, 0x67, 0x9b, 0x5d, 0x45, 0xe4, 0xe8, 0x69, 0x12, 0x19, 0x27, 0xe8, 0xd3, 0xd3, 0xff, 0xfd,
+ 0x30, 0x43, 0x7d, 0xd4, 0xd9, 0x6f, 0x84, 0x7e, 0x18, 0xe6, 0x45, 0x12, 0xfd, 0x34, 0x1e, 0x5e,
+ 0x68, 0x79, 0xd2, 0xf7, 0xf7, 0xb1, 0x20, 0xe4, 0x2d, 0x65, 0x5f, 0xe9, 0x07, 0x59, 0x99, 0x59,
+ 0x4a, 0xf5, 0xec, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x9b, 0x6e, 0x5d, 0x3c, 0xfe, 0x02, 0x00,
+ 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto b/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto
new file mode 100644
index 0000000..7d7808e
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto
@@ -0,0 +1,96 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
+option go_package = "github.com/golang/protobuf/ptypes/struct;structpb";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "StructProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+
+
+// `Struct` represents a structured data value, consisting of fields
+// which map to dynamically typed values. In some languages, `Struct`
+// might be supported by a native representation. For example, in
+// scripting languages like JS a struct is represented as an
+// object. The details of that representation are described together
+// with the proto support for the language.
+//
+// The JSON representation for `Struct` is JSON object.
+message Struct {
+ // Unordered map of dynamically typed values.
+ map<string, Value> fields = 1;
+}
+
+// `Value` represents a dynamically typed value which can be either
+// null, a number, a string, a boolean, a recursive struct value, or a
+// list of values. A producer of value is expected to set one of that
+// variants, absence of any variant indicates an error.
+//
+// The JSON representation for `Value` is JSON value.
+message Value {
+ // The kind of value.
+ oneof kind {
+ // Represents a null value.
+ NullValue null_value = 1;
+ // Represents a double value.
+ double number_value = 2;
+ // Represents a string value.
+ string string_value = 3;
+ // Represents a boolean value.
+ bool bool_value = 4;
+ // Represents a structured value.
+ Struct struct_value = 5;
+ // Represents a repeated `Value`.
+ ListValue list_value = 6;
+ }
+}
+
+// `NullValue` is a singleton enumeration to represent the null value for the
+// `Value` type union.
+//
+// The JSON representation for `NullValue` is JSON `null`.
+enum NullValue {
+ // Null value.
+ NULL_VALUE = 0;
+}
+
+// `ListValue` is a wrapper around a repeated field of values.
+//
+// The JSON representation for `ListValue` is JSON array.
+message ListValue {
+ // Repeated field of dynamically typed values.
+ repeated Value values = 1;
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp.go b/vendor/github.com/golang/protobuf/ptypes/timestamp.go
new file mode 100644
index 0000000..1b36576
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp.go
@@ -0,0 +1,125 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package ptypes
+
+// This file implements operations on google.protobuf.Timestamp.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+
+ tspb "github.com/golang/protobuf/ptypes/timestamp"
+)
+
+const (
+ // Seconds field of the earliest valid Timestamp.
+ // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
+ minValidSeconds = -62135596800
+ // Seconds field just after the latest valid Timestamp.
+ // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
+ maxValidSeconds = 253402300800
+)
+
+// validateTimestamp determines whether a Timestamp is valid.
+// A valid timestamp represents a time in the range
+// [0001-01-01, 10000-01-01) and has a Nanos field
+// in the range [0, 1e9).
+//
+// If the Timestamp is valid, validateTimestamp returns nil.
+// Otherwise, it returns an error that describes
+// the problem.
+//
+// Every valid Timestamp can be represented by a time.Time, but the converse is not true.
+func validateTimestamp(ts *tspb.Timestamp) error {
+ if ts == nil {
+ return errors.New("timestamp: nil Timestamp")
+ }
+ if ts.Seconds < minValidSeconds {
+ return fmt.Errorf("timestamp: %v before 0001-01-01", ts)
+ }
+ if ts.Seconds >= maxValidSeconds {
+ return fmt.Errorf("timestamp: %v after 10000-01-01", ts)
+ }
+ if ts.Nanos < 0 || ts.Nanos >= 1e9 {
+ return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts)
+ }
+ return nil
+}
+
+// Timestamp converts a google.protobuf.Timestamp proto to a time.Time.
+// It returns an error if the argument is invalid.
+//
+// Unlike most Go functions, if Timestamp returns an error, the first return value
+// is not the zero time.Time. Instead, it is the value obtained from the
+// time.Unix function when passed the contents of the Timestamp, in the UTC
+// locale. This may or may not be a meaningful time; many invalid Timestamps
+// do map to valid time.Times.
+//
+// A nil Timestamp returns an error. The first return value in that case is
+// undefined.
+func Timestamp(ts *tspb.Timestamp) (time.Time, error) {
+ // Don't return the zero value on error, because corresponds to a valid
+ // timestamp. Instead return whatever time.Unix gives us.
+ var t time.Time
+ if ts == nil {
+ t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp
+ } else {
+ t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
+ }
+ return t, validateTimestamp(ts)
+}
+
+// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
+// It returns an error if the resulting Timestamp is invalid.
+func TimestampProto(t time.Time) (*tspb.Timestamp, error) {
+ seconds := t.Unix()
+ nanos := int32(t.Sub(time.Unix(seconds, 0)))
+ ts := &tspb.Timestamp{
+ Seconds: seconds,
+ Nanos: nanos,
+ }
+ if err := validateTimestamp(ts); err != nil {
+ return nil, err
+ }
+ return ts, nil
+}
+
+// TimestampString returns the RFC 3339 string for valid Timestamps. For invalid
+// Timestamps, it returns an error message in parentheses.
+func TimestampString(ts *tspb.Timestamp) string {
+ t, err := Timestamp(ts)
+ if err != nil {
+ return fmt.Sprintf("(%v)", err)
+ }
+ return t.Format(time.RFC3339Nano)
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go
new file mode 100644
index 0000000..3b76261
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go
@@ -0,0 +1,162 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
+
+/*
+Package timestamp is a generated protocol buffer package.
+
+It is generated from these files:
+ github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
+
+It has these top-level messages:
+ Timestamp
+*/
+package timestamp
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// A Timestamp represents a point in time independent of any time zone
+// or calendar, represented as seconds and fractions of seconds at
+// nanosecond resolution in UTC Epoch time. It is encoded using the
+// Proleptic Gregorian Calendar which extends the Gregorian calendar
+// backwards to year one. It is encoded assuming all minutes are 60
+// seconds long, i.e. leap seconds are "smeared" so that no leap second
+// table is needed for interpretation. Range is from
+// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
+// By restricting to that range, we ensure that we can convert to
+// and from RFC 3339 date strings.
+// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
+//
+// # Examples
+//
+// Example 1: Compute Timestamp from POSIX `time()`.
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(time(NULL));
+// timestamp.set_nanos(0);
+//
+// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
+//
+// struct timeval tv;
+// gettimeofday(&tv, NULL);
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(tv.tv_sec);
+// timestamp.set_nanos(tv.tv_usec * 1000);
+//
+// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
+//
+// FILETIME ft;
+// GetSystemTimeAsFileTime(&ft);
+// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+//
+// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
+// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
+// Timestamp timestamp;
+// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
+// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
+//
+// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
+//
+// long millis = System.currentTimeMillis();
+//
+// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
+// .setNanos((int) ((millis % 1000) * 1000000)).build();
+//
+//
+// Example 5: Compute Timestamp from current time in Python.
+//
+// timestamp = Timestamp()
+// timestamp.GetCurrentTime()
+//
+// # JSON Mapping
+//
+// In JSON format, the Timestamp type is encoded as a string in the
+// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
+// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
+// where {year} is always expressed using four digits while {month}, {day},
+// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
+// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
+// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
+// is required, though only UTC (as indicated by "Z") is presently supported.
+//
+// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
+// 01:30 UTC on January 15, 2017.
+//
+// In JavaScript, one can convert a Date object to this format using the
+// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
+// method. In Python, a standard `datetime.datetime` object can be converted
+// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
+// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
+// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
+// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime())
+// to obtain a formatter capable of generating timestamps in this format.
+//
+//
+type Timestamp struct {
+ // Represents seconds of UTC time since Unix epoch
+ // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ // 9999-12-31T23:59:59Z inclusive.
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"`
+ // Non-negative fractions of a second at nanosecond resolution. Negative
+ // second values with fractions must still have non-negative nanos values
+ // that count forward in time. Must be from 0 to 999,999,999
+ // inclusive.
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"`
+}
+
+func (m *Timestamp) Reset() { *m = Timestamp{} }
+func (m *Timestamp) String() string { return proto.CompactTextString(m) }
+func (*Timestamp) ProtoMessage() {}
+func (*Timestamp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" }
+
+func (m *Timestamp) GetSeconds() int64 {
+ if m != nil {
+ return m.Seconds
+ }
+ return 0
+}
+
+func (m *Timestamp) GetNanos() int32 {
+ if m != nil {
+ return m.Nanos
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp")
+}
+
+func init() {
+ proto.RegisterFile("github.com/golang/protobuf/ptypes/timestamp/timestamp.proto", fileDescriptor0)
+}
+
+var fileDescriptor0 = []byte{
+ // 190 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x4e, 0xcf, 0x2c, 0xc9,
+ 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x2f, 0x28,
+ 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x28, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x2f, 0xc9,
+ 0xcc, 0x4d, 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0x40, 0xb0, 0xf4, 0xc0, 0x6a, 0x84, 0xf8, 0xd3, 0xf3,
+ 0xf3, 0xd3, 0x73, 0x52, 0xf5, 0x60, 0x3a, 0x94, 0xac, 0xb9, 0x38, 0x43, 0x60, 0x6a, 0x84, 0x24,
+ 0xb8, 0xd8, 0x8b, 0x53, 0x93, 0xf3, 0xf3, 0x52, 0x8a, 0x25, 0x18, 0x15, 0x18, 0x35, 0x98, 0x83,
+ 0x60, 0x5c, 0x21, 0x11, 0x2e, 0xd6, 0xbc, 0xc4, 0xbc, 0xfc, 0x62, 0x09, 0x26, 0x05, 0x46, 0x0d,
+ 0xd6, 0x20, 0x08, 0xc7, 0xa9, 0x8e, 0x4b, 0x38, 0x39, 0x3f, 0x57, 0x0f, 0xcd, 0x4c, 0x27, 0x3e,
+ 0xb8, 0x89, 0x01, 0x20, 0xa1, 0x00, 0xc6, 0x28, 0x6d, 0x12, 0xdc, 0xfc, 0x83, 0x91, 0x71, 0x11,
+ 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a, 0xe1,
+ 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43, 0x8c,
+ 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x6b, 0x59, 0x0a, 0x4d, 0x13, 0x01, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
new file mode 100644
index 0000000..b7cbd17
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
@@ -0,0 +1,133 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
+option go_package = "github.com/golang/protobuf/ptypes/timestamp";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "TimestampProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+
+// A Timestamp represents a point in time independent of any time zone
+// or calendar, represented as seconds and fractions of seconds at
+// nanosecond resolution in UTC Epoch time. It is encoded using the
+// Proleptic Gregorian Calendar which extends the Gregorian calendar
+// backwards to year one. It is encoded assuming all minutes are 60
+// seconds long, i.e. leap seconds are "smeared" so that no leap second
+// table is needed for interpretation. Range is from
+// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
+// By restricting to that range, we ensure that we can convert to
+// and from RFC 3339 date strings.
+// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
+//
+// # Examples
+//
+// Example 1: Compute Timestamp from POSIX `time()`.
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(time(NULL));
+// timestamp.set_nanos(0);
+//
+// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
+//
+// struct timeval tv;
+// gettimeofday(&tv, NULL);
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(tv.tv_sec);
+// timestamp.set_nanos(tv.tv_usec * 1000);
+//
+// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
+//
+// FILETIME ft;
+// GetSystemTimeAsFileTime(&ft);
+// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+//
+// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
+// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
+// Timestamp timestamp;
+// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
+// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
+//
+// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
+//
+// long millis = System.currentTimeMillis();
+//
+// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
+// .setNanos((int) ((millis % 1000) * 1000000)).build();
+//
+//
+// Example 5: Compute Timestamp from current time in Python.
+//
+// timestamp = Timestamp()
+// timestamp.GetCurrentTime()
+//
+// # JSON Mapping
+//
+// In JSON format, the Timestamp type is encoded as a string in the
+// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
+// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
+// where {year} is always expressed using four digits while {month}, {day},
+// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
+// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
+// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
+// is required, though only UTC (as indicated by "Z") is presently supported.
+//
+// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
+// 01:30 UTC on January 15, 2017.
+//
+// In JavaScript, one can convert a Date object to this format using the
+// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
+// method. In Python, a standard `datetime.datetime` object can be converted
+// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
+// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
+// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
+// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime())
+// to obtain a formatter capable of generating timestamps in this format.
+//
+//
+message Timestamp {
+
+ // Represents seconds of UTC time since Unix epoch
+ // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ // 9999-12-31T23:59:59Z inclusive.
+ int64 seconds = 1;
+
+ // Non-negative fractions of a second at nanosecond resolution. Negative
+ // second values with fractions must still have non-negative nanos values
+ // that count forward in time. Must be from 0 to 999,999,999
+ // inclusive.
+ int32 nanos = 2;
+}
diff --git a/vendor/github.com/google/certificate-transparency/LICENSE b/vendor/github.com/google/certificate-transparency/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/google/certificate-transparency/README-MacOS.md b/vendor/github.com/google/certificate-transparency/README-MacOS.md
new file mode 100644
index 0000000..7186f53
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/README-MacOS.md
@@ -0,0 +1,55 @@
+OS X Specific Instructions
+==========================
+
+Builds
+------
+
+We recommend that you use GClient to build on OSX. Please follow the
+instructions in the [main readme](README.md) file.
+
+Trusted root certificates
+-------------------------
+
+The CT code requires a set of trusted root certificates in order to:
+ 1. Validate outbound HTTPS connections
+ 2. (In the case of the log-server) decide whether to accept a certificate
+ chain for inclusion.
+
+On OSX, the system version of OpenSSL (0.9.8gz at time of writing) contains
+Apple-provided patches which intercept failed chain validations and re-attempts
+them using roots obtained from the system keychain. Since we use a much more
+recent (and unpatched) version of OpenSSL this behaviour is unsupported and so
+a PEM file containing the trusted root certs must be used.
+
+To use a certificate PEM bundle file with the CT C++ code, the following
+methods may be used.
+
+### Incoming inclusion requests (ct-server only)
+
+Set the `--trusted_cert_file` flag to point to the location of the PEM file
+containing the set of root certificates whose chains should be accepted for
+inclusion into the log.
+
+### For verifying outbound HTTPS connections (ct-mirror)
+
+Either set the `--trusted_roots_certs` flag, or the `SSL_CERT_FILE`
+environment variable, to point to the location of the PEM file containing the
+root certificates to be used to verify the outbound HTTPS connection.
+
+Sources of trusted roots
+------------------------
+
+Obviously the choice of root certificates to trust for outbound HTTPS
+connections and incoming inclusion requests are a matter of operating policy,
+but it is often useful to have a set of common roots for testing and
+development at the very least.
+
+While OSX ships with a set of common trusted roots, they are not directly
+available to OpenSSL and must be exported from the keychain first. This can be
+achieved with the following command:
+
+```bash
+security find-certificates -a -p /Library/Keychains/System.keychain > certs.pem
+security find-certificates -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> certs.pem
+```
+
diff --git a/vendor/github.com/google/certificate-transparency/README.md b/vendor/github.com/google/certificate-transparency/README.md
new file mode 100644
index 0000000..ffe459f
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/README.md
@@ -0,0 +1,303 @@
+certificate-transparency: Auditing for TLS certificates
+=======================================================
+
+[![Build Status](https://travis-ci.org/google/certificate-transparency.svg?branch=master)](https://travis-ci.org/google/certificate-transparency)
+
+ - [Introduction](#introduction)
+ - [Build Quick Start](#build-quick-start)
+ - [Code Layout](#code-layout)
+ - [Building the code](#building-the-code)
+ - [Build Dependencies](#build-dependencies)
+ - [Software Dependencies](#software-dependencies)
+ - [Build Troubleshooting](#build-troubleshooting)
+ - [Compiler Warnings/Errors](#compiler-warnings-errors)
+ - [Working on a Branch](#working-on-a-branch)
+ - [Using BoringSSL](#using-boringssl)
+ - [Testing the code](#testing-the-code)
+ - [Unit Tests](#unit-tests)
+ - [Testing and Logging Options](#testing-and-logging-options)
+ - [Deploying a Log](#deploying-a-log)
+ - [Operating a Log](#operating-a-log)
+
+Introduction
+------------
+
+This repository holds open-source code for functionality related
+to [certificate transparency](https://www.certificate-transparency.org/) (CT).
+The main areas covered are:
+
+ - An open-source, distributed, implementation of a CT Log server, also including:
+ - An implementation of a read-only ["mirror" server](docs/MirrorLog.md)
+ that mimics a remote Log.
+ - Ancillary tools needed for managing and maintaining the Log.
+ - A collection of client tools and libraries for interacting with a CT Log, in
+ various programming languages.
+ - An **experimental** implementation of a [DNS server](docs/DnsServer.md) that
+ returns CT proofs in the form of DNS records.
+ - An **experimental** implementation of a [general Log](docs/XjsonServer.md)
+ that allows arbitrary data (not just TLS certificates) to be logged.
+
+The supported platforms are:
+
+ - **Linux**: tested on Ubuntu 14.04; other variants (Fedora 22, CentOS 7) may
+ require tweaking of [compiler options](#build-troubleshooting).
+ - **OS X**: version 10.10
+ - **FreeBSD**: version 10.*
+
+
+Build Quick Start
+-----------------
+
+First, ensure that the build machine has all of the required [build dependencies](#build-dependencies).
+Then use
+[gclient](https://www.chromium.org/developers/how-tos/depottools#TOC-gclient) to
+retrieve and build the [other software](#software-dependencies) needed by the Log,
+and then use (GNU) `make` to build and test the CT code:
+
+```bash
+export CXX=clang++ CC=clang
+mkdir ct # or whatever directory you prefer
+cd ct
+gclient config --name="certificate-transparency" https://github.com/google/certificate-transparency.git
+gclient sync # retrieve and build dependencies
+# substitute gmake or gnumake below if that's what your platform calls it:
+make -C certificate-transparency check # build the CT software & self-test
+```
+
+Code Layout
+-----------
+
+The source code is generally arranged according to implementation language, in
+the `cpp`, `go`, `java` and `python` subdirectories. The key subdirectories
+are:
+
+ - For the main distributed CT Log itself:
+ - `cpp/log`: Main distributed CT Log implementation.
+ - `cpp/merkletree`: Merkle tree implementation.
+ - `cpp/server`: Top-level code for server implementations.
+ - `cpp/monitoring`: Code to export operation statistics from CT Log.
+ - The [CT mirror Log](docs/MirrorLog.md) implementation also uses:
+ - `cpp/fetcher`: Code to fetch entries from another Log
+ - Client code for accessing a CT Log instance:
+ - `cpp/client`: CT Log client code in C++
+ - `go/client`: CT Log client code in Go
+ - `python/ct`: CT Log client code in Python
+ - `java/src/org/certificatetransparency/ctlog`: CT Log client code in Java
+ - Other tools:
+ - `go/fixchain`: Tool to fix up certificate chains
+ - `go/gossip`: Code to allow gossip-based synchronization of cert info
+ - `go/scanner`: CT Log scanner tool
+ - `go/merkletree`: Merkle tree implementation in Go.
+
+Building the Code
+-----------------
+
+The CT software in this repository relies on a number of other
+[open-source projects](#software-dependencies), and we recommend that:
+
+ - The CT software should be built using local copies of these dependencies
+ rather than installed packages, to prevent version incompatibilities.
+ - The dependent libraries should be statically linked into the CT binaries,
+ rather than relying on dynamically linked libraries that may be different in
+ the deployed environment.
+
+The supported build system uses the
+[gclient](https://www.chromium.org/developers/how-tos/depottools#TOC-gclient)
+tool from the Chromium project to handle these requirements and to ensure a
+reliable, reproducible build. Older build instructions for using
+[Ubuntu](docs/archive/BuildUbuntu.md) or
+[Fedora](docs/archive/BuildFedora.md) packages and for
+[manually building dependencies from source](docs/archive/BuildSrc.md) are no
+longer supported.
+
+Within a main top-level directory, gclient handles the process of:
+
+ - generating subdirectories for each dependency
+ - generating a subdirectory for for the CT Log code itself
+ - building all of the dependencies
+ - installing the built dependencies into an `install/` subdirectory
+ - configuring the CT build to reference the built dependencies.
+
+Under the covers, this gclient build process is controlled by:
+
+ - The master [DEPS](DEPS) file, which configures the locations and versions
+ of the source code needed for the dependencies, and which hooks onto ...
+ - The makefiles in the [build/](build) subdirectory, which govern the build
+ process for each dependency, ensuring that:
+ - Static libraries are built.
+ - Built code is installed into the local `install/` directory, where it
+ is available for the build of the CT code itself.
+
+
+### Build Dependencies
+
+The following tools are needed to build the CT software and its dependencies.
+
+ - [depot_tools](https://www.chromium.org/developers/how-tos/install-depot-tools)
+ - autoconf/automake etc.
+ - libtool
+ - shtool
+ - clang++ (>=3.4)
+ - cmake (>=v3.1.2)
+ - git
+ - GNU make
+ - Tcl
+ - pkg-config
+ - Python 2.7
+
+The exact packages required to install these tools depends on the platform.
+For a Debian-based system, the relevant packages are:
+`autoconf automake libtool shtool cmake clang git make tcl pkg-config python2.7`
+
+### Software Dependencies
+
+The following collections of additional software are used by the main CT
+Log codebase.
+
+ - Google utility libraries:
+ - [gflags](https://github.com/gflags/gflags): command-line flag handling
+ - [glog](https://github.com/google/glog): logging infrastructure, which
+ also requires libunwind.
+ - [Google Mock](https://github.com/google/googlemock.git): C++ test framework
+ - [Google Test](https://github.com/google/googletest.git): C++ mocking
+ framework
+ - [Protocol Buffers](https://developers.google.com/protocol-buffers/):
+ language-neutral data serialization library
+ - [tcmalloc](http://goog-perftools.sourceforge.net/doc/tcmalloc.html):
+ efficient `malloc` replacement optimized for multi-threaded use
+ - Other utility libraries:
+ - [libevent](http://libevent.org/): event-processing library
+ - [libevhtp](https://github.com/ellzey/libevhtp): HTTP server
+ plug-in/replacement for libevent
+ - [json-c](https://github.com/json-c/json-c): JSON processing library
+ - [libunwind](http://www.nongnu.org/libunwind/): library for generating
+ stack traces
+ - Cryptographic library: one of the following, selected via the `SSL` build
+ variable.
+ - [OpenSSL](https://github.com/google/googletest.git): default
+ cryptography library.
+ - [BoringSSL](https://boringssl.googlesource.com/boringssl/): Google's
+ fork of OpenSSL
+ - Data storage functionality: one of the following, defaulting (and highly
+ recommended to stick with) LevelDB.
+ - [LevelDB](https://github.com/google/leveldb): fast key-value store,
+ which uses:
+ - [Snappy](http://google.github.io/snappy/): compression library
+ - [SQLite](https://www.sqlite.org/): file-based SQL library
+
+The extra (experimental) CT projects in this repo involve additional
+dependencies:
+
+ - The experimental CT [DNS server](docs/DnsServer.md) uses:
+ - [ldnbs](http://www.nlnetlabs.nl/projects/ldns/): DNS library, including
+ DNSSEC function (which relies on OpenSSL for crypto functionality)
+ - The experimental [general Log](docs/XjsonServer.md) uses:
+ - [objecthash](https://github.com/benlaurie/objecthash): tools for
+ hashing objects in a language/encoding-agnostic manner
+ - [ICU](http://site.icu-project.org/): Unicode libraries (needed to
+ normalize international text in objects)
+
+
+
+Build Troubleshooting
+---------------------
+
+### Compiler Warnings/Errors
+
+The CT C++ codebase is built with the Clang `-Werror` flag so that the
+codebase stays warning-free. However, this can cause build errors when
+newer/different versions of the C++ compiler are used, as any newly created
+warnings are treated as errors. To fix this, add the appropriate
+`-Wno-error=<warning-name>` option to `CXXFLAGS`.
+
+For example, on errors involving unused variables try using:
+
+```bash
+CXXFLAGS="-O2 -Wno-error=unused-variable" gclient sync
+```
+
+If an error about an unused typedef in a `glog` header file occurs, try this:
+
+```bash
+CXXFLAGS="-O2 -Wno-error=unused-variable -Wno-error=unused-local-typedefs" gclient sync
+```
+
+When changing `CXXFLAGS` it's safer to remove the existing build directories
+in case not all dependencies are properly accounted for and rebuilt. If
+problems persist, check that the Makefile in `certificate-transparency`
+contains the options that were passed in `CXXFLAGS`.
+
+### Working on a Branch
+
+If you're trying to clone from a branch on the CT repository then you'll need
+to substitute the following command for the `gclient config` command
+[above](#build-quick-start), replacing `branch` as appropriate
+
+```bash
+gclient config --name="certificate-transparency" https://github.com/google/certificate-transparency.git@branch
+```
+
+### Using BoringSSL
+
+The BoringSSL fork of OpenSSL can be used in place of OpenSSL (but note that
+the experimental [CT DNS server](docs/DnsServer.md) does not support this
+configuration). To enable this, after the first step (`gclient config ...`)
+in the gclient [build process](#build-quick-start), modify the top-level
+`.gclient` to add:
+
+```python
+ "custom_vars": { "ssl_impl": "boringssl" } },
+```
+
+Then continue the [build process](#build-quick-start) with the `gclient sync` step.
+
+
+Testing the Code
+----------------
+
+### Unit Tests
+
+The unit tests for the CT code can be run with the `make check` target of
+`certificate-transparency/Makefile`.
+
+## Testing and Logging Options ##
+
+Note that several tests write files on disk. The default directory for
+storing temporary testdata is `/tmp`. You can change this by setting
+`TMPDIR=<tmpdir>` for make.
+
+End-to-end tests also create temporary certificate and server files in
+`test/tmp`. All these files are cleaned up after a successful test
+run.
+
+For logging options, see the
+[glog documentation](http://htmlpreview.github.io/?https://github.com/google/glog/blob/master/doc/glog.html).
+
+By default, unit tests log to `stderr`, and log only messages with a FATAL
+level (i.e., those that result in abnormal program termination). You can
+override the defaults with command-line flags.
+
+
+Deploying a Log
+---------------
+
+The build process described so far generates a set of executables; however,
+other components and configuration is needed to set up a running CT Log.
+In particular, as shown in the following diagram:
+ - A set of web servers that act as HTTPS terminators and load
+ balancers is needed in front of the CT Log instances.
+ - A cluster of [etcd](https://github.com/coreos/etcd) instances is needed to
+ provide replication and synchronization services for the CT Log instances.
+
+<img src="docs/images/SystemDiagram.png" width="650">
+
+Configuring and setting up a distributed production Log is covered in a
+[separate document](docs/Deployment.md).
+
+
+Operating a Log
+---------------
+
+Running a successful, trusted, certificate transparency Log involves more than
+just deploying a set of binaries. Information and advice on operating a
+running CT Log is covered in a [separate document](docs/Operation.md)
diff --git a/vendor/github.com/google/certificate-transparency/cpp/third_party/curl/hostcheck.c b/vendor/github.com/google/certificate-transparency/cpp/third_party/curl/hostcheck.c
new file mode 100644
index 0000000..b894692
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/cpp/third_party/curl/hostcheck.c
@@ -0,0 +1,214 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* This file is an amalgamation of hostcheck.c and most of rawstr.c
+ from cURL. The contents of the COPYING file mentioned above are:
+
+COPYRIGHT AND PERMISSION NOTICE
+
+Copyright (c) 1996 - 2013, Daniel Stenberg, <daniel@haxx.se>.
+
+All rights reserved.
+
+Permission to use, copy, modify, and distribute this software for any purpose
+with or without fee is hereby granted, provided that the above copyright
+notice and this permission notice appear in all copies.
+
+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 OF THIRD PARTY RIGHTS. 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.
+
+Except as contained in this notice, the name of a copyright holder shall not
+be used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization of the copyright holder.
+*/
+
+#include "hostcheck.h"
+#include <string.h>
+
+/* Portable, consistent toupper (remember EBCDIC). Do not use toupper() because
+ its behavior is altered by the current locale. */
+static char Curl_raw_toupper(char in) {
+ switch (in) {
+ case 'a':
+ return 'A';
+ case 'b':
+ return 'B';
+ case 'c':
+ return 'C';
+ case 'd':
+ return 'D';
+ case 'e':
+ return 'E';
+ case 'f':
+ return 'F';
+ case 'g':
+ return 'G';
+ case 'h':
+ return 'H';
+ case 'i':
+ return 'I';
+ case 'j':
+ return 'J';
+ case 'k':
+ return 'K';
+ case 'l':
+ return 'L';
+ case 'm':
+ return 'M';
+ case 'n':
+ return 'N';
+ case 'o':
+ return 'O';
+ case 'p':
+ return 'P';
+ case 'q':
+ return 'Q';
+ case 'r':
+ return 'R';
+ case 's':
+ return 'S';
+ case 't':
+ return 'T';
+ case 'u':
+ return 'U';
+ case 'v':
+ return 'V';
+ case 'w':
+ return 'W';
+ case 'x':
+ return 'X';
+ case 'y':
+ return 'Y';
+ case 'z':
+ return 'Z';
+ }
+ return in;
+}
+
+/*
+ * Curl_raw_equal() is for doing "raw" case insensitive strings. This is meant
+ * to be locale independent and only compare strings we know are safe for
+ * this. See http://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for
+ * some further explanation to why this function is necessary.
+ *
+ * The function is capable of comparing a-z case insensitively even for
+ * non-ascii.
+ */
+
+static int Curl_raw_equal(const char *first, const char *second) {
+ while (*first && *second) {
+ if (Curl_raw_toupper(*first) != Curl_raw_toupper(*second))
+ /* get out of the loop as soon as they don't match */
+ break;
+ first++;
+ second++;
+ }
+ /* we do the comparison here (possibly again), just to make sure that if the
+ loop above is skipped because one of the strings reached zero, we must not
+ return this as a successful match */
+ return (Curl_raw_toupper(*first) == Curl_raw_toupper(*second));
+}
+
+static int Curl_raw_nequal(const char *first, const char *second, size_t max) {
+ while (*first && *second && max) {
+ if (Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) {
+ break;
+ }
+ max--;
+ first++;
+ second++;
+ }
+ if (0 == max)
+ return 1; /* they are equal this far */
+
+ return Curl_raw_toupper(*first) == Curl_raw_toupper(*second);
+}
+
+/*
+ * Match a hostname against a wildcard pattern.
+ * E.g.
+ * "foo.host.com" matches "*.host.com".
+ *
+ * We use the matching rule described in RFC6125, section 6.4.3.
+ * http://tools.ietf.org/html/rfc6125#section-6.4.3
+ */
+
+static int hostmatch(const char *hostname, const char *pattern) {
+ const char *pattern_label_end, *pattern_wildcard, *hostname_label_end;
+ int wildcard_enabled;
+ size_t prefixlen, suffixlen;
+ pattern_wildcard = strchr(pattern, '*');
+ if (pattern_wildcard == NULL)
+ return Curl_raw_equal(pattern, hostname) ? CURL_HOST_MATCH
+ : CURL_HOST_NOMATCH;
+
+ /* We require at least 2 dots in pattern to avoid too wide wildcard
+ match. */
+ wildcard_enabled = 1;
+ pattern_label_end = strchr(pattern, '.');
+ if (pattern_label_end == NULL ||
+ strchr(pattern_label_end + 1, '.') == NULL ||
+ pattern_wildcard > pattern_label_end ||
+ Curl_raw_nequal(pattern, "xn--", 4)) {
+ wildcard_enabled = 0;
+ }
+ if (!wildcard_enabled)
+ return Curl_raw_equal(pattern, hostname) ? CURL_HOST_MATCH
+ : CURL_HOST_NOMATCH;
+
+ hostname_label_end = strchr(hostname, '.');
+ if (hostname_label_end == NULL ||
+ !Curl_raw_equal(pattern_label_end, hostname_label_end))
+ return CURL_HOST_NOMATCH;
+
+ /* The wildcard must match at least one character, so the left-most
+ label of the hostname is at least as large as the left-most label
+ of the pattern. */
+ if (hostname_label_end - hostname < pattern_label_end - pattern)
+ return CURL_HOST_NOMATCH;
+
+ prefixlen = pattern_wildcard - pattern;
+ suffixlen = pattern_label_end - (pattern_wildcard + 1);
+ return Curl_raw_nequal(pattern, hostname, prefixlen) &&
+ Curl_raw_nequal(pattern_wildcard + 1,
+ hostname_label_end - suffixlen, suffixlen)
+ ? CURL_HOST_MATCH
+ : CURL_HOST_NOMATCH;
+}
+
+int Curl_cert_hostcheck(const char *match_pattern, const char *hostname) {
+ if (!match_pattern || !*match_pattern || !hostname ||
+ !*hostname) /* sanity check */
+ return 0;
+
+ if (Curl_raw_equal(hostname, match_pattern)) /* trivial case */
+ return 1;
+
+ if (hostmatch(hostname, match_pattern) == CURL_HOST_MATCH)
+ return 1;
+ return 0;
+}
diff --git a/vendor/github.com/google/certificate-transparency/cpp/third_party/curl/hostcheck.h b/vendor/github.com/google/certificate-transparency/cpp/third_party/curl/hostcheck.h
new file mode 100644
index 0000000..f709917
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/cpp/third_party/curl/hostcheck.h
@@ -0,0 +1,29 @@
+#ifndef HEADER_CURL_HOSTCHECK_H
+#define HEADER_CURL_HOSTCHECK_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#define CURL_HOST_NOMATCH 0
+#define CURL_HOST_MATCH 1
+int Curl_cert_hostcheck(const char* match_pattern, const char* hostname);
+
+#endif /* HEADER_CURL_HOSTCHECK_H */
diff --git a/vendor/github.com/google/certificate-transparency/cpp/third_party/isec_partners/openssl_hostname_validation.c b/vendor/github.com/google/certificate-transparency/cpp/third_party/isec_partners/openssl_hostname_validation.c
new file mode 100644
index 0000000..b16abad
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/cpp/third_party/isec_partners/openssl_hostname_validation.c
@@ -0,0 +1,180 @@
+/* Obtained from: https://github.com/iSECPartners/ssl-conservatory */
+
+/*
+Copyright (C) 2012, iSEC Partners.
+
+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.
+ */
+
+/*
+ * Helper functions to perform basic hostname validation using OpenSSL.
+ *
+ * Please read "everything-you-wanted-to-know-about-openssl.pdf" before
+ * attempting to use this code. This whitepaper describes how the code works,
+ * how it should be used, and what its limitations are.
+ *
+ * Author: Alban Diquet
+ * License: See LICENSE
+ *
+ */
+
+
+#include <openssl/x509v3.h>
+#include <openssl/ssl.h>
+
+#include "third_party/curl/hostcheck.h"
+#include "third_party/isec_partners/openssl_hostname_validation.h"
+
+#define HOSTNAME_MAX_SIZE 255
+
+/**
+* Tries to find a match for hostname in the certificate's Common Name field.
+*
+* Returns MatchFound if a match was found.
+* Returns MatchNotFound if no matches were found.
+* Returns MalformedCertificate if the Common Name had a NUL character embedded
+* in it.
+* Returns Error if the Common Name could not be extracted.
+*/
+static HostnameValidationResult matches_common_name(const char *hostname,
+ const X509 *server_cert) {
+ int common_name_loc = -1;
+ X509_NAME_ENTRY *common_name_entry = NULL;
+ ASN1_STRING *common_name_asn1 = NULL;
+ char *common_name_str = NULL;
+
+ // Find the position of the CN field in the Subject field of the certificate
+ common_name_loc =
+ X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *)server_cert),
+ NID_commonName, -1);
+ if (common_name_loc < 0) {
+ return Error;
+ }
+
+ // Extract the CN field
+ common_name_entry =
+ X509_NAME_get_entry(X509_get_subject_name((X509 *)server_cert),
+ common_name_loc);
+ if (common_name_entry == NULL) {
+ return Error;
+ }
+
+ // Convert the CN field to a C string
+ common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
+ if (common_name_asn1 == NULL) {
+ return Error;
+ }
+ common_name_str = (char *)ASN1_STRING_data(common_name_asn1);
+
+ // Make sure there isn't an embedded NUL character in the CN
+ if ((size_t)ASN1_STRING_length(common_name_asn1) !=
+ strlen(common_name_str)) {
+ return MalformedCertificate;
+ }
+
+ // Compare expected hostname with the CN
+ if (Curl_cert_hostcheck(common_name_str, hostname) == CURL_HOST_MATCH) {
+ return MatchFound;
+ } else {
+ return MatchNotFound;
+ }
+}
+
+
+/**
+* Tries to find a match for hostname in the certificate's Subject Alternative
+* Name extension.
+*
+* Returns MatchFound if a match was found.
+* Returns MatchNotFound if no matches were found.
+* Returns MalformedCertificate if any of the hostnames had a NUL character
+* embedded in it.
+* Returns NoSANPresent if the SAN extension was not present in the certificate.
+*/
+static HostnameValidationResult matches_subject_alternative_name(
+ const char *hostname, const X509 *server_cert) {
+ HostnameValidationResult result = MatchNotFound;
+ int i;
+ int san_names_nb = -1;
+ STACK_OF(GENERAL_NAME) *san_names = NULL;
+
+ // Try to extract the names within the SAN extension from the certificate
+ san_names =
+ X509_get_ext_d2i((X509 *)server_cert, NID_subject_alt_name, NULL, NULL);
+ if (san_names == NULL) {
+ return NoSANPresent;
+ }
+ san_names_nb = sk_GENERAL_NAME_num(san_names);
+
+ // Check each name within the extension
+ for (i = 0; i < san_names_nb; i++) {
+ const GENERAL_NAME *current_name = sk_GENERAL_NAME_value(san_names, i);
+
+ if (current_name->type == GEN_DNS) {
+ // Current name is a DNS name, let's check it
+ char *dns_name = (char *)ASN1_STRING_data(current_name->d.dNSName);
+
+ // Make sure there isn't an embedded NUL character in the DNS name
+ if ((size_t)ASN1_STRING_length(current_name->d.dNSName) !=
+ strlen(dns_name)) {
+ result = MalformedCertificate;
+ break;
+ } else { // Compare expected hostname with the DNS name
+ if (Curl_cert_hostcheck(dns_name, hostname) == CURL_HOST_MATCH) {
+ result = MatchFound;
+ break;
+ }
+ }
+ }
+ }
+ sk_GENERAL_NAME_pop_free(san_names, GENERAL_NAME_free);
+
+ return result;
+}
+
+
+/**
+* Validates the server's identity by looking for the expected hostname in the
+* server's certificate. As described in RFC 6125, it first tries to find a
+* match
+* in the Subject Alternative Name extension. If the extension is not present in
+* the certificate, it checks the Common Name instead.
+*
+* Returns MatchFound if a match was found.
+* Returns MatchNotFound if no matches were found.
+* Returns MalformedCertificate if any of the hostnames had a NUL character
+* embedded in it.
+* Returns Error if there was an error.
+*/
+HostnameValidationResult validate_hostname(const char *hostname,
+ const X509 *server_cert) {
+ HostnameValidationResult result;
+
+ if ((hostname == NULL) || (server_cert == NULL))
+ return Error;
+
+ // First try the Subject Alternative Names extension
+ result = matches_subject_alternative_name(hostname, server_cert);
+ if (result == NoSANPresent) {
+ // Extension was not found: try the Common Name
+ result = matches_common_name(hostname, server_cert);
+ }
+
+ return result;
+}
diff --git a/vendor/github.com/google/certificate-transparency/cpp/third_party/isec_partners/openssl_hostname_validation.h b/vendor/github.com/google/certificate-transparency/cpp/third_party/isec_partners/openssl_hostname_validation.h
new file mode 100644
index 0000000..b5902a1
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/cpp/third_party/isec_partners/openssl_hostname_validation.h
@@ -0,0 +1,59 @@
+/* Obtained from: https://github.com/iSECPartners/ssl-conservatory */
+
+/*
+Copyright (C) 2012, iSEC Partners.
+
+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.
+ */
+
+/*
+ * Helper functions to perform basic hostname validation using OpenSSL.
+ *
+ * Please read "everything-you-wanted-to-know-about-openssl.pdf" before
+ * attempting to use this code. This whitepaper describes how the code works,
+ * how it should be used, and what its limitations are.
+ *
+ * Author: Alban Diquet
+ * License: See LICENSE
+ *
+ */
+
+typedef enum {
+ MatchFound,
+ MatchNotFound,
+ NoSANPresent,
+ MalformedCertificate,
+ Error
+} HostnameValidationResult;
+
+/**
+* Validates the server's identity by looking for the expected hostname in the
+* server's certificate. As described in RFC 6125, it first tries to find a
+* match
+* in the Subject Alternative Name extension. If the extension is not present in
+* the certificate, it checks the Common Name instead.
+*
+* Returns MatchFound if a match was found.
+* Returns MatchNotFound if no matches were found.
+* Returns MalformedCertificate if any of the hostnames had a NUL character
+* embedded in it.
+* Returns Error if there was an error.
+*/
+HostnameValidationResult validate_hostname(const char* hostname,
+ const X509* server_cert);
diff --git a/vendor/github.com/google/certificate-transparency/cpp/version.h b/vendor/github.com/google/certificate-transparency/cpp/version.h
new file mode 100644
index 0000000..53afc73
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/cpp/version.h
@@ -0,0 +1,12 @@
+#ifndef CERT_TRANS_VERSION_H_
+#define CERT_TRANS_VERSION_H_
+
+namespace cert_trans {
+
+
+extern const char kBuildVersion[];
+
+
+} // namespace cert_trans
+
+#endif // CERT_TRANS_VERSION_H_
diff --git a/vendor/github.com/google/certificate-transparency/go/README.md b/vendor/github.com/google/certificate-transparency/go/README.md
new file mode 100644
index 0000000..82c5d1b
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/README.md
@@ -0,0 +1,25 @@
+This is the really early beginnings of a certificate transparency log
+client written in Go, along with a log scanner tool.
+
+You'll need go v1.1 or higher to compile.
+
+# Installation
+
+This go code must be imported into your go workspace before you can
+use it, which can be done with:
+
+ go get github.com/google/certificate-transparency/go/client
+ go get github.com/google/certificate-transparency/go/scanner
+ etc.
+
+# Building the binaries
+
+To compile the log scanner run:
+
+ go build github.com/google/certificate-transparency/go/scanner/main/scanner.go
+
+# Contributing
+
+When sending pull requests, please ensure that everything's been run
+through ```gofmt``` beforehand so we can keep everything nice and
+tidy.
diff --git a/vendor/github.com/google/certificate-transparency/go/asn1/asn1.go b/vendor/github.com/google/certificate-transparency/go/asn1/asn1.go
new file mode 100755
index 0000000..e987477
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/asn1/asn1.go
@@ -0,0 +1,956 @@
+// Copyright 2009 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 asn1 implements parsing of DER-encoded ASN.1 data structures,
+// as defined in ITU-T Rec X.690.
+//
+// See also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,''
+// http://luca.ntop.org/Teaching/Appunti/asn1.html.
+//
+// START CT CHANGES
+// This is a fork of the Go standard library ASN.1 implementation
+// (encoding/asn1). The main difference is that this version tries to correct
+// for errors (e.g. use of tagPrintableString when the string data is really
+// ISO8859-1 - a common error present in many x509 certificates in the wild.)
+// END CT CHANGES
+package asn1
+
+// ASN.1 is a syntax for specifying abstract objects and BER, DER, PER, XER etc
+// are different encoding formats for those objects. Here, we'll be dealing
+// with DER, the Distinguished Encoding Rules. DER is used in X.509 because
+// it's fast to parse and, unlike BER, has a unique encoding for every object.
+// When calculating hashes over objects, it's important that the resulting
+// bytes be the same at both ends and DER removes this margin of error.
+//
+// ASN.1 is very complex and this package doesn't attempt to implement
+// everything by any means.
+
+import (
+ // START CT CHANGES
+ "errors"
+ "fmt"
+ // END CT CHANGES
+ "math/big"
+ "reflect"
+ // START CT CHANGES
+ "strings"
+ // END CT CHANGES
+ "time"
+)
+
+// A StructuralError suggests that the ASN.1 data is valid, but the Go type
+// which is receiving it doesn't match.
+type StructuralError struct {
+ Msg string
+}
+
+func (e StructuralError) Error() string { return "asn1: structure error: " + e.Msg }
+
+// A SyntaxError suggests that the ASN.1 data is invalid.
+type SyntaxError struct {
+ Msg string
+}
+
+func (e SyntaxError) Error() string { return "asn1: syntax error: " + e.Msg }
+
+// We start by dealing with each of the primitive types in turn.
+
+// BOOLEAN
+
+func parseBool(bytes []byte) (ret bool, err error) {
+ if len(bytes) != 1 {
+ err = SyntaxError{"invalid boolean"}
+ return
+ }
+
+ // DER demands that "If the encoding represents the boolean value TRUE,
+ // its single contents octet shall have all eight bits set to one."
+ // Thus only 0 and 255 are valid encoded values.
+ switch bytes[0] {
+ case 0:
+ ret = false
+ case 0xff:
+ ret = true
+ default:
+ err = SyntaxError{"invalid boolean"}
+ }
+
+ return
+}
+
+// INTEGER
+
+// parseInt64 treats the given bytes as a big-endian, signed integer and
+// returns the result.
+func parseInt64(bytes []byte) (ret int64, err error) {
+ if len(bytes) > 8 {
+ // We'll overflow an int64 in this case.
+ err = StructuralError{"integer too large"}
+ return
+ }
+ for bytesRead := 0; bytesRead < len(bytes); bytesRead++ {
+ ret <<= 8
+ ret |= int64(bytes[bytesRead])
+ }
+
+ // Shift up and down in order to sign extend the result.
+ ret <<= 64 - uint8(len(bytes))*8
+ ret >>= 64 - uint8(len(bytes))*8
+ return
+}
+
+// parseInt treats the given bytes as a big-endian, signed integer and returns
+// the result.
+func parseInt32(bytes []byte) (int32, error) {
+ ret64, err := parseInt64(bytes)
+ if err != nil {
+ return 0, err
+ }
+ if ret64 != int64(int32(ret64)) {
+ return 0, StructuralError{"integer too large"}
+ }
+ return int32(ret64), nil
+}
+
+var bigOne = big.NewInt(1)
+
+// parseBigInt treats the given bytes as a big-endian, signed integer and returns
+// the result.
+func parseBigInt(bytes []byte) *big.Int {
+ ret := new(big.Int)
+ if len(bytes) > 0 && bytes[0]&0x80 == 0x80 {
+ // This is a negative number.
+ notBytes := make([]byte, len(bytes))
+ for i := range notBytes {
+ notBytes[i] = ^bytes[i]
+ }
+ ret.SetBytes(notBytes)
+ ret.Add(ret, bigOne)
+ ret.Neg(ret)
+ return ret
+ }
+ ret.SetBytes(bytes)
+ return ret
+}
+
+// BIT STRING
+
+// BitString is the structure to use when you want an ASN.1 BIT STRING type. A
+// bit string is padded up to the nearest byte in memory and the number of
+// valid bits is recorded. Padding bits will be zero.
+type BitString struct {
+ Bytes []byte // bits packed into bytes.
+ BitLength int // length in bits.
+}
+
+// At returns the bit at the given index. If the index is out of range it
+// returns false.
+func (b BitString) At(i int) int {
+ if i < 0 || i >= b.BitLength {
+ return 0
+ }
+ x := i / 8
+ y := 7 - uint(i%8)
+ return int(b.Bytes[x]>>y) & 1
+}
+
+// RightAlign returns a slice where the padding bits are at the beginning. The
+// slice may share memory with the BitString.
+func (b BitString) RightAlign() []byte {
+ shift := uint(8 - (b.BitLength % 8))
+ if shift == 8 || len(b.Bytes) == 0 {
+ return b.Bytes
+ }
+
+ a := make([]byte, len(b.Bytes))
+ a[0] = b.Bytes[0] >> shift
+ for i := 1; i < len(b.Bytes); i++ {
+ a[i] = b.Bytes[i-1] << (8 - shift)
+ a[i] |= b.Bytes[i] >> shift
+ }
+
+ return a
+}
+
+// parseBitString parses an ASN.1 bit string from the given byte slice and returns it.
+func parseBitString(bytes []byte) (ret BitString, err error) {
+ if len(bytes) == 0 {
+ err = SyntaxError{"zero length BIT STRING"}
+ return
+ }
+ paddingBits := int(bytes[0])
+ if paddingBits > 7 ||
+ len(bytes) == 1 && paddingBits > 0 ||
+ bytes[len(bytes)-1]&((1<<bytes[0])-1) != 0 {
+ err = SyntaxError{"invalid padding bits in BIT STRING"}
+ return
+ }
+ ret.BitLength = (len(bytes)-1)*8 - paddingBits
+ ret.Bytes = bytes[1:]
+ return
+}
+
+// OBJECT IDENTIFIER
+
+// An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.
+type ObjectIdentifier []int
+
+// Equal reports whether oi and other represent the same identifier.
+func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool {
+ if len(oi) != len(other) {
+ return false
+ }
+ for i := 0; i < len(oi); i++ {
+ if oi[i] != other[i] {
+ return false
+ }
+ }
+
+ return true
+}
+
+// parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and
+// returns it. An object identifier is a sequence of variable length integers
+// that are assigned in a hierarchy.
+func parseObjectIdentifier(bytes []byte) (s []int, err error) {
+ if len(bytes) == 0 {
+ err = SyntaxError{"zero length OBJECT IDENTIFIER"}
+ return
+ }
+
+ // In the worst case, we get two elements from the first byte (which is
+ // encoded differently) and then every varint is a single byte long.
+ s = make([]int, len(bytes)+1)
+
+ // The first varint is 40*value1 + value2:
+ // According to this packing, value1 can take the values 0, 1 and 2 only.
+ // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
+ // then there are no restrictions on value2.
+ v, offset, err := parseBase128Int(bytes, 0)
+ if err != nil {
+ return
+ }
+ if v < 80 {
+ s[0] = v / 40
+ s[1] = v % 40
+ } else {
+ s[0] = 2
+ s[1] = v - 80
+ }
+
+ i := 2
+ for ; offset < len(bytes); i++ {
+ v, offset, err = parseBase128Int(bytes, offset)
+ if err != nil {
+ return
+ }
+ s[i] = v
+ }
+ s = s[0:i]
+ return
+}
+
+// ENUMERATED
+
+// An Enumerated is represented as a plain int.
+type Enumerated int
+
+// FLAG
+
+// A Flag accepts any data and is set to true if present.
+type Flag bool
+
+// parseBase128Int parses a base-128 encoded int from the given offset in the
+// given byte slice. It returns the value and the new offset.
+func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) {
+ offset = initOffset
+ for shifted := 0; offset < len(bytes); shifted++ {
+ if shifted > 4 {
+ err = StructuralError{"base 128 integer too large"}
+ return
+ }
+ ret <<= 7
+ b := bytes[offset]
+ ret |= int(b & 0x7f)
+ offset++
+ if b&0x80 == 0 {
+ return
+ }
+ }
+ err = SyntaxError{"truncated base 128 integer"}
+ return
+}
+
+// UTCTime
+
+func parseUTCTime(bytes []byte) (ret time.Time, err error) {
+ s := string(bytes)
+ ret, err = time.Parse("0601021504Z0700", s)
+ if err != nil {
+ ret, err = time.Parse("060102150405Z0700", s)
+ }
+ if err == nil && ret.Year() >= 2050 {
+ // UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
+ ret = ret.AddDate(-100, 0, 0)
+ }
+
+ return
+}
+
+// parseGeneralizedTime parses the GeneralizedTime from the given byte slice
+// and returns the resulting time.
+func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) {
+ return time.Parse("20060102150405Z0700", string(bytes))
+}
+
+// PrintableString
+
+// parsePrintableString parses a ASN.1 PrintableString from the given byte
+// array and returns it.
+func parsePrintableString(bytes []byte) (ret string, err error) {
+ for _, b := range bytes {
+ if !isPrintable(b) {
+ err = SyntaxError{"PrintableString contains invalid character"}
+ return
+ }
+ }
+ ret = string(bytes)
+ return
+}
+
+// isPrintable returns true iff the given b is in the ASN.1 PrintableString set.
+func isPrintable(b byte) bool {
+ return 'a' <= b && b <= 'z' ||
+ 'A' <= b && b <= 'Z' ||
+ '0' <= b && b <= '9' ||
+ '\'' <= b && b <= ')' ||
+ '+' <= b && b <= '/' ||
+ b == ' ' ||
+ b == ':' ||
+ b == '=' ||
+ b == '?' ||
+ // This is technically not allowed in a PrintableString.
+ // However, x509 certificates with wildcard strings don't
+ // always use the correct string type so we permit it.
+ b == '*'
+}
+
+// IA5String
+
+// parseIA5String parses a ASN.1 IA5String (ASCII string) from the given
+// byte slice and returns it.
+func parseIA5String(bytes []byte) (ret string, err error) {
+ for _, b := range bytes {
+ if b >= 0x80 {
+ err = SyntaxError{"IA5String contains invalid character"}
+ return
+ }
+ }
+ ret = string(bytes)
+ return
+}
+
+// T61String
+
+// parseT61String parses a ASN.1 T61String (8-bit clean string) from the given
+// byte slice and returns it.
+func parseT61String(bytes []byte) (ret string, err error) {
+ return string(bytes), nil
+}
+
+// UTF8String
+
+// parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte
+// array and returns it.
+func parseUTF8String(bytes []byte) (ret string, err error) {
+ return string(bytes), nil
+}
+
+// A RawValue represents an undecoded ASN.1 object.
+type RawValue struct {
+ Class, Tag int
+ IsCompound bool
+ Bytes []byte
+ FullBytes []byte // includes the tag and length
+}
+
+// RawContent is used to signal that the undecoded, DER data needs to be
+// preserved for a struct. To use it, the first field of the struct must have
+// this type. It's an error for any of the other fields to have this type.
+type RawContent []byte
+
+// Tagging
+
+// parseTagAndLength parses an ASN.1 tag and length pair from the given offset
+// into a byte slice. It returns the parsed data and the new offset. SET and
+// SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we
+// don't distinguish between ordered and unordered objects in this code.
+func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) {
+ offset = initOffset
+ b := bytes[offset]
+ offset++
+ ret.class = int(b >> 6)
+ ret.isCompound = b&0x20 == 0x20
+ ret.tag = int(b & 0x1f)
+
+ // If the bottom five bits are set, then the tag number is actually base 128
+ // encoded afterwards
+ if ret.tag == 0x1f {
+ ret.tag, offset, err = parseBase128Int(bytes, offset)
+ if err != nil {
+ return
+ }
+ }
+ if offset >= len(bytes) {
+ err = SyntaxError{"truncated tag or length"}
+ return
+ }
+ b = bytes[offset]
+ offset++
+ if b&0x80 == 0 {
+ // The length is encoded in the bottom 7 bits.
+ ret.length = int(b & 0x7f)
+ } else {
+ // Bottom 7 bits give the number of length bytes to follow.
+ numBytes := int(b & 0x7f)
+ if numBytes == 0 {
+ err = SyntaxError{"indefinite length found (not DER)"}
+ return
+ }
+ ret.length = 0
+ for i := 0; i < numBytes; i++ {
+ if offset >= len(bytes) {
+ err = SyntaxError{"truncated tag or length"}
+ return
+ }
+ b = bytes[offset]
+ offset++
+ if ret.length >= 1<<23 {
+ // We can't shift ret.length up without
+ // overflowing.
+ err = StructuralError{"length too large"}
+ return
+ }
+ ret.length <<= 8
+ ret.length |= int(b)
+ if ret.length == 0 {
+ // DER requires that lengths be minimal.
+ err = StructuralError{"superfluous leading zeros in length"}
+ return
+ }
+ }
+ }
+
+ return
+}
+
+// parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse
+// a number of ASN.1 values from the given byte slice and returns them as a
+// slice of Go values of the given type.
+func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) {
+ expectedTag, compoundType, ok := getUniversalType(elemType)
+ if !ok {
+ err = StructuralError{"unknown Go type for slice"}
+ return
+ }
+
+ // First we iterate over the input and count the number of elements,
+ // checking that the types are correct in each case.
+ numElements := 0
+ for offset := 0; offset < len(bytes); {
+ var t tagAndLength
+ t, offset, err = parseTagAndLength(bytes, offset)
+ if err != nil {
+ return
+ }
+ // We pretend that GENERAL STRINGs are PRINTABLE STRINGs so
+ // that a sequence of them can be parsed into a []string.
+ if t.tag == tagGeneralString {
+ t.tag = tagPrintableString
+ }
+ if t.class != classUniversal || t.isCompound != compoundType || t.tag != expectedTag {
+ err = StructuralError{"sequence tag mismatch"}
+ return
+ }
+ if invalidLength(offset, t.length, len(bytes)) {
+ err = SyntaxError{"truncated sequence"}
+ return
+ }
+ offset += t.length
+ numElements++
+ }
+ ret = reflect.MakeSlice(sliceType, numElements, numElements)
+ params := fieldParameters{}
+ offset := 0
+ for i := 0; i < numElements; i++ {
+ offset, err = parseField(ret.Index(i), bytes, offset, params)
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+var (
+ bitStringType = reflect.TypeOf(BitString{})
+ objectIdentifierType = reflect.TypeOf(ObjectIdentifier{})
+ enumeratedType = reflect.TypeOf(Enumerated(0))
+ flagType = reflect.TypeOf(Flag(false))
+ timeType = reflect.TypeOf(time.Time{})
+ rawValueType = reflect.TypeOf(RawValue{})
+ rawContentsType = reflect.TypeOf(RawContent(nil))
+ bigIntType = reflect.TypeOf(new(big.Int))
+)
+
+// invalidLength returns true iff offset + length > sliceLength, or if the
+// addition would overflow.
+func invalidLength(offset, length, sliceLength int) bool {
+ return offset+length < offset || offset+length > sliceLength
+}
+
+// START CT CHANGES
+
+// Tests whether the data in |bytes| would be a valid ISO8859-1 string.
+// Clearly, a sequence of bytes comprised solely of valid ISO8859-1
+// codepoints does not imply that the encoding MUST be ISO8859-1, rather that
+// you would not encounter an error trying to interpret the data as such.
+func couldBeISO8859_1(bytes []byte) bool {
+ for _, b := range bytes {
+ if b < 0x20 || (b >= 0x7F && b < 0xA0) {
+ return false
+ }
+ }
+ return true
+}
+
+// Checks whether the data in |bytes| would be a valid T.61 string.
+// Clearly, a sequence of bytes comprised solely of valid T.61
+// codepoints does not imply that the encoding MUST be T.61, rather that
+// you would not encounter an error trying to interpret the data as such.
+func couldBeT61(bytes []byte) bool {
+ for _, b := range bytes {
+ switch b {
+ case 0x00:
+ // Since we're guessing at (incorrect) encodings for a
+ // PrintableString, we'll err on the side of caution and disallow
+ // strings with a NUL in them, don't want to re-create a PayPal NUL
+ // situation in monitors.
+ fallthrough
+ case 0x23, 0x24, 0x5C, 0x5E, 0x60, 0x7B, 0x7D, 0x7E, 0xA5, 0xA6, 0xAC, 0xAD, 0xAE, 0xAF,
+ 0xB9, 0xBA, 0xC0, 0xC9, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9,
+ 0xDA, 0xDB, 0xDC, 0xDE, 0xDF, 0xE5, 0xFF:
+ // These are all invalid code points in T.61, so it can't be a T.61 string.
+ return false
+ }
+ }
+ return true
+}
+
+// Converts the data in |bytes| to the equivalent UTF-8 string.
+func iso8859_1ToUTF8(bytes []byte) string {
+ buf := make([]rune, len(bytes))
+ for i, b := range bytes {
+ buf[i] = rune(b)
+ }
+ return string(buf)
+}
+
+// END CT CHANGES
+
+// parseField is the main parsing function. Given a byte slice and an offset
+// into the array, it will try to parse a suitable ASN.1 value out and store it
+// in the given Value.
+func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) {
+ offset = initOffset
+ fieldType := v.Type()
+
+ // If we have run out of data, it may be that there are optional elements at the end.
+ if offset == len(bytes) {
+ if !setDefaultValue(v, params) {
+ err = SyntaxError{"sequence truncated"}
+ }
+ return
+ }
+
+ // Deal with raw values.
+ if fieldType == rawValueType {
+ var t tagAndLength
+ t, offset, err = parseTagAndLength(bytes, offset)
+ if err != nil {
+ return
+ }
+ if invalidLength(offset, t.length, len(bytes)) {
+ err = SyntaxError{"data truncated"}
+ return
+ }
+ result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length], bytes[initOffset : offset+t.length]}
+ offset += t.length
+ v.Set(reflect.ValueOf(result))
+ return
+ }
+
+ // Deal with the ANY type.
+ if ifaceType := fieldType; ifaceType.Kind() == reflect.Interface && ifaceType.NumMethod() == 0 {
+ var t tagAndLength
+ t, offset, err = parseTagAndLength(bytes, offset)
+ if err != nil {
+ return
+ }
+ if invalidLength(offset, t.length, len(bytes)) {
+ err = SyntaxError{"data truncated"}
+ return
+ }
+ var result interface{}
+ if !t.isCompound && t.class == classUniversal {
+ innerBytes := bytes[offset : offset+t.length]
+ switch t.tag {
+ case tagPrintableString:
+ result, err = parsePrintableString(innerBytes)
+ // START CT CHANGES
+ if err != nil && strings.Contains(err.Error(), "PrintableString contains invalid character") {
+ // Probably an ISO8859-1 string stuffed in, check if it
+ // would be valid and assume that's what's happened if so,
+ // otherwise try T.61, failing that give up and just assign
+ // the bytes
+ switch {
+ case couldBeISO8859_1(innerBytes):
+ result, err = iso8859_1ToUTF8(innerBytes), nil
+ case couldBeT61(innerBytes):
+ result, err = parseT61String(innerBytes)
+ default:
+ result = nil
+ err = errors.New("PrintableString contains invalid character, but couldn't determine correct String type.")
+ }
+ }
+ // END CT CHANGES
+ case tagIA5String:
+ result, err = parseIA5String(innerBytes)
+ case tagT61String:
+ result, err = parseT61String(innerBytes)
+ case tagUTF8String:
+ result, err = parseUTF8String(innerBytes)
+ case tagInteger:
+ result, err = parseInt64(innerBytes)
+ case tagBitString:
+ result, err = parseBitString(innerBytes)
+ case tagOID:
+ result, err = parseObjectIdentifier(innerBytes)
+ case tagUTCTime:
+ result, err = parseUTCTime(innerBytes)
+ case tagOctetString:
+ result = innerBytes
+ default:
+ // If we don't know how to handle the type, we just leave Value as nil.
+ }
+ }
+ offset += t.length
+ if err != nil {
+ return
+ }
+ if result != nil {
+ v.Set(reflect.ValueOf(result))
+ }
+ return
+ }
+ universalTag, compoundType, ok1 := getUniversalType(fieldType)
+ if !ok1 {
+ err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)}
+ return
+ }
+
+ t, offset, err := parseTagAndLength(bytes, offset)
+ if err != nil {
+ return
+ }
+ if params.explicit {
+ expectedClass := classContextSpecific
+ if params.application {
+ expectedClass = classApplication
+ }
+ if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) {
+ if t.length > 0 {
+ t, offset, err = parseTagAndLength(bytes, offset)
+ if err != nil {
+ return
+ }
+ } else {
+ if fieldType != flagType {
+ err = StructuralError{"zero length explicit tag was not an asn1.Flag"}
+ return
+ }
+ v.SetBool(true)
+ return
+ }
+ } else {
+ // The tags didn't match, it might be an optional element.
+ ok := setDefaultValue(v, params)
+ if ok {
+ offset = initOffset
+ } else {
+ err = StructuralError{"explicitly tagged member didn't match"}
+ }
+ return
+ }
+ }
+
+ // Special case for strings: all the ASN.1 string types map to the Go
+ // type string. getUniversalType returns the tag for PrintableString
+ // when it sees a string, so if we see a different string type on the
+ // wire, we change the universal type to match.
+ if universalTag == tagPrintableString {
+ switch t.tag {
+ case tagIA5String, tagGeneralString, tagT61String, tagUTF8String:
+ universalTag = t.tag
+ }
+ }
+
+ // Special case for time: UTCTime and GeneralizedTime both map to the
+ // Go type time.Time.
+ if universalTag == tagUTCTime && t.tag == tagGeneralizedTime {
+ universalTag = tagGeneralizedTime
+ }
+
+ expectedClass := classUniversal
+ expectedTag := universalTag
+
+ if !params.explicit && params.tag != nil {
+ expectedClass = classContextSpecific
+ expectedTag = *params.tag
+ }
+
+ if !params.explicit && params.application && params.tag != nil {
+ expectedClass = classApplication
+ expectedTag = *params.tag
+ }
+
+ // We have unwrapped any explicit tagging at this point.
+ if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType {
+ // Tags don't match. Again, it could be an optional element.
+ ok := setDefaultValue(v, params)
+ if ok {
+ offset = initOffset
+ } else {
+ err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)}
+ }
+ return
+ }
+ if invalidLength(offset, t.length, len(bytes)) {
+ err = SyntaxError{"data truncated"}
+ return
+ }
+ innerBytes := bytes[offset : offset+t.length]
+ offset += t.length
+
+ // We deal with the structures defined in this package first.
+ switch fieldType {
+ case objectIdentifierType:
+ newSlice, err1 := parseObjectIdentifier(innerBytes)
+ v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice)))
+ if err1 == nil {
+ reflect.Copy(v, reflect.ValueOf(newSlice))
+ }
+ err = err1
+ return
+ case bitStringType:
+ bs, err1 := parseBitString(innerBytes)
+ if err1 == nil {
+ v.Set(reflect.ValueOf(bs))
+ }
+ err = err1
+ return
+ case timeType:
+ var time time.Time
+ var err1 error
+ if universalTag == tagUTCTime {
+ time, err1 = parseUTCTime(innerBytes)
+ } else {
+ time, err1 = parseGeneralizedTime(innerBytes)
+ }
+ if err1 == nil {
+ v.Set(reflect.ValueOf(time))
+ }
+ err = err1
+ return
+ case enumeratedType:
+ parsedInt, err1 := parseInt32(innerBytes)
+ if err1 == nil {
+ v.SetInt(int64(parsedInt))
+ }
+ err = err1
+ return
+ case flagType:
+ v.SetBool(true)
+ return
+ case bigIntType:
+ parsedInt := parseBigInt(innerBytes)
+ v.Set(reflect.ValueOf(parsedInt))
+ return
+ }
+ switch val := v; val.Kind() {
+ case reflect.Bool:
+ parsedBool, err1 := parseBool(innerBytes)
+ if err1 == nil {
+ val.SetBool(parsedBool)
+ }
+ err = err1
+ return
+ case reflect.Int, reflect.Int32, reflect.Int64:
+ if val.Type().Size() == 4 {
+ parsedInt, err1 := parseInt32(innerBytes)
+ if err1 == nil {
+ val.SetInt(int64(parsedInt))
+ }
+ err = err1
+ } else {
+ parsedInt, err1 := parseInt64(innerBytes)
+ if err1 == nil {
+ val.SetInt(parsedInt)
+ }
+ err = err1
+ }
+ return
+ // TODO(dfc) Add support for the remaining integer types
+ case reflect.Struct:
+ structType := fieldType
+
+ if structType.NumField() > 0 &&
+ structType.Field(0).Type == rawContentsType {
+ bytes := bytes[initOffset:offset]
+ val.Field(0).Set(reflect.ValueOf(RawContent(bytes)))
+ }
+
+ innerOffset := 0
+ for i := 0; i < structType.NumField(); i++ {
+ field := structType.Field(i)
+ if i == 0 && field.Type == rawContentsType {
+ continue
+ }
+ innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1")))
+ if err != nil {
+ return
+ }
+ }
+ // We allow extra bytes at the end of the SEQUENCE because
+ // adding elements to the end has been used in X.509 as the
+ // version numbers have increased.
+ return
+ case reflect.Slice:
+ sliceType := fieldType
+ if sliceType.Elem().Kind() == reflect.Uint8 {
+ val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes)))
+ reflect.Copy(val, reflect.ValueOf(innerBytes))
+ return
+ }
+ newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem())
+ if err1 == nil {
+ val.Set(newSlice)
+ }
+ err = err1
+ return
+ case reflect.String:
+ var v string
+ switch universalTag {
+ case tagPrintableString:
+ v, err = parsePrintableString(innerBytes)
+ case tagIA5String:
+ v, err = parseIA5String(innerBytes)
+ case tagT61String:
+ v, err = parseT61String(innerBytes)
+ case tagUTF8String:
+ v, err = parseUTF8String(innerBytes)
+ case tagGeneralString:
+ // GeneralString is specified in ISO-2022/ECMA-35,
+ // A brief review suggests that it includes structures
+ // that allow the encoding to change midstring and
+ // such. We give up and pass it as an 8-bit string.
+ v, err = parseT61String(innerBytes)
+ default:
+ err = SyntaxError{fmt.Sprintf("internal error: unknown string type %d", universalTag)}
+ }
+ if err == nil {
+ val.SetString(v)
+ }
+ return
+ }
+ err = StructuralError{"unsupported: " + v.Type().String()}
+ return
+}
+
+// setDefaultValue is used to install a default value, from a tag string, into
+// a Value. It is successful is the field was optional, even if a default value
+// wasn't provided or it failed to install it into the Value.
+func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
+ if !params.optional {
+ return
+ }
+ ok = true
+ if params.defaultValue == nil {
+ return
+ }
+ switch val := v; val.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ val.SetInt(*params.defaultValue)
+ }
+ return
+}
+
+// Unmarshal parses the DER-encoded ASN.1 data structure b
+// and uses the reflect package to fill in an arbitrary value pointed at by val.
+// Because Unmarshal uses the reflect package, the structs
+// being written to must use upper case field names.
+//
+// An ASN.1 INTEGER can be written to an int, int32, int64,
+// or *big.Int (from the math/big package).
+// If the encoded value does not fit in the Go type,
+// Unmarshal returns a parse error.
+//
+// An ASN.1 BIT STRING can be written to a BitString.
+//
+// An ASN.1 OCTET STRING can be written to a []byte.
+//
+// An ASN.1 OBJECT IDENTIFIER can be written to an
+// ObjectIdentifier.
+//
+// An ASN.1 ENUMERATED can be written to an Enumerated.
+//
+// An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time.
+//
+// An ASN.1 PrintableString or IA5String can be written to a string.
+//
+// Any of the above ASN.1 values can be written to an interface{}.
+// The value stored in the interface has the corresponding Go type.
+// For integers, that type is int64.
+//
+// An ASN.1 SEQUENCE OF x or SET OF x can be written
+// to a slice if an x can be written to the slice's element type.
+//
+// An ASN.1 SEQUENCE or SET can be written to a struct
+// if each of the elements in the sequence can be
+// written to the corresponding element in the struct.
+//
+// The following tags on struct fields have special meaning to Unmarshal:
+//
+// optional marks the field as ASN.1 OPTIONAL
+// [explicit] tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC
+// default:x sets the default value for optional integer fields
+//
+// If the type of the first field of a structure is RawContent then the raw
+// ASN1 contents of the struct will be stored in it.
+//
+// Other ASN.1 types are not supported; if it encounters them,
+// Unmarshal returns a parse error.
+func Unmarshal(b []byte, val interface{}) (rest []byte, err error) {
+ return UnmarshalWithParams(b, val, "")
+}
+
+// UnmarshalWithParams allows field parameters to be specified for the
+// top-level element. The form of the params is the same as the field tags.
+func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) {
+ v := reflect.ValueOf(val).Elem()
+ offset, err := parseField(v, b, 0, parseFieldParameters(params))
+ if err != nil {
+ return nil, err
+ }
+ return b[offset:], nil
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/asn1/common.go b/vendor/github.com/google/certificate-transparency/go/asn1/common.go
new file mode 100755
index 0000000..33a117e
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/asn1/common.go
@@ -0,0 +1,163 @@
+// Copyright 2009 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 asn1
+
+import (
+ "reflect"
+ "strconv"
+ "strings"
+)
+
+// ASN.1 objects have metadata preceding them:
+// the tag: the type of the object
+// a flag denoting if this object is compound or not
+// the class type: the namespace of the tag
+// the length of the object, in bytes
+
+// Here are some standard tags and classes
+
+const (
+ tagBoolean = 1
+ tagInteger = 2
+ tagBitString = 3
+ tagOctetString = 4
+ tagOID = 6
+ tagEnum = 10
+ tagUTF8String = 12
+ tagSequence = 16
+ tagSet = 17
+ tagPrintableString = 19
+ tagT61String = 20
+ tagIA5String = 22
+ tagUTCTime = 23
+ tagGeneralizedTime = 24
+ tagGeneralString = 27
+)
+
+const (
+ classUniversal = 0
+ classApplication = 1
+ classContextSpecific = 2
+ classPrivate = 3
+)
+
+type tagAndLength struct {
+ class, tag, length int
+ isCompound bool
+}
+
+// ASN.1 has IMPLICIT and EXPLICIT tags, which can be translated as "instead
+// of" and "in addition to". When not specified, every primitive type has a
+// default tag in the UNIVERSAL class.
+//
+// For example: a BIT STRING is tagged [UNIVERSAL 3] by default (although ASN.1
+// doesn't actually have a UNIVERSAL keyword). However, by saying [IMPLICIT
+// CONTEXT-SPECIFIC 42], that means that the tag is replaced by another.
+//
+// On the other hand, if it said [EXPLICIT CONTEXT-SPECIFIC 10], then an
+// /additional/ tag would wrap the default tag. This explicit tag will have the
+// compound flag set.
+//
+// (This is used in order to remove ambiguity with optional elements.)
+//
+// You can layer EXPLICIT and IMPLICIT tags to an arbitrary depth, however we
+// don't support that here. We support a single layer of EXPLICIT or IMPLICIT
+// tagging with tag strings on the fields of a structure.
+
+// fieldParameters is the parsed representation of tag string from a structure field.
+type fieldParameters struct {
+ optional bool // true iff the field is OPTIONAL
+ explicit bool // true iff an EXPLICIT tag is in use.
+ application bool // true iff an APPLICATION tag is in use.
+ defaultValue *int64 // a default value for INTEGER typed fields (maybe nil).
+ tag *int // the EXPLICIT or IMPLICIT tag (maybe nil).
+ stringType int // the string tag to use when marshaling.
+ set bool // true iff this should be encoded as a SET
+ omitEmpty bool // true iff this should be omitted if empty when marshaling.
+
+ // Invariants:
+ // if explicit is set, tag is non-nil.
+}
+
+// Given a tag string with the format specified in the package comment,
+// parseFieldParameters will parse it into a fieldParameters structure,
+// ignoring unknown parts of the string.
+func parseFieldParameters(str string) (ret fieldParameters) {
+ for _, part := range strings.Split(str, ",") {
+ switch {
+ case part == "optional":
+ ret.optional = true
+ case part == "explicit":
+ ret.explicit = true
+ if ret.tag == nil {
+ ret.tag = new(int)
+ }
+ case part == "ia5":
+ ret.stringType = tagIA5String
+ case part == "printable":
+ ret.stringType = tagPrintableString
+ case part == "utf8":
+ ret.stringType = tagUTF8String
+ case strings.HasPrefix(part, "default:"):
+ i, err := strconv.ParseInt(part[8:], 10, 64)
+ if err == nil {
+ ret.defaultValue = new(int64)
+ *ret.defaultValue = i
+ }
+ case strings.HasPrefix(part, "tag:"):
+ i, err := strconv.Atoi(part[4:])
+ if err == nil {
+ ret.tag = new(int)
+ *ret.tag = i
+ }
+ case part == "set":
+ ret.set = true
+ case part == "application":
+ ret.application = true
+ if ret.tag == nil {
+ ret.tag = new(int)
+ }
+ case part == "omitempty":
+ ret.omitEmpty = true
+ }
+ }
+ return
+}
+
+// Given a reflected Go type, getUniversalType returns the default tag number
+// and expected compound flag.
+func getUniversalType(t reflect.Type) (tagNumber int, isCompound, ok bool) {
+ switch t {
+ case objectIdentifierType:
+ return tagOID, false, true
+ case bitStringType:
+ return tagBitString, false, true
+ case timeType:
+ return tagUTCTime, false, true
+ case enumeratedType:
+ return tagEnum, false, true
+ case bigIntType:
+ return tagInteger, false, true
+ }
+ switch t.Kind() {
+ case reflect.Bool:
+ return tagBoolean, false, true
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ return tagInteger, false, true
+ case reflect.Struct:
+ return tagSequence, true, true
+ case reflect.Slice:
+ if t.Elem().Kind() == reflect.Uint8 {
+ return tagOctetString, false, true
+ }
+ if strings.HasSuffix(t.Name(), "SET") {
+ return tagSet, true, true
+ }
+ return tagSequence, true, true
+ case reflect.String:
+ return tagPrintableString, false, true
+ }
+ return 0, false, false
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/asn1/marshal.go b/vendor/github.com/google/certificate-transparency/go/asn1/marshal.go
new file mode 100755
index 0000000..ed17e41
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/asn1/marshal.go
@@ -0,0 +1,581 @@
+// Copyright 2009 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 asn1
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "math/big"
+ "reflect"
+ "time"
+ "unicode/utf8"
+)
+
+// A forkableWriter is an in-memory buffer that can be
+// 'forked' to create new forkableWriters that bracket the
+// original. After
+// pre, post := w.fork();
+// the overall sequence of bytes represented is logically w+pre+post.
+type forkableWriter struct {
+ *bytes.Buffer
+ pre, post *forkableWriter
+}
+
+func newForkableWriter() *forkableWriter {
+ return &forkableWriter{new(bytes.Buffer), nil, nil}
+}
+
+func (f *forkableWriter) fork() (pre, post *forkableWriter) {
+ if f.pre != nil || f.post != nil {
+ panic("have already forked")
+ }
+ f.pre = newForkableWriter()
+ f.post = newForkableWriter()
+ return f.pre, f.post
+}
+
+func (f *forkableWriter) Len() (l int) {
+ l += f.Buffer.Len()
+ if f.pre != nil {
+ l += f.pre.Len()
+ }
+ if f.post != nil {
+ l += f.post.Len()
+ }
+ return
+}
+
+func (f *forkableWriter) writeTo(out io.Writer) (n int, err error) {
+ n, err = out.Write(f.Bytes())
+ if err != nil {
+ return
+ }
+
+ var nn int
+
+ if f.pre != nil {
+ nn, err = f.pre.writeTo(out)
+ n += nn
+ if err != nil {
+ return
+ }
+ }
+
+ if f.post != nil {
+ nn, err = f.post.writeTo(out)
+ n += nn
+ }
+ return
+}
+
+func marshalBase128Int(out *forkableWriter, n int64) (err error) {
+ if n == 0 {
+ err = out.WriteByte(0)
+ return
+ }
+
+ l := 0
+ for i := n; i > 0; i >>= 7 {
+ l++
+ }
+
+ for i := l - 1; i >= 0; i-- {
+ o := byte(n >> uint(i*7))
+ o &= 0x7f
+ if i != 0 {
+ o |= 0x80
+ }
+ err = out.WriteByte(o)
+ if err != nil {
+ return
+ }
+ }
+
+ return nil
+}
+
+func marshalInt64(out *forkableWriter, i int64) (err error) {
+ n := int64Length(i)
+
+ for ; n > 0; n-- {
+ err = out.WriteByte(byte(i >> uint((n-1)*8)))
+ if err != nil {
+ return
+ }
+ }
+
+ return nil
+}
+
+func int64Length(i int64) (numBytes int) {
+ numBytes = 1
+
+ for i > 127 {
+ numBytes++
+ i >>= 8
+ }
+
+ for i < -128 {
+ numBytes++
+ i >>= 8
+ }
+
+ return
+}
+
+func marshalBigInt(out *forkableWriter, n *big.Int) (err error) {
+ 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 {
+ err = out.WriteByte(0xff)
+ if err != nil {
+ return
+ }
+ }
+ _, err = out.Write(bytes)
+ } else if n.Sign() == 0 {
+ // Zero is written as a single 0 zero rather than no bytes.
+ err = out.WriteByte(0x00)
+ } else {
+ bytes := n.Bytes()
+ if len(bytes) > 0 && bytes[0]&0x80 != 0 {
+ // We'll have to pad this with 0x00 in order to stop it
+ // looking like a negative number.
+ err = out.WriteByte(0)
+ if err != nil {
+ return
+ }
+ }
+ _, err = out.Write(bytes)
+ }
+ return
+}
+
+func marshalLength(out *forkableWriter, i int) (err error) {
+ n := lengthLength(i)
+
+ for ; n > 0; n-- {
+ err = out.WriteByte(byte(i >> uint((n-1)*8)))
+ if err != nil {
+ return
+ }
+ }
+
+ return nil
+}
+
+func lengthLength(i int) (numBytes int) {
+ numBytes = 1
+ for i > 255 {
+ numBytes++
+ i >>= 8
+ }
+ return
+}
+
+func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err error) {
+ b := uint8(t.class) << 6
+ if t.isCompound {
+ b |= 0x20
+ }
+ if t.tag >= 31 {
+ b |= 0x1f
+ err = out.WriteByte(b)
+ if err != nil {
+ return
+ }
+ err = marshalBase128Int(out, int64(t.tag))
+ if err != nil {
+ return
+ }
+ } else {
+ b |= uint8(t.tag)
+ err = out.WriteByte(b)
+ if err != nil {
+ return
+ }
+ }
+
+ if t.length >= 128 {
+ l := lengthLength(t.length)
+ err = out.WriteByte(0x80 | byte(l))
+ if err != nil {
+ return
+ }
+ err = marshalLength(out, t.length)
+ if err != nil {
+ return
+ }
+ } else {
+ err = out.WriteByte(byte(t.length))
+ if err != nil {
+ return
+ }
+ }
+
+ return nil
+}
+
+func marshalBitString(out *forkableWriter, b BitString) (err error) {
+ paddingBits := byte((8 - b.BitLength%8) % 8)
+ err = out.WriteByte(paddingBits)
+ if err != nil {
+ return
+ }
+ _, err = out.Write(b.Bytes)
+ return
+}
+
+func marshalObjectIdentifier(out *forkableWriter, oid []int) (err error) {
+ if len(oid) < 2 || oid[0] > 2 || (oid[0] < 2 && oid[1] >= 40) {
+ return StructuralError{"invalid object identifier"}
+ }
+
+ err = marshalBase128Int(out, int64(oid[0]*40+oid[1]))
+ if err != nil {
+ return
+ }
+ for i := 2; i < len(oid); i++ {
+ err = marshalBase128Int(out, int64(oid[i]))
+ if err != nil {
+ return
+ }
+ }
+
+ return
+}
+
+func marshalPrintableString(out *forkableWriter, s string) (err error) {
+ b := []byte(s)
+ for _, c := range b {
+ if !isPrintable(c) {
+ return StructuralError{"PrintableString contains invalid character"}
+ }
+ }
+
+ _, err = out.Write(b)
+ return
+}
+
+func marshalIA5String(out *forkableWriter, s string) (err error) {
+ b := []byte(s)
+ for _, c := range b {
+ if c > 127 {
+ return StructuralError{"IA5String contains invalid character"}
+ }
+ }
+
+ _, err = out.Write(b)
+ return
+}
+
+func marshalUTF8String(out *forkableWriter, s string) (err error) {
+ _, err = out.Write([]byte(s))
+ return
+}
+
+func marshalTwoDigits(out *forkableWriter, v int) (err error) {
+ err = out.WriteByte(byte('0' + (v/10)%10))
+ if err != nil {
+ return
+ }
+ return out.WriteByte(byte('0' + v%10))
+}
+
+func marshalUTCTime(out *forkableWriter, t time.Time) (err error) {
+ year, month, day := t.Date()
+
+ switch {
+ case 1950 <= year && year < 2000:
+ err = marshalTwoDigits(out, int(year-1900))
+ case 2000 <= year && year < 2050:
+ err = marshalTwoDigits(out, int(year-2000))
+ default:
+ return StructuralError{"cannot represent time as UTCTime"}
+ }
+ if err != nil {
+ return
+ }
+
+ err = marshalTwoDigits(out, int(month))
+ if err != nil {
+ return
+ }
+
+ err = marshalTwoDigits(out, day)
+ if err != nil {
+ return
+ }
+
+ hour, min, sec := t.Clock()
+
+ err = marshalTwoDigits(out, hour)
+ if err != nil {
+ return
+ }
+
+ err = marshalTwoDigits(out, min)
+ if err != nil {
+ return
+ }
+
+ err = marshalTwoDigits(out, sec)
+ if err != nil {
+ return
+ }
+
+ _, offset := t.Zone()
+
+ switch {
+ case offset/60 == 0:
+ err = out.WriteByte('Z')
+ return
+ case offset > 0:
+ err = out.WriteByte('+')
+ case offset < 0:
+ err = out.WriteByte('-')
+ }
+
+ if err != nil {
+ return
+ }
+
+ offsetMinutes := offset / 60
+ if offsetMinutes < 0 {
+ offsetMinutes = -offsetMinutes
+ }
+
+ err = marshalTwoDigits(out, offsetMinutes/60)
+ if err != nil {
+ return
+ }
+
+ err = marshalTwoDigits(out, offsetMinutes%60)
+ return
+}
+
+func stripTagAndLength(in []byte) []byte {
+ _, offset, err := parseTagAndLength(in, 0)
+ if err != nil {
+ return in
+ }
+ return in[offset:]
+}
+
+func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameters) (err error) {
+ switch value.Type() {
+ case timeType:
+ return marshalUTCTime(out, value.Interface().(time.Time))
+ case bitStringType:
+ return marshalBitString(out, value.Interface().(BitString))
+ case objectIdentifierType:
+ return marshalObjectIdentifier(out, value.Interface().(ObjectIdentifier))
+ case bigIntType:
+ return marshalBigInt(out, value.Interface().(*big.Int))
+ }
+
+ switch v := value; v.Kind() {
+ case reflect.Bool:
+ if v.Bool() {
+ return out.WriteByte(255)
+ } else {
+ return out.WriteByte(0)
+ }
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ return marshalInt64(out, int64(v.Int()))
+ case reflect.Struct:
+ t := v.Type()
+
+ startingField := 0
+
+ // If the first element of the structure is a non-empty
+ // RawContents, then we don't bother serializing the rest.
+ if t.NumField() > 0 && t.Field(0).Type == rawContentsType {
+ s := v.Field(0)
+ if s.Len() > 0 {
+ bytes := make([]byte, s.Len())
+ for i := 0; i < s.Len(); i++ {
+ bytes[i] = uint8(s.Index(i).Uint())
+ }
+ /* The RawContents will contain the tag and
+ * length fields but we'll also be writing
+ * those ourselves, so we strip them out of
+ * bytes */
+ _, err = out.Write(stripTagAndLength(bytes))
+ return
+ } else {
+ startingField = 1
+ }
+ }
+
+ for i := startingField; i < t.NumField(); i++ {
+ var pre *forkableWriter
+ pre, out = out.fork()
+ err = marshalField(pre, v.Field(i), parseFieldParameters(t.Field(i).Tag.Get("asn1")))
+ if err != nil {
+ return
+ }
+ }
+ return
+ case reflect.Slice:
+ sliceType := v.Type()
+ if sliceType.Elem().Kind() == reflect.Uint8 {
+ bytes := make([]byte, v.Len())
+ for i := 0; i < v.Len(); i++ {
+ bytes[i] = uint8(v.Index(i).Uint())
+ }
+ _, err = out.Write(bytes)
+ return
+ }
+
+ var fp fieldParameters
+ for i := 0; i < v.Len(); i++ {
+ var pre *forkableWriter
+ pre, out = out.fork()
+ err = marshalField(pre, v.Index(i), fp)
+ if err != nil {
+ return
+ }
+ }
+ return
+ case reflect.String:
+ switch params.stringType {
+ case tagIA5String:
+ return marshalIA5String(out, v.String())
+ case tagPrintableString:
+ return marshalPrintableString(out, v.String())
+ default:
+ return marshalUTF8String(out, v.String())
+ }
+ }
+
+ return StructuralError{"unknown Go type"}
+}
+
+func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) (err error) {
+ // If the field is an interface{} then recurse into it.
+ if v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 {
+ return marshalField(out, v.Elem(), params)
+ }
+
+ if v.Kind() == reflect.Slice && v.Len() == 0 && params.omitEmpty {
+ return
+ }
+
+ if params.optional && reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) {
+ return
+ }
+
+ if v.Type() == rawValueType {
+ rv := v.Interface().(RawValue)
+ if len(rv.FullBytes) != 0 {
+ _, err = out.Write(rv.FullBytes)
+ } else {
+ err = marshalTagAndLength(out, tagAndLength{rv.Class, rv.Tag, len(rv.Bytes), rv.IsCompound})
+ if err != nil {
+ return
+ }
+ _, err = out.Write(rv.Bytes)
+ }
+ return
+ }
+
+ tag, isCompound, ok := getUniversalType(v.Type())
+ if !ok {
+ err = StructuralError{fmt.Sprintf("unknown Go type: %v", v.Type())}
+ return
+ }
+ class := classUniversal
+
+ if params.stringType != 0 && tag != tagPrintableString {
+ return StructuralError{"explicit string type given to non-string member"}
+ }
+
+ if tag == tagPrintableString {
+ if params.stringType == 0 {
+ // This is a string without an explicit string type. We'll use
+ // a PrintableString if the character set in the string is
+ // sufficiently limited, otherwise we'll use a UTF8String.
+ for _, r := range v.String() {
+ if r >= utf8.RuneSelf || !isPrintable(byte(r)) {
+ if !utf8.ValidString(v.String()) {
+ return errors.New("asn1: string not valid UTF-8")
+ }
+ tag = tagUTF8String
+ break
+ }
+ }
+ } else {
+ tag = params.stringType
+ }
+ }
+
+ if params.set {
+ if tag != tagSequence {
+ return StructuralError{"non sequence tagged as set"}
+ }
+ tag = tagSet
+ }
+
+ tags, body := out.fork()
+
+ err = marshalBody(body, v, params)
+ if err != nil {
+ return
+ }
+
+ bodyLen := body.Len()
+
+ var explicitTag *forkableWriter
+ if params.explicit {
+ explicitTag, tags = tags.fork()
+ }
+
+ if !params.explicit && params.tag != nil {
+ // implicit tag.
+ tag = *params.tag
+ class = classContextSpecific
+ }
+
+ err = marshalTagAndLength(tags, tagAndLength{class, tag, bodyLen, isCompound})
+ if err != nil {
+ return
+ }
+
+ if params.explicit {
+ err = marshalTagAndLength(explicitTag, tagAndLength{
+ class: classContextSpecific,
+ tag: *params.tag,
+ length: bodyLen + tags.Len(),
+ isCompound: true,
+ })
+ }
+
+ return nil
+}
+
+// Marshal returns the ASN.1 encoding of val.
+func Marshal(val interface{}) ([]byte, error) {
+ var out bytes.Buffer
+ v := reflect.ValueOf(val)
+ f := newForkableWriter()
+ err := marshalField(f, v, fieldParameters{})
+ if err != nil {
+ return nil, err
+ }
+ _, err = f.writeTo(&out)
+ return out.Bytes(), nil
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/client/getentries.go b/vendor/github.com/google/certificate-transparency/go/client/getentries.go
new file mode 100644
index 0000000..32be65c
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/client/getentries.go
@@ -0,0 +1,88 @@
+package client
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+
+ ct "github.com/google/certificate-transparency/go"
+ "golang.org/x/net/context"
+)
+
+// LeafEntry respresents a JSON leaf entry.
+type LeafEntry struct {
+ LeafInput []byte `json:"leaf_input"`
+ ExtraData []byte `json:"extra_data"`
+}
+
+// GetEntriesResponse respresents the JSON response to the CT get-entries method.
+type GetEntriesResponse struct {
+ Entries []LeafEntry `json:"entries"` // the list of returned entries
+}
+
+// GetRawEntries exposes the /ct/v1/get-entries result with only the JSON parsing done.
+func GetRawEntries(ctx context.Context, httpClient *http.Client, logURL string, start, end int64) (*GetEntriesResponse, error) {
+ if end < 0 {
+ return nil, errors.New("end should be >= 0")
+ }
+ if end < start {
+ return nil, errors.New("start should be <= end")
+ }
+
+ baseURL, err := url.Parse(strings.TrimRight(logURL, "/") + GetEntriesPath)
+ if err != nil {
+ return nil, err
+ }
+
+ baseURL.RawQuery = url.Values{
+ "start": []string{strconv.FormatInt(start, 10)},
+ "end": []string{strconv.FormatInt(end, 10)},
+ }.Encode()
+
+ var resp GetEntriesResponse
+ err = fetchAndParse(context.TODO(), httpClient, baseURL.String(), &resp)
+ if err != nil {
+ return nil, err
+ }
+
+ return &resp, nil
+}
+
+// GetEntries attempts to retrieve the entries in the sequence [|start|, |end|] from the CT log server. (see section 4.6.)
+// Returns a slice of LeafInputs or a non-nil error.
+func (c *LogClient) GetEntries(start, end int64) ([]ct.LogEntry, error) {
+ resp, err := GetRawEntries(context.TODO(), c.httpClient, c.uri, start, end)
+ if err != nil {
+ return nil, err
+ }
+ entries := make([]ct.LogEntry, len(resp.Entries))
+ for index, entry := range resp.Entries {
+ leaf, err := ct.ReadMerkleTreeLeaf(bytes.NewBuffer(entry.LeafInput))
+ if err != nil {
+ return nil, err
+ }
+ entries[index].Leaf = *leaf
+
+ var chain []ct.ASN1Cert
+ switch leaf.TimestampedEntry.EntryType {
+ case ct.X509LogEntryType:
+ chain, err = ct.UnmarshalX509ChainArray(entry.ExtraData)
+
+ case ct.PrecertLogEntryType:
+ chain, err = ct.UnmarshalPrecertChainArray(entry.ExtraData)
+
+ default:
+ return nil, fmt.Errorf("saw unknown entry type: %v", leaf.TimestampedEntry.EntryType)
+ }
+ if err != nil {
+ return nil, err
+ }
+ entries[index].Chain = chain
+ entries[index].Index = start + int64(index)
+ }
+ return entries, nil
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/client/logclient.go b/vendor/github.com/google/certificate-transparency/go/client/logclient.go
new file mode 100644
index 0000000..7b3dbbc
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/client/logclient.go
@@ -0,0 +1,412 @@
+// Package client is a CT log client implementation and contains types and code
+// for interacting with RFC6962-compliant CT Log instances.
+// See http://tools.ietf.org/html/rfc6962 for details
+package client
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "net/url"
+ "strconv"
+ "time"
+
+ ct "github.com/google/certificate-transparency/go"
+ "golang.org/x/net/context"
+)
+
+// URI paths for CT Log endpoints
+const (
+ AddChainPath = "/ct/v1/add-chain"
+ AddPreChainPath = "/ct/v1/add-pre-chain"
+ AddJSONPath = "/ct/v1/add-json"
+ GetSTHPath = "/ct/v1/get-sth"
+ GetEntriesPath = "/ct/v1/get-entries"
+ GetProofByHashPath = "/ct/v1/get-proof-by-hash"
+ GetSTHConsistencyPath = "/ct/v1/get-sth-consistency"
+)
+
+// LogClient represents a client for a given CT Log instance
+type LogClient struct {
+ uri string // the base URI of the log. e.g. http://ct.googleapis/pilot
+ httpClient *http.Client // used to interact with the log via HTTP
+ verifier *ct.SignatureVerifier // nil if no public key for log available
+}
+
+//////////////////////////////////////////////////////////////////////////////////
+// JSON structures follow.
+// These represent the structures returned by the CT Log server.
+//////////////////////////////////////////////////////////////////////////////////
+
+// addChainRequest represents the JSON request body sent to the add-chain CT
+// method.
+type addChainRequest struct {
+ Chain [][]byte `json:"chain"`
+}
+
+// addChainResponse represents the JSON response to the add-chain CT method.
+// An SCT represents a Log's promise to integrate a [pre-]certificate into the
+// log within a defined period of time.
+type addChainResponse struct {
+ SCTVersion ct.Version `json:"sct_version"` // SCT structure version
+ ID []byte `json:"id"` // Log ID
+ Timestamp uint64 `json:"timestamp"` // Timestamp of issuance
+ Extensions string `json:"extensions"` // Holder for any CT extensions
+ Signature []byte `json:"signature"` // Log signature for this SCT
+}
+
+// addJSONRequest represents the JSON request body sent to the add-json CT
+// method.
+type addJSONRequest struct {
+ Data interface{} `json:"data"`
+}
+
+// getSTHResponse respresents the JSON response to the get-sth CT method
+type getSTHResponse struct {
+ TreeSize uint64 `json:"tree_size"` // Number of certs in the current tree
+ Timestamp uint64 `json:"timestamp"` // Time that the tree was created
+ SHA256RootHash []byte `json:"sha256_root_hash"` // Root hash of the tree
+ TreeHeadSignature []byte `json:"tree_head_signature"` // Log signature for this STH
+}
+
+// getConsistencyProofResponse represents the JSON response to the get-consistency-proof CT method
+type getConsistencyProofResponse struct {
+ Consistency [][]byte `json:"consistency"`
+}
+
+// getAuditProofResponse represents the JSON response to the CT get-audit-proof method
+type getAuditProofResponse struct {
+ Hash []string `json:"hash"` // the hashes which make up the proof
+ TreeSize uint64 `json:"tree_size"` // the tree size against which this proof is constructed
+}
+
+// getAcceptedRootsResponse represents the JSON response to the CT get-roots method.
+type getAcceptedRootsResponse struct {
+ Certificates []string `json:"certificates"`
+}
+
+// getEntryAndProodReponse represents the JSON response to the CT get-entry-and-proof method
+type getEntryAndProofResponse struct {
+ LeafInput string `json:"leaf_input"` // the entry itself
+ ExtraData string `json:"extra_data"` // any chain provided when the entry was added to the log
+ AuditPath []string `json:"audit_path"` // the corresponding proof
+}
+
+// GetProofByHashResponse represents the JSON response to the CT get-proof-by-hash method.
+type GetProofByHashResponse struct {
+ LeafIndex int64 `json:"leaf_index"` // The 0-based index of the end entity corresponding to the "hash" parameter.
+ AuditPath [][]byte `json:"audit_path"` // An array of base64-encoded Merkle Tree nodes proving the inclusion of the chosen certificate.
+}
+
+// New constructs a new LogClient instance.
+// |uri| is the base URI of the CT log instance to interact with, e.g.
+// http://ct.googleapis.com/pilot
+// |hc| is the underlying client to be used for HTTP requests to the CT log.
+func New(uri string, hc *http.Client) *LogClient {
+ if hc == nil {
+ hc = new(http.Client)
+ }
+ return &LogClient{uri: uri, httpClient: hc}
+}
+
+// NewWithPubKey constructs a new LogClient instance that includes public
+// key information for the log; this instance will check signatures on
+// responses from the log.
+func NewWithPubKey(uri string, hc *http.Client, pemEncodedKey string) (*LogClient, error) {
+ pubkey, _, rest, err := ct.PublicKeyFromPEM([]byte(pemEncodedKey))
+ if err != nil {
+ return nil, err
+ }
+ if len(rest) > 0 {
+ return nil, errors.New("extra data found after PEM key decoded")
+ }
+
+ verifier, err := ct.NewSignatureVerifier(pubkey)
+ if err != nil {
+ return nil, err
+ }
+
+ if hc == nil {
+ hc = new(http.Client)
+ }
+ return &LogClient{uri: uri, httpClient: hc, verifier: verifier}, nil
+}
+
+// Makes a HTTP call to |uri|, and attempts to parse the response as a
+// JSON representation of the structure in |res|. Uses |ctx| to
+// control the HTTP call (so it can have a timeout or be cancelled by
+// the caller), and |httpClient| to make the actual HTTP call.
+// Returns a non-nil |error| if there was a problem.
+func fetchAndParse(ctx context.Context, httpClient *http.Client, uri string, res interface{}) error {
+ req, err := http.NewRequest(http.MethodGet, uri, nil)
+ if err != nil {
+ return err
+ }
+ req.Cancel = ctx.Done()
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ // Make sure everything is read, so http.Client can reuse the connection.
+ defer ioutil.ReadAll(resp.Body)
+
+ if resp.StatusCode != 200 {
+ return fmt.Errorf("got HTTP Status %s", resp.Status)
+ }
+
+ if err := json.NewDecoder(resp.Body).Decode(res); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// Makes a HTTP POST call to |uri|, and attempts to parse the response as a JSON
+// representation of the structure in |res|.
+// Returns a non-nil |error| if there was a problem.
+func (c *LogClient) postAndParse(uri string, req interface{}, res interface{}) (*http.Response, string, error) {
+ postBody, err := json.Marshal(req)
+ if err != nil {
+ return nil, "", err
+ }
+ httpReq, err := http.NewRequest(http.MethodPost, uri, bytes.NewReader(postBody))
+ if err != nil {
+ return nil, "", err
+ }
+ httpReq.Header.Set("Content-Type", "application/json")
+ resp, err := c.httpClient.Do(httpReq)
+ // Read all of the body, if there is one, so that the http.Client can do
+ // Keep-Alive:
+ var body []byte
+ if resp != nil {
+ body, err = ioutil.ReadAll(resp.Body)
+ resp.Body.Close()
+ }
+ if err != nil {
+ return resp, string(body), err
+ }
+ if resp.StatusCode == 200 {
+ if err != nil {
+ return resp, string(body), err
+ }
+ if err = json.Unmarshal(body, &res); err != nil {
+ return resp, string(body), err
+ }
+ }
+ return resp, string(body), nil
+}
+
+func backoffForRetry(ctx context.Context, d time.Duration) error {
+ backoffTimer := time.NewTimer(d)
+ if ctx != nil {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-backoffTimer.C:
+ }
+ } else {
+ <-backoffTimer.C
+ }
+ return nil
+}
+
+// Attempts to add |chain| to the log, using the api end-point specified by
+// |path|. If provided context expires before submission is complete an
+// error will be returned.
+func (c *LogClient) addChainWithRetry(ctx context.Context, ctype ct.LogEntryType, path string, chain []ct.ASN1Cert) (*ct.SignedCertificateTimestamp, error) {
+ var resp addChainResponse
+ var req addChainRequest
+ for _, link := range chain {
+ req.Chain = append(req.Chain, link)
+ }
+ httpStatus := "Unknown"
+ backoffSeconds := 0
+ done := false
+ for !done {
+ if backoffSeconds > 0 {
+ log.Printf("Got %s, backing-off %d seconds", httpStatus, backoffSeconds)
+ }
+ err := backoffForRetry(ctx, time.Second*time.Duration(backoffSeconds))
+ if err != nil {
+ return nil, err
+ }
+ if backoffSeconds > 0 {
+ backoffSeconds = 0
+ }
+ httpResp, _, err := c.postAndParse(c.uri+path, &req, &resp)
+ if err != nil {
+ backoffSeconds = 10
+ continue
+ }
+ switch {
+ case httpResp.StatusCode == 200:
+ done = true
+ case httpResp.StatusCode == 408:
+ // request timeout, retry immediately
+ case httpResp.StatusCode == 503:
+ // Retry
+ backoffSeconds = 10
+ if retryAfter := httpResp.Header.Get("Retry-After"); retryAfter != "" {
+ if seconds, err := strconv.Atoi(retryAfter); err == nil {
+ backoffSeconds = seconds
+ }
+ }
+ default:
+ return nil, fmt.Errorf("got HTTP Status %s", httpResp.Status)
+ }
+ httpStatus = httpResp.Status
+ }
+
+ ds, err := ct.UnmarshalDigitallySigned(bytes.NewReader(resp.Signature))
+ if err != nil {
+ return nil, err
+ }
+
+ var logID ct.SHA256Hash
+ copy(logID[:], resp.ID)
+ sct := &ct.SignedCertificateTimestamp{
+ SCTVersion: resp.SCTVersion,
+ LogID: logID,
+ Timestamp: resp.Timestamp,
+ Extensions: ct.CTExtensions(resp.Extensions),
+ Signature: *ds}
+ err = c.VerifySCTSignature(*sct, ctype, chain)
+ if err != nil {
+ return nil, err
+ }
+ return sct, nil
+}
+
+// AddChain adds the (DER represented) X509 |chain| to the log.
+func (c *LogClient) AddChain(chain []ct.ASN1Cert) (*ct.SignedCertificateTimestamp, error) {
+ return c.addChainWithRetry(nil, ct.X509LogEntryType, AddChainPath, chain)
+}
+
+// AddPreChain adds the (DER represented) Precertificate |chain| to the log.
+func (c *LogClient) AddPreChain(chain []ct.ASN1Cert) (*ct.SignedCertificateTimestamp, error) {
+ return c.addChainWithRetry(nil, ct.PrecertLogEntryType, AddPreChainPath, chain)
+}
+
+// AddChainWithContext adds the (DER represented) X509 |chain| to the log and
+// fails if the provided context expires before the chain is submitted.
+func (c *LogClient) AddChainWithContext(ctx context.Context, chain []ct.ASN1Cert) (*ct.SignedCertificateTimestamp, error) {
+ return c.addChainWithRetry(ctx, ct.X509LogEntryType, AddChainPath, chain)
+}
+
+// AddJSON submits arbitrary data to to XJSON server.
+func (c *LogClient) AddJSON(data interface{}) (*ct.SignedCertificateTimestamp, error) {
+ req := addJSONRequest{
+ Data: data,
+ }
+ var resp addChainResponse
+ _, _, err := c.postAndParse(c.uri+AddJSONPath, &req, &resp)
+ if err != nil {
+ return nil, err
+ }
+ ds, err := ct.UnmarshalDigitallySigned(bytes.NewReader(resp.Signature))
+ if err != nil {
+ return nil, err
+ }
+ var logID ct.SHA256Hash
+ copy(logID[:], resp.ID)
+ return &ct.SignedCertificateTimestamp{
+ SCTVersion: resp.SCTVersion,
+ LogID: logID,
+ Timestamp: resp.Timestamp,
+ Extensions: ct.CTExtensions(resp.Extensions),
+ Signature: *ds}, nil
+}
+
+// GetSTH retrieves the current STH from the log.
+// Returns a populated SignedTreeHead, or a non-nil error.
+func (c *LogClient) GetSTH() (sth *ct.SignedTreeHead, err error) {
+ var resp getSTHResponse
+ if err = fetchAndParse(context.TODO(), c.httpClient, c.uri+GetSTHPath, &resp); err != nil {
+ return
+ }
+ sth = &ct.SignedTreeHead{
+ TreeSize: resp.TreeSize,
+ Timestamp: resp.Timestamp,
+ }
+
+ if len(resp.SHA256RootHash) != sha256.Size {
+ return nil, fmt.Errorf("sha256_root_hash is invalid length, expected %d got %d", sha256.Size, len(resp.SHA256RootHash))
+ }
+ copy(sth.SHA256RootHash[:], resp.SHA256RootHash)
+
+ ds, err := ct.UnmarshalDigitallySigned(bytes.NewReader(resp.TreeHeadSignature))
+ if err != nil {
+ return nil, err
+ }
+ sth.TreeHeadSignature = *ds
+ err = c.VerifySTHSignature(*sth)
+ if err != nil {
+ return nil, err
+ }
+ return
+}
+
+// VerifySTHSignature checks the signature in sth, returning any error encountered or nil if verification is
+// successful.
+func (c *LogClient) VerifySTHSignature(sth ct.SignedTreeHead) error {
+ if c.verifier == nil {
+ // Can't verify signatures without a verifier
+ return nil
+ }
+ return c.verifier.VerifySTHSignature(sth)
+}
+
+// VerifySCTSignature checks the signature in sct for the given LogEntryType, with associated certificate chain.
+func (c *LogClient) VerifySCTSignature(sct ct.SignedCertificateTimestamp, ctype ct.LogEntryType, certData []ct.ASN1Cert) error {
+ if c.verifier == nil {
+ // Can't verify signatures without a verifier
+ return nil
+ }
+
+ if ctype == ct.PrecertLogEntryType {
+ // TODO(drysdale): cope with pre-certs, which need to have the
+ // following fields set:
+ // leaf.PrecertEntry.TBSCertificate
+ // leaf.PrecertEntry.IssuerKeyHash (SHA-256 of issuer's public key)
+ return errors.New("SCT verification for pre-certificates unimplemented")
+ }
+ // Build enough of a Merkle tree leaf for the verifier to work on.
+ leaf := ct.MerkleTreeLeaf{
+ Version: sct.SCTVersion,
+ LeafType: ct.TimestampedEntryLeafType,
+ TimestampedEntry: ct.TimestampedEntry{
+ Timestamp: sct.Timestamp,
+ EntryType: ctype,
+ X509Entry: certData[0],
+ Extensions: sct.Extensions}}
+ entry := ct.LogEntry{Leaf: leaf}
+ return c.verifier.VerifySCTSignature(sct, entry)
+}
+
+// GetSTHConsistency retrieves the consistency proof between two snapshots.
+func (c *LogClient) GetSTHConsistency(ctx context.Context, first, second uint64) ([][]byte, error) {
+ u := fmt.Sprintf("%s%s?first=%d&second=%d", c.uri, GetSTHConsistencyPath, first, second)
+ var resp getConsistencyProofResponse
+ if err := fetchAndParse(ctx, c.httpClient, u, &resp); err != nil {
+ return nil, err
+ }
+ return resp.Consistency, nil
+}
+
+// GetProofByHash returns an audit path for the hash of an SCT.
+func (c *LogClient) GetProofByHash(ctx context.Context, hash []byte, treeSize uint64) (*GetProofByHashResponse, error) {
+ b64Hash := url.QueryEscape(base64.StdEncoding.EncodeToString(hash))
+ u := fmt.Sprintf("%s%s?tree_size=%d&hash=%v", c.uri, GetProofByHashPath, treeSize, b64Hash)
+ var resp GetProofByHashResponse
+ if err := fetchAndParse(ctx, c.httpClient, u, &resp); err != nil {
+ return nil, err
+ }
+ return &resp, nil
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/serialization.go b/vendor/github.com/google/certificate-transparency/go/serialization.go
new file mode 100644
index 0000000..b83c901
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/serialization.go
@@ -0,0 +1,691 @@
+package ct
+
+import (
+ "bytes"
+ "container/list"
+ "crypto"
+ "encoding/asn1"
+ "encoding/binary"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+)
+
+// Variable size structure prefix-header byte lengths
+const (
+ CertificateLengthBytes = 3
+ PreCertificateLengthBytes = 3
+ ExtensionsLengthBytes = 2
+ CertificateChainLengthBytes = 3
+ SignatureLengthBytes = 2
+ JSONLengthBytes = 3
+)
+
+// Max lengths
+const (
+ MaxCertificateLength = (1 << 24) - 1
+ MaxExtensionsLength = (1 << 16) - 1
+ MaxSCTInListLength = (1 << 16) - 1
+ MaxSCTListLength = (1 << 16) - 1
+)
+
+func writeUint(w io.Writer, value uint64, numBytes int) error {
+ buf := make([]uint8, numBytes)
+ for i := 0; i < numBytes; i++ {
+ buf[numBytes-i-1] = uint8(value & 0xff)
+ value >>= 8
+ }
+ if value != 0 {
+ return errors.New("numBytes was insufficiently large to represent value")
+ }
+ if _, err := w.Write(buf); err != nil {
+ return err
+ }
+ return nil
+}
+
+func writeVarBytes(w io.Writer, value []byte, numLenBytes int) error {
+ if err := writeUint(w, uint64(len(value)), numLenBytes); err != nil {
+ return err
+ }
+ if _, err := w.Write(value); err != nil {
+ return err
+ }
+ return nil
+}
+
+func readUint(r io.Reader, numBytes int) (uint64, error) {
+ var l uint64
+ for i := 0; i < numBytes; i++ {
+ l <<= 8
+ var t uint8
+ if err := binary.Read(r, binary.BigEndian, &t); err != nil {
+ return 0, err
+ }
+ l |= uint64(t)
+ }
+ return l, nil
+}
+
+// Reads a variable length array of bytes from |r|. |numLenBytes| specifies the
+// number of (BigEndian) prefix-bytes which contain the length of the actual
+// array data bytes that follow.
+// Allocates an array to hold the contents and returns a slice view into it if
+// the read was successful, or an error otherwise.
+func readVarBytes(r io.Reader, numLenBytes int) ([]byte, error) {
+ switch {
+ case numLenBytes > 8:
+ return nil, fmt.Errorf("numLenBytes too large (%d)", numLenBytes)
+ case numLenBytes == 0:
+ return nil, errors.New("numLenBytes should be > 0")
+ }
+ l, err := readUint(r, numLenBytes)
+ if err != nil {
+ return nil, err
+ }
+ data := make([]byte, l)
+ if n, err := io.ReadFull(r, data); err != nil {
+ if err == io.EOF || err == io.ErrUnexpectedEOF {
+ return nil, fmt.Errorf("short read: expected %d but got %d", l, n)
+ }
+ return nil, err
+ }
+ return data, nil
+}
+
+// Reads a list of ASN1Cert types from |r|
+func readASN1CertList(r io.Reader, totalLenBytes int, elementLenBytes int) ([]ASN1Cert, error) {
+ listBytes, err := readVarBytes(r, totalLenBytes)
+ if err != nil {
+ return []ASN1Cert{}, err
+ }
+ list := list.New()
+ listReader := bytes.NewReader(listBytes)
+ var entry []byte
+ for err == nil {
+ entry, err = readVarBytes(listReader, elementLenBytes)
+ if err != nil {
+ if err != io.EOF {
+ return []ASN1Cert{}, err
+ }
+ } else {
+ list.PushBack(entry)
+ }
+ }
+ ret := make([]ASN1Cert, list.Len())
+ i := 0
+ for e := list.Front(); e != nil; e = e.Next() {
+ ret[i] = e.Value.([]byte)
+ i++
+ }
+ return ret, nil
+}
+
+// ReadTimestampedEntryInto parses the byte-stream representation of a
+// TimestampedEntry from |r| and populates the struct |t| with the data. See
+// RFC section 3.4 for details on the format.
+// Returns a non-nil error if there was a problem.
+func ReadTimestampedEntryInto(r io.Reader, t *TimestampedEntry) error {
+ var err error
+ if err = binary.Read(r, binary.BigEndian, &t.Timestamp); err != nil {
+ return err
+ }
+ if err = binary.Read(r, binary.BigEndian, &t.EntryType); err != nil {
+ return err
+ }
+ switch t.EntryType {
+ case X509LogEntryType:
+ if t.X509Entry, err = readVarBytes(r, CertificateLengthBytes); err != nil {
+ return err
+ }
+ case PrecertLogEntryType:
+ if err := binary.Read(r, binary.BigEndian, &t.PrecertEntry.IssuerKeyHash); err != nil {
+ return err
+ }
+ if t.PrecertEntry.TBSCertificate, err = readVarBytes(r, PreCertificateLengthBytes); err != nil {
+ return err
+ }
+ case XJSONLogEntryType:
+ if t.JSONData, err = readVarBytes(r, JSONLengthBytes); err != nil {
+ return err
+ }
+ default:
+ return fmt.Errorf("unknown EntryType: %d", t.EntryType)
+ }
+ t.Extensions, err = readVarBytes(r, ExtensionsLengthBytes)
+ return nil
+}
+
+// SerializeTimestampedEntry writes timestamped entry to Writer.
+// In case of error, w may contain garbage.
+func SerializeTimestampedEntry(w io.Writer, t *TimestampedEntry) error {
+ if err := binary.Write(w, binary.BigEndian, t.Timestamp); err != nil {
+ return err
+ }
+ if err := binary.Write(w, binary.BigEndian, t.EntryType); err != nil {
+ return err
+ }
+ switch t.EntryType {
+ case X509LogEntryType:
+ if err := writeVarBytes(w, t.X509Entry, CertificateLengthBytes); err != nil {
+ return err
+ }
+ case PrecertLogEntryType:
+ if err := binary.Write(w, binary.BigEndian, t.PrecertEntry.IssuerKeyHash); err != nil {
+ return err
+ }
+ if err := writeVarBytes(w, t.PrecertEntry.TBSCertificate, PreCertificateLengthBytes); err != nil {
+ return err
+ }
+ case XJSONLogEntryType:
+ // TODO: Pending google/certificate-transparency#1243, replace
+ // with ObjectHash once supported by CT server.
+ //jsonhash := objecthash.CommonJSONHash(string(t.JSONData))
+ if err := writeVarBytes(w, []byte(t.JSONData), JSONLengthBytes); err != nil {
+ return err
+ }
+ default:
+ return fmt.Errorf("unknown EntryType: %d", t.EntryType)
+ }
+ writeVarBytes(w, t.Extensions, ExtensionsLengthBytes)
+ return nil
+}
+
+// ReadMerkleTreeLeaf parses the byte-stream representation of a MerkleTreeLeaf
+// and returns a pointer to a new MerkleTreeLeaf structure containing the
+// parsed data.
+// See RFC section 3.4 for details on the format.
+// Returns a pointer to a new MerkleTreeLeaf or non-nil error if there was a
+// problem
+func ReadMerkleTreeLeaf(r io.Reader) (*MerkleTreeLeaf, error) {
+ var m MerkleTreeLeaf
+ if err := binary.Read(r, binary.BigEndian, &m.Version); err != nil {
+ return nil, err
+ }
+ if m.Version != V1 {
+ return nil, fmt.Errorf("unknown Version %d", m.Version)
+ }
+ if err := binary.Read(r, binary.BigEndian, &m.LeafType); err != nil {
+ return nil, err
+ }
+ if m.LeafType != TimestampedEntryLeafType {
+ return nil, fmt.Errorf("unknown LeafType %d", m.LeafType)
+ }
+ if err := ReadTimestampedEntryInto(r, &m.TimestampedEntry); err != nil {
+ return nil, err
+ }
+ return &m, nil
+}
+
+// UnmarshalX509ChainArray unmarshalls the contents of the "chain:" entry in a
+// GetEntries response in the case where the entry refers to an X509 leaf.
+func UnmarshalX509ChainArray(b []byte) ([]ASN1Cert, error) {
+ return readASN1CertList(bytes.NewReader(b), CertificateChainLengthBytes, CertificateLengthBytes)
+}
+
+// UnmarshalPrecertChainArray unmarshalls the contents of the "chain:" entry in
+// a GetEntries response in the case where the entry refers to a Precertificate
+// leaf.
+func UnmarshalPrecertChainArray(b []byte) ([]ASN1Cert, error) {
+ var chain []ASN1Cert
+
+ reader := bytes.NewReader(b)
+ // read the pre-cert entry:
+ precert, err := readVarBytes(reader, CertificateLengthBytes)
+ if err != nil {
+ return chain, err
+ }
+ chain = append(chain, precert)
+ // and then read and return the chain up to the root:
+ remainingChain, err := readASN1CertList(reader, CertificateChainLengthBytes, CertificateLengthBytes)
+ if err != nil {
+ return chain, err
+ }
+ chain = append(chain, remainingChain...)
+ return chain, nil
+}
+
+// UnmarshalDigitallySigned reconstructs a DigitallySigned structure from a Reader
+func UnmarshalDigitallySigned(r io.Reader) (*DigitallySigned, error) {
+ var h byte
+ if err := binary.Read(r, binary.BigEndian, &h); err != nil {
+ return nil, fmt.Errorf("failed to read HashAlgorithm: %v", err)
+ }
+
+ var s byte
+ if err := binary.Read(r, binary.BigEndian, &s); err != nil {
+ return nil, fmt.Errorf("failed to read SignatureAlgorithm: %v", err)
+ }
+
+ sig, err := readVarBytes(r, SignatureLengthBytes)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read Signature bytes: %v", err)
+ }
+
+ return &DigitallySigned{
+ HashAlgorithm: HashAlgorithm(h),
+ SignatureAlgorithm: SignatureAlgorithm(s),
+ Signature: sig,
+ }, nil
+}
+
+func marshalDigitallySignedHere(ds DigitallySigned, here []byte) ([]byte, error) {
+ sigLen := len(ds.Signature)
+ dsOutLen := 2 + SignatureLengthBytes + sigLen
+ if here == nil {
+ here = make([]byte, dsOutLen)
+ }
+ if len(here) < dsOutLen {
+ return nil, ErrNotEnoughBuffer
+ }
+ here = here[0:dsOutLen]
+
+ here[0] = byte(ds.HashAlgorithm)
+ here[1] = byte(ds.SignatureAlgorithm)
+ binary.BigEndian.PutUint16(here[2:4], uint16(sigLen))
+ copy(here[4:], ds.Signature)
+
+ return here, nil
+}
+
+// MarshalDigitallySigned marshalls a DigitallySigned structure into a byte array
+func MarshalDigitallySigned(ds DigitallySigned) ([]byte, error) {
+ return marshalDigitallySignedHere(ds, nil)
+}
+
+func checkCertificateFormat(cert ASN1Cert) error {
+ if len(cert) == 0 {
+ return errors.New("certificate is zero length")
+ }
+ if len(cert) > MaxCertificateLength {
+ return errors.New("certificate too large")
+ }
+ return nil
+}
+
+func checkExtensionsFormat(ext CTExtensions) error {
+ if len(ext) > MaxExtensionsLength {
+ return errors.New("extensions too large")
+ }
+ return nil
+}
+
+func serializeV1CertSCTSignatureInput(timestamp uint64, cert ASN1Cert, ext CTExtensions) ([]byte, error) {
+ if err := checkCertificateFormat(cert); err != nil {
+ return nil, err
+ }
+ if err := checkExtensionsFormat(ext); err != nil {
+ return nil, err
+ }
+ var buf bytes.Buffer
+ if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, CertificateTimestampSignatureType); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, timestamp); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, X509LogEntryType); err != nil {
+ return nil, err
+ }
+ if err := writeVarBytes(&buf, cert, CertificateLengthBytes); err != nil {
+ return nil, err
+ }
+ if err := writeVarBytes(&buf, ext, ExtensionsLengthBytes); err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+func serializeV1JSONSCTSignatureInput(timestamp uint64, j []byte) ([]byte, error) {
+ var buf bytes.Buffer
+ if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, CertificateTimestampSignatureType); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, timestamp); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, XJSONLogEntryType); err != nil {
+ return nil, err
+ }
+ if err := writeVarBytes(&buf, j, JSONLengthBytes); err != nil {
+ return nil, err
+ }
+ if err := writeVarBytes(&buf, nil, ExtensionsLengthBytes); err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+func serializeV1PrecertSCTSignatureInput(timestamp uint64, issuerKeyHash [issuerKeyHashLength]byte, tbs []byte, ext CTExtensions) ([]byte, error) {
+ if err := checkCertificateFormat(tbs); err != nil {
+ return nil, err
+ }
+ if err := checkExtensionsFormat(ext); err != nil {
+ return nil, err
+ }
+ var buf bytes.Buffer
+ if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, CertificateTimestampSignatureType); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, timestamp); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, PrecertLogEntryType); err != nil {
+ return nil, err
+ }
+ if _, err := buf.Write(issuerKeyHash[:]); err != nil {
+ return nil, err
+ }
+ if err := writeVarBytes(&buf, tbs, CertificateLengthBytes); err != nil {
+ return nil, err
+ }
+ if err := writeVarBytes(&buf, ext, ExtensionsLengthBytes); err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+func serializeV1SCTSignatureInput(sct SignedCertificateTimestamp, entry LogEntry) ([]byte, error) {
+ if sct.SCTVersion != V1 {
+ return nil, fmt.Errorf("unsupported SCT version, expected V1, but got %s", sct.SCTVersion)
+ }
+ if entry.Leaf.LeafType != TimestampedEntryLeafType {
+ return nil, fmt.Errorf("Unsupported leaf type %s", entry.Leaf.LeafType)
+ }
+ switch entry.Leaf.TimestampedEntry.EntryType {
+ case X509LogEntryType:
+ return serializeV1CertSCTSignatureInput(sct.Timestamp, entry.Leaf.TimestampedEntry.X509Entry, entry.Leaf.TimestampedEntry.Extensions)
+ case PrecertLogEntryType:
+ return serializeV1PrecertSCTSignatureInput(sct.Timestamp, entry.Leaf.TimestampedEntry.PrecertEntry.IssuerKeyHash,
+ entry.Leaf.TimestampedEntry.PrecertEntry.TBSCertificate,
+ entry.Leaf.TimestampedEntry.Extensions)
+ case XJSONLogEntryType:
+ return serializeV1JSONSCTSignatureInput(sct.Timestamp, entry.Leaf.TimestampedEntry.JSONData)
+ default:
+ return nil, fmt.Errorf("unknown TimestampedEntryLeafType %s", entry.Leaf.TimestampedEntry.EntryType)
+ }
+}
+
+// SerializeSCTSignatureInput serializes the passed in sct and log entry into
+// the correct format for signing.
+func SerializeSCTSignatureInput(sct SignedCertificateTimestamp, entry LogEntry) ([]byte, error) {
+ switch sct.SCTVersion {
+ case V1:
+ return serializeV1SCTSignatureInput(sct, entry)
+ default:
+ return nil, fmt.Errorf("unknown SCT version %d", sct.SCTVersion)
+ }
+}
+
+// SerializedLength will return the space (in bytes)
+func (sct SignedCertificateTimestamp) SerializedLength() (int, error) {
+ switch sct.SCTVersion {
+ case V1:
+ extLen := len(sct.Extensions)
+ sigLen := len(sct.Signature.Signature)
+ return 1 + 32 + 8 + 2 + extLen + 2 + 2 + sigLen, nil
+ default:
+ return 0, ErrInvalidVersion
+ }
+}
+
+func serializeV1SCTHere(sct SignedCertificateTimestamp, here []byte) ([]byte, error) {
+ if sct.SCTVersion != V1 {
+ return nil, ErrInvalidVersion
+ }
+ sctLen, err := sct.SerializedLength()
+ if err != nil {
+ return nil, err
+ }
+ if here == nil {
+ here = make([]byte, sctLen)
+ }
+ if len(here) < sctLen {
+ return nil, ErrNotEnoughBuffer
+ }
+ if err := checkExtensionsFormat(sct.Extensions); err != nil {
+ return nil, err
+ }
+
+ here = here[0:sctLen]
+
+ // Write Version
+ here[0] = byte(sct.SCTVersion)
+
+ // Write LogID
+ copy(here[1:33], sct.LogID[:])
+
+ // Write Timestamp
+ binary.BigEndian.PutUint64(here[33:41], sct.Timestamp)
+
+ // Write Extensions
+ extLen := len(sct.Extensions)
+ binary.BigEndian.PutUint16(here[41:43], uint16(extLen))
+ n := 43 + extLen
+ copy(here[43:n], sct.Extensions)
+
+ // Write Signature
+ _, err = marshalDigitallySignedHere(sct.Signature, here[n:])
+ if err != nil {
+ return nil, err
+ }
+ return here, nil
+}
+
+// SerializeSCTHere serializes the passed in sct into the format specified
+// by RFC6962 section 3.2.
+// If a bytes slice here is provided then it will attempt to serialize into the
+// provided byte slice, ErrNotEnoughBuffer will be returned if the buffer is
+// too small.
+// If a nil byte slice is provided, a buffer for will be allocated for you
+// The returned slice will be sliced to the correct length.
+func SerializeSCTHere(sct SignedCertificateTimestamp, here []byte) ([]byte, error) {
+ switch sct.SCTVersion {
+ case V1:
+ return serializeV1SCTHere(sct, here)
+ default:
+ return nil, fmt.Errorf("unknown SCT version %d", sct.SCTVersion)
+ }
+}
+
+// SerializeSCT serializes the passed in sct into the format specified
+// by RFC6962 section 3.2
+// Equivalent to SerializeSCTHere(sct, nil)
+func SerializeSCT(sct SignedCertificateTimestamp) ([]byte, error) {
+ return SerializeSCTHere(sct, nil)
+}
+
+func deserializeSCTV1(r io.Reader, sct *SignedCertificateTimestamp) error {
+ if err := binary.Read(r, binary.BigEndian, &sct.LogID); err != nil {
+ return err
+ }
+ if err := binary.Read(r, binary.BigEndian, &sct.Timestamp); err != nil {
+ return err
+ }
+ ext, err := readVarBytes(r, ExtensionsLengthBytes)
+ if err != nil {
+ return err
+ }
+ sct.Extensions = ext
+ ds, err := UnmarshalDigitallySigned(r)
+ if err != nil {
+ return err
+ }
+ sct.Signature = *ds
+ return nil
+}
+
+// DeserializeSCT reads an SCT from Reader.
+func DeserializeSCT(r io.Reader) (*SignedCertificateTimestamp, error) {
+ var sct SignedCertificateTimestamp
+ if err := binary.Read(r, binary.BigEndian, &sct.SCTVersion); err != nil {
+ return nil, err
+ }
+ switch sct.SCTVersion {
+ case V1:
+ return &sct, deserializeSCTV1(r, &sct)
+ default:
+ return nil, fmt.Errorf("unknown SCT version %d", sct.SCTVersion)
+ }
+}
+
+func serializeV1STHSignatureInput(sth SignedTreeHead) ([]byte, error) {
+ if sth.Version != V1 {
+ return nil, fmt.Errorf("invalid STH version %d", sth.Version)
+ }
+ if sth.TreeSize < 0 {
+ return nil, fmt.Errorf("invalid tree size %d", sth.TreeSize)
+ }
+ if len(sth.SHA256RootHash) != crypto.SHA256.Size() {
+ return nil, fmt.Errorf("invalid TreeHash length, got %d expected %d", len(sth.SHA256RootHash), crypto.SHA256.Size())
+ }
+
+ var buf bytes.Buffer
+ if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, TreeHashSignatureType); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, sth.Timestamp); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, sth.TreeSize); err != nil {
+ return nil, err
+ }
+ if err := binary.Write(&buf, binary.BigEndian, sth.SHA256RootHash); err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+// SerializeSTHSignatureInput serializes the passed in sth into the correct
+// format for signing.
+func SerializeSTHSignatureInput(sth SignedTreeHead) ([]byte, error) {
+ switch sth.Version {
+ case V1:
+ return serializeV1STHSignatureInput(sth)
+ default:
+ return nil, fmt.Errorf("unsupported STH version %d", sth.Version)
+ }
+}
+
+// SCTListSerializedLength determines the length of the required buffer should a SCT List need to be serialized
+func SCTListSerializedLength(scts []SignedCertificateTimestamp) (int, error) {
+ if len(scts) == 0 {
+ return 0, fmt.Errorf("SCT List empty")
+ }
+
+ sctListLen := 0
+ for i, sct := range scts {
+ n, err := sct.SerializedLength()
+ if err != nil {
+ return 0, fmt.Errorf("unable to determine length of SCT in position %d: %v", i, err)
+ }
+ if n > MaxSCTInListLength {
+ return 0, fmt.Errorf("SCT in position %d too large: %d", i, n)
+ }
+ sctListLen += 2 + n
+ }
+
+ return sctListLen, nil
+}
+
+// SerializeSCTList serializes the passed-in slice of SignedCertificateTimestamp into a
+// byte slice as a SignedCertificateTimestampList (see RFC6962 Section 3.3)
+func SerializeSCTList(scts []SignedCertificateTimestamp) ([]byte, error) {
+ size, err := SCTListSerializedLength(scts)
+ if err != nil {
+ return nil, err
+ }
+ fullSize := 2 + size // 2 bytes for length + size of SCT list
+ if fullSize > MaxSCTListLength {
+ return nil, fmt.Errorf("SCT List too large to serialize: %d", fullSize)
+ }
+ buf := new(bytes.Buffer)
+ buf.Grow(fullSize)
+ if err = writeUint(buf, uint64(size), 2); err != nil {
+ return nil, err
+ }
+ for _, sct := range scts {
+ serialized, err := SerializeSCT(sct)
+ if err != nil {
+ return nil, err
+ }
+ if err = writeVarBytes(buf, serialized, 2); err != nil {
+ return nil, err
+ }
+ }
+ return asn1.Marshal(buf.Bytes()) // transform to Octet String
+}
+
+// SerializeMerkleTreeLeaf writes MerkleTreeLeaf to Writer.
+// In case of error, w may contain garbage.
+func SerializeMerkleTreeLeaf(w io.Writer, m *MerkleTreeLeaf) error {
+ if m.Version != V1 {
+ return fmt.Errorf("unknown Version %d", m.Version)
+ }
+ if err := binary.Write(w, binary.BigEndian, m.Version); err != nil {
+ return err
+ }
+ if m.LeafType != TimestampedEntryLeafType {
+ return fmt.Errorf("unknown LeafType %d", m.LeafType)
+ }
+ if err := binary.Write(w, binary.BigEndian, m.LeafType); err != nil {
+ return err
+ }
+ if err := SerializeTimestampedEntry(w, &m.TimestampedEntry); err != nil {
+ return err
+ }
+ return nil
+}
+
+// CreateX509MerkleTreeLeaf generates a MerkleTreeLeaf for an X509 cert
+func CreateX509MerkleTreeLeaf(cert ASN1Cert, timestamp uint64) *MerkleTreeLeaf {
+ return &MerkleTreeLeaf{
+ Version: V1,
+ LeafType: TimestampedEntryLeafType,
+ TimestampedEntry: TimestampedEntry{
+ Timestamp: timestamp,
+ EntryType: X509LogEntryType,
+ X509Entry: cert,
+ },
+ }
+}
+
+// CreateJSONMerkleTreeLeaf creates the merkle tree leaf for json data.
+func CreateJSONMerkleTreeLeaf(data interface{}, timestamp uint64) *MerkleTreeLeaf {
+ jsonData, err := json.Marshal(AddJSONRequest{Data: data})
+ if err != nil {
+ return nil
+ }
+ // Match the JSON serialization implemented by json-c
+ jsonStr := strings.Replace(string(jsonData), ":", ": ", -1)
+ jsonStr = strings.Replace(jsonStr, ",", ", ", -1)
+ jsonStr = strings.Replace(jsonStr, "{", "{ ", -1)
+ jsonStr = strings.Replace(jsonStr, "}", " }", -1)
+ jsonStr = strings.Replace(jsonStr, "/", `\/`, -1)
+ // TODO: Pending google/certificate-transparency#1243, replace with
+ // ObjectHash once supported by CT server.
+
+ return &MerkleTreeLeaf{
+ Version: V1,
+ LeafType: TimestampedEntryLeafType,
+ TimestampedEntry: TimestampedEntry{
+ Timestamp: timestamp,
+ EntryType: XJSONLogEntryType,
+ JSONData: []byte(jsonStr),
+ },
+ }
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/signatures.go b/vendor/github.com/google/certificate-transparency/go/signatures.go
new file mode 100644
index 0000000..600db24
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/signatures.go
@@ -0,0 +1,131 @@
+package ct
+
+import (
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rsa"
+ "crypto/sha256"
+ "crypto/x509"
+ "encoding/asn1"
+ "encoding/pem"
+ "errors"
+ "flag"
+ "fmt"
+ "log"
+ "math/big"
+)
+
+var allowVerificationWithNonCompliantKeys = flag.Bool("allow_verification_with_non_compliant_keys", false,
+ "Allow a SignatureVerifier to use keys which are technically non-compliant with RFC6962.")
+
+// PublicKeyFromPEM parses a PEM formatted block and returns the public key contained within and any remaining unread bytes, or an error.
+func PublicKeyFromPEM(b []byte) (crypto.PublicKey, SHA256Hash, []byte, error) {
+ p, rest := pem.Decode(b)
+ if p == nil {
+ return nil, [sha256.Size]byte{}, rest, fmt.Errorf("no PEM block found in %s", string(b))
+ }
+ k, err := x509.ParsePKIXPublicKey(p.Bytes)
+ return k, sha256.Sum256(p.Bytes), rest, err
+}
+
+// SignatureVerifier can verify signatures on SCTs and STHs
+type SignatureVerifier struct {
+ pubKey crypto.PublicKey
+}
+
+// NewSignatureVerifier creates a new SignatureVerifier using the passed in PublicKey.
+func NewSignatureVerifier(pk crypto.PublicKey) (*SignatureVerifier, error) {
+ switch pkType := pk.(type) {
+ case *rsa.PublicKey:
+ if pkType.N.BitLen() < 2048 {
+ e := fmt.Errorf("public key is RSA with < 2048 bits (size:%d)", pkType.N.BitLen())
+ if !(*allowVerificationWithNonCompliantKeys) {
+ return nil, e
+ }
+ log.Printf("WARNING: %v", e)
+ }
+ case *ecdsa.PublicKey:
+ params := *(pkType.Params())
+ if params != *elliptic.P256().Params() {
+ e := fmt.Errorf("public is ECDSA, but not on the P256 curve")
+ if !(*allowVerificationWithNonCompliantKeys) {
+ return nil, e
+ }
+ log.Printf("WARNING: %v", e)
+
+ }
+ default:
+ return nil, fmt.Errorf("Unsupported public key type %v", pkType)
+ }
+
+ return &SignatureVerifier{
+ pubKey: pk,
+ }, nil
+}
+
+// verifySignature verifies that the passed in signature over data was created by our PublicKey.
+// Currently, only SHA256 is supported as a HashAlgorithm, and only ECDSA and RSA signatures are supported.
+func (s SignatureVerifier) verifySignature(data []byte, sig DigitallySigned) error {
+ if sig.HashAlgorithm != SHA256 {
+ return fmt.Errorf("unsupported HashAlgorithm in signature: %v", sig.HashAlgorithm)
+ }
+
+ hasherType := crypto.SHA256
+ hasher := hasherType.New()
+ if _, err := hasher.Write(data); err != nil {
+ return fmt.Errorf("failed to write to hasher: %v", err)
+ }
+ hash := hasher.Sum([]byte{})
+
+ switch sig.SignatureAlgorithm {
+ case RSA:
+ rsaKey, ok := s.pubKey.(*rsa.PublicKey)
+ if !ok {
+ return fmt.Errorf("cannot verify RSA signature with %T key", s.pubKey)
+ }
+ if err := rsa.VerifyPKCS1v15(rsaKey, hasherType, hash, sig.Signature); err != nil {
+ return fmt.Errorf("failed to verify rsa signature: %v", err)
+ }
+ case ECDSA:
+ ecdsaKey, ok := s.pubKey.(*ecdsa.PublicKey)
+ if !ok {
+ return fmt.Errorf("cannot verify ECDSA signature with %T key", s.pubKey)
+ }
+ var ecdsaSig struct {
+ R, S *big.Int
+ }
+ rest, err := asn1.Unmarshal(sig.Signature, &ecdsaSig)
+ if err != nil {
+ return fmt.Errorf("failed to unmarshal ECDSA signature: %v", err)
+ }
+ if len(rest) != 0 {
+ log.Printf("Garbage following signature %v", rest)
+ }
+
+ if !ecdsa.Verify(ecdsaKey, hash, ecdsaSig.R, ecdsaSig.S) {
+ return errors.New("failed to verify ecdsa signature")
+ }
+ default:
+ return fmt.Errorf("unsupported signature type %v", sig.SignatureAlgorithm)
+ }
+ return nil
+}
+
+// VerifySCTSignature verifies that the SCT's signature is valid for the given LogEntry
+func (s SignatureVerifier) VerifySCTSignature(sct SignedCertificateTimestamp, entry LogEntry) error {
+ sctData, err := SerializeSCTSignatureInput(sct, entry)
+ if err != nil {
+ return err
+ }
+ return s.verifySignature(sctData, sct.Signature)
+}
+
+// VerifySTHSignature verifies that the STH's signature is valid.
+func (s SignatureVerifier) VerifySTHSignature(sth SignedTreeHead) error {
+ sthData, err := SerializeSTHSignatureInput(sth)
+ if err != nil {
+ return err
+ }
+ return s.verifySignature(sthData, sth.TreeHeadSignature)
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/types.go b/vendor/github.com/google/certificate-transparency/go/types.go
new file mode 100644
index 0000000..507e624
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/types.go
@@ -0,0 +1,374 @@
+package ct
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+
+ "github.com/google/certificate-transparency/go/x509"
+)
+
+const (
+ issuerKeyHashLength = 32
+)
+
+///////////////////////////////////////////////////////////////////////////////
+// The following structures represent those outlined in the RFC6962 document:
+///////////////////////////////////////////////////////////////////////////////
+
+// LogEntryType represents the LogEntryType enum from section 3.1 of the RFC:
+// enum { x509_entry(0), precert_entry(1), (65535) } LogEntryType;
+type LogEntryType uint16
+
+func (e LogEntryType) String() string {
+ switch e {
+ case X509LogEntryType:
+ return "X509LogEntryType"
+ case PrecertLogEntryType:
+ return "PrecertLogEntryType"
+ case XJSONLogEntryType:
+ return "XJSONLogEntryType"
+ }
+ panic(fmt.Sprintf("No string defined for LogEntryType constant value %d", e))
+}
+
+// LogEntryType constants, see section 3.1 of RFC6962.
+const (
+ X509LogEntryType LogEntryType = 0
+ PrecertLogEntryType LogEntryType = 1
+ XJSONLogEntryType LogEntryType = 0x8000 // Experimental. Don't rely on this!
+)
+
+// MerkleLeafType represents the MerkleLeafType enum from section 3.4 of the
+// RFC: enum { timestamped_entry(0), (255) } MerkleLeafType;
+type MerkleLeafType uint8
+
+func (m MerkleLeafType) String() string {
+ switch m {
+ case TimestampedEntryLeafType:
+ return "TimestampedEntryLeafType"
+ default:
+ return fmt.Sprintf("UnknownLeafType(%d)", m)
+ }
+}
+
+// MerkleLeafType constants, see section 3.4 of the RFC.
+const (
+ TimestampedEntryLeafType MerkleLeafType = 0 // Entry type for an SCT
+)
+
+// Version represents the Version enum from section 3.2 of the RFC:
+// enum { v1(0), (255) } Version;
+type Version uint8
+
+func (v Version) String() string {
+ switch v {
+ case V1:
+ return "V1"
+ default:
+ return fmt.Sprintf("UnknownVersion(%d)", v)
+ }
+}
+
+// CT Version constants, see section 3.2 of the RFC.
+const (
+ V1 Version = 0
+)
+
+// SignatureType differentiates STH signatures from SCT signatures, see RFC
+// section 3.2
+type SignatureType uint8
+
+func (st SignatureType) String() string {
+ switch st {
+ case CertificateTimestampSignatureType:
+ return "CertificateTimestamp"
+ case TreeHashSignatureType:
+ return "TreeHash"
+ default:
+ return fmt.Sprintf("UnknownSignatureType(%d)", st)
+ }
+}
+
+// SignatureType constants, see RFC section 3.2
+const (
+ CertificateTimestampSignatureType SignatureType = 0
+ TreeHashSignatureType SignatureType = 1
+)
+
+// ASN1Cert type for holding the raw DER bytes of an ASN.1 Certificate
+// (section 3.1)
+type ASN1Cert []byte
+
+// PreCert represents a Precertificate (section 3.2)
+type PreCert struct {
+ IssuerKeyHash [issuerKeyHashLength]byte
+ TBSCertificate []byte
+}
+
+// CTExtensions is a representation of the raw bytes of any CtExtension
+// structure (see section 3.2)
+type CTExtensions []byte
+
+// MerkleTreeNode represents an internal node in the CT tree
+type MerkleTreeNode []byte
+
+// ConsistencyProof represents a CT consistency proof (see sections 2.1.2 and
+// 4.4)
+type ConsistencyProof []MerkleTreeNode
+
+// AuditPath represents a CT inclusion proof (see sections 2.1.1 and 4.5)
+type AuditPath []MerkleTreeNode
+
+// LeafInput represents a serialized MerkleTreeLeaf structure
+type LeafInput []byte
+
+// HashAlgorithm from the DigitallySigned struct
+type HashAlgorithm byte
+
+// HashAlgorithm constants
+const (
+ None HashAlgorithm = 0
+ MD5 HashAlgorithm = 1
+ SHA1 HashAlgorithm = 2
+ SHA224 HashAlgorithm = 3
+ SHA256 HashAlgorithm = 4
+ SHA384 HashAlgorithm = 5
+ SHA512 HashAlgorithm = 6
+)
+
+func (h HashAlgorithm) String() string {
+ switch h {
+ case None:
+ return "None"
+ case MD5:
+ return "MD5"
+ case SHA1:
+ return "SHA1"
+ case SHA224:
+ return "SHA224"
+ case SHA256:
+ return "SHA256"
+ case SHA384:
+ return "SHA384"
+ case SHA512:
+ return "SHA512"
+ default:
+ return fmt.Sprintf("UNKNOWN(%d)", h)
+ }
+}
+
+// SignatureAlgorithm from the the DigitallySigned struct
+type SignatureAlgorithm byte
+
+// SignatureAlgorithm constants
+const (
+ Anonymous SignatureAlgorithm = 0
+ RSA SignatureAlgorithm = 1
+ DSA SignatureAlgorithm = 2
+ ECDSA SignatureAlgorithm = 3
+)
+
+func (s SignatureAlgorithm) String() string {
+ switch s {
+ case Anonymous:
+ return "Anonymous"
+ case RSA:
+ return "RSA"
+ case DSA:
+ return "DSA"
+ case ECDSA:
+ return "ECDSA"
+ default:
+ return fmt.Sprintf("UNKNOWN(%d)", s)
+ }
+}
+
+// DigitallySigned represents an RFC5246 DigitallySigned structure
+type DigitallySigned struct {
+ HashAlgorithm HashAlgorithm
+ SignatureAlgorithm SignatureAlgorithm
+ Signature []byte
+}
+
+// FromBase64String populates the DigitallySigned structure from the base64 data passed in.
+// Returns an error if the base64 data is invalid.
+func (d *DigitallySigned) FromBase64String(b64 string) error {
+ raw, err := base64.StdEncoding.DecodeString(b64)
+ if err != nil {
+ return fmt.Errorf("failed to unbase64 DigitallySigned: %v", err)
+ }
+ ds, err := UnmarshalDigitallySigned(bytes.NewReader(raw))
+ if err != nil {
+ return fmt.Errorf("failed to unmarshal DigitallySigned: %v", err)
+ }
+ *d = *ds
+ return nil
+}
+
+// Base64String returns the base64 representation of the DigitallySigned struct.
+func (d DigitallySigned) Base64String() (string, error) {
+ b, err := MarshalDigitallySigned(d)
+ if err != nil {
+ return "", err
+ }
+ return base64.StdEncoding.EncodeToString(b), nil
+}
+
+// MarshalJSON implements the json.Marshaller interface.
+func (d DigitallySigned) MarshalJSON() ([]byte, error) {
+ b64, err := d.Base64String()
+ if err != nil {
+ return []byte{}, err
+ }
+ return []byte(`"` + b64 + `"`), nil
+}
+
+// UnmarshalJSON implements the json.Unmarshaler interface.
+func (d *DigitallySigned) UnmarshalJSON(b []byte) error {
+ var content string
+ if err := json.Unmarshal(b, &content); err != nil {
+ return fmt.Errorf("failed to unmarshal DigitallySigned: %v", err)
+ }
+ return d.FromBase64String(content)
+}
+
+// LogEntry represents the contents of an entry in a CT log, see section 3.1.
+type LogEntry struct {
+ Index int64
+ Leaf MerkleTreeLeaf
+ X509Cert *x509.Certificate
+ Precert *Precertificate
+ JSONData []byte
+ Chain []ASN1Cert
+}
+
+// SHA256Hash represents the output from the SHA256 hash function.
+type SHA256Hash [sha256.Size]byte
+
+// FromBase64String populates the SHA256 struct with the contents of the base64 data passed in.
+func (s *SHA256Hash) FromBase64String(b64 string) error {
+ bs, err := base64.StdEncoding.DecodeString(b64)
+ if err != nil {
+ return fmt.Errorf("failed to unbase64 LogID: %v", err)
+ }
+ if len(bs) != sha256.Size {
+ return fmt.Errorf("invalid SHA256 length, expected 32 but got %d", len(bs))
+ }
+ copy(s[:], bs)
+ return nil
+}
+
+// Base64String returns the base64 representation of this SHA256Hash.
+func (s SHA256Hash) Base64String() string {
+ return base64.StdEncoding.EncodeToString(s[:])
+}
+
+// MarshalJSON implements the json.Marshaller interface for SHA256Hash.
+func (s SHA256Hash) MarshalJSON() ([]byte, error) {
+ return []byte(`"` + s.Base64String() + `"`), nil
+}
+
+// UnmarshalJSON implements the json.Unmarshaller interface.
+func (s *SHA256Hash) UnmarshalJSON(b []byte) error {
+ var content string
+ if err := json.Unmarshal(b, &content); err != nil {
+ return fmt.Errorf("failed to unmarshal SHA256Hash: %v", err)
+ }
+ return s.FromBase64String(content)
+}
+
+// SignedTreeHead represents the structure returned by the get-sth CT method
+// after base64 decoding. See sections 3.5 and 4.3 in the RFC)
+type SignedTreeHead struct {
+ Version Version `json:"sth_version"` // The version of the protocol to which the STH conforms
+ TreeSize uint64 `json:"tree_size"` // The number of entries in the new tree
+ Timestamp uint64 `json:"timestamp"` // The time at which the STH was created
+ SHA256RootHash SHA256Hash `json:"sha256_root_hash"` // The root hash of the log's Merkle tree
+ TreeHeadSignature DigitallySigned `json:"tree_head_signature"` // The Log's signature for this STH (see RFC section 3.5)
+ LogID SHA256Hash `json:"log_id"` // The SHA256 hash of the log's public key
+}
+
+// SignedCertificateTimestamp represents the structure returned by the
+// add-chain and add-pre-chain methods after base64 decoding. (see RFC sections
+// 3.2 ,4.1 and 4.2)
+type SignedCertificateTimestamp struct {
+ SCTVersion Version // The version of the protocol to which the SCT conforms
+ LogID SHA256Hash // the SHA-256 hash of the log's public key, calculated over
+ // the DER encoding of the key represented as SubjectPublicKeyInfo.
+ Timestamp uint64 // Timestamp (in ms since unix epoc) at which the SCT was issued
+ Extensions CTExtensions // For future extensions to the protocol
+ Signature DigitallySigned // The Log's signature for this SCT
+}
+
+func (s SignedCertificateTimestamp) String() string {
+ return fmt.Sprintf("{Version:%d LogId:%s Timestamp:%d Extensions:'%s' Signature:%v}", s.SCTVersion,
+ base64.StdEncoding.EncodeToString(s.LogID[:]),
+ s.Timestamp,
+ s.Extensions,
+ s.Signature)
+}
+
+// TimestampedEntry is part of the MerkleTreeLeaf structure.
+// See RFC section 3.4
+type TimestampedEntry struct {
+ Timestamp uint64
+ EntryType LogEntryType
+ X509Entry ASN1Cert
+ JSONData []byte
+ PrecertEntry PreCert
+ Extensions CTExtensions
+}
+
+// MerkleTreeLeaf represents the deserialized sructure of the hash input for the
+// leaves of a log's Merkle tree. See RFC section 3.4
+type MerkleTreeLeaf struct {
+ Version Version // the version of the protocol to which the MerkleTreeLeaf corresponds
+ LeafType MerkleLeafType // The type of the leaf input, currently only TimestampedEntry can exist
+ TimestampedEntry TimestampedEntry // The entry data itself
+}
+
+// Precertificate represents the parsed CT Precertificate structure.
+type Precertificate struct {
+ // Raw DER bytes of the precert
+ Raw []byte
+ // SHA256 hash of the issuing key
+ IssuerKeyHash [issuerKeyHashLength]byte
+ // Parsed TBSCertificate structure (held in an x509.Certificate for ease of
+ // access.
+ TBSCertificate x509.Certificate
+}
+
+// X509Certificate returns the X.509 Certificate contained within the
+// MerkleTreeLeaf.
+// Returns a pointer to an x509.Certificate or a non-nil error.
+func (m *MerkleTreeLeaf) X509Certificate() (*x509.Certificate, error) {
+ return x509.ParseCertificate(m.TimestampedEntry.X509Entry)
+}
+
+type sctError int
+
+// Preallocate errors for performance
+var (
+ ErrInvalidVersion error = sctError(1)
+ ErrNotEnoughBuffer error = sctError(2)
+)
+
+func (e sctError) Error() string {
+ switch e {
+ case ErrInvalidVersion:
+ return "invalid SCT version detected"
+ case ErrNotEnoughBuffer:
+ return "provided buffer was too small"
+ default:
+ return "unknown error"
+ }
+}
+
+// AddJSONRequest represents the JSON request body sent ot the add-json CT
+// method.
+type AddJSONRequest struct {
+ Data interface{} `json:"data"`
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/cert_pool.go b/vendor/github.com/google/certificate-transparency/go/x509/cert_pool.go
new file mode 100755
index 0000000..babe94d
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/cert_pool.go
@@ -0,0 +1,116 @@
+// 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 x509
+
+import (
+ "encoding/pem"
+)
+
+// CertPool is a set of certificates.
+type CertPool struct {
+ bySubjectKeyId map[string][]int
+ byName map[string][]int
+ certs []*Certificate
+}
+
+// NewCertPool returns a new, empty CertPool.
+func NewCertPool() *CertPool {
+ return &CertPool{
+ make(map[string][]int),
+ make(map[string][]int),
+ nil,
+ }
+}
+
+// findVerifiedParents attempts to find certificates in s which have signed the
+// given certificate. If any candidates were rejected then errCert will be set
+// to one of them, arbitrarily, and err will contain the reason that it was
+// rejected.
+func (s *CertPool) findVerifiedParents(cert *Certificate) (parents []int, errCert *Certificate, err error) {
+ if s == nil {
+ return
+ }
+ var candidates []int
+
+ if len(cert.AuthorityKeyId) > 0 {
+ candidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)]
+ }
+ if len(candidates) == 0 {
+ candidates = s.byName[string(cert.RawIssuer)]
+ }
+
+ for _, c := range candidates {
+ if err = cert.CheckSignatureFrom(s.certs[c]); err == nil {
+ parents = append(parents, c)
+ } else {
+ errCert = s.certs[c]
+ }
+ }
+
+ return
+}
+
+// AddCert adds a certificate to a pool.
+func (s *CertPool) AddCert(cert *Certificate) {
+ if cert == nil {
+ panic("adding nil Certificate to CertPool")
+ }
+
+ // Check that the certificate isn't being added twice.
+ for _, c := range s.certs {
+ if c.Equal(cert) {
+ return
+ }
+ }
+
+ n := len(s.certs)
+ s.certs = append(s.certs, cert)
+
+ if len(cert.SubjectKeyId) > 0 {
+ keyId := string(cert.SubjectKeyId)
+ s.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n)
+ }
+ name := string(cert.RawSubject)
+ s.byName[name] = append(s.byName[name], n)
+}
+
+// AppendCertsFromPEM attempts to parse a series of PEM encoded certificates.
+// It appends any certificates found to s and returns true if any certificates
+// were successfully parsed.
+//
+// On many Linux systems, /etc/ssl/cert.pem will contain the system wide set
+// of root CAs in a format suitable for this function.
+func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool) {
+ for len(pemCerts) > 0 {
+ var block *pem.Block
+ block, pemCerts = pem.Decode(pemCerts)
+ if block == nil {
+ break
+ }
+ if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
+ continue
+ }
+
+ cert, err := ParseCertificate(block.Bytes)
+ if err != nil {
+ continue
+ }
+
+ s.AddCert(cert)
+ ok = true
+ }
+
+ return
+}
+
+// Subjects returns a list of the DER-encoded subjects of
+// all of the certificates in the pool.
+func (s *CertPool) Subjects() (res [][]byte) {
+ res = make([][]byte, len(s.certs))
+ for i, c := range s.certs {
+ res[i] = c.RawSubject
+ }
+ return
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/pem_decrypt.go b/vendor/github.com/google/certificate-transparency/go/x509/pem_decrypt.go
new file mode 100755
index 0000000..194c81b
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/pem_decrypt.go
@@ -0,0 +1,233 @@
+// 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 x509
+
+// RFC 1423 describes the encryption of PEM blocks. The algorithm used to
+// generate a key from the password was derived by looking at the OpenSSL
+// implementation.
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/des"
+ "crypto/md5"
+ "encoding/hex"
+ "encoding/pem"
+ "errors"
+ "io"
+ "strings"
+)
+
+type PEMCipher int
+
+// Possible values for the EncryptPEMBlock encryption algorithm.
+const (
+ _ PEMCipher = iota
+ PEMCipherDES
+ PEMCipher3DES
+ PEMCipherAES128
+ PEMCipherAES192
+ PEMCipherAES256
+)
+
+// rfc1423Algo holds a method for enciphering a PEM block.
+type rfc1423Algo struct {
+ cipher PEMCipher
+ name string
+ cipherFunc func(key []byte) (cipher.Block, error)
+ keySize int
+ blockSize int
+}
+
+// rfc1423Algos holds a slice of the possible ways to encrypt a PEM
+// block. The ivSize numbers were taken from the OpenSSL source.
+var rfc1423Algos = []rfc1423Algo{{
+ cipher: PEMCipherDES,
+ name: "DES-CBC",
+ cipherFunc: des.NewCipher,
+ keySize: 8,
+ blockSize: des.BlockSize,
+}, {
+ cipher: PEMCipher3DES,
+ name: "DES-EDE3-CBC",
+ cipherFunc: des.NewTripleDESCipher,
+ keySize: 24,
+ blockSize: des.BlockSize,
+}, {
+ cipher: PEMCipherAES128,
+ name: "AES-128-CBC",
+ cipherFunc: aes.NewCipher,
+ keySize: 16,
+ blockSize: aes.BlockSize,
+}, {
+ cipher: PEMCipherAES192,
+ name: "AES-192-CBC",
+ cipherFunc: aes.NewCipher,
+ keySize: 24,
+ blockSize: aes.BlockSize,
+}, {
+ cipher: PEMCipherAES256,
+ name: "AES-256-CBC",
+ cipherFunc: aes.NewCipher,
+ keySize: 32,
+ blockSize: aes.BlockSize,
+},
+}
+
+// deriveKey uses a key derivation function to stretch the password into a key
+// with the number of bits our cipher requires. This algorithm was derived from
+// the OpenSSL source.
+func (c rfc1423Algo) deriveKey(password, salt []byte) []byte {
+ hash := md5.New()
+ out := make([]byte, c.keySize)
+ var digest []byte
+
+ for i := 0; i < len(out); i += len(digest) {
+ hash.Reset()
+ hash.Write(digest)
+ hash.Write(password)
+ hash.Write(salt)
+ digest = hash.Sum(digest[:0])
+ copy(out[i:], digest)
+ }
+ return out
+}
+
+// IsEncryptedPEMBlock returns if the PEM block is password encrypted.
+func IsEncryptedPEMBlock(b *pem.Block) bool {
+ _, ok := b.Headers["DEK-Info"]
+ return ok
+}
+
+// IncorrectPasswordError is returned when an incorrect password is detected.
+var IncorrectPasswordError = errors.New("x509: decryption password incorrect")
+
+// DecryptPEMBlock takes a password encrypted PEM block and the password used to
+// encrypt it and returns a slice of decrypted DER encoded bytes. It inspects
+// the DEK-Info header to determine the algorithm used for decryption. If no
+// DEK-Info header is present, an error is returned. If an incorrect password
+// is detected an IncorrectPasswordError is returned.
+func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error) {
+ dek, ok := b.Headers["DEK-Info"]
+ if !ok {
+ return nil, errors.New("x509: no DEK-Info header in block")
+ }
+
+ idx := strings.Index(dek, ",")
+ if idx == -1 {
+ return nil, errors.New("x509: malformed DEK-Info header")
+ }
+
+ mode, hexIV := dek[:idx], dek[idx+1:]
+ ciph := cipherByName(mode)
+ if ciph == nil {
+ return nil, errors.New("x509: unknown encryption mode")
+ }
+ iv, err := hex.DecodeString(hexIV)
+ if err != nil {
+ return nil, err
+ }
+ if len(iv) != ciph.blockSize {
+ return nil, errors.New("x509: incorrect IV size")
+ }
+
+ // Based on the OpenSSL implementation. The salt is the first 8 bytes
+ // of the initialization vector.
+ key := ciph.deriveKey(password, iv[:8])
+ block, err := ciph.cipherFunc(key)
+ if err != nil {
+ return nil, err
+ }
+
+ data := make([]byte, len(b.Bytes))
+ dec := cipher.NewCBCDecrypter(block, iv)
+ dec.CryptBlocks(data, b.Bytes)
+
+ // Blocks are padded using a scheme where the last n bytes of padding are all
+ // equal to n. It can pad from 1 to blocksize bytes inclusive. See RFC 1423.
+ // For example:
+ // [x y z 2 2]
+ // [x y 7 7 7 7 7 7 7]
+ // If we detect a bad padding, we assume it is an invalid password.
+ dlen := len(data)
+ if dlen == 0 || dlen%ciph.blockSize != 0 {
+ return nil, errors.New("x509: invalid padding")
+ }
+ last := int(data[dlen-1])
+ if dlen < last {
+ return nil, IncorrectPasswordError
+ }
+ if last == 0 || last > ciph.blockSize {
+ return nil, IncorrectPasswordError
+ }
+ for _, val := range data[dlen-last:] {
+ if int(val) != last {
+ return nil, IncorrectPasswordError
+ }
+ }
+ return data[:dlen-last], nil
+}
+
+// EncryptPEMBlock returns a PEM block of the specified type holding the
+// given DER-encoded data encrypted with the specified algorithm and
+// password.
+func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error) {
+ ciph := cipherByKey(alg)
+ if ciph == nil {
+ return nil, errors.New("x509: unknown encryption mode")
+ }
+ iv := make([]byte, ciph.blockSize)
+ if _, err := io.ReadFull(rand, iv); err != nil {
+ return nil, errors.New("x509: cannot generate IV: " + err.Error())
+ }
+ // The salt is the first 8 bytes of the initialization vector,
+ // matching the key derivation in DecryptPEMBlock.
+ key := ciph.deriveKey(password, iv[:8])
+ block, err := ciph.cipherFunc(key)
+ if err != nil {
+ return nil, err
+ }
+ enc := cipher.NewCBCEncrypter(block, iv)
+ pad := ciph.blockSize - len(data)%ciph.blockSize
+ encrypted := make([]byte, len(data), len(data)+pad)
+ // We could save this copy by encrypting all the whole blocks in
+ // the data separately, but it doesn't seem worth the additional
+ // code.
+ copy(encrypted, data)
+ // See RFC 1423, section 1.1
+ for i := 0; i < pad; i++ {
+ encrypted = append(encrypted, byte(pad))
+ }
+ enc.CryptBlocks(encrypted, encrypted)
+
+ return &pem.Block{
+ Type: blockType,
+ Headers: map[string]string{
+ "Proc-Type": "4,ENCRYPTED",
+ "DEK-Info": ciph.name + "," + hex.EncodeToString(iv),
+ },
+ Bytes: encrypted,
+ }, nil
+}
+
+func cipherByName(name string) *rfc1423Algo {
+ for i := range rfc1423Algos {
+ alg := &rfc1423Algos[i]
+ if alg.name == name {
+ return alg
+ }
+ }
+ return nil
+}
+
+func cipherByKey(key PEMCipher) *rfc1423Algo {
+ for i := range rfc1423Algos {
+ alg := &rfc1423Algos[i]
+ if alg.cipher == key {
+ return alg
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/pkcs1.go b/vendor/github.com/google/certificate-transparency/go/x509/pkcs1.go
new file mode 100755
index 0000000..638bc67
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/pkcs1.go
@@ -0,0 +1,124 @@
+// 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 x509
+
+import (
+ "crypto/rsa"
+ // START CT CHANGES
+ "github.com/google/certificate-transparency/go/asn1"
+ // END CT CHANGES
+ "errors"
+ "math/big"
+)
+
+// pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key.
+type pkcs1PrivateKey struct {
+ Version int
+ N *big.Int
+ E int
+ D *big.Int
+ P *big.Int
+ Q *big.Int
+ // We ignore these values, if present, because rsa will calculate them.
+ Dp *big.Int `asn1:"optional"`
+ Dq *big.Int `asn1:"optional"`
+ Qinv *big.Int `asn1:"optional"`
+
+ AdditionalPrimes []pkcs1AdditionalRSAPrime `asn1:"optional,omitempty"`
+}
+
+type pkcs1AdditionalRSAPrime struct {
+ Prime *big.Int
+
+ // We ignore these values because rsa will calculate them.
+ Exp *big.Int
+ Coeff *big.Int
+}
+
+// ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.
+func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error) {
+ var priv pkcs1PrivateKey
+ rest, err := asn1.Unmarshal(der, &priv)
+ if len(rest) > 0 {
+ err = asn1.SyntaxError{Msg: "trailing data"}
+ return
+ }
+ if err != nil {
+ return
+ }
+
+ if priv.Version > 1 {
+ return nil, errors.New("x509: unsupported private key version")
+ }
+
+ if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 {
+ return nil, errors.New("x509: private key contains zero or negative value")
+ }
+
+ key = new(rsa.PrivateKey)
+ key.PublicKey = rsa.PublicKey{
+ E: priv.E,
+ N: priv.N,
+ }
+
+ key.D = priv.D
+ key.Primes = make([]*big.Int, 2+len(priv.AdditionalPrimes))
+ key.Primes[0] = priv.P
+ key.Primes[1] = priv.Q
+ for i, a := range priv.AdditionalPrimes {
+ if a.Prime.Sign() <= 0 {
+ return nil, errors.New("x509: private key contains zero or negative prime")
+ }
+ key.Primes[i+2] = a.Prime
+ // We ignore the other two values because rsa will calculate
+ // them as needed.
+ }
+
+ err = key.Validate()
+ if err != nil {
+ return nil, err
+ }
+ key.Precompute()
+
+ return
+}
+
+// MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
+func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
+ key.Precompute()
+
+ version := 0
+ if len(key.Primes) > 2 {
+ version = 1
+ }
+
+ priv := pkcs1PrivateKey{
+ Version: version,
+ N: key.N,
+ E: key.PublicKey.E,
+ D: key.D,
+ P: key.Primes[0],
+ Q: key.Primes[1],
+ Dp: key.Precomputed.Dp,
+ Dq: key.Precomputed.Dq,
+ Qinv: key.Precomputed.Qinv,
+ }
+
+ priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues))
+ for i, values := range key.Precomputed.CRTValues {
+ priv.AdditionalPrimes[i].Prime = key.Primes[2+i]
+ priv.AdditionalPrimes[i].Exp = values.Exp
+ priv.AdditionalPrimes[i].Coeff = values.Coeff
+ }
+
+ b, _ := asn1.Marshal(priv)
+ return b
+}
+
+// rsaPublicKey reflects the ASN.1 structure of a PKCS#1 public key.
+type rsaPublicKey struct {
+ N *big.Int
+ E int
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/pkcs8.go b/vendor/github.com/google/certificate-transparency/go/x509/pkcs8.go
new file mode 100755
index 0000000..c6ad70b
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/pkcs8.go
@@ -0,0 +1,56 @@
+// 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 x509
+
+import (
+ // START CT CHANGES
+ "github.com/google/certificate-transparency/go/asn1"
+ "github.com/google/certificate-transparency/go/x509/pkix"
+ // END CT CHANGES
+ "errors"
+ "fmt"
+)
+
+// pkcs8 reflects an ASN.1, PKCS#8 PrivateKey. See
+// ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-8/pkcs-8v1_2.asn
+// and RFC5208.
+type pkcs8 struct {
+ Version int
+ Algo pkix.AlgorithmIdentifier
+ PrivateKey []byte
+ // optional attributes omitted.
+}
+
+// ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See
+// http://www.rsa.com/rsalabs/node.asp?id=2130 and RFC5208.
+func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) {
+ var privKey pkcs8
+ if _, err := asn1.Unmarshal(der, &privKey); err != nil {
+ return nil, err
+ }
+ switch {
+ case privKey.Algo.Algorithm.Equal(oidPublicKeyRSA):
+ key, err = ParsePKCS1PrivateKey(privKey.PrivateKey)
+ if err != nil {
+ return nil, errors.New("x509: failed to parse RSA private key embedded in PKCS#8: " + err.Error())
+ }
+ return key, nil
+
+ case privKey.Algo.Algorithm.Equal(oidPublicKeyECDSA):
+ bytes := privKey.Algo.Parameters.FullBytes
+ namedCurveOID := new(asn1.ObjectIdentifier)
+ if _, err := asn1.Unmarshal(bytes, namedCurveOID); err != nil {
+ namedCurveOID = nil
+ }
+ key, err = parseECPrivateKey(namedCurveOID, privKey.PrivateKey)
+ if err != nil {
+ return nil, errors.New("x509: failed to parse EC private key embedded in PKCS#8: " + err.Error())
+ }
+ return key, nil
+
+ default:
+ return nil, fmt.Errorf("x509: PKCS#8 wrapping contained private key with unknown algorithm: %v", privKey.Algo.Algorithm)
+ }
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/pkix/pkix.go b/vendor/github.com/google/certificate-transparency/go/x509/pkix/pkix.go
new file mode 100755
index 0000000..67db6ae
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/pkix/pkix.go
@@ -0,0 +1,173 @@
+// 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 pkix contains shared, low level structures used for ASN.1 parsing
+// and serialization of X.509 certificates, CRL and OCSP.
+package pkix
+
+import (
+ // START CT CHANGES
+ "github.com/google/certificate-transparency/go/asn1"
+ // END CT CHANGES
+ "math/big"
+ "time"
+)
+
+// AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC
+// 5280, section 4.1.1.2.
+type AlgorithmIdentifier struct {
+ Algorithm asn1.ObjectIdentifier
+ Parameters asn1.RawValue `asn1:"optional"`
+}
+
+type RDNSequence []RelativeDistinguishedNameSET
+
+type RelativeDistinguishedNameSET []AttributeTypeAndValue
+
+// AttributeTypeAndValue mirrors the ASN.1 structure of the same name in
+// http://tools.ietf.org/html/rfc5280#section-4.1.2.4
+type AttributeTypeAndValue struct {
+ Type asn1.ObjectIdentifier
+ Value interface{}
+}
+
+// Extension represents the ASN.1 structure of the same name. See RFC
+// 5280, section 4.2.
+type Extension struct {
+ Id asn1.ObjectIdentifier
+ Critical bool `asn1:"optional"`
+ Value []byte
+}
+
+// Name represents an X.509 distinguished name. This only includes the common
+// elements of a DN. Additional elements in the name are ignored.
+type Name struct {
+ Country, Organization, OrganizationalUnit []string
+ Locality, Province []string
+ StreetAddress, PostalCode []string
+ SerialNumber, CommonName string
+
+ Names []AttributeTypeAndValue
+}
+
+func (n *Name) FillFromRDNSequence(rdns *RDNSequence) {
+ for _, rdn := range *rdns {
+ if len(rdn) == 0 {
+ continue
+ }
+ atv := rdn[0]
+ n.Names = append(n.Names, atv)
+ value, ok := atv.Value.(string)
+ if !ok {
+ continue
+ }
+
+ t := atv.Type
+ if len(t) == 4 && t[0] == 2 && t[1] == 5 && t[2] == 4 {
+ switch t[3] {
+ case 3:
+ n.CommonName = value
+ case 5:
+ n.SerialNumber = value
+ case 6:
+ n.Country = append(n.Country, value)
+ case 7:
+ n.Locality = append(n.Locality, value)
+ case 8:
+ n.Province = append(n.Province, value)
+ case 9:
+ n.StreetAddress = append(n.StreetAddress, value)
+ case 10:
+ n.Organization = append(n.Organization, value)
+ case 11:
+ n.OrganizationalUnit = append(n.OrganizationalUnit, value)
+ case 17:
+ n.PostalCode = append(n.PostalCode, value)
+ }
+ }
+ }
+}
+
+var (
+ oidCountry = []int{2, 5, 4, 6}
+ oidOrganization = []int{2, 5, 4, 10}
+ oidOrganizationalUnit = []int{2, 5, 4, 11}
+ oidCommonName = []int{2, 5, 4, 3}
+ oidSerialNumber = []int{2, 5, 4, 5}
+ oidLocality = []int{2, 5, 4, 7}
+ oidProvince = []int{2, 5, 4, 8}
+ oidStreetAddress = []int{2, 5, 4, 9}
+ oidPostalCode = []int{2, 5, 4, 17}
+)
+
+// appendRDNs appends a relativeDistinguishedNameSET to the given RDNSequence
+// and returns the new value. The relativeDistinguishedNameSET contains an
+// attributeTypeAndValue for each of the given values. See RFC 5280, A.1, and
+// search for AttributeTypeAndValue.
+func appendRDNs(in RDNSequence, values []string, oid asn1.ObjectIdentifier) RDNSequence {
+ if len(values) == 0 {
+ return in
+ }
+
+ s := make([]AttributeTypeAndValue, len(values))
+ for i, value := range values {
+ s[i].Type = oid
+ s[i].Value = value
+ }
+
+ return append(in, s)
+}
+
+func (n Name) ToRDNSequence() (ret RDNSequence) {
+ ret = appendRDNs(ret, n.Country, oidCountry)
+ ret = appendRDNs(ret, n.Organization, oidOrganization)
+ ret = appendRDNs(ret, n.OrganizationalUnit, oidOrganizationalUnit)
+ ret = appendRDNs(ret, n.Locality, oidLocality)
+ ret = appendRDNs(ret, n.Province, oidProvince)
+ ret = appendRDNs(ret, n.StreetAddress, oidStreetAddress)
+ ret = appendRDNs(ret, n.PostalCode, oidPostalCode)
+ if len(n.CommonName) > 0 {
+ ret = appendRDNs(ret, []string{n.CommonName}, oidCommonName)
+ }
+ if len(n.SerialNumber) > 0 {
+ ret = appendRDNs(ret, []string{n.SerialNumber}, oidSerialNumber)
+ }
+
+ return ret
+}
+
+// CertificateList represents the ASN.1 structure of the same name. See RFC
+// 5280, section 5.1. Use Certificate.CheckCRLSignature to verify the
+// signature.
+type CertificateList struct {
+ TBSCertList TBSCertificateList
+ SignatureAlgorithm AlgorithmIdentifier
+ SignatureValue asn1.BitString
+}
+
+// HasExpired reports whether now is past the expiry time of certList.
+func (certList *CertificateList) HasExpired(now time.Time) bool {
+ return now.After(certList.TBSCertList.NextUpdate)
+}
+
+// TBSCertificateList represents the ASN.1 structure of the same name. See RFC
+// 5280, section 5.1.
+type TBSCertificateList struct {
+ Raw asn1.RawContent
+ Version int `asn1:"optional,default:2"`
+ Signature AlgorithmIdentifier
+ Issuer RDNSequence
+ ThisUpdate time.Time
+ NextUpdate time.Time
+ RevokedCertificates []RevokedCertificate `asn1:"optional"`
+ Extensions []Extension `asn1:"tag:0,optional,explicit"`
+}
+
+// RevokedCertificate represents the ASN.1 structure of the same name. See RFC
+// 5280, section 5.1.
+type RevokedCertificate struct {
+ SerialNumber *big.Int
+ RevocationTime time.Time
+ Extensions []Extension `asn1:"optional"`
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root.go b/vendor/github.com/google/certificate-transparency/go/x509/root.go
new file mode 100755
index 0000000..8aae14e
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/root.go
@@ -0,0 +1,17 @@
+// 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 x509
+
+import "sync"
+
+var (
+ once sync.Once
+ systemRoots *CertPool
+)
+
+func systemRootsPool() *CertPool {
+ once.Do(initSystemRoots)
+ return systemRoots
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root_darwin.go b/vendor/github.com/google/certificate-transparency/go/x509/root_darwin.go
new file mode 100755
index 0000000..3d3fa4e
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/root_darwin.go
@@ -0,0 +1,83 @@
+// 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.
+
+// +build darwin,cgo
+
+package x509
+
+/*
+#cgo CFLAGS: -mmacosx-version-min=10.6 -D__MAC_OS_X_VERSION_MAX_ALLOWED=1060
+#cgo LDFLAGS: -framework CoreFoundation -framework Security
+
+#include <CoreFoundation/CoreFoundation.h>
+#include <Security/Security.h>
+
+// FetchPEMRootsCTX509 fetches the system's list of trusted X.509 root certificates.
+//
+// On success it returns 0 and fills pemRoots with a CFDataRef that contains the extracted root
+// certificates of the system. On failure, the function returns -1.
+//
+// Note: The CFDataRef returned in pemRoots must be released (using CFRelease) after
+// we've consumed its content.
+int FetchPEMRootsCTX509(CFDataRef *pemRoots) {
+ if (pemRoots == NULL) {
+ return -1;
+ }
+
+ CFArrayRef certs = NULL;
+ OSStatus err = SecTrustCopyAnchorCertificates(&certs);
+ if (err != noErr) {
+ return -1;
+ }
+
+ CFMutableDataRef combinedData = CFDataCreateMutable(kCFAllocatorDefault, 0);
+ int i, ncerts = CFArrayGetCount(certs);
+ for (i = 0; i < ncerts; i++) {
+ CFDataRef data = NULL;
+ SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
+ if (cert == NULL) {
+ continue;
+ }
+
+ // Note: SecKeychainItemExport is deprecated as of 10.7 in favor of SecItemExport.
+ // Once we support weak imports via cgo we should prefer that, and fall back to this
+ // for older systems.
+ err = SecKeychainItemExport(cert, kSecFormatX509Cert, kSecItemPemArmour, NULL, &data);
+ if (err != noErr) {
+ continue;
+ }
+
+ if (data != NULL) {
+ CFDataAppendBytes(combinedData, CFDataGetBytePtr(data), CFDataGetLength(data));
+ CFRelease(data);
+ }
+ }
+
+ CFRelease(certs);
+
+ *pemRoots = combinedData;
+ return 0;
+}
+*/
+import "C"
+import "unsafe"
+
+func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) {
+ return nil, nil
+}
+
+func initSystemRoots() {
+ roots := NewCertPool()
+
+ var data C.CFDataRef = nil
+ err := C.FetchPEMRootsCTX509(&data)
+ if err == -1 {
+ return
+ }
+
+ defer C.CFRelease(C.CFTypeRef(data))
+ buf := C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(data)), C.int(C.CFDataGetLength(data)))
+ roots.AppendCertsFromPEM(buf)
+ systemRoots = roots
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root_plan9.go b/vendor/github.com/google/certificate-transparency/go/x509/root_plan9.go
new file mode 100755
index 0000000..9965caa
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/root_plan9.go
@@ -0,0 +1,33 @@
+// 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 plan9
+
+package x509
+
+import "io/ioutil"
+
+// Possible certificate files; stop after finding one.
+var certFiles = []string{
+ "/sys/lib/tls/ca.pem",
+}
+
+func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) {
+ return nil, nil
+}
+
+func initSystemRoots() {
+ roots := NewCertPool()
+ for _, file := range certFiles {
+ data, err := ioutil.ReadFile(file)
+ if err == nil {
+ roots.AppendCertsFromPEM(data)
+ systemRoots = roots
+ return
+ }
+ }
+
+ // All of the files failed to load. systemRoots will be nil which will
+ // trigger a specific error at verification time.
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root_stub.go b/vendor/github.com/google/certificate-transparency/go/x509/root_stub.go
new file mode 100755
index 0000000..4c742cc
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/root_stub.go
@@ -0,0 +1,14 @@
+// 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.
+
+// +build darwin,!cgo
+
+package x509
+
+func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) {
+ return nil, nil
+}
+
+func initSystemRoots() {
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root_unix.go b/vendor/github.com/google/certificate-transparency/go/x509/root_unix.go
new file mode 100755
index 0000000..a5bd19e
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/root_unix.go
@@ -0,0 +1,37 @@
+// 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.
+
+// +build dragonfly freebsd linux openbsd netbsd solaris
+
+package x509
+
+import "io/ioutil"
+
+// Possible certificate files; stop after finding one.
+var certFiles = []string{
+ "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
+ "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL
+ "/etc/ssl/ca-bundle.pem", // OpenSUSE
+ "/etc/ssl/cert.pem", // OpenBSD
+ "/usr/local/share/certs/ca-root-nss.crt", // FreeBSD/DragonFly
+}
+
+func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) {
+ return nil, nil
+}
+
+func initSystemRoots() {
+ roots := NewCertPool()
+ for _, file := range certFiles {
+ data, err := ioutil.ReadFile(file)
+ if err == nil {
+ roots.AppendCertsFromPEM(data)
+ systemRoots = roots
+ return
+ }
+ }
+
+ // All of the files failed to load. systemRoots will be nil which will
+ // trigger a specific error at verification time.
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/root_windows.go b/vendor/github.com/google/certificate-transparency/go/x509/root_windows.go
new file mode 100755
index 0000000..81018b7
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/root_windows.go
@@ -0,0 +1,229 @@
+// 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 x509
+
+import (
+ "errors"
+ "syscall"
+ "unsafe"
+)
+
+// Creates a new *syscall.CertContext representing the leaf certificate in an in-memory
+// certificate store containing itself and all of the intermediate certificates specified
+// in the opts.Intermediates CertPool.
+//
+// A pointer to the in-memory store is available in the returned CertContext's Store field.
+// The store is automatically freed when the CertContext is freed using
+// syscall.CertFreeCertificateContext.
+func createStoreContext(leaf *Certificate, opts *VerifyOptions) (*syscall.CertContext, error) {
+ var storeCtx *syscall.CertContext
+
+ leafCtx, err := syscall.CertCreateCertificateContext(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING, &leaf.Raw[0], uint32(len(leaf.Raw)))
+ if err != nil {
+ return nil, err
+ }
+ defer syscall.CertFreeCertificateContext(leafCtx)
+
+ handle, err := syscall.CertOpenStore(syscall.CERT_STORE_PROV_MEMORY, 0, 0, syscall.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, 0)
+ if err != nil {
+ return nil, err
+ }
+ defer syscall.CertCloseStore(handle, 0)
+
+ err = syscall.CertAddCertificateContextToStore(handle, leafCtx, syscall.CERT_STORE_ADD_ALWAYS, &storeCtx)
+ if err != nil {
+ return nil, err
+ }
+
+ if opts.Intermediates != nil {
+ for _, intermediate := range opts.Intermediates.certs {
+ ctx, err := syscall.CertCreateCertificateContext(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING, &intermediate.Raw[0], uint32(len(intermediate.Raw)))
+ if err != nil {
+ return nil, err
+ }
+
+ err = syscall.CertAddCertificateContextToStore(handle, ctx, syscall.CERT_STORE_ADD_ALWAYS, nil)
+ syscall.CertFreeCertificateContext(ctx)
+ if err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ return storeCtx, nil
+}
+
+// extractSimpleChain extracts the final certificate chain from a CertSimpleChain.
+func extractSimpleChain(simpleChain **syscall.CertSimpleChain, count int) (chain []*Certificate, err error) {
+ if simpleChain == nil || count == 0 {
+ return nil, errors.New("x509: invalid simple chain")
+ }
+
+ simpleChains := (*[1 << 20]*syscall.CertSimpleChain)(unsafe.Pointer(simpleChain))[:]
+ lastChain := simpleChains[count-1]
+ elements := (*[1 << 20]*syscall.CertChainElement)(unsafe.Pointer(lastChain.Elements))[:]
+ for i := 0; i < int(lastChain.NumElements); i++ {
+ // Copy the buf, since ParseCertificate does not create its own copy.
+ cert := elements[i].CertContext
+ encodedCert := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:]
+ buf := make([]byte, cert.Length)
+ copy(buf, encodedCert[:])
+ parsedCert, err := ParseCertificate(buf)
+ if err != nil {
+ return nil, err
+ }
+ chain = append(chain, parsedCert)
+ }
+
+ return chain, nil
+}
+
+// checkChainTrustStatus checks the trust status of the certificate chain, translating
+// any errors it finds into Go errors in the process.
+func checkChainTrustStatus(c *Certificate, chainCtx *syscall.CertChainContext) error {
+ if chainCtx.TrustStatus.ErrorStatus != syscall.CERT_TRUST_NO_ERROR {
+ status := chainCtx.TrustStatus.ErrorStatus
+ switch status {
+ case syscall.CERT_TRUST_IS_NOT_TIME_VALID:
+ return CertificateInvalidError{c, Expired}
+ default:
+ return UnknownAuthorityError{c, nil, nil}
+ }
+ }
+ return nil
+}
+
+// checkChainSSLServerPolicy checks that the certificate chain in chainCtx is valid for
+// use as a certificate chain for a SSL/TLS server.
+func checkChainSSLServerPolicy(c *Certificate, chainCtx *syscall.CertChainContext, opts *VerifyOptions) error {
+ servernamep, err := syscall.UTF16PtrFromString(opts.DNSName)
+ if err != nil {
+ return err
+ }
+ sslPara := &syscall.SSLExtraCertChainPolicyPara{
+ AuthType: syscall.AUTHTYPE_SERVER,
+ ServerName: servernamep,
+ }
+ sslPara.Size = uint32(unsafe.Sizeof(*sslPara))
+
+ para := &syscall.CertChainPolicyPara{
+ ExtraPolicyPara: uintptr(unsafe.Pointer(sslPara)),
+ }
+ para.Size = uint32(unsafe.Sizeof(*para))
+
+ status := syscall.CertChainPolicyStatus{}
+ err = syscall.CertVerifyCertificateChainPolicy(syscall.CERT_CHAIN_POLICY_SSL, chainCtx, para, &status)
+ if err != nil {
+ return err
+ }
+
+ // TODO(mkrautz): use the lChainIndex and lElementIndex fields
+ // of the CertChainPolicyStatus to provide proper context, instead
+ // using c.
+ if status.Error != 0 {
+ switch status.Error {
+ case syscall.CERT_E_EXPIRED:
+ return CertificateInvalidError{c, Expired}
+ case syscall.CERT_E_CN_NO_MATCH:
+ return HostnameError{c, opts.DNSName}
+ case syscall.CERT_E_UNTRUSTEDROOT:
+ return UnknownAuthorityError{c, nil, nil}
+ default:
+ return UnknownAuthorityError{c, nil, nil}
+ }
+ }
+
+ return nil
+}
+
+// systemVerify is like Verify, except that it uses CryptoAPI calls
+// to build certificate chains and verify them.
+func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) {
+ hasDNSName := opts != nil && len(opts.DNSName) > 0
+
+ storeCtx, err := createStoreContext(c, opts)
+ if err != nil {
+ return nil, err
+ }
+ defer syscall.CertFreeCertificateContext(storeCtx)
+
+ para := new(syscall.CertChainPara)
+ para.Size = uint32(unsafe.Sizeof(*para))
+
+ // If there's a DNSName set in opts, assume we're verifying
+ // a certificate from a TLS server.
+ if hasDNSName {
+ oids := []*byte{
+ &syscall.OID_PKIX_KP_SERVER_AUTH[0],
+ // Both IE and Chrome allow certificates with
+ // Server Gated Crypto as well. Some certificates
+ // in the wild require them.
+ &syscall.OID_SERVER_GATED_CRYPTO[0],
+ &syscall.OID_SGC_NETSCAPE[0],
+ }
+ para.RequestedUsage.Type = syscall.USAGE_MATCH_TYPE_OR
+ para.RequestedUsage.Usage.Length = uint32(len(oids))
+ para.RequestedUsage.Usage.UsageIdentifiers = &oids[0]
+ } else {
+ para.RequestedUsage.Type = syscall.USAGE_MATCH_TYPE_AND
+ para.RequestedUsage.Usage.Length = 0
+ para.RequestedUsage.Usage.UsageIdentifiers = nil
+ }
+
+ var verifyTime *syscall.Filetime
+ if opts != nil && !opts.CurrentTime.IsZero() {
+ ft := syscall.NsecToFiletime(opts.CurrentTime.UnixNano())
+ verifyTime = &ft
+ }
+
+ // CertGetCertificateChain will traverse Windows's root stores
+ // in an attempt to build a verified certificate chain. Once
+ // it has found a verified chain, it stops. MSDN docs on
+ // CERT_CHAIN_CONTEXT:
+ //
+ // When a CERT_CHAIN_CONTEXT is built, the first simple chain
+ // begins with an end certificate and ends with a self-signed
+ // certificate. If that self-signed certificate is not a root
+ // or otherwise trusted certificate, an attempt is made to
+ // build a new chain. CTLs are used to create the new chain
+ // beginning with the self-signed certificate from the original
+ // chain as the end certificate of the new chain. This process
+ // continues building additional simple chains until the first
+ // self-signed certificate is a trusted certificate or until
+ // an additional simple chain cannot be built.
+ //
+ // The result is that we'll only get a single trusted chain to
+ // return to our caller.
+ var chainCtx *syscall.CertChainContext
+ err = syscall.CertGetCertificateChain(syscall.Handle(0), storeCtx, verifyTime, storeCtx.Store, para, 0, 0, &chainCtx)
+ if err != nil {
+ return nil, err
+ }
+ defer syscall.CertFreeCertificateChain(chainCtx)
+
+ err = checkChainTrustStatus(c, chainCtx)
+ if err != nil {
+ return nil, err
+ }
+
+ if hasDNSName {
+ err = checkChainSSLServerPolicy(c, chainCtx, opts)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ chain, err := extractSimpleChain(chainCtx.Chains, int(chainCtx.ChainCount))
+ if err != nil {
+ return nil, err
+ }
+
+ chains = append(chains, chain)
+
+ return chains, nil
+}
+
+func initSystemRoots() {
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/sec1.go b/vendor/github.com/google/certificate-transparency/go/x509/sec1.go
new file mode 100755
index 0000000..dbc255f
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/sec1.go
@@ -0,0 +1,85 @@
+// 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 x509
+
+import (
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ // START CT CHANGES
+ "github.com/google/certificate-transparency/go/asn1"
+ // START CT CHANGES
+ "errors"
+ "fmt"
+ "math/big"
+)
+
+const ecPrivKeyVersion = 1
+
+// ecPrivateKey reflects an ASN.1 Elliptic Curve Private Key Structure.
+// References:
+// RFC5915
+// SEC1 - http://www.secg.org/download/aid-780/sec1-v2.pdf
+// Per RFC5915 the NamedCurveOID is marked as ASN.1 OPTIONAL, however in
+// most cases it is not.
+type ecPrivateKey struct {
+ Version int
+ PrivateKey []byte
+ NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"`
+ PublicKey asn1.BitString `asn1:"optional,explicit,tag:1"`
+}
+
+// ParseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
+func ParseECPrivateKey(der []byte) (key *ecdsa.PrivateKey, err error) {
+ return parseECPrivateKey(nil, der)
+}
+
+// MarshalECPrivateKey marshals an EC private key into ASN.1, DER format.
+func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error) {
+ oid, ok := oidFromNamedCurve(key.Curve)
+ if !ok {
+ return nil, errors.New("x509: unknown elliptic curve")
+ }
+ return asn1.Marshal(ecPrivateKey{
+ Version: 1,
+ PrivateKey: key.D.Bytes(),
+ NamedCurveOID: oid,
+ PublicKey: asn1.BitString{Bytes: elliptic.Marshal(key.Curve, key.X, key.Y)},
+ })
+}
+
+// parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
+// The OID for the named curve may be provided from another source (such as
+// the PKCS8 container) - if it is provided then use this instead of the OID
+// that may exist in the EC private key structure.
+func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) {
+ var privKey ecPrivateKey
+ if _, err := asn1.Unmarshal(der, &privKey); err != nil {
+ return nil, errors.New("x509: failed to parse EC private key: " + err.Error())
+ }
+ if privKey.Version != ecPrivKeyVersion {
+ return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version)
+ }
+
+ var curve elliptic.Curve
+ if namedCurveOID != nil {
+ curve = namedCurveFromOID(*namedCurveOID)
+ } else {
+ curve = namedCurveFromOID(privKey.NamedCurveOID)
+ }
+ if curve == nil {
+ return nil, errors.New("x509: unknown elliptic curve")
+ }
+
+ k := new(big.Int).SetBytes(privKey.PrivateKey)
+ if k.Cmp(curve.Params().N) >= 0 {
+ return nil, errors.New("x509: invalid elliptic curve private key value")
+ }
+ priv := new(ecdsa.PrivateKey)
+ priv.Curve = curve
+ priv.D = k
+ priv.X, priv.Y = curve.ScalarBaseMult(privKey.PrivateKey)
+
+ return priv, nil
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/verify.go b/vendor/github.com/google/certificate-transparency/go/x509/verify.go
new file mode 100755
index 0000000..e82dbc1
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/verify.go
@@ -0,0 +1,476 @@
+// 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 x509
+
+import (
+ "fmt"
+ "net"
+ "runtime"
+ "strings"
+ "time"
+ "unicode/utf8"
+)
+
+type InvalidReason int
+
+const (
+ // NotAuthorizedToSign results when a certificate is signed by another
+ // which isn't marked as a CA certificate.
+ NotAuthorizedToSign InvalidReason = iota
+ // Expired results when a certificate has expired, based on the time
+ // given in the VerifyOptions.
+ Expired
+ // CANotAuthorizedForThisName results when an intermediate or root
+ // certificate has a name constraint which doesn't include the name
+ // being checked.
+ CANotAuthorizedForThisName
+ // TooManyIntermediates results when a path length constraint is
+ // violated.
+ TooManyIntermediates
+ // IncompatibleUsage results when the certificate's key usage indicates
+ // that it may only be used for a different purpose.
+ IncompatibleUsage
+)
+
+// CertificateInvalidError results when an odd error occurs. Users of this
+// library probably want to handle all these errors uniformly.
+type CertificateInvalidError struct {
+ Cert *Certificate
+ Reason InvalidReason
+}
+
+func (e CertificateInvalidError) Error() string {
+ switch e.Reason {
+ case NotAuthorizedToSign:
+ return "x509: certificate is not authorized to sign other certificates"
+ case Expired:
+ return "x509: certificate has expired or is not yet valid"
+ case CANotAuthorizedForThisName:
+ return "x509: a root or intermediate certificate is not authorized to sign in this domain"
+ case TooManyIntermediates:
+ return "x509: too many intermediates for path length constraint"
+ case IncompatibleUsage:
+ return "x509: certificate specifies an incompatible key usage"
+ }
+ return "x509: unknown error"
+}
+
+// HostnameError results when the set of authorized names doesn't match the
+// requested name.
+type HostnameError struct {
+ Certificate *Certificate
+ Host string
+}
+
+func (h HostnameError) Error() string {
+ c := h.Certificate
+
+ var valid string
+ if ip := net.ParseIP(h.Host); ip != nil {
+ // Trying to validate an IP
+ if len(c.IPAddresses) == 0 {
+ return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs"
+ }
+ for _, san := range c.IPAddresses {
+ if len(valid) > 0 {
+ valid += ", "
+ }
+ valid += san.String()
+ }
+ } else {
+ if len(c.DNSNames) > 0 {
+ valid = strings.Join(c.DNSNames, ", ")
+ } else {
+ valid = c.Subject.CommonName
+ }
+ }
+ return "x509: certificate is valid for " + valid + ", not " + h.Host
+}
+
+// UnknownAuthorityError results when the certificate issuer is unknown
+type UnknownAuthorityError struct {
+ cert *Certificate
+ // hintErr contains an error that may be helpful in determining why an
+ // authority wasn't found.
+ hintErr error
+ // hintCert contains a possible authority certificate that was rejected
+ // because of the error in hintErr.
+ hintCert *Certificate
+}
+
+func (e UnknownAuthorityError) Error() string {
+ s := "x509: certificate signed by unknown authority"
+ if e.hintErr != nil {
+ certName := e.hintCert.Subject.CommonName
+ if len(certName) == 0 {
+ if len(e.hintCert.Subject.Organization) > 0 {
+ certName = e.hintCert.Subject.Organization[0]
+ }
+ certName = "serial:" + e.hintCert.SerialNumber.String()
+ }
+ s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
+ }
+ return s
+}
+
+// SystemRootsError results when we fail to load the system root certificates.
+type SystemRootsError struct {
+}
+
+func (e SystemRootsError) Error() string {
+ return "x509: failed to load system roots and no roots provided"
+}
+
+// VerifyOptions contains parameters for Certificate.Verify. It's a structure
+// because other PKIX verification APIs have ended up needing many options.
+type VerifyOptions struct {
+ DNSName string
+ Intermediates *CertPool
+ Roots *CertPool // if nil, the system roots are used
+ CurrentTime time.Time // if zero, the current time is used
+ DisableTimeChecks bool
+ // KeyUsage specifies which Extended Key Usage values are acceptable.
+ // An empty list means ExtKeyUsageServerAuth. Key usage is considered a
+ // constraint down the chain which mirrors Windows CryptoAPI behaviour,
+ // but not the spec. To accept any key usage, include ExtKeyUsageAny.
+ KeyUsages []ExtKeyUsage
+}
+
+const (
+ leafCertificate = iota
+ intermediateCertificate
+ rootCertificate
+)
+
+// isValid performs validity checks on the c.
+func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
+ if !opts.DisableTimeChecks {
+ now := opts.CurrentTime
+ if now.IsZero() {
+ now = time.Now()
+ }
+ if now.Before(c.NotBefore) || now.After(c.NotAfter) {
+ return CertificateInvalidError{c, Expired}
+ }
+ }
+
+ if len(c.PermittedDNSDomains) > 0 {
+ ok := false
+ for _, domain := range c.PermittedDNSDomains {
+ if opts.DNSName == domain ||
+ (strings.HasSuffix(opts.DNSName, domain) &&
+ len(opts.DNSName) >= 1+len(domain) &&
+ opts.DNSName[len(opts.DNSName)-len(domain)-1] == '.') {
+ ok = true
+ break
+ }
+ }
+
+ if !ok {
+ return CertificateInvalidError{c, CANotAuthorizedForThisName}
+ }
+ }
+
+ // KeyUsage status flags are ignored. From Engineering Security, Peter
+ // Gutmann: A European government CA marked its signing certificates as
+ // being valid for encryption only, but no-one noticed. Another
+ // European CA marked its signature keys as not being valid for
+ // signatures. A different CA marked its own trusted root certificate
+ // as being invalid for certificate signing. Another national CA
+ // distributed a certificate to be used to encrypt data for the
+ // country’s tax authority that was marked as only being usable for
+ // digital signatures but not for encryption. Yet another CA reversed
+ // the order of the bit flags in the keyUsage due to confusion over
+ // encoding endianness, essentially setting a random keyUsage in
+ // certificates that it issued. Another CA created a self-invalidating
+ // certificate by adding a certificate policy statement stipulating
+ // that the certificate had to be used strictly as specified in the
+ // keyUsage, and a keyUsage containing a flag indicating that the RSA
+ // encryption key could only be used for Diffie-Hellman key agreement.
+
+ if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
+ return CertificateInvalidError{c, NotAuthorizedToSign}
+ }
+
+ if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
+ numIntermediates := len(currentChain) - 1
+ if numIntermediates > c.MaxPathLen {
+ return CertificateInvalidError{c, TooManyIntermediates}
+ }
+ }
+
+ return nil
+}
+
+// Verify attempts to verify c by building one or more chains from c to a
+// certificate in opts.Roots, using certificates in opts.Intermediates if
+// needed. If successful, it returns one or more chains where the first
+// element of the chain is c and the last element is from opts.Roots.
+//
+// WARNING: this doesn't do any revocation checking.
+func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
+ // Use Windows's own verification and chain building.
+ if opts.Roots == nil && runtime.GOOS == "windows" {
+ return c.systemVerify(&opts)
+ }
+
+ if opts.Roots == nil {
+ opts.Roots = systemRootsPool()
+ if opts.Roots == nil {
+ return nil, SystemRootsError{}
+ }
+ }
+
+ err = c.isValid(leafCertificate, nil, &opts)
+ if err != nil {
+ return
+ }
+
+ if len(opts.DNSName) > 0 {
+ err = c.VerifyHostname(opts.DNSName)
+ if err != nil {
+ return
+ }
+ }
+
+ candidateChains, err := c.buildChains(make(map[int][][]*Certificate), []*Certificate{c}, &opts)
+ if err != nil {
+ return
+ }
+
+ keyUsages := opts.KeyUsages
+ if len(keyUsages) == 0 {
+ keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
+ }
+
+ // If any key usage is acceptable then we're done.
+ for _, usage := range keyUsages {
+ if usage == ExtKeyUsageAny {
+ chains = candidateChains
+ return
+ }
+ }
+
+ for _, candidate := range candidateChains {
+ if checkChainForKeyUsage(candidate, keyUsages) {
+ chains = append(chains, candidate)
+ }
+ }
+
+ if len(chains) == 0 {
+ err = CertificateInvalidError{c, IncompatibleUsage}
+ }
+
+ return
+}
+
+func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
+ n := make([]*Certificate, len(chain)+1)
+ copy(n, chain)
+ n[len(chain)] = cert
+ return n
+}
+
+func (c *Certificate) buildChains(cache map[int][][]*Certificate, currentChain []*Certificate, opts *VerifyOptions) (chains [][]*Certificate, err error) {
+ possibleRoots, failedRoot, rootErr := opts.Roots.findVerifiedParents(c)
+ for _, rootNum := range possibleRoots {
+ root := opts.Roots.certs[rootNum]
+ err = root.isValid(rootCertificate, currentChain, opts)
+ if err != nil {
+ continue
+ }
+ chains = append(chains, appendToFreshChain(currentChain, root))
+ }
+
+ possibleIntermediates, failedIntermediate, intermediateErr := opts.Intermediates.findVerifiedParents(c)
+nextIntermediate:
+ for _, intermediateNum := range possibleIntermediates {
+ intermediate := opts.Intermediates.certs[intermediateNum]
+ for _, cert := range currentChain {
+ if cert == intermediate {
+ continue nextIntermediate
+ }
+ }
+ err = intermediate.isValid(intermediateCertificate, currentChain, opts)
+ if err != nil {
+ continue
+ }
+ var childChains [][]*Certificate
+ childChains, ok := cache[intermediateNum]
+ if !ok {
+ childChains, err = intermediate.buildChains(cache, appendToFreshChain(currentChain, intermediate), opts)
+ cache[intermediateNum] = childChains
+ }
+ chains = append(chains, childChains...)
+ }
+
+ if len(chains) > 0 {
+ err = nil
+ }
+
+ if len(chains) == 0 && err == nil {
+ hintErr := rootErr
+ hintCert := failedRoot
+ if hintErr == nil {
+ hintErr = intermediateErr
+ hintCert = failedIntermediate
+ }
+ err = UnknownAuthorityError{c, hintErr, hintCert}
+ }
+
+ return
+}
+
+func matchHostnames(pattern, host string) bool {
+ if len(pattern) == 0 || len(host) == 0 {
+ return false
+ }
+
+ patternParts := strings.Split(pattern, ".")
+ hostParts := strings.Split(host, ".")
+
+ if len(patternParts) != len(hostParts) {
+ return false
+ }
+
+ for i, patternPart := range patternParts {
+ if patternPart == "*" {
+ continue
+ }
+ if patternPart != hostParts[i] {
+ return false
+ }
+ }
+
+ return true
+}
+
+// toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
+// an explicitly ASCII function to avoid any sharp corners resulting from
+// performing Unicode operations on DNS labels.
+func toLowerCaseASCII(in string) string {
+ // If the string is already lower-case then there's nothing to do.
+ isAlreadyLowerCase := true
+ for _, c := range in {
+ if c == utf8.RuneError {
+ // If we get a UTF-8 error then there might be
+ // upper-case ASCII bytes in the invalid sequence.
+ isAlreadyLowerCase = false
+ break
+ }
+ if 'A' <= c && c <= 'Z' {
+ isAlreadyLowerCase = false
+ break
+ }
+ }
+
+ if isAlreadyLowerCase {
+ return in
+ }
+
+ out := []byte(in)
+ for i, c := range out {
+ if 'A' <= c && c <= 'Z' {
+ out[i] += 'a' - 'A'
+ }
+ }
+ return string(out)
+}
+
+// VerifyHostname returns nil if c is a valid certificate for the named host.
+// Otherwise it returns an error describing the mismatch.
+func (c *Certificate) VerifyHostname(h string) error {
+ // IP addresses may be written in [ ].
+ candidateIP := h
+ if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
+ candidateIP = h[1 : len(h)-1]
+ }
+ if ip := net.ParseIP(candidateIP); ip != nil {
+ // We only match IP addresses against IP SANs.
+ // https://tools.ietf.org/html/rfc6125#appendix-B.2
+ for _, candidate := range c.IPAddresses {
+ if ip.Equal(candidate) {
+ return nil
+ }
+ }
+ return HostnameError{c, candidateIP}
+ }
+
+ lowered := toLowerCaseASCII(h)
+
+ if len(c.DNSNames) > 0 {
+ for _, match := range c.DNSNames {
+ if matchHostnames(toLowerCaseASCII(match), lowered) {
+ return nil
+ }
+ }
+ // If Subject Alt Name is given, we ignore the common name.
+ } else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) {
+ return nil
+ }
+
+ return HostnameError{c, h}
+}
+
+func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
+ usages := make([]ExtKeyUsage, len(keyUsages))
+ copy(usages, keyUsages)
+
+ if len(chain) == 0 {
+ return false
+ }
+
+ usagesRemaining := len(usages)
+
+ // We walk down the list and cross out any usages that aren't supported
+ // by each certificate. If we cross out all the usages, then the chain
+ // is unacceptable.
+
+ for i := len(chain) - 1; i >= 0; i-- {
+ cert := chain[i]
+ if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
+ // The certificate doesn't have any extended key usage specified.
+ continue
+ }
+
+ for _, usage := range cert.ExtKeyUsage {
+ if usage == ExtKeyUsageAny {
+ // The certificate is explicitly good for any usage.
+ continue
+ }
+ }
+
+ const invalidUsage ExtKeyUsage = -1
+
+ NextRequestedUsage:
+ for i, requestedUsage := range usages {
+ if requestedUsage == invalidUsage {
+ continue
+ }
+
+ for _, usage := range cert.ExtKeyUsage {
+ if requestedUsage == usage {
+ continue NextRequestedUsage
+ } else if requestedUsage == ExtKeyUsageServerAuth &&
+ (usage == ExtKeyUsageNetscapeServerGatedCrypto ||
+ usage == ExtKeyUsageMicrosoftServerGatedCrypto) {
+ // In order to support COMODO
+ // certificate chains, we have to
+ // accept Netscape or Microsoft SGC
+ // usages as equal to ServerAuth.
+ continue NextRequestedUsage
+ }
+ }
+
+ usages[i] = invalidUsage
+ usagesRemaining--
+ if usagesRemaining == 0 {
+ return false
+ }
+ }
+ }
+
+ return true
+}
diff --git a/vendor/github.com/google/certificate-transparency/go/x509/x509.go b/vendor/github.com/google/certificate-transparency/go/x509/x509.go
new file mode 100755
index 0000000..cda7220
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/go/x509/x509.go
@@ -0,0 +1,1622 @@
+// Copyright 2009 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 x509 parses X.509-encoded keys and certificates.
+//
+// START CT CHANGES
+// This is a fork of the go library crypto/x509 package, it's more relaxed
+// about certificates that it'll accept, and exports the TBSCertificate
+// structure.
+// END CT CHANGES
+package x509
+
+import (
+ "bytes"
+ "crypto"
+ "crypto/dsa"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rsa"
+ "crypto/sha1"
+ // START CT CHANGES
+ "github.com/google/certificate-transparency/go/asn1"
+ "github.com/google/certificate-transparency/go/x509/pkix"
+ // END CT CHANGES
+ "encoding/pem"
+ "errors"
+ // START CT CHANGES
+ "fmt"
+ // END CT CHANGES
+ "io"
+ "math/big"
+ "net"
+ "time"
+)
+
+// pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
+// in RFC 3280.
+type pkixPublicKey struct {
+ Algo pkix.AlgorithmIdentifier
+ BitString asn1.BitString
+}
+
+// ParsePKIXPublicKey parses a DER encoded public key. These values are
+// typically found in PEM blocks with "BEGIN PUBLIC KEY".
+func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
+ var pki publicKeyInfo
+ if _, err = asn1.Unmarshal(derBytes, &pki); err != nil {
+ return
+ }
+ algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
+ if algo == UnknownPublicKeyAlgorithm {
+ return nil, errors.New("x509: unknown public key algorithm")
+ }
+ return parsePublicKey(algo, &pki)
+}
+
+func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
+ switch pub := pub.(type) {
+ case *rsa.PublicKey:
+ publicKeyBytes, err = asn1.Marshal(rsaPublicKey{
+ N: pub.N,
+ E: pub.E,
+ })
+ publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
+ // This is a NULL parameters value which is technically
+ // superfluous, but most other code includes it and, by
+ // doing this, we match their public key hashes.
+ publicKeyAlgorithm.Parameters = asn1.RawValue{
+ Tag: 5,
+ }
+ case *ecdsa.PublicKey:
+ publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
+ oid, ok := oidFromNamedCurve(pub.Curve)
+ if !ok {
+ return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
+ }
+ publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
+ var paramBytes []byte
+ paramBytes, err = asn1.Marshal(oid)
+ if err != nil {
+ return
+ }
+ publicKeyAlgorithm.Parameters.FullBytes = paramBytes
+ default:
+ return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA public keys supported")
+ }
+
+ return publicKeyBytes, publicKeyAlgorithm, nil
+}
+
+// MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
+func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
+ var publicKeyBytes []byte
+ var publicKeyAlgorithm pkix.AlgorithmIdentifier
+ var err error
+
+ if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
+ return nil, err
+ }
+
+ pkix := pkixPublicKey{
+ Algo: publicKeyAlgorithm,
+ BitString: asn1.BitString{
+ Bytes: publicKeyBytes,
+ BitLength: 8 * len(publicKeyBytes),
+ },
+ }
+
+ ret, _ := asn1.Marshal(pkix)
+ return ret, nil
+}
+
+// These structures reflect the ASN.1 structure of X.509 certificates.:
+
+type certificate struct {
+ Raw asn1.RawContent
+ TBSCertificate tbsCertificate
+ SignatureAlgorithm pkix.AlgorithmIdentifier
+ SignatureValue asn1.BitString
+}
+
+type tbsCertificate struct {
+ Raw asn1.RawContent
+ Version int `asn1:"optional,explicit,default:1,tag:0"`
+ SerialNumber *big.Int
+ SignatureAlgorithm pkix.AlgorithmIdentifier
+ Issuer asn1.RawValue
+ Validity validity
+ Subject asn1.RawValue
+ PublicKey publicKeyInfo
+ UniqueId asn1.BitString `asn1:"optional,tag:1"`
+ SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
+ Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
+}
+
+type dsaAlgorithmParameters struct {
+ P, Q, G *big.Int
+}
+
+type dsaSignature struct {
+ R, S *big.Int
+}
+
+type ecdsaSignature dsaSignature
+
+type validity struct {
+ NotBefore, NotAfter time.Time
+}
+
+type publicKeyInfo struct {
+ Raw asn1.RawContent
+ Algorithm pkix.AlgorithmIdentifier
+ PublicKey asn1.BitString
+}
+
+// RFC 5280, 4.2.1.1
+type authKeyId struct {
+ Id []byte `asn1:"optional,tag:0"`
+}
+
+type SignatureAlgorithm int
+
+const (
+ UnknownSignatureAlgorithm SignatureAlgorithm = iota
+ MD2WithRSA
+ MD5WithRSA
+ SHA1WithRSA
+ SHA256WithRSA
+ SHA384WithRSA
+ SHA512WithRSA
+ DSAWithSHA1
+ DSAWithSHA256
+ ECDSAWithSHA1
+ ECDSAWithSHA256
+ ECDSAWithSHA384
+ ECDSAWithSHA512
+)
+
+type PublicKeyAlgorithm int
+
+const (
+ UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
+ RSA
+ DSA
+ ECDSA
+)
+
+// OIDs for signature algorithms
+//
+// pkcs-1 OBJECT IDENTIFIER ::= {
+// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
+//
+//
+// RFC 3279 2.2.1 RSA Signature Algorithms
+//
+// md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
+//
+// md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
+//
+// sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
+//
+// dsaWithSha1 OBJECT IDENTIFIER ::= {
+// iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
+//
+// RFC 3279 2.2.3 ECDSA Signature Algorithm
+//
+// ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
+// iso(1) member-body(2) us(840) ansi-x962(10045)
+// signatures(4) ecdsa-with-SHA1(1)}
+//
+//
+// RFC 4055 5 PKCS #1 Version 1.5
+//
+// sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
+//
+// sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
+//
+// sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
+//
+//
+// RFC 5758 3.1 DSA Signature Algorithms
+//
+// dsaWithSha256 OBJECT IDENTIFIER ::= {
+// joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
+// csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
+//
+// RFC 5758 3.2 ECDSA Signature Algorithm
+//
+// ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
+// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
+//
+// ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
+// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
+//
+// ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
+// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
+
+var (
+ oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
+ oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
+ oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
+ oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
+ oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
+ oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
+ oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
+ oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2}
+ oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
+ oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
+ oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
+ oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
+)
+
+func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm {
+ switch {
+ case oid.Equal(oidSignatureMD2WithRSA):
+ return MD2WithRSA
+ case oid.Equal(oidSignatureMD5WithRSA):
+ return MD5WithRSA
+ case oid.Equal(oidSignatureSHA1WithRSA):
+ return SHA1WithRSA
+ case oid.Equal(oidSignatureSHA256WithRSA):
+ return SHA256WithRSA
+ case oid.Equal(oidSignatureSHA384WithRSA):
+ return SHA384WithRSA
+ case oid.Equal(oidSignatureSHA512WithRSA):
+ return SHA512WithRSA
+ case oid.Equal(oidSignatureDSAWithSHA1):
+ return DSAWithSHA1
+ case oid.Equal(oidSignatureDSAWithSHA256):
+ return DSAWithSHA256
+ case oid.Equal(oidSignatureECDSAWithSHA1):
+ return ECDSAWithSHA1
+ case oid.Equal(oidSignatureECDSAWithSHA256):
+ return ECDSAWithSHA256
+ case oid.Equal(oidSignatureECDSAWithSHA384):
+ return ECDSAWithSHA384
+ case oid.Equal(oidSignatureECDSAWithSHA512):
+ return ECDSAWithSHA512
+ }
+ return UnknownSignatureAlgorithm
+}
+
+// RFC 3279, 2.3 Public Key Algorithms
+//
+// pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
+// rsadsi(113549) pkcs(1) 1 }
+//
+// rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
+//
+// id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
+// x9-57(10040) x9cm(4) 1 }
+//
+// RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
+//
+// id-ecPublicKey OBJECT IDENTIFIER ::= {
+// iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
+var (
+ oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
+ oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
+ oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
+)
+
+func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
+ switch {
+ case oid.Equal(oidPublicKeyRSA):
+ return RSA
+ case oid.Equal(oidPublicKeyDSA):
+ return DSA
+ case oid.Equal(oidPublicKeyECDSA):
+ return ECDSA
+ }
+ return UnknownPublicKeyAlgorithm
+}
+
+// RFC 5480, 2.1.1.1. Named Curve
+//
+// secp224r1 OBJECT IDENTIFIER ::= {
+// iso(1) identified-organization(3) certicom(132) curve(0) 33 }
+//
+// secp256r1 OBJECT IDENTIFIER ::= {
+// iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
+// prime(1) 7 }
+//
+// secp384r1 OBJECT IDENTIFIER ::= {
+// iso(1) identified-organization(3) certicom(132) curve(0) 34 }
+//
+// secp521r1 OBJECT IDENTIFIER ::= {
+// iso(1) identified-organization(3) certicom(132) curve(0) 35 }
+//
+// NB: secp256r1 is equivalent to prime256v1
+var (
+ oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
+ oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
+ oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
+ oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
+)
+
+func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
+ switch {
+ case oid.Equal(oidNamedCurveP224):
+ return elliptic.P224()
+ case oid.Equal(oidNamedCurveP256):
+ return elliptic.P256()
+ case oid.Equal(oidNamedCurveP384):
+ return elliptic.P384()
+ case oid.Equal(oidNamedCurveP521):
+ return elliptic.P521()
+ }
+ return nil
+}
+
+func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
+ switch curve {
+ case elliptic.P224():
+ return oidNamedCurveP224, true
+ case elliptic.P256():
+ return oidNamedCurveP256, true
+ case elliptic.P384():
+ return oidNamedCurveP384, true
+ case elliptic.P521():
+ return oidNamedCurveP521, true
+ }
+
+ return nil, false
+}
+
+// KeyUsage represents the set of actions that are valid for a given key. It's
+// a bitmap of the KeyUsage* constants.
+type KeyUsage int
+
+const (
+ KeyUsageDigitalSignature KeyUsage = 1 << iota
+ KeyUsageContentCommitment
+ KeyUsageKeyEncipherment
+ KeyUsageDataEncipherment
+ KeyUsageKeyAgreement
+ KeyUsageCertSign
+ KeyUsageCRLSign
+ KeyUsageEncipherOnly
+ KeyUsageDecipherOnly
+)
+
+// RFC 5280, 4.2.1.12 Extended Key Usage
+//
+// anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
+//
+// id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
+//
+// id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
+// id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
+// id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
+// id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
+// id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
+// id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
+var (
+ oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
+ oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
+ oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
+ oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
+ oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
+ oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
+ oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
+ oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
+ oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
+ oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
+ oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
+ oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
+)
+
+// ExtKeyUsage represents an extended set of actions that are valid for a given key.
+// Each of the ExtKeyUsage* constants define a unique action.
+type ExtKeyUsage int
+
+const (
+ ExtKeyUsageAny ExtKeyUsage = iota
+ ExtKeyUsageServerAuth
+ ExtKeyUsageClientAuth
+ ExtKeyUsageCodeSigning
+ ExtKeyUsageEmailProtection
+ ExtKeyUsageIPSECEndSystem
+ ExtKeyUsageIPSECTunnel
+ ExtKeyUsageIPSECUser
+ ExtKeyUsageTimeStamping
+ ExtKeyUsageOCSPSigning
+ ExtKeyUsageMicrosoftServerGatedCrypto
+ ExtKeyUsageNetscapeServerGatedCrypto
+)
+
+// extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
+var extKeyUsageOIDs = []struct {
+ extKeyUsage ExtKeyUsage
+ oid asn1.ObjectIdentifier
+}{
+ {ExtKeyUsageAny, oidExtKeyUsageAny},
+ {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
+ {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
+ {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
+ {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
+ {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
+ {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
+ {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
+ {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
+ {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
+ {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
+ {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
+}
+
+func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
+ for _, pair := range extKeyUsageOIDs {
+ if oid.Equal(pair.oid) {
+ return pair.extKeyUsage, true
+ }
+ }
+ return
+}
+
+func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
+ for _, pair := range extKeyUsageOIDs {
+ if eku == pair.extKeyUsage {
+ return pair.oid, true
+ }
+ }
+ return
+}
+
+// A Certificate represents an X.509 certificate.
+type Certificate struct {
+ Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
+ RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
+ RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
+ RawSubject []byte // DER encoded Subject
+ RawIssuer []byte // DER encoded Issuer
+
+ Signature []byte
+ SignatureAlgorithm SignatureAlgorithm
+
+ PublicKeyAlgorithm PublicKeyAlgorithm
+ PublicKey interface{}
+
+ Version int
+ SerialNumber *big.Int
+ Issuer pkix.Name
+ Subject pkix.Name
+ NotBefore, NotAfter time.Time // Validity bounds.
+ KeyUsage KeyUsage
+
+ // Extensions contains raw X.509 extensions. When parsing certificates,
+ // this can be used to extract non-critical extensions that are not
+ // parsed by this package. When marshaling certificates, the Extensions
+ // field is ignored, see ExtraExtensions.
+ Extensions []pkix.Extension
+
+ // ExtraExtensions contains extensions to be copied, raw, into any
+ // marshaled certificates. Values override any extensions that would
+ // otherwise be produced based on the other fields. The ExtraExtensions
+ // field is not populated when parsing certificates, see Extensions.
+ ExtraExtensions []pkix.Extension
+
+ ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
+ UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
+
+ BasicConstraintsValid bool // if true then the next two fields are valid.
+ IsCA bool
+ MaxPathLen int
+
+ SubjectKeyId []byte
+ AuthorityKeyId []byte
+
+ // RFC 5280, 4.2.2.1 (Authority Information Access)
+ OCSPServer []string
+ IssuingCertificateURL []string
+
+ // Subject Alternate Name values
+ DNSNames []string
+ EmailAddresses []string
+ IPAddresses []net.IP
+
+ // Name constraints
+ PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
+ PermittedDNSDomains []string
+
+ // CRL Distribution Points
+ CRLDistributionPoints []string
+
+ PolicyIdentifiers []asn1.ObjectIdentifier
+}
+
+// ErrUnsupportedAlgorithm results from attempting to perform an operation that
+// involves algorithms that are not currently implemented.
+var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
+
+// ConstraintViolationError results when a requested usage is not permitted by
+// a certificate. For example: checking a signature when the public key isn't a
+// certificate signing key.
+type ConstraintViolationError struct{}
+
+func (ConstraintViolationError) Error() string {
+ return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
+}
+
+func (c *Certificate) Equal(other *Certificate) bool {
+ return bytes.Equal(c.Raw, other.Raw)
+}
+
+// Entrust have a broken root certificate (CN=Entrust.net Certification
+// Authority (2048)) which isn't marked as a CA certificate and is thus invalid
+// according to PKIX.
+// We recognise this certificate by its SubjectPublicKeyInfo and exempt it
+// from the Basic Constraints requirement.
+// See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
+//
+// TODO(agl): remove this hack once their reissued root is sufficiently
+// widespread.
+var entrustBrokenSPKI = []byte{
+ 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
+ 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
+ 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
+ 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
+ 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
+ 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
+ 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
+ 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
+ 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
+ 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
+ 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
+ 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
+ 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
+ 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
+ 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
+ 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
+ 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
+ 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
+ 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
+ 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
+ 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
+ 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
+ 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
+ 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
+ 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
+ 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
+ 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
+ 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
+ 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
+ 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
+ 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
+ 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
+ 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
+ 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
+ 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
+ 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
+ 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
+}
+
+// CheckSignatureFrom verifies that the signature on c is a valid signature
+// from parent.
+func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) {
+ // RFC 5280, 4.2.1.9:
+ // "If the basic constraints extension is not present in a version 3
+ // certificate, or the extension is present but the cA boolean is not
+ // asserted, then the certified public key MUST NOT be used to verify
+ // certificate signatures."
+ // (except for Entrust, see comment above entrustBrokenSPKI)
+ if (parent.Version == 3 && !parent.BasicConstraintsValid ||
+ parent.BasicConstraintsValid && !parent.IsCA) &&
+ !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
+ return ConstraintViolationError{}
+ }
+
+ if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
+ return ConstraintViolationError{}
+ }
+
+ if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
+ return ErrUnsupportedAlgorithm
+ }
+
+ // TODO(agl): don't ignore the path length constraint.
+
+ return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
+}
+
+// CheckSignature verifies that signature is a valid signature over signed from
+// c's public key.
+func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) {
+ var hashType crypto.Hash
+
+ switch algo {
+ case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1:
+ hashType = crypto.SHA1
+ case SHA256WithRSA, DSAWithSHA256, ECDSAWithSHA256:
+ hashType = crypto.SHA256
+ case SHA384WithRSA, ECDSAWithSHA384:
+ hashType = crypto.SHA384
+ case SHA512WithRSA, ECDSAWithSHA512:
+ hashType = crypto.SHA512
+ default:
+ return ErrUnsupportedAlgorithm
+ }
+
+ if !hashType.Available() {
+ return ErrUnsupportedAlgorithm
+ }
+ h := hashType.New()
+
+ h.Write(signed)
+ digest := h.Sum(nil)
+
+ switch pub := c.PublicKey.(type) {
+ case *rsa.PublicKey:
+ return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
+ case *dsa.PublicKey:
+ dsaSig := new(dsaSignature)
+ if _, err := asn1.Unmarshal(signature, dsaSig); err != nil {
+ return err
+ }
+ if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
+ return errors.New("x509: DSA signature contained zero or negative values")
+ }
+ if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
+ return errors.New("x509: DSA verification failure")
+ }
+ return
+ case *ecdsa.PublicKey:
+ ecdsaSig := new(ecdsaSignature)
+ if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
+ return err
+ }
+ if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
+ return errors.New("x509: ECDSA signature contained zero or negative values")
+ }
+ if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
+ return errors.New("x509: ECDSA verification failure")
+ }
+ return
+ }
+ return ErrUnsupportedAlgorithm
+}
+
+// CheckCRLSignature checks that the signature in crl is from c.
+func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) {
+ algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm)
+ return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
+}
+
+// START CT CHANGES
+type UnhandledCriticalExtension struct {
+ ID asn1.ObjectIdentifier
+}
+
+func (h UnhandledCriticalExtension) Error() string {
+ return fmt.Sprintf("x509: unhandled critical extension (%v)", h.ID)
+}
+
+// END CT CHANGES
+
+type basicConstraints struct {
+ IsCA bool `asn1:"optional"`
+ MaxPathLen int `asn1:"optional,default:-1"`
+}
+
+// RFC 5280 4.2.1.4
+type policyInformation struct {
+ Policy asn1.ObjectIdentifier
+ // policyQualifiers omitted
+}
+
+// RFC 5280, 4.2.1.10
+type nameConstraints struct {
+ Permitted []generalSubtree `asn1:"optional,tag:0"`
+ Excluded []generalSubtree `asn1:"optional,tag:1"`
+}
+
+type generalSubtree struct {
+ Name string `asn1:"tag:2,optional,ia5"`
+}
+
+// RFC 5280, 4.2.2.1
+type authorityInfoAccess struct {
+ Method asn1.ObjectIdentifier
+ Location asn1.RawValue
+}
+
+// RFC 5280, 4.2.1.14
+type distributionPoint struct {
+ DistributionPoint distributionPointName `asn1:"optional,tag:0"`
+ Reason asn1.BitString `asn1:"optional,tag:1"`
+ CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
+}
+
+type distributionPointName struct {
+ FullName asn1.RawValue `asn1:"optional,tag:0"`
+ RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
+}
+
+func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
+ asn1Data := keyData.PublicKey.RightAlign()
+ switch algo {
+ case RSA:
+ p := new(rsaPublicKey)
+ _, err := asn1.Unmarshal(asn1Data, p)
+ if err != nil {
+ return nil, err
+ }
+
+ if p.N.Sign() <= 0 {
+ return nil, errors.New("x509: RSA modulus is not a positive number")
+ }
+ if p.E <= 0 {
+ return nil, errors.New("x509: RSA public exponent is not a positive number")
+ }
+
+ pub := &rsa.PublicKey{
+ E: p.E,
+ N: p.N,
+ }
+ return pub, nil
+ case DSA:
+ var p *big.Int
+ _, err := asn1.Unmarshal(asn1Data, &p)
+ if err != nil {
+ return nil, err
+ }
+ paramsData := keyData.Algorithm.Parameters.FullBytes
+ params := new(dsaAlgorithmParameters)
+ _, err = asn1.Unmarshal(paramsData, params)
+ if err != nil {
+ return nil, err
+ }
+ if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
+ return nil, errors.New("x509: zero or negative DSA parameter")
+ }
+ pub := &dsa.PublicKey{
+ Parameters: dsa.Parameters{
+ P: params.P,
+ Q: params.Q,
+ G: params.G,
+ },
+ Y: p,
+ }
+ return pub, nil
+ case ECDSA:
+ paramsData := keyData.Algorithm.Parameters.FullBytes
+ namedCurveOID := new(asn1.ObjectIdentifier)
+ _, err := asn1.Unmarshal(paramsData, namedCurveOID)
+ if err != nil {
+ return nil, err
+ }
+ namedCurve := namedCurveFromOID(*namedCurveOID)
+ if namedCurve == nil {
+ return nil, errors.New("x509: unsupported elliptic curve")
+ }
+ x, y := elliptic.Unmarshal(namedCurve, asn1Data)
+ if x == nil {
+ return nil, errors.New("x509: failed to unmarshal elliptic curve point")
+ }
+ pub := &ecdsa.PublicKey{
+ Curve: namedCurve,
+ X: x,
+ Y: y,
+ }
+ return pub, nil
+ default:
+ return nil, nil
+ }
+}
+
+// START CT CHANGES
+
+// NonFatalErrors is an error type which can hold a number of other errors.
+// It's used to collect a range of non-fatal errors which occur while parsing
+// a certificate, that way we can still match on certs which technically are
+// invalid.
+type NonFatalErrors struct {
+ Errors []error
+}
+
+// Adds an error to the list of errors contained by NonFatalErrors.
+func (e *NonFatalErrors) AddError(err error) {
+ e.Errors = append(e.Errors, err)
+}
+
+// Returns a string consisting of the values of Error() from all of the errors
+// contained in |e|
+func (e NonFatalErrors) Error() string {
+ r := "NonFatalErrors: "
+ for _, err := range e.Errors {
+ r += err.Error() + "; "
+ }
+ return r
+}
+
+// Returns true if |e| contains at least one error
+func (e *NonFatalErrors) HasError() bool {
+ return len(e.Errors) > 0
+}
+
+// END CT CHANGES
+
+func parseCertificate(in *certificate) (*Certificate, error) {
+ // START CT CHANGES
+ var nfe NonFatalErrors
+ // END CT CHANGES
+
+ out := new(Certificate)
+ out.Raw = in.Raw
+ out.RawTBSCertificate = in.TBSCertificate.Raw
+ out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
+ out.RawSubject = in.TBSCertificate.Subject.FullBytes
+ out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
+
+ out.Signature = in.SignatureValue.RightAlign()
+ out.SignatureAlgorithm =
+ getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
+
+ out.PublicKeyAlgorithm =
+ getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
+ var err error
+ out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
+ if err != nil {
+ return nil, err
+ }
+
+ if in.TBSCertificate.SerialNumber.Sign() < 0 {
+ // START CT CHANGES
+ nfe.AddError(errors.New("x509: negative serial number"))
+ // END CT CHANGES
+ }
+
+ out.Version = in.TBSCertificate.Version + 1
+ out.SerialNumber = in.TBSCertificate.SerialNumber
+
+ var issuer, subject pkix.RDNSequence
+ if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
+ return nil, err
+ }
+ if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
+ return nil, err
+ }
+
+ out.Issuer.FillFromRDNSequence(&issuer)
+ out.Subject.FillFromRDNSequence(&subject)
+
+ out.NotBefore = in.TBSCertificate.Validity.NotBefore
+ out.NotAfter = in.TBSCertificate.Validity.NotAfter
+
+ for _, e := range in.TBSCertificate.Extensions {
+ out.Extensions = append(out.Extensions, e)
+
+ if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
+ switch e.Id[3] {
+ case 15:
+ // RFC 5280, 4.2.1.3
+ var usageBits asn1.BitString
+ _, err := asn1.Unmarshal(e.Value, &usageBits)
+
+ if err == nil {
+ var usage int
+ for i := 0; i < 9; i++ {
+ if usageBits.At(i) != 0 {
+ usage |= 1 << uint(i)
+ }
+ }
+ out.KeyUsage = KeyUsage(usage)
+ continue
+ }
+ case 19:
+ // RFC 5280, 4.2.1.9
+ var constraints basicConstraints
+ _, err := asn1.Unmarshal(e.Value, &constraints)
+
+ if err == nil {
+ out.BasicConstraintsValid = true
+ out.IsCA = constraints.IsCA
+ out.MaxPathLen = constraints.MaxPathLen
+ continue
+ }
+ case 17:
+ // RFC 5280, 4.2.1.6
+
+ // SubjectAltName ::= GeneralNames
+ //
+ // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
+ //
+ // GeneralName ::= CHOICE {
+ // otherName [0] OtherName,
+ // rfc822Name [1] IA5String,
+ // dNSName [2] IA5String,
+ // x400Address [3] ORAddress,
+ // directoryName [4] Name,
+ // ediPartyName [5] EDIPartyName,
+ // uniformResourceIdentifier [6] IA5String,
+ // iPAddress [7] OCTET STRING,
+ // registeredID [8] OBJECT IDENTIFIER }
+ var seq asn1.RawValue
+ _, err := asn1.Unmarshal(e.Value, &seq)
+ if err != nil {
+ return nil, err
+ }
+ if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
+ return nil, asn1.StructuralError{Msg: "bad SAN sequence"}
+ }
+
+ parsedName := false
+
+ rest := seq.Bytes
+ for len(rest) > 0 {
+ var v asn1.RawValue
+ rest, err = asn1.Unmarshal(rest, &v)
+ if err != nil {
+ return nil, err
+ }
+ switch v.Tag {
+ case 1:
+ out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes))
+ parsedName = true
+ case 2:
+ out.DNSNames = append(out.DNSNames, string(v.Bytes))
+ parsedName = true
+ case 7:
+ switch len(v.Bytes) {
+ case net.IPv4len, net.IPv6len:
+ out.IPAddresses = append(out.IPAddresses, v.Bytes)
+ default:
+ // START CT CHANGES
+ nfe.AddError(fmt.Errorf("x509: certificate contained IP address of length %d : %v", len(v.Bytes), v.Bytes))
+ // END CT CHANGES
+ }
+ }
+ }
+
+ if parsedName {
+ continue
+ }
+ // If we didn't parse any of the names then we
+ // fall through to the critical check below.
+
+ case 30:
+ // RFC 5280, 4.2.1.10
+
+ // NameConstraints ::= SEQUENCE {
+ // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
+ // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
+ //
+ // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
+ //
+ // GeneralSubtree ::= SEQUENCE {
+ // base GeneralName,
+ // minimum [0] BaseDistance DEFAULT 0,
+ // maximum [1] BaseDistance OPTIONAL }
+ //
+ // BaseDistance ::= INTEGER (0..MAX)
+
+ var constraints nameConstraints
+ _, err := asn1.Unmarshal(e.Value, &constraints)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(constraints.Excluded) > 0 && e.Critical {
+ // START CT CHANGES
+ nfe.AddError(UnhandledCriticalExtension{e.Id})
+ // END CT CHANGES
+ }
+
+ for _, subtree := range constraints.Permitted {
+ if len(subtree.Name) == 0 {
+ if e.Critical {
+ // START CT CHANGES
+ nfe.AddError(UnhandledCriticalExtension{e.Id})
+ // END CT CHANGES
+ }
+ continue
+ }
+ out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
+ }
+ continue
+
+ case 31:
+ // RFC 5280, 4.2.1.14
+
+ // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
+ //
+ // DistributionPoint ::= SEQUENCE {
+ // distributionPoint [0] DistributionPointName OPTIONAL,
+ // reasons [1] ReasonFlags OPTIONAL,
+ // cRLIssuer [2] GeneralNames OPTIONAL }
+ //
+ // DistributionPointName ::= CHOICE {
+ // fullName [0] GeneralNames,
+ // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
+
+ var cdp []distributionPoint
+ _, err := asn1.Unmarshal(e.Value, &cdp)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, dp := range cdp {
+ var n asn1.RawValue
+ _, err = asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n)
+ if err != nil {
+ return nil, err
+ }
+
+ if n.Tag == 6 {
+ out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes))
+ }
+ }
+ continue
+
+ case 35:
+ // RFC 5280, 4.2.1.1
+ var a authKeyId
+ _, err = asn1.Unmarshal(e.Value, &a)
+ if err != nil {
+ return nil, err
+ }
+ out.AuthorityKeyId = a.Id
+ continue
+
+ case 37:
+ // RFC 5280, 4.2.1.12. Extended Key Usage
+
+ // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
+ //
+ // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
+ //
+ // KeyPurposeId ::= OBJECT IDENTIFIER
+
+ var keyUsage []asn1.ObjectIdentifier
+ _, err = asn1.Unmarshal(e.Value, &keyUsage)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, u := range keyUsage {
+ if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
+ out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
+ } else {
+ out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
+ }
+ }
+
+ continue
+
+ case 14:
+ // RFC 5280, 4.2.1.2
+ var keyid []byte
+ _, err = asn1.Unmarshal(e.Value, &keyid)
+ if err != nil {
+ return nil, err
+ }
+ out.SubjectKeyId = keyid
+ continue
+
+ case 32:
+ // RFC 5280 4.2.1.4: Certificate Policies
+ var policies []policyInformation
+ if _, err = asn1.Unmarshal(e.Value, &policies); err != nil {
+ return nil, err
+ }
+ out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
+ for i, policy := range policies {
+ out.PolicyIdentifiers[i] = policy.Policy
+ }
+ }
+ } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
+ // RFC 5280 4.2.2.1: Authority Information Access
+ var aia []authorityInfoAccess
+ if _, err = asn1.Unmarshal(e.Value, &aia); err != nil {
+ return nil, err
+ }
+
+ for _, v := range aia {
+ // GeneralName: uniformResourceIdentifier [6] IA5String
+ if v.Location.Tag != 6 {
+ continue
+ }
+ if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
+ out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
+ } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
+ out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
+ }
+ }
+ }
+
+ if e.Critical {
+ // START CT CHANGES
+ nfe.AddError(UnhandledCriticalExtension{e.Id})
+ // END CT CHANGES
+ }
+ }
+ // START CT CHANGES
+ if nfe.HasError() {
+ return out, nfe
+ }
+ // END CT CHANGES
+ return out, nil
+}
+
+// START CT CHANGES
+
+// ParseTBSCertificate parses a single TBSCertificate from the given ASN.1 DER data.
+// The parsed data is returned in a Certificate struct for ease of access.
+func ParseTBSCertificate(asn1Data []byte) (*Certificate, error) {
+ var tbsCert tbsCertificate
+ rest, err := asn1.Unmarshal(asn1Data, &tbsCert)
+ if err != nil {
+ return nil, err
+ }
+ if len(rest) > 0 {
+ return nil, asn1.SyntaxError{Msg: "trailing data"}
+ }
+ return parseCertificate(&certificate{
+ Raw: tbsCert.Raw,
+ TBSCertificate: tbsCert})
+}
+
+// END CT CHANGES
+
+// ParseCertificate parses a single certificate from the given ASN.1 DER data.
+func ParseCertificate(asn1Data []byte) (*Certificate, error) {
+ var cert certificate
+ rest, err := asn1.Unmarshal(asn1Data, &cert)
+ if err != nil {
+ return nil, err
+ }
+ if len(rest) > 0 {
+ return nil, asn1.SyntaxError{Msg: "trailing data"}
+ }
+
+ return parseCertificate(&cert)
+}
+
+// ParseCertificates parses one or more certificates from the given ASN.1 DER
+// data. The certificates must be concatenated with no intermediate padding.
+func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
+ var v []*certificate
+
+ for len(asn1Data) > 0 {
+ cert := new(certificate)
+ var err error
+ asn1Data, err = asn1.Unmarshal(asn1Data, cert)
+ if err != nil {
+ return nil, err
+ }
+ v = append(v, cert)
+ }
+
+ ret := make([]*Certificate, len(v))
+ for i, ci := range v {
+ cert, err := parseCertificate(ci)
+ if err != nil {
+ return nil, err
+ }
+ ret[i] = cert
+ }
+
+ return ret, nil
+}
+
+func reverseBitsInAByte(in byte) byte {
+ b1 := in>>4 | in<<4
+ b2 := b1>>2&0x33 | b1<<2&0xcc
+ b3 := b2>>1&0x55 | b2<<1&0xaa
+ return b3
+}
+
+var (
+ oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
+ oidExtensionKeyUsage = []int{2, 5, 29, 15}
+ oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
+ oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
+ oidExtensionBasicConstraints = []int{2, 5, 29, 19}
+ oidExtensionSubjectAltName = []int{2, 5, 29, 17}
+ oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
+ oidExtensionNameConstraints = []int{2, 5, 29, 30}
+ oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
+ oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
+)
+
+var (
+ oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
+ oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
+)
+
+// oidNotInExtensions returns whether an extension with the given oid exists in
+// extensions.
+func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
+ for _, e := range extensions {
+ if e.Id.Equal(oid) {
+ return true
+ }
+ }
+ return false
+}
+
+func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
+ ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
+ n := 0
+
+ if template.KeyUsage != 0 &&
+ !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
+ ret[n].Id = oidExtensionKeyUsage
+ ret[n].Critical = true
+
+ var a [2]byte
+ a[0] = reverseBitsInAByte(byte(template.KeyUsage))
+ a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
+
+ l := 1
+ if a[1] != 0 {
+ l = 2
+ }
+
+ ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
+ !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
+ ret[n].Id = oidExtensionExtendedKeyUsage
+
+ var oids []asn1.ObjectIdentifier
+ for _, u := range template.ExtKeyUsage {
+ if oid, ok := oidFromExtKeyUsage(u); ok {
+ oids = append(oids, oid)
+ } else {
+ panic("internal error")
+ }
+ }
+
+ oids = append(oids, template.UnknownExtKeyUsage...)
+
+ ret[n].Value, err = asn1.Marshal(oids)
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
+ ret[n].Id = oidExtensionBasicConstraints
+ ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
+ ret[n].Critical = true
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
+ ret[n].Id = oidExtensionSubjectKeyId
+ ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
+ ret[n].Id = oidExtensionAuthorityKeyId
+ ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
+ !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
+ ret[n].Id = oidExtensionAuthorityInfoAccess
+ var aiaValues []authorityInfoAccess
+ for _, name := range template.OCSPServer {
+ aiaValues = append(aiaValues, authorityInfoAccess{
+ Method: oidAuthorityInfoAccessOcsp,
+ Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
+ })
+ }
+ for _, name := range template.IssuingCertificateURL {
+ aiaValues = append(aiaValues, authorityInfoAccess{
+ Method: oidAuthorityInfoAccessIssuers,
+ Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
+ })
+ }
+ ret[n].Value, err = asn1.Marshal(aiaValues)
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
+ !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
+ ret[n].Id = oidExtensionSubjectAltName
+ var rawValues []asn1.RawValue
+ for _, name := range template.DNSNames {
+ rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
+ }
+ for _, email := range template.EmailAddresses {
+ rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
+ }
+ for _, rawIP := range template.IPAddresses {
+ // If possible, we always want to encode IPv4 addresses in 4 bytes.
+ ip := rawIP.To4()
+ if ip == nil {
+ ip = rawIP
+ }
+ rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
+ }
+ ret[n].Value, err = asn1.Marshal(rawValues)
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ if len(template.PolicyIdentifiers) > 0 &&
+ !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
+ ret[n].Id = oidExtensionCertificatePolicies
+ policies := make([]policyInformation, len(template.PolicyIdentifiers))
+ for i, policy := range template.PolicyIdentifiers {
+ policies[i].Policy = policy
+ }
+ ret[n].Value, err = asn1.Marshal(policies)
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ if len(template.PermittedDNSDomains) > 0 &&
+ !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
+ ret[n].Id = oidExtensionNameConstraints
+ ret[n].Critical = template.PermittedDNSDomainsCritical
+
+ var out nameConstraints
+ out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
+ for i, permitted := range template.PermittedDNSDomains {
+ out.Permitted[i] = generalSubtree{Name: permitted}
+ }
+ ret[n].Value, err = asn1.Marshal(out)
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ if len(template.CRLDistributionPoints) > 0 &&
+ !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
+ ret[n].Id = oidExtensionCRLDistributionPoints
+
+ var crlDp []distributionPoint
+ for _, name := range template.CRLDistributionPoints {
+ rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)})
+
+ dp := distributionPoint{
+ DistributionPoint: distributionPointName{
+ FullName: asn1.RawValue{Tag: 0, Class: 2, Bytes: rawFullName},
+ },
+ }
+ crlDp = append(crlDp, dp)
+ }
+
+ ret[n].Value, err = asn1.Marshal(crlDp)
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ // Adding another extension here? Remember to update the maximum number
+ // of elements in the make() at the top of the function.
+
+ return append(ret[:n], template.ExtraExtensions...), nil
+}
+
+func subjectBytes(cert *Certificate) ([]byte, error) {
+ if len(cert.RawSubject) > 0 {
+ return cert.RawSubject, nil
+ }
+
+ return asn1.Marshal(cert.Subject.ToRDNSequence())
+}
+
+// CreateCertificate creates a new certificate based on a template. The
+// following members of template are used: SerialNumber, Subject, NotBefore,
+// NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
+// IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
+// PermittedDNSDomains.
+//
+// The certificate is signed by parent. If parent is equal to template then the
+// certificate is self-signed. The parameter pub is the public key of the
+// signee and priv is the private key of the signer.
+//
+// The returned slice is the certificate in DER encoding.
+//
+// The only supported key types are RSA and ECDSA (*rsa.PublicKey or
+// *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PublicKey for priv).
+func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) {
+ var publicKeyBytes []byte
+ var publicKeyAlgorithm pkix.AlgorithmIdentifier
+
+ if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
+ return nil, err
+ }
+
+ var signatureAlgorithm pkix.AlgorithmIdentifier
+ var hashFunc crypto.Hash
+
+ switch priv := priv.(type) {
+ case *rsa.PrivateKey:
+ signatureAlgorithm.Algorithm = oidSignatureSHA1WithRSA
+ hashFunc = crypto.SHA1
+ case *ecdsa.PrivateKey:
+ switch priv.Curve {
+ case elliptic.P224(), elliptic.P256():
+ hashFunc = crypto.SHA256
+ signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA256
+ case elliptic.P384():
+ hashFunc = crypto.SHA384
+ signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA384
+ case elliptic.P521():
+ hashFunc = crypto.SHA512
+ signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA512
+ default:
+ return nil, errors.New("x509: unknown elliptic curve")
+ }
+ default:
+ return nil, errors.New("x509: only RSA and ECDSA private keys supported")
+ }
+
+ if err != nil {
+ return
+ }
+
+ if len(parent.SubjectKeyId) > 0 {
+ template.AuthorityKeyId = parent.SubjectKeyId
+ }
+
+ extensions, err := buildExtensions(template)
+ if err != nil {
+ return
+ }
+
+ asn1Issuer, err := subjectBytes(parent)
+ if err != nil {
+ return
+ }
+
+ asn1Subject, err := subjectBytes(template)
+ if err != nil {
+ return
+ }
+
+ encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
+ c := tbsCertificate{
+ Version: 2,
+ SerialNumber: template.SerialNumber,
+ SignatureAlgorithm: signatureAlgorithm,
+ Issuer: asn1.RawValue{FullBytes: asn1Issuer},
+ Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
+ Subject: asn1.RawValue{FullBytes: asn1Subject},
+ PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
+ Extensions: extensions,
+ }
+
+ tbsCertContents, err := asn1.Marshal(c)
+ if err != nil {
+ return
+ }
+
+ c.Raw = tbsCertContents
+
+ h := hashFunc.New()
+ h.Write(tbsCertContents)
+ digest := h.Sum(nil)
+
+ var signature []byte
+
+ switch priv := priv.(type) {
+ case *rsa.PrivateKey:
+ signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest)
+ case *ecdsa.PrivateKey:
+ var r, s *big.Int
+ if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil {
+ signature, err = asn1.Marshal(ecdsaSignature{r, s})
+ }
+ default:
+ panic("internal error")
+ }
+
+ if err != nil {
+ return
+ }
+
+ cert, err = asn1.Marshal(certificate{
+ nil,
+ c,
+ signatureAlgorithm,
+ asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
+ })
+ return
+}
+
+// pemCRLPrefix is the magic string that indicates that we have a PEM encoded
+// CRL.
+var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
+
+// pemType is the type of a PEM encoded CRL.
+var pemType = "X509 CRL"
+
+// ParseCRL parses a CRL from the given bytes. It's often the case that PEM
+// encoded CRLs will appear where they should be DER encoded, so this function
+// will transparently handle PEM encoding as long as there isn't any leading
+// garbage.
+func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) {
+ if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
+ block, _ := pem.Decode(crlBytes)
+ if block != nil && block.Type == pemType {
+ crlBytes = block.Bytes
+ }
+ }
+ return ParseDERCRL(crlBytes)
+}
+
+// ParseDERCRL parses a DER encoded CRL from the given bytes.
+func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) {
+ certList = new(pkix.CertificateList)
+ _, err = asn1.Unmarshal(derBytes, certList)
+ if err != nil {
+ certList = nil
+ }
+ return
+}
+
+// CreateCRL returns a DER encoded CRL, signed by this Certificate, that
+// contains the given list of revoked certificates.
+//
+// The only supported key type is RSA (*rsa.PrivateKey for priv).
+func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
+ rsaPriv, ok := priv.(*rsa.PrivateKey)
+ if !ok {
+ return nil, errors.New("x509: non-RSA private keys not supported")
+ }
+ tbsCertList := pkix.TBSCertificateList{
+ Version: 2,
+ Signature: pkix.AlgorithmIdentifier{
+ Algorithm: oidSignatureSHA1WithRSA,
+ },
+ Issuer: c.Subject.ToRDNSequence(),
+ ThisUpdate: now.UTC(),
+ NextUpdate: expiry.UTC(),
+ RevokedCertificates: revokedCerts,
+ }
+
+ tbsCertListContents, err := asn1.Marshal(tbsCertList)
+ if err != nil {
+ return
+ }
+
+ h := sha1.New()
+ h.Write(tbsCertListContents)
+ digest := h.Sum(nil)
+
+ signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
+ if err != nil {
+ return
+ }
+
+ return asn1.Marshal(pkix.CertificateList{
+ TBSCertList: tbsCertList,
+ SignatureAlgorithm: pkix.AlgorithmIdentifier{
+ Algorithm: oidSignatureSHA1WithRSA,
+ },
+ SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
+ })
+}
diff --git a/vendor/github.com/google/certificate-transparency/proto/ct.proto b/vendor/github.com/google/certificate-transparency/proto/ct.proto
new file mode 100644
index 0000000..84e968f
--- /dev/null
+++ b/vendor/github.com/google/certificate-transparency/proto/ct.proto
@@ -0,0 +1,320 @@
+syntax = "proto2";
+
+package ct;
+
+
+////////////////////////////////////////////////////////////////////////////////
+// These protocol buffers should be kept aligned with the I-D. //
+////////////////////////////////////////////////////////////////////////////////
+
+// RFC 5246
+message DigitallySigned {
+ enum HashAlgorithm {
+ NONE = 0;
+ MD5 = 1;
+ SHA1 = 2;
+ SHA224 = 3;
+ SHA256 = 4;
+ SHA384 = 5;
+ SHA512 = 6;
+ }
+
+ enum SignatureAlgorithm {
+ ANONYMOUS = 0;
+ RSA = 1;
+ DSA = 2;
+ ECDSA = 3;
+ }
+
+ // 1 byte
+ optional HashAlgorithm hash_algorithm = 1 [ default = NONE ];
+ // 1 byte
+ optional SignatureAlgorithm sig_algorithm = 2 [ default = ANONYMOUS ];
+ // 0..2^16-1 bytes
+ optional bytes signature = 3;
+}
+
+enum LogEntryType {
+ X509_ENTRY = 0;
+ PRECERT_ENTRY = 1;
+ PRECERT_ENTRY_V2 = 2;
+ // Not part of the I-D, and outside the valid range.
+ X_JSON_ENTRY = 32768; // Experimental, don't rely on this!
+ UNKNOWN_ENTRY_TYPE = 65536;
+}
+
+message X509ChainEntry {
+ // For V1 this entry just includes the certificate in the leaf_certificate
+ // field
+ // <1..2^24-1>
+ optional bytes leaf_certificate = 1;
+ // For V2 it includes the cert and key hash using CertInfo. The
+ // leaf_certificate field is not used
+ optional CertInfo cert_info = 3;
+ // <0..2^24-1>
+ // A chain from the leaf to a trusted root
+ // (excluding leaf and possibly root).
+ repeated bytes certificate_chain = 2;
+}
+
+// opaque TBSCertificate<1..2^16-1>;
+// struct {
+// opaque issuer_key_hash[32];
+// TBSCertificate tbs_certificate;
+// } PreCert;
+// Retained for V1 API compatibility. May be removed in a future release.
+message PreCert {
+ optional bytes issuer_key_hash = 1;
+ optional bytes tbs_certificate = 2;
+}
+
+// In V2 this is used for both certificates and precertificates in SCTs. It
+// replaces PreCert and has the same structure. The older message remains for
+// compatibility with existing code that depends on this proto.
+message CertInfo {
+ optional bytes issuer_key_hash = 1;
+ optional bytes tbs_certificate = 2;
+}
+
+message PrecertChainEntry {
+ // <1..2^24-1>
+ optional bytes pre_certificate = 1;
+ // <0..2^24-1>
+ // The chain certifying the precertificate, as submitted by the CA.
+ repeated bytes precertificate_chain = 2;
+
+ // PreCert input to the SCT. Can be computed from the above.
+ // Store it alongside the entry data so that the signers don't have to
+ // parse certificates to recompute it.
+ optional PreCert pre_cert = 3;
+ // As above for V2 messages. Only one of these fields will be set in a
+ // valid message
+ optional CertInfo cert_info = 4;
+}
+
+message XJSONEntry {
+ optional string json = 1;
+}
+
+// TODO(alcutter): Consider using extensions here instead.
+message LogEntry {
+ optional LogEntryType type = 1 [ default = UNKNOWN_ENTRY_TYPE ];
+
+ optional X509ChainEntry x509_entry = 2;
+
+ optional PrecertChainEntry precert_entry = 3;
+
+ optional XJSONEntry x_json_entry = 4;
+}
+
+enum SignatureType {
+ CERTIFICATE_TIMESTAMP = 0;
+ // TODO(ekasper): called tree_hash in I-D.
+ TREE_HEAD = 1;
+}
+
+enum Version {
+ V1 = 0;
+ V2 = 1;
+ // Not part of the I-D, and outside the valid range.
+ UNKNOWN_VERSION = 256;
+}
+
+message LogID {
+ // 32 bytes
+ optional bytes key_id = 1;
+}
+
+message SctExtension {
+ // Valid range is 0-65534
+ optional uint32 sct_extension_type = 1;
+ // Data is opaque and type specific. <0..2^16-1> bytes
+ optional bytes sct_extension_data = 2;
+}
+
+// TODO(ekasper): implement support for id.
+message SignedCertificateTimestamp {
+ optional Version version = 1 [ default = UNKNOWN_VERSION ];
+ optional LogID id = 2;
+ // UTC time in milliseconds, since January 1, 1970, 00:00.
+ optional uint64 timestamp = 3;
+ optional DigitallySigned signature = 4;
+ // V1 extensions
+ optional bytes extensions = 5;
+ // V2 extensions <0..2^16-1>. Must be ordered by type (lowest first)
+ repeated SctExtension sct_extension = 6;
+}
+
+message SignedCertificateTimestampList {
+ // One or more SCTs, <1..2^16-1> bytes each
+ repeated bytes sct_list = 1;
+}
+
+enum MerkleLeafType {
+ TIMESTAMPED_ENTRY = 0;
+ UNKNOWN_LEAF_TYPE = 256;
+}
+
+message SignedEntry {
+ // For V1 signed entries either the x509 or precert field will be set
+ optional bytes x509 = 1;
+ optional PreCert precert = 2;
+ optional bytes json = 3;
+ // For V2 all entries use the CertInfo field and the above fields are
+ // not set
+ optional CertInfo cert_info = 4;
+}
+
+message TimestampedEntry {
+ optional uint64 timestamp = 1;
+ optional LogEntryType entry_type = 2;
+ optional SignedEntry signed_entry = 3;
+ // V1 extensions
+ optional bytes extensions = 4;
+ // V2 extensions <0..2^16-1>. Must be ordered by type (lowest first)
+ repeated SctExtension sct_extension = 5;
+}
+
+// Stuff that's hashed into a Merkle leaf.
+message MerkleTreeLeaf {
+ // The version of the corresponding SCT.
+ optional Version version = 1 [ default = UNKNOWN_VERSION ];
+ optional MerkleLeafType type = 2 [ default = UNKNOWN_LEAF_TYPE ];
+ optional TimestampedEntry timestamped_entry = 3;
+}
+
+// TODO(benl): No longer needed?
+//
+// Used by cpp/client/ct: it assembles the one from the I-D JSON
+// protocol.
+//
+// Used by cpp/server/blob-server: it uses one to call a variant of
+// LogLookup::AuditProof.
+message MerkleAuditProof {
+ optional Version version = 1 [ default = UNKNOWN_VERSION ];
+ optional LogID id = 2;
+ optional int64 tree_size = 3;
+ optional uint64 timestamp = 4;
+ optional int64 leaf_index = 5;
+ repeated bytes path_node = 6;
+ optional DigitallySigned tree_head_signature = 7;
+}
+
+message ShortMerkleAuditProof {
+ required int64 leaf_index = 1;
+ repeated bytes path_node = 2;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// Finally, stuff that's not in the I-D but that we use internally //
+// for logging entries and tree head state. //
+////////////////////////////////////////////////////////////////////////////////
+
+// TODO(alcutter): Come up with a better name :/
+message LoggedEntryPB {
+ optional int64 sequence_number = 1;
+ optional bytes merkle_leaf_hash = 2;
+ message Contents {
+ optional SignedCertificateTimestamp sct = 1;
+ optional LogEntry entry = 2;
+ }
+ required Contents contents = 3;
+}
+
+message SthExtension {
+ // Valid range is 0-65534
+ optional uint32 sth_extension_type = 1;
+ // Data is opaque and type specific <0..2^16-1> bytes
+ optional bytes sth_extension_data = 2;
+}
+
+message SignedTreeHead {
+ // The version of the tree head signature.
+ // (Note that each leaf has its own version, so a V2 tree
+ // can contain V1 leaves, too.
+ optional Version version = 1 [ default = UNKNOWN_VERSION ];
+ optional LogID id = 2;
+ optional uint64 timestamp = 3;
+ optional int64 tree_size = 4;
+ optional bytes sha256_root_hash = 5;
+ optional DigitallySigned signature = 6;
+ // Only supported in V2. <0..2^16-1>
+ repeated SthExtension sth_extension = 7;
+}
+
+// Stuff the SSL client spits out from a connection.
+message SSLClientCTData {
+ optional LogEntry reconstructed_entry = 1;
+ optional bytes certificate_sha256_hash = 2;
+
+ message SCTInfo {
+ // There is an entry + sct -> leaf hash mapping.
+ optional SignedCertificateTimestamp sct = 1;
+ optional bytes merkle_leaf_hash = 2;
+ }
+ repeated SCTInfo attached_sct_info = 3;
+}
+
+message ClusterNodeState {
+ optional string node_id = 1;
+ optional int64 contiguous_tree_size = 2 [deprecated = true];
+ optional SignedTreeHead newest_sth = 3;
+ optional SignedTreeHead current_serving_sth = 4;
+
+ // The following host_name/log_port pair are used to allow a log node to
+ // contact other nodes in the cluster, primarily for the purposes of
+ // replication.
+ // hostname/ip which can be used to contact [just] this log node
+ optional string hostname = 5;
+ // port on which this log node is listening.
+ optional int32 log_port = 6;
+}
+
+message ClusterControl {
+ optional bool accept_new_entries = 1 [ default = true ];
+}
+
+message ClusterConfig {
+ /////////////////////////////////
+ // This section of the config affects the selection of the cluster's current
+ // serving STH.
+ // The cluster will always attempt to determine the newest (and
+ // largest) possible STH which meets the constraints defined below from the
+ // set of STHs available at the individual cluster nodes.
+ // (Note that nodes with newer/larger STHs can, of course, serve
+ // earlier/smaller STHs.)
+
+
+ // The minimum number of nodes which must be able to serve a given STH.
+ // This setting allows you to configure the level of cluster resiliency
+ // against data (in the form of node/node database) loss.
+ // i.e.: Once an STH has been created, it must have been replicated to
+ // at least this many nodes before being considered as a candidate for
+ // the overall cluster serving STH.
+ optional int32 minimum_serving_nodes = 1;
+
+ // The minimum fraction of nodes which must be able to serve a given STH.
+ // This setting allows you to configure the serving capacity redundancy of
+ // your cluster.
+ // e.g. you determine you need 3 nodes to serve your expected peak traffic
+ // levels, but want to be over-provisioned by 25% to ensure the cluster will
+ // continue to be able to handle the traffic in the case of a single node
+ // failure, you might set this to 0.75 to ensure that any cluster-wide
+ // serving STH candidate must be servable from at least 3 of your 4 nodes.
+ optional double minimum_serving_fraction = 2;
+ /////////////////////////////////
+
+ // When the number of entries in the EtcedConsistentStore exceeds this value,
+ // the log server will reject all calls to add-[pre-]chain to protect itself
+ // and etcd.
+ optional double etcd_reject_add_pending_threshold = 3 [default = 30000];
+}
+
+message SequenceMapping {
+ message Mapping {
+ optional bytes entry_hash = 1;
+ optional int64 sequence_number = 2;
+ }
+
+ repeated Mapping mapping = 1;
+}
diff --git a/vendor/github.com/googleapis/gax-go/LICENSE b/vendor/github.com/googleapis/gax-go/LICENSE
new file mode 100644
index 0000000..6d16b65
--- /dev/null
+++ b/vendor/github.com/googleapis/gax-go/LICENSE
@@ -0,0 +1,27 @@
+Copyright 2016, Google Inc.
+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/googleapis/gax-go/README.md b/vendor/github.com/googleapis/gax-go/README.md
new file mode 100644
index 0000000..3cedd5b
--- /dev/null
+++ b/vendor/github.com/googleapis/gax-go/README.md
@@ -0,0 +1,24 @@
+Google API Extensions for Go
+============================
+
+[![Build Status](https://travis-ci.org/googleapis/gax-go.svg?branch=master)](https://travis-ci.org/googleapis/gax-go)
+[![Code Coverage](https://img.shields.io/codecov/c/github/googleapis/gax-go.svg)](https://codecov.io/github/googleapis/gax-go)
+
+Google API Extensions for Go (gax-go) is a set of modules which aids the
+development of APIs for clients and servers based on `gRPC` and Google API
+conventions.
+
+Application code will rarely need to use this library directly,
+but the code generated automatically from API definition files can use it
+to simplify code generation and to provide more convenient and idiomatic API surface.
+
+**This project is currently experimental and not supported.**
+
+Go Versions
+===========
+This library requires Go 1.6 or above.
+
+License
+=======
+BSD - please see [LICENSE](https://github.com/googleapis/gax-go/blob/master/LICENSE)
+for more information.
diff --git a/vendor/github.com/googleapis/gax-go/call_option.go b/vendor/github.com/googleapis/gax-go/call_option.go
new file mode 100644
index 0000000..4ba1cdf
--- /dev/null
+++ b/vendor/github.com/googleapis/gax-go/call_option.go
@@ -0,0 +1,136 @@
+// Copyright 2016, Google Inc.
+// 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.
+
+package gax
+
+import (
+ "math/rand"
+ "time"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+// CallOption is an option used by Invoke to control behaviors of RPC calls.
+// CallOption works by modifying relevant fields of CallSettings.
+type CallOption interface {
+ // Resolve applies the option by modifying cs.
+ Resolve(cs *CallSettings)
+}
+
+// Retryer is used by Invoke to determine retry behavior.
+type Retryer interface {
+ // Retry reports whether a request should be retriedand how long to pause before retrying
+ // if the previous attempt returned with err. Invoke never calls Retry with nil error.
+ Retry(err error) (pause time.Duration, shouldRetry bool)
+}
+
+type retryerOption func() Retryer
+
+func (o retryerOption) Resolve(s *CallSettings) {
+ s.Retry = o
+}
+
+// WithRetry sets CallSettings.Retry to fn.
+func WithRetry(fn func() Retryer) CallOption {
+ return retryerOption(fn)
+}
+
+// OnCodes returns a Retryer that retries if and only if
+// the previous attempt returns a GRPC error whose error code is stored in cc.
+// Pause times between retries are specified by bo.
+//
+// bo is only used for its parameters; each Retryer has its own copy.
+func OnCodes(cc []codes.Code, bo Backoff) Retryer {
+ return &boRetryer{
+ backoff: bo,
+ codes: append([]codes.Code(nil), cc...),
+ }
+}
+
+type boRetryer struct {
+ backoff Backoff
+ codes []codes.Code
+}
+
+func (r *boRetryer) Retry(err error) (time.Duration, bool) {
+ c := grpc.Code(err)
+ for _, rc := range r.codes {
+ if c == rc {
+ return r.backoff.Pause(), true
+ }
+ }
+ return 0, false
+}
+
+// Backoff implements exponential backoff.
+// The wait time between retries is a random value between 0 and the "retry envelope".
+// The envelope starts at Initial and increases by the factor of Multiplier every retry,
+// but is capped at Max.
+type Backoff struct {
+ // Initial is the initial value of the retry envelope, defaults to 1 second.
+ Initial time.Duration
+
+ // Max is the maximum value of the retry envelope, defaults to 30 seconds.
+ Max time.Duration
+
+ // Multiplier is the factor by which the retry envelope increases.
+ // It should be greater than 1 and defaults to 2.
+ Multiplier float64
+
+ // cur is the current retry envelope
+ cur time.Duration
+}
+
+func (bo *Backoff) Pause() time.Duration {
+ if bo.Initial == 0 {
+ bo.Initial = time.Second
+ }
+ if bo.cur == 0 {
+ bo.cur = bo.Initial
+ }
+ if bo.Max == 0 {
+ bo.Max = 30 * time.Second
+ }
+ if bo.Multiplier < 1 {
+ bo.Multiplier = 2
+ }
+ d := time.Duration(rand.Int63n(int64(bo.cur)))
+ bo.cur = time.Duration(float64(bo.cur) * bo.Multiplier)
+ if bo.cur > bo.Max {
+ bo.cur = bo.Max
+ }
+ return d
+}
+
+type CallSettings struct {
+ // Retry returns a Retryer to be used to control retry logic of a method call.
+ // If Retry is nil or the returned Retryer is nil, the call will not be retried.
+ Retry func() Retryer
+}
diff --git a/vendor/github.com/googleapis/gax-go/gax.go b/vendor/github.com/googleapis/gax-go/gax.go
new file mode 100644
index 0000000..5ebedff
--- /dev/null
+++ b/vendor/github.com/googleapis/gax-go/gax.go
@@ -0,0 +1,40 @@
+// Copyright 2016, Google Inc.
+// 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.
+
+// Package gax contains a set of modules which aid the development of APIs
+// for clients and servers based on gRPC and Google API conventions.
+//
+// Application code will rarely need to use this library directly.
+// However, code generated automatically from API definition files can use it
+// to simplify code generation and to provide more convenient and idiomatic API surfaces.
+//
+// This project is currently experimental and not supported.
+package gax
+
+const Version = "0.1.0"
diff --git a/vendor/github.com/googleapis/gax-go/invoke.go b/vendor/github.com/googleapis/gax-go/invoke.go
new file mode 100644
index 0000000..d2134e1
--- /dev/null
+++ b/vendor/github.com/googleapis/gax-go/invoke.go
@@ -0,0 +1,90 @@
+// Copyright 2016, Google Inc.
+// 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.
+
+package gax
+
+import (
+ "time"
+
+ "golang.org/x/net/context"
+)
+
+// A user defined call stub.
+type APICall func(context.Context) error
+
+// Invoke calls the given APICall,
+// performing retries as specified by opts, if any.
+func Invoke(ctx context.Context, call APICall, opts ...CallOption) error {
+ var settings CallSettings
+ for _, opt := range opts {
+ opt.Resolve(&settings)
+ }
+ return invoke(ctx, call, settings, Sleep)
+}
+
+// Sleep is similar to time.Sleep, but it can be interrupted by ctx.Done() closing.
+// If interrupted, Sleep returns ctx.Err().
+func Sleep(ctx context.Context, d time.Duration) error {
+ t := time.NewTimer(d)
+ select {
+ case <-ctx.Done():
+ t.Stop()
+ return ctx.Err()
+ case <-t.C:
+ return nil
+ }
+}
+
+type sleeper func(ctx context.Context, d time.Duration) error
+
+// invoke implements Invoke, taking an additional sleeper argument for testing.
+func invoke(ctx context.Context, call APICall, settings CallSettings, sp sleeper) error {
+ var retryer Retryer
+ for {
+ err := call(ctx)
+ if err == nil {
+ return nil
+ }
+ if settings.Retry == nil {
+ return err
+ }
+ if retryer == nil {
+ if r := settings.Retry(); r != nil {
+ retryer = r
+ } else {
+ return err
+ }
+ }
+ if d, ok := retryer.Retry(err); !ok {
+ return err
+ } else if err = sp(ctx, d); err != nil {
+ return err
+ }
+ }
+}
diff --git a/vendor/github.com/googleapis/gax-go/path_template.go b/vendor/github.com/googleapis/gax-go/path_template.go
new file mode 100644
index 0000000..41bda94
--- /dev/null
+++ b/vendor/github.com/googleapis/gax-go/path_template.go
@@ -0,0 +1,176 @@
+// Copyright 2016, Google Inc.
+// 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.
+
+package gax
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+)
+
+type matcher interface {
+ match([]string) (int, error)
+ String() string
+}
+
+type segment struct {
+ matcher
+ name string
+}
+
+type labelMatcher string
+
+func (ls labelMatcher) match(segments []string) (int, error) {
+ if len(segments) == 0 {
+ return 0, fmt.Errorf("expected %s but no more segments found", ls)
+ }
+ if segments[0] != string(ls) {
+ return 0, fmt.Errorf("expected %s but got %s", ls, segments[0])
+ }
+ return 1, nil
+}
+
+func (ls labelMatcher) String() string {
+ return string(ls)
+}
+
+type wildcardMatcher int
+
+func (wm wildcardMatcher) match(segments []string) (int, error) {
+ if len(segments) == 0 {
+ return 0, errors.New("no more segments found")
+ }
+ return 1, nil
+}
+
+func (wm wildcardMatcher) String() string {
+ return "*"
+}
+
+type pathWildcardMatcher int
+
+func (pwm pathWildcardMatcher) match(segments []string) (int, error) {
+ length := len(segments) - int(pwm)
+ if length <= 0 {
+ return 0, errors.New("not sufficient segments are supplied for path wildcard")
+ }
+ return length, nil
+}
+
+func (pwm pathWildcardMatcher) String() string {
+ return "**"
+}
+
+type ParseError struct {
+ Pos int
+ Template string
+ Message string
+}
+
+func (pe ParseError) Error() string {
+ return fmt.Sprintf("at %d of template '%s', %s", pe.Pos, pe.Template, pe.Message)
+}
+
+// PathTemplate manages the template to build and match with paths used
+// by API services. It holds a template and variable names in it, and
+// it can extract matched patterns from a path string or build a path
+// string from a binding.
+//
+// See http.proto in github.com/googleapis/googleapis/ for the details of
+// the template syntax.
+type PathTemplate struct {
+ segments []segment
+}
+
+// NewPathTemplate parses a path template, and returns a PathTemplate
+// instance if successful.
+func NewPathTemplate(template string) (*PathTemplate, error) {
+ return parsePathTemplate(template)
+}
+
+// MustCompilePathTemplate is like NewPathTemplate but panics if the
+// expression cannot be parsed. It simplifies safe initialization of
+// global variables holding compiled regular expressions.
+func MustCompilePathTemplate(template string) *PathTemplate {
+ pt, err := NewPathTemplate(template)
+ if err != nil {
+ panic(err)
+ }
+ return pt
+}
+
+// Match attempts to match the given path with the template, and returns
+// the mapping of the variable name to the matched pattern string.
+func (pt *PathTemplate) Match(path string) (map[string]string, error) {
+ paths := strings.Split(path, "/")
+ values := map[string]string{}
+ for _, segment := range pt.segments {
+ length, err := segment.match(paths)
+ if err != nil {
+ return nil, err
+ }
+ if segment.name != "" {
+ value := strings.Join(paths[:length], "/")
+ if oldValue, ok := values[segment.name]; ok {
+ values[segment.name] = oldValue + "/" + value
+ } else {
+ values[segment.name] = value
+ }
+ }
+ paths = paths[length:]
+ }
+ if len(paths) != 0 {
+ return nil, fmt.Errorf("Trailing path %s remains after the matching", strings.Join(paths, "/"))
+ }
+ return values, nil
+}
+
+// Render creates a path string from its template and the binding from
+// the variable name to the value.
+func (pt *PathTemplate) Render(binding map[string]string) (string, error) {
+ result := make([]string, 0, len(pt.segments))
+ var lastVariableName string
+ for _, segment := range pt.segments {
+ name := segment.name
+ if lastVariableName != "" && name == lastVariableName {
+ continue
+ }
+ lastVariableName = name
+ if name == "" {
+ result = append(result, segment.String())
+ } else if value, ok := binding[name]; ok {
+ result = append(result, value)
+ } else {
+ return "", fmt.Errorf("%s is not found", name)
+ }
+ }
+ built := strings.Join(result, "/")
+ return built, nil
+}
diff --git a/vendor/github.com/googleapis/gax-go/path_template_parser.go b/vendor/github.com/googleapis/gax-go/path_template_parser.go
new file mode 100644
index 0000000..79c8e75
--- /dev/null
+++ b/vendor/github.com/googleapis/gax-go/path_template_parser.go
@@ -0,0 +1,227 @@
+// Copyright 2016, Google Inc.
+// 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.
+
+package gax
+
+import (
+ "fmt"
+ "io"
+ "strings"
+)
+
+// This parser follows the syntax of path templates, from
+// https://github.com/googleapis/googleapis/blob/master/google/api/http.proto.
+// The differences are that there is no custom verb, we allow the initial slash
+// to be absent, and that we are not strict as
+// https://tools.ietf.org/html/rfc6570 about the characters in identifiers and
+// literals.
+
+type pathTemplateParser struct {
+ r *strings.Reader
+ runeCount int // the number of the current rune in the original string
+ nextVar int // the number to use for the next unnamed variable
+ seenName map[string]bool // names we've seen already
+ seenPathWildcard bool // have we seen "**" already?
+}
+
+func parsePathTemplate(template string) (pt *PathTemplate, err error) {
+ p := &pathTemplateParser{
+ r: strings.NewReader(template),
+ seenName: map[string]bool{},
+ }
+
+ // Handle panics with strings like errors.
+ // See pathTemplateParser.error, below.
+ defer func() {
+ if x := recover(); x != nil {
+ errmsg, ok := x.(errString)
+ if !ok {
+ panic(x)
+ }
+ pt = nil
+ err = ParseError{p.runeCount, template, string(errmsg)}
+ }
+ }()
+
+ segs := p.template()
+ // If there is a path wildcard, set its length. We can't do this
+ // until we know how many segments we've got all together.
+ for i, seg := range segs {
+ if _, ok := seg.matcher.(pathWildcardMatcher); ok {
+ segs[i].matcher = pathWildcardMatcher(len(segs) - i - 1)
+ break
+ }
+ }
+ return &PathTemplate{segments: segs}, nil
+
+}
+
+// Used to indicate errors "thrown" by this parser. We don't use string because
+// many parts of the standard library panic with strings.
+type errString string
+
+// Terminates parsing immediately with an error.
+func (p *pathTemplateParser) error(msg string) {
+ panic(errString(msg))
+}
+
+// Template = [ "/" ] Segments
+func (p *pathTemplateParser) template() []segment {
+ var segs []segment
+ if p.consume('/') {
+ // Initial '/' needs an initial empty matcher.
+ segs = append(segs, segment{matcher: labelMatcher("")})
+ }
+ return append(segs, p.segments("")...)
+}
+
+// Segments = Segment { "/" Segment }
+func (p *pathTemplateParser) segments(name string) []segment {
+ var segs []segment
+ for {
+ subsegs := p.segment(name)
+ segs = append(segs, subsegs...)
+ if !p.consume('/') {
+ break
+ }
+ }
+ return segs
+}
+
+// Segment = "*" | "**" | LITERAL | Variable
+func (p *pathTemplateParser) segment(name string) []segment {
+ if p.consume('*') {
+ if name == "" {
+ name = fmt.Sprintf("$%d", p.nextVar)
+ p.nextVar++
+ }
+ if p.consume('*') {
+ if p.seenPathWildcard {
+ p.error("multiple '**' disallowed")
+ }
+ p.seenPathWildcard = true
+ // We'll change 0 to the right number at the end.
+ return []segment{{name: name, matcher: pathWildcardMatcher(0)}}
+ }
+ return []segment{{name: name, matcher: wildcardMatcher(0)}}
+ }
+ if p.consume('{') {
+ if name != "" {
+ p.error("recursive named bindings are not allowed")
+ }
+ return p.variable()
+ }
+ return []segment{{name: name, matcher: labelMatcher(p.literal())}}
+}
+
+// Variable = "{" FieldPath [ "=" Segments ] "}"
+// "{" is already consumed.
+func (p *pathTemplateParser) variable() []segment {
+ // Simplification: treat FieldPath as LITERAL, instead of IDENT { '.' IDENT }
+ name := p.literal()
+ if p.seenName[name] {
+ p.error(name + " appears multiple times")
+ }
+ p.seenName[name] = true
+ var segs []segment
+ if p.consume('=') {
+ segs = p.segments(name)
+ } else {
+ // "{var}" is equivalent to "{var=*}"
+ segs = []segment{{name: name, matcher: wildcardMatcher(0)}}
+ }
+ if !p.consume('}') {
+ p.error("expected '}'")
+ }
+ return segs
+}
+
+// A literal is any sequence of characters other than a few special ones.
+// The list of stop characters is not quite the same as in the template RFC.
+func (p *pathTemplateParser) literal() string {
+ lit := p.consumeUntil("/*}{=")
+ if lit == "" {
+ p.error("empty literal")
+ }
+ return lit
+}
+
+// Read runes until EOF or one of the runes in stopRunes is encountered.
+// If the latter, unread the stop rune. Return the accumulated runes as a string.
+func (p *pathTemplateParser) consumeUntil(stopRunes string) string {
+ var runes []rune
+ for {
+ r, ok := p.readRune()
+ if !ok {
+ break
+ }
+ if strings.IndexRune(stopRunes, r) >= 0 {
+ p.unreadRune()
+ break
+ }
+ runes = append(runes, r)
+ }
+ return string(runes)
+}
+
+// If the next rune is r, consume it and return true.
+// Otherwise, leave the input unchanged and return false.
+func (p *pathTemplateParser) consume(r rune) bool {
+ rr, ok := p.readRune()
+ if !ok {
+ return false
+ }
+ if r == rr {
+ return true
+ }
+ p.unreadRune()
+ return false
+}
+
+// Read the next rune from the input. Return it.
+// The second return value is false at EOF.
+func (p *pathTemplateParser) readRune() (rune, bool) {
+ r, _, err := p.r.ReadRune()
+ if err == io.EOF {
+ return r, false
+ }
+ if err != nil {
+ p.error(err.Error())
+ }
+ p.runeCount++
+ return r, true
+}
+
+// Put the last rune that was read back on the input.
+func (p *pathTemplateParser) unreadRune() {
+ if err := p.r.UnreadRune(); err != nil {
+ p.error(err.Error())
+ }
+ p.runeCount--
+}
diff --git a/vendor/github.com/gorilla/context/LICENSE b/vendor/github.com/gorilla/context/LICENSE
new file mode 100644
index 0000000..0e5fb87
--- /dev/null
+++ b/vendor/github.com/gorilla/context/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2012 Rodrigo Moraes. 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/gorilla/context/README.md b/vendor/github.com/gorilla/context/README.md
new file mode 100644
index 0000000..c60a31b
--- /dev/null
+++ b/vendor/github.com/gorilla/context/README.md
@@ -0,0 +1,7 @@
+context
+=======
+[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context)
+
+gorilla/context is a general purpose registry for global request variables.
+
+Read the full documentation here: http://www.gorillatoolkit.org/pkg/context
diff --git a/vendor/github.com/gorilla/context/context.go b/vendor/github.com/gorilla/context/context.go
new file mode 100644
index 0000000..81cb128
--- /dev/null
+++ b/vendor/github.com/gorilla/context/context.go
@@ -0,0 +1,143 @@
+// Copyright 2012 The Gorilla 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 context
+
+import (
+ "net/http"
+ "sync"
+ "time"
+)
+
+var (
+ mutex sync.RWMutex
+ data = make(map[*http.Request]map[interface{}]interface{})
+ datat = make(map[*http.Request]int64)
+)
+
+// Set stores a value for a given key in a given request.
+func Set(r *http.Request, key, val interface{}) {
+ mutex.Lock()
+ if data[r] == nil {
+ data[r] = make(map[interface{}]interface{})
+ datat[r] = time.Now().Unix()
+ }
+ data[r][key] = val
+ mutex.Unlock()
+}
+
+// Get returns a value stored for a given key in a given request.
+func Get(r *http.Request, key interface{}) interface{} {
+ mutex.RLock()
+ if ctx := data[r]; ctx != nil {
+ value := ctx[key]
+ mutex.RUnlock()
+ return value
+ }
+ mutex.RUnlock()
+ return nil
+}
+
+// GetOk returns stored value and presence state like multi-value return of map access.
+func GetOk(r *http.Request, key interface{}) (interface{}, bool) {
+ mutex.RLock()
+ if _, ok := data[r]; ok {
+ value, ok := data[r][key]
+ mutex.RUnlock()
+ return value, ok
+ }
+ mutex.RUnlock()
+ return nil, false
+}
+
+// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests.
+func GetAll(r *http.Request) map[interface{}]interface{} {
+ mutex.RLock()
+ if context, ok := data[r]; ok {
+ result := make(map[interface{}]interface{}, len(context))
+ for k, v := range context {
+ result[k] = v
+ }
+ mutex.RUnlock()
+ return result
+ }
+ mutex.RUnlock()
+ return nil
+}
+
+// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if
+// the request was registered.
+func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) {
+ mutex.RLock()
+ context, ok := data[r]
+ result := make(map[interface{}]interface{}, len(context))
+ for k, v := range context {
+ result[k] = v
+ }
+ mutex.RUnlock()
+ return result, ok
+}
+
+// Delete removes a value stored for a given key in a given request.
+func Delete(r *http.Request, key interface{}) {
+ mutex.Lock()
+ if data[r] != nil {
+ delete(data[r], key)
+ }
+ mutex.Unlock()
+}
+
+// Clear removes all values stored for a given request.
+//
+// This is usually called by a handler wrapper to clean up request
+// variables at the end of a request lifetime. See ClearHandler().
+func Clear(r *http.Request) {
+ mutex.Lock()
+ clear(r)
+ mutex.Unlock()
+}
+
+// clear is Clear without the lock.
+func clear(r *http.Request) {
+ delete(data, r)
+ delete(datat, r)
+}
+
+// Purge removes request data stored for longer than maxAge, in seconds.
+// It returns the amount of requests removed.
+//
+// If maxAge <= 0, all request data is removed.
+//
+// This is only used for sanity check: in case context cleaning was not
+// properly set some request data can be kept forever, consuming an increasing
+// amount of memory. In case this is detected, Purge() must be called
+// periodically until the problem is fixed.
+func Purge(maxAge int) int {
+ mutex.Lock()
+ count := 0
+ if maxAge <= 0 {
+ count = len(data)
+ data = make(map[*http.Request]map[interface{}]interface{})
+ datat = make(map[*http.Request]int64)
+ } else {
+ min := time.Now().Unix() - int64(maxAge)
+ for r := range data {
+ if datat[r] < min {
+ clear(r)
+ count++
+ }
+ }
+ }
+ mutex.Unlock()
+ return count
+}
+
+// ClearHandler wraps an http.Handler and clears request values at the end
+// of a request lifetime.
+func ClearHandler(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer Clear(r)
+ h.ServeHTTP(w, r)
+ })
+}
diff --git a/vendor/github.com/gorilla/context/doc.go b/vendor/github.com/gorilla/context/doc.go
new file mode 100644
index 0000000..73c7400
--- /dev/null
+++ b/vendor/github.com/gorilla/context/doc.go
@@ -0,0 +1,82 @@
+// Copyright 2012 The Gorilla 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 context stores values shared during a request lifetime.
+
+For example, a router can set variables extracted from the URL and later
+application handlers can access those values, or it can be used to store
+sessions values to be saved at the end of a request. There are several
+others common uses.
+
+The idea was posted by Brad Fitzpatrick to the go-nuts mailing list:
+
+ http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53
+
+Here's the basic usage: first define the keys that you will need. The key
+type is interface{} so a key can be of any type that supports equality.
+Here we define a key using a custom int type to avoid name collisions:
+
+ package foo
+
+ import (
+ "github.com/gorilla/context"
+ )
+
+ type key int
+
+ const MyKey key = 0
+
+Then set a variable. Variables are bound to an http.Request object, so you
+need a request instance to set a value:
+
+ context.Set(r, MyKey, "bar")
+
+The application can later access the variable using the same key you provided:
+
+ func MyHandler(w http.ResponseWriter, r *http.Request) {
+ // val is "bar".
+ val := context.Get(r, foo.MyKey)
+
+ // returns ("bar", true)
+ val, ok := context.GetOk(r, foo.MyKey)
+ // ...
+ }
+
+And that's all about the basic usage. We discuss some other ideas below.
+
+Any type can be stored in the context. To enforce a given type, make the key
+private and wrap Get() and Set() to accept and return values of a specific
+type:
+
+ type key int
+
+ const mykey key = 0
+
+ // GetMyKey returns a value for this package from the request values.
+ func GetMyKey(r *http.Request) SomeType {
+ if rv := context.Get(r, mykey); rv != nil {
+ return rv.(SomeType)
+ }
+ return nil
+ }
+
+ // SetMyKey sets a value for this package in the request values.
+ func SetMyKey(r *http.Request, val SomeType) {
+ context.Set(r, mykey, val)
+ }
+
+Variables must be cleared at the end of a request, to remove all values
+that were stored. This can be done in an http.Handler, after a request was
+served. Just call Clear() passing the request:
+
+ context.Clear(r)
+
+...or use ClearHandler(), which conveniently wraps an http.Handler to clear
+variables at the end of a request lifetime.
+
+The Routers from the packages gorilla/mux and gorilla/pat call Clear()
+so if you are using either of them you don't need to clear the context manually.
+*/
+package context
diff --git a/vendor/github.com/gorilla/mux/LICENSE b/vendor/github.com/gorilla/mux/LICENSE
new file mode 100644
index 0000000..0e5fb87
--- /dev/null
+++ b/vendor/github.com/gorilla/mux/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2012 Rodrigo Moraes. 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/gorilla/mux/README.md b/vendor/github.com/gorilla/mux/README.md
new file mode 100644
index 0000000..9516c51
--- /dev/null
+++ b/vendor/github.com/gorilla/mux/README.md
@@ -0,0 +1,242 @@
+mux
+===
+[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
+[![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux)
+
+http://www.gorillatoolkit.org/pkg/mux
+
+Package `gorilla/mux` implements a request router and dispatcher.
+
+The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are:
+
+* Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
+* URL hosts and paths can have variables with an optional regular expression.
+* Registered URLs can be built, or "reversed", which helps maintaining references to resources.
+* Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching.
+* It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`.
+
+Let's start registering a couple of URL paths and handlers:
+
+```go
+func main() {
+ r := mux.NewRouter()
+ r.HandleFunc("/", HomeHandler)
+ r.HandleFunc("/products", ProductsHandler)
+ r.HandleFunc("/articles", ArticlesHandler)
+ http.Handle("/", r)
+}
+```
+
+Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters.
+
+Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example:
+
+```go
+r := mux.NewRouter()
+r.HandleFunc("/products/{key}", ProductHandler)
+r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
+r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
+```
+
+The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`:
+
+```go
+vars := mux.Vars(request)
+category := vars["category"]
+```
+
+And this is all you need to know about the basic usage. More advanced options are explained below.
+
+Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables:
+
+```go
+r := mux.NewRouter()
+// Only matches if domain is "www.example.com".
+r.Host("www.example.com")
+// Matches a dynamic subdomain.
+r.Host("{subdomain:[a-z]+}.domain.com")
+```
+
+There are several other matchers that can be added. To match path prefixes:
+
+```go
+r.PathPrefix("/products/")
+```
+
+...or HTTP methods:
+
+```go
+r.Methods("GET", "POST")
+```
+
+...or URL schemes:
+
+```go
+r.Schemes("https")
+```
+
+...or header values:
+
+```go
+r.Headers("X-Requested-With", "XMLHttpRequest")
+```
+
+...or query values:
+
+```go
+r.Queries("key", "value")
+```
+
+...or to use a custom matcher function:
+
+```go
+r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
+ return r.ProtoMajor == 0
+})
+```
+
+...and finally, it is possible to combine several matchers in a single route:
+
+```go
+r.HandleFunc("/products", ProductsHandler).
+ Host("www.example.com").
+ Methods("GET").
+ Schemes("http")
+```
+
+Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting".
+
+For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it:
+
+```go
+r := mux.NewRouter()
+s := r.Host("www.example.com").Subrouter()
+```
+
+Then register routes in the subrouter:
+
+```go
+s.HandleFunc("/products/", ProductsHandler)
+s.HandleFunc("/products/{key}", ProductHandler)
+s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
+```
+
+The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route.
+
+Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter.
+
+There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths:
+
+```go
+r := mux.NewRouter()
+s := r.PathPrefix("/products").Subrouter()
+// "/products/"
+s.HandleFunc("/", ProductsHandler)
+// "/products/{key}/"
+s.HandleFunc("/{key}/", ProductHandler)
+// "/products/{key}/details"
+s.HandleFunc("/{key}/details", ProductDetailsHandler)
+```
+
+Now let's see how to build registered URLs.
+
+Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example:
+
+```go
+r := mux.NewRouter()
+r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
+ Name("article")
+```
+
+To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do:
+
+```go
+url, err := r.Get("article").URL("category", "technology", "id", "42")
+```
+
+...and the result will be a `url.URL` with the following path:
+
+```
+"/articles/technology/42"
+```
+
+This also works for host variables:
+
+```go
+r := mux.NewRouter()
+r.Host("{subdomain}.domain.com").
+ Path("/articles/{category}/{id:[0-9]+}").
+ HandlerFunc(ArticleHandler).
+ Name("article")
+
+// url.String() will be "http://news.domain.com/articles/technology/42"
+url, err := r.Get("article").URL("subdomain", "news",
+ "category", "technology",
+ "id", "42")
+```
+
+All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match.
+
+Regex support also exists for matching Headers within a route. For example, we could do:
+
+```go
+r.HeadersRegexp("Content-Type", "application/(text|json)")
+```
+
+...and the route will match both requests with a Content-Type of `application/json` as well as `application/text`
+
+There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do:
+
+```go
+// "http://news.domain.com/"
+host, err := r.Get("article").URLHost("subdomain", "news")
+
+// "/articles/technology/42"
+path, err := r.Get("article").URLPath("category", "technology", "id", "42")
+```
+
+And if you use subrouters, host and path defined separately can be built as well:
+
+```go
+r := mux.NewRouter()
+s := r.Host("{subdomain}.domain.com").Subrouter()
+s.Path("/articles/{category}/{id:[0-9]+}").
+ HandlerFunc(ArticleHandler).
+ Name("article")
+
+// "http://news.domain.com/articles/technology/42"
+url, err := r.Get("article").URL("subdomain", "news",
+ "category", "technology",
+ "id", "42")
+```
+
+## Full Example
+
+Here's a complete, runnable example of a small `mux` based server:
+
+```go
+package main
+
+import (
+ "net/http"
+
+ "github.com/gorilla/mux"
+)
+
+func YourHandler(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("Gorilla!\n"))
+}
+
+func main() {
+ r := mux.NewRouter()
+ // Routes consist of a path and a handler function.
+ r.HandleFunc("/", YourHandler)
+
+ // Bind to a port and pass our router in
+ http.ListenAndServe(":8000", r)
+}
+```
+
+## License
+
+BSD licensed. See the LICENSE file for details.
diff --git a/vendor/github.com/gorilla/mux/doc.go b/vendor/github.com/gorilla/mux/doc.go
new file mode 100644
index 0000000..835f534
--- /dev/null
+++ b/vendor/github.com/gorilla/mux/doc.go
@@ -0,0 +1,206 @@
+// Copyright 2012 The Gorilla 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 mux implements a request router and dispatcher.
+
+The name mux stands for "HTTP request multiplexer". Like the standard
+http.ServeMux, mux.Router matches incoming requests against a list of
+registered routes and calls a handler for the route that matches the URL
+or other conditions. The main features are:
+
+ * Requests can be matched based on URL host, path, path prefix, schemes,
+ header and query values, HTTP methods or using custom matchers.
+ * URL hosts and paths can have variables with an optional regular
+ expression.
+ * Registered URLs can be built, or "reversed", which helps maintaining
+ references to resources.
+ * Routes can be used as subrouters: nested routes are only tested if the
+ parent route matches. This is useful to define groups of routes that
+ share common conditions like a host, a path prefix or other repeated
+ attributes. As a bonus, this optimizes request matching.
+ * It implements the http.Handler interface so it is compatible with the
+ standard http.ServeMux.
+
+Let's start registering a couple of URL paths and handlers:
+
+ func main() {
+ r := mux.NewRouter()
+ r.HandleFunc("/", HomeHandler)
+ r.HandleFunc("/products", ProductsHandler)
+ r.HandleFunc("/articles", ArticlesHandler)
+ http.Handle("/", r)
+ }
+
+Here we register three routes mapping URL paths to handlers. This is
+equivalent to how http.HandleFunc() works: if an incoming request URL matches
+one of the paths, the corresponding handler is called passing
+(http.ResponseWriter, *http.Request) as parameters.
+
+Paths can have variables. They are defined using the format {name} or
+{name:pattern}. If a regular expression pattern is not defined, the matched
+variable will be anything until the next slash. For example:
+
+ r := mux.NewRouter()
+ r.HandleFunc("/products/{key}", ProductHandler)
+ r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
+ r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
+
+The names are used to create a map of route variables which can be retrieved
+calling mux.Vars():
+
+ vars := mux.Vars(request)
+ category := vars["category"]
+
+And this is all you need to know about the basic usage. More advanced options
+are explained below.
+
+Routes can also be restricted to a domain or subdomain. Just define a host
+pattern to be matched. They can also have variables:
+
+ r := mux.NewRouter()
+ // Only matches if domain is "www.example.com".
+ r.Host("www.example.com")
+ // Matches a dynamic subdomain.
+ r.Host("{subdomain:[a-z]+}.domain.com")
+
+There are several other matchers that can be added. To match path prefixes:
+
+ r.PathPrefix("/products/")
+
+...or HTTP methods:
+
+ r.Methods("GET", "POST")
+
+...or URL schemes:
+
+ r.Schemes("https")
+
+...or header values:
+
+ r.Headers("X-Requested-With", "XMLHttpRequest")
+
+...or query values:
+
+ r.Queries("key", "value")
+
+...or to use a custom matcher function:
+
+ r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
+ return r.ProtoMajor == 0
+ })
+
+...and finally, it is possible to combine several matchers in a single route:
+
+ r.HandleFunc("/products", ProductsHandler).
+ Host("www.example.com").
+ Methods("GET").
+ Schemes("http")
+
+Setting the same matching conditions again and again can be boring, so we have
+a way to group several routes that share the same requirements.
+We call it "subrouting".
+
+For example, let's say we have several URLs that should only match when the
+host is "www.example.com". Create a route for that host and get a "subrouter"
+from it:
+
+ r := mux.NewRouter()
+ s := r.Host("www.example.com").Subrouter()
+
+Then register routes in the subrouter:
+
+ s.HandleFunc("/products/", ProductsHandler)
+ s.HandleFunc("/products/{key}", ProductHandler)
+ s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
+
+The three URL paths we registered above will only be tested if the domain is
+"www.example.com", because the subrouter is tested first. This is not
+only convenient, but also optimizes request matching. You can create
+subrouters combining any attribute matchers accepted by a route.
+
+Subrouters can be used to create domain or path "namespaces": you define
+subrouters in a central place and then parts of the app can register its
+paths relatively to a given subrouter.
+
+There's one more thing about subroutes. When a subrouter has a path prefix,
+the inner routes use it as base for their paths:
+
+ r := mux.NewRouter()
+ s := r.PathPrefix("/products").Subrouter()
+ // "/products/"
+ s.HandleFunc("/", ProductsHandler)
+ // "/products/{key}/"
+ s.HandleFunc("/{key}/", ProductHandler)
+ // "/products/{key}/details"
+ s.HandleFunc("/{key}/details", ProductDetailsHandler)
+
+Now let's see how to build registered URLs.
+
+Routes can be named. All routes that define a name can have their URLs built,
+or "reversed". We define a name calling Name() on a route. For example:
+
+ r := mux.NewRouter()
+ r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
+ Name("article")
+
+To build a URL, get the route and call the URL() method, passing a sequence of
+key/value pairs for the route variables. For the previous route, we would do:
+
+ url, err := r.Get("article").URL("category", "technology", "id", "42")
+
+...and the result will be a url.URL with the following path:
+
+ "/articles/technology/42"
+
+This also works for host variables:
+
+ r := mux.NewRouter()
+ r.Host("{subdomain}.domain.com").
+ Path("/articles/{category}/{id:[0-9]+}").
+ HandlerFunc(ArticleHandler).
+ Name("article")
+
+ // url.String() will be "http://news.domain.com/articles/technology/42"
+ url, err := r.Get("article").URL("subdomain", "news",
+ "category", "technology",
+ "id", "42")
+
+All variables defined in the route are required, and their values must
+conform to the corresponding patterns. These requirements guarantee that a
+generated URL will always match a registered route -- the only exception is
+for explicitly defined "build-only" routes which never match.
+
+Regex support also exists for matching Headers within a route. For example, we could do:
+
+ r.HeadersRegexp("Content-Type", "application/(text|json)")
+
+...and the route will match both requests with a Content-Type of `application/json` as well as
+`application/text`
+
+There's also a way to build only the URL host or path for a route:
+use the methods URLHost() or URLPath() instead. For the previous route,
+we would do:
+
+ // "http://news.domain.com/"
+ host, err := r.Get("article").URLHost("subdomain", "news")
+
+ // "/articles/technology/42"
+ path, err := r.Get("article").URLPath("category", "technology", "id", "42")
+
+And if you use subrouters, host and path defined separately can be built
+as well:
+
+ r := mux.NewRouter()
+ s := r.Host("{subdomain}.domain.com").Subrouter()
+ s.Path("/articles/{category}/{id:[0-9]+}").
+ HandlerFunc(ArticleHandler).
+ Name("article")
+
+ // "http://news.domain.com/articles/technology/42"
+ url, err := r.Get("article").URL("subdomain", "news",
+ "category", "technology",
+ "id", "42")
+*/
+package mux
diff --git a/vendor/github.com/gorilla/mux/mux.go b/vendor/github.com/gorilla/mux/mux.go
new file mode 100644
index 0000000..fbb7f19
--- /dev/null
+++ b/vendor/github.com/gorilla/mux/mux.go
@@ -0,0 +1,481 @@
+// Copyright 2012 The Gorilla 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 mux
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+ "path"
+ "regexp"
+
+ "github.com/gorilla/context"
+)
+
+// NewRouter returns a new router instance.
+func NewRouter() *Router {
+ return &Router{namedRoutes: make(map[string]*Route), KeepContext: false}
+}
+
+// Router registers routes to be matched and dispatches a handler.
+//
+// It implements the http.Handler interface, so it can be registered to serve
+// requests:
+//
+// var router = mux.NewRouter()
+//
+// func main() {
+// http.Handle("/", router)
+// }
+//
+// Or, for Google App Engine, register it in a init() function:
+//
+// func init() {
+// http.Handle("/", router)
+// }
+//
+// This will send all incoming requests to the router.
+type Router struct {
+ // Configurable Handler to be used when no route matches.
+ NotFoundHandler http.Handler
+ // Parent route, if this is a subrouter.
+ parent parentRoute
+ // Routes to be matched, in order.
+ routes []*Route
+ // Routes by name for URL building.
+ namedRoutes map[string]*Route
+ // See Router.StrictSlash(). This defines the flag for new routes.
+ strictSlash bool
+ // If true, do not clear the request context after handling the request
+ KeepContext bool
+}
+
+// Match matches registered routes against the request.
+func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
+ for _, route := range r.routes {
+ if route.Match(req, match) {
+ return true
+ }
+ }
+
+ // Closest match for a router (includes sub-routers)
+ if r.NotFoundHandler != nil {
+ match.Handler = r.NotFoundHandler
+ return true
+ }
+ return false
+}
+
+// ServeHTTP dispatches the handler registered in the matched route.
+//
+// When there is a match, the route variables can be retrieved calling
+// mux.Vars(request).
+func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
+ // Clean path to canonical form and redirect.
+ if p := cleanPath(req.URL.Path); p != req.URL.Path {
+
+ // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
+ // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
+ // http://code.google.com/p/go/issues/detail?id=5252
+ url := *req.URL
+ url.Path = p
+ p = url.String()
+
+ w.Header().Set("Location", p)
+ w.WriteHeader(http.StatusMovedPermanently)
+ return
+ }
+ var match RouteMatch
+ var handler http.Handler
+ if r.Match(req, &match) {
+ handler = match.Handler
+ setVars(req, match.Vars)
+ setCurrentRoute(req, match.Route)
+ }
+ if handler == nil {
+ handler = http.NotFoundHandler()
+ }
+ if !r.KeepContext {
+ defer context.Clear(req)
+ }
+ handler.ServeHTTP(w, req)
+}
+
+// Get returns a route registered with the given name.
+func (r *Router) Get(name string) *Route {
+ return r.getNamedRoutes()[name]
+}
+
+// GetRoute returns a route registered with the given name. This method
+// was renamed to Get() and remains here for backwards compatibility.
+func (r *Router) GetRoute(name string) *Route {
+ return r.getNamedRoutes()[name]
+}
+
+// StrictSlash defines the trailing slash behavior for new routes. The initial
+// value is false.
+//
+// When true, if the route path is "/path/", accessing "/path" will redirect
+// to the former and vice versa. In other words, your application will always
+// see the path as specified in the route.
+//
+// When false, if the route path is "/path", accessing "/path/" will not match
+// this route and vice versa.
+//
+// Special case: when a route sets a path prefix using the PathPrefix() method,
+// strict slash is ignored for that route because the redirect behavior can't
+// be determined from a prefix alone. However, any subrouters created from that
+// route inherit the original StrictSlash setting.
+func (r *Router) StrictSlash(value bool) *Router {
+ r.strictSlash = value
+ return r
+}
+
+// ----------------------------------------------------------------------------
+// parentRoute
+// ----------------------------------------------------------------------------
+
+// getNamedRoutes returns the map where named routes are registered.
+func (r *Router) getNamedRoutes() map[string]*Route {
+ if r.namedRoutes == nil {
+ if r.parent != nil {
+ r.namedRoutes = r.parent.getNamedRoutes()
+ } else {
+ r.namedRoutes = make(map[string]*Route)
+ }
+ }
+ return r.namedRoutes
+}
+
+// getRegexpGroup returns regexp definitions from the parent route, if any.
+func (r *Router) getRegexpGroup() *routeRegexpGroup {
+ if r.parent != nil {
+ return r.parent.getRegexpGroup()
+ }
+ return nil
+}
+
+func (r *Router) buildVars(m map[string]string) map[string]string {
+ if r.parent != nil {
+ m = r.parent.buildVars(m)
+ }
+ return m
+}
+
+// ----------------------------------------------------------------------------
+// Route factories
+// ----------------------------------------------------------------------------
+
+// NewRoute registers an empty route.
+func (r *Router) NewRoute() *Route {
+ route := &Route{parent: r, strictSlash: r.strictSlash}
+ r.routes = append(r.routes, route)
+ return route
+}
+
+// Handle registers a new route with a matcher for the URL path.
+// See Route.Path() and Route.Handler().
+func (r *Router) Handle(path string, handler http.Handler) *Route {
+ return r.NewRoute().Path(path).Handler(handler)
+}
+
+// HandleFunc registers a new route with a matcher for the URL path.
+// See Route.Path() and Route.HandlerFunc().
+func (r *Router) HandleFunc(path string, f func(http.ResponseWriter,
+ *http.Request)) *Route {
+ return r.NewRoute().Path(path).HandlerFunc(f)
+}
+
+// Headers registers a new route with a matcher for request header values.
+// See Route.Headers().
+func (r *Router) Headers(pairs ...string) *Route {
+ return r.NewRoute().Headers(pairs...)
+}
+
+// Host registers a new route with a matcher for the URL host.
+// See Route.Host().
+func (r *Router) Host(tpl string) *Route {
+ return r.NewRoute().Host(tpl)
+}
+
+// MatcherFunc registers a new route with a custom matcher function.
+// See Route.MatcherFunc().
+func (r *Router) MatcherFunc(f MatcherFunc) *Route {
+ return r.NewRoute().MatcherFunc(f)
+}
+
+// Methods registers a new route with a matcher for HTTP methods.
+// See Route.Methods().
+func (r *Router) Methods(methods ...string) *Route {
+ return r.NewRoute().Methods(methods...)
+}
+
+// Path registers a new route with a matcher for the URL path.
+// See Route.Path().
+func (r *Router) Path(tpl string) *Route {
+ return r.NewRoute().Path(tpl)
+}
+
+// PathPrefix registers a new route with a matcher for the URL path prefix.
+// See Route.PathPrefix().
+func (r *Router) PathPrefix(tpl string) *Route {
+ return r.NewRoute().PathPrefix(tpl)
+}
+
+// Queries registers a new route with a matcher for URL query values.
+// See Route.Queries().
+func (r *Router) Queries(pairs ...string) *Route {
+ return r.NewRoute().Queries(pairs...)
+}
+
+// Schemes registers a new route with a matcher for URL schemes.
+// See Route.Schemes().
+func (r *Router) Schemes(schemes ...string) *Route {
+ return r.NewRoute().Schemes(schemes...)
+}
+
+// BuildVarsFunc registers a new route with a custom function for modifying
+// route variables before building a URL.
+func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route {
+ return r.NewRoute().BuildVarsFunc(f)
+}
+
+// Walk walks the router and all its sub-routers, calling walkFn for each route
+// in the tree. The routes are walked in the order they were added. Sub-routers
+// are explored depth-first.
+func (r *Router) Walk(walkFn WalkFunc) error {
+ return r.walk(walkFn, []*Route{})
+}
+
+// SkipRouter is used as a return value from WalkFuncs to indicate that the
+// router that walk is about to descend down to should be skipped.
+var SkipRouter = errors.New("skip this router")
+
+// WalkFunc is the type of the function called for each route visited by Walk.
+// At every invocation, it is given the current route, and the current router,
+// and a list of ancestor routes that lead to the current route.
+type WalkFunc func(route *Route, router *Router, ancestors []*Route) error
+
+func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
+ for _, t := range r.routes {
+ if t.regexp == nil || t.regexp.path == nil || t.regexp.path.template == "" {
+ continue
+ }
+
+ err := walkFn(t, r, ancestors)
+ if err == SkipRouter {
+ continue
+ }
+ for _, sr := range t.matchers {
+ if h, ok := sr.(*Router); ok {
+ err := h.walk(walkFn, ancestors)
+ if err != nil {
+ return err
+ }
+ }
+ }
+ if h, ok := t.handler.(*Router); ok {
+ ancestors = append(ancestors, t)
+ err := h.walk(walkFn, ancestors)
+ if err != nil {
+ return err
+ }
+ ancestors = ancestors[:len(ancestors)-1]
+ }
+ }
+ return nil
+}
+
+// ----------------------------------------------------------------------------
+// Context
+// ----------------------------------------------------------------------------
+
+// RouteMatch stores information about a matched route.
+type RouteMatch struct {
+ Route *Route
+ Handler http.Handler
+ Vars map[string]string
+}
+
+type contextKey int
+
+const (
+ varsKey contextKey = iota
+ routeKey
+)
+
+// Vars returns the route variables for the current request, if any.
+func Vars(r *http.Request) map[string]string {
+ if rv := context.Get(r, varsKey); rv != nil {
+ return rv.(map[string]string)
+ }
+ return nil
+}
+
+// CurrentRoute returns the matched route for the current request, if any.
+// This only works when called inside the handler of the matched route
+// because the matched route is stored in the request context which is cleared
+// after the handler returns, unless the KeepContext option is set on the
+// Router.
+func CurrentRoute(r *http.Request) *Route {
+ if rv := context.Get(r, routeKey); rv != nil {
+ return rv.(*Route)
+ }
+ return nil
+}
+
+func setVars(r *http.Request, val interface{}) {
+ if val != nil {
+ context.Set(r, varsKey, val)
+ }
+}
+
+func setCurrentRoute(r *http.Request, val interface{}) {
+ if val != nil {
+ context.Set(r, routeKey, val)
+ }
+}
+
+// ----------------------------------------------------------------------------
+// Helpers
+// ----------------------------------------------------------------------------
+
+// cleanPath returns the canonical path for p, eliminating . and .. elements.
+// Borrowed from the net/http package.
+func cleanPath(p string) string {
+ if p == "" {
+ return "/"
+ }
+ if p[0] != '/' {
+ p = "/" + p
+ }
+ np := path.Clean(p)
+ // path.Clean removes trailing slash except for root;
+ // put the trailing slash back if necessary.
+ if p[len(p)-1] == '/' && np != "/" {
+ np += "/"
+ }
+ return np
+}
+
+// uniqueVars returns an error if two slices contain duplicated strings.
+func uniqueVars(s1, s2 []string) error {
+ for _, v1 := range s1 {
+ for _, v2 := range s2 {
+ if v1 == v2 {
+ return fmt.Errorf("mux: duplicated route variable %q", v2)
+ }
+ }
+ }
+ return nil
+}
+
+// checkPairs returns the count of strings passed in, and an error if
+// the count is not an even number.
+func checkPairs(pairs ...string) (int, error) {
+ length := len(pairs)
+ if length%2 != 0 {
+ return length, fmt.Errorf(
+ "mux: number of parameters must be multiple of 2, got %v", pairs)
+ }
+ return length, nil
+}
+
+// mapFromPairsToString converts variadic string parameters to a
+// string to string map.
+func mapFromPairsToString(pairs ...string) (map[string]string, error) {
+ length, err := checkPairs(pairs...)
+ if err != nil {
+ return nil, err
+ }
+ m := make(map[string]string, length/2)
+ for i := 0; i < length; i += 2 {
+ m[pairs[i]] = pairs[i+1]
+ }
+ return m, nil
+}
+
+// mapFromPairsToRegex converts variadic string paramers to a
+// string to regex map.
+func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) {
+ length, err := checkPairs(pairs...)
+ if err != nil {
+ return nil, err
+ }
+ m := make(map[string]*regexp.Regexp, length/2)
+ for i := 0; i < length; i += 2 {
+ regex, err := regexp.Compile(pairs[i+1])
+ if err != nil {
+ return nil, err
+ }
+ m[pairs[i]] = regex
+ }
+ return m, nil
+}
+
+// matchInArray returns true if the given string value is in the array.
+func matchInArray(arr []string, value string) bool {
+ for _, v := range arr {
+ if v == value {
+ return true
+ }
+ }
+ return false
+}
+
+// matchMapWithString returns true if the given key/value pairs exist in a given map.
+func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool {
+ for k, v := range toCheck {
+ // Check if key exists.
+ if canonicalKey {
+ k = http.CanonicalHeaderKey(k)
+ }
+ if values := toMatch[k]; values == nil {
+ return false
+ } else if v != "" {
+ // If value was defined as an empty string we only check that the
+ // key exists. Otherwise we also check for equality.
+ valueExists := false
+ for _, value := range values {
+ if v == value {
+ valueExists = true
+ break
+ }
+ }
+ if !valueExists {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against
+// the given regex
+func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool {
+ for k, v := range toCheck {
+ // Check if key exists.
+ if canonicalKey {
+ k = http.CanonicalHeaderKey(k)
+ }
+ if values := toMatch[k]; values == nil {
+ return false
+ } else if v != nil {
+ // If value was defined as an empty string we only check that the
+ // key exists. Otherwise we also check for equality.
+ valueExists := false
+ for _, value := range values {
+ if v.MatchString(value) {
+ valueExists = true
+ break
+ }
+ }
+ if !valueExists {
+ return false
+ }
+ }
+ }
+ return true
+}
diff --git a/vendor/github.com/gorilla/mux/regexp.go b/vendor/github.com/gorilla/mux/regexp.go
new file mode 100644
index 0000000..08710bc
--- /dev/null
+++ b/vendor/github.com/gorilla/mux/regexp.go
@@ -0,0 +1,312 @@
+// Copyright 2012 The Gorilla 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 mux
+
+import (
+ "bytes"
+ "fmt"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+// newRouteRegexp parses a route template and returns a routeRegexp,
+// used to match a host, a path or a query string.
+//
+// It will extract named variables, assemble a regexp to be matched, create
+// a "reverse" template to build URLs and compile regexps to validate variable
+// values used in URL building.
+//
+// Previously we accepted only Python-like identifiers for variable
+// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that
+// name and pattern can't be empty, and names can't contain a colon.
+func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash bool) (*routeRegexp, error) {
+ // Check if it is well-formed.
+ idxs, errBraces := braceIndices(tpl)
+ if errBraces != nil {
+ return nil, errBraces
+ }
+ // Backup the original.
+ template := tpl
+ // Now let's parse it.
+ defaultPattern := "[^/]+"
+ if matchQuery {
+ defaultPattern = "[^?&]*"
+ } else if matchHost {
+ defaultPattern = "[^.]+"
+ matchPrefix = false
+ }
+ // Only match strict slash if not matching
+ if matchPrefix || matchHost || matchQuery {
+ strictSlash = false
+ }
+ // Set a flag for strictSlash.
+ endSlash := false
+ if strictSlash && strings.HasSuffix(tpl, "/") {
+ tpl = tpl[:len(tpl)-1]
+ endSlash = true
+ }
+ varsN := make([]string, len(idxs)/2)
+ varsR := make([]*regexp.Regexp, len(idxs)/2)
+ pattern := bytes.NewBufferString("")
+ pattern.WriteByte('^')
+ reverse := bytes.NewBufferString("")
+ var end int
+ var err error
+ for i := 0; i < len(idxs); i += 2 {
+ // Set all values we are interested in.
+ raw := tpl[end:idxs[i]]
+ end = idxs[i+1]
+ parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
+ name := parts[0]
+ patt := defaultPattern
+ if len(parts) == 2 {
+ patt = parts[1]
+ }
+ // Name or pattern can't be empty.
+ if name == "" || patt == "" {
+ return nil, fmt.Errorf("mux: missing name or pattern in %q",
+ tpl[idxs[i]:end])
+ }
+ // Build the regexp pattern.
+ fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt)
+
+ // Build the reverse template.
+ fmt.Fprintf(reverse, "%s%%s", raw)
+
+ // Append variable name and compiled pattern.
+ varsN[i/2] = name
+ varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt))
+ if err != nil {
+ return nil, err
+ }
+ }
+ // Add the remaining.
+ raw := tpl[end:]
+ pattern.WriteString(regexp.QuoteMeta(raw))
+ if strictSlash {
+ pattern.WriteString("[/]?")
+ }
+ if matchQuery {
+ // Add the default pattern if the query value is empty
+ if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" {
+ pattern.WriteString(defaultPattern)
+ }
+ }
+ if !matchPrefix {
+ pattern.WriteByte('$')
+ }
+ reverse.WriteString(raw)
+ if endSlash {
+ reverse.WriteByte('/')
+ }
+ // Compile full regexp.
+ reg, errCompile := regexp.Compile(pattern.String())
+ if errCompile != nil {
+ return nil, errCompile
+ }
+ // Done!
+ return &routeRegexp{
+ template: template,
+ matchHost: matchHost,
+ matchQuery: matchQuery,
+ strictSlash: strictSlash,
+ regexp: reg,
+ reverse: reverse.String(),
+ varsN: varsN,
+ varsR: varsR,
+ }, nil
+}
+
+// routeRegexp stores a regexp to match a host or path and information to
+// collect and validate route variables.
+type routeRegexp struct {
+ // The unmodified template.
+ template string
+ // True for host match, false for path or query string match.
+ matchHost bool
+ // True for query string match, false for path and host match.
+ matchQuery bool
+ // The strictSlash value defined on the route, but disabled if PathPrefix was used.
+ strictSlash bool
+ // Expanded regexp.
+ regexp *regexp.Regexp
+ // Reverse template.
+ reverse string
+ // Variable names.
+ varsN []string
+ // Variable regexps (validators).
+ varsR []*regexp.Regexp
+}
+
+// Match matches the regexp against the URL host or path.
+func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
+ if !r.matchHost {
+ if r.matchQuery {
+ return r.matchQueryString(req)
+ }
+
+ return r.regexp.MatchString(req.URL.Path)
+ }
+
+ return r.regexp.MatchString(getHost(req))
+}
+
+// url builds a URL part using the given values.
+func (r *routeRegexp) url(values map[string]string) (string, error) {
+ urlValues := make([]interface{}, len(r.varsN))
+ for k, v := range r.varsN {
+ value, ok := values[v]
+ if !ok {
+ return "", fmt.Errorf("mux: missing route variable %q", v)
+ }
+ urlValues[k] = value
+ }
+ rv := fmt.Sprintf(r.reverse, urlValues...)
+ if !r.regexp.MatchString(rv) {
+ // The URL is checked against the full regexp, instead of checking
+ // individual variables. This is faster but to provide a good error
+ // message, we check individual regexps if the URL doesn't match.
+ for k, v := range r.varsN {
+ if !r.varsR[k].MatchString(values[v]) {
+ return "", fmt.Errorf(
+ "mux: variable %q doesn't match, expected %q", values[v],
+ r.varsR[k].String())
+ }
+ }
+ }
+ return rv, nil
+}
+
+// getURLQuery returns a single query parameter from a request URL.
+// For a URL with foo=bar&baz=ding, we return only the relevant key
+// value pair for the routeRegexp.
+func (r *routeRegexp) getURLQuery(req *http.Request) string {
+ if !r.matchQuery {
+ return ""
+ }
+ templateKey := strings.SplitN(r.template, "=", 2)[0]
+ for key, vals := range req.URL.Query() {
+ if key == templateKey && len(vals) > 0 {
+ return key + "=" + vals[0]
+ }
+ }
+ return ""
+}
+
+func (r *routeRegexp) matchQueryString(req *http.Request) bool {
+ return r.regexp.MatchString(r.getURLQuery(req))
+}
+
+// braceIndices returns the first level curly brace indices from a string.
+// It returns an error in case of unbalanced braces.
+func braceIndices(s string) ([]int, error) {
+ var level, idx int
+ var idxs []int
+ for i := 0; i < len(s); i++ {
+ switch s[i] {
+ case '{':
+ if level++; level == 1 {
+ idx = i
+ }
+ case '}':
+ if level--; level == 0 {
+ idxs = append(idxs, idx, i+1)
+ } else if level < 0 {
+ return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
+ }
+ }
+ }
+ if level != 0 {
+ return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
+ }
+ return idxs, nil
+}
+
+// varGroupName builds a capturing group name for the indexed variable.
+func varGroupName(idx int) string {
+ return "v" + strconv.Itoa(idx)
+}
+
+// ----------------------------------------------------------------------------
+// routeRegexpGroup
+// ----------------------------------------------------------------------------
+
+// routeRegexpGroup groups the route matchers that carry variables.
+type routeRegexpGroup struct {
+ host *routeRegexp
+ path *routeRegexp
+ queries []*routeRegexp
+}
+
+// setMatch extracts the variables from the URL once a route matches.
+func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) {
+ // Store host variables.
+ if v.host != nil {
+ host := getHost(req)
+ matches := v.host.regexp.FindStringSubmatchIndex(host)
+ if len(matches) > 0 {
+ extractVars(host, matches, v.host.varsN, m.Vars)
+ }
+ }
+ // Store path variables.
+ if v.path != nil {
+ matches := v.path.regexp.FindStringSubmatchIndex(req.URL.Path)
+ if len(matches) > 0 {
+ extractVars(req.URL.Path, matches, v.path.varsN, m.Vars)
+ // Check if we should redirect.
+ if v.path.strictSlash {
+ p1 := strings.HasSuffix(req.URL.Path, "/")
+ p2 := strings.HasSuffix(v.path.template, "/")
+ if p1 != p2 {
+ u, _ := url.Parse(req.URL.String())
+ if p1 {
+ u.Path = u.Path[:len(u.Path)-1]
+ } else {
+ u.Path += "/"
+ }
+ m.Handler = http.RedirectHandler(u.String(), 301)
+ }
+ }
+ }
+ }
+ // Store query string variables.
+ for _, q := range v.queries {
+ queryURL := q.getURLQuery(req)
+ matches := q.regexp.FindStringSubmatchIndex(queryURL)
+ if len(matches) > 0 {
+ extractVars(queryURL, matches, q.varsN, m.Vars)
+ }
+ }
+}
+
+// getHost tries its best to return the request host.
+func getHost(r *http.Request) string {
+ if r.URL.IsAbs() {
+ return r.URL.Host
+ }
+ host := r.Host
+ // Slice off any port information.
+ if i := strings.Index(host, ":"); i != -1 {
+ host = host[:i]
+ }
+ return host
+
+}
+
+func extractVars(input string, matches []int, names []string, output map[string]string) {
+ matchesCount := 0
+ prevEnd := -1
+ for i := 2; i < len(matches) && matchesCount < len(names); i += 2 {
+ if prevEnd < matches[i+1] {
+ value := input[matches[i]:matches[i+1]]
+ output[names[matchesCount]] = value
+ prevEnd = matches[i+1]
+ matchesCount++
+ }
+ }
+}
diff --git a/vendor/github.com/gorilla/mux/route.go b/vendor/github.com/gorilla/mux/route.go
new file mode 100644
index 0000000..bf92af2
--- /dev/null
+++ b/vendor/github.com/gorilla/mux/route.go
@@ -0,0 +1,627 @@
+// Copyright 2012 The Gorilla 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 mux
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+)
+
+// Route stores information to match a request and build URLs.
+type Route struct {
+ // Parent where the route was registered (a Router).
+ parent parentRoute
+ // Request handler for the route.
+ handler http.Handler
+ // List of matchers.
+ matchers []matcher
+ // Manager for the variables from host and path.
+ regexp *routeRegexpGroup
+ // If true, when the path pattern is "/path/", accessing "/path" will
+ // redirect to the former and vice versa.
+ strictSlash bool
+ // If true, this route never matches: it is only used to build URLs.
+ buildOnly bool
+ // The name used to build URLs.
+ name string
+ // Error resulted from building a route.
+ err error
+
+ buildVarsFunc BuildVarsFunc
+}
+
+// Match matches the route against the request.
+func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
+ if r.buildOnly || r.err != nil {
+ return false
+ }
+ // Match everything.
+ for _, m := range r.matchers {
+ if matched := m.Match(req, match); !matched {
+ return false
+ }
+ }
+ // Yay, we have a match. Let's collect some info about it.
+ if match.Route == nil {
+ match.Route = r
+ }
+ if match.Handler == nil {
+ match.Handler = r.handler
+ }
+ if match.Vars == nil {
+ match.Vars = make(map[string]string)
+ }
+ // Set variables.
+ if r.regexp != nil {
+ r.regexp.setMatch(req, match, r)
+ }
+ return true
+}
+
+// ----------------------------------------------------------------------------
+// Route attributes
+// ----------------------------------------------------------------------------
+
+// GetError returns an error resulted from building the route, if any.
+func (r *Route) GetError() error {
+ return r.err
+}
+
+// BuildOnly sets the route to never match: it is only used to build URLs.
+func (r *Route) BuildOnly() *Route {
+ r.buildOnly = true
+ return r
+}
+
+// Handler --------------------------------------------------------------------
+
+// Handler sets a handler for the route.
+func (r *Route) Handler(handler http.Handler) *Route {
+ if r.err == nil {
+ r.handler = handler
+ }
+ return r
+}
+
+// HandlerFunc sets a handler function for the route.
+func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route {
+ return r.Handler(http.HandlerFunc(f))
+}
+
+// GetHandler returns the handler for the route, if any.
+func (r *Route) GetHandler() http.Handler {
+ return r.handler
+}
+
+// Name -----------------------------------------------------------------------
+
+// Name sets the name for the route, used to build URLs.
+// If the name was registered already it will be overwritten.
+func (r *Route) Name(name string) *Route {
+ if r.name != "" {
+ r.err = fmt.Errorf("mux: route already has name %q, can't set %q",
+ r.name, name)
+ }
+ if r.err == nil {
+ r.name = name
+ r.getNamedRoutes()[name] = r
+ }
+ return r
+}
+
+// GetName returns the name for the route, if any.
+func (r *Route) GetName() string {
+ return r.name
+}
+
+// ----------------------------------------------------------------------------
+// Matchers
+// ----------------------------------------------------------------------------
+
+// matcher types try to match a request.
+type matcher interface {
+ Match(*http.Request, *RouteMatch) bool
+}
+
+// addMatcher adds a matcher to the route.
+func (r *Route) addMatcher(m matcher) *Route {
+ if r.err == nil {
+ r.matchers = append(r.matchers, m)
+ }
+ return r
+}
+
+// addRegexpMatcher adds a host or path matcher and builder to a route.
+func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error {
+ if r.err != nil {
+ return r.err
+ }
+ r.regexp = r.getRegexpGroup()
+ if !matchHost && !matchQuery {
+ if len(tpl) == 0 || tpl[0] != '/' {
+ return fmt.Errorf("mux: path must start with a slash, got %q", tpl)
+ }
+ if r.regexp.path != nil {
+ tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl
+ }
+ }
+ rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash)
+ if err != nil {
+ return err
+ }
+ for _, q := range r.regexp.queries {
+ if err = uniqueVars(rr.varsN, q.varsN); err != nil {
+ return err
+ }
+ }
+ if matchHost {
+ if r.regexp.path != nil {
+ if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil {
+ return err
+ }
+ }
+ r.regexp.host = rr
+ } else {
+ if r.regexp.host != nil {
+ if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil {
+ return err
+ }
+ }
+ if matchQuery {
+ r.regexp.queries = append(r.regexp.queries, rr)
+ } else {
+ r.regexp.path = rr
+ }
+ }
+ r.addMatcher(rr)
+ return nil
+}
+
+// Headers --------------------------------------------------------------------
+
+// headerMatcher matches the request against header values.
+type headerMatcher map[string]string
+
+func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool {
+ return matchMapWithString(m, r.Header, true)
+}
+
+// Headers adds a matcher for request header values.
+// It accepts a sequence of key/value pairs to be matched. For example:
+//
+// r := mux.NewRouter()
+// r.Headers("Content-Type", "application/json",
+// "X-Requested-With", "XMLHttpRequest")
+//
+// The above route will only match if both request header values match.
+// If the value is an empty string, it will match any value if the key is set.
+func (r *Route) Headers(pairs ...string) *Route {
+ if r.err == nil {
+ var headers map[string]string
+ headers, r.err = mapFromPairsToString(pairs...)
+ return r.addMatcher(headerMatcher(headers))
+ }
+ return r
+}
+
+// headerRegexMatcher matches the request against the route given a regex for the header
+type headerRegexMatcher map[string]*regexp.Regexp
+
+func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool {
+ return matchMapWithRegex(m, r.Header, true)
+}
+
+// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex
+// support. For example:
+//
+// r := mux.NewRouter()
+// r.HeadersRegexp("Content-Type", "application/(text|json)",
+// "X-Requested-With", "XMLHttpRequest")
+//
+// The above route will only match if both the request header matches both regular expressions.
+// It the value is an empty string, it will match any value if the key is set.
+func (r *Route) HeadersRegexp(pairs ...string) *Route {
+ if r.err == nil {
+ var headers map[string]*regexp.Regexp
+ headers, r.err = mapFromPairsToRegex(pairs...)
+ return r.addMatcher(headerRegexMatcher(headers))
+ }
+ return r
+}
+
+// Host -----------------------------------------------------------------------
+
+// Host adds a matcher for the URL host.
+// It accepts a template with zero or more URL variables enclosed by {}.
+// Variables can define an optional regexp pattern to be matched:
+//
+// - {name} matches anything until the next dot.
+//
+// - {name:pattern} matches the given regexp pattern.
+//
+// For example:
+//
+// r := mux.NewRouter()
+// r.Host("www.example.com")
+// r.Host("{subdomain}.domain.com")
+// r.Host("{subdomain:[a-z]+}.domain.com")
+//
+// Variable names must be unique in a given route. They can be retrieved
+// calling mux.Vars(request).
+func (r *Route) Host(tpl string) *Route {
+ r.err = r.addRegexpMatcher(tpl, true, false, false)
+ return r
+}
+
+// MatcherFunc ----------------------------------------------------------------
+
+// MatcherFunc is the function signature used by custom matchers.
+type MatcherFunc func(*http.Request, *RouteMatch) bool
+
+// Match returns the match for a given request.
+func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool {
+ return m(r, match)
+}
+
+// MatcherFunc adds a custom function to be used as request matcher.
+func (r *Route) MatcherFunc(f MatcherFunc) *Route {
+ return r.addMatcher(f)
+}
+
+// Methods --------------------------------------------------------------------
+
+// methodMatcher matches the request against HTTP methods.
+type methodMatcher []string
+
+func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool {
+ return matchInArray(m, r.Method)
+}
+
+// Methods adds a matcher for HTTP methods.
+// It accepts a sequence of one or more methods to be matched, e.g.:
+// "GET", "POST", "PUT".
+func (r *Route) Methods(methods ...string) *Route {
+ for k, v := range methods {
+ methods[k] = strings.ToUpper(v)
+ }
+ return r.addMatcher(methodMatcher(methods))
+}
+
+// Path -----------------------------------------------------------------------
+
+// Path adds a matcher for the URL path.
+// It accepts a template with zero or more URL variables enclosed by {}. The
+// template must start with a "/".
+// Variables can define an optional regexp pattern to be matched:
+//
+// - {name} matches anything until the next slash.
+//
+// - {name:pattern} matches the given regexp pattern.
+//
+// For example:
+//
+// r := mux.NewRouter()
+// r.Path("/products/").Handler(ProductsHandler)
+// r.Path("/products/{key}").Handler(ProductsHandler)
+// r.Path("/articles/{category}/{id:[0-9]+}").
+// Handler(ArticleHandler)
+//
+// Variable names must be unique in a given route. They can be retrieved
+// calling mux.Vars(request).
+func (r *Route) Path(tpl string) *Route {
+ r.err = r.addRegexpMatcher(tpl, false, false, false)
+ return r
+}
+
+// PathPrefix -----------------------------------------------------------------
+
+// PathPrefix adds a matcher for the URL path prefix. This matches if the given
+// template is a prefix of the full URL path. See Route.Path() for details on
+// the tpl argument.
+//
+// Note that it does not treat slashes specially ("/foobar/" will be matched by
+// the prefix "/foo") so you may want to use a trailing slash here.
+//
+// Also note that the setting of Router.StrictSlash() has no effect on routes
+// with a PathPrefix matcher.
+func (r *Route) PathPrefix(tpl string) *Route {
+ r.err = r.addRegexpMatcher(tpl, false, true, false)
+ return r
+}
+
+// Query ----------------------------------------------------------------------
+
+// Queries adds a matcher for URL query values.
+// It accepts a sequence of key/value pairs. Values may define variables.
+// For example:
+//
+// r := mux.NewRouter()
+// r.Queries("foo", "bar", "id", "{id:[0-9]+}")
+//
+// The above route will only match if the URL contains the defined queries
+// values, e.g.: ?foo=bar&id=42.
+//
+// It the value is an empty string, it will match any value if the key is set.
+//
+// Variables can define an optional regexp pattern to be matched:
+//
+// - {name} matches anything until the next slash.
+//
+// - {name:pattern} matches the given regexp pattern.
+func (r *Route) Queries(pairs ...string) *Route {
+ length := len(pairs)
+ if length%2 != 0 {
+ r.err = fmt.Errorf(
+ "mux: number of parameters must be multiple of 2, got %v", pairs)
+ return nil
+ }
+ for i := 0; i < length; i += 2 {
+ if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil {
+ return r
+ }
+ }
+
+ return r
+}
+
+// Schemes --------------------------------------------------------------------
+
+// schemeMatcher matches the request against URL schemes.
+type schemeMatcher []string
+
+func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool {
+ return matchInArray(m, r.URL.Scheme)
+}
+
+// Schemes adds a matcher for URL schemes.
+// It accepts a sequence of schemes to be matched, e.g.: "http", "https".
+func (r *Route) Schemes(schemes ...string) *Route {
+ for k, v := range schemes {
+ schemes[k] = strings.ToLower(v)
+ }
+ return r.addMatcher(schemeMatcher(schemes))
+}
+
+// BuildVarsFunc --------------------------------------------------------------
+
+// BuildVarsFunc is the function signature used by custom build variable
+// functions (which can modify route variables before a route's URL is built).
+type BuildVarsFunc func(map[string]string) map[string]string
+
+// BuildVarsFunc adds a custom function to be used to modify build variables
+// before a route's URL is built.
+func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route {
+ r.buildVarsFunc = f
+ return r
+}
+
+// Subrouter ------------------------------------------------------------------
+
+// Subrouter creates a subrouter for the route.
+//
+// It will test the inner routes only if the parent route matched. For example:
+//
+// r := mux.NewRouter()
+// s := r.Host("www.example.com").Subrouter()
+// s.HandleFunc("/products/", ProductsHandler)
+// s.HandleFunc("/products/{key}", ProductHandler)
+// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
+//
+// Here, the routes registered in the subrouter won't be tested if the host
+// doesn't match.
+func (r *Route) Subrouter() *Router {
+ router := &Router{parent: r, strictSlash: r.strictSlash}
+ r.addMatcher(router)
+ return router
+}
+
+// ----------------------------------------------------------------------------
+// URL building
+// ----------------------------------------------------------------------------
+
+// URL builds a URL for the route.
+//
+// It accepts a sequence of key/value pairs for the route variables. For
+// example, given this route:
+//
+// r := mux.NewRouter()
+// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
+// Name("article")
+//
+// ...a URL for it can be built using:
+//
+// url, err := r.Get("article").URL("category", "technology", "id", "42")
+//
+// ...which will return an url.URL with the following path:
+//
+// "/articles/technology/42"
+//
+// This also works for host variables:
+//
+// r := mux.NewRouter()
+// r.Host("{subdomain}.domain.com").
+// HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
+// Name("article")
+//
+// // url.String() will be "http://news.domain.com/articles/technology/42"
+// url, err := r.Get("article").URL("subdomain", "news",
+// "category", "technology",
+// "id", "42")
+//
+// All variables defined in the route are required, and their values must
+// conform to the corresponding patterns.
+func (r *Route) URL(pairs ...string) (*url.URL, error) {
+ if r.err != nil {
+ return nil, r.err
+ }
+ if r.regexp == nil {
+ return nil, errors.New("mux: route doesn't have a host or path")
+ }
+ values, err := r.prepareVars(pairs...)
+ if err != nil {
+ return nil, err
+ }
+ var scheme, host, path string
+ if r.regexp.host != nil {
+ // Set a default scheme.
+ scheme = "http"
+ if host, err = r.regexp.host.url(values); err != nil {
+ return nil, err
+ }
+ }
+ if r.regexp.path != nil {
+ if path, err = r.regexp.path.url(values); err != nil {
+ return nil, err
+ }
+ }
+ return &url.URL{
+ Scheme: scheme,
+ Host: host,
+ Path: path,
+ }, nil
+}
+
+// URLHost builds the host part of the URL for a route. See Route.URL().
+//
+// The route must have a host defined.
+func (r *Route) URLHost(pairs ...string) (*url.URL, error) {
+ if r.err != nil {
+ return nil, r.err
+ }
+ if r.regexp == nil || r.regexp.host == nil {
+ return nil, errors.New("mux: route doesn't have a host")
+ }
+ values, err := r.prepareVars(pairs...)
+ if err != nil {
+ return nil, err
+ }
+ host, err := r.regexp.host.url(values)
+ if err != nil {
+ return nil, err
+ }
+ return &url.URL{
+ Scheme: "http",
+ Host: host,
+ }, nil
+}
+
+// URLPath builds the path part of the URL for a route. See Route.URL().
+//
+// The route must have a path defined.
+func (r *Route) URLPath(pairs ...string) (*url.URL, error) {
+ if r.err != nil {
+ return nil, r.err
+ }
+ if r.regexp == nil || r.regexp.path == nil {
+ return nil, errors.New("mux: route doesn't have a path")
+ }
+ values, err := r.prepareVars(pairs...)
+ if err != nil {
+ return nil, err
+ }
+ path, err := r.regexp.path.url(values)
+ if err != nil {
+ return nil, err
+ }
+ return &url.URL{
+ Path: path,
+ }, nil
+}
+
+// GetPathTemplate returns the template used to build the
+// route match.
+// This is useful for building simple REST API documentation and for instrumentation
+// against third-party services.
+// An error will be returned if the route does not define a path.
+func (r *Route) GetPathTemplate() (string, error) {
+ if r.err != nil {
+ return "", r.err
+ }
+ if r.regexp == nil || r.regexp.path == nil {
+ return "", errors.New("mux: route doesn't have a path")
+ }
+ return r.regexp.path.template, nil
+}
+
+// GetHostTemplate returns the template used to build the
+// route match.
+// This is useful for building simple REST API documentation and for instrumentation
+// against third-party services.
+// An error will be returned if the route does not define a host.
+func (r *Route) GetHostTemplate() (string, error) {
+ if r.err != nil {
+ return "", r.err
+ }
+ if r.regexp == nil || r.regexp.host == nil {
+ return "", errors.New("mux: route doesn't have a host")
+ }
+ return r.regexp.host.template, nil
+}
+
+// prepareVars converts the route variable pairs into a map. If the route has a
+// BuildVarsFunc, it is invoked.
+func (r *Route) prepareVars(pairs ...string) (map[string]string, error) {
+ m, err := mapFromPairsToString(pairs...)
+ if err != nil {
+ return nil, err
+ }
+ return r.buildVars(m), nil
+}
+
+func (r *Route) buildVars(m map[string]string) map[string]string {
+ if r.parent != nil {
+ m = r.parent.buildVars(m)
+ }
+ if r.buildVarsFunc != nil {
+ m = r.buildVarsFunc(m)
+ }
+ return m
+}
+
+// ----------------------------------------------------------------------------
+// parentRoute
+// ----------------------------------------------------------------------------
+
+// parentRoute allows routes to know about parent host and path definitions.
+type parentRoute interface {
+ getNamedRoutes() map[string]*Route
+ getRegexpGroup() *routeRegexpGroup
+ buildVars(map[string]string) map[string]string
+}
+
+// getNamedRoutes returns the map where named routes are registered.
+func (r *Route) getNamedRoutes() map[string]*Route {
+ if r.parent == nil {
+ // During tests router is not always set.
+ r.parent = NewRouter()
+ }
+ return r.parent.getNamedRoutes()
+}
+
+// getRegexpGroup returns regexp definitions from this route.
+func (r *Route) getRegexpGroup() *routeRegexpGroup {
+ if r.regexp == nil {
+ if r.parent == nil {
+ // During tests router is not always set.
+ r.parent = NewRouter()
+ }
+ regexp := r.parent.getRegexpGroup()
+ if regexp == nil {
+ r.regexp = new(routeRegexpGroup)
+ } else {
+ // Copy.
+ r.regexp = &routeRegexpGroup{
+ host: regexp.host,
+ path: regexp.path,
+ queries: regexp.queries,
+ }
+ }
+ }
+ return r.regexp
+}
diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/LICENSE b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/LICENSE
new file mode 100644
index 0000000..b2b0650
--- /dev/null
+++ b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License. \ No newline at end of file
diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/README.md b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/README.md
new file mode 100644
index 0000000..68c8c46
--- /dev/null
+++ b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/README.md
@@ -0,0 +1,245 @@
+# Go gRPC Interceptors for Prometheus monitoring
+
+[![Travis Build](https://travis-ci.org/grpc-ecosystem/go-grpc-prometheus.svg)](https://travis-ci.org/grpc-ecosystem/go-grpc-prometheus)
+[![Go Report Card](https://goreportcard.com/badge/github.com/grpc-ecosystem/go-grpc-prometheus)](http://goreportcard.com/report/grpc-ecosystem/go-grpc-prometheus)
+[![GoDoc](http://img.shields.io/badge/GoDoc-Reference-blue.svg)](https://godoc.org/github.com/grpc-ecosystem/go-grpc-prometheus)
+[![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
+
+[Prometheus](https://prometheus.io/) monitoring for your [gRPC Go](https://github.com/grpc/grpc-go) servers and clients.
+
+A sister implementation for [gRPC Java](https://github.com/grpc/grpc-java) (same metrics, same semantics) is in [grpc-ecosystem/java-grpc-prometheus](https://github.com/grpc-ecosystem/java-grpc-prometheus).
+
+## Interceptors
+
+[gRPC Go](https://github.com/grpc/grpc-go) recently acquired support for Interceptors, i.e. middleware that is executed
+by a gRPC Server before the request is passed onto the user's application logic. It is a perfect way to implement
+common patterns: auth, logging and... monitoring.
+
+To use Interceptors in chains, please see [`go-grpc-middleware`](https://github.com/mwitkow/go-grpc-middleware).
+
+## Usage
+
+There are two types of interceptors: client-side and server-side. This package provides monitoring Interceptors for both.
+
+### Server-side
+
+```go
+import "github.com/grpc-ecosystem/go-grpc-prometheus"
+...
+ // Initialize your gRPC server's interceptor.
+ myServer := grpc.NewServer(
+ grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
+ grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
+ )
+ // Register your gRPC service implementations.
+ myservice.RegisterMyServiceServer(s.server, &myServiceImpl{})
+ // After all your registrations, make sure all of the Prometheus metrics are initialized.
+ grpc_prometheus.Register(myServer)
+ // Register Prometheus metrics handler.
+ http.Handle("/metrics", prometheus.Handler())
+...
+```
+
+### Client-side
+
+```go
+import "github.com/grpc-ecosystem/go-grpc-prometheus"
+...
+ clientConn, err = grpc.Dial(
+ address,
+ grpc.WithUnaryInterceptor(UnaryClientInterceptor),
+ grpc.WithStreamInterceptor(StreamClientInterceptor)
+ )
+ client = pb_testproto.NewTestServiceClient(clientConn)
+ resp, err := client.PingEmpty(s.ctx, &myservice.Request{Msg: "hello"})
+...
+```
+
+# Metrics
+
+## Labels
+
+All server-side metrics start with `grpc_server` as Prometheus subsystem name. All client-side metrics start with `grpc_client`. Both of them have mirror-concepts. Similarly all methods
+contain the same rich labels:
+
+ * `grpc_service` - the [gRPC service](http://www.grpc.io/docs/#defining-a-service) name, which is the combination of protobuf `package` and
+ the `grpc_service` section name. E.g. for `package = mwitkow.testproto` and
+ `service TestService` the label will be `grpc_service="mwitkow.testproto.TestService"`
+ * `grpc_method` - the name of the method called on the gRPC service. E.g.
+ `grpc_method="Ping"`
+ * `grpc_type` - the gRPC [type of request](http://www.grpc.io/docs/guides/concepts.html#rpc-life-cycle).
+ Differentiating between the two is important especially for latency measurements.
+
+ - `unary` is single request, single response RPC
+ - `client_stream` is a multi-request, single response RPC
+ - `server_stream` is a single request, multi-response RPC
+ - `bidi_stream` is a multi-request, multi-response RPC
+
+
+Additionally for completed RPCs, the following labels are used:
+
+ * `grpc_code` - the human-readable [gRPC status code](https://github.com/grpc/grpc-go/blob/master/codes/codes.go).
+ The list of all statuses is to long, but here are some common ones:
+
+ - `OK` - means the RPC was successful
+ - `IllegalArgument` - RPC contained bad values
+ - `Internal` - server-side error not disclosed to the clients
+
+## Counters
+
+The counters and their up to date documentation is in [server_reporter.go](server_reporter.go) and [client_reporter.go](client_reporter.go)
+the respective Prometheus handler (usually `/metrics`).
+
+For the purpose of this documentation we will only discuss `grpc_server` metrics. The `grpc_client` ones contain mirror concepts.
+
+For simplicity, let's assume we're tracking a single server-side RPC call of [`mwitkow.testproto.TestService`](examples/testproto/test.proto),
+calling the method `PingList`. The call succeeds and returns 20 messages in the stream.
+
+First, immediately after the server receives the call it will increment the
+`grpc_server_started_total` and start the handling time clock (if histograms are enabled).
+
+```jsoniq
+grpc_server_started_total{grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1
+```
+
+Then the user logic gets invoked. It receives one message from the client containing the request
+(it's a `server_stream`):
+
+```jsoniq
+grpc_server_msg_received_total{grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1
+```
+
+The user logic may return an error, or send multiple messages back to the client. In this case, on
+each of the 20 messages sent back, a counter will be incremented:
+
+```jsoniq
+grpc_server_msg_sent_total{grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 20
+```
+
+After the call completes, it's status (`OK` or other [gRPC status code](https://github.com/grpc/grpc-go/blob/master/codes/codes.go))
+and the relevant call labels increment the `grpc_server_handled_total` counter.
+
+```jsoniq
+grpc_server_handled_total{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1
+```
+
+## Histograms
+
+[Prometheus histograms](https://prometheus.io/docs/concepts/metric_types/#histogram) are a great way
+to measure latency distributions of your RPCs. However since it is bad practice to have metrics
+of [high cardinality](https://prometheus.io/docs/practices/instrumentation/#do-not-overuse-labels))
+the latency monitoring metrics are disabled by default. To enable them please call the following
+in your server initialization code:
+
+```jsoniq
+grpc_prometheus.EnableHandlingTimeHistogram()
+```
+
+After the call completes, it's handling time will be recorded in a [Prometheus histogram](https://prometheus.io/docs/concepts/metric_types/#histogram)
+variable `grpc_server_handling_seconds`. It contains three sub-metrics:
+
+ * `grpc_server_handling_seconds_count` - the count of all completed RPCs by status and method
+ * `grpc_server_handling_seconds_sum` - cumulative time of RPCs by status and method, useful for
+ calculating average handling times
+ * `grpc_server_handling_seconds_bucket` - contains the counts of RPCs by status and method in respective
+ handling-time buckets. These buckets can be used by Prometheus to estimate SLAs (see [here](https://prometheus.io/docs/practices/histograms/))
+
+The counter values will look as follows:
+
+```jsoniq
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.005"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.01"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.025"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.05"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.1"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.25"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.5"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="1"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="2.5"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="5"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="10"} 1
+grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="+Inf"} 1
+grpc_server_handling_seconds_sum{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 0.0003866430000000001
+grpc_server_handling_seconds_count{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1
+```
+
+
+## Useful query examples
+
+Prometheus philosophy is to provide the most detailed metrics possible to the monitoring system, and
+let the aggregations be handled there. The verbosity of above metrics make it possible to have that
+flexibility. Here's a couple of useful monitoring queries:
+
+
+### request inbound rate
+```jsoniq
+sum(rate(grpc_server_started_total{job="foo"}[1m])) by (grpc_service)
+```
+For `job="foo"` (common label to differentiate between Prometheus monitoring targets), calculate the
+rate of requests per second (1 minute window) for each gRPC `grpc_service` that the job has. Please note
+how the `grpc_method` is being omitted here: all methods of a given gRPC service will be summed together.
+
+### unary request error rate
+```jsoniq
+sum(rate(grpc_server_handled_total{job="foo",grpc_type="unary",grpc_code!="OK"}[1m])) by (grpc_service)
+```
+For `job="foo"`, calculate the per-`grpc_service` rate of `unary` (1:1) RPCs that failed, i.e. the
+ones that didn't finish with `OK` code.
+
+### unary request error percentage
+```jsoniq
+sum(rate(grpc_server_handled_total{job="foo",grpc_type="unary",grpc_code!="OK"}[1m])) by (grpc_service)
+ /
+sum(rate(grpc_server_started_total{job="foo",grpc_type="unary"}[1m])) by (grpc_service)
+ * 100.0
+```
+For `job="foo"`, calculate the percentage of failed requests by service. It's easy to notice that
+this is a combination of the two above examples. This is an example of a query you would like to
+[alert on](https://prometheus.io/docs/alerting/rules/) in your system for SLA violations, e.g.
+"no more than 1% requests should fail".
+
+### average response stream size
+```jsoniq
+sum(rate(grpc_server_msg_sent_total{job="foo",grpc_type="server_stream"}[10m])) by (grpc_service)
+ /
+sum(rate(grpc_server_started_total{job="foo",grpc_type="server_stream"}[10m])) by (grpc_service)
+```
+For `job="foo"` what is the `grpc_service`-wide `10m` average of messages returned for all `
+server_stream` RPCs. This allows you to track the stream sizes returned by your system, e.g. allows
+you to track when clients started to send "wide" queries that ret
+Note the divisor is the number of started RPCs, in order to account for in-flight requests.
+
+### 99%-tile latency of unary requests
+```jsoniq
+histogram_quantile(0.99,
+ sum(rate(grpc_server_handling_seconds_bucket{job="foo",grpc_type="unary"}[5m])) by (grpc_service,le)
+)
+```
+For `job="foo"`, returns an 99%-tile [quantile estimation](https://prometheus.io/docs/practices/histograms/#quantiles)
+of the handling time of RPCs per service. Please note the `5m` rate, this means that the quantile
+estimation will take samples in a rolling `5m` window. When combined with other quantiles
+(e.g. 50%, 90%), this query gives you tremendous insight into the responsiveness of your system
+(e.g. impact of caching).
+
+### percentage of slow unary queries (>250ms)
+```jsoniq
+100.0 - (
+sum(rate(grpc_server_handling_seconds_bucket{job="foo",grpc_type="unary",le="0.25"}[5m])) by (grpc_service)
+ /
+sum(rate(grpc_server_handling_seconds_count{job="foo",grpc_type="unary"}[5m])) by (grpc_service)
+) * 100.0
+```
+For `job="foo"` calculate the by-`grpc_service` fraction of slow requests that took longer than `0.25`
+seconds. This query is relatively complex, since the Prometheus aggregations use `le` (less or equal)
+buckets, meaning that counting "fast" requests fractions is easier. However, simple maths helps.
+This is an example of a query you would like to alert on in your system for SLA violations,
+e.g. "less than 1% of requests are slower than 250ms".
+
+
+## Status
+
+This code has been used since August 2015 as the basis for monitoring of *production* gRPC micro services at [Improbable](https://improbable.io).
+
+## License
+
+`go-grpc-prometheus` is released under the Apache 2.0 license. See the [LICENSE](LICENSE) file for details.
diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/client.go b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/client.go
new file mode 100644
index 0000000..d9e87b2
--- /dev/null
+++ b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/client.go
@@ -0,0 +1,72 @@
+// Copyright 2016 Michal Witkowski. All Rights Reserved.
+// See LICENSE for licensing terms.
+
+// gRPC Prometheus monitoring interceptors for client-side gRPC.
+
+package grpc_prometheus
+
+import (
+ "io"
+
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+)
+
+// UnaryClientInterceptor is a gRPC client-side interceptor that provides Prometheus monitoring for Unary RPCs.
+func UnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
+ monitor := newClientReporter(Unary, method)
+ monitor.SentMessage()
+ err := invoker(ctx, method, req, reply, cc, opts...)
+ if err != nil {
+ monitor.ReceivedMessage()
+ }
+ monitor.Handled(grpc.Code(err))
+ return err
+}
+
+// StreamServerInterceptor is a gRPC client-side interceptor that provides Prometheus monitoring for Streaming RPCs.
+func StreamClientInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
+ monitor := newClientReporter(clientStreamType(desc), method)
+ clientStream, err := streamer(ctx, desc, cc, method, opts...)
+ if err != nil {
+ monitor.Handled(grpc.Code(err))
+ return nil, err
+ }
+ return &monitoredClientStream{clientStream, monitor}, nil
+}
+
+func clientStreamType(desc *grpc.StreamDesc) grpcType {
+ if desc.ClientStreams && !desc.ServerStreams {
+ return ClientStream
+ } else if !desc.ClientStreams && desc.ServerStreams {
+ return ServerStream
+ }
+ return BidiStream
+}
+
+// monitoredClientStream wraps grpc.ClientStream allowing each Sent/Recv of message to increment counters.
+type monitoredClientStream struct {
+ grpc.ClientStream
+ monitor *clientReporter
+}
+
+func (s *monitoredClientStream) SendMsg(m interface{}) error {
+ err := s.ClientStream.SendMsg(m)
+ if err == nil {
+ s.monitor.SentMessage()
+ }
+ return err
+}
+
+func (s *monitoredClientStream) RecvMsg(m interface{}) error {
+ err := s.ClientStream.RecvMsg(m)
+ if err == nil {
+ s.monitor.ReceivedMessage()
+ } else if err == io.EOF {
+ s.monitor.Handled(codes.OK)
+ } else {
+ s.monitor.Handled(grpc.Code(err))
+ }
+ return err
+}
diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/client_reporter.go b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/client_reporter.go
new file mode 100644
index 0000000..16b7615
--- /dev/null
+++ b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/client_reporter.go
@@ -0,0 +1,111 @@
+// Copyright 2016 Michal Witkowski. All Rights Reserved.
+// See LICENSE for licensing terms.
+
+package grpc_prometheus
+
+import (
+ "time"
+
+ "google.golang.org/grpc/codes"
+
+ prom "github.com/prometheus/client_golang/prometheus"
+)
+
+var (
+ clientStartedCounter = prom.NewCounterVec(
+ prom.CounterOpts{
+ Namespace: "grpc",
+ Subsystem: "client",
+ Name: "started_total",
+ Help: "Total number of RPCs started on the client.",
+ }, []string{"grpc_type", "grpc_service", "grpc_method"})
+
+ clientHandledCounter = prom.NewCounterVec(
+ prom.CounterOpts{
+ Namespace: "grpc",
+ Subsystem: "client",
+ Name: "handled_total",
+ Help: "Total number of RPCs completed by the client, regardless of success or failure.",
+ }, []string{"grpc_type", "grpc_service", "grpc_method", "grpc_code"})
+
+ clientStreamMsgReceived = prom.NewCounterVec(
+ prom.CounterOpts{
+ Namespace: "grpc",
+ Subsystem: "client",
+ Name: "msg_received_total",
+ Help: "Total number of RPC stream messages received by the client.",
+ }, []string{"grpc_type", "grpc_service", "grpc_method"})
+
+ clientStreamMsgSent = prom.NewCounterVec(
+ prom.CounterOpts{
+ Namespace: "grpc",
+ Subsystem: "client",
+ Name: "msg_sent_total",
+ Help: "Total number of gRPC stream messages sent by the client.",
+ }, []string{"grpc_type", "grpc_service", "grpc_method"})
+
+ clientHandledHistogramEnabled = false
+ clientHandledHistogramOpts = prom.HistogramOpts{
+ Namespace: "grpc",
+ Subsystem: "client",
+ Name: "handling_seconds",
+ Help: "Histogram of response latency (seconds) of the gRPC until it is finished by the application.",
+ Buckets: prom.DefBuckets,
+ }
+ clientHandledHistogram *prom.HistogramVec
+)
+
+func init() {
+ prom.MustRegister(clientStartedCounter)
+ prom.MustRegister(clientHandledCounter)
+ prom.MustRegister(clientStreamMsgReceived)
+ prom.MustRegister(clientStreamMsgSent)
+}
+
+// EnableClientHandlingTimeHistogram turns on recording of handling time of RPCs.
+// Histogram metrics can be very expensive for Prometheus to retain and query.
+func EnableClientHandlingTimeHistogram(opts ...HistogramOption) {
+ for _, o := range opts {
+ o(&clientHandledHistogramOpts)
+ }
+ if !clientHandledHistogramEnabled {
+ clientHandledHistogram = prom.NewHistogramVec(
+ clientHandledHistogramOpts,
+ []string{"grpc_type", "grpc_service", "grpc_method"},
+ )
+ prom.Register(clientHandledHistogram)
+ }
+ clientHandledHistogramEnabled = true
+}
+
+type clientReporter struct {
+ rpcType grpcType
+ serviceName string
+ methodName string
+ startTime time.Time
+}
+
+func newClientReporter(rpcType grpcType, fullMethod string) *clientReporter {
+ r := &clientReporter{rpcType: rpcType}
+ if clientHandledHistogramEnabled {
+ r.startTime = time.Now()
+ }
+ r.serviceName, r.methodName = splitMethodName(fullMethod)
+ clientStartedCounter.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
+ return r
+}
+
+func (r *clientReporter) ReceivedMessage() {
+ clientStreamMsgReceived.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
+}
+
+func (r *clientReporter) SentMessage() {
+ clientStreamMsgSent.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
+}
+
+func (r *clientReporter) Handled(code codes.Code) {
+ clientHandledCounter.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName, code.String()).Inc()
+ if clientHandledHistogramEnabled {
+ clientHandledHistogram.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Observe(time.Since(r.startTime).Seconds())
+ }
+}
diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/server.go b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/server.go
new file mode 100644
index 0000000..f85c8c2
--- /dev/null
+++ b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/server.go
@@ -0,0 +1,74 @@
+// Copyright 2016 Michal Witkowski. All Rights Reserved.
+// See LICENSE for licensing terms.
+
+// gRPC Prometheus monitoring interceptors for server-side gRPC.
+
+package grpc_prometheus
+
+import (
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+)
+
+// PreregisterServices takes a gRPC server and pre-initializes all counters to 0.
+// This allows for easier monitoring in Prometheus (no missing metrics), and should be called *after* all services have
+// been registered with the server.
+func Register(server *grpc.Server) {
+ serviceInfo := server.GetServiceInfo()
+ for serviceName, info := range serviceInfo {
+ for _, mInfo := range info.Methods {
+ preRegisterMethod(serviceName, &mInfo)
+ }
+ }
+}
+
+// UnaryServerInterceptor is a gRPC server-side interceptor that provides Prometheus monitoring for Unary RPCs.
+func UnaryServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
+ monitor := newServerReporter(Unary, info.FullMethod)
+ monitor.ReceivedMessage()
+ resp, err := handler(ctx, req)
+ monitor.Handled(grpc.Code(err))
+ if err == nil {
+ monitor.SentMessage()
+ }
+ return resp, err
+}
+
+// StreamServerInterceptor is a gRPC server-side interceptor that provides Prometheus monitoring for Streaming RPCs.
+func StreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
+ monitor := newServerReporter(streamRpcType(info), info.FullMethod)
+ err := handler(srv, &monitoredServerStream{ss, monitor})
+ monitor.Handled(grpc.Code(err))
+ return err
+}
+
+func streamRpcType(info *grpc.StreamServerInfo) grpcType {
+ if info.IsClientStream && !info.IsServerStream {
+ return ClientStream
+ } else if !info.IsClientStream && info.IsServerStream {
+ return ServerStream
+ }
+ return BidiStream
+}
+
+// monitoredStream wraps grpc.ServerStream allowing each Sent/Recv of message to increment counters.
+type monitoredServerStream struct {
+ grpc.ServerStream
+ monitor *serverReporter
+}
+
+func (s *monitoredServerStream) SendMsg(m interface{}) error {
+ err := s.ServerStream.SendMsg(m)
+ if err == nil {
+ s.monitor.SentMessage()
+ }
+ return err
+}
+
+func (s *monitoredServerStream) RecvMsg(m interface{}) error {
+ err := s.ServerStream.RecvMsg(m)
+ if err == nil {
+ s.monitor.ReceivedMessage()
+ }
+ return err
+}
diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/server_reporter.go b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/server_reporter.go
new file mode 100644
index 0000000..628a890
--- /dev/null
+++ b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/server_reporter.go
@@ -0,0 +1,157 @@
+// Copyright 2016 Michal Witkowski. All Rights Reserved.
+// See LICENSE for licensing terms.
+
+package grpc_prometheus
+
+import (
+ "time"
+
+ "google.golang.org/grpc/codes"
+
+ prom "github.com/prometheus/client_golang/prometheus"
+ "google.golang.org/grpc"
+)
+
+type grpcType string
+
+const (
+ Unary grpcType = "unary"
+ ClientStream grpcType = "client_stream"
+ ServerStream grpcType = "server_stream"
+ BidiStream grpcType = "bidi_stream"
+)
+
+var (
+ serverStartedCounter = prom.NewCounterVec(
+ prom.CounterOpts{
+ Namespace: "grpc",
+ Subsystem: "server",
+ Name: "started_total",
+ Help: "Total number of RPCs started on the server.",
+ }, []string{"grpc_type", "grpc_service", "grpc_method"})
+
+ serverHandledCounter = prom.NewCounterVec(
+ prom.CounterOpts{
+ Namespace: "grpc",
+ Subsystem: "server",
+ Name: "handled_total",
+ Help: "Total number of RPCs completed on the server, regardless of success or failure.",
+ }, []string{"grpc_type", "grpc_service", "grpc_method", "grpc_code"})
+
+ serverStreamMsgReceived = prom.NewCounterVec(
+ prom.CounterOpts{
+ Namespace: "grpc",
+ Subsystem: "server",
+ Name: "msg_received_total",
+ Help: "Total number of RPC stream messages received on the server.",
+ }, []string{"grpc_type", "grpc_service", "grpc_method"})
+
+ serverStreamMsgSent = prom.NewCounterVec(
+ prom.CounterOpts{
+ Namespace: "grpc",
+ Subsystem: "server",
+ Name: "msg_sent_total",
+ Help: "Total number of gRPC stream messages sent by the server.",
+ }, []string{"grpc_type", "grpc_service", "grpc_method"})
+
+ serverHandledHistogramEnabled = false
+ serverHandledHistogramOpts = prom.HistogramOpts{
+ Namespace: "grpc",
+ Subsystem: "server",
+ Name: "handling_seconds",
+ Help: "Histogram of response latency (seconds) of gRPC that had been application-level handled by the server.",
+ Buckets: prom.DefBuckets,
+ }
+ serverHandledHistogram *prom.HistogramVec
+)
+
+func init() {
+ prom.MustRegister(serverStartedCounter)
+ prom.MustRegister(serverHandledCounter)
+ prom.MustRegister(serverStreamMsgReceived)
+ prom.MustRegister(serverStreamMsgSent)
+}
+
+type HistogramOption func(*prom.HistogramOpts)
+
+// WithHistogramBuckets allows you to specify custom bucket ranges for histograms if EnableHandlingTimeHistogram is on.
+func WithHistogramBuckets(buckets []float64) HistogramOption {
+ return func(o *prom.HistogramOpts) { o.Buckets = buckets }
+}
+
+// EnableHandlingTimeHistogram turns on recording of handling time of RPCs for server-side interceptors.
+// Histogram metrics can be very expensive for Prometheus to retain and query.
+func EnableHandlingTimeHistogram(opts ...HistogramOption) {
+ for _, o := range opts {
+ o(&serverHandledHistogramOpts)
+ }
+ if !serverHandledHistogramEnabled {
+ serverHandledHistogram = prom.NewHistogramVec(
+ serverHandledHistogramOpts,
+ []string{"grpc_type", "grpc_service", "grpc_method"},
+ )
+ prom.Register(serverHandledHistogram)
+ }
+ serverHandledHistogramEnabled = true
+}
+
+type serverReporter struct {
+ rpcType grpcType
+ serviceName string
+ methodName string
+ startTime time.Time
+}
+
+func newServerReporter(rpcType grpcType, fullMethod string) *serverReporter {
+ r := &serverReporter{rpcType: rpcType}
+ if serverHandledHistogramEnabled {
+ r.startTime = time.Now()
+ }
+ r.serviceName, r.methodName = splitMethodName(fullMethod)
+ serverStartedCounter.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
+ return r
+}
+
+func (r *serverReporter) ReceivedMessage() {
+ serverStreamMsgReceived.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
+}
+
+func (r *serverReporter) SentMessage() {
+ serverStreamMsgSent.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
+}
+
+func (r *serverReporter) Handled(code codes.Code) {
+ serverHandledCounter.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName, code.String()).Inc()
+ if serverHandledHistogramEnabled {
+ serverHandledHistogram.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Observe(time.Since(r.startTime).Seconds())
+ }
+}
+
+// preRegisterMethod is invoked on Register of a Server, allowing all gRPC services labels to be pre-populated.
+func preRegisterMethod(serviceName string, mInfo *grpc.MethodInfo) {
+ methodName := mInfo.Name
+ methodType := string(typeFromMethodInfo(mInfo))
+ // These are just references (no increments), as just referencing will create the labels but not set values.
+ serverStartedCounter.GetMetricWithLabelValues(methodType, serviceName, methodName)
+ serverStreamMsgReceived.GetMetricWithLabelValues(methodType, serviceName, methodName)
+ serverStreamMsgSent.GetMetricWithLabelValues(methodType, serviceName, methodName)
+ if serverHandledHistogramEnabled {
+ serverHandledHistogram.GetMetricWithLabelValues(methodType, serviceName, methodName)
+ }
+ for _, code := range allCodes {
+ serverHandledCounter.GetMetricWithLabelValues(methodType, serviceName, methodName, code.String())
+ }
+}
+
+func typeFromMethodInfo(mInfo *grpc.MethodInfo) grpcType {
+ if mInfo.IsClientStream == false && mInfo.IsServerStream == false {
+ return Unary
+ }
+ if mInfo.IsClientStream == true && mInfo.IsServerStream == false {
+ return ClientStream
+ }
+ if mInfo.IsClientStream == false && mInfo.IsServerStream == true {
+ return ServerStream
+ }
+ return BidiStream
+}
diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/util.go b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/util.go
new file mode 100644
index 0000000..372460a
--- /dev/null
+++ b/vendor/github.com/grpc-ecosystem/go-grpc-prometheus/util.go
@@ -0,0 +1,27 @@
+// Copyright 2016 Michal Witkowski. All Rights Reserved.
+// See LICENSE for licensing terms.
+
+package grpc_prometheus
+
+import (
+ "strings"
+
+ "google.golang.org/grpc/codes"
+)
+
+var (
+ allCodes = []codes.Code{
+ codes.OK, codes.Canceled, codes.Unknown, codes.InvalidArgument, codes.DeadlineExceeded, codes.NotFound,
+ codes.AlreadyExists, codes.PermissionDenied, codes.Unauthenticated, codes.ResourceExhausted,
+ codes.FailedPrecondition, codes.Aborted, codes.OutOfRange, codes.Unimplemented, codes.Internal,
+ codes.Unavailable, codes.DataLoss,
+ }
+)
+
+func splitMethodName(fullMethodName string) (string, string) {
+ fullMethodName = strings.TrimPrefix(fullMethodName, "/") // remove leading slash
+ if i := strings.Index(fullMethodName, "/"); i >= 0 {
+ return fullMethodName[:i], fullMethodName[i+1:]
+ }
+ return "unknown", "unknown"
+}
diff --git a/vendor/github.com/hashicorp/go-immutable-radix/LICENSE b/vendor/github.com/hashicorp/go-immutable-radix/LICENSE
new file mode 100644
index 0000000..e87a115
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-immutable-radix/LICENSE
@@ -0,0 +1,363 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. "Contributor"
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the terms of
+ a Secondary License.
+
+1.6. "Executable Form"
+
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+
+ means a work that combines Covered Software with other material, in a
+ separate file or files, that is not Covered Software.
+
+1.8. "License"
+
+ means this document.
+
+1.9. "Licensable"
+
+ means having the right to grant, to the maximum extent possible, whether
+ at the time of the initial grant or subsequently, any and all of the
+ rights conveyed by this License.
+
+1.10. "Modifications"
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. "Patent Claims" of a Contributor
+
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the License,
+ by the making, using, selling, offering for sale, having made, import,
+ or transfer of either its Contributions or its Contributor Version.
+
+1.12. "Secondary License"
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. "Source Code Form"
+
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, "control" means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution
+ become effective for each Contribution on the date the Contributor first
+ distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under
+ this License. No additional rights or licenses will be implied from the
+ distribution or licensing of Covered Software under this License.
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
+ Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+ This License does not grant any rights in the trademarks, service marks,
+ or logos of any Contributor (except as may be necessary to comply with
+ the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this
+ License (see Section 10.2) or under the terms of a Secondary License (if
+ permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its
+ Contributions are its original creation(s) or it has sufficient rights to
+ grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under
+ applicable copyright doctrines of fair use, fair dealing, or other
+ equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under
+ the terms of this License. You must inform recipients that the Source
+ Code Form of the Covered Software is governed by the terms of this
+ License, and how they can obtain a copy of this License. You may not
+ attempt to alter or restrict the recipients' rights in the Source Code
+ Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter the
+ recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for
+ the Covered Software. If the Larger Work is a combination of Covered
+ Software with a work governed by one or more Secondary Licenses, and the
+ Covered Software is not Incompatible With Secondary Licenses, this
+ License permits You to additionally distribute such Covered Software
+ under the terms of such Secondary License(s), so that the recipient of
+ the Larger Work may, at their option, further distribute the Covered
+ Software under the terms of either this License or such Secondary
+ License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices
+ (including copyright notices, patent notices, disclaimers of warranty, or
+ limitations of liability) contained within the Source Code Form of the
+ Covered Software, except that You may alter any license notices to the
+ extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on
+ behalf of any Contributor. You must make it absolutely clear that any
+ such warranty, support, indemnity, or liability obligation is offered by
+ You alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute,
+ judicial order, or regulation then You must: (a) comply with the terms of
+ this License to the maximum extent possible; and (b) describe the
+ limitations and the code they affect. Such description must be placed in a
+ text file included with all distributions of the Covered Software under
+ this License. Except to the extent prohibited by statute or regulation,
+ such description must be sufficiently detailed for a recipient of ordinary
+ skill to be able to understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing
+ basis, if such Contributor fails to notify You of the non-compliance by
+ some reasonable means prior to 60 days after You have come back into
+ compliance. Moreover, Your grants from a particular Contributor are
+ reinstated on an ongoing basis if such Contributor notifies You of the
+ non-compliance by some reasonable means, this is the first time You have
+ received notice of non-compliance with this License from such
+ Contributor, and You become compliant prior to 30 days after Your receipt
+ of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions,
+ counter-claims, and cross-claims) alleging that a Contributor Version
+ directly or indirectly infringes any patent, then the rights granted to
+ You by any and all Contributors for the Covered Software under Section
+ 2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an "as is" basis,
+ without warranty of any kind, either expressed, implied, or statutory,
+ including, without limitation, warranties that the Covered Software is free
+ of defects, merchantable, fit for a particular purpose or non-infringing.
+ The entire risk as to the quality and performance of the Covered Software
+ is with You. Should any Covered Software prove defective in any respect,
+ You (not any Contributor) assume the cost of any necessary servicing,
+ repair, or correction. This disclaimer of warranty constitutes an essential
+ part of this License. No use of any Covered Software is authorized under
+ this License except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from
+ such party's negligence to the extent applicable law prohibits such
+ limitation. Some jurisdictions do not allow the exclusion or limitation of
+ incidental or consequential damages, so this exclusion and limitation may
+ not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts
+ of a jurisdiction where the defendant maintains its principal place of
+ business and such litigation shall be governed by laws of that
+ jurisdiction, without reference to its conflict-of-law provisions. Nothing
+ in this Section shall prevent a party's ability to bring cross-claims or
+ counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject
+ matter hereof. If any provision of this License is held to be
+ unenforceable, such provision shall be reformed only to the extent
+ necessary to make it enforceable. Any law or regulation which provides that
+ the language of a contract shall be construed against the drafter shall not
+ be used to construe this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version
+ of the License under which You originally received the Covered Software,
+ or under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a
+ modified version of this License if you rename the license and remove
+ any references to the name of the license steward (except to note that
+ such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+ Licenses If You choose to distribute Source Code Form that is
+ Incompatible With Secondary Licenses under the terms of this version of
+ the License, the notice described in Exhibit B of this License must be
+ attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file,
+then You may include the notice in a location (such as a LICENSE file in a
+relevant directory) where a recipient would be likely to look for such a
+notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+
+ This Source Code Form is "Incompatible
+ With Secondary Licenses", as defined by
+ the Mozilla Public License, v. 2.0.
+
diff --git a/vendor/github.com/hashicorp/go-immutable-radix/README.md b/vendor/github.com/hashicorp/go-immutable-radix/README.md
new file mode 100644
index 0000000..8910fcc
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-immutable-radix/README.md
@@ -0,0 +1,41 @@
+go-immutable-radix [![Build Status](https://travis-ci.org/hashicorp/go-immutable-radix.png)](https://travis-ci.org/hashicorp/go-immutable-radix)
+=========
+
+Provides the `iradix` package that implements an immutable [radix tree](http://en.wikipedia.org/wiki/Radix_tree).
+The package only provides a single `Tree` implementation, optimized for sparse nodes.
+
+As a radix tree, it provides the following:
+ * O(k) operations. In many cases, this can be faster than a hash table since
+ the hash function is an O(k) operation, and hash tables have very poor cache locality.
+ * Minimum / Maximum value lookups
+ * Ordered iteration
+
+A tree supports using a transaction to batch multiple updates (insert, delete)
+in a more efficient manner than performing each operation one at a time.
+
+For a mutable variant, see [go-radix](https://github.com/armon/go-radix).
+
+Documentation
+=============
+
+The full documentation is available on [Godoc](http://godoc.org/github.com/hashicorp/go-immutable-radix).
+
+Example
+=======
+
+Below is a simple example of usage
+
+```go
+// Create a tree
+r := iradix.New()
+r, _, _ = r.Insert([]byte("foo"), 1)
+r, _, _ = r.Insert([]byte("bar"), 2)
+r, _, _ = r.Insert([]byte("foobar"), 2)
+
+// Find the longest prefix match
+m, _, _ := r.Root().LongestPrefix([]byte("foozip"))
+if string(m) != "foo" {
+ panic("should be foo")
+}
+```
+
diff --git a/vendor/github.com/hashicorp/go-immutable-radix/edges.go b/vendor/github.com/hashicorp/go-immutable-radix/edges.go
new file mode 100644
index 0000000..a636747
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-immutable-radix/edges.go
@@ -0,0 +1,21 @@
+package iradix
+
+import "sort"
+
+type edges []edge
+
+func (e edges) Len() int {
+ return len(e)
+}
+
+func (e edges) Less(i, j int) bool {
+ return e[i].label < e[j].label
+}
+
+func (e edges) Swap(i, j int) {
+ e[i], e[j] = e[j], e[i]
+}
+
+func (e edges) Sort() {
+ sort.Sort(e)
+}
diff --git a/vendor/github.com/hashicorp/go-immutable-radix/iradix.go b/vendor/github.com/hashicorp/go-immutable-radix/iradix.go
new file mode 100644
index 0000000..b255583
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-immutable-radix/iradix.go
@@ -0,0 +1,333 @@
+package iradix
+
+import (
+ "bytes"
+
+ "github.com/hashicorp/golang-lru/simplelru"
+)
+
+const (
+ // defaultModifiedCache is the default size of the modified node
+ // cache used per transaction. This is used to cache the updates
+ // to the nodes near the root, while the leaves do not need to be
+ // cached. This is important for very large transactions to prevent
+ // the modified cache from growing to be enormous.
+ defaultModifiedCache = 8192
+)
+
+// Tree implements an immutable radix tree. This can be treated as a
+// Dictionary abstract data type. The main advantage over a standard
+// hash map is prefix-based lookups and ordered iteration. The immutability
+// means that it is safe to concurrently read from a Tree without any
+// coordination.
+type Tree struct {
+ root *Node
+ size int
+}
+
+// New returns an empty Tree
+func New() *Tree {
+ t := &Tree{root: &Node{}}
+ return t
+}
+
+// Len is used to return the number of elements in the tree
+func (t *Tree) Len() int {
+ return t.size
+}
+
+// Txn is a transaction on the tree. This transaction is applied
+// atomically and returns a new tree when committed. A transaction
+// is not thread safe, and should only be used by a single goroutine.
+type Txn struct {
+ root *Node
+ size int
+ modified *simplelru.LRU
+}
+
+// Txn starts a new transaction that can be used to mutate the tree
+func (t *Tree) Txn() *Txn {
+ txn := &Txn{
+ root: t.root,
+ size: t.size,
+ }
+ return txn
+}
+
+// writeNode returns a node to be modified, if the current
+// node as already been modified during the course of
+// the transaction, it is used in-place.
+func (t *Txn) writeNode(n *Node) *Node {
+ // Ensure the modified set exists
+ if t.modified == nil {
+ lru, err := simplelru.NewLRU(defaultModifiedCache, nil)
+ if err != nil {
+ panic(err)
+ }
+ t.modified = lru
+ }
+
+ // If this node has already been modified, we can
+ // continue to use it during this transaction.
+ if _, ok := t.modified.Get(n); ok {
+ return n
+ }
+
+ // Copy the existing node
+ nc := new(Node)
+ if n.prefix != nil {
+ nc.prefix = make([]byte, len(n.prefix))
+ copy(nc.prefix, n.prefix)
+ }
+ if n.leaf != nil {
+ nc.leaf = new(leafNode)
+ *nc.leaf = *n.leaf
+ }
+ if len(n.edges) != 0 {
+ nc.edges = make([]edge, len(n.edges))
+ copy(nc.edges, n.edges)
+ }
+
+ // Mark this node as modified
+ t.modified.Add(n, nil)
+ return nc
+}
+
+// insert does a recursive insertion
+func (t *Txn) insert(n *Node, k, search []byte, v interface{}) (*Node, interface{}, bool) {
+ // Handle key exhaution
+ if len(search) == 0 {
+ nc := t.writeNode(n)
+ if n.isLeaf() {
+ old := nc.leaf.val
+ nc.leaf.val = v
+ return nc, old, true
+ } else {
+ nc.leaf = &leafNode{
+ key: k,
+ val: v,
+ }
+ return nc, nil, false
+ }
+ }
+
+ // Look for the edge
+ idx, child := n.getEdge(search[0])
+
+ // No edge, create one
+ if child == nil {
+ e := edge{
+ label: search[0],
+ node: &Node{
+ leaf: &leafNode{
+ key: k,
+ val: v,
+ },
+ prefix: search,
+ },
+ }
+ nc := t.writeNode(n)
+ nc.addEdge(e)
+ return nc, nil, false
+ }
+
+ // Determine longest prefix of the search key on match
+ commonPrefix := longestPrefix(search, child.prefix)
+ if commonPrefix == len(child.prefix) {
+ search = search[commonPrefix:]
+ newChild, oldVal, didUpdate := t.insert(child, k, search, v)
+ if newChild != nil {
+ nc := t.writeNode(n)
+ nc.edges[idx].node = newChild
+ return nc, oldVal, didUpdate
+ }
+ return nil, oldVal, didUpdate
+ }
+
+ // Split the node
+ nc := t.writeNode(n)
+ splitNode := &Node{
+ prefix: search[:commonPrefix],
+ }
+ nc.replaceEdge(edge{
+ label: search[0],
+ node: splitNode,
+ })
+
+ // Restore the existing child node
+ modChild := t.writeNode(child)
+ splitNode.addEdge(edge{
+ label: modChild.prefix[commonPrefix],
+ node: modChild,
+ })
+ modChild.prefix = modChild.prefix[commonPrefix:]
+
+ // Create a new leaf node
+ leaf := &leafNode{
+ key: k,
+ val: v,
+ }
+
+ // If the new key is a subset, add to to this node
+ search = search[commonPrefix:]
+ if len(search) == 0 {
+ splitNode.leaf = leaf
+ return nc, nil, false
+ }
+
+ // Create a new edge for the node
+ splitNode.addEdge(edge{
+ label: search[0],
+ node: &Node{
+ leaf: leaf,
+ prefix: search,
+ },
+ })
+ return nc, nil, false
+}
+
+// delete does a recursive deletion
+func (t *Txn) delete(parent, n *Node, search []byte) (*Node, *leafNode) {
+ // Check for key exhaution
+ if len(search) == 0 {
+ if !n.isLeaf() {
+ return nil, nil
+ }
+
+ // Remove the leaf node
+ nc := t.writeNode(n)
+ nc.leaf = nil
+
+ // Check if this node should be merged
+ if n != t.root && len(nc.edges) == 1 {
+ nc.mergeChild()
+ }
+ return nc, n.leaf
+ }
+
+ // Look for an edge
+ label := search[0]
+ idx, child := n.getEdge(label)
+ if child == nil || !bytes.HasPrefix(search, child.prefix) {
+ return nil, nil
+ }
+
+ // Consume the search prefix
+ search = search[len(child.prefix):]
+ newChild, leaf := t.delete(n, child, search)
+ if newChild == nil {
+ return nil, nil
+ }
+
+ // Copy this node
+ nc := t.writeNode(n)
+
+ // Delete the edge if the node has no edges
+ if newChild.leaf == nil && len(newChild.edges) == 0 {
+ nc.delEdge(label)
+ if n != t.root && len(nc.edges) == 1 && !nc.isLeaf() {
+ nc.mergeChild()
+ }
+ } else {
+ nc.edges[idx].node = newChild
+ }
+ return nc, leaf
+}
+
+// Insert is used to add or update a given key. The return provides
+// the previous value and a bool indicating if any was set.
+func (t *Txn) Insert(k []byte, v interface{}) (interface{}, bool) {
+ newRoot, oldVal, didUpdate := t.insert(t.root, k, k, v)
+ if newRoot != nil {
+ t.root = newRoot
+ }
+ if !didUpdate {
+ t.size++
+ }
+ return oldVal, didUpdate
+}
+
+// Delete is used to delete a given key. Returns the old value if any,
+// and a bool indicating if the key was set.
+func (t *Txn) Delete(k []byte) (interface{}, bool) {
+ newRoot, leaf := t.delete(nil, t.root, k)
+ if newRoot != nil {
+ t.root = newRoot
+ }
+ if leaf != nil {
+ t.size--
+ return leaf.val, true
+ }
+ return nil, false
+}
+
+// Root returns the current root of the radix tree within this
+// transaction. The root is not safe across insert and delete operations,
+// but can be used to read the current state during a transaction.
+func (t *Txn) Root() *Node {
+ return t.root
+}
+
+// Get is used to lookup a specific key, returning
+// the value and if it was found
+func (t *Txn) Get(k []byte) (interface{}, bool) {
+ return t.root.Get(k)
+}
+
+// Commit is used to finalize the transaction and return a new tree
+func (t *Txn) Commit() *Tree {
+ t.modified = nil
+ return &Tree{t.root, t.size}
+}
+
+// Insert is used to add or update a given key. The return provides
+// the new tree, previous value and a bool indicating if any was set.
+func (t *Tree) Insert(k []byte, v interface{}) (*Tree, interface{}, bool) {
+ txn := t.Txn()
+ old, ok := txn.Insert(k, v)
+ return txn.Commit(), old, ok
+}
+
+// Delete is used to delete a given key. Returns the new tree,
+// old value if any, and a bool indicating if the key was set.
+func (t *Tree) Delete(k []byte) (*Tree, interface{}, bool) {
+ txn := t.Txn()
+ old, ok := txn.Delete(k)
+ return txn.Commit(), old, ok
+}
+
+// Root returns the root node of the tree which can be used for richer
+// query operations.
+func (t *Tree) Root() *Node {
+ return t.root
+}
+
+// Get is used to lookup a specific key, returning
+// the value and if it was found
+func (t *Tree) Get(k []byte) (interface{}, bool) {
+ return t.root.Get(k)
+}
+
+// longestPrefix finds the length of the shared prefix
+// of two strings
+func longestPrefix(k1, k2 []byte) int {
+ max := len(k1)
+ if l := len(k2); l < max {
+ max = l
+ }
+ var i int
+ for i = 0; i < max; i++ {
+ if k1[i] != k2[i] {
+ break
+ }
+ }
+ return i
+}
+
+// concat two byte slices, returning a third new copy
+func concat(a, b []byte) []byte {
+ c := make([]byte, len(a)+len(b))
+ copy(c, a)
+ copy(c[len(a):], b)
+ return c
+}
diff --git a/vendor/github.com/hashicorp/go-immutable-radix/iter.go b/vendor/github.com/hashicorp/go-immutable-radix/iter.go
new file mode 100644
index 0000000..75cbaa1
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-immutable-radix/iter.go
@@ -0,0 +1,81 @@
+package iradix
+
+import "bytes"
+
+// Iterator is used to iterate over a set of nodes
+// in pre-order
+type Iterator struct {
+ node *Node
+ stack []edges
+}
+
+// SeekPrefix is used to seek the iterator to a given prefix
+func (i *Iterator) SeekPrefix(prefix []byte) {
+ // Wipe the stack
+ i.stack = nil
+ n := i.node
+ search := prefix
+ for {
+ // Check for key exhaution
+ if len(search) == 0 {
+ i.node = n
+ return
+ }
+
+ // Look for an edge
+ _, n = n.getEdge(search[0])
+ if n == nil {
+ i.node = nil
+ return
+ }
+
+ // Consume the search prefix
+ if bytes.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+
+ } else if bytes.HasPrefix(n.prefix, search) {
+ i.node = n
+ return
+ } else {
+ i.node = nil
+ return
+ }
+ }
+}
+
+// Next returns the next node in order
+func (i *Iterator) Next() ([]byte, interface{}, bool) {
+ // Initialize our stack if needed
+ if i.stack == nil && i.node != nil {
+ i.stack = []edges{
+ edges{
+ edge{node: i.node},
+ },
+ }
+ }
+
+ for len(i.stack) > 0 {
+ // Inspect the last element of the stack
+ n := len(i.stack)
+ last := i.stack[n-1]
+ elem := last[0].node
+
+ // Update the stack
+ if len(last) > 1 {
+ i.stack[n-1] = last[1:]
+ } else {
+ i.stack = i.stack[:n-1]
+ }
+
+ // Push the edges onto the frontier
+ if len(elem.edges) > 0 {
+ i.stack = append(i.stack, elem.edges)
+ }
+
+ // Return the leaf values if any
+ if elem.leaf != nil {
+ return elem.leaf.key, elem.leaf.val, true
+ }
+ }
+ return nil, nil, false
+}
diff --git a/vendor/github.com/hashicorp/go-immutable-radix/node.go b/vendor/github.com/hashicorp/go-immutable-radix/node.go
new file mode 100644
index 0000000..fea6f63
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-immutable-radix/node.go
@@ -0,0 +1,289 @@
+package iradix
+
+import (
+ "bytes"
+ "sort"
+)
+
+// WalkFn is used when walking the tree. Takes a
+// key and value, returning if iteration should
+// be terminated.
+type WalkFn func(k []byte, v interface{}) bool
+
+// leafNode is used to represent a value
+type leafNode struct {
+ key []byte
+ val interface{}
+}
+
+// edge is used to represent an edge node
+type edge struct {
+ label byte
+ node *Node
+}
+
+// Node is an immutable node in the radix tree
+type Node struct {
+ // leaf is used to store possible leaf
+ leaf *leafNode
+
+ // prefix is the common prefix we ignore
+ prefix []byte
+
+ // Edges should be stored in-order for iteration.
+ // We avoid a fully materialized slice to save memory,
+ // since in most cases we expect to be sparse
+ edges edges
+}
+
+func (n *Node) isLeaf() bool {
+ return n.leaf != nil
+}
+
+func (n *Node) addEdge(e edge) {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= e.label
+ })
+ n.edges = append(n.edges, e)
+ if idx != num {
+ copy(n.edges[idx+1:], n.edges[idx:num])
+ n.edges[idx] = e
+ }
+}
+
+func (n *Node) replaceEdge(e edge) {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= e.label
+ })
+ if idx < num && n.edges[idx].label == e.label {
+ n.edges[idx].node = e.node
+ return
+ }
+ panic("replacing missing edge")
+}
+
+func (n *Node) getEdge(label byte) (int, *Node) {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= label
+ })
+ if idx < num && n.edges[idx].label == label {
+ return idx, n.edges[idx].node
+ }
+ return -1, nil
+}
+
+func (n *Node) delEdge(label byte) {
+ num := len(n.edges)
+ idx := sort.Search(num, func(i int) bool {
+ return n.edges[i].label >= label
+ })
+ if idx < num && n.edges[idx].label == label {
+ copy(n.edges[idx:], n.edges[idx+1:])
+ n.edges[len(n.edges)-1] = edge{}
+ n.edges = n.edges[:len(n.edges)-1]
+ }
+}
+
+func (n *Node) mergeChild() {
+ e := n.edges[0]
+ child := e.node
+ n.prefix = concat(n.prefix, child.prefix)
+ if child.leaf != nil {
+ n.leaf = new(leafNode)
+ *n.leaf = *child.leaf
+ } else {
+ n.leaf = nil
+ }
+ if len(child.edges) != 0 {
+ n.edges = make([]edge, len(child.edges))
+ copy(n.edges, child.edges)
+ } else {
+ n.edges = nil
+ }
+}
+
+func (n *Node) Get(k []byte) (interface{}, bool) {
+ search := k
+ for {
+ // Check for key exhaution
+ if len(search) == 0 {
+ if n.isLeaf() {
+ return n.leaf.val, true
+ }
+ break
+ }
+
+ // Look for an edge
+ _, n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Consume the search prefix
+ if bytes.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+ } else {
+ break
+ }
+ }
+ return nil, false
+}
+
+// LongestPrefix is like Get, but instead of an
+// exact match, it will return the longest prefix match.
+func (n *Node) LongestPrefix(k []byte) ([]byte, interface{}, bool) {
+ var last *leafNode
+ search := k
+ for {
+ // Look for a leaf node
+ if n.isLeaf() {
+ last = n.leaf
+ }
+
+ // Check for key exhaution
+ if len(search) == 0 {
+ break
+ }
+
+ // Look for an edge
+ _, n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Consume the search prefix
+ if bytes.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+ } else {
+ break
+ }
+ }
+ if last != nil {
+ return last.key, last.val, true
+ }
+ return nil, nil, false
+}
+
+// Minimum is used to return the minimum value in the tree
+func (n *Node) Minimum() ([]byte, interface{}, bool) {
+ for {
+ if n.isLeaf() {
+ return n.leaf.key, n.leaf.val, true
+ }
+ if len(n.edges) > 0 {
+ n = n.edges[0].node
+ } else {
+ break
+ }
+ }
+ return nil, nil, false
+}
+
+// Maximum is used to return the maximum value in the tree
+func (n *Node) Maximum() ([]byte, interface{}, bool) {
+ for {
+ if num := len(n.edges); num > 0 {
+ n = n.edges[num-1].node
+ continue
+ }
+ if n.isLeaf() {
+ return n.leaf.key, n.leaf.val, true
+ } else {
+ break
+ }
+ }
+ return nil, nil, false
+}
+
+// Iterator is used to return an iterator at
+// the given node to walk the tree
+func (n *Node) Iterator() *Iterator {
+ return &Iterator{node: n}
+}
+
+// Walk is used to walk the tree
+func (n *Node) Walk(fn WalkFn) {
+ recursiveWalk(n, fn)
+}
+
+// WalkPrefix is used to walk the tree under a prefix
+func (n *Node) WalkPrefix(prefix []byte, fn WalkFn) {
+ search := prefix
+ for {
+ // Check for key exhaution
+ if len(search) == 0 {
+ recursiveWalk(n, fn)
+ return
+ }
+
+ // Look for an edge
+ _, n = n.getEdge(search[0])
+ if n == nil {
+ break
+ }
+
+ // Consume the search prefix
+ if bytes.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+
+ } else if bytes.HasPrefix(n.prefix, search) {
+ // Child may be under our search prefix
+ recursiveWalk(n, fn)
+ return
+ } else {
+ break
+ }
+ }
+}
+
+// WalkPath is used to walk the tree, but only visiting nodes
+// from the root down to a given leaf. Where WalkPrefix walks
+// all the entries *under* the given prefix, this walks the
+// entries *above* the given prefix.
+func (n *Node) WalkPath(path []byte, fn WalkFn) {
+ search := path
+ for {
+ // Visit the leaf values if any
+ if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
+ return
+ }
+
+ // Check for key exhaution
+ if len(search) == 0 {
+ return
+ }
+
+ // Look for an edge
+ _, n = n.getEdge(search[0])
+ if n == nil {
+ return
+ }
+
+ // Consume the search prefix
+ if bytes.HasPrefix(search, n.prefix) {
+ search = search[len(n.prefix):]
+ } else {
+ break
+ }
+ }
+}
+
+// recursiveWalk is used to do a pre-order walk of a node
+// recursively. Returns true if the walk should be aborted
+func recursiveWalk(n *Node, fn WalkFn) bool {
+ // Visit the leaf values if any
+ if n.leaf != nil && fn(n.leaf.key, n.leaf.val) {
+ return true
+ }
+
+ // Recurse on the children
+ for _, e := range n.edges {
+ if recursiveWalk(e.node, fn) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/vendor/github.com/hashicorp/go-memdb/LICENSE b/vendor/github.com/hashicorp/go-memdb/LICENSE
new file mode 100644
index 0000000..e87a115
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-memdb/LICENSE
@@ -0,0 +1,363 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. "Contributor"
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the terms of
+ a Secondary License.
+
+1.6. "Executable Form"
+
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+
+ means a work that combines Covered Software with other material, in a
+ separate file or files, that is not Covered Software.
+
+1.8. "License"
+
+ means this document.
+
+1.9. "Licensable"
+
+ means having the right to grant, to the maximum extent possible, whether
+ at the time of the initial grant or subsequently, any and all of the
+ rights conveyed by this License.
+
+1.10. "Modifications"
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. "Patent Claims" of a Contributor
+
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the License,
+ by the making, using, selling, offering for sale, having made, import,
+ or transfer of either its Contributions or its Contributor Version.
+
+1.12. "Secondary License"
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. "Source Code Form"
+
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, "control" means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution
+ become effective for each Contribution on the date the Contributor first
+ distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under
+ this License. No additional rights or licenses will be implied from the
+ distribution or licensing of Covered Software under this License.
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
+ Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+ This License does not grant any rights in the trademarks, service marks,
+ or logos of any Contributor (except as may be necessary to comply with
+ the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this
+ License (see Section 10.2) or under the terms of a Secondary License (if
+ permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its
+ Contributions are its original creation(s) or it has sufficient rights to
+ grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under
+ applicable copyright doctrines of fair use, fair dealing, or other
+ equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under
+ the terms of this License. You must inform recipients that the Source
+ Code Form of the Covered Software is governed by the terms of this
+ License, and how they can obtain a copy of this License. You may not
+ attempt to alter or restrict the recipients' rights in the Source Code
+ Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter the
+ recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for
+ the Covered Software. If the Larger Work is a combination of Covered
+ Software with a work governed by one or more Secondary Licenses, and the
+ Covered Software is not Incompatible With Secondary Licenses, this
+ License permits You to additionally distribute such Covered Software
+ under the terms of such Secondary License(s), so that the recipient of
+ the Larger Work may, at their option, further distribute the Covered
+ Software under the terms of either this License or such Secondary
+ License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices
+ (including copyright notices, patent notices, disclaimers of warranty, or
+ limitations of liability) contained within the Source Code Form of the
+ Covered Software, except that You may alter any license notices to the
+ extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on
+ behalf of any Contributor. You must make it absolutely clear that any
+ such warranty, support, indemnity, or liability obligation is offered by
+ You alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute,
+ judicial order, or regulation then You must: (a) comply with the terms of
+ this License to the maximum extent possible; and (b) describe the
+ limitations and the code they affect. Such description must be placed in a
+ text file included with all distributions of the Covered Software under
+ this License. Except to the extent prohibited by statute or regulation,
+ such description must be sufficiently detailed for a recipient of ordinary
+ skill to be able to understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing
+ basis, if such Contributor fails to notify You of the non-compliance by
+ some reasonable means prior to 60 days after You have come back into
+ compliance. Moreover, Your grants from a particular Contributor are
+ reinstated on an ongoing basis if such Contributor notifies You of the
+ non-compliance by some reasonable means, this is the first time You have
+ received notice of non-compliance with this License from such
+ Contributor, and You become compliant prior to 30 days after Your receipt
+ of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions,
+ counter-claims, and cross-claims) alleging that a Contributor Version
+ directly or indirectly infringes any patent, then the rights granted to
+ You by any and all Contributors for the Covered Software under Section
+ 2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an "as is" basis,
+ without warranty of any kind, either expressed, implied, or statutory,
+ including, without limitation, warranties that the Covered Software is free
+ of defects, merchantable, fit for a particular purpose or non-infringing.
+ The entire risk as to the quality and performance of the Covered Software
+ is with You. Should any Covered Software prove defective in any respect,
+ You (not any Contributor) assume the cost of any necessary servicing,
+ repair, or correction. This disclaimer of warranty constitutes an essential
+ part of this License. No use of any Covered Software is authorized under
+ this License except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from
+ such party's negligence to the extent applicable law prohibits such
+ limitation. Some jurisdictions do not allow the exclusion or limitation of
+ incidental or consequential damages, so this exclusion and limitation may
+ not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts
+ of a jurisdiction where the defendant maintains its principal place of
+ business and such litigation shall be governed by laws of that
+ jurisdiction, without reference to its conflict-of-law provisions. Nothing
+ in this Section shall prevent a party's ability to bring cross-claims or
+ counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject
+ matter hereof. If any provision of this License is held to be
+ unenforceable, such provision shall be reformed only to the extent
+ necessary to make it enforceable. Any law or regulation which provides that
+ the language of a contract shall be construed against the drafter shall not
+ be used to construe this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version
+ of the License under which You originally received the Covered Software,
+ or under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a
+ modified version of this License if you rename the license and remove
+ any references to the name of the license steward (except to note that
+ such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+ Licenses If You choose to distribute Source Code Form that is
+ Incompatible With Secondary Licenses under the terms of this version of
+ the License, the notice described in Exhibit B of this License must be
+ attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file,
+then You may include the notice in a location (such as a LICENSE file in a
+relevant directory) where a recipient would be likely to look for such a
+notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+
+ This Source Code Form is "Incompatible
+ With Secondary Licenses", as defined by
+ the Mozilla Public License, v. 2.0.
+
diff --git a/vendor/github.com/hashicorp/go-memdb/README.md b/vendor/github.com/hashicorp/go-memdb/README.md
new file mode 100644
index 0000000..203a0af
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-memdb/README.md
@@ -0,0 +1,93 @@
+# go-memdb
+
+Provides the `memdb` package that implements a simple in-memory database
+built on immutable radix trees. The database provides Atomicity, Consistency
+and Isolation from ACID. Being that it is in-memory, it does not provide durability.
+The database is instantiated with a schema that specifies the tables and indicies
+that exist and allows transactions to be executed.
+
+The database provides the following:
+
+* Multi-Version Concurrency Control (MVCC) - By leveraging immutable radix trees
+ the database is able to support any number of concurrent readers without locking,
+ and allows a writer to make progress.
+
+* Transaction Support - The database allows for rich transactions, in which multiple
+ objects are inserted, updated or deleted. The transactions can span multiple tables,
+ and are applied atomically. The database provides atomicity and isolation in ACID
+ terminology, such that until commit the updates are not visible.
+
+* Rich Indexing - Tables can support any number of indexes, which can be simple like
+ a single field index, or more advanced compound field indexes. Certain types like
+ UUID can be efficiently compressed from strings into byte indexes for reduces
+ storage requirements.
+
+For the underlying immutable radix trees, see [go-immutable-radix](https://github.com/hashicorp/go-immutable-radix).
+
+Documentation
+=============
+
+The full documentation is available on [Godoc](http://godoc.org/github.com/hashicorp/go-memdb).
+
+Example
+=======
+
+Below is a simple example of usage
+
+```go
+// Create a sample struct
+type Person struct {
+ Email string
+ Name string
+ Age int
+}
+
+// Create the DB schema
+schema := &memdb.DBSchema{
+ Tables: map[string]*memdb.TableSchema{
+ "person": &memdb.TableSchema{
+ Name: "person",
+ Indexes: map[string]*memdb.IndexSchema{
+ "id": &memdb.IndexSchema{
+ Name: "id",
+ Unique: true,
+ Indexer: &memdb.StringFieldIndex{Field: "Email"},
+ },
+ },
+ },
+ },
+}
+
+// Create a new data base
+db, err := memdb.NewMemDB(schema)
+if err != nil {
+ panic(err)
+}
+
+// Create a write transaction
+txn := db.Txn(true)
+
+// Insert a new person
+p := &Person{"joe@aol.com", "Joe", 30}
+if err := txn.Insert("person", p); err != nil {
+ panic(err)
+}
+
+// Commit the transaction
+txn.Commit()
+
+// Create read-only transaction
+txn = db.Txn(false)
+defer txn.Abort()
+
+// Lookup by email
+raw, err := txn.First("person", "id", "joe@aol.com")
+if err != nil {
+ panic(err)
+}
+
+// Say hi!
+fmt.Printf("Hello %s!", raw.(*Person).Name)
+
+```
+
diff --git a/vendor/github.com/hashicorp/go-memdb/index.go b/vendor/github.com/hashicorp/go-memdb/index.go
new file mode 100644
index 0000000..9f4c7d6
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-memdb/index.go
@@ -0,0 +1,419 @@
+package memdb
+
+import (
+ "encoding/hex"
+ "fmt"
+ "reflect"
+ "strings"
+)
+
+// Indexer is an interface used for defining indexes
+type Indexer interface {
+ // ExactFromArgs is used to build an exact index lookup
+ // based on arguments
+ FromArgs(args ...interface{}) ([]byte, error)
+}
+
+// SingleIndexer is an interface used for defining indexes
+// generating a single entry per object
+type SingleIndexer interface {
+ // FromObject is used to extract an index value from an
+ // object or to indicate that the index value is missing.
+ FromObject(raw interface{}) (bool, []byte, error)
+}
+
+// MultiIndexer is an interface used for defining indexes
+// generating multiple entries per object
+type MultiIndexer interface {
+ // FromObject is used to extract index values from an
+ // object or to indicate that the index value is missing.
+ FromObject(raw interface{}) (bool, [][]byte, error)
+}
+
+// PrefixIndexer can optionally be implemented for any
+// indexes that support prefix based iteration. This may
+// not apply to all indexes.
+type PrefixIndexer interface {
+ // PrefixFromArgs returns a prefix that should be used
+ // for scanning based on the arguments
+ PrefixFromArgs(args ...interface{}) ([]byte, error)
+}
+
+// StringFieldIndex is used to extract a field from an object
+// using reflection and builds an index on that field.
+type StringFieldIndex struct {
+ Field string
+ Lowercase bool
+}
+
+func (s *StringFieldIndex) FromObject(obj interface{}) (bool, []byte, error) {
+ v := reflect.ValueOf(obj)
+ v = reflect.Indirect(v) // Dereference the pointer if any
+
+ fv := v.FieldByName(s.Field)
+ if !fv.IsValid() {
+ return false, nil,
+ fmt.Errorf("field '%s' for %#v is invalid", s.Field, obj)
+ }
+
+ val := fv.String()
+ if val == "" {
+ return false, nil, nil
+ }
+
+ if s.Lowercase {
+ val = strings.ToLower(val)
+ }
+
+ // Add the null character as a terminator
+ val += "\x00"
+ return true, []byte(val), nil
+}
+
+func (s *StringFieldIndex) FromArgs(args ...interface{}) ([]byte, error) {
+ if len(args) != 1 {
+ return nil, fmt.Errorf("must provide only a single argument")
+ }
+ arg, ok := args[0].(string)
+ if !ok {
+ return nil, fmt.Errorf("argument must be a string: %#v", args[0])
+ }
+ if s.Lowercase {
+ arg = strings.ToLower(arg)
+ }
+ // Add the null character as a terminator
+ arg += "\x00"
+ return []byte(arg), nil
+}
+
+func (s *StringFieldIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ val, err := s.FromArgs(args...)
+ if err != nil {
+ return nil, err
+ }
+
+ // Strip the null terminator, the rest is a prefix
+ n := len(val)
+ if n > 0 {
+ return val[:n-1], nil
+ }
+ return val, nil
+}
+
+// StringSliceFieldIndex is used to extract a field from an object
+// using reflection and builds an index on that field.
+type StringSliceFieldIndex struct {
+ Field string
+ Lowercase bool
+}
+
+func (s *StringSliceFieldIndex) FromObject(obj interface{}) (bool, [][]byte, error) {
+ v := reflect.ValueOf(obj)
+ v = reflect.Indirect(v) // Dereference the pointer if any
+
+ fv := v.FieldByName(s.Field)
+ if !fv.IsValid() {
+ return false, nil,
+ fmt.Errorf("field '%s' for %#v is invalid", s.Field, obj)
+ }
+
+ if fv.Kind() != reflect.Slice || fv.Type().Elem().Kind() != reflect.String {
+ return false, nil, fmt.Errorf("field '%s' is not a string slice", s.Field)
+ }
+
+ length := fv.Len()
+ vals := make([][]byte, 0, length)
+ for i := 0; i < fv.Len(); i++ {
+ val := fv.Index(i).String()
+ if val == "" {
+ continue
+ }
+
+ if s.Lowercase {
+ val = strings.ToLower(val)
+ }
+
+ // Add the null character as a terminator
+ val += "\x00"
+ vals = append(vals, []byte(val))
+ }
+ if len(vals) == 0 {
+ return false, nil, nil
+ }
+ return true, vals, nil
+}
+
+func (s *StringSliceFieldIndex) FromArgs(args ...interface{}) ([]byte, error) {
+ if len(args) != 1 {
+ return nil, fmt.Errorf("must provide only a single argument")
+ }
+ arg, ok := args[0].(string)
+ if !ok {
+ return nil, fmt.Errorf("argument must be a string: %#v", args[0])
+ }
+ if s.Lowercase {
+ arg = strings.ToLower(arg)
+ }
+ // Add the null character as a terminator
+ arg += "\x00"
+ return []byte(arg), nil
+}
+
+func (s *StringSliceFieldIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ val, err := s.FromArgs(args...)
+ if err != nil {
+ return nil, err
+ }
+
+ // Strip the null terminator, the rest is a prefix
+ n := len(val)
+ if n > 0 {
+ return val[:n-1], nil
+ }
+ return val, nil
+}
+
+// UUIDFieldIndex is used to extract a field from an object
+// using reflection and builds an index on that field by treating
+// it as a UUID. This is an optimization to using a StringFieldIndex
+// as the UUID can be more compactly represented in byte form.
+type UUIDFieldIndex struct {
+ Field string
+}
+
+func (u *UUIDFieldIndex) FromObject(obj interface{}) (bool, []byte, error) {
+ v := reflect.ValueOf(obj)
+ v = reflect.Indirect(v) // Dereference the pointer if any
+
+ fv := v.FieldByName(u.Field)
+ if !fv.IsValid() {
+ return false, nil,
+ fmt.Errorf("field '%s' for %#v is invalid", u.Field, obj)
+ }
+
+ val := fv.String()
+ if val == "" {
+ return false, nil, nil
+ }
+
+ buf, err := u.parseString(val, true)
+ return true, buf, err
+}
+
+func (u *UUIDFieldIndex) FromArgs(args ...interface{}) ([]byte, error) {
+ if len(args) != 1 {
+ return nil, fmt.Errorf("must provide only a single argument")
+ }
+ switch arg := args[0].(type) {
+ case string:
+ return u.parseString(arg, true)
+ case []byte:
+ if len(arg) != 16 {
+ return nil, fmt.Errorf("byte slice must be 16 characters")
+ }
+ return arg, nil
+ default:
+ return nil,
+ fmt.Errorf("argument must be a string or byte slice: %#v", args[0])
+ }
+}
+
+func (u *UUIDFieldIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ if len(args) != 1 {
+ return nil, fmt.Errorf("must provide only a single argument")
+ }
+ switch arg := args[0].(type) {
+ case string:
+ return u.parseString(arg, false)
+ case []byte:
+ return arg, nil
+ default:
+ return nil,
+ fmt.Errorf("argument must be a string or byte slice: %#v", args[0])
+ }
+}
+
+// parseString parses a UUID from the string. If enforceLength is false, it will
+// parse a partial UUID. An error is returned if the input, stripped of hyphens,
+// is not even length.
+func (u *UUIDFieldIndex) parseString(s string, enforceLength bool) ([]byte, error) {
+ // Verify the length
+ l := len(s)
+ if enforceLength && l != 36 {
+ return nil, fmt.Errorf("UUID must be 36 characters")
+ } else if l > 36 {
+ return nil, fmt.Errorf("Invalid UUID length. UUID have 36 characters; got %d", l)
+ }
+
+ hyphens := strings.Count(s, "-")
+ if hyphens > 4 {
+ return nil, fmt.Errorf(`UUID should have maximum of 4 "-"; got %d`, hyphens)
+ }
+
+ // The sanitized length is the length of the original string without the "-".
+ sanitized := strings.Replace(s, "-", "", -1)
+ sanitizedLength := len(sanitized)
+ if sanitizedLength%2 != 0 {
+ return nil, fmt.Errorf("Input (without hyphens) must be even length")
+ }
+
+ dec, err := hex.DecodeString(sanitized)
+ if err != nil {
+ return nil, fmt.Errorf("Invalid UUID: %v", err)
+ }
+
+ return dec, nil
+}
+
+// FieldSetIndex is used to extract a field from an object using reflection and
+// builds an index on whether the field is set by comparing it against its
+// type's nil value.
+type FieldSetIndex struct {
+ Field string
+}
+
+func (f *FieldSetIndex) FromObject(obj interface{}) (bool, []byte, error) {
+ v := reflect.ValueOf(obj)
+ v = reflect.Indirect(v) // Dereference the pointer if any
+
+ fv := v.FieldByName(f.Field)
+ if !fv.IsValid() {
+ return false, nil,
+ fmt.Errorf("field '%s' for %#v is invalid", f.Field, obj)
+ }
+
+ if fv.Interface() == reflect.Zero(fv.Type()).Interface() {
+ return true, []byte{0}, nil
+ }
+
+ return true, []byte{1}, nil
+}
+
+func (f *FieldSetIndex) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromBoolArgs(args)
+}
+
+// ConditionalIndex builds an index based on a condition specified by a passed
+// user function. This function may examine the passed object and return a
+// boolean to encapsulate an arbitrarily complex conditional.
+type ConditionalIndex struct {
+ Conditional ConditionalIndexFunc
+}
+
+// ConditionalIndexFunc is the required function interface for a
+// ConditionalIndex.
+type ConditionalIndexFunc func(obj interface{}) (bool, error)
+
+func (c *ConditionalIndex) FromObject(obj interface{}) (bool, []byte, error) {
+ // Call the user's function
+ res, err := c.Conditional(obj)
+ if err != nil {
+ return false, nil, fmt.Errorf("ConditionalIndexFunc(%#v) failed: %v", obj, err)
+ }
+
+ if res {
+ return true, []byte{1}, nil
+ }
+
+ return true, []byte{0}, nil
+}
+
+func (c *ConditionalIndex) FromArgs(args ...interface{}) ([]byte, error) {
+ return fromBoolArgs(args)
+}
+
+// fromBoolArgs is a helper that expects only a single boolean argument and
+// returns a single length byte array containing either a one or zero depending
+// on whether the passed input is true or false respectively.
+func fromBoolArgs(args []interface{}) ([]byte, error) {
+ if len(args) != 1 {
+ return nil, fmt.Errorf("must provide only a single argument")
+ }
+
+ if val, ok := args[0].(bool); !ok {
+ return nil, fmt.Errorf("argument must be a boolean type: %#v", args[0])
+ } else if val {
+ return []byte{1}, nil
+ }
+
+ return []byte{0}, nil
+}
+
+// CompoundIndex is used to build an index using multiple sub-indexes
+// Prefix based iteration is supported as long as the appropriate prefix
+// of indexers support it. All sub-indexers are only assumed to expect
+// a single argument.
+type CompoundIndex struct {
+ Indexes []Indexer
+
+ // AllowMissing results in an index based on only the indexers
+ // that return data. If true, you may end up with 2/3 columns
+ // indexed which might be useful for an index scan. Otherwise,
+ // the CompoundIndex requires all indexers to be satisfied.
+ AllowMissing bool
+}
+
+func (c *CompoundIndex) FromObject(raw interface{}) (bool, []byte, error) {
+ var out []byte
+ for i, idxRaw := range c.Indexes {
+ idx, ok := idxRaw.(SingleIndexer)
+ if !ok {
+ return false, nil, fmt.Errorf("sub-index %d error: %s", i, "sub-index must be a SingleIndexer")
+ }
+ ok, val, err := idx.FromObject(raw)
+ if err != nil {
+ return false, nil, fmt.Errorf("sub-index %d error: %v", i, err)
+ }
+ if !ok {
+ if c.AllowMissing {
+ break
+ } else {
+ return false, nil, nil
+ }
+ }
+ out = append(out, val...)
+ }
+ return true, out, nil
+}
+
+func (c *CompoundIndex) FromArgs(args ...interface{}) ([]byte, error) {
+ if len(args) != len(c.Indexes) {
+ return nil, fmt.Errorf("less arguments than index fields")
+ }
+ var out []byte
+ for i, arg := range args {
+ val, err := c.Indexes[i].FromArgs(arg)
+ if err != nil {
+ return nil, fmt.Errorf("sub-index %d error: %v", i, err)
+ }
+ out = append(out, val...)
+ }
+ return out, nil
+}
+
+func (c *CompoundIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) {
+ if len(args) > len(c.Indexes) {
+ return nil, fmt.Errorf("more arguments than index fields")
+ }
+ var out []byte
+ for i, arg := range args {
+ if i+1 < len(args) {
+ val, err := c.Indexes[i].FromArgs(arg)
+ if err != nil {
+ return nil, fmt.Errorf("sub-index %d error: %v", i, err)
+ }
+ out = append(out, val...)
+ } else {
+ prefixIndexer, ok := c.Indexes[i].(PrefixIndexer)
+ if !ok {
+ return nil, fmt.Errorf("sub-index %d does not support prefix scanning", i)
+ }
+ val, err := prefixIndexer.PrefixFromArgs(arg)
+ if err != nil {
+ return nil, fmt.Errorf("sub-index %d error: %v", i, err)
+ }
+ out = append(out, val...)
+ }
+ }
+ return out, nil
+}
diff --git a/vendor/github.com/hashicorp/go-memdb/memdb.go b/vendor/github.com/hashicorp/go-memdb/memdb.go
new file mode 100644
index 0000000..1d70851
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-memdb/memdb.go
@@ -0,0 +1,89 @@
+package memdb
+
+import (
+ "sync"
+ "sync/atomic"
+ "unsafe"
+
+ "github.com/hashicorp/go-immutable-radix"
+)
+
+// MemDB is an in-memory database. It provides a table abstraction,
+// which is used to store objects (rows) with multiple indexes based
+// on values. The database makes use of immutable radix trees to provide
+// transactions and MVCC.
+type MemDB struct {
+ schema *DBSchema
+ root unsafe.Pointer // *iradix.Tree underneath
+
+ // There can only be a single writter at once
+ writer sync.Mutex
+}
+
+// NewMemDB creates a new MemDB with the given schema
+func NewMemDB(schema *DBSchema) (*MemDB, error) {
+ // Validate the schema
+ if err := schema.Validate(); err != nil {
+ return nil, err
+ }
+
+ // Create the MemDB
+ db := &MemDB{
+ schema: schema,
+ root: unsafe.Pointer(iradix.New()),
+ }
+ if err := db.initialize(); err != nil {
+ return nil, err
+ }
+ return db, nil
+}
+
+// getRoot is used to do an atomic load of the root pointer
+func (db *MemDB) getRoot() *iradix.Tree {
+ root := (*iradix.Tree)(atomic.LoadPointer(&db.root))
+ return root
+}
+
+// Txn is used to start a new transaction, in either read or write mode.
+// There can only be a single concurrent writer, but any number of readers.
+func (db *MemDB) Txn(write bool) *Txn {
+ if write {
+ db.writer.Lock()
+ }
+ txn := &Txn{
+ db: db,
+ write: write,
+ rootTxn: db.getRoot().Txn(),
+ }
+ return txn
+}
+
+// Snapshot is used to capture a point-in-time snapshot
+// of the database that will not be affected by any write
+// operations to the existing DB.
+func (db *MemDB) Snapshot() *MemDB {
+ clone := &MemDB{
+ schema: db.schema,
+ root: unsafe.Pointer(db.getRoot()),
+ }
+ return clone
+}
+
+// initialize is used to setup the DB for use after creation
+func (db *MemDB) initialize() error {
+ root := db.getRoot()
+ for tName, tableSchema := range db.schema.Tables {
+ for iName, _ := range tableSchema.Indexes {
+ index := iradix.New()
+ path := indexPath(tName, iName)
+ root, _, _ = root.Insert(path, index)
+ }
+ }
+ db.root = unsafe.Pointer(root)
+ return nil
+}
+
+// indexPath returns the path from the root to the given table index
+func indexPath(table, index string) []byte {
+ return []byte(table + "." + index)
+}
diff --git a/vendor/github.com/hashicorp/go-memdb/schema.go b/vendor/github.com/hashicorp/go-memdb/schema.go
new file mode 100644
index 0000000..26d0fcb
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-memdb/schema.go
@@ -0,0 +1,85 @@
+package memdb
+
+import "fmt"
+
+// DBSchema contains the full database schema used for MemDB
+type DBSchema struct {
+ Tables map[string]*TableSchema
+}
+
+// Validate is used to validate the database schema
+func (s *DBSchema) Validate() error {
+ if s == nil {
+ return fmt.Errorf("missing schema")
+ }
+ if len(s.Tables) == 0 {
+ return fmt.Errorf("no tables defined")
+ }
+ for name, table := range s.Tables {
+ if name != table.Name {
+ return fmt.Errorf("table name mis-match for '%s'", name)
+ }
+ if err := table.Validate(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// TableSchema contains the schema for a single table
+type TableSchema struct {
+ Name string
+ Indexes map[string]*IndexSchema
+}
+
+// Validate is used to validate the table schema
+func (s *TableSchema) Validate() error {
+ if s.Name == "" {
+ return fmt.Errorf("missing table name")
+ }
+ if len(s.Indexes) == 0 {
+ return fmt.Errorf("missing table schemas for '%s'", s.Name)
+ }
+ if _, ok := s.Indexes["id"]; !ok {
+ return fmt.Errorf("must have id index")
+ }
+ if !s.Indexes["id"].Unique {
+ return fmt.Errorf("id index must be unique")
+ }
+ if _, ok := s.Indexes["id"].Indexer.(SingleIndexer); !ok {
+ return fmt.Errorf("id index must be a SingleIndexer")
+ }
+ for name, index := range s.Indexes {
+ if name != index.Name {
+ return fmt.Errorf("index name mis-match for '%s'", name)
+ }
+ if err := index.Validate(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// IndexSchema contains the schema for an index
+type IndexSchema struct {
+ Name string
+ AllowMissing bool
+ Unique bool
+ Indexer Indexer
+}
+
+func (s *IndexSchema) Validate() error {
+ if s.Name == "" {
+ return fmt.Errorf("missing index name")
+ }
+ if s.Indexer == nil {
+ return fmt.Errorf("missing index function for '%s'", s.Name)
+ }
+ switch s.Indexer.(type) {
+ case SingleIndexer:
+ case MultiIndexer:
+ default:
+ return fmt.Errorf("indexer for '%s' must be a SingleIndexer or MultiIndexer", s.Name)
+ }
+ return nil
+}
diff --git a/vendor/github.com/hashicorp/go-memdb/txn.go b/vendor/github.com/hashicorp/go-memdb/txn.go
new file mode 100644
index 0000000..fa73c9a
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-memdb/txn.go
@@ -0,0 +1,521 @@
+package memdb
+
+import (
+ "bytes"
+ "fmt"
+ "strings"
+ "sync/atomic"
+ "unsafe"
+
+ "github.com/hashicorp/go-immutable-radix"
+)
+
+const (
+ id = "id"
+)
+
+// tableIndex is a tuple of (Table, Index) used for lookups
+type tableIndex struct {
+ Table string
+ Index string
+}
+
+// Txn is a transaction against a MemDB.
+// This can be a read or write transaction.
+type Txn struct {
+ db *MemDB
+ write bool
+ rootTxn *iradix.Txn
+ after []func()
+
+ modified map[tableIndex]*iradix.Txn
+}
+
+// readableIndex returns a transaction usable for reading the given
+// index in a table. If a write transaction is in progress, we may need
+// to use an existing modified txn.
+func (txn *Txn) readableIndex(table, index string) *iradix.Txn {
+ // Look for existing transaction
+ if txn.write && txn.modified != nil {
+ key := tableIndex{table, index}
+ exist, ok := txn.modified[key]
+ if ok {
+ return exist
+ }
+ }
+
+ // Create a read transaction
+ path := indexPath(table, index)
+ raw, _ := txn.rootTxn.Get(path)
+ indexTxn := raw.(*iradix.Tree).Txn()
+ return indexTxn
+}
+
+// writableIndex returns a transaction usable for modifying the
+// given index in a table.
+func (txn *Txn) writableIndex(table, index string) *iradix.Txn {
+ if txn.modified == nil {
+ txn.modified = make(map[tableIndex]*iradix.Txn)
+ }
+
+ // Look for existing transaction
+ key := tableIndex{table, index}
+ exist, ok := txn.modified[key]
+ if ok {
+ return exist
+ }
+
+ // Start a new transaction
+ path := indexPath(table, index)
+ raw, _ := txn.rootTxn.Get(path)
+ indexTxn := raw.(*iradix.Tree).Txn()
+
+ // Keep this open for the duration of the txn
+ txn.modified[key] = indexTxn
+ return indexTxn
+}
+
+// Abort is used to cancel this transaction.
+// This is a noop for read transactions.
+func (txn *Txn) Abort() {
+ // Noop for a read transaction
+ if !txn.write {
+ return
+ }
+
+ // Check if already aborted or committed
+ if txn.rootTxn == nil {
+ return
+ }
+
+ // Clear the txn
+ txn.rootTxn = nil
+ txn.modified = nil
+
+ // Release the writer lock since this is invalid
+ txn.db.writer.Unlock()
+}
+
+// Commit is used to finalize this transaction.
+// This is a noop for read transactions.
+func (txn *Txn) Commit() {
+ // Noop for a read transaction
+ if !txn.write {
+ return
+ }
+
+ // Check if already aborted or committed
+ if txn.rootTxn == nil {
+ return
+ }
+
+ // Commit each sub-transaction scoped to (table, index)
+ for key, subTxn := range txn.modified {
+ path := indexPath(key.Table, key.Index)
+ final := subTxn.Commit()
+ txn.rootTxn.Insert(path, final)
+ }
+
+ // Update the root of the DB
+ newRoot := txn.rootTxn.Commit()
+ atomic.StorePointer(&txn.db.root, unsafe.Pointer(newRoot))
+
+ // Clear the txn
+ txn.rootTxn = nil
+ txn.modified = nil
+
+ // Release the writer lock since this is invalid
+ txn.db.writer.Unlock()
+
+ // Run the deferred functions, if any
+ for i := len(txn.after); i > 0; i-- {
+ fn := txn.after[i-1]
+ fn()
+ }
+}
+
+// Insert is used to add or update an object into the given table
+func (txn *Txn) Insert(table string, obj interface{}) error {
+ if !txn.write {
+ return fmt.Errorf("cannot insert in read-only transaction")
+ }
+
+ // Get the table schema
+ tableSchema, ok := txn.db.schema.Tables[table]
+ if !ok {
+ return fmt.Errorf("invalid table '%s'", table)
+ }
+
+ // Get the primary ID of the object
+ idSchema := tableSchema.Indexes[id]
+ idIndexer := idSchema.Indexer.(SingleIndexer)
+ ok, idVal, err := idIndexer.FromObject(obj)
+ if err != nil {
+ return fmt.Errorf("failed to build primary index: %v", err)
+ }
+ if !ok {
+ return fmt.Errorf("object missing primary index")
+ }
+
+ // Lookup the object by ID first, to see if this is an update
+ idTxn := txn.writableIndex(table, id)
+ existing, update := idTxn.Get(idVal)
+
+ // On an update, there is an existing object with the given
+ // primary ID. We do the update by deleting the current object
+ // and inserting the new object.
+ for name, indexSchema := range tableSchema.Indexes {
+ indexTxn := txn.writableIndex(table, name)
+
+ // Determine the new index value
+ var (
+ ok bool
+ vals [][]byte
+ err error
+ )
+ switch indexer := indexSchema.Indexer.(type) {
+ case SingleIndexer:
+ var val []byte
+ ok, val, err = indexer.FromObject(obj)
+ vals = [][]byte{val}
+ case MultiIndexer:
+ ok, vals, err = indexer.FromObject(obj)
+ }
+ if err != nil {
+ return fmt.Errorf("failed to build index '%s': %v", name, err)
+ }
+
+ // Handle non-unique index by computing a unique index.
+ // This is done by appending the primary key which must
+ // be unique anyways.
+ if ok && !indexSchema.Unique {
+ for i := range vals {
+ vals[i] = append(vals[i], idVal...)
+ }
+ }
+
+ // Handle the update by deleting from the index first
+ if update {
+ var (
+ okExist bool
+ valsExist [][]byte
+ err error
+ )
+ switch indexer := indexSchema.Indexer.(type) {
+ case SingleIndexer:
+ var valExist []byte
+ okExist, valExist, err = indexer.FromObject(existing)
+ valsExist = [][]byte{valExist}
+ case MultiIndexer:
+ okExist, valsExist, err = indexer.FromObject(existing)
+ }
+ if err != nil {
+ return fmt.Errorf("failed to build index '%s': %v", name, err)
+ }
+ if okExist {
+ for i, valExist := range valsExist {
+ // Handle non-unique index by computing a unique index.
+ // This is done by appending the primary key which must
+ // be unique anyways.
+ if !indexSchema.Unique {
+ valExist = append(valExist, idVal...)
+ }
+
+ // If we are writing to the same index with the same value,
+ // we can avoid the delete as the insert will overwrite the
+ // value anyways.
+ if i >= len(vals) || !bytes.Equal(valExist, vals[i]) {
+ indexTxn.Delete(valExist)
+ }
+ }
+ }
+ }
+
+ // If there is no index value, either this is an error or an expected
+ // case and we can skip updating
+ if !ok {
+ if indexSchema.AllowMissing {
+ continue
+ } else {
+ return fmt.Errorf("missing value for index '%s'", name)
+ }
+ }
+
+ // Update the value of the index
+ for _, val := range vals {
+ indexTxn.Insert(val, obj)
+ }
+ }
+ return nil
+}
+
+// Delete is used to delete a single object from the given table
+// This object must already exist in the table
+func (txn *Txn) Delete(table string, obj interface{}) error {
+ if !txn.write {
+ return fmt.Errorf("cannot delete in read-only transaction")
+ }
+
+ // Get the table schema
+ tableSchema, ok := txn.db.schema.Tables[table]
+ if !ok {
+ return fmt.Errorf("invalid table '%s'", table)
+ }
+
+ // Get the primary ID of the object
+ idSchema := tableSchema.Indexes[id]
+ idIndexer := idSchema.Indexer.(SingleIndexer)
+ ok, idVal, err := idIndexer.FromObject(obj)
+ if err != nil {
+ return fmt.Errorf("failed to build primary index: %v", err)
+ }
+ if !ok {
+ return fmt.Errorf("object missing primary index")
+ }
+
+ // Lookup the object by ID first, check fi we should continue
+ idTxn := txn.writableIndex(table, id)
+ existing, ok := idTxn.Get(idVal)
+ if !ok {
+ return fmt.Errorf("not found")
+ }
+
+ // Remove the object from all the indexes
+ for name, indexSchema := range tableSchema.Indexes {
+ indexTxn := txn.writableIndex(table, name)
+
+ // Handle the update by deleting from the index first
+ var (
+ ok bool
+ vals [][]byte
+ err error
+ )
+ switch indexer := indexSchema.Indexer.(type) {
+ case SingleIndexer:
+ var val []byte
+ ok, val, err = indexer.FromObject(existing)
+ vals = [][]byte{val}
+ case MultiIndexer:
+ ok, vals, err = indexer.FromObject(existing)
+ }
+ if err != nil {
+ return fmt.Errorf("failed to build index '%s': %v", name, err)
+ }
+ if ok {
+ // Handle non-unique index by computing a unique index.
+ // This is done by appending the primary key which must
+ // be unique anyways.
+ for _, val := range vals {
+ if !indexSchema.Unique {
+ val = append(val, idVal...)
+ }
+ indexTxn.Delete(val)
+ }
+ }
+ }
+ return nil
+}
+
+// DeleteAll is used to delete all the objects in a given table
+// matching the constraints on the index
+func (txn *Txn) DeleteAll(table, index string, args ...interface{}) (int, error) {
+ if !txn.write {
+ return 0, fmt.Errorf("cannot delete in read-only transaction")
+ }
+
+ // Get all the objects
+ iter, err := txn.Get(table, index, args...)
+ if err != nil {
+ return 0, err
+ }
+
+ // Put them into a slice so there are no safety concerns while actually
+ // performing the deletes
+ var objs []interface{}
+ for {
+ obj := iter.Next()
+ if obj == nil {
+ break
+ }
+
+ objs = append(objs, obj)
+ }
+
+ // Do the deletes
+ num := 0
+ for _, obj := range objs {
+ if err := txn.Delete(table, obj); err != nil {
+ return num, err
+ }
+ num++
+ }
+ return num, nil
+}
+
+// First is used to return the first matching object for
+// the given constraints on the index
+func (txn *Txn) First(table, index string, args ...interface{}) (interface{}, error) {
+ // Get the index value
+ indexSchema, val, err := txn.getIndexValue(table, index, args...)
+ if err != nil {
+ return nil, err
+ }
+
+ // Get the index itself
+ indexTxn := txn.readableIndex(table, indexSchema.Name)
+
+ // Do an exact lookup
+ if indexSchema.Unique && val != nil && indexSchema.Name == index {
+ obj, ok := indexTxn.Get(val)
+ if !ok {
+ return nil, nil
+ }
+ return obj, nil
+ }
+
+ // Handle non-unique index by using an iterator and getting the first value
+ iter := indexTxn.Root().Iterator()
+ iter.SeekPrefix(val)
+ _, value, _ := iter.Next()
+ return value, nil
+}
+
+// LongestPrefix is used to fetch the longest prefix match for the given
+// constraints on the index. Note that this will not work with the memdb
+// StringFieldIndex because it adds null terminators which prevent the
+// algorithm from correctly finding a match (it will get to right before the
+// null and fail to find a leaf node). This should only be used where the prefix
+// given is capable of matching indexed entries directly, which typically only
+// applies to a custom indexer. See the unit test for an example.
+func (txn *Txn) LongestPrefix(table, index string, args ...interface{}) (interface{}, error) {
+ // Enforce that this only works on prefix indexes.
+ if !strings.HasSuffix(index, "_prefix") {
+ return nil, fmt.Errorf("must use '%s_prefix' on index", index)
+ }
+
+ // Get the index value.
+ indexSchema, val, err := txn.getIndexValue(table, index, args...)
+ if err != nil {
+ return nil, err
+ }
+
+ // This algorithm only makes sense against a unique index, otherwise the
+ // index keys will have the IDs appended to them.
+ if !indexSchema.Unique {
+ return nil, fmt.Errorf("index '%s' is not unique", index)
+ }
+
+ // Find the longest prefix match with the given index.
+ indexTxn := txn.readableIndex(table, indexSchema.Name)
+ if _, value, ok := indexTxn.Root().LongestPrefix(val); ok {
+ return value, nil
+ }
+ return nil, nil
+}
+
+// getIndexValue is used to get the IndexSchema and the value
+// used to scan the index given the parameters. This handles prefix based
+// scans when the index has the "_prefix" suffix. The index must support
+// prefix iteration.
+func (txn *Txn) getIndexValue(table, index string, args ...interface{}) (*IndexSchema, []byte, error) {
+ // Get the table schema
+ tableSchema, ok := txn.db.schema.Tables[table]
+ if !ok {
+ return nil, nil, fmt.Errorf("invalid table '%s'", table)
+ }
+
+ // Check for a prefix scan
+ prefixScan := false
+ if strings.HasSuffix(index, "_prefix") {
+ index = strings.TrimSuffix(index, "_prefix")
+ prefixScan = true
+ }
+
+ // Get the index schema
+ indexSchema, ok := tableSchema.Indexes[index]
+ if !ok {
+ return nil, nil, fmt.Errorf("invalid index '%s'", index)
+ }
+
+ // Hot-path for when there are no arguments
+ if len(args) == 0 {
+ return indexSchema, nil, nil
+ }
+
+ // Special case the prefix scanning
+ if prefixScan {
+ prefixIndexer, ok := indexSchema.Indexer.(PrefixIndexer)
+ if !ok {
+ return indexSchema, nil,
+ fmt.Errorf("index '%s' does not support prefix scanning", index)
+ }
+
+ val, err := prefixIndexer.PrefixFromArgs(args...)
+ if err != nil {
+ return indexSchema, nil, fmt.Errorf("index error: %v", err)
+ }
+ return indexSchema, val, err
+ }
+
+ // Get the exact match index
+ val, err := indexSchema.Indexer.FromArgs(args...)
+ if err != nil {
+ return indexSchema, nil, fmt.Errorf("index error: %v", err)
+ }
+ return indexSchema, val, err
+}
+
+// ResultIterator is used to iterate over a list of results
+// from a Get query on a table.
+type ResultIterator interface {
+ Next() interface{}
+}
+
+// Get is used to construct a ResultIterator over all the
+// rows that match the given constraints of an index.
+func (txn *Txn) Get(table, index string, args ...interface{}) (ResultIterator, error) {
+ // Get the index value to scan
+ indexSchema, val, err := txn.getIndexValue(table, index, args...)
+ if err != nil {
+ return nil, err
+ }
+
+ // Get the index itself
+ indexTxn := txn.readableIndex(table, indexSchema.Name)
+ indexRoot := indexTxn.Root()
+
+ // Get an interator over the index
+ indexIter := indexRoot.Iterator()
+
+ // Seek the iterator to the appropriate sub-set
+ indexIter.SeekPrefix(val)
+
+ // Create an iterator
+ iter := &radixIterator{
+ iter: indexIter,
+ }
+ return iter, nil
+}
+
+// Defer is used to push a new arbitrary function onto a stack which
+// gets called when a transaction is committed and finished. Deferred
+// functions are called in LIFO order, and only invoked at the end of
+// write transactions.
+func (txn *Txn) Defer(fn func()) {
+ txn.after = append(txn.after, fn)
+}
+
+// radixIterator is used to wrap an underlying iradix iterator.
+// This is much mroe efficient than a sliceIterator as we are not
+// materializing the entire view.
+type radixIterator struct {
+ iter *iradix.Iterator
+}
+
+func (r *radixIterator) Next() interface{} {
+ _, value, ok := r.iter.Next()
+ if !ok {
+ return nil
+ }
+ return value
+}
diff --git a/vendor/github.com/hashicorp/go-msgpack/LICENSE b/vendor/github.com/hashicorp/go-msgpack/LICENSE
new file mode 100644
index 0000000..ccae99f
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/LICENSE
@@ -0,0 +1,25 @@
+Copyright (c) 2012, 2013 Ugorji Nwoke.
+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 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.
diff --git a/vendor/github.com/hashicorp/go-msgpack/README.md b/vendor/github.com/hashicorp/go-msgpack/README.md
new file mode 100644
index 0000000..0d9d754
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/README.md
@@ -0,0 +1,14 @@
+# go
+
+Collection of Open-Source Go libraries and tools.
+
+## Codec
+
+[Codec](https://github.com/ugorji/go/tree/master/codec#readme) is a High Performance and Feature-Rich Idiomatic encode/decode and rpc library for [msgpack](http://msgpack.org) and [Binc](https://github.com/ugorji/binc).
+
+Online documentation is at [http://godoc.org/github.com/ugorji/go/codec].
+
+Install using:
+
+ go get github.com/ugorji/go/codec
+
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/0doc.go b/vendor/github.com/hashicorp/go-msgpack/codec/0doc.go
new file mode 100644
index 0000000..c14d810
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/0doc.go
@@ -0,0 +1,143 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+/*
+High Performance, Feature-Rich Idiomatic Go encoding library for msgpack and binc .
+
+Supported Serialization formats are:
+
+ - msgpack: [https://github.com/msgpack/msgpack]
+ - binc: [http://github.com/ugorji/binc]
+
+To install:
+
+ go get github.com/ugorji/go/codec
+
+The idiomatic Go support is as seen in other encoding packages in
+the standard library (ie json, xml, gob, etc).
+
+Rich Feature Set includes:
+
+ - Simple but extremely powerful and feature-rich API
+ - Very High Performance.
+ Our extensive benchmarks show us outperforming Gob, Json and Bson by 2-4X.
+ This was achieved by taking extreme care on:
+ - managing allocation
+ - function frame size (important due to Go's use of split stacks),
+ - reflection use (and by-passing reflection for common types)
+ - recursion implications
+ - zero-copy mode (encoding/decoding to byte slice without using temp buffers)
+ - Correct.
+ Care was taken to precisely handle corner cases like:
+ overflows, nil maps and slices, nil value in stream, etc.
+ - Efficient zero-copying into temporary byte buffers
+ when encoding into or decoding from a byte slice.
+ - Standard field renaming via tags
+ - Encoding from any value
+ (struct, slice, map, primitives, pointers, interface{}, etc)
+ - Decoding into pointer to any non-nil typed value
+ (struct, slice, map, int, float32, bool, string, reflect.Value, etc)
+ - Supports extension functions to handle the encode/decode of custom types
+ - Support Go 1.2 encoding.BinaryMarshaler/BinaryUnmarshaler
+ - Schema-less decoding
+ (decode into a pointer to a nil interface{} as opposed to a typed non-nil value).
+ Includes Options to configure what specific map or slice type to use
+ when decoding an encoded list or map into a nil interface{}
+ - Provides a RPC Server and Client Codec for net/rpc communication protocol.
+ - Msgpack Specific:
+ - Provides extension functions to handle spec-defined extensions (binary, timestamp)
+ - Options to resolve ambiguities in handling raw bytes (as string or []byte)
+ during schema-less decoding (decoding into a nil interface{})
+ - RPC Server/Client Codec for msgpack-rpc protocol defined at:
+ https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
+ - Fast Paths for some container types:
+ For some container types, we circumvent reflection and its associated overhead
+ and allocation costs, and encode/decode directly. These types are:
+ []interface{}
+ []int
+ []string
+ map[interface{}]interface{}
+ map[int]interface{}
+ map[string]interface{}
+
+Extension Support
+
+Users can register a function to handle the encoding or decoding of
+their custom types.
+
+There are no restrictions on what the custom type can be. Some examples:
+
+ type BisSet []int
+ type BitSet64 uint64
+ type UUID string
+ type MyStructWithUnexportedFields struct { a int; b bool; c []int; }
+ type GifImage struct { ... }
+
+As an illustration, MyStructWithUnexportedFields would normally be
+encoded as an empty map because it has no exported fields, while UUID
+would be encoded as a string. However, with extension support, you can
+encode any of these however you like.
+
+RPC
+
+RPC Client and Server Codecs are implemented, so the codecs can be used
+with the standard net/rpc package.
+
+Usage
+
+Typical usage model:
+
+ // create and configure Handle
+ var (
+ bh codec.BincHandle
+ mh codec.MsgpackHandle
+ )
+
+ mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
+
+ // configure extensions
+ // e.g. for msgpack, define functions and enable Time support for tag 1
+ // mh.AddExt(reflect.TypeOf(time.Time{}), 1, myMsgpackTimeEncodeExtFn, myMsgpackTimeDecodeExtFn)
+
+ // create and use decoder/encoder
+ var (
+ r io.Reader
+ w io.Writer
+ b []byte
+ h = &bh // or mh to use msgpack
+ )
+
+ dec = codec.NewDecoder(r, h)
+ dec = codec.NewDecoderBytes(b, h)
+ err = dec.Decode(&v)
+
+ enc = codec.NewEncoder(w, h)
+ enc = codec.NewEncoderBytes(&b, h)
+ err = enc.Encode(v)
+
+ //RPC Server
+ go func() {
+ for {
+ conn, err := listener.Accept()
+ rpcCodec := codec.GoRpc.ServerCodec(conn, h)
+ //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h)
+ rpc.ServeCodec(rpcCodec)
+ }
+ }()
+
+ //RPC Communication (client side)
+ conn, err = net.Dial("tcp", "localhost:5555")
+ rpcCodec := codec.GoRpc.ClientCodec(conn, h)
+ //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h)
+ client := rpc.NewClientWithCodec(rpcCodec)
+
+Representative Benchmark Results
+
+Run the benchmark suite using:
+ go test -bi -bench=. -benchmem
+
+To run full benchmark suite (including against vmsgpack and bson),
+see notes in ext_dep_test.go
+
+*/
+package codec
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/README.md b/vendor/github.com/hashicorp/go-msgpack/codec/README.md
new file mode 100644
index 0000000..6c95d1b
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/README.md
@@ -0,0 +1,174 @@
+# Codec
+
+High Performance and Feature-Rich Idiomatic Go Library providing
+encode/decode support for different serialization formats.
+
+Supported Serialization formats are:
+
+ - msgpack: [https://github.com/msgpack/msgpack]
+ - binc: [http://github.com/ugorji/binc]
+
+To install:
+
+ go get github.com/ugorji/go/codec
+
+Online documentation: [http://godoc.org/github.com/ugorji/go/codec]
+
+The idiomatic Go support is as seen in other encoding packages in
+the standard library (ie json, xml, gob, etc).
+
+Rich Feature Set includes:
+
+ - Simple but extremely powerful and feature-rich API
+ - Very High Performance.
+ Our extensive benchmarks show us outperforming Gob, Json and Bson by 2-4X.
+ This was achieved by taking extreme care on:
+ - managing allocation
+ - function frame size (important due to Go's use of split stacks),
+ - reflection use (and by-passing reflection for common types)
+ - recursion implications
+ - zero-copy mode (encoding/decoding to byte slice without using temp buffers)
+ - Correct.
+ Care was taken to precisely handle corner cases like:
+ overflows, nil maps and slices, nil value in stream, etc.
+ - Efficient zero-copying into temporary byte buffers
+ when encoding into or decoding from a byte slice.
+ - Standard field renaming via tags
+ - Encoding from any value
+ (struct, slice, map, primitives, pointers, interface{}, etc)
+ - Decoding into pointer to any non-nil typed value
+ (struct, slice, map, int, float32, bool, string, reflect.Value, etc)
+ - Supports extension functions to handle the encode/decode of custom types
+ - Support Go 1.2 encoding.BinaryMarshaler/BinaryUnmarshaler
+ - Schema-less decoding
+ (decode into a pointer to a nil interface{} as opposed to a typed non-nil value).
+ Includes Options to configure what specific map or slice type to use
+ when decoding an encoded list or map into a nil interface{}
+ - Provides a RPC Server and Client Codec for net/rpc communication protocol.
+ - Msgpack Specific:
+ - Provides extension functions to handle spec-defined extensions (binary, timestamp)
+ - Options to resolve ambiguities in handling raw bytes (as string or []byte)
+ during schema-less decoding (decoding into a nil interface{})
+ - RPC Server/Client Codec for msgpack-rpc protocol defined at:
+ https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
+ - Fast Paths for some container types:
+ For some container types, we circumvent reflection and its associated overhead
+ and allocation costs, and encode/decode directly. These types are:
+ []interface{}
+ []int
+ []string
+ map[interface{}]interface{}
+ map[int]interface{}
+ map[string]interface{}
+
+## Extension Support
+
+Users can register a function to handle the encoding or decoding of
+their custom types.
+
+There are no restrictions on what the custom type can be. Some examples:
+
+ type BisSet []int
+ type BitSet64 uint64
+ type UUID string
+ type MyStructWithUnexportedFields struct { a int; b bool; c []int; }
+ type GifImage struct { ... }
+
+As an illustration, MyStructWithUnexportedFields would normally be
+encoded as an empty map because it has no exported fields, while UUID
+would be encoded as a string. However, with extension support, you can
+encode any of these however you like.
+
+## RPC
+
+RPC Client and Server Codecs are implemented, so the codecs can be used
+with the standard net/rpc package.
+
+## Usage
+
+Typical usage model:
+
+ // create and configure Handle
+ var (
+ bh codec.BincHandle
+ mh codec.MsgpackHandle
+ )
+
+ mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
+
+ // configure extensions
+ // e.g. for msgpack, define functions and enable Time support for tag 1
+ // mh.AddExt(reflect.TypeOf(time.Time{}), 1, myMsgpackTimeEncodeExtFn, myMsgpackTimeDecodeExtFn)
+
+ // create and use decoder/encoder
+ var (
+ r io.Reader
+ w io.Writer
+ b []byte
+ h = &bh // or mh to use msgpack
+ )
+
+ dec = codec.NewDecoder(r, h)
+ dec = codec.NewDecoderBytes(b, h)
+ err = dec.Decode(&v)
+
+ enc = codec.NewEncoder(w, h)
+ enc = codec.NewEncoderBytes(&b, h)
+ err = enc.Encode(v)
+
+ //RPC Server
+ go func() {
+ for {
+ conn, err := listener.Accept()
+ rpcCodec := codec.GoRpc.ServerCodec(conn, h)
+ //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h)
+ rpc.ServeCodec(rpcCodec)
+ }
+ }()
+
+ //RPC Communication (client side)
+ conn, err = net.Dial("tcp", "localhost:5555")
+ rpcCodec := codec.GoRpc.ClientCodec(conn, h)
+ //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h)
+ client := rpc.NewClientWithCodec(rpcCodec)
+
+## Representative Benchmark Results
+
+A sample run of benchmark using "go test -bi -bench=. -benchmem":
+
+ /proc/cpuinfo: Intel(R) Core(TM) i7-2630QM CPU @ 2.00GHz (HT)
+
+ ..............................................
+ BENCHMARK INIT: 2013-10-16 11:02:50.345970786 -0400 EDT
+ To run full benchmark comparing encodings (MsgPack, Binc, JSON, GOB, etc), use: "go test -bench=."
+ Benchmark:
+ Struct recursive Depth: 1
+ ApproxDeepSize Of benchmark Struct: 4694 bytes
+ Benchmark One-Pass Run:
+ v-msgpack: len: 1600 bytes
+ bson: len: 3025 bytes
+ msgpack: len: 1560 bytes
+ binc: len: 1187 bytes
+ gob: len: 1972 bytes
+ json: len: 2538 bytes
+ ..............................................
+ PASS
+ Benchmark__Msgpack____Encode 50000 54359 ns/op 14953 B/op 83 allocs/op
+ Benchmark__Msgpack____Decode 10000 106531 ns/op 14990 B/op 410 allocs/op
+ Benchmark__Binc_NoSym_Encode 50000 53956 ns/op 14966 B/op 83 allocs/op
+ Benchmark__Binc_NoSym_Decode 10000 103751 ns/op 14529 B/op 386 allocs/op
+ Benchmark__Binc_Sym___Encode 50000 65961 ns/op 17130 B/op 88 allocs/op
+ Benchmark__Binc_Sym___Decode 10000 106310 ns/op 15857 B/op 287 allocs/op
+ Benchmark__Gob________Encode 10000 135944 ns/op 21189 B/op 237 allocs/op
+ Benchmark__Gob________Decode 5000 405390 ns/op 83460 B/op 1841 allocs/op
+ Benchmark__Json_______Encode 20000 79412 ns/op 13874 B/op 102 allocs/op
+ Benchmark__Json_______Decode 10000 247979 ns/op 14202 B/op 493 allocs/op
+ Benchmark__Bson_______Encode 10000 121762 ns/op 27814 B/op 514 allocs/op
+ Benchmark__Bson_______Decode 10000 162126 ns/op 16514 B/op 789 allocs/op
+ Benchmark__VMsgpack___Encode 50000 69155 ns/op 12370 B/op 344 allocs/op
+ Benchmark__VMsgpack___Decode 10000 151609 ns/op 20307 B/op 571 allocs/op
+ ok ugorji.net/codec 30.827s
+
+To run full benchmark suite (including against vmsgpack and bson),
+see notes in ext\_dep\_test.go
+
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/binc.go b/vendor/github.com/hashicorp/go-msgpack/codec/binc.go
new file mode 100644
index 0000000..2bb5e8f
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/binc.go
@@ -0,0 +1,786 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import (
+ "math"
+ // "reflect"
+ // "sync/atomic"
+ "time"
+ //"fmt"
+)
+
+const bincDoPrune = true // No longer needed. Needed before as C lib did not support pruning.
+
+//var _ = fmt.Printf
+
+// vd as low 4 bits (there are 16 slots)
+const (
+ bincVdSpecial byte = iota
+ bincVdPosInt
+ bincVdNegInt
+ bincVdFloat
+
+ bincVdString
+ bincVdByteArray
+ bincVdArray
+ bincVdMap
+
+ bincVdTimestamp
+ bincVdSmallInt
+ bincVdUnicodeOther
+ bincVdSymbol
+
+ bincVdDecimal
+ _ // open slot
+ _ // open slot
+ bincVdCustomExt = 0x0f
+)
+
+const (
+ bincSpNil byte = iota
+ bincSpFalse
+ bincSpTrue
+ bincSpNan
+ bincSpPosInf
+ bincSpNegInf
+ bincSpZeroFloat
+ bincSpZero
+ bincSpNegOne
+)
+
+const (
+ bincFlBin16 byte = iota
+ bincFlBin32
+ _ // bincFlBin32e
+ bincFlBin64
+ _ // bincFlBin64e
+ // others not currently supported
+)
+
+type bincEncDriver struct {
+ w encWriter
+ m map[string]uint16 // symbols
+ s uint32 // symbols sequencer
+ b [8]byte
+}
+
+func (e *bincEncDriver) isBuiltinType(rt uintptr) bool {
+ return rt == timeTypId
+}
+
+func (e *bincEncDriver) encodeBuiltin(rt uintptr, v interface{}) {
+ switch rt {
+ case timeTypId:
+ bs := encodeTime(v.(time.Time))
+ e.w.writen1(bincVdTimestamp<<4 | uint8(len(bs)))
+ e.w.writeb(bs)
+ }
+}
+
+func (e *bincEncDriver) encodeNil() {
+ e.w.writen1(bincVdSpecial<<4 | bincSpNil)
+}
+
+func (e *bincEncDriver) encodeBool(b bool) {
+ if b {
+ e.w.writen1(bincVdSpecial<<4 | bincSpTrue)
+ } else {
+ e.w.writen1(bincVdSpecial<<4 | bincSpFalse)
+ }
+}
+
+func (e *bincEncDriver) encodeFloat32(f float32) {
+ if f == 0 {
+ e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat)
+ return
+ }
+ e.w.writen1(bincVdFloat<<4 | bincFlBin32)
+ e.w.writeUint32(math.Float32bits(f))
+}
+
+func (e *bincEncDriver) encodeFloat64(f float64) {
+ if f == 0 {
+ e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat)
+ return
+ }
+ bigen.PutUint64(e.b[:], math.Float64bits(f))
+ if bincDoPrune {
+ i := 7
+ for ; i >= 0 && (e.b[i] == 0); i-- {
+ }
+ i++
+ if i <= 6 {
+ e.w.writen1(bincVdFloat<<4 | 0x8 | bincFlBin64)
+ e.w.writen1(byte(i))
+ e.w.writeb(e.b[:i])
+ return
+ }
+ }
+ e.w.writen1(bincVdFloat<<4 | bincFlBin64)
+ e.w.writeb(e.b[:])
+}
+
+func (e *bincEncDriver) encIntegerPrune(bd byte, pos bool, v uint64, lim uint8) {
+ if lim == 4 {
+ bigen.PutUint32(e.b[:lim], uint32(v))
+ } else {
+ bigen.PutUint64(e.b[:lim], v)
+ }
+ if bincDoPrune {
+ i := pruneSignExt(e.b[:lim], pos)
+ e.w.writen1(bd | lim - 1 - byte(i))
+ e.w.writeb(e.b[i:lim])
+ } else {
+ e.w.writen1(bd | lim - 1)
+ e.w.writeb(e.b[:lim])
+ }
+}
+
+func (e *bincEncDriver) encodeInt(v int64) {
+ const nbd byte = bincVdNegInt << 4
+ switch {
+ case v >= 0:
+ e.encUint(bincVdPosInt<<4, true, uint64(v))
+ case v == -1:
+ e.w.writen1(bincVdSpecial<<4 | bincSpNegOne)
+ default:
+ e.encUint(bincVdNegInt<<4, false, uint64(-v))
+ }
+}
+
+func (e *bincEncDriver) encodeUint(v uint64) {
+ e.encUint(bincVdPosInt<<4, true, v)
+}
+
+func (e *bincEncDriver) encUint(bd byte, pos bool, v uint64) {
+ switch {
+ case v == 0:
+ e.w.writen1(bincVdSpecial<<4 | bincSpZero)
+ case pos && v >= 1 && v <= 16:
+ e.w.writen1(bincVdSmallInt<<4 | byte(v-1))
+ case v <= math.MaxUint8:
+ e.w.writen2(bd|0x0, byte(v))
+ case v <= math.MaxUint16:
+ e.w.writen1(bd | 0x01)
+ e.w.writeUint16(uint16(v))
+ case v <= math.MaxUint32:
+ e.encIntegerPrune(bd, pos, v, 4)
+ default:
+ e.encIntegerPrune(bd, pos, v, 8)
+ }
+}
+
+func (e *bincEncDriver) encodeExtPreamble(xtag byte, length int) {
+ e.encLen(bincVdCustomExt<<4, uint64(length))
+ e.w.writen1(xtag)
+}
+
+func (e *bincEncDriver) encodeArrayPreamble(length int) {
+ e.encLen(bincVdArray<<4, uint64(length))
+}
+
+func (e *bincEncDriver) encodeMapPreamble(length int) {
+ e.encLen(bincVdMap<<4, uint64(length))
+}
+
+func (e *bincEncDriver) encodeString(c charEncoding, v string) {
+ l := uint64(len(v))
+ e.encBytesLen(c, l)
+ if l > 0 {
+ e.w.writestr(v)
+ }
+}
+
+func (e *bincEncDriver) encodeSymbol(v string) {
+ // if WriteSymbolsNoRefs {
+ // e.encodeString(c_UTF8, v)
+ // return
+ // }
+
+ //symbols only offer benefit when string length > 1.
+ //This is because strings with length 1 take only 2 bytes to store
+ //(bd with embedded length, and single byte for string val).
+
+ l := len(v)
+ switch l {
+ case 0:
+ e.encBytesLen(c_UTF8, 0)
+ return
+ case 1:
+ e.encBytesLen(c_UTF8, 1)
+ e.w.writen1(v[0])
+ return
+ }
+ if e.m == nil {
+ e.m = make(map[string]uint16, 16)
+ }
+ ui, ok := e.m[v]
+ if ok {
+ if ui <= math.MaxUint8 {
+ e.w.writen2(bincVdSymbol<<4, byte(ui))
+ } else {
+ e.w.writen1(bincVdSymbol<<4 | 0x8)
+ e.w.writeUint16(ui)
+ }
+ } else {
+ e.s++
+ ui = uint16(e.s)
+ //ui = uint16(atomic.AddUint32(&e.s, 1))
+ e.m[v] = ui
+ var lenprec uint8
+ switch {
+ case l <= math.MaxUint8:
+ // lenprec = 0
+ case l <= math.MaxUint16:
+ lenprec = 1
+ case int64(l) <= math.MaxUint32:
+ lenprec = 2
+ default:
+ lenprec = 3
+ }
+ if ui <= math.MaxUint8 {
+ e.w.writen2(bincVdSymbol<<4|0x0|0x4|lenprec, byte(ui))
+ } else {
+ e.w.writen1(bincVdSymbol<<4 | 0x8 | 0x4 | lenprec)
+ e.w.writeUint16(ui)
+ }
+ switch lenprec {
+ case 0:
+ e.w.writen1(byte(l))
+ case 1:
+ e.w.writeUint16(uint16(l))
+ case 2:
+ e.w.writeUint32(uint32(l))
+ default:
+ e.w.writeUint64(uint64(l))
+ }
+ e.w.writestr(v)
+ }
+}
+
+func (e *bincEncDriver) encodeStringBytes(c charEncoding, v []byte) {
+ l := uint64(len(v))
+ e.encBytesLen(c, l)
+ if l > 0 {
+ e.w.writeb(v)
+ }
+}
+
+func (e *bincEncDriver) encBytesLen(c charEncoding, length uint64) {
+ //TODO: support bincUnicodeOther (for now, just use string or bytearray)
+ if c == c_RAW {
+ e.encLen(bincVdByteArray<<4, length)
+ } else {
+ e.encLen(bincVdString<<4, length)
+ }
+}
+
+func (e *bincEncDriver) encLen(bd byte, l uint64) {
+ if l < 12 {
+ e.w.writen1(bd | uint8(l+4))
+ } else {
+ e.encLenNumber(bd, l)
+ }
+}
+
+func (e *bincEncDriver) encLenNumber(bd byte, v uint64) {
+ switch {
+ case v <= math.MaxUint8:
+ e.w.writen2(bd, byte(v))
+ case v <= math.MaxUint16:
+ e.w.writen1(bd | 0x01)
+ e.w.writeUint16(uint16(v))
+ case v <= math.MaxUint32:
+ e.w.writen1(bd | 0x02)
+ e.w.writeUint32(uint32(v))
+ default:
+ e.w.writen1(bd | 0x03)
+ e.w.writeUint64(uint64(v))
+ }
+}
+
+//------------------------------------
+
+type bincDecDriver struct {
+ r decReader
+ bdRead bool
+ bdType valueType
+ bd byte
+ vd byte
+ vs byte
+ b [8]byte
+ m map[uint32]string // symbols (use uint32 as key, as map optimizes for it)
+}
+
+func (d *bincDecDriver) initReadNext() {
+ if d.bdRead {
+ return
+ }
+ d.bd = d.r.readn1()
+ d.vd = d.bd >> 4
+ d.vs = d.bd & 0x0f
+ d.bdRead = true
+ d.bdType = valueTypeUnset
+}
+
+func (d *bincDecDriver) currentEncodedType() valueType {
+ if d.bdType == valueTypeUnset {
+ switch d.vd {
+ case bincVdSpecial:
+ switch d.vs {
+ case bincSpNil:
+ d.bdType = valueTypeNil
+ case bincSpFalse, bincSpTrue:
+ d.bdType = valueTypeBool
+ case bincSpNan, bincSpNegInf, bincSpPosInf, bincSpZeroFloat:
+ d.bdType = valueTypeFloat
+ case bincSpZero:
+ d.bdType = valueTypeUint
+ case bincSpNegOne:
+ d.bdType = valueTypeInt
+ default:
+ decErr("currentEncodedType: Unrecognized special value 0x%x", d.vs)
+ }
+ case bincVdSmallInt:
+ d.bdType = valueTypeUint
+ case bincVdPosInt:
+ d.bdType = valueTypeUint
+ case bincVdNegInt:
+ d.bdType = valueTypeInt
+ case bincVdFloat:
+ d.bdType = valueTypeFloat
+ case bincVdString:
+ d.bdType = valueTypeString
+ case bincVdSymbol:
+ d.bdType = valueTypeSymbol
+ case bincVdByteArray:
+ d.bdType = valueTypeBytes
+ case bincVdTimestamp:
+ d.bdType = valueTypeTimestamp
+ case bincVdCustomExt:
+ d.bdType = valueTypeExt
+ case bincVdArray:
+ d.bdType = valueTypeArray
+ case bincVdMap:
+ d.bdType = valueTypeMap
+ default:
+ decErr("currentEncodedType: Unrecognized d.vd: 0x%x", d.vd)
+ }
+ }
+ return d.bdType
+}
+
+func (d *bincDecDriver) tryDecodeAsNil() bool {
+ if d.bd == bincVdSpecial<<4|bincSpNil {
+ d.bdRead = false
+ return true
+ }
+ return false
+}
+
+func (d *bincDecDriver) isBuiltinType(rt uintptr) bool {
+ return rt == timeTypId
+}
+
+func (d *bincDecDriver) decodeBuiltin(rt uintptr, v interface{}) {
+ switch rt {
+ case timeTypId:
+ if d.vd != bincVdTimestamp {
+ decErr("Invalid d.vd. Expecting 0x%x. Received: 0x%x", bincVdTimestamp, d.vd)
+ }
+ tt, err := decodeTime(d.r.readn(int(d.vs)))
+ if err != nil {
+ panic(err)
+ }
+ var vt *time.Time = v.(*time.Time)
+ *vt = tt
+ d.bdRead = false
+ }
+}
+
+func (d *bincDecDriver) decFloatPre(vs, defaultLen byte) {
+ if vs&0x8 == 0 {
+ d.r.readb(d.b[0:defaultLen])
+ } else {
+ l := d.r.readn1()
+ if l > 8 {
+ decErr("At most 8 bytes used to represent float. Received: %v bytes", l)
+ }
+ for i := l; i < 8; i++ {
+ d.b[i] = 0
+ }
+ d.r.readb(d.b[0:l])
+ }
+}
+
+func (d *bincDecDriver) decFloat() (f float64) {
+ //if true { f = math.Float64frombits(d.r.readUint64()); break; }
+ switch vs := d.vs; vs & 0x7 {
+ case bincFlBin32:
+ d.decFloatPre(vs, 4)
+ f = float64(math.Float32frombits(bigen.Uint32(d.b[0:4])))
+ case bincFlBin64:
+ d.decFloatPre(vs, 8)
+ f = math.Float64frombits(bigen.Uint64(d.b[0:8]))
+ default:
+ decErr("only float32 and float64 are supported. d.vd: 0x%x, d.vs: 0x%x", d.vd, d.vs)
+ }
+ return
+}
+
+func (d *bincDecDriver) decUint() (v uint64) {
+ // need to inline the code (interface conversion and type assertion expensive)
+ switch d.vs {
+ case 0:
+ v = uint64(d.r.readn1())
+ case 1:
+ d.r.readb(d.b[6:])
+ v = uint64(bigen.Uint16(d.b[6:]))
+ case 2:
+ d.b[4] = 0
+ d.r.readb(d.b[5:])
+ v = uint64(bigen.Uint32(d.b[4:]))
+ case 3:
+ d.r.readb(d.b[4:])
+ v = uint64(bigen.Uint32(d.b[4:]))
+ case 4, 5, 6:
+ lim := int(7 - d.vs)
+ d.r.readb(d.b[lim:])
+ for i := 0; i < lim; i++ {
+ d.b[i] = 0
+ }
+ v = uint64(bigen.Uint64(d.b[:]))
+ case 7:
+ d.r.readb(d.b[:])
+ v = uint64(bigen.Uint64(d.b[:]))
+ default:
+ decErr("unsigned integers with greater than 64 bits of precision not supported")
+ }
+ return
+}
+
+func (d *bincDecDriver) decIntAny() (ui uint64, i int64, neg bool) {
+ switch d.vd {
+ case bincVdPosInt:
+ ui = d.decUint()
+ i = int64(ui)
+ case bincVdNegInt:
+ ui = d.decUint()
+ i = -(int64(ui))
+ neg = true
+ case bincVdSmallInt:
+ i = int64(d.vs) + 1
+ ui = uint64(d.vs) + 1
+ case bincVdSpecial:
+ switch d.vs {
+ case bincSpZero:
+ //i = 0
+ case bincSpNegOne:
+ neg = true
+ ui = 1
+ i = -1
+ default:
+ decErr("numeric decode fails for special value: d.vs: 0x%x", d.vs)
+ }
+ default:
+ decErr("number can only be decoded from uint or int values. d.bd: 0x%x, d.vd: 0x%x", d.bd, d.vd)
+ }
+ return
+}
+
+func (d *bincDecDriver) decodeInt(bitsize uint8) (i int64) {
+ _, i, _ = d.decIntAny()
+ checkOverflow(0, i, bitsize)
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decodeUint(bitsize uint8) (ui uint64) {
+ ui, i, neg := d.decIntAny()
+ if neg {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ checkOverflow(ui, 0, bitsize)
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decodeFloat(chkOverflow32 bool) (f float64) {
+ switch d.vd {
+ case bincVdSpecial:
+ d.bdRead = false
+ switch d.vs {
+ case bincSpNan:
+ return math.NaN()
+ case bincSpPosInf:
+ return math.Inf(1)
+ case bincSpZeroFloat, bincSpZero:
+ return
+ case bincSpNegInf:
+ return math.Inf(-1)
+ default:
+ decErr("Invalid d.vs decoding float where d.vd=bincVdSpecial: %v", d.vs)
+ }
+ case bincVdFloat:
+ f = d.decFloat()
+ default:
+ _, i, _ := d.decIntAny()
+ f = float64(i)
+ }
+ checkOverflowFloat32(f, chkOverflow32)
+ d.bdRead = false
+ return
+}
+
+// bool can be decoded from bool only (single byte).
+func (d *bincDecDriver) decodeBool() (b bool) {
+ switch d.bd {
+ case (bincVdSpecial | bincSpFalse):
+ // b = false
+ case (bincVdSpecial | bincSpTrue):
+ b = true
+ default:
+ decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) readMapLen() (length int) {
+ if d.vd != bincVdMap {
+ decErr("Invalid d.vd for map. Expecting 0x%x. Got: 0x%x", bincVdMap, d.vd)
+ }
+ length = d.decLen()
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) readArrayLen() (length int) {
+ if d.vd != bincVdArray {
+ decErr("Invalid d.vd for array. Expecting 0x%x. Got: 0x%x", bincVdArray, d.vd)
+ }
+ length = d.decLen()
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decLen() int {
+ if d.vs <= 3 {
+ return int(d.decUint())
+ }
+ return int(d.vs - 4)
+}
+
+func (d *bincDecDriver) decodeString() (s string) {
+ switch d.vd {
+ case bincVdString, bincVdByteArray:
+ if length := d.decLen(); length > 0 {
+ s = string(d.r.readn(length))
+ }
+ case bincVdSymbol:
+ //from vs: extract numSymbolBytes, containsStringVal, strLenPrecision,
+ //extract symbol
+ //if containsStringVal, read it and put in map
+ //else look in map for string value
+ var symbol uint32
+ vs := d.vs
+ //fmt.Printf(">>>> d.vs: 0b%b, & 0x8: %v, & 0x4: %v\n", d.vs, vs & 0x8, vs & 0x4)
+ if vs&0x8 == 0 {
+ symbol = uint32(d.r.readn1())
+ } else {
+ symbol = uint32(d.r.readUint16())
+ }
+ if d.m == nil {
+ d.m = make(map[uint32]string, 16)
+ }
+
+ if vs&0x4 == 0 {
+ s = d.m[symbol]
+ } else {
+ var slen int
+ switch vs & 0x3 {
+ case 0:
+ slen = int(d.r.readn1())
+ case 1:
+ slen = int(d.r.readUint16())
+ case 2:
+ slen = int(d.r.readUint32())
+ case 3:
+ slen = int(d.r.readUint64())
+ }
+ s = string(d.r.readn(slen))
+ d.m[symbol] = s
+ }
+ default:
+ decErr("Invalid d.vd for string. Expecting string:0x%x, bytearray:0x%x or symbol: 0x%x. Got: 0x%x",
+ bincVdString, bincVdByteArray, bincVdSymbol, d.vd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) {
+ var clen int
+ switch d.vd {
+ case bincVdString, bincVdByteArray:
+ clen = d.decLen()
+ default:
+ decErr("Invalid d.vd for bytes. Expecting string:0x%x or bytearray:0x%x. Got: 0x%x",
+ bincVdString, bincVdByteArray, d.vd)
+ }
+ if clen > 0 {
+ // if no contents in stream, don't update the passed byteslice
+ if len(bs) != clen {
+ if len(bs) > clen {
+ bs = bs[:clen]
+ } else {
+ bs = make([]byte, clen)
+ }
+ bsOut = bs
+ changed = true
+ }
+ d.r.readb(bs)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
+ switch d.vd {
+ case bincVdCustomExt:
+ l := d.decLen()
+ xtag = d.r.readn1()
+ if verifyTag && xtag != tag {
+ decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
+ }
+ xbs = d.r.readn(l)
+ case bincVdByteArray:
+ xbs, _ = d.decodeBytes(nil)
+ default:
+ decErr("Invalid d.vd for extensions (Expecting extensions or byte array). Got: 0x%x", d.vd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *bincDecDriver) decodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
+ d.initReadNext()
+
+ switch d.vd {
+ case bincVdSpecial:
+ switch d.vs {
+ case bincSpNil:
+ vt = valueTypeNil
+ case bincSpFalse:
+ vt = valueTypeBool
+ v = false
+ case bincSpTrue:
+ vt = valueTypeBool
+ v = true
+ case bincSpNan:
+ vt = valueTypeFloat
+ v = math.NaN()
+ case bincSpPosInf:
+ vt = valueTypeFloat
+ v = math.Inf(1)
+ case bincSpNegInf:
+ vt = valueTypeFloat
+ v = math.Inf(-1)
+ case bincSpZeroFloat:
+ vt = valueTypeFloat
+ v = float64(0)
+ case bincSpZero:
+ vt = valueTypeUint
+ v = int64(0) // int8(0)
+ case bincSpNegOne:
+ vt = valueTypeInt
+ v = int64(-1) // int8(-1)
+ default:
+ decErr("decodeNaked: Unrecognized special value 0x%x", d.vs)
+ }
+ case bincVdSmallInt:
+ vt = valueTypeUint
+ v = uint64(int8(d.vs)) + 1 // int8(d.vs) + 1
+ case bincVdPosInt:
+ vt = valueTypeUint
+ v = d.decUint()
+ case bincVdNegInt:
+ vt = valueTypeInt
+ v = -(int64(d.decUint()))
+ case bincVdFloat:
+ vt = valueTypeFloat
+ v = d.decFloat()
+ case bincVdSymbol:
+ vt = valueTypeSymbol
+ v = d.decodeString()
+ case bincVdString:
+ vt = valueTypeString
+ v = d.decodeString()
+ case bincVdByteArray:
+ vt = valueTypeBytes
+ v, _ = d.decodeBytes(nil)
+ case bincVdTimestamp:
+ vt = valueTypeTimestamp
+ tt, err := decodeTime(d.r.readn(int(d.vs)))
+ if err != nil {
+ panic(err)
+ }
+ v = tt
+ case bincVdCustomExt:
+ vt = valueTypeExt
+ l := d.decLen()
+ var re RawExt
+ re.Tag = d.r.readn1()
+ re.Data = d.r.readn(l)
+ v = &re
+ vt = valueTypeExt
+ case bincVdArray:
+ vt = valueTypeArray
+ decodeFurther = true
+ case bincVdMap:
+ vt = valueTypeMap
+ decodeFurther = true
+ default:
+ decErr("decodeNaked: Unrecognized d.vd: 0x%x", d.vd)
+ }
+
+ if !decodeFurther {
+ d.bdRead = false
+ }
+ return
+}
+
+//------------------------------------
+
+//BincHandle is a Handle for the Binc Schema-Free Encoding Format
+//defined at https://github.com/ugorji/binc .
+//
+//BincHandle currently supports all Binc features with the following EXCEPTIONS:
+// - only integers up to 64 bits of precision are supported.
+// big integers are unsupported.
+// - Only IEEE 754 binary32 and binary64 floats are supported (ie Go float32 and float64 types).
+// extended precision and decimal IEEE 754 floats are unsupported.
+// - Only UTF-8 strings supported.
+// Unicode_Other Binc types (UTF16, UTF32) are currently unsupported.
+//Note that these EXCEPTIONS are temporary and full support is possible and may happen soon.
+type BincHandle struct {
+ BasicHandle
+}
+
+func (h *BincHandle) newEncDriver(w encWriter) encDriver {
+ return &bincEncDriver{w: w}
+}
+
+func (h *BincHandle) newDecDriver(r decReader) decDriver {
+ return &bincDecDriver{r: r}
+}
+
+func (_ *BincHandle) writeExt() bool {
+ return true
+}
+
+func (h *BincHandle) getBasicHandle() *BasicHandle {
+ return &h.BasicHandle
+}
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/decode.go b/vendor/github.com/hashicorp/go-msgpack/codec/decode.go
new file mode 100644
index 0000000..87bef2b
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/decode.go
@@ -0,0 +1,1048 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import (
+ "io"
+ "reflect"
+ // "runtime/debug"
+)
+
+// Some tagging information for error messages.
+const (
+ msgTagDec = "codec.decoder"
+ msgBadDesc = "Unrecognized descriptor byte"
+ msgDecCannotExpandArr = "cannot expand go array from %v to stream length: %v"
+)
+
+// decReader abstracts the reading source, allowing implementations that can
+// read from an io.Reader or directly off a byte slice with zero-copying.
+type decReader interface {
+ readn(n int) []byte
+ readb([]byte)
+ readn1() uint8
+ readUint16() uint16
+ readUint32() uint32
+ readUint64() uint64
+}
+
+type decDriver interface {
+ initReadNext()
+ tryDecodeAsNil() bool
+ currentEncodedType() valueType
+ isBuiltinType(rt uintptr) bool
+ decodeBuiltin(rt uintptr, v interface{})
+ //decodeNaked: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types).
+ decodeNaked() (v interface{}, vt valueType, decodeFurther bool)
+ decodeInt(bitsize uint8) (i int64)
+ decodeUint(bitsize uint8) (ui uint64)
+ decodeFloat(chkOverflow32 bool) (f float64)
+ decodeBool() (b bool)
+ // decodeString can also decode symbols
+ decodeString() (s string)
+ decodeBytes(bs []byte) (bsOut []byte, changed bool)
+ decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte)
+ readMapLen() int
+ readArrayLen() int
+}
+
+type DecodeOptions struct {
+ // An instance of MapType is used during schema-less decoding of a map in the stream.
+ // If nil, we use map[interface{}]interface{}
+ MapType reflect.Type
+ // An instance of SliceType is used during schema-less decoding of an array in the stream.
+ // If nil, we use []interface{}
+ SliceType reflect.Type
+ // ErrorIfNoField controls whether an error is returned when decoding a map
+ // from a codec stream into a struct, and no matching struct field is found.
+ ErrorIfNoField bool
+}
+
+// ------------------------------------
+
+// ioDecReader is a decReader that reads off an io.Reader
+type ioDecReader struct {
+ r io.Reader
+ br io.ByteReader
+ x [8]byte //temp byte array re-used internally for efficiency
+}
+
+func (z *ioDecReader) readn(n int) (bs []byte) {
+ if n <= 0 {
+ return
+ }
+ bs = make([]byte, n)
+ if _, err := io.ReadAtLeast(z.r, bs, n); err != nil {
+ panic(err)
+ }
+ return
+}
+
+func (z *ioDecReader) readb(bs []byte) {
+ if _, err := io.ReadAtLeast(z.r, bs, len(bs)); err != nil {
+ panic(err)
+ }
+}
+
+func (z *ioDecReader) readn1() uint8 {
+ if z.br != nil {
+ b, err := z.br.ReadByte()
+ if err != nil {
+ panic(err)
+ }
+ return b
+ }
+ z.readb(z.x[:1])
+ return z.x[0]
+}
+
+func (z *ioDecReader) readUint16() uint16 {
+ z.readb(z.x[:2])
+ return bigen.Uint16(z.x[:2])
+}
+
+func (z *ioDecReader) readUint32() uint32 {
+ z.readb(z.x[:4])
+ return bigen.Uint32(z.x[:4])
+}
+
+func (z *ioDecReader) readUint64() uint64 {
+ z.readb(z.x[:8])
+ return bigen.Uint64(z.x[:8])
+}
+
+// ------------------------------------
+
+// bytesDecReader is a decReader that reads off a byte slice with zero copying
+type bytesDecReader struct {
+ b []byte // data
+ c int // cursor
+ a int // available
+}
+
+func (z *bytesDecReader) consume(n int) (oldcursor int) {
+ if z.a == 0 {
+ panic(io.EOF)
+ }
+ if n > z.a {
+ decErr("Trying to read %v bytes. Only %v available", n, z.a)
+ }
+ // z.checkAvailable(n)
+ oldcursor = z.c
+ z.c = oldcursor + n
+ z.a = z.a - n
+ return
+}
+
+func (z *bytesDecReader) readn(n int) (bs []byte) {
+ if n <= 0 {
+ return
+ }
+ c0 := z.consume(n)
+ bs = z.b[c0:z.c]
+ return
+}
+
+func (z *bytesDecReader) readb(bs []byte) {
+ copy(bs, z.readn(len(bs)))
+}
+
+func (z *bytesDecReader) readn1() uint8 {
+ c0 := z.consume(1)
+ return z.b[c0]
+}
+
+// Use binaryEncoding helper for 4 and 8 bits, but inline it for 2 bits
+// creating temp slice variable and copying it to helper function is expensive
+// for just 2 bits.
+
+func (z *bytesDecReader) readUint16() uint16 {
+ c0 := z.consume(2)
+ return uint16(z.b[c0+1]) | uint16(z.b[c0])<<8
+}
+
+func (z *bytesDecReader) readUint32() uint32 {
+ c0 := z.consume(4)
+ return bigen.Uint32(z.b[c0:z.c])
+}
+
+func (z *bytesDecReader) readUint64() uint64 {
+ c0 := z.consume(8)
+ return bigen.Uint64(z.b[c0:z.c])
+}
+
+// ------------------------------------
+
+// decFnInfo has methods for registering handling decoding of a specific type
+// based on some characteristics (builtin, extension, reflect Kind, etc)
+type decFnInfo struct {
+ ti *typeInfo
+ d *Decoder
+ dd decDriver
+ xfFn func(reflect.Value, []byte) error
+ xfTag byte
+ array bool
+}
+
+func (f *decFnInfo) builtin(rv reflect.Value) {
+ f.dd.decodeBuiltin(f.ti.rtid, rv.Addr().Interface())
+}
+
+func (f *decFnInfo) rawExt(rv reflect.Value) {
+ xtag, xbs := f.dd.decodeExt(false, 0)
+ rv.Field(0).SetUint(uint64(xtag))
+ rv.Field(1).SetBytes(xbs)
+}
+
+func (f *decFnInfo) ext(rv reflect.Value) {
+ _, xbs := f.dd.decodeExt(true, f.xfTag)
+ if fnerr := f.xfFn(rv, xbs); fnerr != nil {
+ panic(fnerr)
+ }
+}
+
+func (f *decFnInfo) binaryMarshal(rv reflect.Value) {
+ var bm binaryUnmarshaler
+ if f.ti.unmIndir == -1 {
+ bm = rv.Addr().Interface().(binaryUnmarshaler)
+ } else if f.ti.unmIndir == 0 {
+ bm = rv.Interface().(binaryUnmarshaler)
+ } else {
+ for j, k := int8(0), f.ti.unmIndir; j < k; j++ {
+ if rv.IsNil() {
+ rv.Set(reflect.New(rv.Type().Elem()))
+ }
+ rv = rv.Elem()
+ }
+ bm = rv.Interface().(binaryUnmarshaler)
+ }
+ xbs, _ := f.dd.decodeBytes(nil)
+ if fnerr := bm.UnmarshalBinary(xbs); fnerr != nil {
+ panic(fnerr)
+ }
+}
+
+func (f *decFnInfo) kErr(rv reflect.Value) {
+ decErr("Unhandled value for kind: %v: %s", rv.Kind(), msgBadDesc)
+}
+
+func (f *decFnInfo) kString(rv reflect.Value) {
+ rv.SetString(f.dd.decodeString())
+}
+
+func (f *decFnInfo) kBool(rv reflect.Value) {
+ rv.SetBool(f.dd.decodeBool())
+}
+
+func (f *decFnInfo) kInt(rv reflect.Value) {
+ rv.SetInt(f.dd.decodeInt(intBitsize))
+}
+
+func (f *decFnInfo) kInt64(rv reflect.Value) {
+ rv.SetInt(f.dd.decodeInt(64))
+}
+
+func (f *decFnInfo) kInt32(rv reflect.Value) {
+ rv.SetInt(f.dd.decodeInt(32))
+}
+
+func (f *decFnInfo) kInt8(rv reflect.Value) {
+ rv.SetInt(f.dd.decodeInt(8))
+}
+
+func (f *decFnInfo) kInt16(rv reflect.Value) {
+ rv.SetInt(f.dd.decodeInt(16))
+}
+
+func (f *decFnInfo) kFloat32(rv reflect.Value) {
+ rv.SetFloat(f.dd.decodeFloat(true))
+}
+
+func (f *decFnInfo) kFloat64(rv reflect.Value) {
+ rv.SetFloat(f.dd.decodeFloat(false))
+}
+
+func (f *decFnInfo) kUint8(rv reflect.Value) {
+ rv.SetUint(f.dd.decodeUint(8))
+}
+
+func (f *decFnInfo) kUint64(rv reflect.Value) {
+ rv.SetUint(f.dd.decodeUint(64))
+}
+
+func (f *decFnInfo) kUint(rv reflect.Value) {
+ rv.SetUint(f.dd.decodeUint(uintBitsize))
+}
+
+func (f *decFnInfo) kUint32(rv reflect.Value) {
+ rv.SetUint(f.dd.decodeUint(32))
+}
+
+func (f *decFnInfo) kUint16(rv reflect.Value) {
+ rv.SetUint(f.dd.decodeUint(16))
+}
+
+// func (f *decFnInfo) kPtr(rv reflect.Value) {
+// debugf(">>>>>>> ??? decode kPtr called - shouldn't get called")
+// if rv.IsNil() {
+// rv.Set(reflect.New(rv.Type().Elem()))
+// }
+// f.d.decodeValue(rv.Elem())
+// }
+
+func (f *decFnInfo) kInterface(rv reflect.Value) {
+ // debugf("\t===> kInterface")
+ if !rv.IsNil() {
+ f.d.decodeValue(rv.Elem())
+ return
+ }
+ // nil interface:
+ // use some hieristics to set the nil interface to an
+ // appropriate value based on the first byte read (byte descriptor bd)
+ v, vt, decodeFurther := f.dd.decodeNaked()
+ if vt == valueTypeNil {
+ return
+ }
+ // Cannot decode into nil interface with methods (e.g. error, io.Reader, etc)
+ // if non-nil value in stream.
+ if num := f.ti.rt.NumMethod(); num > 0 {
+ decErr("decodeValue: Cannot decode non-nil codec value into nil %v (%v methods)",
+ f.ti.rt, num)
+ }
+ var rvn reflect.Value
+ var useRvn bool
+ switch vt {
+ case valueTypeMap:
+ if f.d.h.MapType == nil {
+ var m2 map[interface{}]interface{}
+ v = &m2
+ } else {
+ rvn = reflect.New(f.d.h.MapType).Elem()
+ useRvn = true
+ }
+ case valueTypeArray:
+ if f.d.h.SliceType == nil {
+ var m2 []interface{}
+ v = &m2
+ } else {
+ rvn = reflect.New(f.d.h.SliceType).Elem()
+ useRvn = true
+ }
+ case valueTypeExt:
+ re := v.(*RawExt)
+ var bfn func(reflect.Value, []byte) error
+ rvn, bfn = f.d.h.getDecodeExtForTag(re.Tag)
+ if bfn == nil {
+ rvn = reflect.ValueOf(*re)
+ } else if fnerr := bfn(rvn, re.Data); fnerr != nil {
+ panic(fnerr)
+ }
+ rv.Set(rvn)
+ return
+ }
+ if decodeFurther {
+ if useRvn {
+ f.d.decodeValue(rvn)
+ } else if v != nil {
+ // this v is a pointer, so we need to dereference it when done
+ f.d.decode(v)
+ rvn = reflect.ValueOf(v).Elem()
+ useRvn = true
+ }
+ }
+ if useRvn {
+ rv.Set(rvn)
+ } else if v != nil {
+ rv.Set(reflect.ValueOf(v))
+ }
+}
+
+func (f *decFnInfo) kStruct(rv reflect.Value) {
+ fti := f.ti
+ if currEncodedType := f.dd.currentEncodedType(); currEncodedType == valueTypeMap {
+ containerLen := f.dd.readMapLen()
+ if containerLen == 0 {
+ return
+ }
+ tisfi := fti.sfi
+ for j := 0; j < containerLen; j++ {
+ // var rvkencname string
+ // ddecode(&rvkencname)
+ f.dd.initReadNext()
+ rvkencname := f.dd.decodeString()
+ // rvksi := ti.getForEncName(rvkencname)
+ if k := fti.indexForEncName(rvkencname); k > -1 {
+ sfik := tisfi[k]
+ if sfik.i != -1 {
+ f.d.decodeValue(rv.Field(int(sfik.i)))
+ } else {
+ f.d.decEmbeddedField(rv, sfik.is)
+ }
+ // f.d.decodeValue(ti.field(k, rv))
+ } else {
+ if f.d.h.ErrorIfNoField {
+ decErr("No matching struct field found when decoding stream map with key: %v",
+ rvkencname)
+ } else {
+ var nilintf0 interface{}
+ f.d.decodeValue(reflect.ValueOf(&nilintf0).Elem())
+ }
+ }
+ }
+ } else if currEncodedType == valueTypeArray {
+ containerLen := f.dd.readArrayLen()
+ if containerLen == 0 {
+ return
+ }
+ for j, si := range fti.sfip {
+ if j == containerLen {
+ break
+ }
+ if si.i != -1 {
+ f.d.decodeValue(rv.Field(int(si.i)))
+ } else {
+ f.d.decEmbeddedField(rv, si.is)
+ }
+ }
+ if containerLen > len(fti.sfip) {
+ // read remaining values and throw away
+ for j := len(fti.sfip); j < containerLen; j++ {
+ var nilintf0 interface{}
+ f.d.decodeValue(reflect.ValueOf(&nilintf0).Elem())
+ }
+ }
+ } else {
+ decErr("Only encoded map or array can be decoded into a struct. (valueType: %x)",
+ currEncodedType)
+ }
+}
+
+func (f *decFnInfo) kSlice(rv reflect.Value) {
+ // A slice can be set from a map or array in stream.
+ currEncodedType := f.dd.currentEncodedType()
+
+ switch currEncodedType {
+ case valueTypeBytes, valueTypeString:
+ if f.ti.rtid == uint8SliceTypId || f.ti.rt.Elem().Kind() == reflect.Uint8 {
+ if bs2, changed2 := f.dd.decodeBytes(rv.Bytes()); changed2 {
+ rv.SetBytes(bs2)
+ }
+ return
+ }
+ }
+
+ if shortCircuitReflectToFastPath && rv.CanAddr() {
+ switch f.ti.rtid {
+ case intfSliceTypId:
+ f.d.decSliceIntf(rv.Addr().Interface().(*[]interface{}), currEncodedType, f.array)
+ return
+ case uint64SliceTypId:
+ f.d.decSliceUint64(rv.Addr().Interface().(*[]uint64), currEncodedType, f.array)
+ return
+ case int64SliceTypId:
+ f.d.decSliceInt64(rv.Addr().Interface().(*[]int64), currEncodedType, f.array)
+ return
+ case strSliceTypId:
+ f.d.decSliceStr(rv.Addr().Interface().(*[]string), currEncodedType, f.array)
+ return
+ }
+ }
+
+ containerLen, containerLenS := decContLens(f.dd, currEncodedType)
+
+ // an array can never return a nil slice. so no need to check f.array here.
+
+ if rv.IsNil() {
+ rv.Set(reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS))
+ }
+
+ if containerLen == 0 {
+ return
+ }
+
+ if rvcap, rvlen := rv.Len(), rv.Cap(); containerLenS > rvcap {
+ if f.array { // !rv.CanSet()
+ decErr(msgDecCannotExpandArr, rvcap, containerLenS)
+ }
+ rvn := reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS)
+ if rvlen > 0 {
+ reflect.Copy(rvn, rv)
+ }
+ rv.Set(rvn)
+ } else if containerLenS > rvlen {
+ rv.SetLen(containerLenS)
+ }
+
+ for j := 0; j < containerLenS; j++ {
+ f.d.decodeValue(rv.Index(j))
+ }
+}
+
+func (f *decFnInfo) kArray(rv reflect.Value) {
+ // f.d.decodeValue(rv.Slice(0, rv.Len()))
+ f.kSlice(rv.Slice(0, rv.Len()))
+}
+
+func (f *decFnInfo) kMap(rv reflect.Value) {
+ if shortCircuitReflectToFastPath && rv.CanAddr() {
+ switch f.ti.rtid {
+ case mapStrIntfTypId:
+ f.d.decMapStrIntf(rv.Addr().Interface().(*map[string]interface{}))
+ return
+ case mapIntfIntfTypId:
+ f.d.decMapIntfIntf(rv.Addr().Interface().(*map[interface{}]interface{}))
+ return
+ case mapInt64IntfTypId:
+ f.d.decMapInt64Intf(rv.Addr().Interface().(*map[int64]interface{}))
+ return
+ case mapUint64IntfTypId:
+ f.d.decMapUint64Intf(rv.Addr().Interface().(*map[uint64]interface{}))
+ return
+ }
+ }
+
+ containerLen := f.dd.readMapLen()
+
+ if rv.IsNil() {
+ rv.Set(reflect.MakeMap(f.ti.rt))
+ }
+
+ if containerLen == 0 {
+ return
+ }
+
+ ktype, vtype := f.ti.rt.Key(), f.ti.rt.Elem()
+ ktypeId := reflect.ValueOf(ktype).Pointer()
+ for j := 0; j < containerLen; j++ {
+ rvk := reflect.New(ktype).Elem()
+ f.d.decodeValue(rvk)
+
+ // special case if a byte array.
+ // if ktype == intfTyp {
+ if ktypeId == intfTypId {
+ rvk = rvk.Elem()
+ if rvk.Type() == uint8SliceTyp {
+ rvk = reflect.ValueOf(string(rvk.Bytes()))
+ }
+ }
+ rvv := rv.MapIndex(rvk)
+ if !rvv.IsValid() {
+ rvv = reflect.New(vtype).Elem()
+ }
+
+ f.d.decodeValue(rvv)
+ rv.SetMapIndex(rvk, rvv)
+ }
+}
+
+// ----------------------------------------
+
+type decFn struct {
+ i *decFnInfo
+ f func(*decFnInfo, reflect.Value)
+}
+
+// A Decoder reads and decodes an object from an input stream in the codec format.
+type Decoder struct {
+ r decReader
+ d decDriver
+ h *BasicHandle
+ f map[uintptr]decFn
+ x []uintptr
+ s []decFn
+}
+
+// NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
+//
+// For efficiency, Users are encouraged to pass in a memory buffered writer
+// (eg bufio.Reader, bytes.Buffer).
+func NewDecoder(r io.Reader, h Handle) *Decoder {
+ z := ioDecReader{
+ r: r,
+ }
+ z.br, _ = r.(io.ByteReader)
+ return &Decoder{r: &z, d: h.newDecDriver(&z), h: h.getBasicHandle()}
+}
+
+// NewDecoderBytes returns a Decoder which efficiently decodes directly
+// from a byte slice with zero copying.
+func NewDecoderBytes(in []byte, h Handle) *Decoder {
+ z := bytesDecReader{
+ b: in,
+ a: len(in),
+ }
+ return &Decoder{r: &z, d: h.newDecDriver(&z), h: h.getBasicHandle()}
+}
+
+// Decode decodes the stream from reader and stores the result in the
+// value pointed to by v. v cannot be a nil pointer. v can also be
+// a reflect.Value of a pointer.
+//
+// Note that a pointer to a nil interface is not a nil pointer.
+// If you do not know what type of stream it is, pass in a pointer to a nil interface.
+// We will decode and store a value in that nil interface.
+//
+// Sample usages:
+// // Decoding into a non-nil typed value
+// var f float32
+// err = codec.NewDecoder(r, handle).Decode(&f)
+//
+// // Decoding into nil interface
+// var v interface{}
+// dec := codec.NewDecoder(r, handle)
+// err = dec.Decode(&v)
+//
+// When decoding into a nil interface{}, we will decode into an appropriate value based
+// on the contents of the stream:
+// - Numbers are decoded as float64, int64 or uint64.
+// - Other values are decoded appropriately depending on the type:
+// bool, string, []byte, time.Time, etc
+// - Extensions are decoded as RawExt (if no ext function registered for the tag)
+// Configurations exist on the Handle to override defaults
+// (e.g. for MapType, SliceType and how to decode raw bytes).
+//
+// When decoding into a non-nil interface{} value, the mode of encoding is based on the
+// type of the value. When a value is seen:
+// - If an extension is registered for it, call that extension function
+// - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
+// - Else decode it based on its reflect.Kind
+//
+// There are some special rules when decoding into containers (slice/array/map/struct).
+// Decode will typically use the stream contents to UPDATE the container.
+// - A map can be decoded from a stream map, by updating matching keys.
+// - A slice can be decoded from a stream array,
+// by updating the first n elements, where n is length of the stream.
+// - A slice can be decoded from a stream map, by decoding as if
+// it contains a sequence of key-value pairs.
+// - A struct can be decoded from a stream map, by updating matching fields.
+// - A struct can be decoded from a stream array,
+// by updating fields as they occur in the struct (by index).
+//
+// When decoding a stream map or array with length of 0 into a nil map or slice,
+// we reset the destination map or slice to a zero-length value.
+//
+// However, when decoding a stream nil, we reset the destination container
+// to its "zero" value (e.g. nil for slice/map, etc).
+//
+func (d *Decoder) Decode(v interface{}) (err error) {
+ defer panicToErr(&err)
+ d.decode(v)
+ return
+}
+
+func (d *Decoder) decode(iv interface{}) {
+ d.d.initReadNext()
+
+ switch v := iv.(type) {
+ case nil:
+ decErr("Cannot decode into nil.")
+
+ case reflect.Value:
+ d.chkPtrValue(v)
+ d.decodeValue(v.Elem())
+
+ case *string:
+ *v = d.d.decodeString()
+ case *bool:
+ *v = d.d.decodeBool()
+ case *int:
+ *v = int(d.d.decodeInt(intBitsize))
+ case *int8:
+ *v = int8(d.d.decodeInt(8))
+ case *int16:
+ *v = int16(d.d.decodeInt(16))
+ case *int32:
+ *v = int32(d.d.decodeInt(32))
+ case *int64:
+ *v = d.d.decodeInt(64)
+ case *uint:
+ *v = uint(d.d.decodeUint(uintBitsize))
+ case *uint8:
+ *v = uint8(d.d.decodeUint(8))
+ case *uint16:
+ *v = uint16(d.d.decodeUint(16))
+ case *uint32:
+ *v = uint32(d.d.decodeUint(32))
+ case *uint64:
+ *v = d.d.decodeUint(64)
+ case *float32:
+ *v = float32(d.d.decodeFloat(true))
+ case *float64:
+ *v = d.d.decodeFloat(false)
+ case *[]byte:
+ *v, _ = d.d.decodeBytes(*v)
+
+ case *[]interface{}:
+ d.decSliceIntf(v, valueTypeInvalid, false)
+ case *[]uint64:
+ d.decSliceUint64(v, valueTypeInvalid, false)
+ case *[]int64:
+ d.decSliceInt64(v, valueTypeInvalid, false)
+ case *[]string:
+ d.decSliceStr(v, valueTypeInvalid, false)
+ case *map[string]interface{}:
+ d.decMapStrIntf(v)
+ case *map[interface{}]interface{}:
+ d.decMapIntfIntf(v)
+ case *map[uint64]interface{}:
+ d.decMapUint64Intf(v)
+ case *map[int64]interface{}:
+ d.decMapInt64Intf(v)
+
+ case *interface{}:
+ d.decodeValue(reflect.ValueOf(iv).Elem())
+
+ default:
+ rv := reflect.ValueOf(iv)
+ d.chkPtrValue(rv)
+ d.decodeValue(rv.Elem())
+ }
+}
+
+func (d *Decoder) decodeValue(rv reflect.Value) {
+ d.d.initReadNext()
+
+ if d.d.tryDecodeAsNil() {
+ // If value in stream is nil, set the dereferenced value to its "zero" value (if settable)
+ if rv.Kind() == reflect.Ptr {
+ if !rv.IsNil() {
+ rv.Set(reflect.Zero(rv.Type()))
+ }
+ return
+ }
+ // for rv.Kind() == reflect.Ptr {
+ // rv = rv.Elem()
+ // }
+ if rv.IsValid() { // rv.CanSet() // always settable, except it's invalid
+ rv.Set(reflect.Zero(rv.Type()))
+ }
+ return
+ }
+
+ // If stream is not containing a nil value, then we can deref to the base
+ // non-pointer value, and decode into that.
+ for rv.Kind() == reflect.Ptr {
+ if rv.IsNil() {
+ rv.Set(reflect.New(rv.Type().Elem()))
+ }
+ rv = rv.Elem()
+ }
+
+ rt := rv.Type()
+ rtid := reflect.ValueOf(rt).Pointer()
+
+ // retrieve or register a focus'ed function for this type
+ // to eliminate need to do the retrieval multiple times
+
+ // if d.f == nil && d.s == nil { debugf("---->Creating new dec f map for type: %v\n", rt) }
+ var fn decFn
+ var ok bool
+ if useMapForCodecCache {
+ fn, ok = d.f[rtid]
+ } else {
+ for i, v := range d.x {
+ if v == rtid {
+ fn, ok = d.s[i], true
+ break
+ }
+ }
+ }
+ if !ok {
+ // debugf("\tCreating new dec fn for type: %v\n", rt)
+ fi := decFnInfo{ti: getTypeInfo(rtid, rt), d: d, dd: d.d}
+ fn.i = &fi
+ // An extension can be registered for any type, regardless of the Kind
+ // (e.g. type BitSet int64, type MyStruct { / * unexported fields * / }, type X []int, etc.
+ //
+ // We can't check if it's an extension byte here first, because the user may have
+ // registered a pointer or non-pointer type, meaning we may have to recurse first
+ // before matching a mapped type, even though the extension byte is already detected.
+ //
+ // NOTE: if decoding into a nil interface{}, we return a non-nil
+ // value except even if the container registers a length of 0.
+ if rtid == rawExtTypId {
+ fn.f = (*decFnInfo).rawExt
+ } else if d.d.isBuiltinType(rtid) {
+ fn.f = (*decFnInfo).builtin
+ } else if xfTag, xfFn := d.h.getDecodeExt(rtid); xfFn != nil {
+ fi.xfTag, fi.xfFn = xfTag, xfFn
+ fn.f = (*decFnInfo).ext
+ } else if supportBinaryMarshal && fi.ti.unm {
+ fn.f = (*decFnInfo).binaryMarshal
+ } else {
+ switch rk := rt.Kind(); rk {
+ case reflect.String:
+ fn.f = (*decFnInfo).kString
+ case reflect.Bool:
+ fn.f = (*decFnInfo).kBool
+ case reflect.Int:
+ fn.f = (*decFnInfo).kInt
+ case reflect.Int64:
+ fn.f = (*decFnInfo).kInt64
+ case reflect.Int32:
+ fn.f = (*decFnInfo).kInt32
+ case reflect.Int8:
+ fn.f = (*decFnInfo).kInt8
+ case reflect.Int16:
+ fn.f = (*decFnInfo).kInt16
+ case reflect.Float32:
+ fn.f = (*decFnInfo).kFloat32
+ case reflect.Float64:
+ fn.f = (*decFnInfo).kFloat64
+ case reflect.Uint8:
+ fn.f = (*decFnInfo).kUint8
+ case reflect.Uint64:
+ fn.f = (*decFnInfo).kUint64
+ case reflect.Uint:
+ fn.f = (*decFnInfo).kUint
+ case reflect.Uint32:
+ fn.f = (*decFnInfo).kUint32
+ case reflect.Uint16:
+ fn.f = (*decFnInfo).kUint16
+ // case reflect.Ptr:
+ // fn.f = (*decFnInfo).kPtr
+ case reflect.Interface:
+ fn.f = (*decFnInfo).kInterface
+ case reflect.Struct:
+ fn.f = (*decFnInfo).kStruct
+ case reflect.Slice:
+ fn.f = (*decFnInfo).kSlice
+ case reflect.Array:
+ fi.array = true
+ fn.f = (*decFnInfo).kArray
+ case reflect.Map:
+ fn.f = (*decFnInfo).kMap
+ default:
+ fn.f = (*decFnInfo).kErr
+ }
+ }
+ if useMapForCodecCache {
+ if d.f == nil {
+ d.f = make(map[uintptr]decFn, 16)
+ }
+ d.f[rtid] = fn
+ } else {
+ d.s = append(d.s, fn)
+ d.x = append(d.x, rtid)
+ }
+ }
+
+ fn.f(fn.i, rv)
+
+ return
+}
+
+func (d *Decoder) chkPtrValue(rv reflect.Value) {
+ // We can only decode into a non-nil pointer
+ if rv.Kind() == reflect.Ptr && !rv.IsNil() {
+ return
+ }
+ if !rv.IsValid() {
+ decErr("Cannot decode into a zero (ie invalid) reflect.Value")
+ }
+ if !rv.CanInterface() {
+ decErr("Cannot decode into a value without an interface: %v", rv)
+ }
+ rvi := rv.Interface()
+ decErr("Cannot decode into non-pointer or nil pointer. Got: %v, %T, %v",
+ rv.Kind(), rvi, rvi)
+}
+
+func (d *Decoder) decEmbeddedField(rv reflect.Value, index []int) {
+ // d.decodeValue(rv.FieldByIndex(index))
+ // nil pointers may be here; so reproduce FieldByIndex logic + enhancements
+ for _, j := range index {
+ if rv.Kind() == reflect.Ptr {
+ if rv.IsNil() {
+ rv.Set(reflect.New(rv.Type().Elem()))
+ }
+ // If a pointer, it must be a pointer to struct (based on typeInfo contract)
+ rv = rv.Elem()
+ }
+ rv = rv.Field(j)
+ }
+ d.decodeValue(rv)
+}
+
+// --------------------------------------------------
+
+// short circuit functions for common maps and slices
+
+func (d *Decoder) decSliceIntf(v *[]interface{}, currEncodedType valueType, doNotReset bool) {
+ _, containerLenS := decContLens(d.d, currEncodedType)
+ s := *v
+ if s == nil {
+ s = make([]interface{}, containerLenS, containerLenS)
+ } else if containerLenS > cap(s) {
+ if doNotReset {
+ decErr(msgDecCannotExpandArr, cap(s), containerLenS)
+ }
+ s = make([]interface{}, containerLenS, containerLenS)
+ copy(s, *v)
+ } else if containerLenS > len(s) {
+ s = s[:containerLenS]
+ }
+ for j := 0; j < containerLenS; j++ {
+ d.decode(&s[j])
+ }
+ *v = s
+}
+
+func (d *Decoder) decSliceInt64(v *[]int64, currEncodedType valueType, doNotReset bool) {
+ _, containerLenS := decContLens(d.d, currEncodedType)
+ s := *v
+ if s == nil {
+ s = make([]int64, containerLenS, containerLenS)
+ } else if containerLenS > cap(s) {
+ if doNotReset {
+ decErr(msgDecCannotExpandArr, cap(s), containerLenS)
+ }
+ s = make([]int64, containerLenS, containerLenS)
+ copy(s, *v)
+ } else if containerLenS > len(s) {
+ s = s[:containerLenS]
+ }
+ for j := 0; j < containerLenS; j++ {
+ // d.decode(&s[j])
+ d.d.initReadNext()
+ s[j] = d.d.decodeInt(intBitsize)
+ }
+ *v = s
+}
+
+func (d *Decoder) decSliceUint64(v *[]uint64, currEncodedType valueType, doNotReset bool) {
+ _, containerLenS := decContLens(d.d, currEncodedType)
+ s := *v
+ if s == nil {
+ s = make([]uint64, containerLenS, containerLenS)
+ } else if containerLenS > cap(s) {
+ if doNotReset {
+ decErr(msgDecCannotExpandArr, cap(s), containerLenS)
+ }
+ s = make([]uint64, containerLenS, containerLenS)
+ copy(s, *v)
+ } else if containerLenS > len(s) {
+ s = s[:containerLenS]
+ }
+ for j := 0; j < containerLenS; j++ {
+ // d.decode(&s[j])
+ d.d.initReadNext()
+ s[j] = d.d.decodeUint(intBitsize)
+ }
+ *v = s
+}
+
+func (d *Decoder) decSliceStr(v *[]string, currEncodedType valueType, doNotReset bool) {
+ _, containerLenS := decContLens(d.d, currEncodedType)
+ s := *v
+ if s == nil {
+ s = make([]string, containerLenS, containerLenS)
+ } else if containerLenS > cap(s) {
+ if doNotReset {
+ decErr(msgDecCannotExpandArr, cap(s), containerLenS)
+ }
+ s = make([]string, containerLenS, containerLenS)
+ copy(s, *v)
+ } else if containerLenS > len(s) {
+ s = s[:containerLenS]
+ }
+ for j := 0; j < containerLenS; j++ {
+ // d.decode(&s[j])
+ d.d.initReadNext()
+ s[j] = d.d.decodeString()
+ }
+ *v = s
+}
+
+func (d *Decoder) decMapIntfIntf(v *map[interface{}]interface{}) {
+ containerLen := d.d.readMapLen()
+ m := *v
+ if m == nil {
+ m = make(map[interface{}]interface{}, containerLen)
+ *v = m
+ }
+ for j := 0; j < containerLen; j++ {
+ var mk interface{}
+ d.decode(&mk)
+ // special case if a byte array.
+ if bv, bok := mk.([]byte); bok {
+ mk = string(bv)
+ }
+ mv := m[mk]
+ d.decode(&mv)
+ m[mk] = mv
+ }
+}
+
+func (d *Decoder) decMapInt64Intf(v *map[int64]interface{}) {
+ containerLen := d.d.readMapLen()
+ m := *v
+ if m == nil {
+ m = make(map[int64]interface{}, containerLen)
+ *v = m
+ }
+ for j := 0; j < containerLen; j++ {
+ d.d.initReadNext()
+ mk := d.d.decodeInt(intBitsize)
+ mv := m[mk]
+ d.decode(&mv)
+ m[mk] = mv
+ }
+}
+
+func (d *Decoder) decMapUint64Intf(v *map[uint64]interface{}) {
+ containerLen := d.d.readMapLen()
+ m := *v
+ if m == nil {
+ m = make(map[uint64]interface{}, containerLen)
+ *v = m
+ }
+ for j := 0; j < containerLen; j++ {
+ d.d.initReadNext()
+ mk := d.d.decodeUint(intBitsize)
+ mv := m[mk]
+ d.decode(&mv)
+ m[mk] = mv
+ }
+}
+
+func (d *Decoder) decMapStrIntf(v *map[string]interface{}) {
+ containerLen := d.d.readMapLen()
+ m := *v
+ if m == nil {
+ m = make(map[string]interface{}, containerLen)
+ *v = m
+ }
+ for j := 0; j < containerLen; j++ {
+ d.d.initReadNext()
+ mk := d.d.decodeString()
+ mv := m[mk]
+ d.decode(&mv)
+ m[mk] = mv
+ }
+}
+
+// ----------------------------------------
+
+func decContLens(dd decDriver, currEncodedType valueType) (containerLen, containerLenS int) {
+ if currEncodedType == valueTypeInvalid {
+ currEncodedType = dd.currentEncodedType()
+ }
+ switch currEncodedType {
+ case valueTypeArray:
+ containerLen = dd.readArrayLen()
+ containerLenS = containerLen
+ case valueTypeMap:
+ containerLen = dd.readMapLen()
+ containerLenS = containerLen * 2
+ default:
+ decErr("Only encoded map or array can be decoded into a slice. (valueType: %0x)",
+ currEncodedType)
+ }
+ return
+}
+
+func decErr(format string, params ...interface{}) {
+ doPanic(msgTagDec, format, params...)
+}
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/encode.go b/vendor/github.com/hashicorp/go-msgpack/codec/encode.go
new file mode 100644
index 0000000..4914be0
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/encode.go
@@ -0,0 +1,1001 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import (
+ "io"
+ "reflect"
+)
+
+const (
+ // Some tagging information for error messages.
+ msgTagEnc = "codec.encoder"
+ defEncByteBufSize = 1 << 6 // 4:16, 6:64, 8:256, 10:1024
+ // maxTimeSecs32 = math.MaxInt32 / 60 / 24 / 366
+)
+
+// AsSymbolFlag defines what should be encoded as symbols.
+type AsSymbolFlag uint8
+
+const (
+ // AsSymbolDefault is default.
+ // Currently, this means only encode struct field names as symbols.
+ // The default is subject to change.
+ AsSymbolDefault AsSymbolFlag = iota
+
+ // AsSymbolAll means encode anything which could be a symbol as a symbol.
+ AsSymbolAll = 0xfe
+
+ // AsSymbolNone means do not encode anything as a symbol.
+ AsSymbolNone = 1 << iota
+
+ // AsSymbolMapStringKeys means encode keys in map[string]XXX as symbols.
+ AsSymbolMapStringKeysFlag
+
+ // AsSymbolStructFieldName means encode struct field names as symbols.
+ AsSymbolStructFieldNameFlag
+)
+
+// encWriter abstracting writing to a byte array or to an io.Writer.
+type encWriter interface {
+ writeUint16(uint16)
+ writeUint32(uint32)
+ writeUint64(uint64)
+ writeb([]byte)
+ writestr(string)
+ writen1(byte)
+ writen2(byte, byte)
+ atEndOfEncode()
+}
+
+// encDriver abstracts the actual codec (binc vs msgpack, etc)
+type encDriver interface {
+ isBuiltinType(rt uintptr) bool
+ encodeBuiltin(rt uintptr, v interface{})
+ encodeNil()
+ encodeInt(i int64)
+ encodeUint(i uint64)
+ encodeBool(b bool)
+ encodeFloat32(f float32)
+ encodeFloat64(f float64)
+ encodeExtPreamble(xtag byte, length int)
+ encodeArrayPreamble(length int)
+ encodeMapPreamble(length int)
+ encodeString(c charEncoding, v string)
+ encodeSymbol(v string)
+ encodeStringBytes(c charEncoding, v []byte)
+ //TODO
+ //encBignum(f *big.Int)
+ //encStringRunes(c charEncoding, v []rune)
+}
+
+type ioEncWriterWriter interface {
+ WriteByte(c byte) error
+ WriteString(s string) (n int, err error)
+ Write(p []byte) (n int, err error)
+}
+
+type ioEncStringWriter interface {
+ WriteString(s string) (n int, err error)
+}
+
+type EncodeOptions struct {
+ // Encode a struct as an array, and not as a map.
+ StructToArray bool
+
+ // AsSymbols defines what should be encoded as symbols.
+ //
+ // Encoding as symbols can reduce the encoded size significantly.
+ //
+ // However, during decoding, each string to be encoded as a symbol must
+ // be checked to see if it has been seen before. Consequently, encoding time
+ // will increase if using symbols, because string comparisons has a clear cost.
+ //
+ // Sample values:
+ // AsSymbolNone
+ // AsSymbolAll
+ // AsSymbolMapStringKeys
+ // AsSymbolMapStringKeysFlag | AsSymbolStructFieldNameFlag
+ AsSymbols AsSymbolFlag
+}
+
+// ---------------------------------------------
+
+type simpleIoEncWriterWriter struct {
+ w io.Writer
+ bw io.ByteWriter
+ sw ioEncStringWriter
+}
+
+func (o *simpleIoEncWriterWriter) WriteByte(c byte) (err error) {
+ if o.bw != nil {
+ return o.bw.WriteByte(c)
+ }
+ _, err = o.w.Write([]byte{c})
+ return
+}
+
+func (o *simpleIoEncWriterWriter) WriteString(s string) (n int, err error) {
+ if o.sw != nil {
+ return o.sw.WriteString(s)
+ }
+ return o.w.Write([]byte(s))
+}
+
+func (o *simpleIoEncWriterWriter) Write(p []byte) (n int, err error) {
+ return o.w.Write(p)
+}
+
+// ----------------------------------------
+
+// ioEncWriter implements encWriter and can write to an io.Writer implementation
+type ioEncWriter struct {
+ w ioEncWriterWriter
+ x [8]byte // temp byte array re-used internally for efficiency
+}
+
+func (z *ioEncWriter) writeUint16(v uint16) {
+ bigen.PutUint16(z.x[:2], v)
+ z.writeb(z.x[:2])
+}
+
+func (z *ioEncWriter) writeUint32(v uint32) {
+ bigen.PutUint32(z.x[:4], v)
+ z.writeb(z.x[:4])
+}
+
+func (z *ioEncWriter) writeUint64(v uint64) {
+ bigen.PutUint64(z.x[:8], v)
+ z.writeb(z.x[:8])
+}
+
+func (z *ioEncWriter) writeb(bs []byte) {
+ if len(bs) == 0 {
+ return
+ }
+ n, err := z.w.Write(bs)
+ if err != nil {
+ panic(err)
+ }
+ if n != len(bs) {
+ encErr("write: Incorrect num bytes written. Expecting: %v, Wrote: %v", len(bs), n)
+ }
+}
+
+func (z *ioEncWriter) writestr(s string) {
+ n, err := z.w.WriteString(s)
+ if err != nil {
+ panic(err)
+ }
+ if n != len(s) {
+ encErr("write: Incorrect num bytes written. Expecting: %v, Wrote: %v", len(s), n)
+ }
+}
+
+func (z *ioEncWriter) writen1(b byte) {
+ if err := z.w.WriteByte(b); err != nil {
+ panic(err)
+ }
+}
+
+func (z *ioEncWriter) writen2(b1 byte, b2 byte) {
+ z.writen1(b1)
+ z.writen1(b2)
+}
+
+func (z *ioEncWriter) atEndOfEncode() {}
+
+// ----------------------------------------
+
+// bytesEncWriter implements encWriter and can write to an byte slice.
+// It is used by Marshal function.
+type bytesEncWriter struct {
+ b []byte
+ c int // cursor
+ out *[]byte // write out on atEndOfEncode
+}
+
+func (z *bytesEncWriter) writeUint16(v uint16) {
+ c := z.grow(2)
+ z.b[c] = byte(v >> 8)
+ z.b[c+1] = byte(v)
+}
+
+func (z *bytesEncWriter) writeUint32(v uint32) {
+ c := z.grow(4)
+ z.b[c] = byte(v >> 24)
+ z.b[c+1] = byte(v >> 16)
+ z.b[c+2] = byte(v >> 8)
+ z.b[c+3] = byte(v)
+}
+
+func (z *bytesEncWriter) writeUint64(v uint64) {
+ c := z.grow(8)
+ z.b[c] = byte(v >> 56)
+ z.b[c+1] = byte(v >> 48)
+ z.b[c+2] = byte(v >> 40)
+ z.b[c+3] = byte(v >> 32)
+ z.b[c+4] = byte(v >> 24)
+ z.b[c+5] = byte(v >> 16)
+ z.b[c+6] = byte(v >> 8)
+ z.b[c+7] = byte(v)
+}
+
+func (z *bytesEncWriter) writeb(s []byte) {
+ if len(s) == 0 {
+ return
+ }
+ c := z.grow(len(s))
+ copy(z.b[c:], s)
+}
+
+func (z *bytesEncWriter) writestr(s string) {
+ c := z.grow(len(s))
+ copy(z.b[c:], s)
+}
+
+func (z *bytesEncWriter) writen1(b1 byte) {
+ c := z.grow(1)
+ z.b[c] = b1
+}
+
+func (z *bytesEncWriter) writen2(b1 byte, b2 byte) {
+ c := z.grow(2)
+ z.b[c] = b1
+ z.b[c+1] = b2
+}
+
+func (z *bytesEncWriter) atEndOfEncode() {
+ *(z.out) = z.b[:z.c]
+}
+
+func (z *bytesEncWriter) grow(n int) (oldcursor int) {
+ oldcursor = z.c
+ z.c = oldcursor + n
+ if z.c > cap(z.b) {
+ // Tried using appendslice logic: (if cap < 1024, *2, else *1.25).
+ // However, it was too expensive, causing too many iterations of copy.
+ // Using bytes.Buffer model was much better (2*cap + n)
+ bs := make([]byte, 2*cap(z.b)+n)
+ copy(bs, z.b[:oldcursor])
+ z.b = bs
+ } else if z.c > len(z.b) {
+ z.b = z.b[:cap(z.b)]
+ }
+ return
+}
+
+// ---------------------------------------------
+
+type encFnInfo struct {
+ ti *typeInfo
+ e *Encoder
+ ee encDriver
+ xfFn func(reflect.Value) ([]byte, error)
+ xfTag byte
+}
+
+func (f *encFnInfo) builtin(rv reflect.Value) {
+ f.ee.encodeBuiltin(f.ti.rtid, rv.Interface())
+}
+
+func (f *encFnInfo) rawExt(rv reflect.Value) {
+ f.e.encRawExt(rv.Interface().(RawExt))
+}
+
+func (f *encFnInfo) ext(rv reflect.Value) {
+ bs, fnerr := f.xfFn(rv)
+ if fnerr != nil {
+ panic(fnerr)
+ }
+ if bs == nil {
+ f.ee.encodeNil()
+ return
+ }
+ if f.e.hh.writeExt() {
+ f.ee.encodeExtPreamble(f.xfTag, len(bs))
+ f.e.w.writeb(bs)
+ } else {
+ f.ee.encodeStringBytes(c_RAW, bs)
+ }
+
+}
+
+func (f *encFnInfo) binaryMarshal(rv reflect.Value) {
+ var bm binaryMarshaler
+ if f.ti.mIndir == 0 {
+ bm = rv.Interface().(binaryMarshaler)
+ } else if f.ti.mIndir == -1 {
+ bm = rv.Addr().Interface().(binaryMarshaler)
+ } else {
+ for j, k := int8(0), f.ti.mIndir; j < k; j++ {
+ if rv.IsNil() {
+ f.ee.encodeNil()
+ return
+ }
+ rv = rv.Elem()
+ }
+ bm = rv.Interface().(binaryMarshaler)
+ }
+ // debugf(">>>> binaryMarshaler: %T", rv.Interface())
+ bs, fnerr := bm.MarshalBinary()
+ if fnerr != nil {
+ panic(fnerr)
+ }
+ if bs == nil {
+ f.ee.encodeNil()
+ } else {
+ f.ee.encodeStringBytes(c_RAW, bs)
+ }
+}
+
+func (f *encFnInfo) kBool(rv reflect.Value) {
+ f.ee.encodeBool(rv.Bool())
+}
+
+func (f *encFnInfo) kString(rv reflect.Value) {
+ f.ee.encodeString(c_UTF8, rv.String())
+}
+
+func (f *encFnInfo) kFloat64(rv reflect.Value) {
+ f.ee.encodeFloat64(rv.Float())
+}
+
+func (f *encFnInfo) kFloat32(rv reflect.Value) {
+ f.ee.encodeFloat32(float32(rv.Float()))
+}
+
+func (f *encFnInfo) kInt(rv reflect.Value) {
+ f.ee.encodeInt(rv.Int())
+}
+
+func (f *encFnInfo) kUint(rv reflect.Value) {
+ f.ee.encodeUint(rv.Uint())
+}
+
+func (f *encFnInfo) kInvalid(rv reflect.Value) {
+ f.ee.encodeNil()
+}
+
+func (f *encFnInfo) kErr(rv reflect.Value) {
+ encErr("Unsupported kind: %s, for: %#v", rv.Kind(), rv)
+}
+
+func (f *encFnInfo) kSlice(rv reflect.Value) {
+ if rv.IsNil() {
+ f.ee.encodeNil()
+ return
+ }
+
+ if shortCircuitReflectToFastPath {
+ switch f.ti.rtid {
+ case intfSliceTypId:
+ f.e.encSliceIntf(rv.Interface().([]interface{}))
+ return
+ case strSliceTypId:
+ f.e.encSliceStr(rv.Interface().([]string))
+ return
+ case uint64SliceTypId:
+ f.e.encSliceUint64(rv.Interface().([]uint64))
+ return
+ case int64SliceTypId:
+ f.e.encSliceInt64(rv.Interface().([]int64))
+ return
+ }
+ }
+
+ // If in this method, then there was no extension function defined.
+ // So it's okay to treat as []byte.
+ if f.ti.rtid == uint8SliceTypId || f.ti.rt.Elem().Kind() == reflect.Uint8 {
+ f.ee.encodeStringBytes(c_RAW, rv.Bytes())
+ return
+ }
+
+ l := rv.Len()
+ if f.ti.mbs {
+ if l%2 == 1 {
+ encErr("mapBySlice: invalid length (must be divisible by 2): %v", l)
+ }
+ f.ee.encodeMapPreamble(l / 2)
+ } else {
+ f.ee.encodeArrayPreamble(l)
+ }
+ if l == 0 {
+ return
+ }
+ for j := 0; j < l; j++ {
+ // TODO: Consider perf implication of encoding odd index values as symbols if type is string
+ f.e.encodeValue(rv.Index(j))
+ }
+}
+
+func (f *encFnInfo) kArray(rv reflect.Value) {
+ // We cannot share kSlice method, because the array may be non-addressable.
+ // E.g. type struct S{B [2]byte}; Encode(S{}) will bomb on "panic: slice of unaddressable array".
+ // So we have to duplicate the functionality here.
+ // f.e.encodeValue(rv.Slice(0, rv.Len()))
+ // f.kSlice(rv.Slice(0, rv.Len()))
+
+ l := rv.Len()
+ // Handle an array of bytes specially (in line with what is done for slices)
+ if f.ti.rt.Elem().Kind() == reflect.Uint8 {
+ if l == 0 {
+ f.ee.encodeStringBytes(c_RAW, nil)
+ return
+ }
+ var bs []byte
+ if rv.CanAddr() {
+ bs = rv.Slice(0, l).Bytes()
+ } else {
+ bs = make([]byte, l)
+ for i := 0; i < l; i++ {
+ bs[i] = byte(rv.Index(i).Uint())
+ }
+ }
+ f.ee.encodeStringBytes(c_RAW, bs)
+ return
+ }
+
+ if f.ti.mbs {
+ if l%2 == 1 {
+ encErr("mapBySlice: invalid length (must be divisible by 2): %v", l)
+ }
+ f.ee.encodeMapPreamble(l / 2)
+ } else {
+ f.ee.encodeArrayPreamble(l)
+ }
+ if l == 0 {
+ return
+ }
+ for j := 0; j < l; j++ {
+ // TODO: Consider perf implication of encoding odd index values as symbols if type is string
+ f.e.encodeValue(rv.Index(j))
+ }
+}
+
+func (f *encFnInfo) kStruct(rv reflect.Value) {
+ fti := f.ti
+ newlen := len(fti.sfi)
+ rvals := make([]reflect.Value, newlen)
+ var encnames []string
+ e := f.e
+ tisfi := fti.sfip
+ toMap := !(fti.toArray || e.h.StructToArray)
+ // if toMap, use the sorted array. If toArray, use unsorted array (to match sequence in struct)
+ if toMap {
+ tisfi = fti.sfi
+ encnames = make([]string, newlen)
+ }
+ newlen = 0
+ for _, si := range tisfi {
+ if si.i != -1 {
+ rvals[newlen] = rv.Field(int(si.i))
+ } else {
+ rvals[newlen] = rv.FieldByIndex(si.is)
+ }
+ if toMap {
+ if si.omitEmpty && isEmptyValue(rvals[newlen]) {
+ continue
+ }
+ encnames[newlen] = si.encName
+ } else {
+ if si.omitEmpty && isEmptyValue(rvals[newlen]) {
+ rvals[newlen] = reflect.Value{} //encode as nil
+ }
+ }
+ newlen++
+ }
+
+ // debugf(">>>> kStruct: newlen: %v", newlen)
+ if toMap {
+ ee := f.ee //don't dereference everytime
+ ee.encodeMapPreamble(newlen)
+ // asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
+ asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
+ for j := 0; j < newlen; j++ {
+ if asSymbols {
+ ee.encodeSymbol(encnames[j])
+ } else {
+ ee.encodeString(c_UTF8, encnames[j])
+ }
+ e.encodeValue(rvals[j])
+ }
+ } else {
+ f.ee.encodeArrayPreamble(newlen)
+ for j := 0; j < newlen; j++ {
+ e.encodeValue(rvals[j])
+ }
+ }
+}
+
+// func (f *encFnInfo) kPtr(rv reflect.Value) {
+// debugf(">>>>>>> ??? encode kPtr called - shouldn't get called")
+// if rv.IsNil() {
+// f.ee.encodeNil()
+// return
+// }
+// f.e.encodeValue(rv.Elem())
+// }
+
+func (f *encFnInfo) kInterface(rv reflect.Value) {
+ if rv.IsNil() {
+ f.ee.encodeNil()
+ return
+ }
+ f.e.encodeValue(rv.Elem())
+}
+
+func (f *encFnInfo) kMap(rv reflect.Value) {
+ if rv.IsNil() {
+ f.ee.encodeNil()
+ return
+ }
+
+ if shortCircuitReflectToFastPath {
+ switch f.ti.rtid {
+ case mapIntfIntfTypId:
+ f.e.encMapIntfIntf(rv.Interface().(map[interface{}]interface{}))
+ return
+ case mapStrIntfTypId:
+ f.e.encMapStrIntf(rv.Interface().(map[string]interface{}))
+ return
+ case mapStrStrTypId:
+ f.e.encMapStrStr(rv.Interface().(map[string]string))
+ return
+ case mapInt64IntfTypId:
+ f.e.encMapInt64Intf(rv.Interface().(map[int64]interface{}))
+ return
+ case mapUint64IntfTypId:
+ f.e.encMapUint64Intf(rv.Interface().(map[uint64]interface{}))
+ return
+ }
+ }
+
+ l := rv.Len()
+ f.ee.encodeMapPreamble(l)
+ if l == 0 {
+ return
+ }
+ // keyTypeIsString := f.ti.rt.Key().Kind() == reflect.String
+ keyTypeIsString := f.ti.rt.Key() == stringTyp
+ var asSymbols bool
+ if keyTypeIsString {
+ asSymbols = f.e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
+ }
+ mks := rv.MapKeys()
+ // for j, lmks := 0, len(mks); j < lmks; j++ {
+ for j := range mks {
+ if keyTypeIsString {
+ if asSymbols {
+ f.ee.encodeSymbol(mks[j].String())
+ } else {
+ f.ee.encodeString(c_UTF8, mks[j].String())
+ }
+ } else {
+ f.e.encodeValue(mks[j])
+ }
+ f.e.encodeValue(rv.MapIndex(mks[j]))
+ }
+
+}
+
+// --------------------------------------------------
+
+// encFn encapsulates the captured variables and the encode function.
+// This way, we only do some calculations one times, and pass to the
+// code block that should be called (encapsulated in a function)
+// instead of executing the checks every time.
+type encFn struct {
+ i *encFnInfo
+ f func(*encFnInfo, reflect.Value)
+}
+
+// --------------------------------------------------
+
+// An Encoder writes an object to an output stream in the codec format.
+type Encoder struct {
+ w encWriter
+ e encDriver
+ h *BasicHandle
+ hh Handle
+ f map[uintptr]encFn
+ x []uintptr
+ s []encFn
+}
+
+// NewEncoder returns an Encoder for encoding into an io.Writer.
+//
+// For efficiency, Users are encouraged to pass in a memory buffered writer
+// (eg bufio.Writer, bytes.Buffer).
+func NewEncoder(w io.Writer, h Handle) *Encoder {
+ ww, ok := w.(ioEncWriterWriter)
+ if !ok {
+ sww := simpleIoEncWriterWriter{w: w}
+ sww.bw, _ = w.(io.ByteWriter)
+ sww.sw, _ = w.(ioEncStringWriter)
+ ww = &sww
+ //ww = bufio.NewWriterSize(w, defEncByteBufSize)
+ }
+ z := ioEncWriter{
+ w: ww,
+ }
+ return &Encoder{w: &z, hh: h, h: h.getBasicHandle(), e: h.newEncDriver(&z)}
+}
+
+// NewEncoderBytes returns an encoder for encoding directly and efficiently
+// into a byte slice, using zero-copying to temporary slices.
+//
+// It will potentially replace the output byte slice pointed to.
+// After encoding, the out parameter contains the encoded contents.
+func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
+ in := *out
+ if in == nil {
+ in = make([]byte, defEncByteBufSize)
+ }
+ z := bytesEncWriter{
+ b: in,
+ out: out,
+ }
+ return &Encoder{w: &z, hh: h, h: h.getBasicHandle(), e: h.newEncDriver(&z)}
+}
+
+// Encode writes an object into a stream in the codec format.
+//
+// Encoding can be configured via the "codec" struct tag for the fields.
+//
+// The "codec" key in struct field's tag value is the key name,
+// followed by an optional comma and options.
+//
+// To set an option on all fields (e.g. omitempty on all fields), you
+// can create a field called _struct, and set flags on it.
+//
+// Struct values "usually" encode as maps. Each exported struct field is encoded unless:
+// - the field's codec tag is "-", OR
+// - the field is empty and its codec tag specifies the "omitempty" option.
+//
+// When encoding as a map, the first string in the tag (before the comma)
+// is the map key string to use when encoding.
+//
+// However, struct values may encode as arrays. This happens when:
+// - StructToArray Encode option is set, OR
+// - the codec tag on the _struct field sets the "toarray" option
+//
+// Values with types that implement MapBySlice are encoded as stream maps.
+//
+// The empty values (for omitempty option) are false, 0, any nil pointer
+// or interface value, and any array, slice, map, or string of length zero.
+//
+// Anonymous fields are encoded inline if no struct tag is present.
+// Else they are encoded as regular fields.
+//
+// Examples:
+//
+// type MyStruct struct {
+// _struct bool `codec:",omitempty"` //set omitempty for every field
+// Field1 string `codec:"-"` //skip this field
+// Field2 int `codec:"myName"` //Use key "myName" in encode stream
+// Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
+// Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
+// ...
+// }
+//
+// type MyStruct struct {
+// _struct bool `codec:",omitempty,toarray"` //set omitempty for every field
+// //and encode struct as an array
+// }
+//
+// The mode of encoding is based on the type of the value. When a value is seen:
+// - If an extension is registered for it, call that extension function
+// - If it implements BinaryMarshaler, call its MarshalBinary() (data []byte, err error)
+// - Else encode it based on its reflect.Kind
+//
+// Note that struct field names and keys in map[string]XXX will be treated as symbols.
+// Some formats support symbols (e.g. binc) and will properly encode the string
+// only once in the stream, and use a tag to refer to it thereafter.
+func (e *Encoder) Encode(v interface{}) (err error) {
+ defer panicToErr(&err)
+ e.encode(v)
+ e.w.atEndOfEncode()
+ return
+}
+
+func (e *Encoder) encode(iv interface{}) {
+ switch v := iv.(type) {
+ case nil:
+ e.e.encodeNil()
+
+ case reflect.Value:
+ e.encodeValue(v)
+
+ case string:
+ e.e.encodeString(c_UTF8, v)
+ case bool:
+ e.e.encodeBool(v)
+ case int:
+ e.e.encodeInt(int64(v))
+ case int8:
+ e.e.encodeInt(int64(v))
+ case int16:
+ e.e.encodeInt(int64(v))
+ case int32:
+ e.e.encodeInt(int64(v))
+ case int64:
+ e.e.encodeInt(v)
+ case uint:
+ e.e.encodeUint(uint64(v))
+ case uint8:
+ e.e.encodeUint(uint64(v))
+ case uint16:
+ e.e.encodeUint(uint64(v))
+ case uint32:
+ e.e.encodeUint(uint64(v))
+ case uint64:
+ e.e.encodeUint(v)
+ case float32:
+ e.e.encodeFloat32(v)
+ case float64:
+ e.e.encodeFloat64(v)
+
+ case []interface{}:
+ e.encSliceIntf(v)
+ case []string:
+ e.encSliceStr(v)
+ case []int64:
+ e.encSliceInt64(v)
+ case []uint64:
+ e.encSliceUint64(v)
+ case []uint8:
+ e.e.encodeStringBytes(c_RAW, v)
+
+ case map[interface{}]interface{}:
+ e.encMapIntfIntf(v)
+ case map[string]interface{}:
+ e.encMapStrIntf(v)
+ case map[string]string:
+ e.encMapStrStr(v)
+ case map[int64]interface{}:
+ e.encMapInt64Intf(v)
+ case map[uint64]interface{}:
+ e.encMapUint64Intf(v)
+
+ case *string:
+ e.e.encodeString(c_UTF8, *v)
+ case *bool:
+ e.e.encodeBool(*v)
+ case *int:
+ e.e.encodeInt(int64(*v))
+ case *int8:
+ e.e.encodeInt(int64(*v))
+ case *int16:
+ e.e.encodeInt(int64(*v))
+ case *int32:
+ e.e.encodeInt(int64(*v))
+ case *int64:
+ e.e.encodeInt(*v)
+ case *uint:
+ e.e.encodeUint(uint64(*v))
+ case *uint8:
+ e.e.encodeUint(uint64(*v))
+ case *uint16:
+ e.e.encodeUint(uint64(*v))
+ case *uint32:
+ e.e.encodeUint(uint64(*v))
+ case *uint64:
+ e.e.encodeUint(*v)
+ case *float32:
+ e.e.encodeFloat32(*v)
+ case *float64:
+ e.e.encodeFloat64(*v)
+
+ case *[]interface{}:
+ e.encSliceIntf(*v)
+ case *[]string:
+ e.encSliceStr(*v)
+ case *[]int64:
+ e.encSliceInt64(*v)
+ case *[]uint64:
+ e.encSliceUint64(*v)
+ case *[]uint8:
+ e.e.encodeStringBytes(c_RAW, *v)
+
+ case *map[interface{}]interface{}:
+ e.encMapIntfIntf(*v)
+ case *map[string]interface{}:
+ e.encMapStrIntf(*v)
+ case *map[string]string:
+ e.encMapStrStr(*v)
+ case *map[int64]interface{}:
+ e.encMapInt64Intf(*v)
+ case *map[uint64]interface{}:
+ e.encMapUint64Intf(*v)
+
+ default:
+ e.encodeValue(reflect.ValueOf(iv))
+ }
+}
+
+func (e *Encoder) encodeValue(rv reflect.Value) {
+ for rv.Kind() == reflect.Ptr {
+ if rv.IsNil() {
+ e.e.encodeNil()
+ return
+ }
+ rv = rv.Elem()
+ }
+
+ rt := rv.Type()
+ rtid := reflect.ValueOf(rt).Pointer()
+
+ // if e.f == nil && e.s == nil { debugf("---->Creating new enc f map for type: %v\n", rt) }
+ var fn encFn
+ var ok bool
+ if useMapForCodecCache {
+ fn, ok = e.f[rtid]
+ } else {
+ for i, v := range e.x {
+ if v == rtid {
+ fn, ok = e.s[i], true
+ break
+ }
+ }
+ }
+ if !ok {
+ // debugf("\tCreating new enc fn for type: %v\n", rt)
+ fi := encFnInfo{ti: getTypeInfo(rtid, rt), e: e, ee: e.e}
+ fn.i = &fi
+ if rtid == rawExtTypId {
+ fn.f = (*encFnInfo).rawExt
+ } else if e.e.isBuiltinType(rtid) {
+ fn.f = (*encFnInfo).builtin
+ } else if xfTag, xfFn := e.h.getEncodeExt(rtid); xfFn != nil {
+ fi.xfTag, fi.xfFn = xfTag, xfFn
+ fn.f = (*encFnInfo).ext
+ } else if supportBinaryMarshal && fi.ti.m {
+ fn.f = (*encFnInfo).binaryMarshal
+ } else {
+ switch rk := rt.Kind(); rk {
+ case reflect.Bool:
+ fn.f = (*encFnInfo).kBool
+ case reflect.String:
+ fn.f = (*encFnInfo).kString
+ case reflect.Float64:
+ fn.f = (*encFnInfo).kFloat64
+ case reflect.Float32:
+ fn.f = (*encFnInfo).kFloat32
+ case reflect.Int, reflect.Int8, reflect.Int64, reflect.Int32, reflect.Int16:
+ fn.f = (*encFnInfo).kInt
+ case reflect.Uint8, reflect.Uint64, reflect.Uint, reflect.Uint32, reflect.Uint16:
+ fn.f = (*encFnInfo).kUint
+ case reflect.Invalid:
+ fn.f = (*encFnInfo).kInvalid
+ case reflect.Slice:
+ fn.f = (*encFnInfo).kSlice
+ case reflect.Array:
+ fn.f = (*encFnInfo).kArray
+ case reflect.Struct:
+ fn.f = (*encFnInfo).kStruct
+ // case reflect.Ptr:
+ // fn.f = (*encFnInfo).kPtr
+ case reflect.Interface:
+ fn.f = (*encFnInfo).kInterface
+ case reflect.Map:
+ fn.f = (*encFnInfo).kMap
+ default:
+ fn.f = (*encFnInfo).kErr
+ }
+ }
+ if useMapForCodecCache {
+ if e.f == nil {
+ e.f = make(map[uintptr]encFn, 16)
+ }
+ e.f[rtid] = fn
+ } else {
+ e.s = append(e.s, fn)
+ e.x = append(e.x, rtid)
+ }
+ }
+
+ fn.f(fn.i, rv)
+
+}
+
+func (e *Encoder) encRawExt(re RawExt) {
+ if re.Data == nil {
+ e.e.encodeNil()
+ return
+ }
+ if e.hh.writeExt() {
+ e.e.encodeExtPreamble(re.Tag, len(re.Data))
+ e.w.writeb(re.Data)
+ } else {
+ e.e.encodeStringBytes(c_RAW, re.Data)
+ }
+}
+
+// ---------------------------------------------
+// short circuit functions for common maps and slices
+
+func (e *Encoder) encSliceIntf(v []interface{}) {
+ e.e.encodeArrayPreamble(len(v))
+ for _, v2 := range v {
+ e.encode(v2)
+ }
+}
+
+func (e *Encoder) encSliceStr(v []string) {
+ e.e.encodeArrayPreamble(len(v))
+ for _, v2 := range v {
+ e.e.encodeString(c_UTF8, v2)
+ }
+}
+
+func (e *Encoder) encSliceInt64(v []int64) {
+ e.e.encodeArrayPreamble(len(v))
+ for _, v2 := range v {
+ e.e.encodeInt(v2)
+ }
+}
+
+func (e *Encoder) encSliceUint64(v []uint64) {
+ e.e.encodeArrayPreamble(len(v))
+ for _, v2 := range v {
+ e.e.encodeUint(v2)
+ }
+}
+
+func (e *Encoder) encMapStrStr(v map[string]string) {
+ e.e.encodeMapPreamble(len(v))
+ asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
+ for k2, v2 := range v {
+ if asSymbols {
+ e.e.encodeSymbol(k2)
+ } else {
+ e.e.encodeString(c_UTF8, k2)
+ }
+ e.e.encodeString(c_UTF8, v2)
+ }
+}
+
+func (e *Encoder) encMapStrIntf(v map[string]interface{}) {
+ e.e.encodeMapPreamble(len(v))
+ asSymbols := e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
+ for k2, v2 := range v {
+ if asSymbols {
+ e.e.encodeSymbol(k2)
+ } else {
+ e.e.encodeString(c_UTF8, k2)
+ }
+ e.encode(v2)
+ }
+}
+
+func (e *Encoder) encMapInt64Intf(v map[int64]interface{}) {
+ e.e.encodeMapPreamble(len(v))
+ for k2, v2 := range v {
+ e.e.encodeInt(k2)
+ e.encode(v2)
+ }
+}
+
+func (e *Encoder) encMapUint64Intf(v map[uint64]interface{}) {
+ e.e.encodeMapPreamble(len(v))
+ for k2, v2 := range v {
+ e.e.encodeUint(uint64(k2))
+ e.encode(v2)
+ }
+}
+
+func (e *Encoder) encMapIntfIntf(v map[interface{}]interface{}) {
+ e.e.encodeMapPreamble(len(v))
+ for k2, v2 := range v {
+ e.encode(k2)
+ e.encode(v2)
+ }
+}
+
+// ----------------------------------------
+
+func encErr(format string, params ...interface{}) {
+ doPanic(msgTagEnc, format, params...)
+}
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/helper.go b/vendor/github.com/hashicorp/go-msgpack/codec/helper.go
new file mode 100644
index 0000000..e6dc056
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/helper.go
@@ -0,0 +1,589 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+// Contains code shared by both encode and decode.
+
+import (
+ "encoding/binary"
+ "fmt"
+ "math"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+ "unicode"
+ "unicode/utf8"
+)
+
+const (
+ structTagName = "codec"
+
+ // Support
+ // encoding.BinaryMarshaler: MarshalBinary() (data []byte, err error)
+ // encoding.BinaryUnmarshaler: UnmarshalBinary(data []byte) error
+ // This constant flag will enable or disable it.
+ supportBinaryMarshal = true
+
+ // Each Encoder or Decoder uses a cache of functions based on conditionals,
+ // so that the conditionals are not run every time.
+ //
+ // Either a map or a slice is used to keep track of the functions.
+ // The map is more natural, but has a higher cost than a slice/array.
+ // This flag (useMapForCodecCache) controls which is used.
+ useMapForCodecCache = false
+
+ // For some common container types, we can short-circuit an elaborate
+ // reflection dance and call encode/decode directly.
+ // The currently supported types are:
+ // - slices of strings, or id's (int64,uint64) or interfaces.
+ // - maps of str->str, str->intf, id(int64,uint64)->intf, intf->intf
+ shortCircuitReflectToFastPath = true
+
+ // for debugging, set this to false, to catch panic traces.
+ // Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic.
+ recoverPanicToErr = true
+)
+
+type charEncoding uint8
+
+const (
+ c_RAW charEncoding = iota
+ c_UTF8
+ c_UTF16LE
+ c_UTF16BE
+ c_UTF32LE
+ c_UTF32BE
+)
+
+// valueType is the stream type
+type valueType uint8
+
+const (
+ valueTypeUnset valueType = iota
+ valueTypeNil
+ valueTypeInt
+ valueTypeUint
+ valueTypeFloat
+ valueTypeBool
+ valueTypeString
+ valueTypeSymbol
+ valueTypeBytes
+ valueTypeMap
+ valueTypeArray
+ valueTypeTimestamp
+ valueTypeExt
+
+ valueTypeInvalid = 0xff
+)
+
+var (
+ bigen = binary.BigEndian
+ structInfoFieldName = "_struct"
+
+ cachedTypeInfo = make(map[uintptr]*typeInfo, 4)
+ cachedTypeInfoMutex sync.RWMutex
+
+ intfSliceTyp = reflect.TypeOf([]interface{}(nil))
+ intfTyp = intfSliceTyp.Elem()
+
+ strSliceTyp = reflect.TypeOf([]string(nil))
+ boolSliceTyp = reflect.TypeOf([]bool(nil))
+ uintSliceTyp = reflect.TypeOf([]uint(nil))
+ uint8SliceTyp = reflect.TypeOf([]uint8(nil))
+ uint16SliceTyp = reflect.TypeOf([]uint16(nil))
+ uint32SliceTyp = reflect.TypeOf([]uint32(nil))
+ uint64SliceTyp = reflect.TypeOf([]uint64(nil))
+ intSliceTyp = reflect.TypeOf([]int(nil))
+ int8SliceTyp = reflect.TypeOf([]int8(nil))
+ int16SliceTyp = reflect.TypeOf([]int16(nil))
+ int32SliceTyp = reflect.TypeOf([]int32(nil))
+ int64SliceTyp = reflect.TypeOf([]int64(nil))
+ float32SliceTyp = reflect.TypeOf([]float32(nil))
+ float64SliceTyp = reflect.TypeOf([]float64(nil))
+
+ mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
+ mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
+ mapStrStrTyp = reflect.TypeOf(map[string]string(nil))
+
+ mapIntIntfTyp = reflect.TypeOf(map[int]interface{}(nil))
+ mapInt64IntfTyp = reflect.TypeOf(map[int64]interface{}(nil))
+ mapUintIntfTyp = reflect.TypeOf(map[uint]interface{}(nil))
+ mapUint64IntfTyp = reflect.TypeOf(map[uint64]interface{}(nil))
+
+ stringTyp = reflect.TypeOf("")
+ timeTyp = reflect.TypeOf(time.Time{})
+ rawExtTyp = reflect.TypeOf(RawExt{})
+
+ mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
+ binaryMarshalerTyp = reflect.TypeOf((*binaryMarshaler)(nil)).Elem()
+ binaryUnmarshalerTyp = reflect.TypeOf((*binaryUnmarshaler)(nil)).Elem()
+
+ rawExtTypId = reflect.ValueOf(rawExtTyp).Pointer()
+ intfTypId = reflect.ValueOf(intfTyp).Pointer()
+ timeTypId = reflect.ValueOf(timeTyp).Pointer()
+
+ intfSliceTypId = reflect.ValueOf(intfSliceTyp).Pointer()
+ strSliceTypId = reflect.ValueOf(strSliceTyp).Pointer()
+
+ boolSliceTypId = reflect.ValueOf(boolSliceTyp).Pointer()
+ uintSliceTypId = reflect.ValueOf(uintSliceTyp).Pointer()
+ uint8SliceTypId = reflect.ValueOf(uint8SliceTyp).Pointer()
+ uint16SliceTypId = reflect.ValueOf(uint16SliceTyp).Pointer()
+ uint32SliceTypId = reflect.ValueOf(uint32SliceTyp).Pointer()
+ uint64SliceTypId = reflect.ValueOf(uint64SliceTyp).Pointer()
+ intSliceTypId = reflect.ValueOf(intSliceTyp).Pointer()
+ int8SliceTypId = reflect.ValueOf(int8SliceTyp).Pointer()
+ int16SliceTypId = reflect.ValueOf(int16SliceTyp).Pointer()
+ int32SliceTypId = reflect.ValueOf(int32SliceTyp).Pointer()
+ int64SliceTypId = reflect.ValueOf(int64SliceTyp).Pointer()
+ float32SliceTypId = reflect.ValueOf(float32SliceTyp).Pointer()
+ float64SliceTypId = reflect.ValueOf(float64SliceTyp).Pointer()
+
+ mapStrStrTypId = reflect.ValueOf(mapStrStrTyp).Pointer()
+ mapIntfIntfTypId = reflect.ValueOf(mapIntfIntfTyp).Pointer()
+ mapStrIntfTypId = reflect.ValueOf(mapStrIntfTyp).Pointer()
+ mapIntIntfTypId = reflect.ValueOf(mapIntIntfTyp).Pointer()
+ mapInt64IntfTypId = reflect.ValueOf(mapInt64IntfTyp).Pointer()
+ mapUintIntfTypId = reflect.ValueOf(mapUintIntfTyp).Pointer()
+ mapUint64IntfTypId = reflect.ValueOf(mapUint64IntfTyp).Pointer()
+ // Id = reflect.ValueOf().Pointer()
+ // mapBySliceTypId = reflect.ValueOf(mapBySliceTyp).Pointer()
+
+ binaryMarshalerTypId = reflect.ValueOf(binaryMarshalerTyp).Pointer()
+ binaryUnmarshalerTypId = reflect.ValueOf(binaryUnmarshalerTyp).Pointer()
+
+ intBitsize uint8 = uint8(reflect.TypeOf(int(0)).Bits())
+ uintBitsize uint8 = uint8(reflect.TypeOf(uint(0)).Bits())
+
+ bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
+ bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
+)
+
+type binaryUnmarshaler interface {
+ UnmarshalBinary(data []byte) error
+}
+
+type binaryMarshaler interface {
+ MarshalBinary() (data []byte, err error)
+}
+
+// MapBySlice represents a slice which should be encoded as a map in the stream.
+// The slice contains a sequence of key-value pairs.
+type MapBySlice interface {
+ MapBySlice()
+}
+
+// WARNING: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
+//
+// BasicHandle encapsulates the common options and extension functions.
+type BasicHandle struct {
+ extHandle
+ EncodeOptions
+ DecodeOptions
+}
+
+// Handle is the interface for a specific encoding format.
+//
+// Typically, a Handle is pre-configured before first time use,
+// and not modified while in use. Such a pre-configured Handle
+// is safe for concurrent access.
+type Handle interface {
+ writeExt() bool
+ getBasicHandle() *BasicHandle
+ newEncDriver(w encWriter) encDriver
+ newDecDriver(r decReader) decDriver
+}
+
+// RawExt represents raw unprocessed extension data.
+type RawExt struct {
+ Tag byte
+ Data []byte
+}
+
+type extTypeTagFn struct {
+ rtid uintptr
+ rt reflect.Type
+ tag byte
+ encFn func(reflect.Value) ([]byte, error)
+ decFn func(reflect.Value, []byte) error
+}
+
+type extHandle []*extTypeTagFn
+
+// AddExt registers an encode and decode function for a reflect.Type.
+// Note that the type must be a named type, and specifically not
+// a pointer or Interface. An error is returned if that is not honored.
+//
+// To Deregister an ext, call AddExt with 0 tag, nil encfn and nil decfn.
+func (o *extHandle) AddExt(
+ rt reflect.Type,
+ tag byte,
+ encfn func(reflect.Value) ([]byte, error),
+ decfn func(reflect.Value, []byte) error,
+) (err error) {
+ // o is a pointer, because we may need to initialize it
+ if rt.PkgPath() == "" || rt.Kind() == reflect.Interface {
+ err = fmt.Errorf("codec.Handle.AddExt: Takes named type, especially not a pointer or interface: %T",
+ reflect.Zero(rt).Interface())
+ return
+ }
+
+ // o cannot be nil, since it is always embedded in a Handle.
+ // if nil, let it panic.
+ // if o == nil {
+ // err = errors.New("codec.Handle.AddExt: extHandle cannot be a nil pointer.")
+ // return
+ // }
+
+ rtid := reflect.ValueOf(rt).Pointer()
+ for _, v := range *o {
+ if v.rtid == rtid {
+ v.tag, v.encFn, v.decFn = tag, encfn, decfn
+ return
+ }
+ }
+
+ *o = append(*o, &extTypeTagFn{rtid, rt, tag, encfn, decfn})
+ return
+}
+
+func (o extHandle) getExt(rtid uintptr) *extTypeTagFn {
+ for _, v := range o {
+ if v.rtid == rtid {
+ return v
+ }
+ }
+ return nil
+}
+
+func (o extHandle) getExtForTag(tag byte) *extTypeTagFn {
+ for _, v := range o {
+ if v.tag == tag {
+ return v
+ }
+ }
+ return nil
+}
+
+func (o extHandle) getDecodeExtForTag(tag byte) (
+ rv reflect.Value, fn func(reflect.Value, []byte) error) {
+ if x := o.getExtForTag(tag); x != nil {
+ // ext is only registered for base
+ rv = reflect.New(x.rt).Elem()
+ fn = x.decFn
+ }
+ return
+}
+
+func (o extHandle) getDecodeExt(rtid uintptr) (tag byte, fn func(reflect.Value, []byte) error) {
+ if x := o.getExt(rtid); x != nil {
+ tag = x.tag
+ fn = x.decFn
+ }
+ return
+}
+
+func (o extHandle) getEncodeExt(rtid uintptr) (tag byte, fn func(reflect.Value) ([]byte, error)) {
+ if x := o.getExt(rtid); x != nil {
+ tag = x.tag
+ fn = x.encFn
+ }
+ return
+}
+
+type structFieldInfo struct {
+ encName string // encode name
+
+ // only one of 'i' or 'is' can be set. If 'i' is -1, then 'is' has been set.
+
+ is []int // (recursive/embedded) field index in struct
+ i int16 // field index in struct
+ omitEmpty bool
+ toArray bool // if field is _struct, is the toArray set?
+
+ // tag string // tag
+ // name string // field name
+ // encNameBs []byte // encoded name as byte stream
+ // ikind int // kind of the field as an int i.e. int(reflect.Kind)
+}
+
+func parseStructFieldInfo(fname string, stag string) *structFieldInfo {
+ if fname == "" {
+ panic("parseStructFieldInfo: No Field Name")
+ }
+ si := structFieldInfo{
+ // name: fname,
+ encName: fname,
+ // tag: stag,
+ }
+
+ if stag != "" {
+ for i, s := range strings.Split(stag, ",") {
+ if i == 0 {
+ if s != "" {
+ si.encName = s
+ }
+ } else {
+ switch s {
+ case "omitempty":
+ si.omitEmpty = true
+ case "toarray":
+ si.toArray = true
+ }
+ }
+ }
+ }
+ // si.encNameBs = []byte(si.encName)
+ return &si
+}
+
+type sfiSortedByEncName []*structFieldInfo
+
+func (p sfiSortedByEncName) Len() int {
+ return len(p)
+}
+
+func (p sfiSortedByEncName) Less(i, j int) bool {
+ return p[i].encName < p[j].encName
+}
+
+func (p sfiSortedByEncName) Swap(i, j int) {
+ p[i], p[j] = p[j], p[i]
+}
+
+// typeInfo keeps information about each type referenced in the encode/decode sequence.
+//
+// During an encode/decode sequence, we work as below:
+// - If base is a built in type, en/decode base value
+// - If base is registered as an extension, en/decode base value
+// - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
+// - Else decode appropriately based on the reflect.Kind
+type typeInfo struct {
+ sfi []*structFieldInfo // sorted. Used when enc/dec struct to map.
+ sfip []*structFieldInfo // unsorted. Used when enc/dec struct to array.
+
+ rt reflect.Type
+ rtid uintptr
+
+ // baseId gives pointer to the base reflect.Type, after deferencing
+ // the pointers. E.g. base type of ***time.Time is time.Time.
+ base reflect.Type
+ baseId uintptr
+ baseIndir int8 // number of indirections to get to base
+
+ mbs bool // base type (T or *T) is a MapBySlice
+
+ m bool // base type (T or *T) is a binaryMarshaler
+ unm bool // base type (T or *T) is a binaryUnmarshaler
+ mIndir int8 // number of indirections to get to binaryMarshaler type
+ unmIndir int8 // number of indirections to get to binaryUnmarshaler type
+ toArray bool // whether this (struct) type should be encoded as an array
+}
+
+func (ti *typeInfo) indexForEncName(name string) int {
+ //tisfi := ti.sfi
+ const binarySearchThreshold = 16
+ if sfilen := len(ti.sfi); sfilen < binarySearchThreshold {
+ // linear search. faster than binary search in my testing up to 16-field structs.
+ for i, si := range ti.sfi {
+ if si.encName == name {
+ return i
+ }
+ }
+ } else {
+ // binary search. adapted from sort/search.go.
+ h, i, j := 0, 0, sfilen
+ for i < j {
+ h = i + (j-i)/2
+ if ti.sfi[h].encName < name {
+ i = h + 1
+ } else {
+ j = h
+ }
+ }
+ if i < sfilen && ti.sfi[i].encName == name {
+ return i
+ }
+ }
+ return -1
+}
+
+func getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
+ var ok bool
+ cachedTypeInfoMutex.RLock()
+ pti, ok = cachedTypeInfo[rtid]
+ cachedTypeInfoMutex.RUnlock()
+ if ok {
+ return
+ }
+
+ cachedTypeInfoMutex.Lock()
+ defer cachedTypeInfoMutex.Unlock()
+ if pti, ok = cachedTypeInfo[rtid]; ok {
+ return
+ }
+
+ ti := typeInfo{rt: rt, rtid: rtid}
+ pti = &ti
+
+ var indir int8
+ if ok, indir = implementsIntf(rt, binaryMarshalerTyp); ok {
+ ti.m, ti.mIndir = true, indir
+ }
+ if ok, indir = implementsIntf(rt, binaryUnmarshalerTyp); ok {
+ ti.unm, ti.unmIndir = true, indir
+ }
+ if ok, _ = implementsIntf(rt, mapBySliceTyp); ok {
+ ti.mbs = true
+ }
+
+ pt := rt
+ var ptIndir int8
+ // for ; pt.Kind() == reflect.Ptr; pt, ptIndir = pt.Elem(), ptIndir+1 { }
+ for pt.Kind() == reflect.Ptr {
+ pt = pt.Elem()
+ ptIndir++
+ }
+ if ptIndir == 0 {
+ ti.base = rt
+ ti.baseId = rtid
+ } else {
+ ti.base = pt
+ ti.baseId = reflect.ValueOf(pt).Pointer()
+ ti.baseIndir = ptIndir
+ }
+
+ if rt.Kind() == reflect.Struct {
+ var siInfo *structFieldInfo
+ if f, ok := rt.FieldByName(structInfoFieldName); ok {
+ siInfo = parseStructFieldInfo(structInfoFieldName, f.Tag.Get(structTagName))
+ ti.toArray = siInfo.toArray
+ }
+ sfip := make([]*structFieldInfo, 0, rt.NumField())
+ rgetTypeInfo(rt, nil, make(map[string]bool), &sfip, siInfo)
+
+ // // try to put all si close together
+ // const tryToPutAllStructFieldInfoTogether = true
+ // if tryToPutAllStructFieldInfoTogether {
+ // sfip2 := make([]structFieldInfo, len(sfip))
+ // for i, si := range sfip {
+ // sfip2[i] = *si
+ // }
+ // for i := range sfip {
+ // sfip[i] = &sfip2[i]
+ // }
+ // }
+
+ ti.sfip = make([]*structFieldInfo, len(sfip))
+ ti.sfi = make([]*structFieldInfo, len(sfip))
+ copy(ti.sfip, sfip)
+ sort.Sort(sfiSortedByEncName(sfip))
+ copy(ti.sfi, sfip)
+ }
+ // sfi = sfip
+ cachedTypeInfo[rtid] = pti
+ return
+}
+
+func rgetTypeInfo(rt reflect.Type, indexstack []int, fnameToHastag map[string]bool,
+ sfi *[]*structFieldInfo, siInfo *structFieldInfo,
+) {
+ // for rt.Kind() == reflect.Ptr {
+ // // indexstack = append(indexstack, 0)
+ // rt = rt.Elem()
+ // }
+ for j := 0; j < rt.NumField(); j++ {
+ f := rt.Field(j)
+ stag := f.Tag.Get(structTagName)
+ if stag == "-" {
+ continue
+ }
+ if r1, _ := utf8.DecodeRuneInString(f.Name); r1 == utf8.RuneError || !unicode.IsUpper(r1) {
+ continue
+ }
+ // if anonymous and there is no struct tag and its a struct (or pointer to struct), inline it.
+ if f.Anonymous && stag == "" {
+ ft := f.Type
+ for ft.Kind() == reflect.Ptr {
+ ft = ft.Elem()
+ }
+ if ft.Kind() == reflect.Struct {
+ indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
+ rgetTypeInfo(ft, indexstack2, fnameToHastag, sfi, siInfo)
+ continue
+ }
+ }
+ // do not let fields with same name in embedded structs override field at higher level.
+ // this must be done after anonymous check, to allow anonymous field
+ // still include their child fields
+ if _, ok := fnameToHastag[f.Name]; ok {
+ continue
+ }
+ si := parseStructFieldInfo(f.Name, stag)
+ // si.ikind = int(f.Type.Kind())
+ if len(indexstack) == 0 {
+ si.i = int16(j)
+ } else {
+ si.i = -1
+ si.is = append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
+ }
+
+ if siInfo != nil {
+ if siInfo.omitEmpty {
+ si.omitEmpty = true
+ }
+ }
+ *sfi = append(*sfi, si)
+ fnameToHastag[f.Name] = stag != ""
+ }
+}
+
+func panicToErr(err *error) {
+ if recoverPanicToErr {
+ if x := recover(); x != nil {
+ //debug.PrintStack()
+ panicValToErr(x, err)
+ }
+ }
+}
+
+func doPanic(tag string, format string, params ...interface{}) {
+ params2 := make([]interface{}, len(params)+1)
+ params2[0] = tag
+ copy(params2[1:], params)
+ panic(fmt.Errorf("%s: "+format, params2...))
+}
+
+func checkOverflowFloat32(f float64, doCheck bool) {
+ if !doCheck {
+ return
+ }
+ // check overflow (logic adapted from std pkg reflect/value.go OverflowFloat()
+ f2 := f
+ if f2 < 0 {
+ f2 = -f
+ }
+ if math.MaxFloat32 < f2 && f2 <= math.MaxFloat64 {
+ decErr("Overflow float32 value: %v", f2)
+ }
+}
+
+func checkOverflow(ui uint64, i int64, bitsize uint8) {
+ // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
+ if bitsize == 0 {
+ return
+ }
+ if i != 0 {
+ if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc {
+ decErr("Overflow int value: %v", i)
+ }
+ }
+ if ui != 0 {
+ if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc {
+ decErr("Overflow uint value: %v", ui)
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go b/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go
new file mode 100644
index 0000000..58417da
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/helper_internal.go
@@ -0,0 +1,127 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+// All non-std package dependencies live in this file,
+// so porting to different environment is easy (just update functions).
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "reflect"
+)
+
+var (
+ raisePanicAfterRecover = false
+ debugging = true
+)
+
+func panicValToErr(panicVal interface{}, err *error) {
+ switch xerr := panicVal.(type) {
+ case error:
+ *err = xerr
+ case string:
+ *err = errors.New(xerr)
+ default:
+ *err = fmt.Errorf("%v", panicVal)
+ }
+ if raisePanicAfterRecover {
+ panic(panicVal)
+ }
+ return
+}
+
+func isEmptyValueDeref(v reflect.Value, deref bool) bool {
+ switch v.Kind() {
+ case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
+ return v.Len() == 0
+ case reflect.Bool:
+ return !v.Bool()
+ 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.Interface, reflect.Ptr:
+ if deref {
+ if v.IsNil() {
+ return true
+ }
+ return isEmptyValueDeref(v.Elem(), deref)
+ } else {
+ return v.IsNil()
+ }
+ case reflect.Struct:
+ // return true if all fields are empty. else return false.
+
+ // we cannot use equality check, because some fields may be maps/slices/etc
+ // and consequently the structs are not comparable.
+ // return v.Interface() == reflect.Zero(v.Type()).Interface()
+ for i, n := 0, v.NumField(); i < n; i++ {
+ if !isEmptyValueDeref(v.Field(i), deref) {
+ return false
+ }
+ }
+ return true
+ }
+ return false
+}
+
+func isEmptyValue(v reflect.Value) bool {
+ return isEmptyValueDeref(v, true)
+}
+
+func debugf(format string, args ...interface{}) {
+ if debugging {
+ if len(format) == 0 || format[len(format)-1] != '\n' {
+ format = format + "\n"
+ }
+ fmt.Printf(format, args...)
+ }
+}
+
+func pruneSignExt(v []byte, pos bool) (n int) {
+ if len(v) < 2 {
+ } else if pos && v[0] == 0 {
+ for ; v[n] == 0 && n+1 < len(v) && (v[n+1]&(1<<7) == 0); n++ {
+ }
+ } else if !pos && v[0] == 0xff {
+ for ; v[n] == 0xff && n+1 < len(v) && (v[n+1]&(1<<7) != 0); n++ {
+ }
+ }
+ return
+}
+
+func implementsIntf(typ, iTyp reflect.Type) (success bool, indir int8) {
+ if typ == nil {
+ return
+ }
+ rt := typ
+ // The type might be a pointer and we need to keep
+ // dereferencing to the base type until we find an implementation.
+ for {
+ if rt.Implements(iTyp) {
+ return true, indir
+ }
+ if p := rt; p.Kind() == reflect.Ptr {
+ indir++
+ if indir >= math.MaxInt8 { // insane number of indirections
+ return false, 0
+ }
+ rt = p.Elem()
+ continue
+ }
+ break
+ }
+ // No luck yet, but if this is a base type (non-pointer), the pointer might satisfy.
+ if typ.Kind() != reflect.Ptr {
+ // Not a pointer, but does the pointer work?
+ if reflect.PtrTo(typ).Implements(iTyp) {
+ return true, -1
+ }
+ }
+ return false, 0
+}
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go b/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go
new file mode 100644
index 0000000..da0500d
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/msgpack.go
@@ -0,0 +1,816 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+/*
+MSGPACK
+
+Msgpack-c implementation powers the c, c++, python, ruby, etc libraries.
+We need to maintain compatibility with it and how it encodes integer values
+without caring about the type.
+
+For compatibility with behaviour of msgpack-c reference implementation:
+ - Go intX (>0) and uintX
+ IS ENCODED AS
+ msgpack +ve fixnum, unsigned
+ - Go intX (<0)
+ IS ENCODED AS
+ msgpack -ve fixnum, signed
+
+*/
+package codec
+
+import (
+ "fmt"
+ "io"
+ "math"
+ "net/rpc"
+)
+
+const (
+ mpPosFixNumMin byte = 0x00
+ mpPosFixNumMax = 0x7f
+ mpFixMapMin = 0x80
+ mpFixMapMax = 0x8f
+ mpFixArrayMin = 0x90
+ mpFixArrayMax = 0x9f
+ mpFixStrMin = 0xa0
+ mpFixStrMax = 0xbf
+ mpNil = 0xc0
+ _ = 0xc1
+ mpFalse = 0xc2
+ mpTrue = 0xc3
+ mpFloat = 0xca
+ mpDouble = 0xcb
+ mpUint8 = 0xcc
+ mpUint16 = 0xcd
+ mpUint32 = 0xce
+ mpUint64 = 0xcf
+ mpInt8 = 0xd0
+ mpInt16 = 0xd1
+ mpInt32 = 0xd2
+ mpInt64 = 0xd3
+
+ // extensions below
+ mpBin8 = 0xc4
+ mpBin16 = 0xc5
+ mpBin32 = 0xc6
+ mpExt8 = 0xc7
+ mpExt16 = 0xc8
+ mpExt32 = 0xc9
+ mpFixExt1 = 0xd4
+ mpFixExt2 = 0xd5
+ mpFixExt4 = 0xd6
+ mpFixExt8 = 0xd7
+ mpFixExt16 = 0xd8
+
+ mpStr8 = 0xd9 // new
+ mpStr16 = 0xda
+ mpStr32 = 0xdb
+
+ mpArray16 = 0xdc
+ mpArray32 = 0xdd
+
+ mpMap16 = 0xde
+ mpMap32 = 0xdf
+
+ mpNegFixNumMin = 0xe0
+ mpNegFixNumMax = 0xff
+)
+
+// MsgpackSpecRpcMultiArgs is a special type which signifies to the MsgpackSpecRpcCodec
+// that the backend RPC service takes multiple arguments, which have been arranged
+// in sequence in the slice.
+//
+// The Codec then passes it AS-IS to the rpc service (without wrapping it in an
+// array of 1 element).
+type MsgpackSpecRpcMultiArgs []interface{}
+
+// A MsgpackContainer type specifies the different types of msgpackContainers.
+type msgpackContainerType struct {
+ fixCutoff int
+ bFixMin, b8, b16, b32 byte
+ hasFixMin, has8, has8Always bool
+}
+
+var (
+ msgpackContainerStr = msgpackContainerType{32, mpFixStrMin, mpStr8, mpStr16, mpStr32, true, true, false}
+ msgpackContainerBin = msgpackContainerType{0, 0, mpBin8, mpBin16, mpBin32, false, true, true}
+ msgpackContainerList = msgpackContainerType{16, mpFixArrayMin, 0, mpArray16, mpArray32, true, false, false}
+ msgpackContainerMap = msgpackContainerType{16, mpFixMapMin, 0, mpMap16, mpMap32, true, false, false}
+)
+
+//---------------------------------------------
+
+type msgpackEncDriver struct {
+ w encWriter
+ h *MsgpackHandle
+}
+
+func (e *msgpackEncDriver) isBuiltinType(rt uintptr) bool {
+ //no builtin types. All encodings are based on kinds. Types supported as extensions.
+ return false
+}
+
+func (e *msgpackEncDriver) encodeBuiltin(rt uintptr, v interface{}) {}
+
+func (e *msgpackEncDriver) encodeNil() {
+ e.w.writen1(mpNil)
+}
+
+func (e *msgpackEncDriver) encodeInt(i int64) {
+
+ switch {
+ case i >= 0:
+ e.encodeUint(uint64(i))
+ case i >= -32:
+ e.w.writen1(byte(i))
+ case i >= math.MinInt8:
+ e.w.writen2(mpInt8, byte(i))
+ case i >= math.MinInt16:
+ e.w.writen1(mpInt16)
+ e.w.writeUint16(uint16(i))
+ case i >= math.MinInt32:
+ e.w.writen1(mpInt32)
+ e.w.writeUint32(uint32(i))
+ default:
+ e.w.writen1(mpInt64)
+ e.w.writeUint64(uint64(i))
+ }
+}
+
+func (e *msgpackEncDriver) encodeUint(i uint64) {
+ switch {
+ case i <= math.MaxInt8:
+ e.w.writen1(byte(i))
+ case i <= math.MaxUint8:
+ e.w.writen2(mpUint8, byte(i))
+ case i <= math.MaxUint16:
+ e.w.writen1(mpUint16)
+ e.w.writeUint16(uint16(i))
+ case i <= math.MaxUint32:
+ e.w.writen1(mpUint32)
+ e.w.writeUint32(uint32(i))
+ default:
+ e.w.writen1(mpUint64)
+ e.w.writeUint64(uint64(i))
+ }
+}
+
+func (e *msgpackEncDriver) encodeBool(b bool) {
+ if b {
+ e.w.writen1(mpTrue)
+ } else {
+ e.w.writen1(mpFalse)
+ }
+}
+
+func (e *msgpackEncDriver) encodeFloat32(f float32) {
+ e.w.writen1(mpFloat)
+ e.w.writeUint32(math.Float32bits(f))
+}
+
+func (e *msgpackEncDriver) encodeFloat64(f float64) {
+ e.w.writen1(mpDouble)
+ e.w.writeUint64(math.Float64bits(f))
+}
+
+func (e *msgpackEncDriver) encodeExtPreamble(xtag byte, l int) {
+ switch {
+ case l == 1:
+ e.w.writen2(mpFixExt1, xtag)
+ case l == 2:
+ e.w.writen2(mpFixExt2, xtag)
+ case l == 4:
+ e.w.writen2(mpFixExt4, xtag)
+ case l == 8:
+ e.w.writen2(mpFixExt8, xtag)
+ case l == 16:
+ e.w.writen2(mpFixExt16, xtag)
+ case l < 256:
+ e.w.writen2(mpExt8, byte(l))
+ e.w.writen1(xtag)
+ case l < 65536:
+ e.w.writen1(mpExt16)
+ e.w.writeUint16(uint16(l))
+ e.w.writen1(xtag)
+ default:
+ e.w.writen1(mpExt32)
+ e.w.writeUint32(uint32(l))
+ e.w.writen1(xtag)
+ }
+}
+
+func (e *msgpackEncDriver) encodeArrayPreamble(length int) {
+ e.writeContainerLen(msgpackContainerList, length)
+}
+
+func (e *msgpackEncDriver) encodeMapPreamble(length int) {
+ e.writeContainerLen(msgpackContainerMap, length)
+}
+
+func (e *msgpackEncDriver) encodeString(c charEncoding, s string) {
+ if c == c_RAW && e.h.WriteExt {
+ e.writeContainerLen(msgpackContainerBin, len(s))
+ } else {
+ e.writeContainerLen(msgpackContainerStr, len(s))
+ }
+ if len(s) > 0 {
+ e.w.writestr(s)
+ }
+}
+
+func (e *msgpackEncDriver) encodeSymbol(v string) {
+ e.encodeString(c_UTF8, v)
+}
+
+func (e *msgpackEncDriver) encodeStringBytes(c charEncoding, bs []byte) {
+ if c == c_RAW && e.h.WriteExt {
+ e.writeContainerLen(msgpackContainerBin, len(bs))
+ } else {
+ e.writeContainerLen(msgpackContainerStr, len(bs))
+ }
+ if len(bs) > 0 {
+ e.w.writeb(bs)
+ }
+}
+
+func (e *msgpackEncDriver) writeContainerLen(ct msgpackContainerType, l int) {
+ switch {
+ case ct.hasFixMin && l < ct.fixCutoff:
+ e.w.writen1(ct.bFixMin | byte(l))
+ case ct.has8 && l < 256 && (ct.has8Always || e.h.WriteExt):
+ e.w.writen2(ct.b8, uint8(l))
+ case l < 65536:
+ e.w.writen1(ct.b16)
+ e.w.writeUint16(uint16(l))
+ default:
+ e.w.writen1(ct.b32)
+ e.w.writeUint32(uint32(l))
+ }
+}
+
+//---------------------------------------------
+
+type msgpackDecDriver struct {
+ r decReader
+ h *MsgpackHandle
+ bd byte
+ bdRead bool
+ bdType valueType
+}
+
+func (d *msgpackDecDriver) isBuiltinType(rt uintptr) bool {
+ //no builtin types. All encodings are based on kinds. Types supported as extensions.
+ return false
+}
+
+func (d *msgpackDecDriver) decodeBuiltin(rt uintptr, v interface{}) {}
+
+// Note: This returns either a primitive (int, bool, etc) for non-containers,
+// or a containerType, or a specific type denoting nil or extension.
+// It is called when a nil interface{} is passed, leaving it up to the DecDriver
+// to introspect the stream and decide how best to decode.
+// It deciphers the value by looking at the stream first.
+func (d *msgpackDecDriver) decodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
+ d.initReadNext()
+ bd := d.bd
+
+ switch bd {
+ case mpNil:
+ vt = valueTypeNil
+ d.bdRead = false
+ case mpFalse:
+ vt = valueTypeBool
+ v = false
+ case mpTrue:
+ vt = valueTypeBool
+ v = true
+
+ case mpFloat:
+ vt = valueTypeFloat
+ v = float64(math.Float32frombits(d.r.readUint32()))
+ case mpDouble:
+ vt = valueTypeFloat
+ v = math.Float64frombits(d.r.readUint64())
+
+ case mpUint8:
+ vt = valueTypeUint
+ v = uint64(d.r.readn1())
+ case mpUint16:
+ vt = valueTypeUint
+ v = uint64(d.r.readUint16())
+ case mpUint32:
+ vt = valueTypeUint
+ v = uint64(d.r.readUint32())
+ case mpUint64:
+ vt = valueTypeUint
+ v = uint64(d.r.readUint64())
+
+ case mpInt8:
+ vt = valueTypeInt
+ v = int64(int8(d.r.readn1()))
+ case mpInt16:
+ vt = valueTypeInt
+ v = int64(int16(d.r.readUint16()))
+ case mpInt32:
+ vt = valueTypeInt
+ v = int64(int32(d.r.readUint32()))
+ case mpInt64:
+ vt = valueTypeInt
+ v = int64(int64(d.r.readUint64()))
+
+ default:
+ switch {
+ case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
+ // positive fixnum (always signed)
+ vt = valueTypeInt
+ v = int64(int8(bd))
+ case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
+ // negative fixnum
+ vt = valueTypeInt
+ v = int64(int8(bd))
+ case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
+ if d.h.RawToString {
+ var rvm string
+ vt = valueTypeString
+ v = &rvm
+ } else {
+ var rvm = []byte{}
+ vt = valueTypeBytes
+ v = &rvm
+ }
+ decodeFurther = true
+ case bd == mpBin8, bd == mpBin16, bd == mpBin32:
+ var rvm = []byte{}
+ vt = valueTypeBytes
+ v = &rvm
+ decodeFurther = true
+ case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
+ vt = valueTypeArray
+ decodeFurther = true
+ case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
+ vt = valueTypeMap
+ decodeFurther = true
+ case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
+ clen := d.readExtLen()
+ var re RawExt
+ re.Tag = d.r.readn1()
+ re.Data = d.r.readn(clen)
+ v = &re
+ vt = valueTypeExt
+ default:
+ decErr("Nil-Deciphered DecodeValue: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
+ }
+ }
+ if !decodeFurther {
+ d.bdRead = false
+ }
+ return
+}
+
+// int can be decoded from msgpack type: intXXX or uintXXX
+func (d *msgpackDecDriver) decodeInt(bitsize uint8) (i int64) {
+ switch d.bd {
+ case mpUint8:
+ i = int64(uint64(d.r.readn1()))
+ case mpUint16:
+ i = int64(uint64(d.r.readUint16()))
+ case mpUint32:
+ i = int64(uint64(d.r.readUint32()))
+ case mpUint64:
+ i = int64(d.r.readUint64())
+ case mpInt8:
+ i = int64(int8(d.r.readn1()))
+ case mpInt16:
+ i = int64(int16(d.r.readUint16()))
+ case mpInt32:
+ i = int64(int32(d.r.readUint32()))
+ case mpInt64:
+ i = int64(d.r.readUint64())
+ default:
+ switch {
+ case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
+ i = int64(int8(d.bd))
+ case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
+ i = int64(int8(d.bd))
+ default:
+ decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
+ }
+ }
+ // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
+ if bitsize > 0 {
+ if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc {
+ decErr("Overflow int value: %v", i)
+ }
+ }
+ d.bdRead = false
+ return
+}
+
+// uint can be decoded from msgpack type: intXXX or uintXXX
+func (d *msgpackDecDriver) decodeUint(bitsize uint8) (ui uint64) {
+ switch d.bd {
+ case mpUint8:
+ ui = uint64(d.r.readn1())
+ case mpUint16:
+ ui = uint64(d.r.readUint16())
+ case mpUint32:
+ ui = uint64(d.r.readUint32())
+ case mpUint64:
+ ui = d.r.readUint64()
+ case mpInt8:
+ if i := int64(int8(d.r.readn1())); i >= 0 {
+ ui = uint64(i)
+ } else {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ case mpInt16:
+ if i := int64(int16(d.r.readUint16())); i >= 0 {
+ ui = uint64(i)
+ } else {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ case mpInt32:
+ if i := int64(int32(d.r.readUint32())); i >= 0 {
+ ui = uint64(i)
+ } else {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ case mpInt64:
+ if i := int64(d.r.readUint64()); i >= 0 {
+ ui = uint64(i)
+ } else {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ default:
+ switch {
+ case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
+ ui = uint64(d.bd)
+ case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
+ decErr("Assigning negative signed value: %v, to unsigned type", int(d.bd))
+ default:
+ decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
+ }
+ }
+ // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
+ if bitsize > 0 {
+ if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc {
+ decErr("Overflow uint value: %v", ui)
+ }
+ }
+ d.bdRead = false
+ return
+}
+
+// float can either be decoded from msgpack type: float, double or intX
+func (d *msgpackDecDriver) decodeFloat(chkOverflow32 bool) (f float64) {
+ switch d.bd {
+ case mpFloat:
+ f = float64(math.Float32frombits(d.r.readUint32()))
+ case mpDouble:
+ f = math.Float64frombits(d.r.readUint64())
+ default:
+ f = float64(d.decodeInt(0))
+ }
+ checkOverflowFloat32(f, chkOverflow32)
+ d.bdRead = false
+ return
+}
+
+// bool can be decoded from bool, fixnum 0 or 1.
+func (d *msgpackDecDriver) decodeBool() (b bool) {
+ switch d.bd {
+ case mpFalse, 0:
+ // b = false
+ case mpTrue, 1:
+ b = true
+ default:
+ decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *msgpackDecDriver) decodeString() (s string) {
+ clen := d.readContainerLen(msgpackContainerStr)
+ if clen > 0 {
+ s = string(d.r.readn(clen))
+ }
+ d.bdRead = false
+ return
+}
+
+// Callers must check if changed=true (to decide whether to replace the one they have)
+func (d *msgpackDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) {
+ // bytes can be decoded from msgpackContainerStr or msgpackContainerBin
+ var clen int
+ switch d.bd {
+ case mpBin8, mpBin16, mpBin32:
+ clen = d.readContainerLen(msgpackContainerBin)
+ default:
+ clen = d.readContainerLen(msgpackContainerStr)
+ }
+ // if clen < 0 {
+ // changed = true
+ // panic("length cannot be zero. this cannot be nil.")
+ // }
+ if clen > 0 {
+ // if no contents in stream, don't update the passed byteslice
+ if len(bs) != clen {
+ // Return changed=true if length of passed slice diff from length of bytes in stream
+ if len(bs) > clen {
+ bs = bs[:clen]
+ } else {
+ bs = make([]byte, clen)
+ }
+ bsOut = bs
+ changed = true
+ }
+ d.r.readb(bs)
+ }
+ d.bdRead = false
+ return
+}
+
+// Every top-level decode funcs (i.e. decodeValue, decode) must call this first.
+func (d *msgpackDecDriver) initReadNext() {
+ if d.bdRead {
+ return
+ }
+ d.bd = d.r.readn1()
+ d.bdRead = true
+ d.bdType = valueTypeUnset
+}
+
+func (d *msgpackDecDriver) currentEncodedType() valueType {
+ if d.bdType == valueTypeUnset {
+ bd := d.bd
+ switch bd {
+ case mpNil:
+ d.bdType = valueTypeNil
+ case mpFalse, mpTrue:
+ d.bdType = valueTypeBool
+ case mpFloat, mpDouble:
+ d.bdType = valueTypeFloat
+ case mpUint8, mpUint16, mpUint32, mpUint64:
+ d.bdType = valueTypeUint
+ case mpInt8, mpInt16, mpInt32, mpInt64:
+ d.bdType = valueTypeInt
+ default:
+ switch {
+ case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
+ d.bdType = valueTypeInt
+ case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
+ d.bdType = valueTypeInt
+ case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
+ if d.h.RawToString {
+ d.bdType = valueTypeString
+ } else {
+ d.bdType = valueTypeBytes
+ }
+ case bd == mpBin8, bd == mpBin16, bd == mpBin32:
+ d.bdType = valueTypeBytes
+ case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
+ d.bdType = valueTypeArray
+ case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
+ d.bdType = valueTypeMap
+ case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
+ d.bdType = valueTypeExt
+ default:
+ decErr("currentEncodedType: Undeciphered descriptor: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
+ }
+ }
+ }
+ return d.bdType
+}
+
+func (d *msgpackDecDriver) tryDecodeAsNil() bool {
+ if d.bd == mpNil {
+ d.bdRead = false
+ return true
+ }
+ return false
+}
+
+func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) {
+ bd := d.bd
+ switch {
+ case bd == mpNil:
+ clen = -1 // to represent nil
+ case bd == ct.b8:
+ clen = int(d.r.readn1())
+ case bd == ct.b16:
+ clen = int(d.r.readUint16())
+ case bd == ct.b32:
+ clen = int(d.r.readUint32())
+ case (ct.bFixMin & bd) == ct.bFixMin:
+ clen = int(ct.bFixMin ^ bd)
+ default:
+ decErr("readContainerLen: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *msgpackDecDriver) readMapLen() int {
+ return d.readContainerLen(msgpackContainerMap)
+}
+
+func (d *msgpackDecDriver) readArrayLen() int {
+ return d.readContainerLen(msgpackContainerList)
+}
+
+func (d *msgpackDecDriver) readExtLen() (clen int) {
+ switch d.bd {
+ case mpNil:
+ clen = -1 // to represent nil
+ case mpFixExt1:
+ clen = 1
+ case mpFixExt2:
+ clen = 2
+ case mpFixExt4:
+ clen = 4
+ case mpFixExt8:
+ clen = 8
+ case mpFixExt16:
+ clen = 16
+ case mpExt8:
+ clen = int(d.r.readn1())
+ case mpExt16:
+ clen = int(d.r.readUint16())
+ case mpExt32:
+ clen = int(d.r.readUint32())
+ default:
+ decErr("decoding ext bytes: found unexpected byte: %x", d.bd)
+ }
+ return
+}
+
+func (d *msgpackDecDriver) decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
+ xbd := d.bd
+ switch {
+ case xbd == mpBin8, xbd == mpBin16, xbd == mpBin32:
+ xbs, _ = d.decodeBytes(nil)
+ case xbd == mpStr8, xbd == mpStr16, xbd == mpStr32,
+ xbd >= mpFixStrMin && xbd <= mpFixStrMax:
+ xbs = []byte(d.decodeString())
+ default:
+ clen := d.readExtLen()
+ xtag = d.r.readn1()
+ if verifyTag && xtag != tag {
+ decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
+ }
+ xbs = d.r.readn(clen)
+ }
+ d.bdRead = false
+ return
+}
+
+//--------------------------------------------------
+
+//MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format.
+type MsgpackHandle struct {
+ BasicHandle
+
+ // RawToString controls how raw bytes are decoded into a nil interface{}.
+ RawToString bool
+ // WriteExt flag supports encoding configured extensions with extension tags.
+ // It also controls whether other elements of the new spec are encoded (ie Str8).
+ //
+ // With WriteExt=false, configured extensions are serialized as raw bytes
+ // and Str8 is not encoded.
+ //
+ // A stream can still be decoded into a typed value, provided an appropriate value
+ // is provided, but the type cannot be inferred from the stream. If no appropriate
+ // type is provided (e.g. decoding into a nil interface{}), you get back
+ // a []byte or string based on the setting of RawToString.
+ WriteExt bool
+}
+
+func (h *MsgpackHandle) newEncDriver(w encWriter) encDriver {
+ return &msgpackEncDriver{w: w, h: h}
+}
+
+func (h *MsgpackHandle) newDecDriver(r decReader) decDriver {
+ return &msgpackDecDriver{r: r, h: h}
+}
+
+func (h *MsgpackHandle) writeExt() bool {
+ return h.WriteExt
+}
+
+func (h *MsgpackHandle) getBasicHandle() *BasicHandle {
+ return &h.BasicHandle
+}
+
+//--------------------------------------------------
+
+type msgpackSpecRpcCodec struct {
+ rpcCodec
+}
+
+// /////////////// Spec RPC Codec ///////////////////
+func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
+ // WriteRequest can write to both a Go service, and other services that do
+ // not abide by the 1 argument rule of a Go service.
+ // We discriminate based on if the body is a MsgpackSpecRpcMultiArgs
+ var bodyArr []interface{}
+ if m, ok := body.(MsgpackSpecRpcMultiArgs); ok {
+ bodyArr = ([]interface{})(m)
+ } else {
+ bodyArr = []interface{}{body}
+ }
+ r2 := []interface{}{0, uint32(r.Seq), r.ServiceMethod, bodyArr}
+ return c.write(r2, nil, false, true)
+}
+
+func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
+ var moe interface{}
+ if r.Error != "" {
+ moe = r.Error
+ }
+ if moe != nil && body != nil {
+ body = nil
+ }
+ r2 := []interface{}{1, uint32(r.Seq), moe, body}
+ return c.write(r2, nil, false, true)
+}
+
+func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
+ return c.parseCustomHeader(1, &r.Seq, &r.Error)
+}
+
+func (c *msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
+ return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
+}
+
+func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error {
+ if body == nil { // read and discard
+ return c.read(nil)
+ }
+ bodyArr := []interface{}{body}
+ return c.read(&bodyArr)
+}
+
+func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
+
+ if c.cls {
+ return io.EOF
+ }
+
+ // We read the response header by hand
+ // so that the body can be decoded on its own from the stream at a later time.
+
+ const fia byte = 0x94 //four item array descriptor value
+ // Not sure why the panic of EOF is swallowed above.
+ // if bs1 := c.dec.r.readn1(); bs1 != fia {
+ // err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs1)
+ // return
+ // }
+ var b byte
+ b, err = c.br.ReadByte()
+ if err != nil {
+ return
+ }
+ if b != fia {
+ err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, b)
+ return
+ }
+
+ if err = c.read(&b); err != nil {
+ return
+ }
+ if b != expectTypeByte {
+ err = fmt.Errorf("Unexpected byte descriptor in header. Expecting %v. Received %v", expectTypeByte, b)
+ return
+ }
+ if err = c.read(msgid); err != nil {
+ return
+ }
+ if err = c.read(methodOrError); err != nil {
+ return
+ }
+ return
+}
+
+//--------------------------------------------------
+
+// msgpackSpecRpc is the implementation of Rpc that uses custom communication protocol
+// as defined in the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
+type msgpackSpecRpc struct{}
+
+// MsgpackSpecRpc implements Rpc using the communication protocol defined in
+// the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md .
+// Its methods (ServerCodec and ClientCodec) return values that implement RpcCodecBuffered.
+var MsgpackSpecRpc msgpackSpecRpc
+
+func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
+ return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
+}
+
+func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
+ return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
+}
+
+var _ decDriver = (*msgpackDecDriver)(nil)
+var _ encDriver = (*msgpackEncDriver)(nil)
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go b/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go
new file mode 100644
index 0000000..d014dbd
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/rpc.go
@@ -0,0 +1,152 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import (
+ "bufio"
+ "io"
+ "net/rpc"
+ "sync"
+)
+
+// Rpc provides a rpc Server or Client Codec for rpc communication.
+type Rpc interface {
+ ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec
+ ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec
+}
+
+// RpcCodecBuffered allows access to the underlying bufio.Reader/Writer
+// used by the rpc connection. It accomodates use-cases where the connection
+// should be used by rpc and non-rpc functions, e.g. streaming a file after
+// sending an rpc response.
+type RpcCodecBuffered interface {
+ BufferedReader() *bufio.Reader
+ BufferedWriter() *bufio.Writer
+}
+
+// -------------------------------------
+
+// rpcCodec defines the struct members and common methods.
+type rpcCodec struct {
+ rwc io.ReadWriteCloser
+ dec *Decoder
+ enc *Encoder
+ bw *bufio.Writer
+ br *bufio.Reader
+ mu sync.Mutex
+ cls bool
+}
+
+func newRPCCodec(conn io.ReadWriteCloser, h Handle) rpcCodec {
+ bw := bufio.NewWriter(conn)
+ br := bufio.NewReader(conn)
+ return rpcCodec{
+ rwc: conn,
+ bw: bw,
+ br: br,
+ enc: NewEncoder(bw, h),
+ dec: NewDecoder(br, h),
+ }
+}
+
+func (c *rpcCodec) BufferedReader() *bufio.Reader {
+ return c.br
+}
+
+func (c *rpcCodec) BufferedWriter() *bufio.Writer {
+ return c.bw
+}
+
+func (c *rpcCodec) write(obj1, obj2 interface{}, writeObj2, doFlush bool) (err error) {
+ if c.cls {
+ return io.EOF
+ }
+ if err = c.enc.Encode(obj1); err != nil {
+ return
+ }
+ if writeObj2 {
+ if err = c.enc.Encode(obj2); err != nil {
+ return
+ }
+ }
+ if doFlush && c.bw != nil {
+ return c.bw.Flush()
+ }
+ return
+}
+
+func (c *rpcCodec) read(obj interface{}) (err error) {
+ if c.cls {
+ return io.EOF
+ }
+ //If nil is passed in, we should still attempt to read content to nowhere.
+ if obj == nil {
+ var obj2 interface{}
+ return c.dec.Decode(&obj2)
+ }
+ return c.dec.Decode(obj)
+}
+
+func (c *rpcCodec) Close() error {
+ if c.cls {
+ return io.EOF
+ }
+ c.cls = true
+ return c.rwc.Close()
+}
+
+func (c *rpcCodec) ReadResponseBody(body interface{}) error {
+ return c.read(body)
+}
+
+// -------------------------------------
+
+type goRpcCodec struct {
+ rpcCodec
+}
+
+func (c *goRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
+ // Must protect for concurrent access as per API
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.write(r, body, true, true)
+}
+
+func (c *goRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.write(r, body, true, true)
+}
+
+func (c *goRpcCodec) ReadResponseHeader(r *rpc.Response) error {
+ return c.read(r)
+}
+
+func (c *goRpcCodec) ReadRequestHeader(r *rpc.Request) error {
+ return c.read(r)
+}
+
+func (c *goRpcCodec) ReadRequestBody(body interface{}) error {
+ return c.read(body)
+}
+
+// -------------------------------------
+
+// goRpc is the implementation of Rpc that uses the communication protocol
+// as defined in net/rpc package.
+type goRpc struct{}
+
+// GoRpc implements Rpc using the communication protocol defined in net/rpc package.
+// Its methods (ServerCodec and ClientCodec) return values that implement RpcCodecBuffered.
+var GoRpc goRpc
+
+func (x goRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
+ return &goRpcCodec{newRPCCodec(conn, h)}
+}
+
+func (x goRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
+ return &goRpcCodec{newRPCCodec(conn, h)}
+}
+
+var _ RpcCodecBuffered = (*rpcCodec)(nil) // ensure *rpcCodec implements RpcCodecBuffered
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/simple.go b/vendor/github.com/hashicorp/go-msgpack/codec/simple.go
new file mode 100644
index 0000000..9e4d148
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/simple.go
@@ -0,0 +1,461 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import "math"
+
+const (
+ _ uint8 = iota
+ simpleVdNil = 1
+ simpleVdFalse = 2
+ simpleVdTrue = 3
+ simpleVdFloat32 = 4
+ simpleVdFloat64 = 5
+
+ // each lasts for 4 (ie n, n+1, n+2, n+3)
+ simpleVdPosInt = 8
+ simpleVdNegInt = 12
+
+ // containers: each lasts for 4 (ie n, n+1, n+2, ... n+7)
+ simpleVdString = 216
+ simpleVdByteArray = 224
+ simpleVdArray = 232
+ simpleVdMap = 240
+ simpleVdExt = 248
+)
+
+type simpleEncDriver struct {
+ h *SimpleHandle
+ w encWriter
+ //b [8]byte
+}
+
+func (e *simpleEncDriver) isBuiltinType(rt uintptr) bool {
+ return false
+}
+
+func (e *simpleEncDriver) encodeBuiltin(rt uintptr, v interface{}) {
+}
+
+func (e *simpleEncDriver) encodeNil() {
+ e.w.writen1(simpleVdNil)
+}
+
+func (e *simpleEncDriver) encodeBool(b bool) {
+ if b {
+ e.w.writen1(simpleVdTrue)
+ } else {
+ e.w.writen1(simpleVdFalse)
+ }
+}
+
+func (e *simpleEncDriver) encodeFloat32(f float32) {
+ e.w.writen1(simpleVdFloat32)
+ e.w.writeUint32(math.Float32bits(f))
+}
+
+func (e *simpleEncDriver) encodeFloat64(f float64) {
+ e.w.writen1(simpleVdFloat64)
+ e.w.writeUint64(math.Float64bits(f))
+}
+
+func (e *simpleEncDriver) encodeInt(v int64) {
+ if v < 0 {
+ e.encUint(uint64(-v), simpleVdNegInt)
+ } else {
+ e.encUint(uint64(v), simpleVdPosInt)
+ }
+}
+
+func (e *simpleEncDriver) encodeUint(v uint64) {
+ e.encUint(v, simpleVdPosInt)
+}
+
+func (e *simpleEncDriver) encUint(v uint64, bd uint8) {
+ switch {
+ case v <= math.MaxUint8:
+ e.w.writen2(bd, uint8(v))
+ case v <= math.MaxUint16:
+ e.w.writen1(bd + 1)
+ e.w.writeUint16(uint16(v))
+ case v <= math.MaxUint32:
+ e.w.writen1(bd + 2)
+ e.w.writeUint32(uint32(v))
+ case v <= math.MaxUint64:
+ e.w.writen1(bd + 3)
+ e.w.writeUint64(v)
+ }
+}
+
+func (e *simpleEncDriver) encLen(bd byte, length int) {
+ switch {
+ case length == 0:
+ e.w.writen1(bd)
+ case length <= math.MaxUint8:
+ e.w.writen1(bd + 1)
+ e.w.writen1(uint8(length))
+ case length <= math.MaxUint16:
+ e.w.writen1(bd + 2)
+ e.w.writeUint16(uint16(length))
+ case int64(length) <= math.MaxUint32:
+ e.w.writen1(bd + 3)
+ e.w.writeUint32(uint32(length))
+ default:
+ e.w.writen1(bd + 4)
+ e.w.writeUint64(uint64(length))
+ }
+}
+
+func (e *simpleEncDriver) encodeExtPreamble(xtag byte, length int) {
+ e.encLen(simpleVdExt, length)
+ e.w.writen1(xtag)
+}
+
+func (e *simpleEncDriver) encodeArrayPreamble(length int) {
+ e.encLen(simpleVdArray, length)
+}
+
+func (e *simpleEncDriver) encodeMapPreamble(length int) {
+ e.encLen(simpleVdMap, length)
+}
+
+func (e *simpleEncDriver) encodeString(c charEncoding, v string) {
+ e.encLen(simpleVdString, len(v))
+ e.w.writestr(v)
+}
+
+func (e *simpleEncDriver) encodeSymbol(v string) {
+ e.encodeString(c_UTF8, v)
+}
+
+func (e *simpleEncDriver) encodeStringBytes(c charEncoding, v []byte) {
+ e.encLen(simpleVdByteArray, len(v))
+ e.w.writeb(v)
+}
+
+//------------------------------------
+
+type simpleDecDriver struct {
+ h *SimpleHandle
+ r decReader
+ bdRead bool
+ bdType valueType
+ bd byte
+ //b [8]byte
+}
+
+func (d *simpleDecDriver) initReadNext() {
+ if d.bdRead {
+ return
+ }
+ d.bd = d.r.readn1()
+ d.bdRead = true
+ d.bdType = valueTypeUnset
+}
+
+func (d *simpleDecDriver) currentEncodedType() valueType {
+ if d.bdType == valueTypeUnset {
+ switch d.bd {
+ case simpleVdNil:
+ d.bdType = valueTypeNil
+ case simpleVdTrue, simpleVdFalse:
+ d.bdType = valueTypeBool
+ case simpleVdPosInt, simpleVdPosInt + 1, simpleVdPosInt + 2, simpleVdPosInt + 3:
+ d.bdType = valueTypeUint
+ case simpleVdNegInt, simpleVdNegInt + 1, simpleVdNegInt + 2, simpleVdNegInt + 3:
+ d.bdType = valueTypeInt
+ case simpleVdFloat32, simpleVdFloat64:
+ d.bdType = valueTypeFloat
+ case simpleVdString, simpleVdString + 1, simpleVdString + 2, simpleVdString + 3, simpleVdString + 4:
+ d.bdType = valueTypeString
+ case simpleVdByteArray, simpleVdByteArray + 1, simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4:
+ d.bdType = valueTypeBytes
+ case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4:
+ d.bdType = valueTypeExt
+ case simpleVdArray, simpleVdArray + 1, simpleVdArray + 2, simpleVdArray + 3, simpleVdArray + 4:
+ d.bdType = valueTypeArray
+ case simpleVdMap, simpleVdMap + 1, simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4:
+ d.bdType = valueTypeMap
+ default:
+ decErr("currentEncodedType: Unrecognized d.vd: 0x%x", d.bd)
+ }
+ }
+ return d.bdType
+}
+
+func (d *simpleDecDriver) tryDecodeAsNil() bool {
+ if d.bd == simpleVdNil {
+ d.bdRead = false
+ return true
+ }
+ return false
+}
+
+func (d *simpleDecDriver) isBuiltinType(rt uintptr) bool {
+ return false
+}
+
+func (d *simpleDecDriver) decodeBuiltin(rt uintptr, v interface{}) {
+}
+
+func (d *simpleDecDriver) decIntAny() (ui uint64, i int64, neg bool) {
+ switch d.bd {
+ case simpleVdPosInt:
+ ui = uint64(d.r.readn1())
+ i = int64(ui)
+ case simpleVdPosInt + 1:
+ ui = uint64(d.r.readUint16())
+ i = int64(ui)
+ case simpleVdPosInt + 2:
+ ui = uint64(d.r.readUint32())
+ i = int64(ui)
+ case simpleVdPosInt + 3:
+ ui = uint64(d.r.readUint64())
+ i = int64(ui)
+ case simpleVdNegInt:
+ ui = uint64(d.r.readn1())
+ i = -(int64(ui))
+ neg = true
+ case simpleVdNegInt + 1:
+ ui = uint64(d.r.readUint16())
+ i = -(int64(ui))
+ neg = true
+ case simpleVdNegInt + 2:
+ ui = uint64(d.r.readUint32())
+ i = -(int64(ui))
+ neg = true
+ case simpleVdNegInt + 3:
+ ui = uint64(d.r.readUint64())
+ i = -(int64(ui))
+ neg = true
+ default:
+ decErr("decIntAny: Integer only valid from pos/neg integer1..8. Invalid descriptor: %v", d.bd)
+ }
+ // don't do this check, because callers may only want the unsigned value.
+ // if ui > math.MaxInt64 {
+ // decErr("decIntAny: Integer out of range for signed int64: %v", ui)
+ // }
+ return
+}
+
+func (d *simpleDecDriver) decodeInt(bitsize uint8) (i int64) {
+ _, i, _ = d.decIntAny()
+ checkOverflow(0, i, bitsize)
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) decodeUint(bitsize uint8) (ui uint64) {
+ ui, i, neg := d.decIntAny()
+ if neg {
+ decErr("Assigning negative signed value: %v, to unsigned type", i)
+ }
+ checkOverflow(ui, 0, bitsize)
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) decodeFloat(chkOverflow32 bool) (f float64) {
+ switch d.bd {
+ case simpleVdFloat32:
+ f = float64(math.Float32frombits(d.r.readUint32()))
+ case simpleVdFloat64:
+ f = math.Float64frombits(d.r.readUint64())
+ default:
+ if d.bd >= simpleVdPosInt && d.bd <= simpleVdNegInt+3 {
+ _, i, _ := d.decIntAny()
+ f = float64(i)
+ } else {
+ decErr("Float only valid from float32/64: Invalid descriptor: %v", d.bd)
+ }
+ }
+ checkOverflowFloat32(f, chkOverflow32)
+ d.bdRead = false
+ return
+}
+
+// bool can be decoded from bool only (single byte).
+func (d *simpleDecDriver) decodeBool() (b bool) {
+ switch d.bd {
+ case simpleVdTrue:
+ b = true
+ case simpleVdFalse:
+ default:
+ decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) readMapLen() (length int) {
+ d.bdRead = false
+ return d.decLen()
+}
+
+func (d *simpleDecDriver) readArrayLen() (length int) {
+ d.bdRead = false
+ return d.decLen()
+}
+
+func (d *simpleDecDriver) decLen() int {
+ switch d.bd % 8 {
+ case 0:
+ return 0
+ case 1:
+ return int(d.r.readn1())
+ case 2:
+ return int(d.r.readUint16())
+ case 3:
+ ui := uint64(d.r.readUint32())
+ checkOverflow(ui, 0, intBitsize)
+ return int(ui)
+ case 4:
+ ui := d.r.readUint64()
+ checkOverflow(ui, 0, intBitsize)
+ return int(ui)
+ }
+ decErr("decLen: Cannot read length: bd%8 must be in range 0..4. Got: %d", d.bd%8)
+ return -1
+}
+
+func (d *simpleDecDriver) decodeString() (s string) {
+ s = string(d.r.readn(d.decLen()))
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) {
+ if clen := d.decLen(); clen > 0 {
+ // if no contents in stream, don't update the passed byteslice
+ if len(bs) != clen {
+ if len(bs) > clen {
+ bs = bs[:clen]
+ } else {
+ bs = make([]byte, clen)
+ }
+ bsOut = bs
+ changed = true
+ }
+ d.r.readb(bs)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
+ switch d.bd {
+ case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4:
+ l := d.decLen()
+ xtag = d.r.readn1()
+ if verifyTag && xtag != tag {
+ decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
+ }
+ xbs = d.r.readn(l)
+ case simpleVdByteArray, simpleVdByteArray + 1, simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4:
+ xbs, _ = d.decodeBytes(nil)
+ default:
+ decErr("Invalid d.vd for extensions (Expecting extensions or byte array). Got: 0x%x", d.bd)
+ }
+ d.bdRead = false
+ return
+}
+
+func (d *simpleDecDriver) decodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
+ d.initReadNext()
+
+ switch d.bd {
+ case simpleVdNil:
+ vt = valueTypeNil
+ case simpleVdFalse:
+ vt = valueTypeBool
+ v = false
+ case simpleVdTrue:
+ vt = valueTypeBool
+ v = true
+ case simpleVdPosInt, simpleVdPosInt + 1, simpleVdPosInt + 2, simpleVdPosInt + 3:
+ vt = valueTypeUint
+ ui, _, _ := d.decIntAny()
+ v = ui
+ case simpleVdNegInt, simpleVdNegInt + 1, simpleVdNegInt + 2, simpleVdNegInt + 3:
+ vt = valueTypeInt
+ _, i, _ := d.decIntAny()
+ v = i
+ case simpleVdFloat32:
+ vt = valueTypeFloat
+ v = d.decodeFloat(true)
+ case simpleVdFloat64:
+ vt = valueTypeFloat
+ v = d.decodeFloat(false)
+ case simpleVdString, simpleVdString + 1, simpleVdString + 2, simpleVdString + 3, simpleVdString + 4:
+ vt = valueTypeString
+ v = d.decodeString()
+ case simpleVdByteArray, simpleVdByteArray + 1, simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4:
+ vt = valueTypeBytes
+ v, _ = d.decodeBytes(nil)
+ case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4:
+ vt = valueTypeExt
+ l := d.decLen()
+ var re RawExt
+ re.Tag = d.r.readn1()
+ re.Data = d.r.readn(l)
+ v = &re
+ vt = valueTypeExt
+ case simpleVdArray, simpleVdArray + 1, simpleVdArray + 2, simpleVdArray + 3, simpleVdArray + 4:
+ vt = valueTypeArray
+ decodeFurther = true
+ case simpleVdMap, simpleVdMap + 1, simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4:
+ vt = valueTypeMap
+ decodeFurther = true
+ default:
+ decErr("decodeNaked: Unrecognized d.vd: 0x%x", d.bd)
+ }
+
+ if !decodeFurther {
+ d.bdRead = false
+ }
+ return
+}
+
+//------------------------------------
+
+// SimpleHandle is a Handle for a very simple encoding format.
+//
+// simple is a simplistic codec similar to binc, but not as compact.
+// - Encoding of a value is always preceeded by the descriptor byte (bd)
+// - True, false, nil are encoded fully in 1 byte (the descriptor)
+// - Integers (intXXX, uintXXX) are encoded in 1, 2, 4 or 8 bytes (plus a descriptor byte).
+// There are positive (uintXXX and intXXX >= 0) and negative (intXXX < 0) integers.
+// - Floats are encoded in 4 or 8 bytes (plus a descriptor byte)
+// - Lenght of containers (strings, bytes, array, map, extensions)
+// are encoded in 0, 1, 2, 4 or 8 bytes.
+// Zero-length containers have no length encoded.
+// For others, the number of bytes is given by pow(2, bd%3)
+// - maps are encoded as [bd] [length] [[key][value]]...
+// - arrays are encoded as [bd] [length] [value]...
+// - extensions are encoded as [bd] [length] [tag] [byte]...
+// - strings/bytearrays are encoded as [bd] [length] [byte]...
+//
+// The full spec will be published soon.
+type SimpleHandle struct {
+ BasicHandle
+}
+
+func (h *SimpleHandle) newEncDriver(w encWriter) encDriver {
+ return &simpleEncDriver{w: w, h: h}
+}
+
+func (h *SimpleHandle) newDecDriver(r decReader) decDriver {
+ return &simpleDecDriver{r: r, h: h}
+}
+
+func (_ *SimpleHandle) writeExt() bool {
+ return true
+}
+
+func (h *SimpleHandle) getBasicHandle() *BasicHandle {
+ return &h.BasicHandle
+}
+
+var _ decDriver = (*simpleDecDriver)(nil)
+var _ encDriver = (*simpleEncDriver)(nil)
diff --git a/vendor/github.com/hashicorp/go-msgpack/codec/time.go b/vendor/github.com/hashicorp/go-msgpack/codec/time.go
new file mode 100644
index 0000000..c86d653
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-msgpack/codec/time.go
@@ -0,0 +1,193 @@
+// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a BSD-style license found in the LICENSE file.
+
+package codec
+
+import (
+ "time"
+)
+
+var (
+ timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
+)
+
+// EncodeTime encodes a time.Time as a []byte, including
+// information on the instant in time and UTC offset.
+//
+// Format Description
+//
+// A timestamp is composed of 3 components:
+//
+// - secs: signed integer representing seconds since unix epoch
+// - nsces: unsigned integer representing fractional seconds as a
+// nanosecond offset within secs, in the range 0 <= nsecs < 1e9
+// - tz: signed integer representing timezone offset in minutes east of UTC,
+// and a dst (daylight savings time) flag
+//
+// When encoding a timestamp, the first byte is the descriptor, which
+// defines which components are encoded and how many bytes are used to
+// encode secs and nsecs components. *If secs/nsecs is 0 or tz is UTC, it
+// is not encoded in the byte array explicitly*.
+//
+// Descriptor 8 bits are of the form `A B C DDD EE`:
+// A: Is secs component encoded? 1 = true
+// B: Is nsecs component encoded? 1 = true
+// C: Is tz component encoded? 1 = true
+// DDD: Number of extra bytes for secs (range 0-7).
+// If A = 1, secs encoded in DDD+1 bytes.
+// If A = 0, secs is not encoded, and is assumed to be 0.
+// If A = 1, then we need at least 1 byte to encode secs.
+// DDD says the number of extra bytes beyond that 1.
+// E.g. if DDD=0, then secs is represented in 1 byte.
+// if DDD=2, then secs is represented in 3 bytes.
+// EE: Number of extra bytes for nsecs (range 0-3).
+// If B = 1, nsecs encoded in EE+1 bytes (similar to secs/DDD above)
+//
+// Following the descriptor bytes, subsequent bytes are:
+//
+// secs component encoded in `DDD + 1` bytes (if A == 1)
+// nsecs component encoded in `EE + 1` bytes (if B == 1)
+// tz component encoded in 2 bytes (if C == 1)
+//
+// secs and nsecs components are integers encoded in a BigEndian
+// 2-complement encoding format.
+//
+// tz component is encoded as 2 bytes (16 bits). Most significant bit 15 to
+// Least significant bit 0 are described below:
+//
+// Timezone offset has a range of -12:00 to +14:00 (ie -720 to +840 minutes).
+// Bit 15 = have\_dst: set to 1 if we set the dst flag.
+// Bit 14 = dst\_on: set to 1 if dst is in effect at the time, or 0 if not.
+// Bits 13..0 = timezone offset in minutes. It is a signed integer in Big Endian format.
+//
+func encodeTime(t time.Time) []byte {
+ //t := rv.Interface().(time.Time)
+ tsecs, tnsecs := t.Unix(), t.Nanosecond()
+ var (
+ bd byte
+ btmp [8]byte
+ bs [16]byte
+ i int = 1
+ )
+ l := t.Location()
+ if l == time.UTC {
+ l = nil
+ }
+ if tsecs != 0 {
+ bd = bd | 0x80
+ bigen.PutUint64(btmp[:], uint64(tsecs))
+ f := pruneSignExt(btmp[:], tsecs >= 0)
+ bd = bd | (byte(7-f) << 2)
+ copy(bs[i:], btmp[f:])
+ i = i + (8 - f)
+ }
+ if tnsecs != 0 {
+ bd = bd | 0x40
+ bigen.PutUint32(btmp[:4], uint32(tnsecs))
+ f := pruneSignExt(btmp[:4], true)
+ bd = bd | byte(3-f)
+ copy(bs[i:], btmp[f:4])
+ i = i + (4 - f)
+ }
+ if l != nil {
+ bd = bd | 0x20
+ // Note that Go Libs do not give access to dst flag.
+ _, zoneOffset := t.Zone()
+ //zoneName, zoneOffset := t.Zone()
+ zoneOffset /= 60
+ z := uint16(zoneOffset)
+ bigen.PutUint16(btmp[:2], z)
+ // clear dst flags
+ bs[i] = btmp[0] & 0x3f
+ bs[i+1] = btmp[1]
+ i = i + 2
+ }
+ bs[0] = bd
+ return bs[0:i]
+}
+
+// DecodeTime decodes a []byte into a time.Time.
+func decodeTime(bs []byte) (tt time.Time, err error) {
+ bd := bs[0]
+ var (
+ tsec int64
+ tnsec uint32
+ tz uint16
+ i byte = 1
+ i2 byte
+ n byte
+ )
+ if bd&(1<<7) != 0 {
+ var btmp [8]byte
+ n = ((bd >> 2) & 0x7) + 1
+ i2 = i + n
+ copy(btmp[8-n:], bs[i:i2])
+ //if first bit of bs[i] is set, then fill btmp[0..8-n] with 0xff (ie sign extend it)
+ if bs[i]&(1<<7) != 0 {
+ copy(btmp[0:8-n], bsAll0xff)
+ //for j,k := byte(0), 8-n; j < k; j++ { btmp[j] = 0xff }
+ }
+ i = i2
+ tsec = int64(bigen.Uint64(btmp[:]))
+ }
+ if bd&(1<<6) != 0 {
+ var btmp [4]byte
+ n = (bd & 0x3) + 1
+ i2 = i + n
+ copy(btmp[4-n:], bs[i:i2])
+ i = i2
+ tnsec = bigen.Uint32(btmp[:])
+ }
+ if bd&(1<<5) == 0 {
+ tt = time.Unix(tsec, int64(tnsec)).UTC()
+ return
+ }
+ // In stdlib time.Parse, when a date is parsed without a zone name, it uses "" as zone name.
+ // However, we need name here, so it can be shown when time is printed.
+ // Zone name is in form: UTC-08:00.
+ // Note that Go Libs do not give access to dst flag, so we ignore dst bits
+
+ i2 = i + 2
+ tz = bigen.Uint16(bs[i:i2])
+ i = i2
+ // sign extend sign bit into top 2 MSB (which were dst bits):
+ if tz&(1<<13) == 0 { // positive
+ tz = tz & 0x3fff //clear 2 MSBs: dst bits
+ } else { // negative
+ tz = tz | 0xc000 //set 2 MSBs: dst bits
+ //tzname[3] = '-' (TODO: verify. this works here)
+ }
+ tzint := int16(tz)
+ if tzint == 0 {
+ tt = time.Unix(tsec, int64(tnsec)).UTC()
+ } else {
+ // For Go Time, do not use a descriptive timezone.
+ // It's unnecessary, and makes it harder to do a reflect.DeepEqual.
+ // The Offset already tells what the offset should be, if not on UTC and unknown zone name.
+ // var zoneName = timeLocUTCName(tzint)
+ tt = time.Unix(tsec, int64(tnsec)).In(time.FixedZone("", int(tzint)*60))
+ }
+ return
+}
+
+func timeLocUTCName(tzint int16) string {
+ if tzint == 0 {
+ return "UTC"
+ }
+ var tzname = []byte("UTC+00:00")
+ //tzname := fmt.Sprintf("UTC%s%02d:%02d", tzsign, tz/60, tz%60) //perf issue using Sprintf. inline below.
+ //tzhr, tzmin := tz/60, tz%60 //faster if u convert to int first
+ var tzhr, tzmin int16
+ if tzint < 0 {
+ tzname[3] = '-' // (TODO: verify. this works here)
+ tzhr, tzmin = -tzint/60, (-tzint)%60
+ } else {
+ tzhr, tzmin = tzint/60, tzint%60
+ }
+ tzname[4] = timeDigits[tzhr/10]
+ tzname[5] = timeDigits[tzhr%10]
+ tzname[7] = timeDigits[tzmin/10]
+ tzname[8] = timeDigits[tzmin%10]
+ return string(tzname)
+ //return time.FixedZone(string(tzname), int(tzint)*60)
+}
diff --git a/vendor/github.com/hashicorp/go-multierror/LICENSE b/vendor/github.com/hashicorp/go-multierror/LICENSE
new file mode 100644
index 0000000..82b4de9
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-multierror/LICENSE
@@ -0,0 +1,353 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. “Contributor”
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. “Contributor Version”
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor’s Contribution.
+
+1.3. “Contribution”
+
+ means Covered Software of a particular Contributor.
+
+1.4. “Covered Software”
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. “Incompatible With Secondary Licenses”
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of version
+ 1.1 or earlier of the License, but not also under the terms of a
+ Secondary License.
+
+1.6. “Executable Form”
+
+ means any form of the work other than Source Code Form.
+
+1.7. “Larger Work”
+
+ means a work that combines Covered Software with other material, in a separate
+ file or files, that is not Covered Software.
+
+1.8. “License”
+
+ means this document.
+
+1.9. “Licensable”
+
+ means having the right to grant, to the maximum extent possible, whether at the
+ time of the initial grant or subsequently, any and all of the rights conveyed by
+ this License.
+
+1.10. “Modifications”
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to, deletion
+ from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. “Patent Claims” of a Contributor
+
+ means any patent claim(s), including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by such Contributor that
+ would be infringed, but for the grant of the License, by the making,
+ using, selling, offering for sale, having made, import, or transfer of
+ either its Contributions or its Contributor Version.
+
+1.12. “Secondary License”
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. “Source Code Form”
+
+ means the form of the work preferred for making modifications.
+
+1.14. “You” (or “Your”)
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, “You” includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, “control” means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or as
+ part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its Contributions
+ or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution become
+ effective for each Contribution on the date the Contributor first distributes
+ such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under this
+ License. No additional rights or licenses will be implied from the distribution
+ or licensing of Covered Software under this License. Notwithstanding Section
+ 2.1(b) above, no patent license is granted by a Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party’s
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of its
+ Contributions.
+
+ This License does not grant any rights in the trademarks, service marks, or
+ logos of any Contributor (except as may be necessary to comply with the
+ notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this License
+ (see Section 10.2) or under the terms of a Secondary License (if permitted
+ under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its Contributions
+ are its original creation(s) or it has sufficient rights to grant the
+ rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under applicable
+ copyright doctrines of fair use, fair dealing, or other equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under the
+ terms of this License. You must inform recipients that the Source Code Form
+ of the Covered Software is governed by the terms of this License, and how
+ they can obtain a copy of this License. You may not attempt to alter or
+ restrict the recipients’ rights in the Source Code Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this License,
+ or sublicense it under different terms, provided that the license for
+ the Executable Form does not attempt to limit or alter the recipients’
+ rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for the
+ Covered Software. If the Larger Work is a combination of Covered Software
+ with a work governed by one or more Secondary Licenses, and the Covered
+ Software is not Incompatible With Secondary Licenses, this License permits
+ You to additionally distribute such Covered Software under the terms of
+ such Secondary License(s), so that the recipient of the Larger Work may, at
+ their option, further distribute the Covered Software under the terms of
+ either this License or such Secondary License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices (including
+ copyright notices, patent notices, disclaimers of warranty, or limitations
+ of liability) contained within the Source Code Form of the Covered
+ Software, except that You may alter any license notices to the extent
+ required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on behalf
+ of any Contributor. You must make it absolutely clear that any such
+ warranty, support, indemnity, or liability obligation is offered by You
+ alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute, judicial
+ order, or regulation then You must: (a) comply with the terms of this License
+ to the maximum extent possible; and (b) describe the limitations and the code
+ they affect. Such description must be placed in a text file included with all
+ distributions of the Covered Software under this License. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing basis,
+ if such Contributor fails to notify You of the non-compliance by some
+ reasonable means prior to 60 days after You have come back into compliance.
+ Moreover, Your grants from a particular Contributor are reinstated on an
+ ongoing basis if such Contributor notifies You of the non-compliance by
+ some reasonable means, this is the first time You have received notice of
+ non-compliance with this License from such Contributor, and You become
+ compliant prior to 30 days after Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions, counter-claims,
+ and cross-claims) alleging that a Contributor Version directly or
+ indirectly infringes any patent, then the rights granted to You by any and
+ all Contributors for the Covered Software under Section 2.1 of this License
+ shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an “as is” basis, without
+ warranty of any kind, either expressed, implied, or statutory, including,
+ without limitation, warranties that the Covered Software is free of defects,
+ merchantable, fit for a particular purpose or non-infringing. The entire
+ risk as to the quality and performance of the Covered Software is with You.
+ Should any Covered Software prove defective in any respect, You (not any
+ Contributor) assume the cost of any necessary servicing, repair, or
+ correction. This disclaimer of warranty constitutes an essential part of this
+ License. No use of any Covered Software is authorized under this License
+ except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from such
+ party’s negligence to the extent applicable law prohibits such limitation.
+ Some jurisdictions do not allow the exclusion or limitation of incidental or
+ consequential damages, so this exclusion and limitation may not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts of
+ a jurisdiction where the defendant maintains its principal place of business
+ and such litigation shall be governed by laws of that jurisdiction, without
+ reference to its conflict-of-law provisions. Nothing in this Section shall
+ prevent a party’s ability to bring cross-claims or counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject matter
+ hereof. If any provision of this License is held to be unenforceable, such
+ provision shall be reformed only to the extent necessary to make it
+ enforceable. Any law or regulation which provides that the language of a
+ contract shall be construed against the drafter shall not be used to construe
+ this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version of
+ the License under which You originally received the Covered Software, or
+ under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a modified
+ version of this License if you rename the license and remove any
+ references to the name of the license steward (except to note that such
+ modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
+ If You choose to distribute Source Code Form that is Incompatible With
+ Secondary Licenses under the terms of this version of the License, the
+ notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file, then
+You may include the notice in a location (such as a LICENSE file in a relevant
+directory) where a recipient would be likely to look for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - “Incompatible With Secondary Licenses” Notice
+
+ This Source Code Form is “Incompatible
+ With Secondary Licenses”, as defined by
+ the Mozilla Public License, v. 2.0.
diff --git a/vendor/github.com/hashicorp/go-multierror/README.md b/vendor/github.com/hashicorp/go-multierror/README.md
new file mode 100644
index 0000000..e81be50
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-multierror/README.md
@@ -0,0 +1,91 @@
+# go-multierror
+
+`go-multierror` is a package for Go that provides a mechanism for
+representing a list of `error` values as a single `error`.
+
+This allows a function in Go to return an `error` that might actually
+be a list of errors. If the caller knows this, they can unwrap the
+list and access the errors. If the caller doesn't know, the error
+formats to a nice human-readable format.
+
+`go-multierror` implements the
+[errwrap](https://github.com/hashicorp/errwrap) interface so that it can
+be used with that library, as well.
+
+## Installation and Docs
+
+Install using `go get github.com/hashicorp/go-multierror`.
+
+Full documentation is available at
+http://godoc.org/github.com/hashicorp/go-multierror
+
+## Usage
+
+go-multierror is easy to use and purposely built to be unobtrusive in
+existing Go applications/libraries that may not be aware of it.
+
+**Building a list of errors**
+
+The `Append` function is used to create a list of errors. This function
+behaves a lot like the Go built-in `append` function: it doesn't matter
+if the first argument is nil, a `multierror.Error`, or any other `error`,
+the function behaves as you would expect.
+
+```go
+var result error
+
+if err := step1(); err != nil {
+ result = multierror.Append(result, err)
+}
+if err := step2(); err != nil {
+ result = multierror.Append(result, err)
+}
+
+return result
+```
+
+**Customizing the formatting of the errors**
+
+By specifying a custom `ErrorFormat`, you can customize the format
+of the `Error() string` function:
+
+```go
+var result *multierror.Error
+
+// ... accumulate errors here, maybe using Append
+
+if result != nil {
+ result.ErrorFormat = func([]error) string {
+ return "errors!"
+ }
+}
+```
+
+**Accessing the list of errors**
+
+`multierror.Error` implements `error` so if the caller doesn't know about
+multierror, it will work just fine. But if you're aware a multierror might
+be returned, you can use type switches to access the list of errors:
+
+```go
+if err := something(); err != nil {
+ if merr, ok := err.(*multierror.Error); ok {
+ // Use merr.Errors
+ }
+}
+```
+
+**Returning a multierror only if there are errors**
+
+If you build a `multierror.Error`, you can use the `ErrorOrNil` function
+to return an `error` implementation only if there are errors to return:
+
+```go
+var result *multierror.Error
+
+// ... accumulate errors here
+
+// Return the `error` only if errors were added to the multierror, otherwise
+// return nil since there are no errors.
+return result.ErrorOrNil()
+```
diff --git a/vendor/github.com/hashicorp/go-multierror/append.go b/vendor/github.com/hashicorp/go-multierror/append.go
new file mode 100644
index 0000000..8d22ee7
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-multierror/append.go
@@ -0,0 +1,30 @@
+package multierror
+
+// Append is a helper function that will append more errors
+// onto an Error in order to create a larger multi-error.
+//
+// If err is not a multierror.Error, then it will be turned into
+// one. If any of the errs are multierr.Error, they will be flattened
+// one level into err.
+func Append(err error, errs ...error) *Error {
+ switch err := err.(type) {
+ case *Error:
+ // Typed nils can reach here, so initialize if we are nil
+ if err == nil {
+ err = new(Error)
+ }
+
+ err.Errors = append(err.Errors, errs...)
+ return err
+ default:
+ newErrs := make([]error, 0, len(errs)+1)
+ if err != nil {
+ newErrs = append(newErrs, err)
+ }
+ newErrs = append(newErrs, errs...)
+
+ return &Error{
+ Errors: newErrs,
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/go-multierror/format.go b/vendor/github.com/hashicorp/go-multierror/format.go
new file mode 100644
index 0000000..bb65a12
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-multierror/format.go
@@ -0,0 +1,23 @@
+package multierror
+
+import (
+ "fmt"
+ "strings"
+)
+
+// ErrorFormatFunc is a function callback that is called by Error to
+// turn the list of errors into a string.
+type ErrorFormatFunc func([]error) string
+
+// ListFormatFunc is a basic formatter that outputs the number of errors
+// that occurred along with a bullet point list of the errors.
+func ListFormatFunc(es []error) string {
+ points := make([]string, len(es))
+ for i, err := range es {
+ points[i] = fmt.Sprintf("* %s", err)
+ }
+
+ return fmt.Sprintf(
+ "%d error(s) occurred:\n\n%s",
+ len(es), strings.Join(points, "\n"))
+}
diff --git a/vendor/github.com/hashicorp/go-multierror/multierror.go b/vendor/github.com/hashicorp/go-multierror/multierror.go
new file mode 100644
index 0000000..2ea0827
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-multierror/multierror.go
@@ -0,0 +1,51 @@
+package multierror
+
+import (
+ "fmt"
+)
+
+// Error is an error type to track multiple errors. This is used to
+// accumulate errors in cases and return them as a single "error".
+type Error struct {
+ Errors []error
+ ErrorFormat ErrorFormatFunc
+}
+
+func (e *Error) Error() string {
+ fn := e.ErrorFormat
+ if fn == nil {
+ fn = ListFormatFunc
+ }
+
+ return fn(e.Errors)
+}
+
+// ErrorOrNil returns an error interface if this Error represents
+// a list of errors, or returns nil if the list of errors is empty. This
+// function is useful at the end of accumulation to make sure that the value
+// returned represents the existence of errors.
+func (e *Error) ErrorOrNil() error {
+ if e == nil {
+ return nil
+ }
+ if len(e.Errors) == 0 {
+ return nil
+ }
+
+ return e
+}
+
+func (e *Error) GoString() string {
+ return fmt.Sprintf("*%#v", *e)
+}
+
+// WrappedErrors returns the list of errors that this Error is wrapping.
+// It is an implementatin of the errwrap.Wrapper interface so that
+// multierror.Error can be used with that library.
+//
+// This method is not safe to be called concurrently and is no different
+// than accessing the Errors field directly. It is implementd only to
+// satisfy the errwrap.Wrapper interface.
+func (e *Error) WrappedErrors() []error {
+ return e.Errors
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/LICENSE b/vendor/github.com/hashicorp/go-sockaddr/LICENSE
new file mode 100644
index 0000000..a612ad9
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/LICENSE
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
diff --git a/vendor/github.com/hashicorp/go-sockaddr/README.md b/vendor/github.com/hashicorp/go-sockaddr/README.md
new file mode 100644
index 0000000..a2e170a
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/README.md
@@ -0,0 +1,118 @@
+# go-sockaddr
+
+## `sockaddr` Library
+
+Socket address convenience functions for Go. `go-sockaddr` is a convenience
+library that makes doing the right thing with IP addresses easy. `go-sockaddr`
+is loosely modeled after the UNIX `sockaddr_t` and creates a union of the family
+of `sockaddr_t` types (see below for an ascii diagram). Library documentation
+is available
+at
+[https://godoc.org/github.com/hashicorp/go-sockaddr](https://godoc.org/github.com/hashicorp/go-sockaddr).
+The primary intent of the library was to make it possible to define heuristics
+for selecting the correct IP addresses when a configuration is evaluated at
+runtime. See
+the
+[docs](https://godoc.org/github.com/hashicorp/go-sockaddr),
+[`template` package](https://godoc.org/github.com/hashicorp/go-sockaddr/template),
+tests,
+and
+[CLI utility](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr)
+for details and hints as to how to use this library.
+
+For example, with this library it is possible to find an IP address that:
+
+* is attached to a default route
+ ([`GetDefaultInterfaces()`](https://godoc.org/github.com/hashicorp/go-sockaddr#GetDefaultInterfaces))
+* is contained within a CIDR block ([`IfByNetwork()`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByNetwork))
+* is an RFC1918 address
+ ([`IfByRFC("1918")`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByRFC))
+* is ordered
+ ([`OrderedIfAddrBy(args)`](https://godoc.org/github.com/hashicorp/go-sockaddr#OrderedIfAddrBy) where
+ `args` includes, but is not limited
+ to,
+ [`AscIfType`](https://godoc.org/github.com/hashicorp/go-sockaddr#AscIfType),
+ [`AscNetworkSize`](https://godoc.org/github.com/hashicorp/go-sockaddr#AscNetworkSize))
+* excludes all IPv6 addresses
+ ([`IfByType("^(IPv4)$")`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByType))
+* is larger than a `/32`
+ ([`IfByMaskSize(32)`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByMaskSize))
+* is not on a `down` interface
+ ([`ExcludeIfs("flags", "down")`](https://godoc.org/github.com/hashicorp/go-sockaddr#ExcludeIfs))
+* preferences an IPv6 address over an IPv4 address
+ ([`SortIfByType()`](https://godoc.org/github.com/hashicorp/go-sockaddr#SortIfByType) +
+ [`ReverseIfAddrs()`](https://godoc.org/github.com/hashicorp/go-sockaddr#ReverseIfAddrs)); and
+* excludes any IP in RFC6890 address
+ ([`IfByRFC("6890")`](https://godoc.org/github.com/hashicorp/go-sockaddr#IfByRFC))
+
+Or any combination or variation therein.
+
+There are also a few simple helper functions such as `GetPublicIP` and
+`GetPrivateIP` which both return strings and select the first public or private
+IP address on the default interface, respectively. Similarly, there is also a
+helper function called `GetInterfaceIP` which returns the first usable IP
+address on the named interface.
+
+## `sockaddr` CLI
+
+Given the possible complexity of the `sockaddr` library, there is a CLI utility
+that accompanies the library, also
+called
+[`sockaddr`](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr).
+The
+[`sockaddr`](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr)
+utility exposes nearly all of the functionality of the library and can be used
+either as an administrative tool or testing tool. To install
+the
+[`sockaddr`](https://github.com/hashicorp/go-sockaddr/tree/master/cmd/sockaddr),
+run:
+
+```text
+$ go get -u github.com/hashicorp/go-sockaddr/cmd/sockaddr
+```
+
+If you're familiar with UNIX's `sockaddr` struct's, the following diagram
+mapping the C `sockaddr` (top) to `go-sockaddr` structs (bottom) and
+interfaces will be helpful:
+
+```
++-------------------------------------------------------+
+| |
+| sockaddr |
+| SockAddr |
+| |
+| +--------------+ +----------------------------------+ |
+| | sockaddr_un | | | |
+| | SockAddrUnix | | sockaddr_in{,6} | |
+| +--------------+ | IPAddr | |
+| | | |
+| | +-------------+ +--------------+ | |
+| | | sockaddr_in | | sockaddr_in6 | | |
+| | | IPv4Addr | | IPv6Addr | | |
+| | +-------------+ +--------------+ | |
+| | | |
+| +----------------------------------+ |
+| |
++-------------------------------------------------------+
+```
+
+## Inspiration and Design
+
+There were many subtle inspirations that led to this design, but the most direct
+inspiration for the filtering syntax was
+OpenBSD's
+[`pf.conf(5)`](https://www.freebsd.org/cgi/man.cgi?query=pf.conf&apropos=0&sektion=0&arch=default&format=html#PARAMETERS) firewall
+syntax that lets you select the first IP address on a given named interface.
+The original problem stemmed from:
+
+* needing to create immutable images using [Packer](https://www.packer.io) that
+ ran the [Consul](https://www.consul.io) process (Consul can only use one IP
+ address at a time);
+* images that may or may not have multiple interfaces or IP addresses at
+ runtime; and
+* we didn't want to rely on configuration management to render out the correct
+ IP address if the VM image was being used in an auto-scaling group.
+
+Instead we needed some way to codify a heuristic that would correctly select the
+right IP address but the input parameters were not known when the image was
+created.
diff --git a/vendor/github.com/hashicorp/go-sockaddr/doc.go b/vendor/github.com/hashicorp/go-sockaddr/doc.go
new file mode 100644
index 0000000..90671de
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/doc.go
@@ -0,0 +1,5 @@
+/*
+Package sockaddr is a Go implementation of the UNIX socket family data types and
+related helper functions.
+*/
+package sockaddr
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go b/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go
new file mode 100644
index 0000000..3e4ff9f
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/ifaddr.go
@@ -0,0 +1,126 @@
+package sockaddr
+
+// ifAddrAttrMap is a map of the IfAddr type-specific attributes.
+var ifAddrAttrMap map[AttrName]func(IfAddr) string
+var ifAddrAttrs []AttrName
+
+func init() {
+ ifAddrAttrInit()
+}
+
+// GetPrivateIP returns a string with a single IP address that is part of RFC
+// 6890 and has a default route. If the system can't determine its IP address
+// or find an RFC 6890 IP address, an empty string will be returned instead.
+// This function is the `eval` equivalent of:
+//
+// ```
+// $ sockaddr eval -r '{{GetPrivateInterfaces | attr "address"}}'
+/// ```
+func GetPrivateIP() (string, error) {
+ privateIfs, err := GetPrivateInterfaces()
+ if err != nil {
+ return "", err
+ }
+ if len(privateIfs) < 1 {
+ return "", nil
+ }
+
+ ifAddr := privateIfs[0]
+ ip := *ToIPAddr(ifAddr.SockAddr)
+ return ip.NetIP().String(), nil
+}
+
+// GetPublicIP returns a string with a single IP address that is NOT part of RFC
+// 6890 and has a default route. If the system can't determine its IP address
+// or find a non RFC 6890 IP address, an empty string will be returned instead.
+// This function is the `eval` equivalent of:
+//
+// ```
+// $ sockaddr eval -r '{{GetPublicInterfaces | attr "address"}}'
+/// ```
+func GetPublicIP() (string, error) {
+ publicIfs, err := GetPublicInterfaces()
+ if err != nil {
+ return "", err
+ } else if len(publicIfs) < 1 {
+ return "", nil
+ }
+
+ ifAddr := publicIfs[0]
+ ip := *ToIPAddr(ifAddr.SockAddr)
+ return ip.NetIP().String(), nil
+}
+
+// GetInterfaceIP returns a string with a single IP address sorted by the size
+// of the network (i.e. IP addresses with a smaller netmask, larger network
+// size, are sorted first). This function is the `eval` equivalent of:
+//
+// ```
+// $ sockaddr eval -r '{{GetAllInterfaces | include "name" <<ARG>> | sort "type,size" | include "flag" "forwardable" | attr "address" }}'
+/// ```
+func GetInterfaceIP(namedIfRE string) (string, error) {
+ ifAddrs, err := GetAllInterfaces()
+ if err != nil {
+ return "", err
+ }
+
+ ifAddrs, _, err = IfByName(namedIfRE, ifAddrs)
+ if err != nil {
+ return "", err
+ }
+
+ ifAddrs, _, err = IfByFlag("forwardable", ifAddrs)
+ if err != nil {
+ return "", err
+ }
+
+ ifAddrs, err = SortIfBy("+type,+size", ifAddrs)
+ if err != nil {
+ return "", err
+ }
+
+ if len(ifAddrs) == 0 {
+ return "", err
+ }
+
+ ip := ToIPAddr(ifAddrs[0].SockAddr)
+ if ip == nil {
+ return "", err
+ }
+
+ return IPAddrAttr(*ip, "address"), nil
+}
+
+// IfAddrAttrs returns a list of attributes supported by the IfAddr type
+func IfAddrAttrs() []AttrName {
+ return ifAddrAttrs
+}
+
+// IfAddrAttr returns a string representation of an attribute for the given
+// IfAddr.
+func IfAddrAttr(ifAddr IfAddr, attrName AttrName) string {
+ fn, found := ifAddrAttrMap[attrName]
+ if !found {
+ return ""
+ }
+
+ return fn(ifAddr)
+}
+
+// ifAddrAttrInit is called once at init()
+func ifAddrAttrInit() {
+ // Sorted for human readability
+ ifAddrAttrs = []AttrName{
+ "flags",
+ "name",
+ }
+
+ ifAddrAttrMap = map[AttrName]func(ifAddr IfAddr) string{
+ "flags": func(ifAddr IfAddr) string {
+ return ifAddr.Interface.Flags.String()
+ },
+ "name": func(ifAddr IfAddr) string {
+ return ifAddr.Interface.Name
+ },
+ }
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go b/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go
new file mode 100644
index 0000000..8233be2
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/ifaddrs.go
@@ -0,0 +1,969 @@
+package sockaddr
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+// IfAddrs is a slice of IfAddr
+type IfAddrs []IfAddr
+
+func (ifs IfAddrs) Len() int { return len(ifs) }
+
+// CmpIfFunc is the function signature that must be met to be used in the
+// OrderedIfAddrBy multiIfAddrSorter
+type CmpIfAddrFunc func(p1, p2 *IfAddr) int
+
+// multiIfAddrSorter implements the Sort interface, sorting the IfAddrs within.
+type multiIfAddrSorter struct {
+ ifAddrs IfAddrs
+ cmp []CmpIfAddrFunc
+}
+
+// Sort sorts the argument slice according to the Cmp functions passed to
+// OrderedIfAddrBy.
+func (ms *multiIfAddrSorter) Sort(ifAddrs IfAddrs) {
+ ms.ifAddrs = ifAddrs
+ sort.Sort(ms)
+}
+
+// OrderedIfAddrBy sorts SockAddr by the list of sort function pointers.
+func OrderedIfAddrBy(cmpFuncs ...CmpIfAddrFunc) *multiIfAddrSorter {
+ return &multiIfAddrSorter{
+ cmp: cmpFuncs,
+ }
+}
+
+// Len is part of sort.Interface.
+func (ms *multiIfAddrSorter) Len() int {
+ return len(ms.ifAddrs)
+}
+
+// Less is part of sort.Interface. It is implemented by looping along the Cmp()
+// functions until it finds a comparison that is either less than or greater
+// than. A return value of 0 defers sorting to the next function in the
+// multisorter (which means the results of sorting may leave the resutls in a
+// non-deterministic order).
+func (ms *multiIfAddrSorter) Less(i, j int) bool {
+ p, q := &ms.ifAddrs[i], &ms.ifAddrs[j]
+ // Try all but the last comparison.
+ var k int
+ for k = 0; k < len(ms.cmp)-1; k++ {
+ cmp := ms.cmp[k]
+ x := cmp(p, q)
+ switch x {
+ case -1:
+ // p < q, so we have a decision.
+ return true
+ case 1:
+ // p > q, so we have a decision.
+ return false
+ }
+ // p == q; try the next comparison.
+ }
+ // All comparisons to here said "equal", so just return whatever the
+ // final comparison reports.
+ switch ms.cmp[k](p, q) {
+ case -1:
+ return true
+ case 1:
+ return false
+ default:
+ // Still a tie! Now what?
+ return false
+ panic("undefined sort order for remaining items in the list")
+ }
+}
+
+// Swap is part of sort.Interface.
+func (ms *multiIfAddrSorter) Swap(i, j int) {
+ ms.ifAddrs[i], ms.ifAddrs[j] = ms.ifAddrs[j], ms.ifAddrs[i]
+}
+
+// AscIfAddress is a sorting function to sort IfAddrs by their respective
+// address type. Non-equal types are deferred in the sort.
+func AscIfAddress(p1Ptr, p2Ptr *IfAddr) int {
+ return AscAddress(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
+}
+
+// AscIfName is a sorting function to sort IfAddrs by their interface names.
+func AscIfName(p1Ptr, p2Ptr *IfAddr) int {
+ return strings.Compare(p1Ptr.Name, p2Ptr.Name)
+}
+
+// AscIfNetworkSize is a sorting function to sort IfAddrs by their respective
+// network mask size.
+func AscIfNetworkSize(p1Ptr, p2Ptr *IfAddr) int {
+ return AscNetworkSize(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
+}
+
+// AscIfPort is a sorting function to sort IfAddrs by their respective
+// port type. Non-equal types are deferred in the sort.
+func AscIfPort(p1Ptr, p2Ptr *IfAddr) int {
+ return AscPort(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
+}
+
+// AscIfPrivate is a sorting function to sort IfAddrs by "private" values before
+// "public" values. Both IPv4 and IPv6 are compared against RFC6890 (RFC6890
+// includes, and is not limited to, RFC1918 and RFC6598 for IPv4, and IPv6
+// includes RFC4193).
+func AscIfPrivate(p1Ptr, p2Ptr *IfAddr) int {
+ return AscPrivate(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
+}
+
+// AscIfType is a sorting function to sort IfAddrs by their respective address
+// type. Non-equal types are deferred in the sort.
+func AscIfType(p1Ptr, p2Ptr *IfAddr) int {
+ return AscType(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
+}
+
+// DescIfAddress is identical to AscIfAddress but reverse ordered.
+func DescIfAddress(p1Ptr, p2Ptr *IfAddr) int {
+ return -1 * AscAddress(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
+}
+
+// DescIfName is identical to AscIfName but reverse ordered.
+func DescIfName(p1Ptr, p2Ptr *IfAddr) int {
+ return -1 * strings.Compare(p1Ptr.Name, p2Ptr.Name)
+}
+
+// DescIfNetworkSize is identical to AscIfNetworkSize but reverse ordered.
+func DescIfNetworkSize(p1Ptr, p2Ptr *IfAddr) int {
+ return -1 * AscNetworkSize(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
+}
+
+// DescIfPort is identical to AscIfPort but reverse ordered.
+func DescIfPort(p1Ptr, p2Ptr *IfAddr) int {
+ return -1 * AscPort(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
+}
+
+// DescIfPrivate is identical to AscIfPrivate but reverse ordered.
+func DescIfPrivate(p1Ptr, p2Ptr *IfAddr) int {
+ return -1 * AscPrivate(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
+}
+
+// DescIfType is identical to AscIfType but reverse ordered.
+func DescIfType(p1Ptr, p2Ptr *IfAddr) int {
+ return -1 * AscType(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
+}
+
+// FilterIfByType filters IfAddrs and returns a list of the matching type
+func FilterIfByType(ifAddrs IfAddrs, type_ SockAddrType) (matchedIfs, excludedIfs IfAddrs) {
+ excludedIfs = make(IfAddrs, 0, len(ifAddrs))
+ matchedIfs = make(IfAddrs, 0, len(ifAddrs))
+
+ for _, ifAddr := range ifAddrs {
+ if ifAddr.SockAddr.Type()&type_ != 0 {
+ matchedIfs = append(matchedIfs, ifAddr)
+ } else {
+ excludedIfs = append(excludedIfs, ifAddr)
+ }
+ }
+ return matchedIfs, excludedIfs
+}
+
+// IfAttr forwards the selector to IfAttr.Attr() for resolution. If there is
+// more than one IfAddr, only the first IfAddr is used.
+func IfAttr(selectorName string, ifAddrs IfAddrs) (string, error) {
+ if len(ifAddrs) == 0 {
+ return "", nil
+ }
+
+ attrName := AttrName(strings.ToLower(selectorName))
+ attrVal, err := ifAddrs[0].Attr(attrName)
+ return attrVal, err
+}
+
+// GetAllInterfaces iterates over all available network interfaces and finds all
+// available IP addresses on each interface and converts them to
+// sockaddr.IPAddrs, and returning the result as an array of IfAddr.
+func GetAllInterfaces() (IfAddrs, error) {
+ ifs, err := net.Interfaces()
+ if err != nil {
+ return nil, err
+ }
+
+ ifAddrs := make(IfAddrs, 0, len(ifs))
+ for _, intf := range ifs {
+ addrs, err := intf.Addrs()
+ if err != nil {
+ return nil, err
+ }
+
+ for _, addr := range addrs {
+ var ipAddr IPAddr
+ ipAddr, err = NewIPAddr(addr.String())
+ if err != nil {
+ return IfAddrs{}, fmt.Errorf("unable to create an IP address from %q", addr.String())
+ }
+
+ ifAddr := IfAddr{
+ SockAddr: ipAddr,
+ Interface: intf,
+ }
+ ifAddrs = append(ifAddrs, ifAddr)
+ }
+ }
+
+ return ifAddrs, nil
+}
+
+// GetDefaultInterfaces returns IfAddrs of the addresses attached to the default
+// route.
+func GetDefaultInterfaces() (IfAddrs, error) {
+ ri, err := NewRouteInfo()
+ if err != nil {
+ return nil, err
+ }
+
+ defaultIfName, err := ri.GetDefaultInterfaceName()
+ if err != nil {
+ return nil, err
+ }
+
+ var defaultIfs, ifAddrs IfAddrs
+ ifAddrs, err = GetAllInterfaces()
+ for _, ifAddr := range ifAddrs {
+ if ifAddr.Name == defaultIfName {
+ defaultIfs = append(defaultIfs, ifAddr)
+ }
+ }
+
+ return defaultIfs, nil
+}
+
+// GetPrivateInterfaces returns an IfAddrs that are part of RFC 6890 and have a
+// default route. If the system can't determine its IP address or find an RFC
+// 6890 IP address, an empty IfAddrs will be returned instead. This function is
+// the `eval` equivalent of:
+//
+// ```
+// $ sockaddr eval -r '{{GetDefaultInterfaces | include "type" "ip" | include "flags" "forwardable|up" | sort "type,size" | include "RFC" "6890" }}'
+/// ```
+func GetPrivateInterfaces() (IfAddrs, error) {
+ privateIfs, err := GetDefaultInterfaces()
+ if err != nil {
+ return IfAddrs{}, err
+ }
+ if len(privateIfs) == 0 {
+ return IfAddrs{}, nil
+ }
+
+ privateIfs, _ = FilterIfByType(privateIfs, TypeIP)
+ if len(privateIfs) == 0 {
+ return IfAddrs{}, nil
+ }
+
+ privateIfs, _, err = IfByFlag("forwardable|up", privateIfs)
+ if err != nil {
+ return IfAddrs{}, err
+ }
+ if len(privateIfs) == 0 {
+ return IfAddrs{}, nil
+ }
+
+ OrderedIfAddrBy(AscIfType, AscIfNetworkSize).Sort(privateIfs)
+
+ privateIfs, _, err = IfByRFC("6890", privateIfs)
+ if err != nil {
+ return IfAddrs{}, err
+ } else if len(privateIfs) == 0 {
+ return IfAddrs{}, nil
+ }
+
+ return privateIfs, nil
+}
+
+// GetPublicInterfaces returns an IfAddrs that are NOT part of RFC 6890 and has a
+// default route. If the system can't determine its IP address or find a non
+// RFC 6890 IP address, an empty IfAddrs will be returned instead. This
+// function is the `eval` equivalent of:
+//
+// ```
+// $ sockaddr eval -r '{{GetDefaultInterfaces | include "type" "ip" | include "flags" "forwardable|up" | sort "type,size" | exclude "RFC" "6890" }}'
+/// ```
+func GetPublicInterfaces() (IfAddrs, error) {
+ publicIfs, err := GetDefaultInterfaces()
+ if err != nil {
+ return IfAddrs{}, err
+ }
+ if len(publicIfs) == 0 {
+ return IfAddrs{}, nil
+ }
+
+ publicIfs, _ = FilterIfByType(publicIfs, TypeIP)
+ if len(publicIfs) == 0 {
+ return IfAddrs{}, nil
+ }
+
+ publicIfs, _, err = IfByFlag("forwardable|up", publicIfs)
+ if err != nil {
+ return IfAddrs{}, err
+ }
+ if len(publicIfs) == 0 {
+ return IfAddrs{}, nil
+ }
+
+ OrderedIfAddrBy(AscIfType, AscIfNetworkSize).Sort(publicIfs)
+
+ _, publicIfs, err = IfByRFC("6890", publicIfs)
+ if err != nil {
+ return IfAddrs{}, err
+ } else if len(publicIfs) == 0 {
+ return IfAddrs{}, nil
+ }
+
+ return publicIfs, nil
+}
+
+// IfByAddress returns a list of matched and non-matched IfAddrs, or an error if
+// the regexp fails to compile.
+func IfByAddress(inputRe string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) {
+ re, err := regexp.Compile(inputRe)
+ if err != nil {
+ return nil, nil, fmt.Errorf("Unable to compile address regexp %+q: %v", inputRe, err)
+ }
+
+ matchedAddrs := make(IfAddrs, 0, len(ifAddrs))
+ excludedAddrs := make(IfAddrs, 0, len(ifAddrs))
+ for _, addr := range ifAddrs {
+ if re.MatchString(addr.SockAddr.String()) {
+ matchedAddrs = append(matchedAddrs, addr)
+ } else {
+ excludedAddrs = append(excludedAddrs, addr)
+ }
+ }
+
+ return matchedAddrs, excludedAddrs, nil
+}
+
+// IfByName returns a list of matched and non-matched IfAddrs, or an error if
+// the regexp fails to compile.
+func IfByName(inputRe string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) {
+ re, err := regexp.Compile(inputRe)
+ if err != nil {
+ return nil, nil, fmt.Errorf("Unable to compile name regexp %+q: %v", inputRe, err)
+ }
+
+ matchedAddrs := make(IfAddrs, 0, len(ifAddrs))
+ excludedAddrs := make(IfAddrs, 0, len(ifAddrs))
+ for _, addr := range ifAddrs {
+ if re.MatchString(addr.Name) {
+ matchedAddrs = append(matchedAddrs, addr)
+ } else {
+ excludedAddrs = append(excludedAddrs, addr)
+ }
+ }
+
+ return matchedAddrs, excludedAddrs, nil
+}
+
+// IfByPort returns a list of matched and non-matched IfAddrs, or an error if
+// the regexp fails to compile.
+func IfByPort(inputRe string, ifAddrs IfAddrs) (matchedIfs, excludedIfs IfAddrs, err error) {
+ re, err := regexp.Compile(inputRe)
+ if err != nil {
+ return nil, nil, fmt.Errorf("Unable to compile port regexp %+q: %v", inputRe, err)
+ }
+
+ ipIfs, nonIfs := FilterIfByType(ifAddrs, TypeIP)
+ matchedIfs = make(IfAddrs, 0, len(ipIfs))
+ excludedIfs = append(IfAddrs(nil), nonIfs...)
+ for _, addr := range ipIfs {
+ ipAddr := ToIPAddr(addr.SockAddr)
+ if ipAddr == nil {
+ continue
+ }
+
+ port := strconv.FormatInt(int64((*ipAddr).IPPort()), 10)
+ if re.MatchString(port) {
+ matchedIfs = append(matchedIfs, addr)
+ } else {
+ excludedIfs = append(excludedIfs, addr)
+ }
+ }
+
+ return matchedIfs, excludedIfs, nil
+}
+
+// IfByRFC returns a list of matched and non-matched IfAddrs that contain the
+// relevant RFC-specified traits.
+func IfByRFC(selectorParam string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) {
+ inputRFC, err := strconv.ParseUint(selectorParam, 10, 64)
+ if err != nil {
+ return IfAddrs{}, IfAddrs{}, fmt.Errorf("unable to parse RFC number %q: %v", selectorParam, err)
+ }
+
+ matchedIfAddrs := make(IfAddrs, 0, len(ifAddrs))
+ remainingIfAddrs := make(IfAddrs, 0, len(ifAddrs))
+
+ rfcNetMap := KnownRFCs()
+ rfcNets, ok := rfcNetMap[uint(inputRFC)]
+ if !ok {
+ return nil, nil, fmt.Errorf("unsupported RFC %d", inputRFC)
+ }
+
+ for _, ifAddr := range ifAddrs {
+ var contained bool
+ for _, rfcNet := range rfcNets {
+ if rfcNet.Contains(ifAddr.SockAddr) {
+ matchedIfAddrs = append(matchedIfAddrs, ifAddr)
+ contained = true
+ break
+ }
+ }
+ if !contained {
+ remainingIfAddrs = append(remainingIfAddrs, ifAddr)
+ }
+ }
+
+ return matchedIfAddrs, remainingIfAddrs, nil
+}
+
+// IfByRFCs returns a list of matched and non-matched IfAddrs that contain the
+// relevant RFC-specified traits. Multiple RFCs can be specified and separated
+// by the `|` symbol. No protection is taken to ensure an IfAddr does not end
+// up in both the included and excluded list.
+func IfByRFCs(selectorParam string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) {
+ var includedIfs, excludedIfs IfAddrs
+ for _, rfcStr := range strings.Split(selectorParam, "|") {
+ includedRFCIfs, excludedRFCIfs, err := IfByRFC(rfcStr, ifAddrs)
+ if err != nil {
+ return IfAddrs{}, IfAddrs{}, fmt.Errorf("unable to lookup RFC number %q: %v", rfcStr, err)
+ }
+ includedIfs = append(includedIfs, includedRFCIfs...)
+ excludedIfs = append(excludedIfs, excludedRFCIfs...)
+ }
+
+ return includedIfs, excludedIfs, nil
+}
+
+// IfByMaskSize returns a list of matched and non-matched IfAddrs that have the
+// matching mask size.
+func IfByMaskSize(selectorParam string, ifAddrs IfAddrs) (matchedIfs, excludedIfs IfAddrs, err error) {
+ maskSize, err := strconv.ParseUint(selectorParam, 10, 64)
+ if err != nil {
+ return IfAddrs{}, IfAddrs{}, fmt.Errorf("invalid exclude size argument (%q): %v", selectorParam, err)
+ }
+
+ ipIfs, nonIfs := FilterIfByType(ifAddrs, TypeIP)
+ matchedIfs = make(IfAddrs, 0, len(ipIfs))
+ excludedIfs = append(IfAddrs(nil), nonIfs...)
+ for _, addr := range ipIfs {
+ ipAddr := ToIPAddr(addr.SockAddr)
+ if ipAddr == nil {
+ return IfAddrs{}, IfAddrs{}, fmt.Errorf("unable to filter mask sizes on non-IP type %s: %v", addr.SockAddr.Type().String(), addr.SockAddr.String())
+ }
+
+ switch {
+ case (*ipAddr).Type()&TypeIPv4 != 0 && maskSize > 32:
+ return IfAddrs{}, IfAddrs{}, fmt.Errorf("mask size out of bounds for IPv4 address: %d", maskSize)
+ case (*ipAddr).Type()&TypeIPv6 != 0 && maskSize > 128:
+ return IfAddrs{}, IfAddrs{}, fmt.Errorf("mask size out of bounds for IPv6 address: %d", maskSize)
+ }
+
+ if (*ipAddr).Maskbits() == int(maskSize) {
+ matchedIfs = append(matchedIfs, addr)
+ } else {
+ excludedIfs = append(excludedIfs, addr)
+ }
+ }
+
+ return matchedIfs, excludedIfs, nil
+}
+
+// IfByType returns a list of matching and non-matching IfAddr that match the
+// specified type. For instance:
+//
+// include "type" "IPv4,IPv6"
+//
+// will include any IfAddrs that is either an IPv4 or IPv6 address. Any
+// addresses on those interfaces that don't match will be included in the
+// remainder results.
+func IfByType(inputTypes string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) {
+ matchingIfAddrs := make(IfAddrs, 0, len(ifAddrs))
+ remainingIfAddrs := make(IfAddrs, 0, len(ifAddrs))
+
+ ifTypes := strings.Split(strings.ToLower(inputTypes), "|")
+ for _, ifType := range ifTypes {
+ switch ifType {
+ case "ip", "ipv4", "ipv6", "unix":
+ // Valid types
+ default:
+ return nil, nil, fmt.Errorf("unsupported type %q %q", ifType, inputTypes)
+ }
+ }
+
+ for _, ifAddr := range ifAddrs {
+ for _, ifType := range ifTypes {
+ var matched bool
+ switch {
+ case ifType == "ip" && ifAddr.SockAddr.Type()&TypeIP != 0:
+ matched = true
+ case ifType == "ipv4" && ifAddr.SockAddr.Type()&TypeIPv4 != 0:
+ matched = true
+ case ifType == "ipv6" && ifAddr.SockAddr.Type()&TypeIPv6 != 0:
+ matched = true
+ case ifType == "unix" && ifAddr.SockAddr.Type()&TypeUnix != 0:
+ matched = true
+ }
+
+ if matched {
+ matchingIfAddrs = append(matchingIfAddrs, ifAddr)
+ } else {
+ remainingIfAddrs = append(remainingIfAddrs, ifAddr)
+ }
+ }
+ }
+
+ return matchingIfAddrs, remainingIfAddrs, nil
+}
+
+// IfByFlag returns a list of matching and non-matching IfAddrs that match the
+// specified type. For instance:
+//
+// include "flag" "up,broadcast"
+//
+// will include any IfAddrs that have both the "up" and "broadcast" flags set.
+// Any addresses on those interfaces that don't match will be omitted from the
+// results.
+func IfByFlag(inputFlags string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error) {
+ matchedAddrs := make(IfAddrs, 0, len(ifAddrs))
+ excludedAddrs := make(IfAddrs, 0, len(ifAddrs))
+
+ var wantForwardable,
+ wantGlobalUnicast,
+ wantInterfaceLocalMulticast,
+ wantLinkLocalMulticast,
+ wantLinkLocalUnicast,
+ wantLoopback,
+ wantMulticast,
+ wantUnspecified bool
+ var ifFlags net.Flags
+ var checkFlags, checkAttrs bool
+ for _, flagName := range strings.Split(strings.ToLower(inputFlags), "|") {
+ switch flagName {
+ case "broadcast":
+ checkFlags = true
+ ifFlags = ifFlags | net.FlagBroadcast
+ case "down":
+ checkFlags = true
+ ifFlags = (ifFlags &^ net.FlagUp)
+ case "forwardable":
+ checkAttrs = true
+ wantForwardable = true
+ case "global unicast":
+ checkAttrs = true
+ wantGlobalUnicast = true
+ case "interface-local multicast":
+ checkAttrs = true
+ wantInterfaceLocalMulticast = true
+ case "link-local multicast":
+ checkAttrs = true
+ wantLinkLocalMulticast = true
+ case "link-local unicast":
+ checkAttrs = true
+ wantLinkLocalUnicast = true
+ case "loopback":
+ checkAttrs = true
+ checkFlags = true
+ ifFlags = ifFlags | net.FlagLoopback
+ wantLoopback = true
+ case "multicast":
+ checkAttrs = true
+ checkFlags = true
+ ifFlags = ifFlags | net.FlagMulticast
+ wantMulticast = true
+ case "point-to-point":
+ checkFlags = true
+ ifFlags = ifFlags | net.FlagPointToPoint
+ case "unspecified":
+ checkAttrs = true
+ wantUnspecified = true
+ case "up":
+ checkFlags = true
+ ifFlags = ifFlags | net.FlagUp
+ default:
+ return nil, nil, fmt.Errorf("Unknown interface flag: %+q", flagName)
+ }
+ }
+
+ for _, ifAddr := range ifAddrs {
+ var matched bool
+ if checkFlags && ifAddr.Interface.Flags&ifFlags == ifFlags {
+ matched = true
+ }
+ if checkAttrs {
+ if ip := ToIPAddr(ifAddr.SockAddr); ip != nil {
+ netIP := (*ip).NetIP()
+ switch {
+ case wantGlobalUnicast && netIP.IsGlobalUnicast():
+ matched = true
+ case wantInterfaceLocalMulticast && netIP.IsInterfaceLocalMulticast():
+ matched = true
+ case wantLinkLocalMulticast && netIP.IsLinkLocalMulticast():
+ matched = true
+ case wantLinkLocalUnicast && netIP.IsLinkLocalUnicast():
+ matched = true
+ case wantLoopback && netIP.IsLoopback():
+ matched = true
+ case wantMulticast && netIP.IsMulticast():
+ matched = true
+ case wantUnspecified && netIP.IsUnspecified():
+ matched = true
+ case wantForwardable && !IsRFC(ForwardingBlacklist, ifAddr.SockAddr):
+ matched = true
+ }
+ }
+ }
+ if matched {
+ matchedAddrs = append(matchedAddrs, ifAddr)
+ } else {
+ excludedAddrs = append(excludedAddrs, ifAddr)
+ }
+ }
+ return matchedAddrs, excludedAddrs, nil
+}
+
+// IfByNetwork returns an IfAddrs that are equal to or included within the
+// network passed in by selector.
+func IfByNetwork(selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, IfAddrs, error) {
+ var includedIfs, excludedIfs IfAddrs
+ for _, netStr := range strings.Split(selectorParam, "|") {
+ netAddr, err := NewIPAddr(netStr)
+ if err != nil {
+ return nil, nil, fmt.Errorf("unable to create an IP address from %+q: %v", netStr, err)
+ }
+
+ for _, ifAddr := range inputIfAddrs {
+ if netAddr.Contains(ifAddr.SockAddr) {
+ includedIfs = append(includedIfs, ifAddr)
+ } else {
+ excludedIfs = append(excludedIfs, ifAddr)
+ }
+ }
+ }
+
+ return includedIfs, excludedIfs, nil
+}
+
+// IncludeIfs returns an IfAddrs based on the passed in selector.
+func IncludeIfs(selectorName, selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error) {
+ var includedIfs IfAddrs
+ var err error
+
+ switch strings.ToLower(selectorName) {
+ case "address":
+ includedIfs, _, err = IfByAddress(selectorParam, inputIfAddrs)
+ case "flag", "flags":
+ includedIfs, _, err = IfByFlag(selectorParam, inputIfAddrs)
+ case "name":
+ includedIfs, _, err = IfByName(selectorParam, inputIfAddrs)
+ case "network":
+ includedIfs, _, err = IfByNetwork(selectorParam, inputIfAddrs)
+ case "port":
+ includedIfs, _, err = IfByPort(selectorParam, inputIfAddrs)
+ case "rfc", "rfcs":
+ includedIfs, _, err = IfByRFCs(selectorParam, inputIfAddrs)
+ case "size":
+ includedIfs, _, err = IfByMaskSize(selectorParam, inputIfAddrs)
+ case "type":
+ includedIfs, _, err = IfByType(selectorParam, inputIfAddrs)
+ default:
+ return IfAddrs{}, fmt.Errorf("invalid include selector %q", selectorName)
+ }
+
+ if err != nil {
+ return IfAddrs{}, err
+ }
+
+ return includedIfs, nil
+}
+
+// ExcludeIfs returns an IfAddrs based on the passed in selector.
+func ExcludeIfs(selectorName, selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error) {
+ var excludedIfs IfAddrs
+ var err error
+
+ switch strings.ToLower(selectorName) {
+ case "address":
+ _, excludedIfs, err = IfByAddress(selectorParam, inputIfAddrs)
+ case "flag", "flags":
+ _, excludedIfs, err = IfByFlag(selectorParam, inputIfAddrs)
+ case "name":
+ _, excludedIfs, err = IfByName(selectorParam, inputIfAddrs)
+ case "network":
+ _, excludedIfs, err = IfByNetwork(selectorParam, inputIfAddrs)
+ case "port":
+ _, excludedIfs, err = IfByPort(selectorParam, inputIfAddrs)
+ case "rfc", "rfcs":
+ _, excludedIfs, err = IfByRFCs(selectorParam, inputIfAddrs)
+ case "size":
+ _, excludedIfs, err = IfByMaskSize(selectorParam, inputIfAddrs)
+ case "type":
+ _, excludedIfs, err = IfByType(selectorParam, inputIfAddrs)
+ default:
+ return IfAddrs{}, fmt.Errorf("invalid exclude selector %q", selectorName)
+ }
+
+ if err != nil {
+ return IfAddrs{}, err
+ }
+
+ return excludedIfs, nil
+}
+
+// SortIfBy returns an IfAddrs sorted based on the passed in selector. Multiple
+// sort clauses can be passed in as a comma delimited list without whitespace.
+func SortIfBy(selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error) {
+ sortedIfs := append(IfAddrs(nil), inputIfAddrs...)
+
+ clauses := strings.Split(selectorParam, ",")
+ sortFuncs := make([]CmpIfAddrFunc, len(clauses))
+
+ for i, clause := range clauses {
+ switch strings.TrimSpace(strings.ToLower(clause)) {
+ case "+address", "address":
+ // The "address" selector returns an array of IfAddrs
+ // ordered by the network address. IfAddrs that are not
+ // comparable will be at the end of the list and in a
+ // non-deterministic order.
+ sortFuncs[i] = AscIfAddress
+ case "-address":
+ sortFuncs[i] = DescIfAddress
+ case "+name", "name":
+ // The "name" selector returns an array of IfAddrs
+ // ordered by the interface name.
+ sortFuncs[i] = AscIfName
+ case "-name":
+ sortFuncs[i] = DescIfName
+ case "+port", "port":
+ // The "port" selector returns an array of IfAddrs
+ // ordered by the port, if included in the IfAddr.
+ // IfAddrs that are not comparable will be at the end of
+ // the list and in a non-deterministic order.
+ sortFuncs[i] = AscIfPort
+ case "-port":
+ sortFuncs[i] = DescIfPort
+ case "+private", "private":
+ // The "private" selector returns an array of IfAddrs
+ // ordered by private addresses first. IfAddrs that are
+ // not comparable will be at the end of the list and in
+ // a non-deterministic order.
+ sortFuncs[i] = AscIfPrivate
+ case "-private":
+ sortFuncs[i] = DescIfPrivate
+ case "+size", "size":
+ // The "size" selector returns an array of IfAddrs
+ // ordered by the size of the network mask, smaller mask
+ // (larger number of hosts per network) to largest
+ // (e.g. a /24 sorts before a /32).
+ sortFuncs[i] = AscIfNetworkSize
+ case "-size":
+ sortFuncs[i] = DescIfNetworkSize
+ case "+type", "type":
+ // The "type" selector returns an array of IfAddrs
+ // ordered by the type of the IfAddr. The sort order is
+ // Unix, IPv4, then IPv6.
+ sortFuncs[i] = AscIfType
+ case "-type":
+ sortFuncs[i] = DescIfType
+ default:
+ // Return an empty list for invalid sort types.
+ return IfAddrs{}, fmt.Errorf("unknown sort type: %q", clause)
+ }
+ }
+
+ OrderedIfAddrBy(sortFuncs...).Sort(sortedIfs)
+
+ return sortedIfs, nil
+}
+
+// UniqueIfAddrsBy creates a unique set of IfAddrs based on the matching
+// selector. UniqueIfAddrsBy assumes the input has already been sorted.
+func UniqueIfAddrsBy(selectorName string, inputIfAddrs IfAddrs) (IfAddrs, error) {
+ attrName := strings.ToLower(selectorName)
+
+ ifs := make(IfAddrs, 0, len(inputIfAddrs))
+ var lastMatch string
+ for _, ifAddr := range inputIfAddrs {
+ var out string
+ switch attrName {
+ case "address":
+ out = ifAddr.SockAddr.String()
+ case "name":
+ out = ifAddr.Name
+ default:
+ return nil, fmt.Errorf("unsupported unique constraint %+q", selectorName)
+ }
+
+ switch {
+ case lastMatch == "", lastMatch != out:
+ lastMatch = out
+ ifs = append(ifs, ifAddr)
+ case lastMatch == out:
+ continue
+ }
+ }
+
+ return ifs, nil
+}
+
+// JoinIfAddrs joins an IfAddrs and returns a string
+func JoinIfAddrs(selectorName string, joinStr string, inputIfAddrs IfAddrs) (string, error) {
+ outputs := make([]string, 0, len(inputIfAddrs))
+ attrName := AttrName(strings.ToLower(selectorName))
+
+ for _, ifAddr := range inputIfAddrs {
+ var attrVal string
+ var err error
+ attrVal, err = ifAddr.Attr(attrName)
+ if err != nil {
+ return "", err
+ }
+ outputs = append(outputs, attrVal)
+ }
+ return strings.Join(outputs, joinStr), nil
+}
+
+// LimitIfAddrs returns a slice of IfAddrs based on the specified limit.
+func LimitIfAddrs(lim uint, in IfAddrs) (IfAddrs, error) {
+ // Clamp the limit to the length of the array
+ if int(lim) > len(in) {
+ lim = uint(len(in))
+ }
+
+ return in[0:lim], nil
+}
+
+// OffsetIfAddrs returns a slice of IfAddrs based on the specified offset.
+func OffsetIfAddrs(off int, in IfAddrs) (IfAddrs, error) {
+ var end bool
+ if off < 0 {
+ end = true
+ off = off * -1
+ }
+
+ if off > len(in) {
+ return IfAddrs{}, fmt.Errorf("unable to seek past the end of the interface array: offset (%d) exceeds the number of interfaces (%d)", off, len(in))
+ }
+
+ if end {
+ return in[len(in)-off:], nil
+ }
+ return in[off:], nil
+}
+
+func (ifAddr IfAddr) String() string {
+ return fmt.Sprintf("%s %v", ifAddr.SockAddr, ifAddr.Interface)
+}
+
+// parseDefaultIfNameFromRoute parses standard route(8)'s output for the *BSDs
+// and Solaris.
+func parseDefaultIfNameFromRoute(routeOut string) (string, error) {
+ lines := strings.Split(routeOut, "\n")
+ for _, line := range lines {
+ kvs := strings.SplitN(line, ":", 2)
+ if len(kvs) != 2 {
+ continue
+ }
+
+ if strings.TrimSpace(kvs[0]) == "interface" {
+ ifName := strings.TrimSpace(kvs[1])
+ return ifName, nil
+ }
+ }
+
+ return "", errors.New("No default interface found")
+}
+
+// parseDefaultIfNameFromIPCmd parses the default interface from ip(8) for
+// Linux.
+func parseDefaultIfNameFromIPCmd(routeOut string) (string, error) {
+ lines := strings.Split(routeOut, "\n")
+ re := regexp.MustCompile(`[\s]+`)
+ for _, line := range lines {
+ kvs := re.Split(line, -1)
+ if len(kvs) < 5 {
+ continue
+ }
+
+ if kvs[0] == "default" &&
+ kvs[1] == "via" &&
+ kvs[3] == "dev" {
+ ifName := strings.TrimSpace(kvs[4])
+ return ifName, nil
+ }
+ }
+
+ return "", errors.New("No default interface found")
+}
+
+// parseDefaultIfNameWindows parses the default interface from `netstat -rn` and
+// `ipconfig` on Windows.
+func parseDefaultIfNameWindows(routeOut, ipconfigOut string) (string, error) {
+ defaultIPAddr, err := parseDefaultIPAddrWindowsRoute(routeOut)
+ if err != nil {
+ return "", err
+ }
+
+ ifName, err := parseDefaultIfNameWindowsIPConfig(defaultIPAddr, ipconfigOut)
+ if err != nil {
+ return "", err
+ }
+
+ return ifName, nil
+}
+
+// parseDefaultIPAddrWindowsRoute parses the IP address on the default interface
+// `netstat -rn`.
+//
+// NOTES(sean): Only IPv4 addresses are parsed at this time. If you have an
+// IPv6 connected host, submit an issue on github.com/hashicorp/go-sockaddr with
+// the output from `netstat -rn`, `ipconfig`, and version of Windows to see IPv6
+// support added.
+func parseDefaultIPAddrWindowsRoute(routeOut string) (string, error) {
+ lines := strings.Split(routeOut, "\n")
+ re := regexp.MustCompile(`[\s]+`)
+ for _, line := range lines {
+ kvs := re.Split(strings.TrimSpace(line), -1)
+ if len(kvs) < 3 {
+ continue
+ }
+
+ if kvs[0] == "0.0.0.0" && kvs[1] == "0.0.0.0" {
+ defaultIPAddr := strings.TrimSpace(kvs[3])
+ return defaultIPAddr, nil
+ }
+ }
+
+ return "", errors.New("No IP on default interface found")
+}
+
+// parseDefaultIfNameWindowsIPConfig parses the output of `ipconfig` to find the
+// interface name forwarding traffic to the default gateway.
+func parseDefaultIfNameWindowsIPConfig(defaultIPAddr, routeOut string) (string, error) {
+ lines := strings.Split(routeOut, "\n")
+ ifNameRE := regexp.MustCompile(`^Ethernet adapter ([^\s:]+):`)
+ ipAddrRE := regexp.MustCompile(`^ IPv[46] Address\. \. \. \. \. \. \. \. \. \. \. : ([^\s]+)`)
+ var ifName string
+ for _, line := range lines {
+ switch ifNameMatches := ifNameRE.FindStringSubmatch(line); {
+ case len(ifNameMatches) > 1:
+ ifName = ifNameMatches[1]
+ continue
+ }
+
+ switch ipAddrMatches := ipAddrRE.FindStringSubmatch(line); {
+ case len(ipAddrMatches) > 1 && ipAddrMatches[1] == defaultIPAddr:
+ return ifName, nil
+ }
+ }
+
+ return "", errors.New("No default interface found with matching IP")
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ifattr.go b/vendor/github.com/hashicorp/go-sockaddr/ifattr.go
new file mode 100644
index 0000000..6984cb4
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/ifattr.go
@@ -0,0 +1,65 @@
+package sockaddr
+
+import (
+ "fmt"
+ "net"
+)
+
+// IfAddr is a union of a SockAddr and a net.Interface.
+type IfAddr struct {
+ SockAddr
+ net.Interface
+}
+
+// Attr returns the named attribute as a string
+func (ifAddr IfAddr) Attr(attrName AttrName) (string, error) {
+ val := IfAddrAttr(ifAddr, attrName)
+ if val != "" {
+ return val, nil
+ }
+
+ return Attr(ifAddr.SockAddr, attrName)
+}
+
+// Attr returns the named attribute as a string
+func Attr(sa SockAddr, attrName AttrName) (string, error) {
+ switch sockType := sa.Type(); {
+ case sockType&TypeIP != 0:
+ ip := *ToIPAddr(sa)
+ attrVal := IPAddrAttr(ip, attrName)
+ if attrVal != "" {
+ return attrVal, nil
+ }
+
+ if sockType == TypeIPv4 {
+ ipv4 := *ToIPv4Addr(sa)
+ attrVal := IPv4AddrAttr(ipv4, attrName)
+ if attrVal != "" {
+ return attrVal, nil
+ }
+ } else if sockType == TypeIPv6 {
+ ipv6 := *ToIPv6Addr(sa)
+ attrVal := IPv6AddrAttr(ipv6, attrName)
+ if attrVal != "" {
+ return attrVal, nil
+ }
+ }
+
+ case sockType == TypeUnix:
+ us := *ToUnixSock(sa)
+ attrVal := UnixSockAttr(us, attrName)
+ if attrVal != "" {
+ return attrVal, nil
+ }
+ }
+
+ // Non type-specific attributes
+ switch attrName {
+ case "string":
+ return sa.String(), nil
+ case "type":
+ return sa.Type().String(), nil
+ }
+
+ return "", fmt.Errorf("unsupported attribute name %q", attrName)
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipaddr.go b/vendor/github.com/hashicorp/go-sockaddr/ipaddr.go
new file mode 100644
index 0000000..b47d15c
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/ipaddr.go
@@ -0,0 +1,169 @@
+package sockaddr
+
+import (
+ "fmt"
+ "math/big"
+ "net"
+ "strings"
+)
+
+// Constants for the sizes of IPv3, IPv4, and IPv6 address types.
+const (
+ IPv3len = 6
+ IPv4len = 4
+ IPv6len = 16
+)
+
+// IPAddr is a generic IP address interface for IPv4 and IPv6 addresses,
+// networks, and socket endpoints.
+type IPAddr interface {
+ SockAddr
+ AddressBinString() string
+ AddressHexString() string
+ Cmp(SockAddr) int
+ CmpAddress(SockAddr) int
+ CmpPort(SockAddr) int
+ FirstUsable() IPAddr
+ Host() IPAddr
+ IPPort() IPPort
+ LastUsable() IPAddr
+ Maskbits() int
+ NetIP() *net.IP
+ NetIPMask() *net.IPMask
+ NetIPNet() *net.IPNet
+ Network() IPAddr
+ Octets() []int
+}
+
+// IPPort is the type for an IP port number for the TCP and UDP IP transports.
+type IPPort uint16
+
+// IPPrefixLen is a typed integer representing the prefix length for a given
+// IPAddr.
+type IPPrefixLen byte
+
+// ipAddrAttrMap is a map of the IPAddr type-specific attributes.
+var ipAddrAttrMap map[AttrName]func(IPAddr) string
+var ipAddrAttrs []AttrName
+
+func init() {
+ ipAddrInit()
+}
+
+// NewIPAddr creates a new IPAddr from a string. Returns nil if the string is
+// not an IPv4 or an IPv6 address.
+func NewIPAddr(addr string) (IPAddr, error) {
+ ipv4Addr, err := NewIPv4Addr(addr)
+ if err == nil {
+ return ipv4Addr, nil
+ }
+
+ ipv6Addr, err := NewIPv6Addr(addr)
+ if err == nil {
+ return ipv6Addr, nil
+ }
+
+ return nil, fmt.Errorf("invalid IPAddr %v", addr)
+}
+
+// IPAddrAttr returns a string representation of an attribute for the given
+// IPAddr.
+func IPAddrAttr(ip IPAddr, selector AttrName) string {
+ fn, found := ipAddrAttrMap[selector]
+ if !found {
+ return ""
+ }
+
+ return fn(ip)
+}
+
+// IPAttrs returns a list of attributes supported by the IPAddr type
+func IPAttrs() []AttrName {
+ return ipAddrAttrs
+}
+
+// MustIPAddr is a helper method that must return an IPAddr or panic on invalid
+// input.
+func MustIPAddr(addr string) IPAddr {
+ ip, err := NewIPAddr(addr)
+ if err != nil {
+ panic(fmt.Sprintf("Unable to create an IPAddr from %+q: %v", addr, err))
+ }
+ return ip
+}
+
+// ipAddrInit is called once at init()
+func ipAddrInit() {
+ // Sorted for human readability
+ ipAddrAttrs = []AttrName{
+ "host",
+ "address",
+ "port",
+ "netmask",
+ "network",
+ "mask_bits",
+ "binary",
+ "hex",
+ "first_usable",
+ "last_usable",
+ "octets",
+ }
+
+ ipAddrAttrMap = map[AttrName]func(ip IPAddr) string{
+ "address": func(ip IPAddr) string {
+ return ip.NetIP().String()
+ },
+ "binary": func(ip IPAddr) string {
+ return ip.AddressBinString()
+ },
+ "first_usable": func(ip IPAddr) string {
+ return ip.FirstUsable().String()
+ },
+ "hex": func(ip IPAddr) string {
+ return ip.AddressHexString()
+ },
+ "host": func(ip IPAddr) string {
+ return ip.Host().String()
+ },
+ "last_usable": func(ip IPAddr) string {
+ return ip.LastUsable().String()
+ },
+ "mask_bits": func(ip IPAddr) string {
+ return fmt.Sprintf("%d", ip.Maskbits())
+ },
+ "netmask": func(ip IPAddr) string {
+ switch v := ip.(type) {
+ case IPv4Addr:
+ ipv4Mask := IPv4Addr{
+ Address: IPv4Address(v.Mask),
+ Mask: IPv4HostMask,
+ }
+ return ipv4Mask.String()
+ case IPv6Addr:
+ ipv6Mask := new(big.Int)
+ ipv6Mask.Set(v.Mask)
+ ipv6MaskAddr := IPv6Addr{
+ Address: IPv6Address(ipv6Mask),
+ Mask: ipv6HostMask,
+ }
+ return ipv6MaskAddr.String()
+ default:
+ return fmt.Sprintf("<unsupported type: %T>", ip)
+ }
+ },
+ "network": func(ip IPAddr) string {
+ return ip.Network().NetIP().String()
+ },
+ "octets": func(ip IPAddr) string {
+ octets := ip.Octets()
+ octetStrs := make([]string, 0, len(octets))
+ for _, octet := range octets {
+ octetStrs = append(octetStrs, fmt.Sprintf("%d", octet))
+ }
+ return strings.Join(octetStrs, " ")
+ },
+ "port": func(ip IPAddr) string {
+ return fmt.Sprintf("%d", ip.IPPort())
+ },
+ }
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go b/vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go
new file mode 100644
index 0000000..6eeb7dd
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/ipaddrs.go
@@ -0,0 +1,98 @@
+package sockaddr
+
+import "bytes"
+
+type IPAddrs []IPAddr
+
+func (s IPAddrs) Len() int { return len(s) }
+func (s IPAddrs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+// // SortIPAddrsByCmp is a type that satisfies sort.Interface and can be used
+// // by the routines in this package. The SortIPAddrsByCmp type is used to
+// // sort IPAddrs by Cmp()
+// type SortIPAddrsByCmp struct{ IPAddrs }
+
+// // Less reports whether the element with index i should sort before the
+// // element with index j.
+// func (s SortIPAddrsByCmp) Less(i, j int) bool {
+// // Sort by Type, then address, then port number.
+// return Less(s.IPAddrs[i], s.IPAddrs[j])
+// }
+
+// SortIPAddrsBySpecificMaskLen is a type that satisfies sort.Interface and
+// can be used by the routines in this package. The
+// SortIPAddrsBySpecificMaskLen type is used to sort IPAddrs by smallest
+// network (most specific to largest network).
+type SortIPAddrsByNetworkSize struct{ IPAddrs }
+
+// Less reports whether the element with index i should sort before the
+// element with index j.
+func (s SortIPAddrsByNetworkSize) Less(i, j int) bool {
+ // Sort masks with a larger binary value (i.e. fewer hosts per network
+ // prefix) after masks with a smaller value (larger number of hosts per
+ // prefix).
+ switch bytes.Compare([]byte(*s.IPAddrs[i].NetIPMask()), []byte(*s.IPAddrs[j].NetIPMask())) {
+ case 0:
+ // Fall through to the second test if the net.IPMasks are the
+ // same.
+ break
+ case 1:
+ return true
+ case -1:
+ return false
+ default:
+ panic("bad, m'kay?")
+ }
+
+ // Sort IPs based on the length (i.e. prefer IPv4 over IPv6).
+ iLen := len(*s.IPAddrs[i].NetIP())
+ jLen := len(*s.IPAddrs[j].NetIP())
+ if iLen != jLen {
+ return iLen > jLen
+ }
+
+ // Sort IPs based on their network address from lowest to highest.
+ switch bytes.Compare(s.IPAddrs[i].NetIPNet().IP, s.IPAddrs[j].NetIPNet().IP) {
+ case 0:
+ break
+ case 1:
+ return false
+ case -1:
+ return true
+ default:
+ panic("lol wut?")
+ }
+
+ // If a host does not have a port set, it always sorts after hosts
+ // that have a port (e.g. a host with a /32 and port number is more
+ // specific and should sort first over a host with a /32 but no port
+ // set).
+ if s.IPAddrs[i].IPPort() == 0 || s.IPAddrs[j].IPPort() == 0 {
+ return false
+ }
+ return s.IPAddrs[i].IPPort() < s.IPAddrs[j].IPPort()
+}
+
+// SortIPAddrsBySpecificMaskLen is a type that satisfies sort.Interface and
+// can be used by the routines in this package. The
+// SortIPAddrsBySpecificMaskLen type is used to sort IPAddrs by smallest
+// network (most specific to largest network).
+type SortIPAddrsBySpecificMaskLen struct{ IPAddrs }
+
+// Less reports whether the element with index i should sort before the
+// element with index j.
+func (s SortIPAddrsBySpecificMaskLen) Less(i, j int) bool {
+ return s.IPAddrs[i].Maskbits() > s.IPAddrs[j].Maskbits()
+}
+
+// SortIPAddrsByBroadMaskLen is a type that satisfies sort.Interface and can
+// be used by the routines in this package. The SortIPAddrsByBroadMaskLen
+// type is used to sort IPAddrs by largest network (i.e. largest subnets
+// first).
+type SortIPAddrsByBroadMaskLen struct{ IPAddrs }
+
+// Less reports whether the element with index i should sort before the
+// element with index j.
+func (s SortIPAddrsByBroadMaskLen) Less(i, j int) bool {
+ return s.IPAddrs[i].Maskbits() < s.IPAddrs[j].Maskbits()
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go b/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go
new file mode 100644
index 0000000..9f2616a
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/ipv4addr.go
@@ -0,0 +1,515 @@
+package sockaddr
+
+import (
+ "encoding/binary"
+ "fmt"
+ "net"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+type (
+ // IPv4Address is a named type representing an IPv4 address.
+ IPv4Address uint32
+
+ // IPv4Network is a named type representing an IPv4 network.
+ IPv4Network uint32
+
+ // IPv4Mask is a named type representing an IPv4 network mask.
+ IPv4Mask uint32
+)
+
+// IPv4HostMask is a constant represents a /32 IPv4 Address
+// (i.e. 255.255.255.255).
+const IPv4HostMask = IPv4Mask(0xffffffff)
+
+// ipv4AddrAttrMap is a map of the IPv4Addr type-specific attributes.
+var ipv4AddrAttrMap map[AttrName]func(IPv4Addr) string
+var ipv4AddrAttrs []AttrName
+var trailingHexNetmaskRE *regexp.Regexp
+
+// IPv4Addr implements a convenience wrapper around the union of Go's
+// built-in net.IP and net.IPNet types. In UNIX-speak, IPv4Addr implements
+// `sockaddr` when the the address family is set to AF_INET
+// (i.e. `sockaddr_in`).
+type IPv4Addr struct {
+ IPAddr
+ Address IPv4Address
+ Mask IPv4Mask
+ Port IPPort
+}
+
+func init() {
+ ipv4AddrInit()
+ trailingHexNetmaskRE = regexp.MustCompile(`/([0f]{8})$`)
+}
+
+// NewIPv4Addr creates an IPv4Addr from a string. String can be in the form
+// of either an IPv4:port (e.g. `1.2.3.4:80`, in which case the mask is
+// assumed to be a `/32`), an IPv4 address (e.g. `1.2.3.4`, also with a `/32`
+// mask), or an IPv4 CIDR (e.g. `1.2.3.4/24`, which has its IP port
+// initialized to zero). ipv4Str can not be a hostname.
+//
+// NOTE: Many net.*() routines will initialize and return an IPv6 address.
+// To create uint32 values from net.IP, always test to make sure the address
+// returned can be converted to a 4 byte array using To4().
+func NewIPv4Addr(ipv4Str string) (IPv4Addr, error) {
+ // Strip off any bogus hex-encoded netmasks that will be mis-parsed by Go. In
+ // particular, clients with the Barracuda VPN client will see something like:
+ // `192.168.3.51/00ffffff` as their IP address.
+ if match := trailingHexNetmaskRE.FindStringIndex(ipv4Str); match != nil {
+ ipv4Str = ipv4Str[:match[0]]
+ }
+
+ // Parse as an IPv4 CIDR
+ ipAddr, network, err := net.ParseCIDR(ipv4Str)
+ if err == nil {
+ ipv4 := ipAddr.To4()
+ if ipv4 == nil {
+ return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address", ipv4Str)
+ }
+
+ // If we see an IPv6 netmask, convert it to an IPv4 mask.
+ netmaskSepPos := strings.LastIndexByte(ipv4Str, '/')
+ if netmaskSepPos != -1 && netmaskSepPos+1 < len(ipv4Str) {
+ netMask, err := strconv.ParseUint(ipv4Str[netmaskSepPos+1:], 10, 8)
+ if err != nil {
+ return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address: unable to parse CIDR netmask: %v", ipv4Str, err)
+ } else if netMask > 128 {
+ return IPv4Addr{}, fmt.Errorf("Unable to convert %s to an IPv4 address: invalid CIDR netmask", ipv4Str)
+ }
+
+ if netMask >= 96 {
+ // Convert the IPv6 netmask to an IPv4 netmask
+ network.Mask = net.CIDRMask(int(netMask-96), IPv4len*8)
+ }
+ }
+ ipv4Addr := IPv4Addr{
+ Address: IPv4Address(binary.BigEndian.Uint32(ipv4)),
+ Mask: IPv4Mask(binary.BigEndian.Uint32(network.Mask)),
+ }
+ return ipv4Addr, nil
+ }
+
+ // Attempt to parse ipv4Str as a /32 host with a port number.
+ tcpAddr, err := net.ResolveTCPAddr("tcp4", ipv4Str)
+ if err == nil {
+ ipv4 := tcpAddr.IP.To4()
+ if ipv4 == nil {
+ return IPv4Addr{}, fmt.Errorf("Unable to resolve %+q as an IPv4 address", ipv4Str)
+ }
+
+ ipv4Uint32 := binary.BigEndian.Uint32(ipv4)
+ ipv4Addr := IPv4Addr{
+ Address: IPv4Address(ipv4Uint32),
+ Mask: IPv4HostMask,
+ Port: IPPort(tcpAddr.Port),
+ }
+
+ return ipv4Addr, nil
+ }
+
+ // Parse as a naked IPv4 address
+ ip := net.ParseIP(ipv4Str)
+ if ip != nil {
+ ipv4 := ip.To4()
+ if ipv4 == nil {
+ return IPv4Addr{}, fmt.Errorf("Unable to string convert %+q to an IPv4 address", ipv4Str)
+ }
+
+ ipv4Uint32 := binary.BigEndian.Uint32(ipv4)
+ ipv4Addr := IPv4Addr{
+ Address: IPv4Address(ipv4Uint32),
+ Mask: IPv4HostMask,
+ }
+ return ipv4Addr, nil
+ }
+
+ return IPv4Addr{}, fmt.Errorf("Unable to parse %+q to an IPv4 address: %v", ipv4Str, err)
+}
+
+// AddressBinString returns a string with the IPv4Addr's Address represented
+// as a sequence of '0' and '1' characters. This method is useful for
+// debugging or by operators who want to inspect an address.
+func (ipv4 IPv4Addr) AddressBinString() string {
+ return fmt.Sprintf("%032s", strconv.FormatUint(uint64(ipv4.Address), 2))
+}
+
+// AddressHexString returns a string with the IPv4Addr address represented as
+// a sequence of hex characters. This method is useful for debugging or by
+// operators who want to inspect an address.
+func (ipv4 IPv4Addr) AddressHexString() string {
+ return fmt.Sprintf("%08s", strconv.FormatUint(uint64(ipv4.Address), 16))
+}
+
+// Broadcast is an IPv4Addr-only method that returns the broadcast address of
+// the network.
+//
+// NOTE: IPv6 only supports multicast, so this method only exists for
+// IPv4Addr.
+func (ipv4 IPv4Addr) Broadcast() IPAddr {
+ // Nothing should listen on a broadcast address.
+ return IPv4Addr{
+ Address: IPv4Address(ipv4.BroadcastAddress()),
+ Mask: IPv4HostMask,
+ }
+}
+
+// BroadcastAddress returns a IPv4Network of the IPv4Addr's broadcast
+// address.
+func (ipv4 IPv4Addr) BroadcastAddress() IPv4Network {
+ return IPv4Network(uint32(ipv4.Address)&uint32(ipv4.Mask) | ^uint32(ipv4.Mask))
+}
+
+// CmpAddress follows the Cmp() standard protocol and returns:
+//
+// - -1 If the receiver should sort first because its address is lower than arg
+// - 0 if the SockAddr arg is equal to the receiving IPv4Addr or the argument is
+// of a different type.
+// - 1 If the argument should sort first.
+func (ipv4 IPv4Addr) CmpAddress(sa SockAddr) int {
+ ipv4b, ok := sa.(IPv4Addr)
+ if !ok {
+ return sortDeferDecision
+ }
+
+ switch {
+ case ipv4.Address == ipv4b.Address:
+ return sortDeferDecision
+ case ipv4.Address < ipv4b.Address:
+ return sortReceiverBeforeArg
+ default:
+ return sortArgBeforeReceiver
+ }
+}
+
+// CmpPort follows the Cmp() standard protocol and returns:
+//
+// - -1 If the receiver should sort first because its port is lower than arg
+// - 0 if the SockAddr arg's port number is equal to the receiving IPv4Addr,
+// regardless of type.
+// - 1 If the argument should sort first.
+func (ipv4 IPv4Addr) CmpPort(sa SockAddr) int {
+ var saPort IPPort
+ switch v := sa.(type) {
+ case IPv4Addr:
+ saPort = v.Port
+ case IPv6Addr:
+ saPort = v.Port
+ default:
+ return sortDeferDecision
+ }
+
+ switch {
+ case ipv4.Port == saPort:
+ return sortDeferDecision
+ case ipv4.Port < saPort:
+ return sortReceiverBeforeArg
+ default:
+ return sortArgBeforeReceiver
+ }
+}
+
+// CmpRFC follows the Cmp() standard protocol and returns:
+//
+// - -1 If the receiver should sort first because it belongs to the RFC and its
+// arg does not
+// - 0 if the receiver and arg both belong to the same RFC or neither do.
+// - 1 If the arg belongs to the RFC but receiver does not.
+func (ipv4 IPv4Addr) CmpRFC(rfcNum uint, sa SockAddr) int {
+ recvInRFC := IsRFC(rfcNum, ipv4)
+ ipv4b, ok := sa.(IPv4Addr)
+ if !ok {
+ // If the receiver is part of the desired RFC and the SockAddr
+ // argument is not, return -1 so that the receiver sorts before
+ // the non-IPv4 SockAddr. Conversely, if the receiver is not
+ // part of the RFC, punt on sorting and leave it for the next
+ // sorter.
+ if recvInRFC {
+ return sortReceiverBeforeArg
+ } else {
+ return sortDeferDecision
+ }
+ }
+
+ argInRFC := IsRFC(rfcNum, ipv4b)
+ switch {
+ case (recvInRFC && argInRFC), (!recvInRFC && !argInRFC):
+ // If a and b both belong to the RFC, or neither belong to
+ // rfcNum, defer sorting to the next sorter.
+ return sortDeferDecision
+ case recvInRFC && !argInRFC:
+ return sortReceiverBeforeArg
+ default:
+ return sortArgBeforeReceiver
+ }
+}
+
+// Contains returns true if the SockAddr is contained within the receiver.
+func (ipv4 IPv4Addr) Contains(sa SockAddr) bool {
+ ipv4b, ok := sa.(IPv4Addr)
+ if !ok {
+ return false
+ }
+
+ return ipv4.ContainsNetwork(ipv4b)
+}
+
+// ContainsAddress returns true if the IPv4Address is contained within the
+// receiver.
+func (ipv4 IPv4Addr) ContainsAddress(x IPv4Address) bool {
+ return IPv4Address(ipv4.NetworkAddress()) <= x &&
+ IPv4Address(ipv4.BroadcastAddress()) >= x
+}
+
+// ContainsNetwork returns true if the network from IPv4Addr is contained
+// within the receiver.
+func (ipv4 IPv4Addr) ContainsNetwork(x IPv4Addr) bool {
+ return ipv4.NetworkAddress() <= x.NetworkAddress() &&
+ ipv4.BroadcastAddress() >= x.BroadcastAddress()
+}
+
+// DialPacketArgs returns the arguments required to be passed to
+// net.DialUDP(). If the Mask of ipv4 is not a /32 or the Port is 0,
+// DialPacketArgs() will fail. See Host() to create an IPv4Addr with its
+// mask set to /32.
+func (ipv4 IPv4Addr) DialPacketArgs() (network, dialArgs string) {
+ if ipv4.Mask != IPv4HostMask || ipv4.Port == 0 {
+ return "udp4", ""
+ }
+ return "udp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port)
+}
+
+// DialStreamArgs returns the arguments required to be passed to
+// net.DialTCP(). If the Mask of ipv4 is not a /32 or the Port is 0,
+// DialStreamArgs() will fail. See Host() to create an IPv4Addr with its
+// mask set to /32.
+func (ipv4 IPv4Addr) DialStreamArgs() (network, dialArgs string) {
+ if ipv4.Mask != IPv4HostMask || ipv4.Port == 0 {
+ return "tcp4", ""
+ }
+ return "tcp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port)
+}
+
+// Equal returns true if a SockAddr is equal to the receiving IPv4Addr.
+func (ipv4 IPv4Addr) Equal(sa SockAddr) bool {
+ ipv4b, ok := sa.(IPv4Addr)
+ if !ok {
+ return false
+ }
+
+ if ipv4.Port != ipv4b.Port {
+ return false
+ }
+
+ if ipv4.Address != ipv4b.Address {
+ return false
+ }
+
+ if ipv4.NetIPNet().String() != ipv4b.NetIPNet().String() {
+ return false
+ }
+
+ return true
+}
+
+// FirstUsable returns an IPv4Addr set to the first address following the
+// network prefix. The first usable address in a network is normally the
+// gateway and should not be used except by devices forwarding packets
+// between two administratively distinct networks (i.e. a router). This
+// function does not discriminate against first usable vs "first address that
+// should be used." For example, FirstUsable() on "192.168.1.10/24" would
+// return the address "192.168.1.1/24".
+func (ipv4 IPv4Addr) FirstUsable() IPAddr {
+ addr := ipv4.NetworkAddress()
+
+ // If /32, return the address itself. If /31 assume a point-to-point
+ // link and return the lower address.
+ if ipv4.Maskbits() < 31 {
+ addr++
+ }
+
+ return IPv4Addr{
+ Address: IPv4Address(addr),
+ Mask: IPv4HostMask,
+ }
+}
+
+// Host returns a copy of ipv4 with its mask set to /32 so that it can be
+// used by DialPacketArgs(), DialStreamArgs(), ListenPacketArgs(), or
+// ListenStreamArgs().
+func (ipv4 IPv4Addr) Host() IPAddr {
+ // Nothing should listen on a broadcast address.
+ return IPv4Addr{
+ Address: ipv4.Address,
+ Mask: IPv4HostMask,
+ Port: ipv4.Port,
+ }
+}
+
+// IPPort returns the Port number attached to the IPv4Addr
+func (ipv4 IPv4Addr) IPPort() IPPort {
+ return ipv4.Port
+}
+
+// LastUsable returns the last address before the broadcast address in a
+// given network.
+func (ipv4 IPv4Addr) LastUsable() IPAddr {
+ addr := ipv4.BroadcastAddress()
+
+ // If /32, return the address itself. If /31 assume a point-to-point
+ // link and return the upper address.
+ if ipv4.Maskbits() < 31 {
+ addr--
+ }
+
+ return IPv4Addr{
+ Address: IPv4Address(addr),
+ Mask: IPv4HostMask,
+ }
+}
+
+// ListenPacketArgs returns the arguments required to be passed to
+// net.ListenUDP(). If the Mask of ipv4 is not a /32, ListenPacketArgs()
+// will fail. See Host() to create an IPv4Addr with its mask set to /32.
+func (ipv4 IPv4Addr) ListenPacketArgs() (network, listenArgs string) {
+ if ipv4.Mask != IPv4HostMask {
+ return "udp4", ""
+ }
+ return "udp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port)
+}
+
+// ListenStreamArgs returns the arguments required to be passed to
+// net.ListenTCP(). If the Mask of ipv4 is not a /32, ListenStreamArgs()
+// will fail. See Host() to create an IPv4Addr with its mask set to /32.
+func (ipv4 IPv4Addr) ListenStreamArgs() (network, listenArgs string) {
+ if ipv4.Mask != IPv4HostMask {
+ return "tcp4", ""
+ }
+ return "tcp4", fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port)
+}
+
+// Maskbits returns the number of network mask bits in a given IPv4Addr. For
+// example, the Maskbits() of "192.168.1.1/24" would return 24.
+func (ipv4 IPv4Addr) Maskbits() int {
+ mask := make(net.IPMask, IPv4len)
+ binary.BigEndian.PutUint32(mask, uint32(ipv4.Mask))
+ maskOnes, _ := mask.Size()
+ return maskOnes
+}
+
+// MustIPv4Addr is a helper method that must return an IPv4Addr or panic on
+// invalid input.
+func MustIPv4Addr(addr string) IPv4Addr {
+ ipv4, err := NewIPv4Addr(addr)
+ if err != nil {
+ panic(fmt.Sprintf("Unable to create an IPv4Addr from %+q: %v", addr, err))
+ }
+ return ipv4
+}
+
+// NetIP returns the address as a net.IP (address is always presized to
+// IPv4).
+func (ipv4 IPv4Addr) NetIP() *net.IP {
+ x := make(net.IP, IPv4len)
+ binary.BigEndian.PutUint32(x, uint32(ipv4.Address))
+ return &x
+}
+
+// NetIPMask create a new net.IPMask from the IPv4Addr.
+func (ipv4 IPv4Addr) NetIPMask() *net.IPMask {
+ ipv4Mask := net.IPMask{}
+ ipv4Mask = make(net.IPMask, IPv4len)
+ binary.BigEndian.PutUint32(ipv4Mask, uint32(ipv4.Mask))
+ return &ipv4Mask
+}
+
+// NetIPNet create a new net.IPNet from the IPv4Addr.
+func (ipv4 IPv4Addr) NetIPNet() *net.IPNet {
+ ipv4net := &net.IPNet{}
+ ipv4net.IP = make(net.IP, IPv4len)
+ binary.BigEndian.PutUint32(ipv4net.IP, uint32(ipv4.NetworkAddress()))
+ ipv4net.Mask = *ipv4.NetIPMask()
+ return ipv4net
+}
+
+// Network returns the network prefix or network address for a given network.
+func (ipv4 IPv4Addr) Network() IPAddr {
+ return IPv4Addr{
+ Address: IPv4Address(ipv4.NetworkAddress()),
+ Mask: ipv4.Mask,
+ }
+}
+
+// NetworkAddress returns an IPv4Network of the IPv4Addr's network address.
+func (ipv4 IPv4Addr) NetworkAddress() IPv4Network {
+ return IPv4Network(uint32(ipv4.Address) & uint32(ipv4.Mask))
+}
+
+// Octets returns a slice of the four octets in an IPv4Addr's Address. The
+// order of the bytes is big endian.
+func (ipv4 IPv4Addr) Octets() []int {
+ return []int{
+ int(ipv4.Address >> 24),
+ int((ipv4.Address >> 16) & 0xff),
+ int((ipv4.Address >> 8) & 0xff),
+ int(ipv4.Address & 0xff),
+ }
+}
+
+// String returns a string representation of the IPv4Addr
+func (ipv4 IPv4Addr) String() string {
+ if ipv4.Port != 0 {
+ return fmt.Sprintf("%s:%d", ipv4.NetIP().String(), ipv4.Port)
+ }
+
+ if ipv4.Maskbits() == 32 {
+ return ipv4.NetIP().String()
+ }
+
+ return fmt.Sprintf("%s/%d", ipv4.NetIP().String(), ipv4.Maskbits())
+}
+
+// Type is used as a type switch and returns TypeIPv4
+func (IPv4Addr) Type() SockAddrType {
+ return TypeIPv4
+}
+
+// IPv4AddrAttr returns a string representation of an attribute for the given
+// IPv4Addr.
+func IPv4AddrAttr(ipv4 IPv4Addr, selector AttrName) string {
+ fn, found := ipv4AddrAttrMap[selector]
+ if !found {
+ return ""
+ }
+
+ return fn(ipv4)
+}
+
+// IPv4Attrs returns a list of attributes supported by the IPv4Addr type
+func IPv4Attrs() []AttrName {
+ return ipv4AddrAttrs
+}
+
+// ipv4AddrInit is called once at init()
+func ipv4AddrInit() {
+ // Sorted for human readability
+ ipv4AddrAttrs = []AttrName{
+ "size", // Same position as in IPv6 for output consistency
+ "broadcast",
+ "uint32",
+ }
+
+ ipv4AddrAttrMap = map[AttrName]func(ipv4 IPv4Addr) string{
+ "broadcast": func(ipv4 IPv4Addr) string {
+ return ipv4.Broadcast().String()
+ },
+ "size": func(ipv4 IPv4Addr) string {
+ return fmt.Sprintf("%d", 1<<uint(IPv4len*8-ipv4.Maskbits()))
+ },
+ "uint32": func(ipv4 IPv4Addr) string {
+ return fmt.Sprintf("%d", uint32(ipv4.Address))
+ },
+ }
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/ipv6addr.go b/vendor/github.com/hashicorp/go-sockaddr/ipv6addr.go
new file mode 100644
index 0000000..d7f4121
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/ipv6addr.go
@@ -0,0 +1,591 @@
+package sockaddr
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "math/big"
+ "net"
+)
+
+type (
+ // IPv6Address is a named type representing an IPv6 address.
+ IPv6Address *big.Int
+
+ // IPv6Network is a named type representing an IPv6 network.
+ IPv6Network *big.Int
+
+ // IPv6Mask is a named type representing an IPv6 network mask.
+ IPv6Mask *big.Int
+)
+
+// IPv6HostPrefix is a constant represents a /128 IPv6 Prefix.
+const IPv6HostPrefix = IPPrefixLen(128)
+
+// ipv6HostMask is an unexported big.Int representing a /128 IPv6 address.
+// This value must be a constant and always set to all ones.
+var ipv6HostMask IPv6Mask
+
+// ipv6AddrAttrMap is a map of the IPv6Addr type-specific attributes.
+var ipv6AddrAttrMap map[AttrName]func(IPv6Addr) string
+var ipv6AddrAttrs []AttrName
+
+func init() {
+ biMask := new(big.Int)
+ biMask.SetBytes([]byte{
+ 0xff, 0xff,
+ 0xff, 0xff,
+ 0xff, 0xff,
+ 0xff, 0xff,
+ 0xff, 0xff,
+ 0xff, 0xff,
+ 0xff, 0xff,
+ 0xff, 0xff,
+ },
+ )
+ ipv6HostMask = IPv6Mask(biMask)
+
+ ipv6AddrInit()
+}
+
+// IPv6Addr implements a convenience wrapper around the union of Go's
+// built-in net.IP and net.IPNet types. In UNIX-speak, IPv6Addr implements
+// `sockaddr` when the the address family is set to AF_INET6
+// (i.e. `sockaddr_in6`).
+type IPv6Addr struct {
+ IPAddr
+ Address IPv6Address
+ Mask IPv6Mask
+ Port IPPort
+}
+
+// NewIPv6Addr creates an IPv6Addr from a string. String can be in the form of
+// an an IPv6:port (e.g. `[2001:4860:0:2001::68]:80`, in which case the mask is
+// assumed to be a /128), an IPv6 address (e.g. `2001:4860:0:2001::68`, also
+// with a `/128` mask), an IPv6 CIDR (e.g. `2001:4860:0:2001::68/64`, which has
+// its IP port initialized to zero). ipv6Str can not be a hostname.
+//
+// NOTE: Many net.*() routines will initialize and return an IPv4 address.
+// Always test to make sure the address returned cannot be converted to a 4 byte
+// array using To4().
+func NewIPv6Addr(ipv6Str string) (IPv6Addr, error) {
+ v6Addr := false
+LOOP:
+ for i := 0; i < len(ipv6Str); i++ {
+ switch ipv6Str[i] {
+ case '.':
+ break LOOP
+ case ':':
+ v6Addr = true
+ break LOOP
+ }
+ }
+
+ if !v6Addr {
+ return IPv6Addr{}, fmt.Errorf("Unable to resolve %+q as an IPv6 address, appears to be an IPv4 address", ipv6Str)
+ }
+
+ // Attempt to parse ipv6Str as a /128 host with a port number.
+ tcpAddr, err := net.ResolveTCPAddr("tcp6", ipv6Str)
+ if err == nil {
+ ipv6 := tcpAddr.IP.To16()
+ if ipv6 == nil {
+ return IPv6Addr{}, fmt.Errorf("Unable to resolve %+q as a 16byte IPv6 address", ipv6Str)
+ }
+
+ ipv6BigIntAddr := new(big.Int)
+ ipv6BigIntAddr.SetBytes(ipv6)
+
+ ipv6BigIntMask := new(big.Int)
+ ipv6BigIntMask.Set(ipv6HostMask)
+
+ ipv6Addr := IPv6Addr{
+ Address: IPv6Address(ipv6BigIntAddr),
+ Mask: IPv6Mask(ipv6BigIntMask),
+ Port: IPPort(tcpAddr.Port),
+ }
+
+ return ipv6Addr, nil
+ }
+
+ // Parse as a naked IPv6 address. Trim square brackets if present.
+ if len(ipv6Str) > 2 && ipv6Str[0] == '[' && ipv6Str[len(ipv6Str)-1] == ']' {
+ ipv6Str = ipv6Str[1 : len(ipv6Str)-1]
+ }
+ ip := net.ParseIP(ipv6Str)
+ if ip != nil {
+ ipv6 := ip.To16()
+ if ipv6 == nil {
+ return IPv6Addr{}, fmt.Errorf("Unable to string convert %+q to a 16byte IPv6 address", ipv6Str)
+ }
+
+ ipv6BigIntAddr := new(big.Int)
+ ipv6BigIntAddr.SetBytes(ipv6)
+
+ ipv6BigIntMask := new(big.Int)
+ ipv6BigIntMask.Set(ipv6HostMask)
+
+ return IPv6Addr{
+ Address: IPv6Address(ipv6BigIntAddr),
+ Mask: IPv6Mask(ipv6BigIntMask),
+ }, nil
+ }
+
+ // Parse as an IPv6 CIDR
+ ipAddr, network, err := net.ParseCIDR(ipv6Str)
+ if err == nil {
+ ipv6 := ipAddr.To16()
+ if ipv6 == nil {
+ return IPv6Addr{}, fmt.Errorf("Unable to convert %+q to a 16byte IPv6 address", ipv6Str)
+ }
+
+ ipv6BigIntAddr := new(big.Int)
+ ipv6BigIntAddr.SetBytes(ipv6)
+
+ ipv6BigIntMask := new(big.Int)
+ ipv6BigIntMask.SetBytes(network.Mask)
+
+ ipv6Addr := IPv6Addr{
+ Address: IPv6Address(ipv6BigIntAddr),
+ Mask: IPv6Mask(ipv6BigIntMask),
+ }
+ return ipv6Addr, nil
+ }
+
+ return IPv6Addr{}, fmt.Errorf("Unable to parse %+q to an IPv6 address: %v", ipv6Str, err)
+}
+
+// AddressBinString returns a string with the IPv6Addr's Address represented
+// as a sequence of '0' and '1' characters. This method is useful for
+// debugging or by operators who want to inspect an address.
+func (ipv6 IPv6Addr) AddressBinString() string {
+ bi := big.Int(*ipv6.Address)
+ return fmt.Sprintf("%0128s", bi.Text(2))
+}
+
+// AddressHexString returns a string with the IPv6Addr address represented as
+// a sequence of hex characters. This method is useful for debugging or by
+// operators who want to inspect an address.
+func (ipv6 IPv6Addr) AddressHexString() string {
+ bi := big.Int(*ipv6.Address)
+ return fmt.Sprintf("%032s", bi.Text(16))
+}
+
+// CmpAddress follows the Cmp() standard protocol and returns:
+//
+// - -1 If the receiver should sort first because its address is lower than arg
+// - 0 if the SockAddr arg equal to the receiving IPv6Addr or the argument is of a
+// different type.
+// - 1 If the argument should sort first.
+func (ipv6 IPv6Addr) CmpAddress(sa SockAddr) int {
+ ipv6b, ok := sa.(IPv6Addr)
+ if !ok {
+ return sortDeferDecision
+ }
+
+ ipv6aBigInt := new(big.Int)
+ ipv6aBigInt.Set(ipv6.Address)
+ ipv6bBigInt := new(big.Int)
+ ipv6bBigInt.Set(ipv6b.Address)
+
+ return ipv6aBigInt.Cmp(ipv6bBigInt)
+}
+
+// CmpPort follows the Cmp() standard protocol and returns:
+//
+// - -1 If the receiver should sort first because its port is lower than arg
+// - 0 if the SockAddr arg's port number is equal to the receiving IPv6Addr,
+// regardless of type.
+// - 1 If the argument should sort first.
+func (ipv6 IPv6Addr) CmpPort(sa SockAddr) int {
+ var saPort IPPort
+ switch v := sa.(type) {
+ case IPv4Addr:
+ saPort = v.Port
+ case IPv6Addr:
+ saPort = v.Port
+ default:
+ return sortDeferDecision
+ }
+
+ switch {
+ case ipv6.Port == saPort:
+ return sortDeferDecision
+ case ipv6.Port < saPort:
+ return sortReceiverBeforeArg
+ default:
+ return sortArgBeforeReceiver
+ }
+}
+
+// CmpRFC follows the Cmp() standard protocol and returns:
+//
+// - -1 If the receiver should sort first because it belongs to the RFC and its
+// arg does not
+// - 0 if the receiver and arg both belong to the same RFC or neither do.
+// - 1 If the arg belongs to the RFC but receiver does not.
+func (ipv6 IPv6Addr) CmpRFC(rfcNum uint, sa SockAddr) int {
+ recvInRFC := IsRFC(rfcNum, ipv6)
+ ipv6b, ok := sa.(IPv6Addr)
+ if !ok {
+ // If the receiver is part of the desired RFC and the SockAddr
+ // argument is not, sort receiver before the non-IPv6 SockAddr.
+ // Conversely, if the receiver is not part of the RFC, punt on
+ // sorting and leave it for the next sorter.
+ if recvInRFC {
+ return sortReceiverBeforeArg
+ } else {
+ return sortDeferDecision
+ }
+ }
+
+ argInRFC := IsRFC(rfcNum, ipv6b)
+ switch {
+ case (recvInRFC && argInRFC), (!recvInRFC && !argInRFC):
+ // If a and b both belong to the RFC, or neither belong to
+ // rfcNum, defer sorting to the next sorter.
+ return sortDeferDecision
+ case recvInRFC && !argInRFC:
+ return sortReceiverBeforeArg
+ default:
+ return sortArgBeforeReceiver
+ }
+}
+
+// Contains returns true if the SockAddr is contained within the receiver.
+func (ipv6 IPv6Addr) Contains(sa SockAddr) bool {
+ ipv6b, ok := sa.(IPv6Addr)
+ if !ok {
+ return false
+ }
+
+ return ipv6.ContainsNetwork(ipv6b)
+}
+
+// ContainsAddress returns true if the IPv6Address is contained within the
+// receiver.
+func (ipv6 IPv6Addr) ContainsAddress(x IPv6Address) bool {
+ xAddr := IPv6Addr{
+ Address: x,
+ Mask: ipv6HostMask,
+ }
+
+ {
+ xIPv6 := xAddr.FirstUsable().(IPv6Addr)
+ yIPv6 := ipv6.FirstUsable().(IPv6Addr)
+ if xIPv6.CmpAddress(yIPv6) >= 1 {
+ return false
+ }
+ }
+
+ {
+ xIPv6 := xAddr.LastUsable().(IPv6Addr)
+ yIPv6 := ipv6.LastUsable().(IPv6Addr)
+ if xIPv6.CmpAddress(yIPv6) <= -1 {
+ return false
+ }
+ }
+ return true
+}
+
+// ContainsNetwork returns true if the network from IPv6Addr is contained within
+// the receiver.
+func (x IPv6Addr) ContainsNetwork(y IPv6Addr) bool {
+ {
+ xIPv6 := x.FirstUsable().(IPv6Addr)
+ yIPv6 := y.FirstUsable().(IPv6Addr)
+ if ret := xIPv6.CmpAddress(yIPv6); ret >= 1 {
+ return false
+ }
+ }
+
+ {
+ xIPv6 := x.LastUsable().(IPv6Addr)
+ yIPv6 := y.LastUsable().(IPv6Addr)
+ if ret := xIPv6.CmpAddress(yIPv6); ret <= -1 {
+ return false
+ }
+ }
+ return true
+}
+
+// DialPacketArgs returns the arguments required to be passed to
+// net.DialUDP(). If the Mask of ipv6 is not a /128 or the Port is 0,
+// DialPacketArgs() will fail. See Host() to create an IPv6Addr with its
+// mask set to /128.
+func (ipv6 IPv6Addr) DialPacketArgs() (network, dialArgs string) {
+ ipv6Mask := big.Int(*ipv6.Mask)
+ if ipv6Mask.Cmp(ipv6HostMask) != 0 || ipv6.Port == 0 {
+ return "udp6", ""
+ }
+ return "udp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port)
+}
+
+// DialStreamArgs returns the arguments required to be passed to
+// net.DialTCP(). If the Mask of ipv6 is not a /128 or the Port is 0,
+// DialStreamArgs() will fail. See Host() to create an IPv6Addr with its
+// mask set to /128.
+func (ipv6 IPv6Addr) DialStreamArgs() (network, dialArgs string) {
+ ipv6Mask := big.Int(*ipv6.Mask)
+ if ipv6Mask.Cmp(ipv6HostMask) != 0 || ipv6.Port == 0 {
+ return "tcp6", ""
+ }
+ return "tcp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port)
+}
+
+// Equal returns true if a SockAddr is equal to the receiving IPv4Addr.
+func (ipv6a IPv6Addr) Equal(sa SockAddr) bool {
+ ipv6b, ok := sa.(IPv6Addr)
+ if !ok {
+ return false
+ }
+
+ if ipv6a.NetIP().String() != ipv6b.NetIP().String() {
+ return false
+ }
+
+ if ipv6a.NetIPNet().String() != ipv6b.NetIPNet().String() {
+ return false
+ }
+
+ if ipv6a.Port != ipv6b.Port {
+ return false
+ }
+
+ return true
+}
+
+// FirstUsable returns an IPv6Addr set to the first address following the
+// network prefix. The first usable address in a network is normally the
+// gateway and should not be used except by devices forwarding packets
+// between two administratively distinct networks (i.e. a router). This
+// function does not discriminate against first usable vs "first address that
+// should be used." For example, FirstUsable() on "2001:0db8::0003/64" would
+// return "2001:0db8::00011".
+func (ipv6 IPv6Addr) FirstUsable() IPAddr {
+ return IPv6Addr{
+ Address: IPv6Address(ipv6.NetworkAddress()),
+ Mask: ipv6HostMask,
+ }
+}
+
+// Host returns a copy of ipv6 with its mask set to /128 so that it can be
+// used by DialPacketArgs(), DialStreamArgs(), ListenPacketArgs(), or
+// ListenStreamArgs().
+func (ipv6 IPv6Addr) Host() IPAddr {
+ // Nothing should listen on a broadcast address.
+ return IPv6Addr{
+ Address: ipv6.Address,
+ Mask: ipv6HostMask,
+ Port: ipv6.Port,
+ }
+}
+
+// IPPort returns the Port number attached to the IPv6Addr
+func (ipv6 IPv6Addr) IPPort() IPPort {
+ return ipv6.Port
+}
+
+// LastUsable returns the last address in a given network.
+func (ipv6 IPv6Addr) LastUsable() IPAddr {
+ addr := new(big.Int)
+ addr.Set(ipv6.Address)
+
+ mask := new(big.Int)
+ mask.Set(ipv6.Mask)
+
+ negMask := new(big.Int)
+ negMask.Xor(ipv6HostMask, mask)
+
+ lastAddr := new(big.Int)
+ lastAddr.And(addr, mask)
+ lastAddr.Or(lastAddr, negMask)
+
+ return IPv6Addr{
+ Address: IPv6Address(lastAddr),
+ Mask: ipv6HostMask,
+ }
+}
+
+// ListenPacketArgs returns the arguments required to be passed to
+// net.ListenUDP(). If the Mask of ipv6 is not a /128, ListenPacketArgs()
+// will fail. See Host() to create an IPv6Addr with its mask set to /128.
+func (ipv6 IPv6Addr) ListenPacketArgs() (network, listenArgs string) {
+ ipv6Mask := big.Int(*ipv6.Mask)
+ if ipv6Mask.Cmp(ipv6HostMask) != 0 {
+ return "udp6", ""
+ }
+ return "udp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port)
+}
+
+// ListenStreamArgs returns the arguments required to be passed to
+// net.ListenTCP(). If the Mask of ipv6 is not a /128, ListenStreamArgs()
+// will fail. See Host() to create an IPv6Addr with its mask set to /128.
+func (ipv6 IPv6Addr) ListenStreamArgs() (network, listenArgs string) {
+ ipv6Mask := big.Int(*ipv6.Mask)
+ if ipv6Mask.Cmp(ipv6HostMask) != 0 {
+ return "tcp6", ""
+ }
+ return "tcp6", fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port)
+}
+
+// Maskbits returns the number of network mask bits in a given IPv6Addr. For
+// example, the Maskbits() of "2001:0db8::0003/64" would return 64.
+func (ipv6 IPv6Addr) Maskbits() int {
+ maskOnes, _ := ipv6.NetIPNet().Mask.Size()
+
+ return maskOnes
+}
+
+// MustIPv6Addr is a helper method that must return an IPv6Addr or panic on
+// invalid input.
+func MustIPv6Addr(addr string) IPv6Addr {
+ ipv6, err := NewIPv6Addr(addr)
+ if err != nil {
+ panic(fmt.Sprintf("Unable to create an IPv6Addr from %+q: %v", addr, err))
+ }
+ return ipv6
+}
+
+// NetIP returns the address as a net.IP.
+func (ipv6 IPv6Addr) NetIP() *net.IP {
+ return bigIntToNetIPv6(ipv6.Address)
+}
+
+// NetIPMask create a new net.IPMask from the IPv6Addr.
+func (ipv6 IPv6Addr) NetIPMask() *net.IPMask {
+ ipv6Mask := make(net.IPMask, IPv6len)
+ m := big.Int(*ipv6.Mask)
+ copy(ipv6Mask, m.Bytes())
+ return &ipv6Mask
+}
+
+// Network returns a pointer to the net.IPNet within IPv4Addr receiver.
+func (ipv6 IPv6Addr) NetIPNet() *net.IPNet {
+ ipv6net := &net.IPNet{}
+ ipv6net.IP = make(net.IP, IPv6len)
+ copy(ipv6net.IP, *ipv6.NetIP())
+ ipv6net.Mask = *ipv6.NetIPMask()
+ return ipv6net
+}
+
+// Network returns the network prefix or network address for a given network.
+func (ipv6 IPv6Addr) Network() IPAddr {
+ return IPv6Addr{
+ Address: IPv6Address(ipv6.NetworkAddress()),
+ Mask: ipv6.Mask,
+ }
+}
+
+// NetworkAddress returns an IPv6Network of the IPv6Addr's network address.
+func (ipv6 IPv6Addr) NetworkAddress() IPv6Network {
+ addr := new(big.Int)
+ addr.SetBytes((*ipv6.Address).Bytes())
+
+ mask := new(big.Int)
+ mask.SetBytes(*ipv6.NetIPMask())
+
+ netAddr := new(big.Int)
+ netAddr.And(addr, mask)
+
+ return IPv6Network(netAddr)
+}
+
+// Octets returns a slice of the 16 octets in an IPv6Addr's Address. The
+// order of the bytes is big endian.
+func (ipv6 IPv6Addr) Octets() []int {
+ x := make([]int, IPv6len)
+ for i, b := range *bigIntToNetIPv6(ipv6.Address) {
+ x[i] = int(b)
+ }
+
+ return x
+}
+
+// String returns a string representation of the IPv6Addr
+func (ipv6 IPv6Addr) String() string {
+ if ipv6.Port != 0 {
+ return fmt.Sprintf("[%s]:%d", ipv6.NetIP().String(), ipv6.Port)
+ }
+
+ if ipv6.Maskbits() == 128 {
+ return ipv6.NetIP().String()
+ }
+
+ return fmt.Sprintf("%s/%d", ipv6.NetIP().String(), ipv6.Maskbits())
+}
+
+// Type is used as a type switch and returns TypeIPv6
+func (IPv6Addr) Type() SockAddrType {
+ return TypeIPv6
+}
+
+// IPv6Attrs returns a list of attributes supported by the IPv6Addr type
+func IPv6Attrs() []AttrName {
+ return ipv6AddrAttrs
+}
+
+// IPv6AddrAttr returns a string representation of an attribute for the given
+// IPv6Addr.
+func IPv6AddrAttr(ipv6 IPv6Addr, selector AttrName) string {
+ fn, found := ipv6AddrAttrMap[selector]
+ if !found {
+ return ""
+ }
+
+ return fn(ipv6)
+}
+
+// ipv6AddrInit is called once at init()
+func ipv6AddrInit() {
+ // Sorted for human readability
+ ipv6AddrAttrs = []AttrName{
+ "size", // Same position as in IPv6 for output consistency
+ "uint128",
+ }
+
+ ipv6AddrAttrMap = map[AttrName]func(ipv6 IPv6Addr) string{
+ "size": func(ipv6 IPv6Addr) string {
+ netSize := big.NewInt(1)
+ netSize = netSize.Lsh(netSize, uint(IPv6len*8-ipv6.Maskbits()))
+ return netSize.Text(10)
+ },
+ "uint128": func(ipv6 IPv6Addr) string {
+ b := big.Int(*ipv6.Address)
+ return b.Text(10)
+ },
+ }
+}
+
+// bigIntToNetIPv6 is a helper function that correctly returns a net.IP with the
+// correctly padded values.
+func bigIntToNetIPv6(bi *big.Int) *net.IP {
+ x := make(net.IP, IPv6len)
+ ipv6Bytes := bi.Bytes()
+
+ // It's possibe for ipv6Bytes to be less than IPv6len bytes in size. If
+ // they are different sizes we to pad the size of response.
+ if len(ipv6Bytes) < IPv6len {
+ buf := new(bytes.Buffer)
+ buf.Grow(IPv6len)
+
+ for i := len(ipv6Bytes); i < IPv6len; i++ {
+ if err := binary.Write(buf, binary.BigEndian, byte(0)); err != nil {
+ panic(fmt.Sprintf("Unable to pad byte %d of input %v: %v", i, bi, err))
+ }
+ }
+
+ for _, b := range ipv6Bytes {
+ if err := binary.Write(buf, binary.BigEndian, b); err != nil {
+ panic(fmt.Sprintf("Unable to preserve endianness of input %v: %v", bi, err))
+ }
+ }
+
+ ipv6Bytes = buf.Bytes()
+ }
+ i := copy(x, ipv6Bytes)
+ if i != IPv6len {
+ panic("IPv6 wrong size")
+ }
+ return &x
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/rfc.go b/vendor/github.com/hashicorp/go-sockaddr/rfc.go
new file mode 100644
index 0000000..fd9be94
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/rfc.go
@@ -0,0 +1,947 @@
+package sockaddr
+
+// ForwardingBlacklist is a faux RFC that includes a list of non-forwardable IP
+// blocks.
+const ForwardingBlacklist = 4294967295
+
+// IsRFC tests to see if an SockAddr matches the specified RFC
+func IsRFC(rfcNum uint, sa SockAddr) bool {
+ rfcNetMap := KnownRFCs()
+ rfcNets, ok := rfcNetMap[rfcNum]
+ if !ok {
+ return false
+ }
+
+ var contained bool
+ for _, rfcNet := range rfcNets {
+ if rfcNet.Contains(sa) {
+ contained = true
+ break
+ }
+ }
+ return contained
+}
+
+// KnownRFCs returns an initial set of known RFCs.
+//
+// NOTE (sean@): As this list evolves over time, please submit patches to keep
+// this list current. If something isn't right, inquire, as it may just be a
+// bug on my part. Some of the inclusions were based on my judgement as to what
+// would be a useful value (e.g. RFC3330).
+//
+// Useful resources:
+//
+// * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
+// * https://www.iana.org/assignments/ipv6-unicast-address-assignments/ipv6-unicast-address-assignments.xhtml
+// * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
+func KnownRFCs() map[uint]SockAddrs {
+ // NOTE(sean@): Multiple SockAddrs per RFC lend themselves well to a
+ // RADIX tree, but `ENOTIME`. Patches welcome.
+ return map[uint]SockAddrs{
+ 919: {
+ // [RFC919] Broadcasting Internet Datagrams
+ MustIPv4Addr("255.255.255.255/32"), // [RFC1122], §7 Broadcast IP Addressing - Proposed Standards
+ },
+ 1122: {
+ // [RFC1122] Requirements for Internet Hosts -- Communication Layers
+ MustIPv4Addr("0.0.0.0/8"), // [RFC1122], §3.2.1.3
+ MustIPv4Addr("127.0.0.0/8"), // [RFC1122], §3.2.1.3
+ },
+ 1112: {
+ // [RFC1112] Host Extensions for IP Multicasting
+ MustIPv4Addr("224.0.0.0/4"), // [RFC1112], §4 Host Group Addresses
+ },
+ 1918: {
+ // [RFC1918] Address Allocation for Private Internets
+ MustIPv4Addr("10.0.0.0/8"),
+ MustIPv4Addr("172.16.0.0/12"),
+ MustIPv4Addr("192.168.0.0/16"),
+ },
+ 2544: {
+ // [RFC2544] Benchmarking Methodology for Network
+ // Interconnect Devices
+ MustIPv4Addr("198.18.0.0/15"),
+ },
+ 2765: {
+ // [RFC2765] Stateless IP/ICMP Translation Algorithm
+ // (SIIT) (obsoleted by RFCs 6145, which itself was
+ // later obsoleted by 7915).
+
+ // [RFC2765], §2.1 Addresses
+ MustIPv6Addr("0:0:0:0:0:ffff:0:0/96"),
+ },
+ 2928: {
+ // [RFC2928] Initial IPv6 Sub-TLA ID Assignments
+ MustIPv6Addr("2001::/16"), // Superblock
+ //MustIPv6Addr("2001:0000::/23"), // IANA
+ //MustIPv6Addr("2001:0200::/23"), // APNIC
+ //MustIPv6Addr("2001:0400::/23"), // ARIN
+ //MustIPv6Addr("2001:0600::/23"), // RIPE NCC
+ //MustIPv6Addr("2001:0800::/23"), // (future assignment)
+ // ...
+ //MustIPv6Addr("2001:FE00::/23"), // (future assignment)
+ },
+ 3056: { // 6to4 address
+ // [RFC3056] Connection of IPv6 Domains via IPv4 Clouds
+
+ // [RFC3056], §2 IPv6 Prefix Allocation
+ MustIPv6Addr("2002::/16"),
+ },
+ 3068: {
+ // [RFC3068] An Anycast Prefix for 6to4 Relay Routers
+ // (obsolete by RFC7526)
+
+ // [RFC3068], § 6to4 Relay anycast address
+ MustIPv4Addr("192.88.99.0/24"),
+
+ // [RFC3068], §2.5 6to4 IPv6 relay anycast address
+ //
+ // NOTE: /120 == 128-(32-24)
+ MustIPv6Addr("2002:c058:6301::/120"),
+ },
+ 3171: {
+ // [RFC3171] IANA Guidelines for IPv4 Multicast Address Assignments
+ MustIPv4Addr("224.0.0.0/4"),
+ },
+ 3330: {
+ // [RFC3330] Special-Use IPv4 Addresses
+
+ // Addresses in this block refer to source hosts on
+ // "this" network. Address 0.0.0.0/32 may be used as a
+ // source address for this host on this network; other
+ // addresses within 0.0.0.0/8 may be used to refer to
+ // specified hosts on this network [RFC1700, page 4].
+ MustIPv4Addr("0.0.0.0/8"),
+
+ // 10.0.0.0/8 - This block is set aside for use in
+ // private networks. Its intended use is documented in
+ // [RFC1918]. Addresses within this block should not
+ // appear on the public Internet.
+ MustIPv4Addr("10.0.0.0/8"),
+
+ // 14.0.0.0/8 - This block is set aside for assignments
+ // to the international system of Public Data Networks
+ // [RFC1700, page 181]. The registry of assignments
+ // within this block can be accessed from the "Public
+ // Data Network Numbers" link on the web page at
+ // http://www.iana.org/numbers.html. Addresses within
+ // this block are assigned to users and should be
+ // treated as such.
+
+ // 24.0.0.0/8 - This block was allocated in early 1996
+ // for use in provisioning IP service over cable
+ // television systems. Although the IANA initially was
+ // involved in making assignments to cable operators,
+ // this responsibility was transferred to American
+ // Registry for Internet Numbers (ARIN) in May 2001.
+ // Addresses within this block are assigned in the
+ // normal manner and should be treated as such.
+
+ // 39.0.0.0/8 - This block was used in the "Class A
+ // Subnet Experiment" that commenced in May 1995, as
+ // documented in [RFC1797]. The experiment has been
+ // completed and this block has been returned to the
+ // pool of addresses reserved for future allocation or
+ // assignment. This block therefore no longer has a
+ // special use and is subject to allocation to a
+ // Regional Internet Registry for assignment in the
+ // normal manner.
+
+ // 127.0.0.0/8 - This block is assigned for use as the Internet host
+ // loopback address. A datagram sent by a higher level protocol to an
+ // address anywhere within this block should loop back inside the host.
+ // This is ordinarily implemented using only 127.0.0.1/32 for loopback,
+ // but no addresses within this block should ever appear on any network
+ // anywhere [RFC1700, page 5].
+ MustIPv4Addr("127.0.0.0/8"),
+
+ // 128.0.0.0/16 - This block, corresponding to the
+ // numerically lowest of the former Class B addresses,
+ // was initially and is still reserved by the IANA.
+ // Given the present classless nature of the IP address
+ // space, the basis for the reservation no longer
+ // applies and addresses in this block are subject to
+ // future allocation to a Regional Internet Registry for
+ // assignment in the normal manner.
+
+ // 169.254.0.0/16 - This is the "link local" block. It
+ // is allocated for communication between hosts on a
+ // single link. Hosts obtain these addresses by
+ // auto-configuration, such as when a DHCP server may
+ // not be found.
+ MustIPv4Addr("169.254.0.0/16"),
+
+ // 172.16.0.0/12 - This block is set aside for use in
+ // private networks. Its intended use is documented in
+ // [RFC1918]. Addresses within this block should not
+ // appear on the public Internet.
+ MustIPv4Addr("172.16.0.0/12"),
+
+ // 191.255.0.0/16 - This block, corresponding to the numerically highest
+ // to the former Class B addresses, was initially and is still reserved
+ // by the IANA. Given the present classless nature of the IP address
+ // space, the basis for the reservation no longer applies and addresses
+ // in this block are subject to future allocation to a Regional Internet
+ // Registry for assignment in the normal manner.
+
+ // 192.0.0.0/24 - This block, corresponding to the
+ // numerically lowest of the former Class C addresses,
+ // was initially and is still reserved by the IANA.
+ // Given the present classless nature of the IP address
+ // space, the basis for the reservation no longer
+ // applies and addresses in this block are subject to
+ // future allocation to a Regional Internet Registry for
+ // assignment in the normal manner.
+
+ // 192.0.2.0/24 - This block is assigned as "TEST-NET" for use in
+ // documentation and example code. It is often used in conjunction with
+ // domain names example.com or example.net in vendor and protocol
+ // documentation. Addresses within this block should not appear on the
+ // public Internet.
+ MustIPv4Addr("192.0.2.0/24"),
+
+ // 192.88.99.0/24 - This block is allocated for use as 6to4 relay
+ // anycast addresses, according to [RFC3068].
+ MustIPv4Addr("192.88.99.0/24"),
+
+ // 192.168.0.0/16 - This block is set aside for use in private networks.
+ // Its intended use is documented in [RFC1918]. Addresses within this
+ // block should not appear on the public Internet.
+ MustIPv4Addr("192.168.0.0/16"),
+
+ // 198.18.0.0/15 - This block has been allocated for use
+ // in benchmark tests of network interconnect devices.
+ // Its use is documented in [RFC2544].
+ MustIPv4Addr("198.18.0.0/15"),
+
+ // 223.255.255.0/24 - This block, corresponding to the
+ // numerically highest of the former Class C addresses,
+ // was initially and is still reserved by the IANA.
+ // Given the present classless nature of the IP address
+ // space, the basis for the reservation no longer
+ // applies and addresses in this block are subject to
+ // future allocation to a Regional Internet Registry for
+ // assignment in the normal manner.
+
+ // 224.0.0.0/4 - This block, formerly known as the Class
+ // D address space, is allocated for use in IPv4
+ // multicast address assignments. The IANA guidelines
+ // for assignments from this space are described in
+ // [RFC3171].
+ MustIPv4Addr("224.0.0.0/4"),
+
+ // 240.0.0.0/4 - This block, formerly known as the Class E address
+ // space, is reserved. The "limited broadcast" destination address
+ // 255.255.255.255 should never be forwarded outside the (sub-)net of
+ // the source. The remainder of this space is reserved
+ // for future use. [RFC1700, page 4]
+ MustIPv4Addr("240.0.0.0/4"),
+ },
+ 3849: {
+ // [RFC3849] IPv6 Address Prefix Reserved for Documentation
+ MustIPv6Addr("2001:db8::/32"), // [RFC3849], §4 IANA Considerations
+ },
+ 3927: {
+ // [RFC3927] Dynamic Configuration of IPv4 Link-Local Addresses
+ MustIPv4Addr("169.254.0.0/16"), // [RFC3927], §2.1 Link-Local Address Selection
+ },
+ 4038: {
+ // [RFC4038] Application Aspects of IPv6 Transition
+
+ // [RFC4038], §4.2. IPv6 Applications in a Dual-Stack Node
+ MustIPv6Addr("0:0:0:0:0:ffff::/96"),
+ },
+ 4193: {
+ // [RFC4193] Unique Local IPv6 Unicast Addresses
+ MustIPv6Addr("fc00::/7"),
+ },
+ 4291: {
+ // [RFC4291] IP Version 6 Addressing Architecture
+
+ // [RFC4291], §2.5.2 The Unspecified Address
+ MustIPv6Addr("::/128"),
+
+ // [RFC4291], §2.5.3 The Loopback Address
+ MustIPv6Addr("::1/128"),
+
+ // [RFC4291], §2.5.5.1. IPv4-Compatible IPv6 Address
+ MustIPv6Addr("::/96"),
+
+ // [RFC4291], §2.5.5.2. IPv4-Mapped IPv6 Address
+ MustIPv6Addr("::ffff:0:0/96"),
+
+ // [RFC4291], §2.5.6 Link-Local IPv6 Unicast Addresses
+ MustIPv6Addr("fe80::/10"),
+
+ // [RFC4291], §2.5.7 Site-Local IPv6 Unicast Addresses
+ // (depreciated)
+ MustIPv6Addr("fec0::/10"),
+
+ // [RFC4291], §2.7 Multicast Addresses
+ MustIPv6Addr("ff00::/8"),
+
+ // IPv6 Multicast Information.
+ //
+ // In the following "table" below, `ff0x` is replaced
+ // with the following values depending on the scope of
+ // the query:
+ //
+ // IPv6 Multicast Scopes:
+ // * ff00/9 // reserved
+ // * ff01/9 // interface-local
+ // * ff02/9 // link-local
+ // * ff03/9 // realm-local
+ // * ff04/9 // admin-local
+ // * ff05/9 // site-local
+ // * ff08/9 // organization-local
+ // * ff0e/9 // global
+ // * ff0f/9 // reserved
+ //
+ // IPv6 Multicast Addresses:
+ // * ff0x::2 // All routers
+ // * ff02::5 // OSPFIGP
+ // * ff02::6 // OSPFIGP Designated Routers
+ // * ff02::9 // RIP Routers
+ // * ff02::a // EIGRP Routers
+ // * ff02::d // All PIM Routers
+ // * ff02::1a // All RPL Routers
+ // * ff0x::fb // mDNSv6
+ // * ff0x::101 // All Network Time Protocol (NTP) servers
+ // * ff02::1:1 // Link Name
+ // * ff02::1:2 // All-dhcp-agents
+ // * ff02::1:3 // Link-local Multicast Name Resolution
+ // * ff05::1:3 // All-dhcp-servers
+ // * ff02::1:ff00:0/104 // Solicited-node multicast address.
+ // * ff02::2:ff00:0/104 // Node Information Queries
+ },
+ 4380: {
+ // [RFC4380] Teredo: Tunneling IPv6 over UDP through
+ // Network Address Translations (NATs)
+
+ // [RFC4380], §2.6 Global Teredo IPv6 Service Prefix
+ MustIPv6Addr("2001:0000::/32"),
+ },
+ 4773: {
+ // [RFC4773] Administration of the IANA Special Purpose IPv6 Address Block
+ MustIPv6Addr("2001:0000::/23"), // IANA
+ },
+ 4843: {
+ // [RFC4843] An IPv6 Prefix for Overlay Routable Cryptographic Hash Identifiers (ORCHID)
+ MustIPv6Addr("2001:10::/28"), // [RFC4843], §7 IANA Considerations
+ },
+ 5180: {
+ // [RFC5180] IPv6 Benchmarking Methodology for Network Interconnect Devices
+ MustIPv6Addr("2001:0200::/48"), // [RFC5180], §8 IANA Considerations
+ },
+ 5735: {
+ // [RFC5735] Special Use IPv4 Addresses
+ MustIPv4Addr("192.0.2.0/24"), // TEST-NET-1
+ MustIPv4Addr("198.51.100.0/24"), // TEST-NET-2
+ MustIPv4Addr("203.0.113.0/24"), // TEST-NET-3
+ MustIPv4Addr("198.18.0.0/15"), // Benchmarks
+ },
+ 5737: {
+ // [RFC5737] IPv4 Address Blocks Reserved for Documentation
+ MustIPv4Addr("192.0.2.0/24"), // TEST-NET-1
+ MustIPv4Addr("198.51.100.0/24"), // TEST-NET-2
+ MustIPv4Addr("203.0.113.0/24"), // TEST-NET-3
+ },
+ 6052: {
+ // [RFC6052] IPv6 Addressing of IPv4/IPv6 Translators
+ MustIPv6Addr("64:ff9b::/96"), // [RFC6052], §2.1. Well-Known Prefix
+ },
+ 6333: {
+ // [RFC6333] Dual-Stack Lite Broadband Deployments Following IPv4 Exhaustion
+ MustIPv4Addr("192.0.0.0/29"), // [RFC6333], §5.7 Well-Known IPv4 Address
+ },
+ 6598: {
+ // [RFC6598] IANA-Reserved IPv4 Prefix for Shared Address Space
+ MustIPv4Addr("100.64.0.0/10"),
+ },
+ 6666: {
+ // [RFC6666] A Discard Prefix for IPv6
+ MustIPv6Addr("0100::/64"),
+ },
+ 6890: {
+ // [RFC6890] Special-Purpose IP Address Registries
+
+ // From "RFC6890 §2.2.1 Information Requirements":
+ /*
+ The IPv4 and IPv6 Special-Purpose Address Registries maintain the
+ following information regarding each entry:
+
+ o Address Block - A block of IPv4 or IPv6 addresses that has been
+ registered for a special purpose.
+
+ o Name - A descriptive name for the special-purpose address block.
+
+ o RFC - The RFC through which the special-purpose address block was
+ requested.
+
+ o Allocation Date - The date upon which the special-purpose address
+ block was allocated.
+
+ o Termination Date - The date upon which the allocation is to be
+ terminated. This field is applicable for limited-use allocations
+ only.
+
+ o Source - A boolean value indicating whether an address from the
+ allocated special-purpose address block is valid when used as the
+ source address of an IP datagram that transits two devices.
+
+ o Destination - A boolean value indicating whether an address from
+ the allocated special-purpose address block is valid when used as
+ the destination address of an IP datagram that transits two
+ devices.
+
+ o Forwardable - A boolean value indicating whether a router may
+ forward an IP datagram whose destination address is drawn from the
+ allocated special-purpose address block between external
+ interfaces.
+
+ o Global - A boolean value indicating whether an IP datagram whose
+ destination address is drawn from the allocated special-purpose
+ address block is forwardable beyond a specified administrative
+ domain.
+
+ o Reserved-by-Protocol - A boolean value indicating whether the
+ special-purpose address block is reserved by IP, itself. This
+ value is "TRUE" if the RFC that created the special-purpose
+ address block requires all compliant IP implementations to behave
+ in a special way when processing packets either to or from
+ addresses contained by the address block.
+
+ If the value of "Destination" is FALSE, the values of "Forwardable"
+ and "Global" must also be false.
+ */
+
+ /*+----------------------+----------------------------+
+ * | Attribute | Value |
+ * +----------------------+----------------------------+
+ * | Address Block | 0.0.0.0/8 |
+ * | Name | "This host on this network"|
+ * | RFC | [RFC1122], Section 3.2.1.3 |
+ * | Allocation Date | September 1981 |
+ * | Termination Date | N/A |
+ * | Source | True |
+ * | Destination | False |
+ * | Forwardable | False |
+ * | Global | False |
+ * | Reserved-by-Protocol | True |
+ * +----------------------+----------------------------+*/
+ MustIPv4Addr("0.0.0.0/8"),
+
+ /*+----------------------+---------------+
+ * | Attribute | Value |
+ * +----------------------+---------------+
+ * | Address Block | 10.0.0.0/8 |
+ * | Name | Private-Use |
+ * | RFC | [RFC1918] |
+ * | Allocation Date | February 1996 |
+ * | Termination Date | N/A |
+ * | Source | True |
+ * | Destination | True |
+ * | Forwardable | True |
+ * | Global | False |
+ * | Reserved-by-Protocol | False |
+ * +----------------------+---------------+ */
+ MustIPv4Addr("10.0.0.0/8"),
+
+ /*+----------------------+----------------------+
+ | Attribute | Value |
+ +----------------------+----------------------+
+ | Address Block | 100.64.0.0/10 |
+ | Name | Shared Address Space |
+ | RFC | [RFC6598] |
+ | Allocation Date | April 2012 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+----------------------+*/
+ MustIPv4Addr("100.64.0.0/10"),
+
+ /*+----------------------+----------------------------+
+ | Attribute | Value |
+ +----------------------+----------------------------+
+ | Address Block | 127.0.0.0/8 |
+ | Name | Loopback |
+ | RFC | [RFC1122], Section 3.2.1.3 |
+ | Allocation Date | September 1981 |
+ | Termination Date | N/A |
+ | Source | False [1] |
+ | Destination | False [1] |
+ | Forwardable | False [1] |
+ | Global | False [1] |
+ | Reserved-by-Protocol | True |
+ +----------------------+----------------------------+*/
+ // [1] Several protocols have been granted exceptions to
+ // this rule. For examples, see [RFC4379] and
+ // [RFC5884].
+ MustIPv4Addr("127.0.0.0/8"),
+
+ /*+----------------------+----------------+
+ | Attribute | Value |
+ +----------------------+----------------+
+ | Address Block | 169.254.0.0/16 |
+ | Name | Link Local |
+ | RFC | [RFC3927] |
+ | Allocation Date | May 2005 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | True |
+ +----------------------+----------------+*/
+ MustIPv4Addr("169.254.0.0/16"),
+
+ /*+----------------------+---------------+
+ | Attribute | Value |
+ +----------------------+---------------+
+ | Address Block | 172.16.0.0/12 |
+ | Name | Private-Use |
+ | RFC | [RFC1918] |
+ | Allocation Date | February 1996 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+---------------+*/
+ MustIPv4Addr("172.16.0.0/12"),
+
+ /*+----------------------+---------------------------------+
+ | Attribute | Value |
+ +----------------------+---------------------------------+
+ | Address Block | 192.0.0.0/24 [2] |
+ | Name | IETF Protocol Assignments |
+ | RFC | Section 2.1 of this document |
+ | Allocation Date | January 2010 |
+ | Termination Date | N/A |
+ | Source | False |
+ | Destination | False |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+---------------------------------+*/
+ // [2] Not usable unless by virtue of a more specific
+ // reservation.
+ MustIPv4Addr("192.0.0.0/24"),
+
+ /*+----------------------+--------------------------------+
+ | Attribute | Value |
+ +----------------------+--------------------------------+
+ | Address Block | 192.0.0.0/29 |
+ | Name | IPv4 Service Continuity Prefix |
+ | RFC | [RFC6333], [RFC7335] |
+ | Allocation Date | June 2011 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+--------------------------------+*/
+ MustIPv4Addr("192.0.0.0/29"),
+
+ /*+----------------------+----------------------------+
+ | Attribute | Value |
+ +----------------------+----------------------------+
+ | Address Block | 192.0.2.0/24 |
+ | Name | Documentation (TEST-NET-1) |
+ | RFC | [RFC5737] |
+ | Allocation Date | January 2010 |
+ | Termination Date | N/A |
+ | Source | False |
+ | Destination | False |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+----------------------------+*/
+ MustIPv4Addr("192.0.2.0/24"),
+
+ /*+----------------------+--------------------+
+ | Attribute | Value |
+ +----------------------+--------------------+
+ | Address Block | 192.88.99.0/24 |
+ | Name | 6to4 Relay Anycast |
+ | RFC | [RFC3068] |
+ | Allocation Date | June 2001 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | True |
+ | Reserved-by-Protocol | False |
+ +----------------------+--------------------+*/
+ MustIPv4Addr("192.88.99.0/24"),
+
+ /*+----------------------+----------------+
+ | Attribute | Value |
+ +----------------------+----------------+
+ | Address Block | 192.168.0.0/16 |
+ | Name | Private-Use |
+ | RFC | [RFC1918] |
+ | Allocation Date | February 1996 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+----------------+*/
+ MustIPv4Addr("192.168.0.0/16"),
+
+ /*+----------------------+---------------+
+ | Attribute | Value |
+ +----------------------+---------------+
+ | Address Block | 198.18.0.0/15 |
+ | Name | Benchmarking |
+ | RFC | [RFC2544] |
+ | Allocation Date | March 1999 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+---------------+*/
+ MustIPv4Addr("198.18.0.0/15"),
+
+ /*+----------------------+----------------------------+
+ | Attribute | Value |
+ +----------------------+----------------------------+
+ | Address Block | 198.51.100.0/24 |
+ | Name | Documentation (TEST-NET-2) |
+ | RFC | [RFC5737] |
+ | Allocation Date | January 2010 |
+ | Termination Date | N/A |
+ | Source | False |
+ | Destination | False |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+----------------------------+*/
+ MustIPv4Addr("198.51.100.0/24"),
+
+ /*+----------------------+----------------------------+
+ | Attribute | Value |
+ +----------------------+----------------------------+
+ | Address Block | 203.0.113.0/24 |
+ | Name | Documentation (TEST-NET-3) |
+ | RFC | [RFC5737] |
+ | Allocation Date | January 2010 |
+ | Termination Date | N/A |
+ | Source | False |
+ | Destination | False |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+----------------------------+*/
+ MustIPv4Addr("203.0.113.0/24"),
+
+ /*+----------------------+----------------------+
+ | Attribute | Value |
+ +----------------------+----------------------+
+ | Address Block | 240.0.0.0/4 |
+ | Name | Reserved |
+ | RFC | [RFC1112], Section 4 |
+ | Allocation Date | August 1989 |
+ | Termination Date | N/A |
+ | Source | False |
+ | Destination | False |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | True |
+ +----------------------+----------------------+*/
+ MustIPv4Addr("240.0.0.0/4"),
+
+ /*+----------------------+----------------------+
+ | Attribute | Value |
+ +----------------------+----------------------+
+ | Address Block | 255.255.255.255/32 |
+ | Name | Limited Broadcast |
+ | RFC | [RFC0919], Section 7 |
+ | Allocation Date | October 1984 |
+ | Termination Date | N/A |
+ | Source | False |
+ | Destination | True |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+----------------------+*/
+ MustIPv4Addr("255.255.255.255/32"),
+
+ /*+----------------------+------------------+
+ | Attribute | Value |
+ +----------------------+------------------+
+ | Address Block | ::1/128 |
+ | Name | Loopback Address |
+ | RFC | [RFC4291] |
+ | Allocation Date | February 2006 |
+ | Termination Date | N/A |
+ | Source | False |
+ | Destination | False |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | True |
+ +----------------------+------------------+*/
+ MustIPv6Addr("::1/128"),
+
+ /*+----------------------+---------------------+
+ | Attribute | Value |
+ +----------------------+---------------------+
+ | Address Block | ::/128 |
+ | Name | Unspecified Address |
+ | RFC | [RFC4291] |
+ | Allocation Date | February 2006 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | False |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | True |
+ +----------------------+---------------------+*/
+ MustIPv6Addr("::/128"),
+
+ /*+----------------------+---------------------+
+ | Attribute | Value |
+ +----------------------+---------------------+
+ | Address Block | 64:ff9b::/96 |
+ | Name | IPv4-IPv6 Translat. |
+ | RFC | [RFC6052] |
+ | Allocation Date | October 2010 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | True |
+ | Reserved-by-Protocol | False |
+ +----------------------+---------------------+*/
+ MustIPv6Addr("64:ff9b::/96"),
+
+ /*+----------------------+---------------------+
+ | Attribute | Value |
+ +----------------------+---------------------+
+ | Address Block | ::ffff:0:0/96 |
+ | Name | IPv4-mapped Address |
+ | RFC | [RFC4291] |
+ | Allocation Date | February 2006 |
+ | Termination Date | N/A |
+ | Source | False |
+ | Destination | False |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | True |
+ +----------------------+---------------------+*/
+ MustIPv6Addr("::ffff:0:0/96"),
+
+ /*+----------------------+----------------------------+
+ | Attribute | Value |
+ +----------------------+----------------------------+
+ | Address Block | 100::/64 |
+ | Name | Discard-Only Address Block |
+ | RFC | [RFC6666] |
+ | Allocation Date | June 2012 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+----------------------------+*/
+ MustIPv6Addr("100::/64"),
+
+ /*+----------------------+---------------------------+
+ | Attribute | Value |
+ +----------------------+---------------------------+
+ | Address Block | 2001::/23 |
+ | Name | IETF Protocol Assignments |
+ | RFC | [RFC2928] |
+ | Allocation Date | September 2000 |
+ | Termination Date | N/A |
+ | Source | False[1] |
+ | Destination | False[1] |
+ | Forwardable | False[1] |
+ | Global | False[1] |
+ | Reserved-by-Protocol | False |
+ +----------------------+---------------------------+*/
+ // [1] Unless allowed by a more specific allocation.
+ MustIPv6Addr("2001::/16"),
+
+ /*+----------------------+----------------+
+ | Attribute | Value |
+ +----------------------+----------------+
+ | Address Block | 2001::/32 |
+ | Name | TEREDO |
+ | RFC | [RFC4380] |
+ | Allocation Date | January 2006 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+----------------+*/
+ // Covered by previous entry, included for completeness.
+ //
+ // MustIPv6Addr("2001::/16"),
+
+ /*+----------------------+----------------+
+ | Attribute | Value |
+ +----------------------+----------------+
+ | Address Block | 2001:2::/48 |
+ | Name | Benchmarking |
+ | RFC | [RFC5180] |
+ | Allocation Date | April 2008 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+----------------+*/
+ // Covered by previous entry, included for completeness.
+ //
+ // MustIPv6Addr("2001:2::/48"),
+
+ /*+----------------------+---------------+
+ | Attribute | Value |
+ +----------------------+---------------+
+ | Address Block | 2001:db8::/32 |
+ | Name | Documentation |
+ | RFC | [RFC3849] |
+ | Allocation Date | July 2004 |
+ | Termination Date | N/A |
+ | Source | False |
+ | Destination | False |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+---------------+*/
+ // Covered by previous entry, included for completeness.
+ //
+ // MustIPv6Addr("2001:db8::/32"),
+
+ /*+----------------------+--------------+
+ | Attribute | Value |
+ +----------------------+--------------+
+ | Address Block | 2001:10::/28 |
+ | Name | ORCHID |
+ | RFC | [RFC4843] |
+ | Allocation Date | March 2007 |
+ | Termination Date | March 2014 |
+ | Source | False |
+ | Destination | False |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+--------------+*/
+ // Covered by previous entry, included for completeness.
+ //
+ // MustIPv6Addr("2001:10::/28"),
+
+ /*+----------------------+---------------+
+ | Attribute | Value |
+ +----------------------+---------------+
+ | Address Block | 2002::/16 [2] |
+ | Name | 6to4 |
+ | RFC | [RFC3056] |
+ | Allocation Date | February 2001 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | N/A [2] |
+ | Reserved-by-Protocol | False |
+ +----------------------+---------------+*/
+ // [2] See [RFC3056] for details.
+ MustIPv6Addr("2002::/16"),
+
+ /*+----------------------+--------------+
+ | Attribute | Value |
+ +----------------------+--------------+
+ | Address Block | fc00::/7 |
+ | Name | Unique-Local |
+ | RFC | [RFC4193] |
+ | Allocation Date | October 2005 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | True |
+ | Global | False |
+ | Reserved-by-Protocol | False |
+ +----------------------+--------------+*/
+ MustIPv6Addr("fc00::/7"),
+
+ /*+----------------------+-----------------------+
+ | Attribute | Value |
+ +----------------------+-----------------------+
+ | Address Block | fe80::/10 |
+ | Name | Linked-Scoped Unicast |
+ | RFC | [RFC4291] |
+ | Allocation Date | February 2006 |
+ | Termination Date | N/A |
+ | Source | True |
+ | Destination | True |
+ | Forwardable | False |
+ | Global | False |
+ | Reserved-by-Protocol | True |
+ +----------------------+-----------------------+*/
+ MustIPv6Addr("fe80::/10"),
+ },
+ 7335: {
+ // [RFC7335] IPv4 Service Continuity Prefix
+ MustIPv4Addr("192.0.0.0/29"), // [RFC7335], §6 IANA Considerations
+ },
+ ForwardingBlacklist: { // Pseudo-RFC
+ // Blacklist of non-forwardable IP blocks taken from RFC6890
+ //
+ // TODO: the attributes for forwardable should be
+ // searcahble and embedded in the main list of RFCs
+ // above.
+ MustIPv4Addr("0.0.0.0/8"),
+ MustIPv4Addr("127.0.0.0/8"),
+ MustIPv4Addr("169.254.0.0/16"),
+ MustIPv4Addr("192.0.0.0/24"),
+ MustIPv4Addr("192.0.2.0/24"),
+ MustIPv4Addr("198.51.100.0/24"),
+ MustIPv4Addr("203.0.113.0/24"),
+ MustIPv4Addr("240.0.0.0/4"),
+ MustIPv4Addr("255.255.255.255/32"),
+ MustIPv6Addr("::1/128"),
+ MustIPv6Addr("::/128"),
+ MustIPv6Addr("::ffff:0:0/96"),
+
+ // There is no way of expressing a whitelist per RFC2928
+ // atm without creating a negative mask, which I don't
+ // want to do atm.
+ //MustIPv6Addr("2001::/23"),
+
+ MustIPv6Addr("2001:db8::/32"),
+ MustIPv6Addr("2001:10::/28"),
+ MustIPv6Addr("fe80::/10"),
+ },
+ }
+}
+
+// VisitAllRFCs iterates over all known RFCs and calls the visitor
+func VisitAllRFCs(fn func(rfcNum uint, sockaddrs SockAddrs)) {
+ rfcNetMap := KnownRFCs()
+
+ // Blacklist of faux-RFCs. Don't show the world that we're abusing the
+ // RFC system in this library.
+ rfcBlacklist := map[uint]struct{}{
+ ForwardingBlacklist: {},
+ }
+
+ for rfcNum, sas := range rfcNetMap {
+ if _, found := rfcBlacklist[rfcNum]; !found {
+ fn(rfcNum, sas)
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info.go b/vendor/github.com/hashicorp/go-sockaddr/route_info.go
new file mode 100644
index 0000000..2a3ee1d
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/route_info.go
@@ -0,0 +1,19 @@
+package sockaddr
+
+// RouteInterface specifies an interface for obtaining memoized route table and
+// network information from a given OS.
+type RouteInterface interface {
+ // GetDefaultInterfaceName returns the name of the interface that has a
+ // default route or an error and an empty string if a problem was
+ // encountered.
+ GetDefaultInterfaceName() (string, error)
+}
+
+// VisitCommands visits each command used by the platform-specific RouteInfo
+// implementation.
+func (ri routeInfo) VisitCommands(fn func(name string, cmd []string)) {
+ for k, v := range ri.cmds {
+ cmds := append([]string(nil), v...)
+ fn(k, cmds)
+ }
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go
new file mode 100644
index 0000000..705757a
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/route_info_bsd.go
@@ -0,0 +1,36 @@
+// +build darwin dragonfly freebsd netbsd openbsd
+
+package sockaddr
+
+import "os/exec"
+
+var cmds map[string][]string = map[string][]string{
+ "route": {"/sbin/route", "-n", "get", "default"},
+}
+
+type routeInfo struct {
+ cmds map[string][]string
+}
+
+// NewRouteInfo returns a BSD-specific implementation of the RouteInfo
+// interface.
+func NewRouteInfo() (routeInfo, error) {
+ return routeInfo{
+ cmds: cmds,
+ }, nil
+}
+
+// GetDefaultInterfaceName returns the interface name attached to the default
+// route on the default interface.
+func (ri routeInfo) GetDefaultInterfaceName() (string, error) {
+ out, err := exec.Command(cmds["route"][0], cmds["route"][1:]...).Output()
+ if err != nil {
+ return "", err
+ }
+
+ var ifName string
+ if ifName, err = parseDefaultIfNameFromRoute(string(out)); err != nil {
+ return "", err
+ }
+ return ifName, nil
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_default.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_default.go
new file mode 100644
index 0000000..d1b009f
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/route_info_default.go
@@ -0,0 +1,10 @@
+// +build android nacl plan9
+
+package sockaddr
+
+import "errors"
+
+// getDefaultIfName is the default interface function for unsupported platforms.
+func getDefaultIfName() (string, error) {
+ return "", errors.New("No default interface found (unsupported platform)")
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go
new file mode 100644
index 0000000..b33e4c0
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/route_info_linux.go
@@ -0,0 +1,37 @@
+package sockaddr
+
+import (
+ "errors"
+ "os/exec"
+)
+
+var cmds map[string][]string = map[string][]string{
+ "ip": {"/sbin/ip", "route"},
+}
+
+type routeInfo struct {
+ cmds map[string][]string
+}
+
+// NewRouteInfo returns a Linux-specific implementation of the RouteInfo
+// interface.
+func NewRouteInfo() (routeInfo, error) {
+ return routeInfo{
+ cmds: cmds,
+ }, nil
+}
+
+// GetDefaultInterfaceName returns the interface name attached to the default
+// route on the default interface.
+func (ri routeInfo) GetDefaultInterfaceName() (string, error) {
+ out, err := exec.Command(cmds["ip"][0], cmds["ip"][1:]...).Output()
+ if err != nil {
+ return "", err
+ }
+
+ var ifName string
+ if ifName, err = parseDefaultIfNameFromIPCmd(string(out)); err != nil {
+ return "", errors.New("No default interface found")
+ }
+ return ifName, nil
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go
new file mode 100644
index 0000000..ee8e798
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/route_info_solaris.go
@@ -0,0 +1,37 @@
+package sockaddr
+
+import (
+ "errors"
+ "os/exec"
+)
+
+var cmds map[string][]string = map[string][]string{
+ "route": {"/usr/sbin/route", "-n", "get", "default"},
+}
+
+type routeInfo struct {
+ cmds map[string][]string
+}
+
+// NewRouteInfo returns a BSD-specific implementation of the RouteInfo
+// interface.
+func NewRouteInfo() (routeInfo, error) {
+ return routeInfo{
+ cmds: cmds,
+ }, nil
+}
+
+// GetDefaultInterfaceName returns the interface name attached to the default
+// route on the default interface.
+func (ri routeInfo) GetDefaultInterfaceName() (string, error) {
+ out, err := exec.Command(cmds["route"][0], cmds["route"][1:]...).Output()
+ if err != nil {
+ return "", err
+ }
+
+ var ifName string
+ if ifName, err = parseDefaultIfNameFromRoute(string(out)); err != nil {
+ return "", errors.New("No default interface found")
+ }
+ return ifName, nil
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go b/vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go
new file mode 100644
index 0000000..3da9728
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/route_info_windows.go
@@ -0,0 +1,41 @@
+package sockaddr
+
+import "os/exec"
+
+var cmds map[string][]string = map[string][]string{
+ "netstat": {"netstat", "-rn"},
+ "ipconfig": {"ipconfig"},
+}
+
+type routeInfo struct {
+ cmds map[string][]string
+}
+
+// NewRouteInfo returns a BSD-specific implementation of the RouteInfo
+// interface.
+func NewRouteInfo() (routeInfo, error) {
+ return routeInfo{
+ cmds: cmds,
+ }, nil
+}
+
+// GetDefaultInterfaceName returns the interface name attached to the default
+// route on the default interface.
+func (ri routeInfo) GetDefaultInterfaceName() (string, error) {
+ ifNameOut, err := exec.Command(cmds["netstat"][0], cmds["netstat"][1:]...).Output()
+ if err != nil {
+ return "", err
+ }
+
+ ipconfigOut, err := exec.Command(cmds["ipconfig"][0], cmds["ipconfig"][1:]...).Output()
+ if err != nil {
+ return "", err
+ }
+
+ ifName, err := parseDefaultIfNameWindows(string(ifNameOut), string(ipconfigOut))
+ if err != nil {
+ return "", err
+ }
+
+ return ifName, nil
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/sockaddr.go b/vendor/github.com/hashicorp/go-sockaddr/sockaddr.go
new file mode 100644
index 0000000..51389eb
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/sockaddr.go
@@ -0,0 +1,178 @@
+package sockaddr
+
+import (
+ "fmt"
+ "strings"
+)
+
+type SockAddrType int
+type AttrName string
+
+const (
+ TypeUnknown SockAddrType = 0x0
+ TypeUnix = 0x1
+ TypeIPv4 = 0x2
+ TypeIPv6 = 0x4
+
+ // TypeIP is the union of TypeIPv4 and TypeIPv6
+ TypeIP = 0x6
+)
+
+type SockAddr interface {
+ // CmpRFC returns 0 if SockAddr exactly matches one of the matched RFC
+ // networks, -1 if the receiver is contained within the RFC network, or
+ // 1 if the address is not contained within the RFC.
+ CmpRFC(rfcNum uint, sa SockAddr) int
+
+ // Contains returns true if the SockAddr arg is contained within the
+ // receiver
+ Contains(SockAddr) bool
+
+ // Equal allows for the comparison of two SockAddrs
+ Equal(SockAddr) bool
+
+ DialPacketArgs() (string, string)
+ DialStreamArgs() (string, string)
+ ListenPacketArgs() (string, string)
+ ListenStreamArgs() (string, string)
+
+ // String returns the string representation of SockAddr
+ String() string
+
+ // Type returns the SockAddrType
+ Type() SockAddrType
+}
+
+// sockAddrAttrMap is a map of the SockAddr type-specific attributes.
+var sockAddrAttrMap map[AttrName]func(SockAddr) string
+var sockAddrAttrs []AttrName
+
+func init() {
+ sockAddrInit()
+}
+
+// New creates a new SockAddr from the string. The order in which New()
+// attempts to construct a SockAddr is: IPv4Addr, IPv6Addr, SockAddrUnix.
+//
+// NOTE: New() relies on the heuristic wherein if the path begins with either a
+// '.' or '/' character before creating a new UnixSock. For UNIX sockets that
+// are absolute paths or are nested within a sub-directory, this works as
+// expected, however if the UNIX socket is contained in the current working
+// directory, this will fail unless the path begins with "./"
+// (e.g. "./my-local-socket"). Calls directly to NewUnixSock() do not suffer
+// this limitation. Invalid IP addresses such as "256.0.0.0/-1" will run afoul
+// of this heuristic and be assumed to be a valid UNIX socket path (which they
+// are, but it is probably not what you want and you won't realize it until you
+// stat(2) the file system to discover it doesn't exist).
+func NewSockAddr(s string) (SockAddr, error) {
+ ipv4Addr, err := NewIPv4Addr(s)
+ if err == nil {
+ return ipv4Addr, nil
+ }
+
+ ipv6Addr, err := NewIPv6Addr(s)
+ if err == nil {
+ return ipv6Addr, nil
+ }
+
+ // Check to make sure the string begins with either a '.' or '/', or
+ // contains a '/'.
+ if len(s) > 1 && (strings.IndexAny(s[0:1], "./") != -1 || strings.IndexByte(s, '/') != -1) {
+ unixSock, err := NewUnixSock(s)
+ if err == nil {
+ return unixSock, nil
+ }
+ }
+
+ return nil, fmt.Errorf("Unable to convert %q to an IPv4 or IPv6 address, or a UNIX Socket", s)
+}
+
+// ToIPAddr returns an IPAddr type or nil if the type conversion fails.
+func ToIPAddr(sa SockAddr) *IPAddr {
+ ipa, ok := sa.(IPAddr)
+ if !ok {
+ return nil
+ }
+ return &ipa
+}
+
+// ToIPv4Addr returns an IPv4Addr type or nil if the type conversion fails.
+func ToIPv4Addr(sa SockAddr) *IPv4Addr {
+ switch v := sa.(type) {
+ case IPv4Addr:
+ return &v
+ default:
+ return nil
+ }
+}
+
+// ToIPv6Addr returns an IPv6Addr type or nil if the type conversion fails.
+func ToIPv6Addr(sa SockAddr) *IPv6Addr {
+ switch v := sa.(type) {
+ case IPv6Addr:
+ return &v
+ default:
+ return nil
+ }
+}
+
+// ToUnixSock returns a UnixSock type or nil if the type conversion fails.
+func ToUnixSock(sa SockAddr) *UnixSock {
+ switch v := sa.(type) {
+ case UnixSock:
+ return &v
+ default:
+ return nil
+ }
+}
+
+// SockAddrAttr returns a string representation of an attribute for the given
+// SockAddr.
+func SockAddrAttr(sa SockAddr, selector AttrName) string {
+ fn, found := sockAddrAttrMap[selector]
+ if !found {
+ return ""
+ }
+
+ return fn(sa)
+}
+
+// String() for SockAddrType returns a string representation of the
+// SockAddrType (e.g. "IPv4", "IPv6", "UNIX", "IP", or "unknown").
+func (sat SockAddrType) String() string {
+ switch sat {
+ case TypeIPv4:
+ return "IPv4"
+ case TypeIPv6:
+ return "IPv6"
+ // There is no concrete "IP" type. Leaving here as a reminder.
+ // case TypeIP:
+ // return "IP"
+ case TypeUnix:
+ return "UNIX"
+ default:
+ panic("unsupported type")
+ }
+}
+
+// sockAddrInit is called once at init()
+func sockAddrInit() {
+ sockAddrAttrs = []AttrName{
+ "type", // type should be first
+ "string",
+ }
+
+ sockAddrAttrMap = map[AttrName]func(sa SockAddr) string{
+ "string": func(sa SockAddr) string {
+ return sa.String()
+ },
+ "type": func(sa SockAddr) string {
+ return sa.Type().String()
+ },
+ }
+}
+
+// UnixSockAttrs returns a list of attributes supported by the UnixSock type
+func SockAddrAttrs() []AttrName {
+ return sockAddrAttrs
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go b/vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go
new file mode 100644
index 0000000..75fbffb
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/sockaddrs.go
@@ -0,0 +1,193 @@
+package sockaddr
+
+import (
+ "bytes"
+ "sort"
+)
+
+// SockAddrs is a slice of SockAddrs
+type SockAddrs []SockAddr
+
+func (s SockAddrs) Len() int { return len(s) }
+func (s SockAddrs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+// CmpAddrFunc is the function signature that must be met to be used in the
+// OrderedAddrBy multiAddrSorter
+type CmpAddrFunc func(p1, p2 *SockAddr) int
+
+// multiAddrSorter implements the Sort interface, sorting the SockAddrs within.
+type multiAddrSorter struct {
+ addrs SockAddrs
+ cmp []CmpAddrFunc
+}
+
+// Sort sorts the argument slice according to the Cmp functions passed to
+// OrderedAddrBy.
+func (ms *multiAddrSorter) Sort(sockAddrs SockAddrs) {
+ ms.addrs = sockAddrs
+ sort.Sort(ms)
+}
+
+// OrderedAddrBy sorts SockAddr by the list of sort function pointers.
+func OrderedAddrBy(cmpFuncs ...CmpAddrFunc) *multiAddrSorter {
+ return &multiAddrSorter{
+ cmp: cmpFuncs,
+ }
+}
+
+// Len is part of sort.Interface.
+func (ms *multiAddrSorter) Len() int {
+ return len(ms.addrs)
+}
+
+// Less is part of sort.Interface. It is implemented by looping along the
+// Cmp() functions until it finds a comparison that is either less than,
+// equal to, or greater than.
+func (ms *multiAddrSorter) Less(i, j int) bool {
+ p, q := &ms.addrs[i], &ms.addrs[j]
+ // Try all but the last comparison.
+ var k int
+ for k = 0; k < len(ms.cmp)-1; k++ {
+ cmp := ms.cmp[k]
+ x := cmp(p, q)
+ switch x {
+ case -1:
+ // p < q, so we have a decision.
+ return true
+ case 1:
+ // p > q, so we have a decision.
+ return false
+ }
+ // p == q; try the next comparison.
+ }
+ // All comparisons to here said "equal", so just return whatever the
+ // final comparison reports.
+ switch ms.cmp[k](p, q) {
+ case -1:
+ return true
+ case 1:
+ return false
+ default:
+ // Still a tie! Now what?
+ return false
+ }
+}
+
+// Swap is part of sort.Interface.
+func (ms *multiAddrSorter) Swap(i, j int) {
+ ms.addrs[i], ms.addrs[j] = ms.addrs[j], ms.addrs[i]
+}
+
+const (
+ // NOTE (sean@): These constants are here for code readability only and
+ // are sprucing up the code for readability purposes. Some of the
+ // Cmp*() variants have confusing logic (especially when dealing with
+ // mixed-type comparisons) and this, I think, has made it easier to grok
+ // the code faster.
+ sortReceiverBeforeArg = -1
+ sortDeferDecision = 0
+ sortArgBeforeReceiver = 1
+)
+
+// AscAddress is a sorting function to sort SockAddrs by their respective
+// address type. Non-equal types are deferred in the sort.
+func AscAddress(p1Ptr, p2Ptr *SockAddr) int {
+ p1 := *p1Ptr
+ p2 := *p2Ptr
+
+ switch v := p1.(type) {
+ case IPv4Addr:
+ return v.CmpAddress(p2)
+ case IPv6Addr:
+ return v.CmpAddress(p2)
+ case UnixSock:
+ return v.CmpAddress(p2)
+ default:
+ return sortDeferDecision
+ }
+}
+
+// AscPort is a sorting function to sort SockAddrs by their respective address
+// type. Non-equal types are deferred in the sort.
+func AscPort(p1Ptr, p2Ptr *SockAddr) int {
+ p1 := *p1Ptr
+ p2 := *p2Ptr
+
+ switch v := p1.(type) {
+ case IPv4Addr:
+ return v.CmpPort(p2)
+ case IPv6Addr:
+ return v.CmpPort(p2)
+ default:
+ return sortDeferDecision
+ }
+}
+
+// AscPrivate is a sorting function to sort "more secure" private values before
+// "more public" values. Both IPv4 and IPv6 are compared against RFC6890
+// (RFC6890 includes, and is not limited to, RFC1918 and RFC6598 for IPv4, and
+// IPv6 includes RFC4193).
+func AscPrivate(p1Ptr, p2Ptr *SockAddr) int {
+ p1 := *p1Ptr
+ p2 := *p2Ptr
+
+ switch v := p1.(type) {
+ case IPv4Addr, IPv6Addr:
+ return v.CmpRFC(6890, p2)
+ default:
+ return sortDeferDecision
+ }
+}
+
+// AscNetworkSize is a sorting function to sort SockAddrs based on their network
+// size. Non-equal types are deferred in the sort.
+func AscNetworkSize(p1Ptr, p2Ptr *SockAddr) int {
+ p1 := *p1Ptr
+ p2 := *p2Ptr
+ p1Type := p1.Type()
+ p2Type := p2.Type()
+
+ // Network size operations on non-IP types make no sense
+ if p1Type != p2Type && p1Type != TypeIP {
+ return sortDeferDecision
+ }
+
+ ipA := p1.(IPAddr)
+ ipB := p2.(IPAddr)
+
+ return bytes.Compare([]byte(*ipA.NetIPMask()), []byte(*ipB.NetIPMask()))
+}
+
+// AscType is a sorting function to sort "more secure" types before
+// "less-secure" types.
+func AscType(p1Ptr, p2Ptr *SockAddr) int {
+ p1 := *p1Ptr
+ p2 := *p2Ptr
+ p1Type := p1.Type()
+ p2Type := p2.Type()
+ switch {
+ case p1Type < p2Type:
+ return sortReceiverBeforeArg
+ case p1Type == p2Type:
+ return sortDeferDecision
+ case p1Type > p2Type:
+ return sortArgBeforeReceiver
+ default:
+ return sortDeferDecision
+ }
+}
+
+// FilterByType returns two lists: a list of matched and unmatched SockAddrs
+func (sas SockAddrs) FilterByType(type_ SockAddrType) (matched, excluded SockAddrs) {
+ matched = make(SockAddrs, 0, len(sas))
+ excluded = make(SockAddrs, 0, len(sas))
+
+ for _, sa := range sas {
+ if sa.Type()&type_ != 0 {
+ matched = append(matched, sa)
+ } else {
+ excluded = append(excluded, sa)
+ }
+ }
+ return matched, excluded
+}
diff --git a/vendor/github.com/hashicorp/go-sockaddr/unixsock.go b/vendor/github.com/hashicorp/go-sockaddr/unixsock.go
new file mode 100644
index 0000000..f3be3f6
--- /dev/null
+++ b/vendor/github.com/hashicorp/go-sockaddr/unixsock.go
@@ -0,0 +1,135 @@
+package sockaddr
+
+import (
+ "fmt"
+ "strings"
+)
+
+type UnixSock struct {
+ SockAddr
+ path string
+}
+type UnixSocks []*UnixSock
+
+// unixAttrMap is a map of the UnixSockAddr type-specific attributes.
+var unixAttrMap map[AttrName]func(UnixSock) string
+var unixAttrs []AttrName
+
+func init() {
+ unixAttrInit()
+}
+
+// NewUnixSock creates an UnixSock from a string path. String can be in the
+// form of either URI-based string (e.g. `file:///etc/passwd`), an absolute
+// path (e.g. `/etc/passwd`), or a relative path (e.g. `./foo`).
+func NewUnixSock(s string) (ret UnixSock, err error) {
+ ret.path = s
+ return ret, nil
+}
+
+// CmpAddress follows the Cmp() standard protocol and returns:
+//
+// - -1 If the receiver should sort first because its name lexically sorts before arg
+// - 0 if the SockAddr arg is not a UnixSock, or is a UnixSock with the same path.
+// - 1 If the argument should sort first.
+func (us UnixSock) CmpAddress(sa SockAddr) int {
+ usb, ok := sa.(UnixSock)
+ if !ok {
+ return sortDeferDecision
+ }
+
+ return strings.Compare(us.Path(), usb.Path())
+}
+
+// DialPacketArgs returns the arguments required to be passed to net.DialUnix()
+// with the `unixgram` network type.
+func (us UnixSock) DialPacketArgs() (network, dialArgs string) {
+ return "unixgram", us.path
+}
+
+// DialStreamArgs returns the arguments required to be passed to net.DialUnix()
+// with the `unix` network type.
+func (us UnixSock) DialStreamArgs() (network, dialArgs string) {
+ return "unix", us.path
+}
+
+// Equal returns true if a SockAddr is equal to the receiving UnixSock.
+func (us UnixSock) Equal(sa SockAddr) bool {
+ usb, ok := sa.(UnixSock)
+ if !ok {
+ return false
+ }
+
+ if us.Path() != usb.Path() {
+ return false
+ }
+
+ return true
+}
+
+// ListenPacketArgs returns the arguments required to be passed to
+// net.ListenUnixgram() with the `unixgram` network type.
+func (us UnixSock) ListenPacketArgs() (network, dialArgs string) {
+ return "unixgram", us.path
+}
+
+// ListenStreamArgs returns the arguments required to be passed to
+// net.ListenUnix() with the `unix` network type.
+func (us UnixSock) ListenStreamArgs() (network, dialArgs string) {
+ return "unix", us.path
+}
+
+// MustUnixSock is a helper method that must return an UnixSock or panic on
+// invalid input.
+func MustUnixSock(addr string) UnixSock {
+ us, err := NewUnixSock(addr)
+ if err != nil {
+ panic(fmt.Sprintf("Unable to create a UnixSock from %+q: %v", addr, err))
+ }
+ return us
+}
+
+// Path returns the given path of the UnixSock
+func (us UnixSock) Path() string {
+ return us.path
+}
+
+// String returns the path of the UnixSock
+func (us UnixSock) String() string {
+ return fmt.Sprintf("%+q", us.path)
+}
+
+// Type is used as a type switch and returns TypeUnix
+func (UnixSock) Type() SockAddrType {
+ return TypeUnix
+}
+
+// UnixSockAttrs returns a list of attributes supported by the UnixSockAddr type
+func UnixSockAttrs() []AttrName {
+ return unixAttrs
+}
+
+// UnixSockAttr returns a string representation of an attribute for the given
+// UnixSock.
+func UnixSockAttr(us UnixSock, attrName AttrName) string {
+ fn, found := unixAttrMap[attrName]
+ if !found {
+ return ""
+ }
+
+ return fn(us)
+}
+
+// unixAttrInit is called once at init()
+func unixAttrInit() {
+ // Sorted for human readability
+ unixAttrs = []AttrName{
+ "path",
+ }
+
+ unixAttrMap = map[AttrName]func(us UnixSock) string{
+ "path": func(us UnixSock) string {
+ return us.Path()
+ },
+ }
+}
diff --git a/vendor/github.com/hashicorp/golang-lru/LICENSE b/vendor/github.com/hashicorp/golang-lru/LICENSE
new file mode 100644
index 0000000..be2cc4d
--- /dev/null
+++ b/vendor/github.com/hashicorp/golang-lru/LICENSE
@@ -0,0 +1,362 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. "Contributor"
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the terms of
+ a Secondary License.
+
+1.6. "Executable Form"
+
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+
+ means a work that combines Covered Software with other material, in a
+ separate file or files, that is not Covered Software.
+
+1.8. "License"
+
+ means this document.
+
+1.9. "Licensable"
+
+ means having the right to grant, to the maximum extent possible, whether
+ at the time of the initial grant or subsequently, any and all of the
+ rights conveyed by this License.
+
+1.10. "Modifications"
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. "Patent Claims" of a Contributor
+
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the License,
+ by the making, using, selling, offering for sale, having made, import,
+ or transfer of either its Contributions or its Contributor Version.
+
+1.12. "Secondary License"
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. "Source Code Form"
+
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, "control" means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution
+ become effective for each Contribution on the date the Contributor first
+ distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under
+ this License. No additional rights or licenses will be implied from the
+ distribution or licensing of Covered Software under this License.
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
+ Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+ This License does not grant any rights in the trademarks, service marks,
+ or logos of any Contributor (except as may be necessary to comply with
+ the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this
+ License (see Section 10.2) or under the terms of a Secondary License (if
+ permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its
+ Contributions are its original creation(s) or it has sufficient rights to
+ grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under
+ applicable copyright doctrines of fair use, fair dealing, or other
+ equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under
+ the terms of this License. You must inform recipients that the Source
+ Code Form of the Covered Software is governed by the terms of this
+ License, and how they can obtain a copy of this License. You may not
+ attempt to alter or restrict the recipients' rights in the Source Code
+ Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter the
+ recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for
+ the Covered Software. If the Larger Work is a combination of Covered
+ Software with a work governed by one or more Secondary Licenses, and the
+ Covered Software is not Incompatible With Secondary Licenses, this
+ License permits You to additionally distribute such Covered Software
+ under the terms of such Secondary License(s), so that the recipient of
+ the Larger Work may, at their option, further distribute the Covered
+ Software under the terms of either this License or such Secondary
+ License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices
+ (including copyright notices, patent notices, disclaimers of warranty, or
+ limitations of liability) contained within the Source Code Form of the
+ Covered Software, except that You may alter any license notices to the
+ extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on
+ behalf of any Contributor. You must make it absolutely clear that any
+ such warranty, support, indemnity, or liability obligation is offered by
+ You alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute,
+ judicial order, or regulation then You must: (a) comply with the terms of
+ this License to the maximum extent possible; and (b) describe the
+ limitations and the code they affect. Such description must be placed in a
+ text file included with all distributions of the Covered Software under
+ this License. Except to the extent prohibited by statute or regulation,
+ such description must be sufficiently detailed for a recipient of ordinary
+ skill to be able to understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing
+ basis, if such Contributor fails to notify You of the non-compliance by
+ some reasonable means prior to 60 days after You have come back into
+ compliance. Moreover, Your grants from a particular Contributor are
+ reinstated on an ongoing basis if such Contributor notifies You of the
+ non-compliance by some reasonable means, this is the first time You have
+ received notice of non-compliance with this License from such
+ Contributor, and You become compliant prior to 30 days after Your receipt
+ of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions,
+ counter-claims, and cross-claims) alleging that a Contributor Version
+ directly or indirectly infringes any patent, then the rights granted to
+ You by any and all Contributors for the Covered Software under Section
+ 2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an "as is" basis,
+ without warranty of any kind, either expressed, implied, or statutory,
+ including, without limitation, warranties that the Covered Software is free
+ of defects, merchantable, fit for a particular purpose or non-infringing.
+ The entire risk as to the quality and performance of the Covered Software
+ is with You. Should any Covered Software prove defective in any respect,
+ You (not any Contributor) assume the cost of any necessary servicing,
+ repair, or correction. This disclaimer of warranty constitutes an essential
+ part of this License. No use of any Covered Software is authorized under
+ this License except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from
+ such party's negligence to the extent applicable law prohibits such
+ limitation. Some jurisdictions do not allow the exclusion or limitation of
+ incidental or consequential damages, so this exclusion and limitation may
+ not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts
+ of a jurisdiction where the defendant maintains its principal place of
+ business and such litigation shall be governed by laws of that
+ jurisdiction, without reference to its conflict-of-law provisions. Nothing
+ in this Section shall prevent a party's ability to bring cross-claims or
+ counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject
+ matter hereof. If any provision of this License is held to be
+ unenforceable, such provision shall be reformed only to the extent
+ necessary to make it enforceable. Any law or regulation which provides that
+ the language of a contract shall be construed against the drafter shall not
+ be used to construe this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version
+ of the License under which You originally received the Covered Software,
+ or under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a
+ modified version of this License if you rename the license and remove
+ any references to the name of the license steward (except to note that
+ such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+ Licenses If You choose to distribute Source Code Form that is
+ Incompatible With Secondary Licenses under the terms of this version of
+ the License, the notice described in Exhibit B of this License must be
+ attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file,
+then You may include the notice in a location (such as a LICENSE file in a
+relevant directory) where a recipient would be likely to look for such a
+notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+
+ This Source Code Form is "Incompatible
+ With Secondary Licenses", as defined by
+ the Mozilla Public License, v. 2.0.
diff --git a/vendor/github.com/hashicorp/golang-lru/README.md b/vendor/github.com/hashicorp/golang-lru/README.md
new file mode 100644
index 0000000..33e58cf
--- /dev/null
+++ b/vendor/github.com/hashicorp/golang-lru/README.md
@@ -0,0 +1,25 @@
+golang-lru
+==========
+
+This provides the `lru` package which implements a fixed-size
+thread safe LRU cache. It is based on the cache in Groupcache.
+
+Documentation
+=============
+
+Full docs are available on [Godoc](http://godoc.org/github.com/hashicorp/golang-lru)
+
+Example
+=======
+
+Using the LRU is very simple:
+
+```go
+l, _ := New(128)
+for i := 0; i < 256; i++ {
+ l.Add(i, nil)
+}
+if l.Len() != 128 {
+ panic(fmt.Sprintf("bad len: %v", l.Len()))
+}
+```
diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go
new file mode 100644
index 0000000..68d097a
--- /dev/null
+++ b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go
@@ -0,0 +1,160 @@
+package simplelru
+
+import (
+ "container/list"
+ "errors"
+)
+
+// EvictCallback is used to get a callback when a cache entry is evicted
+type EvictCallback func(key interface{}, value interface{})
+
+// LRU implements a non-thread safe fixed size LRU cache
+type LRU struct {
+ size int
+ evictList *list.List
+ items map[interface{}]*list.Element
+ onEvict EvictCallback
+}
+
+// entry is used to hold a value in the evictList
+type entry struct {
+ key interface{}
+ value interface{}
+}
+
+// NewLRU constructs an LRU of the given size
+func NewLRU(size int, onEvict EvictCallback) (*LRU, error) {
+ if size <= 0 {
+ return nil, errors.New("Must provide a positive size")
+ }
+ c := &LRU{
+ size: size,
+ evictList: list.New(),
+ items: make(map[interface{}]*list.Element),
+ onEvict: onEvict,
+ }
+ return c, nil
+}
+
+// Purge is used to completely clear the cache
+func (c *LRU) Purge() {
+ for k, v := range c.items {
+ if c.onEvict != nil {
+ c.onEvict(k, v.Value.(*entry).value)
+ }
+ delete(c.items, k)
+ }
+ c.evictList.Init()
+}
+
+// Add adds a value to the cache. Returns true if an eviction occured.
+func (c *LRU) Add(key, value interface{}) bool {
+ // Check for existing item
+ if ent, ok := c.items[key]; ok {
+ c.evictList.MoveToFront(ent)
+ ent.Value.(*entry).value = value
+ return false
+ }
+
+ // Add new item
+ ent := &entry{key, value}
+ entry := c.evictList.PushFront(ent)
+ c.items[key] = entry
+
+ evict := c.evictList.Len() > c.size
+ // Verify size not exceeded
+ if evict {
+ c.removeOldest()
+ }
+ return evict
+}
+
+// Get looks up a key's value from the cache.
+func (c *LRU) Get(key interface{}) (value interface{}, ok bool) {
+ if ent, ok := c.items[key]; ok {
+ c.evictList.MoveToFront(ent)
+ return ent.Value.(*entry).value, true
+ }
+ return
+}
+
+// Check if a key is in the cache, without updating the recent-ness
+// or deleting it for being stale.
+func (c *LRU) Contains(key interface{}) (ok bool) {
+ _, ok = c.items[key]
+ return ok
+}
+
+// Returns the key value (or undefined if not found) without updating
+// the "recently used"-ness of the key.
+func (c *LRU) Peek(key interface{}) (value interface{}, ok bool) {
+ if ent, ok := c.items[key]; ok {
+ return ent.Value.(*entry).value, true
+ }
+ return nil, ok
+}
+
+// Remove removes the provided key from the cache, returning if the
+// key was contained.
+func (c *LRU) Remove(key interface{}) bool {
+ if ent, ok := c.items[key]; ok {
+ c.removeElement(ent)
+ return true
+ }
+ return false
+}
+
+// RemoveOldest removes the oldest item from the cache.
+func (c *LRU) RemoveOldest() (interface{}, interface{}, bool) {
+ ent := c.evictList.Back()
+ if ent != nil {
+ c.removeElement(ent)
+ kv := ent.Value.(*entry)
+ return kv.key, kv.value, true
+ }
+ return nil, nil, false
+}
+
+// GetOldest returns the oldest entry
+func (c *LRU) GetOldest() (interface{}, interface{}, bool) {
+ ent := c.evictList.Back()
+ if ent != nil {
+ kv := ent.Value.(*entry)
+ return kv.key, kv.value, true
+ }
+ return nil, nil, false
+}
+
+// Keys returns a slice of the keys in the cache, from oldest to newest.
+func (c *LRU) Keys() []interface{} {
+ keys := make([]interface{}, len(c.items))
+ i := 0
+ for ent := c.evictList.Back(); ent != nil; ent = ent.Prev() {
+ keys[i] = ent.Value.(*entry).key
+ i++
+ }
+ return keys
+}
+
+// Len returns the number of items in the cache.
+func (c *LRU) Len() int {
+ return c.evictList.Len()
+}
+
+// removeOldest removes the oldest item from the cache.
+func (c *LRU) removeOldest() {
+ ent := c.evictList.Back()
+ if ent != nil {
+ c.removeElement(ent)
+ }
+}
+
+// removeElement is used to remove a given list element from the cache
+func (c *LRU) removeElement(e *list.Element) {
+ c.evictList.Remove(e)
+ kv := e.Value.(*entry)
+ delete(c.items, kv.key)
+ if c.onEvict != nil {
+ c.onEvict(kv.key, kv.value)
+ }
+}
diff --git a/vendor/github.com/hashicorp/memberlist/LICENSE b/vendor/github.com/hashicorp/memberlist/LICENSE
new file mode 100644
index 0000000..c33dcc7
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/LICENSE
@@ -0,0 +1,354 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. “Contributor”
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. “Contributor Version”
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor’s Contribution.
+
+1.3. “Contribution”
+
+ means Covered Software of a particular Contributor.
+
+1.4. “Covered Software”
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. “Incompatible With Secondary Licenses”
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of version
+ 1.1 or earlier of the License, but not also under the terms of a
+ Secondary License.
+
+1.6. “Executable Form”
+
+ means any form of the work other than Source Code Form.
+
+1.7. “Larger Work”
+
+ means a work that combines Covered Software with other material, in a separate
+ file or files, that is not Covered Software.
+
+1.8. “License”
+
+ means this document.
+
+1.9. “Licensable”
+
+ means having the right to grant, to the maximum extent possible, whether at the
+ time of the initial grant or subsequently, any and all of the rights conveyed by
+ this License.
+
+1.10. “Modifications”
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to, deletion
+ from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. “Patent Claims” of a Contributor
+
+ means any patent claim(s), including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by such Contributor that
+ would be infringed, but for the grant of the License, by the making,
+ using, selling, offering for sale, having made, import, or transfer of
+ either its Contributions or its Contributor Version.
+
+1.12. “Secondary License”
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. “Source Code Form”
+
+ means the form of the work preferred for making modifications.
+
+1.14. “You” (or “Your”)
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, “You” includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, “control” means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or as
+ part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its Contributions
+ or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution become
+ effective for each Contribution on the date the Contributor first distributes
+ such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under this
+ License. No additional rights or licenses will be implied from the distribution
+ or licensing of Covered Software under this License. Notwithstanding Section
+ 2.1(b) above, no patent license is granted by a Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party’s
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of its
+ Contributions.
+
+ This License does not grant any rights in the trademarks, service marks, or
+ logos of any Contributor (except as may be necessary to comply with the
+ notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this License
+ (see Section 10.2) or under the terms of a Secondary License (if permitted
+ under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its Contributions
+ are its original creation(s) or it has sufficient rights to grant the
+ rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under applicable
+ copyright doctrines of fair use, fair dealing, or other equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under the
+ terms of this License. You must inform recipients that the Source Code Form
+ of the Covered Software is governed by the terms of this License, and how
+ they can obtain a copy of this License. You may not attempt to alter or
+ restrict the recipients’ rights in the Source Code Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this License,
+ or sublicense it under different terms, provided that the license for
+ the Executable Form does not attempt to limit or alter the recipients’
+ rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for the
+ Covered Software. If the Larger Work is a combination of Covered Software
+ with a work governed by one or more Secondary Licenses, and the Covered
+ Software is not Incompatible With Secondary Licenses, this License permits
+ You to additionally distribute such Covered Software under the terms of
+ such Secondary License(s), so that the recipient of the Larger Work may, at
+ their option, further distribute the Covered Software under the terms of
+ either this License or such Secondary License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices (including
+ copyright notices, patent notices, disclaimers of warranty, or limitations
+ of liability) contained within the Source Code Form of the Covered
+ Software, except that You may alter any license notices to the extent
+ required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on behalf
+ of any Contributor. You must make it absolutely clear that any such
+ warranty, support, indemnity, or liability obligation is offered by You
+ alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute, judicial
+ order, or regulation then You must: (a) comply with the terms of this License
+ to the maximum extent possible; and (b) describe the limitations and the code
+ they affect. Such description must be placed in a text file included with all
+ distributions of the Covered Software under this License. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing basis,
+ if such Contributor fails to notify You of the non-compliance by some
+ reasonable means prior to 60 days after You have come back into compliance.
+ Moreover, Your grants from a particular Contributor are reinstated on an
+ ongoing basis if such Contributor notifies You of the non-compliance by
+ some reasonable means, this is the first time You have received notice of
+ non-compliance with this License from such Contributor, and You become
+ compliant prior to 30 days after Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions, counter-claims,
+ and cross-claims) alleging that a Contributor Version directly or
+ indirectly infringes any patent, then the rights granted to You by any and
+ all Contributors for the Covered Software under Section 2.1 of this License
+ shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an “as is” basis, without
+ warranty of any kind, either expressed, implied, or statutory, including,
+ without limitation, warranties that the Covered Software is free of defects,
+ merchantable, fit for a particular purpose or non-infringing. The entire
+ risk as to the quality and performance of the Covered Software is with You.
+ Should any Covered Software prove defective in any respect, You (not any
+ Contributor) assume the cost of any necessary servicing, repair, or
+ correction. This disclaimer of warranty constitutes an essential part of this
+ License. No use of any Covered Software is authorized under this License
+ except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from such
+ party’s negligence to the extent applicable law prohibits such limitation.
+ Some jurisdictions do not allow the exclusion or limitation of incidental or
+ consequential damages, so this exclusion and limitation may not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts of
+ a jurisdiction where the defendant maintains its principal place of business
+ and such litigation shall be governed by laws of that jurisdiction, without
+ reference to its conflict-of-law provisions. Nothing in this Section shall
+ prevent a party’s ability to bring cross-claims or counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject matter
+ hereof. If any provision of this License is held to be unenforceable, such
+ provision shall be reformed only to the extent necessary to make it
+ enforceable. Any law or regulation which provides that the language of a
+ contract shall be construed against the drafter shall not be used to construe
+ this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version of
+ the License under which You originally received the Covered Software, or
+ under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a modified
+ version of this License if you rename the license and remove any
+ references to the name of the license steward (except to note that such
+ modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
+ If You choose to distribute Source Code Form that is Incompatible With
+ Secondary Licenses under the terms of this version of the License, the
+ notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file, then
+You may include the notice in a location (such as a LICENSE file in a relevant
+directory) where a recipient would be likely to look for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - “Incompatible With Secondary Licenses” Notice
+
+ This Source Code Form is “Incompatible
+ With Secondary Licenses”, as defined by
+ the Mozilla Public License, v. 2.0.
+
diff --git a/vendor/github.com/hashicorp/memberlist/README.md b/vendor/github.com/hashicorp/memberlist/README.md
new file mode 100644
index 0000000..fc605a5
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/README.md
@@ -0,0 +1,144 @@
+# memberlist [![GoDoc](https://godoc.org/github.com/hashicorp/memberlist?status.png)](https://godoc.org/github.com/hashicorp/memberlist)
+
+memberlist is a [Go](http://www.golang.org) library that manages cluster
+membership and member failure detection using a gossip based protocol.
+
+The use cases for such a library are far-reaching: all distributed systems
+require membership, and memberlist is a re-usable solution to managing
+cluster membership and node failure detection.
+
+memberlist is eventually consistent but converges quickly on average.
+The speed at which it converges can be heavily tuned via various knobs
+on the protocol. Node failures are detected and network partitions are partially
+tolerated by attempting to communicate to potentially dead nodes through
+multiple routes.
+
+## Building
+
+If you wish to build memberlist you'll need Go version 1.2+ installed.
+
+Please check your installation with:
+
+```
+go version
+```
+
+## Usage
+
+Memberlist is surprisingly simple to use. An example is shown below:
+
+```go
+/* Create the initial memberlist from a safe configuration.
+ Please reference the godoc for other default config types.
+ http://godoc.org/github.com/hashicorp/memberlist#Config
+*/
+list, err := memberlist.Create(memberlist.DefaultLocalConfig())
+if err != nil {
+ panic("Failed to create memberlist: " + err.Error())
+}
+
+// Join an existing cluster by specifying at least one known member.
+n, err := list.Join([]string{"1.2.3.4"})
+if err != nil {
+ panic("Failed to join cluster: " + err.Error())
+}
+
+// Ask for members of the cluster
+for _, member := range list.Members() {
+ fmt.Printf("Member: %s %s\n", member.Name, member.Addr)
+}
+
+// Continue doing whatever you need, memberlist will maintain membership
+// information in the background. Delegates can be used for receiving
+// events when members join or leave.
+```
+
+The most difficult part of memberlist is configuring it since it has many
+available knobs in order to tune state propagation delay and convergence times.
+Memberlist provides a default configuration that offers a good starting point,
+but errs on the side of caution, choosing values that are optimized for
+higher convergence at the cost of higher bandwidth usage.
+
+For complete documentation, see the associated [Godoc](http://godoc.org/github.com/hashicorp/memberlist).
+
+## Protocol
+
+memberlist is based on ["SWIM: Scalable Weakly-consistent Infection-style Process Group Membership Protocol"](http://www.cs.cornell.edu/~asdas/research/dsn02-swim.pdf),
+with a few minor adaptations, mostly to increase propagation speed and
+convergence rate.
+
+A high level overview of the memberlist protocol (based on SWIM) is
+described below, but for details please read the full
+[SWIM paper](http://www.cs.cornell.edu/~asdas/research/dsn02-swim.pdf)
+followed by the memberlist source. We welcome any questions related
+to the protocol on our issue tracker.
+
+### Protocol Description
+
+memberlist begins by joining an existing cluster or starting a new
+cluster. If starting a new cluster, additional nodes are expected to join
+it. New nodes in an existing cluster must be given the address of at
+least one existing member in order to join the cluster. The new member
+does a full state sync with the existing member over TCP and begins gossiping its
+existence to the cluster.
+
+Gossip is done over UDP with a configurable but fixed fanout and interval.
+This ensures that network usage is constant with regards to number of nodes, as opposed to
+exponential growth that can occur with traditional heartbeat mechanisms.
+Complete state exchanges with a random node are done periodically over
+TCP, but much less often than gossip messages. This increases the likelihood
+that the membership list converges properly since the full state is exchanged
+and merged. The interval between full state exchanges is configurable or can
+be disabled entirely.
+
+Failure detection is done by periodic random probing using a configurable interval.
+If the node fails to ack within a reasonable time (typically some multiple
+of RTT), then an indirect probe as well as a direct TCP probe are attempted. An
+indirect probe asks a configurable number of random nodes to probe the same node,
+in case there are network issues causing our own node to fail the probe. The direct
+TCP probe is used to help identify the common situation where networking is
+misconfigured to allow TCP but not UDP. Without the TCP probe, a UDP-isolated node
+would think all other nodes were suspect and could cause churn in the cluster when
+it attempts a TCP-based state exchange with another node. It is not desirable to
+operate with only TCP connectivity because convergence will be much slower, but it
+is enabled so that memberlist can detect this situation and alert operators.
+
+If both our probe, the indirect probes, and the direct TCP probe fail within a
+configurable time, then the node is marked "suspicious" and this knowledge is
+gossiped to the cluster. A suspicious node is still considered a member of
+cluster. If the suspect member of the cluster does not dispute the suspicion
+within a configurable period of time, the node is finally considered dead,
+and this state is then gossiped to the cluster.
+
+This is a brief and incomplete description of the protocol. For a better idea,
+please read the
+[SWIM paper](http://www.cs.cornell.edu/~asdas/research/dsn02-swim.pdf)
+in its entirety, along with the memberlist source code.
+
+### Changes from SWIM
+
+As mentioned earlier, the memberlist protocol is based on SWIM but includes
+minor changes, mostly to increase propagation speed and convergence rates.
+
+The changes from SWIM are noted here:
+
+* memberlist does a full state sync over TCP periodically. SWIM only propagates
+ changes over gossip. While both eventually reach convergence, the full state
+ sync increases the likelihood that nodes are fully converged more quickly,
+ at the expense of more bandwidth usage. This feature can be totally disabled
+ if you wish.
+
+* memberlist has a dedicated gossip layer separate from the failure detection
+ protocol. SWIM only piggybacks gossip messages on top of probe/ack messages.
+ memberlist also piggybacks gossip messages on top of probe/ack messages, but
+ also will periodically send out dedicated gossip messages on their own. This
+ feature lets you have a higher gossip rate (for example once per 200ms)
+ and a slower failure detection rate (such as once per second), resulting
+ in overall faster convergence rates and data propagation speeds. This feature
+ can be totally disabed as well, if you wish.
+
+* memberlist stores around the state of dead nodes for a set amount of time,
+ so that when full syncs are requested, the requester also receives information
+ about dead nodes. Because SWIM doesn't do full syncs, SWIM deletes dead node
+ state immediately upon learning that the node is dead. This change again helps
+ the cluster converge more quickly.
diff --git a/vendor/github.com/hashicorp/memberlist/alive_delegate.go b/vendor/github.com/hashicorp/memberlist/alive_delegate.go
new file mode 100644
index 0000000..51a0ba9
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/alive_delegate.go
@@ -0,0 +1,14 @@
+package memberlist
+
+// AliveDelegate is used to involve a client in processing
+// a node "alive" message. When a node joins, either through
+// a UDP gossip or TCP push/pull, we update the state of
+// that node via an alive message. This can be used to filter
+// a node out and prevent it from being considered a peer
+// using application specific logic.
+type AliveDelegate interface {
+ // NotifyMerge is invoked when a merge could take place.
+ // Provides a list of the nodes known by the peer. If
+ // the return value is non-nil, the merge is canceled.
+ NotifyAlive(peer *Node) error
+}
diff --git a/vendor/github.com/hashicorp/memberlist/awareness.go b/vendor/github.com/hashicorp/memberlist/awareness.go
new file mode 100644
index 0000000..ea95c75
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/awareness.go
@@ -0,0 +1,69 @@
+package memberlist
+
+import (
+ "sync"
+ "time"
+
+ "github.com/armon/go-metrics"
+)
+
+// awareness manages a simple metric for tracking the estimated health of the
+// local node. Health is primary the node's ability to respond in the soft
+// real-time manner required for correct health checking of other nodes in the
+// cluster.
+type awareness struct {
+ sync.RWMutex
+
+ // max is the upper threshold for the timeout scale (the score will be
+ // constrained to be from 0 <= score < max).
+ max int
+
+ // score is the current awareness score. Lower values are healthier and
+ // zero is the minimum value.
+ score int
+}
+
+// newAwareness returns a new awareness object.
+func newAwareness(max int) *awareness {
+ return &awareness{
+ max: max,
+ score: 0,
+ }
+}
+
+// ApplyDelta takes the given delta and applies it to the score in a thread-safe
+// manner. It also enforces a floor of zero and a max of max, so deltas may not
+// change the overall score if it's railed at one of the extremes.
+func (a *awareness) ApplyDelta(delta int) {
+ a.Lock()
+ initial := a.score
+ a.score += delta
+ if a.score < 0 {
+ a.score = 0
+ } else if a.score > (a.max - 1) {
+ a.score = (a.max - 1)
+ }
+ final := a.score
+ a.Unlock()
+
+ if initial != final {
+ metrics.SetGauge([]string{"memberlist", "health", "score"}, float32(final))
+ }
+}
+
+// GetHealthScore returns the raw health score.
+func (a *awareness) GetHealthScore() int {
+ a.RLock()
+ score := a.score
+ a.RUnlock()
+ return score
+}
+
+// ScaleTimeout takes the given duration and scales it based on the current
+// score. Less healthyness will lead to longer timeouts.
+func (a *awareness) ScaleTimeout(timeout time.Duration) time.Duration {
+ a.RLock()
+ score := a.score
+ a.RUnlock()
+ return timeout * (time.Duration(score) + 1)
+}
diff --git a/vendor/github.com/hashicorp/memberlist/broadcast.go b/vendor/github.com/hashicorp/memberlist/broadcast.go
new file mode 100644
index 0000000..f7e85a1
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/broadcast.go
@@ -0,0 +1,100 @@
+package memberlist
+
+/*
+The broadcast mechanism works by maintaining a sorted list of messages to be
+sent out. When a message is to be broadcast, the retransmit count
+is set to zero and appended to the queue. The retransmit count serves
+as the "priority", ensuring that newer messages get sent first. Once
+a message hits the retransmit limit, it is removed from the queue.
+
+Additionally, older entries can be invalidated by new messages that
+are contradictory. For example, if we send "{suspect M1 inc: 1},
+then a following {alive M1 inc: 2} will invalidate that message
+*/
+
+type memberlistBroadcast struct {
+ node string
+ msg []byte
+ notify chan struct{}
+}
+
+func (b *memberlistBroadcast) Invalidates(other Broadcast) bool {
+ // Check if that broadcast is a memberlist type
+ mb, ok := other.(*memberlistBroadcast)
+ if !ok {
+ return false
+ }
+
+ // Invalidates any message about the same node
+ return b.node == mb.node
+}
+
+func (b *memberlistBroadcast) Message() []byte {
+ return b.msg
+}
+
+func (b *memberlistBroadcast) Finished() {
+ select {
+ case b.notify <- struct{}{}:
+ default:
+ }
+}
+
+// encodeAndBroadcast encodes a message and enqueues it for broadcast. Fails
+// silently if there is an encoding error.
+func (m *Memberlist) encodeAndBroadcast(node string, msgType messageType, msg interface{}) {
+ m.encodeBroadcastNotify(node, msgType, msg, nil)
+}
+
+// encodeBroadcastNotify encodes a message and enqueues it for broadcast
+// and notifies the given channel when transmission is finished. Fails
+// silently if there is an encoding error.
+func (m *Memberlist) encodeBroadcastNotify(node string, msgType messageType, msg interface{}, notify chan struct{}) {
+ buf, err := encode(msgType, msg)
+ if err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to encode message for broadcast: %s", err)
+ } else {
+ m.queueBroadcast(node, buf.Bytes(), notify)
+ }
+}
+
+// queueBroadcast is used to start dissemination of a message. It will be
+// sent up to a configured number of times. The message could potentially
+// be invalidated by a future message about the same node
+func (m *Memberlist) queueBroadcast(node string, msg []byte, notify chan struct{}) {
+ b := &memberlistBroadcast{node, msg, notify}
+ m.broadcasts.QueueBroadcast(b)
+}
+
+// getBroadcasts is used to return a slice of broadcasts to send up to
+// a maximum byte size, while imposing a per-broadcast overhead. This is used
+// to fill a UDP packet with piggybacked data
+func (m *Memberlist) getBroadcasts(overhead, limit int) [][]byte {
+ // Get memberlist messages first
+ toSend := m.broadcasts.GetBroadcasts(overhead, limit)
+
+ // Check if the user has anything to broadcast
+ d := m.config.Delegate
+ if d != nil {
+ // Determine the bytes used already
+ bytesUsed := 0
+ for _, msg := range toSend {
+ bytesUsed += len(msg) + overhead
+ }
+
+ // Check space remaining for user messages
+ avail := limit - bytesUsed
+ if avail > overhead+userMsgOverhead {
+ userMsgs := d.GetBroadcasts(overhead+userMsgOverhead, avail)
+
+ // Frame each user message
+ for _, msg := range userMsgs {
+ buf := make([]byte, 1, len(msg)+1)
+ buf[0] = byte(userMsg)
+ buf = append(buf, msg...)
+ toSend = append(toSend, buf)
+ }
+ }
+ }
+ return toSend
+}
diff --git a/vendor/github.com/hashicorp/memberlist/config.go b/vendor/github.com/hashicorp/memberlist/config.go
new file mode 100644
index 0000000..2f43d14
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/config.go
@@ -0,0 +1,288 @@
+package memberlist
+
+import (
+ "io"
+ "log"
+ "os"
+ "time"
+)
+
+type Config struct {
+ // The name of this node. This must be unique in the cluster.
+ Name string
+
+ // Transport is a hook for providing custom code to communicate with
+ // other nodes. If this is left nil, then memberlist will by default
+ // make a NetTransport using BindAddr and BindPort from this structure.
+ Transport Transport
+
+ // Configuration related to what address to bind to and ports to
+ // listen on. The port is used for both UDP and TCP gossip. It is
+ // assumed other nodes are running on this port, but they do not need
+ // to.
+ BindAddr string
+ BindPort int
+
+ // Configuration related to what address to advertise to other
+ // cluster members. Used for nat traversal.
+ AdvertiseAddr string
+ AdvertisePort int
+
+ // ProtocolVersion is the configured protocol version that we
+ // will _speak_. This must be between ProtocolVersionMin and
+ // ProtocolVersionMax.
+ ProtocolVersion uint8
+
+ // TCPTimeout is the timeout for establishing a stream connection with
+ // a remote node for a full state sync, and for stream read and write
+ // operations. This is a legacy name for backwards compatibility, but
+ // should really be called StreamTimeout now that we have generalized
+ // the transport.
+ TCPTimeout time.Duration
+
+ // IndirectChecks is the number of nodes that will be asked to perform
+ // an indirect probe of a node in the case a direct probe fails. Memberlist
+ // waits for an ack from any single indirect node, so increasing this
+ // number will increase the likelihood that an indirect probe will succeed
+ // at the expense of bandwidth.
+ IndirectChecks int
+
+ // RetransmitMult is the multiplier for the number of retransmissions
+ // that are attempted for messages broadcasted over gossip. The actual
+ // count of retransmissions is calculated using the formula:
+ //
+ // Retransmits = RetransmitMult * log(N+1)
+ //
+ // This allows the retransmits to scale properly with cluster size. The
+ // higher the multiplier, the more likely a failed broadcast is to converge
+ // at the expense of increased bandwidth.
+ RetransmitMult int
+
+ // SuspicionMult is the multiplier for determining the time an
+ // inaccessible node is considered suspect before declaring it dead.
+ // The actual timeout is calculated using the formula:
+ //
+ // SuspicionTimeout = SuspicionMult * log(N+1) * ProbeInterval
+ //
+ // This allows the timeout to scale properly with expected propagation
+ // delay with a larger cluster size. The higher the multiplier, the longer
+ // an inaccessible node is considered part of the cluster before declaring
+ // it dead, giving that suspect node more time to refute if it is indeed
+ // still alive.
+ SuspicionMult int
+
+ // SuspicionMaxTimeoutMult is the multiplier applied to the
+ // SuspicionTimeout used as an upper bound on detection time. This max
+ // timeout is calculated using the formula:
+ //
+ // SuspicionMaxTimeout = SuspicionMaxTimeoutMult * SuspicionTimeout
+ //
+ // If everything is working properly, confirmations from other nodes will
+ // accelerate suspicion timers in a manner which will cause the timeout
+ // to reach the base SuspicionTimeout before that elapses, so this value
+ // will typically only come into play if a node is experiencing issues
+ // communicating with other nodes. It should be set to a something fairly
+ // large so that a node having problems will have a lot of chances to
+ // recover before falsely declaring other nodes as failed, but short
+ // enough for a legitimately isolated node to still make progress marking
+ // nodes failed in a reasonable amount of time.
+ SuspicionMaxTimeoutMult int
+
+ // PushPullInterval is the interval between complete state syncs.
+ // Complete state syncs are done with a single node over TCP and are
+ // quite expensive relative to standard gossiped messages. Setting this
+ // to zero will disable state push/pull syncs completely.
+ //
+ // Setting this interval lower (more frequent) will increase convergence
+ // speeds across larger clusters at the expense of increased bandwidth
+ // usage.
+ PushPullInterval time.Duration
+
+ // ProbeInterval and ProbeTimeout are used to configure probing
+ // behavior for memberlist.
+ //
+ // ProbeInterval is the interval between random node probes. Setting
+ // this lower (more frequent) will cause the memberlist cluster to detect
+ // failed nodes more quickly at the expense of increased bandwidth usage.
+ //
+ // ProbeTimeout is the timeout to wait for an ack from a probed node
+ // before assuming it is unhealthy. This should be set to 99-percentile
+ // of RTT (round-trip time) on your network.
+ ProbeInterval time.Duration
+ ProbeTimeout time.Duration
+
+ // DisableTcpPings will turn off the fallback TCP pings that are attempted
+ // if the direct UDP ping fails. These get pipelined along with the
+ // indirect UDP pings.
+ DisableTcpPings bool
+
+ // AwarenessMaxMultiplier will increase the probe interval if the node
+ // becomes aware that it might be degraded and not meeting the soft real
+ // time requirements to reliably probe other nodes.
+ AwarenessMaxMultiplier int
+
+ // GossipInterval and GossipNodes are used to configure the gossip
+ // behavior of memberlist.
+ //
+ // GossipInterval is the interval between sending messages that need
+ // to be gossiped that haven't been able to piggyback on probing messages.
+ // If this is set to zero, non-piggyback gossip is disabled. By lowering
+ // this value (more frequent) gossip messages are propagated across
+ // the cluster more quickly at the expense of increased bandwidth.
+ //
+ // GossipNodes is the number of random nodes to send gossip messages to
+ // per GossipInterval. Increasing this number causes the gossip messages
+ // to propagate across the cluster more quickly at the expense of
+ // increased bandwidth.
+ //
+ // GossipToTheDeadTime is the interval after which a node has died that
+ // we will still try to gossip to it. This gives it a chance to refute.
+ GossipInterval time.Duration
+ GossipNodes int
+ GossipToTheDeadTime time.Duration
+
+ // EnableCompression is used to control message compression. This can
+ // be used to reduce bandwidth usage at the cost of slightly more CPU
+ // utilization. This is only available starting at protocol version 1.
+ EnableCompression bool
+
+ // SecretKey is used to initialize the primary encryption key in a keyring.
+ // The primary encryption key is the only key used to encrypt messages and
+ // the first key used while attempting to decrypt messages. Providing a
+ // value for this primary key will enable message-level encryption and
+ // verification, and automatically install the key onto the keyring.
+ // The value should be either 16, 24, or 32 bytes to select AES-128,
+ // AES-192, or AES-256.
+ SecretKey []byte
+
+ // The keyring holds all of the encryption keys used internally. It is
+ // automatically initialized using the SecretKey and SecretKeys values.
+ Keyring *Keyring
+
+ // Delegate and Events are delegates for receiving and providing
+ // data to memberlist via callback mechanisms. For Delegate, see
+ // the Delegate interface. For Events, see the EventDelegate interface.
+ //
+ // The DelegateProtocolMin/Max are used to guarantee protocol-compatibility
+ // for any custom messages that the delegate might do (broadcasts,
+ // local/remote state, etc.). If you don't set these, then the protocol
+ // versions will just be zero, and version compliance won't be done.
+ Delegate Delegate
+ DelegateProtocolVersion uint8
+ DelegateProtocolMin uint8
+ DelegateProtocolMax uint8
+ Events EventDelegate
+ Conflict ConflictDelegate
+ Merge MergeDelegate
+ Ping PingDelegate
+ Alive AliveDelegate
+
+ // DNSConfigPath points to the system's DNS config file, usually located
+ // at /etc/resolv.conf. It can be overridden via config for easier testing.
+ DNSConfigPath string
+
+ // LogOutput is the writer where logs should be sent. If this is not
+ // set, logging will go to stderr by default. You cannot specify both LogOutput
+ // and Logger at the same time.
+ LogOutput io.Writer
+
+ // Logger is a custom logger which you provide. If Logger is set, it will use
+ // this for the internal logger. If Logger is not set, it will fall back to the
+ // behavior for using LogOutput. You cannot specify both LogOutput and Logger
+ // at the same time.
+ Logger *log.Logger
+
+ // Size of Memberlist's internal channel which handles UDP messages. The
+ // size of this determines the size of the queue which Memberlist will keep
+ // while UDP messages are handled.
+ HandoffQueueDepth int
+
+ // Maximum number of bytes that memberlist will put in a packet (this
+ // will be for UDP packets by default with a NetTransport). A safe value
+ // for this is typically 1400 bytes (which is the default). However,
+ // depending on your network's MTU (Maximum Transmission Unit) you may
+ // be able to increase this to get more content into each gossip packet.
+ // This is a legacy name for backward compatibility but should really be
+ // called PacketBufferSize now that we have generalized the transport.
+ UDPBufferSize int
+}
+
+// DefaultLANConfig returns a sane set of configurations for Memberlist.
+// It uses the hostname as the node name, and otherwise sets very conservative
+// values that are sane for most LAN environments. The default configuration
+// errs on the side of caution, choosing values that are optimized
+// for higher convergence at the cost of higher bandwidth usage. Regardless,
+// these values are a good starting point when getting started with memberlist.
+func DefaultLANConfig() *Config {
+ hostname, _ := os.Hostname()
+ return &Config{
+ Name: hostname,
+ BindAddr: "0.0.0.0",
+ BindPort: 7946,
+ AdvertiseAddr: "",
+ AdvertisePort: 7946,
+ ProtocolVersion: ProtocolVersion2Compatible,
+ TCPTimeout: 10 * time.Second, // Timeout after 10 seconds
+ IndirectChecks: 3, // Use 3 nodes for the indirect ping
+ RetransmitMult: 4, // Retransmit a message 4 * log(N+1) nodes
+ SuspicionMult: 5, // Suspect a node for 5 * log(N+1) * Interval
+ SuspicionMaxTimeoutMult: 6, // For 10k nodes this will give a max timeout of 120 seconds
+ PushPullInterval: 30 * time.Second, // Low frequency
+ ProbeTimeout: 500 * time.Millisecond, // Reasonable RTT time for LAN
+ ProbeInterval: 1 * time.Second, // Failure check every second
+ DisableTcpPings: false, // TCP pings are safe, even with mixed versions
+ AwarenessMaxMultiplier: 8, // Probe interval backs off to 8 seconds
+
+ GossipNodes: 3, // Gossip to 3 nodes
+ GossipInterval: 200 * time.Millisecond, // Gossip more rapidly
+ GossipToTheDeadTime: 30 * time.Second, // Same as push/pull
+
+ EnableCompression: true, // Enable compression by default
+
+ SecretKey: nil,
+ Keyring: nil,
+
+ DNSConfigPath: "/etc/resolv.conf",
+
+ HandoffQueueDepth: 1024,
+ UDPBufferSize: 1400,
+ }
+}
+
+// DefaultWANConfig works like DefaultConfig, however it returns a configuration
+// that is optimized for most WAN environments. The default configuration is
+// still very conservative and errs on the side of caution.
+func DefaultWANConfig() *Config {
+ conf := DefaultLANConfig()
+ conf.TCPTimeout = 30 * time.Second
+ conf.SuspicionMult = 6
+ conf.PushPullInterval = 60 * time.Second
+ conf.ProbeTimeout = 3 * time.Second
+ conf.ProbeInterval = 5 * time.Second
+ conf.GossipNodes = 4 // Gossip less frequently, but to an additional node
+ conf.GossipInterval = 500 * time.Millisecond
+ conf.GossipToTheDeadTime = 60 * time.Second
+ return conf
+}
+
+// DefaultLocalConfig works like DefaultConfig, however it returns a configuration
+// that is optimized for a local loopback environments. The default configuration is
+// still very conservative and errs on the side of caution.
+func DefaultLocalConfig() *Config {
+ conf := DefaultLANConfig()
+ conf.TCPTimeout = time.Second
+ conf.IndirectChecks = 1
+ conf.RetransmitMult = 2
+ conf.SuspicionMult = 3
+ conf.PushPullInterval = 15 * time.Second
+ conf.ProbeTimeout = 200 * time.Millisecond
+ conf.ProbeInterval = time.Second
+ conf.GossipInterval = 100 * time.Millisecond
+ conf.GossipToTheDeadTime = 15 * time.Second
+ return conf
+}
+
+// Returns whether or not encryption is enabled
+func (c *Config) EncryptionEnabled() bool {
+ return c.Keyring != nil && len(c.Keyring.GetKeys()) > 0
+}
diff --git a/vendor/github.com/hashicorp/memberlist/conflict_delegate.go b/vendor/github.com/hashicorp/memberlist/conflict_delegate.go
new file mode 100644
index 0000000..f52b136
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/conflict_delegate.go
@@ -0,0 +1,10 @@
+package memberlist
+
+// ConflictDelegate is a used to inform a client that
+// a node has attempted to join which would result in a
+// name conflict. This happens if two clients are configured
+// with the same name but different addresses.
+type ConflictDelegate interface {
+ // NotifyConflict is invoked when a name conflict is detected
+ NotifyConflict(existing, other *Node)
+}
diff --git a/vendor/github.com/hashicorp/memberlist/delegate.go b/vendor/github.com/hashicorp/memberlist/delegate.go
new file mode 100644
index 0000000..5515488
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/delegate.go
@@ -0,0 +1,37 @@
+package memberlist
+
+// Delegate is the interface that clients must implement if they want to hook
+// into the gossip layer of Memberlist. All the methods must be thread-safe,
+// as they can and generally will be called concurrently.
+type Delegate interface {
+ // NodeMeta is used to retrieve meta-data about the current node
+ // when broadcasting an alive message. It's length is limited to
+ // the given byte size. This metadata is available in the Node structure.
+ NodeMeta(limit int) []byte
+
+ // NotifyMsg is called when a user-data message is received.
+ // Care should be taken that this method does not block, since doing
+ // so would block the entire UDP packet receive loop. Additionally, the byte
+ // slice may be modified after the call returns, so it should be copied if needed
+ NotifyMsg([]byte)
+
+ // GetBroadcasts is called when user data messages can be broadcast.
+ // It can return a list of buffers to send. Each buffer should assume an
+ // overhead as provided with a limit on the total byte size allowed.
+ // The total byte size of the resulting data to send must not exceed
+ // the limit. Care should be taken that this method does not block,
+ // since doing so would block the entire UDP packet receive loop.
+ GetBroadcasts(overhead, limit int) [][]byte
+
+ // LocalState is used for a TCP Push/Pull. This is sent to
+ // the remote side in addition to the membership information. Any
+ // data can be sent here. See MergeRemoteState as well. The `join`
+ // boolean indicates this is for a join instead of a push/pull.
+ LocalState(join bool) []byte
+
+ // MergeRemoteState is invoked after a TCP Push/Pull. This is the
+ // state received from the remote side and is the result of the
+ // remote side's LocalState call. The 'join'
+ // boolean indicates this is for a join instead of a push/pull.
+ MergeRemoteState(buf []byte, join bool)
+}
diff --git a/vendor/github.com/hashicorp/memberlist/event_delegate.go b/vendor/github.com/hashicorp/memberlist/event_delegate.go
new file mode 100644
index 0000000..35e2a56
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/event_delegate.go
@@ -0,0 +1,61 @@
+package memberlist
+
+// EventDelegate is a simpler delegate that is used only to receive
+// notifications about members joining and leaving. The methods in this
+// delegate may be called by multiple goroutines, but never concurrently.
+// This allows you to reason about ordering.
+type EventDelegate interface {
+ // NotifyJoin is invoked when a node is detected to have joined.
+ // The Node argument must not be modified.
+ NotifyJoin(*Node)
+
+ // NotifyLeave is invoked when a node is detected to have left.
+ // The Node argument must not be modified.
+ NotifyLeave(*Node)
+
+ // NotifyUpdate is invoked when a node is detected to have
+ // updated, usually involving the meta data. The Node argument
+ // must not be modified.
+ NotifyUpdate(*Node)
+}
+
+// ChannelEventDelegate is used to enable an application to receive
+// events about joins and leaves over a channel instead of a direct
+// function call.
+//
+// Care must be taken that events are processed in a timely manner from
+// the channel, since this delegate will block until an event can be sent.
+type ChannelEventDelegate struct {
+ Ch chan<- NodeEvent
+}
+
+// NodeEventType are the types of events that can be sent from the
+// ChannelEventDelegate.
+type NodeEventType int
+
+const (
+ NodeJoin NodeEventType = iota
+ NodeLeave
+ NodeUpdate
+)
+
+// NodeEvent is a single event related to node activity in the memberlist.
+// The Node member of this struct must not be directly modified. It is passed
+// as a pointer to avoid unnecessary copies. If you wish to modify the node,
+// make a copy first.
+type NodeEvent struct {
+ Event NodeEventType
+ Node *Node
+}
+
+func (c *ChannelEventDelegate) NotifyJoin(n *Node) {
+ c.Ch <- NodeEvent{NodeJoin, n}
+}
+
+func (c *ChannelEventDelegate) NotifyLeave(n *Node) {
+ c.Ch <- NodeEvent{NodeLeave, n}
+}
+
+func (c *ChannelEventDelegate) NotifyUpdate(n *Node) {
+ c.Ch <- NodeEvent{NodeUpdate, n}
+}
diff --git a/vendor/github.com/hashicorp/memberlist/keyring.go b/vendor/github.com/hashicorp/memberlist/keyring.go
new file mode 100644
index 0000000..a2774a0
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/keyring.go
@@ -0,0 +1,160 @@
+package memberlist
+
+import (
+ "bytes"
+ "fmt"
+ "sync"
+)
+
+type Keyring struct {
+ // Keys stores the key data used during encryption and decryption. It is
+ // ordered in such a way where the first key (index 0) is the primary key,
+ // which is used for encrypting messages, and is the first key tried during
+ // message decryption.
+ keys [][]byte
+
+ // The keyring lock is used while performing IO operations on the keyring.
+ l sync.Mutex
+}
+
+// Init allocates substructures
+func (k *Keyring) init() {
+ k.keys = make([][]byte, 0)
+}
+
+// NewKeyring constructs a new container for a set of encryption keys. The
+// keyring contains all key data used internally by memberlist.
+//
+// While creating a new keyring, you must do one of:
+// - Omit keys and primary key, effectively disabling encryption
+// - Pass a set of keys plus the primary key
+// - Pass only a primary key
+//
+// If only a primary key is passed, then it will be automatically added to the
+// keyring. If creating a keyring with multiple keys, one key must be designated
+// primary by passing it as the primaryKey. If the primaryKey does not exist in
+// the list of secondary keys, it will be automatically added at position 0.
+//
+// A key should be either 16, 24, or 32 bytes to select AES-128,
+// AES-192, or AES-256.
+func NewKeyring(keys [][]byte, primaryKey []byte) (*Keyring, error) {
+ keyring := &Keyring{}
+ keyring.init()
+
+ if len(keys) > 0 || len(primaryKey) > 0 {
+ if len(primaryKey) == 0 {
+ return nil, fmt.Errorf("Empty primary key not allowed")
+ }
+ if err := keyring.AddKey(primaryKey); err != nil {
+ return nil, err
+ }
+ for _, key := range keys {
+ if err := keyring.AddKey(key); err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ return keyring, nil
+}
+
+// ValidateKey will check to see if the key is valid and returns an error if not.
+//
+// key should be either 16, 24, or 32 bytes to select AES-128,
+// AES-192, or AES-256.
+func ValidateKey(key []byte) error {
+ if l := len(key); l != 16 && l != 24 && l != 32 {
+ return fmt.Errorf("key size must be 16, 24 or 32 bytes")
+ }
+ return nil
+}
+
+// AddKey will install a new key on the ring. Adding a key to the ring will make
+// it available for use in decryption. If the key already exists on the ring,
+// this function will just return noop.
+//
+// key should be either 16, 24, or 32 bytes to select AES-128,
+// AES-192, or AES-256.
+func (k *Keyring) AddKey(key []byte) error {
+ if err := ValidateKey(key); err != nil {
+ return err
+ }
+
+ // No-op if key is already installed
+ for _, installedKey := range k.keys {
+ if bytes.Equal(installedKey, key) {
+ return nil
+ }
+ }
+
+ keys := append(k.keys, key)
+ primaryKey := k.GetPrimaryKey()
+ if primaryKey == nil {
+ primaryKey = key
+ }
+ k.installKeys(keys, primaryKey)
+ return nil
+}
+
+// UseKey changes the key used to encrypt messages. This is the only key used to
+// encrypt messages, so peers should know this key before this method is called.
+func (k *Keyring) UseKey(key []byte) error {
+ for _, installedKey := range k.keys {
+ if bytes.Equal(key, installedKey) {
+ k.installKeys(k.keys, key)
+ return nil
+ }
+ }
+ return fmt.Errorf("Requested key is not in the keyring")
+}
+
+// RemoveKey drops a key from the keyring. This will return an error if the key
+// requested for removal is currently at position 0 (primary key).
+func (k *Keyring) RemoveKey(key []byte) error {
+ if bytes.Equal(key, k.keys[0]) {
+ return fmt.Errorf("Removing the primary key is not allowed")
+ }
+ for i, installedKey := range k.keys {
+ if bytes.Equal(key, installedKey) {
+ keys := append(k.keys[:i], k.keys[i+1:]...)
+ k.installKeys(keys, k.keys[0])
+ }
+ }
+ return nil
+}
+
+// installKeys will take out a lock on the keyring, and replace the keys with a
+// new set of keys. The key indicated by primaryKey will be installed as the new
+// primary key.
+func (k *Keyring) installKeys(keys [][]byte, primaryKey []byte) {
+ k.l.Lock()
+ defer k.l.Unlock()
+
+ newKeys := [][]byte{primaryKey}
+ for _, key := range keys {
+ if !bytes.Equal(key, primaryKey) {
+ newKeys = append(newKeys, key)
+ }
+ }
+ k.keys = newKeys
+}
+
+// GetKeys returns the current set of keys on the ring.
+func (k *Keyring) GetKeys() [][]byte {
+ k.l.Lock()
+ defer k.l.Unlock()
+
+ return k.keys
+}
+
+// GetPrimaryKey returns the key on the ring at position 0. This is the key used
+// for encrypting messages, and is the first key tried for decrypting messages.
+func (k *Keyring) GetPrimaryKey() (key []byte) {
+ k.l.Lock()
+ defer k.l.Unlock()
+
+ if len(k.keys) > 0 {
+ key = k.keys[0]
+ }
+ return
+}
diff --git a/vendor/github.com/hashicorp/memberlist/logging.go b/vendor/github.com/hashicorp/memberlist/logging.go
new file mode 100644
index 0000000..f31acfb
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/logging.go
@@ -0,0 +1,22 @@
+package memberlist
+
+import (
+ "fmt"
+ "net"
+)
+
+func LogAddress(addr net.Addr) string {
+ if addr == nil {
+ return "from=<unknown address>"
+ }
+
+ return fmt.Sprintf("from=%s", addr.String())
+}
+
+func LogConn(conn net.Conn) string {
+ if conn == nil {
+ return LogAddress(nil)
+ }
+
+ return LogAddress(conn.RemoteAddr())
+}
diff --git a/vendor/github.com/hashicorp/memberlist/memberlist.go b/vendor/github.com/hashicorp/memberlist/memberlist.go
new file mode 100644
index 0000000..e4b0d73
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/memberlist.go
@@ -0,0 +1,625 @@
+/*
+memberlist is a library that manages cluster
+membership and member failure detection using a gossip based protocol.
+
+The use cases for such a library are far-reaching: all distributed systems
+require membership, and memberlist is a re-usable solution to managing
+cluster membership and node failure detection.
+
+memberlist is eventually consistent but converges quickly on average.
+The speed at which it converges can be heavily tuned via various knobs
+on the protocol. Node failures are detected and network partitions are partially
+tolerated by attempting to communicate to potentially dead nodes through
+multiple routes.
+*/
+package memberlist
+
+import (
+ "fmt"
+ "log"
+ "net"
+ "os"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/hashicorp/go-multierror"
+ sockaddr "github.com/hashicorp/go-sockaddr"
+ "github.com/miekg/dns"
+)
+
+type Memberlist struct {
+ sequenceNum uint32 // Local sequence number
+ incarnation uint32 // Local incarnation number
+ numNodes uint32 // Number of known nodes (estimate)
+
+ config *Config
+ shutdown bool
+ shutdownCh chan struct{}
+ leave bool
+ leaveBroadcast chan struct{}
+
+ transport Transport
+ handoff chan msgHandoff
+
+ nodeLock sync.RWMutex
+ nodes []*nodeState // Known nodes
+ nodeMap map[string]*nodeState // Maps Addr.String() -> NodeState
+ nodeTimers map[string]*suspicion // Maps Addr.String() -> suspicion timer
+ awareness *awareness
+
+ tickerLock sync.Mutex
+ tickers []*time.Ticker
+ stopTick chan struct{}
+ probeIndex int
+
+ ackLock sync.Mutex
+ ackHandlers map[uint32]*ackHandler
+
+ broadcasts *TransmitLimitedQueue
+
+ logger *log.Logger
+}
+
+// newMemberlist creates the network listeners.
+// Does not schedule execution of background maintenance.
+func newMemberlist(conf *Config) (*Memberlist, error) {
+ if conf.ProtocolVersion < ProtocolVersionMin {
+ return nil, fmt.Errorf("Protocol version '%d' too low. Must be in range: [%d, %d]",
+ conf.ProtocolVersion, ProtocolVersionMin, ProtocolVersionMax)
+ } else if conf.ProtocolVersion > ProtocolVersionMax {
+ return nil, fmt.Errorf("Protocol version '%d' too high. Must be in range: [%d, %d]",
+ conf.ProtocolVersion, ProtocolVersionMin, ProtocolVersionMax)
+ }
+
+ if len(conf.SecretKey) > 0 {
+ if conf.Keyring == nil {
+ keyring, err := NewKeyring(nil, conf.SecretKey)
+ if err != nil {
+ return nil, err
+ }
+ conf.Keyring = keyring
+ } else {
+ if err := conf.Keyring.AddKey(conf.SecretKey); err != nil {
+ return nil, err
+ }
+ if err := conf.Keyring.UseKey(conf.SecretKey); err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ if conf.LogOutput != nil && conf.Logger != nil {
+ return nil, fmt.Errorf("Cannot specify both LogOutput and Logger. Please choose a single log configuration setting.")
+ }
+
+ logDest := conf.LogOutput
+ if logDest == nil {
+ logDest = os.Stderr
+ }
+
+ logger := conf.Logger
+ if logger == nil {
+ logger = log.New(logDest, "", log.LstdFlags)
+ }
+
+ // Set up a network transport by default if a custom one wasn't given
+ // by the config.
+ transport := conf.Transport
+ if transport == nil {
+ nc := &NetTransportConfig{
+ BindAddrs: []string{conf.BindAddr},
+ BindPort: conf.BindPort,
+ Logger: logger,
+ }
+ nt, err := NewNetTransport(nc)
+ if err != nil {
+ return nil, fmt.Errorf("Could not set up network transport: %v", err)
+ }
+
+ if conf.BindPort == 0 {
+ port := nt.GetAutoBindPort()
+ conf.BindPort = port
+ logger.Printf("[DEBUG] Using dynamic bind port %d", port)
+ }
+ transport = nt
+ }
+
+ m := &Memberlist{
+ config: conf,
+ shutdownCh: make(chan struct{}),
+ leaveBroadcast: make(chan struct{}, 1),
+ transport: transport,
+ handoff: make(chan msgHandoff, conf.HandoffQueueDepth),
+ nodeMap: make(map[string]*nodeState),
+ nodeTimers: make(map[string]*suspicion),
+ awareness: newAwareness(conf.AwarenessMaxMultiplier),
+ ackHandlers: make(map[uint32]*ackHandler),
+ broadcasts: &TransmitLimitedQueue{RetransmitMult: conf.RetransmitMult},
+ logger: logger,
+ }
+ m.broadcasts.NumNodes = func() int {
+ return m.estNumNodes()
+ }
+ go m.streamListen()
+ go m.packetListen()
+ go m.packetHandler()
+ return m, nil
+}
+
+// Create will create a new Memberlist using the given configuration.
+// This will not connect to any other node (see Join) yet, but will start
+// all the listeners to allow other nodes to join this memberlist.
+// After creating a Memberlist, the configuration given should not be
+// modified by the user anymore.
+func Create(conf *Config) (*Memberlist, error) {
+ m, err := newMemberlist(conf)
+ if err != nil {
+ return nil, err
+ }
+ if err := m.setAlive(); err != nil {
+ m.Shutdown()
+ return nil, err
+ }
+ m.schedule()
+ return m, nil
+}
+
+// Join is used to take an existing Memberlist and attempt to join a cluster
+// by contacting all the given hosts and performing a state sync. Initially,
+// the Memberlist only contains our own state, so doing this will cause
+// remote nodes to become aware of the existence of this node, effectively
+// joining the cluster.
+//
+// This returns the number of hosts successfully contacted and an error if
+// none could be reached. If an error is returned, the node did not successfully
+// join the cluster.
+func (m *Memberlist) Join(existing []string) (int, error) {
+ numSuccess := 0
+ var errs error
+ for _, exist := range existing {
+ addrs, err := m.resolveAddr(exist)
+ if err != nil {
+ err = fmt.Errorf("Failed to resolve %s: %v", exist, err)
+ errs = multierror.Append(errs, err)
+ m.logger.Printf("[WARN] memberlist: %v", err)
+ continue
+ }
+
+ for _, addr := range addrs {
+ hp := joinHostPort(addr.ip.String(), addr.port)
+ if err := m.pushPullNode(hp, true); err != nil {
+ err = fmt.Errorf("Failed to join %s: %v", addr.ip, err)
+ errs = multierror.Append(errs, err)
+ m.logger.Printf("[DEBUG] memberlist: %v", err)
+ continue
+ }
+ numSuccess++
+ }
+
+ }
+ if numSuccess > 0 {
+ errs = nil
+ }
+ return numSuccess, errs
+}
+
+// ipPort holds information about a node we want to try to join.
+type ipPort struct {
+ ip net.IP
+ port uint16
+}
+
+// tcpLookupIP is a helper to initiate a TCP-based DNS lookup for the given host.
+// The built-in Go resolver will do a UDP lookup first, and will only use TCP if
+// the response has the truncate bit set, which isn't common on DNS servers like
+// Consul's. By doing the TCP lookup directly, we get the best chance for the
+// largest list of hosts to join. Since joins are relatively rare events, it's ok
+// to do this rather expensive operation.
+func (m *Memberlist) tcpLookupIP(host string, defaultPort uint16) ([]ipPort, error) {
+ // Don't attempt any TCP lookups against non-fully qualified domain
+ // names, since those will likely come from the resolv.conf file.
+ if !strings.Contains(host, ".") {
+ return nil, nil
+ }
+
+ // Make sure the domain name is terminated with a dot (we know there's
+ // at least one character at this point).
+ dn := host
+ if dn[len(dn)-1] != '.' {
+ dn = dn + "."
+ }
+
+ // See if we can find a server to try.
+ cc, err := dns.ClientConfigFromFile(m.config.DNSConfigPath)
+ if err != nil {
+ return nil, err
+ }
+ if len(cc.Servers) > 0 {
+ // We support host:port in the DNS config, but need to add the
+ // default port if one is not supplied.
+ server := cc.Servers[0]
+ if !hasPort(server) {
+ server = net.JoinHostPort(server, cc.Port)
+ }
+
+ // Do the lookup.
+ c := new(dns.Client)
+ c.Net = "tcp"
+ msg := new(dns.Msg)
+ msg.SetQuestion(dn, dns.TypeANY)
+ in, _, err := c.Exchange(msg, server)
+ if err != nil {
+ return nil, err
+ }
+
+ // Handle any IPs we get back that we can attempt to join.
+ var ips []ipPort
+ for _, r := range in.Answer {
+ switch rr := r.(type) {
+ case (*dns.A):
+ ips = append(ips, ipPort{rr.A, defaultPort})
+ case (*dns.AAAA):
+ ips = append(ips, ipPort{rr.AAAA, defaultPort})
+ case (*dns.CNAME):
+ m.logger.Printf("[DEBUG] memberlist: Ignoring CNAME RR in TCP-first answer for '%s'", host)
+ }
+ }
+ return ips, nil
+ }
+
+ return nil, nil
+}
+
+// resolveAddr is used to resolve the address into an address,
+// port, and error. If no port is given, use the default
+func (m *Memberlist) resolveAddr(hostStr string) ([]ipPort, error) {
+ // Normalize the incoming string to host:port so we can apply Go's
+ // parser to it.
+ port := uint16(0)
+ if !hasPort(hostStr) {
+ hostStr += ":" + strconv.Itoa(m.config.BindPort)
+ }
+ host, sport, err := net.SplitHostPort(hostStr)
+ if err != nil {
+ return nil, err
+ }
+
+ // This will capture the supplied port, or the default one added above.
+ lport, err := strconv.ParseUint(sport, 10, 16)
+ if err != nil {
+ return nil, err
+ }
+ port = uint16(lport)
+
+ // If it looks like an IP address we are done. The SplitHostPort() above
+ // will make sure the host part is in good shape for parsing, even for
+ // IPv6 addresses.
+ if ip := net.ParseIP(host); ip != nil {
+ return []ipPort{ipPort{ip, port}}, nil
+ }
+
+ // First try TCP so we have the best chance for the largest list of
+ // hosts to join. If this fails it's not fatal since this isn't a standard
+ // way to query DNS, and we have a fallback below.
+ ips, err := m.tcpLookupIP(host, port)
+ if err != nil {
+ m.logger.Printf("[DEBUG] memberlist: TCP-first lookup failed for '%s', falling back to UDP: %s", hostStr, err)
+ }
+ if len(ips) > 0 {
+ return ips, nil
+ }
+
+ // If TCP didn't yield anything then use the normal Go resolver which
+ // will try UDP, then might possibly try TCP again if the UDP response
+ // indicates it was truncated.
+ ans, err := net.LookupIP(host)
+ if err != nil {
+ return nil, err
+ }
+ ips = make([]ipPort, 0, len(ans))
+ for _, ip := range ans {
+ ips = append(ips, ipPort{ip, port})
+ }
+ return ips, nil
+}
+
+// setAlive is used to mark this node as being alive. This is the same
+// as if we received an alive notification our own network channel for
+// ourself.
+func (m *Memberlist) setAlive() error {
+ // Get the final advertise address from the transport, which may need
+ // to see which address we bound to.
+ addr, port, err := m.transport.FinalAdvertiseAddr(
+ m.config.AdvertiseAddr, m.config.AdvertisePort)
+ if err != nil {
+ return fmt.Errorf("Failed to get final advertise address: %v", err)
+ }
+
+ // Check if this is a public address without encryption
+ ipAddr, err := sockaddr.NewIPAddr(addr.String())
+ if err != nil {
+ return fmt.Errorf("Failed to parse interface addresses: %v", err)
+ }
+ ifAddrs := []sockaddr.IfAddr{
+ sockaddr.IfAddr{
+ SockAddr: ipAddr,
+ },
+ }
+ _, publicIfs, err := sockaddr.IfByRFC("6890", ifAddrs)
+ if len(publicIfs) > 0 && !m.config.EncryptionEnabled() {
+ m.logger.Printf("[WARN] memberlist: Binding to public address without encryption!")
+ }
+
+ // Set any metadata from the delegate.
+ var meta []byte
+ if m.config.Delegate != nil {
+ meta = m.config.Delegate.NodeMeta(MetaMaxSize)
+ if len(meta) > MetaMaxSize {
+ panic("Node meta data provided is longer than the limit")
+ }
+ }
+
+ a := alive{
+ Incarnation: m.nextIncarnation(),
+ Node: m.config.Name,
+ Addr: addr,
+ Port: uint16(port),
+ Meta: meta,
+ Vsn: []uint8{
+ ProtocolVersionMin, ProtocolVersionMax, m.config.ProtocolVersion,
+ m.config.DelegateProtocolMin, m.config.DelegateProtocolMax,
+ m.config.DelegateProtocolVersion,
+ },
+ }
+ m.aliveNode(&a, nil, true)
+ return nil
+}
+
+// LocalNode is used to return the local Node
+func (m *Memberlist) LocalNode() *Node {
+ m.nodeLock.RLock()
+ defer m.nodeLock.RUnlock()
+ state := m.nodeMap[m.config.Name]
+ return &state.Node
+}
+
+// UpdateNode is used to trigger re-advertising the local node. This is
+// primarily used with a Delegate to support dynamic updates to the local
+// meta data. This will block until the update message is successfully
+// broadcasted to a member of the cluster, if any exist or until a specified
+// timeout is reached.
+func (m *Memberlist) UpdateNode(timeout time.Duration) error {
+ // Get the node meta data
+ var meta []byte
+ if m.config.Delegate != nil {
+ meta = m.config.Delegate.NodeMeta(MetaMaxSize)
+ if len(meta) > MetaMaxSize {
+ panic("Node meta data provided is longer than the limit")
+ }
+ }
+
+ // Get the existing node
+ m.nodeLock.RLock()
+ state := m.nodeMap[m.config.Name]
+ m.nodeLock.RUnlock()
+
+ // Format a new alive message
+ a := alive{
+ Incarnation: m.nextIncarnation(),
+ Node: m.config.Name,
+ Addr: state.Addr,
+ Port: state.Port,
+ Meta: meta,
+ Vsn: []uint8{
+ ProtocolVersionMin, ProtocolVersionMax, m.config.ProtocolVersion,
+ m.config.DelegateProtocolMin, m.config.DelegateProtocolMax,
+ m.config.DelegateProtocolVersion,
+ },
+ }
+ notifyCh := make(chan struct{})
+ m.aliveNode(&a, notifyCh, true)
+
+ // Wait for the broadcast or a timeout
+ if m.anyAlive() {
+ var timeoutCh <-chan time.Time
+ if timeout > 0 {
+ timeoutCh = time.After(timeout)
+ }
+ select {
+ case <-notifyCh:
+ case <-timeoutCh:
+ return fmt.Errorf("timeout waiting for update broadcast")
+ }
+ }
+ return nil
+}
+
+// SendTo is deprecated in favor of SendBestEffort, which requires a node to
+// target.
+func (m *Memberlist) SendTo(to net.Addr, msg []byte) error {
+ // Encode as a user message
+ buf := make([]byte, 1, len(msg)+1)
+ buf[0] = byte(userMsg)
+ buf = append(buf, msg...)
+
+ // Send the message
+ return m.rawSendMsgPacket(to.String(), nil, buf)
+}
+
+// SendToUDP is deprecated in favor of SendBestEffort.
+func (m *Memberlist) SendToUDP(to *Node, msg []byte) error {
+ return m.SendBestEffort(to, msg)
+}
+
+// SendToTCP is deprecated in favor of SendReliable.
+func (m *Memberlist) SendToTCP(to *Node, msg []byte) error {
+ return m.SendReliable(to, msg)
+}
+
+// SendBestEffort uses the unreliable packet-oriented interface of the transport
+// to target a user message at the given node (this does not use the gossip
+// mechanism). The maximum size of the message depends on the configured
+// UDPBufferSize for this memberlist instance.
+func (m *Memberlist) SendBestEffort(to *Node, msg []byte) error {
+ // Encode as a user message
+ buf := make([]byte, 1, len(msg)+1)
+ buf[0] = byte(userMsg)
+ buf = append(buf, msg...)
+
+ // Send the message
+ return m.rawSendMsgPacket(to.Address(), to, buf)
+}
+
+// SendReliable uses the reliable stream-oriented interface of the transport to
+// target a user message at the given node (this does not use the gossip
+// mechanism). Delivery is guaranteed if no error is returned, and there is no
+// limit on the size of the message.
+func (m *Memberlist) SendReliable(to *Node, msg []byte) error {
+ return m.sendUserMsg(to.Address(), msg)
+}
+
+// Members returns a list of all known live nodes. The node structures
+// returned must not be modified. If you wish to modify a Node, make a
+// copy first.
+func (m *Memberlist) Members() []*Node {
+ m.nodeLock.RLock()
+ defer m.nodeLock.RUnlock()
+
+ nodes := make([]*Node, 0, len(m.nodes))
+ for _, n := range m.nodes {
+ if n.State != stateDead {
+ nodes = append(nodes, &n.Node)
+ }
+ }
+
+ return nodes
+}
+
+// NumMembers returns the number of alive nodes currently known. Between
+// the time of calling this and calling Members, the number of alive nodes
+// may have changed, so this shouldn't be used to determine how many
+// members will be returned by Members.
+func (m *Memberlist) NumMembers() (alive int) {
+ m.nodeLock.RLock()
+ defer m.nodeLock.RUnlock()
+
+ for _, n := range m.nodes {
+ if n.State != stateDead {
+ alive++
+ }
+ }
+
+ return
+}
+
+// Leave will broadcast a leave message but will not shutdown the background
+// listeners, meaning the node will continue participating in gossip and state
+// updates.
+//
+// This will block until the leave message is successfully broadcasted to
+// a member of the cluster, if any exist or until a specified timeout
+// is reached.
+//
+// This method is safe to call multiple times, but must not be called
+// after the cluster is already shut down.
+func (m *Memberlist) Leave(timeout time.Duration) error {
+ m.nodeLock.Lock()
+ // We can't defer m.nodeLock.Unlock() because m.deadNode will also try to
+ // acquire a lock so we need to Unlock before that.
+
+ if m.shutdown {
+ m.nodeLock.Unlock()
+ panic("leave after shutdown")
+ }
+
+ if !m.leave {
+ m.leave = true
+
+ state, ok := m.nodeMap[m.config.Name]
+ m.nodeLock.Unlock()
+ if !ok {
+ m.logger.Printf("[WARN] memberlist: Leave but we're not in the node map.")
+ return nil
+ }
+
+ d := dead{
+ Incarnation: state.Incarnation,
+ Node: state.Name,
+ }
+ m.deadNode(&d)
+
+ // Block until the broadcast goes out
+ if m.anyAlive() {
+ var timeoutCh <-chan time.Time
+ if timeout > 0 {
+ timeoutCh = time.After(timeout)
+ }
+ select {
+ case <-m.leaveBroadcast:
+ case <-timeoutCh:
+ return fmt.Errorf("timeout waiting for leave broadcast")
+ }
+ }
+ } else {
+ m.nodeLock.Unlock()
+ }
+
+ return nil
+}
+
+// Check for any other alive node.
+func (m *Memberlist) anyAlive() bool {
+ m.nodeLock.RLock()
+ defer m.nodeLock.RUnlock()
+ for _, n := range m.nodes {
+ if n.State != stateDead && n.Name != m.config.Name {
+ return true
+ }
+ }
+ return false
+}
+
+// GetHealthScore gives this instance's idea of how well it is meeting the soft
+// real-time requirements of the protocol. Lower numbers are better, and zero
+// means "totally healthy".
+func (m *Memberlist) GetHealthScore() int {
+ return m.awareness.GetHealthScore()
+}
+
+// ProtocolVersion returns the protocol version currently in use by
+// this memberlist.
+func (m *Memberlist) ProtocolVersion() uint8 {
+ // NOTE: This method exists so that in the future we can control
+ // any locking if necessary, if we change the protocol version at
+ // runtime, etc.
+ return m.config.ProtocolVersion
+}
+
+// Shutdown will stop any background maintanence of network activity
+// for this memberlist, causing it to appear "dead". A leave message
+// will not be broadcasted prior, so the cluster being left will have
+// to detect this node's shutdown using probing. If you wish to more
+// gracefully exit the cluster, call Leave prior to shutting down.
+//
+// This method is safe to call multiple times.
+func (m *Memberlist) Shutdown() error {
+ m.nodeLock.Lock()
+ defer m.nodeLock.Unlock()
+
+ if m.shutdown {
+ return nil
+ }
+
+ // Shut down the transport first, which should block until it's
+ // completely torn down. If we kill the memberlist-side handlers
+ // those I/O handlers might get stuck.
+ m.transport.Shutdown()
+
+ // Now tear down everything else.
+ m.shutdown = true
+ close(m.shutdownCh)
+ m.deschedule()
+ return nil
+}
diff --git a/vendor/github.com/hashicorp/memberlist/merge_delegate.go b/vendor/github.com/hashicorp/memberlist/merge_delegate.go
new file mode 100644
index 0000000..89afb59
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/merge_delegate.go
@@ -0,0 +1,14 @@
+package memberlist
+
+// MergeDelegate is used to involve a client in
+// a potential cluster merge operation. Namely, when
+// a node does a TCP push/pull (as part of a join),
+// the delegate is involved and allowed to cancel the join
+// based on custom logic. The merge delegate is NOT invoked
+// as part of the push-pull anti-entropy.
+type MergeDelegate interface {
+ // NotifyMerge is invoked when a merge could take place.
+ // Provides a list of the nodes known by the peer. If
+ // the return value is non-nil, the merge is canceled.
+ NotifyMerge(peers []*Node) error
+}
diff --git a/vendor/github.com/hashicorp/memberlist/mock_transport.go b/vendor/github.com/hashicorp/memberlist/mock_transport.go
new file mode 100644
index 0000000..b8bafa8
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/mock_transport.go
@@ -0,0 +1,121 @@
+package memberlist
+
+import (
+ "fmt"
+ "net"
+ "strconv"
+ "time"
+)
+
+// MockNetwork is used as a factory that produces MockTransport instances which
+// are uniquely addressed and wired up to talk to each other.
+type MockNetwork struct {
+ transports map[string]*MockTransport
+ port int
+}
+
+// NewTransport returns a new MockTransport with a unique address, wired up to
+// talk to the other transports in the MockNetwork.
+func (n *MockNetwork) NewTransport() *MockTransport {
+ n.port += 1
+ addr := fmt.Sprintf("127.0.0.1:%d", n.port)
+ transport := &MockTransport{
+ net: n,
+ addr: &MockAddress{addr},
+ packetCh: make(chan *Packet),
+ streamCh: make(chan net.Conn),
+ }
+
+ if n.transports == nil {
+ n.transports = make(map[string]*MockTransport)
+ }
+ n.transports[addr] = transport
+ return transport
+}
+
+// MockAddress is a wrapper which adds the net.Addr interface to our mock
+// address scheme.
+type MockAddress struct {
+ addr string
+}
+
+// See net.Addr.
+func (a *MockAddress) Network() string {
+ return "mock"
+}
+
+// See net.Addr.
+func (a *MockAddress) String() string {
+ return a.addr
+}
+
+// MockTransport directly plumbs messages to other transports its MockNetwork.
+type MockTransport struct {
+ net *MockNetwork
+ addr *MockAddress
+ packetCh chan *Packet
+ streamCh chan net.Conn
+}
+
+// See Transport.
+func (t *MockTransport) FinalAdvertiseAddr(string, int) (net.IP, int, error) {
+ host, portStr, err := net.SplitHostPort(t.addr.String())
+ if err != nil {
+ return nil, 0, err
+ }
+
+ ip := net.ParseIP(host)
+ if ip == nil {
+ return nil, 0, fmt.Errorf("Failed to parse IP %q", host)
+ }
+
+ port, err := strconv.ParseInt(portStr, 10, 16)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ return ip, int(port), nil
+}
+
+// See Transport.
+func (t *MockTransport) WriteTo(b []byte, addr string) (time.Time, error) {
+ dest, ok := t.net.transports[addr]
+ if !ok {
+ return time.Time{}, fmt.Errorf("No route to %q", addr)
+ }
+
+ now := time.Now()
+ dest.packetCh <- &Packet{
+ Buf: b,
+ From: t.addr,
+ Timestamp: now,
+ }
+ return now, nil
+}
+
+// See Transport.
+func (t *MockTransport) PacketCh() <-chan *Packet {
+ return t.packetCh
+}
+
+// See Transport.
+func (t *MockTransport) DialTimeout(addr string, timeout time.Duration) (net.Conn, error) {
+ dest, ok := t.net.transports[addr]
+ if !ok {
+ return nil, fmt.Errorf("No route to %q", addr)
+ }
+
+ p1, p2 := net.Pipe()
+ dest.streamCh <- p1
+ return p2, nil
+}
+
+// See Transport.
+func (t *MockTransport) StreamCh() <-chan net.Conn {
+ return t.streamCh
+}
+
+// See Transport.
+func (t *MockTransport) Shutdown() error {
+ return nil
+}
diff --git a/vendor/github.com/hashicorp/memberlist/net.go b/vendor/github.com/hashicorp/memberlist/net.go
new file mode 100644
index 0000000..e0036d0
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/net.go
@@ -0,0 +1,1069 @@
+package memberlist
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "net"
+ "time"
+
+ "github.com/armon/go-metrics"
+ "github.com/hashicorp/go-msgpack/codec"
+)
+
+// This is the minimum and maximum protocol version that we can
+// _understand_. We're allowed to speak at any version within this
+// range. This range is inclusive.
+const (
+ ProtocolVersionMin uint8 = 1
+
+ // Version 3 added support for TCP pings but we kept the default
+ // protocol version at 2 to ease transition to this new feature.
+ // A memberlist speaking version 2 of the protocol will attempt
+ // to TCP ping another memberlist who understands version 3 or
+ // greater.
+ //
+ // Version 4 added support for nacks as part of indirect probes.
+ // A memberlist speaking version 2 of the protocol will expect
+ // nacks from another memberlist who understands version 4 or
+ // greater, and likewise nacks will be sent to memberlists who
+ // understand version 4 or greater.
+ ProtocolVersion2Compatible = 2
+
+ ProtocolVersionMax = 5
+)
+
+// messageType is an integer ID of a type of message that can be received
+// on network channels from other members.
+type messageType uint8
+
+// The list of available message types.
+const (
+ pingMsg messageType = iota
+ indirectPingMsg
+ ackRespMsg
+ suspectMsg
+ aliveMsg
+ deadMsg
+ pushPullMsg
+ compoundMsg
+ userMsg // User mesg, not handled by us
+ compressMsg
+ encryptMsg
+ nackRespMsg
+ hasCrcMsg
+)
+
+// compressionType is used to specify the compression algorithm
+type compressionType uint8
+
+const (
+ lzwAlgo compressionType = iota
+)
+
+const (
+ MetaMaxSize = 512 // Maximum size for node meta data
+ compoundHeaderOverhead = 2 // Assumed header overhead
+ compoundOverhead = 2 // Assumed overhead per entry in compoundHeader
+ userMsgOverhead = 1
+ blockingWarning = 10 * time.Millisecond // Warn if a UDP packet takes this long to process
+ maxPushStateBytes = 10 * 1024 * 1024
+)
+
+// ping request sent directly to node
+type ping struct {
+ SeqNo uint32
+
+ // Node is sent so the target can verify they are
+ // the intended recipient. This is to protect again an agent
+ // restart with a new name.
+ Node string
+}
+
+// indirect ping sent to an indirect ndoe
+type indirectPingReq struct {
+ SeqNo uint32
+ Target []byte
+ Port uint16
+ Node string
+ Nack bool // true if we'd like a nack back
+}
+
+// ack response is sent for a ping
+type ackResp struct {
+ SeqNo uint32
+ Payload []byte
+}
+
+// nack response is sent for an indirect ping when the pinger doesn't hear from
+// the ping-ee within the configured timeout. This lets the original node know
+// that the indirect ping attempt happened but didn't succeed.
+type nackResp struct {
+ SeqNo uint32
+}
+
+// suspect is broadcast when we suspect a node is dead
+type suspect struct {
+ Incarnation uint32
+ Node string
+ From string // Include who is suspecting
+}
+
+// alive is broadcast when we know a node is alive.
+// Overloaded for nodes joining
+type alive struct {
+ Incarnation uint32
+ Node string
+ Addr []byte
+ Port uint16
+ Meta []byte
+
+ // The versions of the protocol/delegate that are being spoken, order:
+ // pmin, pmax, pcur, dmin, dmax, dcur
+ Vsn []uint8
+}
+
+// dead is broadcast when we confirm a node is dead
+// Overloaded for nodes leaving
+type dead struct {
+ Incarnation uint32
+ Node string
+ From string // Include who is suspecting
+}
+
+// pushPullHeader is used to inform the
+// otherside how many states we are transferring
+type pushPullHeader struct {
+ Nodes int
+ UserStateLen int // Encodes the byte lengh of user state
+ Join bool // Is this a join request or a anti-entropy run
+}
+
+// userMsgHeader is used to encapsulate a userMsg
+type userMsgHeader struct {
+ UserMsgLen int // Encodes the byte lengh of user state
+}
+
+// pushNodeState is used for pushPullReq when we are
+// transferring out node states
+type pushNodeState struct {
+ Name string
+ Addr []byte
+ Port uint16
+ Meta []byte
+ Incarnation uint32
+ State nodeStateType
+ Vsn []uint8 // Protocol versions
+}
+
+// compress is used to wrap an underlying payload
+// using a specified compression algorithm
+type compress struct {
+ Algo compressionType
+ Buf []byte
+}
+
+// msgHandoff is used to transfer a message between goroutines
+type msgHandoff struct {
+ msgType messageType
+ buf []byte
+ from net.Addr
+}
+
+// encryptionVersion returns the encryption version to use
+func (m *Memberlist) encryptionVersion() encryptionVersion {
+ switch m.ProtocolVersion() {
+ case 1:
+ return 0
+ default:
+ return 1
+ }
+}
+
+// streamListen is a long running goroutine that pulls incoming streams from the
+// transport and hands them off for processing.
+func (m *Memberlist) streamListen() {
+ for {
+ select {
+ case conn := <-m.transport.StreamCh():
+ go m.handleConn(conn)
+
+ case <-m.shutdownCh:
+ return
+ }
+ }
+}
+
+// handleConn handles a single incoming stream connection from the transport.
+func (m *Memberlist) handleConn(conn net.Conn) {
+ m.logger.Printf("[DEBUG] memberlist: Stream connection %s", LogConn(conn))
+
+ defer conn.Close()
+ metrics.IncrCounter([]string{"memberlist", "tcp", "accept"}, 1)
+
+ conn.SetDeadline(time.Now().Add(m.config.TCPTimeout))
+ msgType, bufConn, dec, err := m.readStream(conn)
+ if err != nil {
+ if err != io.EOF {
+ m.logger.Printf("[ERR] memberlist: failed to receive: %s %s", err, LogConn(conn))
+ }
+ return
+ }
+
+ switch msgType {
+ case userMsg:
+ if err := m.readUserMsg(bufConn, dec); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to receive user message: %s %s", err, LogConn(conn))
+ }
+ case pushPullMsg:
+ join, remoteNodes, userState, err := m.readRemoteState(bufConn, dec)
+ if err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to read remote state: %s %s", err, LogConn(conn))
+ return
+ }
+
+ if err := m.sendLocalState(conn, join); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to push local state: %s %s", err, LogConn(conn))
+ return
+ }
+
+ if err := m.mergeRemoteState(join, remoteNodes, userState); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed push/pull merge: %s %s", err, LogConn(conn))
+ return
+ }
+ case pingMsg:
+ var p ping
+ if err := dec.Decode(&p); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to decode ping: %s %s", err, LogConn(conn))
+ return
+ }
+
+ if p.Node != "" && p.Node != m.config.Name {
+ m.logger.Printf("[WARN] memberlist: Got ping for unexpected node %s %s", p.Node, LogConn(conn))
+ return
+ }
+
+ ack := ackResp{p.SeqNo, nil}
+ out, err := encode(ackRespMsg, &ack)
+ if err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to encode ack: %s", err)
+ return
+ }
+
+ err = m.rawSendMsgStream(conn, out.Bytes())
+ if err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to send ack: %s %s", err, LogConn(conn))
+ return
+ }
+ default:
+ m.logger.Printf("[ERR] memberlist: Received invalid msgType (%d) %s", msgType, LogConn(conn))
+ }
+}
+
+// packetListen is a long running goroutine that pulls packets out of the
+// transport and hands them off for processing.
+func (m *Memberlist) packetListen() {
+ for {
+ select {
+ case packet := <-m.transport.PacketCh():
+ m.ingestPacket(packet.Buf, packet.From, packet.Timestamp)
+
+ case <-m.shutdownCh:
+ return
+ }
+ }
+}
+
+func (m *Memberlist) ingestPacket(buf []byte, from net.Addr, timestamp time.Time) {
+ // Check if encryption is enabled
+ if m.config.EncryptionEnabled() {
+ // Decrypt the payload
+ plain, err := decryptPayload(m.config.Keyring.GetKeys(), buf, nil)
+ if err != nil {
+ m.logger.Printf("[ERR] memberlist: Decrypt packet failed: %v %s", err, LogAddress(from))
+ return
+ }
+
+ // Continue processing the plaintext buffer
+ buf = plain
+ }
+
+ // See if there's a checksum included to verify the contents of the message
+ if len(buf) >= 5 && messageType(buf[0]) == hasCrcMsg {
+ crc := crc32.ChecksumIEEE(buf[5:])
+ expected := binary.BigEndian.Uint32(buf[1:5])
+ if crc != expected {
+ m.logger.Printf("[WARN] memberlist: Got invalid checksum for UDP packet: %x, %x", crc, expected)
+ return
+ }
+ m.handleCommand(buf[5:], from, timestamp)
+ } else {
+ m.handleCommand(buf, from, timestamp)
+ }
+}
+
+func (m *Memberlist) handleCommand(buf []byte, from net.Addr, timestamp time.Time) {
+ // Decode the message type
+ msgType := messageType(buf[0])
+ buf = buf[1:]
+
+ // Switch on the msgType
+ switch msgType {
+ case compoundMsg:
+ m.handleCompound(buf, from, timestamp)
+ case compressMsg:
+ m.handleCompressed(buf, from, timestamp)
+
+ case pingMsg:
+ m.handlePing(buf, from)
+ case indirectPingMsg:
+ m.handleIndirectPing(buf, from)
+ case ackRespMsg:
+ m.handleAck(buf, from, timestamp)
+ case nackRespMsg:
+ m.handleNack(buf, from)
+
+ case suspectMsg:
+ fallthrough
+ case aliveMsg:
+ fallthrough
+ case deadMsg:
+ fallthrough
+ case userMsg:
+ select {
+ case m.handoff <- msgHandoff{msgType, buf, from}:
+ default:
+ m.logger.Printf("[WARN] memberlist: handler queue full, dropping message (%d) %s", msgType, LogAddress(from))
+ }
+
+ default:
+ m.logger.Printf("[ERR] memberlist: msg type (%d) not supported %s", msgType, LogAddress(from))
+ }
+}
+
+// packetHandler is a long running goroutine that processes messages received
+// over the packet interface, but is decoupled from the listener to avoid
+// blocking the listener which may cause ping/ack messages to be delayed.
+func (m *Memberlist) packetHandler() {
+ for {
+ select {
+ case msg := <-m.handoff:
+ msgType := msg.msgType
+ buf := msg.buf
+ from := msg.from
+
+ switch msgType {
+ case suspectMsg:
+ m.handleSuspect(buf, from)
+ case aliveMsg:
+ m.handleAlive(buf, from)
+ case deadMsg:
+ m.handleDead(buf, from)
+ case userMsg:
+ m.handleUser(buf, from)
+ default:
+ m.logger.Printf("[ERR] memberlist: Message type (%d) not supported %s (packet handler)", msgType, LogAddress(from))
+ }
+
+ case <-m.shutdownCh:
+ return
+ }
+ }
+}
+
+func (m *Memberlist) handleCompound(buf []byte, from net.Addr, timestamp time.Time) {
+ // Decode the parts
+ trunc, parts, err := decodeCompoundMessage(buf)
+ if err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to decode compound request: %s %s", err, LogAddress(from))
+ return
+ }
+
+ // Log any truncation
+ if trunc > 0 {
+ m.logger.Printf("[WARN] memberlist: Compound request had %d truncated messages %s", trunc, LogAddress(from))
+ }
+
+ // Handle each message
+ for _, part := range parts {
+ m.handleCommand(part, from, timestamp)
+ }
+}
+
+func (m *Memberlist) handlePing(buf []byte, from net.Addr) {
+ var p ping
+ if err := decode(buf, &p); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to decode ping request: %s %s", err, LogAddress(from))
+ return
+ }
+ // If node is provided, verify that it is for us
+ if p.Node != "" && p.Node != m.config.Name {
+ m.logger.Printf("[WARN] memberlist: Got ping for unexpected node '%s' %s", p.Node, LogAddress(from))
+ return
+ }
+ var ack ackResp
+ ack.SeqNo = p.SeqNo
+ if m.config.Ping != nil {
+ ack.Payload = m.config.Ping.AckPayload()
+ }
+ if err := m.encodeAndSendMsg(from.String(), ackRespMsg, &ack); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to send ack: %s %s", err, LogAddress(from))
+ }
+}
+
+func (m *Memberlist) handleIndirectPing(buf []byte, from net.Addr) {
+ var ind indirectPingReq
+ if err := decode(buf, &ind); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to decode indirect ping request: %s %s", err, LogAddress(from))
+ return
+ }
+
+ // For proto versions < 2, there is no port provided. Mask old
+ // behavior by using the configured port.
+ if m.ProtocolVersion() < 2 || ind.Port == 0 {
+ ind.Port = uint16(m.config.BindPort)
+ }
+
+ // Send a ping to the correct host.
+ localSeqNo := m.nextSeqNo()
+ ping := ping{SeqNo: localSeqNo, Node: ind.Node}
+
+ // Setup a response handler to relay the ack
+ cancelCh := make(chan struct{})
+ respHandler := func(payload []byte, timestamp time.Time) {
+ // Try to prevent the nack if we've caught it in time.
+ close(cancelCh)
+
+ // Forward the ack back to the requestor.
+ ack := ackResp{ind.SeqNo, nil}
+ if err := m.encodeAndSendMsg(from.String(), ackRespMsg, &ack); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to forward ack: %s %s", err, LogAddress(from))
+ }
+ }
+ m.setAckHandler(localSeqNo, respHandler, m.config.ProbeTimeout)
+
+ // Send the ping.
+ addr := joinHostPort(net.IP(ind.Target).String(), ind.Port)
+ if err := m.encodeAndSendMsg(addr, pingMsg, &ping); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to send ping: %s %s", err, LogAddress(from))
+ }
+
+ // Setup a timer to fire off a nack if no ack is seen in time.
+ if ind.Nack {
+ go func() {
+ select {
+ case <-cancelCh:
+ return
+ case <-time.After(m.config.ProbeTimeout):
+ nack := nackResp{ind.SeqNo}
+ if err := m.encodeAndSendMsg(from.String(), nackRespMsg, &nack); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to send nack: %s %s", err, LogAddress(from))
+ }
+ }
+ }()
+ }
+}
+
+func (m *Memberlist) handleAck(buf []byte, from net.Addr, timestamp time.Time) {
+ var ack ackResp
+ if err := decode(buf, &ack); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to decode ack response: %s %s", err, LogAddress(from))
+ return
+ }
+ m.invokeAckHandler(ack, timestamp)
+}
+
+func (m *Memberlist) handleNack(buf []byte, from net.Addr) {
+ var nack nackResp
+ if err := decode(buf, &nack); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to decode nack response: %s %s", err, LogAddress(from))
+ return
+ }
+ m.invokeNackHandler(nack)
+}
+
+func (m *Memberlist) handleSuspect(buf []byte, from net.Addr) {
+ var sus suspect
+ if err := decode(buf, &sus); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to decode suspect message: %s %s", err, LogAddress(from))
+ return
+ }
+ m.suspectNode(&sus)
+}
+
+func (m *Memberlist) handleAlive(buf []byte, from net.Addr) {
+ var live alive
+ if err := decode(buf, &live); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to decode alive message: %s %s", err, LogAddress(from))
+ return
+ }
+
+ // For proto versions < 2, there is no port provided. Mask old
+ // behavior by using the configured port
+ if m.ProtocolVersion() < 2 || live.Port == 0 {
+ live.Port = uint16(m.config.BindPort)
+ }
+
+ m.aliveNode(&live, nil, false)
+}
+
+func (m *Memberlist) handleDead(buf []byte, from net.Addr) {
+ var d dead
+ if err := decode(buf, &d); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to decode dead message: %s %s", err, LogAddress(from))
+ return
+ }
+ m.deadNode(&d)
+}
+
+// handleUser is used to notify channels of incoming user data
+func (m *Memberlist) handleUser(buf []byte, from net.Addr) {
+ d := m.config.Delegate
+ if d != nil {
+ d.NotifyMsg(buf)
+ }
+}
+
+// handleCompressed is used to unpack a compressed message
+func (m *Memberlist) handleCompressed(buf []byte, from net.Addr, timestamp time.Time) {
+ // Try to decode the payload
+ payload, err := decompressPayload(buf)
+ if err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to decompress payload: %v %s", err, LogAddress(from))
+ return
+ }
+
+ // Recursively handle the payload
+ m.handleCommand(payload, from, timestamp)
+}
+
+// encodeAndSendMsg is used to combine the encoding and sending steps
+func (m *Memberlist) encodeAndSendMsg(addr string, msgType messageType, msg interface{}) error {
+ out, err := encode(msgType, msg)
+ if err != nil {
+ return err
+ }
+ if err := m.sendMsg(addr, out.Bytes()); err != nil {
+ return err
+ }
+ return nil
+}
+
+// sendMsg is used to send a message via packet to another host. It will
+// opportunistically create a compoundMsg and piggy back other broadcasts.
+func (m *Memberlist) sendMsg(addr string, msg []byte) error {
+ // Check if we can piggy back any messages
+ bytesAvail := m.config.UDPBufferSize - len(msg) - compoundHeaderOverhead
+ if m.config.EncryptionEnabled() {
+ bytesAvail -= encryptOverhead(m.encryptionVersion())
+ }
+ extra := m.getBroadcasts(compoundOverhead, bytesAvail)
+
+ // Fast path if nothing to piggypack
+ if len(extra) == 0 {
+ return m.rawSendMsgPacket(addr, nil, msg)
+ }
+
+ // Join all the messages
+ msgs := make([][]byte, 0, 1+len(extra))
+ msgs = append(msgs, msg)
+ msgs = append(msgs, extra...)
+
+ // Create a compound message
+ compound := makeCompoundMessage(msgs)
+
+ // Send the message
+ return m.rawSendMsgPacket(addr, nil, compound.Bytes())
+}
+
+// rawSendMsgPacket is used to send message via packet to another host without
+// modification, other than compression or encryption if enabled.
+func (m *Memberlist) rawSendMsgPacket(addr string, node *Node, msg []byte) error {
+ // Check if we have compression enabled
+ if m.config.EnableCompression {
+ buf, err := compressPayload(msg)
+ if err != nil {
+ m.logger.Printf("[WARN] memberlist: Failed to compress payload: %v", err)
+ } else {
+ // Only use compression if it reduced the size
+ if buf.Len() < len(msg) {
+ msg = buf.Bytes()
+ }
+ }
+ }
+
+ // Try to look up the destination node
+ if node == nil {
+ toAddr, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to parse address %q: %v", addr, err)
+ return err
+ }
+ m.nodeLock.RLock()
+ nodeState, ok := m.nodeMap[toAddr]
+ m.nodeLock.RUnlock()
+ if ok {
+ node = &nodeState.Node
+ }
+ }
+
+ // Add a CRC to the end of the payload if the recipient understands
+ // ProtocolVersion >= 5
+ if node != nil && node.PMax >= 5 {
+ crc := crc32.ChecksumIEEE(msg)
+ header := make([]byte, 5, 5+len(msg))
+ header[0] = byte(hasCrcMsg)
+ binary.BigEndian.PutUint32(header[1:], crc)
+ msg = append(header, msg...)
+ }
+
+ // Check if we have encryption enabled
+ if m.config.EncryptionEnabled() {
+ // Encrypt the payload
+ var buf bytes.Buffer
+ primaryKey := m.config.Keyring.GetPrimaryKey()
+ err := encryptPayload(m.encryptionVersion(), primaryKey, msg, nil, &buf)
+ if err != nil {
+ m.logger.Printf("[ERR] memberlist: Encryption of message failed: %v", err)
+ return err
+ }
+ msg = buf.Bytes()
+ }
+
+ metrics.IncrCounter([]string{"memberlist", "udp", "sent"}, float32(len(msg)))
+ _, err := m.transport.WriteTo(msg, addr)
+ return err
+}
+
+// rawSendMsgStream is used to stream a message to another host without
+// modification, other than applying compression and encryption if enabled.
+func (m *Memberlist) rawSendMsgStream(conn net.Conn, sendBuf []byte) error {
+ // Check if compresion is enabled
+ if m.config.EnableCompression {
+ compBuf, err := compressPayload(sendBuf)
+ if err != nil {
+ m.logger.Printf("[ERROR] memberlist: Failed to compress payload: %v", err)
+ } else {
+ sendBuf = compBuf.Bytes()
+ }
+ }
+
+ // Check if encryption is enabled
+ if m.config.EncryptionEnabled() {
+ crypt, err := m.encryptLocalState(sendBuf)
+ if err != nil {
+ m.logger.Printf("[ERROR] memberlist: Failed to encrypt local state: %v", err)
+ return err
+ }
+ sendBuf = crypt
+ }
+
+ // Write out the entire send buffer
+ metrics.IncrCounter([]string{"memberlist", "tcp", "sent"}, float32(len(sendBuf)))
+
+ if n, err := conn.Write(sendBuf); err != nil {
+ return err
+ } else if n != len(sendBuf) {
+ return fmt.Errorf("only %d of %d bytes written", n, len(sendBuf))
+ }
+
+ return nil
+}
+
+// sendUserMsg is used to stream a user message to another host.
+func (m *Memberlist) sendUserMsg(addr string, sendBuf []byte) error {
+ conn, err := m.transport.DialTimeout(addr, m.config.TCPTimeout)
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+
+ bufConn := bytes.NewBuffer(nil)
+ if err := bufConn.WriteByte(byte(userMsg)); err != nil {
+ return err
+ }
+
+ header := userMsgHeader{UserMsgLen: len(sendBuf)}
+ hd := codec.MsgpackHandle{}
+ enc := codec.NewEncoder(bufConn, &hd)
+ if err := enc.Encode(&header); err != nil {
+ return err
+ }
+ if _, err := bufConn.Write(sendBuf); err != nil {
+ return err
+ }
+ return m.rawSendMsgStream(conn, bufConn.Bytes())
+}
+
+// sendAndReceiveState is used to initiate a push/pull over a stream with a
+// remote host.
+func (m *Memberlist) sendAndReceiveState(addr string, join bool) ([]pushNodeState, []byte, error) {
+ // Attempt to connect
+ conn, err := m.transport.DialTimeout(addr, m.config.TCPTimeout)
+ if err != nil {
+ return nil, nil, err
+ }
+ defer conn.Close()
+ m.logger.Printf("[DEBUG] memberlist: Initiating push/pull sync with: %s", conn.RemoteAddr())
+ metrics.IncrCounter([]string{"memberlist", "tcp", "connect"}, 1)
+
+ // Send our state
+ if err := m.sendLocalState(conn, join); err != nil {
+ return nil, nil, err
+ }
+
+ conn.SetDeadline(time.Now().Add(m.config.TCPTimeout))
+ msgType, bufConn, dec, err := m.readStream(conn)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ // Quit if not push/pull
+ if msgType != pushPullMsg {
+ err := fmt.Errorf("received invalid msgType (%d), expected pushPullMsg (%d) %s", msgType, pushPullMsg, LogConn(conn))
+ return nil, nil, err
+ }
+
+ // Read remote state
+ _, remoteNodes, userState, err := m.readRemoteState(bufConn, dec)
+ return remoteNodes, userState, err
+}
+
+// sendLocalState is invoked to send our local state over a stream connection.
+func (m *Memberlist) sendLocalState(conn net.Conn, join bool) error {
+ // Setup a deadline
+ conn.SetDeadline(time.Now().Add(m.config.TCPTimeout))
+
+ // Prepare the local node state
+ m.nodeLock.RLock()
+ localNodes := make([]pushNodeState, len(m.nodes))
+ for idx, n := range m.nodes {
+ localNodes[idx].Name = n.Name
+ localNodes[idx].Addr = n.Addr
+ localNodes[idx].Port = n.Port
+ localNodes[idx].Incarnation = n.Incarnation
+ localNodes[idx].State = n.State
+ localNodes[idx].Meta = n.Meta
+ localNodes[idx].Vsn = []uint8{
+ n.PMin, n.PMax, n.PCur,
+ n.DMin, n.DMax, n.DCur,
+ }
+ }
+ m.nodeLock.RUnlock()
+
+ // Get the delegate state
+ var userData []byte
+ if m.config.Delegate != nil {
+ userData = m.config.Delegate.LocalState(join)
+ }
+
+ // Create a bytes buffer writer
+ bufConn := bytes.NewBuffer(nil)
+
+ // Send our node state
+ header := pushPullHeader{Nodes: len(localNodes), UserStateLen: len(userData), Join: join}
+ hd := codec.MsgpackHandle{}
+ enc := codec.NewEncoder(bufConn, &hd)
+
+ // Begin state push
+ if _, err := bufConn.Write([]byte{byte(pushPullMsg)}); err != nil {
+ return err
+ }
+
+ if err := enc.Encode(&header); err != nil {
+ return err
+ }
+ for i := 0; i < header.Nodes; i++ {
+ if err := enc.Encode(&localNodes[i]); err != nil {
+ return err
+ }
+ }
+
+ // Write the user state as well
+ if userData != nil {
+ if _, err := bufConn.Write(userData); err != nil {
+ return err
+ }
+ }
+
+ // Get the send buffer
+ return m.rawSendMsgStream(conn, bufConn.Bytes())
+}
+
+// encryptLocalState is used to help encrypt local state before sending
+func (m *Memberlist) encryptLocalState(sendBuf []byte) ([]byte, error) {
+ var buf bytes.Buffer
+
+ // Write the encryptMsg byte
+ buf.WriteByte(byte(encryptMsg))
+
+ // Write the size of the message
+ sizeBuf := make([]byte, 4)
+ encVsn := m.encryptionVersion()
+ encLen := encryptedLength(encVsn, len(sendBuf))
+ binary.BigEndian.PutUint32(sizeBuf, uint32(encLen))
+ buf.Write(sizeBuf)
+
+ // Write the encrypted cipher text to the buffer
+ key := m.config.Keyring.GetPrimaryKey()
+ err := encryptPayload(encVsn, key, sendBuf, buf.Bytes()[:5], &buf)
+ if err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+// decryptRemoteState is used to help decrypt the remote state
+func (m *Memberlist) decryptRemoteState(bufConn io.Reader) ([]byte, error) {
+ // Read in enough to determine message length
+ cipherText := bytes.NewBuffer(nil)
+ cipherText.WriteByte(byte(encryptMsg))
+ _, err := io.CopyN(cipherText, bufConn, 4)
+ if err != nil {
+ return nil, err
+ }
+
+ // Ensure we aren't asked to download too much. This is to guard against
+ // an attack vector where a huge amount of state is sent
+ moreBytes := binary.BigEndian.Uint32(cipherText.Bytes()[1:5])
+ if moreBytes > maxPushStateBytes {
+ return nil, fmt.Errorf("Remote node state is larger than limit (%d)", moreBytes)
+ }
+
+ // Read in the rest of the payload
+ _, err = io.CopyN(cipherText, bufConn, int64(moreBytes))
+ if err != nil {
+ return nil, err
+ }
+
+ // Decrypt the cipherText
+ dataBytes := cipherText.Bytes()[:5]
+ cipherBytes := cipherText.Bytes()[5:]
+
+ // Decrypt the payload
+ keys := m.config.Keyring.GetKeys()
+ return decryptPayload(keys, cipherBytes, dataBytes)
+}
+
+// readStream is used to read from a stream connection, decrypting and
+// decompressing the stream if necessary.
+func (m *Memberlist) readStream(conn net.Conn) (messageType, io.Reader, *codec.Decoder, error) {
+ // Created a buffered reader
+ var bufConn io.Reader = bufio.NewReader(conn)
+
+ // Read the message type
+ buf := [1]byte{0}
+ if _, err := bufConn.Read(buf[:]); err != nil {
+ return 0, nil, nil, err
+ }
+ msgType := messageType(buf[0])
+
+ // Check if the message is encrypted
+ if msgType == encryptMsg {
+ if !m.config.EncryptionEnabled() {
+ return 0, nil, nil,
+ fmt.Errorf("Remote state is encrypted and encryption is not configured")
+ }
+
+ plain, err := m.decryptRemoteState(bufConn)
+ if err != nil {
+ return 0, nil, nil, err
+ }
+
+ // Reset message type and bufConn
+ msgType = messageType(plain[0])
+ bufConn = bytes.NewReader(plain[1:])
+ } else if m.config.EncryptionEnabled() {
+ return 0, nil, nil,
+ fmt.Errorf("Encryption is configured but remote state is not encrypted")
+ }
+
+ // Get the msgPack decoders
+ hd := codec.MsgpackHandle{}
+ dec := codec.NewDecoder(bufConn, &hd)
+
+ // Check if we have a compressed message
+ if msgType == compressMsg {
+ var c compress
+ if err := dec.Decode(&c); err != nil {
+ return 0, nil, nil, err
+ }
+ decomp, err := decompressBuffer(&c)
+ if err != nil {
+ return 0, nil, nil, err
+ }
+
+ // Reset the message type
+ msgType = messageType(decomp[0])
+
+ // Create a new bufConn
+ bufConn = bytes.NewReader(decomp[1:])
+
+ // Create a new decoder
+ dec = codec.NewDecoder(bufConn, &hd)
+ }
+
+ return msgType, bufConn, dec, nil
+}
+
+// readRemoteState is used to read the remote state from a connection
+func (m *Memberlist) readRemoteState(bufConn io.Reader, dec *codec.Decoder) (bool, []pushNodeState, []byte, error) {
+ // Read the push/pull header
+ var header pushPullHeader
+ if err := dec.Decode(&header); err != nil {
+ return false, nil, nil, err
+ }
+
+ // Allocate space for the transfer
+ remoteNodes := make([]pushNodeState, header.Nodes)
+
+ // Try to decode all the states
+ for i := 0; i < header.Nodes; i++ {
+ if err := dec.Decode(&remoteNodes[i]); err != nil {
+ return false, nil, nil, err
+ }
+ }
+
+ // Read the remote user state into a buffer
+ var userBuf []byte
+ if header.UserStateLen > 0 {
+ userBuf = make([]byte, header.UserStateLen)
+ bytes, err := io.ReadAtLeast(bufConn, userBuf, header.UserStateLen)
+ if err == nil && bytes != header.UserStateLen {
+ err = fmt.Errorf(
+ "Failed to read full user state (%d / %d)",
+ bytes, header.UserStateLen)
+ }
+ if err != nil {
+ return false, nil, nil, err
+ }
+ }
+
+ // For proto versions < 2, there is no port provided. Mask old
+ // behavior by using the configured port
+ for idx := range remoteNodes {
+ if m.ProtocolVersion() < 2 || remoteNodes[idx].Port == 0 {
+ remoteNodes[idx].Port = uint16(m.config.BindPort)
+ }
+ }
+
+ return header.Join, remoteNodes, userBuf, nil
+}
+
+// mergeRemoteState is used to merge the remote state with our local state
+func (m *Memberlist) mergeRemoteState(join bool, remoteNodes []pushNodeState, userBuf []byte) error {
+ if err := m.verifyProtocol(remoteNodes); err != nil {
+ return err
+ }
+
+ // Invoke the merge delegate if any
+ if join && m.config.Merge != nil {
+ nodes := make([]*Node, len(remoteNodes))
+ for idx, n := range remoteNodes {
+ nodes[idx] = &Node{
+ Name: n.Name,
+ Addr: n.Addr,
+ Port: n.Port,
+ Meta: n.Meta,
+ PMin: n.Vsn[0],
+ PMax: n.Vsn[1],
+ PCur: n.Vsn[2],
+ DMin: n.Vsn[3],
+ DMax: n.Vsn[4],
+ DCur: n.Vsn[5],
+ }
+ }
+ if err := m.config.Merge.NotifyMerge(nodes); err != nil {
+ return err
+ }
+ }
+
+ // Merge the membership state
+ m.mergeState(remoteNodes)
+
+ // Invoke the delegate for user state
+ if userBuf != nil && m.config.Delegate != nil {
+ m.config.Delegate.MergeRemoteState(userBuf, join)
+ }
+ return nil
+}
+
+// readUserMsg is used to decode a userMsg from a stream.
+func (m *Memberlist) readUserMsg(bufConn io.Reader, dec *codec.Decoder) error {
+ // Read the user message header
+ var header userMsgHeader
+ if err := dec.Decode(&header); err != nil {
+ return err
+ }
+
+ // Read the user message into a buffer
+ var userBuf []byte
+ if header.UserMsgLen > 0 {
+ userBuf = make([]byte, header.UserMsgLen)
+ bytes, err := io.ReadAtLeast(bufConn, userBuf, header.UserMsgLen)
+ if err == nil && bytes != header.UserMsgLen {
+ err = fmt.Errorf(
+ "Failed to read full user message (%d / %d)",
+ bytes, header.UserMsgLen)
+ }
+ if err != nil {
+ return err
+ }
+
+ d := m.config.Delegate
+ if d != nil {
+ d.NotifyMsg(userBuf)
+ }
+ }
+
+ return nil
+}
+
+// sendPingAndWaitForAck makes a stream connection to the given address, sends
+// a ping, and waits for an ack. All of this is done as a series of blocking
+// operations, given the deadline. The bool return parameter is true if we
+// we able to round trip a ping to the other node.
+func (m *Memberlist) sendPingAndWaitForAck(addr string, ping ping, deadline time.Time) (bool, error) {
+ conn, err := m.transport.DialTimeout(addr, m.config.TCPTimeout)
+ if err != nil {
+ // If the node is actually dead we expect this to fail, so we
+ // shouldn't spam the logs with it. After this point, errors
+ // with the connection are real, unexpected errors and should
+ // get propagated up.
+ return false, nil
+ }
+ defer conn.Close()
+ conn.SetDeadline(deadline)
+
+ out, err := encode(pingMsg, &ping)
+ if err != nil {
+ return false, err
+ }
+
+ if err = m.rawSendMsgStream(conn, out.Bytes()); err != nil {
+ return false, err
+ }
+
+ msgType, _, dec, err := m.readStream(conn)
+ if err != nil {
+ return false, err
+ }
+
+ if msgType != ackRespMsg {
+ return false, fmt.Errorf("Unexpected msgType (%d) from ping %s", msgType, LogConn(conn))
+ }
+
+ var ack ackResp
+ if err = dec.Decode(&ack); err != nil {
+ return false, err
+ }
+
+ if ack.SeqNo != ping.SeqNo {
+ return false, fmt.Errorf("Sequence number from ack (%d) doesn't match ping (%d)", ack.SeqNo, ping.SeqNo, LogConn(conn))
+ }
+
+ return true, nil
+}
diff --git a/vendor/github.com/hashicorp/memberlist/net_transport.go b/vendor/github.com/hashicorp/memberlist/net_transport.go
new file mode 100644
index 0000000..e7b88b0
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/net_transport.go
@@ -0,0 +1,289 @@
+package memberlist
+
+import (
+ "fmt"
+ "log"
+ "net"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/armon/go-metrics"
+ sockaddr "github.com/hashicorp/go-sockaddr"
+)
+
+const (
+ // udpPacketBufSize is used to buffer incoming packets during read
+ // operations.
+ udpPacketBufSize = 65536
+
+ // udpRecvBufSize is a large buffer size that we attempt to set UDP
+ // sockets to in order to handle a large volume of messages.
+ udpRecvBufSize = 2 * 1024 * 1024
+)
+
+// NetTransportConfig is used to configure a net transport.
+type NetTransportConfig struct {
+ // BindAddrs is a list of addresses to bind to for both TCP and UDP
+ // communications.
+ BindAddrs []string
+
+ // BindPort is the port to listen on, for each address above.
+ BindPort int
+
+ // Logger is a logger for operator messages.
+ Logger *log.Logger
+}
+
+// NetTransport is a Transport implementation that uses connectionless UDP for
+// packet operations, and ad-hoc TCP connections for stream operations.
+type NetTransport struct {
+ config *NetTransportConfig
+ packetCh chan *Packet
+ streamCh chan net.Conn
+ logger *log.Logger
+ wg sync.WaitGroup
+ tcpListeners []*net.TCPListener
+ udpListeners []*net.UDPConn
+ shutdown int32
+}
+
+// NewNetTransport returns a net transport with the given configuration. On
+// success all the network listeners will be created and listening.
+func NewNetTransport(config *NetTransportConfig) (*NetTransport, error) {
+ // If we reject the empty list outright we can assume that there's at
+ // least one listener of each type later during operation.
+ if len(config.BindAddrs) == 0 {
+ return nil, fmt.Errorf("At least one bind address is required")
+ }
+
+ // Build out the new transport.
+ var ok bool
+ t := NetTransport{
+ config: config,
+ packetCh: make(chan *Packet),
+ streamCh: make(chan net.Conn),
+ logger: config.Logger,
+ }
+
+ // Clean up listeners if there's an error.
+ defer func() {
+ if !ok {
+ t.Shutdown()
+ }
+ }()
+
+ // Build all the TCP and UDP listeners.
+ port := config.BindPort
+ for _, addr := range config.BindAddrs {
+ ip := net.ParseIP(addr)
+
+ tcpAddr := &net.TCPAddr{IP: ip, Port: port}
+ tcpLn, err := net.ListenTCP("tcp", tcpAddr)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to start TCP listener on %q port %d: %v", addr, port, err)
+ }
+ t.tcpListeners = append(t.tcpListeners, tcpLn)
+
+ // If the config port given was zero, use the first TCP listener
+ // to pick an available port and then apply that to everything
+ // else.
+ if port == 0 {
+ port = tcpLn.Addr().(*net.TCPAddr).Port
+ }
+
+ udpAddr := &net.UDPAddr{IP: ip, Port: port}
+ udpLn, err := net.ListenUDP("udp", udpAddr)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to start UDP listener on %q port %d: %v", addr, port, err)
+ }
+ if err := setUDPRecvBuf(udpLn); err != nil {
+ return nil, fmt.Errorf("Failed to resize UDP buffer: %v", err)
+ }
+ t.udpListeners = append(t.udpListeners, udpLn)
+ }
+
+ // Fire them up now that we've been able to create them all.
+ for i := 0; i < len(config.BindAddrs); i++ {
+ t.wg.Add(2)
+ go t.tcpListen(t.tcpListeners[i])
+ go t.udpListen(t.udpListeners[i])
+ }
+
+ ok = true
+ return &t, nil
+}
+
+// GetAutoBindPort returns the bind port that was automatically given by the
+// kernel, if a bind port of 0 was given.
+func (t *NetTransport) GetAutoBindPort() int {
+ // We made sure there's at least one TCP listener, and that one's
+ // port was applied to all the others for the dynamic bind case.
+ return t.tcpListeners[0].Addr().(*net.TCPAddr).Port
+}
+
+// See Transport.
+func (t *NetTransport) FinalAdvertiseAddr(ip string, port int) (net.IP, int, error) {
+ var advertiseAddr net.IP
+ var advertisePort int
+ if ip != "" {
+ // If they've supplied an address, use that.
+ advertiseAddr = net.ParseIP(ip)
+ if advertiseAddr == nil {
+ return nil, 0, fmt.Errorf("Failed to parse advertise address %q", ip)
+ }
+
+ // Ensure IPv4 conversion if necessary.
+ if ip4 := advertiseAddr.To4(); ip4 != nil {
+ advertiseAddr = ip4
+ }
+ advertisePort = port
+ } else {
+ if t.config.BindAddrs[0] == "0.0.0.0" {
+ // Otherwise, if we're not bound to a specific IP, let's
+ // use a suitable private IP address.
+ var err error
+ ip, err = sockaddr.GetPrivateIP()
+ if err != nil {
+ return nil, 0, fmt.Errorf("Failed to get interface addresses: %v", err)
+ }
+ if ip == "" {
+ return nil, 0, fmt.Errorf("No private IP address found, and explicit IP not provided")
+ }
+
+ advertiseAddr = net.ParseIP(ip)
+ if advertiseAddr == nil {
+ return nil, 0, fmt.Errorf("Failed to parse advertise address: %q", ip)
+ }
+ } else {
+ // Use the IP that we're bound to, based on the first
+ // TCP listener, which we already ensure is there.
+ advertiseAddr = t.tcpListeners[0].Addr().(*net.TCPAddr).IP
+ }
+
+ // Use the port we are bound to.
+ advertisePort = t.GetAutoBindPort()
+ }
+
+ return advertiseAddr, advertisePort, nil
+}
+
+// See Transport.
+func (t *NetTransport) WriteTo(b []byte, addr string) (time.Time, error) {
+ udpAddr, err := net.ResolveUDPAddr("udp", addr)
+ if err != nil {
+ return time.Time{}, err
+ }
+
+ // We made sure there's at least one UDP listener, so just use the
+ // packet sending interface on the first one. Take the time after the
+ // write call comes back, which will underestimate the time a little,
+ // but help account for any delays before the write occurs.
+ _, err = t.udpListeners[0].WriteTo(b, udpAddr)
+ return time.Now(), err
+}
+
+// See Transport.
+func (t *NetTransport) PacketCh() <-chan *Packet {
+ return t.packetCh
+}
+
+// See Transport.
+func (t *NetTransport) DialTimeout(addr string, timeout time.Duration) (net.Conn, error) {
+ dialer := net.Dialer{Timeout: timeout}
+ return dialer.Dial("tcp", addr)
+}
+
+// See Transport.
+func (t *NetTransport) StreamCh() <-chan net.Conn {
+ return t.streamCh
+}
+
+// See Transport.
+func (t *NetTransport) Shutdown() error {
+ // This will avoid log spam about errors when we shut down.
+ atomic.StoreInt32(&t.shutdown, 1)
+
+ // Rip through all the connections and shut them down.
+ for _, conn := range t.tcpListeners {
+ conn.Close()
+ }
+ for _, conn := range t.udpListeners {
+ conn.Close()
+ }
+
+ // Block until all the listener threads have died.
+ t.wg.Wait()
+ return nil
+}
+
+// tcpListen is a long running goroutine that accepts incoming TCP connections
+// and hands them off to the stream channel.
+func (t *NetTransport) tcpListen(tcpLn *net.TCPListener) {
+ defer t.wg.Done()
+ for {
+ conn, err := tcpLn.AcceptTCP()
+ if err != nil {
+ if s := atomic.LoadInt32(&t.shutdown); s == 1 {
+ break
+ }
+
+ t.logger.Printf("[ERR] memberlist: Error accepting TCP connection: %v", err)
+ continue
+ }
+
+ t.streamCh <- conn
+ }
+}
+
+// udpListen is a long running goroutine that accepts incoming UDP packets and
+// hands them off to the packet channel.
+func (t *NetTransport) udpListen(udpLn *net.UDPConn) {
+ defer t.wg.Done()
+ for {
+ // Do a blocking read into a fresh buffer. Grab a time stamp as
+ // close as possible to the I/O.
+ buf := make([]byte, udpPacketBufSize)
+ n, addr, err := udpLn.ReadFrom(buf)
+ ts := time.Now()
+ if err != nil {
+ if s := atomic.LoadInt32(&t.shutdown); s == 1 {
+ break
+ }
+
+ t.logger.Printf("[ERR] memberlist: Error reading UDP packet: %v", err)
+ continue
+ }
+
+ // Check the length - it needs to have at least one byte to be a
+ // proper message.
+ if n < 1 {
+ t.logger.Printf("[ERR] memberlist: UDP packet too short (%d bytes) %s",
+ len(buf), LogAddress(addr))
+ continue
+ }
+
+ // Ingest the packet.
+ metrics.IncrCounter([]string{"memberlist", "udp", "received"}, float32(n))
+ t.packetCh <- &Packet{
+ Buf: buf[:n],
+ From: addr,
+ Timestamp: ts,
+ }
+ }
+}
+
+// setUDPRecvBuf is used to resize the UDP receive window. The function
+// attempts to set the read buffer to `udpRecvBuf` but backs off until
+// the read buffer can be set.
+func setUDPRecvBuf(c *net.UDPConn) error {
+ size := udpRecvBufSize
+ var err error
+ for size > 0 {
+ if err = c.SetReadBuffer(size); err == nil {
+ return nil
+ }
+ size = size / 2
+ }
+ return err
+}
diff --git a/vendor/github.com/hashicorp/memberlist/ping_delegate.go b/vendor/github.com/hashicorp/memberlist/ping_delegate.go
new file mode 100644
index 0000000..1566c8b
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/ping_delegate.go
@@ -0,0 +1,14 @@
+package memberlist
+
+import "time"
+
+// PingDelegate is used to notify an observer how long it took for a ping message to
+// complete a round trip. It can also be used for writing arbitrary byte slices
+// into ack messages. Note that in order to be meaningful for RTT estimates, this
+// delegate does not apply to indirect pings, nor fallback pings sent over TCP.
+type PingDelegate interface {
+ // AckPayload is invoked when an ack is being sent; the returned bytes will be appended to the ack
+ AckPayload() []byte
+ // NotifyPing is invoked when an ack for a ping is received
+ NotifyPingComplete(other *Node, rtt time.Duration, payload []byte)
+}
diff --git a/vendor/github.com/hashicorp/memberlist/queue.go b/vendor/github.com/hashicorp/memberlist/queue.go
new file mode 100644
index 0000000..994b90f
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/queue.go
@@ -0,0 +1,167 @@
+package memberlist
+
+import (
+ "sort"
+ "sync"
+)
+
+// TransmitLimitedQueue is used to queue messages to broadcast to
+// the cluster (via gossip) but limits the number of transmits per
+// message. It also prioritizes messages with lower transmit counts
+// (hence newer messages).
+type TransmitLimitedQueue struct {
+ // NumNodes returns the number of nodes in the cluster. This is
+ // used to determine the retransmit count, which is calculated
+ // based on the log of this.
+ NumNodes func() int
+
+ // RetransmitMult is the multiplier used to determine the maximum
+ // number of retransmissions attempted.
+ RetransmitMult int
+
+ sync.Mutex
+ bcQueue limitedBroadcasts
+}
+
+type limitedBroadcast struct {
+ transmits int // Number of transmissions attempted.
+ b Broadcast
+}
+type limitedBroadcasts []*limitedBroadcast
+
+// Broadcast is something that can be broadcasted via gossip to
+// the memberlist cluster.
+type Broadcast interface {
+ // Invalidates checks if enqueuing the current broadcast
+ // invalidates a previous broadcast
+ Invalidates(b Broadcast) bool
+
+ // Returns a byte form of the message
+ Message() []byte
+
+ // Finished is invoked when the message will no longer
+ // be broadcast, either due to invalidation or to the
+ // transmit limit being reached
+ Finished()
+}
+
+// QueueBroadcast is used to enqueue a broadcast
+func (q *TransmitLimitedQueue) QueueBroadcast(b Broadcast) {
+ q.Lock()
+ defer q.Unlock()
+
+ // Check if this message invalidates another
+ n := len(q.bcQueue)
+ for i := 0; i < n; i++ {
+ if b.Invalidates(q.bcQueue[i].b) {
+ q.bcQueue[i].b.Finished()
+ copy(q.bcQueue[i:], q.bcQueue[i+1:])
+ q.bcQueue[n-1] = nil
+ q.bcQueue = q.bcQueue[:n-1]
+ n--
+ }
+ }
+
+ // Append to the queue
+ q.bcQueue = append(q.bcQueue, &limitedBroadcast{0, b})
+}
+
+// GetBroadcasts is used to get a number of broadcasts, up to a byte limit
+// and applying a per-message overhead as provided.
+func (q *TransmitLimitedQueue) GetBroadcasts(overhead, limit int) [][]byte {
+ q.Lock()
+ defer q.Unlock()
+
+ // Fast path the default case
+ if len(q.bcQueue) == 0 {
+ return nil
+ }
+
+ transmitLimit := retransmitLimit(q.RetransmitMult, q.NumNodes())
+ bytesUsed := 0
+ var toSend [][]byte
+
+ for i := len(q.bcQueue) - 1; i >= 0; i-- {
+ // Check if this is within our limits
+ b := q.bcQueue[i]
+ msg := b.b.Message()
+ if bytesUsed+overhead+len(msg) > limit {
+ continue
+ }
+
+ // Add to slice to send
+ bytesUsed += overhead + len(msg)
+ toSend = append(toSend, msg)
+
+ // Check if we should stop transmission
+ b.transmits++
+ if b.transmits >= transmitLimit {
+ b.b.Finished()
+ n := len(q.bcQueue)
+ q.bcQueue[i], q.bcQueue[n-1] = q.bcQueue[n-1], nil
+ q.bcQueue = q.bcQueue[:n-1]
+ }
+ }
+
+ // If we are sending anything, we need to re-sort to deal
+ // with adjusted transmit counts
+ if len(toSend) > 0 {
+ q.bcQueue.Sort()
+ }
+ return toSend
+}
+
+// NumQueued returns the number of queued messages
+func (q *TransmitLimitedQueue) NumQueued() int {
+ q.Lock()
+ defer q.Unlock()
+ return len(q.bcQueue)
+}
+
+// Reset clears all the queued messages
+func (q *TransmitLimitedQueue) Reset() {
+ q.Lock()
+ defer q.Unlock()
+ for _, b := range q.bcQueue {
+ b.b.Finished()
+ }
+ q.bcQueue = nil
+}
+
+// Prune will retain the maxRetain latest messages, and the rest
+// will be discarded. This can be used to prevent unbounded queue sizes
+func (q *TransmitLimitedQueue) Prune(maxRetain int) {
+ q.Lock()
+ defer q.Unlock()
+
+ // Do nothing if queue size is less than the limit
+ n := len(q.bcQueue)
+ if n < maxRetain {
+ return
+ }
+
+ // Invalidate the messages we will be removing
+ for i := 0; i < n-maxRetain; i++ {
+ q.bcQueue[i].b.Finished()
+ }
+
+ // Move the messages, and retain only the last maxRetain
+ copy(q.bcQueue[0:], q.bcQueue[n-maxRetain:])
+ q.bcQueue = q.bcQueue[:maxRetain]
+}
+
+func (b limitedBroadcasts) Len() int {
+ return len(b)
+}
+
+func (b limitedBroadcasts) Less(i, j int) bool {
+ return b[i].transmits < b[j].transmits
+}
+
+func (b limitedBroadcasts) Swap(i, j int) {
+ b[i], b[j] = b[j], b[i]
+}
+
+func (b limitedBroadcasts) Sort() {
+ sort.Sort(sort.Reverse(b))
+}
diff --git a/vendor/github.com/hashicorp/memberlist/security.go b/vendor/github.com/hashicorp/memberlist/security.go
new file mode 100644
index 0000000..d90114e
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/security.go
@@ -0,0 +1,198 @@
+package memberlist
+
+import (
+ "bytes"
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rand"
+ "fmt"
+ "io"
+)
+
+/*
+
+Encrypted messages are prefixed with an encryptionVersion byte
+that is used for us to be able to properly encode/decode. We
+currently support the following versions:
+
+ 0 - AES-GCM 128, using PKCS7 padding
+ 1 - AES-GCM 128, no padding. Padding not needed, caused bloat.
+
+*/
+type encryptionVersion uint8
+
+const (
+ minEncryptionVersion encryptionVersion = 0
+ maxEncryptionVersion encryptionVersion = 1
+)
+
+const (
+ versionSize = 1
+ nonceSize = 12
+ tagSize = 16
+ maxPadOverhead = 16
+ blockSize = aes.BlockSize
+)
+
+// pkcs7encode is used to pad a byte buffer to a specific block size using
+// the PKCS7 algorithm. "Ignores" some bytes to compensate for IV
+func pkcs7encode(buf *bytes.Buffer, ignore, blockSize int) {
+ n := buf.Len() - ignore
+ more := blockSize - (n % blockSize)
+ for i := 0; i < more; i++ {
+ buf.WriteByte(byte(more))
+ }
+}
+
+// pkcs7decode is used to decode a buffer that has been padded
+func pkcs7decode(buf []byte, blockSize int) []byte {
+ if len(buf) == 0 {
+ panic("Cannot decode a PKCS7 buffer of zero length")
+ }
+ n := len(buf)
+ last := buf[n-1]
+ n -= int(last)
+ return buf[:n]
+}
+
+// encryptOverhead returns the maximum possible overhead of encryption by version
+func encryptOverhead(vsn encryptionVersion) int {
+ switch vsn {
+ case 0:
+ return 45 // Version: 1, IV: 12, Padding: 16, Tag: 16
+ case 1:
+ return 29 // Version: 1, IV: 12, Tag: 16
+ default:
+ panic("unsupported version")
+ }
+}
+
+// encryptedLength is used to compute the buffer size needed
+// for a message of given length
+func encryptedLength(vsn encryptionVersion, inp int) int {
+ // If we are on version 1, there is no padding
+ if vsn >= 1 {
+ return versionSize + nonceSize + inp + tagSize
+ }
+
+ // Determine the padding size
+ padding := blockSize - (inp % blockSize)
+
+ // Sum the extra parts to get total size
+ return versionSize + nonceSize + inp + padding + tagSize
+}
+
+// encryptPayload is used to encrypt a message with a given key.
+// We make use of AES-128 in GCM mode. New byte buffer is the version,
+// nonce, ciphertext and tag
+func encryptPayload(vsn encryptionVersion, key []byte, msg []byte, data []byte, dst *bytes.Buffer) error {
+ // Get the AES block cipher
+ aesBlock, err := aes.NewCipher(key)
+ if err != nil {
+ return err
+ }
+
+ // Get the GCM cipher mode
+ gcm, err := cipher.NewGCM(aesBlock)
+ if err != nil {
+ return err
+ }
+
+ // Grow the buffer to make room for everything
+ offset := dst.Len()
+ dst.Grow(encryptedLength(vsn, len(msg)))
+
+ // Write the encryption version
+ dst.WriteByte(byte(vsn))
+
+ // Add a random nonce
+ io.CopyN(dst, rand.Reader, nonceSize)
+ afterNonce := dst.Len()
+
+ // Ensure we are correctly padded (only version 0)
+ if vsn == 0 {
+ io.Copy(dst, bytes.NewReader(msg))
+ pkcs7encode(dst, offset+versionSize+nonceSize, aes.BlockSize)
+ }
+
+ // Encrypt message using GCM
+ slice := dst.Bytes()[offset:]
+ nonce := slice[versionSize : versionSize+nonceSize]
+
+ // Message source depends on the encryption version.
+ // Version 0 uses padding, version 1 does not
+ var src []byte
+ if vsn == 0 {
+ src = slice[versionSize+nonceSize:]
+ } else {
+ src = msg
+ }
+ out := gcm.Seal(nil, nonce, src, data)
+
+ // Truncate the plaintext, and write the cipher text
+ dst.Truncate(afterNonce)
+ dst.Write(out)
+ return nil
+}
+
+// decryptMessage performs the actual decryption of ciphertext. This is in its
+// own function to allow it to be called on all keys easily.
+func decryptMessage(key, msg []byte, data []byte) ([]byte, error) {
+ // Get the AES block cipher
+ aesBlock, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, err
+ }
+
+ // Get the GCM cipher mode
+ gcm, err := cipher.NewGCM(aesBlock)
+ if err != nil {
+ return nil, err
+ }
+
+ // Decrypt the message
+ nonce := msg[versionSize : versionSize+nonceSize]
+ ciphertext := msg[versionSize+nonceSize:]
+ plain, err := gcm.Open(nil, nonce, ciphertext, data)
+ if err != nil {
+ return nil, err
+ }
+
+ // Success!
+ return plain, nil
+}
+
+// decryptPayload is used to decrypt a message with a given key,
+// and verify it's contents. Any padding will be removed, and a
+// slice to the plaintext is returned. Decryption is done IN PLACE!
+func decryptPayload(keys [][]byte, msg []byte, data []byte) ([]byte, error) {
+ // Ensure we have at least one byte
+ if len(msg) == 0 {
+ return nil, fmt.Errorf("Cannot decrypt empty payload")
+ }
+
+ // Verify the version
+ vsn := encryptionVersion(msg[0])
+ if vsn > maxEncryptionVersion {
+ return nil, fmt.Errorf("Unsupported encryption version %d", msg[0])
+ }
+
+ // Ensure the length is sane
+ if len(msg) < encryptedLength(vsn, 0) {
+ return nil, fmt.Errorf("Payload is too small to decrypt: %d", len(msg))
+ }
+
+ for _, key := range keys {
+ plain, err := decryptMessage(key, msg, data)
+ if err == nil {
+ // Remove the PKCS7 padding for vsn 0
+ if vsn == 0 {
+ return pkcs7decode(plain, aes.BlockSize), nil
+ } else {
+ return plain, nil
+ }
+ }
+ }
+
+ return nil, fmt.Errorf("No installed keys could decrypt the message")
+}
diff --git a/vendor/github.com/hashicorp/memberlist/state.go b/vendor/github.com/hashicorp/memberlist/state.go
new file mode 100644
index 0000000..71bf6f3
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/state.go
@@ -0,0 +1,1160 @@
+package memberlist
+
+import (
+ "bytes"
+ "fmt"
+ "math"
+ "math/rand"
+ "net"
+ "sync/atomic"
+ "time"
+
+ "github.com/armon/go-metrics"
+)
+
+type nodeStateType int
+
+const (
+ stateAlive nodeStateType = iota
+ stateSuspect
+ stateDead
+)
+
+// Node represents a node in the cluster.
+type Node struct {
+ Name string
+ Addr net.IP
+ Port uint16
+ Meta []byte // Metadata from the delegate for this node.
+ PMin uint8 // Minimum protocol version this understands
+ PMax uint8 // Maximum protocol version this understands
+ PCur uint8 // Current version node is speaking
+ DMin uint8 // Min protocol version for the delegate to understand
+ DMax uint8 // Max protocol version for the delegate to understand
+ DCur uint8 // Current version delegate is speaking
+}
+
+// Address returns the host:port form of a node's address, suitable for use
+// with a transport.
+func (n *Node) Address() string {
+ return joinHostPort(n.Addr.String(), n.Port)
+}
+
+// NodeState is used to manage our state view of another node
+type nodeState struct {
+ Node
+ Incarnation uint32 // Last known incarnation number
+ State nodeStateType // Current state
+ StateChange time.Time // Time last state change happened
+}
+
+// Address returns the host:port form of a node's address, suitable for use
+// with a transport.
+func (n *nodeState) Address() string {
+ return n.Node.Address()
+}
+
+// ackHandler is used to register handlers for incoming acks and nacks.
+type ackHandler struct {
+ ackFn func([]byte, time.Time)
+ nackFn func()
+ timer *time.Timer
+}
+
+// NoPingResponseError is used to indicate a 'ping' packet was
+// successfully issued but no response was received
+type NoPingResponseError struct {
+ node string
+}
+
+func (f NoPingResponseError) Error() string {
+ return fmt.Sprintf("No response from node %s", f.node)
+}
+
+// Schedule is used to ensure the Tick is performed periodically. This
+// function is safe to call multiple times. If the memberlist is already
+// scheduled, then it won't do anything.
+func (m *Memberlist) schedule() {
+ m.tickerLock.Lock()
+ defer m.tickerLock.Unlock()
+
+ // If we already have tickers, then don't do anything, since we're
+ // scheduled
+ if len(m.tickers) > 0 {
+ return
+ }
+
+ // Create the stop tick channel, a blocking channel. We close this
+ // when we should stop the tickers.
+ stopCh := make(chan struct{})
+
+ // Create a new probeTicker
+ if m.config.ProbeInterval > 0 {
+ t := time.NewTicker(m.config.ProbeInterval)
+ go m.triggerFunc(m.config.ProbeInterval, t.C, stopCh, m.probe)
+ m.tickers = append(m.tickers, t)
+ }
+
+ // Create a push pull ticker if needed
+ if m.config.PushPullInterval > 0 {
+ go m.pushPullTrigger(stopCh)
+ }
+
+ // Create a gossip ticker if needed
+ if m.config.GossipInterval > 0 && m.config.GossipNodes > 0 {
+ t := time.NewTicker(m.config.GossipInterval)
+ go m.triggerFunc(m.config.GossipInterval, t.C, stopCh, m.gossip)
+ m.tickers = append(m.tickers, t)
+ }
+
+ // If we made any tickers, then record the stopTick channel for
+ // later.
+ if len(m.tickers) > 0 {
+ m.stopTick = stopCh
+ }
+}
+
+// triggerFunc is used to trigger a function call each time a
+// message is received until a stop tick arrives.
+func (m *Memberlist) triggerFunc(stagger time.Duration, C <-chan time.Time, stop <-chan struct{}, f func()) {
+ // Use a random stagger to avoid syncronizing
+ randStagger := time.Duration(uint64(rand.Int63()) % uint64(stagger))
+ select {
+ case <-time.After(randStagger):
+ case <-stop:
+ return
+ }
+ for {
+ select {
+ case <-C:
+ f()
+ case <-stop:
+ return
+ }
+ }
+}
+
+// pushPullTrigger is used to periodically trigger a push/pull until
+// a stop tick arrives. We don't use triggerFunc since the push/pull
+// timer is dynamically scaled based on cluster size to avoid network
+// saturation
+func (m *Memberlist) pushPullTrigger(stop <-chan struct{}) {
+ interval := m.config.PushPullInterval
+
+ // Use a random stagger to avoid syncronizing
+ randStagger := time.Duration(uint64(rand.Int63()) % uint64(interval))
+ select {
+ case <-time.After(randStagger):
+ case <-stop:
+ return
+ }
+
+ // Tick using a dynamic timer
+ for {
+ tickTime := pushPullScale(interval, m.estNumNodes())
+ select {
+ case <-time.After(tickTime):
+ m.pushPull()
+ case <-stop:
+ return
+ }
+ }
+}
+
+// Deschedule is used to stop the background maintenance. This is safe
+// to call multiple times.
+func (m *Memberlist) deschedule() {
+ m.tickerLock.Lock()
+ defer m.tickerLock.Unlock()
+
+ // If we have no tickers, then we aren't scheduled.
+ if len(m.tickers) == 0 {
+ return
+ }
+
+ // Close the stop channel so all the ticker listeners stop.
+ close(m.stopTick)
+
+ // Explicitly stop all the tickers themselves so they don't take
+ // up any more resources, and get rid of the list.
+ for _, t := range m.tickers {
+ t.Stop()
+ }
+ m.tickers = nil
+}
+
+// Tick is used to perform a single round of failure detection and gossip
+func (m *Memberlist) probe() {
+ // Track the number of indexes we've considered probing
+ numCheck := 0
+START:
+ m.nodeLock.RLock()
+
+ // Make sure we don't wrap around infinitely
+ if numCheck >= len(m.nodes) {
+ m.nodeLock.RUnlock()
+ return
+ }
+
+ // Handle the wrap around case
+ if m.probeIndex >= len(m.nodes) {
+ m.nodeLock.RUnlock()
+ m.resetNodes()
+ m.probeIndex = 0
+ numCheck++
+ goto START
+ }
+
+ // Determine if we should probe this node
+ skip := false
+ var node nodeState
+
+ node = *m.nodes[m.probeIndex]
+ if node.Name == m.config.Name {
+ skip = true
+ } else if node.State == stateDead {
+ skip = true
+ }
+
+ // Potentially skip
+ m.nodeLock.RUnlock()
+ m.probeIndex++
+ if skip {
+ numCheck++
+ goto START
+ }
+
+ // Probe the specific node
+ m.probeNode(&node)
+}
+
+// probeNode handles a single round of failure checking on a node.
+func (m *Memberlist) probeNode(node *nodeState) {
+ defer metrics.MeasureSince([]string{"memberlist", "probeNode"}, time.Now())
+
+ // We use our health awareness to scale the overall probe interval, so we
+ // slow down if we detect problems. The ticker that calls us can handle
+ // us running over the base interval, and will skip missed ticks.
+ probeInterval := m.awareness.ScaleTimeout(m.config.ProbeInterval)
+ if probeInterval > m.config.ProbeInterval {
+ metrics.IncrCounter([]string{"memberlist", "degraded", "probe"}, 1)
+ }
+
+ // Prepare a ping message and setup an ack handler.
+ ping := ping{SeqNo: m.nextSeqNo(), Node: node.Name}
+ ackCh := make(chan ackMessage, m.config.IndirectChecks+1)
+ nackCh := make(chan struct{}, m.config.IndirectChecks+1)
+ m.setProbeChannels(ping.SeqNo, ackCh, nackCh, probeInterval)
+
+ // Send a ping to the node. If this node looks like it's suspect or dead,
+ // also tack on a suspect message so that it has a chance to refute as
+ // soon as possible.
+ deadline := time.Now().Add(probeInterval)
+ addr := node.Address()
+ if node.State == stateAlive {
+ if err := m.encodeAndSendMsg(addr, pingMsg, &ping); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to send ping: %s", err)
+ return
+ }
+ } else {
+ var msgs [][]byte
+ if buf, err := encode(pingMsg, &ping); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to encode ping message: %s", err)
+ return
+ } else {
+ msgs = append(msgs, buf.Bytes())
+ }
+ s := suspect{Incarnation: node.Incarnation, Node: node.Name, From: m.config.Name}
+ if buf, err := encode(suspectMsg, &s); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to encode suspect message: %s", err)
+ return
+ } else {
+ msgs = append(msgs, buf.Bytes())
+ }
+
+ compound := makeCompoundMessage(msgs)
+ if err := m.rawSendMsgPacket(addr, &node.Node, compound.Bytes()); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to send compound ping and suspect message to %s: %s", addr, err)
+ return
+ }
+ }
+
+ // Mark the sent time here, which should be after any pre-processing and
+ // system calls to do the actual send. This probably under-reports a bit,
+ // but it's the best we can do.
+ sent := time.Now()
+
+ // Arrange for our self-awareness to get updated. At this point we've
+ // sent the ping, so any return statement means the probe succeeded
+ // which will improve our health until we get to the failure scenarios
+ // at the end of this function, which will alter this delta variable
+ // accordingly.
+ awarenessDelta := -1
+ defer func() {
+ m.awareness.ApplyDelta(awarenessDelta)
+ }()
+
+ // Wait for response or round-trip-time.
+ select {
+ case v := <-ackCh:
+ if v.Complete == true {
+ if m.config.Ping != nil {
+ rtt := v.Timestamp.Sub(sent)
+ m.config.Ping.NotifyPingComplete(&node.Node, rtt, v.Payload)
+ }
+ return
+ }
+
+ // As an edge case, if we get a timeout, we need to re-enqueue it
+ // here to break out of the select below.
+ if v.Complete == false {
+ ackCh <- v
+ }
+ case <-time.After(m.config.ProbeTimeout):
+ // Note that we don't scale this timeout based on awareness and
+ // the health score. That's because we don't really expect waiting
+ // longer to help get UDP through. Since health does extend the
+ // probe interval it will give the TCP fallback more time, which
+ // is more active in dealing with lost packets, and it gives more
+ // time to wait for indirect acks/nacks.
+ m.logger.Printf("[DEBUG] memberlist: Failed ping: %v (timeout reached)", node.Name)
+ }
+
+ // Get some random live nodes.
+ m.nodeLock.RLock()
+ kNodes := kRandomNodes(m.config.IndirectChecks, m.nodes, func(n *nodeState) bool {
+ return n.Name == m.config.Name ||
+ n.Name == node.Name ||
+ n.State != stateAlive
+ })
+ m.nodeLock.RUnlock()
+
+ // Attempt an indirect ping.
+ expectedNacks := 0
+ ind := indirectPingReq{SeqNo: ping.SeqNo, Target: node.Addr, Port: node.Port, Node: node.Name}
+ for _, peer := range kNodes {
+ // We only expect nack to be sent from peers who understand
+ // version 4 of the protocol.
+ if ind.Nack = peer.PMax >= 4; ind.Nack {
+ expectedNacks++
+ }
+
+ if err := m.encodeAndSendMsg(peer.Address(), indirectPingMsg, &ind); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to send indirect ping: %s", err)
+ }
+ }
+
+ // Also make an attempt to contact the node directly over TCP. This
+ // helps prevent confused clients who get isolated from UDP traffic
+ // but can still speak TCP (which also means they can possibly report
+ // misinformation to other nodes via anti-entropy), avoiding flapping in
+ // the cluster.
+ //
+ // This is a little unusual because we will attempt a TCP ping to any
+ // member who understands version 3 of the protocol, regardless of
+ // which protocol version we are speaking. That's why we've included a
+ // config option to turn this off if desired.
+ fallbackCh := make(chan bool, 1)
+ if (!m.config.DisableTcpPings) && (node.PMax >= 3) {
+ go func() {
+ defer close(fallbackCh)
+ didContact, err := m.sendPingAndWaitForAck(node.Address(), ping, deadline)
+ if err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed fallback ping: %s", err)
+ } else {
+ fallbackCh <- didContact
+ }
+ }()
+ } else {
+ close(fallbackCh)
+ }
+
+ // Wait for the acks or timeout. Note that we don't check the fallback
+ // channel here because we want to issue a warning below if that's the
+ // *only* way we hear back from the peer, so we have to let this time
+ // out first to allow the normal UDP-based acks to come in.
+ select {
+ case v := <-ackCh:
+ if v.Complete == true {
+ return
+ }
+ }
+
+ // Finally, poll the fallback channel. The timeouts are set such that
+ // the channel will have something or be closed without having to wait
+ // any additional time here.
+ for didContact := range fallbackCh {
+ if didContact {
+ m.logger.Printf("[WARN] memberlist: Was able to connect to %s but other probes failed, network may be misconfigured", node.Name)
+ return
+ }
+ }
+
+ // Update our self-awareness based on the results of this failed probe.
+ // If we don't have peers who will send nacks then we penalize for any
+ // failed probe as a simple health metric. If we do have peers to nack
+ // verify, then we can use that as a more sophisticated measure of self-
+ // health because we assume them to be working, and they can help us
+ // decide if the probed node was really dead or if it was something wrong
+ // with ourselves.
+ awarenessDelta = 0
+ if expectedNacks > 0 {
+ if nackCount := len(nackCh); nackCount < expectedNacks {
+ awarenessDelta += (expectedNacks - nackCount)
+ }
+ } else {
+ awarenessDelta += 1
+ }
+
+ // No acks received from target, suspect it as failed.
+ m.logger.Printf("[INFO] memberlist: Suspect %s has failed, no acks received", node.Name)
+ s := suspect{Incarnation: node.Incarnation, Node: node.Name, From: m.config.Name}
+ m.suspectNode(&s)
+}
+
+// Ping initiates a ping to the node with the specified name.
+func (m *Memberlist) Ping(node string, addr net.Addr) (time.Duration, error) {
+ // Prepare a ping message and setup an ack handler.
+ ping := ping{SeqNo: m.nextSeqNo(), Node: node}
+ ackCh := make(chan ackMessage, m.config.IndirectChecks+1)
+ m.setProbeChannels(ping.SeqNo, ackCh, nil, m.config.ProbeInterval)
+
+ // Send a ping to the node.
+ if err := m.encodeAndSendMsg(addr.String(), pingMsg, &ping); err != nil {
+ return 0, err
+ }
+
+ // Mark the sent time here, which should be after any pre-processing and
+ // system calls to do the actual send. This probably under-reports a bit,
+ // but it's the best we can do.
+ sent := time.Now()
+
+ // Wait for response or timeout.
+ select {
+ case v := <-ackCh:
+ if v.Complete == true {
+ return v.Timestamp.Sub(sent), nil
+ }
+ case <-time.After(m.config.ProbeTimeout):
+ // Timeout, return an error below.
+ }
+
+ m.logger.Printf("[DEBUG] memberlist: Failed UDP ping: %v (timeout reached)", node)
+ return 0, NoPingResponseError{ping.Node}
+}
+
+// resetNodes is used when the tick wraps around. It will reap the
+// dead nodes and shuffle the node list.
+func (m *Memberlist) resetNodes() {
+ m.nodeLock.Lock()
+ defer m.nodeLock.Unlock()
+
+ // Move dead nodes, but respect gossip to the dead interval
+ deadIdx := moveDeadNodes(m.nodes, m.config.GossipToTheDeadTime)
+
+ // Deregister the dead nodes
+ for i := deadIdx; i < len(m.nodes); i++ {
+ delete(m.nodeMap, m.nodes[i].Name)
+ m.nodes[i] = nil
+ }
+
+ // Trim the nodes to exclude the dead nodes
+ m.nodes = m.nodes[0:deadIdx]
+
+ // Update numNodes after we've trimmed the dead nodes
+ atomic.StoreUint32(&m.numNodes, uint32(deadIdx))
+
+ // Shuffle live nodes
+ shuffleNodes(m.nodes)
+}
+
+// gossip is invoked every GossipInterval period to broadcast our gossip
+// messages to a few random nodes.
+func (m *Memberlist) gossip() {
+ defer metrics.MeasureSince([]string{"memberlist", "gossip"}, time.Now())
+
+ // Get some random live, suspect, or recently dead nodes
+ m.nodeLock.RLock()
+ kNodes := kRandomNodes(m.config.GossipNodes, m.nodes, func(n *nodeState) bool {
+ if n.Name == m.config.Name {
+ return true
+ }
+
+ switch n.State {
+ case stateAlive, stateSuspect:
+ return false
+
+ case stateDead:
+ return time.Since(n.StateChange) > m.config.GossipToTheDeadTime
+
+ default:
+ return true
+ }
+ })
+ m.nodeLock.RUnlock()
+
+ // Compute the bytes available
+ bytesAvail := m.config.UDPBufferSize - compoundHeaderOverhead
+ if m.config.EncryptionEnabled() {
+ bytesAvail -= encryptOverhead(m.encryptionVersion())
+ }
+
+ for _, node := range kNodes {
+ // Get any pending broadcasts
+ msgs := m.getBroadcasts(compoundOverhead, bytesAvail)
+ if len(msgs) == 0 {
+ return
+ }
+
+ addr := node.Address()
+ if len(msgs) == 1 {
+ // Send single message as is
+ if err := m.rawSendMsgPacket(addr, &node.Node, msgs[0]); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to send gossip to %s: %s", addr, err)
+ }
+ } else {
+ // Otherwise create and send a compound message
+ compound := makeCompoundMessage(msgs)
+ if err := m.rawSendMsgPacket(addr, &node.Node, compound.Bytes()); err != nil {
+ m.logger.Printf("[ERR] memberlist: Failed to send gossip to %s: %s", addr, err)
+ }
+ }
+ }
+}
+
+// pushPull is invoked periodically to randomly perform a complete state
+// exchange. Used to ensure a high level of convergence, but is also
+// reasonably expensive as the entire state of this node is exchanged
+// with the other node.
+func (m *Memberlist) pushPull() {
+ // Get a random live node
+ m.nodeLock.RLock()
+ nodes := kRandomNodes(1, m.nodes, func(n *nodeState) bool {
+ return n.Name == m.config.Name ||
+ n.State != stateAlive
+ })
+ m.nodeLock.RUnlock()
+
+ // If no nodes, bail
+ if len(nodes) == 0 {
+ return
+ }
+ node := nodes[0]
+
+ // Attempt a push pull
+ if err := m.pushPullNode(node.Address(), false); err != nil {
+ m.logger.Printf("[ERR] memberlist: Push/Pull with %s failed: %s", node.Name, err)
+ }
+}
+
+// pushPullNode does a complete state exchange with a specific node.
+func (m *Memberlist) pushPullNode(addr string, join bool) error {
+ defer metrics.MeasureSince([]string{"memberlist", "pushPullNode"}, time.Now())
+
+ // Attempt to send and receive with the node
+ remote, userState, err := m.sendAndReceiveState(addr, join)
+ if err != nil {
+ return err
+ }
+
+ if err := m.mergeRemoteState(join, remote, userState); err != nil {
+ return err
+ }
+ return nil
+}
+
+// verifyProtocol verifies that all the remote nodes can speak with our
+// nodes and vice versa on both the core protocol as well as the
+// delegate protocol level.
+//
+// The verification works by finding the maximum minimum and
+// minimum maximum understood protocol and delegate versions. In other words,
+// it finds the common denominator of protocol and delegate version ranges
+// for the entire cluster.
+//
+// After this, it goes through the entire cluster (local and remote) and
+// verifies that everyone's speaking protocol versions satisfy this range.
+// If this passes, it means that every node can understand each other.
+func (m *Memberlist) verifyProtocol(remote []pushNodeState) error {
+ m.nodeLock.RLock()
+ defer m.nodeLock.RUnlock()
+
+ // Maximum minimum understood and minimum maximum understood for both
+ // the protocol and delegate versions. We use this to verify everyone
+ // can be understood.
+ var maxpmin, minpmax uint8
+ var maxdmin, mindmax uint8
+ minpmax = math.MaxUint8
+ mindmax = math.MaxUint8
+
+ for _, rn := range remote {
+ // If the node isn't alive, then skip it
+ if rn.State != stateAlive {
+ continue
+ }
+
+ // Skip nodes that don't have versions set, it just means
+ // their version is zero.
+ if len(rn.Vsn) == 0 {
+ continue
+ }
+
+ if rn.Vsn[0] > maxpmin {
+ maxpmin = rn.Vsn[0]
+ }
+
+ if rn.Vsn[1] < minpmax {
+ minpmax = rn.Vsn[1]
+ }
+
+ if rn.Vsn[3] > maxdmin {
+ maxdmin = rn.Vsn[3]
+ }
+
+ if rn.Vsn[4] < mindmax {
+ mindmax = rn.Vsn[4]
+ }
+ }
+
+ for _, n := range m.nodes {
+ // Ignore non-alive nodes
+ if n.State != stateAlive {
+ continue
+ }
+
+ if n.PMin > maxpmin {
+ maxpmin = n.PMin
+ }
+
+ if n.PMax < minpmax {
+ minpmax = n.PMax
+ }
+
+ if n.DMin > maxdmin {
+ maxdmin = n.DMin
+ }
+
+ if n.DMax < mindmax {
+ mindmax = n.DMax
+ }
+ }
+
+ // Now that we definitively know the minimum and maximum understood
+ // version that satisfies the whole cluster, we verify that every
+ // node in the cluster satisifies this.
+ for _, n := range remote {
+ var nPCur, nDCur uint8
+ if len(n.Vsn) > 0 {
+ nPCur = n.Vsn[2]
+ nDCur = n.Vsn[5]
+ }
+
+ if nPCur < maxpmin || nPCur > minpmax {
+ return fmt.Errorf(
+ "Node '%s' protocol version (%d) is incompatible: [%d, %d]",
+ n.Name, nPCur, maxpmin, minpmax)
+ }
+
+ if nDCur < maxdmin || nDCur > mindmax {
+ return fmt.Errorf(
+ "Node '%s' delegate protocol version (%d) is incompatible: [%d, %d]",
+ n.Name, nDCur, maxdmin, mindmax)
+ }
+ }
+
+ for _, n := range m.nodes {
+ nPCur := n.PCur
+ nDCur := n.DCur
+
+ if nPCur < maxpmin || nPCur > minpmax {
+ return fmt.Errorf(
+ "Node '%s' protocol version (%d) is incompatible: [%d, %d]",
+ n.Name, nPCur, maxpmin, minpmax)
+ }
+
+ if nDCur < maxdmin || nDCur > mindmax {
+ return fmt.Errorf(
+ "Node '%s' delegate protocol version (%d) is incompatible: [%d, %d]",
+ n.Name, nDCur, maxdmin, mindmax)
+ }
+ }
+
+ return nil
+}
+
+// nextSeqNo returns a usable sequence number in a thread safe way
+func (m *Memberlist) nextSeqNo() uint32 {
+ return atomic.AddUint32(&m.sequenceNum, 1)
+}
+
+// nextIncarnation returns the next incarnation number in a thread safe way
+func (m *Memberlist) nextIncarnation() uint32 {
+ return atomic.AddUint32(&m.incarnation, 1)
+}
+
+// skipIncarnation adds the positive offset to the incarnation number.
+func (m *Memberlist) skipIncarnation(offset uint32) uint32 {
+ return atomic.AddUint32(&m.incarnation, offset)
+}
+
+// estNumNodes is used to get the current estimate of the number of nodes
+func (m *Memberlist) estNumNodes() int {
+ return int(atomic.LoadUint32(&m.numNodes))
+}
+
+type ackMessage struct {
+ Complete bool
+ Payload []byte
+ Timestamp time.Time
+}
+
+// setProbeChannels is used to attach the ackCh to receive a message when an ack
+// with a given sequence number is received. The `complete` field of the message
+// will be false on timeout. Any nack messages will cause an empty struct to be
+// passed to the nackCh, which can be nil if not needed.
+func (m *Memberlist) setProbeChannels(seqNo uint32, ackCh chan ackMessage, nackCh chan struct{}, timeout time.Duration) {
+ // Create handler functions for acks and nacks
+ ackFn := func(payload []byte, timestamp time.Time) {
+ select {
+ case ackCh <- ackMessage{true, payload, timestamp}:
+ default:
+ }
+ }
+ nackFn := func() {
+ select {
+ case nackCh <- struct{}{}:
+ default:
+ }
+ }
+
+ // Add the handlers
+ ah := &ackHandler{ackFn, nackFn, nil}
+ m.ackLock.Lock()
+ m.ackHandlers[seqNo] = ah
+ m.ackLock.Unlock()
+
+ // Setup a reaping routing
+ ah.timer = time.AfterFunc(timeout, func() {
+ m.ackLock.Lock()
+ delete(m.ackHandlers, seqNo)
+ m.ackLock.Unlock()
+ select {
+ case ackCh <- ackMessage{false, nil, time.Now()}:
+ default:
+ }
+ })
+}
+
+// setAckHandler is used to attach a handler to be invoked when an ack with a
+// given sequence number is received. If a timeout is reached, the handler is
+// deleted. This is used for indirect pings so does not configure a function
+// for nacks.
+func (m *Memberlist) setAckHandler(seqNo uint32, ackFn func([]byte, time.Time), timeout time.Duration) {
+ // Add the handler
+ ah := &ackHandler{ackFn, nil, nil}
+ m.ackLock.Lock()
+ m.ackHandlers[seqNo] = ah
+ m.ackLock.Unlock()
+
+ // Setup a reaping routing
+ ah.timer = time.AfterFunc(timeout, func() {
+ m.ackLock.Lock()
+ delete(m.ackHandlers, seqNo)
+ m.ackLock.Unlock()
+ })
+}
+
+// Invokes an ack handler if any is associated, and reaps the handler immediately
+func (m *Memberlist) invokeAckHandler(ack ackResp, timestamp time.Time) {
+ m.ackLock.Lock()
+ ah, ok := m.ackHandlers[ack.SeqNo]
+ delete(m.ackHandlers, ack.SeqNo)
+ m.ackLock.Unlock()
+ if !ok {
+ return
+ }
+ ah.timer.Stop()
+ ah.ackFn(ack.Payload, timestamp)
+}
+
+// Invokes nack handler if any is associated.
+func (m *Memberlist) invokeNackHandler(nack nackResp) {
+ m.ackLock.Lock()
+ ah, ok := m.ackHandlers[nack.SeqNo]
+ m.ackLock.Unlock()
+ if !ok || ah.nackFn == nil {
+ return
+ }
+ ah.nackFn()
+}
+
+// refute gossips an alive message in response to incoming information that we
+// are suspect or dead. It will make sure the incarnation number beats the given
+// accusedInc value, or you can supply 0 to just get the next incarnation number.
+// This alters the node state that's passed in so this MUST be called while the
+// nodeLock is held.
+func (m *Memberlist) refute(me *nodeState, accusedInc uint32) {
+ // Make sure the incarnation number beats the accusation.
+ inc := m.nextIncarnation()
+ if accusedInc >= inc {
+ inc = m.skipIncarnation(accusedInc - inc + 1)
+ }
+ me.Incarnation = inc
+
+ // Decrease our health because we are being asked to refute a problem.
+ m.awareness.ApplyDelta(1)
+
+ // Format and broadcast an alive message.
+ a := alive{
+ Incarnation: inc,
+ Node: me.Name,
+ Addr: me.Addr,
+ Port: me.Port,
+ Meta: me.Meta,
+ Vsn: []uint8{
+ me.PMin, me.PMax, me.PCur,
+ me.DMin, me.DMax, me.DCur,
+ },
+ }
+ m.encodeAndBroadcast(me.Addr.String(), aliveMsg, a)
+}
+
+// aliveNode is invoked by the network layer when we get a message about a
+// live node.
+func (m *Memberlist) aliveNode(a *alive, notify chan struct{}, bootstrap bool) {
+ m.nodeLock.Lock()
+ defer m.nodeLock.Unlock()
+ state, ok := m.nodeMap[a.Node]
+
+ // It is possible that during a Leave(), there is already an aliveMsg
+ // in-queue to be processed but blocked by the locks above. If we let
+ // that aliveMsg process, it'll cause us to re-join the cluster. This
+ // ensures that we don't.
+ if m.leave && a.Node == m.config.Name {
+ return
+ }
+
+ // Invoke the Alive delegate if any. This can be used to filter out
+ // alive messages based on custom logic. For example, using a cluster name.
+ // Using a merge delegate is not enough, as it is possible for passive
+ // cluster merging to still occur.
+ if m.config.Alive != nil {
+ node := &Node{
+ Name: a.Node,
+ Addr: a.Addr,
+ Port: a.Port,
+ Meta: a.Meta,
+ PMin: a.Vsn[0],
+ PMax: a.Vsn[1],
+ PCur: a.Vsn[2],
+ DMin: a.Vsn[3],
+ DMax: a.Vsn[4],
+ DCur: a.Vsn[5],
+ }
+ if err := m.config.Alive.NotifyAlive(node); err != nil {
+ m.logger.Printf("[WARN] memberlist: ignoring alive message for '%s': %s",
+ a.Node, err)
+ return
+ }
+ }
+
+ // Check if we've never seen this node before, and if not, then
+ // store this node in our node map.
+ if !ok {
+ state = &nodeState{
+ Node: Node{
+ Name: a.Node,
+ Addr: a.Addr,
+ Port: a.Port,
+ Meta: a.Meta,
+ },
+ State: stateDead,
+ }
+
+ // Add to map
+ m.nodeMap[a.Node] = state
+
+ // Get a random offset. This is important to ensure
+ // the failure detection bound is low on average. If all
+ // nodes did an append, failure detection bound would be
+ // very high.
+ n := len(m.nodes)
+ offset := randomOffset(n)
+
+ // Add at the end and swap with the node at the offset
+ m.nodes = append(m.nodes, state)
+ m.nodes[offset], m.nodes[n] = m.nodes[n], m.nodes[offset]
+
+ // Update numNodes after we've added a new node
+ atomic.AddUint32(&m.numNodes, 1)
+ }
+
+ // Check if this address is different than the existing node
+ if !bytes.Equal([]byte(state.Addr), a.Addr) || state.Port != a.Port {
+ m.logger.Printf("[ERR] memberlist: Conflicting address for %s. Mine: %v:%d Theirs: %v:%d",
+ state.Name, state.Addr, state.Port, net.IP(a.Addr), a.Port)
+
+ // Inform the conflict delegate if provided
+ if m.config.Conflict != nil {
+ other := Node{
+ Name: a.Node,
+ Addr: a.Addr,
+ Port: a.Port,
+ Meta: a.Meta,
+ }
+ m.config.Conflict.NotifyConflict(&state.Node, &other)
+ }
+ return
+ }
+
+ // Bail if the incarnation number is older, and this is not about us
+ isLocalNode := state.Name == m.config.Name
+ if a.Incarnation <= state.Incarnation && !isLocalNode {
+ return
+ }
+
+ // Bail if strictly less and this is about us
+ if a.Incarnation < state.Incarnation && isLocalNode {
+ return
+ }
+
+ // Clear out any suspicion timer that may be in effect.
+ delete(m.nodeTimers, a.Node)
+
+ // Store the old state and meta data
+ oldState := state.State
+ oldMeta := state.Meta
+
+ // If this is us we need to refute, otherwise re-broadcast
+ if !bootstrap && isLocalNode {
+ // Compute the version vector
+ versions := []uint8{
+ state.PMin, state.PMax, state.PCur,
+ state.DMin, state.DMax, state.DCur,
+ }
+
+ // If the Incarnation is the same, we need special handling, since it
+ // possible for the following situation to happen:
+ // 1) Start with configuration C, join cluster
+ // 2) Hard fail / Kill / Shutdown
+ // 3) Restart with configuration C', join cluster
+ //
+ // In this case, other nodes and the local node see the same incarnation,
+ // but the values may not be the same. For this reason, we always
+ // need to do an equality check for this Incarnation. In most cases,
+ // we just ignore, but we may need to refute.
+ //
+ if a.Incarnation == state.Incarnation &&
+ bytes.Equal(a.Meta, state.Meta) &&
+ bytes.Equal(a.Vsn, versions) {
+ return
+ }
+
+ m.refute(state, a.Incarnation)
+ m.logger.Printf("[WARN] memberlist: Refuting an alive message")
+ } else {
+ m.encodeBroadcastNotify(a.Node, aliveMsg, a, notify)
+
+ // Update protocol versions if it arrived
+ if len(a.Vsn) > 0 {
+ state.PMin = a.Vsn[0]
+ state.PMax = a.Vsn[1]
+ state.PCur = a.Vsn[2]
+ state.DMin = a.Vsn[3]
+ state.DMax = a.Vsn[4]
+ state.DCur = a.Vsn[5]
+ }
+
+ // Update the state and incarnation number
+ state.Incarnation = a.Incarnation
+ state.Meta = a.Meta
+ if state.State != stateAlive {
+ state.State = stateAlive
+ state.StateChange = time.Now()
+ }
+ }
+
+ // Update metrics
+ metrics.IncrCounter([]string{"memberlist", "msg", "alive"}, 1)
+
+ // Notify the delegate of any relevant updates
+ if m.config.Events != nil {
+ if oldState == stateDead {
+ // if Dead -> Alive, notify of join
+ m.config.Events.NotifyJoin(&state.Node)
+
+ } else if !bytes.Equal(oldMeta, state.Meta) {
+ // if Meta changed, trigger an update notification
+ m.config.Events.NotifyUpdate(&state.Node)
+ }
+ }
+}
+
+// suspectNode is invoked by the network layer when we get a message
+// about a suspect node
+func (m *Memberlist) suspectNode(s *suspect) {
+ m.nodeLock.Lock()
+ defer m.nodeLock.Unlock()
+ state, ok := m.nodeMap[s.Node]
+
+ // If we've never heard about this node before, ignore it
+ if !ok {
+ return
+ }
+
+ // Ignore old incarnation numbers
+ if s.Incarnation < state.Incarnation {
+ return
+ }
+
+ // See if there's a suspicion timer we can confirm. If the info is new
+ // to us we will go ahead and re-gossip it. This allows for multiple
+ // independent confirmations to flow even when a node probes a node
+ // that's already suspect.
+ if timer, ok := m.nodeTimers[s.Node]; ok {
+ if timer.Confirm(s.From) {
+ m.encodeAndBroadcast(s.Node, suspectMsg, s)
+ }
+ return
+ }
+
+ // Ignore non-alive nodes
+ if state.State != stateAlive {
+ return
+ }
+
+ // If this is us we need to refute, otherwise re-broadcast
+ if state.Name == m.config.Name {
+ m.refute(state, s.Incarnation)
+ m.logger.Printf("[WARN] memberlist: Refuting a suspect message (from: %s)", s.From)
+ return // Do not mark ourself suspect
+ } else {
+ m.encodeAndBroadcast(s.Node, suspectMsg, s)
+ }
+
+ // Update metrics
+ metrics.IncrCounter([]string{"memberlist", "msg", "suspect"}, 1)
+
+ // Update the state
+ state.Incarnation = s.Incarnation
+ state.State = stateSuspect
+ changeTime := time.Now()
+ state.StateChange = changeTime
+
+ // Setup a suspicion timer. Given that we don't have any known phase
+ // relationship with our peers, we set up k such that we hit the nominal
+ // timeout two probe intervals short of what we expect given the suspicion
+ // multiplier.
+ k := m.config.SuspicionMult - 2
+
+ // If there aren't enough nodes to give the expected confirmations, just
+ // set k to 0 to say that we don't expect any. Note we subtract 2 from n
+ // here to take out ourselves and the node being probed.
+ n := m.estNumNodes()
+ if n-2 < k {
+ k = 0
+ }
+
+ // Compute the timeouts based on the size of the cluster.
+ min := suspicionTimeout(m.config.SuspicionMult, n, m.config.ProbeInterval)
+ max := time.Duration(m.config.SuspicionMaxTimeoutMult) * min
+ fn := func(numConfirmations int) {
+ m.nodeLock.Lock()
+ state, ok := m.nodeMap[s.Node]
+ timeout := ok && state.State == stateSuspect && state.StateChange == changeTime
+ m.nodeLock.Unlock()
+
+ if timeout {
+ if k > 0 && numConfirmations < k {
+ metrics.IncrCounter([]string{"memberlist", "degraded", "timeout"}, 1)
+ }
+
+ m.logger.Printf("[INFO] memberlist: Marking %s as failed, suspect timeout reached (%d peer confirmations)",
+ state.Name, numConfirmations)
+ d := dead{Incarnation: state.Incarnation, Node: state.Name, From: m.config.Name}
+ m.deadNode(&d)
+ }
+ }
+ m.nodeTimers[s.Node] = newSuspicion(s.From, k, min, max, fn)
+}
+
+// deadNode is invoked by the network layer when we get a message
+// about a dead node
+func (m *Memberlist) deadNode(d *dead) {
+ m.nodeLock.Lock()
+ defer m.nodeLock.Unlock()
+ state, ok := m.nodeMap[d.Node]
+
+ // If we've never heard about this node before, ignore it
+ if !ok {
+ return
+ }
+
+ // Ignore old incarnation numbers
+ if d.Incarnation < state.Incarnation {
+ return
+ }
+
+ // Clear out any suspicion timer that may be in effect.
+ delete(m.nodeTimers, d.Node)
+
+ // Ignore if node is already dead
+ if state.State == stateDead {
+ return
+ }
+
+ // Check if this is us
+ if state.Name == m.config.Name {
+ // If we are not leaving we need to refute
+ if !m.leave {
+ m.refute(state, d.Incarnation)
+ m.logger.Printf("[WARN] memberlist: Refuting a dead message (from: %s)", d.From)
+ return // Do not mark ourself dead
+ }
+
+ // If we are leaving, we broadcast and wait
+ m.encodeBroadcastNotify(d.Node, deadMsg, d, m.leaveBroadcast)
+ } else {
+ m.encodeAndBroadcast(d.Node, deadMsg, d)
+ }
+
+ // Update metrics
+ metrics.IncrCounter([]string{"memberlist", "msg", "dead"}, 1)
+
+ // Update the state
+ state.Incarnation = d.Incarnation
+ state.State = stateDead
+ state.StateChange = time.Now()
+
+ // Notify of death
+ if m.config.Events != nil {
+ m.config.Events.NotifyLeave(&state.Node)
+ }
+}
+
+// mergeState is invoked by the network layer when we get a Push/Pull
+// state transfer
+func (m *Memberlist) mergeState(remote []pushNodeState) {
+ for _, r := range remote {
+ switch r.State {
+ case stateAlive:
+ a := alive{
+ Incarnation: r.Incarnation,
+ Node: r.Name,
+ Addr: r.Addr,
+ Port: r.Port,
+ Meta: r.Meta,
+ Vsn: r.Vsn,
+ }
+ m.aliveNode(&a, nil, false)
+
+ case stateDead:
+ // If the remote node believes a node is dead, we prefer to
+ // suspect that node instead of declaring it dead instantly
+ fallthrough
+ case stateSuspect:
+ s := suspect{Incarnation: r.Incarnation, Node: r.Name, From: m.config.Name}
+ m.suspectNode(&s)
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/memberlist/suspicion.go b/vendor/github.com/hashicorp/memberlist/suspicion.go
new file mode 100644
index 0000000..5f573e1
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/suspicion.go
@@ -0,0 +1,130 @@
+package memberlist
+
+import (
+ "math"
+ "sync/atomic"
+ "time"
+)
+
+// suspicion manages the suspect timer for a node and provides an interface
+// to accelerate the timeout as we get more independent confirmations that
+// a node is suspect.
+type suspicion struct {
+ // n is the number of independent confirmations we've seen. This must
+ // be updated using atomic instructions to prevent contention with the
+ // timer callback.
+ n int32
+
+ // k is the number of independent confirmations we'd like to see in
+ // order to drive the timer to its minimum value.
+ k int32
+
+ // min is the minimum timer value.
+ min time.Duration
+
+ // max is the maximum timer value.
+ max time.Duration
+
+ // start captures the timestamp when we began the timer. This is used
+ // so we can calculate durations to feed the timer during updates in
+ // a way the achieves the overall time we'd like.
+ start time.Time
+
+ // timer is the underlying timer that implements the timeout.
+ timer *time.Timer
+
+ // f is the function to call when the timer expires. We hold on to this
+ // because there are cases where we call it directly.
+ timeoutFn func()
+
+ // confirmations is a map of "from" nodes that have confirmed a given
+ // node is suspect. This prevents double counting.
+ confirmations map[string]struct{}
+}
+
+// newSuspicion returns a timer started with the max time, and that will drive
+// to the min time after seeing k or more confirmations. The from node will be
+// excluded from confirmations since we might get our own suspicion message
+// gossiped back to us. The minimum time will be used if no confirmations are
+// called for (k <= 0).
+func newSuspicion(from string, k int, min time.Duration, max time.Duration, fn func(int)) *suspicion {
+ s := &suspicion{
+ k: int32(k),
+ min: min,
+ max: max,
+ confirmations: make(map[string]struct{}),
+ }
+
+ // Exclude the from node from any confirmations.
+ s.confirmations[from] = struct{}{}
+
+ // Pass the number of confirmations into the timeout function for
+ // easy telemetry.
+ s.timeoutFn = func() {
+ fn(int(atomic.LoadInt32(&s.n)))
+ }
+
+ // If there aren't any confirmations to be made then take the min
+ // time from the start.
+ timeout := max
+ if k < 1 {
+ timeout = min
+ }
+ s.timer = time.AfterFunc(timeout, s.timeoutFn)
+
+ // Capture the start time right after starting the timer above so
+ // we should always err on the side of a little longer timeout if
+ // there's any preemption that separates this and the step above.
+ s.start = time.Now()
+ return s
+}
+
+// remainingSuspicionTime takes the state variables of the suspicion timer and
+// calculates the remaining time to wait before considering a node dead. The
+// return value can be negative, so be prepared to fire the timer immediately in
+// that case.
+func remainingSuspicionTime(n, k int32, elapsed time.Duration, min, max time.Duration) time.Duration {
+ frac := math.Log(float64(n)+1.0) / math.Log(float64(k)+1.0)
+ raw := max.Seconds() - frac*(max.Seconds()-min.Seconds())
+ timeout := time.Duration(math.Floor(1000.0*raw)) * time.Millisecond
+ if timeout < min {
+ timeout = min
+ }
+
+ // We have to take into account the amount of time that has passed so
+ // far, so we get the right overall timeout.
+ return timeout - elapsed
+}
+
+// Confirm registers that a possibly new peer has also determined the given
+// node is suspect. This returns true if this was new information, and false
+// if it was a duplicate confirmation, or if we've got enough confirmations to
+// hit the minimum.
+func (s *suspicion) Confirm(from string) bool {
+ // If we've got enough confirmations then stop accepting them.
+ if atomic.LoadInt32(&s.n) >= s.k {
+ return false
+ }
+
+ // Only allow one confirmation from each possible peer.
+ if _, ok := s.confirmations[from]; ok {
+ return false
+ }
+ s.confirmations[from] = struct{}{}
+
+ // Compute the new timeout given the current number of confirmations and
+ // adjust the timer. If the timeout becomes negative *and* we can cleanly
+ // stop the timer then we will call the timeout function directly from
+ // here.
+ n := atomic.AddInt32(&s.n, 1)
+ elapsed := time.Now().Sub(s.start)
+ remaining := remainingSuspicionTime(n, s.k, elapsed, s.min, s.max)
+ if s.timer.Stop() {
+ if remaining > 0 {
+ s.timer.Reset(remaining)
+ } else {
+ go s.timeoutFn()
+ }
+ }
+ return true
+}
diff --git a/vendor/github.com/hashicorp/memberlist/transport.go b/vendor/github.com/hashicorp/memberlist/transport.go
new file mode 100644
index 0000000..ca0a660
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/transport.go
@@ -0,0 +1,65 @@
+package memberlist
+
+import (
+ "net"
+ "time"
+)
+
+// Packet is used to provide some metadata about incoming packets from peers
+// over a packet connection, as well as the packet payload.
+type Packet struct {
+ // Buf has the raw contents of the packet.
+ Buf []byte
+
+ // From has the address of the peer. This is an actual net.Addr so we
+ // can expose some concrete details about incoming packets.
+ From net.Addr
+
+ // Timestamp is the time when the packet was received. This should be
+ // taken as close as possible to the actual receipt time to help make an
+ // accurate RTT measurements during probes.
+ Timestamp time.Time
+}
+
+// Transport is used to abstract over communicating with other peers. The packet
+// interface is assumed to be best-effort and the stream interface is assumed to
+// be reliable.
+type Transport interface {
+ // FinalAdvertiseAddr is given the user's configured values (which
+ // might be empty) and returns the desired IP and port to advertise to
+ // the rest of the cluster.
+ FinalAdvertiseAddr(ip string, port int) (net.IP, int, error)
+
+ // WriteTo is a packet-oriented interface that fires off the given
+ // payload to the given address in a connectionless fashion. This should
+ // return a time stamp that's as close as possible to when the packet
+ // was transmitted to help make accurate RTT measurements during probes.
+ //
+ // This is similar to net.PacketConn, though we didn't want to expose
+ // that full set of required methods to keep assumptions about the
+ // underlying plumbing to a minimum. We also treat the address here as a
+ // string, similar to Dial, so it's network neutral, so this usually is
+ // in the form of "host:port".
+ WriteTo(b []byte, addr string) (time.Time, error)
+
+ // PacketCh returns a channel that can be read to receive incoming
+ // packets from other peers. How this is set up for listening is left as
+ // an exercise for the concrete transport implementations.
+ PacketCh() <-chan *Packet
+
+ // DialTimeout is used to create a connection that allows us to perform
+ // two-way communication with a peer. This is generally more expensive
+ // than packet connections so is used for more infrequent operations
+ // such as anti-entropy or fallback probes if the packet-oriented probe
+ // failed.
+ DialTimeout(addr string, timeout time.Duration) (net.Conn, error)
+
+ // StreamCh returns a channel that can be read to handle incoming stream
+ // connections from other peers. How this is set up for listening is
+ // left as an exercise for the concrete transport implementations.
+ StreamCh() <-chan net.Conn
+
+ // Shutdown is called when memberlist is shutting down; this gives the
+ // transport a chance to clean up any listeners.
+ Shutdown() error
+}
diff --git a/vendor/github.com/hashicorp/memberlist/util.go b/vendor/github.com/hashicorp/memberlist/util.go
new file mode 100644
index 0000000..a4f926e
--- /dev/null
+++ b/vendor/github.com/hashicorp/memberlist/util.go
@@ -0,0 +1,296 @@
+package memberlist
+
+import (
+ "bytes"
+ "compress/lzw"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "math"
+ "math/rand"
+ "net"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/hashicorp/go-msgpack/codec"
+ "github.com/sean-/seed"
+)
+
+// pushPullScale is the minimum number of nodes
+// before we start scaling the push/pull timing. The scale
+// effect is the log2(Nodes) - log2(pushPullScale). This means
+// that the 33rd node will cause us to double the interval,
+// while the 65th will triple it.
+const pushPullScaleThreshold = 32
+
+const (
+ // Constant litWidth 2-8
+ lzwLitWidth = 8
+)
+
+func init() {
+ seed.Init()
+}
+
+// Decode reverses the encode operation on a byte slice input
+func decode(buf []byte, out interface{}) error {
+ r := bytes.NewReader(buf)
+ hd := codec.MsgpackHandle{}
+ dec := codec.NewDecoder(r, &hd)
+ return dec.Decode(out)
+}
+
+// Encode writes an encoded object to a new bytes buffer
+func encode(msgType messageType, in interface{}) (*bytes.Buffer, error) {
+ buf := bytes.NewBuffer(nil)
+ buf.WriteByte(uint8(msgType))
+ hd := codec.MsgpackHandle{}
+ enc := codec.NewEncoder(buf, &hd)
+ err := enc.Encode(in)
+ return buf, err
+}
+
+// Returns a random offset between 0 and n
+func randomOffset(n int) int {
+ if n == 0 {
+ return 0
+ }
+ return int(rand.Uint32() % uint32(n))
+}
+
+// suspicionTimeout computes the timeout that should be used when
+// a node is suspected
+func suspicionTimeout(suspicionMult, n int, interval time.Duration) time.Duration {
+ nodeScale := math.Max(1.0, math.Log10(math.Max(1.0, float64(n))))
+ // multiply by 1000 to keep some precision because time.Duration is an int64 type
+ timeout := time.Duration(suspicionMult) * time.Duration(nodeScale*1000) * interval / 1000
+ return timeout
+}
+
+// retransmitLimit computes the limit of retransmissions
+func retransmitLimit(retransmitMult, n int) int {
+ nodeScale := math.Ceil(math.Log10(float64(n + 1)))
+ limit := retransmitMult * int(nodeScale)
+ return limit
+}
+
+// shuffleNodes randomly shuffles the input nodes using the Fisher-Yates shuffle
+func shuffleNodes(nodes []*nodeState) {
+ n := len(nodes)
+ for i := n - 1; i > 0; i-- {
+ j := rand.Intn(i + 1)
+ nodes[i], nodes[j] = nodes[j], nodes[i]
+ }
+}
+
+// pushPushScale is used to scale the time interval at which push/pull
+// syncs take place. It is used to prevent network saturation as the
+// cluster size grows
+func pushPullScale(interval time.Duration, n int) time.Duration {
+ // Don't scale until we cross the threshold
+ if n <= pushPullScaleThreshold {
+ return interval
+ }
+
+ multiplier := math.Ceil(math.Log2(float64(n))-math.Log2(pushPullScaleThreshold)) + 1.0
+ return time.Duration(multiplier) * interval
+}
+
+// moveDeadNodes moves nodes that are dead and beyond the gossip to the dead interval
+// to the end of the slice and returns the index of the first moved node.
+func moveDeadNodes(nodes []*nodeState, gossipToTheDeadTime time.Duration) int {
+ numDead := 0
+ n := len(nodes)
+ for i := 0; i < n-numDead; i++ {
+ if nodes[i].State != stateDead {
+ continue
+ }
+
+ // Respect the gossip to the dead interval
+ if time.Since(nodes[i].StateChange) <= gossipToTheDeadTime {
+ continue
+ }
+
+ // Move this node to the end
+ nodes[i], nodes[n-numDead-1] = nodes[n-numDead-1], nodes[i]
+ numDead++
+ i--
+ }
+ return n - numDead
+}
+
+// kRandomNodes is used to select up to k random nodes, excluding any nodes where
+// the filter function returns true. It is possible that less than k nodes are
+// returned.
+func kRandomNodes(k int, nodes []*nodeState, filterFn func(*nodeState) bool) []*nodeState {
+ n := len(nodes)
+ kNodes := make([]*nodeState, 0, k)
+OUTER:
+ // Probe up to 3*n times, with large n this is not necessary
+ // since k << n, but with small n we want search to be
+ // exhaustive
+ for i := 0; i < 3*n && len(kNodes) < k; i++ {
+ // Get random node
+ idx := randomOffset(n)
+ node := nodes[idx]
+
+ // Give the filter a shot at it.
+ if filterFn != nil && filterFn(node) {
+ continue OUTER
+ }
+
+ // Check if we have this node already
+ for j := 0; j < len(kNodes); j++ {
+ if node == kNodes[j] {
+ continue OUTER
+ }
+ }
+
+ // Append the node
+ kNodes = append(kNodes, node)
+ }
+ return kNodes
+}
+
+// makeCompoundMessage takes a list of messages and generates
+// a single compound message containing all of them
+func makeCompoundMessage(msgs [][]byte) *bytes.Buffer {
+ // Create a local buffer
+ buf := bytes.NewBuffer(nil)
+
+ // Write out the type
+ buf.WriteByte(uint8(compoundMsg))
+
+ // Write out the number of message
+ buf.WriteByte(uint8(len(msgs)))
+
+ // Add the message lengths
+ for _, m := range msgs {
+ binary.Write(buf, binary.BigEndian, uint16(len(m)))
+ }
+
+ // Append the messages
+ for _, m := range msgs {
+ buf.Write(m)
+ }
+
+ return buf
+}
+
+// decodeCompoundMessage splits a compound message and returns
+// the slices of individual messages. Also returns the number
+// of truncated messages and any potential error
+func decodeCompoundMessage(buf []byte) (trunc int, parts [][]byte, err error) {
+ if len(buf) < 1 {
+ err = fmt.Errorf("missing compound length byte")
+ return
+ }
+ numParts := uint8(buf[0])
+ buf = buf[1:]
+
+ // Check we have enough bytes
+ if len(buf) < int(numParts*2) {
+ err = fmt.Errorf("truncated len slice")
+ return
+ }
+
+ // Decode the lengths
+ lengths := make([]uint16, numParts)
+ for i := 0; i < int(numParts); i++ {
+ lengths[i] = binary.BigEndian.Uint16(buf[i*2 : i*2+2])
+ }
+ buf = buf[numParts*2:]
+
+ // Split each message
+ for idx, msgLen := range lengths {
+ if len(buf) < int(msgLen) {
+ trunc = int(numParts) - idx
+ return
+ }
+
+ // Extract the slice, seek past on the buffer
+ slice := buf[:msgLen]
+ buf = buf[msgLen:]
+ parts = append(parts, slice)
+ }
+ return
+}
+
+// Given a string of the form "host", "host:port",
+// "ipv6::addr" or "[ipv6::address]:port",
+// return true if the string includes a port.
+func hasPort(s string) bool {
+ last := strings.LastIndex(s, ":")
+ if last == -1 {
+ return false
+ }
+ if s[0] == '[' {
+ return s[last-1] == ']'
+ }
+ return strings.Index(s, ":") == last
+}
+
+// compressPayload takes an opaque input buffer, compresses it
+// and wraps it in a compress{} message that is encoded.
+func compressPayload(inp []byte) (*bytes.Buffer, error) {
+ var buf bytes.Buffer
+ compressor := lzw.NewWriter(&buf, lzw.LSB, lzwLitWidth)
+
+ _, err := compressor.Write(inp)
+ if err != nil {
+ return nil, err
+ }
+
+ // Ensure we flush everything out
+ if err := compressor.Close(); err != nil {
+ return nil, err
+ }
+
+ // Create a compressed message
+ c := compress{
+ Algo: lzwAlgo,
+ Buf: buf.Bytes(),
+ }
+ return encode(compressMsg, &c)
+}
+
+// decompressPayload is used to unpack an encoded compress{}
+// message and return its payload uncompressed
+func decompressPayload(msg []byte) ([]byte, error) {
+ // Decode the message
+ var c compress
+ if err := decode(msg, &c); err != nil {
+ return nil, err
+ }
+ return decompressBuffer(&c)
+}
+
+// decompressBuffer is used to decompress the buffer of
+// a single compress message, handling multiple algorithms
+func decompressBuffer(c *compress) ([]byte, error) {
+ // Verify the algorithm
+ if c.Algo != lzwAlgo {
+ return nil, fmt.Errorf("Cannot decompress unknown algorithm %d", c.Algo)
+ }
+
+ // Create a uncompressor
+ uncomp := lzw.NewReader(bytes.NewReader(c.Buf), lzw.LSB, lzwLitWidth)
+ defer uncomp.Close()
+
+ // Read all the data
+ var b bytes.Buffer
+ _, err := io.Copy(&b, uncomp)
+ if err != nil {
+ return nil, err
+ }
+
+ // Return the uncompressed bytes
+ return b.Bytes(), nil
+}
+
+// joinHostPort returns the host:port form of an address, for use with a
+// transport.
+func joinHostPort(host string, port uint16) string {
+ return net.JoinHostPort(host, strconv.Itoa(int(port)))
+}
diff --git a/vendor/github.com/hashicorp/serf/LICENSE b/vendor/github.com/hashicorp/serf/LICENSE
new file mode 100644
index 0000000..c33dcc7
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/LICENSE
@@ -0,0 +1,354 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. “Contributor”
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. “Contributor Version”
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor’s Contribution.
+
+1.3. “Contribution”
+
+ means Covered Software of a particular Contributor.
+
+1.4. “Covered Software”
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. “Incompatible With Secondary Licenses”
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of version
+ 1.1 or earlier of the License, but not also under the terms of a
+ Secondary License.
+
+1.6. “Executable Form”
+
+ means any form of the work other than Source Code Form.
+
+1.7. “Larger Work”
+
+ means a work that combines Covered Software with other material, in a separate
+ file or files, that is not Covered Software.
+
+1.8. “License”
+
+ means this document.
+
+1.9. “Licensable”
+
+ means having the right to grant, to the maximum extent possible, whether at the
+ time of the initial grant or subsequently, any and all of the rights conveyed by
+ this License.
+
+1.10. “Modifications”
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to, deletion
+ from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. “Patent Claims” of a Contributor
+
+ means any patent claim(s), including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by such Contributor that
+ would be infringed, but for the grant of the License, by the making,
+ using, selling, offering for sale, having made, import, or transfer of
+ either its Contributions or its Contributor Version.
+
+1.12. “Secondary License”
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. “Source Code Form”
+
+ means the form of the work preferred for making modifications.
+
+1.14. “You” (or “Your”)
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, “You” includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, “control” means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or as
+ part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its Contributions
+ or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution become
+ effective for each Contribution on the date the Contributor first distributes
+ such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under this
+ License. No additional rights or licenses will be implied from the distribution
+ or licensing of Covered Software under this License. Notwithstanding Section
+ 2.1(b) above, no patent license is granted by a Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party’s
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of its
+ Contributions.
+
+ This License does not grant any rights in the trademarks, service marks, or
+ logos of any Contributor (except as may be necessary to comply with the
+ notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this License
+ (see Section 10.2) or under the terms of a Secondary License (if permitted
+ under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its Contributions
+ are its original creation(s) or it has sufficient rights to grant the
+ rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under applicable
+ copyright doctrines of fair use, fair dealing, or other equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under the
+ terms of this License. You must inform recipients that the Source Code Form
+ of the Covered Software is governed by the terms of this License, and how
+ they can obtain a copy of this License. You may not attempt to alter or
+ restrict the recipients’ rights in the Source Code Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this License,
+ or sublicense it under different terms, provided that the license for
+ the Executable Form does not attempt to limit or alter the recipients’
+ rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for the
+ Covered Software. If the Larger Work is a combination of Covered Software
+ with a work governed by one or more Secondary Licenses, and the Covered
+ Software is not Incompatible With Secondary Licenses, this License permits
+ You to additionally distribute such Covered Software under the terms of
+ such Secondary License(s), so that the recipient of the Larger Work may, at
+ their option, further distribute the Covered Software under the terms of
+ either this License or such Secondary License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices (including
+ copyright notices, patent notices, disclaimers of warranty, or limitations
+ of liability) contained within the Source Code Form of the Covered
+ Software, except that You may alter any license notices to the extent
+ required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on behalf
+ of any Contributor. You must make it absolutely clear that any such
+ warranty, support, indemnity, or liability obligation is offered by You
+ alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute, judicial
+ order, or regulation then You must: (a) comply with the terms of this License
+ to the maximum extent possible; and (b) describe the limitations and the code
+ they affect. Such description must be placed in a text file included with all
+ distributions of the Covered Software under this License. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing basis,
+ if such Contributor fails to notify You of the non-compliance by some
+ reasonable means prior to 60 days after You have come back into compliance.
+ Moreover, Your grants from a particular Contributor are reinstated on an
+ ongoing basis if such Contributor notifies You of the non-compliance by
+ some reasonable means, this is the first time You have received notice of
+ non-compliance with this License from such Contributor, and You become
+ compliant prior to 30 days after Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions, counter-claims,
+ and cross-claims) alleging that a Contributor Version directly or
+ indirectly infringes any patent, then the rights granted to You by any and
+ all Contributors for the Covered Software under Section 2.1 of this License
+ shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an “as is” basis, without
+ warranty of any kind, either expressed, implied, or statutory, including,
+ without limitation, warranties that the Covered Software is free of defects,
+ merchantable, fit for a particular purpose or non-infringing. The entire
+ risk as to the quality and performance of the Covered Software is with You.
+ Should any Covered Software prove defective in any respect, You (not any
+ Contributor) assume the cost of any necessary servicing, repair, or
+ correction. This disclaimer of warranty constitutes an essential part of this
+ License. No use of any Covered Software is authorized under this License
+ except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from such
+ party’s negligence to the extent applicable law prohibits such limitation.
+ Some jurisdictions do not allow the exclusion or limitation of incidental or
+ consequential damages, so this exclusion and limitation may not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts of
+ a jurisdiction where the defendant maintains its principal place of business
+ and such litigation shall be governed by laws of that jurisdiction, without
+ reference to its conflict-of-law provisions. Nothing in this Section shall
+ prevent a party’s ability to bring cross-claims or counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject matter
+ hereof. If any provision of this License is held to be unenforceable, such
+ provision shall be reformed only to the extent necessary to make it
+ enforceable. Any law or regulation which provides that the language of a
+ contract shall be construed against the drafter shall not be used to construe
+ this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version of
+ the License under which You originally received the Covered Software, or
+ under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a modified
+ version of this License if you rename the license and remove any
+ references to the name of the license steward (except to note that such
+ modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
+ If You choose to distribute Source Code Form that is Incompatible With
+ Secondary Licenses under the terms of this version of the License, the
+ notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file, then
+You may include the notice in a location (such as a LICENSE file in a relevant
+directory) where a recipient would be likely to look for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - “Incompatible With Secondary Licenses” Notice
+
+ This Source Code Form is “Incompatible
+ With Secondary Licenses”, as defined by
+ the Mozilla Public License, v. 2.0.
+
diff --git a/vendor/github.com/hashicorp/serf/README.md b/vendor/github.com/hashicorp/serf/README.md
new file mode 100644
index 0000000..ad8210d
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/README.md
@@ -0,0 +1,114 @@
+# Serf
+
+* Website: https://www.serfdom.io
+* IRC: `#serfdom` on Freenode
+* Mailing list: [Google Groups](https://groups.google.com/group/serfdom/)
+
+Serf is a decentralized solution for service discovery and orchestration
+that is lightweight, highly available, and fault tolerant.
+
+Serf runs on Linux, Mac OS X, and Windows. An efficient and lightweight gossip
+protocol is used to communicate with other nodes. Serf can detect node failures
+and notify the rest of the cluster. An event system is built on top of
+Serf, letting you use Serf's gossip protocol to propagate events such
+as deploys, configuration changes, etc. Serf is completely masterless
+with no single point of failure.
+
+Here are some example use cases of Serf, though there are many others:
+
+* Discovering web servers and automatically adding them to a load balancer
+* Organizing many memcached or redis nodes into a cluster, perhaps with
+ something like [twemproxy](https://github.com/twitter/twemproxy) or
+ maybe just configuring an application with the address of all the
+ nodes
+* Triggering web deploys using the event system built on top of Serf
+* Propagating changes to configuration to relevant nodes.
+* Updating DNS records to reflect cluster changes as they occur.
+* Much, much more.
+
+## Quick Start
+
+First, [download a pre-built Serf binary](https://www.serfdom.io/downloads.html)
+for your operating system or [compile Serf yourself](#developing-serf).
+
+Next, let's start a couple Serf agents. Agents run until they're told to quit
+and handle the communication of maintenance tasks of Serf. In a real Serf
+setup, each node in your system will run one or more Serf agents (it can
+run multiple agents if you're running multiple cluster types. e.g. web
+servers vs. memcached servers).
+
+Start each Serf agent in a separate terminal session so that we can see
+the output of each. Start the first agent:
+
+```
+$ serf agent -node=foo -bind=127.0.0.1:5000 -rpc-addr=127.0.0.1:7373
+...
+```
+
+Start the second agent in another terminal session (while the first is still
+running):
+
+```
+$ serf agent -node=bar -bind=127.0.0.1:5001 -rpc-addr=127.0.0.1:7374
+...
+```
+
+At this point two Serf agents are running independently but are still
+unaware of each other. Let's now tell the first agent to join an existing
+cluster (the second agent). When starting a Serf agent, you must join an
+existing cluster by specifying at least one existing member. After this,
+Serf gossips and the remainder of the cluster becomes aware of the join.
+Run the following commands in a third terminal session.
+
+```
+$ serf join 127.0.0.1:5001
+...
+```
+
+If you're watching your terminals, you should see both Serf agents
+become aware of the join. You can prove it by running `serf members`
+to see the members of the Serf cluster:
+
+```
+$ serf members
+foo 127.0.0.1:5000 alive
+bar 127.0.0.1:5001 alive
+...
+```
+
+At this point, you can ctrl-C or force kill either Serf agent, and they'll
+update their membership lists appropriately. If you ctrl-C a Serf agent,
+it will gracefully leave by notifying the cluster of its intent to leave.
+If you force kill an agent, it will eventually (usually within seconds)
+be detected by another member of the cluster which will notify the
+cluster of the node failure.
+
+## Documentation
+
+Full, comprehensive documentation is viewable on the Serf website:
+
+https://www.serfdom.io/docs
+
+## Developing Serf
+
+If you wish to work on Serf itself, you'll first need [Go](https://golang.org)
+installed (version 1.2+ is _required_). Make sure you have Go properly
+[installed](https://golang.org/doc/install),
+including setting up your [GOPATH](https://golang.org/doc/code.html#GOPATH).
+
+Next, clone this repository into `$GOPATH/src/github.com/hashicorp/serf` and
+then just type `make`. In a few moments, you'll have a working `serf` executable:
+
+```
+$ make
+...
+$ bin/serf
+...
+```
+
+*note: `make` will also place a copy of the executable under $GOPATH/bin*
+
+You can run tests by typing `make test`.
+
+If you make any changes to the code, run `make format` in order to automatically
+format the code according to Go standards.
diff --git a/vendor/github.com/hashicorp/serf/coordinate/client.go b/vendor/github.com/hashicorp/serf/coordinate/client.go
new file mode 100644
index 0000000..613bfff
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/coordinate/client.go
@@ -0,0 +1,180 @@
+package coordinate
+
+import (
+ "fmt"
+ "math"
+ "sort"
+ "sync"
+ "time"
+)
+
+// Client manages the estimated network coordinate for a given node, and adjusts
+// it as the node observes round trip times and estimated coordinates from other
+// nodes. The core algorithm is based on Vivaldi, see the documentation for Config
+// for more details.
+type Client struct {
+ // coord is the current estimate of the client's network coordinate.
+ coord *Coordinate
+
+ // origin is a coordinate sitting at the origin.
+ origin *Coordinate
+
+ // config contains the tuning parameters that govern the performance of
+ // the algorithm.
+ config *Config
+
+ // adjustmentIndex is the current index into the adjustmentSamples slice.
+ adjustmentIndex uint
+
+ // adjustment is used to store samples for the adjustment calculation.
+ adjustmentSamples []float64
+
+ // latencyFilterSamples is used to store the last several RTT samples,
+ // keyed by node name. We will use the config's LatencyFilterSamples
+ // value to determine how many samples we keep, per node.
+ latencyFilterSamples map[string][]float64
+
+ // mutex enables safe concurrent access to the client.
+ mutex sync.RWMutex
+}
+
+// NewClient creates a new Client and verifies the configuration is valid.
+func NewClient(config *Config) (*Client, error) {
+ if !(config.Dimensionality > 0) {
+ return nil, fmt.Errorf("dimensionality must be >0")
+ }
+
+ return &Client{
+ coord: NewCoordinate(config),
+ origin: NewCoordinate(config),
+ config: config,
+ adjustmentIndex: 0,
+ adjustmentSamples: make([]float64, config.AdjustmentWindowSize),
+ latencyFilterSamples: make(map[string][]float64),
+ }, nil
+}
+
+// GetCoordinate returns a copy of the coordinate for this client.
+func (c *Client) GetCoordinate() *Coordinate {
+ c.mutex.RLock()
+ defer c.mutex.RUnlock()
+
+ return c.coord.Clone()
+}
+
+// SetCoordinate forces the client's coordinate to a known state.
+func (c *Client) SetCoordinate(coord *Coordinate) {
+ c.mutex.Lock()
+ defer c.mutex.Unlock()
+
+ c.coord = coord.Clone()
+}
+
+// ForgetNode removes any client state for the given node.
+func (c *Client) ForgetNode(node string) {
+ c.mutex.Lock()
+ defer c.mutex.Unlock()
+
+ delete(c.latencyFilterSamples, node)
+}
+
+// latencyFilter applies a simple moving median filter with a new sample for
+// a node. This assumes that the mutex has been locked already.
+func (c *Client) latencyFilter(node string, rttSeconds float64) float64 {
+ samples, ok := c.latencyFilterSamples[node]
+ if !ok {
+ samples = make([]float64, 0, c.config.LatencyFilterSize)
+ }
+
+ // Add the new sample and trim the list, if needed.
+ samples = append(samples, rttSeconds)
+ if len(samples) > int(c.config.LatencyFilterSize) {
+ samples = samples[1:]
+ }
+ c.latencyFilterSamples[node] = samples
+
+ // Sort a copy of the samples and return the median.
+ sorted := make([]float64, len(samples))
+ copy(sorted, samples)
+ sort.Float64s(sorted)
+ return sorted[len(sorted)/2]
+}
+
+// updateVivialdi updates the Vivaldi portion of the client's coordinate. This
+// assumes that the mutex has been locked already.
+func (c *Client) updateVivaldi(other *Coordinate, rttSeconds float64) {
+ const zeroThreshold = 1.0e-6
+
+ dist := c.coord.DistanceTo(other).Seconds()
+ if rttSeconds < zeroThreshold {
+ rttSeconds = zeroThreshold
+ }
+ wrongness := math.Abs(dist-rttSeconds) / rttSeconds
+
+ totalError := c.coord.Error + other.Error
+ if totalError < zeroThreshold {
+ totalError = zeroThreshold
+ }
+ weight := c.coord.Error / totalError
+
+ c.coord.Error = c.config.VivaldiCE*weight*wrongness + c.coord.Error*(1.0-c.config.VivaldiCE*weight)
+ if c.coord.Error > c.config.VivaldiErrorMax {
+ c.coord.Error = c.config.VivaldiErrorMax
+ }
+
+ delta := c.config.VivaldiCC * weight
+ force := delta * (rttSeconds - dist)
+ c.coord = c.coord.ApplyForce(c.config, force, other)
+}
+
+// updateAdjustment updates the adjustment portion of the client's coordinate, if
+// the feature is enabled. This assumes that the mutex has been locked already.
+func (c *Client) updateAdjustment(other *Coordinate, rttSeconds float64) {
+ if c.config.AdjustmentWindowSize == 0 {
+ return
+ }
+
+ // Note that the existing adjustment factors don't figure in to this
+ // calculation so we use the raw distance here.
+ dist := c.coord.rawDistanceTo(other)
+ c.adjustmentSamples[c.adjustmentIndex] = rttSeconds - dist
+ c.adjustmentIndex = (c.adjustmentIndex + 1) % c.config.AdjustmentWindowSize
+
+ sum := 0.0
+ for _, sample := range c.adjustmentSamples {
+ sum += sample
+ }
+ c.coord.Adjustment = sum / (2.0 * float64(c.config.AdjustmentWindowSize))
+}
+
+// updateGravity applies a small amount of gravity to pull coordinates towards
+// the center of the coordinate system to combat drift. This assumes that the
+// mutex is locked already.
+func (c *Client) updateGravity() {
+ dist := c.origin.DistanceTo(c.coord).Seconds()
+ force := -1.0 * math.Pow(dist/c.config.GravityRho, 2.0)
+ c.coord = c.coord.ApplyForce(c.config, force, c.origin)
+}
+
+// Update takes other, a coordinate for another node, and rtt, a round trip
+// time observation for a ping to that node, and updates the estimated position of
+// the client's coordinate. Returns the updated coordinate.
+func (c *Client) Update(node string, other *Coordinate, rtt time.Duration) *Coordinate {
+ c.mutex.Lock()
+ defer c.mutex.Unlock()
+
+ rttSeconds := c.latencyFilter(node, rtt.Seconds())
+ c.updateVivaldi(other, rttSeconds)
+ c.updateAdjustment(other, rttSeconds)
+ c.updateGravity()
+ return c.coord.Clone()
+}
+
+// DistanceTo returns the estimated RTT from the client's coordinate to other, the
+// coordinate for another node.
+func (c *Client) DistanceTo(other *Coordinate) time.Duration {
+ c.mutex.RLock()
+ defer c.mutex.RUnlock()
+
+ return c.coord.DistanceTo(other)
+}
diff --git a/vendor/github.com/hashicorp/serf/coordinate/config.go b/vendor/github.com/hashicorp/serf/coordinate/config.go
new file mode 100644
index 0000000..a5b3aad
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/coordinate/config.go
@@ -0,0 +1,70 @@
+package coordinate
+
+// Config is used to set the parameters of the Vivaldi-based coordinate mapping
+// algorithm.
+//
+// The following references are called out at various points in the documentation
+// here:
+//
+// [1] Dabek, Frank, et al. "Vivaldi: A decentralized network coordinate system."
+// ACM SIGCOMM Computer Communication Review. Vol. 34. No. 4. ACM, 2004.
+// [2] Ledlie, Jonathan, Paul Gardner, and Margo I. Seltzer. "Network Coordinates
+// in the Wild." NSDI. Vol. 7. 2007.
+// [3] Lee, Sanghwan, et al. "On suitability of Euclidean embedding for
+// host-based network coordinate systems." Networking, IEEE/ACM Transactions
+// on 18.1 (2010): 27-40.
+type Config struct {
+ // The dimensionality of the coordinate system. As discussed in [2], more
+ // dimensions improves the accuracy of the estimates up to a point. Per [2]
+ // we chose 4 dimensions plus a non-Euclidean height.
+ Dimensionality uint
+
+ // VivaldiErrorMax is the default error value when a node hasn't yet made
+ // any observations. It also serves as an upper limit on the error value in
+ // case observations cause the error value to increase without bound.
+ VivaldiErrorMax float64
+
+ // VivaldiCE is a tuning factor that controls the maximum impact an
+ // observation can have on a node's confidence. See [1] for more details.
+ VivaldiCE float64
+
+ // VivaldiCC is a tuning factor that controls the maximum impact an
+ // observation can have on a node's coordinate. See [1] for more details.
+ VivaldiCC float64
+
+ // AdjustmentWindowSize is a tuning factor that determines how many samples
+ // we retain to calculate the adjustment factor as discussed in [3]. Setting
+ // this to zero disables this feature.
+ AdjustmentWindowSize uint
+
+ // HeightMin is the minimum value of the height parameter. Since this
+ // always must be positive, it will introduce a small amount error, so
+ // the chosen value should be relatively small compared to "normal"
+ // coordinates.
+ HeightMin float64
+
+ // LatencyFilterSamples is the maximum number of samples that are retained
+ // per node, in order to compute a median. The intent is to ride out blips
+ // but still keep the delay low, since our time to probe any given node is
+ // pretty infrequent. See [2] for more details.
+ LatencyFilterSize uint
+
+ // GravityRho is a tuning factor that sets how much gravity has an effect
+ // to try to re-center coordinates. See [2] for more details.
+ GravityRho float64
+}
+
+// DefaultConfig returns a Config that has some default values suitable for
+// basic testing of the algorithm, but not tuned to any particular type of cluster.
+func DefaultConfig() *Config {
+ return &Config{
+ Dimensionality: 8,
+ VivaldiErrorMax: 1.5,
+ VivaldiCE: 0.25,
+ VivaldiCC: 0.25,
+ AdjustmentWindowSize: 20,
+ HeightMin: 10.0e-6,
+ LatencyFilterSize: 3,
+ GravityRho: 150.0,
+ }
+}
diff --git a/vendor/github.com/hashicorp/serf/coordinate/coordinate.go b/vendor/github.com/hashicorp/serf/coordinate/coordinate.go
new file mode 100644
index 0000000..c9194e0
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/coordinate/coordinate.go
@@ -0,0 +1,183 @@
+package coordinate
+
+import (
+ "math"
+ "math/rand"
+ "time"
+)
+
+// Coordinate is a specialized structure for holding network coordinates for the
+// Vivaldi-based coordinate mapping algorithm. All of the fields should be public
+// to enable this to be serialized. All values in here are in units of seconds.
+type Coordinate struct {
+ // Vec is the Euclidean portion of the coordinate. This is used along
+ // with the other fields to provide an overall distance estimate. The
+ // units here are seconds.
+ Vec []float64
+
+ // Err reflects the confidence in the given coordinate and is updated
+ // dynamically by the Vivaldi Client. This is dimensionless.
+ Error float64
+
+ // Adjustment is a distance offset computed based on a calculation over
+ // observations from all other nodes over a fixed window and is updated
+ // dynamically by the Vivaldi Client. The units here are seconds.
+ Adjustment float64
+
+ // Height is a distance offset that accounts for non-Euclidean effects
+ // which model the access links from nodes to the core Internet. The access
+ // links are usually set by bandwidth and congestion, and the core links
+ // usually follow distance based on geography.
+ Height float64
+}
+
+const (
+ // secondsToNanoseconds is used to convert float seconds to nanoseconds.
+ secondsToNanoseconds = 1.0e9
+
+ // zeroThreshold is used to decide if two coordinates are on top of each
+ // other.
+ zeroThreshold = 1.0e-6
+)
+
+// ErrDimensionalityConflict will be panic-d if you try to perform operations
+// with incompatible dimensions.
+type DimensionalityConflictError struct{}
+
+// Adds the error interface.
+func (e DimensionalityConflictError) Error() string {
+ return "coordinate dimensionality does not match"
+}
+
+// NewCoordinate creates a new coordinate at the origin, using the given config
+// to supply key initial values.
+func NewCoordinate(config *Config) *Coordinate {
+ return &Coordinate{
+ Vec: make([]float64, config.Dimensionality),
+ Error: config.VivaldiErrorMax,
+ Adjustment: 0.0,
+ Height: config.HeightMin,
+ }
+}
+
+// Clone creates an independent copy of this coordinate.
+func (c *Coordinate) Clone() *Coordinate {
+ vec := make([]float64, len(c.Vec))
+ copy(vec, c.Vec)
+ return &Coordinate{
+ Vec: vec,
+ Error: c.Error,
+ Adjustment: c.Adjustment,
+ Height: c.Height,
+ }
+}
+
+// IsCompatibleWith checks to see if the two coordinates are compatible
+// dimensionally. If this returns true then you are guaranteed to not get
+// any runtime errors operating on them.
+func (c *Coordinate) IsCompatibleWith(other *Coordinate) bool {
+ return len(c.Vec) == len(other.Vec)
+}
+
+// ApplyForce returns the result of applying the force from the direction of the
+// other coordinate.
+func (c *Coordinate) ApplyForce(config *Config, force float64, other *Coordinate) *Coordinate {
+ if !c.IsCompatibleWith(other) {
+ panic(DimensionalityConflictError{})
+ }
+
+ ret := c.Clone()
+ unit, mag := unitVectorAt(c.Vec, other.Vec)
+ ret.Vec = add(ret.Vec, mul(unit, force))
+ if mag > zeroThreshold {
+ ret.Height = (ret.Height+other.Height)*force/mag + ret.Height
+ ret.Height = math.Max(ret.Height, config.HeightMin)
+ }
+ return ret
+}
+
+// DistanceTo returns the distance between this coordinate and the other
+// coordinate, including adjustments.
+func (c *Coordinate) DistanceTo(other *Coordinate) time.Duration {
+ if !c.IsCompatibleWith(other) {
+ panic(DimensionalityConflictError{})
+ }
+
+ dist := c.rawDistanceTo(other)
+ adjustedDist := dist + c.Adjustment + other.Adjustment
+ if adjustedDist > 0.0 {
+ dist = adjustedDist
+ }
+ return time.Duration(dist * secondsToNanoseconds)
+}
+
+// rawDistanceTo returns the Vivaldi distance between this coordinate and the
+// other coordinate in seconds, not including adjustments. This assumes the
+// dimensions have already been checked to be compatible.
+func (c *Coordinate) rawDistanceTo(other *Coordinate) float64 {
+ return magnitude(diff(c.Vec, other.Vec)) + c.Height + other.Height
+}
+
+// add returns the sum of vec1 and vec2. This assumes the dimensions have
+// already been checked to be compatible.
+func add(vec1 []float64, vec2 []float64) []float64 {
+ ret := make([]float64, len(vec1))
+ for i, _ := range ret {
+ ret[i] = vec1[i] + vec2[i]
+ }
+ return ret
+}
+
+// diff returns the difference between the vec1 and vec2. This assumes the
+// dimensions have already been checked to be compatible.
+func diff(vec1 []float64, vec2 []float64) []float64 {
+ ret := make([]float64, len(vec1))
+ for i, _ := range ret {
+ ret[i] = vec1[i] - vec2[i]
+ }
+ return ret
+}
+
+// mul returns vec multiplied by a scalar factor.
+func mul(vec []float64, factor float64) []float64 {
+ ret := make([]float64, len(vec))
+ for i, _ := range vec {
+ ret[i] = vec[i] * factor
+ }
+ return ret
+}
+
+// magnitude computes the magnitude of the vec.
+func magnitude(vec []float64) float64 {
+ sum := 0.0
+ for i, _ := range vec {
+ sum += vec[i] * vec[i]
+ }
+ return math.Sqrt(sum)
+}
+
+// unitVectorAt returns a unit vector pointing at vec1 from vec2. If the two
+// positions are the same then a random unit vector is returned. We also return
+// the distance between the points for use in the later height calculation.
+func unitVectorAt(vec1 []float64, vec2 []float64) ([]float64, float64) {
+ ret := diff(vec1, vec2)
+
+ // If the coordinates aren't on top of each other we can normalize.
+ if mag := magnitude(ret); mag > zeroThreshold {
+ return mul(ret, 1.0/mag), mag
+ }
+
+ // Otherwise, just return a random unit vector.
+ for i, _ := range ret {
+ ret[i] = rand.Float64() - 0.5
+ }
+ if mag := magnitude(ret); mag > zeroThreshold {
+ return mul(ret, 1.0/mag), 0.0
+ }
+
+ // And finally just give up and make a unit vector along the first
+ // dimension. This should be exceedingly rare.
+ ret = make([]float64, len(ret))
+ ret[0] = 1.0
+ return ret, 0.0
+}
diff --git a/vendor/github.com/hashicorp/serf/coordinate/phantom.go b/vendor/github.com/hashicorp/serf/coordinate/phantom.go
new file mode 100644
index 0000000..6fb033c
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/coordinate/phantom.go
@@ -0,0 +1,187 @@
+package coordinate
+
+import (
+ "fmt"
+ "math"
+ "math/rand"
+ "time"
+)
+
+// GenerateClients returns a slice with nodes number of clients, all with the
+// given config.
+func GenerateClients(nodes int, config *Config) ([]*Client, error) {
+ clients := make([]*Client, nodes)
+ for i, _ := range clients {
+ client, err := NewClient(config)
+ if err != nil {
+ return nil, err
+ }
+
+ clients[i] = client
+ }
+ return clients, nil
+}
+
+// GenerateLine returns a truth matrix as if all the nodes are in a straight linke
+// with the given spacing between them.
+func GenerateLine(nodes int, spacing time.Duration) [][]time.Duration {
+ truth := make([][]time.Duration, nodes)
+ for i := range truth {
+ truth[i] = make([]time.Duration, nodes)
+ }
+
+ for i := 0; i < nodes; i++ {
+ for j := i + 1; j < nodes; j++ {
+ rtt := time.Duration(j-i) * spacing
+ truth[i][j], truth[j][i] = rtt, rtt
+ }
+ }
+ return truth
+}
+
+// GenerateGrid returns a truth matrix as if all the nodes are in a two dimensional
+// grid with the given spacing between them.
+func GenerateGrid(nodes int, spacing time.Duration) [][]time.Duration {
+ truth := make([][]time.Duration, nodes)
+ for i := range truth {
+ truth[i] = make([]time.Duration, nodes)
+ }
+
+ n := int(math.Sqrt(float64(nodes)))
+ for i := 0; i < nodes; i++ {
+ for j := i + 1; j < nodes; j++ {
+ x1, y1 := float64(i%n), float64(i/n)
+ x2, y2 := float64(j%n), float64(j/n)
+ dx, dy := x2-x1, y2-y1
+ dist := math.Sqrt(dx*dx + dy*dy)
+ rtt := time.Duration(dist * float64(spacing))
+ truth[i][j], truth[j][i] = rtt, rtt
+ }
+ }
+ return truth
+}
+
+// GenerateSplit returns a truth matrix as if half the nodes are close together in
+// one location and half the nodes are close together in another. The lan factor
+// is used to separate the nodes locally and the wan factor represents the split
+// between the two sides.
+func GenerateSplit(nodes int, lan time.Duration, wan time.Duration) [][]time.Duration {
+ truth := make([][]time.Duration, nodes)
+ for i := range truth {
+ truth[i] = make([]time.Duration, nodes)
+ }
+
+ split := nodes / 2
+ for i := 0; i < nodes; i++ {
+ for j := i + 1; j < nodes; j++ {
+ rtt := lan
+ if (i <= split && j > split) || (i > split && j <= split) {
+ rtt += wan
+ }
+ truth[i][j], truth[j][i] = rtt, rtt
+ }
+ }
+ return truth
+}
+
+// GenerateCircle returns a truth matrix for a set of nodes, evenly distributed
+// around a circle with the given radius. The first node is at the "center" of the
+// circle because it's equidistant from all the other nodes, but we place it at
+// double the radius, so it should show up above all the other nodes in height.
+func GenerateCircle(nodes int, radius time.Duration) [][]time.Duration {
+ truth := make([][]time.Duration, nodes)
+ for i := range truth {
+ truth[i] = make([]time.Duration, nodes)
+ }
+
+ for i := 0; i < nodes; i++ {
+ for j := i + 1; j < nodes; j++ {
+ var rtt time.Duration
+ if i == 0 {
+ rtt = 2 * radius
+ } else {
+ t1 := 2.0 * math.Pi * float64(i) / float64(nodes)
+ x1, y1 := math.Cos(t1), math.Sin(t1)
+ t2 := 2.0 * math.Pi * float64(j) / float64(nodes)
+ x2, y2 := math.Cos(t2), math.Sin(t2)
+ dx, dy := x2-x1, y2-y1
+ dist := math.Sqrt(dx*dx + dy*dy)
+ rtt = time.Duration(dist * float64(radius))
+ }
+ truth[i][j], truth[j][i] = rtt, rtt
+ }
+ }
+ return truth
+}
+
+// GenerateRandom returns a truth matrix for a set of nodes with normally
+// distributed delays, with the given mean and deviation. The RNG is re-seeded
+// so you always get the same matrix for a given size.
+func GenerateRandom(nodes int, mean time.Duration, deviation time.Duration) [][]time.Duration {
+ rand.Seed(1)
+
+ truth := make([][]time.Duration, nodes)
+ for i := range truth {
+ truth[i] = make([]time.Duration, nodes)
+ }
+
+ for i := 0; i < nodes; i++ {
+ for j := i + 1; j < nodes; j++ {
+ rttSeconds := rand.NormFloat64()*deviation.Seconds() + mean.Seconds()
+ rtt := time.Duration(rttSeconds * secondsToNanoseconds)
+ truth[i][j], truth[j][i] = rtt, rtt
+ }
+ }
+ return truth
+}
+
+// Simulate runs the given number of cycles using the given list of clients and
+// truth matrix. On each cycle, each client will pick a random node and observe
+// the truth RTT, updating its coordinate estimate. The RNG is re-seeded for
+// each simulation run to get deterministic results (for this algorithm and the
+// underlying algorithm which will use random numbers for position vectors when
+// starting out with everything at the origin).
+func Simulate(clients []*Client, truth [][]time.Duration, cycles int) {
+ rand.Seed(1)
+
+ nodes := len(clients)
+ for cycle := 0; cycle < cycles; cycle++ {
+ for i, _ := range clients {
+ if j := rand.Intn(nodes); j != i {
+ c := clients[j].GetCoordinate()
+ rtt := truth[i][j]
+ node := fmt.Sprintf("node_%d", j)
+ clients[i].Update(node, c, rtt)
+ }
+ }
+ }
+}
+
+// Stats is returned from the Evaluate function with a summary of the algorithm
+// performance.
+type Stats struct {
+ ErrorMax float64
+ ErrorAvg float64
+}
+
+// Evaluate uses the coordinates of the given clients to calculate estimated
+// distances and compares them with the given truth matrix, returning summary
+// stats.
+func Evaluate(clients []*Client, truth [][]time.Duration) (stats Stats) {
+ nodes := len(clients)
+ count := 0
+ for i := 0; i < nodes; i++ {
+ for j := i + 1; j < nodes; j++ {
+ est := clients[i].DistanceTo(clients[j].GetCoordinate()).Seconds()
+ actual := truth[i][j].Seconds()
+ error := math.Abs(est-actual) / actual
+ stats.ErrorMax = math.Max(stats.ErrorMax, error)
+ stats.ErrorAvg += error
+ count += 1
+ }
+ }
+
+ stats.ErrorAvg /= float64(count)
+ fmt.Printf("Error avg=%9.6f max=%9.6f\n", stats.ErrorAvg, stats.ErrorMax)
+ return
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/broadcast.go b/vendor/github.com/hashicorp/serf/serf/broadcast.go
new file mode 100644
index 0000000..d20728f
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/broadcast.go
@@ -0,0 +1,27 @@
+package serf
+
+import (
+ "github.com/hashicorp/memberlist"
+)
+
+// broadcast is an implementation of memberlist.Broadcast and is used
+// to manage broadcasts across the memberlist channel that are related
+// only to Serf.
+type broadcast struct {
+ msg []byte
+ notify chan<- struct{}
+}
+
+func (b *broadcast) Invalidates(other memberlist.Broadcast) bool {
+ return false
+}
+
+func (b *broadcast) Message() []byte {
+ return b.msg
+}
+
+func (b *broadcast) Finished() {
+ if b.notify != nil {
+ close(b.notify)
+ }
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/coalesce.go b/vendor/github.com/hashicorp/serf/serf/coalesce.go
new file mode 100644
index 0000000..567943b
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/coalesce.go
@@ -0,0 +1,80 @@
+package serf
+
+import (
+ "time"
+)
+
+// coalescer is a simple interface that must be implemented to be
+// used inside of a coalesceLoop
+type coalescer interface {
+ // Can the coalescer handle this event, if not it is
+ // directly passed through to the destination channel
+ Handle(Event) bool
+
+ // Invoked to coalesce the given event
+ Coalesce(Event)
+
+ // Invoked to flush the coalesced events
+ Flush(outChan chan<- Event)
+}
+
+// coalescedEventCh returns an event channel where the events are coalesced
+// using the given coalescer.
+func coalescedEventCh(outCh chan<- Event, shutdownCh <-chan struct{},
+ cPeriod time.Duration, qPeriod time.Duration, c coalescer) chan<- Event {
+ inCh := make(chan Event, 1024)
+ go coalesceLoop(inCh, outCh, shutdownCh, cPeriod, qPeriod, c)
+ return inCh
+}
+
+// coalesceLoop is a simple long-running routine that manages the high-level
+// flow of coalescing based on quiescence and a maximum quantum period.
+func coalesceLoop(inCh <-chan Event, outCh chan<- Event, shutdownCh <-chan struct{},
+ coalescePeriod time.Duration, quiescentPeriod time.Duration, c coalescer) {
+ var quiescent <-chan time.Time
+ var quantum <-chan time.Time
+ shutdown := false
+
+INGEST:
+ // Reset the timers
+ quantum = nil
+ quiescent = nil
+
+ for {
+ select {
+ case e := <-inCh:
+ // Ignore any non handled events
+ if !c.Handle(e) {
+ outCh <- e
+ continue
+ }
+
+ // Start a new quantum if we need to
+ // and restart the quiescent timer
+ if quantum == nil {
+ quantum = time.After(coalescePeriod)
+ }
+ quiescent = time.After(quiescentPeriod)
+
+ // Coalesce the event
+ c.Coalesce(e)
+
+ case <-quantum:
+ goto FLUSH
+ case <-quiescent:
+ goto FLUSH
+ case <-shutdownCh:
+ shutdown = true
+ goto FLUSH
+ }
+ }
+
+FLUSH:
+ // Flush the coalesced events
+ c.Flush(outCh)
+
+ // Restart ingestion if we are not done
+ if !shutdown {
+ goto INGEST
+ }
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/coalesce_member.go b/vendor/github.com/hashicorp/serf/serf/coalesce_member.go
new file mode 100644
index 0000000..82fdb8d
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/coalesce_member.go
@@ -0,0 +1,68 @@
+package serf
+
+type coalesceEvent struct {
+ Type EventType
+ Member *Member
+}
+
+type memberEventCoalescer struct {
+ lastEvents map[string]EventType
+ latestEvents map[string]coalesceEvent
+}
+
+func (c *memberEventCoalescer) Handle(e Event) bool {
+ switch e.EventType() {
+ case EventMemberJoin:
+ return true
+ case EventMemberLeave:
+ return true
+ case EventMemberFailed:
+ return true
+ case EventMemberUpdate:
+ return true
+ case EventMemberReap:
+ return true
+ default:
+ return false
+ }
+}
+
+func (c *memberEventCoalescer) Coalesce(raw Event) {
+ e := raw.(MemberEvent)
+ for _, m := range e.Members {
+ c.latestEvents[m.Name] = coalesceEvent{
+ Type: e.Type,
+ Member: &m,
+ }
+ }
+}
+
+func (c *memberEventCoalescer) Flush(outCh chan<- Event) {
+ // Coalesce the various events we got into a single set of events.
+ events := make(map[EventType]*MemberEvent)
+ for name, cevent := range c.latestEvents {
+ previous, ok := c.lastEvents[name]
+
+ // If we sent the same event before, then ignore
+ // unless it is a MemberUpdate
+ if ok && previous == cevent.Type && cevent.Type != EventMemberUpdate {
+ continue
+ }
+
+ // Update our last event
+ c.lastEvents[name] = cevent.Type
+
+ // Add it to our event
+ newEvent, ok := events[cevent.Type]
+ if !ok {
+ newEvent = &MemberEvent{Type: cevent.Type}
+ events[cevent.Type] = newEvent
+ }
+ newEvent.Members = append(newEvent.Members, *cevent.Member)
+ }
+
+ // Send out those events
+ for _, event := range events {
+ outCh <- *event
+ }
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/coalesce_user.go b/vendor/github.com/hashicorp/serf/serf/coalesce_user.go
new file mode 100644
index 0000000..1551b6c
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/coalesce_user.go
@@ -0,0 +1,52 @@
+package serf
+
+type latestUserEvents struct {
+ LTime LamportTime
+ Events []Event
+}
+
+type userEventCoalescer struct {
+ // Maps an event name into the latest versions
+ events map[string]*latestUserEvents
+}
+
+func (c *userEventCoalescer) Handle(e Event) bool {
+ // Only handle EventUser messages
+ if e.EventType() != EventUser {
+ return false
+ }
+
+ // Check if coalescing is enabled
+ user := e.(UserEvent)
+ return user.Coalesce
+}
+
+func (c *userEventCoalescer) Coalesce(e Event) {
+ user := e.(UserEvent)
+ latest, ok := c.events[user.Name]
+
+ // Create a new entry if there are none, or
+ // if this message has the newest LTime
+ if !ok || latest.LTime < user.LTime {
+ latest = &latestUserEvents{
+ LTime: user.LTime,
+ Events: []Event{e},
+ }
+ c.events[user.Name] = latest
+ return
+ }
+
+ // If the the same age, save it
+ if latest.LTime == user.LTime {
+ latest.Events = append(latest.Events, e)
+ }
+}
+
+func (c *userEventCoalescer) Flush(outChan chan<- Event) {
+ for _, latest := range c.events {
+ for _, e := range latest.Events {
+ outChan <- e
+ }
+ }
+ c.events = make(map[string]*latestUserEvents)
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/config.go b/vendor/github.com/hashicorp/serf/serf/config.go
new file mode 100644
index 0000000..87cba9f
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/config.go
@@ -0,0 +1,251 @@
+package serf
+
+import (
+ "io"
+ "os"
+ "time"
+
+ "github.com/hashicorp/memberlist"
+)
+
+// ProtocolVersionMap is the mapping of Serf delegate protocol versions
+// to memberlist protocol versions. We mask the memberlist protocols using
+// our own protocol version.
+var ProtocolVersionMap map[uint8]uint8
+
+func init() {
+ ProtocolVersionMap = map[uint8]uint8{
+ 4: 2,
+ 3: 2,
+ 2: 2,
+ }
+}
+
+// Config is the configuration for creating a Serf instance.
+type Config struct {
+ // The name of this node. This must be unique in the cluster. If this
+ // is not set, Serf will set it to the hostname of the running machine.
+ NodeName string
+
+ // The tags for this role, if any. This is used to provide arbitrary
+ // key/value metadata per-node. For example, a "role" tag may be used to
+ // differentiate "load-balancer" from a "web" role as parts of the same cluster.
+ // Tags are deprecating 'Role', and instead it acts as a special key in this
+ // map.
+ Tags map[string]string
+
+ // EventCh is a channel that receives all the Serf events. The events
+ // are sent on this channel in proper ordering. Care must be taken that
+ // this channel doesn't block, either by processing the events quick
+ // enough or buffering the channel, otherwise it can block state updates
+ // within Serf itself. If no EventCh is specified, no events will be fired,
+ // but point-in-time snapshots of members can still be retrieved by
+ // calling Members on Serf.
+ EventCh chan<- Event
+
+ // ProtocolVersion is the protocol version to speak. This must be between
+ // ProtocolVersionMin and ProtocolVersionMax.
+ ProtocolVersion uint8
+
+ // BroadcastTimeout is the amount of time to wait for a broadcast
+ // message to be sent to the cluster. Broadcast messages are used for
+ // things like leave messages and force remove messages. If this is not
+ // set, a timeout of 5 seconds will be set.
+ BroadcastTimeout time.Duration
+
+ // The settings below relate to Serf's event coalescence feature. Serf
+ // is able to coalesce multiple events into single events in order to
+ // reduce the amount of noise that is sent along the EventCh. For example
+ // if five nodes quickly join, the EventCh will be sent one EventMemberJoin
+ // containing the five nodes rather than five individual EventMemberJoin
+ // events. Coalescence can mitigate potential flapping behavior.
+ //
+ // Coalescence is disabled by default and can be enabled by setting
+ // CoalescePeriod.
+ //
+ // CoalescePeriod specifies the time duration to coalesce events.
+ // For example, if this is set to 5 seconds, then all events received
+ // within 5 seconds that can be coalesced will be.
+ //
+ // QuiescentPeriod specifies the duration of time where if no events
+ // are received, coalescence immediately happens. For example, if
+ // CoalscePeriod is set to 10 seconds but QuiscentPeriod is set to 2
+ // seconds, then the events will be coalesced and dispatched if no
+ // new events are received within 2 seconds of the last event. Otherwise,
+ // every event will always be delayed by at least 10 seconds.
+ CoalescePeriod time.Duration
+ QuiescentPeriod time.Duration
+
+ // The settings below relate to Serf's user event coalescing feature.
+ // The settings operate like above but only affect user messages and
+ // not the Member* messages that Serf generates.
+ UserCoalescePeriod time.Duration
+ UserQuiescentPeriod time.Duration
+
+ // The settings below relate to Serf keeping track of recently
+ // failed/left nodes and attempting reconnects.
+ //
+ // ReapInterval is the interval when the reaper runs. If this is not
+ // set (it is zero), it will be set to a reasonable default.
+ //
+ // ReconnectInterval is the interval when we attempt to reconnect
+ // to failed nodes. If this is not set (it is zero), it will be set
+ // to a reasonable default.
+ //
+ // ReconnectTimeout is the amount of time to attempt to reconnect to
+ // a failed node before giving up and considering it completely gone.
+ //
+ // TombstoneTimeout is the amount of time to keep around nodes
+ // that gracefully left as tombstones for syncing state with other
+ // Serf nodes.
+ ReapInterval time.Duration
+ ReconnectInterval time.Duration
+ ReconnectTimeout time.Duration
+ TombstoneTimeout time.Duration
+
+ // QueueDepthWarning is used to generate warning message if the
+ // number of queued messages to broadcast exceeds this number. This
+ // is to provide the user feedback if events are being triggered
+ // faster than they can be disseminated
+ QueueDepthWarning int
+
+ // MaxQueueDepth is used to start dropping messages if the number
+ // of queued messages to broadcast exceeds this number. This is to
+ // prevent an unbounded growth of memory utilization
+ MaxQueueDepth int
+
+ // RecentIntentBuffer is used to set the size of recent join and leave intent
+ // messages that will be buffered. This is used to guard against
+ // the case where Serf broadcasts an intent that arrives before the
+ // Memberlist event. It is important that this not be too small to avoid
+ // continuous rebroadcasting of dead events.
+ RecentIntentBuffer int
+
+ // EventBuffer is used to control how many events are buffered.
+ // This is used to prevent re-delivery of events to a client. The buffer
+ // must be large enough to handle all "recent" events, since Serf will
+ // not deliver messages that are older than the oldest entry in the buffer.
+ // Thus if a client is generating too many events, it's possible that the
+ // buffer gets overrun and messages are not delivered.
+ EventBuffer int
+
+ // QueryBuffer is used to control how many queries are buffered.
+ // This is used to prevent re-delivery of queries to a client. The buffer
+ // must be large enough to handle all "recent" events, since Serf will not
+ // deliver queries older than the oldest entry in the buffer.
+ // Thus if a client is generating too many queries, it's possible that the
+ // buffer gets overrun and messages are not delivered.
+ QueryBuffer int
+
+ // QueryTimeoutMult configures the default timeout multipler for a query to run if no
+ // specific value is provided. Queries are real-time by nature, where the
+ // reply is time sensitive. As a result, results are collected in an async
+ // fashion, however the query must have a bounded duration. We want the timeout
+ // to be long enough that all nodes have time to receive the message, run a handler,
+ // and generate a reply. Once the timeout is exceeded, any further replies are ignored.
+ // The default value is
+ //
+ // Timeout = GossipInterval * QueryTimeoutMult * log(N+1)
+ //
+ QueryTimeoutMult int
+
+ // QueryResponseSizeLimit and QuerySizeLimit limit the inbound and
+ // outbound payload sizes for queries, respectively. These must fit
+ // in a UDP packet with some additional overhead, so tuning these
+ // past the default values of 1024 will depend on your network
+ // configuration.
+ QueryResponseSizeLimit int
+ QuerySizeLimit int
+
+ // MemberlistConfig is the memberlist configuration that Serf will
+ // use to do the underlying membership management and gossip. Some
+ // fields in the MemberlistConfig will be overwritten by Serf no
+ // matter what:
+ //
+ // * Name - This will always be set to the same as the NodeName
+ // in this configuration.
+ //
+ // * Events - Serf uses a custom event delegate.
+ //
+ // * Delegate - Serf uses a custom delegate.
+ //
+ MemberlistConfig *memberlist.Config
+
+ // LogOutput is the location to write logs to. If this is not set,
+ // logs will go to stderr.
+ LogOutput io.Writer
+
+ // SnapshotPath if provided is used to snapshot live nodes as well
+ // as lamport clock values. When Serf is started with a snapshot,
+ // it will attempt to join all the previously known nodes until one
+ // succeeds and will also avoid replaying old user events.
+ SnapshotPath string
+
+ // RejoinAfterLeave controls our interaction with the snapshot file.
+ // When set to false (default), a leave causes a Serf to not rejoin
+ // the cluster until an explicit join is received. If this is set to
+ // true, we ignore the leave, and rejoin the cluster on start.
+ RejoinAfterLeave bool
+
+ // EnableNameConflictResolution controls if Serf will actively attempt
+ // to resolve a name conflict. Since each Serf member must have a unique
+ // name, a cluster can run into issues if multiple nodes claim the same
+ // name. Without automatic resolution, Serf merely logs some warnings, but
+ // otherwise does not take any action. Automatic resolution detects the
+ // conflict and issues a special query which asks the cluster for the
+ // Name -> IP:Port mapping. If there is a simple majority of votes, that
+ // node stays while the other node will leave the cluster and exit.
+ EnableNameConflictResolution bool
+
+ // DisableCoordinates controls if Serf will maintain an estimate of this
+ // node's network coordinate internally. A network coordinate is useful
+ // for estimating the network distance (i.e. round trip time) between
+ // two nodes. Enabling this option adds some overhead to ping messages.
+ DisableCoordinates bool
+
+ // KeyringFile provides the location of a writable file where Serf can
+ // persist changes to the encryption keyring.
+ KeyringFile string
+
+ // Merge can be optionally provided to intercept a cluster merge
+ // and conditionally abort the merge.
+ Merge MergeDelegate
+}
+
+// Init allocates the subdata structures
+func (c *Config) Init() {
+ if c.Tags == nil {
+ c.Tags = make(map[string]string)
+ }
+}
+
+// DefaultConfig returns a Config struct that contains reasonable defaults
+// for most of the configurations.
+func DefaultConfig() *Config {
+ hostname, err := os.Hostname()
+ if err != nil {
+ panic(err)
+ }
+
+ return &Config{
+ NodeName: hostname,
+ BroadcastTimeout: 5 * time.Second,
+ EventBuffer: 512,
+ QueryBuffer: 512,
+ LogOutput: os.Stderr,
+ ProtocolVersion: ProtocolVersionMax,
+ ReapInterval: 15 * time.Second,
+ RecentIntentBuffer: 128,
+ ReconnectInterval: 30 * time.Second,
+ ReconnectTimeout: 24 * time.Hour,
+ QueueDepthWarning: 128,
+ MaxQueueDepth: 4096,
+ TombstoneTimeout: 24 * time.Hour,
+ MemberlistConfig: memberlist.DefaultLANConfig(),
+ QueryTimeoutMult: 16,
+ QueryResponseSizeLimit: 1024,
+ QuerySizeLimit: 1024,
+ EnableNameConflictResolution: true,
+ DisableCoordinates: false,
+ }
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/conflict_delegate.go b/vendor/github.com/hashicorp/serf/serf/conflict_delegate.go
new file mode 100644
index 0000000..65a5015
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/conflict_delegate.go
@@ -0,0 +1,13 @@
+package serf
+
+import (
+ "github.com/hashicorp/memberlist"
+)
+
+type conflictDelegate struct {
+ serf *Serf
+}
+
+func (c *conflictDelegate) NotifyConflict(existing, other *memberlist.Node) {
+ c.serf.handleNodeConflict(existing, other)
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/delegate.go b/vendor/github.com/hashicorp/serf/serf/delegate.go
new file mode 100644
index 0000000..d19ca30
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/delegate.go
@@ -0,0 +1,254 @@
+package serf
+
+import (
+ "fmt"
+
+ "github.com/armon/go-metrics"
+)
+
+// delegate is the memberlist.Delegate implementation that Serf uses.
+type delegate struct {
+ serf *Serf
+}
+
+func (d *delegate) NodeMeta(limit int) []byte {
+ roleBytes := d.serf.encodeTags(d.serf.config.Tags)
+ if len(roleBytes) > limit {
+ panic(fmt.Errorf("Node tags '%v' exceeds length limit of %d bytes", d.serf.config.Tags, limit))
+ }
+
+ return roleBytes
+}
+
+func (d *delegate) NotifyMsg(buf []byte) {
+ // If we didn't actually receive any data, then ignore it.
+ if len(buf) == 0 {
+ return
+ }
+ metrics.AddSample([]string{"serf", "msgs", "received"}, float32(len(buf)))
+
+ rebroadcast := false
+ rebroadcastQueue := d.serf.broadcasts
+ t := messageType(buf[0])
+ switch t {
+ case messageLeaveType:
+ var leave messageLeave
+ if err := decodeMessage(buf[1:], &leave); err != nil {
+ d.serf.logger.Printf("[ERR] serf: Error decoding leave message: %s", err)
+ break
+ }
+
+ d.serf.logger.Printf("[DEBUG] serf: messageLeaveType: %s", leave.Node)
+ rebroadcast = d.serf.handleNodeLeaveIntent(&leave)
+
+ case messageJoinType:
+ var join messageJoin
+ if err := decodeMessage(buf[1:], &join); err != nil {
+ d.serf.logger.Printf("[ERR] serf: Error decoding join message: %s", err)
+ break
+ }
+
+ d.serf.logger.Printf("[DEBUG] serf: messageJoinType: %s", join.Node)
+ rebroadcast = d.serf.handleNodeJoinIntent(&join)
+
+ case messageUserEventType:
+ var event messageUserEvent
+ if err := decodeMessage(buf[1:], &event); err != nil {
+ d.serf.logger.Printf("[ERR] serf: Error decoding user event message: %s", err)
+ break
+ }
+
+ d.serf.logger.Printf("[DEBUG] serf: messageUserEventType: %s", event.Name)
+ rebroadcast = d.serf.handleUserEvent(&event)
+ rebroadcastQueue = d.serf.eventBroadcasts
+
+ case messageQueryType:
+ var query messageQuery
+ if err := decodeMessage(buf[1:], &query); err != nil {
+ d.serf.logger.Printf("[ERR] serf: Error decoding query message: %s", err)
+ break
+ }
+
+ d.serf.logger.Printf("[DEBUG] serf: messageQueryType: %s", query.Name)
+ rebroadcast = d.serf.handleQuery(&query)
+ rebroadcastQueue = d.serf.queryBroadcasts
+
+ case messageQueryResponseType:
+ var resp messageQueryResponse
+ if err := decodeMessage(buf[1:], &resp); err != nil {
+ d.serf.logger.Printf("[ERR] serf: Error decoding query response message: %s", err)
+ break
+ }
+
+ d.serf.logger.Printf("[DEBUG] serf: messageQueryResponseType: %v", resp.From)
+ d.serf.handleQueryResponse(&resp)
+
+ default:
+ d.serf.logger.Printf("[WARN] serf: Received message of unknown type: %d", t)
+ }
+
+ if rebroadcast {
+ // Copy the buffer since it we cannot rely on the slice not changing
+ newBuf := make([]byte, len(buf))
+ copy(newBuf, buf)
+
+ rebroadcastQueue.QueueBroadcast(&broadcast{
+ msg: newBuf,
+ notify: nil,
+ })
+ }
+}
+
+func (d *delegate) GetBroadcasts(overhead, limit int) [][]byte {
+ msgs := d.serf.broadcasts.GetBroadcasts(overhead, limit)
+
+ // Determine the bytes used already
+ bytesUsed := 0
+ for _, msg := range msgs {
+ lm := len(msg)
+ bytesUsed += lm + overhead
+ metrics.AddSample([]string{"serf", "msgs", "sent"}, float32(lm))
+ }
+
+ // Get any additional query broadcasts
+ queryMsgs := d.serf.queryBroadcasts.GetBroadcasts(overhead, limit-bytesUsed)
+ if queryMsgs != nil {
+ for _, m := range queryMsgs {
+ lm := len(m)
+ bytesUsed += lm + overhead
+ metrics.AddSample([]string{"serf", "msgs", "sent"}, float32(lm))
+ }
+ msgs = append(msgs, queryMsgs...)
+ }
+
+ // Get any additional event broadcasts
+ eventMsgs := d.serf.eventBroadcasts.GetBroadcasts(overhead, limit-bytesUsed)
+ if eventMsgs != nil {
+ for _, m := range eventMsgs {
+ lm := len(m)
+ bytesUsed += lm + overhead
+ metrics.AddSample([]string{"serf", "msgs", "sent"}, float32(lm))
+ }
+ msgs = append(msgs, eventMsgs...)
+ }
+
+ return msgs
+}
+
+func (d *delegate) LocalState(join bool) []byte {
+ d.serf.memberLock.RLock()
+ defer d.serf.memberLock.RUnlock()
+ d.serf.eventLock.RLock()
+ defer d.serf.eventLock.RUnlock()
+
+ // Create the message to send
+ pp := messagePushPull{
+ LTime: d.serf.clock.Time(),
+ StatusLTimes: make(map[string]LamportTime, len(d.serf.members)),
+ LeftMembers: make([]string, 0, len(d.serf.leftMembers)),
+ EventLTime: d.serf.eventClock.Time(),
+ Events: d.serf.eventBuffer,
+ QueryLTime: d.serf.queryClock.Time(),
+ }
+
+ // Add all the join LTimes
+ for name, member := range d.serf.members {
+ pp.StatusLTimes[name] = member.statusLTime
+ }
+
+ // Add all the left nodes
+ for _, member := range d.serf.leftMembers {
+ pp.LeftMembers = append(pp.LeftMembers, member.Name)
+ }
+
+ // Encode the push pull state
+ buf, err := encodeMessage(messagePushPullType, &pp)
+ if err != nil {
+ d.serf.logger.Printf("[ERR] serf: Failed to encode local state: %v", err)
+ return nil
+ }
+ return buf
+}
+
+func (d *delegate) MergeRemoteState(buf []byte, isJoin bool) {
+ // Ensure we have a message
+ if len(buf) == 0 {
+ d.serf.logger.Printf("[ERR] serf: Remote state is zero bytes")
+ return
+ }
+
+ // Check the message type
+ if messageType(buf[0]) != messagePushPullType {
+ d.serf.logger.Printf("[ERR] serf: Remote state has bad type prefix: %v", buf[0])
+ return
+ }
+
+ // Attempt a decode
+ pp := messagePushPull{}
+ if err := decodeMessage(buf[1:], &pp); err != nil {
+ d.serf.logger.Printf("[ERR] serf: Failed to decode remote state: %v", err)
+ return
+ }
+
+ // Witness the Lamport clocks first.
+ // We subtract 1 since no message with that clock has been sent yet
+ if pp.LTime > 0 {
+ d.serf.clock.Witness(pp.LTime - 1)
+ }
+ if pp.EventLTime > 0 {
+ d.serf.eventClock.Witness(pp.EventLTime - 1)
+ }
+ if pp.QueryLTime > 0 {
+ d.serf.queryClock.Witness(pp.QueryLTime - 1)
+ }
+
+ // Process the left nodes first to avoid the LTimes from being increment
+ // in the wrong order
+ leftMap := make(map[string]struct{}, len(pp.LeftMembers))
+ leave := messageLeave{}
+ for _, name := range pp.LeftMembers {
+ leftMap[name] = struct{}{}
+ leave.LTime = pp.StatusLTimes[name]
+ leave.Node = name
+ d.serf.handleNodeLeaveIntent(&leave)
+ }
+
+ // Update any other LTimes
+ join := messageJoin{}
+ for name, statusLTime := range pp.StatusLTimes {
+ // Skip the left nodes
+ if _, ok := leftMap[name]; ok {
+ continue
+ }
+
+ // Create an artificial join message
+ join.LTime = statusLTime
+ join.Node = name
+ d.serf.handleNodeJoinIntent(&join)
+ }
+
+ // If we are doing a join, and eventJoinIgnore is set
+ // then we set the eventMinTime to the EventLTime. This
+ // prevents any of the incoming events from being processed
+ if isJoin && d.serf.eventJoinIgnore {
+ d.serf.eventLock.Lock()
+ if pp.EventLTime > d.serf.eventMinTime {
+ d.serf.eventMinTime = pp.EventLTime
+ }
+ d.serf.eventLock.Unlock()
+ }
+
+ // Process all the events
+ userEvent := messageUserEvent{}
+ for _, events := range pp.Events {
+ if events == nil {
+ continue
+ }
+ userEvent.LTime = events.LTime
+ for _, e := range events.Events {
+ userEvent.Name = e.Name
+ userEvent.Payload = e.Payload
+ d.serf.handleUserEvent(&userEvent)
+ }
+ }
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/event.go b/vendor/github.com/hashicorp/serf/serf/event.go
new file mode 100644
index 0000000..8337e95
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/event.go
@@ -0,0 +1,168 @@
+package serf
+
+import (
+ "fmt"
+ "net"
+ "sync"
+ "time"
+)
+
+// EventType are all the types of events that may occur and be sent
+// along the Serf channel.
+type EventType int
+
+const (
+ EventMemberJoin EventType = iota
+ EventMemberLeave
+ EventMemberFailed
+ EventMemberUpdate
+ EventMemberReap
+ EventUser
+ EventQuery
+)
+
+func (t EventType) String() string {
+ switch t {
+ case EventMemberJoin:
+ return "member-join"
+ case EventMemberLeave:
+ return "member-leave"
+ case EventMemberFailed:
+ return "member-failed"
+ case EventMemberUpdate:
+ return "member-update"
+ case EventMemberReap:
+ return "member-reap"
+ case EventUser:
+ return "user"
+ case EventQuery:
+ return "query"
+ default:
+ panic(fmt.Sprintf("unknown event type: %d", t))
+ }
+}
+
+// Event is a generic interface for exposing Serf events
+// Clients will usually need to use a type switches to get
+// to a more useful type
+type Event interface {
+ EventType() EventType
+ String() string
+}
+
+// MemberEvent is the struct used for member related events
+// Because Serf coalesces events, an event may contain multiple members.
+type MemberEvent struct {
+ Type EventType
+ Members []Member
+}
+
+func (m MemberEvent) EventType() EventType {
+ return m.Type
+}
+
+func (m MemberEvent) String() string {
+ switch m.Type {
+ case EventMemberJoin:
+ return "member-join"
+ case EventMemberLeave:
+ return "member-leave"
+ case EventMemberFailed:
+ return "member-failed"
+ case EventMemberUpdate:
+ return "member-update"
+ case EventMemberReap:
+ return "member-reap"
+ default:
+ panic(fmt.Sprintf("unknown event type: %d", m.Type))
+ }
+}
+
+// UserEvent is the struct used for events that are triggered
+// by the user and are not related to members
+type UserEvent struct {
+ LTime LamportTime
+ Name string
+ Payload []byte
+ Coalesce bool
+}
+
+func (u UserEvent) EventType() EventType {
+ return EventUser
+}
+
+func (u UserEvent) String() string {
+ return fmt.Sprintf("user-event: %s", u.Name)
+}
+
+// Query is the struct used EventQuery type events
+type Query struct {
+ LTime LamportTime
+ Name string
+ Payload []byte
+
+ serf *Serf
+ id uint32 // ID is not exported, since it may change
+ addr []byte // Address to respond to
+ port uint16 // Port to respond to
+ deadline time.Time // Must respond by this deadline
+ respLock sync.Mutex
+}
+
+func (q *Query) EventType() EventType {
+ return EventQuery
+}
+
+func (q *Query) String() string {
+ return fmt.Sprintf("query: %s", q.Name)
+}
+
+// Deadline returns the time by which a response must be sent
+func (q *Query) Deadline() time.Time {
+ return q.deadline
+}
+
+// Respond is used to send a response to the user query
+func (q *Query) Respond(buf []byte) error {
+ q.respLock.Lock()
+ defer q.respLock.Unlock()
+
+ // Check if we've already responded
+ if q.deadline.IsZero() {
+ return fmt.Errorf("Response already sent")
+ }
+
+ // Ensure we aren't past our response deadline
+ if time.Now().After(q.deadline) {
+ return fmt.Errorf("Response is past the deadline")
+ }
+
+ // Create response
+ resp := messageQueryResponse{
+ LTime: q.LTime,
+ ID: q.id,
+ From: q.serf.config.NodeName,
+ Payload: buf,
+ }
+
+ // Format the response
+ raw, err := encodeMessage(messageQueryResponseType, &resp)
+ if err != nil {
+ return fmt.Errorf("Failed to format response: %v", err)
+ }
+
+ // Check the size limit
+ if len(raw) > q.serf.config.QueryResponseSizeLimit {
+ return fmt.Errorf("response exceeds limit of %d bytes", q.serf.config.QueryResponseSizeLimit)
+ }
+
+ // Send the response
+ addr := net.UDPAddr{IP: q.addr, Port: int(q.port)}
+ if err := q.serf.memberlist.SendTo(&addr, raw); err != nil {
+ return err
+ }
+
+ // Clera the deadline, response sent
+ q.deadline = time.Time{}
+ return nil
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/event_delegate.go b/vendor/github.com/hashicorp/serf/serf/event_delegate.go
new file mode 100644
index 0000000..e201322
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/event_delegate.go
@@ -0,0 +1,21 @@
+package serf
+
+import (
+ "github.com/hashicorp/memberlist"
+)
+
+type eventDelegate struct {
+ serf *Serf
+}
+
+func (e *eventDelegate) NotifyJoin(n *memberlist.Node) {
+ e.serf.handleNodeJoin(n)
+}
+
+func (e *eventDelegate) NotifyLeave(n *memberlist.Node) {
+ e.serf.handleNodeLeave(n)
+}
+
+func (e *eventDelegate) NotifyUpdate(n *memberlist.Node) {
+ e.serf.handleNodeUpdate(n)
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/internal_query.go b/vendor/github.com/hashicorp/serf/serf/internal_query.go
new file mode 100644
index 0000000..128b2cf
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/internal_query.go
@@ -0,0 +1,312 @@
+package serf
+
+import (
+ "encoding/base64"
+ "log"
+ "strings"
+)
+
+const (
+ // This is the prefix we use for queries that are internal to Serf.
+ // They are handled internally, and not forwarded to a client.
+ InternalQueryPrefix = "_serf_"
+
+ // pingQuery is run to check for reachability
+ pingQuery = "ping"
+
+ // conflictQuery is run to resolve a name conflict
+ conflictQuery = "conflict"
+
+ // installKeyQuery is used to install a new key
+ installKeyQuery = "install-key"
+
+ // useKeyQuery is used to change the primary encryption key
+ useKeyQuery = "use-key"
+
+ // removeKeyQuery is used to remove a key from the keyring
+ removeKeyQuery = "remove-key"
+
+ // listKeysQuery is used to list all known keys in the cluster
+ listKeysQuery = "list-keys"
+)
+
+// internalQueryName is used to generate a query name for an internal query
+func internalQueryName(name string) string {
+ return InternalQueryPrefix + name
+}
+
+// serfQueries is used to listen for queries that start with
+// _serf and respond to them as appropriate.
+type serfQueries struct {
+ inCh chan Event
+ logger *log.Logger
+ outCh chan<- Event
+ serf *Serf
+ shutdownCh <-chan struct{}
+}
+
+// nodeKeyResponse is used to store the result from an individual node while
+// replying to key modification queries
+type nodeKeyResponse struct {
+ // Result indicates true/false if there were errors or not
+ Result bool
+
+ // Message contains error messages or other information
+ Message string
+
+ // Keys is used in listing queries to relay a list of installed keys
+ Keys []string
+}
+
+// newSerfQueries is used to create a new serfQueries. We return an event
+// channel that is ingested and forwarded to an outCh. Any Queries that
+// have the InternalQueryPrefix are handled instead of forwarded.
+func newSerfQueries(serf *Serf, logger *log.Logger, outCh chan<- Event, shutdownCh <-chan struct{}) (chan<- Event, error) {
+ inCh := make(chan Event, 1024)
+ q := &serfQueries{
+ inCh: inCh,
+ logger: logger,
+ outCh: outCh,
+ serf: serf,
+ shutdownCh: shutdownCh,
+ }
+ go q.stream()
+ return inCh, nil
+}
+
+// stream is a long running routine to ingest the event stream
+func (s *serfQueries) stream() {
+ for {
+ select {
+ case e := <-s.inCh:
+ // Check if this is a query we should process
+ if q, ok := e.(*Query); ok && strings.HasPrefix(q.Name, InternalQueryPrefix) {
+ go s.handleQuery(q)
+
+ } else if s.outCh != nil {
+ s.outCh <- e
+ }
+
+ case <-s.shutdownCh:
+ return
+ }
+ }
+}
+
+// handleQuery is invoked when we get an internal query
+func (s *serfQueries) handleQuery(q *Query) {
+ // Get the queryName after the initial prefix
+ queryName := q.Name[len(InternalQueryPrefix):]
+ switch queryName {
+ case pingQuery:
+ // Nothing to do, we will ack the query
+ case conflictQuery:
+ s.handleConflict(q)
+ case installKeyQuery:
+ s.handleInstallKey(q)
+ case useKeyQuery:
+ s.handleUseKey(q)
+ case removeKeyQuery:
+ s.handleRemoveKey(q)
+ case listKeysQuery:
+ s.handleListKeys(q)
+ default:
+ s.logger.Printf("[WARN] serf: Unhandled internal query '%s'", queryName)
+ }
+}
+
+// handleConflict is invoked when we get a query that is attempting to
+// disambiguate a name conflict. They payload is a node name, and the response
+// should the address we believe that node is at, if any.
+func (s *serfQueries) handleConflict(q *Query) {
+ // The target node name is the payload
+ node := string(q.Payload)
+
+ // Do not respond to the query if it is about us
+ if node == s.serf.config.NodeName {
+ return
+ }
+ s.logger.Printf("[DEBUG] serf: Got conflict resolution query for '%s'", node)
+
+ // Look for the member info
+ var out *Member
+ s.serf.memberLock.Lock()
+ if member, ok := s.serf.members[node]; ok {
+ out = &member.Member
+ }
+ s.serf.memberLock.Unlock()
+
+ // Encode the response
+ buf, err := encodeMessage(messageConflictResponseType, out)
+ if err != nil {
+ s.logger.Printf("[ERR] serf: Failed to encode conflict query response: %v", err)
+ return
+ }
+
+ // Send our answer
+ if err := q.Respond(buf); err != nil {
+ s.logger.Printf("[ERR] serf: Failed to respond to conflict query: %v", err)
+ }
+}
+
+// sendKeyResponse handles responding to key-related queries.
+func (s *serfQueries) sendKeyResponse(q *Query, resp *nodeKeyResponse) {
+ buf, err := encodeMessage(messageKeyResponseType, resp)
+ if err != nil {
+ s.logger.Printf("[ERR] serf: Failed to encode key response: %v", err)
+ return
+ }
+
+ if err := q.Respond(buf); err != nil {
+ s.logger.Printf("[ERR] serf: Failed to respond to key query: %v", err)
+ return
+ }
+}
+
+// handleInstallKey is invoked whenever a new encryption key is received from
+// another member in the cluster, and handles the process of installing it onto
+// the memberlist keyring. This type of query may fail if the provided key does
+// not fit the constraints that memberlist enforces. If the query fails, the
+// response will contain the error message so that it may be relayed.
+func (s *serfQueries) handleInstallKey(q *Query) {
+ response := nodeKeyResponse{Result: false}
+ keyring := s.serf.config.MemberlistConfig.Keyring
+ req := keyRequest{}
+
+ err := decodeMessage(q.Payload[1:], &req)
+ if err != nil {
+ s.logger.Printf("[ERR] serf: Failed to decode key request: %v", err)
+ goto SEND
+ }
+
+ if !s.serf.EncryptionEnabled() {
+ response.Message = "No keyring to modify (encryption not enabled)"
+ s.logger.Printf("[ERR] serf: No keyring to modify (encryption not enabled)")
+ goto SEND
+ }
+
+ s.logger.Printf("[INFO] serf: Received install-key query")
+ if err := keyring.AddKey(req.Key); err != nil {
+ response.Message = err.Error()
+ s.logger.Printf("[ERR] serf: Failed to install key: %s", err)
+ goto SEND
+ }
+
+ if err := s.serf.writeKeyringFile(); err != nil {
+ response.Message = err.Error()
+ s.logger.Printf("[ERR] serf: Failed to write keyring file: %s", err)
+ goto SEND
+ }
+
+ response.Result = true
+
+SEND:
+ s.sendKeyResponse(q, &response)
+}
+
+// handleUseKey is invoked whenever a query is received to mark a different key
+// in the internal keyring as the primary key. This type of query may fail due
+// to operator error (requested key not in ring), and thus sends error messages
+// back in the response.
+func (s *serfQueries) handleUseKey(q *Query) {
+ response := nodeKeyResponse{Result: false}
+ keyring := s.serf.config.MemberlistConfig.Keyring
+ req := keyRequest{}
+
+ err := decodeMessage(q.Payload[1:], &req)
+ if err != nil {
+ s.logger.Printf("[ERR] serf: Failed to decode key request: %v", err)
+ goto SEND
+ }
+
+ if !s.serf.EncryptionEnabled() {
+ response.Message = "No keyring to modify (encryption not enabled)"
+ s.logger.Printf("[ERR] serf: No keyring to modify (encryption not enabled)")
+ goto SEND
+ }
+
+ s.logger.Printf("[INFO] serf: Received use-key query")
+ if err := keyring.UseKey(req.Key); err != nil {
+ response.Message = err.Error()
+ s.logger.Printf("[ERR] serf: Failed to change primary key: %s", err)
+ goto SEND
+ }
+
+ if err := s.serf.writeKeyringFile(); err != nil {
+ response.Message = err.Error()
+ s.logger.Printf("[ERR] serf: Failed to write keyring file: %s", err)
+ goto SEND
+ }
+
+ response.Result = true
+
+SEND:
+ s.sendKeyResponse(q, &response)
+}
+
+// handleRemoveKey is invoked when a query is received to remove a particular
+// key from the keyring. This type of query can fail if the key requested for
+// deletion is currently the primary key in the keyring, so therefore it will
+// reply to the query with any relevant errors from the operation.
+func (s *serfQueries) handleRemoveKey(q *Query) {
+ response := nodeKeyResponse{Result: false}
+ keyring := s.serf.config.MemberlistConfig.Keyring
+ req := keyRequest{}
+
+ err := decodeMessage(q.Payload[1:], &req)
+ if err != nil {
+ s.logger.Printf("[ERR] serf: Failed to decode key request: %v", err)
+ goto SEND
+ }
+
+ if !s.serf.EncryptionEnabled() {
+ response.Message = "No keyring to modify (encryption not enabled)"
+ s.logger.Printf("[ERR] serf: No keyring to modify (encryption not enabled)")
+ goto SEND
+ }
+
+ s.logger.Printf("[INFO] serf: Received remove-key query")
+ if err := keyring.RemoveKey(req.Key); err != nil {
+ response.Message = err.Error()
+ s.logger.Printf("[ERR] serf: Failed to remove key: %s", err)
+ goto SEND
+ }
+
+ if err := s.serf.writeKeyringFile(); err != nil {
+ response.Message = err.Error()
+ s.logger.Printf("[ERR] serf: Failed to write keyring file: %s", err)
+ goto SEND
+ }
+
+ response.Result = true
+
+SEND:
+ s.sendKeyResponse(q, &response)
+}
+
+// handleListKeys is invoked when a query is received to return a list of all
+// installed keys the Serf instance knows of. For performance, the keys are
+// encoded to base64 on each of the members to remove this burden from the
+// node asking for the results.
+func (s *serfQueries) handleListKeys(q *Query) {
+ response := nodeKeyResponse{Result: false}
+ keyring := s.serf.config.MemberlistConfig.Keyring
+
+ if !s.serf.EncryptionEnabled() {
+ response.Message = "Keyring is empty (encryption not enabled)"
+ s.logger.Printf("[ERR] serf: Keyring is empty (encryption not enabled)")
+ goto SEND
+ }
+
+ s.logger.Printf("[INFO] serf: Received list-keys query")
+ for _, keyBytes := range keyring.GetKeys() {
+ // Encode the keys before sending the response. This should help take
+ // some the burden of doing this off of the asking member.
+ key := base64.StdEncoding.EncodeToString(keyBytes)
+ response.Keys = append(response.Keys, key)
+ }
+ response.Result = true
+
+SEND:
+ s.sendKeyResponse(q, &response)
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/keymanager.go b/vendor/github.com/hashicorp/serf/serf/keymanager.go
new file mode 100644
index 0000000..72a3194
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/keymanager.go
@@ -0,0 +1,166 @@
+package serf
+
+import (
+ "encoding/base64"
+ "fmt"
+ "sync"
+)
+
+// KeyManager encapsulates all functionality within Serf for handling
+// encryption keyring changes across a cluster.
+type KeyManager struct {
+ serf *Serf
+
+ // Lock to protect read and write operations
+ l sync.RWMutex
+}
+
+// keyRequest is used to contain input parameters which get broadcasted to all
+// nodes as part of a key query operation.
+type keyRequest struct {
+ Key []byte
+}
+
+// KeyResponse is used to relay a query for a list of all keys in use.
+type KeyResponse struct {
+ Messages map[string]string // Map of node name to response message
+ NumNodes int // Total nodes memberlist knows of
+ NumResp int // Total responses received
+ NumErr int // Total errors from request
+
+ // Keys is a mapping of the base64-encoded value of the key bytes to the
+ // number of nodes that have the key installed.
+ Keys map[string]int
+}
+
+// streamKeyResp takes care of reading responses from a channel and composing
+// them into a KeyResponse. It will update a KeyResponse *in place* and
+// therefore has nothing to return.
+func (k *KeyManager) streamKeyResp(resp *KeyResponse, ch <-chan NodeResponse) {
+ for r := range ch {
+ var nodeResponse nodeKeyResponse
+
+ resp.NumResp++
+
+ // Decode the response
+ if len(r.Payload) < 1 || messageType(r.Payload[0]) != messageKeyResponseType {
+ resp.Messages[r.From] = fmt.Sprintf(
+ "Invalid key query response type: %v", r.Payload)
+ resp.NumErr++
+ goto NEXT
+ }
+ if err := decodeMessage(r.Payload[1:], &nodeResponse); err != nil {
+ resp.Messages[r.From] = fmt.Sprintf(
+ "Failed to decode key query response: %v", r.Payload)
+ resp.NumErr++
+ goto NEXT
+ }
+
+ if !nodeResponse.Result {
+ resp.Messages[r.From] = nodeResponse.Message
+ resp.NumErr++
+ }
+
+ // Currently only used for key list queries, this adds keys to a counter
+ // and increments them for each node response which contains them.
+ for _, key := range nodeResponse.Keys {
+ if _, ok := resp.Keys[key]; !ok {
+ resp.Keys[key] = 1
+ } else {
+ resp.Keys[key]++
+ }
+ }
+
+ NEXT:
+ // Return early if all nodes have responded. This allows us to avoid
+ // waiting for the full timeout when there is nothing left to do.
+ if resp.NumResp == resp.NumNodes {
+ return
+ }
+ }
+}
+
+// handleKeyRequest performs query broadcasting to all members for any type of
+// key operation and manages gathering responses and packing them up into a
+// KeyResponse for uniform response handling.
+func (k *KeyManager) handleKeyRequest(key, query string) (*KeyResponse, error) {
+ resp := &KeyResponse{
+ Messages: make(map[string]string),
+ Keys: make(map[string]int),
+ }
+ qName := internalQueryName(query)
+
+ // Decode the new key into raw bytes
+ rawKey, err := base64.StdEncoding.DecodeString(key)
+ if err != nil {
+ return resp, err
+ }
+
+ // Encode the query request
+ req, err := encodeMessage(messageKeyRequestType, keyRequest{Key: rawKey})
+ if err != nil {
+ return resp, err
+ }
+
+ qParam := k.serf.DefaultQueryParams()
+ queryResp, err := k.serf.Query(qName, req, qParam)
+ if err != nil {
+ return resp, err
+ }
+
+ // Handle the response stream and populate the KeyResponse
+ resp.NumNodes = k.serf.memberlist.NumMembers()
+ k.streamKeyResp(resp, queryResp.respCh)
+
+ // Check the response for any reported failure conditions
+ if resp.NumErr != 0 {
+ return resp, fmt.Errorf("%d/%d nodes reported failure", resp.NumErr, resp.NumNodes)
+ }
+ if resp.NumResp != resp.NumNodes {
+ return resp, fmt.Errorf("%d/%d nodes reported success", resp.NumResp, resp.NumNodes)
+ }
+
+ return resp, nil
+}
+
+// InstallKey handles broadcasting a query to all members and gathering
+// responses from each of them, returning a list of messages from each node
+// and any applicable error conditions.
+func (k *KeyManager) InstallKey(key string) (*KeyResponse, error) {
+ k.l.Lock()
+ defer k.l.Unlock()
+
+ return k.handleKeyRequest(key, installKeyQuery)
+}
+
+// UseKey handles broadcasting a primary key change to all members in the
+// cluster, and gathering any response messages. If successful, there should
+// be an empty KeyResponse returned.
+func (k *KeyManager) UseKey(key string) (*KeyResponse, error) {
+ k.l.Lock()
+ defer k.l.Unlock()
+
+ return k.handleKeyRequest(key, useKeyQuery)
+}
+
+// RemoveKey handles broadcasting a key to the cluster for removal. Each member
+// will receive this event, and if they have the key in their keyring, remove
+// it. If any errors are encountered, RemoveKey will collect and relay them.
+func (k *KeyManager) RemoveKey(key string) (*KeyResponse, error) {
+ k.l.Lock()
+ defer k.l.Unlock()
+
+ return k.handleKeyRequest(key, removeKeyQuery)
+}
+
+// ListKeys is used to collect installed keys from members in a Serf cluster
+// and return an aggregated list of all installed keys. This is useful to
+// operators to ensure that there are no lingering keys installed on any agents.
+// Since having multiple keys installed can cause performance penalties in some
+// cases, it's important to verify this information and remove unneeded keys.
+func (k *KeyManager) ListKeys() (*KeyResponse, error) {
+ k.l.RLock()
+ defer k.l.RUnlock()
+
+ return k.handleKeyRequest("", listKeysQuery)
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/lamport.go b/vendor/github.com/hashicorp/serf/serf/lamport.go
new file mode 100644
index 0000000..08f4aa7
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/lamport.go
@@ -0,0 +1,45 @@
+package serf
+
+import (
+ "sync/atomic"
+)
+
+// LamportClock is a thread safe implementation of a lamport clock. It
+// uses efficient atomic operations for all of its functions, falling back
+// to a heavy lock only if there are enough CAS failures.
+type LamportClock struct {
+ counter uint64
+}
+
+// LamportTime is the value of a LamportClock.
+type LamportTime uint64
+
+// Time is used to return the current value of the lamport clock
+func (l *LamportClock) Time() LamportTime {
+ return LamportTime(atomic.LoadUint64(&l.counter))
+}
+
+// Increment is used to increment and return the value of the lamport clock
+func (l *LamportClock) Increment() LamportTime {
+ return LamportTime(atomic.AddUint64(&l.counter, 1))
+}
+
+// Witness is called to update our local clock if necessary after
+// witnessing a clock value received from another process
+func (l *LamportClock) Witness(v LamportTime) {
+WITNESS:
+ // If the other value is old, we do not need to do anything
+ cur := atomic.LoadUint64(&l.counter)
+ other := uint64(v)
+ if other < cur {
+ return
+ }
+
+ // Ensure that our local clock is at least one ahead.
+ if !atomic.CompareAndSwapUint64(&l.counter, cur, other+1) {
+ // The CAS failed, so we just retry. Eventually our CAS should
+ // succeed or a future witness will pass us by and our witness
+ // will end.
+ goto WITNESS
+ }
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/merge_delegate.go b/vendor/github.com/hashicorp/serf/serf/merge_delegate.go
new file mode 100644
index 0000000..7fdc732
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/merge_delegate.go
@@ -0,0 +1,44 @@
+package serf
+
+import (
+ "net"
+
+ "github.com/hashicorp/memberlist"
+)
+
+type MergeDelegate interface {
+ NotifyMerge([]*Member) error
+}
+
+type mergeDelegate struct {
+ serf *Serf
+}
+
+func (m *mergeDelegate) NotifyMerge(nodes []*memberlist.Node) error {
+ members := make([]*Member, len(nodes))
+ for idx, n := range nodes {
+ members[idx] = m.nodeToMember(n)
+ }
+ return m.serf.config.Merge.NotifyMerge(members)
+}
+
+func (m *mergeDelegate) NotifyAlive(peer *memberlist.Node) error {
+ member := m.nodeToMember(peer)
+ return m.serf.config.Merge.NotifyMerge([]*Member{member})
+}
+
+func (m *mergeDelegate) nodeToMember(n *memberlist.Node) *Member {
+ return &Member{
+ Name: n.Name,
+ Addr: net.IP(n.Addr),
+ Port: n.Port,
+ Tags: m.serf.decodeTags(n.Meta),
+ Status: StatusNone,
+ ProtocolMin: n.PMin,
+ ProtocolMax: n.PMax,
+ ProtocolCur: n.PCur,
+ DelegateMin: n.DMin,
+ DelegateMax: n.DMax,
+ DelegateCur: n.DCur,
+ }
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/messages.go b/vendor/github.com/hashicorp/serf/serf/messages.go
new file mode 100644
index 0000000..c90c964
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/messages.go
@@ -0,0 +1,147 @@
+package serf
+
+import (
+ "bytes"
+ "github.com/hashicorp/go-msgpack/codec"
+ "time"
+)
+
+// messageType are the types of gossip messages Serf will send along
+// memberlist.
+type messageType uint8
+
+const (
+ messageLeaveType messageType = iota
+ messageJoinType
+ messagePushPullType
+ messageUserEventType
+ messageQueryType
+ messageQueryResponseType
+ messageConflictResponseType
+ messageKeyRequestType
+ messageKeyResponseType
+)
+
+const (
+ // Ack flag is used to force receiver to send an ack back
+ queryFlagAck uint32 = 1 << iota
+
+ // NoBroadcast is used to prevent re-broadcast of a query.
+ // this can be used to selectively send queries to individual members
+ queryFlagNoBroadcast
+)
+
+// filterType is used with a queryFilter to specify the type of
+// filter we are sending
+type filterType uint8
+
+const (
+ filterNodeType filterType = iota
+ filterTagType
+)
+
+// messageJoin is the message broadcasted after we join to
+// associated the node with a lamport clock
+type messageJoin struct {
+ LTime LamportTime
+ Node string
+}
+
+// messageLeave is the message broadcasted to signal the intentional to
+// leave.
+type messageLeave struct {
+ LTime LamportTime
+ Node string
+}
+
+// messagePushPullType is used when doing a state exchange. This
+// is a relatively large message, but is sent infrequently
+type messagePushPull struct {
+ LTime LamportTime // Current node lamport time
+ StatusLTimes map[string]LamportTime // Maps the node to its status time
+ LeftMembers []string // List of left nodes
+ EventLTime LamportTime // Lamport time for event clock
+ Events []*userEvents // Recent events
+ QueryLTime LamportTime // Lamport time for query clock
+}
+
+// messageUserEvent is used for user-generated events
+type messageUserEvent struct {
+ LTime LamportTime
+ Name string
+ Payload []byte
+ CC bool // "Can Coalesce". Zero value is compatible with Serf 0.1
+}
+
+// messageQuery is used for query events
+type messageQuery struct {
+ LTime LamportTime // Event lamport time
+ ID uint32 // Query ID, randomly generated
+ Addr []byte // Source address, used for a direct reply
+ Port uint16 // Source port, used for a direct reply
+ Filters [][]byte // Potential query filters
+ Flags uint32 // Used to provide various flags
+ Timeout time.Duration // Maximum time between delivery and response
+ Name string // Query name
+ Payload []byte // Query payload
+}
+
+// Ack checks if the ack flag is set
+func (m *messageQuery) Ack() bool {
+ return (m.Flags & queryFlagAck) != 0
+}
+
+// NoBroadcast checks if the no broadcast flag is set
+func (m *messageQuery) NoBroadcast() bool {
+ return (m.Flags & queryFlagNoBroadcast) != 0
+}
+
+// filterNode is used with the filterNodeType, and is a list
+// of node names
+type filterNode []string
+
+// filterTag is used with the filterTagType and is a regular
+// expression to apply to a tag
+type filterTag struct {
+ Tag string
+ Expr string
+}
+
+// messageQueryResponse is used to respond to a query
+type messageQueryResponse struct {
+ LTime LamportTime // Event lamport time
+ ID uint32 // Query ID
+ From string // Node name
+ Flags uint32 // Used to provide various flags
+ Payload []byte // Optional response payload
+}
+
+// Ack checks if the ack flag is set
+func (m *messageQueryResponse) Ack() bool {
+ return (m.Flags & queryFlagAck) != 0
+}
+
+func decodeMessage(buf []byte, out interface{}) error {
+ var handle codec.MsgpackHandle
+ return codec.NewDecoder(bytes.NewReader(buf), &handle).Decode(out)
+}
+
+func encodeMessage(t messageType, msg interface{}) ([]byte, error) {
+ buf := bytes.NewBuffer(nil)
+ buf.WriteByte(uint8(t))
+
+ handle := codec.MsgpackHandle{}
+ encoder := codec.NewEncoder(buf, &handle)
+ err := encoder.Encode(msg)
+ return buf.Bytes(), err
+}
+
+func encodeFilter(f filterType, filt interface{}) ([]byte, error) {
+ buf := bytes.NewBuffer(nil)
+ buf.WriteByte(uint8(f))
+
+ handle := codec.MsgpackHandle{}
+ encoder := codec.NewEncoder(buf, &handle)
+ err := encoder.Encode(filt)
+ return buf.Bytes(), err
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/ping_delegate.go b/vendor/github.com/hashicorp/serf/serf/ping_delegate.go
new file mode 100644
index 0000000..a482685
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/ping_delegate.go
@@ -0,0 +1,89 @@
+package serf
+
+import (
+ "bytes"
+ "log"
+ "time"
+
+ "github.com/armon/go-metrics"
+ "github.com/hashicorp/go-msgpack/codec"
+ "github.com/hashicorp/memberlist"
+ "github.com/hashicorp/serf/coordinate"
+)
+
+// pingDelegate is notified when memberlist successfully completes a direct ping
+// of a peer node. We use this to update our estimated network coordinate, as
+// well as cache the coordinate of the peer.
+type pingDelegate struct {
+ serf *Serf
+}
+
+const (
+ // PingVersion is an internal version for the ping message, above the normal
+ // versioning we get from the protocol version. This enables small updates
+ // to the ping message without a full protocol bump.
+ PingVersion = 1
+)
+
+// AckPayload is called to produce a payload to send back in response to a ping
+// request.
+func (p *pingDelegate) AckPayload() []byte {
+ var buf bytes.Buffer
+
+ // The first byte is the version number, forming a simple header.
+ version := []byte{PingVersion}
+ buf.Write(version)
+
+ // The rest of the message is the serialized coordinate.
+ enc := codec.NewEncoder(&buf, &codec.MsgpackHandle{})
+ if err := enc.Encode(p.serf.coordClient.GetCoordinate()); err != nil {
+ log.Printf("[ERR] serf: Failed to encode coordinate: %v\n", err)
+ }
+ return buf.Bytes()
+}
+
+// NotifyPingComplete is called when this node successfully completes a direct ping
+// of a peer node.
+func (p *pingDelegate) NotifyPingComplete(other *memberlist.Node, rtt time.Duration, payload []byte) {
+ if payload == nil || len(payload) == 0 {
+ return
+ }
+
+ // Verify ping version in the header.
+ version := payload[0]
+ if version != PingVersion {
+ log.Printf("[ERR] serf: Unsupported ping version: %v", version)
+ return
+ }
+
+ // Process the remainder of the message as a coordinate.
+ r := bytes.NewReader(payload[1:])
+ dec := codec.NewDecoder(r, &codec.MsgpackHandle{})
+ var coord coordinate.Coordinate
+ if err := dec.Decode(&coord); err != nil {
+ log.Printf("[ERR] serf: Failed to decode coordinate from ping: %v", err)
+ }
+
+ // Apply the update. Since this is a coordinate coming from some place
+ // else we harden this and look for dimensionality problems proactively.
+ before := p.serf.coordClient.GetCoordinate()
+ if before.IsCompatibleWith(&coord) {
+ after := p.serf.coordClient.Update(other.Name, &coord, rtt)
+
+ // Publish some metrics to give us an idea of how much we are
+ // adjusting each time we update.
+ d := float32(before.DistanceTo(after).Seconds() * 1.0e3)
+ metrics.AddSample([]string{"serf", "coordinate", "adjustment-ms"}, d)
+
+ // Cache the coordinate for the other node, and add our own
+ // to the cache as well since it just got updated. This lets
+ // users call GetCachedCoordinate with our node name, which is
+ // more friendly.
+ p.serf.coordCacheLock.Lock()
+ p.serf.coordCache[other.Name] = &coord
+ p.serf.coordCache[p.serf.config.NodeName] = p.serf.coordClient.GetCoordinate()
+ p.serf.coordCacheLock.Unlock()
+ } else {
+ log.Printf("[ERR] serf: Rejected bad coordinate: %v\n", coord)
+ }
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/query.go b/vendor/github.com/hashicorp/serf/serf/query.go
new file mode 100644
index 0000000..f29a3b3
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/query.go
@@ -0,0 +1,210 @@
+package serf
+
+import (
+ "math"
+ "regexp"
+ "sync"
+ "time"
+)
+
+// QueryParam is provided to Query() to configure the parameters of the
+// query. If not provided, sane defaults will be used.
+type QueryParam struct {
+ // If provided, we restrict the nodes that should respond to those
+ // with names in this list
+ FilterNodes []string
+
+ // FilterTags maps a tag name to a regular expression that is applied
+ // to restrict the nodes that should respond
+ FilterTags map[string]string
+
+ // If true, we are requesting an delivery acknowledgement from
+ // every node that meets the filter requirement. This means nodes
+ // the receive the message but do not pass the filters, will not
+ // send an ack.
+ RequestAck bool
+
+ // The timeout limits how long the query is left open. If not provided,
+ // then a default timeout is used based on the configuration of Serf
+ Timeout time.Duration
+}
+
+// DefaultQueryTimeout returns the default timeout value for a query
+// Computed as GossipInterval * QueryTimeoutMult * log(N+1)
+func (s *Serf) DefaultQueryTimeout() time.Duration {
+ n := s.memberlist.NumMembers()
+ timeout := s.config.MemberlistConfig.GossipInterval
+ timeout *= time.Duration(s.config.QueryTimeoutMult)
+ timeout *= time.Duration(math.Ceil(math.Log10(float64(n + 1))))
+ return timeout
+}
+
+// DefaultQueryParam is used to return the default query parameters
+func (s *Serf) DefaultQueryParams() *QueryParam {
+ return &QueryParam{
+ FilterNodes: nil,
+ FilterTags: nil,
+ RequestAck: false,
+ Timeout: s.DefaultQueryTimeout(),
+ }
+}
+
+// encodeFilters is used to convert the filters into the wire format
+func (q *QueryParam) encodeFilters() ([][]byte, error) {
+ var filters [][]byte
+
+ // Add the node filter
+ if len(q.FilterNodes) > 0 {
+ if buf, err := encodeFilter(filterNodeType, q.FilterNodes); err != nil {
+ return nil, err
+ } else {
+ filters = append(filters, buf)
+ }
+ }
+
+ // Add the tag filters
+ for tag, expr := range q.FilterTags {
+ filt := filterTag{tag, expr}
+ if buf, err := encodeFilter(filterTagType, &filt); err != nil {
+ return nil, err
+ } else {
+ filters = append(filters, buf)
+ }
+ }
+
+ return filters, nil
+}
+
+// QueryResponse is returned for each new Query. It is used to collect
+// Ack's as well as responses and to provide those back to a client.
+type QueryResponse struct {
+ // ackCh is used to send the name of a node for which we've received an ack
+ ackCh chan string
+
+ // deadline is the query end time (start + query timeout)
+ deadline time.Time
+
+ // Query ID
+ id uint32
+
+ // Stores the LTime of the query
+ lTime LamportTime
+
+ // respCh is used to send a response from a node
+ respCh chan NodeResponse
+
+ closed bool
+ closeLock sync.Mutex
+}
+
+// newQueryResponse is used to construct a new query response
+func newQueryResponse(n int, q *messageQuery) *QueryResponse {
+ resp := &QueryResponse{
+ deadline: time.Now().Add(q.Timeout),
+ id: q.ID,
+ lTime: q.LTime,
+ respCh: make(chan NodeResponse, n),
+ }
+ if q.Ack() {
+ resp.ackCh = make(chan string, n)
+ }
+ return resp
+}
+
+// Close is used to close the query, which will close the underlying
+// channels and prevent further deliveries
+func (r *QueryResponse) Close() {
+ r.closeLock.Lock()
+ defer r.closeLock.Unlock()
+ if r.closed {
+ return
+ }
+ r.closed = true
+ if r.ackCh != nil {
+ close(r.ackCh)
+ }
+ if r.respCh != nil {
+ close(r.respCh)
+ }
+}
+
+// Deadline returns the ending deadline of the query
+func (r *QueryResponse) Deadline() time.Time {
+ return r.deadline
+}
+
+// Finished returns if the query is finished running
+func (r *QueryResponse) Finished() bool {
+ return r.closed || time.Now().After(r.deadline)
+}
+
+// AckCh returns a channel that can be used to listen for acks
+// Channel will be closed when the query is finished. This is nil,
+// if the query did not specify RequestAck.
+func (r *QueryResponse) AckCh() <-chan string {
+ return r.ackCh
+}
+
+// ResponseCh returns a channel that can be used to listen for responses.
+// Channel will be closed when the query is finished.
+func (r *QueryResponse) ResponseCh() <-chan NodeResponse {
+ return r.respCh
+}
+
+// NodeResponse is used to represent a single response from a node
+type NodeResponse struct {
+ From string
+ Payload []byte
+}
+
+// shouldProcessQuery checks if a query should be proceeded given
+// a set of filers.
+func (s *Serf) shouldProcessQuery(filters [][]byte) bool {
+ for _, filter := range filters {
+ switch filterType(filter[0]) {
+ case filterNodeType:
+ // Decode the filter
+ var nodes filterNode
+ if err := decodeMessage(filter[1:], &nodes); err != nil {
+ s.logger.Printf("[WARN] serf: failed to decode filterNodeType: %v", err)
+ return false
+ }
+
+ // Check if we are being targeted
+ found := false
+ for _, n := range nodes {
+ if n == s.config.NodeName {
+ found = true
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+
+ case filterTagType:
+ // Decode the filter
+ var filt filterTag
+ if err := decodeMessage(filter[1:], &filt); err != nil {
+ s.logger.Printf("[WARN] serf: failed to decode filterTagType: %v", err)
+ return false
+ }
+
+ // Check if we match this regex
+ tags := s.config.Tags
+ matched, err := regexp.MatchString(filt.Expr, tags[filt.Tag])
+ if err != nil {
+ s.logger.Printf("[WARN] serf: failed to compile filter regex (%s): %v", filt.Expr, err)
+ return false
+ }
+ if !matched {
+ return false
+ }
+
+ default:
+ s.logger.Printf("[WARN] serf: query has unrecognized filter type: %d", filter[0])
+ return false
+ }
+ }
+ return true
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/serf.go b/vendor/github.com/hashicorp/serf/serf/serf.go
new file mode 100644
index 0000000..613b915
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/serf.go
@@ -0,0 +1,1692 @@
+package serf
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "log"
+ "math/rand"
+ "net"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/armon/go-metrics"
+ "github.com/hashicorp/go-msgpack/codec"
+ "github.com/hashicorp/memberlist"
+ "github.com/hashicorp/serf/coordinate"
+)
+
+// These are the protocol versions that Serf can _understand_. These are
+// Serf-level protocol versions that are passed down as the delegate
+// version to memberlist below.
+const (
+ ProtocolVersionMin uint8 = 2
+ ProtocolVersionMax = 4
+)
+
+const (
+ // Used to detect if the meta data is tags
+ // or if it is a raw role
+ tagMagicByte uint8 = 255
+)
+
+var (
+ // FeatureNotSupported is returned if a feature cannot be used
+ // due to an older protocol version being used.
+ FeatureNotSupported = fmt.Errorf("Feature not supported")
+)
+
+func init() {
+ // Seed the random number generator
+ rand.Seed(time.Now().UnixNano())
+}
+
+// Serf is a single node that is part of a single cluster that gets
+// events about joins/leaves/failures/etc. It is created with the Create
+// method.
+//
+// All functions on the Serf structure are safe to call concurrently.
+type Serf struct {
+ // The clocks for different purposes. These MUST be the first things
+ // in this struct due to Golang issue #599.
+ clock LamportClock
+ eventClock LamportClock
+ queryClock LamportClock
+
+ broadcasts *memberlist.TransmitLimitedQueue
+ config *Config
+ failedMembers []*memberState
+ leftMembers []*memberState
+ memberlist *memberlist.Memberlist
+ memberLock sync.RWMutex
+ members map[string]*memberState
+
+ // Circular buffers for recent intents, used
+ // in case we get the intent before the relevant event
+ recentLeave []nodeIntent
+ recentLeaveIndex int
+ recentJoin []nodeIntent
+ recentJoinIndex int
+
+ eventBroadcasts *memberlist.TransmitLimitedQueue
+ eventBuffer []*userEvents
+ eventJoinIgnore bool
+ eventMinTime LamportTime
+ eventLock sync.RWMutex
+
+ queryBroadcasts *memberlist.TransmitLimitedQueue
+ queryBuffer []*queries
+ queryMinTime LamportTime
+ queryResponse map[LamportTime]*QueryResponse
+ queryLock sync.RWMutex
+
+ logger *log.Logger
+ joinLock sync.Mutex
+ stateLock sync.Mutex
+ state SerfState
+ shutdownCh chan struct{}
+
+ snapshotter *Snapshotter
+ keyManager *KeyManager
+
+ coordClient *coordinate.Client
+ coordCache map[string]*coordinate.Coordinate
+ coordCacheLock sync.RWMutex
+}
+
+// SerfState is the state of the Serf instance.
+type SerfState int
+
+const (
+ SerfAlive SerfState = iota
+ SerfLeaving
+ SerfLeft
+ SerfShutdown
+)
+
+func (s SerfState) String() string {
+ switch s {
+ case SerfAlive:
+ return "alive"
+ case SerfLeaving:
+ return "leaving"
+ case SerfLeft:
+ return "left"
+ case SerfShutdown:
+ return "shutdown"
+ default:
+ return "unknown"
+ }
+}
+
+// Member is a single member of the Serf cluster.
+type Member struct {
+ Name string
+ Addr net.IP
+ Port uint16
+ Tags map[string]string
+ Status MemberStatus
+
+ // The minimum, maximum, and current values of the protocol versions
+ // and delegate (Serf) protocol versions that each member can understand
+ // or is speaking.
+ ProtocolMin uint8
+ ProtocolMax uint8
+ ProtocolCur uint8
+ DelegateMin uint8
+ DelegateMax uint8
+ DelegateCur uint8
+}
+
+// MemberStatus is the state that a member is in.
+type MemberStatus int
+
+const (
+ StatusNone MemberStatus = iota
+ StatusAlive
+ StatusLeaving
+ StatusLeft
+ StatusFailed
+)
+
+func (s MemberStatus) String() string {
+ switch s {
+ case StatusNone:
+ return "none"
+ case StatusAlive:
+ return "alive"
+ case StatusLeaving:
+ return "leaving"
+ case StatusLeft:
+ return "left"
+ case StatusFailed:
+ return "failed"
+ default:
+ panic(fmt.Sprintf("unknown MemberStatus: %d", s))
+ }
+}
+
+// memberState is used to track members that are no longer active due to
+// leaving, failing, partitioning, etc. It tracks the member along with
+// when that member was marked as leaving.
+type memberState struct {
+ Member
+ statusLTime LamportTime // lamport clock time of last received message
+ leaveTime time.Time // wall clock time of leave
+}
+
+// nodeIntent is used to buffer intents for out-of-order deliveries
+type nodeIntent struct {
+ LTime LamportTime
+ Node string
+}
+
+// userEvent is used to buffer events to prevent re-delivery
+type userEvent struct {
+ Name string
+ Payload []byte
+}
+
+func (ue *userEvent) Equals(other *userEvent) bool {
+ if ue.Name != other.Name {
+ return false
+ }
+ if bytes.Compare(ue.Payload, other.Payload) != 0 {
+ return false
+ }
+ return true
+}
+
+// userEvents stores all the user events at a specific time
+type userEvents struct {
+ LTime LamportTime
+ Events []userEvent
+}
+
+// queries stores all the query ids at a specific time
+type queries struct {
+ LTime LamportTime
+ QueryIDs []uint32
+}
+
+const (
+ UserEventSizeLimit = 512 // Maximum byte size for event name and payload
+ snapshotSizeLimit = 128 * 1024 // Maximum 128 KB snapshot
+)
+
+// Create creates a new Serf instance, starting all the background tasks
+// to maintain cluster membership information.
+//
+// After calling this function, the configuration should no longer be used
+// or modified by the caller.
+func Create(conf *Config) (*Serf, error) {
+ conf.Init()
+ if conf.ProtocolVersion < ProtocolVersionMin {
+ return nil, fmt.Errorf("Protocol version '%d' too low. Must be in range: [%d, %d]",
+ conf.ProtocolVersion, ProtocolVersionMin, ProtocolVersionMax)
+ } else if conf.ProtocolVersion > ProtocolVersionMax {
+ return nil, fmt.Errorf("Protocol version '%d' too high. Must be in range: [%d, %d]",
+ conf.ProtocolVersion, ProtocolVersionMin, ProtocolVersionMax)
+ }
+
+ serf := &Serf{
+ config: conf,
+ logger: log.New(conf.LogOutput, "", log.LstdFlags),
+ members: make(map[string]*memberState),
+ queryResponse: make(map[LamportTime]*QueryResponse),
+ shutdownCh: make(chan struct{}),
+ state: SerfAlive,
+ }
+
+ // Check that the meta data length is okay
+ if len(serf.encodeTags(conf.Tags)) > memberlist.MetaMaxSize {
+ return nil, fmt.Errorf("Encoded length of tags exceeds limit of %d bytes", memberlist.MetaMaxSize)
+ }
+
+ // Check if serf member event coalescing is enabled
+ if conf.CoalescePeriod > 0 && conf.QuiescentPeriod > 0 && conf.EventCh != nil {
+ c := &memberEventCoalescer{
+ lastEvents: make(map[string]EventType),
+ latestEvents: make(map[string]coalesceEvent),
+ }
+
+ conf.EventCh = coalescedEventCh(conf.EventCh, serf.shutdownCh,
+ conf.CoalescePeriod, conf.QuiescentPeriod, c)
+ }
+
+ // Check if user event coalescing is enabled
+ if conf.UserCoalescePeriod > 0 && conf.UserQuiescentPeriod > 0 && conf.EventCh != nil {
+ c := &userEventCoalescer{
+ events: make(map[string]*latestUserEvents),
+ }
+
+ conf.EventCh = coalescedEventCh(conf.EventCh, serf.shutdownCh,
+ conf.UserCoalescePeriod, conf.UserQuiescentPeriod, c)
+ }
+
+ // Listen for internal Serf queries. This is setup before the snapshotter, since
+ // we want to capture the query-time, but the internal listener does not passthrough
+ // the queries
+ outCh, err := newSerfQueries(serf, serf.logger, conf.EventCh, serf.shutdownCh)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to setup serf query handler: %v", err)
+ }
+ conf.EventCh = outCh
+
+ // Set up network coordinate client.
+ if !conf.DisableCoordinates {
+ serf.coordClient, err = coordinate.NewClient(coordinate.DefaultConfig())
+ if err != nil {
+ return nil, fmt.Errorf("Failed to create coordinate client: %v", err)
+ }
+ }
+
+ // Try access the snapshot
+ var oldClock, oldEventClock, oldQueryClock LamportTime
+ var prev []*PreviousNode
+ if conf.SnapshotPath != "" {
+ eventCh, snap, err := NewSnapshotter(
+ conf.SnapshotPath,
+ snapshotSizeLimit,
+ conf.RejoinAfterLeave,
+ serf.logger,
+ &serf.clock,
+ serf.coordClient,
+ conf.EventCh,
+ serf.shutdownCh)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to setup snapshot: %v", err)
+ }
+ serf.snapshotter = snap
+ conf.EventCh = eventCh
+ prev = snap.AliveNodes()
+ oldClock = snap.LastClock()
+ oldEventClock = snap.LastEventClock()
+ oldQueryClock = snap.LastQueryClock()
+ serf.eventMinTime = oldEventClock + 1
+ serf.queryMinTime = oldQueryClock + 1
+ }
+
+ // Set up the coordinate cache. We do this after we read the snapshot to
+ // make sure we get a good initial value from there, if we got one.
+ if !conf.DisableCoordinates {
+ serf.coordCache = make(map[string]*coordinate.Coordinate)
+ serf.coordCache[conf.NodeName] = serf.coordClient.GetCoordinate()
+ }
+
+ // Setup the various broadcast queues, which we use to send our own
+ // custom broadcasts along the gossip channel.
+ serf.broadcasts = &memberlist.TransmitLimitedQueue{
+ NumNodes: func() int {
+ return len(serf.members)
+ },
+ RetransmitMult: conf.MemberlistConfig.RetransmitMult,
+ }
+ serf.eventBroadcasts = &memberlist.TransmitLimitedQueue{
+ NumNodes: func() int {
+ return len(serf.members)
+ },
+ RetransmitMult: conf.MemberlistConfig.RetransmitMult,
+ }
+ serf.queryBroadcasts = &memberlist.TransmitLimitedQueue{
+ NumNodes: func() int {
+ return len(serf.members)
+ },
+ RetransmitMult: conf.MemberlistConfig.RetransmitMult,
+ }
+
+ // Create the buffer for recent intents
+ serf.recentJoin = make([]nodeIntent, conf.RecentIntentBuffer)
+ serf.recentLeave = make([]nodeIntent, conf.RecentIntentBuffer)
+
+ // Create a buffer for events and queries
+ serf.eventBuffer = make([]*userEvents, conf.EventBuffer)
+ serf.queryBuffer = make([]*queries, conf.QueryBuffer)
+
+ // Ensure our lamport clock is at least 1, so that the default
+ // join LTime of 0 does not cause issues
+ serf.clock.Increment()
+ serf.eventClock.Increment()
+ serf.queryClock.Increment()
+
+ // Restore the clock from snap if we have one
+ serf.clock.Witness(oldClock)
+ serf.eventClock.Witness(oldEventClock)
+ serf.queryClock.Witness(oldQueryClock)
+
+ // Modify the memberlist configuration with keys that we set
+ conf.MemberlistConfig.Events = &eventDelegate{serf: serf}
+ conf.MemberlistConfig.Conflict = &conflictDelegate{serf: serf}
+ conf.MemberlistConfig.Delegate = &delegate{serf: serf}
+ conf.MemberlistConfig.DelegateProtocolVersion = conf.ProtocolVersion
+ conf.MemberlistConfig.DelegateProtocolMin = ProtocolVersionMin
+ conf.MemberlistConfig.DelegateProtocolMax = ProtocolVersionMax
+ conf.MemberlistConfig.Name = conf.NodeName
+ conf.MemberlistConfig.ProtocolVersion = ProtocolVersionMap[conf.ProtocolVersion]
+ if !conf.DisableCoordinates {
+ conf.MemberlistConfig.Ping = &pingDelegate{serf: serf}
+ }
+
+ // Setup a merge delegate if necessary
+ if conf.Merge != nil {
+ md := &mergeDelegate{serf: serf}
+ conf.MemberlistConfig.Merge = md
+ conf.MemberlistConfig.Alive = md
+ }
+
+ // Create the underlying memberlist that will manage membership
+ // and failure detection for the Serf instance.
+ memberlist, err := memberlist.Create(conf.MemberlistConfig)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to create memberlist: %v", err)
+ }
+
+ serf.memberlist = memberlist
+
+ // Create a key manager for handling all encryption key changes
+ serf.keyManager = &KeyManager{serf: serf}
+
+ // Start the background tasks. See the documentation above each method
+ // for more information on their role.
+ go serf.handleReap()
+ go serf.handleReconnect()
+ go serf.checkQueueDepth("Intent", serf.broadcasts)
+ go serf.checkQueueDepth("Event", serf.eventBroadcasts)
+ go serf.checkQueueDepth("Query", serf.queryBroadcasts)
+
+ // Attempt to re-join the cluster if we have known nodes
+ if len(prev) != 0 {
+ go serf.handleRejoin(prev)
+ }
+
+ return serf, nil
+}
+
+// ProtocolVersion returns the current protocol version in use by Serf.
+// This is the Serf protocol version, not the memberlist protocol version.
+func (s *Serf) ProtocolVersion() uint8 {
+ return s.config.ProtocolVersion
+}
+
+// EncryptionEnabled is a predicate that determines whether or not encryption
+// is enabled, which can be possible in one of 2 cases:
+// - Single encryption key passed at agent start (no persistence)
+// - Keyring file provided at agent start
+func (s *Serf) EncryptionEnabled() bool {
+ return s.config.MemberlistConfig.Keyring != nil
+}
+
+// KeyManager returns the key manager for the current Serf instance.
+func (s *Serf) KeyManager() *KeyManager {
+ return s.keyManager
+}
+
+// UserEvent is used to broadcast a custom user event with a given
+// name and payload. The events must be fairly small, and if the
+// size limit is exceeded and error will be returned. If coalesce is enabled,
+// nodes are allowed to coalesce this event. Coalescing is only available
+// starting in v0.2
+func (s *Serf) UserEvent(name string, payload []byte, coalesce bool) error {
+ // Check the size limit
+ if len(name)+len(payload) > UserEventSizeLimit {
+ return fmt.Errorf("user event exceeds limit of %d bytes", UserEventSizeLimit)
+ }
+
+ // Create a message
+ msg := messageUserEvent{
+ LTime: s.eventClock.Time(),
+ Name: name,
+ Payload: payload,
+ CC: coalesce,
+ }
+ s.eventClock.Increment()
+
+ // Process update locally
+ s.handleUserEvent(&msg)
+
+ // Start broadcasting the event
+ raw, err := encodeMessage(messageUserEventType, &msg)
+ if err != nil {
+ return err
+ }
+ s.eventBroadcasts.QueueBroadcast(&broadcast{
+ msg: raw,
+ })
+ return nil
+}
+
+// Query is used to broadcast a new query. The query must be fairly small,
+// and an error will be returned if the size limit is exceeded. This is only
+// available with protocol version 4 and newer. Query parameters are optional,
+// and if not provided, a sane set of defaults will be used.
+func (s *Serf) Query(name string, payload []byte, params *QueryParam) (*QueryResponse, error) {
+ // Check that the latest protocol is in use
+ if s.ProtocolVersion() < 4 {
+ return nil, FeatureNotSupported
+ }
+
+ // Provide default parameters if none given
+ if params == nil {
+ params = s.DefaultQueryParams()
+ } else if params.Timeout == 0 {
+ params.Timeout = s.DefaultQueryTimeout()
+ }
+
+ // Get the local node
+ local := s.memberlist.LocalNode()
+
+ // Encode the filters
+ filters, err := params.encodeFilters()
+ if err != nil {
+ return nil, fmt.Errorf("Failed to format filters: %v", err)
+ }
+
+ // Setup the flags
+ var flags uint32
+ if params.RequestAck {
+ flags |= queryFlagAck
+ }
+
+ // Create a message
+ q := messageQuery{
+ LTime: s.queryClock.Time(),
+ ID: uint32(rand.Int31()),
+ Addr: local.Addr,
+ Port: local.Port,
+ Filters: filters,
+ Flags: flags,
+ Timeout: params.Timeout,
+ Name: name,
+ Payload: payload,
+ }
+
+ // Encode the query
+ raw, err := encodeMessage(messageQueryType, &q)
+ if err != nil {
+ return nil, err
+ }
+
+ // Check the size
+ if len(raw) > s.config.QuerySizeLimit {
+ return nil, fmt.Errorf("query exceeds limit of %d bytes", s.config.QuerySizeLimit)
+ }
+
+ // Register QueryResponse to track acks and responses
+ resp := newQueryResponse(s.memberlist.NumMembers(), &q)
+ s.registerQueryResponse(params.Timeout, resp)
+
+ // Process query locally
+ s.handleQuery(&q)
+
+ // Start broadcasting the event
+ s.queryBroadcasts.QueueBroadcast(&broadcast{
+ msg: raw,
+ })
+ return resp, nil
+}
+
+// registerQueryResponse is used to setup the listeners for the query,
+// and to schedule closing the query after the timeout.
+func (s *Serf) registerQueryResponse(timeout time.Duration, resp *QueryResponse) {
+ s.queryLock.Lock()
+ defer s.queryLock.Unlock()
+
+ // Map the LTime to the QueryResponse. This is necessarily 1-to-1,
+ // since we increment the time for each new query.
+ s.queryResponse[resp.lTime] = resp
+
+ // Setup a timer to close the response and deregister after the timeout
+ time.AfterFunc(timeout, func() {
+ s.queryLock.Lock()
+ delete(s.queryResponse, resp.lTime)
+ resp.Close()
+ s.queryLock.Unlock()
+ })
+}
+
+// SetTags is used to dynamically update the tags associated with
+// the local node. This will propagate the change to the rest of
+// the cluster. Blocks until a the message is broadcast out.
+func (s *Serf) SetTags(tags map[string]string) error {
+ // Check that the meta data length is okay
+ if len(s.encodeTags(tags)) > memberlist.MetaMaxSize {
+ return fmt.Errorf("Encoded length of tags exceeds limit of %d bytes",
+ memberlist.MetaMaxSize)
+ }
+
+ // Update the config
+ s.config.Tags = tags
+
+ // Trigger a memberlist update
+ return s.memberlist.UpdateNode(s.config.BroadcastTimeout)
+}
+
+// Join joins an existing Serf cluster. Returns the number of nodes
+// successfully contacted. The returned error will be non-nil only in the
+// case that no nodes could be contacted. If ignoreOld is true, then any
+// user messages sent prior to the join will be ignored.
+func (s *Serf) Join(existing []string, ignoreOld bool) (int, error) {
+ // Do a quick state check
+ if s.State() != SerfAlive {
+ return 0, fmt.Errorf("Serf can't Join after Leave or Shutdown")
+ }
+
+ // Hold the joinLock, this is to make eventJoinIgnore safe
+ s.joinLock.Lock()
+ defer s.joinLock.Unlock()
+
+ // Ignore any events from a potential join. This is safe since we hold
+ // the joinLock and nobody else can be doing a Join
+ if ignoreOld {
+ s.eventJoinIgnore = true
+ defer func() {
+ s.eventJoinIgnore = false
+ }()
+ }
+
+ // Have memberlist attempt to join
+ num, err := s.memberlist.Join(existing)
+
+ // If we joined any nodes, broadcast the join message
+ if num > 0 {
+ // Start broadcasting the update
+ if err := s.broadcastJoin(s.clock.Time()); err != nil {
+ return num, err
+ }
+ }
+
+ return num, err
+}
+
+// broadcastJoin broadcasts a new join intent with a
+// given clock value. It is used on either join, or if
+// we need to refute an older leave intent. Cannot be called
+// with the memberLock held.
+func (s *Serf) broadcastJoin(ltime LamportTime) error {
+ // Construct message to update our lamport clock
+ msg := messageJoin{
+ LTime: ltime,
+ Node: s.config.NodeName,
+ }
+ s.clock.Witness(ltime)
+
+ // Process update locally
+ s.handleNodeJoinIntent(&msg)
+
+ // Start broadcasting the update
+ if err := s.broadcast(messageJoinType, &msg, nil); err != nil {
+ s.logger.Printf("[WARN] serf: Failed to broadcast join intent: %v", err)
+ return err
+ }
+ return nil
+}
+
+// Leave gracefully exits the cluster. It is safe to call this multiple
+// times.
+func (s *Serf) Leave() error {
+ // Check the current state
+ s.stateLock.Lock()
+ if s.state == SerfLeft {
+ s.stateLock.Unlock()
+ return nil
+ } else if s.state == SerfLeaving {
+ s.stateLock.Unlock()
+ return fmt.Errorf("Leave already in progress")
+ } else if s.state == SerfShutdown {
+ s.stateLock.Unlock()
+ return fmt.Errorf("Leave called after Shutdown")
+ }
+ s.state = SerfLeaving
+ s.stateLock.Unlock()
+
+ // If we have a snapshot, mark we are leaving
+ if s.snapshotter != nil {
+ s.snapshotter.Leave()
+ }
+
+ // Construct the message for the graceful leave
+ msg := messageLeave{
+ LTime: s.clock.Time(),
+ Node: s.config.NodeName,
+ }
+ s.clock.Increment()
+
+ // Process the leave locally
+ s.handleNodeLeaveIntent(&msg)
+
+ // Only broadcast the leave message if there is at least one
+ // other node alive.
+ if s.hasAliveMembers() {
+ notifyCh := make(chan struct{})
+ if err := s.broadcast(messageLeaveType, &msg, notifyCh); err != nil {
+ return err
+ }
+
+ select {
+ case <-notifyCh:
+ case <-time.After(s.config.BroadcastTimeout):
+ return errors.New("timeout while waiting for graceful leave")
+ }
+ }
+
+ // Attempt the memberlist leave
+ err := s.memberlist.Leave(s.config.BroadcastTimeout)
+ if err != nil {
+ return err
+ }
+
+ // Transition to Left only if we not already shutdown
+ s.stateLock.Lock()
+ if s.state != SerfShutdown {
+ s.state = SerfLeft
+ }
+ s.stateLock.Unlock()
+ return nil
+}
+
+// hasAliveMembers is called to check for any alive members other than
+// ourself.
+func (s *Serf) hasAliveMembers() bool {
+ s.memberLock.RLock()
+ defer s.memberLock.RUnlock()
+
+ hasAlive := false
+ for _, m := range s.members {
+ // Skip ourself, we want to know if OTHER members are alive
+ if m.Name == s.config.NodeName {
+ continue
+ }
+
+ if m.Status == StatusAlive {
+ hasAlive = true
+ break
+ }
+ }
+ return hasAlive
+}
+
+// LocalMember returns the Member information for the local node
+func (s *Serf) LocalMember() Member {
+ s.memberLock.RLock()
+ defer s.memberLock.RUnlock()
+ return s.members[s.config.NodeName].Member
+}
+
+// Members returns a point-in-time snapshot of the members of this cluster.
+func (s *Serf) Members() []Member {
+ s.memberLock.RLock()
+ defer s.memberLock.RUnlock()
+
+ members := make([]Member, 0, len(s.members))
+ for _, m := range s.members {
+ members = append(members, m.Member)
+ }
+
+ return members
+}
+
+// RemoveFailedNode forcibly removes a failed node from the cluster
+// immediately, instead of waiting for the reaper to eventually reclaim it.
+// This also has the effect that Serf will no longer attempt to reconnect
+// to this node.
+func (s *Serf) RemoveFailedNode(node string) error {
+ // Construct the message to broadcast
+ msg := messageLeave{
+ LTime: s.clock.Time(),
+ Node: node,
+ }
+ s.clock.Increment()
+
+ // Process our own event
+ s.handleNodeLeaveIntent(&msg)
+
+ // If we have no members, then we don't need to broadcast
+ if !s.hasAliveMembers() {
+ return nil
+ }
+
+ // Broadcast the remove
+ notifyCh := make(chan struct{})
+ if err := s.broadcast(messageLeaveType, &msg, notifyCh); err != nil {
+ return err
+ }
+
+ // Wait for the broadcast
+ select {
+ case <-notifyCh:
+ case <-time.After(s.config.BroadcastTimeout):
+ return fmt.Errorf("timed out broadcasting node removal")
+ }
+
+ return nil
+}
+
+// Shutdown forcefully shuts down the Serf instance, stopping all network
+// activity and background maintenance associated with the instance.
+//
+// This is not a graceful shutdown, and should be preceded by a call
+// to Leave. Otherwise, other nodes in the cluster will detect this node's
+// exit as a node failure.
+//
+// It is safe to call this method multiple times.
+func (s *Serf) Shutdown() error {
+ s.stateLock.Lock()
+ defer s.stateLock.Unlock()
+
+ if s.state == SerfShutdown {
+ return nil
+ }
+
+ if s.state != SerfLeft {
+ s.logger.Printf("[WARN] serf: Shutdown without a Leave")
+ }
+
+ s.state = SerfShutdown
+ close(s.shutdownCh)
+
+ err := s.memberlist.Shutdown()
+ if err != nil {
+ return err
+ }
+
+ // Wait for the snapshoter to finish if we have one
+ if s.snapshotter != nil {
+ s.snapshotter.Wait()
+ }
+
+ return nil
+}
+
+// ShutdownCh returns a channel that can be used to wait for
+// Serf to shutdown.
+func (s *Serf) ShutdownCh() <-chan struct{} {
+ return s.shutdownCh
+}
+
+// Memberlist is used to get access to the underlying Memberlist instance
+func (s *Serf) Memberlist() *memberlist.Memberlist {
+ return s.memberlist
+}
+
+// State is the current state of this Serf instance.
+func (s *Serf) State() SerfState {
+ s.stateLock.Lock()
+ defer s.stateLock.Unlock()
+ return s.state
+}
+
+// broadcast takes a Serf message type, encodes it for the wire, and queues
+// the broadcast. If a notify channel is given, this channel will be closed
+// when the broadcast is sent.
+func (s *Serf) broadcast(t messageType, msg interface{}, notify chan<- struct{}) error {
+ raw, err := encodeMessage(t, msg)
+ if err != nil {
+ return err
+ }
+
+ s.broadcasts.QueueBroadcast(&broadcast{
+ msg: raw,
+ notify: notify,
+ })
+ return nil
+}
+
+// handleNodeJoin is called when a node join event is received
+// from memberlist.
+func (s *Serf) handleNodeJoin(n *memberlist.Node) {
+ s.memberLock.Lock()
+ defer s.memberLock.Unlock()
+
+ var oldStatus MemberStatus
+ member, ok := s.members[n.Name]
+ if !ok {
+ oldStatus = StatusNone
+ member = &memberState{
+ Member: Member{
+ Name: n.Name,
+ Addr: net.IP(n.Addr),
+ Port: n.Port,
+ Tags: s.decodeTags(n.Meta),
+ Status: StatusAlive,
+ },
+ }
+
+ // Check if we have a join intent and use the LTime
+ if join := recentIntent(s.recentJoin, n.Name); join != nil {
+ member.statusLTime = join.LTime
+ }
+
+ // Check if we have a leave intent
+ if leave := recentIntent(s.recentLeave, n.Name); leave != nil {
+ if leave.LTime > member.statusLTime {
+ member.Status = StatusLeaving
+ member.statusLTime = leave.LTime
+ }
+ }
+
+ s.members[n.Name] = member
+ } else {
+ oldStatus = member.Status
+ member.Status = StatusAlive
+ member.leaveTime = time.Time{}
+ member.Addr = net.IP(n.Addr)
+ member.Port = n.Port
+ member.Tags = s.decodeTags(n.Meta)
+ }
+
+ // Update the protocol versions every time we get an event
+ member.ProtocolMin = n.PMin
+ member.ProtocolMax = n.PMax
+ member.ProtocolCur = n.PCur
+ member.DelegateMin = n.DMin
+ member.DelegateMax = n.DMax
+ member.DelegateCur = n.DCur
+
+ // If node was previously in a failed state, then clean up some
+ // internal accounting.
+ // TODO(mitchellh): needs tests to verify not reaped
+ if oldStatus == StatusFailed || oldStatus == StatusLeft {
+ s.failedMembers = removeOldMember(s.failedMembers, member.Name)
+ s.leftMembers = removeOldMember(s.leftMembers, member.Name)
+ }
+
+ // Update some metrics
+ metrics.IncrCounter([]string{"serf", "member", "join"}, 1)
+
+ // Send an event along
+ s.logger.Printf("[INFO] serf: EventMemberJoin: %s %s",
+ member.Member.Name, member.Member.Addr)
+ if s.config.EventCh != nil {
+ s.config.EventCh <- MemberEvent{
+ Type: EventMemberJoin,
+ Members: []Member{member.Member},
+ }
+ }
+}
+
+// handleNodeLeave is called when a node leave event is received
+// from memberlist.
+func (s *Serf) handleNodeLeave(n *memberlist.Node) {
+ s.memberLock.Lock()
+ defer s.memberLock.Unlock()
+
+ member, ok := s.members[n.Name]
+ if !ok {
+ // We've never even heard of this node that is supposedly
+ // leaving. Just ignore it completely.
+ return
+ }
+
+ switch member.Status {
+ case StatusLeaving:
+ member.Status = StatusLeft
+ member.leaveTime = time.Now()
+ s.leftMembers = append(s.leftMembers, member)
+ case StatusAlive:
+ member.Status = StatusFailed
+ member.leaveTime = time.Now()
+ s.failedMembers = append(s.failedMembers, member)
+ default:
+ // Unknown state that it was in? Just don't do anything
+ s.logger.Printf("[WARN] serf: Bad state when leave: %d", member.Status)
+ return
+ }
+
+ // Send an event along
+ event := EventMemberLeave
+ eventStr := "EventMemberLeave"
+ if member.Status != StatusLeft {
+ event = EventMemberFailed
+ eventStr = "EventMemberFailed"
+ }
+
+ // Update some metrics
+ metrics.IncrCounter([]string{"serf", "member", member.Status.String()}, 1)
+
+ s.logger.Printf("[INFO] serf: %s: %s %s",
+ eventStr, member.Member.Name, member.Member.Addr)
+ if s.config.EventCh != nil {
+ s.config.EventCh <- MemberEvent{
+ Type: event,
+ Members: []Member{member.Member},
+ }
+ }
+}
+
+// handleNodeUpdate is called when a node meta data update
+// has taken place
+func (s *Serf) handleNodeUpdate(n *memberlist.Node) {
+ s.memberLock.Lock()
+ defer s.memberLock.Unlock()
+
+ member, ok := s.members[n.Name]
+ if !ok {
+ // We've never even heard of this node that is updating.
+ // Just ignore it completely.
+ return
+ }
+
+ // Update the member attributes
+ member.Addr = net.IP(n.Addr)
+ member.Port = n.Port
+ member.Tags = s.decodeTags(n.Meta)
+
+ // Snag the latest versions. NOTE - the current memberlist code will NOT
+ // fire an update event if the metadata (for Serf, tags) stays the same
+ // and only the protocol versions change. If we wake any Serf-level
+ // protocol changes where we want to get this event under those
+ // circumstances, we will need to update memberlist to do a check of
+ // versions as well as the metadata.
+ member.ProtocolMin = n.PMin
+ member.ProtocolMax = n.PMax
+ member.ProtocolCur = n.PCur
+ member.DelegateMin = n.DMin
+ member.DelegateMax = n.DMax
+ member.DelegateCur = n.DCur
+
+ // Update some metrics
+ metrics.IncrCounter([]string{"serf", "member", "update"}, 1)
+
+ // Send an event along
+ s.logger.Printf("[INFO] serf: EventMemberUpdate: %s", member.Member.Name)
+ if s.config.EventCh != nil {
+ s.config.EventCh <- MemberEvent{
+ Type: EventMemberUpdate,
+ Members: []Member{member.Member},
+ }
+ }
+}
+
+// handleNodeLeaveIntent is called when an intent to leave is received.
+func (s *Serf) handleNodeLeaveIntent(leaveMsg *messageLeave) bool {
+ // Witness a potentially newer time
+ s.clock.Witness(leaveMsg.LTime)
+
+ s.memberLock.Lock()
+ defer s.memberLock.Unlock()
+
+ member, ok := s.members[leaveMsg.Node]
+ if !ok {
+ // If we've already seen this message don't rebroadcast
+ if recentIntent(s.recentLeave, leaveMsg.Node) != nil {
+ return false
+ }
+
+ // We don't know this member so store it in a buffer for now
+ s.recentLeave[s.recentLeaveIndex] = nodeIntent{
+ LTime: leaveMsg.LTime,
+ Node: leaveMsg.Node,
+ }
+ s.recentLeaveIndex = (s.recentLeaveIndex + 1) % len(s.recentLeave)
+ return true
+ }
+
+ // If the message is old, then it is irrelevant and we can skip it
+ if leaveMsg.LTime <= member.statusLTime {
+ return false
+ }
+
+ // Refute us leaving if we are in the alive state
+ // Must be done in another goroutine since we have the memberLock
+ if leaveMsg.Node == s.config.NodeName && s.state == SerfAlive {
+ s.logger.Printf("[DEBUG] serf: Refuting an older leave intent")
+ go s.broadcastJoin(s.clock.Time())
+ return false
+ }
+
+ // State transition depends on current state
+ switch member.Status {
+ case StatusAlive:
+ member.Status = StatusLeaving
+ member.statusLTime = leaveMsg.LTime
+ return true
+ case StatusFailed:
+ member.Status = StatusLeft
+ member.statusLTime = leaveMsg.LTime
+
+ // Remove from the failed list and add to the left list. We add
+ // to the left list so that when we do a sync, other nodes will
+ // remove it from their failed list.
+ s.failedMembers = removeOldMember(s.failedMembers, member.Name)
+ s.leftMembers = append(s.leftMembers, member)
+
+ // We must push a message indicating the node has now
+ // left to allow higher-level applications to handle the
+ // graceful leave.
+ s.logger.Printf("[INFO] serf: EventMemberLeave (forced): %s %s",
+ member.Member.Name, member.Member.Addr)
+ if s.config.EventCh != nil {
+ s.config.EventCh <- MemberEvent{
+ Type: EventMemberLeave,
+ Members: []Member{member.Member},
+ }
+ }
+ return true
+ default:
+ return false
+ }
+}
+
+// handleNodeJoinIntent is called when a node broadcasts a
+// join message to set the lamport time of its join
+func (s *Serf) handleNodeJoinIntent(joinMsg *messageJoin) bool {
+ // Witness a potentially newer time
+ s.clock.Witness(joinMsg.LTime)
+
+ s.memberLock.Lock()
+ defer s.memberLock.Unlock()
+
+ member, ok := s.members[joinMsg.Node]
+ if !ok {
+ // If we've already seen this message don't rebroadcast
+ if recentIntent(s.recentJoin, joinMsg.Node) != nil {
+ return false
+ }
+
+ // We don't know this member so store it in a buffer for now
+ s.recentJoin[s.recentJoinIndex] = nodeIntent{LTime: joinMsg.LTime, Node: joinMsg.Node}
+ s.recentJoinIndex = (s.recentJoinIndex + 1) % len(s.recentJoin)
+ return true
+ }
+
+ // Check if this time is newer than what we have
+ if joinMsg.LTime <= member.statusLTime {
+ return false
+ }
+
+ // Update the LTime
+ member.statusLTime = joinMsg.LTime
+
+ // If we are in the leaving state, we should go back to alive,
+ // since the leaving message must have been for an older time
+ if member.Status == StatusLeaving {
+ member.Status = StatusAlive
+ }
+ return true
+}
+
+// handleUserEvent is called when a user event broadcast is
+// received. Returns if the message should be rebroadcast.
+func (s *Serf) handleUserEvent(eventMsg *messageUserEvent) bool {
+ // Witness a potentially newer time
+ s.eventClock.Witness(eventMsg.LTime)
+
+ s.eventLock.Lock()
+ defer s.eventLock.Unlock()
+
+ // Ignore if it is before our minimum event time
+ if eventMsg.LTime < s.eventMinTime {
+ return false
+ }
+
+ // Check if this message is too old
+ curTime := s.eventClock.Time()
+ if curTime > LamportTime(len(s.eventBuffer)) &&
+ eventMsg.LTime < curTime-LamportTime(len(s.eventBuffer)) {
+ s.logger.Printf(
+ "[WARN] serf: received old event %s from time %d (current: %d)",
+ eventMsg.Name,
+ eventMsg.LTime,
+ s.eventClock.Time())
+ return false
+ }
+
+ // Check if we've already seen this
+ idx := eventMsg.LTime % LamportTime(len(s.eventBuffer))
+ seen := s.eventBuffer[idx]
+ userEvent := userEvent{Name: eventMsg.Name, Payload: eventMsg.Payload}
+ if seen != nil && seen.LTime == eventMsg.LTime {
+ for _, previous := range seen.Events {
+ if previous.Equals(&userEvent) {
+ return false
+ }
+ }
+ } else {
+ seen = &userEvents{LTime: eventMsg.LTime}
+ s.eventBuffer[idx] = seen
+ }
+
+ // Add to recent events
+ seen.Events = append(seen.Events, userEvent)
+
+ // Update some metrics
+ metrics.IncrCounter([]string{"serf", "events"}, 1)
+ metrics.IncrCounter([]string{"serf", "events", eventMsg.Name}, 1)
+
+ if s.config.EventCh != nil {
+ s.config.EventCh <- UserEvent{
+ LTime: eventMsg.LTime,
+ Name: eventMsg.Name,
+ Payload: eventMsg.Payload,
+ Coalesce: eventMsg.CC,
+ }
+ }
+ return true
+}
+
+// handleQuery is called when a query broadcast is
+// received. Returns if the message should be rebroadcast.
+func (s *Serf) handleQuery(query *messageQuery) bool {
+ // Witness a potentially newer time
+ s.queryClock.Witness(query.LTime)
+
+ s.queryLock.Lock()
+ defer s.queryLock.Unlock()
+
+ // Ignore if it is before our minimum query time
+ if query.LTime < s.queryMinTime {
+ return false
+ }
+
+ // Check if this message is too old
+ curTime := s.queryClock.Time()
+ if curTime > LamportTime(len(s.queryBuffer)) &&
+ query.LTime < curTime-LamportTime(len(s.queryBuffer)) {
+ s.logger.Printf(
+ "[WARN] serf: received old query %s from time %d (current: %d)",
+ query.Name,
+ query.LTime,
+ s.queryClock.Time())
+ return false
+ }
+
+ // Check if we've already seen this
+ idx := query.LTime % LamportTime(len(s.queryBuffer))
+ seen := s.queryBuffer[idx]
+ if seen != nil && seen.LTime == query.LTime {
+ for _, previous := range seen.QueryIDs {
+ if previous == query.ID {
+ // Seen this ID already
+ return false
+ }
+ }
+ } else {
+ seen = &queries{LTime: query.LTime}
+ s.queryBuffer[idx] = seen
+ }
+
+ // Add to recent queries
+ seen.QueryIDs = append(seen.QueryIDs, query.ID)
+
+ // Update some metrics
+ metrics.IncrCounter([]string{"serf", "queries"}, 1)
+ metrics.IncrCounter([]string{"serf", "queries", query.Name}, 1)
+
+ // Check if we should rebroadcast, this may be disabled by a flag
+ rebroadcast := true
+ if query.NoBroadcast() {
+ rebroadcast = false
+ }
+
+ // Filter the query
+ if !s.shouldProcessQuery(query.Filters) {
+ // Even if we don't process it further, we should rebroadcast,
+ // since it is the first time we've seen this.
+ return rebroadcast
+ }
+
+ // Send ack if requested, without waiting for client to Respond()
+ if query.Ack() {
+ ack := messageQueryResponse{
+ LTime: query.LTime,
+ ID: query.ID,
+ From: s.config.NodeName,
+ Flags: queryFlagAck,
+ }
+ raw, err := encodeMessage(messageQueryResponseType, &ack)
+ if err != nil {
+ s.logger.Printf("[ERR] serf: failed to format ack: %v", err)
+ } else {
+ addr := net.UDPAddr{IP: query.Addr, Port: int(query.Port)}
+ if err := s.memberlist.SendTo(&addr, raw); err != nil {
+ s.logger.Printf("[ERR] serf: failed to send ack: %v", err)
+ }
+ }
+ }
+
+ if s.config.EventCh != nil {
+ s.config.EventCh <- &Query{
+ LTime: query.LTime,
+ Name: query.Name,
+ Payload: query.Payload,
+ serf: s,
+ id: query.ID,
+ addr: query.Addr,
+ port: query.Port,
+ deadline: time.Now().Add(query.Timeout),
+ }
+ }
+ return rebroadcast
+}
+
+// handleResponse is called when a query response is
+// received.
+func (s *Serf) handleQueryResponse(resp *messageQueryResponse) {
+ // Look for a corresponding QueryResponse
+ s.queryLock.RLock()
+ query, ok := s.queryResponse[resp.LTime]
+ s.queryLock.RUnlock()
+ if !ok {
+ s.logger.Printf("[WARN] serf: reply for non-running query (LTime: %d, ID: %d) From: %s",
+ resp.LTime, resp.ID, resp.From)
+ return
+ }
+
+ // Verify the ID matches
+ if query.id != resp.ID {
+ s.logger.Printf("[WARN] serf: query reply ID mismatch (Local: %d, Response: %d)",
+ query.id, resp.ID)
+ return
+ }
+
+ // Check if the query is closed
+ if query.Finished() {
+ return
+ }
+
+ // Process each type of response
+ if resp.Ack() {
+ metrics.IncrCounter([]string{"serf", "query_acks"}, 1)
+ select {
+ case query.ackCh <- resp.From:
+ default:
+ s.logger.Printf("[WARN] serf: Failed to delivery query ack, dropping")
+ }
+ } else {
+ metrics.IncrCounter([]string{"serf", "query_responses"}, 1)
+ select {
+ case query.respCh <- NodeResponse{From: resp.From, Payload: resp.Payload}:
+ default:
+ s.logger.Printf("[WARN] serf: Failed to delivery query response, dropping")
+ }
+ }
+}
+
+// handleNodeConflict is invoked when a join detects a conflict over a name.
+// This means two different nodes (IP/Port) are claiming the same name. Memberlist
+// will reject the "new" node mapping, but we can still be notified
+func (s *Serf) handleNodeConflict(existing, other *memberlist.Node) {
+ // Log a basic warning if the node is not us...
+ if existing.Name != s.config.NodeName {
+ s.logger.Printf("[WARN] serf: Name conflict for '%s' both %s:%d and %s:%d are claiming",
+ existing.Name, existing.Addr, existing.Port, other.Addr, other.Port)
+ return
+ }
+
+ // The current node is conflicting! This is an error
+ s.logger.Printf("[ERR] serf: Node name conflicts with another node at %s:%d. Names must be unique! (Resolution enabled: %v)",
+ other.Addr, other.Port, s.config.EnableNameConflictResolution)
+
+ // If automatic resolution is enabled, kick off the resolution
+ if s.config.EnableNameConflictResolution {
+ go s.resolveNodeConflict()
+ }
+}
+
+// resolveNodeConflict is used to determine which node should remain during
+// a name conflict. This is done by running an internal query.
+func (s *Serf) resolveNodeConflict() {
+ // Get the local node
+ local := s.memberlist.LocalNode()
+
+ // Start a name resolution query
+ qName := internalQueryName(conflictQuery)
+ payload := []byte(s.config.NodeName)
+ resp, err := s.Query(qName, payload, nil)
+ if err != nil {
+ s.logger.Printf("[ERR] serf: Failed to start name resolution query: %v", err)
+ return
+ }
+
+ // Counter to determine winner
+ var responses, matching int
+
+ // Gather responses
+ respCh := resp.ResponseCh()
+ for r := range respCh {
+ // Decode the response
+ if len(r.Payload) < 1 || messageType(r.Payload[0]) != messageConflictResponseType {
+ s.logger.Printf("[ERR] serf: Invalid conflict query response type: %v", r.Payload)
+ continue
+ }
+ var member Member
+ if err := decodeMessage(r.Payload[1:], &member); err != nil {
+ s.logger.Printf("[ERR] serf: Failed to decode conflict query response: %v", err)
+ continue
+ }
+
+ // Update the counters
+ responses++
+ if bytes.Equal(member.Addr, local.Addr) && member.Port == local.Port {
+ matching++
+ }
+ }
+
+ // Query over, determine if we should live
+ majority := (responses / 2) + 1
+ if matching >= majority {
+ s.logger.Printf("[INFO] serf: majority in name conflict resolution [%d / %d]",
+ matching, responses)
+ return
+ }
+
+ // Since we lost the vote, we need to exit
+ s.logger.Printf("[WARN] serf: minority in name conflict resolution, quiting [%d / %d]",
+ matching, responses)
+ if err := s.Shutdown(); err != nil {
+ s.logger.Printf("[ERR] serf: Failed to shutdown: %v", err)
+ }
+}
+
+// handleReap periodically reaps the list of failed and left members.
+func (s *Serf) handleReap() {
+ for {
+ select {
+ case <-time.After(s.config.ReapInterval):
+ s.memberLock.Lock()
+ s.failedMembers = s.reap(s.failedMembers, s.config.ReconnectTimeout)
+ s.leftMembers = s.reap(s.leftMembers, s.config.TombstoneTimeout)
+ s.memberLock.Unlock()
+ case <-s.shutdownCh:
+ return
+ }
+ }
+}
+
+// handleReconnect attempts to reconnect to recently failed nodes
+// on configured intervals.
+func (s *Serf) handleReconnect() {
+ for {
+ select {
+ case <-time.After(s.config.ReconnectInterval):
+ s.reconnect()
+ case <-s.shutdownCh:
+ return
+ }
+ }
+}
+
+// reap is called with a list of old members and a timeout, and removes
+// members that have exceeded the timeout. The members are removed from
+// both the old list and the members itself. Locking is left to the caller.
+func (s *Serf) reap(old []*memberState, timeout time.Duration) []*memberState {
+ now := time.Now()
+ n := len(old)
+ for i := 0; i < n; i++ {
+ m := old[i]
+
+ // Skip if the timeout is not yet reached
+ if now.Sub(m.leaveTime) <= timeout {
+ continue
+ }
+
+ // Delete from the list
+ old[i], old[n-1] = old[n-1], nil
+ old = old[:n-1]
+ n--
+ i--
+
+ // Delete from members
+ delete(s.members, m.Name)
+
+ // Tell the coordinate client the node has gone away and delete
+ // its cached coordinates.
+ if !s.config.DisableCoordinates {
+ s.coordClient.ForgetNode(m.Name)
+
+ s.coordCacheLock.Lock()
+ delete(s.coordCache, m.Name)
+ s.coordCacheLock.Unlock()
+ }
+
+ // Send an event along
+ s.logger.Printf("[INFO] serf: EventMemberReap: %s", m.Name)
+ if s.config.EventCh != nil {
+ s.config.EventCh <- MemberEvent{
+ Type: EventMemberReap,
+ Members: []Member{m.Member},
+ }
+ }
+ }
+
+ return old
+}
+
+// reconnect attempts to reconnect to recently fail nodes.
+func (s *Serf) reconnect() {
+ s.memberLock.RLock()
+
+ // Nothing to do if there are no failed members
+ n := len(s.failedMembers)
+ if n == 0 {
+ s.memberLock.RUnlock()
+ return
+ }
+
+ // Probability we should attempt to reconect is given
+ // by num failed / (num members - num failed - num left)
+ // This means that we probabilistically expect the cluster
+ // to attempt to connect to each failed member once per
+ // reconnect interval
+ numFailed := float32(len(s.failedMembers))
+ numAlive := float32(len(s.members) - len(s.failedMembers) - len(s.leftMembers))
+ if numAlive == 0 {
+ numAlive = 1 // guard against zero divide
+ }
+ prob := numFailed / numAlive
+ if rand.Float32() > prob {
+ s.memberLock.RUnlock()
+ s.logger.Printf("[DEBUG] serf: forgoing reconnect for random throttling")
+ return
+ }
+
+ // Select a random member to try and join
+ idx := int(rand.Uint32() % uint32(n))
+ mem := s.failedMembers[idx]
+ s.memberLock.RUnlock()
+
+ // Format the addr
+ addr := net.UDPAddr{IP: mem.Addr, Port: int(mem.Port)}
+ s.logger.Printf("[INFO] serf: attempting reconnect to %v %s", mem.Name, addr.String())
+
+ // Attempt to join at the memberlist level
+ s.memberlist.Join([]string{addr.String()})
+}
+
+// checkQueueDepth periodically checks the size of a queue to see if
+// it is too large
+func (s *Serf) checkQueueDepth(name string, queue *memberlist.TransmitLimitedQueue) {
+ for {
+ select {
+ case <-time.After(time.Second):
+ numq := queue.NumQueued()
+ metrics.AddSample([]string{"serf", "queue", name}, float32(numq))
+ if numq >= s.config.QueueDepthWarning {
+ s.logger.Printf("[WARN] serf: %s queue depth: %d", name, numq)
+ }
+ if numq > s.config.MaxQueueDepth {
+ s.logger.Printf("[WARN] serf: %s queue depth (%d) exceeds limit (%d), dropping messages!",
+ name, numq, s.config.MaxQueueDepth)
+ queue.Prune(s.config.MaxQueueDepth)
+ }
+ case <-s.shutdownCh:
+ return
+ }
+ }
+}
+
+// removeOldMember is used to remove an old member from a list of old
+// members.
+func removeOldMember(old []*memberState, name string) []*memberState {
+ for i, m := range old {
+ if m.Name == name {
+ n := len(old)
+ old[i], old[n-1] = old[n-1], nil
+ return old[:n-1]
+ }
+ }
+
+ return old
+}
+
+// recentIntent checks the recent intent buffer for a matching
+// entry for a given node, and either returns the message or nil
+func recentIntent(recent []nodeIntent, node string) (intent *nodeIntent) {
+ for i := 0; i < len(recent); i++ {
+ // Break fast if we hit a zero entry
+ if recent[i].LTime == 0 {
+ break
+ }
+
+ // Check for a node match
+ if recent[i].Node == node {
+ // Take the most recent entry
+ if intent == nil || recent[i].LTime > intent.LTime {
+ intent = &recent[i]
+ }
+ }
+ }
+ return
+}
+
+// handleRejoin attempts to reconnect to previously known alive nodes
+func (s *Serf) handleRejoin(previous []*PreviousNode) {
+ for _, prev := range previous {
+ // Do not attempt to join ourself
+ if prev.Name == s.config.NodeName {
+ continue
+ }
+
+ s.logger.Printf("[INFO] serf: Attempting re-join to previously known node: %s", prev)
+ _, err := s.memberlist.Join([]string{prev.Addr})
+ if err == nil {
+ s.logger.Printf("[INFO] serf: Re-joined to previously known node: %s", prev)
+ return
+ }
+ }
+ s.logger.Printf("[WARN] serf: Failed to re-join any previously known node")
+}
+
+// encodeTags is used to encode a tag map
+func (s *Serf) encodeTags(tags map[string]string) []byte {
+ // Support role-only backwards compatibility
+ if s.ProtocolVersion() < 3 {
+ role := tags["role"]
+ return []byte(role)
+ }
+
+ // Use a magic byte prefix and msgpack encode the tags
+ var buf bytes.Buffer
+ buf.WriteByte(tagMagicByte)
+ enc := codec.NewEncoder(&buf, &codec.MsgpackHandle{})
+ if err := enc.Encode(tags); err != nil {
+ panic(fmt.Sprintf("Failed to encode tags: %v", err))
+ }
+ return buf.Bytes()
+}
+
+// decodeTags is used to decode a tag map
+func (s *Serf) decodeTags(buf []byte) map[string]string {
+ tags := make(map[string]string)
+
+ // Backwards compatibility mode
+ if len(buf) == 0 || buf[0] != tagMagicByte {
+ tags["role"] = string(buf)
+ return tags
+ }
+
+ // Decode the tags
+ r := bytes.NewReader(buf[1:])
+ dec := codec.NewDecoder(r, &codec.MsgpackHandle{})
+ if err := dec.Decode(&tags); err != nil {
+ s.logger.Printf("[ERR] serf: Failed to decode tags: %v", err)
+ }
+ return tags
+}
+
+// Stats is used to provide operator debugging information
+func (s *Serf) Stats() map[string]string {
+ toString := func(v uint64) string {
+ return strconv.FormatUint(v, 10)
+ }
+ stats := map[string]string{
+ "members": toString(uint64(len(s.members))),
+ "failed": toString(uint64(len(s.failedMembers))),
+ "left": toString(uint64(len(s.leftMembers))),
+ "member_time": toString(uint64(s.clock.Time())),
+ "event_time": toString(uint64(s.eventClock.Time())),
+ "query_time": toString(uint64(s.queryClock.Time())),
+ "intent_queue": toString(uint64(s.broadcasts.NumQueued())),
+ "event_queue": toString(uint64(s.eventBroadcasts.NumQueued())),
+ "query_queue": toString(uint64(s.queryBroadcasts.NumQueued())),
+ "encrypted": fmt.Sprintf("%v", s.EncryptionEnabled()),
+ }
+ return stats
+}
+
+// WriteKeyringFile will serialize the current keyring and save it to a file.
+func (s *Serf) writeKeyringFile() error {
+ if len(s.config.KeyringFile) == 0 {
+ return nil
+ }
+
+ keyring := s.config.MemberlistConfig.Keyring
+ keysRaw := keyring.GetKeys()
+ keysEncoded := make([]string, len(keysRaw))
+
+ for i, key := range keysRaw {
+ keysEncoded[i] = base64.StdEncoding.EncodeToString(key)
+ }
+
+ encodedKeys, err := json.MarshalIndent(keysEncoded, "", " ")
+ if err != nil {
+ return fmt.Errorf("Failed to encode keys: %s", err)
+ }
+
+ // Use 0600 for permissions because key data is sensitive
+ if err = ioutil.WriteFile(s.config.KeyringFile, encodedKeys, 0600); err != nil {
+ return fmt.Errorf("Failed to write keyring file: %s", err)
+ }
+
+ // Success!
+ return nil
+}
+
+// GetCoordinate returns the network coordinate of the local node.
+func (s *Serf) GetCoordinate() (*coordinate.Coordinate, error) {
+ if !s.config.DisableCoordinates {
+ return s.coordClient.GetCoordinate(), nil
+ }
+
+ return nil, fmt.Errorf("Coordinates are disabled")
+}
+
+// GetCachedCoordinate returns the network coordinate for the node with the given
+// name. This will only be valid if DisableCoordinates is set to false.
+func (s *Serf) GetCachedCoordinate(name string) (coord *coordinate.Coordinate, ok bool) {
+ if !s.config.DisableCoordinates {
+ s.coordCacheLock.RLock()
+ defer s.coordCacheLock.RUnlock()
+ if coord, ok = s.coordCache[name]; ok {
+ return coord, true
+ }
+
+ return nil, false
+ }
+
+ return nil, false
+}
+
+// NumNodes returns the number of nodes in the serf cluster, regardless of
+// their health or status.
+func (s *Serf) NumNodes() (numNodes int) {
+ s.memberLock.RLock()
+ numNodes = len(s.members)
+ s.memberLock.RUnlock()
+
+ return numNodes
+}
diff --git a/vendor/github.com/hashicorp/serf/serf/snapshot.go b/vendor/github.com/hashicorp/serf/serf/snapshot.go
new file mode 100644
index 0000000..44f8a51
--- /dev/null
+++ b/vendor/github.com/hashicorp/serf/serf/snapshot.go
@@ -0,0 +1,560 @@
+package serf
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "log"
+ "math/rand"
+ "net"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/armon/go-metrics"
+ "github.com/hashicorp/serf/coordinate"
+)
+
+/*
+Serf supports using a "snapshot" file that contains various
+transactional data that is used to help Serf recover quickly
+and gracefully from a failure. We append member events, as well
+as the latest clock values to the file during normal operation,
+and periodically checkpoint and roll over the file. During a restore,
+we can replay the various member events to recall a list of known
+nodes to re-join, as well as restore our clock values to avoid replaying
+old events.
+*/
+
+const flushInterval = 500 * time.Millisecond
+const clockUpdateInterval = 500 * time.Millisecond
+const coordinateUpdateInterval = 60 * time.Second
+const tmpExt = ".compact"
+
+// Snapshotter is responsible for ingesting events and persisting
+// them to disk, and providing a recovery mechanism at start time.
+type Snapshotter struct {
+ aliveNodes map[string]string
+ clock *LamportClock
+ coordClient *coordinate.Client
+ fh *os.File
+ buffered *bufio.Writer
+ inCh <-chan Event
+ lastFlush time.Time
+ lastClock LamportTime
+ lastEventClock LamportTime
+ lastQueryClock LamportTime
+ leaveCh chan struct{}
+ leaving bool
+ logger *log.Logger
+ maxSize int64
+ path string
+ offset int64
+ outCh chan<- Event
+ rejoinAfterLeave bool
+ shutdownCh <-chan struct{}
+ waitCh chan struct{}
+}
+
+// PreviousNode is used to represent the previously known alive nodes
+type PreviousNode struct {
+ Name string
+ Addr string
+}
+
+func (p PreviousNode) String() string {
+ return fmt.Sprintf("%s: %s", p.Name, p.Addr)
+}
+
+// NewSnapshotter creates a new Snapshotter that records events up to a
+// max byte size before rotating the file. It can also be used to
+// recover old state. Snapshotter works by reading an event channel it returns,
+// passing through to an output channel, and persisting relevant events to disk.
+// Setting rejoinAfterLeave makes leave not clear the state, and can be used
+// if you intend to rejoin the same cluster after a leave.
+func NewSnapshotter(path string,
+ maxSize int,
+ rejoinAfterLeave bool,
+ logger *log.Logger,
+ clock *LamportClock,
+ coordClient *coordinate.Client,
+ outCh chan<- Event,
+ shutdownCh <-chan struct{}) (chan<- Event, *Snapshotter, error) {
+ inCh := make(chan Event, 1024)
+
+ // Try to open the file
+ fh, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0755)
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to open snapshot: %v", err)
+ }
+
+ // Determine the offset
+ info, err := fh.Stat()
+ if err != nil {
+ fh.Close()
+ return nil, nil, fmt.Errorf("failed to stat snapshot: %v", err)
+ }
+ offset := info.Size()
+
+ // Create the snapshotter
+ snap := &Snapshotter{
+ aliveNodes: make(map[string]string),
+ clock: clock,
+ coordClient: coordClient,
+ fh: fh,
+ buffered: bufio.NewWriter(fh),
+ inCh: inCh,
+ lastClock: 0,
+ lastEventClock: 0,
+ lastQueryClock: 0,
+ leaveCh: make(chan struct{}),
+ logger: logger,
+ maxSize: int64(maxSize),
+ path: path,
+ offset: offset,
+ outCh: outCh,
+ rejoinAfterLeave: rejoinAfterLeave,
+ shutdownCh: shutdownCh,
+ waitCh: make(chan struct{}),
+ }
+
+ // Recover the last known state
+ if err := snap.replay(); err != nil {
+ fh.Close()
+ return nil, nil, err
+ }
+
+ // Start handling new commands
+ go snap.stream()
+ return inCh, snap, nil
+}
+
+// LastClock returns the last known clock time
+func (s *Snapshotter) LastClock() LamportTime {
+ return s.lastClock
+}
+
+// LastEventClock returns the last known event clock time
+func (s *Snapshotter) LastEventClock() LamportTime {
+ return s.lastEventClock
+}
+
+// LastQueryClock returns the last known query clock time
+func (s *Snapshotter) LastQueryClock() LamportTime {
+ return s.lastQueryClock
+}
+
+// AliveNodes returns the last known alive nodes
+func (s *Snapshotter) AliveNodes() []*PreviousNode {
+ // Copy the previously known
+ previous := make([]*PreviousNode, 0, len(s.aliveNodes))
+ for name, addr := range s.aliveNodes {
+ previous = append(previous, &PreviousNode{name, addr})
+ }
+
+ // Randomize the order, prevents hot shards
+ for i := range previous {
+ j := rand.Intn(i + 1)
+ previous[i], previous[j] = previous[j], previous[i]
+ }
+ return previous
+}
+
+// Wait is used to wait until the snapshotter finishes shut down
+func (s *Snapshotter) Wait() {
+ <-s.waitCh
+}
+
+// Leave is used to remove known nodes to prevent a restart from
+// causing a join. Otherwise nodes will re-join after leaving!
+func (s *Snapshotter) Leave() {
+ select {
+ case s.leaveCh <- struct{}{}:
+ case <-s.shutdownCh:
+ }
+}
+
+// stream is a long running routine that is used to handle events
+func (s *Snapshotter) stream() {
+ clockTicker := time.NewTicker(clockUpdateInterval)
+ defer clockTicker.Stop()
+
+ coordinateTicker := time.NewTicker(coordinateUpdateInterval)
+ defer coordinateTicker.Stop()
+
+ for {
+ select {
+ case <-s.leaveCh:
+ s.leaving = true
+
+ // If we plan to re-join, keep our state
+ if !s.rejoinAfterLeave {
+ s.aliveNodes = make(map[string]string)
+ }
+ s.tryAppend("leave\n")
+ if err := s.buffered.Flush(); err != nil {
+ s.logger.Printf("[ERR] serf: failed to flush leave to snapshot: %v", err)
+ }
+ if err := s.fh.Sync(); err != nil {
+ s.logger.Printf("[ERR] serf: failed to sync leave to snapshot: %v", err)
+ }
+
+ case e := <-s.inCh:
+ // Forward the event immediately
+ if s.outCh != nil {
+ s.outCh <- e
+ }
+
+ // Stop recording events after a leave is issued
+ if s.leaving {
+ continue
+ }
+ switch typed := e.(type) {
+ case MemberEvent:
+ s.processMemberEvent(typed)
+ case UserEvent:
+ s.processUserEvent(typed)
+ case *Query:
+ s.processQuery(typed)
+ default:
+ s.logger.Printf("[ERR] serf: Unknown event to snapshot: %#v", e)
+ }
+
+ case <-clockTicker.C:
+ s.updateClock()
+
+ case <-coordinateTicker.C:
+ s.updateCoordinate()
+
+ case <-s.shutdownCh:
+ if err := s.buffered.Flush(); err != nil {
+ s.logger.Printf("[ERR] serf: failed to flush snapshot: %v", err)
+ }
+ if err := s.fh.Sync(); err != nil {
+ s.logger.Printf("[ERR] serf: failed to sync snapshot: %v", err)
+ }
+ s.fh.Close()
+ close(s.waitCh)
+ return
+ }
+ }
+}
+
+// processMemberEvent is used to handle a single member event
+func (s *Snapshotter) processMemberEvent(e MemberEvent) {
+ switch e.Type {
+ case EventMemberJoin:
+ for _, mem := range e.Members {
+ addr := net.TCPAddr{IP: mem.Addr, Port: int(mem.Port)}
+ s.aliveNodes[mem.Name] = addr.String()
+ s.tryAppend(fmt.Sprintf("alive: %s %s\n", mem.Name, addr.String()))
+ }
+
+ case EventMemberLeave:
+ fallthrough
+ case EventMemberFailed:
+ for _, mem := range e.Members {
+ delete(s.aliveNodes, mem.Name)
+ s.tryAppend(fmt.Sprintf("not-alive: %s\n", mem.Name))
+ }
+ }
+ s.updateClock()
+}
+
+// updateClock is called periodically to check if we should udpate our
+// clock value. This is done after member events but should also be done
+// periodically due to race conditions with join and leave intents
+func (s *Snapshotter) updateClock() {
+ lastSeen := s.clock.Time() - 1
+ if lastSeen > s.lastClock {
+ s.lastClock = lastSeen
+ s.tryAppend(fmt.Sprintf("clock: %d\n", s.lastClock))
+ }
+}
+
+// updateCoordinate is called periodically to write out the current local
+// coordinate. It's safe to call this if coordinates aren't enabled (nil
+// client) and it will be a no-op.
+func (s *Snapshotter) updateCoordinate() {
+ if s.coordClient != nil {
+ encoded, err := json.Marshal(s.coordClient.GetCoordinate())
+ if err != nil {
+ s.logger.Printf("[ERR] serf: Failed to encode coordinate: %v", err)
+ } else {
+ s.tryAppend(fmt.Sprintf("coordinate: %s\n", encoded))
+ }
+ }
+}
+
+// processUserEvent is used to handle a single user event
+func (s *Snapshotter) processUserEvent(e UserEvent) {
+ // Ignore old clocks
+ if e.LTime <= s.lastEventClock {
+ return
+ }
+ s.lastEventClock = e.LTime
+ s.tryAppend(fmt.Sprintf("event-clock: %d\n", e.LTime))
+}
+
+// processQuery is used to handle a single query event
+func (s *Snapshotter) processQuery(q *Query) {
+ // Ignore old clocks
+ if q.LTime <= s.lastQueryClock {
+ return
+ }
+ s.lastQueryClock = q.LTime
+ s.tryAppend(fmt.Sprintf("query-clock: %d\n", q.LTime))
+}
+
+// tryAppend will invoke append line but will not return an error
+func (s *Snapshotter) tryAppend(l string) {
+ if err := s.appendLine(l); err != nil {
+ s.logger.Printf("[ERR] serf: Failed to update snapshot: %v", err)
+ }
+}
+
+// appendLine is used to append a line to the existing log
+func (s *Snapshotter) appendLine(l string) error {
+ defer metrics.MeasureSince([]string{"serf", "snapshot", "appendLine"}, time.Now())
+
+ n, err := s.buffered.WriteString(l)
+ if err != nil {
+ return err
+ }
+
+ // Check if we should flush
+ now := time.Now()
+ if now.Sub(s.lastFlush) > flushInterval {
+ s.lastFlush = now
+ if err := s.buffered.Flush(); err != nil {
+ return err
+ }
+ }
+
+ // Check if a compaction is necessary
+ s.offset += int64(n)
+ if s.offset > s.maxSize {
+ return s.compact()
+ }
+ return nil
+}
+
+// Compact is used to compact the snapshot once it is too large
+func (s *Snapshotter) compact() error {
+ defer metrics.MeasureSince([]string{"serf", "snapshot", "compact"}, time.Now())
+
+ // Try to open the file to new fiel
+ newPath := s.path + tmpExt
+ fh, err := os.OpenFile(newPath, os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0755)
+ if err != nil {
+ return fmt.Errorf("failed to open new snapshot: %v", err)
+ }
+
+ // Create a buffered writer
+ buf := bufio.NewWriter(fh)
+
+ // Write out the live nodes
+ var offset int64
+ for name, addr := range s.aliveNodes {
+ line := fmt.Sprintf("alive: %s %s\n", name, addr)
+ n, err := buf.WriteString(line)
+ if err != nil {
+ fh.Close()
+ return err
+ }
+ offset += int64(n)
+ }
+
+ // Write out the clocks
+ line := fmt.Sprintf("clock: %d\n", s.lastClock)
+ n, err := buf.WriteString(line)
+ if err != nil {
+ fh.Close()
+ return err
+ }
+ offset += int64(n)
+
+ line = fmt.Sprintf("event-clock: %d\n", s.lastEventClock)
+ n, err = buf.WriteString(line)
+ if err != nil {
+ fh.Close()
+ return err
+ }
+ offset += int64(n)
+
+ line = fmt.Sprintf("query-clock: %d\n", s.lastQueryClock)
+ n, err = buf.WriteString(line)
+ if err != nil {
+ fh.Close()
+ return err
+ }
+ offset += int64(n)
+
+ // Write out the coordinate.
+ if s.coordClient != nil {
+ encoded, err := json.Marshal(s.coordClient.GetCoordinate())
+ if err != nil {
+ fh.Close()
+ return err
+ }
+
+ line = fmt.Sprintf("coordinate: %s\n", encoded)
+ n, err = buf.WriteString(line)
+ if err != nil {
+ fh.Close()
+ return err
+ }
+ offset += int64(n)
+ }
+
+ // Flush the new snapshot
+ err = buf.Flush()
+ fh.Close()
+ if err != nil {
+ return fmt.Errorf("failed to flush new snapshot: %v", err)
+ }
+
+ // We now need to swap the old snapshot file with the new snapshot.
+ // Turns out, Windows won't let us rename the files if we have
+ // open handles to them or if the destination already exists. This
+ // means we are forced to close the existing handles, delete the
+ // old file, move the new one in place, and then re-open the file
+ // handles.
+
+ // Flush the existing snapshot, ignoring errors since we will
+ // delete it momentarily.
+ s.buffered.Flush()
+ s.buffered = nil
+
+ // Close the file handle to the old snapshot
+ s.fh.Close()
+ s.fh = nil
+
+ // Delete the old file
+ if err := os.Remove(s.path); err != nil {
+ return fmt.Errorf("failed to remove old snapshot: %v", err)
+ }
+
+ // Move the new file into place
+ if err := os.Rename(newPath, s.path); err != nil {
+ return fmt.Errorf("failed to install new snapshot: %v", err)
+ }
+
+ // Open the new snapshot
+ fh, err = os.OpenFile(s.path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0755)
+ if err != nil {
+ return fmt.Errorf("failed to open snapshot: %v", err)
+ }
+ buf = bufio.NewWriter(fh)
+
+ // Rotate our handles
+ s.fh = fh
+ s.buffered = buf
+ s.offset = offset
+ s.lastFlush = time.Now()
+ return nil
+}
+
+// replay is used to seek to reset our internal state by replaying
+// the snapshot file. It is used at initialization time to read old
+// state
+func (s *Snapshotter) replay() error {
+ // Seek to the beginning
+ if _, err := s.fh.Seek(0, os.SEEK_SET); err != nil {
+ return err
+ }
+
+ // Read each line
+ reader := bufio.NewReader(s.fh)
+ for {
+ line, err := reader.ReadString('\n')
+ if err != nil {
+ break
+ }
+
+ // Skip the newline
+ line = line[:len(line)-1]
+
+ // Switch on the prefix
+ if strings.HasPrefix(line, "alive: ") {
+ info := strings.TrimPrefix(line, "alive: ")
+ addrIdx := strings.LastIndex(info, " ")
+ if addrIdx == -1 {
+ s.logger.Printf("[WARN] serf: Failed to parse address: %v", line)
+ continue
+ }
+ addr := info[addrIdx+1:]
+ name := info[:addrIdx]
+ s.aliveNodes[name] = addr
+
+ } else if strings.HasPrefix(line, "not-alive: ") {
+ name := strings.TrimPrefix(line, "not-alive: ")
+ delete(s.aliveNodes, name)
+
+ } else if strings.HasPrefix(line, "clock: ") {
+ timeStr := strings.TrimPrefix(line, "clock: ")
+ timeInt, err := strconv.ParseUint(timeStr, 10, 64)
+ if err != nil {
+ s.logger.Printf("[WARN] serf: Failed to convert clock time: %v", err)
+ continue
+ }
+ s.lastClock = LamportTime(timeInt)
+
+ } else if strings.HasPrefix(line, "event-clock: ") {
+ timeStr := strings.TrimPrefix(line, "event-clock: ")
+ timeInt, err := strconv.ParseUint(timeStr, 10, 64)
+ if err != nil {
+ s.logger.Printf("[WARN] serf: Failed to convert event clock time: %v", err)
+ continue
+ }
+ s.lastEventClock = LamportTime(timeInt)
+
+ } else if strings.HasPrefix(line, "query-clock: ") {
+ timeStr := strings.TrimPrefix(line, "query-clock: ")
+ timeInt, err := strconv.ParseUint(timeStr, 10, 64)
+ if err != nil {
+ s.logger.Printf("[WARN] serf: Failed to convert query clock time: %v", err)
+ continue
+ }
+ s.lastQueryClock = LamportTime(timeInt)
+
+ } else if strings.HasPrefix(line, "coordinate: ") {
+ if s.coordClient == nil {
+ s.logger.Printf("[WARN] serf: Ignoring snapshot coordinates since they are disabled")
+ continue
+ }
+
+ coordStr := strings.TrimPrefix(line, "coordinate: ")
+ var coord coordinate.Coordinate
+ err := json.Unmarshal([]byte(coordStr), &coord)
+ if err != nil {
+ s.logger.Printf("[WARN] serf: Failed to decode coordinate: %v", err)
+ continue
+ }
+ s.coordClient.SetCoordinate(&coord)
+ } else if line == "leave" {
+ // Ignore a leave if we plan on re-joining
+ if s.rejoinAfterLeave {
+ s.logger.Printf("[INFO] serf: Ignoring previous leave in snapshot")
+ continue
+ }
+ s.aliveNodes = make(map[string]string)
+ s.lastClock = 0
+ s.lastEventClock = 0
+ s.lastQueryClock = 0
+
+ } else if strings.HasPrefix(line, "#") {
+ // Skip comment lines
+
+ } else {
+ s.logger.Printf("[WARN] serf: Unrecognized snapshot line: %v", line)
+ }
+ }
+
+ // Seek to the end
+ if _, err := s.fh.Seek(0, os.SEEK_END); err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/vendor/github.com/imdario/mergo/LICENSE b/vendor/github.com/imdario/mergo/LICENSE
new file mode 100644
index 0000000..6866802
--- /dev/null
+++ b/vendor/github.com/imdario/mergo/LICENSE
@@ -0,0 +1,28 @@
+Copyright (c) 2013 Dario Castañé. All rights reserved.
+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/imdario/mergo/README.md b/vendor/github.com/imdario/mergo/README.md
new file mode 100644
index 0000000..4f0f990
--- /dev/null
+++ b/vendor/github.com/imdario/mergo/README.md
@@ -0,0 +1,122 @@
+# Mergo
+
+A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements.
+
+Also a lovely [comune](http://en.wikipedia.org/wiki/Mergo) (municipality) in the Province of Ancona in the Italian region Marche.
+
+![Mergo dall'alto](http://www.comune.mergo.an.it/Siti/Mergo/Immagini/Foto/mergo_dall_alto.jpg)
+
+## Status
+
+It is ready for production use. It works fine after extensive use in the wild.
+
+[![Build Status][1]][2]
+[![GoDoc](https://godoc.org/github.com/imdario/mergo?status.svg)](https://godoc.org/github.com/imdario/mergo)
+
+[1]: https://travis-ci.org/imdario/mergo.png
+[2]: https://travis-ci.org/imdario/mergo
+
+### Important note
+
+Mergo is intended to assign **only** zero value fields on destination with source value. Since April 6th it works like this. Before it didn't work properly, causing some random overwrites. After some issues and PRs I found it didn't merge as I designed it. Thanks to [imdario/mergo#8](https://github.com/imdario/mergo/pull/8) overwriting functions were added and the wrong behavior was clearly detected.
+
+If you were using Mergo **before** April 6th 2015, please check your project works as intended after updating your local copy with ```go get -u github.com/imdario/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause (I hope it won't!) in existing projects after the change (release 0.2.0).
+
+### Mergo in the wild
+
+- [imdario/zas](https://github.com/imdario/zas)
+- [GoogleCloudPlatform/kubernetes](https://github.com/GoogleCloudPlatform/kubernetes)
+- [soniah/dnsmadeeasy](https://github.com/soniah/dnsmadeeasy)
+- [EagerIO/Stout](https://github.com/EagerIO/Stout)
+- [lynndylanhurley/defsynth-api](https://github.com/lynndylanhurley/defsynth-api)
+- [russross/canvasassignments](https://github.com/russross/canvasassignments)
+- [rdegges/cryptly-api](https://github.com/rdegges/cryptly-api)
+- [casualjim/exeggutor](https://github.com/casualjim/exeggutor)
+- [divshot/gitling](https://github.com/divshot/gitling)
+- [RWJMurphy/gorl](https://github.com/RWJMurphy/gorl)
+- [andrerocker/deploy42](https://github.com/andrerocker/deploy42)
+- [elwinar/rambler](https://github.com/elwinar/rambler)
+- [tmaiaroto/gopartman](https://github.com/tmaiaroto/gopartman)
+- [jfbus/impressionist](https://github.com/jfbus/impressionist)
+- [Jmeyering/zealot](https://github.com/Jmeyering/zealot)
+- [godep-migrator/rigger-host](https://github.com/godep-migrator/rigger-host)
+- [Dronevery/MultiwaySwitch-Go](https://github.com/Dronevery/MultiwaySwitch-Go)
+- [thoas/picfit](https://github.com/thoas/picfit)
+- [mantasmatelis/whooplist-server](https://github.com/mantasmatelis/whooplist-server)
+- [jnuthong/item_search](https://github.com/jnuthong/item_search)
+
+## Installation
+
+ go get github.com/imdario/mergo
+
+ // use in your .go code
+ import (
+ "github.com/imdario/mergo"
+ )
+
+## Usage
+
+You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. Also maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection).
+
+ if err := mergo.Merge(&dst, src); err != nil {
+ // ...
+ }
+
+Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field.
+
+ if err := mergo.Map(&dst, srcMap); err != nil {
+ // ...
+ }
+
+Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values.
+
+More information and examples in [godoc documentation](http://godoc.org/github.com/imdario/mergo).
+
+### Nice example
+
+```go
+package main
+
+import (
+ "fmt"
+ "github.com/imdario/mergo"
+)
+
+type Foo struct {
+ A string
+ B int64
+}
+
+func main() {
+ src := Foo{
+ A: "one",
+ }
+
+ dest := Foo{
+ A: "two",
+ B: 2,
+ }
+
+ mergo.Merge(&dest, src)
+
+ fmt.Println(dest)
+ // Will print
+ // {two 2}
+}
+```
+
+Note: if test are failing due missing package, please execute:
+
+ go get gopkg.in/yaml.v1
+
+## Contact me
+
+If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): [@im_dario](https://twitter.com/im_dario)
+
+## About
+
+Written by [Dario Castañé](http://dario.im).
+
+## License
+
+[BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE).
diff --git a/vendor/github.com/imdario/mergo/doc.go b/vendor/github.com/imdario/mergo/doc.go
new file mode 100644
index 0000000..6e9aa7b
--- /dev/null
+++ b/vendor/github.com/imdario/mergo/doc.go
@@ -0,0 +1,44 @@
+// Copyright 2013 Dario Castañé. All rights reserved.
+// Copyright 2009 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 mergo merges same-type structs and maps by setting default values in zero-value fields.
+
+Mergo won't merge unexported (private) fields but will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection).
+
+Usage
+
+From my own work-in-progress project:
+
+ type networkConfig struct {
+ Protocol string
+ Address string
+ ServerType string `json: "server_type"`
+ Port uint16
+ }
+
+ type FssnConfig struct {
+ Network networkConfig
+ }
+
+ var fssnDefault = FssnConfig {
+ networkConfig {
+ "tcp",
+ "127.0.0.1",
+ "http",
+ 31560,
+ },
+ }
+
+ // Inside a function [...]
+
+ if err := mergo.Merge(&config, fssnDefault); err != nil {
+ log.Fatal(err)
+ }
+
+ // More code [...]
+
+*/
+package mergo
diff --git a/vendor/github.com/imdario/mergo/map.go b/vendor/github.com/imdario/mergo/map.go
new file mode 100644
index 0000000..1ed3d71
--- /dev/null
+++ b/vendor/github.com/imdario/mergo/map.go
@@ -0,0 +1,154 @@
+// Copyright 2014 Dario Castañé. All rights reserved.
+// Copyright 2009 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.
+
+// Based on src/pkg/reflect/deepequal.go from official
+// golang's stdlib.
+
+package mergo
+
+import (
+ "fmt"
+ "reflect"
+ "unicode"
+ "unicode/utf8"
+)
+
+func changeInitialCase(s string, mapper func(rune) rune) string {
+ if s == "" {
+ return s
+ }
+ r, n := utf8.DecodeRuneInString(s)
+ return string(mapper(r)) + s[n:]
+}
+
+func isExported(field reflect.StructField) bool {
+ r, _ := utf8.DecodeRuneInString(field.Name)
+ return r >= 'A' && r <= 'Z'
+}
+
+// Traverses recursively both values, assigning src's fields values to dst.
+// The map argument tracks comparisons that have already been seen, which allows
+// short circuiting on recursive types.
+func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, overwrite bool) (err error) {
+ if dst.CanAddr() {
+ addr := dst.UnsafeAddr()
+ h := 17 * addr
+ seen := visited[h]
+ typ := dst.Type()
+ for p := seen; p != nil; p = p.next {
+ if p.ptr == addr && p.typ == typ {
+ return nil
+ }
+ }
+ // Remember, remember...
+ visited[h] = &visit{addr, typ, seen}
+ }
+ zeroValue := reflect.Value{}
+ switch dst.Kind() {
+ case reflect.Map:
+ dstMap := dst.Interface().(map[string]interface{})
+ for i, n := 0, src.NumField(); i < n; i++ {
+ srcType := src.Type()
+ field := srcType.Field(i)
+ if !isExported(field) {
+ continue
+ }
+ fieldName := field.Name
+ fieldName = changeInitialCase(fieldName, unicode.ToLower)
+ if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v)) || overwrite) {
+ dstMap[fieldName] = src.Field(i).Interface()
+ }
+ }
+ case reflect.Struct:
+ srcMap := src.Interface().(map[string]interface{})
+ for key := range srcMap {
+ srcValue := srcMap[key]
+ fieldName := changeInitialCase(key, unicode.ToUpper)
+ dstElement := dst.FieldByName(fieldName)
+ if dstElement == zeroValue {
+ // We discard it because the field doesn't exist.
+ continue
+ }
+ srcElement := reflect.ValueOf(srcValue)
+ dstKind := dstElement.Kind()
+ srcKind := srcElement.Kind()
+ if srcKind == reflect.Ptr && dstKind != reflect.Ptr {
+ srcElement = srcElement.Elem()
+ srcKind = reflect.TypeOf(srcElement.Interface()).Kind()
+ } else if dstKind == reflect.Ptr {
+ // Can this work? I guess it can't.
+ if srcKind != reflect.Ptr && srcElement.CanAddr() {
+ srcPtr := srcElement.Addr()
+ srcElement = reflect.ValueOf(srcPtr)
+ srcKind = reflect.Ptr
+ }
+ }
+ if !srcElement.IsValid() {
+ continue
+ }
+ if srcKind == dstKind {
+ if err = deepMerge(dstElement, srcElement, visited, depth+1, overwrite); err != nil {
+ return
+ }
+ } else {
+ if srcKind == reflect.Map {
+ if err = deepMap(dstElement, srcElement, visited, depth+1, overwrite); err != nil {
+ return
+ }
+ } else {
+ return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind)
+ }
+ }
+ }
+ }
+ return
+}
+
+// Map sets fields' values in dst from src.
+// src can be a map with string keys or a struct. dst must be the opposite:
+// if src is a map, dst must be a valid pointer to struct. If src is a struct,
+// dst must be map[string]interface{}.
+// It won't merge unexported (private) fields and will do recursively
+// any exported field.
+// If dst is a map, keys will be src fields' names in lower camel case.
+// Missing key in src that doesn't match a field in dst will be skipped. This
+// doesn't apply if dst is a map.
+// This is separated method from Merge because it is cleaner and it keeps sane
+// semantics: merging equal types, mapping different (restricted) types.
+func Map(dst, src interface{}) error {
+ return _map(dst, src, false)
+}
+
+func MapWithOverwrite(dst, src interface{}) error {
+ return _map(dst, src, true)
+}
+
+func _map(dst, src interface{}, overwrite bool) error {
+ var (
+ vDst, vSrc reflect.Value
+ err error
+ )
+ if vDst, vSrc, err = resolveValues(dst, src); err != nil {
+ return err
+ }
+ // To be friction-less, we redirect equal-type arguments
+ // to deepMerge. Only because arguments can be anything.
+ if vSrc.Kind() == vDst.Kind() {
+ return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, overwrite)
+ }
+ switch vSrc.Kind() {
+ case reflect.Struct:
+ if vDst.Kind() != reflect.Map {
+ return ErrExpectedMapAsDestination
+ }
+ case reflect.Map:
+ if vDst.Kind() != reflect.Struct {
+ return ErrExpectedStructAsDestination
+ }
+ default:
+ return ErrNotSupported
+ }
+ return deepMap(vDst, vSrc, make(map[uintptr]*visit), 0, overwrite)
+}
diff --git a/vendor/github.com/imdario/mergo/merge.go b/vendor/github.com/imdario/mergo/merge.go
new file mode 100644
index 0000000..a7dd9d8
--- /dev/null
+++ b/vendor/github.com/imdario/mergo/merge.go
@@ -0,0 +1,120 @@
+// Copyright 2013 Dario Castañé. All rights reserved.
+// Copyright 2009 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.
+
+// Based on src/pkg/reflect/deepequal.go from official
+// golang's stdlib.
+
+package mergo
+
+import (
+ "reflect"
+)
+
+// Traverses recursively both values, assigning src's fields values to dst.
+// The map argument tracks comparisons that have already been seen, which allows
+// short circuiting on recursive types.
+func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, overwrite bool) (err error) {
+ if !src.IsValid() {
+ return
+ }
+ if dst.CanAddr() {
+ addr := dst.UnsafeAddr()
+ h := 17 * addr
+ seen := visited[h]
+ typ := dst.Type()
+ for p := seen; p != nil; p = p.next {
+ if p.ptr == addr && p.typ == typ {
+ return nil
+ }
+ }
+ // Remember, remember...
+ visited[h] = &visit{addr, typ, seen}
+ }
+ switch dst.Kind() {
+ case reflect.Struct:
+ for i, n := 0, dst.NumField(); i < n; i++ {
+ if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, overwrite); err != nil {
+ return
+ }
+ }
+ case reflect.Map:
+ for _, key := range src.MapKeys() {
+ srcElement := src.MapIndex(key)
+ if !srcElement.IsValid() {
+ continue
+ }
+ dstElement := dst.MapIndex(key)
+ switch srcElement.Kind() {
+ case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Slice:
+ if srcElement.IsNil() {
+ continue
+ }
+ fallthrough
+ default:
+ switch reflect.TypeOf(srcElement.Interface()).Kind() {
+ case reflect.Struct:
+ fallthrough
+ case reflect.Ptr:
+ fallthrough
+ case reflect.Map:
+ if err = deepMerge(dstElement, srcElement, visited, depth+1, overwrite); err != nil {
+ return
+ }
+ }
+ }
+ if !isEmptyValue(srcElement) && (overwrite || (!dstElement.IsValid() || isEmptyValue(dst))) {
+ if dst.IsNil() {
+ dst.Set(reflect.MakeMap(dst.Type()))
+ }
+ dst.SetMapIndex(key, srcElement)
+ }
+ }
+ case reflect.Ptr:
+ fallthrough
+ case reflect.Interface:
+ if src.IsNil() {
+ break
+ } else if dst.IsNil() {
+ if dst.CanSet() && (overwrite || isEmptyValue(dst)) {
+ dst.Set(src)
+ }
+ } else if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, overwrite); err != nil {
+ return
+ }
+ default:
+ if dst.CanSet() && !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) {
+ dst.Set(src)
+ }
+ }
+ return
+}
+
+// Merge sets fields' values in dst from src if they have a zero
+// value of their type.
+// dst and src must be valid same-type structs and dst must be
+// a pointer to struct.
+// It won't merge unexported (private) fields and will do recursively
+// any exported field.
+func Merge(dst, src interface{}) error {
+ return merge(dst, src, false)
+}
+
+func MergeWithOverwrite(dst, src interface{}) error {
+ return merge(dst, src, true)
+}
+
+func merge(dst, src interface{}, overwrite bool) error {
+ var (
+ vDst, vSrc reflect.Value
+ err error
+ )
+ if vDst, vSrc, err = resolveValues(dst, src); err != nil {
+ return err
+ }
+ if vDst.Type() != vSrc.Type() {
+ return ErrDifferentArgumentsTypes
+ }
+ return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, overwrite)
+}
diff --git a/vendor/github.com/imdario/mergo/mergo.go b/vendor/github.com/imdario/mergo/mergo.go
new file mode 100644
index 0000000..f8a0991
--- /dev/null
+++ b/vendor/github.com/imdario/mergo/mergo.go
@@ -0,0 +1,90 @@
+// Copyright 2013 Dario Castañé. All rights reserved.
+// Copyright 2009 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.
+
+// Based on src/pkg/reflect/deepequal.go from official
+// golang's stdlib.
+
+package mergo
+
+import (
+ "errors"
+ "reflect"
+)
+
+// Errors reported by Mergo when it finds invalid arguments.
+var (
+ ErrNilArguments = errors.New("src and dst must not be nil")
+ ErrDifferentArgumentsTypes = errors.New("src and dst must be of same type")
+ ErrNotSupported = errors.New("only structs and maps are supported")
+ ErrExpectedMapAsDestination = errors.New("dst was expected to be a map")
+ ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct")
+)
+
+// During deepMerge, must keep track of checks that are
+// in progress. The comparison algorithm assumes that all
+// checks in progress are true when it reencounters them.
+// Visited are stored in a map indexed by 17 * a1 + a2;
+type visit struct {
+ ptr uintptr
+ typ reflect.Type
+ next *visit
+}
+
+// From src/pkg/encoding/json.
+func isEmptyValue(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
+ return v.Len() == 0
+ case reflect.Bool:
+ return !v.Bool()
+ 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.Interface, reflect.Ptr:
+ return v.IsNil()
+ }
+ return false
+}
+
+func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) {
+ if dst == nil || src == nil {
+ err = ErrNilArguments
+ return
+ }
+ vDst = reflect.ValueOf(dst).Elem()
+ if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map {
+ err = ErrNotSupported
+ return
+ }
+ vSrc = reflect.ValueOf(src)
+ // We check if vSrc is a pointer to dereference it.
+ if vSrc.Kind() == reflect.Ptr {
+ vSrc = vSrc.Elem()
+ }
+ return
+}
+
+// Traverses recursively both values, assigning src's fields values to dst.
+// The map argument tracks comparisons that have already been seen, which allows
+// short circuiting on recursive types.
+func deeper(dst, src reflect.Value, visited map[uintptr]*visit, depth int) (err error) {
+ if dst.CanAddr() {
+ addr := dst.UnsafeAddr()
+ h := 17 * addr
+ seen := visited[h]
+ typ := dst.Type()
+ for p := seen; p != nil; p = p.next {
+ if p.ptr == addr && p.typ == typ {
+ return nil
+ }
+ }
+ // Remember, remember...
+ visited[h] = &visit{addr, typ, seen}
+ }
+ return // TODO refactor
+}
diff --git a/vendor/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE
new file mode 100644
index 0000000..5f0d1fb
--- /dev/null
+++ b/vendor/github.com/inconshreveable/mousetrap/LICENSE
@@ -0,0 +1,13 @@
+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
new file mode 100644
index 0000000..7a950d1
--- /dev/null
+++ b/vendor/github.com/inconshreveable/mousetrap/README.md
@@ -0,0 +1,23 @@
+# 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
new file mode 100644
index 0000000..9d2d8a4
--- /dev/null
+++ b/vendor/github.com/inconshreveable/mousetrap/trap_others.go
@@ -0,0 +1,15 @@
+// +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
new file mode 100644
index 0000000..336142a
--- /dev/null
+++ b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go
@@ -0,0 +1,98 @@
+// +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
new file mode 100644
index 0000000..9a28e57
--- /dev/null
+++ b/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
@@ -0,0 +1,46 @@
+// +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/jmespath/go-jmespath/LICENSE b/vendor/github.com/jmespath/go-jmespath/LICENSE
new file mode 100644
index 0000000..b03310a
--- /dev/null
+++ b/vendor/github.com/jmespath/go-jmespath/LICENSE
@@ -0,0 +1,13 @@
+Copyright 2015 James Saryerwinnie
+
+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/jmespath/go-jmespath/README.md b/vendor/github.com/jmespath/go-jmespath/README.md
new file mode 100644
index 0000000..187ef67
--- /dev/null
+++ b/vendor/github.com/jmespath/go-jmespath/README.md
@@ -0,0 +1,7 @@
+# go-jmespath - A JMESPath implementation in Go
+
+[![Build Status](https://img.shields.io/travis/jmespath/go-jmespath.svg)](https://travis-ci.org/jmespath/go-jmespath)
+
+
+
+See http://jmespath.org for more info.
diff --git a/vendor/github.com/jmespath/go-jmespath/api.go b/vendor/github.com/jmespath/go-jmespath/api.go
new file mode 100644
index 0000000..9cfa988
--- /dev/null
+++ b/vendor/github.com/jmespath/go-jmespath/api.go
@@ -0,0 +1,49 @@
+package jmespath
+
+import "strconv"
+
+// JmesPath is the epresentation of a compiled JMES path query. A JmesPath is
+// safe for concurrent use by multiple goroutines.
+type JMESPath struct {
+ ast ASTNode
+ intr *treeInterpreter
+}
+
+// Compile parses a JMESPath expression and returns, if successful, a JMESPath
+// object that can be used to match against data.
+func Compile(expression string) (*JMESPath, error) {
+ parser := NewParser()
+ ast, err := parser.Parse(expression)
+ if err != nil {
+ return nil, err
+ }
+ jmespath := &JMESPath{ast: ast, intr: newInterpreter()}
+ return jmespath, nil
+}
+
+// MustCompile is like Compile but panics if the expression cannot be parsed.
+// It simplifies safe initialization of global variables holding compiled
+// JMESPaths.
+func MustCompile(expression string) *JMESPath {
+ jmespath, err := Compile(expression)
+ if err != nil {
+ panic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error())
+ }
+ return jmespath
+}
+
+// Search evaluates a JMESPath expression against input data and returns the result.
+func (jp *JMESPath) Search(data interface{}) (interface{}, error) {
+ return jp.intr.Execute(jp.ast, data)
+}
+
+// Search evaluates a JMESPath expression against input data and returns the result.
+func Search(expression string, data interface{}) (interface{}, error) {
+ intr := newInterpreter()
+ parser := NewParser()
+ ast, err := parser.Parse(expression)
+ if err != nil {
+ return nil, err
+ }
+ return intr.Execute(ast, data)
+}
diff --git a/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go b/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go
new file mode 100644
index 0000000..1cd2d23
--- /dev/null
+++ b/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go
@@ -0,0 +1,16 @@
+// generated by stringer -type astNodeType; DO NOT EDIT
+
+package jmespath
+
+import "fmt"
+
+const _astNodeType_name = "ASTEmptyASTComparatorASTCurrentNodeASTExpRefASTFunctionExpressionASTFieldASTFilterProjectionASTFlattenASTIdentityASTIndexASTIndexExpressionASTKeyValPairASTLiteralASTMultiSelectHashASTMultiSelectListASTOrExpressionASTAndExpressionASTNotExpressionASTPipeASTProjectionASTSubexpressionASTSliceASTValueProjection"
+
+var _astNodeType_index = [...]uint16{0, 8, 21, 35, 44, 65, 73, 92, 102, 113, 121, 139, 152, 162, 180, 198, 213, 229, 245, 252, 265, 281, 289, 307}
+
+func (i astNodeType) String() string {
+ if i < 0 || i >= astNodeType(len(_astNodeType_index)-1) {
+ return fmt.Sprintf("astNodeType(%d)", i)
+ }
+ return _astNodeType_name[_astNodeType_index[i]:_astNodeType_index[i+1]]
+}
diff --git a/vendor/github.com/jmespath/go-jmespath/functions.go b/vendor/github.com/jmespath/go-jmespath/functions.go
new file mode 100644
index 0000000..9b7cd89
--- /dev/null
+++ b/vendor/github.com/jmespath/go-jmespath/functions.go
@@ -0,0 +1,842 @@
+package jmespath
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+)
+
+type jpFunction func(arguments []interface{}) (interface{}, error)
+
+type jpType string
+
+const (
+ jpUnknown jpType = "unknown"
+ jpNumber jpType = "number"
+ jpString jpType = "string"
+ jpArray jpType = "array"
+ jpObject jpType = "object"
+ jpArrayNumber jpType = "array[number]"
+ jpArrayString jpType = "array[string]"
+ jpExpref jpType = "expref"
+ jpAny jpType = "any"
+)
+
+type functionEntry struct {
+ name string
+ arguments []argSpec
+ handler jpFunction
+ hasExpRef bool
+}
+
+type argSpec struct {
+ types []jpType
+ variadic bool
+}
+
+type byExprString struct {
+ intr *treeInterpreter
+ node ASTNode
+ items []interface{}
+ hasError bool
+}
+
+func (a *byExprString) Len() int {
+ return len(a.items)
+}
+func (a *byExprString) Swap(i, j int) {
+ a.items[i], a.items[j] = a.items[j], a.items[i]
+}
+func (a *byExprString) Less(i, j int) bool {
+ first, err := a.intr.Execute(a.node, a.items[i])
+ if err != nil {
+ a.hasError = true
+ // Return a dummy value.
+ return true
+ }
+ ith, ok := first.(string)
+ if !ok {
+ a.hasError = true
+ return true
+ }
+ second, err := a.intr.Execute(a.node, a.items[j])
+ if err != nil {
+ a.hasError = true
+ // Return a dummy value.
+ return true
+ }
+ jth, ok := second.(string)
+ if !ok {
+ a.hasError = true
+ return true
+ }
+ return ith < jth
+}
+
+type byExprFloat struct {
+ intr *treeInterpreter
+ node ASTNode
+ items []interface{}
+ hasError bool
+}
+
+func (a *byExprFloat) Len() int {
+ return len(a.items)
+}
+func (a *byExprFloat) Swap(i, j int) {
+ a.items[i], a.items[j] = a.items[j], a.items[i]
+}
+func (a *byExprFloat) Less(i, j int) bool {
+ first, err := a.intr.Execute(a.node, a.items[i])
+ if err != nil {
+ a.hasError = true
+ // Return a dummy value.
+ return true
+ }
+ ith, ok := first.(float64)
+ if !ok {
+ a.hasError = true
+ return true
+ }
+ second, err := a.intr.Execute(a.node, a.items[j])
+ if err != nil {
+ a.hasError = true
+ // Return a dummy value.
+ return true
+ }
+ jth, ok := second.(float64)
+ if !ok {
+ a.hasError = true
+ return true
+ }
+ return ith < jth
+}
+
+type functionCaller struct {
+ functionTable map[string]functionEntry
+}
+
+func newFunctionCaller() *functionCaller {
+ caller := &functionCaller{}
+ caller.functionTable = map[string]functionEntry{
+ "length": {
+ name: "length",
+ arguments: []argSpec{
+ {types: []jpType{jpString, jpArray, jpObject}},
+ },
+ handler: jpfLength,
+ },
+ "starts_with": {
+ name: "starts_with",
+ arguments: []argSpec{
+ {types: []jpType{jpString}},
+ {types: []jpType{jpString}},
+ },
+ handler: jpfStartsWith,
+ },
+ "abs": {
+ name: "abs",
+ arguments: []argSpec{
+ {types: []jpType{jpNumber}},
+ },
+ handler: jpfAbs,
+ },
+ "avg": {
+ name: "avg",
+ arguments: []argSpec{
+ {types: []jpType{jpArrayNumber}},
+ },
+ handler: jpfAvg,
+ },
+ "ceil": {
+ name: "ceil",
+ arguments: []argSpec{
+ {types: []jpType{jpNumber}},
+ },
+ handler: jpfCeil,
+ },
+ "contains": {
+ name: "contains",
+ arguments: []argSpec{
+ {types: []jpType{jpArray, jpString}},
+ {types: []jpType{jpAny}},
+ },
+ handler: jpfContains,
+ },
+ "ends_with": {
+ name: "ends_with",
+ arguments: []argSpec{
+ {types: []jpType{jpString}},
+ {types: []jpType{jpString}},
+ },
+ handler: jpfEndsWith,
+ },
+ "floor": {
+ name: "floor",
+ arguments: []argSpec{
+ {types: []jpType{jpNumber}},
+ },
+ handler: jpfFloor,
+ },
+ "map": {
+ name: "amp",
+ arguments: []argSpec{
+ {types: []jpType{jpExpref}},
+ {types: []jpType{jpArray}},
+ },
+ handler: jpfMap,
+ hasExpRef: true,
+ },
+ "max": {
+ name: "max",
+ arguments: []argSpec{
+ {types: []jpType{jpArrayNumber, jpArrayString}},
+ },
+ handler: jpfMax,
+ },
+ "merge": {
+ name: "merge",
+ arguments: []argSpec{
+ {types: []jpType{jpObject}, variadic: true},
+ },
+ handler: jpfMerge,
+ },
+ "max_by": {
+ name: "max_by",
+ arguments: []argSpec{
+ {types: []jpType{jpArray}},
+ {types: []jpType{jpExpref}},
+ },
+ handler: jpfMaxBy,
+ hasExpRef: true,
+ },
+ "sum": {
+ name: "sum",
+ arguments: []argSpec{
+ {types: []jpType{jpArrayNumber}},
+ },
+ handler: jpfSum,
+ },
+ "min": {
+ name: "min",
+ arguments: []argSpec{
+ {types: []jpType{jpArrayNumber, jpArrayString}},
+ },
+ handler: jpfMin,
+ },
+ "min_by": {
+ name: "min_by",
+ arguments: []argSpec{
+ {types: []jpType{jpArray}},
+ {types: []jpType{jpExpref}},
+ },
+ handler: jpfMinBy,
+ hasExpRef: true,
+ },
+ "type": {
+ name: "type",
+ arguments: []argSpec{
+ {types: []jpType{jpAny}},
+ },
+ handler: jpfType,
+ },
+ "keys": {
+ name: "keys",
+ arguments: []argSpec{
+ {types: []jpType{jpObject}},
+ },
+ handler: jpfKeys,
+ },
+ "values": {
+ name: "values",
+ arguments: []argSpec{
+ {types: []jpType{jpObject}},
+ },
+ handler: jpfValues,
+ },
+ "sort": {
+ name: "sort",
+ arguments: []argSpec{
+ {types: []jpType{jpArrayString, jpArrayNumber}},
+ },
+ handler: jpfSort,
+ },
+ "sort_by": {
+ name: "sort_by",
+ arguments: []argSpec{
+ {types: []jpType{jpArray}},
+ {types: []jpType{jpExpref}},
+ },
+ handler: jpfSortBy,
+ hasExpRef: true,
+ },
+ "join": {
+ name: "join",
+ arguments: []argSpec{
+ {types: []jpType{jpString}},
+ {types: []jpType{jpArrayString}},
+ },
+ handler: jpfJoin,
+ },
+ "reverse": {
+ name: "reverse",
+ arguments: []argSpec{
+ {types: []jpType{jpArray, jpString}},
+ },
+ handler: jpfReverse,
+ },
+ "to_array": {
+ name: "to_array",
+ arguments: []argSpec{
+ {types: []jpType{jpAny}},
+ },
+ handler: jpfToArray,
+ },
+ "to_string": {
+ name: "to_string",
+ arguments: []argSpec{
+ {types: []jpType{jpAny}},
+ },
+ handler: jpfToString,
+ },
+ "to_number": {
+ name: "to_number",
+ arguments: []argSpec{
+ {types: []jpType{jpAny}},
+ },
+ handler: jpfToNumber,
+ },
+ "not_null": {
+ name: "not_null",
+ arguments: []argSpec{
+ {types: []jpType{jpAny}, variadic: true},
+ },
+ handler: jpfNotNull,
+ },
+ }
+ return caller
+}
+
+func (e *functionEntry) resolveArgs(arguments []interface{}) ([]interface{}, error) {
+ if len(e.arguments) == 0 {
+ return arguments, nil
+ }
+ if !e.arguments[len(e.arguments)-1].variadic {
+ if len(e.arguments) != len(arguments) {
+ return nil, errors.New("incorrect number of args")
+ }
+ for i, spec := range e.arguments {
+ userArg := arguments[i]
+ err := spec.typeCheck(userArg)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return arguments, nil
+ }
+ if len(arguments) < len(e.arguments) {
+ return nil, errors.New("Invalid arity.")
+ }
+ return arguments, nil
+}
+
+func (a *argSpec) typeCheck(arg interface{}) error {
+ for _, t := range a.types {
+ switch t {
+ case jpNumber:
+ if _, ok := arg.(float64); ok {
+ return nil
+ }
+ case jpString:
+ if _, ok := arg.(string); ok {
+ return nil
+ }
+ case jpArray:
+ if isSliceType(arg) {
+ return nil
+ }
+ case jpObject:
+ if _, ok := arg.(map[string]interface{}); ok {
+ return nil
+ }
+ case jpArrayNumber:
+ if _, ok := toArrayNum(arg); ok {
+ return nil
+ }
+ case jpArrayString:
+ if _, ok := toArrayStr(arg); ok {
+ return nil
+ }
+ case jpAny:
+ return nil
+ case jpExpref:
+ if _, ok := arg.(expRef); ok {
+ return nil
+ }
+ }
+ }
+ return fmt.Errorf("Invalid type for: %v, expected: %#v", arg, a.types)
+}
+
+func (f *functionCaller) CallFunction(name string, arguments []interface{}, intr *treeInterpreter) (interface{}, error) {
+ entry, ok := f.functionTable[name]
+ if !ok {
+ return nil, errors.New("unknown function: " + name)
+ }
+ resolvedArgs, err := entry.resolveArgs(arguments)
+ if err != nil {
+ return nil, err
+ }
+ if entry.hasExpRef {
+ var extra []interface{}
+ extra = append(extra, intr)
+ resolvedArgs = append(extra, resolvedArgs...)
+ }
+ return entry.handler(resolvedArgs)
+}
+
+func jpfAbs(arguments []interface{}) (interface{}, error) {
+ num := arguments[0].(float64)
+ return math.Abs(num), nil
+}
+
+func jpfLength(arguments []interface{}) (interface{}, error) {
+ arg := arguments[0]
+ if c, ok := arg.(string); ok {
+ return float64(utf8.RuneCountInString(c)), nil
+ } else if isSliceType(arg) {
+ v := reflect.ValueOf(arg)
+ return float64(v.Len()), nil
+ } else if c, ok := arg.(map[string]interface{}); ok {
+ return float64(len(c)), nil
+ }
+ return nil, errors.New("could not compute length()")
+}
+
+func jpfStartsWith(arguments []interface{}) (interface{}, error) {
+ search := arguments[0].(string)
+ prefix := arguments[1].(string)
+ return strings.HasPrefix(search, prefix), nil
+}
+
+func jpfAvg(arguments []interface{}) (interface{}, error) {
+ // We've already type checked the value so we can safely use
+ // type assertions.
+ args := arguments[0].([]interface{})
+ length := float64(len(args))
+ numerator := 0.0
+ for _, n := range args {
+ numerator += n.(float64)
+ }
+ return numerator / length, nil
+}
+func jpfCeil(arguments []interface{}) (interface{}, error) {
+ val := arguments[0].(float64)
+ return math.Ceil(val), nil
+}
+func jpfContains(arguments []interface{}) (interface{}, error) {
+ search := arguments[0]
+ el := arguments[1]
+ if searchStr, ok := search.(string); ok {
+ if elStr, ok := el.(string); ok {
+ return strings.Index(searchStr, elStr) != -1, nil
+ }
+ return false, nil
+ }
+ // Otherwise this is a generic contains for []interface{}
+ general := search.([]interface{})
+ for _, item := range general {
+ if item == el {
+ return true, nil
+ }
+ }
+ return false, nil
+}
+func jpfEndsWith(arguments []interface{}) (interface{}, error) {
+ search := arguments[0].(string)
+ suffix := arguments[1].(string)
+ return strings.HasSuffix(search, suffix), nil
+}
+func jpfFloor(arguments []interface{}) (interface{}, error) {
+ val := arguments[0].(float64)
+ return math.Floor(val), nil
+}
+func jpfMap(arguments []interface{}) (interface{}, error) {
+ intr := arguments[0].(*treeInterpreter)
+ exp := arguments[1].(expRef)
+ node := exp.ref
+ arr := arguments[2].([]interface{})
+ mapped := make([]interface{}, 0, len(arr))
+ for _, value := range arr {
+ current, err := intr.Execute(node, value)
+ if err != nil {
+ return nil, err
+ }
+ mapped = append(mapped, current)
+ }
+ return mapped, nil
+}
+func jpfMax(arguments []interface{}) (interface{}, error) {
+ if items, ok := toArrayNum(arguments[0]); ok {
+ if len(items) == 0 {
+ return nil, nil
+ }
+ if len(items) == 1 {
+ return items[0], nil
+ }
+ best := items[0]
+ for _, item := range items[1:] {
+ if item > best {
+ best = item
+ }
+ }
+ return best, nil
+ }
+ // Otherwise we're dealing with a max() of strings.
+ items, _ := toArrayStr(arguments[0])
+ if len(items) == 0 {
+ return nil, nil
+ }
+ if len(items) == 1 {
+ return items[0], nil
+ }
+ best := items[0]
+ for _, item := range items[1:] {
+ if item > best {
+ best = item
+ }
+ }
+ return best, nil
+}
+func jpfMerge(arguments []interface{}) (interface{}, error) {
+ final := make(map[string]interface{})
+ for _, m := range arguments {
+ mapped := m.(map[string]interface{})
+ for key, value := range mapped {
+ final[key] = value
+ }
+ }
+ return final, nil
+}
+func jpfMaxBy(arguments []interface{}) (interface{}, error) {
+ intr := arguments[0].(*treeInterpreter)
+ arr := arguments[1].([]interface{})
+ exp := arguments[2].(expRef)
+ node := exp.ref
+ if len(arr) == 0 {
+ return nil, nil
+ } else if len(arr) == 1 {
+ return arr[0], nil
+ }
+ start, err := intr.Execute(node, arr[0])
+ if err != nil {
+ return nil, err
+ }
+ switch t := start.(type) {
+ case float64:
+ bestVal := t
+ bestItem := arr[0]
+ for _, item := range arr[1:] {
+ result, err := intr.Execute(node, item)
+ if err != nil {
+ return nil, err
+ }
+ current, ok := result.(float64)
+ if !ok {
+ return nil, errors.New("invalid type, must be number")
+ }
+ if current > bestVal {
+ bestVal = current
+ bestItem = item
+ }
+ }
+ return bestItem, nil
+ case string:
+ bestVal := t
+ bestItem := arr[0]
+ for _, item := range arr[1:] {
+ result, err := intr.Execute(node, item)
+ if err != nil {
+ return nil, err
+ }
+ current, ok := result.(string)
+ if !ok {
+ return nil, errors.New("invalid type, must be string")
+ }
+ if current > bestVal {
+ bestVal = current
+ bestItem = item
+ }
+ }
+ return bestItem, nil
+ default:
+ return nil, errors.New("invalid type, must be number of string")
+ }
+}
+func jpfSum(arguments []interface{}) (interface{}, error) {
+ items, _ := toArrayNum(arguments[0])
+ sum := 0.0
+ for _, item := range items {
+ sum += item
+ }
+ return sum, nil
+}
+
+func jpfMin(arguments []interface{}) (interface{}, error) {
+ if items, ok := toArrayNum(arguments[0]); ok {
+ if len(items) == 0 {
+ return nil, nil
+ }
+ if len(items) == 1 {
+ return items[0], nil
+ }
+ best := items[0]
+ for _, item := range items[1:] {
+ if item < best {
+ best = item
+ }
+ }
+ return best, nil
+ }
+ items, _ := toArrayStr(arguments[0])
+ if len(items) == 0 {
+ return nil, nil
+ }
+ if len(items) == 1 {
+ return items[0], nil
+ }
+ best := items[0]
+ for _, item := range items[1:] {
+ if item < best {
+ best = item
+ }
+ }
+ return best, nil
+}
+
+func jpfMinBy(arguments []interface{}) (interface{}, error) {
+ intr := arguments[0].(*treeInterpreter)
+ arr := arguments[1].([]interface{})
+ exp := arguments[2].(expRef)
+ node := exp.ref
+ if len(arr) == 0 {
+ return nil, nil
+ } else if len(arr) == 1 {
+ return arr[0], nil
+ }
+ start, err := intr.Execute(node, arr[0])
+ if err != nil {
+ return nil, err
+ }
+ if t, ok := start.(float64); ok {
+ bestVal := t
+ bestItem := arr[0]
+ for _, item := range arr[1:] {
+ result, err := intr.Execute(node, item)
+ if err != nil {
+ return nil, err
+ }
+ current, ok := result.(float64)
+ if !ok {
+ return nil, errors.New("invalid type, must be number")
+ }
+ if current < bestVal {
+ bestVal = current
+ bestItem = item
+ }
+ }
+ return bestItem, nil
+ } else if t, ok := start.(string); ok {
+ bestVal := t
+ bestItem := arr[0]
+ for _, item := range arr[1:] {
+ result, err := intr.Execute(node, item)
+ if err != nil {
+ return nil, err
+ }
+ current, ok := result.(string)
+ if !ok {
+ return nil, errors.New("invalid type, must be string")
+ }
+ if current < bestVal {
+ bestVal = current
+ bestItem = item
+ }
+ }
+ return bestItem, nil
+ } else {
+ return nil, errors.New("invalid type, must be number of string")
+ }
+}
+func jpfType(arguments []interface{}) (interface{}, error) {
+ arg := arguments[0]
+ if _, ok := arg.(float64); ok {
+ return "number", nil
+ }
+ if _, ok := arg.(string); ok {
+ return "string", nil
+ }
+ if _, ok := arg.([]interface{}); ok {
+ return "array", nil
+ }
+ if _, ok := arg.(map[string]interface{}); ok {
+ return "object", nil
+ }
+ if arg == nil {
+ return "null", nil
+ }
+ if arg == true || arg == false {
+ return "boolean", nil
+ }
+ return nil, errors.New("unknown type")
+}
+func jpfKeys(arguments []interface{}) (interface{}, error) {
+ arg := arguments[0].(map[string]interface{})
+ collected := make([]interface{}, 0, len(arg))
+ for key := range arg {
+ collected = append(collected, key)
+ }
+ return collected, nil
+}
+func jpfValues(arguments []interface{}) (interface{}, error) {
+ arg := arguments[0].(map[string]interface{})
+ collected := make([]interface{}, 0, len(arg))
+ for _, value := range arg {
+ collected = append(collected, value)
+ }
+ return collected, nil
+}
+func jpfSort(arguments []interface{}) (interface{}, error) {
+ if items, ok := toArrayNum(arguments[0]); ok {
+ d := sort.Float64Slice(items)
+ sort.Stable(d)
+ final := make([]interface{}, len(d))
+ for i, val := range d {
+ final[i] = val
+ }
+ return final, nil
+ }
+ // Otherwise we're dealing with sort()'ing strings.
+ items, _ := toArrayStr(arguments[0])
+ d := sort.StringSlice(items)
+ sort.Stable(d)
+ final := make([]interface{}, len(d))
+ for i, val := range d {
+ final[i] = val
+ }
+ return final, nil
+}
+func jpfSortBy(arguments []interface{}) (interface{}, error) {
+ intr := arguments[0].(*treeInterpreter)
+ arr := arguments[1].([]interface{})
+ exp := arguments[2].(expRef)
+ node := exp.ref
+ if len(arr) == 0 {
+ return arr, nil
+ } else if len(arr) == 1 {
+ return arr, nil
+ }
+ start, err := intr.Execute(node, arr[0])
+ if err != nil {
+ return nil, err
+ }
+ if _, ok := start.(float64); ok {
+ sortable := &byExprFloat{intr, node, arr, false}
+ sort.Stable(sortable)
+ if sortable.hasError {
+ return nil, errors.New("error in sort_by comparison")
+ }
+ return arr, nil
+ } else if _, ok := start.(string); ok {
+ sortable := &byExprString{intr, node, arr, false}
+ sort.Stable(sortable)
+ if sortable.hasError {
+ return nil, errors.New("error in sort_by comparison")
+ }
+ return arr, nil
+ } else {
+ return nil, errors.New("invalid type, must be number of string")
+ }
+}
+func jpfJoin(arguments []interface{}) (interface{}, error) {
+ sep := arguments[0].(string)
+ // We can't just do arguments[1].([]string), we have to
+ // manually convert each item to a string.
+ arrayStr := []string{}
+ for _, item := range arguments[1].([]interface{}) {
+ arrayStr = append(arrayStr, item.(string))
+ }
+ return strings.Join(arrayStr, sep), nil
+}
+func jpfReverse(arguments []interface{}) (interface{}, error) {
+ if s, ok := arguments[0].(string); ok {
+ r := []rune(s)
+ for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
+ r[i], r[j] = r[j], r[i]
+ }
+ return string(r), nil
+ }
+ items := arguments[0].([]interface{})
+ length := len(items)
+ reversed := make([]interface{}, length)
+ for i, item := range items {
+ reversed[length-(i+1)] = item
+ }
+ return reversed, nil
+}
+func jpfToArray(arguments []interface{}) (interface{}, error) {
+ if _, ok := arguments[0].([]interface{}); ok {
+ return arguments[0], nil
+ }
+ return arguments[:1:1], nil
+}
+func jpfToString(arguments []interface{}) (interface{}, error) {
+ if v, ok := arguments[0].(string); ok {
+ return v, nil
+ }
+ result, err := json.Marshal(arguments[0])
+ if err != nil {
+ return nil, err
+ }
+ return string(result), nil
+}
+func jpfToNumber(arguments []interface{}) (interface{}, error) {
+ arg := arguments[0]
+ if v, ok := arg.(float64); ok {
+ return v, nil
+ }
+ if v, ok := arg.(string); ok {
+ conv, err := strconv.ParseFloat(v, 64)
+ if err != nil {
+ return nil, nil
+ }
+ return conv, nil
+ }
+ if _, ok := arg.([]interface{}); ok {
+ return nil, nil
+ }
+ if _, ok := arg.(map[string]interface{}); ok {
+ return nil, nil
+ }
+ if arg == nil {
+ return nil, nil
+ }
+ if arg == true || arg == false {
+ return nil, nil
+ }
+ return nil, errors.New("unknown type")
+}
+func jpfNotNull(arguments []interface{}) (interface{}, error) {
+ for _, arg := range arguments {
+ if arg != nil {
+ return arg, nil
+ }
+ }
+ return nil, nil
+}
diff --git a/vendor/github.com/jmespath/go-jmespath/interpreter.go b/vendor/github.com/jmespath/go-jmespath/interpreter.go
new file mode 100644
index 0000000..13c7460
--- /dev/null
+++ b/vendor/github.com/jmespath/go-jmespath/interpreter.go
@@ -0,0 +1,418 @@
+package jmespath
+
+import (
+ "errors"
+ "reflect"
+ "unicode"
+ "unicode/utf8"
+)
+
+/* This is a tree based interpreter. It walks the AST and directly
+ interprets the AST to search through a JSON document.
+*/
+
+type treeInterpreter struct {
+ fCall *functionCaller
+}
+
+func newInterpreter() *treeInterpreter {
+ interpreter := treeInterpreter{}
+ interpreter.fCall = newFunctionCaller()
+ return &interpreter
+}
+
+type expRef struct {
+ ref ASTNode
+}
+
+// Execute takes an ASTNode and input data and interprets the AST directly.
+// It will produce the result of applying the JMESPath expression associated
+// with the ASTNode to the input data "value".
+func (intr *treeInterpreter) Execute(node ASTNode, value interface{}) (interface{}, error) {
+ switch node.nodeType {
+ case ASTComparator:
+ left, err := intr.Execute(node.children[0], value)
+ if err != nil {
+ return nil, err
+ }
+ right, err := intr.Execute(node.children[1], value)
+ if err != nil {
+ return nil, err
+ }
+ switch node.value {
+ case tEQ:
+ return objsEqual(left, right), nil
+ case tNE:
+ return !objsEqual(left, right), nil
+ }
+ leftNum, ok := left.(float64)
+ if !ok {
+ return nil, nil
+ }
+ rightNum, ok := right.(float64)
+ if !ok {
+ return nil, nil
+ }
+ switch node.value {
+ case tGT:
+ return leftNum > rightNum, nil
+ case tGTE:
+ return leftNum >= rightNum, nil
+ case tLT:
+ return leftNum < rightNum, nil
+ case tLTE:
+ return leftNum <= rightNum, nil
+ }
+ case ASTExpRef:
+ return expRef{ref: node.children[0]}, nil
+ case ASTFunctionExpression:
+ resolvedArgs := []interface{}{}
+ for _, arg := range node.children {
+ current, err := intr.Execute(arg, value)
+ if err != nil {
+ return nil, err
+ }
+ resolvedArgs = append(resolvedArgs, current)
+ }
+ return intr.fCall.CallFunction(node.value.(string), resolvedArgs, intr)
+ case ASTField:
+ if m, ok := value.(map[string]interface{}); ok {
+ key := node.value.(string)
+ return m[key], nil
+ }
+ return intr.fieldFromStruct(node.value.(string), value)
+ case ASTFilterProjection:
+ left, err := intr.Execute(node.children[0], value)
+ if err != nil {
+ return nil, nil
+ }
+ sliceType, ok := left.([]interface{})
+ if !ok {
+ if isSliceType(left) {
+ return intr.filterProjectionWithReflection(node, left)
+ }
+ return nil, nil
+ }
+ compareNode := node.children[2]
+ collected := []interface{}{}
+ for _, element := range sliceType {
+ result, err := intr.Execute(compareNode, element)
+ if err != nil {
+ return nil, err
+ }
+ if !isFalse(result) {
+ current, err := intr.Execute(node.children[1], element)
+ if err != nil {
+ return nil, err
+ }
+ if current != nil {
+ collected = append(collected, current)
+ }
+ }
+ }
+ return collected, nil
+ case ASTFlatten:
+ left, err := intr.Execute(node.children[0], value)
+ if err != nil {
+ return nil, nil
+ }
+ sliceType, ok := left.([]interface{})
+ if !ok {
+ // If we can't type convert to []interface{}, there's
+ // a chance this could still work via reflection if we're
+ // dealing with user provided types.
+ if isSliceType(left) {
+ return intr.flattenWithReflection(left)
+ }
+ return nil, nil
+ }
+ flattened := []interface{}{}
+ for _, element := range sliceType {
+ if elementSlice, ok := element.([]interface{}); ok {
+ flattened = append(flattened, elementSlice...)
+ } else if isSliceType(element) {
+ reflectFlat := []interface{}{}
+ v := reflect.ValueOf(element)
+ for i := 0; i < v.Len(); i++ {
+ reflectFlat = append(reflectFlat, v.Index(i).Interface())
+ }
+ flattened = append(flattened, reflectFlat...)
+ } else {
+ flattened = append(flattened, element)
+ }
+ }
+ return flattened, nil
+ case ASTIdentity, ASTCurrentNode:
+ return value, nil
+ case ASTIndex:
+ if sliceType, ok := value.([]interface{}); ok {
+ index := node.value.(int)
+ if index < 0 {
+ index += len(sliceType)
+ }
+ if index < len(sliceType) && index >= 0 {
+ return sliceType[index], nil
+ }
+ return nil, nil
+ }
+ // Otherwise try via reflection.
+ rv := reflect.ValueOf(value)
+ if rv.Kind() == reflect.Slice {
+ index := node.value.(int)
+ if index < 0 {
+ index += rv.Len()
+ }
+ if index < rv.Len() && index >= 0 {
+ v := rv.Index(index)
+ return v.Interface(), nil
+ }
+ }
+ return nil, nil
+ case ASTKeyValPair:
+ return intr.Execute(node.children[0], value)
+ case ASTLiteral:
+ return node.value, nil
+ case ASTMultiSelectHash:
+ if value == nil {
+ return nil, nil
+ }
+ collected := make(map[string]interface{})
+ for _, child := range node.children {
+ current, err := intr.Execute(child, value)
+ if err != nil {
+ return nil, err
+ }
+ key := child.value.(string)
+ collected[key] = current
+ }
+ return collected, nil
+ case ASTMultiSelectList:
+ if value == nil {
+ return nil, nil
+ }
+ collected := []interface{}{}
+ for _, child := range node.children {
+ current, err := intr.Execute(child, value)
+ if err != nil {
+ return nil, err
+ }
+ collected = append(collected, current)
+ }
+ return collected, nil
+ case ASTOrExpression:
+ matched, err := intr.Execute(node.children[0], value)
+ if err != nil {
+ return nil, err
+ }
+ if isFalse(matched) {
+ matched, err = intr.Execute(node.children[1], value)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return matched, nil
+ case ASTAndExpression:
+ matched, err := intr.Execute(node.children[0], value)
+ if err != nil {
+ return nil, err
+ }
+ if isFalse(matched) {
+ return matched, nil
+ }
+ return intr.Execute(node.children[1], value)
+ case ASTNotExpression:
+ matched, err := intr.Execute(node.children[0], value)
+ if err != nil {
+ return nil, err
+ }
+ if isFalse(matched) {
+ return true, nil
+ }
+ return false, nil
+ case ASTPipe:
+ result := value
+ var err error
+ for _, child := range node.children {
+ result, err = intr.Execute(child, result)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return result, nil
+ case ASTProjection:
+ left, err := intr.Execute(node.children[0], value)
+ if err != nil {
+ return nil, err
+ }
+ sliceType, ok := left.([]interface{})
+ if !ok {
+ if isSliceType(left) {
+ return intr.projectWithReflection(node, left)
+ }
+ return nil, nil
+ }
+ collected := []interface{}{}
+ var current interface{}
+ for _, element := range sliceType {
+ current, err = intr.Execute(node.children[1], element)
+ if err != nil {
+ return nil, err
+ }
+ if current != nil {
+ collected = append(collected, current)
+ }
+ }
+ return collected, nil
+ case ASTSubexpression, ASTIndexExpression:
+ left, err := intr.Execute(node.children[0], value)
+ if err != nil {
+ return nil, err
+ }
+ return intr.Execute(node.children[1], left)
+ case ASTSlice:
+ sliceType, ok := value.([]interface{})
+ if !ok {
+ if isSliceType(value) {
+ return intr.sliceWithReflection(node, value)
+ }
+ return nil, nil
+ }
+ parts := node.value.([]*int)
+ sliceParams := make([]sliceParam, 3)
+ for i, part := range parts {
+ if part != nil {
+ sliceParams[i].Specified = true
+ sliceParams[i].N = *part
+ }
+ }
+ return slice(sliceType, sliceParams)
+ case ASTValueProjection:
+ left, err := intr.Execute(node.children[0], value)
+ if err != nil {
+ return nil, nil
+ }
+ mapType, ok := left.(map[string]interface{})
+ if !ok {
+ return nil, nil
+ }
+ values := make([]interface{}, len(mapType))
+ for _, value := range mapType {
+ values = append(values, value)
+ }
+ collected := []interface{}{}
+ for _, element := range values {
+ current, err := intr.Execute(node.children[1], element)
+ if err != nil {
+ return nil, err
+ }
+ if current != nil {
+ collected = append(collected, current)
+ }
+ }
+ return collected, nil
+ }
+ return nil, errors.New("Unknown AST node: " + node.nodeType.String())
+}
+
+func (intr *treeInterpreter) fieldFromStruct(key string, value interface{}) (interface{}, error) {
+ rv := reflect.ValueOf(value)
+ first, n := utf8.DecodeRuneInString(key)
+ fieldName := string(unicode.ToUpper(first)) + key[n:]
+ if rv.Kind() == reflect.Struct {
+ v := rv.FieldByName(fieldName)
+ if !v.IsValid() {
+ return nil, nil
+ }
+ return v.Interface(), nil
+ } else if rv.Kind() == reflect.Ptr {
+ // Handle multiple levels of indirection?
+ if rv.IsNil() {
+ return nil, nil
+ }
+ rv = rv.Elem()
+ v := rv.FieldByName(fieldName)
+ if !v.IsValid() {
+ return nil, nil
+ }
+ return v.Interface(), nil
+ }
+ return nil, nil
+}
+
+func (intr *treeInterpreter) flattenWithReflection(value interface{}) (interface{}, error) {
+ v := reflect.ValueOf(value)
+ flattened := []interface{}{}
+ for i := 0; i < v.Len(); i++ {
+ element := v.Index(i).Interface()
+ if reflect.TypeOf(element).Kind() == reflect.Slice {
+ // Then insert the contents of the element
+ // slice into the flattened slice,
+ // i.e flattened = append(flattened, mySlice...)
+ elementV := reflect.ValueOf(element)
+ for j := 0; j < elementV.Len(); j++ {
+ flattened = append(
+ flattened, elementV.Index(j).Interface())
+ }
+ } else {
+ flattened = append(flattened, element)
+ }
+ }
+ return flattened, nil
+}
+
+func (intr *treeInterpreter) sliceWithReflection(node ASTNode, value interface{}) (interface{}, error) {
+ v := reflect.ValueOf(value)
+ parts := node.value.([]*int)
+ sliceParams := make([]sliceParam, 3)
+ for i, part := range parts {
+ if part != nil {
+ sliceParams[i].Specified = true
+ sliceParams[i].N = *part
+ }
+ }
+ final := []interface{}{}
+ for i := 0; i < v.Len(); i++ {
+ element := v.Index(i).Interface()
+ final = append(final, element)
+ }
+ return slice(final, sliceParams)
+}
+
+func (intr *treeInterpreter) filterProjectionWithReflection(node ASTNode, value interface{}) (interface{}, error) {
+ compareNode := node.children[2]
+ collected := []interface{}{}
+ v := reflect.ValueOf(value)
+ for i := 0; i < v.Len(); i++ {
+ element := v.Index(i).Interface()
+ result, err := intr.Execute(compareNode, element)
+ if err != nil {
+ return nil, err
+ }
+ if !isFalse(result) {
+ current, err := intr.Execute(node.children[1], element)
+ if err != nil {
+ return nil, err
+ }
+ if current != nil {
+ collected = append(collected, current)
+ }
+ }
+ }
+ return collected, nil
+}
+
+func (intr *treeInterpreter) projectWithReflection(node ASTNode, value interface{}) (interface{}, error) {
+ collected := []interface{}{}
+ v := reflect.ValueOf(value)
+ for i := 0; i < v.Len(); i++ {
+ element := v.Index(i).Interface()
+ result, err := intr.Execute(node.children[1], element)
+ if err != nil {
+ return nil, err
+ }
+ if result != nil {
+ collected = append(collected, result)
+ }
+ }
+ return collected, nil
+}
diff --git a/vendor/github.com/jmespath/go-jmespath/lexer.go b/vendor/github.com/jmespath/go-jmespath/lexer.go
new file mode 100644
index 0000000..817900c
--- /dev/null
+++ b/vendor/github.com/jmespath/go-jmespath/lexer.go
@@ -0,0 +1,420 @@
+package jmespath
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+)
+
+type token struct {
+ tokenType tokType
+ value string
+ position int
+ length int
+}
+
+type tokType int
+
+const eof = -1
+
+// Lexer contains information about the expression being tokenized.
+type Lexer struct {
+ expression string // The expression provided by the user.
+ currentPos int // The current position in the string.
+ lastWidth int // The width of the current rune. This
+ buf bytes.Buffer // Internal buffer used for building up values.
+}
+
+// SyntaxError is the main error used whenever a lexing or parsing error occurs.
+type SyntaxError struct {
+ msg string // Error message displayed to user
+ Expression string // Expression that generated a SyntaxError
+ Offset int // The location in the string where the error occurred
+}
+
+func (e SyntaxError) Error() string {
+ // In the future, it would be good to underline the specific
+ // location where the error occurred.
+ return "SyntaxError: " + e.msg
+}
+
+// HighlightLocation will show where the syntax error occurred.
+// It will place a "^" character on a line below the expression
+// at the point where the syntax error occurred.
+func (e SyntaxError) HighlightLocation() string {
+ return e.Expression + "\n" + strings.Repeat(" ", e.Offset) + "^"
+}
+
+//go:generate stringer -type=tokType
+const (
+ tUnknown tokType = iota
+ tStar
+ tDot
+ tFilter
+ tFlatten
+ tLparen
+ tRparen
+ tLbracket
+ tRbracket
+ tLbrace
+ tRbrace
+ tOr
+ tPipe
+ tNumber
+ tUnquotedIdentifier
+ tQuotedIdentifier
+ tComma
+ tColon
+ tLT
+ tLTE
+ tGT
+ tGTE
+ tEQ
+ tNE
+ tJSONLiteral
+ tStringLiteral
+ tCurrent
+ tExpref
+ tAnd
+ tNot
+ tEOF
+)
+
+var basicTokens = map[rune]tokType{
+ '.': tDot,
+ '*': tStar,
+ ',': tComma,
+ ':': tColon,
+ '{': tLbrace,
+ '}': tRbrace,
+ ']': tRbracket, // tLbracket not included because it could be "[]"
+ '(': tLparen,
+ ')': tRparen,
+ '@': tCurrent,
+}
+
+// Bit mask for [a-zA-Z_] shifted down 64 bits to fit in a single uint64.
+// When using this bitmask just be sure to shift the rune down 64 bits
+// before checking against identifierStartBits.
+const identifierStartBits uint64 = 576460745995190270
+
+// Bit mask for [a-zA-Z0-9], 128 bits -> 2 uint64s.
+var identifierTrailingBits = [2]uint64{287948901175001088, 576460745995190270}
+
+var whiteSpace = map[rune]bool{
+ ' ': true, '\t': true, '\n': true, '\r': true,
+}
+
+func (t token) String() string {
+ return fmt.Sprintf("Token{%+v, %s, %d, %d}",
+ t.tokenType, t.value, t.position, t.length)
+}
+
+// NewLexer creates a new JMESPath lexer.
+func NewLexer() *Lexer {
+ lexer := Lexer{}
+ return &lexer
+}
+
+func (lexer *Lexer) next() rune {
+ if lexer.currentPos >= len(lexer.expression) {
+ lexer.lastWidth = 0
+ return eof
+ }
+ r, w := utf8.DecodeRuneInString(lexer.expression[lexer.currentPos:])
+ lexer.lastWidth = w
+ lexer.currentPos += w
+ return r
+}
+
+func (lexer *Lexer) back() {
+ lexer.currentPos -= lexer.lastWidth
+}
+
+func (lexer *Lexer) peek() rune {
+ t := lexer.next()
+ lexer.back()
+ return t
+}
+
+// tokenize takes an expression and returns corresponding tokens.
+func (lexer *Lexer) tokenize(expression string) ([]token, error) {
+ var tokens []token
+ lexer.expression = expression
+ lexer.currentPos = 0
+ lexer.lastWidth = 0
+loop:
+ for {
+ r := lexer.next()
+ if identifierStartBits&(1<<(uint64(r)-64)) > 0 {
+ t := lexer.consumeUnquotedIdentifier()
+ tokens = append(tokens, t)
+ } else if val, ok := basicTokens[r]; ok {
+ // Basic single char token.
+ t := token{
+ tokenType: val,
+ value: string(r),
+ position: lexer.currentPos - lexer.lastWidth,
+ length: 1,
+ }
+ tokens = append(tokens, t)
+ } else if r == '-' || (r >= '0' && r <= '9') {
+ t := lexer.consumeNumber()
+ tokens = append(tokens, t)
+ } else if r == '[' {
+ t := lexer.consumeLBracket()
+ tokens = append(tokens, t)
+ } else if r == '"' {
+ t, err := lexer.consumeQuotedIdentifier()
+ if err != nil {
+ return tokens, err
+ }
+ tokens = append(tokens, t)
+ } else if r == '\'' {
+ t, err := lexer.consumeRawStringLiteral()
+ if err != nil {
+ return tokens, err
+ }
+ tokens = append(tokens, t)
+ } else if r == '`' {
+ t, err := lexer.consumeLiteral()
+ if err != nil {
+ return tokens, err
+ }
+ tokens = append(tokens, t)
+ } else if r == '|' {
+ t := lexer.matchOrElse(r, '|', tOr, tPipe)
+ tokens = append(tokens, t)
+ } else if r == '<' {
+ t := lexer.matchOrElse(r, '=', tLTE, tLT)
+ tokens = append(tokens, t)
+ } else if r == '>' {
+ t := lexer.matchOrElse(r, '=', tGTE, tGT)
+ tokens = append(tokens, t)
+ } else if r == '!' {
+ t := lexer.matchOrElse(r, '=', tNE, tNot)
+ tokens = append(tokens, t)
+ } else if r == '=' {
+ t := lexer.matchOrElse(r, '=', tEQ, tUnknown)
+ tokens = append(tokens, t)
+ } else if r == '&' {
+ t := lexer.matchOrElse(r, '&', tAnd, tExpref)
+ tokens = append(tokens, t)
+ } else if r == eof {
+ break loop
+ } else if _, ok := whiteSpace[r]; ok {
+ // Ignore whitespace
+ } else {
+ return tokens, lexer.syntaxError(fmt.Sprintf("Unknown char: %s", strconv.QuoteRuneToASCII(r)))
+ }
+ }
+ tokens = append(tokens, token{tEOF, "", len(lexer.expression), 0})
+ return tokens, nil
+}
+
+// Consume characters until the ending rune "r" is reached.
+// If the end of the expression is reached before seeing the
+// terminating rune "r", then an error is returned.
+// If no error occurs then the matching substring is returned.
+// The returned string will not include the ending rune.
+func (lexer *Lexer) consumeUntil(end rune) (string, error) {
+ start := lexer.currentPos
+ current := lexer.next()
+ for current != end && current != eof {
+ if current == '\\' && lexer.peek() != eof {
+ lexer.next()
+ }
+ current = lexer.next()
+ }
+ if lexer.lastWidth == 0 {
+ // Then we hit an EOF so we never reached the closing
+ // delimiter.
+ return "", SyntaxError{
+ msg: "Unclosed delimiter: " + string(end),
+ Expression: lexer.expression,
+ Offset: len(lexer.expression),
+ }
+ }
+ return lexer.expression[start : lexer.currentPos-lexer.lastWidth], nil
+}
+
+func (lexer *Lexer) consumeLiteral() (token, error) {
+ start := lexer.currentPos
+ value, err := lexer.consumeUntil('`')
+ if err != nil {
+ return token{}, err
+ }
+ value = strings.Replace(value, "\\`", "`", -1)
+ return token{
+ tokenType: tJSONLiteral,
+ value: value,
+ position: start,
+ length: len(value),
+ }, nil
+}
+
+func (lexer *Lexer) consumeRawStringLiteral() (token, error) {
+ start := lexer.currentPos
+ currentIndex := start
+ current := lexer.next()
+ for current != '\'' && lexer.peek() != eof {
+ if current == '\\' && lexer.peek() == '\'' {
+ chunk := lexer.expression[currentIndex : lexer.currentPos-1]
+ lexer.buf.WriteString(chunk)
+ lexer.buf.WriteString("'")
+ lexer.next()
+ currentIndex = lexer.currentPos
+ }
+ current = lexer.next()
+ }
+ if lexer.lastWidth == 0 {
+ // Then we hit an EOF so we never reached the closing
+ // delimiter.
+ return token{}, SyntaxError{
+ msg: "Unclosed delimiter: '",
+ Expression: lexer.expression,
+ Offset: len(lexer.expression),
+ }
+ }
+ if currentIndex < lexer.currentPos {
+ lexer.buf.WriteString(lexer.expression[currentIndex : lexer.currentPos-1])
+ }
+ value := lexer.buf.String()
+ // Reset the buffer so it can reused again.
+ lexer.buf.Reset()
+ return token{
+ tokenType: tStringLiteral,
+ value: value,
+ position: start,
+ length: len(value),
+ }, nil
+}
+
+func (lexer *Lexer) syntaxError(msg string) SyntaxError {
+ return SyntaxError{
+ msg: msg,
+ Expression: lexer.expression,
+ Offset: lexer.currentPos - 1,
+ }
+}
+
+// Checks for a two char token, otherwise matches a single character
+// token. This is used whenever a two char token overlaps a single
+// char token, e.g. "||" -> tPipe, "|" -> tOr.
+func (lexer *Lexer) matchOrElse(first rune, second rune, matchedType tokType, singleCharType tokType) token {
+ start := lexer.currentPos - lexer.lastWidth
+ nextRune := lexer.next()
+ var t token
+ if nextRune == second {
+ t = token{
+ tokenType: matchedType,
+ value: string(first) + string(second),
+ position: start,
+ length: 2,
+ }
+ } else {
+ lexer.back()
+ t = token{
+ tokenType: singleCharType,
+ value: string(first),
+ position: start,
+ length: 1,
+ }
+ }
+ return t
+}
+
+func (lexer *Lexer) consumeLBracket() token {
+ // There's three options here:
+ // 1. A filter expression "[?"
+ // 2. A flatten operator "[]"
+ // 3. A bare rbracket "["
+ start := lexer.currentPos - lexer.lastWidth
+ nextRune := lexer.next()
+ var t token
+ if nextRune == '?' {
+ t = token{
+ tokenType: tFilter,
+ value: "[?",
+ position: start,
+ length: 2,
+ }
+ } else if nextRune == ']' {
+ t = token{
+ tokenType: tFlatten,
+ value: "[]",
+ position: start,
+ length: 2,
+ }
+ } else {
+ t = token{
+ tokenType: tLbracket,
+ value: "[",
+ position: start,
+ length: 1,
+ }
+ lexer.back()
+ }
+ return t
+}
+
+func (lexer *Lexer) consumeQuotedIdentifier() (token, error) {
+ start := lexer.currentPos
+ value, err := lexer.consumeUntil('"')
+ if err != nil {
+ return token{}, err
+ }
+ var decoded string
+ asJSON := []byte("\"" + value + "\"")
+ if err := json.Unmarshal([]byte(asJSON), &decoded); err != nil {
+ return token{}, err
+ }
+ return token{
+ tokenType: tQuotedIdentifier,
+ value: decoded,
+ position: start - 1,
+ length: len(decoded),
+ }, nil
+}
+
+func (lexer *Lexer) consumeUnquotedIdentifier() token {
+ // Consume runes until we reach the end of an unquoted
+ // identifier.
+ start := lexer.currentPos - lexer.lastWidth
+ for {
+ r := lexer.next()
+ if r < 0 || r > 128 || identifierTrailingBits[uint64(r)/64]&(1<<(uint64(r)%64)) == 0 {
+ lexer.back()
+ break
+ }
+ }
+ value := lexer.expression[start:lexer.currentPos]
+ return token{
+ tokenType: tUnquotedIdentifier,
+ value: value,
+ position: start,
+ length: lexer.currentPos - start,
+ }
+}
+
+func (lexer *Lexer) consumeNumber() token {
+ // Consume runes until we reach something that's not a number.
+ start := lexer.currentPos - lexer.lastWidth
+ for {
+ r := lexer.next()
+ if r < '0' || r > '9' {
+ lexer.back()
+ break
+ }
+ }
+ value := lexer.expression[start:lexer.currentPos]
+ return token{
+ tokenType: tNumber,
+ value: value,
+ position: start,
+ length: lexer.currentPos - start,
+ }
+}
diff --git a/vendor/github.com/jmespath/go-jmespath/parser.go b/vendor/github.com/jmespath/go-jmespath/parser.go
new file mode 100644
index 0000000..1240a17
--- /dev/null
+++ b/vendor/github.com/jmespath/go-jmespath/parser.go
@@ -0,0 +1,603 @@
+package jmespath
+
+import (
+ "encoding/json"
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+type astNodeType int
+
+//go:generate stringer -type astNodeType
+const (
+ ASTEmpty astNodeType = iota
+ ASTComparator
+ ASTCurrentNode
+ ASTExpRef
+ ASTFunctionExpression
+ ASTField
+ ASTFilterProjection
+ ASTFlatten
+ ASTIdentity
+ ASTIndex
+ ASTIndexExpression
+ ASTKeyValPair
+ ASTLiteral
+ ASTMultiSelectHash
+ ASTMultiSelectList
+ ASTOrExpression
+ ASTAndExpression
+ ASTNotExpression
+ ASTPipe
+ ASTProjection
+ ASTSubexpression
+ ASTSlice
+ ASTValueProjection
+)
+
+// ASTNode represents the abstract syntax tree of a JMESPath expression.
+type ASTNode struct {
+ nodeType astNodeType
+ value interface{}
+ children []ASTNode
+}
+
+func (node ASTNode) String() string {
+ return node.PrettyPrint(0)
+}
+
+// PrettyPrint will pretty print the parsed AST.
+// The AST is an implementation detail and this pretty print
+// function is provided as a convenience method to help with
+// debugging. You should not rely on its output as the internal
+// structure of the AST may change at any time.
+func (node ASTNode) PrettyPrint(indent int) string {
+ spaces := strings.Repeat(" ", indent)
+ output := fmt.Sprintf("%s%s {\n", spaces, node.nodeType)
+ nextIndent := indent + 2
+ if node.value != nil {
+ if converted, ok := node.value.(fmt.Stringer); ok {
+ // Account for things like comparator nodes
+ // that are enums with a String() method.
+ output += fmt.Sprintf("%svalue: %s\n", strings.Repeat(" ", nextIndent), converted.String())
+ } else {
+ output += fmt.Sprintf("%svalue: %#v\n", strings.Repeat(" ", nextIndent), node.value)
+ }
+ }
+ lastIndex := len(node.children)
+ if lastIndex > 0 {
+ output += fmt.Sprintf("%schildren: {\n", strings.Repeat(" ", nextIndent))
+ childIndent := nextIndent + 2
+ for _, elem := range node.children {
+ output += elem.PrettyPrint(childIndent)
+ }
+ }
+ output += fmt.Sprintf("%s}\n", spaces)
+ return output
+}
+
+var bindingPowers = map[tokType]int{
+ tEOF: 0,
+ tUnquotedIdentifier: 0,
+ tQuotedIdentifier: 0,
+ tRbracket: 0,
+ tRparen: 0,
+ tComma: 0,
+ tRbrace: 0,
+ tNumber: 0,
+ tCurrent: 0,
+ tExpref: 0,
+ tColon: 0,
+ tPipe: 1,
+ tOr: 2,
+ tAnd: 3,
+ tEQ: 5,
+ tLT: 5,
+ tLTE: 5,
+ tGT: 5,
+ tGTE: 5,
+ tNE: 5,
+ tFlatten: 9,
+ tStar: 20,
+ tFilter: 21,
+ tDot: 40,
+ tNot: 45,
+ tLbrace: 50,
+ tLbracket: 55,
+ tLparen: 60,
+}
+
+// Parser holds state about the current expression being parsed.
+type Parser struct {
+ expression string
+ tokens []token
+ index int
+}
+
+// NewParser creates a new JMESPath parser.
+func NewParser() *Parser {
+ p := Parser{}
+ return &p
+}
+
+// Parse will compile a JMESPath expression.
+func (p *Parser) Parse(expression string) (ASTNode, error) {
+ lexer := NewLexer()
+ p.expression = expression
+ p.index = 0
+ tokens, err := lexer.tokenize(expression)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ p.tokens = tokens
+ parsed, err := p.parseExpression(0)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ if p.current() != tEOF {
+ return ASTNode{}, p.syntaxError(fmt.Sprintf(
+ "Unexpected token at the end of the expresssion: %s", p.current()))
+ }
+ return parsed, nil
+}
+
+func (p *Parser) parseExpression(bindingPower int) (ASTNode, error) {
+ var err error
+ leftToken := p.lookaheadToken(0)
+ p.advance()
+ leftNode, err := p.nud(leftToken)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ currentToken := p.current()
+ for bindingPower < bindingPowers[currentToken] {
+ p.advance()
+ leftNode, err = p.led(currentToken, leftNode)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ currentToken = p.current()
+ }
+ return leftNode, nil
+}
+
+func (p *Parser) parseIndexExpression() (ASTNode, error) {
+ if p.lookahead(0) == tColon || p.lookahead(1) == tColon {
+ return p.parseSliceExpression()
+ }
+ indexStr := p.lookaheadToken(0).value
+ parsedInt, err := strconv.Atoi(indexStr)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ indexNode := ASTNode{nodeType: ASTIndex, value: parsedInt}
+ p.advance()
+ if err := p.match(tRbracket); err != nil {
+ return ASTNode{}, err
+ }
+ return indexNode, nil
+}
+
+func (p *Parser) parseSliceExpression() (ASTNode, error) {
+ parts := []*int{nil, nil, nil}
+ index := 0
+ current := p.current()
+ for current != tRbracket && index < 3 {
+ if current == tColon {
+ index++
+ p.advance()
+ } else if current == tNumber {
+ parsedInt, err := strconv.Atoi(p.lookaheadToken(0).value)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ parts[index] = &parsedInt
+ p.advance()
+ } else {
+ return ASTNode{}, p.syntaxError(
+ "Expected tColon or tNumber" + ", received: " + p.current().String())
+ }
+ current = p.current()
+ }
+ if err := p.match(tRbracket); err != nil {
+ return ASTNode{}, err
+ }
+ return ASTNode{
+ nodeType: ASTSlice,
+ value: parts,
+ }, nil
+}
+
+func (p *Parser) match(tokenType tokType) error {
+ if p.current() == tokenType {
+ p.advance()
+ return nil
+ }
+ return p.syntaxError("Expected " + tokenType.String() + ", received: " + p.current().String())
+}
+
+func (p *Parser) led(tokenType tokType, node ASTNode) (ASTNode, error) {
+ switch tokenType {
+ case tDot:
+ if p.current() != tStar {
+ right, err := p.parseDotRHS(bindingPowers[tDot])
+ return ASTNode{
+ nodeType: ASTSubexpression,
+ children: []ASTNode{node, right},
+ }, err
+ }
+ p.advance()
+ right, err := p.parseProjectionRHS(bindingPowers[tDot])
+ return ASTNode{
+ nodeType: ASTValueProjection,
+ children: []ASTNode{node, right},
+ }, err
+ case tPipe:
+ right, err := p.parseExpression(bindingPowers[tPipe])
+ return ASTNode{nodeType: ASTPipe, children: []ASTNode{node, right}}, err
+ case tOr:
+ right, err := p.parseExpression(bindingPowers[tOr])
+ return ASTNode{nodeType: ASTOrExpression, children: []ASTNode{node, right}}, err
+ case tAnd:
+ right, err := p.parseExpression(bindingPowers[tAnd])
+ return ASTNode{nodeType: ASTAndExpression, children: []ASTNode{node, right}}, err
+ case tLparen:
+ name := node.value
+ var args []ASTNode
+ for p.current() != tRparen {
+ expression, err := p.parseExpression(0)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ if p.current() == tComma {
+ if err := p.match(tComma); err != nil {
+ return ASTNode{}, err
+ }
+ }
+ args = append(args, expression)
+ }
+ if err := p.match(tRparen); err != nil {
+ return ASTNode{}, err
+ }
+ return ASTNode{
+ nodeType: ASTFunctionExpression,
+ value: name,
+ children: args,
+ }, nil
+ case tFilter:
+ return p.parseFilter(node)
+ case tFlatten:
+ left := ASTNode{nodeType: ASTFlatten, children: []ASTNode{node}}
+ right, err := p.parseProjectionRHS(bindingPowers[tFlatten])
+ return ASTNode{
+ nodeType: ASTProjection,
+ children: []ASTNode{left, right},
+ }, err
+ case tEQ, tNE, tGT, tGTE, tLT, tLTE:
+ right, err := p.parseExpression(bindingPowers[tokenType])
+ if err != nil {
+ return ASTNode{}, err
+ }
+ return ASTNode{
+ nodeType: ASTComparator,
+ value: tokenType,
+ children: []ASTNode{node, right},
+ }, nil
+ case tLbracket:
+ tokenType := p.current()
+ var right ASTNode
+ var err error
+ if tokenType == tNumber || tokenType == tColon {
+ right, err = p.parseIndexExpression()
+ if err != nil {
+ return ASTNode{}, err
+ }
+ return p.projectIfSlice(node, right)
+ }
+ // Otherwise this is a projection.
+ if err := p.match(tStar); err != nil {
+ return ASTNode{}, err
+ }
+ if err := p.match(tRbracket); err != nil {
+ return ASTNode{}, err
+ }
+ right, err = p.parseProjectionRHS(bindingPowers[tStar])
+ if err != nil {
+ return ASTNode{}, err
+ }
+ return ASTNode{
+ nodeType: ASTProjection,
+ children: []ASTNode{node, right},
+ }, nil
+ }
+ return ASTNode{}, p.syntaxError("Unexpected token: " + tokenType.String())
+}
+
+func (p *Parser) nud(token token) (ASTNode, error) {
+ switch token.tokenType {
+ case tJSONLiteral:
+ var parsed interface{}
+ err := json.Unmarshal([]byte(token.value), &parsed)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ return ASTNode{nodeType: ASTLiteral, value: parsed}, nil
+ case tStringLiteral:
+ return ASTNode{nodeType: ASTLiteral, value: token.value}, nil
+ case tUnquotedIdentifier:
+ return ASTNode{
+ nodeType: ASTField,
+ value: token.value,
+ }, nil
+ case tQuotedIdentifier:
+ node := ASTNode{nodeType: ASTField, value: token.value}
+ if p.current() == tLparen {
+ return ASTNode{}, p.syntaxErrorToken("Can't have quoted identifier as function name.", token)
+ }
+ return node, nil
+ case tStar:
+ left := ASTNode{nodeType: ASTIdentity}
+ var right ASTNode
+ var err error
+ if p.current() == tRbracket {
+ right = ASTNode{nodeType: ASTIdentity}
+ } else {
+ right, err = p.parseProjectionRHS(bindingPowers[tStar])
+ }
+ return ASTNode{nodeType: ASTValueProjection, children: []ASTNode{left, right}}, err
+ case tFilter:
+ return p.parseFilter(ASTNode{nodeType: ASTIdentity})
+ case tLbrace:
+ return p.parseMultiSelectHash()
+ case tFlatten:
+ left := ASTNode{
+ nodeType: ASTFlatten,
+ children: []ASTNode{{nodeType: ASTIdentity}},
+ }
+ right, err := p.parseProjectionRHS(bindingPowers[tFlatten])
+ if err != nil {
+ return ASTNode{}, err
+ }
+ return ASTNode{nodeType: ASTProjection, children: []ASTNode{left, right}}, nil
+ case tLbracket:
+ tokenType := p.current()
+ //var right ASTNode
+ if tokenType == tNumber || tokenType == tColon {
+ right, err := p.parseIndexExpression()
+ if err != nil {
+ return ASTNode{}, nil
+ }
+ return p.projectIfSlice(ASTNode{nodeType: ASTIdentity}, right)
+ } else if tokenType == tStar && p.lookahead(1) == tRbracket {
+ p.advance()
+ p.advance()
+ right, err := p.parseProjectionRHS(bindingPowers[tStar])
+ if err != nil {
+ return ASTNode{}, err
+ }
+ return ASTNode{
+ nodeType: ASTProjection,
+ children: []ASTNode{{nodeType: ASTIdentity}, right},
+ }, nil
+ } else {
+ return p.parseMultiSelectList()
+ }
+ case tCurrent:
+ return ASTNode{nodeType: ASTCurrentNode}, nil
+ case tExpref:
+ expression, err := p.parseExpression(bindingPowers[tExpref])
+ if err != nil {
+ return ASTNode{}, err
+ }
+ return ASTNode{nodeType: ASTExpRef, children: []ASTNode{expression}}, nil
+ case tNot:
+ expression, err := p.parseExpression(bindingPowers[tNot])
+ if err != nil {
+ return ASTNode{}, err
+ }
+ return ASTNode{nodeType: ASTNotExpression, children: []ASTNode{expression}}, nil
+ case tLparen:
+ expression, err := p.parseExpression(0)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ if err := p.match(tRparen); err != nil {
+ return ASTNode{}, err
+ }
+ return expression, nil
+ case tEOF:
+ return ASTNode{}, p.syntaxErrorToken("Incomplete expression", token)
+ }
+
+ return ASTNode{}, p.syntaxErrorToken("Invalid token: "+token.tokenType.String(), token)
+}
+
+func (p *Parser) parseMultiSelectList() (ASTNode, error) {
+ var expressions []ASTNode
+ for {
+ expression, err := p.parseExpression(0)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ expressions = append(expressions, expression)
+ if p.current() == tRbracket {
+ break
+ }
+ err = p.match(tComma)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ }
+ err := p.match(tRbracket)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ return ASTNode{
+ nodeType: ASTMultiSelectList,
+ children: expressions,
+ }, nil
+}
+
+func (p *Parser) parseMultiSelectHash() (ASTNode, error) {
+ var children []ASTNode
+ for {
+ keyToken := p.lookaheadToken(0)
+ if err := p.match(tUnquotedIdentifier); err != nil {
+ if err := p.match(tQuotedIdentifier); err != nil {
+ return ASTNode{}, p.syntaxError("Expected tQuotedIdentifier or tUnquotedIdentifier")
+ }
+ }
+ keyName := keyToken.value
+ err := p.match(tColon)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ value, err := p.parseExpression(0)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ node := ASTNode{
+ nodeType: ASTKeyValPair,
+ value: keyName,
+ children: []ASTNode{value},
+ }
+ children = append(children, node)
+ if p.current() == tComma {
+ err := p.match(tComma)
+ if err != nil {
+ return ASTNode{}, nil
+ }
+ } else if p.current() == tRbrace {
+ err := p.match(tRbrace)
+ if err != nil {
+ return ASTNode{}, nil
+ }
+ break
+ }
+ }
+ return ASTNode{
+ nodeType: ASTMultiSelectHash,
+ children: children,
+ }, nil
+}
+
+func (p *Parser) projectIfSlice(left ASTNode, right ASTNode) (ASTNode, error) {
+ indexExpr := ASTNode{
+ nodeType: ASTIndexExpression,
+ children: []ASTNode{left, right},
+ }
+ if right.nodeType == ASTSlice {
+ right, err := p.parseProjectionRHS(bindingPowers[tStar])
+ return ASTNode{
+ nodeType: ASTProjection,
+ children: []ASTNode{indexExpr, right},
+ }, err
+ }
+ return indexExpr, nil
+}
+func (p *Parser) parseFilter(node ASTNode) (ASTNode, error) {
+ var right, condition ASTNode
+ var err error
+ condition, err = p.parseExpression(0)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ if err := p.match(tRbracket); err != nil {
+ return ASTNode{}, err
+ }
+ if p.current() == tFlatten {
+ right = ASTNode{nodeType: ASTIdentity}
+ } else {
+ right, err = p.parseProjectionRHS(bindingPowers[tFilter])
+ if err != nil {
+ return ASTNode{}, err
+ }
+ }
+
+ return ASTNode{
+ nodeType: ASTFilterProjection,
+ children: []ASTNode{node, right, condition},
+ }, nil
+}
+
+func (p *Parser) parseDotRHS(bindingPower int) (ASTNode, error) {
+ lookahead := p.current()
+ if tokensOneOf([]tokType{tQuotedIdentifier, tUnquotedIdentifier, tStar}, lookahead) {
+ return p.parseExpression(bindingPower)
+ } else if lookahead == tLbracket {
+ if err := p.match(tLbracket); err != nil {
+ return ASTNode{}, err
+ }
+ return p.parseMultiSelectList()
+ } else if lookahead == tLbrace {
+ if err := p.match(tLbrace); err != nil {
+ return ASTNode{}, err
+ }
+ return p.parseMultiSelectHash()
+ }
+ return ASTNode{}, p.syntaxError("Expected identifier, lbracket, or lbrace")
+}
+
+func (p *Parser) parseProjectionRHS(bindingPower int) (ASTNode, error) {
+ current := p.current()
+ if bindingPowers[current] < 10 {
+ return ASTNode{nodeType: ASTIdentity}, nil
+ } else if current == tLbracket {
+ return p.parseExpression(bindingPower)
+ } else if current == tFilter {
+ return p.parseExpression(bindingPower)
+ } else if current == tDot {
+ err := p.match(tDot)
+ if err != nil {
+ return ASTNode{}, err
+ }
+ return p.parseDotRHS(bindingPower)
+ } else {
+ return ASTNode{}, p.syntaxError("Error")
+ }
+}
+
+func (p *Parser) lookahead(number int) tokType {
+ return p.lookaheadToken(number).tokenType
+}
+
+func (p *Parser) current() tokType {
+ return p.lookahead(0)
+}
+
+func (p *Parser) lookaheadToken(number int) token {
+ return p.tokens[p.index+number]
+}
+
+func (p *Parser) advance() {
+ p.index++
+}
+
+func tokensOneOf(elements []tokType, token tokType) bool {
+ for _, elem := range elements {
+ if elem == token {
+ return true
+ }
+ }
+ return false
+}
+
+func (p *Parser) syntaxError(msg string) SyntaxError {
+ return SyntaxError{
+ msg: msg,
+ Expression: p.expression,
+ Offset: p.lookaheadToken(0).position,
+ }
+}
+
+// Create a SyntaxError based on the provided token.
+// This differs from syntaxError() which creates a SyntaxError
+// based on the current lookahead token.
+func (p *Parser) syntaxErrorToken(msg string, t token) SyntaxError {
+ return SyntaxError{
+ msg: msg,
+ Expression: p.expression,
+ Offset: t.position,
+ }
+}
diff --git a/vendor/github.com/jmespath/go-jmespath/toktype_string.go b/vendor/github.com/jmespath/go-jmespath/toktype_string.go
new file mode 100644
index 0000000..dae79cb
--- /dev/null
+++ b/vendor/github.com/jmespath/go-jmespath/toktype_string.go
@@ -0,0 +1,16 @@
+// generated by stringer -type=tokType; DO NOT EDIT
+
+package jmespath
+
+import "fmt"
+
+const _tokType_name = "tUnknowntStartDottFiltertFlattentLparentRparentLbrackettRbrackettLbracetRbracetOrtPipetNumbertUnquotedIdentifiertQuotedIdentifiertCommatColontLTtLTEtGTtGTEtEQtNEtJSONLiteraltStringLiteraltCurrenttExpreftAndtNottEOF"
+
+var _tokType_index = [...]uint8{0, 8, 13, 17, 24, 32, 39, 46, 55, 64, 71, 78, 81, 86, 93, 112, 129, 135, 141, 144, 148, 151, 155, 158, 161, 173, 187, 195, 202, 206, 210, 214}
+
+func (i tokType) String() string {
+ if i < 0 || i >= tokType(len(_tokType_index)-1) {
+ return fmt.Sprintf("tokType(%d)", i)
+ }
+ return _tokType_name[_tokType_index[i]:_tokType_index[i+1]]
+}
diff --git a/vendor/github.com/jmespath/go-jmespath/util.go b/vendor/github.com/jmespath/go-jmespath/util.go
new file mode 100644
index 0000000..ddc1b7d
--- /dev/null
+++ b/vendor/github.com/jmespath/go-jmespath/util.go
@@ -0,0 +1,185 @@
+package jmespath
+
+import (
+ "errors"
+ "reflect"
+)
+
+// IsFalse determines if an object is false based on the JMESPath spec.
+// JMESPath defines false values to be any of:
+// - An empty string array, or hash.
+// - The boolean value false.
+// - nil
+func isFalse(value interface{}) bool {
+ switch v := value.(type) {
+ case bool:
+ return !v
+ case []interface{}:
+ return len(v) == 0
+ case map[string]interface{}:
+ return len(v) == 0
+ case string:
+ return len(v) == 0
+ case nil:
+ return true
+ }
+ // Try the reflection cases before returning false.
+ rv := reflect.ValueOf(value)
+ switch rv.Kind() {
+ case reflect.Struct:
+ // A struct type will never be false, even if
+ // all of its values are the zero type.
+ return false
+ case reflect.Slice, reflect.Map:
+ return rv.Len() == 0
+ case reflect.Ptr:
+ if rv.IsNil() {
+ return true
+ }
+ // If it's a pointer type, we'll try to deref the pointer
+ // and evaluate the pointer value for isFalse.
+ element := rv.Elem()
+ return isFalse(element.Interface())
+ }
+ return false
+}
+
+// ObjsEqual is a generic object equality check.
+// It will take two arbitrary objects and recursively determine
+// if they are equal.
+func objsEqual(left interface{}, right interface{}) bool {
+ return reflect.DeepEqual(left, right)
+}
+
+// SliceParam refers to a single part of a slice.
+// A slice consists of a start, a stop, and a step, similar to
+// python slices.
+type sliceParam struct {
+ N int
+ Specified bool
+}
+
+// Slice supports [start:stop:step] style slicing that's supported in JMESPath.
+func slice(slice []interface{}, parts []sliceParam) ([]interface{}, error) {
+ computed, err := computeSliceParams(len(slice), parts)
+ if err != nil {
+ return nil, err
+ }
+ start, stop, step := computed[0], computed[1], computed[2]
+ result := []interface{}{}
+ if step > 0 {
+ for i := start; i < stop; i += step {
+ result = append(result, slice[i])
+ }
+ } else {
+ for i := start; i > stop; i += step {
+ result = append(result, slice[i])
+ }
+ }
+ return result, nil
+}
+
+func computeSliceParams(length int, parts []sliceParam) ([]int, error) {
+ var start, stop, step int
+ if !parts[2].Specified {
+ step = 1
+ } else if parts[2].N == 0 {
+ return nil, errors.New("Invalid slice, step cannot be 0")
+ } else {
+ step = parts[2].N
+ }
+ var stepValueNegative bool
+ if step < 0 {
+ stepValueNegative = true
+ } else {
+ stepValueNegative = false
+ }
+
+ if !parts[0].Specified {
+ if stepValueNegative {
+ start = length - 1
+ } else {
+ start = 0
+ }
+ } else {
+ start = capSlice(length, parts[0].N, step)
+ }
+
+ if !parts[1].Specified {
+ if stepValueNegative {
+ stop = -1
+ } else {
+ stop = length
+ }
+ } else {
+ stop = capSlice(length, parts[1].N, step)
+ }
+ return []int{start, stop, step}, nil
+}
+
+func capSlice(length int, actual int, step int) int {
+ if actual < 0 {
+ actual += length
+ if actual < 0 {
+ if step < 0 {
+ actual = -1
+ } else {
+ actual = 0
+ }
+ }
+ } else if actual >= length {
+ if step < 0 {
+ actual = length - 1
+ } else {
+ actual = length
+ }
+ }
+ return actual
+}
+
+// ToArrayNum converts an empty interface type to a slice of float64.
+// If any element in the array cannot be converted, then nil is returned
+// along with a second value of false.
+func toArrayNum(data interface{}) ([]float64, bool) {
+ // Is there a better way to do this with reflect?
+ if d, ok := data.([]interface{}); ok {
+ result := make([]float64, len(d))
+ for i, el := range d {
+ item, ok := el.(float64)
+ if !ok {
+ return nil, false
+ }
+ result[i] = item
+ }
+ return result, true
+ }
+ return nil, false
+}
+
+// ToArrayStr converts an empty interface type to a slice of strings.
+// If any element in the array cannot be converted, then nil is returned
+// along with a second value of false. If the input data could be entirely
+// converted, then the converted data, along with a second value of true,
+// will be returned.
+func toArrayStr(data interface{}) ([]string, bool) {
+ // Is there a better way to do this with reflect?
+ if d, ok := data.([]interface{}); ok {
+ result := make([]string, len(d))
+ for i, el := range d {
+ item, ok := el.(string)
+ if !ok {
+ return nil, false
+ }
+ result[i] = item
+ }
+ return result, true
+ }
+ return nil, false
+}
+
+func isSliceType(v interface{}) bool {
+ if v == nil {
+ return false
+ }
+ return reflect.TypeOf(v).Kind() == reflect.Slice
+}
diff --git a/vendor/github.com/kr/pty/License b/vendor/github.com/kr/pty/License
new file mode 100644
index 0000000..6b7558b
--- /dev/null
+++ b/vendor/github.com/kr/pty/License
@@ -0,0 +1,23 @@
+Copyright (c) 2011 Keith Rarick
+
+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/kr/pty/README.md b/vendor/github.com/kr/pty/README.md
new file mode 100644
index 0000000..7b7900c
--- /dev/null
+++ b/vendor/github.com/kr/pty/README.md
@@ -0,0 +1,36 @@
+# pty
+
+Pty is a Go package for using unix pseudo-terminals.
+
+## Install
+
+ go get github.com/kr/pty
+
+## Example
+
+```go
+package main
+
+import (
+ "github.com/kr/pty"
+ "io"
+ "os"
+ "os/exec"
+)
+
+func main() {
+ c := exec.Command("grep", "--color=auto", "bar")
+ f, err := pty.Start(c)
+ if err != nil {
+ panic(err)
+ }
+
+ go func() {
+ f.Write([]byte("foo\n"))
+ f.Write([]byte("bar\n"))
+ f.Write([]byte("baz\n"))
+ f.Write([]byte{4}) // EOT
+ }()
+ io.Copy(os.Stdout, f)
+}
+```
diff --git a/vendor/github.com/kr/pty/doc.go b/vendor/github.com/kr/pty/doc.go
new file mode 100644
index 0000000..190cfbe
--- /dev/null
+++ b/vendor/github.com/kr/pty/doc.go
@@ -0,0 +1,16 @@
+// Package pty provides functions for working with Unix terminals.
+package pty
+
+import (
+ "errors"
+ "os"
+)
+
+// ErrUnsupported is returned if a function is not
+// available on the current platform.
+var ErrUnsupported = errors.New("unsupported")
+
+// Opens a pty and its corresponding tty.
+func Open() (pty, tty *os.File, err error) {
+ return open()
+}
diff --git a/vendor/github.com/kr/pty/ioctl.go b/vendor/github.com/kr/pty/ioctl.go
new file mode 100644
index 0000000..5b856e8
--- /dev/null
+++ b/vendor/github.com/kr/pty/ioctl.go
@@ -0,0 +1,11 @@
+package pty
+
+import "syscall"
+
+func ioctl(fd, cmd, ptr uintptr) error {
+ _, _, e := syscall.Syscall(syscall.SYS_IOCTL, fd, cmd, ptr)
+ if e != 0 {
+ return e
+ }
+ return nil
+}
diff --git a/vendor/github.com/kr/pty/ioctl_bsd.go b/vendor/github.com/kr/pty/ioctl_bsd.go
new file mode 100644
index 0000000..73b12c5
--- /dev/null
+++ b/vendor/github.com/kr/pty/ioctl_bsd.go
@@ -0,0 +1,39 @@
+// +build darwin dragonfly freebsd netbsd openbsd
+
+package pty
+
+// from <sys/ioccom.h>
+const (
+ _IOC_VOID uintptr = 0x20000000
+ _IOC_OUT uintptr = 0x40000000
+ _IOC_IN uintptr = 0x80000000
+ _IOC_IN_OUT uintptr = _IOC_OUT | _IOC_IN
+ _IOC_DIRMASK = _IOC_VOID | _IOC_OUT | _IOC_IN
+
+ _IOC_PARAM_SHIFT = 13
+ _IOC_PARAM_MASK = (1 << _IOC_PARAM_SHIFT) - 1
+)
+
+func _IOC_PARM_LEN(ioctl uintptr) uintptr {
+ return (ioctl >> 16) & _IOC_PARAM_MASK
+}
+
+func _IOC(inout uintptr, group byte, ioctl_num uintptr, param_len uintptr) uintptr {
+ return inout | (param_len&_IOC_PARAM_MASK)<<16 | uintptr(group)<<8 | ioctl_num
+}
+
+func _IO(group byte, ioctl_num uintptr) uintptr {
+ return _IOC(_IOC_VOID, group, ioctl_num, 0)
+}
+
+func _IOR(group byte, ioctl_num uintptr, param_len uintptr) uintptr {
+ return _IOC(_IOC_OUT, group, ioctl_num, param_len)
+}
+
+func _IOW(group byte, ioctl_num uintptr, param_len uintptr) uintptr {
+ return _IOC(_IOC_IN, group, ioctl_num, param_len)
+}
+
+func _IOWR(group byte, ioctl_num uintptr, param_len uintptr) uintptr {
+ return _IOC(_IOC_IN_OUT, group, ioctl_num, param_len)
+}
diff --git a/vendor/github.com/kr/pty/pty_darwin.go b/vendor/github.com/kr/pty/pty_darwin.go
new file mode 100644
index 0000000..4f4d5ca
--- /dev/null
+++ b/vendor/github.com/kr/pty/pty_darwin.go
@@ -0,0 +1,60 @@
+package pty
+
+import (
+ "errors"
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+func open() (pty, tty *os.File, err error) {
+ p, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ sname, err := ptsname(p)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ err = grantpt(p)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ err = unlockpt(p)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ t, err := os.OpenFile(sname, os.O_RDWR, 0)
+ if err != nil {
+ return nil, nil, err
+ }
+ return p, t, nil
+}
+
+func ptsname(f *os.File) (string, error) {
+ n := make([]byte, _IOC_PARM_LEN(syscall.TIOCPTYGNAME))
+
+ err := ioctl(f.Fd(), syscall.TIOCPTYGNAME, uintptr(unsafe.Pointer(&n[0])))
+ if err != nil {
+ return "", err
+ }
+
+ for i, c := range n {
+ if c == 0 {
+ return string(n[:i]), nil
+ }
+ }
+ return "", errors.New("TIOCPTYGNAME string not NUL-terminated")
+}
+
+func grantpt(f *os.File) error {
+ return ioctl(f.Fd(), syscall.TIOCPTYGRANT, 0)
+}
+
+func unlockpt(f *os.File) error {
+ return ioctl(f.Fd(), syscall.TIOCPTYUNLK, 0)
+}
diff --git a/vendor/github.com/kr/pty/pty_freebsd.go b/vendor/github.com/kr/pty/pty_freebsd.go
new file mode 100644
index 0000000..b341bab
--- /dev/null
+++ b/vendor/github.com/kr/pty/pty_freebsd.go
@@ -0,0 +1,73 @@
+package pty
+
+import (
+ "errors"
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+func posix_openpt(oflag int) (fd int, err error) {
+ r0, _, e1 := syscall.Syscall(syscall.SYS_POSIX_OPENPT, uintptr(oflag), 0, 0)
+ fd = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func open() (pty, tty *os.File, err error) {
+ fd, err := posix_openpt(syscall.O_RDWR | syscall.O_CLOEXEC)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ p := os.NewFile(uintptr(fd), "/dev/pts")
+ sname, err := ptsname(p)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ t, err := os.OpenFile("/dev/"+sname, os.O_RDWR, 0)
+ if err != nil {
+ return nil, nil, err
+ }
+ return p, t, nil
+}
+
+func isptmaster(fd uintptr) (bool, error) {
+ err := ioctl(fd, syscall.TIOCPTMASTER, 0)
+ return err == nil, err
+}
+
+var (
+ emptyFiodgnameArg fiodgnameArg
+ ioctl_FIODGNAME = _IOW('f', 120, unsafe.Sizeof(emptyFiodgnameArg))
+)
+
+func ptsname(f *os.File) (string, error) {
+ master, err := isptmaster(f.Fd())
+ if err != nil {
+ return "", err
+ }
+ if !master {
+ return "", syscall.EINVAL
+ }
+
+ const n = _C_SPECNAMELEN + 1
+ var (
+ buf = make([]byte, n)
+ arg = fiodgnameArg{Len: n, Buf: (*byte)(unsafe.Pointer(&buf[0]))}
+ )
+ err = ioctl(f.Fd(), ioctl_FIODGNAME, uintptr(unsafe.Pointer(&arg)))
+ if err != nil {
+ return "", err
+ }
+
+ for i, c := range buf {
+ if c == 0 {
+ return string(buf[:i]), nil
+ }
+ }
+ return "", errors.New("FIODGNAME string not NUL-terminated")
+}
diff --git a/vendor/github.com/kr/pty/pty_linux.go b/vendor/github.com/kr/pty/pty_linux.go
new file mode 100644
index 0000000..cb901a2
--- /dev/null
+++ b/vendor/github.com/kr/pty/pty_linux.go
@@ -0,0 +1,46 @@
+package pty
+
+import (
+ "os"
+ "strconv"
+ "syscall"
+ "unsafe"
+)
+
+func open() (pty, tty *os.File, err error) {
+ p, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ sname, err := ptsname(p)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ err = unlockpt(p)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ t, err := os.OpenFile(sname, os.O_RDWR|syscall.O_NOCTTY, 0)
+ if err != nil {
+ return nil, nil, err
+ }
+ return p, t, nil
+}
+
+func ptsname(f *os.File) (string, error) {
+ var n _C_uint
+ err := ioctl(f.Fd(), syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n)))
+ if err != nil {
+ return "", err
+ }
+ return "/dev/pts/" + strconv.Itoa(int(n)), nil
+}
+
+func unlockpt(f *os.File) error {
+ var u _C_int
+ // use TIOCSPTLCK with a zero valued arg to clear the slave pty lock
+ return ioctl(f.Fd(), syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))
+}
diff --git a/vendor/github.com/kr/pty/pty_unsupported.go b/vendor/github.com/kr/pty/pty_unsupported.go
new file mode 100644
index 0000000..898c730
--- /dev/null
+++ b/vendor/github.com/kr/pty/pty_unsupported.go
@@ -0,0 +1,11 @@
+// +build !linux,!darwin,!freebsd
+
+package pty
+
+import (
+ "os"
+)
+
+func open() (pty, tty *os.File, err error) {
+ return nil, nil, ErrUnsupported
+}
diff --git a/vendor/github.com/kr/pty/run.go b/vendor/github.com/kr/pty/run.go
new file mode 100644
index 0000000..f0678d2
--- /dev/null
+++ b/vendor/github.com/kr/pty/run.go
@@ -0,0 +1,28 @@
+package pty
+
+import (
+ "os"
+ "os/exec"
+ "syscall"
+)
+
+// Start assigns a pseudo-terminal tty os.File to c.Stdin, c.Stdout,
+// and c.Stderr, calls c.Start, and returns the File of the tty's
+// corresponding pty.
+func Start(c *exec.Cmd) (pty *os.File, err error) {
+ pty, tty, err := Open()
+ if err != nil {
+ return nil, err
+ }
+ defer tty.Close()
+ c.Stdout = tty
+ c.Stdin = tty
+ c.Stderr = tty
+ c.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}
+ err = c.Start()
+ if err != nil {
+ pty.Close()
+ return nil, err
+ }
+ return pty, err
+}
diff --git a/vendor/github.com/kr/pty/util.go b/vendor/github.com/kr/pty/util.go
new file mode 100644
index 0000000..67c52d0
--- /dev/null
+++ b/vendor/github.com/kr/pty/util.go
@@ -0,0 +1,35 @@
+package pty
+
+import (
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+// Getsize returns the number of rows (lines) and cols (positions
+// in each line) in terminal t.
+func Getsize(t *os.File) (rows, cols int, err error) {
+ var ws winsize
+ err = windowrect(&ws, t.Fd())
+ return int(ws.ws_row), int(ws.ws_col), err
+}
+
+type winsize struct {
+ ws_row uint16
+ ws_col uint16
+ ws_xpixel uint16
+ ws_ypixel uint16
+}
+
+func windowrect(ws *winsize, fd uintptr) error {
+ _, _, errno := syscall.Syscall(
+ syscall.SYS_IOCTL,
+ fd,
+ syscall.TIOCGWINSZ,
+ uintptr(unsafe.Pointer(ws)),
+ )
+ if errno != 0 {
+ return syscall.Errno(errno)
+ }
+ return nil
+}
diff --git a/vendor/github.com/kr/pty/ztypes_386.go b/vendor/github.com/kr/pty/ztypes_386.go
new file mode 100644
index 0000000..ff0b8fd
--- /dev/null
+++ b/vendor/github.com/kr/pty/ztypes_386.go
@@ -0,0 +1,9 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types.go
+
+package pty
+
+type (
+ _C_int int32
+ _C_uint uint32
+)
diff --git a/vendor/github.com/kr/pty/ztypes_amd64.go b/vendor/github.com/kr/pty/ztypes_amd64.go
new file mode 100644
index 0000000..ff0b8fd
--- /dev/null
+++ b/vendor/github.com/kr/pty/ztypes_amd64.go
@@ -0,0 +1,9 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types.go
+
+package pty
+
+type (
+ _C_int int32
+ _C_uint uint32
+)
diff --git a/vendor/github.com/kr/pty/ztypes_arm.go b/vendor/github.com/kr/pty/ztypes_arm.go
new file mode 100644
index 0000000..ff0b8fd
--- /dev/null
+++ b/vendor/github.com/kr/pty/ztypes_arm.go
@@ -0,0 +1,9 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types.go
+
+package pty
+
+type (
+ _C_int int32
+ _C_uint uint32
+)
diff --git a/vendor/github.com/kr/pty/ztypes_arm64.go b/vendor/github.com/kr/pty/ztypes_arm64.go
new file mode 100644
index 0000000..6c29a4b
--- /dev/null
+++ b/vendor/github.com/kr/pty/ztypes_arm64.go
@@ -0,0 +1,11 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types.go
+
+// +build arm64
+
+package pty
+
+type (
+ _C_int int32
+ _C_uint uint32
+)
diff --git a/vendor/github.com/kr/pty/ztypes_freebsd_386.go b/vendor/github.com/kr/pty/ztypes_freebsd_386.go
new file mode 100644
index 0000000..d997537
--- /dev/null
+++ b/vendor/github.com/kr/pty/ztypes_freebsd_386.go
@@ -0,0 +1,13 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_freebsd.go
+
+package pty
+
+const (
+ _C_SPECNAMELEN = 0x3f
+)
+
+type fiodgnameArg struct {
+ Len int32
+ Buf *byte
+}
diff --git a/vendor/github.com/kr/pty/ztypes_freebsd_amd64.go b/vendor/github.com/kr/pty/ztypes_freebsd_amd64.go
new file mode 100644
index 0000000..5fa102f
--- /dev/null
+++ b/vendor/github.com/kr/pty/ztypes_freebsd_amd64.go
@@ -0,0 +1,14 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_freebsd.go
+
+package pty
+
+const (
+ _C_SPECNAMELEN = 0x3f
+)
+
+type fiodgnameArg struct {
+ Len int32
+ Pad_cgo_0 [4]byte
+ Buf *byte
+}
diff --git a/vendor/github.com/kr/pty/ztypes_freebsd_arm.go b/vendor/github.com/kr/pty/ztypes_freebsd_arm.go
new file mode 100644
index 0000000..d997537
--- /dev/null
+++ b/vendor/github.com/kr/pty/ztypes_freebsd_arm.go
@@ -0,0 +1,13 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_freebsd.go
+
+package pty
+
+const (
+ _C_SPECNAMELEN = 0x3f
+)
+
+type fiodgnameArg struct {
+ Len int32
+ Buf *byte
+}
diff --git a/vendor/github.com/kr/pty/ztypes_ppc64.go b/vendor/github.com/kr/pty/ztypes_ppc64.go
new file mode 100644
index 0000000..4e1af84
--- /dev/null
+++ b/vendor/github.com/kr/pty/ztypes_ppc64.go
@@ -0,0 +1,11 @@
+// +build ppc64
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types.go
+
+package pty
+
+type (
+ _C_int int32
+ _C_uint uint32
+)
diff --git a/vendor/github.com/kr/pty/ztypes_ppc64le.go b/vendor/github.com/kr/pty/ztypes_ppc64le.go
new file mode 100644
index 0000000..e6780f4
--- /dev/null
+++ b/vendor/github.com/kr/pty/ztypes_ppc64le.go
@@ -0,0 +1,11 @@
+// +build ppc64le
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types.go
+
+package pty
+
+type (
+ _C_int int32
+ _C_uint uint32
+)
diff --git a/vendor/github.com/kr/pty/ztypes_s390x.go b/vendor/github.com/kr/pty/ztypes_s390x.go
new file mode 100644
index 0000000..a7452b6
--- /dev/null
+++ b/vendor/github.com/kr/pty/ztypes_s390x.go
@@ -0,0 +1,11 @@
+// +build s390x
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types.go
+
+package pty
+
+type (
+ _C_int int32
+ _C_uint uint32
+)
diff --git a/vendor/github.com/mattn/go-shellwords/LICENSE b/vendor/github.com/mattn/go-shellwords/LICENSE
new file mode 100644
index 0000000..740fa93
--- /dev/null
+++ b/vendor/github.com/mattn/go-shellwords/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2017 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-shellwords/README.md b/vendor/github.com/mattn/go-shellwords/README.md
new file mode 100644
index 0000000..b1d235c
--- /dev/null
+++ b/vendor/github.com/mattn/go-shellwords/README.md
@@ -0,0 +1,47 @@
+# go-shellwords
+
+[![Coverage Status](https://coveralls.io/repos/mattn/go-shellwords/badge.png?branch=master)](https://coveralls.io/r/mattn/go-shellwords?branch=master)
+[![Build Status](https://travis-ci.org/mattn/go-shellwords.svg?branch=master)](https://travis-ci.org/mattn/go-shellwords)
+
+Parse line as shell words.
+
+## Usage
+
+```go
+args, err := shellwords.Parse("./foo --bar=baz")
+// args should be ["./foo", "--bar=baz"]
+```
+
+```go
+os.Setenv("FOO", "bar")
+p := shellwords.NewParser()
+p.ParseEnv = true
+args, err := p.Parse("./foo $FOO")
+// args should be ["./foo", "bar"]
+```
+
+```go
+p := shellwords.NewParser()
+p.ParseBacktick = true
+args, err := p.Parse("./foo `echo $SHELL`")
+// args should be ["./foo", "/bin/bash"]
+```
+
+```go
+shellwords.ParseBacktick = true
+p := shellwords.NewParser()
+args, err := p.Parse("./foo `echo $SHELL`")
+// args should be ["./foo", "/bin/bash"]
+```
+
+# Thanks
+
+This is based on cpan module [Parse::CommandLine](https://metacpan.org/pod/Parse::CommandLine).
+
+# License
+
+under the MIT License: http://mattn.mit-license.org/2017
+
+# Author
+
+Yasuhiro Matsumoto (a.k.a mattn)
diff --git a/vendor/github.com/mattn/go-shellwords/shellwords.go b/vendor/github.com/mattn/go-shellwords/shellwords.go
new file mode 100644
index 0000000..1078039
--- /dev/null
+++ b/vendor/github.com/mattn/go-shellwords/shellwords.go
@@ -0,0 +1,145 @@
+package shellwords
+
+import (
+ "errors"
+ "os"
+ "regexp"
+)
+
+var (
+ ParseEnv bool = false
+ ParseBacktick bool = false
+)
+
+var envRe = regexp.MustCompile(`\$({[a-zA-Z0-9_]+}|[a-zA-Z0-9_]+)`)
+
+func isSpace(r rune) bool {
+ switch r {
+ case ' ', '\t', '\r', '\n':
+ return true
+ }
+ return false
+}
+
+func replaceEnv(s string) string {
+ return envRe.ReplaceAllStringFunc(s, func(s string) string {
+ s = s[1:]
+ if s[0] == '{' {
+ s = s[1 : len(s)-1]
+ }
+ return os.Getenv(s)
+ })
+}
+
+type Parser struct {
+ ParseEnv bool
+ ParseBacktick bool
+ Position int
+}
+
+func NewParser() *Parser {
+ return &Parser{ParseEnv, ParseBacktick, 0}
+}
+
+func (p *Parser) Parse(line string) ([]string, error) {
+ args := []string{}
+ buf := ""
+ var escaped, doubleQuoted, singleQuoted, backQuote bool
+ backtick := ""
+
+ pos := -1
+ got := false
+
+loop:
+ for i, r := range line {
+ if escaped {
+ buf += string(r)
+ escaped = false
+ continue
+ }
+
+ if r == '\\' {
+ if singleQuoted {
+ buf += string(r)
+ } else {
+ escaped = true
+ }
+ continue
+ }
+
+ if isSpace(r) {
+ if singleQuoted || doubleQuoted || backQuote {
+ buf += string(r)
+ backtick += string(r)
+ } else if got {
+ if p.ParseEnv {
+ buf = replaceEnv(buf)
+ }
+ args = append(args, buf)
+ buf = ""
+ got = false
+ }
+ continue
+ }
+
+ switch r {
+ case '`':
+ if !singleQuoted && !doubleQuoted {
+ if p.ParseBacktick {
+ if backQuote {
+ out, err := shellRun(backtick)
+ if err != nil {
+ return nil, err
+ }
+ buf = out
+ }
+ backtick = ""
+ backQuote = !backQuote
+ continue
+ }
+ backtick = ""
+ backQuote = !backQuote
+ }
+ case '"':
+ if !singleQuoted {
+ doubleQuoted = !doubleQuoted
+ continue
+ }
+ case '\'':
+ if !doubleQuoted {
+ singleQuoted = !singleQuoted
+ continue
+ }
+ case ';', '&', '|', '<', '>':
+ if !(escaped || singleQuoted || doubleQuoted || backQuote) {
+ pos = i
+ break loop
+ }
+ }
+
+ got = true
+ buf += string(r)
+ if backQuote {
+ backtick += string(r)
+ }
+ }
+
+ if got {
+ if p.ParseEnv {
+ buf = replaceEnv(buf)
+ }
+ args = append(args, buf)
+ }
+
+ if escaped || singleQuoted || doubleQuoted || backQuote {
+ return nil, errors.New("invalid command line string")
+ }
+
+ p.Position = pos
+
+ return args, nil
+}
+
+func Parse(line string) ([]string, error) {
+ return NewParser().Parse(line)
+}
diff --git a/vendor/github.com/mattn/go-shellwords/util_posix.go b/vendor/github.com/mattn/go-shellwords/util_posix.go
new file mode 100644
index 0000000..4f8ac55
--- /dev/null
+++ b/vendor/github.com/mattn/go-shellwords/util_posix.go
@@ -0,0 +1,19 @@
+// +build !windows
+
+package shellwords
+
+import (
+ "errors"
+ "os"
+ "os/exec"
+ "strings"
+)
+
+func shellRun(line string) (string, error) {
+ shell := os.Getenv("SHELL")
+ b, err := exec.Command(shell, "-c", line).Output()
+ if err != nil {
+ return "", errors.New(err.Error() + ":" + string(b))
+ }
+ return strings.TrimSpace(string(b)), nil
+}
diff --git a/vendor/github.com/mattn/go-shellwords/util_windows.go b/vendor/github.com/mattn/go-shellwords/util_windows.go
new file mode 100644
index 0000000..7cad4cf
--- /dev/null
+++ b/vendor/github.com/mattn/go-shellwords/util_windows.go
@@ -0,0 +1,17 @@
+package shellwords
+
+import (
+ "errors"
+ "os"
+ "os/exec"
+ "strings"
+)
+
+func shellRun(line string) (string, error) {
+ shell := os.Getenv("COMSPEC")
+ b, err := exec.Command(shell, "/c", line).Output()
+ if err != nil {
+ return "", errors.New(err.Error() + ":" + string(b))
+ }
+ return strings.TrimSpace(string(b)), nil
+}
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE b/vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE
new file mode 100644
index 0000000..8dada3e
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE b/vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE
new file mode 100644
index 0000000..5d8cb5b
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE
@@ -0,0 +1 @@
+Copyright 2012 Matt T. Proud (matt.proud@gmail.com)
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/README.md b/vendor/github.com/matttproud/golang_protobuf_extensions/README.md
new file mode 100644
index 0000000..751ee69
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/README.md
@@ -0,0 +1,20 @@
+# Overview
+This repository provides various Protocol Buffer extensions for the Go
+language (golang), namely support for record length-delimited message
+streaming.
+
+| Java | Go |
+| ------------------------------ | --------------------- |
+| MessageLite#parseDelimitedFrom | pbutil.ReadDelimited |
+| MessageLite#writeDelimitedTo | pbutil.WriteDelimited |
+
+Because [Code Review 9102043](https://codereview.appspot.com/9102043/) is
+destined to never be merged into mainline (i.e., never be promoted to formal
+[goprotobuf features](https://github.com/golang/protobuf)), this repository
+will live here in the wild.
+
+# Documentation
+We have [generated Go Doc documentation](http://godoc.org/github.com/matttproud/golang_protobuf_extensions/pbutil) here.
+
+# Testing
+[![Build Status](https://travis-ci.org/matttproud/golang_protobuf_extensions.png?branch=master)](https://travis-ci.org/matttproud/golang_protobuf_extensions)
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go
new file mode 100644
index 0000000..258c063
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go
@@ -0,0 +1,75 @@
+// Copyright 2013 Matt T. Proud
+//
+// 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 pbutil
+
+import (
+ "encoding/binary"
+ "errors"
+ "io"
+
+ "github.com/golang/protobuf/proto"
+)
+
+var errInvalidVarint = errors.New("invalid varint32 encountered")
+
+// ReadDelimited decodes a message from the provided length-delimited stream,
+// where the length is encoded as 32-bit varint prefix to the message body.
+// It returns the total number of bytes read and any applicable error. This is
+// roughly equivalent to the companion Java API's
+// MessageLite#parseDelimitedFrom. As per the reader contract, this function
+// calls r.Read repeatedly as required until exactly one message including its
+// prefix is read and decoded (or an error has occurred). The function never
+// reads more bytes from the stream than required. The function never returns
+// an error if a message has been read and decoded correctly, even if the end
+// of the stream has been reached in doing so. In that case, any subsequent
+// calls return (0, io.EOF).
+func ReadDelimited(r io.Reader, m proto.Message) (n int, err error) {
+ // Per AbstractParser#parsePartialDelimitedFrom with
+ // CodedInputStream#readRawVarint32.
+ var headerBuf [binary.MaxVarintLen32]byte
+ var bytesRead, varIntBytes int
+ var messageLength uint64
+ for varIntBytes == 0 { // i.e. no varint has been decoded yet.
+ if bytesRead >= len(headerBuf) {
+ return bytesRead, errInvalidVarint
+ }
+ // We have to read byte by byte here to avoid reading more bytes
+ // than required. Each read byte is appended to what we have
+ // read before.
+ newBytesRead, err := r.Read(headerBuf[bytesRead : bytesRead+1])
+ if newBytesRead == 0 {
+ if err != nil {
+ return bytesRead, err
+ }
+ // A Reader should not return (0, nil), but if it does,
+ // it should be treated as no-op (according to the
+ // Reader contract). So let's go on...
+ continue
+ }
+ bytesRead += newBytesRead
+ // Now present everything read so far to the varint decoder and
+ // see if a varint can be decoded already.
+ messageLength, varIntBytes = proto.DecodeVarint(headerBuf[:bytesRead])
+ }
+
+ messageBuf := make([]byte, messageLength)
+ newBytesRead, err := io.ReadFull(r, messageBuf)
+ bytesRead += newBytesRead
+ if err != nil {
+ return bytesRead, err
+ }
+
+ return bytesRead, proto.Unmarshal(messageBuf, m)
+}
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go
new file mode 100644
index 0000000..c318385
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go
@@ -0,0 +1,16 @@
+// Copyright 2013 Matt T. Proud
+//
+// 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 pbutil provides record length-delimited Protocol Buffer streaming.
+package pbutil
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go
new file mode 100644
index 0000000..8fb59ad
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go
@@ -0,0 +1,46 @@
+// Copyright 2013 Matt T. Proud
+//
+// 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 pbutil
+
+import (
+ "encoding/binary"
+ "io"
+
+ "github.com/golang/protobuf/proto"
+)
+
+// WriteDelimited encodes and dumps a message to the provided writer prefixed
+// with a 32-bit varint indicating the length of the encoded message, producing
+// a length-delimited record stream, which can be used to chain together
+// encoded messages of the same type together in a file. It returns the total
+// number of bytes written and any applicable error. This is roughly
+// equivalent to the companion Java API's MessageLite#writeDelimitedTo.
+func WriteDelimited(w io.Writer, m proto.Message) (n int, err error) {
+ buffer, err := proto.Marshal(m)
+ if err != nil {
+ return 0, err
+ }
+
+ var buf [binary.MaxVarintLen32]byte
+ encodedLength := binary.PutUvarint(buf[:], uint64(len(buffer)))
+
+ sync, err := w.Write(buf[:encodedLength])
+ if err != nil {
+ return sync, err
+ }
+
+ n, err = w.Write(buffer)
+ return n + sync, err
+}
diff --git a/vendor/github.com/miekg/dns/LICENSE b/vendor/github.com/miekg/dns/LICENSE
new file mode 100644
index 0000000..5763fa7
--- /dev/null
+++ b/vendor/github.com/miekg/dns/LICENSE
@@ -0,0 +1,32 @@
+Extensions of the original work are copyright (c) 2011 Miek Gieben
+
+As this is fork of the official Go code the same license applies:
+
+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/github.com/miekg/dns/README.md b/vendor/github.com/miekg/dns/README.md
new file mode 100644
index 0000000..1e418da
--- /dev/null
+++ b/vendor/github.com/miekg/dns/README.md
@@ -0,0 +1,153 @@
+[![Build Status](https://travis-ci.org/miekg/dns.svg?branch=master)](https://travis-ci.org/miekg/dns)
+
+# Alternative (more granular) approach to a DNS library
+
+> Less is more.
+
+Complete and usable DNS library. All widely used Resource Records are
+supported, including the DNSSEC types. It follows a lean and mean philosophy.
+If there is stuff you should know as a DNS programmer there isn't a convenience
+function for it. Server side and client side programming is supported, i.e. you
+can build servers and resolvers with it.
+
+We try to keep the "master" branch as sane as possible and at the bleeding edge
+of standards, avoiding breaking changes wherever reasonable. We support the last
+two versions of Go, currently: 1.4 and 1.5.
+
+# Goals
+
+* KISS;
+* Fast;
+* Small API, if its easy to code in Go, don't make a function for it.
+
+# Users
+
+A not-so-up-to-date-list-that-may-be-actually-current:
+
+* https://cloudflare.com
+* https://github.com/abh/geodns
+* http://www.statdns.com/
+* http://www.dnsinspect.com/
+* https://github.com/chuangbo/jianbing-dictionary-dns
+* http://www.dns-lg.com/
+* https://github.com/fcambus/rrda
+* https://github.com/kenshinx/godns
+* https://github.com/skynetservices/skydns
+* https://github.com/DevelopersPL/godnsagent
+* https://github.com/duedil-ltd/discodns
+* https://github.com/StalkR/dns-reverse-proxy
+* https://github.com/tianon/rawdns
+* https://mesosphere.github.io/mesos-dns/
+* https://pulse.turbobytes.com/
+* https://play.google.com/store/apps/details?id=com.turbobytes.dig
+* https://github.com/fcambus/statzone
+* https://github.com/benschw/dns-clb-go
+* https://github.com/corny/dnscheck for http://public-dns.tk/
+* https://namesmith.io
+* https://github.com/miekg/unbound
+* https://github.com/miekg/exdns
+
+Send pull request if you want to be listed here.
+
+# Features
+
+* UDP/TCP queries, IPv4 and IPv6;
+* RFC 1035 zone file parsing ($INCLUDE, $ORIGIN, $TTL and $GENERATE (for all record types) are supported;
+* Fast:
+ * Reply speed around ~ 80K qps (faster hardware results in more qps);
+ * Parsing RRs ~ 100K RR/s, that's 5M records in about 50 seconds;
+* Server side programming (mimicking the net/http package);
+* Client side programming;
+* DNSSEC: signing, validating and key generation for DSA, RSA and ECDSA;
+* EDNS0, NSID;
+* AXFR/IXFR;
+* TSIG, SIG(0);
+* DNS name compression;
+* Depends only on the standard library.
+
+Have fun!
+
+Miek Gieben - 2010-2012 - <miek@miek.nl>
+
+# Building
+
+Building is done with the `go` tool. If you have setup your GOPATH
+correctly, the following should work:
+
+ go get github.com/miekg/dns
+ go build github.com/miekg/dns
+
+## Examples
+
+A short "how to use the API" is at the beginning of doc.go (this also will show
+when you call `godoc github.com/miekg/dns`).
+
+Example programs can be found in the `github.com/miekg/exdns` repository.
+
+## Supported RFCs
+
+*all of them*
+
+* 103{4,5} - DNS standard
+* 1348 - NSAP record (removed the record)
+* 1982 - Serial Arithmetic
+* 1876 - LOC record
+* 1995 - IXFR
+* 1996 - DNS notify
+* 2136 - DNS Update (dynamic updates)
+* 2181 - RRset definition - there is no RRset type though, just []RR
+* 2537 - RSAMD5 DNS keys
+* 2065 - DNSSEC (updated in later RFCs)
+* 2671 - EDNS record
+* 2782 - SRV record
+* 2845 - TSIG record
+* 2915 - NAPTR record
+* 2929 - DNS IANA Considerations
+* 3110 - RSASHA1 DNS keys
+* 3225 - DO bit (DNSSEC OK)
+* 340{1,2,3} - NAPTR record
+* 3445 - Limiting the scope of (DNS)KEY
+* 3597 - Unknown RRs
+* 4025 - IPSECKEY
+* 403{3,4,5} - DNSSEC + validation functions
+* 4255 - SSHFP record
+* 4343 - Case insensitivity
+* 4408 - SPF record
+* 4509 - SHA256 Hash in DS
+* 4592 - Wildcards in the DNS
+* 4635 - HMAC SHA TSIG
+* 4701 - DHCID
+* 4892 - id.server
+* 5001 - NSID
+* 5155 - NSEC3 record
+* 5205 - HIP record
+* 5702 - SHA2 in the DNS
+* 5936 - AXFR
+* 5966 - TCP implementation recommendations
+* 6605 - ECDSA
+* 6725 - IANA Registry Update
+* 6742 - ILNP DNS
+* 6840 - Clarifications and Implementation Notes for DNS Security
+* 6844 - CAA record
+* 6891 - EDNS0 update
+* 6895 - DNS IANA considerations
+* 6975 - Algorithm Understanding in DNSSEC
+* 7043 - EUI48/EUI64 records
+* 7314 - DNS (EDNS) EXPIRE Option
+* 7553 - URI record
+* xxxx - EDNS0 DNS Update Lease (draft)
+
+## Loosely based upon
+
+* `ldns`
+* `NSD`
+* `Net::DNS`
+* `GRONG`
+
+## TODO
+
+* privatekey.Precompute() when signing?
+* Last remaining RRs: APL, ATMA, A6, NSAP and NXT.
+* Missing in parsing: ISDN, UNSPEC, NSAP and ATMA.
+* NSEC(3) cover/match/closest enclose.
+* Replies with TC bit are not parsed to the end.
diff --git a/vendor/github.com/miekg/dns/client.go b/vendor/github.com/miekg/dns/client.go
new file mode 100644
index 0000000..8d0ef7b
--- /dev/null
+++ b/vendor/github.com/miekg/dns/client.go
@@ -0,0 +1,385 @@
+package dns
+
+// A client implementation.
+
+import (
+ "bytes"
+ "io"
+ "net"
+ "time"
+)
+
+const dnsTimeout time.Duration = 2 * time.Second
+const tcpIdleTimeout time.Duration = 8 * time.Second
+
+// A Conn represents a connection to a DNS server.
+type Conn struct {
+ net.Conn // a net.Conn holding the connection
+ UDPSize uint16 // minimum receive buffer for UDP messages
+ TsigSecret map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be fully qualified
+ rtt time.Duration
+ t time.Time
+ tsigRequestMAC string
+}
+
+// A Client defines parameters for a DNS client.
+type Client struct {
+ Net string // if "tcp" a TCP query will be initiated, otherwise an UDP one (default is "" for UDP)
+ UDPSize uint16 // minimum receive buffer for UDP messages
+ DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds
+ ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds
+ WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds
+ TsigSecret map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be fully qualified
+ SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass
+ group singleflight
+}
+
+// Exchange performs a synchronous UDP query. It sends the message m to the address
+// contained in a and waits for an reply. Exchange does not retry a failed query, nor
+// will it fall back to TCP in case of truncation.
+// If you need to send a DNS message on an already existing connection, you can use the
+// following:
+//
+// co := &dns.Conn{Conn: c} // c is your net.Conn
+// co.WriteMsg(m)
+// in, err := co.ReadMsg()
+// co.Close()
+//
+func Exchange(m *Msg, a string) (r *Msg, err error) {
+ var co *Conn
+ co, err = DialTimeout("udp", a, dnsTimeout)
+ if err != nil {
+ return nil, err
+ }
+
+ defer co.Close()
+
+ opt := m.IsEdns0()
+ // If EDNS0 is used use that for size.
+ if opt != nil && opt.UDPSize() >= MinMsgSize {
+ co.UDPSize = opt.UDPSize()
+ }
+
+ co.SetWriteDeadline(time.Now().Add(dnsTimeout))
+ if err = co.WriteMsg(m); err != nil {
+ return nil, err
+ }
+
+ co.SetReadDeadline(time.Now().Add(dnsTimeout))
+ r, err = co.ReadMsg()
+ if err == nil && r.Id != m.Id {
+ err = ErrId
+ }
+ return r, err
+}
+
+// ExchangeConn performs a synchronous query. It sends the message m via the connection
+// c and waits for a reply. The connection c is not closed by ExchangeConn.
+// This function is going away, but can easily be mimicked:
+//
+// co := &dns.Conn{Conn: c} // c is your net.Conn
+// co.WriteMsg(m)
+// in, _ := co.ReadMsg()
+// co.Close()
+//
+func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
+ println("dns: this function is deprecated")
+ co := new(Conn)
+ co.Conn = c
+ if err = co.WriteMsg(m); err != nil {
+ return nil, err
+ }
+ r, err = co.ReadMsg()
+ if err == nil && r.Id != m.Id {
+ err = ErrId
+ }
+ return r, err
+}
+
+// Exchange performs an synchronous query. It sends the message m to the address
+// contained in a and waits for an reply. Basic use pattern with a *dns.Client:
+//
+// c := new(dns.Client)
+// in, rtt, err := c.Exchange(message, "127.0.0.1:53")
+//
+// Exchange does not retry a failed query, nor will it fall back to TCP in
+// case of truncation.
+func (c *Client) Exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
+ if !c.SingleInflight {
+ return c.exchange(m, a)
+ }
+ // This adds a bunch of garbage, TODO(miek).
+ t := "nop"
+ if t1, ok := TypeToString[m.Question[0].Qtype]; ok {
+ t = t1
+ }
+ cl := "nop"
+ if cl1, ok := ClassToString[m.Question[0].Qclass]; ok {
+ cl = cl1
+ }
+ r, rtt, err, shared := c.group.Do(m.Question[0].Name+t+cl, func() (*Msg, time.Duration, error) {
+ return c.exchange(m, a)
+ })
+ if err != nil {
+ return r, rtt, err
+ }
+ if shared {
+ return r.Copy(), rtt, nil
+ }
+ return r, rtt, nil
+}
+
+func (c *Client) dialTimeout() time.Duration {
+ if c.DialTimeout != 0 {
+ return c.DialTimeout
+ }
+ return dnsTimeout
+}
+
+func (c *Client) readTimeout() time.Duration {
+ if c.ReadTimeout != 0 {
+ return c.ReadTimeout
+ }
+ return dnsTimeout
+}
+
+func (c *Client) writeTimeout() time.Duration {
+ if c.WriteTimeout != 0 {
+ return c.WriteTimeout
+ }
+ return dnsTimeout
+}
+
+func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
+ var co *Conn
+ if c.Net == "" {
+ co, err = DialTimeout("udp", a, c.dialTimeout())
+ } else {
+ co, err = DialTimeout(c.Net, a, c.dialTimeout())
+ }
+ if err != nil {
+ return nil, 0, err
+ }
+ defer co.Close()
+
+ opt := m.IsEdns0()
+ // If EDNS0 is used use that for size.
+ if opt != nil && opt.UDPSize() >= MinMsgSize {
+ co.UDPSize = opt.UDPSize()
+ }
+ // Otherwise use the client's configured UDP size.
+ if opt == nil && c.UDPSize >= MinMsgSize {
+ co.UDPSize = c.UDPSize
+ }
+
+ co.TsigSecret = c.TsigSecret
+ co.SetWriteDeadline(time.Now().Add(c.writeTimeout()))
+ if err = co.WriteMsg(m); err != nil {
+ return nil, 0, err
+ }
+
+ co.SetReadDeadline(time.Now().Add(c.readTimeout()))
+ r, err = co.ReadMsg()
+ if err == nil && r.Id != m.Id {
+ err = ErrId
+ }
+ return r, co.rtt, err
+}
+
+// ReadMsg reads a message from the connection co.
+// If the received message contains a TSIG record the transaction
+// signature is verified.
+func (co *Conn) ReadMsg() (*Msg, error) {
+ p, err := co.ReadMsgHeader(nil)
+ if err != nil {
+ return nil, err
+ }
+
+ m := new(Msg)
+ if err := m.Unpack(p); err != nil {
+ // If ErrTruncated was returned, we still want to allow the user to use
+ // the message, but naively they can just check err if they don't want
+ // to use a truncated message
+ if err == ErrTruncated {
+ return m, err
+ }
+ return nil, err
+ }
+ if t := m.IsTsig(); t != nil {
+ if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
+ return m, ErrSecret
+ }
+ // Need to work on the original message p, as that was used to calculate the tsig.
+ err = TsigVerify(p, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
+ }
+ return m, err
+}
+
+// ReadMsgHeader reads a DNS message, parses and populates hdr (when hdr is not nil).
+// Returns message as a byte slice to be parsed with Msg.Unpack later on.
+// Note that error handling on the message body is not possible as only the header is parsed.
+func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
+ var (
+ p []byte
+ n int
+ err error
+ )
+
+ if t, ok := co.Conn.(*net.TCPConn); ok {
+ // First two bytes specify the length of the entire message.
+ l, err := tcpMsgLen(t)
+ if err != nil {
+ return nil, err
+ }
+ p = make([]byte, l)
+ n, err = tcpRead(t, p)
+ } else {
+ if co.UDPSize > MinMsgSize {
+ p = make([]byte, co.UDPSize)
+ } else {
+ p = make([]byte, MinMsgSize)
+ }
+ n, err = co.Read(p)
+ }
+
+ if err != nil {
+ return nil, err
+ } else if n < headerSize {
+ return nil, ErrShortRead
+ }
+
+ p = p[:n]
+ if hdr != nil {
+ if _, err = UnpackStruct(hdr, p, 0); err != nil {
+ return nil, err
+ }
+ }
+ return p, err
+}
+
+// tcpMsgLen is a helper func to read first two bytes of stream as uint16 packet length.
+func tcpMsgLen(t *net.TCPConn) (int, error) {
+ p := []byte{0, 0}
+ n, err := t.Read(p)
+ if err != nil {
+ return 0, err
+ }
+ if n != 2 {
+ return 0, ErrShortRead
+ }
+ l, _ := unpackUint16(p, 0)
+ if l == 0 {
+ return 0, ErrShortRead
+ }
+ return int(l), nil
+}
+
+// tcpRead calls TCPConn.Read enough times to fill allocated buffer.
+func tcpRead(t *net.TCPConn, p []byte) (int, error) {
+ n, err := t.Read(p)
+ if err != nil {
+ return n, err
+ }
+ for n < len(p) {
+ j, err := t.Read(p[n:])
+ if err != nil {
+ return n, err
+ }
+ n += j
+ }
+ return n, err
+}
+
+// Read implements the net.Conn read method.
+func (co *Conn) Read(p []byte) (n int, err error) {
+ if co.Conn == nil {
+ return 0, ErrConnEmpty
+ }
+ if len(p) < 2 {
+ return 0, io.ErrShortBuffer
+ }
+ if t, ok := co.Conn.(*net.TCPConn); ok {
+ l, err := tcpMsgLen(t)
+ if err != nil {
+ return 0, err
+ }
+ if l > len(p) {
+ return int(l), io.ErrShortBuffer
+ }
+ return tcpRead(t, p[:l])
+ }
+ // UDP connection
+ n, err = co.Conn.Read(p)
+ if err != nil {
+ return n, err
+ }
+
+ co.rtt = time.Since(co.t)
+ return n, err
+}
+
+// WriteMsg sends a message throught the connection co.
+// If the message m contains a TSIG record the transaction
+// signature is calculated.
+func (co *Conn) WriteMsg(m *Msg) (err error) {
+ var out []byte
+ if t := m.IsTsig(); t != nil {
+ mac := ""
+ if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
+ return ErrSecret
+ }
+ out, mac, err = TsigGenerate(m, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
+ // Set for the next read, allthough only used in zone transfers
+ co.tsigRequestMAC = mac
+ } else {
+ out, err = m.Pack()
+ }
+ if err != nil {
+ return err
+ }
+ co.t = time.Now()
+ if _, err = co.Write(out); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Write implements the net.Conn Write method.
+func (co *Conn) Write(p []byte) (n int, err error) {
+ if t, ok := co.Conn.(*net.TCPConn); ok {
+ lp := len(p)
+ if lp < 2 {
+ return 0, io.ErrShortBuffer
+ }
+ if lp > MaxMsgSize {
+ return 0, &Error{err: "message too large"}
+ }
+ l := make([]byte, 2, lp+2)
+ l[0], l[1] = packUint16(uint16(lp))
+ p = append(l, p...)
+ n, err := io.Copy(t, bytes.NewReader(p))
+ return int(n), err
+ }
+ n, err = co.Conn.(*net.UDPConn).Write(p)
+ return n, err
+}
+
+// Dial connects to the address on the named network.
+func Dial(network, address string) (conn *Conn, err error) {
+ conn = new(Conn)
+ conn.Conn, err = net.Dial(network, address)
+ if err != nil {
+ return nil, err
+ }
+ return conn, nil
+}
+
+// DialTimeout acts like Dial but takes a timeout.
+func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error) {
+ conn = new(Conn)
+ conn.Conn, err = net.DialTimeout(network, address, timeout)
+ if err != nil {
+ return nil, err
+ }
+ return conn, nil
+}
diff --git a/vendor/github.com/miekg/dns/clientconfig.go b/vendor/github.com/miekg/dns/clientconfig.go
new file mode 100644
index 0000000..cfa9ad0
--- /dev/null
+++ b/vendor/github.com/miekg/dns/clientconfig.go
@@ -0,0 +1,99 @@
+package dns
+
+import (
+ "bufio"
+ "os"
+ "strconv"
+ "strings"
+)
+
+// ClientConfig wraps the contents of the /etc/resolv.conf file.
+type ClientConfig struct {
+ Servers []string // servers to use
+ Search []string // suffixes to append to local name
+ Port string // what port to use
+ Ndots int // number of dots in name to trigger absolute lookup
+ Timeout int // seconds before giving up on packet
+ Attempts int // lost packets before giving up on server, not used in the package dns
+}
+
+// ClientConfigFromFile parses a resolv.conf(5) like file and returns
+// a *ClientConfig.
+func ClientConfigFromFile(resolvconf string) (*ClientConfig, error) {
+ file, err := os.Open(resolvconf)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ c := new(ClientConfig)
+ scanner := bufio.NewScanner(file)
+ c.Servers = make([]string, 0)
+ c.Search = make([]string, 0)
+ c.Port = "53"
+ c.Ndots = 1
+ c.Timeout = 5
+ c.Attempts = 2
+
+ for scanner.Scan() {
+ if err := scanner.Err(); err != nil {
+ return nil, err
+ }
+ line := scanner.Text()
+ f := strings.Fields(line)
+ if len(f) < 1 {
+ continue
+ }
+ switch f[0] {
+ case "nameserver": // add one name server
+ if len(f) > 1 {
+ // One more check: make sure server name is
+ // just an IP address. Otherwise we need DNS
+ // to look it up.
+ name := f[1]
+ c.Servers = append(c.Servers, name)
+ }
+
+ case "domain": // set search path to just this domain
+ if len(f) > 1 {
+ c.Search = make([]string, 1)
+ c.Search[0] = f[1]
+ } else {
+ c.Search = make([]string, 0)
+ }
+
+ case "search": // set search path to given servers
+ c.Search = make([]string, len(f)-1)
+ for i := 0; i < len(c.Search); i++ {
+ c.Search[i] = f[i+1]
+ }
+
+ case "options": // magic options
+ for i := 1; i < len(f); i++ {
+ s := f[i]
+ switch {
+ case len(s) >= 6 && s[:6] == "ndots:":
+ n, _ := strconv.Atoi(s[6:])
+ if n < 1 {
+ n = 1
+ }
+ c.Ndots = n
+ case len(s) >= 8 && s[:8] == "timeout:":
+ n, _ := strconv.Atoi(s[8:])
+ if n < 1 {
+ n = 1
+ }
+ c.Timeout = n
+ case len(s) >= 8 && s[:9] == "attempts:":
+ n, _ := strconv.Atoi(s[9:])
+ if n < 1 {
+ n = 1
+ }
+ c.Attempts = n
+ case s == "rotate":
+ /* not imp */
+ }
+ }
+ }
+ }
+ return c, nil
+}
diff --git a/vendor/github.com/miekg/dns/defaults.go b/vendor/github.com/miekg/dns/defaults.go
new file mode 100644
index 0000000..63165b4
--- /dev/null
+++ b/vendor/github.com/miekg/dns/defaults.go
@@ -0,0 +1,278 @@
+package dns
+
+import (
+ "errors"
+ "net"
+ "strconv"
+)
+
+const hexDigit = "0123456789abcdef"
+
+// Everything is assumed in ClassINET.
+
+// SetReply creates a reply message from a request message.
+func (dns *Msg) SetReply(request *Msg) *Msg {
+ dns.Id = request.Id
+ dns.RecursionDesired = request.RecursionDesired // Copy rd bit
+ dns.Response = true
+ dns.Opcode = OpcodeQuery
+ dns.Rcode = RcodeSuccess
+ if len(request.Question) > 0 {
+ dns.Question = make([]Question, 1)
+ dns.Question[0] = request.Question[0]
+ }
+ return dns
+}
+
+// SetQuestion creates a question message, it sets the Question
+// section, generates an Id and sets the RecursionDesired (RD)
+// bit to true.
+func (dns *Msg) SetQuestion(z string, t uint16) *Msg {
+ dns.Id = Id()
+ dns.RecursionDesired = true
+ dns.Question = make([]Question, 1)
+ dns.Question[0] = Question{z, t, ClassINET}
+ return dns
+}
+
+// SetNotify creates a notify message, it sets the Question
+// section, generates an Id and sets the Authoritative (AA)
+// bit to true.
+func (dns *Msg) SetNotify(z string) *Msg {
+ dns.Opcode = OpcodeNotify
+ dns.Authoritative = true
+ dns.Id = Id()
+ dns.Question = make([]Question, 1)
+ dns.Question[0] = Question{z, TypeSOA, ClassINET}
+ return dns
+}
+
+// SetRcode creates an error message suitable for the request.
+func (dns *Msg) SetRcode(request *Msg, rcode int) *Msg {
+ dns.SetReply(request)
+ dns.Rcode = rcode
+ return dns
+}
+
+// SetRcodeFormatError creates a message with FormError set.
+func (dns *Msg) SetRcodeFormatError(request *Msg) *Msg {
+ dns.Rcode = RcodeFormatError
+ dns.Opcode = OpcodeQuery
+ dns.Response = true
+ dns.Authoritative = false
+ dns.Id = request.Id
+ return dns
+}
+
+// SetUpdate makes the message a dynamic update message. It
+// sets the ZONE section to: z, TypeSOA, ClassINET.
+func (dns *Msg) SetUpdate(z string) *Msg {
+ dns.Id = Id()
+ dns.Response = false
+ dns.Opcode = OpcodeUpdate
+ dns.Compress = false // BIND9 cannot handle compression
+ dns.Question = make([]Question, 1)
+ dns.Question[0] = Question{z, TypeSOA, ClassINET}
+ return dns
+}
+
+// SetIxfr creates message for requesting an IXFR.
+func (dns *Msg) SetIxfr(z string, serial uint32, ns, mbox string) *Msg {
+ dns.Id = Id()
+ dns.Question = make([]Question, 1)
+ dns.Ns = make([]RR, 1)
+ s := new(SOA)
+ s.Hdr = RR_Header{z, TypeSOA, ClassINET, defaultTtl, 0}
+ s.Serial = serial
+ s.Ns = ns
+ s.Mbox = mbox
+ dns.Question[0] = Question{z, TypeIXFR, ClassINET}
+ dns.Ns[0] = s
+ return dns
+}
+
+// SetAxfr creates message for requesting an AXFR.
+func (dns *Msg) SetAxfr(z string) *Msg {
+ dns.Id = Id()
+ dns.Question = make([]Question, 1)
+ dns.Question[0] = Question{z, TypeAXFR, ClassINET}
+ return dns
+}
+
+// SetTsig appends a TSIG RR to the message.
+// This is only a skeleton TSIG RR that is added as the last RR in the
+// additional section. The Tsig is calculated when the message is being send.
+func (dns *Msg) SetTsig(z, algo string, fudge, timesigned int64) *Msg {
+ t := new(TSIG)
+ t.Hdr = RR_Header{z, TypeTSIG, ClassANY, 0, 0}
+ t.Algorithm = algo
+ t.Fudge = 300
+ t.TimeSigned = uint64(timesigned)
+ t.OrigId = dns.Id
+ dns.Extra = append(dns.Extra, t)
+ return dns
+}
+
+// SetEdns0 appends a EDNS0 OPT RR to the message.
+// TSIG should always the last RR in a message.
+func (dns *Msg) SetEdns0(udpsize uint16, do bool) *Msg {
+ e := new(OPT)
+ e.Hdr.Name = "."
+ e.Hdr.Rrtype = TypeOPT
+ e.SetUDPSize(udpsize)
+ if do {
+ e.SetDo()
+ }
+ dns.Extra = append(dns.Extra, e)
+ return dns
+}
+
+// IsTsig checks if the message has a TSIG record as the last record
+// in the additional section. It returns the TSIG record found or nil.
+func (dns *Msg) IsTsig() *TSIG {
+ if len(dns.Extra) > 0 {
+ if dns.Extra[len(dns.Extra)-1].Header().Rrtype == TypeTSIG {
+ return dns.Extra[len(dns.Extra)-1].(*TSIG)
+ }
+ }
+ return nil
+}
+
+// IsEdns0 checks if the message has a EDNS0 (OPT) record, any EDNS0
+// record in the additional section will do. It returns the OPT record
+// found or nil.
+func (dns *Msg) IsEdns0() *OPT {
+ for _, r := range dns.Extra {
+ if r.Header().Rrtype == TypeOPT {
+ return r.(*OPT)
+ }
+ }
+ return nil
+}
+
+// IsDomainName checks if s is a valid domain name, it returns the number of
+// labels and true, when a domain name is valid. Note that non fully qualified
+// domain name is considered valid, in this case the last label is counted in
+// the number of labels. When false is returned the number of labels is not
+// defined. Also note that this function is extremely liberal; almost any
+// string is a valid domain name as the DNS is 8 bit protocol. It checks if each
+// label fits in 63 characters, but there is no length check for the entire
+// string s. I.e. a domain name longer than 255 characters is considered valid.
+func IsDomainName(s string) (labels int, ok bool) {
+ _, labels, err := packDomainName(s, nil, 0, nil, false)
+ return labels, err == nil
+}
+
+// IsSubDomain checks if child is indeed a child of the parent. Both child and
+// parent are *not* downcased before doing the comparison.
+func IsSubDomain(parent, child string) bool {
+ // Entire child is contained in parent
+ return CompareDomainName(parent, child) == CountLabel(parent)
+}
+
+// IsMsg sanity checks buf and returns an error if it isn't a valid DNS packet.
+// The checking is performed on the binary payload.
+func IsMsg(buf []byte) error {
+ // Header
+ if len(buf) < 12 {
+ return errors.New("dns: bad message header")
+ }
+ // Header: Opcode
+ // TODO(miek): more checks here, e.g. check all header bits.
+ return nil
+}
+
+// IsFqdn checks if a domain name is fully qualified.
+func IsFqdn(s string) bool {
+ l := len(s)
+ if l == 0 {
+ return false
+ }
+ return s[l-1] == '.'
+}
+
+// IsRRset checks if a set of RRs is a valid RRset as defined by RFC 2181.
+// This means the RRs need to have the same type, name, and class. Returns true
+// if the RR set is valid, otherwise false.
+func IsRRset(rrset []RR) bool {
+ if len(rrset) == 0 {
+ return false
+ }
+ if len(rrset) == 1 {
+ return true
+ }
+ rrHeader := rrset[0].Header()
+ rrType := rrHeader.Rrtype
+ rrClass := rrHeader.Class
+ rrName := rrHeader.Name
+
+ for _, rr := range rrset[1:] {
+ curRRHeader := rr.Header()
+ if curRRHeader.Rrtype != rrType || curRRHeader.Class != rrClass || curRRHeader.Name != rrName {
+ // Mismatch between the records, so this is not a valid rrset for
+ //signing/verifying
+ return false
+ }
+ }
+
+ return true
+}
+
+// Fqdn return the fully qualified domain name from s.
+// If s is already fully qualified, it behaves as the identity function.
+func Fqdn(s string) string {
+ if IsFqdn(s) {
+ return s
+ }
+ return s + "."
+}
+
+// Copied from the official Go code.
+
+// ReverseAddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
+// address suitable for reverse DNS (PTR) record lookups or an error if it fails
+// to parse the IP address.
+func ReverseAddr(addr string) (arpa string, err error) {
+ ip := net.ParseIP(addr)
+ if ip == nil {
+ return "", &Error{err: "unrecognized address: " + addr}
+ }
+ if ip.To4() != nil {
+ return strconv.Itoa(int(ip[15])) + "." + strconv.Itoa(int(ip[14])) + "." + strconv.Itoa(int(ip[13])) + "." +
+ strconv.Itoa(int(ip[12])) + ".in-addr.arpa.", nil
+ }
+ // Must be IPv6
+ buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
+ // Add it, in reverse, to the buffer
+ for i := len(ip) - 1; i >= 0; i-- {
+ v := ip[i]
+ buf = append(buf, hexDigit[v&0xF])
+ buf = append(buf, '.')
+ buf = append(buf, hexDigit[v>>4])
+ buf = append(buf, '.')
+ }
+ // Append "ip6.arpa." and return (buf already has the final .)
+ buf = append(buf, "ip6.arpa."...)
+ return string(buf), nil
+}
+
+// String returns the string representation for the type t.
+func (t Type) String() string {
+ if t1, ok := TypeToString[uint16(t)]; ok {
+ return t1
+ }
+ return "TYPE" + strconv.Itoa(int(t))
+}
+
+// String returns the string representation for the class c.
+func (c Class) String() string {
+ if c1, ok := ClassToString[uint16(c)]; ok {
+ return c1
+ }
+ return "CLASS" + strconv.Itoa(int(c))
+}
+
+// String returns the string representation for the name n.
+func (n Name) String() string {
+ return sprintName(string(n))
+}
diff --git a/vendor/github.com/miekg/dns/dns.go b/vendor/github.com/miekg/dns/dns.go
new file mode 100644
index 0000000..a3e4a0e
--- /dev/null
+++ b/vendor/github.com/miekg/dns/dns.go
@@ -0,0 +1,100 @@
+package dns
+
+import "strconv"
+
+const (
+ year68 = 1 << 31 // For RFC1982 (Serial Arithmetic) calculations in 32 bits.
+ // DefaultMsgSize is the standard default for messages larger than 512 bytes.
+ DefaultMsgSize = 4096
+ // MinMsgSize is the minimal size of a DNS packet.
+ MinMsgSize = 512
+ // MaxMsgSize is the largest possible DNS packet.
+ MaxMsgSize = 65535
+ defaultTtl = 3600 // Default internal TTL.
+)
+
+// Error represents a DNS error
+type Error struct{ err string }
+
+func (e *Error) Error() string {
+ if e == nil {
+ return "dns: <nil>"
+ }
+ return "dns: " + e.err
+}
+
+// An RR represents a resource record.
+type RR interface {
+ // Header returns the header of an resource record. The header contains
+ // everything up to the rdata.
+ Header() *RR_Header
+ // String returns the text representation of the resource record.
+ String() string
+ // copy returns a copy of the RR
+ copy() RR
+ // len returns the length (in octets) of the uncompressed RR in wire format.
+ len() int
+}
+
+// RR_Header is the header all DNS resource records share.
+type RR_Header struct {
+ Name string `dns:"cdomain-name"`
+ Rrtype uint16
+ Class uint16
+ Ttl uint32
+ Rdlength uint16 // length of data after header
+}
+
+// Header returns itself. This is here to make RR_Header implement the RR interface.
+func (h *RR_Header) Header() *RR_Header { return h }
+
+// Just to imlement the RR interface.
+func (h *RR_Header) copy() RR { return nil }
+
+func (h *RR_Header) copyHeader() *RR_Header {
+ r := new(RR_Header)
+ r.Name = h.Name
+ r.Rrtype = h.Rrtype
+ r.Class = h.Class
+ r.Ttl = h.Ttl
+ r.Rdlength = h.Rdlength
+ return r
+}
+
+func (h *RR_Header) String() string {
+ var s string
+
+ if h.Rrtype == TypeOPT {
+ s = ";"
+ // and maybe other things
+ }
+
+ s += sprintName(h.Name) + "\t"
+ s += strconv.FormatInt(int64(h.Ttl), 10) + "\t"
+ s += Class(h.Class).String() + "\t"
+ s += Type(h.Rrtype).String() + "\t"
+ return s
+}
+
+func (h *RR_Header) len() int {
+ l := len(h.Name) + 1
+ l += 10 // rrtype(2) + class(2) + ttl(4) + rdlength(2)
+ return l
+}
+
+// ToRFC3597 converts a known RR to the unknown RR representation
+// from RFC 3597.
+func (rr *RFC3597) ToRFC3597(r RR) error {
+ buf := make([]byte, r.len()*2)
+ off, err := PackStruct(r, buf, 0)
+ if err != nil {
+ return err
+ }
+ buf = buf[:off]
+ rawSetRdlength(buf, 0, off)
+ _, err = UnpackStruct(rr, buf, 0)
+ if err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/vendor/github.com/miekg/dns/dnssec.go b/vendor/github.com/miekg/dns/dnssec.go
new file mode 100644
index 0000000..84cb214
--- /dev/null
+++ b/vendor/github.com/miekg/dns/dnssec.go
@@ -0,0 +1,664 @@
+package dns
+
+import (
+ "bytes"
+ "crypto"
+ "crypto/dsa"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ _ "crypto/md5"
+ "crypto/rand"
+ "crypto/rsa"
+ _ "crypto/sha1"
+ _ "crypto/sha256"
+ _ "crypto/sha512"
+ "encoding/asn1"
+ "encoding/hex"
+ "math/big"
+ "sort"
+ "strings"
+ "time"
+)
+
+// DNSSEC encryption algorithm codes.
+const (
+ _ uint8 = iota
+ RSAMD5
+ DH
+ DSA
+ _ // Skip 4, RFC 6725, section 2.1
+ RSASHA1
+ DSANSEC3SHA1
+ RSASHA1NSEC3SHA1
+ RSASHA256
+ _ // Skip 9, RFC 6725, section 2.1
+ RSASHA512
+ _ // Skip 11, RFC 6725, section 2.1
+ ECCGOST
+ ECDSAP256SHA256
+ ECDSAP384SHA384
+ INDIRECT uint8 = 252
+ PRIVATEDNS uint8 = 253 // Private (experimental keys)
+ PRIVATEOID uint8 = 254
+)
+
+// Map for algorithm names.
+var AlgorithmToString = map[uint8]string{
+ RSAMD5: "RSAMD5",
+ DH: "DH",
+ DSA: "DSA",
+ RSASHA1: "RSASHA1",
+ DSANSEC3SHA1: "DSA-NSEC3-SHA1",
+ RSASHA1NSEC3SHA1: "RSASHA1-NSEC3-SHA1",
+ RSASHA256: "RSASHA256",
+ RSASHA512: "RSASHA512",
+ ECCGOST: "ECC-GOST",
+ ECDSAP256SHA256: "ECDSAP256SHA256",
+ ECDSAP384SHA384: "ECDSAP384SHA384",
+ INDIRECT: "INDIRECT",
+ PRIVATEDNS: "PRIVATEDNS",
+ PRIVATEOID: "PRIVATEOID",
+}
+
+// Map of algorithm strings.
+var StringToAlgorithm = reverseInt8(AlgorithmToString)
+
+// Map of algorithm crypto hashes.
+var AlgorithmToHash = map[uint8]crypto.Hash{
+ RSAMD5: crypto.MD5, // Deprecated in RFC 6725
+ RSASHA1: crypto.SHA1,
+ RSASHA1NSEC3SHA1: crypto.SHA1,
+ RSASHA256: crypto.SHA256,
+ ECDSAP256SHA256: crypto.SHA256,
+ ECDSAP384SHA384: crypto.SHA384,
+ RSASHA512: crypto.SHA512,
+}
+
+// DNSSEC hashing algorithm codes.
+const (
+ _ uint8 = iota
+ SHA1 // RFC 4034
+ SHA256 // RFC 4509
+ GOST94 // RFC 5933
+ SHA384 // Experimental
+ SHA512 // Experimental
+)
+
+// Map for hash names.
+var HashToString = map[uint8]string{
+ SHA1: "SHA1",
+ SHA256: "SHA256",
+ GOST94: "GOST94",
+ SHA384: "SHA384",
+ SHA512: "SHA512",
+}
+
+// Map of hash strings.
+var StringToHash = reverseInt8(HashToString)
+
+// DNSKEY flag values.
+const (
+ SEP = 1
+ REVOKE = 1 << 7
+ ZONE = 1 << 8
+)
+
+// The RRSIG needs to be converted to wireformat with some of
+// the rdata (the signature) missing. Use this struct to ease
+// the conversion (and re-use the pack/unpack functions).
+type rrsigWireFmt struct {
+ TypeCovered uint16
+ Algorithm uint8
+ Labels uint8
+ OrigTtl uint32
+ Expiration uint32
+ Inception uint32
+ KeyTag uint16
+ SignerName string `dns:"domain-name"`
+ /* No Signature */
+}
+
+// Used for converting DNSKEY's rdata to wirefmt.
+type dnskeyWireFmt struct {
+ Flags uint16
+ Protocol uint8
+ Algorithm uint8
+ PublicKey string `dns:"base64"`
+ /* Nothing is left out */
+}
+
+func divRoundUp(a, b int) int {
+ return (a + b - 1) / b
+}
+
+// KeyTag calculates the keytag (or key-id) of the DNSKEY.
+func (k *DNSKEY) KeyTag() uint16 {
+ if k == nil {
+ return 0
+ }
+ var keytag int
+ switch k.Algorithm {
+ case RSAMD5:
+ // Look at the bottom two bytes of the modules, which the last
+ // item in the pubkey. We could do this faster by looking directly
+ // at the base64 values. But I'm lazy.
+ modulus, _ := fromBase64([]byte(k.PublicKey))
+ if len(modulus) > 1 {
+ x, _ := unpackUint16(modulus, len(modulus)-2)
+ keytag = int(x)
+ }
+ default:
+ keywire := new(dnskeyWireFmt)
+ keywire.Flags = k.Flags
+ keywire.Protocol = k.Protocol
+ keywire.Algorithm = k.Algorithm
+ keywire.PublicKey = k.PublicKey
+ wire := make([]byte, DefaultMsgSize)
+ n, err := PackStruct(keywire, wire, 0)
+ if err != nil {
+ return 0
+ }
+ wire = wire[:n]
+ for i, v := range wire {
+ if i&1 != 0 {
+ keytag += int(v) // must be larger than uint32
+ } else {
+ keytag += int(v) << 8
+ }
+ }
+ keytag += (keytag >> 16) & 0xFFFF
+ keytag &= 0xFFFF
+ }
+ return uint16(keytag)
+}
+
+// ToDS converts a DNSKEY record to a DS record.
+func (k *DNSKEY) ToDS(h uint8) *DS {
+ if k == nil {
+ return nil
+ }
+ ds := new(DS)
+ ds.Hdr.Name = k.Hdr.Name
+ ds.Hdr.Class = k.Hdr.Class
+ ds.Hdr.Rrtype = TypeDS
+ ds.Hdr.Ttl = k.Hdr.Ttl
+ ds.Algorithm = k.Algorithm
+ ds.DigestType = h
+ ds.KeyTag = k.KeyTag()
+
+ keywire := new(dnskeyWireFmt)
+ keywire.Flags = k.Flags
+ keywire.Protocol = k.Protocol
+ keywire.Algorithm = k.Algorithm
+ keywire.PublicKey = k.PublicKey
+ wire := make([]byte, DefaultMsgSize)
+ n, err := PackStruct(keywire, wire, 0)
+ if err != nil {
+ return nil
+ }
+ wire = wire[:n]
+
+ owner := make([]byte, 255)
+ off, err1 := PackDomainName(strings.ToLower(k.Hdr.Name), owner, 0, nil, false)
+ if err1 != nil {
+ return nil
+ }
+ owner = owner[:off]
+ // RFC4034:
+ // digest = digest_algorithm( DNSKEY owner name | DNSKEY RDATA);
+ // "|" denotes concatenation
+ // DNSKEY RDATA = Flags | Protocol | Algorithm | Public Key.
+
+ // digest buffer
+ digest := append(owner, wire...) // another copy
+
+ var hash crypto.Hash
+ switch h {
+ case SHA1:
+ hash = crypto.SHA1
+ case SHA256:
+ hash = crypto.SHA256
+ case SHA384:
+ hash = crypto.SHA384
+ case SHA512:
+ hash = crypto.SHA512
+ default:
+ return nil
+ }
+
+ s := hash.New()
+ s.Write(digest)
+ ds.Digest = hex.EncodeToString(s.Sum(nil))
+ return ds
+}
+
+// ToCDNSKEY converts a DNSKEY record to a CDNSKEY record.
+func (k *DNSKEY) ToCDNSKEY() *CDNSKEY {
+ c := &CDNSKEY{DNSKEY: *k}
+ c.Hdr = *k.Hdr.copyHeader()
+ c.Hdr.Rrtype = TypeCDNSKEY
+ return c
+}
+
+// ToCDS converts a DS record to a CDS record.
+func (d *DS) ToCDS() *CDS {
+ c := &CDS{DS: *d}
+ c.Hdr = *d.Hdr.copyHeader()
+ c.Hdr.Rrtype = TypeCDS
+ return c
+}
+
+// Sign signs an RRSet. The signature needs to be filled in with the values:
+// Inception, Expiration, KeyTag, SignerName and Algorithm. The rest is copied
+// from the RRset. Sign returns a non-nill error when the signing went OK.
+// There is no check if RRSet is a proper (RFC 2181) RRSet. If OrigTTL is non
+// zero, it is used as-is, otherwise the TTL of the RRset is used as the
+// OrigTTL.
+func (rr *RRSIG) Sign(k crypto.Signer, rrset []RR) error {
+ if k == nil {
+ return ErrPrivKey
+ }
+ // s.Inception and s.Expiration may be 0 (rollover etc.), the rest must be set
+ if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 {
+ return ErrKey
+ }
+
+ rr.Hdr.Rrtype = TypeRRSIG
+ rr.Hdr.Name = rrset[0].Header().Name
+ rr.Hdr.Class = rrset[0].Header().Class
+ if rr.OrigTtl == 0 { // If set don't override
+ rr.OrigTtl = rrset[0].Header().Ttl
+ }
+ rr.TypeCovered = rrset[0].Header().Rrtype
+ rr.Labels = uint8(CountLabel(rrset[0].Header().Name))
+
+ if strings.HasPrefix(rrset[0].Header().Name, "*") {
+ rr.Labels-- // wildcard, remove from label count
+ }
+
+ sigwire := new(rrsigWireFmt)
+ sigwire.TypeCovered = rr.TypeCovered
+ sigwire.Algorithm = rr.Algorithm
+ sigwire.Labels = rr.Labels
+ sigwire.OrigTtl = rr.OrigTtl
+ sigwire.Expiration = rr.Expiration
+ sigwire.Inception = rr.Inception
+ sigwire.KeyTag = rr.KeyTag
+ // For signing, lowercase this name
+ sigwire.SignerName = strings.ToLower(rr.SignerName)
+
+ // Create the desired binary blob
+ signdata := make([]byte, DefaultMsgSize)
+ n, err := PackStruct(sigwire, signdata, 0)
+ if err != nil {
+ return err
+ }
+ signdata = signdata[:n]
+ wire, err := rawSignatureData(rrset, rr)
+ if err != nil {
+ return err
+ }
+ signdata = append(signdata, wire...)
+
+ hash, ok := AlgorithmToHash[rr.Algorithm]
+ if !ok {
+ return ErrAlg
+ }
+
+ h := hash.New()
+ h.Write(signdata)
+
+ signature, err := sign(k, h.Sum(nil), hash, rr.Algorithm)
+ if err != nil {
+ return err
+ }
+
+ rr.Signature = toBase64(signature)
+
+ return nil
+}
+
+func sign(k crypto.Signer, hashed []byte, hash crypto.Hash, alg uint8) ([]byte, error) {
+ signature, err := k.Sign(rand.Reader, hashed, hash)
+ if err != nil {
+ return nil, err
+ }
+
+ switch alg {
+ case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512:
+ return signature, nil
+
+ case ECDSAP256SHA256, ECDSAP384SHA384:
+ ecdsaSignature := &struct {
+ R, S *big.Int
+ }{}
+ if _, err := asn1.Unmarshal(signature, ecdsaSignature); err != nil {
+ return nil, err
+ }
+
+ var intlen int
+ switch alg {
+ case ECDSAP256SHA256:
+ intlen = 32
+ case ECDSAP384SHA384:
+ intlen = 48
+ }
+
+ signature := intToBytes(ecdsaSignature.R, intlen)
+ signature = append(signature, intToBytes(ecdsaSignature.S, intlen)...)
+ return signature, nil
+
+ // There is no defined interface for what a DSA backed crypto.Signer returns
+ case DSA, DSANSEC3SHA1:
+ // t := divRoundUp(divRoundUp(p.PublicKey.Y.BitLen(), 8)-64, 8)
+ // signature := []byte{byte(t)}
+ // signature = append(signature, intToBytes(r1, 20)...)
+ // signature = append(signature, intToBytes(s1, 20)...)
+ // rr.Signature = signature
+ }
+
+ return nil, ErrAlg
+}
+
+// Verify validates an RRSet with the signature and key. This is only the
+// cryptographic test, the signature validity period must be checked separately.
+// This function copies the rdata of some RRs (to lowercase domain names) for the validation to work.
+func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error {
+ // First the easy checks
+ if !IsRRset(rrset) {
+ return ErrRRset
+ }
+ if rr.KeyTag != k.KeyTag() {
+ return ErrKey
+ }
+ if rr.Hdr.Class != k.Hdr.Class {
+ return ErrKey
+ }
+ if rr.Algorithm != k.Algorithm {
+ return ErrKey
+ }
+ if strings.ToLower(rr.SignerName) != strings.ToLower(k.Hdr.Name) {
+ return ErrKey
+ }
+ if k.Protocol != 3 {
+ return ErrKey
+ }
+
+ // IsRRset checked that we have at least one RR and that the RRs in
+ // the set have consistent type, class, and name. Also check that type and
+ // class matches the RRSIG record.
+ if rrset[0].Header().Class != rr.Hdr.Class {
+ return ErrRRset
+ }
+ if rrset[0].Header().Rrtype != rr.TypeCovered {
+ return ErrRRset
+ }
+
+ // RFC 4035 5.3.2. Reconstructing the Signed Data
+ // Copy the sig, except the rrsig data
+ sigwire := new(rrsigWireFmt)
+ sigwire.TypeCovered = rr.TypeCovered
+ sigwire.Algorithm = rr.Algorithm
+ sigwire.Labels = rr.Labels
+ sigwire.OrigTtl = rr.OrigTtl
+ sigwire.Expiration = rr.Expiration
+ sigwire.Inception = rr.Inception
+ sigwire.KeyTag = rr.KeyTag
+ sigwire.SignerName = strings.ToLower(rr.SignerName)
+ // Create the desired binary blob
+ signeddata := make([]byte, DefaultMsgSize)
+ n, err := PackStruct(sigwire, signeddata, 0)
+ if err != nil {
+ return err
+ }
+ signeddata = signeddata[:n]
+ wire, err := rawSignatureData(rrset, rr)
+ if err != nil {
+ return err
+ }
+ signeddata = append(signeddata, wire...)
+
+ sigbuf := rr.sigBuf() // Get the binary signature data
+ if rr.Algorithm == PRIVATEDNS { // PRIVATEOID
+ // TODO(miek)
+ // remove the domain name and assume its ours?
+ }
+
+ hash, ok := AlgorithmToHash[rr.Algorithm]
+ if !ok {
+ return ErrAlg
+ }
+
+ switch rr.Algorithm {
+ case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512, RSAMD5:
+ // TODO(mg): this can be done quicker, ie. cache the pubkey data somewhere??
+ pubkey := k.publicKeyRSA() // Get the key
+ if pubkey == nil {
+ return ErrKey
+ }
+
+ h := hash.New()
+ h.Write(signeddata)
+ return rsa.VerifyPKCS1v15(pubkey, hash, h.Sum(nil), sigbuf)
+
+ case ECDSAP256SHA256, ECDSAP384SHA384:
+ pubkey := k.publicKeyECDSA()
+ if pubkey == nil {
+ return ErrKey
+ }
+
+ // Split sigbuf into the r and s coordinates
+ r := new(big.Int).SetBytes(sigbuf[:len(sigbuf)/2])
+ s := new(big.Int).SetBytes(sigbuf[len(sigbuf)/2:])
+
+ h := hash.New()
+ h.Write(signeddata)
+ if ecdsa.Verify(pubkey, h.Sum(nil), r, s) {
+ return nil
+ }
+ return ErrSig
+
+ default:
+ return ErrAlg
+ }
+}
+
+// ValidityPeriod uses RFC1982 serial arithmetic to calculate
+// if a signature period is valid. If t is the zero time, the
+// current time is taken other t is. Returns true if the signature
+// is valid at the given time, otherwise returns false.
+func (rr *RRSIG) ValidityPeriod(t time.Time) bool {
+ var utc int64
+ if t.IsZero() {
+ utc = time.Now().UTC().Unix()
+ } else {
+ utc = t.UTC().Unix()
+ }
+ modi := (int64(rr.Inception) - utc) / year68
+ mode := (int64(rr.Expiration) - utc) / year68
+ ti := int64(rr.Inception) + (modi * year68)
+ te := int64(rr.Expiration) + (mode * year68)
+ return ti <= utc && utc <= te
+}
+
+// Return the signatures base64 encodedig sigdata as a byte slice.
+func (rr *RRSIG) sigBuf() []byte {
+ sigbuf, err := fromBase64([]byte(rr.Signature))
+ if err != nil {
+ return nil
+ }
+ return sigbuf
+}
+
+// publicKeyRSA returns the RSA public key from a DNSKEY record.
+func (k *DNSKEY) publicKeyRSA() *rsa.PublicKey {
+ keybuf, err := fromBase64([]byte(k.PublicKey))
+ if err != nil {
+ return nil
+ }
+
+ // RFC 2537/3110, section 2. RSA Public KEY Resource Records
+ // Length is in the 0th byte, unless its zero, then it
+ // it in bytes 1 and 2 and its a 16 bit number
+ explen := uint16(keybuf[0])
+ keyoff := 1
+ if explen == 0 {
+ explen = uint16(keybuf[1])<<8 | uint16(keybuf[2])
+ keyoff = 3
+ }
+ pubkey := new(rsa.PublicKey)
+
+ pubkey.N = big.NewInt(0)
+ shift := uint64((explen - 1) * 8)
+ expo := uint64(0)
+ for i := int(explen - 1); i > 0; i-- {
+ expo += uint64(keybuf[keyoff+i]) << shift
+ shift -= 8
+ }
+ // Remainder
+ expo += uint64(keybuf[keyoff])
+ if expo > 2<<31 {
+ // Larger expo than supported.
+ // println("dns: F5 primes (or larger) are not supported")
+ return nil
+ }
+ pubkey.E = int(expo)
+
+ pubkey.N.SetBytes(keybuf[keyoff+int(explen):])
+ return pubkey
+}
+
+// publicKeyECDSA returns the Curve public key from the DNSKEY record.
+func (k *DNSKEY) publicKeyECDSA() *ecdsa.PublicKey {
+ keybuf, err := fromBase64([]byte(k.PublicKey))
+ if err != nil {
+ return nil
+ }
+ pubkey := new(ecdsa.PublicKey)
+ switch k.Algorithm {
+ case ECDSAP256SHA256:
+ pubkey.Curve = elliptic.P256()
+ if len(keybuf) != 64 {
+ // wrongly encoded key
+ return nil
+ }
+ case ECDSAP384SHA384:
+ pubkey.Curve = elliptic.P384()
+ if len(keybuf) != 96 {
+ // Wrongly encoded key
+ return nil
+ }
+ }
+ pubkey.X = big.NewInt(0)
+ pubkey.X.SetBytes(keybuf[:len(keybuf)/2])
+ pubkey.Y = big.NewInt(0)
+ pubkey.Y.SetBytes(keybuf[len(keybuf)/2:])
+ return pubkey
+}
+
+func (k *DNSKEY) publicKeyDSA() *dsa.PublicKey {
+ keybuf, err := fromBase64([]byte(k.PublicKey))
+ if err != nil {
+ return nil
+ }
+ if len(keybuf) < 22 {
+ return nil
+ }
+ t, keybuf := int(keybuf[0]), keybuf[1:]
+ size := 64 + t*8
+ q, keybuf := keybuf[:20], keybuf[20:]
+ if len(keybuf) != 3*size {
+ return nil
+ }
+ p, keybuf := keybuf[:size], keybuf[size:]
+ g, y := keybuf[:size], keybuf[size:]
+ pubkey := new(dsa.PublicKey)
+ pubkey.Parameters.Q = big.NewInt(0).SetBytes(q)
+ pubkey.Parameters.P = big.NewInt(0).SetBytes(p)
+ pubkey.Parameters.G = big.NewInt(0).SetBytes(g)
+ pubkey.Y = big.NewInt(0).SetBytes(y)
+ return pubkey
+}
+
+type wireSlice [][]byte
+
+func (p wireSlice) Len() int { return len(p) }
+func (p wireSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+func (p wireSlice) Less(i, j int) bool {
+ _, ioff, _ := UnpackDomainName(p[i], 0)
+ _, joff, _ := UnpackDomainName(p[j], 0)
+ return bytes.Compare(p[i][ioff+10:], p[j][joff+10:]) < 0
+}
+
+// Return the raw signature data.
+func rawSignatureData(rrset []RR, s *RRSIG) (buf []byte, err error) {
+ wires := make(wireSlice, len(rrset))
+ for i, r := range rrset {
+ r1 := r.copy()
+ r1.Header().Ttl = s.OrigTtl
+ labels := SplitDomainName(r1.Header().Name)
+ // 6.2. Canonical RR Form. (4) - wildcards
+ if len(labels) > int(s.Labels) {
+ // Wildcard
+ r1.Header().Name = "*." + strings.Join(labels[len(labels)-int(s.Labels):], ".") + "."
+ }
+ // RFC 4034: 6.2. Canonical RR Form. (2) - domain name to lowercase
+ r1.Header().Name = strings.ToLower(r1.Header().Name)
+ // 6.2. Canonical RR Form. (3) - domain rdata to lowercase.
+ // NS, MD, MF, CNAME, SOA, MB, MG, MR, PTR,
+ // HINFO, MINFO, MX, RP, AFSDB, RT, SIG, PX, NXT, NAPTR, KX,
+ // SRV, DNAME, A6
+ //
+ // RFC 6840 - Clarifications and Implementation Notes for DNS Security (DNSSEC):
+ // Section 6.2 of [RFC4034] also erroneously lists HINFO as a record
+ // that needs conversion to lowercase, and twice at that. Since HINFO
+ // records contain no domain names, they are not subject to case
+ // conversion.
+ switch x := r1.(type) {
+ case *NS:
+ x.Ns = strings.ToLower(x.Ns)
+ case *CNAME:
+ x.Target = strings.ToLower(x.Target)
+ case *SOA:
+ x.Ns = strings.ToLower(x.Ns)
+ x.Mbox = strings.ToLower(x.Mbox)
+ case *MB:
+ x.Mb = strings.ToLower(x.Mb)
+ case *MG:
+ x.Mg = strings.ToLower(x.Mg)
+ case *MR:
+ x.Mr = strings.ToLower(x.Mr)
+ case *PTR:
+ x.Ptr = strings.ToLower(x.Ptr)
+ case *MINFO:
+ x.Rmail = strings.ToLower(x.Rmail)
+ x.Email = strings.ToLower(x.Email)
+ case *MX:
+ x.Mx = strings.ToLower(x.Mx)
+ case *NAPTR:
+ x.Replacement = strings.ToLower(x.Replacement)
+ case *KX:
+ x.Exchanger = strings.ToLower(x.Exchanger)
+ case *SRV:
+ x.Target = strings.ToLower(x.Target)
+ case *DNAME:
+ x.Target = strings.ToLower(x.Target)
+ }
+ // 6.2. Canonical RR Form. (5) - origTTL
+ wire := make([]byte, r1.len()+1) // +1 to be safe(r)
+ off, err1 := PackRR(r1, wire, 0, nil, false)
+ if err1 != nil {
+ return nil, err1
+ }
+ wire = wire[:off]
+ wires[i] = wire
+ }
+ sort.Sort(wires)
+ for i, wire := range wires {
+ if i > 0 && bytes.Equal(wire, wires[i-1]) {
+ continue
+ }
+ buf = append(buf, wire...)
+ }
+ return buf, nil
+}
diff --git a/vendor/github.com/miekg/dns/dnssec_keygen.go b/vendor/github.com/miekg/dns/dnssec_keygen.go
new file mode 100644
index 0000000..229a079
--- /dev/null
+++ b/vendor/github.com/miekg/dns/dnssec_keygen.go
@@ -0,0 +1,156 @@
+package dns
+
+import (
+ "crypto"
+ "crypto/dsa"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/rsa"
+ "math/big"
+)
+
+// Generate generates a DNSKEY of the given bit size.
+// The public part is put inside the DNSKEY record.
+// The Algorithm in the key must be set as this will define
+// what kind of DNSKEY will be generated.
+// The ECDSA algorithms imply a fixed keysize, in that case
+// bits should be set to the size of the algorithm.
+func (k *DNSKEY) Generate(bits int) (crypto.PrivateKey, error) {
+ switch k.Algorithm {
+ case DSA, DSANSEC3SHA1:
+ if bits != 1024 {
+ return nil, ErrKeySize
+ }
+ case RSAMD5, RSASHA1, RSASHA256, RSASHA1NSEC3SHA1:
+ if bits < 512 || bits > 4096 {
+ return nil, ErrKeySize
+ }
+ case RSASHA512:
+ if bits < 1024 || bits > 4096 {
+ return nil, ErrKeySize
+ }
+ case ECDSAP256SHA256:
+ if bits != 256 {
+ return nil, ErrKeySize
+ }
+ case ECDSAP384SHA384:
+ if bits != 384 {
+ return nil, ErrKeySize
+ }
+ }
+
+ switch k.Algorithm {
+ case DSA, DSANSEC3SHA1:
+ params := new(dsa.Parameters)
+ if err := dsa.GenerateParameters(params, rand.Reader, dsa.L1024N160); err != nil {
+ return nil, err
+ }
+ priv := new(dsa.PrivateKey)
+ priv.PublicKey.Parameters = *params
+ err := dsa.GenerateKey(priv, rand.Reader)
+ if err != nil {
+ return nil, err
+ }
+ k.setPublicKeyDSA(params.Q, params.P, params.G, priv.PublicKey.Y)
+ return priv, nil
+ case RSAMD5, RSASHA1, RSASHA256, RSASHA512, RSASHA1NSEC3SHA1:
+ priv, err := rsa.GenerateKey(rand.Reader, bits)
+ if err != nil {
+ return nil, err
+ }
+ k.setPublicKeyRSA(priv.PublicKey.E, priv.PublicKey.N)
+ return priv, nil
+ case ECDSAP256SHA256, ECDSAP384SHA384:
+ var c elliptic.Curve
+ switch k.Algorithm {
+ case ECDSAP256SHA256:
+ c = elliptic.P256()
+ case ECDSAP384SHA384:
+ c = elliptic.P384()
+ }
+ priv, err := ecdsa.GenerateKey(c, rand.Reader)
+ if err != nil {
+ return nil, err
+ }
+ k.setPublicKeyECDSA(priv.PublicKey.X, priv.PublicKey.Y)
+ return priv, nil
+ default:
+ return nil, ErrAlg
+ }
+}
+
+// Set the public key (the value E and N)
+func (k *DNSKEY) setPublicKeyRSA(_E int, _N *big.Int) bool {
+ if _E == 0 || _N == nil {
+ return false
+ }
+ buf := exponentToBuf(_E)
+ buf = append(buf, _N.Bytes()...)
+ k.PublicKey = toBase64(buf)
+ return true
+}
+
+// Set the public key for Elliptic Curves
+func (k *DNSKEY) setPublicKeyECDSA(_X, _Y *big.Int) bool {
+ if _X == nil || _Y == nil {
+ return false
+ }
+ var intlen int
+ switch k.Algorithm {
+ case ECDSAP256SHA256:
+ intlen = 32
+ case ECDSAP384SHA384:
+ intlen = 48
+ }
+ k.PublicKey = toBase64(curveToBuf(_X, _Y, intlen))
+ return true
+}
+
+// Set the public key for DSA
+func (k *DNSKEY) setPublicKeyDSA(_Q, _P, _G, _Y *big.Int) bool {
+ if _Q == nil || _P == nil || _G == nil || _Y == nil {
+ return false
+ }
+ buf := dsaToBuf(_Q, _P, _G, _Y)
+ k.PublicKey = toBase64(buf)
+ return true
+}
+
+// Set the public key (the values E and N) for RSA
+// RFC 3110: Section 2. RSA Public KEY Resource Records
+func exponentToBuf(_E int) []byte {
+ var buf []byte
+ i := big.NewInt(int64(_E))
+ if len(i.Bytes()) < 256 {
+ buf = make([]byte, 1)
+ buf[0] = uint8(len(i.Bytes()))
+ } else {
+ buf = make([]byte, 3)
+ buf[0] = 0
+ buf[1] = uint8(len(i.Bytes()) >> 8)
+ buf[2] = uint8(len(i.Bytes()))
+ }
+ buf = append(buf, i.Bytes()...)
+ return buf
+}
+
+// Set the public key for X and Y for Curve. The two
+// values are just concatenated.
+func curveToBuf(_X, _Y *big.Int, intlen int) []byte {
+ buf := intToBytes(_X, intlen)
+ buf = append(buf, intToBytes(_Y, intlen)...)
+ return buf
+}
+
+// Set the public key for X and Y for Curve. The two
+// values are just concatenated.
+func dsaToBuf(_Q, _P, _G, _Y *big.Int) []byte {
+ t := divRoundUp(divRoundUp(_G.BitLen(), 8)-64, 8)
+ buf := []byte{byte(t)}
+ buf = append(buf, intToBytes(_Q, 20)...)
+ buf = append(buf, intToBytes(_P, 64+t*8)...)
+ buf = append(buf, intToBytes(_G, 64+t*8)...)
+ buf = append(buf, intToBytes(_Y, 64+t*8)...)
+ return buf
+}
diff --git a/vendor/github.com/miekg/dns/dnssec_keyscan.go b/vendor/github.com/miekg/dns/dnssec_keyscan.go
new file mode 100644
index 0000000..19a7833
--- /dev/null
+++ b/vendor/github.com/miekg/dns/dnssec_keyscan.go
@@ -0,0 +1,249 @@
+package dns
+
+import (
+ "crypto"
+ "crypto/dsa"
+ "crypto/ecdsa"
+ "crypto/rsa"
+ "io"
+ "math/big"
+ "strconv"
+ "strings"
+)
+
+// NewPrivateKey returns a PrivateKey by parsing the string s.
+// s should be in the same form of the BIND private key files.
+func (k *DNSKEY) NewPrivateKey(s string) (crypto.PrivateKey, error) {
+ if s[len(s)-1] != '\n' { // We need a closing newline
+ return k.ReadPrivateKey(strings.NewReader(s+"\n"), "")
+ }
+ return k.ReadPrivateKey(strings.NewReader(s), "")
+}
+
+// ReadPrivateKey reads a private key from the io.Reader q. The string file is
+// only used in error reporting.
+// The public key must be known, because some cryptographic algorithms embed
+// the public inside the privatekey.
+func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, error) {
+ m, e := parseKey(q, file)
+ if m == nil {
+ return nil, e
+ }
+ if _, ok := m["private-key-format"]; !ok {
+ return nil, ErrPrivKey
+ }
+ if m["private-key-format"] != "v1.2" && m["private-key-format"] != "v1.3" {
+ return nil, ErrPrivKey
+ }
+ // TODO(mg): check if the pubkey matches the private key
+ algo, err := strconv.Atoi(strings.SplitN(m["algorithm"], " ", 2)[0])
+ if err != nil {
+ return nil, ErrPrivKey
+ }
+ switch uint8(algo) {
+ case DSA:
+ priv, e := readPrivateKeyDSA(m)
+ if e != nil {
+ return nil, e
+ }
+ pub := k.publicKeyDSA()
+ if pub == nil {
+ return nil, ErrKey
+ }
+ priv.PublicKey = *pub
+ return priv, e
+ case RSAMD5:
+ fallthrough
+ case RSASHA1:
+ fallthrough
+ case RSASHA1NSEC3SHA1:
+ fallthrough
+ case RSASHA256:
+ fallthrough
+ case RSASHA512:
+ priv, e := readPrivateKeyRSA(m)
+ if e != nil {
+ return nil, e
+ }
+ pub := k.publicKeyRSA()
+ if pub == nil {
+ return nil, ErrKey
+ }
+ priv.PublicKey = *pub
+ return priv, e
+ case ECCGOST:
+ return nil, ErrPrivKey
+ case ECDSAP256SHA256:
+ fallthrough
+ case ECDSAP384SHA384:
+ priv, e := readPrivateKeyECDSA(m)
+ if e != nil {
+ return nil, e
+ }
+ pub := k.publicKeyECDSA()
+ if pub == nil {
+ return nil, ErrKey
+ }
+ priv.PublicKey = *pub
+ return priv, e
+ default:
+ return nil, ErrPrivKey
+ }
+}
+
+// Read a private key (file) string and create a public key. Return the private key.
+func readPrivateKeyRSA(m map[string]string) (*rsa.PrivateKey, error) {
+ p := new(rsa.PrivateKey)
+ p.Primes = []*big.Int{nil, nil}
+ for k, v := range m {
+ switch k {
+ case "modulus", "publicexponent", "privateexponent", "prime1", "prime2":
+ v1, err := fromBase64([]byte(v))
+ if err != nil {
+ return nil, err
+ }
+ switch k {
+ case "modulus":
+ p.PublicKey.N = big.NewInt(0)
+ p.PublicKey.N.SetBytes(v1)
+ case "publicexponent":
+ i := big.NewInt(0)
+ i.SetBytes(v1)
+ p.PublicKey.E = int(i.Int64()) // int64 should be large enough
+ case "privateexponent":
+ p.D = big.NewInt(0)
+ p.D.SetBytes(v1)
+ case "prime1":
+ p.Primes[0] = big.NewInt(0)
+ p.Primes[0].SetBytes(v1)
+ case "prime2":
+ p.Primes[1] = big.NewInt(0)
+ p.Primes[1].SetBytes(v1)
+ }
+ case "exponent1", "exponent2", "coefficient":
+ // not used in Go (yet)
+ case "created", "publish", "activate":
+ // not used in Go (yet)
+ }
+ }
+ return p, nil
+}
+
+func readPrivateKeyDSA(m map[string]string) (*dsa.PrivateKey, error) {
+ p := new(dsa.PrivateKey)
+ p.X = big.NewInt(0)
+ for k, v := range m {
+ switch k {
+ case "private_value(x)":
+ v1, err := fromBase64([]byte(v))
+ if err != nil {
+ return nil, err
+ }
+ p.X.SetBytes(v1)
+ case "created", "publish", "activate":
+ /* not used in Go (yet) */
+ }
+ }
+ return p, nil
+}
+
+func readPrivateKeyECDSA(m map[string]string) (*ecdsa.PrivateKey, error) {
+ p := new(ecdsa.PrivateKey)
+ p.D = big.NewInt(0)
+ // TODO: validate that the required flags are present
+ for k, v := range m {
+ switch k {
+ case "privatekey":
+ v1, err := fromBase64([]byte(v))
+ if err != nil {
+ return nil, err
+ }
+ p.D.SetBytes(v1)
+ case "created", "publish", "activate":
+ /* not used in Go (yet) */
+ }
+ }
+ return p, nil
+}
+
+// parseKey reads a private key from r. It returns a map[string]string,
+// with the key-value pairs, or an error when the file is not correct.
+func parseKey(r io.Reader, file string) (map[string]string, error) {
+ s := scanInit(r)
+ m := make(map[string]string)
+ c := make(chan lex)
+ k := ""
+ // Start the lexer
+ go klexer(s, c)
+ for l := range c {
+ // It should alternate
+ switch l.value {
+ case zKey:
+ k = l.token
+ case zValue:
+ if k == "" {
+ return nil, &ParseError{file, "no private key seen", l}
+ }
+ //println("Setting", strings.ToLower(k), "to", l.token, "b")
+ m[strings.ToLower(k)] = l.token
+ k = ""
+ }
+ }
+ return m, nil
+}
+
+// klexer scans the sourcefile and returns tokens on the channel c.
+func klexer(s *scan, c chan lex) {
+ var l lex
+ str := "" // Hold the current read text
+ commt := false
+ key := true
+ x, err := s.tokenText()
+ defer close(c)
+ for err == nil {
+ l.column = s.position.Column
+ l.line = s.position.Line
+ switch x {
+ case ':':
+ if commt {
+ break
+ }
+ l.token = str
+ if key {
+ l.value = zKey
+ c <- l
+ // Next token is a space, eat it
+ s.tokenText()
+ key = false
+ str = ""
+ } else {
+ l.value = zValue
+ }
+ case ';':
+ commt = true
+ case '\n':
+ if commt {
+ // Reset a comment
+ commt = false
+ }
+ l.value = zValue
+ l.token = str
+ c <- l
+ str = ""
+ commt = false
+ key = true
+ default:
+ if commt {
+ break
+ }
+ str += string(x)
+ }
+ x, err = s.tokenText()
+ }
+ if len(str) > 0 {
+ // Send remainder
+ l.token = str
+ l.value = zValue
+ c <- l
+ }
+}
diff --git a/vendor/github.com/miekg/dns/dnssec_privkey.go b/vendor/github.com/miekg/dns/dnssec_privkey.go
new file mode 100644
index 0000000..56f3ea9
--- /dev/null
+++ b/vendor/github.com/miekg/dns/dnssec_privkey.go
@@ -0,0 +1,85 @@
+package dns
+
+import (
+ "crypto"
+ "crypto/dsa"
+ "crypto/ecdsa"
+ "crypto/rsa"
+ "math/big"
+ "strconv"
+)
+
+const format = "Private-key-format: v1.3\n"
+
+// PrivateKeyString converts a PrivateKey to a string. This string has the same
+// format as the private-key-file of BIND9 (Private-key-format: v1.3).
+// It needs some info from the key (the algorithm), so its a method of the DNSKEY
+// It supports rsa.PrivateKey, ecdsa.PrivateKey and dsa.PrivateKey
+func (r *DNSKEY) PrivateKeyString(p crypto.PrivateKey) string {
+ algorithm := strconv.Itoa(int(r.Algorithm))
+ algorithm += " (" + AlgorithmToString[r.Algorithm] + ")"
+
+ switch p := p.(type) {
+ case *rsa.PrivateKey:
+ modulus := toBase64(p.PublicKey.N.Bytes())
+ e := big.NewInt(int64(p.PublicKey.E))
+ publicExponent := toBase64(e.Bytes())
+ privateExponent := toBase64(p.D.Bytes())
+ prime1 := toBase64(p.Primes[0].Bytes())
+ prime2 := toBase64(p.Primes[1].Bytes())
+ // Calculate Exponent1/2 and Coefficient as per: http://en.wikipedia.org/wiki/RSA#Using_the_Chinese_remainder_algorithm
+ // and from: http://code.google.com/p/go/issues/detail?id=987
+ one := big.NewInt(1)
+ p1 := big.NewInt(0).Sub(p.Primes[0], one)
+ q1 := big.NewInt(0).Sub(p.Primes[1], one)
+ exp1 := big.NewInt(0).Mod(p.D, p1)
+ exp2 := big.NewInt(0).Mod(p.D, q1)
+ coeff := big.NewInt(0).ModInverse(p.Primes[1], p.Primes[0])
+
+ exponent1 := toBase64(exp1.Bytes())
+ exponent2 := toBase64(exp2.Bytes())
+ coefficient := toBase64(coeff.Bytes())
+
+ return format +
+ "Algorithm: " + algorithm + "\n" +
+ "Modulus: " + modulus + "\n" +
+ "PublicExponent: " + publicExponent + "\n" +
+ "PrivateExponent: " + privateExponent + "\n" +
+ "Prime1: " + prime1 + "\n" +
+ "Prime2: " + prime2 + "\n" +
+ "Exponent1: " + exponent1 + "\n" +
+ "Exponent2: " + exponent2 + "\n" +
+ "Coefficient: " + coefficient + "\n"
+
+ case *ecdsa.PrivateKey:
+ var intlen int
+ switch r.Algorithm {
+ case ECDSAP256SHA256:
+ intlen = 32
+ case ECDSAP384SHA384:
+ intlen = 48
+ }
+ private := toBase64(intToBytes(p.D, intlen))
+ return format +
+ "Algorithm: " + algorithm + "\n" +
+ "PrivateKey: " + private + "\n"
+
+ case *dsa.PrivateKey:
+ T := divRoundUp(divRoundUp(p.PublicKey.Parameters.G.BitLen(), 8)-64, 8)
+ prime := toBase64(intToBytes(p.PublicKey.Parameters.P, 64+T*8))
+ subprime := toBase64(intToBytes(p.PublicKey.Parameters.Q, 20))
+ base := toBase64(intToBytes(p.PublicKey.Parameters.G, 64+T*8))
+ priv := toBase64(intToBytes(p.X, 20))
+ pub := toBase64(intToBytes(p.PublicKey.Y, 64+T*8))
+ return format +
+ "Algorithm: " + algorithm + "\n" +
+ "Prime(p): " + prime + "\n" +
+ "Subprime(q): " + subprime + "\n" +
+ "Base(g): " + base + "\n" +
+ "Private_value(x): " + priv + "\n" +
+ "Public_value(y): " + pub + "\n"
+
+ default:
+ return ""
+ }
+}
diff --git a/vendor/github.com/miekg/dns/doc.go b/vendor/github.com/miekg/dns/doc.go
new file mode 100644
index 0000000..89eace5
--- /dev/null
+++ b/vendor/github.com/miekg/dns/doc.go
@@ -0,0 +1,251 @@
+/*
+Package dns implements a full featured interface to the Domain Name System.
+Server- and client-side programming is supported.
+The package allows complete control over what is send out to the DNS. The package
+API follows the less-is-more principle, by presenting a small, clean interface.
+
+The package dns supports (asynchronous) querying/replying, incoming/outgoing zone transfers,
+TSIG, EDNS0, dynamic updates, notifies and DNSSEC validation/signing.
+Note that domain names MUST be fully qualified, before sending them, unqualified
+names in a message will result in a packing failure.
+
+Resource records are native types. They are not stored in wire format.
+Basic usage pattern for creating a new resource record:
+
+ r := new(dns.MX)
+ r.Hdr = dns.RR_Header{Name: "miek.nl.", Rrtype: dns.TypeMX,
+ Class: dns.ClassINET, Ttl: 3600}
+ r.Preference = 10
+ r.Mx = "mx.miek.nl."
+
+Or directly from a string:
+
+ mx, err := dns.NewRR("miek.nl. 3600 IN MX 10 mx.miek.nl.")
+
+Or when the default TTL (3600) and class (IN) suit you:
+
+ mx, err := dns.NewRR("miek.nl. MX 10 mx.miek.nl.")
+
+Or even:
+
+ mx, err := dns.NewRR("$ORIGIN nl.\nmiek 1H IN MX 10 mx.miek")
+
+In the DNS messages are exchanged, these messages contain resource
+records (sets). Use pattern for creating a message:
+
+ m := new(dns.Msg)
+ m.SetQuestion("miek.nl.", dns.TypeMX)
+
+Or when not certain if the domain name is fully qualified:
+
+ m.SetQuestion(dns.Fqdn("miek.nl"), dns.TypeMX)
+
+The message m is now a message with the question section set to ask
+the MX records for the miek.nl. zone.
+
+The following is slightly more verbose, but more flexible:
+
+ m1 := new(dns.Msg)
+ m1.Id = dns.Id()
+ m1.RecursionDesired = true
+ m1.Question = make([]dns.Question, 1)
+ m1.Question[0] = dns.Question{"miek.nl.", dns.TypeMX, dns.ClassINET}
+
+After creating a message it can be send.
+Basic use pattern for synchronous querying the DNS at a
+server configured on 127.0.0.1 and port 53:
+
+ c := new(dns.Client)
+ in, rtt, err := c.Exchange(m1, "127.0.0.1:53")
+
+Suppressing multiple outstanding queries (with the same question, type and
+class) is as easy as setting:
+
+ c.SingleInflight = true
+
+If these "advanced" features are not needed, a simple UDP query can be send,
+with:
+
+ in, err := dns.Exchange(m1, "127.0.0.1:53")
+
+When this functions returns you will get dns message. A dns message consists
+out of four sections.
+The question section: in.Question, the answer section: in.Answer,
+the authority section: in.Ns and the additional section: in.Extra.
+
+Each of these sections (except the Question section) contain a []RR. Basic
+use pattern for accessing the rdata of a TXT RR as the first RR in
+the Answer section:
+
+ if t, ok := in.Answer[0].(*dns.TXT); ok {
+ // do something with t.Txt
+ }
+
+Domain Name and TXT Character String Representations
+
+Both domain names and TXT character strings are converted to presentation
+form both when unpacked and when converted to strings.
+
+For TXT character strings, tabs, carriage returns and line feeds will be
+converted to \t, \r and \n respectively. Back slashes and quotations marks
+will be escaped. Bytes below 32 and above 127 will be converted to \DDD
+form.
+
+For domain names, in addition to the above rules brackets, periods,
+spaces, semicolons and the at symbol are escaped.
+
+DNSSEC
+
+DNSSEC (DNS Security Extension) adds a layer of security to the DNS. It
+uses public key cryptography to sign resource records. The
+public keys are stored in DNSKEY records and the signatures in RRSIG records.
+
+Requesting DNSSEC information for a zone is done by adding the DO (DNSSEC OK) bit
+to an request.
+
+ m := new(dns.Msg)
+ m.SetEdns0(4096, true)
+
+Signature generation, signature verification and key generation are all supported.
+
+DYNAMIC UPDATES
+
+Dynamic updates reuses the DNS message format, but renames three of
+the sections. Question is Zone, Answer is Prerequisite, Authority is
+Update, only the Additional is not renamed. See RFC 2136 for the gory details.
+
+You can set a rather complex set of rules for the existence of absence of
+certain resource records or names in a zone to specify if resource records
+should be added or removed. The table from RFC 2136 supplemented with the Go
+DNS function shows which functions exist to specify the prerequisites.
+
+ 3.2.4 - Table Of Metavalues Used In Prerequisite Section
+
+ CLASS TYPE RDATA Meaning Function
+ --------------------------------------------------------------
+ ANY ANY empty Name is in use dns.NameUsed
+ ANY rrset empty RRset exists (value indep) dns.RRsetUsed
+ NONE ANY empty Name is not in use dns.NameNotUsed
+ NONE rrset empty RRset does not exist dns.RRsetNotUsed
+ zone rrset rr RRset exists (value dep) dns.Used
+
+The prerequisite section can also be left empty.
+If you have decided on the prerequisites you can tell what RRs should
+be added or deleted. The next table shows the options you have and
+what functions to call.
+
+ 3.4.2.6 - Table Of Metavalues Used In Update Section
+
+ CLASS TYPE RDATA Meaning Function
+ ---------------------------------------------------------------
+ ANY ANY empty Delete all RRsets from name dns.RemoveName
+ ANY rrset empty Delete an RRset dns.RemoveRRset
+ NONE rrset rr Delete an RR from RRset dns.Remove
+ zone rrset rr Add to an RRset dns.Insert
+
+TRANSACTION SIGNATURE
+
+An TSIG or transaction signature adds a HMAC TSIG record to each message sent.
+The supported algorithms include: HmacMD5, HmacSHA1, HmacSHA256 and HmacSHA512.
+
+Basic use pattern when querying with a TSIG name "axfr." (note that these key names
+must be fully qualified - as they are domain names) and the base64 secret
+"so6ZGir4GPAqINNh9U5c3A==":
+
+ c := new(dns.Client)
+ c.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
+ m := new(dns.Msg)
+ m.SetQuestion("miek.nl.", dns.TypeMX)
+ m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix())
+ ...
+ // When sending the TSIG RR is calculated and filled in before sending
+
+When requesting an zone transfer (almost all TSIG usage is when requesting zone transfers), with
+TSIG, this is the basic use pattern. In this example we request an AXFR for
+miek.nl. with TSIG key named "axfr." and secret "so6ZGir4GPAqINNh9U5c3A=="
+and using the server 176.58.119.54:
+
+ t := new(dns.Transfer)
+ m := new(dns.Msg)
+ t.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
+ m.SetAxfr("miek.nl.")
+ m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix())
+ c, err := t.In(m, "176.58.119.54:53")
+ for r := range c { ... }
+
+You can now read the records from the transfer as they come in. Each envelope is checked with TSIG.
+If something is not correct an error is returned.
+
+Basic use pattern validating and replying to a message that has TSIG set.
+
+ server := &dns.Server{Addr: ":53", Net: "udp"}
+ server.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
+ go server.ListenAndServe()
+ dns.HandleFunc(".", handleRequest)
+
+ func handleRequest(w dns.ResponseWriter, r *dns.Msg) {
+ m := new(dns.Msg)
+ m.SetReply(r)
+ if r.IsTsig() {
+ if w.TsigStatus() == nil {
+ // *Msg r has an TSIG record and it was validated
+ m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix())
+ } else {
+ // *Msg r has an TSIG records and it was not valided
+ }
+ }
+ w.WriteMsg(m)
+ }
+
+PRIVATE RRS
+
+RFC 6895 sets aside a range of type codes for private use. This range
+is 65,280 - 65,534 (0xFF00 - 0xFFFE). When experimenting with new Resource Records these
+can be used, before requesting an official type code from IANA.
+
+see http://miek.nl/posts/2014/Sep/21/Private%20RRs%20and%20IDN%20in%20Go%20DNS/ for more
+information.
+
+EDNS0
+
+EDNS0 is an extension mechanism for the DNS defined in RFC 2671 and updated
+by RFC 6891. It defines an new RR type, the OPT RR, which is then completely
+abused.
+Basic use pattern for creating an (empty) OPT RR:
+
+ o := new(dns.OPT)
+ o.Hdr.Name = "." // MUST be the root zone, per definition.
+ o.Hdr.Rrtype = dns.TypeOPT
+
+The rdata of an OPT RR consists out of a slice of EDNS0 (RFC 6891)
+interfaces. Currently only a few have been standardized: EDNS0_NSID
+(RFC 5001) and EDNS0_SUBNET (draft-vandergaast-edns-client-subnet-02). Note
+that these options may be combined in an OPT RR.
+Basic use pattern for a server to check if (and which) options are set:
+
+ // o is a dns.OPT
+ for _, s := range o.Option {
+ switch e := s.(type) {
+ case *dns.EDNS0_NSID:
+ // do stuff with e.Nsid
+ case *dns.EDNS0_SUBNET:
+ // access e.Family, e.Address, etc.
+ }
+ }
+
+SIG(0)
+
+From RFC 2931:
+
+ SIG(0) provides protection for DNS transactions and requests ....
+ ... protection for glue records, DNS requests, protection for message headers
+ on requests and responses, and protection of the overall integrity of a response.
+
+It works like TSIG, except that SIG(0) uses public key cryptography, instead of the shared
+secret approach in TSIG.
+Supported algorithms: DSA, ECDSAP256SHA256, ECDSAP384SHA384, RSASHA1, RSASHA256 and
+RSASHA512.
+
+Signing subsequent messages in multi-message sessions is not implemented.
+*/
+package dns
diff --git a/vendor/github.com/miekg/dns/edns.go b/vendor/github.com/miekg/dns/edns.go
new file mode 100644
index 0000000..0c47f6e
--- /dev/null
+++ b/vendor/github.com/miekg/dns/edns.go
@@ -0,0 +1,505 @@
+package dns
+
+import (
+ "encoding/hex"
+ "errors"
+ "net"
+ "strconv"
+)
+
+// EDNS0 Option codes.
+const (
+ EDNS0LLQ = 0x1 // long lived queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01
+ EDNS0UL = 0x2 // update lease draft: http://files.dns-sd.org/draft-sekar-dns-ul.txt
+ EDNS0NSID = 0x3 // nsid (RFC5001)
+ EDNS0DAU = 0x5 // DNSSEC Algorithm Understood
+ EDNS0DHU = 0x6 // DS Hash Understood
+ EDNS0N3U = 0x7 // NSEC3 Hash Understood
+ EDNS0SUBNET = 0x8 // client-subnet (RFC6891)
+ EDNS0EXPIRE = 0x9 // EDNS0 expire
+ EDNS0SUBNETDRAFT = 0x50fa // Don't use! Use EDNS0SUBNET
+ EDNS0LOCALSTART = 0xFDE9 // Beginning of range reserved for local/experimental use (RFC6891)
+ EDNS0LOCALEND = 0xFFFE // End of range reserved for local/experimental use (RFC6891)
+ _DO = 1 << 15 // dnssec ok
+)
+
+// OPT is the EDNS0 RR appended to messages to convey extra (meta) information.
+// See RFC 6891.
+type OPT struct {
+ Hdr RR_Header
+ Option []EDNS0 `dns:"opt"`
+}
+
+func (rr *OPT) String() string {
+ s := "\n;; OPT PSEUDOSECTION:\n; EDNS: version " + strconv.Itoa(int(rr.Version())) + "; "
+ if rr.Do() {
+ s += "flags: do; "
+ } else {
+ s += "flags: ; "
+ }
+ s += "udp: " + strconv.Itoa(int(rr.UDPSize()))
+
+ for _, o := range rr.Option {
+ switch o.(type) {
+ case *EDNS0_NSID:
+ s += "\n; NSID: " + o.String()
+ h, e := o.pack()
+ var r string
+ if e == nil {
+ for _, c := range h {
+ r += "(" + string(c) + ")"
+ }
+ s += " " + r
+ }
+ case *EDNS0_SUBNET:
+ s += "\n; SUBNET: " + o.String()
+ if o.(*EDNS0_SUBNET).DraftOption {
+ s += " (draft)"
+ }
+ case *EDNS0_UL:
+ s += "\n; UPDATE LEASE: " + o.String()
+ case *EDNS0_LLQ:
+ s += "\n; LONG LIVED QUERIES: " + o.String()
+ case *EDNS0_DAU:
+ s += "\n; DNSSEC ALGORITHM UNDERSTOOD: " + o.String()
+ case *EDNS0_DHU:
+ s += "\n; DS HASH UNDERSTOOD: " + o.String()
+ case *EDNS0_N3U:
+ s += "\n; NSEC3 HASH UNDERSTOOD: " + o.String()
+ case *EDNS0_LOCAL:
+ s += "\n; LOCAL OPT: " + o.String()
+ }
+ }
+ return s
+}
+
+func (rr *OPT) len() int {
+ l := rr.Hdr.len()
+ for i := 0; i < len(rr.Option); i++ {
+ l += 4 // Account for 2-byte option code and 2-byte option length.
+ lo, _ := rr.Option[i].pack()
+ l += len(lo)
+ }
+ return l
+}
+
+// return the old value -> delete SetVersion?
+
+// Version returns the EDNS version used. Only zero is defined.
+func (rr *OPT) Version() uint8 {
+ return uint8((rr.Hdr.Ttl & 0x00FF0000) >> 16)
+}
+
+// SetVersion sets the version of EDNS. This is usually zero.
+func (rr *OPT) SetVersion(v uint8) {
+ rr.Hdr.Ttl = rr.Hdr.Ttl&0xFF00FFFF | (uint32(v) << 16)
+}
+
+// ExtendedRcode returns the EDNS extended RCODE field (the upper 8 bits of the TTL).
+func (rr *OPT) ExtendedRcode() uint8 {
+ return uint8((rr.Hdr.Ttl & 0xFF000000) >> 24)
+}
+
+// SetExtendedRcode sets the EDNS extended RCODE field.
+func (rr *OPT) SetExtendedRcode(v uint8) {
+ rr.Hdr.Ttl = rr.Hdr.Ttl&0x00FFFFFF | (uint32(v) << 24)
+}
+
+// UDPSize returns the UDP buffer size.
+func (rr *OPT) UDPSize() uint16 {
+ return rr.Hdr.Class
+}
+
+// SetUDPSize sets the UDP buffer size.
+func (rr *OPT) SetUDPSize(size uint16) {
+ rr.Hdr.Class = size
+}
+
+// Do returns the value of the DO (DNSSEC OK) bit.
+func (rr *OPT) Do() bool {
+ return rr.Hdr.Ttl&_DO == _DO
+}
+
+// SetDo sets the DO (DNSSEC OK) bit.
+func (rr *OPT) SetDo() {
+ rr.Hdr.Ttl |= _DO
+}
+
+// EDNS0 defines an EDNS0 Option. An OPT RR can have multiple options appended to
+// it.
+type EDNS0 interface {
+ // Option returns the option code for the option.
+ Option() uint16
+ // pack returns the bytes of the option data.
+ pack() ([]byte, error)
+ // unpack sets the data as found in the buffer. Is also sets
+ // the length of the slice as the length of the option data.
+ unpack([]byte) error
+ // String returns the string representation of the option.
+ String() string
+}
+
+// The nsid EDNS0 option is used to retrieve a nameserver
+// identifier. When sending a request Nsid must be set to the empty string
+// The identifier is an opaque string encoded as hex.
+// Basic use pattern for creating an nsid option:
+//
+// o := new(dns.OPT)
+// o.Hdr.Name = "."
+// o.Hdr.Rrtype = dns.TypeOPT
+// e := new(dns.EDNS0_NSID)
+// e.Code = dns.EDNS0NSID
+// e.Nsid = "AA"
+// o.Option = append(o.Option, e)
+type EDNS0_NSID struct {
+ Code uint16 // Always EDNS0NSID
+ Nsid string // This string needs to be hex encoded
+}
+
+func (e *EDNS0_NSID) pack() ([]byte, error) {
+ h, err := hex.DecodeString(e.Nsid)
+ if err != nil {
+ return nil, err
+ }
+ return h, nil
+}
+
+func (e *EDNS0_NSID) Option() uint16 { return EDNS0NSID }
+func (e *EDNS0_NSID) unpack(b []byte) error { e.Nsid = hex.EncodeToString(b); return nil }
+func (e *EDNS0_NSID) String() string { return string(e.Nsid) }
+
+// EDNS0_SUBNET is the subnet option that is used to give the remote nameserver
+// an idea of where the client lives. It can then give back a different
+// answer depending on the location or network topology.
+// Basic use pattern for creating an subnet option:
+//
+// o := new(dns.OPT)
+// o.Hdr.Name = "."
+// o.Hdr.Rrtype = dns.TypeOPT
+// e := new(dns.EDNS0_SUBNET)
+// e.Code = dns.EDNS0SUBNET
+// e.Family = 1 // 1 for IPv4 source address, 2 for IPv6
+// e.NetMask = 32 // 32 for IPV4, 128 for IPv6
+// e.SourceScope = 0
+// e.Address = net.ParseIP("127.0.0.1").To4() // for IPv4
+// // e.Address = net.ParseIP("2001:7b8:32a::2") // for IPV6
+// o.Option = append(o.Option, e)
+//
+// Note: the spec (draft-ietf-dnsop-edns-client-subnet-00) has some insane logic
+// for which netmask applies to the address. This code will parse all the
+// available bits when unpacking (up to optlen). When packing it will apply
+// SourceNetmask. If you need more advanced logic, patches welcome and good luck.
+type EDNS0_SUBNET struct {
+ Code uint16 // Always EDNS0SUBNET
+ Family uint16 // 1 for IP, 2 for IP6
+ SourceNetmask uint8
+ SourceScope uint8
+ Address net.IP
+ DraftOption bool // Set to true if using the old (0x50fa) option code
+}
+
+func (e *EDNS0_SUBNET) Option() uint16 {
+ if e.DraftOption {
+ return EDNS0SUBNETDRAFT
+ }
+ return EDNS0SUBNET
+}
+
+func (e *EDNS0_SUBNET) pack() ([]byte, error) {
+ b := make([]byte, 4)
+ b[0], b[1] = packUint16(e.Family)
+ b[2] = e.SourceNetmask
+ b[3] = e.SourceScope
+ switch e.Family {
+ case 1:
+ if e.SourceNetmask > net.IPv4len*8 {
+ return nil, errors.New("dns: bad netmask")
+ }
+ if len(e.Address.To4()) != net.IPv4len {
+ return nil, errors.New("dns: bad address")
+ }
+ ip := e.Address.To4().Mask(net.CIDRMask(int(e.SourceNetmask), net.IPv4len*8))
+ needLength := (e.SourceNetmask + 8 - 1) / 8 // division rounding up
+ b = append(b, ip[:needLength]...)
+ case 2:
+ if e.SourceNetmask > net.IPv6len*8 {
+ return nil, errors.New("dns: bad netmask")
+ }
+ if len(e.Address) != net.IPv6len {
+ return nil, errors.New("dns: bad address")
+ }
+ ip := e.Address.Mask(net.CIDRMask(int(e.SourceNetmask), net.IPv6len*8))
+ needLength := (e.SourceNetmask + 8 - 1) / 8 // division rounding up
+ b = append(b, ip[:needLength]...)
+ default:
+ return nil, errors.New("dns: bad address family")
+ }
+ return b, nil
+}
+
+func (e *EDNS0_SUBNET) unpack(b []byte) error {
+ if len(b) < 4 {
+ return ErrBuf
+ }
+ e.Family, _ = unpackUint16(b, 0)
+ e.SourceNetmask = b[2]
+ e.SourceScope = b[3]
+ switch e.Family {
+ case 1:
+ if e.SourceNetmask > net.IPv4len*8 || e.SourceScope > net.IPv4len*8 {
+ return errors.New("dns: bad netmask")
+ }
+ addr := make([]byte, net.IPv4len)
+ for i := 0; i < net.IPv4len && 4+i < len(b); i++ {
+ addr[i] = b[4+i]
+ }
+ e.Address = net.IPv4(addr[0], addr[1], addr[2], addr[3])
+ case 2:
+ if e.SourceNetmask > net.IPv6len*8 || e.SourceScope > net.IPv6len*8 {
+ return errors.New("dns: bad netmask")
+ }
+ addr := make([]byte, net.IPv6len)
+ for i := 0; i < net.IPv6len && 4+i < len(b); i++ {
+ addr[i] = b[4+i]
+ }
+ e.Address = net.IP{addr[0], addr[1], addr[2], addr[3], addr[4],
+ addr[5], addr[6], addr[7], addr[8], addr[9], addr[10],
+ addr[11], addr[12], addr[13], addr[14], addr[15]}
+ default:
+ return errors.New("dns: bad address family")
+ }
+ return nil
+}
+
+func (e *EDNS0_SUBNET) String() (s string) {
+ if e.Address == nil {
+ s = "<nil>"
+ } else if e.Address.To4() != nil {
+ s = e.Address.String()
+ } else {
+ s = "[" + e.Address.String() + "]"
+ }
+ s += "/" + strconv.Itoa(int(e.SourceNetmask)) + "/" + strconv.Itoa(int(e.SourceScope))
+ return
+}
+
+// The EDNS0_UL (Update Lease) (draft RFC) option is used to tell the server to set
+// an expiration on an update RR. This is helpful for clients that cannot clean
+// up after themselves. This is a draft RFC and more information can be found at
+// http://files.dns-sd.org/draft-sekar-dns-ul.txt
+//
+// o := new(dns.OPT)
+// o.Hdr.Name = "."
+// o.Hdr.Rrtype = dns.TypeOPT
+// e := new(dns.EDNS0_UL)
+// e.Code = dns.EDNS0UL
+// e.Lease = 120 // in seconds
+// o.Option = append(o.Option, e)
+type EDNS0_UL struct {
+ Code uint16 // Always EDNS0UL
+ Lease uint32
+}
+
+func (e *EDNS0_UL) Option() uint16 { return EDNS0UL }
+func (e *EDNS0_UL) String() string { return strconv.FormatUint(uint64(e.Lease), 10) }
+
+// Copied: http://golang.org/src/pkg/net/dnsmsg.go
+func (e *EDNS0_UL) pack() ([]byte, error) {
+ b := make([]byte, 4)
+ b[0] = byte(e.Lease >> 24)
+ b[1] = byte(e.Lease >> 16)
+ b[2] = byte(e.Lease >> 8)
+ b[3] = byte(e.Lease)
+ return b, nil
+}
+
+func (e *EDNS0_UL) unpack(b []byte) error {
+ if len(b) < 4 {
+ return ErrBuf
+ }
+ e.Lease = uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])
+ return nil
+}
+
+// EDNS0_LLQ stands for Long Lived Queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01
+// Implemented for completeness, as the EDNS0 type code is assigned.
+type EDNS0_LLQ struct {
+ Code uint16 // Always EDNS0LLQ
+ Version uint16
+ Opcode uint16
+ Error uint16
+ Id uint64
+ LeaseLife uint32
+}
+
+func (e *EDNS0_LLQ) Option() uint16 { return EDNS0LLQ }
+
+func (e *EDNS0_LLQ) pack() ([]byte, error) {
+ b := make([]byte, 18)
+ b[0], b[1] = packUint16(e.Version)
+ b[2], b[3] = packUint16(e.Opcode)
+ b[4], b[5] = packUint16(e.Error)
+ b[6] = byte(e.Id >> 56)
+ b[7] = byte(e.Id >> 48)
+ b[8] = byte(e.Id >> 40)
+ b[9] = byte(e.Id >> 32)
+ b[10] = byte(e.Id >> 24)
+ b[11] = byte(e.Id >> 16)
+ b[12] = byte(e.Id >> 8)
+ b[13] = byte(e.Id)
+ b[14] = byte(e.LeaseLife >> 24)
+ b[15] = byte(e.LeaseLife >> 16)
+ b[16] = byte(e.LeaseLife >> 8)
+ b[17] = byte(e.LeaseLife)
+ return b, nil
+}
+
+func (e *EDNS0_LLQ) unpack(b []byte) error {
+ if len(b) < 18 {
+ return ErrBuf
+ }
+ e.Version, _ = unpackUint16(b, 0)
+ e.Opcode, _ = unpackUint16(b, 2)
+ e.Error, _ = unpackUint16(b, 4)
+ e.Id = uint64(b[6])<<56 | uint64(b[6+1])<<48 | uint64(b[6+2])<<40 |
+ uint64(b[6+3])<<32 | uint64(b[6+4])<<24 | uint64(b[6+5])<<16 | uint64(b[6+6])<<8 | uint64(b[6+7])
+ e.LeaseLife = uint32(b[14])<<24 | uint32(b[14+1])<<16 | uint32(b[14+2])<<8 | uint32(b[14+3])
+ return nil
+}
+
+func (e *EDNS0_LLQ) String() string {
+ s := strconv.FormatUint(uint64(e.Version), 10) + " " + strconv.FormatUint(uint64(e.Opcode), 10) +
+ " " + strconv.FormatUint(uint64(e.Error), 10) + " " + strconv.FormatUint(uint64(e.Id), 10) +
+ " " + strconv.FormatUint(uint64(e.LeaseLife), 10)
+ return s
+}
+
+type EDNS0_DAU struct {
+ Code uint16 // Always EDNS0DAU
+ AlgCode []uint8
+}
+
+func (e *EDNS0_DAU) Option() uint16 { return EDNS0DAU }
+func (e *EDNS0_DAU) pack() ([]byte, error) { return e.AlgCode, nil }
+func (e *EDNS0_DAU) unpack(b []byte) error { e.AlgCode = b; return nil }
+
+func (e *EDNS0_DAU) String() string {
+ s := ""
+ for i := 0; i < len(e.AlgCode); i++ {
+ if a, ok := AlgorithmToString[e.AlgCode[i]]; ok {
+ s += " " + a
+ } else {
+ s += " " + strconv.Itoa(int(e.AlgCode[i]))
+ }
+ }
+ return s
+}
+
+type EDNS0_DHU struct {
+ Code uint16 // Always EDNS0DHU
+ AlgCode []uint8
+}
+
+func (e *EDNS0_DHU) Option() uint16 { return EDNS0DHU }
+func (e *EDNS0_DHU) pack() ([]byte, error) { return e.AlgCode, nil }
+func (e *EDNS0_DHU) unpack(b []byte) error { e.AlgCode = b; return nil }
+
+func (e *EDNS0_DHU) String() string {
+ s := ""
+ for i := 0; i < len(e.AlgCode); i++ {
+ if a, ok := HashToString[e.AlgCode[i]]; ok {
+ s += " " + a
+ } else {
+ s += " " + strconv.Itoa(int(e.AlgCode[i]))
+ }
+ }
+ return s
+}
+
+type EDNS0_N3U struct {
+ Code uint16 // Always EDNS0N3U
+ AlgCode []uint8
+}
+
+func (e *EDNS0_N3U) Option() uint16 { return EDNS0N3U }
+func (e *EDNS0_N3U) pack() ([]byte, error) { return e.AlgCode, nil }
+func (e *EDNS0_N3U) unpack(b []byte) error { e.AlgCode = b; return nil }
+
+func (e *EDNS0_N3U) String() string {
+ // Re-use the hash map
+ s := ""
+ for i := 0; i < len(e.AlgCode); i++ {
+ if a, ok := HashToString[e.AlgCode[i]]; ok {
+ s += " " + a
+ } else {
+ s += " " + strconv.Itoa(int(e.AlgCode[i]))
+ }
+ }
+ return s
+}
+
+type EDNS0_EXPIRE struct {
+ Code uint16 // Always EDNS0EXPIRE
+ Expire uint32
+}
+
+func (e *EDNS0_EXPIRE) Option() uint16 { return EDNS0EXPIRE }
+func (e *EDNS0_EXPIRE) String() string { return strconv.FormatUint(uint64(e.Expire), 10) }
+
+func (e *EDNS0_EXPIRE) pack() ([]byte, error) {
+ b := make([]byte, 4)
+ b[0] = byte(e.Expire >> 24)
+ b[1] = byte(e.Expire >> 16)
+ b[2] = byte(e.Expire >> 8)
+ b[3] = byte(e.Expire)
+ return b, nil
+}
+
+func (e *EDNS0_EXPIRE) unpack(b []byte) error {
+ if len(b) < 4 {
+ return ErrBuf
+ }
+ e.Expire = uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])
+ return nil
+}
+
+// The EDNS0_LOCAL option is used for local/experimental purposes. The option
+// code is recommended to be within the range [EDNS0LOCALSTART, EDNS0LOCALEND]
+// (RFC6891), although any unassigned code can actually be used. The content of
+// the option is made available in Data, unaltered.
+// Basic use pattern for creating a local option:
+//
+// o := new(dns.OPT)
+// o.Hdr.Name = "."
+// o.Hdr.Rrtype = dns.TypeOPT
+// e := new(dns.EDNS0_LOCAL)
+// e.Code = dns.EDNS0LOCALSTART
+// e.Data = []byte{72, 82, 74}
+// o.Option = append(o.Option, e)
+type EDNS0_LOCAL struct {
+ Code uint16
+ Data []byte
+}
+
+func (e *EDNS0_LOCAL) Option() uint16 { return e.Code }
+func (e *EDNS0_LOCAL) String() string {
+ return strconv.FormatInt(int64(e.Code), 10) + ":0x" + hex.EncodeToString(e.Data)
+}
+
+func (e *EDNS0_LOCAL) pack() ([]byte, error) {
+ b := make([]byte, len(e.Data))
+ copied := copy(b, e.Data)
+ if copied != len(e.Data) {
+ return nil, ErrBuf
+ }
+ return b, nil
+}
+
+func (e *EDNS0_LOCAL) unpack(b []byte) error {
+ e.Data = make([]byte, len(b))
+ copied := copy(e.Data, b)
+ if copied != len(b) {
+ return ErrBuf
+ }
+ return nil
+}
diff --git a/vendor/github.com/miekg/dns/format.go b/vendor/github.com/miekg/dns/format.go
new file mode 100644
index 0000000..1ac1664
--- /dev/null
+++ b/vendor/github.com/miekg/dns/format.go
@@ -0,0 +1,96 @@
+package dns
+
+import (
+ "net"
+ "reflect"
+ "strconv"
+)
+
+// NumField returns the number of rdata fields r has.
+func NumField(r RR) int {
+ return reflect.ValueOf(r).Elem().NumField() - 1 // Remove RR_Header
+}
+
+// Field returns the rdata field i as a string. Fields are indexed starting from 1.
+// RR types that holds slice data, for instance the NSEC type bitmap will return a single
+// string where the types are concatenated using a space.
+// Accessing non existing fields will cause a panic.
+func Field(r RR, i int) string {
+ if i == 0 {
+ return ""
+ }
+ d := reflect.ValueOf(r).Elem().Field(i)
+ switch k := d.Kind(); k {
+ case reflect.String:
+ return d.String()
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ return strconv.FormatInt(d.Int(), 10)
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ return strconv.FormatUint(d.Uint(), 10)
+ case reflect.Slice:
+ switch reflect.ValueOf(r).Elem().Type().Field(i).Tag {
+ case `dns:"a"`:
+ // TODO(miek): Hmm store this as 16 bytes
+ if d.Len() < net.IPv6len {
+ return net.IPv4(byte(d.Index(0).Uint()),
+ byte(d.Index(1).Uint()),
+ byte(d.Index(2).Uint()),
+ byte(d.Index(3).Uint())).String()
+ }
+ return net.IPv4(byte(d.Index(12).Uint()),
+ byte(d.Index(13).Uint()),
+ byte(d.Index(14).Uint()),
+ byte(d.Index(15).Uint())).String()
+ case `dns:"aaaa"`:
+ return net.IP{
+ byte(d.Index(0).Uint()),
+ byte(d.Index(1).Uint()),
+ byte(d.Index(2).Uint()),
+ byte(d.Index(3).Uint()),
+ byte(d.Index(4).Uint()),
+ byte(d.Index(5).Uint()),
+ byte(d.Index(6).Uint()),
+ byte(d.Index(7).Uint()),
+ byte(d.Index(8).Uint()),
+ byte(d.Index(9).Uint()),
+ byte(d.Index(10).Uint()),
+ byte(d.Index(11).Uint()),
+ byte(d.Index(12).Uint()),
+ byte(d.Index(13).Uint()),
+ byte(d.Index(14).Uint()),
+ byte(d.Index(15).Uint()),
+ }.String()
+ case `dns:"nsec"`:
+ if d.Len() == 0 {
+ return ""
+ }
+ s := Type(d.Index(0).Uint()).String()
+ for i := 1; i < d.Len(); i++ {
+ s += " " + Type(d.Index(i).Uint()).String()
+ }
+ return s
+ case `dns:"wks"`:
+ if d.Len() == 0 {
+ return ""
+ }
+ s := strconv.Itoa(int(d.Index(0).Uint()))
+ for i := 0; i < d.Len(); i++ {
+ s += " " + strconv.Itoa(int(d.Index(i).Uint()))
+ }
+ return s
+ default:
+ // if it does not have a tag its a string slice
+ fallthrough
+ case `dns:"txt"`:
+ if d.Len() == 0 {
+ return ""
+ }
+ s := d.Index(0).String()
+ for i := 1; i < d.Len(); i++ {
+ s += " " + d.Index(i).String()
+ }
+ return s
+ }
+ }
+ return ""
+}
diff --git a/vendor/github.com/miekg/dns/labels.go b/vendor/github.com/miekg/dns/labels.go
new file mode 100644
index 0000000..3944dd0
--- /dev/null
+++ b/vendor/github.com/miekg/dns/labels.go
@@ -0,0 +1,162 @@
+package dns
+
+// Holds a bunch of helper functions for dealing with labels.
+
+// SplitDomainName splits a name string into it's labels.
+// www.miek.nl. returns []string{"www", "miek", "nl"}
+// The root label (.) returns nil. Note that using
+// strings.Split(s) will work in most cases, but does not handle
+// escaped dots (\.) for instance.
+func SplitDomainName(s string) (labels []string) {
+ if len(s) == 0 {
+ return nil
+ }
+ fqdnEnd := 0 // offset of the final '.' or the length of the name
+ idx := Split(s)
+ begin := 0
+ if s[len(s)-1] == '.' {
+ fqdnEnd = len(s) - 1
+ } else {
+ fqdnEnd = len(s)
+ }
+
+ switch len(idx) {
+ case 0:
+ return nil
+ case 1:
+ // no-op
+ default:
+ end := 0
+ for i := 1; i < len(idx); i++ {
+ end = idx[i]
+ labels = append(labels, s[begin:end-1])
+ begin = end
+ }
+ }
+
+ labels = append(labels, s[begin:fqdnEnd])
+ return labels
+}
+
+// CompareDomainName compares the names s1 and s2 and
+// returns how many labels they have in common starting from the *right*.
+// The comparison stops at the first inequality. The names are not downcased
+// before the comparison.
+//
+// www.miek.nl. and miek.nl. have two labels in common: miek and nl
+// www.miek.nl. and www.bla.nl. have one label in common: nl
+func CompareDomainName(s1, s2 string) (n int) {
+ s1 = Fqdn(s1)
+ s2 = Fqdn(s2)
+ l1 := Split(s1)
+ l2 := Split(s2)
+
+ // the first check: root label
+ if l1 == nil || l2 == nil {
+ return
+ }
+
+ j1 := len(l1) - 1 // end
+ i1 := len(l1) - 2 // start
+ j2 := len(l2) - 1
+ i2 := len(l2) - 2
+ // the second check can be done here: last/only label
+ // before we fall through into the for-loop below
+ if s1[l1[j1]:] == s2[l2[j2]:] {
+ n++
+ } else {
+ return
+ }
+ for {
+ if i1 < 0 || i2 < 0 {
+ break
+ }
+ if s1[l1[i1]:l1[j1]] == s2[l2[i2]:l2[j2]] {
+ n++
+ } else {
+ break
+ }
+ j1--
+ i1--
+ j2--
+ i2--
+ }
+ return
+}
+
+// CountLabel counts the the number of labels in the string s.
+func CountLabel(s string) (labels int) {
+ if s == "." {
+ return
+ }
+ off := 0
+ end := false
+ for {
+ off, end = NextLabel(s, off)
+ labels++
+ if end {
+ return
+ }
+ }
+}
+
+// Split splits a name s into its label indexes.
+// www.miek.nl. returns []int{0, 4, 9}, www.miek.nl also returns []int{0, 4, 9}.
+// The root name (.) returns nil. Also see SplitDomainName.
+func Split(s string) []int {
+ if s == "." {
+ return nil
+ }
+ idx := make([]int, 1, 3)
+ off := 0
+ end := false
+
+ for {
+ off, end = NextLabel(s, off)
+ if end {
+ return idx
+ }
+ idx = append(idx, off)
+ }
+}
+
+// NextLabel returns the index of the start of the next label in the
+// string s starting at offset.
+// The bool end is true when the end of the string has been reached.
+// Also see PrevLabel.
+func NextLabel(s string, offset int) (i int, end bool) {
+ quote := false
+ for i = offset; i < len(s)-1; i++ {
+ switch s[i] {
+ case '\\':
+ quote = !quote
+ default:
+ quote = false
+ case '.':
+ if quote {
+ quote = !quote
+ continue
+ }
+ return i + 1, false
+ }
+ }
+ return i + 1, true
+}
+
+// PrevLabel returns the index of the label when starting from the right and
+// jumping n labels to the left.
+// The bool start is true when the start of the string has been overshot.
+// Also see NextLabel.
+func PrevLabel(s string, n int) (i int, start bool) {
+ if n == 0 {
+ return len(s), false
+ }
+ lab := Split(s)
+ if lab == nil {
+ return 0, true
+ }
+ if n > len(lab) {
+ return 0, true
+ }
+ return lab[len(lab)-n], false
+}
diff --git a/vendor/github.com/miekg/dns/msg.go b/vendor/github.com/miekg/dns/msg.go
new file mode 100644
index 0000000..73ffb61
--- /dev/null
+++ b/vendor/github.com/miekg/dns/msg.go
@@ -0,0 +1,1945 @@
+// DNS packet assembly, see RFC 1035. Converting from - Unpack() -
+// and to - Pack() - wire format.
+// All the packers and unpackers take a (msg []byte, off int)
+// and return (off1 int, ok bool). If they return ok==false, they
+// also return off1==len(msg), so that the next unpacker will
+// also fail. This lets us avoid checks of ok until the end of a
+// packing sequence.
+
+package dns
+
+import (
+ "encoding/base32"
+ "encoding/base64"
+ "encoding/hex"
+ "math/big"
+ "math/rand"
+ "net"
+ "reflect"
+ "strconv"
+ "time"
+)
+
+const maxCompressionOffset = 2 << 13 // We have 14 bits for the compression pointer
+
+var (
+ // ErrAlg indicates an error with the (DNSSEC) algorithm.
+ ErrAlg error = &Error{err: "bad algorithm"}
+ // ErrAuth indicates an error in the TSIG authentication.
+ ErrAuth error = &Error{err: "bad authentication"}
+ // ErrBuf indicates that the buffer used it too small for the message.
+ ErrBuf error = &Error{err: "buffer size too small"}
+ // ErrConnEmpty indicates a connection is being uses before it is initialized.
+ ErrConnEmpty error = &Error{err: "conn has no connection"}
+ // ErrExtendedRcode ...
+ ErrExtendedRcode error = &Error{err: "bad extended rcode"}
+ // ErrFqdn indicates that a domain name does not have a closing dot.
+ ErrFqdn error = &Error{err: "domain must be fully qualified"}
+ // ErrId indicates there is a mismatch with the message's ID.
+ ErrId error = &Error{err: "id mismatch"}
+ // ErrKeyAlg indicates that the algorithm in the key is not valid.
+ ErrKeyAlg error = &Error{err: "bad key algorithm"}
+ ErrKey error = &Error{err: "bad key"}
+ ErrKeySize error = &Error{err: "bad key size"}
+ ErrNoSig error = &Error{err: "no signature found"}
+ ErrPrivKey error = &Error{err: "bad private key"}
+ ErrRcode error = &Error{err: "bad rcode"}
+ ErrRdata error = &Error{err: "bad rdata"}
+ ErrRRset error = &Error{err: "bad rrset"}
+ ErrSecret error = &Error{err: "no secrets defined"}
+ ErrShortRead error = &Error{err: "short read"}
+ // ErrSig indicates that a signature can not be cryptographically validated.
+ ErrSig error = &Error{err: "bad signature"}
+ // ErrSOA indicates that no SOA RR was seen when doing zone transfers.
+ ErrSoa error = &Error{err: "no SOA"}
+ // ErrTime indicates a timing error in TSIG authentication.
+ ErrTime error = &Error{err: "bad time"}
+ // ErrTruncated indicates that we failed to unpack a truncated message.
+ // We unpacked as much as we had so Msg can still be used, if desired.
+ ErrTruncated error = &Error{err: "failed to unpack truncated message"}
+)
+
+// Id, by default, returns a 16 bits random number to be used as a
+// message id. The random provided should be good enough. This being a
+// variable the function can be reassigned to a custom function.
+// For instance, to make it return a static value:
+//
+// dns.Id = func() uint16 { return 3 }
+var Id func() uint16 = id
+
+// MsgHdr is a a manually-unpacked version of (id, bits).
+type MsgHdr struct {
+ Id uint16
+ Response bool
+ Opcode int
+ Authoritative bool
+ Truncated bool
+ RecursionDesired bool
+ RecursionAvailable bool
+ Zero bool
+ AuthenticatedData bool
+ CheckingDisabled bool
+ Rcode int
+}
+
+// Msg contains the layout of a DNS message.
+type Msg struct {
+ MsgHdr
+ Compress bool `json:"-"` // If true, the message will be compressed when converted to wire format. This not part of the official DNS packet format.
+ Question []Question // Holds the RR(s) of the question section.
+ Answer []RR // Holds the RR(s) of the answer section.
+ Ns []RR // Holds the RR(s) of the authority section.
+ Extra []RR // Holds the RR(s) of the additional section.
+}
+
+// StringToType is the reverse of TypeToString, needed for string parsing.
+var StringToType = reverseInt16(TypeToString)
+
+// StringToClass is the reverse of ClassToString, needed for string parsing.
+var StringToClass = reverseInt16(ClassToString)
+
+// Map of opcodes strings.
+var StringToOpcode = reverseInt(OpcodeToString)
+
+// Map of rcodes strings.
+var StringToRcode = reverseInt(RcodeToString)
+
+// ClassToString is a maps Classes to strings for each CLASS wire type.
+var ClassToString = map[uint16]string{
+ ClassINET: "IN",
+ ClassCSNET: "CS",
+ ClassCHAOS: "CH",
+ ClassHESIOD: "HS",
+ ClassNONE: "NONE",
+ ClassANY: "ANY",
+}
+
+// OpcodeToString maps Opcodes to strings.
+var OpcodeToString = map[int]string{
+ OpcodeQuery: "QUERY",
+ OpcodeIQuery: "IQUERY",
+ OpcodeStatus: "STATUS",
+ OpcodeNotify: "NOTIFY",
+ OpcodeUpdate: "UPDATE",
+}
+
+// RcodeToString maps Rcodes to strings.
+var RcodeToString = map[int]string{
+ RcodeSuccess: "NOERROR",
+ RcodeFormatError: "FORMERR",
+ RcodeServerFailure: "SERVFAIL",
+ RcodeNameError: "NXDOMAIN",
+ RcodeNotImplemented: "NOTIMPL",
+ RcodeRefused: "REFUSED",
+ RcodeYXDomain: "YXDOMAIN", // From RFC 2136
+ RcodeYXRrset: "YXRRSET",
+ RcodeNXRrset: "NXRRSET",
+ RcodeNotAuth: "NOTAUTH",
+ RcodeNotZone: "NOTZONE",
+ RcodeBadSig: "BADSIG", // Also known as RcodeBadVers, see RFC 6891
+ // RcodeBadVers: "BADVERS",
+ RcodeBadKey: "BADKEY",
+ RcodeBadTime: "BADTIME",
+ RcodeBadMode: "BADMODE",
+ RcodeBadName: "BADNAME",
+ RcodeBadAlg: "BADALG",
+ RcodeBadTrunc: "BADTRUNC",
+}
+
+// Rather than write the usual handful of routines to pack and
+// unpack every message that can appear on the wire, we use
+// reflection to write a generic pack/unpack for structs and then
+// use it. Thus, if in the future we need to define new message
+// structs, no new pack/unpack/printing code needs to be written.
+
+// Domain names are a sequence of counted strings
+// split at the dots. They end with a zero-length string.
+
+// PackDomainName packs a domain name s into msg[off:].
+// If compression is wanted compress must be true and the compression
+// map needs to hold a mapping between domain names and offsets
+// pointing into msg.
+func PackDomainName(s string, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
+ off1, _, err = packDomainName(s, msg, off, compression, compress)
+ return
+}
+
+func packDomainName(s string, msg []byte, off int, compression map[string]int, compress bool) (off1 int, labels int, err error) {
+ // special case if msg == nil
+ lenmsg := 256
+ if msg != nil {
+ lenmsg = len(msg)
+ }
+ ls := len(s)
+ if ls == 0 { // Ok, for instance when dealing with update RR without any rdata.
+ return off, 0, nil
+ }
+ // If not fully qualified, error out, but only if msg == nil #ugly
+ switch {
+ case msg == nil:
+ if s[ls-1] != '.' {
+ s += "."
+ ls++
+ }
+ case msg != nil:
+ if s[ls-1] != '.' {
+ return lenmsg, 0, ErrFqdn
+ }
+ }
+ // Each dot ends a segment of the name.
+ // We trade each dot byte for a length byte.
+ // Except for escaped dots (\.), which are normal dots.
+ // There is also a trailing zero.
+
+ // Compression
+ nameoffset := -1
+ pointer := -1
+ // Emit sequence of counted strings, chopping at dots.
+ begin := 0
+ bs := []byte(s)
+ roBs, bsFresh, escapedDot := s, true, false
+ for i := 0; i < ls; i++ {
+ if bs[i] == '\\' {
+ for j := i; j < ls-1; j++ {
+ bs[j] = bs[j+1]
+ }
+ ls--
+ if off+1 > lenmsg {
+ return lenmsg, labels, ErrBuf
+ }
+ // check for \DDD
+ if i+2 < ls && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
+ bs[i] = dddToByte(bs[i:])
+ for j := i + 1; j < ls-2; j++ {
+ bs[j] = bs[j+2]
+ }
+ ls -= 2
+ } else if bs[i] == 't' {
+ bs[i] = '\t'
+ } else if bs[i] == 'r' {
+ bs[i] = '\r'
+ } else if bs[i] == 'n' {
+ bs[i] = '\n'
+ }
+ escapedDot = bs[i] == '.'
+ bsFresh = false
+ continue
+ }
+
+ if bs[i] == '.' {
+ if i > 0 && bs[i-1] == '.' && !escapedDot {
+ // two dots back to back is not legal
+ return lenmsg, labels, ErrRdata
+ }
+ if i-begin >= 1<<6 { // top two bits of length must be clear
+ return lenmsg, labels, ErrRdata
+ }
+ // off can already (we're in a loop) be bigger than len(msg)
+ // this happens when a name isn't fully qualified
+ if off+1 > lenmsg {
+ return lenmsg, labels, ErrBuf
+ }
+ if msg != nil {
+ msg[off] = byte(i - begin)
+ }
+ offset := off
+ off++
+ for j := begin; j < i; j++ {
+ if off+1 > lenmsg {
+ return lenmsg, labels, ErrBuf
+ }
+ if msg != nil {
+ msg[off] = bs[j]
+ }
+ off++
+ }
+ if compress && !bsFresh {
+ roBs = string(bs)
+ bsFresh = true
+ }
+ // Dont try to compress '.'
+ if compress && roBs[begin:] != "." {
+ if p, ok := compression[roBs[begin:]]; !ok {
+ // Only offsets smaller than this can be used.
+ if offset < maxCompressionOffset {
+ compression[roBs[begin:]] = offset
+ }
+ } else {
+ // The first hit is the longest matching dname
+ // keep the pointer offset we get back and store
+ // the offset of the current name, because that's
+ // where we need to insert the pointer later
+
+ // If compress is true, we're allowed to compress this dname
+ if pointer == -1 && compress {
+ pointer = p // Where to point to
+ nameoffset = offset // Where to point from
+ break
+ }
+ }
+ }
+ labels++
+ begin = i + 1
+ }
+ escapedDot = false
+ }
+ // Root label is special
+ if len(bs) == 1 && bs[0] == '.' {
+ return off, labels, nil
+ }
+ // If we did compression and we find something add the pointer here
+ if pointer != -1 {
+ // We have two bytes (14 bits) to put the pointer in
+ // if msg == nil, we will never do compression
+ msg[nameoffset], msg[nameoffset+1] = packUint16(uint16(pointer ^ 0xC000))
+ off = nameoffset + 1
+ goto End
+ }
+ if msg != nil {
+ msg[off] = 0
+ }
+End:
+ off++
+ return off, labels, nil
+}
+
+// Unpack a domain name.
+// In addition to the simple sequences of counted strings above,
+// domain names are allowed to refer to strings elsewhere in the
+// packet, to avoid repeating common suffixes when returning
+// many entries in a single domain. The pointers are marked
+// by a length byte with the top two bits set. Ignoring those
+// two bits, that byte and the next give a 14 bit offset from msg[0]
+// where we should pick up the trail.
+// Note that if we jump elsewhere in the packet,
+// we return off1 == the offset after the first pointer we found,
+// which is where the next record will start.
+// In theory, the pointers are only allowed to jump backward.
+// We let them jump anywhere and stop jumping after a while.
+
+// UnpackDomainName unpacks a domain name into a string.
+func UnpackDomainName(msg []byte, off int) (string, int, error) {
+ s := make([]byte, 0, 64)
+ off1 := 0
+ lenmsg := len(msg)
+ ptr := 0 // number of pointers followed
+Loop:
+ for {
+ if off >= lenmsg {
+ return "", lenmsg, ErrBuf
+ }
+ c := int(msg[off])
+ off++
+ switch c & 0xC0 {
+ case 0x00:
+ if c == 0x00 {
+ // end of name
+ break Loop
+ }
+ // literal string
+ if off+c > lenmsg {
+ return "", lenmsg, ErrBuf
+ }
+ for j := off; j < off+c; j++ {
+ switch b := msg[j]; b {
+ case '.', '(', ')', ';', ' ', '@':
+ fallthrough
+ case '"', '\\':
+ s = append(s, '\\', b)
+ case '\t':
+ s = append(s, '\\', 't')
+ case '\r':
+ s = append(s, '\\', 'r')
+ default:
+ if b < 32 || b >= 127 { // unprintable use \DDD
+ var buf [3]byte
+ bufs := strconv.AppendInt(buf[:0], int64(b), 10)
+ s = append(s, '\\')
+ for i := 0; i < 3-len(bufs); i++ {
+ s = append(s, '0')
+ }
+ for _, r := range bufs {
+ s = append(s, r)
+ }
+ } else {
+ s = append(s, b)
+ }
+ }
+ }
+ s = append(s, '.')
+ off += c
+ case 0xC0:
+ // pointer to somewhere else in msg.
+ // remember location after first ptr,
+ // since that's how many bytes we consumed.
+ // also, don't follow too many pointers --
+ // maybe there's a loop.
+ if off >= lenmsg {
+ return "", lenmsg, ErrBuf
+ }
+ c1 := msg[off]
+ off++
+ if ptr == 0 {
+ off1 = off
+ }
+ if ptr++; ptr > 10 {
+ return "", lenmsg, &Error{err: "too many compression pointers"}
+ }
+ off = (c^0xC0)<<8 | int(c1)
+ default:
+ // 0x80 and 0x40 are reserved
+ return "", lenmsg, ErrRdata
+ }
+ }
+ if ptr == 0 {
+ off1 = off
+ }
+ if len(s) == 0 {
+ s = []byte(".")
+ }
+ return string(s), off1, nil
+}
+
+func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) {
+ var err error
+ if len(txt) == 0 {
+ if offset >= len(msg) {
+ return offset, ErrBuf
+ }
+ msg[offset] = 0
+ return offset, nil
+ }
+ for i := range txt {
+ if len(txt[i]) > len(tmp) {
+ return offset, ErrBuf
+ }
+ offset, err = packTxtString(txt[i], msg, offset, tmp)
+ if err != nil {
+ return offset, err
+ }
+ }
+ return offset, err
+}
+
+func packTxtString(s string, msg []byte, offset int, tmp []byte) (int, error) {
+ lenByteOffset := offset
+ if offset >= len(msg) {
+ return offset, ErrBuf
+ }
+ offset++
+ bs := tmp[:len(s)]
+ copy(bs, s)
+ for i := 0; i < len(bs); i++ {
+ if len(msg) <= offset {
+ return offset, ErrBuf
+ }
+ if bs[i] == '\\' {
+ i++
+ if i == len(bs) {
+ break
+ }
+ // check for \DDD
+ if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
+ msg[offset] = dddToByte(bs[i:])
+ i += 2
+ } else if bs[i] == 't' {
+ msg[offset] = '\t'
+ } else if bs[i] == 'r' {
+ msg[offset] = '\r'
+ } else if bs[i] == 'n' {
+ msg[offset] = '\n'
+ } else {
+ msg[offset] = bs[i]
+ }
+ } else {
+ msg[offset] = bs[i]
+ }
+ offset++
+ }
+ l := offset - lenByteOffset - 1
+ if l > 255 {
+ return offset, &Error{err: "string exceeded 255 bytes in txt"}
+ }
+ msg[lenByteOffset] = byte(l)
+ return offset, nil
+}
+
+func packOctetString(s string, msg []byte, offset int, tmp []byte) (int, error) {
+ if offset >= len(msg) {
+ return offset, ErrBuf
+ }
+ bs := tmp[:len(s)]
+ copy(bs, s)
+ for i := 0; i < len(bs); i++ {
+ if len(msg) <= offset {
+ return offset, ErrBuf
+ }
+ if bs[i] == '\\' {
+ i++
+ if i == len(bs) {
+ break
+ }
+ // check for \DDD
+ if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
+ msg[offset] = dddToByte(bs[i:])
+ i += 2
+ } else {
+ msg[offset] = bs[i]
+ }
+ } else {
+ msg[offset] = bs[i]
+ }
+ offset++
+ }
+ return offset, nil
+}
+
+func unpackTxt(msg []byte, off0 int) (ss []string, off int, err error) {
+ off = off0
+ var s string
+ for off < len(msg) && err == nil {
+ s, off, err = unpackTxtString(msg, off)
+ if err == nil {
+ ss = append(ss, s)
+ }
+ }
+ return
+}
+
+func unpackTxtString(msg []byte, offset int) (string, int, error) {
+ if offset+1 > len(msg) {
+ return "", offset, &Error{err: "overflow unpacking txt"}
+ }
+ l := int(msg[offset])
+ if offset+l+1 > len(msg) {
+ return "", offset, &Error{err: "overflow unpacking txt"}
+ }
+ s := make([]byte, 0, l)
+ for _, b := range msg[offset+1 : offset+1+l] {
+ switch b {
+ case '"', '\\':
+ s = append(s, '\\', b)
+ case '\t':
+ s = append(s, `\t`...)
+ case '\r':
+ s = append(s, `\r`...)
+ case '\n':
+ s = append(s, `\n`...)
+ default:
+ if b < 32 || b > 127 { // unprintable
+ var buf [3]byte
+ bufs := strconv.AppendInt(buf[:0], int64(b), 10)
+ s = append(s, '\\')
+ for i := 0; i < 3-len(bufs); i++ {
+ s = append(s, '0')
+ }
+ for _, r := range bufs {
+ s = append(s, r)
+ }
+ } else {
+ s = append(s, b)
+ }
+ }
+ }
+ offset += 1 + l
+ return string(s), offset, nil
+}
+
+// Pack a reflect.StructValue into msg. Struct members can only be uint8, uint16, uint32, string,
+// slices and other (often anonymous) structs.
+func packStructValue(val reflect.Value, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
+ var txtTmp []byte
+ lenmsg := len(msg)
+ numfield := val.NumField()
+ for i := 0; i < numfield; i++ {
+ typefield := val.Type().Field(i)
+ if typefield.Tag == `dns:"-"` {
+ continue
+ }
+ switch fv := val.Field(i); fv.Kind() {
+ default:
+ return lenmsg, &Error{err: "bad kind packing"}
+ case reflect.Interface:
+ // PrivateRR is the only RR implementation that has interface field.
+ // therefore it's expected that this interface would be PrivateRdata
+ switch data := fv.Interface().(type) {
+ case PrivateRdata:
+ n, err := data.Pack(msg[off:])
+ if err != nil {
+ return lenmsg, err
+ }
+ off += n
+ default:
+ return lenmsg, &Error{err: "bad kind interface packing"}
+ }
+ case reflect.Slice:
+ switch typefield.Tag {
+ default:
+ return lenmsg, &Error{"bad tag packing slice: " + typefield.Tag.Get("dns")}
+ case `dns:"domain-name"`:
+ for j := 0; j < val.Field(i).Len(); j++ {
+ element := val.Field(i).Index(j).String()
+ off, err = PackDomainName(element, msg, off, compression, false && compress)
+ if err != nil {
+ return lenmsg, err
+ }
+ }
+ case `dns:"txt"`:
+ if txtTmp == nil {
+ txtTmp = make([]byte, 256*4+1)
+ }
+ off, err = packTxt(fv.Interface().([]string), msg, off, txtTmp)
+ if err != nil {
+ return lenmsg, err
+ }
+ case `dns:"opt"`: // edns
+ for j := 0; j < val.Field(i).Len(); j++ {
+ element := val.Field(i).Index(j).Interface()
+ b, e := element.(EDNS0).pack()
+ if e != nil {
+ return lenmsg, &Error{err: "overflow packing opt"}
+ }
+ // Option code
+ msg[off], msg[off+1] = packUint16(element.(EDNS0).Option())
+ // Length
+ msg[off+2], msg[off+3] = packUint16(uint16(len(b)))
+ off += 4
+ if off+len(b) > lenmsg {
+ copy(msg[off:], b)
+ off = lenmsg
+ continue
+ }
+ // Actual data
+ copy(msg[off:off+len(b)], b)
+ off += len(b)
+ }
+ case `dns:"a"`:
+ if val.Type().String() == "dns.IPSECKEY" {
+ // Field(2) is GatewayType, must be 1
+ if val.Field(2).Uint() != 1 {
+ continue
+ }
+ }
+ // It must be a slice of 4, even if it is 16, we encode
+ // only the first 4
+ if off+net.IPv4len > lenmsg {
+ return lenmsg, &Error{err: "overflow packing a"}
+ }
+ switch fv.Len() {
+ case net.IPv6len:
+ msg[off] = byte(fv.Index(12).Uint())
+ msg[off+1] = byte(fv.Index(13).Uint())
+ msg[off+2] = byte(fv.Index(14).Uint())
+ msg[off+3] = byte(fv.Index(15).Uint())
+ off += net.IPv4len
+ case net.IPv4len:
+ msg[off] = byte(fv.Index(0).Uint())
+ msg[off+1] = byte(fv.Index(1).Uint())
+ msg[off+2] = byte(fv.Index(2).Uint())
+ msg[off+3] = byte(fv.Index(3).Uint())
+ off += net.IPv4len
+ case 0:
+ // Allowed, for dynamic updates
+ default:
+ return lenmsg, &Error{err: "overflow packing a"}
+ }
+ case `dns:"aaaa"`:
+ if val.Type().String() == "dns.IPSECKEY" {
+ // Field(2) is GatewayType, must be 2
+ if val.Field(2).Uint() != 2 {
+ continue
+ }
+ }
+ if fv.Len() == 0 {
+ break
+ }
+ if fv.Len() > net.IPv6len || off+fv.Len() > lenmsg {
+ return lenmsg, &Error{err: "overflow packing aaaa"}
+ }
+ for j := 0; j < net.IPv6len; j++ {
+ msg[off] = byte(fv.Index(j).Uint())
+ off++
+ }
+ case `dns:"wks"`:
+ // TODO(miek): this is wrong should be lenrd
+ if off == lenmsg {
+ break // dyn. updates
+ }
+ if val.Field(i).Len() == 0 {
+ break
+ }
+ off1 := off
+ for j := 0; j < val.Field(i).Len(); j++ {
+ serv := int(fv.Index(j).Uint())
+ if off+serv/8+1 > len(msg) {
+ return len(msg), &Error{err: "overflow packing wks"}
+ }
+ msg[off+serv/8] |= byte(1 << (7 - uint(serv%8)))
+ if off+serv/8+1 > off1 {
+ off1 = off + serv/8 + 1
+ }
+ }
+ off = off1
+ case `dns:"nsec"`: // NSEC/NSEC3
+ // This is the uint16 type bitmap
+ if val.Field(i).Len() == 0 {
+ // Do absolutely nothing
+ break
+ }
+ var lastwindow, lastlength uint16
+ for j := 0; j < val.Field(i).Len(); j++ {
+ t := uint16(fv.Index(j).Uint())
+ window := t / 256
+ length := (t-window*256)/8 + 1
+ if window > lastwindow && lastlength != 0 {
+ // New window, jump to the new offset
+ off += int(lastlength) + 2
+ lastlength = 0
+ }
+ if window < lastwindow || length < lastlength {
+ return len(msg), &Error{err: "nsec bits out of order"}
+ }
+ if off+2+int(length) > len(msg) {
+ return len(msg), &Error{err: "overflow packing nsec"}
+ }
+ // Setting the window #
+ msg[off] = byte(window)
+ // Setting the octets length
+ msg[off+1] = byte(length)
+ // Setting the bit value for the type in the right octet
+ msg[off+1+int(length)] |= byte(1 << (7 - (t % 8)))
+ lastwindow, lastlength = window, length
+ }
+ off += int(lastlength) + 2
+ }
+ case reflect.Struct:
+ off, err = packStructValue(fv, msg, off, compression, compress)
+ if err != nil {
+ return lenmsg, err
+ }
+ case reflect.Uint8:
+ if off+1 > lenmsg {
+ return lenmsg, &Error{err: "overflow packing uint8"}
+ }
+ msg[off] = byte(fv.Uint())
+ off++
+ case reflect.Uint16:
+ if off+2 > lenmsg {
+ return lenmsg, &Error{err: "overflow packing uint16"}
+ }
+ i := fv.Uint()
+ msg[off] = byte(i >> 8)
+ msg[off+1] = byte(i)
+ off += 2
+ case reflect.Uint32:
+ if off+4 > lenmsg {
+ return lenmsg, &Error{err: "overflow packing uint32"}
+ }
+ i := fv.Uint()
+ msg[off] = byte(i >> 24)
+ msg[off+1] = byte(i >> 16)
+ msg[off+2] = byte(i >> 8)
+ msg[off+3] = byte(i)
+ off += 4
+ case reflect.Uint64:
+ switch typefield.Tag {
+ default:
+ if off+8 > lenmsg {
+ return lenmsg, &Error{err: "overflow packing uint64"}
+ }
+ i := fv.Uint()
+ msg[off] = byte(i >> 56)
+ msg[off+1] = byte(i >> 48)
+ msg[off+2] = byte(i >> 40)
+ msg[off+3] = byte(i >> 32)
+ msg[off+4] = byte(i >> 24)
+ msg[off+5] = byte(i >> 16)
+ msg[off+6] = byte(i >> 8)
+ msg[off+7] = byte(i)
+ off += 8
+ case `dns:"uint48"`:
+ // Used in TSIG, where it stops at 48 bits, so we discard the upper 16
+ if off+6 > lenmsg {
+ return lenmsg, &Error{err: "overflow packing uint64 as uint48"}
+ }
+ i := fv.Uint()
+ msg[off] = byte(i >> 40)
+ msg[off+1] = byte(i >> 32)
+ msg[off+2] = byte(i >> 24)
+ msg[off+3] = byte(i >> 16)
+ msg[off+4] = byte(i >> 8)
+ msg[off+5] = byte(i)
+ off += 6
+ }
+ case reflect.String:
+ // There are multiple string encodings.
+ // The tag distinguishes ordinary strings from domain names.
+ s := fv.String()
+ switch typefield.Tag {
+ default:
+ return lenmsg, &Error{"bad tag packing string: " + typefield.Tag.Get("dns")}
+ case `dns:"base64"`:
+ b64, e := fromBase64([]byte(s))
+ if e != nil {
+ return lenmsg, e
+ }
+ copy(msg[off:off+len(b64)], b64)
+ off += len(b64)
+ case `dns:"domain-name"`:
+ if val.Type().String() == "dns.IPSECKEY" {
+ // Field(2) is GatewayType, 1 and 2 or used for addresses
+ x := val.Field(2).Uint()
+ if x == 1 || x == 2 {
+ continue
+ }
+ }
+ if off, err = PackDomainName(s, msg, off, compression, false && compress); err != nil {
+ return lenmsg, err
+ }
+ case `dns:"cdomain-name"`:
+ if off, err = PackDomainName(s, msg, off, compression, true && compress); err != nil {
+ return lenmsg, err
+ }
+ case `dns:"size-base32"`:
+ // This is purely for NSEC3 atm, the previous byte must
+ // holds the length of the encoded string. As NSEC3
+ // is only defined to SHA1, the hashlength is 20 (160 bits)
+ msg[off-1] = 20
+ fallthrough
+ case `dns:"base32"`:
+ b32, e := fromBase32([]byte(s))
+ if e != nil {
+ return lenmsg, e
+ }
+ copy(msg[off:off+len(b32)], b32)
+ off += len(b32)
+ case `dns:"size-hex"`:
+ fallthrough
+ case `dns:"hex"`:
+ // There is no length encoded here
+ h, e := hex.DecodeString(s)
+ if e != nil {
+ return lenmsg, e
+ }
+ if off+hex.DecodedLen(len(s)) > lenmsg {
+ return lenmsg, &Error{err: "overflow packing hex"}
+ }
+ copy(msg[off:off+hex.DecodedLen(len(s))], h)
+ off += hex.DecodedLen(len(s))
+ case `dns:"size"`:
+ // the size is already encoded in the RR, we can safely use the
+ // length of string. String is RAW (not encoded in hex, nor base64)
+ copy(msg[off:off+len(s)], s)
+ off += len(s)
+ case `dns:"octet"`:
+ bytesTmp := make([]byte, 256)
+ off, err = packOctetString(fv.String(), msg, off, bytesTmp)
+ if err != nil {
+ return lenmsg, err
+ }
+ case `dns:"txt"`:
+ fallthrough
+ case "":
+ if txtTmp == nil {
+ txtTmp = make([]byte, 256*4+1)
+ }
+ off, err = packTxtString(fv.String(), msg, off, txtTmp)
+ if err != nil {
+ return lenmsg, err
+ }
+ }
+ }
+ }
+ return off, nil
+}
+
+func structValue(any interface{}) reflect.Value {
+ return reflect.ValueOf(any).Elem()
+}
+
+// PackStruct packs any structure to wire format.
+func PackStruct(any interface{}, msg []byte, off int) (off1 int, err error) {
+ off, err = packStructValue(structValue(any), msg, off, nil, false)
+ return off, err
+}
+
+func packStructCompress(any interface{}, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
+ off, err = packStructValue(structValue(any), msg, off, compression, compress)
+ return off, err
+}
+
+// Unpack a reflect.StructValue from msg.
+// Same restrictions as packStructValue.
+func unpackStructValue(val reflect.Value, msg []byte, off int) (off1 int, err error) {
+ lenmsg := len(msg)
+ for i := 0; i < val.NumField(); i++ {
+ if off > lenmsg {
+ return lenmsg, &Error{"bad offset unpacking"}
+ }
+ switch fv := val.Field(i); fv.Kind() {
+ default:
+ return lenmsg, &Error{err: "bad kind unpacking"}
+ case reflect.Interface:
+ // PrivateRR is the only RR implementation that has interface field.
+ // therefore it's expected that this interface would be PrivateRdata
+ switch data := fv.Interface().(type) {
+ case PrivateRdata:
+ n, err := data.Unpack(msg[off:])
+ if err != nil {
+ return lenmsg, err
+ }
+ off += n
+ default:
+ return lenmsg, &Error{err: "bad kind interface unpacking"}
+ }
+ case reflect.Slice:
+ switch val.Type().Field(i).Tag {
+ default:
+ return lenmsg, &Error{"bad tag unpacking slice: " + val.Type().Field(i).Tag.Get("dns")}
+ case `dns:"domain-name"`:
+ // HIP record slice of name (or none)
+ var servers []string
+ var s string
+ for off < lenmsg {
+ s, off, err = UnpackDomainName(msg, off)
+ if err != nil {
+ return lenmsg, err
+ }
+ servers = append(servers, s)
+ }
+ fv.Set(reflect.ValueOf(servers))
+ case `dns:"txt"`:
+ if off == lenmsg {
+ break
+ }
+ var txt []string
+ txt, off, err = unpackTxt(msg, off)
+ if err != nil {
+ return lenmsg, err
+ }
+ fv.Set(reflect.ValueOf(txt))
+ case `dns:"opt"`: // edns0
+ if off == lenmsg {
+ // This is an EDNS0 (OPT Record) with no rdata
+ // We can safely return here.
+ break
+ }
+ var edns []EDNS0
+ Option:
+ code := uint16(0)
+ if off+4 > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking opt"}
+ }
+ code, off = unpackUint16(msg, off)
+ optlen, off1 := unpackUint16(msg, off)
+ if off1+int(optlen) > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking opt"}
+ }
+ switch code {
+ case EDNS0NSID:
+ e := new(EDNS0_NSID)
+ if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
+ return lenmsg, err
+ }
+ edns = append(edns, e)
+ off = off1 + int(optlen)
+ case EDNS0SUBNET, EDNS0SUBNETDRAFT:
+ e := new(EDNS0_SUBNET)
+ if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
+ return lenmsg, err
+ }
+ edns = append(edns, e)
+ off = off1 + int(optlen)
+ if code == EDNS0SUBNETDRAFT {
+ e.DraftOption = true
+ }
+ case EDNS0UL:
+ e := new(EDNS0_UL)
+ if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
+ return lenmsg, err
+ }
+ edns = append(edns, e)
+ off = off1 + int(optlen)
+ case EDNS0LLQ:
+ e := new(EDNS0_LLQ)
+ if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
+ return lenmsg, err
+ }
+ edns = append(edns, e)
+ off = off1 + int(optlen)
+ case EDNS0DAU:
+ e := new(EDNS0_DAU)
+ if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
+ return lenmsg, err
+ }
+ edns = append(edns, e)
+ off = off1 + int(optlen)
+ case EDNS0DHU:
+ e := new(EDNS0_DHU)
+ if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
+ return lenmsg, err
+ }
+ edns = append(edns, e)
+ off = off1 + int(optlen)
+ case EDNS0N3U:
+ e := new(EDNS0_N3U)
+ if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
+ return lenmsg, err
+ }
+ edns = append(edns, e)
+ off = off1 + int(optlen)
+ default:
+ e := new(EDNS0_LOCAL)
+ e.Code = code
+ if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
+ return lenmsg, err
+ }
+ edns = append(edns, e)
+ off = off1 + int(optlen)
+ }
+ if off < lenmsg {
+ goto Option
+ }
+ fv.Set(reflect.ValueOf(edns))
+ case `dns:"a"`:
+ if val.Type().String() == "dns.IPSECKEY" {
+ // Field(2) is GatewayType, must be 1
+ if val.Field(2).Uint() != 1 {
+ continue
+ }
+ }
+ if off == lenmsg {
+ break // dyn. update
+ }
+ if off+net.IPv4len > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking a"}
+ }
+ fv.Set(reflect.ValueOf(net.IPv4(msg[off], msg[off+1], msg[off+2], msg[off+3])))
+ off += net.IPv4len
+ case `dns:"aaaa"`:
+ if val.Type().String() == "dns.IPSECKEY" {
+ // Field(2) is GatewayType, must be 2
+ if val.Field(2).Uint() != 2 {
+ continue
+ }
+ }
+ if off == lenmsg {
+ break
+ }
+ if off+net.IPv6len > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking aaaa"}
+ }
+ fv.Set(reflect.ValueOf(net.IP{msg[off], msg[off+1], msg[off+2], msg[off+3], msg[off+4],
+ msg[off+5], msg[off+6], msg[off+7], msg[off+8], msg[off+9], msg[off+10],
+ msg[off+11], msg[off+12], msg[off+13], msg[off+14], msg[off+15]}))
+ off += net.IPv6len
+ case `dns:"wks"`:
+ // Rest of the record is the bitmap
+ var serv []uint16
+ j := 0
+ for off < lenmsg {
+ if off+1 > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking wks"}
+ }
+ b := msg[off]
+ // Check the bits one by one, and set the type
+ if b&0x80 == 0x80 {
+ serv = append(serv, uint16(j*8+0))
+ }
+ if b&0x40 == 0x40 {
+ serv = append(serv, uint16(j*8+1))
+ }
+ if b&0x20 == 0x20 {
+ serv = append(serv, uint16(j*8+2))
+ }
+ if b&0x10 == 0x10 {
+ serv = append(serv, uint16(j*8+3))
+ }
+ if b&0x8 == 0x8 {
+ serv = append(serv, uint16(j*8+4))
+ }
+ if b&0x4 == 0x4 {
+ serv = append(serv, uint16(j*8+5))
+ }
+ if b&0x2 == 0x2 {
+ serv = append(serv, uint16(j*8+6))
+ }
+ if b&0x1 == 0x1 {
+ serv = append(serv, uint16(j*8+7))
+ }
+ j++
+ off++
+ }
+ fv.Set(reflect.ValueOf(serv))
+ case `dns:"nsec"`: // NSEC/NSEC3
+ if off == len(msg) {
+ break
+ }
+ // Rest of the record is the type bitmap
+ var nsec []uint16
+ length := 0
+ window := 0
+ lastwindow := -1
+ for off < len(msg) {
+ if off+2 > len(msg) {
+ return len(msg), &Error{err: "overflow unpacking nsecx"}
+ }
+ window = int(msg[off])
+ length = int(msg[off+1])
+ off += 2
+ if window <= lastwindow {
+ // RFC 4034: Blocks are present in the NSEC RR RDATA in
+ // increasing numerical order.
+ return len(msg), &Error{err: "out of order NSEC block"}
+ }
+ if length == 0 {
+ // RFC 4034: Blocks with no types present MUST NOT be included.
+ return len(msg), &Error{err: "empty NSEC block"}
+ }
+ if length > 32 {
+ return len(msg), &Error{err: "NSEC block too long"}
+ }
+ if off+length > len(msg) {
+ return len(msg), &Error{err: "overflowing NSEC block"}
+ }
+
+ // Walk the bytes in the window and extract the type bits
+ for j := 0; j < length; j++ {
+ b := msg[off+j]
+ // Check the bits one by one, and set the type
+ if b&0x80 == 0x80 {
+ nsec = append(nsec, uint16(window*256+j*8+0))
+ }
+ if b&0x40 == 0x40 {
+ nsec = append(nsec, uint16(window*256+j*8+1))
+ }
+ if b&0x20 == 0x20 {
+ nsec = append(nsec, uint16(window*256+j*8+2))
+ }
+ if b&0x10 == 0x10 {
+ nsec = append(nsec, uint16(window*256+j*8+3))
+ }
+ if b&0x8 == 0x8 {
+ nsec = append(nsec, uint16(window*256+j*8+4))
+ }
+ if b&0x4 == 0x4 {
+ nsec = append(nsec, uint16(window*256+j*8+5))
+ }
+ if b&0x2 == 0x2 {
+ nsec = append(nsec, uint16(window*256+j*8+6))
+ }
+ if b&0x1 == 0x1 {
+ nsec = append(nsec, uint16(window*256+j*8+7))
+ }
+ }
+ off += length
+ lastwindow = window
+ }
+ fv.Set(reflect.ValueOf(nsec))
+ }
+ case reflect.Struct:
+ off, err = unpackStructValue(fv, msg, off)
+ if err != nil {
+ return lenmsg, err
+ }
+ if val.Type().Field(i).Name == "Hdr" {
+ lenrd := off + int(val.FieldByName("Hdr").FieldByName("Rdlength").Uint())
+ if lenrd > lenmsg {
+ return lenmsg, &Error{err: "overflowing header size"}
+ }
+ msg = msg[:lenrd]
+ lenmsg = len(msg)
+ }
+ case reflect.Uint8:
+ if off == lenmsg {
+ break
+ }
+ if off+1 > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking uint8"}
+ }
+ fv.SetUint(uint64(uint8(msg[off])))
+ off++
+ case reflect.Uint16:
+ if off == lenmsg {
+ break
+ }
+ var i uint16
+ if off+2 > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking uint16"}
+ }
+ i, off = unpackUint16(msg, off)
+ fv.SetUint(uint64(i))
+ case reflect.Uint32:
+ if off == lenmsg {
+ break
+ }
+ if off+4 > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking uint32"}
+ }
+ fv.SetUint(uint64(uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3])))
+ off += 4
+ case reflect.Uint64:
+ if off == lenmsg {
+ break
+ }
+ switch val.Type().Field(i).Tag {
+ default:
+ if off+8 > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking uint64"}
+ }
+ fv.SetUint(uint64(uint64(msg[off])<<56 | uint64(msg[off+1])<<48 | uint64(msg[off+2])<<40 |
+ uint64(msg[off+3])<<32 | uint64(msg[off+4])<<24 | uint64(msg[off+5])<<16 | uint64(msg[off+6])<<8 | uint64(msg[off+7])))
+ off += 8
+ case `dns:"uint48"`:
+ // Used in TSIG where the last 48 bits are occupied, so for now, assume a uint48 (6 bytes)
+ if off+6 > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking uint64 as uint48"}
+ }
+ fv.SetUint(uint64(uint64(msg[off])<<40 | uint64(msg[off+1])<<32 | uint64(msg[off+2])<<24 | uint64(msg[off+3])<<16 |
+ uint64(msg[off+4])<<8 | uint64(msg[off+5])))
+ off += 6
+ }
+ case reflect.String:
+ var s string
+ if off == lenmsg {
+ break
+ }
+ switch val.Type().Field(i).Tag {
+ default:
+ return lenmsg, &Error{"bad tag unpacking string: " + val.Type().Field(i).Tag.Get("dns")}
+ case `dns:"octet"`:
+ s = string(msg[off:])
+ off = lenmsg
+ case `dns:"hex"`:
+ hexend := lenmsg
+ if val.FieldByName("Hdr").FieldByName("Rrtype").Uint() == uint64(TypeHIP) {
+ hexend = off + int(val.FieldByName("HitLength").Uint())
+ }
+ if hexend > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking HIP hex"}
+ }
+ s = hex.EncodeToString(msg[off:hexend])
+ off = hexend
+ case `dns:"base64"`:
+ // Rest of the RR is base64 encoded value
+ b64end := lenmsg
+ if val.FieldByName("Hdr").FieldByName("Rrtype").Uint() == uint64(TypeHIP) {
+ b64end = off + int(val.FieldByName("PublicKeyLength").Uint())
+ }
+ if b64end > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking HIP base64"}
+ }
+ s = toBase64(msg[off:b64end])
+ off = b64end
+ case `dns:"cdomain-name"`:
+ fallthrough
+ case `dns:"domain-name"`:
+ if val.Type().String() == "dns.IPSECKEY" {
+ // Field(2) is GatewayType, 1 and 2 or used for addresses
+ x := val.Field(2).Uint()
+ if x == 1 || x == 2 {
+ continue
+ }
+ }
+ if off == lenmsg && int(val.FieldByName("Hdr").FieldByName("Rdlength").Uint()) == 0 {
+ // zero rdata is ok for dyn updates, but only if rdlength is 0
+ break
+ }
+ s, off, err = UnpackDomainName(msg, off)
+ if err != nil {
+ return lenmsg, err
+ }
+ case `dns:"size-base32"`:
+ var size int
+ switch val.Type().Name() {
+ case "NSEC3":
+ switch val.Type().Field(i).Name {
+ case "NextDomain":
+ name := val.FieldByName("HashLength")
+ size = int(name.Uint())
+ }
+ }
+ if off+size > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking base32"}
+ }
+ s = toBase32(msg[off : off+size])
+ off += size
+ case `dns:"size-hex"`:
+ // a "size" string, but it must be encoded in hex in the string
+ var size int
+ switch val.Type().Name() {
+ case "NSEC3":
+ switch val.Type().Field(i).Name {
+ case "Salt":
+ name := val.FieldByName("SaltLength")
+ size = int(name.Uint())
+ case "NextDomain":
+ name := val.FieldByName("HashLength")
+ size = int(name.Uint())
+ }
+ case "TSIG":
+ switch val.Type().Field(i).Name {
+ case "MAC":
+ name := val.FieldByName("MACSize")
+ size = int(name.Uint())
+ case "OtherData":
+ name := val.FieldByName("OtherLen")
+ size = int(name.Uint())
+ }
+ }
+ if off+size > lenmsg {
+ return lenmsg, &Error{err: "overflow unpacking hex"}
+ }
+ s = hex.EncodeToString(msg[off : off+size])
+ off += size
+ case `dns:"txt"`:
+ fallthrough
+ case "":
+ s, off, err = unpackTxtString(msg, off)
+ }
+ fv.SetString(s)
+ }
+ }
+ return off, nil
+}
+
+// Helpers for dealing with escaped bytes
+func isDigit(b byte) bool { return b >= '0' && b <= '9' }
+
+func dddToByte(s []byte) byte {
+ return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0'))
+}
+
+// UnpackStruct unpacks a binary message from offset off to the interface
+// value given.
+func UnpackStruct(any interface{}, msg []byte, off int) (int, error) {
+ return unpackStructValue(structValue(any), msg, off)
+}
+
+// Helper function for packing and unpacking
+func intToBytes(i *big.Int, length int) []byte {
+ buf := i.Bytes()
+ if len(buf) < length {
+ b := make([]byte, length)
+ copy(b[length-len(buf):], buf)
+ return b
+ }
+ return buf
+}
+
+func unpackUint16(msg []byte, off int) (uint16, int) {
+ return uint16(msg[off])<<8 | uint16(msg[off+1]), off + 2
+}
+
+func packUint16(i uint16) (byte, byte) {
+ return byte(i >> 8), byte(i)
+}
+
+func toBase32(b []byte) string {
+ return base32.HexEncoding.EncodeToString(b)
+}
+
+func fromBase32(s []byte) (buf []byte, err error) {
+ buflen := base32.HexEncoding.DecodedLen(len(s))
+ buf = make([]byte, buflen)
+ n, err := base32.HexEncoding.Decode(buf, s)
+ buf = buf[:n]
+ return
+}
+
+func toBase64(b []byte) string {
+ return base64.StdEncoding.EncodeToString(b)
+}
+
+func fromBase64(s []byte) (buf []byte, err error) {
+ buflen := base64.StdEncoding.DecodedLen(len(s))
+ buf = make([]byte, buflen)
+ n, err := base64.StdEncoding.Decode(buf, s)
+ buf = buf[:n]
+ return
+}
+
+// PackRR packs a resource record rr into msg[off:].
+// See PackDomainName for documentation about the compression.
+func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
+ if rr == nil {
+ return len(msg), &Error{err: "nil rr"}
+ }
+
+ off1, err = packStructCompress(rr, msg, off, compression, compress)
+ if err != nil {
+ return len(msg), err
+ }
+ if rawSetRdlength(msg, off, off1) {
+ return off1, nil
+ }
+ return off, ErrRdata
+}
+
+// UnpackRR unpacks msg[off:] into an RR.
+func UnpackRR(msg []byte, off int) (rr RR, off1 int, err error) {
+ // unpack just the header, to find the rr type and length
+ var h RR_Header
+ off0 := off
+ if off, err = UnpackStruct(&h, msg, off); err != nil {
+ return nil, len(msg), err
+ }
+ end := off + int(h.Rdlength)
+ // make an rr of that type and re-unpack.
+ mk, known := TypeToRR[h.Rrtype]
+ if !known {
+ rr = new(RFC3597)
+ } else {
+ rr = mk()
+ }
+ off, err = UnpackStruct(rr, msg, off0)
+ if off != end {
+ return &h, end, &Error{err: "bad rdlength"}
+ }
+ return rr, off, err
+}
+
+// unpackRRslice unpacks msg[off:] into an []RR.
+// If we cannot unpack the whole array, then it will return nil
+func unpackRRslice(l int, msg []byte, off int) (dst1 []RR, off1 int, err error) {
+ var r RR
+ // Optimistically make dst be the length that was sent
+ dst := make([]RR, 0, l)
+ for i := 0; i < l; i++ {
+ off1 := off
+ r, off, err = UnpackRR(msg, off)
+ if err != nil {
+ off = len(msg)
+ break
+ }
+ // If offset does not increase anymore, l is a lie
+ if off1 == off {
+ l = i
+ break
+ }
+ dst = append(dst, r)
+ }
+ if err != nil && off == len(msg) {
+ dst = nil
+ }
+ return dst, off, err
+}
+
+// Reverse a map
+func reverseInt8(m map[uint8]string) map[string]uint8 {
+ n := make(map[string]uint8)
+ for u, s := range m {
+ n[s] = u
+ }
+ return n
+}
+
+func reverseInt16(m map[uint16]string) map[string]uint16 {
+ n := make(map[string]uint16)
+ for u, s := range m {
+ n[s] = u
+ }
+ return n
+}
+
+func reverseInt(m map[int]string) map[string]int {
+ n := make(map[string]int)
+ for u, s := range m {
+ n[s] = u
+ }
+ return n
+}
+
+// Convert a MsgHdr to a string, with dig-like headers:
+//
+//;; opcode: QUERY, status: NOERROR, id: 48404
+//
+//;; flags: qr aa rd ra;
+func (h *MsgHdr) String() string {
+ if h == nil {
+ return "<nil> MsgHdr"
+ }
+
+ s := ";; opcode: " + OpcodeToString[h.Opcode]
+ s += ", status: " + RcodeToString[h.Rcode]
+ s += ", id: " + strconv.Itoa(int(h.Id)) + "\n"
+
+ s += ";; flags:"
+ if h.Response {
+ s += " qr"
+ }
+ if h.Authoritative {
+ s += " aa"
+ }
+ if h.Truncated {
+ s += " tc"
+ }
+ if h.RecursionDesired {
+ s += " rd"
+ }
+ if h.RecursionAvailable {
+ s += " ra"
+ }
+ if h.Zero { // Hmm
+ s += " z"
+ }
+ if h.AuthenticatedData {
+ s += " ad"
+ }
+ if h.CheckingDisabled {
+ s += " cd"
+ }
+
+ s += ";"
+ return s
+}
+
+// Pack packs a Msg: it is converted to to wire format.
+// If the dns.Compress is true the message will be in compressed wire format.
+func (dns *Msg) Pack() (msg []byte, err error) {
+ return dns.PackBuffer(nil)
+}
+
+// PackBuffer packs a Msg, using the given buffer buf. If buf is too small
+// a new buffer is allocated.
+func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error) {
+ var dh Header
+ var compression map[string]int
+ if dns.Compress {
+ compression = make(map[string]int) // Compression pointer mappings
+ }
+
+ if dns.Rcode < 0 || dns.Rcode > 0xFFF {
+ return nil, ErrRcode
+ }
+ if dns.Rcode > 0xF {
+ // Regular RCODE field is 4 bits
+ opt := dns.IsEdns0()
+ if opt == nil {
+ return nil, ErrExtendedRcode
+ }
+ opt.SetExtendedRcode(uint8(dns.Rcode >> 4))
+ dns.Rcode &= 0xF
+ }
+
+ // Convert convenient Msg into wire-like Header.
+ dh.Id = dns.Id
+ dh.Bits = uint16(dns.Opcode)<<11 | uint16(dns.Rcode)
+ if dns.Response {
+ dh.Bits |= _QR
+ }
+ if dns.Authoritative {
+ dh.Bits |= _AA
+ }
+ if dns.Truncated {
+ dh.Bits |= _TC
+ }
+ if dns.RecursionDesired {
+ dh.Bits |= _RD
+ }
+ if dns.RecursionAvailable {
+ dh.Bits |= _RA
+ }
+ if dns.Zero {
+ dh.Bits |= _Z
+ }
+ if dns.AuthenticatedData {
+ dh.Bits |= _AD
+ }
+ if dns.CheckingDisabled {
+ dh.Bits |= _CD
+ }
+
+ // Prepare variable sized arrays.
+ question := dns.Question
+ answer := dns.Answer
+ ns := dns.Ns
+ extra := dns.Extra
+
+ dh.Qdcount = uint16(len(question))
+ dh.Ancount = uint16(len(answer))
+ dh.Nscount = uint16(len(ns))
+ dh.Arcount = uint16(len(extra))
+
+ // We need the uncompressed length here, because we first pack it and then compress it.
+ msg = buf
+ compress := dns.Compress
+ dns.Compress = false
+ if packLen := dns.Len() + 1; len(msg) < packLen {
+ msg = make([]byte, packLen)
+ }
+ dns.Compress = compress
+
+ // Pack it in: header and then the pieces.
+ off := 0
+ off, err = packStructCompress(&dh, msg, off, compression, dns.Compress)
+ if err != nil {
+ return nil, err
+ }
+ for i := 0; i < len(question); i++ {
+ off, err = packStructCompress(&question[i], msg, off, compression, dns.Compress)
+ if err != nil {
+ return nil, err
+ }
+ }
+ for i := 0; i < len(answer); i++ {
+ off, err = PackRR(answer[i], msg, off, compression, dns.Compress)
+ if err != nil {
+ return nil, err
+ }
+ }
+ for i := 0; i < len(ns); i++ {
+ off, err = PackRR(ns[i], msg, off, compression, dns.Compress)
+ if err != nil {
+ return nil, err
+ }
+ }
+ for i := 0; i < len(extra); i++ {
+ off, err = PackRR(extra[i], msg, off, compression, dns.Compress)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return msg[:off], nil
+}
+
+// Unpack unpacks a binary message to a Msg structure.
+func (dns *Msg) Unpack(msg []byte) (err error) {
+ // Header.
+ var dh Header
+ off := 0
+ if off, err = UnpackStruct(&dh, msg, off); err != nil {
+ return err
+ }
+ dns.Id = dh.Id
+ dns.Response = (dh.Bits & _QR) != 0
+ dns.Opcode = int(dh.Bits>>11) & 0xF
+ dns.Authoritative = (dh.Bits & _AA) != 0
+ dns.Truncated = (dh.Bits & _TC) != 0
+ dns.RecursionDesired = (dh.Bits & _RD) != 0
+ dns.RecursionAvailable = (dh.Bits & _RA) != 0
+ dns.Zero = (dh.Bits & _Z) != 0
+ dns.AuthenticatedData = (dh.Bits & _AD) != 0
+ dns.CheckingDisabled = (dh.Bits & _CD) != 0
+ dns.Rcode = int(dh.Bits & 0xF)
+
+ // Optimistically use the count given to us in the header
+ dns.Question = make([]Question, 0, int(dh.Qdcount))
+
+ var q Question
+ for i := 0; i < int(dh.Qdcount); i++ {
+ off1 := off
+ off, err = UnpackStruct(&q, msg, off)
+ if err != nil {
+ // Even if Truncated is set, we only will set ErrTruncated if we
+ // actually got the questions
+ return err
+ }
+ if off1 == off { // Offset does not increase anymore, dh.Qdcount is a lie!
+ dh.Qdcount = uint16(i)
+ break
+ }
+ dns.Question = append(dns.Question, q)
+ }
+
+ dns.Answer, off, err = unpackRRslice(int(dh.Ancount), msg, off)
+ // The header counts might have been wrong so we need to update it
+ dh.Ancount = uint16(len(dns.Answer))
+ if err == nil {
+ dns.Ns, off, err = unpackRRslice(int(dh.Nscount), msg, off)
+ }
+ // The header counts might have been wrong so we need to update it
+ dh.Nscount = uint16(len(dns.Ns))
+ if err == nil {
+ dns.Extra, off, err = unpackRRslice(int(dh.Arcount), msg, off)
+ }
+ // The header counts might have been wrong so we need to update it
+ dh.Arcount = uint16(len(dns.Extra))
+ if off != len(msg) {
+ // TODO(miek) make this an error?
+ // use PackOpt to let people tell how detailed the error reporting should be?
+ // println("dns: extra bytes in dns packet", off, "<", len(msg))
+ } else if dns.Truncated {
+ // Whether we ran into a an error or not, we want to return that it
+ // was truncated
+ err = ErrTruncated
+ }
+ return err
+}
+
+// Convert a complete message to a string with dig-like output.
+func (dns *Msg) String() string {
+ if dns == nil {
+ return "<nil> MsgHdr"
+ }
+ s := dns.MsgHdr.String() + " "
+ s += "QUERY: " + strconv.Itoa(len(dns.Question)) + ", "
+ s += "ANSWER: " + strconv.Itoa(len(dns.Answer)) + ", "
+ s += "AUTHORITY: " + strconv.Itoa(len(dns.Ns)) + ", "
+ s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n"
+ if len(dns.Question) > 0 {
+ s += "\n;; QUESTION SECTION:\n"
+ for i := 0; i < len(dns.Question); i++ {
+ s += dns.Question[i].String() + "\n"
+ }
+ }
+ if len(dns.Answer) > 0 {
+ s += "\n;; ANSWER SECTION:\n"
+ for i := 0; i < len(dns.Answer); i++ {
+ if dns.Answer[i] != nil {
+ s += dns.Answer[i].String() + "\n"
+ }
+ }
+ }
+ if len(dns.Ns) > 0 {
+ s += "\n;; AUTHORITY SECTION:\n"
+ for i := 0; i < len(dns.Ns); i++ {
+ if dns.Ns[i] != nil {
+ s += dns.Ns[i].String() + "\n"
+ }
+ }
+ }
+ if len(dns.Extra) > 0 {
+ s += "\n;; ADDITIONAL SECTION:\n"
+ for i := 0; i < len(dns.Extra); i++ {
+ if dns.Extra[i] != nil {
+ s += dns.Extra[i].String() + "\n"
+ }
+ }
+ }
+ return s
+}
+
+// Len returns the message length when in (un)compressed wire format.
+// If dns.Compress is true compression it is taken into account. Len()
+// is provided to be a faster way to get the size of the resulting packet,
+// than packing it, measuring the size and discarding the buffer.
+func (dns *Msg) Len() int {
+ // We always return one more than needed.
+ l := 12 // Message header is always 12 bytes
+ var compression map[string]int
+ if dns.Compress {
+ compression = make(map[string]int)
+ }
+ for i := 0; i < len(dns.Question); i++ {
+ l += dns.Question[i].len()
+ if dns.Compress {
+ compressionLenHelper(compression, dns.Question[i].Name)
+ }
+ }
+ for i := 0; i < len(dns.Answer); i++ {
+ l += dns.Answer[i].len()
+ if dns.Compress {
+ k, ok := compressionLenSearch(compression, dns.Answer[i].Header().Name)
+ if ok {
+ l += 1 - k
+ }
+ compressionLenHelper(compression, dns.Answer[i].Header().Name)
+ k, ok = compressionLenSearchType(compression, dns.Answer[i])
+ if ok {
+ l += 1 - k
+ }
+ compressionLenHelperType(compression, dns.Answer[i])
+ }
+ }
+ for i := 0; i < len(dns.Ns); i++ {
+ l += dns.Ns[i].len()
+ if dns.Compress {
+ k, ok := compressionLenSearch(compression, dns.Ns[i].Header().Name)
+ if ok {
+ l += 1 - k
+ }
+ compressionLenHelper(compression, dns.Ns[i].Header().Name)
+ k, ok = compressionLenSearchType(compression, dns.Ns[i])
+ if ok {
+ l += 1 - k
+ }
+ compressionLenHelperType(compression, dns.Ns[i])
+ }
+ }
+ for i := 0; i < len(dns.Extra); i++ {
+ l += dns.Extra[i].len()
+ if dns.Compress {
+ k, ok := compressionLenSearch(compression, dns.Extra[i].Header().Name)
+ if ok {
+ l += 1 - k
+ }
+ compressionLenHelper(compression, dns.Extra[i].Header().Name)
+ k, ok = compressionLenSearchType(compression, dns.Extra[i])
+ if ok {
+ l += 1 - k
+ }
+ compressionLenHelperType(compression, dns.Extra[i])
+ }
+ }
+ return l
+}
+
+// Put the parts of the name in the compression map.
+func compressionLenHelper(c map[string]int, s string) {
+ pref := ""
+ lbs := Split(s)
+ for j := len(lbs) - 1; j >= 0; j-- {
+ pref = s[lbs[j]:]
+ if _, ok := c[pref]; !ok {
+ c[pref] = len(pref)
+ }
+ }
+}
+
+// Look for each part in the compression map and returns its length,
+// keep on searching so we get the longest match.
+func compressionLenSearch(c map[string]int, s string) (int, bool) {
+ off := 0
+ end := false
+ if s == "" { // don't bork on bogus data
+ return 0, false
+ }
+ for {
+ if _, ok := c[s[off:]]; ok {
+ return len(s[off:]), true
+ }
+ if end {
+ break
+ }
+ off, end = NextLabel(s, off)
+ }
+ return 0, false
+}
+
+// TODO(miek): should add all types, because the all can be *used* for compression.
+func compressionLenHelperType(c map[string]int, r RR) {
+ switch x := r.(type) {
+ case *NS:
+ compressionLenHelper(c, x.Ns)
+ case *MX:
+ compressionLenHelper(c, x.Mx)
+ case *CNAME:
+ compressionLenHelper(c, x.Target)
+ case *PTR:
+ compressionLenHelper(c, x.Ptr)
+ case *SOA:
+ compressionLenHelper(c, x.Ns)
+ compressionLenHelper(c, x.Mbox)
+ case *MB:
+ compressionLenHelper(c, x.Mb)
+ case *MG:
+ compressionLenHelper(c, x.Mg)
+ case *MR:
+ compressionLenHelper(c, x.Mr)
+ case *MF:
+ compressionLenHelper(c, x.Mf)
+ case *MD:
+ compressionLenHelper(c, x.Md)
+ case *RT:
+ compressionLenHelper(c, x.Host)
+ case *MINFO:
+ compressionLenHelper(c, x.Rmail)
+ compressionLenHelper(c, x.Email)
+ case *AFSDB:
+ compressionLenHelper(c, x.Hostname)
+ }
+}
+
+// Only search on compressing these types.
+func compressionLenSearchType(c map[string]int, r RR) (int, bool) {
+ switch x := r.(type) {
+ case *NS:
+ return compressionLenSearch(c, x.Ns)
+ case *MX:
+ return compressionLenSearch(c, x.Mx)
+ case *CNAME:
+ return compressionLenSearch(c, x.Target)
+ case *PTR:
+ return compressionLenSearch(c, x.Ptr)
+ case *SOA:
+ k, ok := compressionLenSearch(c, x.Ns)
+ k1, ok1 := compressionLenSearch(c, x.Mbox)
+ if !ok && !ok1 {
+ return 0, false
+ }
+ return k + k1, true
+ case *MB:
+ return compressionLenSearch(c, x.Mb)
+ case *MG:
+ return compressionLenSearch(c, x.Mg)
+ case *MR:
+ return compressionLenSearch(c, x.Mr)
+ case *MF:
+ return compressionLenSearch(c, x.Mf)
+ case *MD:
+ return compressionLenSearch(c, x.Md)
+ case *RT:
+ return compressionLenSearch(c, x.Host)
+ case *MINFO:
+ k, ok := compressionLenSearch(c, x.Rmail)
+ k1, ok1 := compressionLenSearch(c, x.Email)
+ if !ok && !ok1 {
+ return 0, false
+ }
+ return k + k1, true
+ case *AFSDB:
+ return compressionLenSearch(c, x.Hostname)
+ }
+ return 0, false
+}
+
+// id returns a 16 bits random number to be used as a
+// message id. The random provided should be good enough.
+func id() uint16 {
+ return uint16(rand.Int()) ^ uint16(time.Now().Nanosecond())
+}
+
+// Copy returns a new RR which is a deep-copy of r.
+func Copy(r RR) RR {
+ r1 := r.copy()
+ return r1
+}
+
+// Copy returns a new *Msg which is a deep-copy of dns.
+func (dns *Msg) Copy() *Msg {
+ return dns.CopyTo(new(Msg))
+}
+
+// CopyTo copies the contents to the provided message using a deep-copy and returns the copy.
+func (dns *Msg) CopyTo(r1 *Msg) *Msg {
+ r1.MsgHdr = dns.MsgHdr
+ r1.Compress = dns.Compress
+
+ if len(dns.Question) > 0 {
+ r1.Question = make([]Question, len(dns.Question))
+ copy(r1.Question, dns.Question) // TODO(miek): Question is an immutable value, ok to do a shallow-copy
+ }
+
+ rrArr := make([]RR, len(dns.Answer)+len(dns.Ns)+len(dns.Extra))
+ var rri int
+
+ if len(dns.Answer) > 0 {
+ rrbegin := rri
+ for i := 0; i < len(dns.Answer); i++ {
+ rrArr[rri] = dns.Answer[i].copy()
+ rri++
+ }
+ r1.Answer = rrArr[rrbegin:rri:rri]
+ }
+
+ if len(dns.Ns) > 0 {
+ rrbegin := rri
+ for i := 0; i < len(dns.Ns); i++ {
+ rrArr[rri] = dns.Ns[i].copy()
+ rri++
+ }
+ r1.Ns = rrArr[rrbegin:rri:rri]
+ }
+
+ if len(dns.Extra) > 0 {
+ rrbegin := rri
+ for i := 0; i < len(dns.Extra); i++ {
+ rrArr[rri] = dns.Extra[i].copy()
+ rri++
+ }
+ r1.Extra = rrArr[rrbegin:rri:rri]
+ }
+
+ return r1
+}
diff --git a/vendor/github.com/miekg/dns/nsecx.go b/vendor/github.com/miekg/dns/nsecx.go
new file mode 100644
index 0000000..d2392c6
--- /dev/null
+++ b/vendor/github.com/miekg/dns/nsecx.go
@@ -0,0 +1,112 @@
+package dns
+
+import (
+ "crypto/sha1"
+ "hash"
+ "io"
+ "strings"
+)
+
+type saltWireFmt struct {
+ Salt string `dns:"size-hex"`
+}
+
+// HashName hashes a string (label) according to RFC 5155. It returns the hashed string in
+// uppercase.
+func HashName(label string, ha uint8, iter uint16, salt string) string {
+ saltwire := new(saltWireFmt)
+ saltwire.Salt = salt
+ wire := make([]byte, DefaultMsgSize)
+ n, err := PackStruct(saltwire, wire, 0)
+ if err != nil {
+ return ""
+ }
+ wire = wire[:n]
+ name := make([]byte, 255)
+ off, err := PackDomainName(strings.ToLower(label), name, 0, nil, false)
+ if err != nil {
+ return ""
+ }
+ name = name[:off]
+ var s hash.Hash
+ switch ha {
+ case SHA1:
+ s = sha1.New()
+ default:
+ return ""
+ }
+
+ // k = 0
+ name = append(name, wire...)
+ io.WriteString(s, string(name))
+ nsec3 := s.Sum(nil)
+ // k > 0
+ for k := uint16(0); k < iter; k++ {
+ s.Reset()
+ nsec3 = append(nsec3, wire...)
+ io.WriteString(s, string(nsec3))
+ nsec3 = s.Sum(nil)
+ }
+ return toBase32(nsec3)
+}
+
+// Denialer is an interface that should be implemented by types that are used to denial
+// answers in DNSSEC.
+type Denialer interface {
+ // Cover will check if the (unhashed) name is being covered by this NSEC or NSEC3.
+ Cover(name string) bool
+ // Match will check if the ownername matches the (unhashed) name for this NSEC3 or NSEC3.
+ Match(name string) bool
+}
+
+// Cover implements the Denialer interface.
+func (rr *NSEC) Cover(name string) bool {
+ return true
+}
+
+// Match implements the Denialer interface.
+func (rr *NSEC) Match(name string) bool {
+ return true
+}
+
+// Cover implements the Denialer interface.
+func (rr *NSEC3) Cover(name string) bool {
+ // FIXME(miek): check if the zones match
+ // FIXME(miek): check if we're not dealing with parent nsec3
+ hname := HashName(name, rr.Hash, rr.Iterations, rr.Salt)
+ labels := Split(rr.Hdr.Name)
+ if len(labels) < 2 {
+ return false
+ }
+ hash := strings.ToUpper(rr.Hdr.Name[labels[0] : labels[1]-1]) // -1 to remove the dot
+ if hash == rr.NextDomain {
+ return false // empty interval
+ }
+ if hash > rr.NextDomain { // last name, points to apex
+ // hname > hash
+ // hname > rr.NextDomain
+ // TODO(miek)
+ }
+ if hname <= hash {
+ return false
+ }
+ if hname >= rr.NextDomain {
+ return false
+ }
+ return true
+}
+
+// Match implements the Denialer interface.
+func (rr *NSEC3) Match(name string) bool {
+ // FIXME(miek): Check if we are in the same zone
+ hname := HashName(name, rr.Hash, rr.Iterations, rr.Salt)
+ labels := Split(rr.Hdr.Name)
+ if len(labels) < 2 {
+ return false
+ }
+ hash := strings.ToUpper(rr.Hdr.Name[labels[0] : labels[1]-1]) // -1 to remove the .
+ if hash == hname {
+ return true
+ }
+ return false
+}
diff --git a/vendor/github.com/miekg/dns/privaterr.go b/vendor/github.com/miekg/dns/privaterr.go
new file mode 100644
index 0000000..c78f885
--- /dev/null
+++ b/vendor/github.com/miekg/dns/privaterr.go
@@ -0,0 +1,117 @@
+package dns
+
+import (
+ "fmt"
+ "strings"
+)
+
+// PrivateRdata is an interface used for implementing "Private Use" RR types, see
+// RFC 6895. This allows one to experiment with new RR types, without requesting an
+// official type code. Also see dns.PrivateHandle and dns.PrivateHandleRemove.
+type PrivateRdata interface {
+ // String returns the text presentaton of the Rdata of the Private RR.
+ String() string
+ // Parse parses the Rdata of the private RR.
+ Parse([]string) error
+ // Pack is used when packing a private RR into a buffer.
+ Pack([]byte) (int, error)
+ // Unpack is used when unpacking a private RR from a buffer.
+ // TODO(miek): diff. signature than Pack, see edns0.go for instance.
+ Unpack([]byte) (int, error)
+ // Copy copies the Rdata.
+ Copy(PrivateRdata) error
+ // Len returns the length in octets of the Rdata.
+ Len() int
+}
+
+// PrivateRR represents an RR that uses a PrivateRdata user-defined type.
+// It mocks normal RRs and implements dns.RR interface.
+type PrivateRR struct {
+ Hdr RR_Header
+ Data PrivateRdata
+}
+
+func mkPrivateRR(rrtype uint16) *PrivateRR {
+ // Panics if RR is not an instance of PrivateRR.
+ rrfunc, ok := TypeToRR[rrtype]
+ if !ok {
+ panic(fmt.Sprintf("dns: invalid operation with Private RR type %d", rrtype))
+ }
+
+ anyrr := rrfunc()
+ switch rr := anyrr.(type) {
+ case *PrivateRR:
+ return rr
+ }
+ panic(fmt.Sprintf("dns: RR is not a PrivateRR, TypeToRR[%d] generator returned %T", rrtype, anyrr))
+}
+
+// Header return the RR header of r.
+func (r *PrivateRR) Header() *RR_Header { return &r.Hdr }
+
+func (r *PrivateRR) String() string { return r.Hdr.String() + r.Data.String() }
+
+// Private len and copy parts to satisfy RR interface.
+func (r *PrivateRR) len() int { return r.Hdr.len() + r.Data.Len() }
+func (r *PrivateRR) copy() RR {
+ // make new RR like this:
+ rr := mkPrivateRR(r.Hdr.Rrtype)
+ newh := r.Hdr.copyHeader()
+ rr.Hdr = *newh
+
+ err := r.Data.Copy(rr.Data)
+ if err != nil {
+ panic("dns: got value that could not be used to copy Private rdata")
+ }
+ return rr
+}
+
+// PrivateHandle registers a private resource record type. It requires
+// string and numeric representation of private RR type and generator function as argument.
+func PrivateHandle(rtypestr string, rtype uint16, generator func() PrivateRdata) {
+ rtypestr = strings.ToUpper(rtypestr)
+
+ TypeToRR[rtype] = func() RR { return &PrivateRR{RR_Header{}, generator()} }
+ TypeToString[rtype] = rtypestr
+ StringToType[rtypestr] = rtype
+
+ setPrivateRR := func(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := mkPrivateRR(h.Rrtype)
+ rr.Hdr = h
+
+ var l lex
+ text := make([]string, 0, 2) // could be 0..N elements, median is probably 1
+ FETCH:
+ for {
+ // TODO(miek): we could also be returning _QUOTE, this might or might not
+ // be an issue (basically parsing TXT becomes hard)
+ switch l = <-c; l.value {
+ case zNewline, zEOF:
+ break FETCH
+ case zString:
+ text = append(text, l.token)
+ }
+ }
+
+ err := rr.Data.Parse(text)
+ if err != nil {
+ return nil, &ParseError{f, err.Error(), l}, ""
+ }
+
+ return rr, nil, ""
+ }
+
+ typeToparserFunc[rtype] = parserFunc{setPrivateRR, true}
+}
+
+// PrivateHandleRemove removes defenitions required to support private RR type.
+func PrivateHandleRemove(rtype uint16) {
+ rtypestr, ok := TypeToString[rtype]
+ if ok {
+ delete(TypeToRR, rtype)
+ delete(TypeToString, rtype)
+ delete(typeToparserFunc, rtype)
+ delete(StringToType, rtypestr)
+ }
+ return
+}
diff --git a/vendor/github.com/miekg/dns/rawmsg.go b/vendor/github.com/miekg/dns/rawmsg.go
new file mode 100644
index 0000000..f138b77
--- /dev/null
+++ b/vendor/github.com/miekg/dns/rawmsg.go
@@ -0,0 +1,95 @@
+package dns
+
+// These raw* functions do not use reflection, they directly set the values
+// in the buffer. There are faster than their reflection counterparts.
+
+// RawSetId sets the message id in buf.
+func rawSetId(msg []byte, i uint16) bool {
+ if len(msg) < 2 {
+ return false
+ }
+ msg[0], msg[1] = packUint16(i)
+ return true
+}
+
+// rawSetQuestionLen sets the length of the question section.
+func rawSetQuestionLen(msg []byte, i uint16) bool {
+ if len(msg) < 6 {
+ return false
+ }
+ msg[4], msg[5] = packUint16(i)
+ return true
+}
+
+// rawSetAnswerLen sets the lenght of the answer section.
+func rawSetAnswerLen(msg []byte, i uint16) bool {
+ if len(msg) < 8 {
+ return false
+ }
+ msg[6], msg[7] = packUint16(i)
+ return true
+}
+
+// rawSetsNsLen sets the lenght of the authority section.
+func rawSetNsLen(msg []byte, i uint16) bool {
+ if len(msg) < 10 {
+ return false
+ }
+ msg[8], msg[9] = packUint16(i)
+ return true
+}
+
+// rawSetExtraLen sets the lenght of the additional section.
+func rawSetExtraLen(msg []byte, i uint16) bool {
+ if len(msg) < 12 {
+ return false
+ }
+ msg[10], msg[11] = packUint16(i)
+ return true
+}
+
+// rawSetRdlength sets the rdlength in the header of
+// the RR. The offset 'off' must be positioned at the
+// start of the header of the RR, 'end' must be the
+// end of the RR.
+func rawSetRdlength(msg []byte, off, end int) bool {
+ l := len(msg)
+Loop:
+ for {
+ if off+1 > l {
+ return false
+ }
+ c := int(msg[off])
+ off++
+ switch c & 0xC0 {
+ case 0x00:
+ if c == 0x00 {
+ // End of the domainname
+ break Loop
+ }
+ if off+c > l {
+ return false
+ }
+ off += c
+
+ case 0xC0:
+ // pointer, next byte included, ends domainname
+ off++
+ break Loop
+ }
+ }
+ // The domainname has been seen, we at the start of the fixed part in the header.
+ // Type is 2 bytes, class is 2 bytes, ttl 4 and then 2 bytes for the length.
+ off += 2 + 2 + 4
+ if off+2 > l {
+ return false
+ }
+ //off+1 is the end of the header, 'end' is the end of the rr
+ //so 'end' - 'off+2' is the length of the rdata
+ rdatalen := end - (off + 2)
+ if rdatalen > 0xFFFF {
+ return false
+ }
+ msg[off], msg[off+1] = packUint16(uint16(rdatalen))
+ return true
+}
diff --git a/vendor/github.com/miekg/dns/sanitize.go b/vendor/github.com/miekg/dns/sanitize.go
new file mode 100644
index 0000000..b489f3f
--- /dev/null
+++ b/vendor/github.com/miekg/dns/sanitize.go
@@ -0,0 +1,84 @@
+package dns
+
+// Dedup removes identical RRs from rrs. It preserves the original ordering.
+// The lowest TTL of any duplicates is used in the remaining one. Dedup modifies
+// rrs.
+// m is used to store the RRs temporay. If it is nil a new map will be allocated.
+func Dedup(rrs []RR, m map[string]RR) []RR {
+ if m == nil {
+ m = make(map[string]RR)
+ }
+ // Save the keys, so we don't have to call normalizedString twice.
+ keys := make([]*string, 0, len(rrs))
+
+ for _, r := range rrs {
+ key := normalizedString(r)
+ keys = append(keys, &key)
+ if _, ok := m[key]; ok {
+ // Shortest TTL wins.
+ if m[key].Header().Ttl > r.Header().Ttl {
+ m[key].Header().Ttl = r.Header().Ttl
+ }
+ continue
+ }
+
+ m[key] = r
+ }
+ // If the length of the result map equals the amount of RRs we got,
+ // it means they were all different. We can then just return the original rrset.
+ if len(m) == len(rrs) {
+ return rrs
+ }
+
+ j := 0
+ for i, r := range rrs {
+ // If keys[i] lives in the map, we should copy and remove it.
+ if _, ok := m[*keys[i]]; ok {
+ delete(m, *keys[i])
+ rrs[j] = r
+ j++
+ }
+
+ if len(m) == 0 {
+ break
+ }
+ }
+
+ return rrs[:j]
+}
+
+// normalizedString returns a normalized string from r. The TTL
+// is removed and the domain name is lowercased. We go from this:
+// DomainName<TAB>TTL<TAB>CLASS<TAB>TYPE<TAB>RDATA to:
+// lowercasename<TAB>CLASS<TAB>TYPE...
+func normalizedString(r RR) string {
+ // A string Go DNS makes has: domainname<TAB>TTL<TAB>...
+ b := []byte(r.String())
+
+ // find the first non-escaped tab, then another, so we capture where the TTL lives.
+ esc := false
+ ttlStart, ttlEnd := 0, 0
+ for i := 0; i < len(b) && ttlEnd == 0; i++ {
+ switch {
+ case b[i] == '\\':
+ esc = !esc
+ case b[i] == '\t' && !esc:
+ if ttlStart == 0 {
+ ttlStart = i
+ continue
+ }
+ if ttlEnd == 0 {
+ ttlEnd = i
+ }
+ case b[i] >= 'A' && b[i] <= 'Z' && !esc:
+ b[i] += 32
+ default:
+ esc = false
+ }
+ }
+
+ // remove TTL.
+ copy(b[ttlStart:], b[ttlEnd:])
+ cut := ttlEnd - ttlStart
+ return string(b[:len(b)-cut])
+}
diff --git a/vendor/github.com/miekg/dns/scanner.go b/vendor/github.com/miekg/dns/scanner.go
new file mode 100644
index 0000000..c29bc2f
--- /dev/null
+++ b/vendor/github.com/miekg/dns/scanner.go
@@ -0,0 +1,43 @@
+package dns
+
+// Implement a simple scanner, return a byte stream from an io reader.
+
+import (
+ "bufio"
+ "io"
+ "text/scanner"
+)
+
+type scan struct {
+ src *bufio.Reader
+ position scanner.Position
+ eof bool // Have we just seen a eof
+}
+
+func scanInit(r io.Reader) *scan {
+ s := new(scan)
+ s.src = bufio.NewReader(r)
+ s.position.Line = 1
+ return s
+}
+
+// tokenText returns the next byte from the input
+func (s *scan) tokenText() (byte, error) {
+ c, err := s.src.ReadByte()
+ if err != nil {
+ return c, err
+ }
+ // delay the newline handling until the next token is delivered,
+ // fixes off-by-one errors when reporting a parse error.
+ if s.eof == true {
+ s.position.Line++
+ s.position.Column = 0
+ s.eof = false
+ }
+ if c == '\n' {
+ s.eof = true
+ return c, nil
+ }
+ s.position.Column++
+ return c, nil
+}
diff --git a/vendor/github.com/miekg/dns/server.go b/vendor/github.com/miekg/dns/server.go
new file mode 100644
index 0000000..bb0d074
--- /dev/null
+++ b/vendor/github.com/miekg/dns/server.go
@@ -0,0 +1,690 @@
+// DNS server implementation.
+
+package dns
+
+import (
+ "bytes"
+ "io"
+ "net"
+ "sync"
+ "time"
+)
+
+// Maximum number of TCP queries before we close the socket.
+const maxTCPQueries = 128
+
+// Handler is implemented by any value that implements ServeDNS.
+type Handler interface {
+ ServeDNS(w ResponseWriter, r *Msg)
+}
+
+// A ResponseWriter interface is used by an DNS handler to
+// construct an DNS response.
+type ResponseWriter interface {
+ // LocalAddr returns the net.Addr of the server
+ LocalAddr() net.Addr
+ // RemoteAddr returns the net.Addr of the client that sent the current request.
+ RemoteAddr() net.Addr
+ // WriteMsg writes a reply back to the client.
+ WriteMsg(*Msg) error
+ // Write writes a raw buffer back to the client.
+ Write([]byte) (int, error)
+ // Close closes the connection.
+ Close() error
+ // TsigStatus returns the status of the Tsig.
+ TsigStatus() error
+ // TsigTimersOnly sets the tsig timers only boolean.
+ TsigTimersOnly(bool)
+ // Hijack lets the caller take over the connection.
+ // After a call to Hijack(), the DNS package will not do anything with the connection.
+ Hijack()
+}
+
+type response struct {
+ hijacked bool // connection has been hijacked by handler
+ tsigStatus error
+ tsigTimersOnly bool
+ tsigRequestMAC string
+ tsigSecret map[string]string // the tsig secrets
+ udp *net.UDPConn // i/o connection if UDP was used
+ tcp *net.TCPConn // i/o connection if TCP was used
+ udpSession *SessionUDP // oob data to get egress interface right
+ remoteAddr net.Addr // address of the client
+ writer Writer // writer to output the raw DNS bits
+}
+
+// ServeMux is an DNS request multiplexer. It matches the
+// zone name of each incoming request against a list of
+// registered patterns add calls the handler for the pattern
+// that most closely matches the zone name. ServeMux is DNSSEC aware, meaning
+// that queries for the DS record are redirected to the parent zone (if that
+// is also registered), otherwise the child gets the query.
+// ServeMux is also safe for concurrent access from multiple goroutines.
+type ServeMux struct {
+ z map[string]Handler
+ m *sync.RWMutex
+}
+
+// NewServeMux allocates and returns a new ServeMux.
+func NewServeMux() *ServeMux { return &ServeMux{z: make(map[string]Handler), m: new(sync.RWMutex)} }
+
+// DefaultServeMux is the default ServeMux used by Serve.
+var DefaultServeMux = NewServeMux()
+
+// The HandlerFunc type is an adapter to allow the use of
+// ordinary functions as DNS handlers. If f is a function
+// with the appropriate signature, HandlerFunc(f) is a
+// Handler object that calls f.
+type HandlerFunc func(ResponseWriter, *Msg)
+
+// ServeDNS calls f(w, r).
+func (f HandlerFunc) ServeDNS(w ResponseWriter, r *Msg) {
+ f(w, r)
+}
+
+// HandleFailed returns a HandlerFunc that returns SERVFAIL for every request it gets.
+func HandleFailed(w ResponseWriter, r *Msg) {
+ m := new(Msg)
+ m.SetRcode(r, RcodeServerFailure)
+ // does not matter if this write fails
+ w.WriteMsg(m)
+}
+
+func failedHandler() Handler { return HandlerFunc(HandleFailed) }
+
+// ListenAndServe Starts a server on addresss and network speficied. Invoke handler
+// for incoming queries.
+func ListenAndServe(addr string, network string, handler Handler) error {
+ server := &Server{Addr: addr, Net: network, Handler: handler}
+ return server.ListenAndServe()
+}
+
+// ActivateAndServe activates a server with a listener from systemd,
+// l and p should not both be non-nil.
+// If both l and p are not nil only p will be used.
+// Invoke handler for incoming queries.
+func ActivateAndServe(l net.Listener, p net.PacketConn, handler Handler) error {
+ server := &Server{Listener: l, PacketConn: p, Handler: handler}
+ return server.ActivateAndServe()
+}
+
+func (mux *ServeMux) match(q string, t uint16) Handler {
+ mux.m.RLock()
+ defer mux.m.RUnlock()
+ var handler Handler
+ b := make([]byte, len(q)) // worst case, one label of length q
+ off := 0
+ end := false
+ for {
+ l := len(q[off:])
+ for i := 0; i < l; i++ {
+ b[i] = q[off+i]
+ if b[i] >= 'A' && b[i] <= 'Z' {
+ b[i] |= ('a' - 'A')
+ }
+ }
+ if h, ok := mux.z[string(b[:l])]; ok { // 'causes garbage, might want to change the map key
+ if t != TypeDS {
+ return h
+ }
+ // Continue for DS to see if we have a parent too, if so delegeate to the parent
+ handler = h
+ }
+ off, end = NextLabel(q, off)
+ if end {
+ break
+ }
+ }
+ // Wildcard match, if we have found nothing try the root zone as a last resort.
+ if h, ok := mux.z["."]; ok {
+ return h
+ }
+ return handler
+}
+
+// Handle adds a handler to the ServeMux for pattern.
+func (mux *ServeMux) Handle(pattern string, handler Handler) {
+ if pattern == "" {
+ panic("dns: invalid pattern " + pattern)
+ }
+ mux.m.Lock()
+ mux.z[Fqdn(pattern)] = handler
+ mux.m.Unlock()
+}
+
+// HandleFunc adds a handler function to the ServeMux for pattern.
+func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Msg)) {
+ mux.Handle(pattern, HandlerFunc(handler))
+}
+
+// HandleRemove deregistrars the handler specific for pattern from the ServeMux.
+func (mux *ServeMux) HandleRemove(pattern string) {
+ if pattern == "" {
+ panic("dns: invalid pattern " + pattern)
+ }
+ mux.m.Lock()
+ delete(mux.z, Fqdn(pattern))
+ mux.m.Unlock()
+}
+
+// ServeDNS dispatches the request to the handler whose
+// pattern most closely matches the request message. If DefaultServeMux
+// is used the correct thing for DS queries is done: a possible parent
+// is sought.
+// If no handler is found a standard SERVFAIL message is returned
+// If the request message does not have exactly one question in the
+// question section a SERVFAIL is returned, unlesss Unsafe is true.
+func (mux *ServeMux) ServeDNS(w ResponseWriter, request *Msg) {
+ var h Handler
+ if len(request.Question) < 1 { // allow more than one question
+ h = failedHandler()
+ } else {
+ if h = mux.match(request.Question[0].Name, request.Question[0].Qtype); h == nil {
+ h = failedHandler()
+ }
+ }
+ h.ServeDNS(w, request)
+}
+
+// Handle registers the handler with the given pattern
+// in the DefaultServeMux. The documentation for
+// ServeMux explains how patterns are matched.
+func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
+
+// HandleRemove deregisters the handle with the given pattern
+// in the DefaultServeMux.
+func HandleRemove(pattern string) { DefaultServeMux.HandleRemove(pattern) }
+
+// HandleFunc registers the handler function with the given pattern
+// in the DefaultServeMux.
+func HandleFunc(pattern string, handler func(ResponseWriter, *Msg)) {
+ DefaultServeMux.HandleFunc(pattern, handler)
+}
+
+// Writer writes raw DNS messages; each call to Write should send an entire message.
+type Writer interface {
+ io.Writer
+}
+
+// Reader reads raw DNS messages; each call to ReadTCP or ReadUDP should return an entire message.
+type Reader interface {
+ // ReadTCP reads a raw message from a TCP connection. Implementations may alter
+ // connection properties, for example the read-deadline.
+ ReadTCP(conn *net.TCPConn, timeout time.Duration) ([]byte, error)
+ // ReadUDP reads a raw message from a UDP connection. Implementations may alter
+ // connection properties, for example the read-deadline.
+ ReadUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error)
+}
+
+// defaultReader is an adapter for the Server struct that implements the Reader interface
+// using the readTCP and readUDP func of the embedded Server.
+type defaultReader struct {
+ *Server
+}
+
+func (dr *defaultReader) ReadTCP(conn *net.TCPConn, timeout time.Duration) ([]byte, error) {
+ return dr.readTCP(conn, timeout)
+}
+
+func (dr *defaultReader) ReadUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error) {
+ return dr.readUDP(conn, timeout)
+}
+
+// DecorateReader is a decorator hook for extending or supplanting the functionality of a Reader.
+// Implementations should never return a nil Reader.
+type DecorateReader func(Reader) Reader
+
+// DecorateWriter is a decorator hook for extending or supplanting the functionality of a Writer.
+// Implementations should never return a nil Writer.
+type DecorateWriter func(Writer) Writer
+
+// A Server defines parameters for running an DNS server.
+type Server struct {
+ // Address to listen on, ":dns" if empty.
+ Addr string
+ // if "tcp" it will invoke a TCP listener, otherwise an UDP one.
+ Net string
+ // TCP Listener to use, this is to aid in systemd's socket activation.
+ Listener net.Listener
+ // UDP "Listener" to use, this is to aid in systemd's socket activation.
+ PacketConn net.PacketConn
+ // Handler to invoke, dns.DefaultServeMux if nil.
+ Handler Handler
+ // Default buffer size to use to read incoming UDP messages. If not set
+ // it defaults to MinMsgSize (512 B).
+ UDPSize int
+ // The net.Conn.SetReadTimeout value for new connections, defaults to 2 * time.Second.
+ ReadTimeout time.Duration
+ // The net.Conn.SetWriteTimeout value for new connections, defaults to 2 * time.Second.
+ WriteTimeout time.Duration
+ // TCP idle timeout for multiple queries, if nil, defaults to 8 * time.Second (RFC 5966).
+ IdleTimeout func() time.Duration
+ // Secret(s) for Tsig map[<zonename>]<base64 secret>.
+ TsigSecret map[string]string
+ // Unsafe instructs the server to disregard any sanity checks and directly hand the message to
+ // the handler. It will specfically not check if the query has the QR bit not set.
+ Unsafe bool
+ // If NotifyStartedFunc is set it is called once the server has started listening.
+ NotifyStartedFunc func()
+ // DecorateReader is optional, allows customization of the process that reads raw DNS messages.
+ DecorateReader DecorateReader
+ // DecorateWriter is optional, allows customization of the process that writes raw DNS messages.
+ DecorateWriter DecorateWriter
+
+ // Graceful shutdown handling
+
+ inFlight sync.WaitGroup
+
+ lock sync.RWMutex
+ started bool
+}
+
+// ListenAndServe starts a nameserver on the configured address in *Server.
+func (srv *Server) ListenAndServe() error {
+ srv.lock.Lock()
+ defer srv.lock.Unlock()
+ if srv.started {
+ return &Error{err: "server already started"}
+ }
+ addr := srv.Addr
+ if addr == "" {
+ addr = ":domain"
+ }
+ if srv.UDPSize == 0 {
+ srv.UDPSize = MinMsgSize
+ }
+ switch srv.Net {
+ case "tcp", "tcp4", "tcp6":
+ a, e := net.ResolveTCPAddr(srv.Net, addr)
+ if e != nil {
+ return e
+ }
+ l, e := net.ListenTCP(srv.Net, a)
+ if e != nil {
+ return e
+ }
+ srv.Listener = l
+ srv.started = true
+ srv.lock.Unlock()
+ e = srv.serveTCP(l)
+ srv.lock.Lock() // to satisfy the defer at the top
+ return e
+ case "udp", "udp4", "udp6":
+ a, e := net.ResolveUDPAddr(srv.Net, addr)
+ if e != nil {
+ return e
+ }
+ l, e := net.ListenUDP(srv.Net, a)
+ if e != nil {
+ return e
+ }
+ if e := setUDPSocketOptions(l); e != nil {
+ return e
+ }
+ srv.PacketConn = l
+ srv.started = true
+ srv.lock.Unlock()
+ e = srv.serveUDP(l)
+ srv.lock.Lock() // to satisfy the defer at the top
+ return e
+ }
+ return &Error{err: "bad network"}
+}
+
+// ActivateAndServe starts a nameserver with the PacketConn or Listener
+// configured in *Server. Its main use is to start a server from systemd.
+func (srv *Server) ActivateAndServe() error {
+ srv.lock.Lock()
+ defer srv.lock.Unlock()
+ if srv.started {
+ return &Error{err: "server already started"}
+ }
+ pConn := srv.PacketConn
+ l := srv.Listener
+ if pConn != nil {
+ if srv.UDPSize == 0 {
+ srv.UDPSize = MinMsgSize
+ }
+ if t, ok := pConn.(*net.UDPConn); ok {
+ if e := setUDPSocketOptions(t); e != nil {
+ return e
+ }
+ srv.started = true
+ srv.lock.Unlock()
+ e := srv.serveUDP(t)
+ srv.lock.Lock() // to satisfy the defer at the top
+ return e
+ }
+ }
+ if l != nil {
+ if t, ok := l.(*net.TCPListener); ok {
+ srv.started = true
+ srv.lock.Unlock()
+ e := srv.serveTCP(t)
+ srv.lock.Lock() // to satisfy the defer at the top
+ return e
+ }
+ }
+ return &Error{err: "bad listeners"}
+}
+
+// Shutdown gracefully shuts down a server. After a call to Shutdown, ListenAndServe and
+// ActivateAndServe will return. All in progress queries are completed before the server
+// is taken down. If the Shutdown is taking longer than the reading timeout an error
+// is returned.
+func (srv *Server) Shutdown() error {
+ srv.lock.Lock()
+ if !srv.started {
+ srv.lock.Unlock()
+ return &Error{err: "server not started"}
+ }
+ srv.started = false
+ srv.lock.Unlock()
+
+ if srv.PacketConn != nil {
+ srv.PacketConn.Close()
+ }
+ if srv.Listener != nil {
+ srv.Listener.Close()
+ }
+
+ fin := make(chan bool)
+ go func() {
+ srv.inFlight.Wait()
+ fin <- true
+ }()
+
+ select {
+ case <-time.After(srv.getReadTimeout()):
+ return &Error{err: "server shutdown is pending"}
+ case <-fin:
+ return nil
+ }
+}
+
+// getReadTimeout is a helper func to use system timeout if server did not intend to change it.
+func (srv *Server) getReadTimeout() time.Duration {
+ rtimeout := dnsTimeout
+ if srv.ReadTimeout != 0 {
+ rtimeout = srv.ReadTimeout
+ }
+ return rtimeout
+}
+
+// serveTCP starts a TCP listener for the server.
+// Each request is handled in a separate goroutine.
+func (srv *Server) serveTCP(l *net.TCPListener) error {
+ defer l.Close()
+
+ if srv.NotifyStartedFunc != nil {
+ srv.NotifyStartedFunc()
+ }
+
+ reader := Reader(&defaultReader{srv})
+ if srv.DecorateReader != nil {
+ reader = srv.DecorateReader(reader)
+ }
+
+ handler := srv.Handler
+ if handler == nil {
+ handler = DefaultServeMux
+ }
+ rtimeout := srv.getReadTimeout()
+ // deadline is not used here
+ for {
+ rw, e := l.AcceptTCP()
+ if e != nil {
+ if neterr, ok := e.(net.Error); ok && neterr.Temporary() {
+ continue
+ }
+ return e
+ }
+ m, e := reader.ReadTCP(rw, rtimeout)
+ srv.lock.RLock()
+ if !srv.started {
+ srv.lock.RUnlock()
+ return nil
+ }
+ srv.lock.RUnlock()
+ if e != nil {
+ continue
+ }
+ srv.inFlight.Add(1)
+ go srv.serve(rw.RemoteAddr(), handler, m, nil, nil, rw)
+ }
+}
+
+// serveUDP starts a UDP listener for the server.
+// Each request is handled in a separate goroutine.
+func (srv *Server) serveUDP(l *net.UDPConn) error {
+ defer l.Close()
+
+ if srv.NotifyStartedFunc != nil {
+ srv.NotifyStartedFunc()
+ }
+
+ reader := Reader(&defaultReader{srv})
+ if srv.DecorateReader != nil {
+ reader = srv.DecorateReader(reader)
+ }
+
+ handler := srv.Handler
+ if handler == nil {
+ handler = DefaultServeMux
+ }
+ rtimeout := srv.getReadTimeout()
+ // deadline is not used here
+ for {
+ m, s, e := reader.ReadUDP(l, rtimeout)
+ srv.lock.RLock()
+ if !srv.started {
+ srv.lock.RUnlock()
+ return nil
+ }
+ srv.lock.RUnlock()
+ if e != nil {
+ continue
+ }
+ srv.inFlight.Add(1)
+ go srv.serve(s.RemoteAddr(), handler, m, l, s, nil)
+ }
+}
+
+// Serve a new connection.
+func (srv *Server) serve(a net.Addr, h Handler, m []byte, u *net.UDPConn, s *SessionUDP, t *net.TCPConn) {
+ defer srv.inFlight.Done()
+
+ w := &response{tsigSecret: srv.TsigSecret, udp: u, tcp: t, remoteAddr: a, udpSession: s}
+ if srv.DecorateWriter != nil {
+ w.writer = srv.DecorateWriter(w)
+ } else {
+ w.writer = w
+ }
+
+ q := 0 // counter for the amount of TCP queries we get
+
+ reader := Reader(&defaultReader{srv})
+ if srv.DecorateReader != nil {
+ reader = srv.DecorateReader(reader)
+ }
+Redo:
+ req := new(Msg)
+ err := req.Unpack(m)
+ if err != nil { // Send a FormatError back
+ x := new(Msg)
+ x.SetRcodeFormatError(req)
+ w.WriteMsg(x)
+ goto Exit
+ }
+ if !srv.Unsafe && req.Response {
+ goto Exit
+ }
+
+ w.tsigStatus = nil
+ if w.tsigSecret != nil {
+ if t := req.IsTsig(); t != nil {
+ secret := t.Hdr.Name
+ if _, ok := w.tsigSecret[secret]; !ok {
+ w.tsigStatus = ErrKeyAlg
+ }
+ w.tsigStatus = TsigVerify(m, w.tsigSecret[secret], "", false)
+ w.tsigTimersOnly = false
+ w.tsigRequestMAC = req.Extra[len(req.Extra)-1].(*TSIG).MAC
+ }
+ }
+ h.ServeDNS(w, req) // Writes back to the client
+
+Exit:
+ if w.tcp == nil {
+ return
+ }
+ // TODO(miek): make this number configurable?
+ if q > maxTCPQueries { // close socket after this many queries
+ w.Close()
+ return
+ }
+
+ if w.hijacked {
+ return // client calls Close()
+ }
+ if u != nil { // UDP, "close" and return
+ w.Close()
+ return
+ }
+ idleTimeout := tcpIdleTimeout
+ if srv.IdleTimeout != nil {
+ idleTimeout = srv.IdleTimeout()
+ }
+ m, e := reader.ReadTCP(w.tcp, idleTimeout)
+ if e == nil {
+ q++
+ goto Redo
+ }
+ w.Close()
+ return
+}
+
+func (srv *Server) readTCP(conn *net.TCPConn, timeout time.Duration) ([]byte, error) {
+ conn.SetReadDeadline(time.Now().Add(timeout))
+ l := make([]byte, 2)
+ n, err := conn.Read(l)
+ if err != nil || n != 2 {
+ if err != nil {
+ return nil, err
+ }
+ return nil, ErrShortRead
+ }
+ length, _ := unpackUint16(l, 0)
+ if length == 0 {
+ return nil, ErrShortRead
+ }
+ m := make([]byte, int(length))
+ n, err = conn.Read(m[:int(length)])
+ if err != nil || n == 0 {
+ if err != nil {
+ return nil, err
+ }
+ return nil, ErrShortRead
+ }
+ i := n
+ for i < int(length) {
+ j, err := conn.Read(m[i:int(length)])
+ if err != nil {
+ return nil, err
+ }
+ i += j
+ }
+ n = i
+ m = m[:n]
+ return m, nil
+}
+
+func (srv *Server) readUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error) {
+ conn.SetReadDeadline(time.Now().Add(timeout))
+ m := make([]byte, srv.UDPSize)
+ n, s, e := ReadFromSessionUDP(conn, m)
+ if e != nil || n == 0 {
+ if e != nil {
+ return nil, nil, e
+ }
+ return nil, nil, ErrShortRead
+ }
+ m = m[:n]
+ return m, s, nil
+}
+
+// WriteMsg implements the ResponseWriter.WriteMsg method.
+func (w *response) WriteMsg(m *Msg) (err error) {
+ var data []byte
+ if w.tsigSecret != nil { // if no secrets, dont check for the tsig (which is a longer check)
+ if t := m.IsTsig(); t != nil {
+ data, w.tsigRequestMAC, err = TsigGenerate(m, w.tsigSecret[t.Hdr.Name], w.tsigRequestMAC, w.tsigTimersOnly)
+ if err != nil {
+ return err
+ }
+ _, err = w.writer.Write(data)
+ return err
+ }
+ }
+ data, err = m.Pack()
+ if err != nil {
+ return err
+ }
+ _, err = w.writer.Write(data)
+ return err
+}
+
+// Write implements the ResponseWriter.Write method.
+func (w *response) Write(m []byte) (int, error) {
+ switch {
+ case w.udp != nil:
+ n, err := WriteToSessionUDP(w.udp, m, w.udpSession)
+ return n, err
+ case w.tcp != nil:
+ lm := len(m)
+ if lm < 2 {
+ return 0, io.ErrShortBuffer
+ }
+ if lm > MaxMsgSize {
+ return 0, &Error{err: "message too large"}
+ }
+ l := make([]byte, 2, 2+lm)
+ l[0], l[1] = packUint16(uint16(lm))
+ m = append(l, m...)
+
+ n, err := io.Copy(w.tcp, bytes.NewReader(m))
+ return int(n), err
+ }
+ panic("not reached")
+}
+
+// LocalAddr implements the ResponseWriter.LocalAddr method.
+func (w *response) LocalAddr() net.Addr {
+ if w.tcp != nil {
+ return w.tcp.LocalAddr()
+ }
+ return w.udp.LocalAddr()
+}
+
+// RemoteAddr implements the ResponseWriter.RemoteAddr method.
+func (w *response) RemoteAddr() net.Addr { return w.remoteAddr }
+
+// TsigStatus implements the ResponseWriter.TsigStatus method.
+func (w *response) TsigStatus() error { return w.tsigStatus }
+
+// TsigTimersOnly implements the ResponseWriter.TsigTimersOnly method.
+func (w *response) TsigTimersOnly(b bool) { w.tsigTimersOnly = b }
+
+// Hijack implements the ResponseWriter.Hijack method.
+func (w *response) Hijack() { w.hijacked = true }
+
+// Close implements the ResponseWriter.Close method
+func (w *response) Close() error {
+ // Can't close the udp conn, as that is actually the listener.
+ if w.tcp != nil {
+ e := w.tcp.Close()
+ w.tcp = nil
+ return e
+ }
+ return nil
+}
diff --git a/vendor/github.com/miekg/dns/sig0.go b/vendor/github.com/miekg/dns/sig0.go
new file mode 100644
index 0000000..0fccddb
--- /dev/null
+++ b/vendor/github.com/miekg/dns/sig0.go
@@ -0,0 +1,216 @@
+package dns
+
+import (
+ "crypto"
+ "crypto/dsa"
+ "crypto/ecdsa"
+ "crypto/rsa"
+ "math/big"
+ "strings"
+ "time"
+)
+
+// Sign signs a dns.Msg. It fills the signature with the appropriate data.
+// The SIG record should have the SignerName, KeyTag, Algorithm, Inception
+// and Expiration set.
+func (rr *SIG) Sign(k crypto.Signer, m *Msg) ([]byte, error) {
+ if k == nil {
+ return nil, ErrPrivKey
+ }
+ if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 {
+ return nil, ErrKey
+ }
+ rr.Header().Rrtype = TypeSIG
+ rr.Header().Class = ClassANY
+ rr.Header().Ttl = 0
+ rr.Header().Name = "."
+ rr.OrigTtl = 0
+ rr.TypeCovered = 0
+ rr.Labels = 0
+
+ buf := make([]byte, m.Len()+rr.len())
+ mbuf, err := m.PackBuffer(buf)
+ if err != nil {
+ return nil, err
+ }
+ if &buf[0] != &mbuf[0] {
+ return nil, ErrBuf
+ }
+ off, err := PackRR(rr, buf, len(mbuf), nil, false)
+ if err != nil {
+ return nil, err
+ }
+ buf = buf[:off:cap(buf)]
+
+ hash, ok := AlgorithmToHash[rr.Algorithm]
+ if !ok {
+ return nil, ErrAlg
+ }
+
+ hasher := hash.New()
+ // Write SIG rdata
+ hasher.Write(buf[len(mbuf)+1+2+2+4+2:])
+ // Write message
+ hasher.Write(buf[:len(mbuf)])
+
+ signature, err := sign(k, hasher.Sum(nil), hash, rr.Algorithm)
+ if err != nil {
+ return nil, err
+ }
+
+ rr.Signature = toBase64(signature)
+ sig := string(signature)
+
+ buf = append(buf, sig...)
+ if len(buf) > int(^uint16(0)) {
+ return nil, ErrBuf
+ }
+ // Adjust sig data length
+ rdoff := len(mbuf) + 1 + 2 + 2 + 4
+ rdlen, _ := unpackUint16(buf, rdoff)
+ rdlen += uint16(len(sig))
+ buf[rdoff], buf[rdoff+1] = packUint16(rdlen)
+ // Adjust additional count
+ adc, _ := unpackUint16(buf, 10)
+ adc++
+ buf[10], buf[11] = packUint16(adc)
+ return buf, nil
+}
+
+// Verify validates the message buf using the key k.
+// It's assumed that buf is a valid message from which rr was unpacked.
+func (rr *SIG) Verify(k *KEY, buf []byte) error {
+ if k == nil {
+ return ErrKey
+ }
+ if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 {
+ return ErrKey
+ }
+
+ var hash crypto.Hash
+ switch rr.Algorithm {
+ case DSA, RSASHA1:
+ hash = crypto.SHA1
+ case RSASHA256, ECDSAP256SHA256:
+ hash = crypto.SHA256
+ case ECDSAP384SHA384:
+ hash = crypto.SHA384
+ case RSASHA512:
+ hash = crypto.SHA512
+ default:
+ return ErrAlg
+ }
+ hasher := hash.New()
+
+ buflen := len(buf)
+ qdc, _ := unpackUint16(buf, 4)
+ anc, _ := unpackUint16(buf, 6)
+ auc, _ := unpackUint16(buf, 8)
+ adc, offset := unpackUint16(buf, 10)
+ var err error
+ for i := uint16(0); i < qdc && offset < buflen; i++ {
+ _, offset, err = UnpackDomainName(buf, offset)
+ if err != nil {
+ return err
+ }
+ // Skip past Type and Class
+ offset += 2 + 2
+ }
+ for i := uint16(1); i < anc+auc+adc && offset < buflen; i++ {
+ _, offset, err = UnpackDomainName(buf, offset)
+ if err != nil {
+ return err
+ }
+ // Skip past Type, Class and TTL
+ offset += 2 + 2 + 4
+ if offset+1 >= buflen {
+ continue
+ }
+ var rdlen uint16
+ rdlen, offset = unpackUint16(buf, offset)
+ offset += int(rdlen)
+ }
+ if offset >= buflen {
+ return &Error{err: "overflowing unpacking signed message"}
+ }
+
+ // offset should be just prior to SIG
+ bodyend := offset
+ // owner name SHOULD be root
+ _, offset, err = UnpackDomainName(buf, offset)
+ if err != nil {
+ return err
+ }
+ // Skip Type, Class, TTL, RDLen
+ offset += 2 + 2 + 4 + 2
+ sigstart := offset
+ // Skip Type Covered, Algorithm, Labels, Original TTL
+ offset += 2 + 1 + 1 + 4
+ if offset+4+4 >= buflen {
+ return &Error{err: "overflow unpacking signed message"}
+ }
+ expire := uint32(buf[offset])<<24 | uint32(buf[offset+1])<<16 | uint32(buf[offset+2])<<8 | uint32(buf[offset+3])
+ offset += 4
+ incept := uint32(buf[offset])<<24 | uint32(buf[offset+1])<<16 | uint32(buf[offset+2])<<8 | uint32(buf[offset+3])
+ offset += 4
+ now := uint32(time.Now().Unix())
+ if now < incept || now > expire {
+ return ErrTime
+ }
+ // Skip key tag
+ offset += 2
+ var signername string
+ signername, offset, err = UnpackDomainName(buf, offset)
+ if err != nil {
+ return err
+ }
+ // If key has come from the DNS name compression might
+ // have mangled the case of the name
+ if strings.ToLower(signername) != strings.ToLower(k.Header().Name) {
+ return &Error{err: "signer name doesn't match key name"}
+ }
+ sigend := offset
+ hasher.Write(buf[sigstart:sigend])
+ hasher.Write(buf[:10])
+ hasher.Write([]byte{
+ byte((adc - 1) << 8),
+ byte(adc - 1),
+ })
+ hasher.Write(buf[12:bodyend])
+
+ hashed := hasher.Sum(nil)
+ sig := buf[sigend:]
+ switch k.Algorithm {
+ case DSA:
+ pk := k.publicKeyDSA()
+ sig = sig[1:]
+ r := big.NewInt(0)
+ r.SetBytes(sig[:len(sig)/2])
+ s := big.NewInt(0)
+ s.SetBytes(sig[len(sig)/2:])
+ if pk != nil {
+ if dsa.Verify(pk, hashed, r, s) {
+ return nil
+ }
+ return ErrSig
+ }
+ case RSASHA1, RSASHA256, RSASHA512:
+ pk := k.publicKeyRSA()
+ if pk != nil {
+ return rsa.VerifyPKCS1v15(pk, hash, hashed, sig)
+ }
+ case ECDSAP256SHA256, ECDSAP384SHA384:
+ pk := k.publicKeyECDSA()
+ r := big.NewInt(0)
+ r.SetBytes(sig[:len(sig)/2])
+ s := big.NewInt(0)
+ s.SetBytes(sig[len(sig)/2:])
+ if pk != nil {
+ if ecdsa.Verify(pk, hashed, r, s) {
+ return nil
+ }
+ return ErrSig
+ }
+ }
+ return ErrKeyAlg
+}
diff --git a/vendor/github.com/miekg/dns/singleinflight.go b/vendor/github.com/miekg/dns/singleinflight.go
new file mode 100644
index 0000000..9573c7d
--- /dev/null
+++ b/vendor/github.com/miekg/dns/singleinflight.go
@@ -0,0 +1,57 @@
+// 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.
+
+// Adapted for dns package usage by Miek Gieben.
+
+package dns
+
+import "sync"
+import "time"
+
+// call is an in-flight or completed singleflight.Do call
+type call struct {
+ wg sync.WaitGroup
+ val *Msg
+ rtt time.Duration
+ err error
+ dups int
+}
+
+// singleflight represents a class of work and forms a namespace in
+// which units of work can be executed with duplicate suppression.
+type singleflight struct {
+ sync.Mutex // protects m
+ m map[string]*call // lazily initialized
+}
+
+// Do executes and returns the results of the given function, making
+// sure that only one execution is in-flight for a given key at a
+// time. If a duplicate comes in, the duplicate caller waits for the
+// original to complete and receives the same results.
+// The return value shared indicates whether v was given to multiple callers.
+func (g *singleflight) Do(key string, fn func() (*Msg, time.Duration, error)) (v *Msg, rtt time.Duration, err error, shared bool) {
+ g.Lock()
+ if g.m == nil {
+ g.m = make(map[string]*call)
+ }
+ if c, ok := g.m[key]; ok {
+ c.dups++
+ g.Unlock()
+ c.wg.Wait()
+ return c.val, c.rtt, c.err, true
+ }
+ c := new(call)
+ c.wg.Add(1)
+ g.m[key] = c
+ g.Unlock()
+
+ c.val, c.rtt, c.err = fn()
+ c.wg.Done()
+
+ g.Lock()
+ delete(g.m, key)
+ g.Unlock()
+
+ return c.val, c.rtt, c.err, c.dups > 0
+}
diff --git a/vendor/github.com/miekg/dns/tlsa.go b/vendor/github.com/miekg/dns/tlsa.go
new file mode 100644
index 0000000..f027787
--- /dev/null
+++ b/vendor/github.com/miekg/dns/tlsa.go
@@ -0,0 +1,86 @@
+package dns
+
+import (
+ "crypto/sha256"
+ "crypto/sha512"
+ "crypto/x509"
+ "encoding/hex"
+ "errors"
+ "io"
+ "net"
+ "strconv"
+)
+
+// CertificateToDANE converts a certificate to a hex string as used in the TLSA record.
+func CertificateToDANE(selector, matchingType uint8, cert *x509.Certificate) (string, error) {
+ switch matchingType {
+ case 0:
+ switch selector {
+ case 0:
+ return hex.EncodeToString(cert.Raw), nil
+ case 1:
+ return hex.EncodeToString(cert.RawSubjectPublicKeyInfo), nil
+ }
+ case 1:
+ h := sha256.New()
+ switch selector {
+ case 0:
+ io.WriteString(h, string(cert.Raw))
+ return hex.EncodeToString(h.Sum(nil)), nil
+ case 1:
+ io.WriteString(h, string(cert.RawSubjectPublicKeyInfo))
+ return hex.EncodeToString(h.Sum(nil)), nil
+ }
+ case 2:
+ h := sha512.New()
+ switch selector {
+ case 0:
+ io.WriteString(h, string(cert.Raw))
+ return hex.EncodeToString(h.Sum(nil)), nil
+ case 1:
+ io.WriteString(h, string(cert.RawSubjectPublicKeyInfo))
+ return hex.EncodeToString(h.Sum(nil)), nil
+ }
+ }
+ return "", errors.New("dns: bad TLSA MatchingType or TLSA Selector")
+}
+
+// Sign creates a TLSA record from an SSL certificate.
+func (r *TLSA) Sign(usage, selector, matchingType int, cert *x509.Certificate) (err error) {
+ r.Hdr.Rrtype = TypeTLSA
+ r.Usage = uint8(usage)
+ r.Selector = uint8(selector)
+ r.MatchingType = uint8(matchingType)
+
+ r.Certificate, err = CertificateToDANE(r.Selector, r.MatchingType, cert)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+// Verify verifies a TLSA record against an SSL certificate. If it is OK
+// a nil error is returned.
+func (r *TLSA) Verify(cert *x509.Certificate) error {
+ c, err := CertificateToDANE(r.Selector, r.MatchingType, cert)
+ if err != nil {
+ return err // Not also ErrSig?
+ }
+ if r.Certificate == c {
+ return nil
+ }
+ return ErrSig // ErrSig, really?
+}
+
+// TLSAName returns the ownername of a TLSA resource record as per the
+// rules specified in RFC 6698, Section 3.
+func TLSAName(name, service, network string) (string, error) {
+ if !IsFqdn(name) {
+ return "", ErrFqdn
+ }
+ p, e := net.LookupPort(network, service)
+ if e != nil {
+ return "", e
+ }
+ return "_" + strconv.Itoa(p) + "_" + network + "." + name, nil
+}
diff --git a/vendor/github.com/miekg/dns/tsig.go b/vendor/github.com/miekg/dns/tsig.go
new file mode 100644
index 0000000..32616d2
--- /dev/null
+++ b/vendor/github.com/miekg/dns/tsig.go
@@ -0,0 +1,320 @@
+package dns
+
+import (
+ "crypto/hmac"
+ "crypto/md5"
+ "crypto/sha1"
+ "crypto/sha256"
+ "crypto/sha512"
+ "encoding/hex"
+ "hash"
+ "io"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// HMAC hashing codes. These are transmitted as domain names.
+const (
+ HmacMD5 = "hmac-md5.sig-alg.reg.int."
+ HmacSHA1 = "hmac-sha1."
+ HmacSHA256 = "hmac-sha256."
+ HmacSHA512 = "hmac-sha512."
+)
+
+// TSIG is the RR the holds the transaction signature of a message.
+// See RFC 2845 and RFC 4635.
+type TSIG struct {
+ Hdr RR_Header
+ Algorithm string `dns:"domain-name"`
+ TimeSigned uint64 `dns:"uint48"`
+ Fudge uint16
+ MACSize uint16
+ MAC string `dns:"size-hex"`
+ OrigId uint16
+ Error uint16
+ OtherLen uint16
+ OtherData string `dns:"size-hex"`
+}
+
+// TSIG has no official presentation format, but this will suffice.
+
+func (rr *TSIG) String() string {
+ s := "\n;; TSIG PSEUDOSECTION:\n"
+ s += rr.Hdr.String() +
+ " " + rr.Algorithm +
+ " " + tsigTimeToString(rr.TimeSigned) +
+ " " + strconv.Itoa(int(rr.Fudge)) +
+ " " + strconv.Itoa(int(rr.MACSize)) +
+ " " + strings.ToUpper(rr.MAC) +
+ " " + strconv.Itoa(int(rr.OrigId)) +
+ " " + strconv.Itoa(int(rr.Error)) + // BIND prints NOERROR
+ " " + strconv.Itoa(int(rr.OtherLen)) +
+ " " + rr.OtherData
+ return s
+}
+
+// The following values must be put in wireformat, so that the MAC can be calculated.
+// RFC 2845, section 3.4.2. TSIG Variables.
+type tsigWireFmt struct {
+ // From RR_Header
+ Name string `dns:"domain-name"`
+ Class uint16
+ Ttl uint32
+ // Rdata of the TSIG
+ Algorithm string `dns:"domain-name"`
+ TimeSigned uint64 `dns:"uint48"`
+ Fudge uint16
+ // MACSize, MAC and OrigId excluded
+ Error uint16
+ OtherLen uint16
+ OtherData string `dns:"size-hex"`
+}
+
+// If we have the MAC use this type to convert it to wiredata.
+// Section 3.4.3. Request MAC
+type macWireFmt struct {
+ MACSize uint16
+ MAC string `dns:"size-hex"`
+}
+
+// 3.3. Time values used in TSIG calculations
+type timerWireFmt struct {
+ TimeSigned uint64 `dns:"uint48"`
+ Fudge uint16
+}
+
+// TsigGenerate fills out the TSIG record attached to the message.
+// The message should contain
+// a "stub" TSIG RR with the algorithm, key name (owner name of the RR),
+// time fudge (defaults to 300 seconds) and the current time
+// The TSIG MAC is saved in that Tsig RR.
+// When TsigGenerate is called for the first time requestMAC is set to the empty string and
+// timersOnly is false.
+// If something goes wrong an error is returned, otherwise it is nil.
+func TsigGenerate(m *Msg, secret, requestMAC string, timersOnly bool) ([]byte, string, error) {
+ if m.IsTsig() == nil {
+ panic("dns: TSIG not last RR in additional")
+ }
+ // If we barf here, the caller is to blame
+ rawsecret, err := fromBase64([]byte(secret))
+ if err != nil {
+ return nil, "", err
+ }
+
+ rr := m.Extra[len(m.Extra)-1].(*TSIG)
+ m.Extra = m.Extra[0 : len(m.Extra)-1] // kill the TSIG from the msg
+ mbuf, err := m.Pack()
+ if err != nil {
+ return nil, "", err
+ }
+ buf := tsigBuffer(mbuf, rr, requestMAC, timersOnly)
+
+ t := new(TSIG)
+ var h hash.Hash
+ switch rr.Algorithm {
+ case HmacMD5:
+ h = hmac.New(md5.New, []byte(rawsecret))
+ case HmacSHA1:
+ h = hmac.New(sha1.New, []byte(rawsecret))
+ case HmacSHA256:
+ h = hmac.New(sha256.New, []byte(rawsecret))
+ case HmacSHA512:
+ h = hmac.New(sha512.New, []byte(rawsecret))
+ default:
+ return nil, "", ErrKeyAlg
+ }
+ io.WriteString(h, string(buf))
+ t.MAC = hex.EncodeToString(h.Sum(nil))
+ t.MACSize = uint16(len(t.MAC) / 2) // Size is half!
+
+ t.Hdr = RR_Header{Name: rr.Hdr.Name, Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0}
+ t.Fudge = rr.Fudge
+ t.TimeSigned = rr.TimeSigned
+ t.Algorithm = rr.Algorithm
+ t.OrigId = m.Id
+
+ tbuf := make([]byte, t.len())
+ if off, err := PackRR(t, tbuf, 0, nil, false); err == nil {
+ tbuf = tbuf[:off] // reset to actual size used
+ } else {
+ return nil, "", err
+ }
+ mbuf = append(mbuf, tbuf...)
+ rawSetExtraLen(mbuf, uint16(len(m.Extra)+1))
+ return mbuf, t.MAC, nil
+}
+
+// TsigVerify verifies the TSIG on a message.
+// If the signature does not validate err contains the
+// error, otherwise it is nil.
+func TsigVerify(msg []byte, secret, requestMAC string, timersOnly bool) error {
+ rawsecret, err := fromBase64([]byte(secret))
+ if err != nil {
+ return err
+ }
+ // Strip the TSIG from the incoming msg
+ stripped, tsig, err := stripTsig(msg)
+ if err != nil {
+ return err
+ }
+
+ msgMAC, err := hex.DecodeString(tsig.MAC)
+ if err != nil {
+ return err
+ }
+
+ buf := tsigBuffer(stripped, tsig, requestMAC, timersOnly)
+
+ // Fudge factor works both ways. A message can arrive before it was signed because
+ // of clock skew.
+ now := uint64(time.Now().Unix())
+ ti := now - tsig.TimeSigned
+ if now < tsig.TimeSigned {
+ ti = tsig.TimeSigned - now
+ }
+ if uint64(tsig.Fudge) < ti {
+ return ErrTime
+ }
+
+ var h hash.Hash
+ switch tsig.Algorithm {
+ case HmacMD5:
+ h = hmac.New(md5.New, rawsecret)
+ case HmacSHA1:
+ h = hmac.New(sha1.New, rawsecret)
+ case HmacSHA256:
+ h = hmac.New(sha256.New, rawsecret)
+ case HmacSHA512:
+ h = hmac.New(sha512.New, rawsecret)
+ default:
+ return ErrKeyAlg
+ }
+ h.Write(buf)
+ if !hmac.Equal(h.Sum(nil), msgMAC) {
+ return ErrSig
+ }
+ return nil
+}
+
+// Create a wiredata buffer for the MAC calculation.
+func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []byte {
+ var buf []byte
+ if rr.TimeSigned == 0 {
+ rr.TimeSigned = uint64(time.Now().Unix())
+ }
+ if rr.Fudge == 0 {
+ rr.Fudge = 300 // Standard (RFC) default.
+ }
+
+ if requestMAC != "" {
+ m := new(macWireFmt)
+ m.MACSize = uint16(len(requestMAC) / 2)
+ m.MAC = requestMAC
+ buf = make([]byte, len(requestMAC)) // long enough
+ n, _ := PackStruct(m, buf, 0)
+ buf = buf[:n]
+ }
+
+ tsigvar := make([]byte, DefaultMsgSize)
+ if timersOnly {
+ tsig := new(timerWireFmt)
+ tsig.TimeSigned = rr.TimeSigned
+ tsig.Fudge = rr.Fudge
+ n, _ := PackStruct(tsig, tsigvar, 0)
+ tsigvar = tsigvar[:n]
+ } else {
+ tsig := new(tsigWireFmt)
+ tsig.Name = strings.ToLower(rr.Hdr.Name)
+ tsig.Class = ClassANY
+ tsig.Ttl = rr.Hdr.Ttl
+ tsig.Algorithm = strings.ToLower(rr.Algorithm)
+ tsig.TimeSigned = rr.TimeSigned
+ tsig.Fudge = rr.Fudge
+ tsig.Error = rr.Error
+ tsig.OtherLen = rr.OtherLen
+ tsig.OtherData = rr.OtherData
+ n, _ := PackStruct(tsig, tsigvar, 0)
+ tsigvar = tsigvar[:n]
+ }
+
+ if requestMAC != "" {
+ x := append(buf, msgbuf...)
+ buf = append(x, tsigvar...)
+ } else {
+ buf = append(msgbuf, tsigvar...)
+ }
+ return buf
+}
+
+// Strip the TSIG from the raw message.
+func stripTsig(msg []byte) ([]byte, *TSIG, error) {
+ // Copied from msg.go's Unpack()
+ // Header.
+ var dh Header
+ var err error
+ dns := new(Msg)
+ rr := new(TSIG)
+ off := 0
+ tsigoff := 0
+ if off, err = UnpackStruct(&dh, msg, off); err != nil {
+ return nil, nil, err
+ }
+ if dh.Arcount == 0 {
+ return nil, nil, ErrNoSig
+ }
+ // Rcode, see msg.go Unpack()
+ if int(dh.Bits&0xF) == RcodeNotAuth {
+ return nil, nil, ErrAuth
+ }
+
+ // Arrays.
+ dns.Question = make([]Question, dh.Qdcount)
+ dns.Answer = make([]RR, dh.Ancount)
+ dns.Ns = make([]RR, dh.Nscount)
+ dns.Extra = make([]RR, dh.Arcount)
+
+ for i := 0; i < len(dns.Question); i++ {
+ off, err = UnpackStruct(&dns.Question[i], msg, off)
+ if err != nil {
+ return nil, nil, err
+ }
+ }
+ for i := 0; i < len(dns.Answer); i++ {
+ dns.Answer[i], off, err = UnpackRR(msg, off)
+ if err != nil {
+ return nil, nil, err
+ }
+ }
+ for i := 0; i < len(dns.Ns); i++ {
+ dns.Ns[i], off, err = UnpackRR(msg, off)
+ if err != nil {
+ return nil, nil, err
+ }
+ }
+ for i := 0; i < len(dns.Extra); i++ {
+ tsigoff = off
+ dns.Extra[i], off, err = UnpackRR(msg, off)
+ if err != nil {
+ return nil, nil, err
+ }
+ if dns.Extra[i].Header().Rrtype == TypeTSIG {
+ rr = dns.Extra[i].(*TSIG)
+ // Adjust Arcount.
+ arcount, _ := unpackUint16(msg, 10)
+ msg[10], msg[11] = packUint16(arcount - 1)
+ break
+ }
+ }
+ if rr == nil {
+ return nil, nil, ErrNoSig
+ }
+ return msg[:tsigoff], rr, nil
+}
+
+// Translate the TSIG time signed into a date. There is no
+// need for RFC1982 calculations as this date is 48 bits.
+func tsigTimeToString(t uint64) string {
+ ti := time.Unix(int64(t), 0).UTC()
+ return ti.Format("20060102150405")
+}
diff --git a/vendor/github.com/miekg/dns/types.go b/vendor/github.com/miekg/dns/types.go
new file mode 100644
index 0000000..64143db
--- /dev/null
+++ b/vendor/github.com/miekg/dns/types.go
@@ -0,0 +1,1328 @@
+package dns
+
+import (
+ "encoding/base64"
+ "fmt"
+ "net"
+ "strconv"
+ "strings"
+ "time"
+)
+
+type (
+ // Type is a DNS type.
+ Type uint16
+ // Class is a DNS class.
+ Class uint16
+ // Name is a DNS domain name.
+ Name string
+)
+
+// Packet formats
+
+// Wire constants and supported types.
+const (
+ // valid RR_Header.Rrtype and Question.qtype
+
+ TypeNone uint16 = 0
+ TypeA uint16 = 1
+ TypeNS uint16 = 2
+ TypeMD uint16 = 3
+ TypeMF uint16 = 4
+ TypeCNAME uint16 = 5
+ TypeSOA uint16 = 6
+ TypeMB uint16 = 7
+ TypeMG uint16 = 8
+ TypeMR uint16 = 9
+ TypeNULL uint16 = 10
+ TypeWKS uint16 = 11
+ TypePTR uint16 = 12
+ TypeHINFO uint16 = 13
+ TypeMINFO uint16 = 14
+ TypeMX uint16 = 15
+ TypeTXT uint16 = 16
+ TypeRP uint16 = 17
+ TypeAFSDB uint16 = 18
+ TypeX25 uint16 = 19
+ TypeISDN uint16 = 20
+ TypeRT uint16 = 21
+ TypeNSAPPTR uint16 = 23
+ TypeSIG uint16 = 24
+ TypeKEY uint16 = 25
+ TypePX uint16 = 26
+ TypeGPOS uint16 = 27
+ TypeAAAA uint16 = 28
+ TypeLOC uint16 = 29
+ TypeNXT uint16 = 30
+ TypeEID uint16 = 31
+ TypeNIMLOC uint16 = 32
+ TypeSRV uint16 = 33
+ TypeATMA uint16 = 34
+ TypeNAPTR uint16 = 35
+ TypeKX uint16 = 36
+ TypeCERT uint16 = 37
+ TypeDNAME uint16 = 39
+ TypeOPT uint16 = 41 // EDNS
+ TypeDS uint16 = 43
+ TypeSSHFP uint16 = 44
+ TypeIPSECKEY uint16 = 45
+ TypeRRSIG uint16 = 46
+ TypeNSEC uint16 = 47
+ TypeDNSKEY uint16 = 48
+ TypeDHCID uint16 = 49
+ TypeNSEC3 uint16 = 50
+ TypeNSEC3PARAM uint16 = 51
+ TypeTLSA uint16 = 52
+ TypeHIP uint16 = 55
+ TypeNINFO uint16 = 56
+ TypeRKEY uint16 = 57
+ TypeTALINK uint16 = 58
+ TypeCDS uint16 = 59
+ TypeCDNSKEY uint16 = 60
+ TypeOPENPGPKEY uint16 = 61
+ TypeSPF uint16 = 99
+ TypeUINFO uint16 = 100
+ TypeUID uint16 = 101
+ TypeGID uint16 = 102
+ TypeUNSPEC uint16 = 103
+ TypeNID uint16 = 104
+ TypeL32 uint16 = 105
+ TypeL64 uint16 = 106
+ TypeLP uint16 = 107
+ TypeEUI48 uint16 = 108
+ TypeEUI64 uint16 = 109
+ TypeURI uint16 = 256
+ TypeCAA uint16 = 257
+
+ TypeTKEY uint16 = 249
+ TypeTSIG uint16 = 250
+
+ // valid Question.Qtype only
+ TypeIXFR uint16 = 251
+ TypeAXFR uint16 = 252
+ TypeMAILB uint16 = 253
+ TypeMAILA uint16 = 254
+ TypeANY uint16 = 255
+
+ TypeTA uint16 = 32768
+ TypeDLV uint16 = 32769
+ TypeReserved uint16 = 65535
+
+ // valid Question.Qclass
+ ClassINET = 1
+ ClassCSNET = 2
+ ClassCHAOS = 3
+ ClassHESIOD = 4
+ ClassNONE = 254
+ ClassANY = 255
+
+ // Message Response Codes.
+ RcodeSuccess = 0
+ RcodeFormatError = 1
+ RcodeServerFailure = 2
+ RcodeNameError = 3
+ RcodeNotImplemented = 4
+ RcodeRefused = 5
+ RcodeYXDomain = 6
+ RcodeYXRrset = 7
+ RcodeNXRrset = 8
+ RcodeNotAuth = 9
+ RcodeNotZone = 10
+ RcodeBadSig = 16 // TSIG
+ RcodeBadVers = 16 // EDNS0
+ RcodeBadKey = 17
+ RcodeBadTime = 18
+ RcodeBadMode = 19 // TKEY
+ RcodeBadName = 20
+ RcodeBadAlg = 21
+ RcodeBadTrunc = 22 // TSIG
+
+ // Message Opcodes. There is no 3.
+ OpcodeQuery = 0
+ OpcodeIQuery = 1
+ OpcodeStatus = 2
+ OpcodeNotify = 4
+ OpcodeUpdate = 5
+)
+
+// Headers is the wire format for the DNS packet header.
+type Header struct {
+ Id uint16
+ Bits uint16
+ Qdcount, Ancount, Nscount, Arcount uint16
+}
+
+const (
+ headerSize = 12
+
+ // Header.Bits
+ _QR = 1 << 15 // query/response (response=1)
+ _AA = 1 << 10 // authoritative
+ _TC = 1 << 9 // truncated
+ _RD = 1 << 8 // recursion desired
+ _RA = 1 << 7 // recursion available
+ _Z = 1 << 6 // Z
+ _AD = 1 << 5 // authticated data
+ _CD = 1 << 4 // checking disabled
+
+ LOC_EQUATOR = 1 << 31 // RFC 1876, Section 2.
+ LOC_PRIMEMERIDIAN = 1 << 31 // RFC 1876, Section 2.
+
+ LOC_HOURS = 60 * 1000
+ LOC_DEGREES = 60 * LOC_HOURS
+
+ LOC_ALTITUDEBASE = 100000
+)
+
+// Different Certificate Types, see RFC 4398, Section 2.1
+const (
+ CertPKIX = 1 + iota
+ CertSPKI
+ CertPGP
+ CertIPIX
+ CertISPKI
+ CertIPGP
+ CertACPKIX
+ CertIACPKIX
+ CertURI = 253
+ CertOID = 254
+)
+
+// CertTypeToString converts the Cert Type to its string representation.
+// See RFC 4398 and RFC 6944.
+var CertTypeToString = map[uint16]string{
+ CertPKIX: "PKIX",
+ CertSPKI: "SPKI",
+ CertPGP: "PGP",
+ CertIPIX: "IPIX",
+ CertISPKI: "ISPKI",
+ CertIPGP: "IPGP",
+ CertACPKIX: "ACPKIX",
+ CertIACPKIX: "IACPKIX",
+ CertURI: "URI",
+ CertOID: "OID",
+}
+
+// StringToCertType is the reverseof CertTypeToString.
+var StringToCertType = reverseInt16(CertTypeToString)
+
+//go:generate go run types_generate.go
+
+// Question holds a DNS question. There can be multiple questions in the
+// question section of a message. Usually there is just one.
+type Question struct {
+ Name string `dns:"cdomain-name"` // "cdomain-name" specifies encoding (and may be compressed)
+ Qtype uint16
+ Qclass uint16
+}
+
+func (q *Question) len() int {
+ return len(q.Name) + 1 + 2 + 2
+}
+
+func (q *Question) String() (s string) {
+ // prefix with ; (as in dig)
+ s = ";" + sprintName(q.Name) + "\t"
+ s += Class(q.Qclass).String() + "\t"
+ s += " " + Type(q.Qtype).String()
+ return s
+}
+
+// ANY is a wildcard record. See RFC 1035, Section 3.2.3. ANY
+// is named "*" there.
+type ANY struct {
+ Hdr RR_Header
+ // Does not have any rdata
+}
+
+func (rr *ANY) String() string { return rr.Hdr.String() }
+
+type CNAME struct {
+ Hdr RR_Header
+ Target string `dns:"cdomain-name"`
+}
+
+func (rr *CNAME) String() string { return rr.Hdr.String() + sprintName(rr.Target) }
+
+type HINFO struct {
+ Hdr RR_Header
+ Cpu string
+ Os string
+}
+
+func (rr *HINFO) String() string {
+ return rr.Hdr.String() + sprintTxt([]string{rr.Cpu, rr.Os})
+}
+
+type MB struct {
+ Hdr RR_Header
+ Mb string `dns:"cdomain-name"`
+}
+
+func (rr *MB) String() string { return rr.Hdr.String() + sprintName(rr.Mb) }
+
+type MG struct {
+ Hdr RR_Header
+ Mg string `dns:"cdomain-name"`
+}
+
+func (rr *MG) String() string { return rr.Hdr.String() + sprintName(rr.Mg) }
+
+type MINFO struct {
+ Hdr RR_Header
+ Rmail string `dns:"cdomain-name"`
+ Email string `dns:"cdomain-name"`
+}
+
+func (rr *MINFO) String() string {
+ return rr.Hdr.String() + sprintName(rr.Rmail) + " " + sprintName(rr.Email)
+}
+
+type MR struct {
+ Hdr RR_Header
+ Mr string `dns:"cdomain-name"`
+}
+
+func (rr *MR) String() string {
+ return rr.Hdr.String() + sprintName(rr.Mr)
+}
+
+type MF struct {
+ Hdr RR_Header
+ Mf string `dns:"cdomain-name"`
+}
+
+func (rr *MF) String() string {
+ return rr.Hdr.String() + sprintName(rr.Mf)
+}
+
+type MD struct {
+ Hdr RR_Header
+ Md string `dns:"cdomain-name"`
+}
+
+func (rr *MD) String() string {
+ return rr.Hdr.String() + sprintName(rr.Md)
+}
+
+type MX struct {
+ Hdr RR_Header
+ Preference uint16
+ Mx string `dns:"cdomain-name"`
+}
+
+func (rr *MX) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Preference)) + " " + sprintName(rr.Mx)
+}
+
+type AFSDB struct {
+ Hdr RR_Header
+ Subtype uint16
+ Hostname string `dns:"cdomain-name"`
+}
+
+func (rr *AFSDB) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Subtype)) + " " + sprintName(rr.Hostname)
+}
+
+type X25 struct {
+ Hdr RR_Header
+ PSDNAddress string
+}
+
+func (rr *X25) String() string {
+ return rr.Hdr.String() + rr.PSDNAddress
+}
+
+type RT struct {
+ Hdr RR_Header
+ Preference uint16
+ Host string `dns:"cdomain-name"`
+}
+
+func (rr *RT) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Preference)) + " " + sprintName(rr.Host)
+}
+
+type NS struct {
+ Hdr RR_Header
+ Ns string `dns:"cdomain-name"`
+}
+
+func (rr *NS) String() string {
+ return rr.Hdr.String() + sprintName(rr.Ns)
+}
+
+type PTR struct {
+ Hdr RR_Header
+ Ptr string `dns:"cdomain-name"`
+}
+
+func (rr *PTR) String() string {
+ return rr.Hdr.String() + sprintName(rr.Ptr)
+}
+
+type RP struct {
+ Hdr RR_Header
+ Mbox string `dns:"domain-name"`
+ Txt string `dns:"domain-name"`
+}
+
+func (rr *RP) String() string {
+ return rr.Hdr.String() + rr.Mbox + " " + sprintTxt([]string{rr.Txt})
+}
+
+type SOA struct {
+ Hdr RR_Header
+ Ns string `dns:"cdomain-name"`
+ Mbox string `dns:"cdomain-name"`
+ Serial uint32
+ Refresh uint32
+ Retry uint32
+ Expire uint32
+ Minttl uint32
+}
+
+func (rr *SOA) String() string {
+ return rr.Hdr.String() + sprintName(rr.Ns) + " " + sprintName(rr.Mbox) +
+ " " + strconv.FormatInt(int64(rr.Serial), 10) +
+ " " + strconv.FormatInt(int64(rr.Refresh), 10) +
+ " " + strconv.FormatInt(int64(rr.Retry), 10) +
+ " " + strconv.FormatInt(int64(rr.Expire), 10) +
+ " " + strconv.FormatInt(int64(rr.Minttl), 10)
+}
+
+type TXT struct {
+ Hdr RR_Header
+ Txt []string `dns:"txt"`
+}
+
+func (rr *TXT) String() string { return rr.Hdr.String() + sprintTxt(rr.Txt) }
+
+func sprintName(s string) string {
+ src := []byte(s)
+ dst := make([]byte, 0, len(src))
+ for i := 0; i < len(src); {
+ if i+1 < len(src) && src[i] == '\\' && src[i+1] == '.' {
+ dst = append(dst, src[i:i+2]...)
+ i += 2
+ } else {
+ b, n := nextByte(src, i)
+ if n == 0 {
+ i++ // dangling back slash
+ } else if b == '.' {
+ dst = append(dst, b)
+ } else {
+ dst = appendDomainNameByte(dst, b)
+ }
+ i += n
+ }
+ }
+ return string(dst)
+}
+
+func sprintTxtOctet(s string) string {
+ src := []byte(s)
+ dst := make([]byte, 0, len(src))
+ dst = append(dst, '"')
+ for i := 0; i < len(src); {
+ if i+1 < len(src) && src[i] == '\\' && src[i+1] == '.' {
+ dst = append(dst, src[i:i+2]...)
+ i += 2
+ } else {
+ b, n := nextByte(src, i)
+ if n == 0 {
+ i++ // dangling back slash
+ } else if b == '.' {
+ dst = append(dst, b)
+ } else {
+ if b < ' ' || b > '~' {
+ dst = appendByte(dst, b)
+ } else {
+ dst = append(dst, b)
+ }
+ }
+ i += n
+ }
+ }
+ dst = append(dst, '"')
+ return string(dst)
+}
+
+func sprintTxt(txt []string) string {
+ var out []byte
+ for i, s := range txt {
+ if i > 0 {
+ out = append(out, ` "`...)
+ } else {
+ out = append(out, '"')
+ }
+ bs := []byte(s)
+ for j := 0; j < len(bs); {
+ b, n := nextByte(bs, j)
+ if n == 0 {
+ break
+ }
+ out = appendTXTStringByte(out, b)
+ j += n
+ }
+ out = append(out, '"')
+ }
+ return string(out)
+}
+
+func appendDomainNameByte(s []byte, b byte) []byte {
+ switch b {
+ case '.', ' ', '\'', '@', ';', '(', ')': // additional chars to escape
+ return append(s, '\\', b)
+ }
+ return appendTXTStringByte(s, b)
+}
+
+func appendTXTStringByte(s []byte, b byte) []byte {
+ switch b {
+ case '\t':
+ return append(s, '\\', 't')
+ case '\r':
+ return append(s, '\\', 'r')
+ case '\n':
+ return append(s, '\\', 'n')
+ case '"', '\\':
+ return append(s, '\\', b)
+ }
+ if b < ' ' || b > '~' {
+ return appendByte(s, b)
+ }
+ return append(s, b)
+}
+
+func appendByte(s []byte, b byte) []byte {
+ var buf [3]byte
+ bufs := strconv.AppendInt(buf[:0], int64(b), 10)
+ s = append(s, '\\')
+ for i := 0; i < 3-len(bufs); i++ {
+ s = append(s, '0')
+ }
+ for _, r := range bufs {
+ s = append(s, r)
+ }
+ return s
+}
+
+func nextByte(b []byte, offset int) (byte, int) {
+ if offset >= len(b) {
+ return 0, 0
+ }
+ if b[offset] != '\\' {
+ // not an escape sequence
+ return b[offset], 1
+ }
+ switch len(b) - offset {
+ case 1: // dangling escape
+ return 0, 0
+ case 2, 3: // too short to be \ddd
+ default: // maybe \ddd
+ if isDigit(b[offset+1]) && isDigit(b[offset+2]) && isDigit(b[offset+3]) {
+ return dddToByte(b[offset+1:]), 4
+ }
+ }
+ // not \ddd, maybe a control char
+ switch b[offset+1] {
+ case 't':
+ return '\t', 2
+ case 'r':
+ return '\r', 2
+ case 'n':
+ return '\n', 2
+ default:
+ return b[offset+1], 2
+ }
+}
+
+type SPF struct {
+ Hdr RR_Header
+ Txt []string `dns:"txt"`
+}
+
+func (rr *SPF) String() string { return rr.Hdr.String() + sprintTxt(rr.Txt) }
+
+type SRV struct {
+ Hdr RR_Header
+ Priority uint16
+ Weight uint16
+ Port uint16
+ Target string `dns:"domain-name"`
+}
+
+func (rr *SRV) String() string {
+ return rr.Hdr.String() +
+ strconv.Itoa(int(rr.Priority)) + " " +
+ strconv.Itoa(int(rr.Weight)) + " " +
+ strconv.Itoa(int(rr.Port)) + " " + sprintName(rr.Target)
+}
+
+type NAPTR struct {
+ Hdr RR_Header
+ Order uint16
+ Preference uint16
+ Flags string
+ Service string
+ Regexp string
+ Replacement string `dns:"domain-name"`
+}
+
+func (rr *NAPTR) String() string {
+ return rr.Hdr.String() +
+ strconv.Itoa(int(rr.Order)) + " " +
+ strconv.Itoa(int(rr.Preference)) + " " +
+ "\"" + rr.Flags + "\" " +
+ "\"" + rr.Service + "\" " +
+ "\"" + rr.Regexp + "\" " +
+ rr.Replacement
+}
+
+// The CERT resource record, see RFC 4398.
+type CERT struct {
+ Hdr RR_Header
+ Type uint16
+ KeyTag uint16
+ Algorithm uint8
+ Certificate string `dns:"base64"`
+}
+
+func (rr *CERT) String() string {
+ var (
+ ok bool
+ certtype, algorithm string
+ )
+ if certtype, ok = CertTypeToString[rr.Type]; !ok {
+ certtype = strconv.Itoa(int(rr.Type))
+ }
+ if algorithm, ok = AlgorithmToString[rr.Algorithm]; !ok {
+ algorithm = strconv.Itoa(int(rr.Algorithm))
+ }
+ return rr.Hdr.String() + certtype +
+ " " + strconv.Itoa(int(rr.KeyTag)) +
+ " " + algorithm +
+ " " + rr.Certificate
+}
+
+// The DNAME resource record, see RFC 2672.
+type DNAME struct {
+ Hdr RR_Header
+ Target string `dns:"domain-name"`
+}
+
+func (rr *DNAME) String() string {
+ return rr.Hdr.String() + sprintName(rr.Target)
+}
+
+type A struct {
+ Hdr RR_Header
+ A net.IP `dns:"a"`
+}
+
+func (rr *A) String() string {
+ if rr.A == nil {
+ return rr.Hdr.String()
+ }
+ return rr.Hdr.String() + rr.A.String()
+}
+
+type AAAA struct {
+ Hdr RR_Header
+ AAAA net.IP `dns:"aaaa"`
+}
+
+func (rr *AAAA) String() string {
+ if rr.AAAA == nil {
+ return rr.Hdr.String()
+ }
+ return rr.Hdr.String() + rr.AAAA.String()
+}
+
+type PX struct {
+ Hdr RR_Header
+ Preference uint16
+ Map822 string `dns:"domain-name"`
+ Mapx400 string `dns:"domain-name"`
+}
+
+func (rr *PX) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Preference)) + " " + sprintName(rr.Map822) + " " + sprintName(rr.Mapx400)
+}
+
+type GPOS struct {
+ Hdr RR_Header
+ Longitude string
+ Latitude string
+ Altitude string
+}
+
+func (rr *GPOS) String() string {
+ return rr.Hdr.String() + rr.Longitude + " " + rr.Latitude + " " + rr.Altitude
+}
+
+type LOC struct {
+ Hdr RR_Header
+ Version uint8
+ Size uint8
+ HorizPre uint8
+ VertPre uint8
+ Latitude uint32
+ Longitude uint32
+ Altitude uint32
+}
+
+// cmToM takes a cm value expressed in RFC1876 SIZE mantissa/exponent
+// format and returns a string in m (two decimals for the cm)
+func cmToM(m, e uint8) string {
+ if e < 2 {
+ if e == 1 {
+ m *= 10
+ }
+
+ return fmt.Sprintf("0.%02d", m)
+ }
+
+ s := fmt.Sprintf("%d", m)
+ for e > 2 {
+ s += "0"
+ e--
+ }
+ return s
+}
+
+func (rr *LOC) String() string {
+ s := rr.Hdr.String()
+
+ lat := rr.Latitude
+ ns := "N"
+ if lat > LOC_EQUATOR {
+ lat = lat - LOC_EQUATOR
+ } else {
+ ns = "S"
+ lat = LOC_EQUATOR - lat
+ }
+ h := lat / LOC_DEGREES
+ lat = lat % LOC_DEGREES
+ m := lat / LOC_HOURS
+ lat = lat % LOC_HOURS
+ s += fmt.Sprintf("%02d %02d %0.3f %s ", h, m, (float64(lat) / 1000), ns)
+
+ lon := rr.Longitude
+ ew := "E"
+ if lon > LOC_PRIMEMERIDIAN {
+ lon = lon - LOC_PRIMEMERIDIAN
+ } else {
+ ew = "W"
+ lon = LOC_PRIMEMERIDIAN - lon
+ }
+ h = lon / LOC_DEGREES
+ lon = lon % LOC_DEGREES
+ m = lon / LOC_HOURS
+ lon = lon % LOC_HOURS
+ s += fmt.Sprintf("%02d %02d %0.3f %s ", h, m, (float64(lon) / 1000), ew)
+
+ var alt = float64(rr.Altitude) / 100
+ alt -= LOC_ALTITUDEBASE
+ if rr.Altitude%100 != 0 {
+ s += fmt.Sprintf("%.2fm ", alt)
+ } else {
+ s += fmt.Sprintf("%.0fm ", alt)
+ }
+
+ s += cmToM((rr.Size&0xf0)>>4, rr.Size&0x0f) + "m "
+ s += cmToM((rr.HorizPre&0xf0)>>4, rr.HorizPre&0x0f) + "m "
+ s += cmToM((rr.VertPre&0xf0)>>4, rr.VertPre&0x0f) + "m"
+
+ return s
+}
+
+// SIG is identical to RRSIG and nowadays only used for SIG(0), RFC2931.
+type SIG struct {
+ RRSIG
+}
+
+type RRSIG struct {
+ Hdr RR_Header
+ TypeCovered uint16
+ Algorithm uint8
+ Labels uint8
+ OrigTtl uint32
+ Expiration uint32
+ Inception uint32
+ KeyTag uint16
+ SignerName string `dns:"domain-name"`
+ Signature string `dns:"base64"`
+}
+
+func (rr *RRSIG) String() string {
+ s := rr.Hdr.String()
+ s += Type(rr.TypeCovered).String()
+ s += " " + strconv.Itoa(int(rr.Algorithm)) +
+ " " + strconv.Itoa(int(rr.Labels)) +
+ " " + strconv.FormatInt(int64(rr.OrigTtl), 10) +
+ " " + TimeToString(rr.Expiration) +
+ " " + TimeToString(rr.Inception) +
+ " " + strconv.Itoa(int(rr.KeyTag)) +
+ " " + sprintName(rr.SignerName) +
+ " " + rr.Signature
+ return s
+}
+
+type NSEC struct {
+ Hdr RR_Header
+ NextDomain string `dns:"domain-name"`
+ TypeBitMap []uint16 `dns:"nsec"`
+}
+
+func (rr *NSEC) String() string {
+ s := rr.Hdr.String() + sprintName(rr.NextDomain)
+ for i := 0; i < len(rr.TypeBitMap); i++ {
+ s += " " + Type(rr.TypeBitMap[i]).String()
+ }
+ return s
+}
+
+func (rr *NSEC) len() int {
+ l := rr.Hdr.len() + len(rr.NextDomain) + 1
+ lastwindow := uint32(2 ^ 32 + 1)
+ for _, t := range rr.TypeBitMap {
+ window := t / 256
+ if uint32(window) != lastwindow {
+ l += 1 + 32
+ }
+ lastwindow = uint32(window)
+ }
+ return l
+}
+
+type DLV struct {
+ DS
+}
+
+type CDS struct {
+ DS
+}
+
+type DS struct {
+ Hdr RR_Header
+ KeyTag uint16
+ Algorithm uint8
+ DigestType uint8
+ Digest string `dns:"hex"`
+}
+
+func (rr *DS) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.KeyTag)) +
+ " " + strconv.Itoa(int(rr.Algorithm)) +
+ " " + strconv.Itoa(int(rr.DigestType)) +
+ " " + strings.ToUpper(rr.Digest)
+}
+
+type KX struct {
+ Hdr RR_Header
+ Preference uint16
+ Exchanger string `dns:"domain-name"`
+}
+
+func (rr *KX) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Preference)) +
+ " " + sprintName(rr.Exchanger)
+}
+
+type TA struct {
+ Hdr RR_Header
+ KeyTag uint16
+ Algorithm uint8
+ DigestType uint8
+ Digest string `dns:"hex"`
+}
+
+func (rr *TA) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.KeyTag)) +
+ " " + strconv.Itoa(int(rr.Algorithm)) +
+ " " + strconv.Itoa(int(rr.DigestType)) +
+ " " + strings.ToUpper(rr.Digest)
+}
+
+type TALINK struct {
+ Hdr RR_Header
+ PreviousName string `dns:"domain-name"`
+ NextName string `dns:"domain-name"`
+}
+
+func (rr *TALINK) String() string {
+ return rr.Hdr.String() +
+ sprintName(rr.PreviousName) + " " + sprintName(rr.NextName)
+}
+
+type SSHFP struct {
+ Hdr RR_Header
+ Algorithm uint8
+ Type uint8
+ FingerPrint string `dns:"hex"`
+}
+
+func (rr *SSHFP) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Algorithm)) +
+ " " + strconv.Itoa(int(rr.Type)) +
+ " " + strings.ToUpper(rr.FingerPrint)
+}
+
+type IPSECKEY struct {
+ Hdr RR_Header
+ Precedence uint8
+ // GatewayType: 1: A record, 2: AAAA record, 3: domainname.
+ // 0 is use for no type and GatewayName should be "." then.
+ GatewayType uint8
+ Algorithm uint8
+ // Gateway can be an A record, AAAA record or a domain name.
+ GatewayA net.IP `dns:"a"`
+ GatewayAAAA net.IP `dns:"aaaa"`
+ GatewayName string `dns:"domain-name"`
+ PublicKey string `dns:"base64"`
+}
+
+func (rr *IPSECKEY) String() string {
+ s := rr.Hdr.String() + strconv.Itoa(int(rr.Precedence)) +
+ " " + strconv.Itoa(int(rr.GatewayType)) +
+ " " + strconv.Itoa(int(rr.Algorithm))
+ switch rr.GatewayType {
+ case 0:
+ fallthrough
+ case 3:
+ s += " " + rr.GatewayName
+ case 1:
+ s += " " + rr.GatewayA.String()
+ case 2:
+ s += " " + rr.GatewayAAAA.String()
+ default:
+ s += " ."
+ }
+ s += " " + rr.PublicKey
+ return s
+}
+
+func (rr *IPSECKEY) len() int {
+ l := rr.Hdr.len() + 3 + 1
+ switch rr.GatewayType {
+ default:
+ fallthrough
+ case 0:
+ fallthrough
+ case 3:
+ l += len(rr.GatewayName)
+ case 1:
+ l += 4
+ case 2:
+ l += 16
+ }
+ return l + base64.StdEncoding.DecodedLen(len(rr.PublicKey))
+}
+
+type KEY struct {
+ DNSKEY
+}
+
+type CDNSKEY struct {
+ DNSKEY
+}
+
+type DNSKEY struct {
+ Hdr RR_Header
+ Flags uint16
+ Protocol uint8
+ Algorithm uint8
+ PublicKey string `dns:"base64"`
+}
+
+func (rr *DNSKEY) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Flags)) +
+ " " + strconv.Itoa(int(rr.Protocol)) +
+ " " + strconv.Itoa(int(rr.Algorithm)) +
+ " " + rr.PublicKey
+}
+
+type RKEY struct {
+ Hdr RR_Header
+ Flags uint16
+ Protocol uint8
+ Algorithm uint8
+ PublicKey string `dns:"base64"`
+}
+
+func (rr *RKEY) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Flags)) +
+ " " + strconv.Itoa(int(rr.Protocol)) +
+ " " + strconv.Itoa(int(rr.Algorithm)) +
+ " " + rr.PublicKey
+}
+
+type NSAPPTR struct {
+ Hdr RR_Header
+ Ptr string `dns:"domain-name"`
+}
+
+func (rr *NSAPPTR) String() string { return rr.Hdr.String() + sprintName(rr.Ptr) }
+
+type NSEC3 struct {
+ Hdr RR_Header
+ Hash uint8
+ Flags uint8
+ Iterations uint16
+ SaltLength uint8
+ Salt string `dns:"size-hex"`
+ HashLength uint8
+ NextDomain string `dns:"size-base32"`
+ TypeBitMap []uint16 `dns:"nsec"`
+}
+
+func (rr *NSEC3) String() string {
+ s := rr.Hdr.String()
+ s += strconv.Itoa(int(rr.Hash)) +
+ " " + strconv.Itoa(int(rr.Flags)) +
+ " " + strconv.Itoa(int(rr.Iterations)) +
+ " " + saltToString(rr.Salt) +
+ " " + rr.NextDomain
+ for i := 0; i < len(rr.TypeBitMap); i++ {
+ s += " " + Type(rr.TypeBitMap[i]).String()
+ }
+ return s
+}
+
+func (rr *NSEC3) len() int {
+ l := rr.Hdr.len() + 6 + len(rr.Salt)/2 + 1 + len(rr.NextDomain) + 1
+ lastwindow := uint32(2 ^ 32 + 1)
+ for _, t := range rr.TypeBitMap {
+ window := t / 256
+ if uint32(window) != lastwindow {
+ l += 1 + 32
+ }
+ lastwindow = uint32(window)
+ }
+ return l
+}
+
+type NSEC3PARAM struct {
+ Hdr RR_Header
+ Hash uint8
+ Flags uint8
+ Iterations uint16
+ SaltLength uint8
+ Salt string `dns:"hex"`
+}
+
+func (rr *NSEC3PARAM) String() string {
+ s := rr.Hdr.String()
+ s += strconv.Itoa(int(rr.Hash)) +
+ " " + strconv.Itoa(int(rr.Flags)) +
+ " " + strconv.Itoa(int(rr.Iterations)) +
+ " " + saltToString(rr.Salt)
+ return s
+}
+
+type TKEY struct {
+ Hdr RR_Header
+ Algorithm string `dns:"domain-name"`
+ Inception uint32
+ Expiration uint32
+ Mode uint16
+ Error uint16
+ KeySize uint16
+ Key string
+ OtherLen uint16
+ OtherData string
+}
+
+func (rr *TKEY) String() string {
+ // It has no presentation format
+ return ""
+}
+
+// RFC3597 represents an unknown/generic RR.
+type RFC3597 struct {
+ Hdr RR_Header
+ Rdata string `dns:"hex"`
+}
+
+func (rr *RFC3597) String() string {
+ // Let's call it a hack
+ s := rfc3597Header(rr.Hdr)
+
+ s += "\\# " + strconv.Itoa(len(rr.Rdata)/2) + " " + rr.Rdata
+ return s
+}
+
+func rfc3597Header(h RR_Header) string {
+ var s string
+
+ s += sprintName(h.Name) + "\t"
+ s += strconv.FormatInt(int64(h.Ttl), 10) + "\t"
+ s += "CLASS" + strconv.Itoa(int(h.Class)) + "\t"
+ s += "TYPE" + strconv.Itoa(int(h.Rrtype)) + "\t"
+ return s
+}
+
+type URI struct {
+ Hdr RR_Header
+ Priority uint16
+ Weight uint16
+ Target string `dns:"octet"`
+}
+
+func (rr *URI) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Priority)) +
+ " " + strconv.Itoa(int(rr.Weight)) + " " + sprintTxtOctet(rr.Target)
+}
+
+type DHCID struct {
+ Hdr RR_Header
+ Digest string `dns:"base64"`
+}
+
+func (rr *DHCID) String() string { return rr.Hdr.String() + rr.Digest }
+
+type TLSA struct {
+ Hdr RR_Header
+ Usage uint8
+ Selector uint8
+ MatchingType uint8
+ Certificate string `dns:"hex"`
+}
+
+func (rr *TLSA) String() string {
+ return rr.Hdr.String() +
+ strconv.Itoa(int(rr.Usage)) +
+ " " + strconv.Itoa(int(rr.Selector)) +
+ " " + strconv.Itoa(int(rr.MatchingType)) +
+ " " + rr.Certificate
+}
+
+type HIP struct {
+ Hdr RR_Header
+ HitLength uint8
+ PublicKeyAlgorithm uint8
+ PublicKeyLength uint16
+ Hit string `dns:"hex"`
+ PublicKey string `dns:"base64"`
+ RendezvousServers []string `dns:"domain-name"`
+}
+
+func (rr *HIP) String() string {
+ s := rr.Hdr.String() +
+ strconv.Itoa(int(rr.PublicKeyAlgorithm)) +
+ " " + rr.Hit +
+ " " + rr.PublicKey
+ for _, d := range rr.RendezvousServers {
+ s += " " + sprintName(d)
+ }
+ return s
+}
+
+type NINFO struct {
+ Hdr RR_Header
+ ZSData []string `dns:"txt"`
+}
+
+func (rr *NINFO) String() string { return rr.Hdr.String() + sprintTxt(rr.ZSData) }
+
+type WKS struct {
+ Hdr RR_Header
+ Address net.IP `dns:"a"`
+ Protocol uint8
+ BitMap []uint16 `dns:"wks"`
+}
+
+func (rr *WKS) len() int {
+ // TODO: this is missing something...
+ return rr.Hdr.len() + net.IPv4len + 1
+}
+
+func (rr *WKS) String() (s string) {
+ s = rr.Hdr.String()
+ if rr.Address != nil {
+ s += rr.Address.String()
+ }
+ // TODO(miek): missing protocol here, see /etc/protocols
+ for i := 0; i < len(rr.BitMap); i++ {
+ // should lookup the port
+ s += " " + strconv.Itoa(int(rr.BitMap[i]))
+ }
+ return s
+}
+
+type NID struct {
+ Hdr RR_Header
+ Preference uint16
+ NodeID uint64
+}
+
+func (rr *NID) String() string {
+ s := rr.Hdr.String() + strconv.Itoa(int(rr.Preference))
+ node := fmt.Sprintf("%0.16x", rr.NodeID)
+ s += " " + node[0:4] + ":" + node[4:8] + ":" + node[8:12] + ":" + node[12:16]
+ return s
+}
+
+type L32 struct {
+ Hdr RR_Header
+ Preference uint16
+ Locator32 net.IP `dns:"a"`
+}
+
+func (rr *L32) String() string {
+ if rr.Locator32 == nil {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Preference))
+ }
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Preference)) +
+ " " + rr.Locator32.String()
+}
+
+type L64 struct {
+ Hdr RR_Header
+ Preference uint16
+ Locator64 uint64
+}
+
+func (rr *L64) String() string {
+ s := rr.Hdr.String() + strconv.Itoa(int(rr.Preference))
+ node := fmt.Sprintf("%0.16X", rr.Locator64)
+ s += " " + node[0:4] + ":" + node[4:8] + ":" + node[8:12] + ":" + node[12:16]
+ return s
+}
+
+type LP struct {
+ Hdr RR_Header
+ Preference uint16
+ Fqdn string `dns:"domain-name"`
+}
+
+func (rr *LP) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Preference)) + " " + sprintName(rr.Fqdn)
+}
+
+type EUI48 struct {
+ Hdr RR_Header
+ Address uint64 `dns:"uint48"`
+}
+
+func (rr *EUI48) String() string { return rr.Hdr.String() + euiToString(rr.Address, 48) }
+
+type EUI64 struct {
+ Hdr RR_Header
+ Address uint64
+}
+
+func (rr *EUI64) String() string { return rr.Hdr.String() + euiToString(rr.Address, 64) }
+
+type CAA struct {
+ Hdr RR_Header
+ Flag uint8
+ Tag string
+ Value string `dns:"octet"`
+}
+
+func (rr *CAA) String() string {
+ return rr.Hdr.String() + strconv.Itoa(int(rr.Flag)) + " " + rr.Tag + " " + sprintTxtOctet(rr.Value)
+}
+
+type UID struct {
+ Hdr RR_Header
+ Uid uint32
+}
+
+func (rr *UID) String() string { return rr.Hdr.String() + strconv.FormatInt(int64(rr.Uid), 10) }
+
+type GID struct {
+ Hdr RR_Header
+ Gid uint32
+}
+
+func (rr *GID) String() string { return rr.Hdr.String() + strconv.FormatInt(int64(rr.Gid), 10) }
+
+type UINFO struct {
+ Hdr RR_Header
+ Uinfo string
+}
+
+func (rr *UINFO) String() string { return rr.Hdr.String() + sprintTxt([]string{rr.Uinfo}) }
+
+type EID struct {
+ Hdr RR_Header
+ Endpoint string `dns:"hex"`
+}
+
+func (rr *EID) String() string { return rr.Hdr.String() + strings.ToUpper(rr.Endpoint) }
+
+type NIMLOC struct {
+ Hdr RR_Header
+ Locator string `dns:"hex"`
+}
+
+func (rr *NIMLOC) String() string { return rr.Hdr.String() + strings.ToUpper(rr.Locator) }
+
+type OPENPGPKEY struct {
+ Hdr RR_Header
+ PublicKey string `dns:"base64"`
+}
+
+func (rr *OPENPGPKEY) String() string { return rr.Hdr.String() + rr.PublicKey }
+
+// TimeToString translates the RRSIG's incep. and expir. times to the
+// string representation used when printing the record.
+// It takes serial arithmetic (RFC 1982) into account.
+func TimeToString(t uint32) string {
+ mod := ((int64(t) - time.Now().Unix()) / year68) - 1
+ if mod < 0 {
+ mod = 0
+ }
+ ti := time.Unix(int64(t)-(mod*year68), 0).UTC()
+ return ti.Format("20060102150405")
+}
+
+// StringToTime translates the RRSIG's incep. and expir. times from
+// string values like "20110403154150" to an 32 bit integer.
+// It takes serial arithmetic (RFC 1982) into account.
+func StringToTime(s string) (uint32, error) {
+ t, e := time.Parse("20060102150405", s)
+ if e != nil {
+ return 0, e
+ }
+ mod := (t.Unix() / year68) - 1
+ if mod < 0 {
+ mod = 0
+ }
+ return uint32(t.Unix() - (mod * year68)), nil
+}
+
+// saltToString converts a NSECX salt to uppercase and
+// returns "-" when it is empty
+func saltToString(s string) string {
+ if len(s) == 0 {
+ return "-"
+ }
+ return strings.ToUpper(s)
+}
+
+func euiToString(eui uint64, bits int) (hex string) {
+ switch bits {
+ case 64:
+ hex = fmt.Sprintf("%16.16x", eui)
+ hex = hex[0:2] + "-" + hex[2:4] + "-" + hex[4:6] + "-" + hex[6:8] +
+ "-" + hex[8:10] + "-" + hex[10:12] + "-" + hex[12:14] + "-" + hex[14:16]
+ case 48:
+ hex = fmt.Sprintf("%12.12x", eui)
+ hex = hex[0:2] + "-" + hex[2:4] + "-" + hex[4:6] + "-" + hex[6:8] +
+ "-" + hex[8:10] + "-" + hex[10:12]
+ }
+ return
+}
+
+// copyIP returns a copy of ip.
+func copyIP(ip net.IP) net.IP {
+ p := make(net.IP, len(ip))
+ copy(p, ip)
+ return p
+}
diff --git a/vendor/github.com/miekg/dns/udp.go b/vendor/github.com/miekg/dns/udp.go
new file mode 100644
index 0000000..fc86563
--- /dev/null
+++ b/vendor/github.com/miekg/dns/udp.go
@@ -0,0 +1,58 @@
+// +build !windows
+
+package dns
+
+import (
+ "net"
+ "syscall"
+)
+
+// SessionUDP holds the remote address and the associated
+// out-of-band data.
+type SessionUDP struct {
+ raddr *net.UDPAddr
+ context []byte
+}
+
+// RemoteAddr returns the remote network address.
+func (s *SessionUDP) RemoteAddr() net.Addr { return s.raddr }
+
+// setUDPSocketOptions sets the UDP socket options.
+// This function is implemented on a per platform basis. See udp_*.go for more details
+func setUDPSocketOptions(conn *net.UDPConn) error {
+ sa, err := getUDPSocketName(conn)
+ if err != nil {
+ return err
+ }
+ switch sa.(type) {
+ case *syscall.SockaddrInet6:
+ v6only, err := getUDPSocketOptions6Only(conn)
+ if err != nil {
+ return err
+ }
+ setUDPSocketOptions6(conn)
+ if !v6only {
+ setUDPSocketOptions4(conn)
+ }
+ case *syscall.SockaddrInet4:
+ setUDPSocketOptions4(conn)
+ }
+ return nil
+}
+
+// ReadFromSessionUDP acts just like net.UDPConn.ReadFrom(), but returns a session object instead of a
+// net.UDPAddr.
+func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDP, error) {
+ oob := make([]byte, 40)
+ n, oobn, _, raddr, err := conn.ReadMsgUDP(b, oob)
+ if err != nil {
+ return n, nil, err
+ }
+ return n, &SessionUDP{raddr, oob[:oobn]}, err
+}
+
+// WriteToSessionUDP acts just like net.UDPConn.WritetTo(), but uses a *SessionUDP instead of a net.Addr.
+func WriteToSessionUDP(conn *net.UDPConn, b []byte, session *SessionUDP) (int, error) {
+ n, _, err := conn.WriteMsgUDP(b, session.context, session.raddr)
+ return n, err
+}
diff --git a/vendor/github.com/miekg/dns/udp_linux.go b/vendor/github.com/miekg/dns/udp_linux.go
new file mode 100644
index 0000000..c62d218
--- /dev/null
+++ b/vendor/github.com/miekg/dns/udp_linux.go
@@ -0,0 +1,73 @@
+// +build linux
+
+package dns
+
+// See:
+// * http://stackoverflow.com/questions/3062205/setting-the-source-ip-for-a-udp-socket and
+// * http://blog.powerdns.com/2012/10/08/on-binding-datagram-udp-sockets-to-the-any-addresses/
+//
+// Why do we need this: When listening on 0.0.0.0 with UDP so kernel decides what is the outgoing
+// interface, this might not always be the correct one. This code will make sure the egress
+// packet's interface matched the ingress' one.
+
+import (
+ "net"
+ "syscall"
+)
+
+// setUDPSocketOptions4 prepares the v4 socket for sessions.
+func setUDPSocketOptions4(conn *net.UDPConn) error {
+ file, err := conn.File()
+ if err != nil {
+ return err
+ }
+ if err := syscall.SetsockoptInt(int(file.Fd()), syscall.IPPROTO_IP, syscall.IP_PKTINFO, 1); err != nil {
+ return err
+ }
+ // Calling File() above results in the connection becoming blocking, we must fix that.
+ // See https://github.com/miekg/dns/issues/279
+ err = syscall.SetNonblock(int(file.Fd()), true)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+// setUDPSocketOptions6 prepares the v6 socket for sessions.
+func setUDPSocketOptions6(conn *net.UDPConn) error {
+ file, err := conn.File()
+ if err != nil {
+ return err
+ }
+ if err := syscall.SetsockoptInt(int(file.Fd()), syscall.IPPROTO_IPV6, syscall.IPV6_RECVPKTINFO, 1); err != nil {
+ return err
+ }
+ err = syscall.SetNonblock(int(file.Fd()), true)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+// getUDPSocketOption6Only return true if the socket is v6 only and false when it is v4/v6 combined
+// (dualstack).
+func getUDPSocketOptions6Only(conn *net.UDPConn) (bool, error) {
+ file, err := conn.File()
+ if err != nil {
+ return false, err
+ }
+ // dual stack. See http://stackoverflow.com/questions/1618240/how-to-support-both-ipv4-and-ipv6-connections
+ v6only, err := syscall.GetsockoptInt(int(file.Fd()), syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY)
+ if err != nil {
+ return false, err
+ }
+ return v6only == 1, nil
+}
+
+func getUDPSocketName(conn *net.UDPConn) (syscall.Sockaddr, error) {
+ file, err := conn.File()
+ if err != nil {
+ return nil, err
+ }
+ return syscall.Getsockname(int(file.Fd()))
+}
diff --git a/vendor/github.com/miekg/dns/udp_other.go b/vendor/github.com/miekg/dns/udp_other.go
new file mode 100644
index 0000000..c38dd3e
--- /dev/null
+++ b/vendor/github.com/miekg/dns/udp_other.go
@@ -0,0 +1,17 @@
+// +build !linux
+
+package dns
+
+import (
+ "net"
+ "syscall"
+)
+
+// These do nothing. See udp_linux.go for an example of how to implement this.
+
+// We tried to adhire to some kind of naming scheme.
+
+func setUDPSocketOptions4(conn *net.UDPConn) error { return nil }
+func setUDPSocketOptions6(conn *net.UDPConn) error { return nil }
+func getUDPSocketOptions6Only(conn *net.UDPConn) (bool, error) { return false, nil }
+func getUDPSocketName(conn *net.UDPConn) (syscall.Sockaddr, error) { return nil, nil }
diff --git a/vendor/github.com/miekg/dns/udp_windows.go b/vendor/github.com/miekg/dns/udp_windows.go
new file mode 100644
index 0000000..2ce4b33
--- /dev/null
+++ b/vendor/github.com/miekg/dns/udp_windows.go
@@ -0,0 +1,34 @@
+// +build windows
+
+package dns
+
+import "net"
+
+type SessionUDP struct {
+ raddr *net.UDPAddr
+}
+
+// ReadFromSessionUDP acts just like net.UDPConn.ReadFrom(), but returns a session object instead of a
+// net.UDPAddr.
+func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDP, error) {
+ n, raddr, err := conn.ReadFrom(b)
+ if err != nil {
+ return n, nil, err
+ }
+ session := &SessionUDP{raddr.(*net.UDPAddr)}
+ return n, session, err
+}
+
+// WriteToSessionUDP acts just like net.UDPConn.WritetTo(), but uses a *SessionUDP instead of a net.Addr.
+func WriteToSessionUDP(conn *net.UDPConn, b []byte, session *SessionUDP) (int, error) {
+ n, err := conn.WriteTo(b, session.raddr)
+ return n, err
+}
+
+func (s *SessionUDP) RemoteAddr() net.Addr { return s.raddr }
+
+// setUDPSocketOptions sets the UDP socket options.
+// This function is implemented on a per platform basis. See udp_*.go for more details
+func setUDPSocketOptions(conn *net.UDPConn) error {
+ return nil
+}
diff --git a/vendor/github.com/miekg/dns/update.go b/vendor/github.com/miekg/dns/update.go
new file mode 100644
index 0000000..3539987
--- /dev/null
+++ b/vendor/github.com/miekg/dns/update.go
@@ -0,0 +1,94 @@
+package dns
+
+// NameUsed sets the RRs in the prereq section to
+// "Name is in use" RRs. RFC 2136 section 2.4.4.
+func (u *Msg) NameUsed(rr []RR) {
+ u.Answer = make([]RR, len(rr))
+ for i, r := range rr {
+ u.Answer[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassANY}}
+ }
+}
+
+// NameNotUsed sets the RRs in the prereq section to
+// "Name is in not use" RRs. RFC 2136 section 2.4.5.
+func (u *Msg) NameNotUsed(rr []RR) {
+ u.Answer = make([]RR, len(rr))
+ for i, r := range rr {
+ u.Answer[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassNONE}}
+ }
+}
+
+// Used sets the RRs in the prereq section to
+// "RRset exists (value dependent -- with rdata)" RRs. RFC 2136 section 2.4.2.
+func (u *Msg) Used(rr []RR) {
+ if len(u.Question) == 0 {
+ panic("dns: empty question section")
+ }
+ u.Answer = make([]RR, len(rr))
+ for i, r := range rr {
+ u.Answer[i] = r
+ u.Answer[i].Header().Class = u.Question[0].Qclass
+ }
+}
+
+// RRsetUsed sets the RRs in the prereq section to
+// "RRset exists (value independent -- no rdata)" RRs. RFC 2136 section 2.4.1.
+func (u *Msg) RRsetUsed(rr []RR) {
+ u.Answer = make([]RR, len(rr))
+ for i, r := range rr {
+ u.Answer[i] = r
+ u.Answer[i].Header().Class = ClassANY
+ u.Answer[i].Header().Ttl = 0
+ u.Answer[i].Header().Rdlength = 0
+ }
+}
+
+// RRsetNotUsed sets the RRs in the prereq section to
+// "RRset does not exist" RRs. RFC 2136 section 2.4.3.
+func (u *Msg) RRsetNotUsed(rr []RR) {
+ u.Answer = make([]RR, len(rr))
+ for i, r := range rr {
+ u.Answer[i] = r
+ u.Answer[i].Header().Class = ClassNONE
+ u.Answer[i].Header().Rdlength = 0
+ u.Answer[i].Header().Ttl = 0
+ }
+}
+
+// Insert creates a dynamic update packet that adds an complete RRset, see RFC 2136 section 2.5.1.
+func (u *Msg) Insert(rr []RR) {
+ if len(u.Question) == 0 {
+ panic("dns: empty question section")
+ }
+ u.Ns = make([]RR, len(rr))
+ for i, r := range rr {
+ u.Ns[i] = r
+ u.Ns[i].Header().Class = u.Question[0].Qclass
+ }
+}
+
+// RemoveRRset creates a dynamic update packet that deletes an RRset, see RFC 2136 section 2.5.2.
+func (u *Msg) RemoveRRset(rr []RR) {
+ u.Ns = make([]RR, len(rr))
+ for i, r := range rr {
+ u.Ns[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: r.Header().Rrtype, Class: ClassANY}}
+ }
+}
+
+// RemoveName creates a dynamic update packet that deletes all RRsets of a name, see RFC 2136 section 2.5.3
+func (u *Msg) RemoveName(rr []RR) {
+ u.Ns = make([]RR, len(rr))
+ for i, r := range rr {
+ u.Ns[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassANY}}
+ }
+}
+
+// Remove creates a dynamic update packet deletes RR from the RRSset, see RFC 2136 section 2.5.4
+func (u *Msg) Remove(rr []RR) {
+ u.Ns = make([]RR, len(rr))
+ for i, r := range rr {
+ u.Ns[i] = r
+ u.Ns[i].Header().Class = ClassNONE
+ u.Ns[i].Header().Ttl = 0
+ }
+}
diff --git a/vendor/github.com/miekg/dns/xfr.go b/vendor/github.com/miekg/dns/xfr.go
new file mode 100644
index 0000000..7d3a67b
--- /dev/null
+++ b/vendor/github.com/miekg/dns/xfr.go
@@ -0,0 +1,244 @@
+package dns
+
+import (
+ "time"
+)
+
+// Envelope is used when doing a zone transfer with a remote server.
+type Envelope struct {
+ RR []RR // The set of RRs in the answer section of the xfr reply message.
+ Error error // If something went wrong, this contains the error.
+}
+
+// A Transfer defines parameters that are used during a zone transfer.
+type Transfer struct {
+ *Conn
+ DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds
+ ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds
+ WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds
+ TsigSecret map[string]string // Secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be fully qualified
+ tsigTimersOnly bool
+}
+
+// Think we need to away to stop the transfer
+
+// In performs an incoming transfer with the server in a.
+// If you would like to set the source IP, or some other attribute
+// of a Dialer for a Transfer, you can do so by specifying the attributes
+// in the Transfer.Conn:
+//
+// d := net.Dialer{LocalAddr: transfer_source}
+// con, err := d.Dial("tcp", master)
+// dnscon := &dns.Conn{Conn:con}
+// transfer = &dns.Transfer{Conn: dnscon}
+// channel, err := transfer.In(message, master)
+//
+func (t *Transfer) In(q *Msg, a string) (env chan *Envelope, err error) {
+ timeout := dnsTimeout
+ if t.DialTimeout != 0 {
+ timeout = t.DialTimeout
+ }
+ if t.Conn == nil {
+ t.Conn, err = DialTimeout("tcp", a, timeout)
+ if err != nil {
+ return nil, err
+ }
+ }
+ if err := t.WriteMsg(q); err != nil {
+ return nil, err
+ }
+ env = make(chan *Envelope)
+ go func() {
+ if q.Question[0].Qtype == TypeAXFR {
+ go t.inAxfr(q.Id, env)
+ return
+ }
+ if q.Question[0].Qtype == TypeIXFR {
+ go t.inIxfr(q.Id, env)
+ return
+ }
+ }()
+ return env, nil
+}
+
+func (t *Transfer) inAxfr(id uint16, c chan *Envelope) {
+ first := true
+ defer t.Close()
+ defer close(c)
+ timeout := dnsTimeout
+ if t.ReadTimeout != 0 {
+ timeout = t.ReadTimeout
+ }
+ for {
+ t.Conn.SetReadDeadline(time.Now().Add(timeout))
+ in, err := t.ReadMsg()
+ if err != nil {
+ c <- &Envelope{nil, err}
+ return
+ }
+ if id != in.Id {
+ c <- &Envelope{in.Answer, ErrId}
+ return
+ }
+ if first {
+ if !isSOAFirst(in) {
+ c <- &Envelope{in.Answer, ErrSoa}
+ return
+ }
+ first = !first
+ // only one answer that is SOA, receive more
+ if len(in.Answer) == 1 {
+ t.tsigTimersOnly = true
+ c <- &Envelope{in.Answer, nil}
+ continue
+ }
+ }
+
+ if !first {
+ t.tsigTimersOnly = true // Subsequent envelopes use this.
+ if isSOALast(in) {
+ c <- &Envelope{in.Answer, nil}
+ return
+ }
+ c <- &Envelope{in.Answer, nil}
+ }
+ }
+}
+
+func (t *Transfer) inIxfr(id uint16, c chan *Envelope) {
+ serial := uint32(0) // The first serial seen is the current server serial
+ first := true
+ defer t.Close()
+ defer close(c)
+ timeout := dnsTimeout
+ if t.ReadTimeout != 0 {
+ timeout = t.ReadTimeout
+ }
+ for {
+ t.SetReadDeadline(time.Now().Add(timeout))
+ in, err := t.ReadMsg()
+ if err != nil {
+ c <- &Envelope{nil, err}
+ return
+ }
+ if id != in.Id {
+ c <- &Envelope{in.Answer, ErrId}
+ return
+ }
+ if first {
+ // A single SOA RR signals "no changes"
+ if len(in.Answer) == 1 && isSOAFirst(in) {
+ c <- &Envelope{in.Answer, nil}
+ return
+ }
+
+ // Check if the returned answer is ok
+ if !isSOAFirst(in) {
+ c <- &Envelope{in.Answer, ErrSoa}
+ return
+ }
+ // This serial is important
+ serial = in.Answer[0].(*SOA).Serial
+ first = !first
+ }
+
+ // Now we need to check each message for SOA records, to see what we need to do
+ if !first {
+ t.tsigTimersOnly = true
+ // If the last record in the IXFR contains the servers' SOA, we should quit
+ if v, ok := in.Answer[len(in.Answer)-1].(*SOA); ok {
+ if v.Serial == serial {
+ c <- &Envelope{in.Answer, nil}
+ return
+ }
+ }
+ c <- &Envelope{in.Answer, nil}
+ }
+ }
+}
+
+// Out performs an outgoing transfer with the client connecting in w.
+// Basic use pattern:
+//
+// ch := make(chan *dns.Envelope)
+// tr := new(dns.Transfer)
+// tr.Out(w, r, ch)
+// c <- &dns.Envelope{RR: []dns.RR{soa, rr1, rr2, rr3, soa}}
+// close(ch)
+// w.Hijack()
+// // w.Close() // Client closes connection
+//
+// The server is responsible for sending the correct sequence of RRs through the
+// channel ch.
+func (t *Transfer) Out(w ResponseWriter, q *Msg, ch chan *Envelope) error {
+ for x := range ch {
+ r := new(Msg)
+ // Compress?
+ r.SetReply(q)
+ r.Authoritative = true
+ // assume it fits TODO(miek): fix
+ r.Answer = append(r.Answer, x.RR...)
+ if err := w.WriteMsg(r); err != nil {
+ return err
+ }
+ }
+ w.TsigTimersOnly(true)
+ return nil
+}
+
+// ReadMsg reads a message from the transfer connection t.
+func (t *Transfer) ReadMsg() (*Msg, error) {
+ m := new(Msg)
+ p := make([]byte, MaxMsgSize)
+ n, err := t.Read(p)
+ if err != nil && n == 0 {
+ return nil, err
+ }
+ p = p[:n]
+ if err := m.Unpack(p); err != nil {
+ return nil, err
+ }
+ if ts := m.IsTsig(); ts != nil && t.TsigSecret != nil {
+ if _, ok := t.TsigSecret[ts.Hdr.Name]; !ok {
+ return m, ErrSecret
+ }
+ // Need to work on the original message p, as that was used to calculate the tsig.
+ err = TsigVerify(p, t.TsigSecret[ts.Hdr.Name], t.tsigRequestMAC, t.tsigTimersOnly)
+ t.tsigRequestMAC = ts.MAC
+ }
+ return m, err
+}
+
+// WriteMsg writes a message through the transfer connection t.
+func (t *Transfer) WriteMsg(m *Msg) (err error) {
+ var out []byte
+ if ts := m.IsTsig(); ts != nil && t.TsigSecret != nil {
+ if _, ok := t.TsigSecret[ts.Hdr.Name]; !ok {
+ return ErrSecret
+ }
+ out, t.tsigRequestMAC, err = TsigGenerate(m, t.TsigSecret[ts.Hdr.Name], t.tsigRequestMAC, t.tsigTimersOnly)
+ } else {
+ out, err = m.Pack()
+ }
+ if err != nil {
+ return err
+ }
+ if _, err = t.Write(out); err != nil {
+ return err
+ }
+ return nil
+}
+
+func isSOAFirst(in *Msg) bool {
+ if len(in.Answer) > 0 {
+ return in.Answer[0].Header().Rrtype == TypeSOA
+ }
+ return false
+}
+
+func isSOALast(in *Msg) bool {
+ if len(in.Answer) > 0 {
+ return in.Answer[len(in.Answer)-1].Header().Rrtype == TypeSOA
+ }
+ return false
+}
diff --git a/vendor/github.com/miekg/dns/zgenerate.go b/vendor/github.com/miekg/dns/zgenerate.go
new file mode 100644
index 0000000..c506e96
--- /dev/null
+++ b/vendor/github.com/miekg/dns/zgenerate.go
@@ -0,0 +1,158 @@
+package dns
+
+import (
+ "bytes"
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// Parse the $GENERATE statement as used in BIND9 zones.
+// See http://www.zytrax.com/books/dns/ch8/generate.html for instance.
+// We are called after '$GENERATE '. After which we expect:
+// * the range (12-24/2)
+// * lhs (ownername)
+// * [[ttl][class]]
+// * type
+// * rhs (rdata)
+// But we are lazy here, only the range is parsed *all* occurences
+// of $ after that are interpreted.
+// Any error are returned as a string value, the empty string signals
+// "no error".
+func generate(l lex, c chan lex, t chan *Token, o string) string {
+ step := 1
+ if i := strings.IndexAny(l.token, "/"); i != -1 {
+ if i+1 == len(l.token) {
+ return "bad step in $GENERATE range"
+ }
+ if s, e := strconv.Atoi(l.token[i+1:]); e == nil {
+ if s < 0 {
+ return "bad step in $GENERATE range"
+ }
+ step = s
+ } else {
+ return "bad step in $GENERATE range"
+ }
+ l.token = l.token[:i]
+ }
+ sx := strings.SplitN(l.token, "-", 2)
+ if len(sx) != 2 {
+ return "bad start-stop in $GENERATE range"
+ }
+ start, err := strconv.Atoi(sx[0])
+ if err != nil {
+ return "bad start in $GENERATE range"
+ }
+ end, err := strconv.Atoi(sx[1])
+ if err != nil {
+ return "bad stop in $GENERATE range"
+ }
+ if end < 0 || start < 0 || end < start {
+ return "bad range in $GENERATE range"
+ }
+
+ <-c // _BLANK
+ // Create a complete new string, which we then parse again.
+ s := ""
+BuildRR:
+ l = <-c
+ if l.value != zNewline && l.value != zEOF {
+ s += l.token
+ goto BuildRR
+ }
+ for i := start; i <= end; i += step {
+ var (
+ escape bool
+ dom bytes.Buffer
+ mod string
+ err string
+ offset int
+ )
+
+ for j := 0; j < len(s); j++ { // No 'range' because we need to jump around
+ switch s[j] {
+ case '\\':
+ if escape {
+ dom.WriteByte('\\')
+ escape = false
+ continue
+ }
+ escape = true
+ case '$':
+ mod = "%d"
+ offset = 0
+ if escape {
+ dom.WriteByte('$')
+ escape = false
+ continue
+ }
+ escape = false
+ if j+1 >= len(s) { // End of the string
+ dom.WriteString(fmt.Sprintf(mod, i+offset))
+ continue
+ } else {
+ if s[j+1] == '$' {
+ dom.WriteByte('$')
+ j++
+ continue
+ }
+ }
+ // Search for { and }
+ if s[j+1] == '{' { // Modifier block
+ sep := strings.Index(s[j+2:], "}")
+ if sep == -1 {
+ return "bad modifier in $GENERATE"
+ }
+ mod, offset, err = modToPrintf(s[j+2 : j+2+sep])
+ if err != "" {
+ return err
+ }
+ j += 2 + sep // Jump to it
+ }
+ dom.WriteString(fmt.Sprintf(mod, i+offset))
+ default:
+ if escape { // Pretty useless here
+ escape = false
+ continue
+ }
+ dom.WriteByte(s[j])
+ }
+ }
+ // Re-parse the RR and send it on the current channel t
+ rx, e := NewRR("$ORIGIN " + o + "\n" + dom.String())
+ if e != nil {
+ return e.(*ParseError).err
+ }
+ t <- &Token{RR: rx}
+ // Its more efficient to first built the rrlist and then parse it in
+ // one go! But is this a problem?
+ }
+ return ""
+}
+
+// Convert a $GENERATE modifier 0,0,d to something Printf can deal with.
+func modToPrintf(s string) (string, int, string) {
+ xs := strings.SplitN(s, ",", 3)
+ if len(xs) != 3 {
+ return "", 0, "bad modifier in $GENERATE"
+ }
+ // xs[0] is offset, xs[1] is width, xs[2] is base
+ if xs[2] != "o" && xs[2] != "d" && xs[2] != "x" && xs[2] != "X" {
+ return "", 0, "bad base in $GENERATE"
+ }
+ offset, err := strconv.Atoi(xs[0])
+ if err != nil || offset > 255 {
+ return "", 0, "bad offset in $GENERATE"
+ }
+ width, err := strconv.Atoi(xs[1])
+ if err != nil || width > 255 {
+ return "", offset, "bad width in $GENERATE"
+ }
+ switch {
+ case width < 0:
+ return "", offset, "bad width in $GENERATE"
+ case width == 0:
+ return "%" + xs[1] + xs[2], offset, ""
+ }
+ return "%0" + xs[1] + xs[2], offset, ""
+}
diff --git a/vendor/github.com/miekg/dns/zscan.go b/vendor/github.com/miekg/dns/zscan.go
new file mode 100644
index 0000000..b0f46b1
--- /dev/null
+++ b/vendor/github.com/miekg/dns/zscan.go
@@ -0,0 +1,974 @@
+package dns
+
+import (
+ "io"
+ "log"
+ "os"
+ "strconv"
+ "strings"
+)
+
+type debugging bool
+
+const debug debugging = false
+
+func (d debugging) Printf(format string, args ...interface{}) {
+ if d {
+ log.Printf(format, args...)
+ }
+}
+
+const maxTok = 2048 // Largest token we can return.
+const maxUint16 = 1<<16 - 1
+
+// Tokinize a RFC 1035 zone file. The tokenizer will normalize it:
+// * Add ownernames if they are left blank;
+// * Suppress sequences of spaces;
+// * Make each RR fit on one line (_NEWLINE is send as last)
+// * Handle comments: ;
+// * Handle braces - anywhere.
+const (
+ // Zonefile
+ zEOF = iota
+ zString
+ zBlank
+ zQuote
+ zNewline
+ zRrtpe
+ zOwner
+ zClass
+ zDirOrigin // $ORIGIN
+ zDirTtl // $TTL
+ zDirInclude // $INCLUDE
+ zDirGenerate // $GENERATE
+
+ // Privatekey file
+ zValue
+ zKey
+
+ zExpectOwnerDir // Ownername
+ zExpectOwnerBl // Whitespace after the ownername
+ zExpectAny // Expect rrtype, ttl or class
+ zExpectAnyNoClass // Expect rrtype or ttl
+ zExpectAnyNoClassBl // The whitespace after _EXPECT_ANY_NOCLASS
+ zExpectAnyNoTtl // Expect rrtype or class
+ zExpectAnyNoTtlBl // Whitespace after _EXPECT_ANY_NOTTL
+ zExpectRrtype // Expect rrtype
+ zExpectRrtypeBl // Whitespace BEFORE rrtype
+ zExpectRdata // The first element of the rdata
+ zExpectDirTtlBl // Space after directive $TTL
+ zExpectDirTtl // Directive $TTL
+ zExpectDirOriginBl // Space after directive $ORIGIN
+ zExpectDirOrigin // Directive $ORIGIN
+ zExpectDirIncludeBl // Space after directive $INCLUDE
+ zExpectDirInclude // Directive $INCLUDE
+ zExpectDirGenerate // Directive $GENERATE
+ zExpectDirGenerateBl // Space after directive $GENERATE
+)
+
+// ParseError is a parsing error. It contains the parse error and the location in the io.Reader
+// where the error occured.
+type ParseError struct {
+ file string
+ err string
+ lex lex
+}
+
+func (e *ParseError) Error() (s string) {
+ if e.file != "" {
+ s = e.file + ": "
+ }
+ s += "dns: " + e.err + ": " + strconv.QuoteToASCII(e.lex.token) + " at line: " +
+ strconv.Itoa(e.lex.line) + ":" + strconv.Itoa(e.lex.column)
+ return
+}
+
+type lex struct {
+ token string // text of the token
+ tokenUpper string // uppercase text of the token
+ length int // lenght of the token
+ err bool // when true, token text has lexer error
+ value uint8 // value: zString, _BLANK, etc.
+ line int // line in the file
+ column int // column in the file
+ torc uint16 // type or class as parsed in the lexer, we only need to look this up in the grammar
+ comment string // any comment text seen
+}
+
+// Token holds the token that are returned when a zone file is parsed.
+type Token struct {
+ // The scanned resource record when error is not nil.
+ RR
+ // When an error occured, this has the error specifics.
+ Error *ParseError
+ // A potential comment positioned after the RR and on the same line.
+ Comment string
+}
+
+// NewRR reads the RR contained in the string s. Only the first RR is
+// returned. If s contains no RR, return nil with no error. The class
+// defaults to IN and TTL defaults to 3600. The full zone file syntax
+// like $TTL, $ORIGIN, etc. is supported. All fields of the returned
+// RR are set, except RR.Header().Rdlength which is set to 0.
+func NewRR(s string) (RR, error) {
+ if len(s) > 0 && s[len(s)-1] != '\n' { // We need a closing newline
+ return ReadRR(strings.NewReader(s+"\n"), "")
+ }
+ return ReadRR(strings.NewReader(s), "")
+}
+
+// ReadRR reads the RR contained in q.
+// See NewRR for more documentation.
+func ReadRR(q io.Reader, filename string) (RR, error) {
+ r := <-parseZoneHelper(q, ".", filename, 1)
+ if r == nil {
+ return nil, nil
+ }
+
+ if r.Error != nil {
+ return nil, r.Error
+ }
+ return r.RR, nil
+}
+
+// ParseZone reads a RFC 1035 style zonefile from r. It returns *Tokens on the
+// returned channel, which consist out the parsed RR, a potential comment or an error.
+// If there is an error the RR is nil. The string file is only used
+// in error reporting. The string origin is used as the initial origin, as
+// if the file would start with: $ORIGIN origin .
+// The directives $INCLUDE, $ORIGIN, $TTL and $GENERATE are supported.
+// The channel t is closed by ParseZone when the end of r is reached.
+//
+// Basic usage pattern when reading from a string (z) containing the
+// zone data:
+//
+// for x := range dns.ParseZone(strings.NewReader(z), "", "") {
+// if x.Error != nil {
+// // log.Println(x.Error)
+// } else {
+// // Do something with x.RR
+// }
+// }
+//
+// Comments specified after an RR (and on the same line!) are returned too:
+//
+// foo. IN A 10.0.0.1 ; this is a comment
+//
+// The text "; this is comment" is returned in Token.Comment. Comments inside the
+// RR are discarded. Comments on a line by themselves are discarded too.
+func ParseZone(r io.Reader, origin, file string) chan *Token {
+ return parseZoneHelper(r, origin, file, 10000)
+}
+
+func parseZoneHelper(r io.Reader, origin, file string, chansize int) chan *Token {
+ t := make(chan *Token, chansize)
+ go parseZone(r, origin, file, t, 0)
+ return t
+}
+
+func parseZone(r io.Reader, origin, f string, t chan *Token, include int) {
+ defer func() {
+ if include == 0 {
+ close(t)
+ }
+ }()
+ s := scanInit(r)
+ c := make(chan lex)
+ // Start the lexer
+ go zlexer(s, c)
+ // 6 possible beginnings of a line, _ is a space
+ // 0. zRRTYPE -> all omitted until the rrtype
+ // 1. zOwner _ zRrtype -> class/ttl omitted
+ // 2. zOwner _ zString _ zRrtype -> class omitted
+ // 3. zOwner _ zString _ zClass _ zRrtype -> ttl/class
+ // 4. zOwner _ zClass _ zRrtype -> ttl omitted
+ // 5. zOwner _ zClass _ zString _ zRrtype -> class/ttl (reversed)
+ // After detecting these, we know the zRrtype so we can jump to functions
+ // handling the rdata for each of these types.
+
+ if origin == "" {
+ origin = "."
+ }
+ origin = Fqdn(origin)
+ if _, ok := IsDomainName(origin); !ok {
+ t <- &Token{Error: &ParseError{f, "bad initial origin name", lex{}}}
+ return
+ }
+
+ st := zExpectOwnerDir // initial state
+ var h RR_Header
+ var defttl uint32 = defaultTtl
+ var prevName string
+ for l := range c {
+ // Lexer spotted an error already
+ if l.err == true {
+ t <- &Token{Error: &ParseError{f, l.token, l}}
+ return
+
+ }
+ switch st {
+ case zExpectOwnerDir:
+ // We can also expect a directive, like $TTL or $ORIGIN
+ h.Ttl = defttl
+ h.Class = ClassINET
+ switch l.value {
+ case zNewline:
+ st = zExpectOwnerDir
+ case zOwner:
+ h.Name = l.token
+ if l.token[0] == '@' {
+ h.Name = origin
+ prevName = h.Name
+ st = zExpectOwnerBl
+ break
+ }
+ if h.Name[l.length-1] != '.' {
+ h.Name = appendOrigin(h.Name, origin)
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok {
+ t <- &Token{Error: &ParseError{f, "bad owner name", l}}
+ return
+ }
+ prevName = h.Name
+ st = zExpectOwnerBl
+ case zDirTtl:
+ st = zExpectDirTtlBl
+ case zDirOrigin:
+ st = zExpectDirOriginBl
+ case zDirInclude:
+ st = zExpectDirIncludeBl
+ case zDirGenerate:
+ st = zExpectDirGenerateBl
+ case zRrtpe:
+ h.Name = prevName
+ h.Rrtype = l.torc
+ st = zExpectRdata
+ case zClass:
+ h.Name = prevName
+ h.Class = l.torc
+ st = zExpectAnyNoClassBl
+ case zBlank:
+ // Discard, can happen when there is nothing on the
+ // line except the RR type
+ case zString:
+ ttl, ok := stringToTtl(l.token)
+ if !ok {
+ t <- &Token{Error: &ParseError{f, "not a TTL", l}}
+ return
+ }
+ h.Ttl = ttl
+ // Don't about the defttl, we should take the $TTL value
+ // defttl = ttl
+ st = zExpectAnyNoTtlBl
+
+ default:
+ t <- &Token{Error: &ParseError{f, "syntax error at beginning", l}}
+ return
+ }
+ case zExpectDirIncludeBl:
+ if l.value != zBlank {
+ t <- &Token{Error: &ParseError{f, "no blank after $INCLUDE-directive", l}}
+ return
+ }
+ st = zExpectDirInclude
+ case zExpectDirInclude:
+ if l.value != zString {
+ t <- &Token{Error: &ParseError{f, "expecting $INCLUDE value, not this...", l}}
+ return
+ }
+ neworigin := origin // There may be optionally a new origin set after the filename, if not use current one
+ l := <-c
+ switch l.value {
+ case zBlank:
+ l := <-c
+ if l.value == zString {
+ if _, ok := IsDomainName(l.token); !ok || l.length == 0 || l.err {
+ t <- &Token{Error: &ParseError{f, "bad origin name", l}}
+ return
+ }
+ // a new origin is specified.
+ if l.token[l.length-1] != '.' {
+ if origin != "." { // Prevent .. endings
+ neworigin = l.token + "." + origin
+ } else {
+ neworigin = l.token + origin
+ }
+ } else {
+ neworigin = l.token
+ }
+ }
+ case zNewline, zEOF:
+ // Ok
+ default:
+ t <- &Token{Error: &ParseError{f, "garbage after $INCLUDE", l}}
+ return
+ }
+ // Start with the new file
+ r1, e1 := os.Open(l.token)
+ if e1 != nil {
+ t <- &Token{Error: &ParseError{f, "failed to open `" + l.token + "'", l}}
+ return
+ }
+ if include+1 > 7 {
+ t <- &Token{Error: &ParseError{f, "too deeply nested $INCLUDE", l}}
+ return
+ }
+ parseZone(r1, l.token, neworigin, t, include+1)
+ st = zExpectOwnerDir
+ case zExpectDirTtlBl:
+ if l.value != zBlank {
+ t <- &Token{Error: &ParseError{f, "no blank after $TTL-directive", l}}
+ return
+ }
+ st = zExpectDirTtl
+ case zExpectDirTtl:
+ if l.value != zString {
+ t <- &Token{Error: &ParseError{f, "expecting $TTL value, not this...", l}}
+ return
+ }
+ if e, _ := slurpRemainder(c, f); e != nil {
+ t <- &Token{Error: e}
+ return
+ }
+ ttl, ok := stringToTtl(l.token)
+ if !ok {
+ t <- &Token{Error: &ParseError{f, "expecting $TTL value, not this...", l}}
+ return
+ }
+ defttl = ttl
+ st = zExpectOwnerDir
+ case zExpectDirOriginBl:
+ if l.value != zBlank {
+ t <- &Token{Error: &ParseError{f, "no blank after $ORIGIN-directive", l}}
+ return
+ }
+ st = zExpectDirOrigin
+ case zExpectDirOrigin:
+ if l.value != zString {
+ t <- &Token{Error: &ParseError{f, "expecting $ORIGIN value, not this...", l}}
+ return
+ }
+ if e, _ := slurpRemainder(c, f); e != nil {
+ t <- &Token{Error: e}
+ }
+ if _, ok := IsDomainName(l.token); !ok {
+ t <- &Token{Error: &ParseError{f, "bad origin name", l}}
+ return
+ }
+ if l.token[l.length-1] != '.' {
+ if origin != "." { // Prevent .. endings
+ origin = l.token + "." + origin
+ } else {
+ origin = l.token + origin
+ }
+ } else {
+ origin = l.token
+ }
+ st = zExpectOwnerDir
+ case zExpectDirGenerateBl:
+ if l.value != zBlank {
+ t <- &Token{Error: &ParseError{f, "no blank after $GENERATE-directive", l}}
+ return
+ }
+ st = zExpectDirGenerate
+ case zExpectDirGenerate:
+ if l.value != zString {
+ t <- &Token{Error: &ParseError{f, "expecting $GENERATE value, not this...", l}}
+ return
+ }
+ if e := generate(l, c, t, origin); e != "" {
+ t <- &Token{Error: &ParseError{f, e, l}}
+ return
+ }
+ st = zExpectOwnerDir
+ case zExpectOwnerBl:
+ if l.value != zBlank {
+ t <- &Token{Error: &ParseError{f, "no blank after owner", l}}
+ return
+ }
+ st = zExpectAny
+ case zExpectAny:
+ switch l.value {
+ case zRrtpe:
+ h.Rrtype = l.torc
+ st = zExpectRdata
+ case zClass:
+ h.Class = l.torc
+ st = zExpectAnyNoClassBl
+ case zString:
+ ttl, ok := stringToTtl(l.token)
+ if !ok {
+ t <- &Token{Error: &ParseError{f, "not a TTL", l}}
+ return
+ }
+ h.Ttl = ttl
+ // defttl = ttl // don't set the defttl here
+ st = zExpectAnyNoTtlBl
+ default:
+ t <- &Token{Error: &ParseError{f, "expecting RR type, TTL or class, not this...", l}}
+ return
+ }
+ case zExpectAnyNoClassBl:
+ if l.value != zBlank {
+ t <- &Token{Error: &ParseError{f, "no blank before class", l}}
+ return
+ }
+ st = zExpectAnyNoClass
+ case zExpectAnyNoTtlBl:
+ if l.value != zBlank {
+ t <- &Token{Error: &ParseError{f, "no blank before TTL", l}}
+ return
+ }
+ st = zExpectAnyNoTtl
+ case zExpectAnyNoTtl:
+ switch l.value {
+ case zClass:
+ h.Class = l.torc
+ st = zExpectRrtypeBl
+ case zRrtpe:
+ h.Rrtype = l.torc
+ st = zExpectRdata
+ default:
+ t <- &Token{Error: &ParseError{f, "expecting RR type or class, not this...", l}}
+ return
+ }
+ case zExpectAnyNoClass:
+ switch l.value {
+ case zString:
+ ttl, ok := stringToTtl(l.token)
+ if !ok {
+ t <- &Token{Error: &ParseError{f, "not a TTL", l}}
+ return
+ }
+ h.Ttl = ttl
+ // defttl = ttl // don't set the def ttl anymore
+ st = zExpectRrtypeBl
+ case zRrtpe:
+ h.Rrtype = l.torc
+ st = zExpectRdata
+ default:
+ t <- &Token{Error: &ParseError{f, "expecting RR type or TTL, not this...", l}}
+ return
+ }
+ case zExpectRrtypeBl:
+ if l.value != zBlank {
+ t <- &Token{Error: &ParseError{f, "no blank before RR type", l}}
+ return
+ }
+ st = zExpectRrtype
+ case zExpectRrtype:
+ if l.value != zRrtpe {
+ t <- &Token{Error: &ParseError{f, "unknown RR type", l}}
+ return
+ }
+ h.Rrtype = l.torc
+ st = zExpectRdata
+ case zExpectRdata:
+ r, e, c1 := setRR(h, c, origin, f)
+ if e != nil {
+ // If e.lex is nil than we have encounter a unknown RR type
+ // in that case we substitute our current lex token
+ if e.lex.token == "" && e.lex.value == 0 {
+ e.lex = l // Uh, dirty
+ }
+ t <- &Token{Error: e}
+ return
+ }
+ t <- &Token{RR: r, Comment: c1}
+ st = zExpectOwnerDir
+ }
+ }
+ // If we get here, we and the h.Rrtype is still zero, we haven't parsed anything, this
+ // is not an error, because an empty zone file is still a zone file.
+}
+
+// zlexer scans the sourcefile and returns tokens on the channel c.
+func zlexer(s *scan, c chan lex) {
+ var l lex
+ str := make([]byte, maxTok) // Should be enough for any token
+ stri := 0 // Offset in str (0 means empty)
+ com := make([]byte, maxTok) // Hold comment text
+ comi := 0
+ quote := false
+ escape := false
+ space := false
+ commt := false
+ rrtype := false
+ owner := true
+ brace := 0
+ x, err := s.tokenText()
+ defer close(c)
+ for err == nil {
+ l.column = s.position.Column
+ l.line = s.position.Line
+ if stri >= maxTok {
+ l.token = "token length insufficient for parsing"
+ l.err = true
+ debug.Printf("[%+v]", l.token)
+ c <- l
+ return
+ }
+ if comi >= maxTok {
+ l.token = "comment length insufficient for parsing"
+ l.err = true
+ debug.Printf("[%+v]", l.token)
+ c <- l
+ return
+ }
+
+ switch x {
+ case ' ', '\t':
+ if escape {
+ escape = false
+ str[stri] = x
+ stri++
+ break
+ }
+ if quote {
+ // Inside quotes this is legal
+ str[stri] = x
+ stri++
+ break
+ }
+ if commt {
+ com[comi] = x
+ comi++
+ break
+ }
+ if stri == 0 {
+ // Space directly in the beginning, handled in the grammar
+ } else if owner {
+ // If we have a string and its the first, make it an owner
+ l.value = zOwner
+ l.token = string(str[:stri])
+ l.tokenUpper = strings.ToUpper(l.token)
+ l.length = stri
+ // escape $... start with a \ not a $, so this will work
+ switch l.tokenUpper {
+ case "$TTL":
+ l.value = zDirTtl
+ case "$ORIGIN":
+ l.value = zDirOrigin
+ case "$INCLUDE":
+ l.value = zDirInclude
+ case "$GENERATE":
+ l.value = zDirGenerate
+ }
+ debug.Printf("[7 %+v]", l.token)
+ c <- l
+ } else {
+ l.value = zString
+ l.token = string(str[:stri])
+ l.tokenUpper = strings.ToUpper(l.token)
+ l.length = stri
+ if !rrtype {
+ if t, ok := StringToType[l.tokenUpper]; ok {
+ l.value = zRrtpe
+ l.torc = t
+ rrtype = true
+ } else {
+ if strings.HasPrefix(l.tokenUpper, "TYPE") {
+ t, ok := typeToInt(l.token)
+ if !ok {
+ l.token = "unknown RR type"
+ l.err = true
+ c <- l
+ return
+ }
+ l.value = zRrtpe
+ l.torc = t
+ }
+ }
+ if t, ok := StringToClass[l.tokenUpper]; ok {
+ l.value = zClass
+ l.torc = t
+ } else {
+ if strings.HasPrefix(l.tokenUpper, "CLASS") {
+ t, ok := classToInt(l.token)
+ if !ok {
+ l.token = "unknown class"
+ l.err = true
+ c <- l
+ return
+ }
+ l.value = zClass
+ l.torc = t
+ }
+ }
+ }
+ debug.Printf("[6 %+v]", l.token)
+ c <- l
+ }
+ stri = 0
+ // I reverse space stuff here
+ if !space && !commt {
+ l.value = zBlank
+ l.token = " "
+ l.length = 1
+ debug.Printf("[5 %+v]", l.token)
+ c <- l
+ }
+ owner = false
+ space = true
+ case ';':
+ if escape {
+ escape = false
+ str[stri] = x
+ stri++
+ break
+ }
+ if quote {
+ // Inside quotes this is legal
+ str[stri] = x
+ stri++
+ break
+ }
+ if stri > 0 {
+ l.value = zString
+ l.token = string(str[:stri])
+ l.length = stri
+ debug.Printf("[4 %+v]", l.token)
+ c <- l
+ stri = 0
+ }
+ commt = true
+ com[comi] = ';'
+ comi++
+ case '\r':
+ escape = false
+ if quote {
+ str[stri] = x
+ stri++
+ break
+ }
+ // discard if outside of quotes
+ case '\n':
+ escape = false
+ // Escaped newline
+ if quote {
+ str[stri] = x
+ stri++
+ break
+ }
+ // inside quotes this is legal
+ if commt {
+ // Reset a comment
+ commt = false
+ rrtype = false
+ stri = 0
+ // If not in a brace this ends the comment AND the RR
+ if brace == 0 {
+ owner = true
+ owner = true
+ l.value = zNewline
+ l.token = "\n"
+ l.length = 1
+ l.comment = string(com[:comi])
+ debug.Printf("[3 %+v %+v]", l.token, l.comment)
+ c <- l
+ l.comment = ""
+ comi = 0
+ break
+ }
+ com[comi] = ' ' // convert newline to space
+ comi++
+ break
+ }
+
+ if brace == 0 {
+ // If there is previous text, we should output it here
+ if stri != 0 {
+ l.value = zString
+ l.token = string(str[:stri])
+ l.tokenUpper = strings.ToUpper(l.token)
+
+ l.length = stri
+ if !rrtype {
+ if t, ok := StringToType[l.tokenUpper]; ok {
+ l.value = zRrtpe
+ l.torc = t
+ rrtype = true
+ }
+ }
+ debug.Printf("[2 %+v]", l.token)
+ c <- l
+ }
+ l.value = zNewline
+ l.token = "\n"
+ l.length = 1
+ debug.Printf("[1 %+v]", l.token)
+ c <- l
+ stri = 0
+ commt = false
+ rrtype = false
+ owner = true
+ comi = 0
+ }
+ case '\\':
+ // comments do not get escaped chars, everything is copied
+ if commt {
+ com[comi] = x
+ comi++
+ break
+ }
+ // something already escaped must be in string
+ if escape {
+ str[stri] = x
+ stri++
+ escape = false
+ break
+ }
+ // something escaped outside of string gets added to string
+ str[stri] = x
+ stri++
+ escape = true
+ case '"':
+ if commt {
+ com[comi] = x
+ comi++
+ break
+ }
+ if escape {
+ str[stri] = x
+ stri++
+ escape = false
+ break
+ }
+ space = false
+ // send previous gathered text and the quote
+ if stri != 0 {
+ l.value = zString
+ l.token = string(str[:stri])
+ l.length = stri
+
+ debug.Printf("[%+v]", l.token)
+ c <- l
+ stri = 0
+ }
+
+ // send quote itself as separate token
+ l.value = zQuote
+ l.token = "\""
+ l.length = 1
+ c <- l
+ quote = !quote
+ case '(', ')':
+ if commt {
+ com[comi] = x
+ comi++
+ break
+ }
+ if escape {
+ str[stri] = x
+ stri++
+ escape = false
+ break
+ }
+ if quote {
+ str[stri] = x
+ stri++
+ break
+ }
+ switch x {
+ case ')':
+ brace--
+ if brace < 0 {
+ l.token = "extra closing brace"
+ l.err = true
+ debug.Printf("[%+v]", l.token)
+ c <- l
+ return
+ }
+ case '(':
+ brace++
+ }
+ default:
+ escape = false
+ if commt {
+ com[comi] = x
+ comi++
+ break
+ }
+ str[stri] = x
+ stri++
+ space = false
+ }
+ x, err = s.tokenText()
+ }
+ if stri > 0 {
+ // Send remainder
+ l.token = string(str[:stri])
+ l.length = stri
+ l.value = zString
+ debug.Printf("[%+v]", l.token)
+ c <- l
+ }
+}
+
+// Extract the class number from CLASSxx
+func classToInt(token string) (uint16, bool) {
+ offset := 5
+ if len(token) < offset+1 {
+ return 0, false
+ }
+ class, ok := strconv.Atoi(token[offset:])
+ if ok != nil || class > maxUint16 {
+ return 0, false
+ }
+ return uint16(class), true
+}
+
+// Extract the rr number from TYPExxx
+func typeToInt(token string) (uint16, bool) {
+ offset := 4
+ if len(token) < offset+1 {
+ return 0, false
+ }
+ typ, ok := strconv.Atoi(token[offset:])
+ if ok != nil || typ > maxUint16 {
+ return 0, false
+ }
+ return uint16(typ), true
+}
+
+// Parse things like 2w, 2m, etc, Return the time in seconds.
+func stringToTtl(token string) (uint32, bool) {
+ s := uint32(0)
+ i := uint32(0)
+ for _, c := range token {
+ switch c {
+ case 's', 'S':
+ s += i
+ i = 0
+ case 'm', 'M':
+ s += i * 60
+ i = 0
+ case 'h', 'H':
+ s += i * 60 * 60
+ i = 0
+ case 'd', 'D':
+ s += i * 60 * 60 * 24
+ i = 0
+ case 'w', 'W':
+ s += i * 60 * 60 * 24 * 7
+ i = 0
+ case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
+ i *= 10
+ i += uint32(c) - '0'
+ default:
+ return 0, false
+ }
+ }
+ return s + i, true
+}
+
+// Parse LOC records' <digits>[.<digits>][mM] into a
+// mantissa exponent format. Token should contain the entire
+// string (i.e. no spaces allowed)
+func stringToCm(token string) (e, m uint8, ok bool) {
+ if token[len(token)-1] == 'M' || token[len(token)-1] == 'm' {
+ token = token[0 : len(token)-1]
+ }
+ s := strings.SplitN(token, ".", 2)
+ var meters, cmeters, val int
+ var err error
+ switch len(s) {
+ case 2:
+ if cmeters, err = strconv.Atoi(s[1]); err != nil {
+ return
+ }
+ fallthrough
+ case 1:
+ if meters, err = strconv.Atoi(s[0]); err != nil {
+ return
+ }
+ case 0:
+ // huh?
+ return 0, 0, false
+ }
+ ok = true
+ if meters > 0 {
+ e = 2
+ val = meters
+ } else {
+ e = 0
+ val = cmeters
+ }
+ for val > 10 {
+ e++
+ val /= 10
+ }
+ if e > 9 {
+ ok = false
+ }
+ m = uint8(val)
+ return
+}
+
+func appendOrigin(name, origin string) string {
+ if origin == "." {
+ return name + origin
+ }
+ return name + "." + origin
+}
+
+// LOC record helper function
+func locCheckNorth(token string, latitude uint32) (uint32, bool) {
+ switch token {
+ case "n", "N":
+ return LOC_EQUATOR + latitude, true
+ case "s", "S":
+ return LOC_EQUATOR - latitude, true
+ }
+ return latitude, false
+}
+
+// LOC record helper function
+func locCheckEast(token string, longitude uint32) (uint32, bool) {
+ switch token {
+ case "e", "E":
+ return LOC_EQUATOR + longitude, true
+ case "w", "W":
+ return LOC_EQUATOR - longitude, true
+ }
+ return longitude, false
+}
+
+// "Eat" the rest of the "line". Return potential comments
+func slurpRemainder(c chan lex, f string) (*ParseError, string) {
+ l := <-c
+ com := ""
+ switch l.value {
+ case zBlank:
+ l = <-c
+ com = l.comment
+ if l.value != zNewline && l.value != zEOF {
+ return &ParseError{f, "garbage after rdata", l}, ""
+ }
+ case zNewline:
+ com = l.comment
+ case zEOF:
+ default:
+ return &ParseError{f, "garbage after rdata", l}, ""
+ }
+ return nil, com
+}
+
+// Parse a 64 bit-like ipv6 address: "0014:4fff:ff20:ee64"
+// Used for NID and L64 record.
+func stringToNodeID(l lex) (uint64, *ParseError) {
+ if len(l.token) < 19 {
+ return 0, &ParseError{l.token, "bad NID/L64 NodeID/Locator64", l}
+ }
+ // There must be three colons at fixes postitions, if not its a parse error
+ if l.token[4] != ':' && l.token[9] != ':' && l.token[14] != ':' {
+ return 0, &ParseError{l.token, "bad NID/L64 NodeID/Locator64", l}
+ }
+ s := l.token[0:4] + l.token[5:9] + l.token[10:14] + l.token[15:19]
+ u, e := strconv.ParseUint(s, 16, 64)
+ if e != nil {
+ return 0, &ParseError{l.token, "bad NID/L64 NodeID/Locator64", l}
+ }
+ return u, nil
+}
diff --git a/vendor/github.com/miekg/dns/zscan_rr.go b/vendor/github.com/miekg/dns/zscan_rr.go
new file mode 100644
index 0000000..a2db008
--- /dev/null
+++ b/vendor/github.com/miekg/dns/zscan_rr.go
@@ -0,0 +1,2270 @@
+package dns
+
+import (
+ "encoding/base64"
+ "net"
+ "strconv"
+ "strings"
+)
+
+type parserFunc struct {
+ // Func defines the function that parses the tokens and returns the RR
+ // or an error. The last string contains any comments in the line as
+ // they returned by the lexer as well.
+ Func func(h RR_Header, c chan lex, origin string, file string) (RR, *ParseError, string)
+ // Signals if the RR ending is of variable length, like TXT or records
+ // that have Hexadecimal or Base64 as their last element in the Rdata. Records
+ // that have a fixed ending or for instance A, AAAA, SOA and etc.
+ Variable bool
+}
+
+// Parse the rdata of each rrtype.
+// All data from the channel c is either zString or zBlank.
+// After the rdata there may come a zBlank and then a zNewline
+// or immediately a zNewline. If this is not the case we flag
+// an *ParseError: garbage after rdata.
+func setRR(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ parserfunc, ok := typeToparserFunc[h.Rrtype]
+ if ok {
+ r, e, cm := parserfunc.Func(h, c, o, f)
+ if parserfunc.Variable {
+ return r, e, cm
+ }
+ if e != nil {
+ return nil, e, ""
+ }
+ e, cm = slurpRemainder(c, f)
+ if e != nil {
+ return nil, e, ""
+ }
+ return r, nil, cm
+ }
+ // RFC3957 RR (Unknown RR handling)
+ return setRFC3597(h, c, o, f)
+}
+
+// A remainder of the rdata with embedded spaces, return the parsed string (sans the spaces)
+// or an error
+func endingToString(c chan lex, errstr, f string) (string, *ParseError, string) {
+ s := ""
+ l := <-c // zString
+ for l.value != zNewline && l.value != zEOF {
+ if l.err {
+ return s, &ParseError{f, errstr, l}, ""
+ }
+ switch l.value {
+ case zString:
+ s += l.token
+ case zBlank: // Ok
+ default:
+ return "", &ParseError{f, errstr, l}, ""
+ }
+ l = <-c
+ }
+ return s, nil, l.comment
+}
+
+// A remainder of the rdata with embedded spaces, return the parsed string slice (sans the spaces)
+// or an error
+func endingToTxtSlice(c chan lex, errstr, f string) ([]string, *ParseError, string) {
+ // Get the remaining data until we see a zNewline
+ quote := false
+ l := <-c
+ var s []string
+ if l.err {
+ return s, &ParseError{f, errstr, l}, ""
+ }
+ switch l.value == zQuote {
+ case true: // A number of quoted string
+ s = make([]string, 0)
+ empty := true
+ for l.value != zNewline && l.value != zEOF {
+ if l.err {
+ return nil, &ParseError{f, errstr, l}, ""
+ }
+ switch l.value {
+ case zString:
+ empty = false
+ if len(l.token) > 255 {
+ // split up tokens that are larger than 255 into 255-chunks
+ sx := []string{}
+ p, i := 0, 255
+ for {
+ if i <= len(l.token) {
+ sx = append(sx, l.token[p:i])
+ } else {
+ sx = append(sx, l.token[p:])
+ break
+
+ }
+ p, i = p+255, i+255
+ }
+ s = append(s, sx...)
+ break
+ }
+
+ s = append(s, l.token)
+ case zBlank:
+ if quote {
+ // zBlank can only be seen in between txt parts.
+ return nil, &ParseError{f, errstr, l}, ""
+ }
+ case zQuote:
+ if empty && quote {
+ s = append(s, "")
+ }
+ quote = !quote
+ empty = true
+ default:
+ return nil, &ParseError{f, errstr, l}, ""
+ }
+ l = <-c
+ }
+ if quote {
+ return nil, &ParseError{f, errstr, l}, ""
+ }
+ case false: // Unquoted text record
+ s = make([]string, 1)
+ for l.value != zNewline && l.value != zEOF {
+ if l.err {
+ return s, &ParseError{f, errstr, l}, ""
+ }
+ s[0] += l.token
+ l = <-c
+ }
+ }
+ return s, nil, l.comment
+}
+
+func setA(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(A)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 { // Dynamic updates.
+ return rr, nil, ""
+ }
+ rr.A = net.ParseIP(l.token)
+ if rr.A == nil || l.err {
+ return nil, &ParseError{f, "bad A A", l}, ""
+ }
+ return rr, nil, ""
+}
+
+func setAAAA(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(AAAA)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ rr.AAAA = net.ParseIP(l.token)
+ if rr.AAAA == nil || l.err {
+ return nil, &ParseError{f, "bad AAAA AAAA", l}, ""
+ }
+ return rr, nil, ""
+}
+
+func setNS(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(NS)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Ns = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Ns = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad NS Ns", l}, ""
+ }
+ if rr.Ns[l.length-1] != '.' {
+ rr.Ns = appendOrigin(rr.Ns, o)
+ }
+ return rr, nil, ""
+}
+
+func setPTR(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(PTR)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Ptr = l.token
+ if l.length == 0 { // dynamic update rr.
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Ptr = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad PTR Ptr", l}, ""
+ }
+ if rr.Ptr[l.length-1] != '.' {
+ rr.Ptr = appendOrigin(rr.Ptr, o)
+ }
+ return rr, nil, ""
+}
+
+func setNSAPPTR(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(NSAPPTR)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Ptr = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Ptr = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad NSAP-PTR Ptr", l}, ""
+ }
+ if rr.Ptr[l.length-1] != '.' {
+ rr.Ptr = appendOrigin(rr.Ptr, o)
+ }
+ return rr, nil, ""
+}
+
+func setRP(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(RP)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Mbox = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Mbox = o
+ } else {
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad RP Mbox", l}, ""
+ }
+ if rr.Mbox[l.length-1] != '.' {
+ rr.Mbox = appendOrigin(rr.Mbox, o)
+ }
+ }
+ <-c // zBlank
+ l = <-c
+ rr.Txt = l.token
+ if l.token == "@" {
+ rr.Txt = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad RP Txt", l}, ""
+ }
+ if rr.Txt[l.length-1] != '.' {
+ rr.Txt = appendOrigin(rr.Txt, o)
+ }
+ return rr, nil, ""
+}
+
+func setMR(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(MR)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Mr = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Mr = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad MR Mr", l}, ""
+ }
+ if rr.Mr[l.length-1] != '.' {
+ rr.Mr = appendOrigin(rr.Mr, o)
+ }
+ return rr, nil, ""
+}
+
+func setMB(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(MB)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Mb = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Mb = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad MB Mb", l}, ""
+ }
+ if rr.Mb[l.length-1] != '.' {
+ rr.Mb = appendOrigin(rr.Mb, o)
+ }
+ return rr, nil, ""
+}
+
+func setMG(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(MG)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Mg = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Mg = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad MG Mg", l}, ""
+ }
+ if rr.Mg[l.length-1] != '.' {
+ rr.Mg = appendOrigin(rr.Mg, o)
+ }
+ return rr, nil, ""
+}
+
+func setHINFO(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(HINFO)
+ rr.Hdr = h
+
+ chunks, e, c1 := endingToTxtSlice(c, "bad HINFO Fields", f)
+ if e != nil {
+ return nil, e, c1
+ }
+
+ if ln := len(chunks); ln == 0 {
+ return rr, nil, ""
+ } else if ln == 1 {
+ // Can we split it?
+ if out := strings.Fields(chunks[0]); len(out) > 1 {
+ chunks = out
+ } else {
+ chunks = append(chunks, "")
+ }
+ }
+
+ rr.Cpu = chunks[0]
+ rr.Os = strings.Join(chunks[1:], " ")
+
+ return rr, nil, ""
+}
+
+func setMINFO(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(MINFO)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Rmail = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Rmail = o
+ } else {
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad MINFO Rmail", l}, ""
+ }
+ if rr.Rmail[l.length-1] != '.' {
+ rr.Rmail = appendOrigin(rr.Rmail, o)
+ }
+ }
+ <-c // zBlank
+ l = <-c
+ rr.Email = l.token
+ if l.token == "@" {
+ rr.Email = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad MINFO Email", l}, ""
+ }
+ if rr.Email[l.length-1] != '.' {
+ rr.Email = appendOrigin(rr.Email, o)
+ }
+ return rr, nil, ""
+}
+
+func setMF(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(MF)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Mf = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Mf = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad MF Mf", l}, ""
+ }
+ if rr.Mf[l.length-1] != '.' {
+ rr.Mf = appendOrigin(rr.Mf, o)
+ }
+ return rr, nil, ""
+}
+
+func setMD(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(MD)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Md = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Md = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad MD Md", l}, ""
+ }
+ if rr.Md[l.length-1] != '.' {
+ rr.Md = appendOrigin(rr.Md, o)
+ }
+ return rr, nil, ""
+}
+
+func setMX(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(MX)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad MX Pref", l}, ""
+ }
+ rr.Preference = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ rr.Mx = l.token
+ if l.token == "@" {
+ rr.Mx = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad MX Mx", l}, ""
+ }
+ if rr.Mx[l.length-1] != '.' {
+ rr.Mx = appendOrigin(rr.Mx, o)
+ }
+ return rr, nil, ""
+}
+
+func setRT(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(RT)
+ rr.Hdr = h
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil {
+ return nil, &ParseError{f, "bad RT Preference", l}, ""
+ }
+ rr.Preference = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ rr.Host = l.token
+ if l.token == "@" {
+ rr.Host = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad RT Host", l}, ""
+ }
+ if rr.Host[l.length-1] != '.' {
+ rr.Host = appendOrigin(rr.Host, o)
+ }
+ return rr, nil, ""
+}
+
+func setAFSDB(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(AFSDB)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad AFSDB Subtype", l}, ""
+ }
+ rr.Subtype = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ rr.Hostname = l.token
+ if l.token == "@" {
+ rr.Hostname = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad AFSDB Hostname", l}, ""
+ }
+ if rr.Hostname[l.length-1] != '.' {
+ rr.Hostname = appendOrigin(rr.Hostname, o)
+ }
+ return rr, nil, ""
+}
+
+func setX25(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(X25)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.err {
+ return nil, &ParseError{f, "bad X25 PSDNAddress", l}, ""
+ }
+ rr.PSDNAddress = l.token
+ return rr, nil, ""
+}
+
+func setKX(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(KX)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad KX Pref", l}, ""
+ }
+ rr.Preference = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ rr.Exchanger = l.token
+ if l.token == "@" {
+ rr.Exchanger = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad KX Exchanger", l}, ""
+ }
+ if rr.Exchanger[l.length-1] != '.' {
+ rr.Exchanger = appendOrigin(rr.Exchanger, o)
+ }
+ return rr, nil, ""
+}
+
+func setCNAME(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(CNAME)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Target = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Target = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad CNAME Target", l}, ""
+ }
+ if rr.Target[l.length-1] != '.' {
+ rr.Target = appendOrigin(rr.Target, o)
+ }
+ return rr, nil, ""
+}
+
+func setDNAME(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(DNAME)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Target = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Target = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad CNAME Target", l}, ""
+ }
+ if rr.Target[l.length-1] != '.' {
+ rr.Target = appendOrigin(rr.Target, o)
+ }
+ return rr, nil, ""
+}
+
+func setSOA(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(SOA)
+ rr.Hdr = h
+
+ l := <-c
+ rr.Ns = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ <-c // zBlank
+ if l.token == "@" {
+ rr.Ns = o
+ } else {
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad SOA Ns", l}, ""
+ }
+ if rr.Ns[l.length-1] != '.' {
+ rr.Ns = appendOrigin(rr.Ns, o)
+ }
+ }
+
+ l = <-c
+ rr.Mbox = l.token
+ if l.token == "@" {
+ rr.Mbox = o
+ } else {
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad SOA Mbox", l}, ""
+ }
+ if rr.Mbox[l.length-1] != '.' {
+ rr.Mbox = appendOrigin(rr.Mbox, o)
+ }
+ }
+ <-c // zBlank
+
+ var (
+ v uint32
+ ok bool
+ )
+ for i := 0; i < 5; i++ {
+ l = <-c
+ if l.err {
+ return nil, &ParseError{f, "bad SOA zone parameter", l}, ""
+ }
+ if j, e := strconv.Atoi(l.token); e != nil {
+ if i == 0 {
+ // Serial should be a number
+ return nil, &ParseError{f, "bad SOA zone parameter", l}, ""
+ }
+ if v, ok = stringToTtl(l.token); !ok {
+ return nil, &ParseError{f, "bad SOA zone parameter", l}, ""
+
+ }
+ } else {
+ v = uint32(j)
+ }
+ switch i {
+ case 0:
+ rr.Serial = v
+ <-c // zBlank
+ case 1:
+ rr.Refresh = v
+ <-c // zBlank
+ case 2:
+ rr.Retry = v
+ <-c // zBlank
+ case 3:
+ rr.Expire = v
+ <-c // zBlank
+ case 4:
+ rr.Minttl = v
+ }
+ }
+ return rr, nil, ""
+}
+
+func setSRV(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(SRV)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad SRV Priority", l}, ""
+ }
+ rr.Priority = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad SRV Weight", l}, ""
+ }
+ rr.Weight = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad SRV Port", l}, ""
+ }
+ rr.Port = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ rr.Target = l.token
+ if l.token == "@" {
+ rr.Target = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad SRV Target", l}, ""
+ }
+ if rr.Target[l.length-1] != '.' {
+ rr.Target = appendOrigin(rr.Target, o)
+ }
+ return rr, nil, ""
+}
+
+func setNAPTR(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(NAPTR)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad NAPTR Order", l}, ""
+ }
+ rr.Order = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad NAPTR Preference", l}, ""
+ }
+ rr.Preference = uint16(i)
+ // Flags
+ <-c // zBlank
+ l = <-c // _QUOTE
+ if l.value != zQuote {
+ return nil, &ParseError{f, "bad NAPTR Flags", l}, ""
+ }
+ l = <-c // Either String or Quote
+ if l.value == zString {
+ rr.Flags = l.token
+ l = <-c // _QUOTE
+ if l.value != zQuote {
+ return nil, &ParseError{f, "bad NAPTR Flags", l}, ""
+ }
+ } else if l.value == zQuote {
+ rr.Flags = ""
+ } else {
+ return nil, &ParseError{f, "bad NAPTR Flags", l}, ""
+ }
+
+ // Service
+ <-c // zBlank
+ l = <-c // _QUOTE
+ if l.value != zQuote {
+ return nil, &ParseError{f, "bad NAPTR Service", l}, ""
+ }
+ l = <-c // Either String or Quote
+ if l.value == zString {
+ rr.Service = l.token
+ l = <-c // _QUOTE
+ if l.value != zQuote {
+ return nil, &ParseError{f, "bad NAPTR Service", l}, ""
+ }
+ } else if l.value == zQuote {
+ rr.Service = ""
+ } else {
+ return nil, &ParseError{f, "bad NAPTR Service", l}, ""
+ }
+
+ // Regexp
+ <-c // zBlank
+ l = <-c // _QUOTE
+ if l.value != zQuote {
+ return nil, &ParseError{f, "bad NAPTR Regexp", l}, ""
+ }
+ l = <-c // Either String or Quote
+ if l.value == zString {
+ rr.Regexp = l.token
+ l = <-c // _QUOTE
+ if l.value != zQuote {
+ return nil, &ParseError{f, "bad NAPTR Regexp", l}, ""
+ }
+ } else if l.value == zQuote {
+ rr.Regexp = ""
+ } else {
+ return nil, &ParseError{f, "bad NAPTR Regexp", l}, ""
+ }
+ // After quote no space??
+ <-c // zBlank
+ l = <-c // zString
+ rr.Replacement = l.token
+ if l.token == "@" {
+ rr.Replacement = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad NAPTR Replacement", l}, ""
+ }
+ if rr.Replacement[l.length-1] != '.' {
+ rr.Replacement = appendOrigin(rr.Replacement, o)
+ }
+ return rr, nil, ""
+}
+
+func setTALINK(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(TALINK)
+ rr.Hdr = h
+
+ l := <-c
+ rr.PreviousName = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.PreviousName = o
+ } else {
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad TALINK PreviousName", l}, ""
+ }
+ if rr.PreviousName[l.length-1] != '.' {
+ rr.PreviousName = appendOrigin(rr.PreviousName, o)
+ }
+ }
+ <-c // zBlank
+ l = <-c
+ rr.NextName = l.token
+ if l.token == "@" {
+ rr.NextName = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad TALINK NextName", l}, ""
+ }
+ if rr.NextName[l.length-1] != '.' {
+ rr.NextName = appendOrigin(rr.NextName, o)
+ }
+ return rr, nil, ""
+}
+
+func setLOC(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(LOC)
+ rr.Hdr = h
+ // Non zero defaults for LOC record, see RFC 1876, Section 3.
+ rr.HorizPre = 165 // 10000
+ rr.VertPre = 162 // 10
+ rr.Size = 18 // 1
+ ok := false
+ // North
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad LOC Latitude", l}, ""
+ }
+ rr.Latitude = 1000 * 60 * 60 * uint32(i)
+
+ <-c // zBlank
+ // Either number, 'N' or 'S'
+ l = <-c
+ if rr.Latitude, ok = locCheckNorth(l.token, rr.Latitude); ok {
+ goto East
+ }
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad LOC Latitude minutes", l}, ""
+ }
+ rr.Latitude += 1000 * 60 * uint32(i)
+
+ <-c // zBlank
+ l = <-c
+ if i, e := strconv.ParseFloat(l.token, 32); e != nil || l.err {
+ return nil, &ParseError{f, "bad LOC Latitude seconds", l}, ""
+ } else {
+ rr.Latitude += uint32(1000 * i)
+ }
+ <-c // zBlank
+ // Either number, 'N' or 'S'
+ l = <-c
+ if rr.Latitude, ok = locCheckNorth(l.token, rr.Latitude); ok {
+ goto East
+ }
+ // If still alive, flag an error
+ return nil, &ParseError{f, "bad LOC Latitude North/South", l}, ""
+
+East:
+ // East
+ <-c // zBlank
+ l = <-c
+ if i, e := strconv.Atoi(l.token); e != nil || l.err {
+ return nil, &ParseError{f, "bad LOC Longitude", l}, ""
+ } else {
+ rr.Longitude = 1000 * 60 * 60 * uint32(i)
+ }
+ <-c // zBlank
+ // Either number, 'E' or 'W'
+ l = <-c
+ if rr.Longitude, ok = locCheckEast(l.token, rr.Longitude); ok {
+ goto Altitude
+ }
+ if i, e := strconv.Atoi(l.token); e != nil || l.err {
+ return nil, &ParseError{f, "bad LOC Longitude minutes", l}, ""
+ } else {
+ rr.Longitude += 1000 * 60 * uint32(i)
+ }
+ <-c // zBlank
+ l = <-c
+ if i, e := strconv.ParseFloat(l.token, 32); e != nil || l.err {
+ return nil, &ParseError{f, "bad LOC Longitude seconds", l}, ""
+ } else {
+ rr.Longitude += uint32(1000 * i)
+ }
+ <-c // zBlank
+ // Either number, 'E' or 'W'
+ l = <-c
+ if rr.Longitude, ok = locCheckEast(l.token, rr.Longitude); ok {
+ goto Altitude
+ }
+ // If still alive, flag an error
+ return nil, &ParseError{f, "bad LOC Longitude East/West", l}, ""
+
+Altitude:
+ <-c // zBlank
+ l = <-c
+ if l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad LOC Altitude", l}, ""
+ }
+ if l.token[len(l.token)-1] == 'M' || l.token[len(l.token)-1] == 'm' {
+ l.token = l.token[0 : len(l.token)-1]
+ }
+ if i, e := strconv.ParseFloat(l.token, 32); e != nil {
+ return nil, &ParseError{f, "bad LOC Altitude", l}, ""
+ } else {
+ rr.Altitude = uint32(i*100.0 + 10000000.0 + 0.5)
+ }
+
+ // And now optionally the other values
+ l = <-c
+ count := 0
+ for l.value != zNewline && l.value != zEOF {
+ switch l.value {
+ case zString:
+ switch count {
+ case 0: // Size
+ e, m, ok := stringToCm(l.token)
+ if !ok {
+ return nil, &ParseError{f, "bad LOC Size", l}, ""
+ }
+ rr.Size = (e & 0x0f) | (m << 4 & 0xf0)
+ case 1: // HorizPre
+ e, m, ok := stringToCm(l.token)
+ if !ok {
+ return nil, &ParseError{f, "bad LOC HorizPre", l}, ""
+ }
+ rr.HorizPre = (e & 0x0f) | (m << 4 & 0xf0)
+ case 2: // VertPre
+ e, m, ok := stringToCm(l.token)
+ if !ok {
+ return nil, &ParseError{f, "bad LOC VertPre", l}, ""
+ }
+ rr.VertPre = (e & 0x0f) | (m << 4 & 0xf0)
+ }
+ count++
+ case zBlank:
+ // Ok
+ default:
+ return nil, &ParseError{f, "bad LOC Size, HorizPre or VertPre", l}, ""
+ }
+ l = <-c
+ }
+ return rr, nil, ""
+}
+
+func setHIP(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(HIP)
+ rr.Hdr = h
+
+ // HitLength is not represented
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad HIP PublicKeyAlgorithm", l}, ""
+ }
+ rr.PublicKeyAlgorithm = uint8(i)
+ <-c // zBlank
+ l = <-c // zString
+ if l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad HIP Hit", l}, ""
+ }
+ rr.Hit = l.token // This can not contain spaces, see RFC 5205 Section 6.
+ rr.HitLength = uint8(len(rr.Hit)) / 2
+
+ <-c // zBlank
+ l = <-c // zString
+ if l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad HIP PublicKey", l}, ""
+ }
+ rr.PublicKey = l.token // This cannot contain spaces
+ rr.PublicKeyLength = uint16(base64.StdEncoding.DecodedLen(len(rr.PublicKey)))
+
+ // RendezvousServers (if any)
+ l = <-c
+ var xs []string
+ for l.value != zNewline && l.value != zEOF {
+ switch l.value {
+ case zString:
+ if l.token == "@" {
+ xs = append(xs, o)
+ l = <-c
+ continue
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad HIP RendezvousServers", l}, ""
+ }
+ if l.token[l.length-1] != '.' {
+ l.token = appendOrigin(l.token, o)
+ }
+ xs = append(xs, l.token)
+ case zBlank:
+ // Ok
+ default:
+ return nil, &ParseError{f, "bad HIP RendezvousServers", l}, ""
+ }
+ l = <-c
+ }
+ rr.RendezvousServers = xs
+ return rr, nil, l.comment
+}
+
+func setCERT(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(CERT)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ if v, ok := StringToCertType[l.token]; ok {
+ rr.Type = v
+ } else if i, e := strconv.Atoi(l.token); e != nil {
+ return nil, &ParseError{f, "bad CERT Type", l}, ""
+ } else {
+ rr.Type = uint16(i)
+ }
+ <-c // zBlank
+ l = <-c // zString
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad CERT KeyTag", l}, ""
+ }
+ rr.KeyTag = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ if v, ok := StringToAlgorithm[l.token]; ok {
+ rr.Algorithm = v
+ } else if i, e := strconv.Atoi(l.token); e != nil {
+ return nil, &ParseError{f, "bad CERT Algorithm", l}, ""
+ } else {
+ rr.Algorithm = uint8(i)
+ }
+ s, e1, c1 := endingToString(c, "bad CERT Certificate", f)
+ if e1 != nil {
+ return nil, e1, c1
+ }
+ rr.Certificate = s
+ return rr, nil, c1
+}
+
+func setOPENPGPKEY(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(OPENPGPKEY)
+ rr.Hdr = h
+
+ s, e, c1 := endingToString(c, "bad OPENPGPKEY PublicKey", f)
+ if e != nil {
+ return nil, e, c1
+ }
+ rr.PublicKey = s
+ return rr, nil, c1
+}
+
+func setSIG(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ r, e, s := setRRSIG(h, c, o, f)
+ if r != nil {
+ return &SIG{*r.(*RRSIG)}, e, s
+ }
+ return nil, e, s
+}
+
+func setRRSIG(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(RRSIG)
+ rr.Hdr = h
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ if t, ok := StringToType[l.tokenUpper]; !ok {
+ if strings.HasPrefix(l.tokenUpper, "TYPE") {
+ t, ok = typeToInt(l.tokenUpper)
+ if !ok {
+ return nil, &ParseError{f, "bad RRSIG Typecovered", l}, ""
+ }
+ rr.TypeCovered = t
+ } else {
+ return nil, &ParseError{f, "bad RRSIG Typecovered", l}, ""
+ }
+ } else {
+ rr.TypeCovered = t
+ }
+ <-c // zBlank
+ l = <-c
+ i, err := strconv.Atoi(l.token)
+ if err != nil || l.err {
+ return nil, &ParseError{f, "bad RRSIG Algorithm", l}, ""
+ }
+ rr.Algorithm = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, err = strconv.Atoi(l.token)
+ if err != nil || l.err {
+ return nil, &ParseError{f, "bad RRSIG Labels", l}, ""
+ }
+ rr.Labels = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, err = strconv.Atoi(l.token)
+ if err != nil || l.err {
+ return nil, &ParseError{f, "bad RRSIG OrigTtl", l}, ""
+ }
+ rr.OrigTtl = uint32(i)
+ <-c // zBlank
+ l = <-c
+ if i, err := StringToTime(l.token); err != nil {
+ // Try to see if all numeric and use it as epoch
+ if i, err := strconv.ParseInt(l.token, 10, 64); err == nil {
+ // TODO(miek): error out on > MAX_UINT32, same below
+ rr.Expiration = uint32(i)
+ } else {
+ return nil, &ParseError{f, "bad RRSIG Expiration", l}, ""
+ }
+ } else {
+ rr.Expiration = i
+ }
+ <-c // zBlank
+ l = <-c
+ if i, err := StringToTime(l.token); err != nil {
+ if i, err := strconv.ParseInt(l.token, 10, 64); err == nil {
+ rr.Inception = uint32(i)
+ } else {
+ return nil, &ParseError{f, "bad RRSIG Inception", l}, ""
+ }
+ } else {
+ rr.Inception = i
+ }
+ <-c // zBlank
+ l = <-c
+ i, err = strconv.Atoi(l.token)
+ if err != nil || l.err {
+ return nil, &ParseError{f, "bad RRSIG KeyTag", l}, ""
+ }
+ rr.KeyTag = uint16(i)
+ <-c // zBlank
+ l = <-c
+ rr.SignerName = l.token
+ if l.token == "@" {
+ rr.SignerName = o
+ } else {
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad RRSIG SignerName", l}, ""
+ }
+ if rr.SignerName[l.length-1] != '.' {
+ rr.SignerName = appendOrigin(rr.SignerName, o)
+ }
+ }
+ s, e, c1 := endingToString(c, "bad RRSIG Signature", f)
+ if e != nil {
+ return nil, e, c1
+ }
+ rr.Signature = s
+ return rr, nil, c1
+}
+
+func setNSEC(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(NSEC)
+ rr.Hdr = h
+
+ l := <-c
+ rr.NextDomain = l.token
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ if l.token == "@" {
+ rr.NextDomain = o
+ } else {
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad NSEC NextDomain", l}, ""
+ }
+ if rr.NextDomain[l.length-1] != '.' {
+ rr.NextDomain = appendOrigin(rr.NextDomain, o)
+ }
+ }
+
+ rr.TypeBitMap = make([]uint16, 0)
+ var (
+ k uint16
+ ok bool
+ )
+ l = <-c
+ for l.value != zNewline && l.value != zEOF {
+ switch l.value {
+ case zBlank:
+ // Ok
+ case zString:
+ if k, ok = StringToType[l.tokenUpper]; !ok {
+ if k, ok = typeToInt(l.tokenUpper); !ok {
+ return nil, &ParseError{f, "bad NSEC TypeBitMap", l}, ""
+ }
+ }
+ rr.TypeBitMap = append(rr.TypeBitMap, k)
+ default:
+ return nil, &ParseError{f, "bad NSEC TypeBitMap", l}, ""
+ }
+ l = <-c
+ }
+ return rr, nil, l.comment
+}
+
+func setNSEC3(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(NSEC3)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad NSEC3 Hash", l}, ""
+ }
+ rr.Hash = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad NSEC3 Flags", l}, ""
+ }
+ rr.Flags = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad NSEC3 Iterations", l}, ""
+ }
+ rr.Iterations = uint16(i)
+ <-c
+ l = <-c
+ if len(l.token) == 0 || l.err {
+ return nil, &ParseError{f, "bad NSEC3 Salt", l}, ""
+ }
+ rr.SaltLength = uint8(len(l.token)) / 2
+ rr.Salt = l.token
+
+ <-c
+ l = <-c
+ if len(l.token) == 0 || l.err {
+ return nil, &ParseError{f, "bad NSEC3 NextDomain", l}, ""
+ }
+ rr.HashLength = 20 // Fix for NSEC3 (sha1 160 bits)
+ rr.NextDomain = l.token
+
+ rr.TypeBitMap = make([]uint16, 0)
+ var (
+ k uint16
+ ok bool
+ )
+ l = <-c
+ for l.value != zNewline && l.value != zEOF {
+ switch l.value {
+ case zBlank:
+ // Ok
+ case zString:
+ if k, ok = StringToType[l.tokenUpper]; !ok {
+ if k, ok = typeToInt(l.tokenUpper); !ok {
+ return nil, &ParseError{f, "bad NSEC3 TypeBitMap", l}, ""
+ }
+ }
+ rr.TypeBitMap = append(rr.TypeBitMap, k)
+ default:
+ return nil, &ParseError{f, "bad NSEC3 TypeBitMap", l}, ""
+ }
+ l = <-c
+ }
+ return rr, nil, l.comment
+}
+
+func setNSEC3PARAM(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(NSEC3PARAM)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad NSEC3PARAM Hash", l}, ""
+ }
+ rr.Hash = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad NSEC3PARAM Flags", l}, ""
+ }
+ rr.Flags = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad NSEC3PARAM Iterations", l}, ""
+ }
+ rr.Iterations = uint16(i)
+ <-c
+ l = <-c
+ rr.SaltLength = uint8(len(l.token))
+ rr.Salt = l.token
+ return rr, nil, ""
+}
+
+func setEUI48(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(EUI48)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.length != 17 || l.err {
+ return nil, &ParseError{f, "bad EUI48 Address", l}, ""
+ }
+ addr := make([]byte, 12)
+ dash := 0
+ for i := 0; i < 10; i += 2 {
+ addr[i] = l.token[i+dash]
+ addr[i+1] = l.token[i+1+dash]
+ dash++
+ if l.token[i+1+dash] != '-' {
+ return nil, &ParseError{f, "bad EUI48 Address", l}, ""
+ }
+ }
+ addr[10] = l.token[15]
+ addr[11] = l.token[16]
+
+ i, e := strconv.ParseUint(string(addr), 16, 48)
+ if e != nil {
+ return nil, &ParseError{f, "bad EUI48 Address", l}, ""
+ }
+ rr.Address = i
+ return rr, nil, ""
+}
+
+func setEUI64(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(EUI64)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.length != 23 || l.err {
+ return nil, &ParseError{f, "bad EUI64 Address", l}, ""
+ }
+ addr := make([]byte, 16)
+ dash := 0
+ for i := 0; i < 14; i += 2 {
+ addr[i] = l.token[i+dash]
+ addr[i+1] = l.token[i+1+dash]
+ dash++
+ if l.token[i+1+dash] != '-' {
+ return nil, &ParseError{f, "bad EUI64 Address", l}, ""
+ }
+ }
+ addr[14] = l.token[21]
+ addr[15] = l.token[22]
+
+ i, e := strconv.ParseUint(string(addr), 16, 64)
+ if e != nil {
+ return nil, &ParseError{f, "bad EUI68 Address", l}, ""
+ }
+ rr.Address = uint64(i)
+ return rr, nil, ""
+}
+
+func setWKS(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(WKS)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ rr.Address = net.ParseIP(l.token)
+ if rr.Address == nil || l.err {
+ return nil, &ParseError{f, "bad WKS Address", l}, ""
+ }
+
+ <-c // zBlank
+ l = <-c
+ proto := "tcp"
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad WKS Protocol", l}, ""
+ }
+ rr.Protocol = uint8(i)
+ switch rr.Protocol {
+ case 17:
+ proto = "udp"
+ case 6:
+ proto = "tcp"
+ default:
+ return nil, &ParseError{f, "bad WKS Protocol", l}, ""
+ }
+
+ <-c
+ l = <-c
+ rr.BitMap = make([]uint16, 0)
+ var (
+ k int
+ err error
+ )
+ for l.value != zNewline && l.value != zEOF {
+ switch l.value {
+ case zBlank:
+ // Ok
+ case zString:
+ if k, err = net.LookupPort(proto, l.token); err != nil {
+ i, e := strconv.Atoi(l.token) // If a number use that
+ if e != nil {
+ return nil, &ParseError{f, "bad WKS BitMap", l}, ""
+ }
+ rr.BitMap = append(rr.BitMap, uint16(i))
+ }
+ rr.BitMap = append(rr.BitMap, uint16(k))
+ default:
+ return nil, &ParseError{f, "bad WKS BitMap", l}, ""
+ }
+ l = <-c
+ }
+ return rr, nil, l.comment
+}
+
+func setSSHFP(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(SSHFP)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad SSHFP Algorithm", l}, ""
+ }
+ rr.Algorithm = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad SSHFP Type", l}, ""
+ }
+ rr.Type = uint8(i)
+ <-c // zBlank
+ s, e1, c1 := endingToString(c, "bad SSHFP Fingerprint", f)
+ if e1 != nil {
+ return nil, e1, c1
+ }
+ rr.FingerPrint = s
+ return rr, nil, ""
+}
+
+func setDNSKEYs(h RR_Header, c chan lex, o, f, typ string) (RR, *ParseError, string) {
+ rr := new(DNSKEY)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad " + typ + " Flags", l}, ""
+ }
+ rr.Flags = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad " + typ + " Protocol", l}, ""
+ }
+ rr.Protocol = uint8(i)
+ <-c // zBlank
+ l = <-c // zString
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad " + typ + " Algorithm", l}, ""
+ }
+ rr.Algorithm = uint8(i)
+ s, e1, c1 := endingToString(c, "bad "+typ+" PublicKey", f)
+ if e1 != nil {
+ return nil, e1, c1
+ }
+ rr.PublicKey = s
+ return rr, nil, c1
+}
+
+func setKEY(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ r, e, s := setDNSKEYs(h, c, o, f, "KEY")
+ if r != nil {
+ return &KEY{*r.(*DNSKEY)}, e, s
+ }
+ return nil, e, s
+}
+
+func setDNSKEY(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ r, e, s := setDNSKEYs(h, c, o, f, "DNSKEY")
+ return r, e, s
+}
+
+func setCDNSKEY(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ r, e, s := setDNSKEYs(h, c, o, f, "CDNSKEY")
+ if r != nil {
+ return &CDNSKEY{*r.(*DNSKEY)}, e, s
+ }
+ return nil, e, s
+}
+
+func setRKEY(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(RKEY)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad RKEY Flags", l}, ""
+ }
+ rr.Flags = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad RKEY Protocol", l}, ""
+ }
+ rr.Protocol = uint8(i)
+ <-c // zBlank
+ l = <-c // zString
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad RKEY Algorithm", l}, ""
+ }
+ rr.Algorithm = uint8(i)
+ s, e1, c1 := endingToString(c, "bad RKEY PublicKey", f)
+ if e1 != nil {
+ return nil, e1, c1
+ }
+ rr.PublicKey = s
+ return rr, nil, c1
+}
+
+func setEID(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(EID)
+ rr.Hdr = h
+ s, e, c1 := endingToString(c, "bad EID Endpoint", f)
+ if e != nil {
+ return nil, e, c1
+ }
+ rr.Endpoint = s
+ return rr, nil, c1
+}
+
+func setNIMLOC(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(NIMLOC)
+ rr.Hdr = h
+ s, e, c1 := endingToString(c, "bad NIMLOC Locator", f)
+ if e != nil {
+ return nil, e, c1
+ }
+ rr.Locator = s
+ return rr, nil, c1
+}
+
+func setGPOS(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(GPOS)
+ rr.Hdr = h
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ _, e := strconv.ParseFloat(l.token, 64)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad GPOS Longitude", l}, ""
+ }
+ rr.Longitude = l.token
+ <-c // zBlank
+ l = <-c
+ _, e = strconv.ParseFloat(l.token, 64)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad GPOS Latitude", l}, ""
+ }
+ rr.Latitude = l.token
+ <-c // zBlank
+ l = <-c
+ _, e = strconv.ParseFloat(l.token, 64)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad GPOS Altitude", l}, ""
+ }
+ rr.Altitude = l.token
+ return rr, nil, ""
+}
+
+func setDSs(h RR_Header, c chan lex, o, f, typ string) (RR, *ParseError, string) {
+ rr := new(DS)
+ rr.Hdr = h
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad " + typ + " KeyTag", l}, ""
+ }
+ rr.KeyTag = uint16(i)
+ <-c // zBlank
+ l = <-c
+ if i, e := strconv.Atoi(l.token); e != nil {
+ i, ok := StringToAlgorithm[l.tokenUpper]
+ if !ok || l.err {
+ return nil, &ParseError{f, "bad " + typ + " Algorithm", l}, ""
+ }
+ rr.Algorithm = i
+ } else {
+ rr.Algorithm = uint8(i)
+ }
+ <-c // zBlank
+ l = <-c
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad " + typ + " DigestType", l}, ""
+ }
+ rr.DigestType = uint8(i)
+ s, e1, c1 := endingToString(c, "bad "+typ+" Digest", f)
+ if e1 != nil {
+ return nil, e1, c1
+ }
+ rr.Digest = s
+ return rr, nil, c1
+}
+
+func setDS(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ r, e, s := setDSs(h, c, o, f, "DS")
+ return r, e, s
+}
+
+func setDLV(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ r, e, s := setDSs(h, c, o, f, "DLV")
+ if r != nil {
+ return &DLV{*r.(*DS)}, e, s
+ }
+ return nil, e, s
+}
+
+func setCDS(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ r, e, s := setDSs(h, c, o, f, "CDS")
+ if r != nil {
+ return &CDS{*r.(*DS)}, e, s
+ }
+ return nil, e, s
+}
+
+func setTA(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(TA)
+ rr.Hdr = h
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad TA KeyTag", l}, ""
+ }
+ rr.KeyTag = uint16(i)
+ <-c // zBlank
+ l = <-c
+ if i, e := strconv.Atoi(l.token); e != nil {
+ i, ok := StringToAlgorithm[l.tokenUpper]
+ if !ok || l.err {
+ return nil, &ParseError{f, "bad TA Algorithm", l}, ""
+ }
+ rr.Algorithm = i
+ } else {
+ rr.Algorithm = uint8(i)
+ }
+ <-c // zBlank
+ l = <-c
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad TA DigestType", l}, ""
+ }
+ rr.DigestType = uint8(i)
+ s, e, c1 := endingToString(c, "bad TA Digest", f)
+ if e != nil {
+ return nil, e.(*ParseError), c1
+ }
+ rr.Digest = s
+ return rr, nil, c1
+}
+
+func setTLSA(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(TLSA)
+ rr.Hdr = h
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad TLSA Usage", l}, ""
+ }
+ rr.Usage = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad TLSA Selector", l}, ""
+ }
+ rr.Selector = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad TLSA MatchingType", l}, ""
+ }
+ rr.MatchingType = uint8(i)
+ // So this needs be e2 (i.e. different than e), because...??t
+ s, e2, c1 := endingToString(c, "bad TLSA Certificate", f)
+ if e2 != nil {
+ return nil, e2, c1
+ }
+ rr.Certificate = s
+ return rr, nil, c1
+}
+
+func setRFC3597(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(RFC3597)
+ rr.Hdr = h
+ l := <-c
+ if l.token != "\\#" {
+ return nil, &ParseError{f, "bad RFC3597 Rdata", l}, ""
+ }
+ <-c // zBlank
+ l = <-c
+ rdlength, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad RFC3597 Rdata ", l}, ""
+ }
+
+ s, e1, c1 := endingToString(c, "bad RFC3597 Rdata", f)
+ if e1 != nil {
+ return nil, e1, c1
+ }
+ if rdlength*2 != len(s) {
+ return nil, &ParseError{f, "bad RFC3597 Rdata", l}, ""
+ }
+ rr.Rdata = s
+ return rr, nil, c1
+}
+
+func setSPF(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(SPF)
+ rr.Hdr = h
+
+ s, e, c1 := endingToTxtSlice(c, "bad SPF Txt", f)
+ if e != nil {
+ return nil, e, ""
+ }
+ rr.Txt = s
+ return rr, nil, c1
+}
+
+func setTXT(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(TXT)
+ rr.Hdr = h
+
+ // no zBlank reading here, because all this rdata is TXT
+ s, e, c1 := endingToTxtSlice(c, "bad TXT Txt", f)
+ if e != nil {
+ return nil, e, ""
+ }
+ rr.Txt = s
+ return rr, nil, c1
+}
+
+// identical to setTXT
+func setNINFO(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(NINFO)
+ rr.Hdr = h
+
+ s, e, c1 := endingToTxtSlice(c, "bad NINFO ZSData", f)
+ if e != nil {
+ return nil, e, ""
+ }
+ rr.ZSData = s
+ return rr, nil, c1
+}
+
+func setURI(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(URI)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 { // Dynamic updates.
+ return rr, nil, ""
+ }
+
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad URI Priority", l}, ""
+ }
+ rr.Priority = uint16(i)
+ <-c // zBlank
+ l = <-c
+ i, e = strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad URI Weight", l}, ""
+ }
+ rr.Weight = uint16(i)
+
+ <-c // zBlank
+ s, err, c1 := endingToTxtSlice(c, "bad URI Target", f)
+ if err != nil {
+ return nil, err, ""
+ }
+ if len(s) > 1 {
+ return nil, &ParseError{f, "bad URI Target", l}, ""
+ }
+ rr.Target = s[0]
+ return rr, nil, c1
+}
+
+func setDHCID(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ // awesome record to parse!
+ rr := new(DHCID)
+ rr.Hdr = h
+
+ s, e, c1 := endingToString(c, "bad DHCID Digest", f)
+ if e != nil {
+ return nil, e, c1
+ }
+ rr.Digest = s
+ return rr, nil, c1
+}
+
+func setNID(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(NID)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad NID Preference", l}, ""
+ }
+ rr.Preference = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ u, err := stringToNodeID(l)
+ if err != nil || l.err {
+ return nil, err, ""
+ }
+ rr.NodeID = u
+ return rr, nil, ""
+}
+
+func setL32(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(L32)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad L32 Preference", l}, ""
+ }
+ rr.Preference = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ rr.Locator32 = net.ParseIP(l.token)
+ if rr.Locator32 == nil || l.err {
+ return nil, &ParseError{f, "bad L32 Locator", l}, ""
+ }
+ return rr, nil, ""
+}
+
+func setLP(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(LP)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad LP Preference", l}, ""
+ }
+ rr.Preference = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ rr.Fqdn = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Fqdn = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad LP Fqdn", l}, ""
+ }
+ if rr.Fqdn[l.length-1] != '.' {
+ rr.Fqdn = appendOrigin(rr.Fqdn, o)
+ }
+ return rr, nil, ""
+}
+
+func setL64(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(L64)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad L64 Preference", l}, ""
+ }
+ rr.Preference = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ u, err := stringToNodeID(l)
+ if err != nil || l.err {
+ return nil, err, ""
+ }
+ rr.Locator64 = u
+ return rr, nil, ""
+}
+
+func setUID(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(UID)
+ rr.Hdr = h
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad UID Uid", l}, ""
+ }
+ rr.Uid = uint32(i)
+ return rr, nil, ""
+}
+
+func setGID(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(GID)
+ rr.Hdr = h
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad GID Gid", l}, ""
+ }
+ rr.Gid = uint32(i)
+ return rr, nil, ""
+}
+
+func setUINFO(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(UINFO)
+ rr.Hdr = h
+ s, e, c1 := endingToTxtSlice(c, "bad UINFO Uinfo", f)
+ if e != nil {
+ return nil, e, ""
+ }
+ rr.Uinfo = s[0] // silently discard anything above
+ return rr, nil, c1
+}
+
+func setPX(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(PX)
+ rr.Hdr = h
+
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ i, e := strconv.Atoi(l.token)
+ if e != nil || l.err {
+ return nil, &ParseError{f, "bad PX Preference", l}, ""
+ }
+ rr.Preference = uint16(i)
+ <-c // zBlank
+ l = <-c // zString
+ rr.Map822 = l.token
+ if l.length == 0 {
+ return rr, nil, ""
+ }
+ if l.token == "@" {
+ rr.Map822 = o
+ return rr, nil, ""
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad PX Map822", l}, ""
+ }
+ if rr.Map822[l.length-1] != '.' {
+ rr.Map822 = appendOrigin(rr.Map822, o)
+ }
+ <-c // zBlank
+ l = <-c // zString
+ rr.Mapx400 = l.token
+ if l.token == "@" {
+ rr.Mapx400 = o
+ return rr, nil, ""
+ }
+ _, ok = IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad PX Mapx400", l}, ""
+ }
+ if rr.Mapx400[l.length-1] != '.' {
+ rr.Mapx400 = appendOrigin(rr.Mapx400, o)
+ }
+ return rr, nil, ""
+}
+
+func setIPSECKEY(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(IPSECKEY)
+ rr.Hdr = h
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ i, err := strconv.Atoi(l.token)
+ if err != nil || l.err {
+ return nil, &ParseError{f, "bad IPSECKEY Precedence", l}, ""
+ }
+ rr.Precedence = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, err = strconv.Atoi(l.token)
+ if err != nil || l.err {
+ return nil, &ParseError{f, "bad IPSECKEY GatewayType", l}, ""
+ }
+ rr.GatewayType = uint8(i)
+ <-c // zBlank
+ l = <-c
+ i, err = strconv.Atoi(l.token)
+ if err != nil || l.err {
+ return nil, &ParseError{f, "bad IPSECKEY Algorithm", l}, ""
+ }
+ rr.Algorithm = uint8(i)
+
+ // Now according to GatewayType we can have different elements here
+ <-c // zBlank
+ l = <-c
+ switch rr.GatewayType {
+ case 0:
+ fallthrough
+ case 3:
+ rr.GatewayName = l.token
+ if l.token == "@" {
+ rr.GatewayName = o
+ }
+ _, ok := IsDomainName(l.token)
+ if !ok || l.length == 0 || l.err {
+ return nil, &ParseError{f, "bad IPSECKEY GatewayName", l}, ""
+ }
+ if rr.GatewayName[l.length-1] != '.' {
+ rr.GatewayName = appendOrigin(rr.GatewayName, o)
+ }
+ case 1:
+ rr.GatewayA = net.ParseIP(l.token)
+ if rr.GatewayA == nil {
+ return nil, &ParseError{f, "bad IPSECKEY GatewayA", l}, ""
+ }
+ case 2:
+ rr.GatewayAAAA = net.ParseIP(l.token)
+ if rr.GatewayAAAA == nil {
+ return nil, &ParseError{f, "bad IPSECKEY GatewayAAAA", l}, ""
+ }
+ default:
+ return nil, &ParseError{f, "bad IPSECKEY GatewayType", l}, ""
+ }
+
+ s, e, c1 := endingToString(c, "bad IPSECKEY PublicKey", f)
+ if e != nil {
+ return nil, e, c1
+ }
+ rr.PublicKey = s
+ return rr, nil, c1
+}
+
+func setCAA(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
+ rr := new(CAA)
+ rr.Hdr = h
+ l := <-c
+ if l.length == 0 {
+ return rr, nil, l.comment
+ }
+ i, err := strconv.Atoi(l.token)
+ if err != nil || l.err {
+ return nil, &ParseError{f, "bad CAA Flag", l}, ""
+ }
+ rr.Flag = uint8(i)
+
+ <-c // zBlank
+ l = <-c // zString
+ if l.value != zString {
+ return nil, &ParseError{f, "bad CAA Tag", l}, ""
+ }
+ rr.Tag = l.token
+
+ <-c // zBlank
+ s, e, c1 := endingToTxtSlice(c, "bad CAA Value", f)
+ if e != nil {
+ return nil, e, ""
+ }
+ if len(s) > 1 {
+ return nil, &ParseError{f, "bad CAA Value", l}, ""
+ }
+ rr.Value = s[0]
+ return rr, nil, c1
+}
+
+var typeToparserFunc = map[uint16]parserFunc{
+ TypeAAAA: parserFunc{setAAAA, false},
+ TypeAFSDB: parserFunc{setAFSDB, false},
+ TypeA: parserFunc{setA, false},
+ TypeCAA: parserFunc{setCAA, true},
+ TypeCDS: parserFunc{setCDS, true},
+ TypeCDNSKEY: parserFunc{setCDNSKEY, true},
+ TypeCERT: parserFunc{setCERT, true},
+ TypeCNAME: parserFunc{setCNAME, false},
+ TypeDHCID: parserFunc{setDHCID, true},
+ TypeDLV: parserFunc{setDLV, true},
+ TypeDNAME: parserFunc{setDNAME, false},
+ TypeKEY: parserFunc{setKEY, true},
+ TypeDNSKEY: parserFunc{setDNSKEY, true},
+ TypeDS: parserFunc{setDS, true},
+ TypeEID: parserFunc{setEID, true},
+ TypeEUI48: parserFunc{setEUI48, false},
+ TypeEUI64: parserFunc{setEUI64, false},
+ TypeGID: parserFunc{setGID, false},
+ TypeGPOS: parserFunc{setGPOS, false},
+ TypeHINFO: parserFunc{setHINFO, true},
+ TypeHIP: parserFunc{setHIP, true},
+ TypeIPSECKEY: parserFunc{setIPSECKEY, true},
+ TypeKX: parserFunc{setKX, false},
+ TypeL32: parserFunc{setL32, false},
+ TypeL64: parserFunc{setL64, false},
+ TypeLOC: parserFunc{setLOC, true},
+ TypeLP: parserFunc{setLP, false},
+ TypeMB: parserFunc{setMB, false},
+ TypeMD: parserFunc{setMD, false},
+ TypeMF: parserFunc{setMF, false},
+ TypeMG: parserFunc{setMG, false},
+ TypeMINFO: parserFunc{setMINFO, false},
+ TypeMR: parserFunc{setMR, false},
+ TypeMX: parserFunc{setMX, false},
+ TypeNAPTR: parserFunc{setNAPTR, false},
+ TypeNID: parserFunc{setNID, false},
+ TypeNIMLOC: parserFunc{setNIMLOC, true},
+ TypeNINFO: parserFunc{setNINFO, true},
+ TypeNSAPPTR: parserFunc{setNSAPPTR, false},
+ TypeNSEC3PARAM: parserFunc{setNSEC3PARAM, false},
+ TypeNSEC3: parserFunc{setNSEC3, true},
+ TypeNSEC: parserFunc{setNSEC, true},
+ TypeNS: parserFunc{setNS, false},
+ TypeOPENPGPKEY: parserFunc{setOPENPGPKEY, true},
+ TypePTR: parserFunc{setPTR, false},
+ TypePX: parserFunc{setPX, false},
+ TypeSIG: parserFunc{setSIG, true},
+ TypeRKEY: parserFunc{setRKEY, true},
+ TypeRP: parserFunc{setRP, false},
+ TypeRRSIG: parserFunc{setRRSIG, true},
+ TypeRT: parserFunc{setRT, false},
+ TypeSOA: parserFunc{setSOA, false},
+ TypeSPF: parserFunc{setSPF, true},
+ TypeSRV: parserFunc{setSRV, false},
+ TypeSSHFP: parserFunc{setSSHFP, true},
+ TypeTALINK: parserFunc{setTALINK, false},
+ TypeTA: parserFunc{setTA, true},
+ TypeTLSA: parserFunc{setTLSA, true},
+ TypeTXT: parserFunc{setTXT, true},
+ TypeUID: parserFunc{setUID, false},
+ TypeUINFO: parserFunc{setUINFO, true},
+ TypeURI: parserFunc{setURI, true},
+ TypeWKS: parserFunc{setWKS, true},
+ TypeX25: parserFunc{setX25, false},
+}
diff --git a/vendor/github.com/miekg/dns/ztypes.go b/vendor/github.com/miekg/dns/ztypes.go
new file mode 100644
index 0000000..3d0f9ae
--- /dev/null
+++ b/vendor/github.com/miekg/dns/ztypes.go
@@ -0,0 +1,842 @@
+// *** DO NOT MODIFY ***
+// AUTOGENERATED BY go generate
+
+package dns
+
+import (
+ "encoding/base64"
+ "net"
+)
+
+// TypeToRR is a map of constructors for each RR type.
+var TypeToRR = map[uint16]func() RR{
+ TypeA: func() RR { return new(A) },
+ TypeAAAA: func() RR { return new(AAAA) },
+ TypeAFSDB: func() RR { return new(AFSDB) },
+ TypeANY: func() RR { return new(ANY) },
+ TypeCAA: func() RR { return new(CAA) },
+ TypeCDNSKEY: func() RR { return new(CDNSKEY) },
+ TypeCDS: func() RR { return new(CDS) },
+ TypeCERT: func() RR { return new(CERT) },
+ TypeCNAME: func() RR { return new(CNAME) },
+ TypeDHCID: func() RR { return new(DHCID) },
+ TypeDLV: func() RR { return new(DLV) },
+ TypeDNAME: func() RR { return new(DNAME) },
+ TypeDNSKEY: func() RR { return new(DNSKEY) },
+ TypeDS: func() RR { return new(DS) },
+ TypeEID: func() RR { return new(EID) },
+ TypeEUI48: func() RR { return new(EUI48) },
+ TypeEUI64: func() RR { return new(EUI64) },
+ TypeGID: func() RR { return new(GID) },
+ TypeGPOS: func() RR { return new(GPOS) },
+ TypeHINFO: func() RR { return new(HINFO) },
+ TypeHIP: func() RR { return new(HIP) },
+ TypeIPSECKEY: func() RR { return new(IPSECKEY) },
+ TypeKEY: func() RR { return new(KEY) },
+ TypeKX: func() RR { return new(KX) },
+ TypeL32: func() RR { return new(L32) },
+ TypeL64: func() RR { return new(L64) },
+ TypeLOC: func() RR { return new(LOC) },
+ TypeLP: func() RR { return new(LP) },
+ TypeMB: func() RR { return new(MB) },
+ TypeMD: func() RR { return new(MD) },
+ TypeMF: func() RR { return new(MF) },
+ TypeMG: func() RR { return new(MG) },
+ TypeMINFO: func() RR { return new(MINFO) },
+ TypeMR: func() RR { return new(MR) },
+ TypeMX: func() RR { return new(MX) },
+ TypeNAPTR: func() RR { return new(NAPTR) },
+ TypeNID: func() RR { return new(NID) },
+ TypeNIMLOC: func() RR { return new(NIMLOC) },
+ TypeNINFO: func() RR { return new(NINFO) },
+ TypeNS: func() RR { return new(NS) },
+ TypeNSAPPTR: func() RR { return new(NSAPPTR) },
+ TypeNSEC: func() RR { return new(NSEC) },
+ TypeNSEC3: func() RR { return new(NSEC3) },
+ TypeNSEC3PARAM: func() RR { return new(NSEC3PARAM) },
+ TypeOPENPGPKEY: func() RR { return new(OPENPGPKEY) },
+ TypeOPT: func() RR { return new(OPT) },
+ TypePTR: func() RR { return new(PTR) },
+ TypePX: func() RR { return new(PX) },
+ TypeRKEY: func() RR { return new(RKEY) },
+ TypeRP: func() RR { return new(RP) },
+ TypeRRSIG: func() RR { return new(RRSIG) },
+ TypeRT: func() RR { return new(RT) },
+ TypeSIG: func() RR { return new(SIG) },
+ TypeSOA: func() RR { return new(SOA) },
+ TypeSPF: func() RR { return new(SPF) },
+ TypeSRV: func() RR { return new(SRV) },
+ TypeSSHFP: func() RR { return new(SSHFP) },
+ TypeTA: func() RR { return new(TA) },
+ TypeTALINK: func() RR { return new(TALINK) },
+ TypeTKEY: func() RR { return new(TKEY) },
+ TypeTLSA: func() RR { return new(TLSA) },
+ TypeTSIG: func() RR { return new(TSIG) },
+ TypeTXT: func() RR { return new(TXT) },
+ TypeUID: func() RR { return new(UID) },
+ TypeUINFO: func() RR { return new(UINFO) },
+ TypeURI: func() RR { return new(URI) },
+ TypeWKS: func() RR { return new(WKS) },
+ TypeX25: func() RR { return new(X25) },
+}
+
+// TypeToString is a map of strings for each RR type.
+var TypeToString = map[uint16]string{
+ TypeA: "A",
+ TypeAAAA: "AAAA",
+ TypeAFSDB: "AFSDB",
+ TypeANY: "ANY",
+ TypeATMA: "ATMA",
+ TypeAXFR: "AXFR",
+ TypeCAA: "CAA",
+ TypeCDNSKEY: "CDNSKEY",
+ TypeCDS: "CDS",
+ TypeCERT: "CERT",
+ TypeCNAME: "CNAME",
+ TypeDHCID: "DHCID",
+ TypeDLV: "DLV",
+ TypeDNAME: "DNAME",
+ TypeDNSKEY: "DNSKEY",
+ TypeDS: "DS",
+ TypeEID: "EID",
+ TypeEUI48: "EUI48",
+ TypeEUI64: "EUI64",
+ TypeGID: "GID",
+ TypeGPOS: "GPOS",
+ TypeHINFO: "HINFO",
+ TypeHIP: "HIP",
+ TypeIPSECKEY: "IPSECKEY",
+ TypeISDN: "ISDN",
+ TypeIXFR: "IXFR",
+ TypeKEY: "KEY",
+ TypeKX: "KX",
+ TypeL32: "L32",
+ TypeL64: "L64",
+ TypeLOC: "LOC",
+ TypeLP: "LP",
+ TypeMAILA: "MAILA",
+ TypeMAILB: "MAILB",
+ TypeMB: "MB",
+ TypeMD: "MD",
+ TypeMF: "MF",
+ TypeMG: "MG",
+ TypeMINFO: "MINFO",
+ TypeMR: "MR",
+ TypeMX: "MX",
+ TypeNAPTR: "NAPTR",
+ TypeNID: "NID",
+ TypeNIMLOC: "NIMLOC",
+ TypeNINFO: "NINFO",
+ TypeNS: "NS",
+ TypeNSEC: "NSEC",
+ TypeNSEC3: "NSEC3",
+ TypeNSEC3PARAM: "NSEC3PARAM",
+ TypeNULL: "NULL",
+ TypeNXT: "NXT",
+ TypeNone: "None",
+ TypeOPENPGPKEY: "OPENPGPKEY",
+ TypeOPT: "OPT",
+ TypePTR: "PTR",
+ TypePX: "PX",
+ TypeRKEY: "RKEY",
+ TypeRP: "RP",
+ TypeRRSIG: "RRSIG",
+ TypeRT: "RT",
+ TypeReserved: "Reserved",
+ TypeSIG: "SIG",
+ TypeSOA: "SOA",
+ TypeSPF: "SPF",
+ TypeSRV: "SRV",
+ TypeSSHFP: "SSHFP",
+ TypeTA: "TA",
+ TypeTALINK: "TALINK",
+ TypeTKEY: "TKEY",
+ TypeTLSA: "TLSA",
+ TypeTSIG: "TSIG",
+ TypeTXT: "TXT",
+ TypeUID: "UID",
+ TypeUINFO: "UINFO",
+ TypeUNSPEC: "UNSPEC",
+ TypeURI: "URI",
+ TypeWKS: "WKS",
+ TypeX25: "X25",
+ TypeNSAPPTR: "NSAP-PTR",
+}
+
+// Header() functions
+func (rr *A) Header() *RR_Header { return &rr.Hdr }
+func (rr *AAAA) Header() *RR_Header { return &rr.Hdr }
+func (rr *AFSDB) Header() *RR_Header { return &rr.Hdr }
+func (rr *ANY) Header() *RR_Header { return &rr.Hdr }
+func (rr *CAA) Header() *RR_Header { return &rr.Hdr }
+func (rr *CDNSKEY) Header() *RR_Header { return &rr.Hdr }
+func (rr *CDS) Header() *RR_Header { return &rr.Hdr }
+func (rr *CERT) Header() *RR_Header { return &rr.Hdr }
+func (rr *CNAME) Header() *RR_Header { return &rr.Hdr }
+func (rr *DHCID) Header() *RR_Header { return &rr.Hdr }
+func (rr *DLV) Header() *RR_Header { return &rr.Hdr }
+func (rr *DNAME) Header() *RR_Header { return &rr.Hdr }
+func (rr *DNSKEY) Header() *RR_Header { return &rr.Hdr }
+func (rr *DS) Header() *RR_Header { return &rr.Hdr }
+func (rr *EID) Header() *RR_Header { return &rr.Hdr }
+func (rr *EUI48) Header() *RR_Header { return &rr.Hdr }
+func (rr *EUI64) Header() *RR_Header { return &rr.Hdr }
+func (rr *GID) Header() *RR_Header { return &rr.Hdr }
+func (rr *GPOS) Header() *RR_Header { return &rr.Hdr }
+func (rr *HINFO) Header() *RR_Header { return &rr.Hdr }
+func (rr *HIP) Header() *RR_Header { return &rr.Hdr }
+func (rr *IPSECKEY) Header() *RR_Header { return &rr.Hdr }
+func (rr *KEY) Header() *RR_Header { return &rr.Hdr }
+func (rr *KX) Header() *RR_Header { return &rr.Hdr }
+func (rr *L32) Header() *RR_Header { return &rr.Hdr }
+func (rr *L64) Header() *RR_Header { return &rr.Hdr }
+func (rr *LOC) Header() *RR_Header { return &rr.Hdr }
+func (rr *LP) Header() *RR_Header { return &rr.Hdr }
+func (rr *MB) Header() *RR_Header { return &rr.Hdr }
+func (rr *MD) Header() *RR_Header { return &rr.Hdr }
+func (rr *MF) Header() *RR_Header { return &rr.Hdr }
+func (rr *MG) Header() *RR_Header { return &rr.Hdr }
+func (rr *MINFO) Header() *RR_Header { return &rr.Hdr }
+func (rr *MR) Header() *RR_Header { return &rr.Hdr }
+func (rr *MX) Header() *RR_Header { return &rr.Hdr }
+func (rr *NAPTR) Header() *RR_Header { return &rr.Hdr }
+func (rr *NID) Header() *RR_Header { return &rr.Hdr }
+func (rr *NIMLOC) Header() *RR_Header { return &rr.Hdr }
+func (rr *NINFO) Header() *RR_Header { return &rr.Hdr }
+func (rr *NS) Header() *RR_Header { return &rr.Hdr }
+func (rr *NSAPPTR) Header() *RR_Header { return &rr.Hdr }
+func (rr *NSEC) Header() *RR_Header { return &rr.Hdr }
+func (rr *NSEC3) Header() *RR_Header { return &rr.Hdr }
+func (rr *NSEC3PARAM) Header() *RR_Header { return &rr.Hdr }
+func (rr *OPENPGPKEY) Header() *RR_Header { return &rr.Hdr }
+func (rr *OPT) Header() *RR_Header { return &rr.Hdr }
+func (rr *PTR) Header() *RR_Header { return &rr.Hdr }
+func (rr *PX) Header() *RR_Header { return &rr.Hdr }
+func (rr *RFC3597) Header() *RR_Header { return &rr.Hdr }
+func (rr *RKEY) Header() *RR_Header { return &rr.Hdr }
+func (rr *RP) Header() *RR_Header { return &rr.Hdr }
+func (rr *RRSIG) Header() *RR_Header { return &rr.Hdr }
+func (rr *RT) Header() *RR_Header { return &rr.Hdr }
+func (rr *SIG) Header() *RR_Header { return &rr.Hdr }
+func (rr *SOA) Header() *RR_Header { return &rr.Hdr }
+func (rr *SPF) Header() *RR_Header { return &rr.Hdr }
+func (rr *SRV) Header() *RR_Header { return &rr.Hdr }
+func (rr *SSHFP) Header() *RR_Header { return &rr.Hdr }
+func (rr *TA) Header() *RR_Header { return &rr.Hdr }
+func (rr *TALINK) Header() *RR_Header { return &rr.Hdr }
+func (rr *TKEY) Header() *RR_Header { return &rr.Hdr }
+func (rr *TLSA) Header() *RR_Header { return &rr.Hdr }
+func (rr *TSIG) Header() *RR_Header { return &rr.Hdr }
+func (rr *TXT) Header() *RR_Header { return &rr.Hdr }
+func (rr *UID) Header() *RR_Header { return &rr.Hdr }
+func (rr *UINFO) Header() *RR_Header { return &rr.Hdr }
+func (rr *URI) Header() *RR_Header { return &rr.Hdr }
+func (rr *WKS) Header() *RR_Header { return &rr.Hdr }
+func (rr *X25) Header() *RR_Header { return &rr.Hdr }
+
+// len() functions
+func (rr *A) len() int {
+ l := rr.Hdr.len()
+ l += net.IPv4len // A
+ return l
+}
+func (rr *AAAA) len() int {
+ l := rr.Hdr.len()
+ l += net.IPv6len // AAAA
+ return l
+}
+func (rr *AFSDB) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Subtype
+ l += len(rr.Hostname) + 1
+ return l
+}
+func (rr *ANY) len() int {
+ l := rr.Hdr.len()
+ return l
+}
+func (rr *CAA) len() int {
+ l := rr.Hdr.len()
+ l += 1 // Flag
+ l += len(rr.Tag) + 1
+ l += len(rr.Value)
+ return l
+}
+func (rr *CERT) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Type
+ l += 2 // KeyTag
+ l += 1 // Algorithm
+ l += base64.StdEncoding.DecodedLen(len(rr.Certificate))
+ return l
+}
+func (rr *CNAME) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Target) + 1
+ return l
+}
+func (rr *DHCID) len() int {
+ l := rr.Hdr.len()
+ l += base64.StdEncoding.DecodedLen(len(rr.Digest))
+ return l
+}
+func (rr *DNAME) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Target) + 1
+ return l
+}
+func (rr *DNSKEY) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Flags
+ l += 1 // Protocol
+ l += 1 // Algorithm
+ l += base64.StdEncoding.DecodedLen(len(rr.PublicKey))
+ return l
+}
+func (rr *DS) len() int {
+ l := rr.Hdr.len()
+ l += 2 // KeyTag
+ l += 1 // Algorithm
+ l += 1 // DigestType
+ l += len(rr.Digest)/2 + 1
+ return l
+}
+func (rr *EID) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Endpoint)/2 + 1
+ return l
+}
+func (rr *EUI48) len() int {
+ l := rr.Hdr.len()
+ l += 6 // Address
+ return l
+}
+func (rr *EUI64) len() int {
+ l := rr.Hdr.len()
+ l += 8 // Address
+ return l
+}
+func (rr *GID) len() int {
+ l := rr.Hdr.len()
+ l += 4 // Gid
+ return l
+}
+func (rr *GPOS) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Longitude) + 1
+ l += len(rr.Latitude) + 1
+ l += len(rr.Altitude) + 1
+ return l
+}
+func (rr *HINFO) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Cpu) + 1
+ l += len(rr.Os) + 1
+ return l
+}
+func (rr *HIP) len() int {
+ l := rr.Hdr.len()
+ l += 1 // HitLength
+ l += 1 // PublicKeyAlgorithm
+ l += 2 // PublicKeyLength
+ l += len(rr.Hit)/2 + 1
+ l += base64.StdEncoding.DecodedLen(len(rr.PublicKey))
+ for _, x := range rr.RendezvousServers {
+ l += len(x) + 1
+ }
+ return l
+}
+func (rr *KX) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Preference
+ l += len(rr.Exchanger) + 1
+ return l
+}
+func (rr *L32) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Preference
+ l += net.IPv4len // Locator32
+ return l
+}
+func (rr *L64) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Preference
+ l += 8 // Locator64
+ return l
+}
+func (rr *LOC) len() int {
+ l := rr.Hdr.len()
+ l += 1 // Version
+ l += 1 // Size
+ l += 1 // HorizPre
+ l += 1 // VertPre
+ l += 4 // Latitude
+ l += 4 // Longitude
+ l += 4 // Altitude
+ return l
+}
+func (rr *LP) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Preference
+ l += len(rr.Fqdn) + 1
+ return l
+}
+func (rr *MB) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Mb) + 1
+ return l
+}
+func (rr *MD) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Md) + 1
+ return l
+}
+func (rr *MF) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Mf) + 1
+ return l
+}
+func (rr *MG) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Mg) + 1
+ return l
+}
+func (rr *MINFO) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Rmail) + 1
+ l += len(rr.Email) + 1
+ return l
+}
+func (rr *MR) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Mr) + 1
+ return l
+}
+func (rr *MX) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Preference
+ l += len(rr.Mx) + 1
+ return l
+}
+func (rr *NAPTR) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Order
+ l += 2 // Preference
+ l += len(rr.Flags) + 1
+ l += len(rr.Service) + 1
+ l += len(rr.Regexp) + 1
+ l += len(rr.Replacement) + 1
+ return l
+}
+func (rr *NID) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Preference
+ l += 8 // NodeID
+ return l
+}
+func (rr *NIMLOC) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Locator)/2 + 1
+ return l
+}
+func (rr *NINFO) len() int {
+ l := rr.Hdr.len()
+ for _, x := range rr.ZSData {
+ l += len(x) + 1
+ }
+ return l
+}
+func (rr *NS) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Ns) + 1
+ return l
+}
+func (rr *NSAPPTR) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Ptr) + 1
+ return l
+}
+func (rr *NSEC3PARAM) len() int {
+ l := rr.Hdr.len()
+ l += 1 // Hash
+ l += 1 // Flags
+ l += 2 // Iterations
+ l += 1 // SaltLength
+ l += len(rr.Salt)/2 + 1
+ return l
+}
+func (rr *OPENPGPKEY) len() int {
+ l := rr.Hdr.len()
+ l += base64.StdEncoding.DecodedLen(len(rr.PublicKey))
+ return l
+}
+func (rr *PTR) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Ptr) + 1
+ return l
+}
+func (rr *PX) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Preference
+ l += len(rr.Map822) + 1
+ l += len(rr.Mapx400) + 1
+ return l
+}
+func (rr *RFC3597) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Rdata)/2 + 1
+ return l
+}
+func (rr *RKEY) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Flags
+ l += 1 // Protocol
+ l += 1 // Algorithm
+ l += base64.StdEncoding.DecodedLen(len(rr.PublicKey))
+ return l
+}
+func (rr *RP) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Mbox) + 1
+ l += len(rr.Txt) + 1
+ return l
+}
+func (rr *RRSIG) len() int {
+ l := rr.Hdr.len()
+ l += 2 // TypeCovered
+ l += 1 // Algorithm
+ l += 1 // Labels
+ l += 4 // OrigTtl
+ l += 4 // Expiration
+ l += 4 // Inception
+ l += 2 // KeyTag
+ l += len(rr.SignerName) + 1
+ l += base64.StdEncoding.DecodedLen(len(rr.Signature))
+ return l
+}
+func (rr *RT) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Preference
+ l += len(rr.Host) + 1
+ return l
+}
+func (rr *SOA) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Ns) + 1
+ l += len(rr.Mbox) + 1
+ l += 4 // Serial
+ l += 4 // Refresh
+ l += 4 // Retry
+ l += 4 // Expire
+ l += 4 // Minttl
+ return l
+}
+func (rr *SPF) len() int {
+ l := rr.Hdr.len()
+ for _, x := range rr.Txt {
+ l += len(x) + 1
+ }
+ return l
+}
+func (rr *SRV) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Priority
+ l += 2 // Weight
+ l += 2 // Port
+ l += len(rr.Target) + 1
+ return l
+}
+func (rr *SSHFP) len() int {
+ l := rr.Hdr.len()
+ l += 1 // Algorithm
+ l += 1 // Type
+ l += len(rr.FingerPrint)/2 + 1
+ return l
+}
+func (rr *TA) len() int {
+ l := rr.Hdr.len()
+ l += 2 // KeyTag
+ l += 1 // Algorithm
+ l += 1 // DigestType
+ l += len(rr.Digest)/2 + 1
+ return l
+}
+func (rr *TALINK) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.PreviousName) + 1
+ l += len(rr.NextName) + 1
+ return l
+}
+func (rr *TKEY) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Algorithm) + 1
+ l += 4 // Inception
+ l += 4 // Expiration
+ l += 2 // Mode
+ l += 2 // Error
+ l += 2 // KeySize
+ l += len(rr.Key) + 1
+ l += 2 // OtherLen
+ l += len(rr.OtherData) + 1
+ return l
+}
+func (rr *TLSA) len() int {
+ l := rr.Hdr.len()
+ l += 1 // Usage
+ l += 1 // Selector
+ l += 1 // MatchingType
+ l += len(rr.Certificate)/2 + 1
+ return l
+}
+func (rr *TSIG) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Algorithm) + 1
+ l += 6 // TimeSigned
+ l += 2 // Fudge
+ l += 2 // MACSize
+ l += len(rr.MAC)/2 + 1
+ l += 2 // OrigId
+ l += 2 // Error
+ l += 2 // OtherLen
+ l += len(rr.OtherData)/2 + 1
+ return l
+}
+func (rr *TXT) len() int {
+ l := rr.Hdr.len()
+ for _, x := range rr.Txt {
+ l += len(x) + 1
+ }
+ return l
+}
+func (rr *UID) len() int {
+ l := rr.Hdr.len()
+ l += 4 // Uid
+ return l
+}
+func (rr *UINFO) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.Uinfo) + 1
+ return l
+}
+func (rr *URI) len() int {
+ l := rr.Hdr.len()
+ l += 2 // Priority
+ l += 2 // Weight
+ l += len(rr.Target)
+ return l
+}
+func (rr *X25) len() int {
+ l := rr.Hdr.len()
+ l += len(rr.PSDNAddress) + 1
+ return l
+}
+
+// copy() functions
+func (rr *A) copy() RR {
+ return &A{*rr.Hdr.copyHeader(), copyIP(rr.A)}
+}
+func (rr *AAAA) copy() RR {
+ return &AAAA{*rr.Hdr.copyHeader(), copyIP(rr.AAAA)}
+}
+func (rr *AFSDB) copy() RR {
+ return &AFSDB{*rr.Hdr.copyHeader(), rr.Subtype, rr.Hostname}
+}
+func (rr *ANY) copy() RR {
+ return &ANY{*rr.Hdr.copyHeader()}
+}
+func (rr *CAA) copy() RR {
+ return &CAA{*rr.Hdr.copyHeader(), rr.Flag, rr.Tag, rr.Value}
+}
+func (rr *CERT) copy() RR {
+ return &CERT{*rr.Hdr.copyHeader(), rr.Type, rr.KeyTag, rr.Algorithm, rr.Certificate}
+}
+func (rr *CNAME) copy() RR {
+ return &CNAME{*rr.Hdr.copyHeader(), rr.Target}
+}
+func (rr *DHCID) copy() RR {
+ return &DHCID{*rr.Hdr.copyHeader(), rr.Digest}
+}
+func (rr *DNAME) copy() RR {
+ return &DNAME{*rr.Hdr.copyHeader(), rr.Target}
+}
+func (rr *DNSKEY) copy() RR {
+ return &DNSKEY{*rr.Hdr.copyHeader(), rr.Flags, rr.Protocol, rr.Algorithm, rr.PublicKey}
+}
+func (rr *DS) copy() RR {
+ return &DS{*rr.Hdr.copyHeader(), rr.KeyTag, rr.Algorithm, rr.DigestType, rr.Digest}
+}
+func (rr *EID) copy() RR {
+ return &EID{*rr.Hdr.copyHeader(), rr.Endpoint}
+}
+func (rr *EUI48) copy() RR {
+ return &EUI48{*rr.Hdr.copyHeader(), rr.Address}
+}
+func (rr *EUI64) copy() RR {
+ return &EUI64{*rr.Hdr.copyHeader(), rr.Address}
+}
+func (rr *GID) copy() RR {
+ return &GID{*rr.Hdr.copyHeader(), rr.Gid}
+}
+func (rr *GPOS) copy() RR {
+ return &GPOS{*rr.Hdr.copyHeader(), rr.Longitude, rr.Latitude, rr.Altitude}
+}
+func (rr *HINFO) copy() RR {
+ return &HINFO{*rr.Hdr.copyHeader(), rr.Cpu, rr.Os}
+}
+func (rr *HIP) copy() RR {
+ RendezvousServers := make([]string, len(rr.RendezvousServers))
+ copy(RendezvousServers, rr.RendezvousServers)
+ return &HIP{*rr.Hdr.copyHeader(), rr.HitLength, rr.PublicKeyAlgorithm, rr.PublicKeyLength, rr.Hit, rr.PublicKey, RendezvousServers}
+}
+func (rr *IPSECKEY) copy() RR {
+ return &IPSECKEY{*rr.Hdr.copyHeader(), rr.Precedence, rr.GatewayType, rr.Algorithm, copyIP(rr.GatewayA), copyIP(rr.GatewayAAAA), rr.GatewayName, rr.PublicKey}
+}
+func (rr *KX) copy() RR {
+ return &KX{*rr.Hdr.copyHeader(), rr.Preference, rr.Exchanger}
+}
+func (rr *L32) copy() RR {
+ return &L32{*rr.Hdr.copyHeader(), rr.Preference, copyIP(rr.Locator32)}
+}
+func (rr *L64) copy() RR {
+ return &L64{*rr.Hdr.copyHeader(), rr.Preference, rr.Locator64}
+}
+func (rr *LOC) copy() RR {
+ return &LOC{*rr.Hdr.copyHeader(), rr.Version, rr.Size, rr.HorizPre, rr.VertPre, rr.Latitude, rr.Longitude, rr.Altitude}
+}
+func (rr *LP) copy() RR {
+ return &LP{*rr.Hdr.copyHeader(), rr.Preference, rr.Fqdn}
+}
+func (rr *MB) copy() RR {
+ return &MB{*rr.Hdr.copyHeader(), rr.Mb}
+}
+func (rr *MD) copy() RR {
+ return &MD{*rr.Hdr.copyHeader(), rr.Md}
+}
+func (rr *MF) copy() RR {
+ return &MF{*rr.Hdr.copyHeader(), rr.Mf}
+}
+func (rr *MG) copy() RR {
+ return &MG{*rr.Hdr.copyHeader(), rr.Mg}
+}
+func (rr *MINFO) copy() RR {
+ return &MINFO{*rr.Hdr.copyHeader(), rr.Rmail, rr.Email}
+}
+func (rr *MR) copy() RR {
+ return &MR{*rr.Hdr.copyHeader(), rr.Mr}
+}
+func (rr *MX) copy() RR {
+ return &MX{*rr.Hdr.copyHeader(), rr.Preference, rr.Mx}
+}
+func (rr *NAPTR) copy() RR {
+ return &NAPTR{*rr.Hdr.copyHeader(), rr.Order, rr.Preference, rr.Flags, rr.Service, rr.Regexp, rr.Replacement}
+}
+func (rr *NID) copy() RR {
+ return &NID{*rr.Hdr.copyHeader(), rr.Preference, rr.NodeID}
+}
+func (rr *NIMLOC) copy() RR {
+ return &NIMLOC{*rr.Hdr.copyHeader(), rr.Locator}
+}
+func (rr *NINFO) copy() RR {
+ ZSData := make([]string, len(rr.ZSData))
+ copy(ZSData, rr.ZSData)
+ return &NINFO{*rr.Hdr.copyHeader(), ZSData}
+}
+func (rr *NS) copy() RR {
+ return &NS{*rr.Hdr.copyHeader(), rr.Ns}
+}
+func (rr *NSAPPTR) copy() RR {
+ return &NSAPPTR{*rr.Hdr.copyHeader(), rr.Ptr}
+}
+func (rr *NSEC) copy() RR {
+ TypeBitMap := make([]uint16, len(rr.TypeBitMap))
+ copy(TypeBitMap, rr.TypeBitMap)
+ return &NSEC{*rr.Hdr.copyHeader(), rr.NextDomain, TypeBitMap}
+}
+func (rr *NSEC3) copy() RR {
+ TypeBitMap := make([]uint16, len(rr.TypeBitMap))
+ copy(TypeBitMap, rr.TypeBitMap)
+ return &NSEC3{*rr.Hdr.copyHeader(), rr.Hash, rr.Flags, rr.Iterations, rr.SaltLength, rr.Salt, rr.HashLength, rr.NextDomain, TypeBitMap}
+}
+func (rr *NSEC3PARAM) copy() RR {
+ return &NSEC3PARAM{*rr.Hdr.copyHeader(), rr.Hash, rr.Flags, rr.Iterations, rr.SaltLength, rr.Salt}
+}
+func (rr *OPENPGPKEY) copy() RR {
+ return &OPENPGPKEY{*rr.Hdr.copyHeader(), rr.PublicKey}
+}
+func (rr *OPT) copy() RR {
+ Option := make([]EDNS0, len(rr.Option))
+ copy(Option, rr.Option)
+ return &OPT{*rr.Hdr.copyHeader(), Option}
+}
+func (rr *PTR) copy() RR {
+ return &PTR{*rr.Hdr.copyHeader(), rr.Ptr}
+}
+func (rr *PX) copy() RR {
+ return &PX{*rr.Hdr.copyHeader(), rr.Preference, rr.Map822, rr.Mapx400}
+}
+func (rr *RFC3597) copy() RR {
+ return &RFC3597{*rr.Hdr.copyHeader(), rr.Rdata}
+}
+func (rr *RKEY) copy() RR {
+ return &RKEY{*rr.Hdr.copyHeader(), rr.Flags, rr.Protocol, rr.Algorithm, rr.PublicKey}
+}
+func (rr *RP) copy() RR {
+ return &RP{*rr.Hdr.copyHeader(), rr.Mbox, rr.Txt}
+}
+func (rr *RRSIG) copy() RR {
+ return &RRSIG{*rr.Hdr.copyHeader(), rr.TypeCovered, rr.Algorithm, rr.Labels, rr.OrigTtl, rr.Expiration, rr.Inception, rr.KeyTag, rr.SignerName, rr.Signature}
+}
+func (rr *RT) copy() RR {
+ return &RT{*rr.Hdr.copyHeader(), rr.Preference, rr.Host}
+}
+func (rr *SOA) copy() RR {
+ return &SOA{*rr.Hdr.copyHeader(), rr.Ns, rr.Mbox, rr.Serial, rr.Refresh, rr.Retry, rr.Expire, rr.Minttl}
+}
+func (rr *SPF) copy() RR {
+ Txt := make([]string, len(rr.Txt))
+ copy(Txt, rr.Txt)
+ return &SPF{*rr.Hdr.copyHeader(), Txt}
+}
+func (rr *SRV) copy() RR {
+ return &SRV{*rr.Hdr.copyHeader(), rr.Priority, rr.Weight, rr.Port, rr.Target}
+}
+func (rr *SSHFP) copy() RR {
+ return &SSHFP{*rr.Hdr.copyHeader(), rr.Algorithm, rr.Type, rr.FingerPrint}
+}
+func (rr *TA) copy() RR {
+ return &TA{*rr.Hdr.copyHeader(), rr.KeyTag, rr.Algorithm, rr.DigestType, rr.Digest}
+}
+func (rr *TALINK) copy() RR {
+ return &TALINK{*rr.Hdr.copyHeader(), rr.PreviousName, rr.NextName}
+}
+func (rr *TKEY) copy() RR {
+ return &TKEY{*rr.Hdr.copyHeader(), rr.Algorithm, rr.Inception, rr.Expiration, rr.Mode, rr.Error, rr.KeySize, rr.Key, rr.OtherLen, rr.OtherData}
+}
+func (rr *TLSA) copy() RR {
+ return &TLSA{*rr.Hdr.copyHeader(), rr.Usage, rr.Selector, rr.MatchingType, rr.Certificate}
+}
+func (rr *TSIG) copy() RR {
+ return &TSIG{*rr.Hdr.copyHeader(), rr.Algorithm, rr.TimeSigned, rr.Fudge, rr.MACSize, rr.MAC, rr.OrigId, rr.Error, rr.OtherLen, rr.OtherData}
+}
+func (rr *TXT) copy() RR {
+ Txt := make([]string, len(rr.Txt))
+ copy(Txt, rr.Txt)
+ return &TXT{*rr.Hdr.copyHeader(), Txt}
+}
+func (rr *UID) copy() RR {
+ return &UID{*rr.Hdr.copyHeader(), rr.Uid}
+}
+func (rr *UINFO) copy() RR {
+ return &UINFO{*rr.Hdr.copyHeader(), rr.Uinfo}
+}
+func (rr *URI) copy() RR {
+ return &URI{*rr.Hdr.copyHeader(), rr.Priority, rr.Weight, rr.Target}
+}
+func (rr *WKS) copy() RR {
+ BitMap := make([]uint16, len(rr.BitMap))
+ copy(BitMap, rr.BitMap)
+ return &WKS{*rr.Hdr.copyHeader(), copyIP(rr.Address), rr.Protocol, BitMap}
+}
+func (rr *X25) copy() RR {
+ return &X25{*rr.Hdr.copyHeader(), rr.PSDNAddress}
+}
diff --git a/vendor/github.com/mistifyio/go-zfs/LICENSE b/vendor/github.com/mistifyio/go-zfs/LICENSE
new file mode 100644
index 0000000..f4c265c
--- /dev/null
+++ b/vendor/github.com/mistifyio/go-zfs/LICENSE
@@ -0,0 +1,201 @@
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright (c) 2014, OmniTI Computer Consulting, Inc.
+
+ 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. \ No newline at end of file
diff --git a/vendor/github.com/mistifyio/go-zfs/README.md b/vendor/github.com/mistifyio/go-zfs/README.md
new file mode 100644
index 0000000..2515e58
--- /dev/null
+++ b/vendor/github.com/mistifyio/go-zfs/README.md
@@ -0,0 +1,54 @@
+# Go Wrapper for ZFS #
+
+Simple wrappers for ZFS command line tools.
+
+[![GoDoc](https://godoc.org/github.com/mistifyio/go-zfs?status.svg)](https://godoc.org/github.com/mistifyio/go-zfs)
+
+## Requirements ##
+
+You need a working ZFS setup. To use on Ubuntu 14.04, setup ZFS:
+
+ sudo apt-get install python-software-properties
+ sudo apt-add-repository ppa:zfs-native/stable
+ sudo apt-get update
+ sudo apt-get install ubuntu-zfs libzfs-dev
+
+Developed using Go 1.3, but currently there isn't anything 1.3 specific. Don't use Ubuntu packages for Go, use http://golang.org/doc/install
+
+Generally you need root privileges to use anything zfs related.
+
+## Status ##
+
+This has been only been tested on Ubuntu 14.04
+
+In the future, we hope to work directly with libzfs.
+
+# Hacking #
+
+The tests have decent examples for most functions.
+
+```go
+//assuming a zpool named test
+//error handling ommitted
+
+
+f, err := zfs.CreateFilesystem("test/snapshot-test", nil)
+ok(t, err)
+
+s, err := f.Snapshot("test", nil)
+ok(t, err)
+
+// snapshot is named "test/snapshot-test@test"
+
+c, err := s.Clone("test/clone-test", nil)
+
+err := c.Destroy()
+err := s.Destroy()
+err := f.Destroy()
+
+```
+
+# Contributing #
+
+See the [contributing guidelines](./CONTRIBUTING.md)
+
diff --git a/vendor/github.com/mistifyio/go-zfs/error.go b/vendor/github.com/mistifyio/go-zfs/error.go
new file mode 100644
index 0000000..5408ccd
--- /dev/null
+++ b/vendor/github.com/mistifyio/go-zfs/error.go
@@ -0,0 +1,18 @@
+package zfs
+
+import (
+ "fmt"
+)
+
+// Error is an error which is returned when the `zfs` or `zpool` shell
+// commands return with a non-zero exit code.
+type Error struct {
+ Err error
+ Debug string
+ Stderr string
+}
+
+// Error returns the string representation of an Error.
+func (e Error) Error() string {
+ return fmt.Sprintf("%s: %q => %s", e.Err, e.Debug, e.Stderr)
+}
diff --git a/vendor/github.com/mistifyio/go-zfs/utils.go b/vendor/github.com/mistifyio/go-zfs/utils.go
new file mode 100644
index 0000000..c7178d6
--- /dev/null
+++ b/vendor/github.com/mistifyio/go-zfs/utils.go
@@ -0,0 +1,352 @@
+package zfs
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "os/exec"
+ "regexp"
+ "runtime"
+ "strconv"
+ "strings"
+
+ "github.com/pborman/uuid"
+)
+
+type command struct {
+ Command string
+ Stdin io.Reader
+ Stdout io.Writer
+}
+
+func (c *command) Run(arg ...string) ([][]string, error) {
+
+ cmd := exec.Command(c.Command, arg...)
+
+ var stdout, stderr bytes.Buffer
+
+ if c.Stdout == nil {
+ cmd.Stdout = &stdout
+ } else {
+ cmd.Stdout = c.Stdout
+ }
+
+ if c.Stdin != nil {
+ cmd.Stdin = c.Stdin
+
+ }
+ cmd.Stderr = &stderr
+
+ id := uuid.New()
+ joinedArgs := strings.Join(cmd.Args, " ")
+
+ logger.Log([]string{"ID:" + id, "START", joinedArgs})
+ err := cmd.Run()
+ logger.Log([]string{"ID:" + id, "FINISH"})
+
+ if err != nil {
+ return nil, &Error{
+ Err: err,
+ Debug: strings.Join([]string{cmd.Path, joinedArgs}, " "),
+ Stderr: stderr.String(),
+ }
+ }
+
+ // assume if you passed in something for stdout, that you know what to do with it
+ if c.Stdout != nil {
+ return nil, nil
+ }
+
+ lines := strings.Split(stdout.String(), "\n")
+
+ //last line is always blank
+ lines = lines[0 : len(lines)-1]
+ output := make([][]string, len(lines))
+
+ for i, l := range lines {
+ output[i] = strings.Fields(l)
+ }
+
+ return output, nil
+}
+
+func setString(field *string, value string) {
+ v := ""
+ if value != "-" {
+ v = value
+ }
+ *field = v
+}
+
+func setUint(field *uint64, value string) error {
+ var v uint64
+ if value != "-" {
+ var err error
+ v, err = strconv.ParseUint(value, 10, 64)
+ if err != nil {
+ return err
+ }
+ }
+ *field = v
+ return nil
+}
+
+func (ds *Dataset) parseLine(line []string) error {
+ var err error
+
+ if len(line) != len(dsPropList) {
+ return errors.New("Output does not match what is expected on this platform")
+ }
+ setString(&ds.Name, line[0])
+ setString(&ds.Origin, line[1])
+
+ if err = setUint(&ds.Used, line[2]); err != nil {
+ return err
+ }
+ if err = setUint(&ds.Avail, line[3]); err != nil {
+ return err
+ }
+
+ setString(&ds.Mountpoint, line[4])
+ setString(&ds.Compression, line[5])
+ setString(&ds.Type, line[6])
+
+ if err = setUint(&ds.Volsize, line[7]); err != nil {
+ return err
+ }
+ if err = setUint(&ds.Quota, line[8]); err != nil {
+ return err
+ }
+
+ if runtime.GOOS == "solaris" {
+ return nil
+ }
+
+ if err = setUint(&ds.Written, line[9]); err != nil {
+ return err
+ }
+ if err = setUint(&ds.Logicalused, line[10]); err != nil {
+ return err
+ }
+ if err = setUint(&ds.Usedbydataset, line[11]); err != nil {
+ return err
+ }
+ return nil
+}
+
+/*
+ * from zfs diff`s escape function:
+ *
+ * Prints a file name out a character at a time. If the character is
+ * not in the range of what we consider "printable" ASCII, display it
+ * as an escaped 3-digit octal value. ASCII values less than a space
+ * are all control characters and we declare the upper end as the
+ * DELete character. This also is the last 7-bit ASCII character.
+ * We choose to treat all 8-bit ASCII as not printable for this
+ * application.
+ */
+func unescapeFilepath(path string) (string, error) {
+ buf := make([]byte, 0, len(path))
+ llen := len(path)
+ for i := 0; i < llen; {
+ if path[i] == '\\' {
+ if llen < i+4 {
+ return "", fmt.Errorf("Invalid octal code: too short")
+ }
+ octalCode := path[(i + 1):(i + 4)]
+ val, err := strconv.ParseUint(octalCode, 8, 8)
+ if err != nil {
+ return "", fmt.Errorf("Invalid octal code: %v", err)
+ }
+ buf = append(buf, byte(val))
+ i += 4
+ } else {
+ buf = append(buf, path[i])
+ i++
+ }
+ }
+ return string(buf), nil
+}
+
+var changeTypeMap = map[string]ChangeType{
+ "-": Removed,
+ "+": Created,
+ "M": Modified,
+ "R": Renamed,
+}
+var inodeTypeMap = map[string]InodeType{
+ "B": BlockDevice,
+ "C": CharacterDevice,
+ "/": Directory,
+ ">": Door,
+ "|": NamedPipe,
+ "@": SymbolicLink,
+ "P": EventPort,
+ "=": Socket,
+ "F": File,
+}
+
+// matches (+1) or (-1)
+var referenceCountRegex = regexp.MustCompile("\\(([+-]\\d+?)\\)")
+
+func parseReferenceCount(field string) (int, error) {
+ matches := referenceCountRegex.FindStringSubmatch(field)
+ if matches == nil {
+ return 0, fmt.Errorf("Regexp does not match")
+ }
+ return strconv.Atoi(matches[1])
+}
+
+func parseInodeChange(line []string) (*InodeChange, error) {
+ llen := len(line)
+ if llen < 1 {
+ return nil, fmt.Errorf("Empty line passed")
+ }
+
+ changeType := changeTypeMap[line[0]]
+ if changeType == 0 {
+ return nil, fmt.Errorf("Unknown change type '%s'", line[0])
+ }
+
+ switch changeType {
+ case Renamed:
+ if llen != 4 {
+ return nil, fmt.Errorf("Mismatching number of fields: expect 4, got: %d", llen)
+ }
+ case Modified:
+ if llen != 4 && llen != 3 {
+ return nil, fmt.Errorf("Mismatching number of fields: expect 3..4, got: %d", llen)
+ }
+ default:
+ if llen != 3 {
+ return nil, fmt.Errorf("Mismatching number of fields: expect 3, got: %d", llen)
+ }
+ }
+
+ inodeType := inodeTypeMap[line[1]]
+ if inodeType == 0 {
+ return nil, fmt.Errorf("Unknown inode type '%s'", line[1])
+ }
+
+ path, err := unescapeFilepath(line[2])
+ if err != nil {
+ return nil, fmt.Errorf("Failed to parse filename: %v", err)
+ }
+
+ var newPath string
+ var referenceCount int
+ switch changeType {
+ case Renamed:
+ newPath, err = unescapeFilepath(line[3])
+ if err != nil {
+ return nil, fmt.Errorf("Failed to parse filename: %v", err)
+ }
+ case Modified:
+ if llen == 4 {
+ referenceCount, err = parseReferenceCount(line[3])
+ if err != nil {
+ return nil, fmt.Errorf("Failed to parse reference count: %v", err)
+ }
+ }
+ default:
+ newPath = ""
+ }
+
+ return &InodeChange{
+ Change: changeType,
+ Type: inodeType,
+ Path: path,
+ NewPath: newPath,
+ ReferenceCountChange: referenceCount,
+ }, nil
+}
+
+// example input
+//M / /testpool/bar/
+//+ F /testpool/bar/hello.txt
+//M / /testpool/bar/hello.txt (+1)
+//M / /testpool/bar/hello-hardlink
+func parseInodeChanges(lines [][]string) ([]*InodeChange, error) {
+ changes := make([]*InodeChange, len(lines))
+
+ for i, line := range lines {
+ c, err := parseInodeChange(line)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to parse line %d of zfs diff: %v, got: '%s'", i, err, line)
+ }
+ changes[i] = c
+ }
+ return changes, nil
+}
+
+func listByType(t, filter string) ([]*Dataset, error) {
+ args := []string{"list", "-rHp", "-t", t, "-o", dsPropListOptions}
+
+ if filter != "" {
+ args = append(args, filter)
+ }
+ out, err := zfs(args...)
+ if err != nil {
+ return nil, err
+ }
+
+ var datasets []*Dataset
+
+ name := ""
+ var ds *Dataset
+ for _, line := range out {
+ if name != line[0] {
+ name = line[0]
+ ds = &Dataset{Name: name}
+ datasets = append(datasets, ds)
+ }
+ if err := ds.parseLine(line); err != nil {
+ return nil, err
+ }
+ }
+
+ return datasets, nil
+}
+
+func propsSlice(properties map[string]string) []string {
+ args := make([]string, 0, len(properties)*3)
+ for k, v := range properties {
+ args = append(args, "-o")
+ args = append(args, fmt.Sprintf("%s=%s", k, v))
+ }
+ return args
+}
+
+func (z *Zpool) parseLine(line []string) error {
+ prop := line[1]
+ val := line[2]
+
+ var err error
+
+ switch prop {
+ case "name":
+ setString(&z.Name, val)
+ case "health":
+ setString(&z.Health, val)
+ case "allocated":
+ err = setUint(&z.Allocated, val)
+ case "size":
+ err = setUint(&z.Size, val)
+ case "free":
+ err = setUint(&z.Free, val)
+ case "fragmentation":
+ // Trim trailing "%" before parsing uint
+ err = setUint(&z.Fragmentation, val[:len(val)-1])
+ case "readonly":
+ z.ReadOnly = val == "on"
+ case "freeing":
+ err = setUint(&z.Freeing, val)
+ case "leaked":
+ err = setUint(&z.Leaked, val)
+ case "dedupratio":
+ // Trim trailing "x" before parsing float64
+ z.DedupRatio, err = strconv.ParseFloat(val[:len(val)-1], 64)
+ }
+ return err
+}
diff --git a/vendor/github.com/mistifyio/go-zfs/utils_notsolaris.go b/vendor/github.com/mistifyio/go-zfs/utils_notsolaris.go
new file mode 100644
index 0000000..b2b0cd9
--- /dev/null
+++ b/vendor/github.com/mistifyio/go-zfs/utils_notsolaris.go
@@ -0,0 +1,17 @@
+// +build !solaris
+
+package zfs
+
+import (
+ "strings"
+)
+
+// List of ZFS properties to retrieve from zfs list command on a non-Solaris platform
+var dsPropList = []string{"name", "origin", "used", "available", "mountpoint", "compression", "type", "volsize", "quota", "written", "logicalused", "usedbydataset"}
+
+var dsPropListOptions = strings.Join(dsPropList, ",")
+
+// List of Zpool properties to retrieve from zpool list command on a non-Solaris platform
+var zpoolPropList = []string{"name", "health", "allocated", "size", "free", "readonly", "dedupratio", "fragmentation", "freeing", "leaked"}
+var zpoolPropListOptions = strings.Join(zpoolPropList, ",")
+var zpoolArgs = []string{"get", "-p", zpoolPropListOptions}
diff --git a/vendor/github.com/mistifyio/go-zfs/utils_solaris.go b/vendor/github.com/mistifyio/go-zfs/utils_solaris.go
new file mode 100644
index 0000000..4b0a9e9
--- /dev/null
+++ b/vendor/github.com/mistifyio/go-zfs/utils_solaris.go
@@ -0,0 +1,17 @@
+// +build solaris
+
+package zfs
+
+import (
+ "strings"
+)
+
+// List of ZFS properties to retrieve from zfs list command on a Solaris platform
+var dsPropList = []string{"name", "origin", "used", "available", "mountpoint", "compression", "type", "volsize", "quota"}
+
+var dsPropListOptions = strings.Join(dsPropList, ",")
+
+// List of Zpool properties to retrieve from zpool list command on a non-Solaris platform
+var zpoolPropList = []string{"name", "health", "allocated", "size", "free", "readonly", "dedupratio"}
+var zpoolPropListOptions = strings.Join(zpoolPropList, ",")
+var zpoolArgs = []string{"get", "-p", zpoolPropListOptions}
diff --git a/vendor/github.com/mistifyio/go-zfs/zfs.go b/vendor/github.com/mistifyio/go-zfs/zfs.go
new file mode 100644
index 0000000..615337d
--- /dev/null
+++ b/vendor/github.com/mistifyio/go-zfs/zfs.go
@@ -0,0 +1,451 @@
+// Package zfs provides wrappers around the ZFS command line tools.
+package zfs
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "strconv"
+ "strings"
+)
+
+// ZFS dataset types, which can indicate if a dataset is a filesystem,
+// snapshot, or volume.
+const (
+ DatasetFilesystem = "filesystem"
+ DatasetSnapshot = "snapshot"
+ DatasetVolume = "volume"
+)
+
+// Dataset is a ZFS dataset. A dataset could be a clone, filesystem, snapshot,
+// or volume. The Type struct member can be used to determine a dataset's type.
+//
+// The field definitions can be found in the ZFS manual:
+// http://www.freebsd.org/cgi/man.cgi?zfs(8).
+type Dataset struct {
+ Name string
+ Origin string
+ Used uint64
+ Avail uint64
+ Mountpoint string
+ Compression string
+ Type string
+ Written uint64
+ Volsize uint64
+ Logicalused uint64
+ Usedbydataset uint64
+ Quota uint64
+}
+
+// InodeType is the type of inode as reported by Diff
+type InodeType int
+
+// Types of Inodes
+const (
+ _ = iota // 0 == unknown type
+ BlockDevice InodeType = iota
+ CharacterDevice
+ Directory
+ Door
+ NamedPipe
+ SymbolicLink
+ EventPort
+ Socket
+ File
+)
+
+// ChangeType is the type of inode change as reported by Diff
+type ChangeType int
+
+// Types of Changes
+const (
+ _ = iota // 0 == unknown type
+ Removed ChangeType = iota
+ Created
+ Modified
+ Renamed
+)
+
+// DestroyFlag is the options flag passed to Destroy
+type DestroyFlag int
+
+// Valid destroy options
+const (
+ DestroyDefault DestroyFlag = 1 << iota
+ DestroyRecursive = 1 << iota
+ DestroyRecursiveClones = 1 << iota
+ DestroyDeferDeletion = 1 << iota
+ DestroyForceUmount = 1 << iota
+)
+
+// InodeChange represents a change as reported by Diff
+type InodeChange struct {
+ Change ChangeType
+ Type InodeType
+ Path string
+ NewPath string
+ ReferenceCountChange int
+}
+
+// Logger can be used to log commands/actions
+type Logger interface {
+ Log(cmd []string)
+}
+
+type defaultLogger struct{}
+
+func (*defaultLogger) Log(cmd []string) {
+ return
+}
+
+var logger Logger = &defaultLogger{}
+
+// SetLogger set a log handler to log all commands including arguments before
+// they are executed
+func SetLogger(l Logger) {
+ if l != nil {
+ logger = l
+ }
+}
+
+// zfs is a helper function to wrap typical calls to zfs.
+func zfs(arg ...string) ([][]string, error) {
+ c := command{Command: "zfs"}
+ return c.Run(arg...)
+}
+
+// Datasets returns a slice of ZFS datasets, regardless of type.
+// A filter argument may be passed to select a dataset with the matching name,
+// or empty string ("") may be used to select all datasets.
+func Datasets(filter string) ([]*Dataset, error) {
+ return listByType("all", filter)
+}
+
+// Snapshots returns a slice of ZFS snapshots.
+// A filter argument may be passed to select a snapshot with the matching name,
+// or empty string ("") may be used to select all snapshots.
+func Snapshots(filter string) ([]*Dataset, error) {
+ return listByType(DatasetSnapshot, filter)
+}
+
+// Filesystems returns a slice of ZFS filesystems.
+// A filter argument may be passed to select a filesystem with the matching name,
+// or empty string ("") may be used to select all filesystems.
+func Filesystems(filter string) ([]*Dataset, error) {
+ return listByType(DatasetFilesystem, filter)
+}
+
+// Volumes returns a slice of ZFS volumes.
+// A filter argument may be passed to select a volume with the matching name,
+// or empty string ("") may be used to select all volumes.
+func Volumes(filter string) ([]*Dataset, error) {
+ return listByType(DatasetVolume, filter)
+}
+
+// GetDataset retrieves a single ZFS dataset by name. This dataset could be
+// any valid ZFS dataset type, such as a clone, filesystem, snapshot, or volume.
+func GetDataset(name string) (*Dataset, error) {
+ out, err := zfs("list", "-Hp", "-o", dsPropListOptions, name)
+ if err != nil {
+ return nil, err
+ }
+
+ ds := &Dataset{Name: name}
+ for _, line := range out {
+ if err := ds.parseLine(line); err != nil {
+ return nil, err
+ }
+ }
+
+ return ds, nil
+}
+
+// Clone clones a ZFS snapshot and returns a clone dataset.
+// An error will be returned if the input dataset is not of snapshot type.
+func (d *Dataset) Clone(dest string, properties map[string]string) (*Dataset, error) {
+ if d.Type != DatasetSnapshot {
+ return nil, errors.New("can only clone snapshots")
+ }
+ args := make([]string, 2, 4)
+ args[0] = "clone"
+ args[1] = "-p"
+ if properties != nil {
+ args = append(args, propsSlice(properties)...)
+ }
+ args = append(args, []string{d.Name, dest}...)
+ _, err := zfs(args...)
+ if err != nil {
+ return nil, err
+ }
+ return GetDataset(dest)
+}
+
+// Unmount unmounts currently mounted ZFS file systems.
+func (d *Dataset) Unmount(force bool) (*Dataset, error) {
+ if d.Type == DatasetSnapshot {
+ return nil, errors.New("cannot unmount snapshots")
+ }
+ args := make([]string, 1, 3)
+ args[0] = "umount"
+ if force {
+ args = append(args, "-f")
+ }
+ args = append(args, d.Name)
+ _, err := zfs(args...)
+ if err != nil {
+ return nil, err
+ }
+ return GetDataset(d.Name)
+}
+
+// Mount mounts ZFS file systems.
+func (d *Dataset) Mount(overlay bool, options []string) (*Dataset, error) {
+ if d.Type == DatasetSnapshot {
+ return nil, errors.New("cannot mount snapshots")
+ }
+ args := make([]string, 1, 5)
+ args[0] = "mount"
+ if overlay {
+ args = append(args, "-O")
+ }
+ if options != nil {
+ args = append(args, "-o")
+ args = append(args, strings.Join(options, ","))
+ }
+ args = append(args, d.Name)
+ _, err := zfs(args...)
+ if err != nil {
+ return nil, err
+ }
+ return GetDataset(d.Name)
+}
+
+// ReceiveSnapshot receives a ZFS stream from the input io.Reader, creates a
+// new snapshot with the specified name, and streams the input data into the
+// newly-created snapshot.
+func ReceiveSnapshot(input io.Reader, name string) (*Dataset, error) {
+ c := command{Command: "zfs", Stdin: input}
+ _, err := c.Run("receive", name)
+ if err != nil {
+ return nil, err
+ }
+ return GetDataset(name)
+}
+
+// SendSnapshot sends a ZFS stream of a snapshot to the input io.Writer.
+// An error will be returned if the input dataset is not of snapshot type.
+func (d *Dataset) SendSnapshot(output io.Writer) error {
+ if d.Type != DatasetSnapshot {
+ return errors.New("can only send snapshots")
+ }
+
+ c := command{Command: "zfs", Stdout: output}
+ _, err := c.Run("send", d.Name)
+ return err
+}
+
+// CreateVolume creates a new ZFS volume with the specified name, size, and
+// properties.
+// A full list of available ZFS properties may be found here:
+// https://www.freebsd.org/cgi/man.cgi?zfs(8).
+func CreateVolume(name string, size uint64, properties map[string]string) (*Dataset, error) {
+ args := make([]string, 4, 5)
+ args[0] = "create"
+ args[1] = "-p"
+ args[2] = "-V"
+ args[3] = strconv.FormatUint(size, 10)
+ if properties != nil {
+ args = append(args, propsSlice(properties)...)
+ }
+ args = append(args, name)
+ _, err := zfs(args...)
+ if err != nil {
+ return nil, err
+ }
+ return GetDataset(name)
+}
+
+// Destroy destroys a ZFS dataset. If the destroy bit flag is set, any
+// descendents of the dataset will be recursively destroyed, including snapshots.
+// If the deferred bit flag is set, the snapshot is marked for deferred
+// deletion.
+func (d *Dataset) Destroy(flags DestroyFlag) error {
+ args := make([]string, 1, 3)
+ args[0] = "destroy"
+ if flags&DestroyRecursive != 0 {
+ args = append(args, "-r")
+ }
+
+ if flags&DestroyRecursiveClones != 0 {
+ args = append(args, "-R")
+ }
+
+ if flags&DestroyDeferDeletion != 0 {
+ args = append(args, "-d")
+ }
+
+ if flags&DestroyForceUmount != 0 {
+ args = append(args, "-f")
+ }
+
+ args = append(args, d.Name)
+ _, err := zfs(args...)
+ return err
+}
+
+// SetProperty sets a ZFS property on the receiving dataset.
+// A full list of available ZFS properties may be found here:
+// https://www.freebsd.org/cgi/man.cgi?zfs(8).
+func (d *Dataset) SetProperty(key, val string) error {
+ prop := strings.Join([]string{key, val}, "=")
+ _, err := zfs("set", prop, d.Name)
+ return err
+}
+
+// GetProperty returns the current value of a ZFS property from the
+// receiving dataset.
+// A full list of available ZFS properties may be found here:
+// https://www.freebsd.org/cgi/man.cgi?zfs(8).
+func (d *Dataset) GetProperty(key string) (string, error) {
+ out, err := zfs("get", key, d.Name)
+ if err != nil {
+ return "", err
+ }
+
+ return out[0][2], nil
+}
+
+// Rename renames a dataset.
+func (d *Dataset) Rename(name string, createParent bool, recursiveRenameSnapshots bool) (*Dataset, error) {
+ args := make([]string, 3, 5)
+ args[0] = "rename"
+ args[1] = d.Name
+ args[2] = name
+ if createParent {
+ args = append(args, "-p")
+ }
+ if recursiveRenameSnapshots {
+ args = append(args, "-r")
+ }
+ _, err := zfs(args...)
+ if err != nil {
+ return d, err
+ }
+
+ return GetDataset(name)
+}
+
+// Snapshots returns a slice of all ZFS snapshots of a given dataset.
+func (d *Dataset) Snapshots() ([]*Dataset, error) {
+ return Snapshots(d.Name)
+}
+
+// CreateFilesystem creates a new ZFS filesystem with the specified name and
+// properties.
+// A full list of available ZFS properties may be found here:
+// https://www.freebsd.org/cgi/man.cgi?zfs(8).
+func CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {
+ args := make([]string, 1, 4)
+ args[0] = "create"
+
+ if properties != nil {
+ args = append(args, propsSlice(properties)...)
+ }
+
+ args = append(args, name)
+ _, err := zfs(args...)
+ if err != nil {
+ return nil, err
+ }
+ return GetDataset(name)
+}
+
+// Snapshot creates a new ZFS snapshot of the receiving dataset, using the
+// specified name. Optionally, the snapshot can be taken recursively, creating
+// snapshots of all descendent filesystems in a single, atomic operation.
+func (d *Dataset) Snapshot(name string, recursive bool) (*Dataset, error) {
+ args := make([]string, 1, 4)
+ args[0] = "snapshot"
+ if recursive {
+ args = append(args, "-r")
+ }
+ snapName := fmt.Sprintf("%s@%s", d.Name, name)
+ args = append(args, snapName)
+ _, err := zfs(args...)
+ if err != nil {
+ return nil, err
+ }
+ return GetDataset(snapName)
+}
+
+// Rollback rolls back the receiving ZFS dataset to a previous snapshot.
+// Optionally, intermediate snapshots can be destroyed. A ZFS snapshot
+// rollback cannot be completed without this option, if more recent
+// snapshots exist.
+// An error will be returned if the input dataset is not of snapshot type.
+func (d *Dataset) Rollback(destroyMoreRecent bool) error {
+ if d.Type != DatasetSnapshot {
+ return errors.New("can only rollback snapshots")
+ }
+
+ args := make([]string, 1, 3)
+ args[0] = "rollback"
+ if destroyMoreRecent {
+ args = append(args, "-r")
+ }
+ args = append(args, d.Name)
+
+ _, err := zfs(args...)
+ return err
+}
+
+// Children returns a slice of children of the receiving ZFS dataset.
+// A recursion depth may be specified, or a depth of 0 allows unlimited
+// recursion.
+func (d *Dataset) Children(depth uint64) ([]*Dataset, error) {
+ args := []string{"list"}
+ if depth > 0 {
+ args = append(args, "-d")
+ args = append(args, strconv.FormatUint(depth, 10))
+ } else {
+ args = append(args, "-r")
+ }
+ args = append(args, "-t", "all", "-Hp", "-o", dsPropListOptions)
+ args = append(args, d.Name)
+
+ out, err := zfs(args...)
+ if err != nil {
+ return nil, err
+ }
+
+ var datasets []*Dataset
+ name := ""
+ var ds *Dataset
+ for _, line := range out {
+ if name != line[0] {
+ name = line[0]
+ ds = &Dataset{Name: name}
+ datasets = append(datasets, ds)
+ }
+ if err := ds.parseLine(line); err != nil {
+ return nil, err
+ }
+ }
+ return datasets[1:], nil
+}
+
+// Diff returns changes between a snapshot and the given ZFS dataset.
+// The snapshot name must include the filesystem part as it is possible to
+// compare clones with their origin snapshots.
+func (d *Dataset) Diff(snapshot string) ([]*InodeChange, error) {
+ args := []string{"diff", "-FH", snapshot, d.Name}[:]
+ out, err := zfs(args...)
+ if err != nil {
+ return nil, err
+ }
+ inodeChanges, err := parseInodeChanges(out)
+ if err != nil {
+ return nil, err
+ }
+ return inodeChanges, nil
+}
diff --git a/vendor/github.com/mistifyio/go-zfs/zpool.go b/vendor/github.com/mistifyio/go-zfs/zpool.go
new file mode 100644
index 0000000..d8db945
--- /dev/null
+++ b/vendor/github.com/mistifyio/go-zfs/zpool.go
@@ -0,0 +1,112 @@
+package zfs
+
+// ZFS zpool states, which can indicate if a pool is online, offline,
+// degraded, etc. More information regarding zpool states can be found here:
+// https://docs.oracle.com/cd/E19253-01/819-5461/gamno/index.html.
+const (
+ ZpoolOnline = "ONLINE"
+ ZpoolDegraded = "DEGRADED"
+ ZpoolFaulted = "FAULTED"
+ ZpoolOffline = "OFFLINE"
+ ZpoolUnavail = "UNAVAIL"
+ ZpoolRemoved = "REMOVED"
+)
+
+// Zpool is a ZFS zpool. A pool is a top-level structure in ZFS, and can
+// contain many descendent datasets.
+type Zpool struct {
+ Name string
+ Health string
+ Allocated uint64
+ Size uint64
+ Free uint64
+ Fragmentation uint64
+ ReadOnly bool
+ Freeing uint64
+ Leaked uint64
+ DedupRatio float64
+}
+
+// zpool is a helper function to wrap typical calls to zpool.
+func zpool(arg ...string) ([][]string, error) {
+ c := command{Command: "zpool"}
+ return c.Run(arg...)
+}
+
+// GetZpool retrieves a single ZFS zpool by name.
+func GetZpool(name string) (*Zpool, error) {
+ args := zpoolArgs
+ args = append(args, name)
+ out, err := zpool(args...)
+ if err != nil {
+ return nil, err
+ }
+
+ // there is no -H
+ out = out[1:]
+
+ z := &Zpool{Name: name}
+ for _, line := range out {
+ if err := z.parseLine(line); err != nil {
+ return nil, err
+ }
+ }
+
+ return z, nil
+}
+
+// Datasets returns a slice of all ZFS datasets in a zpool.
+func (z *Zpool) Datasets() ([]*Dataset, error) {
+ return Datasets(z.Name)
+}
+
+// Snapshots returns a slice of all ZFS snapshots in a zpool.
+func (z *Zpool) Snapshots() ([]*Dataset, error) {
+ return Snapshots(z.Name)
+}
+
+// CreateZpool creates a new ZFS zpool with the specified name, properties,
+// and optional arguments.
+// A full list of available ZFS properties and command-line arguments may be
+// found here: https://www.freebsd.org/cgi/man.cgi?zfs(8).
+func CreateZpool(name string, properties map[string]string, args ...string) (*Zpool, error) {
+ cli := make([]string, 1, 4)
+ cli[0] = "create"
+ if properties != nil {
+ cli = append(cli, propsSlice(properties)...)
+ }
+ cli = append(cli, name)
+ cli = append(cli, args...)
+ _, err := zpool(cli...)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Zpool{Name: name}, nil
+}
+
+// Destroy destroys a ZFS zpool by name.
+func (z *Zpool) Destroy() error {
+ _, err := zpool("destroy", z.Name)
+ return err
+}
+
+// ListZpools list all ZFS zpools accessible on the current system.
+func ListZpools() ([]*Zpool, error) {
+ args := []string{"list", "-Ho", "name"}
+ out, err := zpool(args...)
+ if err != nil {
+ return nil, err
+ }
+
+ var pools []*Zpool
+
+ for _, line := range out {
+ z, err := GetZpool(line[0])
+ if err != nil {
+ return nil, err
+ }
+ pools = append(pools, z)
+ }
+ return pools, nil
+}
diff --git a/vendor/github.com/mitchellh/mapstructure/LICENSE b/vendor/github.com/mitchellh/mapstructure/LICENSE
new file mode 100644
index 0000000..f9c841a
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Mitchell Hashimoto
+
+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/mitchellh/mapstructure/README.md b/vendor/github.com/mitchellh/mapstructure/README.md
new file mode 100644
index 0000000..659d688
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/README.md
@@ -0,0 +1,46 @@
+# mapstructure
+
+mapstructure is a Go library for decoding generic map values to structures
+and vice versa, while providing helpful error handling.
+
+This library is most useful when decoding values from some data stream (JSON,
+Gob, etc.) where you don't _quite_ know the structure of the underlying data
+until you read a part of it. You can therefore read a `map[string]interface{}`
+and use this library to decode it into the proper underlying native Go
+structure.
+
+## Installation
+
+Standard `go get`:
+
+```
+$ go get github.com/mitchellh/mapstructure
+```
+
+## Usage & Example
+
+For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/mapstructure).
+
+The `Decode` function has examples associated with it there.
+
+## But Why?!
+
+Go offers fantastic standard libraries for decoding formats such as JSON.
+The standard method is to have a struct pre-created, and populate that struct
+from the bytes of the encoded format. This is great, but the problem is if
+you have configuration or an encoding that changes slightly depending on
+specific fields. For example, consider this JSON:
+
+```json
+{
+ "type": "person",
+ "name": "Mitchell"
+}
+```
+
+Perhaps we can't populate a specific structure without first reading
+the "type" field from the JSON. We could always do two passes over the
+decoding of the JSON (reading the "type" first, and the rest later).
+However, it is much simpler to just decode this into a `map[string]interface{}`
+structure, read the "type" key, then use something like this library
+to decode it into the proper structure.
diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
new file mode 100644
index 0000000..115ae67
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
@@ -0,0 +1,154 @@
+package mapstructure
+
+import (
+ "errors"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns
+// it into the proper DecodeHookFunc type, such as DecodeHookFuncType.
+func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc {
+ // Create variables here so we can reference them with the reflect pkg
+ var f1 DecodeHookFuncType
+ var f2 DecodeHookFuncKind
+
+ // Fill in the variables into this interface and the rest is done
+ // automatically using the reflect package.
+ potential := []interface{}{f1, f2}
+
+ v := reflect.ValueOf(h)
+ vt := v.Type()
+ for _, raw := range potential {
+ pt := reflect.ValueOf(raw).Type()
+ if vt.ConvertibleTo(pt) {
+ return v.Convert(pt).Interface()
+ }
+ }
+
+ return nil
+}
+
+// DecodeHookExec executes the given decode hook. This should be used
+// since it'll naturally degrade to the older backwards compatible DecodeHookFunc
+// that took reflect.Kind instead of reflect.Type.
+func DecodeHookExec(
+ raw DecodeHookFunc,
+ from reflect.Type, to reflect.Type,
+ data interface{}) (interface{}, error) {
+ // Build our arguments that reflect expects
+ argVals := make([]reflect.Value, 3)
+ argVals[0] = reflect.ValueOf(from)
+ argVals[1] = reflect.ValueOf(to)
+ argVals[2] = reflect.ValueOf(data)
+
+ switch f := typedDecodeHook(raw).(type) {
+ case DecodeHookFuncType:
+ return f(from, to, data)
+ case DecodeHookFuncKind:
+ return f(from.Kind(), to.Kind(), data)
+ default:
+ return nil, errors.New("invalid decode hook signature")
+ }
+}
+
+// ComposeDecodeHookFunc creates a single DecodeHookFunc that
+// automatically composes multiple DecodeHookFuncs.
+//
+// The composed funcs are called in order, with the result of the
+// previous transformation.
+func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc {
+ return func(
+ f reflect.Type,
+ t reflect.Type,
+ data interface{}) (interface{}, error) {
+ var err error
+ for _, f1 := range fs {
+ data, err = DecodeHookExec(f1, f, t, data)
+ if err != nil {
+ return nil, err
+ }
+
+ // Modify the from kind to be correct with the new data
+ f = nil
+ if val := reflect.ValueOf(data); val.IsValid() {
+ f = val.Type()
+ }
+ }
+
+ return data, nil
+ }
+}
+
+// StringToSliceHookFunc returns a DecodeHookFunc that converts
+// string to []string by splitting on the given sep.
+func StringToSliceHookFunc(sep string) DecodeHookFunc {
+ return func(
+ f reflect.Kind,
+ t reflect.Kind,
+ data interface{}) (interface{}, error) {
+ if f != reflect.String || t != reflect.Slice {
+ return data, nil
+ }
+
+ raw := data.(string)
+ if raw == "" {
+ return []string{}, nil
+ }
+
+ return strings.Split(raw, sep), nil
+ }
+}
+
+// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts
+// strings to time.Duration.
+func StringToTimeDurationHookFunc() DecodeHookFunc {
+ return func(
+ f reflect.Type,
+ t reflect.Type,
+ data interface{}) (interface{}, error) {
+ if f.Kind() != reflect.String {
+ return data, nil
+ }
+ if t != reflect.TypeOf(time.Duration(5)) {
+ return data, nil
+ }
+
+ // Convert it by parsing
+ return time.ParseDuration(data.(string))
+ }
+}
+
+func WeaklyTypedHook(
+ f reflect.Kind,
+ t reflect.Kind,
+ data interface{}) (interface{}, error) {
+ dataVal := reflect.ValueOf(data)
+ switch t {
+ case reflect.String:
+ switch f {
+ case reflect.Bool:
+ if dataVal.Bool() {
+ return "1", nil
+ } else {
+ return "0", nil
+ }
+ case reflect.Float32:
+ return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil
+ case reflect.Int:
+ return strconv.FormatInt(dataVal.Int(), 10), nil
+ case reflect.Slice:
+ dataType := dataVal.Type()
+ elemKind := dataType.Elem().Kind()
+ if elemKind == reflect.Uint8 {
+ return string(dataVal.Interface().([]uint8)), nil
+ }
+ case reflect.Uint:
+ return strconv.FormatUint(dataVal.Uint(), 10), nil
+ }
+ }
+
+ return data, nil
+}
diff --git a/vendor/github.com/mitchellh/mapstructure/error.go b/vendor/github.com/mitchellh/mapstructure/error.go
new file mode 100644
index 0000000..47a99e5
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/error.go
@@ -0,0 +1,50 @@
+package mapstructure
+
+import (
+ "errors"
+ "fmt"
+ "sort"
+ "strings"
+)
+
+// Error implements the error interface and can represents multiple
+// errors that occur in the course of a single decode.
+type Error struct {
+ Errors []string
+}
+
+func (e *Error) Error() string {
+ points := make([]string, len(e.Errors))
+ for i, err := range e.Errors {
+ points[i] = fmt.Sprintf("* %s", err)
+ }
+
+ sort.Strings(points)
+ return fmt.Sprintf(
+ "%d error(s) decoding:\n\n%s",
+ len(e.Errors), strings.Join(points, "\n"))
+}
+
+// WrappedErrors implements the errwrap.Wrapper interface to make this
+// return value more useful with the errwrap and go-multierror libraries.
+func (e *Error) WrappedErrors() []error {
+ if e == nil {
+ return nil
+ }
+
+ result := make([]error, len(e.Errors))
+ for i, e := range e.Errors {
+ result[i] = errors.New(e)
+ }
+
+ return result
+}
+
+func appendErrors(errors []string, err error) []string {
+ switch e := err.(type) {
+ case *Error:
+ return append(errors, e.Errors...)
+ default:
+ return append(errors, e.Error())
+ }
+}
diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go
new file mode 100644
index 0000000..b0ab89b
--- /dev/null
+++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go
@@ -0,0 +1,782 @@
+// The mapstructure package exposes functionality to convert an
+// abitrary 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
+// maps and so on into the proper structures in the native Go struct.
+// See the examples to see what the decoder is capable of.
+package mapstructure
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+// DecodeHookFunc is the callback function that can be used for
+// data transformations. See "DecodeHook" in the DecoderConfig
+// struct.
+//
+// The type should be DecodeHookFuncType or DecodeHookFuncKind.
+// Either is accepted. Types are a superset of Kinds (Types can return
+// Kinds) and are generally a richer thing to use, but Kinds are simpler
+// if you only need those.
+//
+// The reason DecodeHookFunc is multi-typed is for backwards compatibility:
+// we started with Kinds and then realized Types were the better solution,
+// but have a promise to not break backwards compat so we now support
+// both.
+type DecodeHookFunc interface{}
+
+type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error)
+type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error)
+
+// DecoderConfig is the configuration that is used to create a new decoder
+// and allows customization of various aspects of decoding.
+type DecoderConfig struct {
+ // DecodeHook, if set, will be called before any decoding and any
+ // type conversion (if WeaklyTypedInput is on). This lets you modify
+ // the values before they're set down onto the resulting struct.
+ //
+ // If an error is returned, the entire decode will fail with that
+ // error.
+ DecodeHook DecodeHookFunc
+
+ // If ErrorUnused is true, then it is an error for there to exist
+ // keys in the original map that were unused in the decoding process
+ // (extra keys).
+ ErrorUnused bool
+
+ // ZeroFields, if set to true, will zero fields before writing them.
+ // For example, a map will be emptied before decoded values are put in
+ // it. If this is false, a map will be merged.
+ ZeroFields bool
+
+ // If WeaklyTypedInput is true, the decoder will make the following
+ // "weak" conversions:
+ //
+ // - bools to string (true = "1", false = "0")
+ // - numbers to string (base 10)
+ // - bools to int/uint (true = 1, false = 0)
+ // - strings to int/uint (base implied by prefix)
+ // - int to bool (true if value != 0)
+ // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F,
+ // FALSE, false, False. Anything else is an error)
+ // - empty array = empty map and vice versa
+ // - negative numbers to overflowed uint values (base 10)
+ // - slice of maps to a merged map
+ //
+ WeaklyTypedInput bool
+
+ // Metadata is the struct that will contain extra metadata about
+ // the decoding. If this is nil, then no metadata will be tracked.
+ Metadata *Metadata
+
+ // Result is a pointer to the struct that will contain the decoded
+ // value.
+ Result interface{}
+
+ // The tag name that mapstructure reads for field names. This
+ // defaults to "mapstructure"
+ TagName string
+}
+
+// A Decoder takes a raw interface value and turns it into structured
+// data, keeping track of rich error information along the way in case
+// anything goes wrong. Unlike the basic top-level Decode method, you can
+// more finely control how the Decoder behaves using the DecoderConfig
+// structure. The top-level Decode method is just a convenience that sets
+// up the most basic Decoder.
+type Decoder struct {
+ config *DecoderConfig
+}
+
+// Metadata contains information about decoding a structure that
+// is tedious or difficult to get otherwise.
+type Metadata struct {
+ // Keys are the keys of the structure which were successfully decoded
+ Keys []string
+
+ // Unused is a slice of keys that were found in the raw value but
+ // weren't decoded since there was no matching field in the result interface
+ Unused []string
+}
+
+// Decode takes a map and uses reflection to convert it into the
+// given Go native structure. val must be a pointer to a struct.
+func Decode(m interface{}, rawVal interface{}) error {
+ config := &DecoderConfig{
+ Metadata: nil,
+ Result: rawVal,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ return err
+ }
+
+ return decoder.Decode(m)
+}
+
+// WeakDecode is the same as Decode but is shorthand to enable
+// WeaklyTypedInput. See DecoderConfig for more info.
+func WeakDecode(input, output interface{}) error {
+ config := &DecoderConfig{
+ Metadata: nil,
+ Result: output,
+ WeaklyTypedInput: true,
+ }
+
+ decoder, err := NewDecoder(config)
+ if err != nil {
+ return err
+ }
+
+ return decoder.Decode(input)
+}
+
+// NewDecoder returns a new decoder for the given configuration. Once
+// a decoder has been returned, the same configuration must not be used
+// again.
+func NewDecoder(config *DecoderConfig) (*Decoder, error) {
+ val := reflect.ValueOf(config.Result)
+ if val.Kind() != reflect.Ptr {
+ return nil, errors.New("result must be a pointer")
+ }
+
+ val = val.Elem()
+ if !val.CanAddr() {
+ return nil, errors.New("result must be addressable (a pointer)")
+ }
+
+ if config.Metadata != nil {
+ if config.Metadata.Keys == nil {
+ config.Metadata.Keys = make([]string, 0)
+ }
+
+ if config.Metadata.Unused == nil {
+ config.Metadata.Unused = make([]string, 0)
+ }
+ }
+
+ if config.TagName == "" {
+ config.TagName = "mapstructure"
+ }
+
+ result := &Decoder{
+ config: config,
+ }
+
+ return result, nil
+}
+
+// Decode decodes the given raw interface to the target pointer specified
+// by the configuration.
+func (d *Decoder) Decode(raw interface{}) error {
+ return d.decode("", raw, reflect.ValueOf(d.config.Result).Elem())
+}
+
+// Decodes an unknown data type into a specific reflection value.
+func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error {
+ if data == nil {
+ // If the data is nil, then we don't set anything.
+ return nil
+ }
+
+ dataVal := reflect.ValueOf(data)
+ if !dataVal.IsValid() {
+ // If the data value is invalid, then we just set the value
+ // to be the zero value.
+ val.Set(reflect.Zero(val.Type()))
+ return nil
+ }
+
+ if d.config.DecodeHook != nil {
+ // We have a DecodeHook, so let's pre-process the data.
+ var err error
+ data, err = DecodeHookExec(
+ d.config.DecodeHook,
+ dataVal.Type(), val.Type(), data)
+ if err != nil {
+ return err
+ }
+ }
+
+ var err error
+ dataKind := getKind(val)
+ switch dataKind {
+ case reflect.Bool:
+ err = d.decodeBool(name, data, val)
+ case reflect.Interface:
+ err = d.decodeBasic(name, data, val)
+ case reflect.String:
+ err = d.decodeString(name, data, val)
+ case reflect.Int:
+ err = d.decodeInt(name, data, val)
+ case reflect.Uint:
+ err = d.decodeUint(name, data, val)
+ case reflect.Float32:
+ err = d.decodeFloat(name, data, val)
+ case reflect.Struct:
+ err = d.decodeStruct(name, data, val)
+ case reflect.Map:
+ err = d.decodeMap(name, data, val)
+ case reflect.Ptr:
+ err = d.decodePtr(name, data, val)
+ case reflect.Slice:
+ err = d.decodeSlice(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)
+ }
+
+ // If we reached here, then we successfully decoded SOMETHING, so
+ // mark the key as used if we're tracking metadata.
+ if d.config.Metadata != nil && name != "" {
+ d.config.Metadata.Keys = append(d.config.Metadata.Keys, name)
+ }
+
+ return err
+}
+
+// This decodes a basic type (bool, int, string, etc.) and sets the
+// value to "data" of that type.
+func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ if !dataVal.IsValid() {
+ dataVal = reflect.Zero(val.Type())
+ }
+
+ dataValType := dataVal.Type()
+ if !dataValType.AssignableTo(val.Type()) {
+ return fmt.Errorf(
+ "'%s' expected type '%s', got '%s'",
+ name, val.Type(), dataValType)
+ }
+
+ val.Set(dataVal)
+ return nil
+}
+
+func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ dataKind := getKind(dataVal)
+
+ converted := true
+ switch {
+ case dataKind == reflect.String:
+ val.SetString(dataVal.String())
+ case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
+ if dataVal.Bool() {
+ val.SetString("1")
+ } else {
+ val.SetString("0")
+ }
+ case dataKind == reflect.Int && d.config.WeaklyTypedInput:
+ val.SetString(strconv.FormatInt(dataVal.Int(), 10))
+ case dataKind == reflect.Uint && d.config.WeaklyTypedInput:
+ val.SetString(strconv.FormatUint(dataVal.Uint(), 10))
+ case dataKind == reflect.Float32 && d.config.WeaklyTypedInput:
+ val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64))
+ case dataKind == reflect.Slice && d.config.WeaklyTypedInput:
+ dataType := dataVal.Type()
+ elemKind := dataType.Elem().Kind()
+ switch {
+ case elemKind == reflect.Uint8:
+ val.SetString(string(dataVal.Interface().([]uint8)))
+ default:
+ converted = false
+ }
+ default:
+ converted = false
+ }
+
+ if !converted {
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ dataKind := getKind(dataVal)
+ dataType := dataVal.Type()
+
+ switch {
+ case dataKind == reflect.Int:
+ val.SetInt(dataVal.Int())
+ case dataKind == reflect.Uint:
+ val.SetInt(int64(dataVal.Uint()))
+ case dataKind == reflect.Float32:
+ val.SetInt(int64(dataVal.Float()))
+ case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
+ if dataVal.Bool() {
+ val.SetInt(1)
+ } else {
+ val.SetInt(0)
+ }
+ case dataKind == reflect.String && d.config.WeaklyTypedInput:
+ i, err := strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
+ if err == nil {
+ val.SetInt(i)
+ } else {
+ return fmt.Errorf("cannot parse '%s' as int: %s", name, err)
+ }
+ case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
+ jn := data.(json.Number)
+ i, err := jn.Int64()
+ if err != nil {
+ return fmt.Errorf(
+ "error decoding json.Number into %s: %s", name, err)
+ }
+ val.SetInt(i)
+ default:
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ dataKind := getKind(dataVal)
+
+ switch {
+ case dataKind == reflect.Int:
+ i := dataVal.Int()
+ if i < 0 && !d.config.WeaklyTypedInput {
+ return fmt.Errorf("cannot parse '%s', %d overflows uint",
+ name, i)
+ }
+ val.SetUint(uint64(i))
+ case dataKind == reflect.Uint:
+ val.SetUint(dataVal.Uint())
+ case dataKind == reflect.Float32:
+ f := dataVal.Float()
+ if f < 0 && !d.config.WeaklyTypedInput {
+ return fmt.Errorf("cannot parse '%s', %f overflows uint",
+ name, f)
+ }
+ val.SetUint(uint64(f))
+ case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
+ if dataVal.Bool() {
+ val.SetUint(1)
+ } else {
+ val.SetUint(0)
+ }
+ case dataKind == reflect.String && d.config.WeaklyTypedInput:
+ i, err := strconv.ParseUint(dataVal.String(), 0, val.Type().Bits())
+ if err == nil {
+ val.SetUint(i)
+ } else {
+ return fmt.Errorf("cannot parse '%s' as uint: %s", name, err)
+ }
+ default:
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ dataKind := getKind(dataVal)
+
+ switch {
+ case dataKind == reflect.Bool:
+ val.SetBool(dataVal.Bool())
+ case dataKind == reflect.Int && d.config.WeaklyTypedInput:
+ val.SetBool(dataVal.Int() != 0)
+ case dataKind == reflect.Uint && d.config.WeaklyTypedInput:
+ val.SetBool(dataVal.Uint() != 0)
+ case dataKind == reflect.Float32 && d.config.WeaklyTypedInput:
+ val.SetBool(dataVal.Float() != 0)
+ case dataKind == reflect.String && d.config.WeaklyTypedInput:
+ b, err := strconv.ParseBool(dataVal.String())
+ if err == nil {
+ val.SetBool(b)
+ } else if dataVal.String() == "" {
+ val.SetBool(false)
+ } else {
+ return fmt.Errorf("cannot parse '%s' as bool: %s", name, err)
+ }
+ default:
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ dataKind := getKind(dataVal)
+ dataType := dataVal.Type()
+
+ switch {
+ case dataKind == reflect.Int:
+ val.SetFloat(float64(dataVal.Int()))
+ case dataKind == reflect.Uint:
+ val.SetFloat(float64(dataVal.Uint()))
+ case dataKind == reflect.Float32:
+ val.SetFloat(float64(dataVal.Float()))
+ case dataKind == reflect.Bool && d.config.WeaklyTypedInput:
+ if dataVal.Bool() {
+ val.SetFloat(1)
+ } else {
+ val.SetFloat(0)
+ }
+ case dataKind == reflect.String && d.config.WeaklyTypedInput:
+ f, err := strconv.ParseFloat(dataVal.String(), val.Type().Bits())
+ if err == nil {
+ val.SetFloat(f)
+ } else {
+ return fmt.Errorf("cannot parse '%s' as float: %s", name, err)
+ }
+ case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number":
+ jn := data.(json.Number)
+ i, err := jn.Float64()
+ if err != nil {
+ return fmt.Errorf(
+ "error decoding json.Number into %s: %s", name, err)
+ }
+ val.SetFloat(i)
+ default:
+ return fmt.Errorf(
+ "'%s' expected type '%s', got unconvertible type '%s'",
+ name, val.Type(), dataVal.Type())
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error {
+ valType := val.Type()
+ valKeyType := valType.Key()
+ valElemType := valType.Elem()
+
+ // By default we overwrite keys in the current map
+ valMap := val
+
+ // If the map is nil or we're purposely zeroing fields, make a new map
+ if valMap.IsNil() || d.config.ZeroFields {
+ // Make a new map to hold our result
+ mapType := reflect.MapOf(valKeyType, valElemType)
+ valMap = reflect.MakeMap(mapType)
+ }
+
+ // Check input type
+ dataVal := reflect.Indirect(reflect.ValueOf(data))
+ if dataVal.Kind() != reflect.Map {
+ // In weak mode, we accept a slice of maps as an input...
+ if d.config.WeaklyTypedInput {
+ switch dataVal.Kind() {
+ case reflect.Array, reflect.Slice:
+ // Special case for BC reasons (covered by tests)
+ if dataVal.Len() == 0 {
+ val.Set(valMap)
+ return nil
+ }
+
+ for i := 0; i < dataVal.Len(); i++ {
+ err := d.decode(
+ fmt.Sprintf("%s[%d]", name, i),
+ dataVal.Index(i).Interface(), val)
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+ }
+ }
+
+ return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
+ }
+
+ // Accumulate errors
+ errors := make([]string, 0)
+
+ for _, k := range dataVal.MapKeys() {
+ fieldName := fmt.Sprintf("%s[%s]", name, k)
+
+ // First decode the key into the proper type
+ currentKey := reflect.Indirect(reflect.New(valKeyType))
+ if err := d.decode(fieldName, k.Interface(), currentKey); err != nil {
+ errors = appendErrors(errors, err)
+ continue
+ }
+
+ // Next decode the data into the proper type
+ v := dataVal.MapIndex(k).Interface()
+ currentVal := reflect.Indirect(reflect.New(valElemType))
+ if err := d.decode(fieldName, v, currentVal); err != nil {
+ errors = appendErrors(errors, err)
+ continue
+ }
+
+ valMap.SetMapIndex(currentKey, currentVal)
+ }
+
+ // Set the built up map to the value
+ val.Set(valMap)
+
+ // If we had errors, return those
+ if len(errors) > 0 {
+ return &Error{errors}
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodePtr(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.
+ valType := val.Type()
+ valElemType := valType.Elem()
+ realVal := reflect.New(valElemType)
+ if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil {
+ return err
+ }
+
+ val.Set(realVal)
+ return nil
+}
+
+func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.Indirect(reflect.ValueOf(data))
+ dataValKind := dataVal.Kind()
+ valType := val.Type()
+ 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)
+ }
+ }
+
+ // 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)
+
+ for i := 0; i < dataVal.Len(); i++ {
+ currentData := dataVal.Index(i).Interface()
+ currentField := valSlice.Index(i)
+
+ fieldName := fmt.Sprintf("%s[%d]", name, i)
+ if err := d.decode(fieldName, currentData, currentField); err != nil {
+ errors = appendErrors(errors, err)
+ }
+ }
+
+ // Finally, set the value to the slice we built up
+ val.Set(valSlice)
+
+ // If there were errors, we return those
+ if len(errors) > 0 {
+ return &Error{errors}
+ }
+
+ return nil
+}
+
+func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.Indirect(reflect.ValueOf(data))
+
+ // If the type of the value to write to and the data match directly,
+ // then we just set it directly instead of recursing into the structure.
+ if dataVal.Type() == val.Type() {
+ val.Set(dataVal)
+ return nil
+ }
+
+ dataValKind := dataVal.Kind()
+ if dataValKind != reflect.Map {
+ return fmt.Errorf("'%s' expected a map, got '%s'", name, dataValKind)
+ }
+
+ dataValType := dataVal.Type()
+ if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface {
+ return fmt.Errorf(
+ "'%s' needs a map with string keys, has '%s' keys",
+ name, dataValType.Key().Kind())
+ }
+
+ dataValKeys := make(map[reflect.Value]struct{})
+ dataValKeysUnused := make(map[interface{}]struct{})
+ for _, dataValKey := range dataVal.MapKeys() {
+ dataValKeys[dataValKey] = struct{}{}
+ dataValKeysUnused[dataValKey.Interface()] = struct{}{}
+ }
+
+ errors := make([]string, 0)
+
+ // This slice will keep track of all the structs we'll be decoding.
+ // There can be more than one struct if there are embedded structs
+ // that are squashed.
+ structs := make([]reflect.Value, 1, 5)
+ structs[0] = val
+
+ // Compile the list of all the fields that we're going to be decoding
+ // from all the structs.
+ fields := make(map[*reflect.StructField]reflect.Value)
+ for len(structs) > 0 {
+ structVal := structs[0]
+ structs = structs[1:]
+
+ structType := structVal.Type()
+
+ for i := 0; i < structType.NumField(); i++ {
+ fieldType := structType.Field(i)
+ fieldKind := fieldType.Type.Kind()
+
+ // If "squash" is specified in the tag, we squash the field down.
+ squash := false
+ tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",")
+ for _, tag := range tagParts[1:] {
+ if tag == "squash" {
+ squash = true
+ break
+ }
+ }
+
+ if squash {
+ if fieldKind != reflect.Struct {
+ errors = appendErrors(errors,
+ fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind))
+ } else {
+ structs = append(structs, val.FieldByName(fieldType.Name))
+ }
+ continue
+ }
+
+ // Normal struct field, store it away
+ fields[&fieldType] = structVal.Field(i)
+ }
+ }
+
+ for fieldType, field := range fields {
+ fieldName := fieldType.Name
+
+ tagValue := fieldType.Tag.Get(d.config.TagName)
+ tagValue = strings.SplitN(tagValue, ",", 2)[0]
+ if tagValue != "" {
+ fieldName = tagValue
+ }
+
+ rawMapKey := reflect.ValueOf(fieldName)
+ rawMapVal := dataVal.MapIndex(rawMapKey)
+ if !rawMapVal.IsValid() {
+ // Do a slower search by iterating over each key and
+ // doing case-insensitive search.
+ for dataValKey := range dataValKeys {
+ mK, ok := dataValKey.Interface().(string)
+ if !ok {
+ // Not a string key
+ continue
+ }
+
+ if strings.EqualFold(mK, fieldName) {
+ rawMapKey = dataValKey
+ rawMapVal = dataVal.MapIndex(dataValKey)
+ break
+ }
+ }
+
+ if !rawMapVal.IsValid() {
+ // There was no matching key in the map for the value in
+ // the struct. Just ignore.
+ continue
+ }
+ }
+
+ // Delete the key we're using from the unused map so we stop tracking
+ delete(dataValKeysUnused, rawMapKey.Interface())
+
+ if !field.IsValid() {
+ // This should never happen
+ panic("field is not valid")
+ }
+
+ // If we can't set the field, then it is unexported or something,
+ // and we just continue onwards.
+ if !field.CanSet() {
+ continue
+ }
+
+ // If the name is empty string, then we're at the root, and we
+ // don't dot-join the fields.
+ if name != "" {
+ fieldName = fmt.Sprintf("%s.%s", name, fieldName)
+ }
+
+ if err := d.decode(fieldName, rawMapVal.Interface(), field); err != nil {
+ errors = appendErrors(errors, err)
+ }
+ }
+
+ if d.config.ErrorUnused && len(dataValKeysUnused) > 0 {
+ keys := make([]string, 0, len(dataValKeysUnused))
+ for rawKey := range dataValKeysUnused {
+ keys = append(keys, rawKey.(string))
+ }
+ sort.Strings(keys)
+
+ err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", "))
+ errors = appendErrors(errors, err)
+ }
+
+ if len(errors) > 0 {
+ return &Error{errors}
+ }
+
+ // Add the unused keys to the list of unused keys if we're tracking metadata
+ if d.config.Metadata != nil {
+ for rawKey := range dataValKeysUnused {
+ key := rawKey.(string)
+ if name != "" {
+ key = fmt.Sprintf("%s.%s", name, key)
+ }
+
+ d.config.Metadata.Unused = append(d.config.Metadata.Unused, key)
+ }
+ }
+
+ return nil
+}
+
+func getKind(val reflect.Value) reflect.Kind {
+ kind := val.Kind()
+
+ switch {
+ case kind >= reflect.Int && kind <= reflect.Int64:
+ return reflect.Int
+ case kind >= reflect.Uint && kind <= reflect.Uint64:
+ return reflect.Uint
+ case kind >= reflect.Float32 && kind <= reflect.Float64:
+ return reflect.Float32
+ default:
+ return kind
+ }
+}
diff --git a/vendor/github.com/mrunalp/fileutils/LICENSE b/vendor/github.com/mrunalp/fileutils/LICENSE
new file mode 100644
index 0000000..2744858
--- /dev/null
+++ b/vendor/github.com/mrunalp/fileutils/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2014 Docker, Inc.
+
+ 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/mrunalp/fileutils/README.md b/vendor/github.com/mrunalp/fileutils/README.md
new file mode 100644
index 0000000..d156924
--- /dev/null
+++ b/vendor/github.com/mrunalp/fileutils/README.md
@@ -0,0 +1,5 @@
+# fileutils
+
+Collection of utilities for file manipulation in golang
+
+The library is based on docker pkg/archive but does copies instead of handling archive formats.
diff --git a/vendor/github.com/mrunalp/fileutils/fileutils.go b/vendor/github.com/mrunalp/fileutils/fileutils.go
new file mode 100644
index 0000000..b60cb90
--- /dev/null
+++ b/vendor/github.com/mrunalp/fileutils/fileutils.go
@@ -0,0 +1,161 @@
+package fileutils
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "syscall"
+)
+
+// CopyFile copies the file at source to dest
+func CopyFile(source string, dest string) error {
+ si, err := os.Lstat(source)
+ if err != nil {
+ return err
+ }
+
+ st, ok := si.Sys().(*syscall.Stat_t)
+ if !ok {
+ return fmt.Errorf("could not convert to syscall.Stat_t")
+ }
+
+ uid := int(st.Uid)
+ gid := int(st.Gid)
+
+ // Handle symlinks
+ if si.Mode()&os.ModeSymlink != 0 {
+ target, err := os.Readlink(source)
+ if err != nil {
+ return err
+ }
+ if err := os.Symlink(target, dest); err != nil {
+ return err
+ }
+ }
+
+ // Handle device files
+ if st.Mode&syscall.S_IFMT == syscall.S_IFBLK || st.Mode&syscall.S_IFMT == syscall.S_IFCHR {
+ devMajor := int64(major(uint64(st.Rdev)))
+ devMinor := int64(minor(uint64(st.Rdev)))
+ mode := uint32(si.Mode() & 07777)
+ if st.Mode&syscall.S_IFMT == syscall.S_IFBLK {
+ mode |= syscall.S_IFBLK
+ }
+ if st.Mode&syscall.S_IFMT == syscall.S_IFCHR {
+ mode |= syscall.S_IFCHR
+ }
+ if err := syscall.Mknod(dest, mode, int(mkdev(devMajor, devMinor))); err != nil {
+ return err
+ }
+ }
+
+ // Handle regular files
+ if si.Mode().IsRegular() {
+ sf, err := os.Open(source)
+ if err != nil {
+ return err
+ }
+ defer sf.Close()
+
+ df, err := os.Create(dest)
+ if err != nil {
+ return err
+ }
+ defer df.Close()
+
+ _, err = io.Copy(df, sf)
+ if err != nil {
+ return err
+ }
+ }
+
+ // Chown the file
+ if err := os.Lchown(dest, uid, gid); err != nil {
+ return err
+ }
+
+ // Chmod the file
+ if !(si.Mode()&os.ModeSymlink == os.ModeSymlink) {
+ if err := os.Chmod(dest, si.Mode()); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+// CopyDirectory copies the files under the source directory
+// to dest directory. The dest directory is created if it
+// does not exist.
+func CopyDirectory(source string, dest string) error {
+ fi, err := os.Stat(source)
+ if err != nil {
+ return err
+ }
+
+ // Get owner.
+ st, ok := fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return fmt.Errorf("could not convert to syscall.Stat_t")
+ }
+
+ // We have to pick an owner here anyway.
+ if err := MkdirAllNewAs(dest, fi.Mode(), int(st.Uid), int(st.Gid)); err != nil {
+ return err
+ }
+
+ return filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+
+ // Get the relative path
+ relPath, err := filepath.Rel(source, path)
+ if err != nil {
+ return nil
+ }
+
+ if info.IsDir() {
+ // Skip the source directory.
+ if path != source {
+ // Get the owner.
+ st, ok := info.Sys().(*syscall.Stat_t)
+ if !ok {
+ return fmt.Errorf("could not convert to syscall.Stat_t")
+ }
+
+ uid := int(st.Uid)
+ gid := int(st.Gid)
+
+ if err := os.Mkdir(filepath.Join(dest, relPath), info.Mode()); err != nil {
+ return err
+ }
+
+ if err := os.Lchown(filepath.Join(dest, relPath), uid, gid); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+
+ // Copy the file.
+ if err := CopyFile(path, filepath.Join(dest, relPath)); err != nil {
+ return err
+ }
+
+ return nil
+ })
+}
+
+func major(device uint64) uint64 {
+ return (device >> 8) & 0xfff
+}
+
+func minor(device uint64) uint64 {
+ return (device & 0xff) | ((device >> 12) & 0xfff00)
+}
+
+func mkdev(major int64, minor int64) uint32 {
+ return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff))
+}
diff --git a/vendor/github.com/mrunalp/fileutils/idtools.go b/vendor/github.com/mrunalp/fileutils/idtools.go
new file mode 100644
index 0000000..161aec8
--- /dev/null
+++ b/vendor/github.com/mrunalp/fileutils/idtools.go
@@ -0,0 +1,49 @@
+package fileutils
+
+import (
+ "os"
+ "path/filepath"
+)
+
+// MkdirAllNewAs creates a directory (include any along the path) and then modifies
+// ownership ONLY of newly created directories to the requested uid/gid. If the
+// directories along the path exist, no change of ownership will be performed
+func MkdirAllNewAs(path string, mode os.FileMode, ownerUID, ownerGID int) error {
+ // make an array containing the original path asked for, plus (for mkAll == true)
+ // all path components leading up to the complete path that don't exist before we MkdirAll
+ // so that we can chown all of them properly at the end. If chownExisting is false, we won't
+ // chown the full directory path if it exists
+ var paths []string
+ if _, err := os.Stat(path); err != nil && os.IsNotExist(err) {
+ paths = []string{path}
+ } else if err == nil {
+ // nothing to do; directory path fully exists already
+ return nil
+ }
+
+ // walk back to "/" looking for directories which do not exist
+ // and add them to the paths array for chown after creation
+ dirPath := path
+ for {
+ dirPath = filepath.Dir(dirPath)
+ if dirPath == "/" {
+ break
+ }
+ if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) {
+ paths = append(paths, dirPath)
+ }
+ }
+
+ if err := os.MkdirAll(path, mode); err != nil && !os.IsExist(err) {
+ return err
+ }
+
+ // even if it existed, we will chown the requested path + any subpaths that
+ // didn't exist when we called MkdirAll
+ for _, pathComponent := range paths {
+ if err := os.Chown(pathComponent, ownerUID, ownerGID); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/go-digest/LICENSE.code b/vendor/github.com/opencontainers/go-digest/LICENSE.code
new file mode 100644
index 0000000..0ea3ff8
--- /dev/null
+++ b/vendor/github.com/opencontainers/go-digest/LICENSE.code
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2016 Docker, Inc.
+
+ 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
+
+ https://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/opencontainers/go-digest/LICENSE.docs b/vendor/github.com/opencontainers/go-digest/LICENSE.docs
new file mode 100644
index 0000000..e26cd4f
--- /dev/null
+++ b/vendor/github.com/opencontainers/go-digest/LICENSE.docs
@@ -0,0 +1,425 @@
+Attribution-ShareAlike 4.0 International
+
+=======================================================================
+
+Creative Commons Corporation ("Creative Commons") is not a law firm and
+does not provide legal services or legal advice. Distribution of
+Creative Commons public licenses does not create a lawyer-client or
+other relationship. Creative Commons makes its licenses and related
+information available on an "as-is" basis. Creative Commons gives no
+warranties regarding its licenses, any material licensed under their
+terms and conditions, or any related information. Creative Commons
+disclaims all liability for damages resulting from their use to the
+fullest extent possible.
+
+Using Creative Commons Public Licenses
+
+Creative Commons public licenses provide a standard set of terms and
+conditions that creators and other rights holders may use to share
+original works of authorship and other material subject to copyright
+and certain other rights specified in the public license below. The
+following considerations are for informational purposes only, are not
+exhaustive, and do not form part of our licenses.
+
+ Considerations for licensors: Our public licenses are
+ intended for use by those authorized to give the public
+ permission to use material in ways otherwise restricted by
+ copyright and certain other rights. Our licenses are
+ irrevocable. Licensors should read and understand the terms
+ and conditions of the license they choose before applying it.
+ Licensors should also secure all rights necessary before
+ applying our licenses so that the public can reuse the
+ material as expected. Licensors should clearly mark any
+ material not subject to the license. This includes other CC-
+ licensed material, or material used under an exception or
+ limitation to copyright. More considerations for licensors:
+ wiki.creativecommons.org/Considerations_for_licensors
+
+ Considerations for the public: By using one of our public
+ licenses, a licensor grants the public permission to use the
+ licensed material under specified terms and conditions. If
+ the licensor's permission is not necessary for any reason--for
+ example, because of any applicable exception or limitation to
+ copyright--then that use is not regulated by the license. Our
+ licenses grant only permissions under copyright and certain
+ other rights that a licensor has authority to grant. Use of
+ the licensed material may still be restricted for other
+ reasons, including because others have copyright or other
+ rights in the material. A licensor may make special requests,
+ such as asking that all changes be marked or described.
+ Although not required by our licenses, you are encouraged to
+ respect those requests where reasonable. More_considerations
+ for the public:
+ wiki.creativecommons.org/Considerations_for_licensees
+
+=======================================================================
+
+Creative Commons Attribution-ShareAlike 4.0 International Public
+License
+
+By exercising the Licensed Rights (defined below), You accept and agree
+to be bound by the terms and conditions of this Creative Commons
+Attribution-ShareAlike 4.0 International Public License ("Public
+License"). To the extent this Public License may be interpreted as a
+contract, You are granted the Licensed Rights in consideration of Your
+acceptance of these terms and conditions, and the Licensor grants You
+such rights in consideration of benefits the Licensor receives from
+making the Licensed Material available under these terms and
+conditions.
+
+
+Section 1 -- Definitions.
+
+ a. Adapted Material means material subject to Copyright and Similar
+ Rights that is derived from or based upon the Licensed Material
+ and in which the Licensed Material is translated, altered,
+ arranged, transformed, or otherwise modified in a manner requiring
+ permission under the Copyright and Similar Rights held by the
+ Licensor. For purposes of this Public License, where the Licensed
+ Material is a musical work, performance, or sound recording,
+ Adapted Material is always produced where the Licensed Material is
+ synched in timed relation with a moving image.
+
+ b. Adapter's License means the license You apply to Your Copyright
+ and Similar Rights in Your contributions to Adapted Material in
+ accordance with the terms and conditions of this Public License.
+
+ c. BY-SA Compatible License means a license listed at
+ creativecommons.org/compatiblelicenses, approved by Creative
+ Commons as essentially the equivalent of this Public License.
+
+ d. Copyright and Similar Rights means copyright and/or similar rights
+ closely related to copyright including, without limitation,
+ performance, broadcast, sound recording, and Sui Generis Database
+ Rights, without regard to how the rights are labeled or
+ categorized. For purposes of this Public License, the rights
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
+ Rights.
+
+ e. Effective Technological Measures means those measures that, in the
+ absence of proper authority, may not be circumvented under laws
+ fulfilling obligations under Article 11 of the WIPO Copyright
+ Treaty adopted on December 20, 1996, and/or similar international
+ agreements.
+
+ f. Exceptions and Limitations means fair use, fair dealing, and/or
+ any other exception or limitation to Copyright and Similar Rights
+ that applies to Your use of the Licensed Material.
+
+ g. License Elements means the license attributes listed in the name
+ of a Creative Commons Public License. The License Elements of this
+ Public License are Attribution and ShareAlike.
+
+ h. Licensed Material means the artistic or literary work, database,
+ or other material to which the Licensor applied this Public
+ License.
+
+ i. Licensed Rights means the rights granted to You subject to the
+ terms and conditions of this Public License, which are limited to
+ all Copyright and Similar Rights that apply to Your use of the
+ Licensed Material and that the Licensor has authority to license.
+
+ j. Licensor means the individual(s) or entity(ies) granting rights
+ under this Public License.
+
+ k. Share means to provide material to the public by any means or
+ process that requires permission under the Licensed Rights, such
+ as reproduction, public display, public performance, distribution,
+ dissemination, communication, or importation, and to make material
+ available to the public including in ways that members of the
+ public may access the material from a place and at a time
+ individually chosen by them.
+
+ l. Sui Generis Database Rights means rights other than copyright
+ resulting from Directive 96/9/EC of the European Parliament and of
+ the Council of 11 March 1996 on the legal protection of databases,
+ as amended and/or succeeded, as well as other essentially
+ equivalent rights anywhere in the world.
+
+ m. You means the individual or entity exercising the Licensed Rights
+ under this Public License. Your has a corresponding meaning.
+
+
+Section 2 -- Scope.
+
+ a. License grant.
+
+ 1. Subject to the terms and conditions of this Public License,
+ the Licensor hereby grants You a worldwide, royalty-free,
+ non-sublicensable, non-exclusive, irrevocable license to
+ exercise the Licensed Rights in the Licensed Material to:
+
+ a. reproduce and Share the Licensed Material, in whole or
+ in part; and
+
+ b. produce, reproduce, and Share Adapted Material.
+
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
+ Exceptions and Limitations apply to Your use, this Public
+ License does not apply, and You do not need to comply with
+ its terms and conditions.
+
+ 3. Term. The term of this Public License is specified in Section
+ 6(a).
+
+ 4. Media and formats; technical modifications allowed. The
+ Licensor authorizes You to exercise the Licensed Rights in
+ all media and formats whether now known or hereafter created,
+ and to make technical modifications necessary to do so. The
+ Licensor waives and/or agrees not to assert any right or
+ authority to forbid You from making technical modifications
+ necessary to exercise the Licensed Rights, including
+ technical modifications necessary to circumvent Effective
+ Technological Measures. For purposes of this Public License,
+ simply making modifications authorized by this Section 2(a)
+ (4) never produces Adapted Material.
+
+ 5. Downstream recipients.
+
+ a. Offer from the Licensor -- Licensed Material. Every
+ recipient of the Licensed Material automatically
+ receives an offer from the Licensor to exercise the
+ Licensed Rights under the terms and conditions of this
+ Public License.
+
+ b. Additional offer from the Licensor -- Adapted Material.
+ Every recipient of Adapted Material from You
+ automatically receives an offer from the Licensor to
+ exercise the Licensed Rights in the Adapted Material
+ under the conditions of the Adapter's License You apply.
+
+ c. No downstream restrictions. You may not offer or impose
+ any additional or different terms or conditions on, or
+ apply any Effective Technological Measures to, the
+ Licensed Material if doing so restricts exercise of the
+ Licensed Rights by any recipient of the Licensed
+ Material.
+
+ 6. No endorsement. Nothing in this Public License constitutes or
+ may be construed as permission to assert or imply that You
+ are, or that Your use of the Licensed Material is, connected
+ with, or sponsored, endorsed, or granted official status by,
+ the Licensor or others designated to receive attribution as
+ provided in Section 3(a)(1)(A)(i).
+
+ b. Other rights.
+
+ 1. Moral rights, such as the right of integrity, are not
+ licensed under this Public License, nor are publicity,
+ privacy, and/or other similar personality rights; however, to
+ the extent possible, the Licensor waives and/or agrees not to
+ assert any such rights held by the Licensor to the limited
+ extent necessary to allow You to exercise the Licensed
+ Rights, but not otherwise.
+
+ 2. Patent and trademark rights are not licensed under this
+ Public License.
+
+ 3. To the extent possible, the Licensor waives any right to
+ collect royalties from You for the exercise of the Licensed
+ Rights, whether directly or through a collecting society
+ under any voluntary or waivable statutory or compulsory
+ licensing scheme. In all other cases the Licensor expressly
+ reserves any right to collect such royalties.
+
+
+Section 3 -- License Conditions.
+
+Your exercise of the Licensed Rights is expressly made subject to the
+following conditions.
+
+ a. Attribution.
+
+ 1. If You Share the Licensed Material (including in modified
+ form), You must:
+
+ a. retain the following if it is supplied by the Licensor
+ with the Licensed Material:
+
+ i. identification of the creator(s) of the Licensed
+ Material and any others designated to receive
+ attribution, in any reasonable manner requested by
+ the Licensor (including by pseudonym if
+ designated);
+
+ ii. a copyright notice;
+
+ iii. a notice that refers to this Public License;
+
+ iv. a notice that refers to the disclaimer of
+ warranties;
+
+ v. a URI or hyperlink to the Licensed Material to the
+ extent reasonably practicable;
+
+ b. indicate if You modified the Licensed Material and
+ retain an indication of any previous modifications; and
+
+ c. indicate the Licensed Material is licensed under this
+ Public License, and include the text of, or the URI or
+ hyperlink to, this Public License.
+
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
+ reasonable manner based on the medium, means, and context in
+ which You Share the Licensed Material. For example, it may be
+ reasonable to satisfy the conditions by providing a URI or
+ hyperlink to a resource that includes the required
+ information.
+
+ 3. If requested by the Licensor, You must remove any of the
+ information required by Section 3(a)(1)(A) to the extent
+ reasonably practicable.
+
+ b. ShareAlike.
+
+ In addition to the conditions in Section 3(a), if You Share
+ Adapted Material You produce, the following conditions also apply.
+
+ 1. The Adapter's License You apply must be a Creative Commons
+ license with the same License Elements, this version or
+ later, or a BY-SA Compatible License.
+
+ 2. You must include the text of, or the URI or hyperlink to, the
+ Adapter's License You apply. You may satisfy this condition
+ in any reasonable manner based on the medium, means, and
+ context in which You Share Adapted Material.
+
+ 3. You may not offer or impose any additional or different terms
+ or conditions on, or apply any Effective Technological
+ Measures to, Adapted Material that restrict exercise of the
+ rights granted under the Adapter's License You apply.
+
+
+Section 4 -- Sui Generis Database Rights.
+
+Where the Licensed Rights include Sui Generis Database Rights that
+apply to Your use of the Licensed Material:
+
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
+ to extract, reuse, reproduce, and Share all or a substantial
+ portion of the contents of the database;
+
+ b. if You include all or a substantial portion of the database
+ contents in a database in which You have Sui Generis Database
+ Rights, then the database in which You have Sui Generis Database
+ Rights (but not its individual contents) is Adapted Material,
+
+ including for purposes of Section 3(b); and
+ c. You must comply with the conditions in Section 3(a) if You Share
+ all or a substantial portion of the contents of the database.
+
+For the avoidance of doubt, this Section 4 supplements and does not
+replace Your obligations under this Public License where the Licensed
+Rights include other Copyright and Similar Rights.
+
+
+Section 5 -- Disclaimer of Warranties and Limitation of Liability.
+
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
+
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
+
+ c. The disclaimer of warranties and limitation of liability provided
+ above shall be interpreted in a manner that, to the extent
+ possible, most closely approximates an absolute disclaimer and
+ waiver of all liability.
+
+
+Section 6 -- Term and Termination.
+
+ a. This Public License applies for the term of the Copyright and
+ Similar Rights licensed here. However, if You fail to comply with
+ this Public License, then Your rights under this Public License
+ terminate automatically.
+
+ b. Where Your right to use the Licensed Material has terminated under
+ Section 6(a), it reinstates:
+
+ 1. automatically as of the date the violation is cured, provided
+ it is cured within 30 days of Your discovery of the
+ violation; or
+
+ 2. upon express reinstatement by the Licensor.
+
+ For the avoidance of doubt, this Section 6(b) does not affect any
+ right the Licensor may have to seek remedies for Your violations
+ of this Public License.
+
+ c. For the avoidance of doubt, the Licensor may also offer the
+ Licensed Material under separate terms or conditions or stop
+ distributing the Licensed Material at any time; however, doing so
+ will not terminate this Public License.
+
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
+ License.
+
+
+Section 7 -- Other Terms and Conditions.
+
+ a. The Licensor shall not be bound by any additional or different
+ terms or conditions communicated by You unless expressly agreed.
+
+ b. Any arrangements, understandings, or agreements regarding the
+ Licensed Material not stated herein are separate from and
+ independent of the terms and conditions of this Public License.
+
+
+Section 8 -- Interpretation.
+
+ a. For the avoidance of doubt, this Public License does not, and
+ shall not be interpreted to, reduce, limit, restrict, or impose
+ conditions on any use of the Licensed Material that could lawfully
+ be made without permission under this Public License.
+
+ b. To the extent possible, if any provision of this Public License is
+ deemed unenforceable, it shall be automatically reformed to the
+ minimum extent necessary to make it enforceable. If the provision
+ cannot be reformed, it shall be severed from this Public License
+ without affecting the enforceability of the remaining terms and
+ conditions.
+
+ c. No term or condition of this Public License will be waived and no
+ failure to comply consented to unless expressly agreed to by the
+ Licensor.
+
+ d. Nothing in this Public License constitutes or may be interpreted
+ as a limitation upon, or waiver of, any privileges and immunities
+ that apply to the Licensor or You, including from the legal
+ processes of any jurisdiction or authority.
+
+
+=======================================================================
+
+Creative Commons is not a party to its public licenses.
+Notwithstanding, Creative Commons may elect to apply one of its public
+licenses to material it publishes and in those instances will be
+considered the "Licensor." Except for the limited purpose of indicating
+that material is shared under a Creative Commons public license or as
+otherwise permitted by the Creative Commons policies published at
+creativecommons.org/policies, Creative Commons does not authorize the
+use of the trademark "Creative Commons" or any other trademark or logo
+of Creative Commons without its prior written consent including,
+without limitation, in connection with any unauthorized modifications
+to any of its public licenses or any other arrangements,
+understandings, or agreements concerning use of licensed material. For
+the avoidance of doubt, this paragraph does not form part of the public
+licenses.
+
+Creative Commons may be contacted at creativecommons.org.
diff --git a/vendor/github.com/opencontainers/go-digest/README.md b/vendor/github.com/opencontainers/go-digest/README.md
new file mode 100644
index 0000000..9d6174c
--- /dev/null
+++ b/vendor/github.com/opencontainers/go-digest/README.md
@@ -0,0 +1,104 @@
+# go-digest
+
+[![GoDoc](https://godoc.org/github.com/docker/go-digest?status.svg)](https://godoc.org/github.com/docker/go-digest) [![Go Report Card](https://goreportcard.com/badge/github.com/docker/go-digest)](https://goreportcard.com/report/github.com/docker/go-digest) [![Build Status](https://travis-ci.org/docker/go-digest.svg?branch=master)](https://travis-ci.org/docker/go-digest)
+
+Common digest package used across the container ecosystem.
+
+Please see the [godoc](https://godoc.org/github.com/docker/go-digest) for more information.
+
+# What is a digest?
+
+A digest is just a hash.
+
+The most common use case for a digest is to create a content
+identifier for use in [Content Addressable Storage](https://en.wikipedia.org/wiki/Content-addressable_storage)
+systems:
+
+```go
+id := digest.FromBytes([]byte("my content"))
+```
+
+In the example above, the id can be used to uniquely identify
+the byte slice "my content". This allows two disparate applications
+to agree on a verifiable identifier without having to trust one
+another.
+
+An identifying digest can be verified, as follows:
+
+```go
+if id != digest.FromBytes([]byte("my content")) {
+ return errors.New("the content has changed!")
+}
+```
+
+A `Verifier` type can be used to handle cases where an `io.Reader`
+makes more sense:
+
+```go
+rd := getContent()
+verifier := id.Verifier()
+io.Copy(verifier, rd)
+
+if !verifier.Verified() {
+ return errors.New("the content has changed!")
+}
+```
+
+Using [Merkle DAGs](https://en.wikipedia.org/wiki/Merkle_tree), this
+can power a rich, safe, content distribution system.
+
+# Usage
+
+While the [godoc](https://godoc.org/github.com/docker/go-digest) is
+considered the best resource, a few important items need to be called
+out when using this package.
+
+1. Make sure to import the hash implementations into your application
+ or the package will panic. You should have something like the
+ following in the main (or other entrypoint) of your application:
+
+ ```go
+ import (
+ _ "crypto/sha256"
+ _ "crypto/sha512"
+ )
+ ```
+ This may seem inconvenient but it allows you replace the hash
+ implementations with others, such as https://github.com/stevvooe/resumable.
+
+2. Even though `digest.Digest` may be assemable as a string, _always_
+ verify your input with `digest.Parse` or use `Digest.Validate`
+ when accepting untrusted input. While there are measures to
+ avoid common problems, this will ensure you have valid digests
+ in the rest of your application.
+
+# Stability
+
+The Go API, at this stage, is considered stable, unless otherwise noted.
+
+As always, before using a package export, read the [godoc](https://godoc.org/github.com/docker/go-digest).
+
+# Contributing
+
+This package is considered fairly complete. It has been in production
+in thousands (millions?) of deployments and is fairly battle-hardened.
+New additions will be met with skepticism. If you think there is a
+missing feature, please file a bug clearly describing the problem and
+the alternatives you tried before submitting a PR.
+
+# Reporting security issues
+
+The maintainers take security seriously. If you discover a security
+issue, please bring it to their attention right away!
+
+Please DO NOT file a public issue, instead send your report privately
+to security@docker.com.
+
+Security reports are greatly appreciated and we will publicly thank you
+for it. We also like to send gifts—if you're into Docker schwag, make
+sure to let us know. We currently do not offer a paid security bounty
+program, but are not ruling it out in the future.
+
+# Copyright and license
+
+Copyright © 2016 Docker, Inc. All rights reserved, except as follows. Code is released under the [Apache 2.0 license](LICENSE.code). This `README.md` file and the [`CONTRIBUTING.md`](CONTRIBUTING.md) file are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file [`LICENSE.docs`](LICENSE.docs). You may obtain a duplicate copy of the same license, titled CC BY-SA 4.0, at http://creativecommons.org/licenses/by-sa/4.0/.
diff --git a/vendor/github.com/opencontainers/go-digest/algorithm.go b/vendor/github.com/opencontainers/go-digest/algorithm.go
new file mode 100644
index 0000000..a3c4480
--- /dev/null
+++ b/vendor/github.com/opencontainers/go-digest/algorithm.go
@@ -0,0 +1,144 @@
+package digest
+
+import (
+ "crypto"
+ "fmt"
+ "hash"
+ "io"
+)
+
+// Algorithm identifies and implementation of a digester by an identifier.
+// Note the that this defines both the hash algorithm used and the string
+// encoding.
+type Algorithm string
+
+// supported digest types
+const (
+ SHA256 Algorithm = "sha256" // sha256 with hex encoding
+ SHA384 Algorithm = "sha384" // sha384 with hex encoding
+ SHA512 Algorithm = "sha512" // sha512 with hex encoding
+
+ // Canonical is the primary digest algorithm used with the distribution
+ // project. Other digests may be used but this one is the primary storage
+ // digest.
+ Canonical = SHA256
+)
+
+var (
+ // TODO(stevvooe): Follow the pattern of the standard crypto package for
+ // registration of digests. Effectively, we are a registerable set and
+ // common symbol access.
+
+ // algorithms maps values to hash.Hash implementations. Other algorithms
+ // may be available but they cannot be calculated by the digest package.
+ algorithms = map[Algorithm]crypto.Hash{
+ SHA256: crypto.SHA256,
+ SHA384: crypto.SHA384,
+ SHA512: crypto.SHA512,
+ }
+)
+
+// Available returns true if the digest type is available for use. If this
+// returns false, Digester and Hash will return nil.
+func (a Algorithm) Available() bool {
+ h, ok := algorithms[a]
+ if !ok {
+ return false
+ }
+
+ // check availability of the hash, as well
+ return h.Available()
+}
+
+func (a Algorithm) String() string {
+ return string(a)
+}
+
+// Size returns number of bytes returned by the hash.
+func (a Algorithm) Size() int {
+ h, ok := algorithms[a]
+ if !ok {
+ return 0
+ }
+ return h.Size()
+}
+
+// Set implemented to allow use of Algorithm as a command line flag.
+func (a *Algorithm) Set(value string) error {
+ if value == "" {
+ *a = Canonical
+ } else {
+ // just do a type conversion, support is queried with Available.
+ *a = Algorithm(value)
+ }
+
+ if !a.Available() {
+ return ErrDigestUnsupported
+ }
+
+ return nil
+}
+
+// Digester returns a new digester for the specified algorithm. If the algorithm
+// does not have a digester implementation, nil will be returned. This can be
+// checked by calling Available before calling Digester.
+func (a Algorithm) Digester() Digester {
+ return &digester{
+ alg: a,
+ hash: a.Hash(),
+ }
+}
+
+// Hash returns a new hash as used by the algorithm. If not available, the
+// method will panic. Check Algorithm.Available() before calling.
+func (a Algorithm) Hash() hash.Hash {
+ if !a.Available() {
+ // Empty algorithm string is invalid
+ if a == "" {
+ panic(fmt.Sprintf("empty digest algorithm, validate before calling Algorithm.Hash()"))
+ }
+
+ // NOTE(stevvooe): A missing hash is usually a programming error that
+ // must be resolved at compile time. We don't import in the digest
+ // package to allow users to choose their hash implementation (such as
+ // when using stevvooe/resumable or a hardware accelerated package).
+ //
+ // Applications that may want to resolve the hash at runtime should
+ // call Algorithm.Available before call Algorithm.Hash().
+ panic(fmt.Sprintf("%v not available (make sure it is imported)", a))
+ }
+
+ return algorithms[a].New()
+}
+
+// FromReader returns the digest of the reader using the algorithm.
+func (a Algorithm) FromReader(rd io.Reader) (Digest, error) {
+ digester := a.Digester()
+
+ if _, err := io.Copy(digester.Hash(), rd); err != nil {
+ return "", err
+ }
+
+ return digester.Digest(), nil
+}
+
+// FromBytes digests the input and returns a Digest.
+func (a Algorithm) FromBytes(p []byte) Digest {
+ digester := a.Digester()
+
+ if _, err := digester.Hash().Write(p); err != nil {
+ // Writes to a Hash should never fail. None of the existing
+ // hash implementations in the stdlib or hashes vendored
+ // here can return errors from Write. Having a panic in this
+ // condition instead of having FromBytes return an error value
+ // avoids unnecessary error handling paths in all callers.
+ panic("write to hash function returned error: " + err.Error())
+ }
+
+ return digester.Digest()
+}
+
+// FromString digests the string input and returns a Digest.
+func (a Algorithm) FromString(s string) Digest {
+ return a.FromBytes([]byte(s))
+}
diff --git a/vendor/github.com/opencontainers/go-digest/digest.go b/vendor/github.com/opencontainers/go-digest/digest.go
new file mode 100644
index 0000000..7c66c30
--- /dev/null
+++ b/vendor/github.com/opencontainers/go-digest/digest.go
@@ -0,0 +1,140 @@
+package digest
+
+import (
+ "fmt"
+ "hash"
+ "io"
+ "regexp"
+ "strings"
+)
+
+// Digest allows simple protection of hex formatted digest strings, prefixed
+// by their algorithm. Strings of type Digest have some guarantee of being in
+// the correct format and it provides quick access to the components of a
+// digest string.
+//
+// The following is an example of the contents of Digest types:
+//
+// sha256:7173b809ca12ec5dee4506cd86be934c4596dd234ee82c0662eac04a8c2c71dc
+//
+// This allows to abstract the digest behind this type and work only in those
+// terms.
+type Digest string
+
+// NewDigest returns a Digest from alg and a hash.Hash object.
+func NewDigest(alg Algorithm, h hash.Hash) Digest {
+ return NewDigestFromBytes(alg, h.Sum(nil))
+}
+
+// NewDigestFromBytes returns a new digest from the byte contents of p.
+// Typically, this can come from hash.Hash.Sum(...) or xxx.SumXXX(...)
+// functions. This is also useful for rebuilding digests from binary
+// serializations.
+func NewDigestFromBytes(alg Algorithm, p []byte) Digest {
+ return Digest(fmt.Sprintf("%s:%x", alg, p))
+}
+
+// NewDigestFromHex returns a Digest from alg and a the hex encoded digest.
+func NewDigestFromHex(alg, hex string) Digest {
+ return Digest(fmt.Sprintf("%s:%s", alg, hex))
+}
+
+// DigestRegexp matches valid digest types.
+var DigestRegexp = regexp.MustCompile(`[a-zA-Z0-9-_+.]+:[a-fA-F0-9]+`)
+
+// DigestRegexpAnchored matches valid digest types, anchored to the start and end of the match.
+var DigestRegexpAnchored = regexp.MustCompile(`^` + DigestRegexp.String() + `$`)
+
+var (
+ // ErrDigestInvalidFormat returned when digest format invalid.
+ ErrDigestInvalidFormat = fmt.Errorf("invalid checksum digest format")
+
+ // ErrDigestInvalidLength returned when digest has invalid length.
+ ErrDigestInvalidLength = fmt.Errorf("invalid checksum digest length")
+
+ // ErrDigestUnsupported returned when the digest algorithm is unsupported.
+ ErrDigestUnsupported = fmt.Errorf("unsupported digest algorithm")
+)
+
+// Parse parses s and returns the validated digest object. An error will
+// be returned if the format is invalid.
+func Parse(s string) (Digest, error) {
+ d := Digest(s)
+ return d, d.Validate()
+}
+
+// FromReader consumes the content of rd until io.EOF, returning canonical digest.
+func FromReader(rd io.Reader) (Digest, error) {
+ return Canonical.FromReader(rd)
+}
+
+// FromBytes digests the input and returns a Digest.
+func FromBytes(p []byte) Digest {
+ return Canonical.FromBytes(p)
+}
+
+// FromString digests the input and returns a Digest.
+func FromString(s string) Digest {
+ return Canonical.FromString(s)
+}
+
+// Validate checks that the contents of d is a valid digest, returning an
+// error if not.
+func (d Digest) Validate() error {
+ s := string(d)
+
+ i := strings.Index(s, ":")
+
+ // validate i then run through regexp
+ if i < 0 || i+1 == len(s) || !DigestRegexpAnchored.MatchString(s) {
+ return ErrDigestInvalidFormat
+ }
+
+ algorithm := Algorithm(s[:i])
+ if !algorithm.Available() {
+ return ErrDigestUnsupported
+ }
+
+ // Digests much always be hex-encoded, ensuring that their hex portion will
+ // always be size*2
+ if algorithm.Size()*2 != len(s[i+1:]) {
+ return ErrDigestInvalidLength
+ }
+
+ return nil
+}
+
+// Algorithm returns the algorithm portion of the digest. This will panic if
+// the underlying digest is not in a valid format.
+func (d Digest) Algorithm() Algorithm {
+ return Algorithm(d[:d.sepIndex()])
+}
+
+// Verifier returns a writer object that can be used to verify a stream of
+// content against the digest. If the digest is invalid, the method will panic.
+func (d Digest) Verifier() Verifier {
+ return hashVerifier{
+ hash: d.Algorithm().Hash(),
+ digest: d,
+ }
+}
+
+// Hex returns the hex digest portion of the digest. This will panic if the
+// underlying digest is not in a valid format.
+func (d Digest) Hex() string {
+ return string(d[d.sepIndex()+1:])
+}
+
+func (d Digest) String() string {
+ return string(d)
+}
+
+func (d Digest) sepIndex() int {
+ i := strings.Index(string(d), ":")
+
+ if i < 0 {
+ panic(fmt.Sprintf("no ':' separator in digest %q", d))
+ }
+
+ return i
+}
diff --git a/vendor/github.com/opencontainers/go-digest/digester.go b/vendor/github.com/opencontainers/go-digest/digester.go
new file mode 100644
index 0000000..918a3f9
--- /dev/null
+++ b/vendor/github.com/opencontainers/go-digest/digester.go
@@ -0,0 +1,25 @@
+package digest
+
+import "hash"
+
+// Digester calculates the digest of written data. Writes should go directly
+// to the return value of Hash, while calling Digest will return the current
+// value of the digest.
+type Digester interface {
+ Hash() hash.Hash // provides direct access to underlying hash instance.
+ Digest() Digest
+}
+
+// digester provides a simple digester definition that embeds a hasher.
+type digester struct {
+ alg Algorithm
+ hash hash.Hash
+}
+
+func (d *digester) Hash() hash.Hash {
+ return d.hash
+}
+
+func (d *digester) Digest() Digest {
+ return NewDigest(d.alg, d.hash)
+}
diff --git a/vendor/github.com/opencontainers/go-digest/doc.go b/vendor/github.com/opencontainers/go-digest/doc.go
new file mode 100644
index 0000000..f64b0db
--- /dev/null
+++ b/vendor/github.com/opencontainers/go-digest/doc.go
@@ -0,0 +1,42 @@
+// Package digest provides a generalized type to opaquely represent message
+// digests and their operations within the registry. The Digest type is
+// designed to serve as a flexible identifier in a content-addressable system.
+// More importantly, it provides tools and wrappers to work with
+// hash.Hash-based digests with little effort.
+//
+// Basics
+//
+// The format of a digest is simply a string with two parts, dubbed the
+// "algorithm" and the "digest", separated by a colon:
+//
+// <algorithm>:<digest>
+//
+// An example of a sha256 digest representation follows:
+//
+// sha256:7173b809ca12ec5dee4506cd86be934c4596dd234ee82c0662eac04a8c2c71dc
+//
+// In this case, the string "sha256" is the algorithm and the hex bytes are
+// the "digest".
+//
+// Because the Digest type is simply a string, once a valid Digest is
+// obtained, comparisons are cheap, quick and simple to express with the
+// standard equality operator.
+//
+// Verification
+//
+// The main benefit of using the Digest type is simple verification against a
+// given digest. The Verifier interface, modeled after the stdlib hash.Hash
+// interface, provides a common write sink for digest verification. After
+// writing is complete, calling the Verifier.Verified method will indicate
+// whether or not the stream of bytes matches the target digest.
+//
+// Missing Features
+//
+// In addition to the above, we intend to add the following features to this
+// package:
+//
+// 1. A Digester type that supports write sink digest calculation.
+//
+// 2. Suspend and resume of ongoing digest calculations to support efficient digest verification in the registry.
+//
+package digest
diff --git a/vendor/github.com/opencontainers/go-digest/verifiers.go b/vendor/github.com/opencontainers/go-digest/verifiers.go
new file mode 100644
index 0000000..f1db6cd
--- /dev/null
+++ b/vendor/github.com/opencontainers/go-digest/verifiers.go
@@ -0,0 +1,31 @@
+package digest
+
+import (
+ "hash"
+ "io"
+)
+
+// Verifier presents a general verification interface to be used with message
+// digests and other byte stream verifications. Users instantiate a Verifier
+// from one of the various methods, write the data under test to it then check
+// the result with the Verified method.
+type Verifier interface {
+ io.Writer
+
+ // Verified will return true if the content written to Verifier matches
+ // the digest.
+ Verified() bool
+}
+
+type hashVerifier struct {
+ digest Digest
+ hash hash.Hash
+}
+
+func (hv hashVerifier) Write(p []byte) (n int, err error) {
+ return hv.hash.Write(p)
+}
+
+func (hv hashVerifier) Verified() bool {
+ return hv.digest == NewDigest(hv.digest.Algorithm(), hv.hash)
+}
diff --git a/vendor/github.com/opencontainers/image-spec/LICENSE b/vendor/github.com/opencontainers/image-spec/LICENSE
new file mode 100644
index 0000000..9fdc20f
--- /dev/null
+++ b/vendor/github.com/opencontainers/image-spec/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2016 The Linux Foundation.
+
+ 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/opencontainers/image-spec/README.md b/vendor/github.com/opencontainers/image-spec/README.md
new file mode 100644
index 0000000..5ab5554
--- /dev/null
+++ b/vendor/github.com/opencontainers/image-spec/README.md
@@ -0,0 +1,167 @@
+# OCI Image Format Specification
+<div>
+<a href="https://travis-ci.org/opencontainers/image-spec">
+<img src="https://travis-ci.org/opencontainers/image-spec.svg?branch=master"></img>
+</a>
+</div>
+
+The OCI Image Format project creates and maintains the software shipping container image format spec (OCI Image Format).
+
+**[The specification can be found here](spec.md).**
+
+This repository also provides [Go types](specs-go), [intra-blob validation tooling, and JSON Schema](schema).
+The Go types and validation should be compatible with the current Go release; earlier Go releases are not supported.
+
+Additional documentation about how this group operates:
+
+- [Code of Conduct](https://github.com/opencontainers/tob/blob/d2f9d68c1332870e40693fe077d311e0742bc73d/code-of-conduct.md)
+- [Roadmap](#roadmap)
+- [Releases](RELEASES.md)
+- [Project Documentation](project.md)
+
+The _optional_ and _base_ layers of all OCI projects are tracked in the [OCI Scope Table](https://www.opencontainers.org/about/oci-scope-table).
+
+## Running an OCI Image
+
+The OCI Image Format partner project is the [OCI Runtime Spec project](https://github.com/opencontainers/runtime-spec).
+The Runtime Specification outlines how to run a "[filesystem bundle](https://github.com/opencontainers/runtime-spec/blob/master/bundle.md)" that is unpacked on disk.
+At a high-level an OCI implementation would download an OCI Image then unpack that image into an OCI Runtime filesystem bundle.
+At this point the OCI Runtime Bundle would be run by an OCI Runtime.
+
+This entire workflow supports the UX that users have come to expect from container engines like Docker and rkt: primarily, the ability to run an image with no additional arguments:
+
+* docker run example.com/org/app:v1.0.0
+* rkt run example.com/org/app,version=v1.0.0
+
+To support this UX the OCI Image Format contains sufficient information to launch the application on the target platform (e.g. command, arguments, environment variables, etc).
+
+## FAQ
+
+**Q: Why doesn't this project mention distribution?**
+
+A: Distribution, for example using HTTP as both Docker v2.2 and AppC do today, is currently out of scope on the [OCI Scope Table](https://www.opencontainers.org/about/oci-scope-table).
+There has been [some discussion on the TOB mailing list](https://groups.google.com/a/opencontainers.org/d/msg/tob/A3JnmI-D-6Y/tLuptPDHAgAJ) to make distribution an optional layer, but this topic is a work in progress.
+
+**Q: What happens to AppC or Docker Image Formats?**
+
+A: Existing formats can continue to be a proving ground for technologies, as needed.
+The OCI Image Format project strives to provide a dependable open specification that can be shared between different tools and be evolved for years or decades of compatibility; as the deb and rpm format have.
+
+Find more [FAQ on the OCI site](https://www.opencontainers.org/faq).
+
+## Roadmap
+
+The [GitHub milestones](https://github.com/opencontainers/image-spec/milestones) lay out the path to the OCI v1.0.0 release in late 2016.
+
+# Contributing
+
+Development happens on GitHub for the spec.
+Issues are used for bugs and actionable items and longer discussions can happen on the [mailing list](#mailing-list).
+
+The specification and code is licensed under the Apache 2.0 license found in the `LICENSE` file of this repository.
+
+## Discuss your design
+
+The project welcomes submissions, but please let everyone know what you are working on.
+
+Before undertaking a nontrivial change to this specification, send mail to the [mailing list](#mailing-list) to discuss what you plan to do.
+This gives everyone a chance to validate the design, helps prevent duplication of effort, and ensures that the idea fits.
+It also guarantees that the design is sound before code is written; a GitHub pull-request is not the place for high-level discussions.
+
+Typos and grammatical errors can go straight to a pull-request.
+When in doubt, start on the [mailing-list](#mailing-list).
+
+## Weekly Call
+
+The contributors and maintainers of all OCI projects have a weekly meeting Wednesdays at 2:00 PM (USA Pacific).
+Everyone is welcome to participate via [UberConference web][UberConference] or audio-only: +1-415-968-0849 (no PIN needed).
+An initial agenda will be posted to the [mailing list](#mailing-list) earlier in the week, and everyone is welcome to propose additional topics or suggest other agenda alterations there.
+Minutes are posted to the [mailing list](#mailing-list) and minutes from past calls are archived [here][minutes].
+
+## Mailing List
+
+You can subscribe and join the mailing list on [Google Groups](https://groups.google.com/a/opencontainers.org/forum/#!forum/dev).
+
+## IRC
+
+OCI discussion happens on #opencontainers on Freenode ([logs][irc-logs]).
+
+## Markdown style
+
+To keep consistency throughout the Markdown files in the Open Container spec all files should be formatted one sentence per line.
+This fixes two things: it makes diffing easier with git and it resolves fights about line wrapping length.
+For example, this paragraph will span three lines in the Markdown source.
+
+## Git commit
+
+### Sign your work
+
+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 (from [developercertificate.org](http://developercertificate.org/)):
+
+```
+Developer Certificate of Origin
+Version 1.1
+
+Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
+660 York Street, Suite 102,
+San Francisco, CA 94110 USA
+
+Everyone is permitted to copy and distribute verbatim copies of this
+license document, but changing it is not allowed.
+
+
+Developer's Certificate of Origin 1.1
+
+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) 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 to every git commit message:
+
+ Signed-off-by: Joe Smith <joe@gmail.com>
+
+using your real name (sorry, no pseudonyms or anonymous contributions.)
+
+You can add the sign off when creating the git commit via `git commit -s`.
+
+### Commit Style
+
+Simple house-keeping for clean git history.
+Read more on [How to Write a Git Commit Message](http://chris.beams.io/posts/git-commit/) or the Discussion section of [`git-commit(1)`](http://git-scm.com/docs/git-commit).
+
+1. Separate the subject from body with a blank line
+2. Limit the subject line to 50 characters
+3. Capitalize the subject line
+4. Do not end the subject line with a period
+5. Use the imperative mood in the subject line
+6. Wrap the body at 72 characters
+7. Use the body to explain what and why vs. how
+ * If there was important/useful/essential conversation or information, copy or include a reference
+8. When possible, one keyword to scope the change in the subject (i.e. "README: ...", "runtime: ...")
+
+
+[UberConference]: https://www.uberconference.com/opencontainers
+[irc-logs]: http://ircbot.wl.linuxfoundation.org/eavesdrop/%23opencontainers/
+[minutes]: http://ircbot.wl.linuxfoundation.org/meetings/opencontainers/
diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go
new file mode 100644
index 0000000..8475ff7
--- /dev/null
+++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go
@@ -0,0 +1,103 @@
+// Copyright 2016 The Linux Foundation
+//
+// 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 v1
+
+import (
+ "time"
+
+ digest "github.com/opencontainers/go-digest"
+)
+
+// ImageConfig defines the execution parameters which should be used as a base when running a container using an image.
+type ImageConfig struct {
+ // User defines the username or UID which the process in the container should run as.
+ User string `json:"User,omitempty"`
+
+ // ExposedPorts a set of ports to expose from a container running this image.
+ ExposedPorts map[string]struct{} `json:"ExposedPorts,omitempty"`
+
+ // Env is a list of environment variables to be used in a container.
+ Env []string `json:"Env,omitempty"`
+
+ // Entrypoint defines a list of arguments to use as the command to execute when the container starts.
+ Entrypoint []string `json:"Entrypoint,omitempty"`
+
+ // Cmd defines the default arguments to the entrypoint of the container.
+ Cmd []string `json:"Cmd,omitempty"`
+
+ // Volumes is a set of directories which should be created as data volumes in a container running this image.
+ Volumes map[string]struct{} `json:"Volumes,omitempty"`
+
+ // WorkingDir sets the current working directory of the entrypoint process in the container.
+ WorkingDir string `json:"WorkingDir,omitempty"`
+
+ // Labels contains arbitrary metadata for the container.
+ Labels map[string]string `json:"Labels,omitempty"`
+
+ // StopSignal contains the system call signal that will be sent to the container to exit.
+ StopSignal string `json:"StopSignal,omitempty"`
+}
+
+// RootFS describes a layer content addresses
+type RootFS struct {
+ // Type is the type of the rootfs.
+ Type string `json:"type"`
+
+ // DiffIDs is an array of layer content hashes (DiffIDs), in order from bottom-most to top-most.
+ DiffIDs []digest.Digest `json:"diff_ids"`
+}
+
+// History describes the history of a layer.
+type History struct {
+ // Created is the combined date and time at which the layer was created, formatted as defined by RFC 3339, section 5.6.
+ Created *time.Time `json:"created,omitempty"`
+
+ // CreatedBy is the command which created the layer.
+ CreatedBy string `json:"created_by,omitempty"`
+
+ // Author is the author of the build point.
+ Author string `json:"author,omitempty"`
+
+ // Comment is a custom message set when creating the layer.
+ Comment string `json:"comment,omitempty"`
+
+ // EmptyLayer is used to mark if the history item created a filesystem diff.
+ EmptyLayer bool `json:"empty_layer,omitempty"`
+}
+
+// Image is the JSON structure which describes some basic information about the image.
+// This provides the `application/vnd.oci.image.config.v1+json` mediatype when marshalled to JSON.
+type Image struct {
+ // Created is the combined date and time at which the image was created, formatted as defined by RFC 3339, section 5.6.
+ Created *time.Time `json:"created,omitempty"`
+
+ // Author defines the name and/or email address of the person or entity which created and is responsible for maintaining the image.
+ Author string `json:"author,omitempty"`
+
+ // Architecture is the CPU architecture which the binaries in this image are built to run on.
+ Architecture string `json:"architecture"`
+
+ // OS is the name of the operating system which the image is built to run on.
+ OS string `json:"os"`
+
+ // Config defines the execution parameters which should be used as a base when running a container using the image.
+ Config ImageConfig `json:"config,omitempty"`
+
+ // RootFS references the layer content addresses used by the image.
+ RootFS RootFS `json:"rootfs"`
+
+ // History describes the history of each layer.
+ History []History `json:"history,omitempty"`
+}
diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go
new file mode 100644
index 0000000..c461647
--- /dev/null
+++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go
@@ -0,0 +1,68 @@
+// Copyright 2016 The Linux Foundation
+//
+// 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 v1
+
+import digest "github.com/opencontainers/go-digest"
+
+// Descriptor describes the disposition of targeted content.
+// This structure provides `application/vnd.oci.descriptor.v1+json` mediatype
+// when marshalled to JSON.
+type Descriptor struct {
+ // MediaType is the media type of the object this schema refers to.
+ MediaType string `json:"mediaType,omitempty"`
+
+ // Digest is the digest of the targeted content.
+ Digest digest.Digest `json:"digest"`
+
+ // Size specifies the size in bytes of the blob.
+ Size int64 `json:"size"`
+
+ // URLs specifies a list of URLs from which this object MAY be downloaded
+ URLs []string `json:"urls,omitempty"`
+
+ // Annotations contains arbitrary metadata relating to the targeted content.
+ Annotations map[string]string `json:"annotations,omitempty"`
+
+ // Platform describes the platform which the image in the manifest runs on.
+ //
+ // This should only be used when referring to a manifest.
+ Platform *Platform `json:"platform,omitempty"`
+}
+
+// Platform describes the platform which the image in the manifest runs on.
+type Platform struct {
+ // Architecture field specifies the CPU architecture, for example
+ // `amd64` or `ppc64`.
+ Architecture string `json:"architecture"`
+
+ // OS specifies the operating system, for example `linux` or `windows`.
+ OS string `json:"os"`
+
+ // OSVersion is an optional field specifying the operating system
+ // version, for example `10.0.10586`.
+ OSVersion string `json:"os.version,omitempty"`
+
+ // OSFeatures is an optional field specifying an array of strings,
+ // each listing a required OS feature (for example on Windows `win32k`).
+ OSFeatures []string `json:"os.features,omitempty"`
+
+ // Variant is an optional field specifying a variant of the CPU, for
+ // example `ppc64le` to specify a little-endian version of a PowerPC CPU.
+ Variant string `json:"variant,omitempty"`
+
+ // Features is an optional field specifying an array of strings, each
+ // listing a required CPU feature (for example `sse4` or `aes`).
+ Features []string `json:"features,omitempty"`
+}
diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go
new file mode 100644
index 0000000..4e6c4b2
--- /dev/null
+++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go
@@ -0,0 +1,29 @@
+// Copyright 2016 The Linux Foundation
+//
+// 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 v1
+
+import "github.com/opencontainers/image-spec/specs-go"
+
+// Index references manifests for various platforms.
+// This structure provides `application/vnd.oci.image.index.v1+json` mediatype when marshalled to JSON.
+type Index struct {
+ specs.Versioned
+
+ // Manifests references platform specific manifests.
+ Manifests []Descriptor `json:"manifests"`
+
+ // Annotations contains arbitrary metadata for the image index.
+ Annotations map[string]string `json:"annotations,omitempty"`
+}
diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go
new file mode 100644
index 0000000..fc79e9e
--- /dev/null
+++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go
@@ -0,0 +1,28 @@
+// Copyright 2016 The Linux Foundation
+//
+// 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 v1
+
+const (
+ // ImageLayoutFile is the file name of oci image layout file
+ ImageLayoutFile = "oci-layout"
+ // ImageLayoutVersion is the version of ImageLayout
+ ImageLayoutVersion = "1.0.0"
+)
+
+// ImageLayout is the structure in the "oci-layout" file, found in the root
+// of an OCI Image-layout directory.
+type ImageLayout struct {
+ Version string `json:"imageLayoutVersion"`
+}
diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go
new file mode 100644
index 0000000..7ff32c4
--- /dev/null
+++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go
@@ -0,0 +1,32 @@
+// Copyright 2016 The Linux Foundation
+//
+// 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 v1
+
+import "github.com/opencontainers/image-spec/specs-go"
+
+// Manifest provides `application/vnd.oci.image.manifest.v1+json` mediatype structure when marshalled to JSON.
+type Manifest struct {
+ specs.Versioned
+
+ // Config references a configuration object for a container, by digest.
+ // The referenced configuration object is a JSON blob that the runtime uses to set up the container.
+ Config Descriptor `json:"config"`
+
+ // Layers is an indexed list of layers referenced by the manifest.
+ Layers []Descriptor `json:"layers"`
+
+ // Annotations contains arbitrary metadata for the image manifest.
+ Annotations map[string]string `json:"annotations,omitempty"`
+}
diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go
new file mode 100644
index 0000000..bad7bb9
--- /dev/null
+++ b/vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go
@@ -0,0 +1,48 @@
+// Copyright 2016 The Linux Foundation
+//
+// 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 v1
+
+const (
+ // MediaTypeDescriptor specifies the media type for a content descriptor.
+ MediaTypeDescriptor = "application/vnd.oci.descriptor.v1+json"
+
+ // MediaTypeLayoutHeader specifies the media type for the oci-layout.
+ MediaTypeLayoutHeader = "application/vnd.oci.layout.header.v1+json"
+
+ // MediaTypeImageManifest specifies the media type for an image manifest.
+ MediaTypeImageManifest = "application/vnd.oci.image.manifest.v1+json"
+
+ // MediaTypeImageIndex specifies the media type for an image index.
+ MediaTypeImageIndex = "application/vnd.oci.image.index.v1+json"
+
+ // MediaTypeImageLayer is the media type used for layers referenced by the manifest.
+ MediaTypeImageLayer = "application/vnd.oci.image.layer.v1.tar"
+
+ // MediaTypeImageLayerGzip is the media type used for gzipped layers
+ // referenced by the manifest.
+ MediaTypeImageLayerGzip = "application/vnd.oci.image.layer.v1.tar+gzip"
+
+ // MediaTypeImageLayerNonDistributable is the media type for layers referenced by
+ // the manifest but with distribution restrictions.
+ MediaTypeImageLayerNonDistributable = "application/vnd.oci.image.layer.nondistributable.v1.tar"
+
+ // MediaTypeImageLayerNonDistributableGzip is the media type for
+ // gzipped layers referenced by the manifest but with distribution
+ // restrictions.
+ MediaTypeImageLayerNonDistributableGzip = "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip"
+
+ // MediaTypeImageConfig specifies the media type for the image configuration.
+ MediaTypeImageConfig = "application/vnd.oci.image.config.v1+json"
+)
diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/version.go b/vendor/github.com/opencontainers/image-spec/specs-go/version.go
new file mode 100644
index 0000000..0e7d3be
--- /dev/null
+++ b/vendor/github.com/opencontainers/image-spec/specs-go/version.go
@@ -0,0 +1,32 @@
+// Copyright 2016 The Linux Foundation
+//
+// 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 specs
+
+import "fmt"
+
+const (
+ // VersionMajor is for an API incompatible changes
+ VersionMajor = 1
+ // VersionMinor is for functionality in a backwards-compatible manner
+ VersionMinor = 0
+ // VersionPatch is for backwards-compatible bug fixes
+ VersionPatch = 0
+
+ // VersionDev indicates development branch. Releases will be empty string.
+ VersionDev = "-rc5-dev"
+)
+
+// Version is the specification version that the package types support.
+var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev)
diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/versioned.go b/vendor/github.com/opencontainers/image-spec/specs-go/versioned.go
new file mode 100644
index 0000000..58a1510
--- /dev/null
+++ b/vendor/github.com/opencontainers/image-spec/specs-go/versioned.go
@@ -0,0 +1,23 @@
+// Copyright 2016 The Linux Foundation
+//
+// 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 specs
+
+// Versioned provides a struct with the manifest schemaVersion and mediaType.
+// Incoming content with unknown schema version can be decoded against this
+// struct to check the version.
+type Versioned struct {
+ // SchemaVersion is the image manifest schema that this image follows
+ SchemaVersion int `json:"schemaVersion"`
+}
diff --git a/vendor/github.com/opencontainers/runc/LICENSE b/vendor/github.com/opencontainers/runc/LICENSE
new file mode 100644
index 0000000..2744858
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2014 Docker, Inc.
+
+ 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/opencontainers/runc/NOTICE b/vendor/github.com/opencontainers/runc/NOTICE
new file mode 100644
index 0000000..5c97abc
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/NOTICE
@@ -0,0 +1,17 @@
+runc
+
+Copyright 2012-2015 Docker, Inc.
+
+This product includes software developed at Docker, Inc. (http://www.docker.com).
+
+The following is courtesy of our legal counsel:
+
+
+Use and transfer of Docker may be subject to certain restrictions by the
+United States and other governments.
+It is your responsibility to ensure that your use and/or transfer does not
+violate applicable laws.
+
+For more information, please see http://www.bis.doc.gov
+
+See also http://www.apache.org/dev/crypto.html and/or seek legal counsel.
diff --git a/vendor/github.com/opencontainers/runc/README.md b/vendor/github.com/opencontainers/runc/README.md
new file mode 100644
index 0000000..a951f0d
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/README.md
@@ -0,0 +1,222 @@
+# runc
+
+[![Build Status](https://travis-ci.org/opencontainers/runc.svg?branch=master)](https://travis-ci.org/opencontainers/runc)
+[![Go Report Card](https://goreportcard.com/badge/github.com/opencontainers/runc)](https://goreportcard.com/report/github.com/opencontainers/runc)
+[![GoDoc](https://godoc.org/github.com/opencontainers/runc?status.svg)](https://godoc.org/github.com/opencontainers/runc)
+
+## Introduction
+
+`runc` is a CLI tool for spawning and running containers according to the OCI specification.
+
+## Releases
+
+`runc` depends on and tracks the [runtime-spec](https://github.com/opencontainers/runtime-spec) repository.
+We will try to make sure that `runc` and the OCI specification major versions stay in lockstep.
+This means that `runc` 1.0.0 should implement the 1.0 version of the specification.
+
+You can find official releases of `runc` on the [release](https://github.com/opencontainers/runc/releases) page.
+
+### Security
+
+If you wish to report a security issue, please disclose the issue responsibly
+to security@opencontainers.org.
+
+## Building
+
+`runc` currently supports the Linux platform with various architecture support.
+It must be built with Go version 1.6 or higher in order for some features to function properly.
+
+In order to enable seccomp support you will need to install `libseccomp` on your platform.
+> e.g. `libseccomp-devel` for CentOS, or `libseccomp-dev` for Ubuntu
+
+Otherwise, if you do not want to build `runc` with seccomp support you can add `BUILDTAGS=""` when running make.
+
+```bash
+# create a 'github.com/opencontainers' in your GOPATH/src
+cd github.com/opencontainers
+git clone https://github.com/opencontainers/runc
+cd runc
+
+make
+sudo make install
+```
+
+`runc` will be installed to `/usr/local/sbin/runc` on your system.
+
+#### Build Tags
+
+`runc` supports optional build tags for compiling support of various features.
+To add build tags to the make option the `BUILDTAGS` variable must be set.
+
+```bash
+make BUILDTAGS='seccomp apparmor'
+```
+
+| Build Tag | Feature | Dependency |
+|-----------|------------------------------------|-------------|
+| seccomp | Syscall filtering | libseccomp |
+| selinux | selinux process and mount labeling | <none> |
+| apparmor | apparmor profile support | libapparmor |
+| ambient | ambient capability support | kernel 4.3 |
+
+
+### Running the test suite
+
+`runc` currently supports running its test suite via Docker.
+To run the suite just type `make test`.
+
+```bash
+make test
+```
+
+There are additional make targets for running the tests outside of a container but this is not recommended as the tests are written with the expectation that they can write and remove anywhere.
+
+You can run a specific test case by setting the `TESTFLAGS` variable.
+
+```bash
+# make test TESTFLAGS="-run=SomeTestFunction"
+```
+
+### Dependencies Management
+
+`runc` uses [vndr](https://github.com/LK4D4/vndr) for dependencies management.
+Please refer to [vndr](https://github.com/LK4D4/vndr) for how to add or update
+new dependencies.
+
+## Using runc
+
+### Creating an OCI Bundle
+
+In order to use runc you must have your container in the format of an OCI bundle.
+If you have Docker installed you can use its `export` method to acquire a root filesystem from an existing Docker container.
+
+```bash
+# create the top most bundle directory
+mkdir /mycontainer
+cd /mycontainer
+
+# create the rootfs directory
+mkdir rootfs
+
+# export busybox via Docker into the rootfs directory
+docker export $(docker create busybox) | tar -C rootfs -xvf -
+```
+
+After a root filesystem is populated you just generate a spec in the format of a `config.json` file inside your bundle.
+`runc` provides a `spec` command to generate a base template spec that you are then able to edit.
+To find features and documentation for fields in the spec please refer to the [specs](https://github.com/opencontainers/runtime-spec) repository.
+
+```bash
+runc spec
+```
+
+### Running Containers
+
+Assuming you have an OCI bundle from the previous step you can execute the container in two different ways.
+
+The first way is to use the convenience command `run` that will handle creating, starting, and deleting the container after it exits.
+
+```bash
+# run as root
+cd /mycontainer
+runc run mycontainerid
+```
+
+If you used the unmodified `runc spec` template this should give you a `sh` session inside the container.
+
+The second way to start a container is using the specs lifecycle operations.
+This gives you more power over how the container is created and managed while it is running.
+This will also launch the container in the background so you will have to edit the `config.json` to remove the `terminal` setting for the simple examples here.
+Your process field in the `config.json` should look like this below with `"terminal": false` and `"args": ["sleep", "5"]`.
+
+
+```json
+ "process": {
+ "terminal": false,
+ "user": {
+ "uid": 0,
+ "gid": 0
+ },
+ "args": [
+ "sleep", "5"
+ ],
+ "env": [
+ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
+ "TERM=xterm"
+ ],
+ "cwd": "/",
+ "capabilities": [
+ "CAP_AUDIT_WRITE",
+ "CAP_KILL",
+ "CAP_NET_BIND_SERVICE"
+ ],
+ "rlimits": [
+ {
+ "type": "RLIMIT_NOFILE",
+ "hard": 1024,
+ "soft": 1024
+ }
+ ],
+ "noNewPrivileges": true
+ },
+```
+
+Now we can go though the lifecycle operations in your shell.
+
+
+```bash
+# run as root
+cd /mycontainer
+runc create mycontainerid
+
+# view the container is created and in the "created" state
+runc list
+
+# start the process inside the container
+runc start mycontainerid
+
+# after 5 seconds view that the container has exited and is now in the stopped state
+runc list
+
+# now delete the container
+runc delete mycontainerid
+```
+
+This adds more complexity but allows higher level systems to manage runc and provides points in the containers creation to setup various settings after the container has created and/or before it is deleted.
+This is commonly used to setup the container's network stack after `create` but before `start` where the user's defined process will be running.
+
+#### Rootless containers
+`runc` has the ability to run containers without root privileges. This is called `rootless`. You need to pass some parameters to `runc` in order to run rootless containers. See below and compare with the previous version. Run the following commands as an ordinary user:
+```bash
+# Same as the first example
+mkdir ~/mycontainer
+cd ~/mycontainer
+mkdir rootfs
+docker export $(docker create busybox) | tar -C rootfs -xvf -
+
+# The --rootless parameter instructs runc spec to generate a configuration for a rootless container, which will allow you to run the container as a non-root user.
+runc spec --rootless
+
+# The --root parameter tells runc where to store the container state. It must be writable by the user.
+runc --root /tmp/runc run mycontainerid
+```
+
+#### Supervisors
+
+`runc` can be used with process supervisors and init systems to ensure that containers are restarted when they exit.
+An example systemd unit file looks something like this.
+
+```systemd
+[Unit]
+Description=Start My Container
+
+[Service]
+Type=forking
+ExecStart=/usr/local/sbin/runc run -d --pid-file /run/mycontainerid.pid mycontainerid
+ExecStopPost=/usr/local/sbin/runc delete mycontainerid
+WorkingDirectory=/mycontainer
+PIDFile=/run/mycontainerid.pid
+
+[Install]
+WantedBy=multi-user.target
+```
diff --git a/vendor/github.com/opencontainers/runc/VERSION b/vendor/github.com/opencontainers/runc/VERSION
new file mode 100644
index 0000000..3a17781
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/VERSION
@@ -0,0 +1 @@
+1.0.0-rc3
diff --git a/vendor/github.com/opencontainers/runc/checkpoint.go b/vendor/github.com/opencontainers/runc/checkpoint.go
new file mode 100644
index 0000000..7e8c866
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/checkpoint.go
@@ -0,0 +1,132 @@
+// +build linux
+
+package runc
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+ "syscall"
+
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/urfave/cli"
+)
+
+var checkpointCommand = cli.Command{
+ Name: "checkpoint",
+ Usage: "checkpoint a running container",
+ ArgsUsage: `<container-id>
+
+Where "<container-id>" is the name for the instance of the container to be
+checkpointed.`,
+ Description: `The checkpoint command saves the state of the container instance.`,
+ Flags: []cli.Flag{
+ cli.StringFlag{Name: "image-path", Value: "", Usage: "path for saving criu image files"},
+ cli.StringFlag{Name: "work-path", Value: "", Usage: "path for saving work files and logs"},
+ cli.StringFlag{Name: "parent-path", Value: "", Usage: "path for previous criu image files in pre-dump"},
+ cli.BoolFlag{Name: "leave-running", Usage: "leave the process running after checkpointing"},
+ cli.BoolFlag{Name: "tcp-established", Usage: "allow open tcp connections"},
+ cli.BoolFlag{Name: "ext-unix-sk", Usage: "allow external unix sockets"},
+ cli.BoolFlag{Name: "shell-job", Usage: "allow shell jobs"},
+ cli.StringFlag{Name: "page-server", Value: "", Usage: "ADDRESS:PORT of the page server"},
+ cli.BoolFlag{Name: "file-locks", Usage: "handle file locks, for safety"},
+ cli.BoolFlag{Name: "pre-dump", Usage: "dump container's memory information only, leave the container running after this"},
+ cli.StringFlag{Name: "manage-cgroups-mode", Value: "", Usage: "cgroups mode: 'soft' (default), 'full' and 'strict'"},
+ cli.StringSliceFlag{Name: "empty-ns", Usage: "create a namespace, but don't restore its properties"},
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+ // XXX: Currently this is untested with rootless containers.
+ if isRootless() {
+ return fmt.Errorf("runc checkpoint requires root")
+ }
+
+ container, err := getContainer(context)
+ if err != nil {
+ return err
+ }
+ status, err := container.Status()
+ if err != nil {
+ return err
+ }
+ if status == libcontainer.Created {
+ fatalf("Container cannot be checkpointed in created state")
+ }
+ defer destroy(container)
+ options := criuOptions(context)
+ // these are the mandatory criu options for a container
+ setPageServer(context, options)
+ setManageCgroupsMode(context, options)
+ if err := setEmptyNsMask(context, options); err != nil {
+ return err
+ }
+ if err := container.Checkpoint(options); err != nil {
+ return err
+ }
+ return nil
+ },
+}
+
+func getCheckpointImagePath(context *cli.Context) string {
+ imagePath := context.String("image-path")
+ if imagePath == "" {
+ imagePath = getDefaultImagePath(context)
+ }
+ return imagePath
+}
+
+func setPageServer(context *cli.Context, options *libcontainer.CriuOpts) {
+ // xxx following criu opts are optional
+ // The dump image can be sent to a criu page server
+ if psOpt := context.String("page-server"); psOpt != "" {
+ addressPort := strings.Split(psOpt, ":")
+ if len(addressPort) != 2 {
+ fatal(fmt.Errorf("Use --page-server ADDRESS:PORT to specify page server"))
+ }
+ portInt, err := strconv.Atoi(addressPort[1])
+ if err != nil {
+ fatal(fmt.Errorf("Invalid port number"))
+ }
+ options.PageServer = libcontainer.CriuPageServerInfo{
+ Address: addressPort[0],
+ Port: int32(portInt),
+ }
+ }
+}
+
+func setManageCgroupsMode(context *cli.Context, options *libcontainer.CriuOpts) {
+ if cgOpt := context.String("manage-cgroups-mode"); cgOpt != "" {
+ switch cgOpt {
+ case "soft":
+ options.ManageCgroupsMode = libcontainer.CRIU_CG_MODE_SOFT
+ case "full":
+ options.ManageCgroupsMode = libcontainer.CRIU_CG_MODE_FULL
+ case "strict":
+ options.ManageCgroupsMode = libcontainer.CRIU_CG_MODE_STRICT
+ default:
+ fatal(fmt.Errorf("Invalid manage cgroups mode"))
+ }
+ }
+}
+
+var namespaceMapping = map[specs.LinuxNamespaceType]int{
+ specs.NetworkNamespace: syscall.CLONE_NEWNET,
+}
+
+func setEmptyNsMask(context *cli.Context, options *libcontainer.CriuOpts) error {
+ var nsmask int
+
+ for _, ns := range context.StringSlice("empty-ns") {
+ f, exists := namespaceMapping[specs.LinuxNamespaceType(ns)]
+ if !exists {
+ return fmt.Errorf("namespace %q is not supported", ns)
+ }
+ nsmask |= f
+ }
+
+ options.EmptyNs = uint32(nsmask)
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/create.go b/vendor/github.com/opencontainers/runc/create.go
new file mode 100644
index 0000000..4c0973f
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/create.go
@@ -0,0 +1,74 @@
+package runc
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+var createCommand = cli.Command{
+ Name: "create",
+ Usage: "create a container",
+ ArgsUsage: `<container-id>
+
+Where "<container-id>" is your name for the instance of the container that you
+are starting. The name you provide for the container instance must be unique on
+your host.`,
+ Description: `The create command creates an instance of a container for a bundle. The bundle
+is a directory with a specification file named "` + specConfig + `" and a root
+filesystem.
+
+The specification file includes an args parameter. The args parameter is used
+to specify command(s) that get run when the container is started. To change the
+command(s) that get executed on start, edit the args parameter of the spec. See
+"runc spec --help" for more explanation.`,
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "bundle, b",
+ Value: "",
+ Usage: `path to the root of the bundle directory, defaults to the current directory`,
+ },
+ cli.StringFlag{
+ Name: "console-socket",
+ Value: "",
+ Usage: "path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal",
+ },
+ cli.StringFlag{
+ Name: "pid-file",
+ Value: "",
+ Usage: "specify the file to write the process id to",
+ },
+ cli.BoolFlag{
+ Name: "no-pivot",
+ Usage: "do not use pivot root to jail process inside rootfs. This should be used whenever the rootfs is on top of a ramdisk",
+ },
+ cli.BoolFlag{
+ Name: "no-new-keyring",
+ Usage: "do not create a new session keyring for the container. This will cause the container to inherit the calling processes session key",
+ },
+ cli.IntFlag{
+ Name: "preserve-fds",
+ Usage: "Pass N additional file descriptors to the container (stdio + $LISTEN_FDS + N in total)",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+ if err := revisePidFile(context); err != nil {
+ return err
+ }
+ spec, err := setupSpec(context)
+ if err != nil {
+ return err
+ }
+ status, err := startContainer(context, spec, true)
+ if err != nil {
+ return err
+ }
+ // exit with the container's exit status so any external supervisor is
+ // notified of the exit with the correct exit status.
+ os.Exit(status)
+ return nil
+ },
+}
diff --git a/vendor/github.com/opencontainers/runc/delete.go b/vendor/github.com/opencontainers/runc/delete.go
new file mode 100644
index 0000000..5e45750
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/delete.go
@@ -0,0 +1,84 @@
+// +build !solaris
+
+package runc
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "syscall"
+ "time"
+
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/urfave/cli"
+)
+
+func killContainer(container libcontainer.Container) error {
+ _ = container.Signal(syscall.SIGKILL, false)
+ for i := 0; i < 100; i++ {
+ time.Sleep(100 * time.Millisecond)
+ if err := container.Signal(syscall.Signal(0), false); err != nil {
+ destroy(container)
+ return nil
+ }
+ }
+ return fmt.Errorf("container init still running")
+}
+
+var deleteCommand = cli.Command{
+ Name: "delete",
+ Usage: "delete any resources held by the container often used with detached container",
+ ArgsUsage: `<container-id>
+
+Where "<container-id>" is the name for the instance of the container.
+
+EXAMPLE:
+For example, if the container id is "ubuntu01" and runc list currently shows the
+status of "ubuntu01" as "stopped" the following will delete resources held for
+"ubuntu01" removing "ubuntu01" from the runc list of containers:
+
+ # runc delete ubuntu01`,
+ Flags: []cli.Flag{
+ cli.BoolFlag{
+ Name: "force, f",
+ Usage: "Forcibly deletes the container if it is still running (uses SIGKILL)",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+
+ id := context.Args().First()
+ container, err := getContainer(context)
+ if err != nil {
+ if lerr, ok := err.(libcontainer.Error); ok && lerr.Code() == libcontainer.ContainerNotExists {
+ // if there was an aborted start or something of the sort then the container's directory could exist but
+ // libcontainer does not see it because the state.json file inside that directory was never created.
+ path := filepath.Join(context.GlobalString("root"), id)
+ if e := os.RemoveAll(path); e != nil {
+ fmt.Fprintf(os.Stderr, "remove %s: %v\n", path, e)
+ }
+ }
+ return err
+ }
+ s, err := container.Status()
+ if err != nil {
+ return err
+ }
+ switch s {
+ case libcontainer.Stopped:
+ destroy(container)
+ case libcontainer.Created:
+ return killContainer(container)
+ default:
+ if context.Bool("force") {
+ return killContainer(container)
+ } else {
+ return fmt.Errorf("cannot delete container %s that is not stopped: %s\n", id, s)
+ }
+ }
+
+ return nil
+ },
+}
diff --git a/vendor/github.com/opencontainers/runc/events.go b/vendor/github.com/opencontainers/runc/events.go
new file mode 100644
index 0000000..e73f8dd
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/events.go
@@ -0,0 +1,260 @@
+// +build linux
+
+package runc
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "sync"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/urfave/cli"
+)
+
+// event struct for encoding the event data to json.
+type event struct {
+ Type string `json:"type"`
+ ID string `json:"id"`
+ Data interface{} `json:"data,omitempty"`
+}
+
+// stats is the runc specific stats structure for stability when encoding and decoding stats.
+type stats struct {
+ CPU cpu `json:"cpu"`
+ Memory memory `json:"memory"`
+ Pids pids `json:"pids"`
+ Blkio blkio `json:"blkio"`
+ Hugetlb map[string]hugetlb `json:"hugetlb"`
+}
+
+type hugetlb struct {
+ Usage uint64 `json:"usage,omitempty"`
+ Max uint64 `json:"max,omitempty"`
+ Failcnt uint64 `json:"failcnt"`
+}
+
+type blkioEntry struct {
+ Major uint64 `json:"major,omitempty"`
+ Minor uint64 `json:"minor,omitempty"`
+ Op string `json:"op,omitempty"`
+ Value uint64 `json:"value,omitempty"`
+}
+
+type blkio struct {
+ IoServiceBytesRecursive []blkioEntry `json:"ioServiceBytesRecursive,omitempty"`
+ IoServicedRecursive []blkioEntry `json:"ioServicedRecursive,omitempty"`
+ IoQueuedRecursive []blkioEntry `json:"ioQueueRecursive,omitempty"`
+ IoServiceTimeRecursive []blkioEntry `json:"ioServiceTimeRecursive,omitempty"`
+ IoWaitTimeRecursive []blkioEntry `json:"ioWaitTimeRecursive,omitempty"`
+ IoMergedRecursive []blkioEntry `json:"ioMergedRecursive,omitempty"`
+ IoTimeRecursive []blkioEntry `json:"ioTimeRecursive,omitempty"`
+ SectorsRecursive []blkioEntry `json:"sectorsRecursive,omitempty"`
+}
+
+type pids struct {
+ Current uint64 `json:"current,omitempty"`
+ Limit uint64 `json:"limit,omitempty"`
+}
+
+type throttling struct {
+ Periods uint64 `json:"periods,omitempty"`
+ ThrottledPeriods uint64 `json:"throttledPeriods,omitempty"`
+ ThrottledTime uint64 `json:"throttledTime,omitempty"`
+}
+
+type cpuUsage struct {
+ // Units: nanoseconds.
+ Total uint64 `json:"total,omitempty"`
+ Percpu []uint64 `json:"percpu,omitempty"`
+ Kernel uint64 `json:"kernel"`
+ User uint64 `json:"user"`
+}
+
+type cpu struct {
+ Usage cpuUsage `json:"usage,omitempty"`
+ Throttling throttling `json:"throttling,omitempty"`
+}
+
+type memoryEntry struct {
+ Limit uint64 `json:"limit"`
+ Usage uint64 `json:"usage,omitempty"`
+ Max uint64 `json:"max,omitempty"`
+ Failcnt uint64 `json:"failcnt"`
+}
+
+type memory struct {
+ Cache uint64 `json:"cache,omitempty"`
+ Usage memoryEntry `json:"usage,omitempty"`
+ Swap memoryEntry `json:"swap,omitempty"`
+ Kernel memoryEntry `json:"kernel,omitempty"`
+ KernelTCP memoryEntry `json:"kernelTCP,omitempty"`
+ Raw map[string]uint64 `json:"raw,omitempty"`
+}
+
+var eventsCommand = cli.Command{
+ Name: "events",
+ Usage: "display container events such as OOM notifications, cpu, memory, and IO usage statistics",
+ ArgsUsage: `<container-id>
+
+Where "<container-id>" is the name for the instance of the container.`,
+ Description: `The events command displays information about the container. By default the
+information is displayed once every 5 seconds.`,
+ Flags: []cli.Flag{
+ cli.DurationFlag{Name: "interval", Value: 5 * time.Second, Usage: "set the stats collection interval"},
+ cli.BoolFlag{Name: "stats", Usage: "display the container's stats then exit"},
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+ container, err := getContainer(context)
+ if err != nil {
+ return err
+ }
+ duration := context.Duration("interval")
+ if duration <= 0 {
+ return fmt.Errorf("duration interval must be greater than 0")
+ }
+ status, err := container.Status()
+ if err != nil {
+ return err
+ }
+ if status == libcontainer.Stopped {
+ return fmt.Errorf("container with id %s is not running", container.ID())
+ }
+ var (
+ stats = make(chan *libcontainer.Stats, 1)
+ events = make(chan *event, 1024)
+ group = &sync.WaitGroup{}
+ )
+ group.Add(1)
+ go func() {
+ defer group.Done()
+ enc := json.NewEncoder(os.Stdout)
+ for e := range events {
+ if err := enc.Encode(e); err != nil {
+ logrus.Error(err)
+ }
+ }
+ }()
+ if context.Bool("stats") {
+ s, err := container.Stats()
+ if err != nil {
+ return err
+ }
+ events <- &event{Type: "stats", ID: container.ID(), Data: convertLibcontainerStats(s)}
+ close(events)
+ group.Wait()
+ return nil
+ }
+ go func() {
+ for range time.Tick(context.Duration("interval")) {
+ s, err := container.Stats()
+ if err != nil {
+ logrus.Error(err)
+ continue
+ }
+ stats <- s
+ }
+ }()
+ n, err := container.NotifyOOM()
+ if err != nil {
+ return err
+ }
+ for {
+ select {
+ case _, ok := <-n:
+ if ok {
+ // this means an oom event was received, if it is !ok then
+ // the channel was closed because the container stopped and
+ // the cgroups no longer exist.
+ events <- &event{Type: "oom", ID: container.ID()}
+ } else {
+ n = nil
+ }
+ case s := <-stats:
+ events <- &event{Type: "stats", ID: container.ID(), Data: convertLibcontainerStats(s)}
+ }
+ if n == nil {
+ close(events)
+ break
+ }
+ }
+ group.Wait()
+ return nil
+ },
+}
+
+func convertLibcontainerStats(ls *libcontainer.Stats) *stats {
+ cg := ls.CgroupStats
+ if cg == nil {
+ return nil
+ }
+ var s stats
+ s.Pids.Current = cg.PidsStats.Current
+ s.Pids.Limit = cg.PidsStats.Limit
+
+ s.CPU.Usage.Kernel = cg.CpuStats.CpuUsage.UsageInKernelmode
+ s.CPU.Usage.User = cg.CpuStats.CpuUsage.UsageInUsermode
+ s.CPU.Usage.Total = cg.CpuStats.CpuUsage.TotalUsage
+ s.CPU.Usage.Percpu = cg.CpuStats.CpuUsage.PercpuUsage
+ s.CPU.Throttling.Periods = cg.CpuStats.ThrottlingData.Periods
+ s.CPU.Throttling.ThrottledPeriods = cg.CpuStats.ThrottlingData.ThrottledPeriods
+ s.CPU.Throttling.ThrottledTime = cg.CpuStats.ThrottlingData.ThrottledTime
+
+ s.Memory.Cache = cg.MemoryStats.Cache
+ s.Memory.Kernel = convertMemoryEntry(cg.MemoryStats.KernelUsage)
+ s.Memory.KernelTCP = convertMemoryEntry(cg.MemoryStats.KernelTCPUsage)
+ s.Memory.Swap = convertMemoryEntry(cg.MemoryStats.SwapUsage)
+ s.Memory.Usage = convertMemoryEntry(cg.MemoryStats.Usage)
+ s.Memory.Raw = cg.MemoryStats.Stats
+
+ s.Blkio.IoServiceBytesRecursive = convertBlkioEntry(cg.BlkioStats.IoServiceBytesRecursive)
+ s.Blkio.IoServicedRecursive = convertBlkioEntry(cg.BlkioStats.IoServicedRecursive)
+ s.Blkio.IoQueuedRecursive = convertBlkioEntry(cg.BlkioStats.IoQueuedRecursive)
+ s.Blkio.IoServiceTimeRecursive = convertBlkioEntry(cg.BlkioStats.IoServiceTimeRecursive)
+ s.Blkio.IoWaitTimeRecursive = convertBlkioEntry(cg.BlkioStats.IoWaitTimeRecursive)
+ s.Blkio.IoMergedRecursive = convertBlkioEntry(cg.BlkioStats.IoMergedRecursive)
+ s.Blkio.IoTimeRecursive = convertBlkioEntry(cg.BlkioStats.IoTimeRecursive)
+ s.Blkio.SectorsRecursive = convertBlkioEntry(cg.BlkioStats.SectorsRecursive)
+
+ s.Hugetlb = make(map[string]hugetlb)
+ for k, v := range cg.HugetlbStats {
+ s.Hugetlb[k] = convertHugtlb(v)
+ }
+ return &s
+}
+
+func convertHugtlb(c cgroups.HugetlbStats) hugetlb {
+ return hugetlb{
+ Usage: c.Usage,
+ Max: c.MaxUsage,
+ Failcnt: c.Failcnt,
+ }
+}
+
+func convertMemoryEntry(c cgroups.MemoryData) memoryEntry {
+ return memoryEntry{
+ Limit: c.Limit,
+ Usage: c.Usage,
+ Max: c.MaxUsage,
+ Failcnt: c.Failcnt,
+ }
+}
+
+func convertBlkioEntry(c []cgroups.BlkioStatEntry) []blkioEntry {
+ var out []blkioEntry
+ for _, e := range c {
+ out = append(out, blkioEntry{
+ Major: e.Major,
+ Minor: e.Minor,
+ Op: e.Op,
+ Value: e.Value,
+ })
+ }
+ return out
+}
diff --git a/vendor/github.com/opencontainers/runc/exec.go b/vendor/github.com/opencontainers/runc/exec.go
new file mode 100644
index 0000000..800763c
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/exec.go
@@ -0,0 +1,211 @@
+// +build linux
+
+package runc
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/opencontainers/runc/libcontainer/utils"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/urfave/cli"
+)
+
+var execCommand = cli.Command{
+ Name: "exec",
+ Usage: "execute new process inside the container",
+ ArgsUsage: `<container-id> <command> [command options] || -p process.json <container-id>
+
+Where "<container-id>" is the name for the instance of the container and
+"<command>" is the command to be executed in the container.
+"<command>" can't be empty unless a "-p" flag provided.
+
+EXAMPLE:
+For example, if the container is configured to run the linux ps command the
+following will output a list of processes running in the container:
+
+ # runc exec <container-id> ps`,
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "console-socket",
+ Usage: "path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal",
+ },
+ cli.StringFlag{
+ Name: "cwd",
+ Usage: "current working directory in the container",
+ },
+ cli.StringSliceFlag{
+ Name: "env, e",
+ Usage: "set environment variables",
+ },
+ cli.BoolFlag{
+ Name: "tty, t",
+ Usage: "allocate a pseudo-TTY",
+ },
+ cli.StringFlag{
+ Name: "user, u",
+ Usage: "UID (format: <uid>[:<gid>])",
+ },
+ cli.StringFlag{
+ Name: "process, p",
+ Usage: "path to the process.json",
+ },
+ cli.BoolFlag{
+ Name: "detach,d",
+ Usage: "detach from the container's process",
+ },
+ cli.StringFlag{
+ Name: "pid-file",
+ Value: "",
+ Usage: "specify the file to write the process id to",
+ },
+ cli.StringFlag{
+ Name: "process-label",
+ Usage: "set the asm process label for the process commonly used with selinux",
+ },
+ cli.StringFlag{
+ Name: "apparmor",
+ Usage: "set the apparmor profile for the process",
+ },
+ cli.BoolFlag{
+ Name: "no-new-privs",
+ Usage: "set the no new privileges value for the process",
+ },
+ cli.StringSliceFlag{
+ Name: "cap, c",
+ Value: &cli.StringSlice{},
+ Usage: "add a capability to the bounding set for the process",
+ },
+ cli.BoolFlag{
+ Name: "no-subreaper",
+ Usage: "disable the use of the subreaper used to reap reparented processes",
+ Hidden: true,
+ },
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, minArgs); err != nil {
+ return err
+ }
+ if err := revisePidFile(context); err != nil {
+ return err
+ }
+ status, err := execProcess(context)
+ if err == nil {
+ os.Exit(status)
+ }
+ return fmt.Errorf("exec failed: %v", err)
+ },
+ SkipArgReorder: true,
+}
+
+func execProcess(context *cli.Context) (int, error) {
+ container, err := getContainer(context)
+ if err != nil {
+ return -1, err
+ }
+ status, err := container.Status()
+ if err != nil {
+ return -1, err
+ }
+ if status == libcontainer.Stopped {
+ return -1, fmt.Errorf("cannot exec a container that has stopped")
+ }
+ path := context.String("process")
+ if path == "" && len(context.Args()) == 1 {
+ return -1, fmt.Errorf("process args cannot be empty")
+ }
+ detach := context.Bool("detach")
+ state, err := container.State()
+ if err != nil {
+ return -1, err
+ }
+ bundle := utils.SearchLabels(state.Config.Labels, "bundle")
+ p, err := getProcess(context, bundle)
+ if err != nil {
+ return -1, err
+ }
+ r := &runner{
+ enableSubreaper: false,
+ shouldDestroy: false,
+ container: container,
+ consoleSocket: context.String("console-socket"),
+ detach: detach,
+ pidFile: context.String("pid-file"),
+ }
+ return r.run(p)
+}
+
+func getProcess(context *cli.Context, bundle string) (*specs.Process, error) {
+ if path := context.String("process"); path != "" {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ var p specs.Process
+ if err := json.NewDecoder(f).Decode(&p); err != nil {
+ return nil, err
+ }
+ return &p, validateProcessSpec(&p)
+ }
+ // process via cli flags
+ if err := os.Chdir(bundle); err != nil {
+ return nil, err
+ }
+ spec, err := loadSpec(specConfig)
+ if err != nil {
+ return nil, err
+ }
+ p := spec.Process
+ p.Args = context.Args()[1:]
+ // override the cwd, if passed
+ if context.String("cwd") != "" {
+ p.Cwd = context.String("cwd")
+ }
+ if ap := context.String("apparmor"); ap != "" {
+ p.ApparmorProfile = ap
+ }
+ if l := context.String("process-label"); l != "" {
+ p.SelinuxLabel = l
+ }
+ if caps := context.StringSlice("cap"); len(caps) > 0 {
+ for _, c := range caps {
+ p.Capabilities.Bounding = append(p.Capabilities.Bounding, c)
+ p.Capabilities.Inheritable = append(p.Capabilities.Inheritable, c)
+ p.Capabilities.Effective = append(p.Capabilities.Effective, c)
+ p.Capabilities.Permitted = append(p.Capabilities.Permitted, c)
+ p.Capabilities.Ambient = append(p.Capabilities.Ambient, c)
+ }
+ }
+ // append the passed env variables
+ p.Env = append(p.Env, context.StringSlice("env")...)
+
+ // set the tty
+ if context.IsSet("tty") {
+ p.Terminal = context.Bool("tty")
+ }
+ if context.IsSet("no-new-privs") {
+ p.NoNewPrivileges = context.Bool("no-new-privs")
+ }
+ // override the user, if passed
+ if context.String("user") != "" {
+ u := strings.SplitN(context.String("user"), ":", 2)
+ if len(u) > 1 {
+ gid, err := strconv.Atoi(u[1])
+ if err != nil {
+ return nil, fmt.Errorf("parsing %s as int for gid failed: %v", u[1], err)
+ }
+ p.User.GID = uint32(gid)
+ }
+ uid, err := strconv.Atoi(u[0])
+ if err != nil {
+ return nil, fmt.Errorf("parsing %s as int for uid failed: %v", u[0], err)
+ }
+ p.User.UID = uint32(uid)
+ }
+ return &p, nil
+}
diff --git a/vendor/github.com/opencontainers/runc/kill.go b/vendor/github.com/opencontainers/runc/kill.go
new file mode 100644
index 0000000..6ca7083
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/kill.go
@@ -0,0 +1,115 @@
+// +build linux
+
+package runc
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+ "syscall"
+
+ "github.com/urfave/cli"
+)
+
+var signalMap = map[string]syscall.Signal{
+ "ABRT": syscall.SIGABRT,
+ "ALRM": syscall.SIGALRM,
+ "BUS": syscall.SIGBUS,
+ "CHLD": syscall.SIGCHLD,
+ "CLD": syscall.SIGCLD,
+ "CONT": syscall.SIGCONT,
+ "FPE": syscall.SIGFPE,
+ "HUP": syscall.SIGHUP,
+ "ILL": syscall.SIGILL,
+ "INT": syscall.SIGINT,
+ "IO": syscall.SIGIO,
+ "IOT": syscall.SIGIOT,
+ "KILL": syscall.SIGKILL,
+ "PIPE": syscall.SIGPIPE,
+ "POLL": syscall.SIGPOLL,
+ "PROF": syscall.SIGPROF,
+ "PWR": syscall.SIGPWR,
+ "QUIT": syscall.SIGQUIT,
+ "SEGV": syscall.SIGSEGV,
+ "STKFLT": syscall.SIGSTKFLT,
+ "STOP": syscall.SIGSTOP,
+ "SYS": syscall.SIGSYS,
+ "TERM": syscall.SIGTERM,
+ "TRAP": syscall.SIGTRAP,
+ "TSTP": syscall.SIGTSTP,
+ "TTIN": syscall.SIGTTIN,
+ "TTOU": syscall.SIGTTOU,
+ "UNUSED": syscall.SIGUNUSED,
+ "URG": syscall.SIGURG,
+ "USR1": syscall.SIGUSR1,
+ "USR2": syscall.SIGUSR2,
+ "VTALRM": syscall.SIGVTALRM,
+ "WINCH": syscall.SIGWINCH,
+ "XCPU": syscall.SIGXCPU,
+ "XFSZ": syscall.SIGXFSZ,
+}
+
+var killCommand = cli.Command{
+ Name: "kill",
+ Usage: "kill sends the specified signal (default: SIGTERM) to the container's init process",
+ ArgsUsage: `<container-id> [signal]
+
+Where "<container-id>" is the name for the instance of the container and
+"[signal]" is the signal to be sent to the init process.
+
+EXAMPLE:
+For example, if the container id is "ubuntu01" the following will send a "KILL"
+signal to the init process of the "ubuntu01" container:
+
+ # runc kill ubuntu01 KILL`,
+ Flags: []cli.Flag{
+ cli.BoolFlag{
+ Name: "all, a",
+ Usage: "send the specified signal to all processes inside the container",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, minArgs); err != nil {
+ return err
+ }
+ if err := checkArgs(context, 2, maxArgs); err != nil {
+ return err
+ }
+ container, err := getContainer(context)
+ if err != nil {
+ return err
+ }
+
+ sigstr := context.Args().Get(1)
+ if sigstr == "" {
+ sigstr = "SIGTERM"
+ }
+
+ signal, err := parseSignal(sigstr)
+ if err != nil {
+ return err
+ }
+ if err := container.Signal(signal, context.Bool("all")); err != nil {
+ return err
+ }
+ return nil
+ },
+}
+
+func parseSignal(rawSignal string) (syscall.Signal, error) {
+ s, err := strconv.Atoi(rawSignal)
+ if err == nil {
+ sig := syscall.Signal(s)
+ for _, msig := range signalMap {
+ if sig == msig {
+ return sig, nil
+ }
+ }
+ return -1, fmt.Errorf("unknown signal %q", rawSignal)
+ }
+ signal, ok := signalMap[strings.TrimPrefix(strings.ToUpper(rawSignal), "SIG")]
+ if !ok {
+ return -1, fmt.Errorf("unknown signal %q", rawSignal)
+ }
+ return signal, nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/README.md b/vendor/github.com/opencontainers/runc/libcontainer/README.md
new file mode 100644
index 0000000..d2a7d78
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/README.md
@@ -0,0 +1,262 @@
+# libcontainer
+
+[![GoDoc](https://godoc.org/github.com/opencontainers/runc/libcontainer?status.svg)](https://godoc.org/github.com/opencontainers/runc/libcontainer)
+
+Libcontainer provides a native Go implementation for creating containers
+with namespaces, cgroups, capabilities, and filesystem access controls.
+It allows you to manage the lifecycle of the container performing additional operations
+after the container is created.
+
+
+#### Container
+A container is a self contained execution environment that shares the kernel of the
+host system and which is (optionally) isolated from other containers in the system.
+
+#### Using libcontainer
+
+Because containers are spawned in a two step process you will need a binary that
+will be executed as the init process for the container. In libcontainer, we use
+the current binary (/proc/self/exe) to be executed as the init process, and use
+arg "init", we call the first step process "bootstrap", so you always need a "init"
+function as the entry of "bootstrap".
+
+In addition to the go init function the early stage bootstrap is handled by importing
+[nsenter](https://github.com/opencontainers/runc/blob/master/libcontainer/nsenter/README.md).
+
+```go
+import (
+ _ "github.com/opencontainers/runc/libcontainer/nsenter"
+)
+
+func init() {
+ if len(os.Args) > 1 && os.Args[1] == "init" {
+ runtime.GOMAXPROCS(1)
+ runtime.LockOSThread()
+ factory, _ := libcontainer.New("")
+ if err := factory.StartInitialization(); err != nil {
+ logrus.Fatal(err)
+ }
+ panic("--this line should have never been executed, congratulations--")
+ }
+}
+```
+
+Then to create a container you first have to initialize an instance of a factory
+that will handle the creation and initialization for a container.
+
+```go
+factory, err := libcontainer.New("/var/lib/container", libcontainer.Cgroupfs, libcontainer.InitArgs(os.Args[0], "init"))
+if err != nil {
+ logrus.Fatal(err)
+ return
+}
+```
+
+Once you have an instance of the factory created we can create a configuration
+struct describing how the container is to be created. A sample would look similar to this:
+
+```go
+defaultMountFlags := syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV
+config := &configs.Config{
+ Rootfs: "/your/path/to/rootfs",
+ Capabilities: []string{
+ "CAP_CHOWN",
+ "CAP_DAC_OVERRIDE",
+ "CAP_FSETID",
+ "CAP_FOWNER",
+ "CAP_MKNOD",
+ "CAP_NET_RAW",
+ "CAP_SETGID",
+ "CAP_SETUID",
+ "CAP_SETFCAP",
+ "CAP_SETPCAP",
+ "CAP_NET_BIND_SERVICE",
+ "CAP_SYS_CHROOT",
+ "CAP_KILL",
+ "CAP_AUDIT_WRITE",
+ },
+ Namespaces: configs.Namespaces([]configs.Namespace{
+ {Type: configs.NEWNS},
+ {Type: configs.NEWUTS},
+ {Type: configs.NEWIPC},
+ {Type: configs.NEWPID},
+ {Type: configs.NEWUSER},
+ {Type: configs.NEWNET},
+ }),
+ Cgroups: &configs.Cgroup{
+ Name: "test-container",
+ Parent: "system",
+ Resources: &configs.Resources{
+ MemorySwappiness: nil,
+ AllowAllDevices: nil,
+ AllowedDevices: configs.DefaultAllowedDevices,
+ },
+ },
+ MaskPaths: []string{
+ "/proc/kcore",
+ "/sys/firmware",
+ },
+ ReadonlyPaths: []string{
+ "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus",
+ },
+ Devices: configs.DefaultAutoCreatedDevices,
+ Hostname: "testing",
+ Mounts: []*configs.Mount{
+ {
+ Source: "proc",
+ Destination: "/proc",
+ Device: "proc",
+ Flags: defaultMountFlags,
+ },
+ {
+ Source: "tmpfs",
+ Destination: "/dev",
+ Device: "tmpfs",
+ Flags: syscall.MS_NOSUID | syscall.MS_STRICTATIME,
+ Data: "mode=755",
+ },
+ {
+ Source: "devpts",
+ Destination: "/dev/pts",
+ Device: "devpts",
+ Flags: syscall.MS_NOSUID | syscall.MS_NOEXEC,
+ Data: "newinstance,ptmxmode=0666,mode=0620,gid=5",
+ },
+ {
+ Device: "tmpfs",
+ Source: "shm",
+ Destination: "/dev/shm",
+ Data: "mode=1777,size=65536k",
+ Flags: defaultMountFlags,
+ },
+ {
+ Source: "mqueue",
+ Destination: "/dev/mqueue",
+ Device: "mqueue",
+ Flags: defaultMountFlags,
+ },
+ {
+ Source: "sysfs",
+ Destination: "/sys",
+ Device: "sysfs",
+ Flags: defaultMountFlags | syscall.MS_RDONLY,
+ },
+ },
+ UidMappings: []configs.IDMap{
+ {
+ ContainerID: 0,
+ HostID: 1000,
+ Size: 65536,
+ },
+ },
+ GidMappings: []configs.IDMap{
+ {
+ ContainerID: 0,
+ HostID: 1000,
+ Size: 65536,
+ },
+ },
+ Networks: []*configs.Network{
+ {
+ Type: "loopback",
+ Address: "127.0.0.1/0",
+ Gateway: "localhost",
+ },
+ },
+ Rlimits: []configs.Rlimit{
+ {
+ Type: syscall.RLIMIT_NOFILE,
+ Hard: uint64(1025),
+ Soft: uint64(1025),
+ },
+ },
+}
+```
+
+Once you have the configuration populated you can create a container:
+
+```go
+container, err := factory.Create("container-id", config)
+if err != nil {
+ logrus.Fatal(err)
+ return
+}
+```
+
+To spawn bash as the initial process inside the container and have the
+processes pid returned in order to wait, signal, or kill the process:
+
+```go
+process := &libcontainer.Process{
+ Args: []string{"/bin/bash"},
+ Env: []string{"PATH=/bin"},
+ User: "daemon",
+ Stdin: os.Stdin,
+ Stdout: os.Stdout,
+ Stderr: os.Stderr,
+}
+
+err := container.Run(process)
+if err != nil {
+ container.Destroy()
+ logrus.Fatal(err)
+ return
+}
+
+// wait for the process to finish.
+_, err := process.Wait()
+if err != nil {
+ logrus.Fatal(err)
+}
+
+// destroy the container.
+container.Destroy()
+```
+
+Additional ways to interact with a running container are:
+
+```go
+// return all the pids for all processes running inside the container.
+processes, err := container.Processes()
+
+// get detailed cpu, memory, io, and network statistics for the container and
+// it's processes.
+stats, err := container.Stats()
+
+// pause all processes inside the container.
+container.Pause()
+
+// resume all paused processes.
+container.Resume()
+
+// send signal to container's init process.
+container.Signal(signal)
+
+// update container resource constraints.
+container.Set(config)
+
+// get current status of the container.
+status, err := container.Status()
+
+// get current container's state information.
+state, err := container.State()
+```
+
+
+#### Checkpoint & Restore
+
+libcontainer now integrates [CRIU](http://criu.org/) for checkpointing and restoring containers.
+This let's you save the state of a process running inside a container to disk, and then restore
+that state into a new process, on the same machine or on another machine.
+
+`criu` version 1.5.2 or higher is required to use checkpoint and restore.
+If you don't already have `criu` installed, you can build it from source, following the
+[online instructions](http://criu.org/Installation). `criu` is also installed in the docker image
+generated when building libcontainer with docker.
+
+
+## Copyright and license
+
+Code and documentation copyright 2014 Docker, inc. Code released under the Apache 2.0 license.
+Docs released under Creative commons.
+
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor.go b/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor.go
new file mode 100644
index 0000000..82ed1a6
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor.go
@@ -0,0 +1,39 @@
+// +build apparmor,linux
+
+package apparmor
+
+// #cgo LDFLAGS: -lapparmor
+// #include <sys/apparmor.h>
+// #include <stdlib.h>
+import "C"
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "unsafe"
+)
+
+// IsEnabled returns true if apparmor is enabled for the host.
+func IsEnabled() bool {
+ if _, err := os.Stat("/sys/kernel/security/apparmor"); err == nil && os.Getenv("container") == "" {
+ if _, err = os.Stat("/sbin/apparmor_parser"); err == nil {
+ buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled")
+ return err == nil && len(buf) > 1 && buf[0] == 'Y'
+ }
+ }
+ return false
+}
+
+// ApplyProfile will apply the profile with the specified name to the process after
+// the next exec.
+func ApplyProfile(name string) error {
+ if name == "" {
+ return nil
+ }
+ cName := C.CString(name)
+ defer C.free(unsafe.Pointer(cName))
+ if _, err := C.aa_change_onexec(cName); err != nil {
+ return fmt.Errorf("apparmor failed to apply profile: %s", err)
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor_disabled.go b/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor_disabled.go
new file mode 100644
index 0000000..d4110cf
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor_disabled.go
@@ -0,0 +1,20 @@
+// +build !apparmor !linux
+
+package apparmor
+
+import (
+ "errors"
+)
+
+var ErrApparmorNotEnabled = errors.New("apparmor: config provided but apparmor not supported")
+
+func IsEnabled() bool {
+ return false
+}
+
+func ApplyProfile(name string) error {
+ if name != "" {
+ return ErrApparmorNotEnabled
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/capabilities_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/capabilities_linux.go
new file mode 100644
index 0000000..8981b2a
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/capabilities_linux.go
@@ -0,0 +1,114 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/syndtr/gocapability/capability"
+)
+
+const allCapabilityTypes = capability.CAPS | capability.BOUNDS | capability.AMBS
+
+var capabilityMap map[string]capability.Cap
+
+func init() {
+ capabilityMap = make(map[string]capability.Cap)
+ last := capability.CAP_LAST_CAP
+ // workaround for RHEL6 which has no /proc/sys/kernel/cap_last_cap
+ if last == capability.Cap(63) {
+ last = capability.CAP_BLOCK_SUSPEND
+ }
+ for _, cap := range capability.List() {
+ if cap > last {
+ continue
+ }
+ capKey := fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String()))
+ capabilityMap[capKey] = cap
+ }
+}
+
+func newContainerCapList(capConfig *configs.Capabilities) (*containerCapabilities, error) {
+ bounding := []capability.Cap{}
+ for _, c := range capConfig.Bounding {
+ v, ok := capabilityMap[c]
+ if !ok {
+ return nil, fmt.Errorf("unknown capability %q", c)
+ }
+ bounding = append(bounding, v)
+ }
+ effective := []capability.Cap{}
+ for _, c := range capConfig.Effective {
+ v, ok := capabilityMap[c]
+ if !ok {
+ return nil, fmt.Errorf("unknown capability %q", c)
+ }
+ effective = append(effective, v)
+ }
+ inheritable := []capability.Cap{}
+ for _, c := range capConfig.Inheritable {
+ v, ok := capabilityMap[c]
+ if !ok {
+ return nil, fmt.Errorf("unknown capability %q", c)
+ }
+ inheritable = append(inheritable, v)
+ }
+ permitted := []capability.Cap{}
+ for _, c := range capConfig.Permitted {
+ v, ok := capabilityMap[c]
+ if !ok {
+ return nil, fmt.Errorf("unknown capability %q", c)
+ }
+ permitted = append(permitted, v)
+ }
+ ambient := []capability.Cap{}
+ for _, c := range capConfig.Ambient {
+ v, ok := capabilityMap[c]
+ if !ok {
+ return nil, fmt.Errorf("unknown capability %q", c)
+ }
+ ambient = append(ambient, v)
+ }
+ pid, err := capability.NewPid(os.Getpid())
+ if err != nil {
+ return nil, err
+ }
+ return &containerCapabilities{
+ bounding: bounding,
+ effective: effective,
+ inheritable: inheritable,
+ permitted: permitted,
+ ambient: ambient,
+ pid: pid,
+ }, nil
+}
+
+type containerCapabilities struct {
+ pid capability.Capabilities
+ bounding []capability.Cap
+ effective []capability.Cap
+ inheritable []capability.Cap
+ permitted []capability.Cap
+ ambient []capability.Cap
+}
+
+// ApplyBoundingSet sets the capability bounding set to those specified in the whitelist.
+func (c *containerCapabilities) ApplyBoundingSet() error {
+ c.pid.Clear(capability.BOUNDS)
+ c.pid.Set(capability.BOUNDS, c.bounding...)
+ return c.pid.Apply(capability.BOUNDS)
+}
+
+// Apply sets all the capabilities for the current process in the config.
+func (c *containerCapabilities) ApplyCaps() error {
+ c.pid.Clear(allCapabilityTypes)
+ c.pid.Set(capability.BOUNDS, c.bounding...)
+ c.pid.Set(capability.PERMITTED, c.permitted...)
+ c.pid.Set(capability.INHERITABLE, c.inheritable...)
+ c.pid.Set(capability.EFFECTIVE, c.effective...)
+ c.pid.Set(capability.AMBIENT, c.ambient...)
+ return c.pid.Apply(allCapabilityTypes)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go
new file mode 100644
index 0000000..25ff515
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go
@@ -0,0 +1,64 @@
+// +build linux
+
+package cgroups
+
+import (
+ "fmt"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type Manager interface {
+ // Applies cgroup configuration to the process with the specified pid
+ Apply(pid int) error
+
+ // Returns the PIDs inside the cgroup set
+ GetPids() ([]int, error)
+
+ // Returns the PIDs inside the cgroup set & all sub-cgroups
+ GetAllPids() ([]int, error)
+
+ // Returns statistics for the cgroup set
+ GetStats() (*Stats, error)
+
+ // Toggles the freezer cgroup according with specified state
+ Freeze(state configs.FreezerState) error
+
+ // Destroys the cgroup set
+ Destroy() error
+
+ // The option func SystemdCgroups() and Cgroupfs() require following attributes:
+ // Paths map[string]string
+ // Cgroups *configs.Cgroup
+ // Paths maps cgroup subsystem to path at which it is mounted.
+ // Cgroups specifies specific cgroup settings for the various subsystems
+
+ // Returns cgroup paths to save in a state file and to be able to
+ // restore the object later.
+ GetPaths() map[string]string
+
+ // Sets the cgroup as configured.
+ Set(container *configs.Config) error
+}
+
+type NotFoundError struct {
+ Subsystem string
+}
+
+func (e *NotFoundError) Error() string {
+ return fmt.Sprintf("mountpoint for %s not found", e.Subsystem)
+}
+
+func NewNotFoundError(sub string) error {
+ return &NotFoundError{
+ Subsystem: sub,
+ }
+}
+
+func IsNotFound(err error) bool {
+ if err == nil {
+ return false
+ }
+ _, ok := err.(*NotFoundError)
+ return ok
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups_unsupported.go
new file mode 100644
index 0000000..278d507
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups_unsupported.go
@@ -0,0 +1,3 @@
+// +build !linux
+
+package cgroups
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go
new file mode 100644
index 0000000..22d82ac
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go
@@ -0,0 +1,360 @@
+// +build linux
+
+package fs
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "sync"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ libcontainerUtils "github.com/opencontainers/runc/libcontainer/utils"
+)
+
+var (
+ subsystems = subsystemSet{
+ &CpusetGroup{},
+ &DevicesGroup{},
+ &MemoryGroup{},
+ &CpuGroup{},
+ &CpuacctGroup{},
+ &PidsGroup{},
+ &BlkioGroup{},
+ &HugetlbGroup{},
+ &NetClsGroup{},
+ &NetPrioGroup{},
+ &PerfEventGroup{},
+ &FreezerGroup{},
+ &NameGroup{GroupName: "name=systemd", Join: true},
+ }
+ HugePageSizes, _ = cgroups.GetHugePageSize()
+)
+
+var errSubsystemDoesNotExist = errors.New("cgroup: subsystem does not exist")
+
+type subsystemSet []subsystem
+
+func (s subsystemSet) Get(name string) (subsystem, error) {
+ for _, ss := range s {
+ if ss.Name() == name {
+ return ss, nil
+ }
+ }
+ return nil, errSubsystemDoesNotExist
+}
+
+type subsystem interface {
+ // Name returns the name of the subsystem.
+ Name() string
+ // Returns the stats, as 'stats', corresponding to the cgroup under 'path'.
+ GetStats(path string, stats *cgroups.Stats) error
+ // Removes the cgroup represented by 'cgroupData'.
+ Remove(*cgroupData) error
+ // Creates and joins the cgroup represented by 'cgroupData'.
+ Apply(*cgroupData) error
+ // Set the cgroup represented by cgroup.
+ Set(path string, cgroup *configs.Cgroup) error
+}
+
+type Manager struct {
+ mu sync.Mutex
+ Cgroups *configs.Cgroup
+ Paths map[string]string
+}
+
+// The absolute path to the root of the cgroup hierarchies.
+var cgroupRootLock sync.Mutex
+var cgroupRoot string
+
+// Gets the cgroupRoot.
+func getCgroupRoot() (string, error) {
+ cgroupRootLock.Lock()
+ defer cgroupRootLock.Unlock()
+
+ if cgroupRoot != "" {
+ return cgroupRoot, nil
+ }
+
+ root, err := cgroups.FindCgroupMountpointDir()
+ if err != nil {
+ return "", err
+ }
+
+ if _, err := os.Stat(root); err != nil {
+ return "", err
+ }
+
+ cgroupRoot = root
+ return cgroupRoot, nil
+}
+
+type cgroupData struct {
+ root string
+ innerPath string
+ config *configs.Cgroup
+ pid int
+}
+
+func (m *Manager) Apply(pid int) (err error) {
+ if m.Cgroups == nil {
+ return nil
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ var c = m.Cgroups
+
+ d, err := getCgroupData(m.Cgroups, pid)
+ if err != nil {
+ return err
+ }
+
+ m.Paths = make(map[string]string)
+ if c.Paths != nil {
+ for name, path := range c.Paths {
+ _, err := d.path(name)
+ if err != nil {
+ if cgroups.IsNotFound(err) {
+ continue
+ }
+ return err
+ }
+ m.Paths[name] = path
+ }
+ return cgroups.EnterPid(m.Paths, pid)
+ }
+
+ for _, sys := range subsystems {
+ // TODO: Apply should, ideally, be reentrant or be broken up into a separate
+ // create and join phase so that the cgroup hierarchy for a container can be
+ // created then join consists of writing the process pids to cgroup.procs
+ p, err := d.path(sys.Name())
+ if err != nil {
+ // The non-presence of the devices subsystem is
+ // considered fatal for security reasons.
+ if cgroups.IsNotFound(err) && sys.Name() != "devices" {
+ continue
+ }
+ return err
+ }
+ m.Paths[sys.Name()] = p
+
+ if err := sys.Apply(d); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (m *Manager) Destroy() error {
+ if m.Cgroups.Paths != nil {
+ return nil
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if err := cgroups.RemovePaths(m.Paths); err != nil {
+ return err
+ }
+ m.Paths = make(map[string]string)
+ return nil
+}
+
+func (m *Manager) GetPaths() map[string]string {
+ m.mu.Lock()
+ paths := m.Paths
+ m.mu.Unlock()
+ return paths
+}
+
+func (m *Manager) GetStats() (*cgroups.Stats, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ stats := cgroups.NewStats()
+ for name, path := range m.Paths {
+ sys, err := subsystems.Get(name)
+ if err == errSubsystemDoesNotExist || !cgroups.PathExists(path) {
+ continue
+ }
+ if err := sys.GetStats(path, stats); err != nil {
+ return nil, err
+ }
+ }
+ return stats, nil
+}
+
+func (m *Manager) Set(container *configs.Config) error {
+ // If Paths are set, then we are just joining cgroups paths
+ // and there is no need to set any values.
+ if m.Cgroups.Paths != nil {
+ return nil
+ }
+
+ paths := m.GetPaths()
+ for _, sys := range subsystems {
+ path := paths[sys.Name()]
+ if err := sys.Set(path, container.Cgroups); err != nil {
+ return err
+ }
+ }
+
+ if m.Paths["cpu"] != "" {
+ if err := CheckCpushares(m.Paths["cpu"], container.Cgroups.Resources.CpuShares); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Freeze toggles the container's freezer cgroup depending on the state
+// provided
+func (m *Manager) Freeze(state configs.FreezerState) error {
+ paths := m.GetPaths()
+ dir := paths["freezer"]
+ prevState := m.Cgroups.Resources.Freezer
+ m.Cgroups.Resources.Freezer = state
+ freezer, err := subsystems.Get("freezer")
+ if err != nil {
+ return err
+ }
+ err = freezer.Set(dir, m.Cgroups)
+ if err != nil {
+ m.Cgroups.Resources.Freezer = prevState
+ return err
+ }
+ return nil
+}
+
+func (m *Manager) GetPids() ([]int, error) {
+ paths := m.GetPaths()
+ return cgroups.GetPids(paths["devices"])
+}
+
+func (m *Manager) GetAllPids() ([]int, error) {
+ paths := m.GetPaths()
+ return cgroups.GetAllPids(paths["devices"])
+}
+
+func getCgroupData(c *configs.Cgroup, pid int) (*cgroupData, error) {
+ root, err := getCgroupRoot()
+ if err != nil {
+ return nil, err
+ }
+
+ if (c.Name != "" || c.Parent != "") && c.Path != "" {
+ return nil, fmt.Errorf("cgroup: either Path or Name and Parent should be used")
+ }
+
+ // XXX: Do not remove this code. Path safety is important! -- cyphar
+ cgPath := libcontainerUtils.CleanPath(c.Path)
+ cgParent := libcontainerUtils.CleanPath(c.Parent)
+ cgName := libcontainerUtils.CleanPath(c.Name)
+
+ innerPath := cgPath
+ if innerPath == "" {
+ innerPath = filepath.Join(cgParent, cgName)
+ }
+
+ return &cgroupData{
+ root: root,
+ innerPath: innerPath,
+ config: c,
+ pid: pid,
+ }, nil
+}
+
+func (raw *cgroupData) path(subsystem string) (string, error) {
+ mnt, err := cgroups.FindCgroupMountpoint(subsystem)
+ // If we didn't mount the subsystem, there is no point we make the path.
+ if err != nil {
+ return "", err
+ }
+
+ // If the cgroup name/path is absolute do not look relative to the cgroup of the init process.
+ if filepath.IsAbs(raw.innerPath) {
+ // Sometimes subsystems can be mounted together as 'cpu,cpuacct'.
+ return filepath.Join(raw.root, filepath.Base(mnt), raw.innerPath), nil
+ }
+
+ // Use GetOwnCgroupPath instead of GetInitCgroupPath, because the creating
+ // process could in container and shared pid namespace with host, and
+ // /proc/1/cgroup could point to whole other world of cgroups.
+ parentPath, err := cgroups.GetOwnCgroupPath(subsystem)
+ if err != nil {
+ return "", err
+ }
+
+ return filepath.Join(parentPath, raw.innerPath), nil
+}
+
+func (raw *cgroupData) join(subsystem string) (string, error) {
+ path, err := raw.path(subsystem)
+ if err != nil {
+ return "", err
+ }
+ if err := os.MkdirAll(path, 0755); err != nil {
+ return "", err
+ }
+ if err := cgroups.WriteCgroupProc(path, raw.pid); err != nil {
+ return "", err
+ }
+ return path, nil
+}
+
+func writeFile(dir, file, data string) error {
+ // Normally dir should not be empty, one case is that cgroup subsystem
+ // is not mounted, we will get empty dir, and we want it fail here.
+ if dir == "" {
+ return fmt.Errorf("no such directory for %s", file)
+ }
+ if err := ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700); err != nil {
+ return fmt.Errorf("failed to write %v to %v: %v", data, file, err)
+ }
+ return nil
+}
+
+func readFile(dir, file string) (string, error) {
+ data, err := ioutil.ReadFile(filepath.Join(dir, file))
+ return string(data), err
+}
+
+func removePath(p string, err error) error {
+ if err != nil {
+ return err
+ }
+ if p != "" {
+ return os.RemoveAll(p)
+ }
+ return nil
+}
+
+func CheckCpushares(path string, c uint64) error {
+ var cpuShares uint64
+
+ if c == 0 {
+ return nil
+ }
+
+ fd, err := os.Open(filepath.Join(path, "cpu.shares"))
+ if err != nil {
+ return err
+ }
+ defer fd.Close()
+
+ _, err = fmt.Fscanf(fd, "%d", &cpuShares)
+ if err != nil && err != io.EOF {
+ return err
+ }
+
+ if c > cpuShares {
+ return fmt.Errorf("The maximum allowed cpu-shares is %d", cpuShares)
+ } else if c < cpuShares {
+ return fmt.Errorf("The minimum allowed cpu-shares is %d", cpuShares)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/blkio.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/blkio.go
new file mode 100644
index 0000000..a142cb9
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/blkio.go
@@ -0,0 +1,237 @@
+// +build linux
+
+package fs
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type BlkioGroup struct {
+}
+
+func (s *BlkioGroup) Name() string {
+ return "blkio"
+}
+
+func (s *BlkioGroup) Apply(d *cgroupData) error {
+ _, err := d.join("blkio")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ return nil
+}
+
+func (s *BlkioGroup) Set(path string, cgroup *configs.Cgroup) error {
+ if cgroup.Resources.BlkioWeight != 0 {
+ if err := writeFile(path, "blkio.weight", strconv.FormatUint(uint64(cgroup.Resources.BlkioWeight), 10)); err != nil {
+ return err
+ }
+ }
+
+ if cgroup.Resources.BlkioLeafWeight != 0 {
+ if err := writeFile(path, "blkio.leaf_weight", strconv.FormatUint(uint64(cgroup.Resources.BlkioLeafWeight), 10)); err != nil {
+ return err
+ }
+ }
+ for _, wd := range cgroup.Resources.BlkioWeightDevice {
+ if err := writeFile(path, "blkio.weight_device", wd.WeightString()); err != nil {
+ return err
+ }
+ if err := writeFile(path, "blkio.leaf_weight_device", wd.LeafWeightString()); err != nil {
+ return err
+ }
+ }
+ for _, td := range cgroup.Resources.BlkioThrottleReadBpsDevice {
+ if err := writeFile(path, "blkio.throttle.read_bps_device", td.String()); err != nil {
+ return err
+ }
+ }
+ for _, td := range cgroup.Resources.BlkioThrottleWriteBpsDevice {
+ if err := writeFile(path, "blkio.throttle.write_bps_device", td.String()); err != nil {
+ return err
+ }
+ }
+ for _, td := range cgroup.Resources.BlkioThrottleReadIOPSDevice {
+ if err := writeFile(path, "blkio.throttle.read_iops_device", td.String()); err != nil {
+ return err
+ }
+ }
+ for _, td := range cgroup.Resources.BlkioThrottleWriteIOPSDevice {
+ if err := writeFile(path, "blkio.throttle.write_iops_device", td.String()); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (s *BlkioGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("blkio"))
+}
+
+/*
+examples:
+
+ blkio.sectors
+ 8:0 6792
+
+ blkio.io_service_bytes
+ 8:0 Read 1282048
+ 8:0 Write 2195456
+ 8:0 Sync 2195456
+ 8:0 Async 1282048
+ 8:0 Total 3477504
+ Total 3477504
+
+ blkio.io_serviced
+ 8:0 Read 124
+ 8:0 Write 104
+ 8:0 Sync 104
+ 8:0 Async 124
+ 8:0 Total 228
+ Total 228
+
+ blkio.io_queued
+ 8:0 Read 0
+ 8:0 Write 0
+ 8:0 Sync 0
+ 8:0 Async 0
+ 8:0 Total 0
+ Total 0
+*/
+
+func splitBlkioStatLine(r rune) bool {
+ return r == ' ' || r == ':'
+}
+
+func getBlkioStat(path string) ([]cgroups.BlkioStatEntry, error) {
+ var blkioStats []cgroups.BlkioStatEntry
+ f, err := os.Open(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return blkioStats, nil
+ }
+ return nil, err
+ }
+ defer f.Close()
+
+ sc := bufio.NewScanner(f)
+ for sc.Scan() {
+ // format: dev type amount
+ fields := strings.FieldsFunc(sc.Text(), splitBlkioStatLine)
+ if len(fields) < 3 {
+ if len(fields) == 2 && fields[0] == "Total" {
+ // skip total line
+ continue
+ } else {
+ return nil, fmt.Errorf("Invalid line found while parsing %s: %s", path, sc.Text())
+ }
+ }
+
+ v, err := strconv.ParseUint(fields[0], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ major := v
+
+ v, err = strconv.ParseUint(fields[1], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ minor := v
+
+ op := ""
+ valueField := 2
+ if len(fields) == 4 {
+ op = fields[2]
+ valueField = 3
+ }
+ v, err = strconv.ParseUint(fields[valueField], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ blkioStats = append(blkioStats, cgroups.BlkioStatEntry{Major: major, Minor: minor, Op: op, Value: v})
+ }
+
+ return blkioStats, nil
+}
+
+func (s *BlkioGroup) GetStats(path string, stats *cgroups.Stats) error {
+ // Try to read CFQ stats available on all CFQ enabled kernels first
+ if blkioStats, err := getBlkioStat(filepath.Join(path, "blkio.io_serviced_recursive")); err == nil && blkioStats != nil {
+ return getCFQStats(path, stats)
+ }
+ return getStats(path, stats) // Use generic stats as fallback
+}
+
+func getCFQStats(path string, stats *cgroups.Stats) error {
+ var blkioStats []cgroups.BlkioStatEntry
+ var err error
+
+ if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.sectors_recursive")); err != nil {
+ return err
+ }
+ stats.BlkioStats.SectorsRecursive = blkioStats
+
+ if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_service_bytes_recursive")); err != nil {
+ return err
+ }
+ stats.BlkioStats.IoServiceBytesRecursive = blkioStats
+
+ if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_serviced_recursive")); err != nil {
+ return err
+ }
+ stats.BlkioStats.IoServicedRecursive = blkioStats
+
+ if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_queued_recursive")); err != nil {
+ return err
+ }
+ stats.BlkioStats.IoQueuedRecursive = blkioStats
+
+ if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_service_time_recursive")); err != nil {
+ return err
+ }
+ stats.BlkioStats.IoServiceTimeRecursive = blkioStats
+
+ if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_wait_time_recursive")); err != nil {
+ return err
+ }
+ stats.BlkioStats.IoWaitTimeRecursive = blkioStats
+
+ if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_merged_recursive")); err != nil {
+ return err
+ }
+ stats.BlkioStats.IoMergedRecursive = blkioStats
+
+ if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.time_recursive")); err != nil {
+ return err
+ }
+ stats.BlkioStats.IoTimeRecursive = blkioStats
+
+ return nil
+}
+
+func getStats(path string, stats *cgroups.Stats) error {
+ var blkioStats []cgroups.BlkioStatEntry
+ var err error
+
+ if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.throttle.io_service_bytes")); err != nil {
+ return err
+ }
+ stats.BlkioStats.IoServiceBytesRecursive = blkioStats
+
+ if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.throttle.io_serviced")); err != nil {
+ return err
+ }
+ stats.BlkioStats.IoServicedRecursive = blkioStats
+
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpu.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpu.go
new file mode 100644
index 0000000..b712bd0
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpu.go
@@ -0,0 +1,125 @@
+// +build linux
+
+package fs
+
+import (
+ "bufio"
+ "os"
+ "path/filepath"
+ "strconv"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type CpuGroup struct {
+}
+
+func (s *CpuGroup) Name() string {
+ return "cpu"
+}
+
+func (s *CpuGroup) Apply(d *cgroupData) error {
+ // We always want to join the cpu group, to allow fair cpu scheduling
+ // on a container basis
+ path, err := d.path("cpu")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ return s.ApplyDir(path, d.config, d.pid)
+}
+
+func (s *CpuGroup) ApplyDir(path string, cgroup *configs.Cgroup, pid int) error {
+ // This might happen if we have no cpu cgroup mounted.
+ // Just do nothing and don't fail.
+ if path == "" {
+ return nil
+ }
+ if err := os.MkdirAll(path, 0755); err != nil {
+ return err
+ }
+ // We should set the real-Time group scheduling settings before moving
+ // in the process because if the process is already in SCHED_RR mode
+ // and no RT bandwidth is set, adding it will fail.
+ if err := s.SetRtSched(path, cgroup); err != nil {
+ return err
+ }
+ // because we are not using d.join we need to place the pid into the procs file
+ // unlike the other subsystems
+ if err := cgroups.WriteCgroupProc(path, pid); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (s *CpuGroup) SetRtSched(path string, cgroup *configs.Cgroup) error {
+ if cgroup.Resources.CpuRtPeriod != 0 {
+ if err := writeFile(path, "cpu.rt_period_us", strconv.FormatUint(cgroup.Resources.CpuRtPeriod, 10)); err != nil {
+ return err
+ }
+ }
+ if cgroup.Resources.CpuRtRuntime != 0 {
+ if err := writeFile(path, "cpu.rt_runtime_us", strconv.FormatInt(cgroup.Resources.CpuRtRuntime, 10)); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (s *CpuGroup) Set(path string, cgroup *configs.Cgroup) error {
+ if cgroup.Resources.CpuShares != 0 {
+ if err := writeFile(path, "cpu.shares", strconv.FormatUint(cgroup.Resources.CpuShares, 10)); err != nil {
+ return err
+ }
+ }
+ if cgroup.Resources.CpuPeriod != 0 {
+ if err := writeFile(path, "cpu.cfs_period_us", strconv.FormatUint(cgroup.Resources.CpuPeriod, 10)); err != nil {
+ return err
+ }
+ }
+ if cgroup.Resources.CpuQuota != 0 {
+ if err := writeFile(path, "cpu.cfs_quota_us", strconv.FormatInt(cgroup.Resources.CpuQuota, 10)); err != nil {
+ return err
+ }
+ }
+ if err := s.SetRtSched(path, cgroup); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (s *CpuGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("cpu"))
+}
+
+func (s *CpuGroup) GetStats(path string, stats *cgroups.Stats) error {
+ f, err := os.Open(filepath.Join(path, "cpu.stat"))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+ }
+ defer f.Close()
+
+ sc := bufio.NewScanner(f)
+ for sc.Scan() {
+ t, v, err := getCgroupParamKeyValue(sc.Text())
+ if err != nil {
+ return err
+ }
+ switch t {
+ case "nr_periods":
+ stats.CpuStats.ThrottlingData.Periods = v
+
+ case "nr_throttled":
+ stats.CpuStats.ThrottlingData.ThrottledPeriods = v
+
+ case "throttled_time":
+ stats.CpuStats.ThrottlingData.ThrottledTime = v
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuacct.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuacct.go
new file mode 100644
index 0000000..53afbad
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuacct.go
@@ -0,0 +1,121 @@
+// +build linux
+
+package fs
+
+import (
+ "fmt"
+ "io/ioutil"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/system"
+)
+
+const (
+ cgroupCpuacctStat = "cpuacct.stat"
+ nanosecondsInSecond = 1000000000
+)
+
+var clockTicks = uint64(system.GetClockTicks())
+
+type CpuacctGroup struct {
+}
+
+func (s *CpuacctGroup) Name() string {
+ return "cpuacct"
+}
+
+func (s *CpuacctGroup) Apply(d *cgroupData) error {
+ // we just want to join this group even though we don't set anything
+ if _, err := d.join("cpuacct"); err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+
+ return nil
+}
+
+func (s *CpuacctGroup) Set(path string, cgroup *configs.Cgroup) error {
+ return nil
+}
+
+func (s *CpuacctGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("cpuacct"))
+}
+
+func (s *CpuacctGroup) GetStats(path string, stats *cgroups.Stats) error {
+ userModeUsage, kernelModeUsage, err := getCpuUsageBreakdown(path)
+ if err != nil {
+ return err
+ }
+
+ totalUsage, err := getCgroupParamUint(path, "cpuacct.usage")
+ if err != nil {
+ return err
+ }
+
+ percpuUsage, err := getPercpuUsage(path)
+ if err != nil {
+ return err
+ }
+
+ stats.CpuStats.CpuUsage.TotalUsage = totalUsage
+ stats.CpuStats.CpuUsage.PercpuUsage = percpuUsage
+ stats.CpuStats.CpuUsage.UsageInUsermode = userModeUsage
+ stats.CpuStats.CpuUsage.UsageInKernelmode = kernelModeUsage
+ return nil
+}
+
+// Returns user and kernel usage breakdown in nanoseconds.
+func getCpuUsageBreakdown(path string) (uint64, uint64, error) {
+ userModeUsage := uint64(0)
+ kernelModeUsage := uint64(0)
+ const (
+ userField = "user"
+ systemField = "system"
+ )
+
+ // Expected format:
+ // user <usage in ticks>
+ // system <usage in ticks>
+ data, err := ioutil.ReadFile(filepath.Join(path, cgroupCpuacctStat))
+ if err != nil {
+ return 0, 0, err
+ }
+ fields := strings.Fields(string(data))
+ if len(fields) != 4 {
+ return 0, 0, fmt.Errorf("failure - %s is expected to have 4 fields", filepath.Join(path, cgroupCpuacctStat))
+ }
+ if fields[0] != userField {
+ return 0, 0, fmt.Errorf("unexpected field %q in %q, expected %q", fields[0], cgroupCpuacctStat, userField)
+ }
+ if fields[2] != systemField {
+ return 0, 0, fmt.Errorf("unexpected field %q in %q, expected %q", fields[2], cgroupCpuacctStat, systemField)
+ }
+ if userModeUsage, err = strconv.ParseUint(fields[1], 10, 64); err != nil {
+ return 0, 0, err
+ }
+ if kernelModeUsage, err = strconv.ParseUint(fields[3], 10, 64); err != nil {
+ return 0, 0, err
+ }
+
+ return (userModeUsage * nanosecondsInSecond) / clockTicks, (kernelModeUsage * nanosecondsInSecond) / clockTicks, nil
+}
+
+func getPercpuUsage(path string) ([]uint64, error) {
+ percpuUsage := []uint64{}
+ data, err := ioutil.ReadFile(filepath.Join(path, "cpuacct.usage_percpu"))
+ if err != nil {
+ return percpuUsage, err
+ }
+ for _, value := range strings.Fields(string(data)) {
+ value, err := strconv.ParseUint(value, 10, 64)
+ if err != nil {
+ return percpuUsage, fmt.Errorf("Unable to convert param value to uint64: %s", err)
+ }
+ percpuUsage = append(percpuUsage, value)
+ }
+ return percpuUsage, nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go
new file mode 100644
index 0000000..918b9a3
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go
@@ -0,0 +1,162 @@
+// +build linux
+
+package fs
+
+import (
+ "bytes"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ libcontainerUtils "github.com/opencontainers/runc/libcontainer/utils"
+)
+
+type CpusetGroup struct {
+}
+
+func (s *CpusetGroup) Name() string {
+ return "cpuset"
+}
+
+func (s *CpusetGroup) Apply(d *cgroupData) error {
+ dir, err := d.path("cpuset")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ return s.ApplyDir(dir, d.config, d.pid)
+}
+
+func (s *CpusetGroup) Set(path string, cgroup *configs.Cgroup) error {
+ if cgroup.Resources.CpusetCpus != "" {
+ if err := writeFile(path, "cpuset.cpus", cgroup.Resources.CpusetCpus); err != nil {
+ return err
+ }
+ }
+ if cgroup.Resources.CpusetMems != "" {
+ if err := writeFile(path, "cpuset.mems", cgroup.Resources.CpusetMems); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (s *CpusetGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("cpuset"))
+}
+
+func (s *CpusetGroup) GetStats(path string, stats *cgroups.Stats) error {
+ return nil
+}
+
+func (s *CpusetGroup) ApplyDir(dir string, cgroup *configs.Cgroup, pid int) error {
+ // This might happen if we have no cpuset cgroup mounted.
+ // Just do nothing and don't fail.
+ if dir == "" {
+ return nil
+ }
+ root, err := getCgroupRoot()
+ if err != nil {
+ return err
+ }
+ // 'ensureParent' start with parent because we don't want to
+ // explicitly inherit from parent, it could conflict with
+ // 'cpuset.cpu_exclusive'.
+ if err := s.ensureParent(filepath.Dir(dir), root); err != nil {
+ return err
+ }
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return err
+ }
+ // We didn't inherit cpuset configs from parent, but we have
+ // to ensure cpuset configs are set before moving task into the
+ // cgroup.
+ // The logic is, if user specified cpuset configs, use these
+ // specified configs, otherwise, inherit from parent. This makes
+ // cpuset configs work correctly with 'cpuset.cpu_exclusive', and
+ // keep backward compatbility.
+ if err := s.ensureCpusAndMems(dir, cgroup); err != nil {
+ return err
+ }
+
+ // because we are not using d.join we need to place the pid into the procs file
+ // unlike the other subsystems
+ if err := cgroups.WriteCgroupProc(dir, pid); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (s *CpusetGroup) getSubsystemSettings(parent string) (cpus []byte, mems []byte, err error) {
+ if cpus, err = ioutil.ReadFile(filepath.Join(parent, "cpuset.cpus")); err != nil {
+ return
+ }
+ if mems, err = ioutil.ReadFile(filepath.Join(parent, "cpuset.mems")); err != nil {
+ return
+ }
+ return cpus, mems, nil
+}
+
+// ensureParent makes sure that the parent directory of current is created
+// and populated with the proper cpus and mems files copied from
+// it's parent.
+func (s *CpusetGroup) ensureParent(current, root string) error {
+ parent := filepath.Dir(current)
+ if libcontainerUtils.CleanPath(parent) == root {
+ return nil
+ }
+ // Avoid infinite recursion.
+ if parent == current {
+ return fmt.Errorf("cpuset: cgroup parent path outside cgroup root")
+ }
+ if err := s.ensureParent(parent, root); err != nil {
+ return err
+ }
+ if err := os.MkdirAll(current, 0755); err != nil {
+ return err
+ }
+ return s.copyIfNeeded(current, parent)
+}
+
+// copyIfNeeded copies the cpuset.cpus and cpuset.mems from the parent
+// directory to the current directory if the file's contents are 0
+func (s *CpusetGroup) copyIfNeeded(current, parent string) error {
+ var (
+ err error
+ currentCpus, currentMems []byte
+ parentCpus, parentMems []byte
+ )
+
+ if currentCpus, currentMems, err = s.getSubsystemSettings(current); err != nil {
+ return err
+ }
+ if parentCpus, parentMems, err = s.getSubsystemSettings(parent); err != nil {
+ return err
+ }
+
+ if s.isEmpty(currentCpus) {
+ if err := writeFile(current, "cpuset.cpus", string(parentCpus)); err != nil {
+ return err
+ }
+ }
+ if s.isEmpty(currentMems) {
+ if err := writeFile(current, "cpuset.mems", string(parentMems)); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (s *CpusetGroup) isEmpty(b []byte) bool {
+ return len(bytes.Trim(b, "\n")) == 0
+}
+
+func (s *CpusetGroup) ensureCpusAndMems(path string, cgroup *configs.Cgroup) error {
+ if err := s.Set(path, cgroup); err != nil {
+ return err
+ }
+ return s.copyIfNeeded(path, filepath.Dir(path))
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go
new file mode 100644
index 0000000..0ac5b4e
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go
@@ -0,0 +1,80 @@
+// +build linux
+
+package fs
+
+import (
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/system"
+)
+
+type DevicesGroup struct {
+}
+
+func (s *DevicesGroup) Name() string {
+ return "devices"
+}
+
+func (s *DevicesGroup) Apply(d *cgroupData) error {
+ _, err := d.join("devices")
+ if err != nil {
+ // We will return error even it's `not found` error, devices
+ // cgroup is hard requirement for container's security.
+ return err
+ }
+ return nil
+}
+
+func (s *DevicesGroup) Set(path string, cgroup *configs.Cgroup) error {
+ if system.RunningInUserNS() {
+ return nil
+ }
+
+ devices := cgroup.Resources.Devices
+ if len(devices) > 0 {
+ for _, dev := range devices {
+ file := "devices.deny"
+ if dev.Allow {
+ file = "devices.allow"
+ }
+ if err := writeFile(path, file, dev.CgroupString()); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ if cgroup.Resources.AllowAllDevices != nil {
+ if *cgroup.Resources.AllowAllDevices == false {
+ if err := writeFile(path, "devices.deny", "a"); err != nil {
+ return err
+ }
+
+ for _, dev := range cgroup.Resources.AllowedDevices {
+ if err := writeFile(path, "devices.allow", dev.CgroupString()); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+
+ if err := writeFile(path, "devices.allow", "a"); err != nil {
+ return err
+ }
+ }
+
+ for _, dev := range cgroup.Resources.DeniedDevices {
+ if err := writeFile(path, "devices.deny", dev.CgroupString()); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (s *DevicesGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("devices"))
+}
+
+func (s *DevicesGroup) GetStats(path string, stats *cgroups.Stats) error {
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/freezer.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/freezer.go
new file mode 100644
index 0000000..e70dfe3
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/freezer.go
@@ -0,0 +1,61 @@
+// +build linux
+
+package fs
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type FreezerGroup struct {
+}
+
+func (s *FreezerGroup) Name() string {
+ return "freezer"
+}
+
+func (s *FreezerGroup) Apply(d *cgroupData) error {
+ _, err := d.join("freezer")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ return nil
+}
+
+func (s *FreezerGroup) Set(path string, cgroup *configs.Cgroup) error {
+ switch cgroup.Resources.Freezer {
+ case configs.Frozen, configs.Thawed:
+ if err := writeFile(path, "freezer.state", string(cgroup.Resources.Freezer)); err != nil {
+ return err
+ }
+
+ for {
+ state, err := readFile(path, "freezer.state")
+ if err != nil {
+ return err
+ }
+ if strings.TrimSpace(state) == string(cgroup.Resources.Freezer) {
+ break
+ }
+ time.Sleep(1 * time.Millisecond)
+ }
+ case configs.Undefined:
+ return nil
+ default:
+ return fmt.Errorf("Invalid argument '%s' to freezer.state", string(cgroup.Resources.Freezer))
+ }
+
+ return nil
+}
+
+func (s *FreezerGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("freezer"))
+}
+
+func (s *FreezerGroup) GetStats(path string, stats *cgroups.Stats) error {
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/fs_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/fs_unsupported.go
new file mode 100644
index 0000000..3ef9e03
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/fs_unsupported.go
@@ -0,0 +1,3 @@
+// +build !linux
+
+package fs
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/hugetlb.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/hugetlb.go
new file mode 100644
index 0000000..2f97277
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/hugetlb.go
@@ -0,0 +1,71 @@
+// +build linux
+
+package fs
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type HugetlbGroup struct {
+}
+
+func (s *HugetlbGroup) Name() string {
+ return "hugetlb"
+}
+
+func (s *HugetlbGroup) Apply(d *cgroupData) error {
+ _, err := d.join("hugetlb")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ return nil
+}
+
+func (s *HugetlbGroup) Set(path string, cgroup *configs.Cgroup) error {
+ for _, hugetlb := range cgroup.Resources.HugetlbLimit {
+ if err := writeFile(path, strings.Join([]string{"hugetlb", hugetlb.Pagesize, "limit_in_bytes"}, "."), strconv.FormatUint(hugetlb.Limit, 10)); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (s *HugetlbGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("hugetlb"))
+}
+
+func (s *HugetlbGroup) GetStats(path string, stats *cgroups.Stats) error {
+ hugetlbStats := cgroups.HugetlbStats{}
+ for _, pageSize := range HugePageSizes {
+ usage := strings.Join([]string{"hugetlb", pageSize, "usage_in_bytes"}, ".")
+ value, err := getCgroupParamUint(path, usage)
+ if err != nil {
+ return fmt.Errorf("failed to parse %s - %v", usage, err)
+ }
+ hugetlbStats.Usage = value
+
+ maxUsage := strings.Join([]string{"hugetlb", pageSize, "max_usage_in_bytes"}, ".")
+ value, err = getCgroupParamUint(path, maxUsage)
+ if err != nil {
+ return fmt.Errorf("failed to parse %s - %v", maxUsage, err)
+ }
+ hugetlbStats.MaxUsage = value
+
+ failcnt := strings.Join([]string{"hugetlb", pageSize, "failcnt"}, ".")
+ value, err = getCgroupParamUint(path, failcnt)
+ if err != nil {
+ return fmt.Errorf("failed to parse %s - %v", failcnt, err)
+ }
+ hugetlbStats.Failcnt = value
+
+ stats.HugetlbStats[pageSize] = hugetlbStats
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go
new file mode 100644
index 0000000..0981cfb
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go
@@ -0,0 +1,305 @@
+// +build linux
+
+package fs
+
+import (
+ "bufio"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+const (
+ cgroupKernelMemoryLimit = "memory.kmem.limit_in_bytes"
+ cgroupMemorySwapLimit = "memory.memsw.limit_in_bytes"
+ cgroupMemoryLimit = "memory.limit_in_bytes"
+)
+
+type MemoryGroup struct {
+}
+
+func (s *MemoryGroup) Name() string {
+ return "memory"
+}
+
+func (s *MemoryGroup) Apply(d *cgroupData) (err error) {
+ path, err := d.path("memory")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ } else if path == "" {
+ return nil
+ }
+ if memoryAssigned(d.config) {
+ if _, err := os.Stat(path); os.IsNotExist(err) {
+ if err := os.MkdirAll(path, 0755); err != nil {
+ return err
+ }
+ // Only enable kernel memory accouting when this cgroup
+ // is created by libcontainer, otherwise we might get
+ // error when people use `cgroupsPath` to join an existed
+ // cgroup whose kernel memory is not initialized.
+ if err := EnableKernelMemoryAccounting(path); err != nil {
+ return err
+ }
+ }
+ }
+ defer func() {
+ if err != nil {
+ os.RemoveAll(path)
+ }
+ }()
+
+ // We need to join memory cgroup after set memory limits, because
+ // kmem.limit_in_bytes can only be set when the cgroup is empty.
+ _, err = d.join("memory")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ return nil
+}
+
+func EnableKernelMemoryAccounting(path string) error {
+ // Check if kernel memory is enabled
+ // We have to limit the kernel memory here as it won't be accounted at all
+ // until a limit is set on the cgroup and limit cannot be set once the
+ // cgroup has children, or if there are already tasks in the cgroup.
+ for _, i := range []int64{1, -1} {
+ if err := setKernelMemory(path, uint64(i)); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func setKernelMemory(path string, kernelMemoryLimit uint64) error {
+ if path == "" {
+ return fmt.Errorf("no such directory for %s", cgroupKernelMemoryLimit)
+ }
+ if !cgroups.PathExists(filepath.Join(path, cgroupKernelMemoryLimit)) {
+ // kernel memory is not enabled on the system so we should do nothing
+ return nil
+ }
+ if err := ioutil.WriteFile(filepath.Join(path, cgroupKernelMemoryLimit), []byte(strconv.FormatUint(kernelMemoryLimit, 10)), 0700); err != nil {
+ // Check if the error number returned by the syscall is "EBUSY"
+ // The EBUSY signal is returned on attempts to write to the
+ // memory.kmem.limit_in_bytes file if the cgroup has children or
+ // once tasks have been attached to the cgroup
+ if pathErr, ok := err.(*os.PathError); ok {
+ if errNo, ok := pathErr.Err.(syscall.Errno); ok {
+ if errNo == syscall.EBUSY {
+ return fmt.Errorf("failed to set %s, because either tasks have already joined this cgroup or it has children", cgroupKernelMemoryLimit)
+ }
+ }
+ }
+ return fmt.Errorf("failed to write %v to %v: %v", kernelMemoryLimit, cgroupKernelMemoryLimit, err)
+ }
+ return nil
+}
+
+func setMemoryAndSwap(path string, cgroup *configs.Cgroup) error {
+ ulimited := -1
+
+ // If the memory update is set to uint64(-1) we should also
+ // set swap to uint64(-1), it means unlimited memory.
+ if cgroup.Resources.Memory == uint64(ulimited) {
+ // Only set swap if it's enbled in kernel
+ if cgroups.PathExists(filepath.Join(path, cgroupMemorySwapLimit)) {
+ cgroup.Resources.MemorySwap = uint64(ulimited)
+ }
+ }
+
+ // When memory and swap memory are both set, we need to handle the cases
+ // for updating container.
+ if cgroup.Resources.Memory != 0 && cgroup.Resources.MemorySwap != 0 {
+ memoryUsage, err := getMemoryData(path, "")
+ if err != nil {
+ return err
+ }
+
+ // When update memory limit, we should adapt the write sequence
+ // for memory and swap memory, so it won't fail because the new
+ // value and the old value don't fit kernel's validation.
+ if cgroup.Resources.MemorySwap == uint64(ulimited) || memoryUsage.Limit < cgroup.Resources.MemorySwap {
+ if err := writeFile(path, cgroupMemorySwapLimit, strconv.FormatUint(cgroup.Resources.MemorySwap, 10)); err != nil {
+ return err
+ }
+ if err := writeFile(path, cgroupMemoryLimit, strconv.FormatUint(cgroup.Resources.Memory, 10)); err != nil {
+ return err
+ }
+ } else {
+ if err := writeFile(path, cgroupMemoryLimit, strconv.FormatUint(cgroup.Resources.Memory, 10)); err != nil {
+ return err
+ }
+ if err := writeFile(path, cgroupMemorySwapLimit, strconv.FormatUint(cgroup.Resources.MemorySwap, 10)); err != nil {
+ return err
+ }
+ }
+ } else {
+ if cgroup.Resources.Memory != 0 {
+ if err := writeFile(path, cgroupMemoryLimit, strconv.FormatUint(cgroup.Resources.Memory, 10)); err != nil {
+ return err
+ }
+ }
+ if cgroup.Resources.MemorySwap != 0 {
+ if err := writeFile(path, cgroupMemorySwapLimit, strconv.FormatUint(cgroup.Resources.MemorySwap, 10)); err != nil {
+ return err
+ }
+ }
+ }
+
+ return nil
+}
+
+func (s *MemoryGroup) Set(path string, cgroup *configs.Cgroup) error {
+ if err := setMemoryAndSwap(path, cgroup); err != nil {
+ return err
+ }
+
+ if cgroup.Resources.KernelMemory != 0 {
+ if err := setKernelMemory(path, cgroup.Resources.KernelMemory); err != nil {
+ return err
+ }
+ }
+
+ if cgroup.Resources.MemoryReservation != 0 {
+ if err := writeFile(path, "memory.soft_limit_in_bytes", strconv.FormatUint(cgroup.Resources.MemoryReservation, 10)); err != nil {
+ return err
+ }
+ }
+
+ if cgroup.Resources.KernelMemoryTCP != 0 {
+ if err := writeFile(path, "memory.kmem.tcp.limit_in_bytes", strconv.FormatUint(cgroup.Resources.KernelMemoryTCP, 10)); err != nil {
+ return err
+ }
+ }
+ if cgroup.Resources.OomKillDisable {
+ if err := writeFile(path, "memory.oom_control", "1"); err != nil {
+ return err
+ }
+ }
+ if cgroup.Resources.MemorySwappiness == nil || int64(*cgroup.Resources.MemorySwappiness) == -1 {
+ return nil
+ } else if *cgroup.Resources.MemorySwappiness <= 100 {
+ if err := writeFile(path, "memory.swappiness", strconv.FormatUint(*cgroup.Resources.MemorySwappiness, 10)); err != nil {
+ return err
+ }
+ } else {
+ return fmt.Errorf("invalid value:%d. valid memory swappiness range is 0-100", *cgroup.Resources.MemorySwappiness)
+ }
+
+ return nil
+}
+
+func (s *MemoryGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("memory"))
+}
+
+func (s *MemoryGroup) GetStats(path string, stats *cgroups.Stats) error {
+ // Set stats from memory.stat.
+ statsFile, err := os.Open(filepath.Join(path, "memory.stat"))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+ }
+ defer statsFile.Close()
+
+ sc := bufio.NewScanner(statsFile)
+ for sc.Scan() {
+ t, v, err := getCgroupParamKeyValue(sc.Text())
+ if err != nil {
+ return fmt.Errorf("failed to parse memory.stat (%q) - %v", sc.Text(), err)
+ }
+ stats.MemoryStats.Stats[t] = v
+ }
+ stats.MemoryStats.Cache = stats.MemoryStats.Stats["cache"]
+
+ memoryUsage, err := getMemoryData(path, "")
+ if err != nil {
+ return err
+ }
+ stats.MemoryStats.Usage = memoryUsage
+ swapUsage, err := getMemoryData(path, "memsw")
+ if err != nil {
+ return err
+ }
+ stats.MemoryStats.SwapUsage = swapUsage
+ kernelUsage, err := getMemoryData(path, "kmem")
+ if err != nil {
+ return err
+ }
+ stats.MemoryStats.KernelUsage = kernelUsage
+ kernelTCPUsage, err := getMemoryData(path, "kmem.tcp")
+ if err != nil {
+ return err
+ }
+ stats.MemoryStats.KernelTCPUsage = kernelTCPUsage
+
+ return nil
+}
+
+func memoryAssigned(cgroup *configs.Cgroup) bool {
+ return cgroup.Resources.Memory != 0 ||
+ cgroup.Resources.MemoryReservation != 0 ||
+ cgroup.Resources.MemorySwap > 0 ||
+ cgroup.Resources.KernelMemory > 0 ||
+ cgroup.Resources.KernelMemoryTCP > 0 ||
+ cgroup.Resources.OomKillDisable ||
+ (cgroup.Resources.MemorySwappiness != nil && int64(*cgroup.Resources.MemorySwappiness) != -1)
+}
+
+func getMemoryData(path, name string) (cgroups.MemoryData, error) {
+ memoryData := cgroups.MemoryData{}
+
+ moduleName := "memory"
+ if name != "" {
+ moduleName = strings.Join([]string{"memory", name}, ".")
+ }
+ usage := strings.Join([]string{moduleName, "usage_in_bytes"}, ".")
+ maxUsage := strings.Join([]string{moduleName, "max_usage_in_bytes"}, ".")
+ failcnt := strings.Join([]string{moduleName, "failcnt"}, ".")
+ limit := strings.Join([]string{moduleName, "limit_in_bytes"}, ".")
+
+ value, err := getCgroupParamUint(path, usage)
+ if err != nil {
+ if moduleName != "memory" && os.IsNotExist(err) {
+ return cgroups.MemoryData{}, nil
+ }
+ return cgroups.MemoryData{}, fmt.Errorf("failed to parse %s - %v", usage, err)
+ }
+ memoryData.Usage = value
+ value, err = getCgroupParamUint(path, maxUsage)
+ if err != nil {
+ if moduleName != "memory" && os.IsNotExist(err) {
+ return cgroups.MemoryData{}, nil
+ }
+ return cgroups.MemoryData{}, fmt.Errorf("failed to parse %s - %v", maxUsage, err)
+ }
+ memoryData.MaxUsage = value
+ value, err = getCgroupParamUint(path, failcnt)
+ if err != nil {
+ if moduleName != "memory" && os.IsNotExist(err) {
+ return cgroups.MemoryData{}, nil
+ }
+ return cgroups.MemoryData{}, fmt.Errorf("failed to parse %s - %v", failcnt, err)
+ }
+ memoryData.Failcnt = value
+ value, err = getCgroupParamUint(path, limit)
+ if err != nil {
+ if moduleName != "memory" && os.IsNotExist(err) {
+ return cgroups.MemoryData{}, nil
+ }
+ return cgroups.MemoryData{}, fmt.Errorf("failed to parse %s - %v", limit, err)
+ }
+ memoryData.Limit = value
+
+ return memoryData, nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go
new file mode 100644
index 0000000..d8cf1d8
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go
@@ -0,0 +1,40 @@
+// +build linux
+
+package fs
+
+import (
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type NameGroup struct {
+ GroupName string
+ Join bool
+}
+
+func (s *NameGroup) Name() string {
+ return s.GroupName
+}
+
+func (s *NameGroup) Apply(d *cgroupData) error {
+ if s.Join {
+ // ignore errors if the named cgroup does not exist
+ d.join(s.GroupName)
+ }
+ return nil
+}
+
+func (s *NameGroup) Set(path string, cgroup *configs.Cgroup) error {
+ return nil
+}
+
+func (s *NameGroup) Remove(d *cgroupData) error {
+ if s.Join {
+ removePath(d.path(s.GroupName))
+ }
+ return nil
+}
+
+func (s *NameGroup) GetStats(path string, stats *cgroups.Stats) error {
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_cls.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_cls.go
new file mode 100644
index 0000000..8e74b64
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_cls.go
@@ -0,0 +1,43 @@
+// +build linux
+
+package fs
+
+import (
+ "strconv"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type NetClsGroup struct {
+}
+
+func (s *NetClsGroup) Name() string {
+ return "net_cls"
+}
+
+func (s *NetClsGroup) Apply(d *cgroupData) error {
+ _, err := d.join("net_cls")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ return nil
+}
+
+func (s *NetClsGroup) Set(path string, cgroup *configs.Cgroup) error {
+ if cgroup.Resources.NetClsClassid != 0 {
+ if err := writeFile(path, "net_cls.classid", strconv.FormatUint(uint64(cgroup.Resources.NetClsClassid), 10)); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (s *NetClsGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("net_cls"))
+}
+
+func (s *NetClsGroup) GetStats(path string, stats *cgroups.Stats) error {
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_prio.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_prio.go
new file mode 100644
index 0000000..d0ab2af
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_prio.go
@@ -0,0 +1,41 @@
+// +build linux
+
+package fs
+
+import (
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type NetPrioGroup struct {
+}
+
+func (s *NetPrioGroup) Name() string {
+ return "net_prio"
+}
+
+func (s *NetPrioGroup) Apply(d *cgroupData) error {
+ _, err := d.join("net_prio")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ return nil
+}
+
+func (s *NetPrioGroup) Set(path string, cgroup *configs.Cgroup) error {
+ for _, prioMap := range cgroup.Resources.NetPrioIfpriomap {
+ if err := writeFile(path, "net_prio.ifpriomap", prioMap.CgroupString()); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (s *NetPrioGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("net_prio"))
+}
+
+func (s *NetPrioGroup) GetStats(path string, stats *cgroups.Stats) error {
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/perf_event.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/perf_event.go
new file mode 100644
index 0000000..5693676
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/perf_event.go
@@ -0,0 +1,35 @@
+// +build linux
+
+package fs
+
+import (
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type PerfEventGroup struct {
+}
+
+func (s *PerfEventGroup) Name() string {
+ return "perf_event"
+}
+
+func (s *PerfEventGroup) Apply(d *cgroupData) error {
+ // we just want to join this group even though we don't set anything
+ if _, err := d.join("perf_event"); err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ return nil
+}
+
+func (s *PerfEventGroup) Set(path string, cgroup *configs.Cgroup) error {
+ return nil
+}
+
+func (s *PerfEventGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("perf_event"))
+}
+
+func (s *PerfEventGroup) GetStats(path string, stats *cgroups.Stats) error {
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids.go
new file mode 100644
index 0000000..f1e3720
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/pids.go
@@ -0,0 +1,73 @@
+// +build linux
+
+package fs
+
+import (
+ "fmt"
+ "path/filepath"
+ "strconv"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type PidsGroup struct {
+}
+
+func (s *PidsGroup) Name() string {
+ return "pids"
+}
+
+func (s *PidsGroup) Apply(d *cgroupData) error {
+ _, err := d.join("pids")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ return nil
+}
+
+func (s *PidsGroup) Set(path string, cgroup *configs.Cgroup) error {
+ if cgroup.Resources.PidsLimit != 0 {
+ // "max" is the fallback value.
+ limit := "max"
+
+ if cgroup.Resources.PidsLimit > 0 {
+ limit = strconv.FormatInt(cgroup.Resources.PidsLimit, 10)
+ }
+
+ if err := writeFile(path, "pids.max", limit); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (s *PidsGroup) Remove(d *cgroupData) error {
+ return removePath(d.path("pids"))
+}
+
+func (s *PidsGroup) GetStats(path string, stats *cgroups.Stats) error {
+ current, err := getCgroupParamUint(path, "pids.current")
+ if err != nil {
+ return fmt.Errorf("failed to parse pids.current - %s", err)
+ }
+
+ maxString, err := getCgroupParamString(path, "pids.max")
+ if err != nil {
+ return fmt.Errorf("failed to parse pids.max - %s", err)
+ }
+
+ // Default if pids.max == "max" is 0 -- which represents "no limit".
+ var max uint64
+ if maxString != "max" {
+ max, err = parseUint(maxString, 10, 64)
+ if err != nil {
+ return fmt.Errorf("failed to parse pids.max - unable to parse %q as a uint from Cgroup file %q", maxString, filepath.Join(path, "pids.max"))
+ }
+ }
+
+ stats.PidsStats.Current = current
+ stats.PidsStats.Limit = max
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/utils.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/utils.go
new file mode 100644
index 0000000..5ff0a16
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/utils.go
@@ -0,0 +1,78 @@
+// +build linux
+
+package fs
+
+import (
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+var (
+ ErrNotValidFormat = errors.New("line is not a valid key value format")
+)
+
+// Saturates negative values at zero and returns a uint64.
+// Due to kernel bugs, some of the memory cgroup stats can be negative.
+func parseUint(s string, base, bitSize int) (uint64, error) {
+ value, err := strconv.ParseUint(s, base, bitSize)
+ if err != nil {
+ intValue, intErr := strconv.ParseInt(s, base, bitSize)
+ // 1. Handle negative values greater than MinInt64 (and)
+ // 2. Handle negative values lesser than MinInt64
+ if intErr == nil && intValue < 0 {
+ return 0, nil
+ } else if intErr != nil && intErr.(*strconv.NumError).Err == strconv.ErrRange && intValue < 0 {
+ return 0, nil
+ }
+
+ return value, err
+ }
+
+ return value, nil
+}
+
+// Parses a cgroup param and returns as name, value
+// i.e. "io_service_bytes 1234" will return as io_service_bytes, 1234
+func getCgroupParamKeyValue(t string) (string, uint64, error) {
+ parts := strings.Fields(t)
+ switch len(parts) {
+ case 2:
+ value, err := parseUint(parts[1], 10, 64)
+ if err != nil {
+ return "", 0, fmt.Errorf("unable to convert param value (%q) to uint64: %v", parts[1], err)
+ }
+
+ return parts[0], value, nil
+ default:
+ return "", 0, ErrNotValidFormat
+ }
+}
+
+// Gets a single uint64 value from the specified cgroup file.
+func getCgroupParamUint(cgroupPath, cgroupFile string) (uint64, error) {
+ fileName := filepath.Join(cgroupPath, cgroupFile)
+ contents, err := ioutil.ReadFile(fileName)
+ if err != nil {
+ return 0, err
+ }
+
+ res, err := parseUint(strings.TrimSpace(string(contents)), 10, 64)
+ if err != nil {
+ return res, fmt.Errorf("unable to parse %q as a uint from Cgroup file %q", string(contents), fileName)
+ }
+ return res, nil
+}
+
+// Gets a string value from the specified cgroup file
+func getCgroupParamString(cgroupPath, cgroupFile string) (string, error) {
+ contents, err := ioutil.ReadFile(filepath.Join(cgroupPath, cgroupFile))
+ if err != nil {
+ return "", err
+ }
+
+ return strings.TrimSpace(string(contents)), nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/rootless/rootless.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/rootless/rootless.go
new file mode 100644
index 0000000..b1efbfd
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/rootless/rootless.go
@@ -0,0 +1,128 @@
+// +build linux
+
+package rootless
+
+import (
+ "fmt"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/cgroups/fs"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/configs/validate"
+)
+
+// TODO: This is copied from libcontainer/cgroups/fs, which duplicates this code
+// needlessly. We should probably export this list.
+
+var subsystems = []subsystem{
+ &fs.CpusetGroup{},
+ &fs.DevicesGroup{},
+ &fs.MemoryGroup{},
+ &fs.CpuGroup{},
+ &fs.CpuacctGroup{},
+ &fs.PidsGroup{},
+ &fs.BlkioGroup{},
+ &fs.HugetlbGroup{},
+ &fs.NetClsGroup{},
+ &fs.NetPrioGroup{},
+ &fs.PerfEventGroup{},
+ &fs.FreezerGroup{},
+ &fs.NameGroup{GroupName: "name=systemd"},
+}
+
+type subsystem interface {
+ // Name returns the name of the subsystem.
+ Name() string
+
+ // Returns the stats, as 'stats', corresponding to the cgroup under 'path'.
+ GetStats(path string, stats *cgroups.Stats) error
+}
+
+// The noop cgroup manager is used for rootless containers, because we currently
+// cannot manage cgroups if we are in a rootless setup. This manager is chosen
+// by factory if we are in rootless mode. We error out if any cgroup options are
+// set in the config -- this may change in the future with upcoming kernel features
+// like the cgroup namespace.
+
+type Manager struct {
+ Cgroups *configs.Cgroup
+ Paths map[string]string
+}
+
+func (m *Manager) Apply(pid int) error {
+ // If there are no cgroup settings, there's nothing to do.
+ if m.Cgroups == nil {
+ return nil
+ }
+
+ // We can't set paths.
+ // TODO(cyphar): Implement the case where the runner of a rootless container
+ // owns their own cgroup, which would allow us to set up a
+ // cgroup for each path.
+ if m.Cgroups.Paths != nil {
+ return fmt.Errorf("cannot change cgroup path in rootless container")
+ }
+
+ // We load the paths into the manager.
+ paths := make(map[string]string)
+ for _, sys := range subsystems {
+ name := sys.Name()
+
+ path, err := cgroups.GetOwnCgroupPath(name)
+ if err != nil {
+ // Ignore paths we couldn't resolve.
+ continue
+ }
+
+ paths[name] = path
+ }
+
+ m.Paths = paths
+ return nil
+}
+
+func (m *Manager) GetPaths() map[string]string {
+ return m.Paths
+}
+
+func (m *Manager) Set(container *configs.Config) error {
+ // We have to re-do the validation here, since someone might decide to
+ // update a rootless container.
+ return validate.New().Validate(container)
+}
+
+func (m *Manager) GetPids() ([]int, error) {
+ dir, err := cgroups.GetOwnCgroupPath("devices")
+ if err != nil {
+ return nil, err
+ }
+ return cgroups.GetPids(dir)
+}
+
+func (m *Manager) GetAllPids() ([]int, error) {
+ dir, err := cgroups.GetOwnCgroupPath("devices")
+ if err != nil {
+ return nil, err
+ }
+ return cgroups.GetAllPids(dir)
+}
+
+func (m *Manager) GetStats() (*cgroups.Stats, error) {
+ // TODO(cyphar): We can make this work if we figure out a way to allow usage
+ // of cgroups with a rootless container. While this doesn't
+ // actually require write access to a cgroup directory, the
+ // statistics are not useful if they can be affected by
+ // non-container processes.
+ return nil, fmt.Errorf("cannot get cgroup stats in rootless container")
+}
+
+func (m *Manager) Freeze(state configs.FreezerState) error {
+ // TODO(cyphar): We can make this work if we figure out a way to allow usage
+ // of cgroups with a rootless container.
+ return fmt.Errorf("cannot use freezer cgroup in rootless container")
+}
+
+func (m *Manager) Destroy() error {
+ // We don't have to do anything here because we didn't do any setup.
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go
new file mode 100644
index 0000000..b483f1b
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go
@@ -0,0 +1,106 @@
+// +build linux
+
+package cgroups
+
+type ThrottlingData struct {
+ // Number of periods with throttling active
+ Periods uint64 `json:"periods,omitempty"`
+ // Number of periods when the container hit its throttling limit.
+ ThrottledPeriods uint64 `json:"throttled_periods,omitempty"`
+ // Aggregate time the container was throttled for in nanoseconds.
+ ThrottledTime uint64 `json:"throttled_time,omitempty"`
+}
+
+// CpuUsage denotes the usage of a CPU.
+// All CPU stats are aggregate since container inception.
+type CpuUsage struct {
+ // Total CPU time consumed.
+ // Units: nanoseconds.
+ TotalUsage uint64 `json:"total_usage,omitempty"`
+ // Total CPU time consumed per core.
+ // Units: nanoseconds.
+ PercpuUsage []uint64 `json:"percpu_usage,omitempty"`
+ // Time spent by tasks of the cgroup in kernel mode.
+ // Units: nanoseconds.
+ UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
+ // Time spent by tasks of the cgroup in user mode.
+ // Units: nanoseconds.
+ UsageInUsermode uint64 `json:"usage_in_usermode"`
+}
+
+type CpuStats struct {
+ CpuUsage CpuUsage `json:"cpu_usage,omitempty"`
+ ThrottlingData ThrottlingData `json:"throttling_data,omitempty"`
+}
+
+type MemoryData struct {
+ Usage uint64 `json:"usage,omitempty"`
+ MaxUsage uint64 `json:"max_usage,omitempty"`
+ Failcnt uint64 `json:"failcnt"`
+ Limit uint64 `json:"limit"`
+}
+
+type MemoryStats struct {
+ // memory used for cache
+ Cache uint64 `json:"cache,omitempty"`
+ // usage of memory
+ Usage MemoryData `json:"usage,omitempty"`
+ // usage of memory + swap
+ SwapUsage MemoryData `json:"swap_usage,omitempty"`
+ // usage of kernel memory
+ KernelUsage MemoryData `json:"kernel_usage,omitempty"`
+ // usage of kernel TCP memory
+ KernelTCPUsage MemoryData `json:"kernel_tcp_usage,omitempty"`
+
+ Stats map[string]uint64 `json:"stats,omitempty"`
+}
+
+type PidsStats struct {
+ // number of pids in the cgroup
+ Current uint64 `json:"current,omitempty"`
+ // active pids hard limit
+ Limit uint64 `json:"limit,omitempty"`
+}
+
+type BlkioStatEntry struct {
+ Major uint64 `json:"major,omitempty"`
+ Minor uint64 `json:"minor,omitempty"`
+ Op string `json:"op,omitempty"`
+ Value uint64 `json:"value,omitempty"`
+}
+
+type BlkioStats struct {
+ // number of bytes tranferred to and from the block device
+ IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive,omitempty"`
+ IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive,omitempty"`
+ IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive,omitempty"`
+ IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive,omitempty"`
+ IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive,omitempty"`
+ IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive,omitempty"`
+ IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive,omitempty"`
+ SectorsRecursive []BlkioStatEntry `json:"sectors_recursive,omitempty"`
+}
+
+type HugetlbStats struct {
+ // current res_counter usage for hugetlb
+ Usage uint64 `json:"usage,omitempty"`
+ // maximum usage ever recorded.
+ MaxUsage uint64 `json:"max_usage,omitempty"`
+ // number of times hugetlb usage allocation failure.
+ Failcnt uint64 `json:"failcnt"`
+}
+
+type Stats struct {
+ CpuStats CpuStats `json:"cpu_stats,omitempty"`
+ MemoryStats MemoryStats `json:"memory_stats,omitempty"`
+ PidsStats PidsStats `json:"pids_stats,omitempty"`
+ BlkioStats BlkioStats `json:"blkio_stats,omitempty"`
+ // the map is in the format "size of hugepage: stats of the hugepage"
+ HugetlbStats map[string]HugetlbStats `json:"hugetlb_stats,omitempty"`
+}
+
+func NewStats() *Stats {
+ memoryStats := MemoryStats{Stats: make(map[string]uint64)}
+ hugetlbStats := make(map[string]HugetlbStats)
+ return &Stats{MemoryStats: memoryStats, HugetlbStats: hugetlbStats}
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_nosystemd.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_nosystemd.go
new file mode 100644
index 0000000..7de9ae6
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_nosystemd.go
@@ -0,0 +1,55 @@
+// +build !linux
+
+package systemd
+
+import (
+ "fmt"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type Manager struct {
+ Cgroups *configs.Cgroup
+ Paths map[string]string
+}
+
+func UseSystemd() bool {
+ return false
+}
+
+func (m *Manager) Apply(pid int) error {
+ return fmt.Errorf("Systemd not supported")
+}
+
+func (m *Manager) GetPids() ([]int, error) {
+ return nil, fmt.Errorf("Systemd not supported")
+}
+
+func (m *Manager) GetAllPids() ([]int, error) {
+ return nil, fmt.Errorf("Systemd not supported")
+}
+
+func (m *Manager) Destroy() error {
+ return fmt.Errorf("Systemd not supported")
+}
+
+func (m *Manager) GetPaths() map[string]string {
+ return nil
+}
+
+func (m *Manager) GetStats() (*cgroups.Stats, error) {
+ return nil, fmt.Errorf("Systemd not supported")
+}
+
+func (m *Manager) Set(container *configs.Config) error {
+ return nil, fmt.Errorf("Systemd not supported")
+}
+
+func (m *Manager) Freeze(state configs.FreezerState) error {
+ return fmt.Errorf("Systemd not supported")
+}
+
+func Freeze(c *configs.Cgroup, state configs.FreezerState) error {
+ return fmt.Errorf("Systemd not supported")
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go
new file mode 100644
index 0000000..456c57d
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go
@@ -0,0 +1,555 @@
+// +build linux
+
+package systemd
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ systemdDbus "github.com/coreos/go-systemd/dbus"
+ systemdUtil "github.com/coreos/go-systemd/util"
+ "github.com/godbus/dbus"
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/cgroups/fs"
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type Manager struct {
+ mu sync.Mutex
+ Cgroups *configs.Cgroup
+ Paths map[string]string
+}
+
+type subsystem interface {
+ // Name returns the name of the subsystem.
+ Name() string
+ // Returns the stats, as 'stats', corresponding to the cgroup under 'path'.
+ GetStats(path string, stats *cgroups.Stats) error
+ // Set the cgroup represented by cgroup.
+ Set(path string, cgroup *configs.Cgroup) error
+}
+
+var errSubsystemDoesNotExist = errors.New("cgroup: subsystem does not exist")
+
+type subsystemSet []subsystem
+
+func (s subsystemSet) Get(name string) (subsystem, error) {
+ for _, ss := range s {
+ if ss.Name() == name {
+ return ss, nil
+ }
+ }
+ return nil, errSubsystemDoesNotExist
+}
+
+var subsystems = subsystemSet{
+ &fs.CpusetGroup{},
+ &fs.DevicesGroup{},
+ &fs.MemoryGroup{},
+ &fs.CpuGroup{},
+ &fs.CpuacctGroup{},
+ &fs.PidsGroup{},
+ &fs.BlkioGroup{},
+ &fs.HugetlbGroup{},
+ &fs.PerfEventGroup{},
+ &fs.FreezerGroup{},
+ &fs.NetPrioGroup{},
+ &fs.NetClsGroup{},
+ &fs.NameGroup{GroupName: "name=systemd"},
+}
+
+const (
+ testScopeWait = 4
+ testSliceWait = 4
+)
+
+var (
+ connLock sync.Mutex
+ theConn *systemdDbus.Conn
+ hasStartTransientUnit bool
+ hasStartTransientSliceUnit bool
+ hasTransientDefaultDependencies bool
+ hasDelegate bool
+)
+
+func newProp(name string, units interface{}) systemdDbus.Property {
+ return systemdDbus.Property{
+ Name: name,
+ Value: dbus.MakeVariant(units),
+ }
+}
+
+func UseSystemd() bool {
+ if !systemdUtil.IsRunningSystemd() {
+ return false
+ }
+
+ connLock.Lock()
+ defer connLock.Unlock()
+
+ if theConn == nil {
+ var err error
+ theConn, err = systemdDbus.New()
+ if err != nil {
+ return false
+ }
+
+ // Assume we have StartTransientUnit
+ hasStartTransientUnit = true
+
+ // But if we get UnknownMethod error we don't
+ if _, err := theConn.StartTransientUnit("test.scope", "invalid", nil, nil); err != nil {
+ if dbusError, ok := err.(dbus.Error); ok {
+ if dbusError.Name == "org.freedesktop.DBus.Error.UnknownMethod" {
+ hasStartTransientUnit = false
+ return hasStartTransientUnit
+ }
+ }
+ }
+
+ // Ensure the scope name we use doesn't exist. Use the Pid to
+ // avoid collisions between multiple libcontainer users on a
+ // single host.
+ scope := fmt.Sprintf("libcontainer-%d-systemd-test-default-dependencies.scope", os.Getpid())
+ testScopeExists := true
+ for i := 0; i <= testScopeWait; i++ {
+ if _, err := theConn.StopUnit(scope, "replace", nil); err != nil {
+ if dbusError, ok := err.(dbus.Error); ok {
+ if strings.Contains(dbusError.Name, "org.freedesktop.systemd1.NoSuchUnit") {
+ testScopeExists = false
+ break
+ }
+ }
+ }
+ time.Sleep(time.Millisecond)
+ }
+
+ // Bail out if we can't kill this scope without testing for DefaultDependencies
+ if testScopeExists {
+ return hasStartTransientUnit
+ }
+
+ // Assume StartTransientUnit on a scope allows DefaultDependencies
+ hasTransientDefaultDependencies = true
+ ddf := newProp("DefaultDependencies", false)
+ if _, err := theConn.StartTransientUnit(scope, "replace", []systemdDbus.Property{ddf}, nil); err != nil {
+ if dbusError, ok := err.(dbus.Error); ok {
+ if strings.Contains(dbusError.Name, "org.freedesktop.DBus.Error.PropertyReadOnly") {
+ hasTransientDefaultDependencies = false
+ }
+ }
+ }
+
+ // Not critical because of the stop unit logic above.
+ theConn.StopUnit(scope, "replace", nil)
+
+ // Assume StartTransientUnit on a scope allows Delegate
+ hasDelegate = true
+ dl := newProp("Delegate", true)
+ if _, err := theConn.StartTransientUnit(scope, "replace", []systemdDbus.Property{dl}, nil); err != nil {
+ if dbusError, ok := err.(dbus.Error); ok {
+ if strings.Contains(dbusError.Name, "org.freedesktop.DBus.Error.PropertyReadOnly") {
+ hasDelegate = false
+ }
+ }
+ }
+
+ // Assume we have the ability to start a transient unit as a slice
+ // This was broken until systemd v229, but has been back-ported on RHEL environments >= 219
+ // For details, see: https://bugzilla.redhat.com/show_bug.cgi?id=1370299
+ hasStartTransientSliceUnit = true
+
+ // To ensure simple clean-up, we create a slice off the root with no hierarchy
+ slice := fmt.Sprintf("libcontainer_%d_systemd_test_default.slice", os.Getpid())
+ if _, err := theConn.StartTransientUnit(slice, "replace", nil, nil); err != nil {
+ if _, ok := err.(dbus.Error); ok {
+ hasStartTransientSliceUnit = false
+ }
+ }
+
+ for i := 0; i <= testSliceWait; i++ {
+ if _, err := theConn.StopUnit(slice, "replace", nil); err != nil {
+ if dbusError, ok := err.(dbus.Error); ok {
+ if strings.Contains(dbusError.Name, "org.freedesktop.systemd1.NoSuchUnit") {
+ hasStartTransientSliceUnit = false
+ break
+ }
+ }
+ } else {
+ break
+ }
+ time.Sleep(time.Millisecond)
+ }
+
+ // Not critical because of the stop unit logic above.
+ theConn.StopUnit(scope, "replace", nil)
+ theConn.StopUnit(slice, "replace", nil)
+ }
+ return hasStartTransientUnit
+}
+
+func (m *Manager) Apply(pid int) error {
+ var (
+ c = m.Cgroups
+ unitName = getUnitName(c)
+ slice = "system.slice"
+ properties []systemdDbus.Property
+ )
+
+ if c.Paths != nil {
+ paths := make(map[string]string)
+ for name, path := range c.Paths {
+ _, err := getSubsystemPath(m.Cgroups, name)
+ if err != nil {
+ // Don't fail if a cgroup hierarchy was not found, just skip this subsystem
+ if cgroups.IsNotFound(err) {
+ continue
+ }
+ return err
+ }
+ paths[name] = path
+ }
+ m.Paths = paths
+ return cgroups.EnterPid(m.Paths, pid)
+ }
+
+ if c.Parent != "" {
+ slice = c.Parent
+ }
+
+ properties = append(properties, systemdDbus.PropDescription("libcontainer container "+c.Name))
+
+ // if we create a slice, the parent is defined via a Wants=
+ if strings.HasSuffix(unitName, ".slice") {
+ // This was broken until systemd v229, but has been back-ported on RHEL environments >= 219
+ if !hasStartTransientSliceUnit {
+ return fmt.Errorf("systemd version does not support ability to start a slice as transient unit")
+ }
+ properties = append(properties, systemdDbus.PropWants(slice))
+ } else {
+ // otherwise, we use Slice=
+ properties = append(properties, systemdDbus.PropSlice(slice))
+ }
+
+ // only add pid if its valid, -1 is used w/ general slice creation.
+ if pid != -1 {
+ properties = append(properties, newProp("PIDs", []uint32{uint32(pid)}))
+ }
+
+ if hasDelegate {
+ // This is only supported on systemd versions 218 and above.
+ properties = append(properties, newProp("Delegate", true))
+ }
+
+ // Always enable accounting, this gets us the same behaviour as the fs implementation,
+ // plus the kernel has some problems with joining the memory cgroup at a later time.
+ properties = append(properties,
+ newProp("MemoryAccounting", true),
+ newProp("CPUAccounting", true),
+ newProp("BlockIOAccounting", true))
+
+ if hasTransientDefaultDependencies {
+ properties = append(properties,
+ newProp("DefaultDependencies", false))
+ }
+
+ if c.Resources.Memory != 0 {
+ properties = append(properties,
+ newProp("MemoryLimit", c.Resources.Memory))
+ }
+
+ if c.Resources.CpuShares != 0 {
+ properties = append(properties,
+ newProp("CPUShares", c.Resources.CpuShares))
+ }
+
+ // cpu.cfs_quota_us and cpu.cfs_period_us are controlled by systemd.
+ if c.Resources.CpuQuota != 0 && c.Resources.CpuPeriod != 0 {
+ cpuQuotaPerSecUSec := uint64(c.Resources.CpuQuota*1000000) / c.Resources.CpuPeriod
+ properties = append(properties,
+ newProp("CPUQuotaPerSecUSec", cpuQuotaPerSecUSec))
+ }
+
+ if c.Resources.BlkioWeight != 0 {
+ properties = append(properties,
+ newProp("BlockIOWeight", uint64(c.Resources.BlkioWeight)))
+ }
+
+ // We have to set kernel memory here, as we can't change it once
+ // processes have been attached to the cgroup.
+ if c.Resources.KernelMemory != 0 {
+ if err := setKernelMemory(c); err != nil {
+ return err
+ }
+ }
+
+ if _, err := theConn.StartTransientUnit(unitName, "replace", properties, nil); err != nil && !isUnitExists(err) {
+ return err
+ }
+
+ if err := joinCgroups(c, pid); err != nil {
+ return err
+ }
+
+ paths := make(map[string]string)
+ for _, s := range subsystems {
+ subsystemPath, err := getSubsystemPath(m.Cgroups, s.Name())
+ if err != nil {
+ // Don't fail if a cgroup hierarchy was not found, just skip this subsystem
+ if cgroups.IsNotFound(err) {
+ continue
+ }
+ return err
+ }
+ paths[s.Name()] = subsystemPath
+ }
+ m.Paths = paths
+ return nil
+}
+
+func (m *Manager) Destroy() error {
+ if m.Cgroups.Paths != nil {
+ return nil
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ theConn.StopUnit(getUnitName(m.Cgroups), "replace", nil)
+ if err := cgroups.RemovePaths(m.Paths); err != nil {
+ return err
+ }
+ m.Paths = make(map[string]string)
+ return nil
+}
+
+func (m *Manager) GetPaths() map[string]string {
+ m.mu.Lock()
+ paths := m.Paths
+ m.mu.Unlock()
+ return paths
+}
+
+func join(c *configs.Cgroup, subsystem string, pid int) (string, error) {
+ path, err := getSubsystemPath(c, subsystem)
+ if err != nil {
+ return "", err
+ }
+ if err := os.MkdirAll(path, 0755); err != nil {
+ return "", err
+ }
+ if err := cgroups.WriteCgroupProc(path, pid); err != nil {
+ return "", err
+ }
+ return path, nil
+}
+
+func joinCgroups(c *configs.Cgroup, pid int) error {
+ for _, sys := range subsystems {
+ name := sys.Name()
+ switch name {
+ case "name=systemd":
+ // let systemd handle this
+ break
+ case "cpuset":
+ path, err := getSubsystemPath(c, name)
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+ s := &fs.CpusetGroup{}
+ if err := s.ApplyDir(path, c, pid); err != nil {
+ return err
+ }
+ break
+ default:
+ _, err := join(c, name, pid)
+ if err != nil {
+ // Even if it's `not found` error, we'll return err
+ // because devices cgroup is hard requirement for
+ // container security.
+ if name == "devices" {
+ return err
+ }
+ // For other subsystems, omit the `not found` error
+ // because they are optional.
+ if !cgroups.IsNotFound(err) {
+ return err
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
+// systemd represents slice hierarchy using `-`, so we need to follow suit when
+// generating the path of slice. Essentially, test-a-b.slice becomes
+// test.slice/test-a.slice/test-a-b.slice.
+func ExpandSlice(slice string) (string, error) {
+ suffix := ".slice"
+ // Name has to end with ".slice", but can't be just ".slice".
+ if len(slice) < len(suffix) || !strings.HasSuffix(slice, suffix) {
+ return "", fmt.Errorf("invalid slice name: %s", slice)
+ }
+
+ // Path-separators are not allowed.
+ if strings.Contains(slice, "/") {
+ return "", fmt.Errorf("invalid slice name: %s", slice)
+ }
+
+ var path, prefix string
+ sliceName := strings.TrimSuffix(slice, suffix)
+ // if input was -.slice, we should just return root now
+ if sliceName == "-" {
+ return "/", nil
+ }
+ for _, component := range strings.Split(sliceName, "-") {
+ // test--a.slice isn't permitted, nor is -test.slice.
+ if component == "" {
+ return "", fmt.Errorf("invalid slice name: %s", slice)
+ }
+
+ // Append the component to the path and to the prefix.
+ path += prefix + component + suffix + "/"
+ prefix += component + "-"
+ }
+
+ return path, nil
+}
+
+func getSubsystemPath(c *configs.Cgroup, subsystem string) (string, error) {
+ mountpoint, err := cgroups.FindCgroupMountpoint(subsystem)
+ if err != nil {
+ return "", err
+ }
+
+ initPath, err := cgroups.GetInitCgroup(subsystem)
+ if err != nil {
+ return "", err
+ }
+ // if pid 1 is systemd 226 or later, it will be in init.scope, not the root
+ initPath = strings.TrimSuffix(filepath.Clean(initPath), "init.scope")
+
+ slice := "system.slice"
+ if c.Parent != "" {
+ slice = c.Parent
+ }
+
+ slice, err = ExpandSlice(slice)
+ if err != nil {
+ return "", err
+ }
+
+ return filepath.Join(mountpoint, initPath, slice, getUnitName(c)), nil
+}
+
+func (m *Manager) Freeze(state configs.FreezerState) error {
+ path, err := getSubsystemPath(m.Cgroups, "freezer")
+ if err != nil {
+ return err
+ }
+ prevState := m.Cgroups.Resources.Freezer
+ m.Cgroups.Resources.Freezer = state
+ freezer, err := subsystems.Get("freezer")
+ if err != nil {
+ return err
+ }
+ err = freezer.Set(path, m.Cgroups)
+ if err != nil {
+ m.Cgroups.Resources.Freezer = prevState
+ return err
+ }
+ return nil
+}
+
+func (m *Manager) GetPids() ([]int, error) {
+ path, err := getSubsystemPath(m.Cgroups, "devices")
+ if err != nil {
+ return nil, err
+ }
+ return cgroups.GetPids(path)
+}
+
+func (m *Manager) GetAllPids() ([]int, error) {
+ path, err := getSubsystemPath(m.Cgroups, "devices")
+ if err != nil {
+ return nil, err
+ }
+ return cgroups.GetAllPids(path)
+}
+
+func (m *Manager) GetStats() (*cgroups.Stats, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ stats := cgroups.NewStats()
+ for name, path := range m.Paths {
+ sys, err := subsystems.Get(name)
+ if err == errSubsystemDoesNotExist || !cgroups.PathExists(path) {
+ continue
+ }
+ if err := sys.GetStats(path, stats); err != nil {
+ return nil, err
+ }
+ }
+
+ return stats, nil
+}
+
+func (m *Manager) Set(container *configs.Config) error {
+ // If Paths are set, then we are just joining cgroups paths
+ // and there is no need to set any values.
+ if m.Cgroups.Paths != nil {
+ return nil
+ }
+ for _, sys := range subsystems {
+ // Get the subsystem path, but don't error out for not found cgroups.
+ path, err := getSubsystemPath(container.Cgroups, sys.Name())
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+
+ if err := sys.Set(path, container.Cgroups); err != nil {
+ return err
+ }
+ }
+
+ if m.Paths["cpu"] != "" {
+ if err := fs.CheckCpushares(m.Paths["cpu"], container.Cgroups.Resources.CpuShares); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func getUnitName(c *configs.Cgroup) string {
+ // by default, we create a scope unless the user explicitly asks for a slice.
+ if !strings.HasSuffix(c.Name, ".slice") {
+ return fmt.Sprintf("%s-%s.scope", c.ScopePrefix, c.Name)
+ }
+ return c.Name
+}
+
+func setKernelMemory(c *configs.Cgroup) error {
+ path, err := getSubsystemPath(c, "memory")
+ if err != nil && !cgroups.IsNotFound(err) {
+ return err
+ }
+
+ if err := os.MkdirAll(path, 0755); err != nil {
+ return err
+ }
+ return fs.EnableKernelMemoryAccounting(path)
+}
+
+// isUnitExists returns true if the error is that a systemd unit already exists.
+func isUnitExists(err error) bool {
+ if err != nil {
+ if dbusError, ok := err.(dbus.Error); ok {
+ return strings.Contains(dbusError.Name, "org.freedesktop.systemd1.UnitExists")
+ }
+ }
+ return false
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go
new file mode 100644
index 0000000..5db3734
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go
@@ -0,0 +1,447 @@
+// +build linux
+
+package cgroups
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/docker/go-units"
+)
+
+const (
+ cgroupNamePrefix = "name="
+ CgroupProcesses = "cgroup.procs"
+)
+
+// https://www.kernel.org/doc/Documentation/cgroup-v1/cgroups.txt
+func FindCgroupMountpoint(subsystem string) (string, error) {
+ mnt, _, err := FindCgroupMountpointAndRoot(subsystem)
+ return mnt, err
+}
+
+func FindCgroupMountpointAndRoot(subsystem string) (string, string, error) {
+ // We are not using mount.GetMounts() because it's super-inefficient,
+ // parsing it directly sped up x10 times because of not using Sscanf.
+ // It was one of two major performance drawbacks in container start.
+ if !isSubsystemAvailable(subsystem) {
+ return "", "", NewNotFoundError(subsystem)
+ }
+ f, err := os.Open("/proc/self/mountinfo")
+ if err != nil {
+ return "", "", err
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ txt := scanner.Text()
+ fields := strings.Split(txt, " ")
+ for _, opt := range strings.Split(fields[len(fields)-1], ",") {
+ if opt == subsystem {
+ return fields[4], fields[3], nil
+ }
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ return "", "", err
+ }
+
+ return "", "", NewNotFoundError(subsystem)
+}
+
+func isSubsystemAvailable(subsystem string) bool {
+ cgroups, err := ParseCgroupFile("/proc/self/cgroup")
+ if err != nil {
+ return false
+ }
+ _, avail := cgroups[subsystem]
+ return avail
+}
+
+func FindCgroupMountpointDir() (string, error) {
+ f, err := os.Open("/proc/self/mountinfo")
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ text := scanner.Text()
+ fields := strings.Split(text, " ")
+ // Safe as mountinfo encodes mountpoints with spaces as \040.
+ index := strings.Index(text, " - ")
+ postSeparatorFields := strings.Fields(text[index+3:])
+ numPostFields := len(postSeparatorFields)
+
+ // This is an error as we can't detect if the mount is for "cgroup"
+ if numPostFields == 0 {
+ return "", fmt.Errorf("Found no fields post '-' in %q", text)
+ }
+
+ if postSeparatorFields[0] == "cgroup" {
+ // Check that the mount is properly formated.
+ if numPostFields < 3 {
+ return "", fmt.Errorf("Error found less than 3 fields post '-' in %q", text)
+ }
+
+ return filepath.Dir(fields[4]), nil
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ return "", err
+ }
+
+ return "", NewNotFoundError("cgroup")
+}
+
+type Mount struct {
+ Mountpoint string
+ Root string
+ Subsystems []string
+}
+
+func (m Mount) GetOwnCgroup(cgroups map[string]string) (string, error) {
+ if len(m.Subsystems) == 0 {
+ return "", fmt.Errorf("no subsystem for mount")
+ }
+
+ return getControllerPath(m.Subsystems[0], cgroups)
+}
+
+func getCgroupMountsHelper(ss map[string]bool, mi io.Reader, all bool) ([]Mount, error) {
+ res := make([]Mount, 0, len(ss))
+ scanner := bufio.NewScanner(mi)
+ numFound := 0
+ for scanner.Scan() && numFound < len(ss) {
+ txt := scanner.Text()
+ sepIdx := strings.Index(txt, " - ")
+ if sepIdx == -1 {
+ return nil, fmt.Errorf("invalid mountinfo format")
+ }
+ if txt[sepIdx+3:sepIdx+10] == "cgroup2" || txt[sepIdx+3:sepIdx+9] != "cgroup" {
+ continue
+ }
+ fields := strings.Split(txt, " ")
+ m := Mount{
+ Mountpoint: fields[4],
+ Root: fields[3],
+ }
+ for _, opt := range strings.Split(fields[len(fields)-1], ",") {
+ if !ss[opt] {
+ continue
+ }
+ if strings.HasPrefix(opt, cgroupNamePrefix) {
+ m.Subsystems = append(m.Subsystems, opt[len(cgroupNamePrefix):])
+ } else {
+ m.Subsystems = append(m.Subsystems, opt)
+ }
+ if !all {
+ numFound++
+ }
+ }
+ res = append(res, m)
+ }
+ if err := scanner.Err(); err != nil {
+ return nil, err
+ }
+ return res, nil
+}
+
+// GetCgroupMounts returns the mounts for the cgroup subsystems.
+// all indicates whether to return just the first instance or all the mounts.
+func GetCgroupMounts(all bool) ([]Mount, error) {
+ f, err := os.Open("/proc/self/mountinfo")
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ allSubsystems, err := ParseCgroupFile("/proc/self/cgroup")
+ if err != nil {
+ return nil, err
+ }
+
+ allMap := make(map[string]bool)
+ for s := range allSubsystems {
+ allMap[s] = true
+ }
+ return getCgroupMountsHelper(allMap, f, all)
+}
+
+// GetAllSubsystems returns all the cgroup subsystems supported by the kernel
+func GetAllSubsystems() ([]string, error) {
+ f, err := os.Open("/proc/cgroups")
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ subsystems := []string{}
+
+ s := bufio.NewScanner(f)
+ for s.Scan() {
+ text := s.Text()
+ if text[0] != '#' {
+ parts := strings.Fields(text)
+ if len(parts) >= 4 && parts[3] != "0" {
+ subsystems = append(subsystems, parts[0])
+ }
+ }
+ }
+ if err := s.Err(); err != nil {
+ return nil, err
+ }
+ return subsystems, nil
+}
+
+// GetOwnCgroup returns the relative path to the cgroup docker is running in.
+func GetOwnCgroup(subsystem string) (string, error) {
+ cgroups, err := ParseCgroupFile("/proc/self/cgroup")
+ if err != nil {
+ return "", err
+ }
+
+ return getControllerPath(subsystem, cgroups)
+}
+
+func GetOwnCgroupPath(subsystem string) (string, error) {
+ cgroup, err := GetOwnCgroup(subsystem)
+ if err != nil {
+ return "", err
+ }
+
+ return getCgroupPathHelper(subsystem, cgroup)
+}
+
+func GetInitCgroup(subsystem string) (string, error) {
+ cgroups, err := ParseCgroupFile("/proc/1/cgroup")
+ if err != nil {
+ return "", err
+ }
+
+ return getControllerPath(subsystem, cgroups)
+}
+
+func GetInitCgroupPath(subsystem string) (string, error) {
+ cgroup, err := GetInitCgroup(subsystem)
+ if err != nil {
+ return "", err
+ }
+
+ return getCgroupPathHelper(subsystem, cgroup)
+}
+
+func getCgroupPathHelper(subsystem, cgroup string) (string, error) {
+ mnt, root, err := FindCgroupMountpointAndRoot(subsystem)
+ if err != nil {
+ return "", err
+ }
+
+ // This is needed for nested containers, because in /proc/self/cgroup we
+ // see pathes from host, which don't exist in container.
+ relCgroup, err := filepath.Rel(root, cgroup)
+ if err != nil {
+ return "", err
+ }
+
+ return filepath.Join(mnt, relCgroup), nil
+}
+
+func readProcsFile(dir string) ([]int, error) {
+ f, err := os.Open(filepath.Join(dir, CgroupProcesses))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ var (
+ s = bufio.NewScanner(f)
+ out = []int{}
+ )
+
+ for s.Scan() {
+ if t := s.Text(); t != "" {
+ pid, err := strconv.Atoi(t)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, pid)
+ }
+ }
+ return out, nil
+}
+
+// ParseCgroupFile parses the given cgroup file, typically from
+// /proc/<pid>/cgroup, into a map of subgroups to cgroup names.
+func ParseCgroupFile(path string) (map[string]string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ return parseCgroupFromReader(f)
+}
+
+// helper function for ParseCgroupFile to make testing easier
+func parseCgroupFromReader(r io.Reader) (map[string]string, error) {
+ s := bufio.NewScanner(r)
+ cgroups := make(map[string]string)
+
+ for s.Scan() {
+ text := s.Text()
+ // from cgroups(7):
+ // /proc/[pid]/cgroup
+ // ...
+ // For each cgroup hierarchy ... there is one entry
+ // containing three colon-separated fields of the form:
+ // hierarchy-ID:subsystem-list:cgroup-path
+ parts := strings.SplitN(text, ":", 3)
+ if len(parts) < 3 {
+ return nil, fmt.Errorf("invalid cgroup entry: must contain at least two colons: %v", text)
+ }
+
+ for _, subs := range strings.Split(parts[1], ",") {
+ cgroups[subs] = parts[2]
+ }
+ }
+ if err := s.Err(); err != nil {
+ return nil, err
+ }
+
+ return cgroups, nil
+}
+
+func getControllerPath(subsystem string, cgroups map[string]string) (string, error) {
+
+ if p, ok := cgroups[subsystem]; ok {
+ return p, nil
+ }
+
+ if p, ok := cgroups[cgroupNamePrefix+subsystem]; ok {
+ return p, nil
+ }
+
+ return "", NewNotFoundError(subsystem)
+}
+
+func PathExists(path string) bool {
+ if _, err := os.Stat(path); err != nil {
+ return false
+ }
+ return true
+}
+
+func EnterPid(cgroupPaths map[string]string, pid int) error {
+ for _, path := range cgroupPaths {
+ if PathExists(path) {
+ if err := WriteCgroupProc(path, pid); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// RemovePaths iterates over the provided paths removing them.
+// We trying to remove all paths five times with increasing delay between tries.
+// If after all there are not removed cgroups - appropriate error will be
+// returned.
+func RemovePaths(paths map[string]string) (err error) {
+ delay := 10 * time.Millisecond
+ for i := 0; i < 5; i++ {
+ if i != 0 {
+ time.Sleep(delay)
+ delay *= 2
+ }
+ for s, p := range paths {
+ os.RemoveAll(p)
+ // TODO: here probably should be logging
+ _, err := os.Stat(p)
+ // We need this strange way of checking cgroups existence because
+ // RemoveAll almost always returns error, even on already removed
+ // cgroups
+ if os.IsNotExist(err) {
+ delete(paths, s)
+ }
+ }
+ if len(paths) == 0 {
+ return nil
+ }
+ }
+ return fmt.Errorf("Failed to remove paths: %v", paths)
+}
+
+func GetHugePageSize() ([]string, error) {
+ var pageSizes []string
+ sizeList := []string{"B", "kB", "MB", "GB", "TB", "PB"}
+ files, err := ioutil.ReadDir("/sys/kernel/mm/hugepages")
+ if err != nil {
+ return pageSizes, err
+ }
+ for _, st := range files {
+ nameArray := strings.Split(st.Name(), "-")
+ pageSize, err := units.RAMInBytes(nameArray[1])
+ if err != nil {
+ return []string{}, err
+ }
+ sizeString := units.CustomSize("%g%s", float64(pageSize), 1024.0, sizeList)
+ pageSizes = append(pageSizes, sizeString)
+ }
+
+ return pageSizes, nil
+}
+
+// GetPids returns all pids, that were added to cgroup at path.
+func GetPids(path string) ([]int, error) {
+ return readProcsFile(path)
+}
+
+// GetAllPids returns all pids, that were added to cgroup at path and to all its
+// subcgroups.
+func GetAllPids(path string) ([]int, error) {
+ var pids []int
+ // collect pids from all sub-cgroups
+ err := filepath.Walk(path, func(p string, info os.FileInfo, iErr error) error {
+ dir, file := filepath.Split(p)
+ if file != CgroupProcesses {
+ return nil
+ }
+ if iErr != nil {
+ return iErr
+ }
+ cPids, err := readProcsFile(dir)
+ if err != nil {
+ return err
+ }
+ pids = append(pids, cPids...)
+ return nil
+ })
+ return pids, err
+}
+
+// WriteCgroupProc writes the specified pid into the cgroup's cgroup.procs file
+func WriteCgroupProc(dir string, pid int) error {
+ // Normally dir should not be empty, one case is that cgroup subsystem
+ // is not mounted, we will get empty dir, and we want it fail here.
+ if dir == "" {
+ return fmt.Errorf("no such directory for %s", CgroupProcesses)
+ }
+
+ // Dont attach any pid to the cgroup if -1 is specified as a pid
+ if pid != -1 {
+ if err := ioutil.WriteFile(filepath.Join(dir, CgroupProcesses), []byte(strconv.Itoa(pid)), 0700); err != nil {
+ return fmt.Errorf("failed to write %v to %v: %v", pid, CgroupProcesses, err)
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/compat_1.5_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/compat_1.5_linux.go
new file mode 100644
index 0000000..c7bdf1f
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/compat_1.5_linux.go
@@ -0,0 +1,10 @@
+// +build linux,!go1.5
+
+package libcontainer
+
+import "syscall"
+
+// GidMappingsEnableSetgroups was added in Go 1.5, so do nothing when building
+// with earlier versions
+func enableSetgroups(sys *syscall.SysProcAttr) {
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/blkio_device.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/blkio_device.go
new file mode 100644
index 0000000..e0f3ca1
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/blkio_device.go
@@ -0,0 +1,61 @@
+package configs
+
+import "fmt"
+
+// blockIODevice holds major:minor format supported in blkio cgroup
+type blockIODevice struct {
+ // Major is the device's major number
+ Major int64 `json:"major"`
+ // Minor is the device's minor number
+ Minor int64 `json:"minor"`
+}
+
+// WeightDevice struct holds a `major:minor weight`|`major:minor leaf_weight` pair
+type WeightDevice struct {
+ blockIODevice
+ // Weight is the bandwidth rate for the device, range is from 10 to 1000
+ Weight uint16 `json:"weight"`
+ // LeafWeight is the bandwidth rate for the device while competing with the cgroup's child cgroups, range is from 10 to 1000, cfq scheduler only
+ LeafWeight uint16 `json:"leafWeight"`
+}
+
+// NewWeightDevice returns a configured WeightDevice pointer
+func NewWeightDevice(major, minor int64, weight, leafWeight uint16) *WeightDevice {
+ wd := &WeightDevice{}
+ wd.Major = major
+ wd.Minor = minor
+ wd.Weight = weight
+ wd.LeafWeight = leafWeight
+ return wd
+}
+
+// WeightString formats the struct to be writable to the cgroup specific file
+func (wd *WeightDevice) WeightString() string {
+ return fmt.Sprintf("%d:%d %d", wd.Major, wd.Minor, wd.Weight)
+}
+
+// LeafWeightString formats the struct to be writable to the cgroup specific file
+func (wd *WeightDevice) LeafWeightString() string {
+ return fmt.Sprintf("%d:%d %d", wd.Major, wd.Minor, wd.LeafWeight)
+}
+
+// ThrottleDevice struct holds a `major:minor rate_per_second` pair
+type ThrottleDevice struct {
+ blockIODevice
+ // Rate is the IO rate limit per cgroup per device
+ Rate uint64 `json:"rate"`
+}
+
+// NewThrottleDevice returns a configured ThrottleDevice pointer
+func NewThrottleDevice(major, minor int64, rate uint64) *ThrottleDevice {
+ td := &ThrottleDevice{}
+ td.Major = major
+ td.Minor = minor
+ td.Rate = rate
+ return td
+}
+
+// String formats the struct to be writable to the cgroup specific file
+func (td *ThrottleDevice) String() string {
+ return fmt.Sprintf("%d:%d %d", td.Major, td.Minor, td.Rate)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go
new file mode 100644
index 0000000..7572289
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go
@@ -0,0 +1,124 @@
+// +build linux freebsd
+
+package configs
+
+type FreezerState string
+
+const (
+ Undefined FreezerState = ""
+ Frozen FreezerState = "FROZEN"
+ Thawed FreezerState = "THAWED"
+)
+
+type Cgroup struct {
+ // Deprecated, use Path instead
+ Name string `json:"name,omitempty"`
+
+ // name of parent of cgroup or slice
+ // Deprecated, use Path instead
+ Parent string `json:"parent,omitempty"`
+
+ // Path specifies the path to cgroups that are created and/or joined by the container.
+ // The path is assumed to be relative to the host system cgroup mountpoint.
+ Path string `json:"path"`
+
+ // ScopePrefix describes prefix for the scope name
+ ScopePrefix string `json:"scope_prefix"`
+
+ // Paths represent the absolute cgroups paths to join.
+ // This takes precedence over Path.
+ Paths map[string]string
+
+ // Resources contains various cgroups settings to apply
+ *Resources
+}
+
+type Resources struct {
+ // If this is true allow access to any kind of device within the container. If false, allow access only to devices explicitly listed in the allowed_devices list.
+ // Deprecated
+ AllowAllDevices *bool `json:"allow_all_devices,omitempty"`
+ // Deprecated
+ AllowedDevices []*Device `json:"allowed_devices,omitempty"`
+ // Deprecated
+ DeniedDevices []*Device `json:"denied_devices,omitempty"`
+
+ Devices []*Device `json:"devices"`
+
+ // Memory limit (in bytes)
+ Memory uint64 `json:"memory"`
+
+ // Memory reservation or soft_limit (in bytes)
+ MemoryReservation uint64 `json:"memory_reservation"`
+
+ // Total memory usage (memory + swap); set `-1` to enable unlimited swap
+ MemorySwap uint64 `json:"memory_swap"`
+
+ // Kernel memory limit (in bytes)
+ KernelMemory uint64 `json:"kernel_memory"`
+
+ // Kernel memory limit for TCP use (in bytes)
+ KernelMemoryTCP uint64 `json:"kernel_memory_tcp"`
+
+ // CPU shares (relative weight vs. other containers)
+ CpuShares uint64 `json:"cpu_shares"`
+
+ // CPU hardcap limit (in usecs). Allowed cpu time in a given period.
+ CpuQuota int64 `json:"cpu_quota"`
+
+ // CPU period to be used for hardcapping (in usecs). 0 to use system default.
+ CpuPeriod uint64 `json:"cpu_period"`
+
+ // How many time CPU will use in realtime scheduling (in usecs).
+ CpuRtRuntime int64 `json:"cpu_rt_quota"`
+
+ // CPU period to be used for realtime scheduling (in usecs).
+ CpuRtPeriod uint64 `json:"cpu_rt_period"`
+
+ // CPU to use
+ CpusetCpus string `json:"cpuset_cpus"`
+
+ // MEM to use
+ CpusetMems string `json:"cpuset_mems"`
+
+ // Process limit; set <= `0' to disable limit.
+ PidsLimit int64 `json:"pids_limit"`
+
+ // Specifies per cgroup weight, range is from 10 to 1000.
+ BlkioWeight uint16 `json:"blkio_weight"`
+
+ // Specifies tasks' weight in the given cgroup while competing with the cgroup's child cgroups, range is from 10 to 1000, cfq scheduler only
+ BlkioLeafWeight uint16 `json:"blkio_leaf_weight"`
+
+ // Weight per cgroup per device, can override BlkioWeight.
+ BlkioWeightDevice []*WeightDevice `json:"blkio_weight_device"`
+
+ // IO read rate limit per cgroup per device, bytes per second.
+ BlkioThrottleReadBpsDevice []*ThrottleDevice `json:"blkio_throttle_read_bps_device"`
+
+ // IO write rate limit per cgroup per device, bytes per second.
+ BlkioThrottleWriteBpsDevice []*ThrottleDevice `json:"blkio_throttle_write_bps_device"`
+
+ // IO read rate limit per cgroup per device, IO per second.
+ BlkioThrottleReadIOPSDevice []*ThrottleDevice `json:"blkio_throttle_read_iops_device"`
+
+ // IO write rate limit per cgroup per device, IO per second.
+ BlkioThrottleWriteIOPSDevice []*ThrottleDevice `json:"blkio_throttle_write_iops_device"`
+
+ // set the freeze value for the process
+ Freezer FreezerState `json:"freezer"`
+
+ // Hugetlb limit (in bytes)
+ HugetlbLimit []*HugepageLimit `json:"hugetlb_limit"`
+
+ // Whether to disable OOM Killer
+ OomKillDisable bool `json:"oom_kill_disable"`
+
+ // Tuning swappiness behaviour per cgroup
+ MemorySwappiness *uint64 `json:"memory_swappiness"`
+
+ // Set priority of network traffic for container
+ NetPrioIfpriomap []*IfPrioMap `json:"net_prio_ifpriomap"`
+
+ // Set class identifier for container's network packets
+ NetClsClassid uint32 `json:"net_cls_classid_u"`
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unsupported.go
new file mode 100644
index 0000000..95e2830
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unsupported.go
@@ -0,0 +1,6 @@
+// +build !windows,!linux,!freebsd
+
+package configs
+
+type Cgroup struct {
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_windows.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_windows.go
new file mode 100644
index 0000000..d74847b
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_windows.go
@@ -0,0 +1,6 @@
+package configs
+
+// TODO Windows: This can ultimately be entirely factored out on Windows as
+// cgroups are a Unix-specific construct.
+type Cgroup struct {
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/config.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/config.go
new file mode 100644
index 0000000..98f4b85
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/config.go
@@ -0,0 +1,343 @@
+package configs
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "os/exec"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+type Rlimit struct {
+ Type int `json:"type"`
+ Hard uint64 `json:"hard"`
+ Soft uint64 `json:"soft"`
+}
+
+// IDMap represents UID/GID Mappings for User Namespaces.
+type IDMap struct {
+ ContainerID int `json:"container_id"`
+ HostID int `json:"host_id"`
+ Size int `json:"size"`
+}
+
+// Seccomp represents syscall restrictions
+// By default, only the native architecture of the kernel is allowed to be used
+// for syscalls. Additional architectures can be added by specifying them in
+// Architectures.
+type Seccomp struct {
+ DefaultAction Action `json:"default_action"`
+ Architectures []string `json:"architectures"`
+ Syscalls []*Syscall `json:"syscalls"`
+}
+
+// Action is taken upon rule match in Seccomp
+type Action int
+
+const (
+ Kill Action = iota + 1
+ Errno
+ Trap
+ Allow
+ Trace
+)
+
+// Operator is a comparison operator to be used when matching syscall arguments in Seccomp
+type Operator int
+
+const (
+ EqualTo Operator = iota + 1
+ NotEqualTo
+ GreaterThan
+ GreaterThanOrEqualTo
+ LessThan
+ LessThanOrEqualTo
+ MaskEqualTo
+)
+
+// Arg is a rule to match a specific syscall argument in Seccomp
+type Arg struct {
+ Index uint `json:"index"`
+ Value uint64 `json:"value"`
+ ValueTwo uint64 `json:"value_two"`
+ Op Operator `json:"op"`
+}
+
+// Syscall is a rule to match a syscall in Seccomp
+type Syscall struct {
+ Name string `json:"name"`
+ Action Action `json:"action"`
+ Args []*Arg `json:"args"`
+}
+
+// TODO Windows. Many of these fields should be factored out into those parts
+// which are common across platforms, and those which are platform specific.
+
+// Config defines configuration options for executing a process inside a contained environment.
+type Config struct {
+ // NoPivotRoot will use MS_MOVE and a chroot to jail the process into the container's rootfs
+ // This is a common option when the container is running in ramdisk
+ NoPivotRoot bool `json:"no_pivot_root"`
+
+ // ParentDeathSignal specifies the signal that is sent to the container's process in the case
+ // that the parent process dies.
+ ParentDeathSignal int `json:"parent_death_signal"`
+
+ // Path to a directory containing the container's root filesystem.
+ Rootfs string `json:"rootfs"`
+
+ // Readonlyfs will remount the container's rootfs as readonly where only externally mounted
+ // bind mounts are writtable.
+ Readonlyfs bool `json:"readonlyfs"`
+
+ // Specifies the mount propagation flags to be applied to /.
+ RootPropagation int `json:"rootPropagation"`
+
+ // Mounts specify additional source and destination paths that will be mounted inside the container's
+ // rootfs and mount namespace if specified
+ Mounts []*Mount `json:"mounts"`
+
+ // The device nodes that should be automatically created within the container upon container start. Note, make sure that the node is marked as allowed in the cgroup as well!
+ Devices []*Device `json:"devices"`
+
+ MountLabel string `json:"mount_label"`
+
+ // Hostname optionally sets the container's hostname if provided
+ Hostname string `json:"hostname"`
+
+ // Namespaces specifies the container's namespaces that it should setup when cloning the init process
+ // If a namespace is not provided that namespace is shared from the container's parent process
+ Namespaces Namespaces `json:"namespaces"`
+
+ // Capabilities specify the capabilities to keep when executing the process inside the container
+ // All capabilities not specified will be dropped from the processes capability mask
+ Capabilities *Capabilities `json:"capabilities"`
+
+ // Networks specifies the container's network setup to be created
+ Networks []*Network `json:"networks"`
+
+ // Routes can be specified to create entries in the route table as the container is started
+ Routes []*Route `json:"routes"`
+
+ // Cgroups specifies specific cgroup settings for the various subsystems that the container is
+ // placed into to limit the resources the container has available
+ Cgroups *Cgroup `json:"cgroups"`
+
+ // AppArmorProfile specifies the profile to apply to the process running in the container and is
+ // change at the time the process is execed
+ AppArmorProfile string `json:"apparmor_profile,omitempty"`
+
+ // ProcessLabel specifies the label to apply to the process running in the container. It is
+ // commonly used by selinux
+ ProcessLabel string `json:"process_label,omitempty"`
+
+ // Rlimits specifies the resource limits, such as max open files, to set in the container
+ // If Rlimits are not set, the container will inherit rlimits from the parent process
+ Rlimits []Rlimit `json:"rlimits,omitempty"`
+
+ // OomScoreAdj specifies the adjustment to be made by the kernel when calculating oom scores
+ // for a process. Valid values are between the range [-1000, '1000'], where processes with
+ // higher scores are preferred for being killed.
+ // More information about kernel oom score calculation here: https://lwn.net/Articles/317814/
+ OomScoreAdj int `json:"oom_score_adj"`
+
+ // UidMappings is an array of User ID mappings for User Namespaces
+ UidMappings []IDMap `json:"uid_mappings"`
+
+ // GidMappings is an array of Group ID mappings for User Namespaces
+ GidMappings []IDMap `json:"gid_mappings"`
+
+ // MaskPaths specifies paths within the container's rootfs to mask over with a bind
+ // mount pointing to /dev/null as to prevent reads of the file.
+ MaskPaths []string `json:"mask_paths"`
+
+ // ReadonlyPaths specifies paths within the container's rootfs to remount as read-only
+ // so that these files prevent any writes.
+ ReadonlyPaths []string `json:"readonly_paths"`
+
+ // Sysctl is a map of properties and their values. It is the equivalent of using
+ // sysctl -w my.property.name value in Linux.
+ Sysctl map[string]string `json:"sysctl"`
+
+ // Seccomp allows actions to be taken whenever a syscall is made within the container.
+ // A number of rules are given, each having an action to be taken if a syscall matches it.
+ // A default action to be taken if no rules match is also given.
+ Seccomp *Seccomp `json:"seccomp"`
+
+ // NoNewPrivileges controls whether processes in the container can gain additional privileges.
+ NoNewPrivileges bool `json:"no_new_privileges,omitempty"`
+
+ // Hooks are a collection of actions to perform at various container lifecycle events.
+ // CommandHooks are serialized to JSON, but other hooks are not.
+ Hooks *Hooks
+
+ // Version is the version of opencontainer specification that is supported.
+ Version string `json:"version"`
+
+ // Labels are user defined metadata that is stored in the config and populated on the state
+ Labels []string `json:"labels"`
+
+ // NoNewKeyring will not allocated a new session keyring for the container. It will use the
+ // callers keyring in this case.
+ NoNewKeyring bool `json:"no_new_keyring"`
+
+ // Rootless specifies whether the container is a rootless container.
+ Rootless bool `json:"rootless"`
+}
+
+type Hooks struct {
+ // Prestart commands are executed after the container namespaces are created,
+ // but before the user supplied command is executed from init.
+ Prestart []Hook
+
+ // Poststart commands are executed after the container init process starts.
+ Poststart []Hook
+
+ // Poststop commands are executed after the container init process exits.
+ Poststop []Hook
+}
+
+type Capabilities struct {
+ // Bounding is the set of capabilities checked by the kernel.
+ Bounding []string
+ // Effective is the set of capabilities checked by the kernel.
+ Effective []string
+ // Inheritable is the capabilities preserved across execve.
+ Inheritable []string
+ // Permitted is the limiting superset for effective capabilities.
+ Permitted []string
+ // Ambient is the ambient set of capabilities that are kept.
+ Ambient []string
+}
+
+func (hooks *Hooks) UnmarshalJSON(b []byte) error {
+ var state struct {
+ Prestart []CommandHook
+ Poststart []CommandHook
+ Poststop []CommandHook
+ }
+
+ if err := json.Unmarshal(b, &state); err != nil {
+ return err
+ }
+
+ deserialize := func(shooks []CommandHook) (hooks []Hook) {
+ for _, shook := range shooks {
+ hooks = append(hooks, shook)
+ }
+
+ return hooks
+ }
+
+ hooks.Prestart = deserialize(state.Prestart)
+ hooks.Poststart = deserialize(state.Poststart)
+ hooks.Poststop = deserialize(state.Poststop)
+ return nil
+}
+
+func (hooks Hooks) MarshalJSON() ([]byte, error) {
+ serialize := func(hooks []Hook) (serializableHooks []CommandHook) {
+ for _, hook := range hooks {
+ switch chook := hook.(type) {
+ case CommandHook:
+ serializableHooks = append(serializableHooks, chook)
+ default:
+ logrus.Warnf("cannot serialize hook of type %T, skipping", hook)
+ }
+ }
+
+ return serializableHooks
+ }
+
+ return json.Marshal(map[string]interface{}{
+ "prestart": serialize(hooks.Prestart),
+ "poststart": serialize(hooks.Poststart),
+ "poststop": serialize(hooks.Poststop),
+ })
+}
+
+// HookState is the payload provided to a hook on execution.
+type HookState specs.State
+
+type Hook interface {
+ // Run executes the hook with the provided state.
+ Run(HookState) error
+}
+
+// NewFunctionHook will call the provided function when the hook is run.
+func NewFunctionHook(f func(HookState) error) FuncHook {
+ return FuncHook{
+ run: f,
+ }
+}
+
+type FuncHook struct {
+ run func(HookState) error
+}
+
+func (f FuncHook) Run(s HookState) error {
+ return f.run(s)
+}
+
+type Command struct {
+ Path string `json:"path"`
+ Args []string `json:"args"`
+ Env []string `json:"env"`
+ Dir string `json:"dir"`
+ Timeout *time.Duration `json:"timeout"`
+}
+
+// NewCommandHook will execute the provided command when the hook is run.
+func NewCommandHook(cmd Command) CommandHook {
+ return CommandHook{
+ Command: cmd,
+ }
+}
+
+type CommandHook struct {
+ Command
+}
+
+func (c Command) Run(s HookState) error {
+ b, err := json.Marshal(s)
+ if err != nil {
+ return err
+ }
+ var stdout, stderr bytes.Buffer
+ cmd := exec.Cmd{
+ Path: c.Path,
+ Args: c.Args,
+ Env: c.Env,
+ Stdin: bytes.NewReader(b),
+ Stdout: &stdout,
+ Stderr: &stderr,
+ }
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ errC := make(chan error, 1)
+ go func() {
+ err := cmd.Wait()
+ if err != nil {
+ err = fmt.Errorf("error running hook: %v, stdout: %s, stderr: %s", err, stdout.String(), stderr.String())
+ }
+ errC <- err
+ }()
+ var timerCh <-chan time.Time
+ if c.Timeout != nil {
+ timer := time.NewTimer(*c.Timeout)
+ defer timer.Stop()
+ timerCh = timer.C
+ }
+ select {
+ case err := <-errC:
+ return err
+ case <-timerCh:
+ cmd.Process.Kill()
+ cmd.Wait()
+ return fmt.Errorf("hook ran past specified timeout of %.1fs", c.Timeout.Seconds())
+ }
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/config_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/config_unix.go
new file mode 100644
index 0000000..8446399
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/config_unix.go
@@ -0,0 +1,63 @@
+// +build freebsd linux
+
+package configs
+
+import "fmt"
+
+// HostUID gets the translated uid for the process on host which could be
+// different when user namespaces are enabled.
+func (c Config) HostUID(containerId int) (int, error) {
+ if c.Namespaces.Contains(NEWUSER) {
+ if c.UidMappings == nil {
+ return -1, fmt.Errorf("User namespaces enabled, but no uid mappings found.")
+ }
+ id, found := c.hostIDFromMapping(containerId, c.UidMappings)
+ if !found {
+ return -1, fmt.Errorf("User namespaces enabled, but no user mapping found.")
+ }
+ return id, nil
+ }
+ // Return unchanged id.
+ return containerId, nil
+}
+
+// HostRootUID gets the root uid for the process on host which could be non-zero
+// when user namespaces are enabled.
+func (c Config) HostRootUID() (int, error) {
+ return c.HostUID(0)
+}
+
+// HostGID gets the translated gid for the process on host which could be
+// different when user namespaces are enabled.
+func (c Config) HostGID(containerId int) (int, error) {
+ if c.Namespaces.Contains(NEWUSER) {
+ if c.GidMappings == nil {
+ return -1, fmt.Errorf("User namespaces enabled, but no gid mappings found.")
+ }
+ id, found := c.hostIDFromMapping(containerId, c.GidMappings)
+ if !found {
+ return -1, fmt.Errorf("User namespaces enabled, but no group mapping found.")
+ }
+ return id, nil
+ }
+ // Return unchanged id.
+ return containerId, nil
+}
+
+// HostRootGID gets the root gid for the process on host which could be non-zero
+// when user namespaces are enabled.
+func (c Config) HostRootGID() (int, error) {
+ return c.HostGID(0)
+}
+
+// Utility function that gets a host ID for a container ID from user namespace map
+// if that ID is present in the map.
+func (c Config) hostIDFromMapping(containerID int, uMap []IDMap) (int, bool) {
+ for _, m := range uMap {
+ if (containerID >= m.ContainerID) && (containerID <= (m.ContainerID + m.Size - 1)) {
+ hostID := m.HostID + (containerID - m.ContainerID)
+ return hostID, true
+ }
+ }
+ return -1, false
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/device.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/device.go
new file mode 100644
index 0000000..8701bb2
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/device.go
@@ -0,0 +1,57 @@
+package configs
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ Wildcard = -1
+)
+
+// TODO Windows: This can be factored out in the future
+
+type Device struct {
+ // Device type, block, char, etc.
+ Type rune `json:"type"`
+
+ // Path to the device.
+ Path string `json:"path"`
+
+ // Major is the device's major number.
+ Major int64 `json:"major"`
+
+ // Minor is the device's minor number.
+ Minor int64 `json:"minor"`
+
+ // Cgroup permissions format, rwm.
+ Permissions string `json:"permissions"`
+
+ // FileMode permission bits for the device.
+ FileMode os.FileMode `json:"file_mode"`
+
+ // Uid of the device.
+ Uid uint32 `json:"uid"`
+
+ // Gid of the device.
+ Gid uint32 `json:"gid"`
+
+ // Write the file to the allowed list
+ Allow bool `json:"allow"`
+}
+
+func (d *Device) CgroupString() string {
+ return fmt.Sprintf("%c %s:%s %s", d.Type, deviceNumberString(d.Major), deviceNumberString(d.Minor), d.Permissions)
+}
+
+func (d *Device) Mkdev() int {
+ return int((d.Major << 8) | (d.Minor & 0xff) | ((d.Minor & 0xfff00) << 12))
+}
+
+// deviceNumberString converts the device number to a string return result.
+func deviceNumberString(number int64) string {
+ if number == Wildcard {
+ return "*"
+ }
+ return fmt.Sprint(number)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/device_defaults.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/device_defaults.go
new file mode 100644
index 0000000..4d348d2
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/device_defaults.go
@@ -0,0 +1,111 @@
+// +build linux freebsd
+
+package configs
+
+var (
+ // DefaultSimpleDevices are devices that are to be both allowed and created.
+ DefaultSimpleDevices = []*Device{
+ // /dev/null and zero
+ {
+ Path: "/dev/null",
+ Type: 'c',
+ Major: 1,
+ Minor: 3,
+ Permissions: "rwm",
+ FileMode: 0666,
+ },
+ {
+ Path: "/dev/zero",
+ Type: 'c',
+ Major: 1,
+ Minor: 5,
+ Permissions: "rwm",
+ FileMode: 0666,
+ },
+
+ {
+ Path: "/dev/full",
+ Type: 'c',
+ Major: 1,
+ Minor: 7,
+ Permissions: "rwm",
+ FileMode: 0666,
+ },
+
+ // consoles and ttys
+ {
+ Path: "/dev/tty",
+ Type: 'c',
+ Major: 5,
+ Minor: 0,
+ Permissions: "rwm",
+ FileMode: 0666,
+ },
+
+ // /dev/urandom,/dev/random
+ {
+ Path: "/dev/urandom",
+ Type: 'c',
+ Major: 1,
+ Minor: 9,
+ Permissions: "rwm",
+ FileMode: 0666,
+ },
+ {
+ Path: "/dev/random",
+ Type: 'c',
+ Major: 1,
+ Minor: 8,
+ Permissions: "rwm",
+ FileMode: 0666,
+ },
+ }
+ DefaultAllowedDevices = append([]*Device{
+ // allow mknod for any device
+ {
+ Type: 'c',
+ Major: Wildcard,
+ Minor: Wildcard,
+ Permissions: "m",
+ },
+ {
+ Type: 'b',
+ Major: Wildcard,
+ Minor: Wildcard,
+ Permissions: "m",
+ },
+
+ {
+ Path: "/dev/console",
+ Type: 'c',
+ Major: 5,
+ Minor: 1,
+ Permissions: "rwm",
+ },
+ // /dev/pts/ - pts namespaces are "coming soon"
+ {
+ Path: "",
+ Type: 'c',
+ Major: 136,
+ Minor: Wildcard,
+ Permissions: "rwm",
+ },
+ {
+ Path: "",
+ Type: 'c',
+ Major: 5,
+ Minor: 2,
+ Permissions: "rwm",
+ },
+
+ // tuntap
+ {
+ Path: "",
+ Type: 'c',
+ Major: 10,
+ Minor: 200,
+ Permissions: "rwm",
+ },
+ }, DefaultSimpleDevices...)
+ DefaultAutoCreatedDevices = append([]*Device{}, DefaultSimpleDevices...)
+)
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/hugepage_limit.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/hugepage_limit.go
new file mode 100644
index 0000000..d302163
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/hugepage_limit.go
@@ -0,0 +1,9 @@
+package configs
+
+type HugepageLimit struct {
+ // which type of hugepage to limit.
+ Pagesize string `json:"page_size"`
+
+ // usage limit for hugepage.
+ Limit uint64 `json:"limit"`
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/interface_priority_map.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/interface_priority_map.go
new file mode 100644
index 0000000..9a0395e
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/interface_priority_map.go
@@ -0,0 +1,14 @@
+package configs
+
+import (
+ "fmt"
+)
+
+type IfPrioMap struct {
+ Interface string `json:"interface"`
+ Priority int64 `json:"priority"`
+}
+
+func (i *IfPrioMap) CgroupString() string {
+ return fmt.Sprintf("%s %d", i.Interface, i.Priority)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/mount.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/mount.go
new file mode 100644
index 0000000..670757d
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/mount.go
@@ -0,0 +1,39 @@
+package configs
+
+const (
+ // EXT_COPYUP is a directive to copy up the contents of a directory when
+ // a tmpfs is mounted over it.
+ EXT_COPYUP = 1 << iota
+)
+
+type Mount struct {
+ // Source path for the mount.
+ Source string `json:"source"`
+
+ // Destination path for the mount inside the container.
+ Destination string `json:"destination"`
+
+ // Device the mount is for.
+ Device string `json:"device"`
+
+ // Mount flags.
+ Flags int `json:"flags"`
+
+ // Propagation Flags
+ PropagationFlags []int `json:"propagation_flags"`
+
+ // Mount data applied to the mount.
+ Data string `json:"data"`
+
+ // Relabel source if set, "z" indicates shared, "Z" indicates unshared.
+ Relabel string `json:"relabel"`
+
+ // Extensions are additional flags that are specific to runc.
+ Extensions int `json:"extensions"`
+
+ // Optional Command to be run before Source is mounted.
+ PremountCmds []Command `json:"premount_cmds"`
+
+ // Optional Command to be run after Source is mounted.
+ PostmountCmds []Command `json:"postmount_cmds"`
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces.go
new file mode 100644
index 0000000..a3329a3
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces.go
@@ -0,0 +1,5 @@
+package configs
+
+type NamespaceType string
+
+type Namespaces []Namespace
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go
new file mode 100644
index 0000000..fb4b852
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go
@@ -0,0 +1,31 @@
+// +build linux
+
+package configs
+
+import "syscall"
+
+func (n *Namespace) Syscall() int {
+ return namespaceInfo[n.Type]
+}
+
+var namespaceInfo = map[NamespaceType]int{
+ NEWNET: syscall.CLONE_NEWNET,
+ NEWNS: syscall.CLONE_NEWNS,
+ NEWUSER: syscall.CLONE_NEWUSER,
+ NEWIPC: syscall.CLONE_NEWIPC,
+ NEWUTS: syscall.CLONE_NEWUTS,
+ NEWPID: syscall.CLONE_NEWPID,
+}
+
+// CloneFlags parses the container's Namespaces options to set the correct
+// flags on clone, unshare. This function returns flags only for new namespaces.
+func (n *Namespaces) CloneFlags() uintptr {
+ var flag int
+ for _, v := range *n {
+ if v.Path != "" {
+ continue
+ }
+ flag |= namespaceInfo[v.Type]
+ }
+ return uintptr(flag)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go
new file mode 100644
index 0000000..5d9a5c8
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go
@@ -0,0 +1,13 @@
+// +build !linux,!windows
+
+package configs
+
+func (n *Namespace) Syscall() int {
+ panic("No namespace syscall support")
+}
+
+// CloneFlags parses the container's Namespaces options to set the correct
+// flags on clone, unshare. This function returns flags only for new namespaces.
+func (n *Namespaces) CloneFlags() uintptr {
+ panic("No namespace syscall support")
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go
new file mode 100644
index 0000000..1f0b3ee
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go
@@ -0,0 +1,127 @@
+// +build linux freebsd
+
+package configs
+
+import (
+ "fmt"
+ "os"
+ "sync"
+)
+
+const (
+ NEWNET NamespaceType = "NEWNET"
+ NEWPID NamespaceType = "NEWPID"
+ NEWNS NamespaceType = "NEWNS"
+ NEWUTS NamespaceType = "NEWUTS"
+ NEWIPC NamespaceType = "NEWIPC"
+ NEWUSER NamespaceType = "NEWUSER"
+)
+
+var (
+ nsLock sync.Mutex
+ supportedNamespaces = make(map[NamespaceType]bool)
+)
+
+// NsName converts the namespace type to its filename
+func NsName(ns NamespaceType) string {
+ switch ns {
+ case NEWNET:
+ return "net"
+ case NEWNS:
+ return "mnt"
+ case NEWPID:
+ return "pid"
+ case NEWIPC:
+ return "ipc"
+ case NEWUSER:
+ return "user"
+ case NEWUTS:
+ return "uts"
+ }
+ return ""
+}
+
+// IsNamespaceSupported returns whether a namespace is available or
+// not
+func IsNamespaceSupported(ns NamespaceType) bool {
+ nsLock.Lock()
+ defer nsLock.Unlock()
+ supported, ok := supportedNamespaces[ns]
+ if ok {
+ return supported
+ }
+ nsFile := NsName(ns)
+ // if the namespace type is unknown, just return false
+ if nsFile == "" {
+ return false
+ }
+ _, err := os.Stat(fmt.Sprintf("/proc/self/ns/%s", nsFile))
+ // a namespace is supported if it exists and we have permissions to read it
+ supported = err == nil
+ supportedNamespaces[ns] = supported
+ return supported
+}
+
+func NamespaceTypes() []NamespaceType {
+ return []NamespaceType{
+ NEWUSER, // Keep user NS always first, don't move it.
+ NEWIPC,
+ NEWUTS,
+ NEWNET,
+ NEWPID,
+ NEWNS,
+ }
+}
+
+// Namespace defines configuration for each namespace. It specifies an
+// alternate path that is able to be joined via setns.
+type Namespace struct {
+ Type NamespaceType `json:"type"`
+ Path string `json:"path"`
+}
+
+func (n *Namespace) GetPath(pid int) string {
+ if n.Path != "" {
+ return n.Path
+ }
+ return fmt.Sprintf("/proc/%d/ns/%s", pid, NsName(n.Type))
+}
+
+func (n *Namespaces) Remove(t NamespaceType) bool {
+ i := n.index(t)
+ if i == -1 {
+ return false
+ }
+ *n = append((*n)[:i], (*n)[i+1:]...)
+ return true
+}
+
+func (n *Namespaces) Add(t NamespaceType, path string) {
+ i := n.index(t)
+ if i == -1 {
+ *n = append(*n, Namespace{Type: t, Path: path})
+ return
+ }
+ (*n)[i].Path = path
+}
+
+func (n *Namespaces) index(t NamespaceType) int {
+ for i, ns := range *n {
+ if ns.Type == t {
+ return i
+ }
+ }
+ return -1
+}
+
+func (n *Namespaces) Contains(t NamespaceType) bool {
+ return n.index(t) != -1
+}
+
+func (n *Namespaces) PathOf(t NamespaceType) string {
+ i := n.index(t)
+ if i == -1 {
+ return ""
+ }
+ return (*n)[i].Path
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unsupported.go
new file mode 100644
index 0000000..9a74033
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unsupported.go
@@ -0,0 +1,8 @@
+// +build !linux,!freebsd
+
+package configs
+
+// Namespace defines configuration for each namespace. It specifies an
+// alternate path that is able to be joined via setns.
+type Namespace struct {
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/network.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/network.go
new file mode 100644
index 0000000..ccdb228
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/network.go
@@ -0,0 +1,72 @@
+package configs
+
+// Network defines configuration for a container's networking stack
+//
+// The network configuration can be omitted from a container causing the
+// container to be setup with the host's networking stack
+type Network struct {
+ // Type sets the networks type, commonly veth and loopback
+ Type string `json:"type"`
+
+ // Name of the network interface
+ Name string `json:"name"`
+
+ // The bridge to use.
+ Bridge string `json:"bridge"`
+
+ // MacAddress contains the MAC address to set on the network interface
+ MacAddress string `json:"mac_address"`
+
+ // Address contains the IPv4 and mask to set on the network interface
+ Address string `json:"address"`
+
+ // Gateway sets the gateway address that is used as the default for the interface
+ Gateway string `json:"gateway"`
+
+ // IPv6Address contains the IPv6 and mask to set on the network interface
+ IPv6Address string `json:"ipv6_address"`
+
+ // IPv6Gateway sets the ipv6 gateway address that is used as the default for the interface
+ IPv6Gateway string `json:"ipv6_gateway"`
+
+ // Mtu sets the mtu value for the interface and will be mirrored on both the host and
+ // container's interfaces if a pair is created, specifically in the case of type veth
+ // Note: This does not apply to loopback interfaces.
+ Mtu int `json:"mtu"`
+
+ // TxQueueLen sets the tx_queuelen value for the interface and will be mirrored on both the host and
+ // container's interfaces if a pair is created, specifically in the case of type veth
+ // Note: This does not apply to loopback interfaces.
+ TxQueueLen int `json:"txqueuelen"`
+
+ // HostInterfaceName is a unique name of a veth pair that resides on in the host interface of the
+ // container.
+ HostInterfaceName string `json:"host_interface_name"`
+
+ // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface
+ // bridge port in the case of type veth
+ // Note: This is unsupported on some systems.
+ // Note: This does not apply to loopback interfaces.
+ HairpinMode bool `json:"hairpin_mode"`
+}
+
+// Routes can be specified to create entries in the route table as the container is started
+//
+// All of destination, source, and gateway should be either IPv4 or IPv6.
+// One of the three options must be present, and omitted entries will use their
+// IP family default for the route table. For IPv4 for example, setting the
+// gateway to 1.2.3.4 and the interface to eth0 will set up a standard
+// destination of 0.0.0.0(or *) when viewed in the route table.
+type Route struct {
+ // Sets the destination and mask, should be a CIDR. Accepts IPv4 and IPv6
+ Destination string `json:"destination"`
+
+ // Sets the source and mask, should be a CIDR. Accepts IPv4 and IPv6
+ Source string `json:"source"`
+
+ // Sets the gateway. Accepts IPv4 and IPv6
+ Gateway string `json:"gateway"`
+
+ // The device to set this route up for, for example: eth0
+ InterfaceName string `json:"interface_name"`
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/rootless.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/rootless.go
new file mode 100644
index 0000000..0cebfaf
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/rootless.go
@@ -0,0 +1,117 @@
+package validate
+
+import (
+ "fmt"
+ "os"
+ "reflect"
+ "strings"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+var (
+ geteuid = os.Geteuid
+ getegid = os.Getegid
+)
+
+func (v *ConfigValidator) rootless(config *configs.Config) error {
+ if err := rootlessMappings(config); err != nil {
+ return err
+ }
+ if err := rootlessMount(config); err != nil {
+ return err
+ }
+ // Currently, cgroups cannot effectively be used in rootless containers.
+ // The new cgroup namespace doesn't really help us either because it doesn't
+ // have nice interactions with the user namespace (we're working with upstream
+ // to fix this).
+ if err := rootlessCgroup(config); err != nil {
+ return err
+ }
+
+ // XXX: We currently can't verify the user config at all, because
+ // configs.Config doesn't store the user-related configs. So this
+ // has to be verified by setupUser() in init_linux.go.
+
+ return nil
+}
+
+func rootlessMappings(config *configs.Config) error {
+ rootuid, err := config.HostRootUID()
+ if err != nil {
+ return fmt.Errorf("failed to get root uid from uidMappings: %v", err)
+ }
+ if euid := geteuid(); euid != 0 {
+ if !config.Namespaces.Contains(configs.NEWUSER) {
+ return fmt.Errorf("rootless containers require user namespaces")
+ }
+ if rootuid != euid {
+ return fmt.Errorf("rootless containers cannot map container root to a different host user")
+ }
+ }
+
+ rootgid, err := config.HostRootGID()
+ if err != nil {
+ return fmt.Errorf("failed to get root gid from gidMappings: %v", err)
+ }
+
+ // Similar to the above test, we need to make sure that we aren't trying to
+ // map to a group ID that we don't have the right to be.
+ if rootgid != getegid() {
+ return fmt.Errorf("rootless containers cannot map container root to a different host group")
+ }
+
+ // We can only map one user and group inside a container (our own).
+ if len(config.UidMappings) != 1 || config.UidMappings[0].Size != 1 {
+ return fmt.Errorf("rootless containers cannot map more than one user")
+ }
+ if len(config.GidMappings) != 1 || config.GidMappings[0].Size != 1 {
+ return fmt.Errorf("rootless containers cannot map more than one group")
+ }
+
+ return nil
+}
+
+// cgroup verifies that the user isn't trying to set any cgroup limits or paths.
+func rootlessCgroup(config *configs.Config) error {
+ // Nothing set at all.
+ if config.Cgroups == nil || config.Cgroups.Resources == nil {
+ return nil
+ }
+
+ // Used for comparing to the zero value.
+ left := reflect.ValueOf(*config.Cgroups.Resources)
+ right := reflect.Zero(left.Type())
+
+ // This is all we need to do, since specconv won't add cgroup options in
+ // rootless mode.
+ if !reflect.DeepEqual(left.Interface(), right.Interface()) {
+ return fmt.Errorf("cannot specify resource limits in rootless container")
+ }
+
+ return nil
+}
+
+// mount verifies that the user isn't trying to set up any mounts they don't have
+// the rights to do. In addition, it makes sure that no mount has a `uid=` or
+// `gid=` option that doesn't resolve to root.
+func rootlessMount(config *configs.Config) error {
+ // XXX: We could whitelist allowed devices at this point, but I'm not
+ // convinced that's a good idea. The kernel is the best arbiter of
+ // access control.
+
+ for _, mount := range config.Mounts {
+ // Check that the options list doesn't contain any uid= or gid= entries
+ // that don't resolve to root.
+ for _, opt := range strings.Split(mount.Data, ",") {
+ if strings.HasPrefix(opt, "uid=") && opt != "uid=0" {
+ return fmt.Errorf("cannot specify uid= mount options in rootless containers where argument isn't 0")
+ }
+ if strings.HasPrefix(opt, "gid=") && opt != "gid=0" {
+ return fmt.Errorf("cannot specify gid= mount options in rootless containers where argument isn't 0")
+ }
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/validator.go b/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/validator.go
new file mode 100644
index 0000000..8284345
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/validator.go
@@ -0,0 +1,195 @@
+package validate
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+ selinux "github.com/opencontainers/selinux/go-selinux"
+)
+
+type Validator interface {
+ Validate(*configs.Config) error
+}
+
+func New() Validator {
+ return &ConfigValidator{}
+}
+
+type ConfigValidator struct {
+}
+
+func (v *ConfigValidator) Validate(config *configs.Config) error {
+ if err := v.rootfs(config); err != nil {
+ return err
+ }
+ if err := v.network(config); err != nil {
+ return err
+ }
+ if err := v.hostname(config); err != nil {
+ return err
+ }
+ if err := v.security(config); err != nil {
+ return err
+ }
+ if err := v.usernamespace(config); err != nil {
+ return err
+ }
+ if err := v.sysctl(config); err != nil {
+ return err
+ }
+ if config.Rootless {
+ if err := v.rootless(config); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// rootfs validates if the rootfs is an absolute path and is not a symlink
+// to the container's root filesystem.
+func (v *ConfigValidator) rootfs(config *configs.Config) error {
+ if _, err := os.Stat(config.Rootfs); err != nil {
+ if os.IsNotExist(err) {
+ return fmt.Errorf("rootfs (%s) does not exist", config.Rootfs)
+ }
+ return err
+ }
+ cleaned, err := filepath.Abs(config.Rootfs)
+ if err != nil {
+ return err
+ }
+ if cleaned, err = filepath.EvalSymlinks(cleaned); err != nil {
+ return err
+ }
+ if filepath.Clean(config.Rootfs) != cleaned {
+ return fmt.Errorf("%s is not an absolute path or is a symlink", config.Rootfs)
+ }
+ return nil
+}
+
+func (v *ConfigValidator) network(config *configs.Config) error {
+ if !config.Namespaces.Contains(configs.NEWNET) {
+ if len(config.Networks) > 0 || len(config.Routes) > 0 {
+ return fmt.Errorf("unable to apply network settings without a private NET namespace")
+ }
+ }
+ return nil
+}
+
+func (v *ConfigValidator) hostname(config *configs.Config) error {
+ if config.Hostname != "" && !config.Namespaces.Contains(configs.NEWUTS) {
+ return fmt.Errorf("unable to set hostname without a private UTS namespace")
+ }
+ return nil
+}
+
+func (v *ConfigValidator) security(config *configs.Config) error {
+ // restrict sys without mount namespace
+ if (len(config.MaskPaths) > 0 || len(config.ReadonlyPaths) > 0) &&
+ !config.Namespaces.Contains(configs.NEWNS) {
+ return fmt.Errorf("unable to restrict sys entries without a private MNT namespace")
+ }
+ if config.ProcessLabel != "" && !selinux.GetEnabled() {
+ return fmt.Errorf("selinux label is specified in config, but selinux is disabled or not supported")
+ }
+
+ return nil
+}
+
+func (v *ConfigValidator) usernamespace(config *configs.Config) error {
+ if config.Namespaces.Contains(configs.NEWUSER) {
+ if _, err := os.Stat("/proc/self/ns/user"); os.IsNotExist(err) {
+ return fmt.Errorf("USER namespaces aren't enabled in the kernel")
+ }
+ } else {
+ if config.UidMappings != nil || config.GidMappings != nil {
+ return fmt.Errorf("User namespace mappings specified, but USER namespace isn't enabled in the config")
+ }
+ }
+ return nil
+}
+
+// sysctl validates that the specified sysctl keys are valid or not.
+// /proc/sys isn't completely namespaced and depending on which namespaces
+// are specified, a subset of sysctls are permitted.
+func (v *ConfigValidator) sysctl(config *configs.Config) error {
+ validSysctlMap := map[string]bool{
+ "kernel.msgmax": true,
+ "kernel.msgmnb": true,
+ "kernel.msgmni": true,
+ "kernel.sem": true,
+ "kernel.shmall": true,
+ "kernel.shmmax": true,
+ "kernel.shmmni": true,
+ "kernel.shm_rmid_forced": true,
+ }
+
+ for s := range config.Sysctl {
+ if validSysctlMap[s] || strings.HasPrefix(s, "fs.mqueue.") {
+ if config.Namespaces.Contains(configs.NEWIPC) {
+ continue
+ } else {
+ return fmt.Errorf("sysctl %q is not allowed in the hosts ipc namespace", s)
+ }
+ }
+ if strings.HasPrefix(s, "net.") {
+ if config.Namespaces.Contains(configs.NEWNET) {
+ if path := config.Namespaces.PathOf(configs.NEWNET); path != "" {
+ if err := checkHostNs(s, path); err != nil {
+ return err
+ }
+ }
+ continue
+ } else {
+ return fmt.Errorf("sysctl %q is not allowed in the hosts network namespace", s)
+ }
+ }
+ return fmt.Errorf("sysctl %q is not in a separate kernel namespace", s)
+ }
+
+ return nil
+}
+
+func isSymbolicLink(path string) (bool, error) {
+ fi, err := os.Lstat(path)
+ if err != nil {
+ return false, err
+ }
+
+ return fi.Mode()&os.ModeSymlink == os.ModeSymlink, nil
+}
+
+// checkHostNs checks whether network sysctl is used in host namespace.
+func checkHostNs(sysctlConfig string, path string) error {
+ var currentProcessNetns = "/proc/self/ns/net"
+ // readlink on the current processes network namespace
+ destOfCurrentProcess, err := os.Readlink(currentProcessNetns)
+ if err != nil {
+ return fmt.Errorf("read soft link %q error", currentProcessNetns)
+ }
+
+ // First check if the provided path is a symbolic link
+ symLink, err := isSymbolicLink(path)
+ if err != nil {
+ return fmt.Errorf("could not check that %q is a symlink: %v", path, err)
+ }
+
+ if symLink == false {
+ // The provided namespace is not a symbolic link,
+ // it is not the host namespace.
+ return nil
+ }
+
+ // readlink on the path provided in the struct
+ destOfContainer, err := os.Readlink(path)
+ if err != nil {
+ return fmt.Errorf("read soft link %q error", path)
+ }
+ if destOfContainer == destOfCurrentProcess {
+ return fmt.Errorf("sysctl %q is not allowed in the hosts network namespace", sysctlConfig)
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/console.go b/vendor/github.com/opencontainers/runc/libcontainer/console.go
new file mode 100644
index 0000000..917acc7
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/console.go
@@ -0,0 +1,17 @@
+package libcontainer
+
+import (
+ "io"
+ "os"
+)
+
+// Console represents a pseudo TTY.
+type Console interface {
+ io.ReadWriteCloser
+
+ // Path returns the filesystem path to the slave side of the pty.
+ Path() string
+
+ // Fd returns the fd for the master of the pty.
+ File() *os.File
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/console_freebsd.go b/vendor/github.com/opencontainers/runc/libcontainer/console_freebsd.go
new file mode 100644
index 0000000..b7166a3
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/console_freebsd.go
@@ -0,0 +1,13 @@
+// +build freebsd
+
+package libcontainer
+
+import (
+ "errors"
+)
+
+// newConsole returns an initialized console that can be used within a container by copying bytes
+// from the master side to the slave that is attached as the tty for the container's init process.
+func newConsole() (Console, error) {
+ return nil, errors.New("libcontainer console is not supported on FreeBSD")
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/console_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/console_linux.go
new file mode 100644
index 0000000..5927bdc
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/console_linux.go
@@ -0,0 +1,154 @@
+package libcontainer
+
+import (
+ "fmt"
+ "os"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+func ConsoleFromFile(f *os.File) Console {
+ return &linuxConsole{
+ master: f,
+ }
+}
+
+// newConsole returns an initialized console that can be used within a container by copying bytes
+// from the master side to the slave that is attached as the tty for the container's init process.
+func newConsole() (Console, error) {
+ master, err := os.OpenFile("/dev/ptmx", unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, err
+ }
+ console, err := ptsname(master)
+ if err != nil {
+ return nil, err
+ }
+ if err := unlockpt(master); err != nil {
+ return nil, err
+ }
+ return &linuxConsole{
+ slavePath: console,
+ master: master,
+ }, nil
+}
+
+// linuxConsole is a linux pseudo TTY for use within a container.
+type linuxConsole struct {
+ master *os.File
+ slavePath string
+}
+
+func (c *linuxConsole) File() *os.File {
+ return c.master
+}
+
+func (c *linuxConsole) Path() string {
+ return c.slavePath
+}
+
+func (c *linuxConsole) Read(b []byte) (int, error) {
+ return c.master.Read(b)
+}
+
+func (c *linuxConsole) Write(b []byte) (int, error) {
+ return c.master.Write(b)
+}
+
+func (c *linuxConsole) Close() error {
+ if m := c.master; m != nil {
+ return m.Close()
+ }
+ return nil
+}
+
+// mount initializes the console inside the rootfs mounting with the specified mount label
+// and applying the correct ownership of the console.
+func (c *linuxConsole) mount() error {
+ oldMask := unix.Umask(0000)
+ defer unix.Umask(oldMask)
+ f, err := os.Create("/dev/console")
+ if err != nil && !os.IsExist(err) {
+ return err
+ }
+ if f != nil {
+ f.Close()
+ }
+ return unix.Mount(c.slavePath, "/dev/console", "bind", unix.MS_BIND, "")
+}
+
+// dupStdio opens the slavePath for the console and dups the fds to the current
+// processes stdio, fd 0,1,2.
+func (c *linuxConsole) dupStdio() error {
+ slave, err := c.open(unix.O_RDWR)
+ if err != nil {
+ return err
+ }
+ fd := int(slave.Fd())
+ for _, i := range []int{0, 1, 2} {
+ if err := unix.Dup3(fd, i, 0); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// open is a clone of os.OpenFile without the O_CLOEXEC used to open the pty slave.
+func (c *linuxConsole) open(flag int) (*os.File, error) {
+ r, e := unix.Open(c.slavePath, flag, 0)
+ if e != nil {
+ return nil, &os.PathError{
+ Op: "open",
+ Path: c.slavePath,
+ Err: e,
+ }
+ }
+ return os.NewFile(uintptr(r), c.slavePath), nil
+}
+
+func ioctl(fd uintptr, flag, data uintptr) error {
+ if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, flag, data); err != 0 {
+ return err
+ }
+ return nil
+}
+
+// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.
+// unlockpt should be called before opening the slave side of a pty.
+func unlockpt(f *os.File) error {
+ var u int32
+ return ioctl(f.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))
+}
+
+// ptsname retrieves the name of the first available pts for the given master.
+func ptsname(f *os.File) (string, error) {
+ var n int32
+ if err := ioctl(f.Fd(), unix.TIOCGPTN, uintptr(unsafe.Pointer(&n))); err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("/dev/pts/%d", n), nil
+}
+
+// saneTerminal sets the necessary tty_ioctl(4)s to ensure that a pty pair
+// created by us acts normally. In particular, a not-very-well-known default of
+// Linux unix98 ptys is that they have +onlcr by default. While this isn't a
+// problem for terminal emulators, because we relay data from the terminal we
+// also relay that funky line discipline.
+func saneTerminal(terminal *os.File) error {
+ // Go doesn't have a wrapper for any of the termios ioctls.
+ var termios unix.Termios
+
+ if err := ioctl(terminal.Fd(), unix.TCGETS, uintptr(unsafe.Pointer(&termios))); err != nil {
+ return fmt.Errorf("ioctl(tty, tcgets): %s", err.Error())
+ }
+
+ // Set -onlcr so we don't have to deal with \r.
+ termios.Oflag &^= unix.ONLCR
+
+ if err := ioctl(terminal.Fd(), unix.TCSETS, uintptr(unsafe.Pointer(&termios))); err != nil {
+ return fmt.Errorf("ioctl(tty, tcsets): %s", err.Error())
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/console_solaris.go b/vendor/github.com/opencontainers/runc/libcontainer/console_solaris.go
new file mode 100644
index 0000000..e5ca545
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/console_solaris.go
@@ -0,0 +1,11 @@
+package libcontainer
+
+import (
+ "errors"
+)
+
+// newConsole returns an initialized console that can be used within a container by copying bytes
+// from the master side to the slave that is attached as the tty for the container's init process.
+func newConsole() (Console, error) {
+ return nil, errors.New("libcontainer console is not supported on Solaris")
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/console_windows.go b/vendor/github.com/opencontainers/runc/libcontainer/console_windows.go
new file mode 100644
index 0000000..c61e866
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/console_windows.go
@@ -0,0 +1,30 @@
+package libcontainer
+
+// newConsole returns an initialized console that can be used within a container
+func newConsole() (Console, error) {
+ return &windowsConsole{}, nil
+}
+
+// windowsConsole is a Windows pseudo TTY for use within a container.
+type windowsConsole struct {
+}
+
+func (c *windowsConsole) Fd() uintptr {
+ return 0
+}
+
+func (c *windowsConsole) Path() string {
+ return ""
+}
+
+func (c *windowsConsole) Read(b []byte) (int, error) {
+ return 0, nil
+}
+
+func (c *windowsConsole) Write(b []byte) (int, error) {
+ return 0, nil
+}
+
+func (c *windowsConsole) Close() error {
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/container.go b/vendor/github.com/opencontainers/runc/libcontainer/container.go
new file mode 100644
index 0000000..3ddb5ec
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/container.go
@@ -0,0 +1,166 @@
+// Package libcontainer provides a native Go implementation for creating containers
+// with namespaces, cgroups, capabilities, and filesystem access controls.
+// It allows you to manage the lifecycle of the container performing additional operations
+// after the container is created.
+package libcontainer
+
+import (
+ "os"
+ "time"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+// Status is the status of a container.
+type Status int
+
+const (
+ // Created is the status that denotes the container exists but has not been run yet.
+ Created Status = iota
+ // Running is the status that denotes the container exists and is running.
+ Running
+ // Pausing is the status that denotes the container exists, it is in the process of being paused.
+ Pausing
+ // Paused is the status that denotes the container exists, but all its processes are paused.
+ Paused
+ // Stopped is the status that denotes the container does not have a created or running process.
+ Stopped
+)
+
+func (s Status) String() string {
+ switch s {
+ case Created:
+ return "created"
+ case Running:
+ return "running"
+ case Pausing:
+ return "pausing"
+ case Paused:
+ return "paused"
+ case Stopped:
+ return "stopped"
+ default:
+ return "unknown"
+ }
+}
+
+// BaseState represents the platform agnostic pieces relating to a
+// running container's state
+type BaseState struct {
+ // ID is the container ID.
+ ID string `json:"id"`
+
+ // InitProcessPid is the init process id in the parent namespace.
+ InitProcessPid int `json:"init_process_pid"`
+
+ // InitProcessStartTime is the init process start time in clock cycles since boot time.
+ InitProcessStartTime string `json:"init_process_start"`
+
+ // Created is the unix timestamp for the creation time of the container in UTC
+ Created time.Time `json:"created"`
+
+ // Config is the container's configuration.
+ Config configs.Config `json:"config"`
+}
+
+// BaseContainer is a libcontainer container object.
+//
+// Each container is thread-safe within the same process. Since a container can
+// be destroyed by a separate process, any function may return that the container
+// was not found. BaseContainer includes methods that are platform agnostic.
+type BaseContainer interface {
+ // Returns the ID of the container
+ ID() string
+
+ // Returns the current status of the container.
+ //
+ // errors:
+ // ContainerNotExists - Container no longer exists,
+ // Systemerror - System error.
+ Status() (Status, error)
+
+ // State returns the current container's state information.
+ //
+ // errors:
+ // SystemError - System error.
+ State() (*State, error)
+
+ // Returns the current config of the container.
+ Config() configs.Config
+
+ // Returns the PIDs inside this container. The PIDs are in the namespace of the calling process.
+ //
+ // errors:
+ // ContainerNotExists - Container no longer exists,
+ // Systemerror - System error.
+ //
+ // Some of the returned PIDs may no longer refer to processes in the Container, unless
+ // the Container state is PAUSED in which case every PID in the slice is valid.
+ Processes() ([]int, error)
+
+ // Returns statistics for the container.
+ //
+ // errors:
+ // ContainerNotExists - Container no longer exists,
+ // Systemerror - System error.
+ Stats() (*Stats, error)
+
+ // Set resources of container as configured
+ //
+ // We can use this to change resources when containers are running.
+ //
+ // errors:
+ // SystemError - System error.
+ Set(config configs.Config) error
+
+ // Start a process inside the container. Returns error if process fails to
+ // start. You can track process lifecycle with passed Process structure.
+ //
+ // errors:
+ // ContainerNotExists - Container no longer exists,
+ // ConfigInvalid - config is invalid,
+ // ContainerPaused - Container is paused,
+ // SystemError - System error.
+ Start(process *Process) (err error)
+
+ // Run immediately starts the process inside the container. Returns error if process
+ // fails to start. It does not block waiting for the exec fifo after start returns but
+ // opens the fifo after start returns.
+ //
+ // errors:
+ // ContainerNotExists - Container no longer exists,
+ // ConfigInvalid - config is invalid,
+ // ContainerPaused - Container is paused,
+ // SystemError - System error.
+ Run(process *Process) (err error)
+
+ // Destroys the container, if its in a valid state, after killing any
+ // remaining running processes.
+ //
+ // Any event registrations are removed before the container is destroyed.
+ // No error is returned if the container is already destroyed.
+ //
+ // Running containers must first be stopped using Signal(..).
+ // Paused containers must first be resumed using Resume(..).
+ //
+ // errors:
+ // ContainerNotStopped - Container is still running,
+ // ContainerPaused - Container is paused,
+ // SystemError - System error.
+ Destroy() error
+
+ // Signal sends the provided signal code to the container's initial process.
+ //
+ // If all is specified the signal is sent to all processes in the container
+ // including the initial process.
+ //
+ // errors:
+ // SystemError - System error.
+ Signal(s os.Signal, all bool) error
+
+ // Exec signals the container to exec the users process at the end of the init.
+ //
+ // errors:
+ // SystemError - System error.
+ Exec() error
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/container_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/container_linux.go
new file mode 100644
index 0000000..649c2e4
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/container_linux.go
@@ -0,0 +1,1573 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/golang/protobuf/proto"
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/criurpc"
+ "github.com/opencontainers/runc/libcontainer/system"
+ "github.com/opencontainers/runc/libcontainer/utils"
+ "github.com/syndtr/gocapability/capability"
+ "github.com/vishvananda/netlink/nl"
+)
+
+const stdioFdCount = 3
+
+type linuxContainer struct {
+ id string
+ root string
+ config *configs.Config
+ cgroupManager cgroups.Manager
+ initPath string
+ initArgs []string
+ initProcess parentProcess
+ initProcessStartTime string
+ criuPath string
+ m sync.Mutex
+ criuVersion int
+ state containerState
+ created time.Time
+}
+
+// State represents a running container's state
+type State struct {
+ BaseState
+
+ // Platform specific fields below here
+
+ // Specifies if the container was started under the rootless mode.
+ Rootless bool `json:"rootless"`
+
+ // Path to all the cgroups setup for a container. Key is cgroup subsystem name
+ // with the value as the path.
+ CgroupPaths map[string]string `json:"cgroup_paths"`
+
+ // NamespacePaths are filepaths to the container's namespaces. Key is the namespace type
+ // with the value as the path.
+ NamespacePaths map[configs.NamespaceType]string `json:"namespace_paths"`
+
+ // Container's standard descriptors (std{in,out,err}), needed for checkpoint and restore
+ ExternalDescriptors []string `json:"external_descriptors,omitempty"`
+}
+
+// Container is a libcontainer container object.
+//
+// Each container is thread-safe within the same process. Since a container can
+// be destroyed by a separate process, any function may return that the container
+// was not found.
+type Container interface {
+ BaseContainer
+
+ // Methods below here are platform specific
+
+ // Checkpoint checkpoints the running container's state to disk using the criu(8) utility.
+ //
+ // errors:
+ // Systemerror - System error.
+ Checkpoint(criuOpts *CriuOpts) error
+
+ // Restore restores the checkpointed container to a running state using the criu(8) utility.
+ //
+ // errors:
+ // Systemerror - System error.
+ Restore(process *Process, criuOpts *CriuOpts) error
+
+ // If the Container state is RUNNING or CREATED, sets the Container state to PAUSING and pauses
+ // the execution of any user processes. Asynchronously, when the container finished being paused the
+ // state is changed to PAUSED.
+ // If the Container state is PAUSED, do nothing.
+ //
+ // errors:
+ // ContainerNotExists - Container no longer exists,
+ // ContainerNotRunning - Container not running or created,
+ // Systemerror - System error.
+ Pause() error
+
+ // If the Container state is PAUSED, resumes the execution of any user processes in the
+ // Container before setting the Container state to RUNNING.
+ // If the Container state is RUNNING, do nothing.
+ //
+ // errors:
+ // ContainerNotExists - Container no longer exists,
+ // ContainerNotPaused - Container is not paused,
+ // Systemerror - System error.
+ Resume() error
+
+ // NotifyOOM returns a read-only channel signaling when the container receives an OOM notification.
+ //
+ // errors:
+ // Systemerror - System error.
+ NotifyOOM() (<-chan struct{}, error)
+
+ // NotifyMemoryPressure returns a read-only channel signaling when the container reaches a given pressure level
+ //
+ // errors:
+ // Systemerror - System error.
+ NotifyMemoryPressure(level PressureLevel) (<-chan struct{}, error)
+}
+
+// ID returns the container's unique ID
+func (c *linuxContainer) ID() string {
+ return c.id
+}
+
+// Config returns the container's configuration
+func (c *linuxContainer) Config() configs.Config {
+ return *c.config
+}
+
+func (c *linuxContainer) Status() (Status, error) {
+ c.m.Lock()
+ defer c.m.Unlock()
+ return c.currentStatus()
+}
+
+func (c *linuxContainer) State() (*State, error) {
+ c.m.Lock()
+ defer c.m.Unlock()
+ return c.currentState()
+}
+
+func (c *linuxContainer) Processes() ([]int, error) {
+ pids, err := c.cgroupManager.GetAllPids()
+ if err != nil {
+ return nil, newSystemErrorWithCause(err, "getting all container pids from cgroups")
+ }
+ return pids, nil
+}
+
+func (c *linuxContainer) Stats() (*Stats, error) {
+ var (
+ err error
+ stats = &Stats{}
+ )
+ if stats.CgroupStats, err = c.cgroupManager.GetStats(); err != nil {
+ return stats, newSystemErrorWithCause(err, "getting container stats from cgroups")
+ }
+ for _, iface := range c.config.Networks {
+ switch iface.Type {
+ case "veth":
+ istats, err := getNetworkInterfaceStats(iface.HostInterfaceName)
+ if err != nil {
+ return stats, newSystemErrorWithCausef(err, "getting network stats for interface %q", iface.HostInterfaceName)
+ }
+ stats.Interfaces = append(stats.Interfaces, istats)
+ }
+ }
+ return stats, nil
+}
+
+func (c *linuxContainer) Set(config configs.Config) error {
+ c.m.Lock()
+ defer c.m.Unlock()
+ status, err := c.currentStatus()
+ if err != nil {
+ return err
+ }
+ if status == Stopped {
+ return newGenericError(fmt.Errorf("container not running"), ContainerNotRunning)
+ }
+ c.config = &config
+ return c.cgroupManager.Set(c.config)
+}
+
+func (c *linuxContainer) Start(process *Process) error {
+ c.m.Lock()
+ defer c.m.Unlock()
+ status, err := c.currentStatus()
+ if err != nil {
+ return err
+ }
+ if status == Stopped {
+ if err := c.createExecFifo(); err != nil {
+ return err
+ }
+ }
+ if err := c.start(process, status == Stopped); err != nil {
+ if status == Stopped {
+ c.deleteExecFifo()
+ }
+ return err
+ }
+ return nil
+}
+
+func (c *linuxContainer) Run(process *Process) error {
+ c.m.Lock()
+ status, err := c.currentStatus()
+ if err != nil {
+ c.m.Unlock()
+ return err
+ }
+ c.m.Unlock()
+ if err := c.Start(process); err != nil {
+ return err
+ }
+ if status == Stopped {
+ return c.exec()
+ }
+ return nil
+}
+
+func (c *linuxContainer) Exec() error {
+ c.m.Lock()
+ defer c.m.Unlock()
+ return c.exec()
+}
+
+func (c *linuxContainer) exec() error {
+ path := filepath.Join(c.root, execFifoFilename)
+ f, err := os.OpenFile(path, os.O_RDONLY, 0)
+ if err != nil {
+ return newSystemErrorWithCause(err, "open exec fifo for reading")
+ }
+ defer f.Close()
+ data, err := ioutil.ReadAll(f)
+ if err != nil {
+ return err
+ }
+ if len(data) > 0 {
+ os.Remove(path)
+ return nil
+ }
+ return fmt.Errorf("cannot start an already running container")
+}
+
+func (c *linuxContainer) start(process *Process, isInit bool) error {
+ parent, err := c.newParentProcess(process, isInit)
+ if err != nil {
+ return newSystemErrorWithCause(err, "creating new parent process")
+ }
+ if err := parent.start(); err != nil {
+ // terminate the process to ensure that it properly is reaped.
+ if err := parent.terminate(); err != nil {
+ logrus.Warn(err)
+ }
+ return newSystemErrorWithCause(err, "starting container process")
+ }
+ // generate a timestamp indicating when the container was started
+ c.created = time.Now().UTC()
+ if isInit {
+ c.state = &createdState{
+ c: c,
+ }
+ state, err := c.updateState(parent)
+ if err != nil {
+ return err
+ }
+ c.initProcessStartTime = state.InitProcessStartTime
+
+ if c.config.Hooks != nil {
+ s := configs.HookState{
+ Version: c.config.Version,
+ ID: c.id,
+ Pid: parent.pid(),
+ Bundle: utils.SearchLabels(c.config.Labels, "bundle"),
+ }
+ for i, hook := range c.config.Hooks.Poststart {
+ if err := hook.Run(s); err != nil {
+ if err := parent.terminate(); err != nil {
+ logrus.Warn(err)
+ }
+ return newSystemErrorWithCausef(err, "running poststart hook %d", i)
+ }
+ }
+ }
+ } else {
+ c.state = &runningState{
+ c: c,
+ }
+ }
+ return nil
+}
+
+func (c *linuxContainer) Signal(s os.Signal, all bool) error {
+ if all {
+ return signalAllProcesses(c.cgroupManager, s)
+ }
+ if err := c.initProcess.signal(s); err != nil {
+ return newSystemErrorWithCause(err, "signaling init process")
+ }
+ return nil
+}
+
+func (c *linuxContainer) createExecFifo() error {
+ rootuid, err := c.Config().HostRootUID()
+ if err != nil {
+ return err
+ }
+ rootgid, err := c.Config().HostRootGID()
+ if err != nil {
+ return err
+ }
+
+ fifoName := filepath.Join(c.root, execFifoFilename)
+ if _, err := os.Stat(fifoName); err == nil {
+ return fmt.Errorf("exec fifo %s already exists", fifoName)
+ }
+ oldMask := syscall.Umask(0000)
+ if err := syscall.Mkfifo(fifoName, 0622); err != nil {
+ syscall.Umask(oldMask)
+ return err
+ }
+ syscall.Umask(oldMask)
+ if err := os.Chown(fifoName, rootuid, rootgid); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (c *linuxContainer) deleteExecFifo() {
+ fifoName := filepath.Join(c.root, execFifoFilename)
+ os.Remove(fifoName)
+}
+
+func (c *linuxContainer) newParentProcess(p *Process, doInit bool) (parentProcess, error) {
+ parentPipe, childPipe, err := utils.NewSockPair("init")
+ if err != nil {
+ return nil, newSystemErrorWithCause(err, "creating new init pipe")
+ }
+ cmd, err := c.commandTemplate(p, childPipe)
+ if err != nil {
+ return nil, newSystemErrorWithCause(err, "creating new command template")
+ }
+ if !doInit {
+ return c.newSetnsProcess(p, cmd, parentPipe, childPipe)
+ }
+
+ // We only set up rootDir if we're not doing a `runc exec`. The reason for
+ // this is to avoid cases where a racing, unprivileged process inside the
+ // container can get access to the statedir file descriptor (which would
+ // allow for container rootfs escape).
+ rootDir, err := os.Open(c.root)
+ if err != nil {
+ return nil, err
+ }
+ cmd.ExtraFiles = append(cmd.ExtraFiles, rootDir)
+ cmd.Env = append(cmd.Env,
+ fmt.Sprintf("_LIBCONTAINER_STATEDIR=%d", stdioFdCount+len(cmd.ExtraFiles)-1))
+ return c.newInitProcess(p, cmd, parentPipe, childPipe, rootDir)
+}
+
+func (c *linuxContainer) commandTemplate(p *Process, childPipe *os.File) (*exec.Cmd, error) {
+ cmd := exec.Command(c.initPath, c.initArgs[1:]...)
+ cmd.Args[0] = c.initArgs[0]
+ cmd.Stdin = p.Stdin
+ cmd.Stdout = p.Stdout
+ cmd.Stderr = p.Stderr
+ cmd.Dir = c.config.Rootfs
+ if cmd.SysProcAttr == nil {
+ cmd.SysProcAttr = &syscall.SysProcAttr{}
+ }
+ cmd.ExtraFiles = append(cmd.ExtraFiles, p.ExtraFiles...)
+ if p.ConsoleSocket != nil {
+ cmd.ExtraFiles = append(cmd.ExtraFiles, p.ConsoleSocket)
+ cmd.Env = append(cmd.Env,
+ fmt.Sprintf("_LIBCONTAINER_CONSOLE=%d", stdioFdCount+len(cmd.ExtraFiles)-1),
+ )
+ }
+ cmd.ExtraFiles = append(cmd.ExtraFiles, childPipe)
+ cmd.Env = append(cmd.Env,
+ fmt.Sprintf("_LIBCONTAINER_INITPIPE=%d", stdioFdCount+len(cmd.ExtraFiles)-1),
+ )
+ // NOTE: when running a container with no PID namespace and the parent process spawning the container is
+ // PID1 the pdeathsig is being delivered to the container's init process by the kernel for some reason
+ // even with the parent still running.
+ if c.config.ParentDeathSignal > 0 {
+ cmd.SysProcAttr.Pdeathsig = syscall.Signal(c.config.ParentDeathSignal)
+ }
+ return cmd, nil
+}
+
+func (c *linuxContainer) newInitProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe, rootDir *os.File) (*initProcess, error) {
+ cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initStandard))
+ nsMaps := make(map[configs.NamespaceType]string)
+ for _, ns := range c.config.Namespaces {
+ if ns.Path != "" {
+ nsMaps[ns.Type] = ns.Path
+ }
+ }
+ _, sharePidns := nsMaps[configs.NEWPID]
+ data, err := c.bootstrapData(c.config.Namespaces.CloneFlags(), nsMaps)
+ if err != nil {
+ return nil, err
+ }
+ return &initProcess{
+ cmd: cmd,
+ childPipe: childPipe,
+ parentPipe: parentPipe,
+ manager: c.cgroupManager,
+ config: c.newInitConfig(p),
+ container: c,
+ process: p,
+ bootstrapData: data,
+ sharePidns: sharePidns,
+ rootDir: rootDir,
+ }, nil
+}
+
+func (c *linuxContainer) newSetnsProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe *os.File) (*setnsProcess, error) {
+ cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initSetns))
+ state, err := c.currentState()
+ if err != nil {
+ return nil, newSystemErrorWithCause(err, "getting container's current state")
+ }
+ // for setns process, we don't have to set cloneflags as the process namespaces
+ // will only be set via setns syscall
+ data, err := c.bootstrapData(0, state.NamespacePaths)
+ if err != nil {
+ return nil, err
+ }
+ return &setnsProcess{
+ cmd: cmd,
+ cgroupPaths: c.cgroupManager.GetPaths(),
+ childPipe: childPipe,
+ parentPipe: parentPipe,
+ config: c.newInitConfig(p),
+ process: p,
+ bootstrapData: data,
+ }, nil
+}
+
+func (c *linuxContainer) newInitConfig(process *Process) *initConfig {
+ cfg := &initConfig{
+ Config: c.config,
+ Args: process.Args,
+ Env: process.Env,
+ User: process.User,
+ AdditionalGroups: process.AdditionalGroups,
+ Cwd: process.Cwd,
+ Capabilities: process.Capabilities,
+ PassedFilesCount: len(process.ExtraFiles),
+ ContainerId: c.ID(),
+ NoNewPrivileges: c.config.NoNewPrivileges,
+ Rootless: c.config.Rootless,
+ AppArmorProfile: c.config.AppArmorProfile,
+ ProcessLabel: c.config.ProcessLabel,
+ Rlimits: c.config.Rlimits,
+ }
+ if process.NoNewPrivileges != nil {
+ cfg.NoNewPrivileges = *process.NoNewPrivileges
+ }
+ if process.AppArmorProfile != "" {
+ cfg.AppArmorProfile = process.AppArmorProfile
+ }
+ if process.Label != "" {
+ cfg.ProcessLabel = process.Label
+ }
+ if len(process.Rlimits) > 0 {
+ cfg.Rlimits = process.Rlimits
+ }
+ cfg.CreateConsole = process.ConsoleSocket != nil
+ return cfg
+}
+
+func (c *linuxContainer) Destroy() error {
+ c.m.Lock()
+ defer c.m.Unlock()
+ return c.state.destroy()
+}
+
+func (c *linuxContainer) Pause() error {
+ c.m.Lock()
+ defer c.m.Unlock()
+ status, err := c.currentStatus()
+ if err != nil {
+ return err
+ }
+ switch status {
+ case Running, Created:
+ if err := c.cgroupManager.Freeze(configs.Frozen); err != nil {
+ return err
+ }
+ return c.state.transition(&pausedState{
+ c: c,
+ })
+ }
+ return newGenericError(fmt.Errorf("container not running or created: %s", status), ContainerNotRunning)
+}
+
+func (c *linuxContainer) Resume() error {
+ c.m.Lock()
+ defer c.m.Unlock()
+ status, err := c.currentStatus()
+ if err != nil {
+ return err
+ }
+ if status != Paused {
+ return newGenericError(fmt.Errorf("container not paused"), ContainerNotPaused)
+ }
+ if err := c.cgroupManager.Freeze(configs.Thawed); err != nil {
+ return err
+ }
+ return c.state.transition(&runningState{
+ c: c,
+ })
+}
+
+func (c *linuxContainer) NotifyOOM() (<-chan struct{}, error) {
+ // XXX(cyphar): This requires cgroups.
+ if c.config.Rootless {
+ return nil, fmt.Errorf("cannot get OOM notifications from rootless container")
+ }
+ return notifyOnOOM(c.cgroupManager.GetPaths())
+}
+
+func (c *linuxContainer) NotifyMemoryPressure(level PressureLevel) (<-chan struct{}, error) {
+ // XXX(cyphar): This requires cgroups.
+ if c.config.Rootless {
+ return nil, fmt.Errorf("cannot get memory pressure notifications from rootless container")
+ }
+ return notifyMemoryPressure(c.cgroupManager.GetPaths(), level)
+}
+
+var criuFeatures *criurpc.CriuFeatures
+
+func (c *linuxContainer) checkCriuFeatures(criuOpts *CriuOpts, rpcOpts *criurpc.CriuOpts, criuFeat *criurpc.CriuFeatures) error {
+
+ var t criurpc.CriuReqType
+ t = criurpc.CriuReqType_FEATURE_CHECK
+
+ if err := c.checkCriuVersion("1.8"); err != nil {
+ // Feature checking was introduced with CRIU 1.8.
+ // Ignore the feature check if an older CRIU version is used
+ // and just act as before.
+ // As all automated PR testing is done using CRIU 1.7 this
+ // code will not be tested by automated PR testing.
+ return nil
+ }
+
+ // make sure the features we are looking for are really not from
+ // some previous check
+ criuFeatures = nil
+
+ req := &criurpc.CriuReq{
+ Type: &t,
+ // Theoretically this should not be necessary but CRIU
+ // segfaults if Opts is empty.
+ // Fixed in CRIU 2.12
+ Opts: rpcOpts,
+ Features: criuFeat,
+ }
+
+ err := c.criuSwrk(nil, req, criuOpts, false)
+ if err != nil {
+ logrus.Debugf("%s", err)
+ return fmt.Errorf("CRIU feature check failed")
+ }
+
+ logrus.Debugf("Feature check says: %s", criuFeatures)
+ missingFeatures := false
+
+ if *criuFeat.MemTrack && !*criuFeatures.MemTrack {
+ missingFeatures = true
+ logrus.Debugf("CRIU does not support MemTrack")
+ }
+
+ if missingFeatures {
+ return fmt.Errorf("CRIU is missing features")
+ }
+
+ return nil
+}
+
+// checkCriuVersion checks Criu version greater than or equal to minVersion
+func (c *linuxContainer) checkCriuVersion(minVersion string) error {
+ var x, y, z, versionReq int
+
+ _, err := fmt.Sscanf(minVersion, "%d.%d.%d\n", &x, &y, &z) // 1.5.2
+ if err != nil {
+ _, err = fmt.Sscanf(minVersion, "Version: %d.%d\n", &x, &y) // 1.6
+ }
+ versionReq = x*10000 + y*100 + z
+
+ out, err := exec.Command(c.criuPath, "-V").Output()
+ if err != nil {
+ return fmt.Errorf("Unable to execute CRIU command: %s", c.criuPath)
+ }
+
+ x = 0
+ y = 0
+ z = 0
+ if ep := strings.Index(string(out), "-"); ep >= 0 {
+ // criu Git version format
+ var version string
+ if sp := strings.Index(string(out), "GitID"); sp > 0 {
+ version = string(out)[sp:ep]
+ } else {
+ return fmt.Errorf("Unable to parse the CRIU version: %s", c.criuPath)
+ }
+
+ n, err := fmt.Sscanf(string(version), "GitID: v%d.%d.%d", &x, &y, &z) // 1.5.2
+ if err != nil {
+ n, err = fmt.Sscanf(string(version), "GitID: v%d.%d", &x, &y) // 1.6
+ y++
+ } else {
+ z++
+ }
+ if n < 2 || err != nil {
+ return fmt.Errorf("Unable to parse the CRIU version: %s %d %s", version, n, err)
+ }
+ } else {
+ // criu release version format
+ n, err := fmt.Sscanf(string(out), "Version: %d.%d.%d\n", &x, &y, &z) // 1.5.2
+ if err != nil {
+ n, err = fmt.Sscanf(string(out), "Version: %d.%d\n", &x, &y) // 1.6
+ }
+ if n < 2 || err != nil {
+ return fmt.Errorf("Unable to parse the CRIU version: %s %d %s", out, n, err)
+ }
+ }
+
+ c.criuVersion = x*10000 + y*100 + z
+
+ if c.criuVersion < versionReq {
+ return fmt.Errorf("CRIU version must be %s or higher", minVersion)
+ }
+
+ return nil
+}
+
+const descriptorsFilename = "descriptors.json"
+
+func (c *linuxContainer) addCriuDumpMount(req *criurpc.CriuReq, m *configs.Mount) {
+ mountDest := m.Destination
+ if strings.HasPrefix(mountDest, c.config.Rootfs) {
+ mountDest = mountDest[len(c.config.Rootfs):]
+ }
+
+ extMnt := &criurpc.ExtMountMap{
+ Key: proto.String(mountDest),
+ Val: proto.String(mountDest),
+ }
+ req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt)
+}
+
+func (c *linuxContainer) addMaskPaths(req *criurpc.CriuReq) error {
+ for _, path := range c.config.MaskPaths {
+ fi, err := os.Stat(fmt.Sprintf("/proc/%d/root/%s", c.initProcess.pid(), path))
+ if err != nil {
+ if os.IsNotExist(err) {
+ continue
+ }
+ return err
+ }
+ if fi.IsDir() {
+ continue
+ }
+
+ extMnt := &criurpc.ExtMountMap{
+ Key: proto.String(path),
+ Val: proto.String("/dev/null"),
+ }
+ req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt)
+ }
+
+ return nil
+}
+
+func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error {
+ c.m.Lock()
+ defer c.m.Unlock()
+
+ // TODO(avagin): Figure out how to make this work nicely. CRIU 2.0 has
+ // support for doing unprivileged dumps, but the setup of
+ // rootless containers might make this complicated.
+ if c.config.Rootless {
+ return fmt.Errorf("cannot checkpoint a rootless container")
+ }
+
+ if err := c.checkCriuVersion("1.5.2"); err != nil {
+ return err
+ }
+
+ if criuOpts.ImagesDirectory == "" {
+ return fmt.Errorf("invalid directory to save checkpoint")
+ }
+
+ // Since a container can be C/R'ed multiple times,
+ // the checkpoint directory may already exist.
+ if err := os.Mkdir(criuOpts.ImagesDirectory, 0755); err != nil && !os.IsExist(err) {
+ return err
+ }
+
+ if criuOpts.WorkDirectory == "" {
+ criuOpts.WorkDirectory = filepath.Join(c.root, "criu.work")
+ }
+
+ if err := os.Mkdir(criuOpts.WorkDirectory, 0755); err != nil && !os.IsExist(err) {
+ return err
+ }
+
+ workDir, err := os.Open(criuOpts.WorkDirectory)
+ if err != nil {
+ return err
+ }
+ defer workDir.Close()
+
+ imageDir, err := os.Open(criuOpts.ImagesDirectory)
+ if err != nil {
+ return err
+ }
+ defer imageDir.Close()
+
+ rpcOpts := criurpc.CriuOpts{
+ ImagesDirFd: proto.Int32(int32(imageDir.Fd())),
+ WorkDirFd: proto.Int32(int32(workDir.Fd())),
+ LogLevel: proto.Int32(4),
+ LogFile: proto.String("dump.log"),
+ Root: proto.String(c.config.Rootfs),
+ ManageCgroups: proto.Bool(true),
+ NotifyScripts: proto.Bool(true),
+ Pid: proto.Int32(int32(c.initProcess.pid())),
+ ShellJob: proto.Bool(criuOpts.ShellJob),
+ LeaveRunning: proto.Bool(criuOpts.LeaveRunning),
+ TcpEstablished: proto.Bool(criuOpts.TcpEstablished),
+ ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections),
+ FileLocks: proto.Bool(criuOpts.FileLocks),
+ EmptyNs: proto.Uint32(criuOpts.EmptyNs),
+ }
+
+ // append optional criu opts, e.g., page-server and port
+ if criuOpts.PageServer.Address != "" && criuOpts.PageServer.Port != 0 {
+ rpcOpts.Ps = &criurpc.CriuPageServerInfo{
+ Address: proto.String(criuOpts.PageServer.Address),
+ Port: proto.Int32(criuOpts.PageServer.Port),
+ }
+ }
+
+ //pre-dump may need parentImage param to complete iterative migration
+ if criuOpts.ParentImage != "" {
+ rpcOpts.ParentImg = proto.String(criuOpts.ParentImage)
+ rpcOpts.TrackMem = proto.Bool(true)
+ }
+
+ // append optional manage cgroups mode
+ if criuOpts.ManageCgroupsMode != 0 {
+ if err := c.checkCriuVersion("1.7"); err != nil {
+ return err
+ }
+ mode := criurpc.CriuCgMode(criuOpts.ManageCgroupsMode)
+ rpcOpts.ManageCgroupsMode = &mode
+ }
+
+ var t criurpc.CriuReqType
+ if criuOpts.PreDump {
+ feat := criurpc.CriuFeatures{
+ MemTrack: proto.Bool(true),
+ }
+
+ if err := c.checkCriuFeatures(criuOpts, &rpcOpts, &feat); err != nil {
+ return err
+ }
+
+ t = criurpc.CriuReqType_PRE_DUMP
+ } else {
+ t = criurpc.CriuReqType_DUMP
+ }
+ req := &criurpc.CriuReq{
+ Type: &t,
+ Opts: &rpcOpts,
+ }
+
+ //no need to dump these information in pre-dump
+ if !criuOpts.PreDump {
+ for _, m := range c.config.Mounts {
+ switch m.Device {
+ case "bind":
+ c.addCriuDumpMount(req, m)
+ break
+ case "cgroup":
+ binds, err := getCgroupMounts(m)
+ if err != nil {
+ return err
+ }
+ for _, b := range binds {
+ c.addCriuDumpMount(req, b)
+ }
+ break
+ }
+ }
+
+ if err := c.addMaskPaths(req); err != nil {
+ return err
+ }
+
+ for _, node := range c.config.Devices {
+ m := &configs.Mount{Destination: node.Path, Source: node.Path}
+ c.addCriuDumpMount(req, m)
+ }
+
+ // Write the FD info to a file in the image directory
+ fdsJSON, err := json.Marshal(c.initProcess.externalDescriptors())
+ if err != nil {
+ return err
+ }
+
+ err = ioutil.WriteFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename), fdsJSON, 0655)
+ if err != nil {
+ return err
+ }
+ }
+
+ err = c.criuSwrk(nil, req, criuOpts, false)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+func (c *linuxContainer) addCriuRestoreMount(req *criurpc.CriuReq, m *configs.Mount) {
+ mountDest := m.Destination
+ if strings.HasPrefix(mountDest, c.config.Rootfs) {
+ mountDest = mountDest[len(c.config.Rootfs):]
+ }
+
+ extMnt := &criurpc.ExtMountMap{
+ Key: proto.String(mountDest),
+ Val: proto.String(m.Source),
+ }
+ req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt)
+}
+
+func (c *linuxContainer) restoreNetwork(req *criurpc.CriuReq, criuOpts *CriuOpts) {
+ for _, iface := range c.config.Networks {
+ switch iface.Type {
+ case "veth":
+ veth := new(criurpc.CriuVethPair)
+ veth.IfOut = proto.String(iface.HostInterfaceName)
+ veth.IfIn = proto.String(iface.Name)
+ req.Opts.Veths = append(req.Opts.Veths, veth)
+ break
+ case "loopback":
+ break
+ }
+ }
+ for _, i := range criuOpts.VethPairs {
+ veth := new(criurpc.CriuVethPair)
+ veth.IfOut = proto.String(i.HostInterfaceName)
+ veth.IfIn = proto.String(i.ContainerInterfaceName)
+ req.Opts.Veths = append(req.Opts.Veths, veth)
+ }
+}
+
+func (c *linuxContainer) Restore(process *Process, criuOpts *CriuOpts) error {
+ c.m.Lock()
+ defer c.m.Unlock()
+
+ // TODO(avagin): Figure out how to make this work nicely. CRIU doesn't have
+ // support for unprivileged restore at the moment.
+ if c.config.Rootless {
+ return fmt.Errorf("cannot restore a rootless container")
+ }
+
+ if err := c.checkCriuVersion("1.5.2"); err != nil {
+ return err
+ }
+ if criuOpts.WorkDirectory == "" {
+ criuOpts.WorkDirectory = filepath.Join(c.root, "criu.work")
+ }
+ // Since a container can be C/R'ed multiple times,
+ // the work directory may already exist.
+ if err := os.Mkdir(criuOpts.WorkDirectory, 0655); err != nil && !os.IsExist(err) {
+ return err
+ }
+ workDir, err := os.Open(criuOpts.WorkDirectory)
+ if err != nil {
+ return err
+ }
+ defer workDir.Close()
+ if criuOpts.ImagesDirectory == "" {
+ return fmt.Errorf("invalid directory to restore checkpoint")
+ }
+ imageDir, err := os.Open(criuOpts.ImagesDirectory)
+ if err != nil {
+ return err
+ }
+ defer imageDir.Close()
+ // CRIU has a few requirements for a root directory:
+ // * it must be a mount point
+ // * its parent must not be overmounted
+ // c.config.Rootfs is bind-mounted to a temporary directory
+ // to satisfy these requirements.
+ root := filepath.Join(c.root, "criu-root")
+ if err := os.Mkdir(root, 0755); err != nil {
+ return err
+ }
+ defer os.Remove(root)
+ root, err = filepath.EvalSymlinks(root)
+ if err != nil {
+ return err
+ }
+ err = syscall.Mount(c.config.Rootfs, root, "", syscall.MS_BIND|syscall.MS_REC, "")
+ if err != nil {
+ return err
+ }
+ defer syscall.Unmount(root, syscall.MNT_DETACH)
+ t := criurpc.CriuReqType_RESTORE
+ req := &criurpc.CriuReq{
+ Type: &t,
+ Opts: &criurpc.CriuOpts{
+ ImagesDirFd: proto.Int32(int32(imageDir.Fd())),
+ WorkDirFd: proto.Int32(int32(workDir.Fd())),
+ EvasiveDevices: proto.Bool(true),
+ LogLevel: proto.Int32(4),
+ LogFile: proto.String("restore.log"),
+ RstSibling: proto.Bool(true),
+ Root: proto.String(root),
+ ManageCgroups: proto.Bool(true),
+ NotifyScripts: proto.Bool(true),
+ ShellJob: proto.Bool(criuOpts.ShellJob),
+ ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections),
+ TcpEstablished: proto.Bool(criuOpts.TcpEstablished),
+ FileLocks: proto.Bool(criuOpts.FileLocks),
+ EmptyNs: proto.Uint32(criuOpts.EmptyNs),
+ },
+ }
+
+ for _, m := range c.config.Mounts {
+ switch m.Device {
+ case "bind":
+ c.addCriuRestoreMount(req, m)
+ break
+ case "cgroup":
+ binds, err := getCgroupMounts(m)
+ if err != nil {
+ return err
+ }
+ for _, b := range binds {
+ c.addCriuRestoreMount(req, b)
+ }
+ break
+ }
+ }
+
+ if len(c.config.MaskPaths) > 0 {
+ m := &configs.Mount{Destination: "/dev/null", Source: "/dev/null"}
+ c.addCriuRestoreMount(req, m)
+ }
+
+ for _, node := range c.config.Devices {
+ m := &configs.Mount{Destination: node.Path, Source: node.Path}
+ c.addCriuRestoreMount(req, m)
+ }
+
+ if criuOpts.EmptyNs&syscall.CLONE_NEWNET == 0 {
+ c.restoreNetwork(req, criuOpts)
+ }
+
+ // append optional manage cgroups mode
+ if criuOpts.ManageCgroupsMode != 0 {
+ if err := c.checkCriuVersion("1.7"); err != nil {
+ return err
+ }
+ mode := criurpc.CriuCgMode(criuOpts.ManageCgroupsMode)
+ req.Opts.ManageCgroupsMode = &mode
+ }
+
+ var (
+ fds []string
+ fdJSON []byte
+ )
+ if fdJSON, err = ioutil.ReadFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename)); err != nil {
+ return err
+ }
+
+ if err := json.Unmarshal(fdJSON, &fds); err != nil {
+ return err
+ }
+ for i := range fds {
+ if s := fds[i]; strings.Contains(s, "pipe:") {
+ inheritFd := new(criurpc.InheritFd)
+ inheritFd.Key = proto.String(s)
+ inheritFd.Fd = proto.Int32(int32(i))
+ req.Opts.InheritFd = append(req.Opts.InheritFd, inheritFd)
+ }
+ }
+ return c.criuSwrk(process, req, criuOpts, true)
+}
+
+func (c *linuxContainer) criuApplyCgroups(pid int, req *criurpc.CriuReq) error {
+ // XXX: Do we need to deal with this case? AFAIK criu still requires root.
+ if err := c.cgroupManager.Apply(pid); err != nil {
+ return err
+ }
+
+ if err := c.cgroupManager.Set(c.config); err != nil {
+ return newSystemError(err)
+ }
+
+ path := fmt.Sprintf("/proc/%d/cgroup", pid)
+ cgroupsPaths, err := cgroups.ParseCgroupFile(path)
+ if err != nil {
+ return err
+ }
+
+ for c, p := range cgroupsPaths {
+ cgroupRoot := &criurpc.CgroupRoot{
+ Ctrl: proto.String(c),
+ Path: proto.String(p),
+ }
+ req.Opts.CgRoot = append(req.Opts.CgRoot, cgroupRoot)
+ }
+
+ return nil
+}
+
+func (c *linuxContainer) criuSwrk(process *Process, req *criurpc.CriuReq, opts *CriuOpts, applyCgroups bool) error {
+ fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_SEQPACKET|syscall.SOCK_CLOEXEC, 0)
+ if err != nil {
+ return err
+ }
+
+ logPath := filepath.Join(opts.WorkDirectory, req.GetOpts().GetLogFile())
+ criuClient := os.NewFile(uintptr(fds[0]), "criu-transport-client")
+ criuServer := os.NewFile(uintptr(fds[1]), "criu-transport-server")
+ defer criuClient.Close()
+ defer criuServer.Close()
+
+ args := []string{"swrk", "3"}
+ logrus.Debugf("Using CRIU %d at: %s", c.criuVersion, c.criuPath)
+ logrus.Debugf("Using CRIU with following args: %s", args)
+ cmd := exec.Command(c.criuPath, args...)
+ if process != nil {
+ cmd.Stdin = process.Stdin
+ cmd.Stdout = process.Stdout
+ cmd.Stderr = process.Stderr
+ }
+ cmd.ExtraFiles = append(cmd.ExtraFiles, criuServer)
+
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ criuServer.Close()
+
+ defer func() {
+ criuClient.Close()
+ _, err := cmd.Process.Wait()
+ if err != nil {
+ return
+ }
+ }()
+
+ if applyCgroups {
+ err := c.criuApplyCgroups(cmd.Process.Pid, req)
+ if err != nil {
+ return err
+ }
+ }
+
+ var extFds []string
+ if process != nil {
+ extFds, err = getPipeFds(cmd.Process.Pid)
+ if err != nil {
+ return err
+ }
+ }
+
+ logrus.Debugf("Using CRIU in %s mode", req.GetType().String())
+ // In the case of criurpc.CriuReqType_FEATURE_CHECK req.GetOpts()
+ // should be empty. For older CRIU versions it still will be
+ // available but empty.
+ if req.GetType() != criurpc.CriuReqType_FEATURE_CHECK {
+ val := reflect.ValueOf(req.GetOpts())
+ v := reflect.Indirect(val)
+ for i := 0; i < v.NumField(); i++ {
+ st := v.Type()
+ name := st.Field(i).Name
+ if strings.HasPrefix(name, "XXX_") {
+ continue
+ }
+ value := val.MethodByName("Get" + name).Call([]reflect.Value{})
+ logrus.Debugf("CRIU option %s with value %v", name, value[0])
+ }
+ }
+ data, err := proto.Marshal(req)
+ if err != nil {
+ return err
+ }
+ _, err = criuClient.Write(data)
+ if err != nil {
+ return err
+ }
+
+ buf := make([]byte, 10*4096)
+ for true {
+ n, err := criuClient.Read(buf)
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return fmt.Errorf("unexpected EOF")
+ }
+ if n == len(buf) {
+ return fmt.Errorf("buffer is too small")
+ }
+
+ resp := new(criurpc.CriuResp)
+ err = proto.Unmarshal(buf[:n], resp)
+ if err != nil {
+ return err
+ }
+ if !resp.GetSuccess() {
+ typeString := req.GetType().String()
+ return fmt.Errorf("criu failed: type %s errno %d\nlog file: %s", typeString, resp.GetCrErrno(), logPath)
+ }
+
+ t := resp.GetType()
+ switch {
+ case t == criurpc.CriuReqType_FEATURE_CHECK:
+ logrus.Debugf("Feature check says: %s", resp)
+ criuFeatures = resp.GetFeatures()
+ break
+ case t == criurpc.CriuReqType_NOTIFY:
+ if err := c.criuNotifications(resp, process, opts, extFds); err != nil {
+ return err
+ }
+ t = criurpc.CriuReqType_NOTIFY
+ req = &criurpc.CriuReq{
+ Type: &t,
+ NotifySuccess: proto.Bool(true),
+ }
+ data, err = proto.Marshal(req)
+ if err != nil {
+ return err
+ }
+ _, err = criuClient.Write(data)
+ if err != nil {
+ return err
+ }
+ continue
+ case t == criurpc.CriuReqType_RESTORE:
+ case t == criurpc.CriuReqType_DUMP:
+ break
+ case t == criurpc.CriuReqType_PRE_DUMP:
+ // In pre-dump mode CRIU is in a loop and waits for
+ // the final DUMP command.
+ // The current runc pre-dump approach, however, is
+ // start criu in PRE_DUMP once for a single pre-dump
+ // and not the whole series of pre-dump, pre-dump, ...m, dump
+ // If we got the message CriuReqType_PRE_DUMP it means
+ // CRIU was successful and we need to forcefully stop CRIU
+ logrus.Debugf("PRE_DUMP finished. Send close signal to CRIU service")
+ criuClient.Close()
+ // Process status won't be success, because one end of sockets is closed
+ _, err := cmd.Process.Wait()
+ if err != nil {
+ logrus.Debugf("After PRE_DUMP CRIU exiting failed")
+ return err
+ }
+ return nil
+ default:
+ return fmt.Errorf("unable to parse the response %s", resp.String())
+ }
+
+ break
+ }
+
+ // cmd.Wait() waits cmd.goroutines which are used for proxying file descriptors.
+ // Here we want to wait only the CRIU process.
+ st, err := cmd.Process.Wait()
+ if err != nil {
+ return err
+ }
+ if !st.Success() {
+ return fmt.Errorf("criu failed: %s\nlog file: %s", st.String(), logPath)
+ }
+ return nil
+}
+
+// block any external network activity
+func lockNetwork(config *configs.Config) error {
+ for _, config := range config.Networks {
+ strategy, err := getStrategy(config.Type)
+ if err != nil {
+ return err
+ }
+
+ if err := strategy.detach(config); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func unlockNetwork(config *configs.Config) error {
+ for _, config := range config.Networks {
+ strategy, err := getStrategy(config.Type)
+ if err != nil {
+ return err
+ }
+ if err = strategy.attach(config); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (c *linuxContainer) criuNotifications(resp *criurpc.CriuResp, process *Process, opts *CriuOpts, fds []string) error {
+ notify := resp.GetNotify()
+ if notify == nil {
+ return fmt.Errorf("invalid response: %s", resp.String())
+ }
+ switch {
+ case notify.GetScript() == "post-dump":
+ f, err := os.Create(filepath.Join(c.root, "checkpoint"))
+ if err != nil {
+ return err
+ }
+ f.Close()
+ case notify.GetScript() == "network-unlock":
+ if err := unlockNetwork(c.config); err != nil {
+ return err
+ }
+ case notify.GetScript() == "network-lock":
+ if err := lockNetwork(c.config); err != nil {
+ return err
+ }
+ case notify.GetScript() == "setup-namespaces":
+ if c.config.Hooks != nil {
+ s := configs.HookState{
+ Version: c.config.Version,
+ ID: c.id,
+ Pid: int(notify.GetPid()),
+ Bundle: utils.SearchLabels(c.config.Labels, "bundle"),
+ }
+ for i, hook := range c.config.Hooks.Prestart {
+ if err := hook.Run(s); err != nil {
+ return newSystemErrorWithCausef(err, "running prestart hook %d", i)
+ }
+ }
+ }
+ case notify.GetScript() == "post-restore":
+ pid := notify.GetPid()
+ r, err := newRestoredProcess(int(pid), fds)
+ if err != nil {
+ return err
+ }
+ process.ops = r
+ if err := c.state.transition(&restoredState{
+ imageDir: opts.ImagesDirectory,
+ c: c,
+ }); err != nil {
+ return err
+ }
+ // create a timestamp indicating when the restored checkpoint was started
+ c.created = time.Now().UTC()
+ if _, err := c.updateState(r); err != nil {
+ return err
+ }
+ if err := os.Remove(filepath.Join(c.root, "checkpoint")); err != nil {
+ if !os.IsNotExist(err) {
+ logrus.Error(err)
+ }
+ }
+ }
+ return nil
+}
+
+func (c *linuxContainer) updateState(process parentProcess) (*State, error) {
+ c.initProcess = process
+ state, err := c.currentState()
+ if err != nil {
+ return nil, err
+ }
+ err = c.saveState(state)
+ if err != nil {
+ return nil, err
+ }
+ return state, nil
+}
+
+func (c *linuxContainer) saveState(s *State) error {
+ f, err := os.Create(filepath.Join(c.root, stateFilename))
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ return utils.WriteJSON(f, s)
+}
+
+func (c *linuxContainer) deleteState() error {
+ return os.Remove(filepath.Join(c.root, stateFilename))
+}
+
+func (c *linuxContainer) currentStatus() (Status, error) {
+ if err := c.refreshState(); err != nil {
+ return -1, err
+ }
+ return c.state.status(), nil
+}
+
+// refreshState needs to be called to verify that the current state on the
+// container is what is true. Because consumers of libcontainer can use it
+// out of process we need to verify the container's status based on runtime
+// information and not rely on our in process info.
+func (c *linuxContainer) refreshState() error {
+ paused, err := c.isPaused()
+ if err != nil {
+ return err
+ }
+ if paused {
+ return c.state.transition(&pausedState{c: c})
+ }
+ t, err := c.runType()
+ if err != nil {
+ return err
+ }
+ switch t {
+ case Created:
+ return c.state.transition(&createdState{c: c})
+ case Running:
+ return c.state.transition(&runningState{c: c})
+ }
+ return c.state.transition(&stoppedState{c: c})
+}
+
+// doesInitProcessExist checks if the init process is still the same process
+// as the initial one, it could happen that the original process has exited
+// and a new process has been created with the same pid, in this case, the
+// container would already be stopped.
+func (c *linuxContainer) doesInitProcessExist(initPid int) (bool, error) {
+ startTime, err := system.GetProcessStartTime(initPid)
+ if err != nil {
+ return false, newSystemErrorWithCausef(err, "getting init process %d start time", initPid)
+ }
+ if c.initProcessStartTime != startTime {
+ return false, nil
+ }
+ return true, nil
+}
+
+func (c *linuxContainer) runType() (Status, error) {
+ if c.initProcess == nil {
+ return Stopped, nil
+ }
+ pid := c.initProcess.pid()
+ // return Running if the init process is alive
+ if err := syscall.Kill(pid, 0); err != nil {
+ if err == syscall.ESRCH {
+ // It means the process does not exist anymore, could happen when the
+ // process exited just when we call the function, we should not return
+ // error in this case.
+ return Stopped, nil
+ }
+ return Stopped, newSystemErrorWithCausef(err, "sending signal 0 to pid %d", pid)
+ }
+ // check if the process is still the original init process.
+ exist, err := c.doesInitProcessExist(pid)
+ if !exist || err != nil {
+ return Stopped, err
+ }
+ // We'll create exec fifo and blocking on it after container is created,
+ // and delete it after start container.
+ if _, err := os.Stat(filepath.Join(c.root, execFifoFilename)); err == nil {
+ return Created, nil
+ }
+ return Running, nil
+}
+
+func (c *linuxContainer) isPaused() (bool, error) {
+ fcg := c.cgroupManager.GetPaths()["freezer"]
+ if fcg == "" {
+ // A container doesn't have a freezer cgroup
+ return false, nil
+ }
+ data, err := ioutil.ReadFile(filepath.Join(fcg, "freezer.state"))
+ if err != nil {
+ // If freezer cgroup is not mounted, the container would just be not paused.
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, newSystemErrorWithCause(err, "checking if container is paused")
+ }
+ return bytes.Equal(bytes.TrimSpace(data), []byte("FROZEN")), nil
+}
+
+func (c *linuxContainer) currentState() (*State, error) {
+ var (
+ startTime string
+ externalDescriptors []string
+ pid = -1
+ )
+ if c.initProcess != nil {
+ pid = c.initProcess.pid()
+ startTime, _ = c.initProcess.startTime()
+ externalDescriptors = c.initProcess.externalDescriptors()
+ }
+ state := &State{
+ BaseState: BaseState{
+ ID: c.ID(),
+ Config: *c.config,
+ InitProcessPid: pid,
+ InitProcessStartTime: startTime,
+ Created: c.created,
+ },
+ Rootless: c.config.Rootless,
+ CgroupPaths: c.cgroupManager.GetPaths(),
+ NamespacePaths: make(map[configs.NamespaceType]string),
+ ExternalDescriptors: externalDescriptors,
+ }
+ if pid > 0 {
+ for _, ns := range c.config.Namespaces {
+ state.NamespacePaths[ns.Type] = ns.GetPath(pid)
+ }
+ for _, nsType := range configs.NamespaceTypes() {
+ if !configs.IsNamespaceSupported(nsType) {
+ continue
+ }
+ if _, ok := state.NamespacePaths[nsType]; !ok {
+ ns := configs.Namespace{Type: nsType}
+ state.NamespacePaths[ns.Type] = ns.GetPath(pid)
+ }
+ }
+ }
+ return state, nil
+}
+
+// orderNamespacePaths sorts namespace paths into a list of paths that we
+// can setns in order.
+func (c *linuxContainer) orderNamespacePaths(namespaces map[configs.NamespaceType]string) ([]string, error) {
+ paths := []string{}
+
+ for _, ns := range configs.NamespaceTypes() {
+
+ // Remove namespaces that we don't need to join.
+ if !c.config.Namespaces.Contains(ns) {
+ continue
+ }
+
+ if p, ok := namespaces[ns]; ok && p != "" {
+ // check if the requested namespace is supported
+ if !configs.IsNamespaceSupported(ns) {
+ return nil, newSystemError(fmt.Errorf("namespace %s is not supported", ns))
+ }
+ // only set to join this namespace if it exists
+ if _, err := os.Lstat(p); err != nil {
+ return nil, newSystemErrorWithCausef(err, "running lstat on namespace path %q", p)
+ }
+ // do not allow namespace path with comma as we use it to separate
+ // the namespace paths
+ if strings.ContainsRune(p, ',') {
+ return nil, newSystemError(fmt.Errorf("invalid path %s", p))
+ }
+ paths = append(paths, fmt.Sprintf("%s:%s", configs.NsName(ns), p))
+ }
+
+ }
+
+ return paths, nil
+}
+
+func encodeIDMapping(idMap []configs.IDMap) ([]byte, error) {
+ data := bytes.NewBuffer(nil)
+ for _, im := range idMap {
+ line := fmt.Sprintf("%d %d %d\n", im.ContainerID, im.HostID, im.Size)
+ if _, err := data.WriteString(line); err != nil {
+ return nil, err
+ }
+ }
+ return data.Bytes(), nil
+}
+
+// bootstrapData encodes the necessary data in netlink binary format
+// as a io.Reader.
+// Consumer can write the data to a bootstrap program
+// such as one that uses nsenter package to bootstrap the container's
+// init process correctly, i.e. with correct namespaces, uid/gid
+// mapping etc.
+func (c *linuxContainer) bootstrapData(cloneFlags uintptr, nsMaps map[configs.NamespaceType]string) (io.Reader, error) {
+ // create the netlink message
+ r := nl.NewNetlinkRequest(int(InitMsg), 0)
+
+ // write cloneFlags
+ r.AddData(&Int32msg{
+ Type: CloneFlagsAttr,
+ Value: uint32(cloneFlags),
+ })
+
+ // write custom namespace paths
+ if len(nsMaps) > 0 {
+ nsPaths, err := c.orderNamespacePaths(nsMaps)
+ if err != nil {
+ return nil, err
+ }
+ r.AddData(&Bytemsg{
+ Type: NsPathsAttr,
+ Value: []byte(strings.Join(nsPaths, ",")),
+ })
+ }
+
+ // write namespace paths only when we are not joining an existing user ns
+ _, joinExistingUser := nsMaps[configs.NEWUSER]
+ if !joinExistingUser {
+ // write uid mappings
+ if len(c.config.UidMappings) > 0 {
+ b, err := encodeIDMapping(c.config.UidMappings)
+ if err != nil {
+ return nil, err
+ }
+ r.AddData(&Bytemsg{
+ Type: UidmapAttr,
+ Value: b,
+ })
+ }
+
+ // write gid mappings
+ if len(c.config.GidMappings) > 0 {
+ b, err := encodeIDMapping(c.config.GidMappings)
+ if err != nil {
+ return nil, err
+ }
+ r.AddData(&Bytemsg{
+ Type: GidmapAttr,
+ Value: b,
+ })
+ // The following only applies if we are root.
+ if !c.config.Rootless {
+ // check if we have CAP_SETGID to setgroup properly
+ pid, err := capability.NewPid(os.Getpid())
+ if err != nil {
+ return nil, err
+ }
+ if !pid.Get(capability.EFFECTIVE, capability.CAP_SETGID) {
+ r.AddData(&Boolmsg{
+ Type: SetgroupAttr,
+ Value: true,
+ })
+ }
+ }
+ }
+ }
+
+ // write oom_score_adj
+ r.AddData(&Bytemsg{
+ Type: OomScoreAdjAttr,
+ Value: []byte(fmt.Sprintf("%d", c.config.OomScoreAdj)),
+ })
+
+ // write rootless
+ r.AddData(&Boolmsg{
+ Type: RootlessAttr,
+ Value: c.config.Rootless,
+ })
+
+ return bytes.NewReader(r.Serialize()), nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/container_solaris.go b/vendor/github.com/opencontainers/runc/libcontainer/container_solaris.go
new file mode 100644
index 0000000..bb84ff7
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/container_solaris.go
@@ -0,0 +1,20 @@
+package libcontainer
+
+// State represents a running container's state
+type State struct {
+ BaseState
+
+ // Platform specific fields below here
+}
+
+// A libcontainer container object.
+//
+// Each container is thread-safe within the same process. Since a container can
+// be destroyed by a separate process, any function may return that the container
+// was not found.
+type Container interface {
+ BaseContainer
+
+ // Methods below here are platform specific
+
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/container_windows.go b/vendor/github.com/opencontainers/runc/libcontainer/container_windows.go
new file mode 100644
index 0000000..bb84ff7
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/container_windows.go
@@ -0,0 +1,20 @@
+package libcontainer
+
+// State represents a running container's state
+type State struct {
+ BaseState
+
+ // Platform specific fields below here
+}
+
+// A libcontainer container object.
+//
+// Each container is thread-safe within the same process. Since a container can
+// be destroyed by a separate process, any function may return that the container
+// was not found.
+type Container interface {
+ BaseContainer
+
+ // Methods below here are platform specific
+
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go
new file mode 100644
index 0000000..9d7d4dc
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go
@@ -0,0 +1,39 @@
+// +build linux freebsd
+
+package libcontainer
+
+// cgroup restoring strategy provided by criu
+type cgMode uint32
+
+const (
+ CRIU_CG_MODE_SOFT cgMode = 3 + iota // restore cgroup properties if only dir created by criu
+ CRIU_CG_MODE_FULL // always restore all cgroups and their properties
+ CRIU_CG_MODE_STRICT // restore all, requiring them to not present in the system
+ CRIU_CG_MODE_DEFAULT // the same as CRIU_CG_MODE_SOFT
+)
+
+type CriuPageServerInfo struct {
+ Address string // IP address of CRIU page server
+ Port int32 // port number of CRIU page server
+}
+
+type VethPairName struct {
+ ContainerInterfaceName string
+ HostInterfaceName string
+}
+
+type CriuOpts struct {
+ ImagesDirectory string // directory for storing image files
+ WorkDirectory string // directory to cd and write logs/pidfiles/stats to
+ ParentImage string // direcotry for storing parent image files in pre-dump and dump
+ LeaveRunning bool // leave container in running state after checkpoint
+ TcpEstablished bool // checkpoint/restore established TCP connections
+ ExternalUnixConnections bool // allow external unix connections
+ ShellJob bool // allow to dump and restore shell jobs
+ FileLocks bool // handle file locks, for safety
+ PreDump bool // call criu predump to perform iterative checkpoint
+ PageServer CriuPageServerInfo // allow to dump to criu page server
+ VethPairs []VethPairName // pass the veth to criu when restore
+ ManageCgroupsMode cgMode // dump or restore cgroup mode
+ EmptyNs uint32 // don't c/r properties for namespace from this mask
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_windows.go b/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_windows.go
new file mode 100644
index 0000000..bc92077
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_windows.go
@@ -0,0 +1,6 @@
+package libcontainer
+
+// TODO Windows: This can ultimately be entirely factored out as criu is
+// a Unix concept not relevant on Windows.
+type CriuOpts struct {
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go b/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go
new file mode 100644
index 0000000..3c4fb77
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go
@@ -0,0 +1,822 @@
+// Code generated by protoc-gen-go.
+// source: criurpc.proto
+// DO NOT EDIT!
+
+/*
+Package criurpc is a generated protocol buffer package.
+
+It is generated from these files:
+ criurpc.proto
+
+It has these top-level messages:
+ CriuPageServerInfo
+ CriuVethPair
+ ExtMountMap
+ InheritFd
+ CgroupRoot
+ UnixSk
+ CriuOpts
+ CriuDumpResp
+ CriuRestoreResp
+ CriuNotify
+ CriuFeatures
+ CriuReq
+ CriuResp
+*/
+package criurpc
+
+import proto "github.com/golang/protobuf/proto"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = math.Inf
+
+type CriuCgMode int32
+
+const (
+ CriuCgMode_IGNORE CriuCgMode = 0
+ CriuCgMode_NONE CriuCgMode = 1
+ CriuCgMode_PROPS CriuCgMode = 2
+ CriuCgMode_SOFT CriuCgMode = 3
+ CriuCgMode_FULL CriuCgMode = 4
+ CriuCgMode_STRICT CriuCgMode = 5
+ CriuCgMode_DEFAULT CriuCgMode = 6
+)
+
+var CriuCgMode_name = map[int32]string{
+ 0: "IGNORE",
+ 1: "NONE",
+ 2: "PROPS",
+ 3: "SOFT",
+ 4: "FULL",
+ 5: "STRICT",
+ 6: "DEFAULT",
+}
+var CriuCgMode_value = map[string]int32{
+ "IGNORE": 0,
+ "NONE": 1,
+ "PROPS": 2,
+ "SOFT": 3,
+ "FULL": 4,
+ "STRICT": 5,
+ "DEFAULT": 6,
+}
+
+func (x CriuCgMode) Enum() *CriuCgMode {
+ p := new(CriuCgMode)
+ *p = x
+ return p
+}
+func (x CriuCgMode) String() string {
+ return proto.EnumName(CriuCgMode_name, int32(x))
+}
+func (x *CriuCgMode) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(CriuCgMode_value, data, "CriuCgMode")
+ if err != nil {
+ return err
+ }
+ *x = CriuCgMode(value)
+ return nil
+}
+
+type CriuReqType int32
+
+const (
+ CriuReqType_EMPTY CriuReqType = 0
+ CriuReqType_DUMP CriuReqType = 1
+ CriuReqType_RESTORE CriuReqType = 2
+ CriuReqType_CHECK CriuReqType = 3
+ CriuReqType_PRE_DUMP CriuReqType = 4
+ CriuReqType_PAGE_SERVER CriuReqType = 5
+ CriuReqType_NOTIFY CriuReqType = 6
+ CriuReqType_CPUINFO_DUMP CriuReqType = 7
+ CriuReqType_CPUINFO_CHECK CriuReqType = 8
+ CriuReqType_FEATURE_CHECK CriuReqType = 9
+)
+
+var CriuReqType_name = map[int32]string{
+ 0: "EMPTY",
+ 1: "DUMP",
+ 2: "RESTORE",
+ 3: "CHECK",
+ 4: "PRE_DUMP",
+ 5: "PAGE_SERVER",
+ 6: "NOTIFY",
+ 7: "CPUINFO_DUMP",
+ 8: "CPUINFO_CHECK",
+ 9: "FEATURE_CHECK",
+}
+var CriuReqType_value = map[string]int32{
+ "EMPTY": 0,
+ "DUMP": 1,
+ "RESTORE": 2,
+ "CHECK": 3,
+ "PRE_DUMP": 4,
+ "PAGE_SERVER": 5,
+ "NOTIFY": 6,
+ "CPUINFO_DUMP": 7,
+ "CPUINFO_CHECK": 8,
+ "FEATURE_CHECK": 9,
+}
+
+func (x CriuReqType) Enum() *CriuReqType {
+ p := new(CriuReqType)
+ *p = x
+ return p
+}
+func (x CriuReqType) String() string {
+ return proto.EnumName(CriuReqType_name, int32(x))
+}
+func (x *CriuReqType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(CriuReqType_value, data, "CriuReqType")
+ if err != nil {
+ return err
+ }
+ *x = CriuReqType(value)
+ return nil
+}
+
+type CriuPageServerInfo struct {
+ Address *string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"`
+ Port *int32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"`
+ Pid *int32 `protobuf:"varint,3,opt,name=pid" json:"pid,omitempty"`
+ Fd *int32 `protobuf:"varint,4,opt,name=fd" json:"fd,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *CriuPageServerInfo) Reset() { *m = CriuPageServerInfo{} }
+func (m *CriuPageServerInfo) String() string { return proto.CompactTextString(m) }
+func (*CriuPageServerInfo) ProtoMessage() {}
+
+func (m *CriuPageServerInfo) GetAddress() string {
+ if m != nil && m.Address != nil {
+ return *m.Address
+ }
+ return ""
+}
+
+func (m *CriuPageServerInfo) GetPort() int32 {
+ if m != nil && m.Port != nil {
+ return *m.Port
+ }
+ return 0
+}
+
+func (m *CriuPageServerInfo) GetPid() int32 {
+ if m != nil && m.Pid != nil {
+ return *m.Pid
+ }
+ return 0
+}
+
+func (m *CriuPageServerInfo) GetFd() int32 {
+ if m != nil && m.Fd != nil {
+ return *m.Fd
+ }
+ return 0
+}
+
+type CriuVethPair struct {
+ IfIn *string `protobuf:"bytes,1,req,name=if_in" json:"if_in,omitempty"`
+ IfOut *string `protobuf:"bytes,2,req,name=if_out" json:"if_out,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *CriuVethPair) Reset() { *m = CriuVethPair{} }
+func (m *CriuVethPair) String() string { return proto.CompactTextString(m) }
+func (*CriuVethPair) ProtoMessage() {}
+
+func (m *CriuVethPair) GetIfIn() string {
+ if m != nil && m.IfIn != nil {
+ return *m.IfIn
+ }
+ return ""
+}
+
+func (m *CriuVethPair) GetIfOut() string {
+ if m != nil && m.IfOut != nil {
+ return *m.IfOut
+ }
+ return ""
+}
+
+type ExtMountMap struct {
+ Key *string `protobuf:"bytes,1,req,name=key" json:"key,omitempty"`
+ Val *string `protobuf:"bytes,2,req,name=val" json:"val,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ExtMountMap) Reset() { *m = ExtMountMap{} }
+func (m *ExtMountMap) String() string { return proto.CompactTextString(m) }
+func (*ExtMountMap) ProtoMessage() {}
+
+func (m *ExtMountMap) GetKey() string {
+ if m != nil && m.Key != nil {
+ return *m.Key
+ }
+ return ""
+}
+
+func (m *ExtMountMap) GetVal() string {
+ if m != nil && m.Val != nil {
+ return *m.Val
+ }
+ return ""
+}
+
+type InheritFd struct {
+ Key *string `protobuf:"bytes,1,req,name=key" json:"key,omitempty"`
+ Fd *int32 `protobuf:"varint,2,req,name=fd" json:"fd,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *InheritFd) Reset() { *m = InheritFd{} }
+func (m *InheritFd) String() string { return proto.CompactTextString(m) }
+func (*InheritFd) ProtoMessage() {}
+
+func (m *InheritFd) GetKey() string {
+ if m != nil && m.Key != nil {
+ return *m.Key
+ }
+ return ""
+}
+
+func (m *InheritFd) GetFd() int32 {
+ if m != nil && m.Fd != nil {
+ return *m.Fd
+ }
+ return 0
+}
+
+type CgroupRoot struct {
+ Ctrl *string `protobuf:"bytes,1,opt,name=ctrl" json:"ctrl,omitempty"`
+ Path *string `protobuf:"bytes,2,req,name=path" json:"path,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *CgroupRoot) Reset() { *m = CgroupRoot{} }
+func (m *CgroupRoot) String() string { return proto.CompactTextString(m) }
+func (*CgroupRoot) ProtoMessage() {}
+
+func (m *CgroupRoot) GetCtrl() string {
+ if m != nil && m.Ctrl != nil {
+ return *m.Ctrl
+ }
+ return ""
+}
+
+func (m *CgroupRoot) GetPath() string {
+ if m != nil && m.Path != nil {
+ return *m.Path
+ }
+ return ""
+}
+
+type UnixSk struct {
+ Inode *uint32 `protobuf:"varint,1,req,name=inode" json:"inode,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *UnixSk) Reset() { *m = UnixSk{} }
+func (m *UnixSk) String() string { return proto.CompactTextString(m) }
+func (*UnixSk) ProtoMessage() {}
+
+func (m *UnixSk) GetInode() uint32 {
+ if m != nil && m.Inode != nil {
+ return *m.Inode
+ }
+ return 0
+}
+
+type CriuOpts struct {
+ ImagesDirFd *int32 `protobuf:"varint,1,req,name=images_dir_fd" json:"images_dir_fd,omitempty"`
+ Pid *int32 `protobuf:"varint,2,opt,name=pid" json:"pid,omitempty"`
+ LeaveRunning *bool `protobuf:"varint,3,opt,name=leave_running" json:"leave_running,omitempty"`
+ ExtUnixSk *bool `protobuf:"varint,4,opt,name=ext_unix_sk" json:"ext_unix_sk,omitempty"`
+ TcpEstablished *bool `protobuf:"varint,5,opt,name=tcp_established" json:"tcp_established,omitempty"`
+ EvasiveDevices *bool `protobuf:"varint,6,opt,name=evasive_devices" json:"evasive_devices,omitempty"`
+ ShellJob *bool `protobuf:"varint,7,opt,name=shell_job" json:"shell_job,omitempty"`
+ FileLocks *bool `protobuf:"varint,8,opt,name=file_locks" json:"file_locks,omitempty"`
+ LogLevel *int32 `protobuf:"varint,9,opt,name=log_level,def=2" json:"log_level,omitempty"`
+ LogFile *string `protobuf:"bytes,10,opt,name=log_file" json:"log_file,omitempty"`
+ Ps *CriuPageServerInfo `protobuf:"bytes,11,opt,name=ps" json:"ps,omitempty"`
+ NotifyScripts *bool `protobuf:"varint,12,opt,name=notify_scripts" json:"notify_scripts,omitempty"`
+ Root *string `protobuf:"bytes,13,opt,name=root" json:"root,omitempty"`
+ ParentImg *string `protobuf:"bytes,14,opt,name=parent_img" json:"parent_img,omitempty"`
+ TrackMem *bool `protobuf:"varint,15,opt,name=track_mem" json:"track_mem,omitempty"`
+ AutoDedup *bool `protobuf:"varint,16,opt,name=auto_dedup" json:"auto_dedup,omitempty"`
+ WorkDirFd *int32 `protobuf:"varint,17,opt,name=work_dir_fd" json:"work_dir_fd,omitempty"`
+ LinkRemap *bool `protobuf:"varint,18,opt,name=link_remap" json:"link_remap,omitempty"`
+ Veths []*CriuVethPair `protobuf:"bytes,19,rep,name=veths" json:"veths,omitempty"`
+ CpuCap *uint32 `protobuf:"varint,20,opt,name=cpu_cap,def=4294967295" json:"cpu_cap,omitempty"`
+ ForceIrmap *bool `protobuf:"varint,21,opt,name=force_irmap" json:"force_irmap,omitempty"`
+ ExecCmd []string `protobuf:"bytes,22,rep,name=exec_cmd" json:"exec_cmd,omitempty"`
+ ExtMnt []*ExtMountMap `protobuf:"bytes,23,rep,name=ext_mnt" json:"ext_mnt,omitempty"`
+ ManageCgroups *bool `protobuf:"varint,24,opt,name=manage_cgroups" json:"manage_cgroups,omitempty"`
+ CgRoot []*CgroupRoot `protobuf:"bytes,25,rep,name=cg_root" json:"cg_root,omitempty"`
+ RstSibling *bool `protobuf:"varint,26,opt,name=rst_sibling" json:"rst_sibling,omitempty"`
+ InheritFd []*InheritFd `protobuf:"bytes,27,rep,name=inherit_fd" json:"inherit_fd,omitempty"`
+ AutoExtMnt *bool `protobuf:"varint,28,opt,name=auto_ext_mnt" json:"auto_ext_mnt,omitempty"`
+ ExtSharing *bool `protobuf:"varint,29,opt,name=ext_sharing" json:"ext_sharing,omitempty"`
+ ExtMasters *bool `protobuf:"varint,30,opt,name=ext_masters" json:"ext_masters,omitempty"`
+ SkipMnt []string `protobuf:"bytes,31,rep,name=skip_mnt" json:"skip_mnt,omitempty"`
+ EnableFs []string `protobuf:"bytes,32,rep,name=enable_fs" json:"enable_fs,omitempty"`
+ UnixSkIno []*UnixSk `protobuf:"bytes,33,rep,name=unix_sk_ino" json:"unix_sk_ino,omitempty"`
+ ManageCgroupsMode *CriuCgMode `protobuf:"varint,34,opt,name=manage_cgroups_mode,enum=CriuCgMode" json:"manage_cgroups_mode,omitempty"`
+ GhostLimit *uint32 `protobuf:"varint,35,opt,name=ghost_limit,def=1048576" json:"ghost_limit,omitempty"`
+ IrmapScanPaths []string `protobuf:"bytes,36,rep,name=irmap_scan_paths" json:"irmap_scan_paths,omitempty"`
+ External []string `protobuf:"bytes,37,rep,name=external" json:"external,omitempty"`
+ EmptyNs *uint32 `protobuf:"varint,38,opt,name=empty_ns" json:"empty_ns,omitempty"`
+ NoSeccomp *bool `protobuf:"varint,39,opt,name=no_seccomp" json:"no_seccomp,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *CriuOpts) Reset() { *m = CriuOpts{} }
+func (m *CriuOpts) String() string { return proto.CompactTextString(m) }
+func (*CriuOpts) ProtoMessage() {}
+
+const Default_CriuOpts_LogLevel int32 = 2
+const Default_CriuOpts_CpuCap uint32 = 4294967295
+const Default_CriuOpts_GhostLimit uint32 = 1048576
+
+func (m *CriuOpts) GetImagesDirFd() int32 {
+ if m != nil && m.ImagesDirFd != nil {
+ return *m.ImagesDirFd
+ }
+ return 0
+}
+
+func (m *CriuOpts) GetPid() int32 {
+ if m != nil && m.Pid != nil {
+ return *m.Pid
+ }
+ return 0
+}
+
+func (m *CriuOpts) GetLeaveRunning() bool {
+ if m != nil && m.LeaveRunning != nil {
+ return *m.LeaveRunning
+ }
+ return false
+}
+
+func (m *CriuOpts) GetExtUnixSk() bool {
+ if m != nil && m.ExtUnixSk != nil {
+ return *m.ExtUnixSk
+ }
+ return false
+}
+
+func (m *CriuOpts) GetTcpEstablished() bool {
+ if m != nil && m.TcpEstablished != nil {
+ return *m.TcpEstablished
+ }
+ return false
+}
+
+func (m *CriuOpts) GetEvasiveDevices() bool {
+ if m != nil && m.EvasiveDevices != nil {
+ return *m.EvasiveDevices
+ }
+ return false
+}
+
+func (m *CriuOpts) GetShellJob() bool {
+ if m != nil && m.ShellJob != nil {
+ return *m.ShellJob
+ }
+ return false
+}
+
+func (m *CriuOpts) GetFileLocks() bool {
+ if m != nil && m.FileLocks != nil {
+ return *m.FileLocks
+ }
+ return false
+}
+
+func (m *CriuOpts) GetLogLevel() int32 {
+ if m != nil && m.LogLevel != nil {
+ return *m.LogLevel
+ }
+ return Default_CriuOpts_LogLevel
+}
+
+func (m *CriuOpts) GetLogFile() string {
+ if m != nil && m.LogFile != nil {
+ return *m.LogFile
+ }
+ return ""
+}
+
+func (m *CriuOpts) GetPs() *CriuPageServerInfo {
+ if m != nil {
+ return m.Ps
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetNotifyScripts() bool {
+ if m != nil && m.NotifyScripts != nil {
+ return *m.NotifyScripts
+ }
+ return false
+}
+
+func (m *CriuOpts) GetRoot() string {
+ if m != nil && m.Root != nil {
+ return *m.Root
+ }
+ return ""
+}
+
+func (m *CriuOpts) GetParentImg() string {
+ if m != nil && m.ParentImg != nil {
+ return *m.ParentImg
+ }
+ return ""
+}
+
+func (m *CriuOpts) GetTrackMem() bool {
+ if m != nil && m.TrackMem != nil {
+ return *m.TrackMem
+ }
+ return false
+}
+
+func (m *CriuOpts) GetAutoDedup() bool {
+ if m != nil && m.AutoDedup != nil {
+ return *m.AutoDedup
+ }
+ return false
+}
+
+func (m *CriuOpts) GetWorkDirFd() int32 {
+ if m != nil && m.WorkDirFd != nil {
+ return *m.WorkDirFd
+ }
+ return 0
+}
+
+func (m *CriuOpts) GetLinkRemap() bool {
+ if m != nil && m.LinkRemap != nil {
+ return *m.LinkRemap
+ }
+ return false
+}
+
+func (m *CriuOpts) GetVeths() []*CriuVethPair {
+ if m != nil {
+ return m.Veths
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetCpuCap() uint32 {
+ if m != nil && m.CpuCap != nil {
+ return *m.CpuCap
+ }
+ return Default_CriuOpts_CpuCap
+}
+
+func (m *CriuOpts) GetForceIrmap() bool {
+ if m != nil && m.ForceIrmap != nil {
+ return *m.ForceIrmap
+ }
+ return false
+}
+
+func (m *CriuOpts) GetExecCmd() []string {
+ if m != nil {
+ return m.ExecCmd
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetExtMnt() []*ExtMountMap {
+ if m != nil {
+ return m.ExtMnt
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetManageCgroups() bool {
+ if m != nil && m.ManageCgroups != nil {
+ return *m.ManageCgroups
+ }
+ return false
+}
+
+func (m *CriuOpts) GetCgRoot() []*CgroupRoot {
+ if m != nil {
+ return m.CgRoot
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetRstSibling() bool {
+ if m != nil && m.RstSibling != nil {
+ return *m.RstSibling
+ }
+ return false
+}
+
+func (m *CriuOpts) GetInheritFd() []*InheritFd {
+ if m != nil {
+ return m.InheritFd
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetAutoExtMnt() bool {
+ if m != nil && m.AutoExtMnt != nil {
+ return *m.AutoExtMnt
+ }
+ return false
+}
+
+func (m *CriuOpts) GetExtSharing() bool {
+ if m != nil && m.ExtSharing != nil {
+ return *m.ExtSharing
+ }
+ return false
+}
+
+func (m *CriuOpts) GetExtMasters() bool {
+ if m != nil && m.ExtMasters != nil {
+ return *m.ExtMasters
+ }
+ return false
+}
+
+func (m *CriuOpts) GetSkipMnt() []string {
+ if m != nil {
+ return m.SkipMnt
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetEnableFs() []string {
+ if m != nil {
+ return m.EnableFs
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetUnixSkIno() []*UnixSk {
+ if m != nil {
+ return m.UnixSkIno
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetManageCgroupsMode() CriuCgMode {
+ if m != nil && m.ManageCgroupsMode != nil {
+ return *m.ManageCgroupsMode
+ }
+ return CriuCgMode_IGNORE
+}
+
+func (m *CriuOpts) GetGhostLimit() uint32 {
+ if m != nil && m.GhostLimit != nil {
+ return *m.GhostLimit
+ }
+ return Default_CriuOpts_GhostLimit
+}
+
+func (m *CriuOpts) GetIrmapScanPaths() []string {
+ if m != nil {
+ return m.IrmapScanPaths
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetExternal() []string {
+ if m != nil {
+ return m.External
+ }
+ return nil
+}
+
+func (m *CriuOpts) GetEmptyNs() uint32 {
+ if m != nil && m.EmptyNs != nil {
+ return *m.EmptyNs
+ }
+ return 0
+}
+
+func (m *CriuOpts) GetNoSeccomp() bool {
+ if m != nil && m.NoSeccomp != nil {
+ return *m.NoSeccomp
+ }
+ return false
+}
+
+type CriuDumpResp struct {
+ Restored *bool `protobuf:"varint,1,opt,name=restored" json:"restored,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *CriuDumpResp) Reset() { *m = CriuDumpResp{} }
+func (m *CriuDumpResp) String() string { return proto.CompactTextString(m) }
+func (*CriuDumpResp) ProtoMessage() {}
+
+func (m *CriuDumpResp) GetRestored() bool {
+ if m != nil && m.Restored != nil {
+ return *m.Restored
+ }
+ return false
+}
+
+type CriuRestoreResp struct {
+ Pid *int32 `protobuf:"varint,1,req,name=pid" json:"pid,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *CriuRestoreResp) Reset() { *m = CriuRestoreResp{} }
+func (m *CriuRestoreResp) String() string { return proto.CompactTextString(m) }
+func (*CriuRestoreResp) ProtoMessage() {}
+
+func (m *CriuRestoreResp) GetPid() int32 {
+ if m != nil && m.Pid != nil {
+ return *m.Pid
+ }
+ return 0
+}
+
+type CriuNotify struct {
+ Script *string `protobuf:"bytes,1,opt,name=script" json:"script,omitempty"`
+ Pid *int32 `protobuf:"varint,2,opt,name=pid" json:"pid,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *CriuNotify) Reset() { *m = CriuNotify{} }
+func (m *CriuNotify) String() string { return proto.CompactTextString(m) }
+func (*CriuNotify) ProtoMessage() {}
+
+func (m *CriuNotify) GetScript() string {
+ if m != nil && m.Script != nil {
+ return *m.Script
+ }
+ return ""
+}
+
+func (m *CriuNotify) GetPid() int32 {
+ if m != nil && m.Pid != nil {
+ return *m.Pid
+ }
+ return 0
+}
+
+//
+// List of features which can queried via
+// CRIU_REQ_TYPE__FEATURE_CHECK
+type CriuFeatures struct {
+ MemTrack *bool `protobuf:"varint,1,opt,name=mem_track" json:"mem_track,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *CriuFeatures) Reset() { *m = CriuFeatures{} }
+func (m *CriuFeatures) String() string { return proto.CompactTextString(m) }
+func (*CriuFeatures) ProtoMessage() {}
+
+func (m *CriuFeatures) GetMemTrack() bool {
+ if m != nil && m.MemTrack != nil {
+ return *m.MemTrack
+ }
+ return false
+}
+
+type CriuReq struct {
+ Type *CriuReqType `protobuf:"varint,1,req,name=type,enum=CriuReqType" json:"type,omitempty"`
+ Opts *CriuOpts `protobuf:"bytes,2,opt,name=opts" json:"opts,omitempty"`
+ NotifySuccess *bool `protobuf:"varint,3,opt,name=notify_success" json:"notify_success,omitempty"`
+ //
+ // When set service won't close the connection but
+ // will wait for more req-s to appear. Works not
+ // for all request types.
+ KeepOpen *bool `protobuf:"varint,4,opt,name=keep_open" json:"keep_open,omitempty"`
+ //
+ // 'features' can be used to query which features
+ // are supported by the installed criu/kernel
+ // via RPC.
+ Features *CriuFeatures `protobuf:"bytes,5,opt,name=features" json:"features,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *CriuReq) Reset() { *m = CriuReq{} }
+func (m *CriuReq) String() string { return proto.CompactTextString(m) }
+func (*CriuReq) ProtoMessage() {}
+
+func (m *CriuReq) GetType() CriuReqType {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return CriuReqType_EMPTY
+}
+
+func (m *CriuReq) GetOpts() *CriuOpts {
+ if m != nil {
+ return m.Opts
+ }
+ return nil
+}
+
+func (m *CriuReq) GetNotifySuccess() bool {
+ if m != nil && m.NotifySuccess != nil {
+ return *m.NotifySuccess
+ }
+ return false
+}
+
+func (m *CriuReq) GetKeepOpen() bool {
+ if m != nil && m.KeepOpen != nil {
+ return *m.KeepOpen
+ }
+ return false
+}
+
+func (m *CriuReq) GetFeatures() *CriuFeatures {
+ if m != nil {
+ return m.Features
+ }
+ return nil
+}
+
+type CriuResp struct {
+ Type *CriuReqType `protobuf:"varint,1,req,name=type,enum=CriuReqType" json:"type,omitempty"`
+ Success *bool `protobuf:"varint,2,req,name=success" json:"success,omitempty"`
+ Dump *CriuDumpResp `protobuf:"bytes,3,opt,name=dump" json:"dump,omitempty"`
+ Restore *CriuRestoreResp `protobuf:"bytes,4,opt,name=restore" json:"restore,omitempty"`
+ Notify *CriuNotify `protobuf:"bytes,5,opt,name=notify" json:"notify,omitempty"`
+ Ps *CriuPageServerInfo `protobuf:"bytes,6,opt,name=ps" json:"ps,omitempty"`
+ CrErrno *int32 `protobuf:"varint,7,opt,name=cr_errno" json:"cr_errno,omitempty"`
+ Features *CriuFeatures `protobuf:"bytes,8,opt,name=features" json:"features,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *CriuResp) Reset() { *m = CriuResp{} }
+func (m *CriuResp) String() string { return proto.CompactTextString(m) }
+func (*CriuResp) ProtoMessage() {}
+
+func (m *CriuResp) GetType() CriuReqType {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return CriuReqType_EMPTY
+}
+
+func (m *CriuResp) GetSuccess() bool {
+ if m != nil && m.Success != nil {
+ return *m.Success
+ }
+ return false
+}
+
+func (m *CriuResp) GetDump() *CriuDumpResp {
+ if m != nil {
+ return m.Dump
+ }
+ return nil
+}
+
+func (m *CriuResp) GetRestore() *CriuRestoreResp {
+ if m != nil {
+ return m.Restore
+ }
+ return nil
+}
+
+func (m *CriuResp) GetNotify() *CriuNotify {
+ if m != nil {
+ return m.Notify
+ }
+ return nil
+}
+
+func (m *CriuResp) GetPs() *CriuPageServerInfo {
+ if m != nil {
+ return m.Ps
+ }
+ return nil
+}
+
+func (m *CriuResp) GetCrErrno() int32 {
+ if m != nil && m.CrErrno != nil {
+ return *m.CrErrno
+ }
+ return 0
+}
+
+func (m *CriuResp) GetFeatures() *CriuFeatures {
+ if m != nil {
+ return m.Features
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterEnum("CriuCgMode", CriuCgMode_name, CriuCgMode_value)
+ proto.RegisterEnum("CriuReqType", CriuReqType_name, CriuReqType_value)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto b/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto
new file mode 100644
index 0000000..34fa988
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto
@@ -0,0 +1,174 @@
+message criu_page_server_info {
+ optional string address = 1;
+ optional int32 port = 2;
+ optional int32 pid = 3;
+ optional int32 fd = 4;
+}
+
+message criu_veth_pair {
+ required string if_in = 1;
+ required string if_out = 2;
+};
+
+message ext_mount_map {
+ required string key = 1;
+ required string val = 2;
+};
+
+message inherit_fd {
+ required string key = 1;
+ required int32 fd = 2;
+};
+
+message cgroup_root {
+ optional string ctrl = 1;
+ required string path = 2;
+};
+
+message unix_sk {
+ required uint32 inode = 1;
+};
+
+enum criu_cg_mode {
+ IGNORE = 0;
+ NONE = 1;
+ PROPS = 2;
+ SOFT = 3;
+ FULL = 4;
+ STRICT = 5;
+ DEFAULT = 6;
+};
+
+message criu_opts {
+ required int32 images_dir_fd = 1;
+ optional int32 pid = 2; /* if not set on dump, will dump requesting process */
+
+ optional bool leave_running = 3;
+ optional bool ext_unix_sk = 4;
+ optional bool tcp_established = 5;
+ optional bool evasive_devices = 6;
+ optional bool shell_job = 7;
+ optional bool file_locks = 8;
+ optional int32 log_level = 9 [default = 2];
+ optional string log_file = 10; /* No subdirs are allowed. Consider using work-dir */
+
+ optional criu_page_server_info ps = 11;
+
+ optional bool notify_scripts = 12;
+
+ optional string root = 13;
+ optional string parent_img = 14;
+ optional bool track_mem = 15;
+ optional bool auto_dedup = 16;
+
+ optional int32 work_dir_fd = 17;
+ optional bool link_remap = 18;
+ repeated criu_veth_pair veths = 19;
+
+ optional uint32 cpu_cap = 20 [default = 0xffffffff];
+ optional bool force_irmap = 21;
+ repeated string exec_cmd = 22;
+
+ repeated ext_mount_map ext_mnt = 23;
+ optional bool manage_cgroups = 24; /* backward compatibility */
+ repeated cgroup_root cg_root = 25;
+
+ optional bool rst_sibling = 26; /* swrk only */
+ repeated inherit_fd inherit_fd = 27; /* swrk only */
+
+ optional bool auto_ext_mnt = 28;
+ optional bool ext_sharing = 29;
+ optional bool ext_masters = 30;
+
+ repeated string skip_mnt = 31;
+ repeated string enable_fs = 32;
+
+ repeated unix_sk unix_sk_ino = 33;
+
+ optional criu_cg_mode manage_cgroups_mode = 34;
+ optional uint32 ghost_limit = 35 [default = 0x100000];
+ repeated string irmap_scan_paths = 36;
+ repeated string external = 37;
+ optional uint32 empty_ns = 38;
+ optional bool no_seccomp = 39;
+}
+
+message criu_dump_resp {
+ optional bool restored = 1;
+}
+
+message criu_restore_resp {
+ required int32 pid = 1;
+}
+
+message criu_notify {
+ optional string script = 1;
+ optional int32 pid = 2;
+}
+
+enum criu_req_type {
+ EMPTY = 0;
+ DUMP = 1;
+ RESTORE = 2;
+ CHECK = 3;
+ PRE_DUMP = 4;
+ PAGE_SERVER = 5;
+
+ NOTIFY = 6;
+
+ CPUINFO_DUMP = 7;
+ CPUINFO_CHECK = 8;
+
+ FEATURE_CHECK = 9;
+}
+
+/*
+ * List of features which can queried via
+ * CRIU_REQ_TYPE__FEATURE_CHECK
+ */
+message criu_features {
+ optional bool mem_track = 1;
+}
+
+/*
+ * Request -- each type corresponds to must-be-there
+ * request arguments of respective type
+ */
+
+message criu_req {
+ required criu_req_type type = 1;
+
+ optional criu_opts opts = 2;
+ optional bool notify_success = 3;
+
+ /*
+ * When set service won't close the connection but
+ * will wait for more req-s to appear. Works not
+ * for all request types.
+ */
+ optional bool keep_open = 4;
+ /*
+ * 'features' can be used to query which features
+ * are supported by the installed criu/kernel
+ * via RPC.
+ */
+ optional criu_features features = 5;
+}
+
+/*
+ * Response -- it states whether the request was served
+ * and additional request-specific information
+ */
+
+message criu_resp {
+ required criu_req_type type = 1;
+ required bool success = 2;
+
+ optional criu_dump_resp dump = 3;
+ optional criu_restore_resp restore = 4;
+ optional criu_notify notify = 5;
+ optional criu_page_server_info ps = 6;
+
+ optional int32 cr_errno = 7;
+ optional criu_features features = 8;
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unix.go
new file mode 100644
index 0000000..f44e62c
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unix.go
@@ -0,0 +1,106 @@
+// +build linux freebsd
+
+package devices
+
+import (
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "syscall"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+var (
+ ErrNotADevice = errors.New("not a device node")
+)
+
+// Testing dependencies
+var (
+ osLstat = os.Lstat
+ ioutilReadDir = ioutil.ReadDir
+)
+
+// Given the path to a device and its cgroup_permissions(which cannot be easily queried) look up the information about a linux device and return that information as a Device struct.
+func DeviceFromPath(path, permissions string) (*configs.Device, error) {
+ fileInfo, err := osLstat(path)
+ if err != nil {
+ return nil, err
+ }
+ var (
+ devType rune
+ mode = fileInfo.Mode()
+ fileModePermissionBits = os.FileMode.Perm(mode)
+ )
+ switch {
+ case mode&os.ModeDevice == 0:
+ return nil, ErrNotADevice
+ case mode&os.ModeCharDevice != 0:
+ fileModePermissionBits |= syscall.S_IFCHR
+ devType = 'c'
+ default:
+ fileModePermissionBits |= syscall.S_IFBLK
+ devType = 'b'
+ }
+ stat_t, ok := fileInfo.Sys().(*syscall.Stat_t)
+ if !ok {
+ return nil, fmt.Errorf("cannot determine the device number for device %s", path)
+ }
+ devNumber := int(stat_t.Rdev)
+ return &configs.Device{
+ Type: devType,
+ Path: path,
+ Major: Major(devNumber),
+ Minor: Minor(devNumber),
+ Permissions: permissions,
+ FileMode: fileModePermissionBits,
+ Uid: stat_t.Uid,
+ Gid: stat_t.Gid,
+ }, nil
+}
+
+func HostDevices() ([]*configs.Device, error) {
+ return getDevices("/dev")
+}
+
+func getDevices(path string) ([]*configs.Device, error) {
+ files, err := ioutilReadDir(path)
+ if err != nil {
+ return nil, err
+ }
+ out := []*configs.Device{}
+ for _, f := range files {
+ switch {
+ case f.IsDir():
+ switch f.Name() {
+ // ".lxc" & ".lxd-mounts" added to address https://github.com/lxc/lxd/issues/2825
+ case "pts", "shm", "fd", "mqueue", ".lxc", ".lxd-mounts":
+ continue
+ default:
+ sub, err := getDevices(filepath.Join(path, f.Name()))
+ if err != nil {
+ return nil, err
+ }
+
+ out = append(out, sub...)
+ continue
+ }
+ case f.Name() == "console":
+ continue
+ }
+ device, err := DeviceFromPath(filepath.Join(path, f.Name()), "rwm")
+ if err != nil {
+ if err == ErrNotADevice {
+ continue
+ }
+ if os.IsNotExist(err) {
+ continue
+ }
+ return nil, err
+ }
+ out = append(out, device)
+ }
+ return out, nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unsupported.go
new file mode 100644
index 0000000..1e84033
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unsupported.go
@@ -0,0 +1,3 @@
+// +build windows
+
+package devices
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/devices/number.go b/vendor/github.com/opencontainers/runc/libcontainer/devices/number.go
new file mode 100644
index 0000000..885b6e5
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/devices/number.go
@@ -0,0 +1,24 @@
+// +build linux freebsd
+
+package devices
+
+/*
+
+This code provides support for manipulating linux device numbers. It should be replaced by normal syscall functions once http://code.google.com/p/go/issues/detail?id=8106 is solved.
+
+You can read what they are here:
+
+ - http://www.makelinux.net/ldd3/chp-3-sect-2
+ - http://www.linux-tutorial.info/modules.php?name=MContent&pageid=94
+
+Note! These are NOT the same as the MAJOR(dev_t device);, MINOR(dev_t device); and MKDEV(int major, int minor); functions as defined in <linux/kdev_t.h> as the representation of device numbers used by go is different than the one used internally to the kernel! - https://github.com/torvalds/linux/blob/master/include/linux/kdev_t.h#L9
+
+*/
+
+func Major(devNumber int) int64 {
+ return int64((devNumber >> 8) & 0xfff)
+}
+
+func Minor(devNumber int) int64 {
+ return int64((devNumber & 0xff) | ((devNumber >> 12) & 0xfff00))
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/error.go b/vendor/github.com/opencontainers/runc/libcontainer/error.go
new file mode 100644
index 0000000..21a3789
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/error.go
@@ -0,0 +1,70 @@
+package libcontainer
+
+import "io"
+
+// ErrorCode is the API error code type.
+type ErrorCode int
+
+// API error codes.
+const (
+ // Factory errors
+ IdInUse ErrorCode = iota
+ InvalidIdFormat
+
+ // Container errors
+ ContainerNotExists
+ ContainerPaused
+ ContainerNotStopped
+ ContainerNotRunning
+ ContainerNotPaused
+
+ // Process errors
+ NoProcessOps
+
+ // Common errors
+ ConfigInvalid
+ ConsoleExists
+ SystemError
+)
+
+func (c ErrorCode) String() string {
+ switch c {
+ case IdInUse:
+ return "Id already in use"
+ case InvalidIdFormat:
+ return "Invalid format"
+ case ContainerPaused:
+ return "Container paused"
+ case ConfigInvalid:
+ return "Invalid configuration"
+ case SystemError:
+ return "System error"
+ case ContainerNotExists:
+ return "Container does not exist"
+ case ContainerNotStopped:
+ return "Container is not stopped"
+ case ContainerNotRunning:
+ return "Container is not running"
+ case ConsoleExists:
+ return "Console exists for process"
+ case ContainerNotPaused:
+ return "Container is not paused"
+ case NoProcessOps:
+ return "No process operations"
+ default:
+ return "Unknown error"
+ }
+}
+
+// Error is the API error type.
+type Error interface {
+ error
+
+ // Returns an error if it failed to write the detail of the Error to w.
+ // The detail of the Error may include the error message and a
+ // representation of the stack trace.
+ Detail(w io.Writer) error
+
+ // Returns the error code for this error.
+ Code() ErrorCode
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/factory.go b/vendor/github.com/opencontainers/runc/libcontainer/factory.go
new file mode 100644
index 0000000..0986cd7
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/factory.go
@@ -0,0 +1,44 @@
+package libcontainer
+
+import (
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type Factory interface {
+ // Creates a new container with the given id and starts the initial process inside it.
+ // id must be a string containing only letters, digits and underscores and must contain
+ // between 1 and 1024 characters, inclusive.
+ //
+ // The id must not already be in use by an existing container. Containers created using
+ // a factory with the same path (and filesystem) must have distinct ids.
+ //
+ // Returns the new container with a running process.
+ //
+ // errors:
+ // IdInUse - id is already in use by a container
+ // InvalidIdFormat - id has incorrect format
+ // ConfigInvalid - config is invalid
+ // Systemerror - System error
+ //
+ // On error, any partially created container parts are cleaned up (the operation is atomic).
+ Create(id string, config *configs.Config) (Container, error)
+
+ // Load takes an ID for an existing container and returns the container information
+ // from the state. This presents a read only view of the container.
+ //
+ // errors:
+ // Path does not exist
+ // System error
+ Load(id string) (Container, error)
+
+ // StartInitialization is an internal API to libcontainer used during the reexec of the
+ // container.
+ //
+ // Errors:
+ // Pipe connection error
+ // System error
+ StartInitialization() error
+
+ // Type returns info string about factory type (e.g. lxc, libcontainer...)
+ Type() string
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go
new file mode 100644
index 0000000..362d26b
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go
@@ -0,0 +1,344 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "runtime/debug"
+ "strconv"
+ "syscall"
+
+ "github.com/docker/docker/pkg/mount"
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/cgroups/fs"
+ "github.com/opencontainers/runc/libcontainer/cgroups/rootless"
+ "github.com/opencontainers/runc/libcontainer/cgroups/systemd"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/configs/validate"
+ "github.com/opencontainers/runc/libcontainer/utils"
+)
+
+const (
+ stateFilename = "state.json"
+ execFifoFilename = "exec.fifo"
+)
+
+var (
+ idRegex = regexp.MustCompile(`^[\w+-\.]+$`)
+ maxIdLen = 1024
+)
+
+// InitArgs returns an options func to configure a LinuxFactory with the
+// provided init binary path and arguments.
+func InitArgs(args ...string) func(*LinuxFactory) error {
+ return func(l *LinuxFactory) (err error) {
+ if len(args) > 0 {
+ // Resolve relative paths to ensure that its available
+ // after directory changes.
+ if args[0], err = filepath.Abs(args[0]); err != nil {
+ return newGenericError(err, ConfigInvalid)
+ }
+ }
+
+ l.InitArgs = args
+ return nil
+ }
+}
+
+// SystemdCgroups is an options func to configure a LinuxFactory to return
+// containers that use systemd to create and manage cgroups.
+func SystemdCgroups(l *LinuxFactory) error {
+ l.NewCgroupsManager = func(config *configs.Cgroup, paths map[string]string) cgroups.Manager {
+ return &systemd.Manager{
+ Cgroups: config,
+ Paths: paths,
+ }
+ }
+ return nil
+}
+
+// Cgroupfs is an options func to configure a LinuxFactory to return
+// containers that use the native cgroups filesystem implementation to
+// create and manage cgroups.
+func Cgroupfs(l *LinuxFactory) error {
+ l.NewCgroupsManager = func(config *configs.Cgroup, paths map[string]string) cgroups.Manager {
+ return &fs.Manager{
+ Cgroups: config,
+ Paths: paths,
+ }
+ }
+ return nil
+}
+
+// RootlessCgroups is an options func to configure a LinuxFactory to
+// return containers that use the "rootless" cgroup manager, which will
+// fail to do any operations not possible to do with an unprivileged user.
+// It should only be used in conjunction with rootless containers.
+func RootlessCgroups(l *LinuxFactory) error {
+ l.NewCgroupsManager = func(config *configs.Cgroup, paths map[string]string) cgroups.Manager {
+ return &rootless.Manager{
+ Cgroups: config,
+ Paths: paths,
+ }
+ }
+ return nil
+}
+
+// TmpfsRoot is an option func to mount LinuxFactory.Root to tmpfs.
+func TmpfsRoot(l *LinuxFactory) error {
+ mounted, err := mount.Mounted(l.Root)
+ if err != nil {
+ return err
+ }
+ if !mounted {
+ if err := syscall.Mount("tmpfs", l.Root, "tmpfs", 0, ""); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// CriuPath returns an option func to configure a LinuxFactory with the
+// provided criupath
+func CriuPath(criupath string) func(*LinuxFactory) error {
+ return func(l *LinuxFactory) error {
+ l.CriuPath = criupath
+ return nil
+ }
+}
+
+// New returns a linux based container factory based in the root directory and
+// configures the factory with the provided option funcs.
+func New(root string, options ...func(*LinuxFactory) error) (Factory, error) {
+ if root != "" {
+ if err := os.MkdirAll(root, 0700); err != nil {
+ return nil, newGenericError(err, SystemError)
+ }
+ }
+ l := &LinuxFactory{
+ Root: root,
+ InitPath: "/proc/self/exe",
+ InitArgs: []string{os.Args[0], "init"},
+ Validator: validate.New(),
+ CriuPath: "criu",
+ }
+ Cgroupfs(l)
+ for _, opt := range options {
+ if err := opt(l); err != nil {
+ return nil, err
+ }
+ }
+ return l, nil
+}
+
+// LinuxFactory implements the default factory interface for linux based systems.
+type LinuxFactory struct {
+ // Root directory for the factory to store state.
+ Root string
+
+ // InitPath is the path for calling the init responsibilities for spawning
+ // a container.
+ InitPath string
+
+ // InitArgs are arguments for calling the init responsibilities for spawning
+ // a container.
+ InitArgs []string
+
+ // CriuPath is the path to the criu binary used for checkpoint and restore of
+ // containers.
+ CriuPath string
+
+ // Validator provides validation to container configurations.
+ Validator validate.Validator
+
+ // NewCgroupsManager returns an initialized cgroups manager for a single container.
+ NewCgroupsManager func(config *configs.Cgroup, paths map[string]string) cgroups.Manager
+}
+
+func (l *LinuxFactory) Create(id string, config *configs.Config) (Container, error) {
+ if l.Root == "" {
+ return nil, newGenericError(fmt.Errorf("invalid root"), ConfigInvalid)
+ }
+ if err := l.validateID(id); err != nil {
+ return nil, err
+ }
+ if err := l.Validator.Validate(config); err != nil {
+ return nil, newGenericError(err, ConfigInvalid)
+ }
+ uid, err := config.HostRootUID()
+ if err != nil {
+ return nil, newGenericError(err, SystemError)
+ }
+ gid, err := config.HostRootGID()
+ if err != nil {
+ return nil, newGenericError(err, SystemError)
+ }
+ containerRoot := filepath.Join(l.Root, id)
+ if _, err := os.Stat(containerRoot); err == nil {
+ return nil, newGenericError(fmt.Errorf("container with id exists: %v", id), IdInUse)
+ } else if !os.IsNotExist(err) {
+ return nil, newGenericError(err, SystemError)
+ }
+ if err := os.MkdirAll(containerRoot, 0711); err != nil {
+ return nil, newGenericError(err, SystemError)
+ }
+ if err := os.Chown(containerRoot, uid, gid); err != nil {
+ return nil, newGenericError(err, SystemError)
+ }
+ if config.Rootless {
+ RootlessCgroups(l)
+ }
+ c := &linuxContainer{
+ id: id,
+ root: containerRoot,
+ config: config,
+ initPath: l.InitPath,
+ initArgs: l.InitArgs,
+ criuPath: l.CriuPath,
+ cgroupManager: l.NewCgroupsManager(config.Cgroups, nil),
+ }
+ c.state = &stoppedState{c: c}
+ return c, nil
+}
+
+func (l *LinuxFactory) Load(id string) (Container, error) {
+ if l.Root == "" {
+ return nil, newGenericError(fmt.Errorf("invalid root"), ConfigInvalid)
+ }
+ containerRoot := filepath.Join(l.Root, id)
+ state, err := l.loadState(containerRoot, id)
+ if err != nil {
+ return nil, err
+ }
+ r := &nonChildProcess{
+ processPid: state.InitProcessPid,
+ processStartTime: state.InitProcessStartTime,
+ fds: state.ExternalDescriptors,
+ }
+ // We have to use the RootlessManager.
+ if state.Rootless {
+ RootlessCgroups(l)
+ }
+ c := &linuxContainer{
+ initProcess: r,
+ initProcessStartTime: state.InitProcessStartTime,
+ id: id,
+ config: &state.Config,
+ initPath: l.InitPath,
+ initArgs: l.InitArgs,
+ criuPath: l.CriuPath,
+ cgroupManager: l.NewCgroupsManager(state.Config.Cgroups, state.CgroupPaths),
+ root: containerRoot,
+ created: state.Created,
+ }
+ c.state = &loadedState{c: c}
+ if err := c.refreshState(); err != nil {
+ return nil, err
+ }
+ return c, nil
+}
+
+func (l *LinuxFactory) Type() string {
+ return "libcontainer"
+}
+
+// StartInitialization loads a container by opening the pipe fd from the parent to read the configuration and state
+// This is a low level implementation detail of the reexec and should not be consumed externally
+func (l *LinuxFactory) StartInitialization() (err error) {
+ var (
+ pipefd, rootfd int
+ consoleSocket *os.File
+ envInitPipe = os.Getenv("_LIBCONTAINER_INITPIPE")
+ envStateDir = os.Getenv("_LIBCONTAINER_STATEDIR")
+ envConsole = os.Getenv("_LIBCONTAINER_CONSOLE")
+ )
+
+ // Get the INITPIPE.
+ pipefd, err = strconv.Atoi(envInitPipe)
+ if err != nil {
+ return fmt.Errorf("unable to convert _LIBCONTAINER_INITPIPE=%s to int: %s", envInitPipe, err)
+ }
+
+ var (
+ pipe = os.NewFile(uintptr(pipefd), "pipe")
+ it = initType(os.Getenv("_LIBCONTAINER_INITTYPE"))
+ )
+ defer pipe.Close()
+
+ // Only init processes have STATEDIR.
+ rootfd = -1
+ if it == initStandard {
+ if rootfd, err = strconv.Atoi(envStateDir); err != nil {
+ return fmt.Errorf("unable to convert _LIBCONTAINER_STATEDIR=%s to int: %s", envStateDir, err)
+ }
+ }
+
+ if envConsole != "" {
+ console, err := strconv.Atoi(envConsole)
+ if err != nil {
+ return fmt.Errorf("unable to convert _LIBCONTAINER_CONSOLE=%s to int: %s", envConsole, err)
+ }
+ consoleSocket = os.NewFile(uintptr(console), "console-socket")
+ defer consoleSocket.Close()
+ }
+
+ // clear the current process's environment to clean any libcontainer
+ // specific env vars.
+ os.Clearenv()
+
+ defer func() {
+ // We have an error during the initialization of the container's init,
+ // send it back to the parent process in the form of an initError.
+ if werr := utils.WriteJSON(pipe, syncT{procError}); werr != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return
+ }
+ if werr := utils.WriteJSON(pipe, newSystemError(err)); werr != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return
+ }
+ }()
+ defer func() {
+ if e := recover(); e != nil {
+ err = fmt.Errorf("panic from initialization: %v, %v", e, string(debug.Stack()))
+ }
+ }()
+
+ i, err := newContainerInit(it, pipe, consoleSocket, rootfd)
+ if err != nil {
+ return err
+ }
+
+ // If Init succeeds, syscall.Exec will not return, hence none of the defers will be called.
+ return i.Init()
+}
+
+func (l *LinuxFactory) loadState(root, id string) (*State, error) {
+ f, err := os.Open(filepath.Join(root, stateFilename))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, newGenericError(fmt.Errorf("container %q does not exist", id), ContainerNotExists)
+ }
+ return nil, newGenericError(err, SystemError)
+ }
+ defer f.Close()
+ var state *State
+ if err := json.NewDecoder(f).Decode(&state); err != nil {
+ return nil, newGenericError(err, SystemError)
+ }
+ return state, nil
+}
+
+func (l *LinuxFactory) validateID(id string) error {
+ if !idRegex.MatchString(id) {
+ return newGenericError(fmt.Errorf("invalid id format: %v", id), InvalidIdFormat)
+ }
+ if len(id) > maxIdLen {
+ return newGenericError(fmt.Errorf("invalid id format: %v", id), InvalidIdFormat)
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/generic_error.go b/vendor/github.com/opencontainers/runc/libcontainer/generic_error.go
new file mode 100644
index 0000000..6e7de2f
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/generic_error.go
@@ -0,0 +1,92 @@
+package libcontainer
+
+import (
+ "fmt"
+ "io"
+ "text/template"
+ "time"
+
+ "github.com/opencontainers/runc/libcontainer/stacktrace"
+)
+
+var errorTemplate = template.Must(template.New("error").Parse(`Timestamp: {{.Timestamp}}
+Code: {{.ECode}}
+{{if .Message }}
+Message: {{.Message}}
+{{end}}
+Frames:{{range $i, $frame := .Stack.Frames}}
+---
+{{$i}}: {{$frame.Function}}
+Package: {{$frame.Package}}
+File: {{$frame.File}}@{{$frame.Line}}{{end}}
+`))
+
+func newGenericError(err error, c ErrorCode) Error {
+ if le, ok := err.(Error); ok {
+ return le
+ }
+ gerr := &genericError{
+ Timestamp: time.Now(),
+ Err: err,
+ ECode: c,
+ Stack: stacktrace.Capture(1),
+ }
+ if err != nil {
+ gerr.Message = err.Error()
+ }
+ return gerr
+}
+
+func newSystemError(err error) Error {
+ return createSystemError(err, "")
+}
+
+func newSystemErrorWithCausef(err error, cause string, v ...interface{}) Error {
+ return createSystemError(err, fmt.Sprintf(cause, v...))
+}
+
+func newSystemErrorWithCause(err error, cause string) Error {
+ return createSystemError(err, cause)
+}
+
+// createSystemError creates the specified error with the correct number of
+// stack frames skipped. This is only to be called by the other functions for
+// formatting the error.
+func createSystemError(err error, cause string) Error {
+ gerr := &genericError{
+ Timestamp: time.Now(),
+ Err: err,
+ ECode: SystemError,
+ Cause: cause,
+ Stack: stacktrace.Capture(2),
+ }
+ if err != nil {
+ gerr.Message = err.Error()
+ }
+ return gerr
+}
+
+type genericError struct {
+ Timestamp time.Time
+ ECode ErrorCode
+ Err error `json:"-"`
+ Cause string
+ Message string
+ Stack stacktrace.Stacktrace
+}
+
+func (e *genericError) Error() string {
+ if e.Cause == "" {
+ return e.Message
+ }
+ frame := e.Stack.Frames[0]
+ return fmt.Sprintf("%s:%d: %s caused %q", frame.File, frame.Line, e.Cause, e.Message)
+}
+
+func (e *genericError) Code() ErrorCode {
+ return e.ECode
+}
+
+func (e *genericError) Detail(w io.Writer) error {
+ return errorTemplate.Execute(w, e)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/init_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/init_linux.go
new file mode 100644
index 0000000..99cc02c
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/init_linux.go
@@ -0,0 +1,500 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "strings"
+ "syscall"
+ "unsafe"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/system"
+ "github.com/opencontainers/runc/libcontainer/user"
+ "github.com/opencontainers/runc/libcontainer/utils"
+ "github.com/vishvananda/netlink"
+)
+
+type initType string
+
+const (
+ initSetns initType = "setns"
+ initStandard initType = "standard"
+)
+
+type pid struct {
+ Pid int `json:"pid"`
+}
+
+// network is an internal struct used to setup container networks.
+type network struct {
+ configs.Network
+
+ // TempVethPeerName is a unique temporary veth peer name that was placed into
+ // the container's namespace.
+ TempVethPeerName string `json:"temp_veth_peer_name"`
+}
+
+// initConfig is used for transferring parameters from Exec() to Init()
+type initConfig struct {
+ Args []string `json:"args"`
+ Env []string `json:"env"`
+ Cwd string `json:"cwd"`
+ Capabilities *configs.Capabilities `json:"capabilities"`
+ ProcessLabel string `json:"process_label"`
+ AppArmorProfile string `json:"apparmor_profile"`
+ NoNewPrivileges bool `json:"no_new_privileges"`
+ User string `json:"user"`
+ AdditionalGroups []string `json:"additional_groups"`
+ Config *configs.Config `json:"config"`
+ Networks []*network `json:"network"`
+ PassedFilesCount int `json:"passed_files_count"`
+ ContainerId string `json:"containerid"`
+ Rlimits []configs.Rlimit `json:"rlimits"`
+ CreateConsole bool `json:"create_console"`
+ Rootless bool `json:"rootless"`
+}
+
+type initer interface {
+ Init() error
+}
+
+func newContainerInit(t initType, pipe *os.File, consoleSocket *os.File, stateDirFD int) (initer, error) {
+ var config *initConfig
+ if err := json.NewDecoder(pipe).Decode(&config); err != nil {
+ return nil, err
+ }
+ if err := populateProcessEnvironment(config.Env); err != nil {
+ return nil, err
+ }
+ switch t {
+ case initSetns:
+ return &linuxSetnsInit{
+ pipe: pipe,
+ consoleSocket: consoleSocket,
+ config: config,
+ }, nil
+ case initStandard:
+ return &linuxStandardInit{
+ pipe: pipe,
+ consoleSocket: consoleSocket,
+ parentPid: syscall.Getppid(),
+ config: config,
+ stateDirFD: stateDirFD,
+ }, nil
+ }
+ return nil, fmt.Errorf("unknown init type %q", t)
+}
+
+// populateProcessEnvironment loads the provided environment variables into the
+// current processes's environment.
+func populateProcessEnvironment(env []string) error {
+ for _, pair := range env {
+ p := strings.SplitN(pair, "=", 2)
+ if len(p) < 2 {
+ return fmt.Errorf("invalid environment '%v'", pair)
+ }
+ if err := os.Setenv(p[0], p[1]); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// finalizeNamespace drops the caps, sets the correct user
+// and working dir, and closes any leaked file descriptors
+// before executing the command inside the namespace
+func finalizeNamespace(config *initConfig) error {
+ // Ensure that all unwanted fds we may have accidentally
+ // inherited are marked close-on-exec so they stay out of the
+ // container
+ if err := utils.CloseExecFrom(config.PassedFilesCount + 3); err != nil {
+ return err
+ }
+
+ capabilities := &configs.Capabilities{}
+ if config.Capabilities != nil {
+ capabilities = config.Capabilities
+ } else if config.Config.Capabilities != nil {
+ capabilities = config.Config.Capabilities
+ }
+ w, err := newContainerCapList(capabilities)
+ if err != nil {
+ return err
+ }
+ // drop capabilities in bounding set before changing user
+ if err := w.ApplyBoundingSet(); err != nil {
+ return err
+ }
+ // preserve existing capabilities while we change users
+ if err := system.SetKeepCaps(); err != nil {
+ return err
+ }
+ if err := setupUser(config); err != nil {
+ return err
+ }
+ if err := system.ClearKeepCaps(); err != nil {
+ return err
+ }
+ if err := w.ApplyCaps(); err != nil {
+ return err
+ }
+ if config.Cwd != "" {
+ if err := syscall.Chdir(config.Cwd); err != nil {
+ return fmt.Errorf("chdir to cwd (%q) set in config.json failed: %v", config.Cwd, err)
+ }
+ }
+ return nil
+}
+
+// setupConsole sets up the console from inside the container, and sends the
+// master pty fd to the config.Pipe (using cmsg). This is done to ensure that
+// consoles are scoped to a container properly (see runc#814 and the many
+// issues related to that). This has to be run *after* we've pivoted to the new
+// rootfs (and the users' configuration is entirely set up).
+func setupConsole(socket *os.File, config *initConfig, mount bool) error {
+ defer socket.Close()
+ // At this point, /dev/ptmx points to something that we would expect. We
+ // used to change the owner of the slave path, but since the /dev/pts mount
+ // can have gid=X set (at the users' option). So touching the owner of the
+ // slave PTY is not necessary, as the kernel will handle that for us. Note
+ // however, that setupUser (specifically fixStdioPermissions) *will* change
+ // the UID owner of the console to be the user the process will run as (so
+ // they can actually control their console).
+ console, err := newConsole()
+ if err != nil {
+ return err
+ }
+ // After we return from here, we don't need the console anymore.
+ defer console.Close()
+
+ linuxConsole, ok := console.(*linuxConsole)
+ if !ok {
+ return fmt.Errorf("failed to cast console to *linuxConsole")
+ }
+ // Mount the console inside our rootfs.
+ if mount {
+ if err := linuxConsole.mount(); err != nil {
+ return err
+ }
+ }
+ // While we can access console.master, using the API is a good idea.
+ if err := utils.SendFd(socket, linuxConsole.File()); err != nil {
+ return err
+ }
+ // Now, dup over all the things.
+ return linuxConsole.dupStdio()
+}
+
+// syncParentReady sends to the given pipe a JSON payload which indicates that
+// the init is ready to Exec the child process. It then waits for the parent to
+// indicate that it is cleared to Exec.
+func syncParentReady(pipe io.ReadWriter) error {
+ // Tell parent.
+ if err := writeSync(pipe, procReady); err != nil {
+ return err
+ }
+
+ // Wait for parent to give the all-clear.
+ if err := readSync(pipe, procRun); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// syncParentHooks sends to the given pipe a JSON payload which indicates that
+// the parent should execute pre-start hooks. It then waits for the parent to
+// indicate that it is cleared to resume.
+func syncParentHooks(pipe io.ReadWriter) error {
+ // Tell parent.
+ if err := writeSync(pipe, procHooks); err != nil {
+ return err
+ }
+
+ // Wait for parent to give the all-clear.
+ if err := readSync(pipe, procResume); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// setupUser changes the groups, gid, and uid for the user inside the container
+func setupUser(config *initConfig) error {
+ // Set up defaults.
+ defaultExecUser := user.ExecUser{
+ Uid: 0,
+ Gid: 0,
+ Home: "/",
+ }
+
+ passwdPath, err := user.GetPasswdPath()
+ if err != nil {
+ return err
+ }
+
+ groupPath, err := user.GetGroupPath()
+ if err != nil {
+ return err
+ }
+
+ execUser, err := user.GetExecUserPath(config.User, &defaultExecUser, passwdPath, groupPath)
+ if err != nil {
+ return err
+ }
+
+ var addGroups []int
+ if len(config.AdditionalGroups) > 0 {
+ addGroups, err = user.GetAdditionalGroupsPath(config.AdditionalGroups, groupPath)
+ if err != nil {
+ return err
+ }
+ }
+
+ if config.Rootless {
+ if execUser.Uid != 0 {
+ return fmt.Errorf("cannot run as a non-root user in a rootless container")
+ }
+
+ if execUser.Gid != 0 {
+ return fmt.Errorf("cannot run as a non-root group in a rootless container")
+ }
+
+ // We cannot set any additional groups in a rootless container and thus we
+ // bail if the user asked us to do so. TODO: We currently can't do this
+ // earlier, but if libcontainer.Process.User was typesafe this might work.
+ if len(addGroups) > 0 {
+ return fmt.Errorf("cannot set any additional groups in a rootless container")
+ }
+ }
+
+ // before we change to the container's user make sure that the processes STDIO
+ // is correctly owned by the user that we are switching to.
+ if err := fixStdioPermissions(config, execUser); err != nil {
+ return err
+ }
+
+ // This isn't allowed in an unprivileged user namespace since Linux 3.19.
+ // There's nothing we can do about /etc/group entries, so we silently
+ // ignore setting groups here (since the user didn't explicitly ask us to
+ // set the group).
+ if !config.Rootless {
+ suppGroups := append(execUser.Sgids, addGroups...)
+ if err := syscall.Setgroups(suppGroups); err != nil {
+ return err
+ }
+ }
+
+ if err := system.Setgid(execUser.Gid); err != nil {
+ return err
+ }
+
+ if err := system.Setuid(execUser.Uid); err != nil {
+ return err
+ }
+
+ // if we didn't get HOME already, set it based on the user's HOME
+ if envHome := os.Getenv("HOME"); envHome == "" {
+ if err := os.Setenv("HOME", execUser.Home); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// fixStdioPermissions fixes the permissions of PID 1's STDIO within the container to the specified user.
+// The ownership needs to match because it is created outside of the container and needs to be
+// localized.
+func fixStdioPermissions(config *initConfig, u *user.ExecUser) error {
+ var null syscall.Stat_t
+ if err := syscall.Stat("/dev/null", &null); err != nil {
+ return err
+ }
+ for _, fd := range []uintptr{
+ os.Stdin.Fd(),
+ os.Stderr.Fd(),
+ os.Stdout.Fd(),
+ } {
+ var s syscall.Stat_t
+ if err := syscall.Fstat(int(fd), &s); err != nil {
+ return err
+ }
+
+ // Skip chown of /dev/null if it was used as one of the STDIO fds.
+ if s.Rdev == null.Rdev {
+ continue
+ }
+
+ // Skip chown if s.Gid is actually an unmapped gid in the host. While
+ // this is a bit dodgy if it just so happens that the console _is_
+ // owned by overflow_gid, there's no way for us to disambiguate this as
+ // a userspace program.
+ if _, err := config.Config.HostGID(int(s.Gid)); err != nil {
+ continue
+ }
+
+ // We only change the uid owner (as it is possible for the mount to
+ // prefer a different gid, and there's no reason for us to change it).
+ // The reason why we don't just leave the default uid=X mount setup is
+ // that users expect to be able to actually use their console. Without
+ // this code, you couldn't effectively run as a non-root user inside a
+ // container and also have a console set up.
+ if err := syscall.Fchown(int(fd), u.Uid, int(s.Gid)); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// setupNetwork sets up and initializes any network interface inside the container.
+func setupNetwork(config *initConfig) error {
+ for _, config := range config.Networks {
+ strategy, err := getStrategy(config.Type)
+ if err != nil {
+ return err
+ }
+ if err := strategy.initialize(config); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func setupRoute(config *configs.Config) error {
+ for _, config := range config.Routes {
+ _, dst, err := net.ParseCIDR(config.Destination)
+ if err != nil {
+ return err
+ }
+ src := net.ParseIP(config.Source)
+ if src == nil {
+ return fmt.Errorf("Invalid source for route: %s", config.Source)
+ }
+ gw := net.ParseIP(config.Gateway)
+ if gw == nil {
+ return fmt.Errorf("Invalid gateway for route: %s", config.Gateway)
+ }
+ l, err := netlink.LinkByName(config.InterfaceName)
+ if err != nil {
+ return err
+ }
+ route := &netlink.Route{
+ Scope: netlink.SCOPE_UNIVERSE,
+ Dst: dst,
+ Src: src,
+ Gw: gw,
+ LinkIndex: l.Attrs().Index,
+ }
+ if err := netlink.RouteAdd(route); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func setupRlimits(limits []configs.Rlimit, pid int) error {
+ for _, rlimit := range limits {
+ if err := system.Prlimit(pid, rlimit.Type, syscall.Rlimit{Max: rlimit.Hard, Cur: rlimit.Soft}); err != nil {
+ return fmt.Errorf("error setting rlimit type %v: %v", rlimit.Type, err)
+ }
+ }
+ return nil
+}
+
+const _P_PID = 1
+
+type siginfo struct {
+ si_signo int32
+ si_errno int32
+ si_code int32
+ // below here is a union; si_pid is the only field we use
+ si_pid int32
+ // Pad to 128 bytes as detailed in blockUntilWaitable
+ pad [96]byte
+}
+
+// isWaitable returns true if the process has exited false otherwise.
+// Its based off blockUntilWaitable in src/os/wait_waitid.go
+func isWaitable(pid int) (bool, error) {
+ si := &siginfo{}
+ _, _, e := syscall.Syscall6(syscall.SYS_WAITID, _P_PID, uintptr(pid), uintptr(unsafe.Pointer(si)), syscall.WEXITED|syscall.WNOWAIT|syscall.WNOHANG, 0, 0)
+ if e != 0 {
+ return false, os.NewSyscallError("waitid", e)
+ }
+
+ return si.si_pid != 0, nil
+}
+
+// isNoChildren returns true if err represents a syscall.ECHILD false otherwise
+func isNoChildren(err error) bool {
+ switch err := err.(type) {
+ case syscall.Errno:
+ if err == syscall.ECHILD {
+ return true
+ }
+ case *os.SyscallError:
+ if err.Err == syscall.ECHILD {
+ return true
+ }
+ }
+ return false
+}
+
+// signalAllProcesses freezes then iterates over all the processes inside the
+// manager's cgroups sending the signal s to them.
+// If s is SIGKILL then it will wait for each process to exit.
+// For all other signals it will check if the process is ready to report its
+// exit status and only if it is will a wait be performed.
+func signalAllProcesses(m cgroups.Manager, s os.Signal) error {
+ var procs []*os.Process
+ if err := m.Freeze(configs.Frozen); err != nil {
+ logrus.Warn(err)
+ }
+ pids, err := m.GetAllPids()
+ if err != nil {
+ m.Freeze(configs.Thawed)
+ return err
+ }
+ for _, pid := range pids {
+ p, err := os.FindProcess(pid)
+ if err != nil {
+ logrus.Warn(err)
+ continue
+ }
+ procs = append(procs, p)
+ if err := p.Signal(s); err != nil {
+ logrus.Warn(err)
+ }
+ }
+ if err := m.Freeze(configs.Thawed); err != nil {
+ logrus.Warn(err)
+ }
+
+ for _, p := range procs {
+ if s != syscall.SIGKILL {
+ if ok, err := isWaitable(p.Pid); err != nil {
+ if !isNoChildren(err) {
+ logrus.Warn("signalAllProcesses: ", p.Pid, err)
+ }
+ continue
+ } else if !ok {
+ // Not ready to report so don't wait
+ continue
+ }
+ }
+
+ if _, err := p.Wait(); err != nil {
+ if !isNoChildren(err) {
+ logrus.Warn("wait: ", err)
+ }
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/keys/keyctl.go b/vendor/github.com/opencontainers/runc/libcontainer/keys/keyctl.go
new file mode 100644
index 0000000..8c90e56
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/keys/keyctl.go
@@ -0,0 +1,66 @@
+// +build linux
+
+package keys
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+ "syscall"
+ "unsafe"
+)
+
+const KEYCTL_JOIN_SESSION_KEYRING = 1
+const KEYCTL_SETPERM = 5
+const KEYCTL_DESCRIBE = 6
+
+type KeySerial uint32
+
+func JoinSessionKeyring(name string) (KeySerial, error) {
+ var _name *byte
+ var err error
+
+ if len(name) > 0 {
+ _name, err = syscall.BytePtrFromString(name)
+ if err != nil {
+ return KeySerial(0), err
+ }
+ }
+
+ sessKeyId, _, errn := syscall.Syscall(syscall.SYS_KEYCTL, KEYCTL_JOIN_SESSION_KEYRING, uintptr(unsafe.Pointer(_name)), 0)
+ if errn != 0 {
+ return 0, fmt.Errorf("could not create session key: %v", errn)
+ }
+ return KeySerial(sessKeyId), nil
+}
+
+// ModKeyringPerm modifies permissions on a keyring by reading the current permissions,
+// anding the bits with the given mask (clearing permissions) and setting
+// additional permission bits
+func ModKeyringPerm(ringId KeySerial, mask, setbits uint32) error {
+ dest := make([]byte, 1024)
+ destBytes := unsafe.Pointer(&dest[0])
+
+ if _, _, err := syscall.Syscall6(syscall.SYS_KEYCTL, uintptr(KEYCTL_DESCRIBE), uintptr(ringId), uintptr(destBytes), uintptr(len(dest)), 0, 0); err != 0 {
+ return err
+ }
+
+ res := strings.Split(string(dest), ";")
+ if len(res) < 5 {
+ return fmt.Errorf("Destination buffer for key description is too small")
+ }
+
+ // parse permissions
+ perm64, err := strconv.ParseUint(res[3], 16, 32)
+ if err != nil {
+ return err
+ }
+
+ perm := (uint32(perm64) & mask) | setbits
+
+ if _, _, err := syscall.Syscall(syscall.SYS_KEYCTL, uintptr(KEYCTL_SETPERM), uintptr(ringId), uintptr(perm)); err != 0 {
+ return err
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/message_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/message_linux.go
new file mode 100644
index 0000000..bc725a2
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/message_linux.go
@@ -0,0 +1,91 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// list of known message types we want to send to bootstrap program
+// The number is randomly chosen to not conflict with known netlink types
+const (
+ InitMsg uint16 = 62000
+ CloneFlagsAttr uint16 = 27281
+ NsPathsAttr uint16 = 27282
+ UidmapAttr uint16 = 27283
+ GidmapAttr uint16 = 27284
+ SetgroupAttr uint16 = 27285
+ OomScoreAdjAttr uint16 = 27286
+ RootlessAttr uint16 = 27287
+
+ // When syscall.NLA_HDRLEN is in gccgo, take this out.
+ syscall_NLA_HDRLEN = (syscall.SizeofNlAttr + syscall.NLA_ALIGNTO - 1) & ^(syscall.NLA_ALIGNTO - 1)
+)
+
+type Int32msg struct {
+ Type uint16
+ Value uint32
+}
+
+// Serialize serializes the message.
+// Int32msg has the following representation
+// | nlattr len | nlattr type |
+// | uint32 value |
+func (msg *Int32msg) Serialize() []byte {
+ buf := make([]byte, msg.Len())
+ native := nl.NativeEndian()
+ native.PutUint16(buf[0:2], uint16(msg.Len()))
+ native.PutUint16(buf[2:4], msg.Type)
+ native.PutUint32(buf[4:8], msg.Value)
+ return buf
+}
+
+func (msg *Int32msg) Len() int {
+ return syscall_NLA_HDRLEN + 4
+}
+
+// Bytemsg has the following representation
+// | nlattr len | nlattr type |
+// | value | pad |
+type Bytemsg struct {
+ Type uint16
+ Value []byte
+}
+
+func (msg *Bytemsg) Serialize() []byte {
+ l := msg.Len()
+ buf := make([]byte, (l+syscall.NLA_ALIGNTO-1) & ^(syscall.NLA_ALIGNTO-1))
+ native := nl.NativeEndian()
+ native.PutUint16(buf[0:2], uint16(l))
+ native.PutUint16(buf[2:4], msg.Type)
+ copy(buf[4:], msg.Value)
+ return buf
+}
+
+func (msg *Bytemsg) Len() int {
+ return syscall_NLA_HDRLEN + len(msg.Value) + 1 // null-terminated
+}
+
+type Boolmsg struct {
+ Type uint16
+ Value bool
+}
+
+func (msg *Boolmsg) Serialize() []byte {
+ buf := make([]byte, msg.Len())
+ native := nl.NativeEndian()
+ native.PutUint16(buf[0:2], uint16(msg.Len()))
+ native.PutUint16(buf[2:4], msg.Type)
+ if msg.Value {
+ buf[4] = 1
+ } else {
+ buf[4] = 0
+ }
+ return buf
+}
+
+func (msg *Boolmsg) Len() int {
+ return syscall_NLA_HDRLEN + 1
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/network_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/network_linux.go
new file mode 100644
index 0000000..5075bee
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/network_linux.go
@@ -0,0 +1,259 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "fmt"
+ "io/ioutil"
+ "net"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/utils"
+ "github.com/vishvananda/netlink"
+)
+
+var strategies = map[string]networkStrategy{
+ "veth": &veth{},
+ "loopback": &loopback{},
+}
+
+// networkStrategy represents a specific network configuration for
+// a container's networking stack
+type networkStrategy interface {
+ create(*network, int) error
+ initialize(*network) error
+ detach(*configs.Network) error
+ attach(*configs.Network) error
+}
+
+// getStrategy returns the specific network strategy for the
+// provided type.
+func getStrategy(tpe string) (networkStrategy, error) {
+ s, exists := strategies[tpe]
+ if !exists {
+ return nil, fmt.Errorf("unknown strategy type %q", tpe)
+ }
+ return s, nil
+}
+
+// Returns the network statistics for the network interfaces represented by the NetworkRuntimeInfo.
+func getNetworkInterfaceStats(interfaceName string) (*NetworkInterface, error) {
+ out := &NetworkInterface{Name: interfaceName}
+ // This can happen if the network runtime information is missing - possible if the
+ // container was created by an old version of libcontainer.
+ if interfaceName == "" {
+ return out, nil
+ }
+ type netStatsPair struct {
+ // Where to write the output.
+ Out *uint64
+ // The network stats file to read.
+ File string
+ }
+ // Ingress for host veth is from the container. Hence tx_bytes stat on the host veth is actually number of bytes received by the container.
+ netStats := []netStatsPair{
+ {Out: &out.RxBytes, File: "tx_bytes"},
+ {Out: &out.RxPackets, File: "tx_packets"},
+ {Out: &out.RxErrors, File: "tx_errors"},
+ {Out: &out.RxDropped, File: "tx_dropped"},
+
+ {Out: &out.TxBytes, File: "rx_bytes"},
+ {Out: &out.TxPackets, File: "rx_packets"},
+ {Out: &out.TxErrors, File: "rx_errors"},
+ {Out: &out.TxDropped, File: "rx_dropped"},
+ }
+ for _, netStat := range netStats {
+ data, err := readSysfsNetworkStats(interfaceName, netStat.File)
+ if err != nil {
+ return nil, err
+ }
+ *(netStat.Out) = data
+ }
+ return out, nil
+}
+
+// Reads the specified statistics available under /sys/class/net/<EthInterface>/statistics
+func readSysfsNetworkStats(ethInterface, statsFile string) (uint64, error) {
+ data, err := ioutil.ReadFile(filepath.Join("/sys/class/net", ethInterface, "statistics", statsFile))
+ if err != nil {
+ return 0, err
+ }
+ return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
+}
+
+// loopback is a network strategy that provides a basic loopback device
+type loopback struct {
+}
+
+func (l *loopback) create(n *network, nspid int) error {
+ return nil
+}
+
+func (l *loopback) initialize(config *network) error {
+ return netlink.LinkSetUp(&netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: "lo"}})
+}
+
+func (l *loopback) attach(n *configs.Network) (err error) {
+ return nil
+}
+
+func (l *loopback) detach(n *configs.Network) (err error) {
+ return nil
+}
+
+// veth is a network strategy that uses a bridge and creates
+// a veth pair, one that is attached to the bridge on the host and the other
+// is placed inside the container's namespace
+type veth struct {
+}
+
+func (v *veth) detach(n *configs.Network) (err error) {
+ return netlink.LinkSetMaster(&netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: n.HostInterfaceName}}, nil)
+}
+
+// attach a container network interface to an external network
+func (v *veth) attach(n *configs.Network) (err error) {
+ brl, err := netlink.LinkByName(n.Bridge)
+ if err != nil {
+ return err
+ }
+ br, ok := brl.(*netlink.Bridge)
+ if !ok {
+ return fmt.Errorf("Wrong device type %T", brl)
+ }
+ host, err := netlink.LinkByName(n.HostInterfaceName)
+ if err != nil {
+ return err
+ }
+
+ if err := netlink.LinkSetMaster(host, br); err != nil {
+ return err
+ }
+ if err := netlink.LinkSetMTU(host, n.Mtu); err != nil {
+ return err
+ }
+ if n.HairpinMode {
+ if err := netlink.LinkSetHairpin(host, true); err != nil {
+ return err
+ }
+ }
+ if err := netlink.LinkSetUp(host); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (v *veth) create(n *network, nspid int) (err error) {
+ tmpName, err := v.generateTempPeerName()
+ if err != nil {
+ return err
+ }
+ n.TempVethPeerName = tmpName
+ if n.Bridge == "" {
+ return fmt.Errorf("bridge is not specified")
+ }
+ veth := &netlink.Veth{
+ LinkAttrs: netlink.LinkAttrs{
+ Name: n.HostInterfaceName,
+ TxQLen: n.TxQueueLen,
+ },
+ PeerName: n.TempVethPeerName,
+ }
+ if err := netlink.LinkAdd(veth); err != nil {
+ return err
+ }
+ defer func() {
+ if err != nil {
+ netlink.LinkDel(veth)
+ }
+ }()
+ if err := v.attach(&n.Network); err != nil {
+ return err
+ }
+ child, err := netlink.LinkByName(n.TempVethPeerName)
+ if err != nil {
+ return err
+ }
+ return netlink.LinkSetNsPid(child, nspid)
+}
+
+func (v *veth) generateTempPeerName() (string, error) {
+ return utils.GenerateRandomName("veth", 7)
+}
+
+func (v *veth) initialize(config *network) error {
+ peer := config.TempVethPeerName
+ if peer == "" {
+ return fmt.Errorf("peer is not specified")
+ }
+ child, err := netlink.LinkByName(peer)
+ if err != nil {
+ return err
+ }
+ if err := netlink.LinkSetDown(child); err != nil {
+ return err
+ }
+ if err := netlink.LinkSetName(child, config.Name); err != nil {
+ return err
+ }
+ // get the interface again after we changed the name as the index also changes.
+ if child, err = netlink.LinkByName(config.Name); err != nil {
+ return err
+ }
+ if config.MacAddress != "" {
+ mac, err := net.ParseMAC(config.MacAddress)
+ if err != nil {
+ return err
+ }
+ if err := netlink.LinkSetHardwareAddr(child, mac); err != nil {
+ return err
+ }
+ }
+ ip, err := netlink.ParseAddr(config.Address)
+ if err != nil {
+ return err
+ }
+ if err := netlink.AddrAdd(child, ip); err != nil {
+ return err
+ }
+ if config.IPv6Address != "" {
+ ip6, err := netlink.ParseAddr(config.IPv6Address)
+ if err != nil {
+ return err
+ }
+ if err := netlink.AddrAdd(child, ip6); err != nil {
+ return err
+ }
+ }
+ if err := netlink.LinkSetMTU(child, config.Mtu); err != nil {
+ return err
+ }
+ if err := netlink.LinkSetUp(child); err != nil {
+ return err
+ }
+ if config.Gateway != "" {
+ gw := net.ParseIP(config.Gateway)
+ if err := netlink.RouteAdd(&netlink.Route{
+ Scope: netlink.SCOPE_UNIVERSE,
+ LinkIndex: child.Attrs().Index,
+ Gw: gw,
+ }); err != nil {
+ return err
+ }
+ }
+ if config.IPv6Gateway != "" {
+ gw := net.ParseIP(config.IPv6Gateway)
+ if err := netlink.RouteAdd(&netlink.Route{
+ Scope: netlink.SCOPE_UNIVERSE,
+ LinkIndex: child.Attrs().Index,
+ Gw: gw,
+ }); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/notify_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/notify_linux.go
new file mode 100644
index 0000000..839a50c
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/notify_linux.go
@@ -0,0 +1,89 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "syscall"
+)
+
+const oomCgroupName = "memory"
+
+type PressureLevel uint
+
+const (
+ LowPressure PressureLevel = iota
+ MediumPressure
+ CriticalPressure
+)
+
+func registerMemoryEvent(cgDir string, evName string, arg string) (<-chan struct{}, error) {
+ evFile, err := os.Open(filepath.Join(cgDir, evName))
+ if err != nil {
+ return nil, err
+ }
+ fd, _, syserr := syscall.RawSyscall(syscall.SYS_EVENTFD2, 0, syscall.FD_CLOEXEC, 0)
+ if syserr != 0 {
+ evFile.Close()
+ return nil, syserr
+ }
+
+ eventfd := os.NewFile(fd, "eventfd")
+
+ eventControlPath := filepath.Join(cgDir, "cgroup.event_control")
+ data := fmt.Sprintf("%d %d %s", eventfd.Fd(), evFile.Fd(), arg)
+ if err := ioutil.WriteFile(eventControlPath, []byte(data), 0700); err != nil {
+ eventfd.Close()
+ evFile.Close()
+ return nil, err
+ }
+ ch := make(chan struct{})
+ go func() {
+ defer func() {
+ close(ch)
+ eventfd.Close()
+ evFile.Close()
+ }()
+ buf := make([]byte, 8)
+ for {
+ if _, err := eventfd.Read(buf); err != nil {
+ return
+ }
+ // When a cgroup is destroyed, an event is sent to eventfd.
+ // So if the control path is gone, return instead of notifying.
+ if _, err := os.Lstat(eventControlPath); os.IsNotExist(err) {
+ return
+ }
+ ch <- struct{}{}
+ }
+ }()
+ return ch, nil
+}
+
+// notifyOnOOM returns channel on which you can expect event about OOM,
+// if process died without OOM this channel will be closed.
+func notifyOnOOM(paths map[string]string) (<-chan struct{}, error) {
+ dir := paths[oomCgroupName]
+ if dir == "" {
+ return nil, fmt.Errorf("path %q missing", oomCgroupName)
+ }
+
+ return registerMemoryEvent(dir, "memory.oom_control", "")
+}
+
+func notifyMemoryPressure(paths map[string]string, level PressureLevel) (<-chan struct{}, error) {
+ dir := paths[oomCgroupName]
+ if dir == "" {
+ return nil, fmt.Errorf("path %q missing", oomCgroupName)
+ }
+
+ if level > CriticalPressure {
+ return nil, fmt.Errorf("invalid pressure level %d", level)
+ }
+
+ levelStr := []string{"low", "medium", "critical"}[level]
+ return registerMemoryEvent(dir, "memory.pressure_level", levelStr)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md
new file mode 100644
index 0000000..5757013
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md
@@ -0,0 +1,44 @@
+## nsenter
+
+The `nsenter` package registers a special init constructor that is called before
+the Go runtime has a chance to boot. This provides us the ability to `setns` on
+existing namespaces and avoid the issues that the Go runtime has with multiple
+threads. This constructor will be called if this package is registered,
+imported, in your go application.
+
+The `nsenter` package will `import "C"` and it uses [cgo](https://golang.org/cmd/cgo/)
+package. In cgo, if the import of "C" is immediately preceded by a comment, that comment,
+called the preamble, is used as a header when compiling the C parts of the package.
+So every time we import package `nsenter`, the C code function `nsexec()` would be
+called. And package `nsenter` is now only imported in `main_unix.go`, so every time
+before we call `cmd.Start` on linux, that C code would run.
+
+Because `nsexec()` must be run before the Go runtime in order to use the
+Linux kernel namespace, you must `import` this library into a package if
+you plan to use `libcontainer` directly. Otherwise Go will not execute
+the `nsexec()` constructor, which means that the re-exec will not cause
+the namespaces to be joined. You can import it like this:
+
+```go
+import _ "github.com/opencontainers/runc/libcontainer/nsenter"
+```
+
+`nsexec()` will first get the file descriptor number for the init pipe
+from the environment variable `_LIBCONTAINER_INITPIPE` (which was opened
+by the parent and kept open across the fork-exec of the `nsexec()` init
+process). The init pipe is used to read bootstrap data (namespace paths,
+clone flags, uid and gid mappings, and the console path) from the parent
+process. `nsexec()` will then call `setns(2)` to join the namespaces
+provided in the bootstrap data (if available), `clone(2)` a child process
+with the provided clone flags, update the user and group ID mappings, do
+some further miscellaneous setup steps, and then send the PID of the
+child process to the parent of the `nsexec()` "caller". Finally,
+the parent `nsexec()` will exit and the child `nsexec()` process will
+return to allow the Go runtime take over.
+
+NOTE: We do both `setns(2)` and `clone(2)` even if we don't have any
+CLONE_NEW* clone flags because we must fork a new process in order to
+enter the PID namespace.
+
+
+
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/nsenter/namespace.h b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/namespace.h
new file mode 100644
index 0000000..9e9bdca
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/namespace.h
@@ -0,0 +1,32 @@
+#ifndef NSENTER_NAMESPACE_H
+#define NSENTER_NAMESPACE_H
+
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE
+#endif
+#include <sched.h>
+
+/* All of these are taken from include/uapi/linux/sched.h */
+#ifndef CLONE_NEWNS
+# define CLONE_NEWNS 0x00020000 /* New mount namespace group */
+#endif
+#ifndef CLONE_NEWCGROUP
+# define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */
+#endif
+#ifndef CLONE_NEWUTS
+# define CLONE_NEWUTS 0x04000000 /* New utsname namespace */
+#endif
+#ifndef CLONE_NEWIPC
+# define CLONE_NEWIPC 0x08000000 /* New ipc namespace */
+#endif
+#ifndef CLONE_NEWUSER
+# define CLONE_NEWUSER 0x10000000 /* New user namespace */
+#endif
+#ifndef CLONE_NEWPID
+# define CLONE_NEWPID 0x20000000 /* New pid namespace */
+#endif
+#ifndef CLONE_NEWNET
+# define CLONE_NEWNET 0x40000000 /* New network namespace */
+#endif
+
+#endif /* NSENTER_NAMESPACE_H */
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter.go b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter.go
new file mode 100644
index 0000000..07f4d63
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter.go
@@ -0,0 +1,12 @@
+// +build linux,!gccgo
+
+package nsenter
+
+/*
+#cgo CFLAGS: -Wall
+extern void nsexec();
+void __attribute__((constructor)) init(void) {
+ nsexec();
+}
+*/
+import "C"
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_gccgo.go b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_gccgo.go
new file mode 100644
index 0000000..63c7a3e
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_gccgo.go
@@ -0,0 +1,25 @@
+// +build linux,gccgo
+
+package nsenter
+
+/*
+#cgo CFLAGS: -Wall
+extern void nsexec();
+void __attribute__((constructor)) init(void) {
+ nsexec();
+}
+*/
+import "C"
+
+// AlwaysFalse is here to stay false
+// (and be exported so the compiler doesn't optimize out its reference)
+var AlwaysFalse bool
+
+func init() {
+ if AlwaysFalse {
+ // by referencing this C init() in a noop test, it will ensure the compiler
+ // links in the C function.
+ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65134
+ C.init()
+ }
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_unsupported.go
new file mode 100644
index 0000000..ac701ca
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_unsupported.go
@@ -0,0 +1,5 @@
+// +build !linux !cgo
+
+package nsenter
+
+import "C"
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsexec.c b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsexec.c
new file mode 100644
index 0000000..0ad6883
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsexec.c
@@ -0,0 +1,863 @@
+#define _GNU_SOURCE
+#include <endian.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <grp.h>
+#include <sched.h>
+#include <setjmp.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <sys/ioctl.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+
+#include <linux/limits.h>
+#include <linux/netlink.h>
+#include <linux/types.h>
+
+/* Get all of the CLONE_NEW* flags. */
+#include "namespace.h"
+
+/* Synchronisation values. */
+enum sync_t {
+ SYNC_USERMAP_PLS = 0x40, /* Request parent to map our users. */
+ SYNC_USERMAP_ACK = 0x41, /* Mapping finished by the parent. */
+ SYNC_RECVPID_PLS = 0x42, /* Tell parent we're sending the PID. */
+ SYNC_RECVPID_ACK = 0x43, /* PID was correctly received by parent. */
+ SYNC_GRANDCHILD = 0x44, /* The grandchild is ready to run. */
+ SYNC_CHILD_READY = 0x45, /* The child or grandchild is ready to return. */
+
+ /* XXX: This doesn't help with segfaults and other such issues. */
+ SYNC_ERR = 0xFF, /* Fatal error, no turning back. The error code follows. */
+};
+
+/* longjmp() arguments. */
+#define JUMP_PARENT 0x00
+#define JUMP_CHILD 0xA0
+#define JUMP_INIT 0xA1
+
+/* JSON buffer. */
+#define JSON_MAX 4096
+
+/* Assume the stack grows down, so arguments should be above it. */
+struct clone_t {
+ /*
+ * Reserve some space for clone() to locate arguments
+ * and retcode in this place
+ */
+ char stack[4096] __attribute__ ((aligned(16)));
+ char stack_ptr[0];
+
+ /* There's two children. This is used to execute the different code. */
+ jmp_buf *env;
+ int jmpval;
+};
+
+struct nlconfig_t {
+ char *data;
+ uint32_t cloneflags;
+ char *uidmap;
+ size_t uidmap_len;
+ char *gidmap;
+ size_t gidmap_len;
+ char *namespaces;
+ size_t namespaces_len;
+ uint8_t is_setgroup;
+ uint8_t is_rootless;
+ char *oom_score_adj;
+ size_t oom_score_adj_len;
+};
+
+/*
+ * List of netlink message types sent to us as part of bootstrapping the init.
+ * These constants are defined in libcontainer/message_linux.go.
+ */
+#define INIT_MSG 62000
+#define CLONE_FLAGS_ATTR 27281
+#define NS_PATHS_ATTR 27282
+#define UIDMAP_ATTR 27283
+#define GIDMAP_ATTR 27284
+#define SETGROUP_ATTR 27285
+#define OOM_SCORE_ADJ_ATTR 27286
+#define ROOTLESS_ATTR 27287
+
+/*
+ * Use the raw syscall for versions of glibc which don't include a function for
+ * it, namely (glibc 2.12).
+ */
+#if __GLIBC__ == 2 && __GLIBC_MINOR__ < 14
+# define _GNU_SOURCE
+# include "syscall.h"
+# if !defined(SYS_setns) && defined(__NR_setns)
+# define SYS_setns __NR_setns
+# endif
+
+#ifndef SYS_setns
+# error "setns(2) syscall not supported by glibc version"
+#endif
+
+int setns(int fd, int nstype)
+{
+ return syscall(SYS_setns, fd, nstype);
+}
+#endif
+
+/* XXX: This is ugly. */
+static int syncfd = -1;
+
+/* TODO(cyphar): Fix this so it correctly deals with syncT. */
+#define bail(fmt, ...) \
+ do { \
+ int ret = __COUNTER__ + 1; \
+ fprintf(stderr, "nsenter: " fmt ": %m\n", ##__VA_ARGS__); \
+ if (syncfd >= 0) { \
+ enum sync_t s = SYNC_ERR; \
+ if (write(syncfd, &s, sizeof(s)) != sizeof(s)) \
+ fprintf(stderr, "nsenter: failed: write(s)"); \
+ if (write(syncfd, &ret, sizeof(ret)) != sizeof(ret)) \
+ fprintf(stderr, "nsenter: failed: write(ret)"); \
+ } \
+ exit(ret); \
+ } while(0)
+
+static int write_file(char *data, size_t data_len, char *pathfmt, ...)
+{
+ int fd, len, ret = 0;
+ char path[PATH_MAX];
+
+ va_list ap;
+ va_start(ap, pathfmt);
+ len = vsnprintf(path, PATH_MAX, pathfmt, ap);
+ va_end(ap);
+ if (len < 0)
+ return -1;
+
+ fd = open(path, O_RDWR);
+ if (fd < 0) {
+ ret = -1;
+ goto out;
+ }
+
+ len = write(fd, data, data_len);
+ if (len != data_len) {
+ ret = -1;
+ goto out;
+ }
+
+out:
+ close(fd);
+ return ret;
+}
+
+enum policy_t {
+ SETGROUPS_DEFAULT = 0,
+ SETGROUPS_ALLOW,
+ SETGROUPS_DENY,
+};
+
+/* This *must* be called before we touch gid_map. */
+static void update_setgroups(int pid, enum policy_t setgroup)
+{
+ char *policy;
+
+ switch (setgroup) {
+ case SETGROUPS_ALLOW:
+ policy = "allow";
+ break;
+ case SETGROUPS_DENY:
+ policy = "deny";
+ break;
+ case SETGROUPS_DEFAULT:
+ default:
+ /* Nothing to do. */
+ return;
+ }
+
+ if (write_file(policy, strlen(policy), "/proc/%d/setgroups", pid) < 0) {
+ /*
+ * If the kernel is too old to support /proc/pid/setgroups,
+ * open(2) or write(2) will return ENOENT. This is fine.
+ */
+ if (errno != ENOENT)
+ bail("failed to write '%s' to /proc/%d/setgroups", policy, pid);
+ }
+}
+
+static void update_uidmap(int pid, char *map, size_t map_len)
+{
+ if (map == NULL || map_len <= 0)
+ return;
+
+ if (write_file(map, map_len, "/proc/%d/uid_map", pid) < 0)
+ bail("failed to update /proc/%d/uid_map", pid);
+}
+
+static void update_gidmap(int pid, char *map, size_t map_len)
+{
+ if (map == NULL || map_len <= 0)
+ return;
+
+ if (write_file(map, map_len, "/proc/%d/gid_map", pid) < 0)
+ bail("failed to update /proc/%d/gid_map", pid);
+}
+
+static void update_oom_score_adj(char *data, size_t len)
+{
+ if (data == NULL || len <= 0)
+ return;
+
+ if (write_file(data, len, "/proc/self/oom_score_adj") < 0)
+ bail("failed to update /proc/self/oom_score_adj");
+}
+
+/* A dummy function that just jumps to the given jumpval. */
+static int child_func(void *arg) __attribute__ ((noinline));
+static int child_func(void *arg)
+{
+ struct clone_t *ca = (struct clone_t *)arg;
+ longjmp(*ca->env, ca->jmpval);
+}
+
+static int clone_parent(jmp_buf *env, int jmpval) __attribute__ ((noinline));
+static int clone_parent(jmp_buf *env, int jmpval)
+{
+ struct clone_t ca = {
+ .env = env,
+ .jmpval = jmpval,
+ };
+
+ return clone(child_func, ca.stack_ptr, CLONE_PARENT | SIGCHLD, &ca);
+}
+
+/*
+ * Gets the init pipe fd from the environment, which is used to read the
+ * bootstrap data and tell the parent what the new pid is after we finish
+ * setting up the environment.
+ */
+static int initpipe(void)
+{
+ int pipenum;
+ char *initpipe, *endptr;
+
+ initpipe = getenv("_LIBCONTAINER_INITPIPE");
+ if (initpipe == NULL || *initpipe == '\0')
+ return -1;
+
+ pipenum = strtol(initpipe, &endptr, 10);
+ if (*endptr != '\0')
+ bail("unable to parse _LIBCONTAINER_INITPIPE");
+
+ return pipenum;
+}
+
+/* Returns the clone(2) flag for a namespace, given the name of a namespace. */
+static int nsflag(char *name)
+{
+ if (!strcmp(name, "cgroup"))
+ return CLONE_NEWCGROUP;
+ else if (!strcmp(name, "ipc"))
+ return CLONE_NEWIPC;
+ else if (!strcmp(name, "mnt"))
+ return CLONE_NEWNS;
+ else if (!strcmp(name, "net"))
+ return CLONE_NEWNET;
+ else if (!strcmp(name, "pid"))
+ return CLONE_NEWPID;
+ else if (!strcmp(name, "user"))
+ return CLONE_NEWUSER;
+ else if (!strcmp(name, "uts"))
+ return CLONE_NEWUTS;
+
+ /* If we don't recognise a name, fallback to 0. */
+ return 0;
+}
+
+static uint32_t readint32(char *buf)
+{
+ return *(uint32_t *) buf;
+}
+
+static uint8_t readint8(char *buf)
+{
+ return *(uint8_t *) buf;
+}
+
+static void nl_parse(int fd, struct nlconfig_t *config)
+{
+ size_t len, size;
+ struct nlmsghdr hdr;
+ char *data, *current;
+
+ /* Retrieve the netlink header. */
+ len = read(fd, &hdr, NLMSG_HDRLEN);
+ if (len != NLMSG_HDRLEN)
+ bail("invalid netlink header length %zu", len);
+
+ if (hdr.nlmsg_type == NLMSG_ERROR)
+ bail("failed to read netlink message");
+
+ if (hdr.nlmsg_type != INIT_MSG)
+ bail("unexpected msg type %d", hdr.nlmsg_type);
+
+ /* Retrieve data. */
+ size = NLMSG_PAYLOAD(&hdr, 0);
+ current = data = malloc(size);
+ if (!data)
+ bail("failed to allocate %zu bytes of memory for nl_payload", size);
+
+ len = read(fd, data, size);
+ if (len != size)
+ bail("failed to read netlink payload, %zu != %zu", len, size);
+
+ /* Parse the netlink payload. */
+ config->data = data;
+ while (current < data + size) {
+ struct nlattr *nlattr = (struct nlattr *)current;
+ size_t payload_len = nlattr->nla_len - NLA_HDRLEN;
+
+ /* Advance to payload. */
+ current += NLA_HDRLEN;
+
+ /* Handle payload. */
+ switch (nlattr->nla_type) {
+ case CLONE_FLAGS_ATTR:
+ config->cloneflags = readint32(current);
+ break;
+ case ROOTLESS_ATTR:
+ config->is_rootless = readint8(current);
+ break;
+ case OOM_SCORE_ADJ_ATTR:
+ config->oom_score_adj = current;
+ config->oom_score_adj_len = payload_len;
+ break;
+ case NS_PATHS_ATTR:
+ config->namespaces = current;
+ config->namespaces_len = payload_len;
+ break;
+ case UIDMAP_ATTR:
+ config->uidmap = current;
+ config->uidmap_len = payload_len;
+ break;
+ case GIDMAP_ATTR:
+ config->gidmap = current;
+ config->gidmap_len = payload_len;
+ break;
+ case SETGROUP_ATTR:
+ config->is_setgroup = readint8(current);
+ break;
+ default:
+ bail("unknown netlink message type %d", nlattr->nla_type);
+ }
+
+ current += NLA_ALIGN(payload_len);
+ }
+}
+
+void nl_free(struct nlconfig_t *config)
+{
+ free(config->data);
+}
+
+void join_namespaces(char *nslist)
+{
+ int num = 0, i;
+ char *saveptr = NULL;
+ char *namespace = strtok_r(nslist, ",", &saveptr);
+ struct namespace_t {
+ int fd;
+ int ns;
+ char type[PATH_MAX];
+ char path[PATH_MAX];
+ } *namespaces = NULL;
+
+ if (!namespace || !strlen(namespace) || !strlen(nslist))
+ bail("ns paths are empty");
+
+ /*
+ * We have to open the file descriptors first, since after
+ * we join the mnt namespace we might no longer be able to
+ * access the paths.
+ */
+ do {
+ int fd;
+ char *path;
+ struct namespace_t *ns;
+
+ /* Resize the namespace array. */
+ namespaces = realloc(namespaces, ++num * sizeof(struct namespace_t));
+ if (!namespaces)
+ bail("failed to reallocate namespace array");
+ ns = &namespaces[num - 1];
+
+ /* Split 'ns:path'. */
+ path = strstr(namespace, ":");
+ if (!path)
+ bail("failed to parse %s", namespace);
+ *path++ = '\0';
+
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ bail("failed to open %s", path);
+
+ ns->fd = fd;
+ ns->ns = nsflag(namespace);
+ strncpy(ns->path, path, PATH_MAX);
+ } while ((namespace = strtok_r(NULL, ",", &saveptr)) != NULL);
+
+ /*
+ * The ordering in which we join namespaces is important. We should
+ * always join the user namespace *first*. This is all guaranteed
+ * from the container_linux.go side of this, so we're just going to
+ * follow the order given to us.
+ */
+
+ for (i = 0; i < num; i++) {
+ struct namespace_t ns = namespaces[i];
+
+ if (setns(ns.fd, ns.ns) < 0)
+ bail("failed to setns to %s", ns.path);
+
+ close(ns.fd);
+ }
+
+ free(namespaces);
+}
+
+void nsexec(void)
+{
+ int pipenum;
+ jmp_buf env;
+ int sync_child_pipe[2], sync_grandchild_pipe[2];
+ struct nlconfig_t config = {0};
+
+ /*
+ * If we don't have an init pipe, just return to the go routine.
+ * We'll only get an init pipe for start or exec.
+ */
+ pipenum = initpipe();
+ if (pipenum == -1)
+ return;
+
+ /* Parse all of the netlink configuration. */
+ nl_parse(pipenum, &config);
+
+ /* Set oom_score_adj. This has to be done before !dumpable because
+ * /proc/self/oom_score_adj is not writeable unless you're an privileged
+ * user (if !dumpable is set). All children inherit their parent's
+ * oom_score_adj value on fork(2) so this will always be propagated
+ * properly.
+ */
+ update_oom_score_adj(config.oom_score_adj, config.oom_score_adj_len);
+
+ /*
+ * Make the process non-dumpable, to avoid various race conditions that
+ * could cause processes in namespaces we're joining to access host
+ * resources (or potentially execute code).
+ *
+ * However, if the number of namespaces we are joining is 0, we are not
+ * going to be switching to a different security context. Thus setting
+ * ourselves to be non-dumpable only breaks things (like rootless
+ * containers), which is the recommendation from the kernel folks.
+ */
+ if (config.namespaces) {
+ if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) < 0)
+ bail("failed to set process as non-dumpable");
+ }
+
+ /* Pipe so we can tell the child when we've finished setting up. */
+ if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sync_child_pipe) < 0)
+ bail("failed to setup sync pipe between parent and child");
+
+ /*
+ * We need a new socketpair to sync with grandchild so we don't have
+ * race condition with child.
+ */
+ if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sync_grandchild_pipe) < 0)
+ bail("failed to setup sync pipe between parent and grandchild");
+
+ /* TODO: Currently we aren't dealing with child deaths properly. */
+
+ /*
+ * Okay, so this is quite annoying.
+ *
+ * In order for this unsharing code to be more extensible we need to split
+ * up unshare(CLONE_NEWUSER) and clone() in various ways. The ideal case
+ * would be if we did clone(CLONE_NEWUSER) and the other namespaces
+ * separately, but because of SELinux issues we cannot really do that. But
+ * we cannot just dump the namespace flags into clone(...) because several
+ * usecases (such as rootless containers) require more granularity around
+ * the namespace setup. In addition, some older kernels had issues where
+ * CLONE_NEWUSER wasn't handled before other namespaces (but we cannot
+ * handle this while also dealing with SELinux so we choose SELinux support
+ * over broken kernel support).
+ *
+ * However, if we unshare(2) the user namespace *before* we clone(2), then
+ * all hell breaks loose.
+ *
+ * The parent no longer has permissions to do many things (unshare(2) drops
+ * all capabilities in your old namespace), and the container cannot be set
+ * up to have more than one {uid,gid} mapping. This is obviously less than
+ * ideal. In order to fix this, we have to first clone(2) and then unshare.
+ *
+ * Unfortunately, it's not as simple as that. We have to fork to enter the
+ * PID namespace (the PID namespace only applies to children). Since we'll
+ * have to double-fork, this clone_parent() call won't be able to get the
+ * PID of the _actual_ init process (without doing more synchronisation than
+ * I can deal with at the moment). So we'll just get the parent to send it
+ * for us, the only job of this process is to update
+ * /proc/pid/{setgroups,uid_map,gid_map}.
+ *
+ * And as a result of the above, we also need to setns(2) in the first child
+ * because if we join a PID namespace in the topmost parent then our child
+ * will be in that namespace (and it will not be able to give us a PID value
+ * that makes sense without resorting to sending things with cmsg).
+ *
+ * This also deals with an older issue caused by dumping cloneflags into
+ * clone(2): On old kernels, CLONE_PARENT didn't work with CLONE_NEWPID, so
+ * we have to unshare(2) before clone(2) in order to do this. This was fixed
+ * in upstream commit 1f7f4dde5c945f41a7abc2285be43d918029ecc5, and was
+ * introduced by 40a0d32d1eaffe6aac7324ca92604b6b3977eb0e. As far as we're
+ * aware, the last mainline kernel which had this bug was Linux 3.12.
+ * However, we cannot comment on which kernels the broken patch was
+ * backported to.
+ *
+ * -- Aleksa "what has my life come to?" Sarai
+ */
+
+ switch (setjmp(env)) {
+ /*
+ * Stage 0: We're in the parent. Our job is just to create a new child
+ * (stage 1: JUMP_CHILD) process and write its uid_map and
+ * gid_map. That process will go on to create a new process, then
+ * it will send us its PID which we will send to the bootstrap
+ * process.
+ */
+ case JUMP_PARENT: {
+ int len;
+ pid_t child;
+ char buf[JSON_MAX];
+ bool ready = false;
+
+ /* For debugging. */
+ prctl(PR_SET_NAME, (unsigned long) "runc:[0:PARENT]", 0, 0, 0);
+
+ /* Start the process of getting a container. */
+ child = clone_parent(&env, JUMP_CHILD);
+ if (child < 0)
+ bail("unable to fork: child_func");
+
+ /*
+ * State machine for synchronisation with the children.
+ *
+ * Father only return when both child and grandchild are
+ * ready, so we can receive all possible error codes
+ * generated by children.
+ */
+ while (!ready) {
+ enum sync_t s;
+ int ret;
+
+ syncfd = sync_child_pipe[1];
+ close(sync_child_pipe[0]);
+
+ if (read(syncfd, &s, sizeof(s)) != sizeof(s))
+ bail("failed to sync with child: next state");
+
+ switch (s) {
+ case SYNC_ERR:
+ /* We have to mirror the error code of the child. */
+ if (read(syncfd, &ret, sizeof(ret)) != sizeof(ret))
+ bail("failed to sync with child: read(error code)");
+
+ exit(ret);
+ case SYNC_USERMAP_PLS:
+ /*
+ * Enable setgroups(2) if we've been asked to. But we also
+ * have to explicitly disable setgroups(2) if we're
+ * creating a rootless container (this is required since
+ * Linux 3.19).
+ */
+ if (config.is_rootless && config.is_setgroup) {
+ kill(child, SIGKILL);
+ bail("cannot allow setgroup in an unprivileged user namespace setup");
+ }
+
+ if (config.is_setgroup)
+ update_setgroups(child, SETGROUPS_ALLOW);
+ if (config.is_rootless)
+ update_setgroups(child, SETGROUPS_DENY);
+
+ /* Set up mappings. */
+ update_uidmap(child, config.uidmap, config.uidmap_len);
+ update_gidmap(child, config.gidmap, config.gidmap_len);
+
+ s = SYNC_USERMAP_ACK;
+ if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
+ kill(child, SIGKILL);
+ bail("failed to sync with child: write(SYNC_USERMAP_ACK)");
+ }
+ break;
+ case SYNC_RECVPID_PLS: {
+ pid_t old = child;
+
+ /* Get the init_func pid. */
+ if (read(syncfd, &child, sizeof(child)) != sizeof(child)) {
+ kill(old, SIGKILL);
+ bail("failed to sync with child: read(childpid)");
+ }
+
+ /* Send ACK. */
+ s = SYNC_RECVPID_ACK;
+ if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
+ kill(old, SIGKILL);
+ kill(child, SIGKILL);
+ bail("failed to sync with child: write(SYNC_RECVPID_ACK)");
+ }
+ }
+ break;
+ case SYNC_CHILD_READY:
+ ready = true;
+ break;
+ default:
+ bail("unexpected sync value: %u", s);
+ }
+ }
+
+ /* Now sync with grandchild. */
+
+ ready = false;
+ while (!ready) {
+ enum sync_t s;
+ int ret;
+
+ syncfd = sync_grandchild_pipe[1];
+ close(sync_grandchild_pipe[0]);
+
+ s = SYNC_GRANDCHILD;
+ if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
+ kill(child, SIGKILL);
+ bail("failed to sync with child: write(SYNC_GRANDCHILD)");
+ }
+
+ if (read(syncfd, &s, sizeof(s)) != sizeof(s))
+ bail("failed to sync with child: next state");
+
+ switch (s) {
+ case SYNC_ERR:
+ /* We have to mirror the error code of the child. */
+ if (read(syncfd, &ret, sizeof(ret)) != sizeof(ret))
+ bail("failed to sync with child: read(error code)");
+
+ exit(ret);
+ case SYNC_CHILD_READY:
+ ready = true;
+ break;
+ default:
+ bail("unexpected sync value: %u", s);
+ }
+ }
+
+ /* Send the init_func pid back to our parent. */
+ len = snprintf(buf, JSON_MAX, "{\"pid\": %d}\n", child);
+ if (len < 0) {
+ kill(child, SIGKILL);
+ bail("unable to generate JSON for child pid");
+ }
+ if (write(pipenum, buf, len) != len) {
+ kill(child, SIGKILL);
+ bail("unable to send child pid to bootstrapper");
+ }
+
+ exit(0);
+ }
+
+ /*
+ * Stage 1: We're in the first child process. Our job is to join any
+ * provided namespaces in the netlink payload and unshare all
+ * of the requested namespaces. If we've been asked to
+ * CLONE_NEWUSER, we will ask our parent (stage 0) to set up
+ * our user mappings for us. Then, we create a new child
+ * (stage 2: JUMP_INIT) for PID namespace. We then send the
+ * child's PID to our parent (stage 0).
+ */
+ case JUMP_CHILD: {
+ pid_t child;
+ enum sync_t s;
+
+ /* We're in a child and thus need to tell the parent if we die. */
+ syncfd = sync_child_pipe[0];
+ close(sync_child_pipe[1]);
+
+ /* For debugging. */
+ prctl(PR_SET_NAME, (unsigned long) "runc:[1:CHILD]", 0, 0, 0);
+
+ /*
+ * We need to setns first. We cannot do this earlier (in stage 0)
+ * because of the fact that we forked to get here (the PID of
+ * [stage 2: JUMP_INIT]) would be meaningless). We could send it
+ * using cmsg(3) but that's just annoying.
+ */
+ if (config.namespaces)
+ join_namespaces(config.namespaces);
+
+ /*
+ * Unshare all of the namespaces. Now, it should be noted that this
+ * ordering might break in the future (especially with rootless
+ * containers). But for now, it's not possible to split this into
+ * CLONE_NEWUSER + [the rest] because of some RHEL SELinux issues.
+ *
+ * Note that we don't merge this with clone() because there were
+ * some old kernel versions where clone(CLONE_PARENT | CLONE_NEWPID)
+ * was broken, so we'll just do it the long way anyway.
+ */
+ if (unshare(config.cloneflags) < 0)
+ bail("failed to unshare namespaces");
+
+ /*
+ * Deal with user namespaces first. They are quite special, as they
+ * affect our ability to unshare other namespaces and are used as
+ * context for privilege checks.
+ */
+ if (config.cloneflags & CLONE_NEWUSER) {
+ /*
+ * We don't have the privileges to do any mapping here (see the
+ * clone_parent rant). So signal our parent to hook us up.
+ */
+
+ /* Switching is only necessary if we joined namespaces. */
+ if (config.namespaces) {
+ if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0)
+ bail("failed to set process as dumpable");
+ }
+ s = SYNC_USERMAP_PLS;
+ if (write(syncfd, &s, sizeof(s)) != sizeof(s))
+ bail("failed to sync with parent: write(SYNC_USERMAP_PLS)");
+
+ /* ... wait for mapping ... */
+
+ if (read(syncfd, &s, sizeof(s)) != sizeof(s))
+ bail("failed to sync with parent: read(SYNC_USERMAP_ACK)");
+ if (s != SYNC_USERMAP_ACK)
+ bail("failed to sync with parent: SYNC_USERMAP_ACK: got %u", s);
+ /* Switching is only necessary if we joined namespaces. */
+ if (config.namespaces) {
+ if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) < 0)
+ bail("failed to set process as dumpable");
+ }
+ }
+
+ /*
+ * TODO: What about non-namespace clone flags that we're dropping here?
+ *
+ * We fork again because of PID namespace, setns(2) or unshare(2) don't
+ * change the PID namespace of the calling process, because doing so
+ * would change the caller's idea of its own PID (as reported by getpid()),
+ * which would break many applications and libraries, so we must fork
+ * to actually enter the new PID namespace.
+ */
+ child = clone_parent(&env, JUMP_INIT);
+ if (child < 0)
+ bail("unable to fork: init_func");
+
+ /* Send the child to our parent, which knows what it's doing. */
+ s = SYNC_RECVPID_PLS;
+ if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
+ kill(child, SIGKILL);
+ bail("failed to sync with parent: write(SYNC_RECVPID_PLS)");
+ }
+ if (write(syncfd, &child, sizeof(child)) != sizeof(child)) {
+ kill(child, SIGKILL);
+ bail("failed to sync with parent: write(childpid)");
+ }
+
+ /* ... wait for parent to get the pid ... */
+
+ if (read(syncfd, &s, sizeof(s)) != sizeof(s)) {
+ kill(child, SIGKILL);
+ bail("failed to sync with parent: read(SYNC_RECVPID_ACK)");
+ }
+ if (s != SYNC_RECVPID_ACK) {
+ kill(child, SIGKILL);
+ bail("failed to sync with parent: SYNC_RECVPID_ACK: got %u", s);
+ }
+
+ s = SYNC_CHILD_READY;
+ if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
+ kill(child, SIGKILL);
+ bail("failed to sync with parent: write(SYNC_CHILD_READY)");
+ }
+
+ /* Our work is done. [Stage 2: JUMP_INIT] is doing the rest of the work. */
+ exit(0);
+ }
+
+ /*
+ * Stage 2: We're the final child process, and the only process that will
+ * actually return to the Go runtime. Our job is to just do the
+ * final cleanup steps and then return to the Go runtime to allow
+ * init_linux.go to run.
+ */
+ case JUMP_INIT: {
+ /*
+ * We're inside the child now, having jumped from the
+ * start_child() code after forking in the parent.
+ */
+ enum sync_t s;
+
+ /* We're in a child and thus need to tell the parent if we die. */
+ syncfd = sync_grandchild_pipe[0];
+ close(sync_grandchild_pipe[1]);
+ close(sync_child_pipe[0]);
+ close(sync_child_pipe[1]);
+
+ /* For debugging. */
+ prctl(PR_SET_NAME, (unsigned long) "runc:[2:INIT]", 0, 0, 0);
+
+ if (read(syncfd, &s, sizeof(s)) != sizeof(s))
+ bail("failed to sync with parent: read(SYNC_GRANDCHILD)");
+ if (s != SYNC_GRANDCHILD)
+ bail("failed to sync with parent: SYNC_GRANDCHILD: got %u", s);
+
+ if (setsid() < 0)
+ bail("setsid failed");
+
+ if (setuid(0) < 0)
+ bail("setuid failed");
+
+ if (setgid(0) < 0)
+ bail("setgid failed");
+
+ if (!config.is_rootless && config.is_setgroup) {
+ if (setgroups(0, NULL) < 0)
+ bail("setgroups failed");
+ }
+
+ s = SYNC_CHILD_READY;
+ if (write(syncfd, &s, sizeof(s)) != sizeof(s))
+ bail("failed to sync with patent: write(SYNC_CHILD_READY)");
+
+ /* Close sync pipes. */
+ close(sync_grandchild_pipe[0]);
+
+ /* Free netlink data. */
+ nl_free(&config);
+
+ /* Finish executing, let the Go runtime take over. */
+ return;
+ }
+ default:
+ bail("unexpected jump value");
+ }
+
+ /* Should never be reached. */
+ bail("should never be reached");
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/process.go b/vendor/github.com/opencontainers/runc/libcontainer/process.go
new file mode 100644
index 0000000..f1ad081
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/process.go
@@ -0,0 +1,106 @@
+package libcontainer
+
+import (
+ "fmt"
+ "io"
+ "math"
+ "os"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+type processOperations interface {
+ wait() (*os.ProcessState, error)
+ signal(sig os.Signal) error
+ pid() int
+}
+
+// Process specifies the configuration and IO for a process inside
+// a container.
+type Process struct {
+ // The command to be run followed by any arguments.
+ Args []string
+
+ // Env specifies the environment variables for the process.
+ Env []string
+
+ // User will set the uid and gid of the executing process running inside the container
+ // local to the container's user and group configuration.
+ User string
+
+ // AdditionalGroups specifies the gids that should be added to supplementary groups
+ // in addition to those that the user belongs to.
+ AdditionalGroups []string
+
+ // Cwd will change the processes current working directory inside the container's rootfs.
+ Cwd string
+
+ // Stdin is a pointer to a reader which provides the standard input stream.
+ Stdin io.Reader
+
+ // Stdout is a pointer to a writer which receives the standard output stream.
+ Stdout io.Writer
+
+ // Stderr is a pointer to a writer which receives the standard error stream.
+ Stderr io.Writer
+
+ // ExtraFiles specifies additional open files to be inherited by the container
+ ExtraFiles []*os.File
+
+ // Capabilities specify the capabilities to keep when executing the process inside the container
+ // All capabilities not specified will be dropped from the processes capability mask
+ Capabilities *configs.Capabilities
+
+ // AppArmorProfile specifies the profile to apply to the process and is
+ // changed at the time the process is execed
+ AppArmorProfile string
+
+ // Label specifies the label to apply to the process. It is commonly used by selinux
+ Label string
+
+ // NoNewPrivileges controls whether processes can gain additional privileges.
+ NoNewPrivileges *bool
+
+ // Rlimits specifies the resource limits, such as max open files, to set in the container
+ // If Rlimits are not set, the container will inherit rlimits from the parent process
+ Rlimits []configs.Rlimit
+
+ // ConsoleSocket provides the masterfd console.
+ ConsoleSocket *os.File
+
+ ops processOperations
+}
+
+// Wait waits for the process to exit.
+// Wait releases any resources associated with the Process
+func (p Process) Wait() (*os.ProcessState, error) {
+ if p.ops == nil {
+ return nil, newGenericError(fmt.Errorf("invalid process"), NoProcessOps)
+ }
+ return p.ops.wait()
+}
+
+// Pid returns the process ID
+func (p Process) Pid() (int, error) {
+ // math.MinInt32 is returned here, because it's invalid value
+ // for the kill() system call.
+ if p.ops == nil {
+ return math.MinInt32, newGenericError(fmt.Errorf("invalid process"), NoProcessOps)
+ }
+ return p.ops.pid(), nil
+}
+
+// Signal sends a signal to the Process.
+func (p Process) Signal(sig os.Signal) error {
+ if p.ops == nil {
+ return newGenericError(fmt.Errorf("invalid process"), NoProcessOps)
+ }
+ return p.ops.signal(sig)
+}
+
+// IO holds the process's STDIO
+type IO struct {
+ Stdin io.WriteCloser
+ Stdout io.ReadCloser
+ Stderr io.ReadCloser
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/process_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/process_linux.go
new file mode 100644
index 0000000..bfe9955
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/process_linux.go
@@ -0,0 +1,483 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "syscall"
+
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/system"
+ "github.com/opencontainers/runc/libcontainer/utils"
+)
+
+type parentProcess interface {
+ // pid returns the pid for the running process.
+ pid() int
+
+ // start starts the process execution.
+ start() error
+
+ // send a SIGKILL to the process and wait for the exit.
+ terminate() error
+
+ // wait waits on the process returning the process state.
+ wait() (*os.ProcessState, error)
+
+ // startTime returns the process start time.
+ startTime() (string, error)
+
+ signal(os.Signal) error
+
+ externalDescriptors() []string
+
+ setExternalDescriptors(fds []string)
+}
+
+type setnsProcess struct {
+ cmd *exec.Cmd
+ parentPipe *os.File
+ childPipe *os.File
+ cgroupPaths map[string]string
+ config *initConfig
+ fds []string
+ process *Process
+ bootstrapData io.Reader
+}
+
+func (p *setnsProcess) startTime() (string, error) {
+ return system.GetProcessStartTime(p.pid())
+}
+
+func (p *setnsProcess) signal(sig os.Signal) error {
+ s, ok := sig.(syscall.Signal)
+ if !ok {
+ return errors.New("os: unsupported signal type")
+ }
+ return syscall.Kill(p.pid(), s)
+}
+
+func (p *setnsProcess) start() (err error) {
+ defer p.parentPipe.Close()
+ err = p.cmd.Start()
+ p.childPipe.Close()
+ if err != nil {
+ return newSystemErrorWithCause(err, "starting setns process")
+ }
+ if p.bootstrapData != nil {
+ if _, err := io.Copy(p.parentPipe, p.bootstrapData); err != nil {
+ return newSystemErrorWithCause(err, "copying bootstrap data to pipe")
+ }
+ }
+ if err = p.execSetns(); err != nil {
+ return newSystemErrorWithCause(err, "executing setns process")
+ }
+ // We can't join cgroups if we're in a rootless container.
+ if !p.config.Rootless && len(p.cgroupPaths) > 0 {
+ if err := cgroups.EnterPid(p.cgroupPaths, p.pid()); err != nil {
+ return newSystemErrorWithCausef(err, "adding pid %d to cgroups", p.pid())
+ }
+ }
+ // set rlimits, this has to be done here because we lose permissions
+ // to raise the limits once we enter a user-namespace
+ if err := setupRlimits(p.config.Rlimits, p.pid()); err != nil {
+ return newSystemErrorWithCause(err, "setting rlimits for process")
+ }
+ if err := utils.WriteJSON(p.parentPipe, p.config); err != nil {
+ return newSystemErrorWithCause(err, "writing config to pipe")
+ }
+
+ ierr := parseSync(p.parentPipe, func(sync *syncT) error {
+ switch sync.Type {
+ case procReady:
+ // This shouldn't happen.
+ panic("unexpected procReady in setns")
+ case procHooks:
+ // This shouldn't happen.
+ panic("unexpected procHooks in setns")
+ default:
+ return newSystemError(fmt.Errorf("invalid JSON payload from child"))
+ }
+ })
+
+ if err := syscall.Shutdown(int(p.parentPipe.Fd()), syscall.SHUT_WR); err != nil {
+ return newSystemErrorWithCause(err, "calling shutdown on init pipe")
+ }
+ // Must be done after Shutdown so the child will exit and we can wait for it.
+ if ierr != nil {
+ p.wait()
+ return ierr
+ }
+ return nil
+}
+
+// execSetns runs the process that executes C code to perform the setns calls
+// because setns support requires the C process to fork off a child and perform the setns
+// before the go runtime boots, we wait on the process to die and receive the child's pid
+// over the provided pipe.
+func (p *setnsProcess) execSetns() error {
+ status, err := p.cmd.Process.Wait()
+ if err != nil {
+ p.cmd.Wait()
+ return newSystemErrorWithCause(err, "waiting on setns process to finish")
+ }
+ if !status.Success() {
+ p.cmd.Wait()
+ return newSystemError(&exec.ExitError{ProcessState: status})
+ }
+ var pid *pid
+ if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil {
+ p.cmd.Wait()
+ return newSystemErrorWithCause(err, "reading pid from init pipe")
+ }
+ process, err := os.FindProcess(pid.Pid)
+ if err != nil {
+ return err
+ }
+ p.cmd.Process = process
+ p.process.ops = p
+ return nil
+}
+
+// terminate sends a SIGKILL to the forked process for the setns routine then waits to
+// avoid the process becoming a zombie.
+func (p *setnsProcess) terminate() error {
+ if p.cmd.Process == nil {
+ return nil
+ }
+ err := p.cmd.Process.Kill()
+ if _, werr := p.wait(); err == nil {
+ err = werr
+ }
+ return err
+}
+
+func (p *setnsProcess) wait() (*os.ProcessState, error) {
+ err := p.cmd.Wait()
+
+ // Return actual ProcessState even on Wait error
+ return p.cmd.ProcessState, err
+}
+
+func (p *setnsProcess) pid() int {
+ return p.cmd.Process.Pid
+}
+
+func (p *setnsProcess) externalDescriptors() []string {
+ return p.fds
+}
+
+func (p *setnsProcess) setExternalDescriptors(newFds []string) {
+ p.fds = newFds
+}
+
+type initProcess struct {
+ cmd *exec.Cmd
+ parentPipe *os.File
+ childPipe *os.File
+ config *initConfig
+ manager cgroups.Manager
+ container *linuxContainer
+ fds []string
+ process *Process
+ bootstrapData io.Reader
+ sharePidns bool
+ rootDir *os.File
+}
+
+func (p *initProcess) pid() int {
+ return p.cmd.Process.Pid
+}
+
+func (p *initProcess) externalDescriptors() []string {
+ return p.fds
+}
+
+// execSetns runs the process that executes C code to perform the setns calls
+// because setns support requires the C process to fork off a child and perform the setns
+// before the go runtime boots, we wait on the process to die and receive the child's pid
+// over the provided pipe.
+// This is called by initProcess.start function
+func (p *initProcess) execSetns() error {
+ status, err := p.cmd.Process.Wait()
+ if err != nil {
+ p.cmd.Wait()
+ return err
+ }
+ if !status.Success() {
+ p.cmd.Wait()
+ return &exec.ExitError{ProcessState: status}
+ }
+ var pid *pid
+ if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil {
+ p.cmd.Wait()
+ return err
+ }
+ process, err := os.FindProcess(pid.Pid)
+ if err != nil {
+ return err
+ }
+ p.cmd.Process = process
+ p.process.ops = p
+ return nil
+}
+
+func (p *initProcess) start() error {
+ defer p.parentPipe.Close()
+ err := p.cmd.Start()
+ p.process.ops = p
+ p.childPipe.Close()
+ p.rootDir.Close()
+ if err != nil {
+ p.process.ops = nil
+ return newSystemErrorWithCause(err, "starting init process command")
+ }
+ if _, err := io.Copy(p.parentPipe, p.bootstrapData); err != nil {
+ return newSystemErrorWithCause(err, "copying bootstrap data to pipe")
+ }
+ if err := p.execSetns(); err != nil {
+ return newSystemErrorWithCause(err, "running exec setns process for init")
+ }
+ // Save the standard descriptor names before the container process
+ // can potentially move them (e.g., via dup2()). If we don't do this now,
+ // we won't know at checkpoint time which file descriptor to look up.
+ fds, err := getPipeFds(p.pid())
+ if err != nil {
+ return newSystemErrorWithCausef(err, "getting pipe fds for pid %d", p.pid())
+ }
+ p.setExternalDescriptors(fds)
+ // Do this before syncing with child so that no children can escape the
+ // cgroup. We don't need to worry about not doing this and not being root
+ // because we'd be using the rootless cgroup manager in that case.
+ if err := p.manager.Apply(p.pid()); err != nil {
+ return newSystemErrorWithCause(err, "applying cgroup configuration for process")
+ }
+ defer func() {
+ if err != nil {
+ // TODO: should not be the responsibility to call here
+ p.manager.Destroy()
+ }
+ }()
+ if err := p.createNetworkInterfaces(); err != nil {
+ return newSystemErrorWithCause(err, "creating network interfaces")
+ }
+ if err := p.sendConfig(); err != nil {
+ return newSystemErrorWithCause(err, "sending config to init process")
+ }
+ var (
+ sentRun bool
+ sentResume bool
+ )
+
+ ierr := parseSync(p.parentPipe, func(sync *syncT) error {
+ switch sync.Type {
+ case procReady:
+ if err := p.manager.Set(p.config.Config); err != nil {
+ return newSystemErrorWithCause(err, "setting cgroup config for ready process")
+ }
+ // set rlimits, this has to be done here because we lose permissions
+ // to raise the limits once we enter a user-namespace
+ if err := setupRlimits(p.config.Rlimits, p.pid()); err != nil {
+ return newSystemErrorWithCause(err, "setting rlimits for ready process")
+ }
+ // call prestart hooks
+ if !p.config.Config.Namespaces.Contains(configs.NEWNS) {
+ if p.config.Config.Hooks != nil {
+ s := configs.HookState{
+ Version: p.container.config.Version,
+ ID: p.container.id,
+ Pid: p.pid(),
+ Bundle: utils.SearchLabels(p.config.Config.Labels, "bundle"),
+ }
+ for i, hook := range p.config.Config.Hooks.Prestart {
+ if err := hook.Run(s); err != nil {
+ return newSystemErrorWithCausef(err, "running prestart hook %d", i)
+ }
+ }
+ }
+ }
+ // Sync with child.
+ if err := writeSync(p.parentPipe, procRun); err != nil {
+ return newSystemErrorWithCause(err, "writing syncT 'run'")
+ }
+ sentRun = true
+ case procHooks:
+ if p.config.Config.Hooks != nil {
+ s := configs.HookState{
+ Version: p.container.config.Version,
+ ID: p.container.id,
+ Pid: p.pid(),
+ Bundle: utils.SearchLabels(p.config.Config.Labels, "bundle"),
+ }
+ for i, hook := range p.config.Config.Hooks.Prestart {
+ if err := hook.Run(s); err != nil {
+ return newSystemErrorWithCausef(err, "running prestart hook %d", i)
+ }
+ }
+ }
+ // Sync with child.
+ if err := writeSync(p.parentPipe, procResume); err != nil {
+ return newSystemErrorWithCause(err, "writing syncT 'resume'")
+ }
+ sentResume = true
+ default:
+ return newSystemError(fmt.Errorf("invalid JSON payload from child"))
+ }
+
+ return nil
+ })
+
+ if !sentRun {
+ return newSystemErrorWithCause(ierr, "container init")
+ }
+ if p.config.Config.Namespaces.Contains(configs.NEWNS) && !sentResume {
+ return newSystemError(fmt.Errorf("could not synchronise after executing prestart hooks with container process"))
+ }
+ if err := syscall.Shutdown(int(p.parentPipe.Fd()), syscall.SHUT_WR); err != nil {
+ return newSystemErrorWithCause(err, "shutting down init pipe")
+ }
+
+ // Must be done after Shutdown so the child will exit and we can wait for it.
+ if ierr != nil {
+ p.wait()
+ return ierr
+ }
+ return nil
+}
+
+func (p *initProcess) wait() (*os.ProcessState, error) {
+ err := p.cmd.Wait()
+ if err != nil {
+ return p.cmd.ProcessState, err
+ }
+ // we should kill all processes in cgroup when init is died if we use host PID namespace
+ if p.sharePidns {
+ signalAllProcesses(p.manager, syscall.SIGKILL)
+ }
+ return p.cmd.ProcessState, nil
+}
+
+func (p *initProcess) terminate() error {
+ if p.cmd.Process == nil {
+ return nil
+ }
+ err := p.cmd.Process.Kill()
+ if _, werr := p.wait(); err == nil {
+ err = werr
+ }
+ return err
+}
+
+func (p *initProcess) startTime() (string, error) {
+ return system.GetProcessStartTime(p.pid())
+}
+
+func (p *initProcess) sendConfig() error {
+ // send the config to the container's init process, we don't use JSON Encode
+ // here because there might be a problem in JSON decoder in some cases, see:
+ // https://github.com/docker/docker/issues/14203#issuecomment-174177790
+ return utils.WriteJSON(p.parentPipe, p.config)
+}
+
+func (p *initProcess) createNetworkInterfaces() error {
+ for _, config := range p.config.Config.Networks {
+ strategy, err := getStrategy(config.Type)
+ if err != nil {
+ return err
+ }
+ n := &network{
+ Network: *config,
+ }
+ if err := strategy.create(n, p.pid()); err != nil {
+ return err
+ }
+ p.config.Networks = append(p.config.Networks, n)
+ }
+ return nil
+}
+
+func (p *initProcess) signal(sig os.Signal) error {
+ s, ok := sig.(syscall.Signal)
+ if !ok {
+ return errors.New("os: unsupported signal type")
+ }
+ return syscall.Kill(p.pid(), s)
+}
+
+func (p *initProcess) setExternalDescriptors(newFds []string) {
+ p.fds = newFds
+}
+
+func getPipeFds(pid int) ([]string, error) {
+ fds := make([]string, 3)
+
+ dirPath := filepath.Join("/proc", strconv.Itoa(pid), "/fd")
+ for i := 0; i < 3; i++ {
+ // XXX: This breaks if the path is not a valid symlink (which can
+ // happen in certain particularly unlucky mount namespace setups).
+ f := filepath.Join(dirPath, strconv.Itoa(i))
+ target, err := os.Readlink(f)
+ if err != nil {
+ // Ignore permission errors, for rootless containers and other
+ // non-dumpable processes. if we can't get the fd for a particular
+ // file, there's not much we can do.
+ if os.IsPermission(err) {
+ continue
+ }
+ return fds, err
+ }
+ fds[i] = target
+ }
+ return fds, nil
+}
+
+// InitializeIO creates pipes for use with the process's stdio and returns the
+// opposite side for each. Do not use this if you want to have a pseudoterminal
+// set up for you by libcontainer (TODO: fix that too).
+// TODO: This is mostly unnecessary, and should be handled by clients.
+func (p *Process) InitializeIO(rootuid, rootgid int) (i *IO, err error) {
+ var fds []uintptr
+ i = &IO{}
+ // cleanup in case of an error
+ defer func() {
+ if err != nil {
+ for _, fd := range fds {
+ syscall.Close(int(fd))
+ }
+ }
+ }()
+ // STDIN
+ r, w, err := os.Pipe()
+ if err != nil {
+ return nil, err
+ }
+ fds = append(fds, r.Fd(), w.Fd())
+ p.Stdin, i.Stdin = r, w
+ // STDOUT
+ if r, w, err = os.Pipe(); err != nil {
+ return nil, err
+ }
+ fds = append(fds, r.Fd(), w.Fd())
+ p.Stdout, i.Stdout = w, r
+ // STDERR
+ if r, w, err = os.Pipe(); err != nil {
+ return nil, err
+ }
+ fds = append(fds, r.Fd(), w.Fd())
+ p.Stderr, i.Stderr = w, r
+ // change ownership of the pipes incase we are in a user namespace
+ for _, fd := range fds {
+ if err := syscall.Fchown(int(fd), rootuid, rootgid); err != nil {
+ return nil, err
+ }
+ }
+ return i, nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/restored_process.go b/vendor/github.com/opencontainers/runc/libcontainer/restored_process.go
new file mode 100644
index 0000000..a96f4ca
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/restored_process.go
@@ -0,0 +1,122 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/opencontainers/runc/libcontainer/system"
+)
+
+func newRestoredProcess(pid int, fds []string) (*restoredProcess, error) {
+ var (
+ err error
+ )
+ proc, err := os.FindProcess(pid)
+ if err != nil {
+ return nil, err
+ }
+ started, err := system.GetProcessStartTime(pid)
+ if err != nil {
+ return nil, err
+ }
+ return &restoredProcess{
+ proc: proc,
+ processStartTime: started,
+ fds: fds,
+ }, nil
+}
+
+type restoredProcess struct {
+ proc *os.Process
+ processStartTime string
+ fds []string
+}
+
+func (p *restoredProcess) start() error {
+ return newGenericError(fmt.Errorf("restored process cannot be started"), SystemError)
+}
+
+func (p *restoredProcess) pid() int {
+ return p.proc.Pid
+}
+
+func (p *restoredProcess) terminate() error {
+ err := p.proc.Kill()
+ if _, werr := p.wait(); err == nil {
+ err = werr
+ }
+ return err
+}
+
+func (p *restoredProcess) wait() (*os.ProcessState, error) {
+ // TODO: how do we wait on the actual process?
+ // maybe use --exec-cmd in criu
+ st, err := p.proc.Wait()
+ if err != nil {
+ return nil, err
+ }
+ return st, nil
+}
+
+func (p *restoredProcess) startTime() (string, error) {
+ return p.processStartTime, nil
+}
+
+func (p *restoredProcess) signal(s os.Signal) error {
+ return p.proc.Signal(s)
+}
+
+func (p *restoredProcess) externalDescriptors() []string {
+ return p.fds
+}
+
+func (p *restoredProcess) setExternalDescriptors(newFds []string) {
+ p.fds = newFds
+}
+
+// nonChildProcess represents a process where the calling process is not
+// the parent process. This process is created when a factory loads a container from
+// a persisted state.
+type nonChildProcess struct {
+ processPid int
+ processStartTime string
+ fds []string
+}
+
+func (p *nonChildProcess) start() error {
+ return newGenericError(fmt.Errorf("restored process cannot be started"), SystemError)
+}
+
+func (p *nonChildProcess) pid() int {
+ return p.processPid
+}
+
+func (p *nonChildProcess) terminate() error {
+ return newGenericError(fmt.Errorf("restored process cannot be terminated"), SystemError)
+}
+
+func (p *nonChildProcess) wait() (*os.ProcessState, error) {
+ return nil, newGenericError(fmt.Errorf("restored process cannot be waited on"), SystemError)
+}
+
+func (p *nonChildProcess) startTime() (string, error) {
+ return p.processStartTime, nil
+}
+
+func (p *nonChildProcess) signal(s os.Signal) error {
+ proc, err := os.FindProcess(p.processPid)
+ if err != nil {
+ return err
+ }
+ return proc.Signal(s)
+}
+
+func (p *nonChildProcess) externalDescriptors() []string {
+ return p.fds
+}
+
+func (p *nonChildProcess) setExternalDescriptors(newFds []string) {
+ p.fds = newFds
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go
new file mode 100644
index 0000000..d507373
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go
@@ -0,0 +1,812 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/docker/docker/pkg/mount"
+ "github.com/docker/docker/pkg/symlink"
+ "github.com/mrunalp/fileutils"
+ "github.com/opencontainers/runc/libcontainer/cgroups"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/system"
+ libcontainerUtils "github.com/opencontainers/runc/libcontainer/utils"
+ "github.com/opencontainers/selinux/go-selinux/label"
+)
+
+const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV
+
+// needsSetupDev returns true if /dev needs to be set up.
+func needsSetupDev(config *configs.Config) bool {
+ for _, m := range config.Mounts {
+ if m.Device == "bind" && libcontainerUtils.CleanPath(m.Destination) == "/dev" {
+ return false
+ }
+ }
+ return true
+}
+
+// prepareRootfs sets up the devices, mount points, and filesystems for use
+// inside a new mount namespace. It doesn't set anything as ro or pivot_root,
+// because console setup happens inside the caller. You must call
+// finalizeRootfs in order to finish the rootfs setup.
+func prepareRootfs(pipe io.ReadWriter, config *configs.Config) (err error) {
+ if err := prepareRoot(config); err != nil {
+ return newSystemErrorWithCause(err, "preparing rootfs")
+ }
+
+ setupDev := needsSetupDev(config)
+ for _, m := range config.Mounts {
+ for _, precmd := range m.PremountCmds {
+ if err := mountCmd(precmd); err != nil {
+ return newSystemErrorWithCause(err, "running premount command")
+ }
+ }
+
+ if err := mountToRootfs(m, config.Rootfs, config.MountLabel); err != nil {
+ return newSystemErrorWithCausef(err, "mounting %q to rootfs %q at %q", m.Source, config.Rootfs, m.Destination)
+ }
+
+ for _, postcmd := range m.PostmountCmds {
+ if err := mountCmd(postcmd); err != nil {
+ return newSystemErrorWithCause(err, "running postmount command")
+ }
+ }
+ }
+
+ if setupDev {
+ if err := createDevices(config); err != nil {
+ return newSystemErrorWithCause(err, "creating device nodes")
+ }
+ if err := setupPtmx(config); err != nil {
+ return newSystemErrorWithCause(err, "setting up ptmx")
+ }
+ if err := setupDevSymlinks(config.Rootfs); err != nil {
+ return newSystemErrorWithCause(err, "setting up /dev symlinks")
+ }
+ }
+
+ // Signal the parent to run the pre-start hooks.
+ // The hooks are run after the mounts are setup, but before we switch to the new
+ // root, so that the old root is still available in the hooks for any mount
+ // manipulations.
+ if err := syncParentHooks(pipe); err != nil {
+ return err
+ }
+
+ // The reason these operations are done here rather than in finalizeRootfs
+ // is because the console-handling code gets quite sticky if we have to set
+ // up the console before doing the pivot_root(2). This is because the
+ // Console API has to also work with the ExecIn case, which means that the
+ // API must be able to deal with being inside as well as outside the
+ // container. It's just cleaner to do this here (at the expense of the
+ // operation not being perfectly split).
+
+ if err := syscall.Chdir(config.Rootfs); err != nil {
+ return newSystemErrorWithCausef(err, "changing dir to %q", config.Rootfs)
+ }
+
+ if config.NoPivotRoot {
+ err = msMoveRoot(config.Rootfs)
+ } else {
+ err = pivotRoot(config.Rootfs)
+ }
+ if err != nil {
+ return newSystemErrorWithCause(err, "jailing process inside rootfs")
+ }
+
+ if setupDev {
+ if err := reOpenDevNull(); err != nil {
+ return newSystemErrorWithCause(err, "reopening /dev/null inside container")
+ }
+ }
+
+ return nil
+}
+
+// finalizeRootfs actually switches the root of the process and sets anything
+// to ro if necessary. You must call prepareRootfs first.
+func finalizeRootfs(config *configs.Config) (err error) {
+ // remount dev as ro if specified
+ for _, m := range config.Mounts {
+ if libcontainerUtils.CleanPath(m.Destination) == "/dev" {
+ if m.Flags&syscall.MS_RDONLY == syscall.MS_RDONLY {
+ if err := remountReadonly(m); err != nil {
+ return newSystemErrorWithCausef(err, "remounting %q as readonly", m.Destination)
+ }
+ }
+ break
+ }
+ }
+
+ // set rootfs ( / ) as readonly
+ if config.Readonlyfs {
+ if err := setReadonly(); err != nil {
+ return newSystemErrorWithCause(err, "setting rootfs as readonly")
+ }
+ }
+
+ syscall.Umask(0022)
+ return nil
+}
+
+func mountCmd(cmd configs.Command) error {
+ command := exec.Command(cmd.Path, cmd.Args[:]...)
+ command.Env = cmd.Env
+ command.Dir = cmd.Dir
+ if out, err := command.CombinedOutput(); err != nil {
+ return fmt.Errorf("%#v failed: %s: %v", cmd, string(out), err)
+ }
+ return nil
+}
+
+func mountToRootfs(m *configs.Mount, rootfs, mountLabel string) error {
+ var (
+ dest = m.Destination
+ )
+ if !strings.HasPrefix(dest, rootfs) {
+ dest = filepath.Join(rootfs, dest)
+ }
+
+ switch m.Device {
+ case "proc", "sysfs":
+ if err := os.MkdirAll(dest, 0755); err != nil {
+ return err
+ }
+ // Selinux kernels do not support labeling of /proc or /sys
+ return mountPropagate(m, rootfs, "")
+ case "mqueue":
+ if err := os.MkdirAll(dest, 0755); err != nil {
+ return err
+ }
+ if err := mountPropagate(m, rootfs, mountLabel); err != nil {
+ // older kernels do not support labeling of /dev/mqueue
+ if err := mountPropagate(m, rootfs, ""); err != nil {
+ return err
+ }
+ return label.SetFileLabel(dest, mountLabel)
+ }
+ return nil
+ case "tmpfs":
+ copyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP
+ tmpDir := ""
+ stat, err := os.Stat(dest)
+ if err != nil {
+ if err := os.MkdirAll(dest, 0755); err != nil {
+ return err
+ }
+ }
+ if copyUp {
+ tmpDir, err = ioutil.TempDir("/tmp", "runctmpdir")
+ if err != nil {
+ return newSystemErrorWithCause(err, "tmpcopyup: failed to create tmpdir")
+ }
+ defer os.RemoveAll(tmpDir)
+ m.Destination = tmpDir
+ }
+ if err := mountPropagate(m, rootfs, mountLabel); err != nil {
+ return err
+ }
+ if copyUp {
+ if err := fileutils.CopyDirectory(dest, tmpDir); err != nil {
+ errMsg := fmt.Errorf("tmpcopyup: failed to copy %s to %s: %v", dest, tmpDir, err)
+ if err1 := syscall.Unmount(tmpDir, syscall.MNT_DETACH); err1 != nil {
+ return newSystemErrorWithCausef(err1, "tmpcopyup: %v: failed to unmount", errMsg)
+ }
+ return errMsg
+ }
+ if err := syscall.Mount(tmpDir, dest, "", syscall.MS_MOVE, ""); err != nil {
+ errMsg := fmt.Errorf("tmpcopyup: failed to move mount %s to %s: %v", tmpDir, dest, err)
+ if err1 := syscall.Unmount(tmpDir, syscall.MNT_DETACH); err1 != nil {
+ return newSystemErrorWithCausef(err1, "tmpcopyup: %v: failed to unmount", errMsg)
+ }
+ return errMsg
+ }
+ }
+ if stat != nil {
+ if err = os.Chmod(dest, stat.Mode()); err != nil {
+ return err
+ }
+ }
+ return nil
+ case "bind":
+ stat, err := os.Stat(m.Source)
+ if err != nil {
+ // error out if the source of a bind mount does not exist as we will be
+ // unable to bind anything to it.
+ return err
+ }
+ // ensure that the destination of the bind mount is resolved of symlinks at mount time because
+ // any previous mounts can invalidate the next mount's destination.
+ // this can happen when a user specifies mounts within other mounts to cause breakouts or other
+ // evil stuff to try to escape the container's rootfs.
+ if dest, err = symlink.FollowSymlinkInScope(dest, rootfs); err != nil {
+ return err
+ }
+ if err := checkMountDestination(rootfs, dest); err != nil {
+ return err
+ }
+ // update the mount with the correct dest after symlinks are resolved.
+ m.Destination = dest
+ if err := createIfNotExists(dest, stat.IsDir()); err != nil {
+ return err
+ }
+ if err := mountPropagate(m, rootfs, mountLabel); err != nil {
+ return err
+ }
+ // bind mount won't change mount options, we need remount to make mount options effective.
+ // first check that we have non-default options required before attempting a remount
+ if m.Flags&^(syscall.MS_REC|syscall.MS_REMOUNT|syscall.MS_BIND) != 0 {
+ // only remount if unique mount options are set
+ if err := remount(m, rootfs); err != nil {
+ return err
+ }
+ }
+
+ if m.Relabel != "" {
+ if err := label.Validate(m.Relabel); err != nil {
+ return err
+ }
+ shared := label.IsShared(m.Relabel)
+ if err := label.Relabel(m.Source, mountLabel, shared); err != nil {
+ return err
+ }
+ }
+ case "cgroup":
+ binds, err := getCgroupMounts(m)
+ if err != nil {
+ return err
+ }
+ var merged []string
+ for _, b := range binds {
+ ss := filepath.Base(b.Destination)
+ if strings.Contains(ss, ",") {
+ merged = append(merged, ss)
+ }
+ }
+ tmpfs := &configs.Mount{
+ Source: "tmpfs",
+ Device: "tmpfs",
+ Destination: m.Destination,
+ Flags: defaultMountFlags,
+ Data: "mode=755",
+ PropagationFlags: m.PropagationFlags,
+ }
+ if err := mountToRootfs(tmpfs, rootfs, mountLabel); err != nil {
+ return err
+ }
+ for _, b := range binds {
+ if err := mountToRootfs(b, rootfs, mountLabel); err != nil {
+ return err
+ }
+ }
+ for _, mc := range merged {
+ for _, ss := range strings.Split(mc, ",") {
+ // symlink(2) is very dumb, it will just shove the path into
+ // the link and doesn't do any checks or relative path
+ // conversion. Also, don't error out if the cgroup already exists.
+ if err := os.Symlink(mc, filepath.Join(rootfs, m.Destination, ss)); err != nil && !os.IsExist(err) {
+ return err
+ }
+ }
+ }
+ if m.Flags&syscall.MS_RDONLY != 0 {
+ // remount cgroup root as readonly
+ mcgrouproot := &configs.Mount{
+ Source: m.Destination,
+ Device: "bind",
+ Destination: m.Destination,
+ Flags: defaultMountFlags | syscall.MS_RDONLY | syscall.MS_BIND,
+ }
+ if err := remount(mcgrouproot, rootfs); err != nil {
+ return err
+ }
+ }
+ default:
+ // ensure that the destination of the mount is resolved of symlinks at mount time because
+ // any previous mounts can invalidate the next mount's destination.
+ // this can happen when a user specifies mounts within other mounts to cause breakouts or other
+ // evil stuff to try to escape the container's rootfs.
+ var err error
+ if dest, err = symlink.FollowSymlinkInScope(dest, rootfs); err != nil {
+ return err
+ }
+ if err := checkMountDestination(rootfs, dest); err != nil {
+ return err
+ }
+ // update the mount with the correct dest after symlinks are resolved.
+ m.Destination = dest
+ if err := os.MkdirAll(dest, 0755); err != nil {
+ return err
+ }
+ return mountPropagate(m, rootfs, mountLabel)
+ }
+ return nil
+}
+
+func getCgroupMounts(m *configs.Mount) ([]*configs.Mount, error) {
+ mounts, err := cgroups.GetCgroupMounts(false)
+ if err != nil {
+ return nil, err
+ }
+
+ cgroupPaths, err := cgroups.ParseCgroupFile("/proc/self/cgroup")
+ if err != nil {
+ return nil, err
+ }
+
+ var binds []*configs.Mount
+
+ for _, mm := range mounts {
+ dir, err := mm.GetOwnCgroup(cgroupPaths)
+ if err != nil {
+ return nil, err
+ }
+ relDir, err := filepath.Rel(mm.Root, dir)
+ if err != nil {
+ return nil, err
+ }
+ binds = append(binds, &configs.Mount{
+ Device: "bind",
+ Source: filepath.Join(mm.Mountpoint, relDir),
+ Destination: filepath.Join(m.Destination, filepath.Base(mm.Mountpoint)),
+ Flags: syscall.MS_BIND | syscall.MS_REC | m.Flags,
+ PropagationFlags: m.PropagationFlags,
+ })
+ }
+
+ return binds, nil
+}
+
+// checkMountDestination checks to ensure that the mount destination is not over the top of /proc.
+// dest is required to be an abs path and have any symlinks resolved before calling this function.
+func checkMountDestination(rootfs, dest string) error {
+ invalidDestinations := []string{
+ "/proc",
+ }
+ // White list, it should be sub directories of invalid destinations
+ validDestinations := []string{
+ // These entries can be bind mounted by files emulated by fuse,
+ // so commands like top, free displays stats in container.
+ "/proc/cpuinfo",
+ "/proc/diskstats",
+ "/proc/meminfo",
+ "/proc/stat",
+ "/proc/swaps",
+ "/proc/uptime",
+ "/proc/net/dev",
+ }
+ for _, valid := range validDestinations {
+ path, err := filepath.Rel(filepath.Join(rootfs, valid), dest)
+ if err != nil {
+ return err
+ }
+ if path == "." {
+ return nil
+ }
+ }
+ for _, invalid := range invalidDestinations {
+ path, err := filepath.Rel(filepath.Join(rootfs, invalid), dest)
+ if err != nil {
+ return err
+ }
+ if path == "." || !strings.HasPrefix(path, "..") {
+ return fmt.Errorf("%q cannot be mounted because it is located inside %q", dest, invalid)
+ }
+ }
+ return nil
+}
+
+func setupDevSymlinks(rootfs string) error {
+ var links = [][2]string{
+ {"/proc/self/fd", "/dev/fd"},
+ {"/proc/self/fd/0", "/dev/stdin"},
+ {"/proc/self/fd/1", "/dev/stdout"},
+ {"/proc/self/fd/2", "/dev/stderr"},
+ }
+ // kcore support can be toggled with CONFIG_PROC_KCORE; only create a symlink
+ // in /dev if it exists in /proc.
+ if _, err := os.Stat("/proc/kcore"); err == nil {
+ links = append(links, [2]string{"/proc/kcore", "/dev/core"})
+ }
+ for _, link := range links {
+ var (
+ src = link[0]
+ dst = filepath.Join(rootfs, link[1])
+ )
+ if err := os.Symlink(src, dst); err != nil && !os.IsExist(err) {
+ return fmt.Errorf("symlink %s %s %s", src, dst, err)
+ }
+ }
+ return nil
+}
+
+// If stdin, stdout, and/or stderr are pointing to `/dev/null` in the parent's rootfs
+// this method will make them point to `/dev/null` in this container's rootfs. This
+// needs to be called after we chroot/pivot into the container's rootfs so that any
+// symlinks are resolved locally.
+func reOpenDevNull() error {
+ var stat, devNullStat syscall.Stat_t
+ file, err := os.OpenFile("/dev/null", os.O_RDWR, 0)
+ if err != nil {
+ return fmt.Errorf("Failed to open /dev/null - %s", err)
+ }
+ defer file.Close()
+ if err := syscall.Fstat(int(file.Fd()), &devNullStat); err != nil {
+ return err
+ }
+ for fd := 0; fd < 3; fd++ {
+ if err := syscall.Fstat(fd, &stat); err != nil {
+ return err
+ }
+ if stat.Rdev == devNullStat.Rdev {
+ // Close and re-open the fd.
+ if err := syscall.Dup3(int(file.Fd()), fd, 0); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// Create the device nodes in the container.
+func createDevices(config *configs.Config) error {
+ useBindMount := system.RunningInUserNS() || config.Namespaces.Contains(configs.NEWUSER)
+ oldMask := syscall.Umask(0000)
+ for _, node := range config.Devices {
+ // containers running in a user namespace are not allowed to mknod
+ // devices so we can just bind mount it from the host.
+ if err := createDeviceNode(config.Rootfs, node, useBindMount); err != nil {
+ syscall.Umask(oldMask)
+ return err
+ }
+ }
+ syscall.Umask(oldMask)
+ return nil
+}
+
+func bindMountDeviceNode(dest string, node *configs.Device) error {
+ f, err := os.Create(dest)
+ if err != nil && !os.IsExist(err) {
+ return err
+ }
+ if f != nil {
+ f.Close()
+ }
+ return syscall.Mount(node.Path, dest, "bind", syscall.MS_BIND, "")
+}
+
+// Creates the device node in the rootfs of the container.
+func createDeviceNode(rootfs string, node *configs.Device, bind bool) error {
+ dest := filepath.Join(rootfs, node.Path)
+ if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
+ return err
+ }
+
+ if bind {
+ return bindMountDeviceNode(dest, node)
+ }
+ if err := mknodDevice(dest, node); err != nil {
+ if os.IsExist(err) {
+ return nil
+ } else if os.IsPermission(err) {
+ return bindMountDeviceNode(dest, node)
+ }
+ return err
+ }
+ return nil
+}
+
+func mknodDevice(dest string, node *configs.Device) error {
+ fileMode := node.FileMode
+ switch node.Type {
+ case 'c', 'u':
+ fileMode |= syscall.S_IFCHR
+ case 'b':
+ fileMode |= syscall.S_IFBLK
+ case 'p':
+ fileMode |= syscall.S_IFIFO
+ default:
+ return fmt.Errorf("%c is not a valid device type for device %s", node.Type, node.Path)
+ }
+ if err := syscall.Mknod(dest, uint32(fileMode), node.Mkdev()); err != nil {
+ return err
+ }
+ return syscall.Chown(dest, int(node.Uid), int(node.Gid))
+}
+
+func getMountInfo(mountinfo []*mount.Info, dir string) *mount.Info {
+ for _, m := range mountinfo {
+ if m.Mountpoint == dir {
+ return m
+ }
+ }
+ return nil
+}
+
+// Get the parent mount point of directory passed in as argument. Also return
+// optional fields.
+func getParentMount(rootfs string) (string, string, error) {
+ var path string
+
+ mountinfos, err := mount.GetMounts()
+ if err != nil {
+ return "", "", err
+ }
+
+ mountinfo := getMountInfo(mountinfos, rootfs)
+ if mountinfo != nil {
+ return rootfs, mountinfo.Optional, nil
+ }
+
+ path = rootfs
+ for {
+ path = filepath.Dir(path)
+
+ mountinfo = getMountInfo(mountinfos, path)
+ if mountinfo != nil {
+ return path, mountinfo.Optional, nil
+ }
+
+ if path == "/" {
+ break
+ }
+ }
+
+ // If we are here, we did not find parent mount. Something is wrong.
+ return "", "", fmt.Errorf("Could not find parent mount of %s", rootfs)
+}
+
+// Make parent mount private if it was shared
+func rootfsParentMountPrivate(rootfs string) error {
+ sharedMount := false
+
+ parentMount, optionalOpts, err := getParentMount(rootfs)
+ if err != nil {
+ return err
+ }
+
+ optsSplit := strings.Split(optionalOpts, " ")
+ for _, opt := range optsSplit {
+ if strings.HasPrefix(opt, "shared:") {
+ sharedMount = true
+ break
+ }
+ }
+
+ // Make parent mount PRIVATE if it was shared. It is needed for two
+ // reasons. First of all pivot_root() will fail if parent mount is
+ // shared. Secondly when we bind mount rootfs it will propagate to
+ // parent namespace and we don't want that to happen.
+ if sharedMount {
+ return syscall.Mount("", parentMount, "", syscall.MS_PRIVATE, "")
+ }
+
+ return nil
+}
+
+func prepareRoot(config *configs.Config) error {
+ flag := syscall.MS_SLAVE | syscall.MS_REC
+ if config.RootPropagation != 0 {
+ flag = config.RootPropagation
+ }
+ if err := syscall.Mount("", "/", "", uintptr(flag), ""); err != nil {
+ return err
+ }
+
+ // Make parent mount private to make sure following bind mount does
+ // not propagate in other namespaces. Also it will help with kernel
+ // check pass in pivot_root. (IS_SHARED(new_mnt->mnt_parent))
+ if err := rootfsParentMountPrivate(config.Rootfs); err != nil {
+ return err
+ }
+
+ return syscall.Mount(config.Rootfs, config.Rootfs, "bind", syscall.MS_BIND|syscall.MS_REC, "")
+}
+
+func setReadonly() error {
+ return syscall.Mount("/", "/", "bind", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC, "")
+}
+
+func setupPtmx(config *configs.Config) error {
+ ptmx := filepath.Join(config.Rootfs, "dev/ptmx")
+ if err := os.Remove(ptmx); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ if err := os.Symlink("pts/ptmx", ptmx); err != nil {
+ return fmt.Errorf("symlink dev ptmx %s", err)
+ }
+ return nil
+}
+
+// pivotRoot will call pivot_root such that rootfs becomes the new root
+// filesystem, and everything else is cleaned up.
+func pivotRoot(rootfs string) error {
+ // While the documentation may claim otherwise, pivot_root(".", ".") is
+ // actually valid. What this results in is / being the new root but
+ // /proc/self/cwd being the old root. Since we can play around with the cwd
+ // with pivot_root this allows us to pivot without creating directories in
+ // the rootfs. Shout-outs to the LXC developers for giving us this idea.
+
+ oldroot, err := syscall.Open("/", syscall.O_DIRECTORY|syscall.O_RDONLY, 0)
+ if err != nil {
+ return err
+ }
+ defer syscall.Close(oldroot)
+
+ newroot, err := syscall.Open(rootfs, syscall.O_DIRECTORY|syscall.O_RDONLY, 0)
+ if err != nil {
+ return err
+ }
+ defer syscall.Close(newroot)
+
+ // Change to the new root so that the pivot_root actually acts on it.
+ if err := syscall.Fchdir(newroot); err != nil {
+ return err
+ }
+
+ if err := syscall.PivotRoot(".", "."); err != nil {
+ return fmt.Errorf("pivot_root %s", err)
+ }
+
+ // Currently our "." is oldroot (according to the current kernel code).
+ // However, purely for safety, we will fchdir(oldroot) since there isn't
+ // really any guarantee from the kernel what /proc/self/cwd will be after a
+ // pivot_root(2).
+
+ if err := syscall.Fchdir(oldroot); err != nil {
+ return err
+ }
+
+ // Make oldroot rprivate to make sure our unmounts don't propagate to the
+ // host (and thus bork the machine).
+ if err := syscall.Mount("", ".", "", syscall.MS_PRIVATE|syscall.MS_REC, ""); err != nil {
+ return err
+ }
+ // Preform the unmount. MNT_DETACH allows us to unmount /proc/self/cwd.
+ if err := syscall.Unmount(".", syscall.MNT_DETACH); err != nil {
+ return err
+ }
+
+ // Switch back to our shiny new root.
+ if err := syscall.Chdir("/"); err != nil {
+ return fmt.Errorf("chdir / %s", err)
+ }
+ return nil
+}
+
+func msMoveRoot(rootfs string) error {
+ if err := syscall.Mount(rootfs, "/", "", syscall.MS_MOVE, ""); err != nil {
+ return err
+ }
+ if err := syscall.Chroot("."); err != nil {
+ return err
+ }
+ return syscall.Chdir("/")
+}
+
+// createIfNotExists creates a file or a directory only if it does not already exist.
+func createIfNotExists(path string, isDir bool) error {
+ if _, err := os.Stat(path); err != nil {
+ if os.IsNotExist(err) {
+ if isDir {
+ return os.MkdirAll(path, 0755)
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return err
+ }
+ f, err := os.OpenFile(path, os.O_CREATE, 0755)
+ if err != nil {
+ return err
+ }
+ f.Close()
+ }
+ }
+ return nil
+}
+
+// readonlyPath will make a path read only.
+func readonlyPath(path string) error {
+ if err := syscall.Mount(path, path, "", syscall.MS_BIND|syscall.MS_REC, ""); err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+ }
+ return syscall.Mount(path, path, "", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC, "")
+}
+
+// remountReadonly will remount an existing mount point and ensure that it is read-only.
+func remountReadonly(m *configs.Mount) error {
+ var (
+ dest = m.Destination
+ flags = m.Flags
+ )
+ for i := 0; i < 5; i++ {
+ if err := syscall.Mount("", dest, "", uintptr(flags|syscall.MS_REMOUNT|syscall.MS_RDONLY), ""); err != nil {
+ switch err {
+ case syscall.EBUSY:
+ time.Sleep(100 * time.Millisecond)
+ continue
+ default:
+ return err
+ }
+ }
+ return nil
+ }
+ return fmt.Errorf("unable to mount %s as readonly max retries reached", dest)
+}
+
+// maskPath masks the top of the specified path inside a container to avoid
+// security issues from processes reading information from non-namespace aware
+// mounts ( proc/kcore ).
+// For files, maskPath bind mounts /dev/null over the top of the specified path.
+// For directories, maskPath mounts read-only tmpfs over the top of the specified path.
+func maskPath(path string) error {
+ if err := syscall.Mount("/dev/null", path, "", syscall.MS_BIND, ""); err != nil && !os.IsNotExist(err) {
+ if err == syscall.ENOTDIR {
+ return syscall.Mount("tmpfs", path, "tmpfs", syscall.MS_RDONLY, "")
+ }
+ return err
+ }
+ return nil
+}
+
+// writeSystemProperty writes the value to a path under /proc/sys as determined from the key.
+// For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
+func writeSystemProperty(key, value string) error {
+ keyPath := strings.Replace(key, ".", "/", -1)
+ return ioutil.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0644)
+}
+
+func remount(m *configs.Mount, rootfs string) error {
+ var (
+ dest = m.Destination
+ )
+ if !strings.HasPrefix(dest, rootfs) {
+ dest = filepath.Join(rootfs, dest)
+ }
+ if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags|syscall.MS_REMOUNT), ""); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Do the mount operation followed by additional mounts required to take care
+// of propagation flags.
+func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error {
+ var (
+ dest = m.Destination
+ data = label.FormatMountLabel(m.Data, mountLabel)
+ flags = m.Flags
+ )
+ if libcontainerUtils.CleanPath(dest) == "/dev" {
+ flags &= ^syscall.MS_RDONLY
+ }
+
+ copyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP
+ if !(copyUp || strings.HasPrefix(dest, rootfs)) {
+ dest = filepath.Join(rootfs, dest)
+ }
+
+ if err := syscall.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil {
+ return err
+ }
+
+ for _, pflag := range m.PropagationFlags {
+ if err := syscall.Mount("", dest, "", uintptr(pflag), ""); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/seccomp/config.go b/vendor/github.com/opencontainers/runc/libcontainer/seccomp/config.go
new file mode 100644
index 0000000..ded5a6b
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/seccomp/config.go
@@ -0,0 +1,76 @@
+package seccomp
+
+import (
+ "fmt"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+var operators = map[string]configs.Operator{
+ "SCMP_CMP_NE": configs.NotEqualTo,
+ "SCMP_CMP_LT": configs.LessThan,
+ "SCMP_CMP_LE": configs.LessThanOrEqualTo,
+ "SCMP_CMP_EQ": configs.EqualTo,
+ "SCMP_CMP_GE": configs.GreaterThanOrEqualTo,
+ "SCMP_CMP_GT": configs.GreaterThan,
+ "SCMP_CMP_MASKED_EQ": configs.MaskEqualTo,
+}
+
+var actions = map[string]configs.Action{
+ "SCMP_ACT_KILL": configs.Kill,
+ "SCMP_ACT_ERRNO": configs.Errno,
+ "SCMP_ACT_TRAP": configs.Trap,
+ "SCMP_ACT_ALLOW": configs.Allow,
+ "SCMP_ACT_TRACE": configs.Trace,
+}
+
+var archs = map[string]string{
+ "SCMP_ARCH_X86": "x86",
+ "SCMP_ARCH_X86_64": "amd64",
+ "SCMP_ARCH_X32": "x32",
+ "SCMP_ARCH_ARM": "arm",
+ "SCMP_ARCH_AARCH64": "arm64",
+ "SCMP_ARCH_MIPS": "mips",
+ "SCMP_ARCH_MIPS64": "mips64",
+ "SCMP_ARCH_MIPS64N32": "mips64n32",
+ "SCMP_ARCH_MIPSEL": "mipsel",
+ "SCMP_ARCH_MIPSEL64": "mipsel64",
+ "SCMP_ARCH_MIPSEL64N32": "mipsel64n32",
+ "SCMP_ARCH_PPC": "ppc",
+ "SCMP_ARCH_PPC64": "ppc64",
+ "SCMP_ARCH_PPC64LE": "ppc64le",
+ "SCMP_ARCH_S390": "s390",
+ "SCMP_ARCH_S390X": "s390x",
+}
+
+// ConvertStringToOperator converts a string into a Seccomp comparison operator.
+// Comparison operators use the names they are assigned by Libseccomp's header.
+// Attempting to convert a string that is not a valid operator results in an
+// error.
+func ConvertStringToOperator(in string) (configs.Operator, error) {
+ if op, ok := operators[in]; ok == true {
+ return op, nil
+ }
+ return 0, fmt.Errorf("string %s is not a valid operator for seccomp", in)
+}
+
+// ConvertStringToAction converts a string into a Seccomp rule match action.
+// Actions use the names they are assigned in Libseccomp's header, though some
+// (notable, SCMP_ACT_TRACE) are not available in this implementation and will
+// return errors.
+// Attempting to convert a string that is not a valid action results in an
+// error.
+func ConvertStringToAction(in string) (configs.Action, error) {
+ if act, ok := actions[in]; ok == true {
+ return act, nil
+ }
+ return 0, fmt.Errorf("string %s is not a valid action for seccomp", in)
+}
+
+// ConvertStringToArch converts a string into a Seccomp comparison arch.
+func ConvertStringToArch(in string) (string, error) {
+ if arch, ok := archs[in]; ok == true {
+ return arch, nil
+ }
+ return "", fmt.Errorf("string %s is not a valid arch for seccomp", in)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go
new file mode 100644
index 0000000..518d2c3
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go
@@ -0,0 +1,229 @@
+// +build linux,cgo,seccomp
+
+package seccomp
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "strings"
+ "syscall"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+ libseccomp "github.com/seccomp/libseccomp-golang"
+)
+
+var (
+ actAllow = libseccomp.ActAllow
+ actTrap = libseccomp.ActTrap
+ actKill = libseccomp.ActKill
+ actTrace = libseccomp.ActTrace.SetReturnCode(int16(syscall.EPERM))
+ actErrno = libseccomp.ActErrno.SetReturnCode(int16(syscall.EPERM))
+
+ // SeccompModeFilter refers to the syscall argument SECCOMP_MODE_FILTER.
+ SeccompModeFilter = uintptr(2)
+)
+
+// Filters given syscalls in a container, preventing them from being used
+// Started in the container init process, and carried over to all child processes
+// Setns calls, however, require a separate invocation, as they are not children
+// of the init until they join the namespace
+func InitSeccomp(config *configs.Seccomp) error {
+ if config == nil {
+ return fmt.Errorf("cannot initialize Seccomp - nil config passed")
+ }
+
+ defaultAction, err := getAction(config.DefaultAction)
+ if err != nil {
+ return fmt.Errorf("error initializing seccomp - invalid default action")
+ }
+
+ filter, err := libseccomp.NewFilter(defaultAction)
+ if err != nil {
+ return fmt.Errorf("error creating filter: %s", err)
+ }
+
+ // Add extra architectures
+ for _, arch := range config.Architectures {
+ scmpArch, err := libseccomp.GetArchFromString(arch)
+ if err != nil {
+ return err
+ }
+
+ if err := filter.AddArch(scmpArch); err != nil {
+ return err
+ }
+ }
+
+ // Unset no new privs bit
+ if err := filter.SetNoNewPrivsBit(false); err != nil {
+ return fmt.Errorf("error setting no new privileges: %s", err)
+ }
+
+ // Add a rule for each syscall
+ for _, call := range config.Syscalls {
+ if call == nil {
+ return fmt.Errorf("encountered nil syscall while initializing Seccomp")
+ }
+
+ if err = matchCall(filter, call); err != nil {
+ return err
+ }
+ }
+
+ if err = filter.Load(); err != nil {
+ return fmt.Errorf("error loading seccomp filter into kernel: %s", err)
+ }
+
+ return nil
+}
+
+// IsEnabled returns if the kernel has been configured to support seccomp.
+func IsEnabled() bool {
+ // Try to read from /proc/self/status for kernels > 3.8
+ s, err := parseStatusFile("/proc/self/status")
+ if err != nil {
+ // Check if Seccomp is supported, via CONFIG_SECCOMP.
+ if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_GET_SECCOMP, 0, 0); err != syscall.EINVAL {
+ // Make sure the kernel has CONFIG_SECCOMP_FILTER.
+ if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_SECCOMP, SeccompModeFilter, 0); err != syscall.EINVAL {
+ return true
+ }
+ }
+ return false
+ }
+ _, ok := s["Seccomp"]
+ return ok
+}
+
+// Convert Libcontainer Action to Libseccomp ScmpAction
+func getAction(act configs.Action) (libseccomp.ScmpAction, error) {
+ switch act {
+ case configs.Kill:
+ return actKill, nil
+ case configs.Errno:
+ return actErrno, nil
+ case configs.Trap:
+ return actTrap, nil
+ case configs.Allow:
+ return actAllow, nil
+ case configs.Trace:
+ return actTrace, nil
+ default:
+ return libseccomp.ActInvalid, fmt.Errorf("invalid action, cannot use in rule")
+ }
+}
+
+// Convert Libcontainer Operator to Libseccomp ScmpCompareOp
+func getOperator(op configs.Operator) (libseccomp.ScmpCompareOp, error) {
+ switch op {
+ case configs.EqualTo:
+ return libseccomp.CompareEqual, nil
+ case configs.NotEqualTo:
+ return libseccomp.CompareNotEqual, nil
+ case configs.GreaterThan:
+ return libseccomp.CompareGreater, nil
+ case configs.GreaterThanOrEqualTo:
+ return libseccomp.CompareGreaterEqual, nil
+ case configs.LessThan:
+ return libseccomp.CompareLess, nil
+ case configs.LessThanOrEqualTo:
+ return libseccomp.CompareLessOrEqual, nil
+ case configs.MaskEqualTo:
+ return libseccomp.CompareMaskedEqual, nil
+ default:
+ return libseccomp.CompareInvalid, fmt.Errorf("invalid operator, cannot use in rule")
+ }
+}
+
+// Convert Libcontainer Arg to Libseccomp ScmpCondition
+func getCondition(arg *configs.Arg) (libseccomp.ScmpCondition, error) {
+ cond := libseccomp.ScmpCondition{}
+
+ if arg == nil {
+ return cond, fmt.Errorf("cannot convert nil to syscall condition")
+ }
+
+ op, err := getOperator(arg.Op)
+ if err != nil {
+ return cond, err
+ }
+
+ return libseccomp.MakeCondition(arg.Index, op, arg.Value, arg.ValueTwo)
+}
+
+// Add a rule to match a single syscall
+func matchCall(filter *libseccomp.ScmpFilter, call *configs.Syscall) error {
+ if call == nil || filter == nil {
+ return fmt.Errorf("cannot use nil as syscall to block")
+ }
+
+ if len(call.Name) == 0 {
+ return fmt.Errorf("empty string is not a valid syscall")
+ }
+
+ // If we can't resolve the syscall, assume it's not supported on this kernel
+ // Ignore it, don't error out
+ callNum, err := libseccomp.GetSyscallFromName(call.Name)
+ if err != nil {
+ return nil
+ }
+
+ // Convert the call's action to the libseccomp equivalent
+ callAct, err := getAction(call.Action)
+ if err != nil {
+ return err
+ }
+
+ // Unconditional match - just add the rule
+ if len(call.Args) == 0 {
+ if err = filter.AddRule(callNum, callAct); err != nil {
+ return err
+ }
+ } else {
+ // Conditional match - convert the per-arg rules into library format
+ conditions := []libseccomp.ScmpCondition{}
+
+ for _, cond := range call.Args {
+ newCond, err := getCondition(cond)
+ if err != nil {
+ return err
+ }
+
+ conditions = append(conditions, newCond)
+ }
+
+ if err = filter.AddRuleConditional(callNum, callAct, conditions); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func parseStatusFile(path string) (map[string]string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ s := bufio.NewScanner(f)
+ status := make(map[string]string)
+
+ for s.Scan() {
+ text := s.Text()
+ parts := strings.Split(text, ":")
+
+ if len(parts) <= 1 {
+ continue
+ }
+
+ status[parts[0]] = parts[1]
+ }
+ if err := s.Err(); err != nil {
+ return nil, err
+ }
+
+ return status, nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_unsupported.go
new file mode 100644
index 0000000..44df1ad
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_unsupported.go
@@ -0,0 +1,24 @@
+// +build !linux !cgo !seccomp
+
+package seccomp
+
+import (
+ "errors"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+)
+
+var ErrSeccompNotEnabled = errors.New("seccomp: config provided but seccomp not supported")
+
+// InitSeccomp does nothing because seccomp is not supported.
+func InitSeccomp(config *configs.Seccomp) error {
+ if config != nil {
+ return ErrSeccompNotEnabled
+ }
+ return nil
+}
+
+// IsEnabled returns false, because it is not supported.
+func IsEnabled() bool {
+ return false
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/setgroups_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/setgroups_linux.go
new file mode 100644
index 0000000..c7bdb60
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/setgroups_linux.go
@@ -0,0 +1,11 @@
+// +build linux,go1.5
+
+package libcontainer
+
+import "syscall"
+
+// Set the GidMappingsEnableSetgroups member to true, so the process's
+// setgroups proc entry wont be set to 'deny' if GidMappings are set
+func enableSetgroups(sys *syscall.SysProcAttr) {
+ sys.GidMappingsEnableSetgroups = true
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go
new file mode 100644
index 0000000..48cc0ae
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go
@@ -0,0 +1,63 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/opencontainers/runc/libcontainer/apparmor"
+ "github.com/opencontainers/runc/libcontainer/keys"
+ "github.com/opencontainers/runc/libcontainer/seccomp"
+ "github.com/opencontainers/runc/libcontainer/system"
+ "github.com/opencontainers/selinux/go-selinux/label"
+)
+
+// linuxSetnsInit performs the container's initialization for running a new process
+// inside an existing container.
+type linuxSetnsInit struct {
+ pipe *os.File
+ consoleSocket *os.File
+ config *initConfig
+}
+
+func (l *linuxSetnsInit) getSessionRingName() string {
+ return fmt.Sprintf("_ses.%s", l.config.ContainerId)
+}
+
+func (l *linuxSetnsInit) Init() error {
+ if !l.config.Config.NoNewKeyring {
+ // do not inherit the parent's session keyring
+ if _, err := keys.JoinSessionKeyring(l.getSessionRingName()); err != nil {
+ return err
+ }
+ }
+ if l.config.CreateConsole {
+ if err := setupConsole(l.consoleSocket, l.config, false); err != nil {
+ return err
+ }
+ if err := system.Setctty(); err != nil {
+ return err
+ }
+ }
+ if l.config.NoNewPrivileges {
+ if err := system.Prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil {
+ return err
+ }
+ }
+ if l.config.Config.Seccomp != nil {
+ if err := seccomp.InitSeccomp(l.config.Config.Seccomp); err != nil {
+ return err
+ }
+ }
+ if err := finalizeNamespace(l.config); err != nil {
+ return err
+ }
+ if err := apparmor.ApplyProfile(l.config.AppArmorProfile); err != nil {
+ return err
+ }
+ if err := label.SetProcessLabel(l.config.ProcessLabel); err != nil {
+ return err
+ }
+ return system.Execv(l.config.Args[0], l.config.Args[0:], os.Environ())
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/specconv/example.go b/vendor/github.com/opencontainers/runc/libcontainer/specconv/example.go
new file mode 100644
index 0000000..9a4460c
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/specconv/example.go
@@ -0,0 +1,227 @@
+package specconv
+
+import (
+ "os"
+ "runtime"
+ "strings"
+
+ "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+func sPtr(s string) *string { return &s }
+
+// Example returns an example spec file, with many options set so a user can
+// see what a standard spec file looks like.
+func Example() *specs.Spec {
+ return &specs.Spec{
+ Version: specs.Version,
+ Platform: specs.Platform{
+ OS: runtime.GOOS,
+ Arch: runtime.GOARCH,
+ },
+ Root: specs.Root{
+ Path: "rootfs",
+ Readonly: true,
+ },
+ Process: specs.Process{
+ Terminal: true,
+ User: specs.User{},
+ Args: []string{
+ "sh",
+ },
+ Env: []string{
+ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
+ "TERM=xterm",
+ },
+ Cwd: "/",
+ NoNewPrivileges: true,
+ Capabilities: &specs.LinuxCapabilities{
+ Bounding: []string{
+ "CAP_AUDIT_WRITE",
+ "CAP_KILL",
+ "CAP_NET_BIND_SERVICE",
+ },
+ Permitted: []string{
+ "CAP_AUDIT_WRITE",
+ "CAP_KILL",
+ "CAP_NET_BIND_SERVICE",
+ },
+ Inheritable: []string{
+ "CAP_AUDIT_WRITE",
+ "CAP_KILL",
+ "CAP_NET_BIND_SERVICE",
+ },
+ Ambient: []string{
+ "CAP_AUDIT_WRITE",
+ "CAP_KILL",
+ "CAP_NET_BIND_SERVICE",
+ },
+ Effective: []string{
+ "CAP_AUDIT_WRITE",
+ "CAP_KILL",
+ "CAP_NET_BIND_SERVICE",
+ },
+ },
+ Rlimits: []specs.LinuxRlimit{
+ {
+ Type: "RLIMIT_NOFILE",
+ Hard: uint64(1024),
+ Soft: uint64(1024),
+ },
+ },
+ },
+ Hostname: "runc",
+ Mounts: []specs.Mount{
+ {
+ Destination: "/proc",
+ Type: "proc",
+ Source: "proc",
+ Options: nil,
+ },
+ {
+ Destination: "/dev",
+ Type: "tmpfs",
+ Source: "tmpfs",
+ Options: []string{"nosuid", "strictatime", "mode=755", "size=65536k"},
+ },
+ {
+ Destination: "/dev/pts",
+ Type: "devpts",
+ Source: "devpts",
+ Options: []string{"nosuid", "noexec", "newinstance", "ptmxmode=0666", "mode=0620", "gid=5"},
+ },
+ {
+ Destination: "/dev/shm",
+ Type: "tmpfs",
+ Source: "shm",
+ Options: []string{"nosuid", "noexec", "nodev", "mode=1777", "size=65536k"},
+ },
+ {
+ Destination: "/dev/mqueue",
+ Type: "mqueue",
+ Source: "mqueue",
+ Options: []string{"nosuid", "noexec", "nodev"},
+ },
+ {
+ Destination: "/sys",
+ Type: "sysfs",
+ Source: "sysfs",
+ Options: []string{"nosuid", "noexec", "nodev", "ro"},
+ },
+ {
+ Destination: "/sys/fs/cgroup",
+ Type: "cgroup",
+ Source: "cgroup",
+ Options: []string{"nosuid", "noexec", "nodev", "relatime", "ro"},
+ },
+ },
+ Linux: &specs.Linux{
+ MaskedPaths: []string{
+ "/proc/kcore",
+ "/proc/latency_stats",
+ "/proc/timer_list",
+ "/proc/timer_stats",
+ "/proc/sched_debug",
+ "/sys/firmware",
+ },
+ ReadonlyPaths: []string{
+ "/proc/asound",
+ "/proc/bus",
+ "/proc/fs",
+ "/proc/irq",
+ "/proc/sys",
+ "/proc/sysrq-trigger",
+ },
+ Resources: &specs.LinuxResources{
+ Devices: []specs.LinuxDeviceCgroup{
+ {
+ Allow: false,
+ Access: "rwm",
+ },
+ },
+ },
+ Namespaces: []specs.LinuxNamespace{
+ {
+ Type: "pid",
+ },
+ {
+ Type: "network",
+ },
+ {
+ Type: "ipc",
+ },
+ {
+ Type: "uts",
+ },
+ {
+ Type: "mount",
+ },
+ },
+ },
+ }
+}
+
+// ExampleRootless returns an example spec file that works with rootless
+// containers. It's essentially a modified version of the specfile from
+// Example().
+func ToRootless(spec *specs.Spec) {
+ var namespaces []specs.LinuxNamespace
+
+ // Remove networkns from the spec.
+ for _, ns := range spec.Linux.Namespaces {
+ switch ns.Type {
+ case specs.NetworkNamespace, specs.UserNamespace:
+ // Do nothing.
+ default:
+ namespaces = append(namespaces, ns)
+ }
+ }
+ // Add userns to the spec.
+ namespaces = append(namespaces, specs.LinuxNamespace{
+ Type: specs.UserNamespace,
+ })
+ spec.Linux.Namespaces = namespaces
+
+ // Add mappings for the current user.
+ spec.Linux.UIDMappings = []specs.LinuxIDMapping{{
+ HostID: uint32(os.Geteuid()),
+ ContainerID: 0,
+ Size: 1,
+ }}
+ spec.Linux.GIDMappings = []specs.LinuxIDMapping{{
+ HostID: uint32(os.Getegid()),
+ ContainerID: 0,
+ Size: 1,
+ }}
+
+ // Fix up mounts.
+ var mounts []specs.Mount
+ for _, mount := range spec.Mounts {
+ // Ignore all mounts that are under /sys.
+ if strings.HasPrefix(mount.Destination, "/sys") {
+ continue
+ }
+
+ // Remove all gid= and uid= mappings.
+ var options []string
+ for _, option := range mount.Options {
+ if !strings.HasPrefix(option, "gid=") && !strings.HasPrefix(option, "uid=") {
+ options = append(options, option)
+ }
+ }
+
+ mount.Options = options
+ mounts = append(mounts, mount)
+ }
+ // Add the sysfs mount as an rbind.
+ mounts = append(mounts, specs.Mount{
+ Source: "/sys",
+ Destination: "/sys",
+ Type: "none",
+ Options: []string{"rbind", "nosuid", "noexec", "nodev", "ro"},
+ })
+ spec.Mounts = mounts
+
+ // Remove cgroup settings.
+ spec.Linux.Resources = nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/specconv/spec_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/specconv/spec_linux.go
new file mode 100644
index 0000000..1575ae0
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/specconv/spec_linux.go
@@ -0,0 +1,805 @@
+// +build linux
+
+// Package specconv implements conversion of specifications to libcontainer
+// configurations
+package specconv
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/seccomp"
+ libcontainerUtils "github.com/opencontainers/runc/libcontainer/utils"
+ "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+const wildcard = -1
+
+var namespaceMapping = map[specs.LinuxNamespaceType]configs.NamespaceType{
+ specs.PIDNamespace: configs.NEWPID,
+ specs.NetworkNamespace: configs.NEWNET,
+ specs.MountNamespace: configs.NEWNS,
+ specs.UserNamespace: configs.NEWUSER,
+ specs.IPCNamespace: configs.NEWIPC,
+ specs.UTSNamespace: configs.NEWUTS,
+}
+
+var mountPropagationMapping = map[string]int{
+ "rprivate": syscall.MS_PRIVATE | syscall.MS_REC,
+ "private": syscall.MS_PRIVATE,
+ "rslave": syscall.MS_SLAVE | syscall.MS_REC,
+ "slave": syscall.MS_SLAVE,
+ "rshared": syscall.MS_SHARED | syscall.MS_REC,
+ "shared": syscall.MS_SHARED,
+ "": syscall.MS_PRIVATE | syscall.MS_REC,
+}
+
+var allowedDevices = []*configs.Device{
+ // allow mknod for any device
+ {
+ Type: 'c',
+ Major: wildcard,
+ Minor: wildcard,
+ Permissions: "m",
+ Allow: true,
+ },
+ {
+ Type: 'b',
+ Major: wildcard,
+ Minor: wildcard,
+ Permissions: "m",
+ Allow: true,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/null",
+ Major: 1,
+ Minor: 3,
+ Permissions: "rwm",
+ Allow: true,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/random",
+ Major: 1,
+ Minor: 8,
+ Permissions: "rwm",
+ Allow: true,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/full",
+ Major: 1,
+ Minor: 7,
+ Permissions: "rwm",
+ Allow: true,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/tty",
+ Major: 5,
+ Minor: 0,
+ Permissions: "rwm",
+ Allow: true,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/zero",
+ Major: 1,
+ Minor: 5,
+ Permissions: "rwm",
+ Allow: true,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/urandom",
+ Major: 1,
+ Minor: 9,
+ Permissions: "rwm",
+ Allow: true,
+ },
+ {
+ Path: "/dev/console",
+ Type: 'c',
+ Major: 5,
+ Minor: 1,
+ Permissions: "rwm",
+ Allow: true,
+ },
+ // /dev/pts/ - pts namespaces are "coming soon"
+ {
+ Path: "",
+ Type: 'c',
+ Major: 136,
+ Minor: wildcard,
+ Permissions: "rwm",
+ Allow: true,
+ },
+ {
+ Path: "",
+ Type: 'c',
+ Major: 5,
+ Minor: 2,
+ Permissions: "rwm",
+ Allow: true,
+ },
+ // tuntap
+ {
+ Path: "",
+ Type: 'c',
+ Major: 10,
+ Minor: 200,
+ Permissions: "rwm",
+ Allow: true,
+ },
+}
+
+type CreateOpts struct {
+ CgroupName string
+ UseSystemdCgroup bool
+ NoPivotRoot bool
+ NoNewKeyring bool
+ Spec *specs.Spec
+ Rootless bool
+}
+
+// CreateLibcontainerConfig creates a new libcontainer configuration from a
+// given specification and a cgroup name
+func CreateLibcontainerConfig(opts *CreateOpts) (*configs.Config, error) {
+ // runc's cwd will always be the bundle path
+ rcwd, err := os.Getwd()
+ if err != nil {
+ return nil, err
+ }
+ cwd, err := filepath.Abs(rcwd)
+ if err != nil {
+ return nil, err
+ }
+ spec := opts.Spec
+ rootfsPath := spec.Root.Path
+ if !filepath.IsAbs(rootfsPath) {
+ rootfsPath = filepath.Join(cwd, rootfsPath)
+ }
+ labels := []string{}
+ for k, v := range spec.Annotations {
+ labels = append(labels, fmt.Sprintf("%s=%s", k, v))
+ }
+ config := &configs.Config{
+ Rootfs: rootfsPath,
+ NoPivotRoot: opts.NoPivotRoot,
+ Readonlyfs: spec.Root.Readonly,
+ Hostname: spec.Hostname,
+ Labels: append(labels, fmt.Sprintf("bundle=%s", cwd)),
+ NoNewKeyring: opts.NoNewKeyring,
+ Rootless: opts.Rootless,
+ }
+
+ exists := false
+ if config.RootPropagation, exists = mountPropagationMapping[spec.Linux.RootfsPropagation]; !exists {
+ return nil, fmt.Errorf("rootfsPropagation=%v is not supported", spec.Linux.RootfsPropagation)
+ }
+
+ for _, ns := range spec.Linux.Namespaces {
+ t, exists := namespaceMapping[ns.Type]
+ if !exists {
+ return nil, fmt.Errorf("namespace %q does not exist", ns)
+ }
+ if config.Namespaces.Contains(t) {
+ return nil, fmt.Errorf("malformed spec file: duplicated ns %q", ns)
+ }
+ config.Namespaces.Add(t, ns.Path)
+ }
+ if config.Namespaces.Contains(configs.NEWNET) {
+ config.Networks = []*configs.Network{
+ {
+ Type: "loopback",
+ },
+ }
+ }
+ for _, m := range spec.Mounts {
+ config.Mounts = append(config.Mounts, createLibcontainerMount(cwd, m))
+ }
+ if err := createDevices(spec, config); err != nil {
+ return nil, err
+ }
+ if err := setupUserNamespace(spec, config); err != nil {
+ return nil, err
+ }
+ c, err := createCgroupConfig(opts)
+ if err != nil {
+ return nil, err
+ }
+ config.Cgroups = c
+ // set extra path masking for libcontainer for the various unsafe places in proc
+ config.MaskPaths = spec.Linux.MaskedPaths
+ config.ReadonlyPaths = spec.Linux.ReadonlyPaths
+ if spec.Linux.Seccomp != nil {
+ seccomp, err := setupSeccomp(spec.Linux.Seccomp)
+ if err != nil {
+ return nil, err
+ }
+ config.Seccomp = seccomp
+ }
+ if spec.Process.SelinuxLabel != "" {
+ config.ProcessLabel = spec.Process.SelinuxLabel
+ }
+ config.Sysctl = spec.Linux.Sysctl
+ if spec.Linux.Resources != nil && spec.Linux.Resources.OOMScoreAdj != nil {
+ config.OomScoreAdj = *spec.Linux.Resources.OOMScoreAdj
+ }
+ if spec.Process.Capabilities != nil {
+ config.Capabilities = &configs.Capabilities{
+ Bounding: spec.Process.Capabilities.Bounding,
+ Effective: spec.Process.Capabilities.Effective,
+ Permitted: spec.Process.Capabilities.Permitted,
+ Inheritable: spec.Process.Capabilities.Inheritable,
+ Ambient: spec.Process.Capabilities.Ambient,
+ }
+ }
+ createHooks(spec, config)
+ config.MountLabel = spec.Linux.MountLabel
+ config.Version = specs.Version
+ return config, nil
+}
+
+func createLibcontainerMount(cwd string, m specs.Mount) *configs.Mount {
+ flags, pgflags, data, ext := parseMountOptions(m.Options)
+ source := m.Source
+ if m.Type == "bind" {
+ if !filepath.IsAbs(source) {
+ source = filepath.Join(cwd, m.Source)
+ }
+ }
+ return &configs.Mount{
+ Device: m.Type,
+ Source: source,
+ Destination: m.Destination,
+ Data: data,
+ Flags: flags,
+ PropagationFlags: pgflags,
+ Extensions: ext,
+ }
+}
+
+func createCgroupConfig(opts *CreateOpts) (*configs.Cgroup, error) {
+ var (
+ myCgroupPath string
+
+ spec = opts.Spec
+ useSystemdCgroup = opts.UseSystemdCgroup
+ name = opts.CgroupName
+ )
+
+ c := &configs.Cgroup{
+ Resources: &configs.Resources{},
+ }
+
+ if spec.Linux != nil && spec.Linux.CgroupsPath != "" {
+ myCgroupPath = libcontainerUtils.CleanPath(spec.Linux.CgroupsPath)
+ if useSystemdCgroup {
+ myCgroupPath = spec.Linux.CgroupsPath
+ }
+ }
+
+ if useSystemdCgroup {
+ if myCgroupPath == "" {
+ c.Parent = "system.slice"
+ c.ScopePrefix = "runc"
+ c.Name = name
+ } else {
+ // Parse the path from expected "slice:prefix:name"
+ // for e.g. "system.slice:docker:1234"
+ parts := strings.Split(myCgroupPath, ":")
+ if len(parts) != 3 {
+ return nil, fmt.Errorf("expected cgroupsPath to be of format \"slice:prefix:name\" for systemd cgroups")
+ }
+ c.Parent = parts[0]
+ c.ScopePrefix = parts[1]
+ c.Name = parts[2]
+ }
+ } else {
+ if myCgroupPath == "" {
+ c.Name = name
+ }
+ c.Path = myCgroupPath
+ }
+
+ // In rootless containers, any attempt to make cgroup changes will fail.
+ // libcontainer will validate this and we shouldn't add any cgroup options
+ // the user didn't specify.
+ if !opts.Rootless {
+ c.Resources.AllowedDevices = allowedDevices
+ if spec.Linux == nil {
+ return c, nil
+ }
+ }
+ r := spec.Linux.Resources
+ if r == nil {
+ return c, nil
+ }
+ for i, d := range spec.Linux.Resources.Devices {
+ var (
+ t = "a"
+ major = int64(-1)
+ minor = int64(-1)
+ )
+ if d.Type != "" {
+ t = d.Type
+ }
+ if d.Major != nil {
+ major = *d.Major
+ }
+ if d.Minor != nil {
+ minor = *d.Minor
+ }
+ if d.Access == "" {
+ return nil, fmt.Errorf("device access at %d field cannot be empty", i)
+ }
+ dt, err := stringToCgroupDeviceRune(t)
+ if err != nil {
+ return nil, err
+ }
+ dd := &configs.Device{
+ Type: dt,
+ Major: major,
+ Minor: minor,
+ Permissions: d.Access,
+ Allow: d.Allow,
+ }
+ c.Resources.Devices = append(c.Resources.Devices, dd)
+ }
+ if !opts.Rootless {
+ // append the default allowed devices to the end of the list
+ c.Resources.Devices = append(c.Resources.Devices, allowedDevices...)
+ }
+ if r.Memory != nil {
+ if r.Memory.Limit != nil {
+ c.Resources.Memory = *r.Memory.Limit
+ }
+ if r.Memory.Reservation != nil {
+ c.Resources.MemoryReservation = *r.Memory.Reservation
+ }
+ if r.Memory.Swap != nil {
+ c.Resources.MemorySwap = *r.Memory.Swap
+ }
+ if r.Memory.Kernel != nil {
+ c.Resources.KernelMemory = *r.Memory.Kernel
+ }
+ if r.Memory.KernelTCP != nil {
+ c.Resources.KernelMemoryTCP = *r.Memory.KernelTCP
+ }
+ if r.Memory.Swappiness != nil {
+ c.Resources.MemorySwappiness = r.Memory.Swappiness
+ }
+ }
+ if r.CPU != nil {
+ if r.CPU.Shares != nil {
+ c.Resources.CpuShares = *r.CPU.Shares
+ }
+ if r.CPU.Quota != nil {
+ c.Resources.CpuQuota = *r.CPU.Quota
+ }
+ if r.CPU.Period != nil {
+ c.Resources.CpuPeriod = *r.CPU.Period
+ }
+ if r.CPU.RealtimeRuntime != nil {
+ c.Resources.CpuRtRuntime = *r.CPU.RealtimeRuntime
+ }
+ if r.CPU.RealtimePeriod != nil {
+ c.Resources.CpuRtPeriod = *r.CPU.RealtimePeriod
+ }
+ if r.CPU.Cpus != "" {
+ c.Resources.CpusetCpus = r.CPU.Cpus
+ }
+ if r.CPU.Mems != "" {
+ c.Resources.CpusetMems = r.CPU.Mems
+ }
+ }
+ if r.Pids != nil {
+ c.Resources.PidsLimit = r.Pids.Limit
+ }
+ if r.BlockIO != nil {
+ if r.BlockIO.Weight != nil {
+ c.Resources.BlkioWeight = *r.BlockIO.Weight
+ }
+ if r.BlockIO.LeafWeight != nil {
+ c.Resources.BlkioLeafWeight = *r.BlockIO.LeafWeight
+ }
+ if r.BlockIO.WeightDevice != nil {
+ for _, wd := range r.BlockIO.WeightDevice {
+ var weight, leafWeight uint16
+ if wd.Weight != nil {
+ weight = *wd.Weight
+ }
+ if wd.LeafWeight != nil {
+ leafWeight = *wd.LeafWeight
+ }
+ weightDevice := configs.NewWeightDevice(wd.Major, wd.Minor, weight, leafWeight)
+ c.Resources.BlkioWeightDevice = append(c.Resources.BlkioWeightDevice, weightDevice)
+ }
+ }
+ if r.BlockIO.ThrottleReadBpsDevice != nil {
+ for _, td := range r.BlockIO.ThrottleReadBpsDevice {
+ rate := td.Rate
+ throttleDevice := configs.NewThrottleDevice(td.Major, td.Minor, rate)
+ c.Resources.BlkioThrottleReadBpsDevice = append(c.Resources.BlkioThrottleReadBpsDevice, throttleDevice)
+ }
+ }
+ if r.BlockIO.ThrottleWriteBpsDevice != nil {
+ for _, td := range r.BlockIO.ThrottleWriteBpsDevice {
+ rate := td.Rate
+ throttleDevice := configs.NewThrottleDevice(td.Major, td.Minor, rate)
+ c.Resources.BlkioThrottleWriteBpsDevice = append(c.Resources.BlkioThrottleWriteBpsDevice, throttleDevice)
+ }
+ }
+ if r.BlockIO.ThrottleReadIOPSDevice != nil {
+ for _, td := range r.BlockIO.ThrottleReadIOPSDevice {
+ rate := td.Rate
+ throttleDevice := configs.NewThrottleDevice(td.Major, td.Minor, rate)
+ c.Resources.BlkioThrottleReadIOPSDevice = append(c.Resources.BlkioThrottleReadIOPSDevice, throttleDevice)
+ }
+ }
+ if r.BlockIO.ThrottleWriteIOPSDevice != nil {
+ for _, td := range r.BlockIO.ThrottleWriteIOPSDevice {
+ rate := td.Rate
+ throttleDevice := configs.NewThrottleDevice(td.Major, td.Minor, rate)
+ c.Resources.BlkioThrottleWriteIOPSDevice = append(c.Resources.BlkioThrottleWriteIOPSDevice, throttleDevice)
+ }
+ }
+ }
+ for _, l := range r.HugepageLimits {
+ c.Resources.HugetlbLimit = append(c.Resources.HugetlbLimit, &configs.HugepageLimit{
+ Pagesize: l.Pagesize,
+ Limit: l.Limit,
+ })
+ }
+ if r.DisableOOMKiller != nil {
+ c.Resources.OomKillDisable = *r.DisableOOMKiller
+ }
+ if r.Network != nil {
+ if r.Network.ClassID != nil {
+ c.Resources.NetClsClassid = *r.Network.ClassID
+ }
+ for _, m := range r.Network.Priorities {
+ c.Resources.NetPrioIfpriomap = append(c.Resources.NetPrioIfpriomap, &configs.IfPrioMap{
+ Interface: m.Name,
+ Priority: int64(m.Priority),
+ })
+ }
+ }
+ return c, nil
+}
+
+func stringToCgroupDeviceRune(s string) (rune, error) {
+ switch s {
+ case "a":
+ return 'a', nil
+ case "b":
+ return 'b', nil
+ case "c":
+ return 'c', nil
+ default:
+ return 0, fmt.Errorf("invalid cgroup device type %q", s)
+ }
+}
+
+func stringToDeviceRune(s string) (rune, error) {
+ switch s {
+ case "p":
+ return 'p', nil
+ case "u":
+ return 'u', nil
+ case "b":
+ return 'b', nil
+ case "c":
+ return 'c', nil
+ default:
+ return 0, fmt.Errorf("invalid device type %q", s)
+ }
+}
+
+func createDevices(spec *specs.Spec, config *configs.Config) error {
+ // add whitelisted devices
+ config.Devices = []*configs.Device{
+ {
+ Type: 'c',
+ Path: "/dev/null",
+ Major: 1,
+ Minor: 3,
+ FileMode: 0666,
+ Uid: 0,
+ Gid: 0,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/random",
+ Major: 1,
+ Minor: 8,
+ FileMode: 0666,
+ Uid: 0,
+ Gid: 0,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/full",
+ Major: 1,
+ Minor: 7,
+ FileMode: 0666,
+ Uid: 0,
+ Gid: 0,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/tty",
+ Major: 5,
+ Minor: 0,
+ FileMode: 0666,
+ Uid: 0,
+ Gid: 0,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/zero",
+ Major: 1,
+ Minor: 5,
+ FileMode: 0666,
+ Uid: 0,
+ Gid: 0,
+ },
+ {
+ Type: 'c',
+ Path: "/dev/urandom",
+ Major: 1,
+ Minor: 9,
+ FileMode: 0666,
+ Uid: 0,
+ Gid: 0,
+ },
+ }
+ // merge in additional devices from the spec
+ for _, d := range spec.Linux.Devices {
+ var uid, gid uint32
+ var filemode os.FileMode = 0666
+
+ if d.UID != nil {
+ uid = *d.UID
+ }
+ if d.GID != nil {
+ gid = *d.GID
+ }
+ dt, err := stringToDeviceRune(d.Type)
+ if err != nil {
+ return err
+ }
+ if d.FileMode != nil {
+ filemode = *d.FileMode
+ }
+ device := &configs.Device{
+ Type: dt,
+ Path: d.Path,
+ Major: d.Major,
+ Minor: d.Minor,
+ FileMode: filemode,
+ Uid: uid,
+ Gid: gid,
+ }
+ config.Devices = append(config.Devices, device)
+ }
+ return nil
+}
+
+func setupUserNamespace(spec *specs.Spec, config *configs.Config) error {
+ if len(spec.Linux.UIDMappings) == 0 {
+ return nil
+ }
+ create := func(m specs.LinuxIDMapping) configs.IDMap {
+ return configs.IDMap{
+ HostID: int(m.HostID),
+ ContainerID: int(m.ContainerID),
+ Size: int(m.Size),
+ }
+ }
+ for _, m := range spec.Linux.UIDMappings {
+ config.UidMappings = append(config.UidMappings, create(m))
+ }
+ for _, m := range spec.Linux.GIDMappings {
+ config.GidMappings = append(config.GidMappings, create(m))
+ }
+ rootUID, err := config.HostRootUID()
+ if err != nil {
+ return err
+ }
+ rootGID, err := config.HostRootGID()
+ if err != nil {
+ return err
+ }
+ for _, node := range config.Devices {
+ node.Uid = uint32(rootUID)
+ node.Gid = uint32(rootGID)
+ }
+ return nil
+}
+
+// parseMountOptions parses the string and returns the flags, propagation
+// flags and any mount data that it contains.
+func parseMountOptions(options []string) (int, []int, string, int) {
+ var (
+ flag int
+ pgflag []int
+ data []string
+ extFlags int
+ )
+ flags := map[string]struct {
+ clear bool
+ flag int
+ }{
+ "async": {true, syscall.MS_SYNCHRONOUS},
+ "atime": {true, syscall.MS_NOATIME},
+ "bind": {false, syscall.MS_BIND},
+ "defaults": {false, 0},
+ "dev": {true, syscall.MS_NODEV},
+ "diratime": {true, syscall.MS_NODIRATIME},
+ "dirsync": {false, syscall.MS_DIRSYNC},
+ "exec": {true, syscall.MS_NOEXEC},
+ "mand": {false, syscall.MS_MANDLOCK},
+ "noatime": {false, syscall.MS_NOATIME},
+ "nodev": {false, syscall.MS_NODEV},
+ "nodiratime": {false, syscall.MS_NODIRATIME},
+ "noexec": {false, syscall.MS_NOEXEC},
+ "nomand": {true, syscall.MS_MANDLOCK},
+ "norelatime": {true, syscall.MS_RELATIME},
+ "nostrictatime": {true, syscall.MS_STRICTATIME},
+ "nosuid": {false, syscall.MS_NOSUID},
+ "rbind": {false, syscall.MS_BIND | syscall.MS_REC},
+ "relatime": {false, syscall.MS_RELATIME},
+ "remount": {false, syscall.MS_REMOUNT},
+ "ro": {false, syscall.MS_RDONLY},
+ "rw": {true, syscall.MS_RDONLY},
+ "strictatime": {false, syscall.MS_STRICTATIME},
+ "suid": {true, syscall.MS_NOSUID},
+ "sync": {false, syscall.MS_SYNCHRONOUS},
+ }
+ propagationFlags := map[string]int{
+ "private": syscall.MS_PRIVATE,
+ "shared": syscall.MS_SHARED,
+ "slave": syscall.MS_SLAVE,
+ "unbindable": syscall.MS_UNBINDABLE,
+ "rprivate": syscall.MS_PRIVATE | syscall.MS_REC,
+ "rshared": syscall.MS_SHARED | syscall.MS_REC,
+ "rslave": syscall.MS_SLAVE | syscall.MS_REC,
+ "runbindable": syscall.MS_UNBINDABLE | syscall.MS_REC,
+ }
+ extensionFlags := map[string]struct {
+ clear bool
+ flag int
+ }{
+ "tmpcopyup": {false, configs.EXT_COPYUP},
+ }
+ for _, o := range options {
+ // If the option does not exist in the flags table or the flag
+ // is not supported on the platform,
+ // then it is a data value for a specific fs type
+ if f, exists := flags[o]; exists && f.flag != 0 {
+ if f.clear {
+ flag &= ^f.flag
+ } else {
+ flag |= f.flag
+ }
+ } else if f, exists := propagationFlags[o]; exists && f != 0 {
+ pgflag = append(pgflag, f)
+ } else if f, exists := extensionFlags[o]; exists && f.flag != 0 {
+ if f.clear {
+ extFlags &= ^f.flag
+ } else {
+ extFlags |= f.flag
+ }
+ } else {
+ data = append(data, o)
+ }
+ }
+ return flag, pgflag, strings.Join(data, ","), extFlags
+}
+
+func setupSeccomp(config *specs.LinuxSeccomp) (*configs.Seccomp, error) {
+ if config == nil {
+ return nil, nil
+ }
+
+ // No default action specified, no syscalls listed, assume seccomp disabled
+ if config.DefaultAction == "" && len(config.Syscalls) == 0 {
+ return nil, nil
+ }
+
+ newConfig := new(configs.Seccomp)
+ newConfig.Syscalls = []*configs.Syscall{}
+
+ if len(config.Architectures) > 0 {
+ newConfig.Architectures = []string{}
+ for _, arch := range config.Architectures {
+ newArch, err := seccomp.ConvertStringToArch(string(arch))
+ if err != nil {
+ return nil, err
+ }
+ newConfig.Architectures = append(newConfig.Architectures, newArch)
+ }
+ }
+
+ // Convert default action from string representation
+ newDefaultAction, err := seccomp.ConvertStringToAction(string(config.DefaultAction))
+ if err != nil {
+ return nil, err
+ }
+ newConfig.DefaultAction = newDefaultAction
+
+ // Loop through all syscall blocks and convert them to libcontainer format
+ for _, call := range config.Syscalls {
+ newAction, err := seccomp.ConvertStringToAction(string(call.Action))
+ if err != nil {
+ return nil, err
+ }
+
+ for _, name := range call.Names {
+ newCall := configs.Syscall{
+ Name: name,
+ Action: newAction,
+ Args: []*configs.Arg{},
+ }
+ // Loop through all the arguments of the syscall and convert them
+ for _, arg := range call.Args {
+ newOp, err := seccomp.ConvertStringToOperator(string(arg.Op))
+ if err != nil {
+ return nil, err
+ }
+
+ newArg := configs.Arg{
+ Index: arg.Index,
+ Value: arg.Value,
+ ValueTwo: arg.ValueTwo,
+ Op: newOp,
+ }
+
+ newCall.Args = append(newCall.Args, &newArg)
+ }
+ newConfig.Syscalls = append(newConfig.Syscalls, &newCall)
+ }
+ }
+
+ return newConfig, nil
+}
+
+func createHooks(rspec *specs.Spec, config *configs.Config) {
+ config.Hooks = &configs.Hooks{}
+ if rspec.Hooks != nil {
+
+ for _, h := range rspec.Hooks.Prestart {
+ cmd := createCommandHook(h)
+ config.Hooks.Prestart = append(config.Hooks.Prestart, configs.NewCommandHook(cmd))
+ }
+ for _, h := range rspec.Hooks.Poststart {
+ cmd := createCommandHook(h)
+ config.Hooks.Poststart = append(config.Hooks.Poststart, configs.NewCommandHook(cmd))
+ }
+ for _, h := range rspec.Hooks.Poststop {
+ cmd := createCommandHook(h)
+ config.Hooks.Poststop = append(config.Hooks.Poststop, configs.NewCommandHook(cmd))
+ }
+ }
+}
+
+func createCommandHook(h specs.Hook) configs.Command {
+ cmd := configs.Command{
+ Path: h.Path,
+ Args: h.Args,
+ Env: h.Env,
+ }
+ if h.Timeout != nil {
+ d := time.Duration(*h.Timeout) * time.Second
+ cmd.Timeout = &d
+ }
+ return cmd
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/capture.go b/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/capture.go
new file mode 100644
index 0000000..0bbe149
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/capture.go
@@ -0,0 +1,27 @@
+package stacktrace
+
+import "runtime"
+
+// Capture captures a stacktrace for the current calling go program
+//
+// skip is the number of frames to skip
+func Capture(userSkip int) Stacktrace {
+ var (
+ skip = userSkip + 1 // add one for our own function
+ frames []Frame
+ prevPc uintptr
+ )
+ for i := skip; ; i++ {
+ pc, file, line, ok := runtime.Caller(i)
+ //detect if caller is repeated to avoid loop, gccgo
+ //currently runs into a loop without this check
+ if !ok || pc == prevPc {
+ break
+ }
+ frames = append(frames, NewFrame(pc, file, line))
+ prevPc = pc
+ }
+ return Stacktrace{
+ Frames: frames,
+ }
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/frame.go b/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/frame.go
new file mode 100644
index 0000000..0d590d9
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/frame.go
@@ -0,0 +1,38 @@
+package stacktrace
+
+import (
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+// NewFrame returns a new stack frame for the provided information
+func NewFrame(pc uintptr, file string, line int) Frame {
+ fn := runtime.FuncForPC(pc)
+ if fn == nil {
+ return Frame{}
+ }
+ pack, name := parseFunctionName(fn.Name())
+ return Frame{
+ Line: line,
+ File: filepath.Base(file),
+ Package: pack,
+ Function: name,
+ }
+}
+
+func parseFunctionName(name string) (string, string) {
+ i := strings.LastIndex(name, ".")
+ if i == -1 {
+ return "", name
+ }
+ return name[:i], name[i+1:]
+}
+
+// Frame contains all the information for a stack frame within a go program
+type Frame struct {
+ File string
+ Function string
+ Package string
+ Line int
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/stacktrace.go b/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/stacktrace.go
new file mode 100644
index 0000000..5e8b58d
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/stacktrace.go
@@ -0,0 +1,5 @@
+package stacktrace
+
+type Stacktrace struct {
+ Frames []Frame
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go
new file mode 100644
index 0000000..ee6f19a
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go
@@ -0,0 +1,190 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "syscall"
+
+ "github.com/opencontainers/runc/libcontainer/apparmor"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/keys"
+ "github.com/opencontainers/runc/libcontainer/seccomp"
+ "github.com/opencontainers/runc/libcontainer/system"
+ "github.com/opencontainers/selinux/go-selinux/label"
+)
+
+type linuxStandardInit struct {
+ pipe *os.File
+ consoleSocket *os.File
+ parentPid int
+ stateDirFD int
+ config *initConfig
+}
+
+func (l *linuxStandardInit) getSessionRingParams() (string, uint32, uint32) {
+ var newperms uint32
+
+ if l.config.Config.Namespaces.Contains(configs.NEWUSER) {
+ // with user ns we need 'other' search permissions
+ newperms = 0x8
+ } else {
+ // without user ns we need 'UID' search permissions
+ newperms = 0x80000
+ }
+
+ // create a unique per session container name that we can
+ // join in setns; however, other containers can also join it
+ return fmt.Sprintf("_ses.%s", l.config.ContainerId), 0xffffffff, newperms
+}
+
+// PR_SET_NO_NEW_PRIVS isn't exposed in Golang so we define it ourselves copying the value
+// the kernel
+const PR_SET_NO_NEW_PRIVS = 0x26
+
+func (l *linuxStandardInit) Init() error {
+ if !l.config.Config.NoNewKeyring {
+ ringname, keepperms, newperms := l.getSessionRingParams()
+
+ // do not inherit the parent's session keyring
+ sessKeyId, err := keys.JoinSessionKeyring(ringname)
+ if err != nil {
+ return err
+ }
+ // make session keyring searcheable
+ if err := keys.ModKeyringPerm(sessKeyId, keepperms, newperms); err != nil {
+ return err
+ }
+ }
+
+ if err := setupNetwork(l.config); err != nil {
+ return err
+ }
+ if err := setupRoute(l.config.Config); err != nil {
+ return err
+ }
+
+ label.Init()
+
+ // prepareRootfs() can be executed only for a new mount namespace.
+ if l.config.Config.Namespaces.Contains(configs.NEWNS) {
+ if err := prepareRootfs(l.pipe, l.config.Config); err != nil {
+ return err
+ }
+ }
+
+ // Set up the console. This has to be done *before* we finalize the rootfs,
+ // but *after* we've given the user the chance to set up all of the mounts
+ // they wanted.
+ if l.config.CreateConsole {
+ if err := setupConsole(l.consoleSocket, l.config, true); err != nil {
+ return err
+ }
+ if err := system.Setctty(); err != nil {
+ return err
+ }
+ }
+
+ // Finish the rootfs setup.
+ if l.config.Config.Namespaces.Contains(configs.NEWNS) {
+ if err := finalizeRootfs(l.config.Config); err != nil {
+ return err
+ }
+ }
+
+ if hostname := l.config.Config.Hostname; hostname != "" {
+ if err := syscall.Sethostname([]byte(hostname)); err != nil {
+ return err
+ }
+ }
+ if err := apparmor.ApplyProfile(l.config.AppArmorProfile); err != nil {
+ return err
+ }
+ if err := label.SetProcessLabel(l.config.ProcessLabel); err != nil {
+ return err
+ }
+
+ for key, value := range l.config.Config.Sysctl {
+ if err := writeSystemProperty(key, value); err != nil {
+ return err
+ }
+ }
+ for _, path := range l.config.Config.ReadonlyPaths {
+ if err := readonlyPath(path); err != nil {
+ return err
+ }
+ }
+ for _, path := range l.config.Config.MaskPaths {
+ if err := maskPath(path); err != nil {
+ return err
+ }
+ }
+ pdeath, err := system.GetParentDeathSignal()
+ if err != nil {
+ return err
+ }
+ if l.config.NoNewPrivileges {
+ if err := system.Prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil {
+ return err
+ }
+ }
+ // Tell our parent that we're ready to Execv. This must be done before the
+ // Seccomp rules have been applied, because we need to be able to read and
+ // write to a socket.
+ if err := syncParentReady(l.pipe); err != nil {
+ return err
+ }
+ // Without NoNewPrivileges seccomp is a privileged operation, so we need to
+ // do this before dropping capabilities; otherwise do it as late as possible
+ // just before execve so as few syscalls take place after it as possible.
+ if l.config.Config.Seccomp != nil && !l.config.NoNewPrivileges {
+ if err := seccomp.InitSeccomp(l.config.Config.Seccomp); err != nil {
+ return err
+ }
+ }
+ if err := finalizeNamespace(l.config); err != nil {
+ return err
+ }
+ // finalizeNamespace can change user/group which clears the parent death
+ // signal, so we restore it here.
+ if err := pdeath.Restore(); err != nil {
+ return err
+ }
+ // compare the parent from the initial start of the init process and make sure that it did not change.
+ // if the parent changes that means it died and we were reparented to something else so we should
+ // just kill ourself and not cause problems for someone else.
+ if syscall.Getppid() != l.parentPid {
+ return syscall.Kill(syscall.Getpid(), syscall.SIGKILL)
+ }
+ // check for the arg before waiting to make sure it exists and it is returned
+ // as a create time error.
+ name, err := exec.LookPath(l.config.Args[0])
+ if err != nil {
+ return err
+ }
+ // close the pipe to signal that we have completed our init.
+ l.pipe.Close()
+ // wait for the fifo to be opened on the other side before
+ // exec'ing the users process.
+ fd, err := syscall.Openat(l.stateDirFD, execFifoFilename, os.O_WRONLY|syscall.O_CLOEXEC, 0)
+ if err != nil {
+ return newSystemErrorWithCause(err, "openat exec fifo")
+ }
+ if _, err := syscall.Write(fd, []byte("0")); err != nil {
+ return newSystemErrorWithCause(err, "write 0 exec fifo")
+ }
+ if l.config.Config.Seccomp != nil && l.config.NoNewPrivileges {
+ if err := seccomp.InitSeccomp(l.config.Config.Seccomp); err != nil {
+ return newSystemErrorWithCause(err, "init seccomp")
+ }
+ }
+ // close the statedir fd before exec because the kernel resets dumpable in the wrong order
+ // https://github.com/torvalds/linux/blob/v4.9/fs/exec.c#L1290-L1318
+ syscall.Close(l.stateDirFD)
+ if err := syscall.Exec(name, l.config.Args[0:], os.Environ()); err != nil {
+ return newSystemErrorWithCause(err, "exec user process")
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/state_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/state_linux.go
new file mode 100644
index 0000000..62878ac
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/state_linux.go
@@ -0,0 +1,247 @@
+// +build linux
+
+package libcontainer
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/utils"
+)
+
+func newStateTransitionError(from, to containerState) error {
+ return &stateTransitionError{
+ From: from.status().String(),
+ To: to.status().String(),
+ }
+}
+
+// stateTransitionError is returned when an invalid state transition happens from one
+// state to another.
+type stateTransitionError struct {
+ From string
+ To string
+}
+
+func (s *stateTransitionError) Error() string {
+ return fmt.Sprintf("invalid state transition from %s to %s", s.From, s.To)
+}
+
+type containerState interface {
+ transition(containerState) error
+ destroy() error
+ status() Status
+}
+
+func destroy(c *linuxContainer) error {
+ if !c.config.Namespaces.Contains(configs.NEWPID) {
+ if err := signalAllProcesses(c.cgroupManager, syscall.SIGKILL); err != nil {
+ logrus.Warn(err)
+ }
+ }
+ err := c.cgroupManager.Destroy()
+ if rerr := os.RemoveAll(c.root); err == nil {
+ err = rerr
+ }
+ c.initProcess = nil
+ if herr := runPoststopHooks(c); err == nil {
+ err = herr
+ }
+ c.state = &stoppedState{c: c}
+ return err
+}
+
+func runPoststopHooks(c *linuxContainer) error {
+ if c.config.Hooks != nil {
+ s := configs.HookState{
+ Version: c.config.Version,
+ ID: c.id,
+ Bundle: utils.SearchLabels(c.config.Labels, "bundle"),
+ }
+ for _, hook := range c.config.Hooks.Poststop {
+ if err := hook.Run(s); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// stoppedState represents a container is a stopped/destroyed state.
+type stoppedState struct {
+ c *linuxContainer
+}
+
+func (b *stoppedState) status() Status {
+ return Stopped
+}
+
+func (b *stoppedState) transition(s containerState) error {
+ switch s.(type) {
+ case *runningState, *restoredState:
+ b.c.state = s
+ return nil
+ case *stoppedState:
+ return nil
+ }
+ return newStateTransitionError(b, s)
+}
+
+func (b *stoppedState) destroy() error {
+ return destroy(b.c)
+}
+
+// runningState represents a container that is currently running.
+type runningState struct {
+ c *linuxContainer
+}
+
+func (r *runningState) status() Status {
+ return Running
+}
+
+func (r *runningState) transition(s containerState) error {
+ switch s.(type) {
+ case *stoppedState:
+ t, err := r.c.runType()
+ if err != nil {
+ return err
+ }
+ if t == Running {
+ return newGenericError(fmt.Errorf("container still running"), ContainerNotStopped)
+ }
+ r.c.state = s
+ return nil
+ case *pausedState:
+ r.c.state = s
+ return nil
+ case *runningState:
+ return nil
+ }
+ return newStateTransitionError(r, s)
+}
+
+func (r *runningState) destroy() error {
+ t, err := r.c.runType()
+ if err != nil {
+ return err
+ }
+ if t == Running {
+ return newGenericError(fmt.Errorf("container is not destroyed"), ContainerNotStopped)
+ }
+ return destroy(r.c)
+}
+
+type createdState struct {
+ c *linuxContainer
+}
+
+func (i *createdState) status() Status {
+ return Created
+}
+
+func (i *createdState) transition(s containerState) error {
+ switch s.(type) {
+ case *runningState, *pausedState, *stoppedState:
+ i.c.state = s
+ return nil
+ case *createdState:
+ return nil
+ }
+ return newStateTransitionError(i, s)
+}
+
+func (i *createdState) destroy() error {
+ i.c.initProcess.signal(syscall.SIGKILL)
+ return destroy(i.c)
+}
+
+// pausedState represents a container that is currently pause. It cannot be destroyed in a
+// paused state and must transition back to running first.
+type pausedState struct {
+ c *linuxContainer
+}
+
+func (p *pausedState) status() Status {
+ return Paused
+}
+
+func (p *pausedState) transition(s containerState) error {
+ switch s.(type) {
+ case *runningState, *stoppedState:
+ p.c.state = s
+ return nil
+ case *pausedState:
+ return nil
+ }
+ return newStateTransitionError(p, s)
+}
+
+func (p *pausedState) destroy() error {
+ t, err := p.c.runType()
+ if err != nil {
+ return err
+ }
+ if t != Running && t != Created {
+ if err := p.c.cgroupManager.Freeze(configs.Thawed); err != nil {
+ return err
+ }
+ return destroy(p.c)
+ }
+ return newGenericError(fmt.Errorf("container is paused"), ContainerPaused)
+}
+
+// restoredState is the same as the running state but also has associated checkpoint
+// information that maybe need destroyed when the container is stopped and destroy is called.
+type restoredState struct {
+ imageDir string
+ c *linuxContainer
+}
+
+func (r *restoredState) status() Status {
+ return Running
+}
+
+func (r *restoredState) transition(s containerState) error {
+ switch s.(type) {
+ case *stoppedState, *runningState:
+ return nil
+ }
+ return newStateTransitionError(r, s)
+}
+
+func (r *restoredState) destroy() error {
+ if _, err := os.Stat(filepath.Join(r.c.root, "checkpoint")); err != nil {
+ if !os.IsNotExist(err) {
+ return err
+ }
+ }
+ return destroy(r.c)
+}
+
+// loadedState is used whenever a container is restored, loaded, or setting additional
+// processes inside and it should not be destroyed when it is exiting.
+type loadedState struct {
+ c *linuxContainer
+ s Status
+}
+
+func (n *loadedState) status() Status {
+ return n.s
+}
+
+func (n *loadedState) transition(s containerState) error {
+ n.c.state = s
+ return nil
+}
+
+func (n *loadedState) destroy() error {
+ if err := n.c.refreshState(); err != nil {
+ return err
+ }
+ return n.c.state.destroy()
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/stats.go b/vendor/github.com/opencontainers/runc/libcontainer/stats.go
new file mode 100644
index 0000000..303e4b9
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/stats.go
@@ -0,0 +1,15 @@
+package libcontainer
+
+type NetworkInterface struct {
+ // Name is the name of the network interface.
+ Name string
+
+ RxBytes uint64
+ RxPackets uint64
+ RxErrors uint64
+ RxDropped uint64
+ TxBytes uint64
+ TxPackets uint64
+ TxErrors uint64
+ TxDropped uint64
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/stats_freebsd.go b/vendor/github.com/opencontainers/runc/libcontainer/stats_freebsd.go
new file mode 100644
index 0000000..f8d1d68
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/stats_freebsd.go
@@ -0,0 +1,5 @@
+package libcontainer
+
+type Stats struct {
+ Interfaces []*NetworkInterface
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/stats_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/stats_linux.go
new file mode 100644
index 0000000..c629dc6
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/stats_linux.go
@@ -0,0 +1,8 @@
+package libcontainer
+
+import "github.com/opencontainers/runc/libcontainer/cgroups"
+
+type Stats struct {
+ Interfaces []*NetworkInterface
+ CgroupStats *cgroups.Stats
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/stats_solaris.go b/vendor/github.com/opencontainers/runc/libcontainer/stats_solaris.go
new file mode 100644
index 0000000..da78c1c
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/stats_solaris.go
@@ -0,0 +1,7 @@
+package libcontainer
+
+// Solaris - TODO
+
+type Stats struct {
+ Interfaces []*NetworkInterface
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/stats_windows.go b/vendor/github.com/opencontainers/runc/libcontainer/stats_windows.go
new file mode 100644
index 0000000..f8d1d68
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/stats_windows.go
@@ -0,0 +1,5 @@
+package libcontainer
+
+type Stats struct {
+ Interfaces []*NetworkInterface
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/sync.go b/vendor/github.com/opencontainers/runc/libcontainer/sync.go
new file mode 100644
index 0000000..cf7b45b
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/sync.go
@@ -0,0 +1,107 @@
+package libcontainer
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+
+ "github.com/opencontainers/runc/libcontainer/utils"
+)
+
+type syncType string
+
+// Constants that are used for synchronisation between the parent and child
+// during container setup. They come in pairs (with procError being a generic
+// response which is followed by a &genericError).
+//
+// [ child ] <-> [ parent ]
+//
+// procHooks --> [run hooks]
+// <-- procResume
+//
+// procConsole -->
+// <-- procConsoleReq
+// [send(fd)] --> [recv(fd)]
+// <-- procConsoleAck
+//
+// procReady --> [final setup]
+// <-- procRun
+const (
+ procError syncType = "procError"
+ procReady syncType = "procReady"
+ procRun syncType = "procRun"
+ procHooks syncType = "procHooks"
+ procResume syncType = "procResume"
+)
+
+type syncT struct {
+ Type syncType `json:"type"`
+}
+
+// writeSync is used to write to a synchronisation pipe. An error is returned
+// if there was a problem writing the payload.
+func writeSync(pipe io.Writer, sync syncType) error {
+ if err := utils.WriteJSON(pipe, syncT{sync}); err != nil {
+ return err
+ }
+ return nil
+}
+
+// readSync is used to read from a synchronisation pipe. An error is returned
+// if we got a genericError, the pipe was closed, or we got an unexpected flag.
+func readSync(pipe io.Reader, expected syncType) error {
+ var procSync syncT
+ if err := json.NewDecoder(pipe).Decode(&procSync); err != nil {
+ if err == io.EOF {
+ return fmt.Errorf("parent closed synchronisation channel")
+ }
+
+ if procSync.Type == procError {
+ var ierr genericError
+
+ if err := json.NewDecoder(pipe).Decode(&ierr); err != nil {
+ return fmt.Errorf("failed reading error from parent: %v", err)
+ }
+
+ return &ierr
+ }
+
+ if procSync.Type != expected {
+ return fmt.Errorf("invalid synchronisation flag from parent")
+ }
+ }
+ return nil
+}
+
+// parseSync runs the given callback function on each syncT received from the
+// child. It will return once io.EOF is returned from the given pipe.
+func parseSync(pipe io.Reader, fn func(*syncT) error) error {
+ dec := json.NewDecoder(pipe)
+ for {
+ var sync syncT
+ if err := dec.Decode(&sync); err != nil {
+ if err == io.EOF {
+ break
+ }
+ return err
+ }
+
+ // We handle this case outside fn for cleanliness reasons.
+ var ierr *genericError
+ if sync.Type == procError {
+ if err := dec.Decode(&ierr); err != nil && err != io.EOF {
+ return newSystemErrorWithCause(err, "decoding proc error from init")
+ }
+ if ierr != nil {
+ return ierr
+ }
+ // Programmer error.
+ panic("No error following JSON procError payload.")
+ }
+
+ if err := fn(&sync); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/linux.go b/vendor/github.com/opencontainers/runc/libcontainer/system/linux.go
new file mode 100644
index 0000000..1afc52b
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/system/linux.go
@@ -0,0 +1,143 @@
+// +build linux
+
+package system
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "os/exec"
+ "syscall"
+ "unsafe"
+)
+
+// If arg2 is nonzero, set the "child subreaper" attribute of the
+// calling process; if arg2 is zero, unset the attribute. When a
+// process is marked as a child subreaper, all of the children
+// that it creates, and their descendants, will be marked as
+// having a subreaper. In effect, a subreaper fulfills the role
+// of init(1) for its descendant processes. Upon termination of
+// a process that is orphaned (i.e., its immediate parent has
+// already terminated) and marked as having a subreaper, the
+// nearest still living ancestor subreaper will receive a SIGCHLD
+// signal and be able to wait(2) on the process to discover its
+// termination status.
+const PR_SET_CHILD_SUBREAPER = 36
+
+type ParentDeathSignal int
+
+func (p ParentDeathSignal) Restore() error {
+ if p == 0 {
+ return nil
+ }
+ current, err := GetParentDeathSignal()
+ if err != nil {
+ return err
+ }
+ if p == current {
+ return nil
+ }
+ return p.Set()
+}
+
+func (p ParentDeathSignal) Set() error {
+ return SetParentDeathSignal(uintptr(p))
+}
+
+func Execv(cmd string, args []string, env []string) error {
+ name, err := exec.LookPath(cmd)
+ if err != nil {
+ return err
+ }
+
+ return syscall.Exec(name, args, env)
+}
+
+func Prlimit(pid, resource int, limit syscall.Rlimit) error {
+ _, _, err := syscall.RawSyscall6(syscall.SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(&limit)), uintptr(unsafe.Pointer(&limit)), 0, 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+func SetParentDeathSignal(sig uintptr) error {
+ if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, sig, 0); err != 0 {
+ return err
+ }
+ return nil
+}
+
+func GetParentDeathSignal() (ParentDeathSignal, error) {
+ var sig int
+ _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_GET_PDEATHSIG, uintptr(unsafe.Pointer(&sig)), 0)
+ if err != 0 {
+ return -1, err
+ }
+ return ParentDeathSignal(sig), nil
+}
+
+func SetKeepCaps() error {
+ if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_KEEPCAPS, 1, 0); err != 0 {
+ return err
+ }
+
+ return nil
+}
+
+func ClearKeepCaps() error {
+ if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_KEEPCAPS, 0, 0); err != 0 {
+ return err
+ }
+
+ return nil
+}
+
+func Setctty() error {
+ if _, _, err := syscall.RawSyscall(syscall.SYS_IOCTL, 0, uintptr(syscall.TIOCSCTTY), 0); err != 0 {
+ return err
+ }
+ return nil
+}
+
+// RunningInUserNS detects whether we are currently running in a user namespace.
+// Copied from github.com/lxc/lxd/shared/util.go
+func RunningInUserNS() bool {
+ file, err := os.Open("/proc/self/uid_map")
+ if err != nil {
+ // This kernel-provided file only exists if user namespaces are supported
+ return false
+ }
+ defer file.Close()
+
+ buf := bufio.NewReader(file)
+ l, _, err := buf.ReadLine()
+ if err != nil {
+ return false
+ }
+
+ line := string(l)
+ var a, b, c int64
+ fmt.Sscanf(line, "%d %d %d", &a, &b, &c)
+ /*
+ * We assume we are in the initial user namespace if we have a full
+ * range - 4294967295 uids starting at uid 0.
+ */
+ if a == 0 && b == 0 && c == 4294967295 {
+ return false
+ }
+ return true
+}
+
+// SetSubreaper sets the value i as the subreaper setting for the calling process
+func SetSubreaper(i int) error {
+ return Prctl(PR_SET_CHILD_SUBREAPER, uintptr(i), 0, 0, 0)
+}
+
+func Prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) {
+ _, _, e1 := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/proc.go b/vendor/github.com/opencontainers/runc/libcontainer/system/proc.go
new file mode 100644
index 0000000..a0e9637
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/system/proc.go
@@ -0,0 +1,43 @@
+package system
+
+import (
+ "io/ioutil"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+// look in /proc to find the process start time so that we can verify
+// that this pid has started after ourself
+func GetProcessStartTime(pid int) (string, error) {
+ data, err := ioutil.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat"))
+ if err != nil {
+ return "", err
+ }
+ return parseStartTime(string(data))
+}
+
+func parseStartTime(stat string) (string, error) {
+ // the starttime is located at pos 22
+ // from the man page
+ //
+ // starttime %llu (was %lu before Linux 2.6)
+ // (22) The time the process started after system boot. In kernels before Linux 2.6, this
+ // value was expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks
+ // (divide by sysconf(_SC_CLK_TCK)).
+ //
+ // NOTE:
+ // pos 2 could contain space and is inside `(` and `)`:
+ // (2) comm %s
+ // The filename of the executable, in parentheses.
+ // This is visible whether or not the executable is
+ // swapped out.
+ //
+ // the following is an example:
+ // 89653 (gunicorn: maste) S 89630 89653 89653 0 -1 4194560 29689 28896 0 3 146 32 76 19 20 0 1 0 2971844 52965376 3920 18446744073709551615 1 1 0 0 0 0 0 16781312 137447943 0 0 0 17 1 0 0 0 0 0 0 0 0 0 0 0 0 0
+
+ // get parts after last `)`:
+ s := strings.Split(stat, ")")
+ parts := strings.Split(strings.TrimSpace(s[len(s)-1]), " ")
+ return parts[22-3], nil // starts at 3 (after the filename pos `2`)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/setns_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/system/setns_linux.go
new file mode 100644
index 0000000..615ff4c
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/system/setns_linux.go
@@ -0,0 +1,40 @@
+package system
+
+import (
+ "fmt"
+ "runtime"
+ "syscall"
+)
+
+// Via http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=7b21fddd087678a70ad64afc0f632e0f1071b092
+//
+// We need different setns values for the different platforms and arch
+// We are declaring the macro here because the SETNS syscall does not exist in th stdlib
+var setNsMap = map[string]uintptr{
+ "linux/386": 346,
+ "linux/arm64": 268,
+ "linux/amd64": 308,
+ "linux/arm": 375,
+ "linux/ppc": 350,
+ "linux/ppc64": 350,
+ "linux/ppc64le": 350,
+ "linux/s390x": 339,
+}
+
+var sysSetns = setNsMap[fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)]
+
+func SysSetns() uint32 {
+ return uint32(sysSetns)
+}
+
+func Setns(fd uintptr, flags uintptr) error {
+ ns, exists := setNsMap[fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)]
+ if !exists {
+ return fmt.Errorf("unsupported platform %s/%s", runtime.GOOS, runtime.GOARCH)
+ }
+ _, _, err := syscall.RawSyscall(ns, fd, flags, 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_386.go b/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_386.go
new file mode 100644
index 0000000..bb44d89
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_386.go
@@ -0,0 +1,25 @@
+// +build linux,386
+
+package system
+
+import (
+ "syscall"
+)
+
+// Setuid sets the uid of the calling thread to the specified uid.
+func Setuid(uid int) (err error) {
+ _, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID32, uintptr(uid), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+// Setgid sets the gid of the calling thread to the specified gid.
+func Setgid(gid int) (err error) {
+ _, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID32, uintptr(gid), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_64.go b/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_64.go
new file mode 100644
index 0000000..0816bf8
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_64.go
@@ -0,0 +1,25 @@
+// +build linux,arm64 linux,amd64 linux,ppc linux,ppc64 linux,ppc64le linux,s390x
+
+package system
+
+import (
+ "syscall"
+)
+
+// Setuid sets the uid of the calling thread to the specified uid.
+func Setuid(uid int) (err error) {
+ _, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+// Setgid sets the gid of the calling thread to the specified gid.
+func Setgid(gid int) (err error) {
+ _, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID, uintptr(gid), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_arm.go b/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_arm.go
new file mode 100644
index 0000000..3f780f3
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_arm.go
@@ -0,0 +1,25 @@
+// +build linux,arm
+
+package system
+
+import (
+ "syscall"
+)
+
+// Setuid sets the uid of the calling thread to the specified uid.
+func Setuid(uid int) (err error) {
+ _, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID32, uintptr(uid), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+// Setgid sets the gid of the calling thread to the specified gid.
+func Setgid(gid int) (err error) {
+ _, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID32, uintptr(gid), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig.go b/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig.go
new file mode 100644
index 0000000..b3a07cb
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig.go
@@ -0,0 +1,12 @@
+// +build cgo,linux cgo,freebsd
+
+package system
+
+/*
+#include <unistd.h>
+*/
+import "C"
+
+func GetClockTicks() int {
+ return int(C.sysconf(C._SC_CLK_TCK))
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig_notcgo.go b/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig_notcgo.go
new file mode 100644
index 0000000..d93b5d5
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig_notcgo.go
@@ -0,0 +1,15 @@
+// +build !cgo windows
+
+package system
+
+func GetClockTicks() int {
+ // TODO figure out a better alternative for platforms where we're missing cgo
+ //
+ // TODO Windows. This could be implemented using Win32 QueryPerformanceFrequency().
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx
+ //
+ // An example of its usage can be found here.
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx
+
+ return 100
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/system/unsupported.go
new file mode 100644
index 0000000..e7cfd62
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/system/unsupported.go
@@ -0,0 +1,9 @@
+// +build !linux
+
+package system
+
+// RunningInUserNS is a stub for non-Linux systems
+// Always returns false
+func RunningInUserNS() bool {
+ return false
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/system/xattrs_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/system/xattrs_linux.go
new file mode 100644
index 0000000..30f74df
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/system/xattrs_linux.go
@@ -0,0 +1,99 @@
+package system
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _zero uintptr
+
+// Returns the size of xattrs and nil error
+// Requires path, takes allocated []byte or nil as last argument
+func Llistxattr(path string, dest []byte) (size int, err error) {
+ pathBytes, err := syscall.BytePtrFromString(path)
+ if err != nil {
+ return -1, err
+ }
+ var newpathBytes unsafe.Pointer
+ if len(dest) > 0 {
+ newpathBytes = unsafe.Pointer(&dest[0])
+ } else {
+ newpathBytes = unsafe.Pointer(&_zero)
+ }
+
+ _size, _, errno := syscall.Syscall6(syscall.SYS_LLISTXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(newpathBytes), uintptr(len(dest)), 0, 0, 0)
+ size = int(_size)
+ if errno != 0 {
+ return -1, errno
+ }
+
+ return size, nil
+}
+
+// Returns a []byte slice if the xattr is set and nil otherwise
+// Requires path and its attribute as arguments
+func Lgetxattr(path string, attr string) ([]byte, error) {
+ var sz int
+ pathBytes, err := syscall.BytePtrFromString(path)
+ if err != nil {
+ return nil, err
+ }
+ attrBytes, err := syscall.BytePtrFromString(attr)
+ if err != nil {
+ return nil, err
+ }
+
+ // Start with a 128 length byte array
+ sz = 128
+ dest := make([]byte, sz)
+ destBytes := unsafe.Pointer(&dest[0])
+ _sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0)
+
+ switch {
+ case errno == syscall.ENODATA:
+ return nil, errno
+ case errno == syscall.ENOTSUP:
+ return nil, errno
+ case errno == syscall.ERANGE:
+ // 128 byte array might just not be good enough,
+ // A dummy buffer is used ``uintptr(0)`` to get real size
+ // of the xattrs on disk
+ _sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(unsafe.Pointer(nil)), uintptr(0), 0, 0)
+ sz = int(_sz)
+ if sz < 0 {
+ return nil, errno
+ }
+ dest = make([]byte, sz)
+ destBytes := unsafe.Pointer(&dest[0])
+ _sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0)
+ if errno != 0 {
+ return nil, errno
+ }
+ case errno != 0:
+ return nil, errno
+ }
+ sz = int(_sz)
+ return dest[:sz], nil
+}
+
+func Lsetxattr(path string, attr string, data []byte, flags int) error {
+ pathBytes, err := syscall.BytePtrFromString(path)
+ if err != nil {
+ return err
+ }
+ attrBytes, err := syscall.BytePtrFromString(attr)
+ if err != nil {
+ return err
+ }
+ var dataBytes unsafe.Pointer
+ if len(data) > 0 {
+ dataBytes = unsafe.Pointer(&data[0])
+ } else {
+ dataBytes = unsafe.Pointer(&_zero)
+ }
+ _, _, errno := syscall.Syscall6(syscall.SYS_LSETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(dataBytes), uintptr(len(data)), uintptr(flags), 0)
+ if errno != 0 {
+ return errno
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go b/vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go
new file mode 100644
index 0000000..ab1439f
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go
@@ -0,0 +1,110 @@
+package user
+
+import (
+ "errors"
+ "syscall"
+)
+
+var (
+ // The current operating system does not provide the required data for user lookups.
+ ErrUnsupported = errors.New("user lookup: operating system does not provide passwd-formatted data")
+ // No matching entries found in file.
+ ErrNoPasswdEntries = errors.New("no matching entries in passwd file")
+ ErrNoGroupEntries = errors.New("no matching entries in group file")
+)
+
+func lookupUser(filter func(u User) bool) (User, error) {
+ // Get operating system-specific passwd reader-closer.
+ passwd, err := GetPasswd()
+ if err != nil {
+ return User{}, err
+ }
+ defer passwd.Close()
+
+ // Get the users.
+ users, err := ParsePasswdFilter(passwd, filter)
+ if err != nil {
+ return User{}, err
+ }
+
+ // No user entries found.
+ if len(users) == 0 {
+ return User{}, ErrNoPasswdEntries
+ }
+
+ // Assume the first entry is the "correct" one.
+ return users[0], nil
+}
+
+// CurrentUser looks up the current user by their user id in /etc/passwd. If the
+// user cannot be found (or there is no /etc/passwd file on the filesystem),
+// then CurrentUser returns an error.
+func CurrentUser() (User, error) {
+ return LookupUid(syscall.Getuid())
+}
+
+// LookupUser looks up a user by their username in /etc/passwd. If the user
+// cannot be found (or there is no /etc/passwd file on the filesystem), then
+// LookupUser returns an error.
+func LookupUser(username string) (User, error) {
+ return lookupUser(func(u User) bool {
+ return u.Name == username
+ })
+}
+
+// LookupUid looks up a user by their user id in /etc/passwd. If the user cannot
+// be found (or there is no /etc/passwd file on the filesystem), then LookupId
+// returns an error.
+func LookupUid(uid int) (User, error) {
+ return lookupUser(func(u User) bool {
+ return u.Uid == uid
+ })
+}
+
+func lookupGroup(filter func(g Group) bool) (Group, error) {
+ // Get operating system-specific group reader-closer.
+ group, err := GetGroup()
+ if err != nil {
+ return Group{}, err
+ }
+ defer group.Close()
+
+ // Get the users.
+ groups, err := ParseGroupFilter(group, filter)
+ if err != nil {
+ return Group{}, err
+ }
+
+ // No user entries found.
+ if len(groups) == 0 {
+ return Group{}, ErrNoGroupEntries
+ }
+
+ // Assume the first entry is the "correct" one.
+ return groups[0], nil
+}
+
+// CurrentGroup looks up the current user's group by their primary group id's
+// entry in /etc/passwd. If the group cannot be found (or there is no
+// /etc/group file on the filesystem), then CurrentGroup returns an error.
+func CurrentGroup() (Group, error) {
+ return LookupGid(syscall.Getgid())
+}
+
+// LookupGroup looks up a group by its name in /etc/group. If the group cannot
+// be found (or there is no /etc/group file on the filesystem), then LookupGroup
+// returns an error.
+func LookupGroup(groupname string) (Group, error) {
+ return lookupGroup(func(g Group) bool {
+ return g.Name == groupname
+ })
+}
+
+// LookupGid looks up a group by its group id in /etc/group. If the group cannot
+// be found (or there is no /etc/group file on the filesystem), then LookupGid
+// returns an error.
+func LookupGid(gid int) (Group, error) {
+ return lookupGroup(func(g Group) bool {
+ return g.Gid == gid
+ })
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go
new file mode 100644
index 0000000..758b734
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go
@@ -0,0 +1,30 @@
+// +build darwin dragonfly freebsd linux netbsd openbsd solaris
+
+package user
+
+import (
+ "io"
+ "os"
+)
+
+// Unix-specific path to the passwd and group formatted files.
+const (
+ unixPasswdPath = "/etc/passwd"
+ unixGroupPath = "/etc/group"
+)
+
+func GetPasswdPath() (string, error) {
+ return unixPasswdPath, nil
+}
+
+func GetPasswd() (io.ReadCloser, error) {
+ return os.Open(unixPasswdPath)
+}
+
+func GetGroupPath() (string, error) {
+ return unixGroupPath, nil
+}
+
+func GetGroup() (io.ReadCloser, error) {
+ return os.Open(unixGroupPath)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go
new file mode 100644
index 0000000..7217948
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go
@@ -0,0 +1,21 @@
+// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris
+
+package user
+
+import "io"
+
+func GetPasswdPath() (string, error) {
+ return "", ErrUnsupported
+}
+
+func GetPasswd() (io.ReadCloser, error) {
+ return nil, ErrUnsupported
+}
+
+func GetGroupPath() (string, error) {
+ return "", ErrUnsupported
+}
+
+func GetGroup() (io.ReadCloser, error) {
+ return nil, ErrUnsupported
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/user/user.go b/vendor/github.com/opencontainers/runc/libcontainer/user/user.go
new file mode 100644
index 0000000..8962cab
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/user/user.go
@@ -0,0 +1,441 @@
+package user
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "os"
+ "strconv"
+ "strings"
+)
+
+const (
+ minId = 0
+ maxId = 1<<31 - 1 //for 32-bit systems compatibility
+)
+
+var (
+ ErrRange = fmt.Errorf("uids and gids must be in range %d-%d", minId, maxId)
+)
+
+type User struct {
+ Name string
+ Pass string
+ Uid int
+ Gid int
+ Gecos string
+ Home string
+ Shell string
+}
+
+type Group struct {
+ Name string
+ Pass string
+ Gid int
+ List []string
+}
+
+func parseLine(line string, v ...interface{}) {
+ if line == "" {
+ return
+ }
+
+ parts := strings.Split(line, ":")
+ for i, p := range parts {
+ // Ignore cases where we don't have enough fields to populate the arguments.
+ // Some configuration files like to misbehave.
+ if len(v) <= i {
+ break
+ }
+
+ // Use the type of the argument to figure out how to parse it, scanf() style.
+ // This is legit.
+ switch e := v[i].(type) {
+ case *string:
+ *e = p
+ case *int:
+ // "numbers", with conversion errors ignored because of some misbehaving configuration files.
+ *e, _ = strconv.Atoi(p)
+ case *[]string:
+ // Comma-separated lists.
+ if p != "" {
+ *e = strings.Split(p, ",")
+ } else {
+ *e = []string{}
+ }
+ default:
+ // Someone goof'd when writing code using this function. Scream so they can hear us.
+ panic(fmt.Sprintf("parseLine only accepts {*string, *int, *[]string} as arguments! %#v is not a pointer!", e))
+ }
+ }
+}
+
+func ParsePasswdFile(path string) ([]User, error) {
+ passwd, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer passwd.Close()
+ return ParsePasswd(passwd)
+}
+
+func ParsePasswd(passwd io.Reader) ([]User, error) {
+ return ParsePasswdFilter(passwd, nil)
+}
+
+func ParsePasswdFileFilter(path string, filter func(User) bool) ([]User, error) {
+ passwd, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer passwd.Close()
+ return ParsePasswdFilter(passwd, filter)
+}
+
+func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) {
+ if r == nil {
+ return nil, fmt.Errorf("nil source for passwd-formatted data")
+ }
+
+ var (
+ s = bufio.NewScanner(r)
+ out = []User{}
+ )
+
+ for s.Scan() {
+ if err := s.Err(); err != nil {
+ return nil, err
+ }
+
+ line := strings.TrimSpace(s.Text())
+ if line == "" {
+ continue
+ }
+
+ // see: man 5 passwd
+ // name:password:UID:GID:GECOS:directory:shell
+ // Name:Pass:Uid:Gid:Gecos:Home:Shell
+ // root:x:0:0:root:/root:/bin/bash
+ // adm:x:3:4:adm:/var/adm:/bin/false
+ p := User{}
+ parseLine(line, &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell)
+
+ if filter == nil || filter(p) {
+ out = append(out, p)
+ }
+ }
+
+ return out, nil
+}
+
+func ParseGroupFile(path string) ([]Group, error) {
+ group, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+
+ defer group.Close()
+ return ParseGroup(group)
+}
+
+func ParseGroup(group io.Reader) ([]Group, error) {
+ return ParseGroupFilter(group, nil)
+}
+
+func ParseGroupFileFilter(path string, filter func(Group) bool) ([]Group, error) {
+ group, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer group.Close()
+ return ParseGroupFilter(group, filter)
+}
+
+func ParseGroupFilter(r io.Reader, filter func(Group) bool) ([]Group, error) {
+ if r == nil {
+ return nil, fmt.Errorf("nil source for group-formatted data")
+ }
+
+ var (
+ s = bufio.NewScanner(r)
+ out = []Group{}
+ )
+
+ for s.Scan() {
+ if err := s.Err(); err != nil {
+ return nil, err
+ }
+
+ text := s.Text()
+ if text == "" {
+ continue
+ }
+
+ // see: man 5 group
+ // group_name:password:GID:user_list
+ // Name:Pass:Gid:List
+ // root:x:0:root
+ // adm:x:4:root,adm,daemon
+ p := Group{}
+ parseLine(text, &p.Name, &p.Pass, &p.Gid, &p.List)
+
+ if filter == nil || filter(p) {
+ out = append(out, p)
+ }
+ }
+
+ return out, nil
+}
+
+type ExecUser struct {
+ Uid int
+ Gid int
+ Sgids []int
+ Home string
+}
+
+// GetExecUserPath is a wrapper for GetExecUser. It reads data from each of the
+// given file paths and uses that data as the arguments to GetExecUser. If the
+// files cannot be opened for any reason, the error is ignored and a nil
+// io.Reader is passed instead.
+func GetExecUserPath(userSpec string, defaults *ExecUser, passwdPath, groupPath string) (*ExecUser, error) {
+ var passwd, group io.Reader
+
+ if passwdFile, err := os.Open(passwdPath); err == nil {
+ passwd = passwdFile
+ defer passwdFile.Close()
+ }
+
+ if groupFile, err := os.Open(groupPath); err == nil {
+ group = groupFile
+ defer groupFile.Close()
+ }
+
+ return GetExecUser(userSpec, defaults, passwd, group)
+}
+
+// GetExecUser parses a user specification string (using the passwd and group
+// readers as sources for /etc/passwd and /etc/group data, respectively). In
+// the case of blank fields or missing data from the sources, the values in
+// defaults is used.
+//
+// GetExecUser will return an error if a user or group literal could not be
+// found in any entry in passwd and group respectively.
+//
+// Examples of valid user specifications are:
+// * ""
+// * "user"
+// * "uid"
+// * "user:group"
+// * "uid:gid
+// * "user:gid"
+// * "uid:group"
+//
+// It should be noted that if you specify a numeric user or group id, they will
+// not be evaluated as usernames (only the metadata will be filled). So attempting
+// to parse a user with user.Name = "1337" will produce the user with a UID of
+// 1337.
+func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) (*ExecUser, error) {
+ if defaults == nil {
+ defaults = new(ExecUser)
+ }
+
+ // Copy over defaults.
+ user := &ExecUser{
+ Uid: defaults.Uid,
+ Gid: defaults.Gid,
+ Sgids: defaults.Sgids,
+ Home: defaults.Home,
+ }
+
+ // Sgids slice *cannot* be nil.
+ if user.Sgids == nil {
+ user.Sgids = []int{}
+ }
+
+ // Allow for userArg to have either "user" syntax, or optionally "user:group" syntax
+ var userArg, groupArg string
+ parseLine(userSpec, &userArg, &groupArg)
+
+ // Convert userArg and groupArg to be numeric, so we don't have to execute
+ // Atoi *twice* for each iteration over lines.
+ uidArg, uidErr := strconv.Atoi(userArg)
+ gidArg, gidErr := strconv.Atoi(groupArg)
+
+ // Find the matching user.
+ users, err := ParsePasswdFilter(passwd, func(u User) bool {
+ if userArg == "" {
+ // Default to current state of the user.
+ return u.Uid == user.Uid
+ }
+
+ if uidErr == nil {
+ // If the userArg is numeric, always treat it as a UID.
+ return uidArg == u.Uid
+ }
+
+ return u.Name == userArg
+ })
+
+ // If we can't find the user, we have to bail.
+ if err != nil && passwd != nil {
+ if userArg == "" {
+ userArg = strconv.Itoa(user.Uid)
+ }
+ return nil, fmt.Errorf("unable to find user %s: %v", userArg, err)
+ }
+
+ var matchedUserName string
+ if len(users) > 0 {
+ // First match wins, even if there's more than one matching entry.
+ matchedUserName = users[0].Name
+ user.Uid = users[0].Uid
+ user.Gid = users[0].Gid
+ user.Home = users[0].Home
+ } else if userArg != "" {
+ // If we can't find a user with the given username, the only other valid
+ // option is if it's a numeric username with no associated entry in passwd.
+
+ if uidErr != nil {
+ // Not numeric.
+ return nil, fmt.Errorf("unable to find user %s: %v", userArg, ErrNoPasswdEntries)
+ }
+ user.Uid = uidArg
+
+ // Must be inside valid uid range.
+ if user.Uid < minId || user.Uid > maxId {
+ return nil, ErrRange
+ }
+
+ // Okay, so it's numeric. We can just roll with this.
+ }
+
+ // On to the groups. If we matched a username, we need to do this because of
+ // the supplementary group IDs.
+ if groupArg != "" || matchedUserName != "" {
+ groups, err := ParseGroupFilter(group, func(g Group) bool {
+ // If the group argument isn't explicit, we'll just search for it.
+ if groupArg == "" {
+ // Check if user is a member of this group.
+ for _, u := range g.List {
+ if u == matchedUserName {
+ return true
+ }
+ }
+ return false
+ }
+
+ if gidErr == nil {
+ // If the groupArg is numeric, always treat it as a GID.
+ return gidArg == g.Gid
+ }
+
+ return g.Name == groupArg
+ })
+ if err != nil && group != nil {
+ return nil, fmt.Errorf("unable to find groups for spec %v: %v", matchedUserName, err)
+ }
+
+ // Only start modifying user.Gid if it is in explicit form.
+ if groupArg != "" {
+ if len(groups) > 0 {
+ // First match wins, even if there's more than one matching entry.
+ user.Gid = groups[0].Gid
+ } else {
+ // If we can't find a group with the given name, the only other valid
+ // option is if it's a numeric group name with no associated entry in group.
+
+ if gidErr != nil {
+ // Not numeric.
+ return nil, fmt.Errorf("unable to find group %s: %v", groupArg, ErrNoGroupEntries)
+ }
+ user.Gid = gidArg
+
+ // Must be inside valid gid range.
+ if user.Gid < minId || user.Gid > maxId {
+ return nil, ErrRange
+ }
+
+ // Okay, so it's numeric. We can just roll with this.
+ }
+ } else if len(groups) > 0 {
+ // Supplementary group ids only make sense if in the implicit form.
+ user.Sgids = make([]int, len(groups))
+ for i, group := range groups {
+ user.Sgids[i] = group.Gid
+ }
+ }
+ }
+
+ return user, nil
+}
+
+// GetAdditionalGroups looks up a list of groups by name or group id
+// against the given /etc/group formatted data. If a group name cannot
+// be found, an error will be returned. If a group id cannot be found,
+// or the given group data is nil, the id will be returned as-is
+// provided it is in the legal range.
+func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, error) {
+ var groups = []Group{}
+ if group != nil {
+ var err error
+ groups, err = ParseGroupFilter(group, func(g Group) bool {
+ for _, ag := range additionalGroups {
+ if g.Name == ag || strconv.Itoa(g.Gid) == ag {
+ return true
+ }
+ }
+ return false
+ })
+ if err != nil {
+ return nil, fmt.Errorf("Unable to find additional groups %v: %v", additionalGroups, err)
+ }
+ }
+
+ gidMap := make(map[int]struct{})
+ for _, ag := range additionalGroups {
+ var found bool
+ for _, g := range groups {
+ // if we found a matched group either by name or gid, take the
+ // first matched as correct
+ if g.Name == ag || strconv.Itoa(g.Gid) == ag {
+ if _, ok := gidMap[g.Gid]; !ok {
+ gidMap[g.Gid] = struct{}{}
+ found = true
+ break
+ }
+ }
+ }
+ // we asked for a group but didn't find it. let's check to see
+ // if we wanted a numeric group
+ if !found {
+ gid, err := strconv.Atoi(ag)
+ if err != nil {
+ return nil, fmt.Errorf("Unable to find group %s", ag)
+ }
+ // Ensure gid is inside gid range.
+ if gid < minId || gid > maxId {
+ return nil, ErrRange
+ }
+ gidMap[gid] = struct{}{}
+ }
+ }
+ gids := []int{}
+ for gid := range gidMap {
+ gids = append(gids, gid)
+ }
+ return gids, nil
+}
+
+// GetAdditionalGroupsPath is a wrapper around GetAdditionalGroups
+// that opens the groupPath given and gives it as an argument to
+// GetAdditionalGroups.
+func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) {
+ var group io.Reader
+
+ if groupFile, err := os.Open(groupPath); err == nil {
+ group = groupFile
+ defer groupFile.Close()
+ }
+ return GetAdditionalGroups(additionalGroups, group)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/utils/cmsg.go b/vendor/github.com/opencontainers/runc/libcontainer/utils/cmsg.go
new file mode 100644
index 0000000..2cbb649
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/utils/cmsg.go
@@ -0,0 +1,95 @@
+// +build linux
+
+package utils
+
+/*
+ * Copyright 2016, 2017 SUSE LLC
+ *
+ * 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.
+ */
+
+import (
+ "fmt"
+ "os"
+
+ "golang.org/x/sys/unix"
+)
+
+// MaxSendfdLen is the maximum length of the name of a file descriptor being
+// sent using SendFd. The name of the file handle returned by RecvFd will never
+// be larger than this value.
+const MaxNameLen = 4096
+
+// oobSpace is the size of the oob slice required to store a single FD. Note
+// that unix.UnixRights appears to make the assumption that fd is always int32,
+// so sizeof(fd) = 4.
+var oobSpace = unix.CmsgSpace(4)
+
+// RecvFd waits for a file descriptor to be sent over the given AF_UNIX
+// socket. The file name of the remote file descriptor will be recreated
+// locally (it is sent as non-auxiliary data in the same payload).
+func RecvFd(socket *os.File) (*os.File, error) {
+ // For some reason, unix.Recvmsg uses the length rather than the capacity
+ // when passing the msg_controllen and other attributes to recvmsg. So we
+ // have to actually set the length.
+ name := make([]byte, MaxNameLen)
+ oob := make([]byte, oobSpace)
+
+ sockfd := socket.Fd()
+ n, oobn, _, _, err := unix.Recvmsg(int(sockfd), name, oob, 0)
+ if err != nil {
+ return nil, err
+ }
+
+ if n >= MaxNameLen || oobn != oobSpace {
+ return nil, fmt.Errorf("recvfd: incorrect number of bytes read (n=%d oobn=%d)", n, oobn)
+ }
+
+ // Truncate.
+ name = name[:n]
+ oob = oob[:oobn]
+
+ scms, err := unix.ParseSocketControlMessage(oob)
+ if err != nil {
+ return nil, err
+ }
+ if len(scms) != 1 {
+ return nil, fmt.Errorf("recvfd: number of SCMs is not 1: %d", len(scms))
+ }
+ scm := scms[0]
+
+ fds, err := unix.ParseUnixRights(&scm)
+ if err != nil {
+ return nil, err
+ }
+ if len(fds) != 1 {
+ return nil, fmt.Errorf("recvfd: number of fds is not 1: %d", len(fds))
+ }
+ fd := uintptr(fds[0])
+
+ return os.NewFile(fd, string(name)), nil
+}
+
+// SendFd sends a file descriptor over the given AF_UNIX socket. In
+// addition, the file.Name() of the given file will also be sent as
+// non-auxiliary data in the same payload (allowing to send contextual
+// information for a file descriptor).
+func SendFd(socket, file *os.File) error {
+ name := []byte(file.Name())
+ if len(name) >= MaxNameLen {
+ return fmt.Errorf("sendfd: filename too long: %s", file.Name())
+ }
+ oob := unix.UnixRights(int(file.Fd()))
+
+ return unix.Sendmsg(int(socket.Fd()), name, oob, nil, 0)
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go b/vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go
new file mode 100644
index 0000000..2b35b9a
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go
@@ -0,0 +1,126 @@
+package utils
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "unsafe"
+)
+
+const (
+ exitSignalOffset = 128
+)
+
+// GenerateRandomName returns a new name joined with a prefix. This size
+// specified is used to truncate the randomly generated value
+func GenerateRandomName(prefix string, size int) (string, error) {
+ id := make([]byte, 32)
+ if _, err := io.ReadFull(rand.Reader, id); err != nil {
+ return "", err
+ }
+ if size > 64 {
+ size = 64
+ }
+ return prefix + hex.EncodeToString(id)[:size], nil
+}
+
+// ResolveRootfs ensures that the current working directory is
+// not a symlink and returns the absolute path to the rootfs
+func ResolveRootfs(uncleanRootfs string) (string, error) {
+ rootfs, err := filepath.Abs(uncleanRootfs)
+ if err != nil {
+ return "", err
+ }
+ return filepath.EvalSymlinks(rootfs)
+}
+
+// ExitStatus returns the correct exit status for a process based on if it
+// was signaled or exited cleanly
+func ExitStatus(status syscall.WaitStatus) int {
+ if status.Signaled() {
+ return exitSignalOffset + int(status.Signal())
+ }
+ return status.ExitStatus()
+}
+
+// WriteJSON writes the provided struct v to w using standard json marshaling
+func WriteJSON(w io.Writer, v interface{}) error {
+ data, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+ _, err = w.Write(data)
+ return err
+}
+
+// CleanPath makes a path safe for use with filepath.Join. This is done by not
+// only cleaning the path, but also (if the path is relative) adding a leading
+// '/' and cleaning it (then removing the leading '/'). This ensures that a
+// path resulting from prepending another path will always resolve to lexically
+// be a subdirectory of the prefixed path. This is all done lexically, so paths
+// that include symlinks won't be safe as a result of using CleanPath.
+func CleanPath(path string) string {
+ // Deal with empty strings nicely.
+ if path == "" {
+ return ""
+ }
+
+ // Ensure that all paths are cleaned (especially problematic ones like
+ // "/../../../../../" which can cause lots of issues).
+ path = filepath.Clean(path)
+
+ // If the path isn't absolute, we need to do more processing to fix paths
+ // such as "../../../../<etc>/some/path". We also shouldn't convert absolute
+ // paths to relative ones.
+ if !filepath.IsAbs(path) {
+ path = filepath.Clean(string(os.PathSeparator) + path)
+ // This can't fail, as (by definition) all paths are relative to root.
+ path, _ = filepath.Rel(string(os.PathSeparator), path)
+ }
+
+ // Clean the path again for good measure.
+ return filepath.Clean(path)
+}
+
+// SearchLabels searches a list of key-value pairs for the provided key and
+// returns the corresponding value. The pairs must be separated with '='.
+func SearchLabels(labels []string, query string) string {
+ for _, l := range labels {
+ parts := strings.SplitN(l, "=", 2)
+ if len(parts) < 2 {
+ continue
+ }
+ if parts[0] == query {
+ return parts[1]
+ }
+ }
+ return ""
+}
+
+// Annotations returns the bundle path and user defined annotations from the
+// libcontainer state. We need to remove the bundle because that is a label
+// added by libcontainer.
+func Annotations(labels []string) (bundle string, userAnnotations map[string]string) {
+ userAnnotations = make(map[string]string)
+ for _, l := range labels {
+ parts := strings.SplitN(l, "=", 2)
+ if len(parts) < 2 {
+ continue
+ }
+ if parts[0] == "bundle" {
+ bundle = parts[1]
+ } else {
+ userAnnotations[parts[0]] = parts[1]
+ }
+ }
+ return
+}
+
+func GetIntSize() int {
+ return int(unsafe.Sizeof(1))
+}
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/utils/utils_unix.go b/vendor/github.com/opencontainers/runc/libcontainer/utils/utils_unix.go
new file mode 100644
index 0000000..7b798cc
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/libcontainer/utils/utils_unix.go
@@ -0,0 +1,43 @@
+// +build !windows
+
+package utils
+
+import (
+ "io/ioutil"
+ "os"
+ "strconv"
+ "syscall"
+)
+
+func CloseExecFrom(minFd int) error {
+ fdList, err := ioutil.ReadDir("/proc/self/fd")
+ if err != nil {
+ return err
+ }
+ for _, fi := range fdList {
+ fd, err := strconv.Atoi(fi.Name())
+ if err != nil {
+ // ignore non-numeric file names
+ continue
+ }
+
+ if fd < minFd {
+ // ignore descriptors lower than our specified minimum
+ continue
+ }
+
+ // intentionally ignore errors from syscall.CloseOnExec
+ syscall.CloseOnExec(fd)
+ // the cases where this might fail are basically file descriptors that have already been closed (including and especially the one that was created when ioutil.ReadDir did the "opendir" syscall)
+ }
+ return nil
+}
+
+// NewSockPair returns a new unix socket pair
+func NewSockPair(name string) (parent *os.File, child *os.File, err error) {
+ fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0)
+ if err != nil {
+ return nil, nil, err
+ }
+ return os.NewFile(uintptr(fds[1]), name+"-p"), os.NewFile(uintptr(fds[0]), name+"-c"), nil
+}
diff --git a/vendor/github.com/opencontainers/runc/list.go b/vendor/github.com/opencontainers/runc/list.go
new file mode 100644
index 0000000..2ace344
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/list.go
@@ -0,0 +1,175 @@
+// +build linux
+
+package runc
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "syscall"
+ "text/tabwriter"
+ "time"
+
+ "encoding/json"
+
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/opencontainers/runc/libcontainer/user"
+ "github.com/opencontainers/runc/libcontainer/utils"
+ "github.com/urfave/cli"
+)
+
+const formatOptions = `table or json`
+
+// containerState represents the platform agnostic pieces relating to a
+// running container's status and state
+type containerState struct {
+ // Version is the OCI version for the container
+ Version string `json:"ociVersion"`
+ // ID is the container ID
+ ID string `json:"id"`
+ // InitProcessPid is the init process id in the parent namespace
+ InitProcessPid int `json:"pid"`
+ // Status is the current status of the container, running, paused, ...
+ Status string `json:"status"`
+ // Bundle is the path on the filesystem to the bundle
+ Bundle string `json:"bundle"`
+ // Rootfs is a path to a directory containing the container's root filesystem.
+ Rootfs string `json:"rootfs"`
+ // Created is the unix timestamp for the creation time of the container in UTC
+ Created time.Time `json:"created"`
+ // Annotations is the user defined annotations added to the config.
+ Annotations map[string]string `json:"annotations,omitempty"`
+ // The owner of the state directory (the owner of the container).
+ Owner string `json:"owner"`
+}
+
+var listCommand = cli.Command{
+ Name: "list",
+ Usage: "lists containers started by runc with the given root",
+ ArgsUsage: `
+
+Where the given root is specified via the global option "--root"
+(default: "/run/runc").
+
+EXAMPLE 1:
+To list containers created via the default "--root":
+ # runc list
+
+EXAMPLE 2:
+To list containers created using a non-default value for "--root":
+ # runc --root value list`,
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "format, f",
+ Value: "table",
+ Usage: `select one of: ` + formatOptions,
+ },
+ cli.BoolFlag{
+ Name: "quiet, q",
+ Usage: "display only container IDs",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 0, exactArgs); err != nil {
+ return err
+ }
+ s, err := getContainers(context)
+ if err != nil {
+ return err
+ }
+
+ if context.Bool("quiet") {
+ for _, item := range s {
+ fmt.Println(item.ID)
+ }
+ return nil
+ }
+
+ switch context.String("format") {
+ case "table":
+ w := tabwriter.NewWriter(os.Stdout, 12, 1, 3, ' ', 0)
+ fmt.Fprint(w, "ID\tPID\tSTATUS\tBUNDLE\tCREATED\tOWNER\n")
+ for _, item := range s {
+ fmt.Fprintf(w, "%s\t%d\t%s\t%s\t%s\t%s\n",
+ item.ID,
+ item.InitProcessPid,
+ item.Status,
+ item.Bundle,
+ item.Created.Format(time.RFC3339Nano),
+ item.Owner)
+ }
+ if err := w.Flush(); err != nil {
+ return err
+ }
+ case "json":
+ if err := json.NewEncoder(os.Stdout).Encode(s); err != nil {
+ return err
+ }
+ default:
+ return fmt.Errorf("invalid format option")
+ }
+ return nil
+ },
+}
+
+func getContainers(context *cli.Context) ([]containerState, error) {
+ factory, err := loadFactory(context)
+ if err != nil {
+ return nil, err
+ }
+ root := context.GlobalString("root")
+ absRoot, err := filepath.Abs(root)
+ if err != nil {
+ return nil, err
+ }
+ list, err := ioutil.ReadDir(absRoot)
+ if err != nil {
+ fatal(err)
+ }
+
+ var s []containerState
+ for _, item := range list {
+ if item.IsDir() {
+ // This cast is safe on Linux.
+ stat := item.Sys().(*syscall.Stat_t)
+ owner, err := user.LookupUid(int(stat.Uid))
+ if err != nil {
+ owner.Name = string(stat.Uid)
+ }
+
+ container, err := factory.Load(item.Name())
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "load container %s: %v\n", item.Name(), err)
+ continue
+ }
+ containerStatus, err := container.Status()
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "status for %s: %v\n", item.Name(), err)
+ continue
+ }
+ state, err := container.State()
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "state for %s: %v\n", item.Name(), err)
+ continue
+ }
+ pid := state.BaseState.InitProcessPid
+ if containerStatus == libcontainer.Stopped {
+ pid = 0
+ }
+ bundle, annotations := utils.Annotations(state.Config.Labels)
+ s = append(s, containerState{
+ Version: state.BaseState.Config.Version,
+ ID: state.BaseState.ID,
+ InitProcessPid: pid,
+ Status: containerStatus.String(),
+ Bundle: bundle,
+ Rootfs: state.BaseState.Config.Rootfs,
+ Created: state.BaseState.Created,
+ Annotations: annotations,
+ Owner: owner.Name,
+ })
+ }
+ }
+ return s, nil
+}
diff --git a/vendor/github.com/opencontainers/runc/main.go b/vendor/github.com/opencontainers/runc/main.go
new file mode 100644
index 0000000..7a38bf8
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/main.go
@@ -0,0 +1,149 @@
+package runc
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "strings"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/urfave/cli"
+)
+
+// version will be populated by the Makefile, read from
+// VERSION file of the source code.
+var version = ""
+
+// gitCommit will be the hash that the binary was built from
+// and will be populated by the Makefile
+var gitCommit = ""
+
+const (
+ specConfig = "config.json"
+ usage = `Open Container Initiative runtime
+
+runc is a command line client for running applications packaged according to
+the Open Container Initiative (OCI) format and is a compliant implementation of the
+Open Container Initiative specification.
+
+runc integrates well with existing process supervisors to provide a production
+container runtime environment for applications. It can be used with your
+existing process monitoring tools and the container will be spawned as a
+direct child of the process supervisor.
+
+Containers are configured using bundles. A bundle for a container is a directory
+that includes a specification file named "` + specConfig + `" and a root filesystem.
+The root filesystem contains the contents of the container.
+
+To start a new instance of a container:
+
+ # runc run [ -b bundle ] <container-id>
+
+Where "<container-id>" is your name for the instance of the container that you
+are starting. The name you provide for the container instance must be unique on
+your host. Providing the bundle directory using "-b" is optional. The default
+value for "bundle" is the current directory.`
+)
+
+func Main() {
+ app := cli.NewApp()
+ app.Name = "runc"
+ app.Usage = usage
+
+ var v []string
+ if version != "" {
+ v = append(v, version)
+ }
+ if gitCommit != "" {
+ v = append(v, fmt.Sprintf("commit: %s", gitCommit))
+ }
+ v = append(v, fmt.Sprintf("spec: %s", specs.Version))
+ app.Version = strings.Join(v, "\n")
+ app.Flags = []cli.Flag{
+ cli.BoolFlag{
+ Name: "debug",
+ Usage: "enable debug output for logging",
+ },
+ cli.StringFlag{
+ Name: "log",
+ Value: "/dev/null",
+ Usage: "set the log file path where internal debug information is written",
+ },
+ cli.StringFlag{
+ Name: "log-format",
+ Value: "text",
+ Usage: "set the format used by logs ('text' (default), or 'json')",
+ },
+ cli.StringFlag{
+ Name: "root",
+ Value: "/run/runc",
+ Usage: "root directory for storage of container state (this should be located in tmpfs)",
+ },
+ cli.StringFlag{
+ Name: "criu",
+ Value: "criu",
+ Usage: "path to the criu binary used for checkpoint and restore",
+ },
+ cli.BoolFlag{
+ Name: "systemd-cgroup",
+ Usage: "enable systemd cgroup support, expects cgroupsPath to be of form \"slice:prefix:name\" for e.g. \"system.slice:runc:434234\"",
+ },
+ }
+ app.Commands = []cli.Command{
+ checkpointCommand,
+ createCommand,
+ deleteCommand,
+ eventsCommand,
+ execCommand,
+ initCommand,
+ killCommand,
+ listCommand,
+ pauseCommand,
+ psCommand,
+ restoreCommand,
+ resumeCommand,
+ runCommand,
+ specCommand,
+ startCommand,
+ stateCommand,
+ updateCommand,
+ }
+ app.Before = func(context *cli.Context) error {
+ if context.GlobalBool("debug") {
+ logrus.SetLevel(logrus.DebugLevel)
+ }
+ if path := context.GlobalString("log"); path != "" {
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_SYNC, 0666)
+ if err != nil {
+ return err
+ }
+ logrus.SetOutput(f)
+ }
+ switch context.GlobalString("log-format") {
+ case "text":
+ // retain logrus's default.
+ case "json":
+ logrus.SetFormatter(new(logrus.JSONFormatter))
+ default:
+ return fmt.Errorf("unknown log-format %q", context.GlobalString("log-format"))
+ }
+ return nil
+ }
+ // If the command returns an error, cli takes upon itself to print
+ // the error on cli.ErrWriter and exit.
+ // Use our own writer here to ensure the log gets sent to the right location.
+ cli.ErrWriter = &FatalWriter{cli.ErrWriter}
+ if err := app.Run(os.Args); err != nil {
+ fatal(err)
+ }
+}
+
+type FatalWriter struct {
+ cliErrWriter io.Writer
+}
+
+func (f *FatalWriter) Write(p []byte) (n int, err error) {
+ logrus.Error(string(p))
+ return f.cliErrWriter.Write(p)
+}
diff --git a/vendor/github.com/opencontainers/runc/main_solaris.go b/vendor/github.com/opencontainers/runc/main_solaris.go
new file mode 100644
index 0000000..725381d
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/main_solaris.go
@@ -0,0 +1,21 @@
+// +build solaris
+
+package runc
+
+import "github.com/urfave/cli"
+
+var (
+ checkpointCommand cli.Command
+ eventsCommand cli.Command
+ restoreCommand cli.Command
+ specCommand cli.Command
+ killCommand cli.Command
+ deleteCommand cli.Command
+ execCommand cli.Command
+ initCommand cli.Command
+ listCommand cli.Command
+ pauseCommand cli.Command
+ resumeCommand cli.Command
+ startCommand cli.Command
+ stateCommand cli.Command
+)
diff --git a/vendor/github.com/opencontainers/runc/main_unix.go b/vendor/github.com/opencontainers/runc/main_unix.go
new file mode 100644
index 0000000..371e011
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/main_unix.go
@@ -0,0 +1,33 @@
+// +build linux
+
+package runc
+
+import (
+ "os"
+ "runtime"
+
+ "github.com/opencontainers/runc/libcontainer"
+ _ "github.com/opencontainers/runc/libcontainer/nsenter"
+ "github.com/urfave/cli"
+)
+
+func init() {
+ if len(os.Args) > 1 && os.Args[1] == "init" {
+ runtime.GOMAXPROCS(1)
+ runtime.LockOSThread()
+ }
+}
+
+var initCommand = cli.Command{
+ Name: "init",
+ Usage: `initialize the namespaces and launch the process (do not call it outside of runc)`,
+ Action: func(context *cli.Context) error {
+ factory, _ := libcontainer.New("")
+ if err := factory.StartInitialization(); err != nil {
+ // as the error is sent back to the parent there is no need to log
+ // or write it to stderr because the parent process will handle this
+ os.Exit(1)
+ }
+ panic("libcontainer: container init failed to exec")
+ },
+}
diff --git a/vendor/github.com/opencontainers/runc/main_unsupported.go b/vendor/github.com/opencontainers/runc/main_unsupported.go
new file mode 100644
index 0000000..85dc547
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/main_unsupported.go
@@ -0,0 +1,13 @@
+// +build !linux,!solaris
+
+package runc
+
+import "github.com/urfave/cli"
+
+var (
+ checkpointCommand cli.Command
+ eventsCommand cli.Command
+ restoreCommand cli.Command
+ specCommand cli.Command
+ killCommand cli.Command
+)
diff --git a/vendor/github.com/opencontainers/runc/notify_socket.go b/vendor/github.com/opencontainers/runc/notify_socket.go
new file mode 100644
index 0000000..6073d37
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/notify_socket.go
@@ -0,0 +1,108 @@
+// +build linux
+
+package runc
+
+import (
+ "bytes"
+ "fmt"
+ "net"
+ "path/filepath"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/urfave/cli"
+)
+
+type notifySocket struct {
+ socket *net.UnixConn
+ host string
+ socketPath string
+}
+
+func newNotifySocket(context *cli.Context, notifySocketHost string, id string) *notifySocket {
+ if notifySocketHost == "" {
+ return nil
+ }
+
+ root := filepath.Join(context.GlobalString("root"), id)
+ path := filepath.Join(root, "notify.sock")
+
+ notifySocket := &notifySocket{
+ socket: nil,
+ host: notifySocketHost,
+ socketPath: path,
+ }
+
+ return notifySocket
+}
+
+func (ns *notifySocket) Close() error {
+ return ns.socket.Close()
+}
+
+// If systemd is supporting sd_notify protocol, this function will add support
+// for sd_notify protocol from within the container.
+func (s *notifySocket) setupSpec(context *cli.Context, spec *specs.Spec) {
+ mount := specs.Mount{Destination: s.host, Type: "bind", Source: s.socketPath, Options: []string{"bind"}}
+ spec.Mounts = append(spec.Mounts, mount)
+ spec.Process.Env = append(spec.Process.Env, fmt.Sprintf("NOTIFY_SOCKET=%s", s.host))
+}
+
+func (s *notifySocket) setupSocket() error {
+ addr := net.UnixAddr{
+ Name: s.socketPath,
+ Net: "unixgram",
+ }
+
+ socket, err := net.ListenUnixgram("unixgram", &addr)
+ if err != nil {
+ return err
+ }
+
+ s.socket = socket
+ return nil
+}
+
+// pid1 must be set only with -d, as it is used to set the new process as the main process
+// for the service in systemd
+func (notifySocket *notifySocket) run(pid1 int) {
+ buf := make([]byte, 512)
+ notifySocketHostAddr := net.UnixAddr{Name: notifySocket.host, Net: "unixgram"}
+ client, err := net.DialUnix("unixgram", nil, &notifySocketHostAddr)
+ if err != nil {
+ logrus.Error(err)
+ return
+ }
+ for {
+ r, err := notifySocket.socket.Read(buf)
+ if err != nil {
+ break
+ }
+ var out bytes.Buffer
+ for _, line := range bytes.Split(buf[0:r], []byte{'\n'}) {
+ if bytes.HasPrefix(line, []byte("READY=")) {
+ _, err = out.Write(line)
+ if err != nil {
+ return
+ }
+
+ _, err = out.Write([]byte{'\n'})
+ if err != nil {
+ return
+ }
+
+ _, err = client.Write(out.Bytes())
+ if err != nil {
+ return
+ }
+
+ // now we can inform systemd to use pid1 as the pid to monitor
+ if pid1 > 0 {
+ newPid := fmt.Sprintf("MAINPID=%d\n", pid1)
+ client.Write([]byte(newPid))
+ }
+ return
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/opencontainers/runc/pause.go b/vendor/github.com/opencontainers/runc/pause.go
new file mode 100644
index 0000000..fe79f51
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/pause.go
@@ -0,0 +1,57 @@
+// +build linux
+
+package runc
+
+import "github.com/urfave/cli"
+
+var pauseCommand = cli.Command{
+ Name: "pause",
+ Usage: "pause suspends all processes inside the container",
+ ArgsUsage: `<container-id>
+
+Where "<container-id>" is the name for the instance of the container to be
+paused. `,
+ Description: `The pause command suspends all processes in the instance of the container.
+
+Use runc list to identiy instances of containers and their current status.`,
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+ container, err := getContainer(context)
+ if err != nil {
+ return err
+ }
+ if err := container.Pause(); err != nil {
+ return err
+ }
+
+ return nil
+ },
+}
+
+var resumeCommand = cli.Command{
+ Name: "resume",
+ Usage: "resumes all processes that have been previously paused",
+ ArgsUsage: `<container-id>
+
+Where "<container-id>" is the name for the instance of the container to be
+resumed.`,
+ Description: `The resume command resumes all processes in the instance of the container.
+
+Use runc list to identiy instances of containers and their current status.`,
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+ container, err := getContainer(context)
+ if err != nil {
+ return err
+ }
+ if err := container.Resume(); err != nil {
+ return err
+ }
+
+ return nil
+ },
+}
diff --git a/vendor/github.com/opencontainers/runc/ps.go b/vendor/github.com/opencontainers/runc/ps.go
new file mode 100644
index 0000000..84ae5a4
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/ps.go
@@ -0,0 +1,109 @@
+// +build linux
+
+package runc
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "strconv"
+ "strings"
+
+ "github.com/urfave/cli"
+)
+
+var psCommand = cli.Command{
+ Name: "ps",
+ Usage: "ps displays the processes running inside a container",
+ ArgsUsage: `<container-id> [ps options]`,
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "format, f",
+ Value: "table",
+ Usage: `select one of: ` + formatOptions,
+ },
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, minArgs); err != nil {
+ return err
+ }
+ // XXX: Currently not supported with rootless containers.
+ if isRootless() {
+ return fmt.Errorf("runc ps requires root")
+ }
+
+ container, err := getContainer(context)
+ if err != nil {
+ return err
+ }
+
+ pids, err := container.Processes()
+ if err != nil {
+ return err
+ }
+
+ switch context.String("format") {
+ case "table":
+ case "json":
+ return json.NewEncoder(os.Stdout).Encode(pids)
+ default:
+ return fmt.Errorf("invalid format option")
+ }
+
+ // [1:] is to remove command name, ex:
+ // context.Args(): [containet_id ps_arg1 ps_arg2 ...]
+ // psArgs: [ps_arg1 ps_arg2 ...]
+ //
+ psArgs := context.Args()[1:]
+ if len(psArgs) == 0 {
+ psArgs = []string{"-ef"}
+ }
+
+ cmd := exec.Command("ps", psArgs...)
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s: %s", err, output)
+ }
+
+ lines := strings.Split(string(output), "\n")
+ pidIndex, err := getPidIndex(lines[0])
+ if err != nil {
+ return err
+ }
+
+ fmt.Println(lines[0])
+ for _, line := range lines[1:] {
+ if len(line) == 0 {
+ continue
+ }
+ fields := strings.Fields(line)
+ p, err := strconv.Atoi(fields[pidIndex])
+ if err != nil {
+ return fmt.Errorf("unexpected pid '%s': %s", fields[pidIndex], err)
+ }
+
+ for _, pid := range pids {
+ if pid == p {
+ fmt.Println(line)
+ break
+ }
+ }
+ }
+ return nil
+ },
+ SkipArgReorder: true,
+}
+
+func getPidIndex(title string) (int, error) {
+ titles := strings.Fields(title)
+
+ pidIndex := -1
+ for i, name := range titles {
+ if name == "PID" {
+ return i, nil
+ }
+ }
+
+ return pidIndex, fmt.Errorf("couldn't find PID field in ps output")
+}
diff --git a/vendor/github.com/opencontainers/runc/restore.go b/vendor/github.com/opencontainers/runc/restore.go
new file mode 100644
index 0000000..93e5748
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/restore.go
@@ -0,0 +1,216 @@
+// +build linux
+
+package runc
+
+import (
+ "fmt"
+ "os"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/specconv"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/urfave/cli"
+)
+
+var restoreCommand = cli.Command{
+ Name: "restore",
+ Usage: "restore a container from a previous checkpoint",
+ ArgsUsage: `<container-id>
+
+Where "<container-id>" is the name for the instance of the container to be
+restored.`,
+ Description: `Restores the saved state of the container instance that was previously saved
+using the runc checkpoint command.`,
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "image-path",
+ Value: "",
+ Usage: "path to criu image files for restoring",
+ },
+ cli.StringFlag{
+ Name: "work-path",
+ Value: "",
+ Usage: "path for saving work files and logs",
+ },
+ cli.BoolFlag{
+ Name: "tcp-established",
+ Usage: "allow open tcp connections",
+ },
+ cli.BoolFlag{
+ Name: "ext-unix-sk",
+ Usage: "allow external unix sockets",
+ },
+ cli.BoolFlag{
+ Name: "shell-job",
+ Usage: "allow shell jobs",
+ },
+ cli.BoolFlag{
+ Name: "file-locks",
+ Usage: "handle file locks, for safety",
+ },
+ cli.StringFlag{
+ Name: "manage-cgroups-mode",
+ Value: "",
+ Usage: "cgroups mode: 'soft' (default), 'full' and 'strict'",
+ },
+ cli.StringFlag{
+ Name: "bundle, b",
+ Value: "",
+ Usage: "path to the root of the bundle directory",
+ },
+ cli.BoolFlag{
+ Name: "detach,d",
+ Usage: "detach from the container's process",
+ },
+ cli.StringFlag{
+ Name: "pid-file",
+ Value: "",
+ Usage: "specify the file to write the process id to",
+ },
+ cli.BoolFlag{
+ Name: "no-subreaper",
+ Usage: "disable the use of the subreaper used to reap reparented processes",
+ },
+ cli.BoolFlag{
+ Name: "no-pivot",
+ Usage: "do not use pivot root to jail process inside rootfs. This should be used whenever the rootfs is on top of a ramdisk",
+ },
+ cli.StringSliceFlag{
+ Name: "empty-ns",
+ Usage: "create a namespace, but don't restore its properties",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+ // XXX: Currently this is untested with rootless containers.
+ if isRootless() {
+ return fmt.Errorf("runc restore requires root")
+ }
+
+ imagePath := context.String("image-path")
+ id := context.Args().First()
+ if id == "" {
+ return errEmptyID
+ }
+ if imagePath == "" {
+ imagePath = getDefaultImagePath(context)
+ }
+ bundle := context.String("bundle")
+ if bundle != "" {
+ if err := os.Chdir(bundle); err != nil {
+ return err
+ }
+ }
+ spec, err := loadSpec(specConfig)
+ if err != nil {
+ return err
+ }
+ config, err := specconv.CreateLibcontainerConfig(&specconv.CreateOpts{
+ CgroupName: id,
+ UseSystemdCgroup: context.GlobalBool("systemd-cgroup"),
+ NoPivotRoot: context.Bool("no-pivot"),
+ Spec: spec,
+ })
+ if err != nil {
+ return err
+ }
+ status, err := restoreContainer(context, spec, config, imagePath)
+ if err == nil {
+ os.Exit(status)
+ }
+ return err
+ },
+}
+
+func restoreContainer(context *cli.Context, spec *specs.Spec, config *configs.Config, imagePath string) (int, error) {
+ var (
+ rootuid = 0
+ rootgid = 0
+ id = context.Args().First()
+ )
+ factory, err := loadFactory(context)
+ if err != nil {
+ return -1, err
+ }
+ container, err := factory.Load(id)
+ if err != nil {
+ container, err = factory.Create(id, config)
+ if err != nil {
+ return -1, err
+ }
+ }
+ options := criuOptions(context)
+
+ status, err := container.Status()
+ if err != nil {
+ logrus.Error(err)
+ }
+ if status == libcontainer.Running {
+ fatalf("Container with id %s already running", id)
+ }
+
+ setManageCgroupsMode(context, options)
+
+ if err = setEmptyNsMask(context, options); err != nil {
+ return -1, err
+ }
+
+ // ensure that the container is always removed if we were the process
+ // that created it.
+ detach := context.Bool("detach")
+ if !detach {
+ defer destroy(container)
+ }
+ process := &libcontainer.Process{}
+ tty, err := setupIO(process, rootuid, rootgid, false, detach, "")
+ if err != nil {
+ return -1, err
+ }
+
+ notifySocket := newNotifySocket(context, os.Getenv("NOTIFY_SOCKET"), id)
+ if notifySocket != nil {
+ notifySocket.setupSpec(context, spec)
+ notifySocket.setupSocket()
+ }
+
+ handler := newSignalHandler(!context.Bool("no-subreaper"), notifySocket)
+ if err := container.Restore(process, options); err != nil {
+ return -1, err
+ }
+ // We don't need to do a tty.recvtty because config.Terminal is always false.
+ defer tty.Close()
+ if err := tty.ClosePostStart(); err != nil {
+ return -1, err
+ }
+ if pidFile := context.String("pid-file"); pidFile != "" {
+ if err := createPidFile(pidFile, process); err != nil {
+ _ = process.Signal(syscall.SIGKILL)
+ _, _ = process.Wait()
+ return -1, err
+ }
+ }
+ return handler.forward(process, tty, detach)
+}
+
+func criuOptions(context *cli.Context) *libcontainer.CriuOpts {
+ imagePath := getCheckpointImagePath(context)
+ if err := os.MkdirAll(imagePath, 0655); err != nil {
+ fatal(err)
+ }
+ return &libcontainer.CriuOpts{
+ ImagesDirectory: imagePath,
+ WorkDirectory: context.String("work-path"),
+ ParentImage: context.String("parent-path"),
+ LeaveRunning: context.Bool("leave-running"),
+ TcpEstablished: context.Bool("tcp-established"),
+ ExternalUnixConnections: context.Bool("ext-unix-sk"),
+ ShellJob: context.Bool("shell-job"),
+ FileLocks: context.Bool("file-locks"),
+ PreDump: context.Bool("pre-dump"),
+ }
+}
diff --git a/vendor/github.com/opencontainers/runc/rlimit_linux.go b/vendor/github.com/opencontainers/runc/rlimit_linux.go
new file mode 100644
index 0000000..fc2c5f9
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/rlimit_linux.go
@@ -0,0 +1,49 @@
+package runc
+
+import "fmt"
+
+const (
+ RLIMIT_CPU = iota // CPU time in sec
+ RLIMIT_FSIZE // Maximum filesize
+ RLIMIT_DATA // max data size
+ RLIMIT_STACK // max stack size
+ RLIMIT_CORE // max core file size
+ RLIMIT_RSS // max resident set size
+ RLIMIT_NPROC // max number of processes
+ RLIMIT_NOFILE // max number of open files
+ RLIMIT_MEMLOCK // max locked-in-memory address space
+ RLIMIT_AS // address space limit
+ RLIMIT_LOCKS // maximum file locks held
+ RLIMIT_SIGPENDING // max number of pending signals
+ RLIMIT_MSGQUEUE // maximum bytes in POSIX mqueues
+ RLIMIT_NICE // max nice prio allowed to raise to
+ RLIMIT_RTPRIO // maximum realtime priority
+ RLIMIT_RTTIME // timeout for RT tasks in us
+)
+
+var rlimitMap = map[string]int{
+ "RLIMIT_CPU": RLIMIT_CPU,
+ "RLIMIT_FSIZE": RLIMIT_FSIZE,
+ "RLIMIT_DATA": RLIMIT_DATA,
+ "RLIMIT_STACK": RLIMIT_STACK,
+ "RLIMIT_CORE": RLIMIT_CORE,
+ "RLIMIT_RSS": RLIMIT_RSS,
+ "RLIMIT_NPROC": RLIMIT_NPROC,
+ "RLIMIT_NOFILE": RLIMIT_NOFILE,
+ "RLIMIT_MEMLOCK": RLIMIT_MEMLOCK,
+ "RLIMIT_AS": RLIMIT_AS,
+ "RLIMIT_LOCKS": RLIMIT_LOCKS,
+ "RLIMIT_SIGPENDING": RLIMIT_SIGPENDING,
+ "RLIMIT_MSGQUEUE": RLIMIT_MSGQUEUE,
+ "RLIMIT_NICE": RLIMIT_NICE,
+ "RLIMIT_RTPRIO": RLIMIT_RTPRIO,
+ "RLIMIT_RTTIME": RLIMIT_RTTIME,
+}
+
+func strToRlimit(key string) (int, error) {
+ rl, ok := rlimitMap[key]
+ if !ok {
+ return 0, fmt.Errorf("wrong rlimit value: %s", key)
+ }
+ return rl, nil
+}
diff --git a/vendor/github.com/opencontainers/runc/run.go b/vendor/github.com/opencontainers/runc/run.go
new file mode 100644
index 0000000..be8458a
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/run.go
@@ -0,0 +1,84 @@
+// +build linux
+
+package runc
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+// default action is to start a container
+var runCommand = cli.Command{
+ Name: "run",
+ Usage: "create and run a container",
+ ArgsUsage: `<container-id>
+
+Where "<container-id>" is your name for the instance of the container that you
+are starting. The name you provide for the container instance must be unique on
+your host.`,
+ Description: `The run command creates an instance of a container for a bundle. The bundle
+is a directory with a specification file named "` + specConfig + `" and a root
+filesystem.
+
+The specification file includes an args parameter. The args parameter is used
+to specify command(s) that get run when the container is started. To change the
+command(s) that get executed on start, edit the args parameter of the spec. See
+"runc spec --help" for more explanation.`,
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "bundle, b",
+ Value: "",
+ Usage: `path to the root of the bundle directory, defaults to the current directory`,
+ },
+ cli.StringFlag{
+ Name: "console-socket",
+ Value: "",
+ Usage: "path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal",
+ },
+ cli.BoolFlag{
+ Name: "detach, d",
+ Usage: "detach from the container's process",
+ },
+ cli.StringFlag{
+ Name: "pid-file",
+ Value: "",
+ Usage: "specify the file to write the process id to",
+ },
+ cli.BoolFlag{
+ Name: "no-subreaper",
+ Usage: "disable the use of the subreaper used to reap reparented processes",
+ },
+ cli.BoolFlag{
+ Name: "no-pivot",
+ Usage: "do not use pivot root to jail process inside rootfs. This should be used whenever the rootfs is on top of a ramdisk",
+ },
+ cli.BoolFlag{
+ Name: "no-new-keyring",
+ Usage: "do not create a new session keyring for the container. This will cause the container to inherit the calling processes session key",
+ },
+ cli.IntFlag{
+ Name: "preserve-fds",
+ Usage: "Pass N additional file descriptors to the container (stdio + $LISTEN_FDS + N in total)",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+ if err := revisePidFile(context); err != nil {
+ return err
+ }
+ spec, err := setupSpec(context)
+ if err != nil {
+ return err
+ }
+ status, err := startContainer(context, spec, false)
+ if err == nil {
+ // exit with the container's exit status so any external supervisor is
+ // notified of the exit with the correct exit status.
+ os.Exit(status)
+ }
+ return err
+ },
+}
diff --git a/vendor/github.com/opencontainers/runc/signals.go b/vendor/github.com/opencontainers/runc/signals.go
new file mode 100644
index 0000000..5cd2f2a
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/signals.go
@@ -0,0 +1,135 @@
+// +build linux
+
+package runc
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/opencontainers/runc/libcontainer/system"
+ "github.com/opencontainers/runc/libcontainer/utils"
+)
+
+const signalBufferSize = 2048
+
+// newSignalHandler returns a signal handler for processing SIGCHLD and SIGWINCH signals
+// while still forwarding all other signals to the process.
+// If notifySocket is present, use it to read systemd notifications from the container and
+// forward them to notifySocketHost.
+func newSignalHandler(enableSubreaper bool, notifySocket *notifySocket) *signalHandler {
+ if enableSubreaper {
+ // set us as the subreaper before registering the signal handler for the container
+ if err := system.SetSubreaper(1); err != nil {
+ logrus.Warn(err)
+ }
+ }
+ // ensure that we have a large buffer size so that we do not miss any signals
+ // incase we are not processing them fast enough.
+ s := make(chan os.Signal, signalBufferSize)
+ // handle all signals for the process.
+ signal.Notify(s)
+ return &signalHandler{
+ signals: s,
+ notifySocket: notifySocket,
+ }
+}
+
+// exit models a process exit status with the pid and
+// exit status.
+type exit struct {
+ pid int
+ status int
+}
+
+type signalHandler struct {
+ signals chan os.Signal
+ notifySocket *notifySocket
+}
+
+// forward handles the main signal event loop forwarding, resizing, or reaping depending
+// on the signal received.
+func (h *signalHandler) forward(process *libcontainer.Process, tty *tty, detach bool) (int, error) {
+ // make sure we know the pid of our main process so that we can return
+ // after it dies.
+ if detach && h.notifySocket == nil {
+ return 0, nil
+ }
+
+ pid1, err := process.Pid()
+ if err != nil {
+ return -1, err
+ }
+
+ if h.notifySocket != nil {
+ if detach {
+ h.notifySocket.run(pid1)
+ return 0, nil
+ } else {
+ go h.notifySocket.run(0)
+ }
+ }
+
+ // perform the initial tty resize.
+ tty.resize()
+ for s := range h.signals {
+ switch s {
+ case syscall.SIGWINCH:
+ tty.resize()
+ case syscall.SIGCHLD:
+ exits, err := h.reap()
+ if err != nil {
+ logrus.Error(err)
+ }
+ for _, e := range exits {
+ logrus.WithFields(logrus.Fields{
+ "pid": e.pid,
+ "status": e.status,
+ }).Debug("process exited")
+ if e.pid == pid1 {
+ // call Wait() on the process even though we already have the exit
+ // status because we must ensure that any of the go specific process
+ // fun such as flushing pipes are complete before we return.
+ process.Wait()
+ if h.notifySocket != nil {
+ h.notifySocket.Close()
+ }
+ return e.status, nil
+ }
+ }
+ default:
+ logrus.Debugf("sending signal to process %s", s)
+ if err := syscall.Kill(pid1, s.(syscall.Signal)); err != nil {
+ logrus.Error(err)
+ }
+ }
+ }
+ return -1, nil
+}
+
+// reap runs wait4 in a loop until we have finished processing any existing exits
+// then returns all exits to the main event loop for further processing.
+func (h *signalHandler) reap() (exits []exit, err error) {
+ var (
+ ws syscall.WaitStatus
+ rus syscall.Rusage
+ )
+ for {
+ pid, err := syscall.Wait4(-1, &ws, syscall.WNOHANG, &rus)
+ if err != nil {
+ if err == syscall.ECHILD {
+ return exits, nil
+ }
+ return nil, err
+ }
+ if pid <= 0 {
+ return exits, nil
+ }
+ exits = append(exits, exit{
+ pid: pid,
+ status: utils.ExitStatus(ws),
+ })
+ }
+}
diff --git a/vendor/github.com/opencontainers/runc/spec.go b/vendor/github.com/opencontainers/runc/spec.go
new file mode 100644
index 0000000..e5feb71
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/spec.go
@@ -0,0 +1,160 @@
+// +build linux
+
+package runc
+
+import (
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "runtime"
+
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/specconv"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/urfave/cli"
+)
+
+var specCommand = cli.Command{
+ Name: "spec",
+ Usage: "create a new specification file",
+ ArgsUsage: "",
+ Description: `The spec command creates the new specification file named "` + specConfig + `" for
+the bundle.
+
+The spec generated is just a starter file. Editing of the spec is required to
+achieve desired results. For example, the newly generated spec includes an args
+parameter that is initially set to call the "sh" command when the container is
+started. Calling "sh" may work for an ubuntu container or busybox, but will not
+work for containers that do not include the "sh" program.
+
+EXAMPLE:
+ To run docker's hello-world container one needs to set the args parameter
+in the spec to call hello. This can be done using the sed command or a text
+editor. The following commands create a bundle for hello-world, change the
+default args parameter in the spec from "sh" to "/hello", then run the hello
+command in a new hello-world container named container1:
+
+ mkdir hello
+ cd hello
+ docker pull hello-world
+ docker export $(docker create hello-world) > hello-world.tar
+ mkdir rootfs
+ tar -C rootfs -xf hello-world.tar
+ runc spec
+ sed -i 's;"sh";"/hello";' ` + specConfig + `
+ runc run container1
+
+In the run command above, "container1" is the name for the instance of the
+container that you are starting. The name you provide for the container instance
+must be unique on your host.
+
+An alternative for generating a customized spec config is to use "oci-runtime-tool", the
+sub-command "oci-runtime-tool generate" has lots of options that can be used to do any
+customizations as you want, see runtime-tools (https://github.com/opencontainers/runtime-tools)
+to get more information.
+
+When starting a container through runc, runc needs root privilege. If not
+already running as root, you can use sudo to give runc root privilege. For
+example: "sudo runc start container1" will give runc root privilege to start the
+container on your host.
+
+Alternatively, you can start a rootless container, which has the ability to run
+without root privileges. For this to work, the specification file needs to be
+adjusted accordingly. You can pass the parameter --rootless to this command to
+generate a proper rootless spec file.`,
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "bundle, b",
+ Value: "",
+ Usage: "path to the root of the bundle directory",
+ },
+ cli.BoolFlag{
+ Name: "rootless",
+ Usage: "generate a configuration for a rootless container",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 0, exactArgs); err != nil {
+ return err
+ }
+ spec := specconv.Example()
+
+ rootless := context.Bool("rootless")
+ if rootless {
+ specconv.ToRootless(spec)
+ }
+
+ checkNoFile := func(name string) error {
+ _, err := os.Stat(name)
+ if err == nil {
+ return fmt.Errorf("File %s exists. Remove it first", name)
+ }
+ if !os.IsNotExist(err) {
+ return err
+ }
+ return nil
+ }
+ bundle := context.String("bundle")
+ if bundle != "" {
+ if err := os.Chdir(bundle); err != nil {
+ return err
+ }
+ }
+ if err := checkNoFile(specConfig); err != nil {
+ return err
+ }
+ data, err := json.MarshalIndent(spec, "", "\t")
+ if err != nil {
+ return err
+ }
+ if err := ioutil.WriteFile(specConfig, data, 0666); err != nil {
+ return err
+ }
+ return nil
+ },
+}
+
+func sPtr(s string) *string { return &s }
+
+// loadSpec loads the specification from the provided path.
+func loadSpec(cPath string) (spec *specs.Spec, err error) {
+ cf, err := os.Open(cPath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, fmt.Errorf("JSON specification file %s not found", cPath)
+ }
+ return nil, err
+ }
+ defer cf.Close()
+
+ if err = json.NewDecoder(cf).Decode(&spec); err != nil {
+ return nil, err
+ }
+ if err = validatePlatform(&spec.Platform); err != nil {
+ return nil, err
+ }
+ return spec, validateProcessSpec(&spec.Process)
+}
+
+func createLibContainerRlimit(rlimit specs.LinuxRlimit) (configs.Rlimit, error) {
+ rl, err := strToRlimit(rlimit.Type)
+ if err != nil {
+ return configs.Rlimit{}, err
+ }
+ return configs.Rlimit{
+ Type: rl,
+ Hard: rlimit.Hard,
+ Soft: rlimit.Soft,
+ }, nil
+}
+
+func validatePlatform(platform *specs.Platform) error {
+ if platform.OS != runtime.GOOS {
+ return fmt.Errorf("target os %s mismatch with current os %s", platform.OS, runtime.GOOS)
+ }
+ if platform.Arch != runtime.GOARCH {
+ return fmt.Errorf("target arch %s mismatch with current arch %s", platform.Arch, runtime.GOARCH)
+ }
+ return nil
+}
diff --git a/vendor/github.com/opencontainers/runc/start.go b/vendor/github.com/opencontainers/runc/start.go
new file mode 100644
index 0000000..9c8ca61
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/start.go
@@ -0,0 +1,43 @@
+package runc
+
+import (
+ "errors"
+ "fmt"
+
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/urfave/cli"
+)
+
+var startCommand = cli.Command{
+ Name: "start",
+ Usage: "executes the user defined process in a created container",
+ ArgsUsage: `<container-id>
+
+Where "<container-id>" is your name for the instance of the container that you
+are starting. The name you provide for the container instance must be unique on
+your host.`,
+ Description: `The start command executes the user defined process in a created container.`,
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+ container, err := getContainer(context)
+ if err != nil {
+ return err
+ }
+ status, err := container.Status()
+ if err != nil {
+ return err
+ }
+ switch status {
+ case libcontainer.Created:
+ return container.Exec()
+ case libcontainer.Stopped:
+ return errors.New("cannot start a container that has stopped")
+ case libcontainer.Running:
+ return errors.New("cannot start an already running container")
+ default:
+ return fmt.Errorf("cannot start a container in the %s state\n", status)
+ }
+ },
+}
diff --git a/vendor/github.com/opencontainers/runc/state.go b/vendor/github.com/opencontainers/runc/state.go
new file mode 100644
index 0000000..ddd99cd
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/state.go
@@ -0,0 +1,60 @@
+// +build linux
+
+package runc
+
+import (
+ "encoding/json"
+ "os"
+
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/opencontainers/runc/libcontainer/utils"
+ "github.com/urfave/cli"
+)
+
+var stateCommand = cli.Command{
+ Name: "state",
+ Usage: "output the state of a container",
+ ArgsUsage: `<container-id>
+
+Where "<container-id>" is your name for the instance of the container.`,
+ Description: `The state command outputs current state information for the
+instance of a container.`,
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+ container, err := getContainer(context)
+ if err != nil {
+ return err
+ }
+ containerStatus, err := container.Status()
+ if err != nil {
+ return err
+ }
+ state, err := container.State()
+ if err != nil {
+ return err
+ }
+ pid := state.BaseState.InitProcessPid
+ if containerStatus == libcontainer.Stopped {
+ pid = 0
+ }
+ bundle, annotations := utils.Annotations(state.Config.Labels)
+ cs := containerState{
+ Version: state.BaseState.Config.Version,
+ ID: state.BaseState.ID,
+ InitProcessPid: pid,
+ Status: containerStatus.String(),
+ Bundle: bundle,
+ Rootfs: state.BaseState.Config.Rootfs,
+ Created: state.BaseState.Created,
+ Annotations: annotations,
+ }
+ data, err := json.MarshalIndent(cs, "", " ")
+ if err != nil {
+ return err
+ }
+ os.Stdout.Write(data)
+ return nil
+ },
+}
diff --git a/vendor/github.com/opencontainers/runc/tty.go b/vendor/github.com/opencontainers/runc/tty.go
new file mode 100644
index 0000000..5596b46
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/tty.go
@@ -0,0 +1,134 @@
+// +build linux
+
+package runc
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "sync"
+
+ "github.com/docker/docker/pkg/term"
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/opencontainers/runc/libcontainer/utils"
+)
+
+type tty struct {
+ console libcontainer.Console
+ state *term.State
+ closers []io.Closer
+ postStart []io.Closer
+ wg sync.WaitGroup
+ consoleC chan error
+}
+
+func (t *tty) copyIO(w io.Writer, r io.ReadCloser) {
+ defer t.wg.Done()
+ io.Copy(w, r)
+ r.Close()
+}
+
+// setup pipes for the process so that advanced features like c/r are able to easily checkpoint
+// and restore the process's IO without depending on a host specific path or device
+func setupProcessPipes(p *libcontainer.Process, rootuid, rootgid int) (*tty, error) {
+ i, err := p.InitializeIO(rootuid, rootgid)
+ if err != nil {
+ return nil, err
+ }
+ t := &tty{
+ closers: []io.Closer{
+ i.Stdin,
+ i.Stdout,
+ i.Stderr,
+ },
+ }
+ // add the process's io to the post start closers if they support close
+ for _, cc := range []interface{}{
+ p.Stdin,
+ p.Stdout,
+ p.Stderr,
+ } {
+ if c, ok := cc.(io.Closer); ok {
+ t.postStart = append(t.postStart, c)
+ }
+ }
+ go func() {
+ io.Copy(i.Stdin, os.Stdin)
+ i.Stdin.Close()
+ }()
+ t.wg.Add(2)
+ go t.copyIO(os.Stdout, i.Stdout)
+ go t.copyIO(os.Stderr, i.Stderr)
+ return t, nil
+}
+
+func inheritStdio(process *libcontainer.Process) error {
+ process.Stdin = os.Stdin
+ process.Stdout = os.Stdout
+ process.Stderr = os.Stderr
+ return nil
+}
+
+func (t *tty) recvtty(process *libcontainer.Process, socket *os.File) error {
+ f, err := utils.RecvFd(socket)
+ if err != nil {
+ return err
+ }
+ console := libcontainer.ConsoleFromFile(f)
+ go io.Copy(console, os.Stdin)
+ t.wg.Add(1)
+ go t.copyIO(os.Stdout, console)
+ state, err := term.SetRawTerminal(os.Stdin.Fd())
+ if err != nil {
+ return fmt.Errorf("failed to set the terminal from the stdin: %v", err)
+ }
+ t.state = state
+ t.console = console
+ t.closers = []io.Closer{console}
+ return nil
+}
+
+func (t *tty) waitConsole() error {
+ if t.consoleC != nil {
+ return <-t.consoleC
+ }
+ return nil
+}
+
+// ClosePostStart closes any fds that are provided to the container and dup2'd
+// so that we no longer have copy in our process.
+func (t *tty) ClosePostStart() error {
+ for _, c := range t.postStart {
+ c.Close()
+ }
+ return nil
+}
+
+// Close closes all open fds for the tty and/or restores the orignal
+// stdin state to what it was prior to the container execution
+func (t *tty) Close() error {
+ // ensure that our side of the fds are always closed
+ for _, c := range t.postStart {
+ c.Close()
+ }
+ // wait for the copy routines to finish before closing the fds
+ t.wg.Wait()
+ for _, c := range t.closers {
+ c.Close()
+ }
+ if t.state != nil {
+ term.RestoreTerminal(os.Stdin.Fd(), t.state)
+ }
+ return nil
+}
+
+func (t *tty) resize() error {
+ if t.console == nil {
+ return nil
+ }
+ ws, err := term.GetWinsize(os.Stdin.Fd())
+ if err != nil {
+ return err
+ }
+ return term.SetWinsize(t.console.File().Fd(), ws)
+}
diff --git a/vendor/github.com/opencontainers/runc/update.go b/vendor/github.com/opencontainers/runc/update.go
new file mode 100644
index 0000000..549ec35
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/update.go
@@ -0,0 +1,259 @@
+// +build linux
+
+package runc
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "strconv"
+
+ "github.com/docker/go-units"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/urfave/cli"
+)
+
+func i64Ptr(i int64) *int64 { return &i }
+func u64Ptr(i uint64) *uint64 { return &i }
+func u16Ptr(i uint16) *uint16 { return &i }
+
+var updateCommand = cli.Command{
+ Name: "update",
+ Usage: "update container resource constraints",
+ ArgsUsage: `<container-id>`,
+ Flags: []cli.Flag{
+ cli.StringFlag{
+ Name: "resources, r",
+ Value: "",
+ Usage: `path to the file containing the resources to update or '-' to read from the standard input
+
+The accepted format is as follow (unchanged values can be omitted):
+
+{
+ "memory": {
+ "limit": 0,
+ "reservation": 0,
+ "swap": 0,
+ "kernel": 0,
+ "kernelTCP": 0
+ },
+ "cpu": {
+ "shares": 0,
+ "quota": 0,
+ "period": 0,
+ "realtimeRuntime": 0,
+ "realtimePeriod": 0,
+ "cpus": "",
+ "mems": ""
+ },
+ "blockIO": {
+ "blkioWeight": 0
+ }
+}
+
+Note: if data is to be read from a file or the standard input, all
+other options are ignored.
+`,
+ },
+
+ cli.IntFlag{
+ Name: "blkio-weight",
+ Usage: "Specifies per cgroup weight, range is from 10 to 1000",
+ },
+ cli.StringFlag{
+ Name: "cpu-period",
+ Usage: "CPU CFS period to be used for hardcapping (in usecs). 0 to use system default",
+ },
+ cli.StringFlag{
+ Name: "cpu-quota",
+ Usage: "CPU CFS hardcap limit (in usecs). Allowed cpu time in a given period",
+ },
+ cli.StringFlag{
+ Name: "cpu-share",
+ Usage: "CPU shares (relative weight vs. other containers)",
+ },
+ cli.StringFlag{
+ Name: "cpu-rt-period",
+ Usage: "CPU realtime period to be used for hardcapping (in usecs). 0 to use system default",
+ },
+ cli.StringFlag{
+ Name: "cpu-rt-runtime",
+ Usage: "CPU realtime hardcap limit (in usecs). Allowed cpu time in a given period",
+ },
+ cli.StringFlag{
+ Name: "cpuset-cpus",
+ Usage: "CPU(s) to use",
+ },
+ cli.StringFlag{
+ Name: "cpuset-mems",
+ Usage: "Memory node(s) to use",
+ },
+ cli.StringFlag{
+ Name: "kernel-memory",
+ Usage: "Kernel memory limit (in bytes)",
+ },
+ cli.StringFlag{
+ Name: "kernel-memory-tcp",
+ Usage: "Kernel memory limit (in bytes) for tcp buffer",
+ },
+ cli.StringFlag{
+ Name: "memory",
+ Usage: "Memory limit (in bytes)",
+ },
+ cli.StringFlag{
+ Name: "memory-reservation",
+ Usage: "Memory reservation or soft_limit (in bytes)",
+ },
+ cli.StringFlag{
+ Name: "memory-swap",
+ Usage: "Total memory usage (memory + swap); set '-1' to enable unlimited swap",
+ },
+ cli.IntFlag{
+ Name: "pids-limit",
+ Usage: "Maximum number of pids allowed in the container",
+ },
+ },
+ Action: func(context *cli.Context) error {
+ if err := checkArgs(context, 1, exactArgs); err != nil {
+ return err
+ }
+ container, err := getContainer(context)
+ if err != nil {
+ return err
+ }
+
+ r := specs.LinuxResources{
+ Memory: &specs.LinuxMemory{
+ Limit: u64Ptr(0),
+ Reservation: u64Ptr(0),
+ Swap: u64Ptr(0),
+ Kernel: u64Ptr(0),
+ KernelTCP: u64Ptr(0),
+ },
+ CPU: &specs.LinuxCPU{
+ Shares: u64Ptr(0),
+ Quota: i64Ptr(0),
+ Period: u64Ptr(0),
+ RealtimeRuntime: i64Ptr(0),
+ RealtimePeriod: u64Ptr(0),
+ Cpus: "",
+ Mems: "",
+ },
+ BlockIO: &specs.LinuxBlockIO{
+ Weight: u16Ptr(0),
+ },
+ Pids: &specs.LinuxPids{
+ Limit: 0,
+ },
+ }
+
+ config := container.Config()
+
+ if in := context.String("resources"); in != "" {
+ var (
+ f *os.File
+ err error
+ )
+ switch in {
+ case "-":
+ f = os.Stdin
+ default:
+ f, err = os.Open(in)
+ if err != nil {
+ return err
+ }
+ }
+ err = json.NewDecoder(f).Decode(&r)
+ if err != nil {
+ return err
+ }
+ } else {
+ if val := context.Int("blkio-weight"); val != 0 {
+ r.BlockIO.Weight = u16Ptr(uint16(val))
+ }
+ if val := context.String("cpuset-cpus"); val != "" {
+ r.CPU.Cpus = val
+ }
+ if val := context.String("cpuset-mems"); val != "" {
+ r.CPU.Mems = val
+ }
+
+ for _, pair := range []struct {
+ opt string
+ dest *uint64
+ }{
+
+ {"cpu-period", r.CPU.Period},
+ {"cpu-rt-period", r.CPU.RealtimePeriod},
+ {"cpu-share", r.CPU.Shares},
+ } {
+ if val := context.String(pair.opt); val != "" {
+ var err error
+ *pair.dest, err = strconv.ParseUint(val, 10, 64)
+ if err != nil {
+ return fmt.Errorf("invalid value for %s: %s", pair.opt, err)
+ }
+ }
+ }
+ for _, pair := range []struct {
+ opt string
+ dest *int64
+ }{
+
+ {"cpu-quota", r.CPU.Quota},
+ {"cpu-rt-runtime", r.CPU.RealtimeRuntime},
+ } {
+ if val := context.String(pair.opt); val != "" {
+ var err error
+ *pair.dest, err = strconv.ParseInt(val, 10, 64)
+ if err != nil {
+ return fmt.Errorf("invalid value for %s: %s", pair.opt, err)
+ }
+ }
+ }
+ for _, pair := range []struct {
+ opt string
+ dest *uint64
+ }{
+ {"memory", r.Memory.Limit},
+ {"memory-swap", r.Memory.Swap},
+ {"kernel-memory", r.Memory.Kernel},
+ {"kernel-memory-tcp", r.Memory.KernelTCP},
+ {"memory-reservation", r.Memory.Reservation},
+ } {
+ if val := context.String(pair.opt); val != "" {
+ var v int64
+
+ if val != "-1" {
+ v, err = units.RAMInBytes(val)
+ if err != nil {
+ return fmt.Errorf("invalid value for %s: %s", pair.opt, err)
+ }
+ } else {
+ v = -1
+ }
+ *pair.dest = uint64(v)
+ }
+ }
+ r.Pids.Limit = int64(context.Int("pids-limit"))
+ }
+
+ // Update the value
+ config.Cgroups.Resources.BlkioWeight = *r.BlockIO.Weight
+ config.Cgroups.Resources.CpuPeriod = *r.CPU.Period
+ config.Cgroups.Resources.CpuQuota = *r.CPU.Quota
+ config.Cgroups.Resources.CpuShares = *r.CPU.Shares
+ config.Cgroups.Resources.CpuRtPeriod = *r.CPU.RealtimePeriod
+ config.Cgroups.Resources.CpuRtRuntime = *r.CPU.RealtimeRuntime
+ config.Cgroups.Resources.CpusetCpus = r.CPU.Cpus
+ config.Cgroups.Resources.CpusetMems = r.CPU.Mems
+ config.Cgroups.Resources.KernelMemory = *r.Memory.Kernel
+ config.Cgroups.Resources.KernelMemoryTCP = *r.Memory.KernelTCP
+ config.Cgroups.Resources.Memory = *r.Memory.Limit
+ config.Cgroups.Resources.MemoryReservation = *r.Memory.Reservation
+ config.Cgroups.Resources.MemorySwap = *r.Memory.Swap
+ config.Cgroups.Resources.PidsLimit = r.Pids.Limit
+
+ return container.Set(config)
+ },
+}
diff --git a/vendor/github.com/opencontainers/runc/utils.go b/vendor/github.com/opencontainers/runc/utils.go
new file mode 100644
index 0000000..a314d37
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/utils.go
@@ -0,0 +1,82 @@
+package runc
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/urfave/cli"
+)
+
+const (
+ exactArgs = iota
+ minArgs
+ maxArgs
+)
+
+func checkArgs(context *cli.Context, expected, checkType int) error {
+ var err error
+ cmdName := context.Command.Name
+ switch checkType {
+ case exactArgs:
+ if context.NArg() != expected {
+ err = fmt.Errorf("%s: %q requires exactly %d argument(s)", os.Args[0], cmdName, expected)
+ }
+ case minArgs:
+ if context.NArg() < expected {
+ err = fmt.Errorf("%s: %q requires a minimum of %d argument(s)", os.Args[0], cmdName, expected)
+ }
+ case maxArgs:
+ if context.NArg() > expected {
+ err = fmt.Errorf("%s: %q requires a maximum of %d argument(s)", os.Args[0], cmdName, expected)
+ }
+ }
+
+ if err != nil {
+ fmt.Printf("Incorrect Usage.\n\n")
+ cli.ShowCommandHelp(context, cmdName)
+ return err
+ }
+ return nil
+}
+
+// fatal prints the error's details if it is a libcontainer specific error type
+// then exits the program with an exit status of 1.
+func fatal(err error) {
+ // make sure the error is written to the logger
+ logrus.Error(err)
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+}
+
+// setupSpec performs initial setup based on the cli.Context for the container
+func setupSpec(context *cli.Context) (*specs.Spec, error) {
+ bundle := context.String("bundle")
+ if bundle != "" {
+ if err := os.Chdir(bundle); err != nil {
+ return nil, err
+ }
+ }
+ spec, err := loadSpec(specConfig)
+ if err != nil {
+ return nil, err
+ }
+ return spec, nil
+}
+
+func revisePidFile(context *cli.Context) error {
+ pidFile := context.String("pid-file")
+ if pidFile == "" {
+ return nil
+ }
+
+ // convert pid-file to an absolute path so we can write to the right
+ // file after chdir to bundle
+ pidFile, err := filepath.Abs(pidFile)
+ if err != nil {
+ return err
+ }
+ return context.Set("pid-file", pidFile)
+}
diff --git a/vendor/github.com/opencontainers/runc/utils_linux.go b/vendor/github.com/opencontainers/runc/utils_linux.go
new file mode 100644
index 0000000..5ae9381
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/utils_linux.go
@@ -0,0 +1,378 @@
+// +build linux
+
+package runc
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "strconv"
+ "syscall"
+
+ "github.com/Sirupsen/logrus"
+ "github.com/coreos/go-systemd/activation"
+ "github.com/opencontainers/runc/libcontainer"
+ "github.com/opencontainers/runc/libcontainer/cgroups/systemd"
+ "github.com/opencontainers/runc/libcontainer/configs"
+ "github.com/opencontainers/runc/libcontainer/specconv"
+ "github.com/opencontainers/runc/libcontainer/utils"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/urfave/cli"
+)
+
+var errEmptyID = errors.New("container id cannot be empty")
+
+var container libcontainer.Container
+
+// loadFactory returns the configured factory instance for execing containers.
+func loadFactory(context *cli.Context) (libcontainer.Factory, error) {
+ root := context.GlobalString("root")
+ abs, err := filepath.Abs(root)
+ if err != nil {
+ return nil, err
+ }
+ cgroupManager := libcontainer.Cgroupfs
+ if context.GlobalBool("systemd-cgroup") {
+ if systemd.UseSystemd() {
+ cgroupManager = libcontainer.SystemdCgroups
+ } else {
+ return nil, fmt.Errorf("systemd cgroup flag passed, but systemd support for managing cgroups is not available")
+ }
+ }
+ return libcontainer.New(abs, cgroupManager, libcontainer.CriuPath(context.GlobalString("criu")))
+}
+
+// getContainer returns the specified container instance by loading it from state
+// with the default factory.
+func getContainer(context *cli.Context) (libcontainer.Container, error) {
+ id := context.Args().First()
+ if id == "" {
+ return nil, errEmptyID
+ }
+ factory, err := loadFactory(context)
+ if err != nil {
+ return nil, err
+ }
+ return factory.Load(id)
+}
+
+func fatalf(t string, v ...interface{}) {
+ fatal(fmt.Errorf(t, v...))
+}
+
+func getDefaultImagePath(context *cli.Context) string {
+ cwd, err := os.Getwd()
+ if err != nil {
+ panic(err)
+ }
+ return filepath.Join(cwd, "checkpoint")
+}
+
+// newProcess returns a new libcontainer Process with the arguments from the
+// spec and stdio from the current process.
+func newProcess(p specs.Process) (*libcontainer.Process, error) {
+ lp := &libcontainer.Process{
+ Args: p.Args,
+ Env: p.Env,
+ // TODO: fix libcontainer's API to better support uid/gid in a typesafe way.
+ User: fmt.Sprintf("%d:%d", p.User.UID, p.User.GID),
+ Cwd: p.Cwd,
+ Label: p.SelinuxLabel,
+ NoNewPrivileges: &p.NoNewPrivileges,
+ AppArmorProfile: p.ApparmorProfile,
+ }
+ if p.Capabilities != nil {
+ lp.Capabilities = &configs.Capabilities{}
+ lp.Capabilities.Bounding = p.Capabilities.Bounding
+ lp.Capabilities.Effective = p.Capabilities.Effective
+ lp.Capabilities.Inheritable = p.Capabilities.Inheritable
+ lp.Capabilities.Permitted = p.Capabilities.Permitted
+ lp.Capabilities.Ambient = p.Capabilities.Ambient
+ }
+ for _, gid := range p.User.AdditionalGids {
+ lp.AdditionalGroups = append(lp.AdditionalGroups, strconv.FormatUint(uint64(gid), 10))
+ }
+ for _, rlimit := range p.Rlimits {
+ rl, err := createLibContainerRlimit(rlimit)
+ if err != nil {
+ return nil, err
+ }
+ lp.Rlimits = append(lp.Rlimits, rl)
+ }
+ return lp, nil
+}
+
+func destroy(container libcontainer.Container) {
+ if err := container.Destroy(); err != nil {
+ logrus.Error(err)
+ }
+}
+
+// setupIO modifies the given process config according to the options.
+func setupIO(process *libcontainer.Process, rootuid, rootgid int, createTTY, detach bool, sockpath string) (*tty, error) {
+ if createTTY {
+ process.Stdin = nil
+ process.Stdout = nil
+ process.Stderr = nil
+ t := &tty{}
+ if !detach {
+ parent, child, err := utils.NewSockPair("console")
+ if err != nil {
+ return nil, err
+ }
+ process.ConsoleSocket = child
+ t.postStart = append(t.postStart, parent, child)
+ t.consoleC = make(chan error, 1)
+ go func() {
+ if err := t.recvtty(process, parent); err != nil {
+ t.consoleC <- err
+ }
+ t.consoleC <- nil
+ }()
+ } else {
+ // the caller of runc will handle receiving the console master
+ conn, err := net.Dial("unix", sockpath)
+ if err != nil {
+ return nil, err
+ }
+ uc, ok := conn.(*net.UnixConn)
+ if !ok {
+ return nil, fmt.Errorf("casting to UnixConn failed")
+ }
+ t.postStart = append(t.postStart, uc)
+ socket, err := uc.File()
+ if err != nil {
+ return nil, err
+ }
+ t.postStart = append(t.postStart, socket)
+ process.ConsoleSocket = socket
+ }
+ return t, nil
+ }
+ // when runc will detach the caller provides the stdio to runc via runc's 0,1,2
+ // and the container's process inherits runc's stdio.
+ if detach {
+ if err := inheritStdio(process); err != nil {
+ return nil, err
+ }
+ return &tty{}, nil
+ }
+ return setupProcessPipes(process, rootuid, rootgid)
+}
+
+// createPidFile creates a file with the processes pid inside it atomically
+// it creates a temp file with the paths filename + '.' infront of it
+// then renames the file
+func createPidFile(path string, process *libcontainer.Process) error {
+ pid, err := process.Pid()
+ if err != nil {
+ return err
+ }
+ var (
+ tmpDir = filepath.Dir(path)
+ tmpName = filepath.Join(tmpDir, fmt.Sprintf(".%s", filepath.Base(path)))
+ )
+ f, err := os.OpenFile(tmpName, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0666)
+ if err != nil {
+ return err
+ }
+ _, err = fmt.Fprintf(f, "%d", pid)
+ f.Close()
+ if err != nil {
+ return err
+ }
+ return os.Rename(tmpName, path)
+}
+
+// XXX: Currently we autodetect rootless mode.
+func isRootless() bool {
+ return os.Geteuid() != 0
+}
+
+func createContainer(context *cli.Context, id string, spec *specs.Spec) (libcontainer.Container, error) {
+ config, err := specconv.CreateLibcontainerConfig(&specconv.CreateOpts{
+ CgroupName: id,
+ UseSystemdCgroup: context.GlobalBool("systemd-cgroup"),
+ NoPivotRoot: context.Bool("no-pivot"),
+ NoNewKeyring: context.Bool("no-new-keyring"),
+ Spec: spec,
+ Rootless: isRootless(),
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ factory, err := loadFactory(context)
+ if err != nil {
+ return nil, err
+ }
+ return factory.Create(id, config)
+}
+
+type runner struct {
+ enableSubreaper bool
+ shouldDestroy bool
+ detach bool
+ listenFDs []*os.File
+ preserveFDs int
+ pidFile string
+ consoleSocket string
+ container libcontainer.Container
+ create bool
+ notifySocket *notifySocket
+}
+
+func (r *runner) run(config *specs.Process) (int, error) {
+ if err := r.checkTerminal(config); err != nil {
+ r.destroy()
+ return -1, err
+ }
+ process, err := newProcess(*config)
+ if err != nil {
+ r.destroy()
+ return -1, err
+ }
+ if len(r.listenFDs) > 0 {
+ process.Env = append(process.Env, fmt.Sprintf("LISTEN_FDS=%d", len(r.listenFDs)), "LISTEN_PID=1")
+ process.ExtraFiles = append(process.ExtraFiles, r.listenFDs...)
+ }
+ baseFd := 3 + len(process.ExtraFiles)
+ for i := baseFd; i < baseFd+r.preserveFDs; i++ {
+ process.ExtraFiles = append(process.ExtraFiles, os.NewFile(uintptr(i), "PreserveFD:"+strconv.Itoa(i)))
+ }
+ rootuid, err := r.container.Config().HostRootUID()
+ if err != nil {
+ r.destroy()
+ return -1, err
+ }
+ rootgid, err := r.container.Config().HostRootGID()
+ if err != nil {
+ r.destroy()
+ return -1, err
+ }
+ var (
+ detach = r.detach || r.create
+ startFn = r.container.Start
+ )
+ if !r.create {
+ startFn = r.container.Run
+ }
+ // Setting up IO is a two stage process. We need to modify process to deal
+ // with detaching containers, and then we get a tty after the container has
+ // started.
+ handler := newSignalHandler(r.enableSubreaper, r.notifySocket)
+ tty, err := setupIO(process, rootuid, rootgid, config.Terminal, detach, r.consoleSocket)
+ if err != nil {
+ r.destroy()
+ return -1, err
+ }
+ defer tty.Close()
+ if err = startFn(process); err != nil {
+ r.destroy()
+ return -1, err
+ }
+ if err := tty.waitConsole(); err != nil {
+ r.terminate(process)
+ r.destroy()
+ return -1, err
+ }
+ if err = tty.ClosePostStart(); err != nil {
+ r.terminate(process)
+ r.destroy()
+ return -1, err
+ }
+ if r.pidFile != "" {
+ if err = createPidFile(r.pidFile, process); err != nil {
+ r.terminate(process)
+ r.destroy()
+ return -1, err
+ }
+ }
+ status, err := handler.forward(process, tty, detach)
+ if err != nil {
+ r.terminate(process)
+ }
+ if detach {
+ return 0, nil
+ }
+ r.destroy()
+ return status, err
+}
+
+func (r *runner) destroy() {
+ if r.shouldDestroy {
+ destroy(r.container)
+ }
+}
+
+func (r *runner) terminate(p *libcontainer.Process) {
+ _ = p.Signal(syscall.SIGKILL)
+ _, _ = p.Wait()
+}
+
+func (r *runner) checkTerminal(config *specs.Process) error {
+ detach := r.detach || r.create
+ // Check command-line for sanity.
+ if detach && config.Terminal && r.consoleSocket == "" {
+ return fmt.Errorf("cannot allocate tty if runc will detach without setting console socket")
+ }
+ if (!detach || !config.Terminal) && r.consoleSocket != "" {
+ return fmt.Errorf("cannot use console socket if runc will not detach or allocate tty")
+ }
+ return nil
+}
+
+func validateProcessSpec(spec *specs.Process) error {
+ if spec.Cwd == "" {
+ return fmt.Errorf("Cwd property must not be empty")
+ }
+ if !filepath.IsAbs(spec.Cwd) {
+ return fmt.Errorf("Cwd must be an absolute path")
+ }
+ if len(spec.Args) == 0 {
+ return fmt.Errorf("args must not be empty")
+ }
+ return nil
+}
+
+func startContainer(context *cli.Context, spec *specs.Spec, create bool) (int, error) {
+ id := context.Args().First()
+ if id == "" {
+ return -1, errEmptyID
+ }
+
+ notifySocket := newNotifySocket(context, os.Getenv("NOTIFY_SOCKET"), id)
+ if notifySocket != nil {
+ notifySocket.setupSpec(context, spec)
+ }
+
+ container, err := createContainer(context, id, spec)
+ if err != nil {
+ return -1, err
+ }
+
+ if notifySocket != nil {
+ notifySocket.setupSocket()
+ }
+
+ // Support on-demand socket activation by passing file descriptors into the container init process.
+ listenFDs := []*os.File{}
+ if os.Getenv("LISTEN_FDS") != "" {
+ listenFDs = activation.Files(false)
+ }
+ r := &runner{
+ enableSubreaper: !context.Bool("no-subreaper"),
+ shouldDestroy: true,
+ container: container,
+ listenFDs: listenFDs,
+ notifySocket: notifySocket,
+ consoleSocket: context.String("console-socket"),
+ detach: context.Bool("detach"),
+ pidFile: context.String("pid-file"),
+ preserveFDs: context.Int("preserve-fds"),
+ create: create,
+ }
+ return r.run(&spec.Process)
+}
diff --git a/vendor/github.com/opencontainers/runc/vendor.conf b/vendor/github.com/opencontainers/runc/vendor.conf
new file mode 100644
index 0000000..6ab9bf8
--- /dev/null
+++ b/vendor/github.com/opencontainers/runc/vendor.conf
@@ -0,0 +1,21 @@
+# OCI runtime-spec. When updating this, make sure you use a version tag rather
+# than a commit ID so it's much more obvious what version of the spec we are
+# using.
+github.com/opencontainers/runtime-spec v1.0.0-rc5
+# Core libcontainer functionality.
+github.com/mrunalp/fileutils ed869b029674c0e9ce4c0dfa781405c2d9946d08
+github.com/opencontainers/selinux v1.0.0-rc1
+github.com/seccomp/libseccomp-golang 32f571b70023028bd57d9288c20efbcb237f3ce0
+github.com/Sirupsen/logrus 26709e2714106fb8ad40b773b711ebce25b78914
+github.com/syndtr/gocapability e7cb7fa329f456b3855136a2642b197bad7366ba
+github.com/vishvananda/netlink 1e2e08e8a2dcdacaae3f14ac44c5cfa31361f270
+# systemd integration.
+github.com/coreos/go-systemd v14
+github.com/coreos/pkg v3
+github.com/godbus/dbus v3
+github.com/golang/protobuf f7137ae6b19afbfd61a94b746fda3b3fe0491874
+# Command-line interface.
+github.com/docker/docker 0f5c9d301b9b1cca66b3ea0f9dec3b5317d3686d
+github.com/docker/go-units v0.2.0
+github.com/urfave/cli d53eb991652b1d438abdd34ce4bfa3ef1539108e
+golang.org/x/sys 9a7256cb28ed514b4e1e5f68959914c4c28a92e0 https://github.com/golang/sys
diff --git a/vendor/github.com/opencontainers/runtime-spec/LICENSE b/vendor/github.com/opencontainers/runtime-spec/LICENSE
new file mode 100644
index 0000000..bdc4036
--- /dev/null
+++ b/vendor/github.com/opencontainers/runtime-spec/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2015 The Linux Foundation.
+
+ 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/opencontainers/runtime-spec/README.md b/vendor/github.com/opencontainers/runtime-spec/README.md
new file mode 100644
index 0000000..1364f6f
--- /dev/null
+++ b/vendor/github.com/opencontainers/runtime-spec/README.md
@@ -0,0 +1,164 @@
+# Open Container Initiative Runtime Specification
+
+The [Open Container Initiative][oci] develops specifications for standards on Operating System process and application containers.
+
+The specification can be found [here](spec.md).
+
+## Table of Contents
+
+Additional documentation about how this group operates:
+
+- [Code of Conduct][code-of-conduct]
+- [Style and Conventions](style.md)
+- [Roadmap](ROADMAP.md)
+- [Implementations](implementations.md)
+- [Releases](RELEASES.md)
+- [project](project.md)
+- [charter][charter]
+
+## Use Cases
+
+To provide context for users the following section gives example use cases for each part of the spec.
+
+### Application Bundle Builders
+
+Application bundle builders can create a [bundle](bundle.md) directory that includes all of the files required for launching an application as a container.
+The bundle contains an OCI [configuration file](config.md) where the builder can specify host-independent details such as [which executable to launch](config.md#process) and host-specific settings such as [mount](config.md#mounts) locations, [hook](config.md#hooks) paths, Linux [namespaces](config-linux.md#namespaces) and [cgroups](config-linux.md#control-groups).
+Because the configuration includes host-specific settings, application bundle directories copied between two hosts may require configuration adjustments.
+
+### Hook Developers
+
+[Hook](config.md#hooks) developers can extend the functionality of an OCI-compliant runtime by hooking into a container's lifecycle with an external application.
+Example use cases include sophisticated network configuration, volume garbage collection, etc.
+
+### Runtime Developers
+
+Runtime developers can build runtime implementations that run OCI-compliant bundles and container configuration, containing low-level OS and host specific details, on a particular platform.
+
+## Releases
+
+There is a loose [Road Map](./ROADMAP.md).
+During the `0.x` series of OCI releases we make no backwards compatibility guarantees and intend to break the schema during this series.
+
+## Contributing
+
+Development happens on GitHub for the spec.
+Issues are used for bugs and actionable items and longer discussions can happen on the [mailing list](#mailing-list).
+
+The specification and code is licensed under the Apache 2.0 license found in the [LICENSE](./LICENSE) file.
+
+### Discuss your design
+
+The project welcomes submissions, but please let everyone know what you are working on.
+
+Before undertaking a nontrivial change to this specification, send mail to the [mailing list](#mailing-list) to discuss what you plan to do.
+This gives everyone a chance to validate the design, helps prevent duplication of effort, and ensures that the idea fits.
+It also guarantees that the design is sound before code is written; a GitHub pull-request is not the place for high-level discussions.
+
+Typos and grammatical errors can go straight to a pull-request.
+When in doubt, start on the [mailing-list](#mailing-list).
+
+### Weekly Call
+
+The contributors and maintainers of all OCI projects have a weekly meeting on Wednesdays at:
+
+* 8:00 AM (USA Pacific), during [odd weeks][iso-week].
+* 5:00 PM (USA Pacific), during [even weeks][iso-week].
+
+There is an [iCalendar][rfc5545] format for the meetings [here](meeting.ics).
+
+Everyone is welcome to participate via [UberConference web][uberconference] or audio-only: +1 415 968 0849 (no PIN needed).
+An initial agenda will be posted to the [mailing list](#mailing-list) earlier in the week, and everyone is welcome to propose additional topics or suggest other agenda alterations there.
+Minutes are posted to the [mailing list](#mailing-list) and minutes from past calls are archived [here][minutes], with minutes from especially old meetings (September 2015 and earlier) archived [here][runtime-wiki].
+
+### Mailing List
+
+You can subscribe and join the mailing list on [Google Groups][dev-list].
+
+### IRC
+
+OCI discussion happens on #opencontainers on Freenode ([logs][irc-logs]).
+
+### Git commit
+
+#### Sign your work
+
+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 (from http://developercertificate.org):
+
+```
+Developer Certificate of Origin
+Version 1.1
+
+Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
+660 York Street, Suite 102,
+San Francisco, CA 94110 USA
+
+Everyone is permitted to copy and distribute verbatim copies of this
+license document, but changing it is not allowed.
+
+
+Developer's Certificate of Origin 1.1
+
+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) 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 to every git commit message:
+
+ Signed-off-by: Joe Smith <joe@gmail.com>
+
+using your real name (sorry, no pseudonyms or anonymous contributions.)
+
+You can add the sign off when creating the git commit via `git commit -s`.
+
+#### Commit Style
+
+Simple house-keeping for clean git history.
+Read more on [How to Write a Git Commit Message][how-to-git-commit] or the Discussion section of [git-commit(1)][git-commit.1].
+
+1. Separate the subject from body with a blank line
+2. Limit the subject line to 50 characters
+3. Capitalize the subject line
+4. Do not end the subject line with a period
+5. Use the imperative mood in the subject line
+6. Wrap the body at 72 characters
+7. Use the body to explain what and why vs. how
+ * If there was important/useful/essential conversation or information, copy or include a reference
+8. When possible, one keyword to scope the change in the subject (i.e. "README: ...", "runtime: ...")
+
+
+[charter]: https://www.opencontainers.org/about/governance
+[code-of-conduct]: https://github.com/opencontainers/tob/blob/master/code-of-conduct.md
+[dev-list]: https://groups.google.com/a/opencontainers.org/forum/#!forum/dev
+[how-to-git-commit]: http://chris.beams.io/posts/git-commit
+[irc-logs]: http://ircbot.wl.linuxfoundation.org/eavesdrop/%23opencontainers/
+[iso-week]: https://en.wikipedia.org/wiki/ISO_week_date#Calculating_the_week_number_of_a_given_date
+[minutes]: http://ircbot.wl.linuxfoundation.org/meetings/opencontainers/
+[oci]: https://www.opencontainers.org
+[rfc5545]: https://tools.ietf.org/html/rfc5545
+[runtime-wiki]: https://github.com/opencontainers/runtime-spec/wiki
+[uberconference]: https://www.uberconference.com/opencontainers
+
+[git-commit.1]: http://git-scm.com/docs/git-commit
diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go
new file mode 100644
index 0000000..da90405
--- /dev/null
+++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go
@@ -0,0 +1,563 @@
+package specs
+
+import "os"
+
+// Spec is the base configuration for the container.
+type Spec struct {
+ // Version of the Open Container Runtime Specification with which the bundle complies.
+ Version string `json:"ociVersion"`
+ // Platform specifies the configuration's target platform.
+ Platform Platform `json:"platform"`
+ // Process configures the container process.
+ Process Process `json:"process"`
+ // Root configures the container's root filesystem.
+ Root Root `json:"root"`
+ // Hostname configures the container's hostname.
+ Hostname string `json:"hostname,omitempty"`
+ // Mounts configures additional mounts (on top of Root).
+ Mounts []Mount `json:"mounts,omitempty"`
+ // Hooks configures callbacks for container lifecycle events.
+ Hooks *Hooks `json:"hooks,omitempty"`
+ // Annotations contains arbitrary metadata for the container.
+ Annotations map[string]string `json:"annotations,omitempty"`
+
+ // Linux is platform specific configuration for Linux based containers.
+ Linux *Linux `json:"linux,omitempty" platform:"linux"`
+ // Solaris is platform specific configuration for Solaris containers.
+ Solaris *Solaris `json:"solaris,omitempty" platform:"solaris"`
+ // Windows is platform specific configuration for Windows based containers, including Hyper-V containers.
+ Windows *Windows `json:"windows,omitempty" platform:"windows"`
+}
+
+// Process contains information to start a specific application inside the container.
+type Process struct {
+ // Terminal creates an interactive terminal for the container.
+ Terminal bool `json:"terminal,omitempty"`
+ // ConsoleSize specifies the size of the console.
+ ConsoleSize Box `json:"consoleSize,omitempty"`
+ // User specifies user information for the process.
+ User User `json:"user"`
+ // Args specifies the binary and arguments for the application to execute.
+ Args []string `json:"args"`
+ // Env populates the process environment for the process.
+ Env []string `json:"env,omitempty"`
+ // Cwd is the current working directory for the process and must be
+ // relative to the container's root.
+ Cwd string `json:"cwd"`
+ // Capabilities are Linux capabilities that are kept for the process.
+ Capabilities *LinuxCapabilities `json:"capabilities,omitempty" platform:"linux"`
+ // Rlimits specifies rlimit options to apply to the process.
+ Rlimits []LinuxRlimit `json:"rlimits,omitempty" platform:"linux"`
+ // NoNewPrivileges controls whether additional privileges could be gained by processes in the container.
+ NoNewPrivileges bool `json:"noNewPrivileges,omitempty" platform:"linux"`
+ // ApparmorProfile specifies the apparmor profile for the container.
+ ApparmorProfile string `json:"apparmorProfile,omitempty" platform:"linux"`
+ // SelinuxLabel specifies the selinux context that the container process is run as.
+ SelinuxLabel string `json:"selinuxLabel,omitempty" platform:"linux"`
+}
+
+// LinuxCapabilities specifies the whitelist of capabilities that are kept for a process.
+// http://man7.org/linux/man-pages/man7/capabilities.7.html
+type LinuxCapabilities struct {
+ // Bounding is the set of capabilities checked by the kernel.
+ Bounding []string `json:"bounding,omitempty" platform:"linux"`
+ // Effective is the set of capabilities checked by the kernel.
+ Effective []string `json:"effective,omitempty" platform:"linux"`
+ // Inheritable is the capabilities preserved across execve.
+ Inheritable []string `json:"inheritable,omitempty" platform:"linux"`
+ // Permitted is the limiting superset for effective capabilities.
+ Permitted []string `json:"permitted,omitempty" platform:"linux"`
+ // Ambient is the ambient set of capabilities that are kept.
+ Ambient []string `json:"ambient,omitempty" platform:"linux"`
+}
+
+// Box specifies dimensions of a rectangle. Used for specifying the size of a console.
+type Box struct {
+ // Height is the vertical dimension of a box.
+ Height uint `json:"height"`
+ // Width is the horizontal dimension of a box.
+ Width uint `json:"width"`
+}
+
+// User specifies specific user (and group) information for the container process.
+type User struct {
+ // UID is the user id.
+ UID uint32 `json:"uid" platform:"linux,solaris"`
+ // GID is the group id.
+ GID uint32 `json:"gid" platform:"linux,solaris"`
+ // AdditionalGids are additional group ids set for the container's process.
+ AdditionalGids []uint32 `json:"additionalGids,omitempty" platform:"linux,solaris"`
+ // Username is the user name.
+ Username string `json:"username,omitempty" platform:"windows"`
+}
+
+// Root contains information about the container's root filesystem on the host.
+type Root struct {
+ // Path is the absolute path to the container's root filesystem.
+ Path string `json:"path"`
+ // Readonly makes the root filesystem for the container readonly before the process is executed.
+ Readonly bool `json:"readonly,omitempty"`
+}
+
+// Platform specifies OS and arch information for the host system that the container
+// is created for.
+type Platform struct {
+ // OS is the operating system.
+ OS string `json:"os"`
+ // Arch is the architecture
+ Arch string `json:"arch"`
+}
+
+// Mount specifies a mount for a container.
+type Mount struct {
+ // Destination is the path where the mount will be placed relative to the container's root. The path and child directories MUST exist, a runtime MUST NOT create directories automatically to a mount point.
+ Destination string `json:"destination"`
+ // Type specifies the mount kind.
+ Type string `json:"type,omitempty"`
+ // Source specifies the source path of the mount. In the case of bind mounts on
+ // Linux based systems this would be the file on the host.
+ Source string `json:"source,omitempty"`
+ // Options are fstab style mount options.
+ Options []string `json:"options,omitempty"`
+}
+
+// Hook specifies a command that is run at a particular event in the lifecycle of a container
+type Hook struct {
+ Path string `json:"path"`
+ Args []string `json:"args,omitempty"`
+ Env []string `json:"env,omitempty"`
+ Timeout *int `json:"timeout,omitempty"`
+}
+
+// Hooks for container setup and teardown
+type Hooks struct {
+ // Prestart is a list of hooks to be run before the container process is executed.
+ // On Linux, they are run after the container namespaces are created.
+ Prestart []Hook `json:"prestart,omitempty"`
+ // Poststart is a list of hooks to be run after the container process is started.
+ Poststart []Hook `json:"poststart,omitempty"`
+ // Poststop is a list of hooks to be run after the container process exits.
+ Poststop []Hook `json:"poststop,omitempty"`
+}
+
+// Linux contains platform specific configuration for Linux based containers.
+type Linux struct {
+ // UIDMapping specifies user mappings for supporting user namespaces on Linux.
+ UIDMappings []LinuxIDMapping `json:"uidMappings,omitempty"`
+ // GIDMapping specifies group mappings for supporting user namespaces on Linux.
+ GIDMappings []LinuxIDMapping `json:"gidMappings,omitempty"`
+ // Sysctl are a set of key value pairs that are set for the container on start
+ Sysctl map[string]string `json:"sysctl,omitempty"`
+ // Resources contain cgroup information for handling resource constraints
+ // for the container
+ Resources *LinuxResources `json:"resources,omitempty"`
+ // CgroupsPath specifies the path to cgroups that are created and/or joined by the container.
+ // The path is expected to be relative to the cgroups mountpoint.
+ // If resources are specified, the cgroups at CgroupsPath will be updated based on resources.
+ CgroupsPath string `json:"cgroupsPath,omitempty"`
+ // Namespaces contains the namespaces that are created and/or joined by the container
+ Namespaces []LinuxNamespace `json:"namespaces,omitempty"`
+ // Devices are a list of device nodes that are created for the container
+ Devices []LinuxDevice `json:"devices,omitempty"`
+ // Seccomp specifies the seccomp security settings for the container.
+ Seccomp *LinuxSeccomp `json:"seccomp,omitempty"`
+ // RootfsPropagation is the rootfs mount propagation mode for the container.
+ RootfsPropagation string `json:"rootfsPropagation,omitempty"`
+ // MaskedPaths masks over the provided paths inside the container.
+ MaskedPaths []string `json:"maskedPaths,omitempty"`
+ // ReadonlyPaths sets the provided paths as RO inside the container.
+ ReadonlyPaths []string `json:"readonlyPaths,omitempty"`
+ // MountLabel specifies the selinux context for the mounts in the container.
+ MountLabel string `json:"mountLabel,omitempty"`
+ // IntelRdt contains Intel Resource Director Technology (RDT) information
+ // for handling resource constraints (e.g., L3 cache) for the container
+ IntelRdt *LinuxIntelRdt `json:"intelRdt,omitempty"`
+}
+
+// LinuxNamespace is the configuration for a Linux namespace
+type LinuxNamespace struct {
+ // Type is the type of Linux namespace
+ Type LinuxNamespaceType `json:"type"`
+ // Path is a path to an existing namespace persisted on disk that can be joined
+ // and is of the same type
+ Path string `json:"path,omitempty"`
+}
+
+// LinuxNamespaceType is one of the Linux namespaces
+type LinuxNamespaceType string
+
+const (
+ // PIDNamespace for isolating process IDs
+ PIDNamespace LinuxNamespaceType = "pid"
+ // NetworkNamespace for isolating network devices, stacks, ports, etc
+ NetworkNamespace = "network"
+ // MountNamespace for isolating mount points
+ MountNamespace = "mount"
+ // IPCNamespace for isolating System V IPC, POSIX message queues
+ IPCNamespace = "ipc"
+ // UTSNamespace for isolating hostname and NIS domain name
+ UTSNamespace = "uts"
+ // UserNamespace for isolating user and group IDs
+ UserNamespace = "user"
+ // CgroupNamespace for isolating cgroup hierarchies
+ CgroupNamespace = "cgroup"
+)
+
+// LinuxIDMapping specifies UID/GID mappings
+type LinuxIDMapping struct {
+ // HostID is the starting UID/GID on the host to be mapped to 'ContainerID'
+ HostID uint32 `json:"hostID"`
+ // ContainerID is the starting UID/GID in the container
+ ContainerID uint32 `json:"containerID"`
+ // Size is the number of IDs to be mapped
+ Size uint32 `json:"size"`
+}
+
+// LinuxRlimit type and restrictions
+type LinuxRlimit struct {
+ // Type of the rlimit to set
+ Type string `json:"type"`
+ // Hard is the hard limit for the specified type
+ Hard uint64 `json:"hard"`
+ // Soft is the soft limit for the specified type
+ Soft uint64 `json:"soft"`
+}
+
+// LinuxHugepageLimit structure corresponds to limiting kernel hugepages
+type LinuxHugepageLimit struct {
+ // Pagesize is the hugepage size
+ Pagesize string `json:"pageSize"`
+ // Limit is the limit of "hugepagesize" hugetlb usage
+ Limit uint64 `json:"limit"`
+}
+
+// LinuxInterfacePriority for network interfaces
+type LinuxInterfacePriority struct {
+ // Name is the name of the network interface
+ Name string `json:"name"`
+ // Priority for the interface
+ Priority uint32 `json:"priority"`
+}
+
+// linuxBlockIODevice holds major:minor format supported in blkio cgroup
+type linuxBlockIODevice struct {
+ // Major is the device's major number.
+ Major int64 `json:"major"`
+ // Minor is the device's minor number.
+ Minor int64 `json:"minor"`
+}
+
+// LinuxWeightDevice struct holds a `major:minor weight` pair for blkioWeightDevice
+type LinuxWeightDevice struct {
+ linuxBlockIODevice
+ // Weight is the bandwidth rate for the device.
+ Weight *uint16 `json:"weight,omitempty"`
+ // LeafWeight is the bandwidth rate for the device while competing with the cgroup's child cgroups, CFQ scheduler only
+ LeafWeight *uint16 `json:"leafWeight,omitempty"`
+}
+
+// LinuxThrottleDevice struct holds a `major:minor rate_per_second` pair
+type LinuxThrottleDevice struct {
+ linuxBlockIODevice
+ // Rate is the IO rate limit per cgroup per device
+ Rate uint64 `json:"rate"`
+}
+
+// LinuxBlockIO for Linux cgroup 'blkio' resource management
+type LinuxBlockIO struct {
+ // Specifies per cgroup weight
+ Weight *uint16 `json:"blkioWeight,omitempty"`
+ // Specifies tasks' weight in the given cgroup while competing with the cgroup's child cgroups, CFQ scheduler only
+ LeafWeight *uint16 `json:"blkioLeafWeight,omitempty"`
+ // Weight per cgroup per device, can override BlkioWeight
+ WeightDevice []LinuxWeightDevice `json:"blkioWeightDevice,omitempty"`
+ // IO read rate limit per cgroup per device, bytes per second
+ ThrottleReadBpsDevice []LinuxThrottleDevice `json:"blkioThrottleReadBpsDevice,omitempty"`
+ // IO write rate limit per cgroup per device, bytes per second
+ ThrottleWriteBpsDevice []LinuxThrottleDevice `json:"blkioThrottleWriteBpsDevice,omitempty"`
+ // IO read rate limit per cgroup per device, IO per second
+ ThrottleReadIOPSDevice []LinuxThrottleDevice `json:"blkioThrottleReadIOPSDevice,omitempty"`
+ // IO write rate limit per cgroup per device, IO per second
+ ThrottleWriteIOPSDevice []LinuxThrottleDevice `json:"blkioThrottleWriteIOPSDevice,omitempty"`
+}
+
+// LinuxMemory for Linux cgroup 'memory' resource management
+type LinuxMemory struct {
+ // Memory limit (in bytes).
+ Limit *uint64 `json:"limit,omitempty"`
+ // Memory reservation or soft_limit (in bytes).
+ Reservation *uint64 `json:"reservation,omitempty"`
+ // Total memory limit (memory + swap).
+ Swap *uint64 `json:"swap,omitempty"`
+ // Kernel memory limit (in bytes).
+ Kernel *uint64 `json:"kernel,omitempty"`
+ // Kernel memory limit for tcp (in bytes)
+ KernelTCP *uint64 `json:"kernelTCP,omitempty"`
+ // How aggressive the kernel will swap memory pages. Range from 0 to 100.
+ Swappiness *uint64 `json:"swappiness,omitempty"`
+}
+
+// LinuxCPU for Linux cgroup 'cpu' resource management
+type LinuxCPU struct {
+ // CPU shares (relative weight (ratio) vs. other cgroups with cpu shares).
+ Shares *uint64 `json:"shares,omitempty"`
+ // CPU hardcap limit (in usecs). Allowed cpu time in a given period.
+ Quota *int64 `json:"quota,omitempty"`
+ // CPU period to be used for hardcapping (in usecs).
+ Period *uint64 `json:"period,omitempty"`
+ // How much time realtime scheduling may use (in usecs).
+ RealtimeRuntime *int64 `json:"realtimeRuntime,omitempty"`
+ // CPU period to be used for realtime scheduling (in usecs).
+ RealtimePeriod *uint64 `json:"realtimePeriod,omitempty"`
+ // CPUs to use within the cpuset. Default is to use any CPU available.
+ Cpus string `json:"cpus,omitempty"`
+ // List of memory nodes in the cpuset. Default is to use any available memory node.
+ Mems string `json:"mems,omitempty"`
+}
+
+// LinuxPids for Linux cgroup 'pids' resource management (Linux 4.3)
+type LinuxPids struct {
+ // Maximum number of PIDs. Default is "no limit".
+ Limit int64 `json:"limit"`
+}
+
+// LinuxNetwork identification and priority configuration
+type LinuxNetwork struct {
+ // Set class identifier for container's network packets
+ ClassID *uint32 `json:"classID,omitempty"`
+ // Set priority of network traffic for container
+ Priorities []LinuxInterfacePriority `json:"priorities,omitempty"`
+}
+
+// LinuxResources has container runtime resource constraints
+type LinuxResources struct {
+ // Devices configures the device whitelist.
+ Devices []LinuxDeviceCgroup `json:"devices,omitempty"`
+ // DisableOOMKiller disables the OOM killer for out of memory conditions
+ DisableOOMKiller *bool `json:"disableOOMKiller,omitempty"`
+ // Specify an oom_score_adj for the container.
+ OOMScoreAdj *int `json:"oomScoreAdj,omitempty"`
+ // Memory restriction configuration
+ Memory *LinuxMemory `json:"memory,omitempty"`
+ // CPU resource restriction configuration
+ CPU *LinuxCPU `json:"cpu,omitempty"`
+ // Task resource restriction configuration.
+ Pids *LinuxPids `json:"pids,omitempty"`
+ // BlockIO restriction configuration
+ BlockIO *LinuxBlockIO `json:"blockIO,omitempty"`
+ // Hugetlb limit (in bytes)
+ HugepageLimits []LinuxHugepageLimit `json:"hugepageLimits,omitempty"`
+ // Network restriction configuration
+ Network *LinuxNetwork `json:"network,omitempty"`
+}
+
+// LinuxDevice represents the mknod information for a Linux special device file
+type LinuxDevice struct {
+ // Path to the device.
+ Path string `json:"path"`
+ // Device type, block, char, etc.
+ Type string `json:"type"`
+ // Major is the device's major number.
+ Major int64 `json:"major"`
+ // Minor is the device's minor number.
+ Minor int64 `json:"minor"`
+ // FileMode permission bits for the device.
+ FileMode *os.FileMode `json:"fileMode,omitempty"`
+ // UID of the device.
+ UID *uint32 `json:"uid,omitempty"`
+ // Gid of the device.
+ GID *uint32 `json:"gid,omitempty"`
+}
+
+// LinuxDeviceCgroup represents a device rule for the whitelist controller
+type LinuxDeviceCgroup struct {
+ // Allow or deny
+ Allow bool `json:"allow"`
+ // Device type, block, char, etc.
+ Type string `json:"type,omitempty"`
+ // Major is the device's major number.
+ Major *int64 `json:"major,omitempty"`
+ // Minor is the device's minor number.
+ Minor *int64 `json:"minor,omitempty"`
+ // Cgroup access permissions format, rwm.
+ Access string `json:"access,omitempty"`
+}
+
+// Solaris contains platform specific configuration for Solaris application containers.
+type Solaris struct {
+ // SMF FMRI which should go "online" before we start the container process.
+ Milestone string `json:"milestone,omitempty"`
+ // Maximum set of privileges any process in this container can obtain.
+ LimitPriv string `json:"limitpriv,omitempty"`
+ // The maximum amount of shared memory allowed for this container.
+ MaxShmMemory string `json:"maxShmMemory,omitempty"`
+ // Specification for automatic creation of network resources for this container.
+ Anet []SolarisAnet `json:"anet,omitempty"`
+ // Set limit on the amount of CPU time that can be used by container.
+ CappedCPU *SolarisCappedCPU `json:"cappedCPU,omitempty"`
+ // The physical and swap caps on the memory that can be used by this container.
+ CappedMemory *SolarisCappedMemory `json:"cappedMemory,omitempty"`
+}
+
+// SolarisCappedCPU allows users to set limit on the amount of CPU time that can be used by container.
+type SolarisCappedCPU struct {
+ Ncpus string `json:"ncpus,omitempty"`
+}
+
+// SolarisCappedMemory allows users to set the physical and swap caps on the memory that can be used by this container.
+type SolarisCappedMemory struct {
+ Physical string `json:"physical,omitempty"`
+ Swap string `json:"swap,omitempty"`
+}
+
+// SolarisAnet provides the specification for automatic creation of network resources for this container.
+type SolarisAnet struct {
+ // Specify a name for the automatically created VNIC datalink.
+ Linkname string `json:"linkname,omitempty"`
+ // Specify the link over which the VNIC will be created.
+ Lowerlink string `json:"lowerLink,omitempty"`
+ // The set of IP addresses that the container can use.
+ Allowedaddr string `json:"allowedAddress,omitempty"`
+ // Specifies whether allowedAddress limitation is to be applied to the VNIC.
+ Configallowedaddr string `json:"configureAllowedAddress,omitempty"`
+ // The value of the optional default router.
+ Defrouter string `json:"defrouter,omitempty"`
+ // Enable one or more types of link protection.
+ Linkprotection string `json:"linkProtection,omitempty"`
+ // Set the VNIC's macAddress
+ Macaddress string `json:"macAddress,omitempty"`
+}
+
+// Windows defines the runtime configuration for Windows based containers, including Hyper-V containers.
+type Windows struct {
+ // Resources contains information for handling resource constraints for the container.
+ Resources *WindowsResources `json:"resources,omitempty"`
+}
+
+// WindowsResources has container runtime resource constraints for containers running on Windows.
+type WindowsResources struct {
+ // Memory restriction configuration.
+ Memory *WindowsMemoryResources `json:"memory,omitempty"`
+ // CPU resource restriction configuration.
+ CPU *WindowsCPUResources `json:"cpu,omitempty"`
+ // Storage restriction configuration.
+ Storage *WindowsStorageResources `json:"storage,omitempty"`
+ // Network restriction configuration.
+ Network *WindowsNetworkResources `json:"network,omitempty"`
+}
+
+// WindowsMemoryResources contains memory resource management settings.
+type WindowsMemoryResources struct {
+ // Memory limit in bytes.
+ Limit *uint64 `json:"limit,omitempty"`
+ // Memory reservation in bytes.
+ Reservation *uint64 `json:"reservation,omitempty"`
+}
+
+// WindowsCPUResources contains CPU resource management settings.
+type WindowsCPUResources struct {
+ // Number of CPUs available to the container.
+ Count *uint64 `json:"count,omitempty"`
+ // CPU shares (relative weight to other containers with cpu shares). Range is from 1 to 10000.
+ Shares *uint16 `json:"shares,omitempty"`
+ // Specifies the portion of processor cycles that this container can use as a percentage times 100.
+ Maximum *uint16 `json:"maximum,omitempty"`
+}
+
+// WindowsStorageResources contains storage resource management settings.
+type WindowsStorageResources struct {
+ // Specifies maximum Iops for the system drive.
+ Iops *uint64 `json:"iops,omitempty"`
+ // Specifies maximum bytes per second for the system drive.
+ Bps *uint64 `json:"bps,omitempty"`
+ // Sandbox size specifies the minimum size of the system drive in bytes.
+ SandboxSize *uint64 `json:"sandboxSize,omitempty"`
+}
+
+// WindowsNetworkResources contains network resource management settings.
+type WindowsNetworkResources struct {
+ // EgressBandwidth is the maximum egress bandwidth in bytes per second.
+ EgressBandwidth *uint64 `json:"egressBandwidth,omitempty"`
+}
+
+// LinuxSeccomp represents syscall restrictions
+type LinuxSeccomp struct {
+ DefaultAction LinuxSeccompAction `json:"defaultAction"`
+ Architectures []Arch `json:"architectures,omitempty"`
+ Syscalls []LinuxSyscall `json:"syscalls,omitempty"`
+}
+
+// Arch used for additional architectures
+type Arch string
+
+// Additional architectures permitted to be used for system calls
+// By default only the native architecture of the kernel is permitted
+const (
+ ArchX86 Arch = "SCMP_ARCH_X86"
+ ArchX86_64 Arch = "SCMP_ARCH_X86_64"
+ ArchX32 Arch = "SCMP_ARCH_X32"
+ ArchARM Arch = "SCMP_ARCH_ARM"
+ ArchAARCH64 Arch = "SCMP_ARCH_AARCH64"
+ ArchMIPS Arch = "SCMP_ARCH_MIPS"
+ ArchMIPS64 Arch = "SCMP_ARCH_MIPS64"
+ ArchMIPS64N32 Arch = "SCMP_ARCH_MIPS64N32"
+ ArchMIPSEL Arch = "SCMP_ARCH_MIPSEL"
+ ArchMIPSEL64 Arch = "SCMP_ARCH_MIPSEL64"
+ ArchMIPSEL64N32 Arch = "SCMP_ARCH_MIPSEL64N32"
+ ArchPPC Arch = "SCMP_ARCH_PPC"
+ ArchPPC64 Arch = "SCMP_ARCH_PPC64"
+ ArchPPC64LE Arch = "SCMP_ARCH_PPC64LE"
+ ArchS390 Arch = "SCMP_ARCH_S390"
+ ArchS390X Arch = "SCMP_ARCH_S390X"
+ ArchPARISC Arch = "SCMP_ARCH_PARISC"
+ ArchPARISC64 Arch = "SCMP_ARCH_PARISC64"
+)
+
+// LinuxSeccompAction taken upon Seccomp rule match
+type LinuxSeccompAction string
+
+// Define actions for Seccomp rules
+const (
+ ActKill LinuxSeccompAction = "SCMP_ACT_KILL"
+ ActTrap LinuxSeccompAction = "SCMP_ACT_TRAP"
+ ActErrno LinuxSeccompAction = "SCMP_ACT_ERRNO"
+ ActTrace LinuxSeccompAction = "SCMP_ACT_TRACE"
+ ActAllow LinuxSeccompAction = "SCMP_ACT_ALLOW"
+)
+
+// LinuxSeccompOperator used to match syscall arguments in Seccomp
+type LinuxSeccompOperator string
+
+// Define operators for syscall arguments in Seccomp
+const (
+ OpNotEqual LinuxSeccompOperator = "SCMP_CMP_NE"
+ OpLessThan LinuxSeccompOperator = "SCMP_CMP_LT"
+ OpLessEqual LinuxSeccompOperator = "SCMP_CMP_LE"
+ OpEqualTo LinuxSeccompOperator = "SCMP_CMP_EQ"
+ OpGreaterEqual LinuxSeccompOperator = "SCMP_CMP_GE"
+ OpGreaterThan LinuxSeccompOperator = "SCMP_CMP_GT"
+ OpMaskedEqual LinuxSeccompOperator = "SCMP_CMP_MASKED_EQ"
+)
+
+// LinuxSeccompArg used for matching specific syscall arguments in Seccomp
+type LinuxSeccompArg struct {
+ Index uint `json:"index"`
+ Value uint64 `json:"value"`
+ ValueTwo uint64 `json:"valueTwo"`
+ Op LinuxSeccompOperator `json:"op"`
+}
+
+// LinuxSyscall is used to match a syscall in Seccomp
+type LinuxSyscall struct {
+ Names []string `json:"names"`
+ Action LinuxSeccompAction `json:"action"`
+ Args []LinuxSeccompArg `json:"args,omitempty"`
+}
+
+// LinuxIntelRdt has container runtime resource constraints
+// for Intel RDT/CAT which introduced in Linux 4.10 kernel
+type LinuxIntelRdt struct {
+ // The schema for L3 cache id and capacity bitmask (CBM)
+ // Format: "L3:<cache_id0>=<cbm0>;<cache_id1>=<cbm1>;..."
+ L3CacheSchema string `json:"l3CacheSchema,omitempty"`
+}
diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go
new file mode 100644
index 0000000..b5dd3be
--- /dev/null
+++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go
@@ -0,0 +1,17 @@
+package specs
+
+// State holds information about the runtime state of the container.
+type State struct {
+ // Version is the version of the specification that is supported.
+ Version string `json:"ociVersion"`
+ // ID is the container ID
+ ID string `json:"id"`
+ // Status is the runtime status of the container.
+ Status string `json:"status"`
+ // Pid is the process ID for the container process.
+ Pid int `json:"pid"`
+ // Bundle is the path to the container's bundle directory.
+ Bundle string `json:"bundle"`
+ // Annotations are key values associated with the container.
+ Annotations map[string]string `json:"annotations,omitempty"`
+}
diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go
new file mode 100644
index 0000000..dfcf009
--- /dev/null
+++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go
@@ -0,0 +1,18 @@
+package specs
+
+import "fmt"
+
+const (
+ // VersionMajor is for an API incompatible changes
+ VersionMajor = 1
+ // VersionMinor is for functionality in a backwards-compatible manner
+ VersionMinor = 0
+ // VersionPatch is for backwards-compatible bug fixes
+ VersionPatch = 0
+
+ // VersionDev indicates development branch. Releases will be empty string.
+ VersionDev = "-rc5-dev"
+)
+
+// Version is the specification version that the package types support.
+var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev)
diff --git a/vendor/github.com/opencontainers/selinux/LICENSE b/vendor/github.com/opencontainers/selinux/LICENSE
new file mode 100644
index 0000000..8dada3e
--- /dev/null
+++ b/vendor/github.com/opencontainers/selinux/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/opencontainers/selinux/README.md b/vendor/github.com/opencontainers/selinux/README.md
new file mode 100644
index 0000000..043a929
--- /dev/null
+++ b/vendor/github.com/opencontainers/selinux/README.md
@@ -0,0 +1,7 @@
+# selinux
+
+[![GoDoc](https://godoc.org/github.com/opencontainers/selinux?status.svg)](https://godoc.org/github.com/opencontainers/selinux) [![Go Report Card](https://goreportcard.com/badge/github.com/opencontainers/selinux)](https://goreportcard.com/report/github.com/opencontainers/selinux) [![Build Status](https://travis-ci.org/opencontainers/selinux.svg?branch=master)](https://travis-ci.org/opencontainers/selinux)
+
+Common SELinux package used across the container ecosystem.
+
+Please see the [godoc](https://godoc.org/github.com/opencontainers/selinux) for more information.
diff --git a/vendor/github.com/opencontainers/selinux/go-selinux/label/label.go b/vendor/github.com/opencontainers/selinux/go-selinux/label/label.go
new file mode 100644
index 0000000..6cfc5fd
--- /dev/null
+++ b/vendor/github.com/opencontainers/selinux/go-selinux/label/label.go
@@ -0,0 +1,84 @@
+// +build !selinux !linux
+
+package label
+
+// InitLabels returns the process label and file labels to be used within
+// the container. A list of options can be passed into this function to alter
+// the labels.
+func InitLabels(options []string) (string, string, error) {
+ return "", "", nil
+}
+
+func GetROMountLabel() string {
+ return ""
+}
+
+func GenLabels(options string) (string, string, error) {
+ return "", "", nil
+}
+
+func FormatMountLabel(src string, mountLabel string) string {
+ return src
+}
+
+func SetProcessLabel(processLabel string) error {
+ return nil
+}
+
+func GetFileLabel(path string) (string, error) {
+ return "", nil
+}
+
+func SetFileLabel(path string, fileLabel string) error {
+ return nil
+}
+
+func SetFileCreateLabel(fileLabel string) error {
+ return nil
+}
+
+func Relabel(path string, fileLabel string, shared bool) error {
+ return nil
+}
+
+func GetPidLabel(pid int) (string, error) {
+ return "", nil
+}
+
+func Init() {
+}
+
+func ReserveLabel(label string) error {
+ return nil
+}
+
+func ReleaseLabel(label string) error {
+ return nil
+}
+
+// DupSecOpt takes a process label and returns security options that
+// can be used to set duplicate labels on future container processes
+func DupSecOpt(src string) []string {
+ return nil
+}
+
+// DisableSecOpt returns a security opt that can disable labeling
+// support for future container processes
+func DisableSecOpt() []string {
+ return nil
+}
+
+// Validate checks that the label does not include unexpected options
+func Validate(label string) error {
+ return nil
+}
+
+// RelabelNeeded checks whether the user requested a relabel
+func RelabelNeeded(label string) bool {
+ return false
+}
+
+// IsShared checks that the label includes a "shared" mark
+func IsShared(label string) bool {
+ return false
+}
diff --git a/vendor/github.com/opencontainers/selinux/go-selinux/label/label_selinux.go b/vendor/github.com/opencontainers/selinux/go-selinux/label/label_selinux.go
new file mode 100644
index 0000000..569dcf0
--- /dev/null
+++ b/vendor/github.com/opencontainers/selinux/go-selinux/label/label_selinux.go
@@ -0,0 +1,204 @@
+// +build selinux,linux
+
+package label
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/opencontainers/selinux/go-selinux"
+)
+
+// Valid Label Options
+var validOptions = map[string]bool{
+ "disable": true,
+ "type": true,
+ "user": true,
+ "role": true,
+ "level": true,
+}
+
+var ErrIncompatibleLabel = fmt.Errorf("Bad SELinux option z and Z can not be used together")
+
+// InitLabels returns the process label and file labels to be used within
+// the container. A list of options can be passed into this function to alter
+// the labels. The labels returned will include a random MCS String, that is
+// guaranteed to be unique.
+func InitLabels(options []string) (string, string, error) {
+ if !selinux.GetEnabled() {
+ return "", "", nil
+ }
+ processLabel, mountLabel := selinux.ContainerLabels()
+ if processLabel != "" {
+ pcon := selinux.NewContext(processLabel)
+ mcon := selinux.NewContext(mountLabel)
+ for _, opt := range options {
+ if opt == "disable" {
+ return "", "", nil
+ }
+ if i := strings.Index(opt, ":"); i == -1 {
+ return "", "", fmt.Errorf("Bad label option %q, valid options 'disable' or \n'user, role, level, type' followed by ':' and a value", opt)
+ }
+ con := strings.SplitN(opt, ":", 2)
+ if !validOptions[con[0]] {
+ return "", "", fmt.Errorf("Bad label option %q, valid options 'disable, user, role, level, type'", con[0])
+
+ }
+ pcon[con[0]] = con[1]
+ if con[0] == "level" || con[0] == "user" {
+ mcon[con[0]] = con[1]
+ }
+ }
+ processLabel = pcon.Get()
+ mountLabel = mcon.Get()
+ }
+ return processLabel, mountLabel, nil
+}
+
+func ROMountLabel() string {
+ return selinux.ROFileLabel()
+}
+
+// DEPRECATED: The GenLabels function is only to be used during the transition to the official API.
+func GenLabels(options string) (string, string, error) {
+ return InitLabels(strings.Fields(options))
+}
+
+// FormatMountLabel returns a string to be used by the mount command.
+// The format of this string will be used to alter the labeling of the mountpoint.
+// The string returned is suitable to be used as the options field of the mount command.
+// If you need to have additional mount point options, you can pass them in as
+// the first parameter. Second parameter is the label that you wish to apply
+// to all content in the mount point.
+func FormatMountLabel(src, mountLabel string) string {
+ if mountLabel != "" {
+ switch src {
+ case "":
+ src = fmt.Sprintf("context=%q", mountLabel)
+ default:
+ src = fmt.Sprintf("%s,context=%q", src, mountLabel)
+ }
+ }
+ return src
+}
+
+// SetProcessLabel takes a process label and tells the kernel to assign the
+// label to the next program executed by the current process.
+func SetProcessLabel(processLabel string) error {
+ if processLabel == "" {
+ return nil
+ }
+ return selinux.SetExecLabel(processLabel)
+}
+
+// ProcessLabel returns the process label that the kernel will assign
+// to the next program executed by the current process. If "" is returned
+// this indicates that the default labeling will happen for the process.
+func ProcessLabel() (string, error) {
+ return selinux.ExecLabel()
+}
+
+// GetFileLabel returns the label for specified path
+func FileLabel(path string) (string, error) {
+ return selinux.FileLabel(path)
+}
+
+// SetFileLabel modifies the "path" label to the specified file label
+func SetFileLabel(path string, fileLabel string) error {
+ if selinux.GetEnabled() && fileLabel != "" {
+ return selinux.SetFileLabel(path, fileLabel)
+ }
+ return nil
+}
+
+// SetFileCreateLabel tells the kernel the label for all files to be created
+func SetFileCreateLabel(fileLabel string) error {
+ if selinux.GetEnabled() {
+ return selinux.SetFSCreateLabel(fileLabel)
+ }
+ return nil
+}
+
+// Relabel changes the label of path to the filelabel string.
+// It changes the MCS label to s0 if shared is true.
+// This will allow all containers to share the content.
+func Relabel(path string, fileLabel string, shared bool) error {
+ if !selinux.GetEnabled() {
+ return nil
+ }
+
+ if fileLabel == "" {
+ return nil
+ }
+
+ exclude_paths := map[string]bool{"/": true, "/usr": true, "/etc": true}
+ if exclude_paths[path] {
+ return fmt.Errorf("SELinux relabeling of %s is not allowed", path)
+ }
+
+ if shared {
+ c := selinux.NewContext(fileLabel)
+ c["level"] = "s0"
+ fileLabel = c.Get()
+ }
+ if err := selinux.Chcon(path, fileLabel, true); err != nil {
+ return err
+ }
+ return nil
+}
+
+// PidLabel will return the label of the process running with the specified pid
+func PidLabel(pid int) (string, error) {
+ return selinux.PidLabel(pid)
+}
+
+// Init initialises the labeling system
+func Init() {
+ selinux.GetEnabled()
+}
+
+// ReserveLabel will record the fact that the MCS label has already been used.
+// This will prevent InitLabels from using the MCS label in a newly created
+// container
+func ReserveLabel(label string) error {
+ selinux.ReserveLabel(label)
+ return nil
+}
+
+// ReleaseLabel will remove the reservation of the MCS label.
+// This will allow InitLabels to use the MCS label in a newly created
+// containers
+func ReleaseLabel(label string) error {
+ selinux.ReleaseLabel(label)
+ return nil
+}
+
+// DupSecOpt takes a process label and returns security options that
+// can be used to set duplicate labels on future container processes
+func DupSecOpt(src string) []string {
+ return selinux.DupSecOpt(src)
+}
+
+// DisableSecOpt returns a security opt that can disable labeling
+// support for future container processes
+func DisableSecOpt() []string {
+ return selinux.DisableSecOpt()
+}
+
+// Validate checks that the label does not include unexpected options
+func Validate(label string) error {
+ if strings.Contains(label, "z") && strings.Contains(label, "Z") {
+ return ErrIncompatibleLabel
+ }
+ return nil
+}
+
+// RelabelNeeded checks whether the user requested a relabel
+func RelabelNeeded(label string) bool {
+ return strings.Contains(label, "z") || strings.Contains(label, "Z")
+}
+
+// IsShared checks that the label includes a "shared" mark
+func IsShared(label string) bool {
+ return strings.Contains(label, "z")
+}
diff --git a/vendor/github.com/opencontainers/selinux/go-selinux/selinux.go b/vendor/github.com/opencontainers/selinux/go-selinux/selinux.go
new file mode 100644
index 0000000..4cf2c45
--- /dev/null
+++ b/vendor/github.com/opencontainers/selinux/go-selinux/selinux.go
@@ -0,0 +1,593 @@
+// +build linux
+
+package selinux
+
+import (
+ "bufio"
+ "crypto/rand"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+)
+
+const (
+ // Enforcing constant indicate SELinux is in enforcing mode
+ Enforcing = 1
+ // Permissive constant to indicate SELinux is in permissive mode
+ Permissive = 0
+ // Disabled constant to indicate SELinux is disabled
+ Disabled = -1
+ selinuxDir = "/etc/selinux/"
+ selinuxConfig = selinuxDir + "config"
+ selinuxTypeTag = "SELINUXTYPE"
+ selinuxTag = "SELINUX"
+ selinuxPath = "/sys/fs/selinux"
+ xattrNameSelinux = "security.selinux"
+ stRdOnly = 0x01
+)
+
+type selinuxState struct {
+ enabledSet bool
+ enabled bool
+ selinuxfsSet bool
+ selinuxfs string
+ mcsList map[string]bool
+ sync.Mutex
+}
+
+var (
+ assignRegex = regexp.MustCompile(`^([^=]+)=(.*)$`)
+ state = selinuxState{
+ mcsList: make(map[string]bool),
+ }
+)
+
+// Context is a representation of the SELinux label broken into 4 parts
+type Context map[string]string
+
+func (s *selinuxState) setEnable(enabled bool) bool {
+ s.Lock()
+ defer s.Unlock()
+ s.enabledSet = true
+ s.enabled = enabled
+ return s.enabled
+}
+
+func (s *selinuxState) getEnabled() bool {
+ s.Lock()
+ enabled := s.enabled
+ enabledSet := s.enabledSet
+ s.Unlock()
+ if enabledSet {
+ return enabled
+ }
+
+ enabled = false
+ if fs := getSelinuxMountPoint(); fs != "" {
+ if con, _ := CurrentLabel(); con != "kernel" {
+ enabled = true
+ }
+ }
+ return s.setEnable(enabled)
+}
+
+// SetDisabled disables selinux support for the package
+func SetDisabled() {
+ state.setEnable(false)
+}
+
+func (s *selinuxState) setSELinuxfs(selinuxfs string) string {
+ s.Lock()
+ defer s.Unlock()
+ s.selinuxfsSet = true
+ s.selinuxfs = selinuxfs
+ return s.selinuxfs
+}
+
+func (s *selinuxState) getSELinuxfs() string {
+ s.Lock()
+ selinuxfs := s.selinuxfs
+ selinuxfsSet := s.selinuxfsSet
+ s.Unlock()
+ if selinuxfsSet {
+ return selinuxfs
+ }
+
+ selinuxfs = ""
+ f, err := os.Open("/proc/self/mountinfo")
+ if err != nil {
+ return selinuxfs
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ txt := scanner.Text()
+ // Safe as mountinfo encodes mountpoints with spaces as \040.
+ sepIdx := strings.Index(txt, " - ")
+ if sepIdx == -1 {
+ continue
+ }
+ if !strings.Contains(txt[sepIdx:], "selinuxfs") {
+ continue
+ }
+ fields := strings.Split(txt, " ")
+ if len(fields) < 5 {
+ continue
+ }
+ selinuxfs = fields[4]
+ break
+ }
+
+ if selinuxfs != "" {
+ var buf syscall.Statfs_t
+ syscall.Statfs(selinuxfs, &buf)
+ if (buf.Flags & stRdOnly) == 1 {
+ selinuxfs = ""
+ }
+ }
+ return s.setSELinuxfs(selinuxfs)
+}
+
+// getSelinuxMountPoint returns the path to the mountpoint of an selinuxfs
+// filesystem or an empty string if no mountpoint is found. Selinuxfs is
+// a proc-like pseudo-filesystem that exposes the selinux policy API to
+// processes. The existence of an selinuxfs mount is used to determine
+// whether selinux is currently enabled or not.
+func getSelinuxMountPoint() string {
+ return state.getSELinuxfs()
+}
+
+// GetEnabled returns whether selinux is currently enabled.
+func GetEnabled() bool {
+ return state.getEnabled()
+}
+
+func readConfig(target string) (value string) {
+ var (
+ val, key string
+ bufin *bufio.Reader
+ )
+
+ in, err := os.Open(selinuxConfig)
+ if err != nil {
+ return ""
+ }
+ defer in.Close()
+
+ bufin = bufio.NewReader(in)
+
+ for done := false; !done; {
+ var line string
+ if line, err = bufin.ReadString('\n'); err != nil {
+ if err != io.EOF {
+ return ""
+ }
+ done = true
+ }
+ line = strings.TrimSpace(line)
+ if len(line) == 0 {
+ // Skip blank lines
+ continue
+ }
+ if line[0] == ';' || line[0] == '#' {
+ // Skip comments
+ continue
+ }
+ if groups := assignRegex.FindStringSubmatch(line); groups != nil {
+ key, val = strings.TrimSpace(groups[1]), strings.TrimSpace(groups[2])
+ if key == target {
+ return strings.Trim(val, "\"")
+ }
+ }
+ }
+ return ""
+}
+
+func getSELinuxPolicyRoot() string {
+ return selinuxDir + readConfig(selinuxTypeTag)
+}
+
+func readCon(name string) (string, error) {
+ var val string
+
+ in, err := os.Open(name)
+ if err != nil {
+ return "", err
+ }
+ defer in.Close()
+
+ _, err = fmt.Fscanf(in, "%s", &val)
+ return val, err
+}
+
+// SetFileLabel sets the SELinux label for this path or returns an error.
+func SetFileLabel(path string, label string) error {
+ return lsetxattr(path, xattrNameSelinux, []byte(label), 0)
+}
+
+// Filecon returns the SELinux label for this path or returns an error.
+func FileLabel(path string) (string, error) {
+ label, err := lgetxattr(path, xattrNameSelinux)
+ if err != nil {
+ return "", err
+ }
+ // Trim the NUL byte at the end of the byte buffer, if present.
+ if len(label) > 0 && label[len(label)-1] == '\x00' {
+ label = label[:len(label)-1]
+ }
+ return string(label), nil
+}
+
+/*
+SetFSCreateLabel tells kernel the label to create all file system objects
+created by this task. Setting label="" to return to default.
+*/
+func SetFSCreateLabel(label string) error {
+ return writeCon(fmt.Sprintf("/proc/self/task/%d/attr/fscreate", syscall.Gettid()), label)
+}
+
+/*
+FSCreateLabel returns the default label the kernel which the kernel is using
+for file system objects created by this task. "" indicates default.
+*/
+func FSCreateLabel() (string, error) {
+ return readCon(fmt.Sprintf("/proc/self/task/%d/attr/fscreate", syscall.Gettid()))
+}
+
+// CurrentLabel returns the SELinux label of the current process thread, or an error.
+func CurrentLabel() (string, error) {
+ return readCon(fmt.Sprintf("/proc/self/task/%d/attr/current", syscall.Gettid()))
+}
+
+// PidLabel returns the SELinux label of the given pid, or an error.
+func PidLabel(pid int) (string, error) {
+ return readCon(fmt.Sprintf("/proc/%d/attr/current", pid))
+}
+
+/*
+ExecLabel returns the SELinux label that the kernel will use for any programs
+that are executed by the current process thread, or an error.
+*/
+func ExecLabel() (string, error) {
+ return readCon(fmt.Sprintf("/proc/self/task/%d/attr/exec", syscall.Gettid()))
+}
+
+func writeCon(name string, val string) error {
+ out, err := os.OpenFile(name, os.O_WRONLY, 0)
+ if err != nil {
+ return err
+ }
+ defer out.Close()
+
+ if val != "" {
+ _, err = out.Write([]byte(val))
+ } else {
+ _, err = out.Write(nil)
+ }
+ return err
+}
+
+/*
+SetExecLabel sets the SELinux label that the kernel will use for any programs
+that are executed by the current process thread, or an error.
+*/
+func SetExecLabel(label string) error {
+ return writeCon(fmt.Sprintf("/proc/self/task/%d/attr/exec", syscall.Gettid()), label)
+}
+
+// Get returns the Context as a string
+func (c Context) Get() string {
+ return fmt.Sprintf("%s:%s:%s:%s", c["user"], c["role"], c["type"], c["level"])
+}
+
+// NewContext creates a new Context struct from the specified label
+func NewContext(label string) Context {
+ c := make(Context)
+
+ if len(label) != 0 {
+ con := strings.SplitN(label, ":", 4)
+ c["user"] = con[0]
+ c["role"] = con[1]
+ c["type"] = con[2]
+ c["level"] = con[3]
+ }
+ return c
+}
+
+// ReserveLabel reserves the MLS/MCS level component of the specified label
+func ReserveLabel(label string) {
+ if len(label) != 0 {
+ con := strings.SplitN(label, ":", 4)
+ mcsAdd(con[3])
+ }
+}
+
+func selinuxEnforcePath() string {
+ return fmt.Sprintf("%s/enforce", selinuxPath)
+}
+
+// EnforceMode returns the current SELinux mode Enforcing, Permissive, Disabled
+func EnforceMode() int {
+ var enforce int
+
+ enforceS, err := readCon(selinuxEnforcePath())
+ if err != nil {
+ return -1
+ }
+
+ enforce, err = strconv.Atoi(string(enforceS))
+ if err != nil {
+ return -1
+ }
+ return enforce
+}
+
+/*
+SetEnforce sets the current SELinux mode Enforcing, Permissive.
+Disabled is not valid, since this needs to be set at boot time.
+*/
+func SetEnforceMode(mode int) error {
+ return writeCon(selinuxEnforcePath(), fmt.Sprintf("%d", mode))
+}
+
+/*
+DefaultEnforceMode returns the systems default SELinux mode Enforcing,
+Permissive or Disabled. Note this is is just the default at boot time.
+EnforceMode tells you the systems current mode.
+*/
+func DefaultEnforceMode() int {
+ switch readConfig(selinuxTag) {
+ case "enforcing":
+ return Enforcing
+ case "permissive":
+ return Permissive
+ }
+ return Disabled
+}
+
+func mcsAdd(mcs string) error {
+ state.Lock()
+ defer state.Unlock()
+ if state.mcsList[mcs] {
+ return fmt.Errorf("MCS Label already exists")
+ }
+ state.mcsList[mcs] = true
+ return nil
+}
+
+func mcsDelete(mcs string) {
+ state.Lock()
+ defer state.Unlock()
+ state.mcsList[mcs] = false
+}
+
+func intToMcs(id int, catRange uint32) string {
+ var (
+ SETSIZE = int(catRange)
+ TIER = SETSIZE
+ ORD = id
+ )
+
+ if id < 1 || id > 523776 {
+ return ""
+ }
+
+ for ORD > TIER {
+ ORD = ORD - TIER
+ TIER--
+ }
+ TIER = SETSIZE - TIER
+ ORD = ORD + TIER
+ return fmt.Sprintf("s0:c%d,c%d", TIER, ORD)
+}
+
+func uniqMcs(catRange uint32) string {
+ var (
+ n uint32
+ c1, c2 uint32
+ mcs string
+ )
+
+ for {
+ binary.Read(rand.Reader, binary.LittleEndian, &n)
+ c1 = n % catRange
+ binary.Read(rand.Reader, binary.LittleEndian, &n)
+ c2 = n % catRange
+ if c1 == c2 {
+ continue
+ } else {
+ if c1 > c2 {
+ c1, c2 = c2, c1
+ }
+ }
+ mcs = fmt.Sprintf("s0:c%d,c%d", c1, c2)
+ if err := mcsAdd(mcs); err != nil {
+ continue
+ }
+ break
+ }
+ return mcs
+}
+
+/*
+ReleaseLabel will unreserve the MLS/MCS Level field of the specified label.
+Allowing it to be used by another process.
+*/
+func ReleaseLabel(label string) {
+ if len(label) != 0 {
+ con := strings.SplitN(label, ":", 4)
+ mcsDelete(con[3])
+ }
+}
+
+var roFileLabel string
+
+// ROFileLabel returns the specified SELinux readonly file label
+func ROFileLabel() (fileLabel string) {
+ return roFileLabel
+}
+
+/*
+ContainerLabels returns an allocated processLabel and fileLabel to be used for
+container labeling by the calling process.
+*/
+func ContainerLabels() (processLabel string, fileLabel string) {
+ var (
+ val, key string
+ bufin *bufio.Reader
+ )
+
+ if !GetEnabled() {
+ return "", ""
+ }
+ lxcPath := fmt.Sprintf("%s/contexts/lxc_contexts", getSELinuxPolicyRoot())
+ in, err := os.Open(lxcPath)
+ if err != nil {
+ return "", ""
+ }
+ defer in.Close()
+
+ bufin = bufio.NewReader(in)
+
+ for done := false; !done; {
+ var line string
+ if line, err = bufin.ReadString('\n'); err != nil {
+ if err == io.EOF {
+ done = true
+ } else {
+ goto exit
+ }
+ }
+ line = strings.TrimSpace(line)
+ if len(line) == 0 {
+ // Skip blank lines
+ continue
+ }
+ if line[0] == ';' || line[0] == '#' {
+ // Skip comments
+ continue
+ }
+ if groups := assignRegex.FindStringSubmatch(line); groups != nil {
+ key, val = strings.TrimSpace(groups[1]), strings.TrimSpace(groups[2])
+ if key == "process" {
+ processLabel = strings.Trim(val, "\"")
+ }
+ if key == "file" {
+ fileLabel = strings.Trim(val, "\"")
+ }
+ if key == "ro_file" {
+ roFileLabel = strings.Trim(val, "\"")
+ }
+ }
+ }
+
+ if processLabel == "" || fileLabel == "" {
+ return "", ""
+ }
+
+ if roFileLabel == "" {
+ roFileLabel = fileLabel
+ }
+exit:
+ mcs := uniqMcs(1024)
+ scon := NewContext(processLabel)
+ scon["level"] = mcs
+ processLabel = scon.Get()
+ scon = NewContext(fileLabel)
+ scon["level"] = mcs
+ fileLabel = scon.Get()
+ return processLabel, fileLabel
+}
+
+// SecurityCheckContext validates that the SELinux label is understood by the kernel
+func SecurityCheckContext(val string) error {
+ return writeCon(fmt.Sprintf("%s.context", selinuxPath), val)
+}
+
+/*
+CopyLevel returns a label with the MLS/MCS level from src label replaces on
+the dest label.
+*/
+func CopyLevel(src, dest string) (string, error) {
+ if src == "" {
+ return "", nil
+ }
+ if err := SecurityCheckContext(src); err != nil {
+ return "", err
+ }
+ if err := SecurityCheckContext(dest); err != nil {
+ return "", err
+ }
+ scon := NewContext(src)
+ tcon := NewContext(dest)
+ mcsDelete(tcon["level"])
+ mcsAdd(scon["level"])
+ tcon["level"] = scon["level"]
+ return tcon.Get(), nil
+}
+
+// Prevent users from relabing system files
+func badPrefix(fpath string) error {
+ var badprefixes = []string{"/usr"}
+
+ for _, prefix := range badprefixes {
+ if fpath == prefix || strings.HasPrefix(fpath, fmt.Sprintf("%s/", prefix)) {
+ return fmt.Errorf("relabeling content in %s is not allowed", prefix)
+ }
+ }
+ return nil
+}
+
+// Chcon changes the fpath file object to the SELinux label label.
+// If the fpath is a directory and recurse is true Chcon will walk the
+// directory tree setting the label
+func Chcon(fpath string, label string, recurse bool) error {
+ if label == "" {
+ return nil
+ }
+ if err := badPrefix(fpath); err != nil {
+ return err
+ }
+ callback := func(p string, info os.FileInfo, err error) error {
+ return SetFileLabel(p, label)
+ }
+
+ if recurse {
+ return filepath.Walk(fpath, callback)
+ }
+
+ return SetFileLabel(fpath, label)
+}
+
+// DupSecOpt takes an SELinux process label and returns security options that
+// can will set the SELinux Type and Level for future container processes
+func DupSecOpt(src string) []string {
+ if src == "" {
+ return nil
+ }
+ con := NewContext(src)
+ if con["user"] == "" ||
+ con["role"] == "" ||
+ con["type"] == "" ||
+ con["level"] == "" {
+ return nil
+ }
+ return []string{"user:" + con["user"],
+ "role:" + con["role"],
+ "type:" + con["type"],
+ "level:" + con["level"]}
+}
+
+// DisableSecOpt returns a security opt that can be used to disabling SELinux
+// labeling support for future container processes
+func DisableSecOpt() []string {
+ return []string{"disable"}
+}
diff --git a/vendor/github.com/opencontainers/selinux/go-selinux/xattrs.go b/vendor/github.com/opencontainers/selinux/go-selinux/xattrs.go
new file mode 100644
index 0000000..7f2ef85
--- /dev/null
+++ b/vendor/github.com/opencontainers/selinux/go-selinux/xattrs.go
@@ -0,0 +1,78 @@
+// +build linux
+
+package selinux
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _zero uintptr
+
+// Returns a []byte slice if the xattr is set and nil otherwise
+// Requires path and its attribute as arguments
+func lgetxattr(path string, attr string) ([]byte, error) {
+ var sz int
+ pathBytes, err := syscall.BytePtrFromString(path)
+ if err != nil {
+ return nil, err
+ }
+ attrBytes, err := syscall.BytePtrFromString(attr)
+ if err != nil {
+ return nil, err
+ }
+
+ // Start with a 128 length byte array
+ sz = 128
+ dest := make([]byte, sz)
+ destBytes := unsafe.Pointer(&dest[0])
+ _sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0)
+
+ switch {
+ case errno == syscall.ENODATA:
+ return nil, errno
+ case errno == syscall.ENOTSUP:
+ return nil, errno
+ case errno == syscall.ERANGE:
+ // 128 byte array might just not be good enough,
+ // A dummy buffer is used ``uintptr(0)`` to get real size
+ // of the xattrs on disk
+ _sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(unsafe.Pointer(nil)), uintptr(0), 0, 0)
+ sz = int(_sz)
+ if sz < 0 {
+ return nil, errno
+ }
+ dest = make([]byte, sz)
+ destBytes := unsafe.Pointer(&dest[0])
+ _sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0)
+ if errno != 0 {
+ return nil, errno
+ }
+ case errno != 0:
+ return nil, errno
+ }
+ sz = int(_sz)
+ return dest[:sz], nil
+}
+
+func lsetxattr(path string, attr string, data []byte, flags int) error {
+ pathBytes, err := syscall.BytePtrFromString(path)
+ if err != nil {
+ return err
+ }
+ attrBytes, err := syscall.BytePtrFromString(attr)
+ if err != nil {
+ return err
+ }
+ var dataBytes unsafe.Pointer
+ if len(data) > 0 {
+ dataBytes = unsafe.Pointer(&data[0])
+ } else {
+ dataBytes = unsafe.Pointer(&_zero)
+ }
+ _, _, errno := syscall.Syscall6(syscall.SYS_LSETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(dataBytes), uintptr(len(data)), uintptr(flags), 0)
+ if errno != 0 {
+ return errno
+ }
+ return nil
+}
diff --git a/vendor/github.com/pborman/uuid/LICENSE b/vendor/github.com/pborman/uuid/LICENSE
new file mode 100644
index 0000000..5dc6826
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2009,2014 Google Inc. 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/pborman/uuid/README.md b/vendor/github.com/pborman/uuid/README.md
new file mode 100644
index 0000000..f023d47
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/README.md
@@ -0,0 +1,13 @@
+This project was automatically exported from code.google.com/p/go-uuid
+
+# uuid ![build status](https://travis-ci.org/pborman/uuid.svg?branch=master)
+The uuid package generates and inspects UUIDs based on [RFC 412](http://tools.ietf.org/html/rfc4122) and DCE 1.1: Authentication and Security Services.
+
+###### Install
+`go get github.com/pborman/uuid`
+
+###### Documentation
+[![GoDoc](https://godoc.org/github.com/pborman/uuid?status.svg)](http://godoc.org/github.com/pborman/uuid)
+
+Full `go doc` style documentation for the package can be viewed online without installing this package by using the GoDoc site here:
+http://godoc.org/github.com/pborman/uuid
diff --git a/vendor/github.com/pborman/uuid/dce.go b/vendor/github.com/pborman/uuid/dce.go
new file mode 100755
index 0000000..50a0f2d
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/dce.go
@@ -0,0 +1,84 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/binary"
+ "fmt"
+ "os"
+)
+
+// A Domain represents a Version 2 domain
+type Domain byte
+
+// Domain constants for DCE Security (Version 2) UUIDs.
+const (
+ Person = Domain(0)
+ Group = Domain(1)
+ Org = Domain(2)
+)
+
+// NewDCESecurity returns a DCE Security (Version 2) UUID.
+//
+// The domain should be one of Person, Group or Org.
+// On a POSIX system the id should be the users UID for the Person
+// domain and the users GID for the Group. The meaning of id for
+// the domain Org or on non-POSIX systems is site defined.
+//
+// For a given domain/id pair the same token may be returned for up to
+// 7 minutes and 10 seconds.
+func NewDCESecurity(domain Domain, id uint32) UUID {
+ uuid := NewUUID()
+ if uuid != nil {
+ uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2
+ uuid[9] = byte(domain)
+ binary.BigEndian.PutUint32(uuid[0:], id)
+ }
+ return uuid
+}
+
+// NewDCEPerson returns a DCE Security (Version 2) UUID in the person
+// domain with the id returned by os.Getuid.
+//
+// NewDCEPerson(Person, uint32(os.Getuid()))
+func NewDCEPerson() UUID {
+ return NewDCESecurity(Person, uint32(os.Getuid()))
+}
+
+// NewDCEGroup returns a DCE Security (Version 2) UUID in the group
+// domain with the id returned by os.Getgid.
+//
+// NewDCEGroup(Group, uint32(os.Getgid()))
+func NewDCEGroup() UUID {
+ return NewDCESecurity(Group, uint32(os.Getgid()))
+}
+
+// Domain returns the domain for a Version 2 UUID or false.
+func (uuid UUID) Domain() (Domain, bool) {
+ if v, _ := uuid.Version(); v != 2 {
+ return 0, false
+ }
+ return Domain(uuid[9]), true
+}
+
+// Id returns the id for a Version 2 UUID or false.
+func (uuid UUID) Id() (uint32, bool) {
+ if v, _ := uuid.Version(); v != 2 {
+ return 0, false
+ }
+ return binary.BigEndian.Uint32(uuid[0:4]), true
+}
+
+func (d Domain) String() string {
+ switch d {
+ case Person:
+ return "Person"
+ case Group:
+ return "Group"
+ case Org:
+ return "Org"
+ }
+ return fmt.Sprintf("Domain%d", int(d))
+}
diff --git a/vendor/github.com/pborman/uuid/doc.go b/vendor/github.com/pborman/uuid/doc.go
new file mode 100755
index 0000000..d8bd013
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/doc.go
@@ -0,0 +1,8 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// The uuid package generates and inspects UUIDs.
+//
+// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security Services.
+package uuid
diff --git a/vendor/github.com/pborman/uuid/hash.go b/vendor/github.com/pborman/uuid/hash.go
new file mode 100644
index 0000000..a0420c1
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/hash.go
@@ -0,0 +1,53 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "crypto/md5"
+ "crypto/sha1"
+ "hash"
+)
+
+// Well known Name Space IDs and UUIDs
+var (
+ NameSpace_DNS = Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
+ NameSpace_URL = Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
+ NameSpace_OID = Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
+ NameSpace_X500 = Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
+ NIL = Parse("00000000-0000-0000-0000-000000000000")
+)
+
+// NewHash returns a new UUID derived from the hash of space concatenated with
+// data generated by h. The hash should be at least 16 byte in length. The
+// first 16 bytes of the hash are used to form the UUID. The version of the
+// UUID will be the lower 4 bits of version. NewHash is used to implement
+// NewMD5 and NewSHA1.
+func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID {
+ h.Reset()
+ h.Write(space)
+ h.Write([]byte(data))
+ s := h.Sum(nil)
+ uuid := make([]byte, 16)
+ copy(uuid, s)
+ uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4)
+ uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant
+ return uuid
+}
+
+// NewMD5 returns a new MD5 (Version 3) UUID based on the
+// supplied name space and data.
+//
+// NewHash(md5.New(), space, data, 3)
+func NewMD5(space UUID, data []byte) UUID {
+ return NewHash(md5.New(), space, data, 3)
+}
+
+// NewSHA1 returns a new SHA1 (Version 5) UUID based on the
+// supplied name space and data.
+//
+// NewHash(sha1.New(), space, data, 5)
+func NewSHA1(space UUID, data []byte) UUID {
+ return NewHash(sha1.New(), space, data, 5)
+}
diff --git a/vendor/github.com/pborman/uuid/json.go b/vendor/github.com/pborman/uuid/json.go
new file mode 100644
index 0000000..9dda1df
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/json.go
@@ -0,0 +1,34 @@
+// Copyright 2014 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import "errors"
+
+func (u UUID) MarshalJSON() ([]byte, error) {
+ if len(u) != 16 {
+ return []byte(`""`), nil
+ }
+ var js [38]byte
+ js[0] = '"'
+ encodeHex(js[1:], u)
+ js[37] = '"'
+ return js[:], nil
+}
+
+func (u *UUID) UnmarshalJSON(data []byte) error {
+ if string(data) == `""` {
+ return nil
+ }
+ if data[0] != '"' {
+ return errors.New("invalid UUID format")
+ }
+ data = data[1 : len(data)-1]
+ uu := Parse(string(data))
+ if uu == nil {
+ return errors.New("invalid UUID format")
+ }
+ *u = uu
+ return nil
+}
diff --git a/vendor/github.com/pborman/uuid/node.go b/vendor/github.com/pborman/uuid/node.go
new file mode 100755
index 0000000..42d60da
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/node.go
@@ -0,0 +1,117 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "net"
+ "sync"
+)
+
+var (
+ nodeMu sync.Mutex
+ interfaces []net.Interface // cached list of interfaces
+ ifname string // name of interface being used
+ nodeID []byte // hardware for version 1 UUIDs
+)
+
+// NodeInterface returns the name of the interface from which the NodeID was
+// derived. The interface "user" is returned if the NodeID was set by
+// SetNodeID.
+func NodeInterface() string {
+ defer nodeMu.Unlock()
+ nodeMu.Lock()
+ return ifname
+}
+
+// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs.
+// If name is "" then the first usable interface found will be used or a random
+// Node ID will be generated. If a named interface cannot be found then false
+// is returned.
+//
+// SetNodeInterface never fails when name is "".
+func SetNodeInterface(name string) bool {
+ defer nodeMu.Unlock()
+ nodeMu.Lock()
+ return setNodeInterface(name)
+}
+
+func setNodeInterface(name string) bool {
+ if interfaces == nil {
+ var err error
+ interfaces, err = net.Interfaces()
+ if err != nil && name != "" {
+ return false
+ }
+ }
+
+ for _, ifs := range interfaces {
+ if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) {
+ if setNodeID(ifs.HardwareAddr) {
+ ifname = ifs.Name
+ return true
+ }
+ }
+ }
+
+ // We found no interfaces with a valid hardware address. If name
+ // does not specify a specific interface generate a random Node ID
+ // (section 4.1.6)
+ if name == "" {
+ if nodeID == nil {
+ nodeID = make([]byte, 6)
+ }
+ randomBits(nodeID)
+ return true
+ }
+ return false
+}
+
+// NodeID returns a slice of a copy of the current Node ID, setting the Node ID
+// if not already set.
+func NodeID() []byte {
+ defer nodeMu.Unlock()
+ nodeMu.Lock()
+ if nodeID == nil {
+ setNodeInterface("")
+ }
+ nid := make([]byte, 6)
+ copy(nid, nodeID)
+ return nid
+}
+
+// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes
+// of id are used. If id is less than 6 bytes then false is returned and the
+// Node ID is not set.
+func SetNodeID(id []byte) bool {
+ defer nodeMu.Unlock()
+ nodeMu.Lock()
+ if setNodeID(id) {
+ ifname = "user"
+ return true
+ }
+ return false
+}
+
+func setNodeID(id []byte) bool {
+ if len(id) < 6 {
+ return false
+ }
+ if nodeID == nil {
+ nodeID = make([]byte, 6)
+ }
+ copy(nodeID, id)
+ return true
+}
+
+// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is
+// not valid. The NodeID is only well defined for version 1 and 2 UUIDs.
+func (uuid UUID) NodeID() []byte {
+ if len(uuid) != 16 {
+ return nil
+ }
+ node := make([]byte, 6)
+ copy(node, uuid[10:])
+ return node
+}
diff --git a/vendor/github.com/pborman/uuid/sql.go b/vendor/github.com/pborman/uuid/sql.go
new file mode 100644
index 0000000..c84f900
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/sql.go
@@ -0,0 +1,58 @@
+// Copyright 2015 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "errors"
+ "fmt"
+)
+
+// Scan implements sql.Scanner so UUIDs can be read from databases transparently
+// Currently, database types that map to string and []byte are supported. Please
+// consult database-specific driver documentation for matching types.
+func (uuid *UUID) Scan(src interface{}) error {
+ switch src.(type) {
+ case string:
+ // if an empty UUID comes from a table, we return a null UUID
+ if src.(string) == "" {
+ return nil
+ }
+
+ // see uuid.Parse for required string format
+ parsed := Parse(src.(string))
+
+ if parsed == nil {
+ return errors.New("Scan: invalid UUID format")
+ }
+
+ *uuid = parsed
+ case []byte:
+ b := src.([]byte)
+
+ // if an empty UUID comes from a table, we return a null UUID
+ if len(b) == 0 {
+ return nil
+ }
+
+ // assumes a simple slice of bytes if 16 bytes
+ // otherwise attempts to parse
+ if len(b) == 16 {
+ *uuid = UUID(b)
+ } else {
+ u := Parse(string(b))
+
+ if u == nil {
+ return errors.New("Scan: invalid UUID format")
+ }
+
+ *uuid = u
+ }
+
+ default:
+ return fmt.Errorf("Scan: unable to scan type %T into UUID", src)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/pborman/uuid/time.go b/vendor/github.com/pborman/uuid/time.go
new file mode 100755
index 0000000..eedf242
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/time.go
@@ -0,0 +1,132 @@
+// Copyright 2014 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/binary"
+ "sync"
+ "time"
+)
+
+// A Time represents a time as the number of 100's of nanoseconds since 15 Oct
+// 1582.
+type Time int64
+
+const (
+ lillian = 2299160 // Julian day of 15 Oct 1582
+ unix = 2440587 // Julian day of 1 Jan 1970
+ epoch = unix - lillian // Days between epochs
+ g1582 = epoch * 86400 // seconds between epochs
+ g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs
+)
+
+var (
+ timeMu sync.Mutex
+ lasttime uint64 // last time we returned
+ clock_seq uint16 // clock sequence for this run
+
+ timeNow = time.Now // for testing
+)
+
+// UnixTime converts t the number of seconds and nanoseconds using the Unix
+// epoch of 1 Jan 1970.
+func (t Time) UnixTime() (sec, nsec int64) {
+ sec = int64(t - g1582ns100)
+ nsec = (sec % 10000000) * 100
+ sec /= 10000000
+ return sec, nsec
+}
+
+// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and
+// clock sequence as well as adjusting the clock sequence as needed. An error
+// is returned if the current time cannot be determined.
+func GetTime() (Time, uint16, error) {
+ defer timeMu.Unlock()
+ timeMu.Lock()
+ return getTime()
+}
+
+func getTime() (Time, uint16, error) {
+ t := timeNow()
+
+ // If we don't have a clock sequence already, set one.
+ if clock_seq == 0 {
+ setClockSequence(-1)
+ }
+ now := uint64(t.UnixNano()/100) + g1582ns100
+
+ // If time has gone backwards with this clock sequence then we
+ // increment the clock sequence
+ if now <= lasttime {
+ clock_seq = ((clock_seq + 1) & 0x3fff) | 0x8000
+ }
+ lasttime = now
+ return Time(now), clock_seq, nil
+}
+
+// ClockSequence returns the current clock sequence, generating one if not
+// already set. The clock sequence is only used for Version 1 UUIDs.
+//
+// The uuid package does not use global static storage for the clock sequence or
+// the last time a UUID was generated. Unless SetClockSequence a new random
+// clock sequence is generated the first time a clock sequence is requested by
+// ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) sequence is generated
+// for
+func ClockSequence() int {
+ defer timeMu.Unlock()
+ timeMu.Lock()
+ return clockSequence()
+}
+
+func clockSequence() int {
+ if clock_seq == 0 {
+ setClockSequence(-1)
+ }
+ return int(clock_seq & 0x3fff)
+}
+
+// SetClockSeq sets the clock sequence to the lower 14 bits of seq. Setting to
+// -1 causes a new sequence to be generated.
+func SetClockSequence(seq int) {
+ defer timeMu.Unlock()
+ timeMu.Lock()
+ setClockSequence(seq)
+}
+
+func setClockSequence(seq int) {
+ if seq == -1 {
+ var b [2]byte
+ randomBits(b[:]) // clock sequence
+ seq = int(b[0])<<8 | int(b[1])
+ }
+ old_seq := clock_seq
+ clock_seq = uint16(seq&0x3fff) | 0x8000 // Set our variant
+ if old_seq != clock_seq {
+ lasttime = 0
+ }
+}
+
+// Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in
+// uuid. It returns false if uuid is not valid. The time is only well defined
+// for version 1 and 2 UUIDs.
+func (uuid UUID) Time() (Time, bool) {
+ if len(uuid) != 16 {
+ return 0, false
+ }
+ time := int64(binary.BigEndian.Uint32(uuid[0:4]))
+ time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32
+ time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48
+ return Time(time), true
+}
+
+// ClockSequence returns the clock sequence encoded in uuid. It returns false
+// if uuid is not valid. The clock sequence is only well defined for version 1
+// and 2 UUIDs.
+func (uuid UUID) ClockSequence() (int, bool) {
+ if len(uuid) != 16 {
+ return 0, false
+ }
+ return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff, true
+}
diff --git a/vendor/github.com/pborman/uuid/util.go b/vendor/github.com/pborman/uuid/util.go
new file mode 100644
index 0000000..fc8e052
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/util.go
@@ -0,0 +1,43 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "io"
+)
+
+// randomBits completely fills slice b with random data.
+func randomBits(b []byte) {
+ if _, err := io.ReadFull(rander, b); err != nil {
+ panic(err.Error()) // rand should never fail
+ }
+}
+
+// xvalues returns the value of a byte as a hexadecimal digit or 255.
+var xvalues = [256]byte{
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255,
+ 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
+}
+
+// xtob converts the the first two hex bytes of x into a byte.
+func xtob(x string) (byte, bool) {
+ b1 := xvalues[x[0]]
+ b2 := xvalues[x[1]]
+ return (b1 << 4) | b2, b1 != 255 && b2 != 255
+}
diff --git a/vendor/github.com/pborman/uuid/uuid.go b/vendor/github.com/pborman/uuid/uuid.go
new file mode 100644
index 0000000..c4482cd
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/uuid.go
@@ -0,0 +1,176 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "strings"
+)
+
+// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC
+// 4122.
+type UUID []byte
+
+// A Version represents a UUIDs version.
+type Version byte
+
+// A Variant represents a UUIDs variant.
+type Variant byte
+
+// Constants returned by Variant.
+const (
+ Invalid = Variant(iota) // Invalid UUID
+ RFC4122 // The variant specified in RFC4122
+ Reserved // Reserved, NCS backward compatibility.
+ Microsoft // Reserved, Microsoft Corporation backward compatibility.
+ Future // Reserved for future definition.
+)
+
+var rander = rand.Reader // random function
+
+// New returns a new random (version 4) UUID as a string. It is a convenience
+// function for NewRandom().String().
+func New() string {
+ return NewRandom().String()
+}
+
+// Parse decodes s into a UUID or returns nil. Both the UUID form of
+// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
+// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded.
+func Parse(s string) UUID {
+ if len(s) == 36+9 {
+ if strings.ToLower(s[:9]) != "urn:uuid:" {
+ return nil
+ }
+ s = s[9:]
+ } else if len(s) != 36 {
+ return nil
+ }
+ if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
+ return nil
+ }
+ var uuid [16]byte
+ for i, x := range [16]int{
+ 0, 2, 4, 6,
+ 9, 11,
+ 14, 16,
+ 19, 21,
+ 24, 26, 28, 30, 32, 34} {
+ if v, ok := xtob(s[x:]); !ok {
+ return nil
+ } else {
+ uuid[i] = v
+ }
+ }
+ return uuid[:]
+}
+
+// Equal returns true if uuid1 and uuid2 are equal.
+func Equal(uuid1, uuid2 UUID) bool {
+ return bytes.Equal(uuid1, uuid2)
+}
+
+// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+// , or "" if uuid is invalid.
+func (uuid UUID) String() string {
+ if len(uuid) != 16 {
+ return ""
+ }
+ var buf [36]byte
+ encodeHex(buf[:], uuid)
+ return string(buf[:])
+}
+
+// URN returns the RFC 2141 URN form of uuid,
+// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.
+func (uuid UUID) URN() string {
+ if len(uuid) != 16 {
+ return ""
+ }
+ var buf [36 + 9]byte
+ copy(buf[:], "urn:uuid:")
+ encodeHex(buf[9:], uuid)
+ return string(buf[:])
+}
+
+func encodeHex(dst []byte, uuid UUID) {
+ hex.Encode(dst[:], uuid[:4])
+ dst[8] = '-'
+ hex.Encode(dst[9:13], uuid[4:6])
+ dst[13] = '-'
+ hex.Encode(dst[14:18], uuid[6:8])
+ dst[18] = '-'
+ hex.Encode(dst[19:23], uuid[8:10])
+ dst[23] = '-'
+ hex.Encode(dst[24:], uuid[10:])
+}
+
+// Variant returns the variant encoded in uuid. It returns Invalid if
+// uuid is invalid.
+func (uuid UUID) Variant() Variant {
+ if len(uuid) != 16 {
+ return Invalid
+ }
+ switch {
+ case (uuid[8] & 0xc0) == 0x80:
+ return RFC4122
+ case (uuid[8] & 0xe0) == 0xc0:
+ return Microsoft
+ case (uuid[8] & 0xe0) == 0xe0:
+ return Future
+ default:
+ return Reserved
+ }
+}
+
+// Version returns the version of uuid. It returns false if uuid is not
+// valid.
+func (uuid UUID) Version() (Version, bool) {
+ if len(uuid) != 16 {
+ return 0, false
+ }
+ return Version(uuid[6] >> 4), true
+}
+
+func (v Version) String() string {
+ if v > 15 {
+ return fmt.Sprintf("BAD_VERSION_%d", v)
+ }
+ return fmt.Sprintf("VERSION_%d", v)
+}
+
+func (v Variant) String() string {
+ switch v {
+ case RFC4122:
+ return "RFC4122"
+ case Reserved:
+ return "Reserved"
+ case Microsoft:
+ return "Microsoft"
+ case Future:
+ return "Future"
+ case Invalid:
+ return "Invalid"
+ }
+ return fmt.Sprintf("BadVariant%d", int(v))
+}
+
+// SetRand sets the random number generator to r, which implents io.Reader.
+// If r.Read returns an error when the package requests random data then
+// a panic will be issued.
+//
+// Calling SetRand with nil sets the random number generator to the default
+// generator.
+func SetRand(r io.Reader) {
+ if r == nil {
+ rander = rand.Reader
+ return
+ }
+ rander = r
+}
diff --git a/vendor/github.com/pborman/uuid/version1.go b/vendor/github.com/pborman/uuid/version1.go
new file mode 100644
index 0000000..0127eac
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/version1.go
@@ -0,0 +1,41 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+import (
+ "encoding/binary"
+)
+
+// NewUUID returns a Version 1 UUID based on the current NodeID and clock
+// sequence, and the current time. If the NodeID has not been set by SetNodeID
+// or SetNodeInterface then it will be set automatically. If the NodeID cannot
+// be set NewUUID returns nil. If clock sequence has not been set by
+// SetClockSequence then it will be set automatically. If GetTime fails to
+// return the current NewUUID returns nil.
+func NewUUID() UUID {
+ if nodeID == nil {
+ SetNodeInterface("")
+ }
+
+ now, seq, err := GetTime()
+ if err != nil {
+ return nil
+ }
+
+ uuid := make([]byte, 16)
+
+ time_low := uint32(now & 0xffffffff)
+ time_mid := uint16((now >> 32) & 0xffff)
+ time_hi := uint16((now >> 48) & 0x0fff)
+ time_hi |= 0x1000 // Version 1
+
+ binary.BigEndian.PutUint32(uuid[0:], time_low)
+ binary.BigEndian.PutUint16(uuid[4:], time_mid)
+ binary.BigEndian.PutUint16(uuid[6:], time_hi)
+ binary.BigEndian.PutUint16(uuid[8:], seq)
+ copy(uuid[10:], nodeID)
+
+ return uuid
+}
diff --git a/vendor/github.com/pborman/uuid/version4.go b/vendor/github.com/pborman/uuid/version4.go
new file mode 100644
index 0000000..b3d4a36
--- /dev/null
+++ b/vendor/github.com/pborman/uuid/version4.go
@@ -0,0 +1,25 @@
+// Copyright 2011 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package uuid
+
+// Random returns a Random (Version 4) UUID or panics.
+//
+// The strength of the UUIDs is based on the strength of the crypto/rand
+// package.
+//
+// A note about uniqueness derived from from the UUID Wikipedia entry:
+//
+// Randomly generated UUIDs have 122 random bits. One's annual risk of being
+// hit by a meteorite is estimated to be one chance in 17 billion, that
+// means the probability is about 0.00000000006 (6 × 10−11),
+// equivalent to the odds of creating a few tens of trillions of UUIDs in a
+// year and having one duplicate.
+func NewRandom() UUID {
+ uuid := make([]byte, 16)
+ randomBits([]byte(uuid))
+ uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
+ uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
+ return uuid
+}
diff --git a/vendor/github.com/philhofer/fwd/LICENSE.md b/vendor/github.com/philhofer/fwd/LICENSE.md
new file mode 100644
index 0000000..1ac6a81
--- /dev/null
+++ b/vendor/github.com/philhofer/fwd/LICENSE.md
@@ -0,0 +1,7 @@
+Copyright (c) 2014-2015, Philip Hofer
+
+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/philhofer/fwd/README.md b/vendor/github.com/philhofer/fwd/README.md
new file mode 100644
index 0000000..38349af
--- /dev/null
+++ b/vendor/github.com/philhofer/fwd/README.md
@@ -0,0 +1,315 @@
+
+# fwd
+ import "github.com/philhofer/fwd"
+
+The `fwd` package provides a buffered reader
+and writer. Each has methods that help improve
+the encoding/decoding performance of some binary
+protocols.
+
+The `fwd.Writer` and `fwd.Reader` type provide similar
+functionality to their counterparts in `bufio`, plus
+a few extra utility methods that simplify read-ahead
+and write-ahead. I wrote this package to improve serialization
+performance for <a href="http://github.com/tinylib/msgp">http://github.com/tinylib/msgp</a>,
+where it provided about a 2x speedup over `bufio` for certain
+workloads. However, care must be taken to understand the semantics of the
+extra methods provided by this package, as they allow
+the user to access and manipulate the buffer memory
+directly.
+
+The extra methods for `fwd.Reader` are `Peek`, `Skip`
+and `Next`. `(*fwd.Reader).Peek`, unlike `(*bufio.Reader).Peek`,
+will re-allocate the read buffer in order to accommodate arbitrarily
+large read-ahead. `(*fwd.Reader).Skip` skips the next `n` bytes
+in the stream, and uses the `io.Seeker` interface if the underlying
+stream implements it. `(*fwd.Reader).Next` returns a slice pointing
+to the next `n` bytes in the read buffer (like `Peek`), but also
+increments the read position. This allows users to process streams
+in arbitrary block sizes without having to manage appropriately-sized
+slices. Additionally, obviating the need to copy the data from the
+buffer to another location in memory can improve performance dramatically
+in CPU-bound applications.
+
+`fwd.Writer` only has one extra method, which is `(*fwd.Writer).Next`, which
+returns a slice pointing to the next `n` bytes of the writer, and increments
+the write position by the length of the returned slice. This allows users
+to write directly to the end of the buffer.
+
+
+
+
+## Constants
+``` go
+const (
+ // DefaultReaderSize is the default size of the read buffer
+ DefaultReaderSize = 2048
+)
+```
+``` go
+const (
+ // DefaultWriterSize is the
+ // default write buffer size.
+ DefaultWriterSize = 2048
+)
+```
+
+
+
+## type Reader
+``` go
+type Reader struct {
+ // contains filtered or unexported fields
+}
+```
+Reader is a buffered look-ahead reader
+
+
+
+
+
+
+
+
+
+### func NewReader
+``` go
+func NewReader(r io.Reader) *Reader
+```
+NewReader returns a new *Reader that reads from 'r'
+
+
+### func NewReaderSize
+``` go
+func NewReaderSize(r io.Reader, n int) *Reader
+```
+NewReaderSize returns a new *Reader that
+reads from 'r' and has a buffer size 'n'
+
+
+
+
+### func (\*Reader) BufferSize
+``` go
+func (r *Reader) BufferSize() int
+```
+BufferSize returns the total size of the buffer
+
+
+
+### func (\*Reader) Buffered
+``` go
+func (r *Reader) Buffered() int
+```
+Buffered returns the number of bytes currently in the buffer
+
+
+
+### func (\*Reader) Next
+``` go
+func (r *Reader) Next(n int) ([]byte, error)
+```
+Next returns the next 'n' bytes in the stream.
+Unlike Peek, Next advances the reader position.
+The returned bytes point to the same
+data as the buffer, so the slice is
+only valid until the next reader method call.
+An EOF is considered an unexpected error.
+If an the returned slice is less than the
+length asked for, an error will be returned,
+and the reader position will not be incremented.
+
+
+
+### func (\*Reader) Peek
+``` go
+func (r *Reader) Peek(n int) ([]byte, error)
+```
+Peek returns the next 'n' buffered bytes,
+reading from the underlying reader if necessary.
+It will only return a slice shorter than 'n' bytes
+if it also returns an error. Peek does not advance
+the reader. EOF errors are *not* returned as
+io.ErrUnexpectedEOF.
+
+
+
+### func (\*Reader) Read
+``` go
+func (r *Reader) Read(b []byte) (int, error)
+```
+Read implements `io.Reader`
+
+
+
+### func (\*Reader) ReadByte
+``` go
+func (r *Reader) ReadByte() (byte, error)
+```
+ReadByte implements `io.ByteReader`
+
+
+
+### func (\*Reader) ReadFull
+``` go
+func (r *Reader) ReadFull(b []byte) (int, error)
+```
+ReadFull attempts to read len(b) bytes into
+'b'. It returns the number of bytes read into
+'b', and an error if it does not return len(b).
+EOF is considered an unexpected error.
+
+
+
+### func (\*Reader) Reset
+``` go
+func (r *Reader) Reset(rd io.Reader)
+```
+Reset resets the underlying reader
+and the read buffer.
+
+
+
+### func (\*Reader) Skip
+``` go
+func (r *Reader) Skip(n int) (int, error)
+```
+Skip moves the reader forward 'n' bytes.
+Returns the number of bytes skipped and any
+errors encountered. It is analogous to Seek(n, 1).
+If the underlying reader implements io.Seeker, then
+that method will be used to skip forward.
+
+If the reader encounters
+an EOF before skipping 'n' bytes, it
+returns io.ErrUnexpectedEOF. If the
+underlying reader implements io.Seeker, then
+those rules apply instead. (Many implementations
+will not return `io.EOF` until the next call
+to Read.)
+
+
+
+### func (\*Reader) WriteTo
+``` go
+func (r *Reader) WriteTo(w io.Writer) (int64, error)
+```
+WriteTo implements `io.WriterTo`
+
+
+
+## type Writer
+``` go
+type Writer struct {
+ // contains filtered or unexported fields
+}
+```
+Writer is a buffered writer
+
+
+
+
+
+
+
+
+
+### func NewWriter
+``` go
+func NewWriter(w io.Writer) *Writer
+```
+NewWriter returns a new writer
+that writes to 'w' and has a buffer
+that is `DefaultWriterSize` bytes.
+
+
+### func NewWriterSize
+``` go
+func NewWriterSize(w io.Writer, size int) *Writer
+```
+NewWriterSize returns a new writer
+that writes to 'w' and has a buffer
+that is 'size' bytes.
+
+
+
+
+### func (\*Writer) BufferSize
+``` go
+func (w *Writer) BufferSize() int
+```
+BufferSize returns the maximum size of the buffer.
+
+
+
+### func (\*Writer) Buffered
+``` go
+func (w *Writer) Buffered() int
+```
+Buffered returns the number of buffered bytes
+in the reader.
+
+
+
+### func (\*Writer) Flush
+``` go
+func (w *Writer) Flush() error
+```
+Flush flushes any buffered bytes
+to the underlying writer.
+
+
+
+### func (\*Writer) Next
+``` go
+func (w *Writer) Next(n int) ([]byte, error)
+```
+Next returns the next 'n' free bytes
+in the write buffer, flushing the writer
+as necessary. Next will return `io.ErrShortBuffer`
+if 'n' is greater than the size of the write buffer.
+Calls to 'next' increment the write position by
+the size of the returned buffer.
+
+
+
+### func (\*Writer) ReadFrom
+``` go
+func (w *Writer) ReadFrom(r io.Reader) (int64, error)
+```
+ReadFrom implements `io.ReaderFrom`
+
+
+
+### func (\*Writer) Write
+``` go
+func (w *Writer) Write(p []byte) (int, error)
+```
+Write implements `io.Writer`
+
+
+
+### func (\*Writer) WriteByte
+``` go
+func (w *Writer) WriteByte(b byte) error
+```
+WriteByte implements `io.ByteWriter`
+
+
+
+### func (\*Writer) WriteString
+``` go
+func (w *Writer) WriteString(s string) (int, error)
+```
+WriteString is analogous to Write, but it takes a string.
+
+
+
+
+
+
+
+
+
+- - -
+Generated by [godoc2md](http://godoc.org/github.com/davecheney/godoc2md) \ No newline at end of file
diff --git a/vendor/github.com/philhofer/fwd/reader.go b/vendor/github.com/philhofer/fwd/reader.go
new file mode 100644
index 0000000..e591910
--- /dev/null
+++ b/vendor/github.com/philhofer/fwd/reader.go
@@ -0,0 +1,379 @@
+// The `fwd` package provides a buffered reader
+// and writer. Each has methods that help improve
+// the encoding/decoding performance of some binary
+// protocols.
+//
+// The `fwd.Writer` and `fwd.Reader` type provide similar
+// functionality to their counterparts in `bufio`, plus
+// a few extra utility methods that simplify read-ahead
+// and write-ahead. I wrote this package to improve serialization
+// performance for http://github.com/tinylib/msgp,
+// where it provided about a 2x speedup over `bufio` for certain
+// workloads. However, care must be taken to understand the semantics of the
+// extra methods provided by this package, as they allow
+// the user to access and manipulate the buffer memory
+// directly.
+//
+// The extra methods for `fwd.Reader` are `Peek`, `Skip`
+// and `Next`. `(*fwd.Reader).Peek`, unlike `(*bufio.Reader).Peek`,
+// will re-allocate the read buffer in order to accommodate arbitrarily
+// large read-ahead. `(*fwd.Reader).Skip` skips the next `n` bytes
+// in the stream, and uses the `io.Seeker` interface if the underlying
+// stream implements it. `(*fwd.Reader).Next` returns a slice pointing
+// to the next `n` bytes in the read buffer (like `Peek`), but also
+// increments the read position. This allows users to process streams
+// in arbitrary block sizes without having to manage appropriately-sized
+// slices. Additionally, obviating the need to copy the data from the
+// buffer to another location in memory can improve performance dramatically
+// in CPU-bound applications.
+//
+// `fwd.Writer` only has one extra method, which is `(*fwd.Writer).Next`, which
+// returns a slice pointing to the next `n` bytes of the writer, and increments
+// the write position by the length of the returned slice. This allows users
+// to write directly to the end of the buffer.
+//
+package fwd
+
+import "io"
+
+const (
+ // DefaultReaderSize is the default size of the read buffer
+ DefaultReaderSize = 2048
+
+ // minimum read buffer; straight from bufio
+ minReaderSize = 16
+)
+
+// NewReader returns a new *Reader that reads from 'r'
+func NewReader(r io.Reader) *Reader {
+ return NewReaderSize(r, DefaultReaderSize)
+}
+
+// NewReaderSize returns a new *Reader that
+// reads from 'r' and has a buffer size 'n'
+func NewReaderSize(r io.Reader, n int) *Reader {
+ rd := &Reader{
+ r: r,
+ data: make([]byte, 0, max(minReaderSize, n)),
+ }
+ if s, ok := r.(io.Seeker); ok {
+ rd.rs = s
+ }
+ return rd
+}
+
+// Reader is a buffered look-ahead reader
+type Reader struct {
+ r io.Reader // underlying reader
+
+ // data[n:len(data)] is buffered data; data[len(data):cap(data)] is free buffer space
+ data []byte // data
+ n int // read offset
+ state error // last read error
+
+ // if the reader past to NewReader was
+ // also an io.Seeker, this is non-nil
+ rs io.Seeker
+}
+
+// Reset resets the underlying reader
+// and the read buffer.
+func (r *Reader) Reset(rd io.Reader) {
+ r.r = rd
+ r.data = r.data[0:0]
+ r.n = 0
+ r.state = nil
+ if s, ok := rd.(io.Seeker); ok {
+ r.rs = s
+ } else {
+ r.rs = nil
+ }
+}
+
+// more() does one read on the underlying reader
+func (r *Reader) more() {
+ // move data backwards so that
+ // the read offset is 0; this way
+ // we can supply the maximum number of
+ // bytes to the reader
+ if r.n != 0 {
+ if r.n < len(r.data) {
+ r.data = r.data[:copy(r.data[0:], r.data[r.n:])]
+ } else {
+ r.data = r.data[:0]
+ }
+ r.n = 0
+ }
+ var a int
+ a, r.state = r.r.Read(r.data[len(r.data):cap(r.data)])
+ if a == 0 && r.state == nil {
+ r.state = io.ErrNoProgress
+ return
+ }
+ r.data = r.data[:len(r.data)+a]
+}
+
+// pop error
+func (r *Reader) err() (e error) {
+ e, r.state = r.state, nil
+ return
+}
+
+// pop error; EOF -> io.ErrUnexpectedEOF
+func (r *Reader) noEOF() (e error) {
+ e, r.state = r.state, nil
+ if e == io.EOF {
+ e = io.ErrUnexpectedEOF
+ }
+ return
+}
+
+// buffered bytes
+func (r *Reader) buffered() int { return len(r.data) - r.n }
+
+// Buffered returns the number of bytes currently in the buffer
+func (r *Reader) Buffered() int { return len(r.data) - r.n }
+
+// BufferSize returns the total size of the buffer
+func (r *Reader) BufferSize() int { return cap(r.data) }
+
+// Peek returns the next 'n' buffered bytes,
+// reading from the underlying reader if necessary.
+// It will only return a slice shorter than 'n' bytes
+// if it also returns an error. Peek does not advance
+// the reader. EOF errors are *not* returned as
+// io.ErrUnexpectedEOF.
+func (r *Reader) Peek(n int) ([]byte, error) {
+ // in the degenerate case,
+ // we may need to realloc
+ // (the caller asked for more
+ // bytes than the size of the buffer)
+ if cap(r.data) < n {
+ old := r.data[r.n:]
+ r.data = make([]byte, n+r.buffered())
+ r.data = r.data[:copy(r.data, old)]
+ r.n = 0
+ }
+
+ // keep filling until
+ // we hit an error or
+ // read enough bytes
+ for r.buffered() < n && r.state == nil {
+ r.more()
+ }
+
+ // we must have hit an error
+ if r.buffered() < n {
+ return r.data[r.n:], r.err()
+ }
+
+ return r.data[r.n : r.n+n], nil
+}
+
+// Skip moves the reader forward 'n' bytes.
+// Returns the number of bytes skipped and any
+// errors encountered. It is analogous to Seek(n, 1).
+// If the underlying reader implements io.Seeker, then
+// that method will be used to skip forward.
+//
+// If the reader encounters
+// an EOF before skipping 'n' bytes, it
+// returns io.ErrUnexpectedEOF. If the
+// underlying reader implements io.Seeker, then
+// those rules apply instead. (Many implementations
+// will not return `io.EOF` until the next call
+// to Read.)
+func (r *Reader) Skip(n int) (int, error) {
+
+ // fast path
+ if r.buffered() >= n {
+ r.n += n
+ return n, nil
+ }
+
+ // use seeker implementation
+ // if we can
+ if r.rs != nil {
+ return r.skipSeek(n)
+ }
+
+ // loop on filling
+ // and then erasing
+ o := n
+ for r.buffered() < n && r.state == nil {
+ r.more()
+ // we can skip forward
+ // up to r.buffered() bytes
+ step := min(r.buffered(), n)
+ r.n += step
+ n -= step
+ }
+ // at this point, n should be
+ // 0 if everything went smoothly
+ return o - n, r.noEOF()
+}
+
+// Next returns the next 'n' bytes in the stream.
+// Unlike Peek, Next advances the reader position.
+// The returned bytes point to the same
+// data as the buffer, so the slice is
+// only valid until the next reader method call.
+// An EOF is considered an unexpected error.
+// If an the returned slice is less than the
+// length asked for, an error will be returned,
+// and the reader position will not be incremented.
+func (r *Reader) Next(n int) ([]byte, error) {
+
+ // in case the buffer is too small
+ if cap(r.data) < n {
+ old := r.data[r.n:]
+ r.data = make([]byte, n+r.buffered())
+ r.data = r.data[:copy(r.data, old)]
+ r.n = 0
+ }
+
+ // fill at least 'n' bytes
+ for r.buffered() < n && r.state == nil {
+ r.more()
+ }
+
+ if r.buffered() < n {
+ return r.data[r.n:], r.noEOF()
+ }
+ out := r.data[r.n : r.n+n]
+ r.n += n
+ return out, nil
+}
+
+// skipSeek uses the io.Seeker to seek forward.
+// only call this function when n > r.buffered()
+func (r *Reader) skipSeek(n int) (int, error) {
+ o := r.buffered()
+ // first, clear buffer
+ n -= o
+ r.n = 0
+ r.data = r.data[:0]
+
+ // then seek forward remaning bytes
+ i, err := r.rs.Seek(int64(n), 1)
+ return int(i) + o, err
+}
+
+// Read implements `io.Reader`
+func (r *Reader) Read(b []byte) (int, error) {
+ // if we have data in the buffer, just
+ // return that.
+ if r.buffered() != 0 {
+ x := copy(b, r.data[r.n:])
+ r.n += x
+ return x, nil
+ }
+ var n int
+ // we have no buffered data; determine
+ // whether or not to buffer or call
+ // the underlying reader directly
+ if len(b) >= cap(r.data) {
+ n, r.state = r.r.Read(b)
+ } else {
+ r.more()
+ n = copy(b, r.data)
+ r.n = n
+ }
+ if n == 0 {
+ return 0, r.err()
+ }
+ return n, nil
+}
+
+// ReadFull attempts to read len(b) bytes into
+// 'b'. It returns the number of bytes read into
+// 'b', and an error if it does not return len(b).
+// EOF is considered an unexpected error.
+func (r *Reader) ReadFull(b []byte) (int, error) {
+ var n int // read into b
+ var nn int // scratch
+ l := len(b)
+ // either read buffered data,
+ // or read directly for the underlying
+ // buffer, or fetch more buffered data.
+ for n < l && r.state == nil {
+ if r.buffered() != 0 {
+ nn = copy(b[n:], r.data[r.n:])
+ n += nn
+ r.n += nn
+ } else if l-n > cap(r.data) {
+ nn, r.state = r.r.Read(b[n:])
+ n += nn
+ } else {
+ r.more()
+ }
+ }
+ if n < l {
+ return n, r.noEOF()
+ }
+ return n, nil
+}
+
+// ReadByte implements `io.ByteReader`
+func (r *Reader) ReadByte() (byte, error) {
+ for r.buffered() < 1 && r.state == nil {
+ r.more()
+ }
+ if r.buffered() < 1 {
+ return 0, r.err()
+ }
+ b := r.data[r.n]
+ r.n++
+ return b, nil
+}
+
+// WriteTo implements `io.WriterTo`
+func (r *Reader) WriteTo(w io.Writer) (int64, error) {
+ var (
+ i int64
+ ii int
+ err error
+ )
+ // first, clear buffer
+ if r.buffered() > 0 {
+ ii, err = w.Write(r.data[r.n:])
+ i += int64(ii)
+ if err != nil {
+ return i, err
+ }
+ r.data = r.data[0:0]
+ r.n = 0
+ }
+ for r.state == nil {
+ // here we just do
+ // 1:1 reads and writes
+ r.more()
+ if r.buffered() > 0 {
+ ii, err = w.Write(r.data)
+ i += int64(ii)
+ if err != nil {
+ return i, err
+ }
+ r.data = r.data[0:0]
+ r.n = 0
+ }
+ }
+ if r.state != io.EOF {
+ return i, r.err()
+ }
+ return i, nil
+}
+
+func min(a int, b int) int {
+ if a < b {
+ return a
+ }
+ return b
+}
+
+func max(a int, b int) int {
+ if a < b {
+ return b
+ }
+ return a
+}
diff --git a/vendor/github.com/philhofer/fwd/writer.go b/vendor/github.com/philhofer/fwd/writer.go
new file mode 100644
index 0000000..2dc392a
--- /dev/null
+++ b/vendor/github.com/philhofer/fwd/writer.go
@@ -0,0 +1,224 @@
+package fwd
+
+import "io"
+
+const (
+ // DefaultWriterSize is the
+ // default write buffer size.
+ DefaultWriterSize = 2048
+
+ minWriterSize = minReaderSize
+)
+
+// Writer is a buffered writer
+type Writer struct {
+ w io.Writer // writer
+ buf []byte // 0:len(buf) is bufered data
+}
+
+// NewWriter returns a new writer
+// that writes to 'w' and has a buffer
+// that is `DefaultWriterSize` bytes.
+func NewWriter(w io.Writer) *Writer {
+ if wr, ok := w.(*Writer); ok {
+ return wr
+ }
+ return &Writer{
+ w: w,
+ buf: make([]byte, 0, DefaultWriterSize),
+ }
+}
+
+// NewWriterSize returns a new writer
+// that writes to 'w' and has a buffer
+// that is 'size' bytes.
+func NewWriterSize(w io.Writer, size int) *Writer {
+ if wr, ok := w.(*Writer); ok && cap(wr.buf) >= size {
+ return wr
+ }
+ return &Writer{
+ w: w,
+ buf: make([]byte, 0, max(size, minWriterSize)),
+ }
+}
+
+// Buffered returns the number of buffered bytes
+// in the reader.
+func (w *Writer) Buffered() int { return len(w.buf) }
+
+// BufferSize returns the maximum size of the buffer.
+func (w *Writer) BufferSize() int { return cap(w.buf) }
+
+// Flush flushes any buffered bytes
+// to the underlying writer.
+func (w *Writer) Flush() error {
+ l := len(w.buf)
+ if l > 0 {
+ n, err := w.w.Write(w.buf)
+
+ // if we didn't write the whole
+ // thing, copy the unwritten
+ // bytes to the beginnning of the
+ // buffer.
+ if n < l && n > 0 {
+ w.pushback(n)
+ if err == nil {
+ err = io.ErrShortWrite
+ }
+ }
+ if err != nil {
+ return err
+ }
+ w.buf = w.buf[:0]
+ return nil
+ }
+ return nil
+}
+
+// Write implements `io.Writer`
+func (w *Writer) Write(p []byte) (int, error) {
+ c, l, ln := cap(w.buf), len(w.buf), len(p)
+ avail := c - l
+
+ // requires flush
+ if avail < ln {
+ if err := w.Flush(); err != nil {
+ return 0, err
+ }
+ l = len(w.buf)
+ }
+ // too big to fit in buffer;
+ // write directly to w.w
+ if c < ln {
+ return w.w.Write(p)
+ }
+
+ // grow buf slice; copy; return
+ w.buf = w.buf[:l+ln]
+ return copy(w.buf[l:], p), nil
+}
+
+// WriteString is analogous to Write, but it takes a string.
+func (w *Writer) WriteString(s string) (int, error) {
+ c, l, ln := cap(w.buf), len(w.buf), len(s)
+ avail := c - l
+
+ // requires flush
+ if avail < ln {
+ if err := w.Flush(); err != nil {
+ return 0, err
+ }
+ l = len(w.buf)
+ }
+ // too big to fit in buffer;
+ // write directly to w.w
+ //
+ // yes, this is unsafe. *but*
+ // io.Writer is not allowed
+ // to mutate its input or
+ // maintain a reference to it,
+ // per the spec in package io.
+ //
+ // plus, if the string is really
+ // too big to fit in the buffer, then
+ // creating a copy to write it is
+ // expensive (and, strictly speaking,
+ // unnecessary)
+ if c < ln {
+ return w.w.Write(unsafestr(s))
+ }
+
+ // grow buf slice; copy; return
+ w.buf = w.buf[:l+ln]
+ return copy(w.buf[l:], s), nil
+}
+
+// WriteByte implements `io.ByteWriter`
+func (w *Writer) WriteByte(b byte) error {
+ if len(w.buf) == cap(w.buf) {
+ if err := w.Flush(); err != nil {
+ return err
+ }
+ }
+ w.buf = append(w.buf, b)
+ return nil
+}
+
+// Next returns the next 'n' free bytes
+// in the write buffer, flushing the writer
+// as necessary. Next will return `io.ErrShortBuffer`
+// if 'n' is greater than the size of the write buffer.
+// Calls to 'next' increment the write position by
+// the size of the returned buffer.
+func (w *Writer) Next(n int) ([]byte, error) {
+ c, l := cap(w.buf), len(w.buf)
+ if n > c {
+ return nil, io.ErrShortBuffer
+ }
+ avail := c - l
+ if avail < n {
+ if err := w.Flush(); err != nil {
+ return nil, err
+ }
+ l = len(w.buf)
+ }
+ w.buf = w.buf[:l+n]
+ return w.buf[l:], nil
+}
+
+// take the bytes from w.buf[n:len(w.buf)]
+// and put them at the beginning of w.buf,
+// and resize to the length of the copied segment.
+func (w *Writer) pushback(n int) {
+ w.buf = w.buf[:copy(w.buf, w.buf[n:])]
+}
+
+// ReadFrom implements `io.ReaderFrom`
+func (w *Writer) ReadFrom(r io.Reader) (int64, error) {
+ // anticipatory flush
+ if err := w.Flush(); err != nil {
+ return 0, err
+ }
+
+ w.buf = w.buf[0:cap(w.buf)] // expand buffer
+
+ var nn int64 // written
+ var err error // error
+ var x int // read
+
+ // 1:1 reads and writes
+ for err == nil {
+ x, err = r.Read(w.buf)
+ if x > 0 {
+ n, werr := w.w.Write(w.buf[:x])
+ nn += int64(n)
+
+ if err != nil {
+ if n < x && n > 0 {
+ w.pushback(n - x)
+ }
+ return nn, werr
+ }
+ if n < x {
+ w.pushback(n - x)
+ return nn, io.ErrShortWrite
+ }
+ } else if err == nil {
+ err = io.ErrNoProgress
+ break
+ }
+ }
+ if err != io.EOF {
+ return nn, err
+ }
+
+ // we only clear here
+ // because we are sure
+ // the writes have
+ // succeeded. otherwise,
+ // we retain the data in case
+ // future writes succeed.
+ w.buf = w.buf[0:0]
+
+ return nn, nil
+}
diff --git a/vendor/github.com/philhofer/fwd/writer_appengine.go b/vendor/github.com/philhofer/fwd/writer_appengine.go
new file mode 100644
index 0000000..e367f39
--- /dev/null
+++ b/vendor/github.com/philhofer/fwd/writer_appengine.go
@@ -0,0 +1,5 @@
+// +build appengine
+
+package fwd
+
+func unsafestr(s string) []byte { return []byte(s) }
diff --git a/vendor/github.com/philhofer/fwd/writer_unsafe.go b/vendor/github.com/philhofer/fwd/writer_unsafe.go
new file mode 100644
index 0000000..a0bf453
--- /dev/null
+++ b/vendor/github.com/philhofer/fwd/writer_unsafe.go
@@ -0,0 +1,18 @@
+// +build !appengine
+
+package fwd
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+// unsafe cast string as []byte
+func unsafestr(b string) []byte {
+ l := len(b)
+ return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
+ Len: l,
+ Cap: l,
+ Data: (*reflect.StringHeader)(unsafe.Pointer(&b)).Data,
+ }))
+}
diff --git a/vendor/github.com/pivotal-golang/clock/LICENSE b/vendor/github.com/pivotal-golang/clock/LICENSE
new file mode 100644
index 0000000..e06d208
--- /dev/null
+++ b/vendor/github.com/pivotal-golang/clock/LICENSE
@@ -0,0 +1,202 @@
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/vendor/github.com/pivotal-golang/clock/README.md b/vendor/github.com/pivotal-golang/clock/README.md
new file mode 100644
index 0000000..9741b8b
--- /dev/null
+++ b/vendor/github.com/pivotal-golang/clock/README.md
@@ -0,0 +1 @@
+Provides a `Clock` interface, useful for injecting time dependencies in tests.
diff --git a/vendor/github.com/pivotal-golang/clock/clock.go b/vendor/github.com/pivotal-golang/clock/clock.go
new file mode 100644
index 0000000..9c7322c
--- /dev/null
+++ b/vendor/github.com/pivotal-golang/clock/clock.go
@@ -0,0 +1,42 @@
+package clock
+
+import "time"
+
+type Clock interface {
+ Now() time.Time
+ Sleep(d time.Duration)
+ Since(t time.Time) time.Duration
+
+ NewTimer(d time.Duration) Timer
+ NewTicker(d time.Duration) Ticker
+}
+
+type realClock struct{}
+
+func NewClock() Clock {
+ return &realClock{}
+}
+
+func (clock *realClock) Now() time.Time {
+ return time.Now()
+}
+
+func (clock *realClock) Since(t time.Time) time.Duration {
+ return time.Now().Sub(t)
+}
+
+func (clock *realClock) Sleep(d time.Duration) {
+ <-clock.NewTimer(d).C()
+}
+
+func (clock *realClock) NewTimer(d time.Duration) Timer {
+ return &realTimer{
+ t: time.NewTimer(d),
+ }
+}
+
+func (clock *realClock) NewTicker(d time.Duration) Ticker {
+ return &realTicker{
+ t: time.NewTicker(d),
+ }
+}
diff --git a/vendor/github.com/pivotal-golang/clock/ticker.go b/vendor/github.com/pivotal-golang/clock/ticker.go
new file mode 100644
index 0000000..f25129e
--- /dev/null
+++ b/vendor/github.com/pivotal-golang/clock/ticker.go
@@ -0,0 +1,20 @@
+package clock
+
+import "time"
+
+type Ticker interface {
+ C() <-chan time.Time
+ Stop()
+}
+
+type realTicker struct {
+ t *time.Ticker
+}
+
+func (t *realTicker) C() <-chan time.Time {
+ return t.t.C
+}
+
+func (t *realTicker) Stop() {
+ t.t.Stop()
+}
diff --git a/vendor/github.com/pivotal-golang/clock/timer.go b/vendor/github.com/pivotal-golang/clock/timer.go
new file mode 100644
index 0000000..cf8c221
--- /dev/null
+++ b/vendor/github.com/pivotal-golang/clock/timer.go
@@ -0,0 +1,25 @@
+package clock
+
+import "time"
+
+type Timer interface {
+ C() <-chan time.Time
+ Reset(d time.Duration) bool
+ Stop() bool
+}
+
+type realTimer struct {
+ t *time.Timer
+}
+
+func (t *realTimer) C() <-chan time.Time {
+ return t.t.C
+}
+
+func (t *realTimer) Reset(d time.Duration) bool {
+ return t.t.Reset(d)
+}
+
+func (t *realTimer) Stop() bool {
+ return t.t.Stop()
+}
diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE
new file mode 100644
index 0000000..835ba3e
--- /dev/null
+++ b/vendor/github.com/pkg/errors/LICENSE
@@ -0,0 +1,23 @@
+Copyright (c) 2015, Dave Cheney <dave@cheney.net>
+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
new file mode 100644
index 0000000..273db3c
--- /dev/null
+++ b/vendor/github.com/pkg/errors/README.md
@@ -0,0 +1,52 @@
+# 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/errors.go b/vendor/github.com/pkg/errors/errors.go
new file mode 100644
index 0000000..842ee80
--- /dev/null
+++ b/vendor/github.com/pkg/errors/errors.go
@@ -0,0 +1,269 @@
+// 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
new file mode 100644
index 0000000..6b1f289
--- /dev/null
+++ b/vendor/github.com/pkg/errors/stack.go
@@ -0,0 +1,178 @@
+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/pmezard/go-difflib/LICENSE b/vendor/github.com/pmezard/go-difflib/LICENSE
new file mode 100644
index 0000000..c67dad6
--- /dev/null
+++ b/vendor/github.com/pmezard/go-difflib/LICENSE
@@ -0,0 +1,27 @@
+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/README.md b/vendor/github.com/pmezard/go-difflib/README.md
new file mode 100644
index 0000000..e87f307
--- /dev/null
+++ b/vendor/github.com/pmezard/go-difflib/README.md
@@ -0,0 +1,50 @@
+go-difflib
+==========
+
+[![Build Status](https://travis-ci.org/pmezard/go-difflib.png?branch=master)](https://travis-ci.org/pmezard/go-difflib)
+[![GoDoc](https://godoc.org/github.com/pmezard/go-difflib/difflib?status.svg)](https://godoc.org/github.com/pmezard/go-difflib/difflib)
+
+Go-difflib is a partial port of python 3 difflib package. Its main goal
+was to make unified and context diff available in pure Go, mostly for
+testing purposes.
+
+The following class and functions (and related tests) have be ported:
+
+* `SequenceMatcher`
+* `unified_diff()`
+* `context_diff()`
+
+## Installation
+
+```bash
+$ go get github.com/pmezard/go-difflib/difflib
+```
+
+### Quick Start
+
+Diffs are configured with Unified (or ContextDiff) structures, and can
+be output to an io.Writer or returned as a string.
+
+```Go
+diff := UnifiedDiff{
+ A: difflib.SplitLines("foo\nbar\n"),
+ B: difflib.SplitLines("foo\nbaz\n"),
+ FromFile: "Original",
+ ToFile: "Current",
+ Context: 3,
+}
+text, _ := GetUnifiedDiffString(diff)
+fmt.Printf(text)
+```
+
+would output:
+
+```
+--- Original
++++ Current
+@@ -1,3 +1,3 @@
+ foo
+-bar
++baz
+```
+
diff --git a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go
new file mode 100644
index 0000000..003e99f
--- /dev/null
+++ b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go
@@ -0,0 +1,772 @@
+// 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 "<P>" lines in HTML files). That may be
+// because this is the only method of the 3 that has a *concept* of
+// "junk" <wink>.
+//
+// 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()
+ wf := func(format string, args ...interface{}) error {
+ _, err := buf.WriteString(fmt.Sprintf(format, args...))
+ return err
+ }
+ ws := func(s string) error {
+ _, err := buf.WriteString(s)
+ 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
+ }
+ if diff.FromFile != "" || diff.ToFile != "" {
+ err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
+ if err != nil {
+ return err
+ }
+ err = wf("+++ %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 := wf("@@ -%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 := ws(" " + line); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if c.Tag == 'r' || c.Tag == 'd' {
+ for _, line := range diff.A[i1:i2] {
+ if err := ws("-" + line); err != nil {
+ return err
+ }
+ }
+ }
+ if c.Tag == 'r' || c.Tag == 'i' {
+ for _, line := range diff.B[j1:j2] {
+ if err := ws("+" + 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
+ wf := func(format string, args ...interface{}) {
+ _, err := buf.WriteString(fmt.Sprintf(format, args...))
+ if diffErr == nil && err != nil {
+ diffErr = err
+ }
+ }
+ ws := func(s string) {
+ _, err := buf.WriteString(s)
+ 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
+ }
+ if diff.FromFile != "" || diff.ToFile != "" {
+ wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol)
+ wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol)
+ }
+ }
+
+ first, last := g[0], g[len(g)-1]
+ ws("***************" + diff.Eol)
+
+ range1 := formatRangeContext(first.I1, last.I2)
+ wf("*** %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] {
+ ws(prefix[cc.Tag] + line)
+ }
+ }
+ break
+ }
+ }
+
+ range2 := formatRangeContext(first.J1, last.J2)
+ wf("--- %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] {
+ ws(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/prometheus/client_golang/LICENSE b/vendor/github.com/prometheus/client_golang/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/prometheus/client_golang/NOTICE b/vendor/github.com/prometheus/client_golang/NOTICE
new file mode 100644
index 0000000..37e4a7d
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/NOTICE
@@ -0,0 +1,28 @@
+Prometheus instrumentation library for Go applications
+Copyright 2012-2015 The Prometheus Authors
+
+This product includes software developed at
+SoundCloud Ltd. (http://soundcloud.com/).
+
+
+The following components are included in this product:
+
+goautoneg
+http://bitbucket.org/ww/goautoneg
+Copyright 2011, Open Knowledge Foundation Ltd.
+See README.txt for license details.
+
+perks - a fork of https://github.com/bmizerany/perks
+https://github.com/beorn7/perks
+Copyright 2013-2015 Blake Mizerany, Björn Rabenstein
+See https://github.com/beorn7/perks/blob/master/README.md for license details.
+
+Go support for Protocol Buffers - Google's data interchange format
+http://github.com/golang/protobuf/
+Copyright 2010 The Go Authors
+See source code for license details.
+
+Support for streaming Protocol Buffer messages for the Go language (golang).
+https://github.com/matttproud/golang_protobuf_extensions
+Copyright 2013 Matt T. Proud
+Licensed under the Apache License, Version 2.0
diff --git a/vendor/github.com/prometheus/client_golang/README.md b/vendor/github.com/prometheus/client_golang/README.md
new file mode 100644
index 0000000..557eacf
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/README.md
@@ -0,0 +1,45 @@
+# Prometheus Go client library
+
+[![Build Status](https://travis-ci.org/prometheus/client_golang.svg?branch=master)](https://travis-ci.org/prometheus/client_golang)
+
+This is the [Go](http://golang.org) client library for
+[Prometheus](http://prometheus.io). It has two separate parts, one for
+instrumenting application code, and one for creating clients that talk to the
+Prometheus HTTP API.
+
+## Instrumenting applications
+
+[![code-coverage](http://gocover.io/_badge/github.com/prometheus/client_golang/prometheus)](http://gocover.io/github.com/prometheus/client_golang/prometheus) [![go-doc](https://godoc.org/github.com/prometheus/client_golang/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/prometheus)
+
+The
+[`prometheus` directory](https://github.com/prometheus/client_golang/tree/master/prometheus)
+contains the instrumentation library. See the
+[best practices section](http://prometheus.io/docs/practices/naming/) of the
+Prometheus documentation to learn more about instrumenting applications.
+
+The
+[`examples` directory](https://github.com/prometheus/client_golang/tree/master/examples)
+contains simple examples of instrumented code.
+
+## Client for the Prometheus HTTP API
+
+[![code-coverage](http://gocover.io/_badge/github.com/prometheus/client_golang/api/prometheus)](http://gocover.io/github.com/prometheus/client_golang/api/prometheus) [![go-doc](https://godoc.org/github.com/prometheus/client_golang/api/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/api/prometheus)
+
+The
+[`api/prometheus` directory](https://github.com/prometheus/client_golang/tree/master/api/prometheus)
+contains the client for the
+[Prometheus HTTP API](http://prometheus.io/docs/querying/api/). It allows you
+to write Go applications that query time series data from a Prometheus server.
+
+## Where is `model`, `extraction`, and `text`?
+
+The `model` packages has been moved to
+[`prometheus/common/model`](https://github.com/prometheus/common/tree/master/model).
+
+The `extraction` and `text` packages are now contained in
+[`prometheus/common/expfmt`](https://github.com/prometheus/common/tree/master/expfmt).
+
+## Contributing and community
+
+See the [contributing guidelines](CONTRIBUTING.md) and the
+[Community section](http://prometheus.io/community/) of the homepage.
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/README.md b/vendor/github.com/prometheus/client_golang/prometheus/README.md
new file mode 100644
index 0000000..81032be
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/README.md
@@ -0,0 +1,53 @@
+# Overview
+This is the [Prometheus](http://www.prometheus.io) telemetric
+instrumentation client [Go](http://golang.org) client library. It
+enable authors to define process-space metrics for their servers and
+expose them through a web service interface for extraction,
+aggregation, and a whole slew of other post processing techniques.
+
+# Installing
+ $ go get github.com/prometheus/client_golang/prometheus
+
+# Example
+```go
+package main
+
+import (
+ "net/http"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+var (
+ indexed = prometheus.NewCounter(prometheus.CounterOpts{
+ Namespace: "my_company",
+ Subsystem: "indexer",
+ Name: "documents_indexed",
+ Help: "The number of documents indexed.",
+ })
+ size = prometheus.NewGauge(prometheus.GaugeOpts{
+ Namespace: "my_company",
+ Subsystem: "storage",
+ Name: "documents_total_size_bytes",
+ Help: "The total size of all documents in the storage.",
+ })
+)
+
+func main() {
+ http.Handle("/metrics", prometheus.Handler())
+
+ indexed.Inc()
+ size.Set(5)
+
+ http.ListenAndServe(":8080", nil)
+}
+
+func init() {
+ prometheus.MustRegister(indexed)
+ prometheus.MustRegister(size)
+}
+```
+
+# Documentation
+
+[![GoDoc](https://godoc.org/github.com/prometheus/client_golang?status.png)](https://godoc.org/github.com/prometheus/client_golang)
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collector.go b/vendor/github.com/prometheus/client_golang/prometheus/collector.go
new file mode 100644
index 0000000..c046880
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/collector.go
@@ -0,0 +1,75 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+// Collector is the interface implemented by anything that can be used by
+// Prometheus to collect metrics. A Collector has to be registered for
+// collection. See Register, MustRegister, RegisterOrGet, and MustRegisterOrGet.
+//
+// The stock metrics provided by this package (like Gauge, Counter, Summary) are
+// also Collectors (which only ever collect one metric, namely itself). An
+// implementer of Collector may, however, collect multiple metrics in a
+// coordinated fashion and/or create metrics on the fly. Examples for collectors
+// already implemented in this library are the metric vectors (i.e. collection
+// of multiple instances of the same Metric but with different label values)
+// like GaugeVec or SummaryVec, and the ExpvarCollector.
+type Collector interface {
+ // Describe sends the super-set of all possible descriptors of metrics
+ // collected by this Collector to the provided channel and returns once
+ // the last descriptor has been sent. The sent descriptors fulfill the
+ // consistency and uniqueness requirements described in the Desc
+ // documentation. (It is valid if one and the same Collector sends
+ // duplicate descriptors. Those duplicates are simply ignored. However,
+ // two different Collectors must not send duplicate descriptors.) This
+ // method idempotently sends the same descriptors throughout the
+ // lifetime of the Collector. If a Collector encounters an error while
+ // executing this method, it must send an invalid descriptor (created
+ // with NewInvalidDesc) to signal the error to the registry.
+ Describe(chan<- *Desc)
+ // Collect is called by Prometheus when collecting metrics. The
+ // implementation sends each collected metric via the provided channel
+ // and returns once the last metric has been sent. The descriptor of
+ // each sent metric is one of those returned by Describe. Returned
+ // metrics that share the same descriptor must differ in their variable
+ // label values. This method may be called concurrently and must
+ // therefore be implemented in a concurrency safe way. Blocking occurs
+ // at the expense of total performance of rendering all registered
+ // metrics. Ideally, Collector implementations support concurrent
+ // readers.
+ Collect(chan<- Metric)
+}
+
+// SelfCollector implements Collector for a single Metric so that that the
+// Metric collects itself. Add it as an anonymous field to a struct that
+// implements Metric, and call Init with the Metric itself as an argument.
+type SelfCollector struct {
+ self Metric
+}
+
+// Init provides the SelfCollector with a reference to the metric it is supposed
+// to collect. It is usually called within the factory function to create a
+// metric. See example.
+func (c *SelfCollector) Init(self Metric) {
+ c.self = self
+}
+
+// Describe implements Collector.
+func (c *SelfCollector) Describe(ch chan<- *Desc) {
+ ch <- c.self.Desc()
+}
+
+// Collect implements Collector.
+func (c *SelfCollector) Collect(ch chan<- Metric) {
+ ch <- c.self
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter.go b/vendor/github.com/prometheus/client_golang/prometheus/counter.go
new file mode 100644
index 0000000..d2a564b
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/counter.go
@@ -0,0 +1,173 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+ "errors"
+)
+
+// Counter is a Metric that represents a single numerical value that only ever
+// goes up. That implies that it cannot be used to count items whose number can
+// also go down, e.g. the number of currently running goroutines. Those
+// "counters" are represented by Gauges.
+//
+// A Counter is typically used to count requests served, tasks completed, errors
+// occurred, etc.
+//
+// To create Counter instances, use NewCounter.
+type Counter interface {
+ Metric
+ Collector
+
+ // Set is used to set the Counter to an arbitrary value. It is only used
+ // if you have to transfer a value from an external counter into this
+ // Prometheus metric. Do not use it for regular handling of a
+ // Prometheus counter (as it can be used to break the contract of
+ // monotonically increasing values).
+ Set(float64)
+ // Inc increments the counter by 1.
+ Inc()
+ // Add adds the given value to the counter. It panics if the value is <
+ // 0.
+ Add(float64)
+}
+
+// CounterOpts is an alias for Opts. See there for doc comments.
+type CounterOpts Opts
+
+// NewCounter creates a new Counter based on the provided CounterOpts.
+func NewCounter(opts CounterOpts) Counter {
+ desc := NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ nil,
+ opts.ConstLabels,
+ )
+ result := &counter{value: value{desc: desc, valType: CounterValue, labelPairs: desc.constLabelPairs}}
+ result.Init(result) // Init self-collection.
+ return result
+}
+
+type counter struct {
+ value
+}
+
+func (c *counter) Add(v float64) {
+ if v < 0 {
+ panic(errors.New("counter cannot decrease in value"))
+ }
+ c.value.Add(v)
+}
+
+// CounterVec is a Collector that bundles a set of Counters that all share the
+// same Desc, but have different values for their variable labels. This is used
+// if you want to count the same thing partitioned by various dimensions
+// (e.g. number of HTTP requests, partitioned by response code and
+// method). Create instances with NewCounterVec.
+//
+// CounterVec embeds MetricVec. See there for a full list of methods with
+// detailed documentation.
+type CounterVec struct {
+ MetricVec
+}
+
+// NewCounterVec creates a new CounterVec based on the provided CounterOpts and
+// partitioned by the given label names. At least one label name must be
+// provided.
+func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec {
+ desc := NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ labelNames,
+ opts.ConstLabels,
+ )
+ return &CounterVec{
+ MetricVec: MetricVec{
+ children: map[uint64]Metric{},
+ desc: desc,
+ newMetric: func(lvs ...string) Metric {
+ result := &counter{value: value{
+ desc: desc,
+ valType: CounterValue,
+ labelPairs: makeLabelPairs(desc, lvs),
+ }}
+ result.Init(result) // Init self-collection.
+ return result
+ },
+ },
+ }
+}
+
+// GetMetricWithLabelValues replaces the method of the same name in
+// MetricVec. The difference is that this method returns a Counter and not a
+// Metric so that no type conversion is required.
+func (m *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error) {
+ metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...)
+ if metric != nil {
+ return metric.(Counter), err
+ }
+ return nil, err
+}
+
+// GetMetricWith replaces the method of the same name in MetricVec. The
+// difference is that this method returns a Counter and not a Metric so that no
+// type conversion is required.
+func (m *CounterVec) GetMetricWith(labels Labels) (Counter, error) {
+ metric, err := m.MetricVec.GetMetricWith(labels)
+ if metric != nil {
+ return metric.(Counter), err
+ }
+ return nil, err
+}
+
+// WithLabelValues works as GetMetricWithLabelValues, but panics where
+// GetMetricWithLabelValues would have returned an error. By not returning an
+// error, WithLabelValues allows shortcuts like
+// myVec.WithLabelValues("404", "GET").Add(42)
+func (m *CounterVec) WithLabelValues(lvs ...string) Counter {
+ return m.MetricVec.WithLabelValues(lvs...).(Counter)
+}
+
+// With works as GetMetricWith, but panics where GetMetricWithLabels would have
+// returned an error. By not returning an error, With allows shortcuts like
+// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
+func (m *CounterVec) With(labels Labels) Counter {
+ return m.MetricVec.With(labels).(Counter)
+}
+
+// CounterFunc is a Counter whose value is determined at collect time by calling a
+// provided function.
+//
+// To create CounterFunc instances, use NewCounterFunc.
+type CounterFunc interface {
+ Metric
+ Collector
+}
+
+// NewCounterFunc creates a new CounterFunc based on the provided
+// CounterOpts. The value reported is determined by calling the given function
+// from within the Write method. Take into account that metric collection may
+// happen concurrently. If that results in concurrent calls to Write, like in
+// the case where a CounterFunc is directly registered with Prometheus, the
+// provided function must be concurrency-safe. The function should also honor
+// the contract for a Counter (values only go up, not down), but compliance will
+// not be checked.
+func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc {
+ return newValueFunc(NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ nil,
+ opts.ConstLabels,
+ ), CounterValue, function)
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/desc.go b/vendor/github.com/prometheus/client_golang/prometheus/desc.go
new file mode 100644
index 0000000..ee02d9b
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/desc.go
@@ -0,0 +1,192 @@
+package prometheus
+
+import (
+ "errors"
+ "fmt"
+ "regexp"
+ "sort"
+ "strings"
+
+ "github.com/golang/protobuf/proto"
+
+ dto "github.com/prometheus/client_model/go"
+)
+
+var (
+ metricNameRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_:]*$`)
+ labelNameRE = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
+)
+
+// reservedLabelPrefix is a prefix which is not legal in user-supplied
+// label names.
+const reservedLabelPrefix = "__"
+
+// Labels represents a collection of label name -> value mappings. This type is
+// commonly used with the With(Labels) and GetMetricWith(Labels) methods of
+// metric vector Collectors, e.g.:
+// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
+//
+// The other use-case is the specification of constant label pairs in Opts or to
+// create a Desc.
+type Labels map[string]string
+
+// Desc is the descriptor used by every Prometheus Metric. It is essentially
+// the immutable meta-data of a Metric. The normal Metric implementations
+// included in this package manage their Desc under the hood. Users only have to
+// deal with Desc if they use advanced features like the ExpvarCollector or
+// custom Collectors and Metrics.
+//
+// Descriptors registered with the same registry have to fulfill certain
+// consistency and uniqueness criteria if they share the same fully-qualified
+// name: They must have the same help string and the same label names (aka label
+// dimensions) in each, constLabels and variableLabels, but they must differ in
+// the values of the constLabels.
+//
+// Descriptors that share the same fully-qualified names and the same label
+// values of their constLabels are considered equal.
+//
+// Use NewDesc to create new Desc instances.
+type Desc struct {
+ // fqName has been built from Namespace, Subsystem, and Name.
+ fqName string
+ // help provides some helpful information about this metric.
+ help string
+ // constLabelPairs contains precalculated DTO label pairs based on
+ // the constant labels.
+ constLabelPairs []*dto.LabelPair
+ // VariableLabels contains names of labels for which the metric
+ // maintains variable values.
+ variableLabels []string
+ // id is a hash of the values of the ConstLabels and fqName. This
+ // must be unique among all registered descriptors and can therefore be
+ // used as an identifier of the descriptor.
+ id uint64
+ // dimHash is a hash of the label names (preset and variable) and the
+ // Help string. Each Desc with the same fqName must have the same
+ // dimHash.
+ dimHash uint64
+ // err is an error that occured during construction. It is reported on
+ // registration time.
+ err error
+}
+
+// NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc
+// and will be reported on registration time. variableLabels and constLabels can
+// be nil if no such labels should be set. fqName and help must not be empty.
+//
+// variableLabels only contain the label names. Their label values are variable
+// and therefore not part of the Desc. (They are managed within the Metric.)
+//
+// For constLabels, the label values are constant. Therefore, they are fully
+// specified in the Desc. See the Opts documentation for the implications of
+// constant labels.
+func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc {
+ d := &Desc{
+ fqName: fqName,
+ help: help,
+ variableLabels: variableLabels,
+ }
+ if help == "" {
+ d.err = errors.New("empty help string")
+ return d
+ }
+ if !metricNameRE.MatchString(fqName) {
+ d.err = fmt.Errorf("%q is not a valid metric name", fqName)
+ return d
+ }
+ // labelValues contains the label values of const labels (in order of
+ // their sorted label names) plus the fqName (at position 0).
+ labelValues := make([]string, 1, len(constLabels)+1)
+ labelValues[0] = fqName
+ labelNames := make([]string, 0, len(constLabels)+len(variableLabels))
+ labelNameSet := map[string]struct{}{}
+ // First add only the const label names and sort them...
+ for labelName := range constLabels {
+ if !checkLabelName(labelName) {
+ d.err = fmt.Errorf("%q is not a valid label name", labelName)
+ return d
+ }
+ labelNames = append(labelNames, labelName)
+ labelNameSet[labelName] = struct{}{}
+ }
+ sort.Strings(labelNames)
+ // ... so that we can now add const label values in the order of their names.
+ for _, labelName := range labelNames {
+ labelValues = append(labelValues, constLabels[labelName])
+ }
+ // Now add the variable label names, but prefix them with something that
+ // cannot be in a regular label name. That prevents matching the label
+ // dimension with a different mix between preset and variable labels.
+ for _, labelName := range variableLabels {
+ if !checkLabelName(labelName) {
+ d.err = fmt.Errorf("%q is not a valid label name", labelName)
+ return d
+ }
+ labelNames = append(labelNames, "$"+labelName)
+ labelNameSet[labelName] = struct{}{}
+ }
+ if len(labelNames) != len(labelNameSet) {
+ d.err = errors.New("duplicate label names")
+ return d
+ }
+ vh := hashNew()
+ for _, val := range labelValues {
+ vh = hashAdd(vh, val)
+ vh = hashAddByte(vh, separatorByte)
+ }
+ d.id = vh
+ // Sort labelNames so that order doesn't matter for the hash.
+ sort.Strings(labelNames)
+ // Now hash together (in this order) the help string and the sorted
+ // label names.
+ lh := hashNew()
+ lh = hashAdd(lh, help)
+ lh = hashAddByte(lh, separatorByte)
+ for _, labelName := range labelNames {
+ lh = hashAdd(lh, labelName)
+ lh = hashAddByte(lh, separatorByte)
+ }
+ d.dimHash = lh
+
+ d.constLabelPairs = make([]*dto.LabelPair, 0, len(constLabels))
+ for n, v := range constLabels {
+ d.constLabelPairs = append(d.constLabelPairs, &dto.LabelPair{
+ Name: proto.String(n),
+ Value: proto.String(v),
+ })
+ }
+ sort.Sort(LabelPairSorter(d.constLabelPairs))
+ return d
+}
+
+// NewInvalidDesc returns an invalid descriptor, i.e. a descriptor with the
+// provided error set. If a collector returning such a descriptor is registered,
+// registration will fail with the provided error. NewInvalidDesc can be used by
+// a Collector to signal inability to describe itself.
+func NewInvalidDesc(err error) *Desc {
+ return &Desc{
+ err: err,
+ }
+}
+
+func (d *Desc) String() string {
+ lpStrings := make([]string, 0, len(d.constLabelPairs))
+ for _, lp := range d.constLabelPairs {
+ lpStrings = append(
+ lpStrings,
+ fmt.Sprintf("%s=%q", lp.GetName(), lp.GetValue()),
+ )
+ }
+ return fmt.Sprintf(
+ "Desc{fqName: %q, help: %q, constLabels: {%s}, variableLabels: %v}",
+ d.fqName,
+ d.help,
+ strings.Join(lpStrings, ","),
+ d.variableLabels,
+ )
+}
+
+func checkLabelName(l string) bool {
+ return labelNameRE.MatchString(l) &&
+ !strings.HasPrefix(l, reservedLabelPrefix)
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/doc.go b/vendor/github.com/prometheus/client_golang/prometheus/doc.go
new file mode 100644
index 0000000..ca56f5e
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/doc.go
@@ -0,0 +1,111 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package prometheus provides embeddable metric primitives for servers and
+// standardized exposition of telemetry through a web services interface.
+//
+// All exported functions and methods are safe to be used concurrently unless
+// specified otherwise.
+//
+// To expose metrics registered with the Prometheus registry, an HTTP server
+// needs to know about the Prometheus handler. The usual endpoint is "/metrics".
+//
+// http.Handle("/metrics", prometheus.Handler())
+//
+// As a starting point a very basic usage example:
+//
+// package main
+//
+// import (
+// "net/http"
+//
+// "github.com/prometheus/client_golang/prometheus"
+// )
+//
+// var (
+// cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
+// Name: "cpu_temperature_celsius",
+// Help: "Current temperature of the CPU.",
+// })
+// hdFailures = prometheus.NewCounter(prometheus.CounterOpts{
+// Name: "hd_errors_total",
+// Help: "Number of hard-disk errors.",
+// })
+// )
+//
+// func init() {
+// prometheus.MustRegister(cpuTemp)
+// prometheus.MustRegister(hdFailures)
+// }
+//
+// func main() {
+// cpuTemp.Set(65.3)
+// hdFailures.Inc()
+//
+// http.Handle("/metrics", prometheus.Handler())
+// http.ListenAndServe(":8080", nil)
+// }
+//
+//
+// This is a complete program that exports two metrics, a Gauge and a Counter.
+// It also exports some stats about the HTTP usage of the /metrics
+// endpoint. (See the Handler function for more detail.)
+//
+// Two more advanced metric types are the Summary and Histogram. A more
+// thorough description of metric types can be found in the prometheus docs:
+// https://prometheus.io/docs/concepts/metric_types/
+//
+// In addition to the fundamental metric types Gauge, Counter, Summary, and
+// Histogram, a very important part of the Prometheus data model is the
+// partitioning of samples along dimensions called labels, which results in
+// metric vectors. The fundamental types are GaugeVec, CounterVec, SummaryVec,
+// and HistogramVec.
+//
+// Those are all the parts needed for basic usage. Detailed documentation and
+// examples are provided below.
+//
+// Everything else this package offers is essentially for "power users" only. A
+// few pointers to "power user features":
+//
+// All the various ...Opts structs have a ConstLabels field for labels that
+// never change their value (which is only useful under special circumstances,
+// see documentation of the Opts type).
+//
+// The Untyped metric behaves like a Gauge, but signals the Prometheus server
+// not to assume anything about its type.
+//
+// Functions to fine-tune how the metric registry works: EnableCollectChecks,
+// PanicOnCollectError, Register, Unregister, SetMetricFamilyInjectionHook.
+//
+// For custom metric collection, there are two entry points: Custom Metric
+// implementations and custom Collector implementations. A Metric is the
+// fundamental unit in the Prometheus data model: a sample at a point in time
+// together with its meta-data (like its fully-qualified name and any number of
+// pairs of label name and label value) that knows how to marshal itself into a
+// data transfer object (aka DTO, implemented as a protocol buffer). A Collector
+// gets registered with the Prometheus registry and manages the collection of
+// one or more Metrics. Many parts of this package are building blocks for
+// Metrics and Collectors. Desc is the metric descriptor, actually used by all
+// metrics under the hood, and by Collectors to describe the Metrics to be
+// collected, but only to be dealt with by users if they implement their own
+// Metrics or Collectors. To create a Desc, the BuildFQName function will come
+// in handy. Other useful components for Metric and Collector implementation
+// include: LabelPairSorter to sort the DTO version of label pairs,
+// NewConstMetric and MustNewConstMetric to create "throw away" Metrics at
+// collection time, MetricVec to bundle custom Metrics into a metric vector
+// Collector, SelfCollector to make a custom Metric collect itself.
+//
+// A good example for a custom Collector is the ExpVarCollector included in this
+// package, which exports variables exported via the "expvar" package as
+// Prometheus metrics.
+package prometheus
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/expvar.go b/vendor/github.com/prometheus/client_golang/prometheus/expvar.go
new file mode 100644
index 0000000..0f7630d
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/expvar.go
@@ -0,0 +1,119 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+ "encoding/json"
+ "expvar"
+)
+
+// ExpvarCollector collects metrics from the expvar interface. It provides a
+// quick way to expose numeric values that are already exported via expvar as
+// Prometheus metrics. Note that the data models of expvar and Prometheus are
+// fundamentally different, and that the ExpvarCollector is inherently
+// slow. Thus, the ExpvarCollector is probably great for experiments and
+// prototying, but you should seriously consider a more direct implementation of
+// Prometheus metrics for monitoring production systems.
+//
+// Use NewExpvarCollector to create new instances.
+type ExpvarCollector struct {
+ exports map[string]*Desc
+}
+
+// NewExpvarCollector returns a newly allocated ExpvarCollector that still has
+// to be registered with the Prometheus registry.
+//
+// The exports map has the following meaning:
+//
+// The keys in the map correspond to expvar keys, i.e. for every expvar key you
+// want to export as Prometheus metric, you need an entry in the exports
+// map. The descriptor mapped to each key describes how to export the expvar
+// value. It defines the name and the help string of the Prometheus metric
+// proxying the expvar value. The type will always be Untyped.
+//
+// For descriptors without variable labels, the expvar value must be a number or
+// a bool. The number is then directly exported as the Prometheus sample
+// value. (For a bool, 'false' translates to 0 and 'true' to 1). Expvar values
+// that are not numbers or bools are silently ignored.
+//
+// If the descriptor has one variable label, the expvar value must be an expvar
+// map. The keys in the expvar map become the various values of the one
+// Prometheus label. The values in the expvar map must be numbers or bools again
+// as above.
+//
+// For descriptors with more than one variable label, the expvar must be a
+// nested expvar map, i.e. where the values of the topmost map are maps again
+// etc. until a depth is reached that corresponds to the number of labels. The
+// leaves of that structure must be numbers or bools as above to serve as the
+// sample values.
+//
+// Anything that does not fit into the scheme above is silently ignored.
+func NewExpvarCollector(exports map[string]*Desc) *ExpvarCollector {
+ return &ExpvarCollector{
+ exports: exports,
+ }
+}
+
+// Describe implements Collector.
+func (e *ExpvarCollector) Describe(ch chan<- *Desc) {
+ for _, desc := range e.exports {
+ ch <- desc
+ }
+}
+
+// Collect implements Collector.
+func (e *ExpvarCollector) Collect(ch chan<- Metric) {
+ for name, desc := range e.exports {
+ var m Metric
+ expVar := expvar.Get(name)
+ if expVar == nil {
+ continue
+ }
+ var v interface{}
+ labels := make([]string, len(desc.variableLabels))
+ if err := json.Unmarshal([]byte(expVar.String()), &v); err != nil {
+ ch <- NewInvalidMetric(desc, err)
+ continue
+ }
+ var processValue func(v interface{}, i int)
+ processValue = func(v interface{}, i int) {
+ if i >= len(labels) {
+ copiedLabels := append(make([]string, 0, len(labels)), labels...)
+ switch v := v.(type) {
+ case float64:
+ m = MustNewConstMetric(desc, UntypedValue, v, copiedLabels...)
+ case bool:
+ if v {
+ m = MustNewConstMetric(desc, UntypedValue, 1, copiedLabels...)
+ } else {
+ m = MustNewConstMetric(desc, UntypedValue, 0, copiedLabels...)
+ }
+ default:
+ return
+ }
+ ch <- m
+ return
+ }
+ vm, ok := v.(map[string]interface{})
+ if !ok {
+ return
+ }
+ for lv, val := range vm {
+ labels[i] = lv
+ processValue(val, i+1)
+ }
+ }
+ processValue(v, 0)
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/fnv.go b/vendor/github.com/prometheus/client_golang/prometheus/fnv.go
new file mode 100644
index 0000000..e3b67df
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/fnv.go
@@ -0,0 +1,29 @@
+package prometheus
+
+// Inline and byte-free variant of hash/fnv's fnv64a.
+
+const (
+ offset64 = 14695981039346656037
+ prime64 = 1099511628211
+)
+
+// hashNew initializies a new fnv64a hash value.
+func hashNew() uint64 {
+ return offset64
+}
+
+// hashAdd adds a string to a fnv64a hash value, returning the updated hash.
+func hashAdd(h uint64, s string) uint64 {
+ for i := 0; i < len(s); i++ {
+ h ^= uint64(s[i])
+ h *= prime64
+ }
+ return h
+}
+
+// hashAddByte adds a byte to a fnv64a hash value, returning the updated hash.
+func hashAddByte(h uint64, b byte) uint64 {
+ h ^= uint64(b)
+ h *= prime64
+ return h
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
new file mode 100644
index 0000000..390c074
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
@@ -0,0 +1,144 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+// Gauge is a Metric that represents a single numerical value that can
+// arbitrarily go up and down.
+//
+// A Gauge is typically used for measured values like temperatures or current
+// memory usage, but also "counts" that can go up and down, like the number of
+// running goroutines.
+//
+// To create Gauge instances, use NewGauge.
+type Gauge interface {
+ Metric
+ Collector
+
+ // Set sets the Gauge to an arbitrary value.
+ Set(float64)
+ // Inc increments the Gauge by 1.
+ Inc()
+ // Dec decrements the Gauge by 1.
+ Dec()
+ // Add adds the given value to the Gauge. (The value can be
+ // negative, resulting in a decrease of the Gauge.)
+ Add(float64)
+ // Sub subtracts the given value from the Gauge. (The value can be
+ // negative, resulting in an increase of the Gauge.)
+ Sub(float64)
+}
+
+// GaugeOpts is an alias for Opts. See there for doc comments.
+type GaugeOpts Opts
+
+// NewGauge creates a new Gauge based on the provided GaugeOpts.
+func NewGauge(opts GaugeOpts) Gauge {
+ return newValue(NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ nil,
+ opts.ConstLabels,
+ ), GaugeValue, 0)
+}
+
+// GaugeVec is a Collector that bundles a set of Gauges that all share the same
+// Desc, but have different values for their variable labels. This is used if
+// you want to count the same thing partitioned by various dimensions
+// (e.g. number of operations queued, partitioned by user and operation
+// type). Create instances with NewGaugeVec.
+type GaugeVec struct {
+ MetricVec
+}
+
+// NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and
+// partitioned by the given label names. At least one label name must be
+// provided.
+func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec {
+ desc := NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ labelNames,
+ opts.ConstLabels,
+ )
+ return &GaugeVec{
+ MetricVec: MetricVec{
+ children: map[uint64]Metric{},
+ desc: desc,
+ newMetric: func(lvs ...string) Metric {
+ return newValue(desc, GaugeValue, 0, lvs...)
+ },
+ },
+ }
+}
+
+// GetMetricWithLabelValues replaces the method of the same name in
+// MetricVec. The difference is that this method returns a Gauge and not a
+// Metric so that no type conversion is required.
+func (m *GaugeVec) GetMetricWithLabelValues(lvs ...string) (Gauge, error) {
+ metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...)
+ if metric != nil {
+ return metric.(Gauge), err
+ }
+ return nil, err
+}
+
+// GetMetricWith replaces the method of the same name in MetricVec. The
+// difference is that this method returns a Gauge and not a Metric so that no
+// type conversion is required.
+func (m *GaugeVec) GetMetricWith(labels Labels) (Gauge, error) {
+ metric, err := m.MetricVec.GetMetricWith(labels)
+ if metric != nil {
+ return metric.(Gauge), err
+ }
+ return nil, err
+}
+
+// WithLabelValues works as GetMetricWithLabelValues, but panics where
+// GetMetricWithLabelValues would have returned an error. By not returning an
+// error, WithLabelValues allows shortcuts like
+// myVec.WithLabelValues("404", "GET").Add(42)
+func (m *GaugeVec) WithLabelValues(lvs ...string) Gauge {
+ return m.MetricVec.WithLabelValues(lvs...).(Gauge)
+}
+
+// With works as GetMetricWith, but panics where GetMetricWithLabels would have
+// returned an error. By not returning an error, With allows shortcuts like
+// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
+func (m *GaugeVec) With(labels Labels) Gauge {
+ return m.MetricVec.With(labels).(Gauge)
+}
+
+// GaugeFunc is a Gauge whose value is determined at collect time by calling a
+// provided function.
+//
+// To create GaugeFunc instances, use NewGaugeFunc.
+type GaugeFunc interface {
+ Metric
+ Collector
+}
+
+// NewGaugeFunc creates a new GaugeFunc based on the provided GaugeOpts. The
+// value reported is determined by calling the given function from within the
+// Write method. Take into account that metric collection may happen
+// concurrently. If that results in concurrent calls to Write, like in the case
+// where a GaugeFunc is directly registered with Prometheus, the provided
+// function must be concurrency-safe.
+func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc {
+ return newValueFunc(NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ nil,
+ opts.ConstLabels,
+ ), GaugeValue, function)
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go
new file mode 100644
index 0000000..b0d4fb9
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go
@@ -0,0 +1,263 @@
+package prometheus
+
+import (
+ "fmt"
+ "runtime"
+ "runtime/debug"
+ "time"
+)
+
+type goCollector struct {
+ goroutines Gauge
+ gcDesc *Desc
+
+ // metrics to describe and collect
+ metrics memStatsMetrics
+}
+
+// NewGoCollector returns a collector which exports metrics about the current
+// go process.
+func NewGoCollector() *goCollector {
+ return &goCollector{
+ goroutines: NewGauge(GaugeOpts{
+ Namespace: "go",
+ Name: "goroutines",
+ Help: "Number of goroutines that currently exist.",
+ }),
+ gcDesc: NewDesc(
+ "go_gc_duration_seconds",
+ "A summary of the GC invocation durations.",
+ nil, nil),
+ metrics: memStatsMetrics{
+ {
+ desc: NewDesc(
+ memstatNamespace("alloc_bytes"),
+ "Number of bytes allocated and still in use.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.Alloc) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("alloc_bytes_total"),
+ "Total number of bytes allocated, even if freed.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.TotalAlloc) },
+ valType: CounterValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("sys_bytes"),
+ "Number of bytes obtained by system. Sum of all system allocations.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.Sys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("lookups_total"),
+ "Total number of pointer lookups.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.Lookups) },
+ valType: CounterValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("mallocs_total"),
+ "Total number of mallocs.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.Mallocs) },
+ valType: CounterValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("frees_total"),
+ "Total number of frees.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.Frees) },
+ valType: CounterValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_alloc_bytes"),
+ "Number of heap bytes allocated and still in use.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapAlloc) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_sys_bytes"),
+ "Number of heap bytes obtained from system.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_idle_bytes"),
+ "Number of heap bytes waiting to be used.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapIdle) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_inuse_bytes"),
+ "Number of heap bytes that are in use.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapInuse) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_released_bytes_total"),
+ "Total number of heap bytes released to OS.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapReleased) },
+ valType: CounterValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_objects"),
+ "Number of allocated objects.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapObjects) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("stack_inuse_bytes"),
+ "Number of bytes in use by the stack allocator.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.StackInuse) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("stack_sys_bytes"),
+ "Number of bytes obtained from system for stack allocator.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.StackSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("mspan_inuse_bytes"),
+ "Number of bytes in use by mspan structures.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.MSpanInuse) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("mspan_sys_bytes"),
+ "Number of bytes used for mspan structures obtained from system.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.MSpanSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("mcache_inuse_bytes"),
+ "Number of bytes in use by mcache structures.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.MCacheInuse) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("mcache_sys_bytes"),
+ "Number of bytes used for mcache structures obtained from system.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.MCacheSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("buck_hash_sys_bytes"),
+ "Number of bytes used by the profiling bucket hash table.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.BuckHashSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("gc_sys_bytes"),
+ "Number of bytes used for garbage collection system metadata.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.GCSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("other_sys_bytes"),
+ "Number of bytes used for other system allocations.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.OtherSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("next_gc_bytes"),
+ "Number of heap bytes when next garbage collection will take place.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.NextGC) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("last_gc_time_seconds"),
+ "Number of seconds since 1970 of last garbage collection.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.LastGC) / 1e9 },
+ valType: GaugeValue,
+ },
+ },
+ }
+}
+
+func memstatNamespace(s string) string {
+ return fmt.Sprintf("go_memstats_%s", s)
+}
+
+// Describe returns all descriptions of the collector.
+func (c *goCollector) Describe(ch chan<- *Desc) {
+ ch <- c.goroutines.Desc()
+ ch <- c.gcDesc
+
+ for _, i := range c.metrics {
+ ch <- i.desc
+ }
+}
+
+// Collect returns the current state of all metrics of the collector.
+func (c *goCollector) Collect(ch chan<- Metric) {
+ c.goroutines.Set(float64(runtime.NumGoroutine()))
+ ch <- c.goroutines
+
+ var stats debug.GCStats
+ stats.PauseQuantiles = make([]time.Duration, 5)
+ debug.ReadGCStats(&stats)
+
+ quantiles := make(map[float64]float64)
+ for idx, pq := range stats.PauseQuantiles[1:] {
+ quantiles[float64(idx+1)/float64(len(stats.PauseQuantiles)-1)] = pq.Seconds()
+ }
+ quantiles[0.0] = stats.PauseQuantiles[0].Seconds()
+ ch <- MustNewConstSummary(c.gcDesc, uint64(stats.NumGC), float64(stats.PauseTotal.Seconds()), quantiles)
+
+ ms := &runtime.MemStats{}
+ runtime.ReadMemStats(ms)
+ for _, i := range c.metrics {
+ ch <- MustNewConstMetric(i.desc, i.valType, i.eval(ms))
+ }
+}
+
+// memStatsMetrics provide description, value, and value type for memstat metrics.
+type memStatsMetrics []struct {
+ desc *Desc
+ eval func(*runtime.MemStats) float64
+ valType ValueType
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
new file mode 100644
index 0000000..7a68910
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
@@ -0,0 +1,448 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+ "fmt"
+ "math"
+ "sort"
+ "sync/atomic"
+
+ "github.com/golang/protobuf/proto"
+
+ dto "github.com/prometheus/client_model/go"
+)
+
+// A Histogram counts individual observations from an event or sample stream in
+// configurable buckets. Similar to a summary, it also provides a sum of
+// observations and an observation count.
+//
+// On the Prometheus server, quantiles can be calculated from a Histogram using
+// the histogram_quantile function in the query language.
+//
+// Note that Histograms, in contrast to Summaries, can be aggregated with the
+// Prometheus query language (see the documentation for detailed
+// procedures). However, Histograms require the user to pre-define suitable
+// buckets, and they are in general less accurate. The Observe method of a
+// Histogram has a very low performance overhead in comparison with the Observe
+// method of a Summary.
+//
+// To create Histogram instances, use NewHistogram.
+type Histogram interface {
+ Metric
+ Collector
+
+ // Observe adds a single observation to the histogram.
+ Observe(float64)
+}
+
+// bucketLabel is used for the label that defines the upper bound of a
+// bucket of a histogram ("le" -> "less or equal").
+const bucketLabel = "le"
+
+var (
+ // DefBuckets are the default Histogram buckets. The default buckets are
+ // tailored to broadly measure the response time (in seconds) of a
+ // network service. Most likely, however, you will be required to define
+ // buckets customized to your use case.
+ DefBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}
+
+ errBucketLabelNotAllowed = fmt.Errorf(
+ "%q is not allowed as label name in histograms", bucketLabel,
+ )
+)
+
+// LinearBuckets creates 'count' buckets, each 'width' wide, where the lowest
+// bucket has an upper bound of 'start'. The final +Inf bucket is not counted
+// and not included in the returned slice. The returned slice is meant to be
+// used for the Buckets field of HistogramOpts.
+//
+// The function panics if 'count' is zero or negative.
+func LinearBuckets(start, width float64, count int) []float64 {
+ if count < 1 {
+ panic("LinearBuckets needs a positive count")
+ }
+ buckets := make([]float64, count)
+ for i := range buckets {
+ buckets[i] = start
+ start += width
+ }
+ return buckets
+}
+
+// ExponentialBuckets creates 'count' buckets, where the lowest bucket has an
+// upper bound of 'start' and each following bucket's upper bound is 'factor'
+// times the previous bucket's upper bound. The final +Inf bucket is not counted
+// and not included in the returned slice. The returned slice is meant to be
+// used for the Buckets field of HistogramOpts.
+//
+// The function panics if 'count' is 0 or negative, if 'start' is 0 or negative,
+// or if 'factor' is less than or equal 1.
+func ExponentialBuckets(start, factor float64, count int) []float64 {
+ if count < 1 {
+ panic("ExponentialBuckets needs a positive count")
+ }
+ if start <= 0 {
+ panic("ExponentialBuckets needs a positive start value")
+ }
+ if factor <= 1 {
+ panic("ExponentialBuckets needs a factor greater than 1")
+ }
+ buckets := make([]float64, count)
+ for i := range buckets {
+ buckets[i] = start
+ start *= factor
+ }
+ return buckets
+}
+
+// HistogramOpts bundles the options for creating a Histogram metric. It is
+// mandatory to set Name and Help to a non-empty string. All other fields are
+// optional and can safely be left at their zero value.
+type HistogramOpts struct {
+ // Namespace, Subsystem, and Name are components of the fully-qualified
+ // name of the Histogram (created by joining these components with
+ // "_"). Only Name is mandatory, the others merely help structuring the
+ // name. Note that the fully-qualified name of the Histogram must be a
+ // valid Prometheus metric name.
+ Namespace string
+ Subsystem string
+ Name string
+
+ // Help provides information about this Histogram. Mandatory!
+ //
+ // Metrics with the same fully-qualified name must have the same Help
+ // string.
+ Help string
+
+ // ConstLabels are used to attach fixed labels to this
+ // Histogram. Histograms with the same fully-qualified name must have the
+ // same label names in their ConstLabels.
+ //
+ // Note that in most cases, labels have a value that varies during the
+ // lifetime of a process. Those labels are usually managed with a
+ // HistogramVec. ConstLabels serve only special purposes. One is for the
+ // special case where the value of a label does not change during the
+ // lifetime of a process, e.g. if the revision of the running binary is
+ // put into a label. Another, more advanced purpose is if more than one
+ // Collector needs to collect Histograms with the same fully-qualified
+ // name. In that case, those Summaries must differ in the values of
+ // their ConstLabels. See the Collector examples.
+ //
+ // If the value of a label never changes (not even between binaries),
+ // that label most likely should not be a label at all (but part of the
+ // metric name).
+ ConstLabels Labels
+
+ // Buckets defines the buckets into which observations are counted. Each
+ // element in the slice is the upper inclusive bound of a bucket. The
+ // values must be sorted in strictly increasing order. There is no need
+ // to add a highest bucket with +Inf bound, it will be added
+ // implicitly. The default value is DefBuckets.
+ Buckets []float64
+}
+
+// NewHistogram creates a new Histogram based on the provided HistogramOpts. It
+// panics if the buckets in HistogramOpts are not in strictly increasing order.
+func NewHistogram(opts HistogramOpts) Histogram {
+ return newHistogram(
+ NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ nil,
+ opts.ConstLabels,
+ ),
+ opts,
+ )
+}
+
+func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogram {
+ if len(desc.variableLabels) != len(labelValues) {
+ panic(errInconsistentCardinality)
+ }
+
+ for _, n := range desc.variableLabels {
+ if n == bucketLabel {
+ panic(errBucketLabelNotAllowed)
+ }
+ }
+ for _, lp := range desc.constLabelPairs {
+ if lp.GetName() == bucketLabel {
+ panic(errBucketLabelNotAllowed)
+ }
+ }
+
+ if len(opts.Buckets) == 0 {
+ opts.Buckets = DefBuckets
+ }
+
+ h := &histogram{
+ desc: desc,
+ upperBounds: opts.Buckets,
+ labelPairs: makeLabelPairs(desc, labelValues),
+ }
+ for i, upperBound := range h.upperBounds {
+ if i < len(h.upperBounds)-1 {
+ if upperBound >= h.upperBounds[i+1] {
+ panic(fmt.Errorf(
+ "histogram buckets must be in increasing order: %f >= %f",
+ upperBound, h.upperBounds[i+1],
+ ))
+ }
+ } else {
+ if math.IsInf(upperBound, +1) {
+ // The +Inf bucket is implicit. Remove it here.
+ h.upperBounds = h.upperBounds[:i]
+ }
+ }
+ }
+ // Finally we know the final length of h.upperBounds and can make counts.
+ h.counts = make([]uint64, len(h.upperBounds))
+
+ h.Init(h) // Init self-collection.
+ return h
+}
+
+type histogram struct {
+ // sumBits contains the bits of the float64 representing the sum of all
+ // observations. sumBits and count have to go first in the struct to
+ // guarantee alignment for atomic operations.
+ // http://golang.org/pkg/sync/atomic/#pkg-note-BUG
+ sumBits uint64
+ count uint64
+
+ SelfCollector
+ // Note that there is no mutex required.
+
+ desc *Desc
+
+ upperBounds []float64
+ counts []uint64
+
+ labelPairs []*dto.LabelPair
+}
+
+func (h *histogram) Desc() *Desc {
+ return h.desc
+}
+
+func (h *histogram) Observe(v float64) {
+ // TODO(beorn7): For small numbers of buckets (<30), a linear search is
+ // slightly faster than the binary search. If we really care, we could
+ // switch from one search strategy to the other depending on the number
+ // of buckets.
+ //
+ // Microbenchmarks (BenchmarkHistogramNoLabels):
+ // 11 buckets: 38.3 ns/op linear - binary 48.7 ns/op
+ // 100 buckets: 78.1 ns/op linear - binary 54.9 ns/op
+ // 300 buckets: 154 ns/op linear - binary 61.6 ns/op
+ i := sort.SearchFloat64s(h.upperBounds, v)
+ if i < len(h.counts) {
+ atomic.AddUint64(&h.counts[i], 1)
+ }
+ atomic.AddUint64(&h.count, 1)
+ for {
+ oldBits := atomic.LoadUint64(&h.sumBits)
+ newBits := math.Float64bits(math.Float64frombits(oldBits) + v)
+ if atomic.CompareAndSwapUint64(&h.sumBits, oldBits, newBits) {
+ break
+ }
+ }
+}
+
+func (h *histogram) Write(out *dto.Metric) error {
+ his := &dto.Histogram{}
+ buckets := make([]*dto.Bucket, len(h.upperBounds))
+
+ his.SampleSum = proto.Float64(math.Float64frombits(atomic.LoadUint64(&h.sumBits)))
+ his.SampleCount = proto.Uint64(atomic.LoadUint64(&h.count))
+ var count uint64
+ for i, upperBound := range h.upperBounds {
+ count += atomic.LoadUint64(&h.counts[i])
+ buckets[i] = &dto.Bucket{
+ CumulativeCount: proto.Uint64(count),
+ UpperBound: proto.Float64(upperBound),
+ }
+ }
+ his.Bucket = buckets
+ out.Histogram = his
+ out.Label = h.labelPairs
+ return nil
+}
+
+// HistogramVec is a Collector that bundles a set of Histograms that all share the
+// same Desc, but have different values for their variable labels. This is used
+// if you want to count the same thing partitioned by various dimensions
+// (e.g. HTTP request latencies, partitioned by status code and method). Create
+// instances with NewHistogramVec.
+type HistogramVec struct {
+ MetricVec
+}
+
+// NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and
+// partitioned by the given label names. At least one label name must be
+// provided.
+func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec {
+ desc := NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ labelNames,
+ opts.ConstLabels,
+ )
+ return &HistogramVec{
+ MetricVec: MetricVec{
+ children: map[uint64]Metric{},
+ desc: desc,
+ newMetric: func(lvs ...string) Metric {
+ return newHistogram(desc, opts, lvs...)
+ },
+ },
+ }
+}
+
+// GetMetricWithLabelValues replaces the method of the same name in
+// MetricVec. The difference is that this method returns a Histogram and not a
+// Metric so that no type conversion is required.
+func (m *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Histogram, error) {
+ metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...)
+ if metric != nil {
+ return metric.(Histogram), err
+ }
+ return nil, err
+}
+
+// GetMetricWith replaces the method of the same name in MetricVec. The
+// difference is that this method returns a Histogram and not a Metric so that no
+// type conversion is required.
+func (m *HistogramVec) GetMetricWith(labels Labels) (Histogram, error) {
+ metric, err := m.MetricVec.GetMetricWith(labels)
+ if metric != nil {
+ return metric.(Histogram), err
+ }
+ return nil, err
+}
+
+// WithLabelValues works as GetMetricWithLabelValues, but panics where
+// GetMetricWithLabelValues would have returned an error. By not returning an
+// error, WithLabelValues allows shortcuts like
+// myVec.WithLabelValues("404", "GET").Observe(42.21)
+func (m *HistogramVec) WithLabelValues(lvs ...string) Histogram {
+ return m.MetricVec.WithLabelValues(lvs...).(Histogram)
+}
+
+// With works as GetMetricWith, but panics where GetMetricWithLabels would have
+// returned an error. By not returning an error, With allows shortcuts like
+// myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21)
+func (m *HistogramVec) With(labels Labels) Histogram {
+ return m.MetricVec.With(labels).(Histogram)
+}
+
+type constHistogram struct {
+ desc *Desc
+ count uint64
+ sum float64
+ buckets map[float64]uint64
+ labelPairs []*dto.LabelPair
+}
+
+func (h *constHistogram) Desc() *Desc {
+ return h.desc
+}
+
+func (h *constHistogram) Write(out *dto.Metric) error {
+ his := &dto.Histogram{}
+ buckets := make([]*dto.Bucket, 0, len(h.buckets))
+
+ his.SampleCount = proto.Uint64(h.count)
+ his.SampleSum = proto.Float64(h.sum)
+
+ for upperBound, count := range h.buckets {
+ buckets = append(buckets, &dto.Bucket{
+ CumulativeCount: proto.Uint64(count),
+ UpperBound: proto.Float64(upperBound),
+ })
+ }
+
+ if len(buckets) > 0 {
+ sort.Sort(buckSort(buckets))
+ }
+ his.Bucket = buckets
+
+ out.Histogram = his
+ out.Label = h.labelPairs
+
+ return nil
+}
+
+// NewConstHistogram returns a metric representing a Prometheus histogram with
+// fixed values for the count, sum, and bucket counts. As those parameters
+// cannot be changed, the returned value does not implement the Histogram
+// interface (but only the Metric interface). Users of this package will not
+// have much use for it in regular operations. However, when implementing custom
+// Collectors, it is useful as a throw-away metric that is generated on the fly
+// to send it to Prometheus in the Collect method.
+//
+// buckets is a map of upper bounds to cumulative counts, excluding the +Inf
+// bucket.
+//
+// NewConstHistogram returns an error if the length of labelValues is not
+// consistent with the variable labels in Desc.
+func NewConstHistogram(
+ desc *Desc,
+ count uint64,
+ sum float64,
+ buckets map[float64]uint64,
+ labelValues ...string,
+) (Metric, error) {
+ if len(desc.variableLabels) != len(labelValues) {
+ return nil, errInconsistentCardinality
+ }
+ return &constHistogram{
+ desc: desc,
+ count: count,
+ sum: sum,
+ buckets: buckets,
+ labelPairs: makeLabelPairs(desc, labelValues),
+ }, nil
+}
+
+// MustNewConstHistogram is a version of NewConstHistogram that panics where
+// NewConstMetric would have returned an error.
+func MustNewConstHistogram(
+ desc *Desc,
+ count uint64,
+ sum float64,
+ buckets map[float64]uint64,
+ labelValues ...string,
+) Metric {
+ m, err := NewConstHistogram(desc, count, sum, buckets, labelValues...)
+ if err != nil {
+ panic(err)
+ }
+ return m
+}
+
+type buckSort []*dto.Bucket
+
+func (s buckSort) Len() int {
+ return len(s)
+}
+
+func (s buckSort) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+
+func (s buckSort) Less(i, j int) bool {
+ return s[i].GetUpperBound() < s[j].GetUpperBound()
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/http.go b/vendor/github.com/prometheus/client_golang/prometheus/http.go
new file mode 100644
index 0000000..e078e3e
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/http.go
@@ -0,0 +1,381 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+ "bufio"
+ "io"
+ "net"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var instLabels = []string{"method", "code"}
+
+type nower interface {
+ Now() time.Time
+}
+
+type nowFunc func() time.Time
+
+func (n nowFunc) Now() time.Time {
+ return n()
+}
+
+var now nower = nowFunc(func() time.Time {
+ return time.Now()
+})
+
+func nowSeries(t ...time.Time) nower {
+ return nowFunc(func() time.Time {
+ defer func() {
+ t = t[1:]
+ }()
+
+ return t[0]
+ })
+}
+
+// InstrumentHandler wraps the given HTTP handler for instrumentation. It
+// registers four metric collectors (if not already done) and reports HTTP
+// metrics to the (newly or already) registered collectors: http_requests_total
+// (CounterVec), http_request_duration_microseconds (Summary),
+// http_request_size_bytes (Summary), http_response_size_bytes (Summary). Each
+// has a constant label named "handler" with the provided handlerName as
+// value. http_requests_total is a metric vector partitioned by HTTP method
+// (label name "method") and HTTP status code (label name "code").
+//
+// Note that InstrumentHandler has several issues:
+//
+// - It uses Summaries rather than Histograms. Summaries are not useful if
+// aggregation across multiple instances is required.
+//
+// - It uses microseconds as unit, which is deprecated and should be replaced by
+// seconds.
+//
+// - The size of the request is calculated in a separate goroutine. Since this
+// calculator requires access to the request header, it creates a race with
+// any writes to the header performed during request handling.
+// httputil.ReverseProxy is a prominent example for a handler
+// performing such writes.
+//
+// Upcoming versions of this package will provide ways of instrumenting HTTP
+// handlers that are more flexible and have fewer issues. Consider this function
+// DEPRECATED and prefer direct instrumentation in the meantime.
+func InstrumentHandler(handlerName string, handler http.Handler) http.HandlerFunc {
+ return InstrumentHandlerFunc(handlerName, handler.ServeHTTP)
+}
+
+// InstrumentHandlerFunc wraps the given function for instrumentation. It
+// otherwise works in the same way as InstrumentHandler (and shares the same
+// issues).
+func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
+ return InstrumentHandlerFuncWithOpts(
+ SummaryOpts{
+ Subsystem: "http",
+ ConstLabels: Labels{"handler": handlerName},
+ },
+ handlerFunc,
+ )
+}
+
+// InstrumentHandlerWithOpts works like InstrumentHandler (and shares the same
+// issues) but provides more flexibility (at the cost of a more complex call
+// syntax). As InstrumentHandler, this function registers four metric
+// collectors, but it uses the provided SummaryOpts to create them. However, the
+// fields "Name" and "Help" in the SummaryOpts are ignored. "Name" is replaced
+// by "requests_total", "request_duration_microseconds", "request_size_bytes",
+// and "response_size_bytes", respectively. "Help" is replaced by an appropriate
+// help string. The names of the variable labels of the http_requests_total
+// CounterVec are "method" (get, post, etc.), and "code" (HTTP status code).
+//
+// If InstrumentHandlerWithOpts is called as follows, it mimics exactly the
+// behavior of InstrumentHandler:
+//
+// prometheus.InstrumentHandlerWithOpts(
+// prometheus.SummaryOpts{
+// Subsystem: "http",
+// ConstLabels: prometheus.Labels{"handler": handlerName},
+// },
+// handler,
+// )
+//
+// Technical detail: "requests_total" is a CounterVec, not a SummaryVec, so it
+// cannot use SummaryOpts. Instead, a CounterOpts struct is created internally,
+// and all its fields are set to the equally named fields in the provided
+// SummaryOpts.
+func InstrumentHandlerWithOpts(opts SummaryOpts, handler http.Handler) http.HandlerFunc {
+ return InstrumentHandlerFuncWithOpts(opts, handler.ServeHTTP)
+}
+
+// InstrumentHandlerFuncWithOpts works like InstrumentHandlerFunc (and shares
+// the same issues) but provides more flexibility (at the cost of a more complex
+// call syntax). See InstrumentHandlerWithOpts for details how the provided
+// SummaryOpts are used.
+func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
+ reqCnt := NewCounterVec(
+ CounterOpts{
+ Namespace: opts.Namespace,
+ Subsystem: opts.Subsystem,
+ Name: "requests_total",
+ Help: "Total number of HTTP requests made.",
+ ConstLabels: opts.ConstLabels,
+ },
+ instLabels,
+ )
+
+ opts.Name = "request_duration_microseconds"
+ opts.Help = "The HTTP request latencies in microseconds."
+ reqDur := NewSummary(opts)
+
+ opts.Name = "request_size_bytes"
+ opts.Help = "The HTTP request sizes in bytes."
+ reqSz := NewSummary(opts)
+
+ opts.Name = "response_size_bytes"
+ opts.Help = "The HTTP response sizes in bytes."
+ resSz := NewSummary(opts)
+
+ regReqCnt := MustRegisterOrGet(reqCnt).(*CounterVec)
+ regReqDur := MustRegisterOrGet(reqDur).(Summary)
+ regReqSz := MustRegisterOrGet(reqSz).(Summary)
+ regResSz := MustRegisterOrGet(resSz).(Summary)
+
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ now := time.Now()
+
+ delegate := &responseWriterDelegator{ResponseWriter: w}
+ out := make(chan int)
+ urlLen := 0
+ if r.URL != nil {
+ urlLen = len(r.URL.String())
+ }
+ go computeApproximateRequestSize(r, out, urlLen)
+
+ _, cn := w.(http.CloseNotifier)
+ _, fl := w.(http.Flusher)
+ _, hj := w.(http.Hijacker)
+ _, rf := w.(io.ReaderFrom)
+ var rw http.ResponseWriter
+ if cn && fl && hj && rf {
+ rw = &fancyResponseWriterDelegator{delegate}
+ } else {
+ rw = delegate
+ }
+ handlerFunc(rw, r)
+
+ elapsed := float64(time.Since(now)) / float64(time.Microsecond)
+
+ method := sanitizeMethod(r.Method)
+ code := sanitizeCode(delegate.status)
+ regReqCnt.WithLabelValues(method, code).Inc()
+ regReqDur.Observe(elapsed)
+ regResSz.Observe(float64(delegate.written))
+ regReqSz.Observe(float64(<-out))
+ })
+}
+
+func computeApproximateRequestSize(r *http.Request, out chan int, s int) {
+ s += len(r.Method)
+ s += len(r.Proto)
+ for name, values := range r.Header {
+ s += len(name)
+ for _, value := range values {
+ s += len(value)
+ }
+ }
+ s += len(r.Host)
+
+ // N.B. r.Form and r.MultipartForm are assumed to be included in r.URL.
+
+ if r.ContentLength != -1 {
+ s += int(r.ContentLength)
+ }
+ out <- s
+}
+
+type responseWriterDelegator struct {
+ http.ResponseWriter
+
+ handler, method string
+ status int
+ written int64
+ wroteHeader bool
+}
+
+func (r *responseWriterDelegator) WriteHeader(code int) {
+ r.status = code
+ r.wroteHeader = true
+ r.ResponseWriter.WriteHeader(code)
+}
+
+func (r *responseWriterDelegator) Write(b []byte) (int, error) {
+ if !r.wroteHeader {
+ r.WriteHeader(http.StatusOK)
+ }
+ n, err := r.ResponseWriter.Write(b)
+ r.written += int64(n)
+ return n, err
+}
+
+type fancyResponseWriterDelegator struct {
+ *responseWriterDelegator
+}
+
+func (f *fancyResponseWriterDelegator) CloseNotify() <-chan bool {
+ return f.ResponseWriter.(http.CloseNotifier).CloseNotify()
+}
+
+func (f *fancyResponseWriterDelegator) Flush() {
+ f.ResponseWriter.(http.Flusher).Flush()
+}
+
+func (f *fancyResponseWriterDelegator) Hijack() (net.Conn, *bufio.ReadWriter, error) {
+ return f.ResponseWriter.(http.Hijacker).Hijack()
+}
+
+func (f *fancyResponseWriterDelegator) ReadFrom(r io.Reader) (int64, error) {
+ if !f.wroteHeader {
+ f.WriteHeader(http.StatusOK)
+ }
+ n, err := f.ResponseWriter.(io.ReaderFrom).ReadFrom(r)
+ f.written += n
+ return n, err
+}
+
+func sanitizeMethod(m string) string {
+ switch m {
+ case "GET", "get":
+ return "get"
+ case "PUT", "put":
+ return "put"
+ case "HEAD", "head":
+ return "head"
+ case "POST", "post":
+ return "post"
+ case "DELETE", "delete":
+ return "delete"
+ case "CONNECT", "connect":
+ return "connect"
+ case "OPTIONS", "options":
+ return "options"
+ case "NOTIFY", "notify":
+ return "notify"
+ default:
+ return strings.ToLower(m)
+ }
+}
+
+func sanitizeCode(s int) string {
+ switch s {
+ case 100:
+ return "100"
+ case 101:
+ return "101"
+
+ case 200:
+ return "200"
+ case 201:
+ return "201"
+ case 202:
+ return "202"
+ case 203:
+ return "203"
+ case 204:
+ return "204"
+ case 205:
+ return "205"
+ case 206:
+ return "206"
+
+ case 300:
+ return "300"
+ case 301:
+ return "301"
+ case 302:
+ return "302"
+ case 304:
+ return "304"
+ case 305:
+ return "305"
+ case 307:
+ return "307"
+
+ case 400:
+ return "400"
+ case 401:
+ return "401"
+ case 402:
+ return "402"
+ case 403:
+ return "403"
+ case 404:
+ return "404"
+ case 405:
+ return "405"
+ case 406:
+ return "406"
+ case 407:
+ return "407"
+ case 408:
+ return "408"
+ case 409:
+ return "409"
+ case 410:
+ return "410"
+ case 411:
+ return "411"
+ case 412:
+ return "412"
+ case 413:
+ return "413"
+ case 414:
+ return "414"
+ case 415:
+ return "415"
+ case 416:
+ return "416"
+ case 417:
+ return "417"
+ case 418:
+ return "418"
+
+ case 500:
+ return "500"
+ case 501:
+ return "501"
+ case 502:
+ return "502"
+ case 503:
+ return "503"
+ case 504:
+ return "504"
+ case 505:
+ return "505"
+
+ case 428:
+ return "428"
+ case 429:
+ return "429"
+ case 431:
+ return "431"
+ case 511:
+ return "511"
+
+ default:
+ return strconv.Itoa(s)
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric.go b/vendor/github.com/prometheus/client_golang/prometheus/metric.go
new file mode 100644
index 0000000..86fd81c
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/metric.go
@@ -0,0 +1,166 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+ "strings"
+
+ dto "github.com/prometheus/client_model/go"
+)
+
+const separatorByte byte = 255
+
+// A Metric models a single sample value with its meta data being exported to
+// Prometheus. Implementers of Metric in this package inclued Gauge, Counter,
+// Untyped, and Summary. Users can implement their own Metric types, but that
+// should be rarely needed. See the example for SelfCollector, which is also an
+// example for a user-implemented Metric.
+type Metric interface {
+ // Desc returns the descriptor for the Metric. This method idempotently
+ // returns the same descriptor throughout the lifetime of the
+ // Metric. The returned descriptor is immutable by contract. A Metric
+ // unable to describe itself must return an invalid descriptor (created
+ // with NewInvalidDesc).
+ Desc() *Desc
+ // Write encodes the Metric into a "Metric" Protocol Buffer data
+ // transmission object.
+ //
+ // Implementers of custom Metric types must observe concurrency safety
+ // as reads of this metric may occur at any time, and any blocking
+ // occurs at the expense of total performance of rendering all
+ // registered metrics. Ideally Metric implementations should support
+ // concurrent readers.
+ //
+ // The Prometheus client library attempts to minimize memory allocations
+ // and will provide a pre-existing reset dto.Metric pointer. Prometheus
+ // may recycle the dto.Metric proto message, so Metric implementations
+ // should just populate the provided dto.Metric and then should not keep
+ // any reference to it.
+ //
+ // While populating dto.Metric, labels must be sorted lexicographically.
+ // (Implementers may find LabelPairSorter useful for that.)
+ Write(*dto.Metric) error
+}
+
+// Opts bundles the options for creating most Metric types. Each metric
+// implementation XXX has its own XXXOpts type, but in most cases, it is just be
+// an alias of this type (which might change when the requirement arises.)
+//
+// It is mandatory to set Name and Help to a non-empty string. All other fields
+// are optional and can safely be left at their zero value.
+type Opts struct {
+ // Namespace, Subsystem, and Name are components of the fully-qualified
+ // name of the Metric (created by joining these components with
+ // "_"). Only Name is mandatory, the others merely help structuring the
+ // name. Note that the fully-qualified name of the metric must be a
+ // valid Prometheus metric name.
+ Namespace string
+ Subsystem string
+ Name string
+
+ // Help provides information about this metric. Mandatory!
+ //
+ // Metrics with the same fully-qualified name must have the same Help
+ // string.
+ Help string
+
+ // ConstLabels are used to attach fixed labels to this metric. Metrics
+ // with the same fully-qualified name must have the same label names in
+ // their ConstLabels.
+ //
+ // Note that in most cases, labels have a value that varies during the
+ // lifetime of a process. Those labels are usually managed with a metric
+ // vector collector (like CounterVec, GaugeVec, UntypedVec). ConstLabels
+ // serve only special purposes. One is for the special case where the
+ // value of a label does not change during the lifetime of a process,
+ // e.g. if the revision of the running binary is put into a
+ // label. Another, more advanced purpose is if more than one Collector
+ // needs to collect Metrics with the same fully-qualified name. In that
+ // case, those Metrics must differ in the values of their
+ // ConstLabels. See the Collector examples.
+ //
+ // If the value of a label never changes (not even between binaries),
+ // that label most likely should not be a label at all (but part of the
+ // metric name).
+ ConstLabels Labels
+}
+
+// BuildFQName joins the given three name components by "_". Empty name
+// components are ignored. If the name parameter itself is empty, an empty
+// string is returned, no matter what. Metric implementations included in this
+// library use this function internally to generate the fully-qualified metric
+// name from the name component in their Opts. Users of the library will only
+// need this function if they implement their own Metric or instantiate a Desc
+// (with NewDesc) directly.
+func BuildFQName(namespace, subsystem, name string) string {
+ if name == "" {
+ return ""
+ }
+ switch {
+ case namespace != "" && subsystem != "":
+ return strings.Join([]string{namespace, subsystem, name}, "_")
+ case namespace != "":
+ return strings.Join([]string{namespace, name}, "_")
+ case subsystem != "":
+ return strings.Join([]string{subsystem, name}, "_")
+ }
+ return name
+}
+
+// LabelPairSorter implements sort.Interface. It is used to sort a slice of
+// dto.LabelPair pointers. This is useful for implementing the Write method of
+// custom metrics.
+type LabelPairSorter []*dto.LabelPair
+
+func (s LabelPairSorter) Len() int {
+ return len(s)
+}
+
+func (s LabelPairSorter) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+
+func (s LabelPairSorter) Less(i, j int) bool {
+ return s[i].GetName() < s[j].GetName()
+}
+
+type hashSorter []uint64
+
+func (s hashSorter) Len() int {
+ return len(s)
+}
+
+func (s hashSorter) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+
+func (s hashSorter) Less(i, j int) bool {
+ return s[i] < s[j]
+}
+
+type invalidMetric struct {
+ desc *Desc
+ err error
+}
+
+// NewInvalidMetric returns a metric whose Write method always returns the
+// provided error. It is useful if a Collector finds itself unable to collect
+// a metric and wishes to report an error to the registry.
+func NewInvalidMetric(desc *Desc, err error) Metric {
+ return &invalidMetric{desc, err}
+}
+
+func (m *invalidMetric) Desc() *Desc { return m.desc }
+
+func (m *invalidMetric) Write(*dto.Metric) error { return m.err }
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go
new file mode 100644
index 0000000..d8cf0ed
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go
@@ -0,0 +1,142 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import "github.com/prometheus/procfs"
+
+type processCollector struct {
+ pid int
+ collectFn func(chan<- Metric)
+ pidFn func() (int, error)
+ cpuTotal Counter
+ openFDs, maxFDs Gauge
+ vsize, rss Gauge
+ startTime Gauge
+}
+
+// NewProcessCollector returns a collector which exports the current state of
+// process metrics including cpu, memory and file descriptor usage as well as
+// the process start time for the given process id under the given namespace.
+func NewProcessCollector(pid int, namespace string) *processCollector {
+ return NewProcessCollectorPIDFn(
+ func() (int, error) { return pid, nil },
+ namespace,
+ )
+}
+
+// NewProcessCollectorPIDFn returns a collector which exports the current state
+// of process metrics including cpu, memory and file descriptor usage as well
+// as the process start time under the given namespace. The given pidFn is
+// called on each collect and is used to determine the process to export
+// metrics for.
+func NewProcessCollectorPIDFn(
+ pidFn func() (int, error),
+ namespace string,
+) *processCollector {
+ c := processCollector{
+ pidFn: pidFn,
+ collectFn: func(chan<- Metric) {},
+
+ cpuTotal: NewCounter(CounterOpts{
+ Namespace: namespace,
+ Name: "process_cpu_seconds_total",
+ Help: "Total user and system CPU time spent in seconds.",
+ }),
+ openFDs: NewGauge(GaugeOpts{
+ Namespace: namespace,
+ Name: "process_open_fds",
+ Help: "Number of open file descriptors.",
+ }),
+ maxFDs: NewGauge(GaugeOpts{
+ Namespace: namespace,
+ Name: "process_max_fds",
+ Help: "Maximum number of open file descriptors.",
+ }),
+ vsize: NewGauge(GaugeOpts{
+ Namespace: namespace,
+ Name: "process_virtual_memory_bytes",
+ Help: "Virtual memory size in bytes.",
+ }),
+ rss: NewGauge(GaugeOpts{
+ Namespace: namespace,
+ Name: "process_resident_memory_bytes",
+ Help: "Resident memory size in bytes.",
+ }),
+ startTime: NewGauge(GaugeOpts{
+ Namespace: namespace,
+ Name: "process_start_time_seconds",
+ Help: "Start time of the process since unix epoch in seconds.",
+ }),
+ }
+
+ // Set up process metric collection if supported by the runtime.
+ if _, err := procfs.NewStat(); err == nil {
+ c.collectFn = c.processCollect
+ }
+
+ return &c
+}
+
+// Describe returns all descriptions of the collector.
+func (c *processCollector) Describe(ch chan<- *Desc) {
+ ch <- c.cpuTotal.Desc()
+ ch <- c.openFDs.Desc()
+ ch <- c.maxFDs.Desc()
+ ch <- c.vsize.Desc()
+ ch <- c.rss.Desc()
+ ch <- c.startTime.Desc()
+}
+
+// Collect returns the current state of all metrics of the collector.
+func (c *processCollector) Collect(ch chan<- Metric) {
+ c.collectFn(ch)
+}
+
+// TODO(ts): Bring back error reporting by reverting 7faf9e7 as soon as the
+// client allows users to configure the error behavior.
+func (c *processCollector) processCollect(ch chan<- Metric) {
+ pid, err := c.pidFn()
+ if err != nil {
+ return
+ }
+
+ p, err := procfs.NewProc(pid)
+ if err != nil {
+ return
+ }
+
+ if stat, err := p.NewStat(); err == nil {
+ c.cpuTotal.Set(stat.CPUTime())
+ ch <- c.cpuTotal
+ c.vsize.Set(float64(stat.VirtualMemory()))
+ ch <- c.vsize
+ c.rss.Set(float64(stat.ResidentMemory()))
+ ch <- c.rss
+
+ if startTime, err := stat.StartTime(); err == nil {
+ c.startTime.Set(startTime)
+ ch <- c.startTime
+ }
+ }
+
+ if fds, err := p.FileDescriptorsLen(); err == nil {
+ c.openFDs.Set(float64(fds))
+ ch <- c.openFDs
+ }
+
+ if limits, err := p.NewLimits(); err == nil {
+ c.maxFDs.Set(float64(limits.OpenFiles))
+ ch <- c.maxFDs
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push.go b/vendor/github.com/prometheus/client_golang/prometheus/push.go
new file mode 100644
index 0000000..5ec0a3a
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/push.go
@@ -0,0 +1,65 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Copyright (c) 2013, The Prometheus 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 prometheus
+
+// Push triggers a metric collection by the default registry and pushes all
+// collected metrics to the Pushgateway specified by url. See the Pushgateway
+// documentation for detailed implications of the job and instance
+// parameter. instance can be left empty. You can use just host:port or ip:port
+// as url, in which case 'http://' is added automatically. You can also include
+// the schema in the URL. However, do not include the '/metrics/jobs/...' part.
+//
+// Note that all previously pushed metrics with the same job and instance will
+// be replaced with the metrics pushed by this call. (It uses HTTP method 'PUT'
+// to push to the Pushgateway.)
+func Push(job, instance, url string) error {
+ return defRegistry.Push(job, instance, url, "PUT")
+}
+
+// PushAdd works like Push, but only previously pushed metrics with the same
+// name (and the same job and instance) will be replaced. (It uses HTTP method
+// 'POST' to push to the Pushgateway.)
+func PushAdd(job, instance, url string) error {
+ return defRegistry.Push(job, instance, url, "POST")
+}
+
+// PushCollectors works like Push, but it does not collect from the default
+// registry. Instead, it collects from the provided collectors. It is a
+// convenient way to push only a few metrics.
+func PushCollectors(job, instance, url string, collectors ...Collector) error {
+ return pushCollectors(job, instance, url, "PUT", collectors...)
+}
+
+// PushAddCollectors works like PushAdd, but it does not collect from the
+// default registry. Instead, it collects from the provided collectors. It is a
+// convenient way to push only a few metrics.
+func PushAddCollectors(job, instance, url string, collectors ...Collector) error {
+ return pushCollectors(job, instance, url, "POST", collectors...)
+}
+
+func pushCollectors(job, instance, url, method string, collectors ...Collector) error {
+ r := newRegistry()
+ for _, collector := range collectors {
+ if _, err := r.Register(collector); err != nil {
+ return err
+ }
+ }
+ return r.Push(job, instance, url, method)
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry.go b/vendor/github.com/prometheus/client_golang/prometheus/registry.go
new file mode 100644
index 0000000..00c184b
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/registry.go
@@ -0,0 +1,741 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Copyright (c) 2013, The Prometheus 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 prometheus
+
+import (
+ "bytes"
+ "compress/gzip"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "sort"
+ "strings"
+ "sync"
+
+ "github.com/golang/protobuf/proto"
+ "github.com/prometheus/common/expfmt"
+
+ dto "github.com/prometheus/client_model/go"
+)
+
+var (
+ defRegistry = newDefaultRegistry()
+ errAlreadyReg = errors.New("duplicate metrics collector registration attempted")
+)
+
+// Constants relevant to the HTTP interface.
+const (
+ // APIVersion is the version of the format of the exported data. This
+ // will match this library's version, which subscribes to the Semantic
+ // Versioning scheme.
+ APIVersion = "0.0.4"
+
+ // DelimitedTelemetryContentType is the content type set on telemetry
+ // data responses in delimited protobuf format.
+ DelimitedTelemetryContentType = `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`
+ // TextTelemetryContentType is the content type set on telemetry data
+ // responses in text format.
+ TextTelemetryContentType = `text/plain; version=` + APIVersion
+ // ProtoTextTelemetryContentType is the content type set on telemetry
+ // data responses in protobuf text format. (Only used for debugging.)
+ ProtoTextTelemetryContentType = `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=text`
+ // ProtoCompactTextTelemetryContentType is the content type set on
+ // telemetry data responses in protobuf compact text format. (Only used
+ // for debugging.)
+ ProtoCompactTextTelemetryContentType = `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`
+
+ // Constants for object pools.
+ numBufs = 4
+ numMetricFamilies = 1000
+ numMetrics = 10000
+
+ // Capacity for the channel to collect metrics and descriptors.
+ capMetricChan = 1000
+ capDescChan = 10
+
+ contentTypeHeader = "Content-Type"
+ contentLengthHeader = "Content-Length"
+ contentEncodingHeader = "Content-Encoding"
+
+ acceptEncodingHeader = "Accept-Encoding"
+ acceptHeader = "Accept"
+)
+
+// Handler returns the HTTP handler for the global Prometheus registry. It is
+// already instrumented with InstrumentHandler (using "prometheus" as handler
+// name). Usually the handler is used to handle the "/metrics" endpoint.
+//
+// Please note the issues described in the doc comment of InstrumentHandler. You
+// might want to consider using UninstrumentedHandler instead.
+func Handler() http.Handler {
+ return InstrumentHandler("prometheus", defRegistry)
+}
+
+// UninstrumentedHandler works in the same way as Handler, but the returned HTTP
+// handler is not instrumented. This is useful if no instrumentation is desired
+// (for whatever reason) or if the instrumentation has to happen with a
+// different handler name (or with a different instrumentation approach
+// altogether). See the InstrumentHandler example.
+func UninstrumentedHandler() http.Handler {
+ return defRegistry
+}
+
+// Register registers a new Collector to be included in metrics collection. It
+// returns an error if the descriptors provided by the Collector are invalid or
+// if they - in combination with descriptors of already registered Collectors -
+// do not fulfill the consistency and uniqueness criteria described in the Desc
+// documentation.
+//
+// Do not register the same Collector multiple times concurrently. (Registering
+// the same Collector twice would result in an error anyway, but on top of that,
+// it is not safe to do so concurrently.)
+func Register(m Collector) error {
+ _, err := defRegistry.Register(m)
+ return err
+}
+
+// MustRegister works like Register but panics where Register would have
+// returned an error. MustRegister is also Variadic, where Register only
+// accepts a single Collector to register.
+func MustRegister(m ...Collector) {
+ for i := range m {
+ if err := Register(m[i]); err != nil {
+ panic(err)
+ }
+ }
+}
+
+// RegisterOrGet works like Register but does not return an error if a Collector
+// is registered that equals a previously registered Collector. (Two Collectors
+// are considered equal if their Describe method yields the same set of
+// descriptors.) Instead, the previously registered Collector is returned (which
+// is helpful if the new and previously registered Collectors are equal but not
+// identical, i.e. not pointers to the same object).
+//
+// As for Register, it is still not safe to call RegisterOrGet with the same
+// Collector multiple times concurrently.
+func RegisterOrGet(m Collector) (Collector, error) {
+ return defRegistry.RegisterOrGet(m)
+}
+
+// MustRegisterOrGet works like RegisterOrGet but panics where RegisterOrGet
+// would have returned an error.
+func MustRegisterOrGet(m Collector) Collector {
+ existing, err := RegisterOrGet(m)
+ if err != nil {
+ panic(err)
+ }
+ return existing
+}
+
+// Unregister unregisters the Collector that equals the Collector passed in as
+// an argument. (Two Collectors are considered equal if their Describe method
+// yields the same set of descriptors.) The function returns whether a Collector
+// was unregistered.
+func Unregister(c Collector) bool {
+ return defRegistry.Unregister(c)
+}
+
+// SetMetricFamilyInjectionHook sets a function that is called whenever metrics
+// are collected. The hook function must be set before metrics collection begins
+// (i.e. call SetMetricFamilyInjectionHook before setting the HTTP handler.) The
+// MetricFamily protobufs returned by the hook function are merged with the
+// metrics collected in the usual way.
+//
+// This is a way to directly inject MetricFamily protobufs managed and owned by
+// the caller. The caller has full responsibility. As no registration of the
+// injected metrics has happened, there is no descriptor to check against, and
+// there are no registration-time checks. If collect-time checks are disabled
+// (see function EnableCollectChecks), no sanity checks are performed on the
+// returned protobufs at all. If collect-checks are enabled, type and uniqueness
+// checks are performed, but no further consistency checks (which would require
+// knowledge of a metric descriptor).
+//
+// Sorting concerns: The caller is responsible for sorting the label pairs in
+// each metric. However, the order of metrics will be sorted by the registry as
+// it is required anyway after merging with the metric families collected
+// conventionally.
+//
+// The function must be callable at any time and concurrently.
+func SetMetricFamilyInjectionHook(hook func() []*dto.MetricFamily) {
+ defRegistry.metricFamilyInjectionHook = hook
+}
+
+// PanicOnCollectError sets the behavior whether a panic is caused upon an error
+// while metrics are collected and served to the HTTP endpoint. By default, an
+// internal server error (status code 500) is served with an error message.
+func PanicOnCollectError(b bool) {
+ defRegistry.panicOnCollectError = b
+}
+
+// EnableCollectChecks enables (or disables) additional consistency checks
+// during metrics collection. These additional checks are not enabled by default
+// because they inflict a performance penalty and the errors they check for can
+// only happen if the used Metric and Collector types have internal programming
+// errors. It can be helpful to enable these checks while working with custom
+// Collectors or Metrics whose correctness is not well established yet.
+func EnableCollectChecks(b bool) {
+ defRegistry.collectChecksEnabled = b
+}
+
+// encoder is a function that writes a dto.MetricFamily to an io.Writer in a
+// certain encoding. It returns the number of bytes written and any error
+// encountered. Note that pbutil.WriteDelimited and pbutil.MetricFamilyToText
+// are encoders.
+type encoder func(io.Writer, *dto.MetricFamily) (int, error)
+
+type registry struct {
+ mtx sync.RWMutex
+ collectorsByID map[uint64]Collector // ID is a hash of the descIDs.
+ descIDs map[uint64]struct{}
+ dimHashesByName map[string]uint64
+ bufPool chan *bytes.Buffer
+ metricFamilyPool chan *dto.MetricFamily
+ metricPool chan *dto.Metric
+ metricFamilyInjectionHook func() []*dto.MetricFamily
+
+ panicOnCollectError, collectChecksEnabled bool
+}
+
+func (r *registry) Register(c Collector) (Collector, error) {
+ descChan := make(chan *Desc, capDescChan)
+ go func() {
+ c.Describe(descChan)
+ close(descChan)
+ }()
+
+ newDescIDs := map[uint64]struct{}{}
+ newDimHashesByName := map[string]uint64{}
+ var collectorID uint64 // Just a sum of all desc IDs.
+ var duplicateDescErr error
+
+ r.mtx.Lock()
+ defer r.mtx.Unlock()
+ // Coduct various tests...
+ for desc := range descChan {
+
+ // Is the descriptor valid at all?
+ if desc.err != nil {
+ return c, fmt.Errorf("descriptor %s is invalid: %s", desc, desc.err)
+ }
+
+ // Is the descID unique?
+ // (In other words: Is the fqName + constLabel combination unique?)
+ if _, exists := r.descIDs[desc.id]; exists {
+ duplicateDescErr = fmt.Errorf("descriptor %s already exists with the same fully-qualified name and const label values", desc)
+ }
+ // If it is not a duplicate desc in this collector, add it to
+ // the collectorID. (We allow duplicate descs within the same
+ // collector, but their existence must be a no-op.)
+ if _, exists := newDescIDs[desc.id]; !exists {
+ newDescIDs[desc.id] = struct{}{}
+ collectorID += desc.id
+ }
+
+ // Are all the label names and the help string consistent with
+ // previous descriptors of the same name?
+ // First check existing descriptors...
+ if dimHash, exists := r.dimHashesByName[desc.fqName]; exists {
+ if dimHash != desc.dimHash {
+ return nil, fmt.Errorf("a previously registered descriptor with the same fully-qualified name as %s has different label names or a different help string", desc)
+ }
+ } else {
+ // ...then check the new descriptors already seen.
+ if dimHash, exists := newDimHashesByName[desc.fqName]; exists {
+ if dimHash != desc.dimHash {
+ return nil, fmt.Errorf("descriptors reported by collector have inconsistent label names or help strings for the same fully-qualified name, offender is %s", desc)
+ }
+ } else {
+ newDimHashesByName[desc.fqName] = desc.dimHash
+ }
+ }
+ }
+ // Did anything happen at all?
+ if len(newDescIDs) == 0 {
+ return nil, errors.New("collector has no descriptors")
+ }
+ if existing, exists := r.collectorsByID[collectorID]; exists {
+ return existing, errAlreadyReg
+ }
+ // If the collectorID is new, but at least one of the descs existed
+ // before, we are in trouble.
+ if duplicateDescErr != nil {
+ return nil, duplicateDescErr
+ }
+
+ // Only after all tests have passed, actually register.
+ r.collectorsByID[collectorID] = c
+ for hash := range newDescIDs {
+ r.descIDs[hash] = struct{}{}
+ }
+ for name, dimHash := range newDimHashesByName {
+ r.dimHashesByName[name] = dimHash
+ }
+ return c, nil
+}
+
+func (r *registry) RegisterOrGet(m Collector) (Collector, error) {
+ existing, err := r.Register(m)
+ if err != nil && err != errAlreadyReg {
+ return nil, err
+ }
+ return existing, nil
+}
+
+func (r *registry) Unregister(c Collector) bool {
+ descChan := make(chan *Desc, capDescChan)
+ go func() {
+ c.Describe(descChan)
+ close(descChan)
+ }()
+
+ descIDs := map[uint64]struct{}{}
+ var collectorID uint64 // Just a sum of the desc IDs.
+ for desc := range descChan {
+ if _, exists := descIDs[desc.id]; !exists {
+ collectorID += desc.id
+ descIDs[desc.id] = struct{}{}
+ }
+ }
+
+ r.mtx.RLock()
+ if _, exists := r.collectorsByID[collectorID]; !exists {
+ r.mtx.RUnlock()
+ return false
+ }
+ r.mtx.RUnlock()
+
+ r.mtx.Lock()
+ defer r.mtx.Unlock()
+
+ delete(r.collectorsByID, collectorID)
+ for id := range descIDs {
+ delete(r.descIDs, id)
+ }
+ // dimHashesByName is left untouched as those must be consistent
+ // throughout the lifetime of a program.
+ return true
+}
+
+func (r *registry) Push(job, instance, pushURL, method string) error {
+ if !strings.Contains(pushURL, "://") {
+ pushURL = "http://" + pushURL
+ }
+ if strings.HasSuffix(pushURL, "/") {
+ pushURL = pushURL[:len(pushURL)-1]
+ }
+ pushURL = fmt.Sprintf("%s/metrics/jobs/%s", pushURL, url.QueryEscape(job))
+ if instance != "" {
+ pushURL += "/instances/" + url.QueryEscape(instance)
+ }
+ buf := r.getBuf()
+ defer r.giveBuf(buf)
+ if err := r.writePB(expfmt.NewEncoder(buf, expfmt.FmtProtoDelim)); err != nil {
+ if r.panicOnCollectError {
+ panic(err)
+ }
+ return err
+ }
+ req, err := http.NewRequest(method, pushURL, buf)
+ if err != nil {
+ return err
+ }
+ req.Header.Set(contentTypeHeader, DelimitedTelemetryContentType)
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != 202 {
+ return fmt.Errorf("unexpected status code %d while pushing to %s", resp.StatusCode, pushURL)
+ }
+ return nil
+}
+
+func (r *registry) ServeHTTP(w http.ResponseWriter, req *http.Request) {
+ contentType := expfmt.Negotiate(req.Header)
+ buf := r.getBuf()
+ defer r.giveBuf(buf)
+ writer, encoding := decorateWriter(req, buf)
+ if err := r.writePB(expfmt.NewEncoder(writer, contentType)); err != nil {
+ if r.panicOnCollectError {
+ panic(err)
+ }
+ http.Error(w, "An error has occurred:\n\n"+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if closer, ok := writer.(io.Closer); ok {
+ closer.Close()
+ }
+ header := w.Header()
+ header.Set(contentTypeHeader, string(contentType))
+ header.Set(contentLengthHeader, fmt.Sprint(buf.Len()))
+ if encoding != "" {
+ header.Set(contentEncodingHeader, encoding)
+ }
+ w.Write(buf.Bytes())
+}
+
+func (r *registry) writePB(encoder expfmt.Encoder) error {
+ var metricHashes map[uint64]struct{}
+ if r.collectChecksEnabled {
+ metricHashes = make(map[uint64]struct{})
+ }
+ metricChan := make(chan Metric, capMetricChan)
+ wg := sync.WaitGroup{}
+
+ r.mtx.RLock()
+ metricFamiliesByName := make(map[string]*dto.MetricFamily, len(r.dimHashesByName))
+
+ // Scatter.
+ // (Collectors could be complex and slow, so we call them all at once.)
+ wg.Add(len(r.collectorsByID))
+ go func() {
+ wg.Wait()
+ close(metricChan)
+ }()
+ for _, collector := range r.collectorsByID {
+ go func(collector Collector) {
+ defer wg.Done()
+ collector.Collect(metricChan)
+ }(collector)
+ }
+ r.mtx.RUnlock()
+
+ // Drain metricChan in case of premature return.
+ defer func() {
+ for _ = range metricChan {
+ }
+ }()
+
+ // Gather.
+ for metric := range metricChan {
+ // This could be done concurrently, too, but it required locking
+ // of metricFamiliesByName (and of metricHashes if checks are
+ // enabled). Most likely not worth it.
+ desc := metric.Desc()
+ metricFamily, ok := metricFamiliesByName[desc.fqName]
+ if !ok {
+ metricFamily = r.getMetricFamily()
+ defer r.giveMetricFamily(metricFamily)
+ metricFamily.Name = proto.String(desc.fqName)
+ metricFamily.Help = proto.String(desc.help)
+ metricFamiliesByName[desc.fqName] = metricFamily
+ }
+ dtoMetric := r.getMetric()
+ defer r.giveMetric(dtoMetric)
+ if err := metric.Write(dtoMetric); err != nil {
+ // TODO: Consider different means of error reporting so
+ // that a single erroneous metric could be skipped
+ // instead of blowing up the whole collection.
+ return fmt.Errorf("error collecting metric %v: %s", desc, err)
+ }
+ switch {
+ case metricFamily.Type != nil:
+ // Type already set. We are good.
+ case dtoMetric.Gauge != nil:
+ metricFamily.Type = dto.MetricType_GAUGE.Enum()
+ case dtoMetric.Counter != nil:
+ metricFamily.Type = dto.MetricType_COUNTER.Enum()
+ case dtoMetric.Summary != nil:
+ metricFamily.Type = dto.MetricType_SUMMARY.Enum()
+ case dtoMetric.Untyped != nil:
+ metricFamily.Type = dto.MetricType_UNTYPED.Enum()
+ case dtoMetric.Histogram != nil:
+ metricFamily.Type = dto.MetricType_HISTOGRAM.Enum()
+ default:
+ return fmt.Errorf("empty metric collected: %s", dtoMetric)
+ }
+ if r.collectChecksEnabled {
+ if err := r.checkConsistency(metricFamily, dtoMetric, desc, metricHashes); err != nil {
+ return err
+ }
+ }
+ metricFamily.Metric = append(metricFamily.Metric, dtoMetric)
+ }
+
+ if r.metricFamilyInjectionHook != nil {
+ for _, mf := range r.metricFamilyInjectionHook() {
+ existingMF, exists := metricFamiliesByName[mf.GetName()]
+ if !exists {
+ metricFamiliesByName[mf.GetName()] = mf
+ if r.collectChecksEnabled {
+ for _, m := range mf.Metric {
+ if err := r.checkConsistency(mf, m, nil, metricHashes); err != nil {
+ return err
+ }
+ }
+ }
+ continue
+ }
+ for _, m := range mf.Metric {
+ if r.collectChecksEnabled {
+ if err := r.checkConsistency(existingMF, m, nil, metricHashes); err != nil {
+ return err
+ }
+ }
+ existingMF.Metric = append(existingMF.Metric, m)
+ }
+ }
+ }
+
+ // Now that MetricFamilies are all set, sort their Metrics
+ // lexicographically by their label values.
+ for _, mf := range metricFamiliesByName {
+ sort.Sort(metricSorter(mf.Metric))
+ }
+
+ // Write out MetricFamilies sorted by their name.
+ names := make([]string, 0, len(metricFamiliesByName))
+ for name := range metricFamiliesByName {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+
+ for _, name := range names {
+ if err := encoder.Encode(metricFamiliesByName[name]); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (r *registry) checkConsistency(metricFamily *dto.MetricFamily, dtoMetric *dto.Metric, desc *Desc, metricHashes map[uint64]struct{}) error {
+
+ // Type consistency with metric family.
+ if metricFamily.GetType() == dto.MetricType_GAUGE && dtoMetric.Gauge == nil ||
+ metricFamily.GetType() == dto.MetricType_COUNTER && dtoMetric.Counter == nil ||
+ metricFamily.GetType() == dto.MetricType_SUMMARY && dtoMetric.Summary == nil ||
+ metricFamily.GetType() == dto.MetricType_HISTOGRAM && dtoMetric.Histogram == nil ||
+ metricFamily.GetType() == dto.MetricType_UNTYPED && dtoMetric.Untyped == nil {
+ return fmt.Errorf(
+ "collected metric %s %s is not a %s",
+ metricFamily.GetName(), dtoMetric, metricFamily.GetType(),
+ )
+ }
+
+ // Is the metric unique (i.e. no other metric with the same name and the same label values)?
+ h := hashNew()
+ h = hashAdd(h, metricFamily.GetName())
+ h = hashAddByte(h, separatorByte)
+ // Make sure label pairs are sorted. We depend on it for the consistency
+ // check. Label pairs must be sorted by contract. But the point of this
+ // method is to check for contract violations. So we better do the sort
+ // now.
+ sort.Sort(LabelPairSorter(dtoMetric.Label))
+ for _, lp := range dtoMetric.Label {
+ h = hashAdd(h, lp.GetValue())
+ h = hashAddByte(h, separatorByte)
+ }
+ if _, exists := metricHashes[h]; exists {
+ return fmt.Errorf(
+ "collected metric %s %s was collected before with the same name and label values",
+ metricFamily.GetName(), dtoMetric,
+ )
+ }
+ metricHashes[h] = struct{}{}
+
+ if desc == nil {
+ return nil // Nothing left to check if we have no desc.
+ }
+
+ // Desc consistency with metric family.
+ if metricFamily.GetName() != desc.fqName {
+ return fmt.Errorf(
+ "collected metric %s %s has name %q but should have %q",
+ metricFamily.GetName(), dtoMetric, metricFamily.GetName(), desc.fqName,
+ )
+ }
+ if metricFamily.GetHelp() != desc.help {
+ return fmt.Errorf(
+ "collected metric %s %s has help %q but should have %q",
+ metricFamily.GetName(), dtoMetric, metricFamily.GetHelp(), desc.help,
+ )
+ }
+
+ // Is the desc consistent with the content of the metric?
+ lpsFromDesc := make([]*dto.LabelPair, 0, len(dtoMetric.Label))
+ lpsFromDesc = append(lpsFromDesc, desc.constLabelPairs...)
+ for _, l := range desc.variableLabels {
+ lpsFromDesc = append(lpsFromDesc, &dto.LabelPair{
+ Name: proto.String(l),
+ })
+ }
+ if len(lpsFromDesc) != len(dtoMetric.Label) {
+ return fmt.Errorf(
+ "labels in collected metric %s %s are inconsistent with descriptor %s",
+ metricFamily.GetName(), dtoMetric, desc,
+ )
+ }
+ sort.Sort(LabelPairSorter(lpsFromDesc))
+ for i, lpFromDesc := range lpsFromDesc {
+ lpFromMetric := dtoMetric.Label[i]
+ if lpFromDesc.GetName() != lpFromMetric.GetName() ||
+ lpFromDesc.Value != nil && lpFromDesc.GetValue() != lpFromMetric.GetValue() {
+ return fmt.Errorf(
+ "labels in collected metric %s %s are inconsistent with descriptor %s",
+ metricFamily.GetName(), dtoMetric, desc,
+ )
+ }
+ }
+
+ r.mtx.RLock() // Remaining checks need the read lock.
+ defer r.mtx.RUnlock()
+
+ // Is the desc registered?
+ if _, exist := r.descIDs[desc.id]; !exist {
+ return fmt.Errorf(
+ "collected metric %s %s with unregistered descriptor %s",
+ metricFamily.GetName(), dtoMetric, desc,
+ )
+ }
+
+ return nil
+}
+
+func (r *registry) getBuf() *bytes.Buffer {
+ select {
+ case buf := <-r.bufPool:
+ return buf
+ default:
+ return &bytes.Buffer{}
+ }
+}
+
+func (r *registry) giveBuf(buf *bytes.Buffer) {
+ buf.Reset()
+ select {
+ case r.bufPool <- buf:
+ default:
+ }
+}
+
+func (r *registry) getMetricFamily() *dto.MetricFamily {
+ select {
+ case mf := <-r.metricFamilyPool:
+ return mf
+ default:
+ return &dto.MetricFamily{}
+ }
+}
+
+func (r *registry) giveMetricFamily(mf *dto.MetricFamily) {
+ mf.Reset()
+ select {
+ case r.metricFamilyPool <- mf:
+ default:
+ }
+}
+
+func (r *registry) getMetric() *dto.Metric {
+ select {
+ case m := <-r.metricPool:
+ return m
+ default:
+ return &dto.Metric{}
+ }
+}
+
+func (r *registry) giveMetric(m *dto.Metric) {
+ m.Reset()
+ select {
+ case r.metricPool <- m:
+ default:
+ }
+}
+
+func newRegistry() *registry {
+ return &registry{
+ collectorsByID: map[uint64]Collector{},
+ descIDs: map[uint64]struct{}{},
+ dimHashesByName: map[string]uint64{},
+ bufPool: make(chan *bytes.Buffer, numBufs),
+ metricFamilyPool: make(chan *dto.MetricFamily, numMetricFamilies),
+ metricPool: make(chan *dto.Metric, numMetrics),
+ }
+}
+
+func newDefaultRegistry() *registry {
+ r := newRegistry()
+ r.Register(NewProcessCollector(os.Getpid(), ""))
+ r.Register(NewGoCollector())
+ return r
+}
+
+// decorateWriter wraps a writer to handle gzip compression if requested. It
+// returns the decorated writer and the appropriate "Content-Encoding" header
+// (which is empty if no compression is enabled).
+func decorateWriter(request *http.Request, writer io.Writer) (io.Writer, string) {
+ header := request.Header.Get(acceptEncodingHeader)
+ parts := strings.Split(header, ",")
+ for _, part := range parts {
+ part := strings.TrimSpace(part)
+ if part == "gzip" || strings.HasPrefix(part, "gzip;") {
+ return gzip.NewWriter(writer), "gzip"
+ }
+ }
+ return writer, ""
+}
+
+type metricSorter []*dto.Metric
+
+func (s metricSorter) Len() int {
+ return len(s)
+}
+
+func (s metricSorter) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+
+func (s metricSorter) Less(i, j int) bool {
+ if len(s[i].Label) != len(s[j].Label) {
+ // This should not happen. The metrics are
+ // inconsistent. However, we have to deal with the fact, as
+ // people might use custom collectors or metric family injection
+ // to create inconsistent metrics. So let's simply compare the
+ // number of labels in this case. That will still yield
+ // reproducible sorting.
+ return len(s[i].Label) < len(s[j].Label)
+ }
+ for n, lp := range s[i].Label {
+ vi := lp.GetValue()
+ vj := s[j].Label[n].GetValue()
+ if vi != vj {
+ return vi < vj
+ }
+ }
+
+ // We should never arrive here. Multiple metrics with the same
+ // label set in the same scrape will lead to undefined ingestion
+ // behavior. However, as above, we have to provide stable sorting
+ // here, even for inconsistent metrics. So sort equal metrics
+ // by their timestamp, with missing timestamps (implying "now")
+ // coming last.
+ if s[i].TimestampMs == nil {
+ return false
+ }
+ if s[j].TimestampMs == nil {
+ return true
+ }
+ return s[i].GetTimestampMs() < s[j].GetTimestampMs()
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary.go b/vendor/github.com/prometheus/client_golang/prometheus/summary.go
new file mode 100644
index 0000000..eb84961
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/summary.go
@@ -0,0 +1,538 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+ "fmt"
+ "math"
+ "sort"
+ "sync"
+ "time"
+
+ "github.com/beorn7/perks/quantile"
+ "github.com/golang/protobuf/proto"
+
+ dto "github.com/prometheus/client_model/go"
+)
+
+// quantileLabel is used for the label that defines the quantile in a
+// summary.
+const quantileLabel = "quantile"
+
+// A Summary captures individual observations from an event or sample stream and
+// summarizes them in a manner similar to traditional summary statistics: 1. sum
+// of observations, 2. observation count, 3. rank estimations.
+//
+// A typical use-case is the observation of request latencies. By default, a
+// Summary provides the median, the 90th and the 99th percentile of the latency
+// as rank estimations.
+//
+// Note that the rank estimations cannot be aggregated in a meaningful way with
+// the Prometheus query language (i.e. you cannot average or add them). If you
+// need aggregatable quantiles (e.g. you want the 99th percentile latency of all
+// queries served across all instances of a service), consider the Histogram
+// metric type. See the Prometheus documentation for more details.
+//
+// To create Summary instances, use NewSummary.
+type Summary interface {
+ Metric
+ Collector
+
+ // Observe adds a single observation to the summary.
+ Observe(float64)
+}
+
+var (
+ // DefObjectives are the default Summary quantile values.
+ DefObjectives = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}
+
+ errQuantileLabelNotAllowed = fmt.Errorf(
+ "%q is not allowed as label name in summaries", quantileLabel,
+ )
+)
+
+// Default values for SummaryOpts.
+const (
+ // DefMaxAge is the default duration for which observations stay
+ // relevant.
+ DefMaxAge time.Duration = 10 * time.Minute
+ // DefAgeBuckets is the default number of buckets used to calculate the
+ // age of observations.
+ DefAgeBuckets = 5
+ // DefBufCap is the standard buffer size for collecting Summary observations.
+ DefBufCap = 500
+)
+
+// SummaryOpts bundles the options for creating a Summary metric. It is
+// mandatory to set Name and Help to a non-empty string. All other fields are
+// optional and can safely be left at their zero value.
+type SummaryOpts struct {
+ // Namespace, Subsystem, and Name are components of the fully-qualified
+ // name of the Summary (created by joining these components with
+ // "_"). Only Name is mandatory, the others merely help structuring the
+ // name. Note that the fully-qualified name of the Summary must be a
+ // valid Prometheus metric name.
+ Namespace string
+ Subsystem string
+ Name string
+
+ // Help provides information about this Summary. Mandatory!
+ //
+ // Metrics with the same fully-qualified name must have the same Help
+ // string.
+ Help string
+
+ // ConstLabels are used to attach fixed labels to this
+ // Summary. Summaries with the same fully-qualified name must have the
+ // same label names in their ConstLabels.
+ //
+ // Note that in most cases, labels have a value that varies during the
+ // lifetime of a process. Those labels are usually managed with a
+ // SummaryVec. ConstLabels serve only special purposes. One is for the
+ // special case where the value of a label does not change during the
+ // lifetime of a process, e.g. if the revision of the running binary is
+ // put into a label. Another, more advanced purpose is if more than one
+ // Collector needs to collect Summaries with the same fully-qualified
+ // name. In that case, those Summaries must differ in the values of
+ // their ConstLabels. See the Collector examples.
+ //
+ // If the value of a label never changes (not even between binaries),
+ // that label most likely should not be a label at all (but part of the
+ // metric name).
+ ConstLabels Labels
+
+ // Objectives defines the quantile rank estimates with their respective
+ // absolute error. If Objectives[q] = e, then the value reported
+ // for q will be the φ-quantile value for some φ between q-e and q+e.
+ // The default value is DefObjectives.
+ Objectives map[float64]float64
+
+ // MaxAge defines the duration for which an observation stays relevant
+ // for the summary. Must be positive. The default value is DefMaxAge.
+ MaxAge time.Duration
+
+ // AgeBuckets is the number of buckets used to exclude observations that
+ // are older than MaxAge from the summary. A higher number has a
+ // resource penalty, so only increase it if the higher resolution is
+ // really required. For very high observation rates, you might want to
+ // reduce the number of age buckets. With only one age bucket, you will
+ // effectively see a complete reset of the summary each time MaxAge has
+ // passed. The default value is DefAgeBuckets.
+ AgeBuckets uint32
+
+ // BufCap defines the default sample stream buffer size. The default
+ // value of DefBufCap should suffice for most uses. If there is a need
+ // to increase the value, a multiple of 500 is recommended (because that
+ // is the internal buffer size of the underlying package
+ // "github.com/bmizerany/perks/quantile").
+ BufCap uint32
+}
+
+// TODO: Great fuck-up with the sliding-window decay algorithm... The Merge
+// method of perk/quantile is actually not working as advertised - and it might
+// be unfixable, as the underlying algorithm is apparently not capable of
+// merging summaries in the first place. To avoid using Merge, we are currently
+// adding observations to _each_ age bucket, i.e. the effort to add a sample is
+// essentially multiplied by the number of age buckets. When rotating age
+// buckets, we empty the previous head stream. On scrape time, we simply take
+// the quantiles from the head stream (no merging required). Result: More effort
+// on observation time, less effort on scrape time, which is exactly the
+// opposite of what we try to accomplish, but at least the results are correct.
+//
+// The quite elegant previous contraption to merge the age buckets efficiently
+// on scrape time (see code up commit 6b9530d72ea715f0ba612c0120e6e09fbf1d49d0)
+// can't be used anymore.
+
+// NewSummary creates a new Summary based on the provided SummaryOpts.
+func NewSummary(opts SummaryOpts) Summary {
+ return newSummary(
+ NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ nil,
+ opts.ConstLabels,
+ ),
+ opts,
+ )
+}
+
+func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary {
+ if len(desc.variableLabels) != len(labelValues) {
+ panic(errInconsistentCardinality)
+ }
+
+ for _, n := range desc.variableLabels {
+ if n == quantileLabel {
+ panic(errQuantileLabelNotAllowed)
+ }
+ }
+ for _, lp := range desc.constLabelPairs {
+ if lp.GetName() == quantileLabel {
+ panic(errQuantileLabelNotAllowed)
+ }
+ }
+
+ if len(opts.Objectives) == 0 {
+ opts.Objectives = DefObjectives
+ }
+
+ if opts.MaxAge < 0 {
+ panic(fmt.Errorf("illegal max age MaxAge=%v", opts.MaxAge))
+ }
+ if opts.MaxAge == 0 {
+ opts.MaxAge = DefMaxAge
+ }
+
+ if opts.AgeBuckets == 0 {
+ opts.AgeBuckets = DefAgeBuckets
+ }
+
+ if opts.BufCap == 0 {
+ opts.BufCap = DefBufCap
+ }
+
+ s := &summary{
+ desc: desc,
+
+ objectives: opts.Objectives,
+ sortedObjectives: make([]float64, 0, len(opts.Objectives)),
+
+ labelPairs: makeLabelPairs(desc, labelValues),
+
+ hotBuf: make([]float64, 0, opts.BufCap),
+ coldBuf: make([]float64, 0, opts.BufCap),
+ streamDuration: opts.MaxAge / time.Duration(opts.AgeBuckets),
+ }
+ s.headStreamExpTime = time.Now().Add(s.streamDuration)
+ s.hotBufExpTime = s.headStreamExpTime
+
+ for i := uint32(0); i < opts.AgeBuckets; i++ {
+ s.streams = append(s.streams, s.newStream())
+ }
+ s.headStream = s.streams[0]
+
+ for qu := range s.objectives {
+ s.sortedObjectives = append(s.sortedObjectives, qu)
+ }
+ sort.Float64s(s.sortedObjectives)
+
+ s.Init(s) // Init self-collection.
+ return s
+}
+
+type summary struct {
+ SelfCollector
+
+ bufMtx sync.Mutex // Protects hotBuf and hotBufExpTime.
+ mtx sync.Mutex // Protects every other moving part.
+ // Lock bufMtx before mtx if both are needed.
+
+ desc *Desc
+
+ objectives map[float64]float64
+ sortedObjectives []float64
+
+ labelPairs []*dto.LabelPair
+
+ sum float64
+ cnt uint64
+
+ hotBuf, coldBuf []float64
+
+ streams []*quantile.Stream
+ streamDuration time.Duration
+ headStream *quantile.Stream
+ headStreamIdx int
+ headStreamExpTime, hotBufExpTime time.Time
+}
+
+func (s *summary) Desc() *Desc {
+ return s.desc
+}
+
+func (s *summary) Observe(v float64) {
+ s.bufMtx.Lock()
+ defer s.bufMtx.Unlock()
+
+ now := time.Now()
+ if now.After(s.hotBufExpTime) {
+ s.asyncFlush(now)
+ }
+ s.hotBuf = append(s.hotBuf, v)
+ if len(s.hotBuf) == cap(s.hotBuf) {
+ s.asyncFlush(now)
+ }
+}
+
+func (s *summary) Write(out *dto.Metric) error {
+ sum := &dto.Summary{}
+ qs := make([]*dto.Quantile, 0, len(s.objectives))
+
+ s.bufMtx.Lock()
+ s.mtx.Lock()
+ // Swap bufs even if hotBuf is empty to set new hotBufExpTime.
+ s.swapBufs(time.Now())
+ s.bufMtx.Unlock()
+
+ s.flushColdBuf()
+ sum.SampleCount = proto.Uint64(s.cnt)
+ sum.SampleSum = proto.Float64(s.sum)
+
+ for _, rank := range s.sortedObjectives {
+ var q float64
+ if s.headStream.Count() == 0 {
+ q = math.NaN()
+ } else {
+ q = s.headStream.Query(rank)
+ }
+ qs = append(qs, &dto.Quantile{
+ Quantile: proto.Float64(rank),
+ Value: proto.Float64(q),
+ })
+ }
+
+ s.mtx.Unlock()
+
+ if len(qs) > 0 {
+ sort.Sort(quantSort(qs))
+ }
+ sum.Quantile = qs
+
+ out.Summary = sum
+ out.Label = s.labelPairs
+ return nil
+}
+
+func (s *summary) newStream() *quantile.Stream {
+ return quantile.NewTargeted(s.objectives)
+}
+
+// asyncFlush needs bufMtx locked.
+func (s *summary) asyncFlush(now time.Time) {
+ s.mtx.Lock()
+ s.swapBufs(now)
+
+ // Unblock the original goroutine that was responsible for the mutation
+ // that triggered the compaction. But hold onto the global non-buffer
+ // state mutex until the operation finishes.
+ go func() {
+ s.flushColdBuf()
+ s.mtx.Unlock()
+ }()
+}
+
+// rotateStreams needs mtx AND bufMtx locked.
+func (s *summary) maybeRotateStreams() {
+ for !s.hotBufExpTime.Equal(s.headStreamExpTime) {
+ s.headStream.Reset()
+ s.headStreamIdx++
+ if s.headStreamIdx >= len(s.streams) {
+ s.headStreamIdx = 0
+ }
+ s.headStream = s.streams[s.headStreamIdx]
+ s.headStreamExpTime = s.headStreamExpTime.Add(s.streamDuration)
+ }
+}
+
+// flushColdBuf needs mtx locked.
+func (s *summary) flushColdBuf() {
+ for _, v := range s.coldBuf {
+ for _, stream := range s.streams {
+ stream.Insert(v)
+ }
+ s.cnt++
+ s.sum += v
+ }
+ s.coldBuf = s.coldBuf[0:0]
+ s.maybeRotateStreams()
+}
+
+// swapBufs needs mtx AND bufMtx locked, coldBuf must be empty.
+func (s *summary) swapBufs(now time.Time) {
+ if len(s.coldBuf) != 0 {
+ panic("coldBuf is not empty")
+ }
+ s.hotBuf, s.coldBuf = s.coldBuf, s.hotBuf
+ // hotBuf is now empty and gets new expiration set.
+ for now.After(s.hotBufExpTime) {
+ s.hotBufExpTime = s.hotBufExpTime.Add(s.streamDuration)
+ }
+}
+
+type quantSort []*dto.Quantile
+
+func (s quantSort) Len() int {
+ return len(s)
+}
+
+func (s quantSort) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+
+func (s quantSort) Less(i, j int) bool {
+ return s[i].GetQuantile() < s[j].GetQuantile()
+}
+
+// SummaryVec is a Collector that bundles a set of Summaries that all share the
+// same Desc, but have different values for their variable labels. This is used
+// if you want to count the same thing partitioned by various dimensions
+// (e.g. HTTP request latencies, partitioned by status code and method). Create
+// instances with NewSummaryVec.
+type SummaryVec struct {
+ MetricVec
+}
+
+// NewSummaryVec creates a new SummaryVec based on the provided SummaryOpts and
+// partitioned by the given label names. At least one label name must be
+// provided.
+func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec {
+ desc := NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ labelNames,
+ opts.ConstLabels,
+ )
+ return &SummaryVec{
+ MetricVec: MetricVec{
+ children: map[uint64]Metric{},
+ desc: desc,
+ newMetric: func(lvs ...string) Metric {
+ return newSummary(desc, opts, lvs...)
+ },
+ },
+ }
+}
+
+// GetMetricWithLabelValues replaces the method of the same name in
+// MetricVec. The difference is that this method returns a Summary and not a
+// Metric so that no type conversion is required.
+func (m *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Summary, error) {
+ metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...)
+ if metric != nil {
+ return metric.(Summary), err
+ }
+ return nil, err
+}
+
+// GetMetricWith replaces the method of the same name in MetricVec. The
+// difference is that this method returns a Summary and not a Metric so that no
+// type conversion is required.
+func (m *SummaryVec) GetMetricWith(labels Labels) (Summary, error) {
+ metric, err := m.MetricVec.GetMetricWith(labels)
+ if metric != nil {
+ return metric.(Summary), err
+ }
+ return nil, err
+}
+
+// WithLabelValues works as GetMetricWithLabelValues, but panics where
+// GetMetricWithLabelValues would have returned an error. By not returning an
+// error, WithLabelValues allows shortcuts like
+// myVec.WithLabelValues("404", "GET").Observe(42.21)
+func (m *SummaryVec) WithLabelValues(lvs ...string) Summary {
+ return m.MetricVec.WithLabelValues(lvs...).(Summary)
+}
+
+// With works as GetMetricWith, but panics where GetMetricWithLabels would have
+// returned an error. By not returning an error, With allows shortcuts like
+// myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21)
+func (m *SummaryVec) With(labels Labels) Summary {
+ return m.MetricVec.With(labels).(Summary)
+}
+
+type constSummary struct {
+ desc *Desc
+ count uint64
+ sum float64
+ quantiles map[float64]float64
+ labelPairs []*dto.LabelPair
+}
+
+func (s *constSummary) Desc() *Desc {
+ return s.desc
+}
+
+func (s *constSummary) Write(out *dto.Metric) error {
+ sum := &dto.Summary{}
+ qs := make([]*dto.Quantile, 0, len(s.quantiles))
+
+ sum.SampleCount = proto.Uint64(s.count)
+ sum.SampleSum = proto.Float64(s.sum)
+
+ for rank, q := range s.quantiles {
+ qs = append(qs, &dto.Quantile{
+ Quantile: proto.Float64(rank),
+ Value: proto.Float64(q),
+ })
+ }
+
+ if len(qs) > 0 {
+ sort.Sort(quantSort(qs))
+ }
+ sum.Quantile = qs
+
+ out.Summary = sum
+ out.Label = s.labelPairs
+
+ return nil
+}
+
+// NewConstSummary returns a metric representing a Prometheus summary with fixed
+// values for the count, sum, and quantiles. As those parameters cannot be
+// changed, the returned value does not implement the Summary interface (but
+// only the Metric interface). Users of this package will not have much use for
+// it in regular operations. However, when implementing custom Collectors, it is
+// useful as a throw-away metric that is generated on the fly to send it to
+// Prometheus in the Collect method.
+//
+// quantiles maps ranks to quantile values. For example, a median latency of
+// 0.23s and a 99th percentile latency of 0.56s would be expressed as:
+// map[float64]float64{0.5: 0.23, 0.99: 0.56}
+//
+// NewConstSummary returns an error if the length of labelValues is not
+// consistent with the variable labels in Desc.
+func NewConstSummary(
+ desc *Desc,
+ count uint64,
+ sum float64,
+ quantiles map[float64]float64,
+ labelValues ...string,
+) (Metric, error) {
+ if len(desc.variableLabels) != len(labelValues) {
+ return nil, errInconsistentCardinality
+ }
+ return &constSummary{
+ desc: desc,
+ count: count,
+ sum: sum,
+ quantiles: quantiles,
+ labelPairs: makeLabelPairs(desc, labelValues),
+ }, nil
+}
+
+// MustNewConstSummary is a version of NewConstSummary that panics where
+// NewConstMetric would have returned an error.
+func MustNewConstSummary(
+ desc *Desc,
+ count uint64,
+ sum float64,
+ quantiles map[float64]float64,
+ labelValues ...string,
+) Metric {
+ m, err := NewConstSummary(desc, count, sum, quantiles, labelValues...)
+ if err != nil {
+ panic(err)
+ }
+ return m
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/untyped.go b/vendor/github.com/prometheus/client_golang/prometheus/untyped.go
new file mode 100644
index 0000000..89b86ea
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/untyped.go
@@ -0,0 +1,142 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+// Untyped is a Metric that represents a single numerical value that can
+// arbitrarily go up and down.
+//
+// An Untyped metric works the same as a Gauge. The only difference is that to
+// no type information is implied.
+//
+// To create Untyped instances, use NewUntyped.
+type Untyped interface {
+ Metric
+ Collector
+
+ // Set sets the Untyped metric to an arbitrary value.
+ Set(float64)
+ // Inc increments the Untyped metric by 1.
+ Inc()
+ // Dec decrements the Untyped metric by 1.
+ Dec()
+ // Add adds the given value to the Untyped metric. (The value can be
+ // negative, resulting in a decrease.)
+ Add(float64)
+ // Sub subtracts the given value from the Untyped metric. (The value can
+ // be negative, resulting in an increase.)
+ Sub(float64)
+}
+
+// UntypedOpts is an alias for Opts. See there for doc comments.
+type UntypedOpts Opts
+
+// NewUntyped creates a new Untyped metric from the provided UntypedOpts.
+func NewUntyped(opts UntypedOpts) Untyped {
+ return newValue(NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ nil,
+ opts.ConstLabels,
+ ), UntypedValue, 0)
+}
+
+// UntypedVec is a Collector that bundles a set of Untyped metrics that all
+// share the same Desc, but have different values for their variable
+// labels. This is used if you want to count the same thing partitioned by
+// various dimensions. Create instances with NewUntypedVec.
+type UntypedVec struct {
+ MetricVec
+}
+
+// NewUntypedVec creates a new UntypedVec based on the provided UntypedOpts and
+// partitioned by the given label names. At least one label name must be
+// provided.
+func NewUntypedVec(opts UntypedOpts, labelNames []string) *UntypedVec {
+ desc := NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ labelNames,
+ opts.ConstLabels,
+ )
+ return &UntypedVec{
+ MetricVec: MetricVec{
+ children: map[uint64]Metric{},
+ desc: desc,
+ newMetric: func(lvs ...string) Metric {
+ return newValue(desc, UntypedValue, 0, lvs...)
+ },
+ },
+ }
+}
+
+// GetMetricWithLabelValues replaces the method of the same name in
+// MetricVec. The difference is that this method returns an Untyped and not a
+// Metric so that no type conversion is required.
+func (m *UntypedVec) GetMetricWithLabelValues(lvs ...string) (Untyped, error) {
+ metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...)
+ if metric != nil {
+ return metric.(Untyped), err
+ }
+ return nil, err
+}
+
+// GetMetricWith replaces the method of the same name in MetricVec. The
+// difference is that this method returns an Untyped and not a Metric so that no
+// type conversion is required.
+func (m *UntypedVec) GetMetricWith(labels Labels) (Untyped, error) {
+ metric, err := m.MetricVec.GetMetricWith(labels)
+ if metric != nil {
+ return metric.(Untyped), err
+ }
+ return nil, err
+}
+
+// WithLabelValues works as GetMetricWithLabelValues, but panics where
+// GetMetricWithLabelValues would have returned an error. By not returning an
+// error, WithLabelValues allows shortcuts like
+// myVec.WithLabelValues("404", "GET").Add(42)
+func (m *UntypedVec) WithLabelValues(lvs ...string) Untyped {
+ return m.MetricVec.WithLabelValues(lvs...).(Untyped)
+}
+
+// With works as GetMetricWith, but panics where GetMetricWithLabels would have
+// returned an error. By not returning an error, With allows shortcuts like
+// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
+func (m *UntypedVec) With(labels Labels) Untyped {
+ return m.MetricVec.With(labels).(Untyped)
+}
+
+// UntypedFunc is an Untyped whose value is determined at collect time by
+// calling a provided function.
+//
+// To create UntypedFunc instances, use NewUntypedFunc.
+type UntypedFunc interface {
+ Metric
+ Collector
+}
+
+// NewUntypedFunc creates a new UntypedFunc based on the provided
+// UntypedOpts. The value reported is determined by calling the given function
+// from within the Write method. Take into account that metric collection may
+// happen concurrently. If that results in concurrent calls to Write, like in
+// the case where an UntypedFunc is directly registered with Prometheus, the
+// provided function must be concurrency-safe.
+func NewUntypedFunc(opts UntypedOpts, function func() float64) UntypedFunc {
+ return newValueFunc(NewDesc(
+ BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+ opts.Help,
+ nil,
+ opts.ConstLabels,
+ ), UntypedValue, function)
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/value.go b/vendor/github.com/prometheus/client_golang/prometheus/value.go
new file mode 100644
index 0000000..b54ac11
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/value.go
@@ -0,0 +1,234 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "sort"
+ "sync/atomic"
+
+ dto "github.com/prometheus/client_model/go"
+
+ "github.com/golang/protobuf/proto"
+)
+
+// ValueType is an enumeration of metric types that represent a simple value.
+type ValueType int
+
+// Possible values for the ValueType enum.
+const (
+ _ ValueType = iota
+ CounterValue
+ GaugeValue
+ UntypedValue
+)
+
+var errInconsistentCardinality = errors.New("inconsistent label cardinality")
+
+// value is a generic metric for simple values. It implements Metric, Collector,
+// Counter, Gauge, and Untyped. Its effective type is determined by
+// ValueType. This is a low-level building block used by the library to back the
+// implementations of Counter, Gauge, and Untyped.
+type value struct {
+ // valBits containst the bits of the represented float64 value. It has
+ // to go first in the struct to guarantee alignment for atomic
+ // operations. http://golang.org/pkg/sync/atomic/#pkg-note-BUG
+ valBits uint64
+
+ SelfCollector
+
+ desc *Desc
+ valType ValueType
+ labelPairs []*dto.LabelPair
+}
+
+// newValue returns a newly allocated value with the given Desc, ValueType,
+// sample value and label values. It panics if the number of label
+// values is different from the number of variable labels in Desc.
+func newValue(desc *Desc, valueType ValueType, val float64, labelValues ...string) *value {
+ if len(labelValues) != len(desc.variableLabels) {
+ panic(errInconsistentCardinality)
+ }
+ result := &value{
+ desc: desc,
+ valType: valueType,
+ valBits: math.Float64bits(val),
+ labelPairs: makeLabelPairs(desc, labelValues),
+ }
+ result.Init(result)
+ return result
+}
+
+func (v *value) Desc() *Desc {
+ return v.desc
+}
+
+func (v *value) Set(val float64) {
+ atomic.StoreUint64(&v.valBits, math.Float64bits(val))
+}
+
+func (v *value) Inc() {
+ v.Add(1)
+}
+
+func (v *value) Dec() {
+ v.Add(-1)
+}
+
+func (v *value) Add(val float64) {
+ for {
+ oldBits := atomic.LoadUint64(&v.valBits)
+ newBits := math.Float64bits(math.Float64frombits(oldBits) + val)
+ if atomic.CompareAndSwapUint64(&v.valBits, oldBits, newBits) {
+ return
+ }
+ }
+}
+
+func (v *value) Sub(val float64) {
+ v.Add(val * -1)
+}
+
+func (v *value) Write(out *dto.Metric) error {
+ val := math.Float64frombits(atomic.LoadUint64(&v.valBits))
+ return populateMetric(v.valType, val, v.labelPairs, out)
+}
+
+// valueFunc is a generic metric for simple values retrieved on collect time
+// from a function. It implements Metric and Collector. Its effective type is
+// determined by ValueType. This is a low-level building block used by the
+// library to back the implementations of CounterFunc, GaugeFunc, and
+// UntypedFunc.
+type valueFunc struct {
+ SelfCollector
+
+ desc *Desc
+ valType ValueType
+ function func() float64
+ labelPairs []*dto.LabelPair
+}
+
+// newValueFunc returns a newly allocated valueFunc with the given Desc and
+// ValueType. The value reported is determined by calling the given function
+// from within the Write method. Take into account that metric collection may
+// happen concurrently. If that results in concurrent calls to Write, like in
+// the case where a valueFunc is directly registered with Prometheus, the
+// provided function must be concurrency-safe.
+func newValueFunc(desc *Desc, valueType ValueType, function func() float64) *valueFunc {
+ result := &valueFunc{
+ desc: desc,
+ valType: valueType,
+ function: function,
+ labelPairs: makeLabelPairs(desc, nil),
+ }
+ result.Init(result)
+ return result
+}
+
+func (v *valueFunc) Desc() *Desc {
+ return v.desc
+}
+
+func (v *valueFunc) Write(out *dto.Metric) error {
+ return populateMetric(v.valType, v.function(), v.labelPairs, out)
+}
+
+// NewConstMetric returns a metric with one fixed value that cannot be
+// changed. Users of this package will not have much use for it in regular
+// operations. However, when implementing custom Collectors, it is useful as a
+// throw-away metric that is generated on the fly to send it to Prometheus in
+// the Collect method. NewConstMetric returns an error if the length of
+// labelValues is not consistent with the variable labels in Desc.
+func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error) {
+ if len(desc.variableLabels) != len(labelValues) {
+ return nil, errInconsistentCardinality
+ }
+ return &constMetric{
+ desc: desc,
+ valType: valueType,
+ val: value,
+ labelPairs: makeLabelPairs(desc, labelValues),
+ }, nil
+}
+
+// MustNewConstMetric is a version of NewConstMetric that panics where
+// NewConstMetric would have returned an error.
+func MustNewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric {
+ m, err := NewConstMetric(desc, valueType, value, labelValues...)
+ if err != nil {
+ panic(err)
+ }
+ return m
+}
+
+type constMetric struct {
+ desc *Desc
+ valType ValueType
+ val float64
+ labelPairs []*dto.LabelPair
+}
+
+func (m *constMetric) Desc() *Desc {
+ return m.desc
+}
+
+func (m *constMetric) Write(out *dto.Metric) error {
+ return populateMetric(m.valType, m.val, m.labelPairs, out)
+}
+
+func populateMetric(
+ t ValueType,
+ v float64,
+ labelPairs []*dto.LabelPair,
+ m *dto.Metric,
+) error {
+ m.Label = labelPairs
+ switch t {
+ case CounterValue:
+ m.Counter = &dto.Counter{Value: proto.Float64(v)}
+ case GaugeValue:
+ m.Gauge = &dto.Gauge{Value: proto.Float64(v)}
+ case UntypedValue:
+ m.Untyped = &dto.Untyped{Value: proto.Float64(v)}
+ default:
+ return fmt.Errorf("encountered unknown type %v", t)
+ }
+ return nil
+}
+
+func makeLabelPairs(desc *Desc, labelValues []string) []*dto.LabelPair {
+ totalLen := len(desc.variableLabels) + len(desc.constLabelPairs)
+ if totalLen == 0 {
+ // Super fast path.
+ return nil
+ }
+ if len(desc.variableLabels) == 0 {
+ // Moderately fast path.
+ return desc.constLabelPairs
+ }
+ labelPairs := make([]*dto.LabelPair, 0, totalLen)
+ for i, n := range desc.variableLabels {
+ labelPairs = append(labelPairs, &dto.LabelPair{
+ Name: proto.String(n),
+ Value: proto.String(labelValues[i]),
+ })
+ }
+ for _, lp := range desc.constLabelPairs {
+ labelPairs = append(labelPairs, lp)
+ }
+ sort.Sort(LabelPairSorter(labelPairs))
+ return labelPairs
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/vec.go b/vendor/github.com/prometheus/client_golang/prometheus/vec.go
new file mode 100644
index 0000000..68f9461
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/vec.go
@@ -0,0 +1,249 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+ "fmt"
+ "sync"
+)
+
+// MetricVec is a Collector to bundle metrics of the same name that
+// differ in their label values. MetricVec is usually not used directly but as a
+// building block for implementations of vectors of a given metric
+// type. GaugeVec, CounterVec, SummaryVec, and UntypedVec are examples already
+// provided in this package.
+type MetricVec struct {
+ mtx sync.RWMutex // Protects the children.
+ children map[uint64]Metric
+ desc *Desc
+
+ newMetric func(labelValues ...string) Metric
+}
+
+// Describe implements Collector. The length of the returned slice
+// is always one.
+func (m *MetricVec) Describe(ch chan<- *Desc) {
+ ch <- m.desc
+}
+
+// Collect implements Collector.
+func (m *MetricVec) Collect(ch chan<- Metric) {
+ m.mtx.RLock()
+ defer m.mtx.RUnlock()
+
+ for _, metric := range m.children {
+ ch <- metric
+ }
+}
+
+// GetMetricWithLabelValues returns the Metric for the given slice of label
+// values (same order as the VariableLabels in Desc). If that combination of
+// label values is accessed for the first time, a new Metric is created.
+//
+// It is possible to call this method without using the returned Metric to only
+// create the new Metric but leave it at its start value (e.g. a Summary or
+// Histogram without any observations). See also the SummaryVec example.
+//
+// Keeping the Metric for later use is possible (and should be considered if
+// performance is critical), but keep in mind that Reset, DeleteLabelValues and
+// Delete can be used to delete the Metric from the MetricVec. In that case, the
+// Metric will still exist, but it will not be exported anymore, even if a
+// Metric with the same label values is created later. See also the CounterVec
+// example.
+//
+// An error is returned if the number of label values is not the same as the
+// number of VariableLabels in Desc.
+//
+// Note that for more than one label value, this method is prone to mistakes
+// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
+// an alternative to avoid that type of mistake. For higher label numbers, the
+// latter has a much more readable (albeit more verbose) syntax, but it comes
+// with a performance overhead (for creating and processing the Labels map).
+// See also the GaugeVec example.
+func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error) {
+ h, err := m.hashLabelValues(lvs)
+ if err != nil {
+ return nil, err
+ }
+
+ m.mtx.RLock()
+ metric, ok := m.children[h]
+ m.mtx.RUnlock()
+ if ok {
+ return metric, nil
+ }
+
+ m.mtx.Lock()
+ defer m.mtx.Unlock()
+ return m.getOrCreateMetric(h, lvs...), nil
+}
+
+// GetMetricWith returns the Metric for the given Labels map (the label names
+// must match those of the VariableLabels in Desc). If that label map is
+// accessed for the first time, a new Metric is created. Implications of
+// creating a Metric without using it and keeping the Metric for later use are
+// the same as for GetMetricWithLabelValues.
+//
+// An error is returned if the number and names of the Labels are inconsistent
+// with those of the VariableLabels in Desc.
+//
+// This method is used for the same purpose as
+// GetMetricWithLabelValues(...string). See there for pros and cons of the two
+// methods.
+func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error) {
+ h, err := m.hashLabels(labels)
+ if err != nil {
+ return nil, err
+ }
+
+ m.mtx.RLock()
+ metric, ok := m.children[h]
+ m.mtx.RUnlock()
+ if ok {
+ return metric, nil
+ }
+
+ lvs := make([]string, len(labels))
+ for i, label := range m.desc.variableLabels {
+ lvs[i] = labels[label]
+ }
+ m.mtx.Lock()
+ defer m.mtx.Unlock()
+ return m.getOrCreateMetric(h, lvs...), nil
+}
+
+// WithLabelValues works as GetMetricWithLabelValues, but panics if an error
+// occurs. The method allows neat syntax like:
+// httpReqs.WithLabelValues("404", "POST").Inc()
+func (m *MetricVec) WithLabelValues(lvs ...string) Metric {
+ metric, err := m.GetMetricWithLabelValues(lvs...)
+ if err != nil {
+ panic(err)
+ }
+ return metric
+}
+
+// With works as GetMetricWith, but panics if an error occurs. The method allows
+// neat syntax like:
+// httpReqs.With(Labels{"status":"404", "method":"POST"}).Inc()
+func (m *MetricVec) With(labels Labels) Metric {
+ metric, err := m.GetMetricWith(labels)
+ if err != nil {
+ panic(err)
+ }
+ return metric
+}
+
+// DeleteLabelValues removes the metric where the variable labels are the same
+// as those passed in as labels (same order as the VariableLabels in Desc). It
+// returns true if a metric was deleted.
+//
+// It is not an error if the number of label values is not the same as the
+// number of VariableLabels in Desc. However, such inconsistent label count can
+// never match an actual Metric, so the method will always return false in that
+// case.
+//
+// Note that for more than one label value, this method is prone to mistakes
+// caused by an incorrect order of arguments. Consider Delete(Labels) as an
+// alternative to avoid that type of mistake. For higher label numbers, the
+// latter has a much more readable (albeit more verbose) syntax, but it comes
+// with a performance overhead (for creating and processing the Labels map).
+// See also the CounterVec example.
+func (m *MetricVec) DeleteLabelValues(lvs ...string) bool {
+ m.mtx.Lock()
+ defer m.mtx.Unlock()
+
+ h, err := m.hashLabelValues(lvs)
+ if err != nil {
+ return false
+ }
+ if _, ok := m.children[h]; !ok {
+ return false
+ }
+ delete(m.children, h)
+ return true
+}
+
+// Delete deletes the metric where the variable labels are the same as those
+// passed in as labels. It returns true if a metric was deleted.
+//
+// It is not an error if the number and names of the Labels are inconsistent
+// with those of the VariableLabels in the Desc of the MetricVec. However, such
+// inconsistent Labels can never match an actual Metric, so the method will
+// always return false in that case.
+//
+// This method is used for the same purpose as DeleteLabelValues(...string). See
+// there for pros and cons of the two methods.
+func (m *MetricVec) Delete(labels Labels) bool {
+ m.mtx.Lock()
+ defer m.mtx.Unlock()
+
+ h, err := m.hashLabels(labels)
+ if err != nil {
+ return false
+ }
+ if _, ok := m.children[h]; !ok {
+ return false
+ }
+ delete(m.children, h)
+ return true
+}
+
+// Reset deletes all metrics in this vector.
+func (m *MetricVec) Reset() {
+ m.mtx.Lock()
+ defer m.mtx.Unlock()
+
+ for h := range m.children {
+ delete(m.children, h)
+ }
+}
+
+func (m *MetricVec) hashLabelValues(vals []string) (uint64, error) {
+ if len(vals) != len(m.desc.variableLabels) {
+ return 0, errInconsistentCardinality
+ }
+ h := hashNew()
+ for _, val := range vals {
+ h = hashAdd(h, val)
+ }
+ return h, nil
+}
+
+func (m *MetricVec) hashLabels(labels Labels) (uint64, error) {
+ if len(labels) != len(m.desc.variableLabels) {
+ return 0, errInconsistentCardinality
+ }
+ h := hashNew()
+ for _, label := range m.desc.variableLabels {
+ val, ok := labels[label]
+ if !ok {
+ return 0, fmt.Errorf("label name %q missing in label map", label)
+ }
+ h = hashAdd(h, val)
+ }
+ return h, nil
+}
+
+func (m *MetricVec) getOrCreateMetric(hash uint64, labelValues ...string) Metric {
+ metric, ok := m.children[hash]
+ if !ok {
+ // Copy labelValues. Otherwise, they would be allocated even if we don't go
+ // down this code path.
+ copiedLabelValues := append(make([]string, 0, len(labelValues)), labelValues...)
+ metric = m.newMetric(copiedLabelValues...)
+ m.children[hash] = metric
+ }
+ return metric
+}
diff --git a/vendor/github.com/prometheus/client_model/LICENSE b/vendor/github.com/prometheus/client_model/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/prometheus/client_model/NOTICE b/vendor/github.com/prometheus/client_model/NOTICE
new file mode 100644
index 0000000..20110e4
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/NOTICE
@@ -0,0 +1,5 @@
+Data model artifacts for Prometheus.
+Copyright 2012-2015 The Prometheus Authors
+
+This product includes software developed at
+SoundCloud Ltd. (http://soundcloud.com/).
diff --git a/vendor/github.com/prometheus/client_model/README.md b/vendor/github.com/prometheus/client_model/README.md
new file mode 100644
index 0000000..a710042
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/README.md
@@ -0,0 +1,26 @@
+# Background
+Under most circumstances, manually downloading this repository should never
+be required.
+
+# Prerequisites
+# Base
+* [Google Protocol Buffers](https://developers.google.com/protocol-buffers)
+
+## Java
+* [Apache Maven](http://maven.apache.org)
+* [Prometheus Maven Repository](https://github.com/prometheus/io.prometheus-maven-repository) checked out into ../io.prometheus-maven-repository
+
+## Go
+* [Go](http://golang.org)
+* [goprotobuf](https://code.google.com/p/goprotobuf)
+
+## Ruby
+* [Ruby](https://www.ruby-lang.org)
+* [bundler](https://rubygems.org/gems/bundler)
+
+# Building
+ $ make
+
+# Getting Started
+ * The Go source code is periodically indexed: [Go Protocol Buffer Model](http://godoc.org/github.com/prometheus/client_model/go).
+ * All of the core developers are accessible via the [Prometheus Developers Mailinglist](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers).
diff --git a/vendor/github.com/prometheus/client_model/go/metrics.pb.go b/vendor/github.com/prometheus/client_model/go/metrics.pb.go
new file mode 100644
index 0000000..b065f86
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/go/metrics.pb.go
@@ -0,0 +1,364 @@
+// Code generated by protoc-gen-go.
+// source: metrics.proto
+// DO NOT EDIT!
+
+/*
+Package io_prometheus_client is a generated protocol buffer package.
+
+It is generated from these files:
+ metrics.proto
+
+It has these top-level messages:
+ LabelPair
+ Gauge
+ Counter
+ Quantile
+ Summary
+ Untyped
+ Histogram
+ Bucket
+ Metric
+ MetricFamily
+*/
+package io_prometheus_client
+
+import proto "github.com/golang/protobuf/proto"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = math.Inf
+
+type MetricType int32
+
+const (
+ MetricType_COUNTER MetricType = 0
+ MetricType_GAUGE MetricType = 1
+ MetricType_SUMMARY MetricType = 2
+ MetricType_UNTYPED MetricType = 3
+ MetricType_HISTOGRAM MetricType = 4
+)
+
+var MetricType_name = map[int32]string{
+ 0: "COUNTER",
+ 1: "GAUGE",
+ 2: "SUMMARY",
+ 3: "UNTYPED",
+ 4: "HISTOGRAM",
+}
+var MetricType_value = map[string]int32{
+ "COUNTER": 0,
+ "GAUGE": 1,
+ "SUMMARY": 2,
+ "UNTYPED": 3,
+ "HISTOGRAM": 4,
+}
+
+func (x MetricType) Enum() *MetricType {
+ p := new(MetricType)
+ *p = x
+ return p
+}
+func (x MetricType) String() string {
+ return proto.EnumName(MetricType_name, int32(x))
+}
+func (x *MetricType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(MetricType_value, data, "MetricType")
+ if err != nil {
+ return err
+ }
+ *x = MetricType(value)
+ return nil
+}
+
+type LabelPair struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Value *string `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *LabelPair) Reset() { *m = LabelPair{} }
+func (m *LabelPair) String() string { return proto.CompactTextString(m) }
+func (*LabelPair) ProtoMessage() {}
+
+func (m *LabelPair) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *LabelPair) GetValue() string {
+ if m != nil && m.Value != nil {
+ return *m.Value
+ }
+ return ""
+}
+
+type Gauge struct {
+ Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Gauge) Reset() { *m = Gauge{} }
+func (m *Gauge) String() string { return proto.CompactTextString(m) }
+func (*Gauge) ProtoMessage() {}
+
+func (m *Gauge) GetValue() float64 {
+ if m != nil && m.Value != nil {
+ return *m.Value
+ }
+ return 0
+}
+
+type Counter struct {
+ Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Counter) Reset() { *m = Counter{} }
+func (m *Counter) String() string { return proto.CompactTextString(m) }
+func (*Counter) ProtoMessage() {}
+
+func (m *Counter) GetValue() float64 {
+ if m != nil && m.Value != nil {
+ return *m.Value
+ }
+ return 0
+}
+
+type Quantile struct {
+ Quantile *float64 `protobuf:"fixed64,1,opt,name=quantile" json:"quantile,omitempty"`
+ Value *float64 `protobuf:"fixed64,2,opt,name=value" json:"value,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Quantile) Reset() { *m = Quantile{} }
+func (m *Quantile) String() string { return proto.CompactTextString(m) }
+func (*Quantile) ProtoMessage() {}
+
+func (m *Quantile) GetQuantile() float64 {
+ if m != nil && m.Quantile != nil {
+ return *m.Quantile
+ }
+ return 0
+}
+
+func (m *Quantile) GetValue() float64 {
+ if m != nil && m.Value != nil {
+ return *m.Value
+ }
+ return 0
+}
+
+type Summary struct {
+ SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count" json:"sample_count,omitempty"`
+ SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum" json:"sample_sum,omitempty"`
+ Quantile []*Quantile `protobuf:"bytes,3,rep,name=quantile" json:"quantile,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Summary) Reset() { *m = Summary{} }
+func (m *Summary) String() string { return proto.CompactTextString(m) }
+func (*Summary) ProtoMessage() {}
+
+func (m *Summary) GetSampleCount() uint64 {
+ if m != nil && m.SampleCount != nil {
+ return *m.SampleCount
+ }
+ return 0
+}
+
+func (m *Summary) GetSampleSum() float64 {
+ if m != nil && m.SampleSum != nil {
+ return *m.SampleSum
+ }
+ return 0
+}
+
+func (m *Summary) GetQuantile() []*Quantile {
+ if m != nil {
+ return m.Quantile
+ }
+ return nil
+}
+
+type Untyped struct {
+ Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Untyped) Reset() { *m = Untyped{} }
+func (m *Untyped) String() string { return proto.CompactTextString(m) }
+func (*Untyped) ProtoMessage() {}
+
+func (m *Untyped) GetValue() float64 {
+ if m != nil && m.Value != nil {
+ return *m.Value
+ }
+ return 0
+}
+
+type Histogram struct {
+ SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count" json:"sample_count,omitempty"`
+ SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum" json:"sample_sum,omitempty"`
+ Bucket []*Bucket `protobuf:"bytes,3,rep,name=bucket" json:"bucket,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Histogram) Reset() { *m = Histogram{} }
+func (m *Histogram) String() string { return proto.CompactTextString(m) }
+func (*Histogram) ProtoMessage() {}
+
+func (m *Histogram) GetSampleCount() uint64 {
+ if m != nil && m.SampleCount != nil {
+ return *m.SampleCount
+ }
+ return 0
+}
+
+func (m *Histogram) GetSampleSum() float64 {
+ if m != nil && m.SampleSum != nil {
+ return *m.SampleSum
+ }
+ return 0
+}
+
+func (m *Histogram) GetBucket() []*Bucket {
+ if m != nil {
+ return m.Bucket
+ }
+ return nil
+}
+
+type Bucket struct {
+ CumulativeCount *uint64 `protobuf:"varint,1,opt,name=cumulative_count" json:"cumulative_count,omitempty"`
+ UpperBound *float64 `protobuf:"fixed64,2,opt,name=upper_bound" json:"upper_bound,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Bucket) Reset() { *m = Bucket{} }
+func (m *Bucket) String() string { return proto.CompactTextString(m) }
+func (*Bucket) ProtoMessage() {}
+
+func (m *Bucket) GetCumulativeCount() uint64 {
+ if m != nil && m.CumulativeCount != nil {
+ return *m.CumulativeCount
+ }
+ return 0
+}
+
+func (m *Bucket) GetUpperBound() float64 {
+ if m != nil && m.UpperBound != nil {
+ return *m.UpperBound
+ }
+ return 0
+}
+
+type Metric struct {
+ Label []*LabelPair `protobuf:"bytes,1,rep,name=label" json:"label,omitempty"`
+ Gauge *Gauge `protobuf:"bytes,2,opt,name=gauge" json:"gauge,omitempty"`
+ Counter *Counter `protobuf:"bytes,3,opt,name=counter" json:"counter,omitempty"`
+ Summary *Summary `protobuf:"bytes,4,opt,name=summary" json:"summary,omitempty"`
+ Untyped *Untyped `protobuf:"bytes,5,opt,name=untyped" json:"untyped,omitempty"`
+ Histogram *Histogram `protobuf:"bytes,7,opt,name=histogram" json:"histogram,omitempty"`
+ TimestampMs *int64 `protobuf:"varint,6,opt,name=timestamp_ms" json:"timestamp_ms,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Metric) Reset() { *m = Metric{} }
+func (m *Metric) String() string { return proto.CompactTextString(m) }
+func (*Metric) ProtoMessage() {}
+
+func (m *Metric) GetLabel() []*LabelPair {
+ if m != nil {
+ return m.Label
+ }
+ return nil
+}
+
+func (m *Metric) GetGauge() *Gauge {
+ if m != nil {
+ return m.Gauge
+ }
+ return nil
+}
+
+func (m *Metric) GetCounter() *Counter {
+ if m != nil {
+ return m.Counter
+ }
+ return nil
+}
+
+func (m *Metric) GetSummary() *Summary {
+ if m != nil {
+ return m.Summary
+ }
+ return nil
+}
+
+func (m *Metric) GetUntyped() *Untyped {
+ if m != nil {
+ return m.Untyped
+ }
+ return nil
+}
+
+func (m *Metric) GetHistogram() *Histogram {
+ if m != nil {
+ return m.Histogram
+ }
+ return nil
+}
+
+func (m *Metric) GetTimestampMs() int64 {
+ if m != nil && m.TimestampMs != nil {
+ return *m.TimestampMs
+ }
+ return 0
+}
+
+type MetricFamily struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Help *string `protobuf:"bytes,2,opt,name=help" json:"help,omitempty"`
+ Type *MetricType `protobuf:"varint,3,opt,name=type,enum=io.prometheus.client.MetricType" json:"type,omitempty"`
+ Metric []*Metric `protobuf:"bytes,4,rep,name=metric" json:"metric,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MetricFamily) Reset() { *m = MetricFamily{} }
+func (m *MetricFamily) String() string { return proto.CompactTextString(m) }
+func (*MetricFamily) ProtoMessage() {}
+
+func (m *MetricFamily) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *MetricFamily) GetHelp() string {
+ if m != nil && m.Help != nil {
+ return *m.Help
+ }
+ return ""
+}
+
+func (m *MetricFamily) GetType() MetricType {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return MetricType_COUNTER
+}
+
+func (m *MetricFamily) GetMetric() []*Metric {
+ if m != nil {
+ return m.Metric
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterEnum("io.prometheus.client.MetricType", MetricType_name, MetricType_value)
+}
diff --git a/vendor/github.com/prometheus/common/LICENSE b/vendor/github.com/prometheus/common/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/vendor/github.com/prometheus/common/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/prometheus/common/NOTICE b/vendor/github.com/prometheus/common/NOTICE
new file mode 100644
index 0000000..636a2c1
--- /dev/null
+++ b/vendor/github.com/prometheus/common/NOTICE
@@ -0,0 +1,5 @@
+Common libraries shared by Prometheus Go components.
+Copyright 2015 The Prometheus Authors
+
+This product includes software developed at
+SoundCloud Ltd. (http://soundcloud.com/).
diff --git a/vendor/github.com/prometheus/common/README.md b/vendor/github.com/prometheus/common/README.md
new file mode 100644
index 0000000..98f6ce2
--- /dev/null
+++ b/vendor/github.com/prometheus/common/README.md
@@ -0,0 +1,12 @@
+# Common
+[![Build Status](https://travis-ci.org/prometheus/common.svg)](https://travis-ci.org/prometheus/common)
+
+This repository contains Go libraries that are shared across Prometheus
+components and libraries.
+
+* **config**: Common configuration structures
+* **expfmt**: Decoding and encoding for the exposition format
+* **log**: A logging wrapper around [logrus](https://github.com/Sirupsen/logrus)
+* **model**: Shared data structures
+* **route**: A routing wrapper around [httprouter](https://github.com/julienschmidt/httprouter) using `context.Context`
+* **version**: Version informations and metric
diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go
new file mode 100644
index 0000000..487fdc6
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/decode.go
@@ -0,0 +1,412 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package expfmt
+
+import (
+ "fmt"
+ "io"
+ "math"
+ "mime"
+ "net/http"
+
+ dto "github.com/prometheus/client_model/go"
+
+ "github.com/matttproud/golang_protobuf_extensions/pbutil"
+ "github.com/prometheus/common/model"
+)
+
+// Decoder types decode an input stream into metric families.
+type Decoder interface {
+ Decode(*dto.MetricFamily) error
+}
+
+type DecodeOptions struct {
+ // Timestamp is added to each value from the stream that has no explicit timestamp set.
+ Timestamp model.Time
+}
+
+// ResponseFormat extracts the correct format from a HTTP response header.
+// If no matching format can be found FormatUnknown is returned.
+func ResponseFormat(h http.Header) Format {
+ ct := h.Get(hdrContentType)
+
+ mediatype, params, err := mime.ParseMediaType(ct)
+ if err != nil {
+ return FmtUnknown
+ }
+
+ const textType = "text/plain"
+
+ switch mediatype {
+ case ProtoType:
+ if p, ok := params["proto"]; ok && p != ProtoProtocol {
+ return FmtUnknown
+ }
+ if e, ok := params["encoding"]; ok && e != "delimited" {
+ return FmtUnknown
+ }
+ return FmtProtoDelim
+
+ case textType:
+ if v, ok := params["version"]; ok && v != TextVersion {
+ return FmtUnknown
+ }
+ return FmtText
+ }
+
+ return FmtUnknown
+}
+
+// NewDecoder returns a new decoder based on the given input format.
+// If the input format does not imply otherwise, a text format decoder is returned.
+func NewDecoder(r io.Reader, format Format) Decoder {
+ switch format {
+ case FmtProtoDelim:
+ return &protoDecoder{r: r}
+ }
+ return &textDecoder{r: r}
+}
+
+// protoDecoder implements the Decoder interface for protocol buffers.
+type protoDecoder struct {
+ r io.Reader
+}
+
+// Decode implements the Decoder interface.
+func (d *protoDecoder) Decode(v *dto.MetricFamily) error {
+ _, err := pbutil.ReadDelimited(d.r, v)
+ if err != nil {
+ return err
+ }
+ if !model.IsValidMetricName(model.LabelValue(v.GetName())) {
+ return fmt.Errorf("invalid metric name %q", v.GetName())
+ }
+ for _, m := range v.GetMetric() {
+ if m == nil {
+ continue
+ }
+ for _, l := range m.GetLabel() {
+ if l == nil {
+ continue
+ }
+ if !model.LabelValue(l.GetValue()).IsValid() {
+ return fmt.Errorf("invalid label value %q", l.GetValue())
+ }
+ if !model.LabelName(l.GetName()).IsValid() {
+ return fmt.Errorf("invalid label name %q", l.GetName())
+ }
+ }
+ }
+ return nil
+}
+
+// textDecoder implements the Decoder interface for the text protocol.
+type textDecoder struct {
+ r io.Reader
+ p TextParser
+ fams []*dto.MetricFamily
+}
+
+// Decode implements the Decoder interface.
+func (d *textDecoder) Decode(v *dto.MetricFamily) error {
+ // TODO(fabxc): Wrap this as a line reader to make streaming safer.
+ if len(d.fams) == 0 {
+ // No cached metric families, read everything and parse metrics.
+ fams, err := d.p.TextToMetricFamilies(d.r)
+ if err != nil {
+ return err
+ }
+ if len(fams) == 0 {
+ return io.EOF
+ }
+ d.fams = make([]*dto.MetricFamily, 0, len(fams))
+ for _, f := range fams {
+ d.fams = append(d.fams, f)
+ }
+ }
+
+ *v = *d.fams[0]
+ d.fams = d.fams[1:]
+
+ return nil
+}
+
+type SampleDecoder struct {
+ Dec Decoder
+ Opts *DecodeOptions
+
+ f dto.MetricFamily
+}
+
+func (sd *SampleDecoder) Decode(s *model.Vector) error {
+ if err := sd.Dec.Decode(&sd.f); err != nil {
+ return err
+ }
+ *s = extractSamples(&sd.f, sd.Opts)
+ return nil
+}
+
+// Extract samples builds a slice of samples from the provided metric families.
+func ExtractSamples(o *DecodeOptions, fams ...*dto.MetricFamily) model.Vector {
+ var all model.Vector
+ for _, f := range fams {
+ all = append(all, extractSamples(f, o)...)
+ }
+ return all
+}
+
+func extractSamples(f *dto.MetricFamily, o *DecodeOptions) model.Vector {
+ switch f.GetType() {
+ case dto.MetricType_COUNTER:
+ return extractCounter(o, f)
+ case dto.MetricType_GAUGE:
+ return extractGauge(o, f)
+ case dto.MetricType_SUMMARY:
+ return extractSummary(o, f)
+ case dto.MetricType_UNTYPED:
+ return extractUntyped(o, f)
+ case dto.MetricType_HISTOGRAM:
+ return extractHistogram(o, f)
+ }
+ panic("expfmt.extractSamples: unknown metric family type")
+}
+
+func extractCounter(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
+ samples := make(model.Vector, 0, len(f.Metric))
+
+ for _, m := range f.Metric {
+ if m.Counter == nil {
+ continue
+ }
+
+ lset := make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName())
+
+ smpl := &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Counter.GetValue()),
+ }
+
+ if m.TimestampMs != nil {
+ smpl.Timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000)
+ } else {
+ smpl.Timestamp = o.Timestamp
+ }
+
+ samples = append(samples, smpl)
+ }
+
+ return samples
+}
+
+func extractGauge(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
+ samples := make(model.Vector, 0, len(f.Metric))
+
+ for _, m := range f.Metric {
+ if m.Gauge == nil {
+ continue
+ }
+
+ lset := make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName())
+
+ smpl := &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Gauge.GetValue()),
+ }
+
+ if m.TimestampMs != nil {
+ smpl.Timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000)
+ } else {
+ smpl.Timestamp = o.Timestamp
+ }
+
+ samples = append(samples, smpl)
+ }
+
+ return samples
+}
+
+func extractUntyped(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
+ samples := make(model.Vector, 0, len(f.Metric))
+
+ for _, m := range f.Metric {
+ if m.Untyped == nil {
+ continue
+ }
+
+ lset := make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName())
+
+ smpl := &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Untyped.GetValue()),
+ }
+
+ if m.TimestampMs != nil {
+ smpl.Timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000)
+ } else {
+ smpl.Timestamp = o.Timestamp
+ }
+
+ samples = append(samples, smpl)
+ }
+
+ return samples
+}
+
+func extractSummary(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
+ samples := make(model.Vector, 0, len(f.Metric))
+
+ for _, m := range f.Metric {
+ if m.Summary == nil {
+ continue
+ }
+
+ timestamp := o.Timestamp
+ if m.TimestampMs != nil {
+ timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000)
+ }
+
+ for _, q := range m.Summary.Quantile {
+ lset := make(model.LabelSet, len(m.Label)+2)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ // BUG(matt): Update other names to "quantile".
+ lset[model.LabelName(model.QuantileLabel)] = model.LabelValue(fmt.Sprint(q.GetQuantile()))
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName())
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(q.GetValue()),
+ Timestamp: timestamp,
+ })
+ }
+
+ lset := make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_sum")
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Summary.GetSampleSum()),
+ Timestamp: timestamp,
+ })
+
+ lset = make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_count")
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Summary.GetSampleCount()),
+ Timestamp: timestamp,
+ })
+ }
+
+ return samples
+}
+
+func extractHistogram(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
+ samples := make(model.Vector, 0, len(f.Metric))
+
+ for _, m := range f.Metric {
+ if m.Histogram == nil {
+ continue
+ }
+
+ timestamp := o.Timestamp
+ if m.TimestampMs != nil {
+ timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000)
+ }
+
+ infSeen := false
+
+ for _, q := range m.Histogram.Bucket {
+ lset := make(model.LabelSet, len(m.Label)+2)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.LabelName(model.BucketLabel)] = model.LabelValue(fmt.Sprint(q.GetUpperBound()))
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_bucket")
+
+ if math.IsInf(q.GetUpperBound(), +1) {
+ infSeen = true
+ }
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(q.GetCumulativeCount()),
+ Timestamp: timestamp,
+ })
+ }
+
+ lset := make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_sum")
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Histogram.GetSampleSum()),
+ Timestamp: timestamp,
+ })
+
+ lset = make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_count")
+
+ count := &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Histogram.GetSampleCount()),
+ Timestamp: timestamp,
+ }
+ samples = append(samples, count)
+
+ if !infSeen {
+ // Append an infinity bucket sample.
+ lset := make(model.LabelSet, len(m.Label)+2)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.LabelName(model.BucketLabel)] = model.LabelValue("+Inf")
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_bucket")
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: count.Value,
+ Timestamp: timestamp,
+ })
+ }
+ }
+
+ return samples
+}
diff --git a/vendor/github.com/prometheus/common/expfmt/encode.go b/vendor/github.com/prometheus/common/expfmt/encode.go
new file mode 100644
index 0000000..11839ed
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/encode.go
@@ -0,0 +1,88 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package expfmt
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+
+ "github.com/golang/protobuf/proto"
+ "github.com/matttproud/golang_protobuf_extensions/pbutil"
+ "github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg"
+
+ dto "github.com/prometheus/client_model/go"
+)
+
+// Encoder types encode metric families into an underlying wire protocol.
+type Encoder interface {
+ Encode(*dto.MetricFamily) error
+}
+
+type encoder func(*dto.MetricFamily) error
+
+func (e encoder) Encode(v *dto.MetricFamily) error {
+ return e(v)
+}
+
+// Negotiate returns the Content-Type based on the given Accept header.
+// If no appropriate accepted type is found, FmtText is returned.
+func Negotiate(h http.Header) Format {
+ for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) {
+ // Check for protocol buffer
+ if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol {
+ switch ac.Params["encoding"] {
+ case "delimited":
+ return FmtProtoDelim
+ case "text":
+ return FmtProtoText
+ case "compact-text":
+ return FmtProtoCompact
+ }
+ }
+ // Check for text format.
+ ver := ac.Params["version"]
+ if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") {
+ return FmtText
+ }
+ }
+ return FmtText
+}
+
+// NewEncoder returns a new encoder based on content type negotiation.
+func NewEncoder(w io.Writer, format Format) Encoder {
+ switch format {
+ case FmtProtoDelim:
+ return encoder(func(v *dto.MetricFamily) error {
+ _, err := pbutil.WriteDelimited(w, v)
+ return err
+ })
+ case FmtProtoCompact:
+ return encoder(func(v *dto.MetricFamily) error {
+ _, err := fmt.Fprintln(w, v.String())
+ return err
+ })
+ case FmtProtoText:
+ return encoder(func(v *dto.MetricFamily) error {
+ _, err := fmt.Fprintln(w, proto.MarshalTextString(v))
+ return err
+ })
+ case FmtText:
+ return encoder(func(v *dto.MetricFamily) error {
+ _, err := MetricFamilyToText(w, v)
+ return err
+ })
+ }
+ panic("expfmt.NewEncoder: unknown format")
+}
diff --git a/vendor/github.com/prometheus/common/expfmt/expfmt.go b/vendor/github.com/prometheus/common/expfmt/expfmt.go
new file mode 100644
index 0000000..366fbde
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/expfmt.go
@@ -0,0 +1,40 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// A package for reading and writing Prometheus metrics.
+package expfmt
+
+type Format string
+
+const (
+ TextVersion = "0.0.4"
+
+ ProtoType = `application/vnd.google.protobuf`
+ ProtoProtocol = `io.prometheus.client.MetricFamily`
+ ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";"
+
+ // The Content-Type values for the different wire protocols.
+ FmtUnknown Format = `<unknown>`
+ FmtText Format = `text/plain; version=` + TextVersion
+ FmtProtoDelim Format = ProtoFmt + ` encoding=delimited`
+ FmtProtoText Format = ProtoFmt + ` encoding=text`
+ FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text`
+
+ // fmtJSON2 is hidden as it is deprecated.
+ fmtJSON2 Format = `application/json; version=0.0.2`
+)
+
+const (
+ hdrContentType = "Content-Type"
+ hdrAccept = "Accept"
+)
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz.go b/vendor/github.com/prometheus/common/expfmt/fuzz.go
new file mode 100644
index 0000000..dc2eede
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz.go
@@ -0,0 +1,36 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Build only when actually fuzzing
+// +build gofuzz
+
+package expfmt
+
+import "bytes"
+
+// Fuzz text metric parser with with github.com/dvyukov/go-fuzz:
+//
+// go-fuzz-build github.com/prometheus/common/expfmt
+// go-fuzz -bin expfmt-fuzz.zip -workdir fuzz
+//
+// Further input samples should go in the folder fuzz/corpus.
+func Fuzz(in []byte) int {
+ parser := TextParser{}
+ _, err := parser.TextToMetricFamilies(bytes.NewReader(in))
+
+ if err != nil {
+ return 0
+ }
+
+ return 1
+}
diff --git a/vendor/github.com/prometheus/common/expfmt/text_create.go b/vendor/github.com/prometheus/common/expfmt/text_create.go
new file mode 100644
index 0000000..1e06087
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/text_create.go
@@ -0,0 +1,300 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package expfmt
+
+import (
+ "fmt"
+ "io"
+ "math"
+ "strings"
+
+ dto "github.com/prometheus/client_model/go"
+ "github.com/prometheus/common/model"
+)
+
+// MetricFamilyToText converts a MetricFamily proto message into text format and
+// writes the resulting lines to 'out'. It returns the number of bytes written
+// and any error encountered. This function does not perform checks on the
+// content of the metric and label names, i.e. invalid metric or label names
+// will result in invalid text format output.
+// This method fulfills the type 'prometheus.encoder'.
+func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
+ var written int
+
+ // Fail-fast checks.
+ if len(in.Metric) == 0 {
+ return written, fmt.Errorf("MetricFamily has no metrics: %s", in)
+ }
+ name := in.GetName()
+ if name == "" {
+ return written, fmt.Errorf("MetricFamily has no name: %s", in)
+ }
+
+ // Comments, first HELP, then TYPE.
+ if in.Help != nil {
+ n, err := fmt.Fprintf(
+ out, "# HELP %s %s\n",
+ name, escapeString(*in.Help, false),
+ )
+ written += n
+ if err != nil {
+ return written, err
+ }
+ }
+ metricType := in.GetType()
+ n, err := fmt.Fprintf(
+ out, "# TYPE %s %s\n",
+ name, strings.ToLower(metricType.String()),
+ )
+ written += n
+ if err != nil {
+ return written, err
+ }
+
+ // Finally the samples, one line for each.
+ for _, metric := range in.Metric {
+ switch metricType {
+ case dto.MetricType_COUNTER:
+ if metric.Counter == nil {
+ return written, fmt.Errorf(
+ "expected counter in metric %s %s", name, metric,
+ )
+ }
+ n, err = writeSample(
+ name, metric, "", "",
+ metric.Counter.GetValue(),
+ out,
+ )
+ case dto.MetricType_GAUGE:
+ if metric.Gauge == nil {
+ return written, fmt.Errorf(
+ "expected gauge in metric %s %s", name, metric,
+ )
+ }
+ n, err = writeSample(
+ name, metric, "", "",
+ metric.Gauge.GetValue(),
+ out,
+ )
+ case dto.MetricType_UNTYPED:
+ if metric.Untyped == nil {
+ return written, fmt.Errorf(
+ "expected untyped in metric %s %s", name, metric,
+ )
+ }
+ n, err = writeSample(
+ name, metric, "", "",
+ metric.Untyped.GetValue(),
+ out,
+ )
+ case dto.MetricType_SUMMARY:
+ if metric.Summary == nil {
+ return written, fmt.Errorf(
+ "expected summary in metric %s %s", name, metric,
+ )
+ }
+ for _, q := range metric.Summary.Quantile {
+ n, err = writeSample(
+ name, metric,
+ model.QuantileLabel, fmt.Sprint(q.GetQuantile()),
+ q.GetValue(),
+ out,
+ )
+ written += n
+ if err != nil {
+ return written, err
+ }
+ }
+ n, err = writeSample(
+ name+"_sum", metric, "", "",
+ metric.Summary.GetSampleSum(),
+ out,
+ )
+ if err != nil {
+ return written, err
+ }
+ written += n
+ n, err = writeSample(
+ name+"_count", metric, "", "",
+ float64(metric.Summary.GetSampleCount()),
+ out,
+ )
+ case dto.MetricType_HISTOGRAM:
+ if metric.Histogram == nil {
+ return written, fmt.Errorf(
+ "expected histogram in metric %s %s", name, metric,
+ )
+ }
+ infSeen := false
+ for _, q := range metric.Histogram.Bucket {
+ n, err = writeSample(
+ name+"_bucket", metric,
+ model.BucketLabel, fmt.Sprint(q.GetUpperBound()),
+ float64(q.GetCumulativeCount()),
+ out,
+ )
+ written += n
+ if err != nil {
+ return written, err
+ }
+ if math.IsInf(q.GetUpperBound(), +1) {
+ infSeen = true
+ }
+ }
+ if !infSeen {
+ n, err = writeSample(
+ name+"_bucket", metric,
+ model.BucketLabel, "+Inf",
+ float64(metric.Histogram.GetSampleCount()),
+ out,
+ )
+ if err != nil {
+ return written, err
+ }
+ written += n
+ }
+ n, err = writeSample(
+ name+"_sum", metric, "", "",
+ metric.Histogram.GetSampleSum(),
+ out,
+ )
+ if err != nil {
+ return written, err
+ }
+ written += n
+ n, err = writeSample(
+ name+"_count", metric, "", "",
+ float64(metric.Histogram.GetSampleCount()),
+ out,
+ )
+ default:
+ return written, fmt.Errorf(
+ "unexpected type in metric %s %s", name, metric,
+ )
+ }
+ written += n
+ if err != nil {
+ return written, err
+ }
+ }
+ return written, nil
+}
+
+// writeSample writes a single sample in text format to out, given the metric
+// name, the metric proto message itself, optionally an additional label name
+// and value (use empty strings if not required), and the value. The function
+// returns the number of bytes written and any error encountered.
+func writeSample(
+ name string,
+ metric *dto.Metric,
+ additionalLabelName, additionalLabelValue string,
+ value float64,
+ out io.Writer,
+) (int, error) {
+ var written int
+ n, err := fmt.Fprint(out, name)
+ written += n
+ if err != nil {
+ return written, err
+ }
+ n, err = labelPairsToText(
+ metric.Label,
+ additionalLabelName, additionalLabelValue,
+ out,
+ )
+ written += n
+ if err != nil {
+ return written, err
+ }
+ n, err = fmt.Fprintf(out, " %v", value)
+ written += n
+ if err != nil {
+ return written, err
+ }
+ if metric.TimestampMs != nil {
+ n, err = fmt.Fprintf(out, " %v", *metric.TimestampMs)
+ written += n
+ if err != nil {
+ return written, err
+ }
+ }
+ n, err = out.Write([]byte{'\n'})
+ written += n
+ if err != nil {
+ return written, err
+ }
+ return written, nil
+}
+
+// labelPairsToText converts a slice of LabelPair proto messages plus the
+// explicitly given additional label pair into text formatted as required by the
+// text format and writes it to 'out'. An empty slice in combination with an
+// empty string 'additionalLabelName' results in nothing being
+// written. Otherwise, the label pairs are written, escaped as required by the
+// text format, and enclosed in '{...}'. The function returns the number of
+// bytes written and any error encountered.
+func labelPairsToText(
+ in []*dto.LabelPair,
+ additionalLabelName, additionalLabelValue string,
+ out io.Writer,
+) (int, error) {
+ if len(in) == 0 && additionalLabelName == "" {
+ return 0, nil
+ }
+ var written int
+ separator := '{'
+ for _, lp := range in {
+ n, err := fmt.Fprintf(
+ out, `%c%s="%s"`,
+ separator, lp.GetName(), escapeString(lp.GetValue(), true),
+ )
+ written += n
+ if err != nil {
+ return written, err
+ }
+ separator = ','
+ }
+ if additionalLabelName != "" {
+ n, err := fmt.Fprintf(
+ out, `%c%s="%s"`,
+ separator, additionalLabelName,
+ escapeString(additionalLabelValue, true),
+ )
+ written += n
+ if err != nil {
+ return written, err
+ }
+ }
+ n, err := out.Write([]byte{'}'})
+ written += n
+ if err != nil {
+ return written, err
+ }
+ return written, nil
+}
+
+var (
+ escape = strings.NewReplacer("\\", `\\`, "\n", `\n`)
+ escapeWithDoubleQuote = strings.NewReplacer("\\", `\\`, "\n", `\n`, "\"", `\"`)
+)
+
+// escapeString replaces '\' by '\\', new line character by '\n', and - if
+// includeDoubleQuote is true - '"' by '\"'.
+func escapeString(v string, includeDoubleQuote bool) string {
+ if includeDoubleQuote {
+ return escapeWithDoubleQuote.Replace(v)
+ }
+
+ return escape.Replace(v)
+}
diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse.go b/vendor/github.com/prometheus/common/expfmt/text_parse.go
new file mode 100644
index 0000000..bd170b1
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/text_parse.go
@@ -0,0 +1,753 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package expfmt
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "io"
+ "math"
+ "strconv"
+ "strings"
+
+ dto "github.com/prometheus/client_model/go"
+
+ "github.com/golang/protobuf/proto"
+ "github.com/prometheus/common/model"
+)
+
+// A stateFn is a function that represents a state in a state machine. By
+// executing it, the state is progressed to the next state. The stateFn returns
+// another stateFn, which represents the new state. The end state is represented
+// by nil.
+type stateFn func() stateFn
+
+// ParseError signals errors while parsing the simple and flat text-based
+// exchange format.
+type ParseError struct {
+ Line int
+ Msg string
+}
+
+// Error implements the error interface.
+func (e ParseError) Error() string {
+ return fmt.Sprintf("text format parsing error in line %d: %s", e.Line, e.Msg)
+}
+
+// TextParser is used to parse the simple and flat text-based exchange format. Its
+// nil value is ready to use.
+type TextParser struct {
+ metricFamiliesByName map[string]*dto.MetricFamily
+ buf *bufio.Reader // Where the parsed input is read through.
+ err error // Most recent error.
+ lineCount int // Tracks the line count for error messages.
+ currentByte byte // The most recent byte read.
+ currentToken bytes.Buffer // Re-used each time a token has to be gathered from multiple bytes.
+ currentMF *dto.MetricFamily
+ currentMetric *dto.Metric
+ currentLabelPair *dto.LabelPair
+
+ // The remaining member variables are only used for summaries/histograms.
+ currentLabels map[string]string // All labels including '__name__' but excluding 'quantile'/'le'
+ // Summary specific.
+ summaries map[uint64]*dto.Metric // Key is created with LabelsToSignature.
+ currentQuantile float64
+ // Histogram specific.
+ histograms map[uint64]*dto.Metric // Key is created with LabelsToSignature.
+ currentBucket float64
+ // These tell us if the currently processed line ends on '_count' or
+ // '_sum' respectively and belong to a summary/histogram, representing the sample
+ // count and sum of that summary/histogram.
+ currentIsSummaryCount, currentIsSummarySum bool
+ currentIsHistogramCount, currentIsHistogramSum bool
+}
+
+// TextToMetricFamilies reads 'in' as the simple and flat text-based exchange
+// format and creates MetricFamily proto messages. It returns the MetricFamily
+// proto messages in a map where the metric names are the keys, along with any
+// error encountered.
+//
+// If the input contains duplicate metrics (i.e. lines with the same metric name
+// and exactly the same label set), the resulting MetricFamily will contain
+// duplicate Metric proto messages. Similar is true for duplicate label
+// names. Checks for duplicates have to be performed separately, if required.
+// Also note that neither the metrics within each MetricFamily are sorted nor
+// the label pairs within each Metric. Sorting is not required for the most
+// frequent use of this method, which is sample ingestion in the Prometheus
+// server. However, for presentation purposes, you might want to sort the
+// metrics, and in some cases, you must sort the labels, e.g. for consumption by
+// the metric family injection hook of the Prometheus registry.
+//
+// Summaries and histograms are rather special beasts. You would probably not
+// use them in the simple text format anyway. This method can deal with
+// summaries and histograms if they are presented in exactly the way the
+// text.Create function creates them.
+//
+// This method must not be called concurrently. If you want to parse different
+// input concurrently, instantiate a separate Parser for each goroutine.
+func (p *TextParser) TextToMetricFamilies(in io.Reader) (map[string]*dto.MetricFamily, error) {
+ p.reset(in)
+ for nextState := p.startOfLine; nextState != nil; nextState = nextState() {
+ // Magic happens here...
+ }
+ // Get rid of empty metric families.
+ for k, mf := range p.metricFamiliesByName {
+ if len(mf.GetMetric()) == 0 {
+ delete(p.metricFamiliesByName, k)
+ }
+ }
+ // If p.err is io.EOF now, we have run into a premature end of the input
+ // stream. Turn this error into something nicer and more
+ // meaningful. (io.EOF is often used as a signal for the legitimate end
+ // of an input stream.)
+ if p.err == io.EOF {
+ p.parseError("unexpected end of input stream")
+ }
+ return p.metricFamiliesByName, p.err
+}
+
+func (p *TextParser) reset(in io.Reader) {
+ p.metricFamiliesByName = map[string]*dto.MetricFamily{}
+ if p.buf == nil {
+ p.buf = bufio.NewReader(in)
+ } else {
+ p.buf.Reset(in)
+ }
+ p.err = nil
+ p.lineCount = 0
+ if p.summaries == nil || len(p.summaries) > 0 {
+ p.summaries = map[uint64]*dto.Metric{}
+ }
+ if p.histograms == nil || len(p.histograms) > 0 {
+ p.histograms = map[uint64]*dto.Metric{}
+ }
+ p.currentQuantile = math.NaN()
+ p.currentBucket = math.NaN()
+}
+
+// startOfLine represents the state where the next byte read from p.buf is the
+// start of a line (or whitespace leading up to it).
+func (p *TextParser) startOfLine() stateFn {
+ p.lineCount++
+ if p.skipBlankTab(); p.err != nil {
+ // End of input reached. This is the only case where
+ // that is not an error but a signal that we are done.
+ p.err = nil
+ return nil
+ }
+ switch p.currentByte {
+ case '#':
+ return p.startComment
+ case '\n':
+ return p.startOfLine // Empty line, start the next one.
+ }
+ return p.readingMetricName
+}
+
+// startComment represents the state where the next byte read from p.buf is the
+// start of a comment (or whitespace leading up to it).
+func (p *TextParser) startComment() stateFn {
+ if p.skipBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ if p.currentByte == '\n' {
+ return p.startOfLine
+ }
+ if p.readTokenUntilWhitespace(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ // If we have hit the end of line already, there is nothing left
+ // to do. This is not considered a syntax error.
+ if p.currentByte == '\n' {
+ return p.startOfLine
+ }
+ keyword := p.currentToken.String()
+ if keyword != "HELP" && keyword != "TYPE" {
+ // Generic comment, ignore by fast forwarding to end of line.
+ for p.currentByte != '\n' {
+ if p.currentByte, p.err = p.buf.ReadByte(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ }
+ return p.startOfLine
+ }
+ // There is something. Next has to be a metric name.
+ if p.skipBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ if p.readTokenAsMetricName(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ if p.currentByte == '\n' {
+ // At the end of the line already.
+ // Again, this is not considered a syntax error.
+ return p.startOfLine
+ }
+ if !isBlankOrTab(p.currentByte) {
+ p.parseError("invalid metric name in comment")
+ return nil
+ }
+ p.setOrCreateCurrentMF()
+ if p.skipBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ if p.currentByte == '\n' {
+ // At the end of the line already.
+ // Again, this is not considered a syntax error.
+ return p.startOfLine
+ }
+ switch keyword {
+ case "HELP":
+ return p.readingHelp
+ case "TYPE":
+ return p.readingType
+ }
+ panic(fmt.Sprintf("code error: unexpected keyword %q", keyword))
+}
+
+// readingMetricName represents the state where the last byte read (now in
+// p.currentByte) is the first byte of a metric name.
+func (p *TextParser) readingMetricName() stateFn {
+ if p.readTokenAsMetricName(); p.err != nil {
+ return nil
+ }
+ if p.currentToken.Len() == 0 {
+ p.parseError("invalid metric name")
+ return nil
+ }
+ p.setOrCreateCurrentMF()
+ // Now is the time to fix the type if it hasn't happened yet.
+ if p.currentMF.Type == nil {
+ p.currentMF.Type = dto.MetricType_UNTYPED.Enum()
+ }
+ p.currentMetric = &dto.Metric{}
+ // Do not append the newly created currentMetric to
+ // currentMF.Metric right now. First wait if this is a summary,
+ // and the metric exists already, which we can only know after
+ // having read all the labels.
+ if p.skipBlankTabIfCurrentBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ return p.readingLabels
+}
+
+// readingLabels represents the state where the last byte read (now in
+// p.currentByte) is either the first byte of the label set (i.e. a '{'), or the
+// first byte of the value (otherwise).
+func (p *TextParser) readingLabels() stateFn {
+ // Summaries/histograms are special. We have to reset the
+ // currentLabels map, currentQuantile and currentBucket before starting to
+ // read labels.
+ if p.currentMF.GetType() == dto.MetricType_SUMMARY || p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
+ p.currentLabels = map[string]string{}
+ p.currentLabels[string(model.MetricNameLabel)] = p.currentMF.GetName()
+ p.currentQuantile = math.NaN()
+ p.currentBucket = math.NaN()
+ }
+ if p.currentByte != '{' {
+ return p.readingValue
+ }
+ return p.startLabelName
+}
+
+// startLabelName represents the state where the next byte read from p.buf is
+// the start of a label name (or whitespace leading up to it).
+func (p *TextParser) startLabelName() stateFn {
+ if p.skipBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ if p.currentByte == '}' {
+ if p.skipBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ return p.readingValue
+ }
+ if p.readTokenAsLabelName(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ if p.currentToken.Len() == 0 {
+ p.parseError(fmt.Sprintf("invalid label name for metric %q", p.currentMF.GetName()))
+ return nil
+ }
+ p.currentLabelPair = &dto.LabelPair{Name: proto.String(p.currentToken.String())}
+ if p.currentLabelPair.GetName() == string(model.MetricNameLabel) {
+ p.parseError(fmt.Sprintf("label name %q is reserved", model.MetricNameLabel))
+ return nil
+ }
+ // Special summary/histogram treatment. Don't add 'quantile' and 'le'
+ // labels to 'real' labels.
+ if !(p.currentMF.GetType() == dto.MetricType_SUMMARY && p.currentLabelPair.GetName() == model.QuantileLabel) &&
+ !(p.currentMF.GetType() == dto.MetricType_HISTOGRAM && p.currentLabelPair.GetName() == model.BucketLabel) {
+ p.currentMetric.Label = append(p.currentMetric.Label, p.currentLabelPair)
+ }
+ if p.skipBlankTabIfCurrentBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ if p.currentByte != '=' {
+ p.parseError(fmt.Sprintf("expected '=' after label name, found %q", p.currentByte))
+ return nil
+ }
+ return p.startLabelValue
+}
+
+// startLabelValue represents the state where the next byte read from p.buf is
+// the start of a (quoted) label value (or whitespace leading up to it).
+func (p *TextParser) startLabelValue() stateFn {
+ if p.skipBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ if p.currentByte != '"' {
+ p.parseError(fmt.Sprintf("expected '\"' at start of label value, found %q", p.currentByte))
+ return nil
+ }
+ if p.readTokenAsLabelValue(); p.err != nil {
+ return nil
+ }
+ p.currentLabelPair.Value = proto.String(p.currentToken.String())
+ // Special treatment of summaries:
+ // - Quantile labels are special, will result in dto.Quantile later.
+ // - Other labels have to be added to currentLabels for signature calculation.
+ if p.currentMF.GetType() == dto.MetricType_SUMMARY {
+ if p.currentLabelPair.GetName() == model.QuantileLabel {
+ if p.currentQuantile, p.err = strconv.ParseFloat(p.currentLabelPair.GetValue(), 64); p.err != nil {
+ // Create a more helpful error message.
+ p.parseError(fmt.Sprintf("expected float as value for 'quantile' label, got %q", p.currentLabelPair.GetValue()))
+ return nil
+ }
+ } else {
+ p.currentLabels[p.currentLabelPair.GetName()] = p.currentLabelPair.GetValue()
+ }
+ }
+ // Similar special treatment of histograms.
+ if p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
+ if p.currentLabelPair.GetName() == model.BucketLabel {
+ if p.currentBucket, p.err = strconv.ParseFloat(p.currentLabelPair.GetValue(), 64); p.err != nil {
+ // Create a more helpful error message.
+ p.parseError(fmt.Sprintf("expected float as value for 'le' label, got %q", p.currentLabelPair.GetValue()))
+ return nil
+ }
+ } else {
+ p.currentLabels[p.currentLabelPair.GetName()] = p.currentLabelPair.GetValue()
+ }
+ }
+ if p.skipBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ switch p.currentByte {
+ case ',':
+ return p.startLabelName
+
+ case '}':
+ if p.skipBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ return p.readingValue
+ default:
+ p.parseError(fmt.Sprintf("unexpected end of label value %q", p.currentLabelPair.Value))
+ return nil
+ }
+}
+
+// readingValue represents the state where the last byte read (now in
+// p.currentByte) is the first byte of the sample value (i.e. a float).
+func (p *TextParser) readingValue() stateFn {
+ // When we are here, we have read all the labels, so for the
+ // special case of a summary/histogram, we can finally find out
+ // if the metric already exists.
+ if p.currentMF.GetType() == dto.MetricType_SUMMARY {
+ signature := model.LabelsToSignature(p.currentLabels)
+ if summary := p.summaries[signature]; summary != nil {
+ p.currentMetric = summary
+ } else {
+ p.summaries[signature] = p.currentMetric
+ p.currentMF.Metric = append(p.currentMF.Metric, p.currentMetric)
+ }
+ } else if p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
+ signature := model.LabelsToSignature(p.currentLabels)
+ if histogram := p.histograms[signature]; histogram != nil {
+ p.currentMetric = histogram
+ } else {
+ p.histograms[signature] = p.currentMetric
+ p.currentMF.Metric = append(p.currentMF.Metric, p.currentMetric)
+ }
+ } else {
+ p.currentMF.Metric = append(p.currentMF.Metric, p.currentMetric)
+ }
+ if p.readTokenUntilWhitespace(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ value, err := strconv.ParseFloat(p.currentToken.String(), 64)
+ if err != nil {
+ // Create a more helpful error message.
+ p.parseError(fmt.Sprintf("expected float as value, got %q", p.currentToken.String()))
+ return nil
+ }
+ switch p.currentMF.GetType() {
+ case dto.MetricType_COUNTER:
+ p.currentMetric.Counter = &dto.Counter{Value: proto.Float64(value)}
+ case dto.MetricType_GAUGE:
+ p.currentMetric.Gauge = &dto.Gauge{Value: proto.Float64(value)}
+ case dto.MetricType_UNTYPED:
+ p.currentMetric.Untyped = &dto.Untyped{Value: proto.Float64(value)}
+ case dto.MetricType_SUMMARY:
+ // *sigh*
+ if p.currentMetric.Summary == nil {
+ p.currentMetric.Summary = &dto.Summary{}
+ }
+ switch {
+ case p.currentIsSummaryCount:
+ p.currentMetric.Summary.SampleCount = proto.Uint64(uint64(value))
+ case p.currentIsSummarySum:
+ p.currentMetric.Summary.SampleSum = proto.Float64(value)
+ case !math.IsNaN(p.currentQuantile):
+ p.currentMetric.Summary.Quantile = append(
+ p.currentMetric.Summary.Quantile,
+ &dto.Quantile{
+ Quantile: proto.Float64(p.currentQuantile),
+ Value: proto.Float64(value),
+ },
+ )
+ }
+ case dto.MetricType_HISTOGRAM:
+ // *sigh*
+ if p.currentMetric.Histogram == nil {
+ p.currentMetric.Histogram = &dto.Histogram{}
+ }
+ switch {
+ case p.currentIsHistogramCount:
+ p.currentMetric.Histogram.SampleCount = proto.Uint64(uint64(value))
+ case p.currentIsHistogramSum:
+ p.currentMetric.Histogram.SampleSum = proto.Float64(value)
+ case !math.IsNaN(p.currentBucket):
+ p.currentMetric.Histogram.Bucket = append(
+ p.currentMetric.Histogram.Bucket,
+ &dto.Bucket{
+ UpperBound: proto.Float64(p.currentBucket),
+ CumulativeCount: proto.Uint64(uint64(value)),
+ },
+ )
+ }
+ default:
+ p.err = fmt.Errorf("unexpected type for metric name %q", p.currentMF.GetName())
+ }
+ if p.currentByte == '\n' {
+ return p.startOfLine
+ }
+ return p.startTimestamp
+}
+
+// startTimestamp represents the state where the next byte read from p.buf is
+// the start of the timestamp (or whitespace leading up to it).
+func (p *TextParser) startTimestamp() stateFn {
+ if p.skipBlankTab(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ if p.readTokenUntilWhitespace(); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ timestamp, err := strconv.ParseInt(p.currentToken.String(), 10, 64)
+ if err != nil {
+ // Create a more helpful error message.
+ p.parseError(fmt.Sprintf("expected integer as timestamp, got %q", p.currentToken.String()))
+ return nil
+ }
+ p.currentMetric.TimestampMs = proto.Int64(timestamp)
+ if p.readTokenUntilNewline(false); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ if p.currentToken.Len() > 0 {
+ p.parseError(fmt.Sprintf("spurious string after timestamp: %q", p.currentToken.String()))
+ return nil
+ }
+ return p.startOfLine
+}
+
+// readingHelp represents the state where the last byte read (now in
+// p.currentByte) is the first byte of the docstring after 'HELP'.
+func (p *TextParser) readingHelp() stateFn {
+ if p.currentMF.Help != nil {
+ p.parseError(fmt.Sprintf("second HELP line for metric name %q", p.currentMF.GetName()))
+ return nil
+ }
+ // Rest of line is the docstring.
+ if p.readTokenUntilNewline(true); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ p.currentMF.Help = proto.String(p.currentToken.String())
+ return p.startOfLine
+}
+
+// readingType represents the state where the last byte read (now in
+// p.currentByte) is the first byte of the type hint after 'HELP'.
+func (p *TextParser) readingType() stateFn {
+ if p.currentMF.Type != nil {
+ p.parseError(fmt.Sprintf("second TYPE line for metric name %q, or TYPE reported after samples", p.currentMF.GetName()))
+ return nil
+ }
+ // Rest of line is the type.
+ if p.readTokenUntilNewline(false); p.err != nil {
+ return nil // Unexpected end of input.
+ }
+ metricType, ok := dto.MetricType_value[strings.ToUpper(p.currentToken.String())]
+ if !ok {
+ p.parseError(fmt.Sprintf("unknown metric type %q", p.currentToken.String()))
+ return nil
+ }
+ p.currentMF.Type = dto.MetricType(metricType).Enum()
+ return p.startOfLine
+}
+
+// parseError sets p.err to a ParseError at the current line with the given
+// message.
+func (p *TextParser) parseError(msg string) {
+ p.err = ParseError{
+ Line: p.lineCount,
+ Msg: msg,
+ }
+}
+
+// skipBlankTab reads (and discards) bytes from p.buf until it encounters a byte
+// that is neither ' ' nor '\t'. That byte is left in p.currentByte.
+func (p *TextParser) skipBlankTab() {
+ for {
+ if p.currentByte, p.err = p.buf.ReadByte(); p.err != nil || !isBlankOrTab(p.currentByte) {
+ return
+ }
+ }
+}
+
+// skipBlankTabIfCurrentBlankTab works exactly as skipBlankTab but doesn't do
+// anything if p.currentByte is neither ' ' nor '\t'.
+func (p *TextParser) skipBlankTabIfCurrentBlankTab() {
+ if isBlankOrTab(p.currentByte) {
+ p.skipBlankTab()
+ }
+}
+
+// readTokenUntilWhitespace copies bytes from p.buf into p.currentToken. The
+// first byte considered is the byte already read (now in p.currentByte). The
+// first whitespace byte encountered is still copied into p.currentByte, but not
+// into p.currentToken.
+func (p *TextParser) readTokenUntilWhitespace() {
+ p.currentToken.Reset()
+ for p.err == nil && !isBlankOrTab(p.currentByte) && p.currentByte != '\n' {
+ p.currentToken.WriteByte(p.currentByte)
+ p.currentByte, p.err = p.buf.ReadByte()
+ }
+}
+
+// readTokenUntilNewline copies bytes from p.buf into p.currentToken. The first
+// byte considered is the byte already read (now in p.currentByte). The first
+// newline byte encountered is still copied into p.currentByte, but not into
+// p.currentToken. If recognizeEscapeSequence is true, two escape sequences are
+// recognized: '\\' tranlates into '\', and '\n' into a line-feed character. All
+// other escape sequences are invalid and cause an error.
+func (p *TextParser) readTokenUntilNewline(recognizeEscapeSequence bool) {
+ p.currentToken.Reset()
+ escaped := false
+ for p.err == nil {
+ if recognizeEscapeSequence && escaped {
+ switch p.currentByte {
+ case '\\':
+ p.currentToken.WriteByte(p.currentByte)
+ case 'n':
+ p.currentToken.WriteByte('\n')
+ default:
+ p.parseError(fmt.Sprintf("invalid escape sequence '\\%c'", p.currentByte))
+ return
+ }
+ escaped = false
+ } else {
+ switch p.currentByte {
+ case '\n':
+ return
+ case '\\':
+ escaped = true
+ default:
+ p.currentToken.WriteByte(p.currentByte)
+ }
+ }
+ p.currentByte, p.err = p.buf.ReadByte()
+ }
+}
+
+// readTokenAsMetricName copies a metric name from p.buf into p.currentToken.
+// The first byte considered is the byte already read (now in p.currentByte).
+// The first byte not part of a metric name is still copied into p.currentByte,
+// but not into p.currentToken.
+func (p *TextParser) readTokenAsMetricName() {
+ p.currentToken.Reset()
+ if !isValidMetricNameStart(p.currentByte) {
+ return
+ }
+ for {
+ p.currentToken.WriteByte(p.currentByte)
+ p.currentByte, p.err = p.buf.ReadByte()
+ if p.err != nil || !isValidMetricNameContinuation(p.currentByte) {
+ return
+ }
+ }
+}
+
+// readTokenAsLabelName copies a label name from p.buf into p.currentToken.
+// The first byte considered is the byte already read (now in p.currentByte).
+// The first byte not part of a label name is still copied into p.currentByte,
+// but not into p.currentToken.
+func (p *TextParser) readTokenAsLabelName() {
+ p.currentToken.Reset()
+ if !isValidLabelNameStart(p.currentByte) {
+ return
+ }
+ for {
+ p.currentToken.WriteByte(p.currentByte)
+ p.currentByte, p.err = p.buf.ReadByte()
+ if p.err != nil || !isValidLabelNameContinuation(p.currentByte) {
+ return
+ }
+ }
+}
+
+// readTokenAsLabelValue copies a label value from p.buf into p.currentToken.
+// In contrast to the other 'readTokenAs...' functions, which start with the
+// last read byte in p.currentByte, this method ignores p.currentByte and starts
+// with reading a new byte from p.buf. The first byte not part of a label value
+// is still copied into p.currentByte, but not into p.currentToken.
+func (p *TextParser) readTokenAsLabelValue() {
+ p.currentToken.Reset()
+ escaped := false
+ for {
+ if p.currentByte, p.err = p.buf.ReadByte(); p.err != nil {
+ return
+ }
+ if escaped {
+ switch p.currentByte {
+ case '"', '\\':
+ p.currentToken.WriteByte(p.currentByte)
+ case 'n':
+ p.currentToken.WriteByte('\n')
+ default:
+ p.parseError(fmt.Sprintf("invalid escape sequence '\\%c'", p.currentByte))
+ return
+ }
+ escaped = false
+ continue
+ }
+ switch p.currentByte {
+ case '"':
+ return
+ case '\n':
+ p.parseError(fmt.Sprintf("label value %q contains unescaped new-line", p.currentToken.String()))
+ return
+ case '\\':
+ escaped = true
+ default:
+ p.currentToken.WriteByte(p.currentByte)
+ }
+ }
+}
+
+func (p *TextParser) setOrCreateCurrentMF() {
+ p.currentIsSummaryCount = false
+ p.currentIsSummarySum = false
+ p.currentIsHistogramCount = false
+ p.currentIsHistogramSum = false
+ name := p.currentToken.String()
+ if p.currentMF = p.metricFamiliesByName[name]; p.currentMF != nil {
+ return
+ }
+ // Try out if this is a _sum or _count for a summary/histogram.
+ summaryName := summaryMetricName(name)
+ if p.currentMF = p.metricFamiliesByName[summaryName]; p.currentMF != nil {
+ if p.currentMF.GetType() == dto.MetricType_SUMMARY {
+ if isCount(name) {
+ p.currentIsSummaryCount = true
+ }
+ if isSum(name) {
+ p.currentIsSummarySum = true
+ }
+ return
+ }
+ }
+ histogramName := histogramMetricName(name)
+ if p.currentMF = p.metricFamiliesByName[histogramName]; p.currentMF != nil {
+ if p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
+ if isCount(name) {
+ p.currentIsHistogramCount = true
+ }
+ if isSum(name) {
+ p.currentIsHistogramSum = true
+ }
+ return
+ }
+ }
+ p.currentMF = &dto.MetricFamily{Name: proto.String(name)}
+ p.metricFamiliesByName[name] = p.currentMF
+}
+
+func isValidLabelNameStart(b byte) bool {
+ return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_'
+}
+
+func isValidLabelNameContinuation(b byte) bool {
+ return isValidLabelNameStart(b) || (b >= '0' && b <= '9')
+}
+
+func isValidMetricNameStart(b byte) bool {
+ return isValidLabelNameStart(b) || b == ':'
+}
+
+func isValidMetricNameContinuation(b byte) bool {
+ return isValidLabelNameContinuation(b) || b == ':'
+}
+
+func isBlankOrTab(b byte) bool {
+ return b == ' ' || b == '\t'
+}
+
+func isCount(name string) bool {
+ return len(name) > 6 && name[len(name)-6:] == "_count"
+}
+
+func isSum(name string) bool {
+ return len(name) > 4 && name[len(name)-4:] == "_sum"
+}
+
+func isBucket(name string) bool {
+ return len(name) > 7 && name[len(name)-7:] == "_bucket"
+}
+
+func summaryMetricName(name string) string {
+ switch {
+ case isCount(name):
+ return name[:len(name)-6]
+ case isSum(name):
+ return name[:len(name)-4]
+ default:
+ return name
+ }
+}
+
+func histogramMetricName(name string) string {
+ switch {
+ case isCount(name):
+ return name[:len(name)-6]
+ case isSum(name):
+ return name[:len(name)-4]
+ case isBucket(name):
+ return name[:len(name)-7]
+ default:
+ return name
+ }
+}
diff --git a/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt
new file mode 100644
index 0000000..7723656
--- /dev/null
+++ b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt
@@ -0,0 +1,67 @@
+PACKAGE
+
+package goautoneg
+import "bitbucket.org/ww/goautoneg"
+
+HTTP Content-Type Autonegotiation.
+
+The functions in this package implement the behaviour specified in
+http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
+
+Copyright (c) 2011, Open Knowledge Foundation Ltd.
+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 Open Knowledge Foundation Ltd. 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.
+
+
+FUNCTIONS
+
+func Negotiate(header string, alternatives []string) (content_type string)
+Negotiate the most appropriate content_type given the accept header
+and a list of alternatives.
+
+func ParseAccept(header string) (accept []Accept)
+Parse an Accept Header string returning a sorted list
+of clauses
+
+
+TYPES
+
+type Accept struct {
+ Type, SubType string
+ Q float32
+ Params map[string]string
+}
+Structure to represent a clause in an HTTP Accept Header
+
+
+SUBDIRECTORIES
+
+ .hg
diff --git a/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go
new file mode 100644
index 0000000..648b38c
--- /dev/null
+++ b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go
@@ -0,0 +1,162 @@
+/*
+HTTP Content-Type Autonegotiation.
+
+The functions in this package implement the behaviour specified in
+http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
+
+Copyright (c) 2011, Open Knowledge Foundation Ltd.
+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 Open Knowledge Foundation Ltd. 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.
+
+
+*/
+package goautoneg
+
+import (
+ "sort"
+ "strconv"
+ "strings"
+)
+
+// Structure to represent a clause in an HTTP Accept Header
+type Accept struct {
+ Type, SubType string
+ Q float64
+ Params map[string]string
+}
+
+// For internal use, so that we can use the sort interface
+type accept_slice []Accept
+
+func (accept accept_slice) Len() int {
+ slice := []Accept(accept)
+ return len(slice)
+}
+
+func (accept accept_slice) Less(i, j int) bool {
+ slice := []Accept(accept)
+ ai, aj := slice[i], slice[j]
+ if ai.Q > aj.Q {
+ return true
+ }
+ if ai.Type != "*" && aj.Type == "*" {
+ return true
+ }
+ if ai.SubType != "*" && aj.SubType == "*" {
+ return true
+ }
+ return false
+}
+
+func (accept accept_slice) Swap(i, j int) {
+ slice := []Accept(accept)
+ slice[i], slice[j] = slice[j], slice[i]
+}
+
+// Parse an Accept Header string returning a sorted list
+// of clauses
+func ParseAccept(header string) (accept []Accept) {
+ parts := strings.Split(header, ",")
+ accept = make([]Accept, 0, len(parts))
+ for _, part := range parts {
+ part := strings.Trim(part, " ")
+
+ a := Accept{}
+ a.Params = make(map[string]string)
+ a.Q = 1.0
+
+ mrp := strings.Split(part, ";")
+
+ media_range := mrp[0]
+ sp := strings.Split(media_range, "/")
+ a.Type = strings.Trim(sp[0], " ")
+
+ switch {
+ case len(sp) == 1 && a.Type == "*":
+ a.SubType = "*"
+ case len(sp) == 2:
+ a.SubType = strings.Trim(sp[1], " ")
+ default:
+ continue
+ }
+
+ if len(mrp) == 1 {
+ accept = append(accept, a)
+ continue
+ }
+
+ for _, param := range mrp[1:] {
+ sp := strings.SplitN(param, "=", 2)
+ if len(sp) != 2 {
+ continue
+ }
+ token := strings.Trim(sp[0], " ")
+ if token == "q" {
+ a.Q, _ = strconv.ParseFloat(sp[1], 32)
+ } else {
+ a.Params[token] = strings.Trim(sp[1], " ")
+ }
+ }
+
+ accept = append(accept, a)
+ }
+
+ slice := accept_slice(accept)
+ sort.Sort(slice)
+
+ return
+}
+
+// Negotiate the most appropriate content_type given the accept header
+// and a list of alternatives.
+func Negotiate(header string, alternatives []string) (content_type string) {
+ asp := make([][]string, 0, len(alternatives))
+ for _, ctype := range alternatives {
+ asp = append(asp, strings.SplitN(ctype, "/", 2))
+ }
+ for _, clause := range ParseAccept(header) {
+ for i, ctsp := range asp {
+ if clause.Type == ctsp[0] && clause.SubType == ctsp[1] {
+ content_type = alternatives[i]
+ return
+ }
+ if clause.Type == ctsp[0] && clause.SubType == "*" {
+ content_type = alternatives[i]
+ return
+ }
+ if clause.Type == "*" && clause.SubType == "*" {
+ content_type = alternatives[i]
+ return
+ }
+ }
+ }
+ return
+}
diff --git a/vendor/github.com/prometheus/common/model/alert.go b/vendor/github.com/prometheus/common/model/alert.go
new file mode 100644
index 0000000..35e739c
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/alert.go
@@ -0,0 +1,136 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "fmt"
+ "time"
+)
+
+type AlertStatus string
+
+const (
+ AlertFiring AlertStatus = "firing"
+ AlertResolved AlertStatus = "resolved"
+)
+
+// Alert is a generic representation of an alert in the Prometheus eco-system.
+type Alert struct {
+ // Label value pairs for purpose of aggregation, matching, and disposition
+ // dispatching. This must minimally include an "alertname" label.
+ Labels LabelSet `json:"labels"`
+
+ // Extra key/value information which does not define alert identity.
+ Annotations LabelSet `json:"annotations"`
+
+ // The known time range for this alert. Both ends are optional.
+ StartsAt time.Time `json:"startsAt,omitempty"`
+ EndsAt time.Time `json:"endsAt,omitempty"`
+ GeneratorURL string `json:"generatorURL"`
+}
+
+// Name returns the name of the alert. It is equivalent to the "alertname" label.
+func (a *Alert) Name() string {
+ return string(a.Labels[AlertNameLabel])
+}
+
+// Fingerprint returns a unique hash for the alert. It is equivalent to
+// the fingerprint of the alert's label set.
+func (a *Alert) Fingerprint() Fingerprint {
+ return a.Labels.Fingerprint()
+}
+
+func (a *Alert) String() string {
+ s := fmt.Sprintf("%s[%s]", a.Name(), a.Fingerprint().String()[:7])
+ if a.Resolved() {
+ return s + "[resolved]"
+ }
+ return s + "[active]"
+}
+
+// Resolved returns true iff the activity interval ended in the past.
+func (a *Alert) Resolved() bool {
+ return a.ResolvedAt(time.Now())
+}
+
+// ResolvedAt returns true off the activity interval ended before
+// the given timestamp.
+func (a *Alert) ResolvedAt(ts time.Time) bool {
+ if a.EndsAt.IsZero() {
+ return false
+ }
+ return !a.EndsAt.After(ts)
+}
+
+// Status returns the status of the alert.
+func (a *Alert) Status() AlertStatus {
+ if a.Resolved() {
+ return AlertResolved
+ }
+ return AlertFiring
+}
+
+// Validate checks whether the alert data is inconsistent.
+func (a *Alert) Validate() error {
+ if a.StartsAt.IsZero() {
+ return fmt.Errorf("start time missing")
+ }
+ if !a.EndsAt.IsZero() && a.EndsAt.Before(a.StartsAt) {
+ return fmt.Errorf("start time must be before end time")
+ }
+ if err := a.Labels.Validate(); err != nil {
+ return fmt.Errorf("invalid label set: %s", err)
+ }
+ if len(a.Labels) == 0 {
+ return fmt.Errorf("at least one label pair required")
+ }
+ if err := a.Annotations.Validate(); err != nil {
+ return fmt.Errorf("invalid annotations: %s", err)
+ }
+ return nil
+}
+
+// Alert is a list of alerts that can be sorted in chronological order.
+type Alerts []*Alert
+
+func (as Alerts) Len() int { return len(as) }
+func (as Alerts) Swap(i, j int) { as[i], as[j] = as[j], as[i] }
+
+func (as Alerts) Less(i, j int) bool {
+ if as[i].StartsAt.Before(as[j].StartsAt) {
+ return true
+ }
+ if as[i].EndsAt.Before(as[j].EndsAt) {
+ return true
+ }
+ return as[i].Fingerprint() < as[j].Fingerprint()
+}
+
+// HasFiring returns true iff one of the alerts is not resolved.
+func (as Alerts) HasFiring() bool {
+ for _, a := range as {
+ if !a.Resolved() {
+ return true
+ }
+ }
+ return false
+}
+
+// Status returns StatusFiring iff at least one of the alerts is firing.
+func (as Alerts) Status() AlertStatus {
+ if as.HasFiring() {
+ return AlertFiring
+ }
+ return AlertResolved
+}
diff --git a/vendor/github.com/prometheus/common/model/fingerprinting.go b/vendor/github.com/prometheus/common/model/fingerprinting.go
new file mode 100644
index 0000000..fc4de41
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/fingerprinting.go
@@ -0,0 +1,105 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "fmt"
+ "strconv"
+)
+
+// Fingerprint provides a hash-capable representation of a Metric.
+// For our purposes, FNV-1A 64-bit is used.
+type Fingerprint uint64
+
+// FingerprintFromString transforms a string representation into a Fingerprint.
+func FingerprintFromString(s string) (Fingerprint, error) {
+ num, err := strconv.ParseUint(s, 16, 64)
+ return Fingerprint(num), err
+}
+
+// ParseFingerprint parses the input string into a fingerprint.
+func ParseFingerprint(s string) (Fingerprint, error) {
+ num, err := strconv.ParseUint(s, 16, 64)
+ if err != nil {
+ return 0, err
+ }
+ return Fingerprint(num), nil
+}
+
+func (f Fingerprint) String() string {
+ return fmt.Sprintf("%016x", uint64(f))
+}
+
+// Fingerprints represents a collection of Fingerprint subject to a given
+// natural sorting scheme. It implements sort.Interface.
+type Fingerprints []Fingerprint
+
+// Len implements sort.Interface.
+func (f Fingerprints) Len() int {
+ return len(f)
+}
+
+// Less implements sort.Interface.
+func (f Fingerprints) Less(i, j int) bool {
+ return f[i] < f[j]
+}
+
+// Swap implements sort.Interface.
+func (f Fingerprints) Swap(i, j int) {
+ f[i], f[j] = f[j], f[i]
+}
+
+// FingerprintSet is a set of Fingerprints.
+type FingerprintSet map[Fingerprint]struct{}
+
+// Equal returns true if both sets contain the same elements (and not more).
+func (s FingerprintSet) Equal(o FingerprintSet) bool {
+ if len(s) != len(o) {
+ return false
+ }
+
+ for k := range s {
+ if _, ok := o[k]; !ok {
+ return false
+ }
+ }
+
+ return true
+}
+
+// Intersection returns the elements contained in both sets.
+func (s FingerprintSet) Intersection(o FingerprintSet) FingerprintSet {
+ myLength, otherLength := len(s), len(o)
+ if myLength == 0 || otherLength == 0 {
+ return FingerprintSet{}
+ }
+
+ subSet := s
+ superSet := o
+
+ if otherLength < myLength {
+ subSet = o
+ superSet = s
+ }
+
+ out := FingerprintSet{}
+
+ for k := range subSet {
+ if _, ok := superSet[k]; ok {
+ out[k] = struct{}{}
+ }
+ }
+
+ return out
+}
diff --git a/vendor/github.com/prometheus/common/model/fnv.go b/vendor/github.com/prometheus/common/model/fnv.go
new file mode 100644
index 0000000..038fc1c
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/fnv.go
@@ -0,0 +1,42 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+// Inline and byte-free variant of hash/fnv's fnv64a.
+
+const (
+ offset64 = 14695981039346656037
+ prime64 = 1099511628211
+)
+
+// hashNew initializies a new fnv64a hash value.
+func hashNew() uint64 {
+ return offset64
+}
+
+// hashAdd adds a string to a fnv64a hash value, returning the updated hash.
+func hashAdd(h uint64, s string) uint64 {
+ for i := 0; i < len(s); i++ {
+ h ^= uint64(s[i])
+ h *= prime64
+ }
+ return h
+}
+
+// hashAddByte adds a byte to a fnv64a hash value, returning the updated hash.
+func hashAddByte(h uint64, b byte) uint64 {
+ h ^= uint64(b)
+ h *= prime64
+ return h
+}
diff --git a/vendor/github.com/prometheus/common/model/labels.go b/vendor/github.com/prometheus/common/model/labels.go
new file mode 100644
index 0000000..3b72e7f
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/labels.go
@@ -0,0 +1,206 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "encoding/json"
+ "fmt"
+ "regexp"
+ "strings"
+ "unicode/utf8"
+)
+
+const (
+ // AlertNameLabel is the name of the label containing the an alert's name.
+ AlertNameLabel = "alertname"
+
+ // ExportedLabelPrefix is the prefix to prepend to the label names present in
+ // exported metrics if a label of the same name is added by the server.
+ ExportedLabelPrefix = "exported_"
+
+ // MetricNameLabel is the label name indicating the metric name of a
+ // timeseries.
+ MetricNameLabel = "__name__"
+
+ // SchemeLabel is the name of the label that holds the scheme on which to
+ // scrape a target.
+ SchemeLabel = "__scheme__"
+
+ // AddressLabel is the name of the label that holds the address of
+ // a scrape target.
+ AddressLabel = "__address__"
+
+ // MetricsPathLabel is the name of the label that holds the path on which to
+ // scrape a target.
+ MetricsPathLabel = "__metrics_path__"
+
+ // ReservedLabelPrefix is a prefix which is not legal in user-supplied
+ // label names.
+ ReservedLabelPrefix = "__"
+
+ // MetaLabelPrefix is a prefix for labels that provide meta information.
+ // Labels with this prefix are used for intermediate label processing and
+ // will not be attached to time series.
+ MetaLabelPrefix = "__meta_"
+
+ // TmpLabelPrefix is a prefix for temporary labels as part of relabelling.
+ // Labels with this prefix are used for intermediate label processing and
+ // will not be attached to time series. This is reserved for use in
+ // Prometheus configuration files by users.
+ TmpLabelPrefix = "__tmp_"
+
+ // ParamLabelPrefix is a prefix for labels that provide URL parameters
+ // used to scrape a target.
+ ParamLabelPrefix = "__param_"
+
+ // JobLabel is the label name indicating the job from which a timeseries
+ // was scraped.
+ JobLabel = "job"
+
+ // InstanceLabel is the label name used for the instance label.
+ InstanceLabel = "instance"
+
+ // BucketLabel is used for the label that defines the upper bound of a
+ // bucket of a histogram ("le" -> "less or equal").
+ BucketLabel = "le"
+
+ // QuantileLabel is used for the label that defines the quantile in a
+ // summary.
+ QuantileLabel = "quantile"
+)
+
+// LabelNameRE is a regular expression matching valid label names.
+var LabelNameRE = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
+
+// A LabelName is a key for a LabelSet or Metric. It has a value associated
+// therewith.
+type LabelName string
+
+// IsValid is true iff the label name matches the pattern of LabelNameRE.
+func (ln LabelName) IsValid() bool {
+ if len(ln) == 0 {
+ return false
+ }
+ for i, b := range ln {
+ if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || (b >= '0' && b <= '9' && i > 0)) {
+ return false
+ }
+ }
+ return true
+}
+
+// UnmarshalYAML implements the yaml.Unmarshaler interface.
+func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {
+ var s string
+ if err := unmarshal(&s); err != nil {
+ return err
+ }
+ if !LabelNameRE.MatchString(s) {
+ return fmt.Errorf("%q is not a valid label name", s)
+ }
+ *ln = LabelName(s)
+ return nil
+}
+
+// UnmarshalJSON implements the json.Unmarshaler interface.
+func (ln *LabelName) UnmarshalJSON(b []byte) error {
+ var s string
+ if err := json.Unmarshal(b, &s); err != nil {
+ return err
+ }
+ if !LabelNameRE.MatchString(s) {
+ return fmt.Errorf("%q is not a valid label name", s)
+ }
+ *ln = LabelName(s)
+ return nil
+}
+
+// LabelNames is a sortable LabelName slice. In implements sort.Interface.
+type LabelNames []LabelName
+
+func (l LabelNames) Len() int {
+ return len(l)
+}
+
+func (l LabelNames) Less(i, j int) bool {
+ return l[i] < l[j]
+}
+
+func (l LabelNames) Swap(i, j int) {
+ l[i], l[j] = l[j], l[i]
+}
+
+func (l LabelNames) String() string {
+ labelStrings := make([]string, 0, len(l))
+ for _, label := range l {
+ labelStrings = append(labelStrings, string(label))
+ }
+ return strings.Join(labelStrings, ", ")
+}
+
+// A LabelValue is an associated value for a LabelName.
+type LabelValue string
+
+// IsValid returns true iff the string is a valid UTF8.
+func (lv LabelValue) IsValid() bool {
+ return utf8.ValidString(string(lv))
+}
+
+// LabelValues is a sortable LabelValue slice. It implements sort.Interface.
+type LabelValues []LabelValue
+
+func (l LabelValues) Len() int {
+ return len(l)
+}
+
+func (l LabelValues) Less(i, j int) bool {
+ return string(l[i]) < string(l[j])
+}
+
+func (l LabelValues) Swap(i, j int) {
+ l[i], l[j] = l[j], l[i]
+}
+
+// LabelPair pairs a name with a value.
+type LabelPair struct {
+ Name LabelName
+ Value LabelValue
+}
+
+// LabelPairs is a sortable slice of LabelPair pointers. It implements
+// sort.Interface.
+type LabelPairs []*LabelPair
+
+func (l LabelPairs) Len() int {
+ return len(l)
+}
+
+func (l LabelPairs) Less(i, j int) bool {
+ switch {
+ case l[i].Name > l[j].Name:
+ return false
+ case l[i].Name < l[j].Name:
+ return true
+ case l[i].Value > l[j].Value:
+ return false
+ case l[i].Value < l[j].Value:
+ return true
+ default:
+ return false
+ }
+}
+
+func (l LabelPairs) Swap(i, j int) {
+ l[i], l[j] = l[j], l[i]
+}
diff --git a/vendor/github.com/prometheus/common/model/labelset.go b/vendor/github.com/prometheus/common/model/labelset.go
new file mode 100644
index 0000000..5f931cd
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/labelset.go
@@ -0,0 +1,169 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "encoding/json"
+ "fmt"
+ "sort"
+ "strings"
+)
+
+// A LabelSet is a collection of LabelName and LabelValue pairs. The LabelSet
+// may be fully-qualified down to the point where it may resolve to a single
+// Metric in the data store or not. All operations that occur within the realm
+// of a LabelSet can emit a vector of Metric entities to which the LabelSet may
+// match.
+type LabelSet map[LabelName]LabelValue
+
+// Validate checks whether all names and values in the label set
+// are valid.
+func (ls LabelSet) Validate() error {
+ for ln, lv := range ls {
+ if !ln.IsValid() {
+ return fmt.Errorf("invalid name %q", ln)
+ }
+ if !lv.IsValid() {
+ return fmt.Errorf("invalid value %q", lv)
+ }
+ }
+ return nil
+}
+
+// Equal returns true iff both label sets have exactly the same key/value pairs.
+func (ls LabelSet) Equal(o LabelSet) bool {
+ if len(ls) != len(o) {
+ return false
+ }
+ for ln, lv := range ls {
+ olv, ok := o[ln]
+ if !ok {
+ return false
+ }
+ if olv != lv {
+ return false
+ }
+ }
+ return true
+}
+
+// Before compares the metrics, using the following criteria:
+//
+// If m has fewer labels than o, it is before o. If it has more, it is not.
+//
+// If the number of labels is the same, the superset of all label names is
+// sorted alphanumerically. The first differing label pair found in that order
+// determines the outcome: If the label does not exist at all in m, then m is
+// before o, and vice versa. Otherwise the label value is compared
+// alphanumerically.
+//
+// If m and o are equal, the method returns false.
+func (ls LabelSet) Before(o LabelSet) bool {
+ if len(ls) < len(o) {
+ return true
+ }
+ if len(ls) > len(o) {
+ return false
+ }
+
+ lns := make(LabelNames, 0, len(ls)+len(o))
+ for ln := range ls {
+ lns = append(lns, ln)
+ }
+ for ln := range o {
+ lns = append(lns, ln)
+ }
+ // It's probably not worth it to de-dup lns.
+ sort.Sort(lns)
+ for _, ln := range lns {
+ mlv, ok := ls[ln]
+ if !ok {
+ return true
+ }
+ olv, ok := o[ln]
+ if !ok {
+ return false
+ }
+ if mlv < olv {
+ return true
+ }
+ if mlv > olv {
+ return false
+ }
+ }
+ return false
+}
+
+// Clone returns a copy of the label set.
+func (ls LabelSet) Clone() LabelSet {
+ lsn := make(LabelSet, len(ls))
+ for ln, lv := range ls {
+ lsn[ln] = lv
+ }
+ return lsn
+}
+
+// Merge is a helper function to non-destructively merge two label sets.
+func (l LabelSet) Merge(other LabelSet) LabelSet {
+ result := make(LabelSet, len(l))
+
+ for k, v := range l {
+ result[k] = v
+ }
+
+ for k, v := range other {
+ result[k] = v
+ }
+
+ return result
+}
+
+func (l LabelSet) String() string {
+ lstrs := make([]string, 0, len(l))
+ for l, v := range l {
+ lstrs = append(lstrs, fmt.Sprintf("%s=%q", l, v))
+ }
+
+ sort.Strings(lstrs)
+ return fmt.Sprintf("{%s}", strings.Join(lstrs, ", "))
+}
+
+// Fingerprint returns the LabelSet's fingerprint.
+func (ls LabelSet) Fingerprint() Fingerprint {
+ return labelSetToFingerprint(ls)
+}
+
+// FastFingerprint returns the LabelSet's Fingerprint calculated by a faster hashing
+// algorithm, which is, however, more susceptible to hash collisions.
+func (ls LabelSet) FastFingerprint() Fingerprint {
+ return labelSetToFastFingerprint(ls)
+}
+
+// UnmarshalJSON implements the json.Unmarshaler interface.
+func (l *LabelSet) UnmarshalJSON(b []byte) error {
+ var m map[LabelName]LabelValue
+ if err := json.Unmarshal(b, &m); err != nil {
+ return err
+ }
+ // encoding/json only unmarshals maps of the form map[string]T. It treats
+ // LabelName as a string and does not call its UnmarshalJSON method.
+ // Thus, we have to replicate the behavior here.
+ for ln := range m {
+ if !LabelNameRE.MatchString(string(ln)) {
+ return fmt.Errorf("%q is not a valid label name", ln)
+ }
+ }
+ *l = LabelSet(m)
+ return nil
+}
diff --git a/vendor/github.com/prometheus/common/model/metric.go b/vendor/github.com/prometheus/common/model/metric.go
new file mode 100644
index 0000000..a5da59a
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/metric.go
@@ -0,0 +1,98 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "fmt"
+ "regexp"
+ "sort"
+ "strings"
+)
+
+var (
+ separator = []byte{0}
+ MetricNameRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_:]*$`)
+)
+
+// A Metric is similar to a LabelSet, but the key difference is that a Metric is
+// a singleton and refers to one and only one stream of samples.
+type Metric LabelSet
+
+// Equal compares the metrics.
+func (m Metric) Equal(o Metric) bool {
+ return LabelSet(m).Equal(LabelSet(o))
+}
+
+// Before compares the metrics' underlying label sets.
+func (m Metric) Before(o Metric) bool {
+ return LabelSet(m).Before(LabelSet(o))
+}
+
+// Clone returns a copy of the Metric.
+func (m Metric) Clone() Metric {
+ clone := Metric{}
+ for k, v := range m {
+ clone[k] = v
+ }
+ return clone
+}
+
+func (m Metric) String() string {
+ metricName, hasName := m[MetricNameLabel]
+ numLabels := len(m) - 1
+ if !hasName {
+ numLabels = len(m)
+ }
+ labelStrings := make([]string, 0, numLabels)
+ for label, value := range m {
+ if label != MetricNameLabel {
+ labelStrings = append(labelStrings, fmt.Sprintf("%s=%q", label, value))
+ }
+ }
+
+ switch numLabels {
+ case 0:
+ if hasName {
+ return string(metricName)
+ }
+ return "{}"
+ default:
+ sort.Strings(labelStrings)
+ return fmt.Sprintf("%s{%s}", metricName, strings.Join(labelStrings, ", "))
+ }
+}
+
+// Fingerprint returns a Metric's Fingerprint.
+func (m Metric) Fingerprint() Fingerprint {
+ return LabelSet(m).Fingerprint()
+}
+
+// FastFingerprint returns a Metric's Fingerprint calculated by a faster hashing
+// algorithm, which is, however, more susceptible to hash collisions.
+func (m Metric) FastFingerprint() Fingerprint {
+ return LabelSet(m).FastFingerprint()
+}
+
+// IsValidMetricName returns true iff name matches the pattern of MetricNameRE.
+func IsValidMetricName(n LabelValue) bool {
+ if len(n) == 0 {
+ return false
+ }
+ for i, b := range n {
+ if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == ':' || (b >= '0' && b <= '9' && i > 0)) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/vendor/github.com/prometheus/common/model/model.go b/vendor/github.com/prometheus/common/model/model.go
new file mode 100644
index 0000000..a7b9691
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/model.go
@@ -0,0 +1,16 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package model contains common data structures that are shared across
+// Prometheus components and libraries.
+package model
diff --git a/vendor/github.com/prometheus/common/model/signature.go b/vendor/github.com/prometheus/common/model/signature.go
new file mode 100644
index 0000000..8762b13
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/signature.go
@@ -0,0 +1,144 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "sort"
+)
+
+// SeparatorByte is a byte that cannot occur in valid UTF-8 sequences and is
+// used to separate label names, label values, and other strings from each other
+// when calculating their combined hash value (aka signature aka fingerprint).
+const SeparatorByte byte = 255
+
+var (
+ // cache the signature of an empty label set.
+ emptyLabelSignature = hashNew()
+)
+
+// LabelsToSignature returns a quasi-unique signature (i.e., fingerprint) for a
+// given label set. (Collisions are possible but unlikely if the number of label
+// sets the function is applied to is small.)
+func LabelsToSignature(labels map[string]string) uint64 {
+ if len(labels) == 0 {
+ return emptyLabelSignature
+ }
+
+ labelNames := make([]string, 0, len(labels))
+ for labelName := range labels {
+ labelNames = append(labelNames, labelName)
+ }
+ sort.Strings(labelNames)
+
+ sum := hashNew()
+ for _, labelName := range labelNames {
+ sum = hashAdd(sum, labelName)
+ sum = hashAddByte(sum, SeparatorByte)
+ sum = hashAdd(sum, labels[labelName])
+ sum = hashAddByte(sum, SeparatorByte)
+ }
+ return sum
+}
+
+// labelSetToFingerprint works exactly as LabelsToSignature but takes a LabelSet as
+// parameter (rather than a label map) and returns a Fingerprint.
+func labelSetToFingerprint(ls LabelSet) Fingerprint {
+ if len(ls) == 0 {
+ return Fingerprint(emptyLabelSignature)
+ }
+
+ labelNames := make(LabelNames, 0, len(ls))
+ for labelName := range ls {
+ labelNames = append(labelNames, labelName)
+ }
+ sort.Sort(labelNames)
+
+ sum := hashNew()
+ for _, labelName := range labelNames {
+ sum = hashAdd(sum, string(labelName))
+ sum = hashAddByte(sum, SeparatorByte)
+ sum = hashAdd(sum, string(ls[labelName]))
+ sum = hashAddByte(sum, SeparatorByte)
+ }
+ return Fingerprint(sum)
+}
+
+// labelSetToFastFingerprint works similar to labelSetToFingerprint but uses a
+// faster and less allocation-heavy hash function, which is more susceptible to
+// create hash collisions. Therefore, collision detection should be applied.
+func labelSetToFastFingerprint(ls LabelSet) Fingerprint {
+ if len(ls) == 0 {
+ return Fingerprint(emptyLabelSignature)
+ }
+
+ var result uint64
+ for labelName, labelValue := range ls {
+ sum := hashNew()
+ sum = hashAdd(sum, string(labelName))
+ sum = hashAddByte(sum, SeparatorByte)
+ sum = hashAdd(sum, string(labelValue))
+ result ^= sum
+ }
+ return Fingerprint(result)
+}
+
+// SignatureForLabels works like LabelsToSignature but takes a Metric as
+// parameter (rather than a label map) and only includes the labels with the
+// specified LabelNames into the signature calculation. The labels passed in
+// will be sorted by this function.
+func SignatureForLabels(m Metric, labels ...LabelName) uint64 {
+ if len(labels) == 0 {
+ return emptyLabelSignature
+ }
+
+ sort.Sort(LabelNames(labels))
+
+ sum := hashNew()
+ for _, label := range labels {
+ sum = hashAdd(sum, string(label))
+ sum = hashAddByte(sum, SeparatorByte)
+ sum = hashAdd(sum, string(m[label]))
+ sum = hashAddByte(sum, SeparatorByte)
+ }
+ return sum
+}
+
+// SignatureWithoutLabels works like LabelsToSignature but takes a Metric as
+// parameter (rather than a label map) and excludes the labels with any of the
+// specified LabelNames from the signature calculation.
+func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64 {
+ if len(m) == 0 {
+ return emptyLabelSignature
+ }
+
+ labelNames := make(LabelNames, 0, len(m))
+ for labelName := range m {
+ if _, exclude := labels[labelName]; !exclude {
+ labelNames = append(labelNames, labelName)
+ }
+ }
+ if len(labelNames) == 0 {
+ return emptyLabelSignature
+ }
+ sort.Sort(labelNames)
+
+ sum := hashNew()
+ for _, labelName := range labelNames {
+ sum = hashAdd(sum, string(labelName))
+ sum = hashAddByte(sum, SeparatorByte)
+ sum = hashAdd(sum, string(m[labelName]))
+ sum = hashAddByte(sum, SeparatorByte)
+ }
+ return sum
+}
diff --git a/vendor/github.com/prometheus/common/model/silence.go b/vendor/github.com/prometheus/common/model/silence.go
new file mode 100644
index 0000000..7538e29
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/silence.go
@@ -0,0 +1,106 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "encoding/json"
+ "fmt"
+ "regexp"
+ "time"
+)
+
+// Matcher describes a matches the value of a given label.
+type Matcher struct {
+ Name LabelName `json:"name"`
+ Value string `json:"value"`
+ IsRegex bool `json:"isRegex"`
+}
+
+func (m *Matcher) UnmarshalJSON(b []byte) error {
+ type plain Matcher
+ if err := json.Unmarshal(b, (*plain)(m)); err != nil {
+ return err
+ }
+
+ if len(m.Name) == 0 {
+ return fmt.Errorf("label name in matcher must not be empty")
+ }
+ if m.IsRegex {
+ if _, err := regexp.Compile(m.Value); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Validate returns true iff all fields of the matcher have valid values.
+func (m *Matcher) Validate() error {
+ if !m.Name.IsValid() {
+ return fmt.Errorf("invalid name %q", m.Name)
+ }
+ if m.IsRegex {
+ if _, err := regexp.Compile(m.Value); err != nil {
+ return fmt.Errorf("invalid regular expression %q", m.Value)
+ }
+ } else if !LabelValue(m.Value).IsValid() || len(m.Value) == 0 {
+ return fmt.Errorf("invalid value %q", m.Value)
+ }
+ return nil
+}
+
+// Silence defines the representation of a silence definiton
+// in the Prometheus eco-system.
+type Silence struct {
+ ID uint64 `json:"id,omitempty"`
+
+ Matchers []*Matcher `json:"matchers"`
+
+ StartsAt time.Time `json:"startsAt"`
+ EndsAt time.Time `json:"endsAt"`
+
+ CreatedAt time.Time `json:"createdAt,omitempty"`
+ CreatedBy string `json:"createdBy"`
+ Comment string `json:"comment,omitempty"`
+}
+
+// Validate returns true iff all fields of the silence have valid values.
+func (s *Silence) Validate() error {
+ if len(s.Matchers) == 0 {
+ return fmt.Errorf("at least one matcher required")
+ }
+ for _, m := range s.Matchers {
+ if err := m.Validate(); err != nil {
+ return fmt.Errorf("invalid matcher: %s", err)
+ }
+ }
+ if s.StartsAt.IsZero() {
+ return fmt.Errorf("start time missing")
+ }
+ if s.EndsAt.IsZero() {
+ return fmt.Errorf("end time missing")
+ }
+ if s.EndsAt.Before(s.StartsAt) {
+ return fmt.Errorf("start time must be before end time")
+ }
+ if s.CreatedBy == "" {
+ return fmt.Errorf("creator information missing")
+ }
+ if s.Comment == "" {
+ return fmt.Errorf("comment missing")
+ }
+ if s.CreatedAt.IsZero() {
+ return fmt.Errorf("creation timestamp missing")
+ }
+ return nil
+}
diff --git a/vendor/github.com/prometheus/common/model/time.go b/vendor/github.com/prometheus/common/model/time.go
new file mode 100644
index 0000000..548968a
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/time.go
@@ -0,0 +1,249 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "fmt"
+ "math"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+)
+
+const (
+ // MinimumTick is the minimum supported time resolution. This has to be
+ // at least time.Second in order for the code below to work.
+ minimumTick = time.Millisecond
+ // second is the Time duration equivalent to one second.
+ second = int64(time.Second / minimumTick)
+ // The number of nanoseconds per minimum tick.
+ nanosPerTick = int64(minimumTick / time.Nanosecond)
+
+ // Earliest is the earliest Time representable. Handy for
+ // initializing a high watermark.
+ Earliest = Time(math.MinInt64)
+ // Latest is the latest Time representable. Handy for initializing
+ // a low watermark.
+ Latest = Time(math.MaxInt64)
+)
+
+// Time is the number of milliseconds since the epoch
+// (1970-01-01 00:00 UTC) excluding leap seconds.
+type Time int64
+
+// Interval describes and interval between two timestamps.
+type Interval struct {
+ Start, End Time
+}
+
+// Now returns the current time as a Time.
+func Now() Time {
+ return TimeFromUnixNano(time.Now().UnixNano())
+}
+
+// TimeFromUnix returns the Time equivalent to the Unix Time t
+// provided in seconds.
+func TimeFromUnix(t int64) Time {
+ return Time(t * second)
+}
+
+// TimeFromUnixNano returns the Time equivalent to the Unix Time
+// t provided in nanoseconds.
+func TimeFromUnixNano(t int64) Time {
+ return Time(t / nanosPerTick)
+}
+
+// Equal reports whether two Times represent the same instant.
+func (t Time) Equal(o Time) bool {
+ return t == o
+}
+
+// Before reports whether the Time t is before o.
+func (t Time) Before(o Time) bool {
+ return t < o
+}
+
+// After reports whether the Time t is after o.
+func (t Time) After(o Time) bool {
+ return t > o
+}
+
+// Add returns the Time t + d.
+func (t Time) Add(d time.Duration) Time {
+ return t + Time(d/minimumTick)
+}
+
+// Sub returns the Duration t - o.
+func (t Time) Sub(o Time) time.Duration {
+ return time.Duration(t-o) * minimumTick
+}
+
+// Time returns the time.Time representation of t.
+func (t Time) Time() time.Time {
+ return time.Unix(int64(t)/second, (int64(t)%second)*nanosPerTick)
+}
+
+// Unix returns t as a Unix time, the number of seconds elapsed
+// since January 1, 1970 UTC.
+func (t Time) Unix() int64 {
+ return int64(t) / second
+}
+
+// UnixNano returns t as a Unix time, the number of nanoseconds elapsed
+// since January 1, 1970 UTC.
+func (t Time) UnixNano() int64 {
+ return int64(t) * nanosPerTick
+}
+
+// The number of digits after the dot.
+var dotPrecision = int(math.Log10(float64(second)))
+
+// String returns a string representation of the Time.
+func (t Time) String() string {
+ return strconv.FormatFloat(float64(t)/float64(second), 'f', -1, 64)
+}
+
+// MarshalJSON implements the json.Marshaler interface.
+func (t Time) MarshalJSON() ([]byte, error) {
+ return []byte(t.String()), nil
+}
+
+// UnmarshalJSON implements the json.Unmarshaler interface.
+func (t *Time) UnmarshalJSON(b []byte) error {
+ p := strings.Split(string(b), ".")
+ switch len(p) {
+ case 1:
+ v, err := strconv.ParseInt(string(p[0]), 10, 64)
+ if err != nil {
+ return err
+ }
+ *t = Time(v * second)
+
+ case 2:
+ v, err := strconv.ParseInt(string(p[0]), 10, 64)
+ if err != nil {
+ return err
+ }
+ v *= second
+
+ prec := dotPrecision - len(p[1])
+ if prec < 0 {
+ p[1] = p[1][:dotPrecision]
+ } else if prec > 0 {
+ p[1] = p[1] + strings.Repeat("0", prec)
+ }
+
+ va, err := strconv.ParseInt(p[1], 10, 32)
+ if err != nil {
+ return err
+ }
+
+ *t = Time(v + va)
+
+ default:
+ return fmt.Errorf("invalid time %q", string(b))
+ }
+ return nil
+}
+
+// Duration wraps time.Duration. It is used to parse the custom duration format
+// from YAML.
+// This type should not propagate beyond the scope of input/output processing.
+type Duration time.Duration
+
+var durationRE = regexp.MustCompile("^([0-9]+)(y|w|d|h|m|s|ms)$")
+
+// StringToDuration parses a string into a time.Duration, assuming that a year
+// always has 365d, a week always has 7d, and a day always has 24h.
+func ParseDuration(durationStr string) (Duration, error) {
+ matches := durationRE.FindStringSubmatch(durationStr)
+ if len(matches) != 3 {
+ return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
+ }
+ var (
+ n, _ = strconv.Atoi(matches[1])
+ dur = time.Duration(n) * time.Millisecond
+ )
+ switch unit := matches[2]; unit {
+ case "y":
+ dur *= 1000 * 60 * 60 * 24 * 365
+ case "w":
+ dur *= 1000 * 60 * 60 * 24 * 7
+ case "d":
+ dur *= 1000 * 60 * 60 * 24
+ case "h":
+ dur *= 1000 * 60 * 60
+ case "m":
+ dur *= 1000 * 60
+ case "s":
+ dur *= 1000
+ case "ms":
+ // Value already correct
+ default:
+ return 0, fmt.Errorf("invalid time unit in duration string: %q", unit)
+ }
+ return Duration(dur), nil
+}
+
+func (d Duration) String() string {
+ var (
+ ms = int64(time.Duration(d) / time.Millisecond)
+ unit = "ms"
+ )
+ factors := map[string]int64{
+ "y": 1000 * 60 * 60 * 24 * 365,
+ "w": 1000 * 60 * 60 * 24 * 7,
+ "d": 1000 * 60 * 60 * 24,
+ "h": 1000 * 60 * 60,
+ "m": 1000 * 60,
+ "s": 1000,
+ "ms": 1,
+ }
+
+ switch int64(0) {
+ case ms % factors["y"]:
+ unit = "y"
+ case ms % factors["w"]:
+ unit = "w"
+ case ms % factors["d"]:
+ unit = "d"
+ case ms % factors["h"]:
+ unit = "h"
+ case ms % factors["m"]:
+ unit = "m"
+ case ms % factors["s"]:
+ unit = "s"
+ }
+ return fmt.Sprintf("%v%v", ms/factors[unit], unit)
+}
+
+// MarshalYAML implements the yaml.Marshaler interface.
+func (d Duration) MarshalYAML() (interface{}, error) {
+ return d.String(), nil
+}
+
+// UnmarshalYAML implements the yaml.Unmarshaler interface.
+func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
+ var s string
+ if err := unmarshal(&s); err != nil {
+ return err
+ }
+ dur, err := ParseDuration(s)
+ if err != nil {
+ return err
+ }
+ *d = dur
+ return nil
+}
diff --git a/vendor/github.com/prometheus/common/model/value.go b/vendor/github.com/prometheus/common/model/value.go
new file mode 100644
index 0000000..dbf5d10
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/value.go
@@ -0,0 +1,403 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+// A SampleValue is a representation of a value for a given sample at a given
+// time.
+type SampleValue float64
+
+// MarshalJSON implements json.Marshaler.
+func (v SampleValue) MarshalJSON() ([]byte, error) {
+ return json.Marshal(v.String())
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+func (v *SampleValue) UnmarshalJSON(b []byte) error {
+ if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
+ return fmt.Errorf("sample value must be a quoted string")
+ }
+ f, err := strconv.ParseFloat(string(b[1:len(b)-1]), 64)
+ if err != nil {
+ return err
+ }
+ *v = SampleValue(f)
+ return nil
+}
+
+// Equal returns true if the value of v and o is equal or if both are NaN. Note
+// that v==o is false if both are NaN. If you want the conventional float
+// behavior, use == to compare two SampleValues.
+func (v SampleValue) Equal(o SampleValue) bool {
+ if v == o {
+ return true
+ }
+ return math.IsNaN(float64(v)) && math.IsNaN(float64(o))
+}
+
+func (v SampleValue) String() string {
+ return strconv.FormatFloat(float64(v), 'f', -1, 64)
+}
+
+// SamplePair pairs a SampleValue with a Timestamp.
+type SamplePair struct {
+ Timestamp Time
+ Value SampleValue
+}
+
+// MarshalJSON implements json.Marshaler.
+func (s SamplePair) MarshalJSON() ([]byte, error) {
+ t, err := json.Marshal(s.Timestamp)
+ if err != nil {
+ return nil, err
+ }
+ v, err := json.Marshal(s.Value)
+ if err != nil {
+ return nil, err
+ }
+ return []byte(fmt.Sprintf("[%s,%s]", t, v)), nil
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+func (s *SamplePair) UnmarshalJSON(b []byte) error {
+ v := [...]json.Unmarshaler{&s.Timestamp, &s.Value}
+ return json.Unmarshal(b, &v)
+}
+
+// Equal returns true if this SamplePair and o have equal Values and equal
+// Timestamps. The sematics of Value equality is defined by SampleValue.Equal.
+func (s *SamplePair) Equal(o *SamplePair) bool {
+ return s == o || (s.Value.Equal(o.Value) && s.Timestamp.Equal(o.Timestamp))
+}
+
+func (s SamplePair) String() string {
+ return fmt.Sprintf("%s @[%s]", s.Value, s.Timestamp)
+}
+
+// Sample is a sample pair associated with a metric.
+type Sample struct {
+ Metric Metric `json:"metric"`
+ Value SampleValue `json:"value"`
+ Timestamp Time `json:"timestamp"`
+}
+
+// Equal compares first the metrics, then the timestamp, then the value. The
+// sematics of value equality is defined by SampleValue.Equal.
+func (s *Sample) Equal(o *Sample) bool {
+ if s == o {
+ return true
+ }
+
+ if !s.Metric.Equal(o.Metric) {
+ return false
+ }
+ if !s.Timestamp.Equal(o.Timestamp) {
+ return false
+ }
+ if s.Value.Equal(o.Value) {
+ return false
+ }
+
+ return true
+}
+
+func (s Sample) String() string {
+ return fmt.Sprintf("%s => %s", s.Metric, SamplePair{
+ Timestamp: s.Timestamp,
+ Value: s.Value,
+ })
+}
+
+// MarshalJSON implements json.Marshaler.
+func (s Sample) MarshalJSON() ([]byte, error) {
+ v := struct {
+ Metric Metric `json:"metric"`
+ Value SamplePair `json:"value"`
+ }{
+ Metric: s.Metric,
+ Value: SamplePair{
+ Timestamp: s.Timestamp,
+ Value: s.Value,
+ },
+ }
+
+ return json.Marshal(&v)
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+func (s *Sample) UnmarshalJSON(b []byte) error {
+ v := struct {
+ Metric Metric `json:"metric"`
+ Value SamplePair `json:"value"`
+ }{
+ Metric: s.Metric,
+ Value: SamplePair{
+ Timestamp: s.Timestamp,
+ Value: s.Value,
+ },
+ }
+
+ if err := json.Unmarshal(b, &v); err != nil {
+ return err
+ }
+
+ s.Metric = v.Metric
+ s.Timestamp = v.Value.Timestamp
+ s.Value = v.Value.Value
+
+ return nil
+}
+
+// Samples is a sortable Sample slice. It implements sort.Interface.
+type Samples []*Sample
+
+func (s Samples) Len() int {
+ return len(s)
+}
+
+// Less compares first the metrics, then the timestamp.
+func (s Samples) Less(i, j int) bool {
+ switch {
+ case s[i].Metric.Before(s[j].Metric):
+ return true
+ case s[j].Metric.Before(s[i].Metric):
+ return false
+ case s[i].Timestamp.Before(s[j].Timestamp):
+ return true
+ default:
+ return false
+ }
+}
+
+func (s Samples) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+
+// Equal compares two sets of samples and returns true if they are equal.
+func (s Samples) Equal(o Samples) bool {
+ if len(s) != len(o) {
+ return false
+ }
+
+ for i, sample := range s {
+ if !sample.Equal(o[i]) {
+ return false
+ }
+ }
+ return true
+}
+
+// SampleStream is a stream of Values belonging to an attached COWMetric.
+type SampleStream struct {
+ Metric Metric `json:"metric"`
+ Values []SamplePair `json:"values"`
+}
+
+func (ss SampleStream) String() string {
+ vals := make([]string, len(ss.Values))
+ for i, v := range ss.Values {
+ vals[i] = v.String()
+ }
+ return fmt.Sprintf("%s =>\n%s", ss.Metric, strings.Join(vals, "\n"))
+}
+
+// Value is a generic interface for values resulting from a query evaluation.
+type Value interface {
+ Type() ValueType
+ String() string
+}
+
+func (Matrix) Type() ValueType { return ValMatrix }
+func (Vector) Type() ValueType { return ValVector }
+func (*Scalar) Type() ValueType { return ValScalar }
+func (*String) Type() ValueType { return ValString }
+
+type ValueType int
+
+const (
+ ValNone ValueType = iota
+ ValScalar
+ ValVector
+ ValMatrix
+ ValString
+)
+
+// MarshalJSON implements json.Marshaler.
+func (et ValueType) MarshalJSON() ([]byte, error) {
+ return json.Marshal(et.String())
+}
+
+func (et *ValueType) UnmarshalJSON(b []byte) error {
+ var s string
+ if err := json.Unmarshal(b, &s); err != nil {
+ return err
+ }
+ switch s {
+ case "<ValNone>":
+ *et = ValNone
+ case "scalar":
+ *et = ValScalar
+ case "vector":
+ *et = ValVector
+ case "matrix":
+ *et = ValMatrix
+ case "string":
+ *et = ValString
+ default:
+ return fmt.Errorf("unknown value type %q", s)
+ }
+ return nil
+}
+
+func (e ValueType) String() string {
+ switch e {
+ case ValNone:
+ return "<ValNone>"
+ case ValScalar:
+ return "scalar"
+ case ValVector:
+ return "vector"
+ case ValMatrix:
+ return "matrix"
+ case ValString:
+ return "string"
+ }
+ panic("ValueType.String: unhandled value type")
+}
+
+// Scalar is a scalar value evaluated at the set timestamp.
+type Scalar struct {
+ Value SampleValue `json:"value"`
+ Timestamp Time `json:"timestamp"`
+}
+
+func (s Scalar) String() string {
+ return fmt.Sprintf("scalar: %v @[%v]", s.Value, s.Timestamp)
+}
+
+// MarshalJSON implements json.Marshaler.
+func (s Scalar) MarshalJSON() ([]byte, error) {
+ v := strconv.FormatFloat(float64(s.Value), 'f', -1, 64)
+ return json.Marshal([...]interface{}{s.Timestamp, string(v)})
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+func (s *Scalar) UnmarshalJSON(b []byte) error {
+ var f string
+ v := [...]interface{}{&s.Timestamp, &f}
+
+ if err := json.Unmarshal(b, &v); err != nil {
+ return err
+ }
+
+ value, err := strconv.ParseFloat(f, 64)
+ if err != nil {
+ return fmt.Errorf("error parsing sample value: %s", err)
+ }
+ s.Value = SampleValue(value)
+ return nil
+}
+
+// String is a string value evaluated at the set timestamp.
+type String struct {
+ Value string `json:"value"`
+ Timestamp Time `json:"timestamp"`
+}
+
+func (s *String) String() string {
+ return s.Value
+}
+
+// MarshalJSON implements json.Marshaler.
+func (s String) MarshalJSON() ([]byte, error) {
+ return json.Marshal([]interface{}{s.Timestamp, s.Value})
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+func (s *String) UnmarshalJSON(b []byte) error {
+ v := [...]interface{}{&s.Timestamp, &s.Value}
+ return json.Unmarshal(b, &v)
+}
+
+// Vector is basically only an alias for Samples, but the
+// contract is that in a Vector, all Samples have the same timestamp.
+type Vector []*Sample
+
+func (vec Vector) String() string {
+ entries := make([]string, len(vec))
+ for i, s := range vec {
+ entries[i] = s.String()
+ }
+ return strings.Join(entries, "\n")
+}
+
+func (vec Vector) Len() int { return len(vec) }
+func (vec Vector) Swap(i, j int) { vec[i], vec[j] = vec[j], vec[i] }
+
+// Less compares first the metrics, then the timestamp.
+func (vec Vector) Less(i, j int) bool {
+ switch {
+ case vec[i].Metric.Before(vec[j].Metric):
+ return true
+ case vec[j].Metric.Before(vec[i].Metric):
+ return false
+ case vec[i].Timestamp.Before(vec[j].Timestamp):
+ return true
+ default:
+ return false
+ }
+}
+
+// Equal compares two sets of samples and returns true if they are equal.
+func (vec Vector) Equal(o Vector) bool {
+ if len(vec) != len(o) {
+ return false
+ }
+
+ for i, sample := range vec {
+ if !sample.Equal(o[i]) {
+ return false
+ }
+ }
+ return true
+}
+
+// Matrix is a list of time series.
+type Matrix []*SampleStream
+
+func (m Matrix) Len() int { return len(m) }
+func (m Matrix) Less(i, j int) bool { return m[i].Metric.Before(m[j].Metric) }
+func (m Matrix) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
+
+func (mat Matrix) String() string {
+ matCp := make(Matrix, len(mat))
+ copy(matCp, mat)
+ sort.Sort(matCp)
+
+ strs := make([]string, len(matCp))
+
+ for i, ss := range matCp {
+ strs[i] = ss.String()
+ }
+
+ return strings.Join(strs, "\n")
+}
diff --git a/vendor/github.com/prometheus/procfs/LICENSE b/vendor/github.com/prometheus/procfs/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/prometheus/procfs/NOTICE b/vendor/github.com/prometheus/procfs/NOTICE
new file mode 100644
index 0000000..53c5e9a
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/NOTICE
@@ -0,0 +1,7 @@
+procfs provides functions to retrieve system, kernel and process
+metrics from the pseudo-filesystem proc.
+
+Copyright 2014-2015 The Prometheus Authors
+
+This product includes software developed at
+SoundCloud Ltd. (http://soundcloud.com/).
diff --git a/vendor/github.com/prometheus/procfs/README.md b/vendor/github.com/prometheus/procfs/README.md
new file mode 100644
index 0000000..6e7ee6b
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/README.md
@@ -0,0 +1,10 @@
+# procfs
+
+This procfs package provides functions to retrieve system, kernel and process
+metrics from the pseudo-filesystem proc.
+
+*WARNING*: This package is a work in progress. Its API may still break in
+backwards-incompatible ways without warnings. Use it at your own risk.
+
+[![GoDoc](https://godoc.org/github.com/prometheus/procfs?status.png)](https://godoc.org/github.com/prometheus/procfs)
+[![Build Status](https://travis-ci.org/prometheus/procfs.svg?branch=master)](https://travis-ci.org/prometheus/procfs)
diff --git a/vendor/github.com/prometheus/procfs/doc.go b/vendor/github.com/prometheus/procfs/doc.go
new file mode 100644
index 0000000..e2acd6d
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/doc.go
@@ -0,0 +1,45 @@
+// Copyright 2014 Prometheus Team
+// 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 procfs provides functions to retrieve system, kernel and process
+// metrics from the pseudo-filesystem proc.
+//
+// Example:
+//
+// package main
+//
+// import (
+// "fmt"
+// "log"
+//
+// "github.com/prometheus/procfs"
+// )
+//
+// func main() {
+// p, err := procfs.Self()
+// if err != nil {
+// log.Fatalf("could not get process: %s", err)
+// }
+//
+// stat, err := p.NewStat()
+// if err != nil {
+// log.Fatalf("could not get process stat: %s", err)
+// }
+//
+// fmt.Printf("command: %s\n", stat.Comm)
+// fmt.Printf("cpu time: %fs\n", stat.CPUTime())
+// fmt.Printf("vsize: %dB\n", stat.VirtualMemory())
+// fmt.Printf("rss: %dB\n", stat.ResidentMemory())
+// }
+//
+package procfs
diff --git a/vendor/github.com/prometheus/procfs/fs.go b/vendor/github.com/prometheus/procfs/fs.go
new file mode 100644
index 0000000..49aaab0
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/fs.go
@@ -0,0 +1,33 @@
+package procfs
+
+import (
+ "fmt"
+ "os"
+ "path"
+)
+
+// FS represents the pseudo-filesystem proc, which provides an interface to
+// kernel data structures.
+type FS string
+
+// DefaultMountPoint is the common mount point of the proc filesystem.
+const DefaultMountPoint = "/proc"
+
+// NewFS returns a new FS mounted under the given mountPoint. It will error
+// if the mount point can't be read.
+func NewFS(mountPoint string) (FS, error) {
+ info, err := os.Stat(mountPoint)
+ if err != nil {
+ return "", fmt.Errorf("could not read %s: %s", mountPoint, err)
+ }
+ if !info.IsDir() {
+ return "", fmt.Errorf("mount point %s is not a directory", mountPoint)
+ }
+
+ return FS(mountPoint), nil
+}
+
+// Path returns the path of the given subsystem relative to the procfs root.
+func (fs FS) Path(p ...string) string {
+ return path.Join(append([]string{string(fs)}, p...)...)
+}
diff --git a/vendor/github.com/prometheus/procfs/ipvs.go b/vendor/github.com/prometheus/procfs/ipvs.go
new file mode 100644
index 0000000..e7012f7
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/ipvs.go
@@ -0,0 +1,224 @@
+package procfs
+
+import (
+ "bufio"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net"
+ "os"
+ "strconv"
+ "strings"
+)
+
+// IPVSStats holds IPVS statistics, as exposed by the kernel in `/proc/net/ip_vs_stats`.
+type IPVSStats struct {
+ // Total count of connections.
+ Connections uint64
+ // Total incoming packages processed.
+ IncomingPackets uint64
+ // Total outgoing packages processed.
+ OutgoingPackets uint64
+ // Total incoming traffic.
+ IncomingBytes uint64
+ // Total outgoing traffic.
+ OutgoingBytes uint64
+}
+
+// IPVSBackendStatus holds current metrics of one virtual / real address pair.
+type IPVSBackendStatus struct {
+ // The local (virtual) IP address.
+ LocalAddress net.IP
+ // The local (virtual) port.
+ LocalPort uint16
+ // The transport protocol (TCP, UDP).
+ Proto string
+ // The remote (real) IP address.
+ RemoteAddress net.IP
+ // The remote (real) port.
+ RemotePort uint16
+ // The current number of active connections for this virtual/real address pair.
+ ActiveConn uint64
+ // The current number of inactive connections for this virtual/real address pair.
+ InactConn uint64
+ // The current weight of this virtual/real address pair.
+ Weight uint64
+}
+
+// NewIPVSStats reads the IPVS statistics.
+func NewIPVSStats() (IPVSStats, error) {
+ fs, err := NewFS(DefaultMountPoint)
+ if err != nil {
+ return IPVSStats{}, err
+ }
+
+ return fs.NewIPVSStats()
+}
+
+// NewIPVSStats reads the IPVS statistics from the specified `proc` filesystem.
+func (fs FS) NewIPVSStats() (IPVSStats, error) {
+ file, err := os.Open(fs.Path("net/ip_vs_stats"))
+ if err != nil {
+ return IPVSStats{}, err
+ }
+ defer file.Close()
+
+ return parseIPVSStats(file)
+}
+
+// parseIPVSStats performs the actual parsing of `ip_vs_stats`.
+func parseIPVSStats(file io.Reader) (IPVSStats, error) {
+ var (
+ statContent []byte
+ statLines []string
+ statFields []string
+ stats IPVSStats
+ )
+
+ statContent, err := ioutil.ReadAll(file)
+ if err != nil {
+ return IPVSStats{}, err
+ }
+
+ statLines = strings.SplitN(string(statContent), "\n", 4)
+ if len(statLines) != 4 {
+ return IPVSStats{}, errors.New("ip_vs_stats corrupt: too short")
+ }
+
+ statFields = strings.Fields(statLines[2])
+ if len(statFields) != 5 {
+ return IPVSStats{}, errors.New("ip_vs_stats corrupt: unexpected number of fields")
+ }
+
+ stats.Connections, err = strconv.ParseUint(statFields[0], 16, 64)
+ if err != nil {
+ return IPVSStats{}, err
+ }
+ stats.IncomingPackets, err = strconv.ParseUint(statFields[1], 16, 64)
+ if err != nil {
+ return IPVSStats{}, err
+ }
+ stats.OutgoingPackets, err = strconv.ParseUint(statFields[2], 16, 64)
+ if err != nil {
+ return IPVSStats{}, err
+ }
+ stats.IncomingBytes, err = strconv.ParseUint(statFields[3], 16, 64)
+ if err != nil {
+ return IPVSStats{}, err
+ }
+ stats.OutgoingBytes, err = strconv.ParseUint(statFields[4], 16, 64)
+ if err != nil {
+ return IPVSStats{}, err
+ }
+
+ return stats, nil
+}
+
+// NewIPVSBackendStatus reads and returns the status of all (virtual,real) server pairs.
+func NewIPVSBackendStatus() ([]IPVSBackendStatus, error) {
+ fs, err := NewFS(DefaultMountPoint)
+ if err != nil {
+ return []IPVSBackendStatus{}, err
+ }
+
+ return fs.NewIPVSBackendStatus()
+}
+
+// NewIPVSBackendStatus reads and returns the status of all (virtual,real) server pairs from the specified `proc` filesystem.
+func (fs FS) NewIPVSBackendStatus() ([]IPVSBackendStatus, error) {
+ file, err := os.Open(fs.Path("net/ip_vs"))
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+
+ return parseIPVSBackendStatus(file)
+}
+
+func parseIPVSBackendStatus(file io.Reader) ([]IPVSBackendStatus, error) {
+ var (
+ status []IPVSBackendStatus
+ scanner = bufio.NewScanner(file)
+ proto string
+ localAddress net.IP
+ localPort uint16
+ err error
+ )
+
+ for scanner.Scan() {
+ fields := strings.Fields(string(scanner.Text()))
+ if len(fields) == 0 {
+ continue
+ }
+ switch {
+ case fields[0] == "IP" || fields[0] == "Prot" || fields[1] == "RemoteAddress:Port":
+ continue
+ case fields[0] == "TCP" || fields[0] == "UDP":
+ if len(fields) < 2 {
+ continue
+ }
+ proto = fields[0]
+ localAddress, localPort, err = parseIPPort(fields[1])
+ if err != nil {
+ return nil, err
+ }
+ case fields[0] == "->":
+ if len(fields) < 6 {
+ continue
+ }
+ remoteAddress, remotePort, err := parseIPPort(fields[1])
+ if err != nil {
+ return nil, err
+ }
+ weight, err := strconv.ParseUint(fields[3], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ activeConn, err := strconv.ParseUint(fields[4], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ inactConn, err := strconv.ParseUint(fields[5], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ status = append(status, IPVSBackendStatus{
+ LocalAddress: localAddress,
+ LocalPort: localPort,
+ RemoteAddress: remoteAddress,
+ RemotePort: remotePort,
+ Proto: proto,
+ Weight: weight,
+ ActiveConn: activeConn,
+ InactConn: inactConn,
+ })
+ }
+ }
+ return status, nil
+}
+
+func parseIPPort(s string) (net.IP, uint16, error) {
+ tmp := strings.SplitN(s, ":", 2)
+
+ if len(tmp) != 2 {
+ return nil, 0, fmt.Errorf("invalid IP:Port: %s", s)
+ }
+
+ if len(tmp[0]) != 8 && len(tmp[0]) != 32 {
+ return nil, 0, fmt.Errorf("invalid IP: %s", tmp[0])
+ }
+
+ ip, err := hex.DecodeString(tmp[0])
+ if err != nil {
+ return nil, 0, err
+ }
+
+ port, err := strconv.ParseUint(tmp[1], 16, 16)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ return ip, uint16(port), nil
+}
diff --git a/vendor/github.com/prometheus/procfs/mdstat.go b/vendor/github.com/prometheus/procfs/mdstat.go
new file mode 100644
index 0000000..d7a248c
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/mdstat.go
@@ -0,0 +1,138 @@
+package procfs
+
+import (
+ "fmt"
+ "io/ioutil"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+var (
+ statuslineRE = regexp.MustCompile(`(\d+) blocks .*\[(\d+)/(\d+)\] \[[U_]+\]`)
+ buildlineRE = regexp.MustCompile(`\((\d+)/\d+\)`)
+)
+
+// MDStat holds info parsed from /proc/mdstat.
+type MDStat struct {
+ // Name of the device.
+ Name string
+ // activity-state of the device.
+ ActivityState string
+ // Number of active disks.
+ DisksActive int64
+ // Total number of disks the device consists of.
+ DisksTotal int64
+ // Number of blocks the device holds.
+ BlocksTotal int64
+ // Number of blocks on the device that are in sync.
+ BlocksSynced int64
+}
+
+// ParseMDStat parses an mdstat-file and returns a struct with the relevant infos.
+func (fs FS) ParseMDStat() (mdstates []MDStat, err error) {
+ mdStatusFilePath := fs.Path("mdstat")
+ content, err := ioutil.ReadFile(mdStatusFilePath)
+ if err != nil {
+ return []MDStat{}, fmt.Errorf("error parsing %s: %s", mdStatusFilePath, err)
+ }
+
+ mdStates := []MDStat{}
+ lines := strings.Split(string(content), "\n")
+ for i, l := range lines {
+ if l == "" {
+ continue
+ }
+ if l[0] == ' ' {
+ continue
+ }
+ if strings.HasPrefix(l, "Personalities") || strings.HasPrefix(l, "unused") {
+ continue
+ }
+
+ mainLine := strings.Split(l, " ")
+ if len(mainLine) < 3 {
+ return mdStates, fmt.Errorf("error parsing mdline: %s", l)
+ }
+ mdName := mainLine[0]
+ activityState := mainLine[2]
+
+ if len(lines) <= i+3 {
+ return mdStates, fmt.Errorf(
+ "error parsing %s: too few lines for md device %s",
+ mdStatusFilePath,
+ mdName,
+ )
+ }
+
+ active, total, size, err := evalStatusline(lines[i+1])
+ if err != nil {
+ return mdStates, fmt.Errorf("error parsing %s: %s", mdStatusFilePath, err)
+ }
+
+ // j is the line number of the syncing-line.
+ j := i + 2
+ if strings.Contains(lines[i+2], "bitmap") { // skip bitmap line
+ j = i + 3
+ }
+
+ // If device is syncing at the moment, get the number of currently
+ // synced bytes, otherwise that number equals the size of the device.
+ syncedBlocks := size
+ if strings.Contains(lines[j], "recovery") || strings.Contains(lines[j], "resync") {
+ syncedBlocks, err = evalBuildline(lines[j])
+ if err != nil {
+ return mdStates, fmt.Errorf("error parsing %s: %s", mdStatusFilePath, err)
+ }
+ }
+
+ mdStates = append(mdStates, MDStat{
+ Name: mdName,
+ ActivityState: activityState,
+ DisksActive: active,
+ DisksTotal: total,
+ BlocksTotal: size,
+ BlocksSynced: syncedBlocks,
+ })
+ }
+
+ return mdStates, nil
+}
+
+func evalStatusline(statusline string) (active, total, size int64, err error) {
+ matches := statuslineRE.FindStringSubmatch(statusline)
+ if len(matches) != 4 {
+ return 0, 0, 0, fmt.Errorf("unexpected statusline: %s", statusline)
+ }
+
+ size, err = strconv.ParseInt(matches[1], 10, 64)
+ if err != nil {
+ return 0, 0, 0, fmt.Errorf("unexpected statusline %s: %s", statusline, err)
+ }
+
+ total, err = strconv.ParseInt(matches[2], 10, 64)
+ if err != nil {
+ return 0, 0, 0, fmt.Errorf("unexpected statusline %s: %s", statusline, err)
+ }
+
+ active, err = strconv.ParseInt(matches[3], 10, 64)
+ if err != nil {
+ return 0, 0, 0, fmt.Errorf("unexpected statusline %s: %s", statusline, err)
+ }
+
+ return active, total, size, nil
+}
+
+func evalBuildline(buildline string) (syncedBlocks int64, err error) {
+ matches := buildlineRE.FindStringSubmatch(buildline)
+ if len(matches) != 2 {
+ return 0, fmt.Errorf("unexpected buildline: %s", buildline)
+ }
+
+ syncedBlocks, err = strconv.ParseInt(matches[1], 10, 64)
+ if err != nil {
+ return 0, fmt.Errorf("%s in buildline: %s", err, buildline)
+ }
+
+ return syncedBlocks, nil
+}
diff --git a/vendor/github.com/prometheus/procfs/proc.go b/vendor/github.com/prometheus/procfs/proc.go
new file mode 100644
index 0000000..0d0a6a9
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/proc.go
@@ -0,0 +1,212 @@
+package procfs
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "strconv"
+ "strings"
+)
+
+// Proc provides information about a running process.
+type Proc struct {
+ // The process ID.
+ PID int
+
+ fs FS
+}
+
+// Procs represents a list of Proc structs.
+type Procs []Proc
+
+func (p Procs) Len() int { return len(p) }
+func (p Procs) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
+func (p Procs) Less(i, j int) bool { return p[i].PID < p[j].PID }
+
+// Self returns a process for the current process read via /proc/self.
+func Self() (Proc, error) {
+ fs, err := NewFS(DefaultMountPoint)
+ if err != nil {
+ return Proc{}, err
+ }
+ return fs.Self()
+}
+
+// NewProc returns a process for the given pid under /proc.
+func NewProc(pid int) (Proc, error) {
+ fs, err := NewFS(DefaultMountPoint)
+ if err != nil {
+ return Proc{}, err
+ }
+ return fs.NewProc(pid)
+}
+
+// AllProcs returns a list of all currently available processes under /proc.
+func AllProcs() (Procs, error) {
+ fs, err := NewFS(DefaultMountPoint)
+ if err != nil {
+ return Procs{}, err
+ }
+ return fs.AllProcs()
+}
+
+// Self returns a process for the current process.
+func (fs FS) Self() (Proc, error) {
+ p, err := os.Readlink(fs.Path("self"))
+ if err != nil {
+ return Proc{}, err
+ }
+ pid, err := strconv.Atoi(strings.Replace(p, string(fs), "", -1))
+ if err != nil {
+ return Proc{}, err
+ }
+ return fs.NewProc(pid)
+}
+
+// NewProc returns a process for the given pid.
+func (fs FS) NewProc(pid int) (Proc, error) {
+ if _, err := os.Stat(fs.Path(strconv.Itoa(pid))); err != nil {
+ return Proc{}, err
+ }
+ return Proc{PID: pid, fs: fs}, nil
+}
+
+// AllProcs returns a list of all currently available processes.
+func (fs FS) AllProcs() (Procs, error) {
+ d, err := os.Open(fs.Path())
+ if err != nil {
+ return Procs{}, err
+ }
+ defer d.Close()
+
+ names, err := d.Readdirnames(-1)
+ if err != nil {
+ return Procs{}, fmt.Errorf("could not read %s: %s", d.Name(), err)
+ }
+
+ p := Procs{}
+ for _, n := range names {
+ pid, err := strconv.ParseInt(n, 10, 64)
+ if err != nil {
+ continue
+ }
+ p = append(p, Proc{PID: int(pid), fs: fs})
+ }
+
+ return p, nil
+}
+
+// CmdLine returns the command line of a process.
+func (p Proc) CmdLine() ([]string, error) {
+ f, err := os.Open(p.path("cmdline"))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ data, err := ioutil.ReadAll(f)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(data) < 1 {
+ return []string{}, nil
+ }
+
+ return strings.Split(string(data[:len(data)-1]), string(byte(0))), nil
+}
+
+// Comm returns the command name of a process.
+func (p Proc) Comm() (string, error) {
+ f, err := os.Open(p.path("comm"))
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+
+ data, err := ioutil.ReadAll(f)
+ if err != nil {
+ return "", err
+ }
+
+ return strings.TrimSpace(string(data)), nil
+}
+
+// Executable returns the absolute path of the executable command of a process.
+func (p Proc) Executable() (string, error) {
+ exe, err := os.Readlink(p.path("exe"))
+ if os.IsNotExist(err) {
+ return "", nil
+ }
+
+ return exe, err
+}
+
+// FileDescriptors returns the currently open file descriptors of a process.
+func (p Proc) FileDescriptors() ([]uintptr, error) {
+ names, err := p.fileDescriptors()
+ if err != nil {
+ return nil, err
+ }
+
+ fds := make([]uintptr, len(names))
+ for i, n := range names {
+ fd, err := strconv.ParseInt(n, 10, 32)
+ if err != nil {
+ return nil, fmt.Errorf("could not parse fd %s: %s", n, err)
+ }
+ fds[i] = uintptr(fd)
+ }
+
+ return fds, nil
+}
+
+// FileDescriptorTargets returns the targets of all file descriptors of a process.
+// If a file descriptor is not a symlink to a file (like a socket), that value will be the empty string.
+func (p Proc) FileDescriptorTargets() ([]string, error) {
+ names, err := p.fileDescriptors()
+ if err != nil {
+ return nil, err
+ }
+
+ targets := make([]string, len(names))
+
+ for i, name := range names {
+ target, err := os.Readlink(p.path("fd", name))
+ if err == nil {
+ targets[i] = target
+ }
+ }
+
+ return targets, nil
+}
+
+// FileDescriptorsLen returns the number of currently open file descriptors of
+// a process.
+func (p Proc) FileDescriptorsLen() (int, error) {
+ fds, err := p.fileDescriptors()
+ if err != nil {
+ return 0, err
+ }
+
+ return len(fds), nil
+}
+
+func (p Proc) fileDescriptors() ([]string, error) {
+ d, err := os.Open(p.path("fd"))
+ if err != nil {
+ return nil, err
+ }
+ defer d.Close()
+
+ names, err := d.Readdirnames(-1)
+ if err != nil {
+ return nil, fmt.Errorf("could not read %s: %s", d.Name(), err)
+ }
+
+ return names, nil
+}
+
+func (p Proc) path(pa ...string) string {
+ return p.fs.Path(append([]string{strconv.Itoa(p.PID)}, pa...)...)
+}
diff --git a/vendor/github.com/prometheus/procfs/proc_io.go b/vendor/github.com/prometheus/procfs/proc_io.go
new file mode 100644
index 0000000..b4e31d7
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/proc_io.go
@@ -0,0 +1,55 @@
+package procfs
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+)
+
+// ProcIO models the content of /proc/<pid>/io.
+type ProcIO struct {
+ // Chars read.
+ RChar uint64
+ // Chars written.
+ WChar uint64
+ // Read syscalls.
+ SyscR uint64
+ // Write syscalls.
+ SyscW uint64
+ // Bytes read.
+ ReadBytes uint64
+ // Bytes written.
+ WriteBytes uint64
+ // Bytes written, but taking into account truncation. See
+ // Documentation/filesystems/proc.txt in the kernel sources for
+ // detailed explanation.
+ CancelledWriteBytes int64
+}
+
+// NewIO creates a new ProcIO instance from a given Proc instance.
+func (p Proc) NewIO() (ProcIO, error) {
+ pio := ProcIO{}
+
+ f, err := os.Open(p.path("io"))
+ if err != nil {
+ return pio, err
+ }
+ defer f.Close()
+
+ data, err := ioutil.ReadAll(f)
+ if err != nil {
+ return pio, err
+ }
+
+ ioFormat := "rchar: %d\nwchar: %d\nsyscr: %d\nsyscw: %d\n" +
+ "read_bytes: %d\nwrite_bytes: %d\n" +
+ "cancelled_write_bytes: %d\n"
+
+ _, err = fmt.Sscanf(string(data), ioFormat, &pio.RChar, &pio.WChar, &pio.SyscR,
+ &pio.SyscW, &pio.ReadBytes, &pio.WriteBytes, &pio.CancelledWriteBytes)
+ if err != nil {
+ return pio, err
+ }
+
+ return pio, nil
+}
diff --git a/vendor/github.com/prometheus/procfs/proc_limits.go b/vendor/github.com/prometheus/procfs/proc_limits.go
new file mode 100644
index 0000000..2df997c
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/proc_limits.go
@@ -0,0 +1,137 @@
+package procfs
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "regexp"
+ "strconv"
+)
+
+// ProcLimits represents the soft limits for each of the process's resource
+// limits. For more information see getrlimit(2):
+// http://man7.org/linux/man-pages/man2/getrlimit.2.html.
+type ProcLimits struct {
+ // CPU time limit in seconds.
+ CPUTime int
+ // Maximum size of files that the process may create.
+ FileSize int
+ // Maximum size of the process's data segment (initialized data,
+ // uninitialized data, and heap).
+ DataSize int
+ // Maximum size of the process stack in bytes.
+ StackSize int
+ // Maximum size of a core file.
+ CoreFileSize int
+ // Limit of the process's resident set in pages.
+ ResidentSet int
+ // Maximum number of processes that can be created for the real user ID of
+ // the calling process.
+ Processes int
+ // Value one greater than the maximum file descriptor number that can be
+ // opened by this process.
+ OpenFiles int
+ // Maximum number of bytes of memory that may be locked into RAM.
+ LockedMemory int
+ // Maximum size of the process's virtual memory address space in bytes.
+ AddressSpace int
+ // Limit on the combined number of flock(2) locks and fcntl(2) leases that
+ // this process may establish.
+ FileLocks int
+ // Limit of signals that may be queued for the real user ID of the calling
+ // process.
+ PendingSignals int
+ // Limit on the number of bytes that can be allocated for POSIX message
+ // queues for the real user ID of the calling process.
+ MsqqueueSize int
+ // Limit of the nice priority set using setpriority(2) or nice(2).
+ NicePriority int
+ // Limit of the real-time priority set using sched_setscheduler(2) or
+ // sched_setparam(2).
+ RealtimePriority int
+ // Limit (in microseconds) on the amount of CPU time that a process
+ // scheduled under a real-time scheduling policy may consume without making
+ // a blocking system call.
+ RealtimeTimeout int
+}
+
+const (
+ limitsFields = 3
+ limitsUnlimited = "unlimited"
+)
+
+var (
+ limitsDelimiter = regexp.MustCompile(" +")
+)
+
+// NewLimits returns the current soft limits of the process.
+func (p Proc) NewLimits() (ProcLimits, error) {
+ f, err := os.Open(p.path("limits"))
+ if err != nil {
+ return ProcLimits{}, err
+ }
+ defer f.Close()
+
+ var (
+ l = ProcLimits{}
+ s = bufio.NewScanner(f)
+ )
+ for s.Scan() {
+ fields := limitsDelimiter.Split(s.Text(), limitsFields)
+ if len(fields) != limitsFields {
+ return ProcLimits{}, fmt.Errorf(
+ "couldn't parse %s line %s", f.Name(), s.Text())
+ }
+
+ switch fields[0] {
+ case "Max cpu time":
+ l.CPUTime, err = parseInt(fields[1])
+ case "Max file size":
+ l.FileSize, err = parseInt(fields[1])
+ case "Max data size":
+ l.DataSize, err = parseInt(fields[1])
+ case "Max stack size":
+ l.StackSize, err = parseInt(fields[1])
+ case "Max core file size":
+ l.CoreFileSize, err = parseInt(fields[1])
+ case "Max resident set":
+ l.ResidentSet, err = parseInt(fields[1])
+ case "Max processes":
+ l.Processes, err = parseInt(fields[1])
+ case "Max open files":
+ l.OpenFiles, err = parseInt(fields[1])
+ case "Max locked memory":
+ l.LockedMemory, err = parseInt(fields[1])
+ case "Max address space":
+ l.AddressSpace, err = parseInt(fields[1])
+ case "Max file locks":
+ l.FileLocks, err = parseInt(fields[1])
+ case "Max pending signals":
+ l.PendingSignals, err = parseInt(fields[1])
+ case "Max msgqueue size":
+ l.MsqqueueSize, err = parseInt(fields[1])
+ case "Max nice priority":
+ l.NicePriority, err = parseInt(fields[1])
+ case "Max realtime priority":
+ l.RealtimePriority, err = parseInt(fields[1])
+ case "Max realtime timeout":
+ l.RealtimeTimeout, err = parseInt(fields[1])
+ }
+ if err != nil {
+ return ProcLimits{}, err
+ }
+ }
+
+ return l, s.Err()
+}
+
+func parseInt(s string) (int, error) {
+ if s == limitsUnlimited {
+ return -1, nil
+ }
+ i, err := strconv.ParseInt(s, 10, 32)
+ if err != nil {
+ return 0, fmt.Errorf("couldn't parse value %s: %s", s, err)
+ }
+ return int(i), nil
+}
diff --git a/vendor/github.com/prometheus/procfs/proc_stat.go b/vendor/github.com/prometheus/procfs/proc_stat.go
new file mode 100644
index 0000000..724e271
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/proc_stat.go
@@ -0,0 +1,175 @@
+package procfs
+
+import (
+ "bytes"
+ "fmt"
+ "io/ioutil"
+ "os"
+)
+
+// Originally, this USER_HZ value was dynamically retrieved via a sysconf call
+// which required cgo. However, that caused a lot of problems regarding
+// cross-compilation. Alternatives such as running a binary to determine the
+// value, or trying to derive it in some other way were all problematic. After
+// much research it was determined that USER_HZ is actually hardcoded to 100 on
+// all Go-supported platforms as of the time of this writing. This is why we
+// decided to hardcode it here as well. It is not impossible that there could
+// be systems with exceptions, but they should be very exotic edge cases, and
+// in that case, the worst outcome will be two misreported metrics.
+//
+// See also the following discussions:
+//
+// - https://github.com/prometheus/node_exporter/issues/52
+// - https://github.com/prometheus/procfs/pull/2
+// - http://stackoverflow.com/questions/17410841/how-does-user-hz-solve-the-jiffy-scaling-issue
+const userHZ = 100
+
+// ProcStat provides status information about the process,
+// read from /proc/[pid]/stat.
+type ProcStat struct {
+ // The process ID.
+ PID int
+ // The filename of the executable.
+ Comm string
+ // The process state.
+ State string
+ // The PID of the parent of this process.
+ PPID int
+ // The process group ID of the process.
+ PGRP int
+ // The session ID of the process.
+ Session int
+ // The controlling terminal of the process.
+ TTY int
+ // The ID of the foreground process group of the controlling terminal of
+ // the process.
+ TPGID int
+ // The kernel flags word of the process.
+ Flags uint
+ // The number of minor faults the process has made which have not required
+ // loading a memory page from disk.
+ MinFlt uint
+ // The number of minor faults that the process's waited-for children have
+ // made.
+ CMinFlt uint
+ // The number of major faults the process has made which have required
+ // loading a memory page from disk.
+ MajFlt uint
+ // The number of major faults that the process's waited-for children have
+ // made.
+ CMajFlt uint
+ // Amount of time that this process has been scheduled in user mode,
+ // measured in clock ticks.
+ UTime uint
+ // Amount of time that this process has been scheduled in kernel mode,
+ // measured in clock ticks.
+ STime uint
+ // Amount of time that this process's waited-for children have been
+ // scheduled in user mode, measured in clock ticks.
+ CUTime uint
+ // Amount of time that this process's waited-for children have been
+ // scheduled in kernel mode, measured in clock ticks.
+ CSTime uint
+ // For processes running a real-time scheduling policy, this is the negated
+ // scheduling priority, minus one.
+ Priority int
+ // The nice value, a value in the range 19 (low priority) to -20 (high
+ // priority).
+ Nice int
+ // Number of threads in this process.
+ NumThreads int
+ // The time the process started after system boot, the value is expressed
+ // in clock ticks.
+ Starttime uint64
+ // Virtual memory size in bytes.
+ VSize int
+ // Resident set size in pages.
+ RSS int
+
+ fs FS
+}
+
+// NewStat returns the current status information of the process.
+func (p Proc) NewStat() (ProcStat, error) {
+ f, err := os.Open(p.path("stat"))
+ if err != nil {
+ return ProcStat{}, err
+ }
+ defer f.Close()
+
+ data, err := ioutil.ReadAll(f)
+ if err != nil {
+ return ProcStat{}, err
+ }
+
+ var (
+ ignore int
+
+ s = ProcStat{PID: p.PID, fs: p.fs}
+ l = bytes.Index(data, []byte("("))
+ r = bytes.LastIndex(data, []byte(")"))
+ )
+
+ if l < 0 || r < 0 {
+ return ProcStat{}, fmt.Errorf(
+ "unexpected format, couldn't extract comm: %s",
+ data,
+ )
+ }
+
+ s.Comm = string(data[l+1 : r])
+ _, err = fmt.Fscan(
+ bytes.NewBuffer(data[r+2:]),
+ &s.State,
+ &s.PPID,
+ &s.PGRP,
+ &s.Session,
+ &s.TTY,
+ &s.TPGID,
+ &s.Flags,
+ &s.MinFlt,
+ &s.CMinFlt,
+ &s.MajFlt,
+ &s.CMajFlt,
+ &s.UTime,
+ &s.STime,
+ &s.CUTime,
+ &s.CSTime,
+ &s.Priority,
+ &s.Nice,
+ &s.NumThreads,
+ &ignore,
+ &s.Starttime,
+ &s.VSize,
+ &s.RSS,
+ )
+ if err != nil {
+ return ProcStat{}, err
+ }
+
+ return s, nil
+}
+
+// VirtualMemory returns the virtual memory size in bytes.
+func (s ProcStat) VirtualMemory() int {
+ return s.VSize
+}
+
+// ResidentMemory returns the resident memory size in bytes.
+func (s ProcStat) ResidentMemory() int {
+ return s.RSS * os.Getpagesize()
+}
+
+// StartTime returns the unix timestamp of the process in seconds.
+func (s ProcStat) StartTime() (float64, error) {
+ stat, err := s.fs.NewStat()
+ if err != nil {
+ return 0, err
+ }
+ return float64(stat.BootTime) + (float64(s.Starttime) / userHZ), nil
+}
+
+// CPUTime returns the total CPU user and system time in seconds.
+func (s ProcStat) CPUTime() float64 {
+ return float64(s.UTime+s.STime) / userHZ
+}
diff --git a/vendor/github.com/prometheus/procfs/stat.go b/vendor/github.com/prometheus/procfs/stat.go
new file mode 100644
index 0000000..1ca217e
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/stat.go
@@ -0,0 +1,56 @@
+package procfs
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+)
+
+// Stat represents kernel/system statistics.
+type Stat struct {
+ // Boot time in seconds since the Epoch.
+ BootTime int64
+}
+
+// NewStat returns kernel/system statistics read from /proc/stat.
+func NewStat() (Stat, error) {
+ fs, err := NewFS(DefaultMountPoint)
+ if err != nil {
+ return Stat{}, err
+ }
+
+ return fs.NewStat()
+}
+
+// NewStat returns an information about current kernel/system statistics.
+func (fs FS) NewStat() (Stat, error) {
+ f, err := os.Open(fs.Path("stat"))
+ if err != nil {
+ return Stat{}, err
+ }
+ defer f.Close()
+
+ s := bufio.NewScanner(f)
+ for s.Scan() {
+ line := s.Text()
+ if !strings.HasPrefix(line, "btime") {
+ continue
+ }
+ fields := strings.Fields(line)
+ if len(fields) != 2 {
+ return Stat{}, fmt.Errorf("couldn't parse %s line %s", f.Name(), line)
+ }
+ i, err := strconv.ParseInt(fields[1], 10, 32)
+ if err != nil {
+ return Stat{}, fmt.Errorf("couldn't parse %s: %s", fields[1], err)
+ }
+ return Stat{BootTime: i}, nil
+ }
+ if err := s.Err(); err != nil {
+ return Stat{}, fmt.Errorf("couldn't parse %s: %s", f.Name(), err)
+ }
+
+ return Stat{}, fmt.Errorf("couldn't parse %s, missing btime", f.Name())
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/LICENSE b/vendor/github.com/rcrowley/go-metrics/LICENSE
new file mode 100644
index 0000000..363fa9e
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/LICENSE
@@ -0,0 +1,29 @@
+Copyright 2012 Richard Crowley. 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 RICHARD CROWLEY ``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 RICHARD CROWLEY 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.
+
+The views and conclusions contained in the software and documentation
+are those of the authors and should not be interpreted as representing
+official policies, either expressed or implied, of Richard Crowley.
diff --git a/vendor/github.com/rcrowley/go-metrics/README.md b/vendor/github.com/rcrowley/go-metrics/README.md
new file mode 100644
index 0000000..66ba9ca
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/README.md
@@ -0,0 +1,139 @@
+go-metrics
+==========
+
+![travis build status](https://travis-ci.org/rcrowley/go-metrics.svg?branch=master)
+
+Go port of Coda Hale's Metrics library: <https://github.com/dropwizard/metrics>.
+
+Documentation: <http://godoc.org/github.com/rcrowley/go-metrics>.
+
+Usage
+-----
+
+Create and update metrics:
+
+```go
+c := metrics.NewCounter()
+metrics.Register("foo", c)
+c.Inc(47)
+
+g := metrics.NewGauge()
+metrics.Register("bar", g)
+g.Update(47)
+
+s := metrics.NewExpDecaySample(1028, 0.015) // or metrics.NewUniformSample(1028)
+h := metrics.NewHistogram(s)
+metrics.Register("baz", h)
+h.Update(47)
+
+m := metrics.NewMeter()
+metrics.Register("quux", m)
+m.Mark(47)
+
+t := metrics.NewTimer()
+metrics.Register("bang", t)
+t.Time(func() {})
+t.Update(47)
+```
+
+Periodically log every metric in human-readable form to standard error:
+
+```go
+go metrics.Log(metrics.DefaultRegistry, 5 * time.Second, log.New(os.Stderr, "metrics: ", log.Lmicroseconds))
+```
+
+Periodically log every metric in slightly-more-parseable form to syslog:
+
+```go
+w, _ := syslog.Dial("unixgram", "/dev/log", syslog.LOG_INFO, "metrics")
+go metrics.Syslog(metrics.DefaultRegistry, 60e9, w)
+```
+
+Periodically emit every metric to Graphite using the [Graphite client](https://github.com/cyberdelia/go-metrics-graphite):
+
+```go
+
+import "github.com/cyberdelia/go-metrics-graphite"
+
+addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:2003")
+go graphite.Graphite(metrics.DefaultRegistry, 10e9, "metrics", addr)
+```
+
+Periodically emit every metric into InfluxDB:
+
+**NOTE:** this has been pulled out of the library due to constant fluctuations
+in the InfluxDB API. In fact, all client libraries are on their way out. see
+issues [#121](https://github.com/rcrowley/go-metrics/issues/121) and
+[#124](https://github.com/rcrowley/go-metrics/issues/124) for progress and details.
+
+```go
+import "github.com/rcrowley/go-metrics/influxdb"
+
+go influxdb.Influxdb(metrics.DefaultRegistry, 10e9, &influxdb.Config{
+ Host: "127.0.0.1:8086",
+ Database: "metrics",
+ Username: "test",
+ Password: "test",
+})
+```
+
+Periodically upload every metric to Librato using the [Librato client](https://github.com/mihasya/go-metrics-librato):
+
+**Note**: the client included with this repository under the `librato` package
+has been deprecated and moved to the repository linked above.
+
+```go
+import "github.com/mihasya/go-metrics-librato"
+
+go librato.Librato(metrics.DefaultRegistry,
+ 10e9, // interval
+ "example@example.com", // account owner email address
+ "token", // Librato API token
+ "hostname", // source
+ []float64{0.95}, // percentiles to send
+ time.Millisecond, // time unit
+)
+```
+
+Periodically emit every metric to StatHat:
+
+```go
+import "github.com/rcrowley/go-metrics/stathat"
+
+go stathat.Stathat(metrics.DefaultRegistry, 10e9, "example@example.com")
+```
+
+Maintain all metrics along with expvars at `/debug/metrics`:
+
+This uses the same mechanism as [the official expvar](http://golang.org/pkg/expvar/)
+but exposed under `/debug/metrics`, which shows a json representation of all your usual expvars
+as well as all your go-metrics.
+
+
+```go
+import "github.com/rcrowley/go-metrics/exp"
+
+exp.Exp(metrics.DefaultRegistry)
+```
+
+Installation
+------------
+
+```sh
+go get github.com/rcrowley/go-metrics
+```
+
+StatHat support additionally requires their Go client:
+
+```sh
+go get github.com/stathat/go
+```
+
+Publishing Metrics
+------------------
+
+Clients are available for the following destinations:
+
+* Librato - [https://github.com/mihasya/go-metrics-librato](https://github.com/mihasya/go-metrics-librato)
+* Graphite - [https://github.com/cyberdelia/go-metrics-graphite](https://github.com/cyberdelia/go-metrics-graphite)
+* InfluxDB - [https://github.com/vrischmann/go-metrics-influxdb](https://github.com/vrischmann/go-metrics-influxdb)
diff --git a/vendor/github.com/rcrowley/go-metrics/counter.go b/vendor/github.com/rcrowley/go-metrics/counter.go
new file mode 100644
index 0000000..bb7b039
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/counter.go
@@ -0,0 +1,112 @@
+package metrics
+
+import "sync/atomic"
+
+// Counters hold an int64 value that can be incremented and decremented.
+type Counter interface {
+ Clear()
+ Count() int64
+ Dec(int64)
+ Inc(int64)
+ Snapshot() Counter
+}
+
+// GetOrRegisterCounter returns an existing Counter or constructs and registers
+// a new StandardCounter.
+func GetOrRegisterCounter(name string, r Registry) Counter {
+ if nil == r {
+ r = DefaultRegistry
+ }
+ return r.GetOrRegister(name, NewCounter).(Counter)
+}
+
+// NewCounter constructs a new StandardCounter.
+func NewCounter() Counter {
+ if UseNilMetrics {
+ return NilCounter{}
+ }
+ return &StandardCounter{0}
+}
+
+// NewRegisteredCounter constructs and registers a new StandardCounter.
+func NewRegisteredCounter(name string, r Registry) Counter {
+ c := NewCounter()
+ if nil == r {
+ r = DefaultRegistry
+ }
+ r.Register(name, c)
+ return c
+}
+
+// CounterSnapshot is a read-only copy of another Counter.
+type CounterSnapshot int64
+
+// Clear panics.
+func (CounterSnapshot) Clear() {
+ panic("Clear called on a CounterSnapshot")
+}
+
+// Count returns the count at the time the snapshot was taken.
+func (c CounterSnapshot) Count() int64 { return int64(c) }
+
+// Dec panics.
+func (CounterSnapshot) Dec(int64) {
+ panic("Dec called on a CounterSnapshot")
+}
+
+// Inc panics.
+func (CounterSnapshot) Inc(int64) {
+ panic("Inc called on a CounterSnapshot")
+}
+
+// Snapshot returns the snapshot.
+func (c CounterSnapshot) Snapshot() Counter { return c }
+
+// NilCounter is a no-op Counter.
+type NilCounter struct{}
+
+// Clear is a no-op.
+func (NilCounter) Clear() {}
+
+// Count is a no-op.
+func (NilCounter) Count() int64 { return 0 }
+
+// Dec is a no-op.
+func (NilCounter) Dec(i int64) {}
+
+// Inc is a no-op.
+func (NilCounter) Inc(i int64) {}
+
+// Snapshot is a no-op.
+func (NilCounter) Snapshot() Counter { return NilCounter{} }
+
+// StandardCounter is the standard implementation of a Counter and uses the
+// sync/atomic package to manage a single int64 value.
+type StandardCounter struct {
+ count int64
+}
+
+// Clear sets the counter to zero.
+func (c *StandardCounter) Clear() {
+ atomic.StoreInt64(&c.count, 0)
+}
+
+// Count returns the current count.
+func (c *StandardCounter) Count() int64 {
+ return atomic.LoadInt64(&c.count)
+}
+
+// Dec decrements the counter by the given amount.
+func (c *StandardCounter) Dec(i int64) {
+ atomic.AddInt64(&c.count, -i)
+}
+
+// Inc increments the counter by the given amount.
+func (c *StandardCounter) Inc(i int64) {
+ atomic.AddInt64(&c.count, i)
+}
+
+// Snapshot returns a read-only copy of the counter.
+func (c *StandardCounter) Snapshot() Counter {
+ return CounterSnapshot(c.Count())
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/debug.go b/vendor/github.com/rcrowley/go-metrics/debug.go
new file mode 100644
index 0000000..043ccef
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/debug.go
@@ -0,0 +1,76 @@
+package metrics
+
+import (
+ "runtime/debug"
+ "time"
+)
+
+var (
+ debugMetrics struct {
+ GCStats struct {
+ LastGC Gauge
+ NumGC Gauge
+ Pause Histogram
+ //PauseQuantiles Histogram
+ PauseTotal Gauge
+ }
+ ReadGCStats Timer
+ }
+ gcStats debug.GCStats
+)
+
+// Capture new values for the Go garbage collector statistics exported in
+// debug.GCStats. This is designed to be called as a goroutine.
+func CaptureDebugGCStats(r Registry, d time.Duration) {
+ for _ = range time.Tick(d) {
+ CaptureDebugGCStatsOnce(r)
+ }
+}
+
+// Capture new values for the Go garbage collector statistics exported in
+// debug.GCStats. This is designed to be called in a background goroutine.
+// Giving a registry which has not been given to RegisterDebugGCStats will
+// panic.
+//
+// Be careful (but much less so) with this because debug.ReadGCStats calls
+// the C function runtime·lock(runtime·mheap) which, while not a stop-the-world
+// operation, isn't something you want to be doing all the time.
+func CaptureDebugGCStatsOnce(r Registry) {
+ lastGC := gcStats.LastGC
+ t := time.Now()
+ debug.ReadGCStats(&gcStats)
+ debugMetrics.ReadGCStats.UpdateSince(t)
+
+ debugMetrics.GCStats.LastGC.Update(int64(gcStats.LastGC.UnixNano()))
+ debugMetrics.GCStats.NumGC.Update(int64(gcStats.NumGC))
+ if lastGC != gcStats.LastGC && 0 < len(gcStats.Pause) {
+ debugMetrics.GCStats.Pause.Update(int64(gcStats.Pause[0]))
+ }
+ //debugMetrics.GCStats.PauseQuantiles.Update(gcStats.PauseQuantiles)
+ debugMetrics.GCStats.PauseTotal.Update(int64(gcStats.PauseTotal))
+}
+
+// Register metrics for the Go garbage collector statistics exported in
+// debug.GCStats. The metrics are named by their fully-qualified Go symbols,
+// i.e. debug.GCStats.PauseTotal.
+func RegisterDebugGCStats(r Registry) {
+ debugMetrics.GCStats.LastGC = NewGauge()
+ debugMetrics.GCStats.NumGC = NewGauge()
+ debugMetrics.GCStats.Pause = NewHistogram(NewExpDecaySample(1028, 0.015))
+ //debugMetrics.GCStats.PauseQuantiles = NewHistogram(NewExpDecaySample(1028, 0.015))
+ debugMetrics.GCStats.PauseTotal = NewGauge()
+ debugMetrics.ReadGCStats = NewTimer()
+
+ r.Register("debug.GCStats.LastGC", debugMetrics.GCStats.LastGC)
+ r.Register("debug.GCStats.NumGC", debugMetrics.GCStats.NumGC)
+ r.Register("debug.GCStats.Pause", debugMetrics.GCStats.Pause)
+ //r.Register("debug.GCStats.PauseQuantiles", debugMetrics.GCStats.PauseQuantiles)
+ r.Register("debug.GCStats.PauseTotal", debugMetrics.GCStats.PauseTotal)
+ r.Register("debug.ReadGCStats", debugMetrics.ReadGCStats)
+}
+
+// Allocate an initial slice for gcStats.Pause to avoid allocations during
+// normal operation.
+func init() {
+ gcStats.Pause = make([]time.Duration, 11)
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/ewma.go b/vendor/github.com/rcrowley/go-metrics/ewma.go
new file mode 100644
index 0000000..694a1d0
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/ewma.go
@@ -0,0 +1,118 @@
+package metrics
+
+import (
+ "math"
+ "sync"
+ "sync/atomic"
+)
+
+// EWMAs continuously calculate an exponentially-weighted moving average
+// based on an outside source of clock ticks.
+type EWMA interface {
+ Rate() float64
+ Snapshot() EWMA
+ Tick()
+ Update(int64)
+}
+
+// NewEWMA constructs a new EWMA with the given alpha.
+func NewEWMA(alpha float64) EWMA {
+ if UseNilMetrics {
+ return NilEWMA{}
+ }
+ return &StandardEWMA{alpha: alpha}
+}
+
+// NewEWMA1 constructs a new EWMA for a one-minute moving average.
+func NewEWMA1() EWMA {
+ return NewEWMA(1 - math.Exp(-5.0/60.0/1))
+}
+
+// NewEWMA5 constructs a new EWMA for a five-minute moving average.
+func NewEWMA5() EWMA {
+ return NewEWMA(1 - math.Exp(-5.0/60.0/5))
+}
+
+// NewEWMA15 constructs a new EWMA for a fifteen-minute moving average.
+func NewEWMA15() EWMA {
+ return NewEWMA(1 - math.Exp(-5.0/60.0/15))
+}
+
+// EWMASnapshot is a read-only copy of another EWMA.
+type EWMASnapshot float64
+
+// Rate returns the rate of events per second at the time the snapshot was
+// taken.
+func (a EWMASnapshot) Rate() float64 { return float64(a) }
+
+// Snapshot returns the snapshot.
+func (a EWMASnapshot) Snapshot() EWMA { return a }
+
+// Tick panics.
+func (EWMASnapshot) Tick() {
+ panic("Tick called on an EWMASnapshot")
+}
+
+// Update panics.
+func (EWMASnapshot) Update(int64) {
+ panic("Update called on an EWMASnapshot")
+}
+
+// NilEWMA is a no-op EWMA.
+type NilEWMA struct{}
+
+// Rate is a no-op.
+func (NilEWMA) Rate() float64 { return 0.0 }
+
+// Snapshot is a no-op.
+func (NilEWMA) Snapshot() EWMA { return NilEWMA{} }
+
+// Tick is a no-op.
+func (NilEWMA) Tick() {}
+
+// Update is a no-op.
+func (NilEWMA) Update(n int64) {}
+
+// StandardEWMA is the standard implementation of an EWMA and tracks the number
+// of uncounted events and processes them on each tick. It uses the
+// sync/atomic package to manage uncounted events.
+type StandardEWMA struct {
+ uncounted int64 // /!\ this should be the first member to ensure 64-bit alignment
+ alpha float64
+ rate float64
+ init bool
+ mutex sync.Mutex
+}
+
+// Rate returns the moving average rate of events per second.
+func (a *StandardEWMA) Rate() float64 {
+ a.mutex.Lock()
+ defer a.mutex.Unlock()
+ return a.rate * float64(1e9)
+}
+
+// Snapshot returns a read-only copy of the EWMA.
+func (a *StandardEWMA) Snapshot() EWMA {
+ return EWMASnapshot(a.Rate())
+}
+
+// Tick ticks the clock to update the moving average. It assumes it is called
+// every five seconds.
+func (a *StandardEWMA) Tick() {
+ count := atomic.LoadInt64(&a.uncounted)
+ atomic.AddInt64(&a.uncounted, -count)
+ instantRate := float64(count) / float64(5e9)
+ a.mutex.Lock()
+ defer a.mutex.Unlock()
+ if a.init {
+ a.rate += a.alpha * (instantRate - a.rate)
+ } else {
+ a.init = true
+ a.rate = instantRate
+ }
+}
+
+// Update adds n uncounted events.
+func (a *StandardEWMA) Update(n int64) {
+ atomic.AddInt64(&a.uncounted, n)
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/gauge.go b/vendor/github.com/rcrowley/go-metrics/gauge.go
new file mode 100644
index 0000000..807638a
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/gauge.go
@@ -0,0 +1,84 @@
+package metrics
+
+import "sync/atomic"
+
+// Gauges hold an int64 value that can be set arbitrarily.
+type Gauge interface {
+ Snapshot() Gauge
+ Update(int64)
+ Value() int64
+}
+
+// GetOrRegisterGauge returns an existing Gauge or constructs and registers a
+// new StandardGauge.
+func GetOrRegisterGauge(name string, r Registry) Gauge {
+ if nil == r {
+ r = DefaultRegistry
+ }
+ return r.GetOrRegister(name, NewGauge).(Gauge)
+}
+
+// NewGauge constructs a new StandardGauge.
+func NewGauge() Gauge {
+ if UseNilMetrics {
+ return NilGauge{}
+ }
+ return &StandardGauge{0}
+}
+
+// NewRegisteredGauge constructs and registers a new StandardGauge.
+func NewRegisteredGauge(name string, r Registry) Gauge {
+ c := NewGauge()
+ if nil == r {
+ r = DefaultRegistry
+ }
+ r.Register(name, c)
+ return c
+}
+
+// GaugeSnapshot is a read-only copy of another Gauge.
+type GaugeSnapshot int64
+
+// Snapshot returns the snapshot.
+func (g GaugeSnapshot) Snapshot() Gauge { return g }
+
+// Update panics.
+func (GaugeSnapshot) Update(int64) {
+ panic("Update called on a GaugeSnapshot")
+}
+
+// Value returns the value at the time the snapshot was taken.
+func (g GaugeSnapshot) Value() int64 { return int64(g) }
+
+// NilGauge is a no-op Gauge.
+type NilGauge struct{}
+
+// Snapshot is a no-op.
+func (NilGauge) Snapshot() Gauge { return NilGauge{} }
+
+// Update is a no-op.
+func (NilGauge) Update(v int64) {}
+
+// Value is a no-op.
+func (NilGauge) Value() int64 { return 0 }
+
+// StandardGauge is the standard implementation of a Gauge and uses the
+// sync/atomic package to manage a single int64 value.
+type StandardGauge struct {
+ value int64
+}
+
+// Snapshot returns a read-only copy of the gauge.
+func (g *StandardGauge) Snapshot() Gauge {
+ return GaugeSnapshot(g.Value())
+}
+
+// Update updates the gauge's value.
+func (g *StandardGauge) Update(v int64) {
+ atomic.StoreInt64(&g.value, v)
+}
+
+// Value returns the gauge's current value.
+func (g *StandardGauge) Value() int64 {
+ return atomic.LoadInt64(&g.value)
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/gauge_float64.go b/vendor/github.com/rcrowley/go-metrics/gauge_float64.go
new file mode 100644
index 0000000..47c3566
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/gauge_float64.go
@@ -0,0 +1,91 @@
+package metrics
+
+import "sync"
+
+// GaugeFloat64s hold a float64 value that can be set arbitrarily.
+type GaugeFloat64 interface {
+ Snapshot() GaugeFloat64
+ Update(float64)
+ Value() float64
+}
+
+// GetOrRegisterGaugeFloat64 returns an existing GaugeFloat64 or constructs and registers a
+// new StandardGaugeFloat64.
+func GetOrRegisterGaugeFloat64(name string, r Registry) GaugeFloat64 {
+ if nil == r {
+ r = DefaultRegistry
+ }
+ return r.GetOrRegister(name, NewGaugeFloat64()).(GaugeFloat64)
+}
+
+// NewGaugeFloat64 constructs a new StandardGaugeFloat64.
+func NewGaugeFloat64() GaugeFloat64 {
+ if UseNilMetrics {
+ return NilGaugeFloat64{}
+ }
+ return &StandardGaugeFloat64{
+ value: 0.0,
+ }
+}
+
+// NewRegisteredGaugeFloat64 constructs and registers a new StandardGaugeFloat64.
+func NewRegisteredGaugeFloat64(name string, r Registry) GaugeFloat64 {
+ c := NewGaugeFloat64()
+ if nil == r {
+ r = DefaultRegistry
+ }
+ r.Register(name, c)
+ return c
+}
+
+// GaugeFloat64Snapshot is a read-only copy of another GaugeFloat64.
+type GaugeFloat64Snapshot float64
+
+// Snapshot returns the snapshot.
+func (g GaugeFloat64Snapshot) Snapshot() GaugeFloat64 { return g }
+
+// Update panics.
+func (GaugeFloat64Snapshot) Update(float64) {
+ panic("Update called on a GaugeFloat64Snapshot")
+}
+
+// Value returns the value at the time the snapshot was taken.
+func (g GaugeFloat64Snapshot) Value() float64 { return float64(g) }
+
+// NilGauge is a no-op Gauge.
+type NilGaugeFloat64 struct{}
+
+// Snapshot is a no-op.
+func (NilGaugeFloat64) Snapshot() GaugeFloat64 { return NilGaugeFloat64{} }
+
+// Update is a no-op.
+func (NilGaugeFloat64) Update(v float64) {}
+
+// Value is a no-op.
+func (NilGaugeFloat64) Value() float64 { return 0.0 }
+
+// StandardGaugeFloat64 is the standard implementation of a GaugeFloat64 and uses
+// sync.Mutex to manage a single float64 value.
+type StandardGaugeFloat64 struct {
+ mutex sync.Mutex
+ value float64
+}
+
+// Snapshot returns a read-only copy of the gauge.
+func (g *StandardGaugeFloat64) Snapshot() GaugeFloat64 {
+ return GaugeFloat64Snapshot(g.Value())
+}
+
+// Update updates the gauge's value.
+func (g *StandardGaugeFloat64) Update(v float64) {
+ g.mutex.Lock()
+ defer g.mutex.Unlock()
+ g.value = v
+}
+
+// Value returns the gauge's current value.
+func (g *StandardGaugeFloat64) Value() float64 {
+ g.mutex.Lock()
+ defer g.mutex.Unlock()
+ return g.value
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/graphite.go b/vendor/github.com/rcrowley/go-metrics/graphite.go
new file mode 100644
index 0000000..abd0a7d
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/graphite.go
@@ -0,0 +1,113 @@
+package metrics
+
+import (
+ "bufio"
+ "fmt"
+ "log"
+ "net"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// GraphiteConfig provides a container with configuration parameters for
+// the Graphite exporter
+type GraphiteConfig struct {
+ Addr *net.TCPAddr // Network address to connect to
+ Registry Registry // Registry to be exported
+ FlushInterval time.Duration // Flush interval
+ DurationUnit time.Duration // Time conversion unit for durations
+ Prefix string // Prefix to be prepended to metric names
+ Percentiles []float64 // Percentiles to export from timers and histograms
+}
+
+// Graphite is a blocking exporter function which reports metrics in r
+// to a graphite server located at addr, flushing them every d duration
+// and prepending metric names with prefix.
+func Graphite(r Registry, d time.Duration, prefix string, addr *net.TCPAddr) {
+ GraphiteWithConfig(GraphiteConfig{
+ Addr: addr,
+ Registry: r,
+ FlushInterval: d,
+ DurationUnit: time.Nanosecond,
+ Prefix: prefix,
+ Percentiles: []float64{0.5, 0.75, 0.95, 0.99, 0.999},
+ })
+}
+
+// GraphiteWithConfig is a blocking exporter function just like Graphite,
+// but it takes a GraphiteConfig instead.
+func GraphiteWithConfig(c GraphiteConfig) {
+ log.Printf("WARNING: This go-metrics client has been DEPRECATED! It has been moved to https://github.com/cyberdelia/go-metrics-graphite and will be removed from rcrowley/go-metrics on August 12th 2015")
+ for _ = range time.Tick(c.FlushInterval) {
+ if err := graphite(&c); nil != err {
+ log.Println(err)
+ }
+ }
+}
+
+// GraphiteOnce performs a single submission to Graphite, returning a
+// non-nil error on failed connections. This can be used in a loop
+// similar to GraphiteWithConfig for custom error handling.
+func GraphiteOnce(c GraphiteConfig) error {
+ log.Printf("WARNING: This go-metrics client has been DEPRECATED! It has been moved to https://github.com/cyberdelia/go-metrics-graphite and will be removed from rcrowley/go-metrics on August 12th 2015")
+ return graphite(&c)
+}
+
+func graphite(c *GraphiteConfig) error {
+ now := time.Now().Unix()
+ du := float64(c.DurationUnit)
+ conn, err := net.DialTCP("tcp", nil, c.Addr)
+ if nil != err {
+ return err
+ }
+ defer conn.Close()
+ w := bufio.NewWriter(conn)
+ c.Registry.Each(func(name string, i interface{}) {
+ switch metric := i.(type) {
+ case Counter:
+ fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, metric.Count(), now)
+ case Gauge:
+ fmt.Fprintf(w, "%s.%s.value %d %d\n", c.Prefix, name, metric.Value(), now)
+ case GaugeFloat64:
+ fmt.Fprintf(w, "%s.%s.value %f %d\n", c.Prefix, name, metric.Value(), now)
+ case Histogram:
+ h := metric.Snapshot()
+ ps := h.Percentiles(c.Percentiles)
+ fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, h.Count(), now)
+ fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, h.Min(), now)
+ fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, h.Max(), now)
+ fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, h.Mean(), now)
+ fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, h.StdDev(), now)
+ for psIdx, psKey := range c.Percentiles {
+ key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1)
+ fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx], now)
+ }
+ case Meter:
+ m := metric.Snapshot()
+ fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, m.Count(), now)
+ fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, m.Rate1(), now)
+ fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, m.Rate5(), now)
+ fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, m.Rate15(), now)
+ fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, m.RateMean(), now)
+ case Timer:
+ t := metric.Snapshot()
+ ps := t.Percentiles(c.Percentiles)
+ fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, t.Count(), now)
+ fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, t.Min()/int64(du), now)
+ fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, t.Max()/int64(du), now)
+ fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, t.Mean()/du, now)
+ fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, t.StdDev()/du, now)
+ for psIdx, psKey := range c.Percentiles {
+ key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1)
+ fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx], now)
+ }
+ fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, t.Rate1(), now)
+ fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, t.Rate5(), now)
+ fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, t.Rate15(), now)
+ fmt.Fprintf(w, "%s.%s.mean-rate %.2f %d\n", c.Prefix, name, t.RateMean(), now)
+ }
+ w.Flush()
+ })
+ return nil
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/healthcheck.go b/vendor/github.com/rcrowley/go-metrics/healthcheck.go
new file mode 100644
index 0000000..445131c
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/healthcheck.go
@@ -0,0 +1,61 @@
+package metrics
+
+// Healthchecks hold an error value describing an arbitrary up/down status.
+type Healthcheck interface {
+ Check()
+ Error() error
+ Healthy()
+ Unhealthy(error)
+}
+
+// NewHealthcheck constructs a new Healthcheck which will use the given
+// function to update its status.
+func NewHealthcheck(f func(Healthcheck)) Healthcheck {
+ if UseNilMetrics {
+ return NilHealthcheck{}
+ }
+ return &StandardHealthcheck{nil, f}
+}
+
+// NilHealthcheck is a no-op.
+type NilHealthcheck struct{}
+
+// Check is a no-op.
+func (NilHealthcheck) Check() {}
+
+// Error is a no-op.
+func (NilHealthcheck) Error() error { return nil }
+
+// Healthy is a no-op.
+func (NilHealthcheck) Healthy() {}
+
+// Unhealthy is a no-op.
+func (NilHealthcheck) Unhealthy(error) {}
+
+// StandardHealthcheck is the standard implementation of a Healthcheck and
+// stores the status and a function to call to update the status.
+type StandardHealthcheck struct {
+ err error
+ f func(Healthcheck)
+}
+
+// Check runs the healthcheck function to update the healthcheck's status.
+func (h *StandardHealthcheck) Check() {
+ h.f(h)
+}
+
+// Error returns the healthcheck's status, which will be nil if it is healthy.
+func (h *StandardHealthcheck) Error() error {
+ return h.err
+}
+
+// Healthy marks the healthcheck as healthy.
+func (h *StandardHealthcheck) Healthy() {
+ h.err = nil
+}
+
+// Unhealthy marks the healthcheck as unhealthy. The error is stored and
+// may be retrieved by the Error method.
+func (h *StandardHealthcheck) Unhealthy(err error) {
+ h.err = err
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/histogram.go b/vendor/github.com/rcrowley/go-metrics/histogram.go
new file mode 100644
index 0000000..dbc837f
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/histogram.go
@@ -0,0 +1,202 @@
+package metrics
+
+// Histograms calculate distribution statistics from a series of int64 values.
+type Histogram interface {
+ Clear()
+ Count() int64
+ Max() int64
+ Mean() float64
+ Min() int64
+ Percentile(float64) float64
+ Percentiles([]float64) []float64
+ Sample() Sample
+ Snapshot() Histogram
+ StdDev() float64
+ Sum() int64
+ Update(int64)
+ Variance() float64
+}
+
+// GetOrRegisterHistogram returns an existing Histogram or constructs and
+// registers a new StandardHistogram.
+func GetOrRegisterHistogram(name string, r Registry, s Sample) Histogram {
+ if nil == r {
+ r = DefaultRegistry
+ }
+ return r.GetOrRegister(name, func() Histogram { return NewHistogram(s) }).(Histogram)
+}
+
+// NewHistogram constructs a new StandardHistogram from a Sample.
+func NewHistogram(s Sample) Histogram {
+ if UseNilMetrics {
+ return NilHistogram{}
+ }
+ return &StandardHistogram{sample: s}
+}
+
+// NewRegisteredHistogram constructs and registers a new StandardHistogram from
+// a Sample.
+func NewRegisteredHistogram(name string, r Registry, s Sample) Histogram {
+ c := NewHistogram(s)
+ if nil == r {
+ r = DefaultRegistry
+ }
+ r.Register(name, c)
+ return c
+}
+
+// HistogramSnapshot is a read-only copy of another Histogram.
+type HistogramSnapshot struct {
+ sample *SampleSnapshot
+}
+
+// Clear panics.
+func (*HistogramSnapshot) Clear() {
+ panic("Clear called on a HistogramSnapshot")
+}
+
+// Count returns the number of samples recorded at the time the snapshot was
+// taken.
+func (h *HistogramSnapshot) Count() int64 { return h.sample.Count() }
+
+// Max returns the maximum value in the sample at the time the snapshot was
+// taken.
+func (h *HistogramSnapshot) Max() int64 { return h.sample.Max() }
+
+// Mean returns the mean of the values in the sample at the time the snapshot
+// was taken.
+func (h *HistogramSnapshot) Mean() float64 { return h.sample.Mean() }
+
+// Min returns the minimum value in the sample at the time the snapshot was
+// taken.
+func (h *HistogramSnapshot) Min() int64 { return h.sample.Min() }
+
+// Percentile returns an arbitrary percentile of values in the sample at the
+// time the snapshot was taken.
+func (h *HistogramSnapshot) Percentile(p float64) float64 {
+ return h.sample.Percentile(p)
+}
+
+// Percentiles returns a slice of arbitrary percentiles of values in the sample
+// at the time the snapshot was taken.
+func (h *HistogramSnapshot) Percentiles(ps []float64) []float64 {
+ return h.sample.Percentiles(ps)
+}
+
+// Sample returns the Sample underlying the histogram.
+func (h *HistogramSnapshot) Sample() Sample { return h.sample }
+
+// Snapshot returns the snapshot.
+func (h *HistogramSnapshot) Snapshot() Histogram { return h }
+
+// StdDev returns the standard deviation of the values in the sample at the
+// time the snapshot was taken.
+func (h *HistogramSnapshot) StdDev() float64 { return h.sample.StdDev() }
+
+// Sum returns the sum in the sample at the time the snapshot was taken.
+func (h *HistogramSnapshot) Sum() int64 { return h.sample.Sum() }
+
+// Update panics.
+func (*HistogramSnapshot) Update(int64) {
+ panic("Update called on a HistogramSnapshot")
+}
+
+// Variance returns the variance of inputs at the time the snapshot was taken.
+func (h *HistogramSnapshot) Variance() float64 { return h.sample.Variance() }
+
+// NilHistogram is a no-op Histogram.
+type NilHistogram struct{}
+
+// Clear is a no-op.
+func (NilHistogram) Clear() {}
+
+// Count is a no-op.
+func (NilHistogram) Count() int64 { return 0 }
+
+// Max is a no-op.
+func (NilHistogram) Max() int64 { return 0 }
+
+// Mean is a no-op.
+func (NilHistogram) Mean() float64 { return 0.0 }
+
+// Min is a no-op.
+func (NilHistogram) Min() int64 { return 0 }
+
+// Percentile is a no-op.
+func (NilHistogram) Percentile(p float64) float64 { return 0.0 }
+
+// Percentiles is a no-op.
+func (NilHistogram) Percentiles(ps []float64) []float64 {
+ return make([]float64, len(ps))
+}
+
+// Sample is a no-op.
+func (NilHistogram) Sample() Sample { return NilSample{} }
+
+// Snapshot is a no-op.
+func (NilHistogram) Snapshot() Histogram { return NilHistogram{} }
+
+// StdDev is a no-op.
+func (NilHistogram) StdDev() float64 { return 0.0 }
+
+// Sum is a no-op.
+func (NilHistogram) Sum() int64 { return 0 }
+
+// Update is a no-op.
+func (NilHistogram) Update(v int64) {}
+
+// Variance is a no-op.
+func (NilHistogram) Variance() float64 { return 0.0 }
+
+// StandardHistogram is the standard implementation of a Histogram and uses a
+// Sample to bound its memory use.
+type StandardHistogram struct {
+ sample Sample
+}
+
+// Clear clears the histogram and its sample.
+func (h *StandardHistogram) Clear() { h.sample.Clear() }
+
+// Count returns the number of samples recorded since the histogram was last
+// cleared.
+func (h *StandardHistogram) Count() int64 { return h.sample.Count() }
+
+// Max returns the maximum value in the sample.
+func (h *StandardHistogram) Max() int64 { return h.sample.Max() }
+
+// Mean returns the mean of the values in the sample.
+func (h *StandardHistogram) Mean() float64 { return h.sample.Mean() }
+
+// Min returns the minimum value in the sample.
+func (h *StandardHistogram) Min() int64 { return h.sample.Min() }
+
+// Percentile returns an arbitrary percentile of the values in the sample.
+func (h *StandardHistogram) Percentile(p float64) float64 {
+ return h.sample.Percentile(p)
+}
+
+// Percentiles returns a slice of arbitrary percentiles of the values in the
+// sample.
+func (h *StandardHistogram) Percentiles(ps []float64) []float64 {
+ return h.sample.Percentiles(ps)
+}
+
+// Sample returns the Sample underlying the histogram.
+func (h *StandardHistogram) Sample() Sample { return h.sample }
+
+// Snapshot returns a read-only copy of the histogram.
+func (h *StandardHistogram) Snapshot() Histogram {
+ return &HistogramSnapshot{sample: h.sample.Snapshot().(*SampleSnapshot)}
+}
+
+// StdDev returns the standard deviation of the values in the sample.
+func (h *StandardHistogram) StdDev() float64 { return h.sample.StdDev() }
+
+// Sum returns the sum in the sample.
+func (h *StandardHistogram) Sum() int64 { return h.sample.Sum() }
+
+// Update samples a new value.
+func (h *StandardHistogram) Update(v int64) { h.sample.Update(v) }
+
+// Variance returns the variance of the values in the sample.
+func (h *StandardHistogram) Variance() float64 { return h.sample.Variance() }
diff --git a/vendor/github.com/rcrowley/go-metrics/json.go b/vendor/github.com/rcrowley/go-metrics/json.go
new file mode 100644
index 0000000..2676aee
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/json.go
@@ -0,0 +1,83 @@
+package metrics
+
+import (
+ "encoding/json"
+ "io"
+ "time"
+)
+
+// MarshalJSON returns a byte slice containing a JSON representation of all
+// the metrics in the Registry.
+func (r *StandardRegistry) MarshalJSON() ([]byte, error) {
+ data := make(map[string]map[string]interface{})
+ r.Each(func(name string, i interface{}) {
+ values := make(map[string]interface{})
+ switch metric := i.(type) {
+ case Counter:
+ values["count"] = metric.Count()
+ case Gauge:
+ values["value"] = metric.Value()
+ case GaugeFloat64:
+ values["value"] = metric.Value()
+ case Healthcheck:
+ values["error"] = nil
+ metric.Check()
+ if err := metric.Error(); nil != err {
+ values["error"] = metric.Error().Error()
+ }
+ case Histogram:
+ h := metric.Snapshot()
+ ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
+ values["count"] = h.Count()
+ values["min"] = h.Min()
+ values["max"] = h.Max()
+ values["mean"] = h.Mean()
+ values["stddev"] = h.StdDev()
+ values["median"] = ps[0]
+ values["75%"] = ps[1]
+ values["95%"] = ps[2]
+ values["99%"] = ps[3]
+ values["99.9%"] = ps[4]
+ case Meter:
+ m := metric.Snapshot()
+ values["count"] = m.Count()
+ values["1m.rate"] = m.Rate1()
+ values["5m.rate"] = m.Rate5()
+ values["15m.rate"] = m.Rate15()
+ values["mean.rate"] = m.RateMean()
+ case Timer:
+ t := metric.Snapshot()
+ ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
+ values["count"] = t.Count()
+ values["min"] = t.Min()
+ values["max"] = t.Max()
+ values["mean"] = t.Mean()
+ values["stddev"] = t.StdDev()
+ values["median"] = ps[0]
+ values["75%"] = ps[1]
+ values["95%"] = ps[2]
+ values["99%"] = ps[3]
+ values["99.9%"] = ps[4]
+ values["1m.rate"] = t.Rate1()
+ values["5m.rate"] = t.Rate5()
+ values["15m.rate"] = t.Rate15()
+ values["mean.rate"] = t.RateMean()
+ }
+ data[name] = values
+ })
+ return json.Marshal(data)
+}
+
+// WriteJSON writes metrics from the given registry periodically to the
+// specified io.Writer as JSON.
+func WriteJSON(r Registry, d time.Duration, w io.Writer) {
+ for _ = range time.Tick(d) {
+ WriteJSONOnce(r, w)
+ }
+}
+
+// WriteJSONOnce writes metrics from the given registry to the specified
+// io.Writer as JSON.
+func WriteJSONOnce(r Registry, w io.Writer) {
+ json.NewEncoder(w).Encode(r)
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/log.go b/vendor/github.com/rcrowley/go-metrics/log.go
new file mode 100644
index 0000000..f074eb0
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/log.go
@@ -0,0 +1,77 @@
+package metrics
+
+import (
+ "log"
+ "time"
+)
+
+func Log(r Registry, freq time.Duration, l *log.Logger) {
+ LogScaled(r, freq, time.Nanosecond, l)
+}
+
+// Output each metric in the given registry periodically using the given
+// logger. Print timings in `scale` units (eg time.Millisecond) rather than nanos.
+func LogScaled(r Registry, freq time.Duration, scale time.Duration, l *log.Logger) {
+ du := float64(scale)
+ duSuffix := scale.String()[1:]
+
+ for _ = range time.Tick(freq) {
+ r.Each(func(name string, i interface{}) {
+ switch metric := i.(type) {
+ case Counter:
+ l.Printf("counter %s\n", name)
+ l.Printf(" count: %9d\n", metric.Count())
+ case Gauge:
+ l.Printf("gauge %s\n", name)
+ l.Printf(" value: %9d\n", metric.Value())
+ case GaugeFloat64:
+ l.Printf("gauge %s\n", name)
+ l.Printf(" value: %f\n", metric.Value())
+ case Healthcheck:
+ metric.Check()
+ l.Printf("healthcheck %s\n", name)
+ l.Printf(" error: %v\n", metric.Error())
+ case Histogram:
+ h := metric.Snapshot()
+ ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
+ l.Printf("histogram %s\n", name)
+ l.Printf(" count: %9d\n", h.Count())
+ l.Printf(" min: %9d\n", h.Min())
+ l.Printf(" max: %9d\n", h.Max())
+ l.Printf(" mean: %12.2f\n", h.Mean())
+ l.Printf(" stddev: %12.2f\n", h.StdDev())
+ l.Printf(" median: %12.2f\n", ps[0])
+ l.Printf(" 75%%: %12.2f\n", ps[1])
+ l.Printf(" 95%%: %12.2f\n", ps[2])
+ l.Printf(" 99%%: %12.2f\n", ps[3])
+ l.Printf(" 99.9%%: %12.2f\n", ps[4])
+ case Meter:
+ m := metric.Snapshot()
+ l.Printf("meter %s\n", name)
+ l.Printf(" count: %9d\n", m.Count())
+ l.Printf(" 1-min rate: %12.2f\n", m.Rate1())
+ l.Printf(" 5-min rate: %12.2f\n", m.Rate5())
+ l.Printf(" 15-min rate: %12.2f\n", m.Rate15())
+ l.Printf(" mean rate: %12.2f\n", m.RateMean())
+ case Timer:
+ t := metric.Snapshot()
+ ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
+ l.Printf("timer %s\n", name)
+ l.Printf(" count: %9d\n", t.Count())
+ l.Printf(" min: %12.2f%s\n", float64(t.Min())/du, duSuffix)
+ l.Printf(" max: %12.2f%s\n", float64(t.Max())/du, duSuffix)
+ l.Printf(" mean: %12.2f%s\n", t.Mean()/du, duSuffix)
+ l.Printf(" stddev: %12.2f%s\n", t.StdDev()/du, duSuffix)
+ l.Printf(" median: %12.2f%s\n", ps[0]/du, duSuffix)
+ l.Printf(" 75%%: %12.2f%s\n", ps[1]/du, duSuffix)
+ l.Printf(" 95%%: %12.2f%s\n", ps[2]/du, duSuffix)
+ l.Printf(" 99%%: %12.2f%s\n", ps[3]/du, duSuffix)
+ l.Printf(" 99.9%%: %12.2f%s\n", ps[4]/du, duSuffix)
+ l.Printf(" 1-min rate: %12.2f\n", t.Rate1())
+ l.Printf(" 5-min rate: %12.2f\n", t.Rate5())
+ l.Printf(" 15-min rate: %12.2f\n", t.Rate15())
+ l.Printf(" mean rate: %12.2f\n", t.RateMean())
+ }
+ })
+ }
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/meter.go b/vendor/github.com/rcrowley/go-metrics/meter.go
new file mode 100644
index 0000000..0389ab0
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/meter.go
@@ -0,0 +1,233 @@
+package metrics
+
+import (
+ "sync"
+ "time"
+)
+
+// Meters count events to produce exponentially-weighted moving average rates
+// at one-, five-, and fifteen-minutes and a mean rate.
+type Meter interface {
+ Count() int64
+ Mark(int64)
+ Rate1() float64
+ Rate5() float64
+ Rate15() float64
+ RateMean() float64
+ Snapshot() Meter
+}
+
+// GetOrRegisterMeter returns an existing Meter or constructs and registers a
+// new StandardMeter.
+func GetOrRegisterMeter(name string, r Registry) Meter {
+ if nil == r {
+ r = DefaultRegistry
+ }
+ return r.GetOrRegister(name, NewMeter).(Meter)
+}
+
+// NewMeter constructs a new StandardMeter and launches a goroutine.
+func NewMeter() Meter {
+ if UseNilMetrics {
+ return NilMeter{}
+ }
+ m := newStandardMeter()
+ arbiter.Lock()
+ defer arbiter.Unlock()
+ arbiter.meters = append(arbiter.meters, m)
+ if !arbiter.started {
+ arbiter.started = true
+ go arbiter.tick()
+ }
+ return m
+}
+
+// NewMeter constructs and registers a new StandardMeter and launches a
+// goroutine.
+func NewRegisteredMeter(name string, r Registry) Meter {
+ c := NewMeter()
+ if nil == r {
+ r = DefaultRegistry
+ }
+ r.Register(name, c)
+ return c
+}
+
+// MeterSnapshot is a read-only copy of another Meter.
+type MeterSnapshot struct {
+ count int64
+ rate1, rate5, rate15, rateMean float64
+}
+
+// Count returns the count of events at the time the snapshot was taken.
+func (m *MeterSnapshot) Count() int64 { return m.count }
+
+// Mark panics.
+func (*MeterSnapshot) Mark(n int64) {
+ panic("Mark called on a MeterSnapshot")
+}
+
+// Rate1 returns the one-minute moving average rate of events per second at the
+// time the snapshot was taken.
+func (m *MeterSnapshot) Rate1() float64 { return m.rate1 }
+
+// Rate5 returns the five-minute moving average rate of events per second at
+// the time the snapshot was taken.
+func (m *MeterSnapshot) Rate5() float64 { return m.rate5 }
+
+// Rate15 returns the fifteen-minute moving average rate of events per second
+// at the time the snapshot was taken.
+func (m *MeterSnapshot) Rate15() float64 { return m.rate15 }
+
+// RateMean returns the meter's mean rate of events per second at the time the
+// snapshot was taken.
+func (m *MeterSnapshot) RateMean() float64 { return m.rateMean }
+
+// Snapshot returns the snapshot.
+func (m *MeterSnapshot) Snapshot() Meter { return m }
+
+// NilMeter is a no-op Meter.
+type NilMeter struct{}
+
+// Count is a no-op.
+func (NilMeter) Count() int64 { return 0 }
+
+// Mark is a no-op.
+func (NilMeter) Mark(n int64) {}
+
+// Rate1 is a no-op.
+func (NilMeter) Rate1() float64 { return 0.0 }
+
+// Rate5 is a no-op.
+func (NilMeter) Rate5() float64 { return 0.0 }
+
+// Rate15is a no-op.
+func (NilMeter) Rate15() float64 { return 0.0 }
+
+// RateMean is a no-op.
+func (NilMeter) RateMean() float64 { return 0.0 }
+
+// Snapshot is a no-op.
+func (NilMeter) Snapshot() Meter { return NilMeter{} }
+
+// StandardMeter is the standard implementation of a Meter.
+type StandardMeter struct {
+ lock sync.RWMutex
+ snapshot *MeterSnapshot
+ a1, a5, a15 EWMA
+ startTime time.Time
+}
+
+func newStandardMeter() *StandardMeter {
+ return &StandardMeter{
+ snapshot: &MeterSnapshot{},
+ a1: NewEWMA1(),
+ a5: NewEWMA5(),
+ a15: NewEWMA15(),
+ startTime: time.Now(),
+ }
+}
+
+// Count returns the number of events recorded.
+func (m *StandardMeter) Count() int64 {
+ m.lock.RLock()
+ count := m.snapshot.count
+ m.lock.RUnlock()
+ return count
+}
+
+// Mark records the occurance of n events.
+func (m *StandardMeter) Mark(n int64) {
+ m.lock.Lock()
+ defer m.lock.Unlock()
+ m.snapshot.count += n
+ m.a1.Update(n)
+ m.a5.Update(n)
+ m.a15.Update(n)
+ m.updateSnapshot()
+}
+
+// Rate1 returns the one-minute moving average rate of events per second.
+func (m *StandardMeter) Rate1() float64 {
+ m.lock.RLock()
+ rate1 := m.snapshot.rate1
+ m.lock.RUnlock()
+ return rate1
+}
+
+// Rate5 returns the five-minute moving average rate of events per second.
+func (m *StandardMeter) Rate5() float64 {
+ m.lock.RLock()
+ rate5 := m.snapshot.rate5
+ m.lock.RUnlock()
+ return rate5
+}
+
+// Rate15 returns the fifteen-minute moving average rate of events per second.
+func (m *StandardMeter) Rate15() float64 {
+ m.lock.RLock()
+ rate15 := m.snapshot.rate15
+ m.lock.RUnlock()
+ return rate15
+}
+
+// RateMean returns the meter's mean rate of events per second.
+func (m *StandardMeter) RateMean() float64 {
+ m.lock.RLock()
+ rateMean := m.snapshot.rateMean
+ m.lock.RUnlock()
+ return rateMean
+}
+
+// Snapshot returns a read-only copy of the meter.
+func (m *StandardMeter) Snapshot() Meter {
+ m.lock.RLock()
+ snapshot := *m.snapshot
+ m.lock.RUnlock()
+ return &snapshot
+}
+
+func (m *StandardMeter) updateSnapshot() {
+ // should run with write lock held on m.lock
+ snapshot := m.snapshot
+ snapshot.rate1 = m.a1.Rate()
+ snapshot.rate5 = m.a5.Rate()
+ snapshot.rate15 = m.a15.Rate()
+ snapshot.rateMean = float64(snapshot.count) / time.Since(m.startTime).Seconds()
+}
+
+func (m *StandardMeter) tick() {
+ m.lock.Lock()
+ defer m.lock.Unlock()
+ m.a1.Tick()
+ m.a5.Tick()
+ m.a15.Tick()
+ m.updateSnapshot()
+}
+
+type meterArbiter struct {
+ sync.RWMutex
+ started bool
+ meters []*StandardMeter
+ ticker *time.Ticker
+}
+
+var arbiter = meterArbiter{ticker: time.NewTicker(5e9)}
+
+// Ticks meters on the scheduled interval
+func (ma *meterArbiter) tick() {
+ for {
+ select {
+ case <-ma.ticker.C:
+ ma.tickMeters()
+ }
+ }
+}
+
+func (ma *meterArbiter) tickMeters() {
+ ma.RLock()
+ defer ma.RUnlock()
+ for _, meter := range ma.meters {
+ meter.tick()
+ }
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/metrics.go b/vendor/github.com/rcrowley/go-metrics/metrics.go
new file mode 100644
index 0000000..b97a49e
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/metrics.go
@@ -0,0 +1,13 @@
+// Go port of Coda Hale's Metrics library
+//
+// <https://github.com/rcrowley/go-metrics>
+//
+// Coda Hale's original work: <https://github.com/codahale/metrics>
+package metrics
+
+// UseNilMetrics is checked by the constructor functions for all of the
+// standard metrics. If it is true, the metric returned is a stub.
+//
+// This global kill-switch helps quantify the observer effect and makes
+// for less cluttered pprof profiles.
+var UseNilMetrics bool = false
diff --git a/vendor/github.com/rcrowley/go-metrics/opentsdb.go b/vendor/github.com/rcrowley/go-metrics/opentsdb.go
new file mode 100644
index 0000000..266b6c9
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/opentsdb.go
@@ -0,0 +1,119 @@
+package metrics
+
+import (
+ "bufio"
+ "fmt"
+ "log"
+ "net"
+ "os"
+ "strings"
+ "time"
+)
+
+var shortHostName string = ""
+
+// OpenTSDBConfig provides a container with configuration parameters for
+// the OpenTSDB exporter
+type OpenTSDBConfig struct {
+ Addr *net.TCPAddr // Network address to connect to
+ Registry Registry // Registry to be exported
+ FlushInterval time.Duration // Flush interval
+ DurationUnit time.Duration // Time conversion unit for durations
+ Prefix string // Prefix to be prepended to metric names
+}
+
+// OpenTSDB is a blocking exporter function which reports metrics in r
+// to a TSDB server located at addr, flushing them every d duration
+// and prepending metric names with prefix.
+func OpenTSDB(r Registry, d time.Duration, prefix string, addr *net.TCPAddr) {
+ OpenTSDBWithConfig(OpenTSDBConfig{
+ Addr: addr,
+ Registry: r,
+ FlushInterval: d,
+ DurationUnit: time.Nanosecond,
+ Prefix: prefix,
+ })
+}
+
+// OpenTSDBWithConfig is a blocking exporter function just like OpenTSDB,
+// but it takes a OpenTSDBConfig instead.
+func OpenTSDBWithConfig(c OpenTSDBConfig) {
+ for _ = range time.Tick(c.FlushInterval) {
+ if err := openTSDB(&c); nil != err {
+ log.Println(err)
+ }
+ }
+}
+
+func getShortHostname() string {
+ if shortHostName == "" {
+ host, _ := os.Hostname()
+ if index := strings.Index(host, "."); index > 0 {
+ shortHostName = host[:index]
+ } else {
+ shortHostName = host
+ }
+ }
+ return shortHostName
+}
+
+func openTSDB(c *OpenTSDBConfig) error {
+ shortHostname := getShortHostname()
+ now := time.Now().Unix()
+ du := float64(c.DurationUnit)
+ conn, err := net.DialTCP("tcp", nil, c.Addr)
+ if nil != err {
+ return err
+ }
+ defer conn.Close()
+ w := bufio.NewWriter(conn)
+ c.Registry.Each(func(name string, i interface{}) {
+ switch metric := i.(type) {
+ case Counter:
+ fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, metric.Count(), shortHostname)
+ case Gauge:
+ fmt.Fprintf(w, "put %s.%s.value %d %d host=%s\n", c.Prefix, name, now, metric.Value(), shortHostname)
+ case GaugeFloat64:
+ fmt.Fprintf(w, "put %s.%s.value %d %f host=%s\n", c.Prefix, name, now, metric.Value(), shortHostname)
+ case Histogram:
+ h := metric.Snapshot()
+ ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
+ fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, h.Count(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.min %d %d host=%s\n", c.Prefix, name, now, h.Min(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.max %d %d host=%s\n", c.Prefix, name, now, h.Max(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.mean %d %.2f host=%s\n", c.Prefix, name, now, h.Mean(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.std-dev %d %.2f host=%s\n", c.Prefix, name, now, h.StdDev(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.50-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[0], shortHostname)
+ fmt.Fprintf(w, "put %s.%s.75-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[1], shortHostname)
+ fmt.Fprintf(w, "put %s.%s.95-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[2], shortHostname)
+ fmt.Fprintf(w, "put %s.%s.99-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[3], shortHostname)
+ fmt.Fprintf(w, "put %s.%s.999-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[4], shortHostname)
+ case Meter:
+ m := metric.Snapshot()
+ fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, m.Count(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.one-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate1(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.five-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate5(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.fifteen-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate15(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.mean %d %.2f host=%s\n", c.Prefix, name, now, m.RateMean(), shortHostname)
+ case Timer:
+ t := metric.Snapshot()
+ ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
+ fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, t.Count(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.min %d %d host=%s\n", c.Prefix, name, now, t.Min()/int64(du), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.max %d %d host=%s\n", c.Prefix, name, now, t.Max()/int64(du), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.mean %d %.2f host=%s\n", c.Prefix, name, now, t.Mean()/du, shortHostname)
+ fmt.Fprintf(w, "put %s.%s.std-dev %d %.2f host=%s\n", c.Prefix, name, now, t.StdDev()/du, shortHostname)
+ fmt.Fprintf(w, "put %s.%s.50-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[0]/du, shortHostname)
+ fmt.Fprintf(w, "put %s.%s.75-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[1]/du, shortHostname)
+ fmt.Fprintf(w, "put %s.%s.95-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[2]/du, shortHostname)
+ fmt.Fprintf(w, "put %s.%s.99-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[3]/du, shortHostname)
+ fmt.Fprintf(w, "put %s.%s.999-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[4]/du, shortHostname)
+ fmt.Fprintf(w, "put %s.%s.one-minute %d %.2f host=%s\n", c.Prefix, name, now, t.Rate1(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.five-minute %d %.2f host=%s\n", c.Prefix, name, now, t.Rate5(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.fifteen-minute %d %.2f host=%s\n", c.Prefix, name, now, t.Rate15(), shortHostname)
+ fmt.Fprintf(w, "put %s.%s.mean-rate %d %.2f host=%s\n", c.Prefix, name, now, t.RateMean(), shortHostname)
+ }
+ w.Flush()
+ })
+ return nil
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/registry.go b/vendor/github.com/rcrowley/go-metrics/registry.go
new file mode 100644
index 0000000..e1f68a5
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/registry.go
@@ -0,0 +1,247 @@
+package metrics
+
+import (
+ "fmt"
+ "reflect"
+ "sync"
+)
+
+// DuplicateMetric is the error returned by Registry.Register when a metric
+// already exists. If you mean to Register that metric you must first
+// Unregister the existing metric.
+type DuplicateMetric string
+
+func (err DuplicateMetric) Error() string {
+ return fmt.Sprintf("duplicate metric: %s", string(err))
+}
+
+// A Registry holds references to a set of metrics by name and can iterate
+// over them, calling callback functions provided by the user.
+//
+// This is an interface so as to encourage other structs to implement
+// the Registry API as appropriate.
+type Registry interface {
+
+ // Call the given function for each registered metric.
+ Each(func(string, interface{}))
+
+ // Get the metric by the given name or nil if none is registered.
+ Get(string) interface{}
+
+ // Gets an existing metric or registers the given one.
+ // The interface can be the metric to register if not found in registry,
+ // or a function returning the metric for lazy instantiation.
+ GetOrRegister(string, interface{}) interface{}
+
+ // Register the given metric under the given name.
+ Register(string, interface{}) error
+
+ // Run all registered healthchecks.
+ RunHealthchecks()
+
+ // Unregister the metric with the given name.
+ Unregister(string)
+
+ // Unregister all metrics. (Mostly for testing.)
+ UnregisterAll()
+}
+
+// The standard implementation of a Registry is a mutex-protected map
+// of names to metrics.
+type StandardRegistry struct {
+ metrics map[string]interface{}
+ mutex sync.Mutex
+}
+
+// Create a new registry.
+func NewRegistry() Registry {
+ return &StandardRegistry{metrics: make(map[string]interface{})}
+}
+
+// Call the given function for each registered metric.
+func (r *StandardRegistry) Each(f func(string, interface{})) {
+ for name, i := range r.registered() {
+ f(name, i)
+ }
+}
+
+// Get the metric by the given name or nil if none is registered.
+func (r *StandardRegistry) Get(name string) interface{} {
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ return r.metrics[name]
+}
+
+// Gets an existing metric or creates and registers a new one. Threadsafe
+// alternative to calling Get and Register on failure.
+// The interface can be the metric to register if not found in registry,
+// or a function returning the metric for lazy instantiation.
+func (r *StandardRegistry) GetOrRegister(name string, i interface{}) interface{} {
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ if metric, ok := r.metrics[name]; ok {
+ return metric
+ }
+ if v := reflect.ValueOf(i); v.Kind() == reflect.Func {
+ i = v.Call(nil)[0].Interface()
+ }
+ r.register(name, i)
+ return i
+}
+
+// Register the given metric under the given name. Returns a DuplicateMetric
+// if a metric by the given name is already registered.
+func (r *StandardRegistry) Register(name string, i interface{}) error {
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ return r.register(name, i)
+}
+
+// Run all registered healthchecks.
+func (r *StandardRegistry) RunHealthchecks() {
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ for _, i := range r.metrics {
+ if h, ok := i.(Healthcheck); ok {
+ h.Check()
+ }
+ }
+}
+
+// Unregister the metric with the given name.
+func (r *StandardRegistry) Unregister(name string) {
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ delete(r.metrics, name)
+}
+
+// Unregister all metrics. (Mostly for testing.)
+func (r *StandardRegistry) UnregisterAll() {
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ for name, _ := range r.metrics {
+ delete(r.metrics, name)
+ }
+}
+
+func (r *StandardRegistry) register(name string, i interface{}) error {
+ if _, ok := r.metrics[name]; ok {
+ return DuplicateMetric(name)
+ }
+ switch i.(type) {
+ case Counter, Gauge, GaugeFloat64, Healthcheck, Histogram, Meter, Timer:
+ r.metrics[name] = i
+ }
+ return nil
+}
+
+func (r *StandardRegistry) registered() map[string]interface{} {
+ r.mutex.Lock()
+ defer r.mutex.Unlock()
+ metrics := make(map[string]interface{}, len(r.metrics))
+ for name, i := range r.metrics {
+ metrics[name] = i
+ }
+ return metrics
+}
+
+type PrefixedRegistry struct {
+ underlying Registry
+ prefix string
+}
+
+func NewPrefixedRegistry(prefix string) Registry {
+ return &PrefixedRegistry{
+ underlying: NewRegistry(),
+ prefix: prefix,
+ }
+}
+
+func NewPrefixedChildRegistry(parent Registry, prefix string) Registry {
+ return &PrefixedRegistry{
+ underlying: parent,
+ prefix: prefix,
+ }
+}
+
+// Call the given function for each registered metric.
+func (r *PrefixedRegistry) Each(fn func(string, interface{})) {
+ r.underlying.Each(fn)
+}
+
+// Get the metric by the given name or nil if none is registered.
+func (r *PrefixedRegistry) Get(name string) interface{} {
+ return r.underlying.Get(name)
+}
+
+// Gets an existing metric or registers the given one.
+// The interface can be the metric to register if not found in registry,
+// or a function returning the metric for lazy instantiation.
+func (r *PrefixedRegistry) GetOrRegister(name string, metric interface{}) interface{} {
+ realName := r.prefix + name
+ return r.underlying.GetOrRegister(realName, metric)
+}
+
+// Register the given metric under the given name. The name will be prefixed.
+func (r *PrefixedRegistry) Register(name string, metric interface{}) error {
+ realName := r.prefix + name
+ return r.underlying.Register(realName, metric)
+}
+
+// Run all registered healthchecks.
+func (r *PrefixedRegistry) RunHealthchecks() {
+ r.underlying.RunHealthchecks()
+}
+
+// Unregister the metric with the given name. The name will be prefixed.
+func (r *PrefixedRegistry) Unregister(name string) {
+ realName := r.prefix + name
+ r.underlying.Unregister(realName)
+}
+
+// Unregister all metrics. (Mostly for testing.)
+func (r *PrefixedRegistry) UnregisterAll() {
+ r.underlying.UnregisterAll()
+}
+
+var DefaultRegistry Registry = NewRegistry()
+
+// Call the given function for each registered metric.
+func Each(f func(string, interface{})) {
+ DefaultRegistry.Each(f)
+}
+
+// Get the metric by the given name or nil if none is registered.
+func Get(name string) interface{} {
+ return DefaultRegistry.Get(name)
+}
+
+// Gets an existing metric or creates and registers a new one. Threadsafe
+// alternative to calling Get and Register on failure.
+func GetOrRegister(name string, i interface{}) interface{} {
+ return DefaultRegistry.GetOrRegister(name, i)
+}
+
+// Register the given metric under the given name. Returns a DuplicateMetric
+// if a metric by the given name is already registered.
+func Register(name string, i interface{}) error {
+ return DefaultRegistry.Register(name, i)
+}
+
+// Register the given metric under the given name. Panics if a metric by the
+// given name is already registered.
+func MustRegister(name string, i interface{}) {
+ if err := Register(name, i); err != nil {
+ panic(err)
+ }
+}
+
+// Run all registered healthchecks.
+func RunHealthchecks() {
+ DefaultRegistry.RunHealthchecks()
+}
+
+// Unregister the metric with the given name.
+func Unregister(name string) {
+ DefaultRegistry.Unregister(name)
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/runtime.go b/vendor/github.com/rcrowley/go-metrics/runtime.go
new file mode 100644
index 0000000..11c6b78
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/runtime.go
@@ -0,0 +1,212 @@
+package metrics
+
+import (
+ "runtime"
+ "runtime/pprof"
+ "time"
+)
+
+var (
+ memStats runtime.MemStats
+ runtimeMetrics struct {
+ MemStats struct {
+ Alloc Gauge
+ BuckHashSys Gauge
+ DebugGC Gauge
+ EnableGC Gauge
+ Frees Gauge
+ HeapAlloc Gauge
+ HeapIdle Gauge
+ HeapInuse Gauge
+ HeapObjects Gauge
+ HeapReleased Gauge
+ HeapSys Gauge
+ LastGC Gauge
+ Lookups Gauge
+ Mallocs Gauge
+ MCacheInuse Gauge
+ MCacheSys Gauge
+ MSpanInuse Gauge
+ MSpanSys Gauge
+ NextGC Gauge
+ NumGC Gauge
+ GCCPUFraction GaugeFloat64
+ PauseNs Histogram
+ PauseTotalNs Gauge
+ StackInuse Gauge
+ StackSys Gauge
+ Sys Gauge
+ TotalAlloc Gauge
+ }
+ NumCgoCall Gauge
+ NumGoroutine Gauge
+ NumThread Gauge
+ ReadMemStats Timer
+ }
+ frees uint64
+ lookups uint64
+ mallocs uint64
+ numGC uint32
+ numCgoCalls int64
+
+ threadCreateProfile = pprof.Lookup("threadcreate")
+)
+
+// Capture new values for the Go runtime statistics exported in
+// runtime.MemStats. This is designed to be called as a goroutine.
+func CaptureRuntimeMemStats(r Registry, d time.Duration) {
+ for _ = range time.Tick(d) {
+ CaptureRuntimeMemStatsOnce(r)
+ }
+}
+
+// Capture new values for the Go runtime statistics exported in
+// runtime.MemStats. This is designed to be called in a background
+// goroutine. Giving a registry which has not been given to
+// RegisterRuntimeMemStats will panic.
+//
+// Be very careful with this because runtime.ReadMemStats calls the C
+// functions runtime·semacquire(&runtime·worldsema) and runtime·stoptheworld()
+// and that last one does what it says on the tin.
+func CaptureRuntimeMemStatsOnce(r Registry) {
+ t := time.Now()
+ runtime.ReadMemStats(&memStats) // This takes 50-200us.
+ runtimeMetrics.ReadMemStats.UpdateSince(t)
+
+ runtimeMetrics.MemStats.Alloc.Update(int64(memStats.Alloc))
+ runtimeMetrics.MemStats.BuckHashSys.Update(int64(memStats.BuckHashSys))
+ if memStats.DebugGC {
+ runtimeMetrics.MemStats.DebugGC.Update(1)
+ } else {
+ runtimeMetrics.MemStats.DebugGC.Update(0)
+ }
+ if memStats.EnableGC {
+ runtimeMetrics.MemStats.EnableGC.Update(1)
+ } else {
+ runtimeMetrics.MemStats.EnableGC.Update(0)
+ }
+
+ runtimeMetrics.MemStats.Frees.Update(int64(memStats.Frees - frees))
+ runtimeMetrics.MemStats.HeapAlloc.Update(int64(memStats.HeapAlloc))
+ runtimeMetrics.MemStats.HeapIdle.Update(int64(memStats.HeapIdle))
+ runtimeMetrics.MemStats.HeapInuse.Update(int64(memStats.HeapInuse))
+ runtimeMetrics.MemStats.HeapObjects.Update(int64(memStats.HeapObjects))
+ runtimeMetrics.MemStats.HeapReleased.Update(int64(memStats.HeapReleased))
+ runtimeMetrics.MemStats.HeapSys.Update(int64(memStats.HeapSys))
+ runtimeMetrics.MemStats.LastGC.Update(int64(memStats.LastGC))
+ runtimeMetrics.MemStats.Lookups.Update(int64(memStats.Lookups - lookups))
+ runtimeMetrics.MemStats.Mallocs.Update(int64(memStats.Mallocs - mallocs))
+ runtimeMetrics.MemStats.MCacheInuse.Update(int64(memStats.MCacheInuse))
+ runtimeMetrics.MemStats.MCacheSys.Update(int64(memStats.MCacheSys))
+ runtimeMetrics.MemStats.MSpanInuse.Update(int64(memStats.MSpanInuse))
+ runtimeMetrics.MemStats.MSpanSys.Update(int64(memStats.MSpanSys))
+ runtimeMetrics.MemStats.NextGC.Update(int64(memStats.NextGC))
+ runtimeMetrics.MemStats.NumGC.Update(int64(memStats.NumGC - numGC))
+ runtimeMetrics.MemStats.GCCPUFraction.Update(gcCPUFraction(&memStats))
+
+ // <https://code.google.com/p/go/source/browse/src/pkg/runtime/mgc0.c>
+ i := numGC % uint32(len(memStats.PauseNs))
+ ii := memStats.NumGC % uint32(len(memStats.PauseNs))
+ if memStats.NumGC-numGC >= uint32(len(memStats.PauseNs)) {
+ for i = 0; i < uint32(len(memStats.PauseNs)); i++ {
+ runtimeMetrics.MemStats.PauseNs.Update(int64(memStats.PauseNs[i]))
+ }
+ } else {
+ if i > ii {
+ for ; i < uint32(len(memStats.PauseNs)); i++ {
+ runtimeMetrics.MemStats.PauseNs.Update(int64(memStats.PauseNs[i]))
+ }
+ i = 0
+ }
+ for ; i < ii; i++ {
+ runtimeMetrics.MemStats.PauseNs.Update(int64(memStats.PauseNs[i]))
+ }
+ }
+ frees = memStats.Frees
+ lookups = memStats.Lookups
+ mallocs = memStats.Mallocs
+ numGC = memStats.NumGC
+
+ runtimeMetrics.MemStats.PauseTotalNs.Update(int64(memStats.PauseTotalNs))
+ runtimeMetrics.MemStats.StackInuse.Update(int64(memStats.StackInuse))
+ runtimeMetrics.MemStats.StackSys.Update(int64(memStats.StackSys))
+ runtimeMetrics.MemStats.Sys.Update(int64(memStats.Sys))
+ runtimeMetrics.MemStats.TotalAlloc.Update(int64(memStats.TotalAlloc))
+
+ currentNumCgoCalls := numCgoCall()
+ runtimeMetrics.NumCgoCall.Update(currentNumCgoCalls - numCgoCalls)
+ numCgoCalls = currentNumCgoCalls
+
+ runtimeMetrics.NumGoroutine.Update(int64(runtime.NumGoroutine()))
+
+ runtimeMetrics.NumThread.Update(int64(threadCreateProfile.Count()))
+}
+
+// Register runtimeMetrics for the Go runtime statistics exported in runtime and
+// specifically runtime.MemStats. The runtimeMetrics are named by their
+// fully-qualified Go symbols, i.e. runtime.MemStats.Alloc.
+func RegisterRuntimeMemStats(r Registry) {
+ runtimeMetrics.MemStats.Alloc = NewGauge()
+ runtimeMetrics.MemStats.BuckHashSys = NewGauge()
+ runtimeMetrics.MemStats.DebugGC = NewGauge()
+ runtimeMetrics.MemStats.EnableGC = NewGauge()
+ runtimeMetrics.MemStats.Frees = NewGauge()
+ runtimeMetrics.MemStats.HeapAlloc = NewGauge()
+ runtimeMetrics.MemStats.HeapIdle = NewGauge()
+ runtimeMetrics.MemStats.HeapInuse = NewGauge()
+ runtimeMetrics.MemStats.HeapObjects = NewGauge()
+ runtimeMetrics.MemStats.HeapReleased = NewGauge()
+ runtimeMetrics.MemStats.HeapSys = NewGauge()
+ runtimeMetrics.MemStats.LastGC = NewGauge()
+ runtimeMetrics.MemStats.Lookups = NewGauge()
+ runtimeMetrics.MemStats.Mallocs = NewGauge()
+ runtimeMetrics.MemStats.MCacheInuse = NewGauge()
+ runtimeMetrics.MemStats.MCacheSys = NewGauge()
+ runtimeMetrics.MemStats.MSpanInuse = NewGauge()
+ runtimeMetrics.MemStats.MSpanSys = NewGauge()
+ runtimeMetrics.MemStats.NextGC = NewGauge()
+ runtimeMetrics.MemStats.NumGC = NewGauge()
+ runtimeMetrics.MemStats.GCCPUFraction = NewGaugeFloat64()
+ runtimeMetrics.MemStats.PauseNs = NewHistogram(NewExpDecaySample(1028, 0.015))
+ runtimeMetrics.MemStats.PauseTotalNs = NewGauge()
+ runtimeMetrics.MemStats.StackInuse = NewGauge()
+ runtimeMetrics.MemStats.StackSys = NewGauge()
+ runtimeMetrics.MemStats.Sys = NewGauge()
+ runtimeMetrics.MemStats.TotalAlloc = NewGauge()
+ runtimeMetrics.NumCgoCall = NewGauge()
+ runtimeMetrics.NumGoroutine = NewGauge()
+ runtimeMetrics.NumThread = NewGauge()
+ runtimeMetrics.ReadMemStats = NewTimer()
+
+ r.Register("runtime.MemStats.Alloc", runtimeMetrics.MemStats.Alloc)
+ r.Register("runtime.MemStats.BuckHashSys", runtimeMetrics.MemStats.BuckHashSys)
+ r.Register("runtime.MemStats.DebugGC", runtimeMetrics.MemStats.DebugGC)
+ r.Register("runtime.MemStats.EnableGC", runtimeMetrics.MemStats.EnableGC)
+ r.Register("runtime.MemStats.Frees", runtimeMetrics.MemStats.Frees)
+ r.Register("runtime.MemStats.HeapAlloc", runtimeMetrics.MemStats.HeapAlloc)
+ r.Register("runtime.MemStats.HeapIdle", runtimeMetrics.MemStats.HeapIdle)
+ r.Register("runtime.MemStats.HeapInuse", runtimeMetrics.MemStats.HeapInuse)
+ r.Register("runtime.MemStats.HeapObjects", runtimeMetrics.MemStats.HeapObjects)
+ r.Register("runtime.MemStats.HeapReleased", runtimeMetrics.MemStats.HeapReleased)
+ r.Register("runtime.MemStats.HeapSys", runtimeMetrics.MemStats.HeapSys)
+ r.Register("runtime.MemStats.LastGC", runtimeMetrics.MemStats.LastGC)
+ r.Register("runtime.MemStats.Lookups", runtimeMetrics.MemStats.Lookups)
+ r.Register("runtime.MemStats.Mallocs", runtimeMetrics.MemStats.Mallocs)
+ r.Register("runtime.MemStats.MCacheInuse", runtimeMetrics.MemStats.MCacheInuse)
+ r.Register("runtime.MemStats.MCacheSys", runtimeMetrics.MemStats.MCacheSys)
+ r.Register("runtime.MemStats.MSpanInuse", runtimeMetrics.MemStats.MSpanInuse)
+ r.Register("runtime.MemStats.MSpanSys", runtimeMetrics.MemStats.MSpanSys)
+ r.Register("runtime.MemStats.NextGC", runtimeMetrics.MemStats.NextGC)
+ r.Register("runtime.MemStats.NumGC", runtimeMetrics.MemStats.NumGC)
+ r.Register("runtime.MemStats.GCCPUFraction", runtimeMetrics.MemStats.GCCPUFraction)
+ r.Register("runtime.MemStats.PauseNs", runtimeMetrics.MemStats.PauseNs)
+ r.Register("runtime.MemStats.PauseTotalNs", runtimeMetrics.MemStats.PauseTotalNs)
+ r.Register("runtime.MemStats.StackInuse", runtimeMetrics.MemStats.StackInuse)
+ r.Register("runtime.MemStats.StackSys", runtimeMetrics.MemStats.StackSys)
+ r.Register("runtime.MemStats.Sys", runtimeMetrics.MemStats.Sys)
+ r.Register("runtime.MemStats.TotalAlloc", runtimeMetrics.MemStats.TotalAlloc)
+ r.Register("runtime.NumCgoCall", runtimeMetrics.NumCgoCall)
+ r.Register("runtime.NumGoroutine", runtimeMetrics.NumGoroutine)
+ r.Register("runtime.NumThread", runtimeMetrics.NumThread)
+ r.Register("runtime.ReadMemStats", runtimeMetrics.ReadMemStats)
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/runtime_cgo.go b/vendor/github.com/rcrowley/go-metrics/runtime_cgo.go
new file mode 100644
index 0000000..e3391f4
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/runtime_cgo.go
@@ -0,0 +1,10 @@
+// +build cgo
+// +build !appengine
+
+package metrics
+
+import "runtime"
+
+func numCgoCall() int64 {
+ return runtime.NumCgoCall()
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/runtime_gccpufraction.go b/vendor/github.com/rcrowley/go-metrics/runtime_gccpufraction.go
new file mode 100644
index 0000000..ca12c05
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/runtime_gccpufraction.go
@@ -0,0 +1,9 @@
+// +build go1.5
+
+package metrics
+
+import "runtime"
+
+func gcCPUFraction(memStats *runtime.MemStats) float64 {
+ return memStats.GCCPUFraction
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/runtime_no_cgo.go b/vendor/github.com/rcrowley/go-metrics/runtime_no_cgo.go
new file mode 100644
index 0000000..616a3b4
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/runtime_no_cgo.go
@@ -0,0 +1,7 @@
+// +build !cgo appengine
+
+package metrics
+
+func numCgoCall() int64 {
+ return 0
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/runtime_no_gccpufraction.go b/vendor/github.com/rcrowley/go-metrics/runtime_no_gccpufraction.go
new file mode 100644
index 0000000..be96aa6
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/runtime_no_gccpufraction.go
@@ -0,0 +1,9 @@
+// +build !go1.5
+
+package metrics
+
+import "runtime"
+
+func gcCPUFraction(memStats *runtime.MemStats) float64 {
+ return 0
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/sample.go b/vendor/github.com/rcrowley/go-metrics/sample.go
new file mode 100644
index 0000000..5f6a377
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/sample.go
@@ -0,0 +1,609 @@
+package metrics
+
+import (
+ "math"
+ "math/rand"
+ "sort"
+ "sync"
+ "time"
+)
+
+const rescaleThreshold = time.Hour
+
+// Samples maintain a statistically-significant selection of values from
+// a stream.
+type Sample interface {
+ Clear()
+ Count() int64
+ Max() int64
+ Mean() float64
+ Min() int64
+ Percentile(float64) float64
+ Percentiles([]float64) []float64
+ Size() int
+ Snapshot() Sample
+ StdDev() float64
+ Sum() int64
+ Update(int64)
+ Values() []int64
+ Variance() float64
+}
+
+// ExpDecaySample is an exponentially-decaying sample using a forward-decaying
+// priority reservoir. See Cormode et al's "Forward Decay: A Practical Time
+// Decay Model for Streaming Systems".
+//
+// <http://www.research.att.com/people/Cormode_Graham/library/publications/CormodeShkapenyukSrivastavaXu09.pdf>
+type ExpDecaySample struct {
+ alpha float64
+ count int64
+ mutex sync.Mutex
+ reservoirSize int
+ t0, t1 time.Time
+ values *expDecaySampleHeap
+}
+
+// NewExpDecaySample constructs a new exponentially-decaying sample with the
+// given reservoir size and alpha.
+func NewExpDecaySample(reservoirSize int, alpha float64) Sample {
+ if UseNilMetrics {
+ return NilSample{}
+ }
+ s := &ExpDecaySample{
+ alpha: alpha,
+ reservoirSize: reservoirSize,
+ t0: time.Now(),
+ values: newExpDecaySampleHeap(reservoirSize),
+ }
+ s.t1 = s.t0.Add(rescaleThreshold)
+ return s
+}
+
+// Clear clears all samples.
+func (s *ExpDecaySample) Clear() {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ s.count = 0
+ s.t0 = time.Now()
+ s.t1 = s.t0.Add(rescaleThreshold)
+ s.values.Clear()
+}
+
+// Count returns the number of samples recorded, which may exceed the
+// reservoir size.
+func (s *ExpDecaySample) Count() int64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return s.count
+}
+
+// Max returns the maximum value in the sample, which may not be the maximum
+// value ever to be part of the sample.
+func (s *ExpDecaySample) Max() int64 {
+ return SampleMax(s.Values())
+}
+
+// Mean returns the mean of the values in the sample.
+func (s *ExpDecaySample) Mean() float64 {
+ return SampleMean(s.Values())
+}
+
+// Min returns the minimum value in the sample, which may not be the minimum
+// value ever to be part of the sample.
+func (s *ExpDecaySample) Min() int64 {
+ return SampleMin(s.Values())
+}
+
+// Percentile returns an arbitrary percentile of values in the sample.
+func (s *ExpDecaySample) Percentile(p float64) float64 {
+ return SamplePercentile(s.Values(), p)
+}
+
+// Percentiles returns a slice of arbitrary percentiles of values in the
+// sample.
+func (s *ExpDecaySample) Percentiles(ps []float64) []float64 {
+ return SamplePercentiles(s.Values(), ps)
+}
+
+// Size returns the size of the sample, which is at most the reservoir size.
+func (s *ExpDecaySample) Size() int {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return s.values.Size()
+}
+
+// Snapshot returns a read-only copy of the sample.
+func (s *ExpDecaySample) Snapshot() Sample {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ vals := s.values.Values()
+ values := make([]int64, len(vals))
+ for i, v := range vals {
+ values[i] = v.v
+ }
+ return &SampleSnapshot{
+ count: s.count,
+ values: values,
+ }
+}
+
+// StdDev returns the standard deviation of the values in the sample.
+func (s *ExpDecaySample) StdDev() float64 {
+ return SampleStdDev(s.Values())
+}
+
+// Sum returns the sum of the values in the sample.
+func (s *ExpDecaySample) Sum() int64 {
+ return SampleSum(s.Values())
+}
+
+// Update samples a new value.
+func (s *ExpDecaySample) Update(v int64) {
+ s.update(time.Now(), v)
+}
+
+// Values returns a copy of the values in the sample.
+func (s *ExpDecaySample) Values() []int64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ vals := s.values.Values()
+ values := make([]int64, len(vals))
+ for i, v := range vals {
+ values[i] = v.v
+ }
+ return values
+}
+
+// Variance returns the variance of the values in the sample.
+func (s *ExpDecaySample) Variance() float64 {
+ return SampleVariance(s.Values())
+}
+
+// update samples a new value at a particular timestamp. This is a method all
+// its own to facilitate testing.
+func (s *ExpDecaySample) update(t time.Time, v int64) {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ s.count++
+ if s.values.Size() == s.reservoirSize {
+ s.values.Pop()
+ }
+ s.values.Push(expDecaySample{
+ k: math.Exp(t.Sub(s.t0).Seconds()*s.alpha) / rand.Float64(),
+ v: v,
+ })
+ if t.After(s.t1) {
+ values := s.values.Values()
+ t0 := s.t0
+ s.values.Clear()
+ s.t0 = t
+ s.t1 = s.t0.Add(rescaleThreshold)
+ for _, v := range values {
+ v.k = v.k * math.Exp(-s.alpha*s.t0.Sub(t0).Seconds())
+ s.values.Push(v)
+ }
+ }
+}
+
+// NilSample is a no-op Sample.
+type NilSample struct{}
+
+// Clear is a no-op.
+func (NilSample) Clear() {}
+
+// Count is a no-op.
+func (NilSample) Count() int64 { return 0 }
+
+// Max is a no-op.
+func (NilSample) Max() int64 { return 0 }
+
+// Mean is a no-op.
+func (NilSample) Mean() float64 { return 0.0 }
+
+// Min is a no-op.
+func (NilSample) Min() int64 { return 0 }
+
+// Percentile is a no-op.
+func (NilSample) Percentile(p float64) float64 { return 0.0 }
+
+// Percentiles is a no-op.
+func (NilSample) Percentiles(ps []float64) []float64 {
+ return make([]float64, len(ps))
+}
+
+// Size is a no-op.
+func (NilSample) Size() int { return 0 }
+
+// Sample is a no-op.
+func (NilSample) Snapshot() Sample { return NilSample{} }
+
+// StdDev is a no-op.
+func (NilSample) StdDev() float64 { return 0.0 }
+
+// Sum is a no-op.
+func (NilSample) Sum() int64 { return 0 }
+
+// Update is a no-op.
+func (NilSample) Update(v int64) {}
+
+// Values is a no-op.
+func (NilSample) Values() []int64 { return []int64{} }
+
+// Variance is a no-op.
+func (NilSample) Variance() float64 { return 0.0 }
+
+// SampleMax returns the maximum value of the slice of int64.
+func SampleMax(values []int64) int64 {
+ if 0 == len(values) {
+ return 0
+ }
+ var max int64 = math.MinInt64
+ for _, v := range values {
+ if max < v {
+ max = v
+ }
+ }
+ return max
+}
+
+// SampleMean returns the mean value of the slice of int64.
+func SampleMean(values []int64) float64 {
+ if 0 == len(values) {
+ return 0.0
+ }
+ return float64(SampleSum(values)) / float64(len(values))
+}
+
+// SampleMin returns the minimum value of the slice of int64.
+func SampleMin(values []int64) int64 {
+ if 0 == len(values) {
+ return 0
+ }
+ var min int64 = math.MaxInt64
+ for _, v := range values {
+ if min > v {
+ min = v
+ }
+ }
+ return min
+}
+
+// SamplePercentiles returns an arbitrary percentile of the slice of int64.
+func SamplePercentile(values int64Slice, p float64) float64 {
+ return SamplePercentiles(values, []float64{p})[0]
+}
+
+// SamplePercentiles returns a slice of arbitrary percentiles of the slice of
+// int64.
+func SamplePercentiles(values int64Slice, ps []float64) []float64 {
+ scores := make([]float64, len(ps))
+ size := len(values)
+ if size > 0 {
+ sort.Sort(values)
+ for i, p := range ps {
+ pos := p * float64(size+1)
+ if pos < 1.0 {
+ scores[i] = float64(values[0])
+ } else if pos >= float64(size) {
+ scores[i] = float64(values[size-1])
+ } else {
+ lower := float64(values[int(pos)-1])
+ upper := float64(values[int(pos)])
+ scores[i] = lower + (pos-math.Floor(pos))*(upper-lower)
+ }
+ }
+ }
+ return scores
+}
+
+// SampleSnapshot is a read-only copy of another Sample.
+type SampleSnapshot struct {
+ count int64
+ values []int64
+}
+
+// Clear panics.
+func (*SampleSnapshot) Clear() {
+ panic("Clear called on a SampleSnapshot")
+}
+
+// Count returns the count of inputs at the time the snapshot was taken.
+func (s *SampleSnapshot) Count() int64 { return s.count }
+
+// Max returns the maximal value at the time the snapshot was taken.
+func (s *SampleSnapshot) Max() int64 { return SampleMax(s.values) }
+
+// Mean returns the mean value at the time the snapshot was taken.
+func (s *SampleSnapshot) Mean() float64 { return SampleMean(s.values) }
+
+// Min returns the minimal value at the time the snapshot was taken.
+func (s *SampleSnapshot) Min() int64 { return SampleMin(s.values) }
+
+// Percentile returns an arbitrary percentile of values at the time the
+// snapshot was taken.
+func (s *SampleSnapshot) Percentile(p float64) float64 {
+ return SamplePercentile(s.values, p)
+}
+
+// Percentiles returns a slice of arbitrary percentiles of values at the time
+// the snapshot was taken.
+func (s *SampleSnapshot) Percentiles(ps []float64) []float64 {
+ return SamplePercentiles(s.values, ps)
+}
+
+// Size returns the size of the sample at the time the snapshot was taken.
+func (s *SampleSnapshot) Size() int { return len(s.values) }
+
+// Snapshot returns the snapshot.
+func (s *SampleSnapshot) Snapshot() Sample { return s }
+
+// StdDev returns the standard deviation of values at the time the snapshot was
+// taken.
+func (s *SampleSnapshot) StdDev() float64 { return SampleStdDev(s.values) }
+
+// Sum returns the sum of values at the time the snapshot was taken.
+func (s *SampleSnapshot) Sum() int64 { return SampleSum(s.values) }
+
+// Update panics.
+func (*SampleSnapshot) Update(int64) {
+ panic("Update called on a SampleSnapshot")
+}
+
+// Values returns a copy of the values in the sample.
+func (s *SampleSnapshot) Values() []int64 {
+ values := make([]int64, len(s.values))
+ copy(values, s.values)
+ return values
+}
+
+// Variance returns the variance of values at the time the snapshot was taken.
+func (s *SampleSnapshot) Variance() float64 { return SampleVariance(s.values) }
+
+// SampleStdDev returns the standard deviation of the slice of int64.
+func SampleStdDev(values []int64) float64 {
+ return math.Sqrt(SampleVariance(values))
+}
+
+// SampleSum returns the sum of the slice of int64.
+func SampleSum(values []int64) int64 {
+ var sum int64
+ for _, v := range values {
+ sum += v
+ }
+ return sum
+}
+
+// SampleVariance returns the variance of the slice of int64.
+func SampleVariance(values []int64) float64 {
+ if 0 == len(values) {
+ return 0.0
+ }
+ m := SampleMean(values)
+ var sum float64
+ for _, v := range values {
+ d := float64(v) - m
+ sum += d * d
+ }
+ return sum / float64(len(values))
+}
+
+// A uniform sample using Vitter's Algorithm R.
+//
+// <http://www.cs.umd.edu/~samir/498/vitter.pdf>
+type UniformSample struct {
+ count int64
+ mutex sync.Mutex
+ reservoirSize int
+ values []int64
+}
+
+// NewUniformSample constructs a new uniform sample with the given reservoir
+// size.
+func NewUniformSample(reservoirSize int) Sample {
+ if UseNilMetrics {
+ return NilSample{}
+ }
+ return &UniformSample{
+ reservoirSize: reservoirSize,
+ values: make([]int64, 0, reservoirSize),
+ }
+}
+
+// Clear clears all samples.
+func (s *UniformSample) Clear() {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ s.count = 0
+ s.values = make([]int64, 0, s.reservoirSize)
+}
+
+// Count returns the number of samples recorded, which may exceed the
+// reservoir size.
+func (s *UniformSample) Count() int64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return s.count
+}
+
+// Max returns the maximum value in the sample, which may not be the maximum
+// value ever to be part of the sample.
+func (s *UniformSample) Max() int64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return SampleMax(s.values)
+}
+
+// Mean returns the mean of the values in the sample.
+func (s *UniformSample) Mean() float64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return SampleMean(s.values)
+}
+
+// Min returns the minimum value in the sample, which may not be the minimum
+// value ever to be part of the sample.
+func (s *UniformSample) Min() int64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return SampleMin(s.values)
+}
+
+// Percentile returns an arbitrary percentile of values in the sample.
+func (s *UniformSample) Percentile(p float64) float64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return SamplePercentile(s.values, p)
+}
+
+// Percentiles returns a slice of arbitrary percentiles of values in the
+// sample.
+func (s *UniformSample) Percentiles(ps []float64) []float64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return SamplePercentiles(s.values, ps)
+}
+
+// Size returns the size of the sample, which is at most the reservoir size.
+func (s *UniformSample) Size() int {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return len(s.values)
+}
+
+// Snapshot returns a read-only copy of the sample.
+func (s *UniformSample) Snapshot() Sample {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ values := make([]int64, len(s.values))
+ copy(values, s.values)
+ return &SampleSnapshot{
+ count: s.count,
+ values: values,
+ }
+}
+
+// StdDev returns the standard deviation of the values in the sample.
+func (s *UniformSample) StdDev() float64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return SampleStdDev(s.values)
+}
+
+// Sum returns the sum of the values in the sample.
+func (s *UniformSample) Sum() int64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return SampleSum(s.values)
+}
+
+// Update samples a new value.
+func (s *UniformSample) Update(v int64) {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ s.count++
+ if len(s.values) < s.reservoirSize {
+ s.values = append(s.values, v)
+ } else {
+ r := rand.Int63n(s.count)
+ if r < int64(len(s.values)) {
+ s.values[int(r)] = v
+ }
+ }
+}
+
+// Values returns a copy of the values in the sample.
+func (s *UniformSample) Values() []int64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ values := make([]int64, len(s.values))
+ copy(values, s.values)
+ return values
+}
+
+// Variance returns the variance of the values in the sample.
+func (s *UniformSample) Variance() float64 {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+ return SampleVariance(s.values)
+}
+
+// expDecaySample represents an individual sample in a heap.
+type expDecaySample struct {
+ k float64
+ v int64
+}
+
+func newExpDecaySampleHeap(reservoirSize int) *expDecaySampleHeap {
+ return &expDecaySampleHeap{make([]expDecaySample, 0, reservoirSize)}
+}
+
+// expDecaySampleHeap is a min-heap of expDecaySamples.
+// The internal implementation is copied from the standard library's container/heap
+type expDecaySampleHeap struct {
+ s []expDecaySample
+}
+
+func (h *expDecaySampleHeap) Clear() {
+ h.s = h.s[:0]
+}
+
+func (h *expDecaySampleHeap) Push(s expDecaySample) {
+ n := len(h.s)
+ h.s = h.s[0 : n+1]
+ h.s[n] = s
+ h.up(n)
+}
+
+func (h *expDecaySampleHeap) Pop() expDecaySample {
+ n := len(h.s) - 1
+ h.s[0], h.s[n] = h.s[n], h.s[0]
+ h.down(0, n)
+
+ n = len(h.s)
+ s := h.s[n-1]
+ h.s = h.s[0 : n-1]
+ return s
+}
+
+func (h *expDecaySampleHeap) Size() int {
+ return len(h.s)
+}
+
+func (h *expDecaySampleHeap) Values() []expDecaySample {
+ return h.s
+}
+
+func (h *expDecaySampleHeap) up(j int) {
+ for {
+ i := (j - 1) / 2 // parent
+ if i == j || !(h.s[j].k < h.s[i].k) {
+ break
+ }
+ h.s[i], h.s[j] = h.s[j], h.s[i]
+ j = i
+ }
+}
+
+func (h *expDecaySampleHeap) down(i, n int) {
+ for {
+ j1 := 2*i + 1
+ if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
+ break
+ }
+ j := j1 // left child
+ if j2 := j1 + 1; j2 < n && !(h.s[j1].k < h.s[j2].k) {
+ j = j2 // = 2*i + 2 // right child
+ }
+ if !(h.s[j].k < h.s[i].k) {
+ break
+ }
+ h.s[i], h.s[j] = h.s[j], h.s[i]
+ i = j
+ }
+}
+
+type int64Slice []int64
+
+func (p int64Slice) Len() int { return len(p) }
+func (p int64Slice) Less(i, j int) bool { return p[i] < p[j] }
+func (p int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
diff --git a/vendor/github.com/rcrowley/go-metrics/syslog.go b/vendor/github.com/rcrowley/go-metrics/syslog.go
new file mode 100644
index 0000000..693f190
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/syslog.go
@@ -0,0 +1,78 @@
+// +build !windows
+
+package metrics
+
+import (
+ "fmt"
+ "log/syslog"
+ "time"
+)
+
+// Output each metric in the given registry to syslog periodically using
+// the given syslogger.
+func Syslog(r Registry, d time.Duration, w *syslog.Writer) {
+ for _ = range time.Tick(d) {
+ r.Each(func(name string, i interface{}) {
+ switch metric := i.(type) {
+ case Counter:
+ w.Info(fmt.Sprintf("counter %s: count: %d", name, metric.Count()))
+ case Gauge:
+ w.Info(fmt.Sprintf("gauge %s: value: %d", name, metric.Value()))
+ case GaugeFloat64:
+ w.Info(fmt.Sprintf("gauge %s: value: %f", name, metric.Value()))
+ case Healthcheck:
+ metric.Check()
+ w.Info(fmt.Sprintf("healthcheck %s: error: %v", name, metric.Error()))
+ case Histogram:
+ h := metric.Snapshot()
+ ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
+ w.Info(fmt.Sprintf(
+ "histogram %s: count: %d min: %d max: %d mean: %.2f stddev: %.2f median: %.2f 75%%: %.2f 95%%: %.2f 99%%: %.2f 99.9%%: %.2f",
+ name,
+ h.Count(),
+ h.Min(),
+ h.Max(),
+ h.Mean(),
+ h.StdDev(),
+ ps[0],
+ ps[1],
+ ps[2],
+ ps[3],
+ ps[4],
+ ))
+ case Meter:
+ m := metric.Snapshot()
+ w.Info(fmt.Sprintf(
+ "meter %s: count: %d 1-min: %.2f 5-min: %.2f 15-min: %.2f mean: %.2f",
+ name,
+ m.Count(),
+ m.Rate1(),
+ m.Rate5(),
+ m.Rate15(),
+ m.RateMean(),
+ ))
+ case Timer:
+ t := metric.Snapshot()
+ ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
+ w.Info(fmt.Sprintf(
+ "timer %s: count: %d min: %d max: %d mean: %.2f stddev: %.2f median: %.2f 75%%: %.2f 95%%: %.2f 99%%: %.2f 99.9%%: %.2f 1-min: %.2f 5-min: %.2f 15-min: %.2f mean-rate: %.2f",
+ name,
+ t.Count(),
+ t.Min(),
+ t.Max(),
+ t.Mean(),
+ t.StdDev(),
+ ps[0],
+ ps[1],
+ ps[2],
+ ps[3],
+ ps[4],
+ t.Rate1(),
+ t.Rate5(),
+ t.Rate15(),
+ t.RateMean(),
+ ))
+ }
+ })
+ }
+}
diff --git a/vendor/github.com/rcrowley/go-metrics/timer.go b/vendor/github.com/rcrowley/go-metrics/timer.go
new file mode 100644
index 0000000..17db8f8
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/timer.go
@@ -0,0 +1,311 @@
+package metrics
+
+import (
+ "sync"
+ "time"
+)
+
+// Timers capture the duration and rate of events.
+type Timer interface {
+ Count() int64
+ Max() int64
+ Mean() float64
+ Min() int64
+ Percentile(float64) float64
+ Percentiles([]float64) []float64
+ Rate1() float64
+ Rate5() float64
+ Rate15() float64
+ RateMean() float64
+ Snapshot() Timer
+ StdDev() float64
+ Sum() int64
+ Time(func())
+ Update(time.Duration)
+ UpdateSince(time.Time)
+ Variance() float64
+}
+
+// GetOrRegisterTimer returns an existing Timer or constructs and registers a
+// new StandardTimer.
+func GetOrRegisterTimer(name string, r Registry) Timer {
+ if nil == r {
+ r = DefaultRegistry
+ }
+ return r.GetOrRegister(name, NewTimer).(Timer)
+}
+
+// NewCustomTimer constructs a new StandardTimer from a Histogram and a Meter.
+func NewCustomTimer(h Histogram, m Meter) Timer {
+ if UseNilMetrics {
+ return NilTimer{}
+ }
+ return &StandardTimer{
+ histogram: h,
+ meter: m,
+ }
+}
+
+// NewRegisteredTimer constructs and registers a new StandardTimer.
+func NewRegisteredTimer(name string, r Registry) Timer {
+ c := NewTimer()
+ if nil == r {
+ r = DefaultRegistry
+ }
+ r.Register(name, c)
+ return c
+}
+
+// NewTimer constructs a new StandardTimer using an exponentially-decaying
+// sample with the same reservoir size and alpha as UNIX load averages.
+func NewTimer() Timer {
+ if UseNilMetrics {
+ return NilTimer{}
+ }
+ return &StandardTimer{
+ histogram: NewHistogram(NewExpDecaySample(1028, 0.015)),
+ meter: NewMeter(),
+ }
+}
+
+// NilTimer is a no-op Timer.
+type NilTimer struct {
+ h Histogram
+ m Meter
+}
+
+// Count is a no-op.
+func (NilTimer) Count() int64 { return 0 }
+
+// Max is a no-op.
+func (NilTimer) Max() int64 { return 0 }
+
+// Mean is a no-op.
+func (NilTimer) Mean() float64 { return 0.0 }
+
+// Min is a no-op.
+func (NilTimer) Min() int64 { return 0 }
+
+// Percentile is a no-op.
+func (NilTimer) Percentile(p float64) float64 { return 0.0 }
+
+// Percentiles is a no-op.
+func (NilTimer) Percentiles(ps []float64) []float64 {
+ return make([]float64, len(ps))
+}
+
+// Rate1 is a no-op.
+func (NilTimer) Rate1() float64 { return 0.0 }
+
+// Rate5 is a no-op.
+func (NilTimer) Rate5() float64 { return 0.0 }
+
+// Rate15 is a no-op.
+func (NilTimer) Rate15() float64 { return 0.0 }
+
+// RateMean is a no-op.
+func (NilTimer) RateMean() float64 { return 0.0 }
+
+// Snapshot is a no-op.
+func (NilTimer) Snapshot() Timer { return NilTimer{} }
+
+// StdDev is a no-op.
+func (NilTimer) StdDev() float64 { return 0.0 }
+
+// Sum is a no-op.
+func (NilTimer) Sum() int64 { return 0 }
+
+// Time is a no-op.
+func (NilTimer) Time(func()) {}
+
+// Update is a no-op.
+func (NilTimer) Update(time.Duration) {}
+
+// UpdateSince is a no-op.
+func (NilTimer) UpdateSince(time.Time) {}
+
+// Variance is a no-op.
+func (NilTimer) Variance() float64 { return 0.0 }
+
+// StandardTimer is the standard implementation of a Timer and uses a Histogram
+// and Meter.
+type StandardTimer struct {
+ histogram Histogram
+ meter Meter
+ mutex sync.Mutex
+}
+
+// Count returns the number of events recorded.
+func (t *StandardTimer) Count() int64 {
+ return t.histogram.Count()
+}
+
+// Max returns the maximum value in the sample.
+func (t *StandardTimer) Max() int64 {
+ return t.histogram.Max()
+}
+
+// Mean returns the mean of the values in the sample.
+func (t *StandardTimer) Mean() float64 {
+ return t.histogram.Mean()
+}
+
+// Min returns the minimum value in the sample.
+func (t *StandardTimer) Min() int64 {
+ return t.histogram.Min()
+}
+
+// Percentile returns an arbitrary percentile of the values in the sample.
+func (t *StandardTimer) Percentile(p float64) float64 {
+ return t.histogram.Percentile(p)
+}
+
+// Percentiles returns a slice of arbitrary percentiles of the values in the
+// sample.
+func (t *StandardTimer) Percentiles(ps []float64) []float64 {
+ return t.histogram.Percentiles(ps)
+}
+
+// Rate1 returns the one-minute moving average rate of events per second.
+func (t *StandardTimer) Rate1() float64 {
+ return t.meter.Rate1()
+}
+
+// Rate5 returns the five-minute moving average rate of events per second.
+func (t *StandardTimer) Rate5() float64 {
+ return t.meter.Rate5()
+}
+
+// Rate15 returns the fifteen-minute moving average rate of events per second.
+func (t *StandardTimer) Rate15() float64 {
+ return t.meter.Rate15()
+}
+
+// RateMean returns the meter's mean rate of events per second.
+func (t *StandardTimer) RateMean() float64 {
+ return t.meter.RateMean()
+}
+
+// Snapshot returns a read-only copy of the timer.
+func (t *StandardTimer) Snapshot() Timer {
+ t.mutex.Lock()
+ defer t.mutex.Unlock()
+ return &TimerSnapshot{
+ histogram: t.histogram.Snapshot().(*HistogramSnapshot),
+ meter: t.meter.Snapshot().(*MeterSnapshot),
+ }
+}
+
+// StdDev returns the standard deviation of the values in the sample.
+func (t *StandardTimer) StdDev() float64 {
+ return t.histogram.StdDev()
+}
+
+// Sum returns the sum in the sample.
+func (t *StandardTimer) Sum() int64 {
+ return t.histogram.Sum()
+}
+
+// Record the duration of the execution of the given function.
+func (t *StandardTimer) Time(f func()) {
+ ts := time.Now()
+ f()
+ t.Update(time.Since(ts))
+}
+
+// Record the duration of an event.
+func (t *StandardTimer) Update(d time.Duration) {
+ t.mutex.Lock()
+ defer t.mutex.Unlock()
+ t.histogram.Update(int64(d))
+ t.meter.Mark(1)
+}
+
+// Record the duration of an event that started at a time and ends now.
+func (t *StandardTimer) UpdateSince(ts time.Time) {
+ t.mutex.Lock()
+ defer t.mutex.Unlock()
+ t.histogram.Update(int64(time.Since(ts)))
+ t.meter.Mark(1)
+}
+
+// Variance returns the variance of the values in the sample.
+func (t *StandardTimer) Variance() float64 {
+ return t.histogram.Variance()
+}
+
+// TimerSnapshot is a read-only copy of another Timer.
+type TimerSnapshot struct {
+ histogram *HistogramSnapshot
+ meter *MeterSnapshot
+}
+
+// Count returns the number of events recorded at the time the snapshot was
+// taken.
+func (t *TimerSnapshot) Count() int64 { return t.histogram.Count() }
+
+// Max returns the maximum value at the time the snapshot was taken.
+func (t *TimerSnapshot) Max() int64 { return t.histogram.Max() }
+
+// Mean returns the mean value at the time the snapshot was taken.
+func (t *TimerSnapshot) Mean() float64 { return t.histogram.Mean() }
+
+// Min returns the minimum value at the time the snapshot was taken.
+func (t *TimerSnapshot) Min() int64 { return t.histogram.Min() }
+
+// Percentile returns an arbitrary percentile of sampled values at the time the
+// snapshot was taken.
+func (t *TimerSnapshot) Percentile(p float64) float64 {
+ return t.histogram.Percentile(p)
+}
+
+// Percentiles returns a slice of arbitrary percentiles of sampled values at
+// the time the snapshot was taken.
+func (t *TimerSnapshot) Percentiles(ps []float64) []float64 {
+ return t.histogram.Percentiles(ps)
+}
+
+// Rate1 returns the one-minute moving average rate of events per second at the
+// time the snapshot was taken.
+func (t *TimerSnapshot) Rate1() float64 { return t.meter.Rate1() }
+
+// Rate5 returns the five-minute moving average rate of events per second at
+// the time the snapshot was taken.
+func (t *TimerSnapshot) Rate5() float64 { return t.meter.Rate5() }
+
+// Rate15 returns the fifteen-minute moving average rate of events per second
+// at the time the snapshot was taken.
+func (t *TimerSnapshot) Rate15() float64 { return t.meter.Rate15() }
+
+// RateMean returns the meter's mean rate of events per second at the time the
+// snapshot was taken.
+func (t *TimerSnapshot) RateMean() float64 { return t.meter.RateMean() }
+
+// Snapshot returns the snapshot.
+func (t *TimerSnapshot) Snapshot() Timer { return t }
+
+// StdDev returns the standard deviation of the values at the time the snapshot
+// was taken.
+func (t *TimerSnapshot) StdDev() float64 { return t.histogram.StdDev() }
+
+// Sum returns the sum at the time the snapshot was taken.
+func (t *TimerSnapshot) Sum() int64 { return t.histogram.Sum() }
+
+// Time panics.
+func (*TimerSnapshot) Time(func()) {
+ panic("Time called on a TimerSnapshot")
+}
+
+// Update panics.
+func (*TimerSnapshot) Update(time.Duration) {
+ panic("Update called on a TimerSnapshot")
+}
+
+// UpdateSince panics.
+func (*TimerSnapshot) UpdateSince(time.Time) {
+ panic("UpdateSince called on a TimerSnapshot")
+}
+
+// Variance returns the variance of the values at the time the snapshot was
+// taken.
+func (t *TimerSnapshot) Variance() float64 { return t.histogram.Variance() }
diff --git a/vendor/github.com/rcrowley/go-metrics/writer.go b/vendor/github.com/rcrowley/go-metrics/writer.go
new file mode 100644
index 0000000..091e971
--- /dev/null
+++ b/vendor/github.com/rcrowley/go-metrics/writer.go
@@ -0,0 +1,100 @@
+package metrics
+
+import (
+ "fmt"
+ "io"
+ "sort"
+ "time"
+)
+
+// Write sorts writes each metric in the given registry periodically to the
+// given io.Writer.
+func Write(r Registry, d time.Duration, w io.Writer) {
+ for _ = range time.Tick(d) {
+ WriteOnce(r, w)
+ }
+}
+
+// WriteOnce sorts and writes metrics in the given registry to the given
+// io.Writer.
+func WriteOnce(r Registry, w io.Writer) {
+ var namedMetrics namedMetricSlice
+ r.Each(func(name string, i interface{}) {
+ namedMetrics = append(namedMetrics, namedMetric{name, i})
+ })
+
+ sort.Sort(namedMetrics)
+ for _, namedMetric := range namedMetrics {
+ switch metric := namedMetric.m.(type) {
+ case Counter:
+ fmt.Fprintf(w, "counter %s\n", namedMetric.name)
+ fmt.Fprintf(w, " count: %9d\n", metric.Count())
+ case Gauge:
+ fmt.Fprintf(w, "gauge %s\n", namedMetric.name)
+ fmt.Fprintf(w, " value: %9d\n", metric.Value())
+ case GaugeFloat64:
+ fmt.Fprintf(w, "gauge %s\n", namedMetric.name)
+ fmt.Fprintf(w, " value: %f\n", metric.Value())
+ case Healthcheck:
+ metric.Check()
+ fmt.Fprintf(w, "healthcheck %s\n", namedMetric.name)
+ fmt.Fprintf(w, " error: %v\n", metric.Error())
+ case Histogram:
+ h := metric.Snapshot()
+ ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
+ fmt.Fprintf(w, "histogram %s\n", namedMetric.name)
+ fmt.Fprintf(w, " count: %9d\n", h.Count())
+ fmt.Fprintf(w, " min: %9d\n", h.Min())
+ fmt.Fprintf(w, " max: %9d\n", h.Max())
+ fmt.Fprintf(w, " mean: %12.2f\n", h.Mean())
+ fmt.Fprintf(w, " stddev: %12.2f\n", h.StdDev())
+ fmt.Fprintf(w, " median: %12.2f\n", ps[0])
+ fmt.Fprintf(w, " 75%%: %12.2f\n", ps[1])
+ fmt.Fprintf(w, " 95%%: %12.2f\n", ps[2])
+ fmt.Fprintf(w, " 99%%: %12.2f\n", ps[3])
+ fmt.Fprintf(w, " 99.9%%: %12.2f\n", ps[4])
+ case Meter:
+ m := metric.Snapshot()
+ fmt.Fprintf(w, "meter %s\n", namedMetric.name)
+ fmt.Fprintf(w, " count: %9d\n", m.Count())
+ fmt.Fprintf(w, " 1-min rate: %12.2f\n", m.Rate1())
+ fmt.Fprintf(w, " 5-min rate: %12.2f\n", m.Rate5())
+ fmt.Fprintf(w, " 15-min rate: %12.2f\n", m.Rate15())
+ fmt.Fprintf(w, " mean rate: %12.2f\n", m.RateMean())
+ case Timer:
+ t := metric.Snapshot()
+ ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
+ fmt.Fprintf(w, "timer %s\n", namedMetric.name)
+ fmt.Fprintf(w, " count: %9d\n", t.Count())
+ fmt.Fprintf(w, " min: %9d\n", t.Min())
+ fmt.Fprintf(w, " max: %9d\n", t.Max())
+ fmt.Fprintf(w, " mean: %12.2f\n", t.Mean())
+ fmt.Fprintf(w, " stddev: %12.2f\n", t.StdDev())
+ fmt.Fprintf(w, " median: %12.2f\n", ps[0])
+ fmt.Fprintf(w, " 75%%: %12.2f\n", ps[1])
+ fmt.Fprintf(w, " 95%%: %12.2f\n", ps[2])
+ fmt.Fprintf(w, " 99%%: %12.2f\n", ps[3])
+ fmt.Fprintf(w, " 99.9%%: %12.2f\n", ps[4])
+ fmt.Fprintf(w, " 1-min rate: %12.2f\n", t.Rate1())
+ fmt.Fprintf(w, " 5-min rate: %12.2f\n", t.Rate5())
+ fmt.Fprintf(w, " 15-min rate: %12.2f\n", t.Rate15())
+ fmt.Fprintf(w, " mean rate: %12.2f\n", t.RateMean())
+ }
+ }
+}
+
+type namedMetric struct {
+ name string
+ m interface{}
+}
+
+// namedMetricSlice is a slice of namedMetrics that implements sort.Interface.
+type namedMetricSlice []namedMetric
+
+func (nms namedMetricSlice) Len() int { return len(nms) }
+
+func (nms namedMetricSlice) Swap(i, j int) { nms[i], nms[j] = nms[j], nms[i] }
+
+func (nms namedMetricSlice) Less(i, j int) bool {
+ return nms[i].name < nms[j].name
+}
diff --git a/vendor/github.com/resin-os/circbuf/LICENSE b/vendor/github.com/resin-os/circbuf/LICENSE
new file mode 100755
index 0000000..106569e
--- /dev/null
+++ b/vendor/github.com/resin-os/circbuf/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Armon Dadgar
+
+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/resin-os/circbuf/README.md b/vendor/github.com/resin-os/circbuf/README.md
new file mode 100644
index 0000000..f2e356b
--- /dev/null
+++ b/vendor/github.com/resin-os/circbuf/README.md
@@ -0,0 +1,28 @@
+circbuf
+=======
+
+This repository provides the `circbuf` package. This provides a `Buffer` object
+which is a circular (or ring) buffer. It has a fixed size, but can be written
+to infinitely. Only the last `size` bytes are ever retained. The buffer implements
+the `io.Writer` interface.
+
+Documentation
+=============
+
+Full documentation can be found on [Godoc](http://godoc.org/github.com/armon/circbuf)
+
+Usage
+=====
+
+The `circbuf` package is very easy to use:
+
+```go
+buf, _ := NewBuffer(6)
+buf.Write([]byte("hello world"))
+
+if string(buf.Bytes()) != " world" {
+ panic("should only have last 6 bytes!")
+}
+
+```
+
diff --git a/vendor/github.com/resin-os/circbuf/circbuf.go b/vendor/github.com/resin-os/circbuf/circbuf.go
new file mode 100644
index 0000000..381e096
--- /dev/null
+++ b/vendor/github.com/resin-os/circbuf/circbuf.go
@@ -0,0 +1,115 @@
+package circbuf
+
+import (
+ "fmt"
+)
+
+// Buffer implements a circular buffer. It is a fixed size,
+// and new writes overwrite older data, such that for a buffer
+// of size N, for any amount of writes, only the last N bytes
+// are retained.
+type Buffer struct {
+ data []byte
+ out []byte
+ size int64
+ writeCursor int64
+ written int64
+}
+
+// NewBuffer creates a new buffer of a given size. The size
+// must be greater than 0.
+func NewBuffer(size int64) (*Buffer, error) {
+ if size <= 0 {
+ return nil, fmt.Errorf("Size must be positive")
+ }
+
+ b := &Buffer{
+ size: size,
+ data: make([]byte, size),
+ out: make([]byte, size),
+ }
+ return b, nil
+}
+
+// Write writes up to len(buf) bytes to the internal ring,
+// overriding older data if necessary.
+func (b *Buffer) Write(buf []byte) (int, error) {
+ // Account for total bytes written
+ n := len(buf)
+ b.written += int64(n)
+
+ // If the buffer is larger than ours, then we only care
+ // about the last size bytes anyways
+ if int64(n) > b.size {
+ buf = buf[int64(n)-b.size:]
+ }
+
+ // Copy in place
+ remain := b.size - b.writeCursor
+ copy(b.data[b.writeCursor:], buf)
+ if int64(len(buf)) > remain {
+ copy(b.data, buf[remain:])
+ }
+
+ // Update location of the cursor
+ b.writeCursor = ((b.writeCursor + int64(len(buf))) % b.size)
+ return n, nil
+}
+
+// WriteByte writes a single byte into the buffer.
+func (b *Buffer) WriteByte(c byte) error {
+ b.data[b.writeCursor] = c
+ b.writeCursor = ((b.writeCursor + 1) % b.size)
+ b.written++
+ return nil
+}
+
+// Size returns the size of the buffer
+func (b *Buffer) Size() int64 {
+ return b.size
+}
+
+// TotalWritten provides the total number of bytes written
+func (b *Buffer) TotalWritten() int64 {
+ return b.written
+}
+
+// Bytes provides a slice of the bytes written. This
+// slice should not be written to. The underlying array
+// may point to data that will be overwritten by a subsequent
+// call to Bytes. It does no allocation.
+func (b *Buffer) Bytes() []byte {
+ switch {
+ case b.written >= b.size && b.writeCursor == 0:
+ return b.data
+ case b.written > b.size:
+ copy(b.out, b.data[b.writeCursor:])
+ copy(b.out[b.size-b.writeCursor:], b.data[:b.writeCursor])
+ return b.out
+ default:
+ return b.data[:b.writeCursor]
+ }
+}
+
+// Get returns a single byte out of the buffer, at the given position.
+func (b *Buffer) Get(i int64) (byte, error) {
+ switch {
+ case i >= b.written || i >= b.size:
+ return 0, fmt.Errorf("Index out of bounds: %v", i)
+ case b.written > b.size:
+ return b.data[(b.writeCursor+i)%b.size], nil
+ default:
+ return b.data[i], nil
+ }
+}
+
+// Reset resets the buffer so it has no content.
+func (b *Buffer) Reset() {
+ b.writeCursor = 0
+ b.written = 0
+}
+
+// String returns the contents of the buffer as a string
+func (b *Buffer) String() string {
+ return string(b.Bytes())
+}
diff --git a/vendor/github.com/resin-os/librsync-go/LICENSE b/vendor/github.com/resin-os/librsync-go/LICENSE
new file mode 100644
index 0000000..430d42b
--- /dev/null
+++ b/vendor/github.com/resin-os/librsync-go/LICENSE
@@ -0,0 +1,177 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
diff --git a/vendor/github.com/resin-os/librsync-go/README.md b/vendor/github.com/resin-os/librsync-go/README.md
new file mode 100644
index 0000000..716f2af
--- /dev/null
+++ b/vendor/github.com/resin-os/librsync-go/README.md
@@ -0,0 +1,15 @@
+librsync-go
+=========
+
+librsync-go is a reimplementation of [librsync](https://github.com/librsync/librsync) in Go.
+
+Installing
+----------
+
+To install the rdiff utility:
+
+```
+go install github.com/resin-os/librsync-go/cmd/rdiff
+```
+
+To use it as a library simply include `github.com/resin-os/librsync-go` in your import statement
diff --git a/vendor/github.com/resin-os/librsync-go/delta.go b/vendor/github.com/resin-os/librsync-go/delta.go
new file mode 100644
index 0000000..c3d5e68
--- /dev/null
+++ b/vendor/github.com/resin-os/librsync-go/delta.go
@@ -0,0 +1,83 @@
+package librsync
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/binary"
+ "io"
+
+ "github.com/resin-os/circbuf"
+)
+
+func Delta(sig *SignatureType, i io.Reader, output io.Writer) error {
+ input := bufio.NewReader(i)
+
+ err := binary.Write(output, binary.BigEndian, DELTA_MAGIC)
+ if err != nil {
+ return err
+ }
+
+ prevByte := byte(0)
+ m := match{output: output}
+
+ weakSum := NewRollsum()
+ block, _ := circbuf.NewBuffer(int64(sig.blockLen))
+ block.WriteByte(0)
+ pos := 0
+
+ for {
+ pos += 1
+ in, err := input.ReadByte()
+ if err == io.EOF {
+ break
+ } else if err != nil {
+ return err
+ }
+
+ if block.TotalWritten() > 0 {
+ prevByte, err = block.Get(0)
+ if err != nil {
+ return err
+ }
+ }
+ block.WriteByte(in)
+ weakSum.Rollin(in)
+
+ if weakSum.count < uint64(sig.blockLen) {
+ continue
+ }
+
+ if weakSum.count > uint64(sig.blockLen) {
+ err := m.add(MATCH_KIND_LITERAL, uint64(prevByte), 1)
+ if err != nil {
+ return err
+ }
+ weakSum.Rollout(prevByte)
+ }
+
+ if blockIdx, ok := sig.weak2block[weakSum.Digest()]; ok {
+ strong2, _ := CalcStrongSum(block.Bytes(), sig.sigType, sig.strongLen)
+ if bytes.Equal(sig.strongSigs[blockIdx], strong2) {
+ weakSum.Reset()
+ block.Reset()
+ err := m.add(MATCH_KIND_COPY, uint64(blockIdx)*uint64(sig.blockLen), uint64(sig.blockLen))
+ if err != nil {
+ return err
+ }
+ }
+ }
+ }
+
+ for _, b := range block.Bytes() {
+ err := m.add(MATCH_KIND_LITERAL, uint64(b), 1)
+ if err != nil {
+ return err
+ }
+ }
+
+ if err := m.flush(); err != nil {
+ return err
+ }
+
+ return binary.Write(output, binary.BigEndian, OP_END)
+}
diff --git a/vendor/github.com/resin-os/librsync-go/match.go b/vendor/github.com/resin-os/librsync-go/match.go
new file mode 100644
index 0000000..95b220f
--- /dev/null
+++ b/vendor/github.com/resin-os/librsync-go/match.go
@@ -0,0 +1,151 @@
+package librsync
+
+import (
+ "encoding/binary"
+ "fmt"
+ "io"
+)
+
+type matchKind uint8
+
+const (
+ MATCH_KIND_LITERAL matchKind = iota
+ MATCH_KIND_COPY
+)
+
+type match struct {
+ kind matchKind
+ pos uint64
+ len uint64
+ output io.Writer
+ lit []byte
+}
+
+func intSize(d uint64) uint8 {
+ switch {
+ case d == uint64(uint8(d)):
+ return 1
+ case d == uint64(uint16(d)):
+ return 2
+ case d == uint64(uint32(d)):
+ return 4
+ default:
+ return 8
+ }
+}
+
+func (m *match) write(d uint64, size uint8) error {
+ switch size {
+ case 1:
+ return binary.Write(m.output, binary.BigEndian, uint8(d))
+ case 2:
+ return binary.Write(m.output, binary.BigEndian, uint16(d))
+ case 4:
+ return binary.Write(m.output, binary.BigEndian, uint32(d))
+ case 8:
+ return binary.Write(m.output, binary.BigEndian, uint64(d))
+ }
+ return fmt.Errorf("Invalid size: %v", size)
+}
+
+func (m *match) flush() error {
+ if m.len == 0 {
+ return nil
+ }
+ posSize := intSize(m.pos)
+ lenSize := intSize(m.len)
+
+ var cmd Op
+
+ switch m.kind {
+ case MATCH_KIND_COPY:
+ switch posSize {
+ case 1:
+ cmd = OP_COPY_N1_N1
+ case 2:
+ cmd = OP_COPY_N2_N1
+ case 4:
+ cmd = OP_COPY_N4_N1
+ case 8:
+ cmd = OP_COPY_N8_N1
+ }
+
+ switch lenSize {
+ case 2:
+ cmd += 1
+ case 4:
+ cmd += 2
+ case 8:
+ cmd += 3
+ }
+
+ err := binary.Write(m.output, binary.BigEndian, cmd)
+ if err != nil {
+ return err
+ }
+ err = m.write(m.pos, posSize)
+ if err != nil {
+ return err
+ }
+ err = m.write(m.len, lenSize)
+ if err != nil {
+ return err
+ }
+ case MATCH_KIND_LITERAL:
+ cmd = OP_LITERAL_N1
+ switch lenSize {
+ case 1:
+ cmd = OP_LITERAL_N1
+ case 2:
+ cmd = OP_LITERAL_N2
+ case 4:
+ cmd = OP_LITERAL_N4
+ case 8:
+ cmd = OP_LITERAL_N8
+ }
+
+ err := binary.Write(m.output, binary.BigEndian, cmd)
+ if err != nil {
+ return err
+ }
+ err = m.write(m.len, lenSize)
+ if err != nil {
+ return err
+ }
+ m.output.Write(m.lit)
+ m.lit = []byte{}
+ }
+ m.pos = 0
+ m.len = 0
+ return nil
+}
+
+func (m *match) add(kind matchKind, pos, len uint64) error {
+ if len != 0 && m.kind != kind {
+ err := m.flush()
+ if err != nil {
+ return err
+ }
+ }
+
+ m.kind = kind
+
+ switch kind {
+ case MATCH_KIND_LITERAL:
+ m.lit = append(m.lit, byte(pos))
+ m.len += 1
+ case MATCH_KIND_COPY:
+ m.lit = []byte{}
+ if m.pos+m.len != pos {
+ err := m.flush()
+ if err != nil {
+ return err
+ }
+ m.pos = pos
+ m.len = len
+ } else {
+ m.len += len
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/resin-os/librsync-go/op.go b/vendor/github.com/resin-os/librsync-go/op.go
new file mode 100644
index 0000000..38934d5
--- /dev/null
+++ b/vendor/github.com/resin-os/librsync-go/op.go
@@ -0,0 +1,539 @@
+package librsync
+
+type Op uint8
+
+type OpKind uint16
+
+const (
+ KIND_END OpKind = iota + 1000
+ KIND_LITERAL
+ KIND_SIGNATURE
+ KIND_COPY
+ KIND_CHECKSUM
+ KIND_RESERVED
+)
+
+type Command struct {
+ Kind OpKind
+ Immediate uint8
+ Len1 uint8
+ Len2 uint8
+}
+
+const (
+ OP_END Op = iota
+ OP_LITERAL_1
+ OP_LITERAL_2
+ OP_LITERAL_3
+ OP_LITERAL_4
+ OP_LITERAL_5
+ OP_LITERAL_6
+ OP_LITERAL_7
+ OP_LITERAL_8
+ OP_LITERAL_9
+ OP_LITERAL_10
+ OP_LITERAL_11
+ OP_LITERAL_12
+ OP_LITERAL_13
+ OP_LITERAL_14
+ OP_LITERAL_15
+ OP_LITERAL_16
+ OP_LITERAL_17
+ OP_LITERAL_18
+ OP_LITERAL_19
+ OP_LITERAL_20
+ OP_LITERAL_21
+ OP_LITERAL_22
+ OP_LITERAL_23
+ OP_LITERAL_24
+ OP_LITERAL_25
+ OP_LITERAL_26
+ OP_LITERAL_27
+ OP_LITERAL_28
+ OP_LITERAL_29
+ OP_LITERAL_30
+ OP_LITERAL_31
+ OP_LITERAL_32
+ OP_LITERAL_33
+ OP_LITERAL_34
+ OP_LITERAL_35
+ OP_LITERAL_36
+ OP_LITERAL_37
+ OP_LITERAL_38
+ OP_LITERAL_39
+ OP_LITERAL_40
+ OP_LITERAL_41
+ OP_LITERAL_42
+ OP_LITERAL_43
+ OP_LITERAL_44
+ OP_LITERAL_45
+ OP_LITERAL_46
+ OP_LITERAL_47
+ OP_LITERAL_48
+ OP_LITERAL_49
+ OP_LITERAL_50
+ OP_LITERAL_51
+ OP_LITERAL_52
+ OP_LITERAL_53
+ OP_LITERAL_54
+ OP_LITERAL_55
+ OP_LITERAL_56
+ OP_LITERAL_57
+ OP_LITERAL_58
+ OP_LITERAL_59
+ OP_LITERAL_60
+ OP_LITERAL_61
+ OP_LITERAL_62
+ OP_LITERAL_63
+ OP_LITERAL_64
+ OP_LITERAL_N1
+ OP_LITERAL_N2
+ OP_LITERAL_N4
+ OP_LITERAL_N8
+ OP_COPY_N1_N1
+ OP_COPY_N1_N2
+ OP_COPY_N1_N4
+ OP_COPY_N1_N8
+ OP_COPY_N2_N1
+ OP_COPY_N2_N2
+ OP_COPY_N2_N4
+ OP_COPY_N2_N8
+ OP_COPY_N4_N1
+ OP_COPY_N4_N2
+ OP_COPY_N4_N4
+ OP_COPY_N4_N8
+ OP_COPY_N8_N1
+ OP_COPY_N8_N2
+ OP_COPY_N8_N4
+ OP_COPY_N8_N8
+ OP_RESERVED_85
+ OP_RESERVED_86
+ OP_RESERVED_87
+ OP_RESERVED_88
+ OP_RESERVED_89
+ OP_RESERVED_90
+ OP_RESERVED_91
+ OP_RESERVED_92
+ OP_RESERVED_93
+ OP_RESERVED_94
+ OP_RESERVED_95
+ OP_RESERVED_96
+ OP_RESERVED_97
+ OP_RESERVED_98
+ OP_RESERVED_99
+ OP_RESERVED_100
+ OP_RESERVED_101
+ OP_RESERVED_102
+ OP_RESERVED_103
+ OP_RESERVED_104
+ OP_RESERVED_105
+ OP_RESERVED_106
+ OP_RESERVED_107
+ OP_RESERVED_108
+ OP_RESERVED_109
+ OP_RESERVED_110
+ OP_RESERVED_111
+ OP_RESERVED_112
+ OP_RESERVED_113
+ OP_RESERVED_114
+ OP_RESERVED_115
+ OP_RESERVED_116
+ OP_RESERVED_117
+ OP_RESERVED_118
+ OP_RESERVED_119
+ OP_RESERVED_120
+ OP_RESERVED_121
+ OP_RESERVED_122
+ OP_RESERVED_123
+ OP_RESERVED_124
+ OP_RESERVED_125
+ OP_RESERVED_126
+ OP_RESERVED_127
+ OP_RESERVED_128
+ OP_RESERVED_129
+ OP_RESERVED_130
+ OP_RESERVED_131
+ OP_RESERVED_132
+ OP_RESERVED_133
+ OP_RESERVED_134
+ OP_RESERVED_135
+ OP_RESERVED_136
+ OP_RESERVED_137
+ OP_RESERVED_138
+ OP_RESERVED_139
+ OP_RESERVED_140
+ OP_RESERVED_141
+ OP_RESERVED_142
+ OP_RESERVED_143
+ OP_RESERVED_144
+ OP_RESERVED_145
+ OP_RESERVED_146
+ OP_RESERVED_147
+ OP_RESERVED_148
+ OP_RESERVED_149
+ OP_RESERVED_150
+ OP_RESERVED_151
+ OP_RESERVED_152
+ OP_RESERVED_153
+ OP_RESERVED_154
+ OP_RESERVED_155
+ OP_RESERVED_156
+ OP_RESERVED_157
+ OP_RESERVED_158
+ OP_RESERVED_159
+ OP_RESERVED_160
+ OP_RESERVED_161
+ OP_RESERVED_162
+ OP_RESERVED_163
+ OP_RESERVED_164
+ OP_RESERVED_165
+ OP_RESERVED_166
+ OP_RESERVED_167
+ OP_RESERVED_168
+ OP_RESERVED_169
+ OP_RESERVED_170
+ OP_RESERVED_171
+ OP_RESERVED_172
+ OP_RESERVED_173
+ OP_RESERVED_174
+ OP_RESERVED_175
+ OP_RESERVED_176
+ OP_RESERVED_177
+ OP_RESERVED_178
+ OP_RESERVED_179
+ OP_RESERVED_180
+ OP_RESERVED_181
+ OP_RESERVED_182
+ OP_RESERVED_183
+ OP_RESERVED_184
+ OP_RESERVED_185
+ OP_RESERVED_186
+ OP_RESERVED_187
+ OP_RESERVED_188
+ OP_RESERVED_189
+ OP_RESERVED_190
+ OP_RESERVED_191
+ OP_RESERVED_192
+ OP_RESERVED_193
+ OP_RESERVED_194
+ OP_RESERVED_195
+ OP_RESERVED_196
+ OP_RESERVED_197
+ OP_RESERVED_198
+ OP_RESERVED_199
+ OP_RESERVED_200
+ OP_RESERVED_201
+ OP_RESERVED_202
+ OP_RESERVED_203
+ OP_RESERVED_204
+ OP_RESERVED_205
+ OP_RESERVED_206
+ OP_RESERVED_207
+ OP_RESERVED_208
+ OP_RESERVED_209
+ OP_RESERVED_210
+ OP_RESERVED_211
+ OP_RESERVED_212
+ OP_RESERVED_213
+ OP_RESERVED_214
+ OP_RESERVED_215
+ OP_RESERVED_216
+ OP_RESERVED_217
+ OP_RESERVED_218
+ OP_RESERVED_219
+ OP_RESERVED_220
+ OP_RESERVED_221
+ OP_RESERVED_222
+ OP_RESERVED_223
+ OP_RESERVED_224
+ OP_RESERVED_225
+ OP_RESERVED_226
+ OP_RESERVED_227
+ OP_RESERVED_228
+ OP_RESERVED_229
+ OP_RESERVED_230
+ OP_RESERVED_231
+ OP_RESERVED_232
+ OP_RESERVED_233
+ OP_RESERVED_234
+ OP_RESERVED_235
+ OP_RESERVED_236
+ OP_RESERVED_237
+ OP_RESERVED_238
+ OP_RESERVED_239
+ OP_RESERVED_240
+ OP_RESERVED_241
+ OP_RESERVED_242
+ OP_RESERVED_243
+ OP_RESERVED_244
+ OP_RESERVED_245
+ OP_RESERVED_246
+ OP_RESERVED_247
+ OP_RESERVED_248
+ OP_RESERVED_249
+ OP_RESERVED_250
+ OP_RESERVED_251
+ OP_RESERVED_252
+ OP_RESERVED_253
+ OP_RESERVED_254
+ OP_RESERVED_255
+)
+
+var op2cmd = []Command{
+ Command{KIND_END, 0, 0, 0}, /* OP_END = 0 */
+ Command{KIND_LITERAL, 1, 0, 0}, /* OP_LITERAL_1 = 0x1 */
+ Command{KIND_LITERAL, 2, 0, 0}, /* OP_LITERAL_2 = 0x2 */
+ Command{KIND_LITERAL, 3, 0, 0}, /* OP_LITERAL_3 = 0x3 */
+ Command{KIND_LITERAL, 4, 0, 0}, /* OP_LITERAL_4 = 0x4 */
+ Command{KIND_LITERAL, 5, 0, 0}, /* OP_LITERAL_5 = 0x5 */
+ Command{KIND_LITERAL, 6, 0, 0}, /* OP_LITERAL_6 = 0x6 */
+ Command{KIND_LITERAL, 7, 0, 0}, /* OP_LITERAL_7 = 0x7 */
+ Command{KIND_LITERAL, 8, 0, 0}, /* OP_LITERAL_8 = 0x8 */
+ Command{KIND_LITERAL, 9, 0, 0}, /* OP_LITERAL_9 = 0x9 */
+ Command{KIND_LITERAL, 10, 0, 0}, /* OP_LITERAL_10 = 0xa */
+ Command{KIND_LITERAL, 11, 0, 0}, /* OP_LITERAL_11 = 0xb */
+ Command{KIND_LITERAL, 12, 0, 0}, /* OP_LITERAL_12 = 0xc */
+ Command{KIND_LITERAL, 13, 0, 0}, /* OP_LITERAL_13 = 0xd */
+ Command{KIND_LITERAL, 14, 0, 0}, /* OP_LITERAL_14 = 0xe */
+ Command{KIND_LITERAL, 15, 0, 0}, /* OP_LITERAL_15 = 0xf */
+ Command{KIND_LITERAL, 16, 0, 0}, /* OP_LITERAL_16 = 0x10 */
+ Command{KIND_LITERAL, 17, 0, 0}, /* OP_LITERAL_17 = 0x11 */
+ Command{KIND_LITERAL, 18, 0, 0}, /* OP_LITERAL_18 = 0x12 */
+ Command{KIND_LITERAL, 19, 0, 0}, /* OP_LITERAL_19 = 0x13 */
+ Command{KIND_LITERAL, 20, 0, 0}, /* OP_LITERAL_20 = 0x14 */
+ Command{KIND_LITERAL, 21, 0, 0}, /* OP_LITERAL_21 = 0x15 */
+ Command{KIND_LITERAL, 22, 0, 0}, /* OP_LITERAL_22 = 0x16 */
+ Command{KIND_LITERAL, 23, 0, 0}, /* OP_LITERAL_23 = 0x17 */
+ Command{KIND_LITERAL, 24, 0, 0}, /* OP_LITERAL_24 = 0x18 */
+ Command{KIND_LITERAL, 25, 0, 0}, /* OP_LITERAL_25 = 0x19 */
+ Command{KIND_LITERAL, 26, 0, 0}, /* OP_LITERAL_26 = 0x1a */
+ Command{KIND_LITERAL, 27, 0, 0}, /* OP_LITERAL_27 = 0x1b */
+ Command{KIND_LITERAL, 28, 0, 0}, /* OP_LITERAL_28 = 0x1c */
+ Command{KIND_LITERAL, 29, 0, 0}, /* OP_LITERAL_29 = 0x1d */
+ Command{KIND_LITERAL, 30, 0, 0}, /* OP_LITERAL_30 = 0x1e */
+ Command{KIND_LITERAL, 31, 0, 0}, /* OP_LITERAL_31 = 0x1f */
+ Command{KIND_LITERAL, 32, 0, 0}, /* OP_LITERAL_32 = 0x20 */
+ Command{KIND_LITERAL, 33, 0, 0}, /* OP_LITERAL_33 = 0x21 */
+ Command{KIND_LITERAL, 34, 0, 0}, /* OP_LITERAL_34 = 0x22 */
+ Command{KIND_LITERAL, 35, 0, 0}, /* OP_LITERAL_35 = 0x23 */
+ Command{KIND_LITERAL, 36, 0, 0}, /* OP_LITERAL_36 = 0x24 */
+ Command{KIND_LITERAL, 37, 0, 0}, /* OP_LITERAL_37 = 0x25 */
+ Command{KIND_LITERAL, 38, 0, 0}, /* OP_LITERAL_38 = 0x26 */
+ Command{KIND_LITERAL, 39, 0, 0}, /* OP_LITERAL_39 = 0x27 */
+ Command{KIND_LITERAL, 40, 0, 0}, /* OP_LITERAL_40 = 0x28 */
+ Command{KIND_LITERAL, 41, 0, 0}, /* OP_LITERAL_41 = 0x29 */
+ Command{KIND_LITERAL, 42, 0, 0}, /* OP_LITERAL_42 = 0x2a */
+ Command{KIND_LITERAL, 43, 0, 0}, /* OP_LITERAL_43 = 0x2b */
+ Command{KIND_LITERAL, 44, 0, 0}, /* OP_LITERAL_44 = 0x2c */
+ Command{KIND_LITERAL, 45, 0, 0}, /* OP_LITERAL_45 = 0x2d */
+ Command{KIND_LITERAL, 46, 0, 0}, /* OP_LITERAL_46 = 0x2e */
+ Command{KIND_LITERAL, 47, 0, 0}, /* OP_LITERAL_47 = 0x2f */
+ Command{KIND_LITERAL, 48, 0, 0}, /* OP_LITERAL_48 = 0x30 */
+ Command{KIND_LITERAL, 49, 0, 0}, /* OP_LITERAL_49 = 0x31 */
+ Command{KIND_LITERAL, 50, 0, 0}, /* OP_LITERAL_50 = 0x32 */
+ Command{KIND_LITERAL, 51, 0, 0}, /* OP_LITERAL_51 = 0x33 */
+ Command{KIND_LITERAL, 52, 0, 0}, /* OP_LITERAL_52 = 0x34 */
+ Command{KIND_LITERAL, 53, 0, 0}, /* OP_LITERAL_53 = 0x35 */
+ Command{KIND_LITERAL, 54, 0, 0}, /* OP_LITERAL_54 = 0x36 */
+ Command{KIND_LITERAL, 55, 0, 0}, /* OP_LITERAL_55 = 0x37 */
+ Command{KIND_LITERAL, 56, 0, 0}, /* OP_LITERAL_56 = 0x38 */
+ Command{KIND_LITERAL, 57, 0, 0}, /* OP_LITERAL_57 = 0x39 */
+ Command{KIND_LITERAL, 58, 0, 0}, /* OP_LITERAL_58 = 0x3a */
+ Command{KIND_LITERAL, 59, 0, 0}, /* OP_LITERAL_59 = 0x3b */
+ Command{KIND_LITERAL, 60, 0, 0}, /* OP_LITERAL_60 = 0x3c */
+ Command{KIND_LITERAL, 61, 0, 0}, /* OP_LITERAL_61 = 0x3d */
+ Command{KIND_LITERAL, 62, 0, 0}, /* OP_LITERAL_62 = 0x3e */
+ Command{KIND_LITERAL, 63, 0, 0}, /* OP_LITERAL_63 = 0x3f */
+ Command{KIND_LITERAL, 64, 0, 0}, /* OP_LITERAL_64 = 0x40 */
+ Command{KIND_LITERAL, 0, 1, 0}, /* OP_LITERAL_N1 = 0x41 */
+ Command{KIND_LITERAL, 0, 2, 0}, /* OP_LITERAL_N2 = 0x42 */
+ Command{KIND_LITERAL, 0, 4, 0}, /* OP_LITERAL_N4 = 0x43 */
+ Command{KIND_LITERAL, 0, 8, 0}, /* OP_LITERAL_N8 = 0x44 */
+ Command{KIND_COPY, 0, 1, 1}, /* OP_COPY_N1_N1 = 0x45 */
+ Command{KIND_COPY, 0, 1, 2}, /* OP_COPY_N1_N2 = 0x46 */
+ Command{KIND_COPY, 0, 1, 4}, /* OP_COPY_N1_N4 = 0x47 */
+ Command{KIND_COPY, 0, 1, 8}, /* OP_COPY_N1_N8 = 0x48 */
+ Command{KIND_COPY, 0, 2, 1}, /* OP_COPY_N2_N1 = 0x49 */
+ Command{KIND_COPY, 0, 2, 2}, /* OP_COPY_N2_N2 = 0x4a */
+ Command{KIND_COPY, 0, 2, 4}, /* OP_COPY_N2_N4 = 0x4b */
+ Command{KIND_COPY, 0, 2, 8}, /* OP_COPY_N2_N8 = 0x4c */
+ Command{KIND_COPY, 0, 4, 1}, /* OP_COPY_N4_N1 = 0x4d */
+ Command{KIND_COPY, 0, 4, 2}, /* OP_COPY_N4_N2 = 0x4e */
+ Command{KIND_COPY, 0, 4, 4}, /* OP_COPY_N4_N4 = 0x4f */
+ Command{KIND_COPY, 0, 4, 8}, /* OP_COPY_N4_N8 = 0x50 */
+ Command{KIND_COPY, 0, 8, 1}, /* OP_COPY_N8_N1 = 0x51 */
+ Command{KIND_COPY, 0, 8, 2}, /* OP_COPY_N8_N2 = 0x52 */
+ Command{KIND_COPY, 0, 8, 4}, /* OP_COPY_N8_N4 = 0x53 */
+ Command{KIND_COPY, 0, 8, 8}, /* OP_COPY_N8_N8 = 0x54 */
+ Command{KIND_RESERVED, 85, 0, 0}, /* OP_RESERVED_85 = 0x55 */
+ Command{KIND_RESERVED, 86, 0, 0}, /* OP_RESERVED_86 = 0x56 */
+ Command{KIND_RESERVED, 87, 0, 0}, /* OP_RESERVED_87 = 0x57 */
+ Command{KIND_RESERVED, 88, 0, 0}, /* OP_RESERVED_88 = 0x58 */
+ Command{KIND_RESERVED, 89, 0, 0}, /* OP_RESERVED_89 = 0x59 */
+ Command{KIND_RESERVED, 90, 0, 0}, /* OP_RESERVED_90 = 0x5a */
+ Command{KIND_RESERVED, 91, 0, 0}, /* OP_RESERVED_91 = 0x5b */
+ Command{KIND_RESERVED, 92, 0, 0}, /* OP_RESERVED_92 = 0x5c */
+ Command{KIND_RESERVED, 93, 0, 0}, /* OP_RESERVED_93 = 0x5d */
+ Command{KIND_RESERVED, 94, 0, 0}, /* OP_RESERVED_94 = 0x5e */
+ Command{KIND_RESERVED, 95, 0, 0}, /* OP_RESERVED_95 = 0x5f */
+ Command{KIND_RESERVED, 96, 0, 0}, /* OP_RESERVED_96 = 0x60 */
+ Command{KIND_RESERVED, 97, 0, 0}, /* OP_RESERVED_97 = 0x61 */
+ Command{KIND_RESERVED, 98, 0, 0}, /* OP_RESERVED_98 = 0x62 */
+ Command{KIND_RESERVED, 99, 0, 0}, /* OP_RESERVED_99 = 0x63 */
+ Command{KIND_RESERVED, 100, 0, 0}, /* OP_RESERVED_100 = 0x64 */
+ Command{KIND_RESERVED, 101, 0, 0}, /* OP_RESERVED_101 = 0x65 */
+ Command{KIND_RESERVED, 102, 0, 0}, /* OP_RESERVED_102 = 0x66 */
+ Command{KIND_RESERVED, 103, 0, 0}, /* OP_RESERVED_103 = 0x67 */
+ Command{KIND_RESERVED, 104, 0, 0}, /* OP_RESERVED_104 = 0x68 */
+ Command{KIND_RESERVED, 105, 0, 0}, /* OP_RESERVED_105 = 0x69 */
+ Command{KIND_RESERVED, 106, 0, 0}, /* OP_RESERVED_106 = 0x6a */
+ Command{KIND_RESERVED, 107, 0, 0}, /* OP_RESERVED_107 = 0x6b */
+ Command{KIND_RESERVED, 108, 0, 0}, /* OP_RESERVED_108 = 0x6c */
+ Command{KIND_RESERVED, 109, 0, 0}, /* OP_RESERVED_109 = 0x6d */
+ Command{KIND_RESERVED, 110, 0, 0}, /* OP_RESERVED_110 = 0x6e */
+ Command{KIND_RESERVED, 111, 0, 0}, /* OP_RESERVED_111 = 0x6f */
+ Command{KIND_RESERVED, 112, 0, 0}, /* OP_RESERVED_112 = 0x70 */
+ Command{KIND_RESERVED, 113, 0, 0}, /* OP_RESERVED_113 = 0x71 */
+ Command{KIND_RESERVED, 114, 0, 0}, /* OP_RESERVED_114 = 0x72 */
+ Command{KIND_RESERVED, 115, 0, 0}, /* OP_RESERVED_115 = 0x73 */
+ Command{KIND_RESERVED, 116, 0, 0}, /* OP_RESERVED_116 = 0x74 */
+ Command{KIND_RESERVED, 117, 0, 0}, /* OP_RESERVED_117 = 0x75 */
+ Command{KIND_RESERVED, 118, 0, 0}, /* OP_RESERVED_118 = 0x76 */
+ Command{KIND_RESERVED, 119, 0, 0}, /* OP_RESERVED_119 = 0x77 */
+ Command{KIND_RESERVED, 120, 0, 0}, /* OP_RESERVED_120 = 0x78 */
+ Command{KIND_RESERVED, 121, 0, 0}, /* OP_RESERVED_121 = 0x79 */
+ Command{KIND_RESERVED, 122, 0, 0}, /* OP_RESERVED_122 = 0x7a */
+ Command{KIND_RESERVED, 123, 0, 0}, /* OP_RESERVED_123 = 0x7b */
+ Command{KIND_RESERVED, 124, 0, 0}, /* OP_RESERVED_124 = 0x7c */
+ Command{KIND_RESERVED, 125, 0, 0}, /* OP_RESERVED_125 = 0x7d */
+ Command{KIND_RESERVED, 126, 0, 0}, /* OP_RESERVED_126 = 0x7e */
+ Command{KIND_RESERVED, 127, 0, 0}, /* OP_RESERVED_127 = 0x7f */
+ Command{KIND_RESERVED, 128, 0, 0}, /* OP_RESERVED_128 = 0x80 */
+ Command{KIND_RESERVED, 129, 0, 0}, /* OP_RESERVED_129 = 0x81 */
+ Command{KIND_RESERVED, 130, 0, 0}, /* OP_RESERVED_130 = 0x82 */
+ Command{KIND_RESERVED, 131, 0, 0}, /* OP_RESERVED_131 = 0x83 */
+ Command{KIND_RESERVED, 132, 0, 0}, /* OP_RESERVED_132 = 0x84 */
+ Command{KIND_RESERVED, 133, 0, 0}, /* OP_RESERVED_133 = 0x85 */
+ Command{KIND_RESERVED, 134, 0, 0}, /* OP_RESERVED_134 = 0x86 */
+ Command{KIND_RESERVED, 135, 0, 0}, /* OP_RESERVED_135 = 0x87 */
+ Command{KIND_RESERVED, 136, 0, 0}, /* OP_RESERVED_136 = 0x88 */
+ Command{KIND_RESERVED, 137, 0, 0}, /* OP_RESERVED_137 = 0x89 */
+ Command{KIND_RESERVED, 138, 0, 0}, /* OP_RESERVED_138 = 0x8a */
+ Command{KIND_RESERVED, 139, 0, 0}, /* OP_RESERVED_139 = 0x8b */
+ Command{KIND_RESERVED, 140, 0, 0}, /* OP_RESERVED_140 = 0x8c */
+ Command{KIND_RESERVED, 141, 0, 0}, /* OP_RESERVED_141 = 0x8d */
+ Command{KIND_RESERVED, 142, 0, 0}, /* OP_RESERVED_142 = 0x8e */
+ Command{KIND_RESERVED, 143, 0, 0}, /* OP_RESERVED_143 = 0x8f */
+ Command{KIND_RESERVED, 144, 0, 0}, /* OP_RESERVED_144 = 0x90 */
+ Command{KIND_RESERVED, 145, 0, 0}, /* OP_RESERVED_145 = 0x91 */
+ Command{KIND_RESERVED, 146, 0, 0}, /* OP_RESERVED_146 = 0x92 */
+ Command{KIND_RESERVED, 147, 0, 0}, /* OP_RESERVED_147 = 0x93 */
+ Command{KIND_RESERVED, 148, 0, 0}, /* OP_RESERVED_148 = 0x94 */
+ Command{KIND_RESERVED, 149, 0, 0}, /* OP_RESERVED_149 = 0x95 */
+ Command{KIND_RESERVED, 150, 0, 0}, /* OP_RESERVED_150 = 0x96 */
+ Command{KIND_RESERVED, 151, 0, 0}, /* OP_RESERVED_151 = 0x97 */
+ Command{KIND_RESERVED, 152, 0, 0}, /* OP_RESERVED_152 = 0x98 */
+ Command{KIND_RESERVED, 153, 0, 0}, /* OP_RESERVED_153 = 0x99 */
+ Command{KIND_RESERVED, 154, 0, 0}, /* OP_RESERVED_154 = 0x9a */
+ Command{KIND_RESERVED, 155, 0, 0}, /* OP_RESERVED_155 = 0x9b */
+ Command{KIND_RESERVED, 156, 0, 0}, /* OP_RESERVED_156 = 0x9c */
+ Command{KIND_RESERVED, 157, 0, 0}, /* OP_RESERVED_157 = 0x9d */
+ Command{KIND_RESERVED, 158, 0, 0}, /* OP_RESERVED_158 = 0x9e */
+ Command{KIND_RESERVED, 159, 0, 0}, /* OP_RESERVED_159 = 0x9f */
+ Command{KIND_RESERVED, 160, 0, 0}, /* OP_RESERVED_160 = 0xa0 */
+ Command{KIND_RESERVED, 161, 0, 0}, /* OP_RESERVED_161 = 0xa1 */
+ Command{KIND_RESERVED, 162, 0, 0}, /* OP_RESERVED_162 = 0xa2 */
+ Command{KIND_RESERVED, 163, 0, 0}, /* OP_RESERVED_163 = 0xa3 */
+ Command{KIND_RESERVED, 164, 0, 0}, /* OP_RESERVED_164 = 0xa4 */
+ Command{KIND_RESERVED, 165, 0, 0}, /* OP_RESERVED_165 = 0xa5 */
+ Command{KIND_RESERVED, 166, 0, 0}, /* OP_RESERVED_166 = 0xa6 */
+ Command{KIND_RESERVED, 167, 0, 0}, /* OP_RESERVED_167 = 0xa7 */
+ Command{KIND_RESERVED, 168, 0, 0}, /* OP_RESERVED_168 = 0xa8 */
+ Command{KIND_RESERVED, 169, 0, 0}, /* OP_RESERVED_169 = 0xa9 */
+ Command{KIND_RESERVED, 170, 0, 0}, /* OP_RESERVED_170 = 0xaa */
+ Command{KIND_RESERVED, 171, 0, 0}, /* OP_RESERVED_171 = 0xab */
+ Command{KIND_RESERVED, 172, 0, 0}, /* OP_RESERVED_172 = 0xac */
+ Command{KIND_RESERVED, 173, 0, 0}, /* OP_RESERVED_173 = 0xad */
+ Command{KIND_RESERVED, 174, 0, 0}, /* OP_RESERVED_174 = 0xae */
+ Command{KIND_RESERVED, 175, 0, 0}, /* OP_RESERVED_175 = 0xaf */
+ Command{KIND_RESERVED, 176, 0, 0}, /* OP_RESERVED_176 = 0xb0 */
+ Command{KIND_RESERVED, 177, 0, 0}, /* OP_RESERVED_177 = 0xb1 */
+ Command{KIND_RESERVED, 178, 0, 0}, /* OP_RESERVED_178 = 0xb2 */
+ Command{KIND_RESERVED, 179, 0, 0}, /* OP_RESERVED_179 = 0xb3 */
+ Command{KIND_RESERVED, 180, 0, 0}, /* OP_RESERVED_180 = 0xb4 */
+ Command{KIND_RESERVED, 181, 0, 0}, /* OP_RESERVED_181 = 0xb5 */
+ Command{KIND_RESERVED, 182, 0, 0}, /* OP_RESERVED_182 = 0xb6 */
+ Command{KIND_RESERVED, 183, 0, 0}, /* OP_RESERVED_183 = 0xb7 */
+ Command{KIND_RESERVED, 184, 0, 0}, /* OP_RESERVED_184 = 0xb8 */
+ Command{KIND_RESERVED, 185, 0, 0}, /* OP_RESERVED_185 = 0xb9 */
+ Command{KIND_RESERVED, 186, 0, 0}, /* OP_RESERVED_186 = 0xba */
+ Command{KIND_RESERVED, 187, 0, 0}, /* OP_RESERVED_187 = 0xbb */
+ Command{KIND_RESERVED, 188, 0, 0}, /* OP_RESERVED_188 = 0xbc */
+ Command{KIND_RESERVED, 189, 0, 0}, /* OP_RESERVED_189 = 0xbd */
+ Command{KIND_RESERVED, 190, 0, 0}, /* OP_RESERVED_190 = 0xbe */
+ Command{KIND_RESERVED, 191, 0, 0}, /* OP_RESERVED_191 = 0xbf */
+ Command{KIND_RESERVED, 192, 0, 0}, /* OP_RESERVED_192 = 0xc0 */
+ Command{KIND_RESERVED, 193, 0, 0}, /* OP_RESERVED_193 = 0xc1 */
+ Command{KIND_RESERVED, 194, 0, 0}, /* OP_RESERVED_194 = 0xc2 */
+ Command{KIND_RESERVED, 195, 0, 0}, /* OP_RESERVED_195 = 0xc3 */
+ Command{KIND_RESERVED, 196, 0, 0}, /* OP_RESERVED_196 = 0xc4 */
+ Command{KIND_RESERVED, 197, 0, 0}, /* OP_RESERVED_197 = 0xc5 */
+ Command{KIND_RESERVED, 198, 0, 0}, /* OP_RESERVED_198 = 0xc6 */
+ Command{KIND_RESERVED, 199, 0, 0}, /* OP_RESERVED_199 = 0xc7 */
+ Command{KIND_RESERVED, 200, 0, 0}, /* OP_RESERVED_200 = 0xc8 */
+ Command{KIND_RESERVED, 201, 0, 0}, /* OP_RESERVED_201 = 0xc9 */
+ Command{KIND_RESERVED, 202, 0, 0}, /* OP_RESERVED_202 = 0xca */
+ Command{KIND_RESERVED, 203, 0, 0}, /* OP_RESERVED_203 = 0xcb */
+ Command{KIND_RESERVED, 204, 0, 0}, /* OP_RESERVED_204 = 0xcc */
+ Command{KIND_RESERVED, 205, 0, 0}, /* OP_RESERVED_205 = 0xcd */
+ Command{KIND_RESERVED, 206, 0, 0}, /* OP_RESERVED_206 = 0xce */
+ Command{KIND_RESERVED, 207, 0, 0}, /* OP_RESERVED_207 = 0xcf */
+ Command{KIND_RESERVED, 208, 0, 0}, /* OP_RESERVED_208 = 0xd0 */
+ Command{KIND_RESERVED, 209, 0, 0}, /* OP_RESERVED_209 = 0xd1 */
+ Command{KIND_RESERVED, 210, 0, 0}, /* OP_RESERVED_210 = 0xd2 */
+ Command{KIND_RESERVED, 211, 0, 0}, /* OP_RESERVED_211 = 0xd3 */
+ Command{KIND_RESERVED, 212, 0, 0}, /* OP_RESERVED_212 = 0xd4 */
+ Command{KIND_RESERVED, 213, 0, 0}, /* OP_RESERVED_213 = 0xd5 */
+ Command{KIND_RESERVED, 214, 0, 0}, /* OP_RESERVED_214 = 0xd6 */
+ Command{KIND_RESERVED, 215, 0, 0}, /* OP_RESERVED_215 = 0xd7 */
+ Command{KIND_RESERVED, 216, 0, 0}, /* OP_RESERVED_216 = 0xd8 */
+ Command{KIND_RESERVED, 217, 0, 0}, /* OP_RESERVED_217 = 0xd9 */
+ Command{KIND_RESERVED, 218, 0, 0}, /* OP_RESERVED_218 = 0xda */
+ Command{KIND_RESERVED, 219, 0, 0}, /* OP_RESERVED_219 = 0xdb */
+ Command{KIND_RESERVED, 220, 0, 0}, /* OP_RESERVED_220 = 0xdc */
+ Command{KIND_RESERVED, 221, 0, 0}, /* OP_RESERVED_221 = 0xdd */
+ Command{KIND_RESERVED, 222, 0, 0}, /* OP_RESERVED_222 = 0xde */
+ Command{KIND_RESERVED, 223, 0, 0}, /* OP_RESERVED_223 = 0xdf */
+ Command{KIND_RESERVED, 224, 0, 0}, /* OP_RESERVED_224 = 0xe0 */
+ Command{KIND_RESERVED, 225, 0, 0}, /* OP_RESERVED_225 = 0xe1 */
+ Command{KIND_RESERVED, 226, 0, 0}, /* OP_RESERVED_226 = 0xe2 */
+ Command{KIND_RESERVED, 227, 0, 0}, /* OP_RESERVED_227 = 0xe3 */
+ Command{KIND_RESERVED, 228, 0, 0}, /* OP_RESERVED_228 = 0xe4 */
+ Command{KIND_RESERVED, 229, 0, 0}, /* OP_RESERVED_229 = 0xe5 */
+ Command{KIND_RESERVED, 230, 0, 0}, /* OP_RESERVED_230 = 0xe6 */
+ Command{KIND_RESERVED, 231, 0, 0}, /* OP_RESERVED_231 = 0xe7 */
+ Command{KIND_RESERVED, 232, 0, 0}, /* OP_RESERVED_232 = 0xe8 */
+ Command{KIND_RESERVED, 233, 0, 0}, /* OP_RESERVED_233 = 0xe9 */
+ Command{KIND_RESERVED, 234, 0, 0}, /* OP_RESERVED_234 = 0xea */
+ Command{KIND_RESERVED, 235, 0, 0}, /* OP_RESERVED_235 = 0xeb */
+ Command{KIND_RESERVED, 236, 0, 0}, /* OP_RESERVED_236 = 0xec */
+ Command{KIND_RESERVED, 237, 0, 0}, /* OP_RESERVED_237 = 0xed */
+ Command{KIND_RESERVED, 238, 0, 0}, /* OP_RESERVED_238 = 0xee */
+ Command{KIND_RESERVED, 239, 0, 0}, /* OP_RESERVED_239 = 0xef */
+ Command{KIND_RESERVED, 240, 0, 0}, /* OP_RESERVED_240 = 0xf0 */
+ Command{KIND_RESERVED, 241, 0, 0}, /* OP_RESERVED_241 = 0xf1 */
+ Command{KIND_RESERVED, 242, 0, 0}, /* OP_RESERVED_242 = 0xf2 */
+ Command{KIND_RESERVED, 243, 0, 0}, /* OP_RESERVED_243 = 0xf3 */
+ Command{KIND_RESERVED, 244, 0, 0}, /* OP_RESERVED_244 = 0xf4 */
+ Command{KIND_RESERVED, 245, 0, 0}, /* OP_RESERVED_245 = 0xf5 */
+ Command{KIND_RESERVED, 246, 0, 0}, /* OP_RESERVED_246 = 0xf6 */
+ Command{KIND_RESERVED, 247, 0, 0}, /* OP_RESERVED_247 = 0xf7 */
+ Command{KIND_RESERVED, 248, 0, 0}, /* OP_RESERVED_248 = 0xf8 */
+ Command{KIND_RESERVED, 249, 0, 0}, /* OP_RESERVED_249 = 0xf9 */
+ Command{KIND_RESERVED, 250, 0, 0}, /* OP_RESERVED_250 = 0xfa */
+ Command{KIND_RESERVED, 251, 0, 0}, /* OP_RESERVED_251 = 0xfb */
+ Command{KIND_RESERVED, 252, 0, 0}, /* OP_RESERVED_252 = 0xfc */
+ Command{KIND_RESERVED, 253, 0, 0}, /* OP_RESERVED_253 = 0xfd */
+ Command{KIND_RESERVED, 254, 0, 0}, /* OP_RESERVED_254 = 0xfe */
+ Command{KIND_RESERVED, 255, 0, 0}, /* OP_RESERVED_255 = 0xff */
+}
diff --git a/vendor/github.com/resin-os/librsync-go/patch.go b/vendor/github.com/resin-os/librsync-go/patch.go
new file mode 100644
index 0000000..690a884
--- /dev/null
+++ b/vendor/github.com/resin-os/librsync-go/patch.go
@@ -0,0 +1,88 @@
+package librsync
+
+import (
+ "encoding/binary"
+ "fmt"
+ "io"
+)
+
+type MagicNumber uint32
+
+const (
+ DELTA_MAGIC MagicNumber = 0x72730236
+
+ // A signature file with MD4 signatures.
+ //
+ // Backward compatible with librsync < 1.0, but strongly deprecated because
+ // it creates a security vulnerability on files containing partly untrusted
+ // data. See <https://github.com/librsync/librsync/issues/5>.
+ MD4_SIG_MAGIC MagicNumber = 0x72730136
+
+ // A signature file using the BLAKE2 hash. Supported from librsync 1.0.
+ BLAKE2_SIG_MAGIC MagicNumber = 0x72730137
+)
+
+func readParam(r io.Reader, size uint8) int64 {
+ switch size {
+ case 1:
+ var tmp uint8
+ binary.Read(r, binary.BigEndian, &tmp)
+ return int64(tmp)
+ case 2:
+ var tmp uint16
+ binary.Read(r, binary.BigEndian, &tmp)
+ return int64(tmp)
+ case 4:
+ var tmp uint32
+ binary.Read(r, binary.BigEndian, &tmp)
+ return int64(tmp)
+ case 8:
+ var tmp int64
+ binary.Read(r, binary.BigEndian, &tmp)
+ return int64(tmp)
+ }
+ return 0
+}
+
+func Patch(base io.ReadSeeker, delta io.Reader, out io.Writer) error {
+ var magic MagicNumber
+
+ err := binary.Read(delta, binary.BigEndian, &magic)
+ if err != nil {
+ return err
+ }
+
+ if magic != DELTA_MAGIC {
+ return fmt.Errorf("Got magic number %x rather than expected value %x", magic, DELTA_MAGIC)
+ }
+
+ for {
+ var op Op
+ err := binary.Read(delta, binary.BigEndian, &op)
+ if err != nil {
+ return err
+ }
+ cmd := op2cmd[op]
+
+ var param1, param2 int64
+
+ if cmd.Len1 == 0 {
+ param1 = int64(cmd.Immediate)
+ } else {
+ param1 = readParam(delta, cmd.Len1)
+ param2 = readParam(delta, cmd.Len2)
+ }
+
+ switch cmd.Kind {
+ default:
+ return fmt.Errorf("Bogus command %x", cmd.Kind)
+ case KIND_LITERAL:
+ io.CopyN(out, delta, param1)
+ case KIND_COPY:
+ base.Seek(param1, io.SeekStart)
+ io.CopyN(out, base, param2)
+ case KIND_END:
+ return nil
+ }
+ }
+}
diff --git a/vendor/github.com/resin-os/librsync-go/rollsum.go b/vendor/github.com/resin-os/librsync-go/rollsum.go
new file mode 100644
index 0000000..83e9f3e
--- /dev/null
+++ b/vendor/github.com/resin-os/librsync-go/rollsum.go
@@ -0,0 +1,67 @@
+package librsync
+
+type Rollsum struct {
+ count uint64
+ s1, s2 uint16
+}
+
+const ROLLSUM_CHAR_OFFSET = 31
+
+func WeakChecksum(data []byte) uint32 {
+ var sum Rollsum
+ sum.Update(data)
+ return sum.Digest()
+}
+
+func NewRollsum() Rollsum {
+ return Rollsum{}
+}
+
+func (r *Rollsum) Update(p []byte) {
+ l := len(p)
+
+ for n := 0; n < l; {
+ if n+15 < l {
+ for i := 0; i < 16; i++ {
+ r.s1 += uint16(p[n+i])
+ r.s2 += r.s1
+ }
+ n += 16
+ } else {
+ r.s1 += uint16(p[n])
+ r.s2 += r.s1
+ n += 1
+ }
+ }
+
+ r.s1 += uint16(l * ROLLSUM_CHAR_OFFSET)
+ r.s2 += uint16(((l * (l + 1)) / 2) * ROLLSUM_CHAR_OFFSET)
+ r.count += uint64(l)
+}
+
+func (r *Rollsum) Rotate(out, in byte) {
+ r.s1 += uint16(in - out)
+ r.s2 += r.s1 - uint16(r.count)*(uint16(out)+uint16(ROLLSUM_CHAR_OFFSET))
+}
+
+func (r *Rollsum) Rollin(in byte) {
+ r.s1 += uint16(in) + uint16(ROLLSUM_CHAR_OFFSET)
+ r.s2 += r.s1
+ r.count += 1
+}
+
+func (r *Rollsum) Rollout(out byte) {
+ r.s1 -= uint16(out) + uint16(ROLLSUM_CHAR_OFFSET)
+ r.s2 -= uint16(r.count) * (uint16(out) + uint16(ROLLSUM_CHAR_OFFSET))
+ r.count -= 1
+}
+
+func (r *Rollsum) Digest() uint32 {
+ return (uint32(r.s2) << 16) | (uint32(r.s1) & 0xffff)
+}
+
+func (r *Rollsum) Reset() {
+ r.count = 0
+ r.s1 = 0
+ r.s2 = 0
+}
diff --git a/vendor/github.com/resin-os/librsync-go/signature.go b/vendor/github.com/resin-os/librsync-go/signature.go
new file mode 100644
index 0000000..2aca3b9
--- /dev/null
+++ b/vendor/github.com/resin-os/librsync-go/signature.go
@@ -0,0 +1,98 @@
+package librsync
+
+import (
+ "encoding/binary"
+ "fmt"
+ "io"
+
+ "golang.org/x/crypto/blake2b"
+ "golang.org/x/crypto/md4"
+)
+
+const (
+ BLAKE2_SUM_LENGTH = 32
+ MD4_SUM_LENGTH = 16
+)
+
+type SignatureType struct {
+ sigType MagicNumber
+ blockLen uint32
+ strongLen uint32
+ strongSigs [][]byte
+ weak2block map[uint32]int
+}
+
+func CalcStrongSum(data []byte, sigType MagicNumber, strongLen uint32) ([]byte, error) {
+ switch sigType {
+ case BLAKE2_SIG_MAGIC:
+ d := blake2b.Sum256(data)
+ return d[:strongLen], nil
+ case MD4_SIG_MAGIC:
+ d := md4.New()
+ d.Write(data)
+ return d.Sum(nil)[:strongLen], nil
+ }
+ return nil, fmt.Errorf("Invalid sigType %#x", sigType)
+}
+
+func Signature(input io.Reader, output io.Writer, blockLen, strongLen uint32, sigType MagicNumber) (*SignatureType, error) {
+ var maxStrongLen uint32
+
+ switch sigType {
+ case BLAKE2_SIG_MAGIC:
+ maxStrongLen = BLAKE2_SUM_LENGTH
+ case MD4_SIG_MAGIC:
+ maxStrongLen = MD4_SUM_LENGTH
+ default:
+ return nil, fmt.Errorf("invalid sigType %#x", sigType)
+ }
+
+ if strongLen > maxStrongLen {
+ return nil, fmt.Errorf("invalid strongLen %d for sigType %#x", strongLen, sigType)
+ }
+
+ err := binary.Write(output, binary.BigEndian, sigType)
+ if err != nil {
+ return nil, err
+ }
+ err = binary.Write(output, binary.BigEndian, blockLen)
+ if err != nil {
+ return nil, err
+ }
+ err = binary.Write(output, binary.BigEndian, strongLen)
+ if err != nil {
+ return nil, err
+ }
+
+ block := make([]byte, blockLen)
+
+ var ret SignatureType
+ ret.weak2block = make(map[uint32]int)
+ ret.sigType = sigType
+ ret.strongLen = strongLen
+ ret.blockLen = blockLen
+
+ for {
+ n, err := io.ReadFull(input, block)
+ if err == io.ErrUnexpectedEOF || err == io.EOF {
+ break
+ } else if err != nil {
+ return nil, err
+ }
+ data := block[:n]
+
+ weak := WeakChecksum(data)
+ err = binary.Write(output, binary.BigEndian, weak)
+ if err != nil {
+ return nil, err
+ }
+
+ strong, _ := CalcStrongSum(data, sigType, strongLen)
+ output.Write(strong)
+
+ ret.weak2block[weak] = len(ret.strongSigs)
+ ret.strongSigs = append(ret.strongSigs, strong)
+ }
+
+ return &ret, nil
+}
diff --git a/vendor/github.com/sean-/seed/LICENSE b/vendor/github.com/sean-/seed/LICENSE
new file mode 100644
index 0000000..33d326a
--- /dev/null
+++ b/vendor/github.com/sean-/seed/LICENSE
@@ -0,0 +1,54 @@
+MIT License
+
+Copyright (c) 2017 Sean Chittenden
+Copyright (c) 2016 Alex Dadgar
+
+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.
+
+=====
+
+Bits of Go-lang's `once.Do()` were cribbed and reused here, too.
+
+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/github.com/sean-/seed/README.md b/vendor/github.com/sean-/seed/README.md
new file mode 100644
index 0000000..0137564
--- /dev/null
+++ b/vendor/github.com/sean-/seed/README.md
@@ -0,0 +1,44 @@
+# `seed` - Quickly Seed Go's Random Number Generator
+
+Boiler-plate to securely [seed](https://en.wikipedia.org/wiki/Random_seed) Go's
+random number generator (if possible). This library isn't anything fancy, it's
+just a canonical way of seeding Go's random number generator. Cribbed from
+[`Nomad`](https://github.com/hashicorp/nomad/commit/f89a993ec6b91636a3384dd568898245fbc273a1)
+before it was moved into
+[`Consul`](https://github.com/hashicorp/consul/commit/d695bcaae6e31ee307c11fdf55bb0bf46ea9fcf4)
+and made into a helper function, and now further modularized to be a super
+lightweight and reusable library.
+
+Time is better than
+[Go's default seed of `1`](https://golang.org/pkg/math/rand/#Seed), but friends
+don't let friends use time as a seed to a random number generator. Use
+`seed.MustInit()` instead.
+
+`seed.Init()` is an idempotent and reentrant call that will return an error if
+it can't seed the value the first time it is called. `Init()` is reentrant.
+
+`seed.MustInit()` is idempotent and reentrant call that will `panic()` if it
+can't seed the value the first time it is called. `MustInit()` is reentrant.
+
+## Usage
+
+```
+package mypackage
+
+import (
+ "github.com/sean-/seed"
+)
+
+// MustInit will panic() if it is unable to set a high-entropy random seed:
+func init() {
+ seed.MustInit()
+}
+
+// Or if you want to not panic() and can actually handle this error:
+func init() {
+ if secure, err := !seed.Init(); !secure {
+ // Handle the error
+ //panic(fmt.Sprintf("Unable to securely seed Go's RNG: %v", err))
+ }
+}
+```
diff --git a/vendor/github.com/sean-/seed/init.go b/vendor/github.com/sean-/seed/init.go
new file mode 100644
index 0000000..248d6b6
--- /dev/null
+++ b/vendor/github.com/sean-/seed/init.go
@@ -0,0 +1,84 @@
+package seed
+
+import (
+ crand "crypto/rand"
+ "fmt"
+ "math"
+ "math/big"
+ "math/rand"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+var (
+ m sync.Mutex
+ secure int32
+ seeded int32
+)
+
+func cryptoSeed() error {
+ defer atomic.StoreInt32(&seeded, 1)
+
+ var err error
+ var n *big.Int
+ n, err = crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
+ if err != nil {
+ rand.Seed(time.Now().UTC().UnixNano())
+ return err
+ }
+ rand.Seed(n.Int64())
+ atomic.StoreInt32(&secure, 1)
+ return nil
+}
+
+// Init provides best-effort seeding (which is better than running with Go's
+// default seed of 1). If `/dev/urandom` is available, Init() will seed Go's
+// runtime with entropy from `/dev/urandom` and return true because the runtime
+// was securely seeded. If Init() has already initialized the random number or
+// it had failed to securely initialize the random number generation, Init()
+// will return false. See MustInit().
+func Init() (seededSecurely bool, err error) {
+ if atomic.LoadInt32(&seeded) == 1 {
+ return false, nil
+ }
+
+ // Slow-path
+ m.Lock()
+ defer m.Unlock()
+
+ if err := cryptoSeed(); err != nil {
+ return false, err
+ }
+
+ return true, nil
+}
+
+// MustInit provides guaranteed secure seeding. If `/dev/urandom` is not
+// available, MustInit will panic() with an error indicating why reading from
+// `/dev/urandom` failed. MustInit() will upgrade the seed if for some reason a
+// call to Init() failed in the past.
+func MustInit() {
+ if atomic.LoadInt32(&secure) == 1 {
+ return
+ }
+
+ // Slow-path
+ m.Lock()
+ defer m.Unlock()
+
+ if err := cryptoSeed(); err != nil {
+ panic(fmt.Sprintf("Unable to seed the random number generator: %v", err))
+ }
+}
+
+// Secure returns true if a cryptographically secure seed was used to
+// initialize rand.
+func Secure() bool {
+ return atomic.LoadInt32(&secure) == 1
+}
+
+// Seeded returns true if Init has seeded the random number generator.
+func Seeded() bool {
+ return atomic.LoadInt32(&seeded) == 1
+}
diff --git a/vendor/github.com/seccomp/libseccomp-golang/LICENSE b/vendor/github.com/seccomp/libseccomp-golang/LICENSE
new file mode 100644
index 0000000..81cf60d
--- /dev/null
+++ b/vendor/github.com/seccomp/libseccomp-golang/LICENSE
@@ -0,0 +1,22 @@
+Copyright (c) 2015 Matthew Heon <mheon@redhat.com>
+Copyright (c) 2015 Paul Moore <pmoore@redhat.com>
+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/seccomp/libseccomp-golang/README b/vendor/github.com/seccomp/libseccomp-golang/README
new file mode 100644
index 0000000..64cab69
--- /dev/null
+++ b/vendor/github.com/seccomp/libseccomp-golang/README
@@ -0,0 +1,26 @@
+libseccomp-golang: Go Language Bindings for the libseccomp Project
+===============================================================================
+https://github.com/seccomp/libseccomp-golang
+https://github.com/seccomp/libseccomp
+
+The libseccomp library provides an easy to use, platform independent, interface
+to the Linux Kernel's syscall filtering mechanism. The libseccomp API is
+designed to abstract away the underlying BPF based syscall filter language and
+present a more conventional function-call based filtering interface that should
+be familiar to, and easily adopted by, application developers.
+
+The libseccomp-golang library provides a Go based interface to the libseccomp
+library.
+
+* Online Resources
+
+The library source repository currently lives on GitHub at the following URLs:
+
+ -> https://github.com/seccomp/libseccomp-golang
+ -> https://github.com/seccomp/libseccomp
+
+The project mailing list is currently hosted on Google Groups at the URL below,
+please note that a Google account is not required to subscribe to the mailing
+list.
+
+ -> https://groups.google.com/d/forum/libseccomp
diff --git a/vendor/github.com/seccomp/libseccomp-golang/seccomp.go b/vendor/github.com/seccomp/libseccomp-golang/seccomp.go
new file mode 100644
index 0000000..b2c010f
--- /dev/null
+++ b/vendor/github.com/seccomp/libseccomp-golang/seccomp.go
@@ -0,0 +1,857 @@
+// +build linux
+
+// Public API specification for libseccomp Go bindings
+// Contains public API for the bindings
+
+// Package seccomp provides bindings for libseccomp, a library wrapping the Linux
+// seccomp syscall. Seccomp enables an application to restrict system call use
+// for itself and its children.
+package seccomp
+
+import (
+ "fmt"
+ "os"
+ "runtime"
+ "strings"
+ "sync"
+ "syscall"
+ "unsafe"
+)
+
+// C wrapping code
+
+// #cgo pkg-config: libseccomp
+// #include <stdlib.h>
+// #include <seccomp.h>
+import "C"
+
+// Exported types
+
+// ScmpArch represents a CPU architecture. Seccomp can restrict syscalls on a
+// per-architecture basis.
+type ScmpArch uint
+
+// ScmpAction represents an action to be taken on a filter rule match in
+// libseccomp
+type ScmpAction uint
+
+// ScmpCompareOp represents a comparison operator which can be used in a filter
+// rule
+type ScmpCompareOp uint
+
+// ScmpCondition represents a rule in a libseccomp filter context
+type ScmpCondition struct {
+ Argument uint `json:"argument,omitempty"`
+ Op ScmpCompareOp `json:"operator,omitempty"`
+ Operand1 uint64 `json:"operand_one,omitempty"`
+ Operand2 uint64 `json:"operand_two,omitempty"`
+}
+
+// ScmpSyscall represents a Linux System Call
+type ScmpSyscall int32
+
+// Exported Constants
+
+const (
+ // Valid architectures recognized by libseccomp
+ // ARM64 and all MIPS architectures are unsupported by versions of the
+ // library before v2.2 and will return errors if used
+
+ // ArchInvalid is a placeholder to ensure uninitialized ScmpArch
+ // variables are invalid
+ ArchInvalid ScmpArch = iota
+ // ArchNative is the native architecture of the kernel
+ ArchNative ScmpArch = iota
+ // ArchX86 represents 32-bit x86 syscalls
+ ArchX86 ScmpArch = iota
+ // ArchAMD64 represents 64-bit x86-64 syscalls
+ ArchAMD64 ScmpArch = iota
+ // ArchX32 represents 64-bit x86-64 syscalls (32-bit pointers)
+ ArchX32 ScmpArch = iota
+ // ArchARM represents 32-bit ARM syscalls
+ ArchARM ScmpArch = iota
+ // ArchARM64 represents 64-bit ARM syscalls
+ ArchARM64 ScmpArch = iota
+ // ArchMIPS represents 32-bit MIPS syscalls
+ ArchMIPS ScmpArch = iota
+ // ArchMIPS64 represents 64-bit MIPS syscalls
+ ArchMIPS64 ScmpArch = iota
+ // ArchMIPS64N32 represents 64-bit MIPS syscalls (32-bit pointers)
+ ArchMIPS64N32 ScmpArch = iota
+ // ArchMIPSEL represents 32-bit MIPS syscalls (little endian)
+ ArchMIPSEL ScmpArch = iota
+ // ArchMIPSEL64 represents 64-bit MIPS syscalls (little endian)
+ ArchMIPSEL64 ScmpArch = iota
+ // ArchMIPSEL64N32 represents 64-bit MIPS syscalls (little endian,
+ // 32-bit pointers)
+ ArchMIPSEL64N32 ScmpArch = iota
+ // ArchPPC represents 32-bit POWERPC syscalls
+ ArchPPC ScmpArch = iota
+ // ArchPPC64 represents 64-bit POWER syscalls (big endian)
+ ArchPPC64 ScmpArch = iota
+ // ArchPPC64LE represents 64-bit POWER syscalls (little endian)
+ ArchPPC64LE ScmpArch = iota
+ // ArchS390 represents 31-bit System z/390 syscalls
+ ArchS390 ScmpArch = iota
+ // ArchS390X represents 64-bit System z/390 syscalls
+ ArchS390X ScmpArch = iota
+)
+
+const (
+ // Supported actions on filter match
+
+ // ActInvalid is a placeholder to ensure uninitialized ScmpAction
+ // variables are invalid
+ ActInvalid ScmpAction = iota
+ // ActKill kills the process
+ ActKill ScmpAction = iota
+ // ActTrap throws SIGSYS
+ ActTrap ScmpAction = iota
+ // ActErrno causes the syscall to return a negative error code. This
+ // code can be set with the SetReturnCode method
+ ActErrno ScmpAction = iota
+ // ActTrace causes the syscall to notify tracing processes with the
+ // given error code. This code can be set with the SetReturnCode method
+ ActTrace ScmpAction = iota
+ // ActAllow permits the syscall to continue execution
+ ActAllow ScmpAction = iota
+)
+
+const (
+ // These are comparison operators used in conditional seccomp rules
+ // They are used to compare the value of a single argument of a syscall
+ // against a user-defined constant
+
+ // CompareInvalid is a placeholder to ensure uninitialized ScmpCompareOp
+ // variables are invalid
+ CompareInvalid ScmpCompareOp = iota
+ // CompareNotEqual returns true if the argument is not equal to the
+ // given value
+ CompareNotEqual ScmpCompareOp = iota
+ // CompareLess returns true if the argument is less than the given value
+ CompareLess ScmpCompareOp = iota
+ // CompareLessOrEqual returns true if the argument is less than or equal
+ // to the given value
+ CompareLessOrEqual ScmpCompareOp = iota
+ // CompareEqual returns true if the argument is equal to the given value
+ CompareEqual ScmpCompareOp = iota
+ // CompareGreaterEqual returns true if the argument is greater than or
+ // equal to the given value
+ CompareGreaterEqual ScmpCompareOp = iota
+ // CompareGreater returns true if the argument is greater than the given
+ // value
+ CompareGreater ScmpCompareOp = iota
+ // CompareMaskedEqual returns true if the argument is equal to the given
+ // value, when masked (bitwise &) against the second given value
+ CompareMaskedEqual ScmpCompareOp = iota
+)
+
+// Helpers for types
+
+// GetArchFromString returns an ScmpArch constant from a string representing an
+// architecture
+func GetArchFromString(arch string) (ScmpArch, error) {
+ switch strings.ToLower(arch) {
+ case "x86":
+ return ArchX86, nil
+ case "amd64", "x86-64", "x86_64", "x64":
+ return ArchAMD64, nil
+ case "x32":
+ return ArchX32, nil
+ case "arm":
+ return ArchARM, nil
+ case "arm64", "aarch64":
+ return ArchARM64, nil
+ case "mips":
+ return ArchMIPS, nil
+ case "mips64":
+ return ArchMIPS64, nil
+ case "mips64n32":
+ return ArchMIPS64N32, nil
+ case "mipsel":
+ return ArchMIPSEL, nil
+ case "mipsel64":
+ return ArchMIPSEL64, nil
+ case "mipsel64n32":
+ return ArchMIPSEL64N32, nil
+ case "ppc":
+ return ArchPPC, nil
+ case "ppc64":
+ return ArchPPC64, nil
+ case "ppc64le":
+ return ArchPPC64LE, nil
+ case "s390":
+ return ArchS390, nil
+ case "s390x":
+ return ArchS390X, nil
+ default:
+ return ArchInvalid, fmt.Errorf("cannot convert unrecognized string %s", arch)
+ }
+}
+
+// String returns a string representation of an architecture constant
+func (a ScmpArch) String() string {
+ switch a {
+ case ArchX86:
+ return "x86"
+ case ArchAMD64:
+ return "amd64"
+ case ArchX32:
+ return "x32"
+ case ArchARM:
+ return "arm"
+ case ArchARM64:
+ return "arm64"
+ case ArchMIPS:
+ return "mips"
+ case ArchMIPS64:
+ return "mips64"
+ case ArchMIPS64N32:
+ return "mips64n32"
+ case ArchMIPSEL:
+ return "mipsel"
+ case ArchMIPSEL64:
+ return "mipsel64"
+ case ArchMIPSEL64N32:
+ return "mipsel64n32"
+ case ArchPPC:
+ return "ppc"
+ case ArchPPC64:
+ return "ppc64"
+ case ArchPPC64LE:
+ return "ppc64le"
+ case ArchS390:
+ return "s390"
+ case ArchS390X:
+ return "s390x"
+ case ArchNative:
+ return "native"
+ case ArchInvalid:
+ return "Invalid architecture"
+ default:
+ return "Unknown architecture"
+ }
+}
+
+// String returns a string representation of a comparison operator constant
+func (a ScmpCompareOp) String() string {
+ switch a {
+ case CompareNotEqual:
+ return "Not equal"
+ case CompareLess:
+ return "Less than"
+ case CompareLessOrEqual:
+ return "Less than or equal to"
+ case CompareEqual:
+ return "Equal"
+ case CompareGreaterEqual:
+ return "Greater than or equal to"
+ case CompareGreater:
+ return "Greater than"
+ case CompareMaskedEqual:
+ return "Masked equality"
+ case CompareInvalid:
+ return "Invalid comparison operator"
+ default:
+ return "Unrecognized comparison operator"
+ }
+}
+
+// String returns a string representation of a seccomp match action
+func (a ScmpAction) String() string {
+ switch a & 0xFFFF {
+ case ActKill:
+ return "Action: Kill Process"
+ case ActTrap:
+ return "Action: Send SIGSYS"
+ case ActErrno:
+ return fmt.Sprintf("Action: Return error code %d", (a >> 16))
+ case ActTrace:
+ return fmt.Sprintf("Action: Notify tracing processes with code %d",
+ (a >> 16))
+ case ActAllow:
+ return "Action: Allow system call"
+ default:
+ return "Unrecognized Action"
+ }
+}
+
+// SetReturnCode adds a return code to a supporting ScmpAction, clearing any
+// existing code Only valid on ActErrno and ActTrace. Takes no action otherwise.
+// Accepts 16-bit return code as argument.
+// Returns a valid ScmpAction of the original type with the new error code set.
+func (a ScmpAction) SetReturnCode(code int16) ScmpAction {
+ aTmp := a & 0x0000FFFF
+ if aTmp == ActErrno || aTmp == ActTrace {
+ return (aTmp | (ScmpAction(code)&0xFFFF)<<16)
+ }
+ return a
+}
+
+// GetReturnCode returns the return code of an ScmpAction
+func (a ScmpAction) GetReturnCode() int16 {
+ return int16(a >> 16)
+}
+
+// General utility functions
+
+// GetLibraryVersion returns the version of the library the bindings are built
+// against.
+// The version is formatted as follows: Major.Minor.Micro
+func GetLibraryVersion() (major, minor, micro int) {
+ return verMajor, verMinor, verMicro
+}
+
+// Syscall functions
+
+// GetName retrieves the name of a syscall from its number.
+// Acts on any syscall number.
+// Returns either a string containing the name of the syscall, or an error.
+func (s ScmpSyscall) GetName() (string, error) {
+ return s.GetNameByArch(ArchNative)
+}
+
+// GetNameByArch retrieves the name of a syscall from its number for a given
+// architecture.
+// Acts on any syscall number.
+// Accepts a valid architecture constant.
+// Returns either a string containing the name of the syscall, or an error.
+// if the syscall is unrecognized or an issue occurred.
+func (s ScmpSyscall) GetNameByArch(arch ScmpArch) (string, error) {
+ if err := sanitizeArch(arch); err != nil {
+ return "", err
+ }
+
+ cString := C.seccomp_syscall_resolve_num_arch(arch.toNative(), C.int(s))
+ if cString == nil {
+ return "", fmt.Errorf("could not resolve syscall name")
+ }
+ defer C.free(unsafe.Pointer(cString))
+
+ finalStr := C.GoString(cString)
+ return finalStr, nil
+}
+
+// GetSyscallFromName returns the number of a syscall by name on the kernel's
+// native architecture.
+// Accepts a string containing the name of a syscall.
+// Returns the number of the syscall, or an error if no syscall with that name
+// was found.
+func GetSyscallFromName(name string) (ScmpSyscall, error) {
+ cString := C.CString(name)
+ defer C.free(unsafe.Pointer(cString))
+
+ result := C.seccomp_syscall_resolve_name(cString)
+ if result == scmpError {
+ return 0, fmt.Errorf("could not resolve name to syscall")
+ }
+
+ return ScmpSyscall(result), nil
+}
+
+// GetSyscallFromNameByArch returns the number of a syscall by name for a given
+// architecture's ABI.
+// Accepts the name of a syscall and an architecture constant.
+// Returns the number of the syscall, or an error if an invalid architecture is
+// passed or a syscall with that name was not found.
+func GetSyscallFromNameByArch(name string, arch ScmpArch) (ScmpSyscall, error) {
+ if err := sanitizeArch(arch); err != nil {
+ return 0, err
+ }
+
+ cString := C.CString(name)
+ defer C.free(unsafe.Pointer(cString))
+
+ result := C.seccomp_syscall_resolve_name_arch(arch.toNative(), cString)
+ if result == scmpError {
+ return 0, fmt.Errorf("could not resolve name to syscall")
+ }
+
+ return ScmpSyscall(result), nil
+}
+
+// MakeCondition creates and returns a new condition to attach to a filter rule.
+// Associated rules will only match if this condition is true.
+// Accepts the number the argument we are checking, and a comparison operator
+// and value to compare to.
+// The rule will match if argument $arg (zero-indexed) of the syscall is
+// $COMPARE_OP the provided comparison value.
+// Some comparison operators accept two values. Masked equals, for example,
+// will mask $arg of the syscall with the second value provided (via bitwise
+// AND) and then compare against the first value provided.
+// For example, in the less than or equal case, if the syscall argument was
+// 0 and the value provided was 1, the condition would match, as 0 is less
+// than or equal to 1.
+// Return either an error on bad argument or a valid ScmpCondition struct.
+func MakeCondition(arg uint, comparison ScmpCompareOp, values ...uint64) (ScmpCondition, error) {
+ var condStruct ScmpCondition
+
+ if comparison == CompareInvalid {
+ return condStruct, fmt.Errorf("invalid comparison operator")
+ } else if arg > 5 {
+ return condStruct, fmt.Errorf("syscalls only have up to 6 arguments")
+ } else if len(values) > 2 {
+ return condStruct, fmt.Errorf("conditions can have at most 2 arguments")
+ } else if len(values) == 0 {
+ return condStruct, fmt.Errorf("must provide at least one value to compare against")
+ }
+
+ condStruct.Argument = arg
+ condStruct.Op = comparison
+ condStruct.Operand1 = values[0]
+ if len(values) == 2 {
+ condStruct.Operand2 = values[1]
+ } else {
+ condStruct.Operand2 = 0 // Unused
+ }
+
+ return condStruct, nil
+}
+
+// Utility Functions
+
+// GetNativeArch returns architecture token representing the native kernel
+// architecture
+func GetNativeArch() (ScmpArch, error) {
+ arch := C.seccomp_arch_native()
+
+ return archFromNative(arch)
+}
+
+// Public Filter API
+
+// ScmpFilter represents a filter context in libseccomp.
+// A filter context is initially empty. Rules can be added to it, and it can
+// then be loaded into the kernel.
+type ScmpFilter struct {
+ filterCtx C.scmp_filter_ctx
+ valid bool
+ lock sync.Mutex
+}
+
+// NewFilter creates and returns a new filter context.
+// Accepts a default action to be taken for syscalls which match no rules in
+// the filter.
+// Returns a reference to a valid filter context, or nil and an error if the
+// filter context could not be created or an invalid default action was given.
+func NewFilter(defaultAction ScmpAction) (*ScmpFilter, error) {
+ if err := sanitizeAction(defaultAction); err != nil {
+ return nil, err
+ }
+
+ fPtr := C.seccomp_init(defaultAction.toNative())
+ if fPtr == nil {
+ return nil, fmt.Errorf("could not create filter")
+ }
+
+ filter := new(ScmpFilter)
+ filter.filterCtx = fPtr
+ filter.valid = true
+ runtime.SetFinalizer(filter, filterFinalizer)
+
+ return filter, nil
+}
+
+// IsValid determines whether a filter context is valid to use.
+// Some operations (Release and Merge) render filter contexts invalid and
+// consequently prevent further use.
+func (f *ScmpFilter) IsValid() bool {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ return f.valid
+}
+
+// Reset resets a filter context, removing all its existing state.
+// Accepts a new default action to be taken for syscalls which do not match.
+// Returns an error if the filter or action provided are invalid.
+func (f *ScmpFilter) Reset(defaultAction ScmpAction) error {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ if err := sanitizeAction(defaultAction); err != nil {
+ return err
+ } else if !f.valid {
+ return errBadFilter
+ }
+
+ retCode := C.seccomp_reset(f.filterCtx, defaultAction.toNative())
+ if retCode != 0 {
+ return syscall.Errno(-1 * retCode)
+ }
+
+ return nil
+}
+
+// Release releases a filter context, freeing its memory. Should be called after
+// loading into the kernel, when the filter is no longer needed.
+// After calling this function, the given filter is no longer valid and cannot
+// be used.
+// Release() will be invoked automatically when a filter context is garbage
+// collected, but can also be called manually to free memory.
+func (f *ScmpFilter) Release() {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ if !f.valid {
+ return
+ }
+
+ f.valid = false
+ C.seccomp_release(f.filterCtx)
+}
+
+// Merge merges two filter contexts.
+// The source filter src will be released as part of the process, and will no
+// longer be usable or valid after this call.
+// To be merged, filters must NOT share any architectures, and all their
+// attributes (Default Action, Bad Arch Action, No New Privs and TSync bools)
+// must match.
+// The filter src will be merged into the filter this is called on.
+// The architectures of the src filter not present in the destination, and all
+// associated rules, will be added to the destination.
+// Returns an error if merging the filters failed.
+func (f *ScmpFilter) Merge(src *ScmpFilter) error {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ src.lock.Lock()
+ defer src.lock.Unlock()
+
+ if !src.valid || !f.valid {
+ return fmt.Errorf("one or more of the filter contexts is invalid or uninitialized")
+ }
+
+ // Merge the filters
+ retCode := C.seccomp_merge(f.filterCtx, src.filterCtx)
+ if syscall.Errno(-1*retCode) == syscall.EINVAL {
+ return fmt.Errorf("filters could not be merged due to a mismatch in attributes or invalid filter")
+ } else if retCode != 0 {
+ return syscall.Errno(-1 * retCode)
+ }
+
+ src.valid = false
+
+ return nil
+}
+
+// IsArchPresent checks if an architecture is present in a filter.
+// If a filter contains an architecture, it uses its default action for
+// syscalls which do not match rules in it, and its rules can match syscalls
+// for that ABI.
+// If a filter does not contain an architecture, all syscalls made to that
+// kernel ABI will fail with the filter's default Bad Architecture Action
+// (by default, killing the process).
+// Accepts an architecture constant.
+// Returns true if the architecture is present in the filter, false otherwise,
+// and an error on an invalid filter context, architecture constant, or an
+// issue with the call to libseccomp.
+func (f *ScmpFilter) IsArchPresent(arch ScmpArch) (bool, error) {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ if err := sanitizeArch(arch); err != nil {
+ return false, err
+ } else if !f.valid {
+ return false, errBadFilter
+ }
+
+ retCode := C.seccomp_arch_exist(f.filterCtx, arch.toNative())
+ if syscall.Errno(-1*retCode) == syscall.EEXIST {
+ // -EEXIST is "arch not present"
+ return false, nil
+ } else if retCode != 0 {
+ return false, syscall.Errno(-1 * retCode)
+ }
+
+ return true, nil
+}
+
+// AddArch adds an architecture to the filter.
+// Accepts an architecture constant.
+// Returns an error on invalid filter context or architecture token, or an
+// issue with the call to libseccomp.
+func (f *ScmpFilter) AddArch(arch ScmpArch) error {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ if err := sanitizeArch(arch); err != nil {
+ return err
+ } else if !f.valid {
+ return errBadFilter
+ }
+
+ // Libseccomp returns -EEXIST if the specified architecture is already
+ // present. Succeed silently in this case, as it's not fatal, and the
+ // architecture is present already.
+ retCode := C.seccomp_arch_add(f.filterCtx, arch.toNative())
+ if retCode != 0 && syscall.Errno(-1*retCode) != syscall.EEXIST {
+ return syscall.Errno(-1 * retCode)
+ }
+
+ return nil
+}
+
+// RemoveArch removes an architecture from the filter.
+// Accepts an architecture constant.
+// Returns an error on invalid filter context or architecture token, or an
+// issue with the call to libseccomp.
+func (f *ScmpFilter) RemoveArch(arch ScmpArch) error {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ if err := sanitizeArch(arch); err != nil {
+ return err
+ } else if !f.valid {
+ return errBadFilter
+ }
+
+ // Similar to AddArch, -EEXIST is returned if the arch is not present
+ // Succeed silently in that case, this is not fatal and the architecture
+ // is not present in the filter after RemoveArch
+ retCode := C.seccomp_arch_remove(f.filterCtx, arch.toNative())
+ if retCode != 0 && syscall.Errno(-1*retCode) != syscall.EEXIST {
+ return syscall.Errno(-1 * retCode)
+ }
+
+ return nil
+}
+
+// Load loads a filter context into the kernel.
+// Returns an error if the filter context is invalid or the syscall failed.
+func (f *ScmpFilter) Load() error {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ if !f.valid {
+ return errBadFilter
+ }
+
+ if retCode := C.seccomp_load(f.filterCtx); retCode != 0 {
+ return syscall.Errno(-1 * retCode)
+ }
+
+ return nil
+}
+
+// GetDefaultAction returns the default action taken on a syscall which does not
+// match a rule in the filter, or an error if an issue was encountered
+// retrieving the value.
+func (f *ScmpFilter) GetDefaultAction() (ScmpAction, error) {
+ action, err := f.getFilterAttr(filterAttrActDefault)
+ if err != nil {
+ return 0x0, err
+ }
+
+ return actionFromNative(action)
+}
+
+// GetBadArchAction returns the default action taken on a syscall for an
+// architecture not in the filter, or an error if an issue was encountered
+// retrieving the value.
+func (f *ScmpFilter) GetBadArchAction() (ScmpAction, error) {
+ action, err := f.getFilterAttr(filterAttrActBadArch)
+ if err != nil {
+ return 0x0, err
+ }
+
+ return actionFromNative(action)
+}
+
+// GetNoNewPrivsBit returns the current state the No New Privileges bit will be set
+// to on the filter being loaded, or an error if an issue was encountered
+// retrieving the value.
+// The No New Privileges bit tells the kernel that new processes run with exec()
+// cannot gain more privileges than the process that ran exec().
+// For example, a process with No New Privileges set would be unable to exec
+// setuid/setgid executables.
+func (f *ScmpFilter) GetNoNewPrivsBit() (bool, error) {
+ noNewPrivs, err := f.getFilterAttr(filterAttrNNP)
+ if err != nil {
+ return false, err
+ }
+
+ if noNewPrivs == 0 {
+ return false, nil
+ }
+
+ return true, nil
+}
+
+// GetTsyncBit returns whether Thread Synchronization will be enabled on the
+// filter being loaded, or an error if an issue was encountered retrieving the
+// value.
+// Thread Sync ensures that all members of the thread group of the calling
+// process will share the same Seccomp filter set.
+// Tsync is a fairly recent addition to the Linux kernel and older kernels
+// lack support. If the running kernel does not support Tsync and it is
+// requested in a filter, Libseccomp will not enable TSync support and will
+// proceed as normal.
+// This function is unavailable before v2.2 of libseccomp and will return an
+// error.
+func (f *ScmpFilter) GetTsyncBit() (bool, error) {
+ tSync, err := f.getFilterAttr(filterAttrTsync)
+ if err != nil {
+ return false, err
+ }
+
+ if tSync == 0 {
+ return false, nil
+ }
+
+ return true, nil
+}
+
+// SetBadArchAction sets the default action taken on a syscall for an
+// architecture not in the filter, or an error if an issue was encountered
+// setting the value.
+func (f *ScmpFilter) SetBadArchAction(action ScmpAction) error {
+ if err := sanitizeAction(action); err != nil {
+ return err
+ }
+
+ return f.setFilterAttr(filterAttrActBadArch, action.toNative())
+}
+
+// SetNoNewPrivsBit sets the state of the No New Privileges bit, which will be
+// applied on filter load, or an error if an issue was encountered setting the
+// value.
+// Filters with No New Privileges set to 0 can only be loaded if the process
+// has the CAP_SYS_ADMIN capability.
+func (f *ScmpFilter) SetNoNewPrivsBit(state bool) error {
+ var toSet C.uint32_t = 0x0
+
+ if state {
+ toSet = 0x1
+ }
+
+ return f.setFilterAttr(filterAttrNNP, toSet)
+}
+
+// SetTsync sets whether Thread Synchronization will be enabled on the filter
+// being loaded. Returns an error if setting Tsync failed, or the filter is
+// invalid.
+// Thread Sync ensures that all members of the thread group of the calling
+// process will share the same Seccomp filter set.
+// Tsync is a fairly recent addition to the Linux kernel and older kernels
+// lack support. If the running kernel does not support Tsync and it is
+// requested in a filter, Libseccomp will not enable TSync support and will
+// proceed as normal.
+// This function is unavailable before v2.2 of libseccomp and will return an
+// error.
+func (f *ScmpFilter) SetTsync(enable bool) error {
+ var toSet C.uint32_t = 0x0
+
+ if enable {
+ toSet = 0x1
+ }
+
+ return f.setFilterAttr(filterAttrTsync, toSet)
+}
+
+// SetSyscallPriority sets a syscall's priority.
+// This provides a hint to the filter generator in libseccomp about the
+// importance of this syscall. High-priority syscalls are placed
+// first in the filter code, and incur less overhead (at the expense of
+// lower-priority syscalls).
+func (f *ScmpFilter) SetSyscallPriority(call ScmpSyscall, priority uint8) error {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ if !f.valid {
+ return errBadFilter
+ }
+
+ if retCode := C.seccomp_syscall_priority(f.filterCtx, C.int(call),
+ C.uint8_t(priority)); retCode != 0 {
+ return syscall.Errno(-1 * retCode)
+ }
+
+ return nil
+}
+
+// AddRule adds a single rule for an unconditional action on a syscall.
+// Accepts the number of the syscall and the action to be taken on the call
+// being made.
+// Returns an error if an issue was encountered adding the rule.
+func (f *ScmpFilter) AddRule(call ScmpSyscall, action ScmpAction) error {
+ return f.addRuleGeneric(call, action, false, nil)
+}
+
+// AddRuleExact adds a single rule for an unconditional action on a syscall.
+// Accepts the number of the syscall and the action to be taken on the call
+// being made.
+// No modifications will be made to the rule, and it will fail to add if it
+// cannot be applied to the current architecture without modification.
+// The rule will function exactly as described, but it may not function identically
+// (or be able to be applied to) all architectures.
+// Returns an error if an issue was encountered adding the rule.
+func (f *ScmpFilter) AddRuleExact(call ScmpSyscall, action ScmpAction) error {
+ return f.addRuleGeneric(call, action, true, nil)
+}
+
+// AddRuleConditional adds a single rule for a conditional action on a syscall.
+// Returns an error if an issue was encountered adding the rule.
+// All conditions must match for the rule to match.
+// There is a bug in library versions below v2.2.1 which can, in some cases,
+// cause conditions to be lost when more than one are used. Consequently,
+// AddRuleConditional is disabled on library versions lower than v2.2.1
+func (f *ScmpFilter) AddRuleConditional(call ScmpSyscall, action ScmpAction, conds []ScmpCondition) error {
+ return f.addRuleGeneric(call, action, false, conds)
+}
+
+// AddRuleConditionalExact adds a single rule for a conditional action on a
+// syscall.
+// No modifications will be made to the rule, and it will fail to add if it
+// cannot be applied to the current architecture without modification.
+// The rule will function exactly as described, but it may not function identically
+// (or be able to be applied to) all architectures.
+// Returns an error if an issue was encountered adding the rule.
+// There is a bug in library versions below v2.2.1 which can, in some cases,
+// cause conditions to be lost when more than one are used. Consequently,
+// AddRuleConditionalExact is disabled on library versions lower than v2.2.1
+func (f *ScmpFilter) AddRuleConditionalExact(call ScmpSyscall, action ScmpAction, conds []ScmpCondition) error {
+ return f.addRuleGeneric(call, action, true, conds)
+}
+
+// ExportPFC output PFC-formatted, human-readable dump of a filter context's
+// rules to a file.
+// Accepts file to write to (must be open for writing).
+// Returns an error if writing to the file fails.
+func (f *ScmpFilter) ExportPFC(file *os.File) error {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ fd := file.Fd()
+
+ if !f.valid {
+ return errBadFilter
+ }
+
+ if retCode := C.seccomp_export_pfc(f.filterCtx, C.int(fd)); retCode != 0 {
+ return syscall.Errno(-1 * retCode)
+ }
+
+ return nil
+}
+
+// ExportBPF outputs Berkeley Packet Filter-formatted, kernel-readable dump of a
+// filter context's rules to a file.
+// Accepts file to write to (must be open for writing).
+// Returns an error if writing to the file fails.
+func (f *ScmpFilter) ExportBPF(file *os.File) error {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ fd := file.Fd()
+
+ if !f.valid {
+ return errBadFilter
+ }
+
+ if retCode := C.seccomp_export_bpf(f.filterCtx, C.int(fd)); retCode != 0 {
+ return syscall.Errno(-1 * retCode)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/seccomp/libseccomp-golang/seccomp_internal.go b/vendor/github.com/seccomp/libseccomp-golang/seccomp_internal.go
new file mode 100644
index 0000000..ab67a3d
--- /dev/null
+++ b/vendor/github.com/seccomp/libseccomp-golang/seccomp_internal.go
@@ -0,0 +1,506 @@
+// +build linux
+
+// Internal functions for libseccomp Go bindings
+// No exported functions
+
+package seccomp
+
+import (
+ "fmt"
+ "os"
+ "syscall"
+)
+
+// Unexported C wrapping code - provides the C-Golang interface
+// Get the seccomp header in scope
+// Need stdlib.h for free() on cstrings
+
+// #cgo pkg-config: libseccomp
+/*
+#include <stdlib.h>
+#include <seccomp.h>
+
+#if SCMP_VER_MAJOR < 2
+#error Minimum supported version of Libseccomp is v2.1.0
+#elif SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 1
+#error Minimum supported version of Libseccomp is v2.1.0
+#endif
+
+#define ARCH_BAD ~0
+
+const uint32_t C_ARCH_BAD = ARCH_BAD;
+
+#ifndef SCMP_ARCH_AARCH64
+#define SCMP_ARCH_AARCH64 ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_MIPS
+#define SCMP_ARCH_MIPS ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_MIPS64
+#define SCMP_ARCH_MIPS64 ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_MIPS64N32
+#define SCMP_ARCH_MIPS64N32 ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_MIPSEL
+#define SCMP_ARCH_MIPSEL ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_MIPSEL64
+#define SCMP_ARCH_MIPSEL64 ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_MIPSEL64N32
+#define SCMP_ARCH_MIPSEL64N32 ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_PPC
+#define SCMP_ARCH_PPC ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_PPC64
+#define SCMP_ARCH_PPC64 ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_PPC64LE
+#define SCMP_ARCH_PPC64LE ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_S390
+#define SCMP_ARCH_S390 ARCH_BAD
+#endif
+
+#ifndef SCMP_ARCH_S390X
+#define SCMP_ARCH_S390X ARCH_BAD
+#endif
+
+const uint32_t C_ARCH_NATIVE = SCMP_ARCH_NATIVE;
+const uint32_t C_ARCH_X86 = SCMP_ARCH_X86;
+const uint32_t C_ARCH_X86_64 = SCMP_ARCH_X86_64;
+const uint32_t C_ARCH_X32 = SCMP_ARCH_X32;
+const uint32_t C_ARCH_ARM = SCMP_ARCH_ARM;
+const uint32_t C_ARCH_AARCH64 = SCMP_ARCH_AARCH64;
+const uint32_t C_ARCH_MIPS = SCMP_ARCH_MIPS;
+const uint32_t C_ARCH_MIPS64 = SCMP_ARCH_MIPS64;
+const uint32_t C_ARCH_MIPS64N32 = SCMP_ARCH_MIPS64N32;
+const uint32_t C_ARCH_MIPSEL = SCMP_ARCH_MIPSEL;
+const uint32_t C_ARCH_MIPSEL64 = SCMP_ARCH_MIPSEL64;
+const uint32_t C_ARCH_MIPSEL64N32 = SCMP_ARCH_MIPSEL64N32;
+const uint32_t C_ARCH_PPC = SCMP_ARCH_PPC;
+const uint32_t C_ARCH_PPC64 = SCMP_ARCH_PPC64;
+const uint32_t C_ARCH_PPC64LE = SCMP_ARCH_PPC64LE;
+const uint32_t C_ARCH_S390 = SCMP_ARCH_S390;
+const uint32_t C_ARCH_S390X = SCMP_ARCH_S390X;
+
+const uint32_t C_ACT_KILL = SCMP_ACT_KILL;
+const uint32_t C_ACT_TRAP = SCMP_ACT_TRAP;
+const uint32_t C_ACT_ERRNO = SCMP_ACT_ERRNO(0);
+const uint32_t C_ACT_TRACE = SCMP_ACT_TRACE(0);
+const uint32_t C_ACT_ALLOW = SCMP_ACT_ALLOW;
+
+// If TSync is not supported, make sure it doesn't map to a supported filter attribute
+// Don't worry about major version < 2, the minimum version checks should catch that case
+#if SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 2
+#define SCMP_FLTATR_CTL_TSYNC _SCMP_CMP_MIN
+#endif
+
+const uint32_t C_ATTRIBUTE_DEFAULT = (uint32_t)SCMP_FLTATR_ACT_DEFAULT;
+const uint32_t C_ATTRIBUTE_BADARCH = (uint32_t)SCMP_FLTATR_ACT_BADARCH;
+const uint32_t C_ATTRIBUTE_NNP = (uint32_t)SCMP_FLTATR_CTL_NNP;
+const uint32_t C_ATTRIBUTE_TSYNC = (uint32_t)SCMP_FLTATR_CTL_TSYNC;
+
+const int C_CMP_NE = (int)SCMP_CMP_NE;
+const int C_CMP_LT = (int)SCMP_CMP_LT;
+const int C_CMP_LE = (int)SCMP_CMP_LE;
+const int C_CMP_EQ = (int)SCMP_CMP_EQ;
+const int C_CMP_GE = (int)SCMP_CMP_GE;
+const int C_CMP_GT = (int)SCMP_CMP_GT;
+const int C_CMP_MASKED_EQ = (int)SCMP_CMP_MASKED_EQ;
+
+const int C_VERSION_MAJOR = SCMP_VER_MAJOR;
+const int C_VERSION_MINOR = SCMP_VER_MINOR;
+const int C_VERSION_MICRO = SCMP_VER_MICRO;
+
+typedef struct scmp_arg_cmp* scmp_cast_t;
+
+// Wrapper to create an scmp_arg_cmp struct
+void*
+make_struct_arg_cmp(
+ unsigned int arg,
+ int compare,
+ uint64_t a,
+ uint64_t b
+ )
+{
+ struct scmp_arg_cmp *s = malloc(sizeof(struct scmp_arg_cmp));
+
+ s->arg = arg;
+ s->op = compare;
+ s->datum_a = a;
+ s->datum_b = b;
+
+ return s;
+}
+*/
+import "C"
+
+// Nonexported types
+type scmpFilterAttr uint32
+
+// Nonexported constants
+
+const (
+ filterAttrActDefault scmpFilterAttr = iota
+ filterAttrActBadArch scmpFilterAttr = iota
+ filterAttrNNP scmpFilterAttr = iota
+ filterAttrTsync scmpFilterAttr = iota
+)
+
+const (
+ // An error return from certain libseccomp functions
+ scmpError C.int = -1
+ // Comparison boundaries to check for architecture validity
+ archStart ScmpArch = ArchNative
+ archEnd ScmpArch = ArchS390X
+ // Comparison boundaries to check for action validity
+ actionStart ScmpAction = ActKill
+ actionEnd ScmpAction = ActAllow
+ // Comparison boundaries to check for comparison operator validity
+ compareOpStart ScmpCompareOp = CompareNotEqual
+ compareOpEnd ScmpCompareOp = CompareMaskedEqual
+)
+
+var (
+ // Error thrown on bad filter context
+ errBadFilter = fmt.Errorf("filter is invalid or uninitialized")
+ // Constants representing library major, minor, and micro versions
+ verMajor = int(C.C_VERSION_MAJOR)
+ verMinor = int(C.C_VERSION_MINOR)
+ verMicro = int(C.C_VERSION_MICRO)
+)
+
+// Nonexported functions
+
+// Check if library version is greater than or equal to the given one
+func checkVersionAbove(major, minor, micro int) bool {
+ return (verMajor > major) ||
+ (verMajor == major && verMinor > minor) ||
+ (verMajor == major && verMinor == minor && verMicro >= micro)
+}
+
+// Init function: Verify library version is appropriate
+func init() {
+ if !checkVersionAbove(2, 1, 0) {
+ fmt.Fprintf(os.Stderr, "Libseccomp version too low: minimum supported is 2.1.0, detected %d.%d.%d", C.C_VERSION_MAJOR, C.C_VERSION_MINOR, C.C_VERSION_MICRO)
+ os.Exit(-1)
+ }
+}
+
+// Filter helpers
+
+// Filter finalizer - ensure that kernel context for filters is freed
+func filterFinalizer(f *ScmpFilter) {
+ f.Release()
+}
+
+// Get a raw filter attribute
+func (f *ScmpFilter) getFilterAttr(attr scmpFilterAttr) (C.uint32_t, error) {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ if !f.valid {
+ return 0x0, errBadFilter
+ }
+
+ if !checkVersionAbove(2, 2, 0) && attr == filterAttrTsync {
+ return 0x0, fmt.Errorf("the thread synchronization attribute is not supported in this version of the library")
+ }
+
+ var attribute C.uint32_t
+
+ retCode := C.seccomp_attr_get(f.filterCtx, attr.toNative(), &attribute)
+ if retCode != 0 {
+ return 0x0, syscall.Errno(-1 * retCode)
+ }
+
+ return attribute, nil
+}
+
+// Set a raw filter attribute
+func (f *ScmpFilter) setFilterAttr(attr scmpFilterAttr, value C.uint32_t) error {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ if !f.valid {
+ return errBadFilter
+ }
+
+ if !checkVersionAbove(2, 2, 0) && attr == filterAttrTsync {
+ return fmt.Errorf("the thread synchronization attribute is not supported in this version of the library")
+ }
+
+ retCode := C.seccomp_attr_set(f.filterCtx, attr.toNative(), value)
+ if retCode != 0 {
+ return syscall.Errno(-1 * retCode)
+ }
+
+ return nil
+}
+
+// DOES NOT LOCK OR CHECK VALIDITY
+// Assumes caller has already done this
+// Wrapper for seccomp_rule_add_... functions
+func (f *ScmpFilter) addRuleWrapper(call ScmpSyscall, action ScmpAction, exact bool, cond C.scmp_cast_t) error {
+ var length C.uint
+ if cond != nil {
+ length = 1
+ } else {
+ length = 0
+ }
+
+ var retCode C.int
+ if exact {
+ retCode = C.seccomp_rule_add_exact_array(f.filterCtx, action.toNative(), C.int(call), length, cond)
+ } else {
+ retCode = C.seccomp_rule_add_array(f.filterCtx, action.toNative(), C.int(call), length, cond)
+ }
+
+ if syscall.Errno(-1*retCode) == syscall.EFAULT {
+ return fmt.Errorf("unrecognized syscall")
+ } else if syscall.Errno(-1*retCode) == syscall.EPERM {
+ return fmt.Errorf("requested action matches default action of filter")
+ } else if retCode != 0 {
+ return syscall.Errno(-1 * retCode)
+ }
+
+ return nil
+}
+
+// Generic add function for filter rules
+func (f *ScmpFilter) addRuleGeneric(call ScmpSyscall, action ScmpAction, exact bool, conds []ScmpCondition) error {
+ f.lock.Lock()
+ defer f.lock.Unlock()
+
+ if !f.valid {
+ return errBadFilter
+ }
+
+ if len(conds) == 0 {
+ if err := f.addRuleWrapper(call, action, exact, nil); err != nil {
+ return err
+ }
+ } else {
+ // We don't support conditional filtering in library version v2.1
+ if !checkVersionAbove(2, 2, 1) {
+ return fmt.Errorf("conditional filtering requires libseccomp version >= 2.2.1")
+ }
+
+ for _, cond := range conds {
+ cmpStruct := C.make_struct_arg_cmp(C.uint(cond.Argument), cond.Op.toNative(), C.uint64_t(cond.Operand1), C.uint64_t(cond.Operand2))
+ defer C.free(cmpStruct)
+
+ if err := f.addRuleWrapper(call, action, exact, C.scmp_cast_t(cmpStruct)); err != nil {
+ return err
+ }
+ }
+ }
+
+ return nil
+}
+
+// Generic Helpers
+
+// Helper - Sanitize Arch token input
+func sanitizeArch(in ScmpArch) error {
+ if in < archStart || in > archEnd {
+ return fmt.Errorf("unrecognized architecture")
+ }
+
+ if in.toNative() == C.C_ARCH_BAD {
+ return fmt.Errorf("architecture is not supported on this version of the library")
+ }
+
+ return nil
+}
+
+func sanitizeAction(in ScmpAction) error {
+ inTmp := in & 0x0000FFFF
+ if inTmp < actionStart || inTmp > actionEnd {
+ return fmt.Errorf("unrecognized action")
+ }
+
+ if inTmp != ActTrace && inTmp != ActErrno && (in&0xFFFF0000) != 0 {
+ return fmt.Errorf("highest 16 bits must be zeroed except for Trace and Errno")
+ }
+
+ return nil
+}
+
+func sanitizeCompareOp(in ScmpCompareOp) error {
+ if in < compareOpStart || in > compareOpEnd {
+ return fmt.Errorf("unrecognized comparison operator")
+ }
+
+ return nil
+}
+
+func archFromNative(a C.uint32_t) (ScmpArch, error) {
+ switch a {
+ case C.C_ARCH_X86:
+ return ArchX86, nil
+ case C.C_ARCH_X86_64:
+ return ArchAMD64, nil
+ case C.C_ARCH_X32:
+ return ArchX32, nil
+ case C.C_ARCH_ARM:
+ return ArchARM, nil
+ case C.C_ARCH_NATIVE:
+ return ArchNative, nil
+ case C.C_ARCH_AARCH64:
+ return ArchARM64, nil
+ case C.C_ARCH_MIPS:
+ return ArchMIPS, nil
+ case C.C_ARCH_MIPS64:
+ return ArchMIPS64, nil
+ case C.C_ARCH_MIPS64N32:
+ return ArchMIPS64N32, nil
+ case C.C_ARCH_MIPSEL:
+ return ArchMIPSEL, nil
+ case C.C_ARCH_MIPSEL64:
+ return ArchMIPSEL64, nil
+ case C.C_ARCH_MIPSEL64N32:
+ return ArchMIPSEL64N32, nil
+ case C.C_ARCH_PPC:
+ return ArchPPC, nil
+ case C.C_ARCH_PPC64:
+ return ArchPPC64, nil
+ case C.C_ARCH_PPC64LE:
+ return ArchPPC64LE, nil
+ case C.C_ARCH_S390:
+ return ArchS390, nil
+ case C.C_ARCH_S390X:
+ return ArchS390X, nil
+ default:
+ return 0x0, fmt.Errorf("unrecognized architecture")
+ }
+}
+
+// Only use with sanitized arches, no error handling
+func (a ScmpArch) toNative() C.uint32_t {
+ switch a {
+ case ArchX86:
+ return C.C_ARCH_X86
+ case ArchAMD64:
+ return C.C_ARCH_X86_64
+ case ArchX32:
+ return C.C_ARCH_X32
+ case ArchARM:
+ return C.C_ARCH_ARM
+ case ArchARM64:
+ return C.C_ARCH_AARCH64
+ case ArchMIPS:
+ return C.C_ARCH_MIPS
+ case ArchMIPS64:
+ return C.C_ARCH_MIPS64
+ case ArchMIPS64N32:
+ return C.C_ARCH_MIPS64N32
+ case ArchMIPSEL:
+ return C.C_ARCH_MIPSEL
+ case ArchMIPSEL64:
+ return C.C_ARCH_MIPSEL64
+ case ArchMIPSEL64N32:
+ return C.C_ARCH_MIPSEL64N32
+ case ArchPPC:
+ return C.C_ARCH_PPC
+ case ArchPPC64:
+ return C.C_ARCH_PPC64
+ case ArchPPC64LE:
+ return C.C_ARCH_PPC64LE
+ case ArchS390:
+ return C.C_ARCH_S390
+ case ArchS390X:
+ return C.C_ARCH_S390X
+ case ArchNative:
+ return C.C_ARCH_NATIVE
+ default:
+ return 0x0
+ }
+}
+
+// Only use with sanitized ops, no error handling
+func (a ScmpCompareOp) toNative() C.int {
+ switch a {
+ case CompareNotEqual:
+ return C.C_CMP_NE
+ case CompareLess:
+ return C.C_CMP_LT
+ case CompareLessOrEqual:
+ return C.C_CMP_LE
+ case CompareEqual:
+ return C.C_CMP_EQ
+ case CompareGreaterEqual:
+ return C.C_CMP_GE
+ case CompareGreater:
+ return C.C_CMP_GT
+ case CompareMaskedEqual:
+ return C.C_CMP_MASKED_EQ
+ default:
+ return 0x0
+ }
+}
+
+func actionFromNative(a C.uint32_t) (ScmpAction, error) {
+ aTmp := a & 0xFFFF
+ switch a & 0xFFFF0000 {
+ case C.C_ACT_KILL:
+ return ActKill, nil
+ case C.C_ACT_TRAP:
+ return ActTrap, nil
+ case C.C_ACT_ERRNO:
+ return ActErrno.SetReturnCode(int16(aTmp)), nil
+ case C.C_ACT_TRACE:
+ return ActTrace.SetReturnCode(int16(aTmp)), nil
+ case C.C_ACT_ALLOW:
+ return ActAllow, nil
+ default:
+ return 0x0, fmt.Errorf("unrecognized action")
+ }
+}
+
+// Only use with sanitized actions, no error handling
+func (a ScmpAction) toNative() C.uint32_t {
+ switch a & 0xFFFF {
+ case ActKill:
+ return C.C_ACT_KILL
+ case ActTrap:
+ return C.C_ACT_TRAP
+ case ActErrno:
+ return C.C_ACT_ERRNO | (C.uint32_t(a) >> 16)
+ case ActTrace:
+ return C.C_ACT_TRACE | (C.uint32_t(a) >> 16)
+ case ActAllow:
+ return C.C_ACT_ALLOW
+ default:
+ return 0x0
+ }
+}
+
+// Internal only, assumes safe attribute
+func (a scmpFilterAttr) toNative() uint32 {
+ switch a {
+ case filterAttrActDefault:
+ return uint32(C.C_ATTRIBUTE_DEFAULT)
+ case filterAttrActBadArch:
+ return uint32(C.C_ATTRIBUTE_BADARCH)
+ case filterAttrNNP:
+ return uint32(C.C_ATTRIBUTE_NNP)
+ case filterAttrTsync:
+ return uint32(C.C_ATTRIBUTE_TSYNC)
+ default:
+ return 0x0
+ }
+}
diff --git a/vendor/github.com/spf13/cobra/LICENSE.txt b/vendor/github.com/spf13/cobra/LICENSE.txt
new file mode 100644
index 0000000..298f0e2
--- /dev/null
+++ b/vendor/github.com/spf13/cobra/LICENSE.txt
@@ -0,0 +1,174 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md
new file mode 100644
index 0000000..6814a6d
--- /dev/null
+++ b/vendor/github.com/spf13/cobra/README.md
@@ -0,0 +1,928 @@
+![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png)
+
+Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files.
+
+Many of the most widely used Go projects are built using Cobra including:
+
+* [Kubernetes](http://kubernetes.io/)
+* [Hugo](http://gohugo.io)
+* [rkt](https://github.com/coreos/rkt)
+* [etcd](https://github.com/coreos/etcd)
+* [Docker (distribution)](https://github.com/docker/distribution)
+* [OpenShift](https://www.openshift.com/)
+* [Delve](https://github.com/derekparker/delve)
+* [GopherJS](http://www.gopherjs.org/)
+* [CockroachDB](http://www.cockroachlabs.com/)
+* [Bleve](http://www.blevesearch.com/)
+* [ProjectAtomic (enterprise)](http://www.projectatomic.io/)
+* [Parse (CLI)](https://parse.com/)
+* [GiantSwarm's swarm](https://github.com/giantswarm/cli)
+* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
+
+
+[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra)
+[![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra)
+[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra)
+
+![cobra](https://cloud.githubusercontent.com/assets/173412/10911369/84832a8e-8212-11e5-9f82-cc96660a4794.gif)
+
+# Overview
+
+Cobra is a library providing a simple interface to create powerful modern CLI
+interfaces similar to git & go tools.
+
+Cobra is also an application that will generate your application scaffolding to rapidly
+develop a Cobra-based application.
+
+Cobra provides:
+* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
+* Fully POSIX-compliant flags (including short & long versions)
+* Nested subcommands
+* Global, local and cascading flags
+* Easy generation of applications & commands with `cobra create appname` & `cobra add cmdname`
+* Intelligent suggestions (`app srver`... did you mean `app server`?)
+* Automatic help generation for commands and flags
+* Automatic detailed help for `app help [command]`
+* Automatic help flag recognition of `-h`, `--help`, etc.
+* Automatically generated bash autocomplete for your application
+* Automatically generated man pages for your application
+* Command aliases so you can change things without breaking them
+* The flexibilty to define your own help, usage, etc.
+* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
+
+Cobra has an exceptionally clean interface and simple design without needless
+constructors or initialization methods.
+
+Applications built with Cobra commands are designed to be as user-friendly as
+possible. Flags can be placed before or after the command (as long as a
+confusing space isn’t provided). Both short and long flags can be used. A
+command need not even be fully typed. Help is automatically generated and
+available for the application or for a specific command using either the help
+command or the `--help` flag.
+
+# Concepts
+
+Cobra is built on a structure of commands, arguments & flags.
+
+**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.
+
+The best applications will read like sentences when used. Users will know how
+to use the application because they will natively understand how to use it.
+
+The pattern to follow is
+`APPNAME VERB NOUN --ADJECTIVE.`
+ or
+`APPNAME COMMAND ARG --FLAG`
+
+A few good real world examples may better illustrate this point.
+
+In the following example, 'server' is a command, and 'port' is a flag:
+
+ > hugo server --port=1313
+
+In this command we are telling Git to clone the url bare.
+
+ > git clone URL --bare
+
+## Commands
+
+Command is the central point of the application. Each interaction that
+the application supports will be contained in a Command. A command can
+have children commands and optionally run an action.
+
+In the example above, 'server' is the command.
+
+A Command has the following structure:
+
+```go
+type Command struct {
+ Use string // The one-line usage message.
+ Short string // The short description shown in the 'help' output.
+ Long string // The long message shown in the 'help <this-command>' output.
+ Run func(cmd *Command, args []string) // Run runs the command.
+}
+```
+
+## Flags
+
+A Flag is a way to modify the behavior of a command. Cobra supports
+fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
+A Cobra command can define flags that persist through to children commands
+and flags that are only available to that command.
+
+In the example above, 'port' is the flag.
+
+Flag functionality is provided by the [pflag
+library](https://github.com/ogier/pflag), a fork of the flag standard library
+which maintains the same interface while adding POSIX compliance.
+
+## Usage
+
+Cobra works by creating a set of commands and then organizing them into a tree.
+The tree defines the structure of the application.
+
+Once each command is defined with its corresponding flags, then the
+tree is assigned to the commander which is finally executed.
+
+# Installing
+Using Cobra is easy. First, use `go get` to install the latest version
+of the library. This command will install the `cobra` generator executible
+along with the library:
+
+ > go get -v github.com/spf13/cobra/cobra
+
+Next, include Cobra in your application:
+
+```go
+import "github.com/spf13/cobra"
+```
+
+# Getting Started
+
+While you are welcome to provide your own organization, typically a Cobra based
+application will follow the following organizational structure.
+
+```
+ ▾ appName/
+ ▾ cmd/
+ add.go
+ your.go
+ commands.go
+ here.go
+ main.go
+```
+
+In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
+
+```go
+package main
+
+import "{pathToYourApp}/cmd"
+
+func main() {
+ if err := cmd.RootCmd.Execute(); err != nil {
+ fmt.Println(err)
+ os.Exit(-1)
+ }
+}
+```
+
+## Using the Cobra Generator
+
+Cobra provides its own program that will create your application and add any
+commands you want. It's the easiest way to incorporate Cobra into your application.
+
+### cobra init
+
+The `cobra init [yourApp]` command will create your initial application code
+for you. It is a very powerful application that will populate your program with
+the right structure so you can immediately enjoy all the benefits of Cobra. It
+will also automatically apply the license you specify to your application.
+
+Cobra init is pretty smart. You can provide it a full path, or simply a path
+similar to what is expected in the import.
+
+```
+cobra init github.com/spf13/newAppName
+```
+
+### cobra add
+
+Once an application is initialized Cobra can create additional commands for you.
+Let's say you created an app and you wanted the following commands for it:
+
+* app serve
+* app config
+* app config create
+
+In your project directory (where your main.go file is) you would run the following:
+
+```
+cobra add serve
+cobra add config
+cobra add create -p 'configCmd'
+```
+
+Once you have run these three commands you would have an app structure that would look like:
+
+```
+ ▾ app/
+ ▾ cmd/
+ serve.go
+ config.go
+ create.go
+ main.go
+```
+
+at this point you can run `go run main.go` and it would run your app. `go run
+main.go serve`, `go run main.go config`, `go run main.go config create` along
+with `go run main.go help serve`, etc would all work.
+
+Obviously you haven't added your own code to these yet, the commands are ready
+for you to give them their tasks. Have fun.
+
+### Configuring the cobra generator
+
+The cobra generator will be easier to use if you provide a simple configuration
+file which will help you eliminate providing a bunch of repeated information in
+flags over and over.
+
+An example ~/.cobra.yaml file:
+
+```yaml
+author: Steve Francia <spf@spf13.com>
+license: MIT
+```
+
+You can specify no license by setting `license` to `none` or you can specify
+a custom license:
+
+```yaml
+license:
+ header: This file is part of {{ .appName }}.
+ text: |
+ {{ .copyright }}
+
+ This is my license. There are many like it, but this one is mine.
+ My license is my best friend. It is my life. I must master it as I must
+ master my life.
+```
+
+## Manually implementing Cobra
+
+To manually implement cobra you need to create a bare main.go file and a RootCmd file.
+You will optionally provide additional commands as you see fit.
+
+### Create the root command
+
+The root command represents your binary itself.
+
+
+#### Manually create rootCmd
+
+Cobra doesn't require any special constructors. Simply create your commands.
+
+Ideally you place this in app/cmd/root.go:
+
+```go
+var RootCmd = &cobra.Command{
+ Use: "hugo",
+ Short: "Hugo is a very fast static site generator",
+ Long: `A Fast and Flexible Static Site Generator built with
+ love by spf13 and friends in Go.
+ Complete documentation is available at http://hugo.spf13.com`,
+ Run: func(cmd *cobra.Command, args []string) {
+ // Do Stuff Here
+ },
+}
+```
+
+You will additionally define flags and handle configuration in your init() function.
+
+for example cmd/root.go:
+
+```go
+func init() {
+ cobra.OnInitialize(initConfig)
+ RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
+ RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/")
+ RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
+ RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
+ RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
+ viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
+ viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))
+ viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
+ viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
+ viper.SetDefault("license", "apache")
+}
+```
+
+### Create your main.go
+
+With the root command you need to have your main function execute it.
+Execute should be run on the root for clarity, though it can be called on any command.
+
+In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
+
+```go
+package main
+
+import "{pathToYourApp}/cmd"
+
+func main() {
+ if err := cmd.RootCmd.Execute(); err != nil {
+ fmt.Println(err)
+ os.Exit(-1)
+ }
+}
+```
+
+
+### Create additional commands
+
+Additional commands can be defined and typically are each given their own file
+inside of the cmd/ directory.
+
+If you wanted to create a version command you would create cmd/version.go and
+populate it with the following:
+
+```go
+package cmd
+
+import (
+ "github.com/spf13/cobra"
+)
+
+func init() {
+ RootCmd.AddCommand(versionCmd)
+}
+
+var versionCmd = &cobra.Command{
+ Use: "version",
+ Short: "Print the version number of Hugo",
+ Long: `All software has versions. This is Hugo's`,
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
+ },
+}
+```
+
+### Attach command to its parent
+
+
+If you notice in the above example we attach the command to its parent. In
+this case the parent is the rootCmd. In this example we are attaching it to the
+root, but commands can be attached at any level.
+
+```go
+RootCmd.AddCommand(versionCmd)
+```
+
+### Remove a command from its parent
+
+Removing a command is not a common action in simple programs, but it allows 3rd
+parties to customize an existing command tree.
+
+In this example, we remove the existing `VersionCmd` command of an existing
+root command, and we replace it with our own version:
+
+```go
+mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)
+mainlib.RootCmd.AddCommand(versionCmd)
+```
+
+## Working with Flags
+
+Flags provide modifiers to control how the action command operates.
+
+### Assign flags to a command
+
+Since the flags are defined and used in different locations, we need to
+define a variable outside with the correct scope to assign the flag to
+work with.
+
+```go
+var Verbose bool
+var Source string
+```
+
+There are two different approaches to assign a flag.
+
+### Persistent Flags
+
+A flag can be 'persistent' meaning that this flag will be available to the
+command it's assigned to as well as every command under that command. For
+global flags, assign a flag as a persistent flag on the root.
+
+```go
+RootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
+```
+
+### Local Flags
+
+A flag can also be assigned locally which will only apply to that specific command.
+
+```go
+RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
+```
+
+### Positional Arguments
+
+Validation of positional arguments can be specified using the `Args` field, which accepts
+one of the following values:
+
+- `NoArgs` - the command will report an error if there are any positional args.
+- `ArbitraryArgs` - the command will accept any args.
+- `OnlyValidArgs` - the command will report an error if there are any positiona
+ args that are not in the `ValidArgs` list.
+- `MinimumNArgs(int)` - the command will report an error if there are not at
+ least N positional args.
+- `MaximumNArgs(int)` - the command will report an error if there are more than
+ N positional args.
+- `ExactArgs(int)` - the command will report an error if there are not
+ exactly N positional args.
+- `RangeArgs(min, max)` - the command will report an error if the number of args
+ is not between the minimum and maximum number of expected args.
+
+By default, `Args` uses the following legacy behaviour:
+- root commands with no subcommands can take arbitrary arguments
+- root commands with subcommands will do subcommand validity checking
+- subcommands will always accept arbitrary arguments and do no subsubcommand validity checking
+
+
+```go
+var HugoCmd = &cobra.Command{
+ Use: "hugo",
+ Short: "Hugo is a very fast static site generator",
+ ValidArgs: []string{"one", "two"}
+ Args: cobra.OnlyValidArgs
+ Run: func(cmd *cobra.Command, args []string) {
+ // args will only have the values one, two
+ // or the cmd.Execute() will fail.
+ },
+}
+```
+
+## Example
+
+In the example below, we have defined three commands. Two are at the top level
+and one (cmdTimes) is a child of one of the top commands. In this case the root
+is not executable meaning that a subcommand is required. This is accomplished
+by not providing a 'Run' for the 'rootCmd'.
+
+We have only defined one flag for a single command.
+
+More documentation about flags is available at https://github.com/spf13/pflag
+
+```go
+package main
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/spf13/cobra"
+)
+
+func main() {
+
+ var echoTimes int
+
+ var cmdPrint = &cobra.Command{
+ Use: "print [string to print]",
+ Short: "Print anything to the screen",
+ Long: `print is for printing anything back to the screen.
+ For many years people have printed back to the screen.
+ `,
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Println("Print: " + strings.Join(args, " "))
+ },
+ }
+
+ var cmdEcho = &cobra.Command{
+ Use: "echo [string to echo]",
+ Short: "Echo anything to the screen",
+ Long: `echo is for echoing anything back.
+ Echo works a lot like print, except it has a child command.
+ `,
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Println("Print: " + strings.Join(args, " "))
+ },
+ }
+
+ var cmdTimes = &cobra.Command{
+ Use: "times [# times] [string to echo]",
+ Short: "Echo anything to the screen more times",
+ Long: `echo things multiple times back to the user by providing
+ a count and a string.`,
+ Run: func(cmd *cobra.Command, args []string) {
+ for i := 0; i < echoTimes; i++ {
+ fmt.Println("Echo: " + strings.Join(args, " "))
+ }
+ },
+ }
+
+ cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
+
+ var rootCmd = &cobra.Command{Use: "app"}
+ rootCmd.AddCommand(cmdPrint, cmdEcho)
+ cmdEcho.AddCommand(cmdTimes)
+ rootCmd.Execute()
+}
+```
+
+For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/).
+
+## The Help Command
+
+Cobra automatically adds a help command to your application when you have subcommands.
+This will be called when a user runs 'app help'. Additionally, help will also
+support all other commands as input. Say, for instance, you have a command called
+'create' without any additional configuration; Cobra will work when 'app help
+create' is called. Every command will automatically have the '--help' flag added.
+
+### Example
+
+The following output is automatically generated by Cobra. Nothing beyond the
+command and flag definitions are needed.
+
+ > hugo help
+
+ hugo is the main command, used to build your Hugo site.
+
+ Hugo is a Fast and Flexible Static Site Generator
+ built with love by spf13 and friends in Go.
+
+ Complete documentation is available at http://gohugo.io/.
+
+ Usage:
+ hugo [flags]
+ hugo [command]
+
+ Available Commands:
+ server Hugo runs its own webserver to render the files
+ version Print the version number of Hugo
+ config Print the site configuration
+ check Check content in the source directory
+ benchmark Benchmark hugo by building a site a number of times.
+ convert Convert your content to different formats
+ new Create new content for your site
+ list Listing out various types of content
+ undraft Undraft changes the content's draft status from 'True' to 'False'
+ genautocomplete Generate shell autocompletion script for Hugo
+ gendoc Generate Markdown documentation for the Hugo CLI.
+ genman Generate man page for Hugo
+ import Import your site from others.
+
+ Flags:
+ -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
+ -D, --buildDrafts[=false]: include content marked as draft
+ -F, --buildFuture[=false]: include content with publishdate in the future
+ --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
+ --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
+ --config="": config file (default is path/config.yaml|json|toml)
+ -d, --destination="": filesystem path to write files to
+ --disableRSS[=false]: Do not build RSS files
+ --disableSitemap[=false]: Do not build Sitemap file
+ --editor="": edit new content with this editor, if provided
+ --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
+ --log[=false]: Enable Logging
+ --logFile="": Log File path (if set, logging enabled automatically)
+ --noTimes[=false]: Don't sync modification time of files
+ --pluralizeListTitles[=true]: Pluralize titles in lists using inflect
+ --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
+ -s, --source="": filesystem path to read files relative from
+ --stepAnalysis[=false]: display memory and timing of different steps of the program
+ -t, --theme="": theme to use (located in /themes/THEMENAME/)
+ --uglyURLs[=false]: if true, use /filename.html instead of /filename/
+ -v, --verbose[=false]: verbose output
+ --verboseLog[=false]: verbose logging
+ -w, --watch[=false]: watch filesystem for changes and recreate as needed
+
+ Use "hugo [command] --help" for more information about a command.
+
+
+Help is just a command like any other. There is no special logic or behavior
+around it. In fact, you can provide your own if you want.
+
+### Defining your own help
+
+You can provide your own Help command or your own template for the default command to use.
+
+The default help command is
+
+```go
+func (c *Command) initHelp() {
+ if c.helpCommand == nil {
+ c.helpCommand = &Command{
+ Use: "help [command]",
+ Short: "Help about any command",
+ Long: `Help provides help for any command in the application.
+ Simply type ` + c.Name() + ` help [path to command] for full details.`,
+ Run: c.HelpFunc(),
+ }
+ }
+ c.AddCommand(c.helpCommand)
+}
+```
+
+You can provide your own command, function or template through the following methods:
+
+```go
+command.SetHelpCommand(cmd *Command)
+
+command.SetHelpFunc(f func(*Command, []string))
+
+command.SetHelpTemplate(s string)
+```
+
+The latter two will also apply to any children commands.
+
+## Usage
+
+When the user provides an invalid flag or invalid command, Cobra responds by
+showing the user the 'usage'.
+
+### Example
+You may recognize this from the help above. That's because the default help
+embeds the usage as part of its output.
+
+ Usage:
+ hugo [flags]
+ hugo [command]
+
+ Available Commands:
+ server Hugo runs its own webserver to render the files
+ version Print the version number of Hugo
+ config Print the site configuration
+ check Check content in the source directory
+ benchmark Benchmark hugo by building a site a number of times.
+ convert Convert your content to different formats
+ new Create new content for your site
+ list Listing out various types of content
+ undraft Undraft changes the content's draft status from 'True' to 'False'
+ genautocomplete Generate shell autocompletion script for Hugo
+ gendoc Generate Markdown documentation for the Hugo CLI.
+ genman Generate man page for Hugo
+ import Import your site from others.
+
+ Flags:
+ -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
+ -D, --buildDrafts[=false]: include content marked as draft
+ -F, --buildFuture[=false]: include content with publishdate in the future
+ --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
+ --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
+ --config="": config file (default is path/config.yaml|json|toml)
+ -d, --destination="": filesystem path to write files to
+ --disableRSS[=false]: Do not build RSS files
+ --disableSitemap[=false]: Do not build Sitemap file
+ --editor="": edit new content with this editor, if provided
+ --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
+ --log[=false]: Enable Logging
+ --logFile="": Log File path (if set, logging enabled automatically)
+ --noTimes[=false]: Don't sync modification time of files
+ --pluralizeListTitles[=true]: Pluralize titles in lists using inflect
+ --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
+ -s, --source="": filesystem path to read files relative from
+ --stepAnalysis[=false]: display memory and timing of different steps of the program
+ -t, --theme="": theme to use (located in /themes/THEMENAME/)
+ --uglyURLs[=false]: if true, use /filename.html instead of /filename/
+ -v, --verbose[=false]: verbose output
+ --verboseLog[=false]: verbose logging
+ -w, --watch[=false]: watch filesystem for changes and recreate as needed
+
+### Defining your own usage
+You can provide your own usage function or template for Cobra to use.
+
+The default usage function is:
+
+```go
+return func(c *Command) error {
+ err := tmpl(c.Out(), c.UsageTemplate(), c)
+ return err
+}
+```
+
+Like help, the function and template are overridable through public methods:
+
+```go
+command.SetUsageFunc(f func(*Command) error)
+
+command.SetUsageTemplate(s string)
+```
+
+## PreRun or PostRun Hooks
+
+It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherrited by children if they do not declare their own. These function are run in the following order:
+
+- `PersistentPreRun`
+- `PreRun`
+- `Run`
+- `PostRun`
+- `PersistentPostRun`
+
+An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`:
+
+```go
+package main
+
+import (
+ "fmt"
+
+ "github.com/spf13/cobra"
+)
+
+func main() {
+
+ var rootCmd = &cobra.Command{
+ Use: "root [sub]",
+ Short: "My root command",
+ PersistentPreRun: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
+ },
+ PreRun: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
+ },
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("Inside rootCmd Run with args: %v\n", args)
+ },
+ PostRun: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
+ },
+ PersistentPostRun: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
+ },
+ }
+
+ var subCmd = &cobra.Command{
+ Use: "sub [no options!]",
+ Short: "My subcommand",
+ PreRun: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
+ },
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("Inside subCmd Run with args: %v\n", args)
+ },
+ PostRun: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
+ },
+ PersistentPostRun: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
+ },
+ }
+
+ rootCmd.AddCommand(subCmd)
+
+ rootCmd.SetArgs([]string{""})
+ _ = rootCmd.Execute()
+ fmt.Print("\n")
+ rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
+ _ = rootCmd.Execute()
+}
+```
+
+
+## Alternative Error Handling
+
+Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top,
+providing a way to handle the errors in one location. The current list of functions that return an error is:
+
+* PersistentPreRunE
+* PreRunE
+* RunE
+* PostRunE
+* PersistentPostRunE
+
+If you would like to silence the default `error` and `usage` output in favor of your own, you can set `SilenceUsage`
+and `SilenceErrors` to `false` on the command. A child command respects these flags if they are set on the parent
+command.
+
+**Example Usage using RunE:**
+
+```go
+package main
+
+import (
+ "errors"
+ "log"
+
+ "github.com/spf13/cobra"
+)
+
+func main() {
+ var rootCmd = &cobra.Command{
+ Use: "hugo",
+ Short: "Hugo is a very fast static site generator",
+ Long: `A Fast and Flexible Static Site Generator built with
+ love by spf13 and friends in Go.
+ Complete documentation is available at http://hugo.spf13.com`,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ // Do Stuff Here
+ return errors.New("some random error")
+ },
+ }
+
+ if err := rootCmd.Execute(); err != nil {
+ log.Fatal(err)
+ }
+}
+```
+
+## Suggestions when "unknown command" happens
+
+Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:
+
+```
+$ hugo srever
+Error: unknown command "srever" for "hugo"
+
+Did you mean this?
+ server
+
+Run 'hugo --help' for usage.
+```
+
+Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
+
+If you need to disable suggestions or tweak the string distance in your command, use:
+
+```go
+command.DisableSuggestions = true
+```
+
+or
+
+```go
+command.SuggestionsMinimumDistance = 1
+```
+
+You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example:
+
+```
+$ kubectl remove
+Error: unknown command "remove" for "kubectl"
+
+Did you mean this?
+ delete
+
+Run 'kubectl help' for usage.
+```
+
+## Generating Markdown-formatted documentation for your command
+
+Cobra can generate a Markdown-formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Markdown Docs](doc/md_docs.md).
+
+## Generating man pages for your command
+
+Cobra can generate a man page based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Man Docs](doc/man_docs.md).
+
+## Generating bash completions for your command
+
+Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in [Bash Completions](bash_completions.md).
+
+## Debugging
+
+Cobra provides a ‘DebugFlags’ method on a command which, when called, will print
+out everything Cobra knows about the flags for each command.
+
+### Example
+
+```go
+command.DebugFlags()
+```
+
+## Release Notes
+* **0.9.0** June 17, 2014
+ * flags can appears anywhere in the args (provided they are unambiguous)
+ * --help prints usage screen for app or command
+ * Prefix matching for commands
+ * Cleaner looking help and usage output
+ * Extensive test suite
+* **0.8.0** Nov 5, 2013
+ * Reworked interface to remove commander completely
+ * Command now primary structure
+ * No initialization needed
+ * Usage & Help templates & functions definable at any level
+ * Updated Readme
+* **0.7.0** Sept 24, 2013
+ * Needs more eyes
+ * Test suite
+ * Support for automatic error messages
+ * Support for help command
+ * Support for printing to any io.Writer instead of os.Stderr
+ * Support for persistent flags which cascade down tree
+ * Ready for integration into Hugo
+* **0.1.0** Sept 3, 2013
+ * Implement first draft
+
+## Extensions
+
+Libraries for extending Cobra:
+
+* [cmdns](https://github.com/gosuri/cmdns): Enables name spacing a command's immediate children. It provides an alternative way to structure subcommands, similar to `heroku apps:create` and `ovrclk clusters:launch`.
+
+## ToDo
+* Launch proper documentation site
+
+## Contributing
+
+1. Fork it
+2. Create your feature branch (`git checkout -b my-new-feature`)
+3. Commit your changes (`git commit -am 'Add some feature'`)
+4. Push to the branch (`git push origin my-new-feature`)
+5. Create new Pull Request
+
+## Contributors
+
+Names in no particular order:
+
+* [spf13](https://github.com/spf13),
+[eparis](https://github.com/eparis),
+[bep](https://github.com/bep), and many more!
+
+## License
+
+Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
+
+
+[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/spf13/cobra/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go
new file mode 100644
index 0000000..639fae7
--- /dev/null
+++ b/vendor/github.com/spf13/cobra/args.go
@@ -0,0 +1,98 @@
+package cobra
+
+import (
+ "fmt"
+)
+
+type PositionalArgs func(cmd *Command, args []string) error
+
+// Legacy arg validation has the following behaviour:
+// - root commands with no subcommands can take arbitrary arguments
+// - root commands with subcommands will do subcommand validity checking
+// - subcommands will always accept arbitrary arguments
+func legacyArgs(cmd *Command, args []string) error {
+ // no subcommand, always take args
+ if !cmd.HasSubCommands() {
+ return nil
+ }
+
+ // root command with subcommands, do subcommand checking
+ if !cmd.HasParent() && len(args) > 0 {
+ return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))
+ }
+ return nil
+}
+
+// NoArgs returns an error if any args are included
+func NoArgs(cmd *Command, args []string) error {
+ if len(args) > 0 {
+ return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())
+ }
+ return nil
+}
+
+// OnlyValidArgs returns an error if any args are not in the list of ValidArgs
+func OnlyValidArgs(cmd *Command, args []string) error {
+ if len(cmd.ValidArgs) > 0 {
+ for _, v := range args {
+ if !stringInSlice(v, cmd.ValidArgs) {
+ return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))
+ }
+ }
+ }
+ return nil
+}
+
+func stringInSlice(a string, list []string) bool {
+ for _, b := range list {
+ if b == a {
+ return true
+ }
+ }
+ return false
+}
+
+// ArbitraryArgs never returns an error
+func ArbitraryArgs(cmd *Command, args []string) error {
+ return nil
+}
+
+// MinimumNArgs returns an error if there is not at least N args
+func MinimumNArgs(n int) PositionalArgs {
+ return func(cmd *Command, args []string) error {
+ if len(args) < n {
+ return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args))
+ }
+ return nil
+ }
+}
+
+// MaximumNArgs returns an error if there are more than N args
+func MaximumNArgs(n int) PositionalArgs {
+ return func(cmd *Command, args []string) error {
+ if len(args) > n {
+ return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args))
+ }
+ return nil
+ }
+}
+
+// ExactArgs returns an error if there are not exactly n args
+func ExactArgs(n int) PositionalArgs {
+ return func(cmd *Command, args []string) error {
+ if len(args) != n {
+ return fmt.Errorf("accepts %d arg(s), received %d", n, len(args))
+ }
+ return nil
+ }
+}
+
+// RangeArgs returns an error if the number of args is not within the expected range
+func RangeArgs(min int, max int) PositionalArgs {
+ return func(cmd *Command, args []string) error {
+ if len(args) < min || len(args) > max {
+ return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args))
+ }
+ return nil
+ }
+}
diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go
new file mode 100644
index 0000000..236dee6
--- /dev/null
+++ b/vendor/github.com/spf13/cobra/bash_completions.go
@@ -0,0 +1,630 @@
+package cobra
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "sort"
+ "strings"
+
+ "github.com/spf13/pflag"
+)
+
+const (
+ BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions"
+ BashCompCustom = "cobra_annotation_bash_completion_custom"
+ BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
+ BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
+)
+
+func preamble(out io.Writer, name string) error {
+ _, err := fmt.Fprintf(out, "# bash completion for %-36s -*- shell-script -*-\n", name)
+ if err != nil {
+ return err
+ }
+ _, err = fmt.Fprint(out, `
+__debug()
+{
+ if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
+ echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
+ fi
+}
+
+# Homebrew on Macs have version 1.3 of bash-completion which doesn't include
+# _init_completion. This is a very minimal version of that function.
+__my_init_completion()
+{
+ COMPREPLY=()
+ _get_comp_words_by_ref "$@" cur prev words cword
+}
+
+__index_of_word()
+{
+ local w word=$1
+ shift
+ index=0
+ for w in "$@"; do
+ [[ $w = "$word" ]] && return
+ index=$((index+1))
+ done
+ index=-1
+}
+
+__contains_word()
+{
+ local w word=$1; shift
+ for w in "$@"; do
+ [[ $w = "$word" ]] && return
+ done
+ return 1
+}
+
+__handle_reply()
+{
+ __debug "${FUNCNAME[0]}"
+ case $cur in
+ -*)
+ if [[ $(type -t compopt) = "builtin" ]]; then
+ compopt -o nospace
+ fi
+ local allflags
+ if [ ${#must_have_one_flag[@]} -ne 0 ]; then
+ allflags=("${must_have_one_flag[@]}")
+ else
+ allflags=("${flags[*]} ${two_word_flags[*]}")
+ fi
+ COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") )
+ if [[ $(type -t compopt) = "builtin" ]]; then
+ [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace
+ fi
+
+ # complete after --flag=abc
+ if [[ $cur == *=* ]]; then
+ if [[ $(type -t compopt) = "builtin" ]]; then
+ compopt +o nospace
+ fi
+
+ local index flag
+ flag="${cur%%=*}"
+ __index_of_word "${flag}" "${flags_with_completion[@]}"
+ if [[ ${index} -ge 0 ]]; then
+ COMPREPLY=()
+ PREFIX=""
+ cur="${cur#*=}"
+ ${flags_completion[${index}]}
+ if [ -n "${ZSH_VERSION}" ]; then
+ # zfs completion needs --flag= prefix
+ eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
+ fi
+ fi
+ fi
+ return 0;
+ ;;
+ esac
+
+ # check if we are handling a flag with special work handling
+ local index
+ __index_of_word "${prev}" "${flags_with_completion[@]}"
+ if [[ ${index} -ge 0 ]]; then
+ ${flags_completion[${index}]}
+ return
+ fi
+
+ # we are parsing a flag and don't have a special handler, no completion
+ if [[ ${cur} != "${words[cword]}" ]]; then
+ return
+ fi
+
+ local completions
+ completions=("${commands[@]}")
+ if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
+ completions=("${must_have_one_noun[@]}")
+ fi
+ if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
+ completions+=("${must_have_one_flag[@]}")
+ fi
+ COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )
+
+ if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then
+ COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") )
+ fi
+
+ if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
+ declare -F __custom_func >/dev/null && __custom_func
+ fi
+
+ __ltrim_colon_completions "$cur"
+}
+
+# The arguments should be in the form "ext1|ext2|extn"
+__handle_filename_extension_flag()
+{
+ local ext="$1"
+ _filedir "@(${ext})"
+}
+
+__handle_subdirs_in_dir_flag()
+{
+ local dir="$1"
+ pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1
+}
+
+__handle_flag()
+{
+ __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
+
+ # if a command required a flag, and we found it, unset must_have_one_flag()
+ local flagname=${words[c]}
+ local flagvalue
+ # if the word contained an =
+ if [[ ${words[c]} == *"="* ]]; then
+ flagvalue=${flagname#*=} # take in as flagvalue after the =
+ flagname=${flagname%%=*} # strip everything after the =
+ flagname="${flagname}=" # but put the = back
+ fi
+ __debug "${FUNCNAME[0]}: looking for ${flagname}"
+ if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then
+ must_have_one_flag=()
+ fi
+
+ # if you set a flag which only applies to this command, don't show subcommands
+ if __contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then
+ commands=()
+ fi
+
+ # keep flag value with flagname as flaghash
+ if [ -n "${flagvalue}" ] ; then
+ flaghash[${flagname}]=${flagvalue}
+ elif [ -n "${words[ $((c+1)) ]}" ] ; then
+ flaghash[${flagname}]=${words[ $((c+1)) ]}
+ else
+ flaghash[${flagname}]="true" # pad "true" for bool flag
+ fi
+
+ # skip the argument to a two word flag
+ if __contains_word "${words[c]}" "${two_word_flags[@]}"; then
+ c=$((c+1))
+ # if we are looking for a flags value, don't show commands
+ if [[ $c -eq $cword ]]; then
+ commands=()
+ fi
+ fi
+
+ c=$((c+1))
+
+}
+
+__handle_noun()
+{
+ __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
+
+ if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
+ must_have_one_noun=()
+ elif __contains_word "${words[c]}" "${noun_aliases[@]}"; then
+ must_have_one_noun=()
+ fi
+
+ nouns+=("${words[c]}")
+ c=$((c+1))
+}
+
+__handle_command()
+{
+ __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
+
+ local next_command
+ if [[ -n ${last_command} ]]; then
+ next_command="_${last_command}_${words[c]//:/__}"
+ else
+ if [[ $c -eq 0 ]]; then
+ next_command="_$(basename "${words[c]//:/__}")"
+ else
+ next_command="_${words[c]//:/__}"
+ fi
+ fi
+ c=$((c+1))
+ __debug "${FUNCNAME[0]}: looking for ${next_command}"
+ declare -F $next_command >/dev/null && $next_command
+}
+
+__handle_word()
+{
+ if [[ $c -ge $cword ]]; then
+ __handle_reply
+ return
+ fi
+ __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
+ if [[ "${words[c]}" == -* ]]; then
+ __handle_flag
+ elif __contains_word "${words[c]}" "${commands[@]}"; then
+ __handle_command
+ elif [[ $c -eq 0 ]] && __contains_word "$(basename "${words[c]}")" "${commands[@]}"; then
+ __handle_command
+ else
+ __handle_noun
+ fi
+ __handle_word
+}
+
+`)
+ return err
+}
+
+func postscript(w io.Writer, name string) error {
+ name = strings.Replace(name, ":", "__", -1)
+ _, err := fmt.Fprintf(w, "__start_%s()\n", name)
+ if err != nil {
+ return err
+ }
+ _, err = fmt.Fprintf(w, `{
+ local cur prev words cword
+ declare -A flaghash 2>/dev/null || :
+ if declare -F _init_completion >/dev/null 2>&1; then
+ _init_completion -s || return
+ else
+ __my_init_completion -n "=" || return
+ fi
+
+ local c=0
+ local flags=()
+ local two_word_flags=()
+ local local_nonpersistent_flags=()
+ local flags_with_completion=()
+ local flags_completion=()
+ local commands=("%s")
+ local must_have_one_flag=()
+ local must_have_one_noun=()
+ local last_command
+ local nouns=()
+
+ __handle_word
+}
+
+`, name)
+ if err != nil {
+ return err
+ }
+ _, err = fmt.Fprintf(w, `if [[ $(type -t compopt) = "builtin" ]]; then
+ complete -o default -F __start_%s %s
+else
+ complete -o default -o nospace -F __start_%s %s
+fi
+
+`, name, name, name, name)
+ if err != nil {
+ return err
+ }
+ _, err = fmt.Fprintf(w, "# ex: ts=4 sw=4 et filetype=sh\n")
+ return err
+}
+
+func writeCommands(cmd *Command, w io.Writer) error {
+ if _, err := fmt.Fprintf(w, " commands=()\n"); err != nil {
+ return err
+ }
+ for _, c := range cmd.Commands() {
+ if !c.IsAvailableCommand() || c == cmd.helpCommand {
+ continue
+ }
+ if _, err := fmt.Fprintf(w, " commands+=(%q)\n", c.Name()); err != nil {
+ return err
+ }
+ }
+ _, err := fmt.Fprintf(w, "\n")
+ return err
+}
+
+func writeFlagHandler(name string, annotations map[string][]string, w io.Writer) error {
+ for key, value := range annotations {
+ switch key {
+ case BashCompFilenameExt:
+ _, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
+ if err != nil {
+ return err
+ }
+
+ if len(value) > 0 {
+ ext := "__handle_filename_extension_flag " + strings.Join(value, "|")
+ _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
+ } else {
+ ext := "_filedir"
+ _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
+ }
+ if err != nil {
+ return err
+ }
+ case BashCompCustom:
+ _, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
+ if err != nil {
+ return err
+ }
+ if len(value) > 0 {
+ handlers := strings.Join(value, "; ")
+ _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", handlers)
+ } else {
+ _, err = fmt.Fprintf(w, " flags_completion+=(:)\n")
+ }
+ if err != nil {
+ return err
+ }
+ case BashCompSubdirsInDir:
+ _, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
+
+ if len(value) == 1 {
+ ext := "__handle_subdirs_in_dir_flag " + value[0]
+ _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
+ } else {
+ ext := "_filedir -d"
+ _, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
+ }
+ if err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func writeShortFlag(flag *pflag.Flag, w io.Writer) error {
+ b := (len(flag.NoOptDefVal) > 0)
+ name := flag.Shorthand
+ format := " "
+ if !b {
+ format += "two_word_"
+ }
+ format += "flags+=(\"-%s\")\n"
+ if _, err := fmt.Fprintf(w, format, name); err != nil {
+ return err
+ }
+ return writeFlagHandler("-"+name, flag.Annotations, w)
+}
+
+func writeFlag(flag *pflag.Flag, w io.Writer) error {
+ b := (len(flag.NoOptDefVal) > 0)
+ name := flag.Name
+ format := " flags+=(\"--%s"
+ if !b {
+ format += "="
+ }
+ format += "\")\n"
+ if _, err := fmt.Fprintf(w, format, name); err != nil {
+ return err
+ }
+ return writeFlagHandler("--"+name, flag.Annotations, w)
+}
+
+func writeLocalNonPersistentFlag(flag *pflag.Flag, w io.Writer) error {
+ b := (len(flag.NoOptDefVal) > 0)
+ name := flag.Name
+ format := " local_nonpersistent_flags+=(\"--%s"
+ if !b {
+ format += "="
+ }
+ format += "\")\n"
+ if _, err := fmt.Fprintf(w, format, name); err != nil {
+ return err
+ }
+ return nil
+}
+
+func writeFlags(cmd *Command, w io.Writer) error {
+ _, err := fmt.Fprintf(w, ` flags=()
+ two_word_flags=()
+ local_nonpersistent_flags=()
+ flags_with_completion=()
+ flags_completion=()
+
+`)
+ if err != nil {
+ return err
+ }
+ localNonPersistentFlags := cmd.LocalNonPersistentFlags()
+ var visitErr error
+ cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
+ if err := writeFlag(flag, w); err != nil {
+ visitErr = err
+ return
+ }
+ if len(flag.Shorthand) > 0 {
+ if err := writeShortFlag(flag, w); err != nil {
+ visitErr = err
+ return
+ }
+ }
+ if localNonPersistentFlags.Lookup(flag.Name) != nil {
+ if err := writeLocalNonPersistentFlag(flag, w); err != nil {
+ visitErr = err
+ return
+ }
+ }
+ })
+ if visitErr != nil {
+ return visitErr
+ }
+ cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
+ if err := writeFlag(flag, w); err != nil {
+ visitErr = err
+ return
+ }
+ if len(flag.Shorthand) > 0 {
+ if err := writeShortFlag(flag, w); err != nil {
+ visitErr = err
+ return
+ }
+ }
+ })
+ if visitErr != nil {
+ return visitErr
+ }
+
+ _, err = fmt.Fprintf(w, "\n")
+ return err
+}
+
+func writeRequiredFlag(cmd *Command, w io.Writer) error {
+ if _, err := fmt.Fprintf(w, " must_have_one_flag=()\n"); err != nil {
+ return err
+ }
+ flags := cmd.NonInheritedFlags()
+ var visitErr error
+ flags.VisitAll(func(flag *pflag.Flag) {
+ for key := range flag.Annotations {
+ switch key {
+ case BashCompOneRequiredFlag:
+ format := " must_have_one_flag+=(\"--%s"
+ b := (flag.Value.Type() == "bool")
+ if !b {
+ format += "="
+ }
+ format += "\")\n"
+ if _, err := fmt.Fprintf(w, format, flag.Name); err != nil {
+ visitErr = err
+ return
+ }
+
+ if len(flag.Shorthand) > 0 {
+ if _, err := fmt.Fprintf(w, " must_have_one_flag+=(\"-%s\")\n", flag.Shorthand); err != nil {
+ visitErr = err
+ return
+ }
+ }
+ }
+ }
+ })
+ return visitErr
+}
+
+func writeRequiredNouns(cmd *Command, w io.Writer) error {
+ if _, err := fmt.Fprintf(w, " must_have_one_noun=()\n"); err != nil {
+ return err
+ }
+ sort.Sort(sort.StringSlice(cmd.ValidArgs))
+ for _, value := range cmd.ValidArgs {
+ if _, err := fmt.Fprintf(w, " must_have_one_noun+=(%q)\n", value); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeArgAliases(cmd *Command, w io.Writer) error {
+ if _, err := fmt.Fprintf(w, " noun_aliases=()\n"); err != nil {
+ return err
+ }
+ sort.Sort(sort.StringSlice(cmd.ArgAliases))
+ for _, value := range cmd.ArgAliases {
+ if _, err := fmt.Fprintf(w, " noun_aliases+=(%q)\n", value); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func gen(cmd *Command, w io.Writer) error {
+ for _, c := range cmd.Commands() {
+ if !c.IsAvailableCommand() || c == cmd.helpCommand {
+ continue
+ }
+ if err := gen(c, w); err != nil {
+ return err
+ }
+ }
+ commandName := cmd.CommandPath()
+ commandName = strings.Replace(commandName, " ", "_", -1)
+ commandName = strings.Replace(commandName, ":", "__", -1)
+ if _, err := fmt.Fprintf(w, "_%s()\n{\n", commandName); err != nil {
+ return err
+ }
+ if _, err := fmt.Fprintf(w, " last_command=%q\n", commandName); err != nil {
+ return err
+ }
+ if err := writeCommands(cmd, w); err != nil {
+ return err
+ }
+ if err := writeFlags(cmd, w); err != nil {
+ return err
+ }
+ if err := writeRequiredFlag(cmd, w); err != nil {
+ return err
+ }
+ if err := writeRequiredNouns(cmd, w); err != nil {
+ return err
+ }
+ if err := writeArgAliases(cmd, w); err != nil {
+ return err
+ }
+ if _, err := fmt.Fprintf(w, "}\n\n"); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (cmd *Command) GenBashCompletion(w io.Writer) error {
+ if err := preamble(w, cmd.Name()); err != nil {
+ return err
+ }
+ if len(cmd.BashCompletionFunction) > 0 {
+ if _, err := fmt.Fprintf(w, "%s\n", cmd.BashCompletionFunction); err != nil {
+ return err
+ }
+ }
+ if err := gen(cmd, w); err != nil {
+ return err
+ }
+ return postscript(w, cmd.Name())
+}
+
+func (cmd *Command) GenBashCompletionFile(filename string) error {
+ outFile, err := os.Create(filename)
+ if err != nil {
+ return err
+ }
+ defer outFile.Close()
+
+ return cmd.GenBashCompletion(outFile)
+}
+
+// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag, if it exists.
+func (cmd *Command) MarkFlagRequired(name string) error {
+ return MarkFlagRequired(cmd.Flags(), name)
+}
+
+// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag, if it exists.
+func (cmd *Command) MarkPersistentFlagRequired(name string) error {
+ return MarkFlagRequired(cmd.PersistentFlags(), name)
+}
+
+// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag in the flag set, if it exists.
+func MarkFlagRequired(flags *pflag.FlagSet, name string) error {
+ return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"})
+}
+
+// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists.
+// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
+func (cmd *Command) MarkFlagFilename(name string, extensions ...string) error {
+ return MarkFlagFilename(cmd.Flags(), name, extensions...)
+}
+
+// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
+// Generated bash autocompletion will call the bash function f for the flag.
+func (cmd *Command) MarkFlagCustom(name string, f string) error {
+ return MarkFlagCustom(cmd.Flags(), name, f)
+}
+
+// MarkPersistentFlagFilename adds the BashCompFilenameExt annotation to the named persistent flag, if it exists.
+// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
+func (cmd *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {
+ return MarkFlagFilename(cmd.PersistentFlags(), name, extensions...)
+}
+
+// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag in the flag set, if it exists.
+// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
+func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
+ return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
+}
+
+// MarkFlagCustom adds the BashCompCustom annotation to the named flag in the flag set, if it exists.
+// Generated bash autocompletion will call the bash function f for the flag.
+func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {
+ return flags.SetAnnotation(name, BashCompCustom, []string{f})
+}
diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go
new file mode 100644
index 0000000..93a2c0f
--- /dev/null
+++ b/vendor/github.com/spf13/cobra/cobra.go
@@ -0,0 +1,175 @@
+// Copyright © 2013 Steve Francia <spf@spf13.com>.
+//
+// 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.
+
+// Commands similar to git, go tools and other modern CLI tools
+// inspired by go, go-Commander, gh and subcommand
+
+package cobra
+
+import (
+ "fmt"
+ "io"
+ "reflect"
+ "strconv"
+ "strings"
+ "text/template"
+ "unicode"
+)
+
+var templateFuncs = template.FuncMap{
+ "trim": strings.TrimSpace,
+ "trimRightSpace": trimRightSpace,
+ "appendIfNotPresent": appendIfNotPresent,
+ "rpad": rpad,
+ "gt": Gt,
+ "eq": Eq,
+}
+
+var initializers []func()
+
+// automatic prefix matching can be a dangerous thing to automatically enable in CLI tools.
+// Set this to true to enable it
+var EnablePrefixMatching = false
+
+//EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
+//To disable sorting, set it to false.
+var EnableCommandSorting = true
+
+//AddTemplateFunc adds a template function that's available to Usage and Help
+//template generation.
+func AddTemplateFunc(name string, tmplFunc interface{}) {
+ templateFuncs[name] = tmplFunc
+}
+
+//AddTemplateFuncs adds multiple template functions availalble to Usage and
+//Help template generation.
+func AddTemplateFuncs(tmplFuncs template.FuncMap) {
+ for k, v := range tmplFuncs {
+ templateFuncs[k] = v
+ }
+}
+
+//OnInitialize takes a series of func() arguments and appends them to a slice of func().
+func OnInitialize(y ...func()) {
+ for _, x := range y {
+ initializers = append(initializers, x)
+ }
+}
+
+//Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
+//Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
+//ints and then compared.
+func Gt(a interface{}, b interface{}) bool {
+ var left, right int64
+ av := reflect.ValueOf(a)
+
+ switch av.Kind() {
+ case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
+ left = int64(av.Len())
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ left = av.Int()
+ case reflect.String:
+ left, _ = strconv.ParseInt(av.String(), 10, 64)
+ }
+
+ bv := reflect.ValueOf(b)
+
+ switch bv.Kind() {
+ case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
+ right = int64(bv.Len())
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ right = bv.Int()
+ case reflect.String:
+ right, _ = strconv.ParseInt(bv.String(), 10, 64)
+ }
+
+ return left > right
+}
+
+//Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
+func Eq(a interface{}, b interface{}) bool {
+ av := reflect.ValueOf(a)
+ bv := reflect.ValueOf(b)
+
+ switch av.Kind() {
+ case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
+ panic("Eq called on unsupported type")
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ return av.Int() == bv.Int()
+ case reflect.String:
+ return av.String() == bv.String()
+ }
+ return false
+}
+
+func trimRightSpace(s string) string {
+ return strings.TrimRightFunc(s, unicode.IsSpace)
+}
+
+// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s
+func appendIfNotPresent(s, stringToAppend string) string {
+ if strings.Contains(s, stringToAppend) {
+ return s
+ }
+ return s + " " + stringToAppend
+}
+
+//rpad adds padding to the right of a string
+func rpad(s string, padding int) string {
+ template := fmt.Sprintf("%%-%ds", padding)
+ return fmt.Sprintf(template, s)
+}
+
+// tmpl executes the given template text on data, writing the result to w.
+func tmpl(w io.Writer, text string, data interface{}) error {
+ t := template.New("top")
+ t.Funcs(templateFuncs)
+ template.Must(t.Parse(text))
+ return t.Execute(w, data)
+}
+
+// ld compares two strings and returns the levenshtein distance between them
+func ld(s, t string, ignoreCase bool) int {
+ if ignoreCase {
+ s = strings.ToLower(s)
+ t = strings.ToLower(t)
+ }
+ d := make([][]int, len(s)+1)
+ for i := range d {
+ d[i] = make([]int, len(t)+1)
+ }
+ for i := range d {
+ d[i][0] = i
+ }
+ for j := range d[0] {
+ d[0][j] = j
+ }
+ for j := 1; j <= len(t); j++ {
+ for i := 1; i <= len(s); i++ {
+ if s[i-1] == t[j-1] {
+ d[i][j] = d[i-1][j-1]
+ } else {
+ min := d[i-1][j]
+ if d[i][j-1] < min {
+ min = d[i][j-1]
+ }
+ if d[i-1][j-1] < min {
+ min = d[i-1][j-1]
+ }
+ d[i][j] = min + 1
+ }
+ }
+
+ }
+ return d[len(s)][len(t)]
+}
diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go
new file mode 100644
index 0000000..2887208
--- /dev/null
+++ b/vendor/github.com/spf13/cobra/command.go
@@ -0,0 +1,1359 @@
+// Copyright © 2013 Steve Francia <spf@spf13.com>.
+//
+// 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 cobra is a commander providing a simple interface to create powerful modern CLI interfaces.
+//In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
+package cobra
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ flag "github.com/spf13/pflag"
+)
+
+// Command is just that, a command for your application.
+// eg. 'go run' ... 'run' is the command. Cobra requires
+// you to define the usage and description as part of your command
+// definition to ensure usability.
+type Command struct {
+ // Name is the command name, usually the executable's name.
+ name string
+ // The one-line usage message.
+ Use string
+ // An array of aliases that can be used instead of the first word in Use.
+ Aliases []string
+ // An array of command names for which this command will be suggested - similar to aliases but only suggests.
+ SuggestFor []string
+ // The short description shown in the 'help' output.
+ Short string
+ // The long message shown in the 'help <this-command>' output.
+ Long string
+ // Examples of how to use the command
+ Example string
+ // List of all valid non-flag arguments that are accepted in bash completions
+ ValidArgs []string
+ // List of aliases for ValidArgs. These are not suggested to the user in the bash
+ // completion, but accepted if entered manually.
+ ArgAliases []string
+ // Expected arguments
+ Args PositionalArgs
+ // Custom functions used by the bash autocompletion generator
+ BashCompletionFunction string
+ // Is this command deprecated and should print this string when used?
+ Deprecated string
+ // Is this command hidden and should NOT show up in the list of available commands?
+ Hidden bool
+ // Tags are key/value pairs that can be used by applications to identify or
+ // group commands
+ Tags map[string]string
+ // Full set of flags
+ flags *flag.FlagSet
+ // Set of flags childrens of this command will inherit
+ pflags *flag.FlagSet
+ // Flags that are declared specifically by this command (not inherited).
+ lflags *flag.FlagSet
+ // SilenceErrors is an option to quiet errors down stream
+ SilenceErrors bool
+ // Silence Usage is an option to silence usage when an error occurs.
+ SilenceUsage bool
+ // The *Run functions are executed in the following order:
+ // * PersistentPreRun()
+ // * PreRun()
+ // * Run()
+ // * PostRun()
+ // * PersistentPostRun()
+ // All functions get the same args, the arguments after the command name
+ // PersistentPreRun: children of this command will inherit and execute
+ PersistentPreRun func(cmd *Command, args []string)
+ // PersistentPreRunE: PersistentPreRun but returns an error
+ PersistentPreRunE func(cmd *Command, args []string) error
+ // PreRun: children of this command will not inherit.
+ PreRun func(cmd *Command, args []string)
+ // PreRunE: PreRun but returns an error
+ PreRunE func(cmd *Command, args []string) error
+ // Run: Typically the actual work function. Most commands will only implement this
+ Run func(cmd *Command, args []string)
+ // RunE: Run but returns an error
+ RunE func(cmd *Command, args []string) error
+ // PostRun: run after the Run command.
+ PostRun func(cmd *Command, args []string)
+ // PostRunE: PostRun but returns an error
+ PostRunE func(cmd *Command, args []string) error
+ // PersistentPostRun: children of this command will inherit and execute after PostRun
+ PersistentPostRun func(cmd *Command, args []string)
+ // PersistentPostRunE: PersistentPostRun but returns an error
+ PersistentPostRunE func(cmd *Command, args []string) error
+ // DisableAutoGenTag remove
+ DisableAutoGenTag bool
+ // Commands is the list of commands supported by this program.
+ commands []*Command
+ // Parent Command for this command
+ parent *Command
+ // max lengths of commands' string lengths for use in padding
+ commandsMaxUseLen int
+ commandsMaxCommandPathLen int
+ commandsMaxNameLen int
+ // is commands slice are sorted or not
+ commandsAreSorted bool
+
+ flagErrorBuf *bytes.Buffer
+
+ args []string // actual args parsed from flags
+ output *io.Writer // nil means stderr; use Out() method instead
+ usageFunc func(*Command) error // Usage can be defined by application
+ usageTemplate string // Can be defined by Application
+ flagErrorFunc func(*Command, error) error
+ helpTemplate string // Can be defined by Application
+ helpFunc func(*Command, []string) // Help can be defined by application
+ helpCommand *Command // The help command
+ // The global normalization function that we can use on every pFlag set and children commands
+ globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName
+
+ // Disable the suggestions based on Levenshtein distance that go along with 'unknown command' messages
+ DisableSuggestions bool
+ // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0
+ SuggestionsMinimumDistance int
+
+ // Disable the flag parsing. If this is true all flags will be passed to the command as arguments.
+ DisableFlagParsing bool
+
+ // TraverseChildren parses flags on all parents before executing child command
+ TraverseChildren bool
+}
+
+// os.Args[1:] by default, if desired, can be overridden
+// particularly useful when testing.
+func (c *Command) SetArgs(a []string) {
+ c.args = a
+}
+
+func (c *Command) getOut(def io.Writer) io.Writer {
+ if c.output != nil {
+ return *c.output
+ }
+
+ if c.HasParent() {
+ return c.parent.Out()
+ }
+ return def
+}
+
+func (c *Command) Out() io.Writer {
+ return c.getOut(os.Stderr)
+}
+
+func (c *Command) getOutOrStdout() io.Writer {
+ return c.getOut(os.Stdout)
+}
+
+// SetOutput sets the destination for usage and error messages.
+// If output is nil, os.Stderr is used.
+func (c *Command) SetOutput(output io.Writer) {
+ c.output = &output
+}
+
+// Usage can be defined by application
+func (c *Command) SetUsageFunc(f func(*Command) error) {
+ c.usageFunc = f
+}
+
+// Can be defined by Application
+func (c *Command) SetUsageTemplate(s string) {
+ c.usageTemplate = s
+}
+
+// SetFlagErrorFunc sets a function to generate an error when flag parsing
+// fails
+func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
+ c.flagErrorFunc = f
+}
+
+// Can be defined by Application
+func (c *Command) SetHelpFunc(f func(*Command, []string)) {
+ c.helpFunc = f
+}
+
+func (c *Command) SetHelpCommand(cmd *Command) {
+ c.helpCommand = cmd
+}
+
+// Can be defined by Application
+func (c *Command) SetHelpTemplate(s string) {
+ c.helpTemplate = s
+}
+
+// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
+// The user should not have a cyclic dependency on commands.
+func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
+ c.Flags().SetNormalizeFunc(n)
+ c.PersistentFlags().SetNormalizeFunc(n)
+ c.globNormFunc = n
+
+ for _, command := range c.commands {
+ command.SetGlobalNormalizationFunc(n)
+ }
+}
+
+func (c *Command) UsageFunc() (f func(*Command) error) {
+ if c.usageFunc != nil {
+ return c.usageFunc
+ }
+
+ if c.HasParent() {
+ return c.parent.UsageFunc()
+ }
+ return func(c *Command) error {
+ err := tmpl(c.Out(), c.UsageTemplate(), c)
+ if err != nil {
+ fmt.Print(err)
+ }
+ return err
+ }
+}
+
+// HelpFunc returns either the function set by SetHelpFunc for this command
+// or a parent, or it returns a function which calls c.Help()
+func (c *Command) HelpFunc() func(*Command, []string) {
+ cmd := c
+ for cmd != nil {
+ if cmd.helpFunc != nil {
+ return cmd.helpFunc
+ }
+ cmd = cmd.parent
+ }
+ return func(*Command, []string) {
+ err := c.Help()
+ if err != nil {
+ c.Println(err)
+ }
+ }
+}
+
+// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
+// command or a parent, or it returns a function which returns the original
+// error.
+func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
+ if c.flagErrorFunc != nil {
+ return c.flagErrorFunc
+ }
+
+ if c.HasParent() {
+ return c.parent.FlagErrorFunc()
+ }
+ return func(c *Command, err error) error {
+ return err
+ }
+}
+
+var minUsagePadding = 25
+
+func (c *Command) UsagePadding() int {
+ if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
+ return minUsagePadding
+ }
+ return c.parent.commandsMaxUseLen
+}
+
+var minCommandPathPadding = 11
+
+//
+func (c *Command) CommandPathPadding() int {
+ if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
+ return minCommandPathPadding
+ }
+ return c.parent.commandsMaxCommandPathLen
+}
+
+var minNamePadding = 11
+
+func (c *Command) NamePadding() int {
+ if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
+ return minNamePadding
+ }
+ return c.parent.commandsMaxNameLen
+}
+
+func (c *Command) UsageTemplate() string {
+ if c.usageTemplate != "" {
+ return c.usageTemplate
+ }
+
+ if c.HasParent() {
+ return c.parent.UsageTemplate()
+ }
+ return `Usage:{{if .Runnable}}
+ {{if .HasAvailableFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
+ {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
+
+Aliases:
+ {{.NameAndAliases}}
+{{end}}{{if .HasExample}}
+
+Examples:
+{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}
+
+Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}
+ {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableLocalFlags}}
+
+Flags:
+{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasAvailableInheritedFlags}}
+
+Global Flags:
+{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
+
+Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
+ {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }}
+
+Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
+`
+}
+
+func (c *Command) HelpTemplate() string {
+ if c.helpTemplate != "" {
+ return c.helpTemplate
+ }
+
+ if c.HasParent() {
+ return c.parent.HelpTemplate()
+ }
+ return `{{with or .Long .Short }}{{. | trim}}
+
+{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
+}
+
+// Really only used when casting a command to a commander
+func (c *Command) resetChildrensParents() {
+ for _, x := range c.commands {
+ x.parent = c
+ }
+}
+
+// Test if the named flag is a boolean flag.
+func isBooleanFlag(name string, f *flag.FlagSet) bool {
+ flag := f.Lookup(name)
+ if flag == nil {
+ return false
+ }
+ return flag.Value.Type() == "bool"
+}
+
+// Test if the named flag is a boolean flag.
+func isBooleanShortFlag(name string, f *flag.FlagSet) bool {
+ result := false
+ f.VisitAll(func(f *flag.Flag) {
+ if f.Shorthand == name && f.Value.Type() == "bool" {
+ result = true
+ }
+ })
+ return result
+}
+
+func stripFlags(args []string, c *Command) []string {
+ if len(args) < 1 {
+ return args
+ }
+ c.mergePersistentFlags()
+
+ commands := []string{}
+
+ inQuote := false
+ inFlag := false
+ for _, y := range args {
+ if !inQuote {
+ switch {
+ case strings.HasPrefix(y, "\""):
+ inQuote = true
+ case strings.Contains(y, "=\""):
+ inQuote = true
+ case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
+ // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
+ inFlag = !isBooleanFlag(y[2:], c.Flags())
+ case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):
+ inFlag = true
+ case inFlag:
+ inFlag = false
+ case y == "":
+ // strip empty commands, as the go tests expect this to be ok....
+ case !strings.HasPrefix(y, "-"):
+ commands = append(commands, y)
+ inFlag = false
+ }
+ }
+
+ if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {
+ inQuote = false
+ }
+ }
+
+ return commands
+}
+
+// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
+// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
+func argsMinusFirstX(args []string, x string) []string {
+ for i, y := range args {
+ if x == y {
+ ret := []string{}
+ ret = append(ret, args[:i]...)
+ ret = append(ret, args[i+1:]...)
+ return ret
+ }
+ }
+ return args
+}
+
+func isFlagArg(arg string) bool {
+ return ((len(arg) >= 3 && arg[1] == '-') ||
+ (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
+}
+
+// Find the target command given the args and command tree
+// Meant to be run on the highest node. Only searches down.
+func (c *Command) Find(args []string) (*Command, []string, error) {
+ var innerfind func(*Command, []string) (*Command, []string)
+
+ innerfind = func(c *Command, innerArgs []string) (*Command, []string) {
+ argsWOflags := stripFlags(innerArgs, c)
+ if len(argsWOflags) == 0 {
+ return c, innerArgs
+ }
+ nextSubCmd := argsWOflags[0]
+
+ cmd := c.findNext(nextSubCmd)
+ if cmd != nil {
+ return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))
+ }
+ return c, innerArgs
+ }
+
+ commandFound, a := innerfind(c, args)
+ if commandFound.Args == nil {
+ return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))
+ }
+ return commandFound, a, nil
+}
+
+func (c *Command) findNext(next string) *Command {
+ matches := make([]*Command, 0)
+ for _, cmd := range c.commands {
+ if cmd.Name() == next || cmd.HasAlias(next) {
+ return cmd
+ }
+ if EnablePrefixMatching && cmd.HasNameOrAliasPrefix(next) {
+ matches = append(matches, cmd)
+ }
+ }
+
+ if len(matches) == 1 {
+ return matches[0]
+ }
+ return nil
+}
+
+// Traverse the command tree to find the command, and parse args for
+// each parent.
+func (c *Command) Traverse(args []string) (*Command, []string, error) {
+ flags := []string{}
+ inFlag := false
+
+ for i, arg := range args {
+ switch {
+ // A long flag with a space separated value
+ case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):
+ // TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
+ inFlag = !isBooleanFlag(arg[2:], c.Flags())
+ flags = append(flags, arg)
+ continue
+ // A short flag with a space separated value
+ case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !isBooleanShortFlag(arg[1:], c.Flags()):
+ inFlag = true
+ flags = append(flags, arg)
+ continue
+ // The value for a flag
+ case inFlag:
+ inFlag = false
+ flags = append(flags, arg)
+ continue
+ // A flag without a value, or with an `=` separated value
+ case isFlagArg(arg):
+ flags = append(flags, arg)
+ continue
+ }
+
+ cmd := c.findNext(arg)
+ if cmd == nil {
+ return c, args, nil
+ }
+
+ if err := c.ParseFlags(flags); err != nil {
+ return nil, args, err
+ }
+ return cmd.Traverse(args[i+1:])
+ }
+ return c, args, nil
+}
+
+func (c *Command) findSuggestions(arg string) string {
+ if c.DisableSuggestions {
+ return ""
+ }
+ if c.SuggestionsMinimumDistance <= 0 {
+ c.SuggestionsMinimumDistance = 2
+ }
+ suggestionsString := ""
+ if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {
+ suggestionsString += "\n\nDid you mean this?\n"
+ for _, s := range suggestions {
+ suggestionsString += fmt.Sprintf("\t%v\n", s)
+ }
+ }
+ return suggestionsString
+}
+
+func (c *Command) SuggestionsFor(typedName string) []string {
+ suggestions := []string{}
+ for _, cmd := range c.commands {
+ if cmd.IsAvailableCommand() {
+ levenshteinDistance := ld(typedName, cmd.Name(), true)
+ suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance
+ suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))
+ if suggestByLevenshtein || suggestByPrefix {
+ suggestions = append(suggestions, cmd.Name())
+ }
+ for _, explicitSuggestion := range cmd.SuggestFor {
+ if strings.EqualFold(typedName, explicitSuggestion) {
+ suggestions = append(suggestions, cmd.Name())
+ }
+ }
+ }
+ }
+ return suggestions
+}
+
+func (c *Command) VisitParents(fn func(*Command)) {
+ var traverse func(*Command) *Command
+
+ traverse = func(x *Command) *Command {
+ if x != c {
+ fn(x)
+ }
+ if x.HasParent() {
+ return traverse(x.parent)
+ }
+ return x
+ }
+ traverse(c)
+}
+
+func (c *Command) Root() *Command {
+ var findRoot func(*Command) *Command
+
+ findRoot = func(x *Command) *Command {
+ if x.HasParent() {
+ return findRoot(x.parent)
+ }
+ return x
+ }
+
+ return findRoot(c)
+}
+
+// ArgsLenAtDash will return the length of f.Args at the moment when a -- was
+// found during arg parsing. This allows your program to know which args were
+// before the -- and which came after. (Description from
+// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).
+func (c *Command) ArgsLenAtDash() int {
+ return c.Flags().ArgsLenAtDash()
+}
+
+func (c *Command) execute(a []string) (err error) {
+ if c == nil {
+ return fmt.Errorf("Called Execute() on a nil Command")
+ }
+
+ if len(c.Deprecated) > 0 {
+ c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
+ }
+
+ // initialize help flag as the last point possible to allow for user
+ // overriding
+ c.initHelpFlag()
+
+ err = c.ParseFlags(a)
+ if err != nil {
+ return c.FlagErrorFunc()(c, err)
+ }
+ // If help is called, regardless of other flags, return we want help
+ // Also say we need help if the command isn't runnable.
+ helpVal, err := c.Flags().GetBool("help")
+ if err != nil {
+ // should be impossible to get here as we always declare a help
+ // flag in initHelpFlag()
+ c.Println("\"help\" flag declared as non-bool. Please correct your code")
+ return err
+ }
+ if helpVal || !c.Runnable() {
+ return flag.ErrHelp
+ }
+
+ c.preRun()
+
+ argWoFlags := c.Flags().Args()
+ if c.DisableFlagParsing {
+ argWoFlags = a
+ }
+
+ if err := c.ValidateArgs(argWoFlags); err != nil {
+ return err
+ }
+
+ for p := c; p != nil; p = p.Parent() {
+ if p.PersistentPreRunE != nil {
+ if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
+ return err
+ }
+ break
+ } else if p.PersistentPreRun != nil {
+ p.PersistentPreRun(c, argWoFlags)
+ break
+ }
+ }
+ if c.PreRunE != nil {
+ if err := c.PreRunE(c, argWoFlags); err != nil {
+ return err
+ }
+ } else if c.PreRun != nil {
+ c.PreRun(c, argWoFlags)
+ }
+
+ if c.RunE != nil {
+ if err := c.RunE(c, argWoFlags); err != nil {
+ return err
+ }
+ } else {
+ c.Run(c, argWoFlags)
+ }
+ if c.PostRunE != nil {
+ if err := c.PostRunE(c, argWoFlags); err != nil {
+ return err
+ }
+ } else if c.PostRun != nil {
+ c.PostRun(c, argWoFlags)
+ }
+ for p := c; p != nil; p = p.Parent() {
+ if p.PersistentPostRunE != nil {
+ if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
+ return err
+ }
+ break
+ } else if p.PersistentPostRun != nil {
+ p.PersistentPostRun(c, argWoFlags)
+ break
+ }
+ }
+
+ return nil
+}
+
+func (c *Command) preRun() {
+ for _, x := range initializers {
+ x()
+ }
+}
+
+func (c *Command) errorMsgFromParse() string {
+ s := c.flagErrorBuf.String()
+
+ x := strings.Split(s, "\n")
+
+ if len(x) > 0 {
+ return x[0]
+ }
+ return ""
+}
+
+// Call execute to use the args (os.Args[1:] by default)
+// and run through the command tree finding appropriate matches
+// for commands and then corresponding flags.
+func (c *Command) Execute() error {
+ _, err := c.ExecuteC()
+ return err
+}
+
+func (c *Command) ExecuteC() (cmd *Command, err error) {
+
+ // Regardless of what command execute is called on, run on Root only
+ if c.HasParent() {
+ return c.Root().ExecuteC()
+ }
+
+ // windows hook
+ if preExecHookFn != nil {
+ preExecHookFn(c)
+ }
+
+ // initialize help as the last point possible to allow for user
+ // overriding
+ c.initHelpCmd()
+
+ var args []string
+
+ // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
+ if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {
+ args = os.Args[1:]
+ } else {
+ args = c.args
+ }
+
+ var flags []string
+ if c.TraverseChildren {
+ cmd, flags, err = c.Traverse(args)
+ } else {
+ cmd, flags, err = c.Find(args)
+ }
+ if err != nil {
+ // If found parse to a subcommand and then failed, talk about the subcommand
+ if cmd != nil {
+ c = cmd
+ }
+ if !c.SilenceErrors {
+ c.Println("Error:", err.Error())
+ c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
+ }
+ return c, err
+ }
+
+ err = cmd.execute(flags)
+ if err != nil {
+ // Always show help if requested, even if SilenceErrors is in
+ // effect
+ if err == flag.ErrHelp {
+ cmd.HelpFunc()(cmd, args)
+ return cmd, nil
+ }
+
+ // If root command has SilentErrors flagged,
+ // all subcommands should respect it
+ if !cmd.SilenceErrors && !c.SilenceErrors {
+ c.Println("Error:", err.Error())
+ }
+
+ // If root command has SilentUsage flagged,
+ // all subcommands should respect it
+ if !cmd.SilenceUsage && !c.SilenceUsage {
+ c.Println(cmd.UsageString())
+ }
+ return cmd, err
+ }
+ return cmd, nil
+}
+
+func (c *Command) ValidateArgs(args []string) error {
+ if c.Args == nil {
+ return nil
+ }
+ return c.Args(c, args)
+}
+
+func (c *Command) initHelpFlag() {
+ c.mergePersistentFlags()
+ if c.Flags().Lookup("help") == nil {
+ c.Flags().BoolP("help", "h", false, "help for "+c.Name())
+ }
+}
+
+func (c *Command) initHelpCmd() {
+ if c.helpCommand == nil {
+ if !c.HasSubCommands() {
+ return
+ }
+
+ c.helpCommand = &Command{
+ Use: "help [command]",
+ Short: "Help about any command",
+ Long: `Help provides help for any command in the application.
+ Simply type ` + c.Name() + ` help [path to command] for full details.`,
+ PersistentPreRun: func(cmd *Command, args []string) {},
+ PersistentPostRun: func(cmd *Command, args []string) {},
+
+ Run: func(c *Command, args []string) {
+ cmd, _, e := c.Root().Find(args)
+ if cmd == nil || e != nil {
+ c.Printf("Unknown help topic %#q.", args)
+ c.Root().Usage()
+ } else {
+ helpFunc := cmd.HelpFunc()
+ helpFunc(cmd, args)
+ }
+ },
+ }
+ }
+ c.AddCommand(c.helpCommand)
+}
+
+// Used for testing
+func (c *Command) ResetCommands() {
+ c.commands = nil
+ c.helpCommand = nil
+}
+
+// Sorts commands by their names
+type commandSorterByName []*Command
+
+func (c commandSorterByName) Len() int { return len(c) }
+func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
+func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }
+
+// Commands returns a sorted slice of child commands.
+func (c *Command) Commands() []*Command {
+ // do not sort commands if it already sorted or sorting was disabled
+ if EnableCommandSorting && !c.commandsAreSorted {
+ sort.Sort(commandSorterByName(c.commands))
+ c.commandsAreSorted = true
+ }
+ return c.commands
+}
+
+// AddCommand adds one or more commands to this parent command.
+func (c *Command) AddCommand(cmds ...*Command) {
+ for i, x := range cmds {
+ if cmds[i] == c {
+ panic("Command can't be a child of itself")
+ }
+ cmds[i].parent = c
+ // update max lengths
+ usageLen := len(x.Use)
+ if usageLen > c.commandsMaxUseLen {
+ c.commandsMaxUseLen = usageLen
+ }
+ commandPathLen := len(x.CommandPath())
+ if commandPathLen > c.commandsMaxCommandPathLen {
+ c.commandsMaxCommandPathLen = commandPathLen
+ }
+ nameLen := len(x.Name())
+ if nameLen > c.commandsMaxNameLen {
+ c.commandsMaxNameLen = nameLen
+ }
+ // If global normalization function exists, update all children
+ if c.globNormFunc != nil {
+ x.SetGlobalNormalizationFunc(c.globNormFunc)
+ }
+ c.commands = append(c.commands, x)
+ c.commandsAreSorted = false
+ }
+}
+
+// RemoveCommand removes one or more commands from a parent command.
+func (c *Command) RemoveCommand(cmds ...*Command) {
+ commands := []*Command{}
+main:
+ for _, command := range c.commands {
+ for _, cmd := range cmds {
+ if command == cmd {
+ command.parent = nil
+ continue main
+ }
+ }
+ commands = append(commands, command)
+ }
+ c.commands = commands
+ // recompute all lengths
+ c.commandsMaxUseLen = 0
+ c.commandsMaxCommandPathLen = 0
+ c.commandsMaxNameLen = 0
+ for _, command := range c.commands {
+ usageLen := len(command.Use)
+ if usageLen > c.commandsMaxUseLen {
+ c.commandsMaxUseLen = usageLen
+ }
+ commandPathLen := len(command.CommandPath())
+ if commandPathLen > c.commandsMaxCommandPathLen {
+ c.commandsMaxCommandPathLen = commandPathLen
+ }
+ nameLen := len(command.Name())
+ if nameLen > c.commandsMaxNameLen {
+ c.commandsMaxNameLen = nameLen
+ }
+ }
+}
+
+// Print is a convenience method to Print to the defined output
+func (c *Command) Print(i ...interface{}) {
+ fmt.Fprint(c.Out(), i...)
+}
+
+// Println is a convenience method to Println to the defined output
+func (c *Command) Println(i ...interface{}) {
+ str := fmt.Sprintln(i...)
+ c.Print(str)
+}
+
+// Printf is a convenience method to Printf to the defined output
+func (c *Command) Printf(format string, i ...interface{}) {
+ str := fmt.Sprintf(format, i...)
+ c.Print(str)
+}
+
+// Output the usage for the command
+// Used when a user provides invalid input
+// Can be defined by user by overriding UsageFunc
+func (c *Command) Usage() error {
+ c.mergePersistentFlags()
+ err := c.UsageFunc()(c)
+ return err
+}
+
+// Output the help for the command
+// Used when a user calls help [command]
+// by the default HelpFunc in the commander
+func (c *Command) Help() error {
+ c.mergePersistentFlags()
+ err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)
+ return err
+}
+
+func (c *Command) UsageString() string {
+ tmpOutput := c.output
+ bb := new(bytes.Buffer)
+ c.SetOutput(bb)
+ c.Usage()
+ c.output = tmpOutput
+ return bb.String()
+}
+
+// CommandPath returns the full path to this command.
+func (c *Command) CommandPath() string {
+ str := c.Name()
+ x := c
+ for x.HasParent() {
+ str = x.parent.Name() + " " + str
+ x = x.parent
+ }
+ return str
+}
+
+//The full usage for a given command (including parents)
+func (c *Command) UseLine() string {
+ str := ""
+ if c.HasParent() {
+ str = c.parent.CommandPath() + " "
+ }
+ return str + c.Use
+}
+
+// For use in determining which flags have been assigned to which commands
+// and which persist
+func (c *Command) DebugFlags() {
+ c.Println("DebugFlags called on", c.Name())
+ var debugflags func(*Command)
+
+ debugflags = func(x *Command) {
+ if x.HasFlags() || x.HasPersistentFlags() {
+ c.Println(x.Name())
+ }
+ if x.HasFlags() {
+ x.flags.VisitAll(func(f *flag.Flag) {
+ if x.HasPersistentFlags() {
+ if x.persistentFlag(f.Name) == nil {
+ c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")
+ } else {
+ c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")
+ }
+ } else {
+ c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")
+ }
+ })
+ }
+ if x.HasPersistentFlags() {
+ x.pflags.VisitAll(func(f *flag.Flag) {
+ if x.HasFlags() {
+ if x.flags.Lookup(f.Name) == nil {
+ c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
+ }
+ } else {
+ c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
+ }
+ })
+ }
+ c.Println(x.flagErrorBuf)
+ if x.HasSubCommands() {
+ for _, y := range x.commands {
+ debugflags(y)
+ }
+ }
+ }
+
+ debugflags(c)
+}
+
+// Name returns the command's name: the first word in the use line.
+func (c *Command) Name() string {
+ if c.name != "" {
+ return c.name
+ }
+ name := c.Use
+ i := strings.Index(name, " ")
+ if i >= 0 {
+ name = name[:i]
+ }
+ return name
+}
+
+// HasAlias determines if a given string is an alias of the command.
+func (c *Command) HasAlias(s string) bool {
+ for _, a := range c.Aliases {
+ if a == s {
+ return true
+ }
+ }
+ return false
+}
+
+// HasNameOrAliasPrefix returns true if the Name or any of aliases start
+// with prefix
+func (c *Command) HasNameOrAliasPrefix(prefix string) bool {
+ if strings.HasPrefix(c.Name(), prefix) {
+ return true
+ }
+ for _, alias := range c.Aliases {
+ if strings.HasPrefix(alias, prefix) {
+ return true
+ }
+ }
+ return false
+}
+
+func (c *Command) NameAndAliases() string {
+ return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
+}
+
+func (c *Command) HasExample() bool {
+ return len(c.Example) > 0
+}
+
+// Runnable determines if the command is itself runnable
+func (c *Command) Runnable() bool {
+ return c.Run != nil || c.RunE != nil
+}
+
+// HasSubCommands determines if the command has children commands
+func (c *Command) HasSubCommands() bool {
+ return len(c.commands) > 0
+}
+
+// IsAvailableCommand determines if a command is available as a non-help command
+// (this includes all non deprecated/hidden commands)
+func (c *Command) IsAvailableCommand() bool {
+ if len(c.Deprecated) != 0 || c.Hidden {
+ return false
+ }
+
+ if c.HasParent() && c.Parent().helpCommand == c {
+ return false
+ }
+
+ if c.Runnable() || c.HasAvailableSubCommands() {
+ return true
+ }
+
+ return false
+}
+
+// IsHelpCommand determines if a command is a 'help' command; a help command is
+// determined by the fact that it is NOT runnable/hidden/deprecated, and has no
+// sub commands that are runnable/hidden/deprecated
+func (c *Command) IsHelpCommand() bool {
+
+ // if a command is runnable, deprecated, or hidden it is not a 'help' command
+ if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
+ return false
+ }
+
+ // if any non-help sub commands are found, the command is not a 'help' command
+ for _, sub := range c.commands {
+ if !sub.IsHelpCommand() {
+ return false
+ }
+ }
+
+ // the command either has no sub commands, or no non-help sub commands
+ return true
+}
+
+// HasHelpSubCommands determines if a command has any avilable 'help' sub commands
+// that need to be shown in the usage/help default template under 'additional help
+// topics'
+func (c *Command) HasHelpSubCommands() bool {
+
+ // return true on the first found available 'help' sub command
+ for _, sub := range c.commands {
+ if sub.IsHelpCommand() {
+ return true
+ }
+ }
+
+ // the command either has no sub commands, or no available 'help' sub commands
+ return false
+}
+
+// HasAvailableSubCommands determines if a command has available sub commands that
+// need to be shown in the usage/help default template under 'available commands'
+func (c *Command) HasAvailableSubCommands() bool {
+
+ // return true on the first found available (non deprecated/help/hidden)
+ // sub command
+ for _, sub := range c.commands {
+ if sub.IsAvailableCommand() {
+ return true
+ }
+ }
+
+ // the command either has no sub comamnds, or no available (non deprecated/help/hidden)
+ // sub commands
+ return false
+}
+
+// Determine if the command is a child command
+func (c *Command) HasParent() bool {
+ return c.parent != nil
+}
+
+// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists
+func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
+ return c.globNormFunc
+}
+
+// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)
+func (c *Command) Flags() *flag.FlagSet {
+ if c.flags == nil {
+ c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+ if c.flagErrorBuf == nil {
+ c.flagErrorBuf = new(bytes.Buffer)
+ }
+ c.flags.SetOutput(c.flagErrorBuf)
+ }
+ return c.flags
+}
+
+// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands
+func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
+ persistentFlags := c.PersistentFlags()
+
+ out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+ c.LocalFlags().VisitAll(func(f *flag.Flag) {
+ if persistentFlags.Lookup(f.Name) == nil {
+ out.AddFlag(f)
+ }
+ })
+ return out
+}
+
+// Get the local FlagSet specifically set in the current command
+func (c *Command) LocalFlags() *flag.FlagSet {
+ c.mergePersistentFlags()
+
+ local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+ c.lflags.VisitAll(func(f *flag.Flag) {
+ local.AddFlag(f)
+ })
+ if !c.HasParent() {
+ flag.CommandLine.VisitAll(func(f *flag.Flag) {
+ if local.Lookup(f.Name) == nil {
+ local.AddFlag(f)
+ }
+ })
+ }
+ return local
+}
+
+// All Flags which were inherited from parents commands
+func (c *Command) InheritedFlags() *flag.FlagSet {
+ c.mergePersistentFlags()
+
+ inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+ local := c.LocalFlags()
+
+ var rmerge func(x *Command)
+
+ rmerge = func(x *Command) {
+ if x.HasPersistentFlags() {
+ x.PersistentFlags().VisitAll(func(f *flag.Flag) {
+ if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
+ inherited.AddFlag(f)
+ }
+ })
+ }
+ if x.HasParent() {
+ rmerge(x.parent)
+ }
+ }
+
+ if c.HasParent() {
+ rmerge(c.parent)
+ }
+
+ return inherited
+}
+
+// All Flags which were not inherited from parent commands
+func (c *Command) NonInheritedFlags() *flag.FlagSet {
+ return c.LocalFlags()
+}
+
+// Get the Persistent FlagSet specifically set in the current command
+func (c *Command) PersistentFlags() *flag.FlagSet {
+ if c.pflags == nil {
+ c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+ if c.flagErrorBuf == nil {
+ c.flagErrorBuf = new(bytes.Buffer)
+ }
+ c.pflags.SetOutput(c.flagErrorBuf)
+ }
+ return c.pflags
+}
+
+// For use in testing
+func (c *Command) ResetFlags() {
+ c.flagErrorBuf = new(bytes.Buffer)
+ c.flagErrorBuf.Reset()
+ c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+ c.flags.SetOutput(c.flagErrorBuf)
+ c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+ c.pflags.SetOutput(c.flagErrorBuf)
+}
+
+// Does the command contain any flags (local plus persistent from the entire structure)
+func (c *Command) HasFlags() bool {
+ return c.Flags().HasFlags()
+}
+
+// Does the command contain persistent flags
+func (c *Command) HasPersistentFlags() bool {
+ return c.PersistentFlags().HasFlags()
+}
+
+// Does the command has flags specifically declared locally
+func (c *Command) HasLocalFlags() bool {
+ return c.LocalFlags().HasFlags()
+}
+
+// Does the command have flags inherited from its parent command
+func (c *Command) HasInheritedFlags() bool {
+ return c.InheritedFlags().HasFlags()
+}
+
+// Does the command contain any flags (local plus persistent from the entire
+// structure) which are not hidden or deprecated
+func (c *Command) HasAvailableFlags() bool {
+ return c.Flags().HasAvailableFlags()
+}
+
+// Does the command contain persistent flags which are not hidden or deprecated
+func (c *Command) HasAvailablePersistentFlags() bool {
+ return c.PersistentFlags().HasAvailableFlags()
+}
+
+// Does the command has flags specifically declared locally which are not hidden
+// or deprecated
+func (c *Command) HasAvailableLocalFlags() bool {
+ return c.LocalFlags().HasAvailableFlags()
+}
+
+// Does the command have flags inherited from its parent command which are
+// not hidden or deprecated
+func (c *Command) HasAvailableInheritedFlags() bool {
+ return c.InheritedFlags().HasAvailableFlags()
+}
+
+// Flag climbs up the command tree looking for matching flag
+func (c *Command) Flag(name string) (flag *flag.Flag) {
+ flag = c.Flags().Lookup(name)
+
+ if flag == nil {
+ flag = c.persistentFlag(name)
+ }
+
+ return
+}
+
+// recursively find matching persistent flag
+func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
+ if c.HasPersistentFlags() {
+ flag = c.PersistentFlags().Lookup(name)
+ }
+
+ if flag == nil && c.HasParent() {
+ flag = c.parent.persistentFlag(name)
+ }
+ return
+}
+
+// ParseFlags parses persistent flag tree & local flags
+func (c *Command) ParseFlags(args []string) (err error) {
+ if c.DisableFlagParsing {
+ return nil
+ }
+ c.mergePersistentFlags()
+ err = c.Flags().Parse(args)
+ return
+}
+
+// Parent returns a commands parent command
+func (c *Command) Parent() *Command {
+ return c.parent
+}
+
+func (c *Command) mergePersistentFlags() {
+ var rmerge func(x *Command)
+
+ // Save the set of local flags
+ if c.lflags == nil {
+ c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+ if c.flagErrorBuf == nil {
+ c.flagErrorBuf = new(bytes.Buffer)
+ }
+ c.lflags.SetOutput(c.flagErrorBuf)
+ addtolocal := func(f *flag.Flag) {
+ c.lflags.AddFlag(f)
+ }
+ c.Flags().VisitAll(addtolocal)
+ c.PersistentFlags().VisitAll(addtolocal)
+ }
+ rmerge = func(x *Command) {
+ if !x.HasParent() {
+ flag.CommandLine.VisitAll(func(f *flag.Flag) {
+ if x.PersistentFlags().Lookup(f.Name) == nil {
+ x.PersistentFlags().AddFlag(f)
+ }
+ })
+ }
+ if x.HasPersistentFlags() {
+ x.PersistentFlags().VisitAll(func(f *flag.Flag) {
+ if c.Flags().Lookup(f.Name) == nil {
+ c.Flags().AddFlag(f)
+ }
+ })
+ }
+ if x.HasParent() {
+ rmerge(x.parent)
+ }
+ }
+
+ rmerge(c)
+}
diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go
new file mode 100644
index 0000000..6159c1c
--- /dev/null
+++ b/vendor/github.com/spf13/cobra/command_notwin.go
@@ -0,0 +1,5 @@
+// +build !windows
+
+package cobra
+
+var preExecHookFn func(*Command)
diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go
new file mode 100644
index 0000000..4b0eaa1
--- /dev/null
+++ b/vendor/github.com/spf13/cobra/command_win.go
@@ -0,0 +1,26 @@
+// +build windows
+
+package cobra
+
+import (
+ "os"
+ "time"
+
+ "github.com/inconshreveable/mousetrap"
+)
+
+var preExecHookFn = preExecHook
+
+// enables an information splash screen on Windows if the CLI is started from explorer.exe.
+var MousetrapHelpText string = `This is a command line tool
+
+You need to open cmd.exe and run it from there.
+`
+
+func preExecHook(c *Command) {
+ if mousetrap.StartedByExplorer() {
+ c.Print(MousetrapHelpText)
+ time.Sleep(5 * time.Second)
+ os.Exit(1)
+ }
+}
diff --git a/vendor/github.com/spf13/pflag/LICENSE b/vendor/github.com/spf13/pflag/LICENSE
new file mode 100644
index 0000000..63ed1cf
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/LICENSE
@@ -0,0 +1,28 @@
+Copyright (c) 2012 Alex Ogier. All rights reserved.
+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/spf13/pflag/README.md b/vendor/github.com/spf13/pflag/README.md
new file mode 100644
index 0000000..eefb46d
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/README.md
@@ -0,0 +1,277 @@
+[![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
+
+pflag is a drop-in replacement for Go's flag package, implementing
+POSIX/GNU-style --flags.
+
+pflag is compatible with the [GNU extensions to the POSIX recommendations
+for command-line options][1]. For a more precise description, see the
+"Command-line flag syntax" section below.
+
+[1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
+
+pflag is available under the same style of BSD license as the Go language,
+which can be found in the LICENSE file.
+
+## Installation
+
+pflag is available using the standard `go get` command.
+
+Install by running:
+
+ go get github.com/spf13/pflag
+
+Run tests by running:
+
+ go test github.com/spf13/pflag
+
+## Usage
+
+pflag is a drop-in replacement of Go's native flag package. If you import
+pflag under the name "flag" then all code should continue to function
+with no changes.
+
+``` go
+import flag "github.com/spf13/pflag"
+```
+
+There is one exception to this: if you directly instantiate the Flag struct
+there is one more field "Shorthand" that you will need to set.
+Most code never instantiates this struct directly, and instead uses
+functions such as String(), BoolVar(), and Var(), and is therefore
+unaffected.
+
+Define flags using flag.String(), Bool(), Int(), etc.
+
+This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
+
+``` go
+var ip *int = flag.Int("flagname", 1234, "help message for flagname")
+```
+
+If you like, you can bind the flag to a variable using the Var() functions.
+
+``` go
+var flagvar int
+func init() {
+ flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
+}
+```
+
+Or you can create custom flags that satisfy the Value interface (with
+pointer receivers) and couple them to flag parsing by
+
+``` go
+flag.Var(&flagVal, "name", "help message for flagname")
+```
+
+For such flags, the default value is just the initial value of the variable.
+
+After all flags are defined, call
+
+``` go
+flag.Parse()
+```
+
+to parse the command line into the defined flags.
+
+Flags may then be used directly. If you're using the flags themselves,
+they are all pointers; if you bind to variables, they're values.
+
+``` go
+fmt.Println("ip has value ", *ip)
+fmt.Println("flagvar has value ", flagvar)
+```
+
+There are helpers function to get values later if you have the FlagSet but
+it was difficult to keep up with all of the flag pointers in your code.
+If you have a pflag.FlagSet with a flag called 'flagname' of type int you
+can use GetInt() to get the int value. But notice that 'flagname' must exist
+and it must be an int. GetString("flagname") will fail.
+
+``` go
+i, err := flagset.GetInt("flagname")
+```
+
+After parsing, the arguments after the flag are available as the
+slice flag.Args() or individually as flag.Arg(i).
+The arguments are indexed from 0 through flag.NArg()-1.
+
+The pflag package also defines some new functions that are not in flag,
+that give one-letter shorthands for flags. You can use these by appending
+'P' to the name of any function that defines a flag.
+
+``` go
+var ip = flag.IntP("flagname", "f", 1234, "help message")
+var flagvar bool
+func init() {
+ flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
+}
+flag.VarP(&flagVal, "varname", "v", "help message")
+```
+
+Shorthand letters can be used with single dashes on the command line.
+Boolean shorthand flags can be combined with other shorthand flags.
+
+The default set of command-line flags is controlled by
+top-level functions. The FlagSet type allows one to define
+independent sets of flags, such as to implement subcommands
+in a command-line interface. The methods of FlagSet are
+analogous to the top-level functions for the command-line
+flag set.
+
+## Setting no option default values for flags
+
+After you create a flag it is possible to set the pflag.NoOptDefVal for
+the given flag. Doing this changes the meaning of the flag slightly. If
+a flag has a NoOptDefVal and the flag is set on the command line without
+an option the flag will be set to the NoOptDefVal. For example given:
+
+``` go
+var ip = flag.IntP("flagname", "f", 1234, "help message")
+flag.Lookup("flagname").NoOptDefVal = "4321"
+```
+
+Would result in something like
+
+| Parsed Arguments | Resulting Value |
+| ------------- | ------------- |
+| --flagname=1357 | ip=1357 |
+| --flagname | ip=4321 |
+| [nothing] | ip=1234 |
+
+## Command line flag syntax
+
+```
+--flag // boolean flags, or flags with no option default values
+--flag x // only on flags without a default value
+--flag=x
+```
+
+Unlike the flag package, a single dash before an option means something
+different than a double dash. Single dashes signify a series of shorthand
+letters for flags. All but the last shorthand letter must be boolean flags
+or a flag with a default value
+
+```
+// boolean or flags where the 'no option default value' is set
+-f
+-f=true
+-abc
+but
+-b true is INVALID
+
+// non-boolean and flags without a 'no option default value'
+-n 1234
+-n=1234
+-n1234
+
+// mixed
+-abcs "hello"
+-absd="hello"
+-abcs1234
+```
+
+Flag parsing stops after the terminator "--". Unlike the flag package,
+flags can be interspersed with arguments anywhere on the command line
+before this terminator.
+
+Integer flags accept 1234, 0664, 0x1234 and may be negative.
+Boolean flags (in their long form) accept 1, 0, t, f, true, false,
+TRUE, FALSE, True, False.
+Duration flags accept any input valid for time.ParseDuration.
+
+## Mutating or "Normalizing" Flag names
+
+It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow.
+
+**Example #1**: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag
+
+``` go
+func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
+ from := []string{"-", "_"}
+ to := "."
+ for _, sep := range from {
+ name = strings.Replace(name, sep, to, -1)
+ }
+ return pflag.NormalizedName(name)
+}
+
+myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc)
+```
+
+**Example #2**: You want to alias two flags. aka --old-flag-name == --new-flag-name
+
+``` go
+func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
+ switch name {
+ case "old-flag-name":
+ name = "new-flag-name"
+ break
+ }
+ return pflag.NormalizedName(name)
+}
+
+myFlagSet.SetNormalizeFunc(aliasNormalizeFunc)
+```
+
+## Deprecating a flag or its shorthand
+It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used.
+
+**Example #1**: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead.
+```go
+// deprecate a flag by specifying its name and a usage message
+flags.MarkDeprecated("badflag", "please use --good-flag instead")
+```
+This hides "badflag" from help text, and prints `Flag --badflag has been deprecated, please use --good-flag instead` when "badflag" is used.
+
+**Example #2**: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n".
+```go
+// deprecate a flag shorthand by specifying its flag name and a usage message
+flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only")
+```
+This hides the shortname "n" from help text, and prints `Flag shorthand -n has been deprecated, please use --noshorthandflag only` when the shorthand "n" is used.
+
+Note that usage message is essential here, and it should not be empty.
+
+## Hidden flags
+It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text.
+
+**Example**: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available.
+```go
+// hide a flag by specifying its name
+flags.MarkHidden("secretFlag")
+```
+
+## Supporting Go flags when using pflag
+In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary
+to support flags defined by third-party dependencies (e.g. `golang/glog`).
+
+**Example**: You want to add the Go flags to the `CommandLine` flagset
+```go
+import (
+ goflag "flag"
+ flag "github.com/spf13/pflag"
+)
+
+var ip *int = flag.Int("flagname", 1234, "help message for flagname")
+
+func main() {
+ flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
+ flag.Parse()
+}
+```
+
+## More info
+
+You can see the full reference documentation of the pflag package
+[at godoc.org][3], or through go's standard documentation system by
+running `godoc -http=:6060` and browsing to
+[http://localhost:6060/pkg/github.com/ogier/pflag][2] after
+installation.
+
+[2]: http://localhost:6060/pkg/github.com/ogier/pflag
+[3]: http://godoc.org/github.com/ogier/pflag
diff --git a/vendor/github.com/spf13/pflag/bool.go b/vendor/github.com/spf13/pflag/bool.go
new file mode 100644
index 0000000..c4c5c0b
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/bool.go
@@ -0,0 +1,94 @@
+package pflag
+
+import "strconv"
+
+// optional interface to indicate boolean flags that can be
+// supplied without "=value" text
+type boolFlag interface {
+ Value
+ IsBoolFlag() bool
+}
+
+// -- bool Value
+type boolValue bool
+
+func newBoolValue(val bool, p *bool) *boolValue {
+ *p = val
+ return (*boolValue)(p)
+}
+
+func (b *boolValue) Set(s string) error {
+ v, err := strconv.ParseBool(s)
+ *b = boolValue(v)
+ return err
+}
+
+func (b *boolValue) Type() string {
+ return "bool"
+}
+
+func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) }
+
+func (b *boolValue) IsBoolFlag() bool { return true }
+
+func boolConv(sval string) (interface{}, error) {
+ return strconv.ParseBool(sval)
+}
+
+// GetBool return the bool value of a flag with the given name
+func (f *FlagSet) GetBool(name string) (bool, error) {
+ val, err := f.getFlagType(name, "bool", boolConv)
+ if err != nil {
+ return false, err
+ }
+ return val.(bool), nil
+}
+
+// BoolVar defines a bool flag with specified name, default value, and usage string.
+// The argument p points to a bool variable in which to store the value of the flag.
+func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
+ f.BoolVarP(p, name, "", value, usage)
+}
+
+// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
+ flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage)
+ flag.NoOptDefVal = "true"
+}
+
+// BoolVar defines a bool flag with specified name, default value, and usage string.
+// The argument p points to a bool variable in which to store the value of the flag.
+func BoolVar(p *bool, name string, value bool, usage string) {
+ BoolVarP(p, name, "", value, usage)
+}
+
+// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
+func BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
+ flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage)
+ flag.NoOptDefVal = "true"
+}
+
+// Bool defines a bool flag with specified name, default value, and usage string.
+// The return value is the address of a bool variable that stores the value of the flag.
+func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
+ return f.BoolP(name, "", value, usage)
+}
+
+// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {
+ p := new(bool)
+ f.BoolVarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Bool defines a bool flag with specified name, default value, and usage string.
+// The return value is the address of a bool variable that stores the value of the flag.
+func Bool(name string, value bool, usage string) *bool {
+ return BoolP(name, "", value, usage)
+}
+
+// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
+func BoolP(name, shorthand string, value bool, usage string) *bool {
+ b := CommandLine.BoolP(name, shorthand, value, usage)
+ return b
+}
diff --git a/vendor/github.com/spf13/pflag/bool_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go
new file mode 100644
index 0000000..5af02f1
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/bool_slice.go
@@ -0,0 +1,147 @@
+package pflag
+
+import (
+ "io"
+ "strconv"
+ "strings"
+)
+
+// -- boolSlice Value
+type boolSliceValue struct {
+ value *[]bool
+ changed bool
+}
+
+func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue {
+ bsv := new(boolSliceValue)
+ bsv.value = p
+ *bsv.value = val
+ return bsv
+}
+
+// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag.
+// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended.
+func (s *boolSliceValue) Set(val string) error {
+
+ // remove all quote characters
+ rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
+
+ // read flag arguments with CSV parser
+ boolStrSlice, err := readAsCSV(rmQuote.Replace(val))
+ if err != nil && err != io.EOF {
+ return err
+ }
+
+ // parse boolean values into slice
+ out := make([]bool, 0, len(boolStrSlice))
+ for _, boolStr := range boolStrSlice {
+ b, err := strconv.ParseBool(strings.TrimSpace(boolStr))
+ if err != nil {
+ return err
+ }
+ out = append(out, b)
+ }
+
+ if !s.changed {
+ *s.value = out
+ } else {
+ *s.value = append(*s.value, out...)
+ }
+
+ s.changed = true
+
+ return nil
+}
+
+// Type returns a string that uniquely represents this flag's type.
+func (s *boolSliceValue) Type() string {
+ return "boolSlice"
+}
+
+// String defines a "native" format for this boolean slice flag value.
+func (s *boolSliceValue) String() string {
+
+ boolStrSlice := make([]string, len(*s.value))
+ for i, b := range *s.value {
+ boolStrSlice[i] = strconv.FormatBool(b)
+ }
+
+ out, _ := writeAsCSV(boolStrSlice)
+
+ return "[" + out + "]"
+}
+
+func boolSliceConv(val string) (interface{}, error) {
+ val = strings.Trim(val, "[]")
+ // Empty string would cause a slice with one (empty) entry
+ if len(val) == 0 {
+ return []bool{}, nil
+ }
+ ss := strings.Split(val, ",")
+ out := make([]bool, len(ss))
+ for i, t := range ss {
+ var err error
+ out[i], err = strconv.ParseBool(t)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return out, nil
+}
+
+// GetBoolSlice returns the []bool value of a flag with the given name.
+func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) {
+ val, err := f.getFlagType(name, "boolSlice", boolSliceConv)
+ if err != nil {
+ return []bool{}, err
+ }
+ return val.([]bool), nil
+}
+
+// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string.
+// The argument p points to a []bool variable in which to store the value of the flag.
+func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
+ f.VarP(newBoolSliceValue(value, p), name, "", usage)
+}
+
+// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
+ f.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
+}
+
+// BoolSliceVar defines a []bool flag with specified name, default value, and usage string.
+// The argument p points to a []bool variable in which to store the value of the flag.
+func BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
+ CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage)
+}
+
+// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
+func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
+ CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
+}
+
+// BoolSlice defines a []bool flag with specified name, default value, and usage string.
+// The return value is the address of a []bool variable that stores the value of the flag.
+func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool {
+ p := []bool{}
+ f.BoolSliceVarP(&p, name, "", value, usage)
+ return &p
+}
+
+// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
+ p := []bool{}
+ f.BoolSliceVarP(&p, name, shorthand, value, usage)
+ return &p
+}
+
+// BoolSlice defines a []bool flag with specified name, default value, and usage string.
+// The return value is the address of a []bool variable that stores the value of the flag.
+func BoolSlice(name string, value []bool, usage string) *[]bool {
+ return CommandLine.BoolSliceP(name, "", value, usage)
+}
+
+// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
+func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
+ return CommandLine.BoolSliceP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go
new file mode 100644
index 0000000..d22be41
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/count.go
@@ -0,0 +1,94 @@
+package pflag
+
+import "strconv"
+
+// -- count Value
+type countValue int
+
+func newCountValue(val int, p *int) *countValue {
+ *p = val
+ return (*countValue)(p)
+}
+
+func (i *countValue) Set(s string) error {
+ v, err := strconv.ParseInt(s, 0, 64)
+ // -1 means that no specific value was passed, so increment
+ if v == -1 {
+ *i = countValue(*i + 1)
+ } else {
+ *i = countValue(v)
+ }
+ return err
+}
+
+func (i *countValue) Type() string {
+ return "count"
+}
+
+func (i *countValue) String() string { return strconv.Itoa(int(*i)) }
+
+func countConv(sval string) (interface{}, error) {
+ i, err := strconv.Atoi(sval)
+ if err != nil {
+ return nil, err
+ }
+ return i, nil
+}
+
+// GetCount return the int value of a flag with the given name
+func (f *FlagSet) GetCount(name string) (int, error) {
+ val, err := f.getFlagType(name, "count", countConv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(int), nil
+}
+
+// CountVar defines a count flag with specified name, default value, and usage string.
+// The argument p points to an int variable in which to store the value of the flag.
+// A count flag will add 1 to its value evey time it is found on the command line
+func (f *FlagSet) CountVar(p *int, name string, usage string) {
+ f.CountVarP(p, name, "", usage)
+}
+
+// CountVarP is like CountVar only take a shorthand for the flag name.
+func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) {
+ flag := f.VarPF(newCountValue(0, p), name, shorthand, usage)
+ flag.NoOptDefVal = "-1"
+}
+
+// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set
+func CountVar(p *int, name string, usage string) {
+ CommandLine.CountVar(p, name, usage)
+}
+
+// CountVarP is like CountVar only take a shorthand for the flag name.
+func CountVarP(p *int, name, shorthand string, usage string) {
+ CommandLine.CountVarP(p, name, shorthand, usage)
+}
+
+// Count defines a count flag with specified name, default value, and usage string.
+// The return value is the address of an int variable that stores the value of the flag.
+// A count flag will add 1 to its value evey time it is found on the command line
+func (f *FlagSet) Count(name string, usage string) *int {
+ p := new(int)
+ f.CountVarP(p, name, "", usage)
+ return p
+}
+
+// CountP is like Count only takes a shorthand for the flag name.
+func (f *FlagSet) CountP(name, shorthand string, usage string) *int {
+ p := new(int)
+ f.CountVarP(p, name, shorthand, usage)
+ return p
+}
+
+// Count like Count only the flag is placed on the CommandLine isntead of a given flag set
+func Count(name string, usage string) *int {
+ return CommandLine.CountP(name, "", usage)
+}
+
+// CountP is like Count only takes a shorthand for the flag name.
+func CountP(name, shorthand string, usage string) *int {
+ return CommandLine.CountP(name, shorthand, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/duration.go b/vendor/github.com/spf13/pflag/duration.go
new file mode 100644
index 0000000..e9debef
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/duration.go
@@ -0,0 +1,86 @@
+package pflag
+
+import (
+ "time"
+)
+
+// -- time.Duration Value
+type durationValue time.Duration
+
+func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
+ *p = val
+ return (*durationValue)(p)
+}
+
+func (d *durationValue) Set(s string) error {
+ v, err := time.ParseDuration(s)
+ *d = durationValue(v)
+ return err
+}
+
+func (d *durationValue) Type() string {
+ return "duration"
+}
+
+func (d *durationValue) String() string { return (*time.Duration)(d).String() }
+
+func durationConv(sval string) (interface{}, error) {
+ return time.ParseDuration(sval)
+}
+
+// GetDuration return the duration value of a flag with the given name
+func (f *FlagSet) GetDuration(name string) (time.Duration, error) {
+ val, err := f.getFlagType(name, "duration", durationConv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(time.Duration), nil
+}
+
+// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
+// The argument p points to a time.Duration variable in which to store the value of the flag.
+func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
+ f.VarP(newDurationValue(value, p), name, "", usage)
+}
+
+// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
+ f.VarP(newDurationValue(value, p), name, shorthand, usage)
+}
+
+// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
+// The argument p points to a time.Duration variable in which to store the value of the flag.
+func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
+ CommandLine.VarP(newDurationValue(value, p), name, "", usage)
+}
+
+// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
+func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
+ CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage)
+}
+
+// Duration defines a time.Duration flag with specified name, default value, and usage string.
+// The return value is the address of a time.Duration variable that stores the value of the flag.
+func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
+ p := new(time.Duration)
+ f.DurationVarP(p, name, "", value, usage)
+ return p
+}
+
+// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
+ p := new(time.Duration)
+ f.DurationVarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Duration defines a time.Duration flag with specified name, default value, and usage string.
+// The return value is the address of a time.Duration variable that stores the value of the flag.
+func Duration(name string, value time.Duration, usage string) *time.Duration {
+ return CommandLine.DurationP(name, "", value, usage)
+}
+
+// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
+func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
+ return CommandLine.DurationP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go
new file mode 100644
index 0000000..746af63
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/flag.go
@@ -0,0 +1,1063 @@
+// Copyright 2009 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 pflag is a drop-in replacement for Go's flag package, implementing
+POSIX/GNU-style --flags.
+
+pflag is compatible with the GNU extensions to the POSIX recommendations
+for command-line options. See
+http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
+
+Usage:
+
+pflag is a drop-in replacement of Go's native flag package. If you import
+pflag under the name "flag" then all code should continue to function
+with no changes.
+
+ import flag "github.com/ogier/pflag"
+
+ There is one exception to this: if you directly instantiate the Flag struct
+there is one more field "Shorthand" that you will need to set.
+Most code never instantiates this struct directly, and instead uses
+functions such as String(), BoolVar(), and Var(), and is therefore
+unaffected.
+
+Define flags using flag.String(), Bool(), Int(), etc.
+
+This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
+ var ip = flag.Int("flagname", 1234, "help message for flagname")
+If you like, you can bind the flag to a variable using the Var() functions.
+ var flagvar int
+ func init() {
+ flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
+ }
+Or you can create custom flags that satisfy the Value interface (with
+pointer receivers) and couple them to flag parsing by
+ flag.Var(&flagVal, "name", "help message for flagname")
+For such flags, the default value is just the initial value of the variable.
+
+After all flags are defined, call
+ flag.Parse()
+to parse the command line into the defined flags.
+
+Flags may then be used directly. If you're using the flags themselves,
+they are all pointers; if you bind to variables, they're values.
+ fmt.Println("ip has value ", *ip)
+ fmt.Println("flagvar has value ", flagvar)
+
+After parsing, the arguments after the flag are available as the
+slice flag.Args() or individually as flag.Arg(i).
+The arguments are indexed from 0 through flag.NArg()-1.
+
+The pflag package also defines some new functions that are not in flag,
+that give one-letter shorthands for flags. You can use these by appending
+'P' to the name of any function that defines a flag.
+ var ip = flag.IntP("flagname", "f", 1234, "help message")
+ var flagvar bool
+ func init() {
+ flag.BoolVarP("boolname", "b", true, "help message")
+ }
+ flag.VarP(&flagVar, "varname", "v", 1234, "help message")
+Shorthand letters can be used with single dashes on the command line.
+Boolean shorthand flags can be combined with other shorthand flags.
+
+Command line flag syntax:
+ --flag // boolean flags only
+ --flag=x
+
+Unlike the flag package, a single dash before an option means something
+different than a double dash. Single dashes signify a series of shorthand
+letters for flags. All but the last shorthand letter must be boolean flags.
+ // boolean flags
+ -f
+ -abc
+ // non-boolean flags
+ -n 1234
+ -Ifile
+ // mixed
+ -abcs "hello"
+ -abcn1234
+
+Flag parsing stops after the terminator "--". Unlike the flag package,
+flags can be interspersed with arguments anywhere on the command line
+before this terminator.
+
+Integer flags accept 1234, 0664, 0x1234 and may be negative.
+Boolean flags (in their long form) accept 1, 0, t, f, true, false,
+TRUE, FALSE, True, False.
+Duration flags accept any input valid for time.ParseDuration.
+
+The default set of command-line flags is controlled by
+top-level functions. The FlagSet type allows one to define
+independent sets of flags, such as to implement subcommands
+in a command-line interface. The methods of FlagSet are
+analogous to the top-level functions for the command-line
+flag set.
+*/
+package pflag
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "sort"
+ "strings"
+)
+
+// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
+var ErrHelp = errors.New("pflag: help requested")
+
+// ErrorHandling defines how to handle flag parsing errors.
+type ErrorHandling int
+
+const (
+ // ContinueOnError will return an err from Parse() if an error is found
+ ContinueOnError ErrorHandling = iota
+ // ExitOnError will call os.Exit(2) if an error is found when parsing
+ ExitOnError
+ // PanicOnError will panic() if an error is found when parsing flags
+ PanicOnError
+)
+
+// NormalizedName is a flag name that has been normalized according to rules
+// for the FlagSet (e.g. making '-' and '_' equivalent).
+type NormalizedName string
+
+// A FlagSet represents a set of defined flags.
+type FlagSet struct {
+ // Usage is the function called when an error occurs while parsing flags.
+ // The field is a function (not a method) that may be changed to point to
+ // a custom error handler.
+ Usage func()
+
+ name string
+ parsed bool
+ actual map[NormalizedName]*Flag
+ formal map[NormalizedName]*Flag
+ shorthands map[byte]*Flag
+ args []string // arguments after flags
+ argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no --
+ exitOnError bool // does the program exit if there's an error?
+ errorHandling ErrorHandling
+ output io.Writer // nil means stderr; use out() accessor
+ interspersed bool // allow interspersed option/non-option args
+ normalizeNameFunc func(f *FlagSet, name string) NormalizedName
+}
+
+// A Flag represents the state of a flag.
+type Flag struct {
+ Name string // name as it appears on command line
+ Shorthand string // one-letter abbreviated flag
+ Usage string // help message
+ Value Value // value as set
+ DefValue string // default value (as text); for usage message
+ Changed bool // If the user set the value (or if left to default)
+ NoOptDefVal string //default value (as text); if the flag is on the command line without any options
+ Deprecated string // If this flag is deprecated, this string is the new or now thing to use
+ Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text
+ ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use
+ Annotations map[string][]string // used by cobra.Command bash autocomple code
+}
+
+// Value is the interface to the dynamic value stored in a flag.
+// (The default value is represented as a string.)
+type Value interface {
+ String() string
+ Set(string) error
+ Type() string
+}
+
+// sortFlags returns the flags as a slice in lexicographical sorted order.
+func sortFlags(flags map[NormalizedName]*Flag) []*Flag {
+ list := make(sort.StringSlice, len(flags))
+ i := 0
+ for k := range flags {
+ list[i] = string(k)
+ i++
+ }
+ list.Sort()
+ result := make([]*Flag, len(list))
+ for i, name := range list {
+ result[i] = flags[NormalizedName(name)]
+ }
+ return result
+}
+
+// SetNormalizeFunc allows you to add a function which can translate flag names.
+// Flags added to the FlagSet will be translated and then when anything tries to
+// look up the flag that will also be translated. So it would be possible to create
+// a flag named "getURL" and have it translated to "geturl". A user could then pass
+// "--getUrl" which may also be translated to "geturl" and everything will work.
+func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) {
+ f.normalizeNameFunc = n
+ for k, v := range f.formal {
+ delete(f.formal, k)
+ nname := f.normalizeFlagName(string(k))
+ f.formal[nname] = v
+ v.Name = string(nname)
+ }
+}
+
+// GetNormalizeFunc returns the previously set NormalizeFunc of a function which
+// does no translation, if not set previously.
+func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName {
+ if f.normalizeNameFunc != nil {
+ return f.normalizeNameFunc
+ }
+ return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) }
+}
+
+func (f *FlagSet) normalizeFlagName(name string) NormalizedName {
+ n := f.GetNormalizeFunc()
+ return n(f, name)
+}
+
+func (f *FlagSet) out() io.Writer {
+ if f.output == nil {
+ return os.Stderr
+ }
+ return f.output
+}
+
+// SetOutput sets the destination for usage and error messages.
+// If output is nil, os.Stderr is used.
+func (f *FlagSet) SetOutput(output io.Writer) {
+ f.output = output
+}
+
+// VisitAll visits the flags in lexicographical order, calling fn for each.
+// It visits all flags, even those not set.
+func (f *FlagSet) VisitAll(fn func(*Flag)) {
+ for _, flag := range sortFlags(f.formal) {
+ fn(flag)
+ }
+}
+
+// HasFlags returns a bool to indicate if the FlagSet has any flags definied.
+func (f *FlagSet) HasFlags() bool {
+ return len(f.formal) > 0
+}
+
+// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
+// definied that are not hidden or deprecated.
+func (f *FlagSet) HasAvailableFlags() bool {
+ for _, flag := range f.formal {
+ if !flag.Hidden && len(flag.Deprecated) == 0 {
+ return true
+ }
+ }
+ return false
+}
+
+// VisitAll visits the command-line flags in lexicographical order, calling
+// fn for each. It visits all flags, even those not set.
+func VisitAll(fn func(*Flag)) {
+ CommandLine.VisitAll(fn)
+}
+
+// Visit visits the flags in lexicographical order, calling fn for each.
+// It visits only those flags that have been set.
+func (f *FlagSet) Visit(fn func(*Flag)) {
+ for _, flag := range sortFlags(f.actual) {
+ fn(flag)
+ }
+}
+
+// Visit visits the command-line flags in lexicographical order, calling fn
+// for each. It visits only those flags that have been set.
+func Visit(fn func(*Flag)) {
+ CommandLine.Visit(fn)
+}
+
+// Lookup returns the Flag structure of the named flag, returning nil if none exists.
+func (f *FlagSet) Lookup(name string) *Flag {
+ return f.lookup(f.normalizeFlagName(name))
+}
+
+// lookup returns the Flag structure of the named flag, returning nil if none exists.
+func (f *FlagSet) lookup(name NormalizedName) *Flag {
+ return f.formal[name]
+}
+
+// func to return a given type for a given flag name
+func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) {
+ flag := f.Lookup(name)
+ if flag == nil {
+ err := fmt.Errorf("flag accessed but not defined: %s", name)
+ return nil, err
+ }
+
+ if flag.Value.Type() != ftype {
+ err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type())
+ return nil, err
+ }
+
+ sval := flag.Value.String()
+ result, err := convFunc(sval)
+ if err != nil {
+ return nil, err
+ }
+ return result, nil
+}
+
+// ArgsLenAtDash will return the length of f.Args at the moment when a -- was
+// found during arg parsing. This allows your program to know which args were
+// before the -- and which came after.
+func (f *FlagSet) ArgsLenAtDash() int {
+ return f.argsLenAtDash
+}
+
+// MarkDeprecated indicated that a flag is deprecated in your program. It will
+// continue to function but will not show up in help or usage messages. Using
+// this flag will also print the given usageMessage.
+func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
+ flag := f.Lookup(name)
+ if flag == nil {
+ return fmt.Errorf("flag %q does not exist", name)
+ }
+ if len(usageMessage) == 0 {
+ return fmt.Errorf("deprecated message for flag %q must be set", name)
+ }
+ flag.Deprecated = usageMessage
+ return nil
+}
+
+// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your
+// program. It will continue to function but will not show up in help or usage
+// messages. Using this flag will also print the given usageMessage.
+func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error {
+ flag := f.Lookup(name)
+ if flag == nil {
+ return fmt.Errorf("flag %q does not exist", name)
+ }
+ if len(usageMessage) == 0 {
+ return fmt.Errorf("deprecated message for flag %q must be set", name)
+ }
+ flag.ShorthandDeprecated = usageMessage
+ return nil
+}
+
+// MarkHidden sets a flag to 'hidden' in your program. It will continue to
+// function but will not show up in help or usage messages.
+func (f *FlagSet) MarkHidden(name string) error {
+ flag := f.Lookup(name)
+ if flag == nil {
+ return fmt.Errorf("flag %q does not exist", name)
+ }
+ flag.Hidden = true
+ return nil
+}
+
+// Lookup returns the Flag structure of the named command-line flag,
+// returning nil if none exists.
+func Lookup(name string) *Flag {
+ return CommandLine.Lookup(name)
+}
+
+// Set sets the value of the named flag.
+func (f *FlagSet) Set(name, value string) error {
+ normalName := f.normalizeFlagName(name)
+ flag, ok := f.formal[normalName]
+ if !ok {
+ return fmt.Errorf("no such flag -%v", name)
+ }
+ err := flag.Value.Set(value)
+ if err != nil {
+ return err
+ }
+ if f.actual == nil {
+ f.actual = make(map[NormalizedName]*Flag)
+ }
+ f.actual[normalName] = flag
+ flag.Changed = true
+ if len(flag.Deprecated) > 0 {
+ fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
+ }
+ return nil
+}
+
+// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet.
+// This is sometimes used by spf13/cobra programs which want to generate additional
+// bash completion information.
+func (f *FlagSet) SetAnnotation(name, key string, values []string) error {
+ normalName := f.normalizeFlagName(name)
+ flag, ok := f.formal[normalName]
+ if !ok {
+ return fmt.Errorf("no such flag -%v", name)
+ }
+ if flag.Annotations == nil {
+ flag.Annotations = map[string][]string{}
+ }
+ flag.Annotations[key] = values
+ return nil
+}
+
+// Changed returns true if the flag was explicitly set during Parse() and false
+// otherwise
+func (f *FlagSet) Changed(name string) bool {
+ flag := f.Lookup(name)
+ // If a flag doesn't exist, it wasn't changed....
+ if flag == nil {
+ return false
+ }
+ return flag.Changed
+}
+
+// Set sets the value of the named command-line flag.
+func Set(name, value string) error {
+ return CommandLine.Set(name, value)
+}
+
+// PrintDefaults prints, to standard error unless configured
+// otherwise, the default values of all defined flags in the set.
+func (f *FlagSet) PrintDefaults() {
+ usages := f.FlagUsages()
+ fmt.Fprint(f.out(), usages)
+}
+
+// defaultIsZeroValue returns true if the default value for this flag represents
+// a zero value.
+func (f *Flag) defaultIsZeroValue() bool {
+ switch f.Value.(type) {
+ case boolFlag:
+ return f.DefValue == "false"
+ case *durationValue:
+ // Beginning in Go 1.7, duration zero values are "0s"
+ return f.DefValue == "0" || f.DefValue == "0s"
+ case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value:
+ return f.DefValue == "0"
+ case *stringValue:
+ return f.DefValue == ""
+ case *ipValue, *ipMaskValue, *ipNetValue:
+ return f.DefValue == "<nil>"
+ case *intSliceValue, *stringSliceValue, *stringArrayValue:
+ return f.DefValue == "[]"
+ default:
+ switch f.Value.String() {
+ case "false":
+ return true
+ case "<nil>":
+ return true
+ case "":
+ return true
+ case "0":
+ return true
+ }
+ return false
+ }
+}
+
+// UnquoteUsage extracts a back-quoted name from the usage
+// string for a flag and returns it and the un-quoted usage.
+// Given "a `name` to show" it returns ("name", "a name to show").
+// If there are no back quotes, the name is an educated guess of the
+// type of the flag's value, or the empty string if the flag is boolean.
+func UnquoteUsage(flag *Flag) (name string, usage string) {
+ // Look for a back-quoted name, but avoid the strings package.
+ usage = flag.Usage
+ for i := 0; i < len(usage); i++ {
+ if usage[i] == '`' {
+ for j := i + 1; j < len(usage); j++ {
+ if usage[j] == '`' {
+ name = usage[i+1 : j]
+ usage = usage[:i] + name + usage[j+1:]
+ return name, usage
+ }
+ }
+ break // Only one back quote; use type name.
+ }
+ }
+
+ name = flag.Value.Type()
+ switch name {
+ case "bool":
+ name = ""
+ case "float64":
+ name = "float"
+ case "int64":
+ name = "int"
+ case "uint64":
+ name = "uint"
+ }
+
+ return
+}
+
+// Splits the string `s` on whitespace into an initial substring up to
+// `i` runes in length and the remainder. Will go `slop` over `i` if
+// that encompasses the entire string (which allows the caller to
+// avoid short orphan words on the final line).
+func wrapN(i, slop int, s string) (string, string) {
+ if i+slop > len(s) {
+ return s, ""
+ }
+
+ w := strings.LastIndexAny(s[:i], " \t")
+ if w <= 0 {
+ return s, ""
+ }
+
+ return s[:w], s[w+1:]
+}
+
+// Wraps the string `s` to a maximum width `w` with leading indent
+// `i`. The first line is not indented (this is assumed to be done by
+// caller). Pass `w` == 0 to do no wrapping
+func wrap(i, w int, s string) string {
+ if w == 0 {
+ return s
+ }
+
+ // space between indent i and end of line width w into which
+ // we should wrap the text.
+ wrap := w - i
+
+ var r, l string
+
+ // Not enough space for sensible wrapping. Wrap as a block on
+ // the next line instead.
+ if wrap < 24 {
+ i = 16
+ wrap = w - i
+ r += "\n" + strings.Repeat(" ", i)
+ }
+ // If still not enough space then don't even try to wrap.
+ if wrap < 24 {
+ return s
+ }
+
+ // Try to avoid short orphan words on the final line, by
+ // allowing wrapN to go a bit over if that would fit in the
+ // remainder of the line.
+ slop := 5
+ wrap = wrap - slop
+
+ // Handle first line, which is indented by the caller (or the
+ // special case above)
+ l, s = wrapN(wrap, slop, s)
+ r = r + l
+
+ // Now wrap the rest
+ for s != "" {
+ var t string
+
+ t, s = wrapN(wrap, slop, s)
+ r = r + "\n" + strings.Repeat(" ", i) + t
+ }
+
+ return r
+
+}
+
+// FlagUsagesWrapped returns a string containing the usage information
+// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
+// wrapping)
+func (f *FlagSet) FlagUsagesWrapped(cols int) string {
+ x := new(bytes.Buffer)
+
+ lines := make([]string, 0, len(f.formal))
+
+ maxlen := 0
+ f.VisitAll(func(flag *Flag) {
+ if len(flag.Deprecated) > 0 || flag.Hidden {
+ return
+ }
+
+ line := ""
+ if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {
+ line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)
+ } else {
+ line = fmt.Sprintf(" --%s", flag.Name)
+ }
+
+ varname, usage := UnquoteUsage(flag)
+ if len(varname) > 0 {
+ line += " " + varname
+ }
+ if len(flag.NoOptDefVal) > 0 {
+ switch flag.Value.Type() {
+ case "string":
+ line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal)
+ case "bool":
+ if flag.NoOptDefVal != "true" {
+ line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
+ }
+ default:
+ line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
+ }
+ }
+
+ // This special character will be replaced with spacing once the
+ // correct alignment is calculated
+ line += "\x00"
+ if len(line) > maxlen {
+ maxlen = len(line)
+ }
+
+ line += usage
+ if !flag.defaultIsZeroValue() {
+ if flag.Value.Type() == "string" {
+ line += fmt.Sprintf(" (default \"%s\")", flag.DefValue)
+ } else {
+ line += fmt.Sprintf(" (default %s)", flag.DefValue)
+ }
+ }
+
+ lines = append(lines, line)
+ })
+
+ for _, line := range lines {
+ sidx := strings.Index(line, "\x00")
+ spacing := strings.Repeat(" ", maxlen-sidx)
+ // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx
+ fmt.Fprintln(x, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:]))
+ }
+
+ return x.String()
+}
+
+// FlagUsages returns a string containing the usage information for all flags in
+// the FlagSet
+func (f *FlagSet) FlagUsages() string {
+ return f.FlagUsagesWrapped(0)
+}
+
+// PrintDefaults prints to standard error the default values of all defined command-line flags.
+func PrintDefaults() {
+ CommandLine.PrintDefaults()
+}
+
+// defaultUsage is the default function to print a usage message.
+func defaultUsage(f *FlagSet) {
+ fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
+ f.PrintDefaults()
+}
+
+// NOTE: Usage is not just defaultUsage(CommandLine)
+// because it serves (via godoc flag Usage) as the example
+// for how to write your own usage function.
+
+// Usage prints to standard error a usage message documenting all defined command-line flags.
+// The function is a variable that may be changed to point to a custom function.
+// By default it prints a simple header and calls PrintDefaults; for details about the
+// format of the output and how to control it, see the documentation for PrintDefaults.
+var Usage = func() {
+ fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
+ PrintDefaults()
+}
+
+// NFlag returns the number of flags that have been set.
+func (f *FlagSet) NFlag() int { return len(f.actual) }
+
+// NFlag returns the number of command-line flags that have been set.
+func NFlag() int { return len(CommandLine.actual) }
+
+// Arg returns the i'th argument. Arg(0) is the first remaining argument
+// after flags have been processed.
+func (f *FlagSet) Arg(i int) string {
+ if i < 0 || i >= len(f.args) {
+ return ""
+ }
+ return f.args[i]
+}
+
+// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
+// after flags have been processed.
+func Arg(i int) string {
+ return CommandLine.Arg(i)
+}
+
+// NArg is the number of arguments remaining after flags have been processed.
+func (f *FlagSet) NArg() int { return len(f.args) }
+
+// NArg is the number of arguments remaining after flags have been processed.
+func NArg() int { return len(CommandLine.args) }
+
+// Args returns the non-flag arguments.
+func (f *FlagSet) Args() []string { return f.args }
+
+// Args returns the non-flag command-line arguments.
+func Args() []string { return CommandLine.args }
+
+// Var defines a flag with the specified name and usage string. The type and
+// value of the flag are represented by the first argument, of type Value, which
+// typically holds a user-defined implementation of Value. For instance, the
+// caller could create a flag that turns a comma-separated string into a slice
+// of strings by giving the slice the methods of Value; in particular, Set would
+// decompose the comma-separated string into the slice.
+func (f *FlagSet) Var(value Value, name string, usage string) {
+ f.VarP(value, name, "", usage)
+}
+
+// VarPF is like VarP, but returns the flag created
+func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
+ // Remember the default value as a string; it won't change.
+ flag := &Flag{
+ Name: name,
+ Shorthand: shorthand,
+ Usage: usage,
+ Value: value,
+ DefValue: value.String(),
+ }
+ f.AddFlag(flag)
+ return flag
+}
+
+// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
+ f.VarPF(value, name, shorthand, usage)
+}
+
+// AddFlag will add the flag to the FlagSet
+func (f *FlagSet) AddFlag(flag *Flag) {
+ // Call normalizeFlagName function only once
+ normalizedFlagName := f.normalizeFlagName(flag.Name)
+
+ _, alreadythere := f.formal[normalizedFlagName]
+ if alreadythere {
+ msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
+ fmt.Fprintln(f.out(), msg)
+ panic(msg) // Happens only if flags are declared with identical names
+ }
+ if f.formal == nil {
+ f.formal = make(map[NormalizedName]*Flag)
+ }
+
+ flag.Name = string(normalizedFlagName)
+ f.formal[normalizedFlagName] = flag
+
+ if len(flag.Shorthand) == 0 {
+ return
+ }
+ if len(flag.Shorthand) > 1 {
+ fmt.Fprintf(f.out(), "%s shorthand more than ASCII character: %s\n", f.name, flag.Shorthand)
+ panic("shorthand is more than one character")
+ }
+ if f.shorthands == nil {
+ f.shorthands = make(map[byte]*Flag)
+ }
+ c := flag.Shorthand[0]
+ old, alreadythere := f.shorthands[c]
+ if alreadythere {
+ fmt.Fprintf(f.out(), "%s shorthand reused: %q for %s already used for %s\n", f.name, c, flag.Name, old.Name)
+ panic("shorthand redefinition")
+ }
+ f.shorthands[c] = flag
+}
+
+// AddFlagSet adds one FlagSet to another. If a flag is already present in f
+// the flag from newSet will be ignored
+func (f *FlagSet) AddFlagSet(newSet *FlagSet) {
+ if newSet == nil {
+ return
+ }
+ newSet.VisitAll(func(flag *Flag) {
+ if f.Lookup(flag.Name) == nil {
+ f.AddFlag(flag)
+ }
+ })
+}
+
+// Var defines a flag with the specified name and usage string. The type and
+// value of the flag are represented by the first argument, of type Value, which
+// typically holds a user-defined implementation of Value. For instance, the
+// caller could create a flag that turns a comma-separated string into a slice
+// of strings by giving the slice the methods of Value; in particular, Set would
+// decompose the comma-separated string into the slice.
+func Var(value Value, name string, usage string) {
+ CommandLine.VarP(value, name, "", usage)
+}
+
+// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
+func VarP(value Value, name, shorthand, usage string) {
+ CommandLine.VarP(value, name, shorthand, usage)
+}
+
+// failf prints to standard error a formatted error and usage message and
+// returns the error.
+func (f *FlagSet) failf(format string, a ...interface{}) error {
+ err := fmt.Errorf(format, a...)
+ fmt.Fprintln(f.out(), err)
+ f.usage()
+ return err
+}
+
+// usage calls the Usage method for the flag set, or the usage function if
+// the flag set is CommandLine.
+func (f *FlagSet) usage() {
+ if f == CommandLine {
+ Usage()
+ } else if f.Usage == nil {
+ defaultUsage(f)
+ } else {
+ f.Usage()
+ }
+}
+
+func (f *FlagSet) setFlag(flag *Flag, value string, origArg string) error {
+ if err := flag.Value.Set(value); err != nil {
+ return f.failf("invalid argument %q for %s: %v", value, origArg, err)
+ }
+ // mark as visited for Visit()
+ if f.actual == nil {
+ f.actual = make(map[NormalizedName]*Flag)
+ }
+ f.actual[f.normalizeFlagName(flag.Name)] = flag
+ flag.Changed = true
+ if len(flag.Deprecated) > 0 {
+ fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
+ }
+ if len(flag.ShorthandDeprecated) > 0 && containsShorthand(origArg, flag.Shorthand) {
+ fmt.Fprintf(os.Stderr, "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated)
+ }
+ return nil
+}
+
+func containsShorthand(arg, shorthand string) bool {
+ // filter out flags --<flag_name>
+ if strings.HasPrefix(arg, "-") {
+ return false
+ }
+ arg = strings.SplitN(arg, "=", 2)[0]
+ return strings.Contains(arg, shorthand)
+}
+
+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] == '=' {
+ err = f.failf("bad flag syntax: %s", s)
+ return
+ }
+ split := strings.SplitN(name, "=", 2)
+ name = split[0]
+ flag, alreadythere := f.formal[f.normalizeFlagName(name)]
+ if !alreadythere {
+ if name == "help" { // special case for nice help message.
+ f.usage()
+ return a, ErrHelp
+ }
+ err = f.failf("unknown flag: --%s", name)
+ return
+ }
+ var value string
+ if len(split) == 2 {
+ // '--flag=arg'
+ value = split[1]
+ } else if len(flag.NoOptDefVal) > 0 {
+ // '--flag' (arg was optional)
+ value = flag.NoOptDefVal
+ } else if len(a) > 0 {
+ // '--flag arg'
+ value = a[0]
+ a = a[1:]
+ } else {
+ // '--flag' (arg was required)
+ err = f.failf("flag needs an argument: %s", s)
+ return
+ }
+ err = fn(flag, value, s)
+ return
+}
+
+func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
+ if strings.HasPrefix(shorthands, "test.") {
+ return
+ }
+ outArgs = args
+ outShorts = shorthands[1:]
+ c := shorthands[0]
+
+ flag, alreadythere := f.shorthands[c]
+ if !alreadythere {
+ if c == 'h' { // special case for nice help message.
+ f.usage()
+ err = ErrHelp
+ return
+ }
+ //TODO continue on error
+ err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
+ return
+ }
+ var value string
+ if len(shorthands) > 2 && shorthands[1] == '=' {
+ value = shorthands[2:]
+ outShorts = ""
+ } else if len(flag.NoOptDefVal) > 0 {
+ value = flag.NoOptDefVal
+ } else if len(shorthands) > 1 {
+ value = shorthands[1:]
+ outShorts = ""
+ } else if len(args) > 0 {
+ value = args[0]
+ outArgs = args[1:]
+ } else {
+ err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
+ return
+ }
+ err = fn(flag, value, shorthands)
+ return
+}
+
+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, fn)
+ if err != nil {
+ return
+ }
+ }
+
+ return
+}
+
+func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
+ for len(args) > 0 {
+ s := args[0]
+ args = args[1:]
+ if len(s) == 0 || s[0] != '-' || len(s) == 1 {
+ if !f.interspersed {
+ f.args = append(f.args, s)
+ f.args = append(f.args, args...)
+ return nil
+ }
+ f.args = append(f.args, s)
+ continue
+ }
+
+ if s[1] == '-' {
+ if len(s) == 2 { // "--" terminates the flags
+ f.argsLenAtDash = len(f.args)
+ f.args = append(f.args, args...)
+ break
+ }
+ args, err = f.parseLongArg(s, args, fn)
+ } else {
+ args, err = f.parseShortArg(s, args, fn)
+ }
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// Parse parses flag definitions from the argument list, which should not
+// include the command name. 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) Parse(arguments []string) error {
+ f.parsed = true
+ f.args = make([]string, 0, len(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:
+ return err
+ case ExitOnError:
+ os.Exit(2)
+ case PanicOnError:
+ panic(err)
+ }
+ }
+ return nil
+}
+
+// Parsed reports whether f.Parse has been called.
+func (f *FlagSet) Parsed() bool {
+ return f.parsed
+}
+
+// Parse parses the command-line flags from os.Args[1:]. Must be called
+// after all flags are defined and before flags are accessed by the program.
+func Parse() {
+ // Ignore errors; CommandLine is set for ExitOnError.
+ 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)
+}
+
+// Parsed returns true if the command-line flags have been parsed.
+func Parsed() bool {
+ return CommandLine.Parsed()
+}
+
+// CommandLine is the default set of command-line flags, parsed from os.Args.
+var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
+
+// NewFlagSet returns a new, empty flag set with the specified name and
+// error handling property.
+func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
+ f := &FlagSet{
+ name: name,
+ errorHandling: errorHandling,
+ argsLenAtDash: -1,
+ interspersed: true,
+ }
+ return f
+}
+
+// SetInterspersed sets whether to support interspersed option/non-option arguments.
+func (f *FlagSet) SetInterspersed(interspersed bool) {
+ f.interspersed = interspersed
+}
+
+// Init sets the name and error handling property for a flag set.
+// By default, the zero FlagSet uses an empty name and the
+// ContinueOnError error handling policy.
+func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
+ f.name = name
+ f.errorHandling = errorHandling
+ f.argsLenAtDash = -1
+}
diff --git a/vendor/github.com/spf13/pflag/float32.go b/vendor/github.com/spf13/pflag/float32.go
new file mode 100644
index 0000000..a243f81
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/float32.go
@@ -0,0 +1,88 @@
+package pflag
+
+import "strconv"
+
+// -- float32 Value
+type float32Value float32
+
+func newFloat32Value(val float32, p *float32) *float32Value {
+ *p = val
+ return (*float32Value)(p)
+}
+
+func (f *float32Value) Set(s string) error {
+ v, err := strconv.ParseFloat(s, 32)
+ *f = float32Value(v)
+ return err
+}
+
+func (f *float32Value) Type() string {
+ return "float32"
+}
+
+func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) }
+
+func float32Conv(sval string) (interface{}, error) {
+ v, err := strconv.ParseFloat(sval, 32)
+ if err != nil {
+ return 0, err
+ }
+ return float32(v), nil
+}
+
+// GetFloat32 return the float32 value of a flag with the given name
+func (f *FlagSet) GetFloat32(name string) (float32, error) {
+ val, err := f.getFlagType(name, "float32", float32Conv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(float32), nil
+}
+
+// Float32Var defines a float32 flag with specified name, default value, and usage string.
+// The argument p points to a float32 variable in which to store the value of the flag.
+func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) {
+ f.VarP(newFloat32Value(value, p), name, "", usage)
+}
+
+// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
+ f.VarP(newFloat32Value(value, p), name, shorthand, usage)
+}
+
+// Float32Var defines a float32 flag with specified name, default value, and usage string.
+// The argument p points to a float32 variable in which to store the value of the flag.
+func Float32Var(p *float32, name string, value float32, usage string) {
+ CommandLine.VarP(newFloat32Value(value, p), name, "", usage)
+}
+
+// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
+func Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
+ CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage)
+}
+
+// Float32 defines a float32 flag with specified name, default value, and usage string.
+// The return value is the address of a float32 variable that stores the value of the flag.
+func (f *FlagSet) Float32(name string, value float32, usage string) *float32 {
+ p := new(float32)
+ f.Float32VarP(p, name, "", value, usage)
+ return p
+}
+
+// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 {
+ p := new(float32)
+ f.Float32VarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Float32 defines a float32 flag with specified name, default value, and usage string.
+// The return value is the address of a float32 variable that stores the value of the flag.
+func Float32(name string, value float32, usage string) *float32 {
+ return CommandLine.Float32P(name, "", value, usage)
+}
+
+// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
+func Float32P(name, shorthand string, value float32, usage string) *float32 {
+ return CommandLine.Float32P(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/float64.go b/vendor/github.com/spf13/pflag/float64.go
new file mode 100644
index 0000000..04b5492
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/float64.go
@@ -0,0 +1,84 @@
+package pflag
+
+import "strconv"
+
+// -- float64 Value
+type float64Value float64
+
+func newFloat64Value(val float64, p *float64) *float64Value {
+ *p = val
+ return (*float64Value)(p)
+}
+
+func (f *float64Value) Set(s string) error {
+ v, err := strconv.ParseFloat(s, 64)
+ *f = float64Value(v)
+ return err
+}
+
+func (f *float64Value) Type() string {
+ return "float64"
+}
+
+func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) }
+
+func float64Conv(sval string) (interface{}, error) {
+ return strconv.ParseFloat(sval, 64)
+}
+
+// GetFloat64 return the float64 value of a flag with the given name
+func (f *FlagSet) GetFloat64(name string) (float64, error) {
+ val, err := f.getFlagType(name, "float64", float64Conv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(float64), nil
+}
+
+// Float64Var defines a float64 flag with specified name, default value, and usage string.
+// The argument p points to a float64 variable in which to store the value of the flag.
+func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
+ f.VarP(newFloat64Value(value, p), name, "", usage)
+}
+
+// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
+ f.VarP(newFloat64Value(value, p), name, shorthand, usage)
+}
+
+// Float64Var defines a float64 flag with specified name, default value, and usage string.
+// The argument p points to a float64 variable in which to store the value of the flag.
+func Float64Var(p *float64, name string, value float64, usage string) {
+ CommandLine.VarP(newFloat64Value(value, p), name, "", usage)
+}
+
+// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
+func Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
+ CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage)
+}
+
+// Float64 defines a float64 flag with specified name, default value, and usage string.
+// The return value is the address of a float64 variable that stores the value of the flag.
+func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
+ p := new(float64)
+ f.Float64VarP(p, name, "", value, usage)
+ return p
+}
+
+// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 {
+ p := new(float64)
+ f.Float64VarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Float64 defines a float64 flag with specified name, default value, and usage string.
+// The return value is the address of a float64 variable that stores the value of the flag.
+func Float64(name string, value float64, usage string) *float64 {
+ return CommandLine.Float64P(name, "", value, usage)
+}
+
+// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
+func Float64P(name, shorthand string, value float64, usage string) *float64 {
+ return CommandLine.Float64P(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go
new file mode 100644
index 0000000..c4f47eb
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/golangflag.go
@@ -0,0 +1,101 @@
+// Copyright 2009 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 pflag
+
+import (
+ goflag "flag"
+ "reflect"
+ "strings"
+)
+
+// flagValueWrapper implements pflag.Value around a flag.Value. The main
+// difference here is the addition of the Type method that returns a string
+// name of the type. As this is generally unknown, we approximate that with
+// reflection.
+type flagValueWrapper struct {
+ inner goflag.Value
+ flagType string
+}
+
+// We are just copying the boolFlag interface out of goflag as that is what
+// they use to decide if a flag should get "true" when no arg is given.
+type goBoolFlag interface {
+ goflag.Value
+ IsBoolFlag() bool
+}
+
+func wrapFlagValue(v goflag.Value) Value {
+ // If the flag.Value happens to also be a pflag.Value, just use it directly.
+ if pv, ok := v.(Value); ok {
+ return pv
+ }
+
+ pv := &flagValueWrapper{
+ inner: v,
+ }
+
+ t := reflect.TypeOf(v)
+ if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr {
+ t = t.Elem()
+ }
+
+ pv.flagType = strings.TrimSuffix(t.Name(), "Value")
+ return pv
+}
+
+func (v *flagValueWrapper) String() string {
+ return v.inner.String()
+}
+
+func (v *flagValueWrapper) Set(s string) error {
+ return v.inner.Set(s)
+}
+
+func (v *flagValueWrapper) Type() string {
+ return v.flagType
+}
+
+// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag
+// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei
+// with both `-v` and `--v` in flags. If the golang flag was more than a single
+// character (ex: `verbose`) it will only be accessible via `--verbose`
+func PFlagFromGoFlag(goflag *goflag.Flag) *Flag {
+ // Remember the default value as a string; it won't change.
+ flag := &Flag{
+ Name: goflag.Name,
+ Usage: goflag.Usage,
+ Value: wrapFlagValue(goflag.Value),
+ // Looks like golang flags don't set DefValue correctly :-(
+ //DefValue: goflag.DefValue,
+ DefValue: goflag.Value.String(),
+ }
+ // Ex: if the golang flag was -v, allow both -v and --v to work
+ if len(flag.Name) == 1 {
+ flag.Shorthand = flag.Name
+ }
+ if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() {
+ flag.NoOptDefVal = "true"
+ }
+ return flag
+}
+
+// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet
+func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) {
+ if f.Lookup(goflag.Name) != nil {
+ return
+ }
+ newflag := PFlagFromGoFlag(goflag)
+ f.AddFlag(newflag)
+}
+
+// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet
+func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) {
+ if newSet == nil {
+ return
+ }
+ newSet.VisitAll(func(goflag *goflag.Flag) {
+ f.AddGoFlag(goflag)
+ })
+}
diff --git a/vendor/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go
new file mode 100644
index 0000000..1474b89
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/int.go
@@ -0,0 +1,84 @@
+package pflag
+
+import "strconv"
+
+// -- int Value
+type intValue int
+
+func newIntValue(val int, p *int) *intValue {
+ *p = val
+ return (*intValue)(p)
+}
+
+func (i *intValue) Set(s string) error {
+ v, err := strconv.ParseInt(s, 0, 64)
+ *i = intValue(v)
+ return err
+}
+
+func (i *intValue) Type() string {
+ return "int"
+}
+
+func (i *intValue) String() string { return strconv.Itoa(int(*i)) }
+
+func intConv(sval string) (interface{}, error) {
+ return strconv.Atoi(sval)
+}
+
+// GetInt return the int value of a flag with the given name
+func (f *FlagSet) GetInt(name string) (int, error) {
+ val, err := f.getFlagType(name, "int", intConv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(int), nil
+}
+
+// IntVar defines an int flag with specified name, default value, and usage string.
+// The argument p points to an int variable in which to store the value of the flag.
+func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
+ f.VarP(newIntValue(value, p), name, "", usage)
+}
+
+// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) {
+ f.VarP(newIntValue(value, p), name, shorthand, usage)
+}
+
+// IntVar defines an int flag with specified name, default value, and usage string.
+// The argument p points to an int variable in which to store the value of the flag.
+func IntVar(p *int, name string, value int, usage string) {
+ CommandLine.VarP(newIntValue(value, p), name, "", usage)
+}
+
+// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash.
+func IntVarP(p *int, name, shorthand string, value int, usage string) {
+ CommandLine.VarP(newIntValue(value, p), name, shorthand, usage)
+}
+
+// Int defines an int flag with specified name, default value, and usage string.
+// The return value is the address of an int variable that stores the value of the flag.
+func (f *FlagSet) Int(name string, value int, usage string) *int {
+ p := new(int)
+ f.IntVarP(p, name, "", value, usage)
+ return p
+}
+
+// IntP is like Int, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int {
+ p := new(int)
+ f.IntVarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Int defines an int flag with specified name, default value, and usage string.
+// The return value is the address of an int variable that stores the value of the flag.
+func Int(name string, value int, usage string) *int {
+ return CommandLine.IntP(name, "", value, usage)
+}
+
+// IntP is like Int, but accepts a shorthand letter that can be used after a single dash.
+func IntP(name, shorthand string, value int, usage string) *int {
+ return CommandLine.IntP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/int32.go b/vendor/github.com/spf13/pflag/int32.go
new file mode 100644
index 0000000..9b95944
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/int32.go
@@ -0,0 +1,88 @@
+package pflag
+
+import "strconv"
+
+// -- int32 Value
+type int32Value int32
+
+func newInt32Value(val int32, p *int32) *int32Value {
+ *p = val
+ return (*int32Value)(p)
+}
+
+func (i *int32Value) Set(s string) error {
+ v, err := strconv.ParseInt(s, 0, 32)
+ *i = int32Value(v)
+ return err
+}
+
+func (i *int32Value) Type() string {
+ return "int32"
+}
+
+func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) }
+
+func int32Conv(sval string) (interface{}, error) {
+ v, err := strconv.ParseInt(sval, 0, 32)
+ if err != nil {
+ return 0, err
+ }
+ return int32(v), nil
+}
+
+// GetInt32 return the int32 value of a flag with the given name
+func (f *FlagSet) GetInt32(name string) (int32, error) {
+ val, err := f.getFlagType(name, "int32", int32Conv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(int32), nil
+}
+
+// Int32Var defines an int32 flag with specified name, default value, and usage string.
+// The argument p points to an int32 variable in which to store the value of the flag.
+func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) {
+ f.VarP(newInt32Value(value, p), name, "", usage)
+}
+
+// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
+ f.VarP(newInt32Value(value, p), name, shorthand, usage)
+}
+
+// Int32Var defines an int32 flag with specified name, default value, and usage string.
+// The argument p points to an int32 variable in which to store the value of the flag.
+func Int32Var(p *int32, name string, value int32, usage string) {
+ CommandLine.VarP(newInt32Value(value, p), name, "", usage)
+}
+
+// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash.
+func Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
+ CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage)
+}
+
+// Int32 defines an int32 flag with specified name, default value, and usage string.
+// The return value is the address of an int32 variable that stores the value of the flag.
+func (f *FlagSet) Int32(name string, value int32, usage string) *int32 {
+ p := new(int32)
+ f.Int32VarP(p, name, "", value, usage)
+ return p
+}
+
+// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 {
+ p := new(int32)
+ f.Int32VarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Int32 defines an int32 flag with specified name, default value, and usage string.
+// The return value is the address of an int32 variable that stores the value of the flag.
+func Int32(name string, value int32, usage string) *int32 {
+ return CommandLine.Int32P(name, "", value, usage)
+}
+
+// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash.
+func Int32P(name, shorthand string, value int32, usage string) *int32 {
+ return CommandLine.Int32P(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/int64.go b/vendor/github.com/spf13/pflag/int64.go
new file mode 100644
index 0000000..0026d78
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/int64.go
@@ -0,0 +1,84 @@
+package pflag
+
+import "strconv"
+
+// -- int64 Value
+type int64Value int64
+
+func newInt64Value(val int64, p *int64) *int64Value {
+ *p = val
+ return (*int64Value)(p)
+}
+
+func (i *int64Value) Set(s string) error {
+ v, err := strconv.ParseInt(s, 0, 64)
+ *i = int64Value(v)
+ return err
+}
+
+func (i *int64Value) Type() string {
+ return "int64"
+}
+
+func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) }
+
+func int64Conv(sval string) (interface{}, error) {
+ return strconv.ParseInt(sval, 0, 64)
+}
+
+// GetInt64 return the int64 value of a flag with the given name
+func (f *FlagSet) GetInt64(name string) (int64, error) {
+ val, err := f.getFlagType(name, "int64", int64Conv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(int64), nil
+}
+
+// Int64Var defines an int64 flag with specified name, default value, and usage string.
+// The argument p points to an int64 variable in which to store the value of the flag.
+func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
+ f.VarP(newInt64Value(value, p), name, "", usage)
+}
+
+// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
+ f.VarP(newInt64Value(value, p), name, shorthand, usage)
+}
+
+// Int64Var defines an int64 flag with specified name, default value, and usage string.
+// The argument p points to an int64 variable in which to store the value of the flag.
+func Int64Var(p *int64, name string, value int64, usage string) {
+ CommandLine.VarP(newInt64Value(value, p), name, "", usage)
+}
+
+// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash.
+func Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
+ CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage)
+}
+
+// Int64 defines an int64 flag with specified name, default value, and usage string.
+// The return value is the address of an int64 variable that stores the value of the flag.
+func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
+ p := new(int64)
+ f.Int64VarP(p, name, "", value, usage)
+ return p
+}
+
+// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 {
+ p := new(int64)
+ f.Int64VarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Int64 defines an int64 flag with specified name, default value, and usage string.
+// The return value is the address of an int64 variable that stores the value of the flag.
+func Int64(name string, value int64, usage string) *int64 {
+ return CommandLine.Int64P(name, "", value, usage)
+}
+
+// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash.
+func Int64P(name, shorthand string, value int64, usage string) *int64 {
+ return CommandLine.Int64P(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/int8.go b/vendor/github.com/spf13/pflag/int8.go
new file mode 100644
index 0000000..4da9222
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/int8.go
@@ -0,0 +1,88 @@
+package pflag
+
+import "strconv"
+
+// -- int8 Value
+type int8Value int8
+
+func newInt8Value(val int8, p *int8) *int8Value {
+ *p = val
+ return (*int8Value)(p)
+}
+
+func (i *int8Value) Set(s string) error {
+ v, err := strconv.ParseInt(s, 0, 8)
+ *i = int8Value(v)
+ return err
+}
+
+func (i *int8Value) Type() string {
+ return "int8"
+}
+
+func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) }
+
+func int8Conv(sval string) (interface{}, error) {
+ v, err := strconv.ParseInt(sval, 0, 8)
+ if err != nil {
+ return 0, err
+ }
+ return int8(v), nil
+}
+
+// GetInt8 return the int8 value of a flag with the given name
+func (f *FlagSet) GetInt8(name string) (int8, error) {
+ val, err := f.getFlagType(name, "int8", int8Conv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(int8), nil
+}
+
+// Int8Var defines an int8 flag with specified name, default value, and usage string.
+// The argument p points to an int8 variable in which to store the value of the flag.
+func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) {
+ f.VarP(newInt8Value(value, p), name, "", usage)
+}
+
+// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
+ f.VarP(newInt8Value(value, p), name, shorthand, usage)
+}
+
+// Int8Var defines an int8 flag with specified name, default value, and usage string.
+// The argument p points to an int8 variable in which to store the value of the flag.
+func Int8Var(p *int8, name string, value int8, usage string) {
+ CommandLine.VarP(newInt8Value(value, p), name, "", usage)
+}
+
+// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash.
+func Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
+ CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage)
+}
+
+// Int8 defines an int8 flag with specified name, default value, and usage string.
+// The return value is the address of an int8 variable that stores the value of the flag.
+func (f *FlagSet) Int8(name string, value int8, usage string) *int8 {
+ p := new(int8)
+ f.Int8VarP(p, name, "", value, usage)
+ return p
+}
+
+// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 {
+ p := new(int8)
+ f.Int8VarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Int8 defines an int8 flag with specified name, default value, and usage string.
+// The return value is the address of an int8 variable that stores the value of the flag.
+func Int8(name string, value int8, usage string) *int8 {
+ return CommandLine.Int8P(name, "", value, usage)
+}
+
+// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash.
+func Int8P(name, shorthand string, value int8, usage string) *int8 {
+ return CommandLine.Int8P(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/int_slice.go b/vendor/github.com/spf13/pflag/int_slice.go
new file mode 100644
index 0000000..1e7c9ed
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/int_slice.go
@@ -0,0 +1,128 @@
+package pflag
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// -- intSlice Value
+type intSliceValue struct {
+ value *[]int
+ changed bool
+}
+
+func newIntSliceValue(val []int, p *[]int) *intSliceValue {
+ isv := new(intSliceValue)
+ isv.value = p
+ *isv.value = val
+ return isv
+}
+
+func (s *intSliceValue) Set(val string) error {
+ ss := strings.Split(val, ",")
+ out := make([]int, len(ss))
+ for i, d := range ss {
+ var err error
+ out[i], err = strconv.Atoi(d)
+ if err != nil {
+ return err
+ }
+
+ }
+ if !s.changed {
+ *s.value = out
+ } else {
+ *s.value = append(*s.value, out...)
+ }
+ s.changed = true
+ return nil
+}
+
+func (s *intSliceValue) Type() string {
+ return "intSlice"
+}
+
+func (s *intSliceValue) String() string {
+ out := make([]string, len(*s.value))
+ for i, d := range *s.value {
+ out[i] = fmt.Sprintf("%d", d)
+ }
+ return "[" + strings.Join(out, ",") + "]"
+}
+
+func intSliceConv(val string) (interface{}, error) {
+ val = strings.Trim(val, "[]")
+ // Empty string would cause a slice with one (empty) entry
+ if len(val) == 0 {
+ return []int{}, nil
+ }
+ ss := strings.Split(val, ",")
+ out := make([]int, len(ss))
+ for i, d := range ss {
+ var err error
+ out[i], err = strconv.Atoi(d)
+ if err != nil {
+ return nil, err
+ }
+
+ }
+ return out, nil
+}
+
+// GetIntSlice return the []int value of a flag with the given name
+func (f *FlagSet) GetIntSlice(name string) ([]int, error) {
+ val, err := f.getFlagType(name, "intSlice", intSliceConv)
+ if err != nil {
+ return []int{}, err
+ }
+ return val.([]int), nil
+}
+
+// IntSliceVar defines a intSlice flag with specified name, default value, and usage string.
+// The argument p points to a []int variable in which to store the value of the flag.
+func (f *FlagSet) IntSliceVar(p *[]int, name string, value []int, usage string) {
+ f.VarP(newIntSliceValue(value, p), name, "", usage)
+}
+
+// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) {
+ f.VarP(newIntSliceValue(value, p), name, shorthand, usage)
+}
+
+// IntSliceVar defines a int[] flag with specified name, default value, and usage string.
+// The argument p points to a int[] variable in which to store the value of the flag.
+func IntSliceVar(p *[]int, name string, value []int, usage string) {
+ CommandLine.VarP(newIntSliceValue(value, p), name, "", usage)
+}
+
+// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash.
+func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) {
+ CommandLine.VarP(newIntSliceValue(value, p), name, shorthand, usage)
+}
+
+// IntSlice defines a []int flag with specified name, default value, and usage string.
+// The return value is the address of a []int variable that stores the value of the flag.
+func (f *FlagSet) IntSlice(name string, value []int, usage string) *[]int {
+ p := []int{}
+ f.IntSliceVarP(&p, name, "", value, usage)
+ return &p
+}
+
+// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IntSliceP(name, shorthand string, value []int, usage string) *[]int {
+ p := []int{}
+ f.IntSliceVarP(&p, name, shorthand, value, usage)
+ return &p
+}
+
+// IntSlice defines a []int flag with specified name, default value, and usage string.
+// The return value is the address of a []int variable that stores the value of the flag.
+func IntSlice(name string, value []int, usage string) *[]int {
+ return CommandLine.IntSliceP(name, "", value, usage)
+}
+
+// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash.
+func IntSliceP(name, shorthand string, value []int, usage string) *[]int {
+ return CommandLine.IntSliceP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go
new file mode 100644
index 0000000..3d414ba
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/ip.go
@@ -0,0 +1,94 @@
+package pflag
+
+import (
+ "fmt"
+ "net"
+ "strings"
+)
+
+// -- net.IP value
+type ipValue net.IP
+
+func newIPValue(val net.IP, p *net.IP) *ipValue {
+ *p = val
+ return (*ipValue)(p)
+}
+
+func (i *ipValue) String() string { return net.IP(*i).String() }
+func (i *ipValue) Set(s string) error {
+ ip := net.ParseIP(strings.TrimSpace(s))
+ if ip == nil {
+ return fmt.Errorf("failed to parse IP: %q", s)
+ }
+ *i = ipValue(ip)
+ return nil
+}
+
+func (i *ipValue) Type() string {
+ return "ip"
+}
+
+func ipConv(sval string) (interface{}, error) {
+ ip := net.ParseIP(sval)
+ if ip != nil {
+ return ip, nil
+ }
+ return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
+}
+
+// GetIP return the net.IP value of a flag with the given name
+func (f *FlagSet) GetIP(name string) (net.IP, error) {
+ val, err := f.getFlagType(name, "ip", ipConv)
+ if err != nil {
+ return nil, err
+ }
+ return val.(net.IP), nil
+}
+
+// IPVar defines an net.IP flag with specified name, default value, and usage string.
+// The argument p points to an net.IP variable in which to store the value of the flag.
+func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) {
+ f.VarP(newIPValue(value, p), name, "", usage)
+}
+
+// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
+ f.VarP(newIPValue(value, p), name, shorthand, usage)
+}
+
+// IPVar defines an net.IP flag with specified name, default value, and usage string.
+// The argument p points to an net.IP variable in which to store the value of the flag.
+func IPVar(p *net.IP, name string, value net.IP, usage string) {
+ CommandLine.VarP(newIPValue(value, p), name, "", usage)
+}
+
+// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash.
+func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
+ CommandLine.VarP(newIPValue(value, p), name, shorthand, usage)
+}
+
+// IP defines an net.IP flag with specified name, default value, and usage string.
+// The return value is the address of an net.IP variable that stores the value of the flag.
+func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP {
+ p := new(net.IP)
+ f.IPVarP(p, name, "", value, usage)
+ return p
+}
+
+// IPP is like IP, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP {
+ p := new(net.IP)
+ f.IPVarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// IP defines an net.IP flag with specified name, default value, and usage string.
+// The return value is the address of an net.IP variable that stores the value of the flag.
+func IP(name string, value net.IP, usage string) *net.IP {
+ return CommandLine.IPP(name, "", value, usage)
+}
+
+// IPP is like IP, but accepts a shorthand letter that can be used after a single dash.
+func IPP(name, shorthand string, value net.IP, usage string) *net.IP {
+ return CommandLine.IPP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/ip_slice.go b/vendor/github.com/spf13/pflag/ip_slice.go
new file mode 100644
index 0000000..7dd196f
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/ip_slice.go
@@ -0,0 +1,148 @@
+package pflag
+
+import (
+ "fmt"
+ "io"
+ "net"
+ "strings"
+)
+
+// -- ipSlice Value
+type ipSliceValue struct {
+ value *[]net.IP
+ changed bool
+}
+
+func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue {
+ ipsv := new(ipSliceValue)
+ ipsv.value = p
+ *ipsv.value = val
+ return ipsv
+}
+
+// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag.
+// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended.
+func (s *ipSliceValue) Set(val string) error {
+
+ // remove all quote characters
+ rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
+
+ // read flag arguments with CSV parser
+ ipStrSlice, err := readAsCSV(rmQuote.Replace(val))
+ if err != nil && err != io.EOF {
+ return err
+ }
+
+ // parse ip values into slice
+ out := make([]net.IP, 0, len(ipStrSlice))
+ for _, ipStr := range ipStrSlice {
+ ip := net.ParseIP(strings.TrimSpace(ipStr))
+ if ip == nil {
+ return fmt.Errorf("invalid string being converted to IP address: %s", ipStr)
+ }
+ out = append(out, ip)
+ }
+
+ if !s.changed {
+ *s.value = out
+ } else {
+ *s.value = append(*s.value, out...)
+ }
+
+ s.changed = true
+
+ return nil
+}
+
+// Type returns a string that uniquely represents this flag's type.
+func (s *ipSliceValue) Type() string {
+ return "ipSlice"
+}
+
+// String defines a "native" format for this net.IP slice flag value.
+func (s *ipSliceValue) String() string {
+
+ ipStrSlice := make([]string, len(*s.value))
+ for i, ip := range *s.value {
+ ipStrSlice[i] = ip.String()
+ }
+
+ out, _ := writeAsCSV(ipStrSlice)
+
+ return "[" + out + "]"
+}
+
+func ipSliceConv(val string) (interface{}, error) {
+ val = strings.Trim(val, "[]")
+ // Emtpy string would cause a slice with one (empty) entry
+ if len(val) == 0 {
+ return []net.IP{}, nil
+ }
+ ss := strings.Split(val, ",")
+ out := make([]net.IP, len(ss))
+ for i, sval := range ss {
+ ip := net.ParseIP(strings.TrimSpace(sval))
+ if ip == nil {
+ return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
+ }
+ out[i] = ip
+ }
+ return out, nil
+}
+
+// GetIPSlice returns the []net.IP value of a flag with the given name
+func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) {
+ val, err := f.getFlagType(name, "ipSlice", ipSliceConv)
+ if err != nil {
+ return []net.IP{}, err
+ }
+ return val.([]net.IP), nil
+}
+
+// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string.
+// The argument p points to a []net.IP variable in which to store the value of the flag.
+func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
+ f.VarP(newIPSliceValue(value, p), name, "", usage)
+}
+
+// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
+ f.VarP(newIPSliceValue(value, p), name, shorthand, usage)
+}
+
+// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string.
+// The argument p points to a []net.IP variable in which to store the value of the flag.
+func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
+ CommandLine.VarP(newIPSliceValue(value, p), name, "", usage)
+}
+
+// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
+func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
+ CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage)
+}
+
+// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
+// The return value is the address of a []net.IP variable that stores the value of that flag.
+func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP {
+ p := []net.IP{}
+ f.IPSliceVarP(&p, name, "", value, usage)
+ return &p
+}
+
+// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
+ p := []net.IP{}
+ f.IPSliceVarP(&p, name, shorthand, value, usage)
+ return &p
+}
+
+// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
+// The return value is the address of a []net.IP variable that stores the value of the flag.
+func IPSlice(name string, value []net.IP, usage string) *[]net.IP {
+ return CommandLine.IPSliceP(name, "", value, usage)
+}
+
+// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
+func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
+ return CommandLine.IPSliceP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/ipmask.go b/vendor/github.com/spf13/pflag/ipmask.go
new file mode 100644
index 0000000..5bd44bd
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/ipmask.go
@@ -0,0 +1,122 @@
+package pflag
+
+import (
+ "fmt"
+ "net"
+ "strconv"
+)
+
+// -- net.IPMask value
+type ipMaskValue net.IPMask
+
+func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue {
+ *p = val
+ return (*ipMaskValue)(p)
+}
+
+func (i *ipMaskValue) String() string { return net.IPMask(*i).String() }
+func (i *ipMaskValue) Set(s string) error {
+ ip := ParseIPv4Mask(s)
+ if ip == nil {
+ return fmt.Errorf("failed to parse IP mask: %q", s)
+ }
+ *i = ipMaskValue(ip)
+ return nil
+}
+
+func (i *ipMaskValue) Type() string {
+ return "ipMask"
+}
+
+// ParseIPv4Mask written in IP form (e.g. 255.255.255.0).
+// This function should really belong to the net package.
+func ParseIPv4Mask(s string) net.IPMask {
+ mask := net.ParseIP(s)
+ if mask == nil {
+ if len(s) != 8 {
+ return nil
+ }
+ // net.IPMask.String() actually outputs things like ffffff00
+ // so write a horrible parser for that as well :-(
+ m := []int{}
+ for i := 0; i < 4; i++ {
+ b := "0x" + s[2*i:2*i+2]
+ d, err := strconv.ParseInt(b, 0, 0)
+ if err != nil {
+ return nil
+ }
+ m = append(m, int(d))
+ }
+ s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3])
+ mask = net.ParseIP(s)
+ if mask == nil {
+ return nil
+ }
+ }
+ return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15])
+}
+
+func parseIPv4Mask(sval string) (interface{}, error) {
+ mask := ParseIPv4Mask(sval)
+ if mask == nil {
+ return nil, fmt.Errorf("unable to parse %s as net.IPMask", sval)
+ }
+ return mask, nil
+}
+
+// GetIPv4Mask return the net.IPv4Mask value of a flag with the given name
+func (f *FlagSet) GetIPv4Mask(name string) (net.IPMask, error) {
+ val, err := f.getFlagType(name, "ipMask", parseIPv4Mask)
+ if err != nil {
+ return nil, err
+ }
+ return val.(net.IPMask), nil
+}
+
+// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
+// The argument p points to an net.IPMask variable in which to store the value of the flag.
+func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
+ f.VarP(newIPMaskValue(value, p), name, "", usage)
+}
+
+// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
+ f.VarP(newIPMaskValue(value, p), name, shorthand, usage)
+}
+
+// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
+// The argument p points to an net.IPMask variable in which to store the value of the flag.
+func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
+ CommandLine.VarP(newIPMaskValue(value, p), name, "", usage)
+}
+
+// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
+func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
+ CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage)
+}
+
+// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
+// The return value is the address of an net.IPMask variable that stores the value of the flag.
+func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask {
+ p := new(net.IPMask)
+ f.IPMaskVarP(p, name, "", value, usage)
+ return p
+}
+
+// IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
+ p := new(net.IPMask)
+ f.IPMaskVarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
+// The return value is the address of an net.IPMask variable that stores the value of the flag.
+func IPMask(name string, value net.IPMask, usage string) *net.IPMask {
+ return CommandLine.IPMaskP(name, "", value, usage)
+}
+
+// IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash.
+func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
+ return CommandLine.IPMaskP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/ipnet.go b/vendor/github.com/spf13/pflag/ipnet.go
new file mode 100644
index 0000000..e2c1b8b
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/ipnet.go
@@ -0,0 +1,98 @@
+package pflag
+
+import (
+ "fmt"
+ "net"
+ "strings"
+)
+
+// IPNet adapts net.IPNet for use as a flag.
+type ipNetValue net.IPNet
+
+func (ipnet ipNetValue) String() string {
+ n := net.IPNet(ipnet)
+ return n.String()
+}
+
+func (ipnet *ipNetValue) Set(value string) error {
+ _, n, err := net.ParseCIDR(strings.TrimSpace(value))
+ if err != nil {
+ return err
+ }
+ *ipnet = ipNetValue(*n)
+ return nil
+}
+
+func (*ipNetValue) Type() string {
+ return "ipNet"
+}
+
+func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue {
+ *p = val
+ return (*ipNetValue)(p)
+}
+
+func ipNetConv(sval string) (interface{}, error) {
+ _, n, err := net.ParseCIDR(strings.TrimSpace(sval))
+ if err == nil {
+ return *n, nil
+ }
+ return nil, fmt.Errorf("invalid string being converted to IPNet: %s", sval)
+}
+
+// GetIPNet return the net.IPNet value of a flag with the given name
+func (f *FlagSet) GetIPNet(name string) (net.IPNet, error) {
+ val, err := f.getFlagType(name, "ipNet", ipNetConv)
+ if err != nil {
+ return net.IPNet{}, err
+ }
+ return val.(net.IPNet), nil
+}
+
+// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string.
+// The argument p points to an net.IPNet variable in which to store the value of the flag.
+func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) {
+ f.VarP(newIPNetValue(value, p), name, "", usage)
+}
+
+// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) {
+ f.VarP(newIPNetValue(value, p), name, shorthand, usage)
+}
+
+// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string.
+// The argument p points to an net.IPNet variable in which to store the value of the flag.
+func IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) {
+ CommandLine.VarP(newIPNetValue(value, p), name, "", usage)
+}
+
+// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash.
+func IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) {
+ CommandLine.VarP(newIPNetValue(value, p), name, shorthand, usage)
+}
+
+// IPNet defines an net.IPNet flag with specified name, default value, and usage string.
+// The return value is the address of an net.IPNet variable that stores the value of the flag.
+func (f *FlagSet) IPNet(name string, value net.IPNet, usage string) *net.IPNet {
+ p := new(net.IPNet)
+ f.IPNetVarP(p, name, "", value, usage)
+ return p
+}
+
+// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet {
+ p := new(net.IPNet)
+ f.IPNetVarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// IPNet defines an net.IPNet flag with specified name, default value, and usage string.
+// The return value is the address of an net.IPNet variable that stores the value of the flag.
+func IPNet(name string, value net.IPNet, usage string) *net.IPNet {
+ return CommandLine.IPNetP(name, "", value, usage)
+}
+
+// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash.
+func IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet {
+ return CommandLine.IPNetP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go
new file mode 100644
index 0000000..04e0a26
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/string.go
@@ -0,0 +1,80 @@
+package pflag
+
+// -- string Value
+type stringValue string
+
+func newStringValue(val string, p *string) *stringValue {
+ *p = val
+ return (*stringValue)(p)
+}
+
+func (s *stringValue) Set(val string) error {
+ *s = stringValue(val)
+ return nil
+}
+func (s *stringValue) Type() string {
+ return "string"
+}
+
+func (s *stringValue) String() string { return string(*s) }
+
+func stringConv(sval string) (interface{}, error) {
+ return sval, nil
+}
+
+// GetString return the string value of a flag with the given name
+func (f *FlagSet) GetString(name string) (string, error) {
+ val, err := f.getFlagType(name, "string", stringConv)
+ if err != nil {
+ return "", err
+ }
+ return val.(string), nil
+}
+
+// StringVar defines a string flag with specified name, default value, and usage string.
+// The argument p points to a string variable in which to store the value of the flag.
+func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
+ f.VarP(newStringValue(value, p), name, "", usage)
+}
+
+// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) {
+ f.VarP(newStringValue(value, p), name, shorthand, usage)
+}
+
+// StringVar defines a string flag with specified name, default value, and usage string.
+// The argument p points to a string variable in which to store the value of the flag.
+func StringVar(p *string, name string, value string, usage string) {
+ CommandLine.VarP(newStringValue(value, p), name, "", usage)
+}
+
+// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash.
+func StringVarP(p *string, name, shorthand string, value string, usage string) {
+ CommandLine.VarP(newStringValue(value, p), name, shorthand, usage)
+}
+
+// String defines a string flag with specified name, default value, and usage string.
+// The return value is the address of a string variable that stores the value of the flag.
+func (f *FlagSet) String(name string, value string, usage string) *string {
+ p := new(string)
+ f.StringVarP(p, name, "", value, usage)
+ return p
+}
+
+// StringP is like String, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string {
+ p := new(string)
+ f.StringVarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// String defines a string flag with specified name, default value, and usage string.
+// The return value is the address of a string variable that stores the value of the flag.
+func String(name string, value string, usage string) *string {
+ return CommandLine.StringP(name, "", value, usage)
+}
+
+// StringP is like String, but accepts a shorthand letter that can be used after a single dash.
+func StringP(name, shorthand string, value string, usage string) *string {
+ return CommandLine.StringP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go
new file mode 100644
index 0000000..276b7ed
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/string_array.go
@@ -0,0 +1,103 @@
+package pflag
+
+// -- stringArray Value
+type stringArrayValue struct {
+ value *[]string
+ changed bool
+}
+
+func newStringArrayValue(val []string, p *[]string) *stringArrayValue {
+ ssv := new(stringArrayValue)
+ ssv.value = p
+ *ssv.value = val
+ return ssv
+}
+
+func (s *stringArrayValue) Set(val string) error {
+ if !s.changed {
+ *s.value = []string{val}
+ s.changed = true
+ } else {
+ *s.value = append(*s.value, val)
+ }
+ return nil
+}
+
+func (s *stringArrayValue) Type() string {
+ return "stringArray"
+}
+
+func (s *stringArrayValue) String() string {
+ str, _ := writeAsCSV(*s.value)
+ return "[" + str + "]"
+}
+
+func stringArrayConv(sval string) (interface{}, error) {
+ sval = sval[1 : len(sval)-1]
+ // An empty string would cause a array with one (empty) string
+ if len(sval) == 0 {
+ return []string{}, nil
+ }
+ return readAsCSV(sval)
+}
+
+// GetStringArray return the []string value of a flag with the given name
+func (f *FlagSet) GetStringArray(name string) ([]string, error) {
+ val, err := f.getFlagType(name, "stringArray", stringArrayConv)
+ if err != nil {
+ return []string{}, err
+ }
+ return val.([]string), nil
+}
+
+// StringArrayVar defines a string flag with specified name, default value, and usage string.
+// The argument p points to a []string variable in which to store the values of the multiple flags.
+// The value of each argument will not try to be separated by comma
+func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) {
+ f.VarP(newStringArrayValue(value, p), name, "", usage)
+}
+
+// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
+ f.VarP(newStringArrayValue(value, p), name, shorthand, usage)
+}
+
+// StringArrayVar defines a string flag with specified name, default value, and usage string.
+// The argument p points to a []string variable in which to store the value of the flag.
+// The value of each argument will not try to be separated by comma
+func StringArrayVar(p *[]string, name string, value []string, usage string) {
+ CommandLine.VarP(newStringArrayValue(value, p), name, "", usage)
+}
+
+// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
+func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
+ CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage)
+}
+
+// StringArray defines a string flag with specified name, default value, and usage string.
+// The return value is the address of a []string variable that stores the value of the flag.
+// The value of each argument will not try to be separated by comma
+func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string {
+ p := []string{}
+ f.StringArrayVarP(&p, name, "", value, usage)
+ return &p
+}
+
+// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string {
+ p := []string{}
+ f.StringArrayVarP(&p, name, shorthand, value, usage)
+ return &p
+}
+
+// StringArray defines a string flag with specified name, default value, and usage string.
+// The return value is the address of a []string variable that stores the value of the flag.
+// The value of each argument will not try to be separated by comma
+func StringArray(name string, value []string, usage string) *[]string {
+ return CommandLine.StringArrayP(name, "", value, usage)
+}
+
+// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
+func StringArrayP(name, shorthand string, value []string, usage string) *[]string {
+ return CommandLine.StringArrayP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go
new file mode 100644
index 0000000..05eee75
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/string_slice.go
@@ -0,0 +1,129 @@
+package pflag
+
+import (
+ "bytes"
+ "encoding/csv"
+ "strings"
+)
+
+// -- stringSlice Value
+type stringSliceValue struct {
+ value *[]string
+ changed bool
+}
+
+func newStringSliceValue(val []string, p *[]string) *stringSliceValue {
+ ssv := new(stringSliceValue)
+ ssv.value = p
+ *ssv.value = val
+ return ssv
+}
+
+func readAsCSV(val string) ([]string, error) {
+ if val == "" {
+ return []string{}, nil
+ }
+ stringReader := strings.NewReader(val)
+ csvReader := csv.NewReader(stringReader)
+ return csvReader.Read()
+}
+
+func writeAsCSV(vals []string) (string, error) {
+ b := &bytes.Buffer{}
+ w := csv.NewWriter(b)
+ err := w.Write(vals)
+ if err != nil {
+ return "", err
+ }
+ w.Flush()
+ return strings.TrimSuffix(b.String(), "\n"), nil
+}
+
+func (s *stringSliceValue) Set(val string) error {
+ v, err := readAsCSV(val)
+ if err != nil {
+ return err
+ }
+ if !s.changed {
+ *s.value = v
+ } else {
+ *s.value = append(*s.value, v...)
+ }
+ s.changed = true
+ return nil
+}
+
+func (s *stringSliceValue) Type() string {
+ return "stringSlice"
+}
+
+func (s *stringSliceValue) String() string {
+ str, _ := writeAsCSV(*s.value)
+ return "[" + str + "]"
+}
+
+func stringSliceConv(sval string) (interface{}, error) {
+ sval = sval[1 : len(sval)-1]
+ // An empty string would cause a slice with one (empty) string
+ if len(sval) == 0 {
+ return []string{}, nil
+ }
+ return readAsCSV(sval)
+}
+
+// GetStringSlice return the []string value of a flag with the given name
+func (f *FlagSet) GetStringSlice(name string) ([]string, error) {
+ val, err := f.getFlagType(name, "stringSlice", stringSliceConv)
+ if err != nil {
+ return []string{}, err
+ }
+ return val.([]string), nil
+}
+
+// StringSliceVar defines a string flag with specified name, default value, and usage string.
+// The argument p points to a []string variable in which to store the value of the flag.
+func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) {
+ f.VarP(newStringSliceValue(value, p), name, "", usage)
+}
+
+// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) {
+ f.VarP(newStringSliceValue(value, p), name, shorthand, usage)
+}
+
+// StringSliceVar defines a string flag with specified name, default value, and usage string.
+// The argument p points to a []string variable in which to store the value of the flag.
+func StringSliceVar(p *[]string, name string, value []string, usage string) {
+ CommandLine.VarP(newStringSliceValue(value, p), name, "", usage)
+}
+
+// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash.
+func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) {
+ CommandLine.VarP(newStringSliceValue(value, p), name, shorthand, usage)
+}
+
+// StringSlice defines a string flag with specified name, default value, and usage string.
+// The return value is the address of a []string variable that stores the value of the flag.
+func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string {
+ p := []string{}
+ f.StringSliceVarP(&p, name, "", value, usage)
+ return &p
+}
+
+// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage string) *[]string {
+ p := []string{}
+ f.StringSliceVarP(&p, name, shorthand, value, usage)
+ return &p
+}
+
+// StringSlice defines a string flag with specified name, default value, and usage string.
+// The return value is the address of a []string variable that stores the value of the flag.
+func StringSlice(name string, value []string, usage string) *[]string {
+ return CommandLine.StringSliceP(name, "", value, usage)
+}
+
+// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash.
+func StringSliceP(name, shorthand string, value []string, usage string) *[]string {
+ return CommandLine.StringSliceP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/uint.go b/vendor/github.com/spf13/pflag/uint.go
new file mode 100644
index 0000000..dcbc2b7
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/uint.go
@@ -0,0 +1,88 @@
+package pflag
+
+import "strconv"
+
+// -- uint Value
+type uintValue uint
+
+func newUintValue(val uint, p *uint) *uintValue {
+ *p = val
+ return (*uintValue)(p)
+}
+
+func (i *uintValue) Set(s string) error {
+ v, err := strconv.ParseUint(s, 0, 64)
+ *i = uintValue(v)
+ return err
+}
+
+func (i *uintValue) Type() string {
+ return "uint"
+}
+
+func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) }
+
+func uintConv(sval string) (interface{}, error) {
+ v, err := strconv.ParseUint(sval, 0, 0)
+ if err != nil {
+ return 0, err
+ }
+ return uint(v), nil
+}
+
+// GetUint return the uint value of a flag with the given name
+func (f *FlagSet) GetUint(name string) (uint, error) {
+ val, err := f.getFlagType(name, "uint", uintConv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(uint), nil
+}
+
+// UintVar defines a uint flag with specified name, default value, and usage string.
+// The argument p points to a uint variable in which to store the value of the flag.
+func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
+ f.VarP(newUintValue(value, p), name, "", usage)
+}
+
+// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) {
+ f.VarP(newUintValue(value, p), name, shorthand, usage)
+}
+
+// UintVar defines a uint flag with specified name, default value, and usage string.
+// The argument p points to a uint variable in which to store the value of the flag.
+func UintVar(p *uint, name string, value uint, usage string) {
+ CommandLine.VarP(newUintValue(value, p), name, "", usage)
+}
+
+// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash.
+func UintVarP(p *uint, name, shorthand string, value uint, usage string) {
+ CommandLine.VarP(newUintValue(value, p), name, shorthand, usage)
+}
+
+// Uint defines a uint flag with specified name, default value, and usage string.
+// The return value is the address of a uint variable that stores the value of the flag.
+func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
+ p := new(uint)
+ f.UintVarP(p, name, "", value, usage)
+ return p
+}
+
+// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint {
+ p := new(uint)
+ f.UintVarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Uint defines a uint flag with specified name, default value, and usage string.
+// The return value is the address of a uint variable that stores the value of the flag.
+func Uint(name string, value uint, usage string) *uint {
+ return CommandLine.UintP(name, "", value, usage)
+}
+
+// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash.
+func UintP(name, shorthand string, value uint, usage string) *uint {
+ return CommandLine.UintP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/uint16.go b/vendor/github.com/spf13/pflag/uint16.go
new file mode 100644
index 0000000..7e9914e
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/uint16.go
@@ -0,0 +1,88 @@
+package pflag
+
+import "strconv"
+
+// -- uint16 value
+type uint16Value uint16
+
+func newUint16Value(val uint16, p *uint16) *uint16Value {
+ *p = val
+ return (*uint16Value)(p)
+}
+
+func (i *uint16Value) Set(s string) error {
+ v, err := strconv.ParseUint(s, 0, 16)
+ *i = uint16Value(v)
+ return err
+}
+
+func (i *uint16Value) Type() string {
+ return "uint16"
+}
+
+func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
+
+func uint16Conv(sval string) (interface{}, error) {
+ v, err := strconv.ParseUint(sval, 0, 16)
+ if err != nil {
+ return 0, err
+ }
+ return uint16(v), nil
+}
+
+// GetUint16 return the uint16 value of a flag with the given name
+func (f *FlagSet) GetUint16(name string) (uint16, error) {
+ val, err := f.getFlagType(name, "uint16", uint16Conv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(uint16), nil
+}
+
+// Uint16Var defines a uint flag with specified name, default value, and usage string.
+// The argument p points to a uint variable in which to store the value of the flag.
+func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) {
+ f.VarP(newUint16Value(value, p), name, "", usage)
+}
+
+// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
+ f.VarP(newUint16Value(value, p), name, shorthand, usage)
+}
+
+// Uint16Var defines a uint flag with specified name, default value, and usage string.
+// The argument p points to a uint variable in which to store the value of the flag.
+func Uint16Var(p *uint16, name string, value uint16, usage string) {
+ CommandLine.VarP(newUint16Value(value, p), name, "", usage)
+}
+
+// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
+func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
+ CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage)
+}
+
+// Uint16 defines a uint flag with specified name, default value, and usage string.
+// The return value is the address of a uint variable that stores the value of the flag.
+func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 {
+ p := new(uint16)
+ f.Uint16VarP(p, name, "", value, usage)
+ return p
+}
+
+// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
+ p := new(uint16)
+ f.Uint16VarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Uint16 defines a uint flag with specified name, default value, and usage string.
+// The return value is the address of a uint variable that stores the value of the flag.
+func Uint16(name string, value uint16, usage string) *uint16 {
+ return CommandLine.Uint16P(name, "", value, usage)
+}
+
+// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash.
+func Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
+ return CommandLine.Uint16P(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/uint32.go b/vendor/github.com/spf13/pflag/uint32.go
new file mode 100644
index 0000000..d802453
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/uint32.go
@@ -0,0 +1,88 @@
+package pflag
+
+import "strconv"
+
+// -- uint32 value
+type uint32Value uint32
+
+func newUint32Value(val uint32, p *uint32) *uint32Value {
+ *p = val
+ return (*uint32Value)(p)
+}
+
+func (i *uint32Value) Set(s string) error {
+ v, err := strconv.ParseUint(s, 0, 32)
+ *i = uint32Value(v)
+ return err
+}
+
+func (i *uint32Value) Type() string {
+ return "uint32"
+}
+
+func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
+
+func uint32Conv(sval string) (interface{}, error) {
+ v, err := strconv.ParseUint(sval, 0, 32)
+ if err != nil {
+ return 0, err
+ }
+ return uint32(v), nil
+}
+
+// GetUint32 return the uint32 value of a flag with the given name
+func (f *FlagSet) GetUint32(name string) (uint32, error) {
+ val, err := f.getFlagType(name, "uint32", uint32Conv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(uint32), nil
+}
+
+// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
+// The argument p points to a uint32 variable in which to store the value of the flag.
+func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) {
+ f.VarP(newUint32Value(value, p), name, "", usage)
+}
+
+// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
+ f.VarP(newUint32Value(value, p), name, shorthand, usage)
+}
+
+// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
+// The argument p points to a uint32 variable in which to store the value of the flag.
+func Uint32Var(p *uint32, name string, value uint32, usage string) {
+ CommandLine.VarP(newUint32Value(value, p), name, "", usage)
+}
+
+// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
+func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
+ CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage)
+}
+
+// Uint32 defines a uint32 flag with specified name, default value, and usage string.
+// The return value is the address of a uint32 variable that stores the value of the flag.
+func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 {
+ p := new(uint32)
+ f.Uint32VarP(p, name, "", value, usage)
+ return p
+}
+
+// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
+ p := new(uint32)
+ f.Uint32VarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Uint32 defines a uint32 flag with specified name, default value, and usage string.
+// The return value is the address of a uint32 variable that stores the value of the flag.
+func Uint32(name string, value uint32, usage string) *uint32 {
+ return CommandLine.Uint32P(name, "", value, usage)
+}
+
+// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash.
+func Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
+ return CommandLine.Uint32P(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/uint64.go b/vendor/github.com/spf13/pflag/uint64.go
new file mode 100644
index 0000000..f62240f
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/uint64.go
@@ -0,0 +1,88 @@
+package pflag
+
+import "strconv"
+
+// -- uint64 Value
+type uint64Value uint64
+
+func newUint64Value(val uint64, p *uint64) *uint64Value {
+ *p = val
+ return (*uint64Value)(p)
+}
+
+func (i *uint64Value) Set(s string) error {
+ v, err := strconv.ParseUint(s, 0, 64)
+ *i = uint64Value(v)
+ return err
+}
+
+func (i *uint64Value) Type() string {
+ return "uint64"
+}
+
+func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
+
+func uint64Conv(sval string) (interface{}, error) {
+ v, err := strconv.ParseUint(sval, 0, 64)
+ if err != nil {
+ return 0, err
+ }
+ return uint64(v), nil
+}
+
+// GetUint64 return the uint64 value of a flag with the given name
+func (f *FlagSet) GetUint64(name string) (uint64, error) {
+ val, err := f.getFlagType(name, "uint64", uint64Conv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(uint64), nil
+}
+
+// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
+// The argument p points to a uint64 variable in which to store the value of the flag.
+func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
+ f.VarP(newUint64Value(value, p), name, "", usage)
+}
+
+// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
+ f.VarP(newUint64Value(value, p), name, shorthand, usage)
+}
+
+// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
+// The argument p points to a uint64 variable in which to store the value of the flag.
+func Uint64Var(p *uint64, name string, value uint64, usage string) {
+ CommandLine.VarP(newUint64Value(value, p), name, "", usage)
+}
+
+// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
+func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
+ CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage)
+}
+
+// Uint64 defines a uint64 flag with specified name, default value, and usage string.
+// The return value is the address of a uint64 variable that stores the value of the flag.
+func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
+ p := new(uint64)
+ f.Uint64VarP(p, name, "", value, usage)
+ return p
+}
+
+// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
+ p := new(uint64)
+ f.Uint64VarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Uint64 defines a uint64 flag with specified name, default value, and usage string.
+// The return value is the address of a uint64 variable that stores the value of the flag.
+func Uint64(name string, value uint64, usage string) *uint64 {
+ return CommandLine.Uint64P(name, "", value, usage)
+}
+
+// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash.
+func Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
+ return CommandLine.Uint64P(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/uint8.go b/vendor/github.com/spf13/pflag/uint8.go
new file mode 100644
index 0000000..bb0e83c
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/uint8.go
@@ -0,0 +1,88 @@
+package pflag
+
+import "strconv"
+
+// -- uint8 Value
+type uint8Value uint8
+
+func newUint8Value(val uint8, p *uint8) *uint8Value {
+ *p = val
+ return (*uint8Value)(p)
+}
+
+func (i *uint8Value) Set(s string) error {
+ v, err := strconv.ParseUint(s, 0, 8)
+ *i = uint8Value(v)
+ return err
+}
+
+func (i *uint8Value) Type() string {
+ return "uint8"
+}
+
+func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
+
+func uint8Conv(sval string) (interface{}, error) {
+ v, err := strconv.ParseUint(sval, 0, 8)
+ if err != nil {
+ return 0, err
+ }
+ return uint8(v), nil
+}
+
+// GetUint8 return the uint8 value of a flag with the given name
+func (f *FlagSet) GetUint8(name string) (uint8, error) {
+ val, err := f.getFlagType(name, "uint8", uint8Conv)
+ if err != nil {
+ return 0, err
+ }
+ return val.(uint8), nil
+}
+
+// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
+// The argument p points to a uint8 variable in which to store the value of the flag.
+func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) {
+ f.VarP(newUint8Value(value, p), name, "", usage)
+}
+
+// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
+ f.VarP(newUint8Value(value, p), name, shorthand, usage)
+}
+
+// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
+// The argument p points to a uint8 variable in which to store the value of the flag.
+func Uint8Var(p *uint8, name string, value uint8, usage string) {
+ CommandLine.VarP(newUint8Value(value, p), name, "", usage)
+}
+
+// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
+func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
+ CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage)
+}
+
+// Uint8 defines a uint8 flag with specified name, default value, and usage string.
+// The return value is the address of a uint8 variable that stores the value of the flag.
+func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 {
+ p := new(uint8)
+ f.Uint8VarP(p, name, "", value, usage)
+ return p
+}
+
+// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
+ p := new(uint8)
+ f.Uint8VarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// Uint8 defines a uint8 flag with specified name, default value, and usage string.
+// The return value is the address of a uint8 variable that stores the value of the flag.
+func Uint8(name string, value uint8, usage string) *uint8 {
+ return CommandLine.Uint8P(name, "", value, usage)
+}
+
+// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash.
+func Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
+ return CommandLine.Uint8P(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/uint_slice.go b/vendor/github.com/spf13/pflag/uint_slice.go
new file mode 100644
index 0000000..edd94c6
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/uint_slice.go
@@ -0,0 +1,126 @@
+package pflag
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// -- uintSlice Value
+type uintSliceValue struct {
+ value *[]uint
+ changed bool
+}
+
+func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue {
+ uisv := new(uintSliceValue)
+ uisv.value = p
+ *uisv.value = val
+ return uisv
+}
+
+func (s *uintSliceValue) Set(val string) error {
+ ss := strings.Split(val, ",")
+ out := make([]uint, len(ss))
+ for i, d := range ss {
+ u, err := strconv.ParseUint(d, 10, 0)
+ if err != nil {
+ return err
+ }
+ out[i] = uint(u)
+ }
+ if !s.changed {
+ *s.value = out
+ } else {
+ *s.value = append(*s.value, out...)
+ }
+ s.changed = true
+ return nil
+}
+
+func (s *uintSliceValue) Type() string {
+ return "uintSlice"
+}
+
+func (s *uintSliceValue) String() string {
+ out := make([]string, len(*s.value))
+ for i, d := range *s.value {
+ out[i] = fmt.Sprintf("%d", d)
+ }
+ return "[" + strings.Join(out, ",") + "]"
+}
+
+func uintSliceConv(val string) (interface{}, error) {
+ val = strings.Trim(val, "[]")
+ // Empty string would cause a slice with one (empty) entry
+ if len(val) == 0 {
+ return []uint{}, nil
+ }
+ ss := strings.Split(val, ",")
+ out := make([]uint, len(ss))
+ for i, d := range ss {
+ u, err := strconv.ParseUint(d, 10, 0)
+ if err != nil {
+ return nil, err
+ }
+ out[i] = uint(u)
+ }
+ return out, nil
+}
+
+// GetUintSlice returns the []uint value of a flag with the given name.
+func (f *FlagSet) GetUintSlice(name string) ([]uint, error) {
+ val, err := f.getFlagType(name, "uintSlice", uintSliceConv)
+ if err != nil {
+ return []uint{}, err
+ }
+ return val.([]uint), nil
+}
+
+// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string.
+// The argument p points to a []uint variable in which to store the value of the flag.
+func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) {
+ f.VarP(newUintSliceValue(value, p), name, "", usage)
+}
+
+// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
+ f.VarP(newUintSliceValue(value, p), name, shorthand, usage)
+}
+
+// UintSliceVar defines a uint[] flag with specified name, default value, and usage string.
+// The argument p points to a uint[] variable in which to store the value of the flag.
+func UintSliceVar(p *[]uint, name string, value []uint, usage string) {
+ CommandLine.VarP(newUintSliceValue(value, p), name, "", usage)
+}
+
+// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
+func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
+ CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage)
+}
+
+// UintSlice defines a []uint flag with specified name, default value, and usage string.
+// The return value is the address of a []uint variable that stores the value of the flag.
+func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint {
+ p := []uint{}
+ f.UintSliceVarP(&p, name, "", value, usage)
+ return &p
+}
+
+// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
+ p := []uint{}
+ f.UintSliceVarP(&p, name, shorthand, value, usage)
+ return &p
+}
+
+// UintSlice defines a []uint flag with specified name, default value, and usage string.
+// The return value is the address of a []uint variable that stores the value of the flag.
+func UintSlice(name string, value []uint, usage string) *[]uint {
+ return CommandLine.UintSliceP(name, "", value, usage)
+}
+
+// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
+func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
+ return CommandLine.UintSliceP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/stevvooe/continuity/LICENSE b/vendor/github.com/stevvooe/continuity/LICENSE
new file mode 100644
index 0000000..8f71f43
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/LICENSE
@@ -0,0 +1,202 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/vendor/github.com/stevvooe/continuity/README.md b/vendor/github.com/stevvooe/continuity/README.md
new file mode 100644
index 0000000..50b64c2
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/README.md
@@ -0,0 +1,19 @@
+# continuity
+
+[![GoDoc](https://godoc.org/github.com/containerd/continuity?status.svg)](https://godoc.org/github.com/containerd/continuity)
+[![Build Status](https://travis-ci.org/containerd/continuity.svg?branch=master)](https://travis-ci.org/containerd/continuity)
+
+A transport-agnostic, filesystem metadata manifest system
+
+This project is a staging area for experiments in providing transport agnostic
+metadata storage.
+
+Please see https://github.com/opencontainers/specs/issues/11 for more details.
+
+## Building Proto Package
+
+If you change the proto file you will need to rebuild the generated Go with `go generate`.
+
+```
+go generate ./proto
+```
diff --git a/vendor/github.com/stevvooe/continuity/sysx/asm.s b/vendor/github.com/stevvooe/continuity/sysx/asm.s
new file mode 100644
index 0000000..8ed2fdb
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/asm.s
@@ -0,0 +1,10 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !gccgo
+
+#include "textflag.h"
+
+TEXT ·use(SB),NOSPLIT,$0
+ RET
diff --git a/vendor/github.com/stevvooe/continuity/sysx/chmod_darwin.go b/vendor/github.com/stevvooe/continuity/sysx/chmod_darwin.go
new file mode 100644
index 0000000..e3ae2b7
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/chmod_darwin.go
@@ -0,0 +1,18 @@
+package sysx
+
+const (
+ // AtSymlinkNoFollow defined from AT_SYMLINK_NOFOLLOW in <sys/fcntl.h>
+ AtSymlinkNofollow = 0x20
+)
+
+const (
+
+ // SYS_FCHMODAT defined from golang.org/sys/unix
+ SYS_FCHMODAT = 467
+)
+
+// These functions will be generated by generate.sh
+// $ GOOS=darwin GOARCH=386 ./generate.sh chmod
+// $ GOOS=darwin GOARCH=amd64 ./generate.sh chmod
+
+//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
diff --git a/vendor/github.com/stevvooe/continuity/sysx/chmod_darwin_386.go b/vendor/github.com/stevvooe/continuity/sysx/chmod_darwin_386.go
new file mode 100644
index 0000000..5a8cf5b
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/chmod_darwin_386.go
@@ -0,0 +1,25 @@
+// mksyscall.pl -l32 chmod_darwin.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// 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 = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.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
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/chmod_darwin_amd64.go b/vendor/github.com/stevvooe/continuity/sysx/chmod_darwin_amd64.go
new file mode 100644
index 0000000..3287d1d
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/chmod_darwin_amd64.go
@@ -0,0 +1,25 @@
+// mksyscall.pl chmod_darwin.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// 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 = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.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
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/chmod_freebsd.go b/vendor/github.com/stevvooe/continuity/sysx/chmod_freebsd.go
new file mode 100644
index 0000000..b64a708
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/chmod_freebsd.go
@@ -0,0 +1,17 @@
+package sysx
+
+const (
+ // AtSymlinkNoFollow defined from AT_SYMLINK_NOFOLLOW in <sys/fcntl.h>
+ AtSymlinkNofollow = 0x200
+)
+
+const (
+
+ // SYS_FCHMODAT defined from golang.org/sys/unix
+ SYS_FCHMODAT = 490
+)
+
+// These functions will be generated by generate.sh
+// $ GOOS=freebsd GOARCH=amd64 ./generate.sh chmod
+
+//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
diff --git a/vendor/github.com/stevvooe/continuity/sysx/chmod_freebsd_amd64.go b/vendor/github.com/stevvooe/continuity/sysx/chmod_freebsd_amd64.go
new file mode 100644
index 0000000..5a271ab
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/chmod_freebsd_amd64.go
@@ -0,0 +1,25 @@
+// mksyscall.pl chmod_freebsd.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// 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 = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.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
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/chmod_linux.go b/vendor/github.com/stevvooe/continuity/sysx/chmod_linux.go
new file mode 100644
index 0000000..89df6d3
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/chmod_linux.go
@@ -0,0 +1,12 @@
+package sysx
+
+import "syscall"
+
+const (
+ // AtSymlinkNoFollow defined from AT_SYMLINK_NOFOLLOW in /usr/include/linux/fcntl.h
+ AtSymlinkNofollow = 0x100
+)
+
+func Fchmodat(dirfd int, path string, mode uint32, flags int) error {
+ return syscall.Fchmodat(dirfd, path, mode, flags)
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/copy_linux.go b/vendor/github.com/stevvooe/continuity/sysx/copy_linux.go
new file mode 100644
index 0000000..d7ccbb2
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/copy_linux.go
@@ -0,0 +1,9 @@
+package sysx
+
+// These functions will be generated by generate.sh
+// $ GOOS=linux GOARCH=386 ./generate.sh copy
+// $ GOOS=linux GOARCH=amd64 ./generate.sh copy
+// $ GOOS=linux GOARCH=arm ./generate.sh copy
+// $ GOOS=linux GOARCH=arm64 ./generate.sh copy
+
+//sys CopyFileRange(fdin uintptr, offin *int64, fdout uintptr, offout *int64, len int, flags int) (n int, err error)
diff --git a/vendor/github.com/stevvooe/continuity/sysx/copy_linux_386.go b/vendor/github.com/stevvooe/continuity/sysx/copy_linux_386.go
new file mode 100644
index 0000000..c1368c5
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/copy_linux_386.go
@@ -0,0 +1,20 @@
+// mksyscall.pl -l32 copy_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func CopyFileRange(fdin uintptr, offin *int64, fdout uintptr, offout *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := syscall.Syscall6(SYS_COPY_FILE_RANGE, uintptr(fdin), uintptr(unsafe.Pointer(offin)), uintptr(fdout), uintptr(unsafe.Pointer(offout)), uintptr(len), uintptr(flags))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/copy_linux_amd64.go b/vendor/github.com/stevvooe/continuity/sysx/copy_linux_amd64.go
new file mode 100644
index 0000000..9941b01
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/copy_linux_amd64.go
@@ -0,0 +1,20 @@
+// mksyscall.pl copy_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func CopyFileRange(fdin uintptr, offin *int64, fdout uintptr, offout *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := syscall.Syscall6(SYS_COPY_FILE_RANGE, uintptr(fdin), uintptr(unsafe.Pointer(offin)), uintptr(fdout), uintptr(unsafe.Pointer(offout)), uintptr(len), uintptr(flags))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/copy_linux_arm.go b/vendor/github.com/stevvooe/continuity/sysx/copy_linux_arm.go
new file mode 100644
index 0000000..c1368c5
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/copy_linux_arm.go
@@ -0,0 +1,20 @@
+// mksyscall.pl -l32 copy_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func CopyFileRange(fdin uintptr, offin *int64, fdout uintptr, offout *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := syscall.Syscall6(SYS_COPY_FILE_RANGE, uintptr(fdin), uintptr(unsafe.Pointer(offin)), uintptr(fdout), uintptr(unsafe.Pointer(offout)), uintptr(len), uintptr(flags))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/copy_linux_arm64.go b/vendor/github.com/stevvooe/continuity/sysx/copy_linux_arm64.go
new file mode 100644
index 0000000..9941b01
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/copy_linux_arm64.go
@@ -0,0 +1,20 @@
+// mksyscall.pl copy_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func CopyFileRange(fdin uintptr, offin *int64, fdout uintptr, offout *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := syscall.Syscall6(SYS_COPY_FILE_RANGE, uintptr(fdin), uintptr(unsafe.Pointer(offin)), uintptr(fdout), uintptr(unsafe.Pointer(offout)), uintptr(len), uintptr(flags))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/nodata_linux.go b/vendor/github.com/stevvooe/continuity/sysx/nodata_linux.go
new file mode 100644
index 0000000..fc47ddb
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/nodata_linux.go
@@ -0,0 +1,7 @@
+package sysx
+
+import (
+ "syscall"
+)
+
+const ENODATA = syscall.ENODATA
diff --git a/vendor/github.com/stevvooe/continuity/sysx/nodata_unix.go b/vendor/github.com/stevvooe/continuity/sysx/nodata_unix.go
new file mode 100644
index 0000000..7e68512
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/nodata_unix.go
@@ -0,0 +1,9 @@
+// +build darwin freebsd
+
+package sysx
+
+import (
+ "syscall"
+)
+
+const ENODATA = syscall.ENOATTR
diff --git a/vendor/github.com/stevvooe/continuity/sysx/sys.go b/vendor/github.com/stevvooe/continuity/sysx/sys.go
new file mode 100644
index 0000000..0bb1676
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/sys.go
@@ -0,0 +1,37 @@
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _zero uintptr
+
+// use is a no-op, but the compiler cannot see that it is.
+// Calling use(p) ensures that p is kept live until that point.
+//go:noescape
+func use(p unsafe.Pointer)
+
+// Do the interface allocations only once for common
+// Errno values.
+var (
+ errEAGAIN error = syscall.EAGAIN
+ errEINVAL error = syscall.EINVAL
+ errENOENT error = syscall.ENOENT
+)
+
+// errnoErr returns common boxed Errno values, to prevent
+// allocations at runtime.
+func errnoErr(e syscall.Errno) error {
+ switch e {
+ case 0:
+ return nil
+ case syscall.EAGAIN:
+ return errEAGAIN
+ case syscall.EINVAL:
+ return errEINVAL
+ case syscall.ENOENT:
+ return errENOENT
+ }
+ return e
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_386.go b/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_386.go
new file mode 100644
index 0000000..0063f8a
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_386.go
@@ -0,0 +1,7 @@
+package sysx
+
+const (
+ // SYS_COPYFILERANGE defined in Kernel 4.5+
+ // Number defined in /usr/include/asm/unistd_32.h
+ SYS_COPY_FILE_RANGE = 377
+)
diff --git a/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_amd64.go b/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_amd64.go
new file mode 100644
index 0000000..4170540
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_amd64.go
@@ -0,0 +1,7 @@
+package sysx
+
+const (
+ // SYS_COPYFILERANGE defined in Kernel 4.5+
+ // Number defined in /usr/include/asm/unistd_64.h
+ SYS_COPY_FILE_RANGE = 326
+)
diff --git a/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_arm.go b/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_arm.go
new file mode 100644
index 0000000..a05dcbb
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_arm.go
@@ -0,0 +1,7 @@
+package sysx
+
+const (
+ // SYS_COPY_FILE_RANGE defined in Kernel 4.5+
+ // Number defined in /usr/include/arm-linux-gnueabihf/asm/unistd.h
+ SYS_COPY_FILE_RANGE = 391
+)
diff --git a/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_arm64.go b/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_arm64.go
new file mode 100644
index 0000000..da31bbd
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/sysnum_linux_arm64.go
@@ -0,0 +1,7 @@
+package sysx
+
+const (
+ // SYS_COPY_FILE_RANGE defined in Kernel 4.5+
+ // Number defined in /usr/include/asm-generic/unistd.h
+ SYS_COPY_FILE_RANGE = 285
+)
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr.go b/vendor/github.com/stevvooe/continuity/sysx/xattr.go
new file mode 100644
index 0000000..20937c2
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr.go
@@ -0,0 +1,67 @@
+package sysx
+
+import (
+ "bytes"
+ "fmt"
+ "syscall"
+)
+
+const defaultXattrBufferSize = 5
+
+var ErrNotSupported = fmt.Errorf("not supported")
+
+type listxattrFunc func(path string, dest []byte) (int, error)
+
+func listxattrAll(path string, listFunc listxattrFunc) ([]string, error) {
+ var p []byte // nil on first execution
+
+ for {
+ n, err := listFunc(path, p) // first call gets buffer size.
+ if err != nil {
+ return nil, err
+ }
+
+ if n > len(p) {
+ p = make([]byte, n)
+ continue
+ }
+
+ p = p[:n]
+
+ ps := bytes.Split(bytes.TrimSuffix(p, []byte{0}), []byte{0})
+ var entries []string
+ for _, p := range ps {
+ s := string(p)
+ if s != "" {
+ entries = append(entries, s)
+ }
+ }
+
+ return entries, nil
+ }
+}
+
+type getxattrFunc func(string, string, []byte) (int, error)
+
+func getxattrAll(path, attr string, getFunc getxattrFunc) ([]byte, error) {
+ p := make([]byte, defaultXattrBufferSize)
+ for {
+ n, err := getFunc(path, attr, p)
+ if err != nil {
+ if errno, ok := err.(syscall.Errno); ok && errno == syscall.ERANGE {
+ p = make([]byte, len(p)*2) // this can't be ideal.
+ continue // try again!
+ }
+
+ return nil, err
+ }
+
+ // realloc to correct size and repeat
+ if n > len(p) {
+ p = make([]byte, n)
+ continue
+ }
+
+ return p[:n], nil
+ }
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_darwin.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_darwin.go
new file mode 100644
index 0000000..1164a7d
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_darwin.go
@@ -0,0 +1,71 @@
+package sysx
+
+// These functions will be generated by generate.sh
+// $ GOOS=darwin GOARCH=386 ./generate.sh xattr
+// $ GOOS=darwin GOARCH=amd64 ./generate.sh xattr
+
+//sys getxattr(path string, attr string, dest []byte, pos int, options int) (sz int, err error)
+//sys setxattr(path string, attr string, data []byte, flags int) (err error)
+//sys removexattr(path string, attr string, options int) (err error)
+//sys listxattr(path string, dest []byte, options int) (sz int, err error)
+//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
+
+const (
+ xattrNoFollow = 0x01
+)
+
+func listxattrFollow(path string, dest []byte) (sz int, err error) {
+ return listxattr(path, dest, 0)
+}
+
+// Listxattr calls syscall getxattr
+func Listxattr(path string) ([]string, error) {
+ return listxattrAll(path, listxattrFollow)
+}
+
+// Removexattr calls syscall getxattr
+func Removexattr(path string, attr string) (err error) {
+ return removexattr(path, attr, 0)
+}
+
+// Setxattr calls syscall setxattr
+func Setxattr(path string, attr string, data []byte, flags int) (err error) {
+ return setxattr(path, attr, data, flags)
+}
+
+func getxattrFollow(path, attr string, dest []byte) (sz int, err error) {
+ return getxattr(path, attr, dest, 0, 0)
+}
+
+// Getxattr calls syscall getxattr
+func Getxattr(path, attr string) ([]byte, error) {
+ return getxattrAll(path, attr, getxattrFollow)
+}
+
+func listxattrNoFollow(path string, dest []byte) (sz int, err error) {
+ return listxattr(path, dest, xattrNoFollow)
+}
+
+// LListxattr calls syscall listxattr with XATTR_NOFOLLOW
+func LListxattr(path string) ([]string, error) {
+ return listxattrAll(path, listxattrNoFollow)
+}
+
+// LRemovexattr calls syscall removexattr with XATTR_NOFOLLOW
+func LRemovexattr(path string, attr string) (err error) {
+ return removexattr(path, attr, xattrNoFollow)
+}
+
+// Setxattr calls syscall setxattr with XATTR_NOFOLLOW
+func LSetxattr(path string, attr string, data []byte, flags int) (err error) {
+ return setxattr(path, attr, data, flags|xattrNoFollow)
+}
+
+func getxattrNoFollow(path, attr string, dest []byte) (sz int, err error) {
+ return getxattr(path, attr, dest, 0, xattrNoFollow)
+}
+
+// LGetxattr calls syscall getxattr with XATTR_NOFOLLOW
+func LGetxattr(path, attr string) ([]byte, error) {
+ return getxattrAll(path, attr, getxattrNoFollow)
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_darwin_386.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_darwin_386.go
new file mode 100644
index 0000000..aa896b5
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_darwin_386.go
@@ -0,0 +1,111 @@
+// mksyscall.pl -l32 xattr_darwin.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getxattr(path string, attr string, dest []byte, pos int, options int) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), uintptr(pos), uintptr(options))
+ 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 setxattr(path string, attr string, data []byte, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.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 removexattr(path string, attr string, options int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.BytePtrFromString(attr)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.Syscall(syscall.SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
+ 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 listxattr(path string, dest []byte, options int) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.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.Syscall6(syscall.SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)), uintptr(options), 0, 0)
+ use(unsafe.Pointer(_p0))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_darwin_amd64.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_darwin_amd64.go
new file mode 100644
index 0000000..6ff27e2
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_darwin_amd64.go
@@ -0,0 +1,111 @@
+// mksyscall.pl xattr_darwin.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getxattr(path string, attr string, dest []byte, pos int, options int) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), uintptr(pos), uintptr(options))
+ 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 setxattr(path string, attr string, data []byte, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.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 removexattr(path string, attr string, options int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.BytePtrFromString(attr)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.Syscall(syscall.SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
+ 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 listxattr(path string, dest []byte, options int) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.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.Syscall6(syscall.SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)), uintptr(options), 0, 0)
+ use(unsafe.Pointer(_p0))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_freebsd.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_freebsd.go
new file mode 100644
index 0000000..80dba49
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_freebsd.go
@@ -0,0 +1,53 @@
+package sysx
+
+import (
+ "errors"
+)
+
+// Initial stub version for FreeBSD. FreeBSD has a different
+// syscall API from Darwin and Linux for extended attributes;
+// it is also not widely used. It is not exposed at all by the
+// Go syscall package, so we need to implement directly eventually.
+
+var unsupported error = errors.New("extended attributes unsupported on FreeBSD")
+
+// Listxattr calls syscall listxattr and reads all content
+// and returns a string array
+func Listxattr(path string) ([]string, error) {
+ return []string{}, nil
+}
+
+// Removexattr calls syscall removexattr
+func Removexattr(path string, attr string) (err error) {
+ return unsupported
+}
+
+// Setxattr calls syscall setxattr
+func Setxattr(path string, attr string, data []byte, flags int) (err error) {
+ return unsupported
+}
+
+// Getxattr calls syscall getxattr
+func Getxattr(path, attr string) ([]byte, error) {
+ return []byte{}, nil
+}
+
+// LListxattr lists xattrs, not following symlinks
+func LListxattr(path string) ([]string, error) {
+ return []string{}, nil
+}
+
+// LRemovexattr removes an xattr, not following symlinks
+func LRemovexattr(path string, attr string) (err error) {
+ return unsupported
+}
+
+// LSetxattr sets an xattr, not following symlinks
+func LSetxattr(path string, attr string, data []byte, flags int) (err error) {
+ return unsupported
+}
+
+// LGetxattr gets an xattr, not following symlinks
+func LGetxattr(path, attr string) ([]byte, error) {
+ return []byte{}, nil
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_linux.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux.go
new file mode 100644
index 0000000..cd18136
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux.go
@@ -0,0 +1,61 @@
+package sysx
+
+import "syscall"
+
+// These functions will be generated by generate.sh
+// $ GOOS=linux GOARCH=386 ./generate.sh xattr
+// $ GOOS=linux GOARCH=amd64 ./generate.sh xattr
+// $ GOOS=linux GOARCH=arm ./generate.sh xattr
+// $ GOOS=linux GOARCH=arm64 ./generate.sh xattr
+// $ GOOS=linux GOARCH=ppc64 ./generate.sh xattr
+// $ GOOS=linux GOARCH=ppc64le ./generate.sh xattr
+// $ GOOS=linux GOARCH=s390x ./generate.sh xattr
+
+// Listxattr calls syscall listxattr and reads all content
+// and returns a string array
+func Listxattr(path string) ([]string, error) {
+ return listxattrAll(path, syscall.Listxattr)
+}
+
+// Removexattr calls syscall removexattr
+func Removexattr(path string, attr string) (err error) {
+ return syscall.Removexattr(path, attr)
+}
+
+// Setxattr calls syscall setxattr
+func Setxattr(path string, attr string, data []byte, flags int) (err error) {
+ return syscall.Setxattr(path, attr, data, flags)
+}
+
+// Getxattr calls syscall getxattr
+func Getxattr(path, attr string) ([]byte, error) {
+ return getxattrAll(path, attr, syscall.Getxattr)
+}
+
+//sys llistxattr(path string, dest []byte) (sz int, err error)
+
+// LListxattr lists xattrs, not following symlinks
+func LListxattr(path string) ([]string, error) {
+ return listxattrAll(path, llistxattr)
+}
+
+//sys lremovexattr(path string, attr string) (err error)
+
+// LRemovexattr removes an xattr, not following symlinks
+func LRemovexattr(path string, attr string) (err error) {
+ return lremovexattr(path, attr)
+}
+
+//sys lsetxattr(path string, attr string, data []byte, flags int) (err error)
+
+// LSetxattr sets an xattr, not following symlinks
+func LSetxattr(path string, attr string, data []byte, flags int) (err error) {
+ return lsetxattr(path, attr, data, flags)
+}
+
+//sys lgetxattr(path string, attr string, dest []byte) (sz int, err error)
+
+// LGetxattr gets an xattr, not following symlinks
+func LGetxattr(path, attr string) ([]byte, error) {
+ return getxattrAll(path, attr, lgetxattr)
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_386.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_386.go
new file mode 100644
index 0000000..c3e5c8e
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_386.go
@@ -0,0 +1,111 @@
+// mksyscall.pl -l32 xattr_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func llistxattr(path string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.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.Syscall(syscall.SYS_LLISTXATTR, 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 lremovexattr(path string, attr string) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.BytePtrFromString(attr)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.Syscall(syscall.SYS_LREMOVEXATTR, 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 lsetxattr(path string, attr string, data []byte, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LSETXATTR, 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 lgetxattr(path string, attr string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LGETXATTR, 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
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_amd64.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_amd64.go
new file mode 100644
index 0000000..dec46fa
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_amd64.go
@@ -0,0 +1,111 @@
+// mksyscall.pl xattr_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func llistxattr(path string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.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.Syscall(syscall.SYS_LLISTXATTR, 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 lremovexattr(path string, attr string) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.BytePtrFromString(attr)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.Syscall(syscall.SYS_LREMOVEXATTR, 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 lsetxattr(path string, attr string, data []byte, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LSETXATTR, 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 lgetxattr(path string, attr string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LGETXATTR, 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
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_arm.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_arm.go
new file mode 100644
index 0000000..c3e5c8e
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_arm.go
@@ -0,0 +1,111 @@
+// mksyscall.pl -l32 xattr_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func llistxattr(path string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.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.Syscall(syscall.SYS_LLISTXATTR, 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 lremovexattr(path string, attr string) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.BytePtrFromString(attr)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.Syscall(syscall.SYS_LREMOVEXATTR, 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 lsetxattr(path string, attr string, data []byte, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LSETXATTR, 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 lgetxattr(path string, attr string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LGETXATTR, 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
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_arm64.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_arm64.go
new file mode 100644
index 0000000..dec46fa
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_arm64.go
@@ -0,0 +1,111 @@
+// mksyscall.pl xattr_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func llistxattr(path string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.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.Syscall(syscall.SYS_LLISTXATTR, 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 lremovexattr(path string, attr string) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.BytePtrFromString(attr)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.Syscall(syscall.SYS_LREMOVEXATTR, 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 lsetxattr(path string, attr string, data []byte, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LSETXATTR, 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 lgetxattr(path string, attr string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LGETXATTR, 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
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_ppc64.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_ppc64.go
new file mode 100644
index 0000000..dec46fa
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_ppc64.go
@@ -0,0 +1,111 @@
+// mksyscall.pl xattr_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func llistxattr(path string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.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.Syscall(syscall.SYS_LLISTXATTR, 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 lremovexattr(path string, attr string) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.BytePtrFromString(attr)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.Syscall(syscall.SYS_LREMOVEXATTR, 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 lsetxattr(path string, attr string, data []byte, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LSETXATTR, 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 lgetxattr(path string, attr string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LGETXATTR, 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
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_ppc64le.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_ppc64le.go
new file mode 100644
index 0000000..dec46fa
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_ppc64le.go
@@ -0,0 +1,111 @@
+// mksyscall.pl xattr_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func llistxattr(path string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.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.Syscall(syscall.SYS_LLISTXATTR, 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 lremovexattr(path string, attr string) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.BytePtrFromString(attr)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.Syscall(syscall.SYS_LREMOVEXATTR, 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 lsetxattr(path string, attr string, data []byte, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LSETXATTR, 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 lgetxattr(path string, attr string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LGETXATTR, 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
+}
diff --git a/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_s390x.go b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_s390x.go
new file mode 100644
index 0000000..dec46fa
--- /dev/null
+++ b/vendor/github.com/stevvooe/continuity/sysx/xattr_linux_s390x.go
@@ -0,0 +1,111 @@
+// mksyscall.pl xattr_linux.go
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+package sysx
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func llistxattr(path string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.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.Syscall(syscall.SYS_LLISTXATTR, 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 lremovexattr(path string, attr string) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.BytePtrFromString(attr)
+ if err != nil {
+ return
+ }
+ _, _, e1 := syscall.Syscall(syscall.SYS_LREMOVEXATTR, 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 lsetxattr(path string, attr string, data []byte, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LSETXATTR, 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 lgetxattr(path string, attr string, dest []byte) (sz int, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.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 := syscall.Syscall6(syscall.SYS_LGETXATTR, 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
+}
diff --git a/vendor/github.com/stretchr/testify/LICENSE b/vendor/github.com/stretchr/testify/LICENSE
new file mode 100644
index 0000000..473b670
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/LICENSE
@@ -0,0 +1,22 @@
+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/README.md b/vendor/github.com/stretchr/testify/README.md
new file mode 100644
index 0000000..e57b181
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/README.md
@@ -0,0 +1,332 @@
+Testify - Thou Shalt Write Tests
+================================
+
+[![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) [![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/testify)](https://goreportcard.com/report/github.com/stretchr/testify) [![GoDoc](https://godoc.org/github.com/stretchr/testify?status.svg)](https://godoc.org/github.com/stretchr/testify)
+
+Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend.
+
+Features include:
+
+ * [Easy assertions](#assert-package)
+ * [Mocking](#mock-package)
+ * [HTTP response trapping](#http-package)
+ * [Testing suite interfaces and functions](#suite-package)
+
+Get started:
+
+ * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date)
+ * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing
+ * Check out the API Documentation http://godoc.org/github.com/stretchr/testify
+ * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc)
+ * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development)
+
+
+
+[`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package
+-------------------------------------------------------------------------------------------
+
+The `assert` package provides some helpful methods that allow you to write better test code in Go.
+
+ * Prints friendly, easy to read failure descriptions
+ * Allows for very readable code
+ * Optionally annotate each assertion with a message
+
+See it in action:
+
+```go
+package yours
+
+import (
+ "testing"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestSomething(t *testing.T) {
+
+ // assert equality
+ assert.Equal(t, 123, 123, "they should be equal")
+
+ // assert inequality
+ assert.NotEqual(t, 123, 456, "they should not be equal")
+
+ // assert for nil (good for errors)
+ assert.Nil(t, object)
+
+ // assert for not nil (good when you expect something)
+ if assert.NotNil(t, object) {
+
+ // now we know that object isn't nil, we are safe to make
+ // further assertions without causing any errors
+ assert.Equal(t, "Something", object.Value)
+
+ }
+
+}
+```
+
+ * Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities.
+ * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions.
+
+if you assert many times, use the below:
+
+```go
+package yours
+
+import (
+ "testing"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestSomething(t *testing.T) {
+ assert := assert.New(t)
+
+ // assert equality
+ assert.Equal(123, 123, "they should be equal")
+
+ // assert inequality
+ assert.NotEqual(123, 456, "they should not be equal")
+
+ // assert for nil (good for errors)
+ assert.Nil(object)
+
+ // assert for not nil (good when you expect something)
+ if assert.NotNil(object) {
+
+ // now we know that object isn't nil, we are safe to make
+ // further assertions without causing any errors
+ assert.Equal("Something", object.Value)
+ }
+}
+```
+
+[`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package
+---------------------------------------------------------------------------------------------
+
+The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test.
+
+See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details.
+
+
+[`http`](http://godoc.org/github.com/stretchr/testify/http "API documentation") package
+---------------------------------------------------------------------------------------
+
+The `http` package contains test objects useful for testing code that relies on the `net/http` package. Check out the [(deprecated) API documentation for the `http` package](http://godoc.org/github.com/stretchr/testify/http).
+
+We recommend you use [httptest](http://golang.org/pkg/net/http/httptest) instead.
+
+[`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package
+----------------------------------------------------------------------------------------
+
+The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code.
+
+An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened:
+
+```go
+package yours
+
+import (
+ "testing"
+ "github.com/stretchr/testify/mock"
+)
+
+/*
+ Test objects
+*/
+
+// MyMockedObject is a mocked object that implements an interface
+// that describes an object that the code I am testing relies on.
+type MyMockedObject struct{
+ mock.Mock
+}
+
+// DoSomething is a method on MyMockedObject that implements some interface
+// and just records the activity, and returns what the Mock object tells it to.
+//
+// In the real object, this method would do something useful, but since this
+// is a mocked object - we're just going to stub it out.
+//
+// NOTE: This method is not being tested here, code that uses this object is.
+func (m *MyMockedObject) DoSomething(number int) (bool, error) {
+
+ args := m.Called(number)
+ return args.Bool(0), args.Error(1)
+
+}
+
+/*
+ Actual test functions
+*/
+
+// TestSomething is an example of how to use our test object to
+// make assertions about some target code we are testing.
+func TestSomething(t *testing.T) {
+
+ // create an instance of our test object
+ testObj := new(MyMockedObject)
+
+ // setup expectations
+ testObj.On("DoSomething", 123).Return(true, nil)
+
+ // call the code we are testing
+ targetFuncThatDoesSomethingWithObj(testObj)
+
+ // assert that the expectations were met
+ testObj.AssertExpectations(t)
+
+}
+```
+
+For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock).
+
+You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker.
+
+[`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package
+-----------------------------------------------------------------------------------------
+
+The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal.
+
+An example suite is shown below:
+
+```go
+// Basic imports
+import (
+ "testing"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/suite"
+)
+
+// Define the suite, and absorb the built-in basic suite
+// functionality from testify - including a T() method which
+// returns the current testing context
+type ExampleTestSuite struct {
+ suite.Suite
+ VariableThatShouldStartAtFive int
+}
+
+// Make sure that VariableThatShouldStartAtFive is set to five
+// before each test
+func (suite *ExampleTestSuite) SetupTest() {
+ suite.VariableThatShouldStartAtFive = 5
+}
+
+// All methods that begin with "Test" are run as tests within a
+// suite.
+func (suite *ExampleTestSuite) TestExample() {
+ assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
+}
+
+// In order for 'go test' to run this suite, we need to create
+// a normal test function and pass our suite to suite.Run
+func TestExampleTestSuite(t *testing.T) {
+ suite.Run(t, new(ExampleTestSuite))
+}
+```
+
+For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go)
+
+For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite).
+
+`Suite` object has assertion methods:
+
+```go
+// Basic imports
+import (
+ "testing"
+ "github.com/stretchr/testify/suite"
+)
+
+// Define the suite, and absorb the built-in basic suite
+// functionality from testify - including assertion methods.
+type ExampleTestSuite struct {
+ suite.Suite
+ VariableThatShouldStartAtFive int
+}
+
+// Make sure that VariableThatShouldStartAtFive is set to five
+// before each test
+func (suite *ExampleTestSuite) SetupTest() {
+ suite.VariableThatShouldStartAtFive = 5
+}
+
+// All methods that begin with "Test" are run as tests within a
+// suite.
+func (suite *ExampleTestSuite) TestExample() {
+ suite.Equal(suite.VariableThatShouldStartAtFive, 5)
+}
+
+// In order for 'go test' to run this suite, we need to create
+// a normal test function and pass our suite to suite.Run
+func TestExampleTestSuite(t *testing.T) {
+ suite.Run(t, new(ExampleTestSuite))
+}
+```
+
+------
+
+Installation
+============
+
+To install Testify, use `go get`:
+
+ * Latest version: go get github.com/stretchr/testify
+ * Specific version: go get gopkg.in/stretchr/testify.v1
+
+This will then make the following packages available to you:
+
+ github.com/stretchr/testify/assert
+ github.com/stretchr/testify/mock
+ github.com/stretchr/testify/http
+
+Import the `testify/assert` package into your code using this template:
+
+```go
+package yours
+
+import (
+ "testing"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestSomething(t *testing.T) {
+
+ assert.True(t, true, "True is true!")
+
+}
+```
+
+------
+
+Staying up to date
+==================
+
+To update Testify to the latest version, use `go get -u github.com/stretchr/testify`.
+
+------
+
+Version History
+===============
+
+ * 1.0 - New package versioning strategy adopted.
+
+------
+
+Contributing
+============
+
+Please feel free to submit issues, fork the repository and send pull requests!
+
+When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it.
+
+------
+
+Licence
+=======
+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
new file mode 100644
index 0000000..aa4311f
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go
@@ -0,0 +1,352 @@
+/*
+* 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).
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+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()
+// a.EqualError(err, expectedErrorString, "An error was expected")
+//
+// 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 each value from two slices.
+func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
+ return InEpsilonSlice(a.t, expected, actual, epsilon, 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).
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+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/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go
new file mode 100644
index 0000000..d1552e5
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/assertions.go
@@ -0,0 +1,1069 @@
+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 occurred 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 {
+ // The breaks below failed to terminate the loop, and we ran off the
+ // end of the call stack.
+ break
+ }
+
+ // This is a huge edge case, but it will panic if this is the case, see #180
+ if file == "<autogenerated>" {
+ break
+ }
+
+ f := runtime.FuncForPC(pc)
+ if f == nil {
+ break
+ }
+ name = f.Name()
+
+ // testing.tRunner is the standard library function that calls
+ // tests. Subtests are called directly by tRunner, without going through
+ // the Test/Benchmark/Example function that contains the t.Run calls, so
+ // with subtests we should break when we hit tRunner, without adding it
+ // to the list of callers.
+ if name == "testing.tRunner" {
+ 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))
+ }
+
+ // 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 ""
+}
+
+// Aligns the provided message so that all lines after the first line start at the same location as the first line.
+// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
+// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
+// basis on which the alignment occurs).
+func indentMessageLines(message string, longestLabelLen int) string {
+ outBuf := new(bytes.Buffer)
+
+ for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
+ // no need to align first line because it starts at the correct location (after the label)
+ if i != 0 {
+ // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
+ outBuf.WriteString("\n\r\t" + strings.Repeat(" ", longestLabelLen +1) + "\t")
+ }
+ 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 {
+ content := []labeledContent{
+ {"Error Trace", strings.Join(CallerInfo(), "\n\r\t\t\t")},
+ {"Error", failureMessage},
+ }
+
+ message := messageFromMsgAndArgs(msgAndArgs...)
+ if len(message) > 0 {
+ content = append(content, labeledContent{"Messages", message})
+ }
+
+ t.Errorf("\r" + getWhitespaceString() + labeledOutput(content...))
+
+ return false
+}
+
+type labeledContent struct {
+ label string
+ content string
+}
+
+// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
+//
+// \r\t{{label}}:{{align_spaces}}\t{{content}}\n
+//
+// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
+// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
+// alignment is achieved, "\t{{content}}\n" is added for the output.
+//
+// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line.
+func labeledOutput(content ...labeledContent) string {
+ longestLabel := 0
+ for _, v := range content {
+ if len(v.label) > longestLabel {
+ longestLabel = len(v.label)
+ }
+ }
+ var output string
+ for _, v := range content {
+ output += "\r\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
+ }
+ return output
+}
+
+// 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).
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
+
+ if !ObjectsAreEqual(expected, actual) {
+ diff := diff(expected, actual)
+ expected, actual = formatUnequalValues(expected, actual)
+ return Fail(t, fmt.Sprintf("Not equal: \n"+
+ "expected: %s\n"+
+ "received: %s%s", expected, actual, diff), msgAndArgs...)
+ }
+
+ return true
+
+}
+
+// formatUnequalValues takes two values of arbitrary types and returns string
+// representations appropriate to be presented to the user.
+//
+// If the values are not of like type, the returned strings will be prefixed
+// with the type name, and the value will be enclosed in parenthesis similar
+// to a type conversion in the Go grammar.
+func formatUnequalValues(expected, actual interface{}) (e string, a string) {
+ if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
+ return fmt.Sprintf("%T(%#v)", expected, expected),
+ fmt.Sprintf("%T(%#v)", actual, actual)
+ }
+
+ return fmt.Sprintf("%#v", expected),
+ fmt.Sprintf("%#v", actual)
+}
+
+// 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) {
+ diff := diff(expected, actual)
+ expected, actual = formatUnequalValues(expected, actual)
+ return Fail(t, fmt.Sprintf("Not equal: \n"+
+ "expected: %s\n"+
+ "received: %s%s", expected, actual, diff), 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).
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+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:\n%+v", 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 {
+
+ if err == nil {
+ return Fail(t, "An error is expected but got nil.", msgAndArgs...)
+ }
+
+ 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()
+// assert.EqualError(t, err, expectedErrorString, "An error was expected")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
+ if !Error(t, theError, msgAndArgs...) {
+ return false
+ }
+ expected := errString
+ actual := theError.Error()
+ // don't need to use deep equals here, we know they are both strings
+ if expected != actual {
+ return Fail(t, fmt.Sprintf("Error message not equal:\n"+
+ "expected: %q\n"+
+ "received: %q", expected, actual), msgAndArgs...)
+ }
+ return true
+}
+
+// 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 ""
+ }
+
+ e := spewConfig.Sdump(expected)
+ a := spewConfig.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
+}
+
+var spewConfig = spew.ConfigState{
+ Indent: " ",
+ DisablePointerAddresses: true,
+ DisableCapacities: true,
+ SortKeys: true,
+}
diff --git a/vendor/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go
new file mode 100644
index 0000000..c9dccc4
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/doc.go
@@ -0,0 +1,45 @@
+// 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
new file mode 100644
index 0000000..ac9dc9d
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/errors.go
@@ -0,0 +1,10 @@
+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
new file mode 100644
index 0000000..b867e95
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/forward_assertions.go
@@ -0,0 +1,16 @@
+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
new file mode 100644
index 0000000..fa7ab89
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/assert/http_assertions.go
@@ -0,0 +1,106 @@
+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, fmt.Sprintf("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/stretchr/testify/require/doc.go b/vendor/github.com/stretchr/testify/require/doc.go
new file mode 100644
index 0000000..169de39
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/doc.go
@@ -0,0 +1,28 @@
+// Package require implements the same assertions as the `assert` package but
+// stops test execution when a test fails.
+//
+// Example Usage
+//
+// The following is a complete example using require in a standard test function:
+// import (
+// "testing"
+// "github.com/stretchr/testify/require"
+// )
+//
+// func TestSomething(t *testing.T) {
+//
+// var a string = "Hello"
+// var b string = "Hello"
+//
+// require.Equal(t, a, b, "The two words should be the same.")
+//
+// }
+//
+// Assertions
+//
+// The `require` package have same global functions as in the `assert` package,
+// but instead of returning a boolean result they call `t.FailNow()`.
+//
+// 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 require
diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements.go b/vendor/github.com/stretchr/testify/require/forward_requirements.go
new file mode 100644
index 0000000..d3c2ab9
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/forward_requirements.go
@@ -0,0 +1,16 @@
+package require
+
+// 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=require -template=require_forward.go.tmpl
diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go
new file mode 100644
index 0000000..fc567f1
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/require.go
@@ -0,0 +1,429 @@
+/*
+* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
+* THIS FILE MUST NOT BE EDITED BY HAND
+ */
+
+package require
+
+import (
+ assert "github.com/stretchr/testify/assert"
+ http "net/http"
+ url "net/url"
+ time "time"
+)
+
+// Condition uses a Comparison to assert a complex condition.
+func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) {
+ if !assert.Condition(t, comp, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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 interface{}, contains interface{}, msgAndArgs ...interface{}) {
+ if !assert.Contains(t, s, contains, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.Empty(t, object, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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).
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if !assert.Equal(t, expected, actual, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// EqualError asserts that a function returned an error (i.e. not `nil`)
+// and that it is equal to the provided error.
+//
+// actualObj, err := SomeFunction()
+// assert.EqualError(t, err, expectedErrorString, "An error was expected")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) {
+ if !assert.EqualError(t, theError, errString, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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 interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if !assert.EqualValues(t, expected, actual, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.Error(t, err, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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 interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if !assert.Exactly(t, expected, actual, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// Fail reports a failure through
+func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) {
+ if !assert.Fail(t, failureMessage, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// FailNow fails test
+func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) {
+ if !assert.FailNow(t, failureMessage, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.False(t, value, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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 string, url string, values url.Values, str interface{}) {
+ if !assert.HTTPBodyContains(t, handler, method, url, values, str) {
+ t.FailNow()
+ }
+}
+
+// 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 string, url string, values url.Values, str interface{}) {
+ if !assert.HTTPBodyNotContains(t, handler, method, url, values, str) {
+ t.FailNow()
+ }
+}
+
+// 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 string, url string, values url.Values) {
+ if !assert.HTTPError(t, handler, method, url, values) {
+ t.FailNow()
+ }
+}
+
+// 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 string, url string, values url.Values) {
+ if !assert.HTTPRedirect(t, handler, method, url, values) {
+ t.FailNow()
+ }
+}
+
+// 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 string, url string, values url.Values) {
+ if !assert.HTTPSuccess(t, handler, method, url, values) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.Implements(t, interfaceObject, object, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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 interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
+ if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// InDeltaSlice is the same as InDelta, except it compares two slices.
+func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
+ if !assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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 interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
+ if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
+func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
+ if !assert.InEpsilonSlice(t, expected, actual, epsilon, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// IsType asserts that the specified objects are of the same type.
+func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) {
+ if !assert.IsType(t, expectedType, object, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.JSONEq(t, expected, actual, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.Len(t, object, length, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.Nil(t, object, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.NoError(t, err, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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 interface{}, contains interface{}, msgAndArgs ...interface{}) {
+ if !assert.NotContains(t, s, contains, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.NotEmpty(t, object, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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).
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ if !assert.NotEqual(t, expected, actual, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.NotNil(t, object, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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 assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ if !assert.NotPanics(t, f, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.NotRegexp(t, rx, str, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// NotZero asserts that i is not the zero value for its type and returns the truth.
+func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) {
+ if !assert.NotZero(t, i, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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 assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ if !assert.Panics(t, f, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.Regexp(t, rx, str, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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{}) {
+ if !assert.True(t, value, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// 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 time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) {
+ if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) {
+ t.FailNow()
+ }
+}
+
+// Zero asserts that i is the zero value for its type and returns the truth.
+func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) {
+ if !assert.Zero(t, i, msgAndArgs...) {
+ t.FailNow()
+ }
+}
diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go
new file mode 100644
index 0000000..caa1879
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/require_forward.go
@@ -0,0 +1,353 @@
+/*
+* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen
+* THIS FILE MUST NOT BE EDITED BY HAND
+ */
+
+package require
+
+import (
+ assert "github.com/stretchr/testify/assert"
+ http "net/http"
+ url "net/url"
+ time "time"
+)
+
+// Condition uses a Comparison to assert a complex condition.
+func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) {
+ 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{}) {
+ 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{}) {
+ 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).
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ 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()
+// a.EqualError(err, expectedErrorString, "An error was expected")
+//
+// Returns whether the assertion was successful (true) or not (false).
+func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) {
+ 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{}) {
+ 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{}) {
+ 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{}) {
+ Exactly(a.t, expected, actual, msgAndArgs...)
+}
+
+// Fail reports a failure through
+func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) {
+ Fail(a.t, failureMessage, msgAndArgs...)
+}
+
+// FailNow fails test
+func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) {
+ 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{}) {
+ 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{}) {
+ 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{}) {
+ 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) {
+ 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) {
+ 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) {
+ 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{}) {
+ 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{}) {
+ 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{}) {
+ 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{}) {
+ InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...)
+}
+
+// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
+func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) {
+ InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...)
+}
+
+// IsType asserts that the specified objects are of the same type.
+func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) {
+ 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{}) {
+ 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{}) {
+ 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{}) {
+ 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{}) {
+ 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{}) {
+ 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{}) {
+ 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).
+//
+// Pointer variable equality is determined based on the equality of the
+// referenced values (as opposed to the memory addresses).
+func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) {
+ 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{}) {
+ 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 assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ 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{}) {
+ 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{}) {
+ 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 assert.PanicTestFunc, msgAndArgs ...interface{}) {
+ 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{}) {
+ 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{}) {
+ 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{}) {
+ 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{}) {
+ Zero(a.t, i, msgAndArgs...)
+}
diff --git a/vendor/github.com/stretchr/testify/require/requirements.go b/vendor/github.com/stretchr/testify/require/requirements.go
new file mode 100644
index 0000000..4114756
--- /dev/null
+++ b/vendor/github.com/stretchr/testify/require/requirements.go
@@ -0,0 +1,9 @@
+package require
+
+// TestingT is an interface wrapper around *testing.T
+type TestingT interface {
+ Errorf(format string, args ...interface{})
+ FailNow()
+}
+
+//go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl
diff --git a/vendor/github.com/syndtr/gocapability/LICENSE b/vendor/github.com/syndtr/gocapability/LICENSE
new file mode 100644
index 0000000..80dd96d
--- /dev/null
+++ b/vendor/github.com/syndtr/gocapability/LICENSE
@@ -0,0 +1,24 @@
+Copyright 2013 Suryandaru Triandana <syndtr@gmail.com>
+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/syndtr/gocapability/capability/capability.go b/vendor/github.com/syndtr/gocapability/capability/capability.go
new file mode 100644
index 0000000..c07c557
--- /dev/null
+++ b/vendor/github.com/syndtr/gocapability/capability/capability.go
@@ -0,0 +1,72 @@
+// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com>
+// All rights reserved.
+//
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Package capability provides utilities for manipulating POSIX capabilities.
+package capability
+
+type Capabilities interface {
+ // Get check whether a capability present in the given
+ // capabilities set. The 'which' value should be one of EFFECTIVE,
+ // PERMITTED, INHERITABLE, BOUNDING or AMBIENT.
+ Get(which CapType, what Cap) bool
+
+ // Empty check whether all capability bits of the given capabilities
+ // set are zero. The 'which' value should be one of EFFECTIVE,
+ // PERMITTED, INHERITABLE, BOUNDING or AMBIENT.
+ Empty(which CapType) bool
+
+ // Full check whether all capability bits of the given capabilities
+ // set are one. The 'which' value should be one of EFFECTIVE,
+ // PERMITTED, INHERITABLE, BOUNDING or AMBIENT.
+ Full(which CapType) bool
+
+ // Set sets capabilities of the given capabilities sets. The
+ // 'which' value should be one or combination (OR'ed) of EFFECTIVE,
+ // PERMITTED, INHERITABLE, BOUNDING or AMBIENT.
+ Set(which CapType, caps ...Cap)
+
+ // Unset unsets capabilities of the given capabilities sets. The
+ // 'which' value should be one or combination (OR'ed) of EFFECTIVE,
+ // PERMITTED, INHERITABLE, BOUNDING or AMBIENT.
+ Unset(which CapType, caps ...Cap)
+
+ // Fill sets all bits of the given capabilities kind to one. The
+ // 'kind' value should be one or combination (OR'ed) of CAPS,
+ // BOUNDS or AMBS.
+ Fill(kind CapType)
+
+ // Clear sets all bits of the given capabilities kind to zero. The
+ // 'kind' value should be one or combination (OR'ed) of CAPS,
+ // BOUNDS or AMBS.
+ Clear(kind CapType)
+
+ // String return current capabilities state of the given capabilities
+ // set as string. The 'which' value should be one of EFFECTIVE,
+ // PERMITTED, INHERITABLE BOUNDING or AMBIENT
+ StringCap(which CapType) string
+
+ // String return current capabilities state as string.
+ String() string
+
+ // Load load actual capabilities value. This will overwrite all
+ // outstanding changes.
+ Load() error
+
+ // Apply apply the capabilities settings, so all changes will take
+ // effect.
+ Apply(kind CapType) error
+}
+
+// NewPid create new initialized Capabilities object for given pid when it
+// is nonzero, or for the current pid if pid is 0
+func NewPid(pid int) (Capabilities, error) {
+ return newPid(pid)
+}
+
+// NewFile create new initialized Capabilities object for given named file.
+func NewFile(name string) (Capabilities, error) {
+ return newFile(name)
+}
diff --git a/vendor/github.com/syndtr/gocapability/capability/capability_linux.go b/vendor/github.com/syndtr/gocapability/capability/capability_linux.go
new file mode 100644
index 0000000..6d2135a
--- /dev/null
+++ b/vendor/github.com/syndtr/gocapability/capability/capability_linux.go
@@ -0,0 +1,650 @@
+// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com>
+// All rights reserved.
+//
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package capability
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+ "syscall"
+)
+
+var errUnknownVers = errors.New("unknown capability version")
+
+const (
+ linuxCapVer1 = 0x19980330
+ linuxCapVer2 = 0x20071026
+ linuxCapVer3 = 0x20080522
+)
+
+var (
+ capVers uint32
+ capLastCap Cap
+)
+
+func init() {
+ var hdr capHeader
+ capget(&hdr, nil)
+ capVers = hdr.version
+
+ if initLastCap() == nil {
+ CAP_LAST_CAP = capLastCap
+ if capLastCap > 31 {
+ capUpperMask = (uint32(1) << (uint(capLastCap) - 31)) - 1
+ } else {
+ capUpperMask = 0
+ }
+ }
+}
+
+func initLastCap() error {
+ if capLastCap != 0 {
+ return nil
+ }
+
+ f, err := os.Open("/proc/sys/kernel/cap_last_cap")
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+
+ var b []byte = make([]byte, 11)
+ _, err = f.Read(b)
+ if err != nil {
+ return err
+ }
+
+ fmt.Sscanf(string(b), "%d", &capLastCap)
+
+ return nil
+}
+
+func mkStringCap(c Capabilities, which CapType) (ret string) {
+ for i, first := Cap(0), true; i <= CAP_LAST_CAP; i++ {
+ if !c.Get(which, i) {
+ continue
+ }
+ if first {
+ first = false
+ } else {
+ ret += ", "
+ }
+ ret += i.String()
+ }
+ return
+}
+
+func mkString(c Capabilities, max CapType) (ret string) {
+ ret = "{"
+ for i := CapType(1); i <= max; i <<= 1 {
+ ret += " " + i.String() + "=\""
+ if c.Empty(i) {
+ ret += "empty"
+ } else if c.Full(i) {
+ ret += "full"
+ } else {
+ ret += c.StringCap(i)
+ }
+ ret += "\""
+ }
+ ret += " }"
+ return
+}
+
+func newPid(pid int) (c Capabilities, err error) {
+ switch capVers {
+ case linuxCapVer1:
+ p := new(capsV1)
+ p.hdr.version = capVers
+ p.hdr.pid = pid
+ c = p
+ case linuxCapVer2, linuxCapVer3:
+ p := new(capsV3)
+ p.hdr.version = capVers
+ p.hdr.pid = pid
+ c = p
+ default:
+ err = errUnknownVers
+ return
+ }
+ err = c.Load()
+ if err != nil {
+ c = nil
+ }
+ return
+}
+
+type capsV1 struct {
+ hdr capHeader
+ data capData
+}
+
+func (c *capsV1) Get(which CapType, what Cap) bool {
+ if what > 32 {
+ return false
+ }
+
+ switch which {
+ case EFFECTIVE:
+ return (1<<uint(what))&c.data.effective != 0
+ case PERMITTED:
+ return (1<<uint(what))&c.data.permitted != 0
+ case INHERITABLE:
+ return (1<<uint(what))&c.data.inheritable != 0
+ }
+
+ return false
+}
+
+func (c *capsV1) getData(which CapType) (ret uint32) {
+ switch which {
+ case EFFECTIVE:
+ ret = c.data.effective
+ case PERMITTED:
+ ret = c.data.permitted
+ case INHERITABLE:
+ ret = c.data.inheritable
+ }
+ return
+}
+
+func (c *capsV1) Empty(which CapType) bool {
+ return c.getData(which) == 0
+}
+
+func (c *capsV1) Full(which CapType) bool {
+ return (c.getData(which) & 0x7fffffff) == 0x7fffffff
+}
+
+func (c *capsV1) Set(which CapType, caps ...Cap) {
+ for _, what := range caps {
+ if what > 32 {
+ continue
+ }
+
+ if which&EFFECTIVE != 0 {
+ c.data.effective |= 1 << uint(what)
+ }
+ if which&PERMITTED != 0 {
+ c.data.permitted |= 1 << uint(what)
+ }
+ if which&INHERITABLE != 0 {
+ c.data.inheritable |= 1 << uint(what)
+ }
+ }
+}
+
+func (c *capsV1) Unset(which CapType, caps ...Cap) {
+ for _, what := range caps {
+ if what > 32 {
+ continue
+ }
+
+ if which&EFFECTIVE != 0 {
+ c.data.effective &= ^(1 << uint(what))
+ }
+ if which&PERMITTED != 0 {
+ c.data.permitted &= ^(1 << uint(what))
+ }
+ if which&INHERITABLE != 0 {
+ c.data.inheritable &= ^(1 << uint(what))
+ }
+ }
+}
+
+func (c *capsV1) Fill(kind CapType) {
+ if kind&CAPS == CAPS {
+ c.data.effective = 0x7fffffff
+ c.data.permitted = 0x7fffffff
+ c.data.inheritable = 0
+ }
+}
+
+func (c *capsV1) Clear(kind CapType) {
+ if kind&CAPS == CAPS {
+ c.data.effective = 0
+ c.data.permitted = 0
+ c.data.inheritable = 0
+ }
+}
+
+func (c *capsV1) StringCap(which CapType) (ret string) {
+ return mkStringCap(c, which)
+}
+
+func (c *capsV1) String() (ret string) {
+ return mkString(c, BOUNDING)
+}
+
+func (c *capsV1) Load() (err error) {
+ return capget(&c.hdr, &c.data)
+}
+
+func (c *capsV1) Apply(kind CapType) error {
+ if kind&CAPS == CAPS {
+ return capset(&c.hdr, &c.data)
+ }
+ return nil
+}
+
+type capsV3 struct {
+ hdr capHeader
+ data [2]capData
+ bounds [2]uint32
+ ambient [2]uint32
+}
+
+func (c *capsV3) Get(which CapType, what Cap) bool {
+ var i uint
+ if what > 31 {
+ i = uint(what) >> 5
+ what %= 32
+ }
+
+ switch which {
+ case EFFECTIVE:
+ return (1<<uint(what))&c.data[i].effective != 0
+ case PERMITTED:
+ return (1<<uint(what))&c.data[i].permitted != 0
+ case INHERITABLE:
+ return (1<<uint(what))&c.data[i].inheritable != 0
+ case BOUNDING:
+ return (1<<uint(what))&c.bounds[i] != 0
+ case AMBIENT:
+ return (1<<uint(what))&c.ambient[i] != 0
+ }
+
+ return false
+}
+
+func (c *capsV3) getData(which CapType, dest []uint32) {
+ switch which {
+ case EFFECTIVE:
+ dest[0] = c.data[0].effective
+ dest[1] = c.data[1].effective
+ case PERMITTED:
+ dest[0] = c.data[0].permitted
+ dest[1] = c.data[1].permitted
+ case INHERITABLE:
+ dest[0] = c.data[0].inheritable
+ dest[1] = c.data[1].inheritable
+ case BOUNDING:
+ dest[0] = c.bounds[0]
+ dest[1] = c.bounds[1]
+ case AMBIENT:
+ dest[0] = c.ambient[0]
+ dest[1] = c.ambient[1]
+ }
+}
+
+func (c *capsV3) Empty(which CapType) bool {
+ var data [2]uint32
+ c.getData(which, data[:])
+ return data[0] == 0 && data[1] == 0
+}
+
+func (c *capsV3) Full(which CapType) bool {
+ var data [2]uint32
+ c.getData(which, data[:])
+ if (data[0] & 0xffffffff) != 0xffffffff {
+ return false
+ }
+ return (data[1] & capUpperMask) == capUpperMask
+}
+
+func (c *capsV3) Set(which CapType, caps ...Cap) {
+ for _, what := range caps {
+ var i uint
+ if what > 31 {
+ i = uint(what) >> 5
+ what %= 32
+ }
+
+ if which&EFFECTIVE != 0 {
+ c.data[i].effective |= 1 << uint(what)
+ }
+ if which&PERMITTED != 0 {
+ c.data[i].permitted |= 1 << uint(what)
+ }
+ if which&INHERITABLE != 0 {
+ c.data[i].inheritable |= 1 << uint(what)
+ }
+ if which&BOUNDING != 0 {
+ c.bounds[i] |= 1 << uint(what)
+ }
+ if which&AMBIENT != 0 {
+ c.ambient[i] |= 1 << uint(what)
+ }
+ }
+}
+
+func (c *capsV3) Unset(which CapType, caps ...Cap) {
+ for _, what := range caps {
+ var i uint
+ if what > 31 {
+ i = uint(what) >> 5
+ what %= 32
+ }
+
+ if which&EFFECTIVE != 0 {
+ c.data[i].effective &= ^(1 << uint(what))
+ }
+ if which&PERMITTED != 0 {
+ c.data[i].permitted &= ^(1 << uint(what))
+ }
+ if which&INHERITABLE != 0 {
+ c.data[i].inheritable &= ^(1 << uint(what))
+ }
+ if which&BOUNDING != 0 {
+ c.bounds[i] &= ^(1 << uint(what))
+ }
+ if which&AMBIENT != 0 {
+ c.ambient[i] &= ^(1 << uint(what))
+ }
+ }
+}
+
+func (c *capsV3) Fill(kind CapType) {
+ if kind&CAPS == CAPS {
+ c.data[0].effective = 0xffffffff
+ c.data[0].permitted = 0xffffffff
+ c.data[0].inheritable = 0
+ c.data[1].effective = 0xffffffff
+ c.data[1].permitted = 0xffffffff
+ c.data[1].inheritable = 0
+ }
+
+ if kind&BOUNDS == BOUNDS {
+ c.bounds[0] = 0xffffffff
+ c.bounds[1] = 0xffffffff
+ }
+ if kind&AMBS == AMBS {
+ c.ambient[0] = 0xffffffff
+ c.ambient[1] = 0xffffffff
+ }
+}
+
+func (c *capsV3) Clear(kind CapType) {
+ if kind&CAPS == CAPS {
+ c.data[0].effective = 0
+ c.data[0].permitted = 0
+ c.data[0].inheritable = 0
+ c.data[1].effective = 0
+ c.data[1].permitted = 0
+ c.data[1].inheritable = 0
+ }
+
+ if kind&BOUNDS == BOUNDS {
+ c.bounds[0] = 0
+ c.bounds[1] = 0
+ }
+ if kind&AMBS == AMBS {
+ c.ambient[0] = 0
+ c.ambient[1] = 0
+ }
+}
+
+func (c *capsV3) StringCap(which CapType) (ret string) {
+ return mkStringCap(c, which)
+}
+
+func (c *capsV3) String() (ret string) {
+ return mkString(c, BOUNDING)
+}
+
+func (c *capsV3) Load() (err error) {
+ err = capget(&c.hdr, &c.data[0])
+ if err != nil {
+ return
+ }
+
+ var status_path string
+
+ if c.hdr.pid == 0 {
+ status_path = fmt.Sprintf("/proc/self/status")
+ } else {
+ status_path = fmt.Sprintf("/proc/%d/status", c.hdr.pid)
+ }
+
+ f, err := os.Open(status_path)
+ if err != nil {
+ return
+ }
+ b := bufio.NewReader(f)
+ for {
+ line, e := b.ReadString('\n')
+ if e != nil {
+ if e != io.EOF {
+ err = e
+ }
+ break
+ }
+ if strings.HasPrefix(line, "CapB") {
+ fmt.Sscanf(line[4:], "nd: %08x%08x", &c.bounds[1], &c.bounds[0])
+ break
+ }
+ if strings.HasPrefix(line, "CapA") {
+ fmt.Sscanf(line[4:], "mb: %08x%08x", &c.ambient[1], &c.ambient[0])
+ break
+ }
+ }
+ f.Close()
+
+ return
+}
+
+func (c *capsV3) Apply(kind CapType) (err error) {
+ if kind&BOUNDS == BOUNDS {
+ var data [2]capData
+ err = capget(&c.hdr, &data[0])
+ if err != nil {
+ return
+ }
+ if (1<<uint(CAP_SETPCAP))&data[0].effective != 0 {
+ for i := Cap(0); i <= CAP_LAST_CAP; i++ {
+ if c.Get(BOUNDING, i) {
+ continue
+ }
+ err = prctl(syscall.PR_CAPBSET_DROP, uintptr(i), 0, 0, 0)
+ if err != nil {
+ // Ignore EINVAL since the capability may not be supported in this system.
+ if errno, ok := err.(syscall.Errno); ok && errno == syscall.EINVAL {
+ err = nil
+ continue
+ }
+ return
+ }
+ }
+ }
+ }
+
+ if kind&CAPS == CAPS {
+ err = capset(&c.hdr, &c.data[0])
+ if err != nil {
+ return
+ }
+ }
+
+ if kind&AMBS == AMBS {
+ for i := Cap(0); i <= CAP_LAST_CAP; i++ {
+ action := pr_CAP_AMBIENT_LOWER
+ if c.Get(AMBIENT, i) {
+ action = pr_CAP_AMBIENT_RAISE
+ }
+ err := prctl(pr_CAP_AMBIENT, action, uintptr(i), 0, 0)
+ // Ignore EINVAL as not supported on kernels before 4.3
+ if errno, ok := err.(syscall.Errno); ok && errno == syscall.EINVAL {
+ err = nil
+ continue
+ }
+ }
+ }
+
+ return
+}
+
+func newFile(path string) (c Capabilities, err error) {
+ c = &capsFile{path: path}
+ err = c.Load()
+ if err != nil {
+ c = nil
+ }
+ return
+}
+
+type capsFile struct {
+ path string
+ data vfscapData
+}
+
+func (c *capsFile) Get(which CapType, what Cap) bool {
+ var i uint
+ if what > 31 {
+ if c.data.version == 1 {
+ return false
+ }
+ i = uint(what) >> 5
+ what %= 32
+ }
+
+ switch which {
+ case EFFECTIVE:
+ return (1<<uint(what))&c.data.effective[i] != 0
+ case PERMITTED:
+ return (1<<uint(what))&c.data.data[i].permitted != 0
+ case INHERITABLE:
+ return (1<<uint(what))&c.data.data[i].inheritable != 0
+ }
+
+ return false
+}
+
+func (c *capsFile) getData(which CapType, dest []uint32) {
+ switch which {
+ case EFFECTIVE:
+ dest[0] = c.data.effective[0]
+ dest[1] = c.data.effective[1]
+ case PERMITTED:
+ dest[0] = c.data.data[0].permitted
+ dest[1] = c.data.data[1].permitted
+ case INHERITABLE:
+ dest[0] = c.data.data[0].inheritable
+ dest[1] = c.data.data[1].inheritable
+ }
+}
+
+func (c *capsFile) Empty(which CapType) bool {
+ var data [2]uint32
+ c.getData(which, data[:])
+ return data[0] == 0 && data[1] == 0
+}
+
+func (c *capsFile) Full(which CapType) bool {
+ var data [2]uint32
+ c.getData(which, data[:])
+ if c.data.version == 0 {
+ return (data[0] & 0x7fffffff) == 0x7fffffff
+ }
+ if (data[0] & 0xffffffff) != 0xffffffff {
+ return false
+ }
+ return (data[1] & capUpperMask) == capUpperMask
+}
+
+func (c *capsFile) Set(which CapType, caps ...Cap) {
+ for _, what := range caps {
+ var i uint
+ if what > 31 {
+ if c.data.version == 1 {
+ continue
+ }
+ i = uint(what) >> 5
+ what %= 32
+ }
+
+ if which&EFFECTIVE != 0 {
+ c.data.effective[i] |= 1 << uint(what)
+ }
+ if which&PERMITTED != 0 {
+ c.data.data[i].permitted |= 1 << uint(what)
+ }
+ if which&INHERITABLE != 0 {
+ c.data.data[i].inheritable |= 1 << uint(what)
+ }
+ }
+}
+
+func (c *capsFile) Unset(which CapType, caps ...Cap) {
+ for _, what := range caps {
+ var i uint
+ if what > 31 {
+ if c.data.version == 1 {
+ continue
+ }
+ i = uint(what) >> 5
+ what %= 32
+ }
+
+ if which&EFFECTIVE != 0 {
+ c.data.effective[i] &= ^(1 << uint(what))
+ }
+ if which&PERMITTED != 0 {
+ c.data.data[i].permitted &= ^(1 << uint(what))
+ }
+ if which&INHERITABLE != 0 {
+ c.data.data[i].inheritable &= ^(1 << uint(what))
+ }
+ }
+}
+
+func (c *capsFile) Fill(kind CapType) {
+ if kind&CAPS == CAPS {
+ c.data.effective[0] = 0xffffffff
+ c.data.data[0].permitted = 0xffffffff
+ c.data.data[0].inheritable = 0
+ if c.data.version == 2 {
+ c.data.effective[1] = 0xffffffff
+ c.data.data[1].permitted = 0xffffffff
+ c.data.data[1].inheritable = 0
+ }
+ }
+}
+
+func (c *capsFile) Clear(kind CapType) {
+ if kind&CAPS == CAPS {
+ c.data.effective[0] = 0
+ c.data.data[0].permitted = 0
+ c.data.data[0].inheritable = 0
+ if c.data.version == 2 {
+ c.data.effective[1] = 0
+ c.data.data[1].permitted = 0
+ c.data.data[1].inheritable = 0
+ }
+ }
+}
+
+func (c *capsFile) StringCap(which CapType) (ret string) {
+ return mkStringCap(c, which)
+}
+
+func (c *capsFile) String() (ret string) {
+ return mkString(c, INHERITABLE)
+}
+
+func (c *capsFile) Load() (err error) {
+ return getVfsCap(c.path, &c.data)
+}
+
+func (c *capsFile) Apply(kind CapType) (err error) {
+ if kind&CAPS == CAPS {
+ return setVfsCap(c.path, &c.data)
+ }
+ return
+}
diff --git a/vendor/github.com/syndtr/gocapability/capability/capability_noop.go b/vendor/github.com/syndtr/gocapability/capability/capability_noop.go
new file mode 100644
index 0000000..9bb3070
--- /dev/null
+++ b/vendor/github.com/syndtr/gocapability/capability/capability_noop.go
@@ -0,0 +1,19 @@
+// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com>
+// 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
+
+package capability
+
+import "errors"
+
+func newPid(pid int) (Capabilities, error) {
+ return nil, errors.New("not supported")
+}
+
+func newFile(path string) (Capabilities, error) {
+ return nil, errors.New("not supported")
+}
diff --git a/vendor/github.com/syndtr/gocapability/capability/enum.go b/vendor/github.com/syndtr/gocapability/capability/enum.go
new file mode 100644
index 0000000..6938173
--- /dev/null
+++ b/vendor/github.com/syndtr/gocapability/capability/enum.go
@@ -0,0 +1,268 @@
+// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com>
+// All rights reserved.
+//
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package capability
+
+type CapType uint
+
+func (c CapType) String() string {
+ switch c {
+ case EFFECTIVE:
+ return "effective"
+ case PERMITTED:
+ return "permitted"
+ case INHERITABLE:
+ return "inheritable"
+ case BOUNDING:
+ return "bounding"
+ case CAPS:
+ return "caps"
+ case AMBIENT:
+ return "ambient"
+ }
+ return "unknown"
+}
+
+const (
+ EFFECTIVE CapType = 1 << iota
+ PERMITTED
+ INHERITABLE
+ BOUNDING
+ AMBIENT
+
+ CAPS = EFFECTIVE | PERMITTED | INHERITABLE
+ BOUNDS = BOUNDING
+ AMBS = AMBIENT
+)
+
+//go:generate go run enumgen/gen.go
+type Cap int
+
+// POSIX-draft defined capabilities.
+const (
+ // In a system with the [_POSIX_CHOWN_RESTRICTED] option defined, this
+ // overrides the restriction of changing file ownership and group
+ // ownership.
+ CAP_CHOWN = Cap(0)
+
+ // Override all DAC access, including ACL execute access if
+ // [_POSIX_ACL] is defined. Excluding DAC access covered by
+ // CAP_LINUX_IMMUTABLE.
+ CAP_DAC_OVERRIDE = Cap(1)
+
+ // Overrides all DAC restrictions regarding read and search on files
+ // and directories, including ACL restrictions if [_POSIX_ACL] is
+ // defined. Excluding DAC access covered by CAP_LINUX_IMMUTABLE.
+ CAP_DAC_READ_SEARCH = Cap(2)
+
+ // Overrides all restrictions about allowed operations on files, where
+ // file owner ID must be equal to the user ID, except where CAP_FSETID
+ // is applicable. It doesn't override MAC and DAC restrictions.
+ CAP_FOWNER = Cap(3)
+
+ // Overrides the following restrictions that the effective user ID
+ // shall match the file owner ID when setting the S_ISUID and S_ISGID
+ // bits on that file; that the effective group ID (or one of the
+ // supplementary group IDs) shall match the file owner ID when setting
+ // the S_ISGID bit on that file; that the S_ISUID and S_ISGID bits are
+ // cleared on successful return from chown(2) (not implemented).
+ CAP_FSETID = Cap(4)
+
+ // Overrides the restriction that the real or effective user ID of a
+ // process sending a signal must match the real or effective user ID
+ // of the process receiving the signal.
+ CAP_KILL = Cap(5)
+
+ // Allows setgid(2) manipulation
+ // Allows setgroups(2)
+ // Allows forged gids on socket credentials passing.
+ CAP_SETGID = Cap(6)
+
+ // Allows set*uid(2) manipulation (including fsuid).
+ // Allows forged pids on socket credentials passing.
+ CAP_SETUID = Cap(7)
+
+ // Linux-specific capabilities
+
+ // Without VFS support for capabilities:
+ // Transfer any capability in your permitted set to any pid,
+ // remove any capability in your permitted set from any pid
+ // With VFS support for capabilities (neither of above, but)
+ // Add any capability from current's capability bounding set
+ // to the current process' inheritable set
+ // Allow taking bits out of capability bounding set
+ // Allow modification of the securebits for a process
+ CAP_SETPCAP = Cap(8)
+
+ // Allow modification of S_IMMUTABLE and S_APPEND file attributes
+ CAP_LINUX_IMMUTABLE = Cap(9)
+
+ // Allows binding to TCP/UDP sockets below 1024
+ // Allows binding to ATM VCIs below 32
+ CAP_NET_BIND_SERVICE = Cap(10)
+
+ // Allow broadcasting, listen to multicast
+ CAP_NET_BROADCAST = Cap(11)
+
+ // Allow interface configuration
+ // Allow administration of IP firewall, masquerading and accounting
+ // Allow setting debug option on sockets
+ // Allow modification of routing tables
+ // Allow setting arbitrary process / process group ownership on
+ // sockets
+ // Allow binding to any address for transparent proxying (also via NET_RAW)
+ // Allow setting TOS (type of service)
+ // Allow setting promiscuous mode
+ // Allow clearing driver statistics
+ // Allow multicasting
+ // Allow read/write of device-specific registers
+ // Allow activation of ATM control sockets
+ CAP_NET_ADMIN = Cap(12)
+
+ // Allow use of RAW sockets
+ // Allow use of PACKET sockets
+ // Allow binding to any address for transparent proxying (also via NET_ADMIN)
+ CAP_NET_RAW = Cap(13)
+
+ // Allow locking of shared memory segments
+ // Allow mlock and mlockall (which doesn't really have anything to do
+ // with IPC)
+ CAP_IPC_LOCK = Cap(14)
+
+ // Override IPC ownership checks
+ CAP_IPC_OWNER = Cap(15)
+
+ // Insert and remove kernel modules - modify kernel without limit
+ CAP_SYS_MODULE = Cap(16)
+
+ // Allow ioperm/iopl access
+ // Allow sending USB messages to any device via /proc/bus/usb
+ CAP_SYS_RAWIO = Cap(17)
+
+ // Allow use of chroot()
+ CAP_SYS_CHROOT = Cap(18)
+
+ // Allow ptrace() of any process
+ CAP_SYS_PTRACE = Cap(19)
+
+ // Allow configuration of process accounting
+ CAP_SYS_PACCT = Cap(20)
+
+ // Allow configuration of the secure attention key
+ // Allow administration of the random device
+ // Allow examination and configuration of disk quotas
+ // Allow setting the domainname
+ // Allow setting the hostname
+ // Allow calling bdflush()
+ // Allow mount() and umount(), setting up new smb connection
+ // Allow some autofs root ioctls
+ // Allow nfsservctl
+ // Allow VM86_REQUEST_IRQ
+ // Allow to read/write pci config on alpha
+ // Allow irix_prctl on mips (setstacksize)
+ // Allow flushing all cache on m68k (sys_cacheflush)
+ // Allow removing semaphores
+ // Used instead of CAP_CHOWN to "chown" IPC message queues, semaphores
+ // and shared memory
+ // Allow locking/unlocking of shared memory segment
+ // Allow turning swap on/off
+ // Allow forged pids on socket credentials passing
+ // Allow setting readahead and flushing buffers on block devices
+ // Allow setting geometry in floppy driver
+ // Allow turning DMA on/off in xd driver
+ // Allow administration of md devices (mostly the above, but some
+ // extra ioctls)
+ // Allow tuning the ide driver
+ // Allow access to the nvram device
+ // Allow administration of apm_bios, serial and bttv (TV) device
+ // Allow manufacturer commands in isdn CAPI support driver
+ // Allow reading non-standardized portions of pci configuration space
+ // Allow DDI debug ioctl on sbpcd driver
+ // Allow setting up serial ports
+ // Allow sending raw qic-117 commands
+ // Allow enabling/disabling tagged queuing on SCSI controllers and sending
+ // arbitrary SCSI commands
+ // Allow setting encryption key on loopback filesystem
+ // Allow setting zone reclaim policy
+ CAP_SYS_ADMIN = Cap(21)
+
+ // Allow use of reboot()
+ CAP_SYS_BOOT = Cap(22)
+
+ // Allow raising priority and setting priority on other (different
+ // UID) processes
+ // Allow use of FIFO and round-robin (realtime) scheduling on own
+ // processes and setting the scheduling algorithm used by another
+ // process.
+ // Allow setting cpu affinity on other processes
+ CAP_SYS_NICE = Cap(23)
+
+ // Override resource limits. Set resource limits.
+ // Override quota limits.
+ // Override reserved space on ext2 filesystem
+ // Modify data journaling mode on ext3 filesystem (uses journaling
+ // resources)
+ // NOTE: ext2 honors fsuid when checking for resource overrides, so
+ // you can override using fsuid too
+ // Override size restrictions on IPC message queues
+ // Allow more than 64hz interrupts from the real-time clock
+ // Override max number of consoles on console allocation
+ // Override max number of keymaps
+ CAP_SYS_RESOURCE = Cap(24)
+
+ // Allow manipulation of system clock
+ // Allow irix_stime on mips
+ // Allow setting the real-time clock
+ CAP_SYS_TIME = Cap(25)
+
+ // Allow configuration of tty devices
+ // Allow vhangup() of tty
+ CAP_SYS_TTY_CONFIG = Cap(26)
+
+ // Allow the privileged aspects of mknod()
+ CAP_MKNOD = Cap(27)
+
+ // Allow taking of leases on files
+ CAP_LEASE = Cap(28)
+
+ CAP_AUDIT_WRITE = Cap(29)
+ CAP_AUDIT_CONTROL = Cap(30)
+ CAP_SETFCAP = Cap(31)
+
+ // Override MAC access.
+ // The base kernel enforces no MAC policy.
+ // An LSM may enforce a MAC policy, and if it does and it chooses
+ // to implement capability based overrides of that policy, this is
+ // the capability it should use to do so.
+ CAP_MAC_OVERRIDE = Cap(32)
+
+ // Allow MAC configuration or state changes.
+ // The base kernel requires no MAC configuration.
+ // An LSM may enforce a MAC policy, and if it does and it chooses
+ // to implement capability based checks on modifications to that
+ // policy or the data required to maintain it, this is the
+ // capability it should use to do so.
+ CAP_MAC_ADMIN = Cap(33)
+
+ // Allow configuring the kernel's syslog (printk behaviour)
+ CAP_SYSLOG = Cap(34)
+
+ // Allow triggering something that will wake the system
+ CAP_WAKE_ALARM = Cap(35)
+
+ // Allow preventing system suspends
+ CAP_BLOCK_SUSPEND = Cap(36)
+
+ // Allow reading audit messages from the kernel
+ CAP_AUDIT_READ = Cap(37)
+)
+
+var (
+ // Highest valid capability of the running kernel.
+ CAP_LAST_CAP = Cap(63)
+
+ capUpperMask = ^uint32(0)
+)
diff --git a/vendor/github.com/syndtr/gocapability/capability/enum_gen.go b/vendor/github.com/syndtr/gocapability/capability/enum_gen.go
new file mode 100644
index 0000000..b9e6d2d
--- /dev/null
+++ b/vendor/github.com/syndtr/gocapability/capability/enum_gen.go
@@ -0,0 +1,129 @@
+// generated file; DO NOT EDIT - use go generate in directory with source
+
+package capability
+
+func (c Cap) String() string {
+ switch c {
+ case CAP_CHOWN:
+ return "chown"
+ case CAP_DAC_OVERRIDE:
+ return "dac_override"
+ case CAP_DAC_READ_SEARCH:
+ return "dac_read_search"
+ case CAP_FOWNER:
+ return "fowner"
+ case CAP_FSETID:
+ return "fsetid"
+ case CAP_KILL:
+ return "kill"
+ case CAP_SETGID:
+ return "setgid"
+ case CAP_SETUID:
+ return "setuid"
+ case CAP_SETPCAP:
+ return "setpcap"
+ case CAP_LINUX_IMMUTABLE:
+ return "linux_immutable"
+ case CAP_NET_BIND_SERVICE:
+ return "net_bind_service"
+ case CAP_NET_BROADCAST:
+ return "net_broadcast"
+ case CAP_NET_ADMIN:
+ return "net_admin"
+ case CAP_NET_RAW:
+ return "net_raw"
+ case CAP_IPC_LOCK:
+ return "ipc_lock"
+ case CAP_IPC_OWNER:
+ return "ipc_owner"
+ case CAP_SYS_MODULE:
+ return "sys_module"
+ case CAP_SYS_RAWIO:
+ return "sys_rawio"
+ case CAP_SYS_CHROOT:
+ return "sys_chroot"
+ case CAP_SYS_PTRACE:
+ return "sys_ptrace"
+ case CAP_SYS_PACCT:
+ return "sys_pacct"
+ case CAP_SYS_ADMIN:
+ return "sys_admin"
+ case CAP_SYS_BOOT:
+ return "sys_boot"
+ case CAP_SYS_NICE:
+ return "sys_nice"
+ case CAP_SYS_RESOURCE:
+ return "sys_resource"
+ case CAP_SYS_TIME:
+ return "sys_time"
+ case CAP_SYS_TTY_CONFIG:
+ return "sys_tty_config"
+ case CAP_MKNOD:
+ return "mknod"
+ case CAP_LEASE:
+ return "lease"
+ case CAP_AUDIT_WRITE:
+ return "audit_write"
+ case CAP_AUDIT_CONTROL:
+ return "audit_control"
+ case CAP_SETFCAP:
+ return "setfcap"
+ case CAP_MAC_OVERRIDE:
+ return "mac_override"
+ case CAP_MAC_ADMIN:
+ return "mac_admin"
+ case CAP_SYSLOG:
+ return "syslog"
+ case CAP_WAKE_ALARM:
+ return "wake_alarm"
+ case CAP_BLOCK_SUSPEND:
+ return "block_suspend"
+ case CAP_AUDIT_READ:
+ return "audit_read"
+ }
+ return "unknown"
+}
+
+// List returns list of all supported capabilities
+func List() []Cap {
+ return []Cap{
+ CAP_CHOWN,
+ CAP_DAC_OVERRIDE,
+ CAP_DAC_READ_SEARCH,
+ CAP_FOWNER,
+ CAP_FSETID,
+ CAP_KILL,
+ CAP_SETGID,
+ CAP_SETUID,
+ CAP_SETPCAP,
+ CAP_LINUX_IMMUTABLE,
+ CAP_NET_BIND_SERVICE,
+ CAP_NET_BROADCAST,
+ CAP_NET_ADMIN,
+ CAP_NET_RAW,
+ CAP_IPC_LOCK,
+ CAP_IPC_OWNER,
+ CAP_SYS_MODULE,
+ CAP_SYS_RAWIO,
+ CAP_SYS_CHROOT,
+ CAP_SYS_PTRACE,
+ CAP_SYS_PACCT,
+ CAP_SYS_ADMIN,
+ CAP_SYS_BOOT,
+ CAP_SYS_NICE,
+ CAP_SYS_RESOURCE,
+ CAP_SYS_TIME,
+ CAP_SYS_TTY_CONFIG,
+ CAP_MKNOD,
+ CAP_LEASE,
+ CAP_AUDIT_WRITE,
+ CAP_AUDIT_CONTROL,
+ CAP_SETFCAP,
+ CAP_MAC_OVERRIDE,
+ CAP_MAC_ADMIN,
+ CAP_SYSLOG,
+ CAP_WAKE_ALARM,
+ CAP_BLOCK_SUSPEND,
+ CAP_AUDIT_READ,
+ }
+}
diff --git a/vendor/github.com/syndtr/gocapability/capability/syscall_linux.go b/vendor/github.com/syndtr/gocapability/capability/syscall_linux.go
new file mode 100644
index 0000000..eb71700
--- /dev/null
+++ b/vendor/github.com/syndtr/gocapability/capability/syscall_linux.go
@@ -0,0 +1,154 @@
+// Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com>
+// All rights reserved.
+//
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package capability
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+type capHeader struct {
+ version uint32
+ pid int
+}
+
+type capData struct {
+ effective uint32
+ permitted uint32
+ inheritable uint32
+}
+
+func capget(hdr *capHeader, data *capData) (err error) {
+ _, _, e1 := syscall.Syscall(syscall.SYS_CAPGET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func capset(hdr *capHeader, data *capData) (err error) {
+ _, _, e1 := syscall.Syscall(syscall.SYS_CAPSET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+// not yet in syscall
+const (
+ pr_CAP_AMBIENT = 47
+ pr_CAP_AMBIENT_IS_SET = uintptr(1)
+ pr_CAP_AMBIENT_RAISE = uintptr(2)
+ pr_CAP_AMBIENT_LOWER = uintptr(3)
+ pr_CAP_AMBIENT_CLEAR_ALL = uintptr(4)
+)
+
+func prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) {
+ _, _, e1 := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+const (
+ vfsXattrName = "security.capability"
+
+ vfsCapVerMask = 0xff000000
+ vfsCapVer1 = 0x01000000
+ vfsCapVer2 = 0x02000000
+
+ vfsCapFlagMask = ^vfsCapVerMask
+ vfsCapFlageffective = 0x000001
+
+ vfscapDataSizeV1 = 4 * (1 + 2*1)
+ vfscapDataSizeV2 = 4 * (1 + 2*2)
+)
+
+type vfscapData struct {
+ magic uint32
+ data [2]struct {
+ permitted uint32
+ inheritable uint32
+ }
+ effective [2]uint32
+ version int8
+}
+
+var (
+ _vfsXattrName *byte
+)
+
+func init() {
+ _vfsXattrName, _ = syscall.BytePtrFromString(vfsXattrName)
+}
+
+func getVfsCap(path string, dest *vfscapData) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(dest)), vfscapDataSizeV2, 0, 0)
+ if e1 != 0 {
+ if e1 == syscall.ENODATA {
+ dest.version = 2
+ return
+ }
+ err = e1
+ }
+ switch dest.magic & vfsCapVerMask {
+ case vfsCapVer1:
+ dest.version = 1
+ if r0 != vfscapDataSizeV1 {
+ return syscall.EINVAL
+ }
+ dest.data[1].permitted = 0
+ dest.data[1].inheritable = 0
+ case vfsCapVer2:
+ dest.version = 2
+ if r0 != vfscapDataSizeV2 {
+ return syscall.EINVAL
+ }
+ default:
+ return syscall.EINVAL
+ }
+ if dest.magic&vfsCapFlageffective != 0 {
+ dest.effective[0] = dest.data[0].permitted | dest.data[0].inheritable
+ dest.effective[1] = dest.data[1].permitted | dest.data[1].inheritable
+ } else {
+ dest.effective[0] = 0
+ dest.effective[1] = 0
+ }
+ return
+}
+
+func setVfsCap(path string, data *vfscapData) (err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var size uintptr
+ if data.version == 1 {
+ data.magic = vfsCapVer1
+ size = vfscapDataSizeV1
+ } else if data.version == 2 {
+ data.magic = vfsCapVer2
+ if data.effective[0] != 0 || data.effective[1] != 0 {
+ data.magic |= vfsCapFlageffective
+ }
+ size = vfscapDataSizeV2
+ } else {
+ return syscall.EINVAL
+ }
+ _, _, e1 := syscall.Syscall6(syscall.SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(data)), size, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
diff --git a/vendor/github.com/tchap/go-patricia/LICENSE b/vendor/github.com/tchap/go-patricia/LICENSE
new file mode 100644
index 0000000..e50d398
--- /dev/null
+++ b/vendor/github.com/tchap/go-patricia/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 The AUTHORS
+
+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/tchap/go-patricia/README.md b/vendor/github.com/tchap/go-patricia/README.md
new file mode 100644
index 0000000..d9cbf62
--- /dev/null
+++ b/vendor/github.com/tchap/go-patricia/README.md
@@ -0,0 +1,123 @@
+# go-patricia #
+
+**Documentation**: [GoDoc](http://godoc.org/github.com/tchap/go-patricia/patricia)<br />
+**Build Status**: [![Build
+Status](https://drone.io/github.com/tchap/go-patricia/status.png)](https://drone.io/github.com/tchap/go-patricia/latest)<br />
+**Test Coverage**: [![Coverage
+Status](https://coveralls.io/repos/tchap/go-patricia/badge.png)](https://coveralls.io/r/tchap/go-patricia)
+
+## About ##
+
+A generic patricia trie (also called radix tree) implemented in Go (Golang).
+
+The patricia trie as implemented in this library enables fast visiting of items
+in some particular ways:
+
+1. visit all items saved in the tree,
+2. visit all items matching particular prefix (visit subtree), or
+3. given a string, visit all items matching some prefix of that string.
+
+`[]byte` type is used for keys, `interface{}` for values.
+
+`Trie` is not thread safe. Synchronize the access yourself.
+
+### State of the Project ###
+
+Apparently some people are using this, so the API should not change often.
+Any ideas on how to make the library better are still welcome.
+
+More (unit) testing would be cool as well...
+
+## Usage ##
+
+Import the package from GitHub first.
+
+```go
+import "github.com/tchap/go-patricia/patricia"
+```
+
+You can as well use gopkg.in thingie:
+
+```go
+import "gopkg.in/tchap/go-patricia.v2/patricia"
+```
+
+Then you can start having fun.
+
+```go
+printItem := func(prefix patricia.Prefix, item patricia.Item) error {
+ fmt.Printf("%q: %v\n", prefix, item)
+ return nil
+}
+
+// Create a new default trie (using the default parameter values).
+trie := NewTrie()
+
+// Create a new custom trie.
+trie := NewTrie(MaxPrefixPerNode(16), MaxChildrenPerSparseNode(10))
+
+// Insert some items.
+trie.Insert(Prefix("Pepa Novak"), 1)
+trie.Insert(Prefix("Pepa Sindelar"), 2)
+trie.Insert(Prefix("Karel Macha"), 3)
+trie.Insert(Prefix("Karel Hynek Macha"), 4)
+
+// Just check if some things are present in the tree.
+key := Prefix("Pepa Novak")
+fmt.Printf("%q present? %v\n", key, trie.Match(key))
+// "Pepa Novak" present? true
+key = Prefix("Karel")
+fmt.Printf("Anybody called %q here? %v\n", key, trie.MatchSubtree(key))
+// Anybody called "Karel" here? true
+
+// Walk the tree in alphabetical order.
+trie.Visit(printItem)
+// "Karel Hynek Macha": 4
+// "Karel Macha": 3
+// "Pepa Novak": 1
+// "Pepa Sindelar": 2
+
+// Walk a subtree.
+trie.VisitSubtree(Prefix("Pepa"), printItem)
+// "Pepa Novak": 1
+// "Pepa Sindelar": 2
+
+// Modify an item, then fetch it from the tree.
+trie.Set(Prefix("Karel Hynek Macha"), 10)
+key = Prefix("Karel Hynek Macha")
+fmt.Printf("%q: %v\n", key, trie.Get(key))
+// "Karel Hynek Macha": 10
+
+// Walk prefixes.
+prefix := Prefix("Karel Hynek Macha je kouzelnik")
+trie.VisitPrefixes(prefix, printItem)
+// "Karel Hynek Macha": 10
+
+// Delete some items.
+trie.Delete(Prefix("Pepa Novak"))
+trie.Delete(Prefix("Karel Macha"))
+
+// Walk again.
+trie.Visit(printItem)
+// "Karel Hynek Macha": 10
+// "Pepa Sindelar": 2
+
+// Delete a subtree.
+trie.DeleteSubtree(Prefix("Pepa"))
+
+// Print what is left.
+trie.Visit(printItem)
+// "Karel Hynek Macha": 10
+```
+
+## License ##
+
+MIT, check the `LICENSE` file.
+
+[![Gittip
+Badge](http://img.shields.io/gittip/alanhamlett.png)](https://www.gittip.com/tchap/
+"Gittip Badge")
+
+[![Bitdeli
+Badge](https://d2weczhvl823v0.cloudfront.net/tchap/go-patricia/trend.png)](https://bitdeli.com/free
+"Bitdeli Badge")
diff --git a/vendor/github.com/tchap/go-patricia/patricia/children.go b/vendor/github.com/tchap/go-patricia/patricia/children.go
new file mode 100644
index 0000000..a5677c3
--- /dev/null
+++ b/vendor/github.com/tchap/go-patricia/patricia/children.go
@@ -0,0 +1,325 @@
+// Copyright (c) 2014 The go-patricia AUTHORS
+//
+// Use of this source code is governed by The MIT License
+// that can be found in the LICENSE file.
+
+package patricia
+
+import (
+ "fmt"
+ "io"
+ "sort"
+)
+
+type childList interface {
+ length() int
+ head() *Trie
+ add(child *Trie) childList
+ remove(b byte)
+ replace(b byte, child *Trie)
+ next(b byte) *Trie
+ walk(prefix *Prefix, visitor VisitorFunc) error
+ print(w io.Writer, indent int)
+ total() int
+}
+
+type tries []*Trie
+
+func (t tries) Len() int {
+ return len(t)
+}
+
+func (t tries) Less(i, j int) bool {
+ strings := sort.StringSlice{string(t[i].prefix), string(t[j].prefix)}
+ return strings.Less(0, 1)
+}
+
+func (t tries) Swap(i, j int) {
+ t[i], t[j] = t[j], t[i]
+}
+
+type sparseChildList struct {
+ children tries
+}
+
+func newSparseChildList(maxChildrenPerSparseNode int) childList {
+ return &sparseChildList{
+ children: make(tries, 0, maxChildrenPerSparseNode),
+ }
+}
+
+func (list *sparseChildList) length() int {
+ return len(list.children)
+}
+
+func (list *sparseChildList) head() *Trie {
+ return list.children[0]
+}
+
+func (list *sparseChildList) add(child *Trie) childList {
+ // Search for an empty spot and insert the child if possible.
+ if len(list.children) != cap(list.children) {
+ list.children = append(list.children, child)
+ return list
+ }
+
+ // Otherwise we have to transform to the dense list type.
+ return newDenseChildList(list, child)
+}
+
+func (list *sparseChildList) remove(b byte) {
+ for i, node := range list.children {
+ if node.prefix[0] == b {
+ list.children[i] = list.children[len(list.children)-1]
+ list.children[len(list.children)-1] = nil
+ list.children = list.children[:len(list.children)-1]
+ return
+ }
+ }
+
+ // This is not supposed to be reached.
+ panic("removing non-existent child")
+}
+
+func (list *sparseChildList) replace(b byte, child *Trie) {
+ // Make a consistency check.
+ if p0 := child.prefix[0]; p0 != b {
+ panic(fmt.Errorf("child prefix mismatch: %v != %v", p0, b))
+ }
+
+ // Seek the child and replace it.
+ for i, node := range list.children {
+ if node.prefix[0] == b {
+ list.children[i] = child
+ return
+ }
+ }
+}
+
+func (list *sparseChildList) next(b byte) *Trie {
+ for _, child := range list.children {
+ if child.prefix[0] == b {
+ return child
+ }
+ }
+ return nil
+}
+
+func (list *sparseChildList) walk(prefix *Prefix, visitor VisitorFunc) error {
+
+ sort.Sort(list.children)
+
+ for _, child := range list.children {
+ *prefix = append(*prefix, child.prefix...)
+ if child.item != nil {
+ err := visitor(*prefix, child.item)
+ if err != nil {
+ if err == SkipSubtree {
+ *prefix = (*prefix)[:len(*prefix)-len(child.prefix)]
+ continue
+ }
+ *prefix = (*prefix)[:len(*prefix)-len(child.prefix)]
+ return err
+ }
+ }
+
+ err := child.children.walk(prefix, visitor)
+ *prefix = (*prefix)[:len(*prefix)-len(child.prefix)]
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (list *sparseChildList) total() int {
+ tot := 0
+ for _, child := range list.children {
+ if child != nil {
+ tot = tot + child.total()
+ }
+ }
+ return tot
+}
+
+func (list *sparseChildList) print(w io.Writer, indent int) {
+ for _, child := range list.children {
+ if child != nil {
+ child.print(w, indent)
+ }
+ }
+}
+
+type denseChildList struct {
+ min int
+ max int
+ numChildren int
+ headIndex int
+ children []*Trie
+}
+
+func newDenseChildList(list *sparseChildList, child *Trie) childList {
+ var (
+ min int = 255
+ max int = 0
+ )
+ for _, child := range list.children {
+ b := int(child.prefix[0])
+ if b < min {
+ min = b
+ }
+ if b > max {
+ max = b
+ }
+ }
+
+ b := int(child.prefix[0])
+ if b < min {
+ min = b
+ }
+ if b > max {
+ max = b
+ }
+
+ children := make([]*Trie, max-min+1)
+ for _, child := range list.children {
+ children[int(child.prefix[0])-min] = child
+ }
+ children[int(child.prefix[0])-min] = child
+
+ return &denseChildList{
+ min: min,
+ max: max,
+ numChildren: list.length() + 1,
+ headIndex: 0,
+ children: children,
+ }
+}
+
+func (list *denseChildList) length() int {
+ return list.numChildren
+}
+
+func (list *denseChildList) head() *Trie {
+ return list.children[list.headIndex]
+}
+
+func (list *denseChildList) add(child *Trie) childList {
+ b := int(child.prefix[0])
+ var i int
+
+ switch {
+ case list.min <= b && b <= list.max:
+ if list.children[b-list.min] != nil {
+ panic("dense child list collision detected")
+ }
+ i = b - list.min
+ list.children[i] = child
+
+ case b < list.min:
+ children := make([]*Trie, list.max-b+1)
+ i = 0
+ children[i] = child
+ copy(children[list.min-b:], list.children)
+ list.children = children
+ list.min = b
+
+ default: // b > list.max
+ children := make([]*Trie, b-list.min+1)
+ i = b - list.min
+ children[i] = child
+ copy(children, list.children)
+ list.children = children
+ list.max = b
+ }
+
+ list.numChildren++
+ if i < list.headIndex {
+ list.headIndex = i
+ }
+ return list
+}
+
+func (list *denseChildList) remove(b byte) {
+ i := int(b) - list.min
+ if list.children[i] == nil {
+ // This is not supposed to be reached.
+ panic("removing non-existent child")
+ }
+ list.numChildren--
+ list.children[i] = nil
+
+ // Update head index.
+ if i == list.headIndex {
+ for ; i < len(list.children); i++ {
+ if list.children[i] != nil {
+ list.headIndex = i
+ return
+ }
+ }
+ }
+}
+
+func (list *denseChildList) replace(b byte, child *Trie) {
+ // Make a consistency check.
+ if p0 := child.prefix[0]; p0 != b {
+ panic(fmt.Errorf("child prefix mismatch: %v != %v", p0, b))
+ }
+
+ // Replace the child.
+ list.children[int(b)-list.min] = child
+}
+
+func (list *denseChildList) next(b byte) *Trie {
+ i := int(b)
+ if i < list.min || list.max < i {
+ return nil
+ }
+ return list.children[i-list.min]
+}
+
+func (list *denseChildList) walk(prefix *Prefix, visitor VisitorFunc) error {
+ for _, child := range list.children {
+ if child == nil {
+ continue
+ }
+ *prefix = append(*prefix, child.prefix...)
+ if child.item != nil {
+ if err := visitor(*prefix, child.item); err != nil {
+ if err == SkipSubtree {
+ *prefix = (*prefix)[:len(*prefix)-len(child.prefix)]
+ continue
+ }
+ *prefix = (*prefix)[:len(*prefix)-len(child.prefix)]
+ return err
+ }
+ }
+
+ err := child.children.walk(prefix, visitor)
+ *prefix = (*prefix)[:len(*prefix)-len(child.prefix)]
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (list *denseChildList) print(w io.Writer, indent int) {
+ for _, child := range list.children {
+ if child != nil {
+ child.print(w, indent)
+ }
+ }
+}
+
+func (list *denseChildList) total() int {
+ tot := 0
+ for _, child := range list.children {
+ if child != nil {
+ tot = tot + child.total()
+ }
+ }
+ return tot
+}
diff --git a/vendor/github.com/tchap/go-patricia/patricia/patricia.go b/vendor/github.com/tchap/go-patricia/patricia/patricia.go
new file mode 100644
index 0000000..a1fc53d
--- /dev/null
+++ b/vendor/github.com/tchap/go-patricia/patricia/patricia.go
@@ -0,0 +1,594 @@
+// Copyright (c) 2014 The go-patricia AUTHORS
+//
+// Use of this source code is governed by The MIT License
+// that can be found in the LICENSE file.
+
+package patricia
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+)
+
+//------------------------------------------------------------------------------
+// Trie
+//------------------------------------------------------------------------------
+
+const (
+ DefaultMaxPrefixPerNode = 10
+ DefaultMaxChildrenPerSparseNode = 8
+)
+
+type (
+ Prefix []byte
+ Item interface{}
+ VisitorFunc func(prefix Prefix, item Item) error
+)
+
+// Trie is a generic patricia trie that allows fast retrieval of items by prefix.
+// and other funky stuff.
+//
+// Trie is not thread-safe.
+type Trie struct {
+ prefix Prefix
+ item Item
+
+ maxPrefixPerNode int
+ maxChildrenPerSparseNode int
+
+ children childList
+}
+
+// Public API ------------------------------------------------------------------
+
+type Option func(*Trie)
+
+// Trie constructor.
+func NewTrie(options ...Option) *Trie {
+ trie := &Trie{}
+
+ for _, opt := range options {
+ opt(trie)
+ }
+
+ if trie.maxPrefixPerNode <= 0 {
+ trie.maxPrefixPerNode = DefaultMaxPrefixPerNode
+ }
+ if trie.maxChildrenPerSparseNode <= 0 {
+ trie.maxChildrenPerSparseNode = DefaultMaxChildrenPerSparseNode
+ }
+
+ trie.children = newSparseChildList(trie.maxChildrenPerSparseNode)
+ return trie
+}
+
+func MaxPrefixPerNode(value int) Option {
+ return func(trie *Trie) {
+ trie.maxPrefixPerNode = value
+ }
+}
+
+func MaxChildrenPerSparseNode(value int) Option {
+ return func(trie *Trie) {
+ trie.maxChildrenPerSparseNode = value
+ }
+}
+
+// Item returns the item stored in the root of this trie.
+func (trie *Trie) Item() Item {
+ return trie.item
+}
+
+// Insert inserts a new item into the trie using the given prefix. Insert does
+// not replace existing items. It returns false if an item was already in place.
+func (trie *Trie) Insert(key Prefix, item Item) (inserted bool) {
+ return trie.put(key, item, false)
+}
+
+// Set works much like Insert, but it always sets the item, possibly replacing
+// the item previously inserted.
+func (trie *Trie) Set(key Prefix, item Item) {
+ trie.put(key, item, true)
+}
+
+// Get returns the item located at key.
+//
+// This method is a bit dangerous, because Get can as well end up in an internal
+// node that is not really representing any user-defined value. So when nil is
+// a valid value being used, it is not possible to tell if the value was inserted
+// into the tree by the user or not. A possible workaround for this is not to use
+// nil interface as a valid value, even using zero value of any type is enough
+// to prevent this bad behaviour.
+func (trie *Trie) Get(key Prefix) (item Item) {
+ _, node, found, leftover := trie.findSubtree(key)
+ if !found || len(leftover) != 0 {
+ return nil
+ }
+ return node.item
+}
+
+// Match returns what Get(prefix) != nil would return. The same warning as for
+// Get applies here as well.
+func (trie *Trie) Match(prefix Prefix) (matchedExactly bool) {
+ return trie.Get(prefix) != nil
+}
+
+// MatchSubtree returns true when there is a subtree representing extensions
+// to key, that is if there are any keys in the tree which have key as prefix.
+func (trie *Trie) MatchSubtree(key Prefix) (matched bool) {
+ _, _, matched, _ = trie.findSubtree(key)
+ return
+}
+
+// Visit calls visitor on every node containing a non-nil item
+// in alphabetical order.
+//
+// If an error is returned from visitor, the function stops visiting the tree
+// and returns that error, unless it is a special error - SkipSubtree. In that
+// case Visit skips the subtree represented by the current node and continues
+// elsewhere.
+func (trie *Trie) Visit(visitor VisitorFunc) error {
+ return trie.walk(nil, visitor)
+}
+
+func (trie *Trie) size() int {
+ n := 0
+
+ trie.walk(nil, func(prefix Prefix, item Item) error {
+ n++
+ return nil
+ })
+
+ return n
+}
+
+func (trie *Trie) total() int {
+ return 1 + trie.children.total()
+}
+
+// VisitSubtree works much like Visit, but it only visits nodes matching prefix.
+func (trie *Trie) VisitSubtree(prefix Prefix, visitor VisitorFunc) error {
+ // Nil prefix not allowed.
+ if prefix == nil {
+ panic(ErrNilPrefix)
+ }
+
+ // Empty trie must be handled explicitly.
+ if trie.prefix == nil {
+ return nil
+ }
+
+ // Locate the relevant subtree.
+ _, root, found, leftover := trie.findSubtree(prefix)
+ if !found {
+ return nil
+ }
+ prefix = append(prefix, leftover...)
+
+ // Visit it.
+ return root.walk(prefix, visitor)
+}
+
+// VisitPrefixes visits only nodes that represent prefixes of key.
+// To say the obvious, returning SkipSubtree from visitor makes no sense here.
+func (trie *Trie) VisitPrefixes(key Prefix, visitor VisitorFunc) error {
+ // Nil key not allowed.
+ if key == nil {
+ panic(ErrNilPrefix)
+ }
+
+ // Empty trie must be handled explicitly.
+ if trie.prefix == nil {
+ return nil
+ }
+
+ // Walk the path matching key prefixes.
+ node := trie
+ prefix := key
+ offset := 0
+ for {
+ // Compute what part of prefix matches.
+ common := node.longestCommonPrefixLength(key)
+ key = key[common:]
+ offset += common
+
+ // Partial match means that there is no subtree matching prefix.
+ if common < len(node.prefix) {
+ return nil
+ }
+
+ // Call the visitor.
+ if item := node.item; item != nil {
+ if err := visitor(prefix[:offset], item); err != nil {
+ return err
+ }
+ }
+
+ if len(key) == 0 {
+ // This node represents key, we are finished.
+ return nil
+ }
+
+ // There is some key suffix left, move to the children.
+ child := node.children.next(key[0])
+ if child == nil {
+ // There is nowhere to continue, return.
+ return nil
+ }
+
+ node = child
+ }
+}
+
+// Delete deletes the item represented by the given prefix.
+//
+// True is returned if the matching node was found and deleted.
+func (trie *Trie) Delete(key Prefix) (deleted bool) {
+ // Nil prefix not allowed.
+ if key == nil {
+ panic(ErrNilPrefix)
+ }
+
+ // Empty trie must be handled explicitly.
+ if trie.prefix == nil {
+ return false
+ }
+
+ // Find the relevant node.
+ path, found, _ := trie.findSubtreePath(key)
+ if !found {
+ return false
+ }
+
+ node := path[len(path)-1]
+ var parent *Trie
+ if len(path) != 1 {
+ parent = path[len(path)-2]
+ }
+
+ // If the item is already set to nil, there is nothing to do.
+ if node.item == nil {
+ return false
+ }
+
+ // Delete the item.
+ node.item = nil
+
+ // Initialise i before goto.
+ // Will be used later in a loop.
+ i := len(path) - 1
+
+ // In case there are some child nodes, we cannot drop the whole subtree.
+ // We can try to compact nodes, though.
+ if node.children.length() != 0 {
+ goto Compact
+ }
+
+ // In case we are at the root, just reset it and we are done.
+ if parent == nil {
+ node.reset()
+ return true
+ }
+
+ // We can drop a subtree.
+ // Find the first ancestor that has its value set or it has 2 or more child nodes.
+ // That will be the node where to drop the subtree at.
+ for ; i >= 0; i-- {
+ if current := path[i]; current.item != nil || current.children.length() >= 2 {
+ break
+ }
+ }
+
+ // Handle the case when there is no such node.
+ // In other words, we can reset the whole tree.
+ if i == -1 {
+ path[0].reset()
+ return true
+ }
+
+ // We can just remove the subtree here.
+ node = path[i]
+ if i == 0 {
+ parent = nil
+ } else {
+ parent = path[i-1]
+ }
+ // i+1 is always a valid index since i is never pointing to the last node.
+ // The loop above skips at least the last node since we are sure that the item
+ // is set to nil and it has no children, othewise we would be compacting instead.
+ node.children.remove(path[i+1].prefix[0])
+
+Compact:
+ // The node is set to the first non-empty ancestor,
+ // so try to compact since that might be possible now.
+ if compacted := node.compact(); compacted != node {
+ if parent == nil {
+ *node = *compacted
+ } else {
+ parent.children.replace(node.prefix[0], compacted)
+ *parent = *parent.compact()
+ }
+ }
+
+ return true
+}
+
+// DeleteSubtree finds the subtree exactly matching prefix and deletes it.
+//
+// True is returned if the subtree was found and deleted.
+func (trie *Trie) DeleteSubtree(prefix Prefix) (deleted bool) {
+ // Nil prefix not allowed.
+ if prefix == nil {
+ panic(ErrNilPrefix)
+ }
+
+ // Empty trie must be handled explicitly.
+ if trie.prefix == nil {
+ return false
+ }
+
+ // Locate the relevant subtree.
+ parent, root, found, _ := trie.findSubtree(prefix)
+ if !found {
+ return false
+ }
+
+ // If we are in the root of the trie, reset the trie.
+ if parent == nil {
+ root.reset()
+ return true
+ }
+
+ // Otherwise remove the root node from its parent.
+ parent.children.remove(root.prefix[0])
+ return true
+}
+
+// Internal helper methods -----------------------------------------------------
+
+func (trie *Trie) empty() bool {
+ return trie.item == nil && trie.children.length() == 0
+}
+
+func (trie *Trie) reset() {
+ trie.prefix = nil
+ trie.children = newSparseChildList(trie.maxPrefixPerNode)
+}
+
+func (trie *Trie) put(key Prefix, item Item, replace bool) (inserted bool) {
+ // Nil prefix not allowed.
+ if key == nil {
+ panic(ErrNilPrefix)
+ }
+
+ var (
+ common int
+ node *Trie = trie
+ child *Trie
+ )
+
+ if node.prefix == nil {
+ if len(key) <= trie.maxPrefixPerNode {
+ node.prefix = key
+ goto InsertItem
+ }
+ node.prefix = key[:trie.maxPrefixPerNode]
+ key = key[trie.maxPrefixPerNode:]
+ goto AppendChild
+ }
+
+ for {
+ // Compute the longest common prefix length.
+ common = node.longestCommonPrefixLength(key)
+ key = key[common:]
+
+ // Only a part matches, split.
+ if common < len(node.prefix) {
+ goto SplitPrefix
+ }
+
+ // common == len(node.prefix) since never (common > len(node.prefix))
+ // common == len(former key) <-> 0 == len(key)
+ // -> former key == node.prefix
+ if len(key) == 0 {
+ goto InsertItem
+ }
+
+ // Check children for matching prefix.
+ child = node.children.next(key[0])
+ if child == nil {
+ goto AppendChild
+ }
+ node = child
+ }
+
+SplitPrefix:
+ // Split the prefix if necessary.
+ child = new(Trie)
+ *child = *node
+ *node = *NewTrie()
+ node.prefix = child.prefix[:common]
+ child.prefix = child.prefix[common:]
+ child = child.compact()
+ node.children = node.children.add(child)
+
+AppendChild:
+ // Keep appending children until whole prefix is inserted.
+ // This loop starts with empty node.prefix that needs to be filled.
+ for len(key) != 0 {
+ child := NewTrie()
+ if len(key) <= trie.maxPrefixPerNode {
+ child.prefix = key
+ node.children = node.children.add(child)
+ node = child
+ goto InsertItem
+ } else {
+ child.prefix = key[:trie.maxPrefixPerNode]
+ key = key[trie.maxPrefixPerNode:]
+ node.children = node.children.add(child)
+ node = child
+ }
+ }
+
+InsertItem:
+ // Try to insert the item if possible.
+ if replace || node.item == nil {
+ node.item = item
+ return true
+ }
+ return false
+}
+
+func (trie *Trie) compact() *Trie {
+ // Only a node with a single child can be compacted.
+ if trie.children.length() != 1 {
+ return trie
+ }
+
+ child := trie.children.head()
+
+ // If any item is set, we cannot compact since we want to retain
+ // the ability to do searching by key. This makes compaction less usable,
+ // but that simply cannot be avoided.
+ if trie.item != nil || child.item != nil {
+ return trie
+ }
+
+ // Make sure the combined prefixes fit into a single node.
+ if len(trie.prefix)+len(child.prefix) > trie.maxPrefixPerNode {
+ return trie
+ }
+
+ // Concatenate the prefixes, move the items.
+ child.prefix = append(trie.prefix, child.prefix...)
+ if trie.item != nil {
+ child.item = trie.item
+ }
+
+ return child
+}
+
+func (trie *Trie) findSubtree(prefix Prefix) (parent *Trie, root *Trie, found bool, leftover Prefix) {
+ // Find the subtree matching prefix.
+ root = trie
+ for {
+ // Compute what part of prefix matches.
+ common := root.longestCommonPrefixLength(prefix)
+ prefix = prefix[common:]
+
+ // We used up the whole prefix, subtree found.
+ if len(prefix) == 0 {
+ found = true
+ leftover = root.prefix[common:]
+ return
+ }
+
+ // Partial match means that there is no subtree matching prefix.
+ if common < len(root.prefix) {
+ leftover = root.prefix[common:]
+ return
+ }
+
+ // There is some prefix left, move to the children.
+ child := root.children.next(prefix[0])
+ if child == nil {
+ // There is nowhere to continue, there is no subtree matching prefix.
+ return
+ }
+
+ parent = root
+ root = child
+ }
+}
+
+func (trie *Trie) findSubtreePath(prefix Prefix) (path []*Trie, found bool, leftover Prefix) {
+ // Find the subtree matching prefix.
+ root := trie
+ var subtreePath []*Trie
+ for {
+ // Append the current root to the path.
+ subtreePath = append(subtreePath, root)
+
+ // Compute what part of prefix matches.
+ common := root.longestCommonPrefixLength(prefix)
+ prefix = prefix[common:]
+
+ // We used up the whole prefix, subtree found.
+ if len(prefix) == 0 {
+ path = subtreePath
+ found = true
+ leftover = root.prefix[common:]
+ return
+ }
+
+ // Partial match means that there is no subtree matching prefix.
+ if common < len(root.prefix) {
+ leftover = root.prefix[common:]
+ return
+ }
+
+ // There is some prefix left, move to the children.
+ child := root.children.next(prefix[0])
+ if child == nil {
+ // There is nowhere to continue, there is no subtree matching prefix.
+ return
+ }
+
+ root = child
+ }
+}
+
+func (trie *Trie) walk(actualRootPrefix Prefix, visitor VisitorFunc) error {
+ var prefix Prefix
+ // Allocate a bit more space for prefix at the beginning.
+ if actualRootPrefix == nil {
+ prefix = make(Prefix, 32+len(trie.prefix))
+ copy(prefix, trie.prefix)
+ prefix = prefix[:len(trie.prefix)]
+ } else {
+ prefix = make(Prefix, 32+len(actualRootPrefix))
+ copy(prefix, actualRootPrefix)
+ prefix = prefix[:len(actualRootPrefix)]
+ }
+
+ // Visit the root first. Not that this works for empty trie as well since
+ // in that case item == nil && len(children) == 0.
+ if trie.item != nil {
+ if err := visitor(prefix, trie.item); err != nil {
+ if err == SkipSubtree {
+ return nil
+ }
+ return err
+ }
+ }
+
+ // Then continue to the children.
+ return trie.children.walk(&prefix, visitor)
+}
+
+func (trie *Trie) longestCommonPrefixLength(prefix Prefix) (i int) {
+ for ; i < len(prefix) && i < len(trie.prefix) && prefix[i] == trie.prefix[i]; i++ {
+ }
+ return
+}
+
+func (trie *Trie) dump() string {
+ writer := &bytes.Buffer{}
+ trie.print(writer, 0)
+ return writer.String()
+}
+
+func (trie *Trie) print(writer io.Writer, indent int) {
+ fmt.Fprintf(writer, "%s%s %v\n", strings.Repeat(" ", indent), string(trie.prefix), trie.item)
+ trie.children.print(writer, indent+2)
+}
+
+// Errors ----------------------------------------------------------------------
+
+var (
+ SkipSubtree = errors.New("Skip this subtree")
+ ErrNilPrefix = errors.New("Nil prefix passed into a method call")
+)
diff --git a/vendor/github.com/tinylib/msgp/LICENSE b/vendor/github.com/tinylib/msgp/LICENSE
new file mode 100644
index 0000000..14d6042
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/LICENSE
@@ -0,0 +1,8 @@
+Copyright (c) 2014 Philip Hofer
+Portions Copyright (c) 2009 The Go Authors (license at http://golang.org) where indicated
+
+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/tinylib/msgp/README.md b/vendor/github.com/tinylib/msgp/README.md
new file mode 100644
index 0000000..a7cc849
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/README.md
@@ -0,0 +1,104 @@
+MessagePack Code Generator [![Build Status](https://travis-ci.org/tinylib/msgp.svg?branch=master)](https://travis-ci.org/tinylib/msgp)
+=======
+
+[![forthebadge](http://forthebadge.com/badges/uses-badges.svg)](http://forthebadge.com)
+[![forthebadge](http://forthebadge.com/badges/ages-12.svg)](http://forthebadge.com)
+
+This is a code generation tool and serialization library for [MessagePack](http://msgpack.org). It is targeted at the `go generate` [tool](http://tip.golang.org/cmd/go/#hdr-Generate_Go_files_by_processing_source). You can read more about MessagePack [in the wiki](http://github.com/tinylib/msgp/wiki), or at [msgpack.org](http://msgpack.org).
+
+### Why?
+
+- Use Go as your schema language
+- Speeeeeed (400MB/s on modern hardware)
+- [JSON interop](http://godoc.org/github.com/tinylib/msgp/msgp#CopyToJSON)
+- [User-defined extensions](http://github.com/tinylib/msgp/wiki/Using-Extensions)
+- Type safety
+- Encoding flexibility
+
+### Quickstart
+
+Note: you need at least go 1.3 to compile this package, and at least go 1.4 to use `go generate`.
+
+In a source file, include the following directive:
+
+```go
+//go:generate msgp
+```
+
+The `msgp` command will generate serialization methods for all exported type declarations in the file.
+
+You can [read more about the code generation options here](http://github.com/tinylib/msgp/wiki/Using-the-Code-Generator).
+
+### Use
+
+Field names can be set in much the same way as the `encoding/json` package. For example:
+
+```go
+type Person struct {
+ Name string `msg:"name"`
+ Address string `msg:"address"`
+ Age int `msg:"age"`
+ Hidden string `msg:"-"` // this field is ignored
+ unexported bool // this field is also ignored
+}
+```
+
+By default, the code generator will satisfy `msgp.Sizer`, `msgp.Encodable`, `msgp.Decodable`,
+`msgp.Marshaler`, and `msgp.Unmarshaler`. Carefully-designed applications can use these methods to do
+marshalling/unmarshalling with zero allocations.
+
+While `msgp.Marshaler` and `msgp.Unmarshaler` are quite similar to the standard library's
+`json.Marshaler` and `json.Unmarshaler`, `msgp.Encodable` and `msgp.Decodable` are useful for
+stream serialization. (`*msgp.Writer` and `*msgp.Reader` are essentially protocol-aware versions
+of `*bufio.Writer` and `*bufio.Reader`, respectively.)
+
+### Features
+
+ - Extremely fast generated code
+ - Test and benchmark generation
+ - JSON interoperability (see `msgp.CopyToJSON() and msgp.UnmarshalAsJSON()`)
+ - Support for complex type declarations
+ - Native support for Go's `time.Time`, `complex64`, and `complex128` types
+ - Generation of both `[]byte`-oriented and `io.Reader/io.Writer`-oriented methods
+ - Support for arbitrary type system extensions
+ - [Preprocessor directives](http://github.com/tinylib/msgp/wiki/Preprocessor-Directives)
+
+Consider the following:
+```go
+const Eight = 8
+type MyInt int
+type Data []byte
+
+type Struct struct {
+ Which map[string]*MyInt `msg:"which"`
+ Other Data `msg:"other"`
+ Nums [Eight]float64 `msg:"nums"`
+}
+```
+As long as the declarations of `MyInt` and `Data` are in the same file as `Struct`, the parser will determine that the type information for `MyInt` and `Data` can be passed into the definition of `Struct` before its methods are generated.
+
+#### Extensions
+
+MessagePack supports defining your own types through "extensions," which are just a tuple of
+the data "type" (`int8`) and the raw binary. You [can see a worked example in the wiki.](http://github.com/tinylib/msgp/wiki/Using-Extensions)
+
+### Status
+
+Alpha. I _will_ break stuff. There is an open milestone for Beta stability (targeted for January.) Only the `/msgp` sub-directory will have a stability guarantee.
+
+You can read more about how `msgp` maps MessagePack types onto Go types [in the wiki](http://github.com/tinylib/msgp/wiki).
+
+Here some of the known limitations/restrictions:
+
+ - Identifiers from outside the processed source file are assumed (optimistically) to satisfy the generator's interfaces. If this isn't the case, your code will fail to compile.
+ - Like most serializers, `chan` and `func` fields are ignored, as well as non-exported fields.
+ - Encoding of `interface{}` is limited to built-ins or types that have explicit encoding methods.
+ - _Maps must have `string` keys._ This is intentional (as it preserves JSON interop.) Although non-string map keys are not forbidden by the MessagePack standard, many serializers impose this restriction. (It also means *any* well-formed `struct` can be de-serialized into a `map[string]interface{}`.) The only exception to this rule is that the deserializers will allow you to read map keys encoded as `bin` types, due to the fact that some legacy encodings permitted this. (However, those values will still be cast to Go `string`s, and they will be converted to `str` types when re-encoded. It is the responsibility of the user to ensure that map keys are UTF-8 safe in this case.) The same rules hold true for JSON translation.
+
+If the output compiles, then there's a pretty good chance things are fine. (Plus, we generate tests for you.) *Please, please, please* file an issue if you think the generator is writing broken code.
+
+### Performance
+
+If you like benchmarks, see [here.](https://github.com/alecthomas/go_serialization_benchmarks)
+
+As one might expect, the generated methods that deal with `[]byte` are faster, but the `io.Reader/Writer` methods are generally more memory-efficient for large (> 2KB) objects.
diff --git a/vendor/github.com/tinylib/msgp/msgp/circular.go b/vendor/github.com/tinylib/msgp/msgp/circular.go
new file mode 100644
index 0000000..35583ba
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/circular.go
@@ -0,0 +1,38 @@
+package msgp
+
+import (
+ "testing"
+)
+
+// EndlessReader is an io.Reader
+// that loops over the same data
+// endlessly. It is used for benchmarking.
+type EndlessReader struct {
+ tb *testing.B
+ data []byte
+ offset int
+}
+
+// NewEndlessReader returns a new endless reader
+func NewEndlessReader(b []byte, tb *testing.B) *EndlessReader {
+ return &EndlessReader{tb: tb, data: b, offset: 0}
+}
+
+// Read implements io.Reader. In practice, it
+// always returns (len(p), nil), although it
+// fills the supplied slice while the benchmark
+// timer is stopped.
+func (c *EndlessReader) Read(p []byte) (int, error) {
+ c.tb.StopTimer()
+ var n int
+ l := len(p)
+ m := len(c.data)
+ for n < l {
+ nn := copy(p[n:], c.data[c.offset:])
+ n += nn
+ c.offset += nn
+ c.offset %= m
+ }
+ c.tb.StartTimer()
+ return n, nil
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/defs.go b/vendor/github.com/tinylib/msgp/msgp/defs.go
new file mode 100644
index 0000000..c634eef
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/defs.go
@@ -0,0 +1,142 @@
+// This package is the support library for the msgp code generator (http://github.com/tinylib/msgp).
+//
+// This package defines the utilites used by the msgp code generator for encoding and decoding MessagePack
+// from []byte and io.Reader/io.Writer types. Much of this package is devoted to helping the msgp code
+// generator implement the Marshaler/Unmarshaler and Encodable/Decodable interfaces.
+//
+// This package defines four "families" of functions:
+// - AppendXxxx() appends an object to a []byte in MessagePack encoding.
+// - ReadXxxxBytes() reads an object from a []byte and returns the remaining bytes.
+// - (*Writer).WriteXxxx() writes an object to the buffered *Writer type.
+// - (*Reader).ReadXxxx() reads an object from a buffered *Reader type.
+//
+// Once a type has satisfied the `Encodable` and `Decodable` interfaces,
+// it can be written and read from arbitrary `io.Writer`s and `io.Reader`s using
+// msgp.Encode(io.Writer, msgp.Encodable)
+// and
+// msgp.Decode(io.Reader, msgp.Decodable)
+//
+// There are also methods for converting MessagePack to JSON without
+// an explicit de-serialization step.
+//
+// For additional tips, tricks, and gotchas, please visit
+// the wiki at http://github.com/tinylib/msgp
+package msgp
+
+const last4 = 0x0f
+const first4 = 0xf0
+const last5 = 0x1f
+const first3 = 0xe0
+const last7 = 0x7f
+
+func isfixint(b byte) bool {
+ return b>>7 == 0
+}
+
+func isnfixint(b byte) bool {
+ return b&first3 == mnfixint
+}
+
+func isfixmap(b byte) bool {
+ return b&first4 == mfixmap
+}
+
+func isfixarray(b byte) bool {
+ return b&first4 == mfixarray
+}
+
+func isfixstr(b byte) bool {
+ return b&first3 == mfixstr
+}
+
+func wfixint(u uint8) byte {
+ return u & last7
+}
+
+func rfixint(b byte) uint8 {
+ return b
+}
+
+func wnfixint(i int8) byte {
+ return byte(i) | mnfixint
+}
+
+func rnfixint(b byte) int8 {
+ return int8(b)
+}
+
+func rfixmap(b byte) uint8 {
+ return b & last4
+}
+
+func wfixmap(u uint8) byte {
+ return mfixmap | (u & last4)
+}
+
+func rfixstr(b byte) uint8 {
+ return b & last5
+}
+
+func wfixstr(u uint8) byte {
+ return (u & last5) | mfixstr
+}
+
+func rfixarray(b byte) uint8 {
+ return (b & last4)
+}
+
+func wfixarray(u uint8) byte {
+ return (u & last4) | mfixarray
+}
+
+// These are all the byte
+// prefixes defined by the
+// msgpack standard
+const (
+ // 0XXXXXXX
+ mfixint uint8 = 0x00
+
+ // 111XXXXX
+ mnfixint uint8 = 0xe0
+
+ // 1000XXXX
+ mfixmap uint8 = 0x80
+
+ // 1001XXXX
+ mfixarray uint8 = 0x90
+
+ // 101XXXXX
+ mfixstr uint8 = 0xa0
+
+ mnil uint8 = 0xc0
+ mfalse uint8 = 0xc2
+ mtrue uint8 = 0xc3
+ mbin8 uint8 = 0xc4
+ mbin16 uint8 = 0xc5
+ mbin32 uint8 = 0xc6
+ mext8 uint8 = 0xc7
+ mext16 uint8 = 0xc8
+ mext32 uint8 = 0xc9
+ mfloat32 uint8 = 0xca
+ mfloat64 uint8 = 0xcb
+ muint8 uint8 = 0xcc
+ muint16 uint8 = 0xcd
+ muint32 uint8 = 0xce
+ muint64 uint8 = 0xcf
+ mint8 uint8 = 0xd0
+ mint16 uint8 = 0xd1
+ mint32 uint8 = 0xd2
+ mint64 uint8 = 0xd3
+ mfixext1 uint8 = 0xd4
+ mfixext2 uint8 = 0xd5
+ mfixext4 uint8 = 0xd6
+ mfixext8 uint8 = 0xd7
+ mfixext16 uint8 = 0xd8
+ mstr8 uint8 = 0xd9
+ mstr16 uint8 = 0xda
+ mstr32 uint8 = 0xdb
+ marray16 uint8 = 0xdc
+ marray32 uint8 = 0xdd
+ mmap16 uint8 = 0xde
+ mmap32 uint8 = 0xdf
+)
diff --git a/vendor/github.com/tinylib/msgp/msgp/edit.go b/vendor/github.com/tinylib/msgp/msgp/edit.go
new file mode 100644
index 0000000..41f9298
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/edit.go
@@ -0,0 +1,241 @@
+package msgp
+
+import (
+ "math"
+)
+
+// Locate returns a []byte pointing to the field
+// in a messagepack map with the provided key. (The returned []byte
+// points to a sub-slice of 'raw'; Locate does no allocations.) If the
+// key doesn't exist in the map, a zero-length []byte will be returned.
+func Locate(key string, raw []byte) []byte {
+ s, n := locate(raw, key)
+ return raw[s:n]
+}
+
+// Replace takes a key ("key") in a messagepack map ("raw")
+// and replaces its value with the one provided and returns
+// the new []byte. The returned []byte may point to the same
+// memory as "raw". Replace makes no effort to evaluate the validity
+// of the contents of 'val'. It may use up to the full capacity of 'raw.'
+// Replace returns 'nil' if the field doesn't exist or if the object in 'raw'
+// is not a map.
+func Replace(key string, raw []byte, val []byte) []byte {
+ start, end := locate(raw, key)
+ if start == end {
+ return nil
+ }
+ return replace(raw, start, end, val, true)
+}
+
+// CopyReplace works similarly to Replace except that the returned
+// byte slice does not point to the same memory as 'raw'. CopyReplace
+// returns 'nil' if the field doesn't exist or 'raw' isn't a map.
+func CopyReplace(key string, raw []byte, val []byte) []byte {
+ start, end := locate(raw, key)
+ if start == end {
+ return nil
+ }
+ return replace(raw, start, end, val, false)
+}
+
+// Remove removes a key-value pair from 'raw'. It returns
+// 'raw' unchanged if the key didn't exist.
+func Remove(key string, raw []byte) []byte {
+ start, end := locateKV(raw, key)
+ if start == end {
+ return raw
+ }
+ raw = raw[:start+copy(raw[start:], raw[end:])]
+ return resizeMap(raw, -1)
+}
+
+// HasKey returns whether the map in 'raw' has
+// a field with key 'key'
+func HasKey(key string, raw []byte) bool {
+ sz, bts, err := ReadMapHeaderBytes(raw)
+ if err != nil {
+ return false
+ }
+ var field []byte
+ for i := uint32(0); i < sz; i++ {
+ field, bts, err = ReadStringZC(bts)
+ if err != nil {
+ return false
+ }
+ if UnsafeString(field) == key {
+ return true
+ }
+ }
+ return false
+}
+
+func replace(raw []byte, start int, end int, val []byte, inplace bool) []byte {
+ ll := end - start // length of segment to replace
+ lv := len(val)
+
+ if inplace {
+ extra := lv - ll
+
+ // fastest case: we're doing
+ // a 1:1 replacement
+ if extra == 0 {
+ copy(raw[start:], val)
+ return raw
+
+ } else if extra < 0 {
+ // 'val' smaller than replaced value
+ // copy in place and shift back
+
+ x := copy(raw[start:], val)
+ y := copy(raw[start+x:], raw[end:])
+ return raw[:start+x+y]
+
+ } else if extra < cap(raw)-len(raw) {
+ // 'val' less than (cap-len) extra bytes
+ // copy in place and shift forward
+ raw = raw[0 : len(raw)+extra]
+ // shift end forward
+ copy(raw[end+extra:], raw[end:])
+ copy(raw[start:], val)
+ return raw
+ }
+ }
+
+ // we have to allocate new space
+ out := make([]byte, len(raw)+len(val)-ll)
+ x := copy(out, raw[:start])
+ y := copy(out[x:], val)
+ copy(out[x+y:], raw[end:])
+ return out
+}
+
+// locate does a naive O(n) search for the map key; returns start, end
+// (returns 0,0 on error)
+func locate(raw []byte, key string) (start int, end int) {
+ var (
+ sz uint32
+ bts []byte
+ field []byte
+ err error
+ )
+ sz, bts, err = ReadMapHeaderBytes(raw)
+ if err != nil {
+ return
+ }
+
+ // loop and locate field
+ for i := uint32(0); i < sz; i++ {
+ field, bts, err = ReadStringZC(bts)
+ if err != nil {
+ return 0, 0
+ }
+ if UnsafeString(field) == key {
+ // start location
+ l := len(raw)
+ start = l - len(bts)
+ bts, err = Skip(bts)
+ if err != nil {
+ return 0, 0
+ }
+ end = l - len(bts)
+ return
+ }
+ bts, err = Skip(bts)
+ if err != nil {
+ return 0, 0
+ }
+ }
+ return 0, 0
+}
+
+// locate key AND value
+func locateKV(raw []byte, key string) (start int, end int) {
+ var (
+ sz uint32
+ bts []byte
+ field []byte
+ err error
+ )
+ sz, bts, err = ReadMapHeaderBytes(raw)
+ if err != nil {
+ return 0, 0
+ }
+
+ for i := uint32(0); i < sz; i++ {
+ tmp := len(bts)
+ field, bts, err = ReadStringZC(bts)
+ if err != nil {
+ return 0, 0
+ }
+ if UnsafeString(field) == key {
+ start = len(raw) - tmp
+ bts, err = Skip(bts)
+ if err != nil {
+ return 0, 0
+ }
+ end = len(raw) - len(bts)
+ return
+ }
+ bts, err = Skip(bts)
+ if err != nil {
+ return 0, 0
+ }
+ }
+ return 0, 0
+}
+
+// delta is delta on map size
+func resizeMap(raw []byte, delta int64) []byte {
+ var sz int64
+ switch raw[0] {
+ case mmap16:
+ sz = int64(big.Uint16(raw[1:]))
+ if sz+delta <= math.MaxUint16 {
+ big.PutUint16(raw[1:], uint16(sz+delta))
+ return raw
+ }
+ if cap(raw)-len(raw) >= 2 {
+ raw = raw[0 : len(raw)+2]
+ copy(raw[5:], raw[3:])
+ big.PutUint32(raw[1:], uint32(sz+delta))
+ return raw
+ }
+ n := make([]byte, 0, len(raw)+5)
+ n = AppendMapHeader(n, uint32(sz+delta))
+ return append(n, raw[3:]...)
+
+ case mmap32:
+ sz = int64(big.Uint32(raw[1:]))
+ big.PutUint32(raw[1:], uint32(sz+delta))
+ return raw
+
+ default:
+ sz = int64(rfixmap(raw[0]))
+ if sz+delta < 16 {
+ raw[0] = wfixmap(uint8(sz + delta))
+ return raw
+ } else if sz+delta <= math.MaxUint16 {
+ if cap(raw)-len(raw) >= 2 {
+ raw = raw[0 : len(raw)+2]
+ copy(raw[3:], raw[1:])
+ raw[0] = mmap16
+ big.PutUint16(raw[1:], uint16(sz+delta))
+ return raw
+ }
+ n := make([]byte, 0, len(raw)+5)
+ n = AppendMapHeader(n, uint32(sz+delta))
+ return append(n, raw[1:]...)
+ }
+ if cap(raw)-len(raw) >= 4 {
+ raw = raw[0 : len(raw)+4]
+ copy(raw[5:], raw[1:])
+ raw[0] = mmap32
+ big.PutUint32(raw[1:], uint32(sz+delta))
+ return raw
+ }
+ n := make([]byte, 0, len(raw)+5)
+ n = AppendMapHeader(n, uint32(sz+delta))
+ return append(n, raw[1:]...)
+ }
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/elsize.go b/vendor/github.com/tinylib/msgp/msgp/elsize.go
new file mode 100644
index 0000000..95762e7
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/elsize.go
@@ -0,0 +1,99 @@
+package msgp
+
+// size of every object on the wire,
+// plus type information. gives us
+// constant-time type information
+// for traversing composite objects.
+//
+var sizes = [256]bytespec{
+ mnil: {size: 1, extra: constsize, typ: NilType},
+ mfalse: {size: 1, extra: constsize, typ: BoolType},
+ mtrue: {size: 1, extra: constsize, typ: BoolType},
+ mbin8: {size: 2, extra: extra8, typ: BinType},
+ mbin16: {size: 3, extra: extra16, typ: BinType},
+ mbin32: {size: 5, extra: extra32, typ: BinType},
+ mext8: {size: 3, extra: extra8, typ: ExtensionType},
+ mext16: {size: 4, extra: extra16, typ: ExtensionType},
+ mext32: {size: 6, extra: extra32, typ: ExtensionType},
+ mfloat32: {size: 5, extra: constsize, typ: Float32Type},
+ mfloat64: {size: 9, extra: constsize, typ: Float64Type},
+ muint8: {size: 2, extra: constsize, typ: UintType},
+ muint16: {size: 3, extra: constsize, typ: UintType},
+ muint32: {size: 5, extra: constsize, typ: UintType},
+ muint64: {size: 9, extra: constsize, typ: UintType},
+ mint8: {size: 2, extra: constsize, typ: IntType},
+ mint16: {size: 3, extra: constsize, typ: IntType},
+ mint32: {size: 5, extra: constsize, typ: IntType},
+ mint64: {size: 9, extra: constsize, typ: IntType},
+ mfixext1: {size: 3, extra: constsize, typ: ExtensionType},
+ mfixext2: {size: 4, extra: constsize, typ: ExtensionType},
+ mfixext4: {size: 6, extra: constsize, typ: ExtensionType},
+ mfixext8: {size: 10, extra: constsize, typ: ExtensionType},
+ mfixext16: {size: 18, extra: constsize, typ: ExtensionType},
+ mstr8: {size: 2, extra: extra8, typ: StrType},
+ mstr16: {size: 3, extra: extra16, typ: StrType},
+ mstr32: {size: 5, extra: extra32, typ: StrType},
+ marray16: {size: 3, extra: array16v, typ: ArrayType},
+ marray32: {size: 5, extra: array32v, typ: ArrayType},
+ mmap16: {size: 3, extra: map16v, typ: MapType},
+ mmap32: {size: 5, extra: map32v, typ: MapType},
+}
+
+func init() {
+ // set up fixed fields
+
+ // fixint
+ for i := mfixint; i < 0x80; i++ {
+ sizes[i] = bytespec{size: 1, extra: constsize, typ: IntType}
+ }
+
+ // nfixint
+ for i := uint16(mnfixint); i < 0x100; i++ {
+ sizes[uint8(i)] = bytespec{size: 1, extra: constsize, typ: IntType}
+ }
+
+ // fixstr gets constsize,
+ // since the prefix yields the size
+ for i := mfixstr; i < 0xc0; i++ {
+ sizes[i] = bytespec{size: 1 + rfixstr(i), extra: constsize, typ: StrType}
+ }
+
+ // fixmap
+ for i := mfixmap; i < 0x90; i++ {
+ sizes[i] = bytespec{size: 1, extra: varmode(2 * rfixmap(i)), typ: MapType}
+ }
+
+ // fixarray
+ for i := mfixarray; i < 0xa0; i++ {
+ sizes[i] = bytespec{size: 1, extra: varmode(rfixarray(i)), typ: ArrayType}
+ }
+}
+
+// a valid bytespsec has
+// non-zero 'size' and
+// non-zero 'typ'
+type bytespec struct {
+ size uint8 // prefix size information
+ extra varmode // extra size information
+ typ Type // type
+ _ byte // makes bytespec 4 bytes (yes, this matters)
+}
+
+// size mode
+// if positive, # elements for composites
+type varmode int8
+
+const (
+ constsize varmode = 0 // constant size (size bytes + uint8(varmode) objects)
+ extra8 = -1 // has uint8(p[1]) extra bytes
+ extra16 = -2 // has be16(p[1:]) extra bytes
+ extra32 = -3 // has be32(p[1:]) extra bytes
+ map16v = -4 // use map16
+ map32v = -5 // use map32
+ array16v = -6 // use array16
+ array32v = -7 // use array32
+)
+
+func getType(v byte) Type {
+ return sizes[v].typ
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/errors.go b/vendor/github.com/tinylib/msgp/msgp/errors.go
new file mode 100644
index 0000000..5c24f27
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/errors.go
@@ -0,0 +1,142 @@
+package msgp
+
+import (
+ "fmt"
+ "reflect"
+)
+
+var (
+ // ErrShortBytes is returned when the
+ // slice being decoded is too short to
+ // contain the contents of the message
+ ErrShortBytes error = errShort{}
+
+ // this error is only returned
+ // if we reach code that should
+ // be unreachable
+ fatal error = errFatal{}
+)
+
+// Error is the interface satisfied
+// by all of the errors that originate
+// from this package.
+type Error interface {
+ error
+
+ // Resumable returns whether
+ // or not the error means that
+ // the stream of data is malformed
+ // and the information is unrecoverable.
+ Resumable() bool
+}
+
+type errShort struct{}
+
+func (e errShort) Error() string { return "msgp: too few bytes left to read object" }
+func (e errShort) Resumable() bool { return false }
+
+type errFatal struct{}
+
+func (f errFatal) Error() string { return "msgp: fatal decoding error (unreachable code)" }
+func (f errFatal) Resumable() bool { return false }
+
+// ArrayError is an error returned
+// when decoding a fix-sized array
+// of the wrong size
+type ArrayError struct {
+ Wanted uint32
+ Got uint32
+}
+
+// Error implements the error interface
+func (a ArrayError) Error() string {
+ return fmt.Sprintf("msgp: wanted array of size %d; got %d", a.Wanted, a.Got)
+}
+
+// Resumable is always 'true' for ArrayErrors
+func (a ArrayError) Resumable() bool { return true }
+
+// IntOverflow is returned when a call
+// would downcast an integer to a type
+// with too few bits to hold its value.
+type IntOverflow struct {
+ Value int64 // the value of the integer
+ FailedBitsize int // the bit size that the int64 could not fit into
+}
+
+// Error implements the error interface
+func (i IntOverflow) Error() string {
+ return fmt.Sprintf("msgp: %d overflows int%d", i.Value, i.FailedBitsize)
+}
+
+// Resumable is always 'true' for overflows
+func (i IntOverflow) Resumable() bool { return true }
+
+// UintOverflow is returned when a call
+// would downcast an unsigned integer to a type
+// with too few bits to hold its value
+type UintOverflow struct {
+ Value uint64 // value of the uint
+ FailedBitsize int // the bit size that couldn't fit the value
+}
+
+// Error implements the error interface
+func (u UintOverflow) Error() string {
+ return fmt.Sprintf("msgp: %d overflows uint%d", u.Value, u.FailedBitsize)
+}
+
+// Resumable is always 'true' for overflows
+func (u UintOverflow) Resumable() bool { return true }
+
+// A TypeError is returned when a particular
+// decoding method is unsuitable for decoding
+// a particular MessagePack value.
+type TypeError struct {
+ Method Type // Type expected by method
+ Encoded Type // Type actually encoded
+}
+
+// Error implements the error interface
+func (t TypeError) Error() string {
+ return fmt.Sprintf("msgp: attempted to decode type %q with method for %q", t.Encoded, t.Method)
+}
+
+// Resumable returns 'true' for TypeErrors
+func (t TypeError) Resumable() bool { return true }
+
+// returns either InvalidPrefixError or
+// TypeError depending on whether or not
+// the prefix is recognized
+func badPrefix(want Type, lead byte) error {
+ t := sizes[lead].typ
+ if t == InvalidType {
+ return InvalidPrefixError(lead)
+ }
+ return TypeError{Method: want, Encoded: t}
+}
+
+// InvalidPrefixError is returned when a bad encoding
+// uses a prefix that is not recognized in the MessagePack standard.
+// This kind of error is unrecoverable.
+type InvalidPrefixError byte
+
+// Error implements the error interface
+func (i InvalidPrefixError) Error() string {
+ return fmt.Sprintf("msgp: unrecognized type prefix 0x%x", byte(i))
+}
+
+// Resumable returns 'false' for InvalidPrefixErrors
+func (i InvalidPrefixError) Resumable() bool { return false }
+
+// ErrUnsupportedType is returned
+// when a bad argument is supplied
+// to a function that takes `interface{}`.
+type ErrUnsupportedType struct {
+ T reflect.Type
+}
+
+// Error implements error
+func (e *ErrUnsupportedType) Error() string { return fmt.Sprintf("msgp: type %q not supported", e.T) }
+
+// Resumable returns 'true' for ErrUnsupportedType
+func (e *ErrUnsupportedType) Resumable() bool { return true }
diff --git a/vendor/github.com/tinylib/msgp/msgp/extension.go b/vendor/github.com/tinylib/msgp/msgp/extension.go
new file mode 100644
index 0000000..32a0ada
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/extension.go
@@ -0,0 +1,548 @@
+package msgp
+
+import (
+ "fmt"
+ "math"
+)
+
+const (
+ // Complex64Extension is the extension number used for complex64
+ Complex64Extension = 3
+
+ // Complex128Extension is the extension number used for complex128
+ Complex128Extension = 4
+
+ // TimeExtension is the extension number used for time.Time
+ TimeExtension = 5
+)
+
+// our extensions live here
+var extensionReg = make(map[int8]func() Extension)
+
+// RegisterExtension registers extensions so that they
+// can be initialized and returned by methods that
+// decode `interface{}` values. This should only
+// be called during initialization. f() should return
+// a newly-initialized zero value of the extension. Keep in
+// mind that extensions 3, 4, and 5 are reserved for
+// complex64, complex128, and time.Time, respectively,
+// and that MessagePack reserves extension types from -127 to -1.
+//
+// For example, if you wanted to register a user-defined struct:
+//
+// msgp.RegisterExtension(10, func() msgp.Extension { &MyExtension{} })
+//
+// RegisterExtension will panic if you call it multiple times
+// with the same 'typ' argument, or if you use a reserved
+// type (3, 4, or 5).
+func RegisterExtension(typ int8, f func() Extension) {
+ switch typ {
+ case Complex64Extension, Complex128Extension, TimeExtension:
+ panic(fmt.Sprint("msgp: forbidden extension type:", typ))
+ }
+ if _, ok := extensionReg[typ]; ok {
+ panic(fmt.Sprint("msgp: RegisterExtension() called with typ", typ, "more than once"))
+ }
+ extensionReg[typ] = f
+}
+
+// ExtensionTypeError is an error type returned
+// when there is a mis-match between an extension type
+// and the type encoded on the wire
+type ExtensionTypeError struct {
+ Got int8
+ Want int8
+}
+
+// Error implements the error interface
+func (e ExtensionTypeError) Error() string {
+ return fmt.Sprintf("msgp: error decoding extension: wanted type %d; got type %d", e.Want, e.Got)
+}
+
+// Resumable returns 'true' for ExtensionTypeErrors
+func (e ExtensionTypeError) Resumable() bool { return true }
+
+func errExt(got int8, wanted int8) error {
+ return ExtensionTypeError{Got: got, Want: wanted}
+}
+
+// Extension is the interface fulfilled
+// by types that want to define their
+// own binary encoding.
+type Extension interface {
+ // ExtensionType should return
+ // a int8 that identifies the concrete
+ // type of the extension. (Types <0 are
+ // officially reserved by the MessagePack
+ // specifications.)
+ ExtensionType() int8
+
+ // Len should return the length
+ // of the data to be encoded
+ Len() int
+
+ // MarshalBinaryTo should copy
+ // the data into the supplied slice,
+ // assuming that the slice has length Len()
+ MarshalBinaryTo([]byte) error
+
+ UnmarshalBinary([]byte) error
+}
+
+// RawExtension implements the Extension interface
+type RawExtension struct {
+ Data []byte
+ Type int8
+}
+
+// ExtensionType implements Extension.ExtensionType, and returns r.Type
+func (r *RawExtension) ExtensionType() int8 { return r.Type }
+
+// Len implements Extension.Len, and returns len(r.Data)
+func (r *RawExtension) Len() int { return len(r.Data) }
+
+// MarshalBinaryTo implements Extension.MarshalBinaryTo,
+// and returns a copy of r.Data
+func (r *RawExtension) MarshalBinaryTo(d []byte) error {
+ copy(d, r.Data)
+ return nil
+}
+
+// UnmarshalBinary implements Extension.UnmarshalBinary,
+// and sets r.Data to the contents of the provided slice
+func (r *RawExtension) UnmarshalBinary(b []byte) error {
+ if cap(r.Data) >= len(b) {
+ r.Data = r.Data[0:len(b)]
+ } else {
+ r.Data = make([]byte, len(b))
+ }
+ copy(r.Data, b)
+ return nil
+}
+
+// WriteExtension writes an extension type to the writer
+func (mw *Writer) WriteExtension(e Extension) error {
+ l := e.Len()
+ var err error
+ switch l {
+ case 0:
+ o, err := mw.require(3)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mext8
+ mw.buf[o+1] = 0
+ mw.buf[o+2] = byte(e.ExtensionType())
+ case 1:
+ o, err := mw.require(2)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mfixext1
+ mw.buf[o+1] = byte(e.ExtensionType())
+ case 2:
+ o, err := mw.require(2)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mfixext2
+ mw.buf[o+1] = byte(e.ExtensionType())
+ case 4:
+ o, err := mw.require(2)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mfixext4
+ mw.buf[o+1] = byte(e.ExtensionType())
+ case 8:
+ o, err := mw.require(2)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mfixext8
+ mw.buf[o+1] = byte(e.ExtensionType())
+ case 16:
+ o, err := mw.require(2)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mfixext16
+ mw.buf[o+1] = byte(e.ExtensionType())
+ default:
+ switch {
+ case l < math.MaxUint8:
+ o, err := mw.require(3)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mext8
+ mw.buf[o+1] = byte(uint8(l))
+ mw.buf[o+2] = byte(e.ExtensionType())
+ case l < math.MaxUint16:
+ o, err := mw.require(4)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mext16
+ big.PutUint16(mw.buf[o+1:], uint16(l))
+ mw.buf[o+3] = byte(e.ExtensionType())
+ default:
+ o, err := mw.require(6)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mext32
+ big.PutUint32(mw.buf[o+1:], uint32(l))
+ mw.buf[o+5] = byte(e.ExtensionType())
+ }
+ }
+ // we can only write directly to the
+ // buffer if we're sure that it
+ // fits the object
+ if l <= mw.bufsize() {
+ o, err := mw.require(l)
+ if err != nil {
+ return err
+ }
+ return e.MarshalBinaryTo(mw.buf[o:])
+ }
+ // here we create a new buffer
+ // just large enough for the body
+ // and save it as the write buffer
+ err = mw.flush()
+ if err != nil {
+ return err
+ }
+ buf := make([]byte, l)
+ err = e.MarshalBinaryTo(buf)
+ if err != nil {
+ return err
+ }
+ mw.buf = buf
+ mw.wloc = l
+ return nil
+}
+
+// peek at the extension type, assuming the next
+// kind to be read is Extension
+func (m *Reader) peekExtensionType() (int8, error) {
+ p, err := m.r.Peek(2)
+ if err != nil {
+ return 0, err
+ }
+ spec := sizes[p[0]]
+ if spec.typ != ExtensionType {
+ return 0, badPrefix(ExtensionType, p[0])
+ }
+ if spec.extra == constsize {
+ return int8(p[1]), nil
+ }
+ size := spec.size
+ p, err = m.r.Peek(int(size))
+ if err != nil {
+ return 0, err
+ }
+ return int8(p[size-1]), nil
+}
+
+// peekExtension peeks at the extension encoding type
+// (must guarantee at least 1 byte in 'b')
+func peekExtension(b []byte) (int8, error) {
+ spec := sizes[b[0]]
+ size := spec.size
+ if spec.typ != ExtensionType {
+ return 0, badPrefix(ExtensionType, b[0])
+ }
+ if len(b) < int(size) {
+ return 0, ErrShortBytes
+ }
+ // for fixed extensions,
+ // the type information is in
+ // the second byte
+ if spec.extra == constsize {
+ return int8(b[1]), nil
+ }
+ // otherwise, it's in the last
+ // part of the prefix
+ return int8(b[size-1]), nil
+}
+
+// ReadExtension reads the next object from the reader
+// as an extension. ReadExtension will fail if the next
+// object in the stream is not an extension, or if
+// e.Type() is not the same as the wire type.
+func (m *Reader) ReadExtension(e Extension) (err error) {
+ var p []byte
+ p, err = m.r.Peek(2)
+ if err != nil {
+ return
+ }
+ lead := p[0]
+ var read int
+ var off int
+ switch lead {
+ case mfixext1:
+ if int8(p[1]) != e.ExtensionType() {
+ err = errExt(int8(p[1]), e.ExtensionType())
+ return
+ }
+ p, err = m.r.Peek(3)
+ if err != nil {
+ return
+ }
+ err = e.UnmarshalBinary(p[2:])
+ if err == nil {
+ _, err = m.r.Skip(3)
+ }
+ return
+
+ case mfixext2:
+ if int8(p[1]) != e.ExtensionType() {
+ err = errExt(int8(p[1]), e.ExtensionType())
+ return
+ }
+ p, err = m.r.Peek(4)
+ if err != nil {
+ return
+ }
+ err = e.UnmarshalBinary(p[2:])
+ if err == nil {
+ _, err = m.r.Skip(4)
+ }
+ return
+
+ case mfixext4:
+ if int8(p[1]) != e.ExtensionType() {
+ err = errExt(int8(p[1]), e.ExtensionType())
+ return
+ }
+ p, err = m.r.Peek(6)
+ if err != nil {
+ return
+ }
+ err = e.UnmarshalBinary(p[2:])
+ if err == nil {
+ _, err = m.r.Skip(6)
+ }
+ return
+
+ case mfixext8:
+ if int8(p[1]) != e.ExtensionType() {
+ err = errExt(int8(p[1]), e.ExtensionType())
+ return
+ }
+ p, err = m.r.Peek(10)
+ if err != nil {
+ return
+ }
+ err = e.UnmarshalBinary(p[2:])
+ if err == nil {
+ _, err = m.r.Skip(10)
+ }
+ return
+
+ case mfixext16:
+ if int8(p[1]) != e.ExtensionType() {
+ err = errExt(int8(p[1]), e.ExtensionType())
+ return
+ }
+ p, err = m.r.Peek(18)
+ if err != nil {
+ return
+ }
+ err = e.UnmarshalBinary(p[2:])
+ if err == nil {
+ _, err = m.r.Skip(18)
+ }
+ return
+
+ case mext8:
+ p, err = m.r.Peek(3)
+ if err != nil {
+ return
+ }
+ if int8(p[2]) != e.ExtensionType() {
+ err = errExt(int8(p[2]), e.ExtensionType())
+ return
+ }
+ read = int(uint8(p[1]))
+ off = 3
+
+ case mext16:
+ p, err = m.r.Peek(4)
+ if err != nil {
+ return
+ }
+ if int8(p[3]) != e.ExtensionType() {
+ err = errExt(int8(p[3]), e.ExtensionType())
+ return
+ }
+ read = int(big.Uint16(p[1:]))
+ off = 4
+
+ case mext32:
+ p, err = m.r.Peek(6)
+ if err != nil {
+ return
+ }
+ if int8(p[5]) != e.ExtensionType() {
+ err = errExt(int8(p[5]), e.ExtensionType())
+ return
+ }
+ read = int(big.Uint32(p[1:]))
+ off = 6
+
+ default:
+ err = badPrefix(ExtensionType, lead)
+ return
+ }
+
+ p, err = m.r.Peek(read + off)
+ if err != nil {
+ return
+ }
+ err = e.UnmarshalBinary(p[off:])
+ if err == nil {
+ _, err = m.r.Skip(read + off)
+ }
+ return
+}
+
+// AppendExtension appends a MessagePack extension to the provided slice
+func AppendExtension(b []byte, e Extension) ([]byte, error) {
+ l := e.Len()
+ var o []byte
+ var n int
+ switch l {
+ case 0:
+ o, n = ensure(b, 3)
+ o[n] = mext8
+ o[n+1] = 0
+ o[n+2] = byte(e.ExtensionType())
+ return o[:n+3], nil
+ case 1:
+ o, n = ensure(b, 3)
+ o[n] = mfixext1
+ o[n+1] = byte(e.ExtensionType())
+ n += 2
+ case 2:
+ o, n = ensure(b, 4)
+ o[n] = mfixext2
+ o[n+1] = byte(e.ExtensionType())
+ n += 2
+ case 4:
+ o, n = ensure(b, 6)
+ o[n] = mfixext4
+ o[n+1] = byte(e.ExtensionType())
+ n += 2
+ case 8:
+ o, n = ensure(b, 10)
+ o[n] = mfixext8
+ o[n+1] = byte(e.ExtensionType())
+ n += 2
+ case 16:
+ o, n = ensure(b, 18)
+ o[n] = mfixext16
+ o[n+1] = byte(e.ExtensionType())
+ n += 2
+ }
+ switch {
+ case l < math.MaxUint8:
+ o, n = ensure(b, l+3)
+ o[n] = mext8
+ o[n+1] = byte(uint8(l))
+ o[n+2] = byte(e.ExtensionType())
+ n += 3
+ case l < math.MaxUint16:
+ o, n = ensure(b, l+4)
+ o[n] = mext16
+ big.PutUint16(o[n+1:], uint16(l))
+ o[n+3] = byte(e.ExtensionType())
+ n += 4
+ default:
+ o, n = ensure(b, l+6)
+ o[n] = mext32
+ big.PutUint32(o[n+1:], uint32(l))
+ o[n+5] = byte(e.ExtensionType())
+ n += 6
+ }
+ return o, e.MarshalBinaryTo(o[n:])
+}
+
+// ReadExtensionBytes reads an extension from 'b' into 'e'
+// and returns any remaining bytes.
+// Possible errors:
+// - ErrShortBytes ('b' not long enough)
+// - ExtensionTypeErorr{} (wire type not the same as e.Type())
+// - TypeErorr{} (next object not an extension)
+// - InvalidPrefixError
+// - An umarshal error returned from e.UnmarshalBinary
+func ReadExtensionBytes(b []byte, e Extension) ([]byte, error) {
+ l := len(b)
+ if l < 3 {
+ return b, ErrShortBytes
+ }
+ lead := b[0]
+ var (
+ sz int // size of 'data'
+ off int // offset of 'data'
+ typ int8
+ )
+ switch lead {
+ case mfixext1:
+ typ = int8(b[1])
+ sz = 1
+ off = 2
+ case mfixext2:
+ typ = int8(b[1])
+ sz = 2
+ off = 2
+ case mfixext4:
+ typ = int8(b[1])
+ sz = 4
+ off = 2
+ case mfixext8:
+ typ = int8(b[1])
+ sz = 8
+ off = 2
+ case mfixext16:
+ typ = int8(b[1])
+ sz = 16
+ off = 2
+ case mext8:
+ sz = int(uint8(b[1]))
+ typ = int8(b[2])
+ off = 3
+ if sz == 0 {
+ return b[3:], e.UnmarshalBinary(b[3:3])
+ }
+ case mext16:
+ if l < 4 {
+ return b, ErrShortBytes
+ }
+ sz = int(big.Uint16(b[1:]))
+ typ = int8(b[3])
+ off = 4
+ case mext32:
+ if l < 6 {
+ return b, ErrShortBytes
+ }
+ sz = int(big.Uint32(b[1:]))
+ typ = int8(b[5])
+ off = 6
+ default:
+ return b, badPrefix(ExtensionType, lead)
+ }
+
+ if typ != e.ExtensionType() {
+ return b, errExt(typ, e.ExtensionType())
+ }
+
+ // the data of the extension starts
+ // at 'off' and is 'sz' bytes long
+ if len(b[off:]) < sz {
+ return b, ErrShortBytes
+ }
+ tot := off + sz
+ return b[tot:], e.UnmarshalBinary(b[off:tot])
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/integers.go b/vendor/github.com/tinylib/msgp/msgp/integers.go
new file mode 100644
index 0000000..f817d77
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/integers.go
@@ -0,0 +1,174 @@
+package msgp
+
+/* ----------------------------------
+ integer encoding utilities
+ (inline-able)
+
+ TODO(tinylib): there are faster,
+ albeit non-portable solutions
+ to the code below. implement
+ byteswap?
+ ---------------------------------- */
+
+func putMint64(b []byte, i int64) {
+ b[0] = mint64
+ b[1] = byte(i >> 56)
+ b[2] = byte(i >> 48)
+ b[3] = byte(i >> 40)
+ b[4] = byte(i >> 32)
+ b[5] = byte(i >> 24)
+ b[6] = byte(i >> 16)
+ b[7] = byte(i >> 8)
+ b[8] = byte(i)
+}
+
+func getMint64(b []byte) int64 {
+ return (int64(b[1]) << 56) | (int64(b[2]) << 48) |
+ (int64(b[3]) << 40) | (int64(b[4]) << 32) |
+ (int64(b[5]) << 24) | (int64(b[6]) << 16) |
+ (int64(b[7]) << 8) | (int64(b[8]))
+}
+
+func putMint32(b []byte, i int32) {
+ b[0] = mint32
+ b[1] = byte(i >> 24)
+ b[2] = byte(i >> 16)
+ b[3] = byte(i >> 8)
+ b[4] = byte(i)
+}
+
+func getMint32(b []byte) int32 {
+ return (int32(b[1]) << 24) | (int32(b[2]) << 16) | (int32(b[3]) << 8) | (int32(b[4]))
+}
+
+func putMint16(b []byte, i int16) {
+ b[0] = mint16
+ b[1] = byte(i >> 8)
+ b[2] = byte(i)
+}
+
+func getMint16(b []byte) (i int16) {
+ return (int16(b[1]) << 8) | int16(b[2])
+}
+
+func putMint8(b []byte, i int8) {
+ b[0] = mint8
+ b[1] = byte(i)
+}
+
+func getMint8(b []byte) (i int8) {
+ return int8(b[1])
+}
+
+func putMuint64(b []byte, u uint64) {
+ b[0] = muint64
+ b[1] = byte(u >> 56)
+ b[2] = byte(u >> 48)
+ b[3] = byte(u >> 40)
+ b[4] = byte(u >> 32)
+ b[5] = byte(u >> 24)
+ b[6] = byte(u >> 16)
+ b[7] = byte(u >> 8)
+ b[8] = byte(u)
+}
+
+func getMuint64(b []byte) uint64 {
+ return (uint64(b[1]) << 56) | (uint64(b[2]) << 48) |
+ (uint64(b[3]) << 40) | (uint64(b[4]) << 32) |
+ (uint64(b[5]) << 24) | (uint64(b[6]) << 16) |
+ (uint64(b[7]) << 8) | (uint64(b[8]))
+}
+
+func putMuint32(b []byte, u uint32) {
+ b[0] = muint32
+ b[1] = byte(u >> 24)
+ b[2] = byte(u >> 16)
+ b[3] = byte(u >> 8)
+ b[4] = byte(u)
+}
+
+func getMuint32(b []byte) uint32 {
+ return (uint32(b[1]) << 24) | (uint32(b[2]) << 16) | (uint32(b[3]) << 8) | (uint32(b[4]))
+}
+
+func putMuint16(b []byte, u uint16) {
+ b[0] = muint16
+ b[1] = byte(u >> 8)
+ b[2] = byte(u)
+}
+
+func getMuint16(b []byte) uint16 {
+ return (uint16(b[1]) << 8) | uint16(b[2])
+}
+
+func putMuint8(b []byte, u uint8) {
+ b[0] = muint8
+ b[1] = byte(u)
+}
+
+func getMuint8(b []byte) uint8 {
+ return uint8(b[1])
+}
+
+func getUnix(b []byte) (sec int64, nsec int32) {
+ sec = (int64(b[0]) << 56) | (int64(b[1]) << 48) |
+ (int64(b[2]) << 40) | (int64(b[3]) << 32) |
+ (int64(b[4]) << 24) | (int64(b[5]) << 16) |
+ (int64(b[6]) << 8) | (int64(b[7]))
+
+ nsec = (int32(b[8]) << 24) | (int32(b[9]) << 16) | (int32(b[10]) << 8) | (int32(b[11]))
+ return
+}
+
+func putUnix(b []byte, sec int64, nsec int32) {
+ b[0] = byte(sec >> 56)
+ b[1] = byte(sec >> 48)
+ b[2] = byte(sec >> 40)
+ b[3] = byte(sec >> 32)
+ b[4] = byte(sec >> 24)
+ b[5] = byte(sec >> 16)
+ b[6] = byte(sec >> 8)
+ b[7] = byte(sec)
+ b[8] = byte(nsec >> 24)
+ b[9] = byte(nsec >> 16)
+ b[10] = byte(nsec >> 8)
+ b[11] = byte(nsec)
+}
+
+/* -----------------------------
+ prefix utilities
+ ----------------------------- */
+
+// write prefix and uint8
+func prefixu8(b []byte, pre byte, sz uint8) {
+ b[0] = pre
+ b[1] = byte(sz)
+}
+
+// write prefix and big-endian uint16
+func prefixu16(b []byte, pre byte, sz uint16) {
+ b[0] = pre
+ b[1] = byte(sz >> 8)
+ b[2] = byte(sz)
+}
+
+// write prefix and big-endian uint32
+func prefixu32(b []byte, pre byte, sz uint32) {
+ b[0] = pre
+ b[1] = byte(sz >> 24)
+ b[2] = byte(sz >> 16)
+ b[3] = byte(sz >> 8)
+ b[4] = byte(sz)
+}
+
+func prefixu64(b []byte, pre byte, sz uint64) {
+ b[0] = pre
+ b[1] = byte(sz >> 56)
+ b[2] = byte(sz >> 48)
+ b[3] = byte(sz >> 40)
+ b[4] = byte(sz >> 32)
+ b[5] = byte(sz >> 24)
+ b[6] = byte(sz >> 16)
+ b[7] = byte(sz >> 8)
+ b[8] = byte(sz)
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/json.go b/vendor/github.com/tinylib/msgp/msgp/json.go
new file mode 100644
index 0000000..5c799ff
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/json.go
@@ -0,0 +1,542 @@
+package msgp
+
+import (
+ "bufio"
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "strconv"
+ "unicode/utf8"
+)
+
+var (
+ null = []byte("null")
+ hex = []byte("0123456789abcdef")
+)
+
+var defuns [_maxtype]func(jsWriter, *Reader) (int, error)
+
+// note: there is an initialization loop if
+// this isn't set up during init()
+func init() {
+ // since none of these functions are inline-able,
+ // there is not much of a penalty to the indirect
+ // call. however, this is best expressed as a jump-table...
+ defuns = [_maxtype]func(jsWriter, *Reader) (int, error){
+ StrType: rwString,
+ BinType: rwBytes,
+ MapType: rwMap,
+ ArrayType: rwArray,
+ Float64Type: rwFloat64,
+ Float32Type: rwFloat32,
+ BoolType: rwBool,
+ IntType: rwInt,
+ UintType: rwUint,
+ NilType: rwNil,
+ ExtensionType: rwExtension,
+ Complex64Type: rwExtension,
+ Complex128Type: rwExtension,
+ TimeType: rwTime,
+ }
+}
+
+// this is the interface
+// used to write json
+type jsWriter interface {
+ io.Writer
+ io.ByteWriter
+ WriteString(string) (int, error)
+}
+
+// CopyToJSON reads MessagePack from 'src' and copies it
+// as JSON to 'dst' until EOF.
+func CopyToJSON(dst io.Writer, src io.Reader) (n int64, err error) {
+ r := NewReader(src)
+ n, err = r.WriteToJSON(dst)
+ freeR(r)
+ return
+}
+
+// WriteToJSON translates MessagePack from 'r' and writes it as
+// JSON to 'w' until the underlying reader returns io.EOF. It returns
+// the number of bytes written, and an error if it stopped before EOF.
+func (r *Reader) WriteToJSON(w io.Writer) (n int64, err error) {
+ var j jsWriter
+ var bf *bufio.Writer
+ if jsw, ok := w.(jsWriter); ok {
+ j = jsw
+ } else {
+ bf = bufio.NewWriterSize(w, 512)
+ j = bf
+ }
+ var nn int
+ for err == nil {
+ nn, err = rwNext(j, r)
+ n += int64(nn)
+ }
+ if err != io.EOF {
+ if bf != nil {
+ bf.Flush()
+ }
+ return
+ }
+ err = nil
+ if bf != nil {
+ err = bf.Flush()
+ }
+ return
+}
+
+func rwNext(w jsWriter, src *Reader) (int, error) {
+ t, err := src.NextType()
+ if err != nil {
+ return 0, err
+ }
+ return defuns[t](w, src)
+}
+
+func rwMap(dst jsWriter, src *Reader) (n int, err error) {
+ var comma bool
+ var sz uint32
+ var field []byte
+
+ sz, err = src.ReadMapHeader()
+ if err != nil {
+ return
+ }
+
+ if sz == 0 {
+ return dst.WriteString("{}")
+ }
+
+ err = dst.WriteByte('{')
+ if err != nil {
+ return
+ }
+ n++
+ var nn int
+ for i := uint32(0); i < sz; i++ {
+ if comma {
+ err = dst.WriteByte(',')
+ if err != nil {
+ return
+ }
+ n++
+ }
+
+ field, err = src.ReadMapKeyPtr()
+ if err != nil {
+ return
+ }
+ nn, err = rwquoted(dst, field)
+ n += nn
+ if err != nil {
+ return
+ }
+
+ err = dst.WriteByte(':')
+ if err != nil {
+ return
+ }
+ n++
+ nn, err = rwNext(dst, src)
+ n += nn
+ if err != nil {
+ return
+ }
+ if !comma {
+ comma = true
+ }
+ }
+
+ err = dst.WriteByte('}')
+ if err != nil {
+ return
+ }
+ n++
+ return
+}
+
+func rwArray(dst jsWriter, src *Reader) (n int, err error) {
+ err = dst.WriteByte('[')
+ if err != nil {
+ return
+ }
+ var sz uint32
+ var nn int
+ sz, err = src.ReadArrayHeader()
+ if err != nil {
+ return
+ }
+ comma := false
+ for i := uint32(0); i < sz; i++ {
+ if comma {
+ err = dst.WriteByte(',')
+ if err != nil {
+ return
+ }
+ n++
+ }
+ nn, err = rwNext(dst, src)
+ n += nn
+ if err != nil {
+ return
+ }
+ comma = true
+ }
+
+ err = dst.WriteByte(']')
+ if err != nil {
+ return
+ }
+ n++
+ return
+}
+
+func rwNil(dst jsWriter, src *Reader) (int, error) {
+ err := src.ReadNil()
+ if err != nil {
+ return 0, err
+ }
+ return dst.Write(null)
+}
+
+func rwFloat32(dst jsWriter, src *Reader) (int, error) {
+ f, err := src.ReadFloat32()
+ if err != nil {
+ return 0, err
+ }
+ src.scratch = strconv.AppendFloat(src.scratch[:0], float64(f), 'f', -1, 64)
+ return dst.Write(src.scratch)
+}
+
+func rwFloat64(dst jsWriter, src *Reader) (int, error) {
+ f, err := src.ReadFloat64()
+ if err != nil {
+ return 0, err
+ }
+ src.scratch = strconv.AppendFloat(src.scratch[:0], f, 'f', -1, 32)
+ return dst.Write(src.scratch)
+}
+
+func rwInt(dst jsWriter, src *Reader) (int, error) {
+ i, err := src.ReadInt64()
+ if err != nil {
+ return 0, err
+ }
+ src.scratch = strconv.AppendInt(src.scratch[:0], i, 10)
+ return dst.Write(src.scratch)
+}
+
+func rwUint(dst jsWriter, src *Reader) (int, error) {
+ u, err := src.ReadUint64()
+ if err != nil {
+ return 0, err
+ }
+ src.scratch = strconv.AppendUint(src.scratch[:0], u, 10)
+ return dst.Write(src.scratch)
+}
+
+func rwBool(dst jsWriter, src *Reader) (int, error) {
+ b, err := src.ReadBool()
+ if err != nil {
+ return 0, err
+ }
+ if b {
+ return dst.WriteString("true")
+ }
+ return dst.WriteString("false")
+}
+
+func rwTime(dst jsWriter, src *Reader) (int, error) {
+ t, err := src.ReadTime()
+ if err != nil {
+ return 0, err
+ }
+ bts, err := t.MarshalJSON()
+ if err != nil {
+ return 0, err
+ }
+ return dst.Write(bts)
+}
+
+func rwExtension(dst jsWriter, src *Reader) (n int, err error) {
+ et, err := src.peekExtensionType()
+ if err != nil {
+ return 0, err
+ }
+
+ // registered extensions can override
+ // the JSON encoding
+ if j, ok := extensionReg[et]; ok {
+ var bts []byte
+ e := j()
+ err = src.ReadExtension(e)
+ if err != nil {
+ return
+ }
+ bts, err = json.Marshal(e)
+ if err != nil {
+ return
+ }
+ return dst.Write(bts)
+ }
+
+ e := RawExtension{}
+ e.Type = et
+ err = src.ReadExtension(&e)
+ if err != nil {
+ return
+ }
+
+ var nn int
+ err = dst.WriteByte('{')
+ if err != nil {
+ return
+ }
+ n++
+
+ nn, err = dst.WriteString(`"type:"`)
+ n += nn
+ if err != nil {
+ return
+ }
+
+ src.scratch = strconv.AppendInt(src.scratch[0:0], int64(e.Type), 10)
+ nn, err = dst.Write(src.scratch)
+ n += nn
+ if err != nil {
+ return
+ }
+
+ nn, err = dst.WriteString(`,"data":"`)
+ n += nn
+ if err != nil {
+ return
+ }
+
+ enc := base64.NewEncoder(base64.StdEncoding, dst)
+
+ nn, err = enc.Write(e.Data)
+ n += nn
+ if err != nil {
+ return
+ }
+ err = enc.Close()
+ if err != nil {
+ return
+ }
+ nn, err = dst.WriteString(`"}`)
+ n += nn
+ return
+}
+
+func rwString(dst jsWriter, src *Reader) (n int, err error) {
+ var p []byte
+ p, err = src.r.Peek(1)
+ if err != nil {
+ return
+ }
+ lead := p[0]
+ var read int
+
+ if isfixstr(lead) {
+ read = int(rfixstr(lead))
+ src.r.Skip(1)
+ goto write
+ }
+
+ switch lead {
+ case mstr8:
+ p, err = src.r.Next(2)
+ if err != nil {
+ return
+ }
+ read = int(uint8(p[1]))
+ case mstr16:
+ p, err = src.r.Next(3)
+ if err != nil {
+ return
+ }
+ read = int(big.Uint16(p[1:]))
+ case mstr32:
+ p, err = src.r.Next(5)
+ if err != nil {
+ return
+ }
+ read = int(big.Uint32(p[1:]))
+ default:
+ err = badPrefix(StrType, lead)
+ return
+ }
+write:
+ p, err = src.r.Next(read)
+ if err != nil {
+ return
+ }
+ n, err = rwquoted(dst, p)
+ return
+}
+
+func rwBytes(dst jsWriter, src *Reader) (n int, err error) {
+ var nn int
+ err = dst.WriteByte('"')
+ if err != nil {
+ return
+ }
+ n++
+ src.scratch, err = src.ReadBytes(src.scratch[:0])
+ if err != nil {
+ return
+ }
+ enc := base64.NewEncoder(base64.StdEncoding, dst)
+ nn, err = enc.Write(src.scratch)
+ n += nn
+ if err != nil {
+ return
+ }
+ err = enc.Close()
+ if err != nil {
+ return
+ }
+ err = dst.WriteByte('"')
+ if err != nil {
+ return
+ }
+ n++
+ return
+}
+
+// Below (c) The Go Authors, 2009-2014
+// Subject to the BSD-style license found at http://golang.org
+//
+// see: encoding/json/encode.go:(*encodeState).stringbytes()
+func rwquoted(dst jsWriter, s []byte) (n int, err error) {
+ var nn int
+ err = dst.WriteByte('"')
+ if err != nil {
+ return
+ }
+ n++
+ start := 0
+ for i := 0; i < len(s); {
+ if b := s[i]; b < utf8.RuneSelf {
+ if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
+ i++
+ continue
+ }
+ if start < i {
+ nn, err = dst.Write(s[start:i])
+ n += nn
+ if err != nil {
+ return
+ }
+ }
+ switch b {
+ case '\\', '"':
+ err = dst.WriteByte('\\')
+ if err != nil {
+ return
+ }
+ n++
+ err = dst.WriteByte(b)
+ if err != nil {
+ return
+ }
+ n++
+ case '\n':
+ err = dst.WriteByte('\\')
+ if err != nil {
+ return
+ }
+ n++
+ err = dst.WriteByte('n')
+ if err != nil {
+ return
+ }
+ n++
+ case '\r':
+ err = dst.WriteByte('\\')
+ if err != nil {
+ return
+ }
+ n++
+ err = dst.WriteByte('r')
+ if err != nil {
+ return
+ }
+ n++
+ default:
+ nn, err = dst.WriteString(`\u00`)
+ n += nn
+ if err != nil {
+ return
+ }
+ err = dst.WriteByte(hex[b>>4])
+ if err != nil {
+ return
+ }
+ n++
+ err = dst.WriteByte(hex[b&0xF])
+ if err != nil {
+ return
+ }
+ n++
+ }
+ i++
+ start = i
+ continue
+ }
+ c, size := utf8.DecodeRune(s[i:])
+ if c == utf8.RuneError && size == 1 {
+ if start < i {
+ nn, err = dst.Write(s[start:i])
+ n += nn
+ if err != nil {
+ return
+ }
+ nn, err = dst.WriteString(`\ufffd`)
+ n += nn
+ if err != nil {
+ return
+ }
+ i += size
+ start = i
+ continue
+ }
+ }
+ if c == '\u2028' || c == '\u2029' {
+ if start < i {
+ nn, err = dst.Write(s[start:i])
+ n += nn
+ if err != nil {
+ return
+ }
+ nn, err = dst.WriteString(`\u202`)
+ n += nn
+ if err != nil {
+ return
+ }
+ err = dst.WriteByte(hex[c&0xF])
+ if err != nil {
+ return
+ }
+ n++
+ }
+ }
+ i += size
+ }
+ if start < len(s) {
+ nn, err = dst.Write(s[start:])
+ n += nn
+ if err != nil {
+ return
+ }
+ }
+ err = dst.WriteByte('"')
+ if err != nil {
+ return
+ }
+ n++
+ return
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/json_bytes.go b/vendor/github.com/tinylib/msgp/msgp/json_bytes.go
new file mode 100644
index 0000000..438caf5
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/json_bytes.go
@@ -0,0 +1,363 @@
+package msgp
+
+import (
+ "bufio"
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "strconv"
+ "time"
+)
+
+var unfuns [_maxtype]func(jsWriter, []byte, []byte) ([]byte, []byte, error)
+
+func init() {
+
+ // NOTE(pmh): this is best expressed as a jump table,
+ // but gc doesn't do that yet. revisit post-go1.5.
+ unfuns = [_maxtype]func(jsWriter, []byte, []byte) ([]byte, []byte, error){
+ StrType: rwStringBytes,
+ BinType: rwBytesBytes,
+ MapType: rwMapBytes,
+ ArrayType: rwArrayBytes,
+ Float64Type: rwFloat64Bytes,
+ Float32Type: rwFloat32Bytes,
+ BoolType: rwBoolBytes,
+ IntType: rwIntBytes,
+ UintType: rwUintBytes,
+ NilType: rwNullBytes,
+ ExtensionType: rwExtensionBytes,
+ Complex64Type: rwExtensionBytes,
+ Complex128Type: rwExtensionBytes,
+ TimeType: rwTimeBytes,
+ }
+}
+
+// UnmarshalAsJSON takes raw messagepack and writes
+// it as JSON to 'w'. If an error is returned, the
+// bytes not translated will also be returned. If
+// no errors are encountered, the length of the returned
+// slice will be zero.
+func UnmarshalAsJSON(w io.Writer, msg []byte) ([]byte, error) {
+ var (
+ scratch []byte
+ cast bool
+ dst jsWriter
+ err error
+ )
+ if jsw, ok := w.(jsWriter); ok {
+ dst = jsw
+ cast = true
+ } else {
+ dst = bufio.NewWriterSize(w, 512)
+ }
+ for len(msg) > 0 && err == nil {
+ msg, scratch, err = writeNext(dst, msg, scratch)
+ }
+ if !cast && err == nil {
+ err = dst.(*bufio.Writer).Flush()
+ }
+ return msg, err
+}
+
+func writeNext(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ if len(msg) < 1 {
+ return msg, scratch, ErrShortBytes
+ }
+ t := getType(msg[0])
+ if t == InvalidType {
+ return msg, scratch, InvalidPrefixError(msg[0])
+ }
+ if t == ExtensionType {
+ et, err := peekExtension(msg)
+ if err != nil {
+ return nil, scratch, err
+ }
+ if et == TimeExtension {
+ t = TimeType
+ }
+ }
+ return unfuns[t](w, msg, scratch)
+}
+
+func rwArrayBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ sz, msg, err := ReadArrayHeaderBytes(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ err = w.WriteByte('[')
+ if err != nil {
+ return msg, scratch, err
+ }
+ for i := uint32(0); i < sz; i++ {
+ if i != 0 {
+ err = w.WriteByte(',')
+ if err != nil {
+ return msg, scratch, err
+ }
+ }
+ msg, scratch, err = writeNext(w, msg, scratch)
+ if err != nil {
+ return msg, scratch, err
+ }
+ }
+ err = w.WriteByte(']')
+ return msg, scratch, err
+}
+
+func rwMapBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ sz, msg, err := ReadMapHeaderBytes(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ err = w.WriteByte('{')
+ if err != nil {
+ return msg, scratch, err
+ }
+ for i := uint32(0); i < sz; i++ {
+ if i != 0 {
+ err = w.WriteByte(',')
+ if err != nil {
+ return msg, scratch, err
+ }
+ }
+ msg, scratch, err = rwMapKeyBytes(w, msg, scratch)
+ if err != nil {
+ return msg, scratch, err
+ }
+ err = w.WriteByte(':')
+ if err != nil {
+ return msg, scratch, err
+ }
+ msg, scratch, err = writeNext(w, msg, scratch)
+ if err != nil {
+ return msg, scratch, err
+ }
+ }
+ err = w.WriteByte('}')
+ return msg, scratch, err
+}
+
+func rwMapKeyBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ msg, scratch, err := rwStringBytes(w, msg, scratch)
+ if err != nil {
+ if tperr, ok := err.(TypeError); ok && tperr.Encoded == BinType {
+ return rwBytesBytes(w, msg, scratch)
+ }
+ }
+ return msg, scratch, err
+}
+
+func rwStringBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ str, msg, err := ReadStringZC(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ _, err = rwquoted(w, str)
+ return msg, scratch, err
+}
+
+func rwBytesBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ bts, msg, err := ReadBytesZC(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ l := base64.StdEncoding.EncodedLen(len(bts))
+ if cap(scratch) >= l {
+ scratch = scratch[0:l]
+ } else {
+ scratch = make([]byte, l)
+ }
+ base64.StdEncoding.Encode(scratch, bts)
+ err = w.WriteByte('"')
+ if err != nil {
+ return msg, scratch, err
+ }
+ _, err = w.Write(scratch)
+ if err != nil {
+ return msg, scratch, err
+ }
+ err = w.WriteByte('"')
+ return msg, scratch, err
+}
+
+func rwNullBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ msg, err := ReadNilBytes(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ _, err = w.Write(null)
+ return msg, scratch, err
+}
+
+func rwBoolBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ b, msg, err := ReadBoolBytes(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ if b {
+ _, err = w.WriteString("true")
+ return msg, scratch, err
+ }
+ _, err = w.WriteString("false")
+ return msg, scratch, err
+}
+
+func rwIntBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ i, msg, err := ReadInt64Bytes(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ scratch = strconv.AppendInt(scratch[0:0], i, 10)
+ _, err = w.Write(scratch)
+ return msg, scratch, err
+}
+
+func rwUintBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ u, msg, err := ReadUint64Bytes(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ scratch = strconv.AppendUint(scratch[0:0], u, 10)
+ _, err = w.Write(scratch)
+ return msg, scratch, err
+}
+
+func rwFloatBytes(w jsWriter, msg []byte, f64 bool, scratch []byte) ([]byte, []byte, error) {
+ var f float64
+ var err error
+ var sz int
+ if f64 {
+ sz = 64
+ f, msg, err = ReadFloat64Bytes(msg)
+ } else {
+ sz = 32
+ var v float32
+ v, msg, err = ReadFloat32Bytes(msg)
+ f = float64(v)
+ }
+ if err != nil {
+ return msg, scratch, err
+ }
+ scratch = strconv.AppendFloat(scratch, f, 'f', -1, sz)
+ _, err = w.Write(scratch)
+ return msg, scratch, err
+}
+
+func rwFloat32Bytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ var f float32
+ var err error
+ f, msg, err = ReadFloat32Bytes(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ scratch = strconv.AppendFloat(scratch[:0], float64(f), 'f', -1, 32)
+ _, err = w.Write(scratch)
+ return msg, scratch, err
+}
+
+func rwFloat64Bytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ var f float64
+ var err error
+ f, msg, err = ReadFloat64Bytes(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ scratch = strconv.AppendFloat(scratch[:0], f, 'f', -1, 64)
+ _, err = w.Write(scratch)
+ return msg, scratch, err
+}
+
+func rwTimeBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ var t time.Time
+ var err error
+ t, msg, err = ReadTimeBytes(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ bts, err := t.MarshalJSON()
+ if err != nil {
+ return msg, scratch, err
+ }
+ _, err = w.Write(bts)
+ return msg, scratch, err
+}
+
+func rwExtensionBytes(w jsWriter, msg []byte, scratch []byte) ([]byte, []byte, error) {
+ var err error
+ var et int8
+ et, err = peekExtension(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+
+ // if it's time.Time
+ if et == TimeExtension {
+ var tm time.Time
+ tm, msg, err = ReadTimeBytes(msg)
+ if err != nil {
+ return msg, scratch, err
+ }
+ bts, err := tm.MarshalJSON()
+ if err != nil {
+ return msg, scratch, err
+ }
+ _, err = w.Write(bts)
+ return msg, scratch, err
+ }
+
+ // if the extension is registered,
+ // use its canonical JSON form
+ if f, ok := extensionReg[et]; ok {
+ e := f()
+ msg, err = ReadExtensionBytes(msg, e)
+ if err != nil {
+ return msg, scratch, err
+ }
+ bts, err := json.Marshal(e)
+ if err != nil {
+ return msg, scratch, err
+ }
+ _, err = w.Write(bts)
+ return msg, scratch, err
+ }
+
+ // otherwise, write `{"type": <num>, "data": "<base64data>"}`
+ r := RawExtension{}
+ r.Type = et
+ msg, err = ReadExtensionBytes(msg, &r)
+ if err != nil {
+ return msg, scratch, err
+ }
+ scratch, err = writeExt(w, r, scratch)
+ return msg, scratch, err
+}
+
+func writeExt(w jsWriter, r RawExtension, scratch []byte) ([]byte, error) {
+ _, err := w.WriteString(`{"type":`)
+ if err != nil {
+ return scratch, err
+ }
+ scratch = strconv.AppendInt(scratch[0:0], int64(r.Type), 10)
+ _, err = w.Write(scratch)
+ if err != nil {
+ return scratch, err
+ }
+ _, err = w.WriteString(`,"data":"`)
+ if err != nil {
+ return scratch, err
+ }
+ l := base64.StdEncoding.EncodedLen(len(r.Data))
+ if cap(scratch) >= l {
+ scratch = scratch[0:l]
+ } else {
+ scratch = make([]byte, l)
+ }
+ base64.StdEncoding.Encode(scratch, r.Data)
+ _, err = w.Write(scratch)
+ if err != nil {
+ return scratch, err
+ }
+ _, err = w.WriteString(`"}`)
+ return scratch, err
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/number.go b/vendor/github.com/tinylib/msgp/msgp/number.go
new file mode 100644
index 0000000..69afc8a
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/number.go
@@ -0,0 +1,140 @@
+package msgp
+
+import (
+ "strconv"
+)
+
+// The portable parts of the Number implementation
+
+// DecodeMsg implements msgp.Decodable
+func (n *Number) DecodeMsg(r *Reader) error {
+ typ, err := r.NextType()
+ if err != nil {
+ return err
+ }
+ switch typ {
+ case Float32Type:
+ f, err := r.ReadFloat32()
+ if err != nil {
+ return err
+ }
+ n.AsFloat32(f)
+ return nil
+ case Float64Type:
+ f, err := r.ReadFloat64()
+ if err != nil {
+ return err
+ }
+ n.AsFloat64(f)
+ return nil
+ case IntType:
+ i, err := r.ReadInt64()
+ if err != nil {
+ return err
+ }
+ n.AsInt(i)
+ return nil
+ case UintType:
+ u, err := r.ReadUint64()
+ if err != nil {
+ return err
+ }
+ n.AsUint(u)
+ return nil
+ default:
+ return TypeError{Encoded: typ, Method: IntType}
+ }
+}
+
+// UnmarshalMsg implements msgp.Unmarshaler
+func (n *Number) UnmarshalMsg(b []byte) ([]byte, error) {
+ typ := NextType(b)
+ switch typ {
+ case IntType:
+ i, o, err := ReadInt64Bytes(b)
+ if err != nil {
+ return b, err
+ }
+ n.AsInt(i)
+ return o, nil
+ case UintType:
+ u, o, err := ReadUint64Bytes(b)
+ if err != nil {
+ return b, err
+ }
+ n.AsUint(u)
+ return o, nil
+ case Float64Type:
+ f, o, err := ReadFloat64Bytes(b)
+ if err != nil {
+ return b, err
+ }
+ n.AsFloat64(f)
+ return o, nil
+ case Float32Type:
+ f, o, err := ReadFloat32Bytes(b)
+ if err != nil {
+ return b, err
+ }
+ n.AsFloat32(f)
+ return o, nil
+ default:
+ return b, TypeError{Method: IntType, Encoded: typ}
+ }
+}
+
+// Msgsize implements msgp.Sizer
+func (n *Number) Msgsize() int {
+ switch n.typ {
+ case Float32Type:
+ return Float32Size
+ case Float64Type:
+ return Float64Size
+ case IntType:
+ return Int64Size
+ case UintType:
+ return Uint64Size
+ default:
+ return 1 // fixint(0)
+ }
+}
+
+// MarshalJSON implements json.Marshaler
+func (n *Number) MarshalJSON() ([]byte, error) {
+ t := n.Type()
+ if t == InvalidType {
+ return []byte{'0'}, nil
+ }
+ out := make([]byte, 0, 32)
+ switch t {
+ case Float32Type, Float64Type:
+ f, _ := n.Float()
+ return strconv.AppendFloat(out, f, 'f', -1, 64), nil
+ case IntType:
+ i, _ := n.Int()
+ return strconv.AppendInt(out, i, 10), nil
+ case UintType:
+ u, _ := n.Uint()
+ return strconv.AppendUint(out, u, 10), nil
+ default:
+ panic("(*Number).typ is invalid")
+ }
+}
+
+func (n *Number) String() string {
+ switch n.typ {
+ case InvalidType:
+ return "0"
+ case Float32Type, Float64Type:
+ f, _ := n.Float()
+ return strconv.FormatFloat(f, 'f', -1, 64)
+ case IntType:
+ i, _ := n.Int()
+ return strconv.FormatInt(i, 10)
+ case UintType:
+ u, _ := n.Uint()
+ return strconv.FormatUint(u, 10)
+ default:
+ panic("(*Number).typ is invalid")
+ }
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/number_appengine.go b/vendor/github.com/tinylib/msgp/msgp/number_appengine.go
new file mode 100644
index 0000000..c94140d
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/number_appengine.go
@@ -0,0 +1,101 @@
+// +build appengine
+
+package msgp
+
+// let's just assume appengine
+// uses 64-bit hardware...
+const smallint = false
+
+func UnsafeString(b []byte) string {
+ return string(b)
+}
+
+func UnsafeBytes(s string) []byte {
+ return []byte(s)
+}
+
+type Number struct {
+ ibits uint64 // zero or bits
+ fbits float64 // zero or bits
+ typ Type // zero or type
+}
+
+func (n *Number) AsFloat64(f float64) {
+ n.typ = Float64Type
+ n.fbits = f
+ n.ibits = 0
+}
+
+func (n *Number) AsFloat32(f float32) {
+ n.typ = Float32Type
+ n.fbits = float64(f)
+ n.ibits = 0
+}
+
+func (n *Number) AsInt(i int64) {
+ n.fbits = 0
+ if i == 0 {
+ n.typ = InvalidType
+ n.ibits = 0
+ return
+ }
+ n.ibits = uint64(i)
+ n.typ = IntType
+}
+
+func (n *Number) AsUint(u uint64) {
+ n.ibits = u
+ n.fbits = 0
+ n.typ = UintType
+}
+
+func (n *Number) Float() (float64, bool) {
+ return n.fbits, n.typ == Float64Type || n.typ == Float32Type
+}
+
+func (n *Number) Int() (int64, bool) {
+ return int64(n.ibits), n.typ == IntType
+}
+
+func (n *Number) Uint() (uint64, bool) {
+ return n.ibits, n.typ == UintType
+}
+
+func (n *Number) Type() Type {
+ if n.typ == InvalidType {
+ return IntType
+ }
+ return n.typ
+}
+
+func (n *Number) MarshalMsg(o []byte) ([]byte, error) {
+ switch n.typ {
+ case InvalidType:
+ return AppendInt64(o, 0), nil
+ case IntType:
+ return AppendInt64(o, int64(n.ibits)), nil
+ case UintType:
+ return AppendUint64(o, n.ibits), nil
+ case Float32Type:
+ return AppendFloat32(o, float32(n.fbits)), nil
+ case Float64Type:
+ return AppendFloat64(o, n.fbits), nil
+ }
+ panic("unreachable code!")
+}
+
+func (n *Number) EncodeMsg(w *Writer) error {
+ switch n.typ {
+ case InvalidType:
+ return w.WriteInt64(0)
+ case IntType:
+ return w.WriteInt64(int64(n.ibits))
+ case UintType:
+ return w.WriteUint64(n.ibits)
+ case Float32Type:
+ return w.WriteFloat32(float32(n.fbits))
+ case Float64Type:
+ return w.WriteFloat64(n.fbits)
+ }
+ panic("unreachable code!")
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/number_unsafe.go b/vendor/github.com/tinylib/msgp/msgp/number_unsafe.go
new file mode 100644
index 0000000..8ea0462
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/number_unsafe.go
@@ -0,0 +1,159 @@
+// +build !appengine
+
+package msgp
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+const (
+ // spec says int and uint are always
+ // the same size, but that int/uint
+ // size may not be machine word size
+ smallint = unsafe.Sizeof(int(0)) == 4
+)
+
+// UnsafeString returns the byte slice as a volatile string
+// THIS SHOULD ONLY BE USED BY THE CODE GENERATOR.
+// THIS IS EVIL CODE.
+// YOU HAVE BEEN WARNED.
+func UnsafeString(b []byte) string {
+ return *(*string)(unsafe.Pointer(&reflect.StringHeader{Data: uintptr(unsafe.Pointer(&b[0])), Len: len(b)}))
+}
+
+// UnsafeBytes returns the string as a byte slice
+// THIS SHOULD ONLY BE USED BY THE CODE GENERATOR.
+// THIS IS EVIL CODE.
+// YOU HAVE BEEN WARNED.
+func UnsafeBytes(s string) []byte {
+ return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
+ Len: len(s),
+ Cap: len(s),
+ Data: (*(*reflect.StringHeader)(unsafe.Pointer(&s))).Data,
+ }))
+}
+
+// Number can be
+// an int64, uint64, float32,
+// or float64 internally.
+// It can decode itself
+// from any of the native
+// messagepack number types.
+// The zero-value of Number
+// is Int(0). Using the equality
+// operator with Number compares
+// both the type and the value
+// of the number.
+type Number struct {
+ // internally, this
+ // is just a tagged union.
+ // the raw bits of the number
+ // are stored the same way regardless.
+ bits uint64
+ typ Type
+}
+
+// AsFloat64 sets the number to
+// a float64.
+func (n *Number) AsFloat64(f float64) {
+ n.typ = Float64Type
+ n.bits = *(*uint64)(unsafe.Pointer(&f))
+}
+
+// AsInt sets the number to an int64.
+func (n *Number) AsInt(i int64) {
+
+ // we always store int(0)
+ // as {0, InvalidType} in
+ // order to preserve
+ // the behavior of the == operator
+ if i == 0 {
+ n.typ = InvalidType
+ n.bits = 0
+ return
+ }
+
+ n.typ = IntType
+ n.bits = uint64(i)
+}
+
+// AsUint sets the number to a uint64.
+func (n *Number) AsUint(u uint64) {
+ n.typ = UintType
+ n.bits = u
+}
+
+// AsFloat32 sets the number to a float32.
+func (n *Number) AsFloat32(f float32) {
+ n.typ = Float32Type
+ g := float64(f)
+ n.bits = *(*uint64)(unsafe.Pointer(&g))
+}
+
+// Type will return one of:
+// Float64Type, Float32Type, UintType, or IntType.
+func (n *Number) Type() Type {
+ if n.typ == InvalidType {
+ return IntType
+ }
+ return n.typ
+}
+
+// Float casts the number of the float,
+// and returns whether or not that was
+// the underlying type. (This is legal
+// for both float32 and float64 types.)
+func (n *Number) Float() (float64, bool) {
+ return *(*float64)(unsafe.Pointer(&n.bits)), n.typ == Float64Type || n.typ == Float32Type
+}
+
+// Int casts the number as an int64, and
+// returns whether or not that was the
+// underlying type.
+func (n *Number) Int() (int64, bool) {
+ return int64(n.bits), n.typ == IntType || n.typ == InvalidType
+}
+
+// Uint casts the number as a uint64, and returns
+// whether or not that was the underlying type.
+func (n *Number) Uint() (uint64, bool) {
+ return n.bits, n.typ == UintType
+}
+
+// EncodeMsg implements msgp.Encodable
+func (n *Number) EncodeMsg(w *Writer) error {
+ switch n.typ {
+ case InvalidType:
+ return w.WriteInt(0)
+ case IntType:
+ return w.WriteInt64(int64(n.bits))
+ case UintType:
+ return w.WriteUint64(n.bits)
+ case Float64Type:
+ return w.WriteFloat64(*(*float64)(unsafe.Pointer(&n.bits)))
+ case Float32Type:
+ return w.WriteFloat32(float32(*(*float64)(unsafe.Pointer(&n.bits))))
+ default:
+ // this should never ever happen
+ panic("(*Number).typ is invalid")
+ }
+}
+
+// MarshalMsg implements msgp.Marshaler
+func (n *Number) MarshalMsg(b []byte) ([]byte, error) {
+ switch n.typ {
+ case InvalidType:
+ return AppendInt(b, 0), nil
+ case IntType:
+ return AppendInt64(b, int64(n.bits)), nil
+ case UintType:
+ return AppendUint64(b, n.bits), nil
+ case Float64Type:
+ return AppendFloat64(b, *(*float64)(unsafe.Pointer(&n.bits))), nil
+ case Float32Type:
+ return AppendFloat32(b, float32(*(*float64)(unsafe.Pointer(&n.bits)))), nil
+ default:
+ panic("(*Number).typ is invalid")
+ }
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/read.go b/vendor/github.com/tinylib/msgp/msgp/read.go
new file mode 100644
index 0000000..c34482e
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/read.go
@@ -0,0 +1,1118 @@
+package msgp
+
+import (
+ "github.com/philhofer/fwd"
+ "io"
+ "math"
+ "sync"
+ "time"
+)
+
+// where we keep old *Readers
+var readerPool = sync.Pool{New: func() interface{} { return &Reader{} }}
+
+// Type is a MessagePack wire type,
+// including this package's built-in
+// extension types.
+type Type byte
+
+// MessagePack Types
+//
+// The zero value of Type
+// is InvalidType.
+const (
+ InvalidType Type = iota
+
+ // MessagePack built-in types
+
+ StrType
+ BinType
+ MapType
+ ArrayType
+ Float64Type
+ Float32Type
+ BoolType
+ IntType
+ UintType
+ NilType
+ ExtensionType
+
+ // pseudo-types provided
+ // by extensions
+
+ Complex64Type
+ Complex128Type
+ TimeType
+
+ _maxtype
+)
+
+// String implements fmt.Stringer
+func (t Type) String() string {
+ switch t {
+ case StrType:
+ return "str"
+ case BinType:
+ return "bin"
+ case MapType:
+ return "map"
+ case ArrayType:
+ return "array"
+ case Float64Type:
+ return "float64"
+ case Float32Type:
+ return "float32"
+ case BoolType:
+ return "bool"
+ case UintType:
+ return "uint"
+ case IntType:
+ return "int"
+ case ExtensionType:
+ return "ext"
+ case NilType:
+ return "nil"
+ default:
+ return "<invalid>"
+ }
+}
+
+func freeR(m *Reader) {
+ readerPool.Put(m)
+}
+
+// Unmarshaler is the interface fulfilled
+// by objects that know how to unmarshal
+// themselves from MessagePack.
+// UnmarshalMsg unmarshals the object
+// from binary, returing any leftover
+// bytes and any errors encountered.
+type Unmarshaler interface {
+ UnmarshalMsg([]byte) ([]byte, error)
+}
+
+// Decodable is the interface fulfilled
+// by objects that know how to read
+// themselves from a *Reader.
+type Decodable interface {
+ DecodeMsg(*Reader) error
+}
+
+// Decode decodes 'd' from 'r'.
+func Decode(r io.Reader, d Decodable) error {
+ rd := NewReader(r)
+ err := d.DecodeMsg(rd)
+ freeR(rd)
+ return err
+}
+
+// NewReader returns a *Reader that
+// reads from the provided reader. The
+// reader will be buffered.
+func NewReader(r io.Reader) *Reader {
+ p := readerPool.Get().(*Reader)
+ if p.r == nil {
+ p.r = fwd.NewReader(r)
+ } else {
+ p.r.Reset(r)
+ }
+ return p
+}
+
+// NewReaderSize returns a *Reader with a buffer of the given size.
+// (This is vastly preferable to passing the decoder a reader that is already buffered.)
+func NewReaderSize(r io.Reader, sz int) *Reader {
+ return &Reader{r: fwd.NewReaderSize(r, sz)}
+}
+
+// Reader wraps an io.Reader and provides
+// methods to read MessagePack-encoded values
+// from it. Readers are buffered.
+type Reader struct {
+ r *fwd.Reader
+ scratch []byte
+}
+
+// Read implements `io.Reader`
+func (m *Reader) Read(p []byte) (int, error) {
+ return m.r.Read(p)
+}
+
+// ReadFull implements `io.ReadFull`
+func (m *Reader) ReadFull(p []byte) (int, error) {
+ return m.r.ReadFull(p)
+}
+
+// Reset resets the underlying reader.
+func (m *Reader) Reset(r io.Reader) { m.r.Reset(r) }
+
+// Buffered returns the number of bytes currently in the read buffer.
+func (m *Reader) Buffered() int { return m.r.Buffered() }
+
+// BufferSize returns the capacity of the read buffer.
+func (m *Reader) BufferSize() int { return m.r.BufferSize() }
+
+// NextType returns the next object type to be decoded.
+func (m *Reader) NextType() (Type, error) {
+ p, err := m.r.Peek(1)
+ if err != nil {
+ return InvalidType, err
+ }
+ t := getType(p[0])
+ if t == InvalidType {
+ return t, InvalidPrefixError(p[0])
+ }
+ if t == ExtensionType {
+ v, err := m.peekExtensionType()
+ if err != nil {
+ return InvalidType, err
+ }
+ switch v {
+ case Complex64Extension:
+ return Complex64Type, nil
+ case Complex128Extension:
+ return Complex128Type, nil
+ case TimeExtension:
+ return TimeType, nil
+ }
+ }
+ return t, nil
+}
+
+// IsNil returns whether or not
+// the next byte is a null messagepack byte
+func (m *Reader) IsNil() bool {
+ p, err := m.r.Peek(1)
+ return err == nil && p[0] == mnil
+}
+
+// returns (obj size, obj elements, error)
+// only maps and arrays have non-zero obj elements
+//
+// use uintptr b/c it's guaranteed to be large enough
+// to hold whatever we can fit in memory.
+func getNextSize(r *fwd.Reader) (uintptr, uintptr, error) {
+ b, err := r.Peek(1)
+ if err != nil {
+ return 0, 0, err
+ }
+ lead := b[0]
+ spec := &sizes[lead]
+ size, mode := spec.size, spec.extra
+ if size == 0 {
+ return 0, 0, InvalidPrefixError(lead)
+ }
+ if mode >= 0 {
+ return uintptr(size), uintptr(mode), nil
+ }
+ b, err = r.Peek(int(size))
+ if err != nil {
+ return 0, 0, err
+ }
+ switch mode {
+ case extra8:
+ return uintptr(size) + uintptr(b[1]), 0, nil
+ case extra16:
+ return uintptr(size) + uintptr(big.Uint16(b[1:])), 0, nil
+ case extra32:
+ return uintptr(size) + uintptr(big.Uint32(b[1:])), 0, nil
+ case map16v:
+ return uintptr(size), 2 * uintptr(big.Uint16(b[1:])), nil
+ case map32v:
+ return uintptr(size), 2 * uintptr(big.Uint32(b[1:])), nil
+ case array16v:
+ return uintptr(size), uintptr(big.Uint16(b[1:])), nil
+ case array32v:
+ return uintptr(size), uintptr(big.Uint32(b[1:])), nil
+ default:
+ return 0, 0, fatal
+ }
+}
+
+// Skip skips over the next object, regardless of
+// its type. If it is an array or map, the whole array
+// or map will be skipped.
+func (m *Reader) Skip() error {
+ var (
+ v uintptr // bytes
+ o uintptr // objects
+ err error
+ p []byte
+ )
+
+ // we can use the faster
+ // method if we have enough
+ // buffered data
+ if m.r.Buffered() >= 5 {
+ p, err = m.r.Peek(5)
+ if err != nil {
+ return err
+ }
+ v, o, err = getSize(p)
+ if err != nil {
+ return err
+ }
+ } else {
+ v, o, err = getNextSize(m.r)
+ if err != nil {
+ return err
+ }
+ }
+
+ // 'v' is always non-zero
+ // if err == nil
+ _, err = m.r.Skip(int(v))
+ if err != nil {
+ return err
+ }
+
+ // for maps and slices, skip elements
+ for x := uintptr(0); x < o; x++ {
+ err = m.Skip()
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// ReadMapHeader reads the next object
+// as a map header and returns the size
+// of the map and the number of bytes written.
+// It will return a TypeError{} if the next
+// object is not a map.
+func (m *Reader) ReadMapHeader() (sz uint32, err error) {
+ var p []byte
+ var lead byte
+ p, err = m.r.Peek(1)
+ if err != nil {
+ return
+ }
+ lead = p[0]
+ if isfixmap(lead) {
+ sz = uint32(rfixmap(lead))
+ _, err = m.r.Skip(1)
+ return
+ }
+ switch lead {
+ case mmap16:
+ p, err = m.r.Next(3)
+ if err != nil {
+ return
+ }
+ sz = uint32(big.Uint16(p[1:]))
+ return
+ case mmap32:
+ p, err = m.r.Next(5)
+ if err != nil {
+ return
+ }
+ sz = big.Uint32(p[1:])
+ return
+ default:
+ err = badPrefix(MapType, lead)
+ return
+ }
+}
+
+// ReadMapKey reads either a 'str' or 'bin' field from
+// the reader and returns the value as a []byte. It uses
+// scratch for storage if it is large enough.
+func (m *Reader) ReadMapKey(scratch []byte) ([]byte, error) {
+ out, err := m.ReadStringAsBytes(scratch)
+ if err != nil {
+ if tperr, ok := err.(TypeError); ok && tperr.Encoded == BinType {
+ return m.ReadBytes(scratch)
+ }
+ return nil, err
+ }
+ return out, nil
+}
+
+// MapKeyPtr returns a []byte pointing to the contents
+// of a valid map key. The key cannot be empty, and it
+// must be shorter than the total buffer size of the
+// *Reader. Additionally, the returned slice is only
+// valid until the next *Reader method call. Users
+// should exercise extreme care when using this
+// method; writing into the returned slice may
+// corrupt future reads.
+func (m *Reader) ReadMapKeyPtr() ([]byte, error) {
+ p, err := m.r.Peek(1)
+ if err != nil {
+ return nil, err
+ }
+ lead := p[0]
+ var read int
+ if isfixstr(lead) {
+ read = int(rfixstr(lead))
+ m.r.Skip(1)
+ goto fill
+ }
+ switch lead {
+ case mstr8, mbin8:
+ p, err = m.r.Next(2)
+ if err != nil {
+ return nil, err
+ }
+ read = int(p[1])
+ case mstr16, mbin16:
+ p, err = m.r.Next(3)
+ if err != nil {
+ return nil, err
+ }
+ read = int(big.Uint16(p[1:]))
+ case mstr32, mbin32:
+ p, err = m.r.Next(5)
+ if err != nil {
+ return nil, err
+ }
+ read = int(big.Uint32(p[1:]))
+ default:
+ return nil, badPrefix(StrType, lead)
+ }
+fill:
+ if read == 0 {
+ return nil, ErrShortBytes
+ }
+ return m.r.Next(read)
+}
+
+// ReadArrayHeader reads the next object as an
+// array header and returns the size of the array
+// and the number of bytes read.
+func (m *Reader) ReadArrayHeader() (sz uint32, err error) {
+ var lead byte
+ var p []byte
+ p, err = m.r.Peek(1)
+ if err != nil {
+ return
+ }
+ lead = p[0]
+ if isfixarray(lead) {
+ sz = uint32(rfixarray(lead))
+ _, err = m.r.Skip(1)
+ return
+ }
+ switch lead {
+ case marray16:
+ p, err = m.r.Next(3)
+ if err != nil {
+ return
+ }
+ sz = uint32(big.Uint16(p[1:]))
+ return
+
+ case marray32:
+ p, err = m.r.Next(5)
+ if err != nil {
+ return
+ }
+ sz = big.Uint32(p[1:])
+ return
+
+ default:
+ err = badPrefix(ArrayType, lead)
+ return
+ }
+}
+
+// ReadNil reads a 'nil' MessagePack byte from the reader
+func (m *Reader) ReadNil() error {
+ p, err := m.r.Peek(1)
+ if err != nil {
+ return err
+ }
+ if p[0] != mnil {
+ return badPrefix(NilType, p[0])
+ }
+ _, err = m.r.Skip(1)
+ return err
+}
+
+// ReadFloat64 reads a float64 from the reader.
+// (If the value on the wire is encoded as a float32,
+// it will be up-cast to a float64.)
+func (m *Reader) ReadFloat64() (f float64, err error) {
+ var p []byte
+ p, err = m.r.Peek(9)
+ if err != nil {
+ // we'll allow a coversion from float32 to float64,
+ // since we don't lose any precision
+ if err == io.EOF && len(p) > 0 && p[0] == mfloat32 {
+ ef, err := m.ReadFloat32()
+ return float64(ef), err
+ }
+ return
+ }
+ if p[0] != mfloat64 {
+ // see above
+ if p[0] == mfloat32 {
+ ef, err := m.ReadFloat32()
+ return float64(ef), err
+ }
+ err = badPrefix(Float64Type, p[0])
+ return
+ }
+ f = math.Float64frombits(getMuint64(p))
+ _, err = m.r.Skip(9)
+ return
+}
+
+// ReadFloat32 reads a float32 from the reader
+func (m *Reader) ReadFloat32() (f float32, err error) {
+ var p []byte
+ p, err = m.r.Peek(5)
+ if err != nil {
+ return
+ }
+ if p[0] != mfloat32 {
+ err = badPrefix(Float32Type, p[0])
+ return
+ }
+ f = math.Float32frombits(getMuint32(p))
+ _, err = m.r.Skip(5)
+ return
+}
+
+// ReadBool reads a bool from the reader
+func (m *Reader) ReadBool() (b bool, err error) {
+ var p []byte
+ p, err = m.r.Peek(1)
+ if err != nil {
+ return
+ }
+ switch p[0] {
+ case mtrue:
+ b = true
+ case mfalse:
+ default:
+ err = badPrefix(BoolType, p[0])
+ return
+ }
+ _, err = m.r.Skip(1)
+ return
+}
+
+// ReadInt64 reads an int64 from the reader
+func (m *Reader) ReadInt64() (i int64, err error) {
+ var p []byte
+ var lead byte
+ p, err = m.r.Peek(1)
+ if err != nil {
+ return
+ }
+ lead = p[0]
+
+ if isfixint(lead) {
+ i = int64(rfixint(lead))
+ _, err = m.r.Skip(1)
+ return
+ } else if isnfixint(lead) {
+ i = int64(rnfixint(lead))
+ _, err = m.r.Skip(1)
+ return
+ }
+
+ switch lead {
+ case mint8:
+ p, err = m.r.Next(2)
+ if err != nil {
+ return
+ }
+ i = int64(getMint8(p))
+ return
+
+ case mint16:
+ p, err = m.r.Next(3)
+ if err != nil {
+ return
+ }
+ i = int64(getMint16(p))
+ return
+
+ case mint32:
+ p, err = m.r.Next(5)
+ if err != nil {
+ return
+ }
+ i = int64(getMint32(p))
+ return
+
+ case mint64:
+ p, err = m.r.Next(9)
+ if err != nil {
+ return
+ }
+ i = getMint64(p)
+ return
+
+ default:
+ err = badPrefix(IntType, lead)
+ return
+ }
+}
+
+// ReadInt32 reads an int32 from the reader
+func (m *Reader) ReadInt32() (i int32, err error) {
+ var in int64
+ in, err = m.ReadInt64()
+ if in > math.MaxInt32 || in < math.MinInt32 {
+ err = IntOverflow{Value: in, FailedBitsize: 32}
+ return
+ }
+ i = int32(in)
+ return
+}
+
+// ReadInt16 reads an int16 from the reader
+func (m *Reader) ReadInt16() (i int16, err error) {
+ var in int64
+ in, err = m.ReadInt64()
+ if in > math.MaxInt16 || in < math.MinInt16 {
+ err = IntOverflow{Value: in, FailedBitsize: 16}
+ return
+ }
+ i = int16(in)
+ return
+}
+
+// ReadInt8 reads an int8 from the reader
+func (m *Reader) ReadInt8() (i int8, err error) {
+ var in int64
+ in, err = m.ReadInt64()
+ if in > math.MaxInt8 || in < math.MinInt8 {
+ err = IntOverflow{Value: in, FailedBitsize: 8}
+ return
+ }
+ i = int8(in)
+ return
+}
+
+// ReadInt reads an int from the reader
+func (m *Reader) ReadInt() (i int, err error) {
+ if smallint {
+ var in int32
+ in, err = m.ReadInt32()
+ i = int(in)
+ return
+ }
+ var in int64
+ in, err = m.ReadInt64()
+ i = int(in)
+ return
+}
+
+// ReadUint64 reads a uint64 from the reader
+func (m *Reader) ReadUint64() (u uint64, err error) {
+ var p []byte
+ var lead byte
+ p, err = m.r.Peek(1)
+ if err != nil {
+ return
+ }
+ lead = p[0]
+ if isfixint(lead) {
+ u = uint64(rfixint(lead))
+ _, err = m.r.Skip(1)
+ return
+ }
+ switch lead {
+ case muint8:
+ p, err = m.r.Next(2)
+ if err != nil {
+ return
+ }
+ u = uint64(getMuint8(p))
+ return
+
+ case muint16:
+ p, err = m.r.Next(3)
+ if err != nil {
+ return
+ }
+ u = uint64(getMuint16(p))
+ return
+
+ case muint32:
+ p, err = m.r.Next(5)
+ if err != nil {
+ return
+ }
+ u = uint64(getMuint32(p))
+ return
+
+ case muint64:
+ p, err = m.r.Next(9)
+ if err != nil {
+ return
+ }
+ u = getMuint64(p)
+ return
+
+ default:
+ err = badPrefix(UintType, lead)
+ return
+
+ }
+}
+
+// ReadUint32 reads a uint32 from the reader
+func (m *Reader) ReadUint32() (u uint32, err error) {
+ var in uint64
+ in, err = m.ReadUint64()
+ if in > math.MaxUint32 {
+ err = UintOverflow{Value: in, FailedBitsize: 32}
+ return
+ }
+ u = uint32(in)
+ return
+}
+
+// ReadUint16 reads a uint16 from the reader
+func (m *Reader) ReadUint16() (u uint16, err error) {
+ var in uint64
+ in, err = m.ReadUint64()
+ if in > math.MaxUint16 {
+ err = UintOverflow{Value: in, FailedBitsize: 16}
+ return
+ }
+ u = uint16(in)
+ return
+}
+
+// ReadUint8 reads a uint8 from the reader
+func (m *Reader) ReadUint8() (u uint8, err error) {
+ var in uint64
+ in, err = m.ReadUint64()
+ if in > math.MaxUint8 {
+ err = UintOverflow{Value: in, FailedBitsize: 8}
+ return
+ }
+ u = uint8(in)
+ return
+}
+
+// ReadUint reads a uint from the reader
+func (m *Reader) ReadUint() (u uint, err error) {
+ if smallint {
+ var un uint32
+ un, err = m.ReadUint32()
+ u = uint(un)
+ return
+ }
+ var un uint64
+ un, err = m.ReadUint64()
+ u = uint(un)
+ return
+}
+
+func (m *Reader) ReadByte() (b byte, err error) {
+ var in uint64
+ in, err = m.ReadUint64()
+ if in > math.MaxUint8 {
+ err = UintOverflow{Value: in, FailedBitsize: 8}
+ return
+ }
+ b = byte(in)
+ return
+}
+
+// ReadBytes reads a MessagePack 'bin' object
+// from the reader and returns its value. It may
+// use 'scratch' for storage if it is non-nil.
+func (m *Reader) ReadBytes(scratch []byte) (b []byte, err error) {
+ var p []byte
+ var lead byte
+ p, err = m.r.Peek(2)
+ if err != nil {
+ return
+ }
+ lead = p[0]
+ var read int64
+ switch lead {
+ case mbin8:
+ read = int64(p[1])
+ m.r.Skip(2)
+ case mbin16:
+ p, err = m.r.Next(3)
+ if err != nil {
+ return
+ }
+ read = int64(big.Uint16(p[1:]))
+ case mbin32:
+ p, err = m.r.Next(5)
+ if err != nil {
+ return
+ }
+ read = int64(big.Uint32(p[1:]))
+ default:
+ err = badPrefix(BinType, lead)
+ return
+ }
+ if int64(cap(scratch)) < read {
+ b = make([]byte, read)
+ } else {
+ b = scratch[0:read]
+ }
+ _, err = m.r.ReadFull(b)
+ return
+}
+
+// ReadExactBytes reads a MessagePack 'bin'-encoded
+// object off of the wire into the provided slice. An
+// ArrayError will be returned if the object is not
+// exactly the length of the input slice.
+func (m *Reader) ReadExactBytes(into []byte) error {
+ p, err := m.r.Peek(2)
+ if err != nil {
+ return err
+ }
+ lead := p[0]
+ var read int64 // bytes to read
+ var skip int // prefix size to skip
+ switch lead {
+ case mbin8:
+ read = int64(p[1])
+ skip = 2
+ case mbin16:
+ p, err = m.r.Peek(3)
+ if err != nil {
+ return err
+ }
+ read = int64(big.Uint16(p[1:]))
+ skip = 3
+ case mbin32:
+ p, err = m.r.Peek(5)
+ if err != nil {
+ return err
+ }
+ read = int64(big.Uint32(p[1:]))
+ skip = 5
+ default:
+ return badPrefix(BinType, lead)
+ }
+ if read != int64(len(into)) {
+ return ArrayError{Wanted: uint32(len(into)), Got: uint32(read)}
+ }
+ m.r.Skip(skip)
+ _, err = m.r.ReadFull(into)
+ return err
+}
+
+// ReadStringAsBytes reads a MessagePack 'str' (utf-8) string
+// and returns its value as bytes. It may use 'scratch' for storage
+// if it is non-nil.
+func (m *Reader) ReadStringAsBytes(scratch []byte) (b []byte, err error) {
+ var p []byte
+ var lead byte
+ p, err = m.r.Peek(1)
+ if err != nil {
+ return
+ }
+ lead = p[0]
+ var read int64
+
+ if isfixstr(lead) {
+ read = int64(rfixstr(lead))
+ m.r.Skip(1)
+ goto fill
+ }
+
+ switch lead {
+ case mstr8:
+ p, err = m.r.Next(2)
+ if err != nil {
+ return
+ }
+ read = int64(uint8(p[1]))
+ case mstr16:
+ p, err = m.r.Next(3)
+ if err != nil {
+ return
+ }
+ read = int64(big.Uint16(p[1:]))
+ case mstr32:
+ p, err = m.r.Next(5)
+ if err != nil {
+ return
+ }
+ read = int64(big.Uint32(p[1:]))
+ default:
+ err = badPrefix(StrType, lead)
+ return
+ }
+fill:
+ if int64(cap(scratch)) < read {
+ b = make([]byte, read)
+ } else {
+ b = scratch[0:read]
+ }
+ _, err = m.r.ReadFull(b)
+ return
+}
+
+// ReadString reads a utf-8 string from the reader
+func (m *Reader) ReadString() (s string, err error) {
+ var p []byte
+ var lead byte
+ var read int64
+ p, err = m.r.Peek(1)
+ if err != nil {
+ return
+ }
+ lead = p[0]
+
+ if isfixstr(lead) {
+ read = int64(rfixstr(lead))
+ m.r.Skip(1)
+ goto fill
+ }
+
+ switch lead {
+ case mstr8:
+ p, err = m.r.Next(2)
+ if err != nil {
+ return
+ }
+ read = int64(uint8(p[1]))
+ case mstr16:
+ p, err = m.r.Next(3)
+ if err != nil {
+ return
+ }
+ read = int64(big.Uint16(p[1:]))
+ case mstr32:
+ p, err = m.r.Next(5)
+ if err != nil {
+ return
+ }
+ read = int64(big.Uint32(p[1:]))
+ default:
+ err = badPrefix(StrType, lead)
+ return
+ }
+fill:
+ if read == 0 {
+ s, err = "", nil
+ return
+ }
+ // reading into the memory
+ // that will become the string
+ // itself has vastly superior
+ // worst-case performance, because
+ // the reader buffer doesn't have
+ // to be large enough to hold the string.
+ // the idea here is to make it more
+ // difficult for someone malicious
+ // to cause the system to run out of
+ // memory by sending very large strings.
+ //
+ // NOTE: this works because the argument
+ // passed to (*fwd.Reader).ReadFull escapes
+ // to the heap; its argument may, in turn,
+ // be passed to the underlying reader, and
+ // thus escape analysis *must* conclude that
+ // 'out' escapes.
+ out := make([]byte, read)
+ _, err = m.r.ReadFull(out)
+ if err != nil {
+ return
+ }
+ s = UnsafeString(out)
+ return
+}
+
+// ReadComplex64 reads a complex64 from the reader
+func (m *Reader) ReadComplex64() (f complex64, err error) {
+ var p []byte
+ p, err = m.r.Peek(10)
+ if err != nil {
+ return
+ }
+ if p[0] != mfixext8 {
+ err = badPrefix(Complex64Type, p[0])
+ return
+ }
+ if int8(p[1]) != Complex64Extension {
+ err = errExt(int8(p[1]), Complex64Extension)
+ return
+ }
+ f = complex(math.Float32frombits(big.Uint32(p[2:])),
+ math.Float32frombits(big.Uint32(p[6:])))
+ _, err = m.r.Skip(10)
+ return
+}
+
+// ReadComplex128 reads a complex128 from the reader
+func (m *Reader) ReadComplex128() (f complex128, err error) {
+ var p []byte
+ p, err = m.r.Peek(18)
+ if err != nil {
+ return
+ }
+ if p[0] != mfixext16 {
+ err = badPrefix(Complex128Type, p[0])
+ return
+ }
+ if int8(p[1]) != Complex128Extension {
+ err = errExt(int8(p[1]), Complex128Extension)
+ return
+ }
+ f = complex(math.Float64frombits(big.Uint64(p[2:])),
+ math.Float64frombits(big.Uint64(p[10:])))
+ _, err = m.r.Skip(18)
+ return
+}
+
+// ReadMapStrIntf reads a MessagePack map into a map[string]interface{}.
+// (You must pass a non-nil map into the function.)
+func (m *Reader) ReadMapStrIntf(mp map[string]interface{}) (err error) {
+ var sz uint32
+ sz, err = m.ReadMapHeader()
+ if err != nil {
+ return
+ }
+ for key := range mp {
+ delete(mp, key)
+ }
+ for i := uint32(0); i < sz; i++ {
+ var key string
+ var val interface{}
+ key, err = m.ReadString()
+ if err != nil {
+ return
+ }
+ val, err = m.ReadIntf()
+ if err != nil {
+ return
+ }
+ mp[key] = val
+ }
+ return
+}
+
+// ReadTime reads a time.Time object from the reader.
+// The returned time's location will be set to time.Local.
+func (m *Reader) ReadTime() (t time.Time, err error) {
+ var p []byte
+ p, err = m.r.Peek(15)
+ if err != nil {
+ return
+ }
+ if p[0] != mext8 || p[1] != 12 {
+ err = badPrefix(TimeType, p[0])
+ return
+ }
+ if int8(p[2]) != TimeExtension {
+ err = errExt(int8(p[2]), TimeExtension)
+ return
+ }
+ sec, nsec := getUnix(p[3:])
+ t = time.Unix(sec, int64(nsec)).Local()
+ _, err = m.r.Skip(15)
+ return
+}
+
+// ReadIntf reads out the next object as a raw interface{}.
+// Arrays are decoded as []interface{}, and maps are decoded
+// as map[string]interface{}. Integers are decoded as int64
+// and unsigned integers are decoded as uint64.
+func (m *Reader) ReadIntf() (i interface{}, err error) {
+ var t Type
+ t, err = m.NextType()
+ if err != nil {
+ return
+ }
+ switch t {
+ case BoolType:
+ i, err = m.ReadBool()
+ return
+
+ case IntType:
+ i, err = m.ReadInt64()
+ return
+
+ case UintType:
+ i, err = m.ReadUint64()
+ return
+
+ case BinType:
+ i, err = m.ReadBytes(nil)
+ return
+
+ case StrType:
+ i, err = m.ReadString()
+ return
+
+ case Complex64Type:
+ i, err = m.ReadComplex64()
+ return
+
+ case Complex128Type:
+ i, err = m.ReadComplex128()
+ return
+
+ case TimeType:
+ i, err = m.ReadTime()
+ return
+
+ case ExtensionType:
+ var t int8
+ t, err = m.peekExtensionType()
+ if err != nil {
+ return
+ }
+ f, ok := extensionReg[t]
+ if ok {
+ e := f()
+ err = m.ReadExtension(e)
+ i = e
+ return
+ }
+ var e RawExtension
+ e.Type = t
+ err = m.ReadExtension(&e)
+ i = &e
+ return
+
+ case MapType:
+ mp := make(map[string]interface{})
+ err = m.ReadMapStrIntf(mp)
+ i = mp
+ return
+
+ case NilType:
+ err = m.ReadNil()
+ i = nil
+ return
+
+ case Float32Type:
+ i, err = m.ReadFloat32()
+ return
+
+ case Float64Type:
+ i, err = m.ReadFloat64()
+ return
+
+ case ArrayType:
+ var sz uint32
+ sz, err = m.ReadArrayHeader()
+
+ if err != nil {
+ return
+ }
+ out := make([]interface{}, int(sz))
+ for j := range out {
+ out[j], err = m.ReadIntf()
+ if err != nil {
+ return
+ }
+ }
+ i = out
+ return
+
+ default:
+ return nil, fatal // unreachable
+ }
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/read_bytes.go b/vendor/github.com/tinylib/msgp/msgp/read_bytes.go
new file mode 100644
index 0000000..732fa68
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/read_bytes.go
@@ -0,0 +1,1073 @@
+package msgp
+
+import (
+ "bytes"
+ "encoding/binary"
+ "math"
+ "time"
+)
+
+var big = binary.BigEndian
+
+// NextType returns the type of the next
+// object in the slice. If the length
+// of the input is zero, it returns
+// InvalidType.
+func NextType(b []byte) Type {
+ if len(b) == 0 {
+ return InvalidType
+ }
+ spec := sizes[b[0]]
+ t := spec.typ
+ if t == ExtensionType && len(b) > int(spec.size) {
+ var tp int8
+ if spec.extra == constsize {
+ tp = int8(b[1])
+ } else {
+ tp = int8(b[spec.size-1])
+ }
+ switch tp {
+ case TimeExtension:
+ return TimeType
+ case Complex128Extension:
+ return Complex128Type
+ case Complex64Extension:
+ return Complex64Type
+ default:
+ return ExtensionType
+ }
+ }
+ return t
+}
+
+// IsNil returns true if len(b)>0 and
+// the leading byte is a 'nil' MessagePack
+// byte; false otherwise
+func IsNil(b []byte) bool {
+ if len(b) != 0 && b[0] == mnil {
+ return true
+ }
+ return false
+}
+
+// Raw is raw MessagePack.
+// Raw allows you to read and write
+// data without interpreting its contents.
+type Raw []byte
+
+// MarshalMsg implements msgp.Marshaler.
+// It appends the raw contents of 'raw'
+// to the provided byte slice. If 'raw'
+// is 0 bytes, 'nil' will be appended instead.
+func (r Raw) MarshalMsg(b []byte) ([]byte, error) {
+ i := len(r)
+ if i == 0 {
+ return AppendNil(b), nil
+ }
+ o, l := ensure(b, i)
+ copy(o[l:], []byte(r))
+ return o, nil
+}
+
+// UnmarshalMsg implements msgp.Unmarshaler.
+// It sets the contents of *Raw to be the next
+// object in the provided byte slice.
+func (r *Raw) UnmarshalMsg(b []byte) ([]byte, error) {
+ l := len(b)
+ out, err := Skip(b)
+ if err != nil {
+ return b, err
+ }
+ rlen := l - len(out)
+ if cap(*r) < rlen {
+ *r = make(Raw, rlen)
+ } else {
+ *r = (*r)[0:rlen]
+ }
+ copy(*r, b[:rlen])
+ return out, nil
+}
+
+// EncodeMsg implements msgp.Encodable.
+// It writes the raw bytes to the writer.
+// If r is empty, it writes 'nil' instead.
+func (r Raw) EncodeMsg(w *Writer) error {
+ if len(r) == 0 {
+ return w.WriteNil()
+ }
+ _, err := w.Write([]byte(r))
+ return err
+}
+
+// DecodeMsg implements msgp.Decodable.
+// It sets the value of *Raw to be the
+// next object on the wire.
+func (r *Raw) DecodeMsg(f *Reader) error {
+ *r = (*r)[:0]
+ return appendNext(f, (*[]byte)(r))
+}
+
+// Msgsize implements msgp.Sizer
+func (r Raw) Msgsize() int {
+ l := len(r)
+ if l == 0 {
+ return 1 // for 'nil'
+ }
+ return l
+}
+
+func appendNext(f *Reader, d *[]byte) error {
+ amt, o, err := getNextSize(f.r)
+ if err != nil {
+ return err
+ }
+ var i int
+ *d, i = ensure(*d, int(amt))
+ _, err = f.r.ReadFull((*d)[i:])
+ if err != nil {
+ return err
+ }
+ for o > 0 {
+ err = appendNext(f, d)
+ if err != nil {
+ return err
+ }
+ o--
+ }
+ return nil
+}
+
+// MarshalJSON implements json.Marshaler
+func (r *Raw) MarshalJSON() ([]byte, error) {
+ var buf bytes.Buffer
+ _, err := UnmarshalAsJSON(&buf, []byte(*r))
+ return buf.Bytes(), err
+}
+
+// ReadMapHeaderBytes reads a map header size
+// from 'b' and returns the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a map)
+func ReadMapHeaderBytes(b []byte) (sz uint32, o []byte, err error) {
+ l := len(b)
+ if l < 1 {
+ err = ErrShortBytes
+ return
+ }
+
+ lead := b[0]
+ if isfixmap(lead) {
+ sz = uint32(rfixmap(lead))
+ o = b[1:]
+ return
+ }
+
+ switch lead {
+ case mmap16:
+ if l < 3 {
+ err = ErrShortBytes
+ return
+ }
+ sz = uint32(big.Uint16(b[1:]))
+ o = b[3:]
+ return
+
+ case mmap32:
+ if l < 5 {
+ err = ErrShortBytes
+ return
+ }
+ sz = big.Uint32(b[1:])
+ o = b[5:]
+ return
+
+ default:
+ err = badPrefix(MapType, lead)
+ return
+ }
+}
+
+// ReadMapKeyZC attempts to read a map key
+// from 'b' and returns the key bytes and the remaining bytes
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a str or bin)
+func ReadMapKeyZC(b []byte) ([]byte, []byte, error) {
+ o, b, err := ReadStringZC(b)
+ if err != nil {
+ if tperr, ok := err.(TypeError); ok && tperr.Encoded == BinType {
+ return ReadBytesZC(b)
+ }
+ return nil, b, err
+ }
+ return o, b, nil
+}
+
+// ReadArrayHeaderBytes attempts to read
+// the array header size off of 'b' and return
+// the size and remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not an array)
+func ReadArrayHeaderBytes(b []byte) (sz uint32, o []byte, err error) {
+ if len(b) < 1 {
+ return 0, nil, ErrShortBytes
+ }
+ lead := b[0]
+ if isfixarray(lead) {
+ sz = uint32(rfixarray(lead))
+ o = b[1:]
+ return
+ }
+
+ switch lead {
+ case marray16:
+ if len(b) < 3 {
+ err = ErrShortBytes
+ return
+ }
+ sz = uint32(big.Uint16(b[1:]))
+ o = b[3:]
+ return
+
+ case marray32:
+ if len(b) < 5 {
+ err = ErrShortBytes
+ return
+ }
+ sz = big.Uint32(b[1:])
+ o = b[5:]
+ return
+
+ default:
+ err = badPrefix(ArrayType, lead)
+ return
+ }
+}
+
+// ReadNilBytes tries to read a "nil" byte
+// off of 'b' and return the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a 'nil')
+// - InvalidPrefixError
+func ReadNilBytes(b []byte) ([]byte, error) {
+ if len(b) < 1 {
+ return nil, ErrShortBytes
+ }
+ if b[0] != mnil {
+ return b, badPrefix(NilType, b[0])
+ }
+ return b[1:], nil
+}
+
+// ReadFloat64Bytes tries to read a float64
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a float64)
+func ReadFloat64Bytes(b []byte) (f float64, o []byte, err error) {
+ if len(b) < 9 {
+ if len(b) >= 5 && b[0] == mfloat32 {
+ var tf float32
+ tf, o, err = ReadFloat32Bytes(b)
+ f = float64(tf)
+ return
+ }
+ err = ErrShortBytes
+ return
+ }
+
+ if b[0] != mfloat64 {
+ if b[0] == mfloat32 {
+ var tf float32
+ tf, o, err = ReadFloat32Bytes(b)
+ f = float64(tf)
+ return
+ }
+ err = badPrefix(Float64Type, b[0])
+ return
+ }
+
+ f = math.Float64frombits(getMuint64(b))
+ o = b[9:]
+ return
+}
+
+// ReadFloat32Bytes tries to read a float64
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a float32)
+func ReadFloat32Bytes(b []byte) (f float32, o []byte, err error) {
+ if len(b) < 5 {
+ err = ErrShortBytes
+ return
+ }
+
+ if b[0] != mfloat32 {
+ err = TypeError{Method: Float32Type, Encoded: getType(b[0])}
+ return
+ }
+
+ f = math.Float32frombits(getMuint32(b))
+ o = b[5:]
+ return
+}
+
+// ReadBoolBytes tries to read a float64
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a bool)
+func ReadBoolBytes(b []byte) (bool, []byte, error) {
+ if len(b) < 1 {
+ return false, b, ErrShortBytes
+ }
+ switch b[0] {
+ case mtrue:
+ return true, b[1:], nil
+ case mfalse:
+ return false, b[1:], nil
+ default:
+ return false, b, badPrefix(BoolType, b[0])
+ }
+}
+
+// ReadInt64Bytes tries to read an int64
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError (not a int)
+func ReadInt64Bytes(b []byte) (i int64, o []byte, err error) {
+ l := len(b)
+ if l < 1 {
+ return 0, nil, ErrShortBytes
+ }
+
+ lead := b[0]
+ if isfixint(lead) {
+ i = int64(rfixint(lead))
+ o = b[1:]
+ return
+ }
+ if isnfixint(lead) {
+ i = int64(rnfixint(lead))
+ o = b[1:]
+ return
+ }
+
+ switch lead {
+ case mint8:
+ if l < 2 {
+ err = ErrShortBytes
+ return
+ }
+ i = int64(getMint8(b))
+ o = b[2:]
+ return
+
+ case mint16:
+ if l < 3 {
+ err = ErrShortBytes
+ return
+ }
+ i = int64(getMint16(b))
+ o = b[3:]
+ return
+
+ case mint32:
+ if l < 5 {
+ err = ErrShortBytes
+ return
+ }
+ i = int64(getMint32(b))
+ o = b[5:]
+ return
+
+ case mint64:
+ if l < 9 {
+ err = ErrShortBytes
+ return
+ }
+ i = getMint64(b)
+ o = b[9:]
+ return
+
+ default:
+ err = badPrefix(IntType, lead)
+ return
+ }
+}
+
+// ReadInt32Bytes tries to read an int32
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a int)
+// - IntOverflow{} (value doesn't fit in int32)
+func ReadInt32Bytes(b []byte) (int32, []byte, error) {
+ i, o, err := ReadInt64Bytes(b)
+ if i > math.MaxInt32 || i < math.MinInt32 {
+ return 0, o, IntOverflow{Value: i, FailedBitsize: 32}
+ }
+ return int32(i), o, err
+}
+
+// ReadInt16Bytes tries to read an int16
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a int)
+// - IntOverflow{} (value doesn't fit in int16)
+func ReadInt16Bytes(b []byte) (int16, []byte, error) {
+ i, o, err := ReadInt64Bytes(b)
+ if i > math.MaxInt16 || i < math.MinInt16 {
+ return 0, o, IntOverflow{Value: i, FailedBitsize: 16}
+ }
+ return int16(i), o, err
+}
+
+// ReadInt8Bytes tries to read an int16
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a int)
+// - IntOverflow{} (value doesn't fit in int8)
+func ReadInt8Bytes(b []byte) (int8, []byte, error) {
+ i, o, err := ReadInt64Bytes(b)
+ if i > math.MaxInt8 || i < math.MinInt8 {
+ return 0, o, IntOverflow{Value: i, FailedBitsize: 8}
+ }
+ return int8(i), o, err
+}
+
+// ReadIntBytes tries to read an int
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a int)
+// - IntOverflow{} (value doesn't fit in int; 32-bit platforms only)
+func ReadIntBytes(b []byte) (int, []byte, error) {
+ if smallint {
+ i, b, err := ReadInt32Bytes(b)
+ return int(i), b, err
+ }
+ i, b, err := ReadInt64Bytes(b)
+ return int(i), b, err
+}
+
+// ReadUint64Bytes tries to read a uint64
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a uint)
+func ReadUint64Bytes(b []byte) (u uint64, o []byte, err error) {
+ l := len(b)
+ if l < 1 {
+ return 0, nil, ErrShortBytes
+ }
+
+ lead := b[0]
+ if isfixint(lead) {
+ u = uint64(rfixint(lead))
+ o = b[1:]
+ return
+ }
+
+ switch lead {
+ case muint8:
+ if l < 2 {
+ err = ErrShortBytes
+ return
+ }
+ u = uint64(getMuint8(b))
+ o = b[2:]
+ return
+
+ case muint16:
+ if l < 3 {
+ err = ErrShortBytes
+ return
+ }
+ u = uint64(getMuint16(b))
+ o = b[3:]
+ return
+
+ case muint32:
+ if l < 5 {
+ err = ErrShortBytes
+ return
+ }
+ u = uint64(getMuint32(b))
+ o = b[5:]
+ return
+
+ case muint64:
+ if l < 9 {
+ err = ErrShortBytes
+ return
+ }
+ u = getMuint64(b)
+ o = b[9:]
+ return
+
+ default:
+ err = badPrefix(UintType, lead)
+ return
+ }
+}
+
+// ReadUint32Bytes tries to read a uint32
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a uint)
+// - UintOverflow{} (value too large for uint32)
+func ReadUint32Bytes(b []byte) (uint32, []byte, error) {
+ v, o, err := ReadUint64Bytes(b)
+ if v > math.MaxUint32 {
+ return 0, nil, UintOverflow{Value: v, FailedBitsize: 32}
+ }
+ return uint32(v), o, err
+}
+
+// ReadUint16Bytes tries to read a uint16
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a uint)
+// - UintOverflow{} (value too large for uint16)
+func ReadUint16Bytes(b []byte) (uint16, []byte, error) {
+ v, o, err := ReadUint64Bytes(b)
+ if v > math.MaxUint16 {
+ return 0, nil, UintOverflow{Value: v, FailedBitsize: 16}
+ }
+ return uint16(v), o, err
+}
+
+// ReadUint8Bytes tries to read a uint8
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a uint)
+// - UintOverflow{} (value too large for uint8)
+func ReadUint8Bytes(b []byte) (uint8, []byte, error) {
+ v, o, err := ReadUint64Bytes(b)
+ if v > math.MaxUint8 {
+ return 0, nil, UintOverflow{Value: v, FailedBitsize: 8}
+ }
+ return uint8(v), o, err
+}
+
+// ReadUintBytes tries to read a uint
+// from 'b' and return the value and the remaining bytes.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a uint)
+// - UintOverflow{} (value too large for uint; 32-bit platforms only)
+func ReadUintBytes(b []byte) (uint, []byte, error) {
+ if smallint {
+ u, b, err := ReadUint32Bytes(b)
+ return uint(u), b, err
+ }
+ u, b, err := ReadUint64Bytes(b)
+ return uint(u), b, err
+}
+
+// ReadByteBytes is analagous to ReadUint8Bytes
+func ReadByteBytes(b []byte) (byte, []byte, error) {
+ return ReadUint8Bytes(b)
+}
+
+// ReadBytesBytes reads a 'bin' object
+// from 'b' and returns its vaue and
+// the remaining bytes in 'b'.
+// Possible errors:
+// - ErrShortBytes (too few bytes)
+// - TypeError{} (not a 'bin' object)
+func ReadBytesBytes(b []byte, scratch []byte) (v []byte, o []byte, err error) {
+ return readBytesBytes(b, scratch, false)
+}
+
+func readBytesBytes(b []byte, scratch []byte, zc bool) (v []byte, o []byte, err error) {
+ l := len(b)
+ if l < 1 {
+ return nil, nil, ErrShortBytes
+ }
+
+ lead := b[0]
+ var read int
+ switch lead {
+ case mbin8:
+ if l < 2 {
+ err = ErrShortBytes
+ return
+ }
+
+ read = int(b[1])
+ b = b[2:]
+
+ case mbin16:
+ if l < 3 {
+ err = ErrShortBytes
+ return
+ }
+ read = int(big.Uint16(b[1:]))
+ b = b[3:]
+
+ case mbin32:
+ if l < 5 {
+ err = ErrShortBytes
+ return
+ }
+ read = int(big.Uint32(b[1:]))
+ b = b[5:]
+
+ default:
+ err = badPrefix(BinType, lead)
+ return
+ }
+
+ if len(b) < read {
+ err = ErrShortBytes
+ return
+ }
+
+ // zero-copy
+ if zc {
+ v = b[0:read]
+ o = b[read:]
+ return
+ }
+
+ if cap(scratch) >= read {
+ v = scratch[0:read]
+ } else {
+ v = make([]byte, read)
+ }
+
+ o = b[copy(v, b):]
+ return
+}
+
+// ReadBytesZC extracts the messagepack-encoded
+// binary field without copying. The returned []byte
+// points to the same memory as the input slice.
+// Possible errors:
+// - ErrShortBytes (b not long enough)
+// - TypeError{} (object not 'bin')
+func ReadBytesZC(b []byte) (v []byte, o []byte, err error) {
+ return readBytesBytes(b, nil, true)
+}
+
+func ReadExactBytes(b []byte, into []byte) (o []byte, err error) {
+ l := len(b)
+ if l < 1 {
+ err = ErrShortBytes
+ return
+ }
+
+ lead := b[0]
+ var read uint32
+ var skip int
+ switch lead {
+ case mbin8:
+ if l < 2 {
+ err = ErrShortBytes
+ return
+ }
+
+ read = uint32(b[1])
+ skip = 2
+
+ case mbin16:
+ if l < 3 {
+ err = ErrShortBytes
+ return
+ }
+ read = uint32(big.Uint16(b[1:]))
+ skip = 3
+
+ case mbin32:
+ if l < 5 {
+ err = ErrShortBytes
+ return
+ }
+ read = uint32(big.Uint32(b[1:]))
+ skip = 5
+
+ default:
+ err = badPrefix(BinType, lead)
+ return
+ }
+
+ if read != uint32(len(into)) {
+ err = ArrayError{Wanted: uint32(len(into)), Got: read}
+ return
+ }
+
+ o = b[skip+copy(into, b[skip:]):]
+ return
+}
+
+// ReadStringZC reads a messagepack string field
+// without copying. The returned []byte points
+// to the same memory as the input slice.
+// Possible errors:
+// - ErrShortBytes (b not long enough)
+// - TypeError{} (object not 'str')
+func ReadStringZC(b []byte) (v []byte, o []byte, err error) {
+ l := len(b)
+ if l < 1 {
+ return nil, nil, ErrShortBytes
+ }
+
+ lead := b[0]
+ var read int
+
+ if isfixstr(lead) {
+ read = int(rfixstr(lead))
+ b = b[1:]
+ } else {
+ switch lead {
+ case mstr8:
+ if l < 2 {
+ err = ErrShortBytes
+ return
+ }
+ read = int(b[1])
+ b = b[2:]
+
+ case mstr16:
+ if l < 3 {
+ err = ErrShortBytes
+ return
+ }
+ read = int(big.Uint16(b[1:]))
+ b = b[3:]
+
+ case mstr32:
+ if l < 5 {
+ err = ErrShortBytes
+ return
+ }
+ read = int(big.Uint32(b[1:]))
+ b = b[5:]
+
+ default:
+ err = TypeError{Method: StrType, Encoded: getType(lead)}
+ return
+ }
+ }
+
+ if len(b) < read {
+ err = ErrShortBytes
+ return
+ }
+
+ v = b[0:read]
+ o = b[read:]
+ return
+}
+
+// ReadStringBytes reads a 'str' object
+// from 'b' and returns its value and the
+// remaining bytes in 'b'.
+// Possible errors:
+// - ErrShortBytes (b not long enough)
+// - TypeError{} (not 'str' type)
+// - InvalidPrefixError
+func ReadStringBytes(b []byte) (string, []byte, error) {
+ v, o, err := ReadStringZC(b)
+ return string(v), o, err
+}
+
+// ReadComplex128Bytes reads a complex128
+// extension object from 'b' and returns the
+// remaining bytes.
+// Possible errors:
+// - ErrShortBytes (not enough bytes in 'b')
+// - TypeError{} (object not a complex128)
+// - InvalidPrefixError
+// - ExtensionTypeError{} (object an extension of the correct size, but not a complex128)
+func ReadComplex128Bytes(b []byte) (c complex128, o []byte, err error) {
+ if len(b) < 18 {
+ err = ErrShortBytes
+ return
+ }
+ if b[0] != mfixext16 {
+ err = badPrefix(Complex128Type, b[0])
+ return
+ }
+ if int8(b[1]) != Complex128Extension {
+ err = errExt(int8(b[1]), Complex128Extension)
+ return
+ }
+ c = complex(math.Float64frombits(big.Uint64(b[2:])),
+ math.Float64frombits(big.Uint64(b[10:])))
+ o = b[18:]
+ return
+}
+
+// ReadComplex64Bytes reads a complex64
+// extension object from 'b' and returns the
+// remaining bytes.
+// Possible errors:
+// - ErrShortBytes (not enough bytes in 'b')
+// - TypeError{} (object not a complex64)
+// - ExtensionTypeError{} (object an extension of the correct size, but not a complex64)
+func ReadComplex64Bytes(b []byte) (c complex64, o []byte, err error) {
+ if len(b) < 10 {
+ err = ErrShortBytes
+ return
+ }
+ if b[0] != mfixext8 {
+ err = badPrefix(Complex64Type, b[0])
+ return
+ }
+ if b[1] != Complex64Extension {
+ err = errExt(int8(b[1]), Complex64Extension)
+ return
+ }
+ c = complex(math.Float32frombits(big.Uint32(b[2:])),
+ math.Float32frombits(big.Uint32(b[6:])))
+ o = b[10:]
+ return
+}
+
+// ReadTimeBytes reads a time.Time
+// extension object from 'b' and returns the
+// remaining bytes.
+// Possible errors:
+// - ErrShortBytes (not enough bytes in 'b')
+// - TypeError{} (object not a complex64)
+// - ExtensionTypeError{} (object an extension of the correct size, but not a time.Time)
+func ReadTimeBytes(b []byte) (t time.Time, o []byte, err error) {
+ if len(b) < 15 {
+ err = ErrShortBytes
+ return
+ }
+ if b[0] != mext8 || b[1] != 12 {
+ err = badPrefix(TimeType, b[0])
+ return
+ }
+ if int8(b[2]) != TimeExtension {
+ err = errExt(int8(b[2]), TimeExtension)
+ return
+ }
+ sec, nsec := getUnix(b[3:])
+ t = time.Unix(sec, int64(nsec)).Local()
+ o = b[15:]
+ return
+}
+
+// ReadMapStrIntfBytes reads a map[string]interface{}
+// out of 'b' and returns the map and remaining bytes.
+// If 'old' is non-nil, the values will be read into that map.
+func ReadMapStrIntfBytes(b []byte, old map[string]interface{}) (v map[string]interface{}, o []byte, err error) {
+ var sz uint32
+ o = b
+ sz, o, err = ReadMapHeaderBytes(o)
+
+ if err != nil {
+ return
+ }
+
+ if old != nil {
+ for key := range old {
+ delete(old, key)
+ }
+ v = old
+ } else {
+ v = make(map[string]interface{}, int(sz))
+ }
+
+ for z := uint32(0); z < sz; z++ {
+ if len(o) < 1 {
+ err = ErrShortBytes
+ return
+ }
+ var key []byte
+ key, o, err = ReadMapKeyZC(o)
+ if err != nil {
+ return
+ }
+ var val interface{}
+ val, o, err = ReadIntfBytes(o)
+ if err != nil {
+ return
+ }
+ v[string(key)] = val
+ }
+ return
+}
+
+// ReadIntfBytes attempts to read
+// the next object out of 'b' as a raw interface{} and
+// return the remaining bytes.
+func ReadIntfBytes(b []byte) (i interface{}, o []byte, err error) {
+ if len(b) < 1 {
+ err = ErrShortBytes
+ return
+ }
+
+ k := NextType(b)
+
+ switch k {
+ case MapType:
+ i, o, err = ReadMapStrIntfBytes(b, nil)
+ return
+
+ case ArrayType:
+ var sz uint32
+ sz, b, err = ReadArrayHeaderBytes(b)
+ if err != nil {
+ return
+ }
+ j := make([]interface{}, int(sz))
+ i = j
+ for d := range j {
+ j[d], b, err = ReadIntfBytes(b)
+ if err != nil {
+ return
+ }
+ }
+ return
+
+ case Float32Type:
+ i, o, err = ReadFloat32Bytes(b)
+ return
+
+ case Float64Type:
+ i, o, err = ReadFloat64Bytes(b)
+ return
+
+ case IntType:
+ i, o, err = ReadInt64Bytes(b)
+ return
+
+ case UintType:
+ i, o, err = ReadUint64Bytes(b)
+ return
+
+ case BoolType:
+ i, o, err = ReadBoolBytes(b)
+ return
+
+ case TimeType:
+ i, o, err = ReadTimeBytes(b)
+ return
+
+ case Complex64Type:
+ i, o, err = ReadComplex64Bytes(b)
+ return
+
+ case Complex128Type:
+ i, o, err = ReadComplex128Bytes(b)
+ return
+
+ case ExtensionType:
+ var t int8
+ t, err = peekExtension(b)
+ if err != nil {
+ return
+ }
+ // use a user-defined extension,
+ // if it's been registered
+ f, ok := extensionReg[t]
+ if ok {
+ e := f()
+ o, err = ReadExtensionBytes(b, e)
+ i = e
+ return
+ }
+ // last resort is a raw extension
+ e := RawExtension{}
+ e.Type = int8(t)
+ o, err = ReadExtensionBytes(b, &e)
+ i = &e
+ return
+
+ case NilType:
+ o, err = ReadNilBytes(b)
+ return
+
+ case BinType:
+ i, o, err = ReadBytesBytes(b, nil)
+ return
+
+ case StrType:
+ i, o, err = ReadStringBytes(b)
+ return
+
+ default:
+ err = InvalidPrefixError(b[0])
+ return
+ }
+}
+
+// Skip skips the next object in 'b' and
+// returns the remaining bytes. If the object
+// is a map or array, all of its elements
+// will be skipped.
+// Possible Errors:
+// - ErrShortBytes (not enough bytes in b)
+// - InvalidPrefixError (bad encoding)
+func Skip(b []byte) ([]byte, error) {
+ sz, asz, err := getSize(b)
+ if err != nil {
+ return b, err
+ }
+ if uintptr(len(b)) < sz {
+ return b, ErrShortBytes
+ }
+ b = b[sz:]
+ for asz > 0 {
+ b, err = Skip(b)
+ if err != nil {
+ return b, err
+ }
+ asz--
+ }
+ return b, nil
+}
+
+// returns (skip N bytes, skip M objects, error)
+func getSize(b []byte) (uintptr, uintptr, error) {
+ l := len(b)
+ if l == 0 {
+ return 0, 0, ErrShortBytes
+ }
+ lead := b[0]
+ spec := &sizes[lead] // get type information
+ size, mode := spec.size, spec.extra
+ if size == 0 {
+ return 0, 0, InvalidPrefixError(lead)
+ }
+ if mode >= 0 { // fixed composites
+ return uintptr(size), uintptr(mode), nil
+ }
+ if l < int(size) {
+ return 0, 0, ErrShortBytes
+ }
+ switch mode {
+ case extra8:
+ return uintptr(size) + uintptr(b[1]), 0, nil
+ case extra16:
+ return uintptr(size) + uintptr(big.Uint16(b[1:])), 0, nil
+ case extra32:
+ return uintptr(size) + uintptr(big.Uint32(b[1:])), 0, nil
+ case map16v:
+ return uintptr(size), 2 * uintptr(big.Uint16(b[1:])), nil
+ case map32v:
+ return uintptr(size), 2 * uintptr(big.Uint32(b[1:])), nil
+ case array16v:
+ return uintptr(size), uintptr(big.Uint16(b[1:])), nil
+ case array32v:
+ return uintptr(size), uintptr(big.Uint32(b[1:])), nil
+ default:
+ return 0, 0, fatal
+ }
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/size.go b/vendor/github.com/tinylib/msgp/msgp/size.go
new file mode 100644
index 0000000..ce2f8b1
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/size.go
@@ -0,0 +1,38 @@
+package msgp
+
+// The sizes provided
+// are the worst-case
+// encoded sizes for
+// each type. For variable-
+// length types ([]byte, string),
+// the total encoded size is
+// the prefix size plus the
+// length of the object.
+const (
+ Int64Size = 9
+ IntSize = Int64Size
+ UintSize = Int64Size
+ Int8Size = 2
+ Int16Size = 3
+ Int32Size = 5
+ Uint8Size = 2
+ ByteSize = Uint8Size
+ Uint16Size = 3
+ Uint32Size = 5
+ Uint64Size = Int64Size
+ Float64Size = 9
+ Float32Size = 5
+ Complex64Size = 10
+ Complex128Size = 18
+
+ TimeSize = 15
+ BoolSize = 1
+ NilSize = 1
+
+ MapHeaderSize = 5
+ ArrayHeaderSize = 5
+
+ BytesPrefixSize = 5
+ StringPrefixSize = 5
+ ExtensionPrefixSize = 6
+)
diff --git a/vendor/github.com/tinylib/msgp/msgp/write.go b/vendor/github.com/tinylib/msgp/msgp/write.go
new file mode 100644
index 0000000..216697f
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/write.go
@@ -0,0 +1,768 @@
+package msgp
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "reflect"
+ "sync"
+ "time"
+)
+
+func abs(i int64) int64 {
+ if i < 0 {
+ return -i
+ }
+ return i
+}
+
+// Sizer is an interface implemented
+// by types that can estimate their
+// size when MessagePack encoded.
+// This interface is optional, but
+// encoding/marshaling implementations
+// may use this as a way to pre-allocate
+// memory for serialization.
+type Sizer interface {
+ Msgsize() int
+}
+
+var (
+ // Nowhere is an io.Writer to nowhere
+ Nowhere io.Writer = nwhere{}
+
+ btsType = reflect.TypeOf(([]byte)(nil))
+ writerPool = sync.Pool{
+ New: func() interface{} {
+ return &Writer{buf: make([]byte, 2048)}
+ },
+ }
+)
+
+func popWriter(w io.Writer) *Writer {
+ wr := writerPool.Get().(*Writer)
+ wr.Reset(w)
+ return wr
+}
+
+func pushWriter(wr *Writer) {
+ wr.w = nil
+ wr.wloc = 0
+ writerPool.Put(wr)
+}
+
+// freeW frees a writer for use
+// by other processes. It is not necessary
+// to call freeW on a writer. However, maintaining
+// a reference to a *Writer after calling freeW on
+// it will cause undefined behavior.
+func freeW(w *Writer) { pushWriter(w) }
+
+// Require ensures that cap(old)-len(old) >= extra
+func Require(old []byte, extra int) []byte {
+ if cap(old)-len(old) >= extra {
+ return old
+ }
+ if len(old) == 0 {
+ return make([]byte, 0, extra)
+ }
+ n := make([]byte, len(old), cap(old)-len(old)+extra)
+ copy(n, old)
+ return n
+}
+
+// nowhere writer
+type nwhere struct{}
+
+func (n nwhere) Write(p []byte) (int, error) { return len(p), nil }
+
+// Marshaler is the interface implemented
+// by types that know how to marshal themselves
+// as MessagePack. MarshalMsg appends the marshalled
+// form of the object to the provided
+// byte slice, returning the extended
+// slice and any errors encountered.
+type Marshaler interface {
+ MarshalMsg([]byte) ([]byte, error)
+}
+
+// Encodable is the interface implemented
+// by types that know how to write themselves
+// as MessagePack using a *msgp.Writer.
+type Encodable interface {
+ EncodeMsg(*Writer) error
+}
+
+// Writer is a buffered writer
+// that can be used to write
+// MessagePack objects to an io.Writer.
+// You must call *Writer.Flush() in order
+// to flush all of the buffered data
+// to the underlying writer.
+type Writer struct {
+ w io.Writer
+ buf []byte
+ wloc int
+}
+
+// NewWriter returns a new *Writer.
+func NewWriter(w io.Writer) *Writer {
+ if wr, ok := w.(*Writer); ok {
+ return wr
+ }
+ return popWriter(w)
+}
+
+// NewWriterSize returns a writer with a custom buffer size.
+func NewWriterSize(w io.Writer, sz int) *Writer {
+ // we must be able to require() 18
+ // contiguous bytes, so that is the
+ // practical minimum buffer size
+ if sz < 18 {
+ sz = 18
+ }
+
+ return &Writer{
+ w: w,
+ buf: make([]byte, sz),
+ }
+}
+
+// Encode encodes an Encodable to an io.Writer.
+func Encode(w io.Writer, e Encodable) error {
+ wr := NewWriter(w)
+ err := e.EncodeMsg(wr)
+ if err == nil {
+ err = wr.Flush()
+ }
+ freeW(wr)
+ return err
+}
+
+func (mw *Writer) flush() error {
+ if mw.wloc == 0 {
+ return nil
+ }
+ n, err := mw.w.Write(mw.buf[:mw.wloc])
+ if err != nil {
+ if n > 0 {
+ mw.wloc = copy(mw.buf, mw.buf[n:mw.wloc])
+ }
+ return err
+ }
+ mw.wloc = 0
+ return nil
+}
+
+// Flush flushes all of the buffered
+// data to the underlying writer.
+func (mw *Writer) Flush() error { return mw.flush() }
+
+// Buffered returns the number bytes in the write buffer
+func (mw *Writer) Buffered() int { return len(mw.buf) - mw.wloc }
+
+func (mw *Writer) avail() int { return len(mw.buf) - mw.wloc }
+
+func (mw *Writer) bufsize() int { return len(mw.buf) }
+
+// NOTE: this should only be called with
+// a number that is guaranteed to be less than
+// len(mw.buf). typically, it is called with a constant.
+//
+// NOTE: this is a hot code path
+func (mw *Writer) require(n int) (int, error) {
+ c := len(mw.buf)
+ wl := mw.wloc
+ if c-wl < n {
+ if err := mw.flush(); err != nil {
+ return 0, err
+ }
+ wl = mw.wloc
+ }
+ mw.wloc += n
+ return wl, nil
+}
+
+// push one byte onto the buffer
+//
+// NOTE: this is a hot code path
+func (mw *Writer) push(b byte) error {
+ if mw.wloc == len(mw.buf) {
+ if err := mw.flush(); err != nil {
+ return err
+ }
+ }
+ mw.buf[mw.wloc] = b
+ mw.wloc++
+ return nil
+}
+
+func (mw *Writer) prefix8(b byte, u uint8) error {
+ const need = 2
+ if len(mw.buf)-mw.wloc < need {
+ if err := mw.flush(); err != nil {
+ return err
+ }
+ }
+ prefixu8(mw.buf[mw.wloc:], b, u)
+ mw.wloc += need
+ return nil
+}
+
+func (mw *Writer) prefix16(b byte, u uint16) error {
+ const need = 3
+ if len(mw.buf)-mw.wloc < need {
+ if err := mw.flush(); err != nil {
+ return err
+ }
+ }
+ prefixu16(mw.buf[mw.wloc:], b, u)
+ mw.wloc += need
+ return nil
+}
+
+func (mw *Writer) prefix32(b byte, u uint32) error {
+ const need = 5
+ if len(mw.buf)-mw.wloc < need {
+ if err := mw.flush(); err != nil {
+ return err
+ }
+ }
+ prefixu32(mw.buf[mw.wloc:], b, u)
+ mw.wloc += need
+ return nil
+}
+
+func (mw *Writer) prefix64(b byte, u uint64) error {
+ const need = 9
+ if len(mw.buf)-mw.wloc < need {
+ if err := mw.flush(); err != nil {
+ return err
+ }
+ }
+ prefixu64(mw.buf[mw.wloc:], b, u)
+ mw.wloc += need
+ return nil
+}
+
+// Write implements io.Writer, and writes
+// data directly to the buffer.
+func (mw *Writer) Write(p []byte) (int, error) {
+ l := len(p)
+ if mw.avail() < l {
+ if err := mw.flush(); err != nil {
+ return 0, err
+ }
+ if l > len(mw.buf) {
+ return mw.w.Write(p)
+ }
+ }
+ mw.wloc += copy(mw.buf[mw.wloc:], p)
+ return l, nil
+}
+
+// implements io.WriteString
+func (mw *Writer) writeString(s string) error {
+ l := len(s)
+ if mw.avail() < l {
+ if err := mw.flush(); err != nil {
+ return err
+ }
+ if l > len(mw.buf) {
+ _, err := io.WriteString(mw.w, s)
+ return err
+ }
+ }
+ mw.wloc += copy(mw.buf[mw.wloc:], s)
+ return nil
+}
+
+// Reset changes the underlying writer used by the Writer
+func (mw *Writer) Reset(w io.Writer) {
+ mw.buf = mw.buf[:cap(mw.buf)]
+ mw.w = w
+ mw.wloc = 0
+}
+
+// WriteMapHeader writes a map header of the given
+// size to the writer
+func (mw *Writer) WriteMapHeader(sz uint32) error {
+ switch {
+ case sz < 16:
+ return mw.push(wfixmap(uint8(sz)))
+ case sz < math.MaxUint16:
+ return mw.prefix16(mmap16, uint16(sz))
+ default:
+ return mw.prefix32(mmap32, sz)
+ }
+}
+
+// WriteArrayHeader writes an array header of the
+// given size to the writer
+func (mw *Writer) WriteArrayHeader(sz uint32) error {
+ switch {
+ case sz < 16:
+ return mw.push(wfixarray(uint8(sz)))
+ case sz < math.MaxUint16:
+ return mw.prefix16(marray16, uint16(sz))
+ default:
+ return mw.prefix32(marray32, sz)
+ }
+}
+
+// WriteNil writes a nil byte to the buffer
+func (mw *Writer) WriteNil() error {
+ return mw.push(mnil)
+}
+
+// WriteFloat64 writes a float64 to the writer
+func (mw *Writer) WriteFloat64(f float64) error {
+ return mw.prefix64(mfloat64, math.Float64bits(f))
+}
+
+// WriteFloat32 writes a float32 to the writer
+func (mw *Writer) WriteFloat32(f float32) error {
+ return mw.prefix32(mfloat32, math.Float32bits(f))
+}
+
+// WriteInt64 writes an int64 to the writer
+func (mw *Writer) WriteInt64(i int64) error {
+ a := abs(i)
+ switch {
+ case i < 0 && i > -32:
+ return mw.push(wnfixint(int8(i)))
+ case i >= 0 && i < 128:
+ return mw.push(wfixint(uint8(i)))
+ case a < math.MaxInt8:
+ return mw.prefix8(mint8, uint8(i))
+ case a < math.MaxInt16:
+ return mw.prefix16(mint16, uint16(i))
+ case a < math.MaxInt32:
+ return mw.prefix32(mint32, uint32(i))
+ default:
+ return mw.prefix64(mint64, uint64(i))
+ }
+}
+
+// WriteInt8 writes an int8 to the writer
+func (mw *Writer) WriteInt8(i int8) error { return mw.WriteInt64(int64(i)) }
+
+// WriteInt16 writes an int16 to the writer
+func (mw *Writer) WriteInt16(i int16) error { return mw.WriteInt64(int64(i)) }
+
+// WriteInt32 writes an int32 to the writer
+func (mw *Writer) WriteInt32(i int32) error { return mw.WriteInt64(int64(i)) }
+
+// WriteInt writes an int to the writer
+func (mw *Writer) WriteInt(i int) error { return mw.WriteInt64(int64(i)) }
+
+// WriteUint64 writes a uint64 to the writer
+func (mw *Writer) WriteUint64(u uint64) error {
+ switch {
+ case u < (1 << 7):
+ return mw.push(wfixint(uint8(u)))
+ case u < math.MaxUint8:
+ return mw.prefix8(muint8, uint8(u))
+ case u < math.MaxUint16:
+ return mw.prefix16(muint16, uint16(u))
+ case u < math.MaxUint32:
+ return mw.prefix32(muint32, uint32(u))
+ default:
+ return mw.prefix64(muint64, u)
+ }
+}
+
+// WriteByte is analagous to WriteUint8
+func (mw *Writer) WriteByte(u byte) error { return mw.WriteUint8(uint8(u)) }
+
+// WriteUint8 writes a uint8 to the writer
+func (mw *Writer) WriteUint8(u uint8) error { return mw.WriteUint64(uint64(u)) }
+
+// WriteUint16 writes a uint16 to the writer
+func (mw *Writer) WriteUint16(u uint16) error { return mw.WriteUint64(uint64(u)) }
+
+// WriteUint32 writes a uint32 to the writer
+func (mw *Writer) WriteUint32(u uint32) error { return mw.WriteUint64(uint64(u)) }
+
+// WriteUint writes a uint to the writer
+func (mw *Writer) WriteUint(u uint) error { return mw.WriteUint64(uint64(u)) }
+
+// WriteBytes writes binary as 'bin' to the writer
+func (mw *Writer) WriteBytes(b []byte) error {
+ sz := uint32(len(b))
+ var err error
+ switch {
+ case sz < math.MaxUint8:
+ err = mw.prefix8(mbin8, uint8(sz))
+ case sz < math.MaxUint16:
+ err = mw.prefix16(mbin16, uint16(sz))
+ default:
+ err = mw.prefix32(mbin32, sz)
+ }
+ if err != nil {
+ return err
+ }
+ _, err = mw.Write(b)
+ return err
+}
+
+// WriteBool writes a bool to the writer
+func (mw *Writer) WriteBool(b bool) error {
+ if b {
+ return mw.push(mtrue)
+ }
+ return mw.push(mfalse)
+}
+
+// WriteString writes a messagepack string to the writer.
+// (This is NOT an implementation of io.StringWriter)
+func (mw *Writer) WriteString(s string) error {
+ sz := uint32(len(s))
+ var err error
+ switch {
+ case sz < 32:
+ err = mw.push(wfixstr(uint8(sz)))
+ case sz < math.MaxUint8:
+ err = mw.prefix8(mstr8, uint8(sz))
+ case sz < math.MaxUint16:
+ err = mw.prefix16(mstr16, uint16(sz))
+ default:
+ err = mw.prefix32(mstr32, sz)
+ }
+ if err != nil {
+ return err
+ }
+ return mw.writeString(s)
+}
+
+// WriteComplex64 writes a complex64 to the writer
+func (mw *Writer) WriteComplex64(f complex64) error {
+ o, err := mw.require(10)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mfixext8
+ mw.buf[o+1] = Complex64Extension
+ big.PutUint32(mw.buf[o+2:], math.Float32bits(real(f)))
+ big.PutUint32(mw.buf[o+6:], math.Float32bits(imag(f)))
+ return nil
+}
+
+// WriteComplex128 writes a complex128 to the writer
+func (mw *Writer) WriteComplex128(f complex128) error {
+ o, err := mw.require(18)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mfixext16
+ mw.buf[o+1] = Complex128Extension
+ big.PutUint64(mw.buf[o+2:], math.Float64bits(real(f)))
+ big.PutUint64(mw.buf[o+10:], math.Float64bits(imag(f)))
+ return nil
+}
+
+// WriteMapStrStr writes a map[string]string to the writer
+func (mw *Writer) WriteMapStrStr(mp map[string]string) (err error) {
+ err = mw.WriteMapHeader(uint32(len(mp)))
+ if err != nil {
+ return
+ }
+ for key, val := range mp {
+ err = mw.WriteString(key)
+ if err != nil {
+ return
+ }
+ err = mw.WriteString(val)
+ if err != nil {
+ return
+ }
+ }
+ return nil
+}
+
+// WriteMapStrIntf writes a map[string]interface to the writer
+func (mw *Writer) WriteMapStrIntf(mp map[string]interface{}) (err error) {
+ err = mw.WriteMapHeader(uint32(len(mp)))
+ if err != nil {
+ return
+ }
+ for key, val := range mp {
+ err = mw.WriteString(key)
+ if err != nil {
+ return
+ }
+ err = mw.WriteIntf(val)
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// WriteTime writes a time.Time object to the wire.
+//
+// Time is encoded as Unix time, which means that
+// location (time zone) data is removed from the object.
+// The encoded object itself is 12 bytes: 8 bytes for
+// a big-endian 64-bit integer denoting seconds
+// elapsed since "zero" Unix time, followed by 4 bytes
+// for a big-endian 32-bit signed integer denoting
+// the nanosecond offset of the time. This encoding
+// is intended to ease portability accross languages.
+// (Note that this is *not* the standard time.Time
+// binary encoding, because its implementation relies
+// heavily on the internal representation used by the
+// time package.)
+func (mw *Writer) WriteTime(t time.Time) error {
+ t = t.UTC()
+ o, err := mw.require(15)
+ if err != nil {
+ return err
+ }
+ mw.buf[o] = mext8
+ mw.buf[o+1] = 12
+ mw.buf[o+2] = TimeExtension
+ putUnix(mw.buf[o+3:], t.Unix(), int32(t.Nanosecond()))
+ return nil
+}
+
+// WriteIntf writes the concrete type of 'v'.
+// WriteIntf will error if 'v' is not one of the following:
+// - A bool, float, string, []byte, int, uint, or complex
+// - A map of supported types (with string keys)
+// - An array or slice of supported types
+// - A pointer to a supported type
+// - A type that satisfies the msgp.Encodable interface
+// - A type that satisfies the msgp.Extension interface
+func (mw *Writer) WriteIntf(v interface{}) error {
+ if v == nil {
+ return mw.WriteNil()
+ }
+ switch v := v.(type) {
+
+ // preferred interfaces
+
+ case Encodable:
+ return v.EncodeMsg(mw)
+ case Extension:
+ return mw.WriteExtension(v)
+
+ // concrete types
+
+ case bool:
+ return mw.WriteBool(v)
+ case float32:
+ return mw.WriteFloat32(v)
+ case float64:
+ return mw.WriteFloat64(v)
+ case complex64:
+ return mw.WriteComplex64(v)
+ case complex128:
+ return mw.WriteComplex128(v)
+ case uint8:
+ return mw.WriteUint8(v)
+ case uint16:
+ return mw.WriteUint16(v)
+ case uint32:
+ return mw.WriteUint32(v)
+ case uint64:
+ return mw.WriteUint64(v)
+ case uint:
+ return mw.WriteUint(v)
+ case int8:
+ return mw.WriteInt8(v)
+ case int16:
+ return mw.WriteInt16(v)
+ case int32:
+ return mw.WriteInt32(v)
+ case int64:
+ return mw.WriteInt64(v)
+ case int:
+ return mw.WriteInt(v)
+ case string:
+ return mw.WriteString(v)
+ case []byte:
+ return mw.WriteBytes(v)
+ case map[string]string:
+ return mw.WriteMapStrStr(v)
+ case map[string]interface{}:
+ return mw.WriteMapStrIntf(v)
+ case time.Time:
+ return mw.WriteTime(v)
+ }
+
+ val := reflect.ValueOf(v)
+ if !isSupported(val.Kind()) || !val.IsValid() {
+ return fmt.Errorf("msgp: type %s not supported", val)
+ }
+
+ switch val.Kind() {
+ case reflect.Ptr:
+ if val.IsNil() {
+ return mw.WriteNil()
+ }
+ return mw.WriteIntf(val.Elem().Interface())
+ case reflect.Slice:
+ return mw.writeSlice(val)
+ case reflect.Map:
+ return mw.writeMap(val)
+ }
+ return &ErrUnsupportedType{val.Type()}
+}
+
+func (mw *Writer) writeMap(v reflect.Value) (err error) {
+ if v.Elem().Kind() != reflect.String {
+ return errors.New("msgp: map keys must be strings")
+ }
+ ks := v.MapKeys()
+ err = mw.WriteMapHeader(uint32(len(ks)))
+ if err != nil {
+ return
+ }
+ for _, key := range ks {
+ val := v.MapIndex(key)
+ err = mw.WriteString(key.String())
+ if err != nil {
+ return
+ }
+ err = mw.WriteIntf(val.Interface())
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+func (mw *Writer) writeSlice(v reflect.Value) (err error) {
+ // is []byte
+ if v.Type().ConvertibleTo(btsType) {
+ return mw.WriteBytes(v.Bytes())
+ }
+
+ sz := uint32(v.Len())
+ err = mw.WriteArrayHeader(sz)
+ if err != nil {
+ return
+ }
+ for i := uint32(0); i < sz; i++ {
+ err = mw.WriteIntf(v.Index(int(i)).Interface())
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+func (mw *Writer) writeStruct(v reflect.Value) error {
+ if enc, ok := v.Interface().(Encodable); ok {
+ return enc.EncodeMsg(mw)
+ }
+ return fmt.Errorf("msgp: unsupported type: %s", v.Type())
+}
+
+func (mw *Writer) writeVal(v reflect.Value) error {
+ if !isSupported(v.Kind()) {
+ return fmt.Errorf("msgp: msgp/enc: type %q not supported", v.Type())
+ }
+
+ // shortcut for nil values
+ if v.IsNil() {
+ return mw.WriteNil()
+ }
+ switch v.Kind() {
+ case reflect.Bool:
+ return mw.WriteBool(v.Bool())
+
+ case reflect.Float32, reflect.Float64:
+ return mw.WriteFloat64(v.Float())
+
+ case reflect.Complex64, reflect.Complex128:
+ return mw.WriteComplex128(v.Complex())
+
+ case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8:
+ return mw.WriteInt64(v.Int())
+
+ case reflect.Interface, reflect.Ptr:
+ if v.IsNil() {
+ mw.WriteNil()
+ }
+ return mw.writeVal(v.Elem())
+
+ case reflect.Map:
+ return mw.writeMap(v)
+
+ case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8:
+ return mw.WriteUint64(v.Uint())
+
+ case reflect.String:
+ return mw.WriteString(v.String())
+
+ case reflect.Slice, reflect.Array:
+ return mw.writeSlice(v)
+
+ case reflect.Struct:
+ return mw.writeStruct(v)
+
+ }
+ return fmt.Errorf("msgp: msgp/enc: type %q not supported", v.Type())
+}
+
+// is the reflect.Kind encodable?
+func isSupported(k reflect.Kind) bool {
+ switch k {
+ case reflect.Func, reflect.Chan, reflect.Invalid, reflect.UnsafePointer:
+ return false
+ default:
+ return true
+ }
+}
+
+// GuessSize guesses the size of the underlying
+// value of 'i'. If the underlying value is not
+// a simple builtin (or []byte), GuessSize defaults
+// to 512.
+func GuessSize(i interface{}) int {
+ if i == nil {
+ return NilSize
+ }
+
+ switch i := i.(type) {
+ case Sizer:
+ return i.Msgsize()
+ case Extension:
+ return ExtensionPrefixSize + i.Len()
+ case float64:
+ return Float64Size
+ case float32:
+ return Float32Size
+ case uint8, uint16, uint32, uint64, uint:
+ return UintSize
+ case int8, int16, int32, int64, int:
+ return IntSize
+ case []byte:
+ return BytesPrefixSize + len(i)
+ case string:
+ return StringPrefixSize + len(i)
+ case complex64:
+ return Complex64Size
+ case complex128:
+ return Complex128Size
+ case bool:
+ return BoolSize
+ case map[string]interface{}:
+ s := MapHeaderSize
+ for key, val := range i {
+ s += StringPrefixSize + len(key) + GuessSize(val)
+ }
+ return s
+ case map[string]string:
+ s := MapHeaderSize
+ for key, val := range i {
+ s += 2*StringPrefixSize + len(key) + len(val)
+ }
+ return s
+ default:
+ return 512
+ }
+}
diff --git a/vendor/github.com/tinylib/msgp/msgp/write_bytes.go b/vendor/github.com/tinylib/msgp/msgp/write_bytes.go
new file mode 100644
index 0000000..658102e
--- /dev/null
+++ b/vendor/github.com/tinylib/msgp/msgp/write_bytes.go
@@ -0,0 +1,369 @@
+package msgp
+
+import (
+ "math"
+ "reflect"
+ "time"
+)
+
+// ensure 'sz' extra bytes in 'b' btw len(b) and cap(b)
+func ensure(b []byte, sz int) ([]byte, int) {
+ l := len(b)
+ c := cap(b)
+ if c-l < sz {
+ o := make([]byte, (2*c)+sz) // exponential growth
+ n := copy(o, b)
+ return o[:n+sz], n
+ }
+ return b[:l+sz], l
+}
+
+// AppendMapHeader appends a map header with the
+// given size to the slice
+func AppendMapHeader(b []byte, sz uint32) []byte {
+ switch {
+ case sz < 16:
+ return append(b, wfixmap(uint8(sz)))
+
+ case sz < math.MaxUint16:
+ o, n := ensure(b, 3)
+ prefixu16(o[n:], mmap16, uint16(sz))
+ return o
+
+ default:
+ o, n := ensure(b, 5)
+ prefixu32(o[n:], mmap32, sz)
+ return o
+ }
+}
+
+// AppendArrayHeader appends an array header with
+// the given size to the slice
+func AppendArrayHeader(b []byte, sz uint32) []byte {
+ switch {
+ case sz < 16:
+ return append(b, wfixarray(uint8(sz)))
+
+ case sz < math.MaxUint16:
+ o, n := ensure(b, 3)
+ prefixu16(o[n:], marray16, uint16(sz))
+ return o
+
+ default:
+ o, n := ensure(b, 5)
+ prefixu32(o[n:], marray32, sz)
+ return o
+ }
+}
+
+// AppendNil appends a 'nil' byte to the slice
+func AppendNil(b []byte) []byte { return append(b, mnil) }
+
+// AppendFloat64 appends a float64 to the slice
+func AppendFloat64(b []byte, f float64) []byte {
+ o, n := ensure(b, Float64Size)
+ prefixu64(o[n:], mfloat64, math.Float64bits(f))
+ return o
+}
+
+// AppendFloat32 appends a float32 to the slice
+func AppendFloat32(b []byte, f float32) []byte {
+ o, n := ensure(b, Float32Size)
+ prefixu32(o[n:], mfloat32, math.Float32bits(f))
+ return o
+}
+
+// AppendInt64 appends an int64 to the slice
+func AppendInt64(b []byte, i int64) []byte {
+ a := abs(i)
+ switch {
+ case i < 0 && i > -32:
+ return append(b, wnfixint(int8(i)))
+
+ case i >= 0 && i < 128:
+ return append(b, wfixint(uint8(i)))
+
+ case a < math.MaxInt8:
+ o, n := ensure(b, 2)
+ putMint8(o[n:], int8(i))
+ return o
+
+ case a < math.MaxInt16:
+ o, n := ensure(b, 3)
+ putMint16(o[n:], int16(i))
+ return o
+
+ case a < math.MaxInt32:
+ o, n := ensure(b, 5)
+ putMint32(o[n:], int32(i))
+ return o
+
+ default:
+ o, n := ensure(b, 9)
+ putMint64(o[n:], i)
+ return o
+ }
+}
+
+// AppendInt appends an int to the slice
+func AppendInt(b []byte, i int) []byte { return AppendInt64(b, int64(i)) }
+
+// AppendInt8 appends an int8 to the slice
+func AppendInt8(b []byte, i int8) []byte { return AppendInt64(b, int64(i)) }
+
+// AppendInt16 appends an int16 to the slice
+func AppendInt16(b []byte, i int16) []byte { return AppendInt64(b, int64(i)) }
+
+// AppendInt32 appends an int32 to the slice
+func AppendInt32(b []byte, i int32) []byte { return AppendInt64(b, int64(i)) }
+
+// AppendUint64 appends a uint64 to the slice
+func AppendUint64(b []byte, u uint64) []byte {
+ switch {
+ case u < (1 << 7):
+ return append(b, wfixint(uint8(u)))
+
+ case u < math.MaxUint8:
+ o, n := ensure(b, 2)
+ putMuint8(o[n:], uint8(u))
+ return o
+
+ case u < math.MaxUint16:
+ o, n := ensure(b, 3)
+ putMuint16(o[n:], uint16(u))
+ return o
+
+ case u < math.MaxUint32:
+ o, n := ensure(b, 5)
+ putMuint32(o[n:], uint32(u))
+ return o
+
+ default:
+ o, n := ensure(b, 9)
+ putMuint64(o[n:], u)
+ return o
+
+ }
+}
+
+// AppendUint appends a uint to the slice
+func AppendUint(b []byte, u uint) []byte { return AppendUint64(b, uint64(u)) }
+
+// AppendUint8 appends a uint8 to the slice
+func AppendUint8(b []byte, u uint8) []byte { return AppendUint64(b, uint64(u)) }
+
+// AppendByte is analagous to AppendUint8
+func AppendByte(b []byte, u byte) []byte { return AppendUint8(b, uint8(u)) }
+
+// AppendUint16 appends a uint16 to the slice
+func AppendUint16(b []byte, u uint16) []byte { return AppendUint64(b, uint64(u)) }
+
+// AppendUint32 appends a uint32 to the slice
+func AppendUint32(b []byte, u uint32) []byte { return AppendUint64(b, uint64(u)) }
+
+// AppendBytes appends bytes to the slice as MessagePack 'bin' data
+func AppendBytes(b []byte, bts []byte) []byte {
+ sz := len(bts)
+ var o []byte
+ var n int
+ switch {
+ case sz < math.MaxUint8:
+ o, n = ensure(b, 2+sz)
+ prefixu8(o[n:], mbin8, uint8(sz))
+ n += 2
+ case sz < math.MaxUint16:
+ o, n = ensure(b, 3+sz)
+ prefixu16(o[n:], mbin16, uint16(sz))
+ n += 3
+ default:
+ o, n = ensure(b, 5+sz)
+ prefixu32(o[n:], mbin32, uint32(sz))
+ n += 5
+ }
+ return o[:n+copy(o[n:], bts)]
+}
+
+// AppendBool appends a bool to the slice
+func AppendBool(b []byte, t bool) []byte {
+ if t {
+ return append(b, mtrue)
+ }
+ return append(b, mfalse)
+}
+
+// AppendString appends a string as a MessagePack 'str' to the slice
+func AppendString(b []byte, s string) []byte {
+ sz := len(s)
+ var n int
+ var o []byte
+ switch {
+ case sz < 32:
+ o, n = ensure(b, 1+sz)
+ o[n] = wfixstr(uint8(sz))
+ n++
+ case sz < math.MaxUint8:
+ o, n = ensure(b, 2+sz)
+ prefixu8(o[n:], mstr8, uint8(sz))
+ n += 2
+ case sz < math.MaxUint16:
+ o, n = ensure(b, 3+sz)
+ prefixu16(o[n:], mstr16, uint16(sz))
+ n += 3
+ default:
+ o, n = ensure(b, 5+sz)
+ prefixu32(o[n:], mstr32, uint32(sz))
+ n += 5
+ }
+ return o[:n+copy(o[n:], s)]
+}
+
+// AppendComplex64 appends a complex64 to the slice as a MessagePack extension
+func AppendComplex64(b []byte, c complex64) []byte {
+ o, n := ensure(b, Complex64Size)
+ o[n] = mfixext8
+ o[n+1] = Complex64Extension
+ big.PutUint32(o[n+2:], math.Float32bits(real(c)))
+ big.PutUint32(o[n+6:], math.Float32bits(imag(c)))
+ return o
+}
+
+// AppendComplex128 appends a complex128 to the slice as a MessagePack extension
+func AppendComplex128(b []byte, c complex128) []byte {
+ o, n := ensure(b, Complex128Size)
+ o[n] = mfixext16
+ o[n+1] = Complex128Extension
+ big.PutUint64(o[n+2:], math.Float64bits(real(c)))
+ big.PutUint64(o[n+10:], math.Float64bits(imag(c)))
+ return o
+}
+
+// AppendTime appends a time.Time to the slice as a MessagePack extension
+func AppendTime(b []byte, t time.Time) []byte {
+ o, n := ensure(b, TimeSize)
+ t = t.UTC()
+ o[n] = mext8
+ o[n+1] = 12
+ o[n+2] = TimeExtension
+ putUnix(o[n+3:], t.Unix(), int32(t.Nanosecond()))
+ return o
+}
+
+// AppendMapStrStr appends a map[string]string to the slice
+// as a MessagePack map with 'str'-type keys and values
+func AppendMapStrStr(b []byte, m map[string]string) []byte {
+ sz := uint32(len(m))
+ b = AppendMapHeader(b, sz)
+ for key, val := range m {
+ b = AppendString(b, key)
+ b = AppendString(b, val)
+ }
+ return b
+}
+
+// AppendMapStrIntf appends a map[string]interface{} to the slice
+// as a MessagePack map with 'str'-type keys.
+func AppendMapStrIntf(b []byte, m map[string]interface{}) ([]byte, error) {
+ sz := uint32(len(m))
+ b = AppendMapHeader(b, sz)
+ var err error
+ for key, val := range m {
+ b = AppendString(b, key)
+ b, err = AppendIntf(b, val)
+ if err != nil {
+ return b, err
+ }
+ }
+ return b, nil
+}
+
+// AppendIntf appends the concrete type of 'i' to the
+// provided []byte. 'i' must be one of the following:
+// - 'nil'
+// - A bool, float, string, []byte, int, uint, or complex
+// - A map[string]interface{} or map[string]string
+// - A []T, where T is another supported type
+// - A *T, where T is another supported type
+// - A type that satisfieds the msgp.Marshaler interface
+// - A type that satisfies the msgp.Extension interface
+func AppendIntf(b []byte, i interface{}) ([]byte, error) {
+ if i == nil {
+ return AppendNil(b), nil
+ }
+
+ // all the concrete types
+ // for which we have methods
+ switch i := i.(type) {
+ case Marshaler:
+ return i.MarshalMsg(b)
+ case Extension:
+ return AppendExtension(b, i)
+ case bool:
+ return AppendBool(b, i), nil
+ case float32:
+ return AppendFloat32(b, i), nil
+ case float64:
+ return AppendFloat64(b, i), nil
+ case complex64:
+ return AppendComplex64(b, i), nil
+ case complex128:
+ return AppendComplex128(b, i), nil
+ case string:
+ return AppendString(b, i), nil
+ case []byte:
+ return AppendBytes(b, i), nil
+ case int8:
+ return AppendInt8(b, i), nil
+ case int16:
+ return AppendInt16(b, i), nil
+ case int32:
+ return AppendInt32(b, i), nil
+ case int64:
+ return AppendInt64(b, i), nil
+ case int:
+ return AppendInt64(b, int64(i)), nil
+ case uint:
+ return AppendUint64(b, uint64(i)), nil
+ case uint8:
+ return AppendUint8(b, i), nil
+ case uint16:
+ return AppendUint16(b, i), nil
+ case uint32:
+ return AppendUint32(b, i), nil
+ case uint64:
+ return AppendUint64(b, i), nil
+ case time.Time:
+ return AppendTime(b, i), nil
+ case map[string]interface{}:
+ return AppendMapStrIntf(b, i)
+ case map[string]string:
+ return AppendMapStrStr(b, i), nil
+ case []interface{}:
+ b = AppendArrayHeader(b, uint32(len(i)))
+ var err error
+ for _, k := range i {
+ b, err = AppendIntf(b, k)
+ if err != nil {
+ return b, err
+ }
+ }
+ return b, nil
+ }
+
+ var err error
+ v := reflect.ValueOf(i)
+ switch v.Kind() {
+ case reflect.Array, reflect.Slice:
+ l := v.Len()
+ b = AppendArrayHeader(b, uint32(l))
+ for i := 0; i < l; i++ {
+ b, err = AppendIntf(b, v.Index(i).Interface())
+ if err != nil {
+ return b, err
+ }
+ }
+ return b, nil
+
+ default:
+ return b, &ErrUnsupportedType{T: v.Type()}
+ }
+}
diff --git a/vendor/github.com/tonistiigi/fifo/LICENSE b/vendor/github.com/tonistiigi/fifo/LICENSE
new file mode 100644
index 0000000..8d318c1
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fifo/LICENSE
@@ -0,0 +1,21 @@
+MIT
+
+Copyright (C) 2016 Tõnis Tiigi <tonistiigi@gmail.com>
+
+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/tonistiigi/fifo/fifo.go b/vendor/github.com/tonistiigi/fifo/fifo.go
new file mode 100644
index 0000000..9e8e2ca
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fifo/fifo.go
@@ -0,0 +1,217 @@
+package fifo
+
+import (
+ "io"
+ "os"
+ "runtime"
+ "sync"
+ "syscall"
+
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "golang.org/x/sys/unix"
+)
+
+type fifo struct {
+ flag int
+ opened chan struct{}
+ closed chan struct{}
+ closing chan struct{}
+ err error
+ file *os.File
+ closingOnce sync.Once // close has been called
+ closedOnce sync.Once // fifo is closed
+ handle *handle
+}
+
+var leakCheckWg *sync.WaitGroup
+
+// OpenFifo opens a fifo. Returns io.ReadWriteCloser.
+// Context can be used to cancel this function until open(2) has not returned.
+// Accepted flags:
+// - syscall.O_CREAT - create new fifo if one doesn't exist
+// - syscall.O_RDONLY - open fifo only from reader side
+// - syscall.O_WRONLY - open fifo only from writer side
+// - syscall.O_RDWR - open fifo from both sides, never block on syscall level
+// - syscall.O_NONBLOCK - return io.ReadWriteCloser even if other side of the
+// fifo isn't open. read/write will be connected after the actual fifo is
+// open or after fifo is closed.
+func OpenFifo(ctx context.Context, fn string, flag int, perm os.FileMode) (io.ReadWriteCloser, error) {
+ if _, err := os.Stat(fn); err != nil {
+ if os.IsNotExist(err) && flag&syscall.O_CREAT != 0 {
+ if err := unix.Mkfifo(fn, uint32(perm&os.ModePerm)); err != nil && !os.IsExist(err) {
+ return nil, errors.Wrapf(err, "error creating fifo %v", fn)
+ }
+ } else {
+ return nil, err
+ }
+ }
+
+ block := flag&syscall.O_NONBLOCK == 0 || flag&syscall.O_RDWR != 0
+
+ flag &= ^syscall.O_CREAT
+ flag &= ^syscall.O_NONBLOCK
+
+ h, err := getHandle(fn)
+ if err != nil {
+ return nil, err
+ }
+
+ f := &fifo{
+ handle: h,
+ flag: flag,
+ opened: make(chan struct{}),
+ closed: make(chan struct{}),
+ closing: make(chan struct{}),
+ }
+
+ wg := leakCheckWg
+ if wg != nil {
+ wg.Add(2)
+ }
+
+ go func() {
+ if wg != nil {
+ defer wg.Done()
+ }
+ select {
+ case <-ctx.Done():
+ f.Close()
+ case <-f.opened:
+ case <-f.closed:
+ }
+ }()
+ go func() {
+ if wg != nil {
+ defer wg.Done()
+ }
+ var file *os.File
+ fn, err := h.Path()
+ if err == nil {
+ file, err = os.OpenFile(fn, flag, 0)
+ }
+ select {
+ case <-f.closing:
+ if err == nil {
+ select {
+ case <-ctx.Done():
+ err = ctx.Err()
+ default:
+ err = errors.Errorf("fifo %v was closed before opening", h.Name())
+ }
+ if file != nil {
+ file.Close()
+ }
+ }
+ default:
+ }
+ if err != nil {
+ f.closedOnce.Do(func() {
+ f.err = err
+ close(f.closed)
+ })
+ return
+ }
+ f.file = file
+ close(f.opened)
+ }()
+ if block {
+ select {
+ case <-f.opened:
+ case <-f.closed:
+ return nil, f.err
+ }
+ }
+ return f, nil
+}
+
+// Read from a fifo to a byte array.
+func (f *fifo) Read(b []byte) (int, error) {
+ if f.flag&syscall.O_WRONLY > 0 {
+ return 0, errors.New("reading from write-only fifo")
+ }
+ select {
+ case <-f.opened:
+ return f.file.Read(b)
+ default:
+ }
+ select {
+ case <-f.opened:
+ return f.file.Read(b)
+ case <-f.closed:
+ return 0, errors.New("reading from a closed fifo")
+ }
+}
+
+// Write from byte array to a fifo.
+func (f *fifo) Write(b []byte) (int, error) {
+ if f.flag&(syscall.O_WRONLY|syscall.O_RDWR) == 0 {
+ return 0, errors.New("writing to read-only fifo")
+ }
+ select {
+ case <-f.opened:
+ return f.file.Write(b)
+ default:
+ }
+ select {
+ case <-f.opened:
+ return f.file.Write(b)
+ case <-f.closed:
+ return 0, errors.New("writing to a closed fifo")
+ }
+}
+
+// Close the fifo. Next reads/writes will error. This method can also be used
+// before open(2) has returned and fifo was never opened.
+func (f *fifo) Close() (retErr error) {
+ for {
+ select {
+ case <-f.closed:
+ f.handle.Close()
+ return
+ default:
+ select {
+ case <-f.opened:
+ f.closedOnce.Do(func() {
+ retErr = f.file.Close()
+ f.err = retErr
+ close(f.closed)
+ })
+ default:
+ if f.flag&syscall.O_RDWR != 0 {
+ runtime.Gosched()
+ break
+ }
+ f.closingOnce.Do(func() {
+ close(f.closing)
+ })
+ reverseMode := syscall.O_WRONLY
+ if f.flag&syscall.O_WRONLY > 0 {
+ reverseMode = syscall.O_RDONLY
+ }
+ fn, err := f.handle.Path()
+ // if Close() is called concurrently(shouldn't) it may cause error
+ // because handle is closed
+ select {
+ case <-f.closed:
+ default:
+ if err != nil {
+ // Path has become invalid. We will leak a goroutine.
+ // This case should not happen in linux.
+ f.closedOnce.Do(func() {
+ f.err = err
+ close(f.closed)
+ })
+ <-f.closed
+ break
+ }
+ f, err := os.OpenFile(fn, reverseMode|syscall.O_NONBLOCK, 0)
+ if err == nil {
+ f.Close()
+ }
+ runtime.Gosched()
+ }
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/tonistiigi/fifo/handle_linux.go b/vendor/github.com/tonistiigi/fifo/handle_linux.go
new file mode 100644
index 0000000..7bda64c
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fifo/handle_linux.go
@@ -0,0 +1,76 @@
+// +build linux
+
+package fifo
+
+import (
+ "fmt"
+ "os"
+ "sync"
+ "syscall"
+
+ "github.com/pkg/errors"
+)
+
+const O_PATH = 010000000
+
+type handle struct {
+ f *os.File
+ dev uint64
+ ino uint64
+ closeOnce sync.Once
+ name string
+}
+
+func getHandle(fn string) (*handle, error) {
+ f, err := os.OpenFile(fn, O_PATH, 0)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to open %v with O_PATH", fn)
+ }
+
+ var stat syscall.Stat_t
+ if err := syscall.Fstat(int(f.Fd()), &stat); err != nil {
+ f.Close()
+ return nil, errors.Wrapf(err, "failed to stat handle %v", f.Fd())
+ }
+
+ h := &handle{
+ f: f,
+ name: fn,
+ dev: stat.Dev,
+ ino: stat.Ino,
+ }
+
+ // check /proc just in case
+ if _, err := os.Stat(h.procPath()); err != nil {
+ f.Close()
+ return nil, errors.Wrapf(err, "couldn't stat %v", h.procPath())
+ }
+
+ return h, nil
+}
+
+func (h *handle) procPath() string {
+ return fmt.Sprintf("/proc/self/fd/%d", h.f.Fd())
+}
+
+func (h *handle) Name() string {
+ return h.name
+}
+
+func (h *handle) Path() (string, error) {
+ var stat syscall.Stat_t
+ if err := syscall.Stat(h.procPath(), &stat); err != nil {
+ return "", errors.Wrapf(err, "path %v could not be statted", h.procPath())
+ }
+ if stat.Dev != h.dev || stat.Ino != h.ino {
+ return "", errors.Errorf("failed to verify handle %v/%v %v/%v", stat.Dev, h.dev, stat.Ino, h.ino)
+ }
+ return h.procPath(), nil
+}
+
+func (h *handle) Close() error {
+ h.closeOnce.Do(func() {
+ h.f.Close()
+ })
+ return nil
+}
diff --git a/vendor/github.com/tonistiigi/fifo/handle_nolinux.go b/vendor/github.com/tonistiigi/fifo/handle_nolinux.go
new file mode 100644
index 0000000..d9648d8
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fifo/handle_nolinux.go
@@ -0,0 +1,49 @@
+// +build !linux
+
+package fifo
+
+import (
+ "syscall"
+
+ "github.com/pkg/errors"
+)
+
+type handle struct {
+ fn string
+ dev uint64
+ ino uint64
+}
+
+func getHandle(fn string) (*handle, error) {
+ var stat syscall.Stat_t
+ if err := syscall.Stat(fn, &stat); err != nil {
+ return nil, errors.Wrapf(err, "failed to stat %v", fn)
+ }
+
+ h := &handle{
+ fn: fn,
+ dev: uint64(stat.Dev),
+ ino: stat.Ino,
+ }
+
+ return h, nil
+}
+
+func (h *handle) Path() (string, error) {
+ var stat syscall.Stat_t
+ if err := syscall.Stat(h.fn, &stat); err != nil {
+ return "", errors.Wrapf(err, "path %v could not be statted", h.fn)
+ }
+ if uint64(stat.Dev) != h.dev || stat.Ino != h.ino {
+ return "", errors.Errorf("failed to verify handle %v/%v %v/%v for %v", stat.Dev, h.dev, stat.Ino, h.ino, h.fn)
+ }
+ return h.fn, nil
+}
+
+func (h *handle) Name() string {
+ return h.fn
+}
+
+func (h *handle) Close() error {
+ return nil
+}
diff --git a/vendor/github.com/tonistiigi/fifo/readme.md b/vendor/github.com/tonistiigi/fifo/readme.md
new file mode 100644
index 0000000..1c82669
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fifo/readme.md
@@ -0,0 +1,30 @@
+### fifo
+
+Go package for handling fifos in a sane way.
+
+```
+// OpenFifo opens a fifo. Returns io.ReadWriteCloser.
+// Context can be used to cancel this function until open(2) has not returned.
+// Accepted flags:
+// - syscall.O_CREAT - create new fifo if one doesn't exist
+// - syscall.O_RDONLY - open fifo only from reader side
+// - syscall.O_WRONLY - open fifo only from writer side
+// - syscall.O_RDWR - open fifo from both sides, never block on syscall level
+// - syscall.O_NONBLOCK - return io.ReadWriteCloser even if other side of the
+// fifo isn't open. read/write will be connected after the actual fifo is
+// open or after fifo is closed.
+func OpenFifo(ctx context.Context, fn string, flag int, perm os.FileMode) (io.ReadWriteCloser, error)
+
+
+// Read from a fifo to a byte array.
+func (f *fifo) Read(b []byte) (int, error)
+
+
+// Write from byte array to a fifo.
+func (f *fifo) Write(b []byte) (int, error)
+
+
+// Close the fifo. Next reads/writes will error. This method can also be used
+// before open(2) has returned and fifo was never opened.
+func (f *fifo) Close() error
+``` \ No newline at end of file
diff --git a/vendor/github.com/tonistiigi/fsutil/LICENSE b/vendor/github.com/tonistiigi/fsutil/LICENSE
new file mode 100644
index 0000000..7df441d
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/LICENSE
@@ -0,0 +1,22 @@
+MIT
+
+Copyright 2017 Tõnis Tiigi <tonistiigi@gmail.com>
+
+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/tonistiigi/fsutil/diff.go b/vendor/github.com/tonistiigi/fsutil/diff.go
new file mode 100644
index 0000000..1530973
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/diff.go
@@ -0,0 +1,37 @@
+package fsutil
+
+import (
+ "os"
+
+ "golang.org/x/net/context"
+)
+
+type walkerFn func(ctx context.Context, pathC chan<- *currentPath) error
+
+func Changes(ctx context.Context, a, b walkerFn, changeFn ChangeFunc) error {
+ return nil
+}
+
+type HandleChangeFn func(ChangeKind, string, os.FileInfo, error) error
+
+func GetWalkerFn(root string) walkerFn {
+ return func(ctx context.Context, pathC chan<- *currentPath) error {
+ return Walk(ctx, root, nil, func(path string, f os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+
+ p := &currentPath{
+ path: path,
+ f: f,
+ }
+
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case pathC <- p:
+ return nil
+ }
+ })
+ }
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/diff_containerd.go b/vendor/github.com/tonistiigi/fsutil/diff_containerd.go
new file mode 100644
index 0000000..c7c9788
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/diff_containerd.go
@@ -0,0 +1,199 @@
+package fsutil
+
+import (
+ "os"
+ "strings"
+
+ "golang.org/x/net/context"
+ "golang.org/x/sync/errgroup"
+)
+
+// Everything below is copied from containerd/fs. TODO: remove duplication @dmcgowan
+
+// Const redefined because containerd/fs doesn't build on !linux
+
+// ChangeKind is the type of modification that
+// a change is making.
+type ChangeKind int
+
+const (
+ // ChangeKindAdd represents an addition of
+ // a file
+ ChangeKindAdd ChangeKind = iota
+
+ // ChangeKindModify represents a change to
+ // an existing file
+ ChangeKindModify
+
+ // ChangeKindDelete represents a delete of
+ // a file
+ ChangeKindDelete
+)
+
+// ChangeFunc is the type of function called for each change
+// computed during a directory changes calculation.
+type ChangeFunc func(ChangeKind, string, os.FileInfo, error) error
+
+type currentPath struct {
+ path string
+ f os.FileInfo
+ // fullPath string
+}
+
+// doubleWalkDiff walks both directories to create a diff
+func doubleWalkDiff(ctx context.Context, changeFn ChangeFunc, a, b walkerFn) (err error) {
+ g, ctx := errgroup.WithContext(ctx)
+
+ var (
+ c1 = make(chan *currentPath, 128)
+ c2 = make(chan *currentPath, 128)
+
+ f1, f2 *currentPath
+ rmdir string
+ )
+ g.Go(func() error {
+ defer close(c1)
+ return a(ctx, c1)
+ })
+ g.Go(func() error {
+ defer close(c2)
+ return b(ctx, c2)
+ })
+ g.Go(func() error {
+ loop0:
+ for c1 != nil || c2 != nil {
+ if f1 == nil && c1 != nil {
+ f1, err = nextPath(ctx, c1)
+ if err != nil {
+ return err
+ }
+ if f1 == nil {
+ c1 = nil
+ }
+ }
+
+ if f2 == nil && c2 != nil {
+ f2, err = nextPath(ctx, c2)
+ if err != nil {
+ return err
+ }
+ if f2 == nil {
+ c2 = nil
+ }
+ }
+ if f1 == nil && f2 == nil {
+ continue
+ }
+
+ var f os.FileInfo
+ k, p := pathChange(f1, f2)
+ switch k {
+ case ChangeKindAdd:
+ if rmdir != "" {
+ rmdir = ""
+ }
+ f = f2.f
+ f2 = nil
+ case ChangeKindDelete:
+ // Check if this file is already removed by being
+ // under of a removed directory
+ if rmdir != "" && strings.HasPrefix(f1.path, rmdir) {
+ f1 = nil
+ continue
+ } else if rmdir == "" && f1.f.IsDir() {
+ rmdir = f1.path + string(os.PathSeparator)
+ } else if rmdir != "" {
+ rmdir = ""
+ }
+ f1 = nil
+ case ChangeKindModify:
+ same, err := sameFile(f1, f2)
+ if err != nil {
+ return err
+ }
+ if f1.f.IsDir() && !f2.f.IsDir() {
+ rmdir = f1.path + string(os.PathSeparator)
+ } else if rmdir != "" {
+ rmdir = ""
+ }
+ f = f2.f
+ f1 = nil
+ f2 = nil
+ if same {
+ continue loop0
+ }
+ }
+ if err := changeFn(k, p, f, nil); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+
+ return g.Wait()
+}
+
+func pathChange(lower, upper *currentPath) (ChangeKind, string) {
+ if lower == nil {
+ if upper == nil {
+ panic("cannot compare nil paths")
+ }
+ return ChangeKindAdd, upper.path
+ }
+ if upper == nil {
+ return ChangeKindDelete, lower.path
+ }
+
+ switch i := ComparePath(lower.path, upper.path); {
+ case i < 0:
+ // File in lower that is not in upper
+ return ChangeKindDelete, lower.path
+ case i > 0:
+ // File in upper that is not in lower
+ return ChangeKindAdd, upper.path
+ default:
+ return ChangeKindModify, upper.path
+ }
+}
+
+func sameFile(f1, f2 *currentPath) (same bool, retErr error) {
+ // If not a directory also check size, modtime, and content
+ if !f1.f.IsDir() {
+ if f1.f.Size() != f2.f.Size() {
+ return false, nil
+ }
+
+ t1 := f1.f.ModTime()
+ t2 := f2.f.ModTime()
+ if t1.UnixNano() != t2.UnixNano() {
+ return false, nil
+ }
+ }
+
+ ls1, ok := f1.f.Sys().(*Stat)
+ if !ok {
+ return false, nil
+ }
+ ls2, ok := f1.f.Sys().(*Stat)
+ if !ok {
+ return false, nil
+ }
+
+ return compareStat(ls1, ls2)
+}
+
+// compareStat returns whether the stats are equivalent,
+// whether the files are considered the same file, and
+// an error
+func compareStat(ls1, ls2 *Stat) (bool, error) {
+ return ls1.Mode == ls2.Mode && ls1.Uid == ls2.Uid && ls1.Gid == ls2.Gid && ls1.Devmajor == ls2.Devmajor && ls1.Devminor == ls2.Devminor && ls1.Linkname == ls2.Linkname, nil
+}
+
+func nextPath(ctx context.Context, pathC <-chan *currentPath) (*currentPath, error) {
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case p := <-pathC:
+ return p, nil
+ }
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/diff_containerd_linux.go b/vendor/github.com/tonistiigi/fsutil/diff_containerd_linux.go
new file mode 100644
index 0000000..3c9f078
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/diff_containerd_linux.go
@@ -0,0 +1,37 @@
+package fsutil
+
+import (
+ "bytes"
+ "syscall"
+
+ "github.com/pkg/errors"
+ "github.com/stevvooe/continuity/sysx"
+)
+
+// compareSysStat returns whether the stats are equivalent,
+// whether the files are considered the same file, and
+// an error
+func compareSysStat(s1, s2 interface{}) (bool, error) {
+ ls1, ok := s1.(*syscall.Stat_t)
+ if !ok {
+ return false, nil
+ }
+ ls2, ok := s2.(*syscall.Stat_t)
+ if !ok {
+ return false, nil
+ }
+
+ return ls1.Mode == ls2.Mode && ls1.Uid == ls2.Uid && ls1.Gid == ls2.Gid && ls1.Rdev == ls2.Rdev, nil
+}
+
+func compareCapabilities(p1, p2 string) (bool, error) {
+ c1, err := sysx.LGetxattr(p1, "security.capability")
+ if err != nil && err != syscall.ENODATA {
+ return false, errors.Wrapf(err, "failed to get xattr for %s", p1)
+ }
+ c2, err := sysx.LGetxattr(p2, "security.capability")
+ if err != nil && err != syscall.ENODATA {
+ return false, errors.Wrapf(err, "failed to get xattr for %s", p2)
+ }
+ return bytes.Equal(c1, c2), nil
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/diskwriter.go b/vendor/github.com/tonistiigi/fsutil/diskwriter.go
new file mode 100644
index 0000000..a54b4a7
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/diskwriter.go
@@ -0,0 +1,353 @@
+// +build linux windows
+
+package fsutil
+
+import (
+ "archive/tar"
+ "crypto/sha256"
+ "encoding/hex"
+ "hash"
+ "io"
+ "os"
+ "path/filepath"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/docker/docker/pkg/archive"
+ "github.com/docker/docker/pkg/tarsum"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "golang.org/x/sync/errgroup"
+)
+
+type WriteToFunc func(context.Context, string, io.WriteCloser) error
+
+type DiskWriterOpt struct {
+ AsyncDataCb WriteToFunc
+ SyncDataCb WriteToFunc
+ NotifyCb func(ChangeKind, string, os.FileInfo, error) error
+}
+
+type DiskWriter struct {
+ opt DiskWriterOpt
+ dest string
+
+ wg sync.WaitGroup
+ ctx context.Context
+ cancel func()
+ eg *errgroup.Group
+}
+
+func NewDiskWriter(ctx context.Context, dest string, opt DiskWriterOpt) (*DiskWriter, error) {
+ if opt.SyncDataCb == nil && opt.AsyncDataCb == nil {
+ return nil, errors.New("no data callback specified")
+ }
+ if opt.SyncDataCb != nil && opt.AsyncDataCb != nil {
+ return nil, errors.New("can't specify both sync and async data callbacks")
+ }
+
+ ctx, cancel := context.WithCancel(ctx)
+ eg, ctx := errgroup.WithContext(ctx)
+
+ return &DiskWriter{
+ opt: opt,
+ dest: dest,
+ eg: eg,
+ ctx: ctx,
+ cancel: cancel,
+ }, nil
+}
+
+func (dw *DiskWriter) Wait(ctx context.Context) error {
+ return dw.eg.Wait()
+}
+
+func (dw *DiskWriter) HandleChange(kind ChangeKind, p string, fi os.FileInfo, err error) (retErr error) {
+ if err != nil {
+ return err
+ }
+
+ select {
+ case <-dw.ctx.Done():
+ return dw.ctx.Err()
+ default:
+ }
+
+ defer func() {
+ if retErr != nil {
+ dw.cancel()
+ }
+ }()
+
+ p = filepath.FromSlash(p)
+
+ destPath := filepath.Join(dw.dest, p)
+
+ if kind == ChangeKindDelete {
+ // todo: no need to validate if diff is trusted but is it always?
+ if err := os.RemoveAll(destPath); err != nil {
+ return errors.Wrapf(err, "failed to remove: %s", destPath)
+ }
+ if dw.opt.NotifyCb != nil {
+ if err := dw.opt.NotifyCb(kind, p, nil, nil); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+
+ stat, ok := fi.Sys().(*Stat)
+ if !ok {
+ return errors.Errorf("%s invalid change without stat information", p)
+ }
+
+ rename := true
+ oldFi, err := os.Lstat(destPath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ if kind != ChangeKindAdd {
+ return errors.Wrapf(err, "invalid addition: %s", destPath)
+ }
+ rename = false
+ } else {
+ return errors.Wrapf(err, "failed to stat %s", destPath)
+ }
+ }
+
+ if oldFi != nil && fi.IsDir() && oldFi.IsDir() {
+ if err := rewriteMetadata(destPath, stat); err != nil {
+ return errors.Wrapf(err, "error setting dir metadata for %s", destPath)
+ }
+ return nil
+ }
+
+ newPath := destPath
+ if rename {
+ newPath = filepath.Join(filepath.Dir(destPath), ".tmp."+nextSuffix())
+ }
+
+ isRegularFile := false
+
+ switch {
+ case fi.IsDir():
+ if err := os.Mkdir(newPath, fi.Mode()); err != nil {
+ return errors.Wrapf(err, "failed to create dir %s", newPath)
+ }
+ case fi.Mode()&os.ModeDevice != 0 || fi.Mode()&os.ModeNamedPipe != 0:
+ if err := handleTarTypeBlockCharFifo(newPath, stat); err != nil {
+ return errors.Wrapf(err, "failed to create device %s", newPath)
+ }
+ case fi.Mode()&os.ModeSymlink != 0:
+ if err := os.Symlink(stat.Linkname, newPath); err != nil {
+ return errors.Wrapf(err, "failed to symlink %s", newPath)
+ }
+ case stat.Linkname != "":
+ if err := os.Link(filepath.Join(dw.dest, stat.Linkname), newPath); err != nil {
+ return errors.Wrapf(err, "failed to link %s to %s", newPath, stat.Linkname)
+ }
+ default:
+ isRegularFile = true
+ file, err := os.OpenFile(newPath, os.O_CREATE|os.O_WRONLY, fi.Mode()) //todo: windows
+ if err != nil {
+ return errors.Wrapf(err, "failed to create %s", newPath)
+ }
+ if dw.opt.SyncDataCb != nil {
+ if err := dw.processChange(ChangeKindAdd, p, fi, file); err != nil {
+ file.Close()
+ return err
+ }
+ break
+ }
+ if err := file.Close(); err != nil {
+ return errors.Wrapf(err, "failed to close %s", newPath)
+ }
+ }
+
+ if err := rewriteMetadata(newPath, stat); err != nil {
+ return errors.Wrapf(err, "error setting metadata for %s", newPath)
+ }
+
+ if rename {
+ if err := os.Rename(newPath, destPath); err != nil {
+ return errors.Wrapf(err, "failed to rename %s to %s", newPath, destPath)
+ }
+ }
+
+ if isRegularFile {
+ if dw.opt.AsyncDataCb != nil {
+ dw.requestAsyncFileData(p, destPath, fi)
+ }
+ } else {
+ return dw.processChange(kind, p, fi, nil)
+ }
+
+ return nil
+}
+
+func (dw *DiskWriter) requestAsyncFileData(p, dest string, fi os.FileInfo) {
+ // todo: limit worker threads
+ dw.eg.Go(func() error {
+ if err := dw.processChange(ChangeKindAdd, p, fi, &lazyFileWriter{
+ dest: dest,
+ }); err != nil {
+ return err
+ }
+ return chtimes(dest, fi.ModTime().UnixNano()) // TODO: parent dirs
+ })
+}
+
+func (dw *DiskWriter) processChange(kind ChangeKind, p string, fi os.FileInfo, w io.WriteCloser) error {
+ origw := w
+ var hw *hashedWriter
+ if dw.opt.NotifyCb != nil {
+ var err error
+ if hw, err = newHashWriter(p, fi, w); err != nil {
+ return err
+ }
+ w = hw
+ }
+ if origw != nil {
+ fn := dw.opt.SyncDataCb
+ if fn == nil && dw.opt.AsyncDataCb != nil {
+ fn = dw.opt.AsyncDataCb
+ }
+ if err := fn(dw.ctx, p, w); err != nil {
+ return err
+ }
+ } else {
+ if hw != nil {
+ hw.Close()
+ }
+ }
+ if hw != nil {
+ return dw.opt.NotifyCb(kind, p, hw, nil)
+ }
+ return nil
+}
+
+type hashedWriter struct {
+ os.FileInfo
+ io.Writer
+ h hash.Hash
+ w io.WriteCloser
+ sum string
+}
+
+func newHashWriter(p string, fi os.FileInfo, w io.WriteCloser) (*hashedWriter, error) {
+ h, err := NewTarsumHash(p, fi)
+ if err != nil {
+ return nil, err
+ }
+ hw := &hashedWriter{
+ FileInfo: fi,
+ Writer: io.MultiWriter(w, h),
+ h: h,
+ w: w,
+ }
+ return hw, nil
+}
+
+func (hw *hashedWriter) Close() error {
+ hw.sum = string(hex.EncodeToString(hw.h.Sum(nil)))
+ if hw.w != nil {
+ return hw.w.Close()
+ }
+ return nil
+}
+
+func (hw *hashedWriter) Hash() string {
+ return hw.sum
+}
+
+type lazyFileWriter struct {
+ dest string
+ ctx context.Context
+ f *os.File
+}
+
+func (lfw *lazyFileWriter) Write(dt []byte) (int, error) {
+ if lfw.f == nil {
+ file, err := os.OpenFile(lfw.dest, os.O_WRONLY, 0) //todo: windows
+ if err != nil {
+ return 0, errors.Wrapf(err, "failed to open %s", lfw.dest)
+ }
+ lfw.f = file
+ }
+ return lfw.f.Write(dt)
+}
+
+func (lfw *lazyFileWriter) Close() error {
+ if lfw.f != nil {
+ return lfw.f.Close()
+ }
+ return nil
+}
+
+func mkdev(major int64, minor int64) uint32 {
+ return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff))
+}
+
+// Random number state.
+// We generate random temporary file names so that there's a good
+// chance the file doesn't exist yet - keeps the number of tries in
+// TempFile to a minimum.
+var rand uint32
+var randmu sync.Mutex
+
+func reseed() uint32 {
+ return uint32(time.Now().UnixNano() + int64(os.Getpid()))
+}
+
+func nextSuffix() string {
+ randmu.Lock()
+ r := rand
+ if r == 0 {
+ r = reseed()
+ }
+ r = r*1664525 + 1013904223 // constants from Numerical Recipes
+ rand = r
+ randmu.Unlock()
+ return strconv.Itoa(int(1e9 + r%1e9))[1:]
+}
+
+func NewTarsumHash(p string, fi os.FileInfo) (hash.Hash, error) {
+ stat, ok := fi.Sys().(*Stat)
+ link := ""
+ if ok {
+ link = stat.Linkname
+ }
+ if fi.IsDir() {
+ p += string(os.PathSeparator)
+ }
+ h, err := archive.FileInfoHeader(p, fi, link)
+ if err != nil {
+ return nil, err
+ }
+ h.Name = p
+ if ok {
+ h.Uid = int(stat.Uid)
+ h.Gid = int(stat.Gid)
+ h.Linkname = stat.Linkname
+ if stat.Xattrs != nil {
+ h.Xattrs = make(map[string]string)
+ for k, v := range stat.Xattrs {
+ h.Xattrs[k] = string(v)
+ }
+ }
+ }
+ tsh := &tarsumHash{h: h, Hash: sha256.New()}
+ tsh.Reset()
+ return tsh, nil
+}
+
+// Reset resets the Hash to its initial state.
+func (tsh *tarsumHash) Reset() {
+ tsh.Hash.Reset()
+ tarsum.WriteV1Header(tsh.h, tsh.Hash)
+}
+
+type tarsumHash struct {
+ hash.Hash
+ h *tar.Header
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/diskwriter_linux.go b/vendor/github.com/tonistiigi/fsutil/diskwriter_linux.go
new file mode 100644
index 0000000..c6d97eb
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/diskwriter_linux.go
@@ -0,0 +1,64 @@
+// +build linux
+
+package fsutil
+
+import (
+ "os"
+ "syscall"
+
+ "github.com/pkg/errors"
+ "github.com/stevvooe/continuity/sysx"
+ "golang.org/x/sys/unix"
+)
+
+func rewriteMetadata(p string, stat *Stat) error {
+ for key, value := range stat.Xattrs {
+ sysx.Setxattr(p, key, value, 0)
+ }
+
+ if err := os.Lchown(p, int(stat.Uid), int(stat.Gid)); err != nil {
+ return errors.Wrapf(err, "failed to lchown %s", p)
+ }
+
+ if os.FileMode(stat.Mode)&os.ModeSymlink == 0 {
+ if err := os.Chmod(p, os.FileMode(stat.Mode)); err != nil {
+ return errors.Wrapf(err, "failed to chown %s", p)
+ }
+ }
+
+ if err := chtimes(p, stat.ModTime); err != nil {
+ return errors.Wrapf(err, "failed to chtimes %s", p)
+ }
+
+ return nil
+}
+
+func chtimes(path string, un int64) error {
+ var utimes [2]unix.Timespec
+ utimes[0] = unix.NsecToTimespec(un)
+ utimes[1] = utimes[0]
+
+ if err := unix.UtimesNanoAt(unix.AT_FDCWD, path, utimes[0:], unix.AT_SYMLINK_NOFOLLOW); err != nil {
+ return errors.Wrap(err, "failed call to UtimesNanoAt")
+ }
+
+ return nil
+}
+
+// handleTarTypeBlockCharFifo is an OS-specific helper function used by
+// createTarFile to handle the following types of header: Block; Char; Fifo
+func handleTarTypeBlockCharFifo(path string, stat *Stat) error {
+ mode := uint32(stat.Mode & 07777)
+ if os.FileMode(stat.Mode)&os.ModeCharDevice != 0 {
+ mode |= syscall.S_IFCHR
+ } else if os.FileMode(stat.Mode)&os.ModeNamedPipe != 0 {
+ mode |= syscall.S_IFIFO
+ } else {
+ mode |= syscall.S_IFBLK
+ }
+
+ if err := syscall.Mknod(path, mode, int(mkdev(stat.Devmajor, stat.Devminor))); err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/diskwriter_windows.go b/vendor/github.com/tonistiigi/fsutil/diskwriter_windows.go
new file mode 100644
index 0000000..16a26f0
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/diskwriter_windows.go
@@ -0,0 +1,25 @@
+// +build windows
+
+package fsutil
+
+import (
+ "os"
+ "time"
+
+ "github.com/pkg/errors"
+)
+
+func rewriteMetadata(p string, stat *Stat) error {
+ return chtimes(p, stat.ModTime)
+}
+
+func chtimes(path string, un int64) error {
+ mtime := time.Unix(0, un)
+ return os.Chtimes(path, mtime, mtime)
+}
+
+// handleTarTypeBlockCharFifo is an OS-specific helper function used by
+// createTarFile to handle the following types of header: Block; Char; Fifo
+func handleTarTypeBlockCharFifo(path string, stat *Stat) error {
+ return errors.New("Not implemented on windows")
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/generate.go b/vendor/github.com/tonistiigi/fsutil/generate.go
new file mode 100644
index 0000000..e433195
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/generate.go
@@ -0,0 +1,3 @@
+package fsutil
+
+//go:generate protoc --gogoslick_out=. stat.proto wire.proto
diff --git a/vendor/github.com/tonistiigi/fsutil/hardlinks.go b/vendor/github.com/tonistiigi/fsutil/hardlinks.go
new file mode 100644
index 0000000..e598ead
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/hardlinks.go
@@ -0,0 +1,46 @@
+package fsutil
+
+import (
+ "os"
+
+ "github.com/pkg/errors"
+)
+
+// Hardlinks validates that all targets for links were part of the changes
+
+type Hardlinks struct {
+ seenFiles map[string]struct{}
+}
+
+func (v *Hardlinks) HandleChange(kind ChangeKind, p string, fi os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+
+ if v.seenFiles == nil {
+ v.seenFiles = make(map[string]struct{})
+ }
+
+ if kind == ChangeKindDelete {
+ return nil
+ }
+
+ stat, ok := fi.Sys().(*Stat)
+ if !ok {
+ return errors.Errorf("invalid change without stat info: %s", p)
+ }
+
+ if fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
+ return nil
+ }
+
+ if len(stat.Linkname) > 0 {
+ if _, ok := v.seenFiles[stat.Linkname]; !ok {
+ return errors.Errorf("invalid link %s to unknown path: %q", p, stat.Linkname)
+ }
+ } else {
+ v.seenFiles[p] = struct{}{}
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/readme.md b/vendor/github.com/tonistiigi/fsutil/readme.md
new file mode 100644
index 0000000..5ce685b
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/readme.md
@@ -0,0 +1,45 @@
+Incremental file directory sync tools in golang.
+
+```
+BENCH_FILE_SIZE=10000 ./bench.test --test.bench .
+BenchmarkCopyWithTar10-4 2000 995242 ns/op
+BenchmarkCopyWithTar50-4 300 4710021 ns/op
+BenchmarkCopyWithTar200-4 100 16627260 ns/op
+BenchmarkCopyWithTar1000-4 20 60031459 ns/op
+BenchmarkCPA10-4 1000 1678367 ns/op
+BenchmarkCPA50-4 500 3690306 ns/op
+BenchmarkCPA200-4 200 9495066 ns/op
+BenchmarkCPA1000-4 50 29769289 ns/op
+BenchmarkDiffCopy10-4 2000 943889 ns/op
+BenchmarkDiffCopy50-4 500 3285950 ns/op
+BenchmarkDiffCopy200-4 200 8563792 ns/op
+BenchmarkDiffCopy1000-4 50 29511340 ns/op
+BenchmarkDiffCopyProto10-4 2000 944615 ns/op
+BenchmarkDiffCopyProto50-4 500 3334940 ns/op
+BenchmarkDiffCopyProto200-4 200 9420038 ns/op
+BenchmarkDiffCopyProto1000-4 50 30632429 ns/op
+BenchmarkIncrementalDiffCopy10-4 2000 691993 ns/op
+BenchmarkIncrementalDiffCopy50-4 1000 1304253 ns/op
+BenchmarkIncrementalDiffCopy200-4 500 3306519 ns/op
+BenchmarkIncrementalDiffCopy1000-4 200 10211343 ns/op
+BenchmarkIncrementalDiffCopy5000-4 20 55194427 ns/op
+BenchmarkIncrementalDiffCopy10000-4 20 91759289 ns/op
+BenchmarkIncrementalCopyWithTar10-4 2000 1020258 ns/op
+BenchmarkIncrementalCopyWithTar50-4 300 5348786 ns/op
+BenchmarkIncrementalCopyWithTar200-4 100 19495000 ns/op
+BenchmarkIncrementalCopyWithTar1000-4 20 70338507 ns/op
+BenchmarkIncrementalRsync10-4 30 45215754 ns/op
+BenchmarkIncrementalRsync50-4 30 45837260 ns/op
+BenchmarkIncrementalRsync200-4 30 48780614 ns/op
+BenchmarkIncrementalRsync1000-4 20 54801892 ns/op
+BenchmarkIncrementalRsync5000-4 20 84782542 ns/op
+BenchmarkIncrementalRsync10000-4 10 103355108 ns/op
+BenchmarkRsync10-4 30 46776470 ns/op
+BenchmarkRsync50-4 30 48601555 ns/op
+BenchmarkRsync200-4 20 59642691 ns/op
+BenchmarkRsync1000-4 20 101343010 ns/op
+BenchmarkGnuTar10-4 500 3171448 ns/op
+BenchmarkGnuTar50-4 300 5030296 ns/op
+BenchmarkGnuTar200-4 100 10464313 ns/op
+BenchmarkGnuTar1000-4 50 30375257 ns/op
+``` \ No newline at end of file
diff --git a/vendor/github.com/tonistiigi/fsutil/receive.go b/vendor/github.com/tonistiigi/fsutil/receive.go
new file mode 100644
index 0000000..e7cee2b
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/receive.go
@@ -0,0 +1,210 @@
+// +build linux windows
+
+package fsutil
+
+import (
+ "io"
+ "os"
+ "sync"
+
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "golang.org/x/sync/errgroup"
+)
+
+func Receive(ctx context.Context, conn Stream, dest string, notifyHashed ChangeFunc) error {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ r := &receiver{
+ conn: &syncStream{Stream: conn},
+ dest: dest,
+ files: make(map[string]uint32),
+ pipes: make(map[uint32]io.WriteCloser),
+ notifyHashed: notifyHashed,
+ }
+ return r.run(ctx)
+}
+
+type receiver struct {
+ dest string
+ conn Stream
+ files map[string]uint32
+ pipes map[uint32]io.WriteCloser
+ mu sync.RWMutex
+ muPipes sync.RWMutex
+
+ notifyHashed ChangeFunc
+ orderValidator Validator
+ hlValidator Hardlinks
+}
+
+type dynamicWalker struct {
+ walkChan chan *currentPath
+ closed bool
+}
+
+func newDynamicWalker() *dynamicWalker {
+ return &dynamicWalker{
+ walkChan: make(chan *currentPath, 128),
+ }
+}
+
+func (w *dynamicWalker) update(p *currentPath) error {
+ if w.closed {
+ return errors.New("walker is closed")
+ }
+ if p == nil {
+ close(w.walkChan)
+ return nil
+ }
+ w.walkChan <- p
+ return nil
+}
+
+func (w *dynamicWalker) fill(ctx context.Context, pathC chan<- *currentPath) error {
+ for {
+ select {
+ case p, ok := <-w.walkChan:
+ if !ok {
+ return nil
+ }
+ pathC <- p
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+ return nil
+}
+
+func (r *receiver) run(ctx context.Context) error {
+ g, ctx := errgroup.WithContext(ctx)
+
+ dw, err := NewDiskWriter(ctx, r.dest, DiskWriterOpt{
+ AsyncDataCb: r.asyncDataFunc,
+ NotifyCb: r.notifyHashed,
+ })
+ if err != nil {
+ return err
+ }
+
+ w := newDynamicWalker()
+
+ g.Go(func() error {
+ err := doubleWalkDiff(ctx, dw.HandleChange, GetWalkerFn(r.dest), w.fill)
+ if err != nil {
+ return err
+ }
+ if err := dw.Wait(ctx); err != nil {
+ return err
+ }
+ r.conn.SendMsg(&Packet{Type: PACKET_FIN})
+ return nil
+ })
+
+ g.Go(func() error {
+ var i uint32 = 0
+
+ var p Packet
+ for {
+ p = Packet{Data: p.Data[:0]}
+ if err := r.conn.RecvMsg(&p); err != nil {
+ return err
+ }
+ switch p.Type {
+ case PACKET_STAT:
+ if p.Stat == nil {
+ if err := w.update(nil); err != nil {
+ return err
+ }
+ break
+ }
+ if fileCanRequestData(os.FileMode(p.Stat.Mode)) {
+ r.mu.Lock()
+ r.files[p.Stat.Path] = i
+ r.mu.Unlock()
+ }
+ i++
+ cp := &currentPath{path: p.Stat.Path, f: &StatInfo{p.Stat}}
+ if err := r.orderValidator.HandleChange(ChangeKindAdd, cp.path, cp.f, nil); err != nil {
+ return err
+ }
+ if err := r.hlValidator.HandleChange(ChangeKindAdd, cp.path, cp.f, nil); err != nil {
+ return err
+ }
+ if err := w.update(cp); err != nil {
+ return err
+ }
+ case PACKET_DATA:
+ r.muPipes.Lock()
+ pw, ok := r.pipes[p.ID]
+ r.muPipes.Unlock()
+ if !ok {
+ return errors.Errorf("invalid file request %s", p.ID)
+ }
+ if len(p.Data) == 0 {
+ if err := pw.Close(); err != nil {
+ return err
+ }
+ } else {
+ if _, err := pw.Write(p.Data); err != nil {
+ return err
+ }
+ }
+ case PACKET_FIN:
+ return nil
+ }
+ }
+ })
+ return g.Wait()
+}
+
+func (r *receiver) asyncDataFunc(ctx context.Context, p string, wc io.WriteCloser) error {
+ r.mu.Lock()
+ id, ok := r.files[p]
+ if !ok {
+ r.mu.Unlock()
+ return errors.Errorf("invalid file request %s", p)
+ }
+ delete(r.files, p)
+ r.mu.Unlock()
+
+ wwc := newWrappedWriteCloser(wc)
+ r.muPipes.Lock()
+ r.pipes[id] = wwc
+ r.muPipes.Unlock()
+ if err := r.conn.SendMsg(&Packet{Type: PACKET_REQ, ID: id}); err != nil {
+ return err
+ }
+ err := wwc.Wait(ctx)
+ r.muPipes.Lock()
+ delete(r.pipes, id)
+ r.muPipes.Unlock()
+ return err
+}
+
+type wrappedWriteCloser struct {
+ io.WriteCloser
+ err error
+ once sync.Once
+ done chan struct{}
+}
+
+func newWrappedWriteCloser(wc io.WriteCloser) *wrappedWriteCloser {
+ return &wrappedWriteCloser{WriteCloser: wc, done: make(chan struct{})}
+}
+
+func (w *wrappedWriteCloser) Close() error {
+ w.err = w.WriteCloser.Close()
+ w.once.Do(func() { close(w.done) })
+ return w.err
+}
+
+func (w *wrappedWriteCloser) Wait(ctx context.Context) error {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-w.done:
+ return w.err
+ }
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/receive_unsupported.go b/vendor/github.com/tonistiigi/fsutil/receive_unsupported.go
new file mode 100644
index 0000000..8e83342
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/receive_unsupported.go
@@ -0,0 +1,14 @@
+// +build !linux,!windows
+
+package fsutil
+
+import (
+ "runtime"
+
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+func Receive(ctx context.Context, conn Stream, dest string, notifyHashed ChangeFunc) error {
+ return errors.Errorf("receive is unsupported in %s", runtime.GOOS)
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/send.go b/vendor/github.com/tonistiigi/fsutil/send.go
new file mode 100644
index 0000000..c7b6382
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/send.go
@@ -0,0 +1,201 @@
+package fsutil
+
+import (
+ "io"
+ "os"
+ "path/filepath"
+ "sync"
+
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+ "golang.org/x/sync/errgroup"
+)
+
+var bufPool = sync.Pool{
+ New: func() interface{} {
+ return make([]byte, 32*1<<10)
+ },
+}
+
+type Stream interface {
+ RecvMsg(interface{}) error
+ SendMsg(m interface{}) error
+ Context() context.Context
+}
+
+func Send(ctx context.Context, conn Stream, root string, opt *WalkOpt, progressCb func(int, bool)) error {
+ s := &sender{
+ conn: &syncStream{Stream: conn},
+ root: root,
+ opt: opt,
+ files: make(map[uint32]string),
+ progressCb: progressCb,
+ sendpipeline: make(chan *sendHandle, 128),
+ }
+ return s.run(ctx)
+}
+
+type sendHandle struct {
+ id uint32
+ path string
+}
+
+type sender struct {
+ conn Stream
+ opt *WalkOpt
+ root string
+ files map[uint32]string
+ mu sync.RWMutex
+ progressCb func(int, bool)
+ progressCurrent int
+ sendpipeline chan *sendHandle
+}
+
+func (s *sender) run(ctx context.Context) error {
+ g, ctx := errgroup.WithContext(ctx)
+
+ defer s.updateProgress(0, true)
+
+ g.Go(func() error {
+ return s.walk(ctx)
+ })
+
+ for i := 0; i < 4; i++ {
+ g.Go(func() error {
+ for h := range s.sendpipeline {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+ if err := s.sendFile(h); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ }
+
+ g.Go(func() error {
+ defer close(s.sendpipeline)
+
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+ var p Packet
+ if err := s.conn.RecvMsg(&p); err != nil {
+ return err
+ }
+ switch p.Type {
+ case PACKET_REQ:
+ if err := s.queue(p.ID); err != nil {
+ return err
+ }
+ case PACKET_FIN:
+ return s.conn.SendMsg(&Packet{Type: PACKET_FIN})
+ }
+ }
+ })
+
+ return g.Wait()
+}
+
+func (s *sender) updateProgress(size int, last bool) {
+ if s.progressCb != nil {
+ s.progressCurrent += size
+ s.progressCb(s.progressCurrent, last)
+ }
+}
+
+func (s *sender) queue(id uint32) error {
+ s.mu.Lock()
+ p, ok := s.files[id]
+ if !ok {
+ s.mu.Unlock()
+ return errors.Errorf("invalid file id %d", id)
+ }
+ delete(s.files, id)
+ s.mu.Unlock()
+ s.sendpipeline <- &sendHandle{id, p}
+ return nil
+}
+
+func (s *sender) sendFile(h *sendHandle) error {
+ f, err := os.Open(filepath.Join(s.root, h.path))
+ if err == nil {
+ buf := bufPool.Get().([]byte)
+ defer bufPool.Put(buf)
+ if _, err := io.CopyBuffer(&fileSender{sender: s, id: h.id}, f, buf); err != nil {
+ return err
+ }
+ }
+ return s.conn.SendMsg(&Packet{ID: h.id, Type: PACKET_DATA})
+}
+
+func (s *sender) walk(ctx context.Context) error {
+ var i uint32 = 0
+ err := Walk(ctx, s.root, s.opt, func(path string, fi os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ stat, ok := fi.Sys().(*Stat)
+ if !ok {
+ return errors.Wrapf(err, "invalid fileinfo without stat info: %s", path)
+ }
+
+ p := &Packet{
+ Type: PACKET_STAT,
+ Stat: stat,
+ }
+ if fileCanRequestData(os.FileMode(stat.Mode)) {
+ s.mu.Lock()
+ s.files[i] = stat.Path
+ s.mu.Unlock()
+ }
+ i++
+ s.updateProgress(p.Size(), false)
+ return errors.Wrapf(s.conn.SendMsg(p), "failed to send stat %s", path)
+ })
+ if err != nil {
+ return err
+ }
+ return errors.Wrapf(s.conn.SendMsg(&Packet{Type: PACKET_STAT}), "failed to send last stat")
+}
+
+func fileCanRequestData(m os.FileMode) bool {
+ // avoid updating this function as it needs to match between sender/receiver.
+ // version if needed
+ return m&os.ModeType == 0
+}
+
+type fileSender struct {
+ sender *sender
+ id uint32
+}
+
+func (fs *fileSender) Write(dt []byte) (int, error) {
+ if len(dt) == 0 {
+ return 0, nil
+ }
+ p := &Packet{Type: PACKET_DATA, ID: fs.id, Data: dt}
+ if err := fs.sender.conn.SendMsg(p); err != nil {
+ return 0, err
+ }
+ fs.sender.updateProgress(p.Size(), false)
+ return len(dt), nil
+}
+
+type syncStream struct {
+ Stream
+ mu sync.Mutex
+}
+
+func (ss *syncStream) SendMsg(m interface{}) error {
+ ss.mu.Lock()
+ err := ss.Stream.SendMsg(m)
+ ss.mu.Unlock()
+ return err
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/stat.pb.go b/vendor/github.com/tonistiigi/fsutil/stat.pb.go
new file mode 100644
index 0000000..3f6925e
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/stat.pb.go
@@ -0,0 +1,931 @@
+// Code generated by protoc-gen-gogo.
+// source: stat.proto
+// DO NOT EDIT!
+
+/*
+ Package fsutil is a generated protocol buffer package.
+
+ It is generated from these files:
+ stat.proto
+ wire.proto
+
+ It has these top-level messages:
+ Stat
+ Packet
+*/
+package fsutil
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+import bytes "bytes"
+
+import strings "strings"
+import reflect "reflect"
+import github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
+
+type Stat struct {
+ Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+ Mode uint32 `protobuf:"varint,2,opt,name=mode,proto3" json:"mode,omitempty"`
+ Uid uint32 `protobuf:"varint,3,opt,name=uid,proto3" json:"uid,omitempty"`
+ Gid uint32 `protobuf:"varint,4,opt,name=gid,proto3" json:"gid,omitempty"`
+ Size_ int64 `protobuf:"varint,5,opt,name=size,proto3" json:"size,omitempty"`
+ ModTime int64 `protobuf:"varint,6,opt,name=modTime,proto3" json:"modTime,omitempty"`
+ // int32 typeflag = 7;
+ Linkname string `protobuf:"bytes,7,opt,name=linkname,proto3" json:"linkname,omitempty"`
+ Devmajor int64 `protobuf:"varint,8,opt,name=devmajor,proto3" json:"devmajor,omitempty"`
+ Devminor int64 `protobuf:"varint,9,opt,name=devminor,proto3" json:"devminor,omitempty"`
+ Xattrs map[string][]byte `protobuf:"bytes,10,rep,name=xattrs" json:"xattrs,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+}
+
+func (m *Stat) Reset() { *m = Stat{} }
+func (*Stat) ProtoMessage() {}
+func (*Stat) Descriptor() ([]byte, []int) { return fileDescriptorStat, []int{0} }
+
+func (m *Stat) GetPath() string {
+ if m != nil {
+ return m.Path
+ }
+ return ""
+}
+
+func (m *Stat) GetMode() uint32 {
+ if m != nil {
+ return m.Mode
+ }
+ return 0
+}
+
+func (m *Stat) GetUid() uint32 {
+ if m != nil {
+ return m.Uid
+ }
+ return 0
+}
+
+func (m *Stat) GetGid() uint32 {
+ if m != nil {
+ return m.Gid
+ }
+ return 0
+}
+
+func (m *Stat) GetSize_() int64 {
+ if m != nil {
+ return m.Size_
+ }
+ return 0
+}
+
+func (m *Stat) GetModTime() int64 {
+ if m != nil {
+ return m.ModTime
+ }
+ return 0
+}
+
+func (m *Stat) GetLinkname() string {
+ if m != nil {
+ return m.Linkname
+ }
+ return ""
+}
+
+func (m *Stat) GetDevmajor() int64 {
+ if m != nil {
+ return m.Devmajor
+ }
+ return 0
+}
+
+func (m *Stat) GetDevminor() int64 {
+ if m != nil {
+ return m.Devminor
+ }
+ return 0
+}
+
+func (m *Stat) GetXattrs() map[string][]byte {
+ if m != nil {
+ return m.Xattrs
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Stat)(nil), "fsutil.Stat")
+}
+func (this *Stat) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Stat)
+ if !ok {
+ that2, ok := that.(Stat)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Path != that1.Path {
+ return false
+ }
+ if this.Mode != that1.Mode {
+ return false
+ }
+ if this.Uid != that1.Uid {
+ return false
+ }
+ if this.Gid != that1.Gid {
+ return false
+ }
+ if this.Size_ != that1.Size_ {
+ return false
+ }
+ if this.ModTime != that1.ModTime {
+ return false
+ }
+ if this.Linkname != that1.Linkname {
+ return false
+ }
+ if this.Devmajor != that1.Devmajor {
+ return false
+ }
+ if this.Devminor != that1.Devminor {
+ return false
+ }
+ if len(this.Xattrs) != len(that1.Xattrs) {
+ return false
+ }
+ for i := range this.Xattrs {
+ if !bytes.Equal(this.Xattrs[i], that1.Xattrs[i]) {
+ return false
+ }
+ }
+ return true
+}
+func (this *Stat) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 14)
+ s = append(s, "&fsutil.Stat{")
+ s = append(s, "Path: "+fmt.Sprintf("%#v", this.Path)+",\n")
+ s = append(s, "Mode: "+fmt.Sprintf("%#v", this.Mode)+",\n")
+ s = append(s, "Uid: "+fmt.Sprintf("%#v", this.Uid)+",\n")
+ s = append(s, "Gid: "+fmt.Sprintf("%#v", this.Gid)+",\n")
+ s = append(s, "Size_: "+fmt.Sprintf("%#v", this.Size_)+",\n")
+ s = append(s, "ModTime: "+fmt.Sprintf("%#v", this.ModTime)+",\n")
+ s = append(s, "Linkname: "+fmt.Sprintf("%#v", this.Linkname)+",\n")
+ s = append(s, "Devmajor: "+fmt.Sprintf("%#v", this.Devmajor)+",\n")
+ s = append(s, "Devminor: "+fmt.Sprintf("%#v", this.Devminor)+",\n")
+ keysForXattrs := make([]string, 0, len(this.Xattrs))
+ for k, _ := range this.Xattrs {
+ keysForXattrs = append(keysForXattrs, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForXattrs)
+ mapStringForXattrs := "map[string][]byte{"
+ for _, k := range keysForXattrs {
+ mapStringForXattrs += fmt.Sprintf("%#v: %#v,", k, this.Xattrs[k])
+ }
+ mapStringForXattrs += "}"
+ if this.Xattrs != nil {
+ s = append(s, "Xattrs: "+mapStringForXattrs+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringStat(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func (m *Stat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Stat) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if len(m.Path) > 0 {
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(len(m.Path)))
+ i += copy(dAtA[i:], m.Path)
+ }
+ if m.Mode != 0 {
+ dAtA[i] = 0x10
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(m.Mode))
+ }
+ if m.Uid != 0 {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(m.Uid))
+ }
+ if m.Gid != 0 {
+ dAtA[i] = 0x20
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(m.Gid))
+ }
+ if m.Size_ != 0 {
+ dAtA[i] = 0x28
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(m.Size_))
+ }
+ if m.ModTime != 0 {
+ dAtA[i] = 0x30
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(m.ModTime))
+ }
+ if len(m.Linkname) > 0 {
+ dAtA[i] = 0x3a
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(len(m.Linkname)))
+ i += copy(dAtA[i:], m.Linkname)
+ }
+ if m.Devmajor != 0 {
+ dAtA[i] = 0x40
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(m.Devmajor))
+ }
+ if m.Devminor != 0 {
+ dAtA[i] = 0x48
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(m.Devminor))
+ }
+ if len(m.Xattrs) > 0 {
+ for k, _ := range m.Xattrs {
+ dAtA[i] = 0x52
+ i++
+ v := m.Xattrs[k]
+ byteSize := 0
+ if len(v) > 0 {
+ byteSize = 1 + len(v) + sovStat(uint64(len(v)))
+ }
+ mapSize := 1 + len(k) + sovStat(uint64(len(k))) + byteSize
+ i = encodeVarintStat(dAtA, i, uint64(mapSize))
+ dAtA[i] = 0xa
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(len(k)))
+ i += copy(dAtA[i:], k)
+ if len(v) > 0 {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintStat(dAtA, i, uint64(len(v)))
+ i += copy(dAtA[i:], v)
+ }
+ }
+ }
+ return i, nil
+}
+
+func encodeFixed64Stat(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Stat(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintStat(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func (m *Stat) Size() (n int) {
+ var l int
+ _ = l
+ l = len(m.Path)
+ if l > 0 {
+ n += 1 + l + sovStat(uint64(l))
+ }
+ if m.Mode != 0 {
+ n += 1 + sovStat(uint64(m.Mode))
+ }
+ if m.Uid != 0 {
+ n += 1 + sovStat(uint64(m.Uid))
+ }
+ if m.Gid != 0 {
+ n += 1 + sovStat(uint64(m.Gid))
+ }
+ if m.Size_ != 0 {
+ n += 1 + sovStat(uint64(m.Size_))
+ }
+ if m.ModTime != 0 {
+ n += 1 + sovStat(uint64(m.ModTime))
+ }
+ l = len(m.Linkname)
+ if l > 0 {
+ n += 1 + l + sovStat(uint64(l))
+ }
+ if m.Devmajor != 0 {
+ n += 1 + sovStat(uint64(m.Devmajor))
+ }
+ if m.Devminor != 0 {
+ n += 1 + sovStat(uint64(m.Devminor))
+ }
+ if len(m.Xattrs) > 0 {
+ for k, v := range m.Xattrs {
+ _ = k
+ _ = v
+ l = 0
+ if len(v) > 0 {
+ l = 1 + len(v) + sovStat(uint64(len(v)))
+ }
+ mapEntrySize := 1 + len(k) + sovStat(uint64(len(k))) + l
+ n += mapEntrySize + 1 + sovStat(uint64(mapEntrySize))
+ }
+ }
+ return n
+}
+
+func sovStat(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozStat(x uint64) (n int) {
+ return sovStat(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *Stat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ keysForXattrs := make([]string, 0, len(this.Xattrs))
+ for k, _ := range this.Xattrs {
+ keysForXattrs = append(keysForXattrs, k)
+ }
+ github_com_gogo_protobuf_sortkeys.Strings(keysForXattrs)
+ mapStringForXattrs := "map[string][]byte{"
+ for _, k := range keysForXattrs {
+ mapStringForXattrs += fmt.Sprintf("%v: %v,", k, this.Xattrs[k])
+ }
+ mapStringForXattrs += "}"
+ s := strings.Join([]string{`&Stat{`,
+ `Path:` + fmt.Sprintf("%v", this.Path) + `,`,
+ `Mode:` + fmt.Sprintf("%v", this.Mode) + `,`,
+ `Uid:` + fmt.Sprintf("%v", this.Uid) + `,`,
+ `Gid:` + fmt.Sprintf("%v", this.Gid) + `,`,
+ `Size_:` + fmt.Sprintf("%v", this.Size_) + `,`,
+ `ModTime:` + fmt.Sprintf("%v", this.ModTime) + `,`,
+ `Linkname:` + fmt.Sprintf("%v", this.Linkname) + `,`,
+ `Devmajor:` + fmt.Sprintf("%v", this.Devmajor) + `,`,
+ `Devminor:` + fmt.Sprintf("%v", this.Devminor) + `,`,
+ `Xattrs:` + mapStringForXattrs + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringStat(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *Stat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Stat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Stat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Path", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthStat
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Path = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Mode", wireType)
+ }
+ m.Mode = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Mode |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Uid", wireType)
+ }
+ m.Uid = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Uid |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Gid", wireType)
+ }
+ m.Gid = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Gid |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Size_", wireType)
+ }
+ m.Size_ = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Size_ |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ModTime", wireType)
+ }
+ m.ModTime = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ModTime |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Linkname", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthStat
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Linkname = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 8:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Devmajor", wireType)
+ }
+ m.Devmajor = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Devmajor |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 9:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Devminor", wireType)
+ }
+ m.Devminor = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Devminor |= (int64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 10:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Xattrs", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthStat
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var keykey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ keykey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var stringLenmapkey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLenmapkey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLenmapkey := int(stringLenmapkey)
+ if intStringLenmapkey < 0 {
+ return ErrInvalidLengthStat
+ }
+ postStringIndexmapkey := iNdEx + intStringLenmapkey
+ if postStringIndexmapkey > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapkey := string(dAtA[iNdEx:postStringIndexmapkey])
+ iNdEx = postStringIndexmapkey
+ if m.Xattrs == nil {
+ m.Xattrs = make(map[string][]byte)
+ }
+ if iNdEx < postIndex {
+ var valuekey uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ valuekey |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ var mapbyteLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ mapbyteLen |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intMapbyteLen := int(mapbyteLen)
+ if intMapbyteLen < 0 {
+ return ErrInvalidLengthStat
+ }
+ postbytesIndex := iNdEx + intMapbyteLen
+ if postbytesIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ mapvalue := make([]byte, mapbyteLen)
+ copy(mapvalue, dAtA[iNdEx:postbytesIndex])
+ iNdEx = postbytesIndex
+ m.Xattrs[mapkey] = mapvalue
+ } else {
+ var mapvalue []byte
+ m.Xattrs[mapkey] = mapvalue
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipStat(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthStat
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipStat(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthStat
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowStat
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipStat(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthStat = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowStat = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("stat.proto", fileDescriptorStat) }
+
+var fileDescriptorStat = []byte{
+ // 303 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x4c, 0x91, 0xb1, 0x4e, 0xf3, 0x30,
+ 0x14, 0x85, 0x73, 0x9b, 0x36, 0x6d, 0xdd, 0xff, 0x97, 0x90, 0xc5, 0x70, 0xd5, 0xc1, 0x8a, 0x98,
+ 0x32, 0xa0, 0x08, 0xc1, 0x02, 0x8c, 0x48, 0xbc, 0x40, 0x60, 0x60, 0x35, 0xb2, 0x29, 0xa6, 0x4d,
+ 0x5c, 0x25, 0x4e, 0x45, 0x99, 0x78, 0x04, 0x1e, 0x83, 0xd7, 0x60, 0x63, 0xec, 0xc8, 0x48, 0xcc,
+ 0xc2, 0xd8, 0x47, 0x40, 0x76, 0xda, 0xc2, 0x76, 0xce, 0x77, 0x7c, 0x65, 0x9d, 0x7b, 0x09, 0xa9,
+ 0x0c, 0x37, 0xe9, 0xbc, 0xd4, 0x46, 0xd3, 0xe8, 0xae, 0xaa, 0x8d, 0x9a, 0x1d, 0xbc, 0x75, 0x48,
+ 0xf7, 0xca, 0x70, 0x43, 0x29, 0xe9, 0xce, 0xb9, 0xb9, 0x47, 0x88, 0x21, 0x19, 0x66, 0x5e, 0x3b,
+ 0x96, 0x6b, 0x21, 0xb1, 0x13, 0x43, 0xf2, 0x3f, 0xf3, 0x9a, 0xee, 0x91, 0xb0, 0x56, 0x02, 0x43,
+ 0x8f, 0x9c, 0x74, 0x64, 0xa2, 0x04, 0x76, 0x5b, 0x32, 0x51, 0xc2, 0xcd, 0x55, 0xea, 0x49, 0x62,
+ 0x2f, 0x86, 0x24, 0xcc, 0xbc, 0xa6, 0x48, 0xfa, 0xb9, 0x16, 0xd7, 0x2a, 0x97, 0x18, 0x79, 0xbc,
+ 0xb5, 0x74, 0x4c, 0x06, 0x33, 0x55, 0x4c, 0x0b, 0x9e, 0x4b, 0xec, 0xfb, 0xdf, 0x77, 0xde, 0x65,
+ 0x42, 0x2e, 0x72, 0xfe, 0xa0, 0x4b, 0x1c, 0xf8, 0xb1, 0x9d, 0xdf, 0x66, 0xaa, 0xd0, 0x25, 0x0e,
+ 0x7f, 0x33, 0xe7, 0xe9, 0x11, 0x89, 0x1e, 0xb9, 0x31, 0x65, 0x85, 0x24, 0x0e, 0x93, 0xd1, 0x31,
+ 0xa6, 0x6d, 0xdf, 0xd4, 0x75, 0x4d, 0x6f, 0x7c, 0x74, 0x59, 0x98, 0x72, 0x99, 0x6d, 0xde, 0x8d,
+ 0xcf, 0xc8, 0xe8, 0x0f, 0x76, 0xa5, 0xa6, 0x72, 0xb9, 0xd9, 0x86, 0x93, 0x74, 0x9f, 0xf4, 0x16,
+ 0x7c, 0x56, 0xb7, 0xdb, 0xf8, 0x97, 0xb5, 0xe6, 0xbc, 0x73, 0x0a, 0x17, 0x87, 0xab, 0x86, 0x05,
+ 0x1f, 0x0d, 0x0b, 0xd6, 0x0d, 0x83, 0x67, 0xcb, 0xe0, 0xd5, 0x32, 0x78, 0xb7, 0x0c, 0x56, 0x96,
+ 0xc1, 0xa7, 0x65, 0xf0, 0x6d, 0x59, 0xb0, 0xb6, 0x0c, 0x5e, 0xbe, 0x58, 0x70, 0x1b, 0xf9, 0x03,
+ 0x9c, 0xfc, 0x04, 0x00, 0x00, 0xff, 0xff, 0x19, 0x97, 0x14, 0xf4, 0x8e, 0x01, 0x00, 0x00,
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/stat.proto b/vendor/github.com/tonistiigi/fsutil/stat.proto
new file mode 100644
index 0000000..e279413
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/stat.proto
@@ -0,0 +1,17 @@
+syntax = "proto3";
+
+package fsutil;
+
+message Stat {
+ string path = 1;
+ uint32 mode = 2;
+ uint32 uid = 3;
+ uint32 gid = 4;
+ int64 size = 5;
+ int64 modTime = 6;
+ // int32 typeflag = 7;
+ string linkname = 7;
+ int64 devmajor = 8;
+ int64 devminor = 9;
+ map<string, bytes> xattrs = 10;
+} \ No newline at end of file
diff --git a/vendor/github.com/tonistiigi/fsutil/validator.go b/vendor/github.com/tonistiigi/fsutil/validator.go
new file mode 100644
index 0000000..e4a5eba
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/validator.go
@@ -0,0 +1,88 @@
+package fsutil
+
+import (
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/pkg/errors"
+)
+
+type parent struct {
+ dir string
+ last string
+}
+
+type Validator struct {
+ parentDirs []parent
+}
+
+func (v *Validator) HandleChange(kind ChangeKind, p string, fi os.FileInfo, err error) (retErr error) {
+ if err != nil {
+ return err
+ }
+ // test that all paths are in order and all parent dirs were present
+ if v.parentDirs == nil {
+ v.parentDirs = make([]parent, 1, 10)
+ }
+ if p != filepath.Clean(p) {
+ return errors.Errorf("invalid unclean path %s", p)
+ }
+ if filepath.IsAbs(p) {
+ return errors.Errorf("abolute path %s not allowed", p)
+ }
+ dir := filepath.Dir(p)
+ base := filepath.Base(p)
+ if dir == "." {
+ dir = ""
+ }
+ if dir == ".." || strings.HasPrefix(p, "../") {
+ return errors.Errorf("invalid path: %s", p)
+ }
+
+ // find a parent dir from saved records
+ i := sort.Search(len(v.parentDirs), func(i int) bool {
+ return ComparePath(v.parentDirs[len(v.parentDirs)-1-i].dir, dir) <= 0
+ })
+ i = len(v.parentDirs) - 1 - i
+ if i != len(v.parentDirs)-1 { // skipping back to grandparent
+ v.parentDirs = v.parentDirs[:i+1]
+ }
+
+ if dir != v.parentDirs[len(v.parentDirs)-1].dir || v.parentDirs[i].last >= base {
+ return errors.Errorf("changes out of order: %q %q", p, filepath.Join(v.parentDirs[i].dir, v.parentDirs[i].last))
+ }
+ v.parentDirs[i].last = base
+ if kind != ChangeKindDelete && fi.IsDir() {
+ v.parentDirs = append(v.parentDirs, parent{
+ dir: filepath.Join(dir, base),
+ last: "",
+ })
+ }
+ // todo: validate invalid mode combinations
+ return err
+}
+
+func ComparePath(p1, p2 string) int {
+ // byte-by-byte comparison to be compatible with str<>str
+ min := min(len(p1), len(p2))
+ for i := 0; i < min; i++ {
+ switch {
+ case p1[i] == p2[i]:
+ continue
+ case p2[i] != '/' && p1[i] < p2[i] || p1[i] == '/':
+ return -1
+ default:
+ return 1
+ }
+ }
+ return len(p1) - len(p2)
+}
+
+func min(x, y int) int {
+ if x < y {
+ return x
+ }
+ return y
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/walker.go b/vendor/github.com/tonistiigi/fsutil/walker.go
new file mode 100644
index 0000000..bfec609
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/walker.go
@@ -0,0 +1,170 @@
+package fsutil
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/docker/docker/pkg/fileutils"
+ "github.com/pkg/errors"
+ "golang.org/x/net/context"
+)
+
+type WalkOpt struct {
+ IncludePaths []string // todo: remove?
+ ExcludePatterns []string
+}
+
+func Walk(ctx context.Context, p string, opt *WalkOpt, fn filepath.WalkFunc) error {
+ root, err := filepath.EvalSymlinks(p)
+ if err != nil {
+ return errors.Wrapf(err, "failed to resolve %s", root)
+ }
+ fi, err := os.Stat(root)
+ if err != nil {
+ return errors.Wrapf(err, "failed to stat: %s", root)
+ }
+ if !fi.IsDir() {
+ return errors.Errorf("%s is not a directory", root)
+ }
+
+ var pm *fileutils.PatternMatcher
+ if opt != nil && opt.ExcludePatterns != nil {
+ pm, err = fileutils.NewPatternMatcher(opt.ExcludePatterns)
+ if err != nil {
+ return errors.Wrapf(err, "invalid excludepaths %s", opt.ExcludePatterns)
+ }
+ }
+
+ seenFiles := make(map[uint64]string)
+ return filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
+ if err != nil {
+ if os.IsNotExist(err) {
+ return filepath.SkipDir
+ }
+ return err
+ }
+ origpath := path
+ path, err = filepath.Rel(root, path)
+ if err != nil {
+ return err
+ }
+ // Skip root
+ if path == "." {
+ return nil
+ }
+
+ if opt != nil {
+ if opt.IncludePaths != nil {
+ matched := false
+ for _, p := range opt.IncludePaths {
+ if m, _ := filepath.Match(p, path); m {
+ matched = true
+ break
+ }
+ }
+ if !matched {
+ if fi.IsDir() {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ }
+ if pm != nil {
+ m, err := pm.Matches(path)
+ if err != nil {
+ return errors.Wrap(err, "failed to match excludepatterns")
+ }
+
+ if m {
+ if fi.IsDir() {
+ if !pm.Exclusions() {
+ return filepath.SkipDir
+ }
+ dirSlash := path + string(filepath.Separator)
+ for _, pat := range pm.Patterns() {
+ if !pat.Exclusion() {
+ continue
+ }
+ patStr := pat.String() + string(filepath.Separator)
+ if strings.HasPrefix(patStr, dirSlash) {
+ goto passedFilter
+ }
+ }
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ }
+ }
+
+ passedFilter:
+ path = filepath.ToSlash(path)
+
+ stat := &Stat{
+ Path: path,
+ Mode: uint32(fi.Mode()),
+ Size_: fi.Size(),
+ ModTime: fi.ModTime().UnixNano(),
+ }
+
+ setUnixOpt(fi, stat, path, seenFiles)
+
+ if !fi.IsDir() {
+ if fi.Mode()&os.ModeSymlink != 0 {
+ link, err := os.Readlink(origpath)
+ if err != nil {
+ return errors.Wrapf(err, "failed to readlink %s", origpath)
+ }
+ stat.Linkname = link
+ }
+ }
+ if err := loadXattr(origpath, stat); err != nil {
+ return errors.Wrapf(err, "failed to xattr %s", path)
+ }
+
+ if runtime.GOOS == "windows" {
+ permPart := stat.Mode & uint32(os.ModePerm)
+ noPermPart := stat.Mode &^ uint32(os.ModePerm)
+ // Add the x bit: make everything +x from windows
+ permPart |= 0111
+ permPart &= 0755
+ stat.Mode = noPermPart | permPart
+ }
+
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ if err := fn(path, &StatInfo{stat}, nil); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
+
+type StatInfo struct {
+ *Stat
+}
+
+func (s *StatInfo) Name() string {
+ return filepath.Base(s.Stat.Path)
+}
+func (s *StatInfo) Size() int64 {
+ return s.Stat.Size_
+}
+func (s *StatInfo) Mode() os.FileMode {
+ return os.FileMode(s.Stat.Mode)
+}
+func (s *StatInfo) ModTime() time.Time {
+ return time.Unix(s.Stat.ModTime/1e9, s.Stat.ModTime%1e9)
+}
+func (s *StatInfo) IsDir() bool {
+ return s.Mode().IsDir()
+}
+func (s *StatInfo) Sys() interface{} {
+ return s.Stat
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/walker_unix.go b/vendor/github.com/tonistiigi/fsutil/walker_unix.go
new file mode 100644
index 0000000..6f13c95
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/walker_unix.go
@@ -0,0 +1,61 @@
+// +build !windows
+
+package fsutil
+
+import (
+ "os"
+ "syscall"
+
+ "github.com/pkg/errors"
+ "github.com/stevvooe/continuity/sysx"
+)
+
+func loadXattr(origpath string, stat *Stat) error {
+ xattrs, err := sysx.LListxattr(origpath)
+ if err != nil {
+ return errors.Wrapf(err, "failed to xattr %s", origpath)
+ }
+ if len(xattrs) > 0 {
+ m := make(map[string][]byte)
+ for _, key := range xattrs {
+ v, err := sysx.LGetxattr(origpath, key)
+ if err == nil {
+ m[key] = v
+ }
+ }
+ stat.Xattrs = m
+ }
+ return nil
+}
+
+func setUnixOpt(fi os.FileInfo, stat *Stat, path string, seenFiles map[uint64]string) {
+ s := fi.Sys().(*syscall.Stat_t)
+
+ stat.Uid = s.Uid
+ stat.Gid = s.Gid
+
+ if !fi.IsDir() {
+ if s.Mode&syscall.S_IFBLK != 0 ||
+ s.Mode&syscall.S_IFCHR != 0 {
+ stat.Devmajor = int64(major(uint64(s.Rdev)))
+ stat.Devminor = int64(minor(uint64(s.Rdev)))
+ }
+
+ ino := s.Ino
+ if s.Nlink > 1 {
+ if oldpath, ok := seenFiles[ino]; ok {
+ stat.Linkname = oldpath
+ stat.Size_ = 0
+ }
+ }
+ seenFiles[ino] = path
+ }
+}
+
+func major(device uint64) uint64 {
+ return (device >> 8) & 0xfff
+}
+
+func minor(device uint64) uint64 {
+ return (device & 0xff) | ((device >> 12) & 0xfff00)
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/walker_windows.go b/vendor/github.com/tonistiigi/fsutil/walker_windows.go
new file mode 100644
index 0000000..a1a2b45
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/walker_windows.go
@@ -0,0 +1,14 @@
+// +build windows
+
+package fsutil
+
+import (
+ "os"
+)
+
+func loadXattr(_ string, _ *Stat) error {
+ return nil
+}
+
+func setUnixOpt(_ os.FileInfo, _ *Stat, _ string, _ map[uint64]string) {
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/wire.pb.go b/vendor/github.com/tonistiigi/fsutil/wire.pb.go
new file mode 100644
index 0000000..263fb12
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/wire.pb.go
@@ -0,0 +1,563 @@
+// Code generated by protoc-gen-gogo.
+// source: wire.proto
+// DO NOT EDIT!
+
+package fsutil
+
+import proto "github.com/gogo/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+import strconv "strconv"
+
+import bytes "bytes"
+
+import strings "strings"
+import reflect "reflect"
+
+import io "io"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+type Packet_PacketType int32
+
+const (
+ PACKET_STAT Packet_PacketType = 0
+ PACKET_REQ Packet_PacketType = 1
+ PACKET_DATA Packet_PacketType = 2
+ PACKET_FIN Packet_PacketType = 3
+)
+
+var Packet_PacketType_name = map[int32]string{
+ 0: "PACKET_STAT",
+ 1: "PACKET_REQ",
+ 2: "PACKET_DATA",
+ 3: "PACKET_FIN",
+}
+var Packet_PacketType_value = map[string]int32{
+ "PACKET_STAT": 0,
+ "PACKET_REQ": 1,
+ "PACKET_DATA": 2,
+ "PACKET_FIN": 3,
+}
+
+func (Packet_PacketType) EnumDescriptor() ([]byte, []int) { return fileDescriptorWire, []int{0, 0} }
+
+type Packet struct {
+ Type Packet_PacketType `protobuf:"varint,1,opt,name=type,proto3,enum=fsutil.Packet_PacketType" json:"type,omitempty"`
+ Stat *Stat `protobuf:"bytes,2,opt,name=stat" json:"stat,omitempty"`
+ ID uint32 `protobuf:"varint,3,opt,name=ID,proto3" json:"ID,omitempty"`
+ Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"`
+}
+
+func (m *Packet) Reset() { *m = Packet{} }
+func (*Packet) ProtoMessage() {}
+func (*Packet) Descriptor() ([]byte, []int) { return fileDescriptorWire, []int{0} }
+
+func (m *Packet) GetType() Packet_PacketType {
+ if m != nil {
+ return m.Type
+ }
+ return PACKET_STAT
+}
+
+func (m *Packet) GetStat() *Stat {
+ if m != nil {
+ return m.Stat
+ }
+ return nil
+}
+
+func (m *Packet) GetID() uint32 {
+ if m != nil {
+ return m.ID
+ }
+ return 0
+}
+
+func (m *Packet) GetData() []byte {
+ if m != nil {
+ return m.Data
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Packet)(nil), "fsutil.Packet")
+ proto.RegisterEnum("fsutil.Packet_PacketType", Packet_PacketType_name, Packet_PacketType_value)
+}
+func (x Packet_PacketType) String() string {
+ s, ok := Packet_PacketType_name[int32(x)]
+ if ok {
+ return s
+ }
+ return strconv.Itoa(int(x))
+}
+func (this *Packet) Equal(that interface{}) bool {
+ if that == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ }
+
+ that1, ok := that.(*Packet)
+ if !ok {
+ that2, ok := that.(Packet)
+ if ok {
+ that1 = &that2
+ } else {
+ return false
+ }
+ }
+ if that1 == nil {
+ if this == nil {
+ return true
+ }
+ return false
+ } else if this == nil {
+ return false
+ }
+ if this.Type != that1.Type {
+ return false
+ }
+ if !this.Stat.Equal(that1.Stat) {
+ return false
+ }
+ if this.ID != that1.ID {
+ return false
+ }
+ if !bytes.Equal(this.Data, that1.Data) {
+ return false
+ }
+ return true
+}
+func (this *Packet) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 8)
+ s = append(s, "&fsutil.Packet{")
+ s = append(s, "Type: "+fmt.Sprintf("%#v", this.Type)+",\n")
+ if this.Stat != nil {
+ s = append(s, "Stat: "+fmt.Sprintf("%#v", this.Stat)+",\n")
+ }
+ s = append(s, "ID: "+fmt.Sprintf("%#v", this.ID)+",\n")
+ s = append(s, "Data: "+fmt.Sprintf("%#v", this.Data)+",\n")
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringWire(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func (m *Packet) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalTo(dAtA)
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Packet) MarshalTo(dAtA []byte) (int, error) {
+ var i int
+ _ = i
+ var l int
+ _ = l
+ if m.Type != 0 {
+ dAtA[i] = 0x8
+ i++
+ i = encodeVarintWire(dAtA, i, uint64(m.Type))
+ }
+ if m.Stat != nil {
+ dAtA[i] = 0x12
+ i++
+ i = encodeVarintWire(dAtA, i, uint64(m.Stat.Size()))
+ n1, err := m.Stat.MarshalTo(dAtA[i:])
+ if err != nil {
+ return 0, err
+ }
+ i += n1
+ }
+ if m.ID != 0 {
+ dAtA[i] = 0x18
+ i++
+ i = encodeVarintWire(dAtA, i, uint64(m.ID))
+ }
+ if len(m.Data) > 0 {
+ dAtA[i] = 0x22
+ i++
+ i = encodeVarintWire(dAtA, i, uint64(len(m.Data)))
+ i += copy(dAtA[i:], m.Data)
+ }
+ return i, nil
+}
+
+func encodeFixed64Wire(dAtA []byte, offset int, v uint64) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ dAtA[offset+4] = uint8(v >> 32)
+ dAtA[offset+5] = uint8(v >> 40)
+ dAtA[offset+6] = uint8(v >> 48)
+ dAtA[offset+7] = uint8(v >> 56)
+ return offset + 8
+}
+func encodeFixed32Wire(dAtA []byte, offset int, v uint32) int {
+ dAtA[offset] = uint8(v)
+ dAtA[offset+1] = uint8(v >> 8)
+ dAtA[offset+2] = uint8(v >> 16)
+ dAtA[offset+3] = uint8(v >> 24)
+ return offset + 4
+}
+func encodeVarintWire(dAtA []byte, offset int, v uint64) int {
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return offset + 1
+}
+func (m *Packet) Size() (n int) {
+ var l int
+ _ = l
+ if m.Type != 0 {
+ n += 1 + sovWire(uint64(m.Type))
+ }
+ if m.Stat != nil {
+ l = m.Stat.Size()
+ n += 1 + l + sovWire(uint64(l))
+ }
+ if m.ID != 0 {
+ n += 1 + sovWire(uint64(m.ID))
+ }
+ l = len(m.Data)
+ if l > 0 {
+ n += 1 + l + sovWire(uint64(l))
+ }
+ return n
+}
+
+func sovWire(x uint64) (n int) {
+ for {
+ n++
+ x >>= 7
+ if x == 0 {
+ break
+ }
+ }
+ return n
+}
+func sozWire(x uint64) (n int) {
+ return sovWire(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *Packet) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Packet{`,
+ `Type:` + fmt.Sprintf("%v", this.Type) + `,`,
+ `Stat:` + strings.Replace(fmt.Sprintf("%v", this.Stat), "Stat", "Stat", 1) + `,`,
+ `ID:` + fmt.Sprintf("%v", this.ID) + `,`,
+ `Data:` + fmt.Sprintf("%v", this.Data) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringWire(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *Packet) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWire
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Packet: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Packet: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
+ }
+ m.Type = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWire
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Type |= (Packet_PacketType(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Stat", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWire
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthWire
+ }
+ postIndex := iNdEx + msglen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Stat == nil {
+ m.Stat = &Stat{}
+ }
+ if err := m.Stat.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType)
+ }
+ m.ID = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWire
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ID |= (uint32(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
+ }
+ var byteLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowWire
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ byteLen |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if byteLen < 0 {
+ return ErrInvalidLengthWire
+ }
+ postIndex := iNdEx + byteLen
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
+ if m.Data == nil {
+ m.Data = []byte{}
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipWire(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if skippy < 0 {
+ return ErrInvalidLengthWire
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipWire(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWire
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWire
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ return iNdEx, nil
+ case 1:
+ iNdEx += 8
+ return iNdEx, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWire
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ iNdEx += length
+ if length < 0 {
+ return 0, ErrInvalidLengthWire
+ }
+ return iNdEx, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = iNdEx
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowWire
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := skipWire(dAtA[start:])
+ if err != nil {
+ return 0, err
+ }
+ iNdEx = start + next
+ }
+ return iNdEx, nil
+ case 4:
+ return iNdEx, nil
+ case 5:
+ iNdEx += 4
+ return iNdEx, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
+
+var (
+ ErrInvalidLengthWire = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowWire = fmt.Errorf("proto: integer overflow")
+)
+
+func init() { proto.RegisterFile("wire.proto", fileDescriptorWire) }
+
+var fileDescriptorWire = []byte{
+ // 253 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x2a, 0xcf, 0x2c, 0x4a,
+ 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x4b, 0x2b, 0x2e, 0x2d, 0xc9, 0xcc, 0x91, 0xe2,
+ 0x2a, 0x2e, 0x49, 0x2c, 0x81, 0x88, 0x29, 0x9d, 0x65, 0xe4, 0x62, 0x0b, 0x48, 0x4c, 0xce, 0x4e,
+ 0x2d, 0x11, 0xd2, 0xe5, 0x62, 0x29, 0xa9, 0x2c, 0x48, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x33,
+ 0x92, 0xd4, 0x83, 0xa8, 0xd6, 0x83, 0xc8, 0x42, 0xa9, 0x90, 0xca, 0x82, 0xd4, 0x20, 0xb0, 0x32,
+ 0x21, 0x05, 0x2e, 0x16, 0x90, 0x39, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xdc, 0x46, 0x3c, 0x30, 0xe5,
+ 0xc1, 0x25, 0x89, 0x25, 0x41, 0x60, 0x19, 0x21, 0x3e, 0x2e, 0x26, 0x4f, 0x17, 0x09, 0x66, 0x05,
+ 0x46, 0x0d, 0xde, 0x20, 0x26, 0x4f, 0x17, 0x21, 0x21, 0x2e, 0x96, 0x94, 0xc4, 0x92, 0x44, 0x09,
+ 0x16, 0x05, 0x46, 0x0d, 0x9e, 0x20, 0x30, 0x5b, 0xc9, 0x8f, 0x8b, 0x0b, 0x61, 0xb2, 0x10, 0x3f,
+ 0x17, 0x77, 0x80, 0xa3, 0xb3, 0xb7, 0x6b, 0x48, 0x7c, 0x70, 0x88, 0x63, 0x88, 0x00, 0x83, 0x10,
+ 0x1f, 0x17, 0x17, 0x54, 0x20, 0xc8, 0x35, 0x50, 0x80, 0x11, 0x49, 0x81, 0x8b, 0x63, 0x88, 0xa3,
+ 0x00, 0x13, 0x92, 0x02, 0x37, 0x4f, 0x3f, 0x01, 0x66, 0x27, 0x9d, 0x0b, 0x0f, 0xe5, 0x18, 0x6e,
+ 0x3c, 0x94, 0x63, 0xf8, 0xf0, 0x50, 0x8e, 0xb1, 0xe1, 0x91, 0x1c, 0xe3, 0x8a, 0x47, 0x72, 0x8c,
+ 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x8b, 0x47, 0x72,
+ 0x0c, 0x1f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x90, 0xc4, 0x06, 0x0e, 0x04, 0x63, 0x40,
+ 0x00, 0x00, 0x00, 0xff, 0xff, 0xda, 0x30, 0x43, 0x22, 0x26, 0x01, 0x00, 0x00,
+}
diff --git a/vendor/github.com/tonistiigi/fsutil/wire.proto b/vendor/github.com/tonistiigi/fsutil/wire.proto
new file mode 100644
index 0000000..d194320
--- /dev/null
+++ b/vendor/github.com/tonistiigi/fsutil/wire.proto
@@ -0,0 +1,18 @@
+syntax = "proto3";
+
+package fsutil;
+
+import "stat.proto";
+
+message Packet {
+ enum PacketType {
+ PACKET_STAT = 0;
+ PACKET_REQ = 1;
+ PACKET_DATA = 2;
+ PACKET_FIN = 3;
+ }
+ PacketType type = 1;
+ Stat stat = 2;
+ uint32 ID = 3;
+ bytes data = 4;
+}
diff --git a/vendor/github.com/urfave/cli/LICENSE b/vendor/github.com/urfave/cli/LICENSE
new file mode 100644
index 0000000..42a597e
--- /dev/null
+++ b/vendor/github.com/urfave/cli/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2016 Jeremy Saenz & Contributors
+
+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/urfave/cli/README.md b/vendor/github.com/urfave/cli/README.md
new file mode 100644
index 0000000..2bbbd8e
--- /dev/null
+++ b/vendor/github.com/urfave/cli/README.md
@@ -0,0 +1,1381 @@
+cli
+===
+
+[![Build Status](https://travis-ci.org/urfave/cli.svg?branch=master)](https://travis-ci.org/urfave/cli)
+[![Windows Build Status](https://ci.appveyor.com/api/projects/status/rtgk5xufi932pb2v?svg=true)](https://ci.appveyor.com/project/urfave/cli)
+[![GoDoc](https://godoc.org/github.com/urfave/cli?status.svg)](https://godoc.org/github.com/urfave/cli)
+[![codebeat](https://codebeat.co/badges/0a8f30aa-f975-404b-b878-5fab3ae1cc5f)](https://codebeat.co/projects/github-com-urfave-cli)
+[![Go Report Card](https://goreportcard.com/badge/urfave/cli)](https://goreportcard.com/report/urfave/cli)
+[![top level coverage](https://gocover.io/_badge/github.com/urfave/cli?0 "top level coverage")](http://gocover.io/github.com/urfave/cli) /
+[![altsrc coverage](https://gocover.io/_badge/github.com/urfave/cli/altsrc?0 "altsrc coverage")](http://gocover.io/github.com/urfave/cli/altsrc)
+
+**Notice:** This is the library formerly known as
+`github.com/codegangsta/cli` -- Github will automatically redirect requests
+to this repository, but we recommend updating your references for clarity.
+
+cli is a simple, fast, and fun package for building command line apps in Go. The
+goal is to enable developers to write fast and distributable command line
+applications in an expressive way.
+
+<!-- toc -->
+
+- [Overview](#overview)
+- [Installation](#installation)
+ * [Supported platforms](#supported-platforms)
+ * [Using the `v2` branch](#using-the-v2-branch)
+ * [Pinning to the `v1` releases](#pinning-to-the-v1-releases)
+- [Getting Started](#getting-started)
+- [Examples](#examples)
+ * [Arguments](#arguments)
+ * [Flags](#flags)
+ + [Placeholder Values](#placeholder-values)
+ + [Alternate Names](#alternate-names)
+ + [Ordering](#ordering)
+ + [Values from the Environment](#values-from-the-environment)
+ + [Values from alternate input sources (YAML, TOML, and others)](#values-from-alternate-input-sources-yaml-toml-and-others)
+ * [Subcommands](#subcommands)
+ * [Subcommands categories](#subcommands-categories)
+ * [Exit code](#exit-code)
+ * [Bash Completion](#bash-completion)
+ + [Enabling](#enabling)
+ + [Distribution](#distribution)
+ + [Customization](#customization)
+ * [Generated Help Text](#generated-help-text)
+ + [Customization](#customization-1)
+ * [Version Flag](#version-flag)
+ + [Customization](#customization-2)
+ + [Full API Example](#full-api-example)
+- [Contribution Guidelines](#contribution-guidelines)
+
+<!-- tocstop -->
+
+## Overview
+
+Command line apps are usually so tiny that there is absolutely no reason why
+your code should *not* be self-documenting. Things like generating help text and
+parsing command flags/options should not hinder productivity when writing a
+command line app.
+
+**This is where cli comes into play.** cli makes command line programming fun,
+organized, and expressive!
+
+## Installation
+
+Make sure you have a working Go environment. Go version 1.2+ is supported. [See
+the install instructions for Go](http://golang.org/doc/install.html).
+
+To install cli, simply run:
+```
+$ go get github.com/urfave/cli
+```
+
+Make sure your `PATH` includes the `$GOPATH/bin` directory so your commands can
+be easily used:
+```
+export PATH=$PATH:$GOPATH/bin
+```
+
+### Supported platforms
+
+cli is tested against multiple versions of Go on Linux, and against the latest
+released version of Go on OS X and Windows. For full details, see
+[`./.travis.yml`](./.travis.yml) and [`./appveyor.yml`](./appveyor.yml).
+
+### Using the `v2` branch
+
+**Warning**: The `v2` branch is currently unreleased and considered unstable.
+
+There is currently a long-lived branch named `v2` that is intended to land as
+the new `master` branch once development there has settled down. The current
+`master` branch (mirrored as `v1`) is being manually merged into `v2` on
+an irregular human-based schedule, but generally if one wants to "upgrade" to
+`v2` *now* and accept the volatility (read: "awesomeness") that comes along with
+that, please use whatever version pinning of your preference, such as via
+`gopkg.in`:
+
+```
+$ go get gopkg.in/urfave/cli.v2
+```
+
+``` go
+...
+import (
+ "gopkg.in/urfave/cli.v2" // imports as package "cli"
+)
+...
+```
+
+### Pinning to the `v1` releases
+
+Similarly to the section above describing use of the `v2` branch, if one wants
+to avoid any unexpected compatibility pains once `v2` becomes `master`, then
+pinning to `v1` is an acceptable option, e.g.:
+
+```
+$ go get gopkg.in/urfave/cli.v1
+```
+
+``` go
+...
+import (
+ "gopkg.in/urfave/cli.v1" // imports as package "cli"
+)
+...
+```
+
+This will pull the latest tagged `v1` release (e.g. `v1.18.1` at the time of writing).
+
+## Getting Started
+
+One of the philosophies behind cli is that an API should be playful and full of
+discovery. So a cli app can be as little as one line of code in `main()`.
+
+<!-- {
+ "args": ["&#45;&#45;help"],
+ "output": "A new cli application"
+} -->
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ cli.NewApp().Run(os.Args)
+}
+```
+
+This app will run and show help text, but is not very useful. Let's give an
+action to execute and some help documentation:
+
+<!-- {
+ "output": "boom! I say!"
+} -->
+``` go
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+ app.Name = "boom"
+ app.Usage = "make an explosive entrance"
+ app.Action = func(c *cli.Context) error {
+ fmt.Println("boom! I say!")
+ return nil
+ }
+
+ app.Run(os.Args)
+}
+```
+
+Running this already gives you a ton of functionality, plus support for things
+like subcommands and flags, which are covered below.
+
+## Examples
+
+Being a programmer can be a lonely job. Thankfully by the power of automation
+that is not the case! Let's create a greeter app to fend off our demons of
+loneliness!
+
+Start by creating a directory named `greet`, and within it, add a file,
+`greet.go` with the following code in it:
+
+<!-- {
+ "output": "Hello friend!"
+} -->
+``` go
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+ app.Name = "greet"
+ app.Usage = "fight the loneliness!"
+ app.Action = func(c *cli.Context) error {
+ fmt.Println("Hello friend!")
+ return nil
+ }
+
+ app.Run(os.Args)
+}
+```
+
+Install our command to the `$GOPATH/bin` directory:
+
+```
+$ go install
+```
+
+Finally run our new command:
+
+```
+$ greet
+Hello friend!
+```
+
+cli also generates neat help text:
+
+```
+$ greet help
+NAME:
+ greet - fight the loneliness!
+
+USAGE:
+ greet [global options] command [command options] [arguments...]
+
+VERSION:
+ 0.0.0
+
+COMMANDS:
+ help, h Shows a list of commands or help for one command
+
+GLOBAL OPTIONS
+ --version Shows version information
+```
+
+### Arguments
+
+You can lookup arguments by calling the `Args` function on `cli.Context`, e.g.:
+
+<!-- {
+ "output": "Hello \""
+} -->
+``` go
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+
+ app.Action = func(c *cli.Context) error {
+ fmt.Printf("Hello %q", c.Args().Get(0))
+ return nil
+ }
+
+ app.Run(os.Args)
+}
+```
+
+### Flags
+
+Setting and querying flags is simple.
+
+<!-- {
+ "output": "Hello Nefertiti"
+} -->
+``` go
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+
+ app.Flags = []cli.Flag {
+ cli.StringFlag{
+ Name: "lang",
+ Value: "english",
+ Usage: "language for the greeting",
+ },
+ }
+
+ app.Action = func(c *cli.Context) error {
+ name := "Nefertiti"
+ if c.NArg() > 0 {
+ name = c.Args().Get(0)
+ }
+ if c.String("lang") == "spanish" {
+ fmt.Println("Hola", name)
+ } else {
+ fmt.Println("Hello", name)
+ }
+ return nil
+ }
+
+ app.Run(os.Args)
+}
+```
+
+You can also set a destination variable for a flag, to which the content will be
+scanned.
+
+<!-- {
+ "output": "Hello someone"
+} -->
+``` go
+package main
+
+import (
+ "os"
+ "fmt"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ var language string
+
+ app := cli.NewApp()
+
+ app.Flags = []cli.Flag {
+ cli.StringFlag{
+ Name: "lang",
+ Value: "english",
+ Usage: "language for the greeting",
+ Destination: &language,
+ },
+ }
+
+ app.Action = func(c *cli.Context) error {
+ name := "someone"
+ if c.NArg() > 0 {
+ name = c.Args()[0]
+ }
+ if language == "spanish" {
+ fmt.Println("Hola", name)
+ } else {
+ fmt.Println("Hello", name)
+ }
+ return nil
+ }
+
+ app.Run(os.Args)
+}
+```
+
+See full list of flags at http://godoc.org/github.com/urfave/cli
+
+#### Placeholder Values
+
+Sometimes it's useful to specify a flag's value within the usage string itself.
+Such placeholders are indicated with back quotes.
+
+For example this:
+
+<!-- {
+ "args": ["&#45;&#45;help"],
+ "output": "&#45;&#45;config FILE, &#45;c FILE"
+} -->
+```go
+package main
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+
+ app.Flags = []cli.Flag{
+ cli.StringFlag{
+ Name: "config, c",
+ Usage: "Load configuration from `FILE`",
+ },
+ }
+
+ app.Run(os.Args)
+}
+```
+
+Will result in help output like:
+
+```
+--config FILE, -c FILE Load configuration from FILE
+```
+
+Note that only the first placeholder is used. Subsequent back-quoted words will
+be left as-is.
+
+#### Alternate Names
+
+You can set alternate (or short) names for flags by providing a comma-delimited
+list for the `Name`. e.g.
+
+<!-- {
+ "args": ["&#45;&#45;help"],
+ "output": "&#45;&#45;lang value, &#45;l value.*language for the greeting.*default: \"english\""
+} -->
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+
+ app.Flags = []cli.Flag {
+ cli.StringFlag{
+ Name: "lang, l",
+ Value: "english",
+ Usage: "language for the greeting",
+ },
+ }
+
+ app.Run(os.Args)
+}
+```
+
+That flag can then be set with `--lang spanish` or `-l spanish`. Note that
+giving two different forms of the same flag in the same command invocation is an
+error.
+
+#### Ordering
+
+Flags for the application and commands are shown in the order they are defined.
+However, it's possible to sort them from outside this library by using `FlagsByName`
+or `CommandsByName` with `sort`.
+
+For example this:
+
+<!-- {
+ "args": ["&#45;&#45;help"],
+ "output": "add a task to the list\n.*complete a task on the list\n.*\n\n.*\n.*Load configuration from FILE\n.*Language for the greeting.*"
+} -->
+``` go
+package main
+
+import (
+ "os"
+ "sort"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+
+ app.Flags = []cli.Flag {
+ cli.StringFlag{
+ Name: "lang, l",
+ Value: "english",
+ Usage: "Language for the greeting",
+ },
+ cli.StringFlag{
+ Name: "config, c",
+ Usage: "Load configuration from `FILE`",
+ },
+ }
+
+ app.Commands = []cli.Command{
+ {
+ Name: "complete",
+ Aliases: []string{"c"},
+ Usage: "complete a task on the list",
+ Action: func(c *cli.Context) error {
+ return nil
+ },
+ },
+ {
+ Name: "add",
+ Aliases: []string{"a"},
+ Usage: "add a task to the list",
+ Action: func(c *cli.Context) error {
+ return nil
+ },
+ },
+ }
+
+ sort.Sort(cli.FlagsByName(app.Flags))
+ sort.Sort(cli.CommandsByName(app.Commands))
+
+ app.Run(os.Args)
+}
+```
+
+Will result in help output like:
+
+```
+--config FILE, -c FILE Load configuration from FILE
+--lang value, -l value Language for the greeting (default: "english")
+```
+
+#### Values from the Environment
+
+You can also have the default value set from the environment via `EnvVar`. e.g.
+
+<!-- {
+ "args": ["&#45;&#45;help"],
+ "output": "language for the greeting.*APP_LANG"
+} -->
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+
+ app.Flags = []cli.Flag {
+ cli.StringFlag{
+ Name: "lang, l",
+ Value: "english",
+ Usage: "language for the greeting",
+ EnvVar: "APP_LANG",
+ },
+ }
+
+ app.Run(os.Args)
+}
+```
+
+The `EnvVar` may also be given as a comma-delimited "cascade", where the first
+environment variable that resolves is used as the default.
+
+<!-- {
+ "args": ["&#45;&#45;help"],
+ "output": "language for the greeting.*LEGACY_COMPAT_LANG.*APP_LANG.*LANG"
+} -->
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+
+ app.Flags = []cli.Flag {
+ cli.StringFlag{
+ Name: "lang, l",
+ Value: "english",
+ Usage: "language for the greeting",
+ EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG",
+ },
+ }
+
+ app.Run(os.Args)
+}
+```
+
+#### Values from alternate input sources (YAML, TOML, and others)
+
+There is a separate package altsrc that adds support for getting flag values
+from other file input sources.
+
+Currently supported input source formats:
+* YAML
+* TOML
+
+In order to get values for a flag from an alternate input source the following
+code would be added to wrap an existing cli.Flag like below:
+
+``` go
+ altsrc.NewIntFlag(cli.IntFlag{Name: "test"})
+```
+
+Initialization must also occur for these flags. Below is an example initializing
+getting data from a yaml file below.
+
+``` go
+ command.Before = altsrc.InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
+```
+
+The code above will use the "load" string as a flag name to get the file name of
+a yaml file from the cli.Context. It will then use that file name to initialize
+the yaml input source for any flags that are defined on that command. As a note
+the "load" flag used would also have to be defined on the command flags in order
+for this code snipped to work.
+
+Currently only the aboved specified formats are supported but developers can
+add support for other input sources by implementing the
+altsrc.InputSourceContext for their given sources.
+
+Here is a more complete sample of a command using YAML support:
+
+<!-- {
+ "args": ["test-cmd", "&#45;&#45;help"],
+ "output": "&#45&#45;test value.*default: 0"
+} -->
+``` go
+package notmain
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/urfave/cli"
+ "github.com/urfave/cli/altsrc"
+)
+
+func main() {
+ app := cli.NewApp()
+
+ flags := []cli.Flag{
+ altsrc.NewIntFlag(cli.IntFlag{Name: "test"}),
+ cli.StringFlag{Name: "load"},
+ }
+
+ app.Action = func(c *cli.Context) error {
+ fmt.Println("yaml ist rad")
+ return nil
+ }
+
+ app.Before = altsrc.InitInputSourceWithContext(flags, altsrc.NewYamlSourceFromFlagFunc("load"))
+ app.Flags = flags
+
+ app.Run(os.Args)
+}
+```
+
+### Subcommands
+
+Subcommands can be defined for a more git-like command line app.
+
+<!-- {
+ "args": ["template", "add"],
+ "output": "new task template: .+"
+} -->
+```go
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+
+ app.Commands = []cli.Command{
+ {
+ Name: "add",
+ Aliases: []string{"a"},
+ Usage: "add a task to the list",
+ Action: func(c *cli.Context) error {
+ fmt.Println("added task: ", c.Args().First())
+ return nil
+ },
+ },
+ {
+ Name: "complete",
+ Aliases: []string{"c"},
+ Usage: "complete a task on the list",
+ Action: func(c *cli.Context) error {
+ fmt.Println("completed task: ", c.Args().First())
+ return nil
+ },
+ },
+ {
+ Name: "template",
+ Aliases: []string{"t"},
+ Usage: "options for task templates",
+ Subcommands: []cli.Command{
+ {
+ Name: "add",
+ Usage: "add a new template",
+ Action: func(c *cli.Context) error {
+ fmt.Println("new task template: ", c.Args().First())
+ return nil
+ },
+ },
+ {
+ Name: "remove",
+ Usage: "remove an existing template",
+ Action: func(c *cli.Context) error {
+ fmt.Println("removed task template: ", c.Args().First())
+ return nil
+ },
+ },
+ },
+ },
+ }
+
+ app.Run(os.Args)
+}
+```
+
+### Subcommands categories
+
+For additional organization in apps that have many subcommands, you can
+associate a category for each command to group them together in the help
+output.
+
+E.g.
+
+```go
+package main
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+
+ app.Commands = []cli.Command{
+ {
+ Name: "noop",
+ },
+ {
+ Name: "add",
+ Category: "template",
+ },
+ {
+ Name: "remove",
+ Category: "template",
+ },
+ }
+
+ app.Run(os.Args)
+}
+```
+
+Will include:
+
+```
+COMMANDS:
+ noop
+
+ Template actions:
+ add
+ remove
+```
+
+### Exit code
+
+Calling `App.Run` will not automatically call `os.Exit`, which means that by
+default the exit code will "fall through" to being `0`. An explicit exit code
+may be set by returning a non-nil error that fulfills `cli.ExitCoder`, *or* a
+`cli.MultiError` that includes an error that fulfills `cli.ExitCoder`, e.g.:
+
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+ app.Flags = []cli.Flag{
+ cli.BoolTFlag{
+ Name: "ginger-crouton",
+ Usage: "is it in the soup?",
+ },
+ }
+ app.Action = func(ctx *cli.Context) error {
+ if !ctx.Bool("ginger-crouton") {
+ return cli.NewExitError("it is not in the soup", 86)
+ }
+ return nil
+ }
+
+ app.Run(os.Args)
+}
+```
+
+### Bash Completion
+
+You can enable completion commands by setting the `EnableBashCompletion`
+flag on the `App` object. By default, this setting will only auto-complete to
+show an app's subcommands, but you can write your own completion methods for
+the App or its subcommands.
+
+<!-- {
+ "args": ["complete", "&#45;&#45;generate&#45;bash&#45;completion"],
+ "output": "laundry"
+} -->
+``` go
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ tasks := []string{"cook", "clean", "laundry", "eat", "sleep", "code"}
+
+ app := cli.NewApp()
+ app.EnableBashCompletion = true
+ app.Commands = []cli.Command{
+ {
+ Name: "complete",
+ Aliases: []string{"c"},
+ Usage: "complete a task on the list",
+ Action: func(c *cli.Context) error {
+ fmt.Println("completed task: ", c.Args().First())
+ return nil
+ },
+ BashComplete: func(c *cli.Context) {
+ // This will complete if no args are passed
+ if c.NArg() > 0 {
+ return
+ }
+ for _, t := range tasks {
+ fmt.Println(t)
+ }
+ },
+ },
+ }
+
+ app.Run(os.Args)
+}
+```
+
+#### Enabling
+
+Source the `autocomplete/bash_autocomplete` file in your `.bashrc` file while
+setting the `PROG` variable to the name of your program:
+
+`PROG=myprogram source /.../cli/autocomplete/bash_autocomplete`
+
+#### Distribution
+
+Copy `autocomplete/bash_autocomplete` into `/etc/bash_completion.d/` and rename
+it to the name of the program you wish to add autocomplete support for (or
+automatically install it there if you are distributing a package). Don't forget
+to source the file to make it active in the current shell.
+
+```
+sudo cp src/bash_autocomplete /etc/bash_completion.d/<myprogram>
+source /etc/bash_completion.d/<myprogram>
+```
+
+Alternatively, you can just document that users should source the generic
+`autocomplete/bash_autocomplete` in their bash configuration with `$PROG` set
+to the name of their program (as above).
+
+#### Customization
+
+The default bash completion flag (`--generate-bash-completion`) is defined as
+`cli.BashCompletionFlag`, and may be redefined if desired, e.g.:
+
+<!-- {
+ "args": ["&#45;&#45;compgen"],
+ "output": "wat\nhelp\nh"
+} -->
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ cli.BashCompletionFlag = cli.BoolFlag{
+ Name: "compgen",
+ Hidden: true,
+ }
+
+ app := cli.NewApp()
+ app.EnableBashCompletion = true
+ app.Commands = []cli.Command{
+ {
+ Name: "wat",
+ },
+ }
+ app.Run(os.Args)
+}
+```
+
+### Generated Help Text
+
+The default help flag (`-h/--help`) is defined as `cli.HelpFlag` and is checked
+by the cli internals in order to print generated help text for the app, command,
+or subcommand, and break execution.
+
+#### Customization
+
+All of the help text generation may be customized, and at multiple levels. The
+templates are exposed as variables `AppHelpTemplate`, `CommandHelpTemplate`, and
+`SubcommandHelpTemplate` which may be reassigned or augmented, and full override
+is possible by assigning a compatible func to the `cli.HelpPrinter` variable,
+e.g.:
+
+<!-- {
+ "output": "Ha HA. I pwnd the help!!1"
+} -->
+``` go
+package main
+
+import (
+ "fmt"
+ "io"
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ // EXAMPLE: Append to an existing template
+ cli.AppHelpTemplate = fmt.Sprintf(`%s
+
+WEBSITE: http://awesometown.example.com
+
+SUPPORT: support@awesometown.example.com
+
+`, cli.AppHelpTemplate)
+
+ // EXAMPLE: Override a template
+ cli.AppHelpTemplate = `NAME:
+ {{.Name}} - {{.Usage}}
+USAGE:
+ {{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}
+ {{if len .Authors}}
+AUTHOR:
+ {{range .Authors}}{{ . }}{{end}}
+ {{end}}{{if .Commands}}
+COMMANDS:
+{{range .Commands}}{{if not .HideHelp}} {{join .Names ", "}}{{ "\t"}}{{.Usage}}{{ "\n" }}{{end}}{{end}}{{end}}{{if .VisibleFlags}}
+GLOBAL OPTIONS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}{{if .Copyright }}
+COPYRIGHT:
+ {{.Copyright}}
+ {{end}}{{if .Version}}
+VERSION:
+ {{.Version}}
+ {{end}}
+`
+
+ // EXAMPLE: Replace the `HelpPrinter` func
+ cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) {
+ fmt.Println("Ha HA. I pwnd the help!!1")
+ }
+
+ cli.NewApp().Run(os.Args)
+}
+```
+
+The default flag may be customized to something other than `-h/--help` by
+setting `cli.HelpFlag`, e.g.:
+
+<!-- {
+ "args": ["&#45;&#45halp"],
+ "output": "haaaaalp.*HALP"
+} -->
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ cli.HelpFlag = cli.BoolFlag{
+ Name: "halp, haaaaalp",
+ Usage: "HALP",
+ EnvVar: "SHOW_HALP,HALPPLZ",
+ }
+
+ cli.NewApp().Run(os.Args)
+}
+```
+
+### Version Flag
+
+The default version flag (`-v/--version`) is defined as `cli.VersionFlag`, which
+is checked by the cli internals in order to print the `App.Version` via
+`cli.VersionPrinter` and break execution.
+
+#### Customization
+
+The default flag may be customized to something other than `-v/--version` by
+setting `cli.VersionFlag`, e.g.:
+
+<!-- {
+ "args": ["&#45;&#45print-version"],
+ "output": "partay version 19\\.99\\.0"
+} -->
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+func main() {
+ cli.VersionFlag = cli.BoolFlag{
+ Name: "print-version, V",
+ Usage: "print only the version",
+ }
+
+ app := cli.NewApp()
+ app.Name = "partay"
+ app.Version = "19.99.0"
+ app.Run(os.Args)
+}
+```
+
+Alternatively, the version printer at `cli.VersionPrinter` may be overridden, e.g.:
+
+<!-- {
+ "args": ["&#45;&#45version"],
+ "output": "version=19\\.99\\.0 revision=fafafaf"
+} -->
+``` go
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/urfave/cli"
+)
+
+var (
+ Revision = "fafafaf"
+)
+
+func main() {
+ cli.VersionPrinter = func(c *cli.Context) {
+ fmt.Printf("version=%s revision=%s\n", c.App.Version, Revision)
+ }
+
+ app := cli.NewApp()
+ app.Name = "partay"
+ app.Version = "19.99.0"
+ app.Run(os.Args)
+}
+```
+
+#### Full API Example
+
+**Notice**: This is a contrived (functioning) example meant strictly for API
+demonstration purposes. Use of one's imagination is encouraged.
+
+<!-- {
+ "output": "made it!\nPhew!"
+} -->
+``` go
+package main
+
+import (
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "time"
+
+ "github.com/urfave/cli"
+)
+
+func init() {
+ cli.AppHelpTemplate += "\nCUSTOMIZED: you bet ur muffins\n"
+ cli.CommandHelpTemplate += "\nYMMV\n"
+ cli.SubcommandHelpTemplate += "\nor something\n"
+
+ cli.HelpFlag = cli.BoolFlag{Name: "halp"}
+ cli.BashCompletionFlag = cli.BoolFlag{Name: "compgen", Hidden: true}
+ cli.VersionFlag = cli.BoolFlag{Name: "print-version, V"}
+
+ cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) {
+ fmt.Fprintf(w, "best of luck to you\n")
+ }
+ cli.VersionPrinter = func(c *cli.Context) {
+ fmt.Fprintf(c.App.Writer, "version=%s\n", c.App.Version)
+ }
+ cli.OsExiter = func(c int) {
+ fmt.Fprintf(cli.ErrWriter, "refusing to exit %d\n", c)
+ }
+ cli.ErrWriter = ioutil.Discard
+ cli.FlagStringer = func(fl cli.Flag) string {
+ return fmt.Sprintf("\t\t%s", fl.GetName())
+ }
+}
+
+type hexWriter struct{}
+
+func (w *hexWriter) Write(p []byte) (int, error) {
+ for _, b := range p {
+ fmt.Printf("%x", b)
+ }
+ fmt.Printf("\n")
+
+ return len(p), nil
+}
+
+type genericType struct{
+ s string
+}
+
+func (g *genericType) Set(value string) error {
+ g.s = value
+ return nil
+}
+
+func (g *genericType) String() string {
+ return g.s
+}
+
+func main() {
+ app := cli.NewApp()
+ app.Name = "kənˈtrīv"
+ app.Version = "19.99.0"
+ app.Compiled = time.Now()
+ app.Authors = []cli.Author{
+ cli.Author{
+ Name: "Example Human",
+ Email: "human@example.com",
+ },
+ }
+ app.Copyright = "(c) 1999 Serious Enterprise"
+ app.HelpName = "contrive"
+ app.Usage = "demonstrate available API"
+ app.UsageText = "contrive - demonstrating the available API"
+ app.ArgsUsage = "[args and such]"
+ app.Commands = []cli.Command{
+ cli.Command{
+ Name: "doo",
+ Aliases: []string{"do"},
+ Category: "motion",
+ Usage: "do the doo",
+ UsageText: "doo - does the dooing",
+ Description: "no really, there is a lot of dooing to be done",
+ ArgsUsage: "[arrgh]",
+ Flags: []cli.Flag{
+ cli.BoolFlag{Name: "forever, forevvarr"},
+ },
+ Subcommands: cli.Commands{
+ cli.Command{
+ Name: "wop",
+ Action: wopAction,
+ },
+ },
+ SkipFlagParsing: false,
+ HideHelp: false,
+ Hidden: false,
+ HelpName: "doo!",
+ BashComplete: func(c *cli.Context) {
+ fmt.Fprintf(c.App.Writer, "--better\n")
+ },
+ Before: func(c *cli.Context) error {
+ fmt.Fprintf(c.App.Writer, "brace for impact\n")
+ return nil
+ },
+ After: func(c *cli.Context) error {
+ fmt.Fprintf(c.App.Writer, "did we lose anyone?\n")
+ return nil
+ },
+ Action: func(c *cli.Context) error {
+ c.Command.FullName()
+ c.Command.HasName("wop")
+ c.Command.Names()
+ c.Command.VisibleFlags()
+ fmt.Fprintf(c.App.Writer, "dodododododoodododddooooododododooo\n")
+ if c.Bool("forever") {
+ c.Command.Run(c)
+ }
+ return nil
+ },
+ OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
+ fmt.Fprintf(c.App.Writer, "for shame\n")
+ return err
+ },
+ },
+ }
+ app.Flags = []cli.Flag{
+ cli.BoolFlag{Name: "fancy"},
+ cli.BoolTFlag{Name: "fancier"},
+ cli.DurationFlag{Name: "howlong, H", Value: time.Second * 3},
+ cli.Float64Flag{Name: "howmuch"},
+ cli.GenericFlag{Name: "wat", Value: &genericType{}},
+ cli.Int64Flag{Name: "longdistance"},
+ cli.Int64SliceFlag{Name: "intervals"},
+ cli.IntFlag{Name: "distance"},
+ cli.IntSliceFlag{Name: "times"},
+ cli.StringFlag{Name: "dance-move, d"},
+ cli.StringSliceFlag{Name: "names, N"},
+ cli.UintFlag{Name: "age"},
+ cli.Uint64Flag{Name: "bigage"},
+ }
+ app.EnableBashCompletion = true
+ app.HideHelp = false
+ app.HideVersion = false
+ app.BashComplete = func(c *cli.Context) {
+ fmt.Fprintf(c.App.Writer, "lipstick\nkiss\nme\nlipstick\nringo\n")
+ }
+ app.Before = func(c *cli.Context) error {
+ fmt.Fprintf(c.App.Writer, "HEEEERE GOES\n")
+ return nil
+ }
+ app.After = func(c *cli.Context) error {
+ fmt.Fprintf(c.App.Writer, "Phew!\n")
+ return nil
+ }
+ app.CommandNotFound = func(c *cli.Context, command string) {
+ fmt.Fprintf(c.App.Writer, "Thar be no %q here.\n", command)
+ }
+ app.OnUsageError = func(c *cli.Context, err error, isSubcommand bool) error {
+ if isSubcommand {
+ return err
+ }
+
+ fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err)
+ return nil
+ }
+ app.Action = func(c *cli.Context) error {
+ cli.DefaultAppComplete(c)
+ cli.HandleExitCoder(errors.New("not an exit coder, though"))
+ cli.ShowAppHelp(c)
+ cli.ShowCommandCompletions(c, "nope")
+ cli.ShowCommandHelp(c, "also-nope")
+ cli.ShowCompletions(c)
+ cli.ShowSubcommandHelp(c)
+ cli.ShowVersion(c)
+
+ categories := c.App.Categories()
+ categories.AddCommand("sounds", cli.Command{
+ Name: "bloop",
+ })
+
+ for _, category := range c.App.Categories() {
+ fmt.Fprintf(c.App.Writer, "%s\n", category.Name)
+ fmt.Fprintf(c.App.Writer, "%#v\n", category.Commands)
+ fmt.Fprintf(c.App.Writer, "%#v\n", category.VisibleCommands())
+ }
+
+ fmt.Printf("%#v\n", c.App.Command("doo"))
+ if c.Bool("infinite") {
+ c.App.Run([]string{"app", "doo", "wop"})
+ }
+
+ if c.Bool("forevar") {
+ c.App.RunAsSubcommand(c)
+ }
+ c.App.Setup()
+ fmt.Printf("%#v\n", c.App.VisibleCategories())
+ fmt.Printf("%#v\n", c.App.VisibleCommands())
+ fmt.Printf("%#v\n", c.App.VisibleFlags())
+
+ fmt.Printf("%#v\n", c.Args().First())
+ if len(c.Args()) > 0 {
+ fmt.Printf("%#v\n", c.Args()[1])
+ }
+ fmt.Printf("%#v\n", c.Args().Present())
+ fmt.Printf("%#v\n", c.Args().Tail())
+
+ set := flag.NewFlagSet("contrive", 0)
+ nc := cli.NewContext(c.App, set, c)
+
+ fmt.Printf("%#v\n", nc.Args())
+ fmt.Printf("%#v\n", nc.Bool("nope"))
+ fmt.Printf("%#v\n", nc.BoolT("nerp"))
+ fmt.Printf("%#v\n", nc.Duration("howlong"))
+ fmt.Printf("%#v\n", nc.Float64("hay"))
+ fmt.Printf("%#v\n", nc.Generic("bloop"))
+ fmt.Printf("%#v\n", nc.Int64("bonk"))
+ fmt.Printf("%#v\n", nc.Int64Slice("burnks"))
+ fmt.Printf("%#v\n", nc.Int("bips"))
+ fmt.Printf("%#v\n", nc.IntSlice("blups"))
+ fmt.Printf("%#v\n", nc.String("snurt"))
+ fmt.Printf("%#v\n", nc.StringSlice("snurkles"))
+ fmt.Printf("%#v\n", nc.Uint("flub"))
+ fmt.Printf("%#v\n", nc.Uint64("florb"))
+ fmt.Printf("%#v\n", nc.GlobalBool("global-nope"))
+ fmt.Printf("%#v\n", nc.GlobalBoolT("global-nerp"))
+ fmt.Printf("%#v\n", nc.GlobalDuration("global-howlong"))
+ fmt.Printf("%#v\n", nc.GlobalFloat64("global-hay"))
+ fmt.Printf("%#v\n", nc.GlobalGeneric("global-bloop"))
+ fmt.Printf("%#v\n", nc.GlobalInt("global-bips"))
+ fmt.Printf("%#v\n", nc.GlobalIntSlice("global-blups"))
+ fmt.Printf("%#v\n", nc.GlobalString("global-snurt"))
+ fmt.Printf("%#v\n", nc.GlobalStringSlice("global-snurkles"))
+
+ fmt.Printf("%#v\n", nc.FlagNames())
+ fmt.Printf("%#v\n", nc.GlobalFlagNames())
+ fmt.Printf("%#v\n", nc.GlobalIsSet("wat"))
+ fmt.Printf("%#v\n", nc.GlobalSet("wat", "nope"))
+ fmt.Printf("%#v\n", nc.NArg())
+ fmt.Printf("%#v\n", nc.NumFlags())
+ fmt.Printf("%#v\n", nc.Parent())
+
+ nc.Set("wat", "also-nope")
+
+ ec := cli.NewExitError("ohwell", 86)
+ fmt.Fprintf(c.App.Writer, "%d", ec.ExitCode())
+ fmt.Printf("made it!\n")
+ return ec
+ }
+
+ if os.Getenv("HEXY") != "" {
+ app.Writer = &hexWriter{}
+ app.ErrWriter = &hexWriter{}
+ }
+
+ app.Metadata = map[string]interface{}{
+ "layers": "many",
+ "explicable": false,
+ "whatever-values": 19.99,
+ }
+
+ app.Run(os.Args)
+}
+
+func wopAction(c *cli.Context) error {
+ fmt.Fprintf(c.App.Writer, ":wave: over here, eh\n")
+ return nil
+}
+```
+
+## Contribution Guidelines
+
+Feel free to put up a pull request to fix a bug or maybe add a feature. I will
+give it a code review and make sure that it does not break backwards
+compatibility. If I or any other collaborators agree that it is in line with
+the vision of the project, we will work with you to get the code into
+a mergeable state and merge it into the master branch.
+
+If you have contributed something significant to the project, we will most
+likely add you as a collaborator. As a collaborator you are given the ability
+to merge others pull requests. It is very important that new code does not
+break existing code, so be careful about what code you do choose to merge.
+
+If you feel like you have contributed to the project but have not yet been
+added as a collaborator, we probably forgot to add you, please open an issue.
diff --git a/vendor/github.com/urfave/cli/app.go b/vendor/github.com/urfave/cli/app.go
new file mode 100644
index 0000000..95ffc0b
--- /dev/null
+++ b/vendor/github.com/urfave/cli/app.go
@@ -0,0 +1,492 @@
+package cli
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "sort"
+ "time"
+)
+
+var (
+ changeLogURL = "https://github.com/urfave/cli/blob/master/CHANGELOG.md"
+ appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL)
+ runAndExitOnErrorDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-runandexitonerror", changeLogURL)
+
+ contactSysadmin = "This is an error in the application. Please contact the distributor of this application if this is not you."
+
+ errInvalidActionType = NewExitError("ERROR invalid Action type. "+
+ fmt.Sprintf("Must be `func(*Context`)` or `func(*Context) error). %s", contactSysadmin)+
+ fmt.Sprintf("See %s", appActionDeprecationURL), 2)
+)
+
+// App is the main structure of a cli application. It is recommended that
+// an app be created with the cli.NewApp() function
+type App struct {
+ // The name of the program. Defaults to path.Base(os.Args[0])
+ Name string
+ // Full name of command for help, defaults to Name
+ HelpName string
+ // Description of the program.
+ Usage string
+ // Text to override the USAGE section of help
+ UsageText string
+ // Description of the program argument format.
+ ArgsUsage string
+ // Version of the program
+ Version string
+ // Description of the program
+ Description string
+ // List of commands to execute
+ Commands []Command
+ // List of flags to parse
+ Flags []Flag
+ // Boolean to enable bash completion commands
+ EnableBashCompletion bool
+ // Boolean to hide built-in help command
+ HideHelp bool
+ // Boolean to hide built-in version flag and the VERSION section of help
+ HideVersion bool
+ // Populate on app startup, only gettable through method Categories()
+ categories CommandCategories
+ // An action to execute when the bash-completion flag is set
+ BashComplete BashCompleteFunc
+ // An action to execute before any subcommands are run, but after the context is ready
+ // If a non-nil error is returned, no subcommands are run
+ Before BeforeFunc
+ // An action to execute after any subcommands are run, but after the subcommand has finished
+ // It is run even if Action() panics
+ After AfterFunc
+
+ // The action to execute when no subcommands are specified
+ // Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}`
+ // *Note*: support for the deprecated `Action` signature will be removed in a future version
+ Action interface{}
+
+ // Execute this function if the proper command cannot be found
+ CommandNotFound CommandNotFoundFunc
+ // Execute this function if an usage error occurs
+ OnUsageError OnUsageErrorFunc
+ // Compilation date
+ Compiled time.Time
+ // List of all authors who contributed
+ Authors []Author
+ // Copyright of the binary if any
+ Copyright string
+ // Name of Author (Note: Use App.Authors, this is deprecated)
+ Author string
+ // Email of Author (Note: Use App.Authors, this is deprecated)
+ Email string
+ // Writer writer to write output to
+ Writer io.Writer
+ // ErrWriter writes error output
+ ErrWriter io.Writer
+ // Other custom info
+ Metadata map[string]interface{}
+
+ didSetup bool
+}
+
+// Tries to find out when this binary was compiled.
+// Returns the current time if it fails to find it.
+func compileTime() time.Time {
+ info, err := os.Stat(os.Args[0])
+ if err != nil {
+ return time.Now()
+ }
+ return info.ModTime()
+}
+
+// NewApp creates a new cli Application with some reasonable defaults for Name,
+// Usage, Version and Action.
+func NewApp() *App {
+ return &App{
+ Name: filepath.Base(os.Args[0]),
+ HelpName: filepath.Base(os.Args[0]),
+ Usage: "A new cli application",
+ UsageText: "",
+ Version: "0.0.0",
+ BashComplete: DefaultAppComplete,
+ Action: helpCommand.Action,
+ Compiled: compileTime(),
+ Writer: os.Stdout,
+ }
+}
+
+// Setup runs initialization code to ensure all data structures are ready for
+// `Run` or inspection prior to `Run`. It is internally called by `Run`, but
+// will return early if setup has already happened.
+func (a *App) Setup() {
+ if a.didSetup {
+ return
+ }
+
+ a.didSetup = true
+
+ if a.Author != "" || a.Email != "" {
+ a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email})
+ }
+
+ newCmds := []Command{}
+ for _, c := range a.Commands {
+ if c.HelpName == "" {
+ c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
+ }
+ newCmds = append(newCmds, c)
+ }
+ a.Commands = newCmds
+
+ if a.Command(helpCommand.Name) == nil && !a.HideHelp {
+ a.Commands = append(a.Commands, helpCommand)
+ if (HelpFlag != BoolFlag{}) {
+ a.appendFlag(HelpFlag)
+ }
+ }
+
+ if !a.HideVersion {
+ a.appendFlag(VersionFlag)
+ }
+
+ a.categories = CommandCategories{}
+ for _, command := range a.Commands {
+ a.categories = a.categories.AddCommand(command.Category, command)
+ }
+ sort.Sort(a.categories)
+
+ if a.Metadata == nil {
+ a.Metadata = make(map[string]interface{})
+ }
+
+ if a.Writer == nil {
+ a.Writer = os.Stdout
+ }
+}
+
+// Run is the entry point to the cli app. Parses the arguments slice and routes
+// to the proper flag/args combination
+func (a *App) Run(arguments []string) (err error) {
+ a.Setup()
+
+ // handle the completion flag separately from the flagset since
+ // completion could be attempted after a flag, but before its value was put
+ // on the command line. this causes the flagset to interpret the completion
+ // flag name as the value of the flag before it which is undesirable
+ // note that we can only do this because the shell autocomplete function
+ // always appends the completion flag at the end of the command
+ shellComplete, arguments := checkShellCompleteFlag(a, arguments)
+
+ // parse flags
+ set, err := flagSet(a.Name, a.Flags)
+ if err != nil {
+ return err
+ }
+
+ set.SetOutput(ioutil.Discard)
+ err = set.Parse(arguments[1:])
+ nerr := normalizeFlags(a.Flags, set)
+ context := NewContext(a, set, nil)
+ if nerr != nil {
+ fmt.Fprintln(a.Writer, nerr)
+ ShowAppHelp(context)
+ return nerr
+ }
+ context.shellComplete = shellComplete
+
+ if checkCompletions(context) {
+ return nil
+ }
+
+ if err != nil {
+ if a.OnUsageError != nil {
+ err := a.OnUsageError(context, err, false)
+ HandleExitCoder(err)
+ return err
+ }
+ fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error())
+ ShowAppHelp(context)
+ return err
+ }
+
+ if !a.HideHelp && checkHelp(context) {
+ ShowAppHelp(context)
+ return nil
+ }
+
+ if !a.HideVersion && checkVersion(context) {
+ ShowVersion(context)
+ return nil
+ }
+
+ if a.After != nil {
+ defer func() {
+ if afterErr := a.After(context); afterErr != nil {
+ if err != nil {
+ err = NewMultiError(err, afterErr)
+ } else {
+ err = afterErr
+ }
+ }
+ }()
+ }
+
+ if a.Before != nil {
+ beforeErr := a.Before(context)
+ if beforeErr != nil {
+ fmt.Fprintf(a.Writer, "%v\n\n", beforeErr)
+ ShowAppHelp(context)
+ HandleExitCoder(beforeErr)
+ err = beforeErr
+ return err
+ }
+ }
+
+ args := context.Args()
+ if args.Present() {
+ name := args.First()
+ c := a.Command(name)
+ if c != nil {
+ return c.Run(context)
+ }
+ }
+
+ if a.Action == nil {
+ a.Action = helpCommand.Action
+ }
+
+ // Run default Action
+ err = HandleAction(a.Action, context)
+
+ HandleExitCoder(err)
+ return err
+}
+
+// RunAndExitOnError calls .Run() and exits non-zero if an error was returned
+//
+// Deprecated: instead you should return an error that fulfills cli.ExitCoder
+// to cli.App.Run. This will cause the application to exit with the given eror
+// code in the cli.ExitCoder
+func (a *App) RunAndExitOnError() {
+ if err := a.Run(os.Args); err != nil {
+ fmt.Fprintln(a.errWriter(), err)
+ OsExiter(1)
+ }
+}
+
+// RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to
+// generate command-specific flags
+func (a *App) RunAsSubcommand(ctx *Context) (err error) {
+ // append help to commands
+ if len(a.Commands) > 0 {
+ if a.Command(helpCommand.Name) == nil && !a.HideHelp {
+ a.Commands = append(a.Commands, helpCommand)
+ if (HelpFlag != BoolFlag{}) {
+ a.appendFlag(HelpFlag)
+ }
+ }
+ }
+
+ newCmds := []Command{}
+ for _, c := range a.Commands {
+ if c.HelpName == "" {
+ c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
+ }
+ newCmds = append(newCmds, c)
+ }
+ a.Commands = newCmds
+
+ // parse flags
+ set, err := flagSet(a.Name, a.Flags)
+ if err != nil {
+ return err
+ }
+
+ set.SetOutput(ioutil.Discard)
+ err = set.Parse(ctx.Args().Tail())
+ nerr := normalizeFlags(a.Flags, set)
+ context := NewContext(a, set, ctx)
+
+ if nerr != nil {
+ fmt.Fprintln(a.Writer, nerr)
+ fmt.Fprintln(a.Writer)
+ if len(a.Commands) > 0 {
+ ShowSubcommandHelp(context)
+ } else {
+ ShowCommandHelp(ctx, context.Args().First())
+ }
+ return nerr
+ }
+
+ if checkCompletions(context) {
+ return nil
+ }
+
+ if err != nil {
+ if a.OnUsageError != nil {
+ err = a.OnUsageError(context, err, true)
+ HandleExitCoder(err)
+ return err
+ }
+ fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error())
+ ShowSubcommandHelp(context)
+ return err
+ }
+
+ if len(a.Commands) > 0 {
+ if checkSubcommandHelp(context) {
+ return nil
+ }
+ } else {
+ if checkCommandHelp(ctx, context.Args().First()) {
+ return nil
+ }
+ }
+
+ if a.After != nil {
+ defer func() {
+ afterErr := a.After(context)
+ if afterErr != nil {
+ HandleExitCoder(err)
+ if err != nil {
+ err = NewMultiError(err, afterErr)
+ } else {
+ err = afterErr
+ }
+ }
+ }()
+ }
+
+ if a.Before != nil {
+ beforeErr := a.Before(context)
+ if beforeErr != nil {
+ HandleExitCoder(beforeErr)
+ err = beforeErr
+ return err
+ }
+ }
+
+ args := context.Args()
+ if args.Present() {
+ name := args.First()
+ c := a.Command(name)
+ if c != nil {
+ return c.Run(context)
+ }
+ }
+
+ // Run default Action
+ err = HandleAction(a.Action, context)
+
+ HandleExitCoder(err)
+ return err
+}
+
+// Command returns the named command on App. Returns nil if the command does not exist
+func (a *App) Command(name string) *Command {
+ for _, c := range a.Commands {
+ if c.HasName(name) {
+ return &c
+ }
+ }
+
+ return nil
+}
+
+// Categories returns a slice containing all the categories with the commands they contain
+func (a *App) Categories() CommandCategories {
+ return a.categories
+}
+
+// VisibleCategories returns a slice of categories and commands that are
+// Hidden=false
+func (a *App) VisibleCategories() []*CommandCategory {
+ ret := []*CommandCategory{}
+ for _, category := range a.categories {
+ if visible := func() *CommandCategory {
+ for _, command := range category.Commands {
+ if !command.Hidden {
+ return category
+ }
+ }
+ return nil
+ }(); visible != nil {
+ ret = append(ret, visible)
+ }
+ }
+ return ret
+}
+
+// VisibleCommands returns a slice of the Commands with Hidden=false
+func (a *App) VisibleCommands() []Command {
+ ret := []Command{}
+ for _, command := range a.Commands {
+ if !command.Hidden {
+ ret = append(ret, command)
+ }
+ }
+ return ret
+}
+
+// VisibleFlags returns a slice of the Flags with Hidden=false
+func (a *App) VisibleFlags() []Flag {
+ return visibleFlags(a.Flags)
+}
+
+func (a *App) hasFlag(flag Flag) bool {
+ for _, f := range a.Flags {
+ if flag == f {
+ return true
+ }
+ }
+
+ return false
+}
+
+func (a *App) errWriter() io.Writer {
+
+ // When the app ErrWriter is nil use the package level one.
+ if a.ErrWriter == nil {
+ return ErrWriter
+ }
+
+ return a.ErrWriter
+}
+
+func (a *App) appendFlag(flag Flag) {
+ if !a.hasFlag(flag) {
+ a.Flags = append(a.Flags, flag)
+ }
+}
+
+// Author represents someone who has contributed to a cli project.
+type Author struct {
+ Name string // The Authors name
+ Email string // The Authors email
+}
+
+// String makes Author comply to the Stringer interface, to allow an easy print in the templating process
+func (a Author) String() string {
+ e := ""
+ if a.Email != "" {
+ e = " <" + a.Email + ">"
+ }
+
+ return fmt.Sprintf("%v%v", a.Name, e)
+}
+
+// HandleAction attempts to figure out which Action signature was used. If
+// it's an ActionFunc or a func with the legacy signature for Action, the func
+// is run!
+func HandleAction(action interface{}, context *Context) (err error) {
+ if a, ok := action.(ActionFunc); ok {
+ return a(context)
+ } else if a, ok := action.(func(*Context) error); ok {
+ return a(context)
+ } else if a, ok := action.(func(*Context)); ok { // deprecated function signature
+ a(context)
+ return nil
+ } else {
+ return errInvalidActionType
+ }
+}
diff --git a/vendor/github.com/urfave/cli/category.go b/vendor/github.com/urfave/cli/category.go
new file mode 100644
index 0000000..1a60550
--- /dev/null
+++ b/vendor/github.com/urfave/cli/category.go
@@ -0,0 +1,44 @@
+package cli
+
+// CommandCategories is a slice of *CommandCategory.
+type CommandCategories []*CommandCategory
+
+// CommandCategory is a category containing commands.
+type CommandCategory struct {
+ Name string
+ Commands Commands
+}
+
+func (c CommandCategories) Less(i, j int) bool {
+ return c[i].Name < c[j].Name
+}
+
+func (c CommandCategories) Len() int {
+ return len(c)
+}
+
+func (c CommandCategories) Swap(i, j int) {
+ c[i], c[j] = c[j], c[i]
+}
+
+// AddCommand adds a command to a category.
+func (c CommandCategories) AddCommand(category string, command Command) CommandCategories {
+ for _, commandCategory := range c {
+ if commandCategory.Name == category {
+ commandCategory.Commands = append(commandCategory.Commands, command)
+ return c
+ }
+ }
+ return append(c, &CommandCategory{Name: category, Commands: []Command{command}})
+}
+
+// VisibleCommands returns a slice of the Commands with Hidden=false
+func (c *CommandCategory) VisibleCommands() []Command {
+ ret := []Command{}
+ for _, command := range c.Commands {
+ if !command.Hidden {
+ ret = append(ret, command)
+ }
+ }
+ return ret
+}
diff --git a/vendor/github.com/urfave/cli/cli.go b/vendor/github.com/urfave/cli/cli.go
new file mode 100644
index 0000000..74fd101
--- /dev/null
+++ b/vendor/github.com/urfave/cli/cli.go
@@ -0,0 +1,21 @@
+// Package cli provides a minimal framework for creating and organizing command line
+// Go applications. cli is designed to be easy to understand and write, the most simple
+// cli application can be written as follows:
+// func main() {
+// cli.NewApp().Run(os.Args)
+// }
+//
+// Of course this application does not do much, so let's make this an actual application:
+// func main() {
+// app := cli.NewApp()
+// app.Name = "greet"
+// app.Usage = "say a greeting"
+// app.Action = func(c *cli.Context) error {
+// println("Greetings")
+// }
+//
+// app.Run(os.Args)
+// }
+package cli
+
+//go:generate python ./generate-flag-types cli -i flag-types.json -o flag_generated.go
diff --git a/vendor/github.com/urfave/cli/command.go b/vendor/github.com/urfave/cli/command.go
new file mode 100644
index 0000000..40ebdb6
--- /dev/null
+++ b/vendor/github.com/urfave/cli/command.go
@@ -0,0 +1,299 @@
+package cli
+
+import (
+ "fmt"
+ "io/ioutil"
+ "sort"
+ "strings"
+)
+
+// Command is a subcommand for a cli.App.
+type Command struct {
+ // The name of the command
+ Name string
+ // short name of the command. Typically one character (deprecated, use `Aliases`)
+ ShortName string
+ // A list of aliases for the command
+ Aliases []string
+ // A short description of the usage of this command
+ Usage string
+ // Custom text to show on USAGE section of help
+ UsageText string
+ // A longer explanation of how the command works
+ Description string
+ // A short description of the arguments of this command
+ ArgsUsage string
+ // The category the command is part of
+ Category string
+ // The function to call when checking for bash command completions
+ BashComplete BashCompleteFunc
+ // An action to execute before any sub-subcommands are run, but after the context is ready
+ // If a non-nil error is returned, no sub-subcommands are run
+ Before BeforeFunc
+ // An action to execute after any subcommands are run, but after the subcommand has finished
+ // It is run even if Action() panics
+ After AfterFunc
+ // The function to call when this command is invoked
+ Action interface{}
+ // TODO: replace `Action: interface{}` with `Action: ActionFunc` once some kind
+ // of deprecation period has passed, maybe?
+
+ // Execute this function if a usage error occurs.
+ OnUsageError OnUsageErrorFunc
+ // List of child commands
+ Subcommands Commands
+ // List of flags to parse
+ Flags []Flag
+ // Treat all flags as normal arguments if true
+ SkipFlagParsing bool
+ // Skip argument reordering which attempts to move flags before arguments,
+ // but only works if all flags appear after all arguments. This behavior was
+ // removed n version 2 since it only works under specific conditions so we
+ // backport here by exposing it as an option for compatibility.
+ SkipArgReorder bool
+ // Boolean to hide built-in help command
+ HideHelp bool
+ // Boolean to hide this command from help or completion
+ Hidden bool
+
+ // Full name of command for help, defaults to full command name, including parent commands.
+ HelpName string
+ commandNamePath []string
+}
+
+type CommandsByName []Command
+
+func (c CommandsByName) Len() int {
+ return len(c)
+}
+
+func (c CommandsByName) Less(i, j int) bool {
+ return c[i].Name < c[j].Name
+}
+
+func (c CommandsByName) Swap(i, j int) {
+ c[i], c[j] = c[j], c[i]
+}
+
+// FullName returns the full name of the command.
+// For subcommands this ensures that parent commands are part of the command path
+func (c Command) FullName() string {
+ if c.commandNamePath == nil {
+ return c.Name
+ }
+ return strings.Join(c.commandNamePath, " ")
+}
+
+// Commands is a slice of Command
+type Commands []Command
+
+// Run invokes the command given the context, parses ctx.Args() to generate command-specific flags
+func (c Command) Run(ctx *Context) (err error) {
+ if len(c.Subcommands) > 0 {
+ return c.startApp(ctx)
+ }
+
+ if !c.HideHelp && (HelpFlag != BoolFlag{}) {
+ // append help to flags
+ c.Flags = append(
+ c.Flags,
+ HelpFlag,
+ )
+ }
+
+ set, err := flagSet(c.Name, c.Flags)
+ if err != nil {
+ return err
+ }
+ set.SetOutput(ioutil.Discard)
+
+ if c.SkipFlagParsing {
+ err = set.Parse(append([]string{"--"}, ctx.Args().Tail()...))
+ } else if !c.SkipArgReorder {
+ firstFlagIndex := -1
+ terminatorIndex := -1
+ for index, arg := range ctx.Args() {
+ if arg == "--" {
+ terminatorIndex = index
+ break
+ } else if arg == "-" {
+ // Do nothing. A dash alone is not really a flag.
+ continue
+ } else if strings.HasPrefix(arg, "-") && firstFlagIndex == -1 {
+ firstFlagIndex = index
+ }
+ }
+
+ if firstFlagIndex > -1 {
+ args := ctx.Args()
+ regularArgs := make([]string, len(args[1:firstFlagIndex]))
+ copy(regularArgs, args[1:firstFlagIndex])
+
+ var flagArgs []string
+ if terminatorIndex > -1 {
+ flagArgs = args[firstFlagIndex:terminatorIndex]
+ regularArgs = append(regularArgs, args[terminatorIndex:]...)
+ } else {
+ flagArgs = args[firstFlagIndex:]
+ }
+
+ err = set.Parse(append(flagArgs, regularArgs...))
+ } else {
+ err = set.Parse(ctx.Args().Tail())
+ }
+ } else {
+ err = set.Parse(ctx.Args().Tail())
+ }
+
+ nerr := normalizeFlags(c.Flags, set)
+ if nerr != nil {
+ fmt.Fprintln(ctx.App.Writer, nerr)
+ fmt.Fprintln(ctx.App.Writer)
+ ShowCommandHelp(ctx, c.Name)
+ return nerr
+ }
+
+ context := NewContext(ctx.App, set, ctx)
+ if checkCommandCompletions(context, c.Name) {
+ return nil
+ }
+
+ if err != nil {
+ if c.OnUsageError != nil {
+ err := c.OnUsageError(ctx, err, false)
+ HandleExitCoder(err)
+ return err
+ }
+ fmt.Fprintln(ctx.App.Writer, "Incorrect Usage:", err.Error())
+ fmt.Fprintln(ctx.App.Writer)
+ ShowCommandHelp(ctx, c.Name)
+ return err
+ }
+
+ if checkCommandHelp(context, c.Name) {
+ return nil
+ }
+
+ if c.After != nil {
+ defer func() {
+ afterErr := c.After(context)
+ if afterErr != nil {
+ HandleExitCoder(err)
+ if err != nil {
+ err = NewMultiError(err, afterErr)
+ } else {
+ err = afterErr
+ }
+ }
+ }()
+ }
+
+ if c.Before != nil {
+ err = c.Before(context)
+ if err != nil {
+ fmt.Fprintln(ctx.App.Writer, err)
+ fmt.Fprintln(ctx.App.Writer)
+ ShowCommandHelp(ctx, c.Name)
+ HandleExitCoder(err)
+ return err
+ }
+ }
+
+ if c.Action == nil {
+ c.Action = helpSubcommand.Action
+ }
+
+ context.Command = c
+ err = HandleAction(c.Action, context)
+
+ if err != nil {
+ HandleExitCoder(err)
+ }
+ return err
+}
+
+// Names returns the names including short names and aliases.
+func (c Command) Names() []string {
+ names := []string{c.Name}
+
+ if c.ShortName != "" {
+ names = append(names, c.ShortName)
+ }
+
+ return append(names, c.Aliases...)
+}
+
+// HasName returns true if Command.Name or Command.ShortName matches given name
+func (c Command) HasName(name string) bool {
+ for _, n := range c.Names() {
+ if n == name {
+ return true
+ }
+ }
+ return false
+}
+
+func (c Command) startApp(ctx *Context) error {
+ app := NewApp()
+ app.Metadata = ctx.App.Metadata
+ // set the name and usage
+ app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name)
+ if c.HelpName == "" {
+ app.HelpName = c.HelpName
+ } else {
+ app.HelpName = app.Name
+ }
+
+ app.Usage = c.Usage
+ app.Description = c.Description
+ app.ArgsUsage = c.ArgsUsage
+
+ // set CommandNotFound
+ app.CommandNotFound = ctx.App.CommandNotFound
+
+ // set the flags and commands
+ app.Commands = c.Subcommands
+ app.Flags = c.Flags
+ app.HideHelp = c.HideHelp
+
+ app.Version = ctx.App.Version
+ app.HideVersion = ctx.App.HideVersion
+ app.Compiled = ctx.App.Compiled
+ app.Author = ctx.App.Author
+ app.Email = ctx.App.Email
+ app.Writer = ctx.App.Writer
+ app.ErrWriter = ctx.App.ErrWriter
+
+ app.categories = CommandCategories{}
+ for _, command := range c.Subcommands {
+ app.categories = app.categories.AddCommand(command.Category, command)
+ }
+
+ sort.Sort(app.categories)
+
+ // bash completion
+ app.EnableBashCompletion = ctx.App.EnableBashCompletion
+ if c.BashComplete != nil {
+ app.BashComplete = c.BashComplete
+ }
+
+ // set the actions
+ app.Before = c.Before
+ app.After = c.After
+ if c.Action != nil {
+ app.Action = c.Action
+ } else {
+ app.Action = helpSubcommand.Action
+ }
+
+ for index, cc := range app.Commands {
+ app.Commands[index].commandNamePath = []string{c.Name, cc.Name}
+ }
+
+ return app.RunAsSubcommand(ctx)
+}
+
+// VisibleFlags returns a slice of the Flags with Hidden=false
+func (c Command) VisibleFlags() []Flag {
+ return visibleFlags(c.Flags)
+}
diff --git a/vendor/github.com/urfave/cli/context.go b/vendor/github.com/urfave/cli/context.go
new file mode 100644
index 0000000..cb89e92
--- /dev/null
+++ b/vendor/github.com/urfave/cli/context.go
@@ -0,0 +1,276 @@
+package cli
+
+import (
+ "errors"
+ "flag"
+ "reflect"
+ "strings"
+ "syscall"
+)
+
+// Context is a type that is passed through to
+// each Handler action in a cli application. Context
+// can be used to retrieve context-specific Args and
+// parsed command-line options.
+type Context struct {
+ App *App
+ Command Command
+ shellComplete bool
+ flagSet *flag.FlagSet
+ setFlags map[string]bool
+ parentContext *Context
+}
+
+// NewContext creates a new context. For use in when invoking an App or Command action.
+func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context {
+ c := &Context{App: app, flagSet: set, parentContext: parentCtx}
+
+ if parentCtx != nil {
+ c.shellComplete = parentCtx.shellComplete
+ }
+
+ return c
+}
+
+// NumFlags returns the number of flags set
+func (c *Context) NumFlags() int {
+ return c.flagSet.NFlag()
+}
+
+// Set sets a context flag to a value.
+func (c *Context) Set(name, value string) error {
+ return c.flagSet.Set(name, value)
+}
+
+// GlobalSet sets a context flag to a value on the global flagset
+func (c *Context) GlobalSet(name, value string) error {
+ return globalContext(c).flagSet.Set(name, value)
+}
+
+// IsSet determines if the flag was actually set
+func (c *Context) IsSet(name string) bool {
+ if c.setFlags == nil {
+ c.setFlags = make(map[string]bool)
+
+ c.flagSet.Visit(func(f *flag.Flag) {
+ c.setFlags[f.Name] = true
+ })
+
+ c.flagSet.VisitAll(func(f *flag.Flag) {
+ if _, ok := c.setFlags[f.Name]; ok {
+ return
+ }
+ c.setFlags[f.Name] = false
+ })
+
+ // XXX hack to support IsSet for flags with EnvVar
+ //
+ // There isn't an easy way to do this with the current implementation since
+ // whether a flag was set via an environment variable is very difficult to
+ // determine here. Instead, we intend to introduce a backwards incompatible
+ // change in version 2 to add `IsSet` to the Flag interface to push the
+ // responsibility closer to where the information required to determine
+ // whether a flag is set by non-standard means such as environment
+ // variables is avaliable.
+ //
+ // See https://github.com/urfave/cli/issues/294 for additional discussion
+ flags := c.Command.Flags
+ if c.Command.Name == "" { // cannot == Command{} since it contains slice types
+ if c.App != nil {
+ flags = c.App.Flags
+ }
+ }
+ for _, f := range flags {
+ eachName(f.GetName(), func(name string) {
+ if isSet, ok := c.setFlags[name]; isSet || !ok {
+ return
+ }
+
+ val := reflect.ValueOf(f)
+ if val.Kind() == reflect.Ptr {
+ val = val.Elem()
+ }
+
+ envVarValue := val.FieldByName("EnvVar")
+ if !envVarValue.IsValid() {
+ return
+ }
+
+ eachName(envVarValue.String(), func(envVar string) {
+ envVar = strings.TrimSpace(envVar)
+ if _, ok := syscall.Getenv(envVar); ok {
+ c.setFlags[name] = true
+ return
+ }
+ })
+ })
+ }
+ }
+
+ return c.setFlags[name]
+}
+
+// GlobalIsSet determines if the global flag was actually set
+func (c *Context) GlobalIsSet(name string) bool {
+ ctx := c
+ if ctx.parentContext != nil {
+ ctx = ctx.parentContext
+ }
+
+ for ; ctx != nil; ctx = ctx.parentContext {
+ if ctx.IsSet(name) {
+ return true
+ }
+ }
+ return false
+}
+
+// FlagNames returns a slice of flag names used in this context.
+func (c *Context) FlagNames() (names []string) {
+ for _, flag := range c.Command.Flags {
+ name := strings.Split(flag.GetName(), ",")[0]
+ if name == "help" {
+ continue
+ }
+ names = append(names, name)
+ }
+ return
+}
+
+// GlobalFlagNames returns a slice of global flag names used by the app.
+func (c *Context) GlobalFlagNames() (names []string) {
+ for _, flag := range c.App.Flags {
+ name := strings.Split(flag.GetName(), ",")[0]
+ if name == "help" || name == "version" {
+ continue
+ }
+ names = append(names, name)
+ }
+ return
+}
+
+// Parent returns the parent context, if any
+func (c *Context) Parent() *Context {
+ return c.parentContext
+}
+
+// value returns the value of the flag coressponding to `name`
+func (c *Context) value(name string) interface{} {
+ return c.flagSet.Lookup(name).Value.(flag.Getter).Get()
+}
+
+// Args contains apps console arguments
+type Args []string
+
+// Args returns the command line arguments associated with the context.
+func (c *Context) Args() Args {
+ args := Args(c.flagSet.Args())
+ return args
+}
+
+// NArg returns the number of the command line arguments.
+func (c *Context) NArg() int {
+ return len(c.Args())
+}
+
+// Get returns the nth argument, or else a blank string
+func (a Args) Get(n int) string {
+ if len(a) > n {
+ return a[n]
+ }
+ return ""
+}
+
+// First returns the first argument, or else a blank string
+func (a Args) First() string {
+ return a.Get(0)
+}
+
+// Tail returns the rest of the arguments (not the first one)
+// or else an empty string slice
+func (a Args) Tail() []string {
+ if len(a) >= 2 {
+ return []string(a)[1:]
+ }
+ return []string{}
+}
+
+// Present checks if there are any arguments present
+func (a Args) Present() bool {
+ return len(a) != 0
+}
+
+// Swap swaps arguments at the given indexes
+func (a Args) Swap(from, to int) error {
+ if from >= len(a) || to >= len(a) {
+ return errors.New("index out of range")
+ }
+ a[from], a[to] = a[to], a[from]
+ return nil
+}
+
+func globalContext(ctx *Context) *Context {
+ if ctx == nil {
+ return nil
+ }
+
+ for {
+ if ctx.parentContext == nil {
+ return ctx
+ }
+ ctx = ctx.parentContext
+ }
+}
+
+func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
+ if ctx.parentContext != nil {
+ ctx = ctx.parentContext
+ }
+ for ; ctx != nil; ctx = ctx.parentContext {
+ if f := ctx.flagSet.Lookup(name); f != nil {
+ return ctx.flagSet
+ }
+ }
+ return nil
+}
+
+func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
+ switch ff.Value.(type) {
+ case *StringSlice:
+ default:
+ set.Set(name, ff.Value.String())
+ }
+}
+
+func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
+ visited := make(map[string]bool)
+ set.Visit(func(f *flag.Flag) {
+ visited[f.Name] = true
+ })
+ for _, f := range flags {
+ parts := strings.Split(f.GetName(), ",")
+ if len(parts) == 1 {
+ continue
+ }
+ var ff *flag.Flag
+ for _, name := range parts {
+ name = strings.Trim(name, " ")
+ if visited[name] {
+ if ff != nil {
+ return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
+ }
+ ff = set.Lookup(name)
+ }
+ }
+ if ff == nil {
+ continue
+ }
+ for _, name := range parts {
+ name = strings.Trim(name, " ")
+ if !visited[name] {
+ copyFlag(name, ff, set)
+ }
+ }
+ }
+ return nil
+}
diff --git a/vendor/github.com/urfave/cli/errors.go b/vendor/github.com/urfave/cli/errors.go
new file mode 100644
index 0000000..562b295
--- /dev/null
+++ b/vendor/github.com/urfave/cli/errors.go
@@ -0,0 +1,115 @@
+package cli
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "strings"
+)
+
+// OsExiter is the function used when the app exits. If not set defaults to os.Exit.
+var OsExiter = os.Exit
+
+// ErrWriter is used to write errors to the user. This can be anything
+// implementing the io.Writer interface and defaults to os.Stderr.
+var ErrWriter io.Writer = os.Stderr
+
+// MultiError is an error that wraps multiple errors.
+type MultiError struct {
+ Errors []error
+}
+
+// NewMultiError creates a new MultiError. Pass in one or more errors.
+func NewMultiError(err ...error) MultiError {
+ return MultiError{Errors: err}
+}
+
+// Error implements the error interface.
+func (m MultiError) Error() string {
+ errs := make([]string, len(m.Errors))
+ for i, err := range m.Errors {
+ errs[i] = err.Error()
+ }
+
+ return strings.Join(errs, "\n")
+}
+
+type ErrorFormatter interface {
+ Format(s fmt.State, verb rune)
+}
+
+// ExitCoder is the interface checked by `App` and `Command` for a custom exit
+// code
+type ExitCoder interface {
+ error
+ ExitCode() int
+}
+
+// ExitError fulfills both the builtin `error` interface and `ExitCoder`
+type ExitError struct {
+ exitCode int
+ message interface{}
+}
+
+// NewExitError makes a new *ExitError
+func NewExitError(message interface{}, exitCode int) *ExitError {
+ return &ExitError{
+ exitCode: exitCode,
+ message: message,
+ }
+}
+
+// Error returns the string message, fulfilling the interface required by
+// `error`
+func (ee *ExitError) Error() string {
+ return fmt.Sprintf("%v", ee.message)
+}
+
+// ExitCode returns the exit code, fulfilling the interface required by
+// `ExitCoder`
+func (ee *ExitError) ExitCode() int {
+ return ee.exitCode
+}
+
+// HandleExitCoder checks if the error fulfills the ExitCoder interface, and if
+// so prints the error to stderr (if it is non-empty) and calls OsExiter with the
+// given exit code. If the given error is a MultiError, then this func is
+// called on all members of the Errors slice and calls OsExiter with the last exit code.
+func HandleExitCoder(err error) {
+ if err == nil {
+ return
+ }
+
+ if exitErr, ok := err.(ExitCoder); ok {
+ if err.Error() != "" {
+ if _, ok := exitErr.(ErrorFormatter); ok {
+ fmt.Fprintf(ErrWriter, "%+v\n", err)
+ } else {
+ fmt.Fprintln(ErrWriter, err)
+ }
+ }
+ OsExiter(exitErr.ExitCode())
+ return
+ }
+
+ if multiErr, ok := err.(MultiError); ok {
+ code := handleMultiError(multiErr)
+ OsExiter(code)
+ return
+ }
+}
+
+func handleMultiError(multiErr MultiError) int {
+ code := 1
+ for _, merr := range multiErr.Errors {
+ if multiErr2, ok := merr.(MultiError); ok {
+ code = handleMultiError(multiErr2)
+ } else {
+ fmt.Fprintln(ErrWriter, merr)
+ if exitErr, ok := merr.(ExitCoder); ok {
+ code = exitErr.ExitCode()
+ }
+ }
+ }
+ return code
+}
diff --git a/vendor/github.com/urfave/cli/flag.go b/vendor/github.com/urfave/cli/flag.go
new file mode 100644
index 0000000..7dd8a2c
--- /dev/null
+++ b/vendor/github.com/urfave/cli/flag.go
@@ -0,0 +1,799 @@
+package cli
+
+import (
+ "flag"
+ "fmt"
+ "reflect"
+ "runtime"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+)
+
+const defaultPlaceholder = "value"
+
+// BashCompletionFlag enables bash-completion for all commands and subcommands
+var BashCompletionFlag = BoolFlag{
+ Name: "generate-bash-completion",
+ Hidden: true,
+}
+
+// VersionFlag prints the version for the application
+var VersionFlag = BoolFlag{
+ Name: "version, v",
+ Usage: "print the version",
+}
+
+// HelpFlag prints the help for all commands and subcommands
+// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand
+// unless HideHelp is set to true)
+var HelpFlag = BoolFlag{
+ Name: "help, h",
+ Usage: "show help",
+}
+
+// FlagStringer converts a flag definition to a string. This is used by help
+// to display a flag.
+var FlagStringer FlagStringFunc = stringifyFlag
+
+// FlagsByName is a slice of Flag.
+type FlagsByName []Flag
+
+func (f FlagsByName) Len() int {
+ return len(f)
+}
+
+func (f FlagsByName) Less(i, j int) bool {
+ return f[i].GetName() < f[j].GetName()
+}
+
+func (f FlagsByName) Swap(i, j int) {
+ f[i], f[j] = f[j], f[i]
+}
+
+// Flag is a common interface related to parsing flags in cli.
+// For more advanced flag parsing techniques, it is recommended that
+// this interface be implemented.
+type Flag interface {
+ fmt.Stringer
+ // Apply Flag settings to the given flag set
+ Apply(*flag.FlagSet)
+ GetName() string
+}
+
+// errorableFlag is an interface that allows us to return errors during apply
+// it allows flags defined in this library to return errors in a fashion backwards compatible
+// TODO remove in v2 and modify the existing Flag interface to return errors
+type errorableFlag interface {
+ Flag
+
+ ApplyWithError(*flag.FlagSet) error
+}
+
+func flagSet(name string, flags []Flag) (*flag.FlagSet, error) {
+ set := flag.NewFlagSet(name, flag.ContinueOnError)
+
+ for _, f := range flags {
+ //TODO remove in v2 when errorableFlag is removed
+ if ef, ok := f.(errorableFlag); ok {
+ if err := ef.ApplyWithError(set); err != nil {
+ return nil, err
+ }
+ } else {
+ f.Apply(set)
+ }
+ }
+ return set, nil
+}
+
+func eachName(longName string, fn func(string)) {
+ parts := strings.Split(longName, ",")
+ for _, name := range parts {
+ name = strings.Trim(name, " ")
+ fn(name)
+ }
+}
+
+// Generic is a generic parseable type identified by a specific flag
+type Generic interface {
+ Set(value string) error
+ String() string
+}
+
+// Apply takes the flagset and calls Set on the generic flag with the value
+// provided by the user for parsing by the flag
+// Ignores parsing errors
+func (f GenericFlag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError takes the flagset and calls Set on the generic flag with the value
+// provided by the user for parsing by the flag
+func (f GenericFlag) ApplyWithError(set *flag.FlagSet) error {
+ val := f.Value
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ if err := val.Set(envVal); err != nil {
+ return fmt.Errorf("could not parse %s as value for flag %s: %s", envVal, f.Name, err)
+ }
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ set.Var(f.Value, name, f.Usage)
+ })
+
+ return nil
+}
+
+// StringSlice is an opaque type for []string to satisfy flag.Value and flag.Getter
+type StringSlice []string
+
+// Set appends the string value to the list of values
+func (f *StringSlice) Set(value string) error {
+ *f = append(*f, value)
+ return nil
+}
+
+// String returns a readable representation of this value (for usage defaults)
+func (f *StringSlice) String() string {
+ return fmt.Sprintf("%s", *f)
+}
+
+// Value returns the slice of strings set by this flag
+func (f *StringSlice) Value() []string {
+ return *f
+}
+
+// Get returns the slice of strings set by this flag
+func (f *StringSlice) Get() interface{} {
+ return *f
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f StringSliceFlag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f StringSliceFlag) ApplyWithError(set *flag.FlagSet) error {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ newVal := &StringSlice{}
+ for _, s := range strings.Split(envVal, ",") {
+ s = strings.TrimSpace(s)
+ if err := newVal.Set(s); err != nil {
+ return fmt.Errorf("could not parse %s as string value for flag %s: %s", envVal, f.Name, err)
+ }
+ }
+ f.Value = newVal
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Value == nil {
+ f.Value = &StringSlice{}
+ }
+ set.Var(f.Value, name, f.Usage)
+ })
+
+ return nil
+}
+
+// IntSlice is an opaque type for []int to satisfy flag.Value and flag.Getter
+type IntSlice []int
+
+// Set parses the value into an integer and appends it to the list of values
+func (f *IntSlice) Set(value string) error {
+ tmp, err := strconv.Atoi(value)
+ if err != nil {
+ return err
+ }
+ *f = append(*f, tmp)
+ return nil
+}
+
+// String returns a readable representation of this value (for usage defaults)
+func (f *IntSlice) String() string {
+ return fmt.Sprintf("%#v", *f)
+}
+
+// Value returns the slice of ints set by this flag
+func (f *IntSlice) Value() []int {
+ return *f
+}
+
+// Get returns the slice of ints set by this flag
+func (f *IntSlice) Get() interface{} {
+ return *f
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f IntSliceFlag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f IntSliceFlag) ApplyWithError(set *flag.FlagSet) error {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ newVal := &IntSlice{}
+ for _, s := range strings.Split(envVal, ",") {
+ s = strings.TrimSpace(s)
+ if err := newVal.Set(s); err != nil {
+ return fmt.Errorf("could not parse %s as int slice value for flag %s: %s", envVal, f.Name, err)
+ }
+ }
+ f.Value = newVal
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Value == nil {
+ f.Value = &IntSlice{}
+ }
+ set.Var(f.Value, name, f.Usage)
+ })
+
+ return nil
+}
+
+// Int64Slice is an opaque type for []int to satisfy flag.Value and flag.Getter
+type Int64Slice []int64
+
+// Set parses the value into an integer and appends it to the list of values
+func (f *Int64Slice) Set(value string) error {
+ tmp, err := strconv.ParseInt(value, 10, 64)
+ if err != nil {
+ return err
+ }
+ *f = append(*f, tmp)
+ return nil
+}
+
+// String returns a readable representation of this value (for usage defaults)
+func (f *Int64Slice) String() string {
+ return fmt.Sprintf("%#v", *f)
+}
+
+// Value returns the slice of ints set by this flag
+func (f *Int64Slice) Value() []int64 {
+ return *f
+}
+
+// Get returns the slice of ints set by this flag
+func (f *Int64Slice) Get() interface{} {
+ return *f
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f Int64SliceFlag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f Int64SliceFlag) ApplyWithError(set *flag.FlagSet) error {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ newVal := &Int64Slice{}
+ for _, s := range strings.Split(envVal, ",") {
+ s = strings.TrimSpace(s)
+ if err := newVal.Set(s); err != nil {
+ return fmt.Errorf("could not parse %s as int64 slice value for flag %s: %s", envVal, f.Name, err)
+ }
+ }
+ f.Value = newVal
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Value == nil {
+ f.Value = &Int64Slice{}
+ }
+ set.Var(f.Value, name, f.Usage)
+ })
+ return nil
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f BoolFlag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f BoolFlag) ApplyWithError(set *flag.FlagSet) error {
+ val := false
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ if envVal == "" {
+ val = false
+ break
+ }
+
+ envValBool, err := strconv.ParseBool(envVal)
+ if err != nil {
+ return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err)
+ }
+
+ val = envValBool
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.BoolVar(f.Destination, name, val, f.Usage)
+ return
+ }
+ set.Bool(name, val, f.Usage)
+ })
+
+ return nil
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f BoolTFlag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f BoolTFlag) ApplyWithError(set *flag.FlagSet) error {
+ val := true
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ if envVal == "" {
+ val = false
+ break
+ }
+
+ envValBool, err := strconv.ParseBool(envVal)
+ if err != nil {
+ return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err)
+ }
+
+ val = envValBool
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.BoolVar(f.Destination, name, val, f.Usage)
+ return
+ }
+ set.Bool(name, val, f.Usage)
+ })
+
+ return nil
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f StringFlag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f StringFlag) ApplyWithError(set *flag.FlagSet) error {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ f.Value = envVal
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.StringVar(f.Destination, name, f.Value, f.Usage)
+ return
+ }
+ set.String(name, f.Value, f.Usage)
+ })
+
+ return nil
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f IntFlag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f IntFlag) ApplyWithError(set *flag.FlagSet) error {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ envValInt, err := strconv.ParseInt(envVal, 0, 64)
+ if err != nil {
+ return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err)
+ }
+ f.Value = int(envValInt)
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.IntVar(f.Destination, name, f.Value, f.Usage)
+ return
+ }
+ set.Int(name, f.Value, f.Usage)
+ })
+
+ return nil
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f Int64Flag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f Int64Flag) ApplyWithError(set *flag.FlagSet) error {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ envValInt, err := strconv.ParseInt(envVal, 0, 64)
+ if err != nil {
+ return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err)
+ }
+
+ f.Value = envValInt
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.Int64Var(f.Destination, name, f.Value, f.Usage)
+ return
+ }
+ set.Int64(name, f.Value, f.Usage)
+ })
+
+ return nil
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f UintFlag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f UintFlag) ApplyWithError(set *flag.FlagSet) error {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ envValInt, err := strconv.ParseUint(envVal, 0, 64)
+ if err != nil {
+ return fmt.Errorf("could not parse %s as uint value for flag %s: %s", envVal, f.Name, err)
+ }
+
+ f.Value = uint(envValInt)
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.UintVar(f.Destination, name, f.Value, f.Usage)
+ return
+ }
+ set.Uint(name, f.Value, f.Usage)
+ })
+
+ return nil
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f Uint64Flag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f Uint64Flag) ApplyWithError(set *flag.FlagSet) error {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ envValInt, err := strconv.ParseUint(envVal, 0, 64)
+ if err != nil {
+ return fmt.Errorf("could not parse %s as uint64 value for flag %s: %s", envVal, f.Name, err)
+ }
+
+ f.Value = uint64(envValInt)
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.Uint64Var(f.Destination, name, f.Value, f.Usage)
+ return
+ }
+ set.Uint64(name, f.Value, f.Usage)
+ })
+
+ return nil
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f DurationFlag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f DurationFlag) ApplyWithError(set *flag.FlagSet) error {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ envValDuration, err := time.ParseDuration(envVal)
+ if err != nil {
+ return fmt.Errorf("could not parse %s as duration for flag %s: %s", envVal, f.Name, err)
+ }
+
+ f.Value = envValDuration
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.DurationVar(f.Destination, name, f.Value, f.Usage)
+ return
+ }
+ set.Duration(name, f.Value, f.Usage)
+ })
+
+ return nil
+}
+
+// Apply populates the flag given the flag set and environment
+// Ignores errors
+func (f Float64Flag) Apply(set *flag.FlagSet) {
+ f.ApplyWithError(set)
+}
+
+// ApplyWithError populates the flag given the flag set and environment
+func (f Float64Flag) ApplyWithError(set *flag.FlagSet) error {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal, ok := syscall.Getenv(envVar); ok {
+ envValFloat, err := strconv.ParseFloat(envVal, 10)
+ if err != nil {
+ return fmt.Errorf("could not parse %s as float64 value for flag %s: %s", envVal, f.Name, err)
+ }
+
+ f.Value = float64(envValFloat)
+ break
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.Float64Var(f.Destination, name, f.Value, f.Usage)
+ return
+ }
+ set.Float64(name, f.Value, f.Usage)
+ })
+
+ return nil
+}
+
+func visibleFlags(fl []Flag) []Flag {
+ visible := []Flag{}
+ for _, flag := range fl {
+ if !flagValue(flag).FieldByName("Hidden").Bool() {
+ visible = append(visible, flag)
+ }
+ }
+ return visible
+}
+
+func prefixFor(name string) (prefix string) {
+ if len(name) == 1 {
+ prefix = "-"
+ } else {
+ prefix = "--"
+ }
+
+ return
+}
+
+// Returns the placeholder, if any, and the unquoted usage string.
+func unquoteUsage(usage string) (string, string) {
+ for i := 0; i < len(usage); i++ {
+ if usage[i] == '`' {
+ for j := i + 1; j < len(usage); j++ {
+ if usage[j] == '`' {
+ name := usage[i+1 : j]
+ usage = usage[:i] + name + usage[j+1:]
+ return name, usage
+ }
+ }
+ break
+ }
+ }
+ return "", usage
+}
+
+func prefixedNames(fullName, placeholder string) string {
+ var prefixed string
+ parts := strings.Split(fullName, ",")
+ for i, name := range parts {
+ name = strings.Trim(name, " ")
+ prefixed += prefixFor(name) + name
+ if placeholder != "" {
+ prefixed += " " + placeholder
+ }
+ if i < len(parts)-1 {
+ prefixed += ", "
+ }
+ }
+ return prefixed
+}
+
+func withEnvHint(envVar, str string) string {
+ envText := ""
+ if envVar != "" {
+ prefix := "$"
+ suffix := ""
+ sep := ", $"
+ if runtime.GOOS == "windows" {
+ prefix = "%"
+ suffix = "%"
+ sep = "%, %"
+ }
+ envText = fmt.Sprintf(" [%s%s%s]", prefix, strings.Join(strings.Split(envVar, ","), sep), suffix)
+ }
+ return str + envText
+}
+
+func flagValue(f Flag) reflect.Value {
+ fv := reflect.ValueOf(f)
+ for fv.Kind() == reflect.Ptr {
+ fv = reflect.Indirect(fv)
+ }
+ return fv
+}
+
+func stringifyFlag(f Flag) string {
+ fv := flagValue(f)
+
+ switch f.(type) {
+ case IntSliceFlag:
+ return withEnvHint(fv.FieldByName("EnvVar").String(),
+ stringifyIntSliceFlag(f.(IntSliceFlag)))
+ case Int64SliceFlag:
+ return withEnvHint(fv.FieldByName("EnvVar").String(),
+ stringifyInt64SliceFlag(f.(Int64SliceFlag)))
+ case StringSliceFlag:
+ return withEnvHint(fv.FieldByName("EnvVar").String(),
+ stringifyStringSliceFlag(f.(StringSliceFlag)))
+ }
+
+ placeholder, usage := unquoteUsage(fv.FieldByName("Usage").String())
+
+ needsPlaceholder := false
+ defaultValueString := ""
+ val := fv.FieldByName("Value")
+
+ if val.IsValid() {
+ needsPlaceholder = true
+ defaultValueString = fmt.Sprintf(" (default: %v)", val.Interface())
+
+ if val.Kind() == reflect.String && val.String() != "" {
+ defaultValueString = fmt.Sprintf(" (default: %q)", val.String())
+ }
+ }
+
+ if defaultValueString == " (default: )" {
+ defaultValueString = ""
+ }
+
+ if needsPlaceholder && placeholder == "" {
+ placeholder = defaultPlaceholder
+ }
+
+ usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultValueString))
+
+ return withEnvHint(fv.FieldByName("EnvVar").String(),
+ fmt.Sprintf("%s\t%s", prefixedNames(fv.FieldByName("Name").String(), placeholder), usageWithDefault))
+}
+
+func stringifyIntSliceFlag(f IntSliceFlag) string {
+ defaultVals := []string{}
+ if f.Value != nil && len(f.Value.Value()) > 0 {
+ for _, i := range f.Value.Value() {
+ defaultVals = append(defaultVals, fmt.Sprintf("%d", i))
+ }
+ }
+
+ return stringifySliceFlag(f.Usage, f.Name, defaultVals)
+}
+
+func stringifyInt64SliceFlag(f Int64SliceFlag) string {
+ defaultVals := []string{}
+ if f.Value != nil && len(f.Value.Value()) > 0 {
+ for _, i := range f.Value.Value() {
+ defaultVals = append(defaultVals, fmt.Sprintf("%d", i))
+ }
+ }
+
+ return stringifySliceFlag(f.Usage, f.Name, defaultVals)
+}
+
+func stringifyStringSliceFlag(f StringSliceFlag) string {
+ defaultVals := []string{}
+ if f.Value != nil && len(f.Value.Value()) > 0 {
+ for _, s := range f.Value.Value() {
+ if len(s) > 0 {
+ defaultVals = append(defaultVals, fmt.Sprintf("%q", s))
+ }
+ }
+ }
+
+ return stringifySliceFlag(f.Usage, f.Name, defaultVals)
+}
+
+func stringifySliceFlag(usage, name string, defaultVals []string) string {
+ placeholder, usage := unquoteUsage(usage)
+ if placeholder == "" {
+ placeholder = defaultPlaceholder
+ }
+
+ defaultVal := ""
+ if len(defaultVals) > 0 {
+ defaultVal = fmt.Sprintf(" (default: %s)", strings.Join(defaultVals, ", "))
+ }
+
+ usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultVal))
+ return fmt.Sprintf("%s\t%s", prefixedNames(name, placeholder), usageWithDefault)
+}
diff --git a/vendor/github.com/urfave/cli/flag_generated.go b/vendor/github.com/urfave/cli/flag_generated.go
new file mode 100644
index 0000000..491b619
--- /dev/null
+++ b/vendor/github.com/urfave/cli/flag_generated.go
@@ -0,0 +1,627 @@
+package cli
+
+import (
+ "flag"
+ "strconv"
+ "time"
+)
+
+// WARNING: This file is generated!
+
+// BoolFlag is a flag with type bool
+type BoolFlag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Destination *bool
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f BoolFlag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f BoolFlag) GetName() string {
+ return f.Name
+}
+
+// Bool looks up the value of a local BoolFlag, returns
+// false if not found
+func (c *Context) Bool(name string) bool {
+ return lookupBool(name, c.flagSet)
+}
+
+// GlobalBool looks up the value of a global BoolFlag, returns
+// false if not found
+func (c *Context) GlobalBool(name string) bool {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupBool(name, fs)
+ }
+ return false
+}
+
+func lookupBool(name string, set *flag.FlagSet) bool {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := strconv.ParseBool(f.Value.String())
+ if err != nil {
+ return false
+ }
+ return parsed
+ }
+ return false
+}
+
+// BoolTFlag is a flag with type bool that is true by default
+type BoolTFlag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Destination *bool
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f BoolTFlag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f BoolTFlag) GetName() string {
+ return f.Name
+}
+
+// BoolT looks up the value of a local BoolTFlag, returns
+// false if not found
+func (c *Context) BoolT(name string) bool {
+ return lookupBoolT(name, c.flagSet)
+}
+
+// GlobalBoolT looks up the value of a global BoolTFlag, returns
+// false if not found
+func (c *Context) GlobalBoolT(name string) bool {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupBoolT(name, fs)
+ }
+ return false
+}
+
+func lookupBoolT(name string, set *flag.FlagSet) bool {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := strconv.ParseBool(f.Value.String())
+ if err != nil {
+ return false
+ }
+ return parsed
+ }
+ return false
+}
+
+// DurationFlag is a flag with type time.Duration (see https://golang.org/pkg/time/#ParseDuration)
+type DurationFlag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value time.Duration
+ Destination *time.Duration
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f DurationFlag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f DurationFlag) GetName() string {
+ return f.Name
+}
+
+// Duration looks up the value of a local DurationFlag, returns
+// 0 if not found
+func (c *Context) Duration(name string) time.Duration {
+ return lookupDuration(name, c.flagSet)
+}
+
+// GlobalDuration looks up the value of a global DurationFlag, returns
+// 0 if not found
+func (c *Context) GlobalDuration(name string) time.Duration {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupDuration(name, fs)
+ }
+ return 0
+}
+
+func lookupDuration(name string, set *flag.FlagSet) time.Duration {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := time.ParseDuration(f.Value.String())
+ if err != nil {
+ return 0
+ }
+ return parsed
+ }
+ return 0
+}
+
+// Float64Flag is a flag with type float64
+type Float64Flag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value float64
+ Destination *float64
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f Float64Flag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f Float64Flag) GetName() string {
+ return f.Name
+}
+
+// Float64 looks up the value of a local Float64Flag, returns
+// 0 if not found
+func (c *Context) Float64(name string) float64 {
+ return lookupFloat64(name, c.flagSet)
+}
+
+// GlobalFloat64 looks up the value of a global Float64Flag, returns
+// 0 if not found
+func (c *Context) GlobalFloat64(name string) float64 {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupFloat64(name, fs)
+ }
+ return 0
+}
+
+func lookupFloat64(name string, set *flag.FlagSet) float64 {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := strconv.ParseFloat(f.Value.String(), 64)
+ if err != nil {
+ return 0
+ }
+ return parsed
+ }
+ return 0
+}
+
+// GenericFlag is a flag with type Generic
+type GenericFlag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value Generic
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f GenericFlag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f GenericFlag) GetName() string {
+ return f.Name
+}
+
+// Generic looks up the value of a local GenericFlag, returns
+// nil if not found
+func (c *Context) Generic(name string) interface{} {
+ return lookupGeneric(name, c.flagSet)
+}
+
+// GlobalGeneric looks up the value of a global GenericFlag, returns
+// nil if not found
+func (c *Context) GlobalGeneric(name string) interface{} {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupGeneric(name, fs)
+ }
+ return nil
+}
+
+func lookupGeneric(name string, set *flag.FlagSet) interface{} {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := f.Value, error(nil)
+ if err != nil {
+ return nil
+ }
+ return parsed
+ }
+ return nil
+}
+
+// Int64Flag is a flag with type int64
+type Int64Flag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value int64
+ Destination *int64
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f Int64Flag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f Int64Flag) GetName() string {
+ return f.Name
+}
+
+// Int64 looks up the value of a local Int64Flag, returns
+// 0 if not found
+func (c *Context) Int64(name string) int64 {
+ return lookupInt64(name, c.flagSet)
+}
+
+// GlobalInt64 looks up the value of a global Int64Flag, returns
+// 0 if not found
+func (c *Context) GlobalInt64(name string) int64 {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupInt64(name, fs)
+ }
+ return 0
+}
+
+func lookupInt64(name string, set *flag.FlagSet) int64 {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := strconv.ParseInt(f.Value.String(), 0, 64)
+ if err != nil {
+ return 0
+ }
+ return parsed
+ }
+ return 0
+}
+
+// IntFlag is a flag with type int
+type IntFlag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value int
+ Destination *int
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f IntFlag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f IntFlag) GetName() string {
+ return f.Name
+}
+
+// Int looks up the value of a local IntFlag, returns
+// 0 if not found
+func (c *Context) Int(name string) int {
+ return lookupInt(name, c.flagSet)
+}
+
+// GlobalInt looks up the value of a global IntFlag, returns
+// 0 if not found
+func (c *Context) GlobalInt(name string) int {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupInt(name, fs)
+ }
+ return 0
+}
+
+func lookupInt(name string, set *flag.FlagSet) int {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := strconv.ParseInt(f.Value.String(), 0, 64)
+ if err != nil {
+ return 0
+ }
+ return int(parsed)
+ }
+ return 0
+}
+
+// IntSliceFlag is a flag with type *IntSlice
+type IntSliceFlag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value *IntSlice
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f IntSliceFlag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f IntSliceFlag) GetName() string {
+ return f.Name
+}
+
+// IntSlice looks up the value of a local IntSliceFlag, returns
+// nil if not found
+func (c *Context) IntSlice(name string) []int {
+ return lookupIntSlice(name, c.flagSet)
+}
+
+// GlobalIntSlice looks up the value of a global IntSliceFlag, returns
+// nil if not found
+func (c *Context) GlobalIntSlice(name string) []int {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupIntSlice(name, fs)
+ }
+ return nil
+}
+
+func lookupIntSlice(name string, set *flag.FlagSet) []int {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := (f.Value.(*IntSlice)).Value(), error(nil)
+ if err != nil {
+ return nil
+ }
+ return parsed
+ }
+ return nil
+}
+
+// Int64SliceFlag is a flag with type *Int64Slice
+type Int64SliceFlag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value *Int64Slice
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f Int64SliceFlag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f Int64SliceFlag) GetName() string {
+ return f.Name
+}
+
+// Int64Slice looks up the value of a local Int64SliceFlag, returns
+// nil if not found
+func (c *Context) Int64Slice(name string) []int64 {
+ return lookupInt64Slice(name, c.flagSet)
+}
+
+// GlobalInt64Slice looks up the value of a global Int64SliceFlag, returns
+// nil if not found
+func (c *Context) GlobalInt64Slice(name string) []int64 {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupInt64Slice(name, fs)
+ }
+ return nil
+}
+
+func lookupInt64Slice(name string, set *flag.FlagSet) []int64 {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := (f.Value.(*Int64Slice)).Value(), error(nil)
+ if err != nil {
+ return nil
+ }
+ return parsed
+ }
+ return nil
+}
+
+// StringFlag is a flag with type string
+type StringFlag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value string
+ Destination *string
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f StringFlag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f StringFlag) GetName() string {
+ return f.Name
+}
+
+// String looks up the value of a local StringFlag, returns
+// "" if not found
+func (c *Context) String(name string) string {
+ return lookupString(name, c.flagSet)
+}
+
+// GlobalString looks up the value of a global StringFlag, returns
+// "" if not found
+func (c *Context) GlobalString(name string) string {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupString(name, fs)
+ }
+ return ""
+}
+
+func lookupString(name string, set *flag.FlagSet) string {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := f.Value.String(), error(nil)
+ if err != nil {
+ return ""
+ }
+ return parsed
+ }
+ return ""
+}
+
+// StringSliceFlag is a flag with type *StringSlice
+type StringSliceFlag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value *StringSlice
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f StringSliceFlag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f StringSliceFlag) GetName() string {
+ return f.Name
+}
+
+// StringSlice looks up the value of a local StringSliceFlag, returns
+// nil if not found
+func (c *Context) StringSlice(name string) []string {
+ return lookupStringSlice(name, c.flagSet)
+}
+
+// GlobalStringSlice looks up the value of a global StringSliceFlag, returns
+// nil if not found
+func (c *Context) GlobalStringSlice(name string) []string {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupStringSlice(name, fs)
+ }
+ return nil
+}
+
+func lookupStringSlice(name string, set *flag.FlagSet) []string {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := (f.Value.(*StringSlice)).Value(), error(nil)
+ if err != nil {
+ return nil
+ }
+ return parsed
+ }
+ return nil
+}
+
+// Uint64Flag is a flag with type uint64
+type Uint64Flag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value uint64
+ Destination *uint64
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f Uint64Flag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f Uint64Flag) GetName() string {
+ return f.Name
+}
+
+// Uint64 looks up the value of a local Uint64Flag, returns
+// 0 if not found
+func (c *Context) Uint64(name string) uint64 {
+ return lookupUint64(name, c.flagSet)
+}
+
+// GlobalUint64 looks up the value of a global Uint64Flag, returns
+// 0 if not found
+func (c *Context) GlobalUint64(name string) uint64 {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupUint64(name, fs)
+ }
+ return 0
+}
+
+func lookupUint64(name string, set *flag.FlagSet) uint64 {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := strconv.ParseUint(f.Value.String(), 0, 64)
+ if err != nil {
+ return 0
+ }
+ return parsed
+ }
+ return 0
+}
+
+// UintFlag is a flag with type uint
+type UintFlag struct {
+ Name string
+ Usage string
+ EnvVar string
+ Hidden bool
+ Value uint
+ Destination *uint
+}
+
+// String returns a readable representation of this value
+// (for usage defaults)
+func (f UintFlag) String() string {
+ return FlagStringer(f)
+}
+
+// GetName returns the name of the flag
+func (f UintFlag) GetName() string {
+ return f.Name
+}
+
+// Uint looks up the value of a local UintFlag, returns
+// 0 if not found
+func (c *Context) Uint(name string) uint {
+ return lookupUint(name, c.flagSet)
+}
+
+// GlobalUint looks up the value of a global UintFlag, returns
+// 0 if not found
+func (c *Context) GlobalUint(name string) uint {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupUint(name, fs)
+ }
+ return 0
+}
+
+func lookupUint(name string, set *flag.FlagSet) uint {
+ f := set.Lookup(name)
+ if f != nil {
+ parsed, err := strconv.ParseUint(f.Value.String(), 0, 64)
+ if err != nil {
+ return 0
+ }
+ return uint(parsed)
+ }
+ return 0
+}
diff --git a/vendor/github.com/urfave/cli/funcs.go b/vendor/github.com/urfave/cli/funcs.go
new file mode 100644
index 0000000..cba5e6c
--- /dev/null
+++ b/vendor/github.com/urfave/cli/funcs.go
@@ -0,0 +1,28 @@
+package cli
+
+// BashCompleteFunc is an action to execute when the bash-completion flag is set
+type BashCompleteFunc func(*Context)
+
+// BeforeFunc is an action to execute before any subcommands are run, but after
+// the context is ready if a non-nil error is returned, no subcommands are run
+type BeforeFunc func(*Context) error
+
+// AfterFunc is an action to execute after any subcommands are run, but after the
+// subcommand has finished it is run even if Action() panics
+type AfterFunc func(*Context) error
+
+// ActionFunc is the action to execute when no subcommands are specified
+type ActionFunc func(*Context) error
+
+// CommandNotFoundFunc is executed if the proper command cannot be found
+type CommandNotFoundFunc func(*Context, string)
+
+// OnUsageErrorFunc is executed if an usage error occurs. This is useful for displaying
+// customized usage error messages. This function is able to replace the
+// original error messages. If this function is not set, the "Incorrect usage"
+// is displayed and the execution is interrupted.
+type OnUsageErrorFunc func(context *Context, err error, isSubcommand bool) error
+
+// FlagStringFunc is used by the help generation to display a flag, which is
+// expected to be a single line.
+type FlagStringFunc func(Flag) string
diff --git a/vendor/github.com/urfave/cli/help.go b/vendor/github.com/urfave/cli/help.go
new file mode 100644
index 0000000..d00e4da
--- /dev/null
+++ b/vendor/github.com/urfave/cli/help.go
@@ -0,0 +1,294 @@
+package cli
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "strings"
+ "text/tabwriter"
+ "text/template"
+)
+
+// AppHelpTemplate is the text template for the Default help topic.
+// cli.go uses text/template to render templates. You can
+// render custom help text by setting this variable.
+var AppHelpTemplate = `NAME:
+ {{.Name}}{{if .Usage}} - {{.Usage}}{{end}}
+
+USAGE:
+ {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}}
+
+VERSION:
+ {{.Version}}{{end}}{{end}}{{if .Description}}
+
+DESCRIPTION:
+ {{.Description}}{{end}}{{if len .Authors}}
+
+AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}:
+ {{range $index, $author := .Authors}}{{if $index}}
+ {{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}}
+
+COMMANDS:{{range .VisibleCategories}}{{if .Name}}
+ {{.Name}}:{{end}}{{range .VisibleCommands}}
+ {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{if .VisibleFlags}}
+
+GLOBAL OPTIONS:
+ {{range $index, $option := .VisibleFlags}}{{if $index}}
+ {{end}}{{$option}}{{end}}{{end}}{{if .Copyright}}
+
+COPYRIGHT:
+ {{.Copyright}}{{end}}
+`
+
+// CommandHelpTemplate is the text template for the command help topic.
+// cli.go uses text/template to render templates. You can
+// render custom help text by setting this variable.
+var CommandHelpTemplate = `NAME:
+ {{.HelpName}} - {{.Usage}}
+
+USAGE:
+ {{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{if .Category}}
+
+CATEGORY:
+ {{.Category}}{{end}}{{if .Description}}
+
+DESCRIPTION:
+ {{.Description}}{{end}}{{if .VisibleFlags}}
+
+OPTIONS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}
+`
+
+// SubcommandHelpTemplate is the text template for the subcommand help topic.
+// cli.go uses text/template to render templates. You can
+// render custom help text by setting this variable.
+var SubcommandHelpTemplate = `NAME:
+ {{.HelpName}} - {{if .Description}}{{.Description}}{{else}}{{.Usage}}{{end}}
+
+USAGE:
+ {{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}
+
+COMMANDS:{{range .VisibleCategories}}{{if .Name}}
+ {{.Name}}:{{end}}{{range .VisibleCommands}}
+ {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}
+{{end}}{{if .VisibleFlags}}
+OPTIONS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}
+`
+
+var helpCommand = Command{
+ Name: "help",
+ Aliases: []string{"h"},
+ Usage: "Shows a list of commands or help for one command",
+ ArgsUsage: "[command]",
+ Action: func(c *Context) error {
+ args := c.Args()
+ if args.Present() {
+ return ShowCommandHelp(c, args.First())
+ }
+
+ ShowAppHelp(c)
+ return nil
+ },
+}
+
+var helpSubcommand = Command{
+ Name: "help",
+ Aliases: []string{"h"},
+ Usage: "Shows a list of commands or help for one command",
+ ArgsUsage: "[command]",
+ Action: func(c *Context) error {
+ args := c.Args()
+ if args.Present() {
+ return ShowCommandHelp(c, args.First())
+ }
+
+ return ShowSubcommandHelp(c)
+ },
+}
+
+// Prints help for the App or Command
+type helpPrinter func(w io.Writer, templ string, data interface{})
+
+// HelpPrinter is a function that writes the help output. If not set a default
+// is used. The function signature is:
+// func(w io.Writer, templ string, data interface{})
+var HelpPrinter helpPrinter = printHelp
+
+// VersionPrinter prints the version for the App
+var VersionPrinter = printVersion
+
+// ShowAppHelp is an action that displays the help.
+func ShowAppHelp(c *Context) error {
+ HelpPrinter(c.App.Writer, AppHelpTemplate, c.App)
+ return nil
+}
+
+// DefaultAppComplete prints the list of subcommands as the default app completion method
+func DefaultAppComplete(c *Context) {
+ for _, command := range c.App.Commands {
+ if command.Hidden {
+ continue
+ }
+ for _, name := range command.Names() {
+ fmt.Fprintln(c.App.Writer, name)
+ }
+ }
+}
+
+// ShowCommandHelp prints help for the given command
+func ShowCommandHelp(ctx *Context, command string) error {
+ // show the subcommand help for a command with subcommands
+ if command == "" {
+ HelpPrinter(ctx.App.Writer, SubcommandHelpTemplate, ctx.App)
+ return nil
+ }
+
+ for _, c := range ctx.App.Commands {
+ if c.HasName(command) {
+ HelpPrinter(ctx.App.Writer, CommandHelpTemplate, c)
+ return nil
+ }
+ }
+
+ if ctx.App.CommandNotFound == nil {
+ return NewExitError(fmt.Sprintf("No help topic for '%v'", command), 3)
+ }
+
+ ctx.App.CommandNotFound(ctx, command)
+ return nil
+}
+
+// ShowSubcommandHelp prints help for the given subcommand
+func ShowSubcommandHelp(c *Context) error {
+ return ShowCommandHelp(c, c.Command.Name)
+}
+
+// ShowVersion prints the version number of the App
+func ShowVersion(c *Context) {
+ VersionPrinter(c)
+}
+
+func printVersion(c *Context) {
+ fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version)
+}
+
+// ShowCompletions prints the lists of commands within a given context
+func ShowCompletions(c *Context) {
+ a := c.App
+ if a != nil && a.BashComplete != nil {
+ a.BashComplete(c)
+ }
+}
+
+// ShowCommandCompletions prints the custom completions for a given command
+func ShowCommandCompletions(ctx *Context, command string) {
+ c := ctx.App.Command(command)
+ if c != nil && c.BashComplete != nil {
+ c.BashComplete(ctx)
+ }
+}
+
+func printHelp(out io.Writer, templ string, data interface{}) {
+ funcMap := template.FuncMap{
+ "join": strings.Join,
+ }
+
+ w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0)
+ t := template.Must(template.New("help").Funcs(funcMap).Parse(templ))
+ err := t.Execute(w, data)
+ if err != nil {
+ // If the writer is closed, t.Execute will fail, and there's nothing
+ // we can do to recover.
+ if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" {
+ fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err)
+ }
+ return
+ }
+ w.Flush()
+}
+
+func checkVersion(c *Context) bool {
+ found := false
+ if VersionFlag.Name != "" {
+ eachName(VersionFlag.Name, func(name string) {
+ if c.GlobalBool(name) || c.Bool(name) {
+ found = true
+ }
+ })
+ }
+ return found
+}
+
+func checkHelp(c *Context) bool {
+ found := false
+ if HelpFlag.Name != "" {
+ eachName(HelpFlag.Name, func(name string) {
+ if c.GlobalBool(name) || c.Bool(name) {
+ found = true
+ }
+ })
+ }
+ return found
+}
+
+func checkCommandHelp(c *Context, name string) bool {
+ if c.Bool("h") || c.Bool("help") {
+ ShowCommandHelp(c, name)
+ return true
+ }
+
+ return false
+}
+
+func checkSubcommandHelp(c *Context) bool {
+ if c.Bool("h") || c.Bool("help") {
+ ShowSubcommandHelp(c)
+ return true
+ }
+
+ return false
+}
+
+func checkShellCompleteFlag(a *App, arguments []string) (bool, []string) {
+ if !a.EnableBashCompletion {
+ return false, arguments
+ }
+
+ pos := len(arguments) - 1
+ lastArg := arguments[pos]
+
+ if lastArg != "--"+BashCompletionFlag.Name {
+ return false, arguments
+ }
+
+ return true, arguments[:pos]
+}
+
+func checkCompletions(c *Context) bool {
+ if !c.shellComplete {
+ return false
+ }
+
+ if args := c.Args(); args.Present() {
+ name := args.First()
+ if cmd := c.App.Command(name); cmd != nil {
+ // let the command handle the completion
+ return false
+ }
+ }
+
+ ShowCompletions(c)
+ return true
+}
+
+func checkCommandCompletions(c *Context, name string) bool {
+ if !c.shellComplete {
+ return false
+ }
+
+ ShowCommandCompletions(c, name)
+ return true
+}
diff --git a/vendor/github.com/vbatts/tar-split/LICENSE b/vendor/github.com/vbatts/tar-split/LICENSE
new file mode 100644
index 0000000..ca03685
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/LICENSE
@@ -0,0 +1,28 @@
+Copyright (c) 2015 Vincent Batts, Raleigh, NC, USA
+
+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.
+
+3. 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 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/vbatts/tar-split/README.md b/vendor/github.com/vbatts/tar-split/README.md
new file mode 100644
index 0000000..4c544d8
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/README.md
@@ -0,0 +1,137 @@
+# tar-split
+
+[![Build Status](https://travis-ci.org/vbatts/tar-split.svg?branch=master)](https://travis-ci.org/vbatts/tar-split)
+
+Pristinely disassembling a tar archive, and stashing needed raw bytes and offsets to reassemble a validating original archive.
+
+## Docs
+
+Code API for libraries provided by `tar-split`:
+
+* https://godoc.org/github.com/vbatts/tar-split/tar/asm
+* https://godoc.org/github.com/vbatts/tar-split/tar/storage
+* https://godoc.org/github.com/vbatts/tar-split/archive/tar
+
+## Install
+
+The command line utilitiy is installable via:
+
+```bash
+go get github.com/vbatts/tar-split/cmd/tar-split
+```
+
+## Usage
+
+For cli usage, see its [README.md](cmd/tar-split/README.md).
+For the library see the [docs](#docs)
+
+## Demo
+
+### Basic disassembly and assembly
+
+This demonstrates the `tar-split` command and how to assemble a tar archive from the `tar-data.json.gz`
+
+
+![basic cmd demo thumbnail](https://i.ytimg.com/vi/vh5wyjIOBtc/2.jpg?time=1445027151805)
+[youtube video of basic command demo](https://youtu.be/vh5wyjIOBtc)
+
+### Docker layer preservation
+
+This demonstrates the tar-split integration for docker-1.8. Providing consistent tar archives for the image layer content.
+
+![docker tar-split demo](https://i.ytimg.com/vi_webp/vh5wyjIOBtc/default.webp)
+[youtube vide of docker layer checksums](https://youtu.be/tV_Dia8E8xw)
+
+## Caveat
+
+Eventually this should detect TARs that this is not possible with.
+
+For example stored sparse files that have "holes" in them, will be read as a
+contiguous file, though the archive contents may be recorded in sparse format.
+Therefore when adding the file payload to a reassembled tar, to achieve
+identical output, the file payload would need be precisely re-sparsified. This
+is not something I seek to fix imediately, but would rather have an alert that
+precise reassembly is not possible.
+(see more http://www.gnu.org/software/tar/manual/html_node/Sparse-Formats.html)
+
+
+Other caveat, while tar archives support having multiple file entries for the
+same path, we will not support this feature. If there are more than one entries
+with the same path, expect an err (like `ErrDuplicatePath`) or a resulting tar
+stream that does not validate your original checksum/signature.
+
+## Contract
+
+Do not break the API of stdlib `archive/tar` in our fork (ideally find an upstream mergeable solution).
+
+## Std Version
+
+The version of golang stdlib `archive/tar` is from go1.6
+It is minimally extended to expose the raw bytes of the TAR, rather than just the marshalled headers and file stream.
+
+
+## Design
+
+See the [design](concept/DESIGN.md).
+
+## Stored Metadata
+
+Since the raw bytes of the headers and padding are stored, you may be wondering
+what the size implications are. The headers are at least 512 bytes per
+file (sometimes more), at least 1024 null bytes on the end, and then various
+padding. This makes for a constant linear growth in the stored metadata, with a
+naive storage implementation.
+
+First we'll get an archive to work with. For repeatability, we'll make an
+archive from what you've just cloned:
+
+```bash
+git archive --format=tar -o tar-split.tar HEAD .
+```
+
+```bash
+$ go get github.com/vbatts/tar-split/cmd/tar-split
+$ tar-split checksize ./tar-split.tar
+inspecting "tar-split.tar" (size 210k)
+ -- number of files: 50
+ -- size of metadata uncompressed: 53k
+ -- size of gzip compressed metadata: 3k
+```
+
+So assuming you've managed the extraction of the archive yourself, for reuse of
+the file payloads from a relative path, then the only additional storage
+implications are as little as 3kb.
+
+But let's look at a larger archive, with many files.
+
+```bash
+$ ls -sh ./d.tar
+1.4G ./d.tar
+$ tar-split checksize ~/d.tar
+inspecting "/home/vbatts/d.tar" (size 1420749k)
+ -- number of files: 38718
+ -- size of metadata uncompressed: 43261k
+ -- size of gzip compressed metadata: 2251k
+```
+
+Here, an archive with 38,718 files has a compressed footprint of about 2mb.
+
+Rolling the null bytes on the end of the archive, we will assume a
+bytes-per-file rate for the storage implications.
+
+| uncompressed | compressed |
+| :----------: | :--------: |
+| ~ 1kb per/file | 0.06kb per/file |
+
+
+## What's Next?
+
+* More implementations of storage Packer and Unpacker
+* More implementations of FileGetter and FilePutter
+* would be interesting to have an assembler stream that implements `io.Seeker`
+
+
+## License
+
+See [LICENSE](LICENSE)
+
diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/common.go b/vendor/github.com/vbatts/tar-split/archive/tar/common.go
new file mode 100644
index 0000000..36f4e23
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/archive/tar/common.go
@@ -0,0 +1,340 @@
+// Copyright 2009 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 tar implements access to tar archives.
+// It aims to cover most of the variations, including those produced
+// by GNU and BSD tars.
+//
+// References:
+// http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
+// http://www.gnu.org/software/tar/manual/html_node/Standard.html
+// http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html
+package tar
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "os"
+ "path"
+ "time"
+)
+
+const (
+ blockSize = 512
+
+ // Types
+ TypeReg = '0' // regular file
+ TypeRegA = '\x00' // regular file
+ TypeLink = '1' // hard link
+ TypeSymlink = '2' // symbolic link
+ TypeChar = '3' // character device node
+ TypeBlock = '4' // block device node
+ TypeDir = '5' // directory
+ TypeFifo = '6' // fifo node
+ TypeCont = '7' // reserved
+ TypeXHeader = 'x' // extended header
+ TypeXGlobalHeader = 'g' // global extended header
+ TypeGNULongName = 'L' // Next file has a long name
+ TypeGNULongLink = 'K' // Next file symlinks to a file w/ a long name
+ TypeGNUSparse = 'S' // sparse file
+)
+
+// A Header represents a single header in a tar archive.
+// Some fields may not be populated.
+type Header struct {
+ Name string // name of header file entry
+ Mode int64 // permission and mode bits
+ Uid int // user id of owner
+ Gid int // group id of owner
+ Size int64 // length in bytes
+ ModTime time.Time // modified time
+ Typeflag byte // type of header entry
+ Linkname string // target name of link
+ Uname string // user name of owner
+ Gname string // group name of owner
+ Devmajor int64 // major number of character or block device
+ Devminor int64 // minor number of character or block device
+ AccessTime time.Time // access time
+ ChangeTime time.Time // status change time
+ Xattrs map[string]string
+}
+
+// File name constants from the tar spec.
+const (
+ fileNameSize = 100 // Maximum number of bytes in a standard tar name.
+ fileNamePrefixSize = 155 // Maximum number of ustar extension bytes.
+)
+
+// FileInfo returns an os.FileInfo for the Header.
+func (h *Header) FileInfo() os.FileInfo {
+ return headerFileInfo{h}
+}
+
+// headerFileInfo implements os.FileInfo.
+type headerFileInfo struct {
+ h *Header
+}
+
+func (fi headerFileInfo) Size() int64 { return fi.h.Size }
+func (fi headerFileInfo) IsDir() bool { return fi.Mode().IsDir() }
+func (fi headerFileInfo) ModTime() time.Time { return fi.h.ModTime }
+func (fi headerFileInfo) Sys() interface{} { return fi.h }
+
+// Name returns the base name of the file.
+func (fi headerFileInfo) Name() string {
+ if fi.IsDir() {
+ return path.Base(path.Clean(fi.h.Name))
+ }
+ return path.Base(fi.h.Name)
+}
+
+// Mode returns the permission and mode bits for the headerFileInfo.
+func (fi headerFileInfo) Mode() (mode os.FileMode) {
+ // Set file permission bits.
+ mode = os.FileMode(fi.h.Mode).Perm()
+
+ // Set setuid, setgid and sticky bits.
+ if fi.h.Mode&c_ISUID != 0 {
+ // setuid
+ mode |= os.ModeSetuid
+ }
+ if fi.h.Mode&c_ISGID != 0 {
+ // setgid
+ mode |= os.ModeSetgid
+ }
+ if fi.h.Mode&c_ISVTX != 0 {
+ // sticky
+ mode |= os.ModeSticky
+ }
+
+ // Set file mode bits.
+ // clear perm, setuid, setgid and sticky bits.
+ m := os.FileMode(fi.h.Mode) &^ 07777
+ if m == c_ISDIR {
+ // directory
+ mode |= os.ModeDir
+ }
+ if m == c_ISFIFO {
+ // named pipe (FIFO)
+ mode |= os.ModeNamedPipe
+ }
+ if m == c_ISLNK {
+ // symbolic link
+ mode |= os.ModeSymlink
+ }
+ if m == c_ISBLK {
+ // device file
+ mode |= os.ModeDevice
+ }
+ if m == c_ISCHR {
+ // Unix character device
+ mode |= os.ModeDevice
+ mode |= os.ModeCharDevice
+ }
+ if m == c_ISSOCK {
+ // Unix domain socket
+ mode |= os.ModeSocket
+ }
+
+ switch fi.h.Typeflag {
+ case TypeSymlink:
+ // symbolic link
+ mode |= os.ModeSymlink
+ case TypeChar:
+ // character device node
+ mode |= os.ModeDevice
+ mode |= os.ModeCharDevice
+ case TypeBlock:
+ // block device node
+ mode |= os.ModeDevice
+ case TypeDir:
+ // directory
+ mode |= os.ModeDir
+ case TypeFifo:
+ // fifo node
+ mode |= os.ModeNamedPipe
+ }
+
+ return mode
+}
+
+// sysStat, if non-nil, populates h from system-dependent fields of fi.
+var sysStat func(fi os.FileInfo, h *Header) error
+
+// Mode constants from the tar spec.
+const (
+ c_ISUID = 04000 // Set uid
+ c_ISGID = 02000 // Set gid
+ c_ISVTX = 01000 // Save text (sticky bit)
+ c_ISDIR = 040000 // Directory
+ c_ISFIFO = 010000 // FIFO
+ c_ISREG = 0100000 // Regular file
+ c_ISLNK = 0120000 // Symbolic link
+ c_ISBLK = 060000 // Block special file
+ c_ISCHR = 020000 // Character special file
+ c_ISSOCK = 0140000 // Socket
+)
+
+// Keywords for the PAX Extended Header
+const (
+ paxAtime = "atime"
+ paxCharset = "charset"
+ paxComment = "comment"
+ paxCtime = "ctime" // please note that ctime is not a valid pax header.
+ paxGid = "gid"
+ paxGname = "gname"
+ paxLinkpath = "linkpath"
+ paxMtime = "mtime"
+ paxPath = "path"
+ paxSize = "size"
+ paxUid = "uid"
+ paxUname = "uname"
+ paxXattr = "SCHILY.xattr."
+ paxNone = ""
+)
+
+// FileInfoHeader creates a partially-populated Header from fi.
+// If fi describes a symlink, FileInfoHeader records link as the link target.
+// If fi describes a directory, a slash is appended to the name.
+// Because os.FileInfo's Name method returns only the base name of
+// the file it describes, it may be necessary to modify the Name field
+// of the returned header to provide the full path name of the file.
+func FileInfoHeader(fi os.FileInfo, link string) (*Header, error) {
+ if fi == nil {
+ return nil, errors.New("tar: FileInfo is nil")
+ }
+ fm := fi.Mode()
+ h := &Header{
+ Name: fi.Name(),
+ ModTime: fi.ModTime(),
+ Mode: int64(fm.Perm()), // or'd with c_IS* constants later
+ }
+ switch {
+ case fm.IsRegular():
+ h.Mode |= c_ISREG
+ h.Typeflag = TypeReg
+ h.Size = fi.Size()
+ case fi.IsDir():
+ h.Typeflag = TypeDir
+ h.Mode |= c_ISDIR
+ h.Name += "/"
+ case fm&os.ModeSymlink != 0:
+ h.Typeflag = TypeSymlink
+ h.Mode |= c_ISLNK
+ h.Linkname = link
+ case fm&os.ModeDevice != 0:
+ if fm&os.ModeCharDevice != 0 {
+ h.Mode |= c_ISCHR
+ h.Typeflag = TypeChar
+ } else {
+ h.Mode |= c_ISBLK
+ h.Typeflag = TypeBlock
+ }
+ case fm&os.ModeNamedPipe != 0:
+ h.Typeflag = TypeFifo
+ h.Mode |= c_ISFIFO
+ case fm&os.ModeSocket != 0:
+ h.Mode |= c_ISSOCK
+ default:
+ return nil, fmt.Errorf("archive/tar: unknown file mode %v", fm)
+ }
+ if fm&os.ModeSetuid != 0 {
+ h.Mode |= c_ISUID
+ }
+ if fm&os.ModeSetgid != 0 {
+ h.Mode |= c_ISGID
+ }
+ if fm&os.ModeSticky != 0 {
+ h.Mode |= c_ISVTX
+ }
+ // If possible, populate additional fields from OS-specific
+ // FileInfo fields.
+ if sys, ok := fi.Sys().(*Header); ok {
+ // This FileInfo came from a Header (not the OS). Use the
+ // original Header to populate all remaining fields.
+ h.Uid = sys.Uid
+ h.Gid = sys.Gid
+ h.Uname = sys.Uname
+ h.Gname = sys.Gname
+ h.AccessTime = sys.AccessTime
+ h.ChangeTime = sys.ChangeTime
+ if sys.Xattrs != nil {
+ h.Xattrs = make(map[string]string)
+ for k, v := range sys.Xattrs {
+ h.Xattrs[k] = v
+ }
+ }
+ if sys.Typeflag == TypeLink {
+ // hard link
+ h.Typeflag = TypeLink
+ h.Size = 0
+ h.Linkname = sys.Linkname
+ }
+ }
+ if sysStat != nil {
+ return h, sysStat(fi, h)
+ }
+ return h, nil
+}
+
+var zeroBlock = make([]byte, blockSize)
+
+// POSIX specifies a sum of the unsigned byte values, but the Sun tar uses signed byte values.
+// We compute and return both.
+func checksum(header []byte) (unsigned int64, signed int64) {
+ for i := 0; i < len(header); i++ {
+ if i == 148 {
+ // The chksum field (header[148:156]) is special: it should be treated as space bytes.
+ unsigned += ' ' * 8
+ signed += ' ' * 8
+ i += 7
+ continue
+ }
+ unsigned += int64(header[i])
+ signed += int64(int8(header[i]))
+ }
+ return
+}
+
+type slicer []byte
+
+func (sp *slicer) next(n int) (b []byte) {
+ s := *sp
+ b, *sp = s[0:n], s[n:]
+ return
+}
+
+func isASCII(s string) bool {
+ for _, c := range s {
+ if c >= 0x80 {
+ return false
+ }
+ }
+ return true
+}
+
+func toASCII(s string) string {
+ if isASCII(s) {
+ return s
+ }
+ var buf bytes.Buffer
+ for _, c := range s {
+ if c < 0x80 {
+ buf.WriteByte(byte(c))
+ }
+ }
+ return buf.String()
+}
+
+// isHeaderOnlyType checks if the given type flag is of the type that has no
+// data section even if a size is specified.
+func isHeaderOnlyType(flag byte) bool {
+ switch flag {
+ case TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, TypeFifo:
+ return true
+ default:
+ return false
+ }
+}
diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/reader.go b/vendor/github.com/vbatts/tar-split/archive/tar/reader.go
new file mode 100644
index 0000000..adf3212
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/archive/tar/reader.go
@@ -0,0 +1,1064 @@
+// Copyright 2009 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 tar
+
+// TODO(dsymonds):
+// - pax extensions
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "io/ioutil"
+ "math"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var (
+ ErrHeader = errors.New("archive/tar: invalid tar header")
+)
+
+const maxNanoSecondIntSize = 9
+
+// A Reader provides sequential access to the contents of a tar archive.
+// A tar archive consists of a sequence of files.
+// The Next method advances to the next file in the archive (including the first),
+// and then it can be treated as an io.Reader to access the file's data.
+type Reader struct {
+ r io.Reader
+ err error
+ pad int64 // amount of padding (ignored) after current file entry
+ curr numBytesReader // reader for current file entry
+ hdrBuff [blockSize]byte // buffer to use in readHeader
+
+ RawAccounting bool // Whether to enable the access needed to reassemble the tar from raw bytes. Some performance/memory hit for this.
+ rawBytes *bytes.Buffer // last raw bits
+}
+
+type parser struct {
+ err error // Last error seen
+}
+
+// RawBytes accesses the raw bytes of the archive, apart from the file payload itself.
+// This includes the header and padding.
+//
+// This call resets the current rawbytes buffer
+//
+// Only when RawAccounting is enabled, otherwise this returns nil
+func (tr *Reader) RawBytes() []byte {
+ if !tr.RawAccounting {
+ return nil
+ }
+ if tr.rawBytes == nil {
+ tr.rawBytes = bytes.NewBuffer(nil)
+ }
+ // if we've read them, then flush them.
+ defer tr.rawBytes.Reset()
+ return tr.rawBytes.Bytes()
+}
+
+// A numBytesReader is an io.Reader with a numBytes method, returning the number
+// of bytes remaining in the underlying encoded data.
+type numBytesReader interface {
+ io.Reader
+ numBytes() int64
+}
+
+// A regFileReader is a numBytesReader for reading file data from a tar archive.
+type regFileReader struct {
+ r io.Reader // underlying reader
+ nb int64 // number of unread bytes for current file entry
+}
+
+// A sparseFileReader is a numBytesReader for reading sparse file data from a
+// tar archive.
+type sparseFileReader struct {
+ rfr numBytesReader // Reads the sparse-encoded file data
+ sp []sparseEntry // The sparse map for the file
+ pos int64 // Keeps track of file position
+ total int64 // Total size of the file
+}
+
+// A sparseEntry holds a single entry in a sparse file's sparse map.
+//
+// Sparse files are represented using a series of sparseEntrys.
+// Despite the name, a sparseEntry represents an actual data fragment that
+// references data found in the underlying archive stream. All regions not
+// covered by a sparseEntry are logically filled with zeros.
+//
+// For example, if the underlying raw file contains the 10-byte data:
+// var compactData = "abcdefgh"
+//
+// And the sparse map has the following entries:
+// var sp = []sparseEntry{
+// {offset: 2, numBytes: 5} // Data fragment for [2..7]
+// {offset: 18, numBytes: 3} // Data fragment for [18..21]
+// }
+//
+// Then the content of the resulting sparse file with a "real" size of 25 is:
+// var sparseData = "\x00"*2 + "abcde" + "\x00"*11 + "fgh" + "\x00"*4
+type sparseEntry struct {
+ offset int64 // Starting position of the fragment
+ numBytes int64 // Length of the fragment
+}
+
+// Keywords for GNU sparse files in a PAX extended header
+const (
+ paxGNUSparseNumBlocks = "GNU.sparse.numblocks"
+ paxGNUSparseOffset = "GNU.sparse.offset"
+ paxGNUSparseNumBytes = "GNU.sparse.numbytes"
+ paxGNUSparseMap = "GNU.sparse.map"
+ paxGNUSparseName = "GNU.sparse.name"
+ paxGNUSparseMajor = "GNU.sparse.major"
+ paxGNUSparseMinor = "GNU.sparse.minor"
+ paxGNUSparseSize = "GNU.sparse.size"
+ paxGNUSparseRealSize = "GNU.sparse.realsize"
+)
+
+// Keywords for old GNU sparse headers
+const (
+ oldGNUSparseMainHeaderOffset = 386
+ oldGNUSparseMainHeaderIsExtendedOffset = 482
+ oldGNUSparseMainHeaderNumEntries = 4
+ oldGNUSparseExtendedHeaderIsExtendedOffset = 504
+ oldGNUSparseExtendedHeaderNumEntries = 21
+ oldGNUSparseOffsetSize = 12
+ oldGNUSparseNumBytesSize = 12
+)
+
+// NewReader creates a new Reader reading from r.
+func NewReader(r io.Reader) *Reader { return &Reader{r: r} }
+
+// Next advances to the next entry in the tar archive.
+//
+// io.EOF is returned at the end of the input.
+func (tr *Reader) Next() (*Header, error) {
+ if tr.RawAccounting {
+ if tr.rawBytes == nil {
+ tr.rawBytes = bytes.NewBuffer(nil)
+ } else {
+ tr.rawBytes.Reset()
+ }
+ }
+
+ if tr.err != nil {
+ return nil, tr.err
+ }
+
+ var hdr *Header
+ var extHdrs map[string]string
+
+ // Externally, Next iterates through the tar archive as if it is a series of
+ // files. Internally, the tar format often uses fake "files" to add meta
+ // data that describes the next file. These meta data "files" should not
+ // normally be visible to the outside. As such, this loop iterates through
+ // one or more "header files" until it finds a "normal file".
+loop:
+ for {
+ tr.err = tr.skipUnread()
+ if tr.err != nil {
+ return nil, tr.err
+ }
+
+ hdr = tr.readHeader()
+ if tr.err != nil {
+ return nil, tr.err
+ }
+ // Check for PAX/GNU special headers and files.
+ switch hdr.Typeflag {
+ case TypeXHeader:
+ extHdrs, tr.err = parsePAX(tr)
+ if tr.err != nil {
+ return nil, tr.err
+ }
+ continue loop // This is a meta header affecting the next header
+ case TypeGNULongName, TypeGNULongLink:
+ var realname []byte
+ realname, tr.err = ioutil.ReadAll(tr)
+ if tr.err != nil {
+ return nil, tr.err
+ }
+
+ if tr.RawAccounting {
+ if _, tr.err = tr.rawBytes.Write(realname); tr.err != nil {
+ return nil, tr.err
+ }
+ }
+
+ // Convert GNU extensions to use PAX headers.
+ if extHdrs == nil {
+ extHdrs = make(map[string]string)
+ }
+ var p parser
+ switch hdr.Typeflag {
+ case TypeGNULongName:
+ extHdrs[paxPath] = p.parseString(realname)
+ case TypeGNULongLink:
+ extHdrs[paxLinkpath] = p.parseString(realname)
+ }
+ if p.err != nil {
+ tr.err = p.err
+ return nil, tr.err
+ }
+ continue loop // This is a meta header affecting the next header
+ default:
+ mergePAX(hdr, extHdrs)
+
+ // Check for a PAX format sparse file
+ sp, err := tr.checkForGNUSparsePAXHeaders(hdr, extHdrs)
+ if err != nil {
+ tr.err = err
+ return nil, err
+ }
+ if sp != nil {
+ // Current file is a PAX format GNU sparse file.
+ // Set the current file reader to a sparse file reader.
+ tr.curr, tr.err = newSparseFileReader(tr.curr, sp, hdr.Size)
+ if tr.err != nil {
+ return nil, tr.err
+ }
+ }
+ break loop // This is a file, so stop
+ }
+ }
+ return hdr, nil
+}
+
+// checkForGNUSparsePAXHeaders checks the PAX headers for GNU sparse headers. If they are found, then
+// this function reads the sparse map and returns it. Unknown sparse formats are ignored, causing the file to
+// be treated as a regular file.
+func (tr *Reader) checkForGNUSparsePAXHeaders(hdr *Header, headers map[string]string) ([]sparseEntry, error) {
+ var sparseFormat string
+
+ // Check for sparse format indicators
+ major, majorOk := headers[paxGNUSparseMajor]
+ minor, minorOk := headers[paxGNUSparseMinor]
+ sparseName, sparseNameOk := headers[paxGNUSparseName]
+ _, sparseMapOk := headers[paxGNUSparseMap]
+ sparseSize, sparseSizeOk := headers[paxGNUSparseSize]
+ sparseRealSize, sparseRealSizeOk := headers[paxGNUSparseRealSize]
+
+ // Identify which, if any, sparse format applies from which PAX headers are set
+ if majorOk && minorOk {
+ sparseFormat = major + "." + minor
+ } else if sparseNameOk && sparseMapOk {
+ sparseFormat = "0.1"
+ } else if sparseSizeOk {
+ sparseFormat = "0.0"
+ } else {
+ // Not a PAX format GNU sparse file.
+ return nil, nil
+ }
+
+ // Check for unknown sparse format
+ if sparseFormat != "0.0" && sparseFormat != "0.1" && sparseFormat != "1.0" {
+ return nil, nil
+ }
+
+ // Update hdr from GNU sparse PAX headers
+ if sparseNameOk {
+ hdr.Name = sparseName
+ }
+ if sparseSizeOk {
+ realSize, err := strconv.ParseInt(sparseSize, 10, 0)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ hdr.Size = realSize
+ } else if sparseRealSizeOk {
+ realSize, err := strconv.ParseInt(sparseRealSize, 10, 0)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ hdr.Size = realSize
+ }
+
+ // Set up the sparse map, according to the particular sparse format in use
+ var sp []sparseEntry
+ var err error
+ switch sparseFormat {
+ case "0.0", "0.1":
+ sp, err = readGNUSparseMap0x1(headers)
+ case "1.0":
+ sp, err = readGNUSparseMap1x0(tr.curr)
+ }
+ return sp, err
+}
+
+// mergePAX merges well known headers according to PAX standard.
+// In general headers with the same name as those found
+// in the header struct overwrite those found in the header
+// struct with higher precision or longer values. Esp. useful
+// for name and linkname fields.
+func mergePAX(hdr *Header, headers map[string]string) error {
+ for k, v := range headers {
+ switch k {
+ case paxPath:
+ hdr.Name = v
+ case paxLinkpath:
+ hdr.Linkname = v
+ case paxGname:
+ hdr.Gname = v
+ case paxUname:
+ hdr.Uname = v
+ case paxUid:
+ uid, err := strconv.ParseInt(v, 10, 0)
+ if err != nil {
+ return err
+ }
+ hdr.Uid = int(uid)
+ case paxGid:
+ gid, err := strconv.ParseInt(v, 10, 0)
+ if err != nil {
+ return err
+ }
+ hdr.Gid = int(gid)
+ case paxAtime:
+ t, err := parsePAXTime(v)
+ if err != nil {
+ return err
+ }
+ hdr.AccessTime = t
+ case paxMtime:
+ t, err := parsePAXTime(v)
+ if err != nil {
+ return err
+ }
+ hdr.ModTime = t
+ case paxCtime:
+ t, err := parsePAXTime(v)
+ if err != nil {
+ return err
+ }
+ hdr.ChangeTime = t
+ case paxSize:
+ size, err := strconv.ParseInt(v, 10, 0)
+ if err != nil {
+ return err
+ }
+ hdr.Size = int64(size)
+ default:
+ if strings.HasPrefix(k, paxXattr) {
+ if hdr.Xattrs == nil {
+ hdr.Xattrs = make(map[string]string)
+ }
+ hdr.Xattrs[k[len(paxXattr):]] = v
+ }
+ }
+ }
+ return nil
+}
+
+// parsePAXTime takes a string of the form %d.%d as described in
+// the PAX specification.
+func parsePAXTime(t string) (time.Time, error) {
+ buf := []byte(t)
+ pos := bytes.IndexByte(buf, '.')
+ var seconds, nanoseconds int64
+ var err error
+ if pos == -1 {
+ seconds, err = strconv.ParseInt(t, 10, 0)
+ if err != nil {
+ return time.Time{}, err
+ }
+ } else {
+ seconds, err = strconv.ParseInt(string(buf[:pos]), 10, 0)
+ if err != nil {
+ return time.Time{}, err
+ }
+ nano_buf := string(buf[pos+1:])
+ // Pad as needed before converting to a decimal.
+ // For example .030 -> .030000000 -> 30000000 nanoseconds
+ if len(nano_buf) < maxNanoSecondIntSize {
+ // Right pad
+ nano_buf += strings.Repeat("0", maxNanoSecondIntSize-len(nano_buf))
+ } else if len(nano_buf) > maxNanoSecondIntSize {
+ // Right truncate
+ nano_buf = nano_buf[:maxNanoSecondIntSize]
+ }
+ nanoseconds, err = strconv.ParseInt(string(nano_buf), 10, 0)
+ if err != nil {
+ return time.Time{}, err
+ }
+ }
+ ts := time.Unix(seconds, nanoseconds)
+ return ts, nil
+}
+
+// parsePAX parses PAX headers.
+// If an extended header (type 'x') is invalid, ErrHeader is returned
+func parsePAX(r io.Reader) (map[string]string, error) {
+ buf, err := ioutil.ReadAll(r)
+ if err != nil {
+ return nil, err
+ }
+ // leaving this function for io.Reader makes it more testable
+ if tr, ok := r.(*Reader); ok && tr.RawAccounting {
+ if _, err = tr.rawBytes.Write(buf); err != nil {
+ return nil, err
+ }
+ }
+ sbuf := string(buf)
+
+ // For GNU PAX sparse format 0.0 support.
+ // This function transforms the sparse format 0.0 headers into sparse format 0.1 headers.
+ var sparseMap bytes.Buffer
+
+ headers := make(map[string]string)
+ // Each record is constructed as
+ // "%d %s=%s\n", length, keyword, value
+ for len(sbuf) > 0 {
+ key, value, residual, err := parsePAXRecord(sbuf)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ sbuf = residual
+
+ keyStr := string(key)
+ if keyStr == paxGNUSparseOffset || keyStr == paxGNUSparseNumBytes {
+ // GNU sparse format 0.0 special key. Write to sparseMap instead of using the headers map.
+ sparseMap.WriteString(value)
+ sparseMap.Write([]byte{','})
+ } else {
+ // Normal key. Set the value in the headers map.
+ headers[keyStr] = string(value)
+ }
+ }
+ if sparseMap.Len() != 0 {
+ // Add sparse info to headers, chopping off the extra comma
+ sparseMap.Truncate(sparseMap.Len() - 1)
+ headers[paxGNUSparseMap] = sparseMap.String()
+ }
+ return headers, nil
+}
+
+// parsePAXRecord parses the input PAX record string into a key-value pair.
+// If parsing is successful, it will slice off the currently read record and
+// return the remainder as r.
+//
+// A PAX record is of the following form:
+// "%d %s=%s\n" % (size, key, value)
+func parsePAXRecord(s string) (k, v, r string, err error) {
+ // The size field ends at the first space.
+ sp := strings.IndexByte(s, ' ')
+ if sp == -1 {
+ return "", "", s, ErrHeader
+ }
+
+ // Parse the first token as a decimal integer.
+ n, perr := strconv.ParseInt(s[:sp], 10, 0) // Intentionally parse as native int
+ if perr != nil || n < 5 || int64(len(s)) < n {
+ return "", "", s, ErrHeader
+ }
+
+ // Extract everything between the space and the final newline.
+ rec, nl, rem := s[sp+1:n-1], s[n-1:n], s[n:]
+ if nl != "\n" {
+ return "", "", s, ErrHeader
+ }
+
+ // The first equals separates the key from the value.
+ eq := strings.IndexByte(rec, '=')
+ if eq == -1 {
+ return "", "", s, ErrHeader
+ }
+ return rec[:eq], rec[eq+1:], rem, nil
+}
+
+// parseString parses bytes as a NUL-terminated C-style string.
+// If a NUL byte is not found then the whole slice is returned as a string.
+func (*parser) parseString(b []byte) string {
+ n := 0
+ for n < len(b) && b[n] != 0 {
+ n++
+ }
+ return string(b[0:n])
+}
+
+// parseNumeric parses the input as being encoded in either base-256 or octal.
+// This function may return negative numbers.
+// If parsing fails or an integer overflow occurs, err will be set.
+func (p *parser) parseNumeric(b []byte) int64 {
+ // Check for base-256 (binary) format first.
+ // If the first bit is set, then all following bits constitute a two's
+ // complement encoded number in big-endian byte order.
+ if len(b) > 0 && b[0]&0x80 != 0 {
+ // Handling negative numbers relies on the following identity:
+ // -a-1 == ^a
+ //
+ // If the number is negative, we use an inversion mask to invert the
+ // data bytes and treat the value as an unsigned number.
+ var inv byte // 0x00 if positive or zero, 0xff if negative
+ if b[0]&0x40 != 0 {
+ inv = 0xff
+ }
+
+ var x uint64
+ for i, c := range b {
+ c ^= inv // Inverts c only if inv is 0xff, otherwise does nothing
+ if i == 0 {
+ c &= 0x7f // Ignore signal bit in first byte
+ }
+ if (x >> 56) > 0 {
+ p.err = ErrHeader // Integer overflow
+ return 0
+ }
+ x = x<<8 | uint64(c)
+ }
+ if (x >> 63) > 0 {
+ p.err = ErrHeader // Integer overflow
+ return 0
+ }
+ if inv == 0xff {
+ return ^int64(x)
+ }
+ return int64(x)
+ }
+
+ // Normal case is base-8 (octal) format.
+ return p.parseOctal(b)
+}
+
+func (p *parser) parseOctal(b []byte) int64 {
+ // Because unused fields are filled with NULs, we need
+ // to skip leading NULs. Fields may also be padded with
+ // spaces or NULs.
+ // So we remove leading and trailing NULs and spaces to
+ // be sure.
+ b = bytes.Trim(b, " \x00")
+
+ if len(b) == 0 {
+ return 0
+ }
+ x, perr := strconv.ParseUint(p.parseString(b), 8, 64)
+ if perr != nil {
+ p.err = ErrHeader
+ }
+ return int64(x)
+}
+
+// skipUnread skips any unread bytes in the existing file entry, as well as any
+// alignment padding. It returns io.ErrUnexpectedEOF if any io.EOF is
+// encountered in the data portion; it is okay to hit io.EOF in the padding.
+//
+// Note that this function still works properly even when sparse files are being
+// used since numBytes returns the bytes remaining in the underlying io.Reader.
+func (tr *Reader) skipUnread() error {
+ dataSkip := tr.numBytes() // Number of data bytes to skip
+ totalSkip := dataSkip + tr.pad // Total number of bytes to skip
+ tr.curr, tr.pad = nil, 0
+ if tr.RawAccounting {
+ _, tr.err = io.CopyN(tr.rawBytes, tr.r, totalSkip)
+ return tr.err
+ }
+ // If possible, Seek to the last byte before the end of the data section.
+ // Do this because Seek is often lazy about reporting errors; this will mask
+ // the fact that the tar stream may be truncated. We can rely on the
+ // io.CopyN done shortly afterwards to trigger any IO errors.
+ var seekSkipped int64 // Number of bytes skipped via Seek
+ if sr, ok := tr.r.(io.Seeker); ok && dataSkip > 1 {
+ // Not all io.Seeker can actually Seek. For example, os.Stdin implements
+ // io.Seeker, but calling Seek always returns an error and performs
+ // no action. Thus, we try an innocent seek to the current position
+ // to see if Seek is really supported.
+ pos1, err := sr.Seek(0, os.SEEK_CUR)
+ if err == nil {
+ // Seek seems supported, so perform the real Seek.
+ pos2, err := sr.Seek(dataSkip-1, os.SEEK_CUR)
+ if err != nil {
+ tr.err = err
+ return tr.err
+ }
+ seekSkipped = pos2 - pos1
+ }
+ }
+
+ var copySkipped int64 // Number of bytes skipped via CopyN
+ copySkipped, tr.err = io.CopyN(ioutil.Discard, tr.r, totalSkip-seekSkipped)
+ if tr.err == io.EOF && seekSkipped+copySkipped < dataSkip {
+ tr.err = io.ErrUnexpectedEOF
+ }
+ return tr.err
+}
+
+func (tr *Reader) verifyChecksum(header []byte) bool {
+ if tr.err != nil {
+ return false
+ }
+
+ var p parser
+ given := p.parseOctal(header[148:156])
+ unsigned, signed := checksum(header)
+ return p.err == nil && (given == unsigned || given == signed)
+}
+
+// readHeader reads the next block header and assumes that the underlying reader
+// is already aligned to a block boundary.
+//
+// The err will be set to io.EOF only when one of the following occurs:
+// * Exactly 0 bytes are read and EOF is hit.
+// * Exactly 1 block of zeros is read and EOF is hit.
+// * At least 2 blocks of zeros are read.
+func (tr *Reader) readHeader() *Header {
+ header := tr.hdrBuff[:]
+ copy(header, zeroBlock)
+
+ if n, err := io.ReadFull(tr.r, header); err != nil {
+ tr.err = err
+ // because it could read some of the block, but reach EOF first
+ if tr.err == io.EOF && tr.RawAccounting {
+ if _, err := tr.rawBytes.Write(header[:n]); err != nil {
+ tr.err = err
+ }
+ }
+ return nil // io.EOF is okay here
+ }
+ if tr.RawAccounting {
+ if _, tr.err = tr.rawBytes.Write(header); tr.err != nil {
+ return nil
+ }
+ }
+
+ // Two blocks of zero bytes marks the end of the archive.
+ if bytes.Equal(header, zeroBlock[0:blockSize]) {
+ if n, err := io.ReadFull(tr.r, header); err != nil {
+ tr.err = err
+ // because it could read some of the block, but reach EOF first
+ if tr.err == io.EOF && tr.RawAccounting {
+ if _, err := tr.rawBytes.Write(header[:n]); err != nil {
+ tr.err = err
+ }
+ }
+ return nil // io.EOF is okay here
+ }
+ if tr.RawAccounting {
+ if _, tr.err = tr.rawBytes.Write(header); tr.err != nil {
+ return nil
+ }
+ }
+ if bytes.Equal(header, zeroBlock[0:blockSize]) {
+ tr.err = io.EOF
+ } else {
+ tr.err = ErrHeader // zero block and then non-zero block
+ }
+ return nil
+ }
+
+ if !tr.verifyChecksum(header) {
+ tr.err = ErrHeader
+ return nil
+ }
+
+ // Unpack
+ var p parser
+ hdr := new(Header)
+ s := slicer(header)
+
+ hdr.Name = p.parseString(s.next(100))
+ hdr.Mode = p.parseNumeric(s.next(8))
+ hdr.Uid = int(p.parseNumeric(s.next(8)))
+ hdr.Gid = int(p.parseNumeric(s.next(8)))
+ hdr.Size = p.parseNumeric(s.next(12))
+ hdr.ModTime = time.Unix(p.parseNumeric(s.next(12)), 0)
+ s.next(8) // chksum
+ hdr.Typeflag = s.next(1)[0]
+ hdr.Linkname = p.parseString(s.next(100))
+
+ // The remainder of the header depends on the value of magic.
+ // The original (v7) version of tar had no explicit magic field,
+ // so its magic bytes, like the rest of the block, are NULs.
+ magic := string(s.next(8)) // contains version field as well.
+ var format string
+ switch {
+ case magic[:6] == "ustar\x00": // POSIX tar (1003.1-1988)
+ if string(header[508:512]) == "tar\x00" {
+ format = "star"
+ } else {
+ format = "posix"
+ }
+ case magic == "ustar \x00": // old GNU tar
+ format = "gnu"
+ }
+
+ switch format {
+ case "posix", "gnu", "star":
+ hdr.Uname = p.parseString(s.next(32))
+ hdr.Gname = p.parseString(s.next(32))
+ devmajor := s.next(8)
+ devminor := s.next(8)
+ if hdr.Typeflag == TypeChar || hdr.Typeflag == TypeBlock {
+ hdr.Devmajor = p.parseNumeric(devmajor)
+ hdr.Devminor = p.parseNumeric(devminor)
+ }
+ var prefix string
+ switch format {
+ case "posix", "gnu":
+ prefix = p.parseString(s.next(155))
+ case "star":
+ prefix = p.parseString(s.next(131))
+ hdr.AccessTime = time.Unix(p.parseNumeric(s.next(12)), 0)
+ hdr.ChangeTime = time.Unix(p.parseNumeric(s.next(12)), 0)
+ }
+ if len(prefix) > 0 {
+ hdr.Name = prefix + "/" + hdr.Name
+ }
+ }
+
+ if p.err != nil {
+ tr.err = p.err
+ return nil
+ }
+
+ nb := hdr.Size
+ if isHeaderOnlyType(hdr.Typeflag) {
+ nb = 0
+ }
+ if nb < 0 {
+ tr.err = ErrHeader
+ return nil
+ }
+
+ // Set the current file reader.
+ tr.pad = -nb & (blockSize - 1) // blockSize is a power of two
+ tr.curr = &regFileReader{r: tr.r, nb: nb}
+
+ // Check for old GNU sparse format entry.
+ if hdr.Typeflag == TypeGNUSparse {
+ // Get the real size of the file.
+ hdr.Size = p.parseNumeric(header[483:495])
+ if p.err != nil {
+ tr.err = p.err
+ return nil
+ }
+
+ // Read the sparse map.
+ sp := tr.readOldGNUSparseMap(header)
+ if tr.err != nil {
+ return nil
+ }
+
+ // Current file is a GNU sparse file. Update the current file reader.
+ tr.curr, tr.err = newSparseFileReader(tr.curr, sp, hdr.Size)
+ if tr.err != nil {
+ return nil
+ }
+ }
+
+ return hdr
+}
+
+// readOldGNUSparseMap reads the sparse map as stored in the old GNU sparse format.
+// The sparse map is stored in the tar header if it's small enough. If it's larger than four entries,
+// then one or more extension headers are used to store the rest of the sparse map.
+func (tr *Reader) readOldGNUSparseMap(header []byte) []sparseEntry {
+ var p parser
+ isExtended := header[oldGNUSparseMainHeaderIsExtendedOffset] != 0
+ spCap := oldGNUSparseMainHeaderNumEntries
+ if isExtended {
+ spCap += oldGNUSparseExtendedHeaderNumEntries
+ }
+ sp := make([]sparseEntry, 0, spCap)
+ s := slicer(header[oldGNUSparseMainHeaderOffset:])
+
+ // Read the four entries from the main tar header
+ for i := 0; i < oldGNUSparseMainHeaderNumEntries; i++ {
+ offset := p.parseNumeric(s.next(oldGNUSparseOffsetSize))
+ numBytes := p.parseNumeric(s.next(oldGNUSparseNumBytesSize))
+ if p.err != nil {
+ tr.err = p.err
+ return nil
+ }
+ if offset == 0 && numBytes == 0 {
+ break
+ }
+ sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
+ }
+
+ for isExtended {
+ // There are more entries. Read an extension header and parse its entries.
+ sparseHeader := make([]byte, blockSize)
+ if _, tr.err = io.ReadFull(tr.r, sparseHeader); tr.err != nil {
+ return nil
+ }
+ if tr.RawAccounting {
+ if _, tr.err = tr.rawBytes.Write(sparseHeader); tr.err != nil {
+ return nil
+ }
+ }
+
+ isExtended = sparseHeader[oldGNUSparseExtendedHeaderIsExtendedOffset] != 0
+ s = slicer(sparseHeader)
+ for i := 0; i < oldGNUSparseExtendedHeaderNumEntries; i++ {
+ offset := p.parseNumeric(s.next(oldGNUSparseOffsetSize))
+ numBytes := p.parseNumeric(s.next(oldGNUSparseNumBytesSize))
+ if p.err != nil {
+ tr.err = p.err
+ return nil
+ }
+ if offset == 0 && numBytes == 0 {
+ break
+ }
+ sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
+ }
+ }
+ return sp
+}
+
+// readGNUSparseMap1x0 reads the sparse map as stored in GNU's PAX sparse format
+// version 1.0. The format of the sparse map consists of a series of
+// newline-terminated numeric fields. The first field is the number of entries
+// and is always present. Following this are the entries, consisting of two
+// fields (offset, numBytes). This function must stop reading at the end
+// boundary of the block containing the last newline.
+//
+// Note that the GNU manual says that numeric values should be encoded in octal
+// format. However, the GNU tar utility itself outputs these values in decimal.
+// As such, this library treats values as being encoded in decimal.
+func readGNUSparseMap1x0(r io.Reader) ([]sparseEntry, error) {
+ var cntNewline int64
+ var buf bytes.Buffer
+ var blk = make([]byte, blockSize)
+
+ // feedTokens copies data in numBlock chunks from r into buf until there are
+ // at least cnt newlines in buf. It will not read more blocks than needed.
+ var feedTokens = func(cnt int64) error {
+ for cntNewline < cnt {
+ if _, err := io.ReadFull(r, blk); err != nil {
+ if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ }
+ return err
+ }
+ buf.Write(blk)
+ for _, c := range blk {
+ if c == '\n' {
+ cntNewline++
+ }
+ }
+ }
+ return nil
+ }
+
+ // nextToken gets the next token delimited by a newline. This assumes that
+ // at least one newline exists in the buffer.
+ var nextToken = func() string {
+ cntNewline--
+ tok, _ := buf.ReadString('\n')
+ return tok[:len(tok)-1] // Cut off newline
+ }
+
+ // Parse for the number of entries.
+ // Use integer overflow resistant math to check this.
+ if err := feedTokens(1); err != nil {
+ return nil, err
+ }
+ numEntries, err := strconv.ParseInt(nextToken(), 10, 0) // Intentionally parse as native int
+ if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) {
+ return nil, ErrHeader
+ }
+
+ // Parse for all member entries.
+ // numEntries is trusted after this since a potential attacker must have
+ // committed resources proportional to what this library used.
+ if err := feedTokens(2 * numEntries); err != nil {
+ return nil, err
+ }
+ sp := make([]sparseEntry, 0, numEntries)
+ for i := int64(0); i < numEntries; i++ {
+ offset, err := strconv.ParseInt(nextToken(), 10, 64)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ numBytes, err := strconv.ParseInt(nextToken(), 10, 64)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
+ }
+ return sp, nil
+}
+
+// readGNUSparseMap0x1 reads the sparse map as stored in GNU's PAX sparse format
+// version 0.1. The sparse map is stored in the PAX headers.
+func readGNUSparseMap0x1(extHdrs map[string]string) ([]sparseEntry, error) {
+ // Get number of entries.
+ // Use integer overflow resistant math to check this.
+ numEntriesStr := extHdrs[paxGNUSparseNumBlocks]
+ numEntries, err := strconv.ParseInt(numEntriesStr, 10, 0) // Intentionally parse as native int
+ if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) {
+ return nil, ErrHeader
+ }
+
+ // There should be two numbers in sparseMap for each entry.
+ sparseMap := strings.Split(extHdrs[paxGNUSparseMap], ",")
+ if int64(len(sparseMap)) != 2*numEntries {
+ return nil, ErrHeader
+ }
+
+ // Loop through the entries in the sparse map.
+ // numEntries is trusted now.
+ sp := make([]sparseEntry, 0, numEntries)
+ for i := int64(0); i < numEntries; i++ {
+ offset, err := strconv.ParseInt(sparseMap[2*i], 10, 64)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ numBytes, err := strconv.ParseInt(sparseMap[2*i+1], 10, 64)
+ if err != nil {
+ return nil, ErrHeader
+ }
+ sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
+ }
+ return sp, nil
+}
+
+// numBytes returns the number of bytes left to read in the current file's entry
+// in the tar archive, or 0 if there is no current file.
+func (tr *Reader) numBytes() int64 {
+ if tr.curr == nil {
+ // No current file, so no bytes
+ return 0
+ }
+ return tr.curr.numBytes()
+}
+
+// Read reads from the current entry in the tar archive.
+// It returns 0, io.EOF when it reaches the end of that entry,
+// until Next is called to advance to the next entry.
+//
+// Calling Read on special types like TypeLink, TypeSymLink, TypeChar,
+// TypeBlock, TypeDir, and TypeFifo returns 0, io.EOF regardless of what
+// the Header.Size claims.
+func (tr *Reader) Read(b []byte) (n int, err error) {
+ if tr.err != nil {
+ return 0, tr.err
+ }
+ if tr.curr == nil {
+ return 0, io.EOF
+ }
+
+ n, err = tr.curr.Read(b)
+ if err != nil && err != io.EOF {
+ tr.err = err
+ }
+ return
+}
+
+func (rfr *regFileReader) Read(b []byte) (n int, err error) {
+ if rfr.nb == 0 {
+ // file consumed
+ return 0, io.EOF
+ }
+ if int64(len(b)) > rfr.nb {
+ b = b[0:rfr.nb]
+ }
+ n, err = rfr.r.Read(b)
+ rfr.nb -= int64(n)
+
+ if err == io.EOF && rfr.nb > 0 {
+ err = io.ErrUnexpectedEOF
+ }
+ return
+}
+
+// numBytes returns the number of bytes left to read in the file's data in the tar archive.
+func (rfr *regFileReader) numBytes() int64 {
+ return rfr.nb
+}
+
+// newSparseFileReader creates a new sparseFileReader, but validates all of the
+// sparse entries before doing so.
+func newSparseFileReader(rfr numBytesReader, sp []sparseEntry, total int64) (*sparseFileReader, error) {
+ if total < 0 {
+ return nil, ErrHeader // Total size cannot be negative
+ }
+
+ // Validate all sparse entries. These are the same checks as performed by
+ // the BSD tar utility.
+ for i, s := range sp {
+ switch {
+ case s.offset < 0 || s.numBytes < 0:
+ return nil, ErrHeader // Negative values are never okay
+ case s.offset > math.MaxInt64-s.numBytes:
+ return nil, ErrHeader // Integer overflow with large length
+ case s.offset+s.numBytes > total:
+ return nil, ErrHeader // Region extends beyond the "real" size
+ case i > 0 && sp[i-1].offset+sp[i-1].numBytes > s.offset:
+ return nil, ErrHeader // Regions can't overlap and must be in order
+ }
+ }
+ return &sparseFileReader{rfr: rfr, sp: sp, total: total}, nil
+}
+
+// readHole reads a sparse hole ending at endOffset.
+func (sfr *sparseFileReader) readHole(b []byte, endOffset int64) int {
+ n64 := endOffset - sfr.pos
+ if n64 > int64(len(b)) {
+ n64 = int64(len(b))
+ }
+ n := int(n64)
+ for i := 0; i < n; i++ {
+ b[i] = 0
+ }
+ sfr.pos += n64
+ return n
+}
+
+// Read reads the sparse file data in expanded form.
+func (sfr *sparseFileReader) Read(b []byte) (n int, err error) {
+ // Skip past all empty fragments.
+ for len(sfr.sp) > 0 && sfr.sp[0].numBytes == 0 {
+ sfr.sp = sfr.sp[1:]
+ }
+
+ // If there are no more fragments, then it is possible that there
+ // is one last sparse hole.
+ if len(sfr.sp) == 0 {
+ // This behavior matches the BSD tar utility.
+ // However, GNU tar stops returning data even if sfr.total is unmet.
+ if sfr.pos < sfr.total {
+ return sfr.readHole(b, sfr.total), nil
+ }
+ return 0, io.EOF
+ }
+
+ // In front of a data fragment, so read a hole.
+ if sfr.pos < sfr.sp[0].offset {
+ return sfr.readHole(b, sfr.sp[0].offset), nil
+ }
+
+ // In a data fragment, so read from it.
+ // This math is overflow free since we verify that offset and numBytes can
+ // be safely added when creating the sparseFileReader.
+ endPos := sfr.sp[0].offset + sfr.sp[0].numBytes // End offset of fragment
+ bytesLeft := endPos - sfr.pos // Bytes left in fragment
+ if int64(len(b)) > bytesLeft {
+ b = b[:bytesLeft]
+ }
+
+ n, err = sfr.rfr.Read(b)
+ sfr.pos += int64(n)
+ if err == io.EOF {
+ if sfr.pos < endPos {
+ err = io.ErrUnexpectedEOF // There was supposed to be more data
+ } else if sfr.pos < sfr.total {
+ err = nil // There is still an implicit sparse hole at the end
+ }
+ }
+
+ if sfr.pos == endPos {
+ sfr.sp = sfr.sp[1:] // We are done with this fragment, so pop it
+ }
+ return n, err
+}
+
+// numBytes returns the number of bytes left to read in the sparse file's
+// sparse-encoded data in the tar archive.
+func (sfr *sparseFileReader) numBytes() int64 {
+ return sfr.rfr.numBytes()
+}
diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/stat_atim.go b/vendor/github.com/vbatts/tar-split/archive/tar/stat_atim.go
new file mode 100644
index 0000000..cf9cc79
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/archive/tar/stat_atim.go
@@ -0,0 +1,20 @@
+// 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 linux dragonfly openbsd solaris
+
+package tar
+
+import (
+ "syscall"
+ "time"
+)
+
+func statAtime(st *syscall.Stat_t) time.Time {
+ return time.Unix(st.Atim.Unix())
+}
+
+func statCtime(st *syscall.Stat_t) time.Time {
+ return time.Unix(st.Ctim.Unix())
+}
diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/stat_atimespec.go b/vendor/github.com/vbatts/tar-split/archive/tar/stat_atimespec.go
new file mode 100644
index 0000000..6f17dbe
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/archive/tar/stat_atimespec.go
@@ -0,0 +1,20 @@
+// 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 darwin freebsd netbsd
+
+package tar
+
+import (
+ "syscall"
+ "time"
+)
+
+func statAtime(st *syscall.Stat_t) time.Time {
+ return time.Unix(st.Atimespec.Unix())
+}
+
+func statCtime(st *syscall.Stat_t) time.Time {
+ return time.Unix(st.Ctimespec.Unix())
+}
diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/stat_unix.go b/vendor/github.com/vbatts/tar-split/archive/tar/stat_unix.go
new file mode 100644
index 0000000..cb843db
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/archive/tar/stat_unix.go
@@ -0,0 +1,32 @@
+// 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 linux darwin dragonfly freebsd openbsd netbsd solaris
+
+package tar
+
+import (
+ "os"
+ "syscall"
+)
+
+func init() {
+ sysStat = statUnix
+}
+
+func statUnix(fi os.FileInfo, h *Header) error {
+ sys, ok := fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return nil
+ }
+ h.Uid = int(sys.Uid)
+ h.Gid = int(sys.Gid)
+ // TODO(bradfitz): populate username & group. os/user
+ // doesn't cache LookupId lookups, and lacks group
+ // lookup functions.
+ h.AccessTime = statAtime(sys)
+ h.ChangeTime = statCtime(sys)
+ // TODO(bradfitz): major/minor device numbers?
+ return nil
+}
diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/writer.go b/vendor/github.com/vbatts/tar-split/archive/tar/writer.go
new file mode 100644
index 0000000..0426381
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/archive/tar/writer.go
@@ -0,0 +1,416 @@
+// Copyright 2009 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 tar
+
+// TODO(dsymonds):
+// - catch more errors (no first header, etc.)
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "path"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var (
+ ErrWriteTooLong = errors.New("archive/tar: write too long")
+ ErrFieldTooLong = errors.New("archive/tar: header field too long")
+ ErrWriteAfterClose = errors.New("archive/tar: write after close")
+ errInvalidHeader = errors.New("archive/tar: header field too long or contains invalid values")
+)
+
+// A Writer provides sequential writing of a tar archive in POSIX.1 format.
+// A tar archive consists of a sequence of files.
+// Call WriteHeader to begin a new file, and then call Write to supply that file's data,
+// writing at most hdr.Size bytes in total.
+type Writer struct {
+ w io.Writer
+ err error
+ nb int64 // number of unwritten bytes for current file entry
+ pad int64 // amount of padding to write after current file entry
+ closed bool
+ usedBinary bool // whether the binary numeric field extension was used
+ preferPax bool // use pax header instead of binary numeric header
+ hdrBuff [blockSize]byte // buffer to use in writeHeader when writing a regular header
+ paxHdrBuff [blockSize]byte // buffer to use in writeHeader when writing a pax header
+}
+
+type formatter struct {
+ err error // Last error seen
+}
+
+// NewWriter creates a new Writer writing to w.
+func NewWriter(w io.Writer) *Writer { return &Writer{w: w} }
+
+// Flush finishes writing the current file (optional).
+func (tw *Writer) Flush() error {
+ if tw.nb > 0 {
+ tw.err = fmt.Errorf("archive/tar: missed writing %d bytes", tw.nb)
+ return tw.err
+ }
+
+ n := tw.nb + tw.pad
+ for n > 0 && tw.err == nil {
+ nr := n
+ if nr > blockSize {
+ nr = blockSize
+ }
+ var nw int
+ nw, tw.err = tw.w.Write(zeroBlock[0:nr])
+ n -= int64(nw)
+ }
+ tw.nb = 0
+ tw.pad = 0
+ return tw.err
+}
+
+// Write s into b, terminating it with a NUL if there is room.
+func (f *formatter) formatString(b []byte, s string) {
+ if len(s) > len(b) {
+ f.err = ErrFieldTooLong
+ return
+ }
+ ascii := toASCII(s)
+ copy(b, ascii)
+ if len(ascii) < len(b) {
+ b[len(ascii)] = 0
+ }
+}
+
+// Encode x as an octal ASCII string and write it into b with leading zeros.
+func (f *formatter) formatOctal(b []byte, x int64) {
+ s := strconv.FormatInt(x, 8)
+ // leading zeros, but leave room for a NUL.
+ for len(s)+1 < len(b) {
+ s = "0" + s
+ }
+ f.formatString(b, s)
+}
+
+// fitsInBase256 reports whether x can be encoded into n bytes using base-256
+// encoding. Unlike octal encoding, base-256 encoding does not require that the
+// string ends with a NUL character. Thus, all n bytes are available for output.
+//
+// If operating in binary mode, this assumes strict GNU binary mode; which means
+// that the first byte can only be either 0x80 or 0xff. Thus, the first byte is
+// equivalent to the sign bit in two's complement form.
+func fitsInBase256(n int, x int64) bool {
+ var binBits = uint(n-1) * 8
+ return n >= 9 || (x >= -1<<binBits && x < 1<<binBits)
+}
+
+// Write x into b, as binary (GNUtar/star extension).
+func (f *formatter) formatNumeric(b []byte, x int64) {
+ if fitsInBase256(len(b), x) {
+ for i := len(b) - 1; i >= 0; i-- {
+ b[i] = byte(x)
+ x >>= 8
+ }
+ b[0] |= 0x80 // Highest bit indicates binary format
+ return
+ }
+
+ f.formatOctal(b, 0) // Last resort, just write zero
+ f.err = ErrFieldTooLong
+}
+
+var (
+ minTime = time.Unix(0, 0)
+ // There is room for 11 octal digits (33 bits) of mtime.
+ maxTime = minTime.Add((1<<33 - 1) * time.Second)
+)
+
+// WriteHeader writes hdr and prepares to accept the file's contents.
+// WriteHeader calls Flush if it is not the first header.
+// Calling after a Close will return ErrWriteAfterClose.
+func (tw *Writer) WriteHeader(hdr *Header) error {
+ return tw.writeHeader(hdr, true)
+}
+
+// WriteHeader writes hdr and prepares to accept the file's contents.
+// WriteHeader calls Flush if it is not the first header.
+// Calling after a Close will return ErrWriteAfterClose.
+// As this method is called internally by writePax header to allow it to
+// suppress writing the pax header.
+func (tw *Writer) writeHeader(hdr *Header, allowPax bool) error {
+ if tw.closed {
+ return ErrWriteAfterClose
+ }
+ if tw.err == nil {
+ tw.Flush()
+ }
+ if tw.err != nil {
+ return tw.err
+ }
+
+ // a map to hold pax header records, if any are needed
+ paxHeaders := make(map[string]string)
+
+ // TODO(shanemhansen): we might want to use PAX headers for
+ // subsecond time resolution, but for now let's just capture
+ // too long fields or non ascii characters
+
+ var f formatter
+ var header []byte
+
+ // We need to select which scratch buffer to use carefully,
+ // since this method is called recursively to write PAX headers.
+ // If allowPax is true, this is the non-recursive call, and we will use hdrBuff.
+ // If allowPax is false, we are being called by writePAXHeader, and hdrBuff is
+ // already being used by the non-recursive call, so we must use paxHdrBuff.
+ header = tw.hdrBuff[:]
+ if !allowPax {
+ header = tw.paxHdrBuff[:]
+ }
+ copy(header, zeroBlock)
+ s := slicer(header)
+
+ // Wrappers around formatter that automatically sets paxHeaders if the
+ // argument extends beyond the capacity of the input byte slice.
+ var formatString = func(b []byte, s string, paxKeyword string) {
+ needsPaxHeader := paxKeyword != paxNone && len(s) > len(b) || !isASCII(s)
+ if needsPaxHeader {
+ paxHeaders[paxKeyword] = s
+ return
+ }
+ f.formatString(b, s)
+ }
+ var formatNumeric = func(b []byte, x int64, paxKeyword string) {
+ // Try octal first.
+ s := strconv.FormatInt(x, 8)
+ if len(s) < len(b) {
+ f.formatOctal(b, x)
+ return
+ }
+
+ // If it is too long for octal, and PAX is preferred, use a PAX header.
+ if paxKeyword != paxNone && tw.preferPax {
+ f.formatOctal(b, 0)
+ s := strconv.FormatInt(x, 10)
+ paxHeaders[paxKeyword] = s
+ return
+ }
+
+ tw.usedBinary = true
+ f.formatNumeric(b, x)
+ }
+
+ // keep a reference to the filename to allow to overwrite it later if we detect that we can use ustar longnames instead of pax
+ pathHeaderBytes := s.next(fileNameSize)
+
+ formatString(pathHeaderBytes, hdr.Name, paxPath)
+
+ // Handle out of range ModTime carefully.
+ var modTime int64
+ if !hdr.ModTime.Before(minTime) && !hdr.ModTime.After(maxTime) {
+ modTime = hdr.ModTime.Unix()
+ }
+
+ f.formatOctal(s.next(8), hdr.Mode) // 100:108
+ formatNumeric(s.next(8), int64(hdr.Uid), paxUid) // 108:116
+ formatNumeric(s.next(8), int64(hdr.Gid), paxGid) // 116:124
+ formatNumeric(s.next(12), hdr.Size, paxSize) // 124:136
+ formatNumeric(s.next(12), modTime, paxNone) // 136:148 --- consider using pax for finer granularity
+ s.next(8) // chksum (148:156)
+ s.next(1)[0] = hdr.Typeflag // 156:157
+
+ formatString(s.next(100), hdr.Linkname, paxLinkpath)
+
+ copy(s.next(8), []byte("ustar\x0000")) // 257:265
+ formatString(s.next(32), hdr.Uname, paxUname) // 265:297
+ formatString(s.next(32), hdr.Gname, paxGname) // 297:329
+ formatNumeric(s.next(8), hdr.Devmajor, paxNone) // 329:337
+ formatNumeric(s.next(8), hdr.Devminor, paxNone) // 337:345
+
+ // keep a reference to the prefix to allow to overwrite it later if we detect that we can use ustar longnames instead of pax
+ prefixHeaderBytes := s.next(155)
+ formatString(prefixHeaderBytes, "", paxNone) // 345:500 prefix
+
+ // Use the GNU magic instead of POSIX magic if we used any GNU extensions.
+ if tw.usedBinary {
+ copy(header[257:265], []byte("ustar \x00"))
+ }
+
+ _, paxPathUsed := paxHeaders[paxPath]
+ // try to use a ustar header when only the name is too long
+ if !tw.preferPax && len(paxHeaders) == 1 && paxPathUsed {
+ prefix, suffix, ok := splitUSTARPath(hdr.Name)
+ if ok {
+ // Since we can encode in USTAR format, disable PAX header.
+ delete(paxHeaders, paxPath)
+
+ // Update the path fields
+ formatString(pathHeaderBytes, suffix, paxNone)
+ formatString(prefixHeaderBytes, prefix, paxNone)
+ }
+ }
+
+ // The chksum field is terminated by a NUL and a space.
+ // This is different from the other octal fields.
+ chksum, _ := checksum(header)
+ f.formatOctal(header[148:155], chksum) // Never fails
+ header[155] = ' '
+
+ // Check if there were any formatting errors.
+ if f.err != nil {
+ tw.err = f.err
+ return tw.err
+ }
+
+ if allowPax {
+ for k, v := range hdr.Xattrs {
+ paxHeaders[paxXattr+k] = v
+ }
+ }
+
+ if len(paxHeaders) > 0 {
+ if !allowPax {
+ return errInvalidHeader
+ }
+ if err := tw.writePAXHeader(hdr, paxHeaders); err != nil {
+ return err
+ }
+ }
+ tw.nb = int64(hdr.Size)
+ tw.pad = (blockSize - (tw.nb % blockSize)) % blockSize
+
+ _, tw.err = tw.w.Write(header)
+ return tw.err
+}
+
+// splitUSTARPath splits a path according to USTAR prefix and suffix rules.
+// If the path is not splittable, then it will return ("", "", false).
+func splitUSTARPath(name string) (prefix, suffix string, ok bool) {
+ length := len(name)
+ if length <= fileNameSize || !isASCII(name) {
+ return "", "", false
+ } else if length > fileNamePrefixSize+1 {
+ length = fileNamePrefixSize + 1
+ } else if name[length-1] == '/' {
+ length--
+ }
+
+ i := strings.LastIndex(name[:length], "/")
+ nlen := len(name) - i - 1 // nlen is length of suffix
+ plen := i // plen is length of prefix
+ if i <= 0 || nlen > fileNameSize || nlen == 0 || plen > fileNamePrefixSize {
+ return "", "", false
+ }
+ return name[:i], name[i+1:], true
+}
+
+// writePaxHeader writes an extended pax header to the
+// archive.
+func (tw *Writer) writePAXHeader(hdr *Header, paxHeaders map[string]string) error {
+ // Prepare extended header
+ ext := new(Header)
+ ext.Typeflag = TypeXHeader
+ // Setting ModTime is required for reader parsing to
+ // succeed, and seems harmless enough.
+ ext.ModTime = hdr.ModTime
+ // The spec asks that we namespace our pseudo files
+ // with the current pid. However, this results in differing outputs
+ // for identical inputs. As such, the constant 0 is now used instead.
+ // golang.org/issue/12358
+ dir, file := path.Split(hdr.Name)
+ fullName := path.Join(dir, "PaxHeaders.0", file)
+
+ ascii := toASCII(fullName)
+ if len(ascii) > 100 {
+ ascii = ascii[:100]
+ }
+ ext.Name = ascii
+ // Construct the body
+ var buf bytes.Buffer
+
+ // Keys are sorted before writing to body to allow deterministic output.
+ var keys []string
+ for k := range paxHeaders {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+
+ for _, k := range keys {
+ fmt.Fprint(&buf, formatPAXRecord(k, paxHeaders[k]))
+ }
+
+ ext.Size = int64(len(buf.Bytes()))
+ if err := tw.writeHeader(ext, false); err != nil {
+ return err
+ }
+ if _, err := tw.Write(buf.Bytes()); err != nil {
+ return err
+ }
+ if err := tw.Flush(); err != nil {
+ return err
+ }
+ return nil
+}
+
+// formatPAXRecord formats a single PAX record, prefixing it with the
+// appropriate length.
+func formatPAXRecord(k, v string) string {
+ const padding = 3 // Extra padding for ' ', '=', and '\n'
+ size := len(k) + len(v) + padding
+ size += len(strconv.Itoa(size))
+ record := fmt.Sprintf("%d %s=%s\n", size, k, v)
+
+ // Final adjustment if adding size field increased the record size.
+ if len(record) != size {
+ size = len(record)
+ record = fmt.Sprintf("%d %s=%s\n", size, k, v)
+ }
+ return record
+}
+
+// Write writes to the current entry in the tar archive.
+// Write returns the error ErrWriteTooLong if more than
+// hdr.Size bytes are written after WriteHeader.
+func (tw *Writer) Write(b []byte) (n int, err error) {
+ if tw.closed {
+ err = ErrWriteAfterClose
+ return
+ }
+ overwrite := false
+ if int64(len(b)) > tw.nb {
+ b = b[0:tw.nb]
+ overwrite = true
+ }
+ n, err = tw.w.Write(b)
+ tw.nb -= int64(n)
+ if err == nil && overwrite {
+ err = ErrWriteTooLong
+ return
+ }
+ tw.err = err
+ return
+}
+
+// Close closes the tar archive, flushing any unwritten
+// data to the underlying writer.
+func (tw *Writer) Close() error {
+ if tw.err != nil || tw.closed {
+ return tw.err
+ }
+ tw.Flush()
+ tw.closed = true
+ if tw.err != nil {
+ return tw.err
+ }
+
+ // trailer: two zero blocks
+ for i := 0; i < 2; i++ {
+ _, tw.err = tw.w.Write(zeroBlock)
+ if tw.err != nil {
+ break
+ }
+ }
+ return tw.err
+}
diff --git a/vendor/github.com/vbatts/tar-split/tar/asm/README.md b/vendor/github.com/vbatts/tar-split/tar/asm/README.md
new file mode 100644
index 0000000..2a3a5b5
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/tar/asm/README.md
@@ -0,0 +1,44 @@
+asm
+===
+
+This library for assembly and disassembly of tar archives, facilitated by
+`github.com/vbatts/tar-split/tar/storage`.
+
+
+Concerns
+--------
+
+For completely safe assembly/disassembly, there will need to be a Content
+Addressable Storage (CAS) directory, that maps to a checksum in the
+`storage.Entity` of `storage.FileType`.
+
+This is due to the fact that tar archives _can_ allow multiple records for the
+same path, but the last one effectively wins. Even if the prior records had a
+different payload.
+
+In this way, when assembling an archive from relative paths, if the archive has
+multiple entries for the same path, then all payloads read in from a relative
+path would be identical.
+
+
+Thoughts
+--------
+
+Have a look-aside directory or storage. This way when a clobbering record is
+encountered from the tar stream, then the payload of the prior/existing file is
+stored to the CAS. This way the clobbering record's file payload can be
+extracted, but we'll have preserved the payload needed to reassemble a precise
+tar archive.
+
+clobbered/path/to/file.[0-N]
+
+*alternatively*
+
+We could just _not_ support tar streams that have clobbering file paths.
+Appending records to the archive is not incredibly common, and doesn't happen
+by default for most implementations. Not supporting them wouldn't be a
+security concern either, as if it did occur, we would reassemble an archive
+that doesn't validate signature/checksum, so it shouldn't be trusted anyway.
+
+Otherwise, this will allow us to defer support for appended files as a FUTURE FEATURE.
+
diff --git a/vendor/github.com/vbatts/tar-split/tar/asm/assemble.go b/vendor/github.com/vbatts/tar-split/tar/asm/assemble.go
new file mode 100644
index 0000000..d624450
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/tar/asm/assemble.go
@@ -0,0 +1,130 @@
+package asm
+
+import (
+ "bytes"
+ "fmt"
+ "hash"
+ "hash/crc64"
+ "io"
+ "sync"
+
+ "github.com/vbatts/tar-split/tar/storage"
+)
+
+// NewOutputTarStream returns an io.ReadCloser that is an assembled tar archive
+// stream.
+//
+// It takes a storage.FileGetter, for mapping the file payloads that are to be read in,
+// and a storage.Unpacker, which has access to the rawbytes and file order
+// metadata. With the combination of these two items, a precise assembled Tar
+// archive is possible.
+func NewOutputTarStream(fg storage.FileGetter, up storage.Unpacker) io.ReadCloser {
+ // ... Since these are interfaces, this is possible, so let's not have a nil pointer
+ if fg == nil || up == nil {
+ return nil
+ }
+ pr, pw := io.Pipe()
+ go func() {
+ err := WriteOutputTarStream(fg, up, pw)
+ if err != nil {
+ pw.CloseWithError(err)
+ } else {
+ pw.Close()
+ }
+ }()
+ return pr
+}
+
+// WriteOutputTarStream writes assembled tar archive to a writer.
+func WriteOutputTarStream(fg storage.FileGetter, up storage.Unpacker, w io.Writer) error {
+ // ... Since these are interfaces, this is possible, so let's not have a nil pointer
+ if fg == nil || up == nil {
+ return nil
+ }
+ var copyBuffer []byte
+ var crcHash hash.Hash
+ var crcSum []byte
+ var multiWriter io.Writer
+ for {
+ entry, err := up.Next()
+ if err != nil {
+ if err == io.EOF {
+ return nil
+ }
+ return err
+ }
+ switch entry.Type {
+ case storage.SegmentType:
+ if _, err := w.Write(entry.Payload); err != nil {
+ return err
+ }
+ case storage.FileType:
+ if entry.Size == 0 {
+ continue
+ }
+ fh, err := fg.Get(entry.GetName())
+ if err != nil {
+ return err
+ }
+ if crcHash == nil {
+ crcHash = crc64.New(storage.CRCTable)
+ crcSum = make([]byte, 8)
+ multiWriter = io.MultiWriter(w, crcHash)
+ copyBuffer = byteBufferPool.Get().([]byte)
+ defer byteBufferPool.Put(copyBuffer)
+ } else {
+ crcHash.Reset()
+ }
+
+ if _, err := copyWithBuffer(multiWriter, fh, copyBuffer); err != nil {
+ fh.Close()
+ return err
+ }
+
+ if !bytes.Equal(crcHash.Sum(crcSum[:0]), entry.Payload) {
+ // I would rather this be a comparable ErrInvalidChecksum or such,
+ // but since it's coming through the PipeReader, the context of
+ // _which_ file would be lost...
+ fh.Close()
+ return fmt.Errorf("file integrity checksum failed for %q", entry.GetName())
+ }
+ fh.Close()
+ }
+ }
+}
+
+var byteBufferPool = &sync.Pool{
+ New: func() interface{} {
+ return make([]byte, 32*1024)
+ },
+}
+
+// copyWithBuffer is taken from stdlib io.Copy implementation
+// https://github.com/golang/go/blob/go1.5.1/src/io/io.go#L367
+func copyWithBuffer(dst io.Writer, src io.Reader, buf []byte) (written int64, err error) {
+ for {
+ nr, er := src.Read(buf)
+ if nr > 0 {
+ nw, ew := dst.Write(buf[0:nr])
+ if nw > 0 {
+ written += int64(nw)
+ }
+ if ew != nil {
+ err = ew
+ break
+ }
+ if nr != nw {
+ err = io.ErrShortWrite
+ break
+ }
+ }
+ if er == io.EOF {
+ break
+ }
+ if er != nil {
+ err = er
+ break
+ }
+ }
+ return written, err
+}
diff --git a/vendor/github.com/vbatts/tar-split/tar/asm/disassemble.go b/vendor/github.com/vbatts/tar-split/tar/asm/disassemble.go
new file mode 100644
index 0000000..54ef23a
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/tar/asm/disassemble.go
@@ -0,0 +1,141 @@
+package asm
+
+import (
+ "io"
+ "io/ioutil"
+
+ "github.com/vbatts/tar-split/archive/tar"
+ "github.com/vbatts/tar-split/tar/storage"
+)
+
+// NewInputTarStream wraps the Reader stream of a tar archive and provides a
+// Reader stream of the same.
+//
+// In the middle it will pack the segments and file metadata to storage.Packer
+// `p`.
+//
+// The the storage.FilePutter is where payload of files in the stream are
+// stashed. If this stashing is not needed, you can provide a nil
+// storage.FilePutter. Since the checksumming is still needed, then a default
+// of NewDiscardFilePutter will be used internally
+func NewInputTarStream(r io.Reader, p storage.Packer, fp storage.FilePutter) (io.Reader, error) {
+ // What to do here... folks will want their own access to the Reader that is
+ // their tar archive stream, but we'll need that same stream to use our
+ // forked 'archive/tar'.
+ // Perhaps do an io.TeeReader that hands back an io.Reader for them to read
+ // from, and we'll MITM the stream to store metadata.
+ // We'll need a storage.FilePutter too ...
+
+ // Another concern, whether to do any storage.FilePutter operations, such that we
+ // don't extract any amount of the archive. But then again, we're not making
+ // files/directories, hardlinks, etc. Just writing the io to the storage.FilePutter.
+ // Perhaps we have a DiscardFilePutter that is a bit bucket.
+
+ // we'll return the pipe reader, since TeeReader does not buffer and will
+ // only read what the outputRdr Read's. Since Tar archives have padding on
+ // the end, we want to be the one reading the padding, even if the user's
+ // `archive/tar` doesn't care.
+ pR, pW := io.Pipe()
+ outputRdr := io.TeeReader(r, pW)
+
+ // we need a putter that will generate the crc64 sums of file payloads
+ if fp == nil {
+ fp = storage.NewDiscardFilePutter()
+ }
+
+ go func() {
+ tr := tar.NewReader(outputRdr)
+ tr.RawAccounting = true
+ for {
+ hdr, err := tr.Next()
+ if err != nil {
+ if err != io.EOF {
+ pW.CloseWithError(err)
+ return
+ }
+ // even when an EOF is reached, there is often 1024 null bytes on
+ // the end of an archive. Collect them too.
+ if b := tr.RawBytes(); len(b) > 0 {
+ _, err := p.AddEntry(storage.Entry{
+ Type: storage.SegmentType,
+ Payload: b,
+ })
+ if err != nil {
+ pW.CloseWithError(err)
+ return
+ }
+ }
+ break // not return. We need the end of the reader.
+ }
+ if hdr == nil {
+ break // not return. We need the end of the reader.
+ }
+
+ if b := tr.RawBytes(); len(b) > 0 {
+ _, err := p.AddEntry(storage.Entry{
+ Type: storage.SegmentType,
+ Payload: b,
+ })
+ if err != nil {
+ pW.CloseWithError(err)
+ return
+ }
+ }
+
+ var csum []byte
+ if hdr.Size > 0 {
+ var err error
+ _, csum, err = fp.Put(hdr.Name, tr)
+ if err != nil {
+ pW.CloseWithError(err)
+ return
+ }
+ }
+
+ entry := storage.Entry{
+ Type: storage.FileType,
+ Size: hdr.Size,
+ Payload: csum,
+ }
+ // For proper marshalling of non-utf8 characters
+ entry.SetName(hdr.Name)
+
+ // File entries added, regardless of size
+ _, err = p.AddEntry(entry)
+ if err != nil {
+ pW.CloseWithError(err)
+ return
+ }
+
+ if b := tr.RawBytes(); len(b) > 0 {
+ _, err = p.AddEntry(storage.Entry{
+ Type: storage.SegmentType,
+ Payload: b,
+ })
+ if err != nil {
+ pW.CloseWithError(err)
+ return
+ }
+ }
+ }
+
+ // it is allowable, and not uncommon that there is further padding on the
+ // end of an archive, apart from the expected 1024 null bytes.
+ remainder, err := ioutil.ReadAll(outputRdr)
+ if err != nil && err != io.EOF {
+ pW.CloseWithError(err)
+ return
+ }
+ _, err = p.AddEntry(storage.Entry{
+ Type: storage.SegmentType,
+ Payload: remainder,
+ })
+ if err != nil {
+ pW.CloseWithError(err)
+ return
+ }
+ pW.Close()
+ }()
+
+ return pR, nil
+}
diff --git a/vendor/github.com/vbatts/tar-split/tar/asm/doc.go b/vendor/github.com/vbatts/tar-split/tar/asm/doc.go
new file mode 100644
index 0000000..4367b90
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/tar/asm/doc.go
@@ -0,0 +1,9 @@
+/*
+Package asm provides the API for streaming assembly and disassembly of tar
+archives.
+
+Using the `github.com/vbatts/tar-split/tar/storage` for Packing/Unpacking the
+metadata for a stream, as well as an implementation of Getting/Putting the file
+entries' payload.
+*/
+package asm
diff --git a/vendor/github.com/vbatts/tar-split/tar/storage/doc.go b/vendor/github.com/vbatts/tar-split/tar/storage/doc.go
new file mode 100644
index 0000000..83f7089
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/tar/storage/doc.go
@@ -0,0 +1,12 @@
+/*
+Package storage is for metadata of a tar archive.
+
+Packing and unpacking the Entries of the stream. The types of streams are
+either segments of raw bytes (for the raw headers and various padding) and for
+an entry marking a file payload.
+
+The raw bytes are stored precisely in the packed (marshalled) Entry, whereas
+the file payload marker include the name of the file, size, and crc64 checksum
+(for basic file integrity).
+*/
+package storage
diff --git a/vendor/github.com/vbatts/tar-split/tar/storage/entry.go b/vendor/github.com/vbatts/tar-split/tar/storage/entry.go
new file mode 100644
index 0000000..c91e7ea
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/tar/storage/entry.go
@@ -0,0 +1,78 @@
+package storage
+
+import "unicode/utf8"
+
+// Entries is for sorting by Position
+type Entries []Entry
+
+func (e Entries) Len() int { return len(e) }
+func (e Entries) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
+func (e Entries) Less(i, j int) bool { return e[i].Position < e[j].Position }
+
+// Type of Entry
+type Type int
+
+const (
+ // FileType represents a file payload from the tar stream.
+ //
+ // This will be used to map to relative paths on disk. Only Size > 0 will get
+ // read into a resulting output stream (due to hardlinks).
+ FileType Type = 1 + iota
+ // SegmentType represents a raw bytes segment from the archive stream. These raw
+ // byte segments consist of the raw headers and various padding.
+ //
+ // Its payload is to be marshalled base64 encoded.
+ SegmentType
+)
+
+// Entry is the structure for packing and unpacking the information read from
+// the Tar archive.
+//
+// FileType Payload checksum is using `hash/crc64` for basic file integrity,
+// _not_ for cryptography.
+// From http://www.backplane.com/matt/crc64.html, CRC32 has almost 40,000
+// collisions in a sample of 18.2 million, CRC64 had none.
+type Entry struct {
+ Type Type `json:"type"`
+ Name string `json:"name,omitempty"`
+ NameRaw []byte `json:"name_raw,omitempty"`
+ Size int64 `json:"size,omitempty"`
+ Payload []byte `json:"payload"` // SegmentType stores payload here; FileType stores crc64 checksum here;
+ Position int `json:"position"`
+}
+
+// SetName will check name for valid UTF-8 string, and set the appropriate
+// field. See https://github.com/vbatts/tar-split/issues/17
+func (e *Entry) SetName(name string) {
+ if utf8.ValidString(name) {
+ e.Name = name
+ } else {
+ e.NameRaw = []byte(name)
+ }
+}
+
+// SetNameBytes will check name for valid UTF-8 string, and set the appropriate
+// field
+func (e *Entry) SetNameBytes(name []byte) {
+ if utf8.Valid(name) {
+ e.Name = string(name)
+ } else {
+ e.NameRaw = name
+ }
+}
+
+// GetName returns the string for the entry's name, regardless of the field stored in
+func (e *Entry) GetName() string {
+ if len(e.NameRaw) > 0 {
+ return string(e.NameRaw)
+ }
+ return e.Name
+}
+
+// GetNameBytes returns the bytes for the entry's name, regardless of the field stored in
+func (e *Entry) GetNameBytes() []byte {
+ if len(e.NameRaw) > 0 {
+ return e.NameRaw
+ }
+ return []byte(e.Name)
+}
diff --git a/vendor/github.com/vbatts/tar-split/tar/storage/getter.go b/vendor/github.com/vbatts/tar-split/tar/storage/getter.go
new file mode 100644
index 0000000..ae11f8f
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/tar/storage/getter.go
@@ -0,0 +1,104 @@
+package storage
+
+import (
+ "bytes"
+ "errors"
+ "hash/crc64"
+ "io"
+ "os"
+ "path/filepath"
+)
+
+// FileGetter is the interface for getting a stream of a file payload,
+// addressed by name/filename. Presumably, the names will be scoped to relative
+// file paths.
+type FileGetter interface {
+ // Get returns a stream for the provided file path
+ Get(filename string) (output io.ReadCloser, err error)
+}
+
+// FilePutter is the interface for storing a stream of a file payload,
+// addressed by name/filename.
+type FilePutter interface {
+ // Put returns the size of the stream received, and the crc64 checksum for
+ // the provided stream
+ Put(filename string, input io.Reader) (size int64, checksum []byte, err error)
+}
+
+// FileGetPutter is the interface that groups both Getting and Putting file
+// payloads.
+type FileGetPutter interface {
+ FileGetter
+ FilePutter
+}
+
+// NewPathFileGetter returns a FileGetter that is for files relative to path
+// relpath.
+func NewPathFileGetter(relpath string) FileGetter {
+ return &pathFileGetter{root: relpath}
+}
+
+type pathFileGetter struct {
+ root string
+}
+
+func (pfg pathFileGetter) Get(filename string) (io.ReadCloser, error) {
+ return os.Open(filepath.Join(pfg.root, filename))
+}
+
+type bufferFileGetPutter struct {
+ files map[string][]byte
+}
+
+func (bfgp bufferFileGetPutter) Get(name string) (io.ReadCloser, error) {
+ if _, ok := bfgp.files[name]; !ok {
+ return nil, errors.New("no such file")
+ }
+ b := bytes.NewBuffer(bfgp.files[name])
+ return &readCloserWrapper{b}, nil
+}
+
+func (bfgp *bufferFileGetPutter) Put(name string, r io.Reader) (int64, []byte, error) {
+ crc := crc64.New(CRCTable)
+ buf := bytes.NewBuffer(nil)
+ cw := io.MultiWriter(crc, buf)
+ i, err := io.Copy(cw, r)
+ if err != nil {
+ return 0, nil, err
+ }
+ bfgp.files[name] = buf.Bytes()
+ return i, crc.Sum(nil), nil
+}
+
+type readCloserWrapper struct {
+ io.Reader
+}
+
+func (w *readCloserWrapper) Close() error { return nil }
+
+// NewBufferFileGetPutter is a simple in-memory FileGetPutter
+//
+// Implication is this is memory intensive...
+// Probably best for testing or light weight cases.
+func NewBufferFileGetPutter() FileGetPutter {
+ return &bufferFileGetPutter{
+ files: map[string][]byte{},
+ }
+}
+
+// NewDiscardFilePutter is a bit bucket FilePutter
+func NewDiscardFilePutter() FilePutter {
+ return &bitBucketFilePutter{}
+}
+
+type bitBucketFilePutter struct {
+}
+
+func (bbfp *bitBucketFilePutter) Put(name string, r io.Reader) (int64, []byte, error) {
+ c := crc64.New(CRCTable)
+ i, err := io.Copy(c, r)
+ return i, c.Sum(nil), err
+}
+
+// CRCTable is the default table used for crc64 sum calculations
+var CRCTable = crc64.MakeTable(crc64.ISO)
diff --git a/vendor/github.com/vbatts/tar-split/tar/storage/packer.go b/vendor/github.com/vbatts/tar-split/tar/storage/packer.go
new file mode 100644
index 0000000..aba6948
--- /dev/null
+++ b/vendor/github.com/vbatts/tar-split/tar/storage/packer.go
@@ -0,0 +1,127 @@
+package storage
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "path/filepath"
+ "unicode/utf8"
+)
+
+// ErrDuplicatePath occurs when a tar archive has more than one entry for the
+// same file path
+var ErrDuplicatePath = errors.New("duplicates of file paths not supported")
+
+// Packer describes the methods to pack Entries to a storage destination
+type Packer interface {
+ // AddEntry packs the Entry and returns its position
+ AddEntry(e Entry) (int, error)
+}
+
+// Unpacker describes the methods to read Entries from a source
+type Unpacker interface {
+ // Next returns the next Entry being unpacked, or error, until io.EOF
+ Next() (*Entry, error)
+}
+
+/* TODO(vbatts) figure out a good model for this
+type PackUnpacker interface {
+ Packer
+ Unpacker
+}
+*/
+
+type jsonUnpacker struct {
+ seen seenNames
+ dec *json.Decoder
+}
+
+func (jup *jsonUnpacker) Next() (*Entry, error) {
+ var e Entry
+ err := jup.dec.Decode(&e)
+ if err != nil {
+ return nil, err
+ }
+
+ // check for dup name
+ if e.Type == FileType {
+ cName := filepath.Clean(e.GetName())
+ if _, ok := jup.seen[cName]; ok {
+ return nil, ErrDuplicatePath
+ }
+ jup.seen[cName] = struct{}{}
+ }
+
+ return &e, err
+}
+
+// NewJSONUnpacker provides an Unpacker that reads Entries (SegmentType and
+// FileType) as a json document.
+//
+// Each Entry read are expected to be delimited by new line.
+func NewJSONUnpacker(r io.Reader) Unpacker {
+ return &jsonUnpacker{
+ dec: json.NewDecoder(r),
+ seen: seenNames{},
+ }
+}
+
+type jsonPacker struct {
+ w io.Writer
+ e *json.Encoder
+ pos int
+ seen seenNames
+}
+
+type seenNames map[string]struct{}
+
+func (jp *jsonPacker) AddEntry(e Entry) (int, error) {
+ // if Name is not valid utf8, switch it to raw first.
+ if e.Name != "" {
+ if !utf8.ValidString(e.Name) {
+ e.NameRaw = []byte(e.Name)
+ e.Name = ""
+ }
+ }
+
+ // check early for dup name
+ if e.Type == FileType {
+ cName := filepath.Clean(e.GetName())
+ if _, ok := jp.seen[cName]; ok {
+ return -1, ErrDuplicatePath
+ }
+ jp.seen[cName] = struct{}{}
+ }
+
+ e.Position = jp.pos
+ err := jp.e.Encode(e)
+ if err != nil {
+ return -1, err
+ }
+
+ // made it this far, increment now
+ jp.pos++
+ return e.Position, nil
+}
+
+// NewJSONPacker provides a Packer that writes each Entry (SegmentType and
+// FileType) as a json document.
+//
+// The Entries are delimited by new line.
+func NewJSONPacker(w io.Writer) Packer {
+ return &jsonPacker{
+ w: w,
+ e: json.NewEncoder(w),
+ seen: seenNames{},
+ }
+}
+
+/*
+TODO(vbatts) perhaps have a more compact packer/unpacker, maybe using msgapck
+(https://github.com/ugorji/go)
+
+
+Even though, since our jsonUnpacker and jsonPacker just take
+io.Reader/io.Writer, then we can get away with passing them a
+gzip.Reader/gzip.Writer
+*/
diff --git a/vendor/github.com/vdemeester/shakers/LICENSE b/vendor/github.com/vdemeester/shakers/LICENSE
new file mode 100644
index 0000000..e9e9e84
--- /dev/null
+++ b/vendor/github.com/vdemeester/shakers/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2015-2016 Vincent Demeester
+
+ 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
+
+ https://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/vdemeester/shakers/README.md b/vendor/github.com/vdemeester/shakers/README.md
new file mode 100644
index 0000000..165bc96
--- /dev/null
+++ b/vendor/github.com/vdemeester/shakers/README.md
@@ -0,0 +1,30 @@
+# Shakers
+🐹 + 🐙 = 😽 [![Circle CI](https://circleci.com/gh/vdemeester/shakers.svg?style=svg)](https://circleci.com/gh/vdemeester/shakers)
+
+A collection of `go-check` Checkers to ease the use of it.
+
+## Building and testing it
+
+You need either [docker](https://github.com/docker/docker), or `go`
+and `glide` in order to build and test shakers.
+
+### Using Docker and Makefile
+
+You need to run the ``test-unit`` target.
+```bash
+$ make test-unit
+docker build -t "shakers-dev:master" .
+# […]
+docker run --rm -it "shakers-dev:master" ./script/make.sh test-unit
+---> Making bundle: test-unit (in .)
++ go test -cover -coverprofile=cover.out .
+ok github.com/vdemeester/shakers 0.015s coverage: 96.0% of statements
+
+Test success
+```
+
+### Using glide and `GO15VENDOREXPERIMENT`
+
+- Get the dependencies with `glide up` (or use `go get` but you have no garantuees over the version of the dependencies)
+- If you're using glide (and not standard `go get`) export `GO15VENDOREXPERIMENT` with `export GO15VENDOREXPERIMENT=1`
+- Run tests with `go test .`
diff --git a/vendor/github.com/vdemeester/shakers/bool.go b/vendor/github.com/vdemeester/shakers/bool.go
new file mode 100644
index 0000000..ab2a993
--- /dev/null
+++ b/vendor/github.com/vdemeester/shakers/bool.go
@@ -0,0 +1,46 @@
+package shakers
+
+import (
+ "github.com/go-check/check"
+)
+
+// True checker verifies the obtained value is true
+//
+// c.Assert(myBool, True)
+//
+var True check.Checker = &boolChecker{
+ &check.CheckerInfo{
+ Name: "True",
+ Params: []string{"obtained"},
+ },
+ true,
+}
+
+// False checker verifies the obtained value is false
+//
+// c.Assert(myBool, False)
+//
+var False check.Checker = &boolChecker{
+ &check.CheckerInfo{
+ Name: "False",
+ Params: []string{"obtained"},
+ },
+ false,
+}
+
+type boolChecker struct {
+ *check.CheckerInfo
+ expected bool
+}
+
+func (checker *boolChecker) Check(params []interface{}, names []string) (bool, string) {
+ return is(checker.expected, params[0])
+}
+
+func is(expected bool, obtained interface{}) (bool, string) {
+ obtainedBool, ok := obtained.(bool)
+ if !ok {
+ return false, "obtained value must be a bool."
+ }
+ return obtainedBool == expected, ""
+}
diff --git a/vendor/github.com/vdemeester/shakers/common.go b/vendor/github.com/vdemeester/shakers/common.go
new file mode 100644
index 0000000..a2245c6
--- /dev/null
+++ b/vendor/github.com/vdemeester/shakers/common.go
@@ -0,0 +1,310 @@
+package shakers
+
+import (
+ "reflect"
+ "time"
+
+ "github.com/go-check/check"
+)
+
+// As a commodity, we bring all check.Checker variables into the current namespace to avoid having
+// to think about check.X versus checker.X.
+var (
+ DeepEquals = check.DeepEquals
+ ErrorMatches = check.ErrorMatches
+ FitsTypeOf = check.FitsTypeOf
+ HasLen = check.HasLen
+ Implements = check.Implements
+ IsNil = check.IsNil
+ Matches = check.Matches
+ Not = check.Not
+ NotNil = check.NotNil
+ PanicMatches = check.PanicMatches
+ Panics = check.Panics
+)
+
+// Equaler is an interface implemented if the type has a Equal method.
+// This is used to compare struct using shakers.Equals.
+type Equaler interface {
+ Equal(Equaler) bool
+}
+
+// Equals checker verifies the obtained value is equal to the specified one.
+// It's is smart in a wait that it supports several *types* (built-in, Equaler,
+// time.Time)
+//
+// c.Assert(myStruct, Equals, aStruct, check.Commentf("bouuuhh"))
+// c.Assert(myTime, Equals, aTime, check.Commentf("bouuuhh"))
+//
+var Equals check.Checker = &equalChecker{
+ &check.CheckerInfo{
+ Name: "Equals",
+ Params: []string{"obtained", "expected"},
+ },
+}
+
+type equalChecker struct {
+ *check.CheckerInfo
+}
+
+func (checker *equalChecker) Check(params []interface{}, names []string) (bool, string) {
+ return isEqual(params[0], params[1])
+}
+
+func isEqual(obtained, expected interface{}) (bool, string) {
+ switch obtained.(type) {
+ case time.Time:
+ return timeEquals(obtained, expected)
+ case Equaler:
+ return equalerEquals(obtained, expected)
+ default:
+ if reflect.TypeOf(obtained) != reflect.TypeOf(expected) {
+ return false, "obtained value and expected value have not the same type."
+ }
+ return obtained == expected, ""
+ }
+}
+
+func equalerEquals(obtained, expected interface{}) (bool, string) {
+ expectedEqualer, ok := expected.(Equaler)
+ if !ok {
+ return false, "expected value must be an Equaler - implementing Equal(Equaler)."
+ }
+ obtainedEqualer, ok := obtained.(Equaler)
+ if !ok {
+ return false, "obtained value must be an Equaler - implementing Equal(Equaler)."
+ }
+ return obtainedEqualer.Equal(expectedEqualer), ""
+}
+
+// GreaterThan checker verifies the obtained value is greater than the specified one.
+// It's is smart in a wait that it supports several *types* (built-in, time.Time)
+//
+// c.Assert(myTime, GreaterThan, aTime, check.Commentf("bouuuhh"))
+// c.Assert(myInt, GreaterThan, 2, check.Commentf("bouuuhh"))
+//
+var GreaterThan check.Checker = &greaterThanChecker{
+ &check.CheckerInfo{
+ Name: "GreaterThan",
+ Params: []string{"obtained", "expected"},
+ },
+}
+
+type greaterThanChecker struct {
+ *check.CheckerInfo
+}
+
+func (checker *greaterThanChecker) Check(params []interface{}, names []string) (bool, string) {
+ return greaterThan(params[0], params[1])
+}
+
+func greaterThan(obtained, expected interface{}) (bool, string) {
+ if _, ok := obtained.(time.Time); ok {
+ return isAfter(obtained, expected)
+ }
+ if reflect.TypeOf(obtained) != reflect.TypeOf(expected) {
+ return false, "obtained value and expected value have not the same type."
+ }
+ switch v := obtained.(type) {
+ case float32:
+ return v > expected.(float32), ""
+ case float64:
+ return v > expected.(float64), ""
+ case int:
+ return v > expected.(int), ""
+ case int8:
+ return v > expected.(int8), ""
+ case int16:
+ return v > expected.(int16), ""
+ case int32:
+ return v > expected.(int32), ""
+ case int64:
+ return v > expected.(int64), ""
+ case uint:
+ return v > expected.(uint), ""
+ case uint8:
+ return v > expected.(uint8), ""
+ case uint16:
+ return v > expected.(uint16), ""
+ case uint32:
+ return v > expected.(uint32), ""
+ case uint64:
+ return v > expected.(uint64), ""
+ default:
+ return false, "obtained value type not supported."
+ }
+}
+
+// GreaterOrEqualThan checker verifies the obtained value is greater or equal than the specified one.
+// It's is smart in a wait that it supports several *types* (built-in, time.Time)
+//
+// c.Assert(myTime, GreaterOrEqualThan, aTime, check.Commentf("bouuuhh"))
+// c.Assert(myInt, GreaterOrEqualThan, 2, check.Commentf("bouuuhh"))
+//
+var GreaterOrEqualThan check.Checker = &greaterOrEqualThanChecker{
+ &check.CheckerInfo{
+ Name: "GreaterOrEqualThan",
+ Params: []string{"obtained", "expected"},
+ },
+}
+
+type greaterOrEqualThanChecker struct {
+ *check.CheckerInfo
+}
+
+func (checker *greaterOrEqualThanChecker) Check(params []interface{}, names []string) (bool, string) {
+ return greaterOrEqualThan(params[0], params[1])
+}
+
+func greaterOrEqualThan(obtained, expected interface{}) (bool, string) {
+ if _, ok := obtained.(time.Time); ok {
+ return isAfter(obtained, expected)
+ }
+ if reflect.TypeOf(obtained) != reflect.TypeOf(expected) {
+ return false, "obtained value and expected value have not the same type."
+ }
+ switch v := obtained.(type) {
+ case float32:
+ return v >= expected.(float32), ""
+ case float64:
+ return v >= expected.(float64), ""
+ case int:
+ return v >= expected.(int), ""
+ case int8:
+ return v >= expected.(int8), ""
+ case int16:
+ return v >= expected.(int16), ""
+ case int32:
+ return v >= expected.(int32), ""
+ case int64:
+ return v >= expected.(int64), ""
+ case uint:
+ return v >= expected.(uint), ""
+ case uint8:
+ return v >= expected.(uint8), ""
+ case uint16:
+ return v >= expected.(uint16), ""
+ case uint32:
+ return v >= expected.(uint32), ""
+ case uint64:
+ return v >= expected.(uint64), ""
+ default:
+ return false, "obtained value type not supported."
+ }
+}
+
+// LessThan checker verifies the obtained value is less than the specified one.
+// It's is smart in a wait that it supports several *types* (built-in, time.Time)
+//
+// c.Assert(myTime, LessThan, aTime, check.Commentf("bouuuhh"))
+// c.Assert(myInt, LessThan, 2, check.Commentf("bouuuhh"))
+//
+var LessThan check.Checker = &lessThanChecker{
+ &check.CheckerInfo{
+ Name: "LessThan",
+ Params: []string{"obtained", "expected"},
+ },
+}
+
+type lessThanChecker struct {
+ *check.CheckerInfo
+}
+
+func (checker *lessThanChecker) Check(params []interface{}, names []string) (bool, string) {
+ return lessThan(params[0], params[1])
+}
+
+func lessThan(obtained, expected interface{}) (bool, string) {
+ if _, ok := obtained.(time.Time); ok {
+ return isBefore(obtained, expected)
+ }
+ if reflect.TypeOf(obtained) != reflect.TypeOf(expected) {
+ return false, "obtained value and expected value have not the same type."
+ }
+ switch v := obtained.(type) {
+ case float32:
+ return v < expected.(float32), ""
+ case float64:
+ return v < expected.(float64), ""
+ case int:
+ return v < expected.(int), ""
+ case int8:
+ return v < expected.(int8), ""
+ case int16:
+ return v < expected.(int16), ""
+ case int32:
+ return v < expected.(int32), ""
+ case int64:
+ return v < expected.(int64), ""
+ case uint:
+ return v < expected.(uint), ""
+ case uint8:
+ return v < expected.(uint8), ""
+ case uint16:
+ return v < expected.(uint16), ""
+ case uint32:
+ return v < expected.(uint32), ""
+ case uint64:
+ return v < expected.(uint64), ""
+ default:
+ return false, "obtained value type not supported."
+ }
+}
+
+// LessOrEqualThan checker verifies the obtained value is less or equal than the specified one.
+// It's is smart in a wait that it supports several *types* (built-in, time.Time)
+//
+// c.Assert(myTime, LessThan, aTime, check.Commentf("bouuuhh"))
+// c.Assert(myInt, LessThan, 2, check.Commentf("bouuuhh"))
+//
+var LessOrEqualThan check.Checker = &lessOrEqualThanChecker{
+ &check.CheckerInfo{
+ Name: "LessOrEqualThan",
+ Params: []string{"obtained", "expected"},
+ },
+}
+
+type lessOrEqualThanChecker struct {
+ *check.CheckerInfo
+}
+
+func (checker *lessOrEqualThanChecker) Check(params []interface{}, names []string) (bool, string) {
+ return lessOrEqualThan(params[0], params[1])
+}
+
+func lessOrEqualThan(obtained, expected interface{}) (bool, string) {
+ if _, ok := obtained.(time.Time); ok {
+ return isBefore(obtained, expected)
+ }
+ if reflect.TypeOf(obtained) != reflect.TypeOf(expected) {
+ return false, "obtained value and expected value have not the same type."
+ }
+ switch v := obtained.(type) {
+ case float32:
+ return v <= expected.(float32), ""
+ case float64:
+ return v <= expected.(float64), ""
+ case int:
+ return v <= expected.(int), ""
+ case int8:
+ return v <= expected.(int8), ""
+ case int16:
+ return v <= expected.(int16), ""
+ case int32:
+ return v <= expected.(int32), ""
+ case int64:
+ return v <= expected.(int64), ""
+ case uint:
+ return v <= expected.(uint), ""
+ case uint8:
+ return v <= expected.(uint8), ""
+ case uint16:
+ return v <= expected.(uint16), ""
+ case uint32:
+ return v <= expected.(uint32), ""
+ case uint64:
+ return v <= expected.(uint64), ""
+ default:
+ return false, "obtained value type not supported."
+ }
+}
diff --git a/vendor/github.com/vdemeester/shakers/string.go b/vendor/github.com/vdemeester/shakers/string.go
new file mode 100644
index 0000000..75ecb10
--- /dev/null
+++ b/vendor/github.com/vdemeester/shakers/string.go
@@ -0,0 +1,168 @@
+// Package shakers provide some checker implementation the go-check.Checker interface.
+package shakers
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/go-check/check"
+)
+
+// Contains checker verifies that obtained value contains a substring.
+var Contains check.Checker = &substringChecker{
+ &check.CheckerInfo{
+ Name: "Contains",
+ Params: []string{"obtained", "substring"},
+ },
+ strings.Contains,
+}
+
+// ContainsAny checker verifies that any Unicode code points in chars
+// are in the obtained string.
+var ContainsAny check.Checker = &substringChecker{
+ &check.CheckerInfo{
+ Name: "ContainsAny",
+ Params: []string{"obtained", "chars"},
+ },
+ strings.ContainsAny,
+}
+
+// HasPrefix checker verifies that obtained value has the specified substring as prefix
+var HasPrefix check.Checker = &substringChecker{
+ &check.CheckerInfo{
+ Name: "HasPrefix",
+ Params: []string{"obtained", "prefix"},
+ },
+ strings.HasPrefix,
+}
+
+// HasSuffix checker verifies that obtained value has the specified substring as prefix
+var HasSuffix check.Checker = &substringChecker{
+ &check.CheckerInfo{
+ Name: "HasSuffix",
+ Params: []string{"obtained", "suffix"},
+ },
+ strings.HasSuffix,
+}
+
+// EqualFold checker verifies that obtained value is, interpreted as UTF-8 strings, are equal under Unicode case-folding.
+var EqualFold check.Checker = &substringChecker{
+ &check.CheckerInfo{
+ Name: "EqualFold",
+ Params: []string{"obtained", "expected"},
+ },
+ strings.EqualFold,
+}
+
+type substringChecker struct {
+ *check.CheckerInfo
+ substringFunction func(string, string) bool
+}
+
+func (checker *substringChecker) Check(params []interface{}, names []string) (bool, string) {
+ obtained := params[0]
+ substring := params[1]
+ substringStr, ok := substring.(string)
+ if !ok {
+ return false, fmt.Sprintf("%s value must be a string.", names[1])
+ }
+ obtainedString, obtainedIsStr := obtained.(string)
+ if !obtainedIsStr {
+ if obtainedWithStringer, obtainedHasStringer := obtained.(fmt.Stringer); obtainedHasStringer {
+ obtainedString, obtainedIsStr = obtainedWithStringer.String(), true
+ }
+ }
+ if obtainedIsStr {
+ return checker.substringFunction(obtainedString, substringStr), ""
+ }
+ return false, "obtained value is not a string and has no .String()."
+}
+
+// IndexAny checker verifies that the index of the first instance of any Unicode code point from chars in the obtained value is equal to expected
+var IndexAny check.Checker = &substringCountChecker{
+ &check.CheckerInfo{
+ Name: "IndexAny",
+ Params: []string{"obtained", "chars", "expected"},
+ },
+ strings.IndexAny,
+}
+
+// Index checker verifies that the index of the first instance of sep in the obtained value is equal to expected
+var Index check.Checker = &substringCountChecker{
+ &check.CheckerInfo{
+ Name: "Index",
+ Params: []string{"obtained", "sep", "expected"},
+ },
+ strings.Index,
+}
+
+// Count checker verifies that obtained value has the specified number of non-overlapping instances of sep
+var Count check.Checker = &substringCountChecker{
+ &check.CheckerInfo{
+ Name: "Count",
+ Params: []string{"obtained", "sep", "expected"},
+ },
+ strings.Count,
+}
+
+type substringCountChecker struct {
+ *check.CheckerInfo
+ substringFunction func(string, string) int
+}
+
+func (checker *substringCountChecker) Check(params []interface{}, names []string) (bool, string) {
+ obtained := params[0]
+ substring := params[1]
+ expected := params[2]
+ substringStr, ok := substring.(string)
+ if !ok {
+ return false, fmt.Sprintf("%s value must be a string.", names[1])
+ }
+ obtainedString, obtainedIsStr := obtained.(string)
+ if !obtainedIsStr {
+ if obtainedWithStringer, obtainedHasStringer := obtained.(fmt.Stringer); obtainedHasStringer {
+ obtainedString, obtainedIsStr = obtainedWithStringer.String(), true
+ }
+ }
+ if obtainedIsStr {
+ return checker.substringFunction(obtainedString, substringStr) == expected, ""
+ }
+ return false, "obtained value is not a string and has no .String()."
+}
+
+// IsLower checker verifies that the obtained value is in lower case
+var IsLower check.Checker = &stringTransformChecker{
+ &check.CheckerInfo{
+ Name: "IsLower",
+ Params: []string{"obtained"},
+ },
+ strings.ToLower,
+}
+
+// IsUpper checker verifies that the obtained value is in lower case
+var IsUpper check.Checker = &stringTransformChecker{
+ &check.CheckerInfo{
+ Name: "IsUpper",
+ Params: []string{"obtained"},
+ },
+ strings.ToUpper,
+}
+
+type stringTransformChecker struct {
+ *check.CheckerInfo
+ stringFunction func(string) string
+}
+
+func (checker *stringTransformChecker) Check(params []interface{}, names []string) (bool, string) {
+ obtained := params[0]
+ obtainedString, obtainedIsStr := obtained.(string)
+ if !obtainedIsStr {
+ if obtainedWithStringer, obtainedHasStringer := obtained.(fmt.Stringer); obtainedHasStringer {
+ obtainedString, obtainedIsStr = obtainedWithStringer.String(), true
+ }
+ }
+ if obtainedIsStr {
+ return checker.stringFunction(obtainedString) == obtainedString, ""
+ }
+ return false, "obtained value is not a string and has no .String()."
+}
diff --git a/vendor/github.com/vdemeester/shakers/time.go b/vendor/github.com/vdemeester/shakers/time.go
new file mode 100644
index 0000000..0da8d00
--- /dev/null
+++ b/vendor/github.com/vdemeester/shakers/time.go
@@ -0,0 +1,234 @@
+package shakers
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/go-check/check"
+)
+
+// Default format when parsing (in addition to RFC and default time formats..)
+const shortForm = "2006-01-02"
+
+// IsBefore checker verifies the specified value is before the specified time.
+// It is exclusive.
+//
+// c.Assert(myTime, IsBefore, theTime, check.Commentf("bouuuhhh"))
+//
+var IsBefore check.Checker = &isBeforeChecker{
+ &check.CheckerInfo{
+ Name: "IsBefore",
+ Params: []string{"obtained", "expected"},
+ },
+}
+
+type isBeforeChecker struct {
+ *check.CheckerInfo
+}
+
+func (checker *isBeforeChecker) Check(params []interface{}, names []string) (bool, string) {
+ return isBefore(params[0], params[1])
+}
+
+func isBefore(value, t interface{}) (bool, string) {
+ tTime, ok := parseTime(t)
+ if !ok {
+ return false, "expected must be a Time struct, or parseable."
+ }
+ valueTime, valueIsTime := parseTime(value)
+ if valueIsTime {
+ return valueTime.Before(tTime), ""
+ }
+ return false, "obtained value is not a time.Time struct or parseable as a time."
+}
+
+// IsAfter checker verifies the specified value is before the specified time.
+// It is exclusive.
+//
+// c.Assert(myTime, IsAfter, theTime, check.Commentf("bouuuhhh"))
+//
+var IsAfter check.Checker = &isAfterChecker{
+ &check.CheckerInfo{
+ Name: "IsAfter",
+ Params: []string{"obtained", "expected"},
+ },
+}
+
+type isAfterChecker struct {
+ *check.CheckerInfo
+}
+
+func (checker *isAfterChecker) Check(params []interface{}, names []string) (bool, string) {
+ return isAfter(params[0], params[1])
+}
+
+func isAfter(value, t interface{}) (bool, string) {
+ tTime, ok := parseTime(t)
+ if !ok {
+ return false, "expected must be a Time struct, or parseable."
+ }
+ valueTime, valueIsTime := parseTime(value)
+ if valueIsTime {
+ return valueTime.After(tTime), ""
+ }
+ return false, "obtained value is not a time.Time struct or parseable as a time."
+}
+
+// IsBetween checker verifies the specified time is between the specified start
+// and end. It's exclusive so if the specified time is at the tip of the interval.
+//
+// c.Assert(myTime, IsBetween, startTime, endTime, check.Commentf("bouuuhhh"))
+//
+var IsBetween check.Checker = &isBetweenChecker{
+ &check.CheckerInfo{
+ Name: "IsBetween",
+ Params: []string{"obtained", "start", "end"},
+ },
+}
+
+type isBetweenChecker struct {
+ *check.CheckerInfo
+}
+
+func (checker *isBetweenChecker) Check(params []interface{}, names []string) (bool, string) {
+ return isBetween(params[0], params[1], params[2])
+}
+
+func isBetween(value, start, end interface{}) (bool, string) {
+ startTime, ok := parseTime(start)
+ if !ok {
+ return false, "start must be a Time struct, or parseable."
+ }
+ endTime, ok := parseTime(end)
+ if !ok {
+ return false, "end must be a Time struct, or parseable."
+ }
+ valueTime, valueIsTime := parseTime(value)
+ if valueIsTime {
+ return valueTime.After(startTime) && valueTime.Before(endTime), ""
+ }
+ return false, "obtained value is not a time.Time struct or parseable as a time."
+}
+
+// TimeEquals checker verifies the specified time is the equal to the expected
+// time.
+//
+// c.Assert(myTime, TimeEquals, expected, check.Commentf("bouhhh"))
+//
+// It's possible to ignore some part of the time (like hours, minutes, etc..) using
+// the TimeIgnore checker with it.
+//
+// c.Assert(myTime, TimeIgnore(TimeEquals, time.Hour), expected, check.Commentf("... bouh.."))
+//
+var TimeEquals check.Checker = &timeEqualsChecker{
+ &check.CheckerInfo{
+ Name: "TimeEquals",
+ Params: []string{"obtained", "expected"},
+ },
+}
+
+type timeEqualsChecker struct {
+ *check.CheckerInfo
+}
+
+func (checker *timeEqualsChecker) Check(params []interface{}, names []string) (bool, string) {
+ return timeEquals(params[0], params[1])
+}
+
+func timeEquals(obtained, expected interface{}) (bool, string) {
+ expectedTime, ok := parseTime(expected)
+ if !ok {
+ return false, "expected must be a Time struct, or parseable."
+ }
+ valueTime, valueIsTime := parseTime(obtained)
+ if valueIsTime {
+ return valueTime.Equal(expectedTime), ""
+ }
+ return false, "obtained value is not a time.Time struct or parseable as a time."
+}
+
+// TimeIgnore checker will ignore some part of the time on the encapsulated checker.
+//
+// c.Assert(myTime, TimeIgnore(IsBetween, time.Second), start, end)
+//
+// FIXME use interface{} for ignore (to enable "Month", ..
+func TimeIgnore(checker check.Checker, ignore time.Duration) check.Checker {
+ return &timeIgnoreChecker{
+ sub: checker,
+ ignore: ignore,
+ }
+}
+
+type timeIgnoreChecker struct {
+ sub check.Checker
+ ignore time.Duration
+}
+
+func (checker *timeIgnoreChecker) Info() *check.CheckerInfo {
+ info := *checker.sub.Info()
+ info.Name = fmt.Sprintf("TimeIgnore(%s, %v)", info.Name, checker.ignore)
+ return &info
+}
+
+func (checker *timeIgnoreChecker) Check(params []interface{}, names []string) (bool, string) {
+ // Naive implementation : all params are supposed to be date
+ mParams := make([]interface{}, len(params))
+ for index, param := range params {
+ paramTime, ok := parseTime(param)
+ if !ok {
+ return false, fmt.Sprintf("%s must be a Time struct, or parseable.", names[index])
+ }
+ year := paramTime.Year()
+ month := paramTime.Month()
+ day := paramTime.Day()
+ hour := paramTime.Hour()
+ min := paramTime.Minute()
+ sec := paramTime.Second()
+ nsec := paramTime.Nanosecond()
+ location := paramTime.Location()
+ switch checker.ignore {
+ case time.Hour:
+ hour = 0
+ fallthrough
+ case time.Minute:
+ min = 0
+ fallthrough
+ case time.Second:
+ sec = 0
+ fallthrough
+ case time.Millisecond:
+ fallthrough
+ case time.Microsecond:
+ fallthrough
+ case time.Nanosecond:
+ nsec = 0
+ }
+ mParams[index] = time.Date(year, month, day, hour, min, sec, nsec, location)
+ }
+ return checker.sub.Check(mParams, names)
+}
+
+func parseTime(datetime interface{}) (time.Time, bool) {
+ switch datetime.(type) {
+ case time.Time:
+ return datetime.(time.Time), true
+ case string:
+ return parseTimeAsString(datetime.(string))
+ default:
+ if datetimeWithStr, ok := datetime.(fmt.Stringer); ok {
+ return parseTimeAsString(datetimeWithStr.String())
+ }
+ return time.Time{}, false
+ }
+}
+
+func parseTimeAsString(timeAsStr string) (time.Time, bool) {
+ forms := []string{shortForm, time.RFC3339, time.RFC3339Nano, time.RFC822, time.RFC822Z}
+ for _, form := range forms {
+ datetime, err := time.Parse(form, timeAsStr)
+ if err == nil {
+ return datetime, true
+ }
+ }
+ return time.Time{}, false
+}
diff --git a/vendor/github.com/vishvananda/netlink/LICENSE b/vendor/github.com/vishvananda/netlink/LICENSE
new file mode 100644
index 0000000..9f64db8
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/LICENSE
@@ -0,0 +1,192 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2014 Vishvananda Ishaya.
+ Copyright 2014 Docker, Inc.
+
+ 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/vishvananda/netlink/README.md b/vendor/github.com/vishvananda/netlink/README.md
new file mode 100644
index 0000000..2367fae
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/README.md
@@ -0,0 +1,89 @@
+# netlink - netlink library for go #
+
+[![Build Status](https://travis-ci.org/vishvananda/netlink.png?branch=master)](https://travis-ci.org/vishvananda/netlink) [![GoDoc](https://godoc.org/github.com/vishvananda/netlink?status.svg)](https://godoc.org/github.com/vishvananda/netlink)
+
+The netlink package provides a simple netlink library for go. Netlink
+is the interface a user-space program in linux uses to communicate with
+the kernel. It can be used to add and remove interfaces, set ip addresses
+and routes, and configure ipsec. Netlink communication requires elevated
+privileges, so in most cases this code needs to be run as root. Since
+low-level netlink messages are inscrutable at best, the library attempts
+to provide an api that is loosely modeled on the CLI provided by iproute2.
+Actions like `ip link add` will be accomplished via a similarly named
+function like AddLink(). This library began its life as a fork of the
+netlink functionality in
+[docker/libcontainer](https://github.com/docker/libcontainer) but was
+heavily rewritten to improve testability, performance, and to add new
+functionality like ipsec xfrm handling.
+
+## Local Build and Test ##
+
+You can use go get command:
+
+ go get github.com/vishvananda/netlink
+
+Testing dependencies:
+
+ go get github.com/vishvananda/netns
+
+Testing (requires root):
+
+ sudo -E go test github.com/vishvananda/netlink
+
+## Examples ##
+
+Add a new bridge and add eth1 into it:
+
+```go
+package main
+
+import (
+ "net"
+ "github.com/vishvananda/netlink"
+)
+
+func main() {
+ la := netlink.NewLinkAttrs()
+ la.Name = "foo"
+ mybridge := &netlink.Bridge{la}}
+ _ := netlink.LinkAdd(mybridge)
+ eth1, _ := netlink.LinkByName("eth1")
+ netlink.LinkSetMaster(eth1, mybridge)
+}
+
+```
+Note `NewLinkAttrs` constructor, it sets default values in structure. For now
+it sets only `TxQLen` to `-1`, so kernel will set default by itself. If you're
+using simple initialization(`LinkAttrs{Name: "foo"}`) `TxQLen` will be set to
+`0` unless you specify it like `LinkAttrs{Name: "foo", TxQLen: 1000}`.
+
+Add a new ip address to loopback:
+
+```go
+package main
+
+import (
+ "net"
+ "github.com/vishvananda/netlink"
+)
+
+func main() {
+ lo, _ := netlink.LinkByName("lo")
+ addr, _ := netlink.ParseAddr("169.254.169.254/32")
+ netlink.AddrAdd(lo, addr)
+}
+
+```
+
+## Future Work ##
+
+Many pieces of netlink are not yet fully supported in the high-level
+interface. Aspects of virtually all of the high-level objects don't exist.
+Many of the underlying primitives are there, so its a matter of putting
+the right fields into the high-level objects and making sure that they
+are serialized and deserialized correctly in the Add and List methods.
+
+There are also a few pieces of low level netlink functionality that still
+need to be implemented. Routing rules are not in place and some of the
+more advanced link types. Hopefully there is decent structure and testing
+in place to make these fairly straightforward to add.
diff --git a/vendor/github.com/vishvananda/netlink/addr.go b/vendor/github.com/vishvananda/netlink/addr.go
new file mode 100644
index 0000000..f08c956
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/addr.go
@@ -0,0 +1,56 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+ "strings"
+)
+
+// Addr represents an IP address from netlink. Netlink ip addresses
+// include a mask, so it stores the address as a net.IPNet.
+type Addr struct {
+ *net.IPNet
+ Label string
+ Flags int
+ Scope int
+ Peer *net.IPNet
+ Broadcast net.IP
+ PreferedLft int
+ ValidLft int
+}
+
+// String returns $ip/$netmask $label
+func (a Addr) String() string {
+ return strings.TrimSpace(fmt.Sprintf("%s %s", a.IPNet, a.Label))
+}
+
+// ParseAddr parses the string representation of an address in the
+// form $ip/$netmask $label. The label portion is optional
+func ParseAddr(s string) (*Addr, error) {
+ label := ""
+ parts := strings.Split(s, " ")
+ if len(parts) > 1 {
+ s = parts[0]
+ label = parts[1]
+ }
+ m, err := ParseIPNet(s)
+ if err != nil {
+ return nil, err
+ }
+ return &Addr{IPNet: m, Label: label}, nil
+}
+
+// Equal returns true if both Addrs have the same net.IPNet value.
+func (a Addr) Equal(x Addr) bool {
+ sizea, _ := a.Mask.Size()
+ sizeb, _ := x.Mask.Size()
+ // ignore label for comparison
+ return a.IP.Equal(x.IP) && sizea == sizeb
+}
+
+func (a Addr) PeerEqual(x Addr) bool {
+ sizea, _ := a.Peer.Mask.Size()
+ sizeb, _ := x.Peer.Mask.Size()
+ // ignore label for comparison
+ return a.Peer.IP.Equal(x.Peer.IP) && sizea == sizeb
+}
diff --git a/vendor/github.com/vishvananda/netlink/addr_linux.go b/vendor/github.com/vishvananda/netlink/addr_linux.go
new file mode 100644
index 0000000..f33242a
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/addr_linux.go
@@ -0,0 +1,288 @@
+package netlink
+
+import (
+ "fmt"
+ "log"
+ "net"
+ "strings"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+ "github.com/vishvananda/netns"
+)
+
+// IFA_FLAGS is a u32 attribute.
+const IFA_FLAGS = 0x8
+
+// AddrAdd will add an IP address to a link device.
+// Equivalent to: `ip addr add $addr dev $link`
+func AddrAdd(link Link, addr *Addr) error {
+ return pkgHandle.AddrAdd(link, addr)
+}
+
+// AddrAdd will add an IP address to a link device.
+// Equivalent to: `ip addr add $addr dev $link`
+func (h *Handle) AddrAdd(link Link, addr *Addr) error {
+ req := h.newNetlinkRequest(syscall.RTM_NEWADDR, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+ return h.addrHandle(link, addr, req)
+}
+
+// AddrReplace will replace (or, if not present, add) an IP address on a link device.
+// Equivalent to: `ip addr replace $addr dev $link`
+func AddrReplace(link Link, addr *Addr) error {
+ return pkgHandle.AddrReplace(link, addr)
+}
+
+// AddrReplace will replace (or, if not present, add) an IP address on a link device.
+// Equivalent to: `ip addr replace $addr dev $link`
+func (h *Handle) AddrReplace(link Link, addr *Addr) error {
+ req := h.newNetlinkRequest(syscall.RTM_NEWADDR, syscall.NLM_F_CREATE|syscall.NLM_F_REPLACE|syscall.NLM_F_ACK)
+ return h.addrHandle(link, addr, req)
+}
+
+// AddrDel will delete an IP address from a link device.
+// Equivalent to: `ip addr del $addr dev $link`
+func AddrDel(link Link, addr *Addr) error {
+ return pkgHandle.AddrDel(link, addr)
+}
+
+// AddrDel will delete an IP address from a link device.
+// Equivalent to: `ip addr del $addr dev $link`
+func (h *Handle) AddrDel(link Link, addr *Addr) error {
+ req := h.newNetlinkRequest(syscall.RTM_DELADDR, syscall.NLM_F_ACK)
+ return h.addrHandle(link, addr, req)
+}
+
+func (h *Handle) addrHandle(link Link, addr *Addr, req *nl.NetlinkRequest) error {
+ base := link.Attrs()
+ if addr.Label != "" && !strings.HasPrefix(addr.Label, base.Name) {
+ return fmt.Errorf("label must begin with interface name")
+ }
+ h.ensureIndex(base)
+
+ family := nl.GetIPFamily(addr.IP)
+
+ msg := nl.NewIfAddrmsg(family)
+ msg.Index = uint32(base.Index)
+ msg.Scope = uint8(addr.Scope)
+ prefixlen, _ := addr.Mask.Size()
+ msg.Prefixlen = uint8(prefixlen)
+ req.AddData(msg)
+
+ var localAddrData []byte
+ if family == FAMILY_V4 {
+ localAddrData = addr.IP.To4()
+ } else {
+ localAddrData = addr.IP.To16()
+ }
+
+ localData := nl.NewRtAttr(syscall.IFA_LOCAL, localAddrData)
+ req.AddData(localData)
+ var peerAddrData []byte
+ if addr.Peer != nil {
+ if family == FAMILY_V4 {
+ peerAddrData = addr.Peer.IP.To4()
+ } else {
+ peerAddrData = addr.Peer.IP.To16()
+ }
+ } else {
+ peerAddrData = localAddrData
+ }
+
+ addressData := nl.NewRtAttr(syscall.IFA_ADDRESS, peerAddrData)
+ req.AddData(addressData)
+
+ if addr.Flags != 0 {
+ if addr.Flags <= 0xff {
+ msg.IfAddrmsg.Flags = uint8(addr.Flags)
+ } else {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(addr.Flags))
+ flagsData := nl.NewRtAttr(IFA_FLAGS, b)
+ req.AddData(flagsData)
+ }
+ }
+
+ if addr.Broadcast != nil {
+ req.AddData(nl.NewRtAttr(syscall.IFA_BROADCAST, addr.Broadcast))
+ }
+
+ if addr.Label != "" {
+ labelData := nl.NewRtAttr(syscall.IFA_LABEL, nl.ZeroTerminated(addr.Label))
+ req.AddData(labelData)
+ }
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// AddrList gets a list of IP addresses in the system.
+// Equivalent to: `ip addr show`.
+// The list can be filtered by link and ip family.
+func AddrList(link Link, family int) ([]Addr, error) {
+ return pkgHandle.AddrList(link, family)
+}
+
+// AddrList gets a list of IP addresses in the system.
+// Equivalent to: `ip addr show`.
+// The list can be filtered by link and ip family.
+func (h *Handle) AddrList(link Link, family int) ([]Addr, error) {
+ req := h.newNetlinkRequest(syscall.RTM_GETADDR, syscall.NLM_F_DUMP)
+ msg := nl.NewIfInfomsg(family)
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWADDR)
+ if err != nil {
+ return nil, err
+ }
+
+ indexFilter := 0
+ if link != nil {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ indexFilter = base.Index
+ }
+
+ var res []Addr
+ for _, m := range msgs {
+ addr, msgFamily, ifindex, err := parseAddr(m)
+ if err != nil {
+ return res, err
+ }
+
+ if link != nil && ifindex != indexFilter {
+ // Ignore messages from other interfaces
+ continue
+ }
+
+ if family != FAMILY_ALL && msgFamily != family {
+ continue
+ }
+
+ res = append(res, addr)
+ }
+
+ return res, nil
+}
+
+func parseAddr(m []byte) (addr Addr, family, index int, err error) {
+ msg := nl.DeserializeIfAddrmsg(m)
+
+ family = -1
+ index = -1
+
+ attrs, err1 := nl.ParseRouteAttr(m[msg.Len():])
+ if err1 != nil {
+ err = err1
+ return
+ }
+
+ family = int(msg.Family)
+ index = int(msg.Index)
+
+ var local, dst *net.IPNet
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case syscall.IFA_ADDRESS:
+ dst = &net.IPNet{
+ IP: attr.Value,
+ Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)),
+ }
+ addr.Peer = dst
+ case syscall.IFA_LOCAL:
+ local = &net.IPNet{
+ IP: attr.Value,
+ Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)),
+ }
+ addr.IPNet = local
+ case syscall.IFA_BROADCAST:
+ addr.Broadcast = attr.Value
+ case syscall.IFA_LABEL:
+ addr.Label = string(attr.Value[:len(attr.Value)-1])
+ case IFA_FLAGS:
+ addr.Flags = int(native.Uint32(attr.Value[0:4]))
+ case nl.IFA_CACHEINFO:
+ ci := nl.DeserializeIfaCacheInfo(attr.Value)
+ addr.PreferedLft = int(ci.IfaPrefered)
+ addr.ValidLft = int(ci.IfaValid)
+ }
+ }
+
+ // IFA_LOCAL should be there but if not, fall back to IFA_ADDRESS
+ if local != nil {
+ addr.IPNet = local
+ } else {
+ addr.IPNet = dst
+ }
+ addr.Scope = int(msg.Scope)
+
+ return
+}
+
+type AddrUpdate struct {
+ LinkAddress net.IPNet
+ LinkIndex int
+ Flags int
+ Scope int
+ PreferedLft int
+ ValidLft int
+ NewAddr bool // true=added false=deleted
+}
+
+// AddrSubscribe takes a chan down which notifications will be sent
+// when addresses change. Close the 'done' chan to stop subscription.
+func AddrSubscribe(ch chan<- AddrUpdate, done <-chan struct{}) error {
+ return addrSubscribe(netns.None(), netns.None(), ch, done)
+}
+
+// AddrSubscribeAt works like AddrSubscribe plus it allows the caller
+// to choose the network namespace in which to subscribe (ns).
+func AddrSubscribeAt(ns netns.NsHandle, ch chan<- AddrUpdate, done <-chan struct{}) error {
+ return addrSubscribe(ns, netns.None(), ch, done)
+}
+
+func addrSubscribe(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-chan struct{}) error {
+ s, err := nl.SubscribeAt(newNs, curNs, syscall.NETLINK_ROUTE, syscall.RTNLGRP_IPV4_IFADDR, syscall.RTNLGRP_IPV6_IFADDR)
+ if err != nil {
+ return err
+ }
+ if done != nil {
+ go func() {
+ <-done
+ s.Close()
+ }()
+ }
+ go func() {
+ defer close(ch)
+ for {
+ msgs, err := s.Receive()
+ if err != nil {
+ log.Printf("netlink.AddrSubscribe: Receive() error: %v", err)
+ return
+ }
+ for _, m := range msgs {
+ msgType := m.Header.Type
+ if msgType != syscall.RTM_NEWADDR && msgType != syscall.RTM_DELADDR {
+ log.Printf("netlink.AddrSubscribe: bad message type: %d", msgType)
+ continue
+ }
+
+ addr, _, ifindex, err := parseAddr(m.Data)
+ if err != nil {
+ log.Printf("netlink.AddrSubscribe: could not parse address: %v", err)
+ continue
+ }
+
+ ch <- AddrUpdate{LinkAddress: *addr.IPNet,
+ LinkIndex: ifindex,
+ NewAddr: msgType == syscall.RTM_NEWADDR,
+ Flags: addr.Flags,
+ Scope: addr.Scope,
+ PreferedLft: addr.PreferedLft,
+ ValidLft: addr.ValidLft}
+ }
+ }
+ }()
+
+ return nil
+}
diff --git a/vendor/github.com/vishvananda/netlink/bpf_linux.go b/vendor/github.com/vishvananda/netlink/bpf_linux.go
new file mode 100644
index 0000000..5337439
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/bpf_linux.go
@@ -0,0 +1,62 @@
+package netlink
+
+/*
+#include <asm/types.h>
+#include <asm/unistd.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <unistd.h>
+
+static int load_simple_bpf(int prog_type, int ret) {
+#ifdef __NR_bpf
+ // { return ret; }
+ __u64 __attribute__((aligned(8))) insns[] = {
+ 0x00000000000000b7ull | ((__u64)ret<<32),
+ 0x0000000000000095ull,
+ };
+ __u8 __attribute__((aligned(8))) license[] = "ASL2";
+ // Copied from a header file since libc is notoriously slow to update.
+ // The call will succeed or fail and that will be our indication on
+ // whether or not it is supported.
+ struct {
+ __u32 prog_type;
+ __u32 insn_cnt;
+ __u64 insns;
+ __u64 license;
+ __u32 log_level;
+ __u32 log_size;
+ __u64 log_buf;
+ __u32 kern_version;
+ } __attribute__((aligned(8))) attr = {
+ .prog_type = prog_type,
+ .insn_cnt = 2,
+ .insns = (uintptr_t)&insns,
+ .license = (uintptr_t)&license,
+ };
+ return syscall(__NR_bpf, 5, &attr, sizeof(attr));
+#else
+ errno = EINVAL;
+ return -1;
+#endif
+}
+*/
+import "C"
+
+type BpfProgType C.int
+
+const (
+ BPF_PROG_TYPE_UNSPEC BpfProgType = iota
+ BPF_PROG_TYPE_SOCKET_FILTER
+ BPF_PROG_TYPE_KPROBE
+ BPF_PROG_TYPE_SCHED_CLS
+ BPF_PROG_TYPE_SCHED_ACT
+ BPF_PROG_TYPE_TRACEPOINT
+ BPF_PROG_TYPE_XDP
+)
+
+// loadSimpleBpf loads a trivial bpf program for testing purposes
+func loadSimpleBpf(progType BpfProgType, ret int) (int, error) {
+ fd, err := C.load_simple_bpf(C.int(progType), C.int(ret))
+ return int(fd), err
+}
diff --git a/vendor/github.com/vishvananda/netlink/class.go b/vendor/github.com/vishvananda/netlink/class.go
new file mode 100644
index 0000000..8ee13af
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/class.go
@@ -0,0 +1,78 @@
+package netlink
+
+import (
+ "fmt"
+)
+
+type Class interface {
+ Attrs() *ClassAttrs
+ Type() string
+}
+
+// ClassAttrs represents a netlink class. A filter is associated with a link,
+// has a handle and a parent. The root filter of a device should have a
+// parent == HANDLE_ROOT.
+type ClassAttrs struct {
+ LinkIndex int
+ Handle uint32
+ Parent uint32
+ Leaf uint32
+}
+
+func (q ClassAttrs) String() string {
+ return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Leaf: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Leaf)
+}
+
+type HtbClassAttrs struct {
+ // TODO handle all attributes
+ Rate uint64
+ Ceil uint64
+ Buffer uint32
+ Cbuffer uint32
+ Quantum uint32
+ Level uint32
+ Prio uint32
+}
+
+func (q HtbClassAttrs) String() string {
+ return fmt.Sprintf("{Rate: %d, Ceil: %d, Buffer: %d, Cbuffer: %d}", q.Rate, q.Ceil, q.Buffer, q.Cbuffer)
+}
+
+// HtbClass represents an Htb class
+type HtbClass struct {
+ ClassAttrs
+ Rate uint64
+ Ceil uint64
+ Buffer uint32
+ Cbuffer uint32
+ Quantum uint32
+ Level uint32
+ Prio uint32
+}
+
+func (q HtbClass) String() string {
+ return fmt.Sprintf("{Rate: %d, Ceil: %d, Buffer: %d, Cbuffer: %d}", q.Rate, q.Ceil, q.Buffer, q.Cbuffer)
+}
+
+func (q *HtbClass) Attrs() *ClassAttrs {
+ return &q.ClassAttrs
+}
+
+func (q *HtbClass) Type() string {
+ return "htb"
+}
+
+// GenericClass classes represent types that are not currently understood
+// by this netlink library.
+type GenericClass struct {
+ ClassAttrs
+ ClassType string
+}
+
+func (class *GenericClass) Attrs() *ClassAttrs {
+ return &class.ClassAttrs
+}
+
+func (class *GenericClass) Type() string {
+ return class.ClassType
+}
diff --git a/vendor/github.com/vishvananda/netlink/class_linux.go b/vendor/github.com/vishvananda/netlink/class_linux.go
new file mode 100644
index 0000000..91cd388
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/class_linux.go
@@ -0,0 +1,254 @@
+package netlink
+
+import (
+ "errors"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// NOTE: function is in here because it uses other linux functions
+func NewHtbClass(attrs ClassAttrs, cattrs HtbClassAttrs) *HtbClass {
+ mtu := 1600
+ rate := cattrs.Rate / 8
+ ceil := cattrs.Ceil / 8
+ buffer := cattrs.Buffer
+ cbuffer := cattrs.Cbuffer
+
+ if ceil == 0 {
+ ceil = rate
+ }
+
+ if buffer == 0 {
+ buffer = uint32(float64(rate)/Hz() + float64(mtu))
+ }
+ buffer = uint32(Xmittime(rate, buffer))
+
+ if cbuffer == 0 {
+ cbuffer = uint32(float64(ceil)/Hz() + float64(mtu))
+ }
+ cbuffer = uint32(Xmittime(ceil, cbuffer))
+
+ return &HtbClass{
+ ClassAttrs: attrs,
+ Rate: rate,
+ Ceil: ceil,
+ Buffer: buffer,
+ Cbuffer: cbuffer,
+ Quantum: 10,
+ Level: 0,
+ Prio: 0,
+ }
+}
+
+// ClassDel will delete a class from the system.
+// Equivalent to: `tc class del $class`
+func ClassDel(class Class) error {
+ return pkgHandle.ClassDel(class)
+}
+
+// ClassDel will delete a class from the system.
+// Equivalent to: `tc class del $class`
+func (h *Handle) ClassDel(class Class) error {
+ return h.classModify(syscall.RTM_DELTCLASS, 0, class)
+}
+
+// ClassChange will change a class in place
+// Equivalent to: `tc class change $class`
+// The parent and handle MUST NOT be changed.
+func ClassChange(class Class) error {
+ return pkgHandle.ClassChange(class)
+}
+
+// ClassChange will change a class in place
+// Equivalent to: `tc class change $class`
+// The parent and handle MUST NOT be changed.
+func (h *Handle) ClassChange(class Class) error {
+ return h.classModify(syscall.RTM_NEWTCLASS, 0, class)
+}
+
+// ClassReplace will replace a class to the system.
+// quivalent to: `tc class replace $class`
+// The handle MAY be changed.
+// If a class already exist with this parent/handle pair, the class is changed.
+// If a class does not already exist with this parent/handle, a new class is created.
+func ClassReplace(class Class) error {
+ return pkgHandle.ClassReplace(class)
+}
+
+// ClassReplace will replace a class to the system.
+// quivalent to: `tc class replace $class`
+// The handle MAY be changed.
+// If a class already exist with this parent/handle pair, the class is changed.
+// If a class does not already exist with this parent/handle, a new class is created.
+func (h *Handle) ClassReplace(class Class) error {
+ return h.classModify(syscall.RTM_NEWTCLASS, syscall.NLM_F_CREATE, class)
+}
+
+// ClassAdd will add a class to the system.
+// Equivalent to: `tc class add $class`
+func ClassAdd(class Class) error {
+ return pkgHandle.ClassAdd(class)
+}
+
+// ClassAdd will add a class to the system.
+// Equivalent to: `tc class add $class`
+func (h *Handle) ClassAdd(class Class) error {
+ return h.classModify(
+ syscall.RTM_NEWTCLASS,
+ syscall.NLM_F_CREATE|syscall.NLM_F_EXCL,
+ class,
+ )
+}
+
+func (h *Handle) classModify(cmd, flags int, class Class) error {
+ req := h.newNetlinkRequest(cmd, flags|syscall.NLM_F_ACK)
+ base := class.Attrs()
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Ifindex: int32(base.LinkIndex),
+ Handle: base.Handle,
+ Parent: base.Parent,
+ }
+ req.AddData(msg)
+
+ if cmd != syscall.RTM_DELTCLASS {
+ if err := classPayload(req, class); err != nil {
+ return err
+ }
+ }
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+func classPayload(req *nl.NetlinkRequest, class Class) error {
+ req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(class.Type())))
+
+ options := nl.NewRtAttr(nl.TCA_OPTIONS, nil)
+ if htb, ok := class.(*HtbClass); ok {
+ opt := nl.TcHtbCopt{}
+ opt.Buffer = htb.Buffer
+ opt.Cbuffer = htb.Cbuffer
+ opt.Quantum = htb.Quantum
+ opt.Level = htb.Level
+ opt.Prio = htb.Prio
+ // TODO: Handle Debug properly. For now default to 0
+ /* Calculate {R,C}Tab and set Rate and Ceil */
+ cellLog := -1
+ ccellLog := -1
+ linklayer := nl.LINKLAYER_ETHERNET
+ mtu := 1600
+ var rtab [256]uint32
+ var ctab [256]uint32
+ tcrate := nl.TcRateSpec{Rate: uint32(htb.Rate)}
+ if CalcRtable(&tcrate, rtab, cellLog, uint32(mtu), linklayer) < 0 {
+ return errors.New("HTB: failed to calculate rate table")
+ }
+ opt.Rate = tcrate
+ tcceil := nl.TcRateSpec{Rate: uint32(htb.Ceil)}
+ if CalcRtable(&tcceil, ctab, ccellLog, uint32(mtu), linklayer) < 0 {
+ return errors.New("HTB: failed to calculate ceil rate table")
+ }
+ opt.Ceil = tcceil
+ nl.NewRtAttrChild(options, nl.TCA_HTB_PARMS, opt.Serialize())
+ nl.NewRtAttrChild(options, nl.TCA_HTB_RTAB, SerializeRtab(rtab))
+ nl.NewRtAttrChild(options, nl.TCA_HTB_CTAB, SerializeRtab(ctab))
+ }
+ req.AddData(options)
+ return nil
+}
+
+// ClassList gets a list of classes in the system.
+// Equivalent to: `tc class show`.
+// Generally returns nothing if link and parent are not specified.
+func ClassList(link Link, parent uint32) ([]Class, error) {
+ return pkgHandle.ClassList(link, parent)
+}
+
+// ClassList gets a list of classes in the system.
+// Equivalent to: `tc class show`.
+// Generally returns nothing if link and parent are not specified.
+func (h *Handle) ClassList(link Link, parent uint32) ([]Class, error) {
+ req := h.newNetlinkRequest(syscall.RTM_GETTCLASS, syscall.NLM_F_DUMP)
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Parent: parent,
+ }
+ if link != nil {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ msg.Ifindex = int32(base.Index)
+ }
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWTCLASS)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []Class
+ for _, m := range msgs {
+ msg := nl.DeserializeTcMsg(m)
+
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ base := ClassAttrs{
+ LinkIndex: int(msg.Ifindex),
+ Handle: msg.Handle,
+ Parent: msg.Parent,
+ }
+
+ var class Class
+ classType := ""
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case nl.TCA_KIND:
+ classType = string(attr.Value[:len(attr.Value)-1])
+ switch classType {
+ case "htb":
+ class = &HtbClass{}
+ default:
+ class = &GenericClass{ClassType: classType}
+ }
+ case nl.TCA_OPTIONS:
+ switch classType {
+ case "htb":
+ data, err := nl.ParseRouteAttr(attr.Value)
+ if err != nil {
+ return nil, err
+ }
+ _, err = parseHtbClassData(class, data)
+ if err != nil {
+ return nil, err
+ }
+ }
+ }
+ }
+ *class.Attrs() = base
+ res = append(res, class)
+ }
+
+ return res, nil
+}
+
+func parseHtbClassData(class Class, data []syscall.NetlinkRouteAttr) (bool, error) {
+ htb := class.(*HtbClass)
+ detailed := false
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_HTB_PARMS:
+ opt := nl.DeserializeTcHtbCopt(datum.Value)
+ htb.Rate = uint64(opt.Rate.Rate)
+ htb.Ceil = uint64(opt.Ceil.Rate)
+ htb.Buffer = opt.Buffer
+ htb.Cbuffer = opt.Cbuffer
+ htb.Quantum = opt.Quantum
+ htb.Level = opt.Level
+ htb.Prio = opt.Prio
+ }
+ }
+ return detailed, nil
+}
diff --git a/vendor/github.com/vishvananda/netlink/conntrack_linux.go b/vendor/github.com/vishvananda/netlink/conntrack_linux.go
new file mode 100644
index 0000000..20df903
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/conntrack_linux.go
@@ -0,0 +1,344 @@
+package netlink
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "net"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// ConntrackTableType Conntrack table for the netlink operation
+type ConntrackTableType uint8
+
+const (
+ // ConntrackTable Conntrack table
+ // https://github.com/torvalds/linux/blob/master/include/uapi/linux/netfilter/nfnetlink.h -> #define NFNL_SUBSYS_CTNETLINK 1
+ ConntrackTable = 1
+ // ConntrackExpectTable Conntrack expect table
+ // https://github.com/torvalds/linux/blob/master/include/uapi/linux/netfilter/nfnetlink.h -> #define NFNL_SUBSYS_CTNETLINK_EXP 2
+ ConntrackExpectTable = 2
+)
+
+const (
+ // backward compatibility with golang 1.6 which does not have io.SeekCurrent
+ seekCurrent = 1
+)
+
+// InetFamily Family type
+type InetFamily uint8
+
+// -L [table] [options] List conntrack or expectation table
+// -G [table] parameters Get conntrack or expectation
+
+// -I [table] parameters Create a conntrack or expectation
+// -U [table] parameters Update a conntrack
+// -E [table] [options] Show events
+
+// -C [table] Show counter
+// -S Show statistics
+
+// ConntrackTableList returns the flow list of a table of a specific family
+// conntrack -L [table] [options] List conntrack or expectation table
+func ConntrackTableList(table ConntrackTableType, family InetFamily) ([]*ConntrackFlow, error) {
+ return pkgHandle.ConntrackTableList(table, family)
+}
+
+// ConntrackTableFlush flushes all the flows of a specified table
+// conntrack -F [table] Flush table
+// The flush operation applies to all the family types
+func ConntrackTableFlush(table ConntrackTableType) error {
+ return pkgHandle.ConntrackTableFlush(table)
+}
+
+// ConntrackDeleteFilter deletes entries on the specified table on the base of the filter
+// conntrack -D [table] parameters Delete conntrack or expectation
+func ConntrackDeleteFilter(table ConntrackTableType, family InetFamily, filter *ConntrackFilter) (uint, error) {
+ return pkgHandle.ConntrackDeleteFilter(table, family, filter)
+}
+
+// ConntrackTableList returns the flow list of a table of a specific family using the netlink handle passed
+// conntrack -L [table] [options] List conntrack or expectation table
+func (h *Handle) ConntrackTableList(table ConntrackTableType, family InetFamily) ([]*ConntrackFlow, error) {
+ res, err := h.dumpConntrackTable(table, family)
+ if err != nil {
+ return nil, err
+ }
+
+ // Deserialize all the flows
+ var result []*ConntrackFlow
+ for _, dataRaw := range res {
+ result = append(result, parseRawData(dataRaw))
+ }
+
+ return result, nil
+}
+
+// ConntrackTableFlush flushes all the flows of a specified table using the netlink handle passed
+// conntrack -F [table] Flush table
+// The flush operation applies to all the family types
+func (h *Handle) ConntrackTableFlush(table ConntrackTableType) error {
+ req := h.newConntrackRequest(table, syscall.AF_INET, nl.IPCTNL_MSG_CT_DELETE, syscall.NLM_F_ACK)
+ _, err := req.Execute(syscall.NETLINK_NETFILTER, 0)
+ return err
+}
+
+// ConntrackDeleteFilter deletes entries on the specified table on the base of the filter using the netlink handle passed
+// conntrack -D [table] parameters Delete conntrack or expectation
+func (h *Handle) ConntrackDeleteFilter(table ConntrackTableType, family InetFamily, filter *ConntrackFilter) (uint, error) {
+ res, err := h.dumpConntrackTable(table, family)
+ if err != nil {
+ return 0, err
+ }
+
+ var matched uint
+ for _, dataRaw := range res {
+ flow := parseRawData(dataRaw)
+ if match := filter.MatchConntrackFlow(flow); match {
+ req2 := h.newConntrackRequest(table, family, nl.IPCTNL_MSG_CT_DELETE, syscall.NLM_F_ACK)
+ // skip the first 4 byte that are the netfilter header, the newConntrackRequest is adding it already
+ req2.AddRawData(dataRaw[4:])
+ req2.Execute(syscall.NETLINK_NETFILTER, 0)
+ matched++
+ }
+ }
+
+ return matched, nil
+}
+
+func (h *Handle) newConntrackRequest(table ConntrackTableType, family InetFamily, operation, flags int) *nl.NetlinkRequest {
+ // Create the Netlink request object
+ req := h.newNetlinkRequest((int(table)<<8)|operation, flags)
+ // Add the netfilter header
+ msg := &nl.Nfgenmsg{
+ NfgenFamily: uint8(family),
+ Version: nl.NFNETLINK_V0,
+ ResId: 0,
+ }
+ req.AddData(msg)
+ return req
+}
+
+func (h *Handle) dumpConntrackTable(table ConntrackTableType, family InetFamily) ([][]byte, error) {
+ req := h.newConntrackRequest(table, family, nl.IPCTNL_MSG_CT_GET, syscall.NLM_F_DUMP)
+ return req.Execute(syscall.NETLINK_NETFILTER, 0)
+}
+
+// The full conntrack flow structure is very complicated and can be found in the file:
+// http://git.netfilter.org/libnetfilter_conntrack/tree/include/internal/object.h
+// For the time being, the structure below allows to parse and extract the base information of a flow
+type ipTuple struct {
+ SrcIP net.IP
+ DstIP net.IP
+ Protocol uint8
+ SrcPort uint16
+ DstPort uint16
+}
+
+type ConntrackFlow struct {
+ FamilyType uint8
+ Forward ipTuple
+ Reverse ipTuple
+}
+
+func (s *ConntrackFlow) String() string {
+ // conntrack cmd output:
+ // udp 17 src=127.0.0.1 dst=127.0.0.1 sport=4001 dport=1234 [UNREPLIED] src=127.0.0.1 dst=127.0.0.1 sport=1234 dport=4001
+ return fmt.Sprintf("%s\t%d src=%s dst=%s sport=%d dport=%d\tsrc=%s dst=%s sport=%d dport=%d",
+ nl.L4ProtoMap[s.Forward.Protocol], s.Forward.Protocol,
+ s.Forward.SrcIP.String(), s.Forward.DstIP.String(), s.Forward.SrcPort, s.Forward.DstPort,
+ s.Reverse.SrcIP.String(), s.Reverse.DstIP.String(), s.Reverse.SrcPort, s.Reverse.DstPort)
+}
+
+// This method parse the ip tuple structure
+// The message structure is the following:
+// <len, [CTA_IP_V4_SRC|CTA_IP_V6_SRC], 16 bytes for the IP>
+// <len, [CTA_IP_V4_DST|CTA_IP_V6_DST], 16 bytes for the IP>
+// <len, NLA_F_NESTED|nl.CTA_TUPLE_PROTO, 1 byte for the protocol, 3 bytes of padding>
+// <len, CTA_PROTO_SRC_PORT, 2 bytes for the source port, 2 bytes of padding>
+// <len, CTA_PROTO_DST_PORT, 2 bytes for the source port, 2 bytes of padding>
+func parseIpTuple(reader *bytes.Reader, tpl *ipTuple) {
+ for i := 0; i < 2; i++ {
+ _, t, _, v := parseNfAttrTLV(reader)
+ switch t {
+ case nl.CTA_IP_V4_SRC, nl.CTA_IP_V6_SRC:
+ tpl.SrcIP = v
+ case nl.CTA_IP_V4_DST, nl.CTA_IP_V6_DST:
+ tpl.DstIP = v
+ }
+ }
+ // Skip the next 4 bytes nl.NLA_F_NESTED|nl.CTA_TUPLE_PROTO
+ reader.Seek(4, seekCurrent)
+ _, t, _, v := parseNfAttrTLV(reader)
+ if t == nl.CTA_PROTO_NUM {
+ tpl.Protocol = uint8(v[0])
+ }
+ // Skip some padding 3 bytes
+ reader.Seek(3, seekCurrent)
+ for i := 0; i < 2; i++ {
+ _, t, _ := parseNfAttrTL(reader)
+ switch t {
+ case nl.CTA_PROTO_SRC_PORT:
+ parseBERaw16(reader, &tpl.SrcPort)
+ case nl.CTA_PROTO_DST_PORT:
+ parseBERaw16(reader, &tpl.DstPort)
+ }
+ // Skip some padding 2 byte
+ reader.Seek(2, seekCurrent)
+ }
+}
+
+func parseNfAttrTLV(r *bytes.Reader) (isNested bool, attrType, len uint16, value []byte) {
+ isNested, attrType, len = parseNfAttrTL(r)
+
+ value = make([]byte, len)
+ binary.Read(r, binary.BigEndian, &value)
+ return isNested, attrType, len, value
+}
+
+func parseNfAttrTL(r *bytes.Reader) (isNested bool, attrType, len uint16) {
+ binary.Read(r, nl.NativeEndian(), &len)
+ len -= nl.SizeofNfattr
+
+ binary.Read(r, nl.NativeEndian(), &attrType)
+ isNested = (attrType & nl.NLA_F_NESTED) == nl.NLA_F_NESTED
+ attrType = attrType & (nl.NLA_F_NESTED - 1)
+
+ return isNested, attrType, len
+}
+
+func parseBERaw16(r *bytes.Reader, v *uint16) {
+ binary.Read(r, binary.BigEndian, v)
+}
+
+func parseRawData(data []byte) *ConntrackFlow {
+ s := &ConntrackFlow{}
+ // First there is the Nfgenmsg header
+ // consume only the family field
+ reader := bytes.NewReader(data)
+ binary.Read(reader, nl.NativeEndian(), &s.FamilyType)
+
+ // skip rest of the Netfilter header
+ reader.Seek(3, seekCurrent)
+ // The message structure is the following:
+ // <len, NLA_F_NESTED|CTA_TUPLE_ORIG> 4 bytes
+ // <len, NLA_F_NESTED|CTA_TUPLE_IP> 4 bytes
+ // flow information of the forward flow
+ // <len, NLA_F_NESTED|CTA_TUPLE_REPLY> 4 bytes
+ // <len, NLA_F_NESTED|CTA_TUPLE_IP> 4 bytes
+ // flow information of the reverse flow
+ for reader.Len() > 0 {
+ nested, t, l := parseNfAttrTL(reader)
+ if nested && t == nl.CTA_TUPLE_ORIG {
+ if nested, t, _ = parseNfAttrTL(reader); nested && t == nl.CTA_TUPLE_IP {
+ parseIpTuple(reader, &s.Forward)
+ }
+ } else if nested && t == nl.CTA_TUPLE_REPLY {
+ if nested, t, _ = parseNfAttrTL(reader); nested && t == nl.CTA_TUPLE_IP {
+ parseIpTuple(reader, &s.Reverse)
+
+ // Got all the useful information stop parsing
+ break
+ } else {
+ // Header not recognized skip it
+ reader.Seek(int64(l), seekCurrent)
+ }
+ }
+ }
+
+ return s
+}
+
+// Conntrack parameters and options:
+// -n, --src-nat ip source NAT ip
+// -g, --dst-nat ip destination NAT ip
+// -j, --any-nat ip source or destination NAT ip
+// -m, --mark mark Set mark
+// -c, --secmark secmark Set selinux secmark
+// -e, --event-mask eventmask Event mask, eg. NEW,DESTROY
+// -z, --zero Zero counters while listing
+// -o, --output type[,...] Output format, eg. xml
+// -l, --label label[,...] conntrack labels
+
+// Common parameters and options:
+// -s, --src, --orig-src ip Source address from original direction
+// -d, --dst, --orig-dst ip Destination address from original direction
+// -r, --reply-src ip Source addres from reply direction
+// -q, --reply-dst ip Destination address from reply direction
+// -p, --protonum proto Layer 4 Protocol, eg. 'tcp'
+// -f, --family proto Layer 3 Protocol, eg. 'ipv6'
+// -t, --timeout timeout Set timeout
+// -u, --status status Set status, eg. ASSURED
+// -w, --zone value Set conntrack zone
+// --orig-zone value Set zone for original direction
+// --reply-zone value Set zone for reply direction
+// -b, --buffer-size Netlink socket buffer size
+// --mask-src ip Source mask address
+// --mask-dst ip Destination mask address
+
+// Filter types
+type ConntrackFilterType uint8
+
+const (
+ ConntrackOrigSrcIP = iota // -orig-src ip Source address from original direction
+ ConntrackOrigDstIP // -orig-dst ip Destination address from original direction
+ ConntrackNatSrcIP // -src-nat ip Source NAT ip
+ ConntrackNatDstIP // -dst-nat ip Destination NAT ip
+ ConntrackNatAnyIP // -any-nat ip Source or destination NAT ip
+)
+
+type ConntrackFilter struct {
+ ipFilter map[ConntrackFilterType]net.IP
+}
+
+// AddIP adds an IP to the conntrack filter
+func (f *ConntrackFilter) AddIP(tp ConntrackFilterType, ip net.IP) error {
+ if f.ipFilter == nil {
+ f.ipFilter = make(map[ConntrackFilterType]net.IP)
+ }
+ if _, ok := f.ipFilter[tp]; ok {
+ return errors.New("Filter attribute already present")
+ }
+ f.ipFilter[tp] = ip
+ return nil
+}
+
+// MatchConntrackFlow applies the filter to the flow and returns true if the flow matches the filter
+// false otherwise
+func (f *ConntrackFilter) MatchConntrackFlow(flow *ConntrackFlow) bool {
+ if len(f.ipFilter) == 0 {
+ // empty filter always not match
+ return false
+ }
+
+ match := true
+ // -orig-src ip Source address from original direction
+ if elem, found := f.ipFilter[ConntrackOrigSrcIP]; found {
+ match = match && elem.Equal(flow.Forward.SrcIP)
+ }
+
+ // -orig-dst ip Destination address from original direction
+ if elem, found := f.ipFilter[ConntrackOrigDstIP]; match && found {
+ match = match && elem.Equal(flow.Forward.DstIP)
+ }
+
+ // -src-nat ip Source NAT ip
+ if elem, found := f.ipFilter[ConntrackNatSrcIP]; match && found {
+ match = match && elem.Equal(flow.Reverse.SrcIP)
+ }
+
+ // -dst-nat ip Destination NAT ip
+ if elem, found := f.ipFilter[ConntrackNatDstIP]; match && found {
+ match = match && elem.Equal(flow.Reverse.DstIP)
+ }
+
+ // -any-nat ip Source or destination NAT ip
+ if elem, found := f.ipFilter[ConntrackNatAnyIP]; match && found {
+ match = match && (elem.Equal(flow.Reverse.SrcIP) || elem.Equal(flow.Reverse.DstIP))
+ }
+
+ return match
+}
diff --git a/vendor/github.com/vishvananda/netlink/conntrack_unspecified.go b/vendor/github.com/vishvananda/netlink/conntrack_unspecified.go
new file mode 100644
index 0000000..af7af79
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/conntrack_unspecified.go
@@ -0,0 +1,53 @@
+// +build !linux
+
+package netlink
+
+// ConntrackTableType Conntrack table for the netlink operation
+type ConntrackTableType uint8
+
+// InetFamily Family type
+type InetFamily uint8
+
+// ConntrackFlow placeholder
+type ConntrackFlow struct{}
+
+// ConntrackFilter placeholder
+type ConntrackFilter struct{}
+
+// ConntrackTableList returns the flow list of a table of a specific family
+// conntrack -L [table] [options] List conntrack or expectation table
+func ConntrackTableList(table ConntrackTableType, family InetFamily) ([]*ConntrackFlow, error) {
+ return nil, ErrNotImplemented
+}
+
+// ConntrackTableFlush flushes all the flows of a specified table
+// conntrack -F [table] Flush table
+// The flush operation applies to all the family types
+func ConntrackTableFlush(table ConntrackTableType) error {
+ return ErrNotImplemented
+}
+
+// ConntrackDeleteFilter deletes entries on the specified table on the base of the filter
+// conntrack -D [table] parameters Delete conntrack or expectation
+func ConntrackDeleteFilter(table ConntrackTableType, family InetFamily, filter *ConntrackFilter) (uint, error) {
+ return 0, ErrNotImplemented
+}
+
+// ConntrackTableList returns the flow list of a table of a specific family using the netlink handle passed
+// conntrack -L [table] [options] List conntrack or expectation table
+func (h *Handle) ConntrackTableList(table ConntrackTableType, family InetFamily) ([]*ConntrackFlow, error) {
+ return nil, ErrNotImplemented
+}
+
+// ConntrackTableFlush flushes all the flows of a specified table using the netlink handle passed
+// conntrack -F [table] Flush table
+// The flush operation applies to all the family types
+func (h *Handle) ConntrackTableFlush(table ConntrackTableType) error {
+ return ErrNotImplemented
+}
+
+// ConntrackDeleteFilter deletes entries on the specified table on the base of the filter using the netlink handle passed
+// conntrack -D [table] parameters Delete conntrack or expectation
+func (h *Handle) ConntrackDeleteFilter(table ConntrackTableType, family InetFamily, filter *ConntrackFilter) (uint, error) {
+ return 0, ErrNotImplemented
+}
diff --git a/vendor/github.com/vishvananda/netlink/filter.go b/vendor/github.com/vishvananda/netlink/filter.go
new file mode 100644
index 0000000..938b28b
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/filter.go
@@ -0,0 +1,283 @@
+package netlink
+
+import (
+ "fmt"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+type Filter interface {
+ Attrs() *FilterAttrs
+ Type() string
+}
+
+// FilterAttrs represents a netlink filter. A filter is associated with a link,
+// has a handle and a parent. The root filter of a device should have a
+// parent == HANDLE_ROOT.
+type FilterAttrs struct {
+ LinkIndex int
+ Handle uint32
+ Parent uint32
+ Priority uint16 // lower is higher priority
+ Protocol uint16 // syscall.ETH_P_*
+}
+
+func (q FilterAttrs) String() string {
+ return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Priority: %d, Protocol: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Priority, q.Protocol)
+}
+
+type TcAct int32
+
+const (
+ TC_ACT_UNSPEC TcAct = -1
+ TC_ACT_OK TcAct = 0
+ TC_ACT_RECLASSIFY TcAct = 1
+ TC_ACT_SHOT TcAct = 2
+ TC_ACT_PIPE TcAct = 3
+ TC_ACT_STOLEN TcAct = 4
+ TC_ACT_QUEUED TcAct = 5
+ TC_ACT_REPEAT TcAct = 6
+ TC_ACT_REDIRECT TcAct = 7
+ TC_ACT_JUMP TcAct = 0x10000000
+)
+
+func (a TcAct) String() string {
+ switch a {
+ case TC_ACT_UNSPEC:
+ return "unspec"
+ case TC_ACT_OK:
+ return "ok"
+ case TC_ACT_RECLASSIFY:
+ return "reclassify"
+ case TC_ACT_SHOT:
+ return "shot"
+ case TC_ACT_PIPE:
+ return "pipe"
+ case TC_ACT_STOLEN:
+ return "stolen"
+ case TC_ACT_QUEUED:
+ return "queued"
+ case TC_ACT_REPEAT:
+ return "repeat"
+ case TC_ACT_REDIRECT:
+ return "redirect"
+ case TC_ACT_JUMP:
+ return "jump"
+ }
+ return fmt.Sprintf("0x%x", int32(a))
+}
+
+type TcPolAct int32
+
+const (
+ TC_POLICE_UNSPEC TcPolAct = TcPolAct(TC_ACT_UNSPEC)
+ TC_POLICE_OK TcPolAct = TcPolAct(TC_ACT_OK)
+ TC_POLICE_RECLASSIFY TcPolAct = TcPolAct(TC_ACT_RECLASSIFY)
+ TC_POLICE_SHOT TcPolAct = TcPolAct(TC_ACT_SHOT)
+ TC_POLICE_PIPE TcPolAct = TcPolAct(TC_ACT_PIPE)
+)
+
+func (a TcPolAct) String() string {
+ switch a {
+ case TC_POLICE_UNSPEC:
+ return "unspec"
+ case TC_POLICE_OK:
+ return "ok"
+ case TC_POLICE_RECLASSIFY:
+ return "reclassify"
+ case TC_POLICE_SHOT:
+ return "shot"
+ case TC_POLICE_PIPE:
+ return "pipe"
+ }
+ return fmt.Sprintf("0x%x", int32(a))
+}
+
+type ActionAttrs struct {
+ Index int
+ Capab int
+ Action TcAct
+ Refcnt int
+ Bindcnt int
+}
+
+func (q ActionAttrs) String() string {
+ return fmt.Sprintf("{Index: %d, Capab: %x, Action: %s, Refcnt: %d, Bindcnt: %d}", q.Index, q.Capab, q.Action.String(), q.Refcnt, q.Bindcnt)
+}
+
+// Action represents an action in any supported filter.
+type Action interface {
+ Attrs() *ActionAttrs
+ Type() string
+}
+
+type GenericAction struct {
+ ActionAttrs
+}
+
+func (action *GenericAction) Type() string {
+ return "generic"
+}
+
+func (action *GenericAction) Attrs() *ActionAttrs {
+ return &action.ActionAttrs
+}
+
+type BpfAction struct {
+ ActionAttrs
+ Fd int
+ Name string
+}
+
+func (action *BpfAction) Type() string {
+ return "bpf"
+}
+
+func (action *BpfAction) Attrs() *ActionAttrs {
+ return &action.ActionAttrs
+}
+
+type MirredAct uint8
+
+func (a MirredAct) String() string {
+ switch a {
+ case TCA_EGRESS_REDIR:
+ return "egress redir"
+ case TCA_EGRESS_MIRROR:
+ return "egress mirror"
+ case TCA_INGRESS_REDIR:
+ return "ingress redir"
+ case TCA_INGRESS_MIRROR:
+ return "ingress mirror"
+ }
+ return "unknown"
+}
+
+const (
+ TCA_EGRESS_REDIR MirredAct = 1 /* packet redirect to EGRESS*/
+ TCA_EGRESS_MIRROR MirredAct = 2 /* mirror packet to EGRESS */
+ TCA_INGRESS_REDIR MirredAct = 3 /* packet redirect to INGRESS*/
+ TCA_INGRESS_MIRROR MirredAct = 4 /* mirror packet to INGRESS */
+)
+
+type MirredAction struct {
+ ActionAttrs
+ MirredAction MirredAct
+ Ifindex int
+}
+
+func (action *MirredAction) Type() string {
+ return "mirred"
+}
+
+func (action *MirredAction) Attrs() *ActionAttrs {
+ return &action.ActionAttrs
+}
+
+func NewMirredAction(redirIndex int) *MirredAction {
+ return &MirredAction{
+ ActionAttrs: ActionAttrs{
+ Action: TC_ACT_STOLEN,
+ },
+ MirredAction: TCA_EGRESS_REDIR,
+ Ifindex: redirIndex,
+ }
+}
+
+// Constants used in TcU32Sel.Flags.
+const (
+ TC_U32_TERMINAL = nl.TC_U32_TERMINAL
+ TC_U32_OFFSET = nl.TC_U32_OFFSET
+ TC_U32_VAROFFSET = nl.TC_U32_VAROFFSET
+ TC_U32_EAT = nl.TC_U32_EAT
+)
+
+// Sel of the U32 filters that contains multiple TcU32Key. This is the copy
+// and the frontend representation of nl.TcU32Sel. It is serialized into canonical
+// nl.TcU32Sel with the appropriate endianness.
+type TcU32Sel struct {
+ Flags uint8
+ Offshift uint8
+ Nkeys uint8
+ Pad uint8
+ Offmask uint16
+ Off uint16
+ Offoff int16
+ Hoff int16
+ Hmask uint32
+ Keys []TcU32Key
+}
+
+// TcU32Key contained of Sel in the U32 filters. This is the copy and the frontend
+// representation of nl.TcU32Key. It is serialized into chanonical nl.TcU32Sel
+// with the appropriate endianness.
+type TcU32Key struct {
+ Mask uint32
+ Val uint32
+ Off int32
+ OffMask int32
+}
+
+// U32 filters on many packet related properties
+type U32 struct {
+ FilterAttrs
+ ClassId uint32
+ RedirIndex int
+ Sel *TcU32Sel
+ Actions []Action
+}
+
+func (filter *U32) Attrs() *FilterAttrs {
+ return &filter.FilterAttrs
+}
+
+func (filter *U32) Type() string {
+ return "u32"
+}
+
+type FilterFwAttrs struct {
+ ClassId uint32
+ InDev string
+ Mask uint32
+ Index uint32
+ Buffer uint32
+ Mtu uint32
+ Mpu uint16
+ Rate uint32
+ AvRate uint32
+ PeakRate uint32
+ Action TcPolAct
+ Overhead uint16
+ LinkLayer int
+}
+
+type BpfFilter struct {
+ FilterAttrs
+ ClassId uint32
+ Fd int
+ Name string
+ DirectAction bool
+}
+
+func (filter *BpfFilter) Type() string {
+ return "bpf"
+}
+
+func (filter *BpfFilter) Attrs() *FilterAttrs {
+ return &filter.FilterAttrs
+}
+
+// GenericFilter filters represent types that are not currently understood
+// by this netlink library.
+type GenericFilter struct {
+ FilterAttrs
+ FilterType string
+}
+
+func (filter *GenericFilter) Attrs() *FilterAttrs {
+ return &filter.FilterAttrs
+}
+
+func (filter *GenericFilter) Type() string {
+ return filter.FilterType
+}
diff --git a/vendor/github.com/vishvananda/netlink/filter_linux.go b/vendor/github.com/vishvananda/netlink/filter_linux.go
new file mode 100644
index 0000000..dc0f90a
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/filter_linux.go
@@ -0,0 +1,591 @@
+package netlink
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "syscall"
+ "unsafe"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// Fw filter filters on firewall marks
+// NOTE: this is in filter_linux because it refers to nl.TcPolice which
+// is defined in nl/tc_linux.go
+type Fw struct {
+ FilterAttrs
+ ClassId uint32
+ // TODO remove nl type from interface
+ Police nl.TcPolice
+ InDev string
+ // TODO Action
+ Mask uint32
+ AvRate uint32
+ Rtab [256]uint32
+ Ptab [256]uint32
+}
+
+func NewFw(attrs FilterAttrs, fattrs FilterFwAttrs) (*Fw, error) {
+ var rtab [256]uint32
+ var ptab [256]uint32
+ rcellLog := -1
+ pcellLog := -1
+ avrate := fattrs.AvRate / 8
+ police := nl.TcPolice{}
+ police.Rate.Rate = fattrs.Rate / 8
+ police.PeakRate.Rate = fattrs.PeakRate / 8
+ buffer := fattrs.Buffer
+ linklayer := nl.LINKLAYER_ETHERNET
+
+ if fattrs.LinkLayer != nl.LINKLAYER_UNSPEC {
+ linklayer = fattrs.LinkLayer
+ }
+
+ police.Action = int32(fattrs.Action)
+ if police.Rate.Rate != 0 {
+ police.Rate.Mpu = fattrs.Mpu
+ police.Rate.Overhead = fattrs.Overhead
+ if CalcRtable(&police.Rate, rtab, rcellLog, fattrs.Mtu, linklayer) < 0 {
+ return nil, errors.New("TBF: failed to calculate rate table")
+ }
+ police.Burst = uint32(Xmittime(uint64(police.Rate.Rate), uint32(buffer)))
+ }
+ police.Mtu = fattrs.Mtu
+ if police.PeakRate.Rate != 0 {
+ police.PeakRate.Mpu = fattrs.Mpu
+ police.PeakRate.Overhead = fattrs.Overhead
+ if CalcRtable(&police.PeakRate, ptab, pcellLog, fattrs.Mtu, linklayer) < 0 {
+ return nil, errors.New("POLICE: failed to calculate peak rate table")
+ }
+ }
+
+ return &Fw{
+ FilterAttrs: attrs,
+ ClassId: fattrs.ClassId,
+ InDev: fattrs.InDev,
+ Mask: fattrs.Mask,
+ Police: police,
+ AvRate: avrate,
+ Rtab: rtab,
+ Ptab: ptab,
+ }, nil
+}
+
+func (filter *Fw) Attrs() *FilterAttrs {
+ return &filter.FilterAttrs
+}
+
+func (filter *Fw) Type() string {
+ return "fw"
+}
+
+// FilterDel will delete a filter from the system.
+// Equivalent to: `tc filter del $filter`
+func FilterDel(filter Filter) error {
+ return pkgHandle.FilterDel(filter)
+}
+
+// FilterDel will delete a filter from the system.
+// Equivalent to: `tc filter del $filter`
+func (h *Handle) FilterDel(filter Filter) error {
+ req := h.newNetlinkRequest(syscall.RTM_DELTFILTER, syscall.NLM_F_ACK)
+ base := filter.Attrs()
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Ifindex: int32(base.LinkIndex),
+ Handle: base.Handle,
+ Parent: base.Parent,
+ Info: MakeHandle(base.Priority, nl.Swap16(base.Protocol)),
+ }
+ req.AddData(msg)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// FilterAdd will add a filter to the system.
+// Equivalent to: `tc filter add $filter`
+func FilterAdd(filter Filter) error {
+ return pkgHandle.FilterAdd(filter)
+}
+
+// FilterAdd will add a filter to the system.
+// Equivalent to: `tc filter add $filter`
+func (h *Handle) FilterAdd(filter Filter) error {
+ native = nl.NativeEndian()
+ req := h.newNetlinkRequest(syscall.RTM_NEWTFILTER, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+ base := filter.Attrs()
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Ifindex: int32(base.LinkIndex),
+ Handle: base.Handle,
+ Parent: base.Parent,
+ Info: MakeHandle(base.Priority, nl.Swap16(base.Protocol)),
+ }
+ req.AddData(msg)
+ req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(filter.Type())))
+
+ options := nl.NewRtAttr(nl.TCA_OPTIONS, nil)
+ if u32, ok := filter.(*U32); ok {
+ // Convert TcU32Sel into nl.TcU32Sel as it is without copy.
+ sel := (*nl.TcU32Sel)(unsafe.Pointer(u32.Sel))
+ if sel == nil {
+ // match all
+ sel = &nl.TcU32Sel{
+ Nkeys: 1,
+ Flags: nl.TC_U32_TERMINAL,
+ }
+ sel.Keys = append(sel.Keys, nl.TcU32Key{})
+ }
+
+ if native != networkOrder {
+ // Copy TcU32Sel.
+ cSel := *sel
+ keys := make([]nl.TcU32Key, cap(sel.Keys))
+ copy(keys, sel.Keys)
+ cSel.Keys = keys
+ sel = &cSel
+
+ // Handle the endianness of attributes
+ sel.Offmask = native.Uint16(htons(sel.Offmask))
+ sel.Hmask = native.Uint32(htonl(sel.Hmask))
+ for i, key := range sel.Keys {
+ sel.Keys[i].Mask = native.Uint32(htonl(key.Mask))
+ sel.Keys[i].Val = native.Uint32(htonl(key.Val))
+ }
+ }
+ sel.Nkeys = uint8(len(sel.Keys))
+ nl.NewRtAttrChild(options, nl.TCA_U32_SEL, sel.Serialize())
+ if u32.ClassId != 0 {
+ nl.NewRtAttrChild(options, nl.TCA_U32_CLASSID, nl.Uint32Attr(u32.ClassId))
+ }
+ actionsAttr := nl.NewRtAttrChild(options, nl.TCA_U32_ACT, nil)
+ // backwards compatibility
+ if u32.RedirIndex != 0 {
+ u32.Actions = append([]Action{NewMirredAction(u32.RedirIndex)}, u32.Actions...)
+ }
+ if err := EncodeActions(actionsAttr, u32.Actions); err != nil {
+ return err
+ }
+ } else if fw, ok := filter.(*Fw); ok {
+ if fw.Mask != 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, fw.Mask)
+ nl.NewRtAttrChild(options, nl.TCA_FW_MASK, b)
+ }
+ if fw.InDev != "" {
+ nl.NewRtAttrChild(options, nl.TCA_FW_INDEV, nl.ZeroTerminated(fw.InDev))
+ }
+ if (fw.Police != nl.TcPolice{}) {
+
+ police := nl.NewRtAttrChild(options, nl.TCA_FW_POLICE, nil)
+ nl.NewRtAttrChild(police, nl.TCA_POLICE_TBF, fw.Police.Serialize())
+ if (fw.Police.Rate != nl.TcRateSpec{}) {
+ payload := SerializeRtab(fw.Rtab)
+ nl.NewRtAttrChild(police, nl.TCA_POLICE_RATE, payload)
+ }
+ if (fw.Police.PeakRate != nl.TcRateSpec{}) {
+ payload := SerializeRtab(fw.Ptab)
+ nl.NewRtAttrChild(police, nl.TCA_POLICE_PEAKRATE, payload)
+ }
+ }
+ if fw.ClassId != 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, fw.ClassId)
+ nl.NewRtAttrChild(options, nl.TCA_FW_CLASSID, b)
+ }
+ } else if bpf, ok := filter.(*BpfFilter); ok {
+ var bpfFlags uint32
+ if bpf.ClassId != 0 {
+ nl.NewRtAttrChild(options, nl.TCA_BPF_CLASSID, nl.Uint32Attr(bpf.ClassId))
+ }
+ if bpf.Fd >= 0 {
+ nl.NewRtAttrChild(options, nl.TCA_BPF_FD, nl.Uint32Attr((uint32(bpf.Fd))))
+ }
+ if bpf.Name != "" {
+ nl.NewRtAttrChild(options, nl.TCA_BPF_NAME, nl.ZeroTerminated(bpf.Name))
+ }
+ if bpf.DirectAction {
+ bpfFlags |= nl.TCA_BPF_FLAG_ACT_DIRECT
+ }
+ nl.NewRtAttrChild(options, nl.TCA_BPF_FLAGS, nl.Uint32Attr(bpfFlags))
+ }
+
+ req.AddData(options)
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// FilterList gets a list of filters in the system.
+// Equivalent to: `tc filter show`.
+// Generally returns nothing if link and parent are not specified.
+func FilterList(link Link, parent uint32) ([]Filter, error) {
+ return pkgHandle.FilterList(link, parent)
+}
+
+// FilterList gets a list of filters in the system.
+// Equivalent to: `tc filter show`.
+// Generally returns nothing if link and parent are not specified.
+func (h *Handle) FilterList(link Link, parent uint32) ([]Filter, error) {
+ req := h.newNetlinkRequest(syscall.RTM_GETTFILTER, syscall.NLM_F_DUMP)
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Parent: parent,
+ }
+ if link != nil {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ msg.Ifindex = int32(base.Index)
+ }
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWTFILTER)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []Filter
+ for _, m := range msgs {
+ msg := nl.DeserializeTcMsg(m)
+
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ base := FilterAttrs{
+ LinkIndex: int(msg.Ifindex),
+ Handle: msg.Handle,
+ Parent: msg.Parent,
+ }
+ base.Priority, base.Protocol = MajorMinor(msg.Info)
+ base.Protocol = nl.Swap16(base.Protocol)
+
+ var filter Filter
+ filterType := ""
+ detailed := false
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case nl.TCA_KIND:
+ filterType = string(attr.Value[:len(attr.Value)-1])
+ switch filterType {
+ case "u32":
+ filter = &U32{}
+ case "fw":
+ filter = &Fw{}
+ case "bpf":
+ filter = &BpfFilter{}
+ default:
+ filter = &GenericFilter{FilterType: filterType}
+ }
+ case nl.TCA_OPTIONS:
+ data, err := nl.ParseRouteAttr(attr.Value)
+ if err != nil {
+ return nil, err
+ }
+ switch filterType {
+ case "u32":
+ detailed, err = parseU32Data(filter, data)
+ if err != nil {
+ return nil, err
+ }
+ case "fw":
+ detailed, err = parseFwData(filter, data)
+ if err != nil {
+ return nil, err
+ }
+ case "bpf":
+ detailed, err = parseBpfData(filter, data)
+ if err != nil {
+ return nil, err
+ }
+ default:
+ detailed = true
+ }
+ }
+ }
+ // only return the detailed version of the filter
+ if detailed {
+ *filter.Attrs() = base
+ res = append(res, filter)
+ }
+ }
+
+ return res, nil
+}
+
+func toTcGen(attrs *ActionAttrs, tcgen *nl.TcGen) {
+ tcgen.Index = uint32(attrs.Index)
+ tcgen.Capab = uint32(attrs.Capab)
+ tcgen.Action = int32(attrs.Action)
+ tcgen.Refcnt = int32(attrs.Refcnt)
+ tcgen.Bindcnt = int32(attrs.Bindcnt)
+}
+
+func toAttrs(tcgen *nl.TcGen, attrs *ActionAttrs) {
+ attrs.Index = int(tcgen.Index)
+ attrs.Capab = int(tcgen.Capab)
+ attrs.Action = TcAct(tcgen.Action)
+ attrs.Refcnt = int(tcgen.Refcnt)
+ attrs.Bindcnt = int(tcgen.Bindcnt)
+}
+
+func EncodeActions(attr *nl.RtAttr, actions []Action) error {
+ tabIndex := int(nl.TCA_ACT_TAB)
+
+ for _, action := range actions {
+ switch action := action.(type) {
+ default:
+ return fmt.Errorf("unknown action type %s", action.Type())
+ case *MirredAction:
+ table := nl.NewRtAttrChild(attr, tabIndex, nil)
+ tabIndex++
+ nl.NewRtAttrChild(table, nl.TCA_ACT_KIND, nl.ZeroTerminated("mirred"))
+ aopts := nl.NewRtAttrChild(table, nl.TCA_ACT_OPTIONS, nil)
+ mirred := nl.TcMirred{
+ Eaction: int32(action.MirredAction),
+ Ifindex: uint32(action.Ifindex),
+ }
+ toTcGen(action.Attrs(), &mirred.TcGen)
+ nl.NewRtAttrChild(aopts, nl.TCA_MIRRED_PARMS, mirred.Serialize())
+ case *BpfAction:
+ table := nl.NewRtAttrChild(attr, tabIndex, nil)
+ tabIndex++
+ nl.NewRtAttrChild(table, nl.TCA_ACT_KIND, nl.ZeroTerminated("bpf"))
+ aopts := nl.NewRtAttrChild(table, nl.TCA_ACT_OPTIONS, nil)
+ gen := nl.TcGen{}
+ toTcGen(action.Attrs(), &gen)
+ nl.NewRtAttrChild(aopts, nl.TCA_ACT_BPF_PARMS, gen.Serialize())
+ nl.NewRtAttrChild(aopts, nl.TCA_ACT_BPF_FD, nl.Uint32Attr(uint32(action.Fd)))
+ nl.NewRtAttrChild(aopts, nl.TCA_ACT_BPF_NAME, nl.ZeroTerminated(action.Name))
+ case *GenericAction:
+ table := nl.NewRtAttrChild(attr, tabIndex, nil)
+ tabIndex++
+ nl.NewRtAttrChild(table, nl.TCA_ACT_KIND, nl.ZeroTerminated("gact"))
+ aopts := nl.NewRtAttrChild(table, nl.TCA_ACT_OPTIONS, nil)
+ gen := nl.TcGen{}
+ toTcGen(action.Attrs(), &gen)
+ nl.NewRtAttrChild(aopts, nl.TCA_GACT_PARMS, gen.Serialize())
+ }
+ }
+ return nil
+}
+
+func parseActions(tables []syscall.NetlinkRouteAttr) ([]Action, error) {
+ var actions []Action
+ for _, table := range tables {
+ var action Action
+ var actionType string
+ aattrs, err := nl.ParseRouteAttr(table.Value)
+ if err != nil {
+ return nil, err
+ }
+ nextattr:
+ for _, aattr := range aattrs {
+ switch aattr.Attr.Type {
+ case nl.TCA_KIND:
+ actionType = string(aattr.Value[:len(aattr.Value)-1])
+ // only parse if the action is mirred or bpf
+ switch actionType {
+ case "mirred":
+ action = &MirredAction{}
+ case "bpf":
+ action = &BpfAction{}
+ case "gact":
+ action = &GenericAction{}
+ default:
+ break nextattr
+ }
+ case nl.TCA_OPTIONS:
+ adata, err := nl.ParseRouteAttr(aattr.Value)
+ if err != nil {
+ return nil, err
+ }
+ for _, adatum := range adata {
+ switch actionType {
+ case "mirred":
+ switch adatum.Attr.Type {
+ case nl.TCA_MIRRED_PARMS:
+ mirred := *nl.DeserializeTcMirred(adatum.Value)
+ toAttrs(&mirred.TcGen, action.Attrs())
+ action.(*MirredAction).ActionAttrs = ActionAttrs{}
+ action.(*MirredAction).Ifindex = int(mirred.Ifindex)
+ action.(*MirredAction).MirredAction = MirredAct(mirred.Eaction)
+ }
+ case "bpf":
+ switch adatum.Attr.Type {
+ case nl.TCA_ACT_BPF_PARMS:
+ gen := *nl.DeserializeTcGen(adatum.Value)
+ toAttrs(&gen, action.Attrs())
+ case nl.TCA_ACT_BPF_FD:
+ action.(*BpfAction).Fd = int(native.Uint32(adatum.Value[0:4]))
+ case nl.TCA_ACT_BPF_NAME:
+ action.(*BpfAction).Name = string(adatum.Value[:len(adatum.Value)-1])
+ }
+ case "gact":
+ switch adatum.Attr.Type {
+ case nl.TCA_GACT_PARMS:
+ gen := *nl.DeserializeTcGen(adatum.Value)
+ toAttrs(&gen, action.Attrs())
+ }
+ }
+ }
+ }
+ }
+ actions = append(actions, action)
+ }
+ return actions, nil
+}
+
+func parseU32Data(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) {
+ native = nl.NativeEndian()
+ u32 := filter.(*U32)
+ detailed := false
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_U32_SEL:
+ detailed = true
+ sel := nl.DeserializeTcU32Sel(datum.Value)
+ u32.Sel = (*TcU32Sel)(unsafe.Pointer(sel))
+ if native != networkOrder {
+ // Handle the endianness of attributes
+ u32.Sel.Offmask = native.Uint16(htons(sel.Offmask))
+ u32.Sel.Hmask = native.Uint32(htonl(sel.Hmask))
+ for i, key := range u32.Sel.Keys {
+ u32.Sel.Keys[i].Mask = native.Uint32(htonl(key.Mask))
+ u32.Sel.Keys[i].Val = native.Uint32(htonl(key.Val))
+ }
+ }
+ case nl.TCA_U32_ACT:
+ tables, err := nl.ParseRouteAttr(datum.Value)
+ if err != nil {
+ return detailed, err
+ }
+ u32.Actions, err = parseActions(tables)
+ if err != nil {
+ return detailed, err
+ }
+ for _, action := range u32.Actions {
+ if action, ok := action.(*MirredAction); ok {
+ u32.RedirIndex = int(action.Ifindex)
+ }
+ }
+ case nl.TCA_U32_CLASSID:
+ u32.ClassId = native.Uint32(datum.Value)
+ }
+ }
+ return detailed, nil
+}
+
+func parseFwData(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) {
+ native = nl.NativeEndian()
+ fw := filter.(*Fw)
+ detailed := true
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_FW_MASK:
+ fw.Mask = native.Uint32(datum.Value[0:4])
+ case nl.TCA_FW_CLASSID:
+ fw.ClassId = native.Uint32(datum.Value[0:4])
+ case nl.TCA_FW_INDEV:
+ fw.InDev = string(datum.Value[:len(datum.Value)-1])
+ case nl.TCA_FW_POLICE:
+ adata, _ := nl.ParseRouteAttr(datum.Value)
+ for _, aattr := range adata {
+ switch aattr.Attr.Type {
+ case nl.TCA_POLICE_TBF:
+ fw.Police = *nl.DeserializeTcPolice(aattr.Value)
+ case nl.TCA_POLICE_RATE:
+ fw.Rtab = DeserializeRtab(aattr.Value)
+ case nl.TCA_POLICE_PEAKRATE:
+ fw.Ptab = DeserializeRtab(aattr.Value)
+ }
+ }
+ }
+ }
+ return detailed, nil
+}
+
+func parseBpfData(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) {
+ native = nl.NativeEndian()
+ bpf := filter.(*BpfFilter)
+ detailed := true
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_BPF_FD:
+ bpf.Fd = int(native.Uint32(datum.Value[0:4]))
+ case nl.TCA_BPF_NAME:
+ bpf.Name = string(datum.Value[:len(datum.Value)-1])
+ case nl.TCA_BPF_CLASSID:
+ bpf.ClassId = native.Uint32(datum.Value[0:4])
+ case nl.TCA_BPF_FLAGS:
+ flags := native.Uint32(datum.Value[0:4])
+ if (flags & nl.TCA_BPF_FLAG_ACT_DIRECT) != 0 {
+ bpf.DirectAction = true
+ }
+ }
+ }
+ return detailed, nil
+}
+
+func AlignToAtm(size uint) uint {
+ var linksize, cells int
+ cells = int(size / nl.ATM_CELL_PAYLOAD)
+ if (size % nl.ATM_CELL_PAYLOAD) > 0 {
+ cells++
+ }
+ linksize = cells * nl.ATM_CELL_SIZE
+ return uint(linksize)
+}
+
+func AdjustSize(sz uint, mpu uint, linklayer int) uint {
+ if sz < mpu {
+ sz = mpu
+ }
+ switch linklayer {
+ case nl.LINKLAYER_ATM:
+ return AlignToAtm(sz)
+ default:
+ return sz
+ }
+}
+
+func CalcRtable(rate *nl.TcRateSpec, rtab [256]uint32, cellLog int, mtu uint32, linklayer int) int {
+ bps := rate.Rate
+ mpu := rate.Mpu
+ var sz uint
+ if mtu == 0 {
+ mtu = 2047
+ }
+ if cellLog < 0 {
+ cellLog = 0
+ for (mtu >> uint(cellLog)) > 255 {
+ cellLog++
+ }
+ }
+ for i := 0; i < 256; i++ {
+ sz = AdjustSize(uint((i+1)<<uint32(cellLog)), uint(mpu), linklayer)
+ rtab[i] = uint32(Xmittime(uint64(bps), uint32(sz)))
+ }
+ rate.CellAlign = -1
+ rate.CellLog = uint8(cellLog)
+ rate.Linklayer = uint8(linklayer & nl.TC_LINKLAYER_MASK)
+ return cellLog
+}
+
+func DeserializeRtab(b []byte) [256]uint32 {
+ var rtab [256]uint32
+ native := nl.NativeEndian()
+ r := bytes.NewReader(b)
+ _ = binary.Read(r, native, &rtab)
+ return rtab
+}
+
+func SerializeRtab(rtab [256]uint32) []byte {
+ native := nl.NativeEndian()
+ var w bytes.Buffer
+ _ = binary.Write(&w, native, rtab)
+ return w.Bytes()
+}
diff --git a/vendor/github.com/vishvananda/netlink/genetlink_linux.go b/vendor/github.com/vishvananda/netlink/genetlink_linux.go
new file mode 100644
index 0000000..a388a87
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/genetlink_linux.go
@@ -0,0 +1,167 @@
+package netlink
+
+import (
+ "fmt"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+type GenlOp struct {
+ ID uint32
+ Flags uint32
+}
+
+type GenlMulticastGroup struct {
+ ID uint32
+ Name string
+}
+
+type GenlFamily struct {
+ ID uint16
+ HdrSize uint32
+ Name string
+ Version uint32
+ MaxAttr uint32
+ Ops []GenlOp
+ Groups []GenlMulticastGroup
+}
+
+func parseOps(b []byte) ([]GenlOp, error) {
+ attrs, err := nl.ParseRouteAttr(b)
+ if err != nil {
+ return nil, err
+ }
+ ops := make([]GenlOp, 0, len(attrs))
+ for _, a := range attrs {
+ nattrs, err := nl.ParseRouteAttr(a.Value)
+ if err != nil {
+ return nil, err
+ }
+ var op GenlOp
+ for _, na := range nattrs {
+ switch na.Attr.Type {
+ case nl.GENL_CTRL_ATTR_OP_ID:
+ op.ID = native.Uint32(na.Value)
+ case nl.GENL_CTRL_ATTR_OP_FLAGS:
+ op.Flags = native.Uint32(na.Value)
+ }
+ }
+ ops = append(ops, op)
+ }
+ return ops, nil
+}
+
+func parseMulticastGroups(b []byte) ([]GenlMulticastGroup, error) {
+ attrs, err := nl.ParseRouteAttr(b)
+ if err != nil {
+ return nil, err
+ }
+ groups := make([]GenlMulticastGroup, 0, len(attrs))
+ for _, a := range attrs {
+ nattrs, err := nl.ParseRouteAttr(a.Value)
+ if err != nil {
+ return nil, err
+ }
+ var g GenlMulticastGroup
+ for _, na := range nattrs {
+ switch na.Attr.Type {
+ case nl.GENL_CTRL_ATTR_MCAST_GRP_NAME:
+ g.Name = nl.BytesToString(na.Value)
+ case nl.GENL_CTRL_ATTR_MCAST_GRP_ID:
+ g.ID = native.Uint32(na.Value)
+ }
+ }
+ groups = append(groups, g)
+ }
+ return groups, nil
+}
+
+func (f *GenlFamily) parseAttributes(attrs []syscall.NetlinkRouteAttr) error {
+ for _, a := range attrs {
+ switch a.Attr.Type {
+ case nl.GENL_CTRL_ATTR_FAMILY_NAME:
+ f.Name = nl.BytesToString(a.Value)
+ case nl.GENL_CTRL_ATTR_FAMILY_ID:
+ f.ID = native.Uint16(a.Value)
+ case nl.GENL_CTRL_ATTR_VERSION:
+ f.Version = native.Uint32(a.Value)
+ case nl.GENL_CTRL_ATTR_HDRSIZE:
+ f.HdrSize = native.Uint32(a.Value)
+ case nl.GENL_CTRL_ATTR_MAXATTR:
+ f.MaxAttr = native.Uint32(a.Value)
+ case nl.GENL_CTRL_ATTR_OPS:
+ ops, err := parseOps(a.Value)
+ if err != nil {
+ return err
+ }
+ f.Ops = ops
+ case nl.GENL_CTRL_ATTR_MCAST_GROUPS:
+ groups, err := parseMulticastGroups(a.Value)
+ if err != nil {
+ return err
+ }
+ f.Groups = groups
+ }
+ }
+
+ return nil
+}
+
+func parseFamilies(msgs [][]byte) ([]*GenlFamily, error) {
+ families := make([]*GenlFamily, 0, len(msgs))
+ for _, m := range msgs {
+ attrs, err := nl.ParseRouteAttr(m[nl.SizeofGenlmsg:])
+ if err != nil {
+ return nil, err
+ }
+ family := &GenlFamily{}
+ if err := family.parseAttributes(attrs); err != nil {
+ return nil, err
+ }
+
+ families = append(families, family)
+ }
+ return families, nil
+}
+
+func (h *Handle) GenlFamilyList() ([]*GenlFamily, error) {
+ msg := &nl.Genlmsg{
+ Command: nl.GENL_CTRL_CMD_GETFAMILY,
+ Version: nl.GENL_CTRL_VERSION,
+ }
+ req := h.newNetlinkRequest(nl.GENL_ID_CTRL, syscall.NLM_F_DUMP)
+ req.AddData(msg)
+ msgs, err := req.Execute(syscall.NETLINK_GENERIC, 0)
+ if err != nil {
+ return nil, err
+ }
+ return parseFamilies(msgs)
+}
+
+func GenlFamilyList() ([]*GenlFamily, error) {
+ return pkgHandle.GenlFamilyList()
+}
+
+func (h *Handle) GenlFamilyGet(name string) (*GenlFamily, error) {
+ msg := &nl.Genlmsg{
+ Command: nl.GENL_CTRL_CMD_GETFAMILY,
+ Version: nl.GENL_CTRL_VERSION,
+ }
+ req := h.newNetlinkRequest(nl.GENL_ID_CTRL, 0)
+ req.AddData(msg)
+ req.AddData(nl.NewRtAttr(nl.GENL_CTRL_ATTR_FAMILY_NAME, nl.ZeroTerminated(name)))
+ msgs, err := req.Execute(syscall.NETLINK_GENERIC, 0)
+ if err != nil {
+ return nil, err
+ }
+ families, err := parseFamilies(msgs)
+ if len(families) != 1 {
+ return nil, fmt.Errorf("invalid response for GENL_CTRL_CMD_GETFAMILY")
+ }
+ return families[0], nil
+}
+
+func GenlFamilyGet(name string) (*GenlFamily, error) {
+ return pkgHandle.GenlFamilyGet(name)
+}
diff --git a/vendor/github.com/vishvananda/netlink/genetlink_unspecified.go b/vendor/github.com/vishvananda/netlink/genetlink_unspecified.go
new file mode 100644
index 0000000..0192b99
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/genetlink_unspecified.go
@@ -0,0 +1,25 @@
+// +build !linux
+
+package netlink
+
+type GenlOp struct{}
+
+type GenlMulticastGroup struct{}
+
+type GenlFamily struct{}
+
+func (h *Handle) GenlFamilyList() ([]*GenlFamily, error) {
+ return nil, ErrNotImplemented
+}
+
+func GenlFamilyList() ([]*GenlFamily, error) {
+ return nil, ErrNotImplemented
+}
+
+func (h *Handle) GenlFamilyGet(name string) (*GenlFamily, error) {
+ return nil, ErrNotImplemented
+}
+
+func GenlFamilyGet(name string) (*GenlFamily, error) {
+ return nil, ErrNotImplemented
+}
diff --git a/vendor/github.com/vishvananda/netlink/gtp_linux.go b/vendor/github.com/vishvananda/netlink/gtp_linux.go
new file mode 100644
index 0000000..7331303
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/gtp_linux.go
@@ -0,0 +1,238 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+ "strings"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+type PDP struct {
+ Version uint32
+ TID uint64
+ PeerAddress net.IP
+ MSAddress net.IP
+ Flow uint16
+ NetNSFD uint32
+ ITEI uint32
+ OTEI uint32
+}
+
+func (pdp *PDP) String() string {
+ elems := []string{}
+ elems = append(elems, fmt.Sprintf("Version: %d", pdp.Version))
+ if pdp.Version == 0 {
+ elems = append(elems, fmt.Sprintf("TID: %d", pdp.TID))
+ } else if pdp.Version == 1 {
+ elems = append(elems, fmt.Sprintf("TEI: %d/%d", pdp.ITEI, pdp.OTEI))
+ }
+ elems = append(elems, fmt.Sprintf("MS-Address: %s", pdp.MSAddress))
+ elems = append(elems, fmt.Sprintf("Peer-Address: %s", pdp.PeerAddress))
+ return fmt.Sprintf("{%s}", strings.Join(elems, " "))
+}
+
+func (p *PDP) parseAttributes(attrs []syscall.NetlinkRouteAttr) error {
+ for _, a := range attrs {
+ switch a.Attr.Type {
+ case nl.GENL_GTP_ATTR_VERSION:
+ p.Version = native.Uint32(a.Value)
+ case nl.GENL_GTP_ATTR_TID:
+ p.TID = native.Uint64(a.Value)
+ case nl.GENL_GTP_ATTR_PEER_ADDRESS:
+ p.PeerAddress = net.IP(a.Value)
+ case nl.GENL_GTP_ATTR_MS_ADDRESS:
+ p.MSAddress = net.IP(a.Value)
+ case nl.GENL_GTP_ATTR_FLOW:
+ p.Flow = native.Uint16(a.Value)
+ case nl.GENL_GTP_ATTR_NET_NS_FD:
+ p.NetNSFD = native.Uint32(a.Value)
+ case nl.GENL_GTP_ATTR_I_TEI:
+ p.ITEI = native.Uint32(a.Value)
+ case nl.GENL_GTP_ATTR_O_TEI:
+ p.OTEI = native.Uint32(a.Value)
+ }
+ }
+ return nil
+}
+
+func parsePDP(msgs [][]byte) ([]*PDP, error) {
+ pdps := make([]*PDP, 0, len(msgs))
+ for _, m := range msgs {
+ attrs, err := nl.ParseRouteAttr(m[nl.SizeofGenlmsg:])
+ if err != nil {
+ return nil, err
+ }
+ pdp := &PDP{}
+ if err := pdp.parseAttributes(attrs); err != nil {
+ return nil, err
+ }
+ pdps = append(pdps, pdp)
+ }
+ return pdps, nil
+}
+
+func (h *Handle) GTPPDPList() ([]*PDP, error) {
+ f, err := h.GenlFamilyGet(nl.GENL_GTP_NAME)
+ if err != nil {
+ return nil, err
+ }
+ msg := &nl.Genlmsg{
+ Command: nl.GENL_GTP_CMD_GETPDP,
+ Version: nl.GENL_GTP_VERSION,
+ }
+ req := h.newNetlinkRequest(int(f.ID), syscall.NLM_F_DUMP)
+ req.AddData(msg)
+ msgs, err := req.Execute(syscall.NETLINK_GENERIC, 0)
+ if err != nil {
+ return nil, err
+ }
+ return parsePDP(msgs)
+}
+
+func GTPPDPList() ([]*PDP, error) {
+ return pkgHandle.GTPPDPList()
+}
+
+func gtpPDPGet(req *nl.NetlinkRequest) (*PDP, error) {
+ msgs, err := req.Execute(syscall.NETLINK_GENERIC, 0)
+ if err != nil {
+ return nil, err
+ }
+ pdps, err := parsePDP(msgs)
+ if err != nil {
+ return nil, err
+ }
+ if len(pdps) != 1 {
+ return nil, fmt.Errorf("invalid reqponse for GENL_GTP_CMD_GETPDP")
+ }
+ return pdps[0], nil
+}
+
+func (h *Handle) GTPPDPByTID(link Link, tid int) (*PDP, error) {
+ f, err := h.GenlFamilyGet(nl.GENL_GTP_NAME)
+ if err != nil {
+ return nil, err
+ }
+ msg := &nl.Genlmsg{
+ Command: nl.GENL_GTP_CMD_GETPDP,
+ Version: nl.GENL_GTP_VERSION,
+ }
+ req := h.newNetlinkRequest(int(f.ID), 0)
+ req.AddData(msg)
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_VERSION, nl.Uint32Attr(0)))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_LINK, nl.Uint32Attr(uint32(link.Attrs().Index))))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_TID, nl.Uint64Attr(uint64(tid))))
+ return gtpPDPGet(req)
+}
+
+func GTPPDPByTID(link Link, tid int) (*PDP, error) {
+ return pkgHandle.GTPPDPByTID(link, tid)
+}
+
+func (h *Handle) GTPPDPByITEI(link Link, itei int) (*PDP, error) {
+ f, err := h.GenlFamilyGet(nl.GENL_GTP_NAME)
+ if err != nil {
+ return nil, err
+ }
+ msg := &nl.Genlmsg{
+ Command: nl.GENL_GTP_CMD_GETPDP,
+ Version: nl.GENL_GTP_VERSION,
+ }
+ req := h.newNetlinkRequest(int(f.ID), 0)
+ req.AddData(msg)
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_VERSION, nl.Uint32Attr(1)))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_LINK, nl.Uint32Attr(uint32(link.Attrs().Index))))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_I_TEI, nl.Uint32Attr(uint32(itei))))
+ return gtpPDPGet(req)
+}
+
+func GTPPDPByITEI(link Link, itei int) (*PDP, error) {
+ return pkgHandle.GTPPDPByITEI(link, itei)
+}
+
+func (h *Handle) GTPPDPByMSAddress(link Link, addr net.IP) (*PDP, error) {
+ f, err := h.GenlFamilyGet(nl.GENL_GTP_NAME)
+ if err != nil {
+ return nil, err
+ }
+ msg := &nl.Genlmsg{
+ Command: nl.GENL_GTP_CMD_GETPDP,
+ Version: nl.GENL_GTP_VERSION,
+ }
+ req := h.newNetlinkRequest(int(f.ID), 0)
+ req.AddData(msg)
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_VERSION, nl.Uint32Attr(0)))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_LINK, nl.Uint32Attr(uint32(link.Attrs().Index))))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_MS_ADDRESS, []byte(addr.To4())))
+ return gtpPDPGet(req)
+}
+
+func GTPPDPByMSAddress(link Link, addr net.IP) (*PDP, error) {
+ return pkgHandle.GTPPDPByMSAddress(link, addr)
+}
+
+func (h *Handle) GTPPDPAdd(link Link, pdp *PDP) error {
+ f, err := h.GenlFamilyGet(nl.GENL_GTP_NAME)
+ if err != nil {
+ return err
+ }
+ msg := &nl.Genlmsg{
+ Command: nl.GENL_GTP_CMD_NEWPDP,
+ Version: nl.GENL_GTP_VERSION,
+ }
+ req := h.newNetlinkRequest(int(f.ID), syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+ req.AddData(msg)
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_VERSION, nl.Uint32Attr(pdp.Version)))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_LINK, nl.Uint32Attr(uint32(link.Attrs().Index))))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_PEER_ADDRESS, []byte(pdp.PeerAddress.To4())))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_MS_ADDRESS, []byte(pdp.MSAddress.To4())))
+
+ switch pdp.Version {
+ case 0:
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_TID, nl.Uint64Attr(pdp.TID)))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_FLOW, nl.Uint16Attr(pdp.Flow)))
+ case 1:
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_I_TEI, nl.Uint32Attr(pdp.ITEI)))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_O_TEI, nl.Uint32Attr(pdp.OTEI)))
+ default:
+ return fmt.Errorf("unsupported GTP version: %d", pdp.Version)
+ }
+ _, err = req.Execute(syscall.NETLINK_GENERIC, 0)
+ return err
+}
+
+func GTPPDPAdd(link Link, pdp *PDP) error {
+ return pkgHandle.GTPPDPAdd(link, pdp)
+}
+
+func (h *Handle) GTPPDPDel(link Link, pdp *PDP) error {
+ f, err := h.GenlFamilyGet(nl.GENL_GTP_NAME)
+ if err != nil {
+ return err
+ }
+ msg := &nl.Genlmsg{
+ Command: nl.GENL_GTP_CMD_DELPDP,
+ Version: nl.GENL_GTP_VERSION,
+ }
+ req := h.newNetlinkRequest(int(f.ID), syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+ req.AddData(msg)
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_VERSION, nl.Uint32Attr(pdp.Version)))
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_LINK, nl.Uint32Attr(uint32(link.Attrs().Index))))
+
+ switch pdp.Version {
+ case 0:
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_TID, nl.Uint64Attr(pdp.TID)))
+ case 1:
+ req.AddData(nl.NewRtAttr(nl.GENL_GTP_ATTR_I_TEI, nl.Uint32Attr(pdp.ITEI)))
+ default:
+ return fmt.Errorf("unsupported GTP version: %d", pdp.Version)
+ }
+ _, err = req.Execute(syscall.NETLINK_GENERIC, 0)
+ return err
+}
+
+func GTPPDPDel(link Link, pdp *PDP) error {
+ return pkgHandle.GTPPDPDel(link, pdp)
+}
diff --git a/vendor/github.com/vishvananda/netlink/handle_linux.go b/vendor/github.com/vishvananda/netlink/handle_linux.go
new file mode 100644
index 0000000..a04ceae
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/handle_linux.go
@@ -0,0 +1,111 @@
+package netlink
+
+import (
+ "fmt"
+ "syscall"
+ "time"
+
+ "github.com/vishvananda/netlink/nl"
+ "github.com/vishvananda/netns"
+)
+
+// Empty handle used by the netlink package methods
+var pkgHandle = &Handle{}
+
+// Handle is an handle for the netlink requests on a
+// specific network namespace. All the requests on the
+// same netlink family share the same netlink socket,
+// which gets released when the handle is deleted.
+type Handle struct {
+ sockets map[int]*nl.SocketHandle
+ lookupByDump bool
+}
+
+// SupportsNetlinkFamily reports whether the passed netlink family is supported by this Handle
+func (h *Handle) SupportsNetlinkFamily(nlFamily int) bool {
+ _, ok := h.sockets[nlFamily]
+ return ok
+}
+
+// NewHandle returns a netlink handle on the current network namespace.
+// Caller may specify the netlink families the handle should support.
+// If no families are specified, all the families the netlink package
+// supports will be automatically added.
+func NewHandle(nlFamilies ...int) (*Handle, error) {
+ return newHandle(netns.None(), netns.None(), nlFamilies...)
+}
+
+// SetSocketTimeout sets the send and receive timeout for each socket in the
+// netlink handle. Although the socket timeout has granularity of one
+// microsecond, the effective granularity is floored by the kernel timer tick,
+// which default value is four milliseconds.
+func (h *Handle) SetSocketTimeout(to time.Duration) error {
+ if to < time.Microsecond {
+ return fmt.Errorf("invalid timeout, minimul value is %s", time.Microsecond)
+ }
+ tv := syscall.NsecToTimeval(to.Nanoseconds())
+ for _, sh := range h.sockets {
+ fd := sh.Socket.GetFd()
+ err := syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &tv)
+ if err != nil {
+ return err
+ }
+ err = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &tv)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// NewHandle returns a netlink handle on the network namespace
+// specified by ns. If ns=netns.None(), current network namespace
+// will be assumed
+func NewHandleAt(ns netns.NsHandle, nlFamilies ...int) (*Handle, error) {
+ return newHandle(ns, netns.None(), nlFamilies...)
+}
+
+// NewHandleAtFrom works as NewHandle but allows client to specify the
+// new and the origin netns Handle.
+func NewHandleAtFrom(newNs, curNs netns.NsHandle) (*Handle, error) {
+ return newHandle(newNs, curNs)
+}
+
+func newHandle(newNs, curNs netns.NsHandle, nlFamilies ...int) (*Handle, error) {
+ h := &Handle{sockets: map[int]*nl.SocketHandle{}}
+ fams := nl.SupportedNlFamilies
+ if len(nlFamilies) != 0 {
+ fams = nlFamilies
+ }
+ for _, f := range fams {
+ s, err := nl.GetNetlinkSocketAt(newNs, curNs, f)
+ if err != nil {
+ return nil, err
+ }
+ h.sockets[f] = &nl.SocketHandle{Socket: s}
+ }
+ return h, nil
+}
+
+// Delete releases the resources allocated to this handle
+func (h *Handle) Delete() {
+ for _, sh := range h.sockets {
+ sh.Close()
+ }
+ h.sockets = nil
+}
+
+func (h *Handle) newNetlinkRequest(proto, flags int) *nl.NetlinkRequest {
+ // Do this so that package API still use nl package variable nextSeqNr
+ if h.sockets == nil {
+ return nl.NewNetlinkRequest(proto, flags)
+ }
+ return &nl.NetlinkRequest{
+ NlMsghdr: syscall.NlMsghdr{
+ Len: uint32(syscall.SizeofNlMsghdr),
+ Type: uint16(proto),
+ Flags: syscall.NLM_F_REQUEST | uint16(flags),
+ },
+ Sockets: h.sockets,
+ }
+}
diff --git a/vendor/github.com/vishvananda/netlink/handle_unspecified.go b/vendor/github.com/vishvananda/netlink/handle_unspecified.go
new file mode 100644
index 0000000..32cf022
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/handle_unspecified.go
@@ -0,0 +1,218 @@
+// +build !linux
+
+package netlink
+
+import (
+ "net"
+ "time"
+
+ "github.com/vishvananda/netns"
+)
+
+type Handle struct{}
+
+func NewHandle(nlFamilies ...int) (*Handle, error) {
+ return nil, ErrNotImplemented
+}
+
+func NewHandleAt(ns netns.NsHandle, nlFamilies ...int) (*Handle, error) {
+ return nil, ErrNotImplemented
+}
+
+func NewHandleAtFrom(newNs, curNs netns.NsHandle) (*Handle, error) {
+ return nil, ErrNotImplemented
+}
+
+func (h *Handle) Delete() {}
+
+func (h *Handle) SupportsNetlinkFamily(nlFamily int) bool {
+ return false
+}
+
+func (h *Handle) SetSocketTimeout(to time.Duration) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) SetPromiscOn(link Link) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) SetPromiscOff(link Link) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetUp(link Link) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetDown(link Link) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetMTU(link Link, mtu int) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetName(link Link, name string) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetAlias(link Link, name string) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetVfVlan(link Link, vf, vlan int) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetVfTxRate(link Link, vf, rate int) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetMaster(link Link, master *Bridge) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetNoMaster(link Link) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetMasterByIndex(link Link, masterIndex int) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetNsPid(link Link, nspid int) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetNsFd(link Link, fd int) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkAdd(link Link) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkDel(link Link) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkByName(name string) (Link, error) {
+ return nil, ErrNotImplemented
+}
+
+func (h *Handle) LinkByAlias(alias string) (Link, error) {
+ return nil, ErrNotImplemented
+}
+
+func (h *Handle) LinkByIndex(index int) (Link, error) {
+ return nil, ErrNotImplemented
+}
+
+func (h *Handle) LinkList() ([]Link, error) {
+ return nil, ErrNotImplemented
+}
+
+func (h *Handle) LinkSetHairpin(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetGuard(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetFastLeave(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetLearning(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetRootBlock(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) LinkSetFlood(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) setProtinfoAttr(link Link, mode bool, attr int) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) AddrAdd(link Link, addr *Addr) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) AddrDel(link Link, addr *Addr) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) AddrList(link Link, family int) ([]Addr, error) {
+ return nil, ErrNotImplemented
+}
+
+func (h *Handle) ClassDel(class Class) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) ClassChange(class Class) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) ClassReplace(class Class) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) ClassAdd(class Class) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) ClassList(link Link, parent uint32) ([]Class, error) {
+ return nil, ErrNotImplemented
+}
+
+func (h *Handle) FilterDel(filter Filter) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) FilterAdd(filter Filter) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) FilterList(link Link, parent uint32) ([]Filter, error) {
+ return nil, ErrNotImplemented
+}
+
+func (h *Handle) NeighAdd(neigh *Neigh) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) NeighSet(neigh *Neigh) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) NeighAppend(neigh *Neigh) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) NeighDel(neigh *Neigh) error {
+ return ErrNotImplemented
+}
+
+func (h *Handle) NeighList(linkIndex, family int) ([]Neigh, error) {
+ return nil, ErrNotImplemented
+}
+
+func (h *Handle) NeighProxyList(linkIndex, family int) ([]Neigh, error) {
+ return nil, ErrNotImplemented
+}
diff --git a/vendor/github.com/vishvananda/netlink/link.go b/vendor/github.com/vishvananda/netlink/link.go
new file mode 100644
index 0000000..547e92e
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/link.go
@@ -0,0 +1,773 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+)
+
+// Link represents a link device from netlink. Shared link attributes
+// like name may be retrieved using the Attrs() method. Unique data
+// can be retrieved by casting the object to the proper type.
+type Link interface {
+ Attrs() *LinkAttrs
+ Type() string
+}
+
+type (
+ NsPid int
+ NsFd int
+)
+
+// LinkAttrs represents data shared by most link types
+type LinkAttrs struct {
+ Index int
+ MTU int
+ TxQLen int // Transmit Queue Length
+ Name string
+ HardwareAddr net.HardwareAddr
+ Flags net.Flags
+ RawFlags uint32
+ ParentIndex int // index of the parent link device
+ MasterIndex int // must be the index of a bridge
+ Namespace interface{} // nil | NsPid | NsFd
+ Alias string
+ Statistics *LinkStatistics
+ Promisc int
+ Xdp *LinkXdp
+ EncapType string
+ Protinfo *Protinfo
+ OperState LinkOperState
+}
+
+// LinkOperState represents the values of the IFLA_OPERSTATE link
+// attribute, which contains the RFC2863 state of the interface.
+type LinkOperState uint8
+
+const (
+ OperUnknown = iota // Status can't be determined.
+ OperNotPresent // Some component is missing.
+ OperDown // Down.
+ OperLowerLayerDown // Down due to state of lower layer.
+ OperTesting // In some test mode.
+ OperDormant // Not up but pending an external event.
+ OperUp // Up, ready to send packets.
+)
+
+func (s LinkOperState) String() string {
+ switch s {
+ case OperNotPresent:
+ return "not-present"
+ case OperDown:
+ return "down"
+ case OperLowerLayerDown:
+ return "lower-layer-down"
+ case OperTesting:
+ return "testing"
+ case OperDormant:
+ return "dormant"
+ case OperUp:
+ return "up"
+ default:
+ return "unknown"
+ }
+}
+
+// NewLinkAttrs returns LinkAttrs structure filled with default values
+func NewLinkAttrs() LinkAttrs {
+ return LinkAttrs{
+ TxQLen: -1,
+ }
+}
+
+type LinkStatistics LinkStatistics64
+
+/*
+Ref: struct rtnl_link_stats {...}
+*/
+type LinkStatistics32 struct {
+ RxPackets uint32
+ TxPackets uint32
+ RxBytes uint32
+ TxBytes uint32
+ RxErrors uint32
+ TxErrors uint32
+ RxDropped uint32
+ TxDropped uint32
+ Multicast uint32
+ Collisions uint32
+ RxLengthErrors uint32
+ RxOverErrors uint32
+ RxCrcErrors uint32
+ RxFrameErrors uint32
+ RxFifoErrors uint32
+ RxMissedErrors uint32
+ TxAbortedErrors uint32
+ TxCarrierErrors uint32
+ TxFifoErrors uint32
+ TxHeartbeatErrors uint32
+ TxWindowErrors uint32
+ RxCompressed uint32
+ TxCompressed uint32
+}
+
+func (s32 LinkStatistics32) to64() *LinkStatistics64 {
+ return &LinkStatistics64{
+ RxPackets: uint64(s32.RxPackets),
+ TxPackets: uint64(s32.TxPackets),
+ RxBytes: uint64(s32.RxBytes),
+ TxBytes: uint64(s32.TxBytes),
+ RxErrors: uint64(s32.RxErrors),
+ TxErrors: uint64(s32.TxErrors),
+ RxDropped: uint64(s32.RxDropped),
+ TxDropped: uint64(s32.TxDropped),
+ Multicast: uint64(s32.Multicast),
+ Collisions: uint64(s32.Collisions),
+ RxLengthErrors: uint64(s32.RxLengthErrors),
+ RxOverErrors: uint64(s32.RxOverErrors),
+ RxCrcErrors: uint64(s32.RxCrcErrors),
+ RxFrameErrors: uint64(s32.RxFrameErrors),
+ RxFifoErrors: uint64(s32.RxFifoErrors),
+ RxMissedErrors: uint64(s32.RxMissedErrors),
+ TxAbortedErrors: uint64(s32.TxAbortedErrors),
+ TxCarrierErrors: uint64(s32.TxCarrierErrors),
+ TxFifoErrors: uint64(s32.TxFifoErrors),
+ TxHeartbeatErrors: uint64(s32.TxHeartbeatErrors),
+ TxWindowErrors: uint64(s32.TxWindowErrors),
+ RxCompressed: uint64(s32.RxCompressed),
+ TxCompressed: uint64(s32.TxCompressed),
+ }
+}
+
+/*
+Ref: struct rtnl_link_stats64 {...}
+*/
+type LinkStatistics64 struct {
+ RxPackets uint64
+ TxPackets uint64
+ RxBytes uint64
+ TxBytes uint64
+ RxErrors uint64
+ TxErrors uint64
+ RxDropped uint64
+ TxDropped uint64
+ Multicast uint64
+ Collisions uint64
+ RxLengthErrors uint64
+ RxOverErrors uint64
+ RxCrcErrors uint64
+ RxFrameErrors uint64
+ RxFifoErrors uint64
+ RxMissedErrors uint64
+ TxAbortedErrors uint64
+ TxCarrierErrors uint64
+ TxFifoErrors uint64
+ TxHeartbeatErrors uint64
+ TxWindowErrors uint64
+ RxCompressed uint64
+ TxCompressed uint64
+}
+
+type LinkXdp struct {
+ Fd int
+ Attached bool
+ Flags uint32
+}
+
+// Device links cannot be created via netlink. These links
+// are links created by udev like 'lo' and 'etho0'
+type Device struct {
+ LinkAttrs
+}
+
+func (device *Device) Attrs() *LinkAttrs {
+ return &device.LinkAttrs
+}
+
+func (device *Device) Type() string {
+ return "device"
+}
+
+// Dummy links are dummy ethernet devices
+type Dummy struct {
+ LinkAttrs
+}
+
+func (dummy *Dummy) Attrs() *LinkAttrs {
+ return &dummy.LinkAttrs
+}
+
+func (dummy *Dummy) Type() string {
+ return "dummy"
+}
+
+// Ifb links are advanced dummy devices for packet filtering
+type Ifb struct {
+ LinkAttrs
+}
+
+func (ifb *Ifb) Attrs() *LinkAttrs {
+ return &ifb.LinkAttrs
+}
+
+func (ifb *Ifb) Type() string {
+ return "ifb"
+}
+
+// Bridge links are simple linux bridges
+type Bridge struct {
+ LinkAttrs
+ MulticastSnooping *bool
+ HelloTime *uint32
+}
+
+func (bridge *Bridge) Attrs() *LinkAttrs {
+ return &bridge.LinkAttrs
+}
+
+func (bridge *Bridge) Type() string {
+ return "bridge"
+}
+
+// Vlan links have ParentIndex set in their Attrs()
+type Vlan struct {
+ LinkAttrs
+ VlanId int
+}
+
+func (vlan *Vlan) Attrs() *LinkAttrs {
+ return &vlan.LinkAttrs
+}
+
+func (vlan *Vlan) Type() string {
+ return "vlan"
+}
+
+type MacvlanMode uint16
+
+const (
+ MACVLAN_MODE_DEFAULT MacvlanMode = iota
+ MACVLAN_MODE_PRIVATE
+ MACVLAN_MODE_VEPA
+ MACVLAN_MODE_BRIDGE
+ MACVLAN_MODE_PASSTHRU
+ MACVLAN_MODE_SOURCE
+)
+
+// Macvlan links have ParentIndex set in their Attrs()
+type Macvlan struct {
+ LinkAttrs
+ Mode MacvlanMode
+}
+
+func (macvlan *Macvlan) Attrs() *LinkAttrs {
+ return &macvlan.LinkAttrs
+}
+
+func (macvlan *Macvlan) Type() string {
+ return "macvlan"
+}
+
+// Macvtap - macvtap is a virtual interfaces based on macvlan
+type Macvtap struct {
+ Macvlan
+}
+
+func (macvtap Macvtap) Type() string {
+ return "macvtap"
+}
+
+type TuntapMode uint16
+type TuntapFlag uint16
+
+// Tuntap links created via /dev/tun/tap, but can be destroyed via netlink
+type Tuntap struct {
+ LinkAttrs
+ Mode TuntapMode
+ Flags TuntapFlag
+}
+
+func (tuntap *Tuntap) Attrs() *LinkAttrs {
+ return &tuntap.LinkAttrs
+}
+
+func (tuntap *Tuntap) Type() string {
+ return "tuntap"
+}
+
+// Veth devices must specify PeerName on create
+type Veth struct {
+ LinkAttrs
+ PeerName string // veth on create only
+}
+
+func (veth *Veth) Attrs() *LinkAttrs {
+ return &veth.LinkAttrs
+}
+
+func (veth *Veth) Type() string {
+ return "veth"
+}
+
+// GenericLink links represent types that are not currently understood
+// by this netlink library.
+type GenericLink struct {
+ LinkAttrs
+ LinkType string
+}
+
+func (generic *GenericLink) Attrs() *LinkAttrs {
+ return &generic.LinkAttrs
+}
+
+func (generic *GenericLink) Type() string {
+ return generic.LinkType
+}
+
+type Vxlan struct {
+ LinkAttrs
+ VxlanId int
+ VtepDevIndex int
+ SrcAddr net.IP
+ Group net.IP
+ TTL int
+ TOS int
+ Learning bool
+ Proxy bool
+ RSC bool
+ L2miss bool
+ L3miss bool
+ UDPCSum bool
+ NoAge bool
+ GBP bool
+ Age int
+ Limit int
+ Port int
+ PortLow int
+ PortHigh int
+}
+
+func (vxlan *Vxlan) Attrs() *LinkAttrs {
+ return &vxlan.LinkAttrs
+}
+
+func (vxlan *Vxlan) Type() string {
+ return "vxlan"
+}
+
+type IPVlanMode uint16
+
+const (
+ IPVLAN_MODE_L2 IPVlanMode = iota
+ IPVLAN_MODE_L3
+ IPVLAN_MODE_L3S
+ IPVLAN_MODE_MAX
+)
+
+type IPVlan struct {
+ LinkAttrs
+ Mode IPVlanMode
+}
+
+func (ipvlan *IPVlan) Attrs() *LinkAttrs {
+ return &ipvlan.LinkAttrs
+}
+
+func (ipvlan *IPVlan) Type() string {
+ return "ipvlan"
+}
+
+// BondMode type
+type BondMode int
+
+func (b BondMode) String() string {
+ s, ok := bondModeToString[b]
+ if !ok {
+ return fmt.Sprintf("BondMode(%d)", b)
+ }
+ return s
+}
+
+// StringToBondMode returns bond mode, or uknonw is the s is invalid.
+func StringToBondMode(s string) BondMode {
+ mode, ok := StringToBondModeMap[s]
+ if !ok {
+ return BOND_MODE_UNKNOWN
+ }
+ return mode
+}
+
+// Possible BondMode
+const (
+ BOND_MODE_BALANCE_RR BondMode = iota
+ BOND_MODE_ACTIVE_BACKUP
+ BOND_MODE_BALANCE_XOR
+ BOND_MODE_BROADCAST
+ BOND_MODE_802_3AD
+ BOND_MODE_BALANCE_TLB
+ BOND_MODE_BALANCE_ALB
+ BOND_MODE_UNKNOWN
+)
+
+var bondModeToString = map[BondMode]string{
+ BOND_MODE_BALANCE_RR: "balance-rr",
+ BOND_MODE_ACTIVE_BACKUP: "active-backup",
+ BOND_MODE_BALANCE_XOR: "balance-xor",
+ BOND_MODE_BROADCAST: "broadcast",
+ BOND_MODE_802_3AD: "802.3ad",
+ BOND_MODE_BALANCE_TLB: "balance-tlb",
+ BOND_MODE_BALANCE_ALB: "balance-alb",
+}
+var StringToBondModeMap = map[string]BondMode{
+ "balance-rr": BOND_MODE_BALANCE_RR,
+ "active-backup": BOND_MODE_ACTIVE_BACKUP,
+ "balance-xor": BOND_MODE_BALANCE_XOR,
+ "broadcast": BOND_MODE_BROADCAST,
+ "802.3ad": BOND_MODE_802_3AD,
+ "balance-tlb": BOND_MODE_BALANCE_TLB,
+ "balance-alb": BOND_MODE_BALANCE_ALB,
+}
+
+// BondArpValidate type
+type BondArpValidate int
+
+// Possible BondArpValidate value
+const (
+ BOND_ARP_VALIDATE_NONE BondArpValidate = iota
+ BOND_ARP_VALIDATE_ACTIVE
+ BOND_ARP_VALIDATE_BACKUP
+ BOND_ARP_VALIDATE_ALL
+)
+
+// BondPrimaryReselect type
+type BondPrimaryReselect int
+
+// Possible BondPrimaryReselect value
+const (
+ BOND_PRIMARY_RESELECT_ALWAYS BondPrimaryReselect = iota
+ BOND_PRIMARY_RESELECT_BETTER
+ BOND_PRIMARY_RESELECT_FAILURE
+)
+
+// BondArpAllTargets type
+type BondArpAllTargets int
+
+// Possible BondArpAllTargets value
+const (
+ BOND_ARP_ALL_TARGETS_ANY BondArpAllTargets = iota
+ BOND_ARP_ALL_TARGETS_ALL
+)
+
+// BondFailOverMac type
+type BondFailOverMac int
+
+// Possible BondFailOverMac value
+const (
+ BOND_FAIL_OVER_MAC_NONE BondFailOverMac = iota
+ BOND_FAIL_OVER_MAC_ACTIVE
+ BOND_FAIL_OVER_MAC_FOLLOW
+)
+
+// BondXmitHashPolicy type
+type BondXmitHashPolicy int
+
+func (b BondXmitHashPolicy) String() string {
+ s, ok := bondXmitHashPolicyToString[b]
+ if !ok {
+ return fmt.Sprintf("XmitHashPolicy(%d)", b)
+ }
+ return s
+}
+
+// StringToBondXmitHashPolicy returns bond lacp arte, or uknonw is the s is invalid.
+func StringToBondXmitHashPolicy(s string) BondXmitHashPolicy {
+ lacp, ok := StringToBondXmitHashPolicyMap[s]
+ if !ok {
+ return BOND_XMIT_HASH_POLICY_UNKNOWN
+ }
+ return lacp
+}
+
+// Possible BondXmitHashPolicy value
+const (
+ BOND_XMIT_HASH_POLICY_LAYER2 BondXmitHashPolicy = iota
+ BOND_XMIT_HASH_POLICY_LAYER3_4
+ BOND_XMIT_HASH_POLICY_LAYER2_3
+ BOND_XMIT_HASH_POLICY_ENCAP2_3
+ BOND_XMIT_HASH_POLICY_ENCAP3_4
+ BOND_XMIT_HASH_POLICY_UNKNOWN
+)
+
+var bondXmitHashPolicyToString = map[BondXmitHashPolicy]string{
+ BOND_XMIT_HASH_POLICY_LAYER2: "layer2",
+ BOND_XMIT_HASH_POLICY_LAYER3_4: "layer3+4",
+ BOND_XMIT_HASH_POLICY_LAYER2_3: "layer2+3",
+ BOND_XMIT_HASH_POLICY_ENCAP2_3: "encap2+3",
+ BOND_XMIT_HASH_POLICY_ENCAP3_4: "encap3+4",
+}
+var StringToBondXmitHashPolicyMap = map[string]BondXmitHashPolicy{
+ "layer2": BOND_XMIT_HASH_POLICY_LAYER2,
+ "layer3+4": BOND_XMIT_HASH_POLICY_LAYER3_4,
+ "layer2+3": BOND_XMIT_HASH_POLICY_LAYER2_3,
+ "encap2+3": BOND_XMIT_HASH_POLICY_ENCAP2_3,
+ "encap3+4": BOND_XMIT_HASH_POLICY_ENCAP3_4,
+}
+
+// BondLacpRate type
+type BondLacpRate int
+
+func (b BondLacpRate) String() string {
+ s, ok := bondLacpRateToString[b]
+ if !ok {
+ return fmt.Sprintf("LacpRate(%d)", b)
+ }
+ return s
+}
+
+// StringToBondLacpRate returns bond lacp arte, or uknonw is the s is invalid.
+func StringToBondLacpRate(s string) BondLacpRate {
+ lacp, ok := StringToBondLacpRateMap[s]
+ if !ok {
+ return BOND_LACP_RATE_UNKNOWN
+ }
+ return lacp
+}
+
+// Possible BondLacpRate value
+const (
+ BOND_LACP_RATE_SLOW BondLacpRate = iota
+ BOND_LACP_RATE_FAST
+ BOND_LACP_RATE_UNKNOWN
+)
+
+var bondLacpRateToString = map[BondLacpRate]string{
+ BOND_LACP_RATE_SLOW: "slow",
+ BOND_LACP_RATE_FAST: "fast",
+}
+var StringToBondLacpRateMap = map[string]BondLacpRate{
+ "slow": BOND_LACP_RATE_SLOW,
+ "fast": BOND_LACP_RATE_FAST,
+}
+
+// BondAdSelect type
+type BondAdSelect int
+
+// Possible BondAdSelect value
+const (
+ BOND_AD_SELECT_STABLE BondAdSelect = iota
+ BOND_AD_SELECT_BANDWIDTH
+ BOND_AD_SELECT_COUNT
+)
+
+// BondAdInfo represents ad info for bond
+type BondAdInfo struct {
+ AggregatorId int
+ NumPorts int
+ ActorKey int
+ PartnerKey int
+ PartnerMac net.HardwareAddr
+}
+
+// Bond representation
+type Bond struct {
+ LinkAttrs
+ Mode BondMode
+ ActiveSlave int
+ Miimon int
+ UpDelay int
+ DownDelay int
+ UseCarrier int
+ ArpInterval int
+ ArpIpTargets []net.IP
+ ArpValidate BondArpValidate
+ ArpAllTargets BondArpAllTargets
+ Primary int
+ PrimaryReselect BondPrimaryReselect
+ FailOverMac BondFailOverMac
+ XmitHashPolicy BondXmitHashPolicy
+ ResendIgmp int
+ NumPeerNotif int
+ AllSlavesActive int
+ MinLinks int
+ LpInterval int
+ PackersPerSlave int
+ LacpRate BondLacpRate
+ AdSelect BondAdSelect
+ // looking at iproute tool AdInfo can only be retrived. It can't be set.
+ AdInfo *BondAdInfo
+ AdActorSysPrio int
+ AdUserPortKey int
+ AdActorSystem net.HardwareAddr
+ TlbDynamicLb int
+}
+
+func NewLinkBond(atr LinkAttrs) *Bond {
+ return &Bond{
+ LinkAttrs: atr,
+ Mode: -1,
+ ActiveSlave: -1,
+ Miimon: -1,
+ UpDelay: -1,
+ DownDelay: -1,
+ UseCarrier: -1,
+ ArpInterval: -1,
+ ArpIpTargets: nil,
+ ArpValidate: -1,
+ ArpAllTargets: -1,
+ Primary: -1,
+ PrimaryReselect: -1,
+ FailOverMac: -1,
+ XmitHashPolicy: -1,
+ ResendIgmp: -1,
+ NumPeerNotif: -1,
+ AllSlavesActive: -1,
+ MinLinks: -1,
+ LpInterval: -1,
+ PackersPerSlave: -1,
+ LacpRate: -1,
+ AdSelect: -1,
+ AdActorSysPrio: -1,
+ AdUserPortKey: -1,
+ AdActorSystem: nil,
+ TlbDynamicLb: -1,
+ }
+}
+
+// Flag mask for bond options. Bond.Flagmask must be set to on for option to work.
+const (
+ BOND_MODE_MASK uint64 = 1 << (1 + iota)
+ BOND_ACTIVE_SLAVE_MASK
+ BOND_MIIMON_MASK
+ BOND_UPDELAY_MASK
+ BOND_DOWNDELAY_MASK
+ BOND_USE_CARRIER_MASK
+ BOND_ARP_INTERVAL_MASK
+ BOND_ARP_VALIDATE_MASK
+ BOND_ARP_ALL_TARGETS_MASK
+ BOND_PRIMARY_MASK
+ BOND_PRIMARY_RESELECT_MASK
+ BOND_FAIL_OVER_MAC_MASK
+ BOND_XMIT_HASH_POLICY_MASK
+ BOND_RESEND_IGMP_MASK
+ BOND_NUM_PEER_NOTIF_MASK
+ BOND_ALL_SLAVES_ACTIVE_MASK
+ BOND_MIN_LINKS_MASK
+ BOND_LP_INTERVAL_MASK
+ BOND_PACKETS_PER_SLAVE_MASK
+ BOND_LACP_RATE_MASK
+ BOND_AD_SELECT_MASK
+)
+
+// Attrs implementation.
+func (bond *Bond) Attrs() *LinkAttrs {
+ return &bond.LinkAttrs
+}
+
+// Type implementation fro Vxlan.
+func (bond *Bond) Type() string {
+ return "bond"
+}
+
+// Gretap devices must specify LocalIP and RemoteIP on create
+type Gretap struct {
+ LinkAttrs
+ IKey uint32
+ OKey uint32
+ EncapSport uint16
+ EncapDport uint16
+ Local net.IP
+ Remote net.IP
+ IFlags uint16
+ OFlags uint16
+ PMtuDisc uint8
+ Ttl uint8
+ Tos uint8
+ EncapType uint16
+ EncapFlags uint16
+ Link uint32
+}
+
+func (gretap *Gretap) Attrs() *LinkAttrs {
+ return &gretap.LinkAttrs
+}
+
+func (gretap *Gretap) Type() string {
+ return "gretap"
+}
+
+type Iptun struct {
+ LinkAttrs
+ Ttl uint8
+ Tos uint8
+ PMtuDisc uint8
+ Link uint32
+ Local net.IP
+ Remote net.IP
+}
+
+func (iptun *Iptun) Attrs() *LinkAttrs {
+ return &iptun.LinkAttrs
+}
+
+func (iptun *Iptun) Type() string {
+ return "ipip"
+}
+
+type Vti struct {
+ LinkAttrs
+ IKey uint32
+ OKey uint32
+ Link uint32
+ Local net.IP
+ Remote net.IP
+}
+
+func (vti *Vti) Attrs() *LinkAttrs {
+ return &vti.LinkAttrs
+}
+
+func (iptun *Vti) Type() string {
+ return "vti"
+}
+
+type Vrf struct {
+ LinkAttrs
+ Table uint32
+}
+
+func (vrf *Vrf) Attrs() *LinkAttrs {
+ return &vrf.LinkAttrs
+}
+
+func (vrf *Vrf) Type() string {
+ return "vrf"
+}
+
+type GTP struct {
+ LinkAttrs
+ FD0 int
+ FD1 int
+ Role int
+ PDPHashsize int
+}
+
+func (gtp *GTP) Attrs() *LinkAttrs {
+ return &gtp.LinkAttrs
+}
+
+func (gtp *GTP) Type() string {
+ return "gtp"
+}
+
+// iproute2 supported devices;
+// vlan | veth | vcan | dummy | ifb | macvlan | macvtap |
+// bridge | bond | ipoib | ip6tnl | ipip | sit | vxlan |
+// gre | gretap | ip6gre | ip6gretap | vti | nlmon |
+// bond_slave | ipvlan
+
+// LinkNotFoundError wraps the various not found errors when
+// getting/reading links. This is intended for better error
+// handling by dependent code so that "not found error" can
+// be distinguished from other errors
+type LinkNotFoundError struct {
+ error
+}
diff --git a/vendor/github.com/vishvananda/netlink/link_linux.go b/vendor/github.com/vishvananda/netlink/link_linux.go
new file mode 100644
index 0000000..1c1bc52
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/link_linux.go
@@ -0,0 +1,1798 @@
+package netlink
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "net"
+ "os"
+ "syscall"
+ "unsafe"
+
+ "github.com/vishvananda/netlink/nl"
+ "github.com/vishvananda/netns"
+)
+
+const (
+ SizeofLinkStats32 = 0x5c
+ SizeofLinkStats64 = 0xd8
+ IFLA_STATS64 = 0x17 // syscall pkg does not contain this one
+)
+
+const (
+ TUNTAP_MODE_TUN TuntapMode = syscall.IFF_TUN
+ TUNTAP_MODE_TAP TuntapMode = syscall.IFF_TAP
+ TUNTAP_DEFAULTS TuntapFlag = syscall.IFF_TUN_EXCL | syscall.IFF_ONE_QUEUE
+ TUNTAP_VNET_HDR TuntapFlag = syscall.IFF_VNET_HDR
+ TUNTAP_TUN_EXCL TuntapFlag = syscall.IFF_TUN_EXCL
+ TUNTAP_NO_PI TuntapFlag = syscall.IFF_NO_PI
+ TUNTAP_ONE_QUEUE TuntapFlag = syscall.IFF_ONE_QUEUE
+)
+
+var lookupByDump = false
+
+var macvlanModes = [...]uint32{
+ 0,
+ nl.MACVLAN_MODE_PRIVATE,
+ nl.MACVLAN_MODE_VEPA,
+ nl.MACVLAN_MODE_BRIDGE,
+ nl.MACVLAN_MODE_PASSTHRU,
+ nl.MACVLAN_MODE_SOURCE,
+}
+
+func ensureIndex(link *LinkAttrs) {
+ if link != nil && link.Index == 0 {
+ newlink, _ := LinkByName(link.Name)
+ if newlink != nil {
+ link.Index = newlink.Attrs().Index
+ }
+ }
+}
+
+func (h *Handle) ensureIndex(link *LinkAttrs) {
+ if link != nil && link.Index == 0 {
+ newlink, _ := h.LinkByName(link.Name)
+ if newlink != nil {
+ link.Index = newlink.Attrs().Index
+ }
+ }
+}
+
+func (h *Handle) LinkSetARPOff(link Link) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Change |= syscall.IFF_NOARP
+ msg.Flags |= syscall.IFF_NOARP
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+func LinkSetARPOff(link Link) error {
+ return pkgHandle.LinkSetARPOff(link)
+}
+
+func (h *Handle) LinkSetARPOn(link Link) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Change |= syscall.IFF_NOARP
+ msg.Flags &= ^uint32(syscall.IFF_NOARP)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+func LinkSetARPOn(link Link) error {
+ return pkgHandle.LinkSetARPOn(link)
+}
+
+func (h *Handle) SetPromiscOn(link Link) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Change = syscall.IFF_PROMISC
+ msg.Flags = syscall.IFF_PROMISC
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+func BridgeSetMcastSnoop(link Link, on bool) error {
+ return pkgHandle.BridgeSetMcastSnoop(link, on)
+}
+
+func (h *Handle) BridgeSetMcastSnoop(link Link, on bool) error {
+ bridge := link.(*Bridge)
+ bridge.MulticastSnooping = &on
+ return h.linkModify(bridge, syscall.NLM_F_ACK)
+}
+
+func SetPromiscOn(link Link) error {
+ return pkgHandle.SetPromiscOn(link)
+}
+
+func (h *Handle) SetPromiscOff(link Link) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Change = syscall.IFF_PROMISC
+ msg.Flags = 0 & ^syscall.IFF_PROMISC
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+func SetPromiscOff(link Link) error {
+ return pkgHandle.SetPromiscOff(link)
+}
+
+// LinkSetUp enables the link device.
+// Equivalent to: `ip link set $link up`
+func LinkSetUp(link Link) error {
+ return pkgHandle.LinkSetUp(link)
+}
+
+// LinkSetUp enables the link device.
+// Equivalent to: `ip link set $link up`
+func (h *Handle) LinkSetUp(link Link) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Change = syscall.IFF_UP
+ msg.Flags = syscall.IFF_UP
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetDown disables link device.
+// Equivalent to: `ip link set $link down`
+func LinkSetDown(link Link) error {
+ return pkgHandle.LinkSetDown(link)
+}
+
+// LinkSetDown disables link device.
+// Equivalent to: `ip link set $link down`
+func (h *Handle) LinkSetDown(link Link) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Change = syscall.IFF_UP
+ msg.Flags = 0 & ^syscall.IFF_UP
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetMTU sets the mtu of the link device.
+// Equivalent to: `ip link set $link mtu $mtu`
+func LinkSetMTU(link Link, mtu int) error {
+ return pkgHandle.LinkSetMTU(link, mtu)
+}
+
+// LinkSetMTU sets the mtu of the link device.
+// Equivalent to: `ip link set $link mtu $mtu`
+func (h *Handle) LinkSetMTU(link Link, mtu int) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(mtu))
+
+ data := nl.NewRtAttr(syscall.IFLA_MTU, b)
+ req.AddData(data)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetName sets the name of the link device.
+// Equivalent to: `ip link set $link name $name`
+func LinkSetName(link Link, name string) error {
+ return pkgHandle.LinkSetName(link, name)
+}
+
+// LinkSetName sets the name of the link device.
+// Equivalent to: `ip link set $link name $name`
+func (h *Handle) LinkSetName(link Link, name string) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ data := nl.NewRtAttr(syscall.IFLA_IFNAME, []byte(name))
+ req.AddData(data)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetAlias sets the alias of the link device.
+// Equivalent to: `ip link set dev $link alias $name`
+func LinkSetAlias(link Link, name string) error {
+ return pkgHandle.LinkSetAlias(link, name)
+}
+
+// LinkSetAlias sets the alias of the link device.
+// Equivalent to: `ip link set dev $link alias $name`
+func (h *Handle) LinkSetAlias(link Link, name string) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ data := nl.NewRtAttr(syscall.IFLA_IFALIAS, []byte(name))
+ req.AddData(data)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetHardwareAddr sets the hardware address of the link device.
+// Equivalent to: `ip link set $link address $hwaddr`
+func LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error {
+ return pkgHandle.LinkSetHardwareAddr(link, hwaddr)
+}
+
+// LinkSetHardwareAddr sets the hardware address of the link device.
+// Equivalent to: `ip link set $link address $hwaddr`
+func (h *Handle) LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ data := nl.NewRtAttr(syscall.IFLA_ADDRESS, []byte(hwaddr))
+ req.AddData(data)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetVfHardwareAddr sets the hardware address of a vf for the link.
+// Equivalent to: `ip link set $link vf $vf mac $hwaddr`
+func LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error {
+ return pkgHandle.LinkSetVfHardwareAddr(link, vf, hwaddr)
+}
+
+// LinkSetVfHardwareAddr sets the hardware address of a vf for the link.
+// Equivalent to: `ip link set $link vf $vf mac $hwaddr`
+func (h *Handle) LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ data := nl.NewRtAttr(nl.IFLA_VFINFO_LIST, nil)
+ info := nl.NewRtAttrChild(data, nl.IFLA_VF_INFO, nil)
+ vfmsg := nl.VfMac{
+ Vf: uint32(vf),
+ }
+ copy(vfmsg.Mac[:], []byte(hwaddr))
+ nl.NewRtAttrChild(info, nl.IFLA_VF_MAC, vfmsg.Serialize())
+ req.AddData(data)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetVfVlan sets the vlan of a vf for the link.
+// Equivalent to: `ip link set $link vf $vf vlan $vlan`
+func LinkSetVfVlan(link Link, vf, vlan int) error {
+ return pkgHandle.LinkSetVfVlan(link, vf, vlan)
+}
+
+// LinkSetVfVlan sets the vlan of a vf for the link.
+// Equivalent to: `ip link set $link vf $vf vlan $vlan`
+func (h *Handle) LinkSetVfVlan(link Link, vf, vlan int) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ data := nl.NewRtAttr(nl.IFLA_VFINFO_LIST, nil)
+ info := nl.NewRtAttrChild(data, nl.IFLA_VF_INFO, nil)
+ vfmsg := nl.VfVlan{
+ Vf: uint32(vf),
+ Vlan: uint32(vlan),
+ }
+ nl.NewRtAttrChild(info, nl.IFLA_VF_VLAN, vfmsg.Serialize())
+ req.AddData(data)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetVfTxRate sets the tx rate of a vf for the link.
+// Equivalent to: `ip link set $link vf $vf rate $rate`
+func LinkSetVfTxRate(link Link, vf, rate int) error {
+ return pkgHandle.LinkSetVfTxRate(link, vf, rate)
+}
+
+// LinkSetVfTxRate sets the tx rate of a vf for the link.
+// Equivalent to: `ip link set $link vf $vf rate $rate`
+func (h *Handle) LinkSetVfTxRate(link Link, vf, rate int) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ data := nl.NewRtAttr(nl.IFLA_VFINFO_LIST, nil)
+ info := nl.NewRtAttrChild(data, nl.IFLA_VF_INFO, nil)
+ vfmsg := nl.VfTxRate{
+ Vf: uint32(vf),
+ Rate: uint32(rate),
+ }
+ nl.NewRtAttrChild(info, nl.IFLA_VF_TX_RATE, vfmsg.Serialize())
+ req.AddData(data)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetMaster sets the master of the link device.
+// Equivalent to: `ip link set $link master $master`
+func LinkSetMaster(link Link, master *Bridge) error {
+ return pkgHandle.LinkSetMaster(link, master)
+}
+
+// LinkSetMaster sets the master of the link device.
+// Equivalent to: `ip link set $link master $master`
+func (h *Handle) LinkSetMaster(link Link, master *Bridge) error {
+ index := 0
+ if master != nil {
+ masterBase := master.Attrs()
+ h.ensureIndex(masterBase)
+ index = masterBase.Index
+ }
+ if index <= 0 {
+ return fmt.Errorf("Device does not exist")
+ }
+ return h.LinkSetMasterByIndex(link, index)
+}
+
+// LinkSetNoMaster removes the master of the link device.
+// Equivalent to: `ip link set $link nomaster`
+func LinkSetNoMaster(link Link) error {
+ return pkgHandle.LinkSetNoMaster(link)
+}
+
+// LinkSetNoMaster removes the master of the link device.
+// Equivalent to: `ip link set $link nomaster`
+func (h *Handle) LinkSetNoMaster(link Link) error {
+ return h.LinkSetMasterByIndex(link, 0)
+}
+
+// LinkSetMasterByIndex sets the master of the link device.
+// Equivalent to: `ip link set $link master $master`
+func LinkSetMasterByIndex(link Link, masterIndex int) error {
+ return pkgHandle.LinkSetMasterByIndex(link, masterIndex)
+}
+
+// LinkSetMasterByIndex sets the master of the link device.
+// Equivalent to: `ip link set $link master $master`
+func (h *Handle) LinkSetMasterByIndex(link Link, masterIndex int) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(masterIndex))
+
+ data := nl.NewRtAttr(syscall.IFLA_MASTER, b)
+ req.AddData(data)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetNsPid puts the device into a new network namespace. The
+// pid must be a pid of a running process.
+// Equivalent to: `ip link set $link netns $pid`
+func LinkSetNsPid(link Link, nspid int) error {
+ return pkgHandle.LinkSetNsPid(link, nspid)
+}
+
+// LinkSetNsPid puts the device into a new network namespace. The
+// pid must be a pid of a running process.
+// Equivalent to: `ip link set $link netns $pid`
+func (h *Handle) LinkSetNsPid(link Link, nspid int) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(nspid))
+
+ data := nl.NewRtAttr(syscall.IFLA_NET_NS_PID, b)
+ req.AddData(data)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetNsFd puts the device into a new network namespace. The
+// fd must be an open file descriptor to a network namespace.
+// Similar to: `ip link set $link netns $ns`
+func LinkSetNsFd(link Link, fd int) error {
+ return pkgHandle.LinkSetNsFd(link, fd)
+}
+
+// LinkSetNsFd puts the device into a new network namespace. The
+// fd must be an open file descriptor to a network namespace.
+// Similar to: `ip link set $link netns $ns`
+func (h *Handle) LinkSetNsFd(link Link, fd int) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(fd))
+
+ data := nl.NewRtAttr(nl.IFLA_NET_NS_FD, b)
+ req.AddData(data)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// LinkSetXdpFd adds a bpf function to the driver. The fd must be a bpf
+// program loaded with bpf(type=BPF_PROG_TYPE_XDP)
+func LinkSetXdpFd(link Link, fd int) error {
+ base := link.Attrs()
+ ensureIndex(base)
+ req := nl.NewNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ addXdpAttrs(&LinkXdp{Fd: fd}, req)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+func boolAttr(val bool) []byte {
+ var v uint8
+ if val {
+ v = 1
+ }
+ return nl.Uint8Attr(v)
+}
+
+type vxlanPortRange struct {
+ Lo, Hi uint16
+}
+
+func addVxlanAttrs(vxlan *Vxlan, linkInfo *nl.RtAttr) {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_ID, nl.Uint32Attr(uint32(vxlan.VxlanId)))
+ if vxlan.VtepDevIndex != 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_LINK, nl.Uint32Attr(uint32(vxlan.VtepDevIndex)))
+ }
+ if vxlan.SrcAddr != nil {
+ ip := vxlan.SrcAddr.To4()
+ if ip != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_LOCAL, []byte(ip))
+ } else {
+ ip = vxlan.SrcAddr.To16()
+ if ip != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_LOCAL6, []byte(ip))
+ }
+ }
+ }
+ if vxlan.Group != nil {
+ group := vxlan.Group.To4()
+ if group != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_GROUP, []byte(group))
+ } else {
+ group = vxlan.Group.To16()
+ if group != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_GROUP6, []byte(group))
+ }
+ }
+ }
+
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_TTL, nl.Uint8Attr(uint8(vxlan.TTL)))
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_TOS, nl.Uint8Attr(uint8(vxlan.TOS)))
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_LEARNING, boolAttr(vxlan.Learning))
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_PROXY, boolAttr(vxlan.Proxy))
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_RSC, boolAttr(vxlan.RSC))
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_L2MISS, boolAttr(vxlan.L2miss))
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_L3MISS, boolAttr(vxlan.L3miss))
+
+ if vxlan.UDPCSum {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_UDP_CSUM, boolAttr(vxlan.UDPCSum))
+ }
+ if vxlan.GBP {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_GBP, []byte{})
+ }
+ if vxlan.NoAge {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_AGEING, nl.Uint32Attr(0))
+ } else if vxlan.Age > 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_AGEING, nl.Uint32Attr(uint32(vxlan.Age)))
+ }
+ if vxlan.Limit > 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_LIMIT, nl.Uint32Attr(uint32(vxlan.Limit)))
+ }
+ if vxlan.Port > 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_PORT, htons(uint16(vxlan.Port)))
+ }
+ if vxlan.PortLow > 0 || vxlan.PortHigh > 0 {
+ pr := vxlanPortRange{uint16(vxlan.PortLow), uint16(vxlan.PortHigh)}
+
+ buf := new(bytes.Buffer)
+ binary.Write(buf, binary.BigEndian, &pr)
+
+ nl.NewRtAttrChild(data, nl.IFLA_VXLAN_PORT_RANGE, buf.Bytes())
+ }
+}
+
+func addBondAttrs(bond *Bond, linkInfo *nl.RtAttr) {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ if bond.Mode >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_MODE, nl.Uint8Attr(uint8(bond.Mode)))
+ }
+ if bond.ActiveSlave >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_ACTIVE_SLAVE, nl.Uint32Attr(uint32(bond.ActiveSlave)))
+ }
+ if bond.Miimon >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_MIIMON, nl.Uint32Attr(uint32(bond.Miimon)))
+ }
+ if bond.UpDelay >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_UPDELAY, nl.Uint32Attr(uint32(bond.UpDelay)))
+ }
+ if bond.DownDelay >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_DOWNDELAY, nl.Uint32Attr(uint32(bond.DownDelay)))
+ }
+ if bond.UseCarrier >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_USE_CARRIER, nl.Uint8Attr(uint8(bond.UseCarrier)))
+ }
+ if bond.ArpInterval >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_ARP_INTERVAL, nl.Uint32Attr(uint32(bond.ArpInterval)))
+ }
+ if bond.ArpIpTargets != nil {
+ msg := nl.NewRtAttrChild(data, nl.IFLA_BOND_ARP_IP_TARGET, nil)
+ for i := range bond.ArpIpTargets {
+ ip := bond.ArpIpTargets[i].To4()
+ if ip != nil {
+ nl.NewRtAttrChild(msg, i, []byte(ip))
+ continue
+ }
+ ip = bond.ArpIpTargets[i].To16()
+ if ip != nil {
+ nl.NewRtAttrChild(msg, i, []byte(ip))
+ }
+ }
+ }
+ if bond.ArpValidate >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_ARP_VALIDATE, nl.Uint32Attr(uint32(bond.ArpValidate)))
+ }
+ if bond.ArpAllTargets >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_ARP_ALL_TARGETS, nl.Uint32Attr(uint32(bond.ArpAllTargets)))
+ }
+ if bond.Primary >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_PRIMARY, nl.Uint32Attr(uint32(bond.Primary)))
+ }
+ if bond.PrimaryReselect >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_PRIMARY_RESELECT, nl.Uint8Attr(uint8(bond.PrimaryReselect)))
+ }
+ if bond.FailOverMac >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_FAIL_OVER_MAC, nl.Uint8Attr(uint8(bond.FailOverMac)))
+ }
+ if bond.XmitHashPolicy >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_XMIT_HASH_POLICY, nl.Uint8Attr(uint8(bond.XmitHashPolicy)))
+ }
+ if bond.ResendIgmp >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_RESEND_IGMP, nl.Uint32Attr(uint32(bond.ResendIgmp)))
+ }
+ if bond.NumPeerNotif >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_NUM_PEER_NOTIF, nl.Uint8Attr(uint8(bond.NumPeerNotif)))
+ }
+ if bond.AllSlavesActive >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_ALL_SLAVES_ACTIVE, nl.Uint8Attr(uint8(bond.AllSlavesActive)))
+ }
+ if bond.MinLinks >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_MIN_LINKS, nl.Uint32Attr(uint32(bond.MinLinks)))
+ }
+ if bond.LpInterval >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_LP_INTERVAL, nl.Uint32Attr(uint32(bond.LpInterval)))
+ }
+ if bond.PackersPerSlave >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_PACKETS_PER_SLAVE, nl.Uint32Attr(uint32(bond.PackersPerSlave)))
+ }
+ if bond.LacpRate >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_AD_LACP_RATE, nl.Uint8Attr(uint8(bond.LacpRate)))
+ }
+ if bond.AdSelect >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_AD_SELECT, nl.Uint8Attr(uint8(bond.AdSelect)))
+ }
+ if bond.AdActorSysPrio >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_AD_ACTOR_SYS_PRIO, nl.Uint16Attr(uint16(bond.AdActorSysPrio)))
+ }
+ if bond.AdUserPortKey >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_AD_USER_PORT_KEY, nl.Uint16Attr(uint16(bond.AdUserPortKey)))
+ }
+ if bond.AdActorSystem != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_AD_ACTOR_SYSTEM, []byte(bond.AdActorSystem))
+ }
+ if bond.TlbDynamicLb >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_TLB_DYNAMIC_LB, nl.Uint8Attr(uint8(bond.TlbDynamicLb)))
+ }
+}
+
+// LinkAdd adds a new link device. The type and features of the device
+// are taken from the parameters in the link object.
+// Equivalent to: `ip link add $link`
+func LinkAdd(link Link) error {
+ return pkgHandle.LinkAdd(link)
+}
+
+// LinkAdd adds a new link device. The type and features of the device
+// are taken fromt the parameters in the link object.
+// Equivalent to: `ip link add $link`
+func (h *Handle) LinkAdd(link Link) error {
+ return h.linkModify(link, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+}
+
+func (h *Handle) linkModify(link Link, flags int) error {
+ // TODO: support extra data for macvlan
+ base := link.Attrs()
+
+ if base.Name == "" {
+ return fmt.Errorf("LinkAttrs.Name cannot be empty!")
+ }
+
+ if tuntap, ok := link.(*Tuntap); ok {
+ // TODO: support user
+ // TODO: support group
+ // TODO: multi_queue
+ // TODO: support non- persistent
+ if tuntap.Mode < syscall.IFF_TUN || tuntap.Mode > syscall.IFF_TAP {
+ return fmt.Errorf("Tuntap.Mode %v unknown!", tuntap.Mode)
+ }
+ file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
+ if err != nil {
+ return err
+ }
+ defer file.Close()
+ var req ifReq
+ if tuntap.Flags == 0 {
+ req.Flags = uint16(TUNTAP_DEFAULTS)
+ } else {
+ req.Flags = uint16(tuntap.Flags)
+ }
+ req.Flags |= uint16(tuntap.Mode)
+ copy(req.Name[:15], base.Name)
+ _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, file.Fd(), uintptr(syscall.TUNSETIFF), uintptr(unsafe.Pointer(&req)))
+ if errno != 0 {
+ return fmt.Errorf("Tuntap IOCTL TUNSETIFF failed, errno %v", errno)
+ }
+ _, _, errno = syscall.Syscall(syscall.SYS_IOCTL, file.Fd(), uintptr(syscall.TUNSETPERSIST), 1)
+ if errno != 0 {
+ return fmt.Errorf("Tuntap IOCTL TUNSETPERSIST failed, errno %v", errno)
+ }
+ h.ensureIndex(base)
+
+ // can't set master during create, so set it afterwards
+ if base.MasterIndex != 0 {
+ // TODO: verify MasterIndex is actually a bridge?
+ return h.LinkSetMasterByIndex(link, base.MasterIndex)
+ }
+ return nil
+ }
+
+ req := h.newNetlinkRequest(syscall.RTM_NEWLINK, flags)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ // TODO: make it shorter
+ if base.Flags&net.FlagUp != 0 {
+ msg.Change = syscall.IFF_UP
+ msg.Flags = syscall.IFF_UP
+ }
+ if base.Flags&net.FlagBroadcast != 0 {
+ msg.Change |= syscall.IFF_BROADCAST
+ msg.Flags |= syscall.IFF_BROADCAST
+ }
+ if base.Flags&net.FlagLoopback != 0 {
+ msg.Change |= syscall.IFF_LOOPBACK
+ msg.Flags |= syscall.IFF_LOOPBACK
+ }
+ if base.Flags&net.FlagPointToPoint != 0 {
+ msg.Change |= syscall.IFF_POINTOPOINT
+ msg.Flags |= syscall.IFF_POINTOPOINT
+ }
+ if base.Flags&net.FlagMulticast != 0 {
+ msg.Change |= syscall.IFF_MULTICAST
+ msg.Flags |= syscall.IFF_MULTICAST
+ }
+ req.AddData(msg)
+
+ if base.ParentIndex != 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(base.ParentIndex))
+ data := nl.NewRtAttr(syscall.IFLA_LINK, b)
+ req.AddData(data)
+ } else if link.Type() == "ipvlan" {
+ return fmt.Errorf("Can't create ipvlan link without ParentIndex")
+ }
+
+ nameData := nl.NewRtAttr(syscall.IFLA_IFNAME, nl.ZeroTerminated(base.Name))
+ req.AddData(nameData)
+
+ if base.MTU > 0 {
+ mtu := nl.NewRtAttr(syscall.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU)))
+ req.AddData(mtu)
+ }
+
+ if base.TxQLen >= 0 {
+ qlen := nl.NewRtAttr(syscall.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen)))
+ req.AddData(qlen)
+ }
+
+ if base.HardwareAddr != nil {
+ hwaddr := nl.NewRtAttr(syscall.IFLA_ADDRESS, []byte(base.HardwareAddr))
+ req.AddData(hwaddr)
+ }
+
+ if base.Namespace != nil {
+ var attr *nl.RtAttr
+ switch base.Namespace.(type) {
+ case NsPid:
+ val := nl.Uint32Attr(uint32(base.Namespace.(NsPid)))
+ attr = nl.NewRtAttr(syscall.IFLA_NET_NS_PID, val)
+ case NsFd:
+ val := nl.Uint32Attr(uint32(base.Namespace.(NsFd)))
+ attr = nl.NewRtAttr(nl.IFLA_NET_NS_FD, val)
+ }
+
+ req.AddData(attr)
+ }
+
+ if base.Xdp != nil {
+ addXdpAttrs(base.Xdp, req)
+ }
+
+ linkInfo := nl.NewRtAttr(syscall.IFLA_LINKINFO, nil)
+ nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type()))
+
+ if vlan, ok := link.(*Vlan); ok {
+ b := make([]byte, 2)
+ native.PutUint16(b, uint16(vlan.VlanId))
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ nl.NewRtAttrChild(data, nl.IFLA_VLAN_ID, b)
+ } else if veth, ok := link.(*Veth); ok {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ peer := nl.NewRtAttrChild(data, nl.VETH_INFO_PEER, nil)
+ nl.NewIfInfomsgChild(peer, syscall.AF_UNSPEC)
+ nl.NewRtAttrChild(peer, syscall.IFLA_IFNAME, nl.ZeroTerminated(veth.PeerName))
+ if base.TxQLen >= 0 {
+ nl.NewRtAttrChild(peer, syscall.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen)))
+ }
+ if base.MTU > 0 {
+ nl.NewRtAttrChild(peer, syscall.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU)))
+ }
+
+ } else if vxlan, ok := link.(*Vxlan); ok {
+ addVxlanAttrs(vxlan, linkInfo)
+ } else if bond, ok := link.(*Bond); ok {
+ addBondAttrs(bond, linkInfo)
+ } else if ipv, ok := link.(*IPVlan); ok {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ nl.NewRtAttrChild(data, nl.IFLA_IPVLAN_MODE, nl.Uint16Attr(uint16(ipv.Mode)))
+ } else if macv, ok := link.(*Macvlan); ok {
+ if macv.Mode != MACVLAN_MODE_DEFAULT {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ nl.NewRtAttrChild(data, nl.IFLA_MACVLAN_MODE, nl.Uint32Attr(macvlanModes[macv.Mode]))
+ }
+ } else if macv, ok := link.(*Macvtap); ok {
+ if macv.Mode != MACVLAN_MODE_DEFAULT {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ nl.NewRtAttrChild(data, nl.IFLA_MACVLAN_MODE, nl.Uint32Attr(macvlanModes[macv.Mode]))
+ }
+ } else if gretap, ok := link.(*Gretap); ok {
+ addGretapAttrs(gretap, linkInfo)
+ } else if iptun, ok := link.(*Iptun); ok {
+ addIptunAttrs(iptun, linkInfo)
+ } else if vti, ok := link.(*Vti); ok {
+ addVtiAttrs(vti, linkInfo)
+ } else if vrf, ok := link.(*Vrf); ok {
+ addVrfAttrs(vrf, linkInfo)
+ } else if bridge, ok := link.(*Bridge); ok {
+ addBridgeAttrs(bridge, linkInfo)
+ } else if gtp, ok := link.(*GTP); ok {
+ addGTPAttrs(gtp, linkInfo)
+ }
+
+ req.AddData(linkInfo)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ if err != nil {
+ return err
+ }
+
+ h.ensureIndex(base)
+
+ // can't set master during create, so set it afterwards
+ if base.MasterIndex != 0 {
+ // TODO: verify MasterIndex is actually a bridge?
+ return h.LinkSetMasterByIndex(link, base.MasterIndex)
+ }
+ return nil
+}
+
+// LinkDel deletes link device. Either Index or Name must be set in
+// the link object for it to be deleted. The other values are ignored.
+// Equivalent to: `ip link del $link`
+func LinkDel(link Link) error {
+ return pkgHandle.LinkDel(link)
+}
+
+// LinkDel deletes link device. Either Index or Name must be set in
+// the link object for it to be deleted. The other values are ignored.
+// Equivalent to: `ip link del $link`
+func (h *Handle) LinkDel(link Link) error {
+ base := link.Attrs()
+
+ h.ensureIndex(base)
+
+ req := h.newNetlinkRequest(syscall.RTM_DELLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+func (h *Handle) linkByNameDump(name string) (Link, error) {
+ links, err := h.LinkList()
+ if err != nil {
+ return nil, err
+ }
+
+ for _, link := range links {
+ if link.Attrs().Name == name {
+ return link, nil
+ }
+ }
+ return nil, LinkNotFoundError{fmt.Errorf("Link %s not found", name)}
+}
+
+func (h *Handle) linkByAliasDump(alias string) (Link, error) {
+ links, err := h.LinkList()
+ if err != nil {
+ return nil, err
+ }
+
+ for _, link := range links {
+ if link.Attrs().Alias == alias {
+ return link, nil
+ }
+ }
+ return nil, LinkNotFoundError{fmt.Errorf("Link alias %s not found", alias)}
+}
+
+// LinkByName finds a link by name and returns a pointer to the object.
+func LinkByName(name string) (Link, error) {
+ return pkgHandle.LinkByName(name)
+}
+
+// LinkByName finds a link by name and returns a pointer to the object.
+func (h *Handle) LinkByName(name string) (Link, error) {
+ if h.lookupByDump {
+ return h.linkByNameDump(name)
+ }
+
+ req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ req.AddData(msg)
+
+ nameData := nl.NewRtAttr(syscall.IFLA_IFNAME, nl.ZeroTerminated(name))
+ req.AddData(nameData)
+
+ link, err := execGetLink(req)
+ if err == syscall.EINVAL {
+ // older kernels don't support looking up via IFLA_IFNAME
+ // so fall back to dumping all links
+ h.lookupByDump = true
+ return h.linkByNameDump(name)
+ }
+
+ return link, err
+}
+
+// LinkByAlias finds a link by its alias and returns a pointer to the object.
+// If there are multiple links with the alias it returns the first one
+func LinkByAlias(alias string) (Link, error) {
+ return pkgHandle.LinkByAlias(alias)
+}
+
+// LinkByAlias finds a link by its alias and returns a pointer to the object.
+// If there are multiple links with the alias it returns the first one
+func (h *Handle) LinkByAlias(alias string) (Link, error) {
+ if h.lookupByDump {
+ return h.linkByAliasDump(alias)
+ }
+
+ req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ req.AddData(msg)
+
+ nameData := nl.NewRtAttr(syscall.IFLA_IFALIAS, nl.ZeroTerminated(alias))
+ req.AddData(nameData)
+
+ link, err := execGetLink(req)
+ if err == syscall.EINVAL {
+ // older kernels don't support looking up via IFLA_IFALIAS
+ // so fall back to dumping all links
+ h.lookupByDump = true
+ return h.linkByAliasDump(alias)
+ }
+
+ return link, err
+}
+
+// LinkByIndex finds a link by index and returns a pointer to the object.
+func LinkByIndex(index int) (Link, error) {
+ return pkgHandle.LinkByIndex(index)
+}
+
+// LinkByIndex finds a link by index and returns a pointer to the object.
+func (h *Handle) LinkByIndex(index int) (Link, error) {
+ req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ msg.Index = int32(index)
+ req.AddData(msg)
+
+ return execGetLink(req)
+}
+
+func execGetLink(req *nl.NetlinkRequest) (Link, error) {
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ if err != nil {
+ if errno, ok := err.(syscall.Errno); ok {
+ if errno == syscall.ENODEV {
+ return nil, LinkNotFoundError{fmt.Errorf("Link not found")}
+ }
+ }
+ return nil, err
+ }
+
+ switch {
+ case len(msgs) == 0:
+ return nil, LinkNotFoundError{fmt.Errorf("Link not found")}
+
+ case len(msgs) == 1:
+ return LinkDeserialize(nil, msgs[0])
+
+ default:
+ return nil, fmt.Errorf("More than one link found")
+ }
+}
+
+// linkDeserialize deserializes a raw message received from netlink into
+// a link object.
+func LinkDeserialize(hdr *syscall.NlMsghdr, m []byte) (Link, error) {
+ msg := nl.DeserializeIfInfomsg(m)
+
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ base := LinkAttrs{Index: int(msg.Index), RawFlags: msg.Flags, Flags: linkFlags(msg.Flags), EncapType: msg.EncapType()}
+ if msg.Flags&syscall.IFF_PROMISC != 0 {
+ base.Promisc = 1
+ }
+ var (
+ link Link
+ stats32 []byte
+ stats64 []byte
+ linkType string
+ )
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case syscall.IFLA_LINKINFO:
+ infos, err := nl.ParseRouteAttr(attr.Value)
+ if err != nil {
+ return nil, err
+ }
+ for _, info := range infos {
+ switch info.Attr.Type {
+ case nl.IFLA_INFO_KIND:
+ linkType = string(info.Value[:len(info.Value)-1])
+ switch linkType {
+ case "dummy":
+ link = &Dummy{}
+ case "ifb":
+ link = &Ifb{}
+ case "bridge":
+ link = &Bridge{}
+ case "vlan":
+ link = &Vlan{}
+ case "veth":
+ link = &Veth{}
+ case "vxlan":
+ link = &Vxlan{}
+ case "bond":
+ link = &Bond{}
+ case "ipvlan":
+ link = &IPVlan{}
+ case "macvlan":
+ link = &Macvlan{}
+ case "macvtap":
+ link = &Macvtap{}
+ case "gretap":
+ link = &Gretap{}
+ case "ipip":
+ link = &Iptun{}
+ case "vti":
+ link = &Vti{}
+ case "vrf":
+ link = &Vrf{}
+ case "gtp":
+ link = &GTP{}
+ default:
+ link = &GenericLink{LinkType: linkType}
+ }
+ case nl.IFLA_INFO_DATA:
+ data, err := nl.ParseRouteAttr(info.Value)
+ if err != nil {
+ return nil, err
+ }
+ switch linkType {
+ case "vlan":
+ parseVlanData(link, data)
+ case "vxlan":
+ parseVxlanData(link, data)
+ case "bond":
+ parseBondData(link, data)
+ case "ipvlan":
+ parseIPVlanData(link, data)
+ case "macvlan":
+ parseMacvlanData(link, data)
+ case "macvtap":
+ parseMacvtapData(link, data)
+ case "gretap":
+ parseGretapData(link, data)
+ case "ipip":
+ parseIptunData(link, data)
+ case "vti":
+ parseVtiData(link, data)
+ case "vrf":
+ parseVrfData(link, data)
+ case "bridge":
+ parseBridgeData(link, data)
+ case "gtp":
+ parseGTPData(link, data)
+ }
+ }
+ }
+ case syscall.IFLA_ADDRESS:
+ var nonzero bool
+ for _, b := range attr.Value {
+ if b != 0 {
+ nonzero = true
+ }
+ }
+ if nonzero {
+ base.HardwareAddr = attr.Value[:]
+ }
+ case syscall.IFLA_IFNAME:
+ base.Name = string(attr.Value[:len(attr.Value)-1])
+ case syscall.IFLA_MTU:
+ base.MTU = int(native.Uint32(attr.Value[0:4]))
+ case syscall.IFLA_LINK:
+ base.ParentIndex = int(native.Uint32(attr.Value[0:4]))
+ case syscall.IFLA_MASTER:
+ base.MasterIndex = int(native.Uint32(attr.Value[0:4]))
+ case syscall.IFLA_TXQLEN:
+ base.TxQLen = int(native.Uint32(attr.Value[0:4]))
+ case syscall.IFLA_IFALIAS:
+ base.Alias = string(attr.Value[:len(attr.Value)-1])
+ case syscall.IFLA_STATS:
+ stats32 = attr.Value[:]
+ case IFLA_STATS64:
+ stats64 = attr.Value[:]
+ case nl.IFLA_XDP:
+ xdp, err := parseLinkXdp(attr.Value[:])
+ if err != nil {
+ return nil, err
+ }
+ base.Xdp = xdp
+ case syscall.IFLA_PROTINFO | syscall.NLA_F_NESTED:
+ if hdr != nil && hdr.Type == syscall.RTM_NEWLINK &&
+ msg.Family == syscall.AF_BRIDGE {
+ attrs, err := nl.ParseRouteAttr(attr.Value[:])
+ if err != nil {
+ return nil, err
+ }
+ base.Protinfo = parseProtinfo(attrs)
+ }
+ case syscall.IFLA_OPERSTATE:
+ base.OperState = LinkOperState(uint8(attr.Value[0]))
+ }
+ }
+
+ if stats64 != nil {
+ base.Statistics = parseLinkStats64(stats64)
+ } else if stats32 != nil {
+ base.Statistics = parseLinkStats32(stats32)
+ }
+
+ // Links that don't have IFLA_INFO_KIND are hardware devices
+ if link == nil {
+ link = &Device{}
+ }
+ *link.Attrs() = base
+
+ return link, nil
+}
+
+// LinkList gets a list of link devices.
+// Equivalent to: `ip link show`
+func LinkList() ([]Link, error) {
+ return pkgHandle.LinkList()
+}
+
+// LinkList gets a list of link devices.
+// Equivalent to: `ip link show`
+func (h *Handle) LinkList() ([]Link, error) {
+ // NOTE(vish): This duplicates functionality in net/iface_linux.go, but we need
+ // to get the message ourselves to parse link type.
+ req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_DUMP)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWLINK)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []Link
+ for _, m := range msgs {
+ link, err := LinkDeserialize(nil, m)
+ if err != nil {
+ return nil, err
+ }
+ res = append(res, link)
+ }
+
+ return res, nil
+}
+
+// LinkUpdate is used to pass information back from LinkSubscribe()
+type LinkUpdate struct {
+ nl.IfInfomsg
+ Header syscall.NlMsghdr
+ Link
+}
+
+// LinkSubscribe takes a chan down which notifications will be sent
+// when links change. Close the 'done' chan to stop subscription.
+func LinkSubscribe(ch chan<- LinkUpdate, done <-chan struct{}) error {
+ return linkSubscribe(netns.None(), netns.None(), ch, done)
+}
+
+// LinkSubscribeAt works like LinkSubscribe plus it allows the caller
+// to choose the network namespace in which to subscribe (ns).
+func LinkSubscribeAt(ns netns.NsHandle, ch chan<- LinkUpdate, done <-chan struct{}) error {
+ return linkSubscribe(ns, netns.None(), ch, done)
+}
+
+func linkSubscribe(newNs, curNs netns.NsHandle, ch chan<- LinkUpdate, done <-chan struct{}) error {
+ s, err := nl.SubscribeAt(newNs, curNs, syscall.NETLINK_ROUTE, syscall.RTNLGRP_LINK)
+ if err != nil {
+ return err
+ }
+ if done != nil {
+ go func() {
+ <-done
+ s.Close()
+ }()
+ }
+ go func() {
+ defer close(ch)
+ for {
+ msgs, err := s.Receive()
+ if err != nil {
+ return
+ }
+ for _, m := range msgs {
+ ifmsg := nl.DeserializeIfInfomsg(m.Data)
+ link, err := LinkDeserialize(&m.Header, m.Data)
+ if err != nil {
+ return
+ }
+ ch <- LinkUpdate{IfInfomsg: *ifmsg, Header: m.Header, Link: link}
+ }
+ }
+ }()
+
+ return nil
+}
+
+func LinkSetHairpin(link Link, mode bool) error {
+ return pkgHandle.LinkSetHairpin(link, mode)
+}
+
+func (h *Handle) LinkSetHairpin(link Link, mode bool) error {
+ return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_MODE)
+}
+
+func LinkSetGuard(link Link, mode bool) error {
+ return pkgHandle.LinkSetGuard(link, mode)
+}
+
+func (h *Handle) LinkSetGuard(link Link, mode bool) error {
+ return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_GUARD)
+}
+
+func LinkSetFastLeave(link Link, mode bool) error {
+ return pkgHandle.LinkSetFastLeave(link, mode)
+}
+
+func (h *Handle) LinkSetFastLeave(link Link, mode bool) error {
+ return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_FAST_LEAVE)
+}
+
+func LinkSetLearning(link Link, mode bool) error {
+ return pkgHandle.LinkSetLearning(link, mode)
+}
+
+func (h *Handle) LinkSetLearning(link Link, mode bool) error {
+ return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_LEARNING)
+}
+
+func LinkSetRootBlock(link Link, mode bool) error {
+ return pkgHandle.LinkSetRootBlock(link, mode)
+}
+
+func (h *Handle) LinkSetRootBlock(link Link, mode bool) error {
+ return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROTECT)
+}
+
+func LinkSetFlood(link Link, mode bool) error {
+ return pkgHandle.LinkSetFlood(link, mode)
+}
+
+func (h *Handle) LinkSetFlood(link Link, mode bool) error {
+ return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_UNICAST_FLOOD)
+}
+
+func LinkSetBrProxyArp(link Link, mode bool) error {
+ return pkgHandle.LinkSetBrProxyArp(link, mode)
+}
+
+func (h *Handle) LinkSetBrProxyArp(link Link, mode bool) error {
+ return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROXYARP)
+}
+
+func LinkSetBrProxyArpWiFi(link Link, mode bool) error {
+ return pkgHandle.LinkSetBrProxyArpWiFi(link, mode)
+}
+
+func (h *Handle) LinkSetBrProxyArpWiFi(link Link, mode bool) error {
+ return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROXYARP_WIFI)
+}
+
+func (h *Handle) setProtinfoAttr(link Link, mode bool, attr int) error {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ req := h.newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_BRIDGE)
+ msg.Index = int32(base.Index)
+ req.AddData(msg)
+
+ br := nl.NewRtAttr(syscall.IFLA_PROTINFO|syscall.NLA_F_NESTED, nil)
+ nl.NewRtAttrChild(br, attr, boolToByte(mode))
+ req.AddData(br)
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+func parseVlanData(link Link, data []syscall.NetlinkRouteAttr) {
+ vlan := link.(*Vlan)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.IFLA_VLAN_ID:
+ vlan.VlanId = int(native.Uint16(datum.Value[0:2]))
+ }
+ }
+}
+
+func parseVxlanData(link Link, data []syscall.NetlinkRouteAttr) {
+ vxlan := link.(*Vxlan)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.IFLA_VXLAN_ID:
+ vxlan.VxlanId = int(native.Uint32(datum.Value[0:4]))
+ case nl.IFLA_VXLAN_LINK:
+ vxlan.VtepDevIndex = int(native.Uint32(datum.Value[0:4]))
+ case nl.IFLA_VXLAN_LOCAL:
+ vxlan.SrcAddr = net.IP(datum.Value[0:4])
+ case nl.IFLA_VXLAN_LOCAL6:
+ vxlan.SrcAddr = net.IP(datum.Value[0:16])
+ case nl.IFLA_VXLAN_GROUP:
+ vxlan.Group = net.IP(datum.Value[0:4])
+ case nl.IFLA_VXLAN_GROUP6:
+ vxlan.Group = net.IP(datum.Value[0:16])
+ case nl.IFLA_VXLAN_TTL:
+ vxlan.TTL = int(datum.Value[0])
+ case nl.IFLA_VXLAN_TOS:
+ vxlan.TOS = int(datum.Value[0])
+ case nl.IFLA_VXLAN_LEARNING:
+ vxlan.Learning = int8(datum.Value[0]) != 0
+ case nl.IFLA_VXLAN_PROXY:
+ vxlan.Proxy = int8(datum.Value[0]) != 0
+ case nl.IFLA_VXLAN_RSC:
+ vxlan.RSC = int8(datum.Value[0]) != 0
+ case nl.IFLA_VXLAN_L2MISS:
+ vxlan.L2miss = int8(datum.Value[0]) != 0
+ case nl.IFLA_VXLAN_L3MISS:
+ vxlan.L3miss = int8(datum.Value[0]) != 0
+ case nl.IFLA_VXLAN_UDP_CSUM:
+ vxlan.UDPCSum = int8(datum.Value[0]) != 0
+ case nl.IFLA_VXLAN_GBP:
+ vxlan.GBP = true
+ case nl.IFLA_VXLAN_AGEING:
+ vxlan.Age = int(native.Uint32(datum.Value[0:4]))
+ vxlan.NoAge = vxlan.Age == 0
+ case nl.IFLA_VXLAN_LIMIT:
+ vxlan.Limit = int(native.Uint32(datum.Value[0:4]))
+ case nl.IFLA_VXLAN_PORT:
+ vxlan.Port = int(ntohs(datum.Value[0:2]))
+ case nl.IFLA_VXLAN_PORT_RANGE:
+ buf := bytes.NewBuffer(datum.Value[0:4])
+ var pr vxlanPortRange
+ if binary.Read(buf, binary.BigEndian, &pr) != nil {
+ vxlan.PortLow = int(pr.Lo)
+ vxlan.PortHigh = int(pr.Hi)
+ }
+ }
+ }
+}
+
+func parseBondData(link Link, data []syscall.NetlinkRouteAttr) {
+ bond := link.(*Bond)
+ for i := range data {
+ switch data[i].Attr.Type {
+ case nl.IFLA_BOND_MODE:
+ bond.Mode = BondMode(data[i].Value[0])
+ case nl.IFLA_BOND_ACTIVE_SLAVE:
+ bond.ActiveSlave = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_MIIMON:
+ bond.Miimon = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_UPDELAY:
+ bond.UpDelay = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_DOWNDELAY:
+ bond.DownDelay = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_USE_CARRIER:
+ bond.UseCarrier = int(data[i].Value[0])
+ case nl.IFLA_BOND_ARP_INTERVAL:
+ bond.ArpInterval = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_ARP_IP_TARGET:
+ // TODO: implement
+ case nl.IFLA_BOND_ARP_VALIDATE:
+ bond.ArpValidate = BondArpValidate(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_ARP_ALL_TARGETS:
+ bond.ArpAllTargets = BondArpAllTargets(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_PRIMARY:
+ bond.Primary = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_PRIMARY_RESELECT:
+ bond.PrimaryReselect = BondPrimaryReselect(data[i].Value[0])
+ case nl.IFLA_BOND_FAIL_OVER_MAC:
+ bond.FailOverMac = BondFailOverMac(data[i].Value[0])
+ case nl.IFLA_BOND_XMIT_HASH_POLICY:
+ bond.XmitHashPolicy = BondXmitHashPolicy(data[i].Value[0])
+ case nl.IFLA_BOND_RESEND_IGMP:
+ bond.ResendIgmp = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_NUM_PEER_NOTIF:
+ bond.NumPeerNotif = int(data[i].Value[0])
+ case nl.IFLA_BOND_ALL_SLAVES_ACTIVE:
+ bond.AllSlavesActive = int(data[i].Value[0])
+ case nl.IFLA_BOND_MIN_LINKS:
+ bond.MinLinks = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_LP_INTERVAL:
+ bond.LpInterval = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_PACKETS_PER_SLAVE:
+ bond.PackersPerSlave = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_AD_LACP_RATE:
+ bond.LacpRate = BondLacpRate(data[i].Value[0])
+ case nl.IFLA_BOND_AD_SELECT:
+ bond.AdSelect = BondAdSelect(data[i].Value[0])
+ case nl.IFLA_BOND_AD_INFO:
+ // TODO: implement
+ case nl.IFLA_BOND_AD_ACTOR_SYS_PRIO:
+ bond.AdActorSysPrio = int(native.Uint16(data[i].Value[0:2]))
+ case nl.IFLA_BOND_AD_USER_PORT_KEY:
+ bond.AdUserPortKey = int(native.Uint16(data[i].Value[0:2]))
+ case nl.IFLA_BOND_AD_ACTOR_SYSTEM:
+ bond.AdActorSystem = net.HardwareAddr(data[i].Value[0:6])
+ case nl.IFLA_BOND_TLB_DYNAMIC_LB:
+ bond.TlbDynamicLb = int(data[i].Value[0])
+ }
+ }
+}
+
+func parseIPVlanData(link Link, data []syscall.NetlinkRouteAttr) {
+ ipv := link.(*IPVlan)
+ for _, datum := range data {
+ if datum.Attr.Type == nl.IFLA_IPVLAN_MODE {
+ ipv.Mode = IPVlanMode(native.Uint32(datum.Value[0:4]))
+ return
+ }
+ }
+}
+
+func parseMacvtapData(link Link, data []syscall.NetlinkRouteAttr) {
+ macv := link.(*Macvtap)
+ parseMacvlanData(&macv.Macvlan, data)
+}
+
+func parseMacvlanData(link Link, data []syscall.NetlinkRouteAttr) {
+ macv := link.(*Macvlan)
+ for _, datum := range data {
+ if datum.Attr.Type == nl.IFLA_MACVLAN_MODE {
+ switch native.Uint32(datum.Value[0:4]) {
+ case nl.MACVLAN_MODE_PRIVATE:
+ macv.Mode = MACVLAN_MODE_PRIVATE
+ case nl.MACVLAN_MODE_VEPA:
+ macv.Mode = MACVLAN_MODE_VEPA
+ case nl.MACVLAN_MODE_BRIDGE:
+ macv.Mode = MACVLAN_MODE_BRIDGE
+ case nl.MACVLAN_MODE_PASSTHRU:
+ macv.Mode = MACVLAN_MODE_PASSTHRU
+ case nl.MACVLAN_MODE_SOURCE:
+ macv.Mode = MACVLAN_MODE_SOURCE
+ }
+ return
+ }
+ }
+}
+
+// copied from pkg/net_linux.go
+func linkFlags(rawFlags uint32) net.Flags {
+ var f net.Flags
+ if rawFlags&syscall.IFF_UP != 0 {
+ f |= net.FlagUp
+ }
+ if rawFlags&syscall.IFF_BROADCAST != 0 {
+ f |= net.FlagBroadcast
+ }
+ if rawFlags&syscall.IFF_LOOPBACK != 0 {
+ f |= net.FlagLoopback
+ }
+ if rawFlags&syscall.IFF_POINTOPOINT != 0 {
+ f |= net.FlagPointToPoint
+ }
+ if rawFlags&syscall.IFF_MULTICAST != 0 {
+ f |= net.FlagMulticast
+ }
+ return f
+}
+
+func addGretapAttrs(gretap *Gretap, linkInfo *nl.RtAttr) {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+
+ ip := gretap.Local.To4()
+ if ip != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_LOCAL, []byte(ip))
+ }
+ ip = gretap.Remote.To4()
+ if ip != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_REMOTE, []byte(ip))
+ }
+
+ if gretap.IKey != 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_IKEY, htonl(gretap.IKey))
+ gretap.IFlags |= uint16(nl.GRE_KEY)
+ }
+
+ if gretap.OKey != 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_OKEY, htonl(gretap.OKey))
+ gretap.OFlags |= uint16(nl.GRE_KEY)
+ }
+
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_IFLAGS, htons(gretap.IFlags))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_OFLAGS, htons(gretap.OFlags))
+
+ if gretap.Link != 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_LINK, nl.Uint32Attr(gretap.Link))
+ }
+
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_PMTUDISC, nl.Uint8Attr(gretap.PMtuDisc))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_TTL, nl.Uint8Attr(gretap.Ttl))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_TOS, nl.Uint8Attr(gretap.Tos))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_ENCAP_TYPE, nl.Uint16Attr(gretap.EncapType))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_ENCAP_FLAGS, nl.Uint16Attr(gretap.EncapFlags))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_ENCAP_SPORT, htons(gretap.EncapSport))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_ENCAP_DPORT, htons(gretap.EncapDport))
+}
+
+func parseGretapData(link Link, data []syscall.NetlinkRouteAttr) {
+ gre := link.(*Gretap)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.IFLA_GRE_OKEY:
+ gre.IKey = ntohl(datum.Value[0:4])
+ case nl.IFLA_GRE_IKEY:
+ gre.OKey = ntohl(datum.Value[0:4])
+ case nl.IFLA_GRE_LOCAL:
+ gre.Local = net.IP(datum.Value[0:4])
+ case nl.IFLA_GRE_REMOTE:
+ gre.Remote = net.IP(datum.Value[0:4])
+ case nl.IFLA_GRE_ENCAP_SPORT:
+ gre.EncapSport = ntohs(datum.Value[0:2])
+ case nl.IFLA_GRE_ENCAP_DPORT:
+ gre.EncapDport = ntohs(datum.Value[0:2])
+ case nl.IFLA_GRE_IFLAGS:
+ gre.IFlags = ntohs(datum.Value[0:2])
+ case nl.IFLA_GRE_OFLAGS:
+ gre.OFlags = ntohs(datum.Value[0:2])
+
+ case nl.IFLA_GRE_TTL:
+ gre.Ttl = uint8(datum.Value[0])
+ case nl.IFLA_GRE_TOS:
+ gre.Tos = uint8(datum.Value[0])
+ case nl.IFLA_GRE_PMTUDISC:
+ gre.PMtuDisc = uint8(datum.Value[0])
+ case nl.IFLA_GRE_ENCAP_TYPE:
+ gre.EncapType = native.Uint16(datum.Value[0:2])
+ case nl.IFLA_GRE_ENCAP_FLAGS:
+ gre.EncapFlags = native.Uint16(datum.Value[0:2])
+ }
+ }
+}
+
+func parseLinkStats32(data []byte) *LinkStatistics {
+ return (*LinkStatistics)((*LinkStatistics32)(unsafe.Pointer(&data[0:SizeofLinkStats32][0])).to64())
+}
+
+func parseLinkStats64(data []byte) *LinkStatistics {
+ return (*LinkStatistics)((*LinkStatistics64)(unsafe.Pointer(&data[0:SizeofLinkStats64][0])))
+}
+
+func addXdpAttrs(xdp *LinkXdp, req *nl.NetlinkRequest) {
+ attrs := nl.NewRtAttr(nl.IFLA_XDP|syscall.NLA_F_NESTED, nil)
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(xdp.Fd))
+ nl.NewRtAttrChild(attrs, nl.IFLA_XDP_FD, b)
+ native.PutUint32(b, xdp.Flags)
+ nl.NewRtAttrChild(attrs, nl.IFLA_XDP_FLAGS, b)
+ req.AddData(attrs)
+}
+
+func parseLinkXdp(data []byte) (*LinkXdp, error) {
+ attrs, err := nl.ParseRouteAttr(data)
+ if err != nil {
+ return nil, err
+ }
+ xdp := &LinkXdp{}
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case nl.IFLA_XDP_FD:
+ xdp.Fd = int(native.Uint32(attr.Value[0:4]))
+ case nl.IFLA_XDP_ATTACHED:
+ xdp.Attached = attr.Value[0] != 0
+ case nl.IFLA_XDP_FLAGS:
+ xdp.Flags = native.Uint32(attr.Value[0:4])
+ }
+ }
+ return xdp, nil
+}
+
+func addIptunAttrs(iptun *Iptun, linkInfo *nl.RtAttr) {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+
+ ip := iptun.Local.To4()
+ if ip != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_IPTUN_LOCAL, []byte(ip))
+ }
+
+ ip = iptun.Remote.To4()
+ if ip != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_IPTUN_REMOTE, []byte(ip))
+ }
+
+ if iptun.Link != 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_IPTUN_LINK, nl.Uint32Attr(iptun.Link))
+ }
+ nl.NewRtAttrChild(data, nl.IFLA_IPTUN_PMTUDISC, nl.Uint8Attr(iptun.PMtuDisc))
+ nl.NewRtAttrChild(data, nl.IFLA_IPTUN_TTL, nl.Uint8Attr(iptun.Ttl))
+ nl.NewRtAttrChild(data, nl.IFLA_IPTUN_TOS, nl.Uint8Attr(iptun.Tos))
+}
+
+func parseIptunData(link Link, data []syscall.NetlinkRouteAttr) {
+ iptun := link.(*Iptun)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.IFLA_IPTUN_LOCAL:
+ iptun.Local = net.IP(datum.Value[0:4])
+ case nl.IFLA_IPTUN_REMOTE:
+ iptun.Remote = net.IP(datum.Value[0:4])
+ case nl.IFLA_IPTUN_TTL:
+ iptun.Ttl = uint8(datum.Value[0])
+ case nl.IFLA_IPTUN_TOS:
+ iptun.Tos = uint8(datum.Value[0])
+ case nl.IFLA_IPTUN_PMTUDISC:
+ iptun.PMtuDisc = uint8(datum.Value[0])
+ }
+ }
+}
+
+func addVtiAttrs(vti *Vti, linkInfo *nl.RtAttr) {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+
+ ip := vti.Local.To4()
+ if ip != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_VTI_LOCAL, []byte(ip))
+ }
+
+ ip = vti.Remote.To4()
+ if ip != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_VTI_REMOTE, []byte(ip))
+ }
+
+ if vti.Link != 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_VTI_LINK, nl.Uint32Attr(vti.Link))
+ }
+
+ nl.NewRtAttrChild(data, nl.IFLA_VTI_IKEY, htonl(vti.IKey))
+ nl.NewRtAttrChild(data, nl.IFLA_VTI_OKEY, htonl(vti.OKey))
+}
+
+func parseVtiData(link Link, data []syscall.NetlinkRouteAttr) {
+ vti := link.(*Vti)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.IFLA_VTI_LOCAL:
+ vti.Local = net.IP(datum.Value[0:4])
+ case nl.IFLA_VTI_REMOTE:
+ vti.Remote = net.IP(datum.Value[0:4])
+ case nl.IFLA_VTI_IKEY:
+ vti.IKey = ntohl(datum.Value[0:4])
+ case nl.IFLA_VTI_OKEY:
+ vti.OKey = ntohl(datum.Value[0:4])
+ }
+ }
+}
+
+func addVrfAttrs(vrf *Vrf, linkInfo *nl.RtAttr) {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(vrf.Table))
+ nl.NewRtAttrChild(data, nl.IFLA_VRF_TABLE, b)
+}
+
+func parseVrfData(link Link, data []syscall.NetlinkRouteAttr) {
+ vrf := link.(*Vrf)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.IFLA_VRF_TABLE:
+ vrf.Table = native.Uint32(datum.Value[0:4])
+ }
+ }
+}
+
+func addBridgeAttrs(bridge *Bridge, linkInfo *nl.RtAttr) {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ if bridge.MulticastSnooping != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_BR_MCAST_SNOOPING, boolToByte(*bridge.MulticastSnooping))
+ }
+ if bridge.HelloTime != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_BR_HELLO_TIME, nl.Uint32Attr(*bridge.HelloTime))
+ }
+}
+
+func parseBridgeData(bridge Link, data []syscall.NetlinkRouteAttr) {
+ br := bridge.(*Bridge)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.IFLA_BR_HELLO_TIME:
+ helloTime := native.Uint32(datum.Value[0:4])
+ br.HelloTime = &helloTime
+ case nl.IFLA_BR_MCAST_SNOOPING:
+ mcastSnooping := datum.Value[0] == 1
+ br.MulticastSnooping = &mcastSnooping
+ }
+ }
+}
+
+func addGTPAttrs(gtp *GTP, linkInfo *nl.RtAttr) {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ nl.NewRtAttrChild(data, nl.IFLA_GTP_FD0, nl.Uint32Attr(uint32(gtp.FD0)))
+ nl.NewRtAttrChild(data, nl.IFLA_GTP_FD1, nl.Uint32Attr(uint32(gtp.FD1)))
+ nl.NewRtAttrChild(data, nl.IFLA_GTP_PDP_HASHSIZE, nl.Uint32Attr(131072))
+ if gtp.Role != nl.GTP_ROLE_GGSN {
+ nl.NewRtAttrChild(data, nl.IFLA_GTP_ROLE, nl.Uint32Attr(uint32(gtp.Role)))
+ }
+}
+
+func parseGTPData(link Link, data []syscall.NetlinkRouteAttr) {
+ gtp := link.(*GTP)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.IFLA_GTP_FD0:
+ gtp.FD0 = int(native.Uint32(datum.Value))
+ case nl.IFLA_GTP_FD1:
+ gtp.FD1 = int(native.Uint32(datum.Value))
+ case nl.IFLA_GTP_PDP_HASHSIZE:
+ gtp.PDPHashsize = int(native.Uint32(datum.Value))
+ case nl.IFLA_GTP_ROLE:
+ gtp.Role = int(native.Uint32(datum.Value))
+ }
+ }
+}
diff --git a/vendor/github.com/vishvananda/netlink/link_tuntap_linux.go b/vendor/github.com/vishvananda/netlink/link_tuntap_linux.go
new file mode 100644
index 0000000..310bd33
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/link_tuntap_linux.go
@@ -0,0 +1,14 @@
+package netlink
+
+// ideally golang.org/x/sys/unix would define IfReq but it only has
+// IFNAMSIZ, hence this minimalistic implementation
+const (
+ SizeOfIfReq = 40
+ IFNAMSIZ = 16
+)
+
+type ifReq struct {
+ Name [IFNAMSIZ]byte
+ Flags uint16
+ pad [SizeOfIfReq - IFNAMSIZ - 2]byte
+}
diff --git a/vendor/github.com/vishvananda/netlink/neigh.go b/vendor/github.com/vishvananda/netlink/neigh.go
new file mode 100644
index 0000000..0e5eb90
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/neigh.go
@@ -0,0 +1,22 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+)
+
+// Neigh represents a link layer neighbor from netlink.
+type Neigh struct {
+ LinkIndex int
+ Family int
+ State int
+ Type int
+ Flags int
+ IP net.IP
+ HardwareAddr net.HardwareAddr
+}
+
+// String returns $ip/$hwaddr $label
+func (neigh *Neigh) String() string {
+ return fmt.Sprintf("%s %s", neigh.IP, neigh.HardwareAddr)
+}
diff --git a/vendor/github.com/vishvananda/netlink/neigh_linux.go b/vendor/github.com/vishvananda/netlink/neigh_linux.go
new file mode 100644
index 0000000..f069db2
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/neigh_linux.go
@@ -0,0 +1,250 @@
+package netlink
+
+import (
+ "net"
+ "syscall"
+ "unsafe"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+const (
+ NDA_UNSPEC = iota
+ NDA_DST
+ NDA_LLADDR
+ NDA_CACHEINFO
+ NDA_PROBES
+ NDA_VLAN
+ NDA_PORT
+ NDA_VNI
+ NDA_IFINDEX
+ NDA_MAX = NDA_IFINDEX
+)
+
+// Neighbor Cache Entry States.
+const (
+ NUD_NONE = 0x00
+ NUD_INCOMPLETE = 0x01
+ NUD_REACHABLE = 0x02
+ NUD_STALE = 0x04
+ NUD_DELAY = 0x08
+ NUD_PROBE = 0x10
+ NUD_FAILED = 0x20
+ NUD_NOARP = 0x40
+ NUD_PERMANENT = 0x80
+)
+
+// Neighbor Flags
+const (
+ NTF_USE = 0x01
+ NTF_SELF = 0x02
+ NTF_MASTER = 0x04
+ NTF_PROXY = 0x08
+ NTF_ROUTER = 0x80
+)
+
+type Ndmsg struct {
+ Family uint8
+ Index uint32
+ State uint16
+ Flags uint8
+ Type uint8
+}
+
+func deserializeNdmsg(b []byte) *Ndmsg {
+ var dummy Ndmsg
+ return (*Ndmsg)(unsafe.Pointer(&b[0:unsafe.Sizeof(dummy)][0]))
+}
+
+func (msg *Ndmsg) Serialize() []byte {
+ return (*(*[unsafe.Sizeof(*msg)]byte)(unsafe.Pointer(msg)))[:]
+}
+
+func (msg *Ndmsg) Len() int {
+ return int(unsafe.Sizeof(*msg))
+}
+
+// NeighAdd will add an IP to MAC mapping to the ARP table
+// Equivalent to: `ip neigh add ....`
+func NeighAdd(neigh *Neigh) error {
+ return pkgHandle.NeighAdd(neigh)
+}
+
+// NeighAdd will add an IP to MAC mapping to the ARP table
+// Equivalent to: `ip neigh add ....`
+func (h *Handle) NeighAdd(neigh *Neigh) error {
+ return h.neighAdd(neigh, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL)
+}
+
+// NeighSet will add or replace an IP to MAC mapping to the ARP table
+// Equivalent to: `ip neigh replace....`
+func NeighSet(neigh *Neigh) error {
+ return pkgHandle.NeighSet(neigh)
+}
+
+// NeighSet will add or replace an IP to MAC mapping to the ARP table
+// Equivalent to: `ip neigh replace....`
+func (h *Handle) NeighSet(neigh *Neigh) error {
+ return h.neighAdd(neigh, syscall.NLM_F_CREATE|syscall.NLM_F_REPLACE)
+}
+
+// NeighAppend will append an entry to FDB
+// Equivalent to: `bridge fdb append...`
+func NeighAppend(neigh *Neigh) error {
+ return pkgHandle.NeighAppend(neigh)
+}
+
+// NeighAppend will append an entry to FDB
+// Equivalent to: `bridge fdb append...`
+func (h *Handle) NeighAppend(neigh *Neigh) error {
+ return h.neighAdd(neigh, syscall.NLM_F_CREATE|syscall.NLM_F_APPEND)
+}
+
+// NeighAppend will append an entry to FDB
+// Equivalent to: `bridge fdb append...`
+func neighAdd(neigh *Neigh, mode int) error {
+ return pkgHandle.neighAdd(neigh, mode)
+}
+
+// NeighAppend will append an entry to FDB
+// Equivalent to: `bridge fdb append...`
+func (h *Handle) neighAdd(neigh *Neigh, mode int) error {
+ req := h.newNetlinkRequest(syscall.RTM_NEWNEIGH, mode|syscall.NLM_F_ACK)
+ return neighHandle(neigh, req)
+}
+
+// NeighDel will delete an IP address from a link device.
+// Equivalent to: `ip addr del $addr dev $link`
+func NeighDel(neigh *Neigh) error {
+ return pkgHandle.NeighDel(neigh)
+}
+
+// NeighDel will delete an IP address from a link device.
+// Equivalent to: `ip addr del $addr dev $link`
+func (h *Handle) NeighDel(neigh *Neigh) error {
+ req := h.newNetlinkRequest(syscall.RTM_DELNEIGH, syscall.NLM_F_ACK)
+ return neighHandle(neigh, req)
+}
+
+func neighHandle(neigh *Neigh, req *nl.NetlinkRequest) error {
+ var family int
+ if neigh.Family > 0 {
+ family = neigh.Family
+ } else {
+ family = nl.GetIPFamily(neigh.IP)
+ }
+
+ msg := Ndmsg{
+ Family: uint8(family),
+ Index: uint32(neigh.LinkIndex),
+ State: uint16(neigh.State),
+ Type: uint8(neigh.Type),
+ Flags: uint8(neigh.Flags),
+ }
+ req.AddData(&msg)
+
+ ipData := neigh.IP.To4()
+ if ipData == nil {
+ ipData = neigh.IP.To16()
+ }
+
+ dstData := nl.NewRtAttr(NDA_DST, ipData)
+ req.AddData(dstData)
+
+ if neigh.Flags != NTF_PROXY || neigh.HardwareAddr != nil {
+ hwData := nl.NewRtAttr(NDA_LLADDR, []byte(neigh.HardwareAddr))
+ req.AddData(hwData)
+ }
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// NeighList gets a list of IP-MAC mappings in the system (ARP table).
+// Equivalent to: `ip neighbor show`.
+// The list can be filtered by link and ip family.
+func NeighList(linkIndex, family int) ([]Neigh, error) {
+ return pkgHandle.NeighList(linkIndex, family)
+}
+
+// NeighProxyList gets a list of neighbor proxies in the system.
+// Equivalent to: `ip neighbor show proxy`.
+// The list can be filtered by link and ip family.
+func NeighProxyList(linkIndex, family int) ([]Neigh, error) {
+ return pkgHandle.NeighProxyList(linkIndex, family)
+}
+
+// NeighList gets a list of IP-MAC mappings in the system (ARP table).
+// Equivalent to: `ip neighbor show`.
+// The list can be filtered by link and ip family.
+func (h *Handle) NeighList(linkIndex, family int) ([]Neigh, error) {
+ return h.neighList(linkIndex, family, 0)
+}
+
+// NeighProxyList gets a list of neighbor proxies in the system.
+// Equivalent to: `ip neighbor show proxy`.
+// The list can be filtered by link, ip family.
+func (h *Handle) NeighProxyList(linkIndex, family int) ([]Neigh, error) {
+ return h.neighList(linkIndex, family, NTF_PROXY)
+}
+
+func (h *Handle) neighList(linkIndex, family, flags int) ([]Neigh, error) {
+ req := h.newNetlinkRequest(syscall.RTM_GETNEIGH, syscall.NLM_F_DUMP)
+ msg := Ndmsg{
+ Family: uint8(family),
+ Index: uint32(linkIndex),
+ Flags: uint8(flags),
+ }
+ req.AddData(&msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWNEIGH)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []Neigh
+ for _, m := range msgs {
+ ndm := deserializeNdmsg(m)
+ if linkIndex != 0 && int(ndm.Index) != linkIndex {
+ // Ignore messages from other interfaces
+ continue
+ }
+
+ neigh, err := NeighDeserialize(m)
+ if err != nil {
+ continue
+ }
+
+ res = append(res, *neigh)
+ }
+
+ return res, nil
+}
+
+func NeighDeserialize(m []byte) (*Neigh, error) {
+ msg := deserializeNdmsg(m)
+
+ neigh := Neigh{
+ LinkIndex: int(msg.Index),
+ Family: int(msg.Family),
+ State: int(msg.State),
+ Type: int(msg.Type),
+ Flags: int(msg.Flags),
+ }
+
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case NDA_DST:
+ neigh.IP = net.IP(attr.Value)
+ case NDA_LLADDR:
+ neigh.HardwareAddr = net.HardwareAddr(attr.Value)
+ }
+ }
+
+ return &neigh, nil
+}
diff --git a/vendor/github.com/vishvananda/netlink/netlink.go b/vendor/github.com/vishvananda/netlink/netlink.go
new file mode 100644
index 0000000..fb15952
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/netlink.go
@@ -0,0 +1,39 @@
+// Package netlink provides a simple library for netlink. Netlink is
+// the interface a user-space program in linux uses to communicate with
+// the kernel. It can be used to add and remove interfaces, set up ip
+// addresses and routes, and confiugre ipsec. Netlink communication
+// requires elevated privileges, so in most cases this code needs to
+// be run as root. The low level primitives for netlink are contained
+// in the nl subpackage. This package attempts to provide a high-level
+// interface that is loosly modeled on the iproute2 cli.
+package netlink
+
+import (
+ "errors"
+ "net"
+)
+
+var (
+ // ErrNotImplemented is returned when a requested feature is not implemented.
+ ErrNotImplemented = errors.New("not implemented")
+)
+
+// ParseIPNet parses a string in ip/net format and returns a net.IPNet.
+// This is valuable because addresses in netlink are often IPNets and
+// ParseCIDR returns an IPNet with the IP part set to the base IP of the
+// range.
+func ParseIPNet(s string) (*net.IPNet, error) {
+ ip, ipNet, err := net.ParseCIDR(s)
+ if err != nil {
+ return nil, err
+ }
+ return &net.IPNet{IP: ip, Mask: ipNet.Mask}, nil
+}
+
+// NewIPNet generates an IPNet from an ip address using a netmask of 32 or 128.
+func NewIPNet(ip net.IP) *net.IPNet {
+ if ip.To4() != nil {
+ return &net.IPNet{IP: ip, Mask: net.CIDRMask(32, 32)}
+ }
+ return &net.IPNet{IP: ip, Mask: net.CIDRMask(128, 128)}
+}
diff --git a/vendor/github.com/vishvananda/netlink/netlink_linux.go b/vendor/github.com/vishvananda/netlink/netlink_linux.go
new file mode 100644
index 0000000..a20d293
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/netlink_linux.go
@@ -0,0 +1,11 @@
+package netlink
+
+import "github.com/vishvananda/netlink/nl"
+
+// Family type definitions
+const (
+ FAMILY_ALL = nl.FAMILY_ALL
+ FAMILY_V4 = nl.FAMILY_V4
+ FAMILY_V6 = nl.FAMILY_V6
+ FAMILY_MPLS = nl.FAMILY_MPLS
+)
diff --git a/vendor/github.com/vishvananda/netlink/netlink_unspecified.go b/vendor/github.com/vishvananda/netlink/netlink_unspecified.go
new file mode 100644
index 0000000..2d57c16
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/netlink_unspecified.go
@@ -0,0 +1,221 @@
+// +build !linux
+
+package netlink
+
+import "net"
+
+func LinkSetUp(link Link) error {
+ return ErrNotImplemented
+}
+
+func LinkSetDown(link Link) error {
+ return ErrNotImplemented
+}
+
+func LinkSetMTU(link Link, mtu int) error {
+ return ErrNotImplemented
+}
+
+func LinkSetMaster(link Link, master *Bridge) error {
+ return ErrNotImplemented
+}
+
+func LinkSetNsPid(link Link, nspid int) error {
+ return ErrNotImplemented
+}
+
+func LinkSetNsFd(link Link, fd int) error {
+ return ErrNotImplemented
+}
+
+func LinkSetName(link Link, name string) error {
+ return ErrNotImplemented
+}
+
+func LinkSetAlias(link Link, name string) error {
+ return ErrNotImplemented
+}
+
+func LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error {
+ return ErrNotImplemented
+}
+
+func LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error {
+ return ErrNotImplemented
+}
+
+func LinkSetVfVlan(link Link, vf, vlan int) error {
+ return ErrNotImplemented
+}
+
+func LinkSetVfTxRate(link Link, vf, rate int) error {
+ return ErrNotImplemented
+}
+
+func LinkSetNoMaster(link Link) error {
+ return ErrNotImplemented
+}
+
+func LinkSetMasterByIndex(link Link, masterIndex int) error {
+ return ErrNotImplemented
+}
+
+func LinkSetXdpFd(link Link, fd int) error {
+ return ErrNotImplemented
+}
+
+func LinkSetARPOff(link Link) error {
+ return ErrNotImplemented
+}
+
+func LinkSetARPOn(link Link) error {
+ return ErrNotImplemented
+}
+
+func LinkByName(name string) (Link, error) {
+ return nil, ErrNotImplemented
+}
+
+func LinkByAlias(alias string) (Link, error) {
+ return nil, ErrNotImplemented
+}
+
+func LinkByIndex(index int) (Link, error) {
+ return nil, ErrNotImplemented
+}
+
+func LinkSetHairpin(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func LinkSetGuard(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func LinkSetFastLeave(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func LinkSetLearning(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func LinkSetRootBlock(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func LinkSetFlood(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func LinkAdd(link Link) error {
+ return ErrNotImplemented
+}
+
+func LinkDel(link Link) error {
+ return ErrNotImplemented
+}
+
+func SetHairpin(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func SetGuard(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func SetFastLeave(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func SetLearning(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func SetRootBlock(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func SetFlood(link Link, mode bool) error {
+ return ErrNotImplemented
+}
+
+func LinkList() ([]Link, error) {
+ return nil, ErrNotImplemented
+}
+
+func AddrAdd(link Link, addr *Addr) error {
+ return ErrNotImplemented
+}
+
+func AddrDel(link Link, addr *Addr) error {
+ return ErrNotImplemented
+}
+
+func AddrList(link Link, family int) ([]Addr, error) {
+ return nil, ErrNotImplemented
+}
+
+func RouteAdd(route *Route) error {
+ return ErrNotImplemented
+}
+
+func RouteDel(route *Route) error {
+ return ErrNotImplemented
+}
+
+func RouteList(link Link, family int) ([]Route, error) {
+ return nil, ErrNotImplemented
+}
+
+func XfrmPolicyAdd(policy *XfrmPolicy) error {
+ return ErrNotImplemented
+}
+
+func XfrmPolicyDel(policy *XfrmPolicy) error {
+ return ErrNotImplemented
+}
+
+func XfrmPolicyList(family int) ([]XfrmPolicy, error) {
+ return nil, ErrNotImplemented
+}
+
+func XfrmStateAdd(policy *XfrmState) error {
+ return ErrNotImplemented
+}
+
+func XfrmStateDel(policy *XfrmState) error {
+ return ErrNotImplemented
+}
+
+func XfrmStateList(family int) ([]XfrmState, error) {
+ return nil, ErrNotImplemented
+}
+
+func NeighAdd(neigh *Neigh) error {
+ return ErrNotImplemented
+}
+
+func NeighSet(neigh *Neigh) error {
+ return ErrNotImplemented
+}
+
+func NeighAppend(neigh *Neigh) error {
+ return ErrNotImplemented
+}
+
+func NeighDel(neigh *Neigh) error {
+ return ErrNotImplemented
+}
+
+func NeighList(linkIndex, family int) ([]Neigh, error) {
+ return nil, ErrNotImplemented
+}
+
+func NeighDeserialize(m []byte) (*Neigh, error) {
+ return nil, ErrNotImplemented
+}
+
+func SocketGet(local, remote net.Addr) (*Socket, error) {
+ return nil, ErrNotImplemented
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/addr_linux.go b/vendor/github.com/vishvananda/netlink/nl/addr_linux.go
new file mode 100644
index 0000000..fe362e9
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/addr_linux.go
@@ -0,0 +1,76 @@
+package nl
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+type IfAddrmsg struct {
+ syscall.IfAddrmsg
+}
+
+func NewIfAddrmsg(family int) *IfAddrmsg {
+ return &IfAddrmsg{
+ IfAddrmsg: syscall.IfAddrmsg{
+ Family: uint8(family),
+ },
+ }
+}
+
+// struct ifaddrmsg {
+// __u8 ifa_family;
+// __u8 ifa_prefixlen; /* The prefix length */
+// __u8 ifa_flags; /* Flags */
+// __u8 ifa_scope; /* Address scope */
+// __u32 ifa_index; /* Link index */
+// };
+
+// type IfAddrmsg struct {
+// Family uint8
+// Prefixlen uint8
+// Flags uint8
+// Scope uint8
+// Index uint32
+// }
+// SizeofIfAddrmsg = 0x8
+
+func DeserializeIfAddrmsg(b []byte) *IfAddrmsg {
+ return (*IfAddrmsg)(unsafe.Pointer(&b[0:syscall.SizeofIfAddrmsg][0]))
+}
+
+func (msg *IfAddrmsg) Serialize() []byte {
+ return (*(*[syscall.SizeofIfAddrmsg]byte)(unsafe.Pointer(msg)))[:]
+}
+
+func (msg *IfAddrmsg) Len() int {
+ return syscall.SizeofIfAddrmsg
+}
+
+// struct ifa_cacheinfo {
+// __u32 ifa_prefered;
+// __u32 ifa_valid;
+// __u32 cstamp; /* created timestamp, hundredths of seconds */
+// __u32 tstamp; /* updated timestamp, hundredths of seconds */
+// };
+
+const IFA_CACHEINFO = 6
+const SizeofIfaCacheInfo = 0x10
+
+type IfaCacheInfo struct {
+ IfaPrefered uint32
+ IfaValid uint32
+ Cstamp uint32
+ Tstamp uint32
+}
+
+func (msg *IfaCacheInfo) Len() int {
+ return SizeofIfaCacheInfo
+}
+
+func DeserializeIfaCacheInfo(b []byte) *IfaCacheInfo {
+ return (*IfaCacheInfo)(unsafe.Pointer(&b[0:SizeofIfaCacheInfo][0]))
+}
+
+func (msg *IfaCacheInfo) Serialize() []byte {
+ return (*(*[SizeofIfaCacheInfo]byte)(unsafe.Pointer(msg)))[:]
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/conntrack_linux.go b/vendor/github.com/vishvananda/netlink/nl/conntrack_linux.go
new file mode 100644
index 0000000..6692b53
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/conntrack_linux.go
@@ -0,0 +1,189 @@
+package nl
+
+import "unsafe"
+
+// Track the message sizes for the correct serialization/deserialization
+const (
+ SizeofNfgenmsg = 4
+ SizeofNfattr = 4
+ SizeofNfConntrack = 376
+ SizeofNfctTupleHead = 52
+)
+
+var L4ProtoMap = map[uint8]string{
+ 6: "tcp",
+ 17: "udp",
+}
+
+// All the following constants are coming from:
+// https://github.com/torvalds/linux/blob/master/include/uapi/linux/netfilter/nfnetlink_conntrack.h
+
+// enum cntl_msg_types {
+// IPCTNL_MSG_CT_NEW,
+// IPCTNL_MSG_CT_GET,
+// IPCTNL_MSG_CT_DELETE,
+// IPCTNL_MSG_CT_GET_CTRZERO,
+// IPCTNL_MSG_CT_GET_STATS_CPU,
+// IPCTNL_MSG_CT_GET_STATS,
+// IPCTNL_MSG_CT_GET_DYING,
+// IPCTNL_MSG_CT_GET_UNCONFIRMED,
+//
+// IPCTNL_MSG_MAX
+// };
+const (
+ IPCTNL_MSG_CT_GET = 1
+ IPCTNL_MSG_CT_DELETE = 2
+)
+
+// #define NFNETLINK_V0 0
+const (
+ NFNETLINK_V0 = 0
+)
+
+// #define NLA_F_NESTED (1 << 15)
+const (
+ NLA_F_NESTED = (1 << 15)
+)
+
+// enum ctattr_type {
+// CTA_UNSPEC,
+// CTA_TUPLE_ORIG,
+// CTA_TUPLE_REPLY,
+// CTA_STATUS,
+// CTA_PROTOINFO,
+// CTA_HELP,
+// CTA_NAT_SRC,
+// #define CTA_NAT CTA_NAT_SRC /* backwards compatibility */
+// CTA_TIMEOUT,
+// CTA_MARK,
+// CTA_COUNTERS_ORIG,
+// CTA_COUNTERS_REPLY,
+// CTA_USE,
+// CTA_ID,
+// CTA_NAT_DST,
+// CTA_TUPLE_MASTER,
+// CTA_SEQ_ADJ_ORIG,
+// CTA_NAT_SEQ_ADJ_ORIG = CTA_SEQ_ADJ_ORIG,
+// CTA_SEQ_ADJ_REPLY,
+// CTA_NAT_SEQ_ADJ_REPLY = CTA_SEQ_ADJ_REPLY,
+// CTA_SECMARK, /* obsolete */
+// CTA_ZONE,
+// CTA_SECCTX,
+// CTA_TIMESTAMP,
+// CTA_MARK_MASK,
+// CTA_LABELS,
+// CTA_LABELS_MASK,
+// __CTA_MAX
+// };
+const (
+ CTA_TUPLE_ORIG = 1
+ CTA_TUPLE_REPLY = 2
+ CTA_STATUS = 3
+ CTA_TIMEOUT = 8
+ CTA_MARK = 9
+ CTA_PROTOINFO = 4
+)
+
+// enum ctattr_tuple {
+// CTA_TUPLE_UNSPEC,
+// CTA_TUPLE_IP,
+// CTA_TUPLE_PROTO,
+// CTA_TUPLE_ZONE,
+// __CTA_TUPLE_MAX
+// };
+// #define CTA_TUPLE_MAX (__CTA_TUPLE_MAX - 1)
+const (
+ CTA_TUPLE_IP = 1
+ CTA_TUPLE_PROTO = 2
+)
+
+// enum ctattr_ip {
+// CTA_IP_UNSPEC,
+// CTA_IP_V4_SRC,
+// CTA_IP_V4_DST,
+// CTA_IP_V6_SRC,
+// CTA_IP_V6_DST,
+// __CTA_IP_MAX
+// };
+// #define CTA_IP_MAX (__CTA_IP_MAX - 1)
+const (
+ CTA_IP_V4_SRC = 1
+ CTA_IP_V4_DST = 2
+ CTA_IP_V6_SRC = 3
+ CTA_IP_V6_DST = 4
+)
+
+// enum ctattr_l4proto {
+// CTA_PROTO_UNSPEC,
+// CTA_PROTO_NUM,
+// CTA_PROTO_SRC_PORT,
+// CTA_PROTO_DST_PORT,
+// CTA_PROTO_ICMP_ID,
+// CTA_PROTO_ICMP_TYPE,
+// CTA_PROTO_ICMP_CODE,
+// CTA_PROTO_ICMPV6_ID,
+// CTA_PROTO_ICMPV6_TYPE,
+// CTA_PROTO_ICMPV6_CODE,
+// __CTA_PROTO_MAX
+// };
+// #define CTA_PROTO_MAX (__CTA_PROTO_MAX - 1)
+const (
+ CTA_PROTO_NUM = 1
+ CTA_PROTO_SRC_PORT = 2
+ CTA_PROTO_DST_PORT = 3
+)
+
+// enum ctattr_protoinfo {
+// CTA_PROTOINFO_UNSPEC,
+// CTA_PROTOINFO_TCP,
+// CTA_PROTOINFO_DCCP,
+// CTA_PROTOINFO_SCTP,
+// __CTA_PROTOINFO_MAX
+// };
+// #define CTA_PROTOINFO_MAX (__CTA_PROTOINFO_MAX - 1)
+const (
+ CTA_PROTOINFO_TCP = 1
+)
+
+// enum ctattr_protoinfo_tcp {
+// CTA_PROTOINFO_TCP_UNSPEC,
+// CTA_PROTOINFO_TCP_STATE,
+// CTA_PROTOINFO_TCP_WSCALE_ORIGINAL,
+// CTA_PROTOINFO_TCP_WSCALE_REPLY,
+// CTA_PROTOINFO_TCP_FLAGS_ORIGINAL,
+// CTA_PROTOINFO_TCP_FLAGS_REPLY,
+// __CTA_PROTOINFO_TCP_MAX
+// };
+// #define CTA_PROTOINFO_TCP_MAX (__CTA_PROTOINFO_TCP_MAX - 1)
+const (
+ CTA_PROTOINFO_TCP_STATE = 1
+ CTA_PROTOINFO_TCP_WSCALE_ORIGINAL = 2
+ CTA_PROTOINFO_TCP_WSCALE_REPLY = 3
+ CTA_PROTOINFO_TCP_FLAGS_ORIGINAL = 4
+ CTA_PROTOINFO_TCP_FLAGS_REPLY = 5
+)
+
+// /* General form of address family dependent message.
+// */
+// struct nfgenmsg {
+// __u8 nfgen_family; /* AF_xxx */
+// __u8 version; /* nfnetlink version */
+// __be16 res_id; /* resource id */
+// };
+type Nfgenmsg struct {
+ NfgenFamily uint8
+ Version uint8
+ ResId uint16 // big endian
+}
+
+func (msg *Nfgenmsg) Len() int {
+ return SizeofNfgenmsg
+}
+
+func DeserializeNfgenmsg(b []byte) *Nfgenmsg {
+ return (*Nfgenmsg)(unsafe.Pointer(&b[0:SizeofNfgenmsg][0]))
+}
+
+func (msg *Nfgenmsg) Serialize() []byte {
+ return (*(*[SizeofNfgenmsg]byte)(unsafe.Pointer(msg)))[:]
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/genetlink_linux.go b/vendor/github.com/vishvananda/netlink/nl/genetlink_linux.go
new file mode 100644
index 0000000..81b46f2
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/genetlink_linux.go
@@ -0,0 +1,89 @@
+package nl
+
+import (
+ "unsafe"
+)
+
+const SizeofGenlmsg = 4
+
+const (
+ GENL_ID_CTRL = 0x10
+ GENL_CTRL_VERSION = 2
+ GENL_CTRL_NAME = "nlctrl"
+)
+
+const (
+ GENL_CTRL_CMD_GETFAMILY = 3
+)
+
+const (
+ GENL_CTRL_ATTR_UNSPEC = iota
+ GENL_CTRL_ATTR_FAMILY_ID
+ GENL_CTRL_ATTR_FAMILY_NAME
+ GENL_CTRL_ATTR_VERSION
+ GENL_CTRL_ATTR_HDRSIZE
+ GENL_CTRL_ATTR_MAXATTR
+ GENL_CTRL_ATTR_OPS
+ GENL_CTRL_ATTR_MCAST_GROUPS
+)
+
+const (
+ GENL_CTRL_ATTR_OP_UNSPEC = iota
+ GENL_CTRL_ATTR_OP_ID
+ GENL_CTRL_ATTR_OP_FLAGS
+)
+
+const (
+ GENL_ADMIN_PERM = 1 << iota
+ GENL_CMD_CAP_DO
+ GENL_CMD_CAP_DUMP
+ GENL_CMD_CAP_HASPOL
+)
+
+const (
+ GENL_CTRL_ATTR_MCAST_GRP_UNSPEC = iota
+ GENL_CTRL_ATTR_MCAST_GRP_NAME
+ GENL_CTRL_ATTR_MCAST_GRP_ID
+)
+
+const (
+ GENL_GTP_VERSION = 0
+ GENL_GTP_NAME = "gtp"
+)
+
+const (
+ GENL_GTP_CMD_NEWPDP = iota
+ GENL_GTP_CMD_DELPDP
+ GENL_GTP_CMD_GETPDP
+)
+
+const (
+ GENL_GTP_ATTR_UNSPEC = iota
+ GENL_GTP_ATTR_LINK
+ GENL_GTP_ATTR_VERSION
+ GENL_GTP_ATTR_TID
+ GENL_GTP_ATTR_PEER_ADDRESS
+ GENL_GTP_ATTR_MS_ADDRESS
+ GENL_GTP_ATTR_FLOW
+ GENL_GTP_ATTR_NET_NS_FD
+ GENL_GTP_ATTR_I_TEI
+ GENL_GTP_ATTR_O_TEI
+ GENL_GTP_ATTR_PAD
+)
+
+type Genlmsg struct {
+ Command uint8
+ Version uint8
+}
+
+func (msg *Genlmsg) Len() int {
+ return SizeofGenlmsg
+}
+
+func DeserializeGenlmsg(b []byte) *Genlmsg {
+ return (*Genlmsg)(unsafe.Pointer(&b[0:SizeofGenlmsg][0]))
+}
+
+func (msg *Genlmsg) Serialize() []byte {
+ return (*(*[SizeofGenlmsg]byte)(unsafe.Pointer(msg)))[:]
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/link_linux.go b/vendor/github.com/vishvananda/netlink/nl/link_linux.go
new file mode 100644
index 0000000..f7b9575
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/link_linux.go
@@ -0,0 +1,524 @@
+package nl
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+const (
+ DEFAULT_CHANGE = 0xFFFFFFFF
+ // doesn't exist in syscall
+ IFLA_VFINFO_LIST = syscall.IFLA_IFALIAS + 1 + iota
+ IFLA_STATS64
+ IFLA_VF_PORTS
+ IFLA_PORT_SELF
+ IFLA_AF_SPEC
+ IFLA_GROUP
+ IFLA_NET_NS_FD
+ IFLA_EXT_MASK
+ IFLA_PROMISCUITY
+ IFLA_NUM_TX_QUEUES
+ IFLA_NUM_RX_QUEUES
+ IFLA_CARRIER
+ IFLA_PHYS_PORT_ID
+ IFLA_CARRIER_CHANGES
+ IFLA_PHYS_SWITCH_ID
+ IFLA_LINK_NETNSID
+ IFLA_PHYS_PORT_NAME
+ IFLA_PROTO_DOWN
+ IFLA_GSO_MAX_SEGS
+ IFLA_GSO_MAX_SIZE
+ IFLA_PAD
+ IFLA_XDP
+)
+
+const (
+ IFLA_INFO_UNSPEC = iota
+ IFLA_INFO_KIND
+ IFLA_INFO_DATA
+ IFLA_INFO_XSTATS
+ IFLA_INFO_MAX = IFLA_INFO_XSTATS
+)
+
+const (
+ IFLA_VLAN_UNSPEC = iota
+ IFLA_VLAN_ID
+ IFLA_VLAN_FLAGS
+ IFLA_VLAN_EGRESS_QOS
+ IFLA_VLAN_INGRESS_QOS
+ IFLA_VLAN_PROTOCOL
+ IFLA_VLAN_MAX = IFLA_VLAN_PROTOCOL
+)
+
+const (
+ VETH_INFO_UNSPEC = iota
+ VETH_INFO_PEER
+ VETH_INFO_MAX = VETH_INFO_PEER
+)
+
+const (
+ IFLA_VXLAN_UNSPEC = iota
+ IFLA_VXLAN_ID
+ IFLA_VXLAN_GROUP
+ IFLA_VXLAN_LINK
+ IFLA_VXLAN_LOCAL
+ IFLA_VXLAN_TTL
+ IFLA_VXLAN_TOS
+ IFLA_VXLAN_LEARNING
+ IFLA_VXLAN_AGEING
+ IFLA_VXLAN_LIMIT
+ IFLA_VXLAN_PORT_RANGE
+ IFLA_VXLAN_PROXY
+ IFLA_VXLAN_RSC
+ IFLA_VXLAN_L2MISS
+ IFLA_VXLAN_L3MISS
+ IFLA_VXLAN_PORT
+ IFLA_VXLAN_GROUP6
+ IFLA_VXLAN_LOCAL6
+ IFLA_VXLAN_UDP_CSUM
+ IFLA_VXLAN_UDP_ZERO_CSUM6_TX
+ IFLA_VXLAN_UDP_ZERO_CSUM6_RX
+ IFLA_VXLAN_REMCSUM_TX
+ IFLA_VXLAN_REMCSUM_RX
+ IFLA_VXLAN_GBP
+ IFLA_VXLAN_REMCSUM_NOPARTIAL
+ IFLA_VXLAN_FLOWBASED
+ IFLA_VXLAN_MAX = IFLA_VXLAN_FLOWBASED
+)
+
+const (
+ BRIDGE_MODE_UNSPEC = iota
+ BRIDGE_MODE_HAIRPIN
+)
+
+const (
+ IFLA_BRPORT_UNSPEC = iota
+ IFLA_BRPORT_STATE
+ IFLA_BRPORT_PRIORITY
+ IFLA_BRPORT_COST
+ IFLA_BRPORT_MODE
+ IFLA_BRPORT_GUARD
+ IFLA_BRPORT_PROTECT
+ IFLA_BRPORT_FAST_LEAVE
+ IFLA_BRPORT_LEARNING
+ IFLA_BRPORT_UNICAST_FLOOD
+ IFLA_BRPORT_PROXYARP
+ IFLA_BRPORT_LEARNING_SYNC
+ IFLA_BRPORT_PROXYARP_WIFI
+ IFLA_BRPORT_MAX = IFLA_BRPORT_PROXYARP_WIFI
+)
+
+const (
+ IFLA_IPVLAN_UNSPEC = iota
+ IFLA_IPVLAN_MODE
+ IFLA_IPVLAN_MAX = IFLA_IPVLAN_MODE
+)
+
+const (
+ IFLA_MACVLAN_UNSPEC = iota
+ IFLA_MACVLAN_MODE
+ IFLA_MACVLAN_FLAGS
+ IFLA_MACVLAN_MAX = IFLA_MACVLAN_FLAGS
+)
+
+const (
+ MACVLAN_MODE_PRIVATE = 1
+ MACVLAN_MODE_VEPA = 2
+ MACVLAN_MODE_BRIDGE = 4
+ MACVLAN_MODE_PASSTHRU = 8
+ MACVLAN_MODE_SOURCE = 16
+)
+
+const (
+ IFLA_BOND_UNSPEC = iota
+ IFLA_BOND_MODE
+ IFLA_BOND_ACTIVE_SLAVE
+ IFLA_BOND_MIIMON
+ IFLA_BOND_UPDELAY
+ IFLA_BOND_DOWNDELAY
+ IFLA_BOND_USE_CARRIER
+ IFLA_BOND_ARP_INTERVAL
+ IFLA_BOND_ARP_IP_TARGET
+ IFLA_BOND_ARP_VALIDATE
+ IFLA_BOND_ARP_ALL_TARGETS
+ IFLA_BOND_PRIMARY
+ IFLA_BOND_PRIMARY_RESELECT
+ IFLA_BOND_FAIL_OVER_MAC
+ IFLA_BOND_XMIT_HASH_POLICY
+ IFLA_BOND_RESEND_IGMP
+ IFLA_BOND_NUM_PEER_NOTIF
+ IFLA_BOND_ALL_SLAVES_ACTIVE
+ IFLA_BOND_MIN_LINKS
+ IFLA_BOND_LP_INTERVAL
+ IFLA_BOND_PACKETS_PER_SLAVE
+ IFLA_BOND_AD_LACP_RATE
+ IFLA_BOND_AD_SELECT
+ IFLA_BOND_AD_INFO
+ IFLA_BOND_AD_ACTOR_SYS_PRIO
+ IFLA_BOND_AD_USER_PORT_KEY
+ IFLA_BOND_AD_ACTOR_SYSTEM
+ IFLA_BOND_TLB_DYNAMIC_LB
+)
+
+const (
+ IFLA_BOND_AD_INFO_UNSPEC = iota
+ IFLA_BOND_AD_INFO_AGGREGATOR
+ IFLA_BOND_AD_INFO_NUM_PORTS
+ IFLA_BOND_AD_INFO_ACTOR_KEY
+ IFLA_BOND_AD_INFO_PARTNER_KEY
+ IFLA_BOND_AD_INFO_PARTNER_MAC
+)
+
+const (
+ IFLA_BOND_SLAVE_UNSPEC = iota
+ IFLA_BOND_SLAVE_STATE
+ IFLA_BOND_SLAVE_MII_STATUS
+ IFLA_BOND_SLAVE_LINK_FAILURE_COUNT
+ IFLA_BOND_SLAVE_PERM_HWADDR
+ IFLA_BOND_SLAVE_QUEUE_ID
+ IFLA_BOND_SLAVE_AD_AGGREGATOR_ID
+)
+
+const (
+ IFLA_GRE_UNSPEC = iota
+ IFLA_GRE_LINK
+ IFLA_GRE_IFLAGS
+ IFLA_GRE_OFLAGS
+ IFLA_GRE_IKEY
+ IFLA_GRE_OKEY
+ IFLA_GRE_LOCAL
+ IFLA_GRE_REMOTE
+ IFLA_GRE_TTL
+ IFLA_GRE_TOS
+ IFLA_GRE_PMTUDISC
+ IFLA_GRE_ENCAP_LIMIT
+ IFLA_GRE_FLOWINFO
+ IFLA_GRE_FLAGS
+ IFLA_GRE_ENCAP_TYPE
+ IFLA_GRE_ENCAP_FLAGS
+ IFLA_GRE_ENCAP_SPORT
+ IFLA_GRE_ENCAP_DPORT
+ IFLA_GRE_COLLECT_METADATA
+ IFLA_GRE_MAX = IFLA_GRE_COLLECT_METADATA
+)
+
+const (
+ GRE_CSUM = 0x8000
+ GRE_ROUTING = 0x4000
+ GRE_KEY = 0x2000
+ GRE_SEQ = 0x1000
+ GRE_STRICT = 0x0800
+ GRE_REC = 0x0700
+ GRE_FLAGS = 0x00F8
+ GRE_VERSION = 0x0007
+)
+
+const (
+ IFLA_VF_INFO_UNSPEC = iota
+ IFLA_VF_INFO
+ IFLA_VF_INFO_MAX = IFLA_VF_INFO
+)
+
+const (
+ IFLA_VF_UNSPEC = iota
+ IFLA_VF_MAC /* Hardware queue specific attributes */
+ IFLA_VF_VLAN
+ IFLA_VF_TX_RATE /* Max TX Bandwidth Allocation */
+ IFLA_VF_SPOOFCHK /* Spoof Checking on/off switch */
+ IFLA_VF_LINK_STATE /* link state enable/disable/auto switch */
+ IFLA_VF_RATE /* Min and Max TX Bandwidth Allocation */
+ IFLA_VF_RSS_QUERY_EN /* RSS Redirection Table and Hash Key query
+ * on/off switch
+ */
+ IFLA_VF_STATS /* network device statistics */
+ IFLA_VF_MAX = IFLA_VF_STATS
+)
+
+const (
+ IFLA_VF_LINK_STATE_AUTO = iota /* link state of the uplink */
+ IFLA_VF_LINK_STATE_ENABLE /* link always up */
+ IFLA_VF_LINK_STATE_DISABLE /* link always down */
+ IFLA_VF_LINK_STATE_MAX = IFLA_VF_LINK_STATE_DISABLE
+)
+
+const (
+ IFLA_VF_STATS_RX_PACKETS = iota
+ IFLA_VF_STATS_TX_PACKETS
+ IFLA_VF_STATS_RX_BYTES
+ IFLA_VF_STATS_TX_BYTES
+ IFLA_VF_STATS_BROADCAST
+ IFLA_VF_STATS_MULTICAST
+ IFLA_VF_STATS_MAX = IFLA_VF_STATS_MULTICAST
+)
+
+const (
+ SizeofVfMac = 0x24
+ SizeofVfVlan = 0x0c
+ SizeofVfTxRate = 0x08
+ SizeofVfRate = 0x0c
+ SizeofVfSpoofchk = 0x08
+ SizeofVfLinkState = 0x08
+ SizeofVfRssQueryEn = 0x08
+)
+
+// struct ifla_vf_mac {
+// __u32 vf;
+// __u8 mac[32]; /* MAX_ADDR_LEN */
+// };
+
+type VfMac struct {
+ Vf uint32
+ Mac [32]byte
+}
+
+func (msg *VfMac) Len() int {
+ return SizeofVfMac
+}
+
+func DeserializeVfMac(b []byte) *VfMac {
+ return (*VfMac)(unsafe.Pointer(&b[0:SizeofVfMac][0]))
+}
+
+func (msg *VfMac) Serialize() []byte {
+ return (*(*[SizeofVfMac]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_vlan {
+// __u32 vf;
+// __u32 vlan; /* 0 - 4095, 0 disables VLAN filter */
+// __u32 qos;
+// };
+
+type VfVlan struct {
+ Vf uint32
+ Vlan uint32
+ Qos uint32
+}
+
+func (msg *VfVlan) Len() int {
+ return SizeofVfVlan
+}
+
+func DeserializeVfVlan(b []byte) *VfVlan {
+ return (*VfVlan)(unsafe.Pointer(&b[0:SizeofVfVlan][0]))
+}
+
+func (msg *VfVlan) Serialize() []byte {
+ return (*(*[SizeofVfVlan]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_tx_rate {
+// __u32 vf;
+// __u32 rate; /* Max TX bandwidth in Mbps, 0 disables throttling */
+// };
+
+type VfTxRate struct {
+ Vf uint32
+ Rate uint32
+}
+
+func (msg *VfTxRate) Len() int {
+ return SizeofVfTxRate
+}
+
+func DeserializeVfTxRate(b []byte) *VfTxRate {
+ return (*VfTxRate)(unsafe.Pointer(&b[0:SizeofVfTxRate][0]))
+}
+
+func (msg *VfTxRate) Serialize() []byte {
+ return (*(*[SizeofVfTxRate]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_rate {
+// __u32 vf;
+// __u32 min_tx_rate; /* Min Bandwidth in Mbps */
+// __u32 max_tx_rate; /* Max Bandwidth in Mbps */
+// };
+
+type VfRate struct {
+ Vf uint32
+ MinTxRate uint32
+ MaxTxRate uint32
+}
+
+func (msg *VfRate) Len() int {
+ return SizeofVfRate
+}
+
+func DeserializeVfRate(b []byte) *VfRate {
+ return (*VfRate)(unsafe.Pointer(&b[0:SizeofVfRate][0]))
+}
+
+func (msg *VfRate) Serialize() []byte {
+ return (*(*[SizeofVfRate]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_spoofchk {
+// __u32 vf;
+// __u32 setting;
+// };
+
+type VfSpoofchk struct {
+ Vf uint32
+ Setting uint32
+}
+
+func (msg *VfSpoofchk) Len() int {
+ return SizeofVfSpoofchk
+}
+
+func DeserializeVfSpoofchk(b []byte) *VfSpoofchk {
+ return (*VfSpoofchk)(unsafe.Pointer(&b[0:SizeofVfSpoofchk][0]))
+}
+
+func (msg *VfSpoofchk) Serialize() []byte {
+ return (*(*[SizeofVfSpoofchk]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_link_state {
+// __u32 vf;
+// __u32 link_state;
+// };
+
+type VfLinkState struct {
+ Vf uint32
+ LinkState uint32
+}
+
+func (msg *VfLinkState) Len() int {
+ return SizeofVfLinkState
+}
+
+func DeserializeVfLinkState(b []byte) *VfLinkState {
+ return (*VfLinkState)(unsafe.Pointer(&b[0:SizeofVfLinkState][0]))
+}
+
+func (msg *VfLinkState) Serialize() []byte {
+ return (*(*[SizeofVfLinkState]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_rss_query_en {
+// __u32 vf;
+// __u32 setting;
+// };
+
+type VfRssQueryEn struct {
+ Vf uint32
+ Setting uint32
+}
+
+func (msg *VfRssQueryEn) Len() int {
+ return SizeofVfRssQueryEn
+}
+
+func DeserializeVfRssQueryEn(b []byte) *VfRssQueryEn {
+ return (*VfRssQueryEn)(unsafe.Pointer(&b[0:SizeofVfRssQueryEn][0]))
+}
+
+func (msg *VfRssQueryEn) Serialize() []byte {
+ return (*(*[SizeofVfRssQueryEn]byte)(unsafe.Pointer(msg)))[:]
+}
+
+const (
+ IFLA_XDP_UNSPEC = iota
+ IFLA_XDP_FD /* fd of xdp program to attach, or -1 to remove */
+ IFLA_XDP_ATTACHED /* read-only bool indicating if prog is attached */
+ IFLA_XDP_FLAGS /* xdp prog related flags */
+ IFLA_XDP_MAX = IFLA_XDP_FLAGS
+)
+
+const (
+ IFLA_IPTUN_UNSPEC = iota
+ IFLA_IPTUN_LINK
+ IFLA_IPTUN_LOCAL
+ IFLA_IPTUN_REMOTE
+ IFLA_IPTUN_TTL
+ IFLA_IPTUN_TOS
+ IFLA_IPTUN_ENCAP_LIMIT
+ IFLA_IPTUN_FLOWINFO
+ IFLA_IPTUN_FLAGS
+ IFLA_IPTUN_PROTO
+ IFLA_IPTUN_PMTUDISC
+ IFLA_IPTUN_6RD_PREFIX
+ IFLA_IPTUN_6RD_RELAY_PREFIX
+ IFLA_IPTUN_6RD_PREFIXLEN
+ IFLA_IPTUN_6RD_RELAY_PREFIXLEN
+ IFLA_IPTUN_MAX = IFLA_IPTUN_6RD_RELAY_PREFIXLEN
+)
+
+const (
+ IFLA_VTI_UNSPEC = iota
+ IFLA_VTI_LINK
+ IFLA_VTI_IKEY
+ IFLA_VTI_OKEY
+ IFLA_VTI_LOCAL
+ IFLA_VTI_REMOTE
+ IFLA_VTI_MAX = IFLA_VTI_REMOTE
+)
+
+const (
+ IFLA_VRF_UNSPEC = iota
+ IFLA_VRF_TABLE
+)
+
+const (
+ IFLA_BR_UNSPEC = iota
+ IFLA_BR_FORWARD_DELAY
+ IFLA_BR_HELLO_TIME
+ IFLA_BR_MAX_AGE
+ IFLA_BR_AGEING_TIME
+ IFLA_BR_STP_STATE
+ IFLA_BR_PRIORITY
+ IFLA_BR_VLAN_FILTERING
+ IFLA_BR_VLAN_PROTOCOL
+ IFLA_BR_GROUP_FWD_MASK
+ IFLA_BR_ROOT_ID
+ IFLA_BR_BRIDGE_ID
+ IFLA_BR_ROOT_PORT
+ IFLA_BR_ROOT_PATH_COST
+ IFLA_BR_TOPOLOGY_CHANGE
+ IFLA_BR_TOPOLOGY_CHANGE_DETECTED
+ IFLA_BR_HELLO_TIMER
+ IFLA_BR_TCN_TIMER
+ IFLA_BR_TOPOLOGY_CHANGE_TIMER
+ IFLA_BR_GC_TIMER
+ IFLA_BR_GROUP_ADDR
+ IFLA_BR_FDB_FLUSH
+ IFLA_BR_MCAST_ROUTER
+ IFLA_BR_MCAST_SNOOPING
+ IFLA_BR_MCAST_QUERY_USE_IFADDR
+ IFLA_BR_MCAST_QUERIER
+ IFLA_BR_MCAST_HASH_ELASTICITY
+ IFLA_BR_MCAST_HASH_MAX
+ IFLA_BR_MCAST_LAST_MEMBER_CNT
+ IFLA_BR_MCAST_STARTUP_QUERY_CNT
+ IFLA_BR_MCAST_LAST_MEMBER_INTVL
+ IFLA_BR_MCAST_MEMBERSHIP_INTVL
+ IFLA_BR_MCAST_QUERIER_INTVL
+ IFLA_BR_MCAST_QUERY_INTVL
+ IFLA_BR_MCAST_QUERY_RESPONSE_INTVL
+ IFLA_BR_MCAST_STARTUP_QUERY_INTVL
+ IFLA_BR_NF_CALL_IPTABLES
+ IFLA_BR_NF_CALL_IP6TABLES
+ IFLA_BR_NF_CALL_ARPTABLES
+ IFLA_BR_VLAN_DEFAULT_PVID
+ IFLA_BR_PAD
+ IFLA_BR_VLAN_STATS_ENABLED
+ IFLA_BR_MCAST_STATS_ENABLED
+ IFLA_BR_MCAST_IGMP_VERSION
+ IFLA_BR_MCAST_MLD_VERSION
+ IFLA_BR_MAX = IFLA_BR_MCAST_MLD_VERSION
+)
+
+const (
+ IFLA_GTP_UNSPEC = iota
+ IFLA_GTP_FD0
+ IFLA_GTP_FD1
+ IFLA_GTP_PDP_HASHSIZE
+ IFLA_GTP_ROLE
+)
+
+const (
+ GTP_ROLE_GGSN = iota
+ GTP_ROLE_SGSN
+)
diff --git a/vendor/github.com/vishvananda/netlink/nl/mpls_linux.go b/vendor/github.com/vishvananda/netlink/nl/mpls_linux.go
new file mode 100644
index 0000000..3915b7e
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/mpls_linux.go
@@ -0,0 +1,36 @@
+package nl
+
+import "encoding/binary"
+
+const (
+ MPLS_LS_LABEL_SHIFT = 12
+ MPLS_LS_S_SHIFT = 8
+)
+
+func EncodeMPLSStack(labels ...int) []byte {
+ b := make([]byte, 4*len(labels))
+ for idx, label := range labels {
+ l := label << MPLS_LS_LABEL_SHIFT
+ if idx == len(labels)-1 {
+ l |= 1 << MPLS_LS_S_SHIFT
+ }
+ binary.BigEndian.PutUint32(b[idx*4:], uint32(l))
+ }
+ return b
+}
+
+func DecodeMPLSStack(buf []byte) []int {
+ if len(buf)%4 != 0 {
+ return nil
+ }
+ stack := make([]int, 0, len(buf)/4)
+ for len(buf) > 0 {
+ l := binary.BigEndian.Uint32(buf[:4])
+ buf = buf[4:]
+ stack = append(stack, int(l)>>MPLS_LS_LABEL_SHIFT)
+ if (l>>MPLS_LS_S_SHIFT)&1 > 0 {
+ break
+ }
+ }
+ return stack
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/nl_linux.go b/vendor/github.com/vishvananda/netlink/nl/nl_linux.go
new file mode 100644
index 0000000..1329acd
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/nl_linux.go
@@ -0,0 +1,718 @@
+// Package nl has low level primitives for making Netlink calls.
+package nl
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "net"
+ "runtime"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "unsafe"
+
+ "github.com/vishvananda/netns"
+)
+
+const (
+ // Family type definitions
+ FAMILY_ALL = syscall.AF_UNSPEC
+ FAMILY_V4 = syscall.AF_INET
+ FAMILY_V6 = syscall.AF_INET6
+ FAMILY_MPLS = AF_MPLS
+)
+
+// SupportedNlFamilies contains the list of netlink families this netlink package supports
+var SupportedNlFamilies = []int{syscall.NETLINK_ROUTE, syscall.NETLINK_XFRM, syscall.NETLINK_NETFILTER}
+
+var nextSeqNr uint32
+
+// GetIPFamily returns the family type of a net.IP.
+func GetIPFamily(ip net.IP) int {
+ if len(ip) <= net.IPv4len {
+ return FAMILY_V4
+ }
+ if ip.To4() != nil {
+ return FAMILY_V4
+ }
+ return FAMILY_V6
+}
+
+var nativeEndian binary.ByteOrder
+
+// Get native endianness for the system
+func NativeEndian() binary.ByteOrder {
+ if nativeEndian == nil {
+ var x uint32 = 0x01020304
+ if *(*byte)(unsafe.Pointer(&x)) == 0x01 {
+ nativeEndian = binary.BigEndian
+ } else {
+ nativeEndian = binary.LittleEndian
+ }
+ }
+ return nativeEndian
+}
+
+// Byte swap a 16 bit value if we aren't big endian
+func Swap16(i uint16) uint16 {
+ if NativeEndian() == binary.BigEndian {
+ return i
+ }
+ return (i&0xff00)>>8 | (i&0xff)<<8
+}
+
+// Byte swap a 32 bit value if aren't big endian
+func Swap32(i uint32) uint32 {
+ if NativeEndian() == binary.BigEndian {
+ return i
+ }
+ return (i&0xff000000)>>24 | (i&0xff0000)>>8 | (i&0xff00)<<8 | (i&0xff)<<24
+}
+
+type NetlinkRequestData interface {
+ Len() int
+ Serialize() []byte
+}
+
+// IfInfomsg is related to links, but it is used for list requests as well
+type IfInfomsg struct {
+ syscall.IfInfomsg
+}
+
+// Create an IfInfomsg with family specified
+func NewIfInfomsg(family int) *IfInfomsg {
+ return &IfInfomsg{
+ IfInfomsg: syscall.IfInfomsg{
+ Family: uint8(family),
+ },
+ }
+}
+
+func DeserializeIfInfomsg(b []byte) *IfInfomsg {
+ return (*IfInfomsg)(unsafe.Pointer(&b[0:syscall.SizeofIfInfomsg][0]))
+}
+
+func (msg *IfInfomsg) Serialize() []byte {
+ return (*(*[syscall.SizeofIfInfomsg]byte)(unsafe.Pointer(msg)))[:]
+}
+
+func (msg *IfInfomsg) Len() int {
+ return syscall.SizeofIfInfomsg
+}
+
+func (msg *IfInfomsg) EncapType() string {
+ switch msg.Type {
+ case 0:
+ return "generic"
+ case syscall.ARPHRD_ETHER:
+ return "ether"
+ case syscall.ARPHRD_EETHER:
+ return "eether"
+ case syscall.ARPHRD_AX25:
+ return "ax25"
+ case syscall.ARPHRD_PRONET:
+ return "pronet"
+ case syscall.ARPHRD_CHAOS:
+ return "chaos"
+ case syscall.ARPHRD_IEEE802:
+ return "ieee802"
+ case syscall.ARPHRD_ARCNET:
+ return "arcnet"
+ case syscall.ARPHRD_APPLETLK:
+ return "atalk"
+ case syscall.ARPHRD_DLCI:
+ return "dlci"
+ case syscall.ARPHRD_ATM:
+ return "atm"
+ case syscall.ARPHRD_METRICOM:
+ return "metricom"
+ case syscall.ARPHRD_IEEE1394:
+ return "ieee1394"
+ case syscall.ARPHRD_INFINIBAND:
+ return "infiniband"
+ case syscall.ARPHRD_SLIP:
+ return "slip"
+ case syscall.ARPHRD_CSLIP:
+ return "cslip"
+ case syscall.ARPHRD_SLIP6:
+ return "slip6"
+ case syscall.ARPHRD_CSLIP6:
+ return "cslip6"
+ case syscall.ARPHRD_RSRVD:
+ return "rsrvd"
+ case syscall.ARPHRD_ADAPT:
+ return "adapt"
+ case syscall.ARPHRD_ROSE:
+ return "rose"
+ case syscall.ARPHRD_X25:
+ return "x25"
+ case syscall.ARPHRD_HWX25:
+ return "hwx25"
+ case syscall.ARPHRD_PPP:
+ return "ppp"
+ case syscall.ARPHRD_HDLC:
+ return "hdlc"
+ case syscall.ARPHRD_LAPB:
+ return "lapb"
+ case syscall.ARPHRD_DDCMP:
+ return "ddcmp"
+ case syscall.ARPHRD_RAWHDLC:
+ return "rawhdlc"
+ case syscall.ARPHRD_TUNNEL:
+ return "ipip"
+ case syscall.ARPHRD_TUNNEL6:
+ return "tunnel6"
+ case syscall.ARPHRD_FRAD:
+ return "frad"
+ case syscall.ARPHRD_SKIP:
+ return "skip"
+ case syscall.ARPHRD_LOOPBACK:
+ return "loopback"
+ case syscall.ARPHRD_LOCALTLK:
+ return "ltalk"
+ case syscall.ARPHRD_FDDI:
+ return "fddi"
+ case syscall.ARPHRD_BIF:
+ return "bif"
+ case syscall.ARPHRD_SIT:
+ return "sit"
+ case syscall.ARPHRD_IPDDP:
+ return "ip/ddp"
+ case syscall.ARPHRD_IPGRE:
+ return "gre"
+ case syscall.ARPHRD_PIMREG:
+ return "pimreg"
+ case syscall.ARPHRD_HIPPI:
+ return "hippi"
+ case syscall.ARPHRD_ASH:
+ return "ash"
+ case syscall.ARPHRD_ECONET:
+ return "econet"
+ case syscall.ARPHRD_IRDA:
+ return "irda"
+ case syscall.ARPHRD_FCPP:
+ return "fcpp"
+ case syscall.ARPHRD_FCAL:
+ return "fcal"
+ case syscall.ARPHRD_FCPL:
+ return "fcpl"
+ case syscall.ARPHRD_FCFABRIC:
+ return "fcfb0"
+ case syscall.ARPHRD_FCFABRIC + 1:
+ return "fcfb1"
+ case syscall.ARPHRD_FCFABRIC + 2:
+ return "fcfb2"
+ case syscall.ARPHRD_FCFABRIC + 3:
+ return "fcfb3"
+ case syscall.ARPHRD_FCFABRIC + 4:
+ return "fcfb4"
+ case syscall.ARPHRD_FCFABRIC + 5:
+ return "fcfb5"
+ case syscall.ARPHRD_FCFABRIC + 6:
+ return "fcfb6"
+ case syscall.ARPHRD_FCFABRIC + 7:
+ return "fcfb7"
+ case syscall.ARPHRD_FCFABRIC + 8:
+ return "fcfb8"
+ case syscall.ARPHRD_FCFABRIC + 9:
+ return "fcfb9"
+ case syscall.ARPHRD_FCFABRIC + 10:
+ return "fcfb10"
+ case syscall.ARPHRD_FCFABRIC + 11:
+ return "fcfb11"
+ case syscall.ARPHRD_FCFABRIC + 12:
+ return "fcfb12"
+ case syscall.ARPHRD_IEEE802_TR:
+ return "tr"
+ case syscall.ARPHRD_IEEE80211:
+ return "ieee802.11"
+ case syscall.ARPHRD_IEEE80211_PRISM:
+ return "ieee802.11/prism"
+ case syscall.ARPHRD_IEEE80211_RADIOTAP:
+ return "ieee802.11/radiotap"
+ case syscall.ARPHRD_IEEE802154:
+ return "ieee802.15.4"
+
+ case 65534:
+ return "none"
+ case 65535:
+ return "void"
+ }
+ return fmt.Sprintf("unknown%d", msg.Type)
+}
+
+func rtaAlignOf(attrlen int) int {
+ return (attrlen + syscall.RTA_ALIGNTO - 1) & ^(syscall.RTA_ALIGNTO - 1)
+}
+
+func NewIfInfomsgChild(parent *RtAttr, family int) *IfInfomsg {
+ msg := NewIfInfomsg(family)
+ parent.children = append(parent.children, msg)
+ return msg
+}
+
+// Extend RtAttr to handle data and children
+type RtAttr struct {
+ syscall.RtAttr
+ Data []byte
+ children []NetlinkRequestData
+}
+
+// Create a new Extended RtAttr object
+func NewRtAttr(attrType int, data []byte) *RtAttr {
+ return &RtAttr{
+ RtAttr: syscall.RtAttr{
+ Type: uint16(attrType),
+ },
+ children: []NetlinkRequestData{},
+ Data: data,
+ }
+}
+
+// Create a new RtAttr obj anc add it as a child of an existing object
+func NewRtAttrChild(parent *RtAttr, attrType int, data []byte) *RtAttr {
+ attr := NewRtAttr(attrType, data)
+ parent.children = append(parent.children, attr)
+ return attr
+}
+
+func (a *RtAttr) Len() int {
+ if len(a.children) == 0 {
+ return (syscall.SizeofRtAttr + len(a.Data))
+ }
+
+ l := 0
+ for _, child := range a.children {
+ l += rtaAlignOf(child.Len())
+ }
+ l += syscall.SizeofRtAttr
+ return rtaAlignOf(l + len(a.Data))
+}
+
+// Serialize the RtAttr into a byte array
+// This can't just unsafe.cast because it must iterate through children.
+func (a *RtAttr) Serialize() []byte {
+ native := NativeEndian()
+
+ length := a.Len()
+ buf := make([]byte, rtaAlignOf(length))
+
+ next := 4
+ if a.Data != nil {
+ copy(buf[next:], a.Data)
+ next += rtaAlignOf(len(a.Data))
+ }
+ if len(a.children) > 0 {
+ for _, child := range a.children {
+ childBuf := child.Serialize()
+ copy(buf[next:], childBuf)
+ next += rtaAlignOf(len(childBuf))
+ }
+ }
+
+ if l := uint16(length); l != 0 {
+ native.PutUint16(buf[0:2], l)
+ }
+ native.PutUint16(buf[2:4], a.Type)
+ return buf
+}
+
+type NetlinkRequest struct {
+ syscall.NlMsghdr
+ Data []NetlinkRequestData
+ RawData []byte
+ Sockets map[int]*SocketHandle
+}
+
+// Serialize the Netlink Request into a byte array
+func (req *NetlinkRequest) Serialize() []byte {
+ length := syscall.SizeofNlMsghdr
+ dataBytes := make([][]byte, len(req.Data))
+ for i, data := range req.Data {
+ dataBytes[i] = data.Serialize()
+ length = length + len(dataBytes[i])
+ }
+ length += len(req.RawData)
+
+ req.Len = uint32(length)
+ b := make([]byte, length)
+ hdr := (*(*[syscall.SizeofNlMsghdr]byte)(unsafe.Pointer(req)))[:]
+ next := syscall.SizeofNlMsghdr
+ copy(b[0:next], hdr)
+ for _, data := range dataBytes {
+ for _, dataByte := range data {
+ b[next] = dataByte
+ next = next + 1
+ }
+ }
+ // Add the raw data if any
+ if len(req.RawData) > 0 {
+ copy(b[next:length], req.RawData)
+ }
+ return b
+}
+
+func (req *NetlinkRequest) AddData(data NetlinkRequestData) {
+ if data != nil {
+ req.Data = append(req.Data, data)
+ }
+}
+
+// AddRawData adds raw bytes to the end of the NetlinkRequest object during serialization
+func (req *NetlinkRequest) AddRawData(data []byte) {
+ if data != nil {
+ req.RawData = append(req.RawData, data...)
+ }
+}
+
+// Execute the request against a the given sockType.
+// Returns a list of netlink messages in serialized format, optionally filtered
+// by resType.
+func (req *NetlinkRequest) Execute(sockType int, resType uint16) ([][]byte, error) {
+ var (
+ s *NetlinkSocket
+ err error
+ )
+
+ if req.Sockets != nil {
+ if sh, ok := req.Sockets[sockType]; ok {
+ s = sh.Socket
+ req.Seq = atomic.AddUint32(&sh.Seq, 1)
+ }
+ }
+ sharedSocket := s != nil
+
+ if s == nil {
+ s, err = getNetlinkSocket(sockType)
+ if err != nil {
+ return nil, err
+ }
+ defer s.Close()
+ } else {
+ s.Lock()
+ defer s.Unlock()
+ }
+
+ if err := s.Send(req); err != nil {
+ return nil, err
+ }
+
+ pid, err := s.GetPid()
+ if err != nil {
+ return nil, err
+ }
+
+ var res [][]byte
+
+done:
+ for {
+ msgs, err := s.Receive()
+ if err != nil {
+ return nil, err
+ }
+ for _, m := range msgs {
+ if m.Header.Seq != req.Seq {
+ if sharedSocket {
+ continue
+ }
+ return nil, fmt.Errorf("Wrong Seq nr %d, expected %d", m.Header.Seq, req.Seq)
+ }
+ if m.Header.Pid != pid {
+ return nil, fmt.Errorf("Wrong pid %d, expected %d", m.Header.Pid, pid)
+ }
+ if m.Header.Type == syscall.NLMSG_DONE {
+ break done
+ }
+ if m.Header.Type == syscall.NLMSG_ERROR {
+ native := NativeEndian()
+ error := int32(native.Uint32(m.Data[0:4]))
+ if error == 0 {
+ break done
+ }
+ return nil, syscall.Errno(-error)
+ }
+ if resType != 0 && m.Header.Type != resType {
+ continue
+ }
+ res = append(res, m.Data)
+ if m.Header.Flags&syscall.NLM_F_MULTI == 0 {
+ break done
+ }
+ }
+ }
+ return res, nil
+}
+
+// Create a new netlink request from proto and flags
+// Note the Len value will be inaccurate once data is added until
+// the message is serialized
+func NewNetlinkRequest(proto, flags int) *NetlinkRequest {
+ return &NetlinkRequest{
+ NlMsghdr: syscall.NlMsghdr{
+ Len: uint32(syscall.SizeofNlMsghdr),
+ Type: uint16(proto),
+ Flags: syscall.NLM_F_REQUEST | uint16(flags),
+ Seq: atomic.AddUint32(&nextSeqNr, 1),
+ },
+ }
+}
+
+type NetlinkSocket struct {
+ fd int32
+ lsa syscall.SockaddrNetlink
+ sync.Mutex
+}
+
+func getNetlinkSocket(protocol int) (*NetlinkSocket, error) {
+ fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW|syscall.SOCK_CLOEXEC, protocol)
+ if err != nil {
+ return nil, err
+ }
+ s := &NetlinkSocket{
+ fd: int32(fd),
+ }
+ s.lsa.Family = syscall.AF_NETLINK
+ if err := syscall.Bind(fd, &s.lsa); err != nil {
+ syscall.Close(fd)
+ return nil, err
+ }
+
+ return s, nil
+}
+
+// GetNetlinkSocketAt opens a netlink socket in the network namespace newNs
+// and positions the thread back into the network namespace specified by curNs,
+// when done. If curNs is close, the function derives the current namespace and
+// moves back into it when done. If newNs is close, the socket will be opened
+// in the current network namespace.
+func GetNetlinkSocketAt(newNs, curNs netns.NsHandle, protocol int) (*NetlinkSocket, error) {
+ c, err := executeInNetns(newNs, curNs)
+ if err != nil {
+ return nil, err
+ }
+ defer c()
+ return getNetlinkSocket(protocol)
+}
+
+// executeInNetns sets execution of the code following this call to the
+// network namespace newNs, then moves the thread back to curNs if open,
+// otherwise to the current netns at the time the function was invoked
+// In case of success, the caller is expected to execute the returned function
+// at the end of the code that needs to be executed in the network namespace.
+// Example:
+// func jobAt(...) error {
+// d, err := executeInNetns(...)
+// if err != nil { return err}
+// defer d()
+// < code which needs to be executed in specific netns>
+// }
+// TODO: his function probably belongs to netns pkg.
+func executeInNetns(newNs, curNs netns.NsHandle) (func(), error) {
+ var (
+ err error
+ moveBack func(netns.NsHandle) error
+ closeNs func() error
+ unlockThd func()
+ )
+ restore := func() {
+ // order matters
+ if moveBack != nil {
+ moveBack(curNs)
+ }
+ if closeNs != nil {
+ closeNs()
+ }
+ if unlockThd != nil {
+ unlockThd()
+ }
+ }
+ if newNs.IsOpen() {
+ runtime.LockOSThread()
+ unlockThd = runtime.UnlockOSThread
+ if !curNs.IsOpen() {
+ if curNs, err = netns.Get(); err != nil {
+ restore()
+ return nil, fmt.Errorf("could not get current namespace while creating netlink socket: %v", err)
+ }
+ closeNs = curNs.Close
+ }
+ if err := netns.Set(newNs); err != nil {
+ restore()
+ return nil, fmt.Errorf("failed to set into network namespace %d while creating netlink socket: %v", newNs, err)
+ }
+ moveBack = netns.Set
+ }
+ return restore, nil
+}
+
+// Create a netlink socket with a given protocol (e.g. NETLINK_ROUTE)
+// and subscribe it to multicast groups passed in variable argument list.
+// Returns the netlink socket on which Receive() method can be called
+// to retrieve the messages from the kernel.
+func Subscribe(protocol int, groups ...uint) (*NetlinkSocket, error) {
+ fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, protocol)
+ if err != nil {
+ return nil, err
+ }
+ s := &NetlinkSocket{
+ fd: int32(fd),
+ }
+ s.lsa.Family = syscall.AF_NETLINK
+
+ for _, g := range groups {
+ s.lsa.Groups |= (1 << (g - 1))
+ }
+
+ if err := syscall.Bind(fd, &s.lsa); err != nil {
+ syscall.Close(fd)
+ return nil, err
+ }
+
+ return s, nil
+}
+
+// SubscribeAt works like Subscribe plus let's the caller choose the network
+// namespace in which the socket would be opened (newNs). Then control goes back
+// to curNs if open, otherwise to the netns at the time this function was called.
+func SubscribeAt(newNs, curNs netns.NsHandle, protocol int, groups ...uint) (*NetlinkSocket, error) {
+ c, err := executeInNetns(newNs, curNs)
+ if err != nil {
+ return nil, err
+ }
+ defer c()
+ return Subscribe(protocol, groups...)
+}
+
+func (s *NetlinkSocket) Close() {
+ fd := int(atomic.SwapInt32(&s.fd, -1))
+ syscall.Close(fd)
+}
+
+func (s *NetlinkSocket) GetFd() int {
+ return int(atomic.LoadInt32(&s.fd))
+}
+
+func (s *NetlinkSocket) Send(request *NetlinkRequest) error {
+ fd := int(atomic.LoadInt32(&s.fd))
+ if fd < 0 {
+ return fmt.Errorf("Send called on a closed socket")
+ }
+ if err := syscall.Sendto(fd, request.Serialize(), 0, &s.lsa); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (s *NetlinkSocket) Receive() ([]syscall.NetlinkMessage, error) {
+ fd := int(atomic.LoadInt32(&s.fd))
+ if fd < 0 {
+ return nil, fmt.Errorf("Receive called on a closed socket")
+ }
+ rb := make([]byte, syscall.Getpagesize())
+ nr, _, err := syscall.Recvfrom(fd, rb, 0)
+ if err != nil {
+ return nil, err
+ }
+ if nr < syscall.NLMSG_HDRLEN {
+ return nil, fmt.Errorf("Got short response from netlink")
+ }
+ rb = rb[:nr]
+ return syscall.ParseNetlinkMessage(rb)
+}
+
+func (s *NetlinkSocket) GetPid() (uint32, error) {
+ fd := int(atomic.LoadInt32(&s.fd))
+ lsa, err := syscall.Getsockname(fd)
+ if err != nil {
+ return 0, err
+ }
+ switch v := lsa.(type) {
+ case *syscall.SockaddrNetlink:
+ return v.Pid, nil
+ }
+ return 0, fmt.Errorf("Wrong socket type")
+}
+
+func ZeroTerminated(s string) []byte {
+ bytes := make([]byte, len(s)+1)
+ for i := 0; i < len(s); i++ {
+ bytes[i] = s[i]
+ }
+ bytes[len(s)] = 0
+ return bytes
+}
+
+func NonZeroTerminated(s string) []byte {
+ bytes := make([]byte, len(s))
+ for i := 0; i < len(s); i++ {
+ bytes[i] = s[i]
+ }
+ return bytes
+}
+
+func BytesToString(b []byte) string {
+ n := bytes.Index(b, []byte{0})
+ return string(b[:n])
+}
+
+func Uint8Attr(v uint8) []byte {
+ return []byte{byte(v)}
+}
+
+func Uint16Attr(v uint16) []byte {
+ native := NativeEndian()
+ bytes := make([]byte, 2)
+ native.PutUint16(bytes, v)
+ return bytes
+}
+
+func Uint32Attr(v uint32) []byte {
+ native := NativeEndian()
+ bytes := make([]byte, 4)
+ native.PutUint32(bytes, v)
+ return bytes
+}
+
+func Uint64Attr(v uint64) []byte {
+ native := NativeEndian()
+ bytes := make([]byte, 8)
+ native.PutUint64(bytes, v)
+ return bytes
+}
+
+func ParseRouteAttr(b []byte) ([]syscall.NetlinkRouteAttr, error) {
+ var attrs []syscall.NetlinkRouteAttr
+ for len(b) >= syscall.SizeofRtAttr {
+ a, vbuf, alen, err := netlinkRouteAttrAndValue(b)
+ if err != nil {
+ return nil, err
+ }
+ ra := syscall.NetlinkRouteAttr{Attr: *a, Value: vbuf[:int(a.Len)-syscall.SizeofRtAttr]}
+ attrs = append(attrs, ra)
+ b = b[alen:]
+ }
+ return attrs, nil
+}
+
+func netlinkRouteAttrAndValue(b []byte) (*syscall.RtAttr, []byte, int, error) {
+ a := (*syscall.RtAttr)(unsafe.Pointer(&b[0]))
+ if int(a.Len) < syscall.SizeofRtAttr || int(a.Len) > len(b) {
+ return nil, nil, 0, syscall.EINVAL
+ }
+ return a, b[syscall.SizeofRtAttr:], rtaAlignOf(int(a.Len)), nil
+}
+
+// SocketHandle contains the netlink socket and the associated
+// sequence counter for a specific netlink family
+type SocketHandle struct {
+ Seq uint32
+ Socket *NetlinkSocket
+}
+
+// Close closes the netlink socket
+func (sh *SocketHandle) Close() {
+ if sh.Socket != nil {
+ sh.Socket.Close()
+ }
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/nl_unspecified.go b/vendor/github.com/vishvananda/netlink/nl/nl_unspecified.go
new file mode 100644
index 0000000..dfc0be6
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/nl_unspecified.go
@@ -0,0 +1,11 @@
+// +build !linux
+
+package nl
+
+import "encoding/binary"
+
+var SupportedNlFamilies = []int{}
+
+func NativeEndian() binary.ByteOrder {
+ return nil
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/route_linux.go b/vendor/github.com/vishvananda/netlink/nl/route_linux.go
new file mode 100644
index 0000000..1a064d6
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/route_linux.go
@@ -0,0 +1,80 @@
+package nl
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+type RtMsg struct {
+ syscall.RtMsg
+}
+
+func NewRtMsg() *RtMsg {
+ return &RtMsg{
+ RtMsg: syscall.RtMsg{
+ Table: syscall.RT_TABLE_MAIN,
+ Scope: syscall.RT_SCOPE_UNIVERSE,
+ Protocol: syscall.RTPROT_BOOT,
+ Type: syscall.RTN_UNICAST,
+ },
+ }
+}
+
+func NewRtDelMsg() *RtMsg {
+ return &RtMsg{
+ RtMsg: syscall.RtMsg{
+ Table: syscall.RT_TABLE_MAIN,
+ Scope: syscall.RT_SCOPE_NOWHERE,
+ },
+ }
+}
+
+func (msg *RtMsg) Len() int {
+ return syscall.SizeofRtMsg
+}
+
+func DeserializeRtMsg(b []byte) *RtMsg {
+ return (*RtMsg)(unsafe.Pointer(&b[0:syscall.SizeofRtMsg][0]))
+}
+
+func (msg *RtMsg) Serialize() []byte {
+ return (*(*[syscall.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:]
+}
+
+type RtNexthop struct {
+ syscall.RtNexthop
+ Children []NetlinkRequestData
+}
+
+func DeserializeRtNexthop(b []byte) *RtNexthop {
+ return (*RtNexthop)(unsafe.Pointer(&b[0:syscall.SizeofRtNexthop][0]))
+}
+
+func (msg *RtNexthop) Len() int {
+ if len(msg.Children) == 0 {
+ return syscall.SizeofRtNexthop
+ }
+
+ l := 0
+ for _, child := range msg.Children {
+ l += rtaAlignOf(child.Len())
+ }
+ l += syscall.SizeofRtNexthop
+ return rtaAlignOf(l)
+}
+
+func (msg *RtNexthop) Serialize() []byte {
+ length := msg.Len()
+ msg.RtNexthop.Len = uint16(length)
+ buf := make([]byte, length)
+ copy(buf, (*(*[syscall.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:])
+ next := rtaAlignOf(syscall.SizeofRtNexthop)
+ if len(msg.Children) > 0 {
+ for _, child := range msg.Children {
+ childBuf := child.Serialize()
+ copy(buf[next:], childBuf)
+ next += rtaAlignOf(len(childBuf))
+ }
+ }
+ return buf
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/syscall.go b/vendor/github.com/vishvananda/netlink/nl/syscall.go
new file mode 100644
index 0000000..3473e53
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/syscall.go
@@ -0,0 +1,68 @@
+package nl
+
+// syscall package lack of rule atributes type.
+// Thus there are defined below
+const (
+ FRA_UNSPEC = iota
+ FRA_DST /* destination address */
+ FRA_SRC /* source address */
+ FRA_IIFNAME /* interface name */
+ FRA_GOTO /* target to jump to (FR_ACT_GOTO) */
+ FRA_UNUSED2
+ FRA_PRIORITY /* priority/preference */
+ FRA_UNUSED3
+ FRA_UNUSED4
+ FRA_UNUSED5
+ FRA_FWMARK /* mark */
+ FRA_FLOW /* flow/class id */
+ FRA_TUN_ID
+ FRA_SUPPRESS_IFGROUP
+ FRA_SUPPRESS_PREFIXLEN
+ FRA_TABLE /* Extended table id */
+ FRA_FWMASK /* mask for netfilter mark */
+ FRA_OIFNAME
+)
+
+// ip rule netlink request types
+const (
+ FR_ACT_UNSPEC = iota
+ FR_ACT_TO_TBL /* Pass to fixed table */
+ FR_ACT_GOTO /* Jump to another rule */
+ FR_ACT_NOP /* No operation */
+ FR_ACT_RES3
+ FR_ACT_RES4
+ FR_ACT_BLACKHOLE /* Drop without notification */
+ FR_ACT_UNREACHABLE /* Drop with ENETUNREACH */
+ FR_ACT_PROHIBIT /* Drop with EACCES */
+)
+
+// socket diags related
+const (
+ SOCK_DIAG_BY_FAMILY = 20 /* linux.sock_diag.h */
+ TCPDIAG_NOCOOKIE = 0xFFFFFFFF /* TCPDIAG_NOCOOKIE in net/ipv4/tcp_diag.h*/
+)
+
+const (
+ AF_MPLS = 28
+)
+
+const (
+ RTA_NEWDST = 0x13
+ RTA_ENCAP_TYPE = 0x15
+ RTA_ENCAP = 0x16
+)
+
+// RTA_ENCAP subtype
+const (
+ MPLS_IPTUNNEL_UNSPEC = iota
+ MPLS_IPTUNNEL_DST
+)
+
+// light weight tunnel encap types
+const (
+ LWTUNNEL_ENCAP_NONE = iota
+ LWTUNNEL_ENCAP_MPLS
+ LWTUNNEL_ENCAP_IP
+ LWTUNNEL_ENCAP_ILA
+ LWTUNNEL_ENCAP_IP6
+)
diff --git a/vendor/github.com/vishvananda/netlink/nl/tc_linux.go b/vendor/github.com/vishvananda/netlink/nl/tc_linux.go
new file mode 100644
index 0000000..e91fb21
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/tc_linux.go
@@ -0,0 +1,675 @@
+package nl
+
+import (
+ "unsafe"
+)
+
+// LinkLayer
+const (
+ LINKLAYER_UNSPEC = iota
+ LINKLAYER_ETHERNET
+ LINKLAYER_ATM
+)
+
+// ATM
+const (
+ ATM_CELL_PAYLOAD = 48
+ ATM_CELL_SIZE = 53
+)
+
+const TC_LINKLAYER_MASK = 0x0F
+
+// Police
+const (
+ TCA_POLICE_UNSPEC = iota
+ TCA_POLICE_TBF
+ TCA_POLICE_RATE
+ TCA_POLICE_PEAKRATE
+ TCA_POLICE_AVRATE
+ TCA_POLICE_RESULT
+ TCA_POLICE_MAX = TCA_POLICE_RESULT
+)
+
+// Message types
+const (
+ TCA_UNSPEC = iota
+ TCA_KIND
+ TCA_OPTIONS
+ TCA_STATS
+ TCA_XSTATS
+ TCA_RATE
+ TCA_FCNT
+ TCA_STATS2
+ TCA_STAB
+ TCA_MAX = TCA_STAB
+)
+
+const (
+ TCA_ACT_TAB = 1
+ TCAA_MAX = 1
+)
+
+const (
+ TCA_ACT_UNSPEC = iota
+ TCA_ACT_KIND
+ TCA_ACT_OPTIONS
+ TCA_ACT_INDEX
+ TCA_ACT_STATS
+ TCA_ACT_MAX
+)
+
+const (
+ TCA_PRIO_UNSPEC = iota
+ TCA_PRIO_MQ
+ TCA_PRIO_MAX = TCA_PRIO_MQ
+)
+
+const (
+ SizeofTcMsg = 0x14
+ SizeofTcActionMsg = 0x04
+ SizeofTcPrioMap = 0x14
+ SizeofTcRateSpec = 0x0c
+ SizeofTcNetemQopt = 0x18
+ SizeofTcNetemCorr = 0x0c
+ SizeofTcNetemReorder = 0x08
+ SizeofTcNetemCorrupt = 0x08
+ SizeofTcTbfQopt = 2*SizeofTcRateSpec + 0x0c
+ SizeofTcHtbCopt = 2*SizeofTcRateSpec + 0x14
+ SizeofTcHtbGlob = 0x14
+ SizeofTcU32Key = 0x10
+ SizeofTcU32Sel = 0x10 // without keys
+ SizeofTcGen = 0x14
+ SizeofTcMirred = SizeofTcGen + 0x08
+ SizeofTcPolice = 2*SizeofTcRateSpec + 0x20
+)
+
+// struct tcmsg {
+// unsigned char tcm_family;
+// unsigned char tcm__pad1;
+// unsigned short tcm__pad2;
+// int tcm_ifindex;
+// __u32 tcm_handle;
+// __u32 tcm_parent;
+// __u32 tcm_info;
+// };
+
+type TcMsg struct {
+ Family uint8
+ Pad [3]byte
+ Ifindex int32
+ Handle uint32
+ Parent uint32
+ Info uint32
+}
+
+func (msg *TcMsg) Len() int {
+ return SizeofTcMsg
+}
+
+func DeserializeTcMsg(b []byte) *TcMsg {
+ return (*TcMsg)(unsafe.Pointer(&b[0:SizeofTcMsg][0]))
+}
+
+func (x *TcMsg) Serialize() []byte {
+ return (*(*[SizeofTcMsg]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tcamsg {
+// unsigned char tca_family;
+// unsigned char tca__pad1;
+// unsigned short tca__pad2;
+// };
+
+type TcActionMsg struct {
+ Family uint8
+ Pad [3]byte
+}
+
+func (msg *TcActionMsg) Len() int {
+ return SizeofTcActionMsg
+}
+
+func DeserializeTcActionMsg(b []byte) *TcActionMsg {
+ return (*TcActionMsg)(unsafe.Pointer(&b[0:SizeofTcActionMsg][0]))
+}
+
+func (x *TcActionMsg) Serialize() []byte {
+ return (*(*[SizeofTcActionMsg]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TC_PRIO_MAX = 15
+)
+
+// struct tc_prio_qopt {
+// int bands; /* Number of bands */
+// __u8 priomap[TC_PRIO_MAX+1]; /* Map: logical priority -> PRIO band */
+// };
+
+type TcPrioMap struct {
+ Bands int32
+ Priomap [TC_PRIO_MAX + 1]uint8
+}
+
+func (msg *TcPrioMap) Len() int {
+ return SizeofTcPrioMap
+}
+
+func DeserializeTcPrioMap(b []byte) *TcPrioMap {
+ return (*TcPrioMap)(unsafe.Pointer(&b[0:SizeofTcPrioMap][0]))
+}
+
+func (x *TcPrioMap) Serialize() []byte {
+ return (*(*[SizeofTcPrioMap]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TCA_TBF_UNSPEC = iota
+ TCA_TBF_PARMS
+ TCA_TBF_RTAB
+ TCA_TBF_PTAB
+ TCA_TBF_RATE64
+ TCA_TBF_PRATE64
+ TCA_TBF_BURST
+ TCA_TBF_PBURST
+ TCA_TBF_MAX = TCA_TBF_PBURST
+)
+
+// struct tc_ratespec {
+// unsigned char cell_log;
+// __u8 linklayer; /* lower 4 bits */
+// unsigned short overhead;
+// short cell_align;
+// unsigned short mpu;
+// __u32 rate;
+// };
+
+type TcRateSpec struct {
+ CellLog uint8
+ Linklayer uint8
+ Overhead uint16
+ CellAlign int16
+ Mpu uint16
+ Rate uint32
+}
+
+func (msg *TcRateSpec) Len() int {
+ return SizeofTcRateSpec
+}
+
+func DeserializeTcRateSpec(b []byte) *TcRateSpec {
+ return (*TcRateSpec)(unsafe.Pointer(&b[0:SizeofTcRateSpec][0]))
+}
+
+func (x *TcRateSpec) Serialize() []byte {
+ return (*(*[SizeofTcRateSpec]byte)(unsafe.Pointer(x)))[:]
+}
+
+/**
+* NETEM
+ */
+
+const (
+ TCA_NETEM_UNSPEC = iota
+ TCA_NETEM_CORR
+ TCA_NETEM_DELAY_DIST
+ TCA_NETEM_REORDER
+ TCA_NETEM_CORRUPT
+ TCA_NETEM_LOSS
+ TCA_NETEM_RATE
+ TCA_NETEM_ECN
+ TCA_NETEM_RATE64
+ TCA_NETEM_MAX = TCA_NETEM_RATE64
+)
+
+// struct tc_netem_qopt {
+// __u32 latency; /* added delay (us) */
+// __u32 limit; /* fifo limit (packets) */
+// __u32 loss; /* random packet loss (0=none ~0=100%) */
+// __u32 gap; /* re-ordering gap (0 for none) */
+// __u32 duplicate; /* random packet dup (0=none ~0=100%) */
+// __u32 jitter; /* random jitter in latency (us) */
+// };
+
+type TcNetemQopt struct {
+ Latency uint32
+ Limit uint32
+ Loss uint32
+ Gap uint32
+ Duplicate uint32
+ Jitter uint32
+}
+
+func (msg *TcNetemQopt) Len() int {
+ return SizeofTcNetemQopt
+}
+
+func DeserializeTcNetemQopt(b []byte) *TcNetemQopt {
+ return (*TcNetemQopt)(unsafe.Pointer(&b[0:SizeofTcNetemQopt][0]))
+}
+
+func (x *TcNetemQopt) Serialize() []byte {
+ return (*(*[SizeofTcNetemQopt]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_netem_corr {
+// __u32 delay_corr; /* delay correlation */
+// __u32 loss_corr; /* packet loss correlation */
+// __u32 dup_corr; /* duplicate correlation */
+// };
+
+type TcNetemCorr struct {
+ DelayCorr uint32
+ LossCorr uint32
+ DupCorr uint32
+}
+
+func (msg *TcNetemCorr) Len() int {
+ return SizeofTcNetemCorr
+}
+
+func DeserializeTcNetemCorr(b []byte) *TcNetemCorr {
+ return (*TcNetemCorr)(unsafe.Pointer(&b[0:SizeofTcNetemCorr][0]))
+}
+
+func (x *TcNetemCorr) Serialize() []byte {
+ return (*(*[SizeofTcNetemCorr]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_netem_reorder {
+// __u32 probability;
+// __u32 correlation;
+// };
+
+type TcNetemReorder struct {
+ Probability uint32
+ Correlation uint32
+}
+
+func (msg *TcNetemReorder) Len() int {
+ return SizeofTcNetemReorder
+}
+
+func DeserializeTcNetemReorder(b []byte) *TcNetemReorder {
+ return (*TcNetemReorder)(unsafe.Pointer(&b[0:SizeofTcNetemReorder][0]))
+}
+
+func (x *TcNetemReorder) Serialize() []byte {
+ return (*(*[SizeofTcNetemReorder]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_netem_corrupt {
+// __u32 probability;
+// __u32 correlation;
+// };
+
+type TcNetemCorrupt struct {
+ Probability uint32
+ Correlation uint32
+}
+
+func (msg *TcNetemCorrupt) Len() int {
+ return SizeofTcNetemCorrupt
+}
+
+func DeserializeTcNetemCorrupt(b []byte) *TcNetemCorrupt {
+ return (*TcNetemCorrupt)(unsafe.Pointer(&b[0:SizeofTcNetemCorrupt][0]))
+}
+
+func (x *TcNetemCorrupt) Serialize() []byte {
+ return (*(*[SizeofTcNetemCorrupt]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_tbf_qopt {
+// struct tc_ratespec rate;
+// struct tc_ratespec peakrate;
+// __u32 limit;
+// __u32 buffer;
+// __u32 mtu;
+// };
+
+type TcTbfQopt struct {
+ Rate TcRateSpec
+ Peakrate TcRateSpec
+ Limit uint32
+ Buffer uint32
+ Mtu uint32
+}
+
+func (msg *TcTbfQopt) Len() int {
+ return SizeofTcTbfQopt
+}
+
+func DeserializeTcTbfQopt(b []byte) *TcTbfQopt {
+ return (*TcTbfQopt)(unsafe.Pointer(&b[0:SizeofTcTbfQopt][0]))
+}
+
+func (x *TcTbfQopt) Serialize() []byte {
+ return (*(*[SizeofTcTbfQopt]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TCA_HTB_UNSPEC = iota
+ TCA_HTB_PARMS
+ TCA_HTB_INIT
+ TCA_HTB_CTAB
+ TCA_HTB_RTAB
+ TCA_HTB_DIRECT_QLEN
+ TCA_HTB_RATE64
+ TCA_HTB_CEIL64
+ TCA_HTB_MAX = TCA_HTB_CEIL64
+)
+
+//struct tc_htb_opt {
+// struct tc_ratespec rate;
+// struct tc_ratespec ceil;
+// __u32 buffer;
+// __u32 cbuffer;
+// __u32 quantum;
+// __u32 level; /* out only */
+// __u32 prio;
+//};
+
+type TcHtbCopt struct {
+ Rate TcRateSpec
+ Ceil TcRateSpec
+ Buffer uint32
+ Cbuffer uint32
+ Quantum uint32
+ Level uint32
+ Prio uint32
+}
+
+func (msg *TcHtbCopt) Len() int {
+ return SizeofTcHtbCopt
+}
+
+func DeserializeTcHtbCopt(b []byte) *TcHtbCopt {
+ return (*TcHtbCopt)(unsafe.Pointer(&b[0:SizeofTcHtbCopt][0]))
+}
+
+func (x *TcHtbCopt) Serialize() []byte {
+ return (*(*[SizeofTcHtbCopt]byte)(unsafe.Pointer(x)))[:]
+}
+
+type TcHtbGlob struct {
+ Version uint32
+ Rate2Quantum uint32
+ Defcls uint32
+ Debug uint32
+ DirectPkts uint32
+}
+
+func (msg *TcHtbGlob) Len() int {
+ return SizeofTcHtbGlob
+}
+
+func DeserializeTcHtbGlob(b []byte) *TcHtbGlob {
+ return (*TcHtbGlob)(unsafe.Pointer(&b[0:SizeofTcHtbGlob][0]))
+}
+
+func (x *TcHtbGlob) Serialize() []byte {
+ return (*(*[SizeofTcHtbGlob]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TCA_U32_UNSPEC = iota
+ TCA_U32_CLASSID
+ TCA_U32_HASH
+ TCA_U32_LINK
+ TCA_U32_DIVISOR
+ TCA_U32_SEL
+ TCA_U32_POLICE
+ TCA_U32_ACT
+ TCA_U32_INDEV
+ TCA_U32_PCNT
+ TCA_U32_MARK
+ TCA_U32_MAX = TCA_U32_MARK
+)
+
+// struct tc_u32_key {
+// __be32 mask;
+// __be32 val;
+// int off;
+// int offmask;
+// };
+
+type TcU32Key struct {
+ Mask uint32 // big endian
+ Val uint32 // big endian
+ Off int32
+ OffMask int32
+}
+
+func (msg *TcU32Key) Len() int {
+ return SizeofTcU32Key
+}
+
+func DeserializeTcU32Key(b []byte) *TcU32Key {
+ return (*TcU32Key)(unsafe.Pointer(&b[0:SizeofTcU32Key][0]))
+}
+
+func (x *TcU32Key) Serialize() []byte {
+ return (*(*[SizeofTcU32Key]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_u32_sel {
+// unsigned char flags;
+// unsigned char offshift;
+// unsigned char nkeys;
+//
+// __be16 offmask;
+// __u16 off;
+// short offoff;
+//
+// short hoff;
+// __be32 hmask;
+// struct tc_u32_key keys[0];
+// };
+
+const (
+ TC_U32_TERMINAL = 1 << iota
+ TC_U32_OFFSET = 1 << iota
+ TC_U32_VAROFFSET = 1 << iota
+ TC_U32_EAT = 1 << iota
+)
+
+type TcU32Sel struct {
+ Flags uint8
+ Offshift uint8
+ Nkeys uint8
+ Pad uint8
+ Offmask uint16 // big endian
+ Off uint16
+ Offoff int16
+ Hoff int16
+ Hmask uint32 // big endian
+ Keys []TcU32Key
+}
+
+func (msg *TcU32Sel) Len() int {
+ return SizeofTcU32Sel + int(msg.Nkeys)*SizeofTcU32Key
+}
+
+func DeserializeTcU32Sel(b []byte) *TcU32Sel {
+ x := &TcU32Sel{}
+ copy((*(*[SizeofTcU32Sel]byte)(unsafe.Pointer(x)))[:], b)
+ next := SizeofTcU32Sel
+ var i uint8
+ for i = 0; i < x.Nkeys; i++ {
+ x.Keys = append(x.Keys, *DeserializeTcU32Key(b[next:]))
+ next += SizeofTcU32Key
+ }
+ return x
+}
+
+func (x *TcU32Sel) Serialize() []byte {
+ // This can't just unsafe.cast because it must iterate through keys.
+ buf := make([]byte, x.Len())
+ copy(buf, (*(*[SizeofTcU32Sel]byte)(unsafe.Pointer(x)))[:])
+ next := SizeofTcU32Sel
+ for _, key := range x.Keys {
+ keyBuf := key.Serialize()
+ copy(buf[next:], keyBuf)
+ next += SizeofTcU32Key
+ }
+ return buf
+}
+
+type TcGen struct {
+ Index uint32
+ Capab uint32
+ Action int32
+ Refcnt int32
+ Bindcnt int32
+}
+
+func (msg *TcGen) Len() int {
+ return SizeofTcGen
+}
+
+func DeserializeTcGen(b []byte) *TcGen {
+ return (*TcGen)(unsafe.Pointer(&b[0:SizeofTcGen][0]))
+}
+
+func (x *TcGen) Serialize() []byte {
+ return (*(*[SizeofTcGen]byte)(unsafe.Pointer(x)))[:]
+}
+
+// #define tc_gen \
+// __u32 index; \
+// __u32 capab; \
+// int action; \
+// int refcnt; \
+// int bindcnt
+
+const (
+ TCA_ACT_GACT = 5
+)
+
+const (
+ TCA_GACT_UNSPEC = iota
+ TCA_GACT_TM
+ TCA_GACT_PARMS
+ TCA_GACT_PROB
+ TCA_GACT_MAX = TCA_GACT_PROB
+)
+
+type TcGact TcGen
+
+const (
+ TCA_ACT_BPF = 13
+)
+
+const (
+ TCA_ACT_BPF_UNSPEC = iota
+ TCA_ACT_BPF_TM
+ TCA_ACT_BPF_PARMS
+ TCA_ACT_BPF_OPS_LEN
+ TCA_ACT_BPF_OPS
+ TCA_ACT_BPF_FD
+ TCA_ACT_BPF_NAME
+ TCA_ACT_BPF_MAX = TCA_ACT_BPF_NAME
+)
+
+const (
+ TCA_BPF_FLAG_ACT_DIRECT uint32 = 1 << iota
+)
+
+const (
+ TCA_BPF_UNSPEC = iota
+ TCA_BPF_ACT
+ TCA_BPF_POLICE
+ TCA_BPF_CLASSID
+ TCA_BPF_OPS_LEN
+ TCA_BPF_OPS
+ TCA_BPF_FD
+ TCA_BPF_NAME
+ TCA_BPF_FLAGS
+ TCA_BPF_MAX = TCA_BPF_FLAGS
+)
+
+type TcBpf TcGen
+
+const (
+ TCA_ACT_MIRRED = 8
+)
+
+const (
+ TCA_MIRRED_UNSPEC = iota
+ TCA_MIRRED_TM
+ TCA_MIRRED_PARMS
+ TCA_MIRRED_MAX = TCA_MIRRED_PARMS
+)
+
+// struct tc_mirred {
+// tc_gen;
+// int eaction; /* one of IN/EGRESS_MIRROR/REDIR */
+// __u32 ifindex; /* ifindex of egress port */
+// };
+
+type TcMirred struct {
+ TcGen
+ Eaction int32
+ Ifindex uint32
+}
+
+func (msg *TcMirred) Len() int {
+ return SizeofTcMirred
+}
+
+func DeserializeTcMirred(b []byte) *TcMirred {
+ return (*TcMirred)(unsafe.Pointer(&b[0:SizeofTcMirred][0]))
+}
+
+func (x *TcMirred) Serialize() []byte {
+ return (*(*[SizeofTcMirred]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_police {
+// __u32 index;
+// int action;
+// __u32 limit;
+// __u32 burst;
+// __u32 mtu;
+// struct tc_ratespec rate;
+// struct tc_ratespec peakrate;
+// int refcnt;
+// int bindcnt;
+// __u32 capab;
+// };
+
+type TcPolice struct {
+ Index uint32
+ Action int32
+ Limit uint32
+ Burst uint32
+ Mtu uint32
+ Rate TcRateSpec
+ PeakRate TcRateSpec
+ Refcnt int32
+ Bindcnt int32
+ Capab uint32
+}
+
+func (msg *TcPolice) Len() int {
+ return SizeofTcPolice
+}
+
+func DeserializeTcPolice(b []byte) *TcPolice {
+ return (*TcPolice)(unsafe.Pointer(&b[0:SizeofTcPolice][0]))
+}
+
+func (x *TcPolice) Serialize() []byte {
+ return (*(*[SizeofTcPolice]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TCA_FW_UNSPEC = iota
+ TCA_FW_CLASSID
+ TCA_FW_POLICE
+ TCA_FW_INDEV
+ TCA_FW_ACT
+ TCA_FW_MASK
+ TCA_FW_MAX = TCA_FW_MASK
+)
diff --git a/vendor/github.com/vishvananda/netlink/nl/xfrm_linux.go b/vendor/github.com/vishvananda/netlink/nl/xfrm_linux.go
new file mode 100644
index 0000000..09a2ffa
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/xfrm_linux.go
@@ -0,0 +1,296 @@
+package nl
+
+import (
+ "bytes"
+ "net"
+ "unsafe"
+)
+
+// Infinity for packet and byte counts
+const (
+ XFRM_INF = ^uint64(0)
+)
+
+type XfrmMsgType uint8
+
+type XfrmMsg interface {
+ Type() XfrmMsgType
+}
+
+// Message Types
+const (
+ XFRM_MSG_BASE XfrmMsgType = 0x10
+ XFRM_MSG_NEWSA = 0x10
+ XFRM_MSG_DELSA = 0x11
+ XFRM_MSG_GETSA = 0x12
+ XFRM_MSG_NEWPOLICY = 0x13
+ XFRM_MSG_DELPOLICY = 0x14
+ XFRM_MSG_GETPOLICY = 0x15
+ XFRM_MSG_ALLOCSPI = 0x16
+ XFRM_MSG_ACQUIRE = 0x17
+ XFRM_MSG_EXPIRE = 0x18
+ XFRM_MSG_UPDPOLICY = 0x19
+ XFRM_MSG_UPDSA = 0x1a
+ XFRM_MSG_POLEXPIRE = 0x1b
+ XFRM_MSG_FLUSHSA = 0x1c
+ XFRM_MSG_FLUSHPOLICY = 0x1d
+ XFRM_MSG_NEWAE = 0x1e
+ XFRM_MSG_GETAE = 0x1f
+ XFRM_MSG_REPORT = 0x20
+ XFRM_MSG_MIGRATE = 0x21
+ XFRM_MSG_NEWSADINFO = 0x22
+ XFRM_MSG_GETSADINFO = 0x23
+ XFRM_MSG_NEWSPDINFO = 0x24
+ XFRM_MSG_GETSPDINFO = 0x25
+ XFRM_MSG_MAPPING = 0x26
+ XFRM_MSG_MAX = 0x26
+ XFRM_NR_MSGTYPES = 0x17
+)
+
+// Attribute types
+const (
+ /* Netlink message attributes. */
+ XFRMA_UNSPEC = 0x00
+ XFRMA_ALG_AUTH = 0x01 /* struct xfrm_algo */
+ XFRMA_ALG_CRYPT = 0x02 /* struct xfrm_algo */
+ XFRMA_ALG_COMP = 0x03 /* struct xfrm_algo */
+ XFRMA_ENCAP = 0x04 /* struct xfrm_algo + struct xfrm_encap_tmpl */
+ XFRMA_TMPL = 0x05 /* 1 or more struct xfrm_user_tmpl */
+ XFRMA_SA = 0x06 /* struct xfrm_usersa_info */
+ XFRMA_POLICY = 0x07 /* struct xfrm_userpolicy_info */
+ XFRMA_SEC_CTX = 0x08 /* struct xfrm_sec_ctx */
+ XFRMA_LTIME_VAL = 0x09
+ XFRMA_REPLAY_VAL = 0x0a
+ XFRMA_REPLAY_THRESH = 0x0b
+ XFRMA_ETIMER_THRESH = 0x0c
+ XFRMA_SRCADDR = 0x0d /* xfrm_address_t */
+ XFRMA_COADDR = 0x0e /* xfrm_address_t */
+ XFRMA_LASTUSED = 0x0f /* unsigned long */
+ XFRMA_POLICY_TYPE = 0x10 /* struct xfrm_userpolicy_type */
+ XFRMA_MIGRATE = 0x11
+ XFRMA_ALG_AEAD = 0x12 /* struct xfrm_algo_aead */
+ XFRMA_KMADDRESS = 0x13 /* struct xfrm_user_kmaddress */
+ XFRMA_ALG_AUTH_TRUNC = 0x14 /* struct xfrm_algo_auth */
+ XFRMA_MARK = 0x15 /* struct xfrm_mark */
+ XFRMA_TFCPAD = 0x16 /* __u32 */
+ XFRMA_REPLAY_ESN_VAL = 0x17 /* struct xfrm_replay_esn */
+ XFRMA_SA_EXTRA_FLAGS = 0x18 /* __u32 */
+ XFRMA_MAX = 0x18
+)
+
+const (
+ SizeofXfrmAddress = 0x10
+ SizeofXfrmSelector = 0x38
+ SizeofXfrmLifetimeCfg = 0x40
+ SizeofXfrmLifetimeCur = 0x20
+ SizeofXfrmId = 0x18
+ SizeofXfrmMark = 0x08
+)
+
+// Netlink groups
+const (
+ XFRMNLGRP_NONE = 0x0
+ XFRMNLGRP_ACQUIRE = 0x1
+ XFRMNLGRP_EXPIRE = 0x2
+ XFRMNLGRP_SA = 0x3
+ XFRMNLGRP_POLICY = 0x4
+ XFRMNLGRP_AEVENTS = 0x5
+ XFRMNLGRP_REPORT = 0x6
+ XFRMNLGRP_MIGRATE = 0x7
+ XFRMNLGRP_MAPPING = 0x8
+ __XFRMNLGRP_MAX = 0x9
+)
+
+// typedef union {
+// __be32 a4;
+// __be32 a6[4];
+// } xfrm_address_t;
+
+type XfrmAddress [SizeofXfrmAddress]byte
+
+func (x *XfrmAddress) ToIP() net.IP {
+ var empty = [12]byte{}
+ ip := make(net.IP, net.IPv6len)
+ if bytes.Equal(x[4:16], empty[:]) {
+ ip[10] = 0xff
+ ip[11] = 0xff
+ copy(ip[12:16], x[0:4])
+ } else {
+ copy(ip[:], x[:])
+ }
+ return ip
+}
+
+func (x *XfrmAddress) ToIPNet(prefixlen uint8) *net.IPNet {
+ ip := x.ToIP()
+ if GetIPFamily(ip) == FAMILY_V4 {
+ return &net.IPNet{IP: ip, Mask: net.CIDRMask(int(prefixlen), 32)}
+ }
+ return &net.IPNet{IP: ip, Mask: net.CIDRMask(int(prefixlen), 128)}
+}
+
+func (x *XfrmAddress) FromIP(ip net.IP) {
+ var empty = [16]byte{}
+ if len(ip) < net.IPv4len {
+ copy(x[4:16], empty[:])
+ } else if GetIPFamily(ip) == FAMILY_V4 {
+ copy(x[0:4], ip.To4()[0:4])
+ copy(x[4:16], empty[:12])
+ } else {
+ copy(x[0:16], ip.To16()[0:16])
+ }
+}
+
+func DeserializeXfrmAddress(b []byte) *XfrmAddress {
+ return (*XfrmAddress)(unsafe.Pointer(&b[0:SizeofXfrmAddress][0]))
+}
+
+func (x *XfrmAddress) Serialize() []byte {
+ return (*(*[SizeofXfrmAddress]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct xfrm_selector {
+// xfrm_address_t daddr;
+// xfrm_address_t saddr;
+// __be16 dport;
+// __be16 dport_mask;
+// __be16 sport;
+// __be16 sport_mask;
+// __u16 family;
+// __u8 prefixlen_d;
+// __u8 prefixlen_s;
+// __u8 proto;
+// int ifindex;
+// __kernel_uid32_t user;
+// };
+
+type XfrmSelector struct {
+ Daddr XfrmAddress
+ Saddr XfrmAddress
+ Dport uint16 // big endian
+ DportMask uint16 // big endian
+ Sport uint16 // big endian
+ SportMask uint16 // big endian
+ Family uint16
+ PrefixlenD uint8
+ PrefixlenS uint8
+ Proto uint8
+ Pad [3]byte
+ Ifindex int32
+ User uint32
+}
+
+func (msg *XfrmSelector) Len() int {
+ return SizeofXfrmSelector
+}
+
+func DeserializeXfrmSelector(b []byte) *XfrmSelector {
+ return (*XfrmSelector)(unsafe.Pointer(&b[0:SizeofXfrmSelector][0]))
+}
+
+func (msg *XfrmSelector) Serialize() []byte {
+ return (*(*[SizeofXfrmSelector]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_lifetime_cfg {
+// __u64 soft_byte_limit;
+// __u64 hard_byte_limit;
+// __u64 soft_packet_limit;
+// __u64 hard_packet_limit;
+// __u64 soft_add_expires_seconds;
+// __u64 hard_add_expires_seconds;
+// __u64 soft_use_expires_seconds;
+// __u64 hard_use_expires_seconds;
+// };
+//
+
+type XfrmLifetimeCfg struct {
+ SoftByteLimit uint64
+ HardByteLimit uint64
+ SoftPacketLimit uint64
+ HardPacketLimit uint64
+ SoftAddExpiresSeconds uint64
+ HardAddExpiresSeconds uint64
+ SoftUseExpiresSeconds uint64
+ HardUseExpiresSeconds uint64
+}
+
+func (msg *XfrmLifetimeCfg) Len() int {
+ return SizeofXfrmLifetimeCfg
+}
+
+func DeserializeXfrmLifetimeCfg(b []byte) *XfrmLifetimeCfg {
+ return (*XfrmLifetimeCfg)(unsafe.Pointer(&b[0:SizeofXfrmLifetimeCfg][0]))
+}
+
+func (msg *XfrmLifetimeCfg) Serialize() []byte {
+ return (*(*[SizeofXfrmLifetimeCfg]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_lifetime_cur {
+// __u64 bytes;
+// __u64 packets;
+// __u64 add_time;
+// __u64 use_time;
+// };
+
+type XfrmLifetimeCur struct {
+ Bytes uint64
+ Packets uint64
+ AddTime uint64
+ UseTime uint64
+}
+
+func (msg *XfrmLifetimeCur) Len() int {
+ return SizeofXfrmLifetimeCur
+}
+
+func DeserializeXfrmLifetimeCur(b []byte) *XfrmLifetimeCur {
+ return (*XfrmLifetimeCur)(unsafe.Pointer(&b[0:SizeofXfrmLifetimeCur][0]))
+}
+
+func (msg *XfrmLifetimeCur) Serialize() []byte {
+ return (*(*[SizeofXfrmLifetimeCur]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_id {
+// xfrm_address_t daddr;
+// __be32 spi;
+// __u8 proto;
+// };
+
+type XfrmId struct {
+ Daddr XfrmAddress
+ Spi uint32 // big endian
+ Proto uint8
+ Pad [3]byte
+}
+
+func (msg *XfrmId) Len() int {
+ return SizeofXfrmId
+}
+
+func DeserializeXfrmId(b []byte) *XfrmId {
+ return (*XfrmId)(unsafe.Pointer(&b[0:SizeofXfrmId][0]))
+}
+
+func (msg *XfrmId) Serialize() []byte {
+ return (*(*[SizeofXfrmId]byte)(unsafe.Pointer(msg)))[:]
+}
+
+type XfrmMark struct {
+ Value uint32
+ Mask uint32
+}
+
+func (msg *XfrmMark) Len() int {
+ return SizeofXfrmMark
+}
+
+func DeserializeXfrmMark(b []byte) *XfrmMark {
+ return (*XfrmMark)(unsafe.Pointer(&b[0:SizeofXfrmMark][0]))
+}
+
+func (msg *XfrmMark) Serialize() []byte {
+ return (*(*[SizeofXfrmMark]byte)(unsafe.Pointer(msg)))[:]
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/xfrm_monitor_linux.go b/vendor/github.com/vishvananda/netlink/nl/xfrm_monitor_linux.go
new file mode 100644
index 0000000..715df4c
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/xfrm_monitor_linux.go
@@ -0,0 +1,32 @@
+package nl
+
+import (
+ "unsafe"
+)
+
+const (
+ SizeofXfrmUserExpire = 0xe8
+)
+
+// struct xfrm_user_expire {
+// struct xfrm_usersa_info state;
+// __u8 hard;
+// };
+
+type XfrmUserExpire struct {
+ XfrmUsersaInfo XfrmUsersaInfo
+ Hard uint8
+ Pad [7]byte
+}
+
+func (msg *XfrmUserExpire) Len() int {
+ return SizeofXfrmUserExpire
+}
+
+func DeserializeXfrmUserExpire(b []byte) *XfrmUserExpire {
+ return (*XfrmUserExpire)(unsafe.Pointer(&b[0:SizeofXfrmUserExpire][0]))
+}
+
+func (msg *XfrmUserExpire) Serialize() []byte {
+ return (*(*[SizeofXfrmUserExpire]byte)(unsafe.Pointer(msg)))[:]
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go b/vendor/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go
new file mode 100644
index 0000000..66f7e03
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go
@@ -0,0 +1,119 @@
+package nl
+
+import (
+ "unsafe"
+)
+
+const (
+ SizeofXfrmUserpolicyId = 0x40
+ SizeofXfrmUserpolicyInfo = 0xa8
+ SizeofXfrmUserTmpl = 0x40
+)
+
+// struct xfrm_userpolicy_id {
+// struct xfrm_selector sel;
+// __u32 index;
+// __u8 dir;
+// };
+//
+
+type XfrmUserpolicyId struct {
+ Sel XfrmSelector
+ Index uint32
+ Dir uint8
+ Pad [3]byte
+}
+
+func (msg *XfrmUserpolicyId) Len() int {
+ return SizeofXfrmUserpolicyId
+}
+
+func DeserializeXfrmUserpolicyId(b []byte) *XfrmUserpolicyId {
+ return (*XfrmUserpolicyId)(unsafe.Pointer(&b[0:SizeofXfrmUserpolicyId][0]))
+}
+
+func (msg *XfrmUserpolicyId) Serialize() []byte {
+ return (*(*[SizeofXfrmUserpolicyId]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_userpolicy_info {
+// struct xfrm_selector sel;
+// struct xfrm_lifetime_cfg lft;
+// struct xfrm_lifetime_cur curlft;
+// __u32 priority;
+// __u32 index;
+// __u8 dir;
+// __u8 action;
+// #define XFRM_POLICY_ALLOW 0
+// #define XFRM_POLICY_BLOCK 1
+// __u8 flags;
+// #define XFRM_POLICY_LOCALOK 1 /* Allow user to override global policy */
+// /* Automatically expand selector to include matching ICMP payloads. */
+// #define XFRM_POLICY_ICMP 2
+// __u8 share;
+// };
+
+type XfrmUserpolicyInfo struct {
+ Sel XfrmSelector
+ Lft XfrmLifetimeCfg
+ Curlft XfrmLifetimeCur
+ Priority uint32
+ Index uint32
+ Dir uint8
+ Action uint8
+ Flags uint8
+ Share uint8
+ Pad [4]byte
+}
+
+func (msg *XfrmUserpolicyInfo) Len() int {
+ return SizeofXfrmUserpolicyInfo
+}
+
+func DeserializeXfrmUserpolicyInfo(b []byte) *XfrmUserpolicyInfo {
+ return (*XfrmUserpolicyInfo)(unsafe.Pointer(&b[0:SizeofXfrmUserpolicyInfo][0]))
+}
+
+func (msg *XfrmUserpolicyInfo) Serialize() []byte {
+ return (*(*[SizeofXfrmUserpolicyInfo]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_user_tmpl {
+// struct xfrm_id id;
+// __u16 family;
+// xfrm_address_t saddr;
+// __u32 reqid;
+// __u8 mode;
+// __u8 share;
+// __u8 optional;
+// __u32 aalgos;
+// __u32 ealgos;
+// __u32 calgos;
+// }
+
+type XfrmUserTmpl struct {
+ XfrmId XfrmId
+ Family uint16
+ Pad1 [2]byte
+ Saddr XfrmAddress
+ Reqid uint32
+ Mode uint8
+ Share uint8
+ Optional uint8
+ Pad2 byte
+ Aalgos uint32
+ Ealgos uint32
+ Calgos uint32
+}
+
+func (msg *XfrmUserTmpl) Len() int {
+ return SizeofXfrmUserTmpl
+}
+
+func DeserializeXfrmUserTmpl(b []byte) *XfrmUserTmpl {
+ return (*XfrmUserTmpl)(unsafe.Pointer(&b[0:SizeofXfrmUserTmpl][0]))
+}
+
+func (msg *XfrmUserTmpl) Serialize() []byte {
+ return (*(*[SizeofXfrmUserTmpl]byte)(unsafe.Pointer(msg)))[:]
+}
diff --git a/vendor/github.com/vishvananda/netlink/nl/xfrm_state_linux.go b/vendor/github.com/vishvananda/netlink/nl/xfrm_state_linux.go
new file mode 100644
index 0000000..b6290fd
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/nl/xfrm_state_linux.go
@@ -0,0 +1,334 @@
+package nl
+
+import (
+ "unsafe"
+)
+
+const (
+ SizeofXfrmUsersaId = 0x18
+ SizeofXfrmStats = 0x0c
+ SizeofXfrmUsersaInfo = 0xe0
+ SizeofXfrmUserSpiInfo = 0xe8
+ SizeofXfrmAlgo = 0x44
+ SizeofXfrmAlgoAuth = 0x48
+ SizeofXfrmAlgoAEAD = 0x48
+ SizeofXfrmEncapTmpl = 0x18
+ SizeofXfrmUsersaFlush = 0x8
+ SizeofXfrmReplayStateEsn = 0x18
+)
+
+const (
+ XFRM_STATE_NOECN = 1
+ XFRM_STATE_DECAP_DSCP = 2
+ XFRM_STATE_NOPMTUDISC = 4
+ XFRM_STATE_WILDRECV = 8
+ XFRM_STATE_ICMP = 16
+ XFRM_STATE_AF_UNSPEC = 32
+ XFRM_STATE_ALIGN4 = 64
+ XFRM_STATE_ESN = 128
+)
+
+// struct xfrm_usersa_id {
+// xfrm_address_t daddr;
+// __be32 spi;
+// __u16 family;
+// __u8 proto;
+// };
+
+type XfrmUsersaId struct {
+ Daddr XfrmAddress
+ Spi uint32 // big endian
+ Family uint16
+ Proto uint8
+ Pad byte
+}
+
+func (msg *XfrmUsersaId) Len() int {
+ return SizeofXfrmUsersaId
+}
+
+func DeserializeXfrmUsersaId(b []byte) *XfrmUsersaId {
+ return (*XfrmUsersaId)(unsafe.Pointer(&b[0:SizeofXfrmUsersaId][0]))
+}
+
+func (msg *XfrmUsersaId) Serialize() []byte {
+ return (*(*[SizeofXfrmUsersaId]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_stats {
+// __u32 replay_window;
+// __u32 replay;
+// __u32 integrity_failed;
+// };
+
+type XfrmStats struct {
+ ReplayWindow uint32
+ Replay uint32
+ IntegrityFailed uint32
+}
+
+func (msg *XfrmStats) Len() int {
+ return SizeofXfrmStats
+}
+
+func DeserializeXfrmStats(b []byte) *XfrmStats {
+ return (*XfrmStats)(unsafe.Pointer(&b[0:SizeofXfrmStats][0]))
+}
+
+func (msg *XfrmStats) Serialize() []byte {
+ return (*(*[SizeofXfrmStats]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_usersa_info {
+// struct xfrm_selector sel;
+// struct xfrm_id id;
+// xfrm_address_t saddr;
+// struct xfrm_lifetime_cfg lft;
+// struct xfrm_lifetime_cur curlft;
+// struct xfrm_stats stats;
+// __u32 seq;
+// __u32 reqid;
+// __u16 family;
+// __u8 mode; /* XFRM_MODE_xxx */
+// __u8 replay_window;
+// __u8 flags;
+// #define XFRM_STATE_NOECN 1
+// #define XFRM_STATE_DECAP_DSCP 2
+// #define XFRM_STATE_NOPMTUDISC 4
+// #define XFRM_STATE_WILDRECV 8
+// #define XFRM_STATE_ICMP 16
+// #define XFRM_STATE_AF_UNSPEC 32
+// #define XFRM_STATE_ALIGN4 64
+// #define XFRM_STATE_ESN 128
+// };
+//
+// #define XFRM_SA_XFLAG_DONT_ENCAP_DSCP 1
+//
+
+type XfrmUsersaInfo struct {
+ Sel XfrmSelector
+ Id XfrmId
+ Saddr XfrmAddress
+ Lft XfrmLifetimeCfg
+ Curlft XfrmLifetimeCur
+ Stats XfrmStats
+ Seq uint32
+ Reqid uint32
+ Family uint16
+ Mode uint8
+ ReplayWindow uint8
+ Flags uint8
+ Pad [7]byte
+}
+
+func (msg *XfrmUsersaInfo) Len() int {
+ return SizeofXfrmUsersaInfo
+}
+
+func DeserializeXfrmUsersaInfo(b []byte) *XfrmUsersaInfo {
+ return (*XfrmUsersaInfo)(unsafe.Pointer(&b[0:SizeofXfrmUsersaInfo][0]))
+}
+
+func (msg *XfrmUsersaInfo) Serialize() []byte {
+ return (*(*[SizeofXfrmUsersaInfo]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_userspi_info {
+// struct xfrm_usersa_info info;
+// __u32 min;
+// __u32 max;
+// };
+
+type XfrmUserSpiInfo struct {
+ XfrmUsersaInfo XfrmUsersaInfo
+ Min uint32
+ Max uint32
+}
+
+func (msg *XfrmUserSpiInfo) Len() int {
+ return SizeofXfrmUserSpiInfo
+}
+
+func DeserializeXfrmUserSpiInfo(b []byte) *XfrmUserSpiInfo {
+ return (*XfrmUserSpiInfo)(unsafe.Pointer(&b[0:SizeofXfrmUserSpiInfo][0]))
+}
+
+func (msg *XfrmUserSpiInfo) Serialize() []byte {
+ return (*(*[SizeofXfrmUserSpiInfo]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_algo {
+// char alg_name[64];
+// unsigned int alg_key_len; /* in bits */
+// char alg_key[0];
+// };
+
+type XfrmAlgo struct {
+ AlgName [64]byte
+ AlgKeyLen uint32
+ AlgKey []byte
+}
+
+func (msg *XfrmAlgo) Len() int {
+ return SizeofXfrmAlgo + int(msg.AlgKeyLen/8)
+}
+
+func DeserializeXfrmAlgo(b []byte) *XfrmAlgo {
+ ret := XfrmAlgo{}
+ copy(ret.AlgName[:], b[0:64])
+ ret.AlgKeyLen = *(*uint32)(unsafe.Pointer(&b[64]))
+ ret.AlgKey = b[68:ret.Len()]
+ return &ret
+}
+
+func (msg *XfrmAlgo) Serialize() []byte {
+ b := make([]byte, msg.Len())
+ copy(b[0:64], msg.AlgName[:])
+ copy(b[64:68], (*(*[4]byte)(unsafe.Pointer(&msg.AlgKeyLen)))[:])
+ copy(b[68:msg.Len()], msg.AlgKey[:])
+ return b
+}
+
+// struct xfrm_algo_auth {
+// char alg_name[64];
+// unsigned int alg_key_len; /* in bits */
+// unsigned int alg_trunc_len; /* in bits */
+// char alg_key[0];
+// };
+
+type XfrmAlgoAuth struct {
+ AlgName [64]byte
+ AlgKeyLen uint32
+ AlgTruncLen uint32
+ AlgKey []byte
+}
+
+func (msg *XfrmAlgoAuth) Len() int {
+ return SizeofXfrmAlgoAuth + int(msg.AlgKeyLen/8)
+}
+
+func DeserializeXfrmAlgoAuth(b []byte) *XfrmAlgoAuth {
+ ret := XfrmAlgoAuth{}
+ copy(ret.AlgName[:], b[0:64])
+ ret.AlgKeyLen = *(*uint32)(unsafe.Pointer(&b[64]))
+ ret.AlgTruncLen = *(*uint32)(unsafe.Pointer(&b[68]))
+ ret.AlgKey = b[72:ret.Len()]
+ return &ret
+}
+
+func (msg *XfrmAlgoAuth) Serialize() []byte {
+ b := make([]byte, msg.Len())
+ copy(b[0:64], msg.AlgName[:])
+ copy(b[64:68], (*(*[4]byte)(unsafe.Pointer(&msg.AlgKeyLen)))[:])
+ copy(b[68:72], (*(*[4]byte)(unsafe.Pointer(&msg.AlgTruncLen)))[:])
+ copy(b[72:msg.Len()], msg.AlgKey[:])
+ return b
+}
+
+// struct xfrm_algo_aead {
+// char alg_name[64];
+// unsigned int alg_key_len; /* in bits */
+// unsigned int alg_icv_len; /* in bits */
+// char alg_key[0];
+// }
+
+type XfrmAlgoAEAD struct {
+ AlgName [64]byte
+ AlgKeyLen uint32
+ AlgICVLen uint32
+ AlgKey []byte
+}
+
+func (msg *XfrmAlgoAEAD) Len() int {
+ return SizeofXfrmAlgoAEAD + int(msg.AlgKeyLen/8)
+}
+
+func DeserializeXfrmAlgoAEAD(b []byte) *XfrmAlgoAEAD {
+ ret := XfrmAlgoAEAD{}
+ copy(ret.AlgName[:], b[0:64])
+ ret.AlgKeyLen = *(*uint32)(unsafe.Pointer(&b[64]))
+ ret.AlgICVLen = *(*uint32)(unsafe.Pointer(&b[68]))
+ ret.AlgKey = b[72:ret.Len()]
+ return &ret
+}
+
+func (msg *XfrmAlgoAEAD) Serialize() []byte {
+ b := make([]byte, msg.Len())
+ copy(b[0:64], msg.AlgName[:])
+ copy(b[64:68], (*(*[4]byte)(unsafe.Pointer(&msg.AlgKeyLen)))[:])
+ copy(b[68:72], (*(*[4]byte)(unsafe.Pointer(&msg.AlgICVLen)))[:])
+ copy(b[72:msg.Len()], msg.AlgKey[:])
+ return b
+}
+
+// struct xfrm_encap_tmpl {
+// __u16 encap_type;
+// __be16 encap_sport;
+// __be16 encap_dport;
+// xfrm_address_t encap_oa;
+// };
+
+type XfrmEncapTmpl struct {
+ EncapType uint16
+ EncapSport uint16 // big endian
+ EncapDport uint16 // big endian
+ Pad [2]byte
+ EncapOa XfrmAddress
+}
+
+func (msg *XfrmEncapTmpl) Len() int {
+ return SizeofXfrmEncapTmpl
+}
+
+func DeserializeXfrmEncapTmpl(b []byte) *XfrmEncapTmpl {
+ return (*XfrmEncapTmpl)(unsafe.Pointer(&b[0:SizeofXfrmEncapTmpl][0]))
+}
+
+func (msg *XfrmEncapTmpl) Serialize() []byte {
+ return (*(*[SizeofXfrmEncapTmpl]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_usersa_flush {
+// __u8 proto;
+// };
+
+type XfrmUsersaFlush struct {
+ Proto uint8
+}
+
+func (msg *XfrmUsersaFlush) Len() int {
+ return SizeofXfrmUsersaFlush
+}
+
+func DeserializeXfrmUsersaFlush(b []byte) *XfrmUsersaFlush {
+ return (*XfrmUsersaFlush)(unsafe.Pointer(&b[0:SizeofXfrmUsersaFlush][0]))
+}
+
+func (msg *XfrmUsersaFlush) Serialize() []byte {
+ return (*(*[SizeofXfrmUsersaFlush]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct xfrm_replay_state_esn {
+// unsigned int bmp_len;
+// __u32 oseq;
+// __u32 seq;
+// __u32 oseq_hi;
+// __u32 seq_hi;
+// __u32 replay_window;
+// __u32 bmp[0];
+// };
+
+type XfrmReplayStateEsn struct {
+ BmpLen uint32
+ OSeq uint32
+ Seq uint32
+ OSeqHi uint32
+ SeqHi uint32
+ ReplayWindow uint32
+ Bmp []uint32
+}
+
+func (msg *XfrmReplayStateEsn) Serialize() []byte {
+ // We deliberately do not pass Bmp, as it gets set by the kernel.
+ return (*(*[SizeofXfrmReplayStateEsn]byte)(unsafe.Pointer(msg)))[:]
+}
diff --git a/vendor/github.com/vishvananda/netlink/order.go b/vendor/github.com/vishvananda/netlink/order.go
new file mode 100644
index 0000000..e28e153
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/order.go
@@ -0,0 +1,32 @@
+package netlink
+
+import (
+ "encoding/binary"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+var (
+ native = nl.NativeEndian()
+ networkOrder = binary.BigEndian
+)
+
+func htonl(val uint32) []byte {
+ bytes := make([]byte, 4)
+ binary.BigEndian.PutUint32(bytes, val)
+ return bytes
+}
+
+func htons(val uint16) []byte {
+ bytes := make([]byte, 2)
+ binary.BigEndian.PutUint16(bytes, val)
+ return bytes
+}
+
+func ntohl(buf []byte) uint32 {
+ return binary.BigEndian.Uint32(buf)
+}
+
+func ntohs(buf []byte) uint16 {
+ return binary.BigEndian.Uint16(buf)
+}
diff --git a/vendor/github.com/vishvananda/netlink/protinfo.go b/vendor/github.com/vishvananda/netlink/protinfo.go
new file mode 100644
index 0000000..0087c44
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/protinfo.go
@@ -0,0 +1,58 @@
+package netlink
+
+import (
+ "strings"
+)
+
+// Protinfo represents bridge flags from netlink.
+type Protinfo struct {
+ Hairpin bool
+ Guard bool
+ FastLeave bool
+ RootBlock bool
+ Learning bool
+ Flood bool
+ ProxyArp bool
+ ProxyArpWiFi bool
+}
+
+// String returns a list of enabled flags
+func (prot *Protinfo) String() string {
+ var boolStrings []string
+ if prot.Hairpin {
+ boolStrings = append(boolStrings, "Hairpin")
+ }
+ if prot.Guard {
+ boolStrings = append(boolStrings, "Guard")
+ }
+ if prot.FastLeave {
+ boolStrings = append(boolStrings, "FastLeave")
+ }
+ if prot.RootBlock {
+ boolStrings = append(boolStrings, "RootBlock")
+ }
+ if prot.Learning {
+ boolStrings = append(boolStrings, "Learning")
+ }
+ if prot.Flood {
+ boolStrings = append(boolStrings, "Flood")
+ }
+ if prot.ProxyArp {
+ boolStrings = append(boolStrings, "ProxyArp")
+ }
+ if prot.ProxyArpWiFi {
+ boolStrings = append(boolStrings, "ProxyArpWiFi")
+ }
+ return strings.Join(boolStrings, " ")
+}
+
+func boolToByte(x bool) []byte {
+ if x {
+ return []byte{1}
+ }
+ return []byte{0}
+}
+
+func byteToBool(x byte) bool {
+ return uint8(x) != 0
+}
diff --git a/vendor/github.com/vishvananda/netlink/protinfo_linux.go b/vendor/github.com/vishvananda/netlink/protinfo_linux.go
new file mode 100644
index 0000000..10dd0d5
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/protinfo_linux.go
@@ -0,0 +1,74 @@
+package netlink
+
+import (
+ "fmt"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+func LinkGetProtinfo(link Link) (Protinfo, error) {
+ return pkgHandle.LinkGetProtinfo(link)
+}
+
+func (h *Handle) LinkGetProtinfo(link Link) (Protinfo, error) {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ var pi Protinfo
+ req := h.newNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_DUMP)
+ msg := nl.NewIfInfomsg(syscall.AF_BRIDGE)
+ req.AddData(msg)
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ if err != nil {
+ return pi, err
+ }
+
+ for _, m := range msgs {
+ ans := nl.DeserializeIfInfomsg(m)
+ if int(ans.Index) != base.Index {
+ continue
+ }
+ attrs, err := nl.ParseRouteAttr(m[ans.Len():])
+ if err != nil {
+ return pi, err
+ }
+ for _, attr := range attrs {
+ if attr.Attr.Type != syscall.IFLA_PROTINFO|syscall.NLA_F_NESTED {
+ continue
+ }
+ infos, err := nl.ParseRouteAttr(attr.Value)
+ if err != nil {
+ return pi, err
+ }
+ pi = *parseProtinfo(infos)
+
+ return pi, nil
+ }
+ }
+ return pi, fmt.Errorf("Device with index %d not found", base.Index)
+}
+
+func parseProtinfo(infos []syscall.NetlinkRouteAttr) *Protinfo {
+ var pi Protinfo
+ for _, info := range infos {
+ switch info.Attr.Type {
+ case nl.IFLA_BRPORT_MODE:
+ pi.Hairpin = byteToBool(info.Value[0])
+ case nl.IFLA_BRPORT_GUARD:
+ pi.Guard = byteToBool(info.Value[0])
+ case nl.IFLA_BRPORT_FAST_LEAVE:
+ pi.FastLeave = byteToBool(info.Value[0])
+ case nl.IFLA_BRPORT_PROTECT:
+ pi.RootBlock = byteToBool(info.Value[0])
+ case nl.IFLA_BRPORT_LEARNING:
+ pi.Learning = byteToBool(info.Value[0])
+ case nl.IFLA_BRPORT_UNICAST_FLOOD:
+ pi.Flood = byteToBool(info.Value[0])
+ case nl.IFLA_BRPORT_PROXYARP:
+ pi.ProxyArp = byteToBool(info.Value[0])
+ case nl.IFLA_BRPORT_PROXYARP_WIFI:
+ pi.ProxyArpWiFi = byteToBool(info.Value[0])
+ }
+ }
+ return &pi
+}
diff --git a/vendor/github.com/vishvananda/netlink/qdisc.go b/vendor/github.com/vishvananda/netlink/qdisc.go
new file mode 100644
index 0000000..0ca86eb
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/qdisc.go
@@ -0,0 +1,232 @@
+package netlink
+
+import (
+ "fmt"
+ "math"
+)
+
+const (
+ HANDLE_NONE = 0
+ HANDLE_INGRESS = 0xFFFFFFF1
+ HANDLE_CLSACT = HANDLE_INGRESS
+ HANDLE_ROOT = 0xFFFFFFFF
+ PRIORITY_MAP_LEN = 16
+)
+const (
+ HANDLE_MIN_INGRESS = 0xFFFFFFF2
+ HANDLE_MIN_EGRESS = 0xFFFFFFF3
+)
+
+type Qdisc interface {
+ Attrs() *QdiscAttrs
+ Type() string
+}
+
+// QdiscAttrs represents a netlink qdisc. A qdisc is associated with a link,
+// has a handle, a parent and a refcnt. The root qdisc of a device should
+// have parent == HANDLE_ROOT.
+type QdiscAttrs struct {
+ LinkIndex int
+ Handle uint32
+ Parent uint32
+ Refcnt uint32 // read only
+}
+
+func (q QdiscAttrs) String() string {
+ return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Refcnt: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Refcnt)
+}
+
+func MakeHandle(major, minor uint16) uint32 {
+ return (uint32(major) << 16) | uint32(minor)
+}
+
+func MajorMinor(handle uint32) (uint16, uint16) {
+ return uint16((handle & 0xFFFF0000) >> 16), uint16(handle & 0x0000FFFFF)
+}
+
+func HandleStr(handle uint32) string {
+ switch handle {
+ case HANDLE_NONE:
+ return "none"
+ case HANDLE_INGRESS:
+ return "ingress"
+ case HANDLE_ROOT:
+ return "root"
+ default:
+ major, minor := MajorMinor(handle)
+ return fmt.Sprintf("%x:%x", major, minor)
+ }
+}
+
+func Percentage2u32(percentage float32) uint32 {
+ // FIXME this is most likely not the best way to convert from % to uint32
+ if percentage == 100 {
+ return math.MaxUint32
+ }
+ return uint32(math.MaxUint32 * (percentage / 100))
+}
+
+// PfifoFast is the default qdisc created by the kernel if one has not
+// been defined for the interface
+type PfifoFast struct {
+ QdiscAttrs
+ Bands uint8
+ PriorityMap [PRIORITY_MAP_LEN]uint8
+}
+
+func (qdisc *PfifoFast) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *PfifoFast) Type() string {
+ return "pfifo_fast"
+}
+
+// Prio is a basic qdisc that works just like PfifoFast
+type Prio struct {
+ QdiscAttrs
+ Bands uint8
+ PriorityMap [PRIORITY_MAP_LEN]uint8
+}
+
+func NewPrio(attrs QdiscAttrs) *Prio {
+ return &Prio{
+ QdiscAttrs: attrs,
+ Bands: 3,
+ PriorityMap: [PRIORITY_MAP_LEN]uint8{1, 2, 2, 2, 1, 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1},
+ }
+}
+
+func (qdisc *Prio) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *Prio) Type() string {
+ return "prio"
+}
+
+// Htb is a classful qdisc that rate limits based on tokens
+type Htb struct {
+ QdiscAttrs
+ Version uint32
+ Rate2Quantum uint32
+ Defcls uint32
+ Debug uint32
+ DirectPkts uint32
+}
+
+func NewHtb(attrs QdiscAttrs) *Htb {
+ return &Htb{
+ QdiscAttrs: attrs,
+ Version: 3,
+ Defcls: 0,
+ Rate2Quantum: 10,
+ Debug: 0,
+ DirectPkts: 0,
+ }
+}
+
+func (qdisc *Htb) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *Htb) Type() string {
+ return "htb"
+}
+
+// Netem is a classless qdisc that rate limits based on tokens
+
+type NetemQdiscAttrs struct {
+ Latency uint32 // in us
+ DelayCorr float32 // in %
+ Limit uint32
+ Loss float32 // in %
+ LossCorr float32 // in %
+ Gap uint32
+ Duplicate float32 // in %
+ DuplicateCorr float32 // in %
+ Jitter uint32 // in us
+ ReorderProb float32 // in %
+ ReorderCorr float32 // in %
+ CorruptProb float32 // in %
+ CorruptCorr float32 // in %
+}
+
+func (q NetemQdiscAttrs) String() string {
+ return fmt.Sprintf(
+ "{Latency: %d, Limit: %d, Loss: %f, Gap: %d, Duplicate: %f, Jitter: %d}",
+ q.Latency, q.Limit, q.Loss, q.Gap, q.Duplicate, q.Jitter,
+ )
+}
+
+type Netem struct {
+ QdiscAttrs
+ Latency uint32
+ DelayCorr uint32
+ Limit uint32
+ Loss uint32
+ LossCorr uint32
+ Gap uint32
+ Duplicate uint32
+ DuplicateCorr uint32
+ Jitter uint32
+ ReorderProb uint32
+ ReorderCorr uint32
+ CorruptProb uint32
+ CorruptCorr uint32
+}
+
+func (qdisc *Netem) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *Netem) Type() string {
+ return "netem"
+}
+
+// Tbf is a classless qdisc that rate limits based on tokens
+type Tbf struct {
+ QdiscAttrs
+ Rate uint64
+ Limit uint32
+ Buffer uint32
+ Peakrate uint64
+ Minburst uint32
+ // TODO: handle other settings
+}
+
+func (qdisc *Tbf) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *Tbf) Type() string {
+ return "tbf"
+}
+
+// Ingress is a qdisc for adding ingress filters
+type Ingress struct {
+ QdiscAttrs
+}
+
+func (qdisc *Ingress) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *Ingress) Type() string {
+ return "ingress"
+}
+
+// GenericQdisc qdiscs represent types that are not currently understood
+// by this netlink library.
+type GenericQdisc struct {
+ QdiscAttrs
+ QdiscType string
+}
+
+func (qdisc *GenericQdisc) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *GenericQdisc) Type() string {
+ return qdisc.QdiscType
+}
diff --git a/vendor/github.com/vishvananda/netlink/qdisc_linux.go b/vendor/github.com/vishvananda/netlink/qdisc_linux.go
new file mode 100644
index 0000000..2c0dedd
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/qdisc_linux.go
@@ -0,0 +1,527 @@
+package netlink
+
+import (
+ "fmt"
+ "io/ioutil"
+ "strconv"
+ "strings"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// NOTE function is here because it uses other linux functions
+func NewNetem(attrs QdiscAttrs, nattrs NetemQdiscAttrs) *Netem {
+ var limit uint32 = 1000
+ var lossCorr, delayCorr, duplicateCorr uint32
+ var reorderProb, reorderCorr uint32
+ var corruptProb, corruptCorr uint32
+
+ latency := nattrs.Latency
+ loss := Percentage2u32(nattrs.Loss)
+ gap := nattrs.Gap
+ duplicate := Percentage2u32(nattrs.Duplicate)
+ jitter := nattrs.Jitter
+
+ // Correlation
+ if latency > 0 && jitter > 0 {
+ delayCorr = Percentage2u32(nattrs.DelayCorr)
+ }
+ if loss > 0 {
+ lossCorr = Percentage2u32(nattrs.LossCorr)
+ }
+ if duplicate > 0 {
+ duplicateCorr = Percentage2u32(nattrs.DuplicateCorr)
+ }
+ // FIXME should validate values(like loss/duplicate are percentages...)
+ latency = time2Tick(latency)
+
+ if nattrs.Limit != 0 {
+ limit = nattrs.Limit
+ }
+ // Jitter is only value if latency is > 0
+ if latency > 0 {
+ jitter = time2Tick(jitter)
+ }
+
+ reorderProb = Percentage2u32(nattrs.ReorderProb)
+ reorderCorr = Percentage2u32(nattrs.ReorderCorr)
+
+ if reorderProb > 0 {
+ // ERROR if lantency == 0
+ if gap == 0 {
+ gap = 1
+ }
+ }
+
+ corruptProb = Percentage2u32(nattrs.CorruptProb)
+ corruptCorr = Percentage2u32(nattrs.CorruptCorr)
+
+ return &Netem{
+ QdiscAttrs: attrs,
+ Latency: latency,
+ DelayCorr: delayCorr,
+ Limit: limit,
+ Loss: loss,
+ LossCorr: lossCorr,
+ Gap: gap,
+ Duplicate: duplicate,
+ DuplicateCorr: duplicateCorr,
+ Jitter: jitter,
+ ReorderProb: reorderProb,
+ ReorderCorr: reorderCorr,
+ CorruptProb: corruptProb,
+ CorruptCorr: corruptCorr,
+ }
+}
+
+// QdiscDel will delete a qdisc from the system.
+// Equivalent to: `tc qdisc del $qdisc`
+func QdiscDel(qdisc Qdisc) error {
+ return pkgHandle.QdiscDel(qdisc)
+}
+
+// QdiscDel will delete a qdisc from the system.
+// Equivalent to: `tc qdisc del $qdisc`
+func (h *Handle) QdiscDel(qdisc Qdisc) error {
+ return h.qdiscModify(syscall.RTM_DELQDISC, 0, qdisc)
+}
+
+// QdiscChange will change a qdisc in place
+// Equivalent to: `tc qdisc change $qdisc`
+// The parent and handle MUST NOT be changed.
+func QdiscChange(qdisc Qdisc) error {
+ return pkgHandle.QdiscChange(qdisc)
+}
+
+// QdiscChange will change a qdisc in place
+// Equivalent to: `tc qdisc change $qdisc`
+// The parent and handle MUST NOT be changed.
+func (h *Handle) QdiscChange(qdisc Qdisc) error {
+ return h.qdiscModify(syscall.RTM_NEWQDISC, 0, qdisc)
+}
+
+// QdiscReplace will replace a qdisc to the system.
+// Equivalent to: `tc qdisc replace $qdisc`
+// The handle MUST change.
+func QdiscReplace(qdisc Qdisc) error {
+ return pkgHandle.QdiscReplace(qdisc)
+}
+
+// QdiscReplace will replace a qdisc to the system.
+// Equivalent to: `tc qdisc replace $qdisc`
+// The handle MUST change.
+func (h *Handle) QdiscReplace(qdisc Qdisc) error {
+ return h.qdiscModify(
+ syscall.RTM_NEWQDISC,
+ syscall.NLM_F_CREATE|syscall.NLM_F_REPLACE,
+ qdisc)
+}
+
+// QdiscAdd will add a qdisc to the system.
+// Equivalent to: `tc qdisc add $qdisc`
+func QdiscAdd(qdisc Qdisc) error {
+ return pkgHandle.QdiscAdd(qdisc)
+}
+
+// QdiscAdd will add a qdisc to the system.
+// Equivalent to: `tc qdisc add $qdisc`
+func (h *Handle) QdiscAdd(qdisc Qdisc) error {
+ return h.qdiscModify(
+ syscall.RTM_NEWQDISC,
+ syscall.NLM_F_CREATE|syscall.NLM_F_EXCL,
+ qdisc)
+}
+
+func (h *Handle) qdiscModify(cmd, flags int, qdisc Qdisc) error {
+ req := h.newNetlinkRequest(cmd, flags|syscall.NLM_F_ACK)
+ base := qdisc.Attrs()
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Ifindex: int32(base.LinkIndex),
+ Handle: base.Handle,
+ Parent: base.Parent,
+ }
+ req.AddData(msg)
+
+ // When deleting don't bother building the rest of the netlink payload
+ if cmd != syscall.RTM_DELQDISC {
+ if err := qdiscPayload(req, qdisc); err != nil {
+ return err
+ }
+ }
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+func qdiscPayload(req *nl.NetlinkRequest, qdisc Qdisc) error {
+
+ req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(qdisc.Type())))
+
+ options := nl.NewRtAttr(nl.TCA_OPTIONS, nil)
+ if prio, ok := qdisc.(*Prio); ok {
+ tcmap := nl.TcPrioMap{
+ Bands: int32(prio.Bands),
+ Priomap: prio.PriorityMap,
+ }
+ options = nl.NewRtAttr(nl.TCA_OPTIONS, tcmap.Serialize())
+ } else if tbf, ok := qdisc.(*Tbf); ok {
+ opt := nl.TcTbfQopt{}
+ opt.Rate.Rate = uint32(tbf.Rate)
+ opt.Peakrate.Rate = uint32(tbf.Peakrate)
+ opt.Limit = tbf.Limit
+ opt.Buffer = tbf.Buffer
+ nl.NewRtAttrChild(options, nl.TCA_TBF_PARMS, opt.Serialize())
+ if tbf.Rate >= uint64(1<<32) {
+ nl.NewRtAttrChild(options, nl.TCA_TBF_RATE64, nl.Uint64Attr(tbf.Rate))
+ }
+ if tbf.Peakrate >= uint64(1<<32) {
+ nl.NewRtAttrChild(options, nl.TCA_TBF_PRATE64, nl.Uint64Attr(tbf.Peakrate))
+ }
+ if tbf.Peakrate > 0 {
+ nl.NewRtAttrChild(options, nl.TCA_TBF_PBURST, nl.Uint32Attr(tbf.Minburst))
+ }
+ } else if htb, ok := qdisc.(*Htb); ok {
+ opt := nl.TcHtbGlob{}
+ opt.Version = htb.Version
+ opt.Rate2Quantum = htb.Rate2Quantum
+ opt.Defcls = htb.Defcls
+ // TODO: Handle Debug properly. For now default to 0
+ opt.Debug = htb.Debug
+ opt.DirectPkts = htb.DirectPkts
+ nl.NewRtAttrChild(options, nl.TCA_HTB_INIT, opt.Serialize())
+ // nl.NewRtAttrChild(options, nl.TCA_HTB_DIRECT_QLEN, opt.Serialize())
+ } else if netem, ok := qdisc.(*Netem); ok {
+ opt := nl.TcNetemQopt{}
+ opt.Latency = netem.Latency
+ opt.Limit = netem.Limit
+ opt.Loss = netem.Loss
+ opt.Gap = netem.Gap
+ opt.Duplicate = netem.Duplicate
+ opt.Jitter = netem.Jitter
+ options = nl.NewRtAttr(nl.TCA_OPTIONS, opt.Serialize())
+ // Correlation
+ corr := nl.TcNetemCorr{}
+ corr.DelayCorr = netem.DelayCorr
+ corr.LossCorr = netem.LossCorr
+ corr.DupCorr = netem.DuplicateCorr
+
+ if corr.DelayCorr > 0 || corr.LossCorr > 0 || corr.DupCorr > 0 {
+ nl.NewRtAttrChild(options, nl.TCA_NETEM_CORR, corr.Serialize())
+ }
+ // Corruption
+ corruption := nl.TcNetemCorrupt{}
+ corruption.Probability = netem.CorruptProb
+ corruption.Correlation = netem.CorruptCorr
+ if corruption.Probability > 0 {
+ nl.NewRtAttrChild(options, nl.TCA_NETEM_CORRUPT, corruption.Serialize())
+ }
+ // Reorder
+ reorder := nl.TcNetemReorder{}
+ reorder.Probability = netem.ReorderProb
+ reorder.Correlation = netem.ReorderCorr
+ if reorder.Probability > 0 {
+ nl.NewRtAttrChild(options, nl.TCA_NETEM_REORDER, reorder.Serialize())
+ }
+ } else if _, ok := qdisc.(*Ingress); ok {
+ // ingress filters must use the proper handle
+ if qdisc.Attrs().Parent != HANDLE_INGRESS {
+ return fmt.Errorf("Ingress filters must set Parent to HANDLE_INGRESS")
+ }
+ }
+
+ req.AddData(options)
+ return nil
+}
+
+// QdiscList gets a list of qdiscs in the system.
+// Equivalent to: `tc qdisc show`.
+// The list can be filtered by link.
+func QdiscList(link Link) ([]Qdisc, error) {
+ return pkgHandle.QdiscList(link)
+}
+
+// QdiscList gets a list of qdiscs in the system.
+// Equivalent to: `tc qdisc show`.
+// The list can be filtered by link.
+func (h *Handle) QdiscList(link Link) ([]Qdisc, error) {
+ req := h.newNetlinkRequest(syscall.RTM_GETQDISC, syscall.NLM_F_DUMP)
+ index := int32(0)
+ if link != nil {
+ base := link.Attrs()
+ h.ensureIndex(base)
+ index = int32(base.Index)
+ }
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Ifindex: index,
+ }
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWQDISC)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []Qdisc
+ for _, m := range msgs {
+ msg := nl.DeserializeTcMsg(m)
+
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ // skip qdiscs from other interfaces
+ if link != nil && msg.Ifindex != index {
+ continue
+ }
+
+ base := QdiscAttrs{
+ LinkIndex: int(msg.Ifindex),
+ Handle: msg.Handle,
+ Parent: msg.Parent,
+ Refcnt: msg.Info,
+ }
+ var qdisc Qdisc
+ qdiscType := ""
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case nl.TCA_KIND:
+ qdiscType = string(attr.Value[:len(attr.Value)-1])
+ switch qdiscType {
+ case "pfifo_fast":
+ qdisc = &PfifoFast{}
+ case "prio":
+ qdisc = &Prio{}
+ case "tbf":
+ qdisc = &Tbf{}
+ case "ingress":
+ qdisc = &Ingress{}
+ case "htb":
+ qdisc = &Htb{}
+ case "netem":
+ qdisc = &Netem{}
+ default:
+ qdisc = &GenericQdisc{QdiscType: qdiscType}
+ }
+ case nl.TCA_OPTIONS:
+ switch qdiscType {
+ case "pfifo_fast":
+ // pfifo returns TcPrioMap directly without wrapping it in rtattr
+ if err := parsePfifoFastData(qdisc, attr.Value); err != nil {
+ return nil, err
+ }
+ case "prio":
+ // prio returns TcPrioMap directly without wrapping it in rtattr
+ if err := parsePrioData(qdisc, attr.Value); err != nil {
+ return nil, err
+ }
+ case "tbf":
+ data, err := nl.ParseRouteAttr(attr.Value)
+ if err != nil {
+ return nil, err
+ }
+ if err := parseTbfData(qdisc, data); err != nil {
+ return nil, err
+ }
+ case "htb":
+ data, err := nl.ParseRouteAttr(attr.Value)
+ if err != nil {
+ return nil, err
+ }
+ if err := parseHtbData(qdisc, data); err != nil {
+ return nil, err
+ }
+ case "netem":
+ if err := parseNetemData(qdisc, attr.Value); err != nil {
+ return nil, err
+ }
+
+ // no options for ingress
+ }
+ }
+ }
+ *qdisc.Attrs() = base
+ res = append(res, qdisc)
+ }
+
+ return res, nil
+}
+
+func parsePfifoFastData(qdisc Qdisc, value []byte) error {
+ pfifo := qdisc.(*PfifoFast)
+ tcmap := nl.DeserializeTcPrioMap(value)
+ pfifo.PriorityMap = tcmap.Priomap
+ pfifo.Bands = uint8(tcmap.Bands)
+ return nil
+}
+
+func parsePrioData(qdisc Qdisc, value []byte) error {
+ prio := qdisc.(*Prio)
+ tcmap := nl.DeserializeTcPrioMap(value)
+ prio.PriorityMap = tcmap.Priomap
+ prio.Bands = uint8(tcmap.Bands)
+ return nil
+}
+
+func parseHtbData(qdisc Qdisc, data []syscall.NetlinkRouteAttr) error {
+ native = nl.NativeEndian()
+ htb := qdisc.(*Htb)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_HTB_INIT:
+ opt := nl.DeserializeTcHtbGlob(datum.Value)
+ htb.Version = opt.Version
+ htb.Rate2Quantum = opt.Rate2Quantum
+ htb.Defcls = opt.Defcls
+ htb.Debug = opt.Debug
+ htb.DirectPkts = opt.DirectPkts
+ case nl.TCA_HTB_DIRECT_QLEN:
+ // TODO
+ //htb.DirectQlen = native.uint32(datum.Value)
+ }
+ }
+ return nil
+}
+
+func parseNetemData(qdisc Qdisc, value []byte) error {
+ netem := qdisc.(*Netem)
+ opt := nl.DeserializeTcNetemQopt(value)
+ netem.Latency = opt.Latency
+ netem.Limit = opt.Limit
+ netem.Loss = opt.Loss
+ netem.Gap = opt.Gap
+ netem.Duplicate = opt.Duplicate
+ netem.Jitter = opt.Jitter
+ data, err := nl.ParseRouteAttr(value[nl.SizeofTcNetemQopt:])
+ if err != nil {
+ return err
+ }
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_NETEM_CORR:
+ opt := nl.DeserializeTcNetemCorr(datum.Value)
+ netem.DelayCorr = opt.DelayCorr
+ netem.LossCorr = opt.LossCorr
+ netem.DuplicateCorr = opt.DupCorr
+ case nl.TCA_NETEM_CORRUPT:
+ opt := nl.DeserializeTcNetemCorrupt(datum.Value)
+ netem.CorruptProb = opt.Probability
+ netem.CorruptCorr = opt.Correlation
+ case nl.TCA_NETEM_REORDER:
+ opt := nl.DeserializeTcNetemReorder(datum.Value)
+ netem.ReorderProb = opt.Probability
+ netem.ReorderCorr = opt.Correlation
+ }
+ }
+ return nil
+}
+
+func parseTbfData(qdisc Qdisc, data []syscall.NetlinkRouteAttr) error {
+ native = nl.NativeEndian()
+ tbf := qdisc.(*Tbf)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_TBF_PARMS:
+ opt := nl.DeserializeTcTbfQopt(datum.Value)
+ tbf.Rate = uint64(opt.Rate.Rate)
+ tbf.Peakrate = uint64(opt.Peakrate.Rate)
+ tbf.Limit = opt.Limit
+ tbf.Buffer = opt.Buffer
+ case nl.TCA_TBF_RATE64:
+ tbf.Rate = native.Uint64(datum.Value[0:8])
+ case nl.TCA_TBF_PRATE64:
+ tbf.Peakrate = native.Uint64(datum.Value[0:8])
+ case nl.TCA_TBF_PBURST:
+ tbf.Minburst = native.Uint32(datum.Value[0:4])
+ }
+ }
+ return nil
+}
+
+const (
+ TIME_UNITS_PER_SEC = 1000000
+)
+
+var (
+ tickInUsec float64
+ clockFactor float64
+ hz float64
+)
+
+func initClock() {
+ data, err := ioutil.ReadFile("/proc/net/psched")
+ if err != nil {
+ return
+ }
+ parts := strings.Split(strings.TrimSpace(string(data)), " ")
+ if len(parts) < 3 {
+ return
+ }
+ var vals [3]uint64
+ for i := range vals {
+ val, err := strconv.ParseUint(parts[i], 16, 32)
+ if err != nil {
+ return
+ }
+ vals[i] = val
+ }
+ // compatibility
+ if vals[2] == 1000000000 {
+ vals[0] = vals[1]
+ }
+ clockFactor = float64(vals[2]) / TIME_UNITS_PER_SEC
+ tickInUsec = float64(vals[0]) / float64(vals[1]) * clockFactor
+ hz = float64(vals[0])
+}
+
+func TickInUsec() float64 {
+ if tickInUsec == 0.0 {
+ initClock()
+ }
+ return tickInUsec
+}
+
+func ClockFactor() float64 {
+ if clockFactor == 0.0 {
+ initClock()
+ }
+ return clockFactor
+}
+
+func Hz() float64 {
+ if hz == 0.0 {
+ initClock()
+ }
+ return hz
+}
+
+func time2Tick(time uint32) uint32 {
+ return uint32(float64(time) * TickInUsec())
+}
+
+func tick2Time(tick uint32) uint32 {
+ return uint32(float64(tick) / TickInUsec())
+}
+
+func time2Ktime(time uint32) uint32 {
+ return uint32(float64(time) * ClockFactor())
+}
+
+func ktime2Time(ktime uint32) uint32 {
+ return uint32(float64(ktime) / ClockFactor())
+}
+
+func burst(rate uint64, buffer uint32) uint32 {
+ return uint32(float64(rate) * float64(tick2Time(buffer)) / TIME_UNITS_PER_SEC)
+}
+
+func latency(rate uint64, limit, buffer uint32) float64 {
+ return TIME_UNITS_PER_SEC*(float64(limit)/float64(rate)) - float64(tick2Time(buffer))
+}
+
+func Xmittime(rate uint64, size uint32) float64 {
+ return TickInUsec() * TIME_UNITS_PER_SEC * (float64(size) / float64(rate))
+}
diff --git a/vendor/github.com/vishvananda/netlink/route.go b/vendor/github.com/vishvananda/netlink/route.go
new file mode 100644
index 0000000..03ac4b2
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/route.go
@@ -0,0 +1,116 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+ "strings"
+)
+
+// Scope is an enum representing a route scope.
+type Scope uint8
+
+type NextHopFlag int
+
+type Destination interface {
+ Family() int
+ Decode([]byte) error
+ Encode() ([]byte, error)
+ String() string
+}
+
+type Encap interface {
+ Type() int
+ Decode([]byte) error
+ Encode() ([]byte, error)
+ String() string
+}
+
+// Route represents a netlink route.
+type Route struct {
+ LinkIndex int
+ ILinkIndex int
+ Scope Scope
+ Dst *net.IPNet
+ Src net.IP
+ Gw net.IP
+ MultiPath []*NexthopInfo
+ Protocol int
+ Priority int
+ Table int
+ Type int
+ Tos int
+ Flags int
+ MPLSDst *int
+ NewDst Destination
+ Encap Encap
+}
+
+func (r Route) String() string {
+ elems := []string{}
+ if len(r.MultiPath) == 0 {
+ elems = append(elems, fmt.Sprintf("Ifindex: %d", r.LinkIndex))
+ }
+ if r.MPLSDst != nil {
+ elems = append(elems, fmt.Sprintf("Dst: %d", r.MPLSDst))
+ } else {
+ elems = append(elems, fmt.Sprintf("Dst: %s", r.Dst))
+ }
+ if r.NewDst != nil {
+ elems = append(elems, fmt.Sprintf("NewDst: %s", r.NewDst))
+ }
+ if r.Encap != nil {
+ elems = append(elems, fmt.Sprintf("Encap: %s", r.Encap))
+ }
+ elems = append(elems, fmt.Sprintf("Src: %s", r.Src))
+ if len(r.MultiPath) > 0 {
+ elems = append(elems, fmt.Sprintf("Gw: %s", r.MultiPath))
+ } else {
+ elems = append(elems, fmt.Sprintf("Gw: %s", r.Gw))
+ }
+ elems = append(elems, fmt.Sprintf("Flags: %s", r.ListFlags()))
+ elems = append(elems, fmt.Sprintf("Table: %d", r.Table))
+ return fmt.Sprintf("{%s}", strings.Join(elems, " "))
+}
+
+func (r *Route) SetFlag(flag NextHopFlag) {
+ r.Flags |= int(flag)
+}
+
+func (r *Route) ClearFlag(flag NextHopFlag) {
+ r.Flags &^= int(flag)
+}
+
+type flagString struct {
+ f NextHopFlag
+ s string
+}
+
+// RouteUpdate is sent when a route changes - type is RTM_NEWROUTE or RTM_DELROUTE
+type RouteUpdate struct {
+ Type uint16
+ Route
+}
+
+type NexthopInfo struct {
+ LinkIndex int
+ Hops int
+ Gw net.IP
+ Flags int
+ NewDst Destination
+ Encap Encap
+}
+
+func (n *NexthopInfo) String() string {
+ elems := []string{}
+ elems = append(elems, fmt.Sprintf("Ifindex: %d", n.LinkIndex))
+ if n.NewDst != nil {
+ elems = append(elems, fmt.Sprintf("NewDst: %s", n.NewDst))
+ }
+ if n.Encap != nil {
+ elems = append(elems, fmt.Sprintf("Encap: %s", n.Encap))
+ }
+ elems = append(elems, fmt.Sprintf("Weight: %d", n.Hops+1))
+ elems = append(elems, fmt.Sprintf("Gw: %d", n.Gw))
+ elems = append(elems, fmt.Sprintf("Flags: %s", n.ListFlags()))
+ return fmt.Sprintf("{%s}", strings.Join(elems, " "))
+}
diff --git a/vendor/github.com/vishvananda/netlink/route_linux.go b/vendor/github.com/vishvananda/netlink/route_linux.go
new file mode 100644
index 0000000..cd739e7
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/route_linux.go
@@ -0,0 +1,674 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+ "strings"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+ "github.com/vishvananda/netns"
+)
+
+// RtAttr is shared so it is in netlink_linux.go
+
+const (
+ SCOPE_UNIVERSE Scope = syscall.RT_SCOPE_UNIVERSE
+ SCOPE_SITE Scope = syscall.RT_SCOPE_SITE
+ SCOPE_LINK Scope = syscall.RT_SCOPE_LINK
+ SCOPE_HOST Scope = syscall.RT_SCOPE_HOST
+ SCOPE_NOWHERE Scope = syscall.RT_SCOPE_NOWHERE
+)
+
+const (
+ RT_FILTER_PROTOCOL uint64 = 1 << (1 + iota)
+ RT_FILTER_SCOPE
+ RT_FILTER_TYPE
+ RT_FILTER_TOS
+ RT_FILTER_IIF
+ RT_FILTER_OIF
+ RT_FILTER_DST
+ RT_FILTER_SRC
+ RT_FILTER_GW
+ RT_FILTER_TABLE
+)
+
+const (
+ FLAG_ONLINK NextHopFlag = syscall.RTNH_F_ONLINK
+ FLAG_PERVASIVE NextHopFlag = syscall.RTNH_F_PERVASIVE
+)
+
+var testFlags = []flagString{
+ {f: FLAG_ONLINK, s: "onlink"},
+ {f: FLAG_PERVASIVE, s: "pervasive"},
+}
+
+func listFlags(flag int) []string {
+ var flags []string
+ for _, tf := range testFlags {
+ if flag&int(tf.f) != 0 {
+ flags = append(flags, tf.s)
+ }
+ }
+ return flags
+}
+
+func (r *Route) ListFlags() []string {
+ return listFlags(r.Flags)
+}
+
+func (n *NexthopInfo) ListFlags() []string {
+ return listFlags(n.Flags)
+}
+
+type MPLSDestination struct {
+ Labels []int
+}
+
+func (d *MPLSDestination) Family() int {
+ return nl.FAMILY_MPLS
+}
+
+func (d *MPLSDestination) Decode(buf []byte) error {
+ d.Labels = nl.DecodeMPLSStack(buf)
+ return nil
+}
+
+func (d *MPLSDestination) Encode() ([]byte, error) {
+ return nl.EncodeMPLSStack(d.Labels...), nil
+}
+
+func (d *MPLSDestination) String() string {
+ s := make([]string, 0, len(d.Labels))
+ for _, l := range d.Labels {
+ s = append(s, fmt.Sprintf("%d", l))
+ }
+ return strings.Join(s, "/")
+}
+
+type MPLSEncap struct {
+ Labels []int
+}
+
+func (e *MPLSEncap) Type() int {
+ return nl.LWTUNNEL_ENCAP_MPLS
+}
+
+func (e *MPLSEncap) Decode(buf []byte) error {
+ if len(buf) < 4 {
+ return fmt.Errorf("Lack of bytes")
+ }
+ native := nl.NativeEndian()
+ l := native.Uint16(buf)
+ if len(buf) < int(l) {
+ return fmt.Errorf("Lack of bytes")
+ }
+ buf = buf[:l]
+ typ := native.Uint16(buf[2:])
+ if typ != nl.MPLS_IPTUNNEL_DST {
+ return fmt.Errorf("Unknown MPLS Encap Type: %d", typ)
+ }
+ e.Labels = nl.DecodeMPLSStack(buf[4:])
+ return nil
+}
+
+func (e *MPLSEncap) Encode() ([]byte, error) {
+ s := nl.EncodeMPLSStack(e.Labels...)
+ native := nl.NativeEndian()
+ hdr := make([]byte, 4)
+ native.PutUint16(hdr, uint16(len(s)+4))
+ native.PutUint16(hdr[2:], nl.MPLS_IPTUNNEL_DST)
+ return append(hdr, s...), nil
+}
+
+func (e *MPLSEncap) String() string {
+ s := make([]string, 0, len(e.Labels))
+ for _, l := range e.Labels {
+ s = append(s, fmt.Sprintf("%d", l))
+ }
+ return strings.Join(s, "/")
+}
+
+// RouteAdd will add a route to the system.
+// Equivalent to: `ip route add $route`
+func RouteAdd(route *Route) error {
+ return pkgHandle.RouteAdd(route)
+}
+
+// RouteAdd will add a route to the system.
+// Equivalent to: `ip route add $route`
+func (h *Handle) RouteAdd(route *Route) error {
+ flags := syscall.NLM_F_CREATE | syscall.NLM_F_EXCL | syscall.NLM_F_ACK
+ req := h.newNetlinkRequest(syscall.RTM_NEWROUTE, flags)
+ return h.routeHandle(route, req, nl.NewRtMsg())
+}
+
+// RouteReplace will add a route to the system.
+// Equivalent to: `ip route replace $route`
+func RouteReplace(route *Route) error {
+ return pkgHandle.RouteReplace(route)
+}
+
+// RouteReplace will add a route to the system.
+// Equivalent to: `ip route replace $route`
+func (h *Handle) RouteReplace(route *Route) error {
+ flags := syscall.NLM_F_CREATE | syscall.NLM_F_REPLACE | syscall.NLM_F_ACK
+ req := h.newNetlinkRequest(syscall.RTM_NEWROUTE, flags)
+ return h.routeHandle(route, req, nl.NewRtMsg())
+}
+
+// RouteDel will delete a route from the system.
+// Equivalent to: `ip route del $route`
+func RouteDel(route *Route) error {
+ return pkgHandle.RouteDel(route)
+}
+
+// RouteDel will delete a route from the system.
+// Equivalent to: `ip route del $route`
+func (h *Handle) RouteDel(route *Route) error {
+ req := h.newNetlinkRequest(syscall.RTM_DELROUTE, syscall.NLM_F_ACK)
+ return h.routeHandle(route, req, nl.NewRtDelMsg())
+}
+
+func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg) error {
+ if (route.Dst == nil || route.Dst.IP == nil) && route.Src == nil && route.Gw == nil && route.MPLSDst == nil {
+ return fmt.Errorf("one of Dst.IP, Src, or Gw must not be nil")
+ }
+
+ family := -1
+ var rtAttrs []*nl.RtAttr
+
+ if route.Dst != nil && route.Dst.IP != nil {
+ dstLen, _ := route.Dst.Mask.Size()
+ msg.Dst_len = uint8(dstLen)
+ dstFamily := nl.GetIPFamily(route.Dst.IP)
+ family = dstFamily
+ var dstData []byte
+ if dstFamily == FAMILY_V4 {
+ dstData = route.Dst.IP.To4()
+ } else {
+ dstData = route.Dst.IP.To16()
+ }
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_DST, dstData))
+ } else if route.MPLSDst != nil {
+ family = nl.FAMILY_MPLS
+ msg.Dst_len = uint8(20)
+ msg.Type = syscall.RTN_UNICAST
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_DST, nl.EncodeMPLSStack(*route.MPLSDst)))
+ }
+
+ if route.NewDst != nil {
+ if family != -1 && family != route.NewDst.Family() {
+ return fmt.Errorf("new destination and destination are not the same address family")
+ }
+ buf, err := route.NewDst.Encode()
+ if err != nil {
+ return err
+ }
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(nl.RTA_NEWDST, buf))
+ }
+
+ if route.Encap != nil {
+ buf := make([]byte, 2)
+ native.PutUint16(buf, uint16(route.Encap.Type()))
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(nl.RTA_ENCAP_TYPE, buf))
+ buf, err := route.Encap.Encode()
+ if err != nil {
+ return err
+ }
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(nl.RTA_ENCAP, buf))
+ }
+
+ if route.Src != nil {
+ srcFamily := nl.GetIPFamily(route.Src)
+ if family != -1 && family != srcFamily {
+ return fmt.Errorf("source and destination ip are not the same IP family")
+ }
+ family = srcFamily
+ var srcData []byte
+ if srcFamily == FAMILY_V4 {
+ srcData = route.Src.To4()
+ } else {
+ srcData = route.Src.To16()
+ }
+ // The commonly used src ip for routes is actually PREFSRC
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_PREFSRC, srcData))
+ }
+
+ if route.Gw != nil {
+ gwFamily := nl.GetIPFamily(route.Gw)
+ if family != -1 && family != gwFamily {
+ return fmt.Errorf("gateway, source, and destination ip are not the same IP family")
+ }
+ family = gwFamily
+ var gwData []byte
+ if gwFamily == FAMILY_V4 {
+ gwData = route.Gw.To4()
+ } else {
+ gwData = route.Gw.To16()
+ }
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_GATEWAY, gwData))
+ }
+
+ if len(route.MultiPath) > 0 {
+ buf := []byte{}
+ for _, nh := range route.MultiPath {
+ rtnh := &nl.RtNexthop{
+ RtNexthop: syscall.RtNexthop{
+ Hops: uint8(nh.Hops),
+ Ifindex: int32(nh.LinkIndex),
+ Flags: uint8(nh.Flags),
+ },
+ }
+ children := []nl.NetlinkRequestData{}
+ if nh.Gw != nil {
+ gwFamily := nl.GetIPFamily(nh.Gw)
+ if family != -1 && family != gwFamily {
+ return fmt.Errorf("gateway, source, and destination ip are not the same IP family")
+ }
+ if gwFamily == FAMILY_V4 {
+ children = append(children, nl.NewRtAttr(syscall.RTA_GATEWAY, []byte(nh.Gw.To4())))
+ } else {
+ children = append(children, nl.NewRtAttr(syscall.RTA_GATEWAY, []byte(nh.Gw.To16())))
+ }
+ }
+ if nh.NewDst != nil {
+ if family != -1 && family != nh.NewDst.Family() {
+ return fmt.Errorf("new destination and destination are not the same address family")
+ }
+ buf, err := nh.NewDst.Encode()
+ if err != nil {
+ return err
+ }
+ children = append(children, nl.NewRtAttr(nl.RTA_NEWDST, buf))
+ }
+ if nh.Encap != nil {
+ buf := make([]byte, 2)
+ native.PutUint16(buf, uint16(nh.Encap.Type()))
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(nl.RTA_ENCAP_TYPE, buf))
+ buf, err := nh.Encap.Encode()
+ if err != nil {
+ return err
+ }
+ children = append(children, nl.NewRtAttr(nl.RTA_ENCAP, buf))
+ }
+ rtnh.Children = children
+ buf = append(buf, rtnh.Serialize()...)
+ }
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_MULTIPATH, buf))
+ }
+
+ if route.Table > 0 {
+ if route.Table >= 256 {
+ msg.Table = syscall.RT_TABLE_UNSPEC
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(route.Table))
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_TABLE, b))
+ } else {
+ msg.Table = uint8(route.Table)
+ }
+ }
+
+ if route.Priority > 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(route.Priority))
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_PRIORITY, b))
+ }
+ if route.Tos > 0 {
+ msg.Tos = uint8(route.Tos)
+ }
+ if route.Protocol > 0 {
+ msg.Protocol = uint8(route.Protocol)
+ }
+ if route.Type > 0 {
+ msg.Type = uint8(route.Type)
+ }
+
+ msg.Flags = uint32(route.Flags)
+ msg.Scope = uint8(route.Scope)
+ msg.Family = uint8(family)
+ req.AddData(msg)
+ for _, attr := range rtAttrs {
+ req.AddData(attr)
+ }
+
+ var (
+ b = make([]byte, 4)
+ native = nl.NativeEndian()
+ )
+ native.PutUint32(b, uint32(route.LinkIndex))
+
+ req.AddData(nl.NewRtAttr(syscall.RTA_OIF, b))
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// RouteList gets a list of routes in the system.
+// Equivalent to: `ip route show`.
+// The list can be filtered by link and ip family.
+func RouteList(link Link, family int) ([]Route, error) {
+ return pkgHandle.RouteList(link, family)
+}
+
+// RouteList gets a list of routes in the system.
+// Equivalent to: `ip route show`.
+// The list can be filtered by link and ip family.
+func (h *Handle) RouteList(link Link, family int) ([]Route, error) {
+ var routeFilter *Route
+ if link != nil {
+ routeFilter = &Route{
+ LinkIndex: link.Attrs().Index,
+ }
+ }
+ return h.RouteListFiltered(family, routeFilter, RT_FILTER_OIF)
+}
+
+// RouteListFiltered gets a list of routes in the system filtered with specified rules.
+// All rules must be defined in RouteFilter struct
+func RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) {
+ return pkgHandle.RouteListFiltered(family, filter, filterMask)
+}
+
+// RouteListFiltered gets a list of routes in the system filtered with specified rules.
+// All rules must be defined in RouteFilter struct
+func (h *Handle) RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) {
+ req := h.newNetlinkRequest(syscall.RTM_GETROUTE, syscall.NLM_F_DUMP)
+ infmsg := nl.NewIfInfomsg(family)
+ req.AddData(infmsg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWROUTE)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []Route
+ for _, m := range msgs {
+ msg := nl.DeserializeRtMsg(m)
+ if msg.Flags&syscall.RTM_F_CLONED != 0 {
+ // Ignore cloned routes
+ continue
+ }
+ if msg.Table != syscall.RT_TABLE_MAIN {
+ if filter == nil || filter != nil && filterMask&RT_FILTER_TABLE == 0 {
+ // Ignore non-main tables
+ continue
+ }
+ }
+ route, err := deserializeRoute(m)
+ if err != nil {
+ return nil, err
+ }
+ if filter != nil {
+ switch {
+ case filterMask&RT_FILTER_TABLE != 0 && filter.Table != syscall.RT_TABLE_UNSPEC && route.Table != filter.Table:
+ continue
+ case filterMask&RT_FILTER_PROTOCOL != 0 && route.Protocol != filter.Protocol:
+ continue
+ case filterMask&RT_FILTER_SCOPE != 0 && route.Scope != filter.Scope:
+ continue
+ case filterMask&RT_FILTER_TYPE != 0 && route.Type != filter.Type:
+ continue
+ case filterMask&RT_FILTER_TOS != 0 && route.Tos != filter.Tos:
+ continue
+ case filterMask&RT_FILTER_OIF != 0 && route.LinkIndex != filter.LinkIndex:
+ continue
+ case filterMask&RT_FILTER_IIF != 0 && route.ILinkIndex != filter.ILinkIndex:
+ continue
+ case filterMask&RT_FILTER_GW != 0 && !route.Gw.Equal(filter.Gw):
+ continue
+ case filterMask&RT_FILTER_SRC != 0 && !route.Src.Equal(filter.Src):
+ continue
+ case filterMask&RT_FILTER_DST != 0:
+ if filter.MPLSDst == nil || route.MPLSDst == nil || (*filter.MPLSDst) != (*route.MPLSDst) {
+ if filter.Dst == nil {
+ if route.Dst != nil {
+ continue
+ }
+ } else {
+ if route.Dst == nil {
+ continue
+ }
+ aMaskLen, aMaskBits := route.Dst.Mask.Size()
+ bMaskLen, bMaskBits := filter.Dst.Mask.Size()
+ if !(route.Dst.IP.Equal(filter.Dst.IP) && aMaskLen == bMaskLen && aMaskBits == bMaskBits) {
+ continue
+ }
+ }
+ }
+ }
+ }
+ res = append(res, route)
+ }
+ return res, nil
+}
+
+// deserializeRoute decodes a binary netlink message into a Route struct
+func deserializeRoute(m []byte) (Route, error) {
+ msg := nl.DeserializeRtMsg(m)
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return Route{}, err
+ }
+ route := Route{
+ Scope: Scope(msg.Scope),
+ Protocol: int(msg.Protocol),
+ Table: int(msg.Table),
+ Type: int(msg.Type),
+ Tos: int(msg.Tos),
+ Flags: int(msg.Flags),
+ }
+
+ native := nl.NativeEndian()
+ var encap, encapType syscall.NetlinkRouteAttr
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case syscall.RTA_GATEWAY:
+ route.Gw = net.IP(attr.Value)
+ case syscall.RTA_PREFSRC:
+ route.Src = net.IP(attr.Value)
+ case syscall.RTA_DST:
+ if msg.Family == nl.FAMILY_MPLS {
+ stack := nl.DecodeMPLSStack(attr.Value)
+ if len(stack) == 0 || len(stack) > 1 {
+ return route, fmt.Errorf("invalid MPLS RTA_DST")
+ }
+ route.MPLSDst = &stack[0]
+ } else {
+ route.Dst = &net.IPNet{
+ IP: attr.Value,
+ Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)),
+ }
+ }
+ case syscall.RTA_OIF:
+ route.LinkIndex = int(native.Uint32(attr.Value[0:4]))
+ case syscall.RTA_IIF:
+ route.ILinkIndex = int(native.Uint32(attr.Value[0:4]))
+ case syscall.RTA_PRIORITY:
+ route.Priority = int(native.Uint32(attr.Value[0:4]))
+ case syscall.RTA_TABLE:
+ route.Table = int(native.Uint32(attr.Value[0:4]))
+ case syscall.RTA_MULTIPATH:
+ parseRtNexthop := func(value []byte) (*NexthopInfo, []byte, error) {
+ if len(value) < syscall.SizeofRtNexthop {
+ return nil, nil, fmt.Errorf("Lack of bytes")
+ }
+ nh := nl.DeserializeRtNexthop(value)
+ if len(value) < int(nh.RtNexthop.Len) {
+ return nil, nil, fmt.Errorf("Lack of bytes")
+ }
+ info := &NexthopInfo{
+ LinkIndex: int(nh.RtNexthop.Ifindex),
+ Hops: int(nh.RtNexthop.Hops),
+ Flags: int(nh.RtNexthop.Flags),
+ }
+ attrs, err := nl.ParseRouteAttr(value[syscall.SizeofRtNexthop:int(nh.RtNexthop.Len)])
+ if err != nil {
+ return nil, nil, err
+ }
+ var encap, encapType syscall.NetlinkRouteAttr
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case syscall.RTA_GATEWAY:
+ info.Gw = net.IP(attr.Value)
+ case nl.RTA_NEWDST:
+ var d Destination
+ switch msg.Family {
+ case nl.FAMILY_MPLS:
+ d = &MPLSDestination{}
+ }
+ if err := d.Decode(attr.Value); err != nil {
+ return nil, nil, err
+ }
+ info.NewDst = d
+ case nl.RTA_ENCAP_TYPE:
+ encapType = attr
+ case nl.RTA_ENCAP:
+ encap = attr
+ }
+ }
+
+ if len(encap.Value) != 0 && len(encapType.Value) != 0 {
+ typ := int(native.Uint16(encapType.Value[0:2]))
+ var e Encap
+ switch typ {
+ case nl.LWTUNNEL_ENCAP_MPLS:
+ e = &MPLSEncap{}
+ if err := e.Decode(encap.Value); err != nil {
+ return nil, nil, err
+ }
+ }
+ info.Encap = e
+ }
+
+ return info, value[int(nh.RtNexthop.Len):], nil
+ }
+ rest := attr.Value
+ for len(rest) > 0 {
+ info, buf, err := parseRtNexthop(rest)
+ if err != nil {
+ return route, err
+ }
+ route.MultiPath = append(route.MultiPath, info)
+ rest = buf
+ }
+ case nl.RTA_NEWDST:
+ var d Destination
+ switch msg.Family {
+ case nl.FAMILY_MPLS:
+ d = &MPLSDestination{}
+ }
+ if err := d.Decode(attr.Value); err != nil {
+ return route, err
+ }
+ route.NewDst = d
+ case nl.RTA_ENCAP_TYPE:
+ encapType = attr
+ case nl.RTA_ENCAP:
+ encap = attr
+ }
+ }
+
+ if len(encap.Value) != 0 && len(encapType.Value) != 0 {
+ typ := int(native.Uint16(encapType.Value[0:2]))
+ var e Encap
+ switch typ {
+ case nl.LWTUNNEL_ENCAP_MPLS:
+ e = &MPLSEncap{}
+ if err := e.Decode(encap.Value); err != nil {
+ return route, err
+ }
+ }
+ route.Encap = e
+ }
+
+ return route, nil
+}
+
+// RouteGet gets a route to a specific destination from the host system.
+// Equivalent to: 'ip route get'.
+func RouteGet(destination net.IP) ([]Route, error) {
+ return pkgHandle.RouteGet(destination)
+}
+
+// RouteGet gets a route to a specific destination from the host system.
+// Equivalent to: 'ip route get'.
+func (h *Handle) RouteGet(destination net.IP) ([]Route, error) {
+ req := h.newNetlinkRequest(syscall.RTM_GETROUTE, syscall.NLM_F_REQUEST)
+ family := nl.GetIPFamily(destination)
+ var destinationData []byte
+ var bitlen uint8
+ if family == FAMILY_V4 {
+ destinationData = destination.To4()
+ bitlen = 32
+ } else {
+ destinationData = destination.To16()
+ bitlen = 128
+ }
+ msg := &nl.RtMsg{}
+ msg.Family = uint8(family)
+ msg.Dst_len = bitlen
+ req.AddData(msg)
+
+ rtaDst := nl.NewRtAttr(syscall.RTA_DST, destinationData)
+ req.AddData(rtaDst)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWROUTE)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []Route
+ for _, m := range msgs {
+ route, err := deserializeRoute(m)
+ if err != nil {
+ return nil, err
+ }
+ res = append(res, route)
+ }
+ return res, nil
+
+}
+
+// RouteSubscribe takes a chan down which notifications will be sent
+// when routes are added or deleted. Close the 'done' chan to stop subscription.
+func RouteSubscribe(ch chan<- RouteUpdate, done <-chan struct{}) error {
+ return routeSubscribeAt(netns.None(), netns.None(), ch, done)
+}
+
+// RouteSubscribeAt works like RouteSubscribe plus it allows the caller
+// to choose the network namespace in which to subscribe (ns).
+func RouteSubscribeAt(ns netns.NsHandle, ch chan<- RouteUpdate, done <-chan struct{}) error {
+ return routeSubscribeAt(ns, netns.None(), ch, done)
+}
+
+func routeSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- RouteUpdate, done <-chan struct{}) error {
+ s, err := nl.SubscribeAt(newNs, curNs, syscall.NETLINK_ROUTE, syscall.RTNLGRP_IPV4_ROUTE, syscall.RTNLGRP_IPV6_ROUTE)
+ if err != nil {
+ return err
+ }
+ if done != nil {
+ go func() {
+ <-done
+ s.Close()
+ }()
+ }
+ go func() {
+ defer close(ch)
+ for {
+ msgs, err := s.Receive()
+ if err != nil {
+ return
+ }
+ for _, m := range msgs {
+ route, err := deserializeRoute(m.Data)
+ if err != nil {
+ return
+ }
+ ch <- RouteUpdate{Type: m.Header.Type, Route: route}
+ }
+ }
+ }()
+
+ return nil
+}
diff --git a/vendor/github.com/vishvananda/netlink/route_unspecified.go b/vendor/github.com/vishvananda/netlink/route_unspecified.go
new file mode 100644
index 0000000..2701862
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/route_unspecified.go
@@ -0,0 +1,11 @@
+// +build !linux
+
+package netlink
+
+func (r *Route) ListFlags() []string {
+ return []string{}
+}
+
+func (n *NexthopInfo) ListFlags() []string {
+ return []string{}
+}
diff --git a/vendor/github.com/vishvananda/netlink/rule.go b/vendor/github.com/vishvananda/netlink/rule.go
new file mode 100644
index 0000000..f0243de
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/rule.go
@@ -0,0 +1,40 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+)
+
+// Rule represents a netlink rule.
+type Rule struct {
+ Priority int
+ Table int
+ Mark int
+ Mask int
+ TunID uint
+ Goto int
+ Src *net.IPNet
+ Dst *net.IPNet
+ Flow int
+ IifName string
+ OifName string
+ SuppressIfgroup int
+ SuppressPrefixlen int
+}
+
+func (r Rule) String() string {
+ return fmt.Sprintf("ip rule %d: from %s table %d", r.Priority, r.Src, r.Table)
+}
+
+// NewRule return empty rules.
+func NewRule() *Rule {
+ return &Rule{
+ SuppressIfgroup: -1,
+ SuppressPrefixlen: -1,
+ Priority: -1,
+ Mark: -1,
+ Mask: -1,
+ Goto: -1,
+ Flow: -1,
+ }
+}
diff --git a/vendor/github.com/vishvananda/netlink/rule_linux.go b/vendor/github.com/vishvananda/netlink/rule_linux.go
new file mode 100644
index 0000000..f9cdc85
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/rule_linux.go
@@ -0,0 +1,221 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// RuleAdd adds a rule to the system.
+// Equivalent to: ip rule add
+func RuleAdd(rule *Rule) error {
+ return pkgHandle.RuleAdd(rule)
+}
+
+// RuleAdd adds a rule to the system.
+// Equivalent to: ip rule add
+func (h *Handle) RuleAdd(rule *Rule) error {
+ req := h.newNetlinkRequest(syscall.RTM_NEWRULE, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+ return ruleHandle(rule, req)
+}
+
+// RuleDel deletes a rule from the system.
+// Equivalent to: ip rule del
+func RuleDel(rule *Rule) error {
+ return pkgHandle.RuleDel(rule)
+}
+
+// RuleDel deletes a rule from the system.
+// Equivalent to: ip rule del
+func (h *Handle) RuleDel(rule *Rule) error {
+ req := h.newNetlinkRequest(syscall.RTM_DELRULE, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+ return ruleHandle(rule, req)
+}
+
+func ruleHandle(rule *Rule, req *nl.NetlinkRequest) error {
+ msg := nl.NewRtMsg()
+ msg.Family = syscall.AF_INET
+ var dstFamily uint8
+
+ var rtAttrs []*nl.RtAttr
+ if rule.Dst != nil && rule.Dst.IP != nil {
+ dstLen, _ := rule.Dst.Mask.Size()
+ msg.Dst_len = uint8(dstLen)
+ msg.Family = uint8(nl.GetIPFamily(rule.Dst.IP))
+ dstFamily = msg.Family
+ var dstData []byte
+ if msg.Family == syscall.AF_INET {
+ dstData = rule.Dst.IP.To4()
+ } else {
+ dstData = rule.Dst.IP.To16()
+ }
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_DST, dstData))
+ }
+
+ if rule.Src != nil && rule.Src.IP != nil {
+ msg.Family = uint8(nl.GetIPFamily(rule.Src.IP))
+ if dstFamily != 0 && dstFamily != msg.Family {
+ return fmt.Errorf("source and destination ip are not the same IP family")
+ }
+ srcLen, _ := rule.Src.Mask.Size()
+ msg.Src_len = uint8(srcLen)
+ var srcData []byte
+ if msg.Family == syscall.AF_INET {
+ srcData = rule.Src.IP.To4()
+ } else {
+ srcData = rule.Src.IP.To16()
+ }
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_SRC, srcData))
+ }
+
+ if rule.Table >= 0 {
+ msg.Table = uint8(rule.Table)
+ if rule.Table >= 256 {
+ msg.Table = syscall.RT_TABLE_UNSPEC
+ }
+ }
+
+ req.AddData(msg)
+ for i := range rtAttrs {
+ req.AddData(rtAttrs[i])
+ }
+
+ native := nl.NativeEndian()
+
+ if rule.Priority >= 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(rule.Priority))
+ req.AddData(nl.NewRtAttr(nl.FRA_PRIORITY, b))
+ }
+ if rule.Mark >= 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(rule.Mark))
+ req.AddData(nl.NewRtAttr(nl.FRA_FWMARK, b))
+ }
+ if rule.Mask >= 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(rule.Mask))
+ req.AddData(nl.NewRtAttr(nl.FRA_FWMASK, b))
+ }
+ if rule.Flow >= 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(rule.Flow))
+ req.AddData(nl.NewRtAttr(nl.FRA_FLOW, b))
+ }
+ if rule.TunID > 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(rule.TunID))
+ req.AddData(nl.NewRtAttr(nl.FRA_TUN_ID, b))
+ }
+ if rule.Table >= 256 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(rule.Table))
+ req.AddData(nl.NewRtAttr(nl.FRA_TABLE, b))
+ }
+ if msg.Table > 0 {
+ if rule.SuppressPrefixlen >= 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(rule.SuppressPrefixlen))
+ req.AddData(nl.NewRtAttr(nl.FRA_SUPPRESS_PREFIXLEN, b))
+ }
+ if rule.SuppressIfgroup >= 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(rule.SuppressIfgroup))
+ req.AddData(nl.NewRtAttr(nl.FRA_SUPPRESS_IFGROUP, b))
+ }
+ }
+ if rule.IifName != "" {
+ req.AddData(nl.NewRtAttr(nl.FRA_IIFNAME, []byte(rule.IifName)))
+ }
+ if rule.OifName != "" {
+ req.AddData(nl.NewRtAttr(nl.FRA_OIFNAME, []byte(rule.OifName)))
+ }
+ if rule.Goto >= 0 {
+ msg.Type = nl.FR_ACT_NOP
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(rule.Goto))
+ req.AddData(nl.NewRtAttr(nl.FRA_GOTO, b))
+ }
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// RuleList lists rules in the system.
+// Equivalent to: ip rule list
+func RuleList(family int) ([]Rule, error) {
+ return pkgHandle.RuleList(family)
+}
+
+// RuleList lists rules in the system.
+// Equivalent to: ip rule list
+func (h *Handle) RuleList(family int) ([]Rule, error) {
+ req := h.newNetlinkRequest(syscall.RTM_GETRULE, syscall.NLM_F_DUMP|syscall.NLM_F_REQUEST)
+ msg := nl.NewIfInfomsg(family)
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWRULE)
+ if err != nil {
+ return nil, err
+ }
+
+ native := nl.NativeEndian()
+ var res = make([]Rule, 0)
+ for i := range msgs {
+ msg := nl.DeserializeRtMsg(msgs[i])
+ attrs, err := nl.ParseRouteAttr(msgs[i][msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ rule := NewRule()
+
+ for j := range attrs {
+ switch attrs[j].Attr.Type {
+ case syscall.RTA_TABLE:
+ rule.Table = int(native.Uint32(attrs[j].Value[0:4]))
+ case nl.FRA_SRC:
+ rule.Src = &net.IPNet{
+ IP: attrs[j].Value,
+ Mask: net.CIDRMask(int(msg.Src_len), 8*len(attrs[j].Value)),
+ }
+ case nl.FRA_DST:
+ rule.Dst = &net.IPNet{
+ IP: attrs[j].Value,
+ Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attrs[j].Value)),
+ }
+ case nl.FRA_FWMARK:
+ rule.Mark = int(native.Uint32(attrs[j].Value[0:4]))
+ case nl.FRA_FWMASK:
+ rule.Mask = int(native.Uint32(attrs[j].Value[0:4]))
+ case nl.FRA_TUN_ID:
+ rule.TunID = uint(native.Uint64(attrs[j].Value[0:4]))
+ case nl.FRA_IIFNAME:
+ rule.IifName = string(attrs[j].Value[:len(attrs[j].Value)-1])
+ case nl.FRA_OIFNAME:
+ rule.OifName = string(attrs[j].Value[:len(attrs[j].Value)-1])
+ case nl.FRA_SUPPRESS_PREFIXLEN:
+ i := native.Uint32(attrs[j].Value[0:4])
+ if i != 0xffffffff {
+ rule.SuppressPrefixlen = int(i)
+ }
+ case nl.FRA_SUPPRESS_IFGROUP:
+ i := native.Uint32(attrs[j].Value[0:4])
+ if i != 0xffffffff {
+ rule.SuppressIfgroup = int(i)
+ }
+ case nl.FRA_FLOW:
+ rule.Flow = int(native.Uint32(attrs[j].Value[0:4]))
+ case nl.FRA_GOTO:
+ rule.Goto = int(native.Uint32(attrs[j].Value[0:4]))
+ case nl.FRA_PRIORITY:
+ rule.Priority = int(native.Uint32(attrs[j].Value[0:4]))
+ }
+ }
+ res = append(res, *rule)
+ }
+
+ return res, nil
+}
diff --git a/vendor/github.com/vishvananda/netlink/socket.go b/vendor/github.com/vishvananda/netlink/socket.go
new file mode 100644
index 0000000..41aa726
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/socket.go
@@ -0,0 +1,27 @@
+package netlink
+
+import "net"
+
+// SocketID identifies a single socket.
+type SocketID struct {
+ SourcePort uint16
+ DestinationPort uint16
+ Source net.IP
+ Destination net.IP
+ Interface uint32
+ Cookie [2]uint32
+}
+
+// Socket represents a netlink socket.
+type Socket struct {
+ Family uint8
+ State uint8
+ Timer uint8
+ Retrans uint8
+ ID SocketID
+ Expires uint32
+ RQueue uint32
+ WQueue uint32
+ UID uint32
+ INode uint32
+}
diff --git a/vendor/github.com/vishvananda/netlink/socket_linux.go b/vendor/github.com/vishvananda/netlink/socket_linux.go
new file mode 100644
index 0000000..b42b84f
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/socket_linux.go
@@ -0,0 +1,159 @@
+package netlink
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+const (
+ sizeofSocketID = 0x30
+ sizeofSocketRequest = sizeofSocketID + 0x8
+ sizeofSocket = sizeofSocketID + 0x18
+)
+
+type socketRequest struct {
+ Family uint8
+ Protocol uint8
+ Ext uint8
+ pad uint8
+ States uint32
+ ID SocketID
+}
+
+type writeBuffer struct {
+ Bytes []byte
+ pos int
+}
+
+func (b *writeBuffer) Write(c byte) {
+ b.Bytes[b.pos] = c
+ b.pos++
+}
+
+func (b *writeBuffer) Next(n int) []byte {
+ s := b.Bytes[b.pos : b.pos+n]
+ b.pos += n
+ return s
+}
+
+func (r *socketRequest) Serialize() []byte {
+ b := writeBuffer{Bytes: make([]byte, sizeofSocketRequest)}
+ b.Write(r.Family)
+ b.Write(r.Protocol)
+ b.Write(r.Ext)
+ b.Write(r.pad)
+ native.PutUint32(b.Next(4), r.States)
+ networkOrder.PutUint16(b.Next(2), r.ID.SourcePort)
+ networkOrder.PutUint16(b.Next(2), r.ID.DestinationPort)
+ copy(b.Next(4), r.ID.Source.To4())
+ b.Next(12)
+ copy(b.Next(4), r.ID.Destination.To4())
+ b.Next(12)
+ native.PutUint32(b.Next(4), r.ID.Interface)
+ native.PutUint32(b.Next(4), r.ID.Cookie[0])
+ native.PutUint32(b.Next(4), r.ID.Cookie[1])
+ return b.Bytes
+}
+
+func (r *socketRequest) Len() int { return sizeofSocketRequest }
+
+type readBuffer struct {
+ Bytes []byte
+ pos int
+}
+
+func (b *readBuffer) Read() byte {
+ c := b.Bytes[b.pos]
+ b.pos++
+ return c
+}
+
+func (b *readBuffer) Next(n int) []byte {
+ s := b.Bytes[b.pos : b.pos+n]
+ b.pos += n
+ return s
+}
+
+func (s *Socket) deserialize(b []byte) error {
+ if len(b) < sizeofSocket {
+ return fmt.Errorf("socket data short read (%d); want %d", len(b), sizeofSocket)
+ }
+ rb := readBuffer{Bytes: b}
+ s.Family = rb.Read()
+ s.State = rb.Read()
+ s.Timer = rb.Read()
+ s.Retrans = rb.Read()
+ s.ID.SourcePort = networkOrder.Uint16(rb.Next(2))
+ s.ID.DestinationPort = networkOrder.Uint16(rb.Next(2))
+ s.ID.Source = net.IPv4(rb.Read(), rb.Read(), rb.Read(), rb.Read())
+ rb.Next(12)
+ s.ID.Destination = net.IPv4(rb.Read(), rb.Read(), rb.Read(), rb.Read())
+ rb.Next(12)
+ s.ID.Interface = native.Uint32(rb.Next(4))
+ s.ID.Cookie[0] = native.Uint32(rb.Next(4))
+ s.ID.Cookie[1] = native.Uint32(rb.Next(4))
+ s.Expires = native.Uint32(rb.Next(4))
+ s.RQueue = native.Uint32(rb.Next(4))
+ s.WQueue = native.Uint32(rb.Next(4))
+ s.UID = native.Uint32(rb.Next(4))
+ s.INode = native.Uint32(rb.Next(4))
+ return nil
+}
+
+// SocketGet returns the Socket identified by its local and remote addresses.
+func SocketGet(local, remote net.Addr) (*Socket, error) {
+ localTCP, ok := local.(*net.TCPAddr)
+ if !ok {
+ return nil, ErrNotImplemented
+ }
+ remoteTCP, ok := remote.(*net.TCPAddr)
+ if !ok {
+ return nil, ErrNotImplemented
+ }
+ localIP := localTCP.IP.To4()
+ if localIP == nil {
+ return nil, ErrNotImplemented
+ }
+ remoteIP := remoteTCP.IP.To4()
+ if remoteIP == nil {
+ return nil, ErrNotImplemented
+ }
+
+ s, err := nl.Subscribe(syscall.NETLINK_INET_DIAG)
+ if err != nil {
+ return nil, err
+ }
+ defer s.Close()
+ req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, 0)
+ req.AddData(&socketRequest{
+ Family: syscall.AF_INET,
+ Protocol: syscall.IPPROTO_TCP,
+ ID: SocketID{
+ SourcePort: uint16(localTCP.Port),
+ DestinationPort: uint16(remoteTCP.Port),
+ Source: localIP,
+ Destination: remoteIP,
+ Cookie: [2]uint32{nl.TCPDIAG_NOCOOKIE, nl.TCPDIAG_NOCOOKIE},
+ },
+ })
+ s.Send(req)
+ msgs, err := s.Receive()
+ if err != nil {
+ return nil, err
+ }
+ if len(msgs) == 0 {
+ return nil, errors.New("no message nor error from netlink")
+ }
+ if len(msgs) > 2 {
+ return nil, fmt.Errorf("multiple (%d) matching sockets", len(msgs))
+ }
+ sock := &Socket{}
+ if err := sock.deserialize(msgs[0].Data); err != nil {
+ return nil, err
+ }
+ return sock, nil
+}
diff --git a/vendor/github.com/vishvananda/netlink/xfrm.go b/vendor/github.com/vishvananda/netlink/xfrm.go
new file mode 100644
index 0000000..9962dcf
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/xfrm.go
@@ -0,0 +1,74 @@
+package netlink
+
+import (
+ "fmt"
+ "syscall"
+)
+
+// Proto is an enum representing an ipsec protocol.
+type Proto uint8
+
+const (
+ XFRM_PROTO_ROUTE2 Proto = syscall.IPPROTO_ROUTING
+ XFRM_PROTO_ESP Proto = syscall.IPPROTO_ESP
+ XFRM_PROTO_AH Proto = syscall.IPPROTO_AH
+ XFRM_PROTO_HAO Proto = syscall.IPPROTO_DSTOPTS
+ XFRM_PROTO_COMP Proto = 0x6c // NOTE not defined on darwin
+ XFRM_PROTO_IPSEC_ANY Proto = syscall.IPPROTO_RAW
+)
+
+func (p Proto) String() string {
+ switch p {
+ case XFRM_PROTO_ROUTE2:
+ return "route2"
+ case XFRM_PROTO_ESP:
+ return "esp"
+ case XFRM_PROTO_AH:
+ return "ah"
+ case XFRM_PROTO_HAO:
+ return "hao"
+ case XFRM_PROTO_COMP:
+ return "comp"
+ case XFRM_PROTO_IPSEC_ANY:
+ return "ipsec-any"
+ }
+ return fmt.Sprintf("%d", p)
+}
+
+// Mode is an enum representing an ipsec transport.
+type Mode uint8
+
+const (
+ XFRM_MODE_TRANSPORT Mode = iota
+ XFRM_MODE_TUNNEL
+ XFRM_MODE_ROUTEOPTIMIZATION
+ XFRM_MODE_IN_TRIGGER
+ XFRM_MODE_BEET
+ XFRM_MODE_MAX
+)
+
+func (m Mode) String() string {
+ switch m {
+ case XFRM_MODE_TRANSPORT:
+ return "transport"
+ case XFRM_MODE_TUNNEL:
+ return "tunnel"
+ case XFRM_MODE_ROUTEOPTIMIZATION:
+ return "ro"
+ case XFRM_MODE_IN_TRIGGER:
+ return "in_trigger"
+ case XFRM_MODE_BEET:
+ return "beet"
+ }
+ return fmt.Sprintf("%d", m)
+}
+
+// XfrmMark represents the mark associated to the state or policy
+type XfrmMark struct {
+ Value uint32
+ Mask uint32
+}
+
+func (m *XfrmMark) String() string {
+ return fmt.Sprintf("(0x%x,0x%x)", m.Value, m.Mask)
+}
diff --git a/vendor/github.com/vishvananda/netlink/xfrm_monitor_linux.go b/vendor/github.com/vishvananda/netlink/xfrm_monitor_linux.go
new file mode 100644
index 0000000..7b98c9c
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/xfrm_monitor_linux.go
@@ -0,0 +1,98 @@
+package netlink
+
+import (
+ "fmt"
+ "syscall"
+
+ "github.com/vishvananda/netns"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+type XfrmMsg interface {
+ Type() nl.XfrmMsgType
+}
+
+type XfrmMsgExpire struct {
+ XfrmState *XfrmState
+ Hard bool
+}
+
+func (ue *XfrmMsgExpire) Type() nl.XfrmMsgType {
+ return nl.XFRM_MSG_EXPIRE
+}
+
+func parseXfrmMsgExpire(b []byte) *XfrmMsgExpire {
+ var e XfrmMsgExpire
+
+ msg := nl.DeserializeXfrmUserExpire(b)
+ e.XfrmState = xfrmStateFromXfrmUsersaInfo(&msg.XfrmUsersaInfo)
+ e.Hard = msg.Hard == 1
+
+ return &e
+}
+
+func XfrmMonitor(ch chan<- XfrmMsg, done <-chan struct{}, errorChan chan<- error,
+ types ...nl.XfrmMsgType) error {
+
+ groups, err := xfrmMcastGroups(types)
+ if err != nil {
+ return nil
+ }
+ s, err := nl.SubscribeAt(netns.None(), netns.None(), syscall.NETLINK_XFRM, groups...)
+ if err != nil {
+ return err
+ }
+
+ if done != nil {
+ go func() {
+ <-done
+ s.Close()
+ }()
+
+ }
+
+ go func() {
+ defer close(ch)
+ for {
+ msgs, err := s.Receive()
+ if err != nil {
+ errorChan <- err
+ return
+ }
+ for _, m := range msgs {
+ switch m.Header.Type {
+ case nl.XFRM_MSG_EXPIRE:
+ ch <- parseXfrmMsgExpire(m.Data)
+ default:
+ errorChan <- fmt.Errorf("unsupported msg type: %x", m.Header.Type)
+ }
+ }
+ }
+ }()
+
+ return nil
+}
+
+func xfrmMcastGroups(types []nl.XfrmMsgType) ([]uint, error) {
+ groups := make([]uint, 0)
+
+ if len(types) == 0 {
+ return nil, fmt.Errorf("no xfrm msg type specified")
+ }
+
+ for _, t := range types {
+ var group uint
+
+ switch t {
+ case nl.XFRM_MSG_EXPIRE:
+ group = nl.XFRMNLGRP_EXPIRE
+ default:
+ return nil, fmt.Errorf("unsupported group: %x", t)
+ }
+
+ groups = append(groups, group)
+ }
+
+ return groups, nil
+}
diff --git a/vendor/github.com/vishvananda/netlink/xfrm_policy.go b/vendor/github.com/vishvananda/netlink/xfrm_policy.go
new file mode 100644
index 0000000..c97ec43
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/xfrm_policy.go
@@ -0,0 +1,74 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+)
+
+// Dir is an enum representing an ipsec template direction.
+type Dir uint8
+
+const (
+ XFRM_DIR_IN Dir = iota
+ XFRM_DIR_OUT
+ XFRM_DIR_FWD
+ XFRM_SOCKET_IN
+ XFRM_SOCKET_OUT
+ XFRM_SOCKET_FWD
+)
+
+func (d Dir) String() string {
+ switch d {
+ case XFRM_DIR_IN:
+ return "dir in"
+ case XFRM_DIR_OUT:
+ return "dir out"
+ case XFRM_DIR_FWD:
+ return "dir fwd"
+ case XFRM_SOCKET_IN:
+ return "socket in"
+ case XFRM_SOCKET_OUT:
+ return "socket out"
+ case XFRM_SOCKET_FWD:
+ return "socket fwd"
+ }
+ return fmt.Sprintf("socket %d", d-XFRM_SOCKET_IN)
+}
+
+// XfrmPolicyTmpl encapsulates a rule for the base addresses of an ipsec
+// policy. These rules are matched with XfrmState to determine encryption
+// and authentication algorithms.
+type XfrmPolicyTmpl struct {
+ Dst net.IP
+ Src net.IP
+ Proto Proto
+ Mode Mode
+ Spi int
+ Reqid int
+}
+
+func (t XfrmPolicyTmpl) String() string {
+ return fmt.Sprintf("{Dst: %v, Src: %v, Proto: %s, Mode: %s, Spi: 0x%x, Reqid: 0x%x}",
+ t.Dst, t.Src, t.Proto, t.Mode, t.Spi, t.Reqid)
+}
+
+// XfrmPolicy represents an ipsec policy. It represents the overlay network
+// and has a list of XfrmPolicyTmpls representing the base addresses of
+// the policy.
+type XfrmPolicy struct {
+ Dst *net.IPNet
+ Src *net.IPNet
+ Proto Proto
+ DstPort int
+ SrcPort int
+ Dir Dir
+ Priority int
+ Index int
+ Mark *XfrmMark
+ Tmpls []XfrmPolicyTmpl
+}
+
+func (p XfrmPolicy) String() string {
+ return fmt.Sprintf("{Dst: %v, Src: %v, Proto: %s, DstPort: %d, SrcPort: %d, Dir: %s, Priority: %d, Index: %d, Mark: %s, Tmpls: %s}",
+ p.Dst, p.Src, p.Proto, p.DstPort, p.SrcPort, p.Dir, p.Priority, p.Index, p.Mark, p.Tmpls)
+}
diff --git a/vendor/github.com/vishvananda/netlink/xfrm_policy_linux.go b/vendor/github.com/vishvananda/netlink/xfrm_policy_linux.go
new file mode 100644
index 0000000..c3d4e42
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/xfrm_policy_linux.go
@@ -0,0 +1,257 @@
+package netlink
+
+import (
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+func selFromPolicy(sel *nl.XfrmSelector, policy *XfrmPolicy) {
+ sel.Family = uint16(nl.FAMILY_V4)
+ if policy.Dst != nil {
+ sel.Family = uint16(nl.GetIPFamily(policy.Dst.IP))
+ sel.Daddr.FromIP(policy.Dst.IP)
+ prefixlenD, _ := policy.Dst.Mask.Size()
+ sel.PrefixlenD = uint8(prefixlenD)
+ }
+ if policy.Src != nil {
+ sel.Saddr.FromIP(policy.Src.IP)
+ prefixlenS, _ := policy.Src.Mask.Size()
+ sel.PrefixlenS = uint8(prefixlenS)
+ }
+ sel.Proto = uint8(policy.Proto)
+ sel.Dport = nl.Swap16(uint16(policy.DstPort))
+ sel.Sport = nl.Swap16(uint16(policy.SrcPort))
+ if sel.Dport != 0 {
+ sel.DportMask = ^uint16(0)
+ }
+ if sel.Sport != 0 {
+ sel.SportMask = ^uint16(0)
+ }
+}
+
+// XfrmPolicyAdd will add an xfrm policy to the system.
+// Equivalent to: `ip xfrm policy add $policy`
+func XfrmPolicyAdd(policy *XfrmPolicy) error {
+ return pkgHandle.XfrmPolicyAdd(policy)
+}
+
+// XfrmPolicyAdd will add an xfrm policy to the system.
+// Equivalent to: `ip xfrm policy add $policy`
+func (h *Handle) XfrmPolicyAdd(policy *XfrmPolicy) error {
+ return h.xfrmPolicyAddOrUpdate(policy, nl.XFRM_MSG_NEWPOLICY)
+}
+
+// XfrmPolicyUpdate will update an xfrm policy to the system.
+// Equivalent to: `ip xfrm policy update $policy`
+func XfrmPolicyUpdate(policy *XfrmPolicy) error {
+ return pkgHandle.XfrmPolicyUpdate(policy)
+}
+
+// XfrmPolicyUpdate will update an xfrm policy to the system.
+// Equivalent to: `ip xfrm policy update $policy`
+func (h *Handle) XfrmPolicyUpdate(policy *XfrmPolicy) error {
+ return h.xfrmPolicyAddOrUpdate(policy, nl.XFRM_MSG_UPDPOLICY)
+}
+
+func (h *Handle) xfrmPolicyAddOrUpdate(policy *XfrmPolicy, nlProto int) error {
+ req := h.newNetlinkRequest(nlProto, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+
+ msg := &nl.XfrmUserpolicyInfo{}
+ selFromPolicy(&msg.Sel, policy)
+ msg.Priority = uint32(policy.Priority)
+ msg.Index = uint32(policy.Index)
+ msg.Dir = uint8(policy.Dir)
+ msg.Lft.SoftByteLimit = nl.XFRM_INF
+ msg.Lft.HardByteLimit = nl.XFRM_INF
+ msg.Lft.SoftPacketLimit = nl.XFRM_INF
+ msg.Lft.HardPacketLimit = nl.XFRM_INF
+ req.AddData(msg)
+
+ tmplData := make([]byte, nl.SizeofXfrmUserTmpl*len(policy.Tmpls))
+ for i, tmpl := range policy.Tmpls {
+ start := i * nl.SizeofXfrmUserTmpl
+ userTmpl := nl.DeserializeXfrmUserTmpl(tmplData[start : start+nl.SizeofXfrmUserTmpl])
+ userTmpl.XfrmId.Daddr.FromIP(tmpl.Dst)
+ userTmpl.Saddr.FromIP(tmpl.Src)
+ userTmpl.XfrmId.Proto = uint8(tmpl.Proto)
+ userTmpl.XfrmId.Spi = nl.Swap32(uint32(tmpl.Spi))
+ userTmpl.Mode = uint8(tmpl.Mode)
+ userTmpl.Reqid = uint32(tmpl.Reqid)
+ userTmpl.Aalgos = ^uint32(0)
+ userTmpl.Ealgos = ^uint32(0)
+ userTmpl.Calgos = ^uint32(0)
+ }
+ if len(tmplData) > 0 {
+ tmpls := nl.NewRtAttr(nl.XFRMA_TMPL, tmplData)
+ req.AddData(tmpls)
+ }
+ if policy.Mark != nil {
+ out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(policy.Mark))
+ req.AddData(out)
+ }
+
+ _, err := req.Execute(syscall.NETLINK_XFRM, 0)
+ return err
+}
+
+// XfrmPolicyDel will delete an xfrm policy from the system. Note that
+// the Tmpls are ignored when matching the policy to delete.
+// Equivalent to: `ip xfrm policy del $policy`
+func XfrmPolicyDel(policy *XfrmPolicy) error {
+ return pkgHandle.XfrmPolicyDel(policy)
+}
+
+// XfrmPolicyDel will delete an xfrm policy from the system. Note that
+// the Tmpls are ignored when matching the policy to delete.
+// Equivalent to: `ip xfrm policy del $policy`
+func (h *Handle) XfrmPolicyDel(policy *XfrmPolicy) error {
+ _, err := h.xfrmPolicyGetOrDelete(policy, nl.XFRM_MSG_DELPOLICY)
+ return err
+}
+
+// XfrmPolicyList gets a list of xfrm policies in the system.
+// Equivalent to: `ip xfrm policy show`.
+// The list can be filtered by ip family.
+func XfrmPolicyList(family int) ([]XfrmPolicy, error) {
+ return pkgHandle.XfrmPolicyList(family)
+}
+
+// XfrmPolicyList gets a list of xfrm policies in the system.
+// Equivalent to: `ip xfrm policy show`.
+// The list can be filtered by ip family.
+func (h *Handle) XfrmPolicyList(family int) ([]XfrmPolicy, error) {
+ req := h.newNetlinkRequest(nl.XFRM_MSG_GETPOLICY, syscall.NLM_F_DUMP)
+
+ msg := nl.NewIfInfomsg(family)
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_XFRM, nl.XFRM_MSG_NEWPOLICY)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []XfrmPolicy
+ for _, m := range msgs {
+ if policy, err := parseXfrmPolicy(m, family); err == nil {
+ res = append(res, *policy)
+ } else if err == familyError {
+ continue
+ } else {
+ return nil, err
+ }
+ }
+ return res, nil
+}
+
+// XfrmPolicyGet gets a the policy described by the index or selector, if found.
+// Equivalent to: `ip xfrm policy get { SELECTOR | index INDEX } dir DIR [ctx CTX ] [ mark MARK [ mask MASK ] ] [ ptype PTYPE ]`.
+func XfrmPolicyGet(policy *XfrmPolicy) (*XfrmPolicy, error) {
+ return pkgHandle.XfrmPolicyGet(policy)
+}
+
+// XfrmPolicyGet gets a the policy described by the index or selector, if found.
+// Equivalent to: `ip xfrm policy get { SELECTOR | index INDEX } dir DIR [ctx CTX ] [ mark MARK [ mask MASK ] ] [ ptype PTYPE ]`.
+func (h *Handle) XfrmPolicyGet(policy *XfrmPolicy) (*XfrmPolicy, error) {
+ return h.xfrmPolicyGetOrDelete(policy, nl.XFRM_MSG_GETPOLICY)
+}
+
+// XfrmPolicyFlush will flush the policies on the system.
+// Equivalent to: `ip xfrm policy flush`
+func XfrmPolicyFlush() error {
+ return pkgHandle.XfrmPolicyFlush()
+}
+
+// XfrmPolicyFlush will flush the policies on the system.
+// Equivalent to: `ip xfrm policy flush`
+func (h *Handle) XfrmPolicyFlush() error {
+ req := h.newNetlinkRequest(nl.XFRM_MSG_FLUSHPOLICY, syscall.NLM_F_ACK)
+ _, err := req.Execute(syscall.NETLINK_XFRM, 0)
+ return err
+}
+
+func (h *Handle) xfrmPolicyGetOrDelete(policy *XfrmPolicy, nlProto int) (*XfrmPolicy, error) {
+ req := h.newNetlinkRequest(nlProto, syscall.NLM_F_ACK)
+
+ msg := &nl.XfrmUserpolicyId{}
+ selFromPolicy(&msg.Sel, policy)
+ msg.Index = uint32(policy.Index)
+ msg.Dir = uint8(policy.Dir)
+ req.AddData(msg)
+
+ if policy.Mark != nil {
+ out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(policy.Mark))
+ req.AddData(out)
+ }
+
+ resType := nl.XFRM_MSG_NEWPOLICY
+ if nlProto == nl.XFRM_MSG_DELPOLICY {
+ resType = 0
+ }
+
+ msgs, err := req.Execute(syscall.NETLINK_XFRM, uint16(resType))
+ if err != nil {
+ return nil, err
+ }
+
+ if nlProto == nl.XFRM_MSG_DELPOLICY {
+ return nil, err
+ }
+
+ p, err := parseXfrmPolicy(msgs[0], FAMILY_ALL)
+ if err != nil {
+ return nil, err
+ }
+
+ return p, nil
+}
+
+func parseXfrmPolicy(m []byte, family int) (*XfrmPolicy, error) {
+ msg := nl.DeserializeXfrmUserpolicyInfo(m)
+
+ // This is mainly for the policy dump
+ if family != FAMILY_ALL && family != int(msg.Sel.Family) {
+ return nil, familyError
+ }
+
+ var policy XfrmPolicy
+
+ policy.Dst = msg.Sel.Daddr.ToIPNet(msg.Sel.PrefixlenD)
+ policy.Src = msg.Sel.Saddr.ToIPNet(msg.Sel.PrefixlenS)
+ policy.Proto = Proto(msg.Sel.Proto)
+ policy.DstPort = int(nl.Swap16(msg.Sel.Dport))
+ policy.SrcPort = int(nl.Swap16(msg.Sel.Sport))
+ policy.Priority = int(msg.Priority)
+ policy.Index = int(msg.Index)
+ policy.Dir = Dir(msg.Dir)
+
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case nl.XFRMA_TMPL:
+ max := len(attr.Value)
+ for i := 0; i < max; i += nl.SizeofXfrmUserTmpl {
+ var resTmpl XfrmPolicyTmpl
+ tmpl := nl.DeserializeXfrmUserTmpl(attr.Value[i : i+nl.SizeofXfrmUserTmpl])
+ resTmpl.Dst = tmpl.XfrmId.Daddr.ToIP()
+ resTmpl.Src = tmpl.Saddr.ToIP()
+ resTmpl.Proto = Proto(tmpl.XfrmId.Proto)
+ resTmpl.Mode = Mode(tmpl.Mode)
+ resTmpl.Spi = int(nl.Swap32(tmpl.XfrmId.Spi))
+ resTmpl.Reqid = int(tmpl.Reqid)
+ policy.Tmpls = append(policy.Tmpls, resTmpl)
+ }
+ case nl.XFRMA_MARK:
+ mark := nl.DeserializeXfrmMark(attr.Value[:])
+ policy.Mark = new(XfrmMark)
+ policy.Mark.Value = mark.Value
+ policy.Mark.Mask = mark.Mask
+ }
+ }
+
+ return &policy, nil
+}
diff --git a/vendor/github.com/vishvananda/netlink/xfrm_state.go b/vendor/github.com/vishvananda/netlink/xfrm_state.go
new file mode 100644
index 0000000..368a9b9
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/xfrm_state.go
@@ -0,0 +1,108 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+)
+
+// XfrmStateAlgo represents the algorithm to use for the ipsec encryption.
+type XfrmStateAlgo struct {
+ Name string
+ Key []byte
+ TruncateLen int // Auth only
+ ICVLen int // AEAD only
+}
+
+func (a XfrmStateAlgo) String() string {
+ base := fmt.Sprintf("{Name: %s, Key: 0x%x", a.Name, a.Key)
+ if a.TruncateLen != 0 {
+ base = fmt.Sprintf("%s, Truncate length: %d", base, a.TruncateLen)
+ }
+ if a.ICVLen != 0 {
+ base = fmt.Sprintf("%s, ICV length: %d", base, a.ICVLen)
+ }
+ return fmt.Sprintf("%s}", base)
+}
+
+// EncapType is an enum representing the optional packet encapsulation.
+type EncapType uint8
+
+const (
+ XFRM_ENCAP_ESPINUDP_NONIKE EncapType = iota + 1
+ XFRM_ENCAP_ESPINUDP
+)
+
+func (e EncapType) String() string {
+ switch e {
+ case XFRM_ENCAP_ESPINUDP_NONIKE:
+ return "espinudp-non-ike"
+ case XFRM_ENCAP_ESPINUDP:
+ return "espinudp"
+ }
+ return "unknown"
+}
+
+// XfrmStateEncap represents the encapsulation to use for the ipsec encryption.
+type XfrmStateEncap struct {
+ Type EncapType
+ SrcPort int
+ DstPort int
+ OriginalAddress net.IP
+}
+
+func (e XfrmStateEncap) String() string {
+ return fmt.Sprintf("{Type: %s, Srcport: %d, DstPort: %d, OriginalAddress: %v}",
+ e.Type, e.SrcPort, e.DstPort, e.OriginalAddress)
+}
+
+// XfrmStateLimits represents the configured limits for the state.
+type XfrmStateLimits struct {
+ ByteSoft uint64
+ ByteHard uint64
+ PacketSoft uint64
+ PacketHard uint64
+ TimeSoft uint64
+ TimeHard uint64
+ TimeUseSoft uint64
+ TimeUseHard uint64
+}
+
+// XfrmState represents the state of an ipsec policy. It optionally
+// contains an XfrmStateAlgo for encryption and one for authentication.
+type XfrmState struct {
+ Dst net.IP
+ Src net.IP
+ Proto Proto
+ Mode Mode
+ Spi int
+ Reqid int
+ ReplayWindow int
+ Limits XfrmStateLimits
+ Mark *XfrmMark
+ Auth *XfrmStateAlgo
+ Crypt *XfrmStateAlgo
+ Aead *XfrmStateAlgo
+ Encap *XfrmStateEncap
+ ESN bool
+}
+
+func (sa XfrmState) String() string {
+ return fmt.Sprintf("Dst: %v, Src: %v, Proto: %s, Mode: %s, SPI: 0x%x, ReqID: 0x%x, ReplayWindow: %d, Mark: %v, Auth: %v, Crypt: %v, Aead: %v, Encap: %v, ESN: %t",
+ sa.Dst, sa.Src, sa.Proto, sa.Mode, sa.Spi, sa.Reqid, sa.ReplayWindow, sa.Mark, sa.Auth, sa.Crypt, sa.Aead, sa.Encap, sa.ESN)
+}
+func (sa XfrmState) Print(stats bool) string {
+ if !stats {
+ return sa.String()
+ }
+
+ return fmt.Sprintf("%s, ByteSoft: %s, ByteHard: %s, PacketSoft: %s, PacketHard: %s, TimeSoft: %d, TimeHard: %d, TimeUseSoft: %d, TimeUseHard: %d",
+ sa.String(), printLimit(sa.Limits.ByteSoft), printLimit(sa.Limits.ByteHard), printLimit(sa.Limits.PacketSoft), printLimit(sa.Limits.PacketHard),
+ sa.Limits.TimeSoft, sa.Limits.TimeHard, sa.Limits.TimeUseSoft, sa.Limits.TimeUseHard)
+}
+
+func printLimit(lmt uint64) string {
+ if lmt == ^uint64(0) {
+ return "(INF)"
+ }
+ return fmt.Sprintf("%d", lmt)
+}
diff --git a/vendor/github.com/vishvananda/netlink/xfrm_state_linux.go b/vendor/github.com/vishvananda/netlink/xfrm_state_linux.go
new file mode 100644
index 0000000..6a7bc0d
--- /dev/null
+++ b/vendor/github.com/vishvananda/netlink/xfrm_state_linux.go
@@ -0,0 +1,444 @@
+package netlink
+
+import (
+ "fmt"
+ "syscall"
+ "unsafe"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+func writeStateAlgo(a *XfrmStateAlgo) []byte {
+ algo := nl.XfrmAlgo{
+ AlgKeyLen: uint32(len(a.Key) * 8),
+ AlgKey: a.Key,
+ }
+ end := len(a.Name)
+ if end > 64 {
+ end = 64
+ }
+ copy(algo.AlgName[:end], a.Name)
+ return algo.Serialize()
+}
+
+func writeStateAlgoAuth(a *XfrmStateAlgo) []byte {
+ algo := nl.XfrmAlgoAuth{
+ AlgKeyLen: uint32(len(a.Key) * 8),
+ AlgTruncLen: uint32(a.TruncateLen),
+ AlgKey: a.Key,
+ }
+ end := len(a.Name)
+ if end > 64 {
+ end = 64
+ }
+ copy(algo.AlgName[:end], a.Name)
+ return algo.Serialize()
+}
+
+func writeStateAlgoAead(a *XfrmStateAlgo) []byte {
+ algo := nl.XfrmAlgoAEAD{
+ AlgKeyLen: uint32(len(a.Key) * 8),
+ AlgICVLen: uint32(a.ICVLen),
+ AlgKey: a.Key,
+ }
+ end := len(a.Name)
+ if end > 64 {
+ end = 64
+ }
+ copy(algo.AlgName[:end], a.Name)
+ return algo.Serialize()
+}
+
+func writeMark(m *XfrmMark) []byte {
+ mark := &nl.XfrmMark{
+ Value: m.Value,
+ Mask: m.Mask,
+ }
+ if mark.Mask == 0 {
+ mark.Mask = ^uint32(0)
+ }
+ return mark.Serialize()
+}
+
+func writeReplayEsn(replayWindow int) []byte {
+ replayEsn := &nl.XfrmReplayStateEsn{
+ OSeq: 0,
+ Seq: 0,
+ OSeqHi: 0,
+ SeqHi: 0,
+ ReplayWindow: uint32(replayWindow),
+ }
+
+ // taken from iproute2/ip/xfrm_state.c:
+ replayEsn.BmpLen = uint32((replayWindow + (4 * 8) - 1) / (4 * 8))
+
+ return replayEsn.Serialize()
+}
+
+// XfrmStateAdd will add an xfrm state to the system.
+// Equivalent to: `ip xfrm state add $state`
+func XfrmStateAdd(state *XfrmState) error {
+ return pkgHandle.XfrmStateAdd(state)
+}
+
+// XfrmStateAdd will add an xfrm state to the system.
+// Equivalent to: `ip xfrm state add $state`
+func (h *Handle) XfrmStateAdd(state *XfrmState) error {
+ return h.xfrmStateAddOrUpdate(state, nl.XFRM_MSG_NEWSA)
+}
+
+// XfrmStateAllocSpi will allocate an xfrm state in the system.
+// Equivalent to: `ip xfrm state allocspi`
+func XfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) {
+ return pkgHandle.xfrmStateAllocSpi(state)
+}
+
+// XfrmStateUpdate will update an xfrm state to the system.
+// Equivalent to: `ip xfrm state update $state`
+func XfrmStateUpdate(state *XfrmState) error {
+ return pkgHandle.XfrmStateUpdate(state)
+}
+
+// XfrmStateUpdate will update an xfrm state to the system.
+// Equivalent to: `ip xfrm state update $state`
+func (h *Handle) XfrmStateUpdate(state *XfrmState) error {
+ return h.xfrmStateAddOrUpdate(state, nl.XFRM_MSG_UPDSA)
+}
+
+func (h *Handle) xfrmStateAddOrUpdate(state *XfrmState, nlProto int) error {
+
+ // A state with spi 0 can't be deleted so don't allow it to be set
+ if state.Spi == 0 {
+ return fmt.Errorf("Spi must be set when adding xfrm state.")
+ }
+ req := h.newNetlinkRequest(nlProto, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+
+ msg := xfrmUsersaInfoFromXfrmState(state)
+
+ if state.ESN {
+ if state.ReplayWindow == 0 {
+ return fmt.Errorf("ESN flag set without ReplayWindow")
+ }
+ msg.Flags |= nl.XFRM_STATE_ESN
+ msg.ReplayWindow = 0
+ }
+
+ limitsToLft(state.Limits, &msg.Lft)
+ req.AddData(msg)
+
+ if state.Auth != nil {
+ out := nl.NewRtAttr(nl.XFRMA_ALG_AUTH_TRUNC, writeStateAlgoAuth(state.Auth))
+ req.AddData(out)
+ }
+ if state.Crypt != nil {
+ out := nl.NewRtAttr(nl.XFRMA_ALG_CRYPT, writeStateAlgo(state.Crypt))
+ req.AddData(out)
+ }
+ if state.Aead != nil {
+ out := nl.NewRtAttr(nl.XFRMA_ALG_AEAD, writeStateAlgoAead(state.Aead))
+ req.AddData(out)
+ }
+ if state.Encap != nil {
+ encapData := make([]byte, nl.SizeofXfrmEncapTmpl)
+ encap := nl.DeserializeXfrmEncapTmpl(encapData)
+ encap.EncapType = uint16(state.Encap.Type)
+ encap.EncapSport = nl.Swap16(uint16(state.Encap.SrcPort))
+ encap.EncapDport = nl.Swap16(uint16(state.Encap.DstPort))
+ encap.EncapOa.FromIP(state.Encap.OriginalAddress)
+ out := nl.NewRtAttr(nl.XFRMA_ENCAP, encapData)
+ req.AddData(out)
+ }
+ if state.Mark != nil {
+ out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark))
+ req.AddData(out)
+ }
+ if state.ESN {
+ out := nl.NewRtAttr(nl.XFRMA_REPLAY_ESN_VAL, writeReplayEsn(state.ReplayWindow))
+ req.AddData(out)
+ }
+
+ _, err := req.Execute(syscall.NETLINK_XFRM, 0)
+ return err
+}
+
+func (h *Handle) xfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) {
+ req := h.newNetlinkRequest(nl.XFRM_MSG_ALLOCSPI,
+ syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+
+ msg := &nl.XfrmUserSpiInfo{}
+ msg.XfrmUsersaInfo = *(xfrmUsersaInfoFromXfrmState(state))
+ // 1-255 is reserved by IANA for future use
+ msg.Min = 0x100
+ msg.Max = 0xffffffff
+ req.AddData(msg)
+
+ if state.Mark != nil {
+ out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark))
+ req.AddData(out)
+ }
+
+ msgs, err := req.Execute(syscall.NETLINK_XFRM, 0)
+ if err != nil {
+ return nil, err
+ }
+
+ s, err := parseXfrmState(msgs[0], FAMILY_ALL)
+ if err != nil {
+ return nil, err
+ }
+
+ return s, err
+}
+
+// XfrmStateDel will delete an xfrm state from the system. Note that
+// the Algos are ignored when matching the state to delete.
+// Equivalent to: `ip xfrm state del $state`
+func XfrmStateDel(state *XfrmState) error {
+ return pkgHandle.XfrmStateDel(state)
+}
+
+// XfrmStateDel will delete an xfrm state from the system. Note that
+// the Algos are ignored when matching the state to delete.
+// Equivalent to: `ip xfrm state del $state`
+func (h *Handle) XfrmStateDel(state *XfrmState) error {
+ _, err := h.xfrmStateGetOrDelete(state, nl.XFRM_MSG_DELSA)
+ return err
+}
+
+// XfrmStateList gets a list of xfrm states in the system.
+// Equivalent to: `ip [-4|-6] xfrm state show`.
+// The list can be filtered by ip family.
+func XfrmStateList(family int) ([]XfrmState, error) {
+ return pkgHandle.XfrmStateList(family)
+}
+
+// XfrmStateList gets a list of xfrm states in the system.
+// Equivalent to: `ip xfrm state show`.
+// The list can be filtered by ip family.
+func (h *Handle) XfrmStateList(family int) ([]XfrmState, error) {
+ req := h.newNetlinkRequest(nl.XFRM_MSG_GETSA, syscall.NLM_F_DUMP)
+
+ msgs, err := req.Execute(syscall.NETLINK_XFRM, nl.XFRM_MSG_NEWSA)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []XfrmState
+ for _, m := range msgs {
+ if state, err := parseXfrmState(m, family); err == nil {
+ res = append(res, *state)
+ } else if err == familyError {
+ continue
+ } else {
+ return nil, err
+ }
+ }
+ return res, nil
+}
+
+// XfrmStateGet gets the xfrm state described by the ID, if found.
+// Equivalent to: `ip xfrm state get ID [ mark MARK [ mask MASK ] ]`.
+// Only the fields which constitue the SA ID must be filled in:
+// ID := [ src ADDR ] [ dst ADDR ] [ proto XFRM-PROTO ] [ spi SPI ]
+// mark is optional
+func XfrmStateGet(state *XfrmState) (*XfrmState, error) {
+ return pkgHandle.XfrmStateGet(state)
+}
+
+// XfrmStateGet gets the xfrm state described by the ID, if found.
+// Equivalent to: `ip xfrm state get ID [ mark MARK [ mask MASK ] ]`.
+// Only the fields which constitue the SA ID must be filled in:
+// ID := [ src ADDR ] [ dst ADDR ] [ proto XFRM-PROTO ] [ spi SPI ]
+// mark is optional
+func (h *Handle) XfrmStateGet(state *XfrmState) (*XfrmState, error) {
+ return h.xfrmStateGetOrDelete(state, nl.XFRM_MSG_GETSA)
+}
+
+func (h *Handle) xfrmStateGetOrDelete(state *XfrmState, nlProto int) (*XfrmState, error) {
+ req := h.newNetlinkRequest(nlProto, syscall.NLM_F_ACK)
+
+ msg := &nl.XfrmUsersaId{}
+ msg.Family = uint16(nl.GetIPFamily(state.Dst))
+ msg.Daddr.FromIP(state.Dst)
+ msg.Proto = uint8(state.Proto)
+ msg.Spi = nl.Swap32(uint32(state.Spi))
+ req.AddData(msg)
+
+ if state.Mark != nil {
+ out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark))
+ req.AddData(out)
+ }
+ if state.Src != nil {
+ out := nl.NewRtAttr(nl.XFRMA_SRCADDR, state.Src.To16())
+ req.AddData(out)
+ }
+
+ resType := nl.XFRM_MSG_NEWSA
+ if nlProto == nl.XFRM_MSG_DELSA {
+ resType = 0
+ }
+
+ msgs, err := req.Execute(syscall.NETLINK_XFRM, uint16(resType))
+ if err != nil {
+ return nil, err
+ }
+
+ if nlProto == nl.XFRM_MSG_DELSA {
+ return nil, nil
+ }
+
+ s, err := parseXfrmState(msgs[0], FAMILY_ALL)
+ if err != nil {
+ return nil, err
+ }
+
+ return s, nil
+}
+
+var familyError = fmt.Errorf("family error")
+
+func xfrmStateFromXfrmUsersaInfo(msg *nl.XfrmUsersaInfo) *XfrmState {
+ var state XfrmState
+
+ state.Dst = msg.Id.Daddr.ToIP()
+ state.Src = msg.Saddr.ToIP()
+ state.Proto = Proto(msg.Id.Proto)
+ state.Mode = Mode(msg.Mode)
+ state.Spi = int(nl.Swap32(msg.Id.Spi))
+ state.Reqid = int(msg.Reqid)
+ state.ReplayWindow = int(msg.ReplayWindow)
+ lftToLimits(&msg.Lft, &state.Limits)
+
+ return &state
+}
+
+func parseXfrmState(m []byte, family int) (*XfrmState, error) {
+ msg := nl.DeserializeXfrmUsersaInfo(m)
+
+ // This is mainly for the state dump
+ if family != FAMILY_ALL && family != int(msg.Family) {
+ return nil, familyError
+ }
+
+ state := xfrmStateFromXfrmUsersaInfo(msg)
+
+ attrs, err := nl.ParseRouteAttr(m[nl.SizeofXfrmUsersaInfo:])
+ if err != nil {
+ return nil, err
+ }
+
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case nl.XFRMA_ALG_AUTH, nl.XFRMA_ALG_CRYPT:
+ var resAlgo *XfrmStateAlgo
+ if attr.Attr.Type == nl.XFRMA_ALG_AUTH {
+ if state.Auth == nil {
+ state.Auth = new(XfrmStateAlgo)
+ }
+ resAlgo = state.Auth
+ } else {
+ state.Crypt = new(XfrmStateAlgo)
+ resAlgo = state.Crypt
+ }
+ algo := nl.DeserializeXfrmAlgo(attr.Value[:])
+ (*resAlgo).Name = nl.BytesToString(algo.AlgName[:])
+ (*resAlgo).Key = algo.AlgKey
+ case nl.XFRMA_ALG_AUTH_TRUNC:
+ if state.Auth == nil {
+ state.Auth = new(XfrmStateAlgo)
+ }
+ algo := nl.DeserializeXfrmAlgoAuth(attr.Value[:])
+ state.Auth.Name = nl.BytesToString(algo.AlgName[:])
+ state.Auth.Key = algo.AlgKey
+ state.Auth.TruncateLen = int(algo.AlgTruncLen)
+ case nl.XFRMA_ALG_AEAD:
+ state.Aead = new(XfrmStateAlgo)
+ algo := nl.DeserializeXfrmAlgoAEAD(attr.Value[:])
+ state.Aead.Name = nl.BytesToString(algo.AlgName[:])
+ state.Aead.Key = algo.AlgKey
+ state.Aead.ICVLen = int(algo.AlgICVLen)
+ case nl.XFRMA_ENCAP:
+ encap := nl.DeserializeXfrmEncapTmpl(attr.Value[:])
+ state.Encap = new(XfrmStateEncap)
+ state.Encap.Type = EncapType(encap.EncapType)
+ state.Encap.SrcPort = int(nl.Swap16(encap.EncapSport))
+ state.Encap.DstPort = int(nl.Swap16(encap.EncapDport))
+ state.Encap.OriginalAddress = encap.EncapOa.ToIP()
+ case nl.XFRMA_MARK:
+ mark := nl.DeserializeXfrmMark(attr.Value[:])
+ state.Mark = new(XfrmMark)
+ state.Mark.Value = mark.Value
+ state.Mark.Mask = mark.Mask
+ }
+ }
+
+ return state, nil
+}
+
+// XfrmStateFlush will flush the xfrm state on the system.
+// proto = 0 means any transformation protocols
+// Equivalent to: `ip xfrm state flush [ proto XFRM-PROTO ]`
+func XfrmStateFlush(proto Proto) error {
+ return pkgHandle.XfrmStateFlush(proto)
+}
+
+// XfrmStateFlush will flush the xfrm state on the system.
+// proto = 0 means any transformation protocols
+// Equivalent to: `ip xfrm state flush [ proto XFRM-PROTO ]`
+func (h *Handle) XfrmStateFlush(proto Proto) error {
+ req := h.newNetlinkRequest(nl.XFRM_MSG_FLUSHSA, syscall.NLM_F_ACK)
+
+ req.AddData(&nl.XfrmUsersaFlush{Proto: uint8(proto)})
+
+ _, err := req.Execute(syscall.NETLINK_XFRM, 0)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func limitsToLft(lmts XfrmStateLimits, lft *nl.XfrmLifetimeCfg) {
+ if lmts.ByteSoft != 0 {
+ lft.SoftByteLimit = lmts.ByteSoft
+ } else {
+ lft.SoftByteLimit = nl.XFRM_INF
+ }
+ if lmts.ByteHard != 0 {
+ lft.HardByteLimit = lmts.ByteHard
+ } else {
+ lft.HardByteLimit = nl.XFRM_INF
+ }
+ if lmts.PacketSoft != 0 {
+ lft.SoftPacketLimit = lmts.PacketSoft
+ } else {
+ lft.SoftPacketLimit = nl.XFRM_INF
+ }
+ if lmts.PacketHard != 0 {
+ lft.HardPacketLimit = lmts.PacketHard
+ } else {
+ lft.HardPacketLimit = nl.XFRM_INF
+ }
+ lft.SoftAddExpiresSeconds = lmts.TimeSoft
+ lft.HardAddExpiresSeconds = lmts.TimeHard
+ lft.SoftUseExpiresSeconds = lmts.TimeUseSoft
+ lft.HardUseExpiresSeconds = lmts.TimeUseHard
+}
+
+func lftToLimits(lft *nl.XfrmLifetimeCfg, lmts *XfrmStateLimits) {
+ *lmts = *(*XfrmStateLimits)(unsafe.Pointer(lft))
+}
+
+func xfrmUsersaInfoFromXfrmState(state *XfrmState) *nl.XfrmUsersaInfo {
+ msg := &nl.XfrmUsersaInfo{}
+ msg.Family = uint16(nl.GetIPFamily(state.Dst))
+ msg.Id.Daddr.FromIP(state.Dst)
+ msg.Saddr.FromIP(state.Src)
+ msg.Id.Proto = uint8(state.Proto)
+ msg.Mode = uint8(state.Mode)
+ msg.Id.Spi = nl.Swap32(uint32(state.Spi))
+ msg.Reqid = uint32(state.Reqid)
+ msg.ReplayWindow = uint8(state.ReplayWindow)
+
+ return msg
+}
diff --git a/vendor/github.com/vishvananda/netns/LICENSE b/vendor/github.com/vishvananda/netns/LICENSE
new file mode 100644
index 0000000..9f64db8
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/LICENSE
@@ -0,0 +1,192 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2014 Vishvananda Ishaya.
+ Copyright 2014 Docker, Inc.
+
+ 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/vishvananda/netns/README.md b/vendor/github.com/vishvananda/netns/README.md
new file mode 100644
index 0000000..24a4003
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/README.md
@@ -0,0 +1,49 @@
+# netns - network namespaces in go #
+
+The netns package provides an ultra-simple interface for handling
+network namespaces in go. Changing namespaces requires elevated
+privileges, so in most cases this code needs to be run as root.
+
+## Local Build and Test ##
+
+You can use go get command:
+
+ go get github.com/vishvananda/netns
+
+Testing (requires root):
+
+ sudo -E go test github.com/vishvananda/netns
+
+## Example ##
+
+```go
+package main
+
+import (
+ "net"
+ "runtime"
+ "github.com/vishvananada/netns"
+)
+
+func main() {
+ // Lock the OS Thread so we don't accidentally switch namespaces
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+
+ // Save the current network namespace
+ origns, _ := netns.Get()
+ defer origns.Close()
+
+ // Create a new network namespace
+ newns, _ := netns.New()
+ defer newns.Close()
+
+ // Do something with tne network namespace
+ ifaces, _ := net.Interfaces()
+ fmt.Printf("Interfaces: %v\n", ifaces)
+
+ // Switch back to the original namespace
+ netns.Set(origns)
+}
+
+```
diff --git a/vendor/github.com/vishvananda/netns/netns.go b/vendor/github.com/vishvananda/netns/netns.go
new file mode 100644
index 0000000..2ca0fee
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/netns.go
@@ -0,0 +1,67 @@
+// Package netns allows ultra-simple network namespace handling. NsHandles
+// can be retrieved and set. Note that the current namespace is thread
+// local so actions that set and reset namespaces should use LockOSThread
+// to make sure the namespace doesn't change due to a goroutine switch.
+// It is best to close NsHandles when you are done with them. This can be
+// accomplished via a `defer ns.Close()` on the handle. Changing namespaces
+// requires elevated privileges, so in most cases this code needs to be run
+// as root.
+package netns
+
+import (
+ "fmt"
+ "syscall"
+)
+
+// NsHandle is a handle to a network namespace. It can be cast directly
+// to an int and used as a file descriptor.
+type NsHandle int
+
+// Equal determines if two network handles refer to the same network
+// namespace. This is done by comparing the device and inode that the
+// file descripors point to.
+func (ns NsHandle) Equal(other NsHandle) bool {
+ if ns == other {
+ return true
+ }
+ var s1, s2 syscall.Stat_t
+ if err := syscall.Fstat(int(ns), &s1); err != nil {
+ return false
+ }
+ if err := syscall.Fstat(int(other), &s2); err != nil {
+ return false
+ }
+ return (s1.Dev == s2.Dev) && (s1.Ino == s2.Ino)
+}
+
+// String shows the file descriptor number and its dev and inode.
+func (ns NsHandle) String() string {
+ var s syscall.Stat_t
+ if ns == -1 {
+ return "NS(None)"
+ }
+ if err := syscall.Fstat(int(ns), &s); err != nil {
+ return fmt.Sprintf("NS(%d: unknown)", ns)
+ }
+ return fmt.Sprintf("NS(%d: %d, %d)", ns, s.Dev, s.Ino)
+}
+
+// IsOpen returns true if Close() has not been called.
+func (ns NsHandle) IsOpen() bool {
+ return ns != -1
+}
+
+// Close closes the NsHandle and resets its file descriptor to -1.
+// It is not safe to use an NsHandle after Close() is called.
+func (ns *NsHandle) Close() error {
+ if err := syscall.Close(int(*ns)); err != nil {
+ return err
+ }
+ (*ns) = -1
+ return nil
+}
+
+// Get an empty (closed) NsHandle
+func None() NsHandle {
+ return NsHandle(-1)
+}
diff --git a/vendor/github.com/vishvananda/netns/netns_linux.go b/vendor/github.com/vishvananda/netns/netns_linux.go
new file mode 100644
index 0000000..abdc308
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/netns_linux.go
@@ -0,0 +1,205 @@
+// +build linux
+
+package netns
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+)
+
+const (
+ // These constants belong in the syscall library but have not been
+ // added yet.
+ CLONE_NEWUTS = 0x04000000 /* New utsname group? */
+ CLONE_NEWIPC = 0x08000000 /* New ipcs */
+ CLONE_NEWUSER = 0x10000000 /* New user namespace */
+ CLONE_NEWPID = 0x20000000 /* New pid namespace */
+ CLONE_NEWNET = 0x40000000 /* New network namespace */
+ CLONE_IO = 0x80000000 /* Get io context */
+)
+
+// Setns sets namespace using syscall. Note that this should be a method
+// in syscall but it has not been added.
+func Setns(ns NsHandle, nstype int) (err error) {
+ _, _, e1 := syscall.Syscall(SYS_SETNS, uintptr(ns), uintptr(nstype), 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+// Set sets the current network namespace to the namespace represented
+// by NsHandle.
+func Set(ns NsHandle) (err error) {
+ return Setns(ns, CLONE_NEWNET)
+}
+
+// New creates a new network namespace and returns a handle to it.
+func New() (ns NsHandle, err error) {
+ if err := syscall.Unshare(CLONE_NEWNET); err != nil {
+ return -1, err
+ }
+ return Get()
+}
+
+// Get gets a handle to the current threads network namespace.
+func Get() (NsHandle, error) {
+ return GetFromThread(os.Getpid(), syscall.Gettid())
+}
+
+// GetFromPath gets a handle to a network namespace
+// identified by the path
+func GetFromPath(path string) (NsHandle, error) {
+ fd, err := syscall.Open(path, syscall.O_RDONLY, 0)
+ if err != nil {
+ return -1, err
+ }
+ return NsHandle(fd), nil
+}
+
+// GetFromName gets a handle to a named network namespace such as one
+// created by `ip netns add`.
+func GetFromName(name string) (NsHandle, error) {
+ return GetFromPath(fmt.Sprintf("/var/run/netns/%s", name))
+}
+
+// GetFromPid gets a handle to the network namespace of a given pid.
+func GetFromPid(pid int) (NsHandle, error) {
+ return GetFromPath(fmt.Sprintf("/proc/%d/ns/net", pid))
+}
+
+// GetFromThread gets a handle to the network namespace of a given pid and tid.
+func GetFromThread(pid, tid int) (NsHandle, error) {
+ return GetFromPath(fmt.Sprintf("/proc/%d/task/%d/ns/net", pid, tid))
+}
+
+// GetFromDocker gets a handle to the network namespace of a docker container.
+// Id is prefixed matched against the running docker containers, so a short
+// identifier can be used as long as it isn't ambiguous.
+func GetFromDocker(id string) (NsHandle, error) {
+ pid, err := getPidForContainer(id)
+ if err != nil {
+ return -1, err
+ }
+ return GetFromPid(pid)
+}
+
+// borrowed from docker/utils/utils.go
+func findCgroupMountpoint(cgroupType string) (string, error) {
+ output, err := ioutil.ReadFile("/proc/mounts")
+ if err != nil {
+ return "", err
+ }
+
+ // /proc/mounts has 6 fields per line, one mount per line, e.g.
+ // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0
+ for _, line := range strings.Split(string(output), "\n") {
+ parts := strings.Split(line, " ")
+ if len(parts) == 6 && parts[2] == "cgroup" {
+ for _, opt := range strings.Split(parts[3], ",") {
+ if opt == cgroupType {
+ return parts[1], nil
+ }
+ }
+ }
+ }
+
+ return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType)
+}
+
+// Returns the relative path to the cgroup docker is running in.
+// borrowed from docker/utils/utils.go
+// modified to get the docker pid instead of using /proc/self
+func getThisCgroup(cgroupType string) (string, error) {
+ dockerpid, err := ioutil.ReadFile("/var/run/docker.pid")
+ if err != nil {
+ return "", err
+ }
+ result := strings.Split(string(dockerpid), "\n")
+ if len(result) == 0 || len(result[0]) == 0 {
+ return "", fmt.Errorf("docker pid not found in /var/run/docker.pid")
+ }
+ pid, err := strconv.Atoi(result[0])
+
+ output, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid))
+ if err != nil {
+ return "", err
+ }
+ for _, line := range strings.Split(string(output), "\n") {
+ parts := strings.Split(line, ":")
+ // any type used by docker should work
+ if parts[1] == cgroupType {
+ return parts[2], nil
+ }
+ }
+ return "", fmt.Errorf("cgroup '%s' not found in /proc/%d/cgroup", cgroupType, pid)
+}
+
+// Returns the first pid in a container.
+// borrowed from docker/utils/utils.go
+// modified to only return the first pid
+// modified to glob with id
+// modified to search for newer docker containers
+func getPidForContainer(id string) (int, error) {
+ pid := 0
+
+ // memory is chosen randomly, any cgroup used by docker works
+ cgroupType := "memory"
+
+ cgroupRoot, err := findCgroupMountpoint(cgroupType)
+ if err != nil {
+ return pid, err
+ }
+
+ cgroupThis, err := getThisCgroup(cgroupType)
+ if err != nil {
+ return pid, err
+ }
+
+ id += "*"
+
+ attempts := []string{
+ filepath.Join(cgroupRoot, cgroupThis, id, "tasks"),
+ // With more recent lxc versions use, cgroup will be in lxc/
+ filepath.Join(cgroupRoot, cgroupThis, "lxc", id, "tasks"),
+ // With more recent dockee, cgroup will be in docker/
+ filepath.Join(cgroupRoot, cgroupThis, "docker", id, "tasks"),
+ }
+
+ var filename string
+ for _, attempt := range attempts {
+ filenames, _ := filepath.Glob(attempt)
+ if len(filenames) > 1 {
+ return pid, fmt.Errorf("Ambiguous id supplied: %v", filenames)
+ } else if len(filenames) == 1 {
+ filename = filenames[0]
+ break
+ }
+ }
+
+ if filename == "" {
+ return pid, fmt.Errorf("Unable to find container: %v", id[:len(id)-1])
+ }
+
+ output, err := ioutil.ReadFile(filename)
+ if err != nil {
+ return pid, err
+ }
+
+ result := strings.Split(string(output), "\n")
+ if len(result) == 0 || len(result[0]) == 0 {
+ return pid, fmt.Errorf("No pid found for container")
+ }
+
+ pid, err = strconv.Atoi(result[0])
+ if err != nil {
+ return pid, fmt.Errorf("Invalid pid '%s': %s", result[0], err)
+ }
+
+ return pid, nil
+}
diff --git a/vendor/github.com/vishvananda/netns/netns_linux_386.go b/vendor/github.com/vishvananda/netns/netns_linux_386.go
new file mode 100644
index 0000000..1d769bb
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/netns_linux_386.go
@@ -0,0 +1,7 @@
+// +build linux,386
+
+package netns
+
+const (
+ SYS_SETNS = 346
+)
diff --git a/vendor/github.com/vishvananda/netns/netns_linux_amd64.go b/vendor/github.com/vishvananda/netns/netns_linux_amd64.go
new file mode 100644
index 0000000..b124666
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/netns_linux_amd64.go
@@ -0,0 +1,7 @@
+// +build linux,amd64
+
+package netns
+
+const (
+ SYS_SETNS = 308
+)
diff --git a/vendor/github.com/vishvananda/netns/netns_linux_arm.go b/vendor/github.com/vishvananda/netns/netns_linux_arm.go
new file mode 100644
index 0000000..9c74eb5
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/netns_linux_arm.go
@@ -0,0 +1,7 @@
+// +build linux,arm
+
+package netns
+
+const (
+ SYS_SETNS = 375
+)
diff --git a/vendor/github.com/vishvananda/netns/netns_linux_arm64.go b/vendor/github.com/vishvananda/netns/netns_linux_arm64.go
new file mode 100644
index 0000000..741a302
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/netns_linux_arm64.go
@@ -0,0 +1,7 @@
+// +build linux,arm64
+
+package netns
+
+const (
+ SYS_SETNS = 268
+)
diff --git a/vendor/github.com/vishvananda/netns/netns_linux_ppc64le.go b/vendor/github.com/vishvananda/netns/netns_linux_ppc64le.go
new file mode 100644
index 0000000..c49eba5
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/netns_linux_ppc64le.go
@@ -0,0 +1,7 @@
+// +build linux,ppc64le
+
+package netns
+
+const (
+ SYS_SETNS = 350
+)
diff --git a/vendor/github.com/vishvananda/netns/netns_linux_s390x.go b/vendor/github.com/vishvananda/netns/netns_linux_s390x.go
new file mode 100644
index 0000000..cc13e62
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/netns_linux_s390x.go
@@ -0,0 +1,7 @@
+// +build linux,s390x
+
+package netns
+
+const (
+ SYS_SETNS = 339
+)
diff --git a/vendor/github.com/vishvananda/netns/netns_unspecified.go b/vendor/github.com/vishvananda/netns/netns_unspecified.go
new file mode 100644
index 0000000..b2edc56
--- /dev/null
+++ b/vendor/github.com/vishvananda/netns/netns_unspecified.go
@@ -0,0 +1,35 @@
+// +build !linux
+
+package netns
+
+import (
+ "errors"
+)
+
+var (
+ ErrNotImplemented = errors.New("not implemented")
+)
+
+func Set(ns NsHandle) (err error) {
+ return ErrNotImplemented
+}
+
+func New() (ns NsHandle, err error) {
+ return -1, ErrNotImplemented
+}
+
+func Get() (NsHandle, error) {
+ return -1, ErrNotImplemented
+}
+
+func GetFromName(name string) (NsHandle, error) {
+ return -1, ErrNotImplemented
+}
+
+func GetFromPid(pid int) (NsHandle, error) {
+ return -1, ErrNotImplemented
+}
+
+func GetFromDocker(id string) (NsHandle, error) {
+ return -1, ErrNotImplemented
+}
diff --git a/vendor/github.com/xeipuuv/gojsonpointer/LICENSE-APACHE-2.0.txt b/vendor/github.com/xeipuuv/gojsonpointer/LICENSE-APACHE-2.0.txt
new file mode 100644
index 0000000..55ede8a
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonpointer/LICENSE-APACHE-2.0.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2015 xeipuuv
+
+ 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/xeipuuv/gojsonpointer/README.md b/vendor/github.com/xeipuuv/gojsonpointer/README.md
new file mode 100644
index 0000000..dbe4d50
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonpointer/README.md
@@ -0,0 +1,8 @@
+# gojsonpointer
+An implementation of JSON Pointer - Go language
+
+## References
+http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07
+
+### Note
+The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented.
diff --git a/vendor/github.com/xeipuuv/gojsonpointer/pointer.go b/vendor/github.com/xeipuuv/gojsonpointer/pointer.go
new file mode 100644
index 0000000..6ca317a
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonpointer/pointer.go
@@ -0,0 +1,217 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonpointer
+// repository-desc An implementation of JSON Pointer - Go language
+//
+// description Main and unique file.
+//
+// created 25-02-2013
+
+package gojsonpointer
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "strconv"
+ "strings"
+)
+
+const (
+ const_empty_pointer = ``
+ const_pointer_separator = `/`
+
+ const_invalid_start = `JSON pointer must be empty or start with a "` + const_pointer_separator + `"`
+)
+
+type implStruct struct {
+ mode string // "SET" or "GET"
+
+ inDocument interface{}
+
+ setInValue interface{}
+
+ getOutNode interface{}
+ getOutKind reflect.Kind
+ outError error
+}
+
+func NewJsonPointer(jsonPointerString string) (JsonPointer, error) {
+
+ var p JsonPointer
+ err := p.parse(jsonPointerString)
+ return p, err
+
+}
+
+type JsonPointer struct {
+ referenceTokens []string
+}
+
+// "Constructor", parses the given string JSON pointer
+func (p *JsonPointer) parse(jsonPointerString string) error {
+
+ var err error
+
+ if jsonPointerString != const_empty_pointer {
+ if !strings.HasPrefix(jsonPointerString, const_pointer_separator) {
+ err = errors.New(const_invalid_start)
+ } else {
+ referenceTokens := strings.Split(jsonPointerString, const_pointer_separator)
+ for _, referenceToken := range referenceTokens[1:] {
+ p.referenceTokens = append(p.referenceTokens, referenceToken)
+ }
+ }
+ }
+
+ return err
+}
+
+// Uses the pointer to retrieve a value from a JSON document
+func (p *JsonPointer) Get(document interface{}) (interface{}, reflect.Kind, error) {
+
+ is := &implStruct{mode: "GET", inDocument: document}
+ p.implementation(is)
+ return is.getOutNode, is.getOutKind, is.outError
+
+}
+
+// Uses the pointer to update a value from a JSON document
+func (p *JsonPointer) Set(document interface{}, value interface{}) (interface{}, error) {
+
+ is := &implStruct{mode: "SET", inDocument: document, setInValue: value}
+ p.implementation(is)
+ return document, is.outError
+
+}
+
+// Both Get and Set functions use the same implementation to avoid code duplication
+func (p *JsonPointer) implementation(i *implStruct) {
+
+ kind := reflect.Invalid
+
+ // Full document when empty
+ if len(p.referenceTokens) == 0 {
+ i.getOutNode = i.inDocument
+ i.outError = nil
+ i.getOutKind = kind
+ i.outError = nil
+ return
+ }
+
+ node := i.inDocument
+
+ for ti, token := range p.referenceTokens {
+
+ decodedToken := decodeReferenceToken(token)
+ isLastToken := ti == len(p.referenceTokens)-1
+
+ rValue := reflect.ValueOf(node)
+ kind = rValue.Kind()
+
+ switch kind {
+
+ case reflect.Map:
+ m := node.(map[string]interface{})
+ if _, ok := m[decodedToken]; ok {
+ node = m[decodedToken]
+ if isLastToken && i.mode == "SET" {
+ m[decodedToken] = i.setInValue
+ }
+ } else {
+ i.outError = errors.New(fmt.Sprintf("Object has no key '%s'", token))
+ i.getOutKind = kind
+ i.getOutNode = nil
+ return
+ }
+
+ case reflect.Slice:
+ s := node.([]interface{})
+ tokenIndex, err := strconv.Atoi(token)
+ if err != nil {
+ i.outError = errors.New(fmt.Sprintf("Invalid array index '%s'", token))
+ i.getOutKind = kind
+ i.getOutNode = nil
+ return
+ }
+ sLength := len(s)
+ if tokenIndex < 0 || tokenIndex >= sLength {
+ i.outError = errors.New(fmt.Sprintf("Out of bound array[0,%d] index '%d'", sLength, tokenIndex))
+ i.getOutKind = kind
+ i.getOutNode = nil
+ return
+ }
+
+ node = s[tokenIndex]
+ if isLastToken && i.mode == "SET" {
+ s[tokenIndex] = i.setInValue
+ }
+
+ default:
+ i.outError = errors.New(fmt.Sprintf("Invalid token reference '%s'", token))
+ i.getOutKind = kind
+ i.getOutNode = nil
+ return
+ }
+
+ }
+
+ rValue := reflect.ValueOf(node)
+ kind = rValue.Kind()
+
+ i.getOutNode = node
+ i.getOutKind = kind
+ i.outError = nil
+}
+
+// Pointer to string representation function
+func (p *JsonPointer) String() string {
+
+ if len(p.referenceTokens) == 0 {
+ return const_empty_pointer
+ }
+
+ pointerString := const_pointer_separator + strings.Join(p.referenceTokens, const_pointer_separator)
+
+ return pointerString
+}
+
+// Specific JSON pointer encoding here
+// ~0 => ~
+// ~1 => /
+// ... and vice versa
+
+const (
+ const_encoded_reference_token_0 = `~0`
+ const_encoded_reference_token_1 = `~1`
+ const_decoded_reference_token_0 = `~`
+ const_decoded_reference_token_1 = `/`
+)
+
+func decodeReferenceToken(token string) string {
+ step1 := strings.Replace(token, const_encoded_reference_token_1, const_decoded_reference_token_1, -1)
+ step2 := strings.Replace(step1, const_encoded_reference_token_0, const_decoded_reference_token_0, -1)
+ return step2
+}
+
+func encodeReferenceToken(token string) string {
+ step1 := strings.Replace(token, const_decoded_reference_token_1, const_encoded_reference_token_1, -1)
+ step2 := strings.Replace(step1, const_decoded_reference_token_0, const_encoded_reference_token_0, -1)
+ return step2
+}
diff --git a/vendor/github.com/xeipuuv/gojsonreference/LICENSE-APACHE-2.0.txt b/vendor/github.com/xeipuuv/gojsonreference/LICENSE-APACHE-2.0.txt
new file mode 100644
index 0000000..55ede8a
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonreference/LICENSE-APACHE-2.0.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2015 xeipuuv
+
+ 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/xeipuuv/gojsonreference/README.md b/vendor/github.com/xeipuuv/gojsonreference/README.md
new file mode 100644
index 0000000..9ab6e1e
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonreference/README.md
@@ -0,0 +1,10 @@
+# gojsonreference
+An implementation of JSON Reference - Go language
+
+## Dependencies
+https://github.com/xeipuuv/gojsonpointer
+
+## References
+http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07
+
+http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03
diff --git a/vendor/github.com/xeipuuv/gojsonreference/reference.go b/vendor/github.com/xeipuuv/gojsonreference/reference.go
new file mode 100644
index 0000000..d4d2eca
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonreference/reference.go
@@ -0,0 +1,141 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonreference
+// repository-desc An implementation of JSON Reference - Go language
+//
+// description Main and unique file.
+//
+// created 26-02-2013
+
+package gojsonreference
+
+import (
+ "errors"
+ "github.com/xeipuuv/gojsonpointer"
+ "net/url"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+const (
+ const_fragment_char = `#`
+)
+
+func NewJsonReference(jsonReferenceString string) (JsonReference, error) {
+
+ var r JsonReference
+ err := r.parse(jsonReferenceString)
+ return r, err
+
+}
+
+type JsonReference struct {
+ referenceUrl *url.URL
+ referencePointer gojsonpointer.JsonPointer
+
+ HasFullUrl bool
+ HasUrlPathOnly bool
+ HasFragmentOnly bool
+ HasFileScheme bool
+ HasFullFilePath bool
+}
+
+func (r *JsonReference) GetUrl() *url.URL {
+ return r.referenceUrl
+}
+
+func (r *JsonReference) GetPointer() *gojsonpointer.JsonPointer {
+ return &r.referencePointer
+}
+
+func (r *JsonReference) String() string {
+
+ if r.referenceUrl != nil {
+ return r.referenceUrl.String()
+ }
+
+ if r.HasFragmentOnly {
+ return const_fragment_char + r.referencePointer.String()
+ }
+
+ return r.referencePointer.String()
+}
+
+func (r *JsonReference) IsCanonical() bool {
+ return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullUrl)
+}
+
+// "Constructor", parses the given string JSON reference
+func (r *JsonReference) parse(jsonReferenceString string) (err error) {
+
+ r.referenceUrl, err = url.Parse(jsonReferenceString)
+ if err != nil {
+ return
+ }
+ refUrl := r.referenceUrl
+
+ if refUrl.Scheme != "" && refUrl.Host != "" {
+ r.HasFullUrl = true
+ } else {
+ if refUrl.Path != "" {
+ r.HasUrlPathOnly = true
+ } else if refUrl.RawQuery == "" && refUrl.Fragment != "" {
+ r.HasFragmentOnly = true
+ }
+ }
+
+ r.HasFileScheme = refUrl.Scheme == "file"
+ if runtime.GOOS == "windows" {
+ // on Windows, a file URL may have an extra leading slash, and if it
+ // doesn't then its first component will be treated as the host by the
+ // Go runtime
+ if refUrl.Host == "" && strings.HasPrefix(refUrl.Path, "/") {
+ r.HasFullFilePath = filepath.IsAbs(refUrl.Path[1:])
+ } else {
+ r.HasFullFilePath = filepath.IsAbs(refUrl.Host + refUrl.Path)
+ }
+ } else {
+ r.HasFullFilePath = filepath.IsAbs(refUrl.Path)
+ }
+
+ // invalid json-pointer error means url has no json-pointer fragment. simply ignore error
+ r.referencePointer, _ = gojsonpointer.NewJsonPointer(refUrl.Fragment)
+
+ return
+}
+
+// Creates a new reference from a parent and a child
+// If the child cannot inherit from the parent, an error is returned
+func (r *JsonReference) Inherits(child JsonReference) (*JsonReference, error) {
+ childUrl := child.GetUrl()
+ parentUrl := r.GetUrl()
+ if childUrl == nil {
+ return nil, errors.New("childUrl is nil!")
+ }
+ if parentUrl == nil {
+ return nil, errors.New("parentUrl is nil!")
+ }
+
+ ref, err := NewJsonReference(parentUrl.ResolveReference(childUrl).String())
+ if err != nil {
+ return nil, err
+ }
+ return &ref, err
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/LICENSE-APACHE-2.0.txt b/vendor/github.com/xeipuuv/gojsonschema/LICENSE-APACHE-2.0.txt
new file mode 100644
index 0000000..55ede8a
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/LICENSE-APACHE-2.0.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2015 xeipuuv
+
+ 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/xeipuuv/gojsonschema/README.md b/vendor/github.com/xeipuuv/gojsonschema/README.md
new file mode 100644
index 0000000..187da61
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/README.md
@@ -0,0 +1,236 @@
+[![Build Status](https://travis-ci.org/xeipuuv/gojsonschema.svg)](https://travis-ci.org/xeipuuv/gojsonschema)
+
+# gojsonschema
+
+## Description
+
+An implementation of JSON Schema, based on IETF's draft v4 - Go language
+
+References :
+
+* http://json-schema.org
+* http://json-schema.org/latest/json-schema-core.html
+* http://json-schema.org/latest/json-schema-validation.html
+
+## Installation
+
+```
+go get github.com/xeipuuv/gojsonschema
+```
+
+Dependencies :
+* [github.com/xeipuuv/gojsonpointer](https://github.com/xeipuuv/gojsonpointer)
+* [github.com/xeipuuv/gojsonreference](https://github.com/xeipuuv/gojsonreference)
+* [github.com/stretchr/testify/assert](https://github.com/stretchr/testify#assert-package)
+
+## Usage
+
+### Example
+
+```go
+
+package main
+
+import (
+ "fmt"
+ "github.com/xeipuuv/gojsonschema"
+)
+
+func main() {
+
+ schemaLoader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json")
+ documentLoader := gojsonschema.NewReferenceLoader("file:///home/me/document.json")
+
+ result, err := gojsonschema.Validate(schemaLoader, documentLoader)
+ if err != nil {
+ panic(err.Error())
+ }
+
+ if result.Valid() {
+ fmt.Printf("The document is valid\n")
+ } else {
+ fmt.Printf("The document is not valid. see errors :\n")
+ for _, desc := range result.Errors() {
+ fmt.Printf("- %s\n", desc)
+ }
+ }
+
+}
+
+
+```
+
+#### Loaders
+
+There are various ways to load your JSON data.
+In order to load your schemas and documents,
+first declare an appropriate loader :
+
+* Web / HTTP, using a reference :
+
+```go
+loader := gojsonschema.NewReferenceLoader("http://www.some_host.com/schema.json")
+```
+
+* Local file, using a reference :
+
+```go
+loader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json")
+```
+
+References use the URI scheme, the prefix (file://) and a full path to the file are required.
+
+* JSON strings :
+
+```go
+loader := gojsonschema.NewStringLoader(`{"type": "string"}`)
+```
+
+* Custom Go types :
+
+```go
+m := map[string]interface{}{"type": "string"}
+loader := gojsonschema.NewGoLoader(m)
+```
+
+And
+
+```go
+type Root struct {
+ Users []User `json:"users"`
+}
+
+type User struct {
+ Name string `json:"name"`
+}
+
+...
+
+data := Root{}
+data.Users = append(data.Users, User{"John"})
+data.Users = append(data.Users, User{"Sophia"})
+data.Users = append(data.Users, User{"Bill"})
+
+loader := gojsonschema.NewGoLoader(data)
+```
+
+#### Validation
+
+Once the loaders are set, validation is easy :
+
+```go
+result, err := gojsonschema.Validate(schemaLoader, documentLoader)
+```
+
+Alternatively, you might want to load a schema only once and process to multiple validations :
+
+```go
+schema, err := gojsonschema.NewSchema(schemaLoader)
+...
+result1, err := schema.Validate(documentLoader1)
+...
+result2, err := schema.Validate(documentLoader2)
+...
+// etc ...
+```
+
+To check the result :
+
+```go
+ if result.Valid() {
+ fmt.Printf("The document is valid\n")
+ } else {
+ fmt.Printf("The document is not valid. see errors :\n")
+ for _, err := range result.Errors() {
+ // Err implements the ResultError interface
+ fmt.Printf("- %s\n", err)
+ }
+ }
+```
+
+## Working with Errors
+
+The library handles string error codes which you can customize by creating your own gojsonschema.locale and setting it
+```go
+gojsonschema.Locale = YourCustomLocale{}
+```
+
+However, each error contains additional contextual information.
+
+**err.Type()**: *string* Returns the "type" of error that occurred. Note you can also type check. See below
+
+Note: An error of RequiredType has an err.Type() return value of "required"
+
+ "required": RequiredError
+ "invalid_type": InvalidTypeError
+ "number_any_of": NumberAnyOfError
+ "number_one_of": NumberOneOfError
+ "number_all_of": NumberAllOfError
+ "number_not": NumberNotError
+ "missing_dependency": MissingDependencyError
+ "internal": InternalError
+ "enum": EnumError
+ "array_no_additional_items": ArrayNoAdditionalItemsError
+ "array_min_items": ArrayMinItemsError
+ "array_max_items": ArrayMaxItemsError
+ "unique": ItemsMustBeUniqueError
+ "array_min_properties": ArrayMinPropertiesError
+ "array_max_properties": ArrayMaxPropertiesError
+ "additional_property_not_allowed": AdditionalPropertyNotAllowedError
+ "invalid_property_pattern": InvalidPropertyPatternError
+ "string_gte": StringLengthGTEError
+ "string_lte": StringLengthLTEError
+ "pattern": DoesNotMatchPatternError
+ "multiple_of": MultipleOfError
+ "number_gte": NumberGTEError
+ "number_gt": NumberGTError
+ "number_lte": NumberLTEError
+ "number_lt": NumberLTError
+
+**err.Value()**: *interface{}* Returns the value given
+
+**err.Context()**: *gojsonschema.jsonContext* Returns the context. This has a String() method that will print something like this: (root).firstName
+
+**err.Field()**: *string* Returns the fieldname in the format firstName, or for embedded properties, person.firstName. This returns the same as the String() method on *err.Context()* but removes the (root). prefix.
+
+**err.Description()**: *string* The error description. This is based on the locale you are using. See the beginning of this section for overwriting the locale with a custom implementation.
+
+**err.Details()**: *gojsonschema.ErrorDetails* Returns a map[string]interface{} of additional error details specific to the error. For example, GTE errors will have a "min" value, LTE will have a "max" value. See errors.go for a full description of all the error details. Every error always contains a "field" key that holds the value of *err.Field()*
+
+Note in most cases, the err.Details() will be used to generate replacement strings in your locales. and not used directly i.e.
+```
+%field% must be greater than or equal to %min%
+```
+
+## Formats
+JSON Schema allows for optional "format" property to validate strings against well-known formats. gojsonschema ships with all of the formats defined in the spec that you can use like this:
+````json
+{"type": "string", "format": "email"}
+````
+Available formats: date-time, hostname, email, ipv4, ipv6, uri.
+
+For repetitive or more complex formats, you can create custom format checkers and add them to gojsonschema like this:
+
+```go
+// Define the format checker
+type RoleFormatChecker struct {}
+
+// Ensure it meets the gojsonschema.FormatChecker interface
+func (f RoleFormatChecker) IsFormat(input string) bool {
+ return strings.HasPrefix("ROLE_", input)
+}
+
+// Add it to the library
+gojsonschema.FormatCheckers.Add("role", RoleFormatChecker{})
+````
+
+Now to use in your json schema:
+````json
+{"type": "string", "format": "role"}
+````
+
+## Uses
+
+gojsonschema uses the following test suite :
+
+https://github.com/json-schema/JSON-Schema-Test-Suite
diff --git a/vendor/github.com/xeipuuv/gojsonschema/errors.go b/vendor/github.com/xeipuuv/gojsonschema/errors.go
new file mode 100644
index 0000000..5146cbb
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/errors.go
@@ -0,0 +1,242 @@
+package gojsonschema
+
+import (
+ "fmt"
+ "strings"
+)
+
+type (
+ // RequiredError. ErrorDetails: property string
+ RequiredError struct {
+ ResultErrorFields
+ }
+
+ // InvalidTypeError. ErrorDetails: expected, given
+ InvalidTypeError struct {
+ ResultErrorFields
+ }
+
+ // NumberAnyOfError. ErrorDetails: -
+ NumberAnyOfError struct {
+ ResultErrorFields
+ }
+
+ // NumberOneOfError. ErrorDetails: -
+ NumberOneOfError struct {
+ ResultErrorFields
+ }
+
+ // NumberAllOfError. ErrorDetails: -
+ NumberAllOfError struct {
+ ResultErrorFields
+ }
+
+ // NumberNotError. ErrorDetails: -
+ NumberNotError struct {
+ ResultErrorFields
+ }
+
+ // MissingDependencyError. ErrorDetails: dependency
+ MissingDependencyError struct {
+ ResultErrorFields
+ }
+
+ // InternalError. ErrorDetails: error
+ InternalError struct {
+ ResultErrorFields
+ }
+
+ // EnumError. ErrorDetails: allowed
+ EnumError struct {
+ ResultErrorFields
+ }
+
+ // ArrayNoAdditionalItemsError. ErrorDetails: -
+ ArrayNoAdditionalItemsError struct {
+ ResultErrorFields
+ }
+
+ // ArrayMinItemsError. ErrorDetails: min
+ ArrayMinItemsError struct {
+ ResultErrorFields
+ }
+
+ // ArrayMaxItemsError. ErrorDetails: max
+ ArrayMaxItemsError struct {
+ ResultErrorFields
+ }
+
+ // ItemsMustBeUniqueError. ErrorDetails: type
+ ItemsMustBeUniqueError struct {
+ ResultErrorFields
+ }
+
+ // ArrayMinPropertiesError. ErrorDetails: min
+ ArrayMinPropertiesError struct {
+ ResultErrorFields
+ }
+
+ // ArrayMaxPropertiesError. ErrorDetails: max
+ ArrayMaxPropertiesError struct {
+ ResultErrorFields
+ }
+
+ // AdditionalPropertyNotAllowedError. ErrorDetails: property
+ AdditionalPropertyNotAllowedError struct {
+ ResultErrorFields
+ }
+
+ // InvalidPropertyPatternError. ErrorDetails: property, pattern
+ InvalidPropertyPatternError struct {
+ ResultErrorFields
+ }
+
+ // StringLengthGTEError. ErrorDetails: min
+ StringLengthGTEError struct {
+ ResultErrorFields
+ }
+
+ // StringLengthLTEError. ErrorDetails: max
+ StringLengthLTEError struct {
+ ResultErrorFields
+ }
+
+ // DoesNotMatchPatternError. ErrorDetails: pattern
+ DoesNotMatchPatternError struct {
+ ResultErrorFields
+ }
+
+ // DoesNotMatchFormatError. ErrorDetails: format
+ DoesNotMatchFormatError struct {
+ ResultErrorFields
+ }
+
+ // MultipleOfError. ErrorDetails: multiple
+ MultipleOfError struct {
+ ResultErrorFields
+ }
+
+ // NumberGTEError. ErrorDetails: min
+ NumberGTEError struct {
+ ResultErrorFields
+ }
+
+ // NumberGTError. ErrorDetails: min
+ NumberGTError struct {
+ ResultErrorFields
+ }
+
+ // NumberLTEError. ErrorDetails: max
+ NumberLTEError struct {
+ ResultErrorFields
+ }
+
+ // NumberLTError. ErrorDetails: max
+ NumberLTError struct {
+ ResultErrorFields
+ }
+)
+
+// newError takes a ResultError type and sets the type, context, description, details, value, and field
+func newError(err ResultError, context *jsonContext, value interface{}, locale locale, details ErrorDetails) {
+ var t string
+ var d string
+ switch err.(type) {
+ case *RequiredError:
+ t = "required"
+ d = locale.Required()
+ case *InvalidTypeError:
+ t = "invalid_type"
+ d = locale.InvalidType()
+ case *NumberAnyOfError:
+ t = "number_any_of"
+ d = locale.NumberAnyOf()
+ case *NumberOneOfError:
+ t = "number_one_of"
+ d = locale.NumberOneOf()
+ case *NumberAllOfError:
+ t = "number_all_of"
+ d = locale.NumberAllOf()
+ case *NumberNotError:
+ t = "number_not"
+ d = locale.NumberNot()
+ case *MissingDependencyError:
+ t = "missing_dependency"
+ d = locale.MissingDependency()
+ case *InternalError:
+ t = "internal"
+ d = locale.Internal()
+ case *EnumError:
+ t = "enum"
+ d = locale.Enum()
+ case *ArrayNoAdditionalItemsError:
+ t = "array_no_additional_items"
+ d = locale.ArrayNoAdditionalItems()
+ case *ArrayMinItemsError:
+ t = "array_min_items"
+ d = locale.ArrayMinItems()
+ case *ArrayMaxItemsError:
+ t = "array_max_items"
+ d = locale.ArrayMaxItems()
+ case *ItemsMustBeUniqueError:
+ t = "unique"
+ d = locale.Unique()
+ case *ArrayMinPropertiesError:
+ t = "array_min_properties"
+ d = locale.ArrayMinProperties()
+ case *ArrayMaxPropertiesError:
+ t = "array_max_properties"
+ d = locale.ArrayMaxProperties()
+ case *AdditionalPropertyNotAllowedError:
+ t = "additional_property_not_allowed"
+ d = locale.AdditionalPropertyNotAllowed()
+ case *InvalidPropertyPatternError:
+ t = "invalid_property_pattern"
+ d = locale.InvalidPropertyPattern()
+ case *StringLengthGTEError:
+ t = "string_gte"
+ d = locale.StringGTE()
+ case *StringLengthLTEError:
+ t = "string_lte"
+ d = locale.StringLTE()
+ case *DoesNotMatchPatternError:
+ t = "pattern"
+ d = locale.DoesNotMatchPattern()
+ case *DoesNotMatchFormatError:
+ t = "format"
+ d = locale.DoesNotMatchFormat()
+ case *MultipleOfError:
+ t = "multiple_of"
+ d = locale.MultipleOf()
+ case *NumberGTEError:
+ t = "number_gte"
+ d = locale.NumberGTE()
+ case *NumberGTError:
+ t = "number_gt"
+ d = locale.NumberGT()
+ case *NumberLTEError:
+ t = "number_lte"
+ d = locale.NumberLTE()
+ case *NumberLTError:
+ t = "number_lt"
+ d = locale.NumberLT()
+ }
+
+ err.SetType(t)
+ err.SetContext(context)
+ err.SetValue(value)
+ err.SetDetails(details)
+ details["field"] = err.Field()
+ err.SetDescription(formatErrorDescription(d, details))
+}
+
+// formatErrorDescription takes a string in this format: %field% is required
+// and converts it to a string with replacements. The fields come from
+// the ErrorDetails struct and vary for each type of error.
+func formatErrorDescription(s string, details ErrorDetails) string {
+ for name, val := range details {
+ s = strings.Replace(s, "%"+strings.ToLower(name)+"%", fmt.Sprintf("%v", val), -1)
+ }
+
+ return s
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go b/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go
new file mode 100644
index 0000000..b91c360
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/format_checkers.go
@@ -0,0 +1,178 @@
+package gojsonschema
+
+import (
+ "net"
+ "net/url"
+ "reflect"
+ "regexp"
+ "strings"
+ "time"
+)
+
+type (
+ // FormatChecker is the interface all formatters added to FormatCheckerChain must implement
+ FormatChecker interface {
+ IsFormat(input string) bool
+ }
+
+ // FormatCheckerChain holds the formatters
+ FormatCheckerChain struct {
+ formatters map[string]FormatChecker
+ }
+
+ // EmailFormatter verifies email address formats
+ EmailFormatChecker struct{}
+
+ // IPV4FormatChecker verifies IP addresses in the ipv4 format
+ IPV4FormatChecker struct{}
+
+ // IPV6FormatChecker verifies IP addresses in the ipv6 format
+ IPV6FormatChecker struct{}
+
+ // DateTimeFormatChecker verifies date/time formats per RFC3339 5.6
+ //
+ // Valid formats:
+ // Partial Time: HH:MM:SS
+ // Full Date: YYYY-MM-DD
+ // Full Time: HH:MM:SSZ-07:00
+ // Date Time: YYYY-MM-DDTHH:MM:SSZ-0700
+ //
+ // Where
+ // YYYY = 4DIGIT year
+ // MM = 2DIGIT month ; 01-12
+ // DD = 2DIGIT day-month ; 01-28, 01-29, 01-30, 01-31 based on month/year
+ // HH = 2DIGIT hour ; 00-23
+ // MM = 2DIGIT ; 00-59
+ // SS = 2DIGIT ; 00-58, 00-60 based on leap second rules
+ // T = Literal
+ // Z = Literal
+ //
+ // Note: Nanoseconds are also suported in all formats
+ //
+ // http://tools.ietf.org/html/rfc3339#section-5.6
+ DateTimeFormatChecker struct{}
+
+ // URIFormatCheckers validates a URI with a valid Scheme per RFC3986
+ URIFormatChecker struct{}
+
+ // HostnameFormatChecker validates a hostname is in the correct format
+ HostnameFormatChecker struct{}
+
+ // UUIDFormatChecker validates a UUID is in the correct format
+ UUIDFormatChecker struct{}
+)
+
+var (
+ // Formatters holds the valid formatters, and is a public variable
+ // so library users can add custom formatters
+ FormatCheckers = FormatCheckerChain{
+ formatters: map[string]FormatChecker{
+ "date-time": DateTimeFormatChecker{},
+ "hostname": HostnameFormatChecker{},
+ "email": EmailFormatChecker{},
+ "ipv4": IPV4FormatChecker{},
+ "ipv6": IPV6FormatChecker{},
+ "uri": URIFormatChecker{},
+ "uuid": UUIDFormatChecker{},
+ },
+ }
+
+ // Regex credit: https://github.com/asaskevich/govalidator
+ rxEmail = regexp.MustCompile("^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$")
+
+ // Regex credit: https://www.socketloop.com/tutorials/golang-validate-hostname
+ rxHostname = regexp.MustCompile(`^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$`)
+
+ rxUUID = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$")
+)
+
+// Add adds a FormatChecker to the FormatCheckerChain
+// The name used will be the value used for the format key in your json schema
+func (c *FormatCheckerChain) Add(name string, f FormatChecker) *FormatCheckerChain {
+ c.formatters[name] = f
+
+ return c
+}
+
+// Remove deletes a FormatChecker from the FormatCheckerChain (if it exists)
+func (c *FormatCheckerChain) Remove(name string) *FormatCheckerChain {
+ delete(c.formatters, name)
+
+ return c
+}
+
+// Has checks to see if the FormatCheckerChain holds a FormatChecker with the given name
+func (c *FormatCheckerChain) Has(name string) bool {
+ _, ok := c.formatters[name]
+
+ return ok
+}
+
+// IsFormat will check an input against a FormatChecker with the given name
+// to see if it is the correct format
+func (c *FormatCheckerChain) IsFormat(name string, input interface{}) bool {
+ f, ok := c.formatters[name]
+
+ if !ok {
+ return false
+ }
+
+ if !isKind(input, reflect.String) {
+ return false
+ }
+
+ inputString := input.(string)
+
+ return f.IsFormat(inputString)
+}
+
+func (f EmailFormatChecker) IsFormat(input string) bool {
+ return rxEmail.MatchString(input)
+}
+
+// Credit: https://github.com/asaskevich/govalidator
+func (f IPV4FormatChecker) IsFormat(input string) bool {
+ ip := net.ParseIP(input)
+ return ip != nil && strings.Contains(input, ".")
+}
+
+// Credit: https://github.com/asaskevich/govalidator
+func (f IPV6FormatChecker) IsFormat(input string) bool {
+ ip := net.ParseIP(input)
+ return ip != nil && strings.Contains(input, ":")
+}
+
+func (f DateTimeFormatChecker) IsFormat(input string) bool {
+ formats := []string{
+ "15:04:05",
+ "15:04:05Z07:00",
+ "2006-01-02",
+ time.RFC3339,
+ time.RFC3339Nano,
+ }
+
+ for _, format := range formats {
+ if _, err := time.Parse(format, input); err == nil {
+ return true
+ }
+ }
+
+ return false
+}
+
+func (f URIFormatChecker) IsFormat(input string) bool {
+ u, err := url.Parse(input)
+ if err != nil || u.Scheme == "" {
+ return false
+ }
+
+ return true
+}
+
+func (f HostnameFormatChecker) IsFormat(input string) bool {
+ return rxHostname.MatchString(input) && len(input) < 256
+}
+
+func (f UUIDFormatChecker) IsFormat(input string) bool {
+ return rxUUID.MatchString(input)
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/internalLog.go b/vendor/github.com/xeipuuv/gojsonschema/internalLog.go
new file mode 100644
index 0000000..4ef7a8d
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/internalLog.go
@@ -0,0 +1,37 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Very simple log wrapper.
+// Used for debugging/testing purposes.
+//
+// created 01-01-2015
+
+package gojsonschema
+
+import (
+ "log"
+)
+
+const internalLogEnabled = false
+
+func internalLog(format string, v ...interface{}) {
+ log.Printf(format, v...)
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/jsonContext.go b/vendor/github.com/xeipuuv/gojsonschema/jsonContext.go
new file mode 100644
index 0000000..fcc8d9d
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/jsonContext.go
@@ -0,0 +1,72 @@
+// Copyright 2013 MongoDB, Inc.
+//
+// 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.
+
+// author tolsen
+// author-github https://github.com/tolsen
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Implements a persistent (immutable w/ shared structure) singly-linked list of strings for the purpose of storing a json context
+//
+// created 04-09-2013
+
+package gojsonschema
+
+import "bytes"
+
+// jsonContext implements a persistent linked-list of strings
+type jsonContext struct {
+ head string
+ tail *jsonContext
+}
+
+func newJsonContext(head string, tail *jsonContext) *jsonContext {
+ return &jsonContext{head, tail}
+}
+
+// String displays the context in reverse.
+// This plays well with the data structure's persistent nature with
+// Cons and a json document's tree structure.
+func (c *jsonContext) String(del ...string) string {
+ byteArr := make([]byte, 0, c.stringLen())
+ buf := bytes.NewBuffer(byteArr)
+ c.writeStringToBuffer(buf, del)
+
+ return buf.String()
+}
+
+func (c *jsonContext) stringLen() int {
+ length := 0
+ if c.tail != nil {
+ length = c.tail.stringLen() + 1 // add 1 for "."
+ }
+
+ length += len(c.head)
+ return length
+}
+
+func (c *jsonContext) writeStringToBuffer(buf *bytes.Buffer, del []string) {
+ if c.tail != nil {
+ c.tail.writeStringToBuffer(buf, del)
+
+ if len(del) > 0 {
+ buf.WriteString(del[0])
+ } else {
+ buf.WriteString(".")
+ }
+ }
+
+ buf.WriteString(c.head)
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go b/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go
new file mode 100644
index 0000000..a9458a8
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/jsonLoader.go
@@ -0,0 +1,286 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Different strategies to load JSON files.
+// Includes References (file and HTTP), JSON strings and Go types.
+//
+// created 01-02-2015
+
+package gojsonschema
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "io"
+ "io/ioutil"
+ "net/http"
+ "path/filepath"
+ "runtime"
+ "strings"
+
+ "github.com/xeipuuv/gojsonreference"
+)
+
+// JSON loader interface
+
+type JSONLoader interface {
+ jsonSource() interface{}
+ loadJSON() (interface{}, error)
+ loadSchema() (*Schema, error)
+}
+
+// JSON Reference loader
+// references are used to load JSONs from files and HTTP
+
+type jsonReferenceLoader struct {
+ source string
+}
+
+func (l *jsonReferenceLoader) jsonSource() interface{} {
+ return l.source
+}
+
+func NewReferenceLoader(source string) *jsonReferenceLoader {
+ return &jsonReferenceLoader{source: source}
+}
+
+func (l *jsonReferenceLoader) loadJSON() (interface{}, error) {
+
+ var err error
+
+ reference, err := gojsonreference.NewJsonReference(l.jsonSource().(string))
+ if err != nil {
+ return nil, err
+ }
+
+ refToUrl := reference
+ refToUrl.GetUrl().Fragment = ""
+
+ var document interface{}
+
+ if reference.HasFileScheme {
+
+ filename := strings.Replace(refToUrl.String(), "file://", "", -1)
+ if runtime.GOOS == "windows" {
+ // on Windows, a file URL may have an extra leading slash, use slashes
+ // instead of backslashes, and have spaces escaped
+ if strings.HasPrefix(filename, "/") {
+ filename = filename[1:]
+ }
+ filename = filepath.FromSlash(filename)
+ filename = strings.Replace(filename, "%20", " ", -1)
+ }
+
+ document, err = l.loadFromFile(filename)
+ if err != nil {
+ return nil, err
+ }
+
+ } else {
+
+ document, err = l.loadFromHTTP(refToUrl.String())
+ if err != nil {
+ return nil, err
+ }
+
+ }
+
+ return document, nil
+
+}
+
+func (l *jsonReferenceLoader) loadSchema() (*Schema, error) {
+
+ var err error
+
+ d := Schema{}
+ d.pool = newSchemaPool()
+ d.referencePool = newSchemaReferencePool()
+
+ d.documentReference, err = gojsonreference.NewJsonReference(l.jsonSource().(string))
+ if err != nil {
+ return nil, err
+ }
+
+ spd, err := d.pool.GetDocument(d.documentReference)
+ if err != nil {
+ return nil, err
+ }
+
+ err = d.parse(spd.Document)
+ if err != nil {
+ return nil, err
+ }
+
+ return &d, nil
+
+}
+
+func (l *jsonReferenceLoader) loadFromHTTP(address string) (interface{}, error) {
+
+ resp, err := http.Get(address)
+ if err != nil {
+ return nil, err
+ }
+
+ // must return HTTP Status 200 OK
+ if resp.StatusCode != http.StatusOK {
+ return nil, errors.New(formatErrorDescription(Locale.httpBadStatus(), ErrorDetails{"status": resp.Status}))
+ }
+
+ bodyBuff, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ return decodeJsonUsingNumber(bytes.NewReader(bodyBuff))
+
+}
+
+func (l *jsonReferenceLoader) loadFromFile(path string) (interface{}, error) {
+
+ bodyBuff, err := ioutil.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+
+ return decodeJsonUsingNumber(bytes.NewReader(bodyBuff))
+
+}
+
+// JSON string loader
+
+type jsonStringLoader struct {
+ source string
+}
+
+func (l *jsonStringLoader) jsonSource() interface{} {
+ return l.source
+}
+
+func NewStringLoader(source string) *jsonStringLoader {
+ return &jsonStringLoader{source: source}
+}
+
+func (l *jsonStringLoader) loadJSON() (interface{}, error) {
+
+ return decodeJsonUsingNumber(strings.NewReader(l.jsonSource().(string)))
+
+}
+
+func (l *jsonStringLoader) loadSchema() (*Schema, error) {
+
+ var err error
+
+ document, err := l.loadJSON()
+ if err != nil {
+ return nil, err
+ }
+
+ d := Schema{}
+ d.pool = newSchemaPool()
+ d.referencePool = newSchemaReferencePool()
+ d.documentReference, err = gojsonreference.NewJsonReference("#")
+ d.pool.SetStandaloneDocument(document)
+ if err != nil {
+ return nil, err
+ }
+
+ err = d.parse(document)
+ if err != nil {
+ return nil, err
+ }
+
+ return &d, nil
+
+}
+
+// JSON Go (types) loader
+// used to load JSONs from the code as maps, interface{}, structs ...
+
+type jsonGoLoader struct {
+ source interface{}
+}
+
+func (l *jsonGoLoader) jsonSource() interface{} {
+ return l.source
+}
+
+func NewGoLoader(source interface{}) *jsonGoLoader {
+ return &jsonGoLoader{source: source}
+}
+
+func (l *jsonGoLoader) loadJSON() (interface{}, error) {
+
+ // convert it to a compliant JSON first to avoid types "mismatches"
+
+ jsonBytes, err := json.Marshal(l.jsonSource())
+ if err != nil {
+ return nil, err
+ }
+
+ return decodeJsonUsingNumber(bytes.NewReader(jsonBytes))
+
+}
+
+func (l *jsonGoLoader) loadSchema() (*Schema, error) {
+
+ var err error
+
+ document, err := l.loadJSON()
+ if err != nil {
+ return nil, err
+ }
+
+ d := Schema{}
+ d.pool = newSchemaPool()
+ d.referencePool = newSchemaReferencePool()
+ d.documentReference, err = gojsonreference.NewJsonReference("#")
+ d.pool.SetStandaloneDocument(document)
+ if err != nil {
+ return nil, err
+ }
+
+ err = d.parse(document)
+ if err != nil {
+ return nil, err
+ }
+
+ return &d, nil
+
+}
+
+func decodeJsonUsingNumber(r io.Reader) (interface{}, error) {
+
+ var document interface{}
+
+ decoder := json.NewDecoder(r)
+ decoder.UseNumber()
+
+ err := decoder.Decode(&document)
+ if err != nil {
+ return nil, err
+ }
+
+ return document, nil
+
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/locales.go b/vendor/github.com/xeipuuv/gojsonschema/locales.go
new file mode 100644
index 0000000..de05d60
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/locales.go
@@ -0,0 +1,275 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Contains const string and messages.
+//
+// created 01-01-2015
+
+package gojsonschema
+
+type (
+ // locale is an interface for definining custom error strings
+ locale interface {
+ Required() string
+ InvalidType() string
+ NumberAnyOf() string
+ NumberOneOf() string
+ NumberAllOf() string
+ NumberNot() string
+ MissingDependency() string
+ Internal() string
+ Enum() string
+ ArrayNoAdditionalItems() string
+ ArrayMinItems() string
+ ArrayMaxItems() string
+ Unique() string
+ ArrayMinProperties() string
+ ArrayMaxProperties() string
+ AdditionalPropertyNotAllowed() string
+ InvalidPropertyPattern() string
+ StringGTE() string
+ StringLTE() string
+ DoesNotMatchPattern() string
+ DoesNotMatchFormat() string
+ MultipleOf() string
+ NumberGTE() string
+ NumberGT() string
+ NumberLTE() string
+ NumberLT() string
+
+ // Schema validations
+ RegexPattern() string
+ GreaterThanZero() string
+ MustBeOfA() string
+ MustBeOfAn() string
+ CannotBeUsedWithout() string
+ CannotBeGT() string
+ MustBeOfType() string
+ MustBeValidRegex() string
+ MustBeValidFormat() string
+ MustBeGTEZero() string
+ KeyCannotBeGreaterThan() string
+ KeyItemsMustBeOfType() string
+ KeyItemsMustBeUnique() string
+ ReferenceMustBeCanonical() string
+ NotAValidType() string
+ Duplicated() string
+ httpBadStatus() string
+
+ // ErrorFormat
+ ErrorFormat() string
+ }
+
+ // DefaultLocale is the default locale for this package
+ DefaultLocale struct{}
+)
+
+func (l DefaultLocale) Required() string {
+ return `%property% is required`
+}
+
+func (l DefaultLocale) InvalidType() string {
+ return `Invalid type. Expected: %expected%, given: %given%`
+}
+
+func (l DefaultLocale) NumberAnyOf() string {
+ return `Must validate at least one schema (anyOf)`
+}
+
+func (l DefaultLocale) NumberOneOf() string {
+ return `Must validate one and only one schema (oneOf)`
+}
+
+func (l DefaultLocale) NumberAllOf() string {
+ return `Must validate all the schemas (allOf)`
+}
+
+func (l DefaultLocale) NumberNot() string {
+ return `Must not validate the schema (not)`
+}
+
+func (l DefaultLocale) MissingDependency() string {
+ return `Has a dependency on %dependency%`
+}
+
+func (l DefaultLocale) Internal() string {
+ return `Internal Error %error%`
+}
+
+func (l DefaultLocale) Enum() string {
+ return `%field% must be one of the following: %allowed%`
+}
+
+func (l DefaultLocale) ArrayNoAdditionalItems() string {
+ return `No additional items allowed on array`
+}
+
+func (l DefaultLocale) ArrayMinItems() string {
+ return `Array must have at least %min% items`
+}
+
+func (l DefaultLocale) ArrayMaxItems() string {
+ return `Array must have at most %max% items`
+}
+
+func (l DefaultLocale) Unique() string {
+ return `%type% items must be unique`
+}
+
+func (l DefaultLocale) ArrayMinProperties() string {
+ return `Must have at least %min% properties`
+}
+
+func (l DefaultLocale) ArrayMaxProperties() string {
+ return `Must have at most %max% properties`
+}
+
+func (l DefaultLocale) AdditionalPropertyNotAllowed() string {
+ return `Additional property %property% is not allowed`
+}
+
+func (l DefaultLocale) InvalidPropertyPattern() string {
+ return `Property "%property%" does not match pattern %pattern%`
+}
+
+func (l DefaultLocale) StringGTE() string {
+ return `String length must be greater than or equal to %min%`
+}
+
+func (l DefaultLocale) StringLTE() string {
+ return `String length must be less than or equal to %max%`
+}
+
+func (l DefaultLocale) DoesNotMatchPattern() string {
+ return `Does not match pattern '%pattern%'`
+}
+
+func (l DefaultLocale) DoesNotMatchFormat() string {
+ return `Does not match format '%format%'`
+}
+
+func (l DefaultLocale) MultipleOf() string {
+ return `Must be a multiple of %multiple%`
+}
+
+func (l DefaultLocale) NumberGTE() string {
+ return `Must be greater than or equal to %min%`
+}
+
+func (l DefaultLocale) NumberGT() string {
+ return `Must be greater than %min%`
+}
+
+func (l DefaultLocale) NumberLTE() string {
+ return `Must be less than or equal to %max%`
+}
+
+func (l DefaultLocale) NumberLT() string {
+ return `Must be less than %max%`
+}
+
+// Schema validators
+func (l DefaultLocale) RegexPattern() string {
+ return `Invalid regex pattern '%pattern%'`
+}
+
+func (l DefaultLocale) GreaterThanZero() string {
+ return `%number% must be strictly greater than 0`
+}
+
+func (l DefaultLocale) MustBeOfA() string {
+ return `%x% must be of a %y%`
+}
+
+func (l DefaultLocale) MustBeOfAn() string {
+ return `%x% must be of an %y%`
+}
+
+func (l DefaultLocale) CannotBeUsedWithout() string {
+ return `%x% cannot be used without %y%`
+}
+
+func (l DefaultLocale) CannotBeGT() string {
+ return `%x% cannot be greater than %y%`
+}
+
+func (l DefaultLocale) MustBeOfType() string {
+ return `%key% must be of type %type%`
+}
+
+func (l DefaultLocale) MustBeValidRegex() string {
+ return `%key% must be a valid regex`
+}
+
+func (l DefaultLocale) MustBeValidFormat() string {
+ return `%key% must be a valid format %given%`
+}
+
+func (l DefaultLocale) MustBeGTEZero() string {
+ return `%key% must be greater than or equal to 0`
+}
+
+func (l DefaultLocale) KeyCannotBeGreaterThan() string {
+ return `%key% cannot be greater than %y%`
+}
+
+func (l DefaultLocale) KeyItemsMustBeOfType() string {
+ return `%key% items must be %type%`
+}
+
+func (l DefaultLocale) KeyItemsMustBeUnique() string {
+ return `%key% items must be unique`
+}
+
+func (l DefaultLocale) ReferenceMustBeCanonical() string {
+ return `Reference %reference% must be canonical`
+}
+
+func (l DefaultLocale) NotAValidType() string {
+ return `%type% is not a valid type -- `
+}
+
+func (l DefaultLocale) Duplicated() string {
+ return `%type% type is duplicated`
+}
+
+func (l DefaultLocale) httpBadStatus() string {
+ return `Could not read schema from HTTP, response status is %status%`
+}
+
+// Replacement options: field, description, context, value
+func (l DefaultLocale) ErrorFormat() string {
+ return `%field%: %description%`
+}
+
+const (
+ STRING_NUMBER = "number"
+ STRING_ARRAY_OF_STRINGS = "array of strings"
+ STRING_ARRAY_OF_SCHEMAS = "array of schemas"
+ STRING_SCHEMA = "schema"
+ STRING_SCHEMA_OR_ARRAY_OF_STRINGS = "schema or array of strings"
+ STRING_PROPERTIES = "properties"
+ STRING_DEPENDENCY = "dependency"
+ STRING_PROPERTY = "property"
+ STRING_UNDEFINED = "undefined"
+ STRING_CONTEXT_ROOT = "(root)"
+ STRING_ROOT_SCHEMA_PROPERTY = "(root)"
+)
diff --git a/vendor/github.com/xeipuuv/gojsonschema/result.go b/vendor/github.com/xeipuuv/gojsonschema/result.go
new file mode 100644
index 0000000..c6d3375
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/result.go
@@ -0,0 +1,171 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Result and ResultError implementations.
+//
+// created 01-01-2015
+
+package gojsonschema
+
+import (
+ "fmt"
+ "strings"
+)
+
+type (
+ // ErrorDetails is a map of details specific to each error.
+ // While the values will vary, every error will contain a "field" value
+ ErrorDetails map[string]interface{}
+
+ // ResultError is the interface that library errors must implement
+ ResultError interface {
+ Field() string
+ SetType(string)
+ Type() string
+ SetContext(*jsonContext)
+ Context() *jsonContext
+ SetDescription(string)
+ Description() string
+ SetValue(interface{})
+ Value() interface{}
+ SetDetails(ErrorDetails)
+ Details() ErrorDetails
+ }
+
+ // ResultErrorFields holds the fields for each ResultError implementation.
+ // ResultErrorFields implements the ResultError interface, so custom errors
+ // can be defined by just embedding this type
+ ResultErrorFields struct {
+ errorType string // A string with the type of error (i.e. invalid_type)
+ context *jsonContext // Tree like notation of the part that failed the validation. ex (root).a.b ...
+ description string // A human readable error message
+ value interface{} // Value given by the JSON file that is the source of the error
+ details ErrorDetails
+ }
+
+ Result struct {
+ errors []ResultError
+ // Scores how well the validation matched. Useful in generating
+ // better error messages for anyOf and oneOf.
+ score int
+ }
+)
+
+// Field outputs the field name without the root context
+// i.e. firstName or person.firstName instead of (root).firstName or (root).person.firstName
+func (v *ResultErrorFields) Field() string {
+ if p, ok := v.Details()["property"]; ok {
+ if str, isString := p.(string); isString {
+ return str
+ }
+ }
+
+ return strings.TrimPrefix(v.context.String(), STRING_ROOT_SCHEMA_PROPERTY+".")
+}
+
+func (v *ResultErrorFields) SetType(errorType string) {
+ v.errorType = errorType
+}
+
+func (v *ResultErrorFields) Type() string {
+ return v.errorType
+}
+
+func (v *ResultErrorFields) SetContext(context *jsonContext) {
+ v.context = context
+}
+
+func (v *ResultErrorFields) Context() *jsonContext {
+ return v.context
+}
+
+func (v *ResultErrorFields) SetDescription(description string) {
+ v.description = description
+}
+
+func (v *ResultErrorFields) Description() string {
+ return v.description
+}
+
+func (v *ResultErrorFields) SetValue(value interface{}) {
+ v.value = value
+}
+
+func (v *ResultErrorFields) Value() interface{} {
+ return v.value
+}
+
+func (v *ResultErrorFields) SetDetails(details ErrorDetails) {
+ v.details = details
+}
+
+func (v *ResultErrorFields) Details() ErrorDetails {
+ return v.details
+}
+
+func (v ResultErrorFields) String() string {
+ // as a fallback, the value is displayed go style
+ valueString := fmt.Sprintf("%v", v.value)
+
+ // marshal the go value value to json
+ if v.value == nil {
+ valueString = TYPE_NULL
+ } else {
+ if vs, err := marshalToJsonString(v.value); err == nil {
+ if vs == nil {
+ valueString = TYPE_NULL
+ } else {
+ valueString = *vs
+ }
+ }
+ }
+
+ return formatErrorDescription(Locale.ErrorFormat(), ErrorDetails{
+ "context": v.context.String(),
+ "description": v.description,
+ "value": valueString,
+ "field": v.Field(),
+ })
+}
+
+func (v *Result) Valid() bool {
+ return len(v.errors) == 0
+}
+
+func (v *Result) Errors() []ResultError {
+ return v.errors
+}
+
+func (v *Result) addError(err ResultError, context *jsonContext, value interface{}, details ErrorDetails) {
+ newError(err, context, value, Locale, details)
+ v.errors = append(v.errors, err)
+ v.score -= 2 // results in a net -1 when added to the +1 we get at the end of the validation function
+}
+
+// Used to copy errors from a sub-schema to the main one
+func (v *Result) mergeErrors(otherResult *Result) {
+ v.errors = append(v.errors, otherResult.Errors()...)
+ v.score += otherResult.score
+}
+
+func (v *Result) incrementScore() {
+ v.score++
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/schema.go b/vendor/github.com/xeipuuv/gojsonschema/schema.go
new file mode 100644
index 0000000..577c786
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/schema.go
@@ -0,0 +1,908 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Defines Schema, the main entry to every subSchema.
+// Contains the parsing logic and error checking.
+//
+// created 26-02-2013
+
+package gojsonschema
+
+import (
+ // "encoding/json"
+ "errors"
+ "reflect"
+ "regexp"
+
+ "github.com/xeipuuv/gojsonreference"
+)
+
+var (
+ // Locale is the default locale to use
+ // Library users can overwrite with their own implementation
+ Locale locale = DefaultLocale{}
+)
+
+func NewSchema(l JSONLoader) (*Schema, error) {
+ return l.loadSchema()
+}
+
+type Schema struct {
+ documentReference gojsonreference.JsonReference
+ rootSchema *subSchema
+ pool *schemaPool
+ referencePool *schemaReferencePool
+}
+
+func (d *Schema) parse(document interface{}) error {
+ d.rootSchema = &subSchema{property: STRING_ROOT_SCHEMA_PROPERTY}
+ return d.parseSchema(document, d.rootSchema)
+}
+
+func (d *Schema) SetRootSchemaName(name string) {
+ d.rootSchema.property = name
+}
+
+// Parses a subSchema
+//
+// Pretty long function ( sorry :) )... but pretty straight forward, repetitive and boring
+// Not much magic involved here, most of the job is to validate the key names and their values,
+// then the values are copied into subSchema struct
+//
+func (d *Schema) parseSchema(documentNode interface{}, currentSchema *subSchema) error {
+
+ if !isKind(documentNode, reflect.Map) {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": TYPE_OBJECT,
+ "given": STRING_SCHEMA,
+ },
+ ))
+ }
+
+ m := documentNode.(map[string]interface{})
+
+ if currentSchema == d.rootSchema {
+ currentSchema.ref = &d.documentReference
+ }
+
+ // $subSchema
+ if existsMapKey(m, KEY_SCHEMA) {
+ if !isKind(m[KEY_SCHEMA], reflect.String) {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": TYPE_STRING,
+ "given": KEY_SCHEMA,
+ },
+ ))
+ }
+ schemaRef := m[KEY_SCHEMA].(string)
+ schemaReference, err := gojsonreference.NewJsonReference(schemaRef)
+ currentSchema.subSchema = &schemaReference
+ if err != nil {
+ return err
+ }
+ }
+
+ // $ref
+ if existsMapKey(m, KEY_REF) && !isKind(m[KEY_REF], reflect.String) {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": TYPE_STRING,
+ "given": KEY_REF,
+ },
+ ))
+ }
+ if k, ok := m[KEY_REF].(string); ok {
+
+ if sch, ok := d.referencePool.Get(currentSchema.ref.String() + k); ok {
+
+ currentSchema.refSchema = sch
+
+ } else {
+
+ var err error
+ err = d.parseReference(documentNode, currentSchema, k)
+ if err != nil {
+ return err
+ }
+
+ return nil
+ }
+ }
+
+ // definitions
+ if existsMapKey(m, KEY_DEFINITIONS) {
+ if isKind(m[KEY_DEFINITIONS], reflect.Map) {
+ currentSchema.definitions = make(map[string]*subSchema)
+ for dk, dv := range m[KEY_DEFINITIONS].(map[string]interface{}) {
+ if isKind(dv, reflect.Map) {
+ newSchema := &subSchema{property: KEY_DEFINITIONS, parent: currentSchema, ref: currentSchema.ref}
+ currentSchema.definitions[dk] = newSchema
+ err := d.parseSchema(dv, newSchema)
+ if err != nil {
+ return errors.New(err.Error())
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": STRING_ARRAY_OF_SCHEMAS,
+ "given": KEY_DEFINITIONS,
+ },
+ ))
+ }
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": STRING_ARRAY_OF_SCHEMAS,
+ "given": KEY_DEFINITIONS,
+ },
+ ))
+ }
+
+ }
+
+ // id
+ if existsMapKey(m, KEY_ID) && !isKind(m[KEY_ID], reflect.String) {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": TYPE_STRING,
+ "given": KEY_ID,
+ },
+ ))
+ }
+ if k, ok := m[KEY_ID].(string); ok {
+ currentSchema.id = &k
+ }
+
+ // title
+ if existsMapKey(m, KEY_TITLE) && !isKind(m[KEY_TITLE], reflect.String) {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": TYPE_STRING,
+ "given": KEY_TITLE,
+ },
+ ))
+ }
+ if k, ok := m[KEY_TITLE].(string); ok {
+ currentSchema.title = &k
+ }
+
+ // description
+ if existsMapKey(m, KEY_DESCRIPTION) && !isKind(m[KEY_DESCRIPTION], reflect.String) {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": TYPE_STRING,
+ "given": KEY_DESCRIPTION,
+ },
+ ))
+ }
+ if k, ok := m[KEY_DESCRIPTION].(string); ok {
+ currentSchema.description = &k
+ }
+
+ // type
+ if existsMapKey(m, KEY_TYPE) {
+ if isKind(m[KEY_TYPE], reflect.String) {
+ if k, ok := m[KEY_TYPE].(string); ok {
+ err := currentSchema.types.Add(k)
+ if err != nil {
+ return err
+ }
+ }
+ } else {
+ if isKind(m[KEY_TYPE], reflect.Slice) {
+ arrayOfTypes := m[KEY_TYPE].([]interface{})
+ for _, typeInArray := range arrayOfTypes {
+ if reflect.ValueOf(typeInArray).Kind() != reflect.String {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": TYPE_STRING + "/" + STRING_ARRAY_OF_STRINGS,
+ "given": KEY_TYPE,
+ },
+ ))
+ } else {
+ currentSchema.types.Add(typeInArray.(string))
+ }
+ }
+
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": TYPE_STRING + "/" + STRING_ARRAY_OF_STRINGS,
+ "given": KEY_TYPE,
+ },
+ ))
+ }
+ }
+ }
+
+ // properties
+ if existsMapKey(m, KEY_PROPERTIES) {
+ err := d.parseProperties(m[KEY_PROPERTIES], currentSchema)
+ if err != nil {
+ return err
+ }
+ }
+
+ // additionalProperties
+ if existsMapKey(m, KEY_ADDITIONAL_PROPERTIES) {
+ if isKind(m[KEY_ADDITIONAL_PROPERTIES], reflect.Bool) {
+ currentSchema.additionalProperties = m[KEY_ADDITIONAL_PROPERTIES].(bool)
+ } else if isKind(m[KEY_ADDITIONAL_PROPERTIES], reflect.Map) {
+ newSchema := &subSchema{property: KEY_ADDITIONAL_PROPERTIES, parent: currentSchema, ref: currentSchema.ref}
+ currentSchema.additionalProperties = newSchema
+ err := d.parseSchema(m[KEY_ADDITIONAL_PROPERTIES], newSchema)
+ if err != nil {
+ return errors.New(err.Error())
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": TYPE_BOOLEAN + "/" + STRING_SCHEMA,
+ "given": KEY_ADDITIONAL_PROPERTIES,
+ },
+ ))
+ }
+ }
+
+ // patternProperties
+ if existsMapKey(m, KEY_PATTERN_PROPERTIES) {
+ if isKind(m[KEY_PATTERN_PROPERTIES], reflect.Map) {
+ patternPropertiesMap := m[KEY_PATTERN_PROPERTIES].(map[string]interface{})
+ if len(patternPropertiesMap) > 0 {
+ currentSchema.patternProperties = make(map[string]*subSchema)
+ for k, v := range patternPropertiesMap {
+ _, err := regexp.MatchString(k, "")
+ if err != nil {
+ return errors.New(formatErrorDescription(
+ Locale.RegexPattern(),
+ ErrorDetails{"pattern": k},
+ ))
+ }
+ newSchema := &subSchema{property: k, parent: currentSchema, ref: currentSchema.ref}
+ err = d.parseSchema(v, newSchema)
+ if err != nil {
+ return errors.New(err.Error())
+ }
+ currentSchema.patternProperties[k] = newSchema
+ }
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": STRING_SCHEMA,
+ "given": KEY_PATTERN_PROPERTIES,
+ },
+ ))
+ }
+ }
+
+ // dependencies
+ if existsMapKey(m, KEY_DEPENDENCIES) {
+ err := d.parseDependencies(m[KEY_DEPENDENCIES], currentSchema)
+ if err != nil {
+ return err
+ }
+ }
+
+ // items
+ if existsMapKey(m, KEY_ITEMS) {
+ if isKind(m[KEY_ITEMS], reflect.Slice) {
+ for _, itemElement := range m[KEY_ITEMS].([]interface{}) {
+ if isKind(itemElement, reflect.Map) {
+ newSchema := &subSchema{parent: currentSchema, property: KEY_ITEMS}
+ newSchema.ref = currentSchema.ref
+ currentSchema.AddItemsChild(newSchema)
+ err := d.parseSchema(itemElement, newSchema)
+ if err != nil {
+ return err
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": STRING_SCHEMA + "/" + STRING_ARRAY_OF_SCHEMAS,
+ "given": KEY_ITEMS,
+ },
+ ))
+ }
+ currentSchema.itemsChildrenIsSingleSchema = false
+ }
+ } else if isKind(m[KEY_ITEMS], reflect.Map) {
+ newSchema := &subSchema{parent: currentSchema, property: KEY_ITEMS}
+ newSchema.ref = currentSchema.ref
+ currentSchema.AddItemsChild(newSchema)
+ err := d.parseSchema(m[KEY_ITEMS], newSchema)
+ if err != nil {
+ return err
+ }
+ currentSchema.itemsChildrenIsSingleSchema = true
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": STRING_SCHEMA + "/" + STRING_ARRAY_OF_SCHEMAS,
+ "given": KEY_ITEMS,
+ },
+ ))
+ }
+ }
+
+ // additionalItems
+ if existsMapKey(m, KEY_ADDITIONAL_ITEMS) {
+ if isKind(m[KEY_ADDITIONAL_ITEMS], reflect.Bool) {
+ currentSchema.additionalItems = m[KEY_ADDITIONAL_ITEMS].(bool)
+ } else if isKind(m[KEY_ADDITIONAL_ITEMS], reflect.Map) {
+ newSchema := &subSchema{property: KEY_ADDITIONAL_ITEMS, parent: currentSchema, ref: currentSchema.ref}
+ currentSchema.additionalItems = newSchema
+ err := d.parseSchema(m[KEY_ADDITIONAL_ITEMS], newSchema)
+ if err != nil {
+ return errors.New(err.Error())
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": TYPE_BOOLEAN + "/" + STRING_SCHEMA,
+ "given": KEY_ADDITIONAL_ITEMS,
+ },
+ ))
+ }
+ }
+
+ // validation : number / integer
+
+ if existsMapKey(m, KEY_MULTIPLE_OF) {
+ multipleOfValue := mustBeNumber(m[KEY_MULTIPLE_OF])
+ if multipleOfValue == nil {
+ return errors.New(formatErrorDescription(
+ Locale.InvalidType(),
+ ErrorDetails{
+ "expected": STRING_NUMBER,
+ "given": KEY_MULTIPLE_OF,
+ },
+ ))
+ }
+ if *multipleOfValue <= 0 {
+ return errors.New(formatErrorDescription(
+ Locale.GreaterThanZero(),
+ ErrorDetails{"number": KEY_MULTIPLE_OF},
+ ))
+ }
+ currentSchema.multipleOf = multipleOfValue
+ }
+
+ if existsMapKey(m, KEY_MINIMUM) {
+ minimumValue := mustBeNumber(m[KEY_MINIMUM])
+ if minimumValue == nil {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfA(),
+ ErrorDetails{"x": KEY_MINIMUM, "y": STRING_NUMBER},
+ ))
+ }
+ currentSchema.minimum = minimumValue
+ }
+
+ if existsMapKey(m, KEY_EXCLUSIVE_MINIMUM) {
+ if isKind(m[KEY_EXCLUSIVE_MINIMUM], reflect.Bool) {
+ if currentSchema.minimum == nil {
+ return errors.New(formatErrorDescription(
+ Locale.CannotBeUsedWithout(),
+ ErrorDetails{"x": KEY_EXCLUSIVE_MINIMUM, "y": KEY_MINIMUM},
+ ))
+ }
+ exclusiveMinimumValue := m[KEY_EXCLUSIVE_MINIMUM].(bool)
+ currentSchema.exclusiveMinimum = exclusiveMinimumValue
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfA(),
+ ErrorDetails{"x": KEY_EXCLUSIVE_MINIMUM, "y": TYPE_BOOLEAN},
+ ))
+ }
+ }
+
+ if existsMapKey(m, KEY_MAXIMUM) {
+ maximumValue := mustBeNumber(m[KEY_MAXIMUM])
+ if maximumValue == nil {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfA(),
+ ErrorDetails{"x": KEY_MAXIMUM, "y": STRING_NUMBER},
+ ))
+ }
+ currentSchema.maximum = maximumValue
+ }
+
+ if existsMapKey(m, KEY_EXCLUSIVE_MAXIMUM) {
+ if isKind(m[KEY_EXCLUSIVE_MAXIMUM], reflect.Bool) {
+ if currentSchema.maximum == nil {
+ return errors.New(formatErrorDescription(
+ Locale.CannotBeUsedWithout(),
+ ErrorDetails{"x": KEY_EXCLUSIVE_MAXIMUM, "y": KEY_MAXIMUM},
+ ))
+ }
+ exclusiveMaximumValue := m[KEY_EXCLUSIVE_MAXIMUM].(bool)
+ currentSchema.exclusiveMaximum = exclusiveMaximumValue
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfA(),
+ ErrorDetails{"x": KEY_EXCLUSIVE_MAXIMUM, "y": STRING_NUMBER},
+ ))
+ }
+ }
+
+ if currentSchema.minimum != nil && currentSchema.maximum != nil {
+ if *currentSchema.minimum > *currentSchema.maximum {
+ return errors.New(formatErrorDescription(
+ Locale.CannotBeGT(),
+ ErrorDetails{"x": KEY_MINIMUM, "y": KEY_MAXIMUM},
+ ))
+ }
+ }
+
+ // validation : string
+
+ if existsMapKey(m, KEY_MIN_LENGTH) {
+ minLengthIntegerValue := mustBeInteger(m[KEY_MIN_LENGTH])
+ if minLengthIntegerValue == nil {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_MIN_LENGTH, "y": TYPE_INTEGER},
+ ))
+ }
+ if *minLengthIntegerValue < 0 {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeGTEZero(),
+ ErrorDetails{"key": KEY_MIN_LENGTH},
+ ))
+ }
+ currentSchema.minLength = minLengthIntegerValue
+ }
+
+ if existsMapKey(m, KEY_MAX_LENGTH) {
+ maxLengthIntegerValue := mustBeInteger(m[KEY_MAX_LENGTH])
+ if maxLengthIntegerValue == nil {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_MAX_LENGTH, "y": TYPE_INTEGER},
+ ))
+ }
+ if *maxLengthIntegerValue < 0 {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeGTEZero(),
+ ErrorDetails{"key": KEY_MAX_LENGTH},
+ ))
+ }
+ currentSchema.maxLength = maxLengthIntegerValue
+ }
+
+ if currentSchema.minLength != nil && currentSchema.maxLength != nil {
+ if *currentSchema.minLength > *currentSchema.maxLength {
+ return errors.New(formatErrorDescription(
+ Locale.CannotBeGT(),
+ ErrorDetails{"x": KEY_MIN_LENGTH, "y": KEY_MAX_LENGTH},
+ ))
+ }
+ }
+
+ if existsMapKey(m, KEY_PATTERN) {
+ if isKind(m[KEY_PATTERN], reflect.String) {
+ regexpObject, err := regexp.Compile(m[KEY_PATTERN].(string))
+ if err != nil {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeValidRegex(),
+ ErrorDetails{"key": KEY_PATTERN},
+ ))
+ }
+ currentSchema.pattern = regexpObject
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfA(),
+ ErrorDetails{"x": KEY_PATTERN, "y": TYPE_STRING},
+ ))
+ }
+ }
+
+ if existsMapKey(m, KEY_FORMAT) {
+ formatString, ok := m[KEY_FORMAT].(string)
+ if ok && FormatCheckers.Has(formatString) {
+ currentSchema.format = formatString
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeValidFormat(),
+ ErrorDetails{"key": KEY_FORMAT, "given": m[KEY_FORMAT]},
+ ))
+ }
+ }
+
+ // validation : object
+
+ if existsMapKey(m, KEY_MIN_PROPERTIES) {
+ minPropertiesIntegerValue := mustBeInteger(m[KEY_MIN_PROPERTIES])
+ if minPropertiesIntegerValue == nil {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_MIN_PROPERTIES, "y": TYPE_INTEGER},
+ ))
+ }
+ if *minPropertiesIntegerValue < 0 {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeGTEZero(),
+ ErrorDetails{"key": KEY_MIN_PROPERTIES},
+ ))
+ }
+ currentSchema.minProperties = minPropertiesIntegerValue
+ }
+
+ if existsMapKey(m, KEY_MAX_PROPERTIES) {
+ maxPropertiesIntegerValue := mustBeInteger(m[KEY_MAX_PROPERTIES])
+ if maxPropertiesIntegerValue == nil {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_MAX_PROPERTIES, "y": TYPE_INTEGER},
+ ))
+ }
+ if *maxPropertiesIntegerValue < 0 {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeGTEZero(),
+ ErrorDetails{"key": KEY_MAX_PROPERTIES},
+ ))
+ }
+ currentSchema.maxProperties = maxPropertiesIntegerValue
+ }
+
+ if currentSchema.minProperties != nil && currentSchema.maxProperties != nil {
+ if *currentSchema.minProperties > *currentSchema.maxProperties {
+ return errors.New(formatErrorDescription(
+ Locale.KeyCannotBeGreaterThan(),
+ ErrorDetails{"key": KEY_MIN_PROPERTIES, "y": KEY_MAX_PROPERTIES},
+ ))
+ }
+ }
+
+ if existsMapKey(m, KEY_REQUIRED) {
+ if isKind(m[KEY_REQUIRED], reflect.Slice) {
+ requiredValues := m[KEY_REQUIRED].([]interface{})
+ for _, requiredValue := range requiredValues {
+ if isKind(requiredValue, reflect.String) {
+ err := currentSchema.AddRequired(requiredValue.(string))
+ if err != nil {
+ return err
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.KeyItemsMustBeOfType(),
+ ErrorDetails{"key": KEY_REQUIRED, "type": TYPE_STRING},
+ ))
+ }
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_REQUIRED, "y": TYPE_ARRAY},
+ ))
+ }
+ }
+
+ // validation : array
+
+ if existsMapKey(m, KEY_MIN_ITEMS) {
+ minItemsIntegerValue := mustBeInteger(m[KEY_MIN_ITEMS])
+ if minItemsIntegerValue == nil {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_MIN_ITEMS, "y": TYPE_INTEGER},
+ ))
+ }
+ if *minItemsIntegerValue < 0 {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeGTEZero(),
+ ErrorDetails{"key": KEY_MIN_ITEMS},
+ ))
+ }
+ currentSchema.minItems = minItemsIntegerValue
+ }
+
+ if existsMapKey(m, KEY_MAX_ITEMS) {
+ maxItemsIntegerValue := mustBeInteger(m[KEY_MAX_ITEMS])
+ if maxItemsIntegerValue == nil {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_MAX_ITEMS, "y": TYPE_INTEGER},
+ ))
+ }
+ if *maxItemsIntegerValue < 0 {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeGTEZero(),
+ ErrorDetails{"key": KEY_MAX_ITEMS},
+ ))
+ }
+ currentSchema.maxItems = maxItemsIntegerValue
+ }
+
+ if existsMapKey(m, KEY_UNIQUE_ITEMS) {
+ if isKind(m[KEY_UNIQUE_ITEMS], reflect.Bool) {
+ currentSchema.uniqueItems = m[KEY_UNIQUE_ITEMS].(bool)
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfA(),
+ ErrorDetails{"x": KEY_UNIQUE_ITEMS, "y": TYPE_BOOLEAN},
+ ))
+ }
+ }
+
+ // validation : all
+
+ if existsMapKey(m, KEY_ENUM) {
+ if isKind(m[KEY_ENUM], reflect.Slice) {
+ for _, v := range m[KEY_ENUM].([]interface{}) {
+ err := currentSchema.AddEnum(v)
+ if err != nil {
+ return err
+ }
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_ENUM, "y": TYPE_ARRAY},
+ ))
+ }
+ }
+
+ // validation : subSchema
+
+ if existsMapKey(m, KEY_ONE_OF) {
+ if isKind(m[KEY_ONE_OF], reflect.Slice) {
+ for _, v := range m[KEY_ONE_OF].([]interface{}) {
+ newSchema := &subSchema{property: KEY_ONE_OF, parent: currentSchema, ref: currentSchema.ref}
+ currentSchema.AddOneOf(newSchema)
+ err := d.parseSchema(v, newSchema)
+ if err != nil {
+ return err
+ }
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_ONE_OF, "y": TYPE_ARRAY},
+ ))
+ }
+ }
+
+ if existsMapKey(m, KEY_ANY_OF) {
+ if isKind(m[KEY_ANY_OF], reflect.Slice) {
+ for _, v := range m[KEY_ANY_OF].([]interface{}) {
+ newSchema := &subSchema{property: KEY_ANY_OF, parent: currentSchema, ref: currentSchema.ref}
+ currentSchema.AddAnyOf(newSchema)
+ err := d.parseSchema(v, newSchema)
+ if err != nil {
+ return err
+ }
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_ANY_OF, "y": TYPE_ARRAY},
+ ))
+ }
+ }
+
+ if existsMapKey(m, KEY_ALL_OF) {
+ if isKind(m[KEY_ALL_OF], reflect.Slice) {
+ for _, v := range m[KEY_ALL_OF].([]interface{}) {
+ newSchema := &subSchema{property: KEY_ALL_OF, parent: currentSchema, ref: currentSchema.ref}
+ currentSchema.AddAllOf(newSchema)
+ err := d.parseSchema(v, newSchema)
+ if err != nil {
+ return err
+ }
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_ANY_OF, "y": TYPE_ARRAY},
+ ))
+ }
+ }
+
+ if existsMapKey(m, KEY_NOT) {
+ if isKind(m[KEY_NOT], reflect.Map) {
+ newSchema := &subSchema{property: KEY_NOT, parent: currentSchema, ref: currentSchema.ref}
+ currentSchema.SetNot(newSchema)
+ err := d.parseSchema(m[KEY_NOT], newSchema)
+ if err != nil {
+ return err
+ }
+ } else {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfAn(),
+ ErrorDetails{"x": KEY_NOT, "y": TYPE_OBJECT},
+ ))
+ }
+ }
+
+ return nil
+}
+
+func (d *Schema) parseReference(documentNode interface{}, currentSchema *subSchema, reference string) (e error) {
+
+ var err error
+
+ jsonReference, err := gojsonreference.NewJsonReference(reference)
+ if err != nil {
+ return err
+ }
+
+ standaloneDocument := d.pool.GetStandaloneDocument()
+
+ if jsonReference.HasFullUrl {
+ currentSchema.ref = &jsonReference
+ } else {
+ inheritedReference, err := currentSchema.ref.Inherits(jsonReference)
+ if err != nil {
+ return err
+ }
+ currentSchema.ref = inheritedReference
+ }
+
+ jsonPointer := currentSchema.ref.GetPointer()
+
+ var refdDocumentNode interface{}
+
+ if standaloneDocument != nil {
+
+ var err error
+ refdDocumentNode, _, err = jsonPointer.Get(standaloneDocument)
+ if err != nil {
+ return err
+ }
+
+ } else {
+
+ var err error
+ dsp, err := d.pool.GetDocument(*currentSchema.ref)
+ if err != nil {
+ return err
+ }
+
+ refdDocumentNode, _, err = jsonPointer.Get(dsp.Document)
+ if err != nil {
+ return err
+ }
+
+ }
+
+ if !isKind(refdDocumentNode, reflect.Map) {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfType(),
+ ErrorDetails{"key": STRING_SCHEMA, "type": TYPE_OBJECT},
+ ))
+ }
+
+ // returns the loaded referenced subSchema for the caller to update its current subSchema
+ newSchemaDocument := refdDocumentNode.(map[string]interface{})
+
+ newSchema := &subSchema{property: KEY_REF, parent: currentSchema, ref: currentSchema.ref}
+ d.referencePool.Add(currentSchema.ref.String()+reference, newSchema)
+
+ err = d.parseSchema(newSchemaDocument, newSchema)
+ if err != nil {
+ return err
+ }
+
+ currentSchema.refSchema = newSchema
+
+ return nil
+
+}
+
+func (d *Schema) parseProperties(documentNode interface{}, currentSchema *subSchema) error {
+
+ if !isKind(documentNode, reflect.Map) {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfType(),
+ ErrorDetails{"key": STRING_PROPERTIES, "type": TYPE_OBJECT},
+ ))
+ }
+
+ m := documentNode.(map[string]interface{})
+ for k := range m {
+ schemaProperty := k
+ newSchema := &subSchema{property: schemaProperty, parent: currentSchema, ref: currentSchema.ref}
+ currentSchema.AddPropertiesChild(newSchema)
+ err := d.parseSchema(m[k], newSchema)
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (d *Schema) parseDependencies(documentNode interface{}, currentSchema *subSchema) error {
+
+ if !isKind(documentNode, reflect.Map) {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfType(),
+ ErrorDetails{"key": KEY_DEPENDENCIES, "type": TYPE_OBJECT},
+ ))
+ }
+
+ m := documentNode.(map[string]interface{})
+ currentSchema.dependencies = make(map[string]interface{})
+
+ for k := range m {
+ switch reflect.ValueOf(m[k]).Kind() {
+
+ case reflect.Slice:
+ values := m[k].([]interface{})
+ var valuesToRegister []string
+
+ for _, value := range values {
+ if !isKind(value, reflect.String) {
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfType(),
+ ErrorDetails{
+ "key": STRING_DEPENDENCY,
+ "type": STRING_SCHEMA_OR_ARRAY_OF_STRINGS,
+ },
+ ))
+ } else {
+ valuesToRegister = append(valuesToRegister, value.(string))
+ }
+ currentSchema.dependencies[k] = valuesToRegister
+ }
+
+ case reflect.Map:
+ depSchema := &subSchema{property: k, parent: currentSchema, ref: currentSchema.ref}
+ err := d.parseSchema(m[k], depSchema)
+ if err != nil {
+ return err
+ }
+ currentSchema.dependencies[k] = depSchema
+
+ default:
+ return errors.New(formatErrorDescription(
+ Locale.MustBeOfType(),
+ ErrorDetails{
+ "key": STRING_DEPENDENCY,
+ "type": STRING_SCHEMA_OR_ARRAY_OF_STRINGS,
+ },
+ ))
+ }
+
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go b/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go
new file mode 100644
index 0000000..79fbb60
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/schemaPool.go
@@ -0,0 +1,107 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Defines resources pooling.
+// Eases referencing and avoids downloading the same resource twice.
+//
+// created 26-02-2013
+
+package gojsonschema
+
+import (
+ "errors"
+
+ "github.com/xeipuuv/gojsonreference"
+)
+
+type schemaPoolDocument struct {
+ Document interface{}
+}
+
+type schemaPool struct {
+ schemaPoolDocuments map[string]*schemaPoolDocument
+ standaloneDocument interface{}
+}
+
+func newSchemaPool() *schemaPool {
+
+ p := &schemaPool{}
+ p.schemaPoolDocuments = make(map[string]*schemaPoolDocument)
+ p.standaloneDocument = nil
+
+ return p
+}
+
+func (p *schemaPool) SetStandaloneDocument(document interface{}) {
+ p.standaloneDocument = document
+}
+
+func (p *schemaPool) GetStandaloneDocument() (document interface{}) {
+ return p.standaloneDocument
+}
+
+func (p *schemaPool) GetDocument(reference gojsonreference.JsonReference) (*schemaPoolDocument, error) {
+
+ if internalLogEnabled {
+ internalLog("Get Document ( %s )", reference.String())
+ }
+
+ var err error
+
+ // It is not possible to load anything that is not canonical...
+ if !reference.IsCanonical() {
+ return nil, errors.New(formatErrorDescription(
+ Locale.ReferenceMustBeCanonical(),
+ ErrorDetails{"reference": reference},
+ ))
+ }
+
+ refToUrl := reference
+ refToUrl.GetUrl().Fragment = ""
+
+ var spd *schemaPoolDocument
+
+ // Try to find the requested document in the pool
+ for k := range p.schemaPoolDocuments {
+ if k == refToUrl.String() {
+ spd = p.schemaPoolDocuments[k]
+ }
+ }
+
+ if spd != nil {
+ if internalLogEnabled {
+ internalLog(" From pool")
+ }
+ return spd, nil
+ }
+
+ jsonReferenceLoader := NewReferenceLoader(reference.String())
+ document, err := jsonReferenceLoader.loadJSON()
+ if err != nil {
+ return nil, err
+ }
+
+ spd = &schemaPoolDocument{Document: document}
+ // add the document to the pool for potential later use
+ p.schemaPoolDocuments[refToUrl.String()] = spd
+
+ return spd, nil
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaReferencePool.go b/vendor/github.com/xeipuuv/gojsonschema/schemaReferencePool.go
new file mode 100644
index 0000000..294e36a
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/schemaReferencePool.go
@@ -0,0 +1,67 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Pool of referenced schemas.
+//
+// created 25-06-2013
+
+package gojsonschema
+
+import (
+ "fmt"
+)
+
+type schemaReferencePool struct {
+ documents map[string]*subSchema
+}
+
+func newSchemaReferencePool() *schemaReferencePool {
+
+ p := &schemaReferencePool{}
+ p.documents = make(map[string]*subSchema)
+
+ return p
+}
+
+func (p *schemaReferencePool) Get(ref string) (r *subSchema, o bool) {
+
+ if internalLogEnabled {
+ internalLog(fmt.Sprintf("Schema Reference ( %s )", ref))
+ }
+
+ if sch, ok := p.documents[ref]; ok {
+ if internalLogEnabled {
+ internalLog(fmt.Sprintf(" From pool"))
+ }
+ return sch, true
+ }
+
+ return nil, false
+}
+
+func (p *schemaReferencePool) Add(ref string, sch *subSchema) {
+
+ if internalLogEnabled {
+ internalLog(fmt.Sprintf("Add Schema Reference %s to pool", ref))
+ }
+
+ p.documents[ref] = sch
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/schemaType.go b/vendor/github.com/xeipuuv/gojsonschema/schemaType.go
new file mode 100644
index 0000000..e13a0fb
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/schemaType.go
@@ -0,0 +1,83 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Helper structure to handle schema types, and the combination of them.
+//
+// created 28-02-2013
+
+package gojsonschema
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+)
+
+type jsonSchemaType struct {
+ types []string
+}
+
+// Is the schema typed ? that is containing at least one type
+// When not typed, the schema does not need any type validation
+func (t *jsonSchemaType) IsTyped() bool {
+ return len(t.types) > 0
+}
+
+func (t *jsonSchemaType) Add(etype string) error {
+
+ if !isStringInSlice(JSON_TYPES, etype) {
+ return errors.New(formatErrorDescription(Locale.NotAValidType(), ErrorDetails{"type": etype}))
+ }
+
+ if t.Contains(etype) {
+ return errors.New(formatErrorDescription(Locale.Duplicated(), ErrorDetails{"type": etype}))
+ }
+
+ t.types = append(t.types, etype)
+
+ return nil
+}
+
+func (t *jsonSchemaType) Contains(etype string) bool {
+
+ for _, v := range t.types {
+ if v == etype {
+ return true
+ }
+ }
+
+ return false
+}
+
+func (t *jsonSchemaType) String() string {
+
+ if len(t.types) == 0 {
+ return STRING_UNDEFINED // should never happen
+ }
+
+ // Displayed as a list [type1,type2,...]
+ if len(t.types) > 1 {
+ return fmt.Sprintf("[%s]", strings.Join(t.types, ","))
+ }
+
+ // Only one type: name only
+ return t.types[0]
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/subSchema.go b/vendor/github.com/xeipuuv/gojsonschema/subSchema.go
new file mode 100644
index 0000000..b249b7e
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/subSchema.go
@@ -0,0 +1,227 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Defines the structure of a sub-subSchema.
+// A sub-subSchema can contain other sub-schemas.
+//
+// created 27-02-2013
+
+package gojsonschema
+
+import (
+ "errors"
+ "regexp"
+ "strings"
+
+ "github.com/xeipuuv/gojsonreference"
+)
+
+const (
+ KEY_SCHEMA = "$subSchema"
+ KEY_ID = "$id"
+ KEY_REF = "$ref"
+ KEY_TITLE = "title"
+ KEY_DESCRIPTION = "description"
+ KEY_TYPE = "type"
+ KEY_ITEMS = "items"
+ KEY_ADDITIONAL_ITEMS = "additionalItems"
+ KEY_PROPERTIES = "properties"
+ KEY_PATTERN_PROPERTIES = "patternProperties"
+ KEY_ADDITIONAL_PROPERTIES = "additionalProperties"
+ KEY_DEFINITIONS = "definitions"
+ KEY_MULTIPLE_OF = "multipleOf"
+ KEY_MINIMUM = "minimum"
+ KEY_MAXIMUM = "maximum"
+ KEY_EXCLUSIVE_MINIMUM = "exclusiveMinimum"
+ KEY_EXCLUSIVE_MAXIMUM = "exclusiveMaximum"
+ KEY_MIN_LENGTH = "minLength"
+ KEY_MAX_LENGTH = "maxLength"
+ KEY_PATTERN = "pattern"
+ KEY_FORMAT = "format"
+ KEY_MIN_PROPERTIES = "minProperties"
+ KEY_MAX_PROPERTIES = "maxProperties"
+ KEY_DEPENDENCIES = "dependencies"
+ KEY_REQUIRED = "required"
+ KEY_MIN_ITEMS = "minItems"
+ KEY_MAX_ITEMS = "maxItems"
+ KEY_UNIQUE_ITEMS = "uniqueItems"
+ KEY_ENUM = "enum"
+ KEY_ONE_OF = "oneOf"
+ KEY_ANY_OF = "anyOf"
+ KEY_ALL_OF = "allOf"
+ KEY_NOT = "not"
+)
+
+type subSchema struct {
+
+ // basic subSchema meta properties
+ id *string
+ title *string
+ description *string
+
+ property string
+
+ // Types associated with the subSchema
+ types jsonSchemaType
+
+ // Reference url
+ ref *gojsonreference.JsonReference
+ // Schema referenced
+ refSchema *subSchema
+ // Json reference
+ subSchema *gojsonreference.JsonReference
+
+ // hierarchy
+ parent *subSchema
+ definitions map[string]*subSchema
+ definitionsChildren []*subSchema
+ itemsChildren []*subSchema
+ itemsChildrenIsSingleSchema bool
+ propertiesChildren []*subSchema
+
+ // validation : number / integer
+ multipleOf *float64
+ maximum *float64
+ exclusiveMaximum bool
+ minimum *float64
+ exclusiveMinimum bool
+
+ // validation : string
+ minLength *int
+ maxLength *int
+ pattern *regexp.Regexp
+ format string
+
+ // validation : object
+ minProperties *int
+ maxProperties *int
+ required []string
+
+ dependencies map[string]interface{}
+ additionalProperties interface{}
+ patternProperties map[string]*subSchema
+
+ // validation : array
+ minItems *int
+ maxItems *int
+ uniqueItems bool
+
+ additionalItems interface{}
+
+ // validation : all
+ enum []string
+
+ // validation : subSchema
+ oneOf []*subSchema
+ anyOf []*subSchema
+ allOf []*subSchema
+ not *subSchema
+}
+
+func (s *subSchema) AddEnum(i interface{}) error {
+
+ is, err := marshalToJsonString(i)
+ if err != nil {
+ return err
+ }
+
+ if isStringInSlice(s.enum, *is) {
+ return errors.New(formatErrorDescription(
+ Locale.KeyItemsMustBeUnique(),
+ ErrorDetails{"key": KEY_ENUM},
+ ))
+ }
+
+ s.enum = append(s.enum, *is)
+
+ return nil
+}
+
+func (s *subSchema) ContainsEnum(i interface{}) (bool, error) {
+
+ is, err := marshalToJsonString(i)
+ if err != nil {
+ return false, err
+ }
+
+ return isStringInSlice(s.enum, *is), nil
+}
+
+func (s *subSchema) AddOneOf(subSchema *subSchema) {
+ s.oneOf = append(s.oneOf, subSchema)
+}
+
+func (s *subSchema) AddAllOf(subSchema *subSchema) {
+ s.allOf = append(s.allOf, subSchema)
+}
+
+func (s *subSchema) AddAnyOf(subSchema *subSchema) {
+ s.anyOf = append(s.anyOf, subSchema)
+}
+
+func (s *subSchema) SetNot(subSchema *subSchema) {
+ s.not = subSchema
+}
+
+func (s *subSchema) AddRequired(value string) error {
+
+ if isStringInSlice(s.required, value) {
+ return errors.New(formatErrorDescription(
+ Locale.KeyItemsMustBeUnique(),
+ ErrorDetails{"key": KEY_REQUIRED},
+ ))
+ }
+
+ s.required = append(s.required, value)
+
+ return nil
+}
+
+func (s *subSchema) AddDefinitionChild(child *subSchema) {
+ s.definitionsChildren = append(s.definitionsChildren, child)
+}
+
+func (s *subSchema) AddItemsChild(child *subSchema) {
+ s.itemsChildren = append(s.itemsChildren, child)
+}
+
+func (s *subSchema) AddPropertiesChild(child *subSchema) {
+ s.propertiesChildren = append(s.propertiesChildren, child)
+}
+
+func (s *subSchema) PatternPropertiesString() string {
+
+ if s.patternProperties == nil || len(s.patternProperties) == 0 {
+ return STRING_UNDEFINED // should never happen
+ }
+
+ patternPropertiesKeySlice := []string{}
+ for pk, _ := range s.patternProperties {
+ patternPropertiesKeySlice = append(patternPropertiesKeySlice, `"`+pk+`"`)
+ }
+
+ if len(patternPropertiesKeySlice) == 1 {
+ return patternPropertiesKeySlice[0]
+ }
+
+ return "[" + strings.Join(patternPropertiesKeySlice, ",") + "]"
+
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/types.go b/vendor/github.com/xeipuuv/gojsonschema/types.go
new file mode 100644
index 0000000..952d22e
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/types.go
@@ -0,0 +1,58 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Contains const types for schema and JSON.
+//
+// created 28-02-2013
+
+package gojsonschema
+
+const (
+ TYPE_ARRAY = `array`
+ TYPE_BOOLEAN = `boolean`
+ TYPE_INTEGER = `integer`
+ TYPE_NUMBER = `number`
+ TYPE_NULL = `null`
+ TYPE_OBJECT = `object`
+ TYPE_STRING = `string`
+)
+
+var JSON_TYPES []string
+var SCHEMA_TYPES []string
+
+func init() {
+ JSON_TYPES = []string{
+ TYPE_ARRAY,
+ TYPE_BOOLEAN,
+ TYPE_INTEGER,
+ TYPE_NUMBER,
+ TYPE_NULL,
+ TYPE_OBJECT,
+ TYPE_STRING}
+
+ SCHEMA_TYPES = []string{
+ TYPE_ARRAY,
+ TYPE_BOOLEAN,
+ TYPE_INTEGER,
+ TYPE_NUMBER,
+ TYPE_OBJECT,
+ TYPE_STRING}
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/utils.go b/vendor/github.com/xeipuuv/gojsonschema/utils.go
new file mode 100644
index 0000000..cfeb628
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/utils.go
@@ -0,0 +1,202 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Various utility functions.
+//
+// created 26-02-2013
+
+package gojsonschema
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "reflect"
+ "strconv"
+)
+
+func isKind(what interface{}, kind reflect.Kind) bool {
+ return reflect.ValueOf(what).Kind() == kind
+}
+
+func existsMapKey(m map[string]interface{}, k string) bool {
+ _, ok := m[k]
+ return ok
+}
+
+func isStringInSlice(s []string, what string) bool {
+ for i := range s {
+ if s[i] == what {
+ return true
+ }
+ }
+ return false
+}
+
+func marshalToJsonString(value interface{}) (*string, error) {
+
+ mBytes, err := json.Marshal(value)
+ if err != nil {
+ return nil, err
+ }
+
+ sBytes := string(mBytes)
+ return &sBytes, nil
+}
+
+func isJsonNumber(what interface{}) bool {
+
+ switch what.(type) {
+
+ case json.Number:
+ return true
+ }
+
+ return false
+}
+
+func checkJsonNumber(what interface{}) (isValidFloat64 bool, isValidInt64 bool, isValidInt32 bool) {
+
+ jsonNumber := what.(json.Number)
+
+ _, errFloat64 := jsonNumber.Float64()
+ _, errInt64 := jsonNumber.Int64()
+
+ isValidFloat64 = errFloat64 == nil
+ isValidInt64 = errInt64 == nil
+
+ _, errInt32 := strconv.ParseInt(jsonNumber.String(), 10, 32)
+ isValidInt32 = isValidInt64 && errInt32 == nil
+
+ return
+
+}
+
+// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER
+const (
+ max_json_float = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1
+ min_json_float = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1
+)
+
+func isFloat64AnInteger(f float64) bool {
+
+ if math.IsNaN(f) || math.IsInf(f, 0) || f < min_json_float || f > max_json_float {
+ return false
+ }
+
+ return f == float64(int64(f)) || f == float64(uint64(f))
+}
+
+func mustBeInteger(what interface{}) *int {
+
+ if isJsonNumber(what) {
+
+ number := what.(json.Number)
+
+ _, _, isValidInt32 := checkJsonNumber(number)
+
+ if isValidInt32 {
+
+ int64Value, err := number.Int64()
+ if err != nil {
+ return nil
+ }
+
+ int32Value := int(int64Value)
+ return &int32Value
+
+ } else {
+ return nil
+ }
+
+ }
+
+ return nil
+}
+
+func mustBeNumber(what interface{}) *float64 {
+
+ if isJsonNumber(what) {
+
+ number := what.(json.Number)
+ float64Value, err := number.Float64()
+
+ if err == nil {
+ return &float64Value
+ } else {
+ return nil
+ }
+
+ }
+
+ return nil
+
+}
+
+// formats a number so that it is displayed as the smallest string possible
+func resultErrorFormatJsonNumber(n json.Number) string {
+
+ if int64Value, err := n.Int64(); err == nil {
+ return fmt.Sprintf("%d", int64Value)
+ }
+
+ float64Value, _ := n.Float64()
+
+ return fmt.Sprintf("%g", float64Value)
+}
+
+// formats a number so that it is displayed as the smallest string possible
+func resultErrorFormatNumber(n float64) string {
+
+ if isFloat64AnInteger(n) {
+ return fmt.Sprintf("%d", int64(n))
+ }
+
+ return fmt.Sprintf("%g", n)
+}
+
+func convertDocumentNode(val interface{}) interface{} {
+
+ if lval, ok := val.([]interface{}); ok {
+
+ res := []interface{}{}
+ for _, v := range lval {
+ res = append(res, convertDocumentNode(v))
+ }
+
+ return res
+
+ }
+
+ if mval, ok := val.(map[interface{}]interface{}); ok {
+
+ res := map[string]interface{}{}
+
+ for k, v := range mval {
+ res[k.(string)] = convertDocumentNode(v)
+ }
+
+ return res
+
+ }
+
+ return val
+}
diff --git a/vendor/github.com/xeipuuv/gojsonschema/validation.go b/vendor/github.com/xeipuuv/gojsonschema/validation.go
new file mode 100644
index 0000000..2dc0df2
--- /dev/null
+++ b/vendor/github.com/xeipuuv/gojsonschema/validation.go
@@ -0,0 +1,829 @@
+// Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
+//
+// 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.
+
+// author xeipuuv
+// author-github https://github.com/xeipuuv
+// author-mail xeipuuv@gmail.com
+//
+// repository-name gojsonschema
+// repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
+//
+// description Extends Schema and subSchema, implements the validation phase.
+//
+// created 28-02-2013
+
+package gojsonschema
+
+import (
+ "encoding/json"
+ "reflect"
+ "regexp"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+)
+
+func Validate(ls JSONLoader, ld JSONLoader) (*Result, error) {
+
+ var err error
+
+ // load schema
+
+ schema, err := NewSchema(ls)
+ if err != nil {
+ return nil, err
+ }
+
+ // begine validation
+
+ return schema.Validate(ld)
+
+}
+
+func (v *Schema) Validate(l JSONLoader) (*Result, error) {
+
+ // load document
+
+ root, err := l.loadJSON()
+ if err != nil {
+ return nil, err
+ }
+
+ // begin validation
+
+ result := &Result{}
+ context := newJsonContext(STRING_CONTEXT_ROOT, nil)
+ v.rootSchema.validateRecursive(v.rootSchema, root, result, context)
+
+ return result, nil
+
+}
+
+func (v *subSchema) subValidateWithContext(document interface{}, context *jsonContext) *Result {
+ result := &Result{}
+ v.validateRecursive(v, document, result, context)
+ return result
+}
+
+// Walker function to validate the json recursively against the subSchema
+func (v *subSchema) validateRecursive(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *jsonContext) {
+
+ if internalLogEnabled {
+ internalLog("validateRecursive %s", context.String())
+ internalLog(" %v", currentNode)
+ }
+
+ // Handle referenced schemas, returns directly when a $ref is found
+ if currentSubSchema.refSchema != nil {
+ v.validateRecursive(currentSubSchema.refSchema, currentNode, result, context)
+ return
+ }
+
+ // Check for null value
+ if currentNode == nil {
+ if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_NULL) {
+ result.addError(
+ new(InvalidTypeError),
+ context,
+ currentNode,
+ ErrorDetails{
+ "expected": currentSubSchema.types.String(),
+ "given": TYPE_NULL,
+ },
+ )
+ return
+ }
+
+ currentSubSchema.validateSchema(currentSubSchema, currentNode, result, context)
+ v.validateCommon(currentSubSchema, currentNode, result, context)
+
+ } else { // Not a null value
+
+ if isJsonNumber(currentNode) {
+
+ value := currentNode.(json.Number)
+
+ _, isValidInt64, _ := checkJsonNumber(value)
+
+ validType := currentSubSchema.types.Contains(TYPE_NUMBER) || (isValidInt64 && currentSubSchema.types.Contains(TYPE_INTEGER))
+
+ if currentSubSchema.types.IsTyped() && !validType {
+
+ givenType := TYPE_INTEGER
+ if !isValidInt64 {
+ givenType = TYPE_NUMBER
+ }
+
+ result.addError(
+ new(InvalidTypeError),
+ context,
+ currentNode,
+ ErrorDetails{
+ "expected": currentSubSchema.types.String(),
+ "given": givenType,
+ },
+ )
+ return
+ }
+
+ currentSubSchema.validateSchema(currentSubSchema, value, result, context)
+ v.validateNumber(currentSubSchema, value, result, context)
+ v.validateCommon(currentSubSchema, value, result, context)
+ v.validateString(currentSubSchema, value, result, context)
+
+ } else {
+
+ rValue := reflect.ValueOf(currentNode)
+ rKind := rValue.Kind()
+
+ switch rKind {
+
+ // Slice => JSON array
+
+ case reflect.Slice:
+
+ if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_ARRAY) {
+ result.addError(
+ new(InvalidTypeError),
+ context,
+ currentNode,
+ ErrorDetails{
+ "expected": currentSubSchema.types.String(),
+ "given": TYPE_ARRAY,
+ },
+ )
+ return
+ }
+
+ castCurrentNode := currentNode.([]interface{})
+
+ currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context)
+
+ v.validateArray(currentSubSchema, castCurrentNode, result, context)
+ v.validateCommon(currentSubSchema, castCurrentNode, result, context)
+
+ // Map => JSON object
+
+ case reflect.Map:
+ if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_OBJECT) {
+ result.addError(
+ new(InvalidTypeError),
+ context,
+ currentNode,
+ ErrorDetails{
+ "expected": currentSubSchema.types.String(),
+ "given": TYPE_OBJECT,
+ },
+ )
+ return
+ }
+
+ castCurrentNode, ok := currentNode.(map[string]interface{})
+ if !ok {
+ castCurrentNode = convertDocumentNode(currentNode).(map[string]interface{})
+ }
+
+ currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context)
+
+ v.validateObject(currentSubSchema, castCurrentNode, result, context)
+ v.validateCommon(currentSubSchema, castCurrentNode, result, context)
+
+ for _, pSchema := range currentSubSchema.propertiesChildren {
+ nextNode, ok := castCurrentNode[pSchema.property]
+ if ok {
+ subContext := newJsonContext(pSchema.property, context)
+ v.validateRecursive(pSchema, nextNode, result, subContext)
+ }
+ }
+
+ // Simple JSON values : string, number, boolean
+
+ case reflect.Bool:
+
+ if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_BOOLEAN) {
+ result.addError(
+ new(InvalidTypeError),
+ context,
+ currentNode,
+ ErrorDetails{
+ "expected": currentSubSchema.types.String(),
+ "given": TYPE_BOOLEAN,
+ },
+ )
+ return
+ }
+
+ value := currentNode.(bool)
+
+ currentSubSchema.validateSchema(currentSubSchema, value, result, context)
+ v.validateNumber(currentSubSchema, value, result, context)
+ v.validateCommon(currentSubSchema, value, result, context)
+ v.validateString(currentSubSchema, value, result, context)
+
+ case reflect.String:
+
+ if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_STRING) {
+ result.addError(
+ new(InvalidTypeError),
+ context,
+ currentNode,
+ ErrorDetails{
+ "expected": currentSubSchema.types.String(),
+ "given": TYPE_STRING,
+ },
+ )
+ return
+ }
+
+ value := currentNode.(string)
+
+ currentSubSchema.validateSchema(currentSubSchema, value, result, context)
+ v.validateNumber(currentSubSchema, value, result, context)
+ v.validateCommon(currentSubSchema, value, result, context)
+ v.validateString(currentSubSchema, value, result, context)
+
+ }
+
+ }
+
+ }
+
+ result.incrementScore()
+}
+
+// Different kinds of validation there, subSchema / common / array / object / string...
+func (v *subSchema) validateSchema(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *jsonContext) {
+
+ if internalLogEnabled {
+ internalLog("validateSchema %s", context.String())
+ internalLog(" %v", currentNode)
+ }
+
+ if len(currentSubSchema.anyOf) > 0 {
+
+ validatedAnyOf := false
+ var bestValidationResult *Result
+
+ for _, anyOfSchema := range currentSubSchema.anyOf {
+ if !validatedAnyOf {
+ validationResult := anyOfSchema.subValidateWithContext(currentNode, context)
+ validatedAnyOf = validationResult.Valid()
+
+ if !validatedAnyOf && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) {
+ bestValidationResult = validationResult
+ }
+ }
+ }
+ if !validatedAnyOf {
+
+ result.addError(new(NumberAnyOfError), context, currentNode, ErrorDetails{})
+
+ if bestValidationResult != nil {
+ // add error messages of closest matching subSchema as
+ // that's probably the one the user was trying to match
+ result.mergeErrors(bestValidationResult)
+ }
+ }
+ }
+
+ if len(currentSubSchema.oneOf) > 0 {
+
+ nbValidated := 0
+ var bestValidationResult *Result
+
+ for _, oneOfSchema := range currentSubSchema.oneOf {
+ validationResult := oneOfSchema.subValidateWithContext(currentNode, context)
+ if validationResult.Valid() {
+ nbValidated++
+ } else if nbValidated == 0 && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) {
+ bestValidationResult = validationResult
+ }
+ }
+
+ if nbValidated != 1 {
+
+ result.addError(new(NumberOneOfError), context, currentNode, ErrorDetails{})
+
+ if nbValidated == 0 {
+ // add error messages of closest matching subSchema as
+ // that's probably the one the user was trying to match
+ result.mergeErrors(bestValidationResult)
+ }
+ }
+
+ }
+
+ if len(currentSubSchema.allOf) > 0 {
+ nbValidated := 0
+
+ for _, allOfSchema := range currentSubSchema.allOf {
+ validationResult := allOfSchema.subValidateWithContext(currentNode, context)
+ if validationResult.Valid() {
+ nbValidated++
+ }
+ result.mergeErrors(validationResult)
+ }
+
+ if nbValidated != len(currentSubSchema.allOf) {
+ result.addError(new(NumberAllOfError), context, currentNode, ErrorDetails{})
+ }
+ }
+
+ if currentSubSchema.not != nil {
+ validationResult := currentSubSchema.not.subValidateWithContext(currentNode, context)
+ if validationResult.Valid() {
+ result.addError(new(NumberNotError), context, currentNode, ErrorDetails{})
+ }
+ }
+
+ if currentSubSchema.dependencies != nil && len(currentSubSchema.dependencies) > 0 {
+ if isKind(currentNode, reflect.Map) {
+ for elementKey := range currentNode.(map[string]interface{}) {
+ if dependency, ok := currentSubSchema.dependencies[elementKey]; ok {
+ switch dependency := dependency.(type) {
+
+ case []string:
+ for _, dependOnKey := range dependency {
+ if _, dependencyResolved := currentNode.(map[string]interface{})[dependOnKey]; !dependencyResolved {
+ result.addError(
+ new(MissingDependencyError),
+ context,
+ currentNode,
+ ErrorDetails{"dependency": dependOnKey},
+ )
+ }
+ }
+
+ case *subSchema:
+ dependency.validateRecursive(dependency, currentNode, result, context)
+
+ }
+ }
+ }
+ }
+ }
+
+ result.incrementScore()
+}
+
+func (v *subSchema) validateCommon(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) {
+
+ if internalLogEnabled {
+ internalLog("validateCommon %s", context.String())
+ internalLog(" %v", value)
+ }
+
+ // enum:
+ if len(currentSubSchema.enum) > 0 {
+ has, err := currentSubSchema.ContainsEnum(value)
+ if err != nil {
+ result.addError(new(InternalError), context, value, ErrorDetails{"error": err})
+ }
+ if !has {
+ result.addError(
+ new(EnumError),
+ context,
+ value,
+ ErrorDetails{
+ "allowed": strings.Join(currentSubSchema.enum, ", "),
+ },
+ )
+ }
+ }
+
+ result.incrementScore()
+}
+
+func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface{}, result *Result, context *jsonContext) {
+
+ if internalLogEnabled {
+ internalLog("validateArray %s", context.String())
+ internalLog(" %v", value)
+ }
+
+ nbItems := len(value)
+
+ // TODO explain
+ if currentSubSchema.itemsChildrenIsSingleSchema {
+ for i := range value {
+ subContext := newJsonContext(strconv.Itoa(i), context)
+ validationResult := currentSubSchema.itemsChildren[0].subValidateWithContext(value[i], subContext)
+ result.mergeErrors(validationResult)
+ }
+ } else {
+ if currentSubSchema.itemsChildren != nil && len(currentSubSchema.itemsChildren) > 0 {
+
+ nbItems := len(currentSubSchema.itemsChildren)
+ nbValues := len(value)
+
+ if nbItems == nbValues {
+ for i := 0; i != nbItems; i++ {
+ subContext := newJsonContext(strconv.Itoa(i), context)
+ validationResult := currentSubSchema.itemsChildren[i].subValidateWithContext(value[i], subContext)
+ result.mergeErrors(validationResult)
+ }
+ } else if nbItems < nbValues {
+ switch currentSubSchema.additionalItems.(type) {
+ case bool:
+ if !currentSubSchema.additionalItems.(bool) {
+ result.addError(new(ArrayNoAdditionalItemsError), context, value, ErrorDetails{})
+ }
+ case *subSchema:
+ additionalItemSchema := currentSubSchema.additionalItems.(*subSchema)
+ for i := nbItems; i != nbValues; i++ {
+ subContext := newJsonContext(strconv.Itoa(i), context)
+ validationResult := additionalItemSchema.subValidateWithContext(value[i], subContext)
+ result.mergeErrors(validationResult)
+ }
+ }
+ }
+ }
+ }
+
+ // minItems & maxItems
+ if currentSubSchema.minItems != nil {
+ if nbItems < int(*currentSubSchema.minItems) {
+ result.addError(
+ new(ArrayMinItemsError),
+ context,
+ value,
+ ErrorDetails{"min": *currentSubSchema.minItems},
+ )
+ }
+ }
+ if currentSubSchema.maxItems != nil {
+ if nbItems > int(*currentSubSchema.maxItems) {
+ result.addError(
+ new(ArrayMaxItemsError),
+ context,
+ value,
+ ErrorDetails{"max": *currentSubSchema.maxItems},
+ )
+ }
+ }
+
+ // uniqueItems:
+ if currentSubSchema.uniqueItems {
+ var stringifiedItems []string
+ for _, v := range value {
+ vString, err := marshalToJsonString(v)
+ if err != nil {
+ result.addError(new(InternalError), context, value, ErrorDetails{"err": err})
+ }
+ if isStringInSlice(stringifiedItems, *vString) {
+ result.addError(
+ new(ItemsMustBeUniqueError),
+ context,
+ value,
+ ErrorDetails{"type": TYPE_ARRAY},
+ )
+ }
+ stringifiedItems = append(stringifiedItems, *vString)
+ }
+ }
+
+ result.incrementScore()
+}
+
+func (v *subSchema) validateObject(currentSubSchema *subSchema, value map[string]interface{}, result *Result, context *jsonContext) {
+
+ if internalLogEnabled {
+ internalLog("validateObject %s", context.String())
+ internalLog(" %v", value)
+ }
+
+ // minProperties & maxProperties:
+ if currentSubSchema.minProperties != nil {
+ if len(value) < int(*currentSubSchema.minProperties) {
+ result.addError(
+ new(ArrayMinPropertiesError),
+ context,
+ value,
+ ErrorDetails{"min": *currentSubSchema.minProperties},
+ )
+ }
+ }
+ if currentSubSchema.maxProperties != nil {
+ if len(value) > int(*currentSubSchema.maxProperties) {
+ result.addError(
+ new(ArrayMaxPropertiesError),
+ context,
+ value,
+ ErrorDetails{"max": *currentSubSchema.maxProperties},
+ )
+ }
+ }
+
+ // required:
+ for _, requiredProperty := range currentSubSchema.required {
+ _, ok := value[requiredProperty]
+ if ok {
+ result.incrementScore()
+ } else {
+ result.addError(
+ new(RequiredError),
+ context,
+ value,
+ ErrorDetails{"property": requiredProperty},
+ )
+ }
+ }
+
+ // additionalProperty & patternProperty:
+ if currentSubSchema.additionalProperties != nil {
+
+ switch currentSubSchema.additionalProperties.(type) {
+ case bool:
+
+ if !currentSubSchema.additionalProperties.(bool) {
+
+ for pk := range value {
+
+ found := false
+ for _, spValue := range currentSubSchema.propertiesChildren {
+ if pk == spValue.property {
+ found = true
+ }
+ }
+
+ pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context)
+
+ if found {
+
+ if pp_has && !pp_match {
+ result.addError(
+ new(AdditionalPropertyNotAllowedError),
+ context,
+ value,
+ ErrorDetails{"property": pk},
+ )
+ }
+
+ } else {
+
+ if !pp_has || !pp_match {
+ result.addError(
+ new(AdditionalPropertyNotAllowedError),
+ context,
+ value,
+ ErrorDetails{"property": pk},
+ )
+ }
+
+ }
+ }
+ }
+
+ case *subSchema:
+
+ additionalPropertiesSchema := currentSubSchema.additionalProperties.(*subSchema)
+ for pk := range value {
+
+ found := false
+ for _, spValue := range currentSubSchema.propertiesChildren {
+ if pk == spValue.property {
+ found = true
+ }
+ }
+
+ pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context)
+
+ if found {
+
+ if pp_has && !pp_match {
+ validationResult := additionalPropertiesSchema.subValidateWithContext(value[pk], context)
+ result.mergeErrors(validationResult)
+ }
+
+ } else {
+
+ if !pp_has || !pp_match {
+ validationResult := additionalPropertiesSchema.subValidateWithContext(value[pk], context)
+ result.mergeErrors(validationResult)
+ }
+
+ }
+
+ }
+ }
+ } else {
+
+ for pk := range value {
+
+ pp_has, pp_match := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context)
+
+ if pp_has && !pp_match {
+
+ result.addError(
+ new(InvalidPropertyPatternError),
+ context,
+ value,
+ ErrorDetails{
+ "property": pk,
+ "pattern": currentSubSchema.PatternPropertiesString(),
+ },
+ )
+ }
+
+ }
+ }
+
+ result.incrementScore()
+}
+
+func (v *subSchema) validatePatternProperty(currentSubSchema *subSchema, key string, value interface{}, result *Result, context *jsonContext) (has bool, matched bool) {
+
+ if internalLogEnabled {
+ internalLog("validatePatternProperty %s", context.String())
+ internalLog(" %s %v", key, value)
+ }
+
+ has = false
+
+ validatedkey := false
+
+ for pk, pv := range currentSubSchema.patternProperties {
+ if matches, _ := regexp.MatchString(pk, key); matches {
+ has = true
+ subContext := newJsonContext(key, context)
+ validationResult := pv.subValidateWithContext(value, subContext)
+ result.mergeErrors(validationResult)
+ if validationResult.Valid() {
+ validatedkey = true
+ }
+ }
+ }
+
+ if !validatedkey {
+ return has, false
+ }
+
+ result.incrementScore()
+
+ return has, true
+}
+
+func (v *subSchema) validateString(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) {
+
+ // Ignore JSON numbers
+ if isJsonNumber(value) {
+ return
+ }
+
+ // Ignore non strings
+ if !isKind(value, reflect.String) {
+ return
+ }
+
+ if internalLogEnabled {
+ internalLog("validateString %s", context.String())
+ internalLog(" %v", value)
+ }
+
+ stringValue := value.(string)
+
+ // minLength & maxLength:
+ if currentSubSchema.minLength != nil {
+ if utf8.RuneCount([]byte(stringValue)) < int(*currentSubSchema.minLength) {
+ result.addError(
+ new(StringLengthGTEError),
+ context,
+ value,
+ ErrorDetails{"min": *currentSubSchema.minLength},
+ )
+ }
+ }
+ if currentSubSchema.maxLength != nil {
+ if utf8.RuneCount([]byte(stringValue)) > int(*currentSubSchema.maxLength) {
+ result.addError(
+ new(StringLengthLTEError),
+ context,
+ value,
+ ErrorDetails{"max": *currentSubSchema.maxLength},
+ )
+ }
+ }
+
+ // pattern:
+ if currentSubSchema.pattern != nil {
+ if !currentSubSchema.pattern.MatchString(stringValue) {
+ result.addError(
+ new(DoesNotMatchPatternError),
+ context,
+ value,
+ ErrorDetails{"pattern": currentSubSchema.pattern},
+ )
+
+ }
+ }
+
+ // format
+ if currentSubSchema.format != "" {
+ if !FormatCheckers.IsFormat(currentSubSchema.format, stringValue) {
+ result.addError(
+ new(DoesNotMatchFormatError),
+ context,
+ value,
+ ErrorDetails{"format": currentSubSchema.format},
+ )
+ }
+ }
+
+ result.incrementScore()
+}
+
+func (v *subSchema) validateNumber(currentSubSchema *subSchema, value interface{}, result *Result, context *jsonContext) {
+
+ // Ignore non numbers
+ if !isJsonNumber(value) {
+ return
+ }
+
+ if internalLogEnabled {
+ internalLog("validateNumber %s", context.String())
+ internalLog(" %v", value)
+ }
+
+ number := value.(json.Number)
+ float64Value, _ := number.Float64()
+
+ // multipleOf:
+ if currentSubSchema.multipleOf != nil {
+
+ if !isFloat64AnInteger(float64Value / *currentSubSchema.multipleOf) {
+ result.addError(
+ new(MultipleOfError),
+ context,
+ resultErrorFormatJsonNumber(number),
+ ErrorDetails{"multiple": *currentSubSchema.multipleOf},
+ )
+ }
+ }
+
+ //maximum & exclusiveMaximum:
+ if currentSubSchema.maximum != nil {
+ if currentSubSchema.exclusiveMaximum {
+ if float64Value >= *currentSubSchema.maximum {
+ result.addError(
+ new(NumberLTError),
+ context,
+ resultErrorFormatJsonNumber(number),
+ ErrorDetails{
+ "max": resultErrorFormatNumber(*currentSubSchema.maximum),
+ },
+ )
+ }
+ } else {
+ if float64Value > *currentSubSchema.maximum {
+ result.addError(
+ new(NumberLTEError),
+ context,
+ resultErrorFormatJsonNumber(number),
+ ErrorDetails{
+ "max": resultErrorFormatNumber(*currentSubSchema.maximum),
+ },
+ )
+ }
+ }
+ }
+
+ //minimum & exclusiveMinimum:
+ if currentSubSchema.minimum != nil {
+ if currentSubSchema.exclusiveMinimum {
+ if float64Value <= *currentSubSchema.minimum {
+ result.addError(
+ new(NumberGTError),
+ context,
+ resultErrorFormatJsonNumber(number),
+ ErrorDetails{
+ "min": resultErrorFormatNumber(*currentSubSchema.minimum),
+ },
+ )
+ }
+ } else {
+ if float64Value < *currentSubSchema.minimum {
+ result.addError(
+ new(NumberGTEError),
+ context,
+ resultErrorFormatJsonNumber(number),
+ ErrorDetails{
+ "min": resultErrorFormatNumber(*currentSubSchema.minimum),
+ },
+ )
+ }
+ }
+ }
+
+ result.incrementScore()
+}
diff --git a/vendor/golang.org/x/crypto/LICENSE b/vendor/golang.org/x/crypto/LICENSE
new file mode 100644
index 0000000..6a66aea
--- /dev/null
+++ b/vendor/golang.org/x/crypto/LICENSE
@@ -0,0 +1,27 @@
+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
new file mode 100644
index 0000000..7330990
--- /dev/null
+++ b/vendor/golang.org/x/crypto/PATENTS
@@ -0,0 +1,22 @@
+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/README b/vendor/golang.org/x/crypto/README
new file mode 100644
index 0000000..5910f88
--- /dev/null
+++ b/vendor/golang.org/x/crypto/README
@@ -0,0 +1,3 @@
+This repository holds supplementary Go cryptography libraries.
+
+To submit changes to this repository, see https://golang.org/doc/contribute.html.
diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b.go b/vendor/golang.org/x/crypto/blake2b/blake2b.go
new file mode 100644
index 0000000..7f0a86e
--- /dev/null
+++ b/vendor/golang.org/x/crypto/blake2b/blake2b.go
@@ -0,0 +1,207 @@
+// 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 blake2b implements the BLAKE2b hash algorithm defined by RFC 7693
+// and the extendable output function (XOF) BLAKE2Xb.
+//
+// For a detailed specification of BLAKE2b see https://blake2.net/blake2.pdf
+// and for BLAKE2Xb see https://blake2.net/blake2x.pdf
+//
+// If you aren't sure which function you need, use BLAKE2b (Sum512 or New512).
+// If you need a secret-key MAC (message authentication code), use the New512
+// function with a non-nil key.
+//
+// BLAKE2X is a construction to compute hash values larger than 64 bytes. It
+// can produce hash values between 0 and 4 GiB.
+package blake2b
+
+import (
+ "encoding/binary"
+ "errors"
+ "hash"
+)
+
+const (
+ // The blocksize of BLAKE2b in bytes.
+ BlockSize = 128
+ // The hash size of BLAKE2b-512 in bytes.
+ Size = 64
+ // The hash size of BLAKE2b-384 in bytes.
+ Size384 = 48
+ // The hash size of BLAKE2b-256 in bytes.
+ Size256 = 32
+)
+
+var (
+ useAVX2 bool
+ useAVX bool
+ useSSE4 bool
+)
+
+var errKeySize = errors.New("blake2b: invalid key size")
+
+var iv = [8]uint64{
+ 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
+ 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,
+}
+
+// Sum512 returns the BLAKE2b-512 checksum of the data.
+func Sum512(data []byte) [Size]byte {
+ var sum [Size]byte
+ checkSum(&sum, Size, data)
+ return sum
+}
+
+// Sum384 returns the BLAKE2b-384 checksum of the data.
+func Sum384(data []byte) [Size384]byte {
+ var sum [Size]byte
+ var sum384 [Size384]byte
+ checkSum(&sum, Size384, data)
+ copy(sum384[:], sum[:Size384])
+ return sum384
+}
+
+// Sum256 returns the BLAKE2b-256 checksum of the data.
+func Sum256(data []byte) [Size256]byte {
+ var sum [Size]byte
+ var sum256 [Size256]byte
+ checkSum(&sum, Size256, data)
+ copy(sum256[:], sum[:Size256])
+ return sum256
+}
+
+// New512 returns a new hash.Hash computing the BLAKE2b-512 checksum. A non-nil
+// key turns the hash into a MAC. The key must between zero and 64 bytes long.
+func New512(key []byte) (hash.Hash, error) { return newDigest(Size, key) }
+
+// New384 returns a new hash.Hash computing the BLAKE2b-384 checksum. A non-nil
+// key turns the hash into a MAC. The key must between zero and 64 bytes long.
+func New384(key []byte) (hash.Hash, error) { return newDigest(Size384, key) }
+
+// New256 returns a new hash.Hash computing the BLAKE2b-256 checksum. A non-nil
+// key turns the hash into a MAC. The key must between zero and 64 bytes long.
+func New256(key []byte) (hash.Hash, error) { return newDigest(Size256, key) }
+
+func newDigest(hashSize int, key []byte) (*digest, error) {
+ if len(key) > Size {
+ return nil, errKeySize
+ }
+ d := &digest{
+ size: hashSize,
+ keyLen: len(key),
+ }
+ copy(d.key[:], key)
+ d.Reset()
+ return d, nil
+}
+
+func checkSum(sum *[Size]byte, hashSize int, data []byte) {
+ h := iv
+ h[0] ^= uint64(hashSize) | (1 << 16) | (1 << 24)
+ var c [2]uint64
+
+ if length := len(data); length > BlockSize {
+ n := length &^ (BlockSize - 1)
+ if length == n {
+ n -= BlockSize
+ }
+ hashBlocks(&h, &c, 0, data[:n])
+ data = data[n:]
+ }
+
+ var block [BlockSize]byte
+ offset := copy(block[:], data)
+ remaining := uint64(BlockSize - offset)
+ if c[0] < remaining {
+ c[1]--
+ }
+ c[0] -= remaining
+
+ hashBlocks(&h, &c, 0xFFFFFFFFFFFFFFFF, block[:])
+
+ for i, v := range h[:(hashSize+7)/8] {
+ binary.LittleEndian.PutUint64(sum[8*i:], v)
+ }
+}
+
+type digest struct {
+ h [8]uint64
+ c [2]uint64
+ size int
+ block [BlockSize]byte
+ offset int
+
+ key [BlockSize]byte
+ keyLen int
+}
+
+func (d *digest) BlockSize() int { return BlockSize }
+
+func (d *digest) Size() int { return d.size }
+
+func (d *digest) Reset() {
+ d.h = iv
+ d.h[0] ^= uint64(d.size) | (uint64(d.keyLen) << 8) | (1 << 16) | (1 << 24)
+ d.offset, d.c[0], d.c[1] = 0, 0, 0
+ if d.keyLen > 0 {
+ d.block = d.key
+ d.offset = BlockSize
+ }
+}
+
+func (d *digest) Write(p []byte) (n int, err error) {
+ n = len(p)
+
+ if d.offset > 0 {
+ remaining := BlockSize - d.offset
+ if n <= remaining {
+ d.offset += copy(d.block[d.offset:], p)
+ return
+ }
+ copy(d.block[d.offset:], p[:remaining])
+ hashBlocks(&d.h, &d.c, 0, d.block[:])
+ d.offset = 0
+ p = p[remaining:]
+ }
+
+ if length := len(p); length > BlockSize {
+ nn := length &^ (BlockSize - 1)
+ if length == nn {
+ nn -= BlockSize
+ }
+ hashBlocks(&d.h, &d.c, 0, p[:nn])
+ p = p[nn:]
+ }
+
+ if len(p) > 0 {
+ d.offset += copy(d.block[:], p)
+ }
+
+ return
+}
+
+func (d *digest) Sum(sum []byte) []byte {
+ var hash [Size]byte
+ d.finalize(&hash)
+ return append(sum, hash[:d.size]...)
+}
+
+func (d *digest) finalize(hash *[Size]byte) {
+ var block [BlockSize]byte
+ copy(block[:], d.block[:d.offset])
+ remaining := uint64(BlockSize - d.offset)
+
+ c := d.c
+ if c[0] < remaining {
+ c[1]--
+ }
+ c[0] -= remaining
+
+ h := d.h
+ hashBlocks(&h, &c, 0xFFFFFFFFFFFFFFFF, block[:])
+
+ for i, v := range h {
+ binary.LittleEndian.PutUint64(hash[8*i:], v)
+ }
+}
diff --git a/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go b/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go
new file mode 100644
index 0000000..8c41cf6
--- /dev/null
+++ b/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go
@@ -0,0 +1,43 @@
+// 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 go1.7,amd64,!gccgo,!appengine
+
+package blake2b
+
+func init() {
+ useAVX2 = supportsAVX2()
+ useAVX = supportsAVX()
+ useSSE4 = supportsSSE4()
+}
+
+//go:noescape
+func supportsSSE4() bool
+
+//go:noescape
+func supportsAVX() bool
+
+//go:noescape
+func supportsAVX2() bool
+
+//go:noescape
+func hashBlocksAVX2(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)
+
+//go:noescape
+func hashBlocksAVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)
+
+//go:noescape
+func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)
+
+func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) {
+ if useAVX2 {
+ hashBlocksAVX2(h, c, flag, blocks)
+ } else if useAVX {
+ hashBlocksAVX(h, c, flag, blocks)
+ } else if useSSE4 {
+ hashBlocksSSE4(h, c, flag, blocks)
+ } else {
+ hashBlocksGeneric(h, c, flag, blocks)
+ }
+}
diff --git a/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s b/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s
new file mode 100644
index 0000000..784bce6
--- /dev/null
+++ b/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s
@@ -0,0 +1,762 @@
+// 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 go1.7,amd64,!gccgo,!appengine
+
+#include "textflag.h"
+
+DATA ·AVX2_iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908
+DATA ·AVX2_iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b
+DATA ·AVX2_iv0<>+0x10(SB)/8, $0x3c6ef372fe94f82b
+DATA ·AVX2_iv0<>+0x18(SB)/8, $0xa54ff53a5f1d36f1
+GLOBL ·AVX2_iv0<>(SB), (NOPTR+RODATA), $32
+
+DATA ·AVX2_iv1<>+0x00(SB)/8, $0x510e527fade682d1
+DATA ·AVX2_iv1<>+0x08(SB)/8, $0x9b05688c2b3e6c1f
+DATA ·AVX2_iv1<>+0x10(SB)/8, $0x1f83d9abfb41bd6b
+DATA ·AVX2_iv1<>+0x18(SB)/8, $0x5be0cd19137e2179
+GLOBL ·AVX2_iv1<>(SB), (NOPTR+RODATA), $32
+
+DATA ·AVX2_c40<>+0x00(SB)/8, $0x0201000706050403
+DATA ·AVX2_c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b
+DATA ·AVX2_c40<>+0x10(SB)/8, $0x0201000706050403
+DATA ·AVX2_c40<>+0x18(SB)/8, $0x0a09080f0e0d0c0b
+GLOBL ·AVX2_c40<>(SB), (NOPTR+RODATA), $32
+
+DATA ·AVX2_c48<>+0x00(SB)/8, $0x0100070605040302
+DATA ·AVX2_c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a
+DATA ·AVX2_c48<>+0x10(SB)/8, $0x0100070605040302
+DATA ·AVX2_c48<>+0x18(SB)/8, $0x09080f0e0d0c0b0a
+GLOBL ·AVX2_c48<>(SB), (NOPTR+RODATA), $32
+
+DATA ·AVX_iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908
+DATA ·AVX_iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b
+GLOBL ·AVX_iv0<>(SB), (NOPTR+RODATA), $16
+
+DATA ·AVX_iv1<>+0x00(SB)/8, $0x3c6ef372fe94f82b
+DATA ·AVX_iv1<>+0x08(SB)/8, $0xa54ff53a5f1d36f1
+GLOBL ·AVX_iv1<>(SB), (NOPTR+RODATA), $16
+
+DATA ·AVX_iv2<>+0x00(SB)/8, $0x510e527fade682d1
+DATA ·AVX_iv2<>+0x08(SB)/8, $0x9b05688c2b3e6c1f
+GLOBL ·AVX_iv2<>(SB), (NOPTR+RODATA), $16
+
+DATA ·AVX_iv3<>+0x00(SB)/8, $0x1f83d9abfb41bd6b
+DATA ·AVX_iv3<>+0x08(SB)/8, $0x5be0cd19137e2179
+GLOBL ·AVX_iv3<>(SB), (NOPTR+RODATA), $16
+
+DATA ·AVX_c40<>+0x00(SB)/8, $0x0201000706050403
+DATA ·AVX_c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b
+GLOBL ·AVX_c40<>(SB), (NOPTR+RODATA), $16
+
+DATA ·AVX_c48<>+0x00(SB)/8, $0x0100070605040302
+DATA ·AVX_c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a
+GLOBL ·AVX_c48<>(SB), (NOPTR+RODATA), $16
+
+#define VPERMQ_0x39_Y1_Y1 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xc9; BYTE $0x39
+#define VPERMQ_0x93_Y1_Y1 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xc9; BYTE $0x93
+#define VPERMQ_0x4E_Y2_Y2 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xd2; BYTE $0x4e
+#define VPERMQ_0x93_Y3_Y3 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xdb; BYTE $0x93
+#define VPERMQ_0x39_Y3_Y3 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xdb; BYTE $0x39
+
+#define ROUND_AVX2(m0, m1, m2, m3, t, c40, c48) \
+ VPADDQ m0, Y0, Y0; \
+ VPADDQ Y1, Y0, Y0; \
+ VPXOR Y0, Y3, Y3; \
+ VPSHUFD $-79, Y3, Y3; \
+ VPADDQ Y3, Y2, Y2; \
+ VPXOR Y2, Y1, Y1; \
+ VPSHUFB c40, Y1, Y1; \
+ VPADDQ m1, Y0, Y0; \
+ VPADDQ Y1, Y0, Y0; \
+ VPXOR Y0, Y3, Y3; \
+ VPSHUFB c48, Y3, Y3; \
+ VPADDQ Y3, Y2, Y2; \
+ VPXOR Y2, Y1, Y1; \
+ VPADDQ Y1, Y1, t; \
+ VPSRLQ $63, Y1, Y1; \
+ VPXOR t, Y1, Y1; \
+ VPERMQ_0x39_Y1_Y1; \
+ VPERMQ_0x4E_Y2_Y2; \
+ VPERMQ_0x93_Y3_Y3; \
+ VPADDQ m2, Y0, Y0; \
+ VPADDQ Y1, Y0, Y0; \
+ VPXOR Y0, Y3, Y3; \
+ VPSHUFD $-79, Y3, Y3; \
+ VPADDQ Y3, Y2, Y2; \
+ VPXOR Y2, Y1, Y1; \
+ VPSHUFB c40, Y1, Y1; \
+ VPADDQ m3, Y0, Y0; \
+ VPADDQ Y1, Y0, Y0; \
+ VPXOR Y0, Y3, Y3; \
+ VPSHUFB c48, Y3, Y3; \
+ VPADDQ Y3, Y2, Y2; \
+ VPXOR Y2, Y1, Y1; \
+ VPADDQ Y1, Y1, t; \
+ VPSRLQ $63, Y1, Y1; \
+ VPXOR t, Y1, Y1; \
+ VPERMQ_0x39_Y3_Y3; \
+ VPERMQ_0x4E_Y2_Y2; \
+ VPERMQ_0x93_Y1_Y1
+
+#define VMOVQ_SI_X11_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x1E
+#define VMOVQ_SI_X12_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x26
+#define VMOVQ_SI_X13_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x2E
+#define VMOVQ_SI_X14_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x36
+#define VMOVQ_SI_X15_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x3E
+
+#define VMOVQ_SI_X11(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x5E; BYTE $n
+#define VMOVQ_SI_X12(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x66; BYTE $n
+#define VMOVQ_SI_X13(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x6E; BYTE $n
+#define VMOVQ_SI_X14(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x76; BYTE $n
+#define VMOVQ_SI_X15(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x7E; BYTE $n
+
+#define VPINSRQ_1_SI_X11_0 BYTE $0xC4; BYTE $0x63; BYTE $0xA1; BYTE $0x22; BYTE $0x1E; BYTE $0x01
+#define VPINSRQ_1_SI_X12_0 BYTE $0xC4; BYTE $0x63; BYTE $0x99; BYTE $0x22; BYTE $0x26; BYTE $0x01
+#define VPINSRQ_1_SI_X13_0 BYTE $0xC4; BYTE $0x63; BYTE $0x91; BYTE $0x22; BYTE $0x2E; BYTE $0x01
+#define VPINSRQ_1_SI_X14_0 BYTE $0xC4; BYTE $0x63; BYTE $0x89; BYTE $0x22; BYTE $0x36; BYTE $0x01
+#define VPINSRQ_1_SI_X15_0 BYTE $0xC4; BYTE $0x63; BYTE $0x81; BYTE $0x22; BYTE $0x3E; BYTE $0x01
+
+#define VPINSRQ_1_SI_X11(n) BYTE $0xC4; BYTE $0x63; BYTE $0xA1; BYTE $0x22; BYTE $0x5E; BYTE $n; BYTE $0x01
+#define VPINSRQ_1_SI_X12(n) BYTE $0xC4; BYTE $0x63; BYTE $0x99; BYTE $0x22; BYTE $0x66; BYTE $n; BYTE $0x01
+#define VPINSRQ_1_SI_X13(n) BYTE $0xC4; BYTE $0x63; BYTE $0x91; BYTE $0x22; BYTE $0x6E; BYTE $n; BYTE $0x01
+#define VPINSRQ_1_SI_X14(n) BYTE $0xC4; BYTE $0x63; BYTE $0x89; BYTE $0x22; BYTE $0x76; BYTE $n; BYTE $0x01
+#define VPINSRQ_1_SI_X15(n) BYTE $0xC4; BYTE $0x63; BYTE $0x81; BYTE $0x22; BYTE $0x7E; BYTE $n; BYTE $0x01
+
+#define VMOVQ_R8_X15 BYTE $0xC4; BYTE $0x41; BYTE $0xF9; BYTE $0x6E; BYTE $0xF8
+#define VPINSRQ_1_R9_X15 BYTE $0xC4; BYTE $0x43; BYTE $0x81; BYTE $0x22; BYTE $0xF9; BYTE $0x01
+
+// load msg: Y12 = (i0, i1, i2, i3)
+// i0, i1, i2, i3 must not be 0
+#define LOAD_MSG_AVX2_Y12(i0, i1, i2, i3) \
+ VMOVQ_SI_X12(i0*8); \
+ VMOVQ_SI_X11(i2*8); \
+ VPINSRQ_1_SI_X12(i1*8); \
+ VPINSRQ_1_SI_X11(i3*8); \
+ VINSERTI128 $1, X11, Y12, Y12
+
+// load msg: Y13 = (i0, i1, i2, i3)
+// i0, i1, i2, i3 must not be 0
+#define LOAD_MSG_AVX2_Y13(i0, i1, i2, i3) \
+ VMOVQ_SI_X13(i0*8); \
+ VMOVQ_SI_X11(i2*8); \
+ VPINSRQ_1_SI_X13(i1*8); \
+ VPINSRQ_1_SI_X11(i3*8); \
+ VINSERTI128 $1, X11, Y13, Y13
+
+// load msg: Y14 = (i0, i1, i2, i3)
+// i0, i1, i2, i3 must not be 0
+#define LOAD_MSG_AVX2_Y14(i0, i1, i2, i3) \
+ VMOVQ_SI_X14(i0*8); \
+ VMOVQ_SI_X11(i2*8); \
+ VPINSRQ_1_SI_X14(i1*8); \
+ VPINSRQ_1_SI_X11(i3*8); \
+ VINSERTI128 $1, X11, Y14, Y14
+
+// load msg: Y15 = (i0, i1, i2, i3)
+// i0, i1, i2, i3 must not be 0
+#define LOAD_MSG_AVX2_Y15(i0, i1, i2, i3) \
+ VMOVQ_SI_X15(i0*8); \
+ VMOVQ_SI_X11(i2*8); \
+ VPINSRQ_1_SI_X15(i1*8); \
+ VPINSRQ_1_SI_X11(i3*8); \
+ VINSERTI128 $1, X11, Y15, Y15
+
+#define LOAD_MSG_AVX2_0_2_4_6_1_3_5_7_8_10_12_14_9_11_13_15() \
+ VMOVQ_SI_X12_0; \
+ VMOVQ_SI_X11(4*8); \
+ VPINSRQ_1_SI_X12(2*8); \
+ VPINSRQ_1_SI_X11(6*8); \
+ VINSERTI128 $1, X11, Y12, Y12; \
+ LOAD_MSG_AVX2_Y13(1, 3, 5, 7); \
+ LOAD_MSG_AVX2_Y14(8, 10, 12, 14); \
+ LOAD_MSG_AVX2_Y15(9, 11, 13, 15)
+
+#define LOAD_MSG_AVX2_14_4_9_13_10_8_15_6_1_0_11_5_12_2_7_3() \
+ LOAD_MSG_AVX2_Y12(14, 4, 9, 13); \
+ LOAD_MSG_AVX2_Y13(10, 8, 15, 6); \
+ VMOVQ_SI_X11(11*8); \
+ VPSHUFD $0x4E, 0*8(SI), X14; \
+ VPINSRQ_1_SI_X11(5*8); \
+ VINSERTI128 $1, X11, Y14, Y14; \
+ LOAD_MSG_AVX2_Y15(12, 2, 7, 3)
+
+#define LOAD_MSG_AVX2_11_12_5_15_8_0_2_13_10_3_7_9_14_6_1_4() \
+ VMOVQ_SI_X11(5*8); \
+ VMOVDQU 11*8(SI), X12; \
+ VPINSRQ_1_SI_X11(15*8); \
+ VINSERTI128 $1, X11, Y12, Y12; \
+ VMOVQ_SI_X13(8*8); \
+ VMOVQ_SI_X11(2*8); \
+ VPINSRQ_1_SI_X13_0; \
+ VPINSRQ_1_SI_X11(13*8); \
+ VINSERTI128 $1, X11, Y13, Y13; \
+ LOAD_MSG_AVX2_Y14(10, 3, 7, 9); \
+ LOAD_MSG_AVX2_Y15(14, 6, 1, 4)
+
+#define LOAD_MSG_AVX2_7_3_13_11_9_1_12_14_2_5_4_15_6_10_0_8() \
+ LOAD_MSG_AVX2_Y12(7, 3, 13, 11); \
+ LOAD_MSG_AVX2_Y13(9, 1, 12, 14); \
+ LOAD_MSG_AVX2_Y14(2, 5, 4, 15); \
+ VMOVQ_SI_X15(6*8); \
+ VMOVQ_SI_X11_0; \
+ VPINSRQ_1_SI_X15(10*8); \
+ VPINSRQ_1_SI_X11(8*8); \
+ VINSERTI128 $1, X11, Y15, Y15
+
+#define LOAD_MSG_AVX2_9_5_2_10_0_7_4_15_14_11_6_3_1_12_8_13() \
+ LOAD_MSG_AVX2_Y12(9, 5, 2, 10); \
+ VMOVQ_SI_X13_0; \
+ VMOVQ_SI_X11(4*8); \
+ VPINSRQ_1_SI_X13(7*8); \
+ VPINSRQ_1_SI_X11(15*8); \
+ VINSERTI128 $1, X11, Y13, Y13; \
+ LOAD_MSG_AVX2_Y14(14, 11, 6, 3); \
+ LOAD_MSG_AVX2_Y15(1, 12, 8, 13)
+
+#define LOAD_MSG_AVX2_2_6_0_8_12_10_11_3_4_7_15_1_13_5_14_9() \
+ VMOVQ_SI_X12(2*8); \
+ VMOVQ_SI_X11_0; \
+ VPINSRQ_1_SI_X12(6*8); \
+ VPINSRQ_1_SI_X11(8*8); \
+ VINSERTI128 $1, X11, Y12, Y12; \
+ LOAD_MSG_AVX2_Y13(12, 10, 11, 3); \
+ LOAD_MSG_AVX2_Y14(4, 7, 15, 1); \
+ LOAD_MSG_AVX2_Y15(13, 5, 14, 9)
+
+#define LOAD_MSG_AVX2_12_1_14_4_5_15_13_10_0_6_9_8_7_3_2_11() \
+ LOAD_MSG_AVX2_Y12(12, 1, 14, 4); \
+ LOAD_MSG_AVX2_Y13(5, 15, 13, 10); \
+ VMOVQ_SI_X14_0; \
+ VPSHUFD $0x4E, 8*8(SI), X11; \
+ VPINSRQ_1_SI_X14(6*8); \
+ VINSERTI128 $1, X11, Y14, Y14; \
+ LOAD_MSG_AVX2_Y15(7, 3, 2, 11)
+
+#define LOAD_MSG_AVX2_13_7_12_3_11_14_1_9_5_15_8_2_0_4_6_10() \
+ LOAD_MSG_AVX2_Y12(13, 7, 12, 3); \
+ LOAD_MSG_AVX2_Y13(11, 14, 1, 9); \
+ LOAD_MSG_AVX2_Y14(5, 15, 8, 2); \
+ VMOVQ_SI_X15_0; \
+ VMOVQ_SI_X11(6*8); \
+ VPINSRQ_1_SI_X15(4*8); \
+ VPINSRQ_1_SI_X11(10*8); \
+ VINSERTI128 $1, X11, Y15, Y15
+
+#define LOAD_MSG_AVX2_6_14_11_0_15_9_3_8_12_13_1_10_2_7_4_5() \
+ VMOVQ_SI_X12(6*8); \
+ VMOVQ_SI_X11(11*8); \
+ VPINSRQ_1_SI_X12(14*8); \
+ VPINSRQ_1_SI_X11_0; \
+ VINSERTI128 $1, X11, Y12, Y12; \
+ LOAD_MSG_AVX2_Y13(15, 9, 3, 8); \
+ VMOVQ_SI_X11(1*8); \
+ VMOVDQU 12*8(SI), X14; \
+ VPINSRQ_1_SI_X11(10*8); \
+ VINSERTI128 $1, X11, Y14, Y14; \
+ VMOVQ_SI_X15(2*8); \
+ VMOVDQU 4*8(SI), X11; \
+ VPINSRQ_1_SI_X15(7*8); \
+ VINSERTI128 $1, X11, Y15, Y15
+
+#define LOAD_MSG_AVX2_10_8_7_1_2_4_6_5_15_9_3_13_11_14_12_0() \
+ LOAD_MSG_AVX2_Y12(10, 8, 7, 1); \
+ VMOVQ_SI_X13(2*8); \
+ VPSHUFD $0x4E, 5*8(SI), X11; \
+ VPINSRQ_1_SI_X13(4*8); \
+ VINSERTI128 $1, X11, Y13, Y13; \
+ LOAD_MSG_AVX2_Y14(15, 9, 3, 13); \
+ VMOVQ_SI_X15(11*8); \
+ VMOVQ_SI_X11(12*8); \
+ VPINSRQ_1_SI_X15(14*8); \
+ VPINSRQ_1_SI_X11_0; \
+ VINSERTI128 $1, X11, Y15, Y15
+
+// func hashBlocksAVX2(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)
+TEXT ·hashBlocksAVX2(SB), 4, $320-48 // frame size = 288 + 32 byte alignment
+ MOVQ h+0(FP), AX
+ MOVQ c+8(FP), BX
+ MOVQ flag+16(FP), CX
+ MOVQ blocks_base+24(FP), SI
+ MOVQ blocks_len+32(FP), DI
+
+ MOVQ SP, DX
+ MOVQ SP, R9
+ ADDQ $31, R9
+ ANDQ $~31, R9
+ MOVQ R9, SP
+
+ MOVQ CX, 16(SP)
+ XORQ CX, CX
+ MOVQ CX, 24(SP)
+
+ VMOVDQU ·AVX2_c40<>(SB), Y4
+ VMOVDQU ·AVX2_c48<>(SB), Y5
+
+ VMOVDQU 0(AX), Y8
+ VMOVDQU 32(AX), Y9
+ VMOVDQU ·AVX2_iv0<>(SB), Y6
+ VMOVDQU ·AVX2_iv1<>(SB), Y7
+
+ MOVQ 0(BX), R8
+ MOVQ 8(BX), R9
+ MOVQ R9, 8(SP)
+
+loop:
+ ADDQ $128, R8
+ MOVQ R8, 0(SP)
+ CMPQ R8, $128
+ JGE noinc
+ INCQ R9
+ MOVQ R9, 8(SP)
+
+noinc:
+ VMOVDQA Y8, Y0
+ VMOVDQA Y9, Y1
+ VMOVDQA Y6, Y2
+ VPXOR 0(SP), Y7, Y3
+
+ LOAD_MSG_AVX2_0_2_4_6_1_3_5_7_8_10_12_14_9_11_13_15()
+ VMOVDQA Y12, 32(SP)
+ VMOVDQA Y13, 64(SP)
+ VMOVDQA Y14, 96(SP)
+ VMOVDQA Y15, 128(SP)
+ ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5)
+ LOAD_MSG_AVX2_14_4_9_13_10_8_15_6_1_0_11_5_12_2_7_3()
+ VMOVDQA Y12, 160(SP)
+ VMOVDQA Y13, 192(SP)
+ VMOVDQA Y14, 224(SP)
+ VMOVDQA Y15, 256(SP)
+
+ ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5)
+ LOAD_MSG_AVX2_11_12_5_15_8_0_2_13_10_3_7_9_14_6_1_4()
+ ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5)
+ LOAD_MSG_AVX2_7_3_13_11_9_1_12_14_2_5_4_15_6_10_0_8()
+ ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5)
+ LOAD_MSG_AVX2_9_5_2_10_0_7_4_15_14_11_6_3_1_12_8_13()
+ ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5)
+ LOAD_MSG_AVX2_2_6_0_8_12_10_11_3_4_7_15_1_13_5_14_9()
+ ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5)
+ LOAD_MSG_AVX2_12_1_14_4_5_15_13_10_0_6_9_8_7_3_2_11()
+ ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5)
+ LOAD_MSG_AVX2_13_7_12_3_11_14_1_9_5_15_8_2_0_4_6_10()
+ ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5)
+ LOAD_MSG_AVX2_6_14_11_0_15_9_3_8_12_13_1_10_2_7_4_5()
+ ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5)
+ LOAD_MSG_AVX2_10_8_7_1_2_4_6_5_15_9_3_13_11_14_12_0()
+ ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5)
+
+ ROUND_AVX2(32(SP), 64(SP), 96(SP), 128(SP), Y10, Y4, Y5)
+ ROUND_AVX2(160(SP), 192(SP), 224(SP), 256(SP), Y10, Y4, Y5)
+
+ VPXOR Y0, Y8, Y8
+ VPXOR Y1, Y9, Y9
+ VPXOR Y2, Y8, Y8
+ VPXOR Y3, Y9, Y9
+
+ LEAQ 128(SI), SI
+ SUBQ $128, DI
+ JNE loop
+
+ MOVQ R8, 0(BX)
+ MOVQ R9, 8(BX)
+
+ VMOVDQU Y8, 0(AX)
+ VMOVDQU Y9, 32(AX)
+ VZEROUPPER
+
+ MOVQ DX, SP
+ RET
+
+#define VPUNPCKLQDQ_X2_X2_X15 BYTE $0xC5; BYTE $0x69; BYTE $0x6C; BYTE $0xFA
+#define VPUNPCKLQDQ_X3_X3_X15 BYTE $0xC5; BYTE $0x61; BYTE $0x6C; BYTE $0xFB
+#define VPUNPCKLQDQ_X7_X7_X15 BYTE $0xC5; BYTE $0x41; BYTE $0x6C; BYTE $0xFF
+#define VPUNPCKLQDQ_X13_X13_X15 BYTE $0xC4; BYTE $0x41; BYTE $0x11; BYTE $0x6C; BYTE $0xFD
+#define VPUNPCKLQDQ_X14_X14_X15 BYTE $0xC4; BYTE $0x41; BYTE $0x09; BYTE $0x6C; BYTE $0xFE
+
+#define VPUNPCKHQDQ_X15_X2_X2 BYTE $0xC4; BYTE $0xC1; BYTE $0x69; BYTE $0x6D; BYTE $0xD7
+#define VPUNPCKHQDQ_X15_X3_X3 BYTE $0xC4; BYTE $0xC1; BYTE $0x61; BYTE $0x6D; BYTE $0xDF
+#define VPUNPCKHQDQ_X15_X6_X6 BYTE $0xC4; BYTE $0xC1; BYTE $0x49; BYTE $0x6D; BYTE $0xF7
+#define VPUNPCKHQDQ_X15_X7_X7 BYTE $0xC4; BYTE $0xC1; BYTE $0x41; BYTE $0x6D; BYTE $0xFF
+#define VPUNPCKHQDQ_X15_X3_X2 BYTE $0xC4; BYTE $0xC1; BYTE $0x61; BYTE $0x6D; BYTE $0xD7
+#define VPUNPCKHQDQ_X15_X7_X6 BYTE $0xC4; BYTE $0xC1; BYTE $0x41; BYTE $0x6D; BYTE $0xF7
+#define VPUNPCKHQDQ_X15_X13_X3 BYTE $0xC4; BYTE $0xC1; BYTE $0x11; BYTE $0x6D; BYTE $0xDF
+#define VPUNPCKHQDQ_X15_X13_X7 BYTE $0xC4; BYTE $0xC1; BYTE $0x11; BYTE $0x6D; BYTE $0xFF
+
+#define SHUFFLE_AVX() \
+ VMOVDQA X6, X13; \
+ VMOVDQA X2, X14; \
+ VMOVDQA X4, X6; \
+ VPUNPCKLQDQ_X13_X13_X15; \
+ VMOVDQA X5, X4; \
+ VMOVDQA X6, X5; \
+ VPUNPCKHQDQ_X15_X7_X6; \
+ VPUNPCKLQDQ_X7_X7_X15; \
+ VPUNPCKHQDQ_X15_X13_X7; \
+ VPUNPCKLQDQ_X3_X3_X15; \
+ VPUNPCKHQDQ_X15_X2_X2; \
+ VPUNPCKLQDQ_X14_X14_X15; \
+ VPUNPCKHQDQ_X15_X3_X3; \
+
+#define SHUFFLE_AVX_INV() \
+ VMOVDQA X2, X13; \
+ VMOVDQA X4, X14; \
+ VPUNPCKLQDQ_X2_X2_X15; \
+ VMOVDQA X5, X4; \
+ VPUNPCKHQDQ_X15_X3_X2; \
+ VMOVDQA X14, X5; \
+ VPUNPCKLQDQ_X3_X3_X15; \
+ VMOVDQA X6, X14; \
+ VPUNPCKHQDQ_X15_X13_X3; \
+ VPUNPCKLQDQ_X7_X7_X15; \
+ VPUNPCKHQDQ_X15_X6_X6; \
+ VPUNPCKLQDQ_X14_X14_X15; \
+ VPUNPCKHQDQ_X15_X7_X7; \
+
+#define HALF_ROUND_AVX(v0, v1, v2, v3, v4, v5, v6, v7, m0, m1, m2, m3, t0, c40, c48) \
+ VPADDQ m0, v0, v0; \
+ VPADDQ v2, v0, v0; \
+ VPADDQ m1, v1, v1; \
+ VPADDQ v3, v1, v1; \
+ VPXOR v0, v6, v6; \
+ VPXOR v1, v7, v7; \
+ VPSHUFD $-79, v6, v6; \
+ VPSHUFD $-79, v7, v7; \
+ VPADDQ v6, v4, v4; \
+ VPADDQ v7, v5, v5; \
+ VPXOR v4, v2, v2; \
+ VPXOR v5, v3, v3; \
+ VPSHUFB c40, v2, v2; \
+ VPSHUFB c40, v3, v3; \
+ VPADDQ m2, v0, v0; \
+ VPADDQ v2, v0, v0; \
+ VPADDQ m3, v1, v1; \
+ VPADDQ v3, v1, v1; \
+ VPXOR v0, v6, v6; \
+ VPXOR v1, v7, v7; \
+ VPSHUFB c48, v6, v6; \
+ VPSHUFB c48, v7, v7; \
+ VPADDQ v6, v4, v4; \
+ VPADDQ v7, v5, v5; \
+ VPXOR v4, v2, v2; \
+ VPXOR v5, v3, v3; \
+ VPADDQ v2, v2, t0; \
+ VPSRLQ $63, v2, v2; \
+ VPXOR t0, v2, v2; \
+ VPADDQ v3, v3, t0; \
+ VPSRLQ $63, v3, v3; \
+ VPXOR t0, v3, v3
+
+// load msg: X12 = (i0, i1), X13 = (i2, i3), X14 = (i4, i5), X15 = (i6, i7)
+// i0, i1, i2, i3, i4, i5, i6, i7 must not be 0
+#define LOAD_MSG_AVX(i0, i1, i2, i3, i4, i5, i6, i7) \
+ VMOVQ_SI_X12(i0*8); \
+ VMOVQ_SI_X13(i2*8); \
+ VMOVQ_SI_X14(i4*8); \
+ VMOVQ_SI_X15(i6*8); \
+ VPINSRQ_1_SI_X12(i1*8); \
+ VPINSRQ_1_SI_X13(i3*8); \
+ VPINSRQ_1_SI_X14(i5*8); \
+ VPINSRQ_1_SI_X15(i7*8)
+
+// load msg: X12 = (0, 2), X13 = (4, 6), X14 = (1, 3), X15 = (5, 7)
+#define LOAD_MSG_AVX_0_2_4_6_1_3_5_7() \
+ VMOVQ_SI_X12_0; \
+ VMOVQ_SI_X13(4*8); \
+ VMOVQ_SI_X14(1*8); \
+ VMOVQ_SI_X15(5*8); \
+ VPINSRQ_1_SI_X12(2*8); \
+ VPINSRQ_1_SI_X13(6*8); \
+ VPINSRQ_1_SI_X14(3*8); \
+ VPINSRQ_1_SI_X15(7*8)
+
+// load msg: X12 = (1, 0), X13 = (11, 5), X14 = (12, 2), X15 = (7, 3)
+#define LOAD_MSG_AVX_1_0_11_5_12_2_7_3() \
+ VPSHUFD $0x4E, 0*8(SI), X12; \
+ VMOVQ_SI_X13(11*8); \
+ VMOVQ_SI_X14(12*8); \
+ VMOVQ_SI_X15(7*8); \
+ VPINSRQ_1_SI_X13(5*8); \
+ VPINSRQ_1_SI_X14(2*8); \
+ VPINSRQ_1_SI_X15(3*8)
+
+// load msg: X12 = (11, 12), X13 = (5, 15), X14 = (8, 0), X15 = (2, 13)
+#define LOAD_MSG_AVX_11_12_5_15_8_0_2_13() \
+ VMOVDQU 11*8(SI), X12; \
+ VMOVQ_SI_X13(5*8); \
+ VMOVQ_SI_X14(8*8); \
+ VMOVQ_SI_X15(2*8); \
+ VPINSRQ_1_SI_X13(15*8); \
+ VPINSRQ_1_SI_X14_0; \
+ VPINSRQ_1_SI_X15(13*8)
+
+// load msg: X12 = (2, 5), X13 = (4, 15), X14 = (6, 10), X15 = (0, 8)
+#define LOAD_MSG_AVX_2_5_4_15_6_10_0_8() \
+ VMOVQ_SI_X12(2*8); \
+ VMOVQ_SI_X13(4*8); \
+ VMOVQ_SI_X14(6*8); \
+ VMOVQ_SI_X15_0; \
+ VPINSRQ_1_SI_X12(5*8); \
+ VPINSRQ_1_SI_X13(15*8); \
+ VPINSRQ_1_SI_X14(10*8); \
+ VPINSRQ_1_SI_X15(8*8)
+
+// load msg: X12 = (9, 5), X13 = (2, 10), X14 = (0, 7), X15 = (4, 15)
+#define LOAD_MSG_AVX_9_5_2_10_0_7_4_15() \
+ VMOVQ_SI_X12(9*8); \
+ VMOVQ_SI_X13(2*8); \
+ VMOVQ_SI_X14_0; \
+ VMOVQ_SI_X15(4*8); \
+ VPINSRQ_1_SI_X12(5*8); \
+ VPINSRQ_1_SI_X13(10*8); \
+ VPINSRQ_1_SI_X14(7*8); \
+ VPINSRQ_1_SI_X15(15*8)
+
+// load msg: X12 = (2, 6), X13 = (0, 8), X14 = (12, 10), X15 = (11, 3)
+#define LOAD_MSG_AVX_2_6_0_8_12_10_11_3() \
+ VMOVQ_SI_X12(2*8); \
+ VMOVQ_SI_X13_0; \
+ VMOVQ_SI_X14(12*8); \
+ VMOVQ_SI_X15(11*8); \
+ VPINSRQ_1_SI_X12(6*8); \
+ VPINSRQ_1_SI_X13(8*8); \
+ VPINSRQ_1_SI_X14(10*8); \
+ VPINSRQ_1_SI_X15(3*8)
+
+// load msg: X12 = (0, 6), X13 = (9, 8), X14 = (7, 3), X15 = (2, 11)
+#define LOAD_MSG_AVX_0_6_9_8_7_3_2_11() \
+ MOVQ 0*8(SI), X12; \
+ VPSHUFD $0x4E, 8*8(SI), X13; \
+ MOVQ 7*8(SI), X14; \
+ MOVQ 2*8(SI), X15; \
+ VPINSRQ_1_SI_X12(6*8); \
+ VPINSRQ_1_SI_X14(3*8); \
+ VPINSRQ_1_SI_X15(11*8)
+
+// load msg: X12 = (6, 14), X13 = (11, 0), X14 = (15, 9), X15 = (3, 8)
+#define LOAD_MSG_AVX_6_14_11_0_15_9_3_8() \
+ MOVQ 6*8(SI), X12; \
+ MOVQ 11*8(SI), X13; \
+ MOVQ 15*8(SI), X14; \
+ MOVQ 3*8(SI), X15; \
+ VPINSRQ_1_SI_X12(14*8); \
+ VPINSRQ_1_SI_X13_0; \
+ VPINSRQ_1_SI_X14(9*8); \
+ VPINSRQ_1_SI_X15(8*8)
+
+// load msg: X12 = (5, 15), X13 = (8, 2), X14 = (0, 4), X15 = (6, 10)
+#define LOAD_MSG_AVX_5_15_8_2_0_4_6_10() \
+ MOVQ 5*8(SI), X12; \
+ MOVQ 8*8(SI), X13; \
+ MOVQ 0*8(SI), X14; \
+ MOVQ 6*8(SI), X15; \
+ VPINSRQ_1_SI_X12(15*8); \
+ VPINSRQ_1_SI_X13(2*8); \
+ VPINSRQ_1_SI_X14(4*8); \
+ VPINSRQ_1_SI_X15(10*8)
+
+// load msg: X12 = (12, 13), X13 = (1, 10), X14 = (2, 7), X15 = (4, 5)
+#define LOAD_MSG_AVX_12_13_1_10_2_7_4_5() \
+ VMOVDQU 12*8(SI), X12; \
+ MOVQ 1*8(SI), X13; \
+ MOVQ 2*8(SI), X14; \
+ VPINSRQ_1_SI_X13(10*8); \
+ VPINSRQ_1_SI_X14(7*8); \
+ VMOVDQU 4*8(SI), X15
+
+// load msg: X12 = (15, 9), X13 = (3, 13), X14 = (11, 14), X15 = (12, 0)
+#define LOAD_MSG_AVX_15_9_3_13_11_14_12_0() \
+ MOVQ 15*8(SI), X12; \
+ MOVQ 3*8(SI), X13; \
+ MOVQ 11*8(SI), X14; \
+ MOVQ 12*8(SI), X15; \
+ VPINSRQ_1_SI_X12(9*8); \
+ VPINSRQ_1_SI_X13(13*8); \
+ VPINSRQ_1_SI_X14(14*8); \
+ VPINSRQ_1_SI_X15_0
+
+// func hashBlocksAVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)
+TEXT ·hashBlocksAVX(SB), 4, $288-48 // frame size = 272 + 16 byte alignment
+ MOVQ h+0(FP), AX
+ MOVQ c+8(FP), BX
+ MOVQ flag+16(FP), CX
+ MOVQ blocks_base+24(FP), SI
+ MOVQ blocks_len+32(FP), DI
+
+ MOVQ SP, BP
+ MOVQ SP, R9
+ ADDQ $15, R9
+ ANDQ $~15, R9
+ MOVQ R9, SP
+
+ VMOVDQU ·AVX_c40<>(SB), X0
+ VMOVDQU ·AVX_c48<>(SB), X1
+ VMOVDQA X0, X8
+ VMOVDQA X1, X9
+
+ VMOVDQU ·AVX_iv3<>(SB), X0
+ VMOVDQA X0, 0(SP)
+ XORQ CX, 0(SP) // 0(SP) = ·AVX_iv3 ^ (CX || 0)
+
+ VMOVDQU 0(AX), X10
+ VMOVDQU 16(AX), X11
+ VMOVDQU 32(AX), X2
+ VMOVDQU 48(AX), X3
+
+ MOVQ 0(BX), R8
+ MOVQ 8(BX), R9
+
+loop:
+ ADDQ $128, R8
+ CMPQ R8, $128
+ JGE noinc
+ INCQ R9
+
+noinc:
+ VMOVQ_R8_X15
+ VPINSRQ_1_R9_X15
+
+ VMOVDQA X10, X0
+ VMOVDQA X11, X1
+ VMOVDQU ·AVX_iv0<>(SB), X4
+ VMOVDQU ·AVX_iv1<>(SB), X5
+ VMOVDQU ·AVX_iv2<>(SB), X6
+
+ VPXOR X15, X6, X6
+ VMOVDQA 0(SP), X7
+
+ LOAD_MSG_AVX_0_2_4_6_1_3_5_7()
+ VMOVDQA X12, 16(SP)
+ VMOVDQA X13, 32(SP)
+ VMOVDQA X14, 48(SP)
+ VMOVDQA X15, 64(SP)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX()
+ LOAD_MSG_AVX(8, 10, 12, 14, 9, 11, 13, 15)
+ VMOVDQA X12, 80(SP)
+ VMOVDQA X13, 96(SP)
+ VMOVDQA X14, 112(SP)
+ VMOVDQA X15, 128(SP)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ LOAD_MSG_AVX(14, 4, 9, 13, 10, 8, 15, 6)
+ VMOVDQA X12, 144(SP)
+ VMOVDQA X13, 160(SP)
+ VMOVDQA X14, 176(SP)
+ VMOVDQA X15, 192(SP)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX()
+ LOAD_MSG_AVX_1_0_11_5_12_2_7_3()
+ VMOVDQA X12, 208(SP)
+ VMOVDQA X13, 224(SP)
+ VMOVDQA X14, 240(SP)
+ VMOVDQA X15, 256(SP)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ LOAD_MSG_AVX_11_12_5_15_8_0_2_13()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX()
+ LOAD_MSG_AVX(10, 3, 7, 9, 14, 6, 1, 4)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ LOAD_MSG_AVX(7, 3, 13, 11, 9, 1, 12, 14)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX()
+ LOAD_MSG_AVX_2_5_4_15_6_10_0_8()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ LOAD_MSG_AVX_9_5_2_10_0_7_4_15()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX()
+ LOAD_MSG_AVX(14, 11, 6, 3, 1, 12, 8, 13)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ LOAD_MSG_AVX_2_6_0_8_12_10_11_3()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX()
+ LOAD_MSG_AVX(4, 7, 15, 1, 13, 5, 14, 9)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ LOAD_MSG_AVX(12, 1, 14, 4, 5, 15, 13, 10)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX()
+ LOAD_MSG_AVX_0_6_9_8_7_3_2_11()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ LOAD_MSG_AVX(13, 7, 12, 3, 11, 14, 1, 9)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX()
+ LOAD_MSG_AVX_5_15_8_2_0_4_6_10()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ LOAD_MSG_AVX_6_14_11_0_15_9_3_8()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX()
+ LOAD_MSG_AVX_12_13_1_10_2_7_4_5()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ LOAD_MSG_AVX(10, 8, 7, 1, 2, 4, 6, 5)
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX()
+ LOAD_MSG_AVX_15_9_3_13_11_14_12_0()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 16(SP), 32(SP), 48(SP), 64(SP), X15, X8, X9)
+ SHUFFLE_AVX()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 80(SP), 96(SP), 112(SP), 128(SP), X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 144(SP), 160(SP), 176(SP), 192(SP), X15, X8, X9)
+ SHUFFLE_AVX()
+ HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 208(SP), 224(SP), 240(SP), 256(SP), X15, X8, X9)
+ SHUFFLE_AVX_INV()
+
+ VMOVDQU 32(AX), X14
+ VMOVDQU 48(AX), X15
+ VPXOR X0, X10, X10
+ VPXOR X1, X11, X11
+ VPXOR X2, X14, X14
+ VPXOR X3, X15, X15
+ VPXOR X4, X10, X10
+ VPXOR X5, X11, X11
+ VPXOR X6, X14, X2
+ VPXOR X7, X15, X3
+ VMOVDQU X2, 32(AX)
+ VMOVDQU X3, 48(AX)
+
+ LEAQ 128(SI), SI
+ SUBQ $128, DI
+ JNE loop
+
+ VMOVDQU X10, 0(AX)
+ VMOVDQU X11, 16(AX)
+
+ MOVQ R8, 0(BX)
+ MOVQ R9, 8(BX)
+ VZEROUPPER
+
+ MOVQ BP, SP
+ RET
+
+// func supportsAVX2() bool
+TEXT ·supportsAVX2(SB), 4, $0-1
+ MOVQ runtime·support_avx2(SB), AX
+ MOVB AX, ret+0(FP)
+ RET
+
+// func supportsAVX() bool
+TEXT ·supportsAVX(SB), 4, $0-1
+ MOVQ runtime·support_avx(SB), AX
+ MOVB AX, ret+0(FP)
+ RET
diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.go b/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.go
new file mode 100644
index 0000000..2ab7c30
--- /dev/null
+++ b/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.go
@@ -0,0 +1,25 @@
+// 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 !go1.7,amd64,!gccgo,!appengine
+
+package blake2b
+
+func init() {
+ useSSE4 = supportsSSE4()
+}
+
+//go:noescape
+func supportsSSE4() bool
+
+//go:noescape
+func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)
+
+func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) {
+ if useSSE4 {
+ hashBlocksSSE4(h, c, flag, blocks)
+ } else {
+ hashBlocksGeneric(h, c, flag, blocks)
+ }
+}
diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s b/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s
new file mode 100644
index 0000000..6453074
--- /dev/null
+++ b/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s
@@ -0,0 +1,290 @@
+// 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,!gccgo,!appengine
+
+#include "textflag.h"
+
+DATA ·iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908
+DATA ·iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b
+GLOBL ·iv0<>(SB), (NOPTR+RODATA), $16
+
+DATA ·iv1<>+0x00(SB)/8, $0x3c6ef372fe94f82b
+DATA ·iv1<>+0x08(SB)/8, $0xa54ff53a5f1d36f1
+GLOBL ·iv1<>(SB), (NOPTR+RODATA), $16
+
+DATA ·iv2<>+0x00(SB)/8, $0x510e527fade682d1
+DATA ·iv2<>+0x08(SB)/8, $0x9b05688c2b3e6c1f
+GLOBL ·iv2<>(SB), (NOPTR+RODATA), $16
+
+DATA ·iv3<>+0x00(SB)/8, $0x1f83d9abfb41bd6b
+DATA ·iv3<>+0x08(SB)/8, $0x5be0cd19137e2179
+GLOBL ·iv3<>(SB), (NOPTR+RODATA), $16
+
+DATA ·c40<>+0x00(SB)/8, $0x0201000706050403
+DATA ·c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b
+GLOBL ·c40<>(SB), (NOPTR+RODATA), $16
+
+DATA ·c48<>+0x00(SB)/8, $0x0100070605040302
+DATA ·c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a
+GLOBL ·c48<>(SB), (NOPTR+RODATA), $16
+
+#define SHUFFLE(v2, v3, v4, v5, v6, v7, t1, t2) \
+ MOVO v4, t1; \
+ MOVO v5, v4; \
+ MOVO t1, v5; \
+ MOVO v6, t1; \
+ PUNPCKLQDQ v6, t2; \
+ PUNPCKHQDQ v7, v6; \
+ PUNPCKHQDQ t2, v6; \
+ PUNPCKLQDQ v7, t2; \
+ MOVO t1, v7; \
+ MOVO v2, t1; \
+ PUNPCKHQDQ t2, v7; \
+ PUNPCKLQDQ v3, t2; \
+ PUNPCKHQDQ t2, v2; \
+ PUNPCKLQDQ t1, t2; \
+ PUNPCKHQDQ t2, v3
+
+#define SHUFFLE_INV(v2, v3, v4, v5, v6, v7, t1, t2) \
+ MOVO v4, t1; \
+ MOVO v5, v4; \
+ MOVO t1, v5; \
+ MOVO v2, t1; \
+ PUNPCKLQDQ v2, t2; \
+ PUNPCKHQDQ v3, v2; \
+ PUNPCKHQDQ t2, v2; \
+ PUNPCKLQDQ v3, t2; \
+ MOVO t1, v3; \
+ MOVO v6, t1; \
+ PUNPCKHQDQ t2, v3; \
+ PUNPCKLQDQ v7, t2; \
+ PUNPCKHQDQ t2, v6; \
+ PUNPCKLQDQ t1, t2; \
+ PUNPCKHQDQ t2, v7
+
+#define HALF_ROUND(v0, v1, v2, v3, v4, v5, v6, v7, m0, m1, m2, m3, t0, c40, c48) \
+ PADDQ m0, v0; \
+ PADDQ m1, v1; \
+ PADDQ v2, v0; \
+ PADDQ v3, v1; \
+ PXOR v0, v6; \
+ PXOR v1, v7; \
+ PSHUFD $0xB1, v6, v6; \
+ PSHUFD $0xB1, v7, v7; \
+ PADDQ v6, v4; \
+ PADDQ v7, v5; \
+ PXOR v4, v2; \
+ PXOR v5, v3; \
+ PSHUFB c40, v2; \
+ PSHUFB c40, v3; \
+ PADDQ m2, v0; \
+ PADDQ m3, v1; \
+ PADDQ v2, v0; \
+ PADDQ v3, v1; \
+ PXOR v0, v6; \
+ PXOR v1, v7; \
+ PSHUFB c48, v6; \
+ PSHUFB c48, v7; \
+ PADDQ v6, v4; \
+ PADDQ v7, v5; \
+ PXOR v4, v2; \
+ PXOR v5, v3; \
+ MOVOU v2, t0; \
+ PADDQ v2, t0; \
+ PSRLQ $63, v2; \
+ PXOR t0, v2; \
+ MOVOU v3, t0; \
+ PADDQ v3, t0; \
+ PSRLQ $63, v3; \
+ PXOR t0, v3
+
+#define LOAD_MSG(m0, m1, m2, m3, src, i0, i1, i2, i3, i4, i5, i6, i7) \
+ MOVQ i0*8(src), m0; \
+ PINSRQ $1, i1*8(src), m0; \
+ MOVQ i2*8(src), m1; \
+ PINSRQ $1, i3*8(src), m1; \
+ MOVQ i4*8(src), m2; \
+ PINSRQ $1, i5*8(src), m2; \
+ MOVQ i6*8(src), m3; \
+ PINSRQ $1, i7*8(src), m3
+
+// func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte)
+TEXT ·hashBlocksSSE4(SB), 4, $288-48 // frame size = 272 + 16 byte alignment
+ MOVQ h+0(FP), AX
+ MOVQ c+8(FP), BX
+ MOVQ flag+16(FP), CX
+ MOVQ blocks_base+24(FP), SI
+ MOVQ blocks_len+32(FP), DI
+
+ MOVQ SP, BP
+ MOVQ SP, R9
+ ADDQ $15, R9
+ ANDQ $~15, R9
+ MOVQ R9, SP
+
+ MOVOU ·iv3<>(SB), X0
+ MOVO X0, 0(SP)
+ XORQ CX, 0(SP) // 0(SP) = ·iv3 ^ (CX || 0)
+
+ MOVOU ·c40<>(SB), X13
+ MOVOU ·c48<>(SB), X14
+
+ MOVOU 0(AX), X12
+ MOVOU 16(AX), X15
+
+ MOVQ 0(BX), R8
+ MOVQ 8(BX), R9
+
+loop:
+ ADDQ $128, R8
+ CMPQ R8, $128
+ JGE noinc
+ INCQ R9
+
+noinc:
+ MOVQ R8, X8
+ PINSRQ $1, R9, X8
+
+ MOVO X12, X0
+ MOVO X15, X1
+ MOVOU 32(AX), X2
+ MOVOU 48(AX), X3
+ MOVOU ·iv0<>(SB), X4
+ MOVOU ·iv1<>(SB), X5
+ MOVOU ·iv2<>(SB), X6
+
+ PXOR X8, X6
+ MOVO 0(SP), X7
+
+ LOAD_MSG(X8, X9, X10, X11, SI, 0, 2, 4, 6, 1, 3, 5, 7)
+ MOVO X8, 16(SP)
+ MOVO X9, 32(SP)
+ MOVO X10, 48(SP)
+ MOVO X11, 64(SP)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ LOAD_MSG(X8, X9, X10, X11, SI, 8, 10, 12, 14, 9, 11, 13, 15)
+ MOVO X8, 80(SP)
+ MOVO X9, 96(SP)
+ MOVO X10, 112(SP)
+ MOVO X11, 128(SP)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ LOAD_MSG(X8, X9, X10, X11, SI, 14, 4, 9, 13, 10, 8, 15, 6)
+ MOVO X8, 144(SP)
+ MOVO X9, 160(SP)
+ MOVO X10, 176(SP)
+ MOVO X11, 192(SP)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ LOAD_MSG(X8, X9, X10, X11, SI, 1, 0, 11, 5, 12, 2, 7, 3)
+ MOVO X8, 208(SP)
+ MOVO X9, 224(SP)
+ MOVO X10, 240(SP)
+ MOVO X11, 256(SP)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ LOAD_MSG(X8, X9, X10, X11, SI, 11, 12, 5, 15, 8, 0, 2, 13)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ LOAD_MSG(X8, X9, X10, X11, SI, 10, 3, 7, 9, 14, 6, 1, 4)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ LOAD_MSG(X8, X9, X10, X11, SI, 7, 3, 13, 11, 9, 1, 12, 14)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ LOAD_MSG(X8, X9, X10, X11, SI, 2, 5, 4, 15, 6, 10, 0, 8)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ LOAD_MSG(X8, X9, X10, X11, SI, 9, 5, 2, 10, 0, 7, 4, 15)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ LOAD_MSG(X8, X9, X10, X11, SI, 14, 11, 6, 3, 1, 12, 8, 13)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ LOAD_MSG(X8, X9, X10, X11, SI, 2, 6, 0, 8, 12, 10, 11, 3)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ LOAD_MSG(X8, X9, X10, X11, SI, 4, 7, 15, 1, 13, 5, 14, 9)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ LOAD_MSG(X8, X9, X10, X11, SI, 12, 1, 14, 4, 5, 15, 13, 10)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ LOAD_MSG(X8, X9, X10, X11, SI, 0, 6, 9, 8, 7, 3, 2, 11)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ LOAD_MSG(X8, X9, X10, X11, SI, 13, 7, 12, 3, 11, 14, 1, 9)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ LOAD_MSG(X8, X9, X10, X11, SI, 5, 15, 8, 2, 0, 4, 6, 10)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ LOAD_MSG(X8, X9, X10, X11, SI, 6, 14, 11, 0, 15, 9, 3, 8)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ LOAD_MSG(X8, X9, X10, X11, SI, 12, 13, 1, 10, 2, 7, 4, 5)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ LOAD_MSG(X8, X9, X10, X11, SI, 10, 8, 7, 1, 2, 4, 6, 5)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ LOAD_MSG(X8, X9, X10, X11, SI, 15, 9, 3, 13, 11, 14, 12, 0)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 16(SP), 32(SP), 48(SP), 64(SP), X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 80(SP), 96(SP), 112(SP), 128(SP), X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 144(SP), 160(SP), 176(SP), 192(SP), X11, X13, X14)
+ SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9)
+ HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 208(SP), 224(SP), 240(SP), 256(SP), X11, X13, X14)
+ SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9)
+
+ MOVOU 32(AX), X10
+ MOVOU 48(AX), X11
+ PXOR X0, X12
+ PXOR X1, X15
+ PXOR X2, X10
+ PXOR X3, X11
+ PXOR X4, X12
+ PXOR X5, X15
+ PXOR X6, X10
+ PXOR X7, X11
+ MOVOU X10, 32(AX)
+ MOVOU X11, 48(AX)
+
+ LEAQ 128(SI), SI
+ SUBQ $128, DI
+ JNE loop
+
+ MOVOU X12, 0(AX)
+ MOVOU X15, 16(AX)
+
+ MOVQ R8, 0(BX)
+ MOVQ R9, 8(BX)
+
+ MOVQ BP, SP
+ RET
+
+// func supportsSSE4() bool
+TEXT ·supportsSSE4(SB), 4, $0-1
+ MOVL $1, AX
+ CPUID
+ SHRL $19, CX // Bit 19 indicates SSE4 support
+ ANDL $1, CX // CX != 0 if support SSE4
+ MOVB CX, ret+0(FP)
+ RET
diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_generic.go b/vendor/golang.org/x/crypto/blake2b/blake2b_generic.go
new file mode 100644
index 0000000..4bd2abc
--- /dev/null
+++ b/vendor/golang.org/x/crypto/blake2b/blake2b_generic.go
@@ -0,0 +1,179 @@
+// 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 blake2b
+
+import "encoding/binary"
+
+// the precomputed values for BLAKE2b
+// there are 12 16-byte arrays - one for each round
+// the entries are calculated from the sigma constants.
+var precomputed = [12][16]byte{
+ {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15},
+ {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3},
+ {11, 12, 5, 15, 8, 0, 2, 13, 10, 3, 7, 9, 14, 6, 1, 4},
+ {7, 3, 13, 11, 9, 1, 12, 14, 2, 5, 4, 15, 6, 10, 0, 8},
+ {9, 5, 2, 10, 0, 7, 4, 15, 14, 11, 6, 3, 1, 12, 8, 13},
+ {2, 6, 0, 8, 12, 10, 11, 3, 4, 7, 15, 1, 13, 5, 14, 9},
+ {12, 1, 14, 4, 5, 15, 13, 10, 0, 6, 9, 8, 7, 3, 2, 11},
+ {13, 7, 12, 3, 11, 14, 1, 9, 5, 15, 8, 2, 0, 4, 6, 10},
+ {6, 14, 11, 0, 15, 9, 3, 8, 12, 13, 1, 10, 2, 7, 4, 5},
+ {10, 8, 7, 1, 2, 4, 6, 5, 15, 9, 3, 13, 11, 14, 12, 0},
+ {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, // equal to the first
+ {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, // equal to the second
+}
+
+func hashBlocksGeneric(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) {
+ var m [16]uint64
+ c0, c1 := c[0], c[1]
+
+ for i := 0; i < len(blocks); {
+ c0 += BlockSize
+ if c0 < BlockSize {
+ c1++
+ }
+
+ v0, v1, v2, v3, v4, v5, v6, v7 := h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]
+ v8, v9, v10, v11, v12, v13, v14, v15 := iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]
+ v12 ^= c0
+ v13 ^= c1
+ v14 ^= flag
+
+ for j := range m {
+ m[j] = binary.LittleEndian.Uint64(blocks[i:])
+ i += 8
+ }
+
+ for j := range precomputed {
+ s := &(precomputed[j])
+
+ v0 += m[s[0]]
+ v0 += v4
+ v12 ^= v0
+ v12 = v12<<(64-32) | v12>>32
+ v8 += v12
+ v4 ^= v8
+ v4 = v4<<(64-24) | v4>>24
+ v1 += m[s[1]]
+ v1 += v5
+ v13 ^= v1
+ v13 = v13<<(64-32) | v13>>32
+ v9 += v13
+ v5 ^= v9
+ v5 = v5<<(64-24) | v5>>24
+ v2 += m[s[2]]
+ v2 += v6
+ v14 ^= v2
+ v14 = v14<<(64-32) | v14>>32
+ v10 += v14
+ v6 ^= v10
+ v6 = v6<<(64-24) | v6>>24
+ v3 += m[s[3]]
+ v3 += v7
+ v15 ^= v3
+ v15 = v15<<(64-32) | v15>>32
+ v11 += v15
+ v7 ^= v11
+ v7 = v7<<(64-24) | v7>>24
+
+ v0 += m[s[4]]
+ v0 += v4
+ v12 ^= v0
+ v12 = v12<<(64-16) | v12>>16
+ v8 += v12
+ v4 ^= v8
+ v4 = v4<<(64-63) | v4>>63
+ v1 += m[s[5]]
+ v1 += v5
+ v13 ^= v1
+ v13 = v13<<(64-16) | v13>>16
+ v9 += v13
+ v5 ^= v9
+ v5 = v5<<(64-63) | v5>>63
+ v2 += m[s[6]]
+ v2 += v6
+ v14 ^= v2
+ v14 = v14<<(64-16) | v14>>16
+ v10 += v14
+ v6 ^= v10
+ v6 = v6<<(64-63) | v6>>63
+ v3 += m[s[7]]
+ v3 += v7
+ v15 ^= v3
+ v15 = v15<<(64-16) | v15>>16
+ v11 += v15
+ v7 ^= v11
+ v7 = v7<<(64-63) | v7>>63
+
+ v0 += m[s[8]]
+ v0 += v5
+ v15 ^= v0
+ v15 = v15<<(64-32) | v15>>32
+ v10 += v15
+ v5 ^= v10
+ v5 = v5<<(64-24) | v5>>24
+ v1 += m[s[9]]
+ v1 += v6
+ v12 ^= v1
+ v12 = v12<<(64-32) | v12>>32
+ v11 += v12
+ v6 ^= v11
+ v6 = v6<<(64-24) | v6>>24
+ v2 += m[s[10]]
+ v2 += v7
+ v13 ^= v2
+ v13 = v13<<(64-32) | v13>>32
+ v8 += v13
+ v7 ^= v8
+ v7 = v7<<(64-24) | v7>>24
+ v3 += m[s[11]]
+ v3 += v4
+ v14 ^= v3
+ v14 = v14<<(64-32) | v14>>32
+ v9 += v14
+ v4 ^= v9
+ v4 = v4<<(64-24) | v4>>24
+
+ v0 += m[s[12]]
+ v0 += v5
+ v15 ^= v0
+ v15 = v15<<(64-16) | v15>>16
+ v10 += v15
+ v5 ^= v10
+ v5 = v5<<(64-63) | v5>>63
+ v1 += m[s[13]]
+ v1 += v6
+ v12 ^= v1
+ v12 = v12<<(64-16) | v12>>16
+ v11 += v12
+ v6 ^= v11
+ v6 = v6<<(64-63) | v6>>63
+ v2 += m[s[14]]
+ v2 += v7
+ v13 ^= v2
+ v13 = v13<<(64-16) | v13>>16
+ v8 += v13
+ v7 ^= v8
+ v7 = v7<<(64-63) | v7>>63
+ v3 += m[s[15]]
+ v3 += v4
+ v14 ^= v3
+ v14 = v14<<(64-16) | v14>>16
+ v9 += v14
+ v4 ^= v9
+ v4 = v4<<(64-63) | v4>>63
+
+ }
+
+ h[0] ^= v0 ^ v8
+ h[1] ^= v1 ^ v9
+ h[2] ^= v2 ^ v10
+ h[3] ^= v3 ^ v11
+ h[4] ^= v4 ^ v12
+ h[5] ^= v5 ^ v13
+ h[6] ^= v6 ^ v14
+ h[7] ^= v7 ^ v15
+ }
+ c[0], c[1] = c0, c1
+}
diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_ref.go b/vendor/golang.org/x/crypto/blake2b/blake2b_ref.go
new file mode 100644
index 0000000..da156a1
--- /dev/null
+++ b/vendor/golang.org/x/crypto/blake2b/blake2b_ref.go
@@ -0,0 +1,11 @@
+// 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 appengine gccgo
+
+package blake2b
+
+func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) {
+ hashBlocksGeneric(h, c, flag, blocks)
+}
diff --git a/vendor/golang.org/x/crypto/blake2b/blake2x.go b/vendor/golang.org/x/crypto/blake2b/blake2x.go
new file mode 100644
index 0000000..c814496
--- /dev/null
+++ b/vendor/golang.org/x/crypto/blake2b/blake2x.go
@@ -0,0 +1,177 @@
+// Copyright 2017 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 blake2b
+
+import (
+ "encoding/binary"
+ "errors"
+ "io"
+)
+
+// XOF defines the interface to hash functions that
+// support arbitrary-length output.
+type XOF interface {
+ // Write absorbs more data into the hash's state. It panics if called
+ // after Read.
+ io.Writer
+
+ // Read reads more output from the hash. It returns io.EOF if the limit
+ // has been reached.
+ io.Reader
+
+ // Clone returns a copy of the XOF in its current state.
+ Clone() XOF
+
+ // Reset resets the XOF to its initial state.
+ Reset()
+}
+
+// OutputLengthUnknown can be used as the size argument to NewXOF to indicate
+// the the length of the output is not known in advance.
+const OutputLengthUnknown = 0
+
+// magicUnknownOutputLength is a magic value for the output size that indicates
+// an unknown number of output bytes.
+const magicUnknownOutputLength = (1 << 32) - 1
+
+// maxOutputLength is the absolute maximum number of bytes to produce when the
+// number of output bytes is unknown.
+const maxOutputLength = (1 << 32) * 64
+
+// NewXOF creates a new variable-output-length hash. The hash either produce a
+// known number of bytes (1 <= size < 2**32-1), or an unknown number of bytes
+// (size == OutputLengthUnknown). In the latter case, an absolute limit of
+// 256GiB applies.
+//
+// A non-nil key turns the hash into a MAC. The key must between
+// zero and 32 bytes long.
+func NewXOF(size uint32, key []byte) (XOF, error) {
+ if len(key) > Size {
+ return nil, errKeySize
+ }
+ if size == magicUnknownOutputLength {
+ // 2^32-1 indicates an unknown number of bytes and thus isn't a
+ // valid length.
+ return nil, errors.New("blake2b: XOF length too large")
+ }
+ if size == OutputLengthUnknown {
+ size = magicUnknownOutputLength
+ }
+ x := &xof{
+ d: digest{
+ size: Size,
+ keyLen: len(key),
+ },
+ length: size,
+ }
+ copy(x.d.key[:], key)
+ x.Reset()
+ return x, nil
+}
+
+type xof struct {
+ d digest
+ length uint32
+ remaining uint64
+ cfg, root, block [Size]byte
+ offset int
+ nodeOffset uint32
+ readMode bool
+}
+
+func (x *xof) Write(p []byte) (n int, err error) {
+ if x.readMode {
+ panic("blake2b: write to XOF after read")
+ }
+ return x.d.Write(p)
+}
+
+func (x *xof) Clone() XOF {
+ clone := *x
+ return &clone
+}
+
+func (x *xof) Reset() {
+ x.cfg[0] = byte(Size)
+ binary.LittleEndian.PutUint32(x.cfg[4:], uint32(Size)) // leaf length
+ binary.LittleEndian.PutUint32(x.cfg[12:], x.length) // XOF length
+ x.cfg[17] = byte(Size) // inner hash size
+
+ x.d.Reset()
+ x.d.h[1] ^= uint64(x.length) << 32
+
+ x.remaining = uint64(x.length)
+ if x.remaining == magicUnknownOutputLength {
+ x.remaining = maxOutputLength
+ }
+ x.offset, x.nodeOffset = 0, 0
+ x.readMode = false
+}
+
+func (x *xof) Read(p []byte) (n int, err error) {
+ if !x.readMode {
+ x.d.finalize(&x.root)
+ x.readMode = true
+ }
+
+ if x.remaining == 0 {
+ return 0, io.EOF
+ }
+
+ n = len(p)
+ if uint64(n) > x.remaining {
+ n = int(x.remaining)
+ p = p[:n]
+ }
+
+ if x.offset > 0 {
+ blockRemaining := Size - x.offset
+ if n < blockRemaining {
+ x.offset += copy(p, x.block[x.offset:])
+ x.remaining -= uint64(n)
+ return
+ }
+ copy(p, x.block[x.offset:])
+ p = p[blockRemaining:]
+ x.offset = 0
+ x.remaining -= uint64(blockRemaining)
+ }
+
+ for len(p) >= Size {
+ binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset)
+ x.nodeOffset++
+
+ x.d.initConfig(&x.cfg)
+ x.d.Write(x.root[:])
+ x.d.finalize(&x.block)
+
+ copy(p, x.block[:])
+ p = p[Size:]
+ x.remaining -= uint64(Size)
+ }
+
+ if todo := len(p); todo > 0 {
+ if x.remaining < uint64(Size) {
+ x.cfg[0] = byte(x.remaining)
+ }
+ binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset)
+ x.nodeOffset++
+
+ x.d.initConfig(&x.cfg)
+ x.d.Write(x.root[:])
+ x.d.finalize(&x.block)
+
+ x.offset = copy(p, x.block[:todo])
+ x.remaining -= uint64(todo)
+ }
+ return
+}
+
+func (d *digest) initConfig(cfg *[Size]byte) {
+ d.offset, d.c[0], d.c[1] = 0, 0, 0
+ for i := range d.h {
+ d.h[i] = iv[i] ^ binary.LittleEndian.Uint64(cfg[i*8:])
+ }
+}
diff --git a/vendor/golang.org/x/crypto/blake2b/register.go b/vendor/golang.org/x/crypto/blake2b/register.go
new file mode 100644
index 0000000..efd689a
--- /dev/null
+++ b/vendor/golang.org/x/crypto/blake2b/register.go
@@ -0,0 +1,32 @@
+// Copyright 2017 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 go1.9
+
+package blake2b
+
+import (
+ "crypto"
+ "hash"
+)
+
+func init() {
+ newHash256 := func() hash.Hash {
+ h, _ := New256(nil)
+ return h
+ }
+ newHash384 := func() hash.Hash {
+ h, _ := New384(nil)
+ return h
+ }
+
+ newHash512 := func() hash.Hash {
+ h, _ := New512(nil)
+ return h
+ }
+
+ crypto.RegisterHash(crypto.BLAKE2b_256, newHash256)
+ crypto.RegisterHash(crypto.BLAKE2b_384, newHash384)
+ crypto.RegisterHash(crypto.BLAKE2b_512, newHash512)
+}
diff --git a/vendor/golang.org/x/crypto/curve25519/const_amd64.h b/vendor/golang.org/x/crypto/curve25519/const_amd64.h
new file mode 100644
index 0000000..b3f7416
--- /dev/null
+++ b/vendor/golang.org/x/crypto/curve25519/const_amd64.h
@@ -0,0 +1,8 @@
+// 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: https://bench.cr.yp.to/supercop.html
+
+#define REDMASK51 0x0007FFFFFFFFFFFF
diff --git a/vendor/golang.org/x/crypto/curve25519/const_amd64.s b/vendor/golang.org/x/crypto/curve25519/const_amd64.s
new file mode 100644
index 0000000..ee7b4bd
--- /dev/null
+++ b/vendor/golang.org/x/crypto/curve25519/const_amd64.s
@@ -0,0 +1,20 @@
+// 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: https://bench.cr.yp.to/supercop.html
+
+// +build amd64,!gccgo,!appengine
+
+// These constants cannot be encoded in non-MOVQ immediates.
+// We access them directly from memory instead.
+
+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
new file mode 100644
index 0000000..cd793a5
--- /dev/null
+++ b/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s
@@ -0,0 +1,65 @@
+// 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
+
+// func cswap(inout *[4][5]uint64, v uint64)
+TEXT ·cswap(SB),7,$0
+ MOVQ inout+0(FP),DI
+ MOVQ v+8(FP),SI
+
+ SUBQ $1, SI
+ NOTQ SI
+ MOVQ SI, X15
+ PSHUFD $0x44, X15, X15
+
+ MOVOU 0(DI), X0
+ MOVOU 16(DI), X2
+ MOVOU 32(DI), X4
+ MOVOU 48(DI), X6
+ MOVOU 64(DI), X8
+ MOVOU 80(DI), X1
+ MOVOU 96(DI), X3
+ MOVOU 112(DI), X5
+ MOVOU 128(DI), X7
+ MOVOU 144(DI), X9
+
+ MOVO X1, X10
+ MOVO X3, X11
+ MOVO X5, X12
+ MOVO X7, X13
+ MOVO X9, X14
+
+ PXOR X0, X10
+ PXOR X2, X11
+ PXOR X4, X12
+ PXOR X6, X13
+ PXOR X8, X14
+ PAND X15, X10
+ PAND X15, X11
+ PAND X15, X12
+ PAND X15, X13
+ PAND X15, X14
+ PXOR X10, X0
+ PXOR X10, X1
+ PXOR X11, X2
+ PXOR X11, X3
+ PXOR X12, X4
+ PXOR X12, X5
+ PXOR X13, X6
+ PXOR X13, X7
+ PXOR X14, X8
+ PXOR X14, X9
+
+ MOVOU X0, 0(DI)
+ MOVOU X2, 16(DI)
+ MOVOU X4, 32(DI)
+ MOVOU X6, 48(DI)
+ MOVOU X8, 64(DI)
+ MOVOU X1, 80(DI)
+ MOVOU X3, 96(DI)
+ MOVOU X5, 112(DI)
+ MOVOU X7, 128(DI)
+ MOVOU X9, 144(DI)
+ RET
diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519.go b/vendor/golang.org/x/crypto/curve25519/curve25519.go
new file mode 100644
index 0000000..2d14c2a
--- /dev/null
+++ b/vendor/golang.org/x/crypto/curve25519/curve25519.go
@@ -0,0 +1,834 @@
+// 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
+
+import (
+ "encoding/binary"
+)
+
+// 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) {
+ b = -b
+ for i := range f {
+ t := b & (f[i] ^ g[i])
+ f[i] ^= t
+ g[i] ^= t
+ }
+}
+
+// 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 {
+ return int64(binary.LittleEndian.Uint32(in))
+}
+
+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<y<1.
+//
+// Write r=h-pq.
+// Have 0<=r<=p-1=2^255-20.
+// Thus 0<=r+19(2^-255)r<r+19(2^-255)2^255<=2^255-1.
+//
+// Write x=r+19(2^-255)r+y.
+// Then 0<x<2^255 so floor(2^(-255)x) = 0 so floor(q+2^(-255)x) = q.
+//
+// Have q+2^(-255)x = 2^(-255)(h + 19 2^(-25) h9 + 2^(-1))
+// so floor(2^(-255)(h + 19 2^(-25) h9 + 2^(-1))) = q.
+func feToBytes(s *[32]byte, h *fieldElement) {
+ var carry [10]int32
+
+ q := (19*h[9] + (1 << 24)) >> 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
new file mode 100644
index 0000000..da9b10d
--- /dev/null
+++ b/vendor/golang.org/x/crypto/curve25519/doc.go
@@ -0,0 +1,23 @@
+// 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 https://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
new file mode 100644
index 0000000..3908161
--- /dev/null
+++ b/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s
@@ -0,0 +1,73 @@
+// 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: https://bench.cr.yp.to/supercop.html
+
+// +build amd64,!gccgo,!appengine
+
+#include "const_amd64.h"
+
+// func freeze(inout *[5]uint64)
+TEXT ·freeze(SB),7,$0-8
+ MOVQ inout+0(FP), DI
+
+ MOVQ 0(DI),SI
+ MOVQ 8(DI),DX
+ MOVQ 16(DI),CX
+ MOVQ 24(DI),R8
+ MOVQ 32(DI),R9
+ MOVQ $REDMASK51,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)
+ RET
diff --git a/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s b/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s
new file mode 100644
index 0000000..9e9040b
--- /dev/null
+++ b/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s
@@ -0,0 +1,1377 @@
+// 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: https://bench.cr.yp.to/supercop.html
+
+// +build amd64,!gccgo,!appengine
+
+#include "const_amd64.h"
+
+// func ladderstep(inout *[5][5]uint64)
+TEXT ·ladderstep(SB),0,$296-8
+ MOVQ inout+0(FP),DI
+
+ 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,0(SP)
+ MOVQ DX,8(SP)
+ MOVQ CX,16(SP)
+ MOVQ R8,24(SP)
+ MOVQ R9,32(SP)
+ MOVQ AX,40(SP)
+ MOVQ R10,48(SP)
+ MOVQ R11,56(SP)
+ MOVQ R12,64(SP)
+ MOVQ R13,72(SP)
+ MOVQ 40(SP),AX
+ MULQ 40(SP)
+ MOVQ AX,SI
+ MOVQ DX,CX
+ MOVQ 40(SP),AX
+ SHLQ $1,AX
+ MULQ 48(SP)
+ MOVQ AX,R8
+ MOVQ DX,R9
+ MOVQ 40(SP),AX
+ SHLQ $1,AX
+ MULQ 56(SP)
+ MOVQ AX,R10
+ MOVQ DX,R11
+ MOVQ 40(SP),AX
+ SHLQ $1,AX
+ MULQ 64(SP)
+ MOVQ AX,R12
+ MOVQ DX,R13
+ MOVQ 40(SP),AX
+ SHLQ $1,AX
+ MULQ 72(SP)
+ MOVQ AX,R14
+ MOVQ DX,R15
+ MOVQ 48(SP),AX
+ MULQ 48(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 48(SP),AX
+ SHLQ $1,AX
+ MULQ 56(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 48(SP),AX
+ SHLQ $1,AX
+ MULQ 64(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 48(SP),DX
+ IMUL3Q $38,DX,AX
+ MULQ 72(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 56(SP),AX
+ MULQ 56(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 56(SP),DX
+ IMUL3Q $38,DX,AX
+ MULQ 64(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 56(SP),DX
+ IMUL3Q $38,DX,AX
+ MULQ 72(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 64(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 64(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 64(SP),DX
+ IMUL3Q $38,DX,AX
+ MULQ 72(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 72(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 72(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ $REDMASK51,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,80(SP)
+ MOVQ R8,88(SP)
+ MOVQ R9,96(SP)
+ MOVQ AX,104(SP)
+ MOVQ R10,112(SP)
+ MOVQ 0(SP),AX
+ MULQ 0(SP)
+ MOVQ AX,SI
+ MOVQ DX,CX
+ MOVQ 0(SP),AX
+ SHLQ $1,AX
+ MULQ 8(SP)
+ MOVQ AX,R8
+ MOVQ DX,R9
+ MOVQ 0(SP),AX
+ SHLQ $1,AX
+ MULQ 16(SP)
+ MOVQ AX,R10
+ MOVQ DX,R11
+ MOVQ 0(SP),AX
+ SHLQ $1,AX
+ MULQ 24(SP)
+ MOVQ AX,R12
+ MOVQ DX,R13
+ MOVQ 0(SP),AX
+ SHLQ $1,AX
+ MULQ 32(SP)
+ MOVQ AX,R14
+ MOVQ DX,R15
+ MOVQ 8(SP),AX
+ MULQ 8(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 8(SP),AX
+ SHLQ $1,AX
+ MULQ 16(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 8(SP),AX
+ SHLQ $1,AX
+ MULQ 24(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 8(SP),DX
+ IMUL3Q $38,DX,AX
+ MULQ 32(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 16(SP),AX
+ MULQ 16(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 16(SP),DX
+ IMUL3Q $38,DX,AX
+ MULQ 24(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 16(SP),DX
+ IMUL3Q $38,DX,AX
+ MULQ 32(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 24(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 24(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 24(SP),DX
+ IMUL3Q $38,DX,AX
+ MULQ 32(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 32(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 32(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ $REDMASK51,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(SP)
+ MOVQ R8,128(SP)
+ MOVQ R9,136(SP)
+ MOVQ AX,144(SP)
+ MOVQ R10,152(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 80(SP),SI
+ SUBQ 88(SP),DX
+ SUBQ 96(SP),CX
+ SUBQ 104(SP),R8
+ SUBQ 112(SP),R9
+ MOVQ SI,160(SP)
+ MOVQ DX,168(SP)
+ MOVQ CX,176(SP)
+ MOVQ R8,184(SP)
+ MOVQ R9,192(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,200(SP)
+ MOVQ DX,208(SP)
+ MOVQ CX,216(SP)
+ MOVQ R8,224(SP)
+ MOVQ R9,232(SP)
+ MOVQ AX,240(SP)
+ MOVQ R10,248(SP)
+ MOVQ R11,256(SP)
+ MOVQ R12,264(SP)
+ MOVQ R13,272(SP)
+ MOVQ 224(SP),SI
+ IMUL3Q $19,SI,AX
+ MOVQ AX,280(SP)
+ MULQ 56(SP)
+ MOVQ AX,SI
+ MOVQ DX,CX
+ MOVQ 232(SP),DX
+ IMUL3Q $19,DX,AX
+ MOVQ AX,288(SP)
+ MULQ 48(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 200(SP),AX
+ MULQ 40(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 200(SP),AX
+ MULQ 48(SP)
+ MOVQ AX,R8
+ MOVQ DX,R9
+ MOVQ 200(SP),AX
+ MULQ 56(SP)
+ MOVQ AX,R10
+ MOVQ DX,R11
+ MOVQ 200(SP),AX
+ MULQ 64(SP)
+ MOVQ AX,R12
+ MOVQ DX,R13
+ MOVQ 200(SP),AX
+ MULQ 72(SP)
+ MOVQ AX,R14
+ MOVQ DX,R15
+ MOVQ 208(SP),AX
+ MULQ 40(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 208(SP),AX
+ MULQ 48(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 208(SP),AX
+ MULQ 56(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 208(SP),AX
+ MULQ 64(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 208(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 72(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 216(SP),AX
+ MULQ 40(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 216(SP),AX
+ MULQ 48(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 216(SP),AX
+ MULQ 56(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 216(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 64(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 216(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 72(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 224(SP),AX
+ MULQ 40(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 224(SP),AX
+ MULQ 48(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 280(SP),AX
+ MULQ 64(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 280(SP),AX
+ MULQ 72(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 232(SP),AX
+ MULQ 40(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 288(SP),AX
+ MULQ 56(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 288(SP),AX
+ MULQ 64(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 288(SP),AX
+ MULQ 72(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ $REDMASK51,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(SP)
+ MOVQ R8,48(SP)
+ MOVQ R9,56(SP)
+ MOVQ AX,64(SP)
+ MOVQ R10,72(SP)
+ MOVQ 264(SP),SI
+ IMUL3Q $19,SI,AX
+ MOVQ AX,200(SP)
+ MULQ 16(SP)
+ MOVQ AX,SI
+ MOVQ DX,CX
+ MOVQ 272(SP),DX
+ IMUL3Q $19,DX,AX
+ MOVQ AX,208(SP)
+ MULQ 8(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 240(SP),AX
+ MULQ 0(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 240(SP),AX
+ MULQ 8(SP)
+ MOVQ AX,R8
+ MOVQ DX,R9
+ MOVQ 240(SP),AX
+ MULQ 16(SP)
+ MOVQ AX,R10
+ MOVQ DX,R11
+ MOVQ 240(SP),AX
+ MULQ 24(SP)
+ MOVQ AX,R12
+ MOVQ DX,R13
+ MOVQ 240(SP),AX
+ MULQ 32(SP)
+ MOVQ AX,R14
+ MOVQ DX,R15
+ MOVQ 248(SP),AX
+ MULQ 0(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 248(SP),AX
+ MULQ 8(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 248(SP),AX
+ MULQ 16(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 248(SP),AX
+ MULQ 24(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 248(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 32(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 256(SP),AX
+ MULQ 0(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 256(SP),AX
+ MULQ 8(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 256(SP),AX
+ MULQ 16(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 256(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 24(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 256(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 32(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 264(SP),AX
+ MULQ 0(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 264(SP),AX
+ MULQ 8(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 200(SP),AX
+ MULQ 24(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 200(SP),AX
+ MULQ 32(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 272(SP),AX
+ MULQ 0(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 208(SP),AX
+ MULQ 16(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 208(SP),AX
+ MULQ 24(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 208(SP),AX
+ MULQ 32(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ $REDMASK51,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 40(SP),SI
+ ADDQ 48(SP),R8
+ ADDQ 56(SP),R9
+ ADDQ 64(SP),AX
+ ADDQ 72(SP),R10
+ SUBQ 40(SP),DX
+ SUBQ 48(SP),CX
+ SUBQ 56(SP),R11
+ SUBQ 64(SP),R12
+ SUBQ 72(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,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,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,0(SP)
+ MULQ 16(DI)
+ MOVQ AX,SI
+ MOVQ DX,CX
+ MOVQ 192(DI),DX
+ IMUL3Q $19,DX,AX
+ MOVQ AX,8(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 0(SP),AX
+ MULQ 24(DI)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 0(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 8(SP),AX
+ MULQ 16(DI)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 8(SP),AX
+ MULQ 24(DI)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 8(SP),AX
+ MULQ 32(DI)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ $REDMASK51,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 144(SP),SI
+ IMUL3Q $19,SI,AX
+ MOVQ AX,0(SP)
+ MULQ 96(SP)
+ MOVQ AX,SI
+ MOVQ DX,CX
+ MOVQ 152(SP),DX
+ IMUL3Q $19,DX,AX
+ MOVQ AX,8(SP)
+ MULQ 88(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 120(SP),AX
+ MULQ 80(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 120(SP),AX
+ MULQ 88(SP)
+ MOVQ AX,R8
+ MOVQ DX,R9
+ MOVQ 120(SP),AX
+ MULQ 96(SP)
+ MOVQ AX,R10
+ MOVQ DX,R11
+ MOVQ 120(SP),AX
+ MULQ 104(SP)
+ MOVQ AX,R12
+ MOVQ DX,R13
+ MOVQ 120(SP),AX
+ MULQ 112(SP)
+ MOVQ AX,R14
+ MOVQ DX,R15
+ MOVQ 128(SP),AX
+ MULQ 80(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 128(SP),AX
+ MULQ 88(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 128(SP),AX
+ MULQ 96(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 128(SP),AX
+ MULQ 104(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 128(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 112(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 136(SP),AX
+ MULQ 80(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 136(SP),AX
+ MULQ 88(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 136(SP),AX
+ MULQ 96(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 136(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 104(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 136(SP),DX
+ IMUL3Q $19,DX,AX
+ MULQ 112(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 144(SP),AX
+ MULQ 80(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 144(SP),AX
+ MULQ 88(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 0(SP),AX
+ MULQ 104(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 0(SP),AX
+ MULQ 112(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 152(SP),AX
+ MULQ 80(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 8(SP),AX
+ MULQ 96(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 8(SP),AX
+ MULQ 104(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 8(SP),AX
+ MULQ 112(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ $REDMASK51,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 160(SP),AX
+ MULQ ·_121666_213(SB)
+ SHRQ $13,AX
+ MOVQ AX,SI
+ MOVQ DX,CX
+ MOVQ 168(SP),AX
+ MULQ ·_121666_213(SB)
+ SHRQ $13,AX
+ ADDQ AX,CX
+ MOVQ DX,R8
+ MOVQ 176(SP),AX
+ MULQ ·_121666_213(SB)
+ SHRQ $13,AX
+ ADDQ AX,R8
+ MOVQ DX,R9
+ MOVQ 184(SP),AX
+ MULQ ·_121666_213(SB)
+ SHRQ $13,AX
+ ADDQ AX,R9
+ MOVQ DX,R10
+ MOVQ 192(SP),AX
+ MULQ ·_121666_213(SB)
+ SHRQ $13,AX
+ ADDQ AX,R10
+ IMUL3Q $19,DX,DX
+ ADDQ DX,SI
+ ADDQ 80(SP),SI
+ ADDQ 88(SP),CX
+ ADDQ 96(SP),R8
+ ADDQ 104(SP),R9
+ ADDQ 112(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,0(SP)
+ MULQ 176(SP)
+ MOVQ AX,SI
+ MOVQ DX,CX
+ MOVQ 112(DI),DX
+ IMUL3Q $19,DX,AX
+ MOVQ AX,8(SP)
+ MULQ 168(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 80(DI),AX
+ MULQ 160(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 80(DI),AX
+ MULQ 168(SP)
+ MOVQ AX,R8
+ MOVQ DX,R9
+ MOVQ 80(DI),AX
+ MULQ 176(SP)
+ MOVQ AX,R10
+ MOVQ DX,R11
+ MOVQ 80(DI),AX
+ MULQ 184(SP)
+ MOVQ AX,R12
+ MOVQ DX,R13
+ MOVQ 80(DI),AX
+ MULQ 192(SP)
+ MOVQ AX,R14
+ MOVQ DX,R15
+ MOVQ 88(DI),AX
+ MULQ 160(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 88(DI),AX
+ MULQ 168(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 88(DI),AX
+ MULQ 176(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 88(DI),AX
+ MULQ 184(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 88(DI),DX
+ IMUL3Q $19,DX,AX
+ MULQ 192(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 96(DI),AX
+ MULQ 160(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 96(DI),AX
+ MULQ 168(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 96(DI),AX
+ MULQ 176(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 96(DI),DX
+ IMUL3Q $19,DX,AX
+ MULQ 184(SP)
+ ADDQ AX,SI
+ ADCQ DX,CX
+ MOVQ 96(DI),DX
+ IMUL3Q $19,DX,AX
+ MULQ 192(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 104(DI),AX
+ MULQ 160(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 104(DI),AX
+ MULQ 168(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 0(SP),AX
+ MULQ 184(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 0(SP),AX
+ MULQ 192(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 112(DI),AX
+ MULQ 160(SP)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ 8(SP),AX
+ MULQ 176(SP)
+ ADDQ AX,R8
+ ADCQ DX,R9
+ MOVQ 8(SP),AX
+ MULQ 184(SP)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 8(SP),AX
+ MULQ 192(SP)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ $REDMASK51,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)
+ RET
diff --git a/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go b/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go
new file mode 100644
index 0000000..5822bd5
--- /dev/null
+++ b/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go
@@ -0,0 +1,240 @@
+// 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
new file mode 100644
index 0000000..5ce80a2
--- /dev/null
+++ b/vendor/golang.org/x/crypto/curve25519/mul_amd64.s
@@ -0,0 +1,169 @@
+// 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: https://bench.cr.yp.to/supercop.html
+
+// +build amd64,!gccgo,!appengine
+
+#include "const_amd64.h"
+
+// func mul(dest, a, b *[5]uint64)
+TEXT ·mul(SB),0,$16-24
+ MOVQ dest+0(FP), DI
+ MOVQ a+8(FP), SI
+ MOVQ b+16(FP), DX
+
+ MOVQ DX,CX
+ MOVQ 24(SI),DX
+ IMUL3Q $19,DX,AX
+ MOVQ AX,0(SP)
+ MULQ 16(CX)
+ MOVQ AX,R8
+ MOVQ DX,R9
+ MOVQ 32(SI),DX
+ IMUL3Q $19,DX,AX
+ MOVQ AX,8(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 0(SP),AX
+ MULQ 24(CX)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 0(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 8(SP),AX
+ MULQ 16(CX)
+ ADDQ AX,R10
+ ADCQ DX,R11
+ MOVQ 8(SP),AX
+ MULQ 24(CX)
+ ADDQ AX,R12
+ ADCQ DX,R13
+ MOVQ 8(SP),AX
+ MULQ 32(CX)
+ ADDQ AX,R14
+ ADCQ DX,R15
+ MOVQ $REDMASK51,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)
+ RET
diff --git a/vendor/golang.org/x/crypto/curve25519/square_amd64.s b/vendor/golang.org/x/crypto/curve25519/square_amd64.s
new file mode 100644
index 0000000..12f7373
--- /dev/null
+++ b/vendor/golang.org/x/crypto/curve25519/square_amd64.s
@@ -0,0 +1,132 @@
+// 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: https://bench.cr.yp.to/supercop.html
+
+// +build amd64,!gccgo,!appengine
+
+#include "const_amd64.h"
+
+// func square(out, in *[5]uint64)
+TEXT ·square(SB),7,$0-16
+ MOVQ out+0(FP), DI
+ MOVQ in+8(FP), SI
+
+ 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,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)
+ RET
diff --git a/vendor/golang.org/x/crypto/md4/md4.go b/vendor/golang.org/x/crypto/md4/md4.go
new file mode 100644
index 0000000..6d9ba9e
--- /dev/null
+++ b/vendor/golang.org/x/crypto/md4/md4.go
@@ -0,0 +1,118 @@
+// Copyright 2009 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 md4 implements the MD4 hash algorithm as defined in RFC 1320.
+package md4 // import "golang.org/x/crypto/md4"
+
+import (
+ "crypto"
+ "hash"
+)
+
+func init() {
+ crypto.RegisterHash(crypto.MD4, New)
+}
+
+// The size of an MD4 checksum in bytes.
+const Size = 16
+
+// The blocksize of MD4 in bytes.
+const BlockSize = 64
+
+const (
+ _Chunk = 64
+ _Init0 = 0x67452301
+ _Init1 = 0xEFCDAB89
+ _Init2 = 0x98BADCFE
+ _Init3 = 0x10325476
+)
+
+// digest represents the partial evaluation of a checksum.
+type digest struct {
+ s [4]uint32
+ x [_Chunk]byte
+ nx int
+ len uint64
+}
+
+func (d *digest) Reset() {
+ d.s[0] = _Init0
+ d.s[1] = _Init1
+ d.s[2] = _Init2
+ d.s[3] = _Init3
+ d.nx = 0
+ d.len = 0
+}
+
+// New returns a new hash.Hash computing the MD4 checksum.
+func New() hash.Hash {
+ d := new(digest)
+ d.Reset()
+ return d
+}
+
+func (d *digest) Size() int { return Size }
+
+func (d *digest) BlockSize() int { return BlockSize }
+
+func (d *digest) Write(p []byte) (nn int, err error) {
+ nn = len(p)
+ d.len += uint64(nn)
+ if d.nx > 0 {
+ n := len(p)
+ if n > _Chunk-d.nx {
+ n = _Chunk - d.nx
+ }
+ for i := 0; i < n; i++ {
+ d.x[d.nx+i] = p[i]
+ }
+ d.nx += n
+ if d.nx == _Chunk {
+ _Block(d, d.x[0:])
+ d.nx = 0
+ }
+ p = p[n:]
+ }
+ n := _Block(d, p)
+ p = p[n:]
+ if len(p) > 0 {
+ d.nx = copy(d.x[:], p)
+ }
+ return
+}
+
+func (d0 *digest) Sum(in []byte) []byte {
+ // Make a copy of d0, so that caller can keep writing and summing.
+ d := new(digest)
+ *d = *d0
+
+ // Padding. Add a 1 bit and 0 bits until 56 bytes mod 64.
+ len := d.len
+ var tmp [64]byte
+ tmp[0] = 0x80
+ if len%64 < 56 {
+ d.Write(tmp[0 : 56-len%64])
+ } else {
+ d.Write(tmp[0 : 64+56-len%64])
+ }
+
+ // Length in bits.
+ len <<= 3
+ for i := uint(0); i < 8; i++ {
+ tmp[i] = byte(len >> (8 * i))
+ }
+ d.Write(tmp[0:8])
+
+ if d.nx != 0 {
+ panic("d.nx != 0")
+ }
+
+ for _, s := range d.s {
+ in = append(in, byte(s>>0))
+ in = append(in, byte(s>>8))
+ in = append(in, byte(s>>16))
+ in = append(in, byte(s>>24))
+ }
+ return in
+}
diff --git a/vendor/golang.org/x/crypto/md4/md4block.go b/vendor/golang.org/x/crypto/md4/md4block.go
new file mode 100644
index 0000000..3fed475
--- /dev/null
+++ b/vendor/golang.org/x/crypto/md4/md4block.go
@@ -0,0 +1,89 @@
+// Copyright 2009 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.
+
+// MD4 block step.
+// In its own file so that a faster assembly or C version
+// can be substituted easily.
+
+package md4
+
+var shift1 = []uint{3, 7, 11, 19}
+var shift2 = []uint{3, 5, 9, 13}
+var shift3 = []uint{3, 9, 11, 15}
+
+var xIndex2 = []uint{0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15}
+var xIndex3 = []uint{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}
+
+func _Block(dig *digest, p []byte) int {
+ a := dig.s[0]
+ b := dig.s[1]
+ c := dig.s[2]
+ d := dig.s[3]
+ n := 0
+ var X [16]uint32
+ for len(p) >= _Chunk {
+ aa, bb, cc, dd := a, b, c, d
+
+ j := 0
+ for i := 0; i < 16; i++ {
+ X[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24
+ j += 4
+ }
+
+ // If this needs to be made faster in the future,
+ // the usual trick is to unroll each of these
+ // loops by a factor of 4; that lets you replace
+ // the shift[] lookups with constants and,
+ // with suitable variable renaming in each
+ // unrolled body, delete the a, b, c, d = d, a, b, c
+ // (or you can let the optimizer do the renaming).
+ //
+ // The index variables are uint so that % by a power
+ // of two can be optimized easily by a compiler.
+
+ // Round 1.
+ for i := uint(0); i < 16; i++ {
+ x := i
+ s := shift1[i%4]
+ f := ((c ^ d) & b) ^ d
+ a += f + X[x]
+ a = a<<s | a>>(32-s)
+ a, b, c, d = d, a, b, c
+ }
+
+ // Round 2.
+ for i := uint(0); i < 16; i++ {
+ x := xIndex2[i]
+ s := shift2[i%4]
+ g := (b & c) | (b & d) | (c & d)
+ a += g + X[x] + 0x5a827999
+ a = a<<s | a>>(32-s)
+ a, b, c, d = d, a, b, c
+ }
+
+ // Round 3.
+ for i := uint(0); i < 16; i++ {
+ x := xIndex3[i]
+ s := shift3[i%4]
+ h := b ^ c ^ d
+ a += h + X[x] + 0x6ed9eba1
+ a = a<<s | a>>(32-s)
+ a, b, c, d = d, a, b, c
+ }
+
+ a += aa
+ b += bb
+ c += cc
+ d += dd
+
+ p = p[_Chunk:]
+ n += _Chunk
+ }
+
+ dig.s[0] = a
+ dig.s[1] = b
+ dig.s[2] = c
+ dig.s[3] = d
+ return n
+}
diff --git a/vendor/golang.org/x/crypto/nacl/secretbox/secretbox.go b/vendor/golang.org/x/crypto/nacl/secretbox/secretbox.go
new file mode 100644
index 0000000..1e1dff5
--- /dev/null
+++ b/vendor/golang.org/x/crypto/nacl/secretbox/secretbox.go
@@ -0,0 +1,149 @@
+// 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 secretbox encrypts and authenticates small messages.
+
+Secretbox uses XSalsa20 and Poly1305 to encrypt and authenticate messages with
+secret-key cryptography. The length of messages is not hidden.
+
+It is the caller's responsibility to ensure the uniqueness of nonces—for
+example, by using nonce 1 for the first message, nonce 2 for the second
+message, etc. Nonces are long enough that randomly generated nonces have
+negligible risk of collision.
+
+This package is interoperable with NaCl: https://nacl.cr.yp.to/secretbox.html.
+*/
+package secretbox // import "golang.org/x/crypto/nacl/secretbox"
+
+import (
+ "golang.org/x/crypto/poly1305"
+ "golang.org/x/crypto/salsa20/salsa"
+)
+
+// Overhead is the number of bytes of overhead when boxing a message.
+const Overhead = poly1305.TagSize
+
+// setup produces a sub-key and Salsa20 counter given a nonce and key.
+func setup(subKey *[32]byte, counter *[16]byte, nonce *[24]byte, key *[32]byte) {
+ // We use XSalsa20 for encryption so first we need to generate a
+ // key and nonce with HSalsa20.
+ var hNonce [16]byte
+ copy(hNonce[:], nonce[:])
+ salsa.HSalsa20(subKey, &hNonce, key, &salsa.Sigma)
+
+ // The final 8 bytes of the original nonce form the new nonce.
+ copy(counter[:], nonce[16:])
+}
+
+// sliceForAppend takes a slice and a requested number of bytes. It returns a
+// slice with the contents of the given slice followed by that many bytes and a
+// second slice that aliases into it and contains only the extra bytes. If the
+// original slice has sufficient capacity then no allocation is performed.
+func sliceForAppend(in []byte, n int) (head, tail []byte) {
+ if total := len(in) + n; cap(in) >= total {
+ head = in[:total]
+ } else {
+ head = make([]byte, total)
+ copy(head, in)
+ }
+ tail = head[len(in):]
+ return
+}
+
+// Seal appends an encrypted and authenticated copy of message to out, which
+// must not overlap message. The key and nonce pair must be unique for each
+// distinct message and the output will be Overhead bytes longer than message.
+func Seal(out, message []byte, nonce *[24]byte, key *[32]byte) []byte {
+ var subKey [32]byte
+ var counter [16]byte
+ setup(&subKey, &counter, nonce, key)
+
+ // The Poly1305 key is generated by encrypting 32 bytes of zeros. Since
+ // Salsa20 works with 64-byte blocks, we also generate 32 bytes of
+ // keystream as a side effect.
+ var firstBlock [64]byte
+ salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey)
+
+ var poly1305Key [32]byte
+ copy(poly1305Key[:], firstBlock[:])
+
+ ret, out := sliceForAppend(out, len(message)+poly1305.TagSize)
+
+ // We XOR up to 32 bytes of message with the keystream generated from
+ // the first block.
+ firstMessageBlock := message
+ if len(firstMessageBlock) > 32 {
+ firstMessageBlock = firstMessageBlock[:32]
+ }
+
+ tagOut := out
+ out = out[poly1305.TagSize:]
+ for i, x := range firstMessageBlock {
+ out[i] = firstBlock[32+i] ^ x
+ }
+ message = message[len(firstMessageBlock):]
+ ciphertext := out
+ out = out[len(firstMessageBlock):]
+
+ // Now encrypt the rest.
+ counter[8] = 1
+ salsa.XORKeyStream(out, message, &counter, &subKey)
+
+ var tag [poly1305.TagSize]byte
+ poly1305.Sum(&tag, ciphertext, &poly1305Key)
+ copy(tagOut, tag[:])
+
+ return ret
+}
+
+// Open authenticates and decrypts a box produced by Seal and appends the
+// message to out, which must not overlap box. The output will be Overhead
+// bytes smaller than box.
+func Open(out []byte, box []byte, nonce *[24]byte, key *[32]byte) ([]byte, bool) {
+ if len(box) < Overhead {
+ return nil, false
+ }
+
+ var subKey [32]byte
+ var counter [16]byte
+ setup(&subKey, &counter, nonce, key)
+
+ // The Poly1305 key is generated by encrypting 32 bytes of zeros. Since
+ // Salsa20 works with 64-byte blocks, we also generate 32 bytes of
+ // keystream as a side effect.
+ var firstBlock [64]byte
+ salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey)
+
+ var poly1305Key [32]byte
+ copy(poly1305Key[:], firstBlock[:])
+ var tag [poly1305.TagSize]byte
+ copy(tag[:], box)
+
+ if !poly1305.Verify(&tag, box[poly1305.TagSize:], &poly1305Key) {
+ return nil, false
+ }
+
+ ret, out := sliceForAppend(out, len(box)-Overhead)
+
+ // We XOR up to 32 bytes of box with the keystream generated from
+ // the first block.
+ box = box[Overhead:]
+ firstMessageBlock := box
+ if len(firstMessageBlock) > 32 {
+ firstMessageBlock = firstMessageBlock[:32]
+ }
+ for i, x := range firstMessageBlock {
+ out[i] = firstBlock[32+i] ^ x
+ }
+
+ box = box[len(firstMessageBlock):]
+ out = out[len(firstMessageBlock):]
+
+ // Now decrypt the rest.
+ counter[8] = 1
+ salsa.XORKeyStream(out, box, &counter, &subKey)
+
+ return ret, true
+}
diff --git a/vendor/golang.org/x/crypto/pkcs12/bmp-string.go b/vendor/golang.org/x/crypto/pkcs12/bmp-string.go
new file mode 100644
index 0000000..233b8b6
--- /dev/null
+++ b/vendor/golang.org/x/crypto/pkcs12/bmp-string.go
@@ -0,0 +1,50 @@
+// Copyright 2015 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 pkcs12
+
+import (
+ "errors"
+ "unicode/utf16"
+)
+
+// bmpString returns s encoded in UCS-2 with a zero terminator.
+func bmpString(s string) ([]byte, error) {
+ // References:
+ // https://tools.ietf.org/html/rfc7292#appendix-B.1
+ // https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane
+ // - non-BMP characters are encoded in UTF 16 by using a surrogate pair of 16-bit codes
+ // EncodeRune returns 0xfffd if the rune does not need special encoding
+ // - the above RFC provides the info that BMPStrings are NULL terminated.
+
+ ret := make([]byte, 0, 2*len(s)+2)
+
+ for _, r := range s {
+ if t, _ := utf16.EncodeRune(r); t != 0xfffd {
+ return nil, errors.New("pkcs12: string contains characters that cannot be encoded in UCS-2")
+ }
+ ret = append(ret, byte(r/256), byte(r%256))
+ }
+
+ return append(ret, 0, 0), nil
+}
+
+func decodeBMPString(bmpString []byte) (string, error) {
+ if len(bmpString)%2 != 0 {
+ return "", errors.New("pkcs12: odd-length BMP string")
+ }
+
+ // strip terminator if present
+ if l := len(bmpString); l >= 2 && bmpString[l-1] == 0 && bmpString[l-2] == 0 {
+ bmpString = bmpString[:l-2]
+ }
+
+ s := make([]uint16, 0, len(bmpString)/2)
+ for len(bmpString) > 0 {
+ s = append(s, uint16(bmpString[0])<<8+uint16(bmpString[1]))
+ bmpString = bmpString[2:]
+ }
+
+ return string(utf16.Decode(s)), nil
+}
diff --git a/vendor/golang.org/x/crypto/pkcs12/crypto.go b/vendor/golang.org/x/crypto/pkcs12/crypto.go
new file mode 100644
index 0000000..4bd4470
--- /dev/null
+++ b/vendor/golang.org/x/crypto/pkcs12/crypto.go
@@ -0,0 +1,131 @@
+// Copyright 2015 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 pkcs12
+
+import (
+ "bytes"
+ "crypto/cipher"
+ "crypto/des"
+ "crypto/x509/pkix"
+ "encoding/asn1"
+ "errors"
+
+ "golang.org/x/crypto/pkcs12/internal/rc2"
+)
+
+var (
+ oidPBEWithSHAAnd3KeyTripleDESCBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3})
+ oidPBEWithSHAAnd40BitRC2CBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 6})
+)
+
+// pbeCipher is an abstraction of a PKCS#12 cipher.
+type pbeCipher interface {
+ // create returns a cipher.Block given a key.
+ create(key []byte) (cipher.Block, error)
+ // deriveKey returns a key derived from the given password and salt.
+ deriveKey(salt, password []byte, iterations int) []byte
+ // deriveKey returns an IV derived from the given password and salt.
+ deriveIV(salt, password []byte, iterations int) []byte
+}
+
+type shaWithTripleDESCBC struct{}
+
+func (shaWithTripleDESCBC) create(key []byte) (cipher.Block, error) {
+ return des.NewTripleDESCipher(key)
+}
+
+func (shaWithTripleDESCBC) deriveKey(salt, password []byte, iterations int) []byte {
+ return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 24)
+}
+
+func (shaWithTripleDESCBC) deriveIV(salt, password []byte, iterations int) []byte {
+ return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8)
+}
+
+type shaWith40BitRC2CBC struct{}
+
+func (shaWith40BitRC2CBC) create(key []byte) (cipher.Block, error) {
+ return rc2.New(key, len(key)*8)
+}
+
+func (shaWith40BitRC2CBC) deriveKey(salt, password []byte, iterations int) []byte {
+ return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 5)
+}
+
+func (shaWith40BitRC2CBC) deriveIV(salt, password []byte, iterations int) []byte {
+ return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8)
+}
+
+type pbeParams struct {
+ Salt []byte
+ Iterations int
+}
+
+func pbDecrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.BlockMode, int, error) {
+ var cipherType pbeCipher
+
+ switch {
+ case algorithm.Algorithm.Equal(oidPBEWithSHAAnd3KeyTripleDESCBC):
+ cipherType = shaWithTripleDESCBC{}
+ case algorithm.Algorithm.Equal(oidPBEWithSHAAnd40BitRC2CBC):
+ cipherType = shaWith40BitRC2CBC{}
+ default:
+ return nil, 0, NotImplementedError("algorithm " + algorithm.Algorithm.String() + " is not supported")
+ }
+
+ var params pbeParams
+ if err := unmarshal(algorithm.Parameters.FullBytes, &params); err != nil {
+ return nil, 0, err
+ }
+
+ key := cipherType.deriveKey(params.Salt, password, params.Iterations)
+ iv := cipherType.deriveIV(params.Salt, password, params.Iterations)
+
+ block, err := cipherType.create(key)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ return cipher.NewCBCDecrypter(block, iv), block.BlockSize(), nil
+}
+
+func pbDecrypt(info decryptable, password []byte) (decrypted []byte, err error) {
+ cbc, blockSize, err := pbDecrypterFor(info.Algorithm(), password)
+ if err != nil {
+ return nil, err
+ }
+
+ encrypted := info.Data()
+ if len(encrypted) == 0 {
+ return nil, errors.New("pkcs12: empty encrypted data")
+ }
+ if len(encrypted)%blockSize != 0 {
+ return nil, errors.New("pkcs12: input is not a multiple of the block size")
+ }
+ decrypted = make([]byte, len(encrypted))
+ cbc.CryptBlocks(decrypted, encrypted)
+
+ psLen := int(decrypted[len(decrypted)-1])
+ if psLen == 0 || psLen > blockSize {
+ return nil, ErrDecryption
+ }
+
+ if len(decrypted) < psLen {
+ return nil, ErrDecryption
+ }
+ ps := decrypted[len(decrypted)-psLen:]
+ decrypted = decrypted[:len(decrypted)-psLen]
+ if bytes.Compare(ps, bytes.Repeat([]byte{byte(psLen)}, psLen)) != 0 {
+ return nil, ErrDecryption
+ }
+
+ return
+}
+
+// decryptable abstracts a object that contains ciphertext.
+type decryptable interface {
+ Algorithm() pkix.AlgorithmIdentifier
+ Data() []byte
+}
diff --git a/vendor/golang.org/x/crypto/pkcs12/errors.go b/vendor/golang.org/x/crypto/pkcs12/errors.go
new file mode 100644
index 0000000..7377ce6
--- /dev/null
+++ b/vendor/golang.org/x/crypto/pkcs12/errors.go
@@ -0,0 +1,23 @@
+// Copyright 2015 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 pkcs12
+
+import "errors"
+
+var (
+ // ErrDecryption represents a failure to decrypt the input.
+ ErrDecryption = errors.New("pkcs12: decryption error, incorrect padding")
+
+ // ErrIncorrectPassword is returned when an incorrect password is detected.
+ // Usually, P12/PFX data is signed to be able to verify the password.
+ ErrIncorrectPassword = errors.New("pkcs12: decryption password incorrect")
+)
+
+// NotImplementedError indicates that the input is not currently supported.
+type NotImplementedError string
+
+func (e NotImplementedError) Error() string {
+ return "pkcs12: " + string(e)
+}
diff --git a/vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go b/vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go
new file mode 100644
index 0000000..8c70902
--- /dev/null
+++ b/vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go
@@ -0,0 +1,274 @@
+// Copyright 2015 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 rc2 implements the RC2 cipher
+/*
+https://www.ietf.org/rfc/rfc2268.txt
+http://people.csail.mit.edu/rivest/pubs/KRRR98.pdf
+
+This code is licensed under the MIT license.
+*/
+package rc2
+
+import (
+ "crypto/cipher"
+ "encoding/binary"
+)
+
+// The rc2 block size in bytes
+const BlockSize = 8
+
+type rc2Cipher struct {
+ k [64]uint16
+}
+
+// New returns a new rc2 cipher with the given key and effective key length t1
+func New(key []byte, t1 int) (cipher.Block, error) {
+ // TODO(dgryski): error checking for key length
+ return &rc2Cipher{
+ k: expandKey(key, t1),
+ }, nil
+}
+
+func (*rc2Cipher) BlockSize() int { return BlockSize }
+
+var piTable = [256]byte{
+ 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,
+ 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,
+ 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,
+ 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,
+ 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,
+ 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,
+ 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,
+ 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,
+ 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,
+ 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,
+ 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,
+ 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,
+ 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,
+ 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,
+ 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,
+ 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad,
+}
+
+func expandKey(key []byte, t1 int) [64]uint16 {
+
+ l := make([]byte, 128)
+ copy(l, key)
+
+ var t = len(key)
+ var t8 = (t1 + 7) / 8
+ var tm = byte(255 % uint(1<<(8+uint(t1)-8*uint(t8))))
+
+ for i := len(key); i < 128; i++ {
+ l[i] = piTable[l[i-1]+l[uint8(i-t)]]
+ }
+
+ l[128-t8] = piTable[l[128-t8]&tm]
+
+ for i := 127 - t8; i >= 0; i-- {
+ l[i] = piTable[l[i+1]^l[i+t8]]
+ }
+
+ var k [64]uint16
+
+ for i := range k {
+ k[i] = uint16(l[2*i]) + uint16(l[2*i+1])*256
+ }
+
+ return k
+}
+
+func rotl16(x uint16, b uint) uint16 {
+ return (x >> (16 - b)) | (x << b)
+}
+
+func (c *rc2Cipher) Encrypt(dst, src []byte) {
+
+ r0 := binary.LittleEndian.Uint16(src[0:])
+ r1 := binary.LittleEndian.Uint16(src[2:])
+ r2 := binary.LittleEndian.Uint16(src[4:])
+ r3 := binary.LittleEndian.Uint16(src[6:])
+
+ var j int
+
+ for j <= 16 {
+ // mix r0
+ r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1)
+ r0 = rotl16(r0, 1)
+ j++
+
+ // mix r1
+ r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2)
+ r1 = rotl16(r1, 2)
+ j++
+
+ // mix r2
+ r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3)
+ r2 = rotl16(r2, 3)
+ j++
+
+ // mix r3
+ r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0)
+ r3 = rotl16(r3, 5)
+ j++
+
+ }
+
+ r0 = r0 + c.k[r3&63]
+ r1 = r1 + c.k[r0&63]
+ r2 = r2 + c.k[r1&63]
+ r3 = r3 + c.k[r2&63]
+
+ for j <= 40 {
+
+ // mix r0
+ r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1)
+ r0 = rotl16(r0, 1)
+ j++
+
+ // mix r1
+ r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2)
+ r1 = rotl16(r1, 2)
+ j++
+
+ // mix r2
+ r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3)
+ r2 = rotl16(r2, 3)
+ j++
+
+ // mix r3
+ r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0)
+ r3 = rotl16(r3, 5)
+ j++
+
+ }
+
+ r0 = r0 + c.k[r3&63]
+ r1 = r1 + c.k[r0&63]
+ r2 = r2 + c.k[r1&63]
+ r3 = r3 + c.k[r2&63]
+
+ for j <= 60 {
+
+ // mix r0
+ r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1)
+ r0 = rotl16(r0, 1)
+ j++
+
+ // mix r1
+ r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2)
+ r1 = rotl16(r1, 2)
+ j++
+
+ // mix r2
+ r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3)
+ r2 = rotl16(r2, 3)
+ j++
+
+ // mix r3
+ r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0)
+ r3 = rotl16(r3, 5)
+ j++
+ }
+
+ binary.LittleEndian.PutUint16(dst[0:], r0)
+ binary.LittleEndian.PutUint16(dst[2:], r1)
+ binary.LittleEndian.PutUint16(dst[4:], r2)
+ binary.LittleEndian.PutUint16(dst[6:], r3)
+}
+
+func (c *rc2Cipher) Decrypt(dst, src []byte) {
+
+ r0 := binary.LittleEndian.Uint16(src[0:])
+ r1 := binary.LittleEndian.Uint16(src[2:])
+ r2 := binary.LittleEndian.Uint16(src[4:])
+ r3 := binary.LittleEndian.Uint16(src[6:])
+
+ j := 63
+
+ for j >= 44 {
+ // unmix r3
+ r3 = rotl16(r3, 16-5)
+ r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0)
+ j--
+
+ // unmix r2
+ r2 = rotl16(r2, 16-3)
+ r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3)
+ j--
+
+ // unmix r1
+ r1 = rotl16(r1, 16-2)
+ r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2)
+ j--
+
+ // unmix r0
+ r0 = rotl16(r0, 16-1)
+ r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1)
+ j--
+ }
+
+ r3 = r3 - c.k[r2&63]
+ r2 = r2 - c.k[r1&63]
+ r1 = r1 - c.k[r0&63]
+ r0 = r0 - c.k[r3&63]
+
+ for j >= 20 {
+ // unmix r3
+ r3 = rotl16(r3, 16-5)
+ r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0)
+ j--
+
+ // unmix r2
+ r2 = rotl16(r2, 16-3)
+ r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3)
+ j--
+
+ // unmix r1
+ r1 = rotl16(r1, 16-2)
+ r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2)
+ j--
+
+ // unmix r0
+ r0 = rotl16(r0, 16-1)
+ r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1)
+ j--
+
+ }
+
+ r3 = r3 - c.k[r2&63]
+ r2 = r2 - c.k[r1&63]
+ r1 = r1 - c.k[r0&63]
+ r0 = r0 - c.k[r3&63]
+
+ for j >= 0 {
+
+ // unmix r3
+ r3 = rotl16(r3, 16-5)
+ r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0)
+ j--
+
+ // unmix r2
+ r2 = rotl16(r2, 16-3)
+ r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3)
+ j--
+
+ // unmix r1
+ r1 = rotl16(r1, 16-2)
+ r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2)
+ j--
+
+ // unmix r0
+ r0 = rotl16(r0, 16-1)
+ r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1)
+ j--
+
+ }
+
+ binary.LittleEndian.PutUint16(dst[0:], r0)
+ binary.LittleEndian.PutUint16(dst[2:], r1)
+ binary.LittleEndian.PutUint16(dst[4:], r2)
+ binary.LittleEndian.PutUint16(dst[6:], r3)
+}
diff --git a/vendor/golang.org/x/crypto/pkcs12/mac.go b/vendor/golang.org/x/crypto/pkcs12/mac.go
new file mode 100644
index 0000000..5f38aa7
--- /dev/null
+++ b/vendor/golang.org/x/crypto/pkcs12/mac.go
@@ -0,0 +1,45 @@
+// Copyright 2015 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 pkcs12
+
+import (
+ "crypto/hmac"
+ "crypto/sha1"
+ "crypto/x509/pkix"
+ "encoding/asn1"
+)
+
+type macData struct {
+ Mac digestInfo
+ MacSalt []byte
+ Iterations int `asn1:"optional,default:1"`
+}
+
+// from PKCS#7:
+type digestInfo struct {
+ Algorithm pkix.AlgorithmIdentifier
+ Digest []byte
+}
+
+var (
+ oidSHA1 = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26})
+)
+
+func verifyMac(macData *macData, message, password []byte) error {
+ if !macData.Mac.Algorithm.Algorithm.Equal(oidSHA1) {
+ return NotImplementedError("unknown digest algorithm: " + macData.Mac.Algorithm.Algorithm.String())
+ }
+
+ key := pbkdf(sha1Sum, 20, 64, macData.MacSalt, password, macData.Iterations, 3, 20)
+
+ mac := hmac.New(sha1.New, key)
+ mac.Write(message)
+ expectedMAC := mac.Sum(nil)
+
+ if !hmac.Equal(macData.Mac.Digest, expectedMAC) {
+ return ErrIncorrectPassword
+ }
+ return nil
+}
diff --git a/vendor/golang.org/x/crypto/pkcs12/pbkdf.go b/vendor/golang.org/x/crypto/pkcs12/pbkdf.go
new file mode 100644
index 0000000..5c419d4
--- /dev/null
+++ b/vendor/golang.org/x/crypto/pkcs12/pbkdf.go
@@ -0,0 +1,170 @@
+// Copyright 2015 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 pkcs12
+
+import (
+ "bytes"
+ "crypto/sha1"
+ "math/big"
+)
+
+var (
+ one = big.NewInt(1)
+)
+
+// sha1Sum returns the SHA-1 hash of in.
+func sha1Sum(in []byte) []byte {
+ sum := sha1.Sum(in)
+ return sum[:]
+}
+
+// fillWithRepeats returns v*ceiling(len(pattern) / v) bytes consisting of
+// repeats of pattern.
+func fillWithRepeats(pattern []byte, v int) []byte {
+ if len(pattern) == 0 {
+ return nil
+ }
+ outputLen := v * ((len(pattern) + v - 1) / v)
+ return bytes.Repeat(pattern, (outputLen+len(pattern)-1)/len(pattern))[:outputLen]
+}
+
+func pbkdf(hash func([]byte) []byte, u, v int, salt, password []byte, r int, ID byte, size int) (key []byte) {
+ // implementation of https://tools.ietf.org/html/rfc7292#appendix-B.2 , RFC text verbatim in comments
+
+ // Let H be a hash function built around a compression function f:
+
+ // Z_2^u x Z_2^v -> Z_2^u
+
+ // (that is, H has a chaining variable and output of length u bits, and
+ // the message input to the compression function of H is v bits). The
+ // values for u and v are as follows:
+
+ // HASH FUNCTION VALUE u VALUE v
+ // MD2, MD5 128 512
+ // SHA-1 160 512
+ // SHA-224 224 512
+ // SHA-256 256 512
+ // SHA-384 384 1024
+ // SHA-512 512 1024
+ // SHA-512/224 224 1024
+ // SHA-512/256 256 1024
+
+ // Furthermore, let r be the iteration count.
+
+ // We assume here that u and v are both multiples of 8, as are the
+ // lengths of the password and salt strings (which we denote by p and s,
+ // respectively) and the number n of pseudorandom bits required. In
+ // addition, u and v are of course non-zero.
+
+ // For information on security considerations for MD5 [19], see [25] and
+ // [1], and on those for MD2, see [18].
+
+ // The following procedure can be used to produce pseudorandom bits for
+ // a particular "purpose" that is identified by a byte called "ID".
+ // This standard specifies 3 different values for the ID byte:
+
+ // 1. If ID=1, then the pseudorandom bits being produced are to be used
+ // as key material for performing encryption or decryption.
+
+ // 2. If ID=2, then the pseudorandom bits being produced are to be used
+ // as an IV (Initial Value) for encryption or decryption.
+
+ // 3. If ID=3, then the pseudorandom bits being produced are to be used
+ // as an integrity key for MACing.
+
+ // 1. Construct a string, D (the "diversifier"), by concatenating v/8
+ // copies of ID.
+ var D []byte
+ for i := 0; i < v; i++ {
+ D = append(D, ID)
+ }
+
+ // 2. Concatenate copies of the salt together to create a string S of
+ // length v(ceiling(s/v)) bits (the final copy of the salt may be
+ // truncated to create S). Note that if the salt is the empty
+ // string, then so is S.
+
+ S := fillWithRepeats(salt, v)
+
+ // 3. Concatenate copies of the password together to create a string P
+ // of length v(ceiling(p/v)) bits (the final copy of the password
+ // may be truncated to create P). Note that if the password is the
+ // empty string, then so is P.
+
+ P := fillWithRepeats(password, v)
+
+ // 4. Set I=S||P to be the concatenation of S and P.
+ I := append(S, P...)
+
+ // 5. Set c=ceiling(n/u).
+ c := (size + u - 1) / u
+
+ // 6. For i=1, 2, ..., c, do the following:
+ A := make([]byte, c*20)
+ var IjBuf []byte
+ for i := 0; i < c; i++ {
+ // A. Set A2=H^r(D||I). (i.e., the r-th hash of D||1,
+ // H(H(H(... H(D||I))))
+ Ai := hash(append(D, I...))
+ for j := 1; j < r; j++ {
+ Ai = hash(Ai)
+ }
+ copy(A[i*20:], Ai[:])
+
+ if i < c-1 { // skip on last iteration
+ // B. Concatenate copies of Ai to create a string B of length v
+ // bits (the final copy of Ai may be truncated to create B).
+ var B []byte
+ for len(B) < v {
+ B = append(B, Ai[:]...)
+ }
+ B = B[:v]
+
+ // C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit
+ // blocks, where k=ceiling(s/v)+ceiling(p/v), modify I by
+ // setting I_j=(I_j+B+1) mod 2^v for each j.
+ {
+ Bbi := new(big.Int).SetBytes(B)
+ Ij := new(big.Int)
+
+ for j := 0; j < len(I)/v; j++ {
+ Ij.SetBytes(I[j*v : (j+1)*v])
+ Ij.Add(Ij, Bbi)
+ Ij.Add(Ij, one)
+ Ijb := Ij.Bytes()
+ // We expect Ijb to be exactly v bytes,
+ // if it is longer or shorter we must
+ // adjust it accordingly.
+ if len(Ijb) > v {
+ Ijb = Ijb[len(Ijb)-v:]
+ }
+ if len(Ijb) < v {
+ if IjBuf == nil {
+ IjBuf = make([]byte, v)
+ }
+ bytesShort := v - len(Ijb)
+ for i := 0; i < bytesShort; i++ {
+ IjBuf[i] = 0
+ }
+ copy(IjBuf[bytesShort:], Ijb)
+ Ijb = IjBuf
+ }
+ copy(I[j*v:(j+1)*v], Ijb)
+ }
+ }
+ }
+ }
+ // 7. Concatenate A_1, A_2, ..., A_c together to form a pseudorandom
+ // bit string, A.
+
+ // 8. Use the first n bits of A as the output of this entire process.
+ return A[:size]
+
+ // If the above process is being used to generate a DES key, the process
+ // should be used to create 64 random bits, and the key's parity bits
+ // should be set after the 64 bits have been produced. Similar concerns
+ // hold for 2-key and 3-key triple-DES keys, for CDMF keys, and for any
+ // similar keys with parity bits "built into them".
+}
diff --git a/vendor/golang.org/x/crypto/pkcs12/pkcs12.go b/vendor/golang.org/x/crypto/pkcs12/pkcs12.go
new file mode 100644
index 0000000..eff9ad3
--- /dev/null
+++ b/vendor/golang.org/x/crypto/pkcs12/pkcs12.go
@@ -0,0 +1,346 @@
+// Copyright 2015 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 pkcs12 implements some of PKCS#12.
+//
+// This implementation is distilled from https://tools.ietf.org/html/rfc7292
+// and referenced documents. It is intended for decoding P12/PFX-stored
+// certificates and keys for use with the crypto/tls package.
+package pkcs12
+
+import (
+ "crypto/ecdsa"
+ "crypto/rsa"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/asn1"
+ "encoding/hex"
+ "encoding/pem"
+ "errors"
+)
+
+var (
+ oidDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 1})
+ oidEncryptedDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 6})
+
+ oidFriendlyName = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 20})
+ oidLocalKeyID = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 21})
+ oidMicrosoftCSPName = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 4, 1, 311, 17, 1})
+)
+
+type pfxPdu struct {
+ Version int
+ AuthSafe contentInfo
+ MacData macData `asn1:"optional"`
+}
+
+type contentInfo struct {
+ ContentType asn1.ObjectIdentifier
+ Content asn1.RawValue `asn1:"tag:0,explicit,optional"`
+}
+
+type encryptedData struct {
+ Version int
+ EncryptedContentInfo encryptedContentInfo
+}
+
+type encryptedContentInfo struct {
+ ContentType asn1.ObjectIdentifier
+ ContentEncryptionAlgorithm pkix.AlgorithmIdentifier
+ EncryptedContent []byte `asn1:"tag:0,optional"`
+}
+
+func (i encryptedContentInfo) Algorithm() pkix.AlgorithmIdentifier {
+ return i.ContentEncryptionAlgorithm
+}
+
+func (i encryptedContentInfo) Data() []byte { return i.EncryptedContent }
+
+type safeBag struct {
+ Id asn1.ObjectIdentifier
+ Value asn1.RawValue `asn1:"tag:0,explicit"`
+ Attributes []pkcs12Attribute `asn1:"set,optional"`
+}
+
+type pkcs12Attribute struct {
+ Id asn1.ObjectIdentifier
+ Value asn1.RawValue `asn1:"set"`
+}
+
+type encryptedPrivateKeyInfo struct {
+ AlgorithmIdentifier pkix.AlgorithmIdentifier
+ EncryptedData []byte
+}
+
+func (i encryptedPrivateKeyInfo) Algorithm() pkix.AlgorithmIdentifier {
+ return i.AlgorithmIdentifier
+}
+
+func (i encryptedPrivateKeyInfo) Data() []byte {
+ return i.EncryptedData
+}
+
+// PEM block types
+const (
+ certificateType = "CERTIFICATE"
+ privateKeyType = "PRIVATE KEY"
+)
+
+// unmarshal calls asn1.Unmarshal, but also returns an error if there is any
+// trailing data after unmarshaling.
+func unmarshal(in []byte, out interface{}) error {
+ trailing, err := asn1.Unmarshal(in, out)
+ if err != nil {
+ return err
+ }
+ if len(trailing) != 0 {
+ return errors.New("pkcs12: trailing data found")
+ }
+ return nil
+}
+
+// ConvertToPEM converts all "safe bags" contained in pfxData to PEM blocks.
+func ToPEM(pfxData []byte, password string) ([]*pem.Block, error) {
+ encodedPassword, err := bmpString(password)
+ if err != nil {
+ return nil, ErrIncorrectPassword
+ }
+
+ bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword)
+
+ if err != nil {
+ return nil, err
+ }
+
+ blocks := make([]*pem.Block, 0, len(bags))
+ for _, bag := range bags {
+ block, err := convertBag(&bag, encodedPassword)
+ if err != nil {
+ return nil, err
+ }
+ blocks = append(blocks, block)
+ }
+
+ return blocks, nil
+}
+
+func convertBag(bag *safeBag, password []byte) (*pem.Block, error) {
+ block := &pem.Block{
+ Headers: make(map[string]string),
+ }
+
+ for _, attribute := range bag.Attributes {
+ k, v, err := convertAttribute(&attribute)
+ if err != nil {
+ return nil, err
+ }
+ block.Headers[k] = v
+ }
+
+ switch {
+ case bag.Id.Equal(oidCertBag):
+ block.Type = certificateType
+ certsData, err := decodeCertBag(bag.Value.Bytes)
+ if err != nil {
+ return nil, err
+ }
+ block.Bytes = certsData
+ case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
+ block.Type = privateKeyType
+
+ key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, password)
+ if err != nil {
+ return nil, err
+ }
+
+ switch key := key.(type) {
+ case *rsa.PrivateKey:
+ block.Bytes = x509.MarshalPKCS1PrivateKey(key)
+ case *ecdsa.PrivateKey:
+ block.Bytes, err = x509.MarshalECPrivateKey(key)
+ if err != nil {
+ return nil, err
+ }
+ default:
+ return nil, errors.New("found unknown private key type in PKCS#8 wrapping")
+ }
+ default:
+ return nil, errors.New("don't know how to convert a safe bag of type " + bag.Id.String())
+ }
+ return block, nil
+}
+
+func convertAttribute(attribute *pkcs12Attribute) (key, value string, err error) {
+ isString := false
+
+ switch {
+ case attribute.Id.Equal(oidFriendlyName):
+ key = "friendlyName"
+ isString = true
+ case attribute.Id.Equal(oidLocalKeyID):
+ key = "localKeyId"
+ case attribute.Id.Equal(oidMicrosoftCSPName):
+ // This key is chosen to match OpenSSL.
+ key = "Microsoft CSP Name"
+ isString = true
+ default:
+ return "", "", errors.New("pkcs12: unknown attribute with OID " + attribute.Id.String())
+ }
+
+ if isString {
+ if err := unmarshal(attribute.Value.Bytes, &attribute.Value); err != nil {
+ return "", "", err
+ }
+ if value, err = decodeBMPString(attribute.Value.Bytes); err != nil {
+ return "", "", err
+ }
+ } else {
+ var id []byte
+ if err := unmarshal(attribute.Value.Bytes, &id); err != nil {
+ return "", "", err
+ }
+ value = hex.EncodeToString(id)
+ }
+
+ return key, value, nil
+}
+
+// Decode extracts a certificate and private key from pfxData. This function
+// assumes that there is only one certificate and only one private key in the
+// pfxData.
+func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) {
+ encodedPassword, err := bmpString(password)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ if len(bags) != 2 {
+ err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU")
+ return
+ }
+
+ for _, bag := range bags {
+ switch {
+ case bag.Id.Equal(oidCertBag):
+ if certificate != nil {
+ err = errors.New("pkcs12: expected exactly one certificate bag")
+ }
+
+ certsData, err := decodeCertBag(bag.Value.Bytes)
+ if err != nil {
+ return nil, nil, err
+ }
+ certs, err := x509.ParseCertificates(certsData)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(certs) != 1 {
+ err = errors.New("pkcs12: expected exactly one certificate in the certBag")
+ return nil, nil, err
+ }
+ certificate = certs[0]
+
+ case bag.Id.Equal(oidPKCS8ShroundedKeyBag):
+ if privateKey != nil {
+ err = errors.New("pkcs12: expected exactly one key bag")
+ }
+
+ if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil {
+ return nil, nil, err
+ }
+ }
+ }
+
+ if certificate == nil {
+ return nil, nil, errors.New("pkcs12: certificate missing")
+ }
+ if privateKey == nil {
+ return nil, nil, errors.New("pkcs12: private key missing")
+ }
+
+ return
+}
+
+func getSafeContents(p12Data, password []byte) (bags []safeBag, updatedPassword []byte, err error) {
+ pfx := new(pfxPdu)
+ if err := unmarshal(p12Data, pfx); err != nil {
+ return nil, nil, errors.New("pkcs12: error reading P12 data: " + err.Error())
+ }
+
+ if pfx.Version != 3 {
+ return nil, nil, NotImplementedError("can only decode v3 PFX PDU's")
+ }
+
+ if !pfx.AuthSafe.ContentType.Equal(oidDataContentType) {
+ return nil, nil, NotImplementedError("only password-protected PFX is implemented")
+ }
+
+ // unmarshal the explicit bytes in the content for type 'data'
+ if err := unmarshal(pfx.AuthSafe.Content.Bytes, &pfx.AuthSafe.Content); err != nil {
+ return nil, nil, err
+ }
+
+ if len(pfx.MacData.Mac.Algorithm.Algorithm) == 0 {
+ return nil, nil, errors.New("pkcs12: no MAC in data")
+ }
+
+ if err := verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password); err != nil {
+ if err == ErrIncorrectPassword && len(password) == 2 && password[0] == 0 && password[1] == 0 {
+ // some implementations use an empty byte array
+ // for the empty string password try one more
+ // time with empty-empty password
+ password = nil
+ err = verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password)
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+ }
+
+ var authenticatedSafe []contentInfo
+ if err := unmarshal(pfx.AuthSafe.Content.Bytes, &authenticatedSafe); err != nil {
+ return nil, nil, err
+ }
+
+ if len(authenticatedSafe) != 2 {
+ return nil, nil, NotImplementedError("expected exactly two items in the authenticated safe")
+ }
+
+ for _, ci := range authenticatedSafe {
+ var data []byte
+
+ switch {
+ case ci.ContentType.Equal(oidDataContentType):
+ if err := unmarshal(ci.Content.Bytes, &data); err != nil {
+ return nil, nil, err
+ }
+ case ci.ContentType.Equal(oidEncryptedDataContentType):
+ var encryptedData encryptedData
+ if err := unmarshal(ci.Content.Bytes, &encryptedData); err != nil {
+ return nil, nil, err
+ }
+ if encryptedData.Version != 0 {
+ return nil, nil, NotImplementedError("only version 0 of EncryptedData is supported")
+ }
+ if data, err = pbDecrypt(encryptedData.EncryptedContentInfo, password); err != nil {
+ return nil, nil, err
+ }
+ default:
+ return nil, nil, NotImplementedError("only data and encryptedData content types are supported in authenticated safe")
+ }
+
+ var safeContents []safeBag
+ if err := unmarshal(data, &safeContents); err != nil {
+ return nil, nil, err
+ }
+ bags = append(bags, safeContents...)
+ }
+
+ return bags, password, nil
+}
diff --git a/vendor/golang.org/x/crypto/pkcs12/safebags.go b/vendor/golang.org/x/crypto/pkcs12/safebags.go
new file mode 100644
index 0000000..def1f7b
--- /dev/null
+++ b/vendor/golang.org/x/crypto/pkcs12/safebags.go
@@ -0,0 +1,57 @@
+// Copyright 2015 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 pkcs12
+
+import (
+ "crypto/x509"
+ "encoding/asn1"
+ "errors"
+)
+
+var (
+ // see https://tools.ietf.org/html/rfc7292#appendix-D
+ oidCertTypeX509Certificate = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 22, 1})
+ oidPKCS8ShroundedKeyBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 2})
+ oidCertBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 3})
+)
+
+type certBag struct {
+ Id asn1.ObjectIdentifier
+ Data []byte `asn1:"tag:0,explicit"`
+}
+
+func decodePkcs8ShroudedKeyBag(asn1Data, password []byte) (privateKey interface{}, err error) {
+ pkinfo := new(encryptedPrivateKeyInfo)
+ if err = unmarshal(asn1Data, pkinfo); err != nil {
+ return nil, errors.New("pkcs12: error decoding PKCS#8 shrouded key bag: " + err.Error())
+ }
+
+ pkData, err := pbDecrypt(pkinfo, password)
+ if err != nil {
+ return nil, errors.New("pkcs12: error decrypting PKCS#8 shrouded key bag: " + err.Error())
+ }
+
+ ret := new(asn1.RawValue)
+ if err = unmarshal(pkData, ret); err != nil {
+ return nil, errors.New("pkcs12: error unmarshaling decrypted private key: " + err.Error())
+ }
+
+ if privateKey, err = x509.ParsePKCS8PrivateKey(pkData); err != nil {
+ return nil, errors.New("pkcs12: error parsing PKCS#8 private key: " + err.Error())
+ }
+
+ return privateKey, nil
+}
+
+func decodeCertBag(asn1Data []byte) (x509Certificates []byte, err error) {
+ bag := new(certBag)
+ if err := unmarshal(asn1Data, bag); err != nil {
+ return nil, errors.New("pkcs12: error decoding cert bag: " + err.Error())
+ }
+ if !bag.Id.Equal(oidCertTypeX509Certificate) {
+ return nil, NotImplementedError("only X509 certificates are supported")
+ }
+ return bag.Data, nil
+}
diff --git a/vendor/golang.org/x/crypto/poly1305/poly1305.go b/vendor/golang.org/x/crypto/poly1305/poly1305.go
new file mode 100644
index 0000000..f562fa5
--- /dev/null
+++ b/vendor/golang.org/x/crypto/poly1305/poly1305.go
@@ -0,0 +1,33 @@
+// 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 poly1305 implements Poly1305 one-time message authentication code as
+specified in https://cr.yp.to/mac/poly1305-20050329.pdf.
+
+Poly1305 is a fast, one-time authentication function. It is infeasible for an
+attacker to generate an authenticator for a message without the key. However, a
+key must only be used for a single message. Authenticating two different
+messages with the same key allows an attacker to forge authenticators for other
+messages with the same key.
+
+Poly1305 was originally coupled with AES in order to make Poly1305-AES. AES was
+used with a fixed key in order to generate one-time keys from an nonce.
+However, in this package AES isn't used and the one-time key is specified
+directly.
+*/
+package poly1305 // import "golang.org/x/crypto/poly1305"
+
+import "crypto/subtle"
+
+// TagSize is the size, in bytes, of a poly1305 authenticator.
+const TagSize = 16
+
+// Verify returns true if mac is a valid authenticator for m with the given
+// key.
+func Verify(mac *[16]byte, m []byte, key *[32]byte) bool {
+ var tmp [16]byte
+ Sum(&tmp, m, key)
+ return subtle.ConstantTimeCompare(tmp[:], mac[:]) == 1
+}
diff --git a/vendor/golang.org/x/crypto/poly1305/sum_amd64.go b/vendor/golang.org/x/crypto/poly1305/sum_amd64.go
new file mode 100644
index 0000000..4dd72fe
--- /dev/null
+++ b/vendor/golang.org/x/crypto/poly1305/sum_amd64.go
@@ -0,0 +1,22 @@
+// 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 poly1305
+
+// This function is implemented in sum_amd64.s
+//go:noescape
+func poly1305(out *[16]byte, m *byte, mlen uint64, key *[32]byte)
+
+// Sum generates an authenticator for m using a one-time key and puts the
+// 16-byte result into out. Authenticating two different messages with the same
+// key allows an attacker to forge messages at will.
+func Sum(out *[16]byte, m []byte, key *[32]byte) {
+ var mPtr *byte
+ if len(m) > 0 {
+ mPtr = &m[0]
+ }
+ poly1305(out, mPtr, uint64(len(m)), key)
+}
diff --git a/vendor/golang.org/x/crypto/poly1305/sum_amd64.s b/vendor/golang.org/x/crypto/poly1305/sum_amd64.s
new file mode 100644
index 0000000..2edae63
--- /dev/null
+++ b/vendor/golang.org/x/crypto/poly1305/sum_amd64.s
@@ -0,0 +1,125 @@
+// 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
+
+#include "textflag.h"
+
+#define POLY1305_ADD(msg, h0, h1, h2) \
+ ADDQ 0(msg), h0; \
+ ADCQ 8(msg), h1; \
+ ADCQ $1, h2; \
+ LEAQ 16(msg), msg
+
+#define POLY1305_MUL(h0, h1, h2, r0, r1, t0, t1, t2, t3) \
+ MOVQ r0, AX; \
+ MULQ h0; \
+ MOVQ AX, t0; \
+ MOVQ DX, t1; \
+ MOVQ r0, AX; \
+ MULQ h1; \
+ ADDQ AX, t1; \
+ ADCQ $0, DX; \
+ MOVQ r0, t2; \
+ IMULQ h2, t2; \
+ ADDQ DX, t2; \
+ \
+ MOVQ r1, AX; \
+ MULQ h0; \
+ ADDQ AX, t1; \
+ ADCQ $0, DX; \
+ MOVQ DX, h0; \
+ MOVQ r1, t3; \
+ IMULQ h2, t3; \
+ MOVQ r1, AX; \
+ MULQ h1; \
+ ADDQ AX, t2; \
+ ADCQ DX, t3; \
+ ADDQ h0, t2; \
+ ADCQ $0, t3; \
+ \
+ MOVQ t0, h0; \
+ MOVQ t1, h1; \
+ MOVQ t2, h2; \
+ ANDQ $3, h2; \
+ MOVQ t2, t0; \
+ ANDQ $0xFFFFFFFFFFFFFFFC, t0; \
+ ADDQ t0, h0; \
+ ADCQ t3, h1; \
+ ADCQ $0, h2; \
+ SHRQ $2, t3, t2; \
+ SHRQ $2, t3; \
+ ADDQ t2, h0; \
+ ADCQ t3, h1; \
+ ADCQ $0, h2
+
+DATA ·poly1305Mask<>+0x00(SB)/8, $0x0FFFFFFC0FFFFFFF
+DATA ·poly1305Mask<>+0x08(SB)/8, $0x0FFFFFFC0FFFFFFC
+GLOBL ·poly1305Mask<>(SB), RODATA, $16
+
+// func poly1305(out *[16]byte, m *byte, mlen uint64, key *[32]key)
+TEXT ·poly1305(SB), $0-32
+ MOVQ out+0(FP), DI
+ MOVQ m+8(FP), SI
+ MOVQ mlen+16(FP), R15
+ MOVQ key+24(FP), AX
+
+ MOVQ 0(AX), R11
+ MOVQ 8(AX), R12
+ ANDQ ·poly1305Mask<>(SB), R11 // r0
+ ANDQ ·poly1305Mask<>+8(SB), R12 // r1
+ XORQ R8, R8 // h0
+ XORQ R9, R9 // h1
+ XORQ R10, R10 // h2
+
+ CMPQ R15, $16
+ JB bytes_between_0_and_15
+
+loop:
+ POLY1305_ADD(SI, R8, R9, R10)
+
+multiply:
+ POLY1305_MUL(R8, R9, R10, R11, R12, BX, CX, R13, R14)
+ SUBQ $16, R15
+ CMPQ R15, $16
+ JAE loop
+
+bytes_between_0_and_15:
+ TESTQ R15, R15
+ JZ done
+ MOVQ $1, BX
+ XORQ CX, CX
+ XORQ R13, R13
+ ADDQ R15, SI
+
+flush_buffer:
+ SHLQ $8, BX, CX
+ SHLQ $8, BX
+ MOVB -1(SI), R13
+ XORQ R13, BX
+ DECQ SI
+ DECQ R15
+ JNZ flush_buffer
+
+ ADDQ BX, R8
+ ADCQ CX, R9
+ ADCQ $0, R10
+ MOVQ $16, R15
+ JMP multiply
+
+done:
+ MOVQ R8, AX
+ MOVQ R9, BX
+ SUBQ $0xFFFFFFFFFFFFFFFB, AX
+ SBBQ $0xFFFFFFFFFFFFFFFF, BX
+ SBBQ $3, R10
+ CMOVQCS R8, AX
+ CMOVQCS R9, BX
+ MOVQ key+24(FP), R8
+ ADDQ 16(R8), AX
+ ADCQ 24(R8), BX
+
+ MOVQ AX, 0(DI)
+ MOVQ BX, 8(DI)
+ RET
diff --git a/vendor/golang.org/x/crypto/poly1305/sum_arm.go b/vendor/golang.org/x/crypto/poly1305/sum_arm.go
new file mode 100644
index 0000000..5dc321c
--- /dev/null
+++ b/vendor/golang.org/x/crypto/poly1305/sum_arm.go
@@ -0,0 +1,22 @@
+// Copyright 2015 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 arm,!gccgo,!appengine,!nacl
+
+package poly1305
+
+// This function is implemented in sum_arm.s
+//go:noescape
+func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]byte)
+
+// Sum generates an authenticator for m using a one-time key and puts the
+// 16-byte result into out. Authenticating two different messages with the same
+// key allows an attacker to forge messages at will.
+func Sum(out *[16]byte, m []byte, key *[32]byte) {
+ var mPtr *byte
+ if len(m) > 0 {
+ mPtr = &m[0]
+ }
+ poly1305_auth_armv6(out, mPtr, uint32(len(m)), key)
+}
diff --git a/vendor/golang.org/x/crypto/poly1305/sum_arm.s b/vendor/golang.org/x/crypto/poly1305/sum_arm.s
new file mode 100644
index 0000000..f70b4ac
--- /dev/null
+++ b/vendor/golang.org/x/crypto/poly1305/sum_arm.s
@@ -0,0 +1,427 @@
+// Copyright 2015 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 arm,!gccgo,!appengine,!nacl
+
+#include "textflag.h"
+
+// This code was translated into a form compatible with 5a from the public
+// domain source by Andrew Moon: github.com/floodyberry/poly1305-opt/blob/master/app/extensions/poly1305.
+
+DATA ·poly1305_init_constants_armv6<>+0x00(SB)/4, $0x3ffffff
+DATA ·poly1305_init_constants_armv6<>+0x04(SB)/4, $0x3ffff03
+DATA ·poly1305_init_constants_armv6<>+0x08(SB)/4, $0x3ffc0ff
+DATA ·poly1305_init_constants_armv6<>+0x0c(SB)/4, $0x3f03fff
+DATA ·poly1305_init_constants_armv6<>+0x10(SB)/4, $0x00fffff
+GLOBL ·poly1305_init_constants_armv6<>(SB), 8, $20
+
+// Warning: the linker may use R11 to synthesize certain instructions. Please
+// take care and verify that no synthetic instructions use it.
+
+TEXT poly1305_init_ext_armv6<>(SB), NOSPLIT, $0
+ // Needs 16 bytes of stack and 64 bytes of space pointed to by R0. (It
+ // might look like it's only 60 bytes of space but the final four bytes
+ // will be written by another function.) We need to skip over four
+ // bytes of stack because that's saving the value of 'g'.
+ ADD $4, R13, R8
+ MOVM.IB [R4-R7], (R8)
+ MOVM.IA.W (R1), [R2-R5]
+ MOVW $·poly1305_init_constants_armv6<>(SB), R7
+ MOVW R2, R8
+ MOVW R2>>26, R9
+ MOVW R3>>20, g
+ MOVW R4>>14, R11
+ MOVW R5>>8, R12
+ ORR R3<<6, R9, R9
+ ORR R4<<12, g, g
+ ORR R5<<18, R11, R11
+ MOVM.IA (R7), [R2-R6]
+ AND R8, R2, R2
+ AND R9, R3, R3
+ AND g, R4, R4
+ AND R11, R5, R5
+ AND R12, R6, R6
+ MOVM.IA.W [R2-R6], (R0)
+ EOR R2, R2, R2
+ EOR R3, R3, R3
+ EOR R4, R4, R4
+ EOR R5, R5, R5
+ EOR R6, R6, R6
+ MOVM.IA.W [R2-R6], (R0)
+ MOVM.IA.W (R1), [R2-R5]
+ MOVM.IA [R2-R6], (R0)
+ ADD $20, R13, R0
+ MOVM.DA (R0), [R4-R7]
+ RET
+
+#define MOVW_UNALIGNED(Rsrc, Rdst, Rtmp, offset) \
+ MOVBU (offset+0)(Rsrc), Rtmp; \
+ MOVBU Rtmp, (offset+0)(Rdst); \
+ MOVBU (offset+1)(Rsrc), Rtmp; \
+ MOVBU Rtmp, (offset+1)(Rdst); \
+ MOVBU (offset+2)(Rsrc), Rtmp; \
+ MOVBU Rtmp, (offset+2)(Rdst); \
+ MOVBU (offset+3)(Rsrc), Rtmp; \
+ MOVBU Rtmp, (offset+3)(Rdst)
+
+TEXT poly1305_blocks_armv6<>(SB), NOSPLIT, $0
+ // Needs 24 bytes of stack for saved registers and then 88 bytes of
+ // scratch space after that. We assume that 24 bytes at (R13) have
+ // already been used: four bytes for the link register saved in the
+ // prelude of poly1305_auth_armv6, four bytes for saving the value of g
+ // in that function and 16 bytes of scratch space used around
+ // poly1305_finish_ext_armv6_skip1.
+ ADD $24, R13, R12
+ MOVM.IB [R4-R8, R14], (R12)
+ MOVW R0, 88(R13)
+ MOVW R1, 92(R13)
+ MOVW R2, 96(R13)
+ MOVW R1, R14
+ MOVW R2, R12
+ MOVW 56(R0), R8
+ WORD $0xe1180008 // TST R8, R8 not working see issue 5921
+ EOR R6, R6, R6
+ MOVW.EQ $(1<<24), R6
+ MOVW R6, 84(R13)
+ ADD $116, R13, g
+ MOVM.IA (R0), [R0-R9]
+ MOVM.IA [R0-R4], (g)
+ CMP $16, R12
+ BLO poly1305_blocks_armv6_done
+
+poly1305_blocks_armv6_mainloop:
+ WORD $0xe31e0003 // TST R14, #3 not working see issue 5921
+ BEQ poly1305_blocks_armv6_mainloop_aligned
+ ADD $100, R13, g
+ MOVW_UNALIGNED(R14, g, R0, 0)
+ MOVW_UNALIGNED(R14, g, R0, 4)
+ MOVW_UNALIGNED(R14, g, R0, 8)
+ MOVW_UNALIGNED(R14, g, R0, 12)
+ MOVM.IA (g), [R0-R3]
+ ADD $16, R14
+ B poly1305_blocks_armv6_mainloop_loaded
+
+poly1305_blocks_armv6_mainloop_aligned:
+ MOVM.IA.W (R14), [R0-R3]
+
+poly1305_blocks_armv6_mainloop_loaded:
+ MOVW R0>>26, g
+ MOVW R1>>20, R11
+ MOVW R2>>14, R12
+ MOVW R14, 92(R13)
+ MOVW R3>>8, R4
+ ORR R1<<6, g, g
+ ORR R2<<12, R11, R11
+ ORR R3<<18, R12, R12
+ BIC $0xfc000000, R0, R0
+ BIC $0xfc000000, g, g
+ MOVW 84(R13), R3
+ BIC $0xfc000000, R11, R11
+ BIC $0xfc000000, R12, R12
+ ADD R0, R5, R5
+ ADD g, R6, R6
+ ORR R3, R4, R4
+ ADD R11, R7, R7
+ ADD $116, R13, R14
+ ADD R12, R8, R8
+ ADD R4, R9, R9
+ MOVM.IA (R14), [R0-R4]
+ MULLU R4, R5, (R11, g)
+ MULLU R3, R5, (R14, R12)
+ MULALU R3, R6, (R11, g)
+ MULALU R2, R6, (R14, R12)
+ MULALU R2, R7, (R11, g)
+ MULALU R1, R7, (R14, R12)
+ ADD R4<<2, R4, R4
+ ADD R3<<2, R3, R3
+ MULALU R1, R8, (R11, g)
+ MULALU R0, R8, (R14, R12)
+ MULALU R0, R9, (R11, g)
+ MULALU R4, R9, (R14, R12)
+ MOVW g, 76(R13)
+ MOVW R11, 80(R13)
+ MOVW R12, 68(R13)
+ MOVW R14, 72(R13)
+ MULLU R2, R5, (R11, g)
+ MULLU R1, R5, (R14, R12)
+ MULALU R1, R6, (R11, g)
+ MULALU R0, R6, (R14, R12)
+ MULALU R0, R7, (R11, g)
+ MULALU R4, R7, (R14, R12)
+ ADD R2<<2, R2, R2
+ ADD R1<<2, R1, R1
+ MULALU R4, R8, (R11, g)
+ MULALU R3, R8, (R14, R12)
+ MULALU R3, R9, (R11, g)
+ MULALU R2, R9, (R14, R12)
+ MOVW g, 60(R13)
+ MOVW R11, 64(R13)
+ MOVW R12, 52(R13)
+ MOVW R14, 56(R13)
+ MULLU R0, R5, (R11, g)
+ MULALU R4, R6, (R11, g)
+ MULALU R3, R7, (R11, g)
+ MULALU R2, R8, (R11, g)
+ MULALU R1, R9, (R11, g)
+ ADD $52, R13, R0
+ MOVM.IA (R0), [R0-R7]
+ MOVW g>>26, R12
+ MOVW R4>>26, R14
+ ORR R11<<6, R12, R12
+ ORR R5<<6, R14, R14
+ BIC $0xfc000000, g, g
+ BIC $0xfc000000, R4, R4
+ ADD.S R12, R0, R0
+ ADC $0, R1, R1
+ ADD.S R14, R6, R6
+ ADC $0, R7, R7
+ MOVW R0>>26, R12
+ MOVW R6>>26, R14
+ ORR R1<<6, R12, R12
+ ORR R7<<6, R14, R14
+ BIC $0xfc000000, R0, R0
+ BIC $0xfc000000, R6, R6
+ ADD R14<<2, R14, R14
+ ADD.S R12, R2, R2
+ ADC $0, R3, R3
+ ADD R14, g, g
+ MOVW R2>>26, R12
+ MOVW g>>26, R14
+ ORR R3<<6, R12, R12
+ BIC $0xfc000000, g, R5
+ BIC $0xfc000000, R2, R7
+ ADD R12, R4, R4
+ ADD R14, R0, R0
+ MOVW R4>>26, R12
+ BIC $0xfc000000, R4, R8
+ ADD R12, R6, R9
+ MOVW 96(R13), R12
+ MOVW 92(R13), R14
+ MOVW R0, R6
+ CMP $32, R12
+ SUB $16, R12, R12
+ MOVW R12, 96(R13)
+ BHS poly1305_blocks_armv6_mainloop
+
+poly1305_blocks_armv6_done:
+ MOVW 88(R13), R12
+ MOVW R5, 20(R12)
+ MOVW R6, 24(R12)
+ MOVW R7, 28(R12)
+ MOVW R8, 32(R12)
+ MOVW R9, 36(R12)
+ ADD $48, R13, R0
+ MOVM.DA (R0), [R4-R8, R14]
+ RET
+
+#define MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp) \
+ MOVBU.P 1(Rsrc), Rtmp; \
+ MOVBU.P Rtmp, 1(Rdst); \
+ MOVBU.P 1(Rsrc), Rtmp; \
+ MOVBU.P Rtmp, 1(Rdst)
+
+#define MOVWP_UNALIGNED(Rsrc, Rdst, Rtmp) \
+ MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp); \
+ MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp)
+
+// func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]key)
+TEXT ·poly1305_auth_armv6(SB), $196-16
+ // The value 196, just above, is the sum of 64 (the size of the context
+ // structure) and 132 (the amount of stack needed).
+ //
+ // At this point, the stack pointer (R13) has been moved down. It
+ // points to the saved link register and there's 196 bytes of free
+ // space above it.
+ //
+ // The stack for this function looks like:
+ //
+ // +---------------------
+ // |
+ // | 64 bytes of context structure
+ // |
+ // +---------------------
+ // |
+ // | 112 bytes for poly1305_blocks_armv6
+ // |
+ // +---------------------
+ // | 16 bytes of final block, constructed at
+ // | poly1305_finish_ext_armv6_skip8
+ // +---------------------
+ // | four bytes of saved 'g'
+ // +---------------------
+ // | lr, saved by prelude <- R13 points here
+ // +---------------------
+ MOVW g, 4(R13)
+
+ MOVW out+0(FP), R4
+ MOVW m+4(FP), R5
+ MOVW mlen+8(FP), R6
+ MOVW key+12(FP), R7
+
+ ADD $136, R13, R0 // 136 = 4 + 4 + 16 + 112
+ MOVW R7, R1
+
+ // poly1305_init_ext_armv6 will write to the stack from R13+4, but
+ // that's ok because none of the other values have been written yet.
+ BL poly1305_init_ext_armv6<>(SB)
+ BIC.S $15, R6, R2
+ BEQ poly1305_auth_armv6_noblocks
+ ADD $136, R13, R0
+ MOVW R5, R1
+ ADD R2, R5, R5
+ SUB R2, R6, R6
+ BL poly1305_blocks_armv6<>(SB)
+
+poly1305_auth_armv6_noblocks:
+ ADD $136, R13, R0
+ MOVW R5, R1
+ MOVW R6, R2
+ MOVW R4, R3
+
+ MOVW R0, R5
+ MOVW R1, R6
+ MOVW R2, R7
+ MOVW R3, R8
+ AND.S R2, R2, R2
+ BEQ poly1305_finish_ext_armv6_noremaining
+ EOR R0, R0
+ ADD $8, R13, R9 // 8 = offset to 16 byte scratch space
+ MOVW R0, (R9)
+ MOVW R0, 4(R9)
+ MOVW R0, 8(R9)
+ MOVW R0, 12(R9)
+ WORD $0xe3110003 // TST R1, #3 not working see issue 5921
+ BEQ poly1305_finish_ext_armv6_aligned
+ WORD $0xe3120008 // TST R2, #8 not working see issue 5921
+ BEQ poly1305_finish_ext_armv6_skip8
+ MOVWP_UNALIGNED(R1, R9, g)
+ MOVWP_UNALIGNED(R1, R9, g)
+
+poly1305_finish_ext_armv6_skip8:
+ WORD $0xe3120004 // TST $4, R2 not working see issue 5921
+ BEQ poly1305_finish_ext_armv6_skip4
+ MOVWP_UNALIGNED(R1, R9, g)
+
+poly1305_finish_ext_armv6_skip4:
+ WORD $0xe3120002 // TST $2, R2 not working see issue 5921
+ BEQ poly1305_finish_ext_armv6_skip2
+ MOVHUP_UNALIGNED(R1, R9, g)
+ B poly1305_finish_ext_armv6_skip2
+
+poly1305_finish_ext_armv6_aligned:
+ WORD $0xe3120008 // TST R2, #8 not working see issue 5921
+ BEQ poly1305_finish_ext_armv6_skip8_aligned
+ MOVM.IA.W (R1), [g-R11]
+ MOVM.IA.W [g-R11], (R9)
+
+poly1305_finish_ext_armv6_skip8_aligned:
+ WORD $0xe3120004 // TST $4, R2 not working see issue 5921
+ BEQ poly1305_finish_ext_armv6_skip4_aligned
+ MOVW.P 4(R1), g
+ MOVW.P g, 4(R9)
+
+poly1305_finish_ext_armv6_skip4_aligned:
+ WORD $0xe3120002 // TST $2, R2 not working see issue 5921
+ BEQ poly1305_finish_ext_armv6_skip2
+ MOVHU.P 2(R1), g
+ MOVH.P g, 2(R9)
+
+poly1305_finish_ext_armv6_skip2:
+ WORD $0xe3120001 // TST $1, R2 not working see issue 5921
+ BEQ poly1305_finish_ext_armv6_skip1
+ MOVBU.P 1(R1), g
+ MOVBU.P g, 1(R9)
+
+poly1305_finish_ext_armv6_skip1:
+ MOVW $1, R11
+ MOVBU R11, 0(R9)
+ MOVW R11, 56(R5)
+ MOVW R5, R0
+ ADD $8, R13, R1
+ MOVW $16, R2
+ BL poly1305_blocks_armv6<>(SB)
+
+poly1305_finish_ext_armv6_noremaining:
+ MOVW 20(R5), R0
+ MOVW 24(R5), R1
+ MOVW 28(R5), R2
+ MOVW 32(R5), R3
+ MOVW 36(R5), R4
+ MOVW R4>>26, R12
+ BIC $0xfc000000, R4, R4
+ ADD R12<<2, R12, R12
+ ADD R12, R0, R0
+ MOVW R0>>26, R12
+ BIC $0xfc000000, R0, R0
+ ADD R12, R1, R1
+ MOVW R1>>26, R12
+ BIC $0xfc000000, R1, R1
+ ADD R12, R2, R2
+ MOVW R2>>26, R12
+ BIC $0xfc000000, R2, R2
+ ADD R12, R3, R3
+ MOVW R3>>26, R12
+ BIC $0xfc000000, R3, R3
+ ADD R12, R4, R4
+ ADD $5, R0, R6
+ MOVW R6>>26, R12
+ BIC $0xfc000000, R6, R6
+ ADD R12, R1, R7
+ MOVW R7>>26, R12
+ BIC $0xfc000000, R7, R7
+ ADD R12, R2, g
+ MOVW g>>26, R12
+ BIC $0xfc000000, g, g
+ ADD R12, R3, R11
+ MOVW $-(1<<26), R12
+ ADD R11>>26, R12, R12
+ BIC $0xfc000000, R11, R11
+ ADD R12, R4, R9
+ MOVW R9>>31, R12
+ SUB $1, R12
+ AND R12, R6, R6
+ AND R12, R7, R7
+ AND R12, g, g
+ AND R12, R11, R11
+ AND R12, R9, R9
+ MVN R12, R12
+ AND R12, R0, R0
+ AND R12, R1, R1
+ AND R12, R2, R2
+ AND R12, R3, R3
+ AND R12, R4, R4
+ ORR R6, R0, R0
+ ORR R7, R1, R1
+ ORR g, R2, R2
+ ORR R11, R3, R3
+ ORR R9, R4, R4
+ ORR R1<<26, R0, R0
+ MOVW R1>>6, R1
+ ORR R2<<20, R1, R1
+ MOVW R2>>12, R2
+ ORR R3<<14, R2, R2
+ MOVW R3>>18, R3
+ ORR R4<<8, R3, R3
+ MOVW 40(R5), R6
+ MOVW 44(R5), R7
+ MOVW 48(R5), g
+ MOVW 52(R5), R11
+ ADD.S R6, R0, R0
+ ADC.S R7, R1, R1
+ ADC.S g, R2, R2
+ ADC.S R11, R3, R3
+ MOVM.IA [R0-R3], (R8)
+ MOVW R5, R12
+ EOR R0, R0, R0
+ EOR R1, R1, R1
+ EOR R2, R2, R2
+ EOR R3, R3, R3
+ EOR R4, R4, R4
+ EOR R5, R5, R5
+ EOR R6, R6, R6
+ EOR R7, R7, R7
+ MOVM.IA.W [R0-R7], (R12)
+ MOVM.IA [R0-R7], (R12)
+ MOVW 4(R13), g
+ RET
diff --git a/vendor/golang.org/x/crypto/poly1305/sum_ref.go b/vendor/golang.org/x/crypto/poly1305/sum_ref.go
new file mode 100644
index 0000000..b2805a5
--- /dev/null
+++ b/vendor/golang.org/x/crypto/poly1305/sum_ref.go
@@ -0,0 +1,141 @@
+// 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,!arm gccgo appengine nacl
+
+package poly1305
+
+import "encoding/binary"
+
+// Sum generates an authenticator for msg using a one-time key and puts the
+// 16-byte result into out. Authenticating two different messages with the same
+// key allows an attacker to forge messages at will.
+func Sum(out *[TagSize]byte, msg []byte, key *[32]byte) {
+ var (
+ h0, h1, h2, h3, h4 uint32 // the hash accumulators
+ r0, r1, r2, r3, r4 uint64 // the r part of the key
+ )
+
+ r0 = uint64(binary.LittleEndian.Uint32(key[0:]) & 0x3ffffff)
+ r1 = uint64((binary.LittleEndian.Uint32(key[3:]) >> 2) & 0x3ffff03)
+ r2 = uint64((binary.LittleEndian.Uint32(key[6:]) >> 4) & 0x3ffc0ff)
+ r3 = uint64((binary.LittleEndian.Uint32(key[9:]) >> 6) & 0x3f03fff)
+ r4 = uint64((binary.LittleEndian.Uint32(key[12:]) >> 8) & 0x00fffff)
+
+ R1, R2, R3, R4 := r1*5, r2*5, r3*5, r4*5
+
+ for len(msg) >= TagSize {
+ // h += msg
+ h0 += binary.LittleEndian.Uint32(msg[0:]) & 0x3ffffff
+ h1 += (binary.LittleEndian.Uint32(msg[3:]) >> 2) & 0x3ffffff
+ h2 += (binary.LittleEndian.Uint32(msg[6:]) >> 4) & 0x3ffffff
+ h3 += (binary.LittleEndian.Uint32(msg[9:]) >> 6) & 0x3ffffff
+ h4 += (binary.LittleEndian.Uint32(msg[12:]) >> 8) | (1 << 24)
+
+ // h *= r
+ d0 := (uint64(h0) * r0) + (uint64(h1) * R4) + (uint64(h2) * R3) + (uint64(h3) * R2) + (uint64(h4) * R1)
+ d1 := (d0 >> 26) + (uint64(h0) * r1) + (uint64(h1) * r0) + (uint64(h2) * R4) + (uint64(h3) * R3) + (uint64(h4) * R2)
+ d2 := (d1 >> 26) + (uint64(h0) * r2) + (uint64(h1) * r1) + (uint64(h2) * r0) + (uint64(h3) * R4) + (uint64(h4) * R3)
+ d3 := (d2 >> 26) + (uint64(h0) * r3) + (uint64(h1) * r2) + (uint64(h2) * r1) + (uint64(h3) * r0) + (uint64(h4) * R4)
+ d4 := (d3 >> 26) + (uint64(h0) * r4) + (uint64(h1) * r3) + (uint64(h2) * r2) + (uint64(h3) * r1) + (uint64(h4) * r0)
+
+ // h %= p
+ h0 = uint32(d0) & 0x3ffffff
+ h1 = uint32(d1) & 0x3ffffff
+ h2 = uint32(d2) & 0x3ffffff
+ h3 = uint32(d3) & 0x3ffffff
+ h4 = uint32(d4) & 0x3ffffff
+
+ h0 += uint32(d4>>26) * 5
+ h1 += h0 >> 26
+ h0 = h0 & 0x3ffffff
+
+ msg = msg[TagSize:]
+ }
+
+ if len(msg) > 0 {
+ var block [TagSize]byte
+ off := copy(block[:], msg)
+ block[off] = 0x01
+
+ // h += msg
+ h0 += binary.LittleEndian.Uint32(block[0:]) & 0x3ffffff
+ h1 += (binary.LittleEndian.Uint32(block[3:]) >> 2) & 0x3ffffff
+ h2 += (binary.LittleEndian.Uint32(block[6:]) >> 4) & 0x3ffffff
+ h3 += (binary.LittleEndian.Uint32(block[9:]) >> 6) & 0x3ffffff
+ h4 += (binary.LittleEndian.Uint32(block[12:]) >> 8)
+
+ // h *= r
+ d0 := (uint64(h0) * r0) + (uint64(h1) * R4) + (uint64(h2) * R3) + (uint64(h3) * R2) + (uint64(h4) * R1)
+ d1 := (d0 >> 26) + (uint64(h0) * r1) + (uint64(h1) * r0) + (uint64(h2) * R4) + (uint64(h3) * R3) + (uint64(h4) * R2)
+ d2 := (d1 >> 26) + (uint64(h0) * r2) + (uint64(h1) * r1) + (uint64(h2) * r0) + (uint64(h3) * R4) + (uint64(h4) * R3)
+ d3 := (d2 >> 26) + (uint64(h0) * r3) + (uint64(h1) * r2) + (uint64(h2) * r1) + (uint64(h3) * r0) + (uint64(h4) * R4)
+ d4 := (d3 >> 26) + (uint64(h0) * r4) + (uint64(h1) * r3) + (uint64(h2) * r2) + (uint64(h3) * r1) + (uint64(h4) * r0)
+
+ // h %= p
+ h0 = uint32(d0) & 0x3ffffff
+ h1 = uint32(d1) & 0x3ffffff
+ h2 = uint32(d2) & 0x3ffffff
+ h3 = uint32(d3) & 0x3ffffff
+ h4 = uint32(d4) & 0x3ffffff
+
+ h0 += uint32(d4>>26) * 5
+ h1 += h0 >> 26
+ h0 = h0 & 0x3ffffff
+ }
+
+ // h %= p reduction
+ h2 += h1 >> 26
+ h1 &= 0x3ffffff
+ h3 += h2 >> 26
+ h2 &= 0x3ffffff
+ h4 += h3 >> 26
+ h3 &= 0x3ffffff
+ h0 += 5 * (h4 >> 26)
+ h4 &= 0x3ffffff
+ h1 += h0 >> 26
+ h0 &= 0x3ffffff
+
+ // h - p
+ t0 := h0 + 5
+ t1 := h1 + (t0 >> 26)
+ t2 := h2 + (t1 >> 26)
+ t3 := h3 + (t2 >> 26)
+ t4 := h4 + (t3 >> 26) - (1 << 26)
+ t0 &= 0x3ffffff
+ t1 &= 0x3ffffff
+ t2 &= 0x3ffffff
+ t3 &= 0x3ffffff
+
+ // select h if h < p else h - p
+ t_mask := (t4 >> 31) - 1
+ h_mask := ^t_mask
+ h0 = (h0 & h_mask) | (t0 & t_mask)
+ h1 = (h1 & h_mask) | (t1 & t_mask)
+ h2 = (h2 & h_mask) | (t2 & t_mask)
+ h3 = (h3 & h_mask) | (t3 & t_mask)
+ h4 = (h4 & h_mask) | (t4 & t_mask)
+
+ // h %= 2^128
+ h0 |= h1 << 26
+ h1 = ((h1 >> 6) | (h2 << 20))
+ h2 = ((h2 >> 12) | (h3 << 14))
+ h3 = ((h3 >> 18) | (h4 << 8))
+
+ // s: the s part of the key
+ // tag = (h + s) % (2^128)
+ t := uint64(h0) + uint64(binary.LittleEndian.Uint32(key[16:]))
+ h0 = uint32(t)
+ t = uint64(h1) + uint64(binary.LittleEndian.Uint32(key[20:])) + (t >> 32)
+ h1 = uint32(t)
+ t = uint64(h2) + uint64(binary.LittleEndian.Uint32(key[24:])) + (t >> 32)
+ h2 = uint32(t)
+ t = uint64(h3) + uint64(binary.LittleEndian.Uint32(key[28:])) + (t >> 32)
+ h3 = uint32(t)
+
+ binary.LittleEndian.PutUint32(out[0:], h0)
+ binary.LittleEndian.PutUint32(out[4:], h1)
+ binary.LittleEndian.PutUint32(out[8:], h2)
+ binary.LittleEndian.PutUint32(out[12:], h3)
+}
diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/hsalsa20.go b/vendor/golang.org/x/crypto/salsa20/salsa/hsalsa20.go
new file mode 100644
index 0000000..4c96147
--- /dev/null
+++ b/vendor/golang.org/x/crypto/salsa20/salsa/hsalsa20.go
@@ -0,0 +1,144 @@
+// 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 salsa provides low-level access to functions in the Salsa family.
+package salsa // import "golang.org/x/crypto/salsa20/salsa"
+
+// Sigma is the Salsa20 constant for 256-bit keys.
+var Sigma = [16]byte{'e', 'x', 'p', 'a', 'n', 'd', ' ', '3', '2', '-', 'b', 'y', 't', 'e', ' ', 'k'}
+
+// HSalsa20 applies the HSalsa20 core function to a 16-byte input in, 32-byte
+// key k, and 16-byte constant c, and puts the result into the 32-byte array
+// out.
+func HSalsa20(out *[32]byte, in *[16]byte, k *[32]byte, c *[16]byte) {
+ x0 := uint32(c[0]) | uint32(c[1])<<8 | uint32(c[2])<<16 | uint32(c[3])<<24
+ x1 := uint32(k[0]) | uint32(k[1])<<8 | uint32(k[2])<<16 | uint32(k[3])<<24
+ x2 := uint32(k[4]) | uint32(k[5])<<8 | uint32(k[6])<<16 | uint32(k[7])<<24
+ x3 := uint32(k[8]) | uint32(k[9])<<8 | uint32(k[10])<<16 | uint32(k[11])<<24
+ x4 := uint32(k[12]) | uint32(k[13])<<8 | uint32(k[14])<<16 | uint32(k[15])<<24
+ x5 := uint32(c[4]) | uint32(c[5])<<8 | uint32(c[6])<<16 | uint32(c[7])<<24
+ x6 := uint32(in[0]) | uint32(in[1])<<8 | uint32(in[2])<<16 | uint32(in[3])<<24
+ x7 := uint32(in[4]) | uint32(in[5])<<8 | uint32(in[6])<<16 | uint32(in[7])<<24
+ x8 := uint32(in[8]) | uint32(in[9])<<8 | uint32(in[10])<<16 | uint32(in[11])<<24
+ x9 := uint32(in[12]) | uint32(in[13])<<8 | uint32(in[14])<<16 | uint32(in[15])<<24
+ x10 := uint32(c[8]) | uint32(c[9])<<8 | uint32(c[10])<<16 | uint32(c[11])<<24
+ x11 := uint32(k[16]) | uint32(k[17])<<8 | uint32(k[18])<<16 | uint32(k[19])<<24
+ x12 := uint32(k[20]) | uint32(k[21])<<8 | uint32(k[22])<<16 | uint32(k[23])<<24
+ x13 := uint32(k[24]) | uint32(k[25])<<8 | uint32(k[26])<<16 | uint32(k[27])<<24
+ x14 := uint32(k[28]) | uint32(k[29])<<8 | uint32(k[30])<<16 | uint32(k[31])<<24
+ x15 := uint32(c[12]) | uint32(c[13])<<8 | uint32(c[14])<<16 | uint32(c[15])<<24
+
+ for i := 0; i < 20; i += 2 {
+ u := x0 + x12
+ x4 ^= u<<7 | u>>(32-7)
+ u = x4 + x0
+ x8 ^= u<<9 | u>>(32-9)
+ u = x8 + x4
+ x12 ^= u<<13 | u>>(32-13)
+ u = x12 + x8
+ x0 ^= u<<18 | u>>(32-18)
+
+ u = x5 + x1
+ x9 ^= u<<7 | u>>(32-7)
+ u = x9 + x5
+ x13 ^= u<<9 | u>>(32-9)
+ u = x13 + x9
+ x1 ^= u<<13 | u>>(32-13)
+ u = x1 + x13
+ x5 ^= u<<18 | u>>(32-18)
+
+ u = x10 + x6
+ x14 ^= u<<7 | u>>(32-7)
+ u = x14 + x10
+ x2 ^= u<<9 | u>>(32-9)
+ u = x2 + x14
+ x6 ^= u<<13 | u>>(32-13)
+ u = x6 + x2
+ x10 ^= u<<18 | u>>(32-18)
+
+ u = x15 + x11
+ x3 ^= u<<7 | u>>(32-7)
+ u = x3 + x15
+ x7 ^= u<<9 | u>>(32-9)
+ u = x7 + x3
+ x11 ^= u<<13 | u>>(32-13)
+ u = x11 + x7
+ x15 ^= u<<18 | u>>(32-18)
+
+ u = x0 + x3
+ x1 ^= u<<7 | u>>(32-7)
+ u = x1 + x0
+ x2 ^= u<<9 | u>>(32-9)
+ u = x2 + x1
+ x3 ^= u<<13 | u>>(32-13)
+ u = x3 + x2
+ x0 ^= u<<18 | u>>(32-18)
+
+ u = x5 + x4
+ x6 ^= u<<7 | u>>(32-7)
+ u = x6 + x5
+ x7 ^= u<<9 | u>>(32-9)
+ u = x7 + x6
+ x4 ^= u<<13 | u>>(32-13)
+ u = x4 + x7
+ x5 ^= u<<18 | u>>(32-18)
+
+ u = x10 + x9
+ x11 ^= u<<7 | u>>(32-7)
+ u = x11 + x10
+ x8 ^= u<<9 | u>>(32-9)
+ u = x8 + x11
+ x9 ^= u<<13 | u>>(32-13)
+ u = x9 + x8
+ x10 ^= u<<18 | u>>(32-18)
+
+ u = x15 + x14
+ x12 ^= u<<7 | u>>(32-7)
+ u = x12 + x15
+ x13 ^= u<<9 | u>>(32-9)
+ u = x13 + x12
+ x14 ^= u<<13 | u>>(32-13)
+ u = x14 + x13
+ x15 ^= u<<18 | u>>(32-18)
+ }
+ out[0] = byte(x0)
+ out[1] = byte(x0 >> 8)
+ out[2] = byte(x0 >> 16)
+ out[3] = byte(x0 >> 24)
+
+ out[4] = byte(x5)
+ out[5] = byte(x5 >> 8)
+ out[6] = byte(x5 >> 16)
+ out[7] = byte(x5 >> 24)
+
+ out[8] = byte(x10)
+ out[9] = byte(x10 >> 8)
+ out[10] = byte(x10 >> 16)
+ out[11] = byte(x10 >> 24)
+
+ out[12] = byte(x15)
+ out[13] = byte(x15 >> 8)
+ out[14] = byte(x15 >> 16)
+ out[15] = byte(x15 >> 24)
+
+ out[16] = byte(x6)
+ out[17] = byte(x6 >> 8)
+ out[18] = byte(x6 >> 16)
+ out[19] = byte(x6 >> 24)
+
+ out[20] = byte(x7)
+ out[21] = byte(x7 >> 8)
+ out[22] = byte(x7 >> 16)
+ out[23] = byte(x7 >> 24)
+
+ out[24] = byte(x8)
+ out[25] = byte(x8 >> 8)
+ out[26] = byte(x8 >> 16)
+ out[27] = byte(x8 >> 24)
+
+ out[28] = byte(x9)
+ out[29] = byte(x9 >> 8)
+ out[30] = byte(x9 >> 16)
+ out[31] = byte(x9 >> 24)
+}
diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa2020_amd64.s b/vendor/golang.org/x/crypto/salsa20/salsa/salsa2020_amd64.s
new file mode 100644
index 0000000..22afbdc
--- /dev/null
+++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa2020_amd64.s
@@ -0,0 +1,889 @@
+// 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,!appengine,!gccgo
+
+// This code was translated into a form compatible with 6a from the public
+// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html
+
+// func salsa2020XORKeyStream(out, in *byte, n uint64, nonce, key *byte)
+// This needs up to 64 bytes at 360(SP); hence the non-obvious frame size.
+TEXT ·salsa2020XORKeyStream(SB),0,$456-40 // frame = 424 + 32 byte alignment
+ MOVQ out+0(FP),DI
+ MOVQ in+8(FP),SI
+ MOVQ n+16(FP),DX
+ MOVQ nonce+24(FP),CX
+ MOVQ key+32(FP),R8
+
+ MOVQ SP,R12
+ MOVQ SP,R9
+ ADDQ $31, R9
+ ANDQ $~31, R9
+ MOVQ R9, SP
+
+ MOVQ DX,R9
+ MOVQ CX,DX
+ MOVQ R8,R10
+ CMPQ R9,$0
+ JBE DONE
+ START:
+ MOVL 20(R10),CX
+ MOVL 0(R10),R8
+ MOVL 0(DX),AX
+ MOVL 16(R10),R11
+ MOVL CX,0(SP)
+ MOVL R8, 4 (SP)
+ MOVL AX, 8 (SP)
+ MOVL R11, 12 (SP)
+ MOVL 8(DX),CX
+ MOVL 24(R10),R8
+ MOVL 4(R10),AX
+ MOVL 4(DX),R11
+ MOVL CX,16(SP)
+ MOVL R8, 20 (SP)
+ MOVL AX, 24 (SP)
+ MOVL R11, 28 (SP)
+ MOVL 12(DX),CX
+ MOVL 12(R10),DX
+ MOVL 28(R10),R8
+ MOVL 8(R10),AX
+ MOVL DX,32(SP)
+ MOVL CX, 36 (SP)
+ MOVL R8, 40 (SP)
+ MOVL AX, 44 (SP)
+ MOVQ $1634760805,DX
+ MOVQ $857760878,CX
+ MOVQ $2036477234,R8
+ MOVQ $1797285236,AX
+ MOVL DX,48(SP)
+ MOVL CX, 52 (SP)
+ MOVL R8, 56 (SP)
+ MOVL AX, 60 (SP)
+ CMPQ R9,$256
+ JB BYTESBETWEEN1AND255
+ MOVOA 48(SP),X0
+ PSHUFL $0X55,X0,X1
+ PSHUFL $0XAA,X0,X2
+ PSHUFL $0XFF,X0,X3
+ PSHUFL $0X00,X0,X0
+ MOVOA X1,64(SP)
+ MOVOA X2,80(SP)
+ MOVOA X3,96(SP)
+ MOVOA X0,112(SP)
+ MOVOA 0(SP),X0
+ PSHUFL $0XAA,X0,X1
+ PSHUFL $0XFF,X0,X2
+ PSHUFL $0X00,X0,X3
+ PSHUFL $0X55,X0,X0
+ MOVOA X1,128(SP)
+ MOVOA X2,144(SP)
+ MOVOA X3,160(SP)
+ MOVOA X0,176(SP)
+ MOVOA 16(SP),X0
+ PSHUFL $0XFF,X0,X1
+ PSHUFL $0X55,X0,X2
+ PSHUFL $0XAA,X0,X0
+ MOVOA X1,192(SP)
+ MOVOA X2,208(SP)
+ MOVOA X0,224(SP)
+ MOVOA 32(SP),X0
+ PSHUFL $0X00,X0,X1
+ PSHUFL $0XAA,X0,X2
+ PSHUFL $0XFF,X0,X0
+ MOVOA X1,240(SP)
+ MOVOA X2,256(SP)
+ MOVOA X0,272(SP)
+ BYTESATLEAST256:
+ MOVL 16(SP),DX
+ MOVL 36 (SP),CX
+ MOVL DX,288(SP)
+ MOVL CX,304(SP)
+ ADDQ $1,DX
+ SHLQ $32,CX
+ ADDQ CX,DX
+ MOVQ DX,CX
+ SHRQ $32,CX
+ MOVL DX, 292 (SP)
+ MOVL CX, 308 (SP)
+ ADDQ $1,DX
+ SHLQ $32,CX
+ ADDQ CX,DX
+ MOVQ DX,CX
+ SHRQ $32,CX
+ MOVL DX, 296 (SP)
+ MOVL CX, 312 (SP)
+ ADDQ $1,DX
+ SHLQ $32,CX
+ ADDQ CX,DX
+ MOVQ DX,CX
+ SHRQ $32,CX
+ MOVL DX, 300 (SP)
+ MOVL CX, 316 (SP)
+ ADDQ $1,DX
+ SHLQ $32,CX
+ ADDQ CX,DX
+ MOVQ DX,CX
+ SHRQ $32,CX
+ MOVL DX,16(SP)
+ MOVL CX, 36 (SP)
+ MOVQ R9,352(SP)
+ MOVQ $20,DX
+ MOVOA 64(SP),X0
+ MOVOA 80(SP),X1
+ MOVOA 96(SP),X2
+ MOVOA 256(SP),X3
+ MOVOA 272(SP),X4
+ MOVOA 128(SP),X5
+ MOVOA 144(SP),X6
+ MOVOA 176(SP),X7
+ MOVOA 192(SP),X8
+ MOVOA 208(SP),X9
+ MOVOA 224(SP),X10
+ MOVOA 304(SP),X11
+ MOVOA 112(SP),X12
+ MOVOA 160(SP),X13
+ MOVOA 240(SP),X14
+ MOVOA 288(SP),X15
+ MAINLOOP1:
+ MOVOA X1,320(SP)
+ MOVOA X2,336(SP)
+ MOVOA X13,X1
+ PADDL X12,X1
+ MOVOA X1,X2
+ PSLLL $7,X1
+ PXOR X1,X14
+ PSRLL $25,X2
+ PXOR X2,X14
+ MOVOA X7,X1
+ PADDL X0,X1
+ MOVOA X1,X2
+ PSLLL $7,X1
+ PXOR X1,X11
+ PSRLL $25,X2
+ PXOR X2,X11
+ MOVOA X12,X1
+ PADDL X14,X1
+ MOVOA X1,X2
+ PSLLL $9,X1
+ PXOR X1,X15
+ PSRLL $23,X2
+ PXOR X2,X15
+ MOVOA X0,X1
+ PADDL X11,X1
+ MOVOA X1,X2
+ PSLLL $9,X1
+ PXOR X1,X9
+ PSRLL $23,X2
+ PXOR X2,X9
+ MOVOA X14,X1
+ PADDL X15,X1
+ MOVOA X1,X2
+ PSLLL $13,X1
+ PXOR X1,X13
+ PSRLL $19,X2
+ PXOR X2,X13
+ MOVOA X11,X1
+ PADDL X9,X1
+ MOVOA X1,X2
+ PSLLL $13,X1
+ PXOR X1,X7
+ PSRLL $19,X2
+ PXOR X2,X7
+ MOVOA X15,X1
+ PADDL X13,X1
+ MOVOA X1,X2
+ PSLLL $18,X1
+ PXOR X1,X12
+ PSRLL $14,X2
+ PXOR X2,X12
+ MOVOA 320(SP),X1
+ MOVOA X12,320(SP)
+ MOVOA X9,X2
+ PADDL X7,X2
+ MOVOA X2,X12
+ PSLLL $18,X2
+ PXOR X2,X0
+ PSRLL $14,X12
+ PXOR X12,X0
+ MOVOA X5,X2
+ PADDL X1,X2
+ MOVOA X2,X12
+ PSLLL $7,X2
+ PXOR X2,X3
+ PSRLL $25,X12
+ PXOR X12,X3
+ MOVOA 336(SP),X2
+ MOVOA X0,336(SP)
+ MOVOA X6,X0
+ PADDL X2,X0
+ MOVOA X0,X12
+ PSLLL $7,X0
+ PXOR X0,X4
+ PSRLL $25,X12
+ PXOR X12,X4
+ MOVOA X1,X0
+ PADDL X3,X0
+ MOVOA X0,X12
+ PSLLL $9,X0
+ PXOR X0,X10
+ PSRLL $23,X12
+ PXOR X12,X10
+ MOVOA X2,X0
+ PADDL X4,X0
+ MOVOA X0,X12
+ PSLLL $9,X0
+ PXOR X0,X8
+ PSRLL $23,X12
+ PXOR X12,X8
+ MOVOA X3,X0
+ PADDL X10,X0
+ MOVOA X0,X12
+ PSLLL $13,X0
+ PXOR X0,X5
+ PSRLL $19,X12
+ PXOR X12,X5
+ MOVOA X4,X0
+ PADDL X8,X0
+ MOVOA X0,X12
+ PSLLL $13,X0
+ PXOR X0,X6
+ PSRLL $19,X12
+ PXOR X12,X6
+ MOVOA X10,X0
+ PADDL X5,X0
+ MOVOA X0,X12
+ PSLLL $18,X0
+ PXOR X0,X1
+ PSRLL $14,X12
+ PXOR X12,X1
+ MOVOA 320(SP),X0
+ MOVOA X1,320(SP)
+ MOVOA X4,X1
+ PADDL X0,X1
+ MOVOA X1,X12
+ PSLLL $7,X1
+ PXOR X1,X7
+ PSRLL $25,X12
+ PXOR X12,X7
+ MOVOA X8,X1
+ PADDL X6,X1
+ MOVOA X1,X12
+ PSLLL $18,X1
+ PXOR X1,X2
+ PSRLL $14,X12
+ PXOR X12,X2
+ MOVOA 336(SP),X12
+ MOVOA X2,336(SP)
+ MOVOA X14,X1
+ PADDL X12,X1
+ MOVOA X1,X2
+ PSLLL $7,X1
+ PXOR X1,X5
+ PSRLL $25,X2
+ PXOR X2,X5
+ MOVOA X0,X1
+ PADDL X7,X1
+ MOVOA X1,X2
+ PSLLL $9,X1
+ PXOR X1,X10
+ PSRLL $23,X2
+ PXOR X2,X10
+ MOVOA X12,X1
+ PADDL X5,X1
+ MOVOA X1,X2
+ PSLLL $9,X1
+ PXOR X1,X8
+ PSRLL $23,X2
+ PXOR X2,X8
+ MOVOA X7,X1
+ PADDL X10,X1
+ MOVOA X1,X2
+ PSLLL $13,X1
+ PXOR X1,X4
+ PSRLL $19,X2
+ PXOR X2,X4
+ MOVOA X5,X1
+ PADDL X8,X1
+ MOVOA X1,X2
+ PSLLL $13,X1
+ PXOR X1,X14
+ PSRLL $19,X2
+ PXOR X2,X14
+ MOVOA X10,X1
+ PADDL X4,X1
+ MOVOA X1,X2
+ PSLLL $18,X1
+ PXOR X1,X0
+ PSRLL $14,X2
+ PXOR X2,X0
+ MOVOA 320(SP),X1
+ MOVOA X0,320(SP)
+ MOVOA X8,X0
+ PADDL X14,X0
+ MOVOA X0,X2
+ PSLLL $18,X0
+ PXOR X0,X12
+ PSRLL $14,X2
+ PXOR X2,X12
+ MOVOA X11,X0
+ PADDL X1,X0
+ MOVOA X0,X2
+ PSLLL $7,X0
+ PXOR X0,X6
+ PSRLL $25,X2
+ PXOR X2,X6
+ MOVOA 336(SP),X2
+ MOVOA X12,336(SP)
+ MOVOA X3,X0
+ PADDL X2,X0
+ MOVOA X0,X12
+ PSLLL $7,X0
+ PXOR X0,X13
+ PSRLL $25,X12
+ PXOR X12,X13
+ MOVOA X1,X0
+ PADDL X6,X0
+ MOVOA X0,X12
+ PSLLL $9,X0
+ PXOR X0,X15
+ PSRLL $23,X12
+ PXOR X12,X15
+ MOVOA X2,X0
+ PADDL X13,X0
+ MOVOA X0,X12
+ PSLLL $9,X0
+ PXOR X0,X9
+ PSRLL $23,X12
+ PXOR X12,X9
+ MOVOA X6,X0
+ PADDL X15,X0
+ MOVOA X0,X12
+ PSLLL $13,X0
+ PXOR X0,X11
+ PSRLL $19,X12
+ PXOR X12,X11
+ MOVOA X13,X0
+ PADDL X9,X0
+ MOVOA X0,X12
+ PSLLL $13,X0
+ PXOR X0,X3
+ PSRLL $19,X12
+ PXOR X12,X3
+ MOVOA X15,X0
+ PADDL X11,X0
+ MOVOA X0,X12
+ PSLLL $18,X0
+ PXOR X0,X1
+ PSRLL $14,X12
+ PXOR X12,X1
+ MOVOA X9,X0
+ PADDL X3,X0
+ MOVOA X0,X12
+ PSLLL $18,X0
+ PXOR X0,X2
+ PSRLL $14,X12
+ PXOR X12,X2
+ MOVOA 320(SP),X12
+ MOVOA 336(SP),X0
+ SUBQ $2,DX
+ JA MAINLOOP1
+ PADDL 112(SP),X12
+ PADDL 176(SP),X7
+ PADDL 224(SP),X10
+ PADDL 272(SP),X4
+ MOVD X12,DX
+ MOVD X7,CX
+ MOVD X10,R8
+ MOVD X4,R9
+ PSHUFL $0X39,X12,X12
+ PSHUFL $0X39,X7,X7
+ PSHUFL $0X39,X10,X10
+ PSHUFL $0X39,X4,X4
+ XORL 0(SI),DX
+ XORL 4(SI),CX
+ XORL 8(SI),R8
+ XORL 12(SI),R9
+ MOVL DX,0(DI)
+ MOVL CX,4(DI)
+ MOVL R8,8(DI)
+ MOVL R9,12(DI)
+ MOVD X12,DX
+ MOVD X7,CX
+ MOVD X10,R8
+ MOVD X4,R9
+ PSHUFL $0X39,X12,X12
+ PSHUFL $0X39,X7,X7
+ PSHUFL $0X39,X10,X10
+ PSHUFL $0X39,X4,X4
+ XORL 64(SI),DX
+ XORL 68(SI),CX
+ XORL 72(SI),R8
+ XORL 76(SI),R9
+ MOVL DX,64(DI)
+ MOVL CX,68(DI)
+ MOVL R8,72(DI)
+ MOVL R9,76(DI)
+ MOVD X12,DX
+ MOVD X7,CX
+ MOVD X10,R8
+ MOVD X4,R9
+ PSHUFL $0X39,X12,X12
+ PSHUFL $0X39,X7,X7
+ PSHUFL $0X39,X10,X10
+ PSHUFL $0X39,X4,X4
+ XORL 128(SI),DX
+ XORL 132(SI),CX
+ XORL 136(SI),R8
+ XORL 140(SI),R9
+ MOVL DX,128(DI)
+ MOVL CX,132(DI)
+ MOVL R8,136(DI)
+ MOVL R9,140(DI)
+ MOVD X12,DX
+ MOVD X7,CX
+ MOVD X10,R8
+ MOVD X4,R9
+ XORL 192(SI),DX
+ XORL 196(SI),CX
+ XORL 200(SI),R8
+ XORL 204(SI),R9
+ MOVL DX,192(DI)
+ MOVL CX,196(DI)
+ MOVL R8,200(DI)
+ MOVL R9,204(DI)
+ PADDL 240(SP),X14
+ PADDL 64(SP),X0
+ PADDL 128(SP),X5
+ PADDL 192(SP),X8
+ MOVD X14,DX
+ MOVD X0,CX
+ MOVD X5,R8
+ MOVD X8,R9
+ PSHUFL $0X39,X14,X14
+ PSHUFL $0X39,X0,X0
+ PSHUFL $0X39,X5,X5
+ PSHUFL $0X39,X8,X8
+ XORL 16(SI),DX
+ XORL 20(SI),CX
+ XORL 24(SI),R8
+ XORL 28(SI),R9
+ MOVL DX,16(DI)
+ MOVL CX,20(DI)
+ MOVL R8,24(DI)
+ MOVL R9,28(DI)
+ MOVD X14,DX
+ MOVD X0,CX
+ MOVD X5,R8
+ MOVD X8,R9
+ PSHUFL $0X39,X14,X14
+ PSHUFL $0X39,X0,X0
+ PSHUFL $0X39,X5,X5
+ PSHUFL $0X39,X8,X8
+ XORL 80(SI),DX
+ XORL 84(SI),CX
+ XORL 88(SI),R8
+ XORL 92(SI),R9
+ MOVL DX,80(DI)
+ MOVL CX,84(DI)
+ MOVL R8,88(DI)
+ MOVL R9,92(DI)
+ MOVD X14,DX
+ MOVD X0,CX
+ MOVD X5,R8
+ MOVD X8,R9
+ PSHUFL $0X39,X14,X14
+ PSHUFL $0X39,X0,X0
+ PSHUFL $0X39,X5,X5
+ PSHUFL $0X39,X8,X8
+ XORL 144(SI),DX
+ XORL 148(SI),CX
+ XORL 152(SI),R8
+ XORL 156(SI),R9
+ MOVL DX,144(DI)
+ MOVL CX,148(DI)
+ MOVL R8,152(DI)
+ MOVL R9,156(DI)
+ MOVD X14,DX
+ MOVD X0,CX
+ MOVD X5,R8
+ MOVD X8,R9
+ XORL 208(SI),DX
+ XORL 212(SI),CX
+ XORL 216(SI),R8
+ XORL 220(SI),R9
+ MOVL DX,208(DI)
+ MOVL CX,212(DI)
+ MOVL R8,216(DI)
+ MOVL R9,220(DI)
+ PADDL 288(SP),X15
+ PADDL 304(SP),X11
+ PADDL 80(SP),X1
+ PADDL 144(SP),X6
+ MOVD X15,DX
+ MOVD X11,CX
+ MOVD X1,R8
+ MOVD X6,R9
+ PSHUFL $0X39,X15,X15
+ PSHUFL $0X39,X11,X11
+ PSHUFL $0X39,X1,X1
+ PSHUFL $0X39,X6,X6
+ XORL 32(SI),DX
+ XORL 36(SI),CX
+ XORL 40(SI),R8
+ XORL 44(SI),R9
+ MOVL DX,32(DI)
+ MOVL CX,36(DI)
+ MOVL R8,40(DI)
+ MOVL R9,44(DI)
+ MOVD X15,DX
+ MOVD X11,CX
+ MOVD X1,R8
+ MOVD X6,R9
+ PSHUFL $0X39,X15,X15
+ PSHUFL $0X39,X11,X11
+ PSHUFL $0X39,X1,X1
+ PSHUFL $0X39,X6,X6
+ XORL 96(SI),DX
+ XORL 100(SI),CX
+ XORL 104(SI),R8
+ XORL 108(SI),R9
+ MOVL DX,96(DI)
+ MOVL CX,100(DI)
+ MOVL R8,104(DI)
+ MOVL R9,108(DI)
+ MOVD X15,DX
+ MOVD X11,CX
+ MOVD X1,R8
+ MOVD X6,R9
+ PSHUFL $0X39,X15,X15
+ PSHUFL $0X39,X11,X11
+ PSHUFL $0X39,X1,X1
+ PSHUFL $0X39,X6,X6
+ XORL 160(SI),DX
+ XORL 164(SI),CX
+ XORL 168(SI),R8
+ XORL 172(SI),R9
+ MOVL DX,160(DI)
+ MOVL CX,164(DI)
+ MOVL R8,168(DI)
+ MOVL R9,172(DI)
+ MOVD X15,DX
+ MOVD X11,CX
+ MOVD X1,R8
+ MOVD X6,R9
+ XORL 224(SI),DX
+ XORL 228(SI),CX
+ XORL 232(SI),R8
+ XORL 236(SI),R9
+ MOVL DX,224(DI)
+ MOVL CX,228(DI)
+ MOVL R8,232(DI)
+ MOVL R9,236(DI)
+ PADDL 160(SP),X13
+ PADDL 208(SP),X9
+ PADDL 256(SP),X3
+ PADDL 96(SP),X2
+ MOVD X13,DX
+ MOVD X9,CX
+ MOVD X3,R8
+ MOVD X2,R9
+ PSHUFL $0X39,X13,X13
+ PSHUFL $0X39,X9,X9
+ PSHUFL $0X39,X3,X3
+ PSHUFL $0X39,X2,X2
+ XORL 48(SI),DX
+ XORL 52(SI),CX
+ XORL 56(SI),R8
+ XORL 60(SI),R9
+ MOVL DX,48(DI)
+ MOVL CX,52(DI)
+ MOVL R8,56(DI)
+ MOVL R9,60(DI)
+ MOVD X13,DX
+ MOVD X9,CX
+ MOVD X3,R8
+ MOVD X2,R9
+ PSHUFL $0X39,X13,X13
+ PSHUFL $0X39,X9,X9
+ PSHUFL $0X39,X3,X3
+ PSHUFL $0X39,X2,X2
+ XORL 112(SI),DX
+ XORL 116(SI),CX
+ XORL 120(SI),R8
+ XORL 124(SI),R9
+ MOVL DX,112(DI)
+ MOVL CX,116(DI)
+ MOVL R8,120(DI)
+ MOVL R9,124(DI)
+ MOVD X13,DX
+ MOVD X9,CX
+ MOVD X3,R8
+ MOVD X2,R9
+ PSHUFL $0X39,X13,X13
+ PSHUFL $0X39,X9,X9
+ PSHUFL $0X39,X3,X3
+ PSHUFL $0X39,X2,X2
+ XORL 176(SI),DX
+ XORL 180(SI),CX
+ XORL 184(SI),R8
+ XORL 188(SI),R9
+ MOVL DX,176(DI)
+ MOVL CX,180(DI)
+ MOVL R8,184(DI)
+ MOVL R9,188(DI)
+ MOVD X13,DX
+ MOVD X9,CX
+ MOVD X3,R8
+ MOVD X2,R9
+ XORL 240(SI),DX
+ XORL 244(SI),CX
+ XORL 248(SI),R8
+ XORL 252(SI),R9
+ MOVL DX,240(DI)
+ MOVL CX,244(DI)
+ MOVL R8,248(DI)
+ MOVL R9,252(DI)
+ MOVQ 352(SP),R9
+ SUBQ $256,R9
+ ADDQ $256,SI
+ ADDQ $256,DI
+ CMPQ R9,$256
+ JAE BYTESATLEAST256
+ CMPQ R9,$0
+ JBE DONE
+ BYTESBETWEEN1AND255:
+ CMPQ R9,$64
+ JAE NOCOPY
+ MOVQ DI,DX
+ LEAQ 360(SP),DI
+ MOVQ R9,CX
+ REP; MOVSB
+ LEAQ 360(SP),DI
+ LEAQ 360(SP),SI
+ NOCOPY:
+ MOVQ R9,352(SP)
+ MOVOA 48(SP),X0
+ MOVOA 0(SP),X1
+ MOVOA 16(SP),X2
+ MOVOA 32(SP),X3
+ MOVOA X1,X4
+ MOVQ $20,CX
+ MAINLOOP2:
+ PADDL X0,X4
+ MOVOA X0,X5
+ MOVOA X4,X6
+ PSLLL $7,X4
+ PSRLL $25,X6
+ PXOR X4,X3
+ PXOR X6,X3
+ PADDL X3,X5
+ MOVOA X3,X4
+ MOVOA X5,X6
+ PSLLL $9,X5
+ PSRLL $23,X6
+ PXOR X5,X2
+ PSHUFL $0X93,X3,X3
+ PXOR X6,X2
+ PADDL X2,X4
+ MOVOA X2,X5
+ MOVOA X4,X6
+ PSLLL $13,X4
+ PSRLL $19,X6
+ PXOR X4,X1
+ PSHUFL $0X4E,X2,X2
+ PXOR X6,X1
+ PADDL X1,X5
+ MOVOA X3,X4
+ MOVOA X5,X6
+ PSLLL $18,X5
+ PSRLL $14,X6
+ PXOR X5,X0
+ PSHUFL $0X39,X1,X1
+ PXOR X6,X0
+ PADDL X0,X4
+ MOVOA X0,X5
+ MOVOA X4,X6
+ PSLLL $7,X4
+ PSRLL $25,X6
+ PXOR X4,X1
+ PXOR X6,X1
+ PADDL X1,X5
+ MOVOA X1,X4
+ MOVOA X5,X6
+ PSLLL $9,X5
+ PSRLL $23,X6
+ PXOR X5,X2
+ PSHUFL $0X93,X1,X1
+ PXOR X6,X2
+ PADDL X2,X4
+ MOVOA X2,X5
+ MOVOA X4,X6
+ PSLLL $13,X4
+ PSRLL $19,X6
+ PXOR X4,X3
+ PSHUFL $0X4E,X2,X2
+ PXOR X6,X3
+ PADDL X3,X5
+ MOVOA X1,X4
+ MOVOA X5,X6
+ PSLLL $18,X5
+ PSRLL $14,X6
+ PXOR X5,X0
+ PSHUFL $0X39,X3,X3
+ PXOR X6,X0
+ PADDL X0,X4
+ MOVOA X0,X5
+ MOVOA X4,X6
+ PSLLL $7,X4
+ PSRLL $25,X6
+ PXOR X4,X3
+ PXOR X6,X3
+ PADDL X3,X5
+ MOVOA X3,X4
+ MOVOA X5,X6
+ PSLLL $9,X5
+ PSRLL $23,X6
+ PXOR X5,X2
+ PSHUFL $0X93,X3,X3
+ PXOR X6,X2
+ PADDL X2,X4
+ MOVOA X2,X5
+ MOVOA X4,X6
+ PSLLL $13,X4
+ PSRLL $19,X6
+ PXOR X4,X1
+ PSHUFL $0X4E,X2,X2
+ PXOR X6,X1
+ PADDL X1,X5
+ MOVOA X3,X4
+ MOVOA X5,X6
+ PSLLL $18,X5
+ PSRLL $14,X6
+ PXOR X5,X0
+ PSHUFL $0X39,X1,X1
+ PXOR X6,X0
+ PADDL X0,X4
+ MOVOA X0,X5
+ MOVOA X4,X6
+ PSLLL $7,X4
+ PSRLL $25,X6
+ PXOR X4,X1
+ PXOR X6,X1
+ PADDL X1,X5
+ MOVOA X1,X4
+ MOVOA X5,X6
+ PSLLL $9,X5
+ PSRLL $23,X6
+ PXOR X5,X2
+ PSHUFL $0X93,X1,X1
+ PXOR X6,X2
+ PADDL X2,X4
+ MOVOA X2,X5
+ MOVOA X4,X6
+ PSLLL $13,X4
+ PSRLL $19,X6
+ PXOR X4,X3
+ PSHUFL $0X4E,X2,X2
+ PXOR X6,X3
+ SUBQ $4,CX
+ PADDL X3,X5
+ MOVOA X1,X4
+ MOVOA X5,X6
+ PSLLL $18,X5
+ PXOR X7,X7
+ PSRLL $14,X6
+ PXOR X5,X0
+ PSHUFL $0X39,X3,X3
+ PXOR X6,X0
+ JA MAINLOOP2
+ PADDL 48(SP),X0
+ PADDL 0(SP),X1
+ PADDL 16(SP),X2
+ PADDL 32(SP),X3
+ MOVD X0,CX
+ MOVD X1,R8
+ MOVD X2,R9
+ MOVD X3,AX
+ PSHUFL $0X39,X0,X0
+ PSHUFL $0X39,X1,X1
+ PSHUFL $0X39,X2,X2
+ PSHUFL $0X39,X3,X3
+ XORL 0(SI),CX
+ XORL 48(SI),R8
+ XORL 32(SI),R9
+ XORL 16(SI),AX
+ MOVL CX,0(DI)
+ MOVL R8,48(DI)
+ MOVL R9,32(DI)
+ MOVL AX,16(DI)
+ MOVD X0,CX
+ MOVD X1,R8
+ MOVD X2,R9
+ MOVD X3,AX
+ PSHUFL $0X39,X0,X0
+ PSHUFL $0X39,X1,X1
+ PSHUFL $0X39,X2,X2
+ PSHUFL $0X39,X3,X3
+ XORL 20(SI),CX
+ XORL 4(SI),R8
+ XORL 52(SI),R9
+ XORL 36(SI),AX
+ MOVL CX,20(DI)
+ MOVL R8,4(DI)
+ MOVL R9,52(DI)
+ MOVL AX,36(DI)
+ MOVD X0,CX
+ MOVD X1,R8
+ MOVD X2,R9
+ MOVD X3,AX
+ PSHUFL $0X39,X0,X0
+ PSHUFL $0X39,X1,X1
+ PSHUFL $0X39,X2,X2
+ PSHUFL $0X39,X3,X3
+ XORL 40(SI),CX
+ XORL 24(SI),R8
+ XORL 8(SI),R9
+ XORL 56(SI),AX
+ MOVL CX,40(DI)
+ MOVL R8,24(DI)
+ MOVL R9,8(DI)
+ MOVL AX,56(DI)
+ MOVD X0,CX
+ MOVD X1,R8
+ MOVD X2,R9
+ MOVD X3,AX
+ XORL 60(SI),CX
+ XORL 44(SI),R8
+ XORL 28(SI),R9
+ XORL 12(SI),AX
+ MOVL CX,60(DI)
+ MOVL R8,44(DI)
+ MOVL R9,28(DI)
+ MOVL AX,12(DI)
+ MOVQ 352(SP),R9
+ MOVL 16(SP),CX
+ MOVL 36 (SP),R8
+ ADDQ $1,CX
+ SHLQ $32,R8
+ ADDQ R8,CX
+ MOVQ CX,R8
+ SHRQ $32,R8
+ MOVL CX,16(SP)
+ MOVL R8, 36 (SP)
+ CMPQ R9,$64
+ JA BYTESATLEAST65
+ JAE BYTESATLEAST64
+ MOVQ DI,SI
+ MOVQ DX,DI
+ MOVQ R9,CX
+ REP; MOVSB
+ BYTESATLEAST64:
+ DONE:
+ MOVQ R12,SP
+ RET
+ BYTESATLEAST65:
+ SUBQ $64,R9
+ ADDQ $64,DI
+ ADDQ $64,SI
+ JMP BYTESBETWEEN1AND255
diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa208.go b/vendor/golang.org/x/crypto/salsa20/salsa/salsa208.go
new file mode 100644
index 0000000..9bfc092
--- /dev/null
+++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa208.go
@@ -0,0 +1,199 @@
+// 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 salsa
+
+// Core208 applies the Salsa20/8 core function to the 64-byte array in and puts
+// the result into the 64-byte array out. The input and output may be the same array.
+func Core208(out *[64]byte, in *[64]byte) {
+ j0 := uint32(in[0]) | uint32(in[1])<<8 | uint32(in[2])<<16 | uint32(in[3])<<24
+ j1 := uint32(in[4]) | uint32(in[5])<<8 | uint32(in[6])<<16 | uint32(in[7])<<24
+ j2 := uint32(in[8]) | uint32(in[9])<<8 | uint32(in[10])<<16 | uint32(in[11])<<24
+ j3 := uint32(in[12]) | uint32(in[13])<<8 | uint32(in[14])<<16 | uint32(in[15])<<24
+ j4 := uint32(in[16]) | uint32(in[17])<<8 | uint32(in[18])<<16 | uint32(in[19])<<24
+ j5 := uint32(in[20]) | uint32(in[21])<<8 | uint32(in[22])<<16 | uint32(in[23])<<24
+ j6 := uint32(in[24]) | uint32(in[25])<<8 | uint32(in[26])<<16 | uint32(in[27])<<24
+ j7 := uint32(in[28]) | uint32(in[29])<<8 | uint32(in[30])<<16 | uint32(in[31])<<24
+ j8 := uint32(in[32]) | uint32(in[33])<<8 | uint32(in[34])<<16 | uint32(in[35])<<24
+ j9 := uint32(in[36]) | uint32(in[37])<<8 | uint32(in[38])<<16 | uint32(in[39])<<24
+ j10 := uint32(in[40]) | uint32(in[41])<<8 | uint32(in[42])<<16 | uint32(in[43])<<24
+ j11 := uint32(in[44]) | uint32(in[45])<<8 | uint32(in[46])<<16 | uint32(in[47])<<24
+ j12 := uint32(in[48]) | uint32(in[49])<<8 | uint32(in[50])<<16 | uint32(in[51])<<24
+ j13 := uint32(in[52]) | uint32(in[53])<<8 | uint32(in[54])<<16 | uint32(in[55])<<24
+ j14 := uint32(in[56]) | uint32(in[57])<<8 | uint32(in[58])<<16 | uint32(in[59])<<24
+ j15 := uint32(in[60]) | uint32(in[61])<<8 | uint32(in[62])<<16 | uint32(in[63])<<24
+
+ x0, x1, x2, x3, x4, x5, x6, x7, x8 := j0, j1, j2, j3, j4, j5, j6, j7, j8
+ x9, x10, x11, x12, x13, x14, x15 := j9, j10, j11, j12, j13, j14, j15
+
+ for i := 0; i < 8; i += 2 {
+ u := x0 + x12
+ x4 ^= u<<7 | u>>(32-7)
+ u = x4 + x0
+ x8 ^= u<<9 | u>>(32-9)
+ u = x8 + x4
+ x12 ^= u<<13 | u>>(32-13)
+ u = x12 + x8
+ x0 ^= u<<18 | u>>(32-18)
+
+ u = x5 + x1
+ x9 ^= u<<7 | u>>(32-7)
+ u = x9 + x5
+ x13 ^= u<<9 | u>>(32-9)
+ u = x13 + x9
+ x1 ^= u<<13 | u>>(32-13)
+ u = x1 + x13
+ x5 ^= u<<18 | u>>(32-18)
+
+ u = x10 + x6
+ x14 ^= u<<7 | u>>(32-7)
+ u = x14 + x10
+ x2 ^= u<<9 | u>>(32-9)
+ u = x2 + x14
+ x6 ^= u<<13 | u>>(32-13)
+ u = x6 + x2
+ x10 ^= u<<18 | u>>(32-18)
+
+ u = x15 + x11
+ x3 ^= u<<7 | u>>(32-7)
+ u = x3 + x15
+ x7 ^= u<<9 | u>>(32-9)
+ u = x7 + x3
+ x11 ^= u<<13 | u>>(32-13)
+ u = x11 + x7
+ x15 ^= u<<18 | u>>(32-18)
+
+ u = x0 + x3
+ x1 ^= u<<7 | u>>(32-7)
+ u = x1 + x0
+ x2 ^= u<<9 | u>>(32-9)
+ u = x2 + x1
+ x3 ^= u<<13 | u>>(32-13)
+ u = x3 + x2
+ x0 ^= u<<18 | u>>(32-18)
+
+ u = x5 + x4
+ x6 ^= u<<7 | u>>(32-7)
+ u = x6 + x5
+ x7 ^= u<<9 | u>>(32-9)
+ u = x7 + x6
+ x4 ^= u<<13 | u>>(32-13)
+ u = x4 + x7
+ x5 ^= u<<18 | u>>(32-18)
+
+ u = x10 + x9
+ x11 ^= u<<7 | u>>(32-7)
+ u = x11 + x10
+ x8 ^= u<<9 | u>>(32-9)
+ u = x8 + x11
+ x9 ^= u<<13 | u>>(32-13)
+ u = x9 + x8
+ x10 ^= u<<18 | u>>(32-18)
+
+ u = x15 + x14
+ x12 ^= u<<7 | u>>(32-7)
+ u = x12 + x15
+ x13 ^= u<<9 | u>>(32-9)
+ u = x13 + x12
+ x14 ^= u<<13 | u>>(32-13)
+ u = x14 + x13
+ x15 ^= u<<18 | u>>(32-18)
+ }
+ x0 += j0
+ x1 += j1
+ x2 += j2
+ x3 += j3
+ x4 += j4
+ x5 += j5
+ x6 += j6
+ x7 += j7
+ x8 += j8
+ x9 += j9
+ x10 += j10
+ x11 += j11
+ x12 += j12
+ x13 += j13
+ x14 += j14
+ x15 += j15
+
+ out[0] = byte(x0)
+ out[1] = byte(x0 >> 8)
+ out[2] = byte(x0 >> 16)
+ out[3] = byte(x0 >> 24)
+
+ out[4] = byte(x1)
+ out[5] = byte(x1 >> 8)
+ out[6] = byte(x1 >> 16)
+ out[7] = byte(x1 >> 24)
+
+ out[8] = byte(x2)
+ out[9] = byte(x2 >> 8)
+ out[10] = byte(x2 >> 16)
+ out[11] = byte(x2 >> 24)
+
+ out[12] = byte(x3)
+ out[13] = byte(x3 >> 8)
+ out[14] = byte(x3 >> 16)
+ out[15] = byte(x3 >> 24)
+
+ out[16] = byte(x4)
+ out[17] = byte(x4 >> 8)
+ out[18] = byte(x4 >> 16)
+ out[19] = byte(x4 >> 24)
+
+ out[20] = byte(x5)
+ out[21] = byte(x5 >> 8)
+ out[22] = byte(x5 >> 16)
+ out[23] = byte(x5 >> 24)
+
+ out[24] = byte(x6)
+ out[25] = byte(x6 >> 8)
+ out[26] = byte(x6 >> 16)
+ out[27] = byte(x6 >> 24)
+
+ out[28] = byte(x7)
+ out[29] = byte(x7 >> 8)
+ out[30] = byte(x7 >> 16)
+ out[31] = byte(x7 >> 24)
+
+ out[32] = byte(x8)
+ out[33] = byte(x8 >> 8)
+ out[34] = byte(x8 >> 16)
+ out[35] = byte(x8 >> 24)
+
+ out[36] = byte(x9)
+ out[37] = byte(x9 >> 8)
+ out[38] = byte(x9 >> 16)
+ out[39] = byte(x9 >> 24)
+
+ out[40] = byte(x10)
+ out[41] = byte(x10 >> 8)
+ out[42] = byte(x10 >> 16)
+ out[43] = byte(x10 >> 24)
+
+ out[44] = byte(x11)
+ out[45] = byte(x11 >> 8)
+ out[46] = byte(x11 >> 16)
+ out[47] = byte(x11 >> 24)
+
+ out[48] = byte(x12)
+ out[49] = byte(x12 >> 8)
+ out[50] = byte(x12 >> 16)
+ out[51] = byte(x12 >> 24)
+
+ out[52] = byte(x13)
+ out[53] = byte(x13 >> 8)
+ out[54] = byte(x13 >> 16)
+ out[55] = byte(x13 >> 24)
+
+ out[56] = byte(x14)
+ out[57] = byte(x14 >> 8)
+ out[58] = byte(x14 >> 16)
+ out[59] = byte(x14 >> 24)
+
+ out[60] = byte(x15)
+ out[61] = byte(x15 >> 8)
+ out[62] = byte(x15 >> 16)
+ out[63] = byte(x15 >> 24)
+}
diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go
new file mode 100644
index 0000000..903c785
--- /dev/null
+++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_amd64.go
@@ -0,0 +1,23 @@
+// 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,!appengine,!gccgo
+
+package salsa
+
+// This function is implemented in salsa2020_amd64.s.
+
+//go:noescape
+
+func salsa2020XORKeyStream(out, in *byte, n uint64, nonce, key *byte)
+
+// XORKeyStream crypts bytes from in to out using the given key and counters.
+// In and out may be the same slice but otherwise should not overlap. Counter
+// contains the raw salsa20 counter bytes (both nonce and block counter).
+func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) {
+ if len(in) == 0 {
+ return
+ }
+ salsa2020XORKeyStream(&out[0], &in[0], uint64(len(in)), &counter[0], &key[0])
+}
diff --git a/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_ref.go b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_ref.go
new file mode 100644
index 0000000..95f8ca5
--- /dev/null
+++ b/vendor/golang.org/x/crypto/salsa20/salsa/salsa20_ref.go
@@ -0,0 +1,234 @@
+// 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 appengine gccgo
+
+package salsa
+
+const rounds = 20
+
+// core applies the Salsa20 core function to 16-byte input in, 32-byte key k,
+// and 16-byte constant c, and puts the result into 64-byte array out.
+func core(out *[64]byte, in *[16]byte, k *[32]byte, c *[16]byte) {
+ j0 := uint32(c[0]) | uint32(c[1])<<8 | uint32(c[2])<<16 | uint32(c[3])<<24
+ j1 := uint32(k[0]) | uint32(k[1])<<8 | uint32(k[2])<<16 | uint32(k[3])<<24
+ j2 := uint32(k[4]) | uint32(k[5])<<8 | uint32(k[6])<<16 | uint32(k[7])<<24
+ j3 := uint32(k[8]) | uint32(k[9])<<8 | uint32(k[10])<<16 | uint32(k[11])<<24
+ j4 := uint32(k[12]) | uint32(k[13])<<8 | uint32(k[14])<<16 | uint32(k[15])<<24
+ j5 := uint32(c[4]) | uint32(c[5])<<8 | uint32(c[6])<<16 | uint32(c[7])<<24
+ j6 := uint32(in[0]) | uint32(in[1])<<8 | uint32(in[2])<<16 | uint32(in[3])<<24
+ j7 := uint32(in[4]) | uint32(in[5])<<8 | uint32(in[6])<<16 | uint32(in[7])<<24
+ j8 := uint32(in[8]) | uint32(in[9])<<8 | uint32(in[10])<<16 | uint32(in[11])<<24
+ j9 := uint32(in[12]) | uint32(in[13])<<8 | uint32(in[14])<<16 | uint32(in[15])<<24
+ j10 := uint32(c[8]) | uint32(c[9])<<8 | uint32(c[10])<<16 | uint32(c[11])<<24
+ j11 := uint32(k[16]) | uint32(k[17])<<8 | uint32(k[18])<<16 | uint32(k[19])<<24
+ j12 := uint32(k[20]) | uint32(k[21])<<8 | uint32(k[22])<<16 | uint32(k[23])<<24
+ j13 := uint32(k[24]) | uint32(k[25])<<8 | uint32(k[26])<<16 | uint32(k[27])<<24
+ j14 := uint32(k[28]) | uint32(k[29])<<8 | uint32(k[30])<<16 | uint32(k[31])<<24
+ j15 := uint32(c[12]) | uint32(c[13])<<8 | uint32(c[14])<<16 | uint32(c[15])<<24
+
+ x0, x1, x2, x3, x4, x5, x6, x7, x8 := j0, j1, j2, j3, j4, j5, j6, j7, j8
+ x9, x10, x11, x12, x13, x14, x15 := j9, j10, j11, j12, j13, j14, j15
+
+ for i := 0; i < rounds; i += 2 {
+ u := x0 + x12
+ x4 ^= u<<7 | u>>(32-7)
+ u = x4 + x0
+ x8 ^= u<<9 | u>>(32-9)
+ u = x8 + x4
+ x12 ^= u<<13 | u>>(32-13)
+ u = x12 + x8
+ x0 ^= u<<18 | u>>(32-18)
+
+ u = x5 + x1
+ x9 ^= u<<7 | u>>(32-7)
+ u = x9 + x5
+ x13 ^= u<<9 | u>>(32-9)
+ u = x13 + x9
+ x1 ^= u<<13 | u>>(32-13)
+ u = x1 + x13
+ x5 ^= u<<18 | u>>(32-18)
+
+ u = x10 + x6
+ x14 ^= u<<7 | u>>(32-7)
+ u = x14 + x10
+ x2 ^= u<<9 | u>>(32-9)
+ u = x2 + x14
+ x6 ^= u<<13 | u>>(32-13)
+ u = x6 + x2
+ x10 ^= u<<18 | u>>(32-18)
+
+ u = x15 + x11
+ x3 ^= u<<7 | u>>(32-7)
+ u = x3 + x15
+ x7 ^= u<<9 | u>>(32-9)
+ u = x7 + x3
+ x11 ^= u<<13 | u>>(32-13)
+ u = x11 + x7
+ x15 ^= u<<18 | u>>(32-18)
+
+ u = x0 + x3
+ x1 ^= u<<7 | u>>(32-7)
+ u = x1 + x0
+ x2 ^= u<<9 | u>>(32-9)
+ u = x2 + x1
+ x3 ^= u<<13 | u>>(32-13)
+ u = x3 + x2
+ x0 ^= u<<18 | u>>(32-18)
+
+ u = x5 + x4
+ x6 ^= u<<7 | u>>(32-7)
+ u = x6 + x5
+ x7 ^= u<<9 | u>>(32-9)
+ u = x7 + x6
+ x4 ^= u<<13 | u>>(32-13)
+ u = x4 + x7
+ x5 ^= u<<18 | u>>(32-18)
+
+ u = x10 + x9
+ x11 ^= u<<7 | u>>(32-7)
+ u = x11 + x10
+ x8 ^= u<<9 | u>>(32-9)
+ u = x8 + x11
+ x9 ^= u<<13 | u>>(32-13)
+ u = x9 + x8
+ x10 ^= u<<18 | u>>(32-18)
+
+ u = x15 + x14
+ x12 ^= u<<7 | u>>(32-7)
+ u = x12 + x15
+ x13 ^= u<<9 | u>>(32-9)
+ u = x13 + x12
+ x14 ^= u<<13 | u>>(32-13)
+ u = x14 + x13
+ x15 ^= u<<18 | u>>(32-18)
+ }
+ x0 += j0
+ x1 += j1
+ x2 += j2
+ x3 += j3
+ x4 += j4
+ x5 += j5
+ x6 += j6
+ x7 += j7
+ x8 += j8
+ x9 += j9
+ x10 += j10
+ x11 += j11
+ x12 += j12
+ x13 += j13
+ x14 += j14
+ x15 += j15
+
+ out[0] = byte(x0)
+ out[1] = byte(x0 >> 8)
+ out[2] = byte(x0 >> 16)
+ out[3] = byte(x0 >> 24)
+
+ out[4] = byte(x1)
+ out[5] = byte(x1 >> 8)
+ out[6] = byte(x1 >> 16)
+ out[7] = byte(x1 >> 24)
+
+ out[8] = byte(x2)
+ out[9] = byte(x2 >> 8)
+ out[10] = byte(x2 >> 16)
+ out[11] = byte(x2 >> 24)
+
+ out[12] = byte(x3)
+ out[13] = byte(x3 >> 8)
+ out[14] = byte(x3 >> 16)
+ out[15] = byte(x3 >> 24)
+
+ out[16] = byte(x4)
+ out[17] = byte(x4 >> 8)
+ out[18] = byte(x4 >> 16)
+ out[19] = byte(x4 >> 24)
+
+ out[20] = byte(x5)
+ out[21] = byte(x5 >> 8)
+ out[22] = byte(x5 >> 16)
+ out[23] = byte(x5 >> 24)
+
+ out[24] = byte(x6)
+ out[25] = byte(x6 >> 8)
+ out[26] = byte(x6 >> 16)
+ out[27] = byte(x6 >> 24)
+
+ out[28] = byte(x7)
+ out[29] = byte(x7 >> 8)
+ out[30] = byte(x7 >> 16)
+ out[31] = byte(x7 >> 24)
+
+ out[32] = byte(x8)
+ out[33] = byte(x8 >> 8)
+ out[34] = byte(x8 >> 16)
+ out[35] = byte(x8 >> 24)
+
+ out[36] = byte(x9)
+ out[37] = byte(x9 >> 8)
+ out[38] = byte(x9 >> 16)
+ out[39] = byte(x9 >> 24)
+
+ out[40] = byte(x10)
+ out[41] = byte(x10 >> 8)
+ out[42] = byte(x10 >> 16)
+ out[43] = byte(x10 >> 24)
+
+ out[44] = byte(x11)
+ out[45] = byte(x11 >> 8)
+ out[46] = byte(x11 >> 16)
+ out[47] = byte(x11 >> 24)
+
+ out[48] = byte(x12)
+ out[49] = byte(x12 >> 8)
+ out[50] = byte(x12 >> 16)
+ out[51] = byte(x12 >> 24)
+
+ out[52] = byte(x13)
+ out[53] = byte(x13 >> 8)
+ out[54] = byte(x13 >> 16)
+ out[55] = byte(x13 >> 24)
+
+ out[56] = byte(x14)
+ out[57] = byte(x14 >> 8)
+ out[58] = byte(x14 >> 16)
+ out[59] = byte(x14 >> 24)
+
+ out[60] = byte(x15)
+ out[61] = byte(x15 >> 8)
+ out[62] = byte(x15 >> 16)
+ out[63] = byte(x15 >> 24)
+}
+
+// XORKeyStream crypts bytes from in to out using the given key and counters.
+// In and out may be the same slice but otherwise should not overlap. Counter
+// contains the raw salsa20 counter bytes (both nonce and block counter).
+func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) {
+ var block [64]byte
+ var counterCopy [16]byte
+ copy(counterCopy[:], counter[:])
+
+ for len(in) >= 64 {
+ core(&block, &counterCopy, key, &Sigma)
+ for i, x := range block {
+ out[i] = in[i] ^ x
+ }
+ u := uint32(1)
+ for i := 8; i < 16; i++ {
+ u += uint32(counterCopy[i])
+ counterCopy[i] = byte(u)
+ u >>= 8
+ }
+ in = in[64:]
+ out = out[64:]
+ }
+
+ if len(in) > 0 {
+ core(&block, &counterCopy, key, &Sigma)
+ for i, v := range in {
+ out[i] = v ^ block[i]
+ }
+ }
+}
diff --git a/vendor/golang.org/x/net/LICENSE b/vendor/golang.org/x/net/LICENSE
new file mode 100644
index 0000000..6a66aea
--- /dev/null
+++ b/vendor/golang.org/x/net/LICENSE
@@ -0,0 +1,27 @@
+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/net/PATENTS b/vendor/golang.org/x/net/PATENTS
new file mode 100644
index 0000000..7330990
--- /dev/null
+++ b/vendor/golang.org/x/net/PATENTS
@@ -0,0 +1,22 @@
+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/net/README b/vendor/golang.org/x/net/README
new file mode 100644
index 0000000..6b13d8e
--- /dev/null
+++ b/vendor/golang.org/x/net/README
@@ -0,0 +1,3 @@
+This repository holds supplementary Go networking libraries.
+
+To submit changes to this repository, see http://golang.org/doc/contribute.html.
diff --git a/vendor/golang.org/x/net/context/context.go b/vendor/golang.org/x/net/context/context.go
new file mode 100644
index 0000000..f143ed6
--- /dev/null
+++ b/vendor/golang.org/x/net/context/context.go
@@ -0,0 +1,156 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package context defines the Context type, which carries deadlines,
+// cancelation signals, and other request-scoped values across API boundaries
+// and between processes.
+//
+// Incoming requests to a server should create a Context, and outgoing calls to
+// servers should accept a Context. The chain of function calls between must
+// propagate the Context, optionally replacing it with a modified copy created
+// using WithDeadline, WithTimeout, WithCancel, or WithValue.
+//
+// Programs that use Contexts should follow these rules to keep interfaces
+// consistent across packages and enable static analysis tools to check context
+// propagation:
+//
+// Do not store Contexts inside a struct type; instead, pass a Context
+// explicitly to each function that needs it. The Context should be the first
+// parameter, typically named ctx:
+//
+// func DoSomething(ctx context.Context, arg Arg) error {
+// // ... use ctx ...
+// }
+//
+// Do not pass a nil Context, even if a function permits it. Pass context.TODO
+// if you are unsure about which Context to use.
+//
+// Use context Values only for request-scoped data that transits processes and
+// APIs, not for passing optional parameters to functions.
+//
+// The same Context may be passed to functions running in different goroutines;
+// Contexts are safe for simultaneous use by multiple goroutines.
+//
+// See http://blog.golang.org/context for example code for a server that uses
+// Contexts.
+package context // import "golang.org/x/net/context"
+
+import "time"
+
+// A Context carries a deadline, a cancelation signal, and other values across
+// API boundaries.
+//
+// Context's methods may be called by multiple goroutines simultaneously.
+type Context interface {
+ // Deadline returns the time when work done on behalf of this context
+ // should be canceled. Deadline returns ok==false when no deadline is
+ // set. Successive calls to Deadline return the same results.
+ Deadline() (deadline time.Time, ok bool)
+
+ // Done returns a channel that's closed when work done on behalf of this
+ // context should be canceled. Done may return nil if this context can
+ // never be canceled. Successive calls to Done return the same value.
+ //
+ // WithCancel arranges for Done to be closed when cancel is called;
+ // WithDeadline arranges for Done to be closed when the deadline
+ // expires; WithTimeout arranges for Done to be closed when the timeout
+ // elapses.
+ //
+ // Done is provided for use in select statements:
+ //
+ // // Stream generates values with DoSomething and sends them to out
+ // // until DoSomething returns an error or ctx.Done is closed.
+ // func Stream(ctx context.Context, out chan<- Value) error {
+ // for {
+ // v, err := DoSomething(ctx)
+ // if err != nil {
+ // return err
+ // }
+ // select {
+ // case <-ctx.Done():
+ // return ctx.Err()
+ // case out <- v:
+ // }
+ // }
+ // }
+ //
+ // See http://blog.golang.org/pipelines for more examples of how to use
+ // a Done channel for cancelation.
+ Done() <-chan struct{}
+
+ // Err returns a non-nil error value after Done is closed. Err returns
+ // Canceled if the context was canceled or DeadlineExceeded if the
+ // context's deadline passed. No other values for Err are defined.
+ // After Done is closed, successive calls to Err return the same value.
+ Err() error
+
+ // Value returns the value associated with this context for key, or nil
+ // if no value is associated with key. Successive calls to Value with
+ // the same key returns the same result.
+ //
+ // Use context values only for request-scoped data that transits
+ // processes and API boundaries, not for passing optional parameters to
+ // functions.
+ //
+ // A key identifies a specific value in a Context. Functions that wish
+ // to store values in Context typically allocate a key in a global
+ // variable then use that key as the argument to context.WithValue and
+ // Context.Value. A key can be any type that supports equality;
+ // packages should define keys as an unexported type to avoid
+ // collisions.
+ //
+ // Packages that define a Context key should provide type-safe accessors
+ // for the values stores using that key:
+ //
+ // // Package user defines a User type that's stored in Contexts.
+ // package user
+ //
+ // import "golang.org/x/net/context"
+ //
+ // // User is the type of value stored in the Contexts.
+ // type User struct {...}
+ //
+ // // key is an unexported type for keys defined in this package.
+ // // This prevents collisions with keys defined in other packages.
+ // type key int
+ //
+ // // userKey is the key for user.User values in Contexts. It is
+ // // unexported; clients use user.NewContext and user.FromContext
+ // // instead of using this key directly.
+ // var userKey key = 0
+ //
+ // // NewContext returns a new Context that carries value u.
+ // func NewContext(ctx context.Context, u *User) context.Context {
+ // return context.WithValue(ctx, userKey, u)
+ // }
+ //
+ // // FromContext returns the User value stored in ctx, if any.
+ // func FromContext(ctx context.Context) (*User, bool) {
+ // u, ok := ctx.Value(userKey).(*User)
+ // return u, ok
+ // }
+ Value(key interface{}) interface{}
+}
+
+// Background returns a non-nil, empty Context. It is never canceled, has no
+// values, and has no deadline. It is typically used by the main function,
+// initialization, and tests, and as the top-level Context for incoming
+// requests.
+func Background() Context {
+ return background
+}
+
+// TODO returns a non-nil, empty Context. Code should use context.TODO when
+// it's unclear which Context to use or it is not yet available (because the
+// surrounding function has not yet been extended to accept a Context
+// parameter). TODO is recognized by static analysis tools that determine
+// whether Contexts are propagated correctly in a program.
+func TODO() Context {
+ return todo
+}
+
+// A CancelFunc tells an operation to abandon its work.
+// A CancelFunc does not wait for the work to stop.
+// After the first call, subsequent calls to a CancelFunc do nothing.
+type CancelFunc func()
diff --git a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go
new file mode 100644
index 0000000..606cf1f
--- /dev/null
+++ b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go
@@ -0,0 +1,74 @@
+// 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 go1.7
+
+// Package ctxhttp provides helper functions for performing context-aware HTTP requests.
+package ctxhttp // import "golang.org/x/net/context/ctxhttp"
+
+import (
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+
+ "golang.org/x/net/context"
+)
+
+// Do sends an HTTP request with the provided http.Client and returns
+// an HTTP response.
+//
+// If the client is nil, http.DefaultClient is used.
+//
+// The provided ctx must be non-nil. If it is canceled or times out,
+// ctx.Err() will be returned.
+func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
+ if client == nil {
+ client = http.DefaultClient
+ }
+ resp, err := client.Do(req.WithContext(ctx))
+ // If we got an error, and the context has been canceled,
+ // the context's error is probably more useful.
+ if err != nil {
+ select {
+ case <-ctx.Done():
+ err = ctx.Err()
+ default:
+ }
+ }
+ return resp, err
+}
+
+// Get issues a GET request via the Do function.
+func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
+ req, err := http.NewRequest("GET", url, nil)
+ if err != nil {
+ return nil, err
+ }
+ return Do(ctx, client, req)
+}
+
+// Head issues a HEAD request via the Do function.
+func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
+ req, err := http.NewRequest("HEAD", url, nil)
+ if err != nil {
+ return nil, err
+ }
+ return Do(ctx, client, req)
+}
+
+// Post issues a POST request via the Do function.
+func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) {
+ req, err := http.NewRequest("POST", url, body)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", bodyType)
+ return Do(ctx, client, req)
+}
+
+// PostForm issues a POST request via the Do function.
+func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) {
+ return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
+}
diff --git a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go
new file mode 100644
index 0000000..926870c
--- /dev/null
+++ b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go
@@ -0,0 +1,147 @@
+// Copyright 2015 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 !go1.7
+
+package ctxhttp // import "golang.org/x/net/context/ctxhttp"
+
+import (
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+
+ "golang.org/x/net/context"
+)
+
+func nop() {}
+
+var (
+ testHookContextDoneBeforeHeaders = nop
+ testHookDoReturned = nop
+ testHookDidBodyClose = nop
+)
+
+// Do sends an HTTP request with the provided http.Client and returns an HTTP response.
+// If the client is nil, http.DefaultClient is used.
+// If the context is canceled or times out, ctx.Err() will be returned.
+func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
+ if client == nil {
+ client = http.DefaultClient
+ }
+
+ // TODO(djd): Respect any existing value of req.Cancel.
+ cancel := make(chan struct{})
+ req.Cancel = cancel
+
+ type responseAndError struct {
+ resp *http.Response
+ err error
+ }
+ result := make(chan responseAndError, 1)
+
+ // Make local copies of test hooks closed over by goroutines below.
+ // Prevents data races in tests.
+ testHookDoReturned := testHookDoReturned
+ testHookDidBodyClose := testHookDidBodyClose
+
+ go func() {
+ resp, err := client.Do(req)
+ testHookDoReturned()
+ result <- responseAndError{resp, err}
+ }()
+
+ var resp *http.Response
+
+ select {
+ case <-ctx.Done():
+ testHookContextDoneBeforeHeaders()
+ close(cancel)
+ // Clean up after the goroutine calling client.Do:
+ go func() {
+ if r := <-result; r.resp != nil {
+ testHookDidBodyClose()
+ r.resp.Body.Close()
+ }
+ }()
+ return nil, ctx.Err()
+ case r := <-result:
+ var err error
+ resp, err = r.resp, r.err
+ if err != nil {
+ return resp, err
+ }
+ }
+
+ c := make(chan struct{})
+ go func() {
+ select {
+ case <-ctx.Done():
+ close(cancel)
+ case <-c:
+ // The response's Body is closed.
+ }
+ }()
+ resp.Body = &notifyingReader{resp.Body, c}
+
+ return resp, nil
+}
+
+// Get issues a GET request via the Do function.
+func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
+ req, err := http.NewRequest("GET", url, nil)
+ if err != nil {
+ return nil, err
+ }
+ return Do(ctx, client, req)
+}
+
+// Head issues a HEAD request via the Do function.
+func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
+ req, err := http.NewRequest("HEAD", url, nil)
+ if err != nil {
+ return nil, err
+ }
+ return Do(ctx, client, req)
+}
+
+// Post issues a POST request via the Do function.
+func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) {
+ req, err := http.NewRequest("POST", url, body)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", bodyType)
+ return Do(ctx, client, req)
+}
+
+// PostForm issues a POST request via the Do function.
+func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) {
+ return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
+}
+
+// notifyingReader is an io.ReadCloser that closes the notify channel after
+// Close is called or a Read fails on the underlying ReadCloser.
+type notifyingReader struct {
+ io.ReadCloser
+ notify chan<- struct{}
+}
+
+func (r *notifyingReader) Read(p []byte) (int, error) {
+ n, err := r.ReadCloser.Read(p)
+ if err != nil && r.notify != nil {
+ close(r.notify)
+ r.notify = nil
+ }
+ return n, err
+}
+
+func (r *notifyingReader) Close() error {
+ err := r.ReadCloser.Close()
+ if r.notify != nil {
+ close(r.notify)
+ r.notify = nil
+ }
+ return err
+}
diff --git a/vendor/golang.org/x/net/context/go17.go b/vendor/golang.org/x/net/context/go17.go
new file mode 100644
index 0000000..d20f52b
--- /dev/null
+++ b/vendor/golang.org/x/net/context/go17.go
@@ -0,0 +1,72 @@
+// 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 go1.7
+
+package context
+
+import (
+ "context" // standard library's context, as of Go 1.7
+ "time"
+)
+
+var (
+ todo = context.TODO()
+ background = context.Background()
+)
+
+// Canceled is the error returned by Context.Err when the context is canceled.
+var Canceled = context.Canceled
+
+// DeadlineExceeded is the error returned by Context.Err when the context's
+// deadline passes.
+var DeadlineExceeded = context.DeadlineExceeded
+
+// WithCancel returns a copy of parent with a new Done channel. The returned
+// context's Done channel is closed when the returned cancel function is called
+// or when the parent context's Done channel is closed, whichever happens first.
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete.
+func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
+ ctx, f := context.WithCancel(parent)
+ return ctx, CancelFunc(f)
+}
+
+// WithDeadline returns a copy of the parent context with the deadline adjusted
+// to be no later than d. If the parent's deadline is already earlier than d,
+// WithDeadline(parent, d) is semantically equivalent to parent. The returned
+// context's Done channel is closed when the deadline expires, when the returned
+// cancel function is called, or when the parent context's Done channel is
+// closed, whichever happens first.
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete.
+func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
+ ctx, f := context.WithDeadline(parent, deadline)
+ return ctx, CancelFunc(f)
+}
+
+// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete:
+//
+// func slowOperationWithTimeout(ctx context.Context) (Result, error) {
+// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
+// defer cancel() // releases resources if slowOperation completes before timeout elapses
+// return slowOperation(ctx)
+// }
+func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
+ return WithDeadline(parent, time.Now().Add(timeout))
+}
+
+// WithValue returns a copy of parent in which the value associated with key is
+// val.
+//
+// Use context Values only for request-scoped data that transits processes and
+// APIs, not for passing optional parameters to functions.
+func WithValue(parent Context, key interface{}, val interface{}) Context {
+ return context.WithValue(parent, key, val)
+}
diff --git a/vendor/golang.org/x/net/context/pre_go17.go b/vendor/golang.org/x/net/context/pre_go17.go
new file mode 100644
index 0000000..0f35592
--- /dev/null
+++ b/vendor/golang.org/x/net/context/pre_go17.go
@@ -0,0 +1,300 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !go1.7
+
+package context
+
+import (
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+)
+
+// An emptyCtx is never canceled, has no values, and has no deadline. It is not
+// struct{}, since vars of this type must have distinct addresses.
+type emptyCtx int
+
+func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
+ return
+}
+
+func (*emptyCtx) Done() <-chan struct{} {
+ return nil
+}
+
+func (*emptyCtx) Err() error {
+ return nil
+}
+
+func (*emptyCtx) Value(key interface{}) interface{} {
+ return nil
+}
+
+func (e *emptyCtx) String() string {
+ switch e {
+ case background:
+ return "context.Background"
+ case todo:
+ return "context.TODO"
+ }
+ return "unknown empty Context"
+}
+
+var (
+ background = new(emptyCtx)
+ todo = new(emptyCtx)
+)
+
+// Canceled is the error returned by Context.Err when the context is canceled.
+var Canceled = errors.New("context canceled")
+
+// DeadlineExceeded is the error returned by Context.Err when the context's
+// deadline passes.
+var DeadlineExceeded = errors.New("context deadline exceeded")
+
+// WithCancel returns a copy of parent with a new Done channel. The returned
+// context's Done channel is closed when the returned cancel function is called
+// or when the parent context's Done channel is closed, whichever happens first.
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete.
+func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
+ c := newCancelCtx(parent)
+ propagateCancel(parent, c)
+ return c, func() { c.cancel(true, Canceled) }
+}
+
+// newCancelCtx returns an initialized cancelCtx.
+func newCancelCtx(parent Context) *cancelCtx {
+ return &cancelCtx{
+ Context: parent,
+ done: make(chan struct{}),
+ }
+}
+
+// propagateCancel arranges for child to be canceled when parent is.
+func propagateCancel(parent Context, child canceler) {
+ if parent.Done() == nil {
+ return // parent is never canceled
+ }
+ if p, ok := parentCancelCtx(parent); ok {
+ p.mu.Lock()
+ if p.err != nil {
+ // parent has already been canceled
+ child.cancel(false, p.err)
+ } else {
+ if p.children == nil {
+ p.children = make(map[canceler]bool)
+ }
+ p.children[child] = true
+ }
+ p.mu.Unlock()
+ } else {
+ go func() {
+ select {
+ case <-parent.Done():
+ child.cancel(false, parent.Err())
+ case <-child.Done():
+ }
+ }()
+ }
+}
+
+// parentCancelCtx follows a chain of parent references until it finds a
+// *cancelCtx. This function understands how each of the concrete types in this
+// package represents its parent.
+func parentCancelCtx(parent Context) (*cancelCtx, bool) {
+ for {
+ switch c := parent.(type) {
+ case *cancelCtx:
+ return c, true
+ case *timerCtx:
+ return c.cancelCtx, true
+ case *valueCtx:
+ parent = c.Context
+ default:
+ return nil, false
+ }
+ }
+}
+
+// removeChild removes a context from its parent.
+func removeChild(parent Context, child canceler) {
+ p, ok := parentCancelCtx(parent)
+ if !ok {
+ return
+ }
+ p.mu.Lock()
+ if p.children != nil {
+ delete(p.children, child)
+ }
+ p.mu.Unlock()
+}
+
+// A canceler is a context type that can be canceled directly. The
+// implementations are *cancelCtx and *timerCtx.
+type canceler interface {
+ cancel(removeFromParent bool, err error)
+ Done() <-chan struct{}
+}
+
+// A cancelCtx can be canceled. When canceled, it also cancels any children
+// that implement canceler.
+type cancelCtx struct {
+ Context
+
+ done chan struct{} // closed by the first cancel call.
+
+ mu sync.Mutex
+ children map[canceler]bool // set to nil by the first cancel call
+ err error // set to non-nil by the first cancel call
+}
+
+func (c *cancelCtx) Done() <-chan struct{} {
+ return c.done
+}
+
+func (c *cancelCtx) Err() error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.err
+}
+
+func (c *cancelCtx) String() string {
+ return fmt.Sprintf("%v.WithCancel", c.Context)
+}
+
+// cancel closes c.done, cancels each of c's children, and, if
+// removeFromParent is true, removes c from its parent's children.
+func (c *cancelCtx) cancel(removeFromParent bool, err error) {
+ if err == nil {
+ panic("context: internal error: missing cancel error")
+ }
+ c.mu.Lock()
+ if c.err != nil {
+ c.mu.Unlock()
+ return // already canceled
+ }
+ c.err = err
+ close(c.done)
+ for child := range c.children {
+ // NOTE: acquiring the child's lock while holding parent's lock.
+ child.cancel(false, err)
+ }
+ c.children = nil
+ c.mu.Unlock()
+
+ if removeFromParent {
+ removeChild(c.Context, c)
+ }
+}
+
+// WithDeadline returns a copy of the parent context with the deadline adjusted
+// to be no later than d. If the parent's deadline is already earlier than d,
+// WithDeadline(parent, d) is semantically equivalent to parent. The returned
+// context's Done channel is closed when the deadline expires, when the returned
+// cancel function is called, or when the parent context's Done channel is
+// closed, whichever happens first.
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete.
+func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
+ if cur, ok := parent.Deadline(); ok && cur.Before(deadline) {
+ // The current deadline is already sooner than the new one.
+ return WithCancel(parent)
+ }
+ c := &timerCtx{
+ cancelCtx: newCancelCtx(parent),
+ deadline: deadline,
+ }
+ propagateCancel(parent, c)
+ d := deadline.Sub(time.Now())
+ if d <= 0 {
+ c.cancel(true, DeadlineExceeded) // deadline has already passed
+ return c, func() { c.cancel(true, Canceled) }
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err == nil {
+ c.timer = time.AfterFunc(d, func() {
+ c.cancel(true, DeadlineExceeded)
+ })
+ }
+ return c, func() { c.cancel(true, Canceled) }
+}
+
+// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
+// implement Done and Err. It implements cancel by stopping its timer then
+// delegating to cancelCtx.cancel.
+type timerCtx struct {
+ *cancelCtx
+ timer *time.Timer // Under cancelCtx.mu.
+
+ deadline time.Time
+}
+
+func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
+ return c.deadline, true
+}
+
+func (c *timerCtx) String() string {
+ return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now()))
+}
+
+func (c *timerCtx) cancel(removeFromParent bool, err error) {
+ c.cancelCtx.cancel(false, err)
+ if removeFromParent {
+ // Remove this timerCtx from its parent cancelCtx's children.
+ removeChild(c.cancelCtx.Context, c)
+ }
+ c.mu.Lock()
+ if c.timer != nil {
+ c.timer.Stop()
+ c.timer = nil
+ }
+ c.mu.Unlock()
+}
+
+// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
+//
+// Canceling this context releases resources associated with it, so code should
+// call cancel as soon as the operations running in this Context complete:
+//
+// func slowOperationWithTimeout(ctx context.Context) (Result, error) {
+// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
+// defer cancel() // releases resources if slowOperation completes before timeout elapses
+// return slowOperation(ctx)
+// }
+func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
+ return WithDeadline(parent, time.Now().Add(timeout))
+}
+
+// WithValue returns a copy of parent in which the value associated with key is
+// val.
+//
+// Use context Values only for request-scoped data that transits processes and
+// APIs, not for passing optional parameters to functions.
+func WithValue(parent Context, key interface{}, val interface{}) Context {
+ return &valueCtx{parent, key, val}
+}
+
+// A valueCtx carries a key-value pair. It implements Value for that key and
+// delegates all other calls to the embedded Context.
+type valueCtx struct {
+ Context
+ key, val interface{}
+}
+
+func (c *valueCtx) String() string {
+ return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val)
+}
+
+func (c *valueCtx) Value(key interface{}) interface{} {
+ if c.key == key {
+ return c.val
+ }
+ return c.Context.Value(key)
+}
diff --git a/vendor/golang.org/x/net/http2/README b/vendor/golang.org/x/net/http2/README
new file mode 100644
index 0000000..360d5aa
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/README
@@ -0,0 +1,20 @@
+This is a work-in-progress HTTP/2 implementation for Go.
+
+It will eventually live in the Go standard library and won't require
+any changes to your code to use. It will just be automatic.
+
+Status:
+
+* The server support is pretty good. A few things are missing
+ but are being worked on.
+* The client work has just started but shares a lot of code
+ is coming along much quicker.
+
+Docs are at https://godoc.org/golang.org/x/net/http2
+
+Demo test server at https://http2.golang.org/
+
+Help & bug reports welcome!
+
+Contributing: https://golang.org/doc/contribute.html
+Bugs: https://golang.org/issue/new?title=x/net/http2:+
diff --git a/vendor/golang.org/x/net/http2/ciphers.go b/vendor/golang.org/x/net/http2/ciphers.go
new file mode 100644
index 0000000..698860b
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/ciphers.go
@@ -0,0 +1,641 @@
+// Copyright 2017 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 http2
+
+// A list of the possible cipher suite ids. Taken from
+// http://www.iana.org/assignments/tls-parameters/tls-parameters.txt
+
+const (
+ cipher_TLS_NULL_WITH_NULL_NULL uint16 = 0x0000
+ cipher_TLS_RSA_WITH_NULL_MD5 uint16 = 0x0001
+ cipher_TLS_RSA_WITH_NULL_SHA uint16 = 0x0002
+ cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0003
+ cipher_TLS_RSA_WITH_RC4_128_MD5 uint16 = 0x0004
+ cipher_TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005
+ cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x0006
+ cipher_TLS_RSA_WITH_IDEA_CBC_SHA uint16 = 0x0007
+ cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0008
+ cipher_TLS_RSA_WITH_DES_CBC_SHA uint16 = 0x0009
+ cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000A
+ cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000B
+ cipher_TLS_DH_DSS_WITH_DES_CBC_SHA uint16 = 0x000C
+ cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x000D
+ cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000E
+ cipher_TLS_DH_RSA_WITH_DES_CBC_SHA uint16 = 0x000F
+ cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0010
+ cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0011
+ cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA uint16 = 0x0012
+ cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x0013
+ cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0014
+ cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA uint16 = 0x0015
+ cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0016
+ cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0017
+ cipher_TLS_DH_anon_WITH_RC4_128_MD5 uint16 = 0x0018
+ cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0019
+ cipher_TLS_DH_anon_WITH_DES_CBC_SHA uint16 = 0x001A
+ cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0x001B
+ // Reserved uint16 = 0x001C-1D
+ cipher_TLS_KRB5_WITH_DES_CBC_SHA uint16 = 0x001E
+ cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA uint16 = 0x001F
+ cipher_TLS_KRB5_WITH_RC4_128_SHA uint16 = 0x0020
+ cipher_TLS_KRB5_WITH_IDEA_CBC_SHA uint16 = 0x0021
+ cipher_TLS_KRB5_WITH_DES_CBC_MD5 uint16 = 0x0022
+ cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5 uint16 = 0x0023
+ cipher_TLS_KRB5_WITH_RC4_128_MD5 uint16 = 0x0024
+ cipher_TLS_KRB5_WITH_IDEA_CBC_MD5 uint16 = 0x0025
+ cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA uint16 = 0x0026
+ cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA uint16 = 0x0027
+ cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA uint16 = 0x0028
+ cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 uint16 = 0x0029
+ cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x002A
+ cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5 uint16 = 0x002B
+ cipher_TLS_PSK_WITH_NULL_SHA uint16 = 0x002C
+ cipher_TLS_DHE_PSK_WITH_NULL_SHA uint16 = 0x002D
+ cipher_TLS_RSA_PSK_WITH_NULL_SHA uint16 = 0x002E
+ cipher_TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002F
+ cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0030
+ cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0031
+ cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0032
+ cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0033
+ cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA uint16 = 0x0034
+ cipher_TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035
+ cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0036
+ cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0037
+ cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0038
+ cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0039
+ cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA uint16 = 0x003A
+ cipher_TLS_RSA_WITH_NULL_SHA256 uint16 = 0x003B
+ cipher_TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003C
+ cipher_TLS_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x003D
+ cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x003E
+ cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003F
+ cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x0040
+ cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0041
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0042
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0043
+ cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0044
+ cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0045
+ cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0046
+ // Reserved uint16 = 0x0047-4F
+ // Reserved uint16 = 0x0050-58
+ // Reserved uint16 = 0x0059-5C
+ // Unassigned uint16 = 0x005D-5F
+ // Reserved uint16 = 0x0060-66
+ cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x0067
+ cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x0068
+ cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x0069
+ cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x006A
+ cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x006B
+ cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256 uint16 = 0x006C
+ cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256 uint16 = 0x006D
+ // Unassigned uint16 = 0x006E-83
+ cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0084
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0085
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0086
+ cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0087
+ cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0088
+ cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0089
+ cipher_TLS_PSK_WITH_RC4_128_SHA uint16 = 0x008A
+ cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008B
+ cipher_TLS_PSK_WITH_AES_128_CBC_SHA uint16 = 0x008C
+ cipher_TLS_PSK_WITH_AES_256_CBC_SHA uint16 = 0x008D
+ cipher_TLS_DHE_PSK_WITH_RC4_128_SHA uint16 = 0x008E
+ cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008F
+ cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0090
+ cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0091
+ cipher_TLS_RSA_PSK_WITH_RC4_128_SHA uint16 = 0x0092
+ cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x0093
+ cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0094
+ cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0095
+ cipher_TLS_RSA_WITH_SEED_CBC_SHA uint16 = 0x0096
+ cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA uint16 = 0x0097
+ cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA uint16 = 0x0098
+ cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA uint16 = 0x0099
+ cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA uint16 = 0x009A
+ cipher_TLS_DH_anon_WITH_SEED_CBC_SHA uint16 = 0x009B
+ cipher_TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009C
+ cipher_TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009D
+ cipher_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009E
+ cipher_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009F
+ cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x00A0
+ cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x00A1
+ cipher_TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A2
+ cipher_TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A3
+ cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A4
+ cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A5
+ cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256 uint16 = 0x00A6
+ cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384 uint16 = 0x00A7
+ cipher_TLS_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00A8
+ cipher_TLS_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00A9
+ cipher_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AA
+ cipher_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AB
+ cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AC
+ cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AD
+ cipher_TLS_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00AE
+ cipher_TLS_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00AF
+ cipher_TLS_PSK_WITH_NULL_SHA256 uint16 = 0x00B0
+ cipher_TLS_PSK_WITH_NULL_SHA384 uint16 = 0x00B1
+ cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B2
+ cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B3
+ cipher_TLS_DHE_PSK_WITH_NULL_SHA256 uint16 = 0x00B4
+ cipher_TLS_DHE_PSK_WITH_NULL_SHA384 uint16 = 0x00B5
+ cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B6
+ cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B7
+ cipher_TLS_RSA_PSK_WITH_NULL_SHA256 uint16 = 0x00B8
+ cipher_TLS_RSA_PSK_WITH_NULL_SHA384 uint16 = 0x00B9
+ cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BA
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BB
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BC
+ cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BD
+ cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BE
+ cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BF
+ cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C0
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C1
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C2
+ cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C3
+ cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C4
+ cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C5
+ // Unassigned uint16 = 0x00C6-FE
+ cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV uint16 = 0x00FF
+ // Unassigned uint16 = 0x01-55,*
+ cipher_TLS_FALLBACK_SCSV uint16 = 0x5600
+ // Unassigned uint16 = 0x5601 - 0xC000
+ cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA uint16 = 0xC001
+ cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA uint16 = 0xC002
+ cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC003
+ cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC004
+ cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC005
+ cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA uint16 = 0xC006
+ cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xC007
+ cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC008
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC009
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC00A
+ cipher_TLS_ECDH_RSA_WITH_NULL_SHA uint16 = 0xC00B
+ cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA uint16 = 0xC00C
+ cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC00D
+ cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC00E
+ cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC00F
+ cipher_TLS_ECDHE_RSA_WITH_NULL_SHA uint16 = 0xC010
+ cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xC011
+ cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC012
+ cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC013
+ cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC014
+ cipher_TLS_ECDH_anon_WITH_NULL_SHA uint16 = 0xC015
+ cipher_TLS_ECDH_anon_WITH_RC4_128_SHA uint16 = 0xC016
+ cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0xC017
+ cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA uint16 = 0xC018
+ cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA uint16 = 0xC019
+ cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01A
+ cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01B
+ cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01C
+ cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA uint16 = 0xC01D
+ cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC01E
+ cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA uint16 = 0xC01F
+ cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA uint16 = 0xC020
+ cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC021
+ cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA uint16 = 0xC022
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC023
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC024
+ cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC025
+ cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC026
+ cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC027
+ cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC028
+ cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC029
+ cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC02A
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02B
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02C
+ cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02D
+ cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02E
+ cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02F
+ cipher_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC030
+ cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC031
+ cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC032
+ cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA uint16 = 0xC033
+ cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0xC034
+ cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0xC035
+ cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0xC036
+ cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0xC037
+ cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0xC038
+ cipher_TLS_ECDHE_PSK_WITH_NULL_SHA uint16 = 0xC039
+ cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256 uint16 = 0xC03A
+ cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384 uint16 = 0xC03B
+ cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03C
+ cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03D
+ cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03E
+ cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03F
+ cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC040
+ cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC041
+ cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC042
+ cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC043
+ cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC044
+ cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC045
+ cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC046
+ cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC047
+ cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC048
+ cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC049
+ cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04A
+ cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04B
+ cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04C
+ cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04D
+ cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04E
+ cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04F
+ cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC050
+ cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC051
+ cipher_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC052
+ cipher_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC053
+ cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC054
+ cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC055
+ cipher_TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC056
+ cipher_TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC057
+ cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC058
+ cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC059
+ cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05A
+ cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05B
+ cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05C
+ cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05D
+ cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05E
+ cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05F
+ cipher_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC060
+ cipher_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC061
+ cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC062
+ cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC063
+ cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC064
+ cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC065
+ cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC066
+ cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC067
+ cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC068
+ cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC069
+ cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06A
+ cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06B
+ cipher_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06C
+ cipher_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06D
+ cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06E
+ cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06F
+ cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC070
+ cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC071
+ cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC072
+ cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC073
+ cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC074
+ cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC075
+ cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC076
+ cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC077
+ cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC078
+ cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC079
+ cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07A
+ cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07B
+ cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07C
+ cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07D
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07E
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07F
+ cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC080
+ cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC081
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC082
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC083
+ cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC084
+ cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC085
+ cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC086
+ cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC087
+ cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC088
+ cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC089
+ cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08A
+ cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08B
+ cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08C
+ cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08D
+ cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08E
+ cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08F
+ cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC090
+ cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC091
+ cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC092
+ cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC093
+ cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC094
+ cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC095
+ cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC096
+ cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC097
+ cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC098
+ cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC099
+ cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC09A
+ cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC09B
+ cipher_TLS_RSA_WITH_AES_128_CCM uint16 = 0xC09C
+ cipher_TLS_RSA_WITH_AES_256_CCM uint16 = 0xC09D
+ cipher_TLS_DHE_RSA_WITH_AES_128_CCM uint16 = 0xC09E
+ cipher_TLS_DHE_RSA_WITH_AES_256_CCM uint16 = 0xC09F
+ cipher_TLS_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A0
+ cipher_TLS_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A1
+ cipher_TLS_DHE_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A2
+ cipher_TLS_DHE_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A3
+ cipher_TLS_PSK_WITH_AES_128_CCM uint16 = 0xC0A4
+ cipher_TLS_PSK_WITH_AES_256_CCM uint16 = 0xC0A5
+ cipher_TLS_DHE_PSK_WITH_AES_128_CCM uint16 = 0xC0A6
+ cipher_TLS_DHE_PSK_WITH_AES_256_CCM uint16 = 0xC0A7
+ cipher_TLS_PSK_WITH_AES_128_CCM_8 uint16 = 0xC0A8
+ cipher_TLS_PSK_WITH_AES_256_CCM_8 uint16 = 0xC0A9
+ cipher_TLS_PSK_DHE_WITH_AES_128_CCM_8 uint16 = 0xC0AA
+ cipher_TLS_PSK_DHE_WITH_AES_256_CCM_8 uint16 = 0xC0AB
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM uint16 = 0xC0AC
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM uint16 = 0xC0AD
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 uint16 = 0xC0AE
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 uint16 = 0xC0AF
+ // Unassigned uint16 = 0xC0B0-FF
+ // Unassigned uint16 = 0xC1-CB,*
+ // Unassigned uint16 = 0xCC00-A7
+ cipher_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA8
+ cipher_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA9
+ cipher_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAA
+ cipher_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAB
+ cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAC
+ cipher_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAD
+ cipher_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAE
+)
+
+// isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
+// References:
+// https://tools.ietf.org/html/rfc7540#appendix-A
+// Reject cipher suites from Appendix A.
+// "This list includes those cipher suites that do not
+// offer an ephemeral key exchange and those that are
+// based on the TLS null, stream or block cipher type"
+func isBadCipher(cipher uint16) bool {
+ switch cipher {
+ case cipher_TLS_NULL_WITH_NULL_NULL,
+ cipher_TLS_RSA_WITH_NULL_MD5,
+ cipher_TLS_RSA_WITH_NULL_SHA,
+ cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5,
+ cipher_TLS_RSA_WITH_RC4_128_MD5,
+ cipher_TLS_RSA_WITH_RC4_128_SHA,
+ cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
+ cipher_TLS_RSA_WITH_IDEA_CBC_SHA,
+ cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA,
+ cipher_TLS_RSA_WITH_DES_CBC_SHA,
+ cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
+ cipher_TLS_DH_DSS_WITH_DES_CBC_SHA,
+ cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
+ cipher_TLS_DH_RSA_WITH_DES_CBC_SHA,
+ cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
+ cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA,
+ cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
+ cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA,
+ cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5,
+ cipher_TLS_DH_anon_WITH_RC4_128_MD5,
+ cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA,
+ cipher_TLS_DH_anon_WITH_DES_CBC_SHA,
+ cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_KRB5_WITH_DES_CBC_SHA,
+ cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_KRB5_WITH_RC4_128_SHA,
+ cipher_TLS_KRB5_WITH_IDEA_CBC_SHA,
+ cipher_TLS_KRB5_WITH_DES_CBC_MD5,
+ cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5,
+ cipher_TLS_KRB5_WITH_RC4_128_MD5,
+ cipher_TLS_KRB5_WITH_IDEA_CBC_MD5,
+ cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA,
+ cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA,
+ cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA,
+ cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5,
+ cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5,
+ cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5,
+ cipher_TLS_PSK_WITH_NULL_SHA,
+ cipher_TLS_DHE_PSK_WITH_NULL_SHA,
+ cipher_TLS_RSA_PSK_WITH_NULL_SHA,
+ cipher_TLS_RSA_WITH_AES_128_CBC_SHA,
+ cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA,
+ cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA,
+ cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
+ cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
+ cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA,
+ cipher_TLS_RSA_WITH_AES_256_CBC_SHA,
+ cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA,
+ cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA,
+ cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
+ cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
+ cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA,
+ cipher_TLS_RSA_WITH_NULL_SHA256,
+ cipher_TLS_RSA_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_RSA_WITH_AES_256_CBC_SHA256,
+ cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA,
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA,
+ cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
+ cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
+ cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA,
+ cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256,
+ cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256,
+ cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,
+ cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
+ cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256,
+ cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA,
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA,
+ cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
+ cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
+ cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA,
+ cipher_TLS_PSK_WITH_RC4_128_SHA,
+ cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_PSK_WITH_AES_128_CBC_SHA,
+ cipher_TLS_PSK_WITH_AES_256_CBC_SHA,
+ cipher_TLS_DHE_PSK_WITH_RC4_128_SHA,
+ cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA,
+ cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA,
+ cipher_TLS_RSA_PSK_WITH_RC4_128_SHA,
+ cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA,
+ cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA,
+ cipher_TLS_RSA_WITH_SEED_CBC_SHA,
+ cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA,
+ cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA,
+ cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA,
+ cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA,
+ cipher_TLS_DH_anon_WITH_SEED_CBC_SHA,
+ cipher_TLS_RSA_WITH_AES_128_GCM_SHA256,
+ cipher_TLS_RSA_WITH_AES_256_GCM_SHA384,
+ cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256,
+ cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384,
+ cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256,
+ cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384,
+ cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256,
+ cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384,
+ cipher_TLS_PSK_WITH_AES_128_GCM_SHA256,
+ cipher_TLS_PSK_WITH_AES_256_GCM_SHA384,
+ cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256,
+ cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384,
+ cipher_TLS_PSK_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_PSK_WITH_AES_256_CBC_SHA384,
+ cipher_TLS_PSK_WITH_NULL_SHA256,
+ cipher_TLS_PSK_WITH_NULL_SHA384,
+ cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384,
+ cipher_TLS_DHE_PSK_WITH_NULL_SHA256,
+ cipher_TLS_DHE_PSK_WITH_NULL_SHA384,
+ cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384,
+ cipher_TLS_RSA_PSK_WITH_NULL_SHA256,
+ cipher_TLS_RSA_PSK_WITH_NULL_SHA384,
+ cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256,
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256,
+ cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256,
+ cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
+ cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256,
+ cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
+ cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA,
+ cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
+ cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
+ cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
+ cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA,
+ cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
+ cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
+ cipher_TLS_ECDH_RSA_WITH_NULL_SHA,
+ cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA,
+ cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
+ cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
+ cipher_TLS_ECDHE_RSA_WITH_NULL_SHA,
+ cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA,
+ cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
+ cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
+ cipher_TLS_ECDH_anon_WITH_NULL_SHA,
+ cipher_TLS_ECDH_anon_WITH_RC4_128_SHA,
+ cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA,
+ cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA,
+ cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA,
+ cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA,
+ cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA,
+ cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA,
+ cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA,
+ cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA,
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
+ cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384,
+ cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
+ cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384,
+ cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
+ cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
+ cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
+ cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384,
+ cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA,
+ cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA,
+ cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA,
+ cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA,
+ cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
+ cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384,
+ cipher_TLS_ECDHE_PSK_WITH_NULL_SHA,
+ cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256,
+ cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384,
+ cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256,
+ cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384,
+ cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256,
+ cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384,
+ cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256,
+ cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384,
+ cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256,
+ cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384,
+ cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256,
+ cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384,
+ cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256,
+ cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384,
+ cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256,
+ cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384,
+ cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256,
+ cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384,
+ cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256,
+ cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384,
+ cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
+ cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
+ cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
+ cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384,
+ cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256,
+ cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384,
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
+ cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256,
+ cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384,
+ cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256,
+ cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384,
+ cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,
+ cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,
+ cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
+ cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
+ cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256,
+ cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384,
+ cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256,
+ cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384,
+ cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384,
+ cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
+ cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384,
+ cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
+ cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
+ cipher_TLS_RSA_WITH_AES_128_CCM,
+ cipher_TLS_RSA_WITH_AES_256_CCM,
+ cipher_TLS_RSA_WITH_AES_128_CCM_8,
+ cipher_TLS_RSA_WITH_AES_256_CCM_8,
+ cipher_TLS_PSK_WITH_AES_128_CCM,
+ cipher_TLS_PSK_WITH_AES_256_CCM,
+ cipher_TLS_PSK_WITH_AES_128_CCM_8,
+ cipher_TLS_PSK_WITH_AES_256_CCM_8:
+ return true
+ default:
+ return false
+ }
+}
diff --git a/vendor/golang.org/x/net/http2/client_conn_pool.go b/vendor/golang.org/x/net/http2/client_conn_pool.go
new file mode 100644
index 0000000..bdf5652
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/client_conn_pool.go
@@ -0,0 +1,256 @@
+// Copyright 2015 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.
+
+// Transport code's client connection pooling.
+
+package http2
+
+import (
+ "crypto/tls"
+ "net/http"
+ "sync"
+)
+
+// ClientConnPool manages a pool of HTTP/2 client connections.
+type ClientConnPool interface {
+ GetClientConn(req *http.Request, addr string) (*ClientConn, error)
+ MarkDead(*ClientConn)
+}
+
+// clientConnPoolIdleCloser is the interface implemented by ClientConnPool
+// implementations which can close their idle connections.
+type clientConnPoolIdleCloser interface {
+ ClientConnPool
+ closeIdleConnections()
+}
+
+var (
+ _ clientConnPoolIdleCloser = (*clientConnPool)(nil)
+ _ clientConnPoolIdleCloser = noDialClientConnPool{}
+)
+
+// TODO: use singleflight for dialing and addConnCalls?
+type clientConnPool struct {
+ t *Transport
+
+ mu sync.Mutex // TODO: maybe switch to RWMutex
+ // TODO: add support for sharing conns based on cert names
+ // (e.g. share conn for googleapis.com and appspot.com)
+ conns map[string][]*ClientConn // key is host:port
+ dialing map[string]*dialCall // currently in-flight dials
+ keys map[*ClientConn][]string
+ addConnCalls map[string]*addConnCall // in-flight addConnIfNeede calls
+}
+
+func (p *clientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) {
+ return p.getClientConn(req, addr, dialOnMiss)
+}
+
+const (
+ dialOnMiss = true
+ noDialOnMiss = false
+)
+
+func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error) {
+ if isConnectionCloseRequest(req) && dialOnMiss {
+ // It gets its own connection.
+ const singleUse = true
+ cc, err := p.t.dialClientConn(addr, singleUse)
+ if err != nil {
+ return nil, err
+ }
+ return cc, nil
+ }
+ p.mu.Lock()
+ for _, cc := range p.conns[addr] {
+ if cc.CanTakeNewRequest() {
+ p.mu.Unlock()
+ return cc, nil
+ }
+ }
+ if !dialOnMiss {
+ p.mu.Unlock()
+ return nil, ErrNoCachedConn
+ }
+ call := p.getStartDialLocked(addr)
+ p.mu.Unlock()
+ <-call.done
+ return call.res, call.err
+}
+
+// dialCall is an in-flight Transport dial call to a host.
+type dialCall struct {
+ p *clientConnPool
+ done chan struct{} // closed when done
+ res *ClientConn // valid after done is closed
+ err error // valid after done is closed
+}
+
+// requires p.mu is held.
+func (p *clientConnPool) getStartDialLocked(addr string) *dialCall {
+ if call, ok := p.dialing[addr]; ok {
+ // A dial is already in-flight. Don't start another.
+ return call
+ }
+ call := &dialCall{p: p, done: make(chan struct{})}
+ if p.dialing == nil {
+ p.dialing = make(map[string]*dialCall)
+ }
+ p.dialing[addr] = call
+ go call.dial(addr)
+ return call
+}
+
+// run in its own goroutine.
+func (c *dialCall) dial(addr string) {
+ const singleUse = false // shared conn
+ c.res, c.err = c.p.t.dialClientConn(addr, singleUse)
+ close(c.done)
+
+ c.p.mu.Lock()
+ delete(c.p.dialing, addr)
+ if c.err == nil {
+ c.p.addConnLocked(addr, c.res)
+ }
+ c.p.mu.Unlock()
+}
+
+// addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't
+// already exist. It coalesces concurrent calls with the same key.
+// This is used by the http1 Transport code when it creates a new connection. Because
+// the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know
+// the protocol), it can get into a situation where it has multiple TLS connections.
+// This code decides which ones live or die.
+// The return value used is whether c was used.
+// c is never closed.
+func (p *clientConnPool) addConnIfNeeded(key string, t *Transport, c *tls.Conn) (used bool, err error) {
+ p.mu.Lock()
+ for _, cc := range p.conns[key] {
+ if cc.CanTakeNewRequest() {
+ p.mu.Unlock()
+ return false, nil
+ }
+ }
+ call, dup := p.addConnCalls[key]
+ if !dup {
+ if p.addConnCalls == nil {
+ p.addConnCalls = make(map[string]*addConnCall)
+ }
+ call = &addConnCall{
+ p: p,
+ done: make(chan struct{}),
+ }
+ p.addConnCalls[key] = call
+ go call.run(t, key, c)
+ }
+ p.mu.Unlock()
+
+ <-call.done
+ if call.err != nil {
+ return false, call.err
+ }
+ return !dup, nil
+}
+
+type addConnCall struct {
+ p *clientConnPool
+ done chan struct{} // closed when done
+ err error
+}
+
+func (c *addConnCall) run(t *Transport, key string, tc *tls.Conn) {
+ cc, err := t.NewClientConn(tc)
+
+ p := c.p
+ p.mu.Lock()
+ if err != nil {
+ c.err = err
+ } else {
+ p.addConnLocked(key, cc)
+ }
+ delete(p.addConnCalls, key)
+ p.mu.Unlock()
+ close(c.done)
+}
+
+func (p *clientConnPool) addConn(key string, cc *ClientConn) {
+ p.mu.Lock()
+ p.addConnLocked(key, cc)
+ p.mu.Unlock()
+}
+
+// p.mu must be held
+func (p *clientConnPool) addConnLocked(key string, cc *ClientConn) {
+ for _, v := range p.conns[key] {
+ if v == cc {
+ return
+ }
+ }
+ if p.conns == nil {
+ p.conns = make(map[string][]*ClientConn)
+ }
+ if p.keys == nil {
+ p.keys = make(map[*ClientConn][]string)
+ }
+ p.conns[key] = append(p.conns[key], cc)
+ p.keys[cc] = append(p.keys[cc], key)
+}
+
+func (p *clientConnPool) MarkDead(cc *ClientConn) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ for _, key := range p.keys[cc] {
+ vv, ok := p.conns[key]
+ if !ok {
+ continue
+ }
+ newList := filterOutClientConn(vv, cc)
+ if len(newList) > 0 {
+ p.conns[key] = newList
+ } else {
+ delete(p.conns, key)
+ }
+ }
+ delete(p.keys, cc)
+}
+
+func (p *clientConnPool) closeIdleConnections() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ // TODO: don't close a cc if it was just added to the pool
+ // milliseconds ago and has never been used. There's currently
+ // a small race window with the HTTP/1 Transport's integration
+ // where it can add an idle conn just before using it, and
+ // somebody else can concurrently call CloseIdleConns and
+ // break some caller's RoundTrip.
+ for _, vv := range p.conns {
+ for _, cc := range vv {
+ cc.closeIfIdle()
+ }
+ }
+}
+
+func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn {
+ out := in[:0]
+ for _, v := range in {
+ if v != exclude {
+ out = append(out, v)
+ }
+ }
+ // If we filtered it out, zero out the last item to prevent
+ // the GC from seeing it.
+ if len(in) != len(out) {
+ in[len(in)-1] = nil
+ }
+ return out
+}
+
+// noDialClientConnPool is an implementation of http2.ClientConnPool
+// which never dials. We let the HTTP/1.1 client dial and use its TLS
+// connection instead.
+type noDialClientConnPool struct{ *clientConnPool }
+
+func (p noDialClientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) {
+ return p.getClientConn(req, addr, noDialOnMiss)
+}
diff --git a/vendor/golang.org/x/net/http2/configure_transport.go b/vendor/golang.org/x/net/http2/configure_transport.go
new file mode 100644
index 0000000..4f720f5
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/configure_transport.go
@@ -0,0 +1,80 @@
+// Copyright 2015 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 go1.6
+
+package http2
+
+import (
+ "crypto/tls"
+ "fmt"
+ "net/http"
+)
+
+func configureTransport(t1 *http.Transport) (*Transport, error) {
+ connPool := new(clientConnPool)
+ t2 := &Transport{
+ ConnPool: noDialClientConnPool{connPool},
+ t1: t1,
+ }
+ connPool.t = t2
+ if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil {
+ return nil, err
+ }
+ if t1.TLSClientConfig == nil {
+ t1.TLSClientConfig = new(tls.Config)
+ }
+ if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
+ t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
+ }
+ if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
+ t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
+ }
+ upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper {
+ addr := authorityAddr("https", authority)
+ if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
+ go c.Close()
+ return erringRoundTripper{err}
+ } else if !used {
+ // Turns out we don't need this c.
+ // For example, two goroutines made requests to the same host
+ // at the same time, both kicking off TCP dials. (since protocol
+ // was unknown)
+ go c.Close()
+ }
+ return t2
+ }
+ if m := t1.TLSNextProto; len(m) == 0 {
+ t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{
+ "h2": upgradeFn,
+ }
+ } else {
+ m["h2"] = upgradeFn
+ }
+ return t2, nil
+}
+
+// registerHTTPSProtocol calls Transport.RegisterProtocol but
+// convering panics into errors.
+func registerHTTPSProtocol(t *http.Transport, rt http.RoundTripper) (err error) {
+ defer func() {
+ if e := recover(); e != nil {
+ err = fmt.Errorf("%v", e)
+ }
+ }()
+ t.RegisterProtocol("https", rt)
+ return nil
+}
+
+// noDialH2RoundTripper is a RoundTripper which only tries to complete the request
+// if there's already has a cached connection to the host.
+type noDialH2RoundTripper struct{ t *Transport }
+
+func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
+ res, err := rt.t.RoundTrip(req)
+ if err == ErrNoCachedConn {
+ return nil, http.ErrSkipAltProtocol
+ }
+ return res, err
+}
diff --git a/vendor/golang.org/x/net/http2/databuffer.go b/vendor/golang.org/x/net/http2/databuffer.go
new file mode 100644
index 0000000..a3067f8
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/databuffer.go
@@ -0,0 +1,146 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package http2
+
+import (
+ "errors"
+ "fmt"
+ "sync"
+)
+
+// Buffer chunks are allocated from a pool to reduce pressure on GC.
+// The maximum wasted space per dataBuffer is 2x the largest size class,
+// which happens when the dataBuffer has multiple chunks and there is
+// one unread byte in both the first and last chunks. We use a few size
+// classes to minimize overheads for servers that typically receive very
+// small request bodies.
+//
+// TODO: Benchmark to determine if the pools are necessary. The GC may have
+// improved enough that we can instead allocate chunks like this:
+// make([]byte, max(16<<10, expectedBytesRemaining))
+var (
+ dataChunkSizeClasses = []int{
+ 1 << 10,
+ 2 << 10,
+ 4 << 10,
+ 8 << 10,
+ 16 << 10,
+ }
+ dataChunkPools = [...]sync.Pool{
+ {New: func() interface{} { return make([]byte, 1<<10) }},
+ {New: func() interface{} { return make([]byte, 2<<10) }},
+ {New: func() interface{} { return make([]byte, 4<<10) }},
+ {New: func() interface{} { return make([]byte, 8<<10) }},
+ {New: func() interface{} { return make([]byte, 16<<10) }},
+ }
+)
+
+func getDataBufferChunk(size int64) []byte {
+ i := 0
+ for ; i < len(dataChunkSizeClasses)-1; i++ {
+ if size <= int64(dataChunkSizeClasses[i]) {
+ break
+ }
+ }
+ return dataChunkPools[i].Get().([]byte)
+}
+
+func putDataBufferChunk(p []byte) {
+ for i, n := range dataChunkSizeClasses {
+ if len(p) == n {
+ dataChunkPools[i].Put(p)
+ return
+ }
+ }
+ panic(fmt.Sprintf("unexpected buffer len=%v", len(p)))
+}
+
+// dataBuffer is an io.ReadWriter backed by a list of data chunks.
+// Each dataBuffer is used to read DATA frames on a single stream.
+// The buffer is divided into chunks so the server can limit the
+// total memory used by a single connection without limiting the
+// request body size on any single stream.
+type dataBuffer struct {
+ chunks [][]byte
+ r int // next byte to read is chunks[0][r]
+ w int // next byte to write is chunks[len(chunks)-1][w]
+ size int // total buffered bytes
+ expected int64 // we expect at least this many bytes in future Write calls (ignored if <= 0)
+}
+
+var errReadEmpty = errors.New("read from empty dataBuffer")
+
+// Read copies bytes from the buffer into p.
+// It is an error to read when no data is available.
+func (b *dataBuffer) Read(p []byte) (int, error) {
+ if b.size == 0 {
+ return 0, errReadEmpty
+ }
+ var ntotal int
+ for len(p) > 0 && b.size > 0 {
+ readFrom := b.bytesFromFirstChunk()
+ n := copy(p, readFrom)
+ p = p[n:]
+ ntotal += n
+ b.r += n
+ b.size -= n
+ // If the first chunk has been consumed, advance to the next chunk.
+ if b.r == len(b.chunks[0]) {
+ putDataBufferChunk(b.chunks[0])
+ end := len(b.chunks) - 1
+ copy(b.chunks[:end], b.chunks[1:])
+ b.chunks[end] = nil
+ b.chunks = b.chunks[:end]
+ b.r = 0
+ }
+ }
+ return ntotal, nil
+}
+
+func (b *dataBuffer) bytesFromFirstChunk() []byte {
+ if len(b.chunks) == 1 {
+ return b.chunks[0][b.r:b.w]
+ }
+ return b.chunks[0][b.r:]
+}
+
+// Len returns the number of bytes of the unread portion of the buffer.
+func (b *dataBuffer) Len() int {
+ return b.size
+}
+
+// Write appends p to the buffer.
+func (b *dataBuffer) Write(p []byte) (int, error) {
+ ntotal := len(p)
+ for len(p) > 0 {
+ // If the last chunk is empty, allocate a new chunk. Try to allocate
+ // enough to fully copy p plus any additional bytes we expect to
+ // receive. However, this may allocate less than len(p).
+ want := int64(len(p))
+ if b.expected > want {
+ want = b.expected
+ }
+ chunk := b.lastChunkOrAlloc(want)
+ n := copy(chunk[b.w:], p)
+ p = p[n:]
+ b.w += n
+ b.size += n
+ b.expected -= int64(n)
+ }
+ return ntotal, nil
+}
+
+func (b *dataBuffer) lastChunkOrAlloc(want int64) []byte {
+ if len(b.chunks) != 0 {
+ last := b.chunks[len(b.chunks)-1]
+ if b.w < len(last) {
+ return last
+ }
+ }
+ chunk := getDataBufferChunk(want)
+ b.chunks = append(b.chunks, chunk)
+ b.w = 0
+ return chunk
+}
diff --git a/vendor/golang.org/x/net/http2/errors.go b/vendor/golang.org/x/net/http2/errors.go
new file mode 100644
index 0000000..20fd762
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/errors.go
@@ -0,0 +1,130 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package http2
+
+import (
+ "errors"
+ "fmt"
+)
+
+// An ErrCode is an unsigned 32-bit error code as defined in the HTTP/2 spec.
+type ErrCode uint32
+
+const (
+ ErrCodeNo ErrCode = 0x0
+ ErrCodeProtocol ErrCode = 0x1
+ ErrCodeInternal ErrCode = 0x2
+ ErrCodeFlowControl ErrCode = 0x3
+ ErrCodeSettingsTimeout ErrCode = 0x4
+ ErrCodeStreamClosed ErrCode = 0x5
+ ErrCodeFrameSize ErrCode = 0x6
+ ErrCodeRefusedStream ErrCode = 0x7
+ ErrCodeCancel ErrCode = 0x8
+ ErrCodeCompression ErrCode = 0x9
+ ErrCodeConnect ErrCode = 0xa
+ ErrCodeEnhanceYourCalm ErrCode = 0xb
+ ErrCodeInadequateSecurity ErrCode = 0xc
+ ErrCodeHTTP11Required ErrCode = 0xd
+)
+
+var errCodeName = map[ErrCode]string{
+ ErrCodeNo: "NO_ERROR",
+ ErrCodeProtocol: "PROTOCOL_ERROR",
+ ErrCodeInternal: "INTERNAL_ERROR",
+ ErrCodeFlowControl: "FLOW_CONTROL_ERROR",
+ ErrCodeSettingsTimeout: "SETTINGS_TIMEOUT",
+ ErrCodeStreamClosed: "STREAM_CLOSED",
+ ErrCodeFrameSize: "FRAME_SIZE_ERROR",
+ ErrCodeRefusedStream: "REFUSED_STREAM",
+ ErrCodeCancel: "CANCEL",
+ ErrCodeCompression: "COMPRESSION_ERROR",
+ ErrCodeConnect: "CONNECT_ERROR",
+ ErrCodeEnhanceYourCalm: "ENHANCE_YOUR_CALM",
+ ErrCodeInadequateSecurity: "INADEQUATE_SECURITY",
+ ErrCodeHTTP11Required: "HTTP_1_1_REQUIRED",
+}
+
+func (e ErrCode) String() string {
+ if s, ok := errCodeName[e]; ok {
+ return s
+ }
+ return fmt.Sprintf("unknown error code 0x%x", uint32(e))
+}
+
+// ConnectionError is an error that results in the termination of the
+// entire connection.
+type ConnectionError ErrCode
+
+func (e ConnectionError) Error() string { return fmt.Sprintf("connection error: %s", ErrCode(e)) }
+
+// StreamError is an error that only affects one stream within an
+// HTTP/2 connection.
+type StreamError struct {
+ StreamID uint32
+ Code ErrCode
+ Cause error // optional additional detail
+}
+
+func streamError(id uint32, code ErrCode) StreamError {
+ return StreamError{StreamID: id, Code: code}
+}
+
+func (e StreamError) Error() string {
+ if e.Cause != nil {
+ return fmt.Sprintf("stream error: stream ID %d; %v; %v", e.StreamID, e.Code, e.Cause)
+ }
+ return fmt.Sprintf("stream error: stream ID %d; %v", e.StreamID, e.Code)
+}
+
+// 6.9.1 The Flow Control Window
+// "If a sender receives a WINDOW_UPDATE that causes a flow control
+// window to exceed this maximum it MUST terminate either the stream
+// or the connection, as appropriate. For streams, [...]; for the
+// connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code."
+type goAwayFlowError struct{}
+
+func (goAwayFlowError) Error() string { return "connection exceeded flow control window size" }
+
+// connErrorReason wraps a ConnectionError with an informative error about why it occurs.
+
+// Errors of this type are only returned by the frame parser functions
+// and converted into ConnectionError(ErrCodeProtocol).
+type connError struct {
+ Code ErrCode
+ Reason string
+}
+
+func (e connError) Error() string {
+ return fmt.Sprintf("http2: connection error: %v: %v", e.Code, e.Reason)
+}
+
+type pseudoHeaderError string
+
+func (e pseudoHeaderError) Error() string {
+ return fmt.Sprintf("invalid pseudo-header %q", string(e))
+}
+
+type duplicatePseudoHeaderError string
+
+func (e duplicatePseudoHeaderError) Error() string {
+ return fmt.Sprintf("duplicate pseudo-header %q", string(e))
+}
+
+type headerFieldNameError string
+
+func (e headerFieldNameError) Error() string {
+ return fmt.Sprintf("invalid header field name %q", string(e))
+}
+
+type headerFieldValueError string
+
+func (e headerFieldValueError) Error() string {
+ return fmt.Sprintf("invalid header field value %q", string(e))
+}
+
+var (
+ errMixPseudoHeaderTypes = errors.New("mix of request and response pseudo headers")
+ errPseudoAfterRegular = errors.New("pseudo header field after regular")
+)
diff --git a/vendor/golang.org/x/net/http2/flow.go b/vendor/golang.org/x/net/http2/flow.go
new file mode 100644
index 0000000..957de25
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/flow.go
@@ -0,0 +1,50 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Flow control
+
+package http2
+
+// flow is the flow control window's size.
+type flow struct {
+ // n is the number of DATA bytes we're allowed to send.
+ // A flow is kept both on a conn and a per-stream.
+ n int32
+
+ // conn points to the shared connection-level flow that is
+ // shared by all streams on that conn. It is nil for the flow
+ // that's on the conn directly.
+ conn *flow
+}
+
+func (f *flow) setConnFlow(cf *flow) { f.conn = cf }
+
+func (f *flow) available() int32 {
+ n := f.n
+ if f.conn != nil && f.conn.n < n {
+ n = f.conn.n
+ }
+ return n
+}
+
+func (f *flow) take(n int32) {
+ if n > f.available() {
+ panic("internal error: took too much")
+ }
+ f.n -= n
+ if f.conn != nil {
+ f.conn.n -= n
+ }
+}
+
+// add adds n bytes (positive or negative) to the flow control window.
+// It returns false if the sum would exceed 2^31-1.
+func (f *flow) add(n int32) bool {
+ remain := (1<<31 - 1) - f.n
+ if n > remain {
+ return false
+ }
+ f.n += n
+ return true
+}
diff --git a/vendor/golang.org/x/net/http2/frame.go b/vendor/golang.org/x/net/http2/frame.go
new file mode 100644
index 0000000..3b14890
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/frame.go
@@ -0,0 +1,1579 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package http2
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "strings"
+ "sync"
+
+ "golang.org/x/net/http2/hpack"
+ "golang.org/x/net/lex/httplex"
+)
+
+const frameHeaderLen = 9
+
+var padZeros = make([]byte, 255) // zeros for padding
+
+// A FrameType is a registered frame type as defined in
+// http://http2.github.io/http2-spec/#rfc.section.11.2
+type FrameType uint8
+
+const (
+ FrameData FrameType = 0x0
+ FrameHeaders FrameType = 0x1
+ FramePriority FrameType = 0x2
+ FrameRSTStream FrameType = 0x3
+ FrameSettings FrameType = 0x4
+ FramePushPromise FrameType = 0x5
+ FramePing FrameType = 0x6
+ FrameGoAway FrameType = 0x7
+ FrameWindowUpdate FrameType = 0x8
+ FrameContinuation FrameType = 0x9
+)
+
+var frameName = map[FrameType]string{
+ FrameData: "DATA",
+ FrameHeaders: "HEADERS",
+ FramePriority: "PRIORITY",
+ FrameRSTStream: "RST_STREAM",
+ FrameSettings: "SETTINGS",
+ FramePushPromise: "PUSH_PROMISE",
+ FramePing: "PING",
+ FrameGoAway: "GOAWAY",
+ FrameWindowUpdate: "WINDOW_UPDATE",
+ FrameContinuation: "CONTINUATION",
+}
+
+func (t FrameType) String() string {
+ if s, ok := frameName[t]; ok {
+ return s
+ }
+ return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t))
+}
+
+// Flags is a bitmask of HTTP/2 flags.
+// The meaning of flags varies depending on the frame type.
+type Flags uint8
+
+// Has reports whether f contains all (0 or more) flags in v.
+func (f Flags) Has(v Flags) bool {
+ return (f & v) == v
+}
+
+// Frame-specific FrameHeader flag bits.
+const (
+ // Data Frame
+ FlagDataEndStream Flags = 0x1
+ FlagDataPadded Flags = 0x8
+
+ // Headers Frame
+ FlagHeadersEndStream Flags = 0x1
+ FlagHeadersEndHeaders Flags = 0x4
+ FlagHeadersPadded Flags = 0x8
+ FlagHeadersPriority Flags = 0x20
+
+ // Settings Frame
+ FlagSettingsAck Flags = 0x1
+
+ // Ping Frame
+ FlagPingAck Flags = 0x1
+
+ // Continuation Frame
+ FlagContinuationEndHeaders Flags = 0x4
+
+ FlagPushPromiseEndHeaders Flags = 0x4
+ FlagPushPromisePadded Flags = 0x8
+)
+
+var flagName = map[FrameType]map[Flags]string{
+ FrameData: {
+ FlagDataEndStream: "END_STREAM",
+ FlagDataPadded: "PADDED",
+ },
+ FrameHeaders: {
+ FlagHeadersEndStream: "END_STREAM",
+ FlagHeadersEndHeaders: "END_HEADERS",
+ FlagHeadersPadded: "PADDED",
+ FlagHeadersPriority: "PRIORITY",
+ },
+ FrameSettings: {
+ FlagSettingsAck: "ACK",
+ },
+ FramePing: {
+ FlagPingAck: "ACK",
+ },
+ FrameContinuation: {
+ FlagContinuationEndHeaders: "END_HEADERS",
+ },
+ FramePushPromise: {
+ FlagPushPromiseEndHeaders: "END_HEADERS",
+ FlagPushPromisePadded: "PADDED",
+ },
+}
+
+// a frameParser parses a frame given its FrameHeader and payload
+// bytes. The length of payload will always equal fh.Length (which
+// might be 0).
+type frameParser func(fc *frameCache, fh FrameHeader, payload []byte) (Frame, error)
+
+var frameParsers = map[FrameType]frameParser{
+ FrameData: parseDataFrame,
+ FrameHeaders: parseHeadersFrame,
+ FramePriority: parsePriorityFrame,
+ FrameRSTStream: parseRSTStreamFrame,
+ FrameSettings: parseSettingsFrame,
+ FramePushPromise: parsePushPromise,
+ FramePing: parsePingFrame,
+ FrameGoAway: parseGoAwayFrame,
+ FrameWindowUpdate: parseWindowUpdateFrame,
+ FrameContinuation: parseContinuationFrame,
+}
+
+func typeFrameParser(t FrameType) frameParser {
+ if f := frameParsers[t]; f != nil {
+ return f
+ }
+ return parseUnknownFrame
+}
+
+// A FrameHeader is the 9 byte header of all HTTP/2 frames.
+//
+// See http://http2.github.io/http2-spec/#FrameHeader
+type FrameHeader struct {
+ valid bool // caller can access []byte fields in the Frame
+
+ // Type is the 1 byte frame type. There are ten standard frame
+ // types, but extension frame types may be written by WriteRawFrame
+ // and will be returned by ReadFrame (as UnknownFrame).
+ Type FrameType
+
+ // Flags are the 1 byte of 8 potential bit flags per frame.
+ // They are specific to the frame type.
+ Flags Flags
+
+ // Length is the length of the frame, not including the 9 byte header.
+ // The maximum size is one byte less than 16MB (uint24), but only
+ // frames up to 16KB are allowed without peer agreement.
+ Length uint32
+
+ // StreamID is which stream this frame is for. Certain frames
+ // are not stream-specific, in which case this field is 0.
+ StreamID uint32
+}
+
+// Header returns h. It exists so FrameHeaders can be embedded in other
+// specific frame types and implement the Frame interface.
+func (h FrameHeader) Header() FrameHeader { return h }
+
+func (h FrameHeader) String() string {
+ var buf bytes.Buffer
+ buf.WriteString("[FrameHeader ")
+ h.writeDebug(&buf)
+ buf.WriteByte(']')
+ return buf.String()
+}
+
+func (h FrameHeader) writeDebug(buf *bytes.Buffer) {
+ buf.WriteString(h.Type.String())
+ if h.Flags != 0 {
+ buf.WriteString(" flags=")
+ set := 0
+ for i := uint8(0); i < 8; i++ {
+ if h.Flags&(1<<i) == 0 {
+ continue
+ }
+ set++
+ if set > 1 {
+ buf.WriteByte('|')
+ }
+ name := flagName[h.Type][Flags(1<<i)]
+ if name != "" {
+ buf.WriteString(name)
+ } else {
+ fmt.Fprintf(buf, "0x%x", 1<<i)
+ }
+ }
+ }
+ if h.StreamID != 0 {
+ fmt.Fprintf(buf, " stream=%d", h.StreamID)
+ }
+ fmt.Fprintf(buf, " len=%d", h.Length)
+}
+
+func (h *FrameHeader) checkValid() {
+ if !h.valid {
+ panic("Frame accessor called on non-owned Frame")
+ }
+}
+
+func (h *FrameHeader) invalidate() { h.valid = false }
+
+// frame header bytes.
+// Used only by ReadFrameHeader.
+var fhBytes = sync.Pool{
+ New: func() interface{} {
+ buf := make([]byte, frameHeaderLen)
+ return &buf
+ },
+}
+
+// ReadFrameHeader reads 9 bytes from r and returns a FrameHeader.
+// Most users should use Framer.ReadFrame instead.
+func ReadFrameHeader(r io.Reader) (FrameHeader, error) {
+ bufp := fhBytes.Get().(*[]byte)
+ defer fhBytes.Put(bufp)
+ return readFrameHeader(*bufp, r)
+}
+
+func readFrameHeader(buf []byte, r io.Reader) (FrameHeader, error) {
+ _, err := io.ReadFull(r, buf[:frameHeaderLen])
+ if err != nil {
+ return FrameHeader{}, err
+ }
+ return FrameHeader{
+ Length: (uint32(buf[0])<<16 | uint32(buf[1])<<8 | uint32(buf[2])),
+ Type: FrameType(buf[3]),
+ Flags: Flags(buf[4]),
+ StreamID: binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1),
+ valid: true,
+ }, nil
+}
+
+// A Frame is the base interface implemented by all frame types.
+// Callers will generally type-assert the specific frame type:
+// *HeadersFrame, *SettingsFrame, *WindowUpdateFrame, etc.
+//
+// Frames are only valid until the next call to Framer.ReadFrame.
+type Frame interface {
+ Header() FrameHeader
+
+ // invalidate is called by Framer.ReadFrame to make this
+ // frame's buffers as being invalid, since the subsequent
+ // frame will reuse them.
+ invalidate()
+}
+
+// A Framer reads and writes Frames.
+type Framer struct {
+ r io.Reader
+ lastFrame Frame
+ errDetail error
+
+ // lastHeaderStream is non-zero if the last frame was an
+ // unfinished HEADERS/CONTINUATION.
+ lastHeaderStream uint32
+
+ maxReadSize uint32
+ headerBuf [frameHeaderLen]byte
+
+ // TODO: let getReadBuf be configurable, and use a less memory-pinning
+ // allocator in server.go to minimize memory pinned for many idle conns.
+ // Will probably also need to make frame invalidation have a hook too.
+ getReadBuf func(size uint32) []byte
+ readBuf []byte // cache for default getReadBuf
+
+ maxWriteSize uint32 // zero means unlimited; TODO: implement
+
+ w io.Writer
+ wbuf []byte
+
+ // AllowIllegalWrites permits the Framer's Write methods to
+ // write frames that do not conform to the HTTP/2 spec. This
+ // permits using the Framer to test other HTTP/2
+ // implementations' conformance to the spec.
+ // If false, the Write methods will prefer to return an error
+ // rather than comply.
+ AllowIllegalWrites bool
+
+ // AllowIllegalReads permits the Framer's ReadFrame method
+ // to return non-compliant frames or frame orders.
+ // This is for testing and permits using the Framer to test
+ // other HTTP/2 implementations' conformance to the spec.
+ // It is not compatible with ReadMetaHeaders.
+ AllowIllegalReads bool
+
+ // ReadMetaHeaders if non-nil causes ReadFrame to merge
+ // HEADERS and CONTINUATION frames together and return
+ // MetaHeadersFrame instead.
+ ReadMetaHeaders *hpack.Decoder
+
+ // MaxHeaderListSize is the http2 MAX_HEADER_LIST_SIZE.
+ // It's used only if ReadMetaHeaders is set; 0 means a sane default
+ // (currently 16MB)
+ // If the limit is hit, MetaHeadersFrame.Truncated is set true.
+ MaxHeaderListSize uint32
+
+ // TODO: track which type of frame & with which flags was sent
+ // last. Then return an error (unless AllowIllegalWrites) if
+ // we're in the middle of a header block and a
+ // non-Continuation or Continuation on a different stream is
+ // attempted to be written.
+
+ logReads, logWrites bool
+
+ debugFramer *Framer // only use for logging written writes
+ debugFramerBuf *bytes.Buffer
+ debugReadLoggerf func(string, ...interface{})
+ debugWriteLoggerf func(string, ...interface{})
+
+ frameCache *frameCache // nil if frames aren't reused (default)
+}
+
+func (fr *Framer) maxHeaderListSize() uint32 {
+ if fr.MaxHeaderListSize == 0 {
+ return 16 << 20 // sane default, per docs
+ }
+ return fr.MaxHeaderListSize
+}
+
+func (f *Framer) startWrite(ftype FrameType, flags Flags, streamID uint32) {
+ // Write the FrameHeader.
+ f.wbuf = append(f.wbuf[:0],
+ 0, // 3 bytes of length, filled in in endWrite
+ 0,
+ 0,
+ byte(ftype),
+ byte(flags),
+ byte(streamID>>24),
+ byte(streamID>>16),
+ byte(streamID>>8),
+ byte(streamID))
+}
+
+func (f *Framer) endWrite() error {
+ // Now that we know the final size, fill in the FrameHeader in
+ // the space previously reserved for it. Abuse append.
+ length := len(f.wbuf) - frameHeaderLen
+ if length >= (1 << 24) {
+ return ErrFrameTooLarge
+ }
+ _ = append(f.wbuf[:0],
+ byte(length>>16),
+ byte(length>>8),
+ byte(length))
+ if f.logWrites {
+ f.logWrite()
+ }
+
+ n, err := f.w.Write(f.wbuf)
+ if err == nil && n != len(f.wbuf) {
+ err = io.ErrShortWrite
+ }
+ return err
+}
+
+func (f *Framer) logWrite() {
+ if f.debugFramer == nil {
+ f.debugFramerBuf = new(bytes.Buffer)
+ f.debugFramer = NewFramer(nil, f.debugFramerBuf)
+ f.debugFramer.logReads = false // we log it ourselves, saying "wrote" below
+ // Let us read anything, even if we accidentally wrote it
+ // in the wrong order:
+ f.debugFramer.AllowIllegalReads = true
+ }
+ f.debugFramerBuf.Write(f.wbuf)
+ fr, err := f.debugFramer.ReadFrame()
+ if err != nil {
+ f.debugWriteLoggerf("http2: Framer %p: failed to decode just-written frame", f)
+ return
+ }
+ f.debugWriteLoggerf("http2: Framer %p: wrote %v", f, summarizeFrame(fr))
+}
+
+func (f *Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) }
+func (f *Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) }
+func (f *Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) }
+func (f *Framer) writeUint32(v uint32) {
+ f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
+}
+
+const (
+ minMaxFrameSize = 1 << 14
+ maxFrameSize = 1<<24 - 1
+)
+
+// SetReuseFrames allows the Framer to reuse Frames.
+// If called on a Framer, Frames returned by calls to ReadFrame are only
+// valid until the next call to ReadFrame.
+func (fr *Framer) SetReuseFrames() {
+ if fr.frameCache != nil {
+ return
+ }
+ fr.frameCache = &frameCache{}
+}
+
+type frameCache struct {
+ dataFrame DataFrame
+}
+
+func (fc *frameCache) getDataFrame() *DataFrame {
+ if fc == nil {
+ return &DataFrame{}
+ }
+ return &fc.dataFrame
+}
+
+// NewFramer returns a Framer that writes frames to w and reads them from r.
+func NewFramer(w io.Writer, r io.Reader) *Framer {
+ fr := &Framer{
+ w: w,
+ r: r,
+ logReads: logFrameReads,
+ logWrites: logFrameWrites,
+ debugReadLoggerf: log.Printf,
+ debugWriteLoggerf: log.Printf,
+ }
+ fr.getReadBuf = func(size uint32) []byte {
+ if cap(fr.readBuf) >= int(size) {
+ return fr.readBuf[:size]
+ }
+ fr.readBuf = make([]byte, size)
+ return fr.readBuf
+ }
+ fr.SetMaxReadFrameSize(maxFrameSize)
+ return fr
+}
+
+// SetMaxReadFrameSize sets the maximum size of a frame
+// that will be read by a subsequent call to ReadFrame.
+// It is the caller's responsibility to advertise this
+// limit with a SETTINGS frame.
+func (fr *Framer) SetMaxReadFrameSize(v uint32) {
+ if v > maxFrameSize {
+ v = maxFrameSize
+ }
+ fr.maxReadSize = v
+}
+
+// ErrorDetail returns a more detailed error of the last error
+// returned by Framer.ReadFrame. For instance, if ReadFrame
+// returns a StreamError with code PROTOCOL_ERROR, ErrorDetail
+// will say exactly what was invalid. ErrorDetail is not guaranteed
+// to return a non-nil value and like the rest of the http2 package,
+// its return value is not protected by an API compatibility promise.
+// ErrorDetail is reset after the next call to ReadFrame.
+func (fr *Framer) ErrorDetail() error {
+ return fr.errDetail
+}
+
+// ErrFrameTooLarge is returned from Framer.ReadFrame when the peer
+// sends a frame that is larger than declared with SetMaxReadFrameSize.
+var ErrFrameTooLarge = errors.New("http2: frame too large")
+
+// terminalReadFrameError reports whether err is an unrecoverable
+// error from ReadFrame and no other frames should be read.
+func terminalReadFrameError(err error) bool {
+ if _, ok := err.(StreamError); ok {
+ return false
+ }
+ return err != nil
+}
+
+// ReadFrame reads a single frame. The returned Frame is only valid
+// until the next call to ReadFrame.
+//
+// If the frame is larger than previously set with SetMaxReadFrameSize, the
+// returned error is ErrFrameTooLarge. Other errors may be of type
+// ConnectionError, StreamError, or anything else from the underlying
+// reader.
+func (fr *Framer) ReadFrame() (Frame, error) {
+ fr.errDetail = nil
+ if fr.lastFrame != nil {
+ fr.lastFrame.invalidate()
+ }
+ fh, err := readFrameHeader(fr.headerBuf[:], fr.r)
+ if err != nil {
+ return nil, err
+ }
+ if fh.Length > fr.maxReadSize {
+ return nil, ErrFrameTooLarge
+ }
+ payload := fr.getReadBuf(fh.Length)
+ if _, err := io.ReadFull(fr.r, payload); err != nil {
+ return nil, err
+ }
+ f, err := typeFrameParser(fh.Type)(fr.frameCache, fh, payload)
+ if err != nil {
+ if ce, ok := err.(connError); ok {
+ return nil, fr.connError(ce.Code, ce.Reason)
+ }
+ return nil, err
+ }
+ if err := fr.checkFrameOrder(f); err != nil {
+ return nil, err
+ }
+ if fr.logReads {
+ fr.debugReadLoggerf("http2: Framer %p: read %v", fr, summarizeFrame(f))
+ }
+ if fh.Type == FrameHeaders && fr.ReadMetaHeaders != nil {
+ return fr.readMetaFrame(f.(*HeadersFrame))
+ }
+ return f, nil
+}
+
+// connError returns ConnectionError(code) but first
+// stashes away a public reason to the caller can optionally relay it
+// to the peer before hanging up on them. This might help others debug
+// their implementations.
+func (fr *Framer) connError(code ErrCode, reason string) error {
+ fr.errDetail = errors.New(reason)
+ return ConnectionError(code)
+}
+
+// checkFrameOrder reports an error if f is an invalid frame to return
+// next from ReadFrame. Mostly it checks whether HEADERS and
+// CONTINUATION frames are contiguous.
+func (fr *Framer) checkFrameOrder(f Frame) error {
+ last := fr.lastFrame
+ fr.lastFrame = f
+ if fr.AllowIllegalReads {
+ return nil
+ }
+
+ fh := f.Header()
+ if fr.lastHeaderStream != 0 {
+ if fh.Type != FrameContinuation {
+ return fr.connError(ErrCodeProtocol,
+ fmt.Sprintf("got %s for stream %d; expected CONTINUATION following %s for stream %d",
+ fh.Type, fh.StreamID,
+ last.Header().Type, fr.lastHeaderStream))
+ }
+ if fh.StreamID != fr.lastHeaderStream {
+ return fr.connError(ErrCodeProtocol,
+ fmt.Sprintf("got CONTINUATION for stream %d; expected stream %d",
+ fh.StreamID, fr.lastHeaderStream))
+ }
+ } else if fh.Type == FrameContinuation {
+ return fr.connError(ErrCodeProtocol, fmt.Sprintf("unexpected CONTINUATION for stream %d", fh.StreamID))
+ }
+
+ switch fh.Type {
+ case FrameHeaders, FrameContinuation:
+ if fh.Flags.Has(FlagHeadersEndHeaders) {
+ fr.lastHeaderStream = 0
+ } else {
+ fr.lastHeaderStream = fh.StreamID
+ }
+ }
+
+ return nil
+}
+
+// A DataFrame conveys arbitrary, variable-length sequences of octets
+// associated with a stream.
+// See http://http2.github.io/http2-spec/#rfc.section.6.1
+type DataFrame struct {
+ FrameHeader
+ data []byte
+}
+
+func (f *DataFrame) StreamEnded() bool {
+ return f.FrameHeader.Flags.Has(FlagDataEndStream)
+}
+
+// Data returns the frame's data octets, not including any padding
+// size byte or padding suffix bytes.
+// The caller must not retain the returned memory past the next
+// call to ReadFrame.
+func (f *DataFrame) Data() []byte {
+ f.checkValid()
+ return f.data
+}
+
+func parseDataFrame(fc *frameCache, fh FrameHeader, payload []byte) (Frame, error) {
+ if fh.StreamID == 0 {
+ // DATA frames MUST be associated with a stream. If a
+ // DATA frame is received whose stream identifier
+ // field is 0x0, the recipient MUST respond with a
+ // connection error (Section 5.4.1) of type
+ // PROTOCOL_ERROR.
+ return nil, connError{ErrCodeProtocol, "DATA frame with stream ID 0"}
+ }
+ f := fc.getDataFrame()
+ f.FrameHeader = fh
+
+ var padSize byte
+ if fh.Flags.Has(FlagDataPadded) {
+ var err error
+ payload, padSize, err = readByte(payload)
+ if err != nil {
+ return nil, err
+ }
+ }
+ if int(padSize) > len(payload) {
+ // If the length of the padding is greater than the
+ // length of the frame payload, the recipient MUST
+ // treat this as a connection error.
+ // Filed: https://github.com/http2/http2-spec/issues/610
+ return nil, connError{ErrCodeProtocol, "pad size larger than data payload"}
+ }
+ f.data = payload[:len(payload)-int(padSize)]
+ return f, nil
+}
+
+var (
+ errStreamID = errors.New("invalid stream ID")
+ errDepStreamID = errors.New("invalid dependent stream ID")
+ errPadLength = errors.New("pad length too large")
+ errPadBytes = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled")
+)
+
+func validStreamIDOrZero(streamID uint32) bool {
+ return streamID&(1<<31) == 0
+}
+
+func validStreamID(streamID uint32) bool {
+ return streamID != 0 && streamID&(1<<31) == 0
+}
+
+// WriteData writes a DATA frame.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility not to violate the maximum frame size
+// and to not call other Write methods concurrently.
+func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
+ return f.WriteDataPadded(streamID, endStream, data, nil)
+}
+
+// WriteData writes a DATA frame with optional padding.
+//
+// If pad is nil, the padding bit is not sent.
+// The length of pad must not exceed 255 bytes.
+// The bytes of pad must all be zero, unless f.AllowIllegalWrites is set.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility not to violate the maximum frame size
+// and to not call other Write methods concurrently.
+func (f *Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error {
+ if !validStreamID(streamID) && !f.AllowIllegalWrites {
+ return errStreamID
+ }
+ if len(pad) > 0 {
+ if len(pad) > 255 {
+ return errPadLength
+ }
+ if !f.AllowIllegalWrites {
+ for _, b := range pad {
+ if b != 0 {
+ // "Padding octets MUST be set to zero when sending."
+ return errPadBytes
+ }
+ }
+ }
+ }
+ var flags Flags
+ if endStream {
+ flags |= FlagDataEndStream
+ }
+ if pad != nil {
+ flags |= FlagDataPadded
+ }
+ f.startWrite(FrameData, flags, streamID)
+ if pad != nil {
+ f.wbuf = append(f.wbuf, byte(len(pad)))
+ }
+ f.wbuf = append(f.wbuf, data...)
+ f.wbuf = append(f.wbuf, pad...)
+ return f.endWrite()
+}
+
+// A SettingsFrame conveys configuration parameters that affect how
+// endpoints communicate, such as preferences and constraints on peer
+// behavior.
+//
+// See http://http2.github.io/http2-spec/#SETTINGS
+type SettingsFrame struct {
+ FrameHeader
+ p []byte
+}
+
+func parseSettingsFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
+ if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 {
+ // When this (ACK 0x1) bit is set, the payload of the
+ // SETTINGS frame MUST be empty. Receipt of a
+ // SETTINGS frame with the ACK flag set and a length
+ // field value other than 0 MUST be treated as a
+ // connection error (Section 5.4.1) of type
+ // FRAME_SIZE_ERROR.
+ return nil, ConnectionError(ErrCodeFrameSize)
+ }
+ if fh.StreamID != 0 {
+ // SETTINGS frames always apply to a connection,
+ // never a single stream. The stream identifier for a
+ // SETTINGS frame MUST be zero (0x0). If an endpoint
+ // receives a SETTINGS frame whose stream identifier
+ // field is anything other than 0x0, the endpoint MUST
+ // respond with a connection error (Section 5.4.1) of
+ // type PROTOCOL_ERROR.
+ return nil, ConnectionError(ErrCodeProtocol)
+ }
+ if len(p)%6 != 0 {
+ // Expecting even number of 6 byte settings.
+ return nil, ConnectionError(ErrCodeFrameSize)
+ }
+ f := &SettingsFrame{FrameHeader: fh, p: p}
+ if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 {
+ // Values above the maximum flow control window size of 2^31 - 1 MUST
+ // be treated as a connection error (Section 5.4.1) of type
+ // FLOW_CONTROL_ERROR.
+ return nil, ConnectionError(ErrCodeFlowControl)
+ }
+ return f, nil
+}
+
+func (f *SettingsFrame) IsAck() bool {
+ return f.FrameHeader.Flags.Has(FlagSettingsAck)
+}
+
+func (f *SettingsFrame) Value(s SettingID) (v uint32, ok bool) {
+ f.checkValid()
+ buf := f.p
+ for len(buf) > 0 {
+ settingID := SettingID(binary.BigEndian.Uint16(buf[:2]))
+ if settingID == s {
+ return binary.BigEndian.Uint32(buf[2:6]), true
+ }
+ buf = buf[6:]
+ }
+ return 0, false
+}
+
+// ForeachSetting runs fn for each setting.
+// It stops and returns the first error.
+func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error {
+ f.checkValid()
+ buf := f.p
+ for len(buf) > 0 {
+ if err := fn(Setting{
+ SettingID(binary.BigEndian.Uint16(buf[:2])),
+ binary.BigEndian.Uint32(buf[2:6]),
+ }); err != nil {
+ return err
+ }
+ buf = buf[6:]
+ }
+ return nil
+}
+
+// WriteSettings writes a SETTINGS frame with zero or more settings
+// specified and the ACK bit not set.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *Framer) WriteSettings(settings ...Setting) error {
+ f.startWrite(FrameSettings, 0, 0)
+ for _, s := range settings {
+ f.writeUint16(uint16(s.ID))
+ f.writeUint32(s.Val)
+ }
+ return f.endWrite()
+}
+
+// WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *Framer) WriteSettingsAck() error {
+ f.startWrite(FrameSettings, FlagSettingsAck, 0)
+ return f.endWrite()
+}
+
+// A PingFrame is a mechanism for measuring a minimal round trip time
+// from the sender, as well as determining whether an idle connection
+// is still functional.
+// See http://http2.github.io/http2-spec/#rfc.section.6.7
+type PingFrame struct {
+ FrameHeader
+ Data [8]byte
+}
+
+func (f *PingFrame) IsAck() bool { return f.Flags.Has(FlagPingAck) }
+
+func parsePingFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) {
+ if len(payload) != 8 {
+ return nil, ConnectionError(ErrCodeFrameSize)
+ }
+ if fh.StreamID != 0 {
+ return nil, ConnectionError(ErrCodeProtocol)
+ }
+ f := &PingFrame{FrameHeader: fh}
+ copy(f.Data[:], payload)
+ return f, nil
+}
+
+func (f *Framer) WritePing(ack bool, data [8]byte) error {
+ var flags Flags
+ if ack {
+ flags = FlagPingAck
+ }
+ f.startWrite(FramePing, flags, 0)
+ f.writeBytes(data[:])
+ return f.endWrite()
+}
+
+// A GoAwayFrame informs the remote peer to stop creating streams on this connection.
+// See http://http2.github.io/http2-spec/#rfc.section.6.8
+type GoAwayFrame struct {
+ FrameHeader
+ LastStreamID uint32
+ ErrCode ErrCode
+ debugData []byte
+}
+
+// DebugData returns any debug data in the GOAWAY frame. Its contents
+// are not defined.
+// The caller must not retain the returned memory past the next
+// call to ReadFrame.
+func (f *GoAwayFrame) DebugData() []byte {
+ f.checkValid()
+ return f.debugData
+}
+
+func parseGoAwayFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
+ if fh.StreamID != 0 {
+ return nil, ConnectionError(ErrCodeProtocol)
+ }
+ if len(p) < 8 {
+ return nil, ConnectionError(ErrCodeFrameSize)
+ }
+ return &GoAwayFrame{
+ FrameHeader: fh,
+ LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
+ ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])),
+ debugData: p[8:],
+ }, nil
+}
+
+func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error {
+ f.startWrite(FrameGoAway, 0, 0)
+ f.writeUint32(maxStreamID & (1<<31 - 1))
+ f.writeUint32(uint32(code))
+ f.writeBytes(debugData)
+ return f.endWrite()
+}
+
+// An UnknownFrame is the frame type returned when the frame type is unknown
+// or no specific frame type parser exists.
+type UnknownFrame struct {
+ FrameHeader
+ p []byte
+}
+
+// Payload returns the frame's payload (after the header). It is not
+// valid to call this method after a subsequent call to
+// Framer.ReadFrame, nor is it valid to retain the returned slice.
+// The memory is owned by the Framer and is invalidated when the next
+// frame is read.
+func (f *UnknownFrame) Payload() []byte {
+ f.checkValid()
+ return f.p
+}
+
+func parseUnknownFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
+ return &UnknownFrame{fh, p}, nil
+}
+
+// A WindowUpdateFrame is used to implement flow control.
+// See http://http2.github.io/http2-spec/#rfc.section.6.9
+type WindowUpdateFrame struct {
+ FrameHeader
+ Increment uint32 // never read with high bit set
+}
+
+func parseWindowUpdateFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
+ if len(p) != 4 {
+ return nil, ConnectionError(ErrCodeFrameSize)
+ }
+ inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
+ if inc == 0 {
+ // A receiver MUST treat the receipt of a
+ // WINDOW_UPDATE frame with an flow control window
+ // increment of 0 as a stream error (Section 5.4.2) of
+ // type PROTOCOL_ERROR; errors on the connection flow
+ // control window MUST be treated as a connection
+ // error (Section 5.4.1).
+ if fh.StreamID == 0 {
+ return nil, ConnectionError(ErrCodeProtocol)
+ }
+ return nil, streamError(fh.StreamID, ErrCodeProtocol)
+ }
+ return &WindowUpdateFrame{
+ FrameHeader: fh,
+ Increment: inc,
+ }, nil
+}
+
+// WriteWindowUpdate writes a WINDOW_UPDATE frame.
+// The increment value must be between 1 and 2,147,483,647, inclusive.
+// If the Stream ID is zero, the window update applies to the
+// connection as a whole.
+func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error {
+ // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
+ if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
+ return errors.New("illegal window increment value")
+ }
+ f.startWrite(FrameWindowUpdate, 0, streamID)
+ f.writeUint32(incr)
+ return f.endWrite()
+}
+
+// A HeadersFrame is used to open a stream and additionally carries a
+// header block fragment.
+type HeadersFrame struct {
+ FrameHeader
+
+ // Priority is set if FlagHeadersPriority is set in the FrameHeader.
+ Priority PriorityParam
+
+ headerFragBuf []byte // not owned
+}
+
+func (f *HeadersFrame) HeaderBlockFragment() []byte {
+ f.checkValid()
+ return f.headerFragBuf
+}
+
+func (f *HeadersFrame) HeadersEnded() bool {
+ return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
+}
+
+func (f *HeadersFrame) StreamEnded() bool {
+ return f.FrameHeader.Flags.Has(FlagHeadersEndStream)
+}
+
+func (f *HeadersFrame) HasPriority() bool {
+ return f.FrameHeader.Flags.Has(FlagHeadersPriority)
+}
+
+func parseHeadersFrame(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) {
+ hf := &HeadersFrame{
+ FrameHeader: fh,
+ }
+ if fh.StreamID == 0 {
+ // HEADERS frames MUST be associated with a stream. If a HEADERS frame
+ // is received whose stream identifier field is 0x0, the recipient MUST
+ // respond with a connection error (Section 5.4.1) of type
+ // PROTOCOL_ERROR.
+ return nil, connError{ErrCodeProtocol, "HEADERS frame with stream ID 0"}
+ }
+ var padLength uint8
+ if fh.Flags.Has(FlagHeadersPadded) {
+ if p, padLength, err = readByte(p); err != nil {
+ return
+ }
+ }
+ if fh.Flags.Has(FlagHeadersPriority) {
+ var v uint32
+ p, v, err = readUint32(p)
+ if err != nil {
+ return nil, err
+ }
+ hf.Priority.StreamDep = v & 0x7fffffff
+ hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set
+ p, hf.Priority.Weight, err = readByte(p)
+ if err != nil {
+ return nil, err
+ }
+ }
+ if len(p)-int(padLength) <= 0 {
+ return nil, streamError(fh.StreamID, ErrCodeProtocol)
+ }
+ hf.headerFragBuf = p[:len(p)-int(padLength)]
+ return hf, nil
+}
+
+// HeadersFrameParam are the parameters for writing a HEADERS frame.
+type HeadersFrameParam struct {
+ // StreamID is the required Stream ID to initiate.
+ StreamID uint32
+ // BlockFragment is part (or all) of a Header Block.
+ BlockFragment []byte
+
+ // EndStream indicates that the header block is the last that
+ // the endpoint will send for the identified stream. Setting
+ // this flag causes the stream to enter one of "half closed"
+ // states.
+ EndStream bool
+
+ // EndHeaders indicates that this frame contains an entire
+ // header block and is not followed by any
+ // CONTINUATION frames.
+ EndHeaders bool
+
+ // PadLength is the optional number of bytes of zeros to add
+ // to this frame.
+ PadLength uint8
+
+ // Priority, if non-zero, includes stream priority information
+ // in the HEADER frame.
+ Priority PriorityParam
+}
+
+// WriteHeaders writes a single HEADERS frame.
+//
+// This is a low-level header writing method. Encoding headers and
+// splitting them into any necessary CONTINUATION frames is handled
+// elsewhere.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
+ if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
+ return errStreamID
+ }
+ var flags Flags
+ if p.PadLength != 0 {
+ flags |= FlagHeadersPadded
+ }
+ if p.EndStream {
+ flags |= FlagHeadersEndStream
+ }
+ if p.EndHeaders {
+ flags |= FlagHeadersEndHeaders
+ }
+ if !p.Priority.IsZero() {
+ flags |= FlagHeadersPriority
+ }
+ f.startWrite(FrameHeaders, flags, p.StreamID)
+ if p.PadLength != 0 {
+ f.writeByte(p.PadLength)
+ }
+ if !p.Priority.IsZero() {
+ v := p.Priority.StreamDep
+ if !validStreamIDOrZero(v) && !f.AllowIllegalWrites {
+ return errDepStreamID
+ }
+ if p.Priority.Exclusive {
+ v |= 1 << 31
+ }
+ f.writeUint32(v)
+ f.writeByte(p.Priority.Weight)
+ }
+ f.wbuf = append(f.wbuf, p.BlockFragment...)
+ f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
+ return f.endWrite()
+}
+
+// A PriorityFrame specifies the sender-advised priority of a stream.
+// See http://http2.github.io/http2-spec/#rfc.section.6.3
+type PriorityFrame struct {
+ FrameHeader
+ PriorityParam
+}
+
+// PriorityParam are the stream prioritzation parameters.
+type PriorityParam struct {
+ // StreamDep is a 31-bit stream identifier for the
+ // stream that this stream depends on. Zero means no
+ // dependency.
+ StreamDep uint32
+
+ // Exclusive is whether the dependency is exclusive.
+ Exclusive bool
+
+ // Weight is the stream's zero-indexed weight. It should be
+ // set together with StreamDep, or neither should be set. Per
+ // the spec, "Add one to the value to obtain a weight between
+ // 1 and 256."
+ Weight uint8
+}
+
+func (p PriorityParam) IsZero() bool {
+ return p == PriorityParam{}
+}
+
+func parsePriorityFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) {
+ if fh.StreamID == 0 {
+ return nil, connError{ErrCodeProtocol, "PRIORITY frame with stream ID 0"}
+ }
+ if len(payload) != 5 {
+ return nil, connError{ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))}
+ }
+ v := binary.BigEndian.Uint32(payload[:4])
+ streamID := v & 0x7fffffff // mask off high bit
+ return &PriorityFrame{
+ FrameHeader: fh,
+ PriorityParam: PriorityParam{
+ Weight: payload[4],
+ StreamDep: streamID,
+ Exclusive: streamID != v, // was high bit set?
+ },
+ }, nil
+}
+
+// WritePriority writes a PRIORITY frame.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error {
+ if !validStreamID(streamID) && !f.AllowIllegalWrites {
+ return errStreamID
+ }
+ if !validStreamIDOrZero(p.StreamDep) {
+ return errDepStreamID
+ }
+ f.startWrite(FramePriority, 0, streamID)
+ v := p.StreamDep
+ if p.Exclusive {
+ v |= 1 << 31
+ }
+ f.writeUint32(v)
+ f.writeByte(p.Weight)
+ return f.endWrite()
+}
+
+// A RSTStreamFrame allows for abnormal termination of a stream.
+// See http://http2.github.io/http2-spec/#rfc.section.6.4
+type RSTStreamFrame struct {
+ FrameHeader
+ ErrCode ErrCode
+}
+
+func parseRSTStreamFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
+ if len(p) != 4 {
+ return nil, ConnectionError(ErrCodeFrameSize)
+ }
+ if fh.StreamID == 0 {
+ return nil, ConnectionError(ErrCodeProtocol)
+ }
+ return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
+}
+
+// WriteRSTStream writes a RST_STREAM frame.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error {
+ if !validStreamID(streamID) && !f.AllowIllegalWrites {
+ return errStreamID
+ }
+ f.startWrite(FrameRSTStream, 0, streamID)
+ f.writeUint32(uint32(code))
+ return f.endWrite()
+}
+
+// A ContinuationFrame is used to continue a sequence of header block fragments.
+// See http://http2.github.io/http2-spec/#rfc.section.6.10
+type ContinuationFrame struct {
+ FrameHeader
+ headerFragBuf []byte
+}
+
+func parseContinuationFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
+ if fh.StreamID == 0 {
+ return nil, connError{ErrCodeProtocol, "CONTINUATION frame with stream ID 0"}
+ }
+ return &ContinuationFrame{fh, p}, nil
+}
+
+func (f *ContinuationFrame) HeaderBlockFragment() []byte {
+ f.checkValid()
+ return f.headerFragBuf
+}
+
+func (f *ContinuationFrame) HeadersEnded() bool {
+ return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
+}
+
+// WriteContinuation writes a CONTINUATION frame.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
+ if !validStreamID(streamID) && !f.AllowIllegalWrites {
+ return errStreamID
+ }
+ var flags Flags
+ if endHeaders {
+ flags |= FlagContinuationEndHeaders
+ }
+ f.startWrite(FrameContinuation, flags, streamID)
+ f.wbuf = append(f.wbuf, headerBlockFragment...)
+ return f.endWrite()
+}
+
+// A PushPromiseFrame is used to initiate a server stream.
+// See http://http2.github.io/http2-spec/#rfc.section.6.6
+type PushPromiseFrame struct {
+ FrameHeader
+ PromiseID uint32
+ headerFragBuf []byte // not owned
+}
+
+func (f *PushPromiseFrame) HeaderBlockFragment() []byte {
+ f.checkValid()
+ return f.headerFragBuf
+}
+
+func (f *PushPromiseFrame) HeadersEnded() bool {
+ return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders)
+}
+
+func parsePushPromise(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) {
+ pp := &PushPromiseFrame{
+ FrameHeader: fh,
+ }
+ if pp.StreamID == 0 {
+ // PUSH_PROMISE frames MUST be associated with an existing,
+ // peer-initiated stream. The stream identifier of a
+ // PUSH_PROMISE frame indicates the stream it is associated
+ // with. If the stream identifier field specifies the value
+ // 0x0, a recipient MUST respond with a connection error
+ // (Section 5.4.1) of type PROTOCOL_ERROR.
+ return nil, ConnectionError(ErrCodeProtocol)
+ }
+ // The PUSH_PROMISE frame includes optional padding.
+ // Padding fields and flags are identical to those defined for DATA frames
+ var padLength uint8
+ if fh.Flags.Has(FlagPushPromisePadded) {
+ if p, padLength, err = readByte(p); err != nil {
+ return
+ }
+ }
+
+ p, pp.PromiseID, err = readUint32(p)
+ if err != nil {
+ return
+ }
+ pp.PromiseID = pp.PromiseID & (1<<31 - 1)
+
+ if int(padLength) > len(p) {
+ // like the DATA frame, error out if padding is longer than the body.
+ return nil, ConnectionError(ErrCodeProtocol)
+ }
+ pp.headerFragBuf = p[:len(p)-int(padLength)]
+ return pp, nil
+}
+
+// PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
+type PushPromiseParam struct {
+ // StreamID is the required Stream ID to initiate.
+ StreamID uint32
+
+ // PromiseID is the required Stream ID which this
+ // Push Promises
+ PromiseID uint32
+
+ // BlockFragment is part (or all) of a Header Block.
+ BlockFragment []byte
+
+ // EndHeaders indicates that this frame contains an entire
+ // header block and is not followed by any
+ // CONTINUATION frames.
+ EndHeaders bool
+
+ // PadLength is the optional number of bytes of zeros to add
+ // to this frame.
+ PadLength uint8
+}
+
+// WritePushPromise writes a single PushPromise Frame.
+//
+// As with Header Frames, This is the low level call for writing
+// individual frames. Continuation frames are handled elsewhere.
+//
+// It will perform exactly one Write to the underlying Writer.
+// It is the caller's responsibility to not call other Write methods concurrently.
+func (f *Framer) WritePushPromise(p PushPromiseParam) error {
+ if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
+ return errStreamID
+ }
+ var flags Flags
+ if p.PadLength != 0 {
+ flags |= FlagPushPromisePadded
+ }
+ if p.EndHeaders {
+ flags |= FlagPushPromiseEndHeaders
+ }
+ f.startWrite(FramePushPromise, flags, p.StreamID)
+ if p.PadLength != 0 {
+ f.writeByte(p.PadLength)
+ }
+ if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
+ return errStreamID
+ }
+ f.writeUint32(p.PromiseID)
+ f.wbuf = append(f.wbuf, p.BlockFragment...)
+ f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
+ return f.endWrite()
+}
+
+// WriteRawFrame writes a raw frame. This can be used to write
+// extension frames unknown to this package.
+func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error {
+ f.startWrite(t, flags, streamID)
+ f.writeBytes(payload)
+ return f.endWrite()
+}
+
+func readByte(p []byte) (remain []byte, b byte, err error) {
+ if len(p) == 0 {
+ return nil, 0, io.ErrUnexpectedEOF
+ }
+ return p[1:], p[0], nil
+}
+
+func readUint32(p []byte) (remain []byte, v uint32, err error) {
+ if len(p) < 4 {
+ return nil, 0, io.ErrUnexpectedEOF
+ }
+ return p[4:], binary.BigEndian.Uint32(p[:4]), nil
+}
+
+type streamEnder interface {
+ StreamEnded() bool
+}
+
+type headersEnder interface {
+ HeadersEnded() bool
+}
+
+type headersOrContinuation interface {
+ headersEnder
+ HeaderBlockFragment() []byte
+}
+
+// A MetaHeadersFrame is the representation of one HEADERS frame and
+// zero or more contiguous CONTINUATION frames and the decoding of
+// their HPACK-encoded contents.
+//
+// This type of frame does not appear on the wire and is only returned
+// by the Framer when Framer.ReadMetaHeaders is set.
+type MetaHeadersFrame struct {
+ *HeadersFrame
+
+ // Fields are the fields contained in the HEADERS and
+ // CONTINUATION frames. The underlying slice is owned by the
+ // Framer and must not be retained after the next call to
+ // ReadFrame.
+ //
+ // Fields are guaranteed to be in the correct http2 order and
+ // not have unknown pseudo header fields or invalid header
+ // field names or values. Required pseudo header fields may be
+ // missing, however. Use the MetaHeadersFrame.Pseudo accessor
+ // method access pseudo headers.
+ Fields []hpack.HeaderField
+
+ // Truncated is whether the max header list size limit was hit
+ // and Fields is incomplete. The hpack decoder state is still
+ // valid, however.
+ Truncated bool
+}
+
+// PseudoValue returns the given pseudo header field's value.
+// The provided pseudo field should not contain the leading colon.
+func (mh *MetaHeadersFrame) PseudoValue(pseudo string) string {
+ for _, hf := range mh.Fields {
+ if !hf.IsPseudo() {
+ return ""
+ }
+ if hf.Name[1:] == pseudo {
+ return hf.Value
+ }
+ }
+ return ""
+}
+
+// RegularFields returns the regular (non-pseudo) header fields of mh.
+// The caller does not own the returned slice.
+func (mh *MetaHeadersFrame) RegularFields() []hpack.HeaderField {
+ for i, hf := range mh.Fields {
+ if !hf.IsPseudo() {
+ return mh.Fields[i:]
+ }
+ }
+ return nil
+}
+
+// PseudoFields returns the pseudo header fields of mh.
+// The caller does not own the returned slice.
+func (mh *MetaHeadersFrame) PseudoFields() []hpack.HeaderField {
+ for i, hf := range mh.Fields {
+ if !hf.IsPseudo() {
+ return mh.Fields[:i]
+ }
+ }
+ return mh.Fields
+}
+
+func (mh *MetaHeadersFrame) checkPseudos() error {
+ var isRequest, isResponse bool
+ pf := mh.PseudoFields()
+ for i, hf := range pf {
+ switch hf.Name {
+ case ":method", ":path", ":scheme", ":authority":
+ isRequest = true
+ case ":status":
+ isResponse = true
+ default:
+ return pseudoHeaderError(hf.Name)
+ }
+ // Check for duplicates.
+ // This would be a bad algorithm, but N is 4.
+ // And this doesn't allocate.
+ for _, hf2 := range pf[:i] {
+ if hf.Name == hf2.Name {
+ return duplicatePseudoHeaderError(hf.Name)
+ }
+ }
+ }
+ if isRequest && isResponse {
+ return errMixPseudoHeaderTypes
+ }
+ return nil
+}
+
+func (fr *Framer) maxHeaderStringLen() int {
+ v := fr.maxHeaderListSize()
+ if uint32(int(v)) == v {
+ return int(v)
+ }
+ // They had a crazy big number for MaxHeaderBytes anyway,
+ // so give them unlimited header lengths:
+ return 0
+}
+
+// readMetaFrame returns 0 or more CONTINUATION frames from fr and
+// merge them into into the provided hf and returns a MetaHeadersFrame
+// with the decoded hpack values.
+func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) {
+ if fr.AllowIllegalReads {
+ return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders")
+ }
+ mh := &MetaHeadersFrame{
+ HeadersFrame: hf,
+ }
+ var remainSize = fr.maxHeaderListSize()
+ var sawRegular bool
+
+ var invalid error // pseudo header field errors
+ hdec := fr.ReadMetaHeaders
+ hdec.SetEmitEnabled(true)
+ hdec.SetMaxStringLength(fr.maxHeaderStringLen())
+ hdec.SetEmitFunc(func(hf hpack.HeaderField) {
+ if VerboseLogs && fr.logReads {
+ fr.debugReadLoggerf("http2: decoded hpack field %+v", hf)
+ }
+ if !httplex.ValidHeaderFieldValue(hf.Value) {
+ invalid = headerFieldValueError(hf.Value)
+ }
+ isPseudo := strings.HasPrefix(hf.Name, ":")
+ if isPseudo {
+ if sawRegular {
+ invalid = errPseudoAfterRegular
+ }
+ } else {
+ sawRegular = true
+ if !validWireHeaderFieldName(hf.Name) {
+ invalid = headerFieldNameError(hf.Name)
+ }
+ }
+
+ if invalid != nil {
+ hdec.SetEmitEnabled(false)
+ return
+ }
+
+ size := hf.Size()
+ if size > remainSize {
+ hdec.SetEmitEnabled(false)
+ mh.Truncated = true
+ return
+ }
+ remainSize -= size
+
+ mh.Fields = append(mh.Fields, hf)
+ })
+ // Lose reference to MetaHeadersFrame:
+ defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {})
+
+ var hc headersOrContinuation = hf
+ for {
+ frag := hc.HeaderBlockFragment()
+ if _, err := hdec.Write(frag); err != nil {
+ return nil, ConnectionError(ErrCodeCompression)
+ }
+
+ if hc.HeadersEnded() {
+ break
+ }
+ if f, err := fr.ReadFrame(); err != nil {
+ return nil, err
+ } else {
+ hc = f.(*ContinuationFrame) // guaranteed by checkFrameOrder
+ }
+ }
+
+ mh.HeadersFrame.headerFragBuf = nil
+ mh.HeadersFrame.invalidate()
+
+ if err := hdec.Close(); err != nil {
+ return nil, ConnectionError(ErrCodeCompression)
+ }
+ if invalid != nil {
+ fr.errDetail = invalid
+ if VerboseLogs {
+ log.Printf("http2: invalid header: %v", invalid)
+ }
+ return nil, StreamError{mh.StreamID, ErrCodeProtocol, invalid}
+ }
+ if err := mh.checkPseudos(); err != nil {
+ fr.errDetail = err
+ if VerboseLogs {
+ log.Printf("http2: invalid pseudo headers: %v", err)
+ }
+ return nil, StreamError{mh.StreamID, ErrCodeProtocol, err}
+ }
+ return mh, nil
+}
+
+func summarizeFrame(f Frame) string {
+ var buf bytes.Buffer
+ f.Header().writeDebug(&buf)
+ switch f := f.(type) {
+ case *SettingsFrame:
+ n := 0
+ f.ForeachSetting(func(s Setting) error {
+ n++
+ if n == 1 {
+ buf.WriteString(", settings:")
+ }
+ fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val)
+ return nil
+ })
+ if n > 0 {
+ buf.Truncate(buf.Len() - 1) // remove trailing comma
+ }
+ case *DataFrame:
+ data := f.Data()
+ const max = 256
+ if len(data) > max {
+ data = data[:max]
+ }
+ fmt.Fprintf(&buf, " data=%q", data)
+ if len(f.Data()) > max {
+ fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max)
+ }
+ case *WindowUpdateFrame:
+ if f.StreamID == 0 {
+ buf.WriteString(" (conn)")
+ }
+ fmt.Fprintf(&buf, " incr=%v", f.Increment)
+ case *PingFrame:
+ fmt.Fprintf(&buf, " ping=%q", f.Data[:])
+ case *GoAwayFrame:
+ fmt.Fprintf(&buf, " LastStreamID=%v ErrCode=%v Debug=%q",
+ f.LastStreamID, f.ErrCode, f.debugData)
+ case *RSTStreamFrame:
+ fmt.Fprintf(&buf, " ErrCode=%v", f.ErrCode)
+ }
+ return buf.String()
+}
diff --git a/vendor/golang.org/x/net/http2/go16.go b/vendor/golang.org/x/net/http2/go16.go
new file mode 100644
index 0000000..00b2e9e
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/go16.go
@@ -0,0 +1,16 @@
+// 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 go1.6
+
+package http2
+
+import (
+ "net/http"
+ "time"
+)
+
+func transportExpectContinueTimeout(t1 *http.Transport) time.Duration {
+ return t1.ExpectContinueTimeout
+}
diff --git a/vendor/golang.org/x/net/http2/go17.go b/vendor/golang.org/x/net/http2/go17.go
new file mode 100644
index 0000000..47b7fae
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/go17.go
@@ -0,0 +1,106 @@
+// 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 go1.7
+
+package http2
+
+import (
+ "context"
+ "net"
+ "net/http"
+ "net/http/httptrace"
+ "time"
+)
+
+type contextContext interface {
+ context.Context
+}
+
+func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) {
+ ctx, cancel = context.WithCancel(context.Background())
+ ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr())
+ if hs := opts.baseConfig(); hs != nil {
+ ctx = context.WithValue(ctx, http.ServerContextKey, hs)
+ }
+ return
+}
+
+func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) {
+ return context.WithCancel(ctx)
+}
+
+func requestWithContext(req *http.Request, ctx contextContext) *http.Request {
+ return req.WithContext(ctx)
+}
+
+type clientTrace httptrace.ClientTrace
+
+func reqContext(r *http.Request) context.Context { return r.Context() }
+
+func (t *Transport) idleConnTimeout() time.Duration {
+ if t.t1 != nil {
+ return t.t1.IdleConnTimeout
+ }
+ return 0
+}
+
+func setResponseUncompressed(res *http.Response) { res.Uncompressed = true }
+
+func traceGotConn(req *http.Request, cc *ClientConn) {
+ trace := httptrace.ContextClientTrace(req.Context())
+ if trace == nil || trace.GotConn == nil {
+ return
+ }
+ ci := httptrace.GotConnInfo{Conn: cc.tconn}
+ cc.mu.Lock()
+ ci.Reused = cc.nextStreamID > 1
+ ci.WasIdle = len(cc.streams) == 0 && ci.Reused
+ if ci.WasIdle && !cc.lastActive.IsZero() {
+ ci.IdleTime = time.Now().Sub(cc.lastActive)
+ }
+ cc.mu.Unlock()
+
+ trace.GotConn(ci)
+}
+
+func traceWroteHeaders(trace *clientTrace) {
+ if trace != nil && trace.WroteHeaders != nil {
+ trace.WroteHeaders()
+ }
+}
+
+func traceGot100Continue(trace *clientTrace) {
+ if trace != nil && trace.Got100Continue != nil {
+ trace.Got100Continue()
+ }
+}
+
+func traceWait100Continue(trace *clientTrace) {
+ if trace != nil && trace.Wait100Continue != nil {
+ trace.Wait100Continue()
+ }
+}
+
+func traceWroteRequest(trace *clientTrace, err error) {
+ if trace != nil && trace.WroteRequest != nil {
+ trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
+ }
+}
+
+func traceFirstResponseByte(trace *clientTrace) {
+ if trace != nil && trace.GotFirstResponseByte != nil {
+ trace.GotFirstResponseByte()
+ }
+}
+
+func requestTrace(req *http.Request) *clientTrace {
+ trace := httptrace.ContextClientTrace(req.Context())
+ return (*clientTrace)(trace)
+}
+
+// Ping sends a PING frame to the server and waits for the ack.
+func (cc *ClientConn) Ping(ctx context.Context) error {
+ return cc.ping(ctx)
+}
diff --git a/vendor/golang.org/x/net/http2/go17_not18.go b/vendor/golang.org/x/net/http2/go17_not18.go
new file mode 100644
index 0000000..b4c52ec
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/go17_not18.go
@@ -0,0 +1,36 @@
+// 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 go1.7,!go1.8
+
+package http2
+
+import "crypto/tls"
+
+// temporary copy of Go 1.7's private tls.Config.clone:
+func cloneTLSConfig(c *tls.Config) *tls.Config {
+ return &tls.Config{
+ Rand: c.Rand,
+ Time: c.Time,
+ Certificates: c.Certificates,
+ NameToCertificate: c.NameToCertificate,
+ GetCertificate: c.GetCertificate,
+ RootCAs: c.RootCAs,
+ NextProtos: c.NextProtos,
+ ServerName: c.ServerName,
+ ClientAuth: c.ClientAuth,
+ ClientCAs: c.ClientCAs,
+ InsecureSkipVerify: c.InsecureSkipVerify,
+ CipherSuites: c.CipherSuites,
+ PreferServerCipherSuites: c.PreferServerCipherSuites,
+ SessionTicketsDisabled: c.SessionTicketsDisabled,
+ SessionTicketKey: c.SessionTicketKey,
+ ClientSessionCache: c.ClientSessionCache,
+ MinVersion: c.MinVersion,
+ MaxVersion: c.MaxVersion,
+ CurvePreferences: c.CurvePreferences,
+ DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
+ Renegotiation: c.Renegotiation,
+ }
+}
diff --git a/vendor/golang.org/x/net/http2/go18.go b/vendor/golang.org/x/net/http2/go18.go
new file mode 100644
index 0000000..73cc238
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/go18.go
@@ -0,0 +1,54 @@
+// Copyright 2015 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 go1.8
+
+package http2
+
+import (
+ "crypto/tls"
+ "io"
+ "net/http"
+)
+
+func cloneTLSConfig(c *tls.Config) *tls.Config {
+ c2 := c.Clone()
+ c2.GetClientCertificate = c.GetClientCertificate // golang.org/issue/19264
+ return c2
+}
+
+var _ http.Pusher = (*responseWriter)(nil)
+
+// Push implements http.Pusher.
+func (w *responseWriter) Push(target string, opts *http.PushOptions) error {
+ internalOpts := pushOptions{}
+ if opts != nil {
+ internalOpts.Method = opts.Method
+ internalOpts.Header = opts.Header
+ }
+ return w.push(target, internalOpts)
+}
+
+func configureServer18(h1 *http.Server, h2 *Server) error {
+ if h2.IdleTimeout == 0 {
+ if h1.IdleTimeout != 0 {
+ h2.IdleTimeout = h1.IdleTimeout
+ } else {
+ h2.IdleTimeout = h1.ReadTimeout
+ }
+ }
+ return nil
+}
+
+func shouldLogPanic(panicValue interface{}) bool {
+ return panicValue != nil && panicValue != http.ErrAbortHandler
+}
+
+func reqGetBody(req *http.Request) func() (io.ReadCloser, error) {
+ return req.GetBody
+}
+
+func reqBodyIsNoBody(body io.ReadCloser) bool {
+ return body == http.NoBody
+}
diff --git a/vendor/golang.org/x/net/http2/go19.go b/vendor/golang.org/x/net/http2/go19.go
new file mode 100644
index 0000000..38124ba
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/go19.go
@@ -0,0 +1,16 @@
+// Copyright 2015 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 go1.9
+
+package http2
+
+import (
+ "net/http"
+)
+
+func configureServer19(s *http.Server, conf *Server) error {
+ s.RegisterOnShutdown(conf.state.startGracefulShutdown)
+ return nil
+}
diff --git a/vendor/golang.org/x/net/http2/gotrack.go b/vendor/golang.org/x/net/http2/gotrack.go
new file mode 100644
index 0000000..9933c9f
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/gotrack.go
@@ -0,0 +1,170 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Defensive debug-only utility to track that functions run on the
+// goroutine that they're supposed to.
+
+package http2
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "os"
+ "runtime"
+ "strconv"
+ "sync"
+)
+
+var DebugGoroutines = os.Getenv("DEBUG_HTTP2_GOROUTINES") == "1"
+
+type goroutineLock uint64
+
+func newGoroutineLock() goroutineLock {
+ if !DebugGoroutines {
+ return 0
+ }
+ return goroutineLock(curGoroutineID())
+}
+
+func (g goroutineLock) check() {
+ if !DebugGoroutines {
+ return
+ }
+ if curGoroutineID() != uint64(g) {
+ panic("running on the wrong goroutine")
+ }
+}
+
+func (g goroutineLock) checkNotOn() {
+ if !DebugGoroutines {
+ return
+ }
+ if curGoroutineID() == uint64(g) {
+ panic("running on the wrong goroutine")
+ }
+}
+
+var goroutineSpace = []byte("goroutine ")
+
+func curGoroutineID() uint64 {
+ bp := littleBuf.Get().(*[]byte)
+ defer littleBuf.Put(bp)
+ b := *bp
+ b = b[:runtime.Stack(b, false)]
+ // Parse the 4707 out of "goroutine 4707 ["
+ b = bytes.TrimPrefix(b, goroutineSpace)
+ i := bytes.IndexByte(b, ' ')
+ if i < 0 {
+ panic(fmt.Sprintf("No space found in %q", b))
+ }
+ b = b[:i]
+ n, err := parseUintBytes(b, 10, 64)
+ if err != nil {
+ panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err))
+ }
+ return n
+}
+
+var littleBuf = sync.Pool{
+ New: func() interface{} {
+ buf := make([]byte, 64)
+ return &buf
+ },
+}
+
+// parseUintBytes is like strconv.ParseUint, but using a []byte.
+func parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) {
+ var cutoff, maxVal uint64
+
+ if bitSize == 0 {
+ bitSize = int(strconv.IntSize)
+ }
+
+ s0 := s
+ switch {
+ case len(s) < 1:
+ err = strconv.ErrSyntax
+ goto Error
+
+ case 2 <= base && base <= 36:
+ // valid base; nothing to do
+
+ case base == 0:
+ // Look for octal, hex prefix.
+ switch {
+ case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'):
+ base = 16
+ s = s[2:]
+ if len(s) < 1 {
+ err = strconv.ErrSyntax
+ goto Error
+ }
+ case s[0] == '0':
+ base = 8
+ default:
+ base = 10
+ }
+
+ default:
+ err = errors.New("invalid base " + strconv.Itoa(base))
+ goto Error
+ }
+
+ n = 0
+ cutoff = cutoff64(base)
+ maxVal = 1<<uint(bitSize) - 1
+
+ for i := 0; i < len(s); i++ {
+ var v byte
+ d := s[i]
+ switch {
+ case '0' <= d && d <= '9':
+ v = d - '0'
+ case 'a' <= d && d <= 'z':
+ v = d - 'a' + 10
+ case 'A' <= d && d <= 'Z':
+ v = d - 'A' + 10
+ default:
+ n = 0
+ err = strconv.ErrSyntax
+ goto Error
+ }
+ if int(v) >= base {
+ n = 0
+ err = strconv.ErrSyntax
+ goto Error
+ }
+
+ if n >= cutoff {
+ // n*base overflows
+ n = 1<<64 - 1
+ err = strconv.ErrRange
+ goto Error
+ }
+ n *= uint64(base)
+
+ n1 := n + uint64(v)
+ if n1 < n || n1 > maxVal {
+ // n+v overflows
+ n = 1<<64 - 1
+ err = strconv.ErrRange
+ goto Error
+ }
+ n = n1
+ }
+
+ return n, nil
+
+Error:
+ return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
+}
+
+// Return the first number n such that n*base >= 1<<64.
+func cutoff64(base int) uint64 {
+ if base < 2 {
+ return 0
+ }
+ return (1<<64-1)/uint64(base) + 1
+}
diff --git a/vendor/golang.org/x/net/http2/headermap.go b/vendor/golang.org/x/net/http2/headermap.go
new file mode 100644
index 0000000..c2805f6
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/headermap.go
@@ -0,0 +1,78 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package http2
+
+import (
+ "net/http"
+ "strings"
+)
+
+var (
+ commonLowerHeader = map[string]string{} // Go-Canonical-Case -> lower-case
+ commonCanonHeader = map[string]string{} // lower-case -> Go-Canonical-Case
+)
+
+func init() {
+ for _, v := range []string{
+ "accept",
+ "accept-charset",
+ "accept-encoding",
+ "accept-language",
+ "accept-ranges",
+ "age",
+ "access-control-allow-origin",
+ "allow",
+ "authorization",
+ "cache-control",
+ "content-disposition",
+ "content-encoding",
+ "content-language",
+ "content-length",
+ "content-location",
+ "content-range",
+ "content-type",
+ "cookie",
+ "date",
+ "etag",
+ "expect",
+ "expires",
+ "from",
+ "host",
+ "if-match",
+ "if-modified-since",
+ "if-none-match",
+ "if-unmodified-since",
+ "last-modified",
+ "link",
+ "location",
+ "max-forwards",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "range",
+ "referer",
+ "refresh",
+ "retry-after",
+ "server",
+ "set-cookie",
+ "strict-transport-security",
+ "trailer",
+ "transfer-encoding",
+ "user-agent",
+ "vary",
+ "via",
+ "www-authenticate",
+ } {
+ chk := http.CanonicalHeaderKey(v)
+ commonLowerHeader[chk] = v
+ commonCanonHeader[v] = chk
+ }
+}
+
+func lowerHeader(v string) string {
+ if s, ok := commonLowerHeader[v]; ok {
+ return s
+ }
+ return strings.ToLower(v)
+}
diff --git a/vendor/golang.org/x/net/http2/hpack/encode.go b/vendor/golang.org/x/net/http2/hpack/encode.go
new file mode 100644
index 0000000..54726c2
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/hpack/encode.go
@@ -0,0 +1,240 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package hpack
+
+import (
+ "io"
+)
+
+const (
+ uint32Max = ^uint32(0)
+ initialHeaderTableSize = 4096
+)
+
+type Encoder struct {
+ dynTab dynamicTable
+ // minSize is the minimum table size set by
+ // SetMaxDynamicTableSize after the previous Header Table Size
+ // Update.
+ minSize uint32
+ // maxSizeLimit is the maximum table size this encoder
+ // supports. This will protect the encoder from too large
+ // size.
+ maxSizeLimit uint32
+ // tableSizeUpdate indicates whether "Header Table Size
+ // Update" is required.
+ tableSizeUpdate bool
+ w io.Writer
+ buf []byte
+}
+
+// NewEncoder returns a new Encoder which performs HPACK encoding. An
+// encoded data is written to w.
+func NewEncoder(w io.Writer) *Encoder {
+ e := &Encoder{
+ minSize: uint32Max,
+ maxSizeLimit: initialHeaderTableSize,
+ tableSizeUpdate: false,
+ w: w,
+ }
+ e.dynTab.table.init()
+ e.dynTab.setMaxSize(initialHeaderTableSize)
+ return e
+}
+
+// WriteField encodes f into a single Write to e's underlying Writer.
+// This function may also produce bytes for "Header Table Size Update"
+// if necessary. If produced, it is done before encoding f.
+func (e *Encoder) WriteField(f HeaderField) error {
+ e.buf = e.buf[:0]
+
+ if e.tableSizeUpdate {
+ e.tableSizeUpdate = false
+ if e.minSize < e.dynTab.maxSize {
+ e.buf = appendTableSize(e.buf, e.minSize)
+ }
+ e.minSize = uint32Max
+ e.buf = appendTableSize(e.buf, e.dynTab.maxSize)
+ }
+
+ idx, nameValueMatch := e.searchTable(f)
+ if nameValueMatch {
+ e.buf = appendIndexed(e.buf, idx)
+ } else {
+ indexing := e.shouldIndex(f)
+ if indexing {
+ e.dynTab.add(f)
+ }
+
+ if idx == 0 {
+ e.buf = appendNewName(e.buf, f, indexing)
+ } else {
+ e.buf = appendIndexedName(e.buf, f, idx, indexing)
+ }
+ }
+ n, err := e.w.Write(e.buf)
+ if err == nil && n != len(e.buf) {
+ err = io.ErrShortWrite
+ }
+ return err
+}
+
+// searchTable searches f in both stable and dynamic header tables.
+// The static header table is searched first. Only when there is no
+// exact match for both name and value, the dynamic header table is
+// then searched. If there is no match, i is 0. If both name and value
+// match, i is the matched index and nameValueMatch becomes true. If
+// only name matches, i points to that index and nameValueMatch
+// becomes false.
+func (e *Encoder) searchTable(f HeaderField) (i uint64, nameValueMatch bool) {
+ i, nameValueMatch = staticTable.search(f)
+ if nameValueMatch {
+ return i, true
+ }
+
+ j, nameValueMatch := e.dynTab.table.search(f)
+ if nameValueMatch || (i == 0 && j != 0) {
+ return j + uint64(staticTable.len()), nameValueMatch
+ }
+
+ return i, false
+}
+
+// SetMaxDynamicTableSize changes the dynamic header table size to v.
+// The actual size is bounded by the value passed to
+// SetMaxDynamicTableSizeLimit.
+func (e *Encoder) SetMaxDynamicTableSize(v uint32) {
+ if v > e.maxSizeLimit {
+ v = e.maxSizeLimit
+ }
+ if v < e.minSize {
+ e.minSize = v
+ }
+ e.tableSizeUpdate = true
+ e.dynTab.setMaxSize(v)
+}
+
+// SetMaxDynamicTableSizeLimit changes the maximum value that can be
+// specified in SetMaxDynamicTableSize to v. By default, it is set to
+// 4096, which is the same size of the default dynamic header table
+// size described in HPACK specification. If the current maximum
+// dynamic header table size is strictly greater than v, "Header Table
+// Size Update" will be done in the next WriteField call and the
+// maximum dynamic header table size is truncated to v.
+func (e *Encoder) SetMaxDynamicTableSizeLimit(v uint32) {
+ e.maxSizeLimit = v
+ if e.dynTab.maxSize > v {
+ e.tableSizeUpdate = true
+ e.dynTab.setMaxSize(v)
+ }
+}
+
+// shouldIndex reports whether f should be indexed.
+func (e *Encoder) shouldIndex(f HeaderField) bool {
+ return !f.Sensitive && f.Size() <= e.dynTab.maxSize
+}
+
+// appendIndexed appends index i, as encoded in "Indexed Header Field"
+// representation, to dst and returns the extended buffer.
+func appendIndexed(dst []byte, i uint64) []byte {
+ first := len(dst)
+ dst = appendVarInt(dst, 7, i)
+ dst[first] |= 0x80
+ return dst
+}
+
+// appendNewName appends f, as encoded in one of "Literal Header field
+// - New Name" representation variants, to dst and returns the
+// extended buffer.
+//
+// If f.Sensitive is true, "Never Indexed" representation is used. If
+// f.Sensitive is false and indexing is true, "Inremental Indexing"
+// representation is used.
+func appendNewName(dst []byte, f HeaderField, indexing bool) []byte {
+ dst = append(dst, encodeTypeByte(indexing, f.Sensitive))
+ dst = appendHpackString(dst, f.Name)
+ return appendHpackString(dst, f.Value)
+}
+
+// appendIndexedName appends f and index i referring indexed name
+// entry, as encoded in one of "Literal Header field - Indexed Name"
+// representation variants, to dst and returns the extended buffer.
+//
+// If f.Sensitive is true, "Never Indexed" representation is used. If
+// f.Sensitive is false and indexing is true, "Incremental Indexing"
+// representation is used.
+func appendIndexedName(dst []byte, f HeaderField, i uint64, indexing bool) []byte {
+ first := len(dst)
+ var n byte
+ if indexing {
+ n = 6
+ } else {
+ n = 4
+ }
+ dst = appendVarInt(dst, n, i)
+ dst[first] |= encodeTypeByte(indexing, f.Sensitive)
+ return appendHpackString(dst, f.Value)
+}
+
+// appendTableSize appends v, as encoded in "Header Table Size Update"
+// representation, to dst and returns the extended buffer.
+func appendTableSize(dst []byte, v uint32) []byte {
+ first := len(dst)
+ dst = appendVarInt(dst, 5, uint64(v))
+ dst[first] |= 0x20
+ return dst
+}
+
+// appendVarInt appends i, as encoded in variable integer form using n
+// bit prefix, to dst and returns the extended buffer.
+//
+// See
+// http://http2.github.io/http2-spec/compression.html#integer.representation
+func appendVarInt(dst []byte, n byte, i uint64) []byte {
+ k := uint64((1 << n) - 1)
+ if i < k {
+ return append(dst, byte(i))
+ }
+ dst = append(dst, byte(k))
+ i -= k
+ for ; i >= 128; i >>= 7 {
+ dst = append(dst, byte(0x80|(i&0x7f)))
+ }
+ return append(dst, byte(i))
+}
+
+// appendHpackString appends s, as encoded in "String Literal"
+// representation, to dst and returns the the extended buffer.
+//
+// s will be encoded in Huffman codes only when it produces strictly
+// shorter byte string.
+func appendHpackString(dst []byte, s string) []byte {
+ huffmanLength := HuffmanEncodeLength(s)
+ if huffmanLength < uint64(len(s)) {
+ first := len(dst)
+ dst = appendVarInt(dst, 7, huffmanLength)
+ dst = AppendHuffmanString(dst, s)
+ dst[first] |= 0x80
+ } else {
+ dst = appendVarInt(dst, 7, uint64(len(s)))
+ dst = append(dst, s...)
+ }
+ return dst
+}
+
+// encodeTypeByte returns type byte. If sensitive is true, type byte
+// for "Never Indexed" representation is returned. If sensitive is
+// false and indexing is true, type byte for "Incremental Indexing"
+// representation is returned. Otherwise, type byte for "Without
+// Indexing" is returned.
+func encodeTypeByte(indexing, sensitive bool) byte {
+ if sensitive {
+ return 0x10
+ }
+ if indexing {
+ return 0x40
+ }
+ return 0
+}
diff --git a/vendor/golang.org/x/net/http2/hpack/hpack.go b/vendor/golang.org/x/net/http2/hpack/hpack.go
new file mode 100644
index 0000000..176644a
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/hpack/hpack.go
@@ -0,0 +1,490 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package hpack implements HPACK, a compression format for
+// efficiently representing HTTP header fields in the context of HTTP/2.
+//
+// See http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-09
+package hpack
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+)
+
+// A DecodingError is something the spec defines as a decoding error.
+type DecodingError struct {
+ Err error
+}
+
+func (de DecodingError) Error() string {
+ return fmt.Sprintf("decoding error: %v", de.Err)
+}
+
+// An InvalidIndexError is returned when an encoder references a table
+// entry before the static table or after the end of the dynamic table.
+type InvalidIndexError int
+
+func (e InvalidIndexError) Error() string {
+ return fmt.Sprintf("invalid indexed representation index %d", int(e))
+}
+
+// A HeaderField is a name-value pair. Both the name and value are
+// treated as opaque sequences of octets.
+type HeaderField struct {
+ Name, Value string
+
+ // Sensitive means that this header field should never be
+ // indexed.
+ Sensitive bool
+}
+
+// IsPseudo reports whether the header field is an http2 pseudo header.
+// That is, it reports whether it starts with a colon.
+// It is not otherwise guaranteed to be a valid pseudo header field,
+// though.
+func (hf HeaderField) IsPseudo() bool {
+ return len(hf.Name) != 0 && hf.Name[0] == ':'
+}
+
+func (hf HeaderField) String() string {
+ var suffix string
+ if hf.Sensitive {
+ suffix = " (sensitive)"
+ }
+ return fmt.Sprintf("header field %q = %q%s", hf.Name, hf.Value, suffix)
+}
+
+// Size returns the size of an entry per RFC 7541 section 4.1.
+func (hf HeaderField) Size() uint32 {
+ // http://http2.github.io/http2-spec/compression.html#rfc.section.4.1
+ // "The size of the dynamic table is the sum of the size of
+ // its entries. The size of an entry is the sum of its name's
+ // length in octets (as defined in Section 5.2), its value's
+ // length in octets (see Section 5.2), plus 32. The size of
+ // an entry is calculated using the length of the name and
+ // value without any Huffman encoding applied."
+
+ // This can overflow if somebody makes a large HeaderField
+ // Name and/or Value by hand, but we don't care, because that
+ // won't happen on the wire because the encoding doesn't allow
+ // it.
+ return uint32(len(hf.Name) + len(hf.Value) + 32)
+}
+
+// A Decoder is the decoding context for incremental processing of
+// header blocks.
+type Decoder struct {
+ dynTab dynamicTable
+ emit func(f HeaderField)
+
+ emitEnabled bool // whether calls to emit are enabled
+ maxStrLen int // 0 means unlimited
+
+ // buf is the unparsed buffer. It's only written to
+ // saveBuf if it was truncated in the middle of a header
+ // block. Because it's usually not owned, we can only
+ // process it under Write.
+ buf []byte // not owned; only valid during Write
+
+ // saveBuf is previous data passed to Write which we weren't able
+ // to fully parse before. Unlike buf, we own this data.
+ saveBuf bytes.Buffer
+}
+
+// NewDecoder returns a new decoder with the provided maximum dynamic
+// table size. The emitFunc will be called for each valid field
+// parsed, in the same goroutine as calls to Write, before Write returns.
+func NewDecoder(maxDynamicTableSize uint32, emitFunc func(f HeaderField)) *Decoder {
+ d := &Decoder{
+ emit: emitFunc,
+ emitEnabled: true,
+ }
+ d.dynTab.table.init()
+ d.dynTab.allowedMaxSize = maxDynamicTableSize
+ d.dynTab.setMaxSize(maxDynamicTableSize)
+ return d
+}
+
+// ErrStringLength is returned by Decoder.Write when the max string length
+// (as configured by Decoder.SetMaxStringLength) would be violated.
+var ErrStringLength = errors.New("hpack: string too long")
+
+// SetMaxStringLength sets the maximum size of a HeaderField name or
+// value string. If a string exceeds this length (even after any
+// decompression), Write will return ErrStringLength.
+// A value of 0 means unlimited and is the default from NewDecoder.
+func (d *Decoder) SetMaxStringLength(n int) {
+ d.maxStrLen = n
+}
+
+// SetEmitFunc changes the callback used when new header fields
+// are decoded.
+// It must be non-nil. It does not affect EmitEnabled.
+func (d *Decoder) SetEmitFunc(emitFunc func(f HeaderField)) {
+ d.emit = emitFunc
+}
+
+// SetEmitEnabled controls whether the emitFunc provided to NewDecoder
+// should be called. The default is true.
+//
+// This facility exists to let servers enforce MAX_HEADER_LIST_SIZE
+// while still decoding and keeping in-sync with decoder state, but
+// without doing unnecessary decompression or generating unnecessary
+// garbage for header fields past the limit.
+func (d *Decoder) SetEmitEnabled(v bool) { d.emitEnabled = v }
+
+// EmitEnabled reports whether calls to the emitFunc provided to NewDecoder
+// are currently enabled. The default is true.
+func (d *Decoder) EmitEnabled() bool { return d.emitEnabled }
+
+// TODO: add method *Decoder.Reset(maxSize, emitFunc) to let callers re-use Decoders and their
+// underlying buffers for garbage reasons.
+
+func (d *Decoder) SetMaxDynamicTableSize(v uint32) {
+ d.dynTab.setMaxSize(v)
+}
+
+// SetAllowedMaxDynamicTableSize sets the upper bound that the encoded
+// stream (via dynamic table size updates) may set the maximum size
+// to.
+func (d *Decoder) SetAllowedMaxDynamicTableSize(v uint32) {
+ d.dynTab.allowedMaxSize = v
+}
+
+type dynamicTable struct {
+ // http://http2.github.io/http2-spec/compression.html#rfc.section.2.3.2
+ table headerFieldTable
+ size uint32 // in bytes
+ maxSize uint32 // current maxSize
+ allowedMaxSize uint32 // maxSize may go up to this, inclusive
+}
+
+func (dt *dynamicTable) setMaxSize(v uint32) {
+ dt.maxSize = v
+ dt.evict()
+}
+
+func (dt *dynamicTable) add(f HeaderField) {
+ dt.table.addEntry(f)
+ dt.size += f.Size()
+ dt.evict()
+}
+
+// If we're too big, evict old stuff.
+func (dt *dynamicTable) evict() {
+ var n int
+ for dt.size > dt.maxSize && n < dt.table.len() {
+ dt.size -= dt.table.ents[n].Size()
+ n++
+ }
+ dt.table.evictOldest(n)
+}
+
+func (d *Decoder) maxTableIndex() int {
+ // This should never overflow. RFC 7540 Section 6.5.2 limits the size of
+ // the dynamic table to 2^32 bytes, where each entry will occupy more than
+ // one byte. Further, the staticTable has a fixed, small length.
+ return d.dynTab.table.len() + staticTable.len()
+}
+
+func (d *Decoder) at(i uint64) (hf HeaderField, ok bool) {
+ // See Section 2.3.3.
+ if i == 0 {
+ return
+ }
+ if i <= uint64(staticTable.len()) {
+ return staticTable.ents[i-1], true
+ }
+ if i > uint64(d.maxTableIndex()) {
+ return
+ }
+ // In the dynamic table, newer entries have lower indices.
+ // However, dt.ents[0] is the oldest entry. Hence, dt.ents is
+ // the reversed dynamic table.
+ dt := d.dynTab.table
+ return dt.ents[dt.len()-(int(i)-staticTable.len())], true
+}
+
+// Decode decodes an entire block.
+//
+// TODO: remove this method and make it incremental later? This is
+// easier for debugging now.
+func (d *Decoder) DecodeFull(p []byte) ([]HeaderField, error) {
+ var hf []HeaderField
+ saveFunc := d.emit
+ defer func() { d.emit = saveFunc }()
+ d.emit = func(f HeaderField) { hf = append(hf, f) }
+ if _, err := d.Write(p); err != nil {
+ return nil, err
+ }
+ if err := d.Close(); err != nil {
+ return nil, err
+ }
+ return hf, nil
+}
+
+func (d *Decoder) Close() error {
+ if d.saveBuf.Len() > 0 {
+ d.saveBuf.Reset()
+ return DecodingError{errors.New("truncated headers")}
+ }
+ return nil
+}
+
+func (d *Decoder) Write(p []byte) (n int, err error) {
+ if len(p) == 0 {
+ // Prevent state machine CPU attacks (making us redo
+ // work up to the point of finding out we don't have
+ // enough data)
+ return
+ }
+ // Only copy the data if we have to. Optimistically assume
+ // that p will contain a complete header block.
+ if d.saveBuf.Len() == 0 {
+ d.buf = p
+ } else {
+ d.saveBuf.Write(p)
+ d.buf = d.saveBuf.Bytes()
+ d.saveBuf.Reset()
+ }
+
+ for len(d.buf) > 0 {
+ err = d.parseHeaderFieldRepr()
+ if err == errNeedMore {
+ // Extra paranoia, making sure saveBuf won't
+ // get too large. All the varint and string
+ // reading code earlier should already catch
+ // overlong things and return ErrStringLength,
+ // but keep this as a last resort.
+ const varIntOverhead = 8 // conservative
+ if d.maxStrLen != 0 && int64(len(d.buf)) > 2*(int64(d.maxStrLen)+varIntOverhead) {
+ return 0, ErrStringLength
+ }
+ d.saveBuf.Write(d.buf)
+ return len(p), nil
+ }
+ if err != nil {
+ break
+ }
+ }
+ return len(p), err
+}
+
+// errNeedMore is an internal sentinel error value that means the
+// buffer is truncated and we need to read more data before we can
+// continue parsing.
+var errNeedMore = errors.New("need more data")
+
+type indexType int
+
+const (
+ indexedTrue indexType = iota
+ indexedFalse
+ indexedNever
+)
+
+func (v indexType) indexed() bool { return v == indexedTrue }
+func (v indexType) sensitive() bool { return v == indexedNever }
+
+// returns errNeedMore if there isn't enough data available.
+// any other error is fatal.
+// consumes d.buf iff it returns nil.
+// precondition: must be called with len(d.buf) > 0
+func (d *Decoder) parseHeaderFieldRepr() error {
+ b := d.buf[0]
+ switch {
+ case b&128 != 0:
+ // Indexed representation.
+ // High bit set?
+ // http://http2.github.io/http2-spec/compression.html#rfc.section.6.1
+ return d.parseFieldIndexed()
+ case b&192 == 64:
+ // 6.2.1 Literal Header Field with Incremental Indexing
+ // 0b10xxxxxx: top two bits are 10
+ // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.1
+ return d.parseFieldLiteral(6, indexedTrue)
+ case b&240 == 0:
+ // 6.2.2 Literal Header Field without Indexing
+ // 0b0000xxxx: top four bits are 0000
+ // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.2
+ return d.parseFieldLiteral(4, indexedFalse)
+ case b&240 == 16:
+ // 6.2.3 Literal Header Field never Indexed
+ // 0b0001xxxx: top four bits are 0001
+ // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.3
+ return d.parseFieldLiteral(4, indexedNever)
+ case b&224 == 32:
+ // 6.3 Dynamic Table Size Update
+ // Top three bits are '001'.
+ // http://http2.github.io/http2-spec/compression.html#rfc.section.6.3
+ return d.parseDynamicTableSizeUpdate()
+ }
+
+ return DecodingError{errors.New("invalid encoding")}
+}
+
+// (same invariants and behavior as parseHeaderFieldRepr)
+func (d *Decoder) parseFieldIndexed() error {
+ buf := d.buf
+ idx, buf, err := readVarInt(7, buf)
+ if err != nil {
+ return err
+ }
+ hf, ok := d.at(idx)
+ if !ok {
+ return DecodingError{InvalidIndexError(idx)}
+ }
+ d.buf = buf
+ return d.callEmit(HeaderField{Name: hf.Name, Value: hf.Value})
+}
+
+// (same invariants and behavior as parseHeaderFieldRepr)
+func (d *Decoder) parseFieldLiteral(n uint8, it indexType) error {
+ buf := d.buf
+ nameIdx, buf, err := readVarInt(n, buf)
+ if err != nil {
+ return err
+ }
+
+ var hf HeaderField
+ wantStr := d.emitEnabled || it.indexed()
+ if nameIdx > 0 {
+ ihf, ok := d.at(nameIdx)
+ if !ok {
+ return DecodingError{InvalidIndexError(nameIdx)}
+ }
+ hf.Name = ihf.Name
+ } else {
+ hf.Name, buf, err = d.readString(buf, wantStr)
+ if err != nil {
+ return err
+ }
+ }
+ hf.Value, buf, err = d.readString(buf, wantStr)
+ if err != nil {
+ return err
+ }
+ d.buf = buf
+ if it.indexed() {
+ d.dynTab.add(hf)
+ }
+ hf.Sensitive = it.sensitive()
+ return d.callEmit(hf)
+}
+
+func (d *Decoder) callEmit(hf HeaderField) error {
+ if d.maxStrLen != 0 {
+ if len(hf.Name) > d.maxStrLen || len(hf.Value) > d.maxStrLen {
+ return ErrStringLength
+ }
+ }
+ if d.emitEnabled {
+ d.emit(hf)
+ }
+ return nil
+}
+
+// (same invariants and behavior as parseHeaderFieldRepr)
+func (d *Decoder) parseDynamicTableSizeUpdate() error {
+ buf := d.buf
+ size, buf, err := readVarInt(5, buf)
+ if err != nil {
+ return err
+ }
+ if size > uint64(d.dynTab.allowedMaxSize) {
+ return DecodingError{errors.New("dynamic table size update too large")}
+ }
+ d.dynTab.setMaxSize(uint32(size))
+ d.buf = buf
+ return nil
+}
+
+var errVarintOverflow = DecodingError{errors.New("varint integer overflow")}
+
+// readVarInt reads an unsigned variable length integer off the
+// beginning of p. n is the parameter as described in
+// http://http2.github.io/http2-spec/compression.html#rfc.section.5.1.
+//
+// n must always be between 1 and 8.
+//
+// The returned remain buffer is either a smaller suffix of p, or err != nil.
+// The error is errNeedMore if p doesn't contain a complete integer.
+func readVarInt(n byte, p []byte) (i uint64, remain []byte, err error) {
+ if n < 1 || n > 8 {
+ panic("bad n")
+ }
+ if len(p) == 0 {
+ return 0, p, errNeedMore
+ }
+ i = uint64(p[0])
+ if n < 8 {
+ i &= (1 << uint64(n)) - 1
+ }
+ if i < (1<<uint64(n))-1 {
+ return i, p[1:], nil
+ }
+
+ origP := p
+ p = p[1:]
+ var m uint64
+ for len(p) > 0 {
+ b := p[0]
+ p = p[1:]
+ i += uint64(b&127) << m
+ if b&128 == 0 {
+ return i, p, nil
+ }
+ m += 7
+ if m >= 63 { // TODO: proper overflow check. making this up.
+ return 0, origP, errVarintOverflow
+ }
+ }
+ return 0, origP, errNeedMore
+}
+
+// readString decodes an hpack string from p.
+//
+// wantStr is whether s will be used. If false, decompression and
+// []byte->string garbage are skipped if s will be ignored
+// anyway. This does mean that huffman decoding errors for non-indexed
+// strings past the MAX_HEADER_LIST_SIZE are ignored, but the server
+// is returning an error anyway, and because they're not indexed, the error
+// won't affect the decoding state.
+func (d *Decoder) readString(p []byte, wantStr bool) (s string, remain []byte, err error) {
+ if len(p) == 0 {
+ return "", p, errNeedMore
+ }
+ isHuff := p[0]&128 != 0
+ strLen, p, err := readVarInt(7, p)
+ if err != nil {
+ return "", p, err
+ }
+ if d.maxStrLen != 0 && strLen > uint64(d.maxStrLen) {
+ return "", nil, ErrStringLength
+ }
+ if uint64(len(p)) < strLen {
+ return "", p, errNeedMore
+ }
+ if !isHuff {
+ if wantStr {
+ s = string(p[:strLen])
+ }
+ return s, p[strLen:], nil
+ }
+
+ if wantStr {
+ buf := bufPool.Get().(*bytes.Buffer)
+ buf.Reset() // don't trust others
+ defer bufPool.Put(buf)
+ if err := huffmanDecode(buf, d.maxStrLen, p[:strLen]); err != nil {
+ buf.Reset()
+ return "", nil, err
+ }
+ s = buf.String()
+ buf.Reset() // be nice to GC
+ }
+ return s, p[strLen:], nil
+}
diff --git a/vendor/golang.org/x/net/http2/hpack/huffman.go b/vendor/golang.org/x/net/http2/hpack/huffman.go
new file mode 100644
index 0000000..8850e39
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/hpack/huffman.go
@@ -0,0 +1,212 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package hpack
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "sync"
+)
+
+var bufPool = sync.Pool{
+ New: func() interface{} { return new(bytes.Buffer) },
+}
+
+// HuffmanDecode decodes the string in v and writes the expanded
+// result to w, returning the number of bytes written to w and the
+// Write call's return value. At most one Write call is made.
+func HuffmanDecode(w io.Writer, v []byte) (int, error) {
+ buf := bufPool.Get().(*bytes.Buffer)
+ buf.Reset()
+ defer bufPool.Put(buf)
+ if err := huffmanDecode(buf, 0, v); err != nil {
+ return 0, err
+ }
+ return w.Write(buf.Bytes())
+}
+
+// HuffmanDecodeToString decodes the string in v.
+func HuffmanDecodeToString(v []byte) (string, error) {
+ buf := bufPool.Get().(*bytes.Buffer)
+ buf.Reset()
+ defer bufPool.Put(buf)
+ if err := huffmanDecode(buf, 0, v); err != nil {
+ return "", err
+ }
+ return buf.String(), nil
+}
+
+// ErrInvalidHuffman is returned for errors found decoding
+// Huffman-encoded strings.
+var ErrInvalidHuffman = errors.New("hpack: invalid Huffman-encoded data")
+
+// huffmanDecode decodes v to buf.
+// If maxLen is greater than 0, attempts to write more to buf than
+// maxLen bytes will return ErrStringLength.
+func huffmanDecode(buf *bytes.Buffer, maxLen int, v []byte) error {
+ n := rootHuffmanNode
+ // cur is the bit buffer that has not been fed into n.
+ // cbits is the number of low order bits in cur that are valid.
+ // sbits is the number of bits of the symbol prefix being decoded.
+ cur, cbits, sbits := uint(0), uint8(0), uint8(0)
+ for _, b := range v {
+ cur = cur<<8 | uint(b)
+ cbits += 8
+ sbits += 8
+ for cbits >= 8 {
+ idx := byte(cur >> (cbits - 8))
+ n = n.children[idx]
+ if n == nil {
+ return ErrInvalidHuffman
+ }
+ if n.children == nil {
+ if maxLen != 0 && buf.Len() == maxLen {
+ return ErrStringLength
+ }
+ buf.WriteByte(n.sym)
+ cbits -= n.codeLen
+ n = rootHuffmanNode
+ sbits = cbits
+ } else {
+ cbits -= 8
+ }
+ }
+ }
+ for cbits > 0 {
+ n = n.children[byte(cur<<(8-cbits))]
+ if n == nil {
+ return ErrInvalidHuffman
+ }
+ if n.children != nil || n.codeLen > cbits {
+ break
+ }
+ if maxLen != 0 && buf.Len() == maxLen {
+ return ErrStringLength
+ }
+ buf.WriteByte(n.sym)
+ cbits -= n.codeLen
+ n = rootHuffmanNode
+ sbits = cbits
+ }
+ if sbits > 7 {
+ // Either there was an incomplete symbol, or overlong padding.
+ // Both are decoding errors per RFC 7541 section 5.2.
+ return ErrInvalidHuffman
+ }
+ if mask := uint(1<<cbits - 1); cur&mask != mask {
+ // Trailing bits must be a prefix of EOS per RFC 7541 section 5.2.
+ return ErrInvalidHuffman
+ }
+
+ return nil
+}
+
+type node struct {
+ // children is non-nil for internal nodes
+ children []*node
+
+ // The following are only valid if children is nil:
+ codeLen uint8 // number of bits that led to the output of sym
+ sym byte // output symbol
+}
+
+func newInternalNode() *node {
+ return &node{children: make([]*node, 256)}
+}
+
+var rootHuffmanNode = newInternalNode()
+
+func init() {
+ if len(huffmanCodes) != 256 {
+ panic("unexpected size")
+ }
+ for i, code := range huffmanCodes {
+ addDecoderNode(byte(i), code, huffmanCodeLen[i])
+ }
+}
+
+func addDecoderNode(sym byte, code uint32, codeLen uint8) {
+ cur := rootHuffmanNode
+ for codeLen > 8 {
+ codeLen -= 8
+ i := uint8(code >> codeLen)
+ if cur.children[i] == nil {
+ cur.children[i] = newInternalNode()
+ }
+ cur = cur.children[i]
+ }
+ shift := 8 - codeLen
+ start, end := int(uint8(code<<shift)), int(1<<shift)
+ for i := start; i < start+end; i++ {
+ cur.children[i] = &node{sym: sym, codeLen: codeLen}
+ }
+}
+
+// AppendHuffmanString appends s, as encoded in Huffman codes, to dst
+// and returns the extended buffer.
+func AppendHuffmanString(dst []byte, s string) []byte {
+ rembits := uint8(8)
+
+ for i := 0; i < len(s); i++ {
+ if rembits == 8 {
+ dst = append(dst, 0)
+ }
+ dst, rembits = appendByteToHuffmanCode(dst, rembits, s[i])
+ }
+
+ if rembits < 8 {
+ // special EOS symbol
+ code := uint32(0x3fffffff)
+ nbits := uint8(30)
+
+ t := uint8(code >> (nbits - rembits))
+ dst[len(dst)-1] |= t
+ }
+
+ return dst
+}
+
+// HuffmanEncodeLength returns the number of bytes required to encode
+// s in Huffman codes. The result is round up to byte boundary.
+func HuffmanEncodeLength(s string) uint64 {
+ n := uint64(0)
+ for i := 0; i < len(s); i++ {
+ n += uint64(huffmanCodeLen[s[i]])
+ }
+ return (n + 7) / 8
+}
+
+// appendByteToHuffmanCode appends Huffman code for c to dst and
+// returns the extended buffer and the remaining bits in the last
+// element. The appending is not byte aligned and the remaining bits
+// in the last element of dst is given in rembits.
+func appendByteToHuffmanCode(dst []byte, rembits uint8, c byte) ([]byte, uint8) {
+ code := huffmanCodes[c]
+ nbits := huffmanCodeLen[c]
+
+ for {
+ if rembits > nbits {
+ t := uint8(code << (rembits - nbits))
+ dst[len(dst)-1] |= t
+ rembits -= nbits
+ break
+ }
+
+ t := uint8(code >> (nbits - rembits))
+ dst[len(dst)-1] |= t
+
+ nbits -= rembits
+ rembits = 8
+
+ if nbits == 0 {
+ break
+ }
+
+ dst = append(dst, 0)
+ }
+
+ return dst, rembits
+}
diff --git a/vendor/golang.org/x/net/http2/hpack/tables.go b/vendor/golang.org/x/net/http2/hpack/tables.go
new file mode 100644
index 0000000..a66cfbe
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/hpack/tables.go
@@ -0,0 +1,479 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package hpack
+
+import (
+ "fmt"
+)
+
+// headerFieldTable implements a list of HeaderFields.
+// This is used to implement the static and dynamic tables.
+type headerFieldTable struct {
+ // For static tables, entries are never evicted.
+ //
+ // For dynamic tables, entries are evicted from ents[0] and added to the end.
+ // Each entry has a unique id that starts at one and increments for each
+ // entry that is added. This unique id is stable across evictions, meaning
+ // it can be used as a pointer to a specific entry. As in hpack, unique ids
+ // are 1-based. The unique id for ents[k] is k + evictCount + 1.
+ //
+ // Zero is not a valid unique id.
+ //
+ // evictCount should not overflow in any remotely practical situation. In
+ // practice, we will have one dynamic table per HTTP/2 connection. If we
+ // assume a very powerful server that handles 1M QPS per connection and each
+ // request adds (then evicts) 100 entries from the table, it would still take
+ // 2M years for evictCount to overflow.
+ ents []HeaderField
+ evictCount uint64
+
+ // byName maps a HeaderField name to the unique id of the newest entry with
+ // the same name. See above for a definition of "unique id".
+ byName map[string]uint64
+
+ // byNameValue maps a HeaderField name/value pair to the unique id of the newest
+ // entry with the same name and value. See above for a definition of "unique id".
+ byNameValue map[pairNameValue]uint64
+}
+
+type pairNameValue struct {
+ name, value string
+}
+
+func (t *headerFieldTable) init() {
+ t.byName = make(map[string]uint64)
+ t.byNameValue = make(map[pairNameValue]uint64)
+}
+
+// len reports the number of entries in the table.
+func (t *headerFieldTable) len() int {
+ return len(t.ents)
+}
+
+// addEntry adds a new entry.
+func (t *headerFieldTable) addEntry(f HeaderField) {
+ id := uint64(t.len()) + t.evictCount + 1
+ t.byName[f.Name] = id
+ t.byNameValue[pairNameValue{f.Name, f.Value}] = id
+ t.ents = append(t.ents, f)
+}
+
+// evictOldest evicts the n oldest entries in the table.
+func (t *headerFieldTable) evictOldest(n int) {
+ if n > t.len() {
+ panic(fmt.Sprintf("evictOldest(%v) on table with %v entries", n, t.len()))
+ }
+ for k := 0; k < n; k++ {
+ f := t.ents[k]
+ id := t.evictCount + uint64(k) + 1
+ if t.byName[f.Name] == id {
+ delete(t.byName, f.Name)
+ }
+ if p := (pairNameValue{f.Name, f.Value}); t.byNameValue[p] == id {
+ delete(t.byNameValue, p)
+ }
+ }
+ copy(t.ents, t.ents[n:])
+ for k := t.len() - n; k < t.len(); k++ {
+ t.ents[k] = HeaderField{} // so strings can be garbage collected
+ }
+ t.ents = t.ents[:t.len()-n]
+ if t.evictCount+uint64(n) < t.evictCount {
+ panic("evictCount overflow")
+ }
+ t.evictCount += uint64(n)
+}
+
+// search finds f in the table. If there is no match, i is 0.
+// If both name and value match, i is the matched index and nameValueMatch
+// becomes true. If only name matches, i points to that index and
+// nameValueMatch becomes false.
+//
+// The returned index is a 1-based HPACK index. For dynamic tables, HPACK says
+// that index 1 should be the newest entry, but t.ents[0] is the oldest entry,
+// meaning t.ents is reversed for dynamic tables. Hence, when t is a dynamic
+// table, the return value i actually refers to the entry t.ents[t.len()-i].
+//
+// All tables are assumed to be a dynamic tables except for the global
+// staticTable pointer.
+//
+// See Section 2.3.3.
+func (t *headerFieldTable) search(f HeaderField) (i uint64, nameValueMatch bool) {
+ if !f.Sensitive {
+ if id := t.byNameValue[pairNameValue{f.Name, f.Value}]; id != 0 {
+ return t.idToIndex(id), true
+ }
+ }
+ if id := t.byName[f.Name]; id != 0 {
+ return t.idToIndex(id), false
+ }
+ return 0, false
+}
+
+// idToIndex converts a unique id to an HPACK index.
+// See Section 2.3.3.
+func (t *headerFieldTable) idToIndex(id uint64) uint64 {
+ if id <= t.evictCount {
+ panic(fmt.Sprintf("id (%v) <= evictCount (%v)", id, t.evictCount))
+ }
+ k := id - t.evictCount - 1 // convert id to an index t.ents[k]
+ if t != staticTable {
+ return uint64(t.len()) - k // dynamic table
+ }
+ return k + 1
+}
+
+// http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-07#appendix-B
+var staticTable = newStaticTable()
+var staticTableEntries = [...]HeaderField{
+ {Name: ":authority"},
+ {Name: ":method", Value: "GET"},
+ {Name: ":method", Value: "POST"},
+ {Name: ":path", Value: "/"},
+ {Name: ":path", Value: "/index.html"},
+ {Name: ":scheme", Value: "http"},
+ {Name: ":scheme", Value: "https"},
+ {Name: ":status", Value: "200"},
+ {Name: ":status", Value: "204"},
+ {Name: ":status", Value: "206"},
+ {Name: ":status", Value: "304"},
+ {Name: ":status", Value: "400"},
+ {Name: ":status", Value: "404"},
+ {Name: ":status", Value: "500"},
+ {Name: "accept-charset"},
+ {Name: "accept-encoding", Value: "gzip, deflate"},
+ {Name: "accept-language"},
+ {Name: "accept-ranges"},
+ {Name: "accept"},
+ {Name: "access-control-allow-origin"},
+ {Name: "age"},
+ {Name: "allow"},
+ {Name: "authorization"},
+ {Name: "cache-control"},
+ {Name: "content-disposition"},
+ {Name: "content-encoding"},
+ {Name: "content-language"},
+ {Name: "content-length"},
+ {Name: "content-location"},
+ {Name: "content-range"},
+ {Name: "content-type"},
+ {Name: "cookie"},
+ {Name: "date"},
+ {Name: "etag"},
+ {Name: "expect"},
+ {Name: "expires"},
+ {Name: "from"},
+ {Name: "host"},
+ {Name: "if-match"},
+ {Name: "if-modified-since"},
+ {Name: "if-none-match"},
+ {Name: "if-range"},
+ {Name: "if-unmodified-since"},
+ {Name: "last-modified"},
+ {Name: "link"},
+ {Name: "location"},
+ {Name: "max-forwards"},
+ {Name: "proxy-authenticate"},
+ {Name: "proxy-authorization"},
+ {Name: "range"},
+ {Name: "referer"},
+ {Name: "refresh"},
+ {Name: "retry-after"},
+ {Name: "server"},
+ {Name: "set-cookie"},
+ {Name: "strict-transport-security"},
+ {Name: "transfer-encoding"},
+ {Name: "user-agent"},
+ {Name: "vary"},
+ {Name: "via"},
+ {Name: "www-authenticate"},
+}
+
+func newStaticTable() *headerFieldTable {
+ t := &headerFieldTable{}
+ t.init()
+ for _, e := range staticTableEntries[:] {
+ t.addEntry(e)
+ }
+ return t
+}
+
+var huffmanCodes = [256]uint32{
+ 0x1ff8,
+ 0x7fffd8,
+ 0xfffffe2,
+ 0xfffffe3,
+ 0xfffffe4,
+ 0xfffffe5,
+ 0xfffffe6,
+ 0xfffffe7,
+ 0xfffffe8,
+ 0xffffea,
+ 0x3ffffffc,
+ 0xfffffe9,
+ 0xfffffea,
+ 0x3ffffffd,
+ 0xfffffeb,
+ 0xfffffec,
+ 0xfffffed,
+ 0xfffffee,
+ 0xfffffef,
+ 0xffffff0,
+ 0xffffff1,
+ 0xffffff2,
+ 0x3ffffffe,
+ 0xffffff3,
+ 0xffffff4,
+ 0xffffff5,
+ 0xffffff6,
+ 0xffffff7,
+ 0xffffff8,
+ 0xffffff9,
+ 0xffffffa,
+ 0xffffffb,
+ 0x14,
+ 0x3f8,
+ 0x3f9,
+ 0xffa,
+ 0x1ff9,
+ 0x15,
+ 0xf8,
+ 0x7fa,
+ 0x3fa,
+ 0x3fb,
+ 0xf9,
+ 0x7fb,
+ 0xfa,
+ 0x16,
+ 0x17,
+ 0x18,
+ 0x0,
+ 0x1,
+ 0x2,
+ 0x19,
+ 0x1a,
+ 0x1b,
+ 0x1c,
+ 0x1d,
+ 0x1e,
+ 0x1f,
+ 0x5c,
+ 0xfb,
+ 0x7ffc,
+ 0x20,
+ 0xffb,
+ 0x3fc,
+ 0x1ffa,
+ 0x21,
+ 0x5d,
+ 0x5e,
+ 0x5f,
+ 0x60,
+ 0x61,
+ 0x62,
+ 0x63,
+ 0x64,
+ 0x65,
+ 0x66,
+ 0x67,
+ 0x68,
+ 0x69,
+ 0x6a,
+ 0x6b,
+ 0x6c,
+ 0x6d,
+ 0x6e,
+ 0x6f,
+ 0x70,
+ 0x71,
+ 0x72,
+ 0xfc,
+ 0x73,
+ 0xfd,
+ 0x1ffb,
+ 0x7fff0,
+ 0x1ffc,
+ 0x3ffc,
+ 0x22,
+ 0x7ffd,
+ 0x3,
+ 0x23,
+ 0x4,
+ 0x24,
+ 0x5,
+ 0x25,
+ 0x26,
+ 0x27,
+ 0x6,
+ 0x74,
+ 0x75,
+ 0x28,
+ 0x29,
+ 0x2a,
+ 0x7,
+ 0x2b,
+ 0x76,
+ 0x2c,
+ 0x8,
+ 0x9,
+ 0x2d,
+ 0x77,
+ 0x78,
+ 0x79,
+ 0x7a,
+ 0x7b,
+ 0x7ffe,
+ 0x7fc,
+ 0x3ffd,
+ 0x1ffd,
+ 0xffffffc,
+ 0xfffe6,
+ 0x3fffd2,
+ 0xfffe7,
+ 0xfffe8,
+ 0x3fffd3,
+ 0x3fffd4,
+ 0x3fffd5,
+ 0x7fffd9,
+ 0x3fffd6,
+ 0x7fffda,
+ 0x7fffdb,
+ 0x7fffdc,
+ 0x7fffdd,
+ 0x7fffde,
+ 0xffffeb,
+ 0x7fffdf,
+ 0xffffec,
+ 0xffffed,
+ 0x3fffd7,
+ 0x7fffe0,
+ 0xffffee,
+ 0x7fffe1,
+ 0x7fffe2,
+ 0x7fffe3,
+ 0x7fffe4,
+ 0x1fffdc,
+ 0x3fffd8,
+ 0x7fffe5,
+ 0x3fffd9,
+ 0x7fffe6,
+ 0x7fffe7,
+ 0xffffef,
+ 0x3fffda,
+ 0x1fffdd,
+ 0xfffe9,
+ 0x3fffdb,
+ 0x3fffdc,
+ 0x7fffe8,
+ 0x7fffe9,
+ 0x1fffde,
+ 0x7fffea,
+ 0x3fffdd,
+ 0x3fffde,
+ 0xfffff0,
+ 0x1fffdf,
+ 0x3fffdf,
+ 0x7fffeb,
+ 0x7fffec,
+ 0x1fffe0,
+ 0x1fffe1,
+ 0x3fffe0,
+ 0x1fffe2,
+ 0x7fffed,
+ 0x3fffe1,
+ 0x7fffee,
+ 0x7fffef,
+ 0xfffea,
+ 0x3fffe2,
+ 0x3fffe3,
+ 0x3fffe4,
+ 0x7ffff0,
+ 0x3fffe5,
+ 0x3fffe6,
+ 0x7ffff1,
+ 0x3ffffe0,
+ 0x3ffffe1,
+ 0xfffeb,
+ 0x7fff1,
+ 0x3fffe7,
+ 0x7ffff2,
+ 0x3fffe8,
+ 0x1ffffec,
+ 0x3ffffe2,
+ 0x3ffffe3,
+ 0x3ffffe4,
+ 0x7ffffde,
+ 0x7ffffdf,
+ 0x3ffffe5,
+ 0xfffff1,
+ 0x1ffffed,
+ 0x7fff2,
+ 0x1fffe3,
+ 0x3ffffe6,
+ 0x7ffffe0,
+ 0x7ffffe1,
+ 0x3ffffe7,
+ 0x7ffffe2,
+ 0xfffff2,
+ 0x1fffe4,
+ 0x1fffe5,
+ 0x3ffffe8,
+ 0x3ffffe9,
+ 0xffffffd,
+ 0x7ffffe3,
+ 0x7ffffe4,
+ 0x7ffffe5,
+ 0xfffec,
+ 0xfffff3,
+ 0xfffed,
+ 0x1fffe6,
+ 0x3fffe9,
+ 0x1fffe7,
+ 0x1fffe8,
+ 0x7ffff3,
+ 0x3fffea,
+ 0x3fffeb,
+ 0x1ffffee,
+ 0x1ffffef,
+ 0xfffff4,
+ 0xfffff5,
+ 0x3ffffea,
+ 0x7ffff4,
+ 0x3ffffeb,
+ 0x7ffffe6,
+ 0x3ffffec,
+ 0x3ffffed,
+ 0x7ffffe7,
+ 0x7ffffe8,
+ 0x7ffffe9,
+ 0x7ffffea,
+ 0x7ffffeb,
+ 0xffffffe,
+ 0x7ffffec,
+ 0x7ffffed,
+ 0x7ffffee,
+ 0x7ffffef,
+ 0x7fffff0,
+ 0x3ffffee,
+}
+
+var huffmanCodeLen = [256]uint8{
+ 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28,
+ 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+ 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6,
+ 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10,
+ 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6,
+ 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5,
+ 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28,
+ 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23,
+ 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24,
+ 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23,
+ 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23,
+ 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25,
+ 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27,
+ 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23,
+ 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26,
+}
diff --git a/vendor/golang.org/x/net/http2/http2.go b/vendor/golang.org/x/net/http2/http2.go
new file mode 100644
index 0000000..b6b0f9a
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/http2.go
@@ -0,0 +1,387 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package http2 implements the HTTP/2 protocol.
+//
+// This package is low-level and intended to be used directly by very
+// few people. Most users will use it indirectly through the automatic
+// use by the net/http package (from Go 1.6 and later).
+// For use in earlier Go versions see ConfigureServer. (Transport support
+// requires Go 1.6 or later)
+//
+// See https://http2.github.io/ for more information on HTTP/2.
+//
+// See https://http2.golang.org/ for a test server running this code.
+//
+package http2 // import "golang.org/x/net/http2"
+
+import (
+ "bufio"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+
+ "golang.org/x/net/lex/httplex"
+)
+
+var (
+ VerboseLogs bool
+ logFrameWrites bool
+ logFrameReads bool
+ inTests bool
+)
+
+func init() {
+ e := os.Getenv("GODEBUG")
+ if strings.Contains(e, "http2debug=1") {
+ VerboseLogs = true
+ }
+ if strings.Contains(e, "http2debug=2") {
+ VerboseLogs = true
+ logFrameWrites = true
+ logFrameReads = true
+ }
+}
+
+const (
+ // ClientPreface is the string that must be sent by new
+ // connections from clients.
+ ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
+
+ // SETTINGS_MAX_FRAME_SIZE default
+ // http://http2.github.io/http2-spec/#rfc.section.6.5.2
+ initialMaxFrameSize = 16384
+
+ // NextProtoTLS is the NPN/ALPN protocol negotiated during
+ // HTTP/2's TLS setup.
+ NextProtoTLS = "h2"
+
+ // http://http2.github.io/http2-spec/#SettingValues
+ initialHeaderTableSize = 4096
+
+ initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size
+
+ defaultMaxReadFrameSize = 1 << 20
+)
+
+var (
+ clientPreface = []byte(ClientPreface)
+)
+
+type streamState int
+
+// HTTP/2 stream states.
+//
+// See http://tools.ietf.org/html/rfc7540#section-5.1.
+//
+// For simplicity, the server code merges "reserved (local)" into
+// "half-closed (remote)". This is one less state transition to track.
+// The only downside is that we send PUSH_PROMISEs slightly less
+// liberally than allowable. More discussion here:
+// https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
+//
+// "reserved (remote)" is omitted since the client code does not
+// support server push.
+const (
+ stateIdle streamState = iota
+ stateOpen
+ stateHalfClosedLocal
+ stateHalfClosedRemote
+ stateClosed
+)
+
+var stateName = [...]string{
+ stateIdle: "Idle",
+ stateOpen: "Open",
+ stateHalfClosedLocal: "HalfClosedLocal",
+ stateHalfClosedRemote: "HalfClosedRemote",
+ stateClosed: "Closed",
+}
+
+func (st streamState) String() string {
+ return stateName[st]
+}
+
+// Setting is a setting parameter: which setting it is, and its value.
+type Setting struct {
+ // ID is which setting is being set.
+ // See http://http2.github.io/http2-spec/#SettingValues
+ ID SettingID
+
+ // Val is the value.
+ Val uint32
+}
+
+func (s Setting) String() string {
+ return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
+}
+
+// Valid reports whether the setting is valid.
+func (s Setting) Valid() error {
+ // Limits and error codes from 6.5.2 Defined SETTINGS Parameters
+ switch s.ID {
+ case SettingEnablePush:
+ if s.Val != 1 && s.Val != 0 {
+ return ConnectionError(ErrCodeProtocol)
+ }
+ case SettingInitialWindowSize:
+ if s.Val > 1<<31-1 {
+ return ConnectionError(ErrCodeFlowControl)
+ }
+ case SettingMaxFrameSize:
+ if s.Val < 16384 || s.Val > 1<<24-1 {
+ return ConnectionError(ErrCodeProtocol)
+ }
+ }
+ return nil
+}
+
+// A SettingID is an HTTP/2 setting as defined in
+// http://http2.github.io/http2-spec/#iana-settings
+type SettingID uint16
+
+const (
+ SettingHeaderTableSize SettingID = 0x1
+ SettingEnablePush SettingID = 0x2
+ SettingMaxConcurrentStreams SettingID = 0x3
+ SettingInitialWindowSize SettingID = 0x4
+ SettingMaxFrameSize SettingID = 0x5
+ SettingMaxHeaderListSize SettingID = 0x6
+)
+
+var settingName = map[SettingID]string{
+ SettingHeaderTableSize: "HEADER_TABLE_SIZE",
+ SettingEnablePush: "ENABLE_PUSH",
+ SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
+ SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
+ SettingMaxFrameSize: "MAX_FRAME_SIZE",
+ SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
+}
+
+func (s SettingID) String() string {
+ if v, ok := settingName[s]; ok {
+ return v
+ }
+ return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
+}
+
+var (
+ errInvalidHeaderFieldName = errors.New("http2: invalid header field name")
+ errInvalidHeaderFieldValue = errors.New("http2: invalid header field value")
+)
+
+// validWireHeaderFieldName reports whether v is a valid header field
+// name (key). See httplex.ValidHeaderName for the base rules.
+//
+// Further, http2 says:
+// "Just as in HTTP/1.x, header field names are strings of ASCII
+// characters that are compared in a case-insensitive
+// fashion. However, header field names MUST be converted to
+// lowercase prior to their encoding in HTTP/2. "
+func validWireHeaderFieldName(v string) bool {
+ if len(v) == 0 {
+ return false
+ }
+ for _, r := range v {
+ if !httplex.IsTokenRune(r) {
+ return false
+ }
+ if 'A' <= r && r <= 'Z' {
+ return false
+ }
+ }
+ return true
+}
+
+var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n)
+
+func init() {
+ for i := 100; i <= 999; i++ {
+ if v := http.StatusText(i); v != "" {
+ httpCodeStringCommon[i] = strconv.Itoa(i)
+ }
+ }
+}
+
+func httpCodeString(code int) string {
+ if s, ok := httpCodeStringCommon[code]; ok {
+ return s
+ }
+ return strconv.Itoa(code)
+}
+
+// from pkg io
+type stringWriter interface {
+ WriteString(s string) (n int, err error)
+}
+
+// A gate lets two goroutines coordinate their activities.
+type gate chan struct{}
+
+func (g gate) Done() { g <- struct{}{} }
+func (g gate) Wait() { <-g }
+
+// A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
+type closeWaiter chan struct{}
+
+// Init makes a closeWaiter usable.
+// It exists because so a closeWaiter value can be placed inside a
+// larger struct and have the Mutex and Cond's memory in the same
+// allocation.
+func (cw *closeWaiter) Init() {
+ *cw = make(chan struct{})
+}
+
+// Close marks the closeWaiter as closed and unblocks any waiters.
+func (cw closeWaiter) Close() {
+ close(cw)
+}
+
+// Wait waits for the closeWaiter to become closed.
+func (cw closeWaiter) Wait() {
+ <-cw
+}
+
+// bufferedWriter is a buffered writer that writes to w.
+// Its buffered writer is lazily allocated as needed, to minimize
+// idle memory usage with many connections.
+type bufferedWriter struct {
+ w io.Writer // immutable
+ bw *bufio.Writer // non-nil when data is buffered
+}
+
+func newBufferedWriter(w io.Writer) *bufferedWriter {
+ return &bufferedWriter{w: w}
+}
+
+// bufWriterPoolBufferSize is the size of bufio.Writer's
+// buffers created using bufWriterPool.
+//
+// TODO: pick a less arbitrary value? this is a bit under
+// (3 x typical 1500 byte MTU) at least. Other than that,
+// not much thought went into it.
+const bufWriterPoolBufferSize = 4 << 10
+
+var bufWriterPool = sync.Pool{
+ New: func() interface{} {
+ return bufio.NewWriterSize(nil, bufWriterPoolBufferSize)
+ },
+}
+
+func (w *bufferedWriter) Available() int {
+ if w.bw == nil {
+ return bufWriterPoolBufferSize
+ }
+ return w.bw.Available()
+}
+
+func (w *bufferedWriter) Write(p []byte) (n int, err error) {
+ if w.bw == nil {
+ bw := bufWriterPool.Get().(*bufio.Writer)
+ bw.Reset(w.w)
+ w.bw = bw
+ }
+ return w.bw.Write(p)
+}
+
+func (w *bufferedWriter) Flush() error {
+ bw := w.bw
+ if bw == nil {
+ return nil
+ }
+ err := bw.Flush()
+ bw.Reset(nil)
+ bufWriterPool.Put(bw)
+ w.bw = nil
+ return err
+}
+
+func mustUint31(v int32) uint32 {
+ if v < 0 || v > 2147483647 {
+ panic("out of range")
+ }
+ return uint32(v)
+}
+
+// bodyAllowedForStatus reports whether a given response status code
+// permits a body. See RFC 2616, section 4.4.
+func bodyAllowedForStatus(status int) bool {
+ switch {
+ case status >= 100 && status <= 199:
+ return false
+ case status == 204:
+ return false
+ case status == 304:
+ return false
+ }
+ return true
+}
+
+type httpError struct {
+ msg string
+ timeout bool
+}
+
+func (e *httpError) Error() string { return e.msg }
+func (e *httpError) Timeout() bool { return e.timeout }
+func (e *httpError) Temporary() bool { return true }
+
+var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true}
+
+type connectionStater interface {
+ ConnectionState() tls.ConnectionState
+}
+
+var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }}
+
+type sorter struct {
+ v []string // owned by sorter
+}
+
+func (s *sorter) Len() int { return len(s.v) }
+func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] }
+func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] }
+
+// Keys returns the sorted keys of h.
+//
+// The returned slice is only valid until s used again or returned to
+// its pool.
+func (s *sorter) Keys(h http.Header) []string {
+ keys := s.v[:0]
+ for k := range h {
+ keys = append(keys, k)
+ }
+ s.v = keys
+ sort.Sort(s)
+ return keys
+}
+
+func (s *sorter) SortStrings(ss []string) {
+ // Our sorter works on s.v, which sorter owns, so
+ // stash it away while we sort the user's buffer.
+ save := s.v
+ s.v = ss
+ sort.Sort(s)
+ s.v = save
+}
+
+// validPseudoPath reports whether v is a valid :path pseudo-header
+// value. It must be either:
+//
+// *) a non-empty string starting with '/', but not with with "//",
+// *) the string '*', for OPTIONS requests.
+//
+// For now this is only used a quick check for deciding when to clean
+// up Opaque URLs before sending requests from the Transport.
+// See golang.org/issue/16847
+func validPseudoPath(v string) bool {
+ return (len(v) > 0 && v[0] == '/' && (len(v) == 1 || v[1] != '/')) || v == "*"
+}
diff --git a/vendor/golang.org/x/net/http2/not_go16.go b/vendor/golang.org/x/net/http2/not_go16.go
new file mode 100644
index 0000000..508cebc
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/not_go16.go
@@ -0,0 +1,21 @@
+// Copyright 2015 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 !go1.6
+
+package http2
+
+import (
+ "net/http"
+ "time"
+)
+
+func configureTransport(t1 *http.Transport) (*Transport, error) {
+ return nil, errTransportVersion
+}
+
+func transportExpectContinueTimeout(t1 *http.Transport) time.Duration {
+ return 0
+
+}
diff --git a/vendor/golang.org/x/net/http2/not_go17.go b/vendor/golang.org/x/net/http2/not_go17.go
new file mode 100644
index 0000000..140434a
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/not_go17.go
@@ -0,0 +1,87 @@
+// 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 !go1.7
+
+package http2
+
+import (
+ "crypto/tls"
+ "net"
+ "net/http"
+ "time"
+)
+
+type contextContext interface {
+ Done() <-chan struct{}
+ Err() error
+}
+
+type fakeContext struct{}
+
+func (fakeContext) Done() <-chan struct{} { return nil }
+func (fakeContext) Err() error { panic("should not be called") }
+
+func reqContext(r *http.Request) fakeContext {
+ return fakeContext{}
+}
+
+func setResponseUncompressed(res *http.Response) {
+ // Nothing.
+}
+
+type clientTrace struct{}
+
+func requestTrace(*http.Request) *clientTrace { return nil }
+func traceGotConn(*http.Request, *ClientConn) {}
+func traceFirstResponseByte(*clientTrace) {}
+func traceWroteHeaders(*clientTrace) {}
+func traceWroteRequest(*clientTrace, error) {}
+func traceGot100Continue(trace *clientTrace) {}
+func traceWait100Continue(trace *clientTrace) {}
+
+func nop() {}
+
+func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) {
+ return nil, nop
+}
+
+func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) {
+ return ctx, nop
+}
+
+func requestWithContext(req *http.Request, ctx contextContext) *http.Request {
+ return req
+}
+
+// temporary copy of Go 1.6's private tls.Config.clone:
+func cloneTLSConfig(c *tls.Config) *tls.Config {
+ return &tls.Config{
+ Rand: c.Rand,
+ Time: c.Time,
+ Certificates: c.Certificates,
+ NameToCertificate: c.NameToCertificate,
+ GetCertificate: c.GetCertificate,
+ RootCAs: c.RootCAs,
+ NextProtos: c.NextProtos,
+ ServerName: c.ServerName,
+ ClientAuth: c.ClientAuth,
+ ClientCAs: c.ClientCAs,
+ InsecureSkipVerify: c.InsecureSkipVerify,
+ CipherSuites: c.CipherSuites,
+ PreferServerCipherSuites: c.PreferServerCipherSuites,
+ SessionTicketsDisabled: c.SessionTicketsDisabled,
+ SessionTicketKey: c.SessionTicketKey,
+ ClientSessionCache: c.ClientSessionCache,
+ MinVersion: c.MinVersion,
+ MaxVersion: c.MaxVersion,
+ CurvePreferences: c.CurvePreferences,
+ }
+}
+
+func (cc *ClientConn) Ping(ctx contextContext) error {
+ return cc.ping(ctx)
+}
+
+func (t *Transport) idleConnTimeout() time.Duration { return 0 }
diff --git a/vendor/golang.org/x/net/http2/not_go18.go b/vendor/golang.org/x/net/http2/not_go18.go
new file mode 100644
index 0000000..efbf83c
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/not_go18.go
@@ -0,0 +1,27 @@
+// 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 !go1.8
+
+package http2
+
+import (
+ "io"
+ "net/http"
+)
+
+func configureServer18(h1 *http.Server, h2 *Server) error {
+ // No IdleTimeout to sync prior to Go 1.8.
+ return nil
+}
+
+func shouldLogPanic(panicValue interface{}) bool {
+ return panicValue != nil
+}
+
+func reqGetBody(req *http.Request) func() (io.ReadCloser, error) {
+ return nil
+}
+
+func reqBodyIsNoBody(io.ReadCloser) bool { return false }
diff --git a/vendor/golang.org/x/net/http2/not_go19.go b/vendor/golang.org/x/net/http2/not_go19.go
new file mode 100644
index 0000000..5ae0772
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/not_go19.go
@@ -0,0 +1,16 @@
+// 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 !go1.9
+
+package http2
+
+import (
+ "net/http"
+)
+
+func configureServer19(s *http.Server, conf *Server) error {
+ // not supported prior to go1.9
+ return nil
+}
diff --git a/vendor/golang.org/x/net/http2/pipe.go b/vendor/golang.org/x/net/http2/pipe.go
new file mode 100644
index 0000000..0b9848b
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/pipe.go
@@ -0,0 +1,163 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package http2
+
+import (
+ "errors"
+ "io"
+ "sync"
+)
+
+// pipe is a goroutine-safe io.Reader/io.Writer pair. It's like
+// io.Pipe except there are no PipeReader/PipeWriter halves, and the
+// underlying buffer is an interface. (io.Pipe is always unbuffered)
+type pipe struct {
+ mu sync.Mutex
+ c sync.Cond // c.L lazily initialized to &p.mu
+ b pipeBuffer // nil when done reading
+ err error // read error once empty. non-nil means closed.
+ breakErr error // immediate read error (caller doesn't see rest of b)
+ donec chan struct{} // closed on error
+ readFn func() // optional code to run in Read before error
+}
+
+type pipeBuffer interface {
+ Len() int
+ io.Writer
+ io.Reader
+}
+
+func (p *pipe) Len() int {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.b == nil {
+ return 0
+ }
+ return p.b.Len()
+}
+
+// Read waits until data is available and copies bytes
+// from the buffer into p.
+func (p *pipe) Read(d []byte) (n int, err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.c.L == nil {
+ p.c.L = &p.mu
+ }
+ for {
+ if p.breakErr != nil {
+ return 0, p.breakErr
+ }
+ if p.b.Len() > 0 {
+ return p.b.Read(d)
+ }
+ if p.err != nil {
+ if p.readFn != nil {
+ p.readFn() // e.g. copy trailers
+ p.readFn = nil // not sticky like p.err
+ }
+ p.b = nil
+ return 0, p.err
+ }
+ p.c.Wait()
+ }
+}
+
+var errClosedPipeWrite = errors.New("write on closed buffer")
+
+// Write copies bytes from p into the buffer and wakes a reader.
+// It is an error to write more data than the buffer can hold.
+func (p *pipe) Write(d []byte) (n int, err error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.c.L == nil {
+ p.c.L = &p.mu
+ }
+ defer p.c.Signal()
+ if p.err != nil {
+ return 0, errClosedPipeWrite
+ }
+ if p.breakErr != nil {
+ return len(d), nil // discard when there is no reader
+ }
+ return p.b.Write(d)
+}
+
+// CloseWithError causes the next Read (waking up a current blocked
+// Read if needed) to return the provided err after all data has been
+// read.
+//
+// The error must be non-nil.
+func (p *pipe) CloseWithError(err error) { p.closeWithError(&p.err, err, nil) }
+
+// BreakWithError causes the next Read (waking up a current blocked
+// Read if needed) to return the provided err immediately, without
+// waiting for unread data.
+func (p *pipe) BreakWithError(err error) { p.closeWithError(&p.breakErr, err, nil) }
+
+// closeWithErrorAndCode is like CloseWithError but also sets some code to run
+// in the caller's goroutine before returning the error.
+func (p *pipe) closeWithErrorAndCode(err error, fn func()) { p.closeWithError(&p.err, err, fn) }
+
+func (p *pipe) closeWithError(dst *error, err error, fn func()) {
+ if err == nil {
+ panic("err must be non-nil")
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.c.L == nil {
+ p.c.L = &p.mu
+ }
+ defer p.c.Signal()
+ if *dst != nil {
+ // Already been done.
+ return
+ }
+ p.readFn = fn
+ if dst == &p.breakErr {
+ p.b = nil
+ }
+ *dst = err
+ p.closeDoneLocked()
+}
+
+// requires p.mu be held.
+func (p *pipe) closeDoneLocked() {
+ if p.donec == nil {
+ return
+ }
+ // Close if unclosed. This isn't racy since we always
+ // hold p.mu while closing.
+ select {
+ case <-p.donec:
+ default:
+ close(p.donec)
+ }
+}
+
+// Err returns the error (if any) first set by BreakWithError or CloseWithError.
+func (p *pipe) Err() error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.breakErr != nil {
+ return p.breakErr
+ }
+ return p.err
+}
+
+// Done returns a channel which is closed if and when this pipe is closed
+// with CloseWithError.
+func (p *pipe) Done() <-chan struct{} {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.donec == nil {
+ p.donec = make(chan struct{})
+ if p.err != nil || p.breakErr != nil {
+ // Already hit an error.
+ p.closeDoneLocked()
+ }
+ }
+ return p.donec
+}
diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go
new file mode 100644
index 0000000..7367b31
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/server.go
@@ -0,0 +1,2842 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// TODO: turn off the serve goroutine when idle, so
+// an idle conn only has the readFrames goroutine active. (which could
+// also be optimized probably to pin less memory in crypto/tls). This
+// would involve tracking when the serve goroutine is active (atomic
+// int32 read/CAS probably?) and starting it up when frames arrive,
+// and shutting it down when all handlers exit. the occasional PING
+// packets could use time.AfterFunc to call sc.wakeStartServeLoop()
+// (which is a no-op if already running) and then queue the PING write
+// as normal. The serve loop would then exit in most cases (if no
+// Handlers running) and not be woken up again until the PING packet
+// returns.
+
+// TODO (maybe): add a mechanism for Handlers to going into
+// half-closed-local mode (rw.(io.Closer) test?) but not exit their
+// handler, and continue to be able to read from the
+// Request.Body. This would be a somewhat semantic change from HTTP/1
+// (or at least what we expose in net/http), so I'd probably want to
+// add it there too. For now, this package says that returning from
+// the Handler ServeHTTP function means you're both done reading and
+// done writing, without a way to stop just one or the other.
+
+package http2
+
+import (
+ "bufio"
+ "bytes"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "math"
+ "net"
+ "net/http"
+ "net/textproto"
+ "net/url"
+ "os"
+ "reflect"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/net/http2/hpack"
+)
+
+const (
+ prefaceTimeout = 10 * time.Second
+ firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
+ handlerChunkWriteSize = 4 << 10
+ defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
+)
+
+var (
+ errClientDisconnected = errors.New("client disconnected")
+ errClosedBody = errors.New("body closed by handler")
+ errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
+ errStreamClosed = errors.New("http2: stream closed")
+)
+
+var responseWriterStatePool = sync.Pool{
+ New: func() interface{} {
+ rws := &responseWriterState{}
+ rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
+ return rws
+ },
+}
+
+// Test hooks.
+var (
+ testHookOnConn func()
+ testHookGetServerConn func(*serverConn)
+ testHookOnPanicMu *sync.Mutex // nil except in tests
+ testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool)
+)
+
+// Server is an HTTP/2 server.
+type Server struct {
+ // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
+ // which may run at a time over all connections.
+ // Negative or zero no limit.
+ // TODO: implement
+ MaxHandlers int
+
+ // MaxConcurrentStreams optionally specifies the number of
+ // concurrent streams that each client may have open at a
+ // time. This is unrelated to the number of http.Handler goroutines
+ // which may be active globally, which is MaxHandlers.
+ // If zero, MaxConcurrentStreams defaults to at least 100, per
+ // the HTTP/2 spec's recommendations.
+ MaxConcurrentStreams uint32
+
+ // MaxReadFrameSize optionally specifies the largest frame
+ // this server is willing to read. A valid value is between
+ // 16k and 16M, inclusive. If zero or otherwise invalid, a
+ // default value is used.
+ MaxReadFrameSize uint32
+
+ // PermitProhibitedCipherSuites, if true, permits the use of
+ // cipher suites prohibited by the HTTP/2 spec.
+ PermitProhibitedCipherSuites bool
+
+ // IdleTimeout specifies how long until idle clients should be
+ // closed with a GOAWAY frame. PING frames are not considered
+ // activity for the purposes of IdleTimeout.
+ IdleTimeout time.Duration
+
+ // MaxUploadBufferPerConnection is the size of the initial flow
+ // control window for each connections. The HTTP/2 spec does not
+ // allow this to be smaller than 65535 or larger than 2^32-1.
+ // If the value is outside this range, a default value will be
+ // used instead.
+ MaxUploadBufferPerConnection int32
+
+ // MaxUploadBufferPerStream is the size of the initial flow control
+ // window for each stream. The HTTP/2 spec does not allow this to
+ // be larger than 2^32-1. If the value is zero or larger than the
+ // maximum, a default value will be used instead.
+ MaxUploadBufferPerStream int32
+
+ // NewWriteScheduler constructs a write scheduler for a connection.
+ // If nil, a default scheduler is chosen.
+ NewWriteScheduler func() WriteScheduler
+
+ // Internal state. This is a pointer (rather than embedded directly)
+ // so that we don't embed a Mutex in this struct, which will make the
+ // struct non-copyable, which might break some callers.
+ state *serverInternalState
+}
+
+func (s *Server) initialConnRecvWindowSize() int32 {
+ if s.MaxUploadBufferPerConnection > initialWindowSize {
+ return s.MaxUploadBufferPerConnection
+ }
+ return 1 << 20
+}
+
+func (s *Server) initialStreamRecvWindowSize() int32 {
+ if s.MaxUploadBufferPerStream > 0 {
+ return s.MaxUploadBufferPerStream
+ }
+ return 1 << 20
+}
+
+func (s *Server) maxReadFrameSize() uint32 {
+ if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
+ return v
+ }
+ return defaultMaxReadFrameSize
+}
+
+func (s *Server) maxConcurrentStreams() uint32 {
+ if v := s.MaxConcurrentStreams; v > 0 {
+ return v
+ }
+ return defaultMaxStreams
+}
+
+type serverInternalState struct {
+ mu sync.Mutex
+ activeConns map[*serverConn]struct{}
+}
+
+func (s *serverInternalState) registerConn(sc *serverConn) {
+ if s == nil {
+ return // if the Server was used without calling ConfigureServer
+ }
+ s.mu.Lock()
+ s.activeConns[sc] = struct{}{}
+ s.mu.Unlock()
+}
+
+func (s *serverInternalState) unregisterConn(sc *serverConn) {
+ if s == nil {
+ return // if the Server was used without calling ConfigureServer
+ }
+ s.mu.Lock()
+ delete(s.activeConns, sc)
+ s.mu.Unlock()
+}
+
+func (s *serverInternalState) startGracefulShutdown() {
+ if s == nil {
+ return // if the Server was used without calling ConfigureServer
+ }
+ s.mu.Lock()
+ for sc := range s.activeConns {
+ sc.startGracefulShutdown()
+ }
+ s.mu.Unlock()
+}
+
+// ConfigureServer adds HTTP/2 support to a net/http Server.
+//
+// The configuration conf may be nil.
+//
+// ConfigureServer must be called before s begins serving.
+func ConfigureServer(s *http.Server, conf *Server) error {
+ if s == nil {
+ panic("nil *http.Server")
+ }
+ if conf == nil {
+ conf = new(Server)
+ }
+ conf.state = &serverInternalState{activeConns: make(map[*serverConn]struct{})}
+ if err := configureServer18(s, conf); err != nil {
+ return err
+ }
+ if err := configureServer19(s, conf); err != nil {
+ return err
+ }
+
+ if s.TLSConfig == nil {
+ s.TLSConfig = new(tls.Config)
+ } else if s.TLSConfig.CipherSuites != nil {
+ // If they already provided a CipherSuite list, return
+ // an error if it has a bad order or is missing
+ // ECDHE_RSA_WITH_AES_128_GCM_SHA256.
+ const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
+ haveRequired := false
+ sawBad := false
+ for i, cs := range s.TLSConfig.CipherSuites {
+ if cs == requiredCipher {
+ haveRequired = true
+ }
+ if isBadCipher(cs) {
+ sawBad = true
+ } else if sawBad {
+ return fmt.Errorf("http2: TLSConfig.CipherSuites index %d contains an HTTP/2-approved cipher suite (%#04x), but it comes after unapproved cipher suites. With this configuration, clients that don't support previous, approved cipher suites may be given an unapproved one and reject the connection.", i, cs)
+ }
+ }
+ if !haveRequired {
+ return fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
+ }
+ }
+
+ // Note: not setting MinVersion to tls.VersionTLS12,
+ // as we don't want to interfere with HTTP/1.1 traffic
+ // on the user's server. We enforce TLS 1.2 later once
+ // we accept a connection. Ideally this should be done
+ // during next-proto selection, but using TLS <1.2 with
+ // HTTP/2 is still the client's bug.
+
+ s.TLSConfig.PreferServerCipherSuites = true
+
+ haveNPN := false
+ for _, p := range s.TLSConfig.NextProtos {
+ if p == NextProtoTLS {
+ haveNPN = true
+ break
+ }
+ }
+ if !haveNPN {
+ s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
+ }
+
+ if s.TLSNextProto == nil {
+ s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
+ }
+ protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
+ if testHookOnConn != nil {
+ testHookOnConn()
+ }
+ conf.ServeConn(c, &ServeConnOpts{
+ Handler: h,
+ BaseConfig: hs,
+ })
+ }
+ s.TLSNextProto[NextProtoTLS] = protoHandler
+ return nil
+}
+
+// ServeConnOpts are options for the Server.ServeConn method.
+type ServeConnOpts struct {
+ // BaseConfig optionally sets the base configuration
+ // for values. If nil, defaults are used.
+ BaseConfig *http.Server
+
+ // Handler specifies which handler to use for processing
+ // requests. If nil, BaseConfig.Handler is used. If BaseConfig
+ // or BaseConfig.Handler is nil, http.DefaultServeMux is used.
+ Handler http.Handler
+}
+
+func (o *ServeConnOpts) baseConfig() *http.Server {
+ if o != nil && o.BaseConfig != nil {
+ return o.BaseConfig
+ }
+ return new(http.Server)
+}
+
+func (o *ServeConnOpts) handler() http.Handler {
+ if o != nil {
+ if o.Handler != nil {
+ return o.Handler
+ }
+ if o.BaseConfig != nil && o.BaseConfig.Handler != nil {
+ return o.BaseConfig.Handler
+ }
+ }
+ return http.DefaultServeMux
+}
+
+// ServeConn serves HTTP/2 requests on the provided connection and
+// blocks until the connection is no longer readable.
+//
+// ServeConn starts speaking HTTP/2 assuming that c has not had any
+// reads or writes. It writes its initial settings frame and expects
+// to be able to read the preface and settings frame from the
+// client. If c has a ConnectionState method like a *tls.Conn, the
+// ConnectionState is used to verify the TLS ciphersuite and to set
+// the Request.TLS field in Handlers.
+//
+// ServeConn does not support h2c by itself. Any h2c support must be
+// implemented in terms of providing a suitably-behaving net.Conn.
+//
+// The opts parameter is optional. If nil, default values are used.
+func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
+ baseCtx, cancel := serverConnBaseContext(c, opts)
+ defer cancel()
+
+ sc := &serverConn{
+ srv: s,
+ hs: opts.baseConfig(),
+ conn: c,
+ baseCtx: baseCtx,
+ remoteAddrStr: c.RemoteAddr().String(),
+ bw: newBufferedWriter(c),
+ handler: opts.handler(),
+ streams: make(map[uint32]*stream),
+ readFrameCh: make(chan readFrameResult),
+ wantWriteFrameCh: make(chan FrameWriteRequest, 8),
+ serveMsgCh: make(chan interface{}, 8),
+ wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
+ bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
+ doneServing: make(chan struct{}),
+ clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value"
+ advMaxStreams: s.maxConcurrentStreams(),
+ initialStreamSendWindowSize: initialWindowSize,
+ maxFrameSize: initialMaxFrameSize,
+ headerTableSize: initialHeaderTableSize,
+ serveG: newGoroutineLock(),
+ pushEnabled: true,
+ }
+
+ s.state.registerConn(sc)
+ defer s.state.unregisterConn(sc)
+
+ // The net/http package sets the write deadline from the
+ // http.Server.WriteTimeout during the TLS handshake, but then
+ // passes the connection off to us with the deadline already set.
+ // Write deadlines are set per stream in serverConn.newStream.
+ // Disarm the net.Conn write deadline here.
+ if sc.hs.WriteTimeout != 0 {
+ sc.conn.SetWriteDeadline(time.Time{})
+ }
+
+ if s.NewWriteScheduler != nil {
+ sc.writeSched = s.NewWriteScheduler()
+ } else {
+ sc.writeSched = NewRandomWriteScheduler()
+ }
+
+ // These start at the RFC-specified defaults. If there is a higher
+ // configured value for inflow, that will be updated when we send a
+ // WINDOW_UPDATE shortly after sending SETTINGS.
+ sc.flow.add(initialWindowSize)
+ sc.inflow.add(initialWindowSize)
+ sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
+
+ fr := NewFramer(sc.bw, c)
+ fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
+ fr.MaxHeaderListSize = sc.maxHeaderListSize()
+ fr.SetMaxReadFrameSize(s.maxReadFrameSize())
+ sc.framer = fr
+
+ if tc, ok := c.(connectionStater); ok {
+ sc.tlsState = new(tls.ConnectionState)
+ *sc.tlsState = tc.ConnectionState()
+ // 9.2 Use of TLS Features
+ // An implementation of HTTP/2 over TLS MUST use TLS
+ // 1.2 or higher with the restrictions on feature set
+ // and cipher suite described in this section. Due to
+ // implementation limitations, it might not be
+ // possible to fail TLS negotiation. An endpoint MUST
+ // immediately terminate an HTTP/2 connection that
+ // does not meet the TLS requirements described in
+ // this section with a connection error (Section
+ // 5.4.1) of type INADEQUATE_SECURITY.
+ if sc.tlsState.Version < tls.VersionTLS12 {
+ sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
+ return
+ }
+
+ if sc.tlsState.ServerName == "" {
+ // Client must use SNI, but we don't enforce that anymore,
+ // since it was causing problems when connecting to bare IP
+ // addresses during development.
+ //
+ // TODO: optionally enforce? Or enforce at the time we receive
+ // a new request, and verify the the ServerName matches the :authority?
+ // But that precludes proxy situations, perhaps.
+ //
+ // So for now, do nothing here again.
+ }
+
+ if !s.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
+ // "Endpoints MAY choose to generate a connection error
+ // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
+ // the prohibited cipher suites are negotiated."
+ //
+ // We choose that. In my opinion, the spec is weak
+ // here. It also says both parties must support at least
+ // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
+ // excuses here. If we really must, we could allow an
+ // "AllowInsecureWeakCiphers" option on the server later.
+ // Let's see how it plays out first.
+ sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
+ return
+ }
+ }
+
+ if hook := testHookGetServerConn; hook != nil {
+ hook(sc)
+ }
+ sc.serve()
+}
+
+func (sc *serverConn) rejectConn(err ErrCode, debug string) {
+ sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
+ // ignoring errors. hanging up anyway.
+ sc.framer.WriteGoAway(0, err, []byte(debug))
+ sc.bw.Flush()
+ sc.conn.Close()
+}
+
+type serverConn struct {
+ // Immutable:
+ srv *Server
+ hs *http.Server
+ conn net.Conn
+ bw *bufferedWriter // writing to conn
+ handler http.Handler
+ baseCtx contextContext
+ framer *Framer
+ doneServing chan struct{} // closed when serverConn.serve ends
+ readFrameCh chan readFrameResult // written by serverConn.readFrames
+ wantWriteFrameCh chan FrameWriteRequest // from handlers -> serve
+ wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
+ bodyReadCh chan bodyReadMsg // from handlers -> serve
+ serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop
+ flow flow // conn-wide (not stream-specific) outbound flow control
+ inflow flow // conn-wide inbound flow control
+ tlsState *tls.ConnectionState // shared by all handlers, like net/http
+ remoteAddrStr string
+ writeSched WriteScheduler
+
+ // Everything following is owned by the serve loop; use serveG.check():
+ serveG goroutineLock // used to verify funcs are on serve()
+ pushEnabled bool
+ sawFirstSettings bool // got the initial SETTINGS frame after the preface
+ needToSendSettingsAck bool
+ unackedSettings int // how many SETTINGS have we sent without ACKs?
+ clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
+ advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
+ curClientStreams uint32 // number of open streams initiated by the client
+ curPushedStreams uint32 // number of open streams initiated by server push
+ maxClientStreamID uint32 // max ever seen from client (odd), or 0 if there have been no client requests
+ maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes
+ streams map[uint32]*stream
+ initialStreamSendWindowSize int32
+ maxFrameSize int32
+ headerTableSize uint32
+ peerMaxHeaderListSize uint32 // zero means unknown (default)
+ canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
+ writingFrame bool // started writing a frame (on serve goroutine or separate)
+ writingFrameAsync bool // started a frame on its own goroutine but haven't heard back on wroteFrameCh
+ needsFrameFlush bool // last frame write wasn't a flush
+ inGoAway bool // we've started to or sent GOAWAY
+ inFrameScheduleLoop bool // whether we're in the scheduleFrameWrite loop
+ needToSendGoAway bool // we need to schedule a GOAWAY frame write
+ goAwayCode ErrCode
+ shutdownTimer *time.Timer // nil until used
+ idleTimer *time.Timer // nil if unused
+
+ // Owned by the writeFrameAsync goroutine:
+ headerWriteBuf bytes.Buffer
+ hpackEncoder *hpack.Encoder
+
+ // Used by startGracefulShutdown.
+ shutdownOnce sync.Once
+}
+
+func (sc *serverConn) maxHeaderListSize() uint32 {
+ n := sc.hs.MaxHeaderBytes
+ if n <= 0 {
+ n = http.DefaultMaxHeaderBytes
+ }
+ // http2's count is in a slightly different unit and includes 32 bytes per pair.
+ // So, take the net/http.Server value and pad it up a bit, assuming 10 headers.
+ const perFieldOverhead = 32 // per http2 spec
+ const typicalHeaders = 10 // conservative
+ return uint32(n + typicalHeaders*perFieldOverhead)
+}
+
+func (sc *serverConn) curOpenStreams() uint32 {
+ sc.serveG.check()
+ return sc.curClientStreams + sc.curPushedStreams
+}
+
+// stream represents a stream. This is the minimal metadata needed by
+// the serve goroutine. Most of the actual stream state is owned by
+// the http.Handler's goroutine in the responseWriter. Because the
+// responseWriter's responseWriterState is recycled at the end of a
+// handler, this struct intentionally has no pointer to the
+// *responseWriter{,State} itself, as the Handler ending nils out the
+// responseWriter's state field.
+type stream struct {
+ // immutable:
+ sc *serverConn
+ id uint32
+ body *pipe // non-nil if expecting DATA frames
+ cw closeWaiter // closed wait stream transitions to closed state
+ ctx contextContext
+ cancelCtx func()
+
+ // owned by serverConn's serve loop:
+ bodyBytes int64 // body bytes seen so far
+ declBodyBytes int64 // or -1 if undeclared
+ flow flow // limits writing from Handler to client
+ inflow flow // what the client is allowed to POST/etc to us
+ parent *stream // or nil
+ numTrailerValues int64
+ weight uint8
+ state streamState
+ resetQueued bool // RST_STREAM queued for write; set by sc.resetStream
+ gotTrailerHeader bool // HEADER frame for trailers was seen
+ wroteHeaders bool // whether we wrote headers (not status 100)
+ writeDeadline *time.Timer // nil if unused
+
+ trailer http.Header // accumulated trailers
+ reqTrailer http.Header // handler's Request.Trailer
+}
+
+func (sc *serverConn) Framer() *Framer { return sc.framer }
+func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
+func (sc *serverConn) Flush() error { return sc.bw.Flush() }
+func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
+ return sc.hpackEncoder, &sc.headerWriteBuf
+}
+
+func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
+ sc.serveG.check()
+ // http://tools.ietf.org/html/rfc7540#section-5.1
+ if st, ok := sc.streams[streamID]; ok {
+ return st.state, st
+ }
+ // "The first use of a new stream identifier implicitly closes all
+ // streams in the "idle" state that might have been initiated by
+ // that peer with a lower-valued stream identifier. For example, if
+ // a client sends a HEADERS frame on stream 7 without ever sending a
+ // frame on stream 5, then stream 5 transitions to the "closed"
+ // state when the first frame for stream 7 is sent or received."
+ if streamID%2 == 1 {
+ if streamID <= sc.maxClientStreamID {
+ return stateClosed, nil
+ }
+ } else {
+ if streamID <= sc.maxPushPromiseID {
+ return stateClosed, nil
+ }
+ }
+ return stateIdle, nil
+}
+
+// setConnState calls the net/http ConnState hook for this connection, if configured.
+// Note that the net/http package does StateNew and StateClosed for us.
+// There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
+func (sc *serverConn) setConnState(state http.ConnState) {
+ if sc.hs.ConnState != nil {
+ sc.hs.ConnState(sc.conn, state)
+ }
+}
+
+func (sc *serverConn) vlogf(format string, args ...interface{}) {
+ if VerboseLogs {
+ sc.logf(format, args...)
+ }
+}
+
+func (sc *serverConn) logf(format string, args ...interface{}) {
+ if lg := sc.hs.ErrorLog; lg != nil {
+ lg.Printf(format, args...)
+ } else {
+ log.Printf(format, args...)
+ }
+}
+
+// errno returns v's underlying uintptr, else 0.
+//
+// TODO: remove this helper function once http2 can use build
+// tags. See comment in isClosedConnError.
+func errno(v error) uintptr {
+ if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
+ return uintptr(rv.Uint())
+ }
+ return 0
+}
+
+// isClosedConnError reports whether err is an error from use of a closed
+// network connection.
+func isClosedConnError(err error) bool {
+ if err == nil {
+ return false
+ }
+
+ // TODO: remove this string search and be more like the Windows
+ // case below. That might involve modifying the standard library
+ // to return better error types.
+ str := err.Error()
+ if strings.Contains(str, "use of closed network connection") {
+ return true
+ }
+
+ // TODO(bradfitz): x/tools/cmd/bundle doesn't really support
+ // build tags, so I can't make an http2_windows.go file with
+ // Windows-specific stuff. Fix that and move this, once we
+ // have a way to bundle this into std's net/http somehow.
+ if runtime.GOOS == "windows" {
+ if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
+ if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
+ const WSAECONNABORTED = 10053
+ const WSAECONNRESET = 10054
+ if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
+ return true
+ }
+ }
+ }
+ }
+ return false
+}
+
+func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
+ if err == nil {
+ return
+ }
+ if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) {
+ // Boring, expected errors.
+ sc.vlogf(format, args...)
+ } else {
+ sc.logf(format, args...)
+ }
+}
+
+func (sc *serverConn) canonicalHeader(v string) string {
+ sc.serveG.check()
+ cv, ok := commonCanonHeader[v]
+ if ok {
+ return cv
+ }
+ cv, ok = sc.canonHeader[v]
+ if ok {
+ return cv
+ }
+ if sc.canonHeader == nil {
+ sc.canonHeader = make(map[string]string)
+ }
+ cv = http.CanonicalHeaderKey(v)
+ sc.canonHeader[v] = cv
+ return cv
+}
+
+type readFrameResult struct {
+ f Frame // valid until readMore is called
+ err error
+
+ // readMore should be called once the consumer no longer needs or
+ // retains f. After readMore, f is invalid and more frames can be
+ // read.
+ readMore func()
+}
+
+// readFrames is the loop that reads incoming frames.
+// It takes care to only read one frame at a time, blocking until the
+// consumer is done with the frame.
+// It's run on its own goroutine.
+func (sc *serverConn) readFrames() {
+ gate := make(gate)
+ gateDone := gate.Done
+ for {
+ f, err := sc.framer.ReadFrame()
+ select {
+ case sc.readFrameCh <- readFrameResult{f, err, gateDone}:
+ case <-sc.doneServing:
+ return
+ }
+ select {
+ case <-gate:
+ case <-sc.doneServing:
+ return
+ }
+ if terminalReadFrameError(err) {
+ return
+ }
+ }
+}
+
+// frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
+type frameWriteResult struct {
+ wr FrameWriteRequest // what was written (or attempted)
+ err error // result of the writeFrame call
+}
+
+// writeFrameAsync runs in its own goroutine and writes a single frame
+// and then reports when it's done.
+// At most one goroutine can be running writeFrameAsync at a time per
+// serverConn.
+func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest) {
+ err := wr.write.writeFrame(sc)
+ sc.wroteFrameCh <- frameWriteResult{wr, err}
+}
+
+func (sc *serverConn) closeAllStreamsOnConnClose() {
+ sc.serveG.check()
+ for _, st := range sc.streams {
+ sc.closeStream(st, errClientDisconnected)
+ }
+}
+
+func (sc *serverConn) stopShutdownTimer() {
+ sc.serveG.check()
+ if t := sc.shutdownTimer; t != nil {
+ t.Stop()
+ }
+}
+
+func (sc *serverConn) notePanic() {
+ // Note: this is for serverConn.serve panicking, not http.Handler code.
+ if testHookOnPanicMu != nil {
+ testHookOnPanicMu.Lock()
+ defer testHookOnPanicMu.Unlock()
+ }
+ if testHookOnPanic != nil {
+ if e := recover(); e != nil {
+ if testHookOnPanic(sc, e) {
+ panic(e)
+ }
+ }
+ }
+}
+
+func (sc *serverConn) serve() {
+ sc.serveG.check()
+ defer sc.notePanic()
+ defer sc.conn.Close()
+ defer sc.closeAllStreamsOnConnClose()
+ defer sc.stopShutdownTimer()
+ defer close(sc.doneServing) // unblocks handlers trying to send
+
+ if VerboseLogs {
+ sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
+ }
+
+ sc.writeFrame(FrameWriteRequest{
+ write: writeSettings{
+ {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
+ {SettingMaxConcurrentStreams, sc.advMaxStreams},
+ {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
+ {SettingInitialWindowSize, uint32(sc.srv.initialStreamRecvWindowSize())},
+ },
+ })
+ sc.unackedSettings++
+
+ // Each connection starts with intialWindowSize inflow tokens.
+ // If a higher value is configured, we add more tokens.
+ if diff := sc.srv.initialConnRecvWindowSize() - initialWindowSize; diff > 0 {
+ sc.sendWindowUpdate(nil, int(diff))
+ }
+
+ if err := sc.readPreface(); err != nil {
+ sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
+ return
+ }
+ // Now that we've got the preface, get us out of the
+ // "StateNew" state. We can't go directly to idle, though.
+ // Active means we read some data and anticipate a request. We'll
+ // do another Active when we get a HEADERS frame.
+ sc.setConnState(http.StateActive)
+ sc.setConnState(http.StateIdle)
+
+ if sc.srv.IdleTimeout != 0 {
+ sc.idleTimer = time.AfterFunc(sc.srv.IdleTimeout, sc.onIdleTimer)
+ defer sc.idleTimer.Stop()
+ }
+
+ go sc.readFrames() // closed by defer sc.conn.Close above
+
+ settingsTimer := time.AfterFunc(firstSettingsTimeout, sc.onSettingsTimer)
+ defer settingsTimer.Stop()
+
+ loopNum := 0
+ for {
+ loopNum++
+ select {
+ case wr := <-sc.wantWriteFrameCh:
+ if se, ok := wr.write.(StreamError); ok {
+ sc.resetStream(se)
+ break
+ }
+ sc.writeFrame(wr)
+ case res := <-sc.wroteFrameCh:
+ sc.wroteFrame(res)
+ case res := <-sc.readFrameCh:
+ if !sc.processFrameFromReader(res) {
+ return
+ }
+ res.readMore()
+ if settingsTimer != nil {
+ settingsTimer.Stop()
+ settingsTimer = nil
+ }
+ case m := <-sc.bodyReadCh:
+ sc.noteBodyRead(m.st, m.n)
+ case msg := <-sc.serveMsgCh:
+ switch v := msg.(type) {
+ case func(int):
+ v(loopNum) // for testing
+ case *serverMessage:
+ switch v {
+ case settingsTimerMsg:
+ sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
+ return
+ case idleTimerMsg:
+ sc.vlogf("connection is idle")
+ sc.goAway(ErrCodeNo)
+ case shutdownTimerMsg:
+ sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
+ return
+ case gracefulShutdownMsg:
+ sc.startGracefulShutdownInternal()
+ default:
+ panic("unknown timer")
+ }
+ case *startPushRequest:
+ sc.startPush(v)
+ default:
+ panic(fmt.Sprintf("unexpected type %T", v))
+ }
+ }
+
+ if sc.inGoAway && sc.curOpenStreams() == 0 && !sc.needToSendGoAway && !sc.writingFrame {
+ return
+ }
+ }
+}
+
+func (sc *serverConn) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{}) {
+ select {
+ case <-sc.doneServing:
+ case <-sharedCh:
+ close(privateCh)
+ }
+}
+
+type serverMessage int
+
+// Message values sent to serveMsgCh.
+var (
+ settingsTimerMsg = new(serverMessage)
+ idleTimerMsg = new(serverMessage)
+ shutdownTimerMsg = new(serverMessage)
+ gracefulShutdownMsg = new(serverMessage)
+)
+
+func (sc *serverConn) onSettingsTimer() { sc.sendServeMsg(settingsTimerMsg) }
+func (sc *serverConn) onIdleTimer() { sc.sendServeMsg(idleTimerMsg) }
+func (sc *serverConn) onShutdownTimer() { sc.sendServeMsg(shutdownTimerMsg) }
+
+func (sc *serverConn) sendServeMsg(msg interface{}) {
+ sc.serveG.checkNotOn() // NOT
+ select {
+ case sc.serveMsgCh <- msg:
+ case <-sc.doneServing:
+ }
+}
+
+// readPreface reads the ClientPreface greeting from the peer
+// or returns an error on timeout or an invalid greeting.
+func (sc *serverConn) readPreface() error {
+ errc := make(chan error, 1)
+ go func() {
+ // Read the client preface
+ buf := make([]byte, len(ClientPreface))
+ if _, err := io.ReadFull(sc.conn, buf); err != nil {
+ errc <- err
+ } else if !bytes.Equal(buf, clientPreface) {
+ errc <- fmt.Errorf("bogus greeting %q", buf)
+ } else {
+ errc <- nil
+ }
+ }()
+ timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
+ defer timer.Stop()
+ select {
+ case <-timer.C:
+ return errors.New("timeout waiting for client preface")
+ case err := <-errc:
+ if err == nil {
+ if VerboseLogs {
+ sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
+ }
+ }
+ return err
+ }
+}
+
+var errChanPool = sync.Pool{
+ New: func() interface{} { return make(chan error, 1) },
+}
+
+var writeDataPool = sync.Pool{
+ New: func() interface{} { return new(writeData) },
+}
+
+// writeDataFromHandler writes DATA response frames from a handler on
+// the given stream.
+func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
+ ch := errChanPool.Get().(chan error)
+ writeArg := writeDataPool.Get().(*writeData)
+ *writeArg = writeData{stream.id, data, endStream}
+ err := sc.writeFrameFromHandler(FrameWriteRequest{
+ write: writeArg,
+ stream: stream,
+ done: ch,
+ })
+ if err != nil {
+ return err
+ }
+ var frameWriteDone bool // the frame write is done (successfully or not)
+ select {
+ case err = <-ch:
+ frameWriteDone = true
+ case <-sc.doneServing:
+ return errClientDisconnected
+ case <-stream.cw:
+ // If both ch and stream.cw were ready (as might
+ // happen on the final Write after an http.Handler
+ // ends), prefer the write result. Otherwise this
+ // might just be us successfully closing the stream.
+ // The writeFrameAsync and serve goroutines guarantee
+ // that the ch send will happen before the stream.cw
+ // close.
+ select {
+ case err = <-ch:
+ frameWriteDone = true
+ default:
+ return errStreamClosed
+ }
+ }
+ errChanPool.Put(ch)
+ if frameWriteDone {
+ writeDataPool.Put(writeArg)
+ }
+ return err
+}
+
+// writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
+// if the connection has gone away.
+//
+// This must not be run from the serve goroutine itself, else it might
+// deadlock writing to sc.wantWriteFrameCh (which is only mildly
+// buffered and is read by serve itself). If you're on the serve
+// goroutine, call writeFrame instead.
+func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error {
+ sc.serveG.checkNotOn() // NOT
+ select {
+ case sc.wantWriteFrameCh <- wr:
+ return nil
+ case <-sc.doneServing:
+ // Serve loop is gone.
+ // Client has closed their connection to the server.
+ return errClientDisconnected
+ }
+}
+
+// writeFrame schedules a frame to write and sends it if there's nothing
+// already being written.
+//
+// There is no pushback here (the serve goroutine never blocks). It's
+// the http.Handlers that block, waiting for their previous frames to
+// make it onto the wire
+//
+// If you're not on the serve goroutine, use writeFrameFromHandler instead.
+func (sc *serverConn) writeFrame(wr FrameWriteRequest) {
+ sc.serveG.check()
+
+ // If true, wr will not be written and wr.done will not be signaled.
+ var ignoreWrite bool
+
+ // We are not allowed to write frames on closed streams. RFC 7540 Section
+ // 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on
+ // a closed stream." Our server never sends PRIORITY, so that exception
+ // does not apply.
+ //
+ // The serverConn might close an open stream while the stream's handler
+ // is still running. For example, the server might close a stream when it
+ // receives bad data from the client. If this happens, the handler might
+ // attempt to write a frame after the stream has been closed (since the
+ // handler hasn't yet been notified of the close). In this case, we simply
+ // ignore the frame. The handler will notice that the stream is closed when
+ // it waits for the frame to be written.
+ //
+ // As an exception to this rule, we allow sending RST_STREAM after close.
+ // This allows us to immediately reject new streams without tracking any
+ // state for those streams (except for the queued RST_STREAM frame). This
+ // may result in duplicate RST_STREAMs in some cases, but the client should
+ // ignore those.
+ if wr.StreamID() != 0 {
+ _, isReset := wr.write.(StreamError)
+ if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset {
+ ignoreWrite = true
+ }
+ }
+
+ // Don't send a 100-continue response if we've already sent headers.
+ // See golang.org/issue/14030.
+ switch wr.write.(type) {
+ case *writeResHeaders:
+ wr.stream.wroteHeaders = true
+ case write100ContinueHeadersFrame:
+ if wr.stream.wroteHeaders {
+ // We do not need to notify wr.done because this frame is
+ // never written with wr.done != nil.
+ if wr.done != nil {
+ panic("wr.done != nil for write100ContinueHeadersFrame")
+ }
+ ignoreWrite = true
+ }
+ }
+
+ if !ignoreWrite {
+ sc.writeSched.Push(wr)
+ }
+ sc.scheduleFrameWrite()
+}
+
+// startFrameWrite starts a goroutine to write wr (in a separate
+// goroutine since that might block on the network), and updates the
+// serve goroutine's state about the world, updated from info in wr.
+func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) {
+ sc.serveG.check()
+ if sc.writingFrame {
+ panic("internal error: can only be writing one frame at a time")
+ }
+
+ st := wr.stream
+ if st != nil {
+ switch st.state {
+ case stateHalfClosedLocal:
+ switch wr.write.(type) {
+ case StreamError, handlerPanicRST, writeWindowUpdate:
+ // RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE
+ // in this state. (We never send PRIORITY from the server, so that is not checked.)
+ default:
+ panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
+ }
+ case stateClosed:
+ panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
+ }
+ }
+ if wpp, ok := wr.write.(*writePushPromise); ok {
+ var err error
+ wpp.promisedID, err = wpp.allocatePromisedID()
+ if err != nil {
+ sc.writingFrameAsync = false
+ wr.replyToWriter(err)
+ return
+ }
+ }
+
+ sc.writingFrame = true
+ sc.needsFrameFlush = true
+ if wr.write.staysWithinBuffer(sc.bw.Available()) {
+ sc.writingFrameAsync = false
+ err := wr.write.writeFrame(sc)
+ sc.wroteFrame(frameWriteResult{wr, err})
+ } else {
+ sc.writingFrameAsync = true
+ go sc.writeFrameAsync(wr)
+ }
+}
+
+// errHandlerPanicked is the error given to any callers blocked in a read from
+// Request.Body when the main goroutine panics. Since most handlers read in the
+// the main ServeHTTP goroutine, this will show up rarely.
+var errHandlerPanicked = errors.New("http2: handler panicked")
+
+// wroteFrame is called on the serve goroutine with the result of
+// whatever happened on writeFrameAsync.
+func (sc *serverConn) wroteFrame(res frameWriteResult) {
+ sc.serveG.check()
+ if !sc.writingFrame {
+ panic("internal error: expected to be already writing a frame")
+ }
+ sc.writingFrame = false
+ sc.writingFrameAsync = false
+
+ wr := res.wr
+
+ if writeEndsStream(wr.write) {
+ st := wr.stream
+ if st == nil {
+ panic("internal error: expecting non-nil stream")
+ }
+ switch st.state {
+ case stateOpen:
+ // Here we would go to stateHalfClosedLocal in
+ // theory, but since our handler is done and
+ // the net/http package provides no mechanism
+ // for closing a ResponseWriter while still
+ // reading data (see possible TODO at top of
+ // this file), we go into closed state here
+ // anyway, after telling the peer we're
+ // hanging up on them. We'll transition to
+ // stateClosed after the RST_STREAM frame is
+ // written.
+ st.state = stateHalfClosedLocal
+ // Section 8.1: a server MAY request that the client abort
+ // transmission of a request without error by sending a
+ // RST_STREAM with an error code of NO_ERROR after sending
+ // a complete response.
+ sc.resetStream(streamError(st.id, ErrCodeNo))
+ case stateHalfClosedRemote:
+ sc.closeStream(st, errHandlerComplete)
+ }
+ } else {
+ switch v := wr.write.(type) {
+ case StreamError:
+ // st may be unknown if the RST_STREAM was generated to reject bad input.
+ if st, ok := sc.streams[v.StreamID]; ok {
+ sc.closeStream(st, v)
+ }
+ case handlerPanicRST:
+ sc.closeStream(wr.stream, errHandlerPanicked)
+ }
+ }
+
+ // Reply (if requested) to unblock the ServeHTTP goroutine.
+ wr.replyToWriter(res.err)
+
+ sc.scheduleFrameWrite()
+}
+
+// scheduleFrameWrite tickles the frame writing scheduler.
+//
+// If a frame is already being written, nothing happens. This will be called again
+// when the frame is done being written.
+//
+// If a frame isn't being written we need to send one, the best frame
+// to send is selected, preferring first things that aren't
+// stream-specific (e.g. ACKing settings), and then finding the
+// highest priority stream.
+//
+// If a frame isn't being written and there's nothing else to send, we
+// flush the write buffer.
+func (sc *serverConn) scheduleFrameWrite() {
+ sc.serveG.check()
+ if sc.writingFrame || sc.inFrameScheduleLoop {
+ return
+ }
+ sc.inFrameScheduleLoop = true
+ for !sc.writingFrameAsync {
+ if sc.needToSendGoAway {
+ sc.needToSendGoAway = false
+ sc.startFrameWrite(FrameWriteRequest{
+ write: &writeGoAway{
+ maxStreamID: sc.maxClientStreamID,
+ code: sc.goAwayCode,
+ },
+ })
+ continue
+ }
+ if sc.needToSendSettingsAck {
+ sc.needToSendSettingsAck = false
+ sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}})
+ continue
+ }
+ if !sc.inGoAway || sc.goAwayCode == ErrCodeNo {
+ if wr, ok := sc.writeSched.Pop(); ok {
+ sc.startFrameWrite(wr)
+ continue
+ }
+ }
+ if sc.needsFrameFlush {
+ sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
+ sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
+ continue
+ }
+ break
+ }
+ sc.inFrameScheduleLoop = false
+}
+
+// startGracefulShutdown gracefully shuts down a connection. This
+// sends GOAWAY with ErrCodeNo to tell the client we're gracefully
+// shutting down. The connection isn't closed until all current
+// streams are done.
+//
+// startGracefulShutdown returns immediately; it does not wait until
+// the connection has shut down.
+func (sc *serverConn) startGracefulShutdown() {
+ sc.serveG.checkNotOn() // NOT
+ sc.shutdownOnce.Do(func() { sc.sendServeMsg(gracefulShutdownMsg) })
+}
+
+func (sc *serverConn) startGracefulShutdownInternal() {
+ sc.goAwayIn(ErrCodeNo, 0)
+}
+
+func (sc *serverConn) goAway(code ErrCode) {
+ sc.serveG.check()
+ var forceCloseIn time.Duration
+ if code != ErrCodeNo {
+ forceCloseIn = 250 * time.Millisecond
+ } else {
+ // TODO: configurable
+ forceCloseIn = 1 * time.Second
+ }
+ sc.goAwayIn(code, forceCloseIn)
+}
+
+func (sc *serverConn) goAwayIn(code ErrCode, forceCloseIn time.Duration) {
+ sc.serveG.check()
+ if sc.inGoAway {
+ return
+ }
+ if forceCloseIn != 0 {
+ sc.shutDownIn(forceCloseIn)
+ }
+ sc.inGoAway = true
+ sc.needToSendGoAway = true
+ sc.goAwayCode = code
+ sc.scheduleFrameWrite()
+}
+
+func (sc *serverConn) shutDownIn(d time.Duration) {
+ sc.serveG.check()
+ sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer)
+}
+
+func (sc *serverConn) resetStream(se StreamError) {
+ sc.serveG.check()
+ sc.writeFrame(FrameWriteRequest{write: se})
+ if st, ok := sc.streams[se.StreamID]; ok {
+ st.resetQueued = true
+ }
+}
+
+// processFrameFromReader processes the serve loop's read from readFrameCh from the
+// frame-reading goroutine.
+// processFrameFromReader returns whether the connection should be kept open.
+func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
+ sc.serveG.check()
+ err := res.err
+ if err != nil {
+ if err == ErrFrameTooLarge {
+ sc.goAway(ErrCodeFrameSize)
+ return true // goAway will close the loop
+ }
+ clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
+ if clientGone {
+ // TODO: could we also get into this state if
+ // the peer does a half close
+ // (e.g. CloseWrite) because they're done
+ // sending frames but they're still wanting
+ // our open replies? Investigate.
+ // TODO: add CloseWrite to crypto/tls.Conn first
+ // so we have a way to test this? I suppose
+ // just for testing we could have a non-TLS mode.
+ return false
+ }
+ } else {
+ f := res.f
+ if VerboseLogs {
+ sc.vlogf("http2: server read frame %v", summarizeFrame(f))
+ }
+ err = sc.processFrame(f)
+ if err == nil {
+ return true
+ }
+ }
+
+ switch ev := err.(type) {
+ case StreamError:
+ sc.resetStream(ev)
+ return true
+ case goAwayFlowError:
+ sc.goAway(ErrCodeFlowControl)
+ return true
+ case ConnectionError:
+ sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
+ sc.goAway(ErrCode(ev))
+ return true // goAway will handle shutdown
+ default:
+ if res.err != nil {
+ sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
+ } else {
+ sc.logf("http2: server closing client connection: %v", err)
+ }
+ return false
+ }
+}
+
+func (sc *serverConn) processFrame(f Frame) error {
+ sc.serveG.check()
+
+ // First frame received must be SETTINGS.
+ if !sc.sawFirstSettings {
+ if _, ok := f.(*SettingsFrame); !ok {
+ return ConnectionError(ErrCodeProtocol)
+ }
+ sc.sawFirstSettings = true
+ }
+
+ switch f := f.(type) {
+ case *SettingsFrame:
+ return sc.processSettings(f)
+ case *MetaHeadersFrame:
+ return sc.processHeaders(f)
+ case *WindowUpdateFrame:
+ return sc.processWindowUpdate(f)
+ case *PingFrame:
+ return sc.processPing(f)
+ case *DataFrame:
+ return sc.processData(f)
+ case *RSTStreamFrame:
+ return sc.processResetStream(f)
+ case *PriorityFrame:
+ return sc.processPriority(f)
+ case *GoAwayFrame:
+ return sc.processGoAway(f)
+ case *PushPromiseFrame:
+ // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
+ // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
+ return ConnectionError(ErrCodeProtocol)
+ default:
+ sc.vlogf("http2: server ignoring frame: %v", f.Header())
+ return nil
+ }
+}
+
+func (sc *serverConn) processPing(f *PingFrame) error {
+ sc.serveG.check()
+ if f.IsAck() {
+ // 6.7 PING: " An endpoint MUST NOT respond to PING frames
+ // containing this flag."
+ return nil
+ }
+ if f.StreamID != 0 {
+ // "PING frames are not associated with any individual
+ // stream. If a PING frame is received with a stream
+ // identifier field value other than 0x0, the recipient MUST
+ // respond with a connection error (Section 5.4.1) of type
+ // PROTOCOL_ERROR."
+ return ConnectionError(ErrCodeProtocol)
+ }
+ if sc.inGoAway && sc.goAwayCode != ErrCodeNo {
+ return nil
+ }
+ sc.writeFrame(FrameWriteRequest{write: writePingAck{f}})
+ return nil
+}
+
+func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
+ sc.serveG.check()
+ switch {
+ case f.StreamID != 0: // stream-level flow control
+ state, st := sc.state(f.StreamID)
+ if state == stateIdle {
+ // Section 5.1: "Receiving any frame other than HEADERS
+ // or PRIORITY on a stream in this state MUST be
+ // treated as a connection error (Section 5.4.1) of
+ // type PROTOCOL_ERROR."
+ return ConnectionError(ErrCodeProtocol)
+ }
+ if st == nil {
+ // "WINDOW_UPDATE can be sent by a peer that has sent a
+ // frame bearing the END_STREAM flag. This means that a
+ // receiver could receive a WINDOW_UPDATE frame on a "half
+ // closed (remote)" or "closed" stream. A receiver MUST
+ // NOT treat this as an error, see Section 5.1."
+ return nil
+ }
+ if !st.flow.add(int32(f.Increment)) {
+ return streamError(f.StreamID, ErrCodeFlowControl)
+ }
+ default: // connection-level flow control
+ if !sc.flow.add(int32(f.Increment)) {
+ return goAwayFlowError{}
+ }
+ }
+ sc.scheduleFrameWrite()
+ return nil
+}
+
+func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
+ sc.serveG.check()
+
+ state, st := sc.state(f.StreamID)
+ if state == stateIdle {
+ // 6.4 "RST_STREAM frames MUST NOT be sent for a
+ // stream in the "idle" state. If a RST_STREAM frame
+ // identifying an idle stream is received, the
+ // recipient MUST treat this as a connection error
+ // (Section 5.4.1) of type PROTOCOL_ERROR.
+ return ConnectionError(ErrCodeProtocol)
+ }
+ if st != nil {
+ st.cancelCtx()
+ sc.closeStream(st, streamError(f.StreamID, f.ErrCode))
+ }
+ return nil
+}
+
+func (sc *serverConn) closeStream(st *stream, err error) {
+ sc.serveG.check()
+ if st.state == stateIdle || st.state == stateClosed {
+ panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
+ }
+ st.state = stateClosed
+ if st.writeDeadline != nil {
+ st.writeDeadline.Stop()
+ }
+ if st.isPushed() {
+ sc.curPushedStreams--
+ } else {
+ sc.curClientStreams--
+ }
+ delete(sc.streams, st.id)
+ if len(sc.streams) == 0 {
+ sc.setConnState(http.StateIdle)
+ if sc.srv.IdleTimeout != 0 {
+ sc.idleTimer.Reset(sc.srv.IdleTimeout)
+ }
+ if h1ServerKeepAlivesDisabled(sc.hs) {
+ sc.startGracefulShutdownInternal()
+ }
+ }
+ if p := st.body; p != nil {
+ // Return any buffered unread bytes worth of conn-level flow control.
+ // See golang.org/issue/16481
+ sc.sendWindowUpdate(nil, p.Len())
+
+ p.CloseWithError(err)
+ }
+ st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
+ sc.writeSched.CloseStream(st.id)
+}
+
+func (sc *serverConn) processSettings(f *SettingsFrame) error {
+ sc.serveG.check()
+ if f.IsAck() {
+ sc.unackedSettings--
+ if sc.unackedSettings < 0 {
+ // Why is the peer ACKing settings we never sent?
+ // The spec doesn't mention this case, but
+ // hang up on them anyway.
+ return ConnectionError(ErrCodeProtocol)
+ }
+ return nil
+ }
+ if err := f.ForeachSetting(sc.processSetting); err != nil {
+ return err
+ }
+ sc.needToSendSettingsAck = true
+ sc.scheduleFrameWrite()
+ return nil
+}
+
+func (sc *serverConn) processSetting(s Setting) error {
+ sc.serveG.check()
+ if err := s.Valid(); err != nil {
+ return err
+ }
+ if VerboseLogs {
+ sc.vlogf("http2: server processing setting %v", s)
+ }
+ switch s.ID {
+ case SettingHeaderTableSize:
+ sc.headerTableSize = s.Val
+ sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
+ case SettingEnablePush:
+ sc.pushEnabled = s.Val != 0
+ case SettingMaxConcurrentStreams:
+ sc.clientMaxStreams = s.Val
+ case SettingInitialWindowSize:
+ return sc.processSettingInitialWindowSize(s.Val)
+ case SettingMaxFrameSize:
+ sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31
+ case SettingMaxHeaderListSize:
+ sc.peerMaxHeaderListSize = s.Val
+ default:
+ // Unknown setting: "An endpoint that receives a SETTINGS
+ // frame with any unknown or unsupported identifier MUST
+ // ignore that setting."
+ if VerboseLogs {
+ sc.vlogf("http2: server ignoring unknown setting %v", s)
+ }
+ }
+ return nil
+}
+
+func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
+ sc.serveG.check()
+ // Note: val already validated to be within range by
+ // processSetting's Valid call.
+
+ // "A SETTINGS frame can alter the initial flow control window
+ // size for all current streams. When the value of
+ // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
+ // adjust the size of all stream flow control windows that it
+ // maintains by the difference between the new value and the
+ // old value."
+ old := sc.initialStreamSendWindowSize
+ sc.initialStreamSendWindowSize = int32(val)
+ growth := int32(val) - old // may be negative
+ for _, st := range sc.streams {
+ if !st.flow.add(growth) {
+ // 6.9.2 Initial Flow Control Window Size
+ // "An endpoint MUST treat a change to
+ // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
+ // control window to exceed the maximum size as a
+ // connection error (Section 5.4.1) of type
+ // FLOW_CONTROL_ERROR."
+ return ConnectionError(ErrCodeFlowControl)
+ }
+ }
+ return nil
+}
+
+func (sc *serverConn) processData(f *DataFrame) error {
+ sc.serveG.check()
+ if sc.inGoAway && sc.goAwayCode != ErrCodeNo {
+ return nil
+ }
+ data := f.Data()
+
+ // "If a DATA frame is received whose stream is not in "open"
+ // or "half closed (local)" state, the recipient MUST respond
+ // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
+ id := f.Header().StreamID
+ state, st := sc.state(id)
+ if id == 0 || state == stateIdle {
+ // Section 5.1: "Receiving any frame other than HEADERS
+ // or PRIORITY on a stream in this state MUST be
+ // treated as a connection error (Section 5.4.1) of
+ // type PROTOCOL_ERROR."
+ return ConnectionError(ErrCodeProtocol)
+ }
+ if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued {
+ // This includes sending a RST_STREAM if the stream is
+ // in stateHalfClosedLocal (which currently means that
+ // the http.Handler returned, so it's done reading &
+ // done writing). Try to stop the client from sending
+ // more DATA.
+
+ // But still enforce their connection-level flow control,
+ // and return any flow control bytes since we're not going
+ // to consume them.
+ if sc.inflow.available() < int32(f.Length) {
+ return streamError(id, ErrCodeFlowControl)
+ }
+ // Deduct the flow control from inflow, since we're
+ // going to immediately add it back in
+ // sendWindowUpdate, which also schedules sending the
+ // frames.
+ sc.inflow.take(int32(f.Length))
+ sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
+
+ if st != nil && st.resetQueued {
+ // Already have a stream error in flight. Don't send another.
+ return nil
+ }
+ return streamError(id, ErrCodeStreamClosed)
+ }
+ if st.body == nil {
+ panic("internal error: should have a body in this state")
+ }
+
+ // Sender sending more than they'd declared?
+ if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
+ st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
+ return streamError(id, ErrCodeStreamClosed)
+ }
+ if f.Length > 0 {
+ // Check whether the client has flow control quota.
+ if st.inflow.available() < int32(f.Length) {
+ return streamError(id, ErrCodeFlowControl)
+ }
+ st.inflow.take(int32(f.Length))
+
+ if len(data) > 0 {
+ wrote, err := st.body.Write(data)
+ if err != nil {
+ return streamError(id, ErrCodeStreamClosed)
+ }
+ if wrote != len(data) {
+ panic("internal error: bad Writer")
+ }
+ st.bodyBytes += int64(len(data))
+ }
+
+ // Return any padded flow control now, since we won't
+ // refund it later on body reads.
+ if pad := int32(f.Length) - int32(len(data)); pad > 0 {
+ sc.sendWindowUpdate32(nil, pad)
+ sc.sendWindowUpdate32(st, pad)
+ }
+ }
+ if f.StreamEnded() {
+ st.endStream()
+ }
+ return nil
+}
+
+func (sc *serverConn) processGoAway(f *GoAwayFrame) error {
+ sc.serveG.check()
+ if f.ErrCode != ErrCodeNo {
+ sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
+ } else {
+ sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
+ }
+ sc.startGracefulShutdownInternal()
+ // http://tools.ietf.org/html/rfc7540#section-6.8
+ // We should not create any new streams, which means we should disable push.
+ sc.pushEnabled = false
+ return nil
+}
+
+// isPushed reports whether the stream is server-initiated.
+func (st *stream) isPushed() bool {
+ return st.id%2 == 0
+}
+
+// endStream closes a Request.Body's pipe. It is called when a DATA
+// frame says a request body is over (or after trailers).
+func (st *stream) endStream() {
+ sc := st.sc
+ sc.serveG.check()
+
+ if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
+ st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
+ st.declBodyBytes, st.bodyBytes))
+ } else {
+ st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
+ st.body.CloseWithError(io.EOF)
+ }
+ st.state = stateHalfClosedRemote
+}
+
+// copyTrailersToHandlerRequest is run in the Handler's goroutine in
+// its Request.Body.Read just before it gets io.EOF.
+func (st *stream) copyTrailersToHandlerRequest() {
+ for k, vv := range st.trailer {
+ if _, ok := st.reqTrailer[k]; ok {
+ // Only copy it over it was pre-declared.
+ st.reqTrailer[k] = vv
+ }
+ }
+}
+
+// onWriteTimeout is run on its own goroutine (from time.AfterFunc)
+// when the stream's WriteTimeout has fired.
+func (st *stream) onWriteTimeout() {
+ st.sc.writeFrameFromHandler(FrameWriteRequest{write: streamError(st.id, ErrCodeInternal)})
+}
+
+func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
+ sc.serveG.check()
+ id := f.StreamID
+ if sc.inGoAway {
+ // Ignore.
+ return nil
+ }
+ // http://tools.ietf.org/html/rfc7540#section-5.1.1
+ // Streams initiated by a client MUST use odd-numbered stream
+ // identifiers. [...] An endpoint that receives an unexpected
+ // stream identifier MUST respond with a connection error
+ // (Section 5.4.1) of type PROTOCOL_ERROR.
+ if id%2 != 1 {
+ return ConnectionError(ErrCodeProtocol)
+ }
+ // A HEADERS frame can be used to create a new stream or
+ // send a trailer for an open one. If we already have a stream
+ // open, let it process its own HEADERS frame (trailers at this
+ // point, if it's valid).
+ if st := sc.streams[f.StreamID]; st != nil {
+ if st.resetQueued {
+ // We're sending RST_STREAM to close the stream, so don't bother
+ // processing this frame.
+ return nil
+ }
+ return st.processTrailerHeaders(f)
+ }
+
+ // [...] The identifier of a newly established stream MUST be
+ // numerically greater than all streams that the initiating
+ // endpoint has opened or reserved. [...] An endpoint that
+ // receives an unexpected stream identifier MUST respond with
+ // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
+ if id <= sc.maxClientStreamID {
+ return ConnectionError(ErrCodeProtocol)
+ }
+ sc.maxClientStreamID = id
+
+ if sc.idleTimer != nil {
+ sc.idleTimer.Stop()
+ }
+
+ // http://tools.ietf.org/html/rfc7540#section-5.1.2
+ // [...] Endpoints MUST NOT exceed the limit set by their peer. An
+ // endpoint that receives a HEADERS frame that causes their
+ // advertised concurrent stream limit to be exceeded MUST treat
+ // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR
+ // or REFUSED_STREAM.
+ if sc.curClientStreams+1 > sc.advMaxStreams {
+ if sc.unackedSettings == 0 {
+ // They should know better.
+ return streamError(id, ErrCodeProtocol)
+ }
+ // Assume it's a network race, where they just haven't
+ // received our last SETTINGS update. But actually
+ // this can't happen yet, because we don't yet provide
+ // a way for users to adjust server parameters at
+ // runtime.
+ return streamError(id, ErrCodeRefusedStream)
+ }
+
+ initialState := stateOpen
+ if f.StreamEnded() {
+ initialState = stateHalfClosedRemote
+ }
+ st := sc.newStream(id, 0, initialState)
+
+ if f.HasPriority() {
+ if err := checkPriority(f.StreamID, f.Priority); err != nil {
+ return err
+ }
+ sc.writeSched.AdjustStream(st.id, f.Priority)
+ }
+
+ rw, req, err := sc.newWriterAndRequest(st, f)
+ if err != nil {
+ return err
+ }
+ st.reqTrailer = req.Trailer
+ if st.reqTrailer != nil {
+ st.trailer = make(http.Header)
+ }
+ st.body = req.Body.(*requestBody).pipe // may be nil
+ st.declBodyBytes = req.ContentLength
+
+ handler := sc.handler.ServeHTTP
+ if f.Truncated {
+ // Their header list was too long. Send a 431 error.
+ handler = handleHeaderListTooLong
+ } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil {
+ handler = new400Handler(err)
+ }
+
+ // The net/http package sets the read deadline from the
+ // http.Server.ReadTimeout during the TLS handshake, but then
+ // passes the connection off to us with the deadline already
+ // set. Disarm it here after the request headers are read,
+ // similar to how the http1 server works. Here it's
+ // technically more like the http1 Server's ReadHeaderTimeout
+ // (in Go 1.8), though. That's a more sane option anyway.
+ if sc.hs.ReadTimeout != 0 {
+ sc.conn.SetReadDeadline(time.Time{})
+ }
+
+ go sc.runHandler(rw, req, handler)
+ return nil
+}
+
+func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
+ sc := st.sc
+ sc.serveG.check()
+ if st.gotTrailerHeader {
+ return ConnectionError(ErrCodeProtocol)
+ }
+ st.gotTrailerHeader = true
+ if !f.StreamEnded() {
+ return streamError(st.id, ErrCodeProtocol)
+ }
+
+ if len(f.PseudoFields()) > 0 {
+ return streamError(st.id, ErrCodeProtocol)
+ }
+ if st.trailer != nil {
+ for _, hf := range f.RegularFields() {
+ key := sc.canonicalHeader(hf.Name)
+ if !ValidTrailerHeader(key) {
+ // TODO: send more details to the peer somehow. But http2 has
+ // no way to send debug data at a stream level. Discuss with
+ // HTTP folk.
+ return streamError(st.id, ErrCodeProtocol)
+ }
+ st.trailer[key] = append(st.trailer[key], hf.Value)
+ }
+ }
+ st.endStream()
+ return nil
+}
+
+func checkPriority(streamID uint32, p PriorityParam) error {
+ if streamID == p.StreamDep {
+ // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat
+ // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR."
+ // Section 5.3.3 says that a stream can depend on one of its dependencies,
+ // so it's only self-dependencies that are forbidden.
+ return streamError(streamID, ErrCodeProtocol)
+ }
+ return nil
+}
+
+func (sc *serverConn) processPriority(f *PriorityFrame) error {
+ if sc.inGoAway {
+ return nil
+ }
+ if err := checkPriority(f.StreamID, f.PriorityParam); err != nil {
+ return err
+ }
+ sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam)
+ return nil
+}
+
+func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream {
+ sc.serveG.check()
+ if id == 0 {
+ panic("internal error: cannot create stream with id 0")
+ }
+
+ ctx, cancelCtx := contextWithCancel(sc.baseCtx)
+ st := &stream{
+ sc: sc,
+ id: id,
+ state: state,
+ ctx: ctx,
+ cancelCtx: cancelCtx,
+ }
+ st.cw.Init()
+ st.flow.conn = &sc.flow // link to conn-level counter
+ st.flow.add(sc.initialStreamSendWindowSize)
+ st.inflow.conn = &sc.inflow // link to conn-level counter
+ st.inflow.add(sc.srv.initialStreamRecvWindowSize())
+ if sc.hs.WriteTimeout != 0 {
+ st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout)
+ }
+
+ sc.streams[id] = st
+ sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID})
+ if st.isPushed() {
+ sc.curPushedStreams++
+ } else {
+ sc.curClientStreams++
+ }
+ if sc.curOpenStreams() == 1 {
+ sc.setConnState(http.StateActive)
+ }
+
+ return st
+}
+
+func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) {
+ sc.serveG.check()
+
+ rp := requestParam{
+ method: f.PseudoValue("method"),
+ scheme: f.PseudoValue("scheme"),
+ authority: f.PseudoValue("authority"),
+ path: f.PseudoValue("path"),
+ }
+
+ isConnect := rp.method == "CONNECT"
+ if isConnect {
+ if rp.path != "" || rp.scheme != "" || rp.authority == "" {
+ return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
+ }
+ } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") {
+ // See 8.1.2.6 Malformed Requests and Responses:
+ //
+ // Malformed requests or responses that are detected
+ // MUST be treated as a stream error (Section 5.4.2)
+ // of type PROTOCOL_ERROR."
+ //
+ // 8.1.2.3 Request Pseudo-Header Fields
+ // "All HTTP/2 requests MUST include exactly one valid
+ // value for the :method, :scheme, and :path
+ // pseudo-header fields"
+ return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
+ }
+
+ bodyOpen := !f.StreamEnded()
+ if rp.method == "HEAD" && bodyOpen {
+ // HEAD requests can't have bodies
+ return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
+ }
+
+ rp.header = make(http.Header)
+ for _, hf := range f.RegularFields() {
+ rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value)
+ }
+ if rp.authority == "" {
+ rp.authority = rp.header.Get("Host")
+ }
+
+ rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
+ if err != nil {
+ return nil, nil, err
+ }
+ if bodyOpen {
+ if vv, ok := rp.header["Content-Length"]; ok {
+ req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
+ } else {
+ req.ContentLength = -1
+ }
+ req.Body.(*requestBody).pipe = &pipe{
+ b: &dataBuffer{expected: req.ContentLength},
+ }
+ }
+ return rw, req, nil
+}
+
+type requestParam struct {
+ method string
+ scheme, authority, path string
+ header http.Header
+}
+
+func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error) {
+ sc.serveG.check()
+
+ var tlsState *tls.ConnectionState // nil if not scheme https
+ if rp.scheme == "https" {
+ tlsState = sc.tlsState
+ }
+
+ needsContinue := rp.header.Get("Expect") == "100-continue"
+ if needsContinue {
+ rp.header.Del("Expect")
+ }
+ // Merge Cookie headers into one "; "-delimited value.
+ if cookies := rp.header["Cookie"]; len(cookies) > 1 {
+ rp.header.Set("Cookie", strings.Join(cookies, "; "))
+ }
+
+ // Setup Trailers
+ var trailer http.Header
+ for _, v := range rp.header["Trailer"] {
+ for _, key := range strings.Split(v, ",") {
+ key = http.CanonicalHeaderKey(strings.TrimSpace(key))
+ switch key {
+ case "Transfer-Encoding", "Trailer", "Content-Length":
+ // Bogus. (copy of http1 rules)
+ // Ignore.
+ default:
+ if trailer == nil {
+ trailer = make(http.Header)
+ }
+ trailer[key] = nil
+ }
+ }
+ }
+ delete(rp.header, "Trailer")
+
+ var url_ *url.URL
+ var requestURI string
+ if rp.method == "CONNECT" {
+ url_ = &url.URL{Host: rp.authority}
+ requestURI = rp.authority // mimic HTTP/1 server behavior
+ } else {
+ var err error
+ url_, err = url.ParseRequestURI(rp.path)
+ if err != nil {
+ return nil, nil, streamError(st.id, ErrCodeProtocol)
+ }
+ requestURI = rp.path
+ }
+
+ body := &requestBody{
+ conn: sc,
+ stream: st,
+ needsContinue: needsContinue,
+ }
+ req := &http.Request{
+ Method: rp.method,
+ URL: url_,
+ RemoteAddr: sc.remoteAddrStr,
+ Header: rp.header,
+ RequestURI: requestURI,
+ Proto: "HTTP/2.0",
+ ProtoMajor: 2,
+ ProtoMinor: 0,
+ TLS: tlsState,
+ Host: rp.authority,
+ Body: body,
+ Trailer: trailer,
+ }
+ req = requestWithContext(req, st.ctx)
+
+ rws := responseWriterStatePool.Get().(*responseWriterState)
+ bwSave := rws.bw
+ *rws = responseWriterState{} // zero all the fields
+ rws.conn = sc
+ rws.bw = bwSave
+ rws.bw.Reset(chunkWriter{rws})
+ rws.stream = st
+ rws.req = req
+ rws.body = body
+
+ rw := &responseWriter{rws: rws}
+ return rw, req, nil
+}
+
+// Run on its own goroutine.
+func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
+ didPanic := true
+ defer func() {
+ rw.rws.stream.cancelCtx()
+ if didPanic {
+ e := recover()
+ sc.writeFrameFromHandler(FrameWriteRequest{
+ write: handlerPanicRST{rw.rws.stream.id},
+ stream: rw.rws.stream,
+ })
+ // Same as net/http:
+ if shouldLogPanic(e) {
+ const size = 64 << 10
+ buf := make([]byte, size)
+ buf = buf[:runtime.Stack(buf, false)]
+ sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
+ }
+ return
+ }
+ rw.handlerDone()
+ }()
+ handler(rw, req)
+ didPanic = false
+}
+
+func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
+ // 10.5.1 Limits on Header Block Size:
+ // .. "A server that receives a larger header block than it is
+ // willing to handle can send an HTTP 431 (Request Header Fields Too
+ // Large) status code"
+ const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
+ w.WriteHeader(statusRequestHeaderFieldsTooLarge)
+ io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
+}
+
+// called from handler goroutines.
+// h may be nil.
+func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
+ sc.serveG.checkNotOn() // NOT on
+ var errc chan error
+ if headerData.h != nil {
+ // If there's a header map (which we don't own), so we have to block on
+ // waiting for this frame to be written, so an http.Flush mid-handler
+ // writes out the correct value of keys, before a handler later potentially
+ // mutates it.
+ errc = errChanPool.Get().(chan error)
+ }
+ if err := sc.writeFrameFromHandler(FrameWriteRequest{
+ write: headerData,
+ stream: st,
+ done: errc,
+ }); err != nil {
+ return err
+ }
+ if errc != nil {
+ select {
+ case err := <-errc:
+ errChanPool.Put(errc)
+ return err
+ case <-sc.doneServing:
+ return errClientDisconnected
+ case <-st.cw:
+ return errStreamClosed
+ }
+ }
+ return nil
+}
+
+// called from handler goroutines.
+func (sc *serverConn) write100ContinueHeaders(st *stream) {
+ sc.writeFrameFromHandler(FrameWriteRequest{
+ write: write100ContinueHeadersFrame{st.id},
+ stream: st,
+ })
+}
+
+// A bodyReadMsg tells the server loop that the http.Handler read n
+// bytes of the DATA from the client on the given stream.
+type bodyReadMsg struct {
+ st *stream
+ n int
+}
+
+// called from handler goroutines.
+// Notes that the handler for the given stream ID read n bytes of its body
+// and schedules flow control tokens to be sent.
+func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
+ sc.serveG.checkNotOn() // NOT on
+ if n > 0 {
+ select {
+ case sc.bodyReadCh <- bodyReadMsg{st, n}:
+ case <-sc.doneServing:
+ }
+ }
+}
+
+func (sc *serverConn) noteBodyRead(st *stream, n int) {
+ sc.serveG.check()
+ sc.sendWindowUpdate(nil, n) // conn-level
+ if st.state != stateHalfClosedRemote && st.state != stateClosed {
+ // Don't send this WINDOW_UPDATE if the stream is closed
+ // remotely.
+ sc.sendWindowUpdate(st, n)
+ }
+}
+
+// st may be nil for conn-level
+func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
+ sc.serveG.check()
+ // "The legal range for the increment to the flow control
+ // window is 1 to 2^31-1 (2,147,483,647) octets."
+ // A Go Read call on 64-bit machines could in theory read
+ // a larger Read than this. Very unlikely, but we handle it here
+ // rather than elsewhere for now.
+ const maxUint31 = 1<<31 - 1
+ for n >= maxUint31 {
+ sc.sendWindowUpdate32(st, maxUint31)
+ n -= maxUint31
+ }
+ sc.sendWindowUpdate32(st, int32(n))
+}
+
+// st may be nil for conn-level
+func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
+ sc.serveG.check()
+ if n == 0 {
+ return
+ }
+ if n < 0 {
+ panic("negative update")
+ }
+ var streamID uint32
+ if st != nil {
+ streamID = st.id
+ }
+ sc.writeFrame(FrameWriteRequest{
+ write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
+ stream: st,
+ })
+ var ok bool
+ if st == nil {
+ ok = sc.inflow.add(n)
+ } else {
+ ok = st.inflow.add(n)
+ }
+ if !ok {
+ panic("internal error; sent too many window updates without decrements?")
+ }
+}
+
+// requestBody is the Handler's Request.Body type.
+// Read and Close may be called concurrently.
+type requestBody struct {
+ stream *stream
+ conn *serverConn
+ closed bool // for use by Close only
+ sawEOF bool // for use by Read only
+ pipe *pipe // non-nil if we have a HTTP entity message body
+ needsContinue bool // need to send a 100-continue
+}
+
+func (b *requestBody) Close() error {
+ if b.pipe != nil && !b.closed {
+ b.pipe.BreakWithError(errClosedBody)
+ }
+ b.closed = true
+ return nil
+}
+
+func (b *requestBody) Read(p []byte) (n int, err error) {
+ if b.needsContinue {
+ b.needsContinue = false
+ b.conn.write100ContinueHeaders(b.stream)
+ }
+ if b.pipe == nil || b.sawEOF {
+ return 0, io.EOF
+ }
+ n, err = b.pipe.Read(p)
+ if err == io.EOF {
+ b.sawEOF = true
+ }
+ if b.conn == nil && inTests {
+ return
+ }
+ b.conn.noteBodyReadFromHandler(b.stream, n, err)
+ return
+}
+
+// responseWriter is the http.ResponseWriter implementation. It's
+// intentionally small (1 pointer wide) to minimize garbage. The
+// responseWriterState pointer inside is zeroed at the end of a
+// request (in handlerDone) and calls on the responseWriter thereafter
+// simply crash (caller's mistake), but the much larger responseWriterState
+// and buffers are reused between multiple requests.
+type responseWriter struct {
+ rws *responseWriterState
+}
+
+// Optional http.ResponseWriter interfaces implemented.
+var (
+ _ http.CloseNotifier = (*responseWriter)(nil)
+ _ http.Flusher = (*responseWriter)(nil)
+ _ stringWriter = (*responseWriter)(nil)
+)
+
+type responseWriterState struct {
+ // immutable within a request:
+ stream *stream
+ req *http.Request
+ body *requestBody // to close at end of request, if DATA frames didn't
+ conn *serverConn
+
+ // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
+ bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
+
+ // mutated by http.Handler goroutine:
+ handlerHeader http.Header // nil until called
+ snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
+ trailers []string // set in writeChunk
+ status int // status code passed to WriteHeader
+ wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
+ sentHeader bool // have we sent the header frame?
+ handlerDone bool // handler has finished
+
+ sentContentLen int64 // non-zero if handler set a Content-Length header
+ wroteBytes int64
+
+ closeNotifierMu sync.Mutex // guards closeNotifierCh
+ closeNotifierCh chan bool // nil until first used
+}
+
+type chunkWriter struct{ rws *responseWriterState }
+
+func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
+
+func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 }
+
+// declareTrailer is called for each Trailer header when the
+// response header is written. It notes that a header will need to be
+// written in the trailers at the end of the response.
+func (rws *responseWriterState) declareTrailer(k string) {
+ k = http.CanonicalHeaderKey(k)
+ if !ValidTrailerHeader(k) {
+ // Forbidden by RFC 2616 14.40.
+ rws.conn.logf("ignoring invalid trailer %q", k)
+ return
+ }
+ if !strSliceContains(rws.trailers, k) {
+ rws.trailers = append(rws.trailers, k)
+ }
+}
+
+// writeChunk writes chunks from the bufio.Writer. But because
+// bufio.Writer may bypass its chunking, sometimes p may be
+// arbitrarily large.
+//
+// writeChunk is also responsible (on the first chunk) for sending the
+// HEADER response.
+func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
+ if !rws.wroteHeader {
+ rws.writeHeader(200)
+ }
+
+ isHeadResp := rws.req.Method == "HEAD"
+ if !rws.sentHeader {
+ rws.sentHeader = true
+ var ctype, clen string
+ if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
+ rws.snapHeader.Del("Content-Length")
+ clen64, err := strconv.ParseInt(clen, 10, 64)
+ if err == nil && clen64 >= 0 {
+ rws.sentContentLen = clen64
+ } else {
+ clen = ""
+ }
+ }
+ if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
+ clen = strconv.Itoa(len(p))
+ }
+ _, hasContentType := rws.snapHeader["Content-Type"]
+ if !hasContentType && bodyAllowedForStatus(rws.status) {
+ ctype = http.DetectContentType(p)
+ }
+ var date string
+ if _, ok := rws.snapHeader["Date"]; !ok {
+ // TODO(bradfitz): be faster here, like net/http? measure.
+ date = time.Now().UTC().Format(http.TimeFormat)
+ }
+
+ for _, v := range rws.snapHeader["Trailer"] {
+ foreachHeaderElement(v, rws.declareTrailer)
+ }
+
+ endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
+ err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
+ streamID: rws.stream.id,
+ httpResCode: rws.status,
+ h: rws.snapHeader,
+ endStream: endStream,
+ contentType: ctype,
+ contentLength: clen,
+ date: date,
+ })
+ if err != nil {
+ return 0, err
+ }
+ if endStream {
+ return 0, nil
+ }
+ }
+ if isHeadResp {
+ return len(p), nil
+ }
+ if len(p) == 0 && !rws.handlerDone {
+ return 0, nil
+ }
+
+ if rws.handlerDone {
+ rws.promoteUndeclaredTrailers()
+ }
+
+ endStream := rws.handlerDone && !rws.hasTrailers()
+ if len(p) > 0 || endStream {
+ // only send a 0 byte DATA frame if we're ending the stream.
+ if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
+ return 0, err
+ }
+ }
+
+ if rws.handlerDone && rws.hasTrailers() {
+ err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
+ streamID: rws.stream.id,
+ h: rws.handlerHeader,
+ trailers: rws.trailers,
+ endStream: true,
+ })
+ return len(p), err
+ }
+ return len(p), nil
+}
+
+// TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
+// that, if present, signals that the map entry is actually for
+// the response trailers, and not the response headers. The prefix
+// is stripped after the ServeHTTP call finishes and the values are
+// sent in the trailers.
+//
+// This mechanism is intended only for trailers that are not known
+// prior to the headers being written. If the set of trailers is fixed
+// or known before the header is written, the normal Go trailers mechanism
+// is preferred:
+// https://golang.org/pkg/net/http/#ResponseWriter
+// https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
+const TrailerPrefix = "Trailer:"
+
+// promoteUndeclaredTrailers permits http.Handlers to set trailers
+// after the header has already been flushed. Because the Go
+// ResponseWriter interface has no way to set Trailers (only the
+// Header), and because we didn't want to expand the ResponseWriter
+// interface, and because nobody used trailers, and because RFC 2616
+// says you SHOULD (but not must) predeclare any trailers in the
+// header, the official ResponseWriter rules said trailers in Go must
+// be predeclared, and then we reuse the same ResponseWriter.Header()
+// map to mean both Headers and Trailers. When it's time to write the
+// Trailers, we pick out the fields of Headers that were declared as
+// trailers. That worked for a while, until we found the first major
+// user of Trailers in the wild: gRPC (using them only over http2),
+// and gRPC libraries permit setting trailers mid-stream without
+// predeclarnig them. So: change of plans. We still permit the old
+// way, but we also permit this hack: if a Header() key begins with
+// "Trailer:", the suffix of that key is a Trailer. Because ':' is an
+// invalid token byte anyway, there is no ambiguity. (And it's already
+// filtered out) It's mildly hacky, but not terrible.
+//
+// This method runs after the Handler is done and promotes any Header
+// fields to be trailers.
+func (rws *responseWriterState) promoteUndeclaredTrailers() {
+ for k, vv := range rws.handlerHeader {
+ if !strings.HasPrefix(k, TrailerPrefix) {
+ continue
+ }
+ trailerKey := strings.TrimPrefix(k, TrailerPrefix)
+ rws.declareTrailer(trailerKey)
+ rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv
+ }
+
+ if len(rws.trailers) > 1 {
+ sorter := sorterPool.Get().(*sorter)
+ sorter.SortStrings(rws.trailers)
+ sorterPool.Put(sorter)
+ }
+}
+
+func (w *responseWriter) Flush() {
+ rws := w.rws
+ if rws == nil {
+ panic("Header called after Handler finished")
+ }
+ if rws.bw.Buffered() > 0 {
+ if err := rws.bw.Flush(); err != nil {
+ // Ignore the error. The frame writer already knows.
+ return
+ }
+ } else {
+ // The bufio.Writer won't call chunkWriter.Write
+ // (writeChunk with zero bytes, so we have to do it
+ // ourselves to force the HTTP response header and/or
+ // final DATA frame (with END_STREAM) to be sent.
+ rws.writeChunk(nil)
+ }
+}
+
+func (w *responseWriter) CloseNotify() <-chan bool {
+ rws := w.rws
+ if rws == nil {
+ panic("CloseNotify called after Handler finished")
+ }
+ rws.closeNotifierMu.Lock()
+ ch := rws.closeNotifierCh
+ if ch == nil {
+ ch = make(chan bool, 1)
+ rws.closeNotifierCh = ch
+ cw := rws.stream.cw
+ go func() {
+ cw.Wait() // wait for close
+ ch <- true
+ }()
+ }
+ rws.closeNotifierMu.Unlock()
+ return ch
+}
+
+func (w *responseWriter) Header() http.Header {
+ rws := w.rws
+ if rws == nil {
+ panic("Header called after Handler finished")
+ }
+ if rws.handlerHeader == nil {
+ rws.handlerHeader = make(http.Header)
+ }
+ return rws.handlerHeader
+}
+
+func (w *responseWriter) WriteHeader(code int) {
+ rws := w.rws
+ if rws == nil {
+ panic("WriteHeader called after Handler finished")
+ }
+ rws.writeHeader(code)
+}
+
+func (rws *responseWriterState) writeHeader(code int) {
+ if !rws.wroteHeader {
+ rws.wroteHeader = true
+ rws.status = code
+ if len(rws.handlerHeader) > 0 {
+ rws.snapHeader = cloneHeader(rws.handlerHeader)
+ }
+ }
+}
+
+func cloneHeader(h http.Header) http.Header {
+ h2 := make(http.Header, len(h))
+ for k, vv := range h {
+ vv2 := make([]string, len(vv))
+ copy(vv2, vv)
+ h2[k] = vv2
+ }
+ return h2
+}
+
+// The Life Of A Write is like this:
+//
+// * Handler calls w.Write or w.WriteString ->
+// * -> rws.bw (*bufio.Writer) ->
+// * (Handler migth call Flush)
+// * -> chunkWriter{rws}
+// * -> responseWriterState.writeChunk(p []byte)
+// * -> responseWriterState.writeChunk (most of the magic; see comment there)
+func (w *responseWriter) Write(p []byte) (n int, err error) {
+ return w.write(len(p), p, "")
+}
+
+func (w *responseWriter) WriteString(s string) (n int, err error) {
+ return w.write(len(s), nil, s)
+}
+
+// either dataB or dataS is non-zero.
+func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
+ rws := w.rws
+ if rws == nil {
+ panic("Write called after Handler finished")
+ }
+ if !rws.wroteHeader {
+ w.WriteHeader(200)
+ }
+ if !bodyAllowedForStatus(rws.status) {
+ return 0, http.ErrBodyNotAllowed
+ }
+ rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
+ if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
+ // TODO: send a RST_STREAM
+ return 0, errors.New("http2: handler wrote more than declared Content-Length")
+ }
+
+ if dataB != nil {
+ return rws.bw.Write(dataB)
+ } else {
+ return rws.bw.WriteString(dataS)
+ }
+}
+
+func (w *responseWriter) handlerDone() {
+ rws := w.rws
+ rws.handlerDone = true
+ w.Flush()
+ w.rws = nil
+ responseWriterStatePool.Put(rws)
+}
+
+// Push errors.
+var (
+ ErrRecursivePush = errors.New("http2: recursive push not allowed")
+ ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
+)
+
+// pushOptions is the internal version of http.PushOptions, which we
+// cannot include here because it's only defined in Go 1.8 and later.
+type pushOptions struct {
+ Method string
+ Header http.Header
+}
+
+func (w *responseWriter) push(target string, opts pushOptions) error {
+ st := w.rws.stream
+ sc := st.sc
+ sc.serveG.checkNotOn()
+
+ // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
+ // http://tools.ietf.org/html/rfc7540#section-6.6
+ if st.isPushed() {
+ return ErrRecursivePush
+ }
+
+ // Default options.
+ if opts.Method == "" {
+ opts.Method = "GET"
+ }
+ if opts.Header == nil {
+ opts.Header = http.Header{}
+ }
+ wantScheme := "http"
+ if w.rws.req.TLS != nil {
+ wantScheme = "https"
+ }
+
+ // Validate the request.
+ u, err := url.Parse(target)
+ if err != nil {
+ return err
+ }
+ if u.Scheme == "" {
+ if !strings.HasPrefix(target, "/") {
+ return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
+ }
+ u.Scheme = wantScheme
+ u.Host = w.rws.req.Host
+ } else {
+ if u.Scheme != wantScheme {
+ return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
+ }
+ if u.Host == "" {
+ return errors.New("URL must have a host")
+ }
+ }
+ for k := range opts.Header {
+ if strings.HasPrefix(k, ":") {
+ return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
+ }
+ // These headers are meaningful only if the request has a body,
+ // but PUSH_PROMISE requests cannot have a body.
+ // http://tools.ietf.org/html/rfc7540#section-8.2
+ // Also disallow Host, since the promised URL must be absolute.
+ switch strings.ToLower(k) {
+ case "content-length", "content-encoding", "trailer", "te", "expect", "host":
+ return fmt.Errorf("promised request headers cannot include %q", k)
+ }
+ }
+ if err := checkValidHTTP2RequestHeaders(opts.Header); err != nil {
+ return err
+ }
+
+ // The RFC effectively limits promised requests to GET and HEAD:
+ // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
+ // http://tools.ietf.org/html/rfc7540#section-8.2
+ if opts.Method != "GET" && opts.Method != "HEAD" {
+ return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
+ }
+
+ msg := &startPushRequest{
+ parent: st,
+ method: opts.Method,
+ url: u,
+ header: cloneHeader(opts.Header),
+ done: errChanPool.Get().(chan error),
+ }
+
+ select {
+ case <-sc.doneServing:
+ return errClientDisconnected
+ case <-st.cw:
+ return errStreamClosed
+ case sc.serveMsgCh <- msg:
+ }
+
+ select {
+ case <-sc.doneServing:
+ return errClientDisconnected
+ case <-st.cw:
+ return errStreamClosed
+ case err := <-msg.done:
+ errChanPool.Put(msg.done)
+ return err
+ }
+}
+
+type startPushRequest struct {
+ parent *stream
+ method string
+ url *url.URL
+ header http.Header
+ done chan error
+}
+
+func (sc *serverConn) startPush(msg *startPushRequest) {
+ sc.serveG.check()
+
+ // http://tools.ietf.org/html/rfc7540#section-6.6.
+ // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
+ // is in either the "open" or "half-closed (remote)" state.
+ if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
+ // responseWriter.Push checks that the stream is peer-initiaed.
+ msg.done <- errStreamClosed
+ return
+ }
+
+ // http://tools.ietf.org/html/rfc7540#section-6.6.
+ if !sc.pushEnabled {
+ msg.done <- http.ErrNotSupported
+ return
+ }
+
+ // PUSH_PROMISE frames must be sent in increasing order by stream ID, so
+ // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
+ // is written. Once the ID is allocated, we start the request handler.
+ allocatePromisedID := func() (uint32, error) {
+ sc.serveG.check()
+
+ // Check this again, just in case. Technically, we might have received
+ // an updated SETTINGS by the time we got around to writing this frame.
+ if !sc.pushEnabled {
+ return 0, http.ErrNotSupported
+ }
+ // http://tools.ietf.org/html/rfc7540#section-6.5.2.
+ if sc.curPushedStreams+1 > sc.clientMaxStreams {
+ return 0, ErrPushLimitReached
+ }
+
+ // http://tools.ietf.org/html/rfc7540#section-5.1.1.
+ // Streams initiated by the server MUST use even-numbered identifiers.
+ // A server that is unable to establish a new stream identifier can send a GOAWAY
+ // frame so that the client is forced to open a new connection for new streams.
+ if sc.maxPushPromiseID+2 >= 1<<31 {
+ sc.startGracefulShutdownInternal()
+ return 0, ErrPushLimitReached
+ }
+ sc.maxPushPromiseID += 2
+ promisedID := sc.maxPushPromiseID
+
+ // http://tools.ietf.org/html/rfc7540#section-8.2.
+ // Strictly speaking, the new stream should start in "reserved (local)", then
+ // transition to "half closed (remote)" after sending the initial HEADERS, but
+ // we start in "half closed (remote)" for simplicity.
+ // See further comments at the definition of stateHalfClosedRemote.
+ promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote)
+ rw, req, err := sc.newWriterAndRequestNoBody(promised, requestParam{
+ method: msg.method,
+ scheme: msg.url.Scheme,
+ authority: msg.url.Host,
+ path: msg.url.RequestURI(),
+ header: cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE
+ })
+ if err != nil {
+ // Should not happen, since we've already validated msg.url.
+ panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
+ }
+
+ go sc.runHandler(rw, req, sc.handler.ServeHTTP)
+ return promisedID, nil
+ }
+
+ sc.writeFrame(FrameWriteRequest{
+ write: &writePushPromise{
+ streamID: msg.parent.id,
+ method: msg.method,
+ url: msg.url,
+ h: msg.header,
+ allocatePromisedID: allocatePromisedID,
+ },
+ stream: msg.parent,
+ done: msg.done,
+ })
+}
+
+// foreachHeaderElement splits v according to the "#rule" construction
+// in RFC 2616 section 2.1 and calls fn for each non-empty element.
+func foreachHeaderElement(v string, fn func(string)) {
+ v = textproto.TrimString(v)
+ if v == "" {
+ return
+ }
+ if !strings.Contains(v, ",") {
+ fn(v)
+ return
+ }
+ for _, f := range strings.Split(v, ",") {
+ if f = textproto.TrimString(f); f != "" {
+ fn(f)
+ }
+ }
+}
+
+// From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
+var connHeaders = []string{
+ "Connection",
+ "Keep-Alive",
+ "Proxy-Connection",
+ "Transfer-Encoding",
+ "Upgrade",
+}
+
+// checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
+// per RFC 7540 Section 8.1.2.2.
+// The returned error is reported to users.
+func checkValidHTTP2RequestHeaders(h http.Header) error {
+ for _, k := range connHeaders {
+ if _, ok := h[k]; ok {
+ return fmt.Errorf("request header %q is not valid in HTTP/2", k)
+ }
+ }
+ te := h["Te"]
+ if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
+ return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
+ }
+ return nil
+}
+
+func new400Handler(err error) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ }
+}
+
+// ValidTrailerHeader reports whether name is a valid header field name to appear
+// in trailers.
+// See: http://tools.ietf.org/html/rfc7230#section-4.1.2
+func ValidTrailerHeader(name string) bool {
+ name = http.CanonicalHeaderKey(name)
+ if strings.HasPrefix(name, "If-") || badTrailer[name] {
+ return false
+ }
+ return true
+}
+
+var badTrailer = map[string]bool{
+ "Authorization": true,
+ "Cache-Control": true,
+ "Connection": true,
+ "Content-Encoding": true,
+ "Content-Length": true,
+ "Content-Range": true,
+ "Content-Type": true,
+ "Expect": true,
+ "Host": true,
+ "Keep-Alive": true,
+ "Max-Forwards": true,
+ "Pragma": true,
+ "Proxy-Authenticate": true,
+ "Proxy-Authorization": true,
+ "Proxy-Connection": true,
+ "Range": true,
+ "Realm": true,
+ "Te": true,
+ "Trailer": true,
+ "Transfer-Encoding": true,
+ "Www-Authenticate": true,
+}
+
+// h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
+// disabled. See comments on h1ServerShutdownChan above for why
+// the code is written this way.
+func h1ServerKeepAlivesDisabled(hs *http.Server) bool {
+ var x interface{} = hs
+ type I interface {
+ doKeepAlives() bool
+ }
+ if hs, ok := x.(I); ok {
+ return !hs.doKeepAlives()
+ }
+ return false
+}
diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go
new file mode 100644
index 0000000..3a85f25
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/transport.go
@@ -0,0 +1,2123 @@
+// Copyright 2015 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.
+
+// Transport code.
+
+package http2
+
+import (
+ "bufio"
+ "bytes"
+ "compress/gzip"
+ "crypto/rand"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "log"
+ "math"
+ "net"
+ "net/http"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/net/http2/hpack"
+ "golang.org/x/net/idna"
+ "golang.org/x/net/lex/httplex"
+)
+
+const (
+ // transportDefaultConnFlow is how many connection-level flow control
+ // tokens we give the server at start-up, past the default 64k.
+ transportDefaultConnFlow = 1 << 30
+
+ // transportDefaultStreamFlow is how many stream-level flow
+ // control tokens we announce to the peer, and how many bytes
+ // we buffer per stream.
+ transportDefaultStreamFlow = 4 << 20
+
+ // transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
+ // a stream-level WINDOW_UPDATE for at a time.
+ transportDefaultStreamMinRefresh = 4 << 10
+
+ defaultUserAgent = "Go-http-client/2.0"
+)
+
+// Transport is an HTTP/2 Transport.
+//
+// A Transport internally caches connections to servers. It is safe
+// for concurrent use by multiple goroutines.
+type Transport struct {
+ // DialTLS specifies an optional dial function for creating
+ // TLS connections for requests.
+ //
+ // If DialTLS is nil, tls.Dial is used.
+ //
+ // If the returned net.Conn has a ConnectionState method like tls.Conn,
+ // it will be used to set http.Response.TLS.
+ DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
+
+ // TLSClientConfig specifies the TLS configuration to use with
+ // tls.Client. If nil, the default configuration is used.
+ TLSClientConfig *tls.Config
+
+ // ConnPool optionally specifies an alternate connection pool to use.
+ // If nil, the default is used.
+ ConnPool ClientConnPool
+
+ // DisableCompression, if true, prevents the Transport from
+ // requesting compression with an "Accept-Encoding: gzip"
+ // request header when the Request contains no existing
+ // Accept-Encoding value. If the Transport requests gzip on
+ // its own and gets a gzipped response, it's transparently
+ // decoded in the Response.Body. However, if the user
+ // explicitly requested gzip it is not automatically
+ // uncompressed.
+ DisableCompression bool
+
+ // AllowHTTP, if true, permits HTTP/2 requests using the insecure,
+ // plain-text "http" scheme. Note that this does not enable h2c support.
+ AllowHTTP bool
+
+ // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
+ // send in the initial settings frame. It is how many bytes
+ // of response headers are allow. Unlike the http2 spec, zero here
+ // means to use a default limit (currently 10MB). If you actually
+ // want to advertise an ulimited value to the peer, Transport
+ // interprets the highest possible value here (0xffffffff or 1<<32-1)
+ // to mean no limit.
+ MaxHeaderListSize uint32
+
+ // t1, if non-nil, is the standard library Transport using
+ // this transport. Its settings are used (but not its
+ // RoundTrip method, etc).
+ t1 *http.Transport
+
+ connPoolOnce sync.Once
+ connPoolOrDef ClientConnPool // non-nil version of ConnPool
+}
+
+func (t *Transport) maxHeaderListSize() uint32 {
+ if t.MaxHeaderListSize == 0 {
+ return 10 << 20
+ }
+ if t.MaxHeaderListSize == 0xffffffff {
+ return 0
+ }
+ return t.MaxHeaderListSize
+}
+
+func (t *Transport) disableCompression() bool {
+ return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
+}
+
+var errTransportVersion = errors.New("http2: ConfigureTransport is only supported starting at Go 1.6")
+
+// ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
+// It requires Go 1.6 or later and returns an error if the net/http package is too old
+// or if t1 has already been HTTP/2-enabled.
+func ConfigureTransport(t1 *http.Transport) error {
+ _, err := configureTransport(t1) // in configure_transport.go (go1.6) or not_go16.go
+ return err
+}
+
+func (t *Transport) connPool() ClientConnPool {
+ t.connPoolOnce.Do(t.initConnPool)
+ return t.connPoolOrDef
+}
+
+func (t *Transport) initConnPool() {
+ if t.ConnPool != nil {
+ t.connPoolOrDef = t.ConnPool
+ } else {
+ t.connPoolOrDef = &clientConnPool{t: t}
+ }
+}
+
+// ClientConn is the state of a single HTTP/2 client connection to an
+// HTTP/2 server.
+type ClientConn struct {
+ t *Transport
+ tconn net.Conn // usually *tls.Conn, except specialized impls
+ tlsState *tls.ConnectionState // nil only for specialized impls
+ singleUse bool // whether being used for a single http.Request
+
+ // readLoop goroutine fields:
+ readerDone chan struct{} // closed on error
+ readerErr error // set before readerDone is closed
+
+ idleTimeout time.Duration // or 0 for never
+ idleTimer *time.Timer
+
+ mu sync.Mutex // guards following
+ cond *sync.Cond // hold mu; broadcast on flow/closed changes
+ flow flow // our conn-level flow control quota (cs.flow is per stream)
+ inflow flow // peer's conn-level flow control
+ closed bool
+ wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back
+ goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received
+ goAwayDebug string // goAway frame's debug data, retained as a string
+ streams map[uint32]*clientStream // client-initiated
+ nextStreamID uint32
+ pings map[[8]byte]chan struct{} // in flight ping data to notification channel
+ bw *bufio.Writer
+ br *bufio.Reader
+ fr *Framer
+ lastActive time.Time
+ // Settings from peer: (also guarded by mu)
+ maxFrameSize uint32
+ maxConcurrentStreams uint32
+ initialWindowSize uint32
+
+ hbuf bytes.Buffer // HPACK encoder writes into this
+ henc *hpack.Encoder
+ freeBuf [][]byte
+
+ wmu sync.Mutex // held while writing; acquire AFTER mu if holding both
+ werr error // first write error that has occurred
+}
+
+// clientStream is the state for a single HTTP/2 stream. One of these
+// is created for each Transport.RoundTrip call.
+type clientStream struct {
+ cc *ClientConn
+ req *http.Request
+ trace *clientTrace // or nil
+ ID uint32
+ resc chan resAndError
+ bufPipe pipe // buffered pipe with the flow-controlled response payload
+ startedWrite bool // started request body write; guarded by cc.mu
+ requestedGzip bool
+ on100 func() // optional code to run if get a 100 continue response
+
+ flow flow // guarded by cc.mu
+ inflow flow // guarded by cc.mu
+ bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
+ readErr error // sticky read error; owned by transportResponseBody.Read
+ stopReqBody error // if non-nil, stop writing req body; guarded by cc.mu
+ didReset bool // whether we sent a RST_STREAM to the server; guarded by cc.mu
+
+ peerReset chan struct{} // closed on peer reset
+ resetErr error // populated before peerReset is closed
+
+ done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu
+
+ // owned by clientConnReadLoop:
+ firstByte bool // got the first response byte
+ pastHeaders bool // got first MetaHeadersFrame (actual headers)
+ pastTrailers bool // got optional second MetaHeadersFrame (trailers)
+
+ trailer http.Header // accumulated trailers
+ resTrailer *http.Header // client's Response.Trailer
+}
+
+// awaitRequestCancel runs in its own goroutine and waits for the user
+// to cancel a RoundTrip request, its context to expire, or for the
+// request to be done (any way it might be removed from the cc.streams
+// map: peer reset, successful completion, TCP connection breakage,
+// etc)
+func (cs *clientStream) awaitRequestCancel(req *http.Request) {
+ ctx := reqContext(req)
+ if req.Cancel == nil && ctx.Done() == nil {
+ return
+ }
+ select {
+ case <-req.Cancel:
+ cs.cancelStream()
+ cs.bufPipe.CloseWithError(errRequestCanceled)
+ case <-ctx.Done():
+ cs.cancelStream()
+ cs.bufPipe.CloseWithError(ctx.Err())
+ case <-cs.done:
+ }
+}
+
+func (cs *clientStream) cancelStream() {
+ cs.cc.mu.Lock()
+ didReset := cs.didReset
+ cs.didReset = true
+ cs.cc.mu.Unlock()
+
+ if !didReset {
+ cs.cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
+ }
+}
+
+// checkResetOrDone reports any error sent in a RST_STREAM frame by the
+// server, or errStreamClosed if the stream is complete.
+func (cs *clientStream) checkResetOrDone() error {
+ select {
+ case <-cs.peerReset:
+ return cs.resetErr
+ case <-cs.done:
+ return errStreamClosed
+ default:
+ return nil
+ }
+}
+
+func (cs *clientStream) abortRequestBodyWrite(err error) {
+ if err == nil {
+ panic("nil error")
+ }
+ cc := cs.cc
+ cc.mu.Lock()
+ cs.stopReqBody = err
+ cc.cond.Broadcast()
+ cc.mu.Unlock()
+}
+
+type stickyErrWriter struct {
+ w io.Writer
+ err *error
+}
+
+func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
+ if *sew.err != nil {
+ return 0, *sew.err
+ }
+ n, err = sew.w.Write(p)
+ *sew.err = err
+ return
+}
+
+var ErrNoCachedConn = errors.New("http2: no cached connection was available")
+
+// RoundTripOpt are options for the Transport.RoundTripOpt method.
+type RoundTripOpt struct {
+ // OnlyCachedConn controls whether RoundTripOpt may
+ // create a new TCP connection. If set true and
+ // no cached connection is available, RoundTripOpt
+ // will return ErrNoCachedConn.
+ OnlyCachedConn bool
+}
+
+func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
+ return t.RoundTripOpt(req, RoundTripOpt{})
+}
+
+// authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
+// and returns a host:port. The port 443 is added if needed.
+func authorityAddr(scheme string, authority string) (addr string) {
+ host, port, err := net.SplitHostPort(authority)
+ if err != nil { // authority didn't have a port
+ port = "443"
+ if scheme == "http" {
+ port = "80"
+ }
+ host = authority
+ }
+ if a, err := idna.ToASCII(host); err == nil {
+ host = a
+ }
+ // IPv6 address literal, without a port:
+ if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
+ return host + ":" + port
+ }
+ return net.JoinHostPort(host, port)
+}
+
+// RoundTripOpt is like RoundTrip, but takes options.
+func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
+ if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
+ return nil, errors.New("http2: unsupported scheme")
+ }
+
+ addr := authorityAddr(req.URL.Scheme, req.URL.Host)
+ for {
+ cc, err := t.connPool().GetClientConn(req, addr)
+ if err != nil {
+ t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
+ return nil, err
+ }
+ traceGotConn(req, cc)
+ res, err := cc.RoundTrip(req)
+ if err != nil {
+ if req, err = shouldRetryRequest(req, err); err == nil {
+ continue
+ }
+ }
+ if err != nil {
+ t.vlogf("RoundTrip failure: %v", err)
+ return nil, err
+ }
+ return res, nil
+ }
+}
+
+// CloseIdleConnections closes any connections which were previously
+// connected from previous requests but are now sitting idle.
+// It does not interrupt any connections currently in use.
+func (t *Transport) CloseIdleConnections() {
+ if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok {
+ cp.closeIdleConnections()
+ }
+}
+
+var (
+ errClientConnClosed = errors.New("http2: client conn is closed")
+ errClientConnUnusable = errors.New("http2: client conn not usable")
+
+ errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
+ errClientConnGotGoAwayAfterSomeReqBody = errors.New("http2: Transport received Server's graceful shutdown GOAWAY; some request body already written")
+)
+
+// shouldRetryRequest is called by RoundTrip when a request fails to get
+// response headers. It is always called with a non-nil error.
+// It returns either a request to retry (either the same request, or a
+// modified clone), or an error if the request can't be replayed.
+func shouldRetryRequest(req *http.Request, err error) (*http.Request, error) {
+ switch err {
+ default:
+ return nil, err
+ case errClientConnUnusable, errClientConnGotGoAway:
+ return req, nil
+ case errClientConnGotGoAwayAfterSomeReqBody:
+ // If the Body is nil (or http.NoBody), it's safe to reuse
+ // this request and its Body.
+ if req.Body == nil || reqBodyIsNoBody(req.Body) {
+ return req, nil
+ }
+ // Otherwise we depend on the Request having its GetBody
+ // func defined.
+ getBody := reqGetBody(req) // Go 1.8: getBody = req.GetBody
+ if getBody == nil {
+ return nil, errors.New("http2: Transport: peer server initiated graceful shutdown after some of Request.Body was written; define Request.GetBody to avoid this error")
+ }
+ body, err := getBody()
+ if err != nil {
+ return nil, err
+ }
+ newReq := *req
+ newReq.Body = body
+ return &newReq, nil
+ }
+}
+
+func (t *Transport) dialClientConn(addr string, singleUse bool) (*ClientConn, error) {
+ host, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ return nil, err
+ }
+ tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host))
+ if err != nil {
+ return nil, err
+ }
+ return t.newClientConn(tconn, singleUse)
+}
+
+func (t *Transport) newTLSConfig(host string) *tls.Config {
+ cfg := new(tls.Config)
+ if t.TLSClientConfig != nil {
+ *cfg = *cloneTLSConfig(t.TLSClientConfig)
+ }
+ if !strSliceContains(cfg.NextProtos, NextProtoTLS) {
+ cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...)
+ }
+ if cfg.ServerName == "" {
+ cfg.ServerName = host
+ }
+ return cfg
+}
+
+func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) {
+ if t.DialTLS != nil {
+ return t.DialTLS
+ }
+ return t.dialTLSDefault
+}
+
+func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) {
+ cn, err := tls.Dial(network, addr, cfg)
+ if err != nil {
+ return nil, err
+ }
+ if err := cn.Handshake(); err != nil {
+ return nil, err
+ }
+ if !cfg.InsecureSkipVerify {
+ if err := cn.VerifyHostname(cfg.ServerName); err != nil {
+ return nil, err
+ }
+ }
+ state := cn.ConnectionState()
+ if p := state.NegotiatedProtocol; p != NextProtoTLS {
+ return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
+ }
+ if !state.NegotiatedProtocolIsMutual {
+ return nil, errors.New("http2: could not negotiate protocol mutually")
+ }
+ return cn, nil
+}
+
+// disableKeepAlives reports whether connections should be closed as
+// soon as possible after handling the first request.
+func (t *Transport) disableKeepAlives() bool {
+ return t.t1 != nil && t.t1.DisableKeepAlives
+}
+
+func (t *Transport) expectContinueTimeout() time.Duration {
+ if t.t1 == nil {
+ return 0
+ }
+ return transportExpectContinueTimeout(t.t1)
+}
+
+func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
+ return t.newClientConn(c, false)
+}
+
+func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) {
+ cc := &ClientConn{
+ t: t,
+ tconn: c,
+ readerDone: make(chan struct{}),
+ nextStreamID: 1,
+ maxFrameSize: 16 << 10, // spec default
+ initialWindowSize: 65535, // spec default
+ maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough.
+ streams: make(map[uint32]*clientStream),
+ singleUse: singleUse,
+ wantSettingsAck: true,
+ pings: make(map[[8]byte]chan struct{}),
+ }
+ if d := t.idleConnTimeout(); d != 0 {
+ cc.idleTimeout = d
+ cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
+ }
+ if VerboseLogs {
+ t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
+ }
+
+ cc.cond = sync.NewCond(&cc.mu)
+ cc.flow.add(int32(initialWindowSize))
+
+ // TODO: adjust this writer size to account for frame size +
+ // MTU + crypto/tls record padding.
+ cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr})
+ cc.br = bufio.NewReader(c)
+ cc.fr = NewFramer(cc.bw, cc.br)
+ cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
+ cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
+
+ // TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on
+ // henc in response to SETTINGS frames?
+ cc.henc = hpack.NewEncoder(&cc.hbuf)
+
+ if cs, ok := c.(connectionStater); ok {
+ state := cs.ConnectionState()
+ cc.tlsState = &state
+ }
+
+ initialSettings := []Setting{
+ {ID: SettingEnablePush, Val: 0},
+ {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
+ }
+ if max := t.maxHeaderListSize(); max != 0 {
+ initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
+ }
+
+ cc.bw.Write(clientPreface)
+ cc.fr.WriteSettings(initialSettings...)
+ cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
+ cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
+ cc.bw.Flush()
+ if cc.werr != nil {
+ return nil, cc.werr
+ }
+
+ go cc.readLoop()
+ return cc, nil
+}
+
+func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+
+ old := cc.goAway
+ cc.goAway = f
+
+ // Merge the previous and current GoAway error frames.
+ if cc.goAwayDebug == "" {
+ cc.goAwayDebug = string(f.DebugData())
+ }
+ if old != nil && old.ErrCode != ErrCodeNo {
+ cc.goAway.ErrCode = old.ErrCode
+ }
+ last := f.LastStreamID
+ for streamID, cs := range cc.streams {
+ if streamID > last {
+ select {
+ case cs.resc <- resAndError{err: errClientConnGotGoAway}:
+ default:
+ }
+ }
+ }
+}
+
+func (cc *ClientConn) CanTakeNewRequest() bool {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ return cc.canTakeNewRequestLocked()
+}
+
+func (cc *ClientConn) canTakeNewRequestLocked() bool {
+ if cc.singleUse && cc.nextStreamID > 1 {
+ return false
+ }
+ return cc.goAway == nil && !cc.closed &&
+ int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams) &&
+ cc.nextStreamID < math.MaxInt32
+}
+
+// onIdleTimeout is called from a time.AfterFunc goroutine. It will
+// only be called when we're idle, but because we're coming from a new
+// goroutine, there could be a new request coming in at the same time,
+// so this simply calls the synchronized closeIfIdle to shut down this
+// connection. The timer could just call closeIfIdle, but this is more
+// clear.
+func (cc *ClientConn) onIdleTimeout() {
+ cc.closeIfIdle()
+}
+
+func (cc *ClientConn) closeIfIdle() {
+ cc.mu.Lock()
+ if len(cc.streams) > 0 {
+ cc.mu.Unlock()
+ return
+ }
+ cc.closed = true
+ nextID := cc.nextStreamID
+ // TODO: do clients send GOAWAY too? maybe? Just Close:
+ cc.mu.Unlock()
+
+ if VerboseLogs {
+ cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
+ }
+ cc.tconn.Close()
+}
+
+const maxAllocFrameSize = 512 << 10
+
+// frameBuffer returns a scratch buffer suitable for writing DATA frames.
+// They're capped at the min of the peer's max frame size or 512KB
+// (kinda arbitrarily), but definitely capped so we don't allocate 4GB
+// bufers.
+func (cc *ClientConn) frameScratchBuffer() []byte {
+ cc.mu.Lock()
+ size := cc.maxFrameSize
+ if size > maxAllocFrameSize {
+ size = maxAllocFrameSize
+ }
+ for i, buf := range cc.freeBuf {
+ if len(buf) >= int(size) {
+ cc.freeBuf[i] = nil
+ cc.mu.Unlock()
+ return buf[:size]
+ }
+ }
+ cc.mu.Unlock()
+ return make([]byte, size)
+}
+
+func (cc *ClientConn) putFrameScratchBuffer(buf []byte) {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
+ if len(cc.freeBuf) < maxBufs {
+ cc.freeBuf = append(cc.freeBuf, buf)
+ return
+ }
+ for i, old := range cc.freeBuf {
+ if old == nil {
+ cc.freeBuf[i] = buf
+ return
+ }
+ }
+ // forget about it.
+}
+
+// errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
+// exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
+var errRequestCanceled = errors.New("net/http: request canceled")
+
+func commaSeparatedTrailers(req *http.Request) (string, error) {
+ keys := make([]string, 0, len(req.Trailer))
+ for k := range req.Trailer {
+ k = http.CanonicalHeaderKey(k)
+ switch k {
+ case "Transfer-Encoding", "Trailer", "Content-Length":
+ return "", &badStringError{"invalid Trailer key", k}
+ }
+ keys = append(keys, k)
+ }
+ if len(keys) > 0 {
+ sort.Strings(keys)
+ return strings.Join(keys, ","), nil
+ }
+ return "", nil
+}
+
+func (cc *ClientConn) responseHeaderTimeout() time.Duration {
+ if cc.t.t1 != nil {
+ return cc.t.t1.ResponseHeaderTimeout
+ }
+ // No way to do this (yet?) with just an http2.Transport. Probably
+ // no need. Request.Cancel this is the new way. We only need to support
+ // this for compatibility with the old http.Transport fields when
+ // we're doing transparent http2.
+ return 0
+}
+
+// checkConnHeaders checks whether req has any invalid connection-level headers.
+// per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
+// Certain headers are special-cased as okay but not transmitted later.
+func checkConnHeaders(req *http.Request) error {
+ if v := req.Header.Get("Upgrade"); v != "" {
+ return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
+ }
+ if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
+ return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
+ }
+ if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "close" && vv[0] != "keep-alive") {
+ return fmt.Errorf("http2: invalid Connection request header: %q", vv)
+ }
+ return nil
+}
+
+// actualContentLength returns a sanitized version of
+// req.ContentLength, where 0 actually means zero (not unknown) and -1
+// means unknown.
+func actualContentLength(req *http.Request) int64 {
+ if req.Body == nil {
+ return 0
+ }
+ if req.ContentLength != 0 {
+ return req.ContentLength
+ }
+ return -1
+}
+
+func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
+ if err := checkConnHeaders(req); err != nil {
+ return nil, err
+ }
+ if cc.idleTimer != nil {
+ cc.idleTimer.Stop()
+ }
+
+ trailers, err := commaSeparatedTrailers(req)
+ if err != nil {
+ return nil, err
+ }
+ hasTrailers := trailers != ""
+
+ cc.mu.Lock()
+ cc.lastActive = time.Now()
+ if cc.closed || !cc.canTakeNewRequestLocked() {
+ cc.mu.Unlock()
+ return nil, errClientConnUnusable
+ }
+
+ body := req.Body
+ hasBody := body != nil
+ contentLen := actualContentLength(req)
+
+ // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
+ var requestedGzip bool
+ if !cc.t.disableCompression() &&
+ req.Header.Get("Accept-Encoding") == "" &&
+ req.Header.Get("Range") == "" &&
+ req.Method != "HEAD" {
+ // Request gzip only, not deflate. Deflate is ambiguous and
+ // not as universally supported anyway.
+ // See: http://www.gzip.org/zlib/zlib_faq.html#faq38
+ //
+ // Note that we don't request this for HEAD requests,
+ // due to a bug in nginx:
+ // http://trac.nginx.org/nginx/ticket/358
+ // https://golang.org/issue/5522
+ //
+ // We don't request gzip if the request is for a range, since
+ // auto-decoding a portion of a gzipped document will just fail
+ // anyway. See https://golang.org/issue/8923
+ requestedGzip = true
+ }
+
+ // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
+ // sent by writeRequestBody below, along with any Trailers,
+ // again in form HEADERS{1}, CONTINUATION{0,})
+ hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen)
+ if err != nil {
+ cc.mu.Unlock()
+ return nil, err
+ }
+
+ cs := cc.newStream()
+ cs.req = req
+ cs.trace = requestTrace(req)
+ cs.requestedGzip = requestedGzip
+ bodyWriter := cc.t.getBodyWriterState(cs, body)
+ cs.on100 = bodyWriter.on100
+
+ cc.wmu.Lock()
+ endStream := !hasBody && !hasTrailers
+ werr := cc.writeHeaders(cs.ID, endStream, hdrs)
+ cc.wmu.Unlock()
+ traceWroteHeaders(cs.trace)
+ cc.mu.Unlock()
+
+ if werr != nil {
+ if hasBody {
+ req.Body.Close() // per RoundTripper contract
+ bodyWriter.cancel()
+ }
+ cc.forgetStreamID(cs.ID)
+ // Don't bother sending a RST_STREAM (our write already failed;
+ // no need to keep writing)
+ traceWroteRequest(cs.trace, werr)
+ return nil, werr
+ }
+
+ var respHeaderTimer <-chan time.Time
+ if hasBody {
+ bodyWriter.scheduleBodyWrite()
+ } else {
+ traceWroteRequest(cs.trace, nil)
+ if d := cc.responseHeaderTimeout(); d != 0 {
+ timer := time.NewTimer(d)
+ defer timer.Stop()
+ respHeaderTimer = timer.C
+ }
+ }
+
+ readLoopResCh := cs.resc
+ bodyWritten := false
+ ctx := reqContext(req)
+
+ handleReadLoopResponse := func(re resAndError) (*http.Response, error) {
+ res := re.res
+ if re.err != nil || res.StatusCode > 299 {
+ // On error or status code 3xx, 4xx, 5xx, etc abort any
+ // ongoing write, assuming that the server doesn't care
+ // about our request body. If the server replied with 1xx or
+ // 2xx, however, then assume the server DOES potentially
+ // want our body (e.g. full-duplex streaming:
+ // golang.org/issue/13444). If it turns out the server
+ // doesn't, they'll RST_STREAM us soon enough. This is a
+ // heuristic to avoid adding knobs to Transport. Hopefully
+ // we can keep it.
+ bodyWriter.cancel()
+ cs.abortRequestBodyWrite(errStopReqBodyWrite)
+ }
+ if re.err != nil {
+ if re.err == errClientConnGotGoAway {
+ cc.mu.Lock()
+ if cs.startedWrite {
+ re.err = errClientConnGotGoAwayAfterSomeReqBody
+ }
+ cc.mu.Unlock()
+ }
+ cc.forgetStreamID(cs.ID)
+ return nil, re.err
+ }
+ res.Request = req
+ res.TLS = cc.tlsState
+ return res, nil
+ }
+
+ for {
+ select {
+ case re := <-readLoopResCh:
+ return handleReadLoopResponse(re)
+ case <-respHeaderTimer:
+ cc.forgetStreamID(cs.ID)
+ if !hasBody || bodyWritten {
+ cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
+ } else {
+ bodyWriter.cancel()
+ cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
+ }
+ return nil, errTimeout
+ case <-ctx.Done():
+ cc.forgetStreamID(cs.ID)
+ if !hasBody || bodyWritten {
+ cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
+ } else {
+ bodyWriter.cancel()
+ cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
+ }
+ return nil, ctx.Err()
+ case <-req.Cancel:
+ cc.forgetStreamID(cs.ID)
+ if !hasBody || bodyWritten {
+ cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
+ } else {
+ bodyWriter.cancel()
+ cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
+ }
+ return nil, errRequestCanceled
+ case <-cs.peerReset:
+ // processResetStream already removed the
+ // stream from the streams map; no need for
+ // forgetStreamID.
+ return nil, cs.resetErr
+ case err := <-bodyWriter.resc:
+ // Prefer the read loop's response, if available. Issue 16102.
+ select {
+ case re := <-readLoopResCh:
+ return handleReadLoopResponse(re)
+ default:
+ }
+ if err != nil {
+ return nil, err
+ }
+ bodyWritten = true
+ if d := cc.responseHeaderTimeout(); d != 0 {
+ timer := time.NewTimer(d)
+ defer timer.Stop()
+ respHeaderTimer = timer.C
+ }
+ }
+ }
+}
+
+// requires cc.wmu be held
+func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, hdrs []byte) error {
+ first := true // first frame written (HEADERS is first, then CONTINUATION)
+ frameSize := int(cc.maxFrameSize)
+ for len(hdrs) > 0 && cc.werr == nil {
+ chunk := hdrs
+ if len(chunk) > frameSize {
+ chunk = chunk[:frameSize]
+ }
+ hdrs = hdrs[len(chunk):]
+ endHeaders := len(hdrs) == 0
+ if first {
+ cc.fr.WriteHeaders(HeadersFrameParam{
+ StreamID: streamID,
+ BlockFragment: chunk,
+ EndStream: endStream,
+ EndHeaders: endHeaders,
+ })
+ first = false
+ } else {
+ cc.fr.WriteContinuation(streamID, endHeaders, chunk)
+ }
+ }
+ // TODO(bradfitz): this Flush could potentially block (as
+ // could the WriteHeaders call(s) above), which means they
+ // wouldn't respond to Request.Cancel being readable. That's
+ // rare, but this should probably be in a goroutine.
+ cc.bw.Flush()
+ return cc.werr
+}
+
+// internal error values; they don't escape to callers
+var (
+ // abort request body write; don't send cancel
+ errStopReqBodyWrite = errors.New("http2: aborting request body write")
+
+ // abort request body write, but send stream reset of cancel.
+ errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
+)
+
+func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
+ cc := cs.cc
+ sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
+ buf := cc.frameScratchBuffer()
+ defer cc.putFrameScratchBuffer(buf)
+
+ defer func() {
+ traceWroteRequest(cs.trace, err)
+ // TODO: write h12Compare test showing whether
+ // Request.Body is closed by the Transport,
+ // and in multiple cases: server replies <=299 and >299
+ // while still writing request body
+ cerr := bodyCloser.Close()
+ if err == nil {
+ err = cerr
+ }
+ }()
+
+ req := cs.req
+ hasTrailers := req.Trailer != nil
+
+ var sawEOF bool
+ for !sawEOF {
+ n, err := body.Read(buf)
+ if err == io.EOF {
+ sawEOF = true
+ err = nil
+ } else if err != nil {
+ return err
+ }
+
+ remain := buf[:n]
+ for len(remain) > 0 && err == nil {
+ var allowed int32
+ allowed, err = cs.awaitFlowControl(len(remain))
+ switch {
+ case err == errStopReqBodyWrite:
+ return err
+ case err == errStopReqBodyWriteAndCancel:
+ cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
+ return err
+ case err != nil:
+ return err
+ }
+ cc.wmu.Lock()
+ data := remain[:allowed]
+ remain = remain[allowed:]
+ sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
+ err = cc.fr.WriteData(cs.ID, sentEnd, data)
+ if err == nil {
+ // TODO(bradfitz): this flush is for latency, not bandwidth.
+ // Most requests won't need this. Make this opt-in or
+ // opt-out? Use some heuristic on the body type? Nagel-like
+ // timers? Based on 'n'? Only last chunk of this for loop,
+ // unless flow control tokens are low? For now, always.
+ // If we change this, see comment below.
+ err = cc.bw.Flush()
+ }
+ cc.wmu.Unlock()
+ }
+ if err != nil {
+ return err
+ }
+ }
+
+ if sentEnd {
+ // Already sent END_STREAM (which implies we have no
+ // trailers) and flushed, because currently all
+ // WriteData frames above get a flush. So we're done.
+ return nil
+ }
+
+ var trls []byte
+ if hasTrailers {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ trls = cc.encodeTrailers(req)
+ }
+
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+
+ // Two ways to send END_STREAM: either with trailers, or
+ // with an empty DATA frame.
+ if len(trls) > 0 {
+ err = cc.writeHeaders(cs.ID, true, trls)
+ } else {
+ err = cc.fr.WriteData(cs.ID, true, nil)
+ }
+ if ferr := cc.bw.Flush(); ferr != nil && err == nil {
+ err = ferr
+ }
+ return err
+}
+
+// awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
+// control tokens from the server.
+// It returns either the non-zero number of tokens taken or an error
+// if the stream is dead.
+func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
+ cc := cs.cc
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ for {
+ if cc.closed {
+ return 0, errClientConnClosed
+ }
+ if cs.stopReqBody != nil {
+ return 0, cs.stopReqBody
+ }
+ if err := cs.checkResetOrDone(); err != nil {
+ return 0, err
+ }
+ if a := cs.flow.available(); a > 0 {
+ take := a
+ if int(take) > maxBytes {
+
+ take = int32(maxBytes) // can't truncate int; take is int32
+ }
+ if take > int32(cc.maxFrameSize) {
+ take = int32(cc.maxFrameSize)
+ }
+ cs.flow.take(take)
+ return take, nil
+ }
+ cc.cond.Wait()
+ }
+}
+
+type badStringError struct {
+ what string
+ str string
+}
+
+func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
+
+// requires cc.mu be held.
+func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
+ cc.hbuf.Reset()
+
+ host := req.Host
+ if host == "" {
+ host = req.URL.Host
+ }
+ host, err := httplex.PunycodeHostPort(host)
+ if err != nil {
+ return nil, err
+ }
+
+ var path string
+ if req.Method != "CONNECT" {
+ path = req.URL.RequestURI()
+ if !validPseudoPath(path) {
+ orig := path
+ path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
+ if !validPseudoPath(path) {
+ if req.URL.Opaque != "" {
+ return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
+ } else {
+ return nil, fmt.Errorf("invalid request :path %q", orig)
+ }
+ }
+ }
+ }
+
+ // Check for any invalid headers and return an error before we
+ // potentially pollute our hpack state. (We want to be able to
+ // continue to reuse the hpack encoder for future requests)
+ for k, vv := range req.Header {
+ if !httplex.ValidHeaderFieldName(k) {
+ return nil, fmt.Errorf("invalid HTTP header name %q", k)
+ }
+ for _, v := range vv {
+ if !httplex.ValidHeaderFieldValue(v) {
+ return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k)
+ }
+ }
+ }
+
+ // 8.1.2.3 Request Pseudo-Header Fields
+ // The :path pseudo-header field includes the path and query parts of the
+ // target URI (the path-absolute production and optionally a '?' character
+ // followed by the query production (see Sections 3.3 and 3.4 of
+ // [RFC3986]).
+ cc.writeHeader(":authority", host)
+ cc.writeHeader(":method", req.Method)
+ if req.Method != "CONNECT" {
+ cc.writeHeader(":path", path)
+ cc.writeHeader(":scheme", req.URL.Scheme)
+ }
+ if trailers != "" {
+ cc.writeHeader("trailer", trailers)
+ }
+
+ var didUA bool
+ for k, vv := range req.Header {
+ lowKey := strings.ToLower(k)
+ switch lowKey {
+ case "host", "content-length":
+ // Host is :authority, already sent.
+ // Content-Length is automatic, set below.
+ continue
+ case "connection", "proxy-connection", "transfer-encoding", "upgrade", "keep-alive":
+ // Per 8.1.2.2 Connection-Specific Header
+ // Fields, don't send connection-specific
+ // fields. We have already checked if any
+ // are error-worthy so just ignore the rest.
+ continue
+ case "user-agent":
+ // Match Go's http1 behavior: at most one
+ // User-Agent. If set to nil or empty string,
+ // then omit it. Otherwise if not mentioned,
+ // include the default (below).
+ didUA = true
+ if len(vv) < 1 {
+ continue
+ }
+ vv = vv[:1]
+ if vv[0] == "" {
+ continue
+ }
+ }
+ for _, v := range vv {
+ cc.writeHeader(lowKey, v)
+ }
+ }
+ if shouldSendReqContentLength(req.Method, contentLength) {
+ cc.writeHeader("content-length", strconv.FormatInt(contentLength, 10))
+ }
+ if addGzipHeader {
+ cc.writeHeader("accept-encoding", "gzip")
+ }
+ if !didUA {
+ cc.writeHeader("user-agent", defaultUserAgent)
+ }
+ return cc.hbuf.Bytes(), nil
+}
+
+// shouldSendReqContentLength reports whether the http2.Transport should send
+// a "content-length" request header. This logic is basically a copy of the net/http
+// transferWriter.shouldSendContentLength.
+// The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
+// -1 means unknown.
+func shouldSendReqContentLength(method string, contentLength int64) bool {
+ if contentLength > 0 {
+ return true
+ }
+ if contentLength < 0 {
+ return false
+ }
+ // For zero bodies, whether we send a content-length depends on the method.
+ // It also kinda doesn't matter for http2 either way, with END_STREAM.
+ switch method {
+ case "POST", "PUT", "PATCH":
+ return true
+ default:
+ return false
+ }
+}
+
+// requires cc.mu be held.
+func (cc *ClientConn) encodeTrailers(req *http.Request) []byte {
+ cc.hbuf.Reset()
+ for k, vv := range req.Trailer {
+ // Transfer-Encoding, etc.. have already been filter at the
+ // start of RoundTrip
+ lowKey := strings.ToLower(k)
+ for _, v := range vv {
+ cc.writeHeader(lowKey, v)
+ }
+ }
+ return cc.hbuf.Bytes()
+}
+
+func (cc *ClientConn) writeHeader(name, value string) {
+ if VerboseLogs {
+ log.Printf("http2: Transport encoding header %q = %q", name, value)
+ }
+ cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
+}
+
+type resAndError struct {
+ res *http.Response
+ err error
+}
+
+// requires cc.mu be held.
+func (cc *ClientConn) newStream() *clientStream {
+ cs := &clientStream{
+ cc: cc,
+ ID: cc.nextStreamID,
+ resc: make(chan resAndError, 1),
+ peerReset: make(chan struct{}),
+ done: make(chan struct{}),
+ }
+ cs.flow.add(int32(cc.initialWindowSize))
+ cs.flow.setConnFlow(&cc.flow)
+ cs.inflow.add(transportDefaultStreamFlow)
+ cs.inflow.setConnFlow(&cc.inflow)
+ cc.nextStreamID += 2
+ cc.streams[cs.ID] = cs
+ return cs
+}
+
+func (cc *ClientConn) forgetStreamID(id uint32) {
+ cc.streamByID(id, true)
+}
+
+func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ cs := cc.streams[id]
+ if andRemove && cs != nil && !cc.closed {
+ cc.lastActive = time.Now()
+ delete(cc.streams, id)
+ if len(cc.streams) == 0 && cc.idleTimer != nil {
+ cc.idleTimer.Reset(cc.idleTimeout)
+ }
+ close(cs.done)
+ cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
+ }
+ return cs
+}
+
+// clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
+type clientConnReadLoop struct {
+ cc *ClientConn
+ activeRes map[uint32]*clientStream // keyed by streamID
+ closeWhenIdle bool
+}
+
+// readLoop runs in its own goroutine and reads and dispatches frames.
+func (cc *ClientConn) readLoop() {
+ rl := &clientConnReadLoop{
+ cc: cc,
+ activeRes: make(map[uint32]*clientStream),
+ }
+
+ defer rl.cleanup()
+ cc.readerErr = rl.run()
+ if ce, ok := cc.readerErr.(ConnectionError); ok {
+ cc.wmu.Lock()
+ cc.fr.WriteGoAway(0, ErrCode(ce), nil)
+ cc.wmu.Unlock()
+ }
+}
+
+// GoAwayError is returned by the Transport when the server closes the
+// TCP connection after sending a GOAWAY frame.
+type GoAwayError struct {
+ LastStreamID uint32
+ ErrCode ErrCode
+ DebugData string
+}
+
+func (e GoAwayError) Error() string {
+ return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
+ e.LastStreamID, e.ErrCode, e.DebugData)
+}
+
+func isEOFOrNetReadError(err error) bool {
+ if err == io.EOF {
+ return true
+ }
+ ne, ok := err.(*net.OpError)
+ return ok && ne.Op == "read"
+}
+
+func (rl *clientConnReadLoop) cleanup() {
+ cc := rl.cc
+ defer cc.tconn.Close()
+ defer cc.t.connPool().MarkDead(cc)
+ defer close(cc.readerDone)
+
+ if cc.idleTimer != nil {
+ cc.idleTimer.Stop()
+ }
+
+ // Close any response bodies if the server closes prematurely.
+ // TODO: also do this if we've written the headers but not
+ // gotten a response yet.
+ err := cc.readerErr
+ cc.mu.Lock()
+ if cc.goAway != nil && isEOFOrNetReadError(err) {
+ err = GoAwayError{
+ LastStreamID: cc.goAway.LastStreamID,
+ ErrCode: cc.goAway.ErrCode,
+ DebugData: cc.goAwayDebug,
+ }
+ } else if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ }
+ for _, cs := range rl.activeRes {
+ cs.bufPipe.CloseWithError(err)
+ }
+ for _, cs := range cc.streams {
+ select {
+ case cs.resc <- resAndError{err: err}:
+ default:
+ }
+ close(cs.done)
+ }
+ cc.closed = true
+ cc.cond.Broadcast()
+ cc.mu.Unlock()
+}
+
+func (rl *clientConnReadLoop) run() error {
+ cc := rl.cc
+ rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse
+ gotReply := false // ever saw a HEADERS reply
+ gotSettings := false
+ for {
+ f, err := cc.fr.ReadFrame()
+ if err != nil {
+ cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
+ }
+ if se, ok := err.(StreamError); ok {
+ if cs := cc.streamByID(se.StreamID, true /*ended; remove it*/); cs != nil {
+ cs.cc.writeStreamReset(cs.ID, se.Code, err)
+ if se.Cause == nil {
+ se.Cause = cc.fr.errDetail
+ }
+ rl.endStreamError(cs, se)
+ }
+ continue
+ } else if err != nil {
+ return err
+ }
+ if VerboseLogs {
+ cc.vlogf("http2: Transport received %s", summarizeFrame(f))
+ }
+ if !gotSettings {
+ if _, ok := f.(*SettingsFrame); !ok {
+ cc.logf("protocol error: received %T before a SETTINGS frame", f)
+ return ConnectionError(ErrCodeProtocol)
+ }
+ gotSettings = true
+ }
+ maybeIdle := false // whether frame might transition us to idle
+
+ switch f := f.(type) {
+ case *MetaHeadersFrame:
+ err = rl.processHeaders(f)
+ maybeIdle = true
+ gotReply = true
+ case *DataFrame:
+ err = rl.processData(f)
+ maybeIdle = true
+ case *GoAwayFrame:
+ err = rl.processGoAway(f)
+ maybeIdle = true
+ case *RSTStreamFrame:
+ err = rl.processResetStream(f)
+ maybeIdle = true
+ case *SettingsFrame:
+ err = rl.processSettings(f)
+ case *PushPromiseFrame:
+ err = rl.processPushPromise(f)
+ case *WindowUpdateFrame:
+ err = rl.processWindowUpdate(f)
+ case *PingFrame:
+ err = rl.processPing(f)
+ default:
+ cc.logf("Transport: unhandled response frame type %T", f)
+ }
+ if err != nil {
+ if VerboseLogs {
+ cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
+ }
+ return err
+ }
+ if rl.closeWhenIdle && gotReply && maybeIdle && len(rl.activeRes) == 0 {
+ cc.closeIfIdle()
+ }
+ }
+}
+
+func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
+ cc := rl.cc
+ cs := cc.streamByID(f.StreamID, f.StreamEnded())
+ if cs == nil {
+ // We'd get here if we canceled a request while the
+ // server had its response still in flight. So if this
+ // was just something we canceled, ignore it.
+ return nil
+ }
+ if !cs.firstByte {
+ if cs.trace != nil {
+ // TODO(bradfitz): move first response byte earlier,
+ // when we first read the 9 byte header, not waiting
+ // until all the HEADERS+CONTINUATION frames have been
+ // merged. This works for now.
+ traceFirstResponseByte(cs.trace)
+ }
+ cs.firstByte = true
+ }
+ if !cs.pastHeaders {
+ cs.pastHeaders = true
+ } else {
+ return rl.processTrailers(cs, f)
+ }
+
+ res, err := rl.handleResponse(cs, f)
+ if err != nil {
+ if _, ok := err.(ConnectionError); ok {
+ return err
+ }
+ // Any other error type is a stream error.
+ cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err)
+ cs.resc <- resAndError{err: err}
+ return nil // return nil from process* funcs to keep conn alive
+ }
+ if res == nil {
+ // (nil, nil) special case. See handleResponse docs.
+ return nil
+ }
+ if res.Body != noBody {
+ rl.activeRes[cs.ID] = cs
+ }
+ cs.resTrailer = &res.Trailer
+ cs.resc <- resAndError{res: res}
+ return nil
+}
+
+// may return error types nil, or ConnectionError. Any other error value
+// is a StreamError of type ErrCodeProtocol. The returned error in that case
+// is the detail.
+//
+// As a special case, handleResponse may return (nil, nil) to skip the
+// frame (currently only used for 100 expect continue). This special
+// case is going away after Issue 13851 is fixed.
+func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
+ if f.Truncated {
+ return nil, errResponseHeaderListSize
+ }
+
+ status := f.PseudoValue("status")
+ if status == "" {
+ return nil, errors.New("missing status pseudo header")
+ }
+ statusCode, err := strconv.Atoi(status)
+ if err != nil {
+ return nil, errors.New("malformed non-numeric status pseudo header")
+ }
+
+ if statusCode == 100 {
+ traceGot100Continue(cs.trace)
+ if cs.on100 != nil {
+ cs.on100() // forces any write delay timer to fire
+ }
+ cs.pastHeaders = false // do it all again
+ return nil, nil
+ }
+
+ header := make(http.Header)
+ res := &http.Response{
+ Proto: "HTTP/2.0",
+ ProtoMajor: 2,
+ Header: header,
+ StatusCode: statusCode,
+ Status: status + " " + http.StatusText(statusCode),
+ }
+ for _, hf := range f.RegularFields() {
+ key := http.CanonicalHeaderKey(hf.Name)
+ if key == "Trailer" {
+ t := res.Trailer
+ if t == nil {
+ t = make(http.Header)
+ res.Trailer = t
+ }
+ foreachHeaderElement(hf.Value, func(v string) {
+ t[http.CanonicalHeaderKey(v)] = nil
+ })
+ } else {
+ header[key] = append(header[key], hf.Value)
+ }
+ }
+
+ streamEnded := f.StreamEnded()
+ isHead := cs.req.Method == "HEAD"
+ if !streamEnded || isHead {
+ res.ContentLength = -1
+ if clens := res.Header["Content-Length"]; len(clens) == 1 {
+ if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
+ res.ContentLength = clen64
+ } else {
+ // TODO: care? unlike http/1, it won't mess up our framing, so it's
+ // more safe smuggling-wise to ignore.
+ }
+ } else if len(clens) > 1 {
+ // TODO: care? unlike http/1, it won't mess up our framing, so it's
+ // more safe smuggling-wise to ignore.
+ }
+ }
+
+ if streamEnded || isHead {
+ res.Body = noBody
+ return res, nil
+ }
+
+ cs.bufPipe = pipe{b: &dataBuffer{expected: res.ContentLength}}
+ cs.bytesRemain = res.ContentLength
+ res.Body = transportResponseBody{cs}
+ go cs.awaitRequestCancel(cs.req)
+
+ if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
+ res.Header.Del("Content-Encoding")
+ res.Header.Del("Content-Length")
+ res.ContentLength = -1
+ res.Body = &gzipReader{body: res.Body}
+ setResponseUncompressed(res)
+ }
+ return res, nil
+}
+
+func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
+ if cs.pastTrailers {
+ // Too many HEADERS frames for this stream.
+ return ConnectionError(ErrCodeProtocol)
+ }
+ cs.pastTrailers = true
+ if !f.StreamEnded() {
+ // We expect that any headers for trailers also
+ // has END_STREAM.
+ return ConnectionError(ErrCodeProtocol)
+ }
+ if len(f.PseudoFields()) > 0 {
+ // No pseudo header fields are defined for trailers.
+ // TODO: ConnectionError might be overly harsh? Check.
+ return ConnectionError(ErrCodeProtocol)
+ }
+
+ trailer := make(http.Header)
+ for _, hf := range f.RegularFields() {
+ key := http.CanonicalHeaderKey(hf.Name)
+ trailer[key] = append(trailer[key], hf.Value)
+ }
+ cs.trailer = trailer
+
+ rl.endStream(cs)
+ return nil
+}
+
+// transportResponseBody is the concrete type of Transport.RoundTrip's
+// Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
+// On Close it sends RST_STREAM if EOF wasn't already seen.
+type transportResponseBody struct {
+ cs *clientStream
+}
+
+func (b transportResponseBody) Read(p []byte) (n int, err error) {
+ cs := b.cs
+ cc := cs.cc
+
+ if cs.readErr != nil {
+ return 0, cs.readErr
+ }
+ n, err = b.cs.bufPipe.Read(p)
+ if cs.bytesRemain != -1 {
+ if int64(n) > cs.bytesRemain {
+ n = int(cs.bytesRemain)
+ if err == nil {
+ err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
+ cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
+ }
+ cs.readErr = err
+ return int(cs.bytesRemain), err
+ }
+ cs.bytesRemain -= int64(n)
+ if err == io.EOF && cs.bytesRemain > 0 {
+ err = io.ErrUnexpectedEOF
+ cs.readErr = err
+ return n, err
+ }
+ }
+ if n == 0 {
+ // No flow control tokens to send back.
+ return
+ }
+
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+
+ var connAdd, streamAdd int32
+ // Check the conn-level first, before the stream-level.
+ if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
+ connAdd = transportDefaultConnFlow - v
+ cc.inflow.add(connAdd)
+ }
+ if err == nil { // No need to refresh if the stream is over or failed.
+ // Consider any buffered body data (read from the conn but not
+ // consumed by the client) when computing flow control for this
+ // stream.
+ v := int(cs.inflow.available()) + cs.bufPipe.Len()
+ if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
+ streamAdd = int32(transportDefaultStreamFlow - v)
+ cs.inflow.add(streamAdd)
+ }
+ }
+ if connAdd != 0 || streamAdd != 0 {
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+ if connAdd != 0 {
+ cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
+ }
+ if streamAdd != 0 {
+ cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
+ }
+ cc.bw.Flush()
+ }
+ return
+}
+
+var errClosedResponseBody = errors.New("http2: response body closed")
+
+func (b transportResponseBody) Close() error {
+ cs := b.cs
+ cc := cs.cc
+
+ serverSentStreamEnd := cs.bufPipe.Err() == io.EOF
+ unread := cs.bufPipe.Len()
+
+ if unread > 0 || !serverSentStreamEnd {
+ cc.mu.Lock()
+ cc.wmu.Lock()
+ if !serverSentStreamEnd {
+ cc.fr.WriteRSTStream(cs.ID, ErrCodeCancel)
+ cs.didReset = true
+ }
+ // Return connection-level flow control.
+ if unread > 0 {
+ cc.inflow.add(int32(unread))
+ cc.fr.WriteWindowUpdate(0, uint32(unread))
+ }
+ cc.bw.Flush()
+ cc.wmu.Unlock()
+ cc.mu.Unlock()
+ }
+
+ cs.bufPipe.BreakWithError(errClosedResponseBody)
+ return nil
+}
+
+func (rl *clientConnReadLoop) processData(f *DataFrame) error {
+ cc := rl.cc
+ cs := cc.streamByID(f.StreamID, f.StreamEnded())
+ data := f.Data()
+ if cs == nil {
+ cc.mu.Lock()
+ neverSent := cc.nextStreamID
+ cc.mu.Unlock()
+ if f.StreamID >= neverSent {
+ // We never asked for this.
+ cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
+ return ConnectionError(ErrCodeProtocol)
+ }
+ // We probably did ask for this, but canceled. Just ignore it.
+ // TODO: be stricter here? only silently ignore things which
+ // we canceled, but not things which were closed normally
+ // by the peer? Tough without accumulating too much state.
+
+ // But at least return their flow control:
+ if f.Length > 0 {
+ cc.mu.Lock()
+ cc.inflow.add(int32(f.Length))
+ cc.mu.Unlock()
+
+ cc.wmu.Lock()
+ cc.fr.WriteWindowUpdate(0, uint32(f.Length))
+ cc.bw.Flush()
+ cc.wmu.Unlock()
+ }
+ return nil
+ }
+ if f.Length > 0 {
+ // Check connection-level flow control.
+ cc.mu.Lock()
+ if cs.inflow.available() >= int32(f.Length) {
+ cs.inflow.take(int32(f.Length))
+ } else {
+ cc.mu.Unlock()
+ return ConnectionError(ErrCodeFlowControl)
+ }
+ // Return any padded flow control now, since we won't
+ // refund it later on body reads.
+ if pad := int32(f.Length) - int32(len(data)); pad > 0 {
+ cs.inflow.add(pad)
+ cc.inflow.add(pad)
+ cc.wmu.Lock()
+ cc.fr.WriteWindowUpdate(0, uint32(pad))
+ cc.fr.WriteWindowUpdate(cs.ID, uint32(pad))
+ cc.bw.Flush()
+ cc.wmu.Unlock()
+ }
+ didReset := cs.didReset
+ cc.mu.Unlock()
+
+ if len(data) > 0 && !didReset {
+ if _, err := cs.bufPipe.Write(data); err != nil {
+ rl.endStreamError(cs, err)
+ return err
+ }
+ }
+ }
+
+ if f.StreamEnded() {
+ rl.endStream(cs)
+ }
+ return nil
+}
+
+var errInvalidTrailers = errors.New("http2: invalid trailers")
+
+func (rl *clientConnReadLoop) endStream(cs *clientStream) {
+ // TODO: check that any declared content-length matches, like
+ // server.go's (*stream).endStream method.
+ rl.endStreamError(cs, nil)
+}
+
+func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
+ var code func()
+ if err == nil {
+ err = io.EOF
+ code = cs.copyTrailers
+ }
+ cs.bufPipe.closeWithErrorAndCode(err, code)
+ delete(rl.activeRes, cs.ID)
+ if isConnectionCloseRequest(cs.req) {
+ rl.closeWhenIdle = true
+ }
+
+ select {
+ case cs.resc <- resAndError{err: err}:
+ default:
+ }
+}
+
+func (cs *clientStream) copyTrailers() {
+ for k, vv := range cs.trailer {
+ t := cs.resTrailer
+ if *t == nil {
+ *t = make(http.Header)
+ }
+ (*t)[k] = vv
+ }
+}
+
+func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
+ cc := rl.cc
+ cc.t.connPool().MarkDead(cc)
+ if f.ErrCode != 0 {
+ // TODO: deal with GOAWAY more. particularly the error code
+ cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
+ }
+ cc.setGoAway(f)
+ return nil
+}
+
+func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
+ cc := rl.cc
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+
+ if f.IsAck() {
+ if cc.wantSettingsAck {
+ cc.wantSettingsAck = false
+ return nil
+ }
+ return ConnectionError(ErrCodeProtocol)
+ }
+
+ err := f.ForeachSetting(func(s Setting) error {
+ switch s.ID {
+ case SettingMaxFrameSize:
+ cc.maxFrameSize = s.Val
+ case SettingMaxConcurrentStreams:
+ cc.maxConcurrentStreams = s.Val
+ case SettingInitialWindowSize:
+ // Values above the maximum flow-control
+ // window size of 2^31-1 MUST be treated as a
+ // connection error (Section 5.4.1) of type
+ // FLOW_CONTROL_ERROR.
+ if s.Val > math.MaxInt32 {
+ return ConnectionError(ErrCodeFlowControl)
+ }
+
+ // Adjust flow control of currently-open
+ // frames by the difference of the old initial
+ // window size and this one.
+ delta := int32(s.Val) - int32(cc.initialWindowSize)
+ for _, cs := range cc.streams {
+ cs.flow.add(delta)
+ }
+ cc.cond.Broadcast()
+
+ cc.initialWindowSize = s.Val
+ default:
+ // TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
+ cc.vlogf("Unhandled Setting: %v", s)
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+
+ cc.fr.WriteSettingsAck()
+ cc.bw.Flush()
+ return cc.werr
+}
+
+func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
+ cc := rl.cc
+ cs := cc.streamByID(f.StreamID, false)
+ if f.StreamID != 0 && cs == nil {
+ return nil
+ }
+
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+
+ fl := &cc.flow
+ if cs != nil {
+ fl = &cs.flow
+ }
+ if !fl.add(int32(f.Increment)) {
+ return ConnectionError(ErrCodeFlowControl)
+ }
+ cc.cond.Broadcast()
+ return nil
+}
+
+func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
+ cs := rl.cc.streamByID(f.StreamID, true)
+ if cs == nil {
+ // TODO: return error if server tries to RST_STEAM an idle stream
+ return nil
+ }
+ select {
+ case <-cs.peerReset:
+ // Already reset.
+ // This is the only goroutine
+ // which closes this, so there
+ // isn't a race.
+ default:
+ err := streamError(cs.ID, f.ErrCode)
+ cs.resetErr = err
+ close(cs.peerReset)
+ cs.bufPipe.CloseWithError(err)
+ cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
+ }
+ delete(rl.activeRes, cs.ID)
+ return nil
+}
+
+// Ping sends a PING frame to the server and waits for the ack.
+// Public implementation is in go17.go and not_go17.go
+func (cc *ClientConn) ping(ctx contextContext) error {
+ c := make(chan struct{})
+ // Generate a random payload
+ var p [8]byte
+ for {
+ if _, err := rand.Read(p[:]); err != nil {
+ return err
+ }
+ cc.mu.Lock()
+ // check for dup before insert
+ if _, found := cc.pings[p]; !found {
+ cc.pings[p] = c
+ cc.mu.Unlock()
+ break
+ }
+ cc.mu.Unlock()
+ }
+ cc.wmu.Lock()
+ if err := cc.fr.WritePing(false, p); err != nil {
+ cc.wmu.Unlock()
+ return err
+ }
+ if err := cc.bw.Flush(); err != nil {
+ cc.wmu.Unlock()
+ return err
+ }
+ cc.wmu.Unlock()
+ select {
+ case <-c:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-cc.readerDone:
+ // connection closed
+ return cc.readerErr
+ }
+}
+
+func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
+ if f.IsAck() {
+ cc := rl.cc
+ cc.mu.Lock()
+ defer cc.mu.Unlock()
+ // If ack, notify listener if any
+ if c, ok := cc.pings[f.Data]; ok {
+ close(c)
+ delete(cc.pings, f.Data)
+ }
+ return nil
+ }
+ cc := rl.cc
+ cc.wmu.Lock()
+ defer cc.wmu.Unlock()
+ if err := cc.fr.WritePing(true, f.Data); err != nil {
+ return err
+ }
+ return cc.bw.Flush()
+}
+
+func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
+ // We told the peer we don't want them.
+ // Spec says:
+ // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
+ // setting of the peer endpoint is set to 0. An endpoint that
+ // has set this setting and has received acknowledgement MUST
+ // treat the receipt of a PUSH_PROMISE frame as a connection
+ // error (Section 5.4.1) of type PROTOCOL_ERROR."
+ return ConnectionError(ErrCodeProtocol)
+}
+
+func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
+ // TODO: map err to more interesting error codes, once the
+ // HTTP community comes up with some. But currently for
+ // RST_STREAM there's no equivalent to GOAWAY frame's debug
+ // data, and the error codes are all pretty vague ("cancel").
+ cc.wmu.Lock()
+ cc.fr.WriteRSTStream(streamID, code)
+ cc.bw.Flush()
+ cc.wmu.Unlock()
+}
+
+var (
+ errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
+ errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers")
+)
+
+func (cc *ClientConn) logf(format string, args ...interface{}) {
+ cc.t.logf(format, args...)
+}
+
+func (cc *ClientConn) vlogf(format string, args ...interface{}) {
+ cc.t.vlogf(format, args...)
+}
+
+func (t *Transport) vlogf(format string, args ...interface{}) {
+ if VerboseLogs {
+ t.logf(format, args...)
+ }
+}
+
+func (t *Transport) logf(format string, args ...interface{}) {
+ log.Printf(format, args...)
+}
+
+var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
+
+func strSliceContains(ss []string, s string) bool {
+ for _, v := range ss {
+ if v == s {
+ return true
+ }
+ }
+ return false
+}
+
+type erringRoundTripper struct{ err error }
+
+func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
+
+// gzipReader wraps a response body so it can lazily
+// call gzip.NewReader on the first call to Read
+type gzipReader struct {
+ body io.ReadCloser // underlying Response.Body
+ zr *gzip.Reader // lazily-initialized gzip reader
+ zerr error // sticky error
+}
+
+func (gz *gzipReader) Read(p []byte) (n int, err error) {
+ if gz.zerr != nil {
+ return 0, gz.zerr
+ }
+ if gz.zr == nil {
+ gz.zr, err = gzip.NewReader(gz.body)
+ if err != nil {
+ gz.zerr = err
+ return 0, err
+ }
+ }
+ return gz.zr.Read(p)
+}
+
+func (gz *gzipReader) Close() error {
+ return gz.body.Close()
+}
+
+type errorReader struct{ err error }
+
+func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
+
+// bodyWriterState encapsulates various state around the Transport's writing
+// of the request body, particularly regarding doing delayed writes of the body
+// when the request contains "Expect: 100-continue".
+type bodyWriterState struct {
+ cs *clientStream
+ timer *time.Timer // if non-nil, we're doing a delayed write
+ fnonce *sync.Once // to call fn with
+ fn func() // the code to run in the goroutine, writing the body
+ resc chan error // result of fn's execution
+ delay time.Duration // how long we should delay a delayed write for
+}
+
+func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) {
+ s.cs = cs
+ if body == nil {
+ return
+ }
+ resc := make(chan error, 1)
+ s.resc = resc
+ s.fn = func() {
+ cs.cc.mu.Lock()
+ cs.startedWrite = true
+ cs.cc.mu.Unlock()
+ resc <- cs.writeRequestBody(body, cs.req.Body)
+ }
+ s.delay = t.expectContinueTimeout()
+ if s.delay == 0 ||
+ !httplex.HeaderValuesContainsToken(
+ cs.req.Header["Expect"],
+ "100-continue") {
+ return
+ }
+ s.fnonce = new(sync.Once)
+
+ // Arm the timer with a very large duration, which we'll
+ // intentionally lower later. It has to be large now because
+ // we need a handle to it before writing the headers, but the
+ // s.delay value is defined to not start until after the
+ // request headers were written.
+ const hugeDuration = 365 * 24 * time.Hour
+ s.timer = time.AfterFunc(hugeDuration, func() {
+ s.fnonce.Do(s.fn)
+ })
+ return
+}
+
+func (s bodyWriterState) cancel() {
+ if s.timer != nil {
+ s.timer.Stop()
+ }
+}
+
+func (s bodyWriterState) on100() {
+ if s.timer == nil {
+ // If we didn't do a delayed write, ignore the server's
+ // bogus 100 continue response.
+ return
+ }
+ s.timer.Stop()
+ go func() { s.fnonce.Do(s.fn) }()
+}
+
+// scheduleBodyWrite starts writing the body, either immediately (in
+// the common case) or after the delay timeout. It should not be
+// called until after the headers have been written.
+func (s bodyWriterState) scheduleBodyWrite() {
+ if s.timer == nil {
+ // We're not doing a delayed write (see
+ // getBodyWriterState), so just start the writing
+ // goroutine immediately.
+ go s.fn()
+ return
+ }
+ traceWait100Continue(s.cs.trace)
+ if s.timer.Stop() {
+ s.timer.Reset(s.delay)
+ }
+}
+
+// isConnectionCloseRequest reports whether req should use its own
+// connection for a single request and then close the connection.
+func isConnectionCloseRequest(req *http.Request) bool {
+ return req.Close || httplex.HeaderValuesContainsToken(req.Header["Connection"], "close")
+}
diff --git a/vendor/golang.org/x/net/http2/write.go b/vendor/golang.org/x/net/http2/write.go
new file mode 100644
index 0000000..6b0dfae
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/write.go
@@ -0,0 +1,370 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package http2
+
+import (
+ "bytes"
+ "fmt"
+ "log"
+ "net/http"
+ "net/url"
+ "time"
+
+ "golang.org/x/net/http2/hpack"
+ "golang.org/x/net/lex/httplex"
+)
+
+// writeFramer is implemented by any type that is used to write frames.
+type writeFramer interface {
+ writeFrame(writeContext) error
+
+ // staysWithinBuffer reports whether this writer promises that
+ // it will only write less than or equal to size bytes, and it
+ // won't Flush the write context.
+ staysWithinBuffer(size int) bool
+}
+
+// writeContext is the interface needed by the various frame writer
+// types below. All the writeFrame methods below are scheduled via the
+// frame writing scheduler (see writeScheduler in writesched.go).
+//
+// This interface is implemented by *serverConn.
+//
+// TODO: decide whether to a) use this in the client code (which didn't
+// end up using this yet, because it has a simpler design, not
+// currently implementing priorities), or b) delete this and
+// make the server code a bit more concrete.
+type writeContext interface {
+ Framer() *Framer
+ Flush() error
+ CloseConn() error
+ // HeaderEncoder returns an HPACK encoder that writes to the
+ // returned buffer.
+ HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
+}
+
+// writeEndsStream reports whether w writes a frame that will transition
+// the stream to a half-closed local state. This returns false for RST_STREAM,
+// which closes the entire stream (not just the local half).
+func writeEndsStream(w writeFramer) bool {
+ switch v := w.(type) {
+ case *writeData:
+ return v.endStream
+ case *writeResHeaders:
+ return v.endStream
+ case nil:
+ // This can only happen if the caller reuses w after it's
+ // been intentionally nil'ed out to prevent use. Keep this
+ // here to catch future refactoring breaking it.
+ panic("writeEndsStream called on nil writeFramer")
+ }
+ return false
+}
+
+type flushFrameWriter struct{}
+
+func (flushFrameWriter) writeFrame(ctx writeContext) error {
+ return ctx.Flush()
+}
+
+func (flushFrameWriter) staysWithinBuffer(max int) bool { return false }
+
+type writeSettings []Setting
+
+func (s writeSettings) staysWithinBuffer(max int) bool {
+ const settingSize = 6 // uint16 + uint32
+ return frameHeaderLen+settingSize*len(s) <= max
+
+}
+
+func (s writeSettings) writeFrame(ctx writeContext) error {
+ return ctx.Framer().WriteSettings([]Setting(s)...)
+}
+
+type writeGoAway struct {
+ maxStreamID uint32
+ code ErrCode
+}
+
+func (p *writeGoAway) writeFrame(ctx writeContext) error {
+ err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil)
+ if p.code != 0 {
+ ctx.Flush() // ignore error: we're hanging up on them anyway
+ time.Sleep(50 * time.Millisecond)
+ ctx.CloseConn()
+ }
+ return err
+}
+
+func (*writeGoAway) staysWithinBuffer(max int) bool { return false } // flushes
+
+type writeData struct {
+ streamID uint32
+ p []byte
+ endStream bool
+}
+
+func (w *writeData) String() string {
+ return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream)
+}
+
+func (w *writeData) writeFrame(ctx writeContext) error {
+ return ctx.Framer().WriteData(w.streamID, w.endStream, w.p)
+}
+
+func (w *writeData) staysWithinBuffer(max int) bool {
+ return frameHeaderLen+len(w.p) <= max
+}
+
+// handlerPanicRST is the message sent from handler goroutines when
+// the handler panics.
+type handlerPanicRST struct {
+ StreamID uint32
+}
+
+func (hp handlerPanicRST) writeFrame(ctx writeContext) error {
+ return ctx.Framer().WriteRSTStream(hp.StreamID, ErrCodeInternal)
+}
+
+func (hp handlerPanicRST) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
+
+func (se StreamError) writeFrame(ctx writeContext) error {
+ return ctx.Framer().WriteRSTStream(se.StreamID, se.Code)
+}
+
+func (se StreamError) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
+
+type writePingAck struct{ pf *PingFrame }
+
+func (w writePingAck) writeFrame(ctx writeContext) error {
+ return ctx.Framer().WritePing(true, w.pf.Data)
+}
+
+func (w writePingAck) staysWithinBuffer(max int) bool { return frameHeaderLen+len(w.pf.Data) <= max }
+
+type writeSettingsAck struct{}
+
+func (writeSettingsAck) writeFrame(ctx writeContext) error {
+ return ctx.Framer().WriteSettingsAck()
+}
+
+func (writeSettingsAck) staysWithinBuffer(max int) bool { return frameHeaderLen <= max }
+
+// splitHeaderBlock splits headerBlock into fragments so that each fragment fits
+// in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true
+// for the first/last fragment, respectively.
+func splitHeaderBlock(ctx writeContext, headerBlock []byte, fn func(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error) error {
+ // For now we're lazy and just pick the minimum MAX_FRAME_SIZE
+ // that all peers must support (16KB). Later we could care
+ // more and send larger frames if the peer advertised it, but
+ // there's little point. Most headers are small anyway (so we
+ // generally won't have CONTINUATION frames), and extra frames
+ // only waste 9 bytes anyway.
+ const maxFrameSize = 16384
+
+ first := true
+ for len(headerBlock) > 0 {
+ frag := headerBlock
+ if len(frag) > maxFrameSize {
+ frag = frag[:maxFrameSize]
+ }
+ headerBlock = headerBlock[len(frag):]
+ if err := fn(ctx, frag, first, len(headerBlock) == 0); err != nil {
+ return err
+ }
+ first = false
+ }
+ return nil
+}
+
+// writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames
+// for HTTP response headers or trailers from a server handler.
+type writeResHeaders struct {
+ streamID uint32
+ httpResCode int // 0 means no ":status" line
+ h http.Header // may be nil
+ trailers []string // if non-nil, which keys of h to write. nil means all.
+ endStream bool
+
+ date string
+ contentType string
+ contentLength string
+}
+
+func encKV(enc *hpack.Encoder, k, v string) {
+ if VerboseLogs {
+ log.Printf("http2: server encoding header %q = %q", k, v)
+ }
+ enc.WriteField(hpack.HeaderField{Name: k, Value: v})
+}
+
+func (w *writeResHeaders) staysWithinBuffer(max int) bool {
+ // TODO: this is a common one. It'd be nice to return true
+ // here and get into the fast path if we could be clever and
+ // calculate the size fast enough, or at least a conservative
+ // uppper bound that usually fires. (Maybe if w.h and
+ // w.trailers are nil, so we don't need to enumerate it.)
+ // Otherwise I'm afraid that just calculating the length to
+ // answer this question would be slower than the ~2µs benefit.
+ return false
+}
+
+func (w *writeResHeaders) writeFrame(ctx writeContext) error {
+ enc, buf := ctx.HeaderEncoder()
+ buf.Reset()
+
+ if w.httpResCode != 0 {
+ encKV(enc, ":status", httpCodeString(w.httpResCode))
+ }
+
+ encodeHeaders(enc, w.h, w.trailers)
+
+ if w.contentType != "" {
+ encKV(enc, "content-type", w.contentType)
+ }
+ if w.contentLength != "" {
+ encKV(enc, "content-length", w.contentLength)
+ }
+ if w.date != "" {
+ encKV(enc, "date", w.date)
+ }
+
+ headerBlock := buf.Bytes()
+ if len(headerBlock) == 0 && w.trailers == nil {
+ panic("unexpected empty hpack")
+ }
+
+ return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
+}
+
+func (w *writeResHeaders) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error {
+ if firstFrag {
+ return ctx.Framer().WriteHeaders(HeadersFrameParam{
+ StreamID: w.streamID,
+ BlockFragment: frag,
+ EndStream: w.endStream,
+ EndHeaders: lastFrag,
+ })
+ } else {
+ return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
+ }
+}
+
+// writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames.
+type writePushPromise struct {
+ streamID uint32 // pusher stream
+ method string // for :method
+ url *url.URL // for :scheme, :authority, :path
+ h http.Header
+
+ // Creates an ID for a pushed stream. This runs on serveG just before
+ // the frame is written. The returned ID is copied to promisedID.
+ allocatePromisedID func() (uint32, error)
+ promisedID uint32
+}
+
+func (w *writePushPromise) staysWithinBuffer(max int) bool {
+ // TODO: see writeResHeaders.staysWithinBuffer
+ return false
+}
+
+func (w *writePushPromise) writeFrame(ctx writeContext) error {
+ enc, buf := ctx.HeaderEncoder()
+ buf.Reset()
+
+ encKV(enc, ":method", w.method)
+ encKV(enc, ":scheme", w.url.Scheme)
+ encKV(enc, ":authority", w.url.Host)
+ encKV(enc, ":path", w.url.RequestURI())
+ encodeHeaders(enc, w.h, nil)
+
+ headerBlock := buf.Bytes()
+ if len(headerBlock) == 0 {
+ panic("unexpected empty hpack")
+ }
+
+ return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
+}
+
+func (w *writePushPromise) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error {
+ if firstFrag {
+ return ctx.Framer().WritePushPromise(PushPromiseParam{
+ StreamID: w.streamID,
+ PromiseID: w.promisedID,
+ BlockFragment: frag,
+ EndHeaders: lastFrag,
+ })
+ } else {
+ return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
+ }
+}
+
+type write100ContinueHeadersFrame struct {
+ streamID uint32
+}
+
+func (w write100ContinueHeadersFrame) writeFrame(ctx writeContext) error {
+ enc, buf := ctx.HeaderEncoder()
+ buf.Reset()
+ encKV(enc, ":status", "100")
+ return ctx.Framer().WriteHeaders(HeadersFrameParam{
+ StreamID: w.streamID,
+ BlockFragment: buf.Bytes(),
+ EndStream: false,
+ EndHeaders: true,
+ })
+}
+
+func (w write100ContinueHeadersFrame) staysWithinBuffer(max int) bool {
+ // Sloppy but conservative:
+ return 9+2*(len(":status")+len("100")) <= max
+}
+
+type writeWindowUpdate struct {
+ streamID uint32 // or 0 for conn-level
+ n uint32
+}
+
+func (wu writeWindowUpdate) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
+
+func (wu writeWindowUpdate) writeFrame(ctx writeContext) error {
+ return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n)
+}
+
+// encodeHeaders encodes an http.Header. If keys is not nil, then (k, h[k])
+// is encoded only only if k is in keys.
+func encodeHeaders(enc *hpack.Encoder, h http.Header, keys []string) {
+ if keys == nil {
+ sorter := sorterPool.Get().(*sorter)
+ // Using defer here, since the returned keys from the
+ // sorter.Keys method is only valid until the sorter
+ // is returned:
+ defer sorterPool.Put(sorter)
+ keys = sorter.Keys(h)
+ }
+ for _, k := range keys {
+ vv := h[k]
+ k = lowerHeader(k)
+ if !validWireHeaderFieldName(k) {
+ // Skip it as backup paranoia. Per
+ // golang.org/issue/14048, these should
+ // already be rejected at a higher level.
+ continue
+ }
+ isTE := k == "transfer-encoding"
+ for _, v := range vv {
+ if !httplex.ValidHeaderFieldValue(v) {
+ // TODO: return an error? golang.org/issue/14048
+ // For now just omit it.
+ continue
+ }
+ // TODO: more of "8.1.2.2 Connection-Specific Header Fields"
+ if isTE && v != "trailers" {
+ continue
+ }
+ encKV(enc, k, v)
+ }
+ }
+}
diff --git a/vendor/golang.org/x/net/http2/writesched.go b/vendor/golang.org/x/net/http2/writesched.go
new file mode 100644
index 0000000..4fe3073
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/writesched.go
@@ -0,0 +1,242 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package http2
+
+import "fmt"
+
+// WriteScheduler is the interface implemented by HTTP/2 write schedulers.
+// Methods are never called concurrently.
+type WriteScheduler interface {
+ // OpenStream opens a new stream in the write scheduler.
+ // It is illegal to call this with streamID=0 or with a streamID that is
+ // already open -- the call may panic.
+ OpenStream(streamID uint32, options OpenStreamOptions)
+
+ // CloseStream closes a stream in the write scheduler. Any frames queued on
+ // this stream should be discarded. It is illegal to call this on a stream
+ // that is not open -- the call may panic.
+ CloseStream(streamID uint32)
+
+ // AdjustStream adjusts the priority of the given stream. This may be called
+ // on a stream that has not yet been opened or has been closed. Note that
+ // RFC 7540 allows PRIORITY frames to be sent on streams in any state. See:
+ // https://tools.ietf.org/html/rfc7540#section-5.1
+ AdjustStream(streamID uint32, priority PriorityParam)
+
+ // Push queues a frame in the scheduler. In most cases, this will not be
+ // called with wr.StreamID()!=0 unless that stream is currently open. The one
+ // exception is RST_STREAM frames, which may be sent on idle or closed streams.
+ Push(wr FrameWriteRequest)
+
+ // Pop dequeues the next frame to write. Returns false if no frames can
+ // be written. Frames with a given wr.StreamID() are Pop'd in the same
+ // order they are Push'd.
+ Pop() (wr FrameWriteRequest, ok bool)
+}
+
+// OpenStreamOptions specifies extra options for WriteScheduler.OpenStream.
+type OpenStreamOptions struct {
+ // PusherID is zero if the stream was initiated by the client. Otherwise,
+ // PusherID names the stream that pushed the newly opened stream.
+ PusherID uint32
+}
+
+// FrameWriteRequest is a request to write a frame.
+type FrameWriteRequest struct {
+ // write is the interface value that does the writing, once the
+ // WriteScheduler has selected this frame to write. The write
+ // functions are all defined in write.go.
+ write writeFramer
+
+ // stream is the stream on which this frame will be written.
+ // nil for non-stream frames like PING and SETTINGS.
+ stream *stream
+
+ // done, if non-nil, must be a buffered channel with space for
+ // 1 message and is sent the return value from write (or an
+ // earlier error) when the frame has been written.
+ done chan error
+}
+
+// StreamID returns the id of the stream this frame will be written to.
+// 0 is used for non-stream frames such as PING and SETTINGS.
+func (wr FrameWriteRequest) StreamID() uint32 {
+ if wr.stream == nil {
+ if se, ok := wr.write.(StreamError); ok {
+ // (*serverConn).resetStream doesn't set
+ // stream because it doesn't necessarily have
+ // one. So special case this type of write
+ // message.
+ return se.StreamID
+ }
+ return 0
+ }
+ return wr.stream.id
+}
+
+// DataSize returns the number of flow control bytes that must be consumed
+// to write this entire frame. This is 0 for non-DATA frames.
+func (wr FrameWriteRequest) DataSize() int {
+ if wd, ok := wr.write.(*writeData); ok {
+ return len(wd.p)
+ }
+ return 0
+}
+
+// Consume consumes min(n, available) bytes from this frame, where available
+// is the number of flow control bytes available on the stream. Consume returns
+// 0, 1, or 2 frames, where the integer return value gives the number of frames
+// returned.
+//
+// If flow control prevents consuming any bytes, this returns (_, _, 0). If
+// the entire frame was consumed, this returns (wr, _, 1). Otherwise, this
+// returns (consumed, rest, 2), where 'consumed' contains the consumed bytes and
+// 'rest' contains the remaining bytes. The consumed bytes are deducted from the
+// underlying stream's flow control budget.
+func (wr FrameWriteRequest) Consume(n int32) (FrameWriteRequest, FrameWriteRequest, int) {
+ var empty FrameWriteRequest
+
+ // Non-DATA frames are always consumed whole.
+ wd, ok := wr.write.(*writeData)
+ if !ok || len(wd.p) == 0 {
+ return wr, empty, 1
+ }
+
+ // Might need to split after applying limits.
+ allowed := wr.stream.flow.available()
+ if n < allowed {
+ allowed = n
+ }
+ if wr.stream.sc.maxFrameSize < allowed {
+ allowed = wr.stream.sc.maxFrameSize
+ }
+ if allowed <= 0 {
+ return empty, empty, 0
+ }
+ if len(wd.p) > int(allowed) {
+ wr.stream.flow.take(allowed)
+ consumed := FrameWriteRequest{
+ stream: wr.stream,
+ write: &writeData{
+ streamID: wd.streamID,
+ p: wd.p[:allowed],
+ // Even if the original had endStream set, there
+ // are bytes remaining because len(wd.p) > allowed,
+ // so we know endStream is false.
+ endStream: false,
+ },
+ // Our caller is blocking on the final DATA frame, not
+ // this intermediate frame, so no need to wait.
+ done: nil,
+ }
+ rest := FrameWriteRequest{
+ stream: wr.stream,
+ write: &writeData{
+ streamID: wd.streamID,
+ p: wd.p[allowed:],
+ endStream: wd.endStream,
+ },
+ done: wr.done,
+ }
+ return consumed, rest, 2
+ }
+
+ // The frame is consumed whole.
+ // NB: This cast cannot overflow because allowed is <= math.MaxInt32.
+ wr.stream.flow.take(int32(len(wd.p)))
+ return wr, empty, 1
+}
+
+// String is for debugging only.
+func (wr FrameWriteRequest) String() string {
+ var des string
+ if s, ok := wr.write.(fmt.Stringer); ok {
+ des = s.String()
+ } else {
+ des = fmt.Sprintf("%T", wr.write)
+ }
+ return fmt.Sprintf("[FrameWriteRequest stream=%d, ch=%v, writer=%v]", wr.StreamID(), wr.done != nil, des)
+}
+
+// replyToWriter sends err to wr.done and panics if the send must block
+// This does nothing if wr.done is nil.
+func (wr *FrameWriteRequest) replyToWriter(err error) {
+ if wr.done == nil {
+ return
+ }
+ select {
+ case wr.done <- err:
+ default:
+ panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wr.write))
+ }
+ wr.write = nil // prevent use (assume it's tainted after wr.done send)
+}
+
+// writeQueue is used by implementations of WriteScheduler.
+type writeQueue struct {
+ s []FrameWriteRequest
+}
+
+func (q *writeQueue) empty() bool { return len(q.s) == 0 }
+
+func (q *writeQueue) push(wr FrameWriteRequest) {
+ q.s = append(q.s, wr)
+}
+
+func (q *writeQueue) shift() FrameWriteRequest {
+ if len(q.s) == 0 {
+ panic("invalid use of queue")
+ }
+ wr := q.s[0]
+ // TODO: less copy-happy queue.
+ copy(q.s, q.s[1:])
+ q.s[len(q.s)-1] = FrameWriteRequest{}
+ q.s = q.s[:len(q.s)-1]
+ return wr
+}
+
+// consume consumes up to n bytes from q.s[0]. If the frame is
+// entirely consumed, it is removed from the queue. If the frame
+// is partially consumed, the frame is kept with the consumed
+// bytes removed. Returns true iff any bytes were consumed.
+func (q *writeQueue) consume(n int32) (FrameWriteRequest, bool) {
+ if len(q.s) == 0 {
+ return FrameWriteRequest{}, false
+ }
+ consumed, rest, numresult := q.s[0].Consume(n)
+ switch numresult {
+ case 0:
+ return FrameWriteRequest{}, false
+ case 1:
+ q.shift()
+ case 2:
+ q.s[0] = rest
+ }
+ return consumed, true
+}
+
+type writeQueuePool []*writeQueue
+
+// put inserts an unused writeQueue into the pool.
+func (p *writeQueuePool) put(q *writeQueue) {
+ for i := range q.s {
+ q.s[i] = FrameWriteRequest{}
+ }
+ q.s = q.s[:0]
+ *p = append(*p, q)
+}
+
+// get returns an empty writeQueue.
+func (p *writeQueuePool) get() *writeQueue {
+ ln := len(*p)
+ if ln == 0 {
+ return new(writeQueue)
+ }
+ x := ln - 1
+ q := (*p)[x]
+ (*p)[x] = nil
+ *p = (*p)[:x]
+ return q
+}
diff --git a/vendor/golang.org/x/net/http2/writesched_priority.go b/vendor/golang.org/x/net/http2/writesched_priority.go
new file mode 100644
index 0000000..848fed6
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/writesched_priority.go
@@ -0,0 +1,452 @@
+// 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 http2
+
+import (
+ "fmt"
+ "math"
+ "sort"
+)
+
+// RFC 7540, Section 5.3.5: the default weight is 16.
+const priorityDefaultWeight = 15 // 16 = 15 + 1
+
+// PriorityWriteSchedulerConfig configures a priorityWriteScheduler.
+type PriorityWriteSchedulerConfig struct {
+ // MaxClosedNodesInTree controls the maximum number of closed streams to
+ // retain in the priority tree. Setting this to zero saves a small amount
+ // of memory at the cost of performance.
+ //
+ // See RFC 7540, Section 5.3.4:
+ // "It is possible for a stream to become closed while prioritization
+ // information ... is in transit. ... This potentially creates suboptimal
+ // prioritization, since the stream could be given a priority that is
+ // different from what is intended. To avoid these problems, an endpoint
+ // SHOULD retain stream prioritization state for a period after streams
+ // become closed. The longer state is retained, the lower the chance that
+ // streams are assigned incorrect or default priority values."
+ MaxClosedNodesInTree int
+
+ // MaxIdleNodesInTree controls the maximum number of idle streams to
+ // retain in the priority tree. Setting this to zero saves a small amount
+ // of memory at the cost of performance.
+ //
+ // See RFC 7540, Section 5.3.4:
+ // Similarly, streams that are in the "idle" state can be assigned
+ // priority or become a parent of other streams. This allows for the
+ // creation of a grouping node in the dependency tree, which enables
+ // more flexible expressions of priority. Idle streams begin with a
+ // default priority (Section 5.3.5).
+ MaxIdleNodesInTree int
+
+ // ThrottleOutOfOrderWrites enables write throttling to help ensure that
+ // data is delivered in priority order. This works around a race where
+ // stream B depends on stream A and both streams are about to call Write
+ // to queue DATA frames. If B wins the race, a naive scheduler would eagerly
+ // write as much data from B as possible, but this is suboptimal because A
+ // is a higher-priority stream. With throttling enabled, we write a small
+ // amount of data from B to minimize the amount of bandwidth that B can
+ // steal from A.
+ ThrottleOutOfOrderWrites bool
+}
+
+// NewPriorityWriteScheduler constructs a WriteScheduler that schedules
+// frames by following HTTP/2 priorities as described in RFC 7540 Section 5.3.
+// If cfg is nil, default options are used.
+func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler {
+ if cfg == nil {
+ // For justification of these defaults, see:
+ // https://docs.google.com/document/d/1oLhNg1skaWD4_DtaoCxdSRN5erEXrH-KnLrMwEpOtFY
+ cfg = &PriorityWriteSchedulerConfig{
+ MaxClosedNodesInTree: 10,
+ MaxIdleNodesInTree: 10,
+ ThrottleOutOfOrderWrites: false,
+ }
+ }
+
+ ws := &priorityWriteScheduler{
+ nodes: make(map[uint32]*priorityNode),
+ maxClosedNodesInTree: cfg.MaxClosedNodesInTree,
+ maxIdleNodesInTree: cfg.MaxIdleNodesInTree,
+ enableWriteThrottle: cfg.ThrottleOutOfOrderWrites,
+ }
+ ws.nodes[0] = &ws.root
+ if cfg.ThrottleOutOfOrderWrites {
+ ws.writeThrottleLimit = 1024
+ } else {
+ ws.writeThrottleLimit = math.MaxInt32
+ }
+ return ws
+}
+
+type priorityNodeState int
+
+const (
+ priorityNodeOpen priorityNodeState = iota
+ priorityNodeClosed
+ priorityNodeIdle
+)
+
+// priorityNode is a node in an HTTP/2 priority tree.
+// Each node is associated with a single stream ID.
+// See RFC 7540, Section 5.3.
+type priorityNode struct {
+ q writeQueue // queue of pending frames to write
+ id uint32 // id of the stream, or 0 for the root of the tree
+ weight uint8 // the actual weight is weight+1, so the value is in [1,256]
+ state priorityNodeState // open | closed | idle
+ bytes int64 // number of bytes written by this node, or 0 if closed
+ subtreeBytes int64 // sum(node.bytes) of all nodes in this subtree
+
+ // These links form the priority tree.
+ parent *priorityNode
+ kids *priorityNode // start of the kids list
+ prev, next *priorityNode // doubly-linked list of siblings
+}
+
+func (n *priorityNode) setParent(parent *priorityNode) {
+ if n == parent {
+ panic("setParent to self")
+ }
+ if n.parent == parent {
+ return
+ }
+ // Unlink from current parent.
+ if parent := n.parent; parent != nil {
+ if n.prev == nil {
+ parent.kids = n.next
+ } else {
+ n.prev.next = n.next
+ }
+ if n.next != nil {
+ n.next.prev = n.prev
+ }
+ }
+ // Link to new parent.
+ // If parent=nil, remove n from the tree.
+ // Always insert at the head of parent.kids (this is assumed by walkReadyInOrder).
+ n.parent = parent
+ if parent == nil {
+ n.next = nil
+ n.prev = nil
+ } else {
+ n.next = parent.kids
+ n.prev = nil
+ if n.next != nil {
+ n.next.prev = n
+ }
+ parent.kids = n
+ }
+}
+
+func (n *priorityNode) addBytes(b int64) {
+ n.bytes += b
+ for ; n != nil; n = n.parent {
+ n.subtreeBytes += b
+ }
+}
+
+// walkReadyInOrder iterates over the tree in priority order, calling f for each node
+// with a non-empty write queue. When f returns true, this funcion returns true and the
+// walk halts. tmp is used as scratch space for sorting.
+//
+// f(n, openParent) takes two arguments: the node to visit, n, and a bool that is true
+// if any ancestor p of n is still open (ignoring the root node).
+func (n *priorityNode) walkReadyInOrder(openParent bool, tmp *[]*priorityNode, f func(*priorityNode, bool) bool) bool {
+ if !n.q.empty() && f(n, openParent) {
+ return true
+ }
+ if n.kids == nil {
+ return false
+ }
+
+ // Don't consider the root "open" when updating openParent since
+ // we can't send data frames on the root stream (only control frames).
+ if n.id != 0 {
+ openParent = openParent || (n.state == priorityNodeOpen)
+ }
+
+ // Common case: only one kid or all kids have the same weight.
+ // Some clients don't use weights; other clients (like web browsers)
+ // use mostly-linear priority trees.
+ w := n.kids.weight
+ needSort := false
+ for k := n.kids.next; k != nil; k = k.next {
+ if k.weight != w {
+ needSort = true
+ break
+ }
+ }
+ if !needSort {
+ for k := n.kids; k != nil; k = k.next {
+ if k.walkReadyInOrder(openParent, tmp, f) {
+ return true
+ }
+ }
+ return false
+ }
+
+ // Uncommon case: sort the child nodes. We remove the kids from the parent,
+ // then re-insert after sorting so we can reuse tmp for future sort calls.
+ *tmp = (*tmp)[:0]
+ for n.kids != nil {
+ *tmp = append(*tmp, n.kids)
+ n.kids.setParent(nil)
+ }
+ sort.Sort(sortPriorityNodeSiblings(*tmp))
+ for i := len(*tmp) - 1; i >= 0; i-- {
+ (*tmp)[i].setParent(n) // setParent inserts at the head of n.kids
+ }
+ for k := n.kids; k != nil; k = k.next {
+ if k.walkReadyInOrder(openParent, tmp, f) {
+ return true
+ }
+ }
+ return false
+}
+
+type sortPriorityNodeSiblings []*priorityNode
+
+func (z sortPriorityNodeSiblings) Len() int { return len(z) }
+func (z sortPriorityNodeSiblings) Swap(i, k int) { z[i], z[k] = z[k], z[i] }
+func (z sortPriorityNodeSiblings) Less(i, k int) bool {
+ // Prefer the subtree that has sent fewer bytes relative to its weight.
+ // See sections 5.3.2 and 5.3.4.
+ wi, bi := float64(z[i].weight+1), float64(z[i].subtreeBytes)
+ wk, bk := float64(z[k].weight+1), float64(z[k].subtreeBytes)
+ if bi == 0 && bk == 0 {
+ return wi >= wk
+ }
+ if bk == 0 {
+ return false
+ }
+ return bi/bk <= wi/wk
+}
+
+type priorityWriteScheduler struct {
+ // root is the root of the priority tree, where root.id = 0.
+ // The root queues control frames that are not associated with any stream.
+ root priorityNode
+
+ // nodes maps stream ids to priority tree nodes.
+ nodes map[uint32]*priorityNode
+
+ // maxID is the maximum stream id in nodes.
+ maxID uint32
+
+ // lists of nodes that have been closed or are idle, but are kept in
+ // the tree for improved prioritization. When the lengths exceed either
+ // maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded.
+ closedNodes, idleNodes []*priorityNode
+
+ // From the config.
+ maxClosedNodesInTree int
+ maxIdleNodesInTree int
+ writeThrottleLimit int32
+ enableWriteThrottle bool
+
+ // tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations.
+ tmp []*priorityNode
+
+ // pool of empty queues for reuse.
+ queuePool writeQueuePool
+}
+
+func (ws *priorityWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) {
+ // The stream may be currently idle but cannot be opened or closed.
+ if curr := ws.nodes[streamID]; curr != nil {
+ if curr.state != priorityNodeIdle {
+ panic(fmt.Sprintf("stream %d already opened", streamID))
+ }
+ curr.state = priorityNodeOpen
+ return
+ }
+
+ // RFC 7540, Section 5.3.5:
+ // "All streams are initially assigned a non-exclusive dependency on stream 0x0.
+ // Pushed streams initially depend on their associated stream. In both cases,
+ // streams are assigned a default weight of 16."
+ parent := ws.nodes[options.PusherID]
+ if parent == nil {
+ parent = &ws.root
+ }
+ n := &priorityNode{
+ q: *ws.queuePool.get(),
+ id: streamID,
+ weight: priorityDefaultWeight,
+ state: priorityNodeOpen,
+ }
+ n.setParent(parent)
+ ws.nodes[streamID] = n
+ if streamID > ws.maxID {
+ ws.maxID = streamID
+ }
+}
+
+func (ws *priorityWriteScheduler) CloseStream(streamID uint32) {
+ if streamID == 0 {
+ panic("violation of WriteScheduler interface: cannot close stream 0")
+ }
+ if ws.nodes[streamID] == nil {
+ panic(fmt.Sprintf("violation of WriteScheduler interface: unknown stream %d", streamID))
+ }
+ if ws.nodes[streamID].state != priorityNodeOpen {
+ panic(fmt.Sprintf("violation of WriteScheduler interface: stream %d already closed", streamID))
+ }
+
+ n := ws.nodes[streamID]
+ n.state = priorityNodeClosed
+ n.addBytes(-n.bytes)
+
+ q := n.q
+ ws.queuePool.put(&q)
+ n.q.s = nil
+ if ws.maxClosedNodesInTree > 0 {
+ ws.addClosedOrIdleNode(&ws.closedNodes, ws.maxClosedNodesInTree, n)
+ } else {
+ ws.removeNode(n)
+ }
+}
+
+func (ws *priorityWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) {
+ if streamID == 0 {
+ panic("adjustPriority on root")
+ }
+
+ // If streamID does not exist, there are two cases:
+ // - A closed stream that has been removed (this will have ID <= maxID)
+ // - An idle stream that is being used for "grouping" (this will have ID > maxID)
+ n := ws.nodes[streamID]
+ if n == nil {
+ if streamID <= ws.maxID || ws.maxIdleNodesInTree == 0 {
+ return
+ }
+ ws.maxID = streamID
+ n = &priorityNode{
+ q: *ws.queuePool.get(),
+ id: streamID,
+ weight: priorityDefaultWeight,
+ state: priorityNodeIdle,
+ }
+ n.setParent(&ws.root)
+ ws.nodes[streamID] = n
+ ws.addClosedOrIdleNode(&ws.idleNodes, ws.maxIdleNodesInTree, n)
+ }
+
+ // Section 5.3.1: A dependency on a stream that is not currently in the tree
+ // results in that stream being given a default priority (Section 5.3.5).
+ parent := ws.nodes[priority.StreamDep]
+ if parent == nil {
+ n.setParent(&ws.root)
+ n.weight = priorityDefaultWeight
+ return
+ }
+
+ // Ignore if the client tries to make a node its own parent.
+ if n == parent {
+ return
+ }
+
+ // Section 5.3.3:
+ // "If a stream is made dependent on one of its own dependencies, the
+ // formerly dependent stream is first moved to be dependent on the
+ // reprioritized stream's previous parent. The moved dependency retains
+ // its weight."
+ //
+ // That is: if parent depends on n, move parent to depend on n.parent.
+ for x := parent.parent; x != nil; x = x.parent {
+ if x == n {
+ parent.setParent(n.parent)
+ break
+ }
+ }
+
+ // Section 5.3.3: The exclusive flag causes the stream to become the sole
+ // dependency of its parent stream, causing other dependencies to become
+ // dependent on the exclusive stream.
+ if priority.Exclusive {
+ k := parent.kids
+ for k != nil {
+ next := k.next
+ if k != n {
+ k.setParent(n)
+ }
+ k = next
+ }
+ }
+
+ n.setParent(parent)
+ n.weight = priority.Weight
+}
+
+func (ws *priorityWriteScheduler) Push(wr FrameWriteRequest) {
+ var n *priorityNode
+ if id := wr.StreamID(); id == 0 {
+ n = &ws.root
+ } else {
+ n = ws.nodes[id]
+ if n == nil {
+ // id is an idle or closed stream. wr should not be a HEADERS or
+ // DATA frame. However, wr can be a RST_STREAM. In this case, we
+ // push wr onto the root, rather than creating a new priorityNode,
+ // since RST_STREAM is tiny and the stream's priority is unknown
+ // anyway. See issue #17919.
+ if wr.DataSize() > 0 {
+ panic("add DATA on non-open stream")
+ }
+ n = &ws.root
+ }
+ }
+ n.q.push(wr)
+}
+
+func (ws *priorityWriteScheduler) Pop() (wr FrameWriteRequest, ok bool) {
+ ws.root.walkReadyInOrder(false, &ws.tmp, func(n *priorityNode, openParent bool) bool {
+ limit := int32(math.MaxInt32)
+ if openParent {
+ limit = ws.writeThrottleLimit
+ }
+ wr, ok = n.q.consume(limit)
+ if !ok {
+ return false
+ }
+ n.addBytes(int64(wr.DataSize()))
+ // If B depends on A and B continuously has data available but A
+ // does not, gradually increase the throttling limit to allow B to
+ // steal more and more bandwidth from A.
+ if openParent {
+ ws.writeThrottleLimit += 1024
+ if ws.writeThrottleLimit < 0 {
+ ws.writeThrottleLimit = math.MaxInt32
+ }
+ } else if ws.enableWriteThrottle {
+ ws.writeThrottleLimit = 1024
+ }
+ return true
+ })
+ return wr, ok
+}
+
+func (ws *priorityWriteScheduler) addClosedOrIdleNode(list *[]*priorityNode, maxSize int, n *priorityNode) {
+ if maxSize == 0 {
+ return
+ }
+ if len(*list) == maxSize {
+ // Remove the oldest node, then shift left.
+ ws.removeNode((*list)[0])
+ x := (*list)[1:]
+ copy(*list, x)
+ *list = (*list)[:len(x)]
+ }
+ *list = append(*list, n)
+}
+
+func (ws *priorityWriteScheduler) removeNode(n *priorityNode) {
+ for k := n.kids; k != nil; k = k.next {
+ k.setParent(n.parent)
+ }
+ n.setParent(nil)
+ delete(ws.nodes, n.id)
+}
diff --git a/vendor/golang.org/x/net/http2/writesched_random.go b/vendor/golang.org/x/net/http2/writesched_random.go
new file mode 100644
index 0000000..36d7919
--- /dev/null
+++ b/vendor/golang.org/x/net/http2/writesched_random.go
@@ -0,0 +1,72 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package http2
+
+import "math"
+
+// NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2
+// priorities. Control frames like SETTINGS and PING are written before DATA
+// frames, but if no control frames are queued and multiple streams have queued
+// HEADERS or DATA frames, Pop selects a ready stream arbitrarily.
+func NewRandomWriteScheduler() WriteScheduler {
+ return &randomWriteScheduler{sq: make(map[uint32]*writeQueue)}
+}
+
+type randomWriteScheduler struct {
+ // zero are frames not associated with a specific stream.
+ zero writeQueue
+
+ // sq contains the stream-specific queues, keyed by stream ID.
+ // When a stream is idle or closed, it's deleted from the map.
+ sq map[uint32]*writeQueue
+
+ // pool of empty queues for reuse.
+ queuePool writeQueuePool
+}
+
+func (ws *randomWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) {
+ // no-op: idle streams are not tracked
+}
+
+func (ws *randomWriteScheduler) CloseStream(streamID uint32) {
+ q, ok := ws.sq[streamID]
+ if !ok {
+ return
+ }
+ delete(ws.sq, streamID)
+ ws.queuePool.put(q)
+}
+
+func (ws *randomWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) {
+ // no-op: priorities are ignored
+}
+
+func (ws *randomWriteScheduler) Push(wr FrameWriteRequest) {
+ id := wr.StreamID()
+ if id == 0 {
+ ws.zero.push(wr)
+ return
+ }
+ q, ok := ws.sq[id]
+ if !ok {
+ q = ws.queuePool.get()
+ ws.sq[id] = q
+ }
+ q.push(wr)
+}
+
+func (ws *randomWriteScheduler) Pop() (FrameWriteRequest, bool) {
+ // Control frames first.
+ if !ws.zero.empty() {
+ return ws.zero.shift(), true
+ }
+ // Iterate over all non-idle streams until finding one that can be consumed.
+ for _, q := range ws.sq {
+ if wr, ok := q.consume(math.MaxInt32); ok {
+ return wr, true
+ }
+ }
+ return FrameWriteRequest{}, false
+}
diff --git a/vendor/golang.org/x/net/idna/idna.go b/vendor/golang.org/x/net/idna/idna.go
new file mode 100644
index 0000000..ee2dbda
--- /dev/null
+++ b/vendor/golang.org/x/net/idna/idna.go
@@ -0,0 +1,668 @@
+// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT.
+
+// 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 idna implements IDNA2008 using the compatibility processing
+// defined by UTS (Unicode Technical Standard) #46, which defines a standard to
+// deal with the transition from IDNA2003.
+//
+// IDNA2008 (Internationalized Domain Names for Applications), is defined in RFC
+// 5890, RFC 5891, RFC 5892, RFC 5893 and RFC 5894.
+// UTS #46 is defined in http://www.unicode.org/reports/tr46.
+// See http://unicode.org/cldr/utility/idna.jsp for a visualization of the
+// differences between these two standards.
+package idna // import "golang.org/x/net/idna"
+
+import (
+ "fmt"
+ "strings"
+ "unicode/utf8"
+
+ "golang.org/x/text/secure/bidirule"
+ "golang.org/x/text/unicode/norm"
+)
+
+// NOTE: Unlike common practice in Go APIs, the functions will return a
+// sanitized domain name in case of errors. Browsers sometimes use a partially
+// evaluated string as lookup.
+// TODO: the current error handling is, in my opinion, the least opinionated.
+// Other strategies are also viable, though:
+// Option 1) Return an empty string in case of error, but allow the user to
+// specify explicitly which errors to ignore.
+// Option 2) Return the partially evaluated string if it is itself a valid
+// string, otherwise return the empty string in case of error.
+// Option 3) Option 1 and 2.
+// Option 4) Always return an empty string for now and implement Option 1 as
+// needed, and document that the return string may not be empty in case of
+// error in the future.
+// I think Option 1 is best, but it is quite opinionated.
+
+// ToASCII is a wrapper for Punycode.ToASCII.
+func ToASCII(s string) (string, error) {
+ return Punycode.process(s, true)
+}
+
+// ToUnicode is a wrapper for Punycode.ToUnicode.
+func ToUnicode(s string) (string, error) {
+ return Punycode.process(s, false)
+}
+
+// An Option configures a Profile at creation time.
+type Option func(*options)
+
+// Transitional sets a Profile to use the Transitional mapping as defined in UTS
+// #46. This will cause, for example, "ß" to be mapped to "ss". Using the
+// transitional mapping provides a compromise between IDNA2003 and IDNA2008
+// compatibility. It is used by most browsers when resolving domain names. This
+// option is only meaningful if combined with MapForLookup.
+func Transitional(transitional bool) Option {
+ return func(o *options) { o.transitional = true }
+}
+
+// VerifyDNSLength sets whether a Profile should fail if any of the IDN parts
+// are longer than allowed by the RFC.
+func VerifyDNSLength(verify bool) Option {
+ return func(o *options) { o.verifyDNSLength = verify }
+}
+
+// ValidateLabels sets whether to check the mandatory label validation criteria
+// as defined in Section 5.4 of RFC 5891. This includes testing for correct use
+// of hyphens ('-'), normalization, validity of runes, and the context rules.
+func ValidateLabels(enable bool) Option {
+ return func(o *options) {
+ // Don't override existing mappings, but set one that at least checks
+ // normalization if it is not set.
+ if o.mapping == nil && enable {
+ o.mapping = normalize
+ }
+ o.trie = trie
+ o.validateLabels = enable
+ o.fromPuny = validateFromPunycode
+ }
+}
+
+// StrictDomainName limits the set of permissable ASCII characters to those
+// allowed in domain names as defined in RFC 1034 (A-Z, a-z, 0-9 and the
+// hyphen). This is set by default for MapForLookup and ValidateForRegistration.
+//
+// This option is useful, for instance, for browsers that allow characters
+// outside this range, for example a '_' (U+005F LOW LINE). See
+// http://www.rfc-editor.org/std/std3.txt for more details This option
+// corresponds to the UseSTD3ASCIIRules option in UTS #46.
+func StrictDomainName(use bool) Option {
+ return func(o *options) {
+ o.trie = trie
+ o.useSTD3Rules = use
+ o.fromPuny = validateFromPunycode
+ }
+}
+
+// NOTE: the following options pull in tables. The tables should not be linked
+// in as long as the options are not used.
+
+// BidiRule enables the Bidi rule as defined in RFC 5893. Any application
+// that relies on proper validation of labels should include this rule.
+func BidiRule() Option {
+ return func(o *options) { o.bidirule = bidirule.ValidString }
+}
+
+// ValidateForRegistration sets validation options to verify that a given IDN is
+// properly formatted for registration as defined by Section 4 of RFC 5891.
+func ValidateForRegistration() Option {
+ return func(o *options) {
+ o.mapping = validateRegistration
+ StrictDomainName(true)(o)
+ ValidateLabels(true)(o)
+ VerifyDNSLength(true)(o)
+ BidiRule()(o)
+ }
+}
+
+// MapForLookup sets validation and mapping options such that a given IDN is
+// transformed for domain name lookup according to the requirements set out in
+// Section 5 of RFC 5891. The mappings follow the recommendations of RFC 5894,
+// RFC 5895 and UTS 46. It does not add the Bidi Rule. Use the BidiRule option
+// to add this check.
+//
+// The mappings include normalization and mapping case, width and other
+// compatibility mappings.
+func MapForLookup() Option {
+ return func(o *options) {
+ o.mapping = validateAndMap
+ StrictDomainName(true)(o)
+ ValidateLabels(true)(o)
+ }
+}
+
+type options struct {
+ transitional bool
+ useSTD3Rules bool
+ validateLabels bool
+ verifyDNSLength bool
+
+ trie *idnaTrie
+
+ // fromPuny calls validation rules when converting A-labels to U-labels.
+ fromPuny func(p *Profile, s string) error
+
+ // mapping implements a validation and mapping step as defined in RFC 5895
+ // or UTS 46, tailored to, for example, domain registration or lookup.
+ mapping func(p *Profile, s string) (string, error)
+
+ // bidirule, if specified, checks whether s conforms to the Bidi Rule
+ // defined in RFC 5893.
+ bidirule func(s string) bool
+}
+
+// A Profile defines the configuration of a IDNA mapper.
+type Profile struct {
+ options
+}
+
+func apply(o *options, opts []Option) {
+ for _, f := range opts {
+ f(o)
+ }
+}
+
+// New creates a new Profile.
+//
+// With no options, the returned Profile is the most permissive and equals the
+// Punycode Profile. Options can be passed to further restrict the Profile. The
+// MapForLookup and ValidateForRegistration options set a collection of options,
+// for lookup and registration purposes respectively, which can be tailored by
+// adding more fine-grained options, where later options override earlier
+// options.
+func New(o ...Option) *Profile {
+ p := &Profile{}
+ apply(&p.options, o)
+ return p
+}
+
+// ToASCII converts a domain or domain label to its ASCII form. For example,
+// ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and
+// ToASCII("golang") is "golang". If an error is encountered it will return
+// an error and a (partially) processed result.
+func (p *Profile) ToASCII(s string) (string, error) {
+ return p.process(s, true)
+}
+
+// ToUnicode converts a domain or domain label to its Unicode form. For example,
+// ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and
+// ToUnicode("golang") is "golang". If an error is encountered it will return
+// an error and a (partially) processed result.
+func (p *Profile) ToUnicode(s string) (string, error) {
+ pp := *p
+ pp.transitional = false
+ return pp.process(s, false)
+}
+
+// String reports a string with a description of the profile for debugging
+// purposes. The string format may change with different versions.
+func (p *Profile) String() string {
+ s := ""
+ if p.transitional {
+ s = "Transitional"
+ } else {
+ s = "NonTransitional"
+ }
+ if p.useSTD3Rules {
+ s += ":UseSTD3Rules"
+ }
+ if p.validateLabels {
+ s += ":ValidateLabels"
+ }
+ if p.verifyDNSLength {
+ s += ":VerifyDNSLength"
+ }
+ return s
+}
+
+var (
+ // Punycode is a Profile that does raw punycode processing with a minimum
+ // of validation.
+ Punycode *Profile = punycode
+
+ // Lookup is the recommended profile for looking up domain names, according
+ // to Section 5 of RFC 5891. The exact configuration of this profile may
+ // change over time.
+ Lookup *Profile = lookup
+
+ // Display is the recommended profile for displaying domain names.
+ // The configuration of this profile may change over time.
+ Display *Profile = display
+
+ // Registration is the recommended profile for checking whether a given
+ // IDN is valid for registration, according to Section 4 of RFC 5891.
+ Registration *Profile = registration
+
+ punycode = &Profile{}
+ lookup = &Profile{options{
+ transitional: true,
+ useSTD3Rules: true,
+ validateLabels: true,
+ trie: trie,
+ fromPuny: validateFromPunycode,
+ mapping: validateAndMap,
+ bidirule: bidirule.ValidString,
+ }}
+ display = &Profile{options{
+ useSTD3Rules: true,
+ validateLabels: true,
+ trie: trie,
+ fromPuny: validateFromPunycode,
+ mapping: validateAndMap,
+ bidirule: bidirule.ValidString,
+ }}
+ registration = &Profile{options{
+ useSTD3Rules: true,
+ validateLabels: true,
+ verifyDNSLength: true,
+ trie: trie,
+ fromPuny: validateFromPunycode,
+ mapping: validateRegistration,
+ bidirule: bidirule.ValidString,
+ }}
+
+ // TODO: profiles
+ // Register: recommended for approving domain names: don't do any mappings
+ // but rather reject on invalid input. Bundle or block deviation characters.
+)
+
+type labelError struct{ label, code_ string }
+
+func (e labelError) code() string { return e.code_ }
+func (e labelError) Error() string {
+ return fmt.Sprintf("idna: invalid label %q", e.label)
+}
+
+type runeError rune
+
+func (e runeError) code() string { return "P1" }
+func (e runeError) Error() string {
+ return fmt.Sprintf("idna: disallowed rune %U", e)
+}
+
+// process implements the algorithm described in section 4 of UTS #46,
+// see http://www.unicode.org/reports/tr46.
+func (p *Profile) process(s string, toASCII bool) (string, error) {
+ var err error
+ if p.mapping != nil {
+ s, err = p.mapping(p, s)
+ }
+ // Remove leading empty labels.
+ for ; len(s) > 0 && s[0] == '.'; s = s[1:] {
+ }
+ // It seems like we should only create this error on ToASCII, but the
+ // UTS 46 conformance tests suggests we should always check this.
+ if err == nil && p.verifyDNSLength && s == "" {
+ err = &labelError{s, "A4"}
+ }
+ labels := labelIter{orig: s}
+ for ; !labels.done(); labels.next() {
+ label := labels.label()
+ if label == "" {
+ // Empty labels are not okay. The label iterator skips the last
+ // label if it is empty.
+ if err == nil && p.verifyDNSLength {
+ err = &labelError{s, "A4"}
+ }
+ continue
+ }
+ if strings.HasPrefix(label, acePrefix) {
+ u, err2 := decode(label[len(acePrefix):])
+ if err2 != nil {
+ if err == nil {
+ err = err2
+ }
+ // Spec says keep the old label.
+ continue
+ }
+ labels.set(u)
+ if err == nil && p.validateLabels {
+ err = p.fromPuny(p, u)
+ }
+ if err == nil {
+ // This should be called on NonTransitional, according to the
+ // spec, but that currently does not have any effect. Use the
+ // original profile to preserve options.
+ err = p.validateLabel(u)
+ }
+ } else if err == nil {
+ err = p.validateLabel(label)
+ }
+ }
+ if toASCII {
+ for labels.reset(); !labels.done(); labels.next() {
+ label := labels.label()
+ if !ascii(label) {
+ a, err2 := encode(acePrefix, label)
+ if err == nil {
+ err = err2
+ }
+ label = a
+ labels.set(a)
+ }
+ n := len(label)
+ if p.verifyDNSLength && err == nil && (n == 0 || n > 63) {
+ err = &labelError{label, "A4"}
+ }
+ }
+ }
+ s = labels.result()
+ if toASCII && p.verifyDNSLength && err == nil {
+ // Compute the length of the domain name minus the root label and its dot.
+ n := len(s)
+ if n > 0 && s[n-1] == '.' {
+ n--
+ }
+ if len(s) < 1 || n > 253 {
+ err = &labelError{s, "A4"}
+ }
+ }
+ return s, err
+}
+
+func normalize(p *Profile, s string) (string, error) {
+ return norm.NFC.String(s), nil
+}
+
+func validateRegistration(p *Profile, s string) (string, error) {
+ if !norm.NFC.IsNormalString(s) {
+ return s, &labelError{s, "V1"}
+ }
+ var err error
+ for i := 0; i < len(s); {
+ v, sz := trie.lookupString(s[i:])
+ i += sz
+ // Copy bytes not copied so far.
+ switch p.simplify(info(v).category()) {
+ // TODO: handle the NV8 defined in the Unicode idna data set to allow
+ // for strict conformance to IDNA2008.
+ case valid, deviation:
+ case disallowed, mapped, unknown, ignored:
+ if err == nil {
+ r, _ := utf8.DecodeRuneInString(s[i:])
+ err = runeError(r)
+ }
+ }
+ }
+ return s, err
+}
+
+func validateAndMap(p *Profile, s string) (string, error) {
+ var (
+ err error
+ b []byte
+ k int
+ )
+ for i := 0; i < len(s); {
+ v, sz := trie.lookupString(s[i:])
+ start := i
+ i += sz
+ // Copy bytes not copied so far.
+ switch p.simplify(info(v).category()) {
+ case valid:
+ continue
+ case disallowed:
+ if err == nil {
+ r, _ := utf8.DecodeRuneInString(s[i:])
+ err = runeError(r)
+ }
+ continue
+ case mapped, deviation:
+ b = append(b, s[k:start]...)
+ b = info(v).appendMapping(b, s[start:i])
+ case ignored:
+ b = append(b, s[k:start]...)
+ // drop the rune
+ case unknown:
+ b = append(b, s[k:start]...)
+ b = append(b, "\ufffd"...)
+ }
+ k = i
+ }
+ if k == 0 {
+ // No changes so far.
+ s = norm.NFC.String(s)
+ } else {
+ b = append(b, s[k:]...)
+ if norm.NFC.QuickSpan(b) != len(b) {
+ b = norm.NFC.Bytes(b)
+ }
+ // TODO: the punycode converters require strings as input.
+ s = string(b)
+ }
+ return s, err
+}
+
+// A labelIter allows iterating over domain name labels.
+type labelIter struct {
+ orig string
+ slice []string
+ curStart int
+ curEnd int
+ i int
+}
+
+func (l *labelIter) reset() {
+ l.curStart = 0
+ l.curEnd = 0
+ l.i = 0
+}
+
+func (l *labelIter) done() bool {
+ return l.curStart >= len(l.orig)
+}
+
+func (l *labelIter) result() string {
+ if l.slice != nil {
+ return strings.Join(l.slice, ".")
+ }
+ return l.orig
+}
+
+func (l *labelIter) label() string {
+ if l.slice != nil {
+ return l.slice[l.i]
+ }
+ p := strings.IndexByte(l.orig[l.curStart:], '.')
+ l.curEnd = l.curStart + p
+ if p == -1 {
+ l.curEnd = len(l.orig)
+ }
+ return l.orig[l.curStart:l.curEnd]
+}
+
+// next sets the value to the next label. It skips the last label if it is empty.
+func (l *labelIter) next() {
+ l.i++
+ if l.slice != nil {
+ if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" {
+ l.curStart = len(l.orig)
+ }
+ } else {
+ l.curStart = l.curEnd + 1
+ if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' {
+ l.curStart = len(l.orig)
+ }
+ }
+}
+
+func (l *labelIter) set(s string) {
+ if l.slice == nil {
+ l.slice = strings.Split(l.orig, ".")
+ }
+ l.slice[l.i] = s
+}
+
+// acePrefix is the ASCII Compatible Encoding prefix.
+const acePrefix = "xn--"
+
+func (p *Profile) simplify(cat category) category {
+ switch cat {
+ case disallowedSTD3Mapped:
+ if p.useSTD3Rules {
+ cat = disallowed
+ } else {
+ cat = mapped
+ }
+ case disallowedSTD3Valid:
+ if p.useSTD3Rules {
+ cat = disallowed
+ } else {
+ cat = valid
+ }
+ case deviation:
+ if !p.transitional {
+ cat = valid
+ }
+ case validNV8, validXV8:
+ // TODO: handle V2008
+ cat = valid
+ }
+ return cat
+}
+
+func validateFromPunycode(p *Profile, s string) error {
+ if !norm.NFC.IsNormalString(s) {
+ return &labelError{s, "V1"}
+ }
+ for i := 0; i < len(s); {
+ v, sz := trie.lookupString(s[i:])
+ if c := p.simplify(info(v).category()); c != valid && c != deviation {
+ return &labelError{s, "V6"}
+ }
+ i += sz
+ }
+ return nil
+}
+
+const (
+ zwnj = "\u200c"
+ zwj = "\u200d"
+)
+
+type joinState int8
+
+const (
+ stateStart joinState = iota
+ stateVirama
+ stateBefore
+ stateBeforeVirama
+ stateAfter
+ stateFAIL
+)
+
+var joinStates = [][numJoinTypes]joinState{
+ stateStart: {
+ joiningL: stateBefore,
+ joiningD: stateBefore,
+ joinZWNJ: stateFAIL,
+ joinZWJ: stateFAIL,
+ joinVirama: stateVirama,
+ },
+ stateVirama: {
+ joiningL: stateBefore,
+ joiningD: stateBefore,
+ },
+ stateBefore: {
+ joiningL: stateBefore,
+ joiningD: stateBefore,
+ joiningT: stateBefore,
+ joinZWNJ: stateAfter,
+ joinZWJ: stateFAIL,
+ joinVirama: stateBeforeVirama,
+ },
+ stateBeforeVirama: {
+ joiningL: stateBefore,
+ joiningD: stateBefore,
+ joiningT: stateBefore,
+ },
+ stateAfter: {
+ joiningL: stateFAIL,
+ joiningD: stateBefore,
+ joiningT: stateAfter,
+ joiningR: stateStart,
+ joinZWNJ: stateFAIL,
+ joinZWJ: stateFAIL,
+ joinVirama: stateAfter, // no-op as we can't accept joiners here
+ },
+ stateFAIL: {
+ 0: stateFAIL,
+ joiningL: stateFAIL,
+ joiningD: stateFAIL,
+ joiningT: stateFAIL,
+ joiningR: stateFAIL,
+ joinZWNJ: stateFAIL,
+ joinZWJ: stateFAIL,
+ joinVirama: stateFAIL,
+ },
+}
+
+// validateLabel validates the criteria from Section 4.1. Item 1, 4, and 6 are
+// already implicitly satisfied by the overall implementation.
+func (p *Profile) validateLabel(s string) error {
+ if s == "" {
+ if p.verifyDNSLength {
+ return &labelError{s, "A4"}
+ }
+ return nil
+ }
+ if p.bidirule != nil && !p.bidirule(s) {
+ return &labelError{s, "B"}
+ }
+ if !p.validateLabels {
+ return nil
+ }
+ trie := p.trie // p.validateLabels is only set if trie is set.
+ if len(s) > 4 && s[2] == '-' && s[3] == '-' {
+ return &labelError{s, "V2"}
+ }
+ if s[0] == '-' || s[len(s)-1] == '-' {
+ return &labelError{s, "V3"}
+ }
+ // TODO: merge the use of this in the trie.
+ v, sz := trie.lookupString(s)
+ x := info(v)
+ if x.isModifier() {
+ return &labelError{s, "V5"}
+ }
+ // Quickly return in the absence of zero-width (non) joiners.
+ if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 {
+ return nil
+ }
+ st := stateStart
+ for i := 0; ; {
+ jt := x.joinType()
+ if s[i:i+sz] == zwj {
+ jt = joinZWJ
+ } else if s[i:i+sz] == zwnj {
+ jt = joinZWNJ
+ }
+ st = joinStates[st][jt]
+ if x.isViramaModifier() {
+ st = joinStates[st][joinVirama]
+ }
+ if i += sz; i == len(s) {
+ break
+ }
+ v, sz = trie.lookupString(s[i:])
+ x = info(v)
+ }
+ if st == stateFAIL || st == stateAfter {
+ return &labelError{s, "C"}
+ }
+ return nil
+}
+
+func ascii(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] >= utf8.RuneSelf {
+ return false
+ }
+ }
+ return true
+}
diff --git a/vendor/golang.org/x/net/idna/punycode.go b/vendor/golang.org/x/net/idna/punycode.go
new file mode 100644
index 0000000..02c7d59
--- /dev/null
+++ b/vendor/golang.org/x/net/idna/punycode.go
@@ -0,0 +1,203 @@
+// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT.
+
+// 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 idna
+
+// This file implements the Punycode algorithm from RFC 3492.
+
+import (
+ "math"
+ "strings"
+ "unicode/utf8"
+)
+
+// These parameter values are specified in section 5.
+//
+// All computation is done with int32s, so that overflow behavior is identical
+// regardless of whether int is 32-bit or 64-bit.
+const (
+ base int32 = 36
+ damp int32 = 700
+ initialBias int32 = 72
+ initialN int32 = 128
+ skew int32 = 38
+ tmax int32 = 26
+ tmin int32 = 1
+)
+
+func punyError(s string) error { return &labelError{s, "A3"} }
+
+// decode decodes a string as specified in section 6.2.
+func decode(encoded string) (string, error) {
+ if encoded == "" {
+ return "", nil
+ }
+ pos := 1 + strings.LastIndex(encoded, "-")
+ if pos == 1 {
+ return "", punyError(encoded)
+ }
+ if pos == len(encoded) {
+ return encoded[:len(encoded)-1], nil
+ }
+ output := make([]rune, 0, len(encoded))
+ if pos != 0 {
+ for _, r := range encoded[:pos-1] {
+ output = append(output, r)
+ }
+ }
+ i, n, bias := int32(0), initialN, initialBias
+ for pos < len(encoded) {
+ oldI, w := i, int32(1)
+ for k := base; ; k += base {
+ if pos == len(encoded) {
+ return "", punyError(encoded)
+ }
+ digit, ok := decodeDigit(encoded[pos])
+ if !ok {
+ return "", punyError(encoded)
+ }
+ pos++
+ i += digit * w
+ if i < 0 {
+ return "", punyError(encoded)
+ }
+ t := k - bias
+ if t < tmin {
+ t = tmin
+ } else if t > tmax {
+ t = tmax
+ }
+ if digit < t {
+ break
+ }
+ w *= base - t
+ if w >= math.MaxInt32/base {
+ return "", punyError(encoded)
+ }
+ }
+ x := int32(len(output) + 1)
+ bias = adapt(i-oldI, x, oldI == 0)
+ n += i / x
+ i %= x
+ if n > utf8.MaxRune || len(output) >= 1024 {
+ return "", punyError(encoded)
+ }
+ output = append(output, 0)
+ copy(output[i+1:], output[i:])
+ output[i] = n
+ i++
+ }
+ return string(output), nil
+}
+
+// encode encodes a string as specified in section 6.3 and prepends prefix to
+// the result.
+//
+// The "while h < length(input)" line in the specification becomes "for
+// remaining != 0" in the Go code, because len(s) in Go is in bytes, not runes.
+func encode(prefix, s string) (string, error) {
+ output := make([]byte, len(prefix), len(prefix)+1+2*len(s))
+ copy(output, prefix)
+ delta, n, bias := int32(0), initialN, initialBias
+ b, remaining := int32(0), int32(0)
+ for _, r := range s {
+ if r < 0x80 {
+ b++
+ output = append(output, byte(r))
+ } else {
+ remaining++
+ }
+ }
+ h := b
+ if b > 0 {
+ output = append(output, '-')
+ }
+ for remaining != 0 {
+ m := int32(0x7fffffff)
+ for _, r := range s {
+ if m > r && r >= n {
+ m = r
+ }
+ }
+ delta += (m - n) * (h + 1)
+ if delta < 0 {
+ return "", punyError(s)
+ }
+ n = m
+ for _, r := range s {
+ if r < n {
+ delta++
+ if delta < 0 {
+ return "", punyError(s)
+ }
+ continue
+ }
+ if r > n {
+ continue
+ }
+ q := delta
+ for k := base; ; k += base {
+ t := k - bias
+ if t < tmin {
+ t = tmin
+ } else if t > tmax {
+ t = tmax
+ }
+ if q < t {
+ break
+ }
+ output = append(output, encodeDigit(t+(q-t)%(base-t)))
+ q = (q - t) / (base - t)
+ }
+ output = append(output, encodeDigit(q))
+ bias = adapt(delta, h+1, h == b)
+ delta = 0
+ h++
+ remaining--
+ }
+ delta++
+ n++
+ }
+ return string(output), nil
+}
+
+func decodeDigit(x byte) (digit int32, ok bool) {
+ switch {
+ case '0' <= x && x <= '9':
+ return int32(x - ('0' - 26)), true
+ case 'A' <= x && x <= 'Z':
+ return int32(x - 'A'), true
+ case 'a' <= x && x <= 'z':
+ return int32(x - 'a'), true
+ }
+ return 0, false
+}
+
+func encodeDigit(digit int32) byte {
+ switch {
+ case 0 <= digit && digit < 26:
+ return byte(digit + 'a')
+ case 26 <= digit && digit < 36:
+ return byte(digit + ('0' - 26))
+ }
+ panic("idna: internal error in punycode encoding")
+}
+
+// adapt is the bias adaptation function specified in section 6.1.
+func adapt(delta, numPoints int32, firstTime bool) int32 {
+ if firstTime {
+ delta /= damp
+ } else {
+ delta /= 2
+ }
+ delta += delta / numPoints
+ k := int32(0)
+ for delta > ((base-tmin)*tmax)/2 {
+ delta /= base - tmin
+ k += base
+ }
+ return k + (base-tmin+1)*delta/(delta+skew)
+}
diff --git a/vendor/golang.org/x/net/idna/tables.go b/vendor/golang.org/x/net/idna/tables.go
new file mode 100644
index 0000000..d281934
--- /dev/null
+++ b/vendor/golang.org/x/net/idna/tables.go
@@ -0,0 +1,4477 @@
+// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT.
+
+package idna
+
+// UnicodeVersion is the Unicode version from which the tables in this package are derived.
+const UnicodeVersion = "9.0.0"
+
+var mappings string = "" + // Size: 8176 bytes
+ "\x00\x01 \x03 ̈\x01a\x03 ̄\x012\x013\x03 ́\x03 ̧\x011\x01o\x051⁄4\x051⁄2" +
+ "\x053⁄4\x03i̇\x03l·\x03ʼn\x01s\x03dž\x03ⱥ\x03ⱦ\x01h\x01j\x01r\x01w\x01y" +
+ "\x03 ̆\x03 ̇\x03 ̊\x03 ̨\x03 ̃\x03 ̋\x01l\x01x\x04̈́\x03 ι\x01;\x05 ̈́" +
+ "\x04եւ\x04اٴ\x04وٴ\x04ۇٴ\x04يٴ\x06क़\x06ख़\x06ग़\x06ज़\x06ड़\x06ढ़\x06फ़" +
+ "\x06य़\x06ড়\x06ঢ়\x06য়\x06ਲ਼\x06ਸ਼\x06ਖ਼\x06ਗ਼\x06ਜ਼\x06ਫ਼\x06ଡ଼\x06ଢ଼" +
+ "\x06ํา\x06ໍາ\x06ຫນ\x06ຫມ\x06གྷ\x06ཌྷ\x06དྷ\x06བྷ\x06ཛྷ\x06ཀྵ\x06ཱི\x06ཱུ" +
+ "\x06ྲྀ\x09ྲཱྀ\x06ླྀ\x09ླཱྀ\x06ཱྀ\x06ྒྷ\x06ྜྷ\x06ྡྷ\x06ྦྷ\x06ྫྷ\x06ྐྵ\x02" +
+ "в\x02д\x02о\x02с\x02т\x02ъ\x02ѣ\x02æ\x01b\x01d\x01e\x02ǝ\x01g\x01i\x01k" +
+ "\x01m\x01n\x02ȣ\x01p\x01t\x01u\x02ɐ\x02ɑ\x02ə\x02ɛ\x02ɜ\x02ŋ\x02ɔ\x02ɯ" +
+ "\x01v\x02β\x02γ\x02δ\x02φ\x02χ\x02ρ\x02н\x02ɒ\x01c\x02ɕ\x02ð\x01f\x02ɟ" +
+ "\x02ɡ\x02ɥ\x02ɨ\x02ɩ\x02ɪ\x02ʝ\x02ɭ\x02ʟ\x02ɱ\x02ɰ\x02ɲ\x02ɳ\x02ɴ\x02ɵ" +
+ "\x02ɸ\x02ʂ\x02ʃ\x02ƫ\x02ʉ\x02ʊ\x02ʋ\x02ʌ\x01z\x02ʐ\x02ʑ\x02ʒ\x02θ\x02ss" +
+ "\x02ά\x02έ\x02ή\x02ί\x02ό\x02ύ\x02ώ\x05ἀι\x05ἁι\x05ἂι\x05ἃι\x05ἄι\x05ἅι" +
+ "\x05ἆι\x05ἇι\x05ἠι\x05ἡι\x05ἢι\x05ἣι\x05ἤι\x05ἥι\x05ἦι\x05ἧι\x05ὠι\x05ὡι" +
+ "\x05ὢι\x05ὣι\x05ὤι\x05ὥι\x05ὦι\x05ὧι\x05ὰι\x04αι\x04άι\x05ᾶι\x02ι\x05 ̈͂" +
+ "\x05ὴι\x04ηι\x04ήι\x05ῆι\x05 ̓̀\x05 ̓́\x05 ̓͂\x02ΐ\x05 ̔̀\x05 ̔́\x05 ̔͂" +
+ "\x02ΰ\x05 ̈̀\x01`\x05ὼι\x04ωι\x04ώι\x05ῶι\x06′′\x09′′′\x06‵‵\x09‵‵‵\x02!" +
+ "!\x02??\x02?!\x02!?\x0c′′′′\x010\x014\x015\x016\x017\x018\x019\x01+\x01=" +
+ "\x01(\x01)\x02rs\x02ħ\x02no\x01q\x02sm\x02tm\x02ω\x02å\x02א\x02ב\x02ג" +
+ "\x02ד\x02π\x051⁄7\x051⁄9\x061⁄10\x051⁄3\x052⁄3\x051⁄5\x052⁄5\x053⁄5\x054" +
+ "⁄5\x051⁄6\x055⁄6\x051⁄8\x053⁄8\x055⁄8\x057⁄8\x041⁄\x02ii\x02iv\x02vi" +
+ "\x04viii\x02ix\x02xi\x050⁄3\x06∫∫\x09∫∫∫\x06∮∮\x09∮∮∮\x0210\x0211\x0212" +
+ "\x0213\x0214\x0215\x0216\x0217\x0218\x0219\x0220\x04(10)\x04(11)\x04(12)" +
+ "\x04(13)\x04(14)\x04(15)\x04(16)\x04(17)\x04(18)\x04(19)\x04(20)\x0c∫∫∫∫" +
+ "\x02==\x05⫝̸\x02ɫ\x02ɽ\x02ȿ\x02ɀ\x01.\x04 ゙\x04 ゚\x06より\x06コト\x05(ᄀ)\x05" +
+ "(ᄂ)\x05(ᄃ)\x05(ᄅ)\x05(ᄆ)\x05(ᄇ)\x05(ᄉ)\x05(ᄋ)\x05(ᄌ)\x05(ᄎ)\x05(ᄏ)\x05(ᄐ" +
+ ")\x05(ᄑ)\x05(ᄒ)\x05(가)\x05(나)\x05(다)\x05(라)\x05(마)\x05(바)\x05(사)\x05(아)" +
+ "\x05(자)\x05(차)\x05(카)\x05(타)\x05(파)\x05(하)\x05(주)\x08(오전)\x08(오후)\x05(一)" +
+ "\x05(二)\x05(三)\x05(四)\x05(五)\x05(六)\x05(七)\x05(八)\x05(九)\x05(十)\x05(月)" +
+ "\x05(火)\x05(水)\x05(木)\x05(金)\x05(土)\x05(日)\x05(株)\x05(有)\x05(社)\x05(名)" +
+ "\x05(特)\x05(財)\x05(祝)\x05(労)\x05(代)\x05(呼)\x05(学)\x05(監)\x05(企)\x05(資)" +
+ "\x05(協)\x05(祭)\x05(休)\x05(自)\x05(至)\x0221\x0222\x0223\x0224\x0225\x0226" +
+ "\x0227\x0228\x0229\x0230\x0231\x0232\x0233\x0234\x0235\x06참고\x06주의\x0236" +
+ "\x0237\x0238\x0239\x0240\x0241\x0242\x0243\x0244\x0245\x0246\x0247\x0248" +
+ "\x0249\x0250\x041月\x042月\x043月\x044月\x045月\x046月\x047月\x048月\x049月\x0510" +
+ "月\x0511月\x0512月\x02hg\x02ev\x0cアパート\x0cアルファ\x0cアンペア\x09アール\x0cイニング\x09" +
+ "インチ\x09ウォン\x0fエスクード\x0cエーカー\x09オンス\x09オーム\x09カイリ\x0cカラット\x0cカロリー\x09ガロ" +
+ "ン\x09ガンマ\x06ギガ\x09ギニー\x0cキュリー\x0cギルダー\x06キロ\x0fキログラム\x12キロメートル\x0fキロワッ" +
+ "ト\x09グラム\x0fグラムトン\x0fクルゼイロ\x0cクローネ\x09ケース\x09コルナ\x09コーポ\x0cサイクル\x0fサンチ" +
+ "ーム\x0cシリング\x09センチ\x09セント\x09ダース\x06デシ\x06ドル\x06トン\x06ナノ\x09ノット\x09ハイツ" +
+ "\x0fパーセント\x09パーツ\x0cバーレル\x0fピアストル\x09ピクル\x06ピコ\x06ビル\x0fファラッド\x0cフィート" +
+ "\x0fブッシェル\x09フラン\x0fヘクタール\x06ペソ\x09ペニヒ\x09ヘルツ\x09ペンス\x09ページ\x09ベータ\x0cポイ" +
+ "ント\x09ボルト\x06ホン\x09ポンド\x09ホール\x09ホーン\x0cマイクロ\x09マイル\x09マッハ\x09マルク\x0fマ" +
+ "ンション\x0cミクロン\x06ミリ\x0fミリバール\x06メガ\x0cメガトン\x0cメートル\x09ヤード\x09ヤール\x09ユアン" +
+ "\x0cリットル\x06リラ\x09ルピー\x0cルーブル\x06レム\x0fレントゲン\x09ワット\x040点\x041点\x042点" +
+ "\x043点\x044点\x045点\x046点\x047点\x048点\x049点\x0510点\x0511点\x0512点\x0513点" +
+ "\x0514点\x0515点\x0516点\x0517点\x0518点\x0519点\x0520点\x0521点\x0522点\x0523点" +
+ "\x0524点\x02da\x02au\x02ov\x02pc\x02dm\x02iu\x06平成\x06昭和\x06大正\x06明治\x0c株" +
+ "式会社\x02pa\x02na\x02ma\x02ka\x02kb\x02mb\x02gb\x04kcal\x02pf\x02nf\x02m" +
+ "g\x02kg\x02hz\x02ml\x02dl\x02kl\x02fm\x02nm\x02mm\x02cm\x02km\x02m2\x02m" +
+ "3\x05m∕s\x06m∕s2\x07rad∕s\x08rad∕s2\x02ps\x02ns\x02ms\x02pv\x02nv\x02mv" +
+ "\x02kv\x02pw\x02nw\x02mw\x02kw\x02bq\x02cc\x02cd\x06c∕kg\x02db\x02gy\x02" +
+ "ha\x02hp\x02in\x02kk\x02kt\x02lm\x02ln\x02lx\x02ph\x02pr\x02sr\x02sv\x02" +
+ "wb\x05v∕m\x05a∕m\x041日\x042日\x043日\x044日\x045日\x046日\x047日\x048日\x049日" +
+ "\x0510日\x0511日\x0512日\x0513日\x0514日\x0515日\x0516日\x0517日\x0518日\x0519日" +
+ "\x0520日\x0521日\x0522日\x0523日\x0524日\x0525日\x0526日\x0527日\x0528日\x0529日" +
+ "\x0530日\x0531日\x02ь\x02ɦ\x02ɬ\x02ʞ\x02ʇ\x02œ\x04𤋮\x04𢡊\x04𢡄\x04𣏕\x04𥉉" +
+ "\x04𥳐\x04𧻓\x02ff\x02fi\x02fl\x02st\x04մն\x04մե\x04մի\x04վն\x04մխ\x04יִ" +
+ "\x04ײַ\x02ע\x02ה\x02כ\x02ל\x02ם\x02ר\x02ת\x04שׁ\x04שׂ\x06שּׁ\x06שּׂ\x04א" +
+ "ַ\x04אָ\x04אּ\x04בּ\x04גּ\x04דּ\x04הּ\x04וּ\x04זּ\x04טּ\x04יּ\x04ךּ\x04" +
+ "כּ\x04לּ\x04מּ\x04נּ\x04סּ\x04ףּ\x04פּ\x04צּ\x04קּ\x04רּ\x04שּ\x04תּ" +
+ "\x04וֹ\x04בֿ\x04כֿ\x04פֿ\x04אל\x02ٱ\x02ٻ\x02پ\x02ڀ\x02ٺ\x02ٿ\x02ٹ\x02ڤ" +
+ "\x02ڦ\x02ڄ\x02ڃ\x02چ\x02ڇ\x02ڍ\x02ڌ\x02ڎ\x02ڈ\x02ژ\x02ڑ\x02ک\x02گ\x02ڳ" +
+ "\x02ڱ\x02ں\x02ڻ\x02ۀ\x02ہ\x02ھ\x02ے\x02ۓ\x02ڭ\x02ۇ\x02ۆ\x02ۈ\x02ۋ\x02ۅ" +
+ "\x02ۉ\x02ې\x02ى\x04ئا\x04ئە\x04ئو\x04ئۇ\x04ئۆ\x04ئۈ\x04ئې\x04ئى\x02ی\x04" +
+ "ئج\x04ئح\x04ئم\x04ئي\x04بج\x04بح\x04بخ\x04بم\x04بى\x04بي\x04تج\x04تح" +
+ "\x04تخ\x04تم\x04تى\x04تي\x04ثج\x04ثم\x04ثى\x04ثي\x04جح\x04جم\x04حج\x04حم" +
+ "\x04خج\x04خح\x04خم\x04سج\x04سح\x04سخ\x04سم\x04صح\x04صم\x04ضج\x04ضح\x04ضخ" +
+ "\x04ضم\x04طح\x04طم\x04ظم\x04عج\x04عم\x04غج\x04غم\x04فج\x04فح\x04فخ\x04فم" +
+ "\x04فى\x04في\x04قح\x04قم\x04قى\x04قي\x04كا\x04كج\x04كح\x04كخ\x04كل\x04كم" +
+ "\x04كى\x04كي\x04لج\x04لح\x04لخ\x04لم\x04لى\x04لي\x04مج\x04مح\x04مخ\x04مم" +
+ "\x04مى\x04مي\x04نج\x04نح\x04نخ\x04نم\x04نى\x04ني\x04هج\x04هم\x04هى\x04هي" +
+ "\x04يج\x04يح\x04يخ\x04يم\x04يى\x04يي\x04ذٰ\x04رٰ\x04ىٰ\x05 ٌّ\x05 ٍّ\x05" +
+ " َّ\x05 ُّ\x05 ِّ\x05 ّٰ\x04ئر\x04ئز\x04ئن\x04بر\x04بز\x04بن\x04تر\x04تز" +
+ "\x04تن\x04ثر\x04ثز\x04ثن\x04ما\x04نر\x04نز\x04نن\x04ير\x04يز\x04ين\x04ئخ" +
+ "\x04ئه\x04به\x04ته\x04صخ\x04له\x04نه\x04هٰ\x04يه\x04ثه\x04سه\x04شم\x04شه" +
+ "\x06ـَّ\x06ـُّ\x06ـِّ\x04طى\x04طي\x04عى\x04عي\x04غى\x04غي\x04سى\x04سي" +
+ "\x04شى\x04شي\x04حى\x04حي\x04جى\x04جي\x04خى\x04خي\x04صى\x04صي\x04ضى\x04ضي" +
+ "\x04شج\x04شح\x04شخ\x04شر\x04سر\x04صر\x04ضر\x04اً\x06تجم\x06تحج\x06تحم" +
+ "\x06تخم\x06تمج\x06تمح\x06تمخ\x06جمح\x06حمي\x06حمى\x06سحج\x06سجح\x06سجى" +
+ "\x06سمح\x06سمج\x06سمم\x06صحح\x06صمم\x06شحم\x06شجي\x06شمخ\x06شمم\x06ضحى" +
+ "\x06ضخم\x06طمح\x06طمم\x06طمي\x06عجم\x06عمم\x06عمى\x06غمم\x06غمي\x06غمى" +
+ "\x06فخم\x06قمح\x06قمم\x06لحم\x06لحي\x06لحى\x06لجج\x06لخم\x06لمح\x06محج" +
+ "\x06محم\x06محي\x06مجح\x06مجم\x06مخج\x06مخم\x06مجخ\x06همج\x06همم\x06نحم" +
+ "\x06نحى\x06نجم\x06نجى\x06نمي\x06نمى\x06يمم\x06بخي\x06تجي\x06تجى\x06تخي" +
+ "\x06تخى\x06تمي\x06تمى\x06جمي\x06جحى\x06جمى\x06سخى\x06صحي\x06شحي\x06ضحي" +
+ "\x06لجي\x06لمي\x06يحي\x06يجي\x06يمي\x06ممي\x06قمي\x06نحي\x06عمي\x06كمي" +
+ "\x06نجح\x06مخي\x06لجم\x06كمم\x06جحي\x06حجي\x06مجي\x06فمي\x06بحي\x06سخي" +
+ "\x06نجي\x06صلے\x06قلے\x08الله\x08اكبر\x08محمد\x08صلعم\x08رسول\x08عليه" +
+ "\x08وسلم\x06صلى!صلى الله عليه وسلم\x0fجل جلاله\x08ریال\x01,\x01:\x01!" +
+ "\x01?\x01_\x01{\x01}\x01[\x01]\x01#\x01&\x01*\x01-\x01<\x01>\x01\\\x01$" +
+ "\x01%\x01@\x04ـً\x04ـَ\x04ـُ\x04ـِ\x04ـّ\x04ـْ\x02ء\x02آ\x02أ\x02ؤ\x02إ" +
+ "\x02ئ\x02ا\x02ب\x02ة\x02ت\x02ث\x02ج\x02ح\x02خ\x02د\x02ذ\x02ر\x02ز\x02س" +
+ "\x02ش\x02ص\x02ض\x02ط\x02ظ\x02ع\x02غ\x02ف\x02ق\x02ك\x02ل\x02م\x02ن\x02ه" +
+ "\x02و\x02ي\x04لآ\x04لأ\x04لإ\x04لا\x01\x22\x01'\x01/\x01^\x01|\x01~\x02¢" +
+ "\x02£\x02¬\x02¦\x02¥\x08𝅗𝅥\x08𝅘𝅥\x0c𝅘𝅥𝅮\x0c𝅘𝅥𝅯\x0c𝅘𝅥𝅰\x0c𝅘𝅥𝅱\x0c𝅘𝅥𝅲\x08𝆹" +
+ "𝅥\x08𝆺𝅥\x0c𝆹𝅥𝅮\x0c𝆺𝅥𝅮\x0c𝆹𝅥𝅯\x0c𝆺𝅥𝅯\x02ı\x02ȷ\x02α\x02ε\x02ζ\x02η\x02" +
+ "κ\x02λ\x02μ\x02ν\x02ξ\x02ο\x02σ\x02τ\x02υ\x02ψ\x03∇\x03∂\x02ϝ\x02ٮ\x02ڡ" +
+ "\x02ٯ\x020,\x021,\x022,\x023,\x024,\x025,\x026,\x027,\x028,\x029,\x03(a)" +
+ "\x03(b)\x03(c)\x03(d)\x03(e)\x03(f)\x03(g)\x03(h)\x03(i)\x03(j)\x03(k)" +
+ "\x03(l)\x03(m)\x03(n)\x03(o)\x03(p)\x03(q)\x03(r)\x03(s)\x03(t)\x03(u)" +
+ "\x03(v)\x03(w)\x03(x)\x03(y)\x03(z)\x07〔s〕\x02wz\x02hv\x02sd\x03ppv\x02w" +
+ "c\x02mc\x02md\x02dj\x06ほか\x06ココ\x03サ\x03手\x03字\x03双\x03デ\x03二\x03多\x03解" +
+ "\x03天\x03交\x03映\x03無\x03料\x03前\x03後\x03再\x03新\x03初\x03終\x03生\x03販\x03声" +
+ "\x03吹\x03演\x03投\x03捕\x03一\x03三\x03遊\x03左\x03中\x03右\x03指\x03走\x03打\x03禁" +
+ "\x03空\x03合\x03満\x03有\x03月\x03申\x03割\x03営\x03配\x09〔本〕\x09〔三〕\x09〔二〕\x09〔安" +
+ "〕\x09〔点〕\x09〔打〕\x09〔盗〕\x09〔勝〕\x09〔敗〕\x03得\x03可\x03丽\x03丸\x03乁\x03你\x03" +
+ "侮\x03侻\x03倂\x03偺\x03備\x03僧\x03像\x03㒞\x03免\x03兔\x03兤\x03具\x03㒹\x03內\x03" +
+ "冗\x03冤\x03仌\x03冬\x03况\x03凵\x03刃\x03㓟\x03刻\x03剆\x03剷\x03㔕\x03勇\x03勉\x03" +
+ "勤\x03勺\x03包\x03匆\x03北\x03卉\x03卑\x03博\x03即\x03卽\x03卿\x03灰\x03及\x03叟\x03" +
+ "叫\x03叱\x03吆\x03咞\x03吸\x03呈\x03周\x03咢\x03哶\x03唐\x03啓\x03啣\x03善\x03喙\x03" +
+ "喫\x03喳\x03嗂\x03圖\x03嘆\x03圗\x03噑\x03噴\x03切\x03壮\x03城\x03埴\x03堍\x03型\x03" +
+ "堲\x03報\x03墬\x03売\x03壷\x03夆\x03夢\x03奢\x03姬\x03娛\x03娧\x03姘\x03婦\x03㛮\x03" +
+ "嬈\x03嬾\x03寃\x03寘\x03寧\x03寳\x03寿\x03将\x03尢\x03㞁\x03屠\x03屮\x03峀\x03岍\x03" +
+ "嵃\x03嵮\x03嵫\x03嵼\x03巡\x03巢\x03㠯\x03巽\x03帨\x03帽\x03幩\x03㡢\x03㡼\x03庰\x03" +
+ "庳\x03庶\x03廊\x03廾\x03舁\x03弢\x03㣇\x03形\x03彫\x03㣣\x03徚\x03忍\x03志\x03忹\x03" +
+ "悁\x03㤺\x03㤜\x03悔\x03惇\x03慈\x03慌\x03慎\x03慺\x03憎\x03憲\x03憤\x03憯\x03懞\x03" +
+ "懲\x03懶\x03成\x03戛\x03扝\x03抱\x03拔\x03捐\x03挽\x03拼\x03捨\x03掃\x03揤\x03搢\x03" +
+ "揅\x03掩\x03㨮\x03摩\x03摾\x03撝\x03摷\x03㩬\x03敏\x03敬\x03旣\x03書\x03晉\x03㬙\x03" +
+ "暑\x03㬈\x03㫤\x03冒\x03冕\x03最\x03暜\x03肭\x03䏙\x03朗\x03望\x03朡\x03杞\x03杓\x03" +
+ "㭉\x03柺\x03枅\x03桒\x03梅\x03梎\x03栟\x03椔\x03㮝\x03楂\x03榣\x03槪\x03檨\x03櫛\x03" +
+ "㰘\x03次\x03歔\x03㱎\x03歲\x03殟\x03殺\x03殻\x03汎\x03沿\x03泍\x03汧\x03洖\x03派\x03" +
+ "海\x03流\x03浩\x03浸\x03涅\x03洴\x03港\x03湮\x03㴳\x03滋\x03滇\x03淹\x03潮\x03濆\x03" +
+ "瀹\x03瀞\x03瀛\x03㶖\x03灊\x03災\x03灷\x03炭\x03煅\x03熜\x03爨\x03爵\x03牐\x03犀\x03" +
+ "犕\x03獺\x03王\x03㺬\x03玥\x03㺸\x03瑇\x03瑜\x03瑱\x03璅\x03瓊\x03㼛\x03甤\x03甾\x03" +
+ "異\x03瘐\x03㿼\x03䀈\x03直\x03眞\x03真\x03睊\x03䀹\x03瞋\x03䁆\x03䂖\x03硎\x03碌\x03" +
+ "磌\x03䃣\x03祖\x03福\x03秫\x03䄯\x03穀\x03穊\x03穏\x03䈂\x03篆\x03築\x03䈧\x03糒\x03" +
+ "䊠\x03糨\x03糣\x03紀\x03絣\x03䌁\x03緇\x03縂\x03繅\x03䌴\x03䍙\x03罺\x03羕\x03翺\x03" +
+ "者\x03聠\x03聰\x03䏕\x03育\x03脃\x03䐋\x03脾\x03媵\x03舄\x03辞\x03䑫\x03芑\x03芋\x03" +
+ "芝\x03劳\x03花\x03芳\x03芽\x03苦\x03若\x03茝\x03荣\x03莭\x03茣\x03莽\x03菧\x03著\x03" +
+ "荓\x03菊\x03菌\x03菜\x03䔫\x03蓱\x03蓳\x03蔖\x03蕤\x03䕝\x03䕡\x03䕫\x03虐\x03虜\x03" +
+ "虧\x03虩\x03蚩\x03蚈\x03蜎\x03蛢\x03蝹\x03蜨\x03蝫\x03螆\x03蟡\x03蠁\x03䗹\x03衠\x03" +
+ "衣\x03裗\x03裞\x03䘵\x03裺\x03㒻\x03䚾\x03䛇\x03誠\x03諭\x03變\x03豕\x03貫\x03賁\x03" +
+ "贛\x03起\x03跋\x03趼\x03跰\x03軔\x03輸\x03邔\x03郱\x03鄑\x03鄛\x03鈸\x03鋗\x03鋘\x03" +
+ "鉼\x03鏹\x03鐕\x03開\x03䦕\x03閷\x03䧦\x03雃\x03嶲\x03霣\x03䩮\x03䩶\x03韠\x03䪲\x03" +
+ "頋\x03頩\x03飢\x03䬳\x03餩\x03馧\x03駂\x03駾\x03䯎\x03鬒\x03鱀\x03鳽\x03䳎\x03䳭\x03" +
+ "鵧\x03䳸\x03麻\x03䵖\x03黹\x03黾\x03鼅\x03鼏\x03鼖\x03鼻"
+
+var xorData string = "" + // Size: 4855 bytes
+ "\x02\x0c\x09\x02\xb0\xec\x02\xad\xd8\x02\xad\xd9\x02\x06\x07\x02\x0f\x12" +
+ "\x02\x0f\x1f\x02\x0f\x1d\x02\x01\x13\x02\x0f\x16\x02\x0f\x0b\x02\x0f3" +
+ "\x02\x0f7\x02\x0f?\x02\x0f/\x02\x0f*\x02\x0c&\x02\x0c*\x02\x0c;\x02\x0c9" +
+ "\x02\x0c%\x02\xab\xed\x02\xab\xe2\x02\xab\xe3\x02\xa9\xe0\x02\xa9\xe1" +
+ "\x02\xa9\xe6\x02\xa3\xcb\x02\xa3\xc8\x02\xa3\xc9\x02\x01#\x02\x01\x08" +
+ "\x02\x0e>\x02\x0e'\x02\x0f\x03\x02\x03\x0d\x02\x03\x09\x02\x03\x17\x02" +
+ "\x03\x0e\x02\x02\x03\x02\x011\x02\x01\x00\x02\x01\x10\x02\x03<\x02\x07" +
+ "\x0d\x02\x02\x0c\x02\x0c0\x02\x01\x03\x02\x01\x01\x02\x01 \x02\x01\x22" +
+ "\x02\x01)\x02\x01\x0a\x02\x01\x0c\x02\x02\x06\x02\x02\x02\x02\x03\x10" +
+ "\x03\x037 \x03\x0b+\x03\x02\x01\x04\x02\x01\x02\x02\x019\x02\x03\x1c\x02" +
+ "\x02$\x03\x80p$\x02\x03:\x02\x03\x0a\x03\xc1r.\x03\xc1r,\x03\xc1r\x02" +
+ "\x02\x02:\x02\x02>\x02\x02,\x02\x02\x10\x02\x02\x00\x03\xc1s<\x03\xc1s*" +
+ "\x03\xc2L$\x03\xc2L;\x02\x09)\x02\x0a\x19\x03\x83\xab\xe3\x03\x83\xab" +
+ "\xf2\x03 4\xe0\x03\x81\xab\xea\x03\x81\xab\xf3\x03 4\xef\x03\x96\xe1\xcd" +
+ "\x03\x84\xe5\xc3\x02\x0d\x11\x03\x8b\xec\xcb\x03\x94\xec\xcf\x03\x9a\xec" +
+ "\xc2\x03\x8b\xec\xdb\x03\x94\xec\xdf\x03\x9a\xec\xd2\x03\x01\x0c!\x03" +
+ "\x01\x0c#\x03ʠ\x9d\x03ʣ\x9c\x03ʢ\x9f\x03ʥ\x9e\x03ʤ\x91\x03ʧ\x90\x03ʦ\x93" +
+ "\x03ʩ\x92\x03ʨ\x95\x03\xca\xf3\xb5\x03\xca\xf0\xb4\x03\xca\xf1\xb7\x03" +
+ "\xca\xf6\xb6\x03\xca\xf7\x89\x03\xca\xf4\x88\x03\xca\xf5\x8b\x03\xca\xfa" +
+ "\x8a\x03\xca\xfb\x8d\x03\xca\xf8\x8c\x03\xca\xf9\x8f\x03\xca\xfe\x8e\x03" +
+ "\xca\xff\x81\x03\xca\xfc\x80\x03\xca\xfd\x83\x03\xca\xe2\x82\x03\xca\xe3" +
+ "\x85\x03\xca\xe0\x84\x03\xca\xe1\x87\x03\xca\xe6\x86\x03\xca\xe7\x99\x03" +
+ "\xca\xe4\x98\x03\xca\xe5\x9b\x03\xca\xea\x9a\x03\xca\xeb\x9d\x03\xca\xe8" +
+ "\x9c\x03ؓ\x89\x03ߔ\x8b\x02\x010\x03\x03\x04\x1e\x03\x04\x15\x12\x03\x0b" +
+ "\x05,\x03\x06\x04\x00\x03\x06\x04)\x03\x06\x044\x03\x06\x04<\x03\x06\x05" +
+ "\x1d\x03\x06\x06\x00\x03\x06\x06\x0a\x03\x06\x06'\x03\x06\x062\x03\x0786" +
+ "\x03\x079/\x03\x079 \x03\x07:\x0e\x03\x07:\x1b\x03\x07:%\x03\x07;/\x03" +
+ "\x07;%\x03\x074\x11\x03\x076\x09\x03\x077*\x03\x070\x01\x03\x070\x0f\x03" +
+ "\x070.\x03\x071\x16\x03\x071\x04\x03\x0710\x03\x072\x18\x03\x072-\x03" +
+ "\x073\x14\x03\x073>\x03\x07'\x09\x03\x07 \x00\x03\x07\x1f\x0b\x03\x07" +
+ "\x18#\x03\x07\x18(\x03\x07\x186\x03\x07\x18\x03\x03\x07\x19\x16\x03\x07" +
+ "\x116\x03\x07\x12'\x03\x07\x13\x10\x03\x07\x0c&\x03\x07\x0c\x08\x03\x07" +
+ "\x0c\x13\x03\x07\x0d\x02\x03\x07\x0d\x1c\x03\x07\x0b5\x03\x07\x0b\x0a" +
+ "\x03\x07\x0b\x01\x03\x07\x0b\x0f\x03\x07\x05\x00\x03\x07\x05\x09\x03\x07" +
+ "\x05\x0b\x03\x07\x07\x01\x03\x07\x07\x08\x03\x07\x00<\x03\x07\x00+\x03" +
+ "\x07\x01)\x03\x07\x01\x1b\x03\x07\x01\x08\x03\x07\x03?\x03\x0445\x03\x04" +
+ "4\x08\x03\x0454\x03\x04)/\x03\x04)5\x03\x04+\x05\x03\x04+\x14\x03\x04+ " +
+ "\x03\x04+<\x03\x04*&\x03\x04*\x22\x03\x04&8\x03\x04!\x01\x03\x04!\x22" +
+ "\x03\x04\x11+\x03\x04\x10.\x03\x04\x104\x03\x04\x13=\x03\x04\x12\x04\x03" +
+ "\x04\x12\x0a\x03\x04\x0d\x1d\x03\x04\x0d\x07\x03\x04\x0d \x03\x05<>\x03" +
+ "\x055<\x03\x055!\x03\x055#\x03\x055&\x03\x054\x1d\x03\x054\x02\x03\x054" +
+ "\x07\x03\x0571\x03\x053\x1a\x03\x053\x16\x03\x05.<\x03\x05.\x07\x03\x05)" +
+ ":\x03\x05)<\x03\x05)\x0c\x03\x05)\x15\x03\x05+-\x03\x05+5\x03\x05$\x1e" +
+ "\x03\x05$\x14\x03\x05'\x04\x03\x05'\x14\x03\x05&\x02\x03\x05\x226\x03" +
+ "\x05\x22\x0c\x03\x05\x22\x1c\x03\x05\x19\x0a\x03\x05\x1b\x09\x03\x05\x1b" +
+ "\x0c\x03\x05\x14\x07\x03\x05\x16?\x03\x05\x16\x0c\x03\x05\x0c\x05\x03" +
+ "\x05\x0e\x0f\x03\x05\x01\x0e\x03\x05\x00(\x03\x05\x030\x03\x05\x03\x06" +
+ "\x03\x0a==\x03\x0a=1\x03\x0a=,\x03\x0a=\x0c\x03\x0a??\x03\x0a<\x08\x03" +
+ "\x0a9!\x03\x0a9)\x03\x0a97\x03\x0a99\x03\x0a6\x0a\x03\x0a6\x1c\x03\x0a6" +
+ "\x17\x03\x0a7'\x03\x0a78\x03\x0a73\x03\x0a'\x01\x03\x0a'&\x03\x0a\x1f" +
+ "\x0e\x03\x0a\x1f\x03\x03\x0a\x1f3\x03\x0a\x1b/\x03\x0a\x18\x19\x03\x0a" +
+ "\x19\x01\x03\x0a\x16\x14\x03\x0a\x0e\x22\x03\x0a\x0f\x10\x03\x0a\x0f\x02" +
+ "\x03\x0a\x0f \x03\x0a\x0c\x04\x03\x0a\x0b>\x03\x0a\x0b+\x03\x0a\x08/\x03" +
+ "\x0a\x046\x03\x0a\x05\x14\x03\x0a\x00\x04\x03\x0a\x00\x10\x03\x0a\x00" +
+ "\x14\x03\x0b<3\x03\x0b;*\x03\x0b9\x22\x03\x0b9)\x03\x0b97\x03\x0b+\x10" +
+ "\x03\x0b((\x03\x0b&5\x03\x0b$\x1c\x03\x0b$\x12\x03\x0b%\x04\x03\x0b#<" +
+ "\x03\x0b#0\x03\x0b#\x0d\x03\x0b#\x19\x03\x0b!:\x03\x0b!\x1f\x03\x0b!\x00" +
+ "\x03\x0b\x1e5\x03\x0b\x1c\x1d\x03\x0b\x1d-\x03\x0b\x1d(\x03\x0b\x18.\x03" +
+ "\x0b\x18 \x03\x0b\x18\x16\x03\x0b\x14\x13\x03\x0b\x15$\x03\x0b\x15\x22" +
+ "\x03\x0b\x12\x1b\x03\x0b\x12\x10\x03\x0b\x132\x03\x0b\x13=\x03\x0b\x12" +
+ "\x18\x03\x0b\x0c&\x03\x0b\x061\x03\x0b\x06:\x03\x0b\x05#\x03\x0b\x05<" +
+ "\x03\x0b\x04\x0b\x03\x0b\x04\x04\x03\x0b\x04\x1b\x03\x0b\x042\x03\x0b" +
+ "\x041\x03\x0b\x03\x03\x03\x0b\x03\x1d\x03\x0b\x03/\x03\x0b\x03+\x03\x0b" +
+ "\x02\x1b\x03\x0b\x02\x00\x03\x0b\x01\x1e\x03\x0b\x01\x08\x03\x0b\x015" +
+ "\x03\x06\x0d9\x03\x06\x0d=\x03\x06\x0d?\x03\x02\x001\x03\x02\x003\x03" +
+ "\x02\x02\x19\x03\x02\x006\x03\x02\x02\x1b\x03\x02\x004\x03\x02\x00<\x03" +
+ "\x02\x02\x0a\x03\x02\x02\x0e\x03\x02\x01\x1a\x03\x02\x01\x07\x03\x02\x01" +
+ "\x05\x03\x02\x01\x0b\x03\x02\x01%\x03\x02\x01\x0c\x03\x02\x01\x04\x03" +
+ "\x02\x01\x1c\x03\x02\x00.\x03\x02\x002\x03\x02\x00>\x03\x02\x00\x12\x03" +
+ "\x02\x00\x16\x03\x02\x011\x03\x02\x013\x03\x02\x02 \x03\x02\x02%\x03\x02" +
+ "\x02$\x03\x02\x028\x03\x02\x02;\x03\x02\x024\x03\x02\x012\x03\x02\x022" +
+ "\x03\x02\x02/\x03\x02\x01,\x03\x02\x01\x13\x03\x02\x01\x16\x03\x02\x01" +
+ "\x11\x03\x02\x01\x1e\x03\x02\x01\x15\x03\x02\x01\x17\x03\x02\x01\x0f\x03" +
+ "\x02\x01\x08\x03\x02\x00?\x03\x02\x03\x07\x03\x02\x03\x0d\x03\x02\x03" +
+ "\x13\x03\x02\x03\x1d\x03\x02\x03\x1f\x03\x02\x00\x03\x03\x02\x00\x0d\x03" +
+ "\x02\x00\x01\x03\x02\x00\x1b\x03\x02\x00\x19\x03\x02\x00\x18\x03\x02\x00" +
+ "\x13\x03\x02\x00/\x03\x07>\x12\x03\x07<\x1f\x03\x07>\x1d\x03\x06\x1d\x0e" +
+ "\x03\x07>\x1c\x03\x07>:\x03\x07>\x13\x03\x04\x12+\x03\x07?\x03\x03\x07>" +
+ "\x02\x03\x06\x224\x03\x06\x1a.\x03\x07<%\x03\x06\x1c\x0b\x03\x0609\x03" +
+ "\x05\x1f\x01\x03\x04'\x08\x03\x93\xfd\xf5\x03\x02\x0d \x03\x02\x0d#\x03" +
+ "\x02\x0d!\x03\x02\x0d&\x03\x02\x0d\x22\x03\x02\x0d/\x03\x02\x0d,\x03\x02" +
+ "\x0d$\x03\x02\x0d'\x03\x02\x0d%\x03\x02\x0d;\x03\x02\x0d=\x03\x02\x0d?" +
+ "\x03\x099.\x03\x08\x0b7\x03\x08\x02\x14\x03\x08\x14\x0d\x03\x08.:\x03" +
+ "\x089'\x03\x0f\x0b\x18\x03\x0f\x1c1\x03\x0f\x17&\x03\x0f9\x1f\x03\x0f0" +
+ "\x0c\x03\x0e\x0a9\x03\x0e\x056\x03\x0e\x1c#\x03\x0f\x13\x0e\x03\x072\x00" +
+ "\x03\x070\x0d\x03\x072\x0b\x03\x06\x11\x18\x03\x070\x10\x03\x06\x0f(\x03" +
+ "\x072\x05\x03\x06\x0f,\x03\x073\x15\x03\x06\x07\x08\x03\x05\x16\x02\x03" +
+ "\x04\x0b \x03\x05:8\x03\x05\x16%\x03\x0a\x0d\x1f\x03\x06\x16\x10\x03\x05" +
+ "\x1d5\x03\x05*;\x03\x05\x16\x1b\x03\x04.-\x03\x06\x1a\x19\x03\x04\x03," +
+ "\x03\x0b87\x03\x04/\x0a\x03\x06\x00,\x03\x04-\x01\x03\x04\x1e-\x03\x06/(" +
+ "\x03\x0a\x0b5\x03\x06\x0e7\x03\x06\x07.\x03\x0597\x03\x0a*%\x03\x0760" +
+ "\x03\x06\x0c;\x03\x05'\x00\x03\x072.\x03\x072\x08\x03\x06=\x01\x03\x06" +
+ "\x05\x1b\x03\x06\x06\x12\x03\x06$=\x03\x06'\x0d\x03\x04\x11\x0f\x03\x076" +
+ ",\x03\x06\x07;\x03\x06.,\x03\x86\xf9\xea\x03\x8f\xff\xeb\x02\x092\x02" +
+ "\x095\x02\x094\x02\x09;\x02\x09>\x02\x098\x02\x09*\x02\x09/\x02\x09,\x02" +
+ "\x09%\x02\x09&\x02\x09#\x02\x09 \x02\x08!\x02\x08%\x02\x08$\x02\x08+\x02" +
+ "\x08.\x02\x08*\x02\x08&\x02\x088\x02\x08>\x02\x084\x02\x086\x02\x080\x02" +
+ "\x08\x10\x02\x08\x17\x02\x08\x12\x02\x08\x1d\x02\x08\x1f\x02\x08\x13\x02" +
+ "\x08\x15\x02\x08\x14\x02\x08\x0c\x03\x8b\xfd\xd0\x03\x81\xec\xc6\x03\x87" +
+ "\xe0\x8a\x03-2\xe3\x03\x80\xef\xe4\x03-2\xea\x03\x88\xe6\xeb\x03\x8e\xe6" +
+ "\xe8\x03\x84\xe6\xe9\x03\x97\xe6\xee\x03-2\xf9\x03-2\xf6\x03\x8e\xe3\xad" +
+ "\x03\x80\xe3\x92\x03\x88\xe3\x90\x03\x8e\xe3\x90\x03\x80\xe3\x97\x03\x88" +
+ "\xe3\x95\x03\x88\xfe\xcb\x03\x8e\xfe\xca\x03\x84\xfe\xcd\x03\x91\xef\xc9" +
+ "\x03-2\xc1\x03-2\xc0\x03-2\xcb\x03\x88@\x09\x03\x8e@\x08\x03\x8f\xe0\xf5" +
+ "\x03\x8e\xe6\xf9\x03\x8e\xe0\xfa\x03\x93\xff\xf4\x03\x84\xee\xd3\x03\x0b" +
+ "(\x04\x023 \x021;\x02\x01*\x03\x0b#\x10\x03\x0b 0\x03\x0b!\x10\x03\x0b!0" +
+ "\x03\x07\x15\x08\x03\x09?5\x03\x07\x1f\x08\x03\x07\x17\x0b\x03\x09\x1f" +
+ "\x15\x03\x0b\x1c7\x03\x0a+#\x03\x06\x1a\x1b\x03\x06\x1a\x14\x03\x0a\x01" +
+ "\x18\x03\x06#\x1b\x03\x0a2\x0c\x03\x0a\x01\x04\x03\x09#;\x03\x08='\x03" +
+ "\x08\x1a\x0a\x03\x07</\x03\x07:+\x03\x07\x07*\x03\x06&\x1c\x03\x09\x0c" +
+ "\x16\x03\x09\x10\x0e\x03\x08'\x0f\x03\x08+\x09\x03\x074%\x03\x06!3\x03" +
+ "\x06\x03+\x03\x0b\x1e\x19\x03\x0a))\x03\x09\x08\x19\x03\x08,\x05\x03\x07" +
+ "<2\x03\x06\x1c>\x03\x0a\x111\x03\x09\x1b\x09\x03\x073.\x03\x07\x01\x00" +
+ "\x03\x09/,\x03\x07#>\x03\x07\x048\x03\x0a\x1f\x22\x03\x098>\x03\x09\x11" +
+ "\x00\x03\x08/\x17\x03\x06'\x22\x03\x0b\x1a+\x03\x0a\x22\x19\x03\x0a/1" +
+ "\x03\x0974\x03\x09\x0f\x22\x03\x08,\x22\x03\x08?\x14\x03\x07$5\x03\x07<3" +
+ "\x03\x07=*\x03\x07\x13\x18\x03\x068\x0a\x03\x06\x09\x16\x03\x06\x13\x00" +
+ "\x03\x08\x067\x03\x08\x01\x03\x03\x08\x12\x1d\x03\x07+7\x03\x06(;\x03" +
+ "\x06\x1c?\x03\x07\x0e\x17\x03\x0a\x06\x1d\x03\x0a\x19\x07\x03\x08\x14$" +
+ "\x03\x07$;\x03\x08,$\x03\x08\x06\x0d\x03\x07\x16\x0a\x03\x06>>\x03\x0a" +
+ "\x06\x12\x03\x0a\x14)\x03\x09\x0d\x1f\x03\x09\x12\x17\x03\x09\x19\x01" +
+ "\x03\x08\x11 \x03\x08\x1d'\x03\x06<\x1a\x03\x0a.\x00\x03\x07'\x18\x03" +
+ "\x0a\x22\x08\x03\x08\x0d\x0a\x03\x08\x13)\x03\x07*)\x03\x06<,\x03\x07" +
+ "\x0b\x1a\x03\x09.\x14\x03\x09\x0d\x1e\x03\x07\x0e#\x03\x0b\x1d'\x03\x0a" +
+ "\x0a8\x03\x09%2\x03\x08+&\x03\x080\x12\x03\x0a)4\x03\x08\x06\x1f\x03\x0b" +
+ "\x1b\x1a\x03\x0a\x1b\x0f\x03\x0b\x1d*\x03\x09\x16$\x03\x090\x11\x03\x08" +
+ "\x11\x08\x03\x0a*(\x03\x0a\x042\x03\x089,\x03\x074'\x03\x07\x0f\x05\x03" +
+ "\x09\x0b\x0a\x03\x07\x1b\x01\x03\x09\x17:\x03\x09.\x0d\x03\x07.\x11\x03" +
+ "\x09+\x15\x03\x080\x13\x03\x0b\x1f\x19\x03\x0a \x11\x03\x0a\x220\x03\x09" +
+ "\x07;\x03\x08\x16\x1c\x03\x07,\x13\x03\x07\x0e/\x03\x06\x221\x03\x0a." +
+ "\x0a\x03\x0a7\x02\x03\x0a\x032\x03\x0a\x1d.\x03\x091\x06\x03\x09\x19:" +
+ "\x03\x08\x02/\x03\x060+\x03\x06\x0f-\x03\x06\x1c\x1f\x03\x06\x1d\x07\x03" +
+ "\x0a,\x11\x03\x09=\x0d\x03\x09\x0b;\x03\x07\x1b/\x03\x0a\x1f:\x03\x09 " +
+ "\x1f\x03\x09.\x10\x03\x094\x0b\x03\x09\x1a1\x03\x08#\x1a\x03\x084\x1d" +
+ "\x03\x08\x01\x1f\x03\x08\x11\x22\x03\x07'8\x03\x07\x1a>\x03\x0757\x03" +
+ "\x06&9\x03\x06+\x11\x03\x0a.\x0b\x03\x0a,>\x03\x0a4#\x03\x08%\x17\x03" +
+ "\x07\x05\x22\x03\x07\x0c\x0b\x03\x0a\x1d+\x03\x0a\x19\x16\x03\x09+\x1f" +
+ "\x03\x09\x08\x0b\x03\x08\x16\x18\x03\x08+\x12\x03\x0b\x1d\x0c\x03\x0a=" +
+ "\x10\x03\x0a\x09\x0d\x03\x0a\x10\x11\x03\x09&0\x03\x08(\x1f\x03\x087\x07" +
+ "\x03\x08\x185\x03\x07'6\x03\x06.\x05\x03\x06=\x04\x03\x06;;\x03\x06\x06," +
+ "\x03\x0b\x18>\x03\x08\x00\x18\x03\x06 \x03\x03\x06<\x00\x03\x09%\x18\x03" +
+ "\x0b\x1c<\x03\x0a%!\x03\x0a\x09\x12\x03\x0a\x16\x02\x03\x090'\x03\x09" +
+ "\x0e=\x03\x08 \x0e\x03\x08>\x03\x03\x074>\x03\x06&?\x03\x06\x19\x09\x03" +
+ "\x06?(\x03\x0a-\x0e\x03\x09:3\x03\x098:\x03\x09\x12\x0b\x03\x09\x1d\x17" +
+ "\x03\x087\x05\x03\x082\x14\x03\x08\x06%\x03\x08\x13\x1f\x03\x06\x06\x0e" +
+ "\x03\x0a\x22<\x03\x09/<\x03\x06>+\x03\x0a'?\x03\x0a\x13\x0c\x03\x09\x10<" +
+ "\x03\x07\x1b=\x03\x0a\x19\x13\x03\x09\x22\x1d\x03\x09\x07\x0d\x03\x08)" +
+ "\x1c\x03\x06=\x1a\x03\x0a/4\x03\x0a7\x11\x03\x0a\x16:\x03\x09?3\x03\x09:" +
+ "/\x03\x09\x05\x0a\x03\x09\x14\x06\x03\x087\x22\x03\x080\x07\x03\x08\x1a" +
+ "\x1f\x03\x07\x04(\x03\x07\x04\x09\x03\x06 %\x03\x06<\x08\x03\x0a+\x14" +
+ "\x03\x09\x1d\x16\x03\x0a70\x03\x08 >\x03\x0857\x03\x070\x0a\x03\x06=\x12" +
+ "\x03\x06\x16%\x03\x06\x1d,\x03\x099#\x03\x09\x10>\x03\x07 \x1e\x03\x08" +
+ "\x0c<\x03\x08\x0b\x18\x03\x08\x15+\x03\x08,:\x03\x08%\x22\x03\x07\x0a$" +
+ "\x03\x0b\x1c=\x03\x07+\x08\x03\x0a/\x05\x03\x0a \x07\x03\x0a\x12'\x03" +
+ "\x09#\x11\x03\x08\x1b\x15\x03\x0a\x06\x01\x03\x09\x1c\x1b\x03\x0922\x03" +
+ "\x07\x14<\x03\x07\x09\x04\x03\x061\x04\x03\x07\x0e\x01\x03\x0a\x13\x18" +
+ "\x03\x0a-\x0c\x03\x0a?\x0d\x03\x0a\x09\x0a\x03\x091&\x03\x0a/\x0b\x03" +
+ "\x08$<\x03\x083\x1d\x03\x08\x0c$\x03\x08\x0d\x07\x03\x08\x0d?\x03\x08" +
+ "\x0e\x14\x03\x065\x0a\x03\x08\x1a#\x03\x08\x16#\x03\x0702\x03\x07\x03" +
+ "\x1a\x03\x06(\x1d\x03\x06+\x1b\x03\x06\x0b\x05\x03\x06\x0b\x17\x03\x06" +
+ "\x0c\x04\x03\x06\x1e\x19\x03\x06+0\x03\x062\x18\x03\x0b\x16\x1e\x03\x0a+" +
+ "\x16\x03\x0a-?\x03\x0a#:\x03\x0a#\x10\x03\x0a%$\x03\x0a>+\x03\x0a01\x03" +
+ "\x0a1\x10\x03\x0a\x099\x03\x0a\x0a\x12\x03\x0a\x19\x1f\x03\x0a\x19\x12" +
+ "\x03\x09*)\x03\x09-\x16\x03\x09.1\x03\x09.2\x03\x09<\x0e\x03\x09> \x03" +
+ "\x093\x12\x03\x09\x0b\x01\x03\x09\x1c2\x03\x09\x11\x1c\x03\x09\x15%\x03" +
+ "\x08,&\x03\x08!\x22\x03\x089(\x03\x08\x0b\x1a\x03\x08\x0d2\x03\x08\x0c" +
+ "\x04\x03\x08\x0c\x06\x03\x08\x0c\x1f\x03\x08\x0c\x0c\x03\x08\x0f\x1f\x03" +
+ "\x08\x0f\x1d\x03\x08\x00\x14\x03\x08\x03\x14\x03\x08\x06\x16\x03\x08\x1e" +
+ "#\x03\x08\x11\x11\x03\x08\x10\x18\x03\x08\x14(\x03\x07)\x1e\x03\x07.1" +
+ "\x03\x07 $\x03\x07 '\x03\x078\x08\x03\x07\x0d0\x03\x07\x0f7\x03\x07\x05#" +
+ "\x03\x07\x05\x1a\x03\x07\x1a7\x03\x07\x1d-\x03\x07\x17\x10\x03\x06)\x1f" +
+ "\x03\x062\x0b\x03\x066\x16\x03\x06\x09\x11\x03\x09(\x1e\x03\x07!5\x03" +
+ "\x0b\x11\x16\x03\x0a/\x04\x03\x0a,\x1a\x03\x0b\x173\x03\x0a,1\x03\x0a/5" +
+ "\x03\x0a\x221\x03\x0a\x22\x0d\x03\x0a?%\x03\x0a<,\x03\x0a?#\x03\x0a>\x19" +
+ "\x03\x0a\x08&\x03\x0a\x0b\x0e\x03\x0a\x0c:\x03\x0a\x0c+\x03\x0a\x03\x22" +
+ "\x03\x0a\x06)\x03\x0a\x11\x10\x03\x0a\x11\x1a\x03\x0a\x17-\x03\x0a\x14(" +
+ "\x03\x09)\x1e\x03\x09/\x09\x03\x09.\x00\x03\x09,\x07\x03\x09/*\x03\x09-9" +
+ "\x03\x09\x228\x03\x09%\x09\x03\x09:\x12\x03\x09;\x1d\x03\x09?\x06\x03" +
+ "\x093%\x03\x096\x05\x03\x096\x08\x03\x097\x02\x03\x09\x07,\x03\x09\x04," +
+ "\x03\x09\x1f\x16\x03\x09\x11\x03\x03\x09\x11\x12\x03\x09\x168\x03\x08*" +
+ "\x05\x03\x08/2\x03\x084:\x03\x08\x22+\x03\x08 0\x03\x08&\x0a\x03\x08;" +
+ "\x10\x03\x08>$\x03\x08>\x18\x03\x0829\x03\x082:\x03\x081,\x03\x081<\x03" +
+ "\x081\x1c\x03\x087#\x03\x087*\x03\x08\x09'\x03\x08\x00\x1d\x03\x08\x05-" +
+ "\x03\x08\x1f4\x03\x08\x1d\x04\x03\x08\x16\x0f\x03\x07*7\x03\x07'!\x03" +
+ "\x07%\x1b\x03\x077\x0c\x03\x07\x0c1\x03\x07\x0c.\x03\x07\x00\x06\x03\x07" +
+ "\x01\x02\x03\x07\x010\x03\x07\x06=\x03\x07\x01\x03\x03\x07\x01\x13\x03" +
+ "\x07\x06\x06\x03\x07\x05\x0a\x03\x07\x1f\x09\x03\x07\x17:\x03\x06*1\x03" +
+ "\x06-\x1d\x03\x06\x223\x03\x062:\x03\x060$\x03\x066\x1e\x03\x064\x12\x03" +
+ "\x0645\x03\x06\x0b\x00\x03\x06\x0b7\x03\x06\x07\x1f\x03\x06\x15\x12\x03" +
+ "\x0c\x05\x0f\x03\x0b+\x0b\x03\x0b+-\x03\x06\x16\x1b\x03\x06\x15\x17\x03" +
+ "\x89\xca\xea\x03\x89\xca\xe8\x03\x0c8\x10\x03\x0c8\x01\x03\x0c8\x0f\x03" +
+ "\x0d8%\x03\x0d8!\x03\x0c8-\x03\x0c8/\x03\x0c8+\x03\x0c87\x03\x0c85\x03" +
+ "\x0c9\x09\x03\x0c9\x0d\x03\x0c9\x0f\x03\x0c9\x0b\x03\xcfu\x0c\x03\xcfu" +
+ "\x0f\x03\xcfu\x0e\x03\xcfu\x09\x03\x0c9\x10\x03\x0d9\x0c\x03\xcf`;\x03" +
+ "\xcf`>\x03\xcf`9\x03\xcf`8\x03\xcf`7\x03\xcf`*\x03\xcf`-\x03\xcf`,\x03" +
+ "\x0d\x1b\x1a\x03\x0d\x1b&\x03\x0c=.\x03\x0c=%\x03\x0c>\x1e\x03\x0c>\x14" +
+ "\x03\x0c?\x06\x03\x0c?\x0b\x03\x0c?\x0c\x03\x0c?\x0d\x03\x0c?\x02\x03" +
+ "\x0c>\x0f\x03\x0c>\x08\x03\x0c>\x09\x03\x0c>,\x03\x0c>\x0c\x03\x0c?\x13" +
+ "\x03\x0c?\x16\x03\x0c?\x15\x03\x0c?\x1c\x03\x0c?\x1f\x03\x0c?\x1d\x03" +
+ "\x0c?\x1a\x03\x0c?\x17\x03\x0c?\x08\x03\x0c?\x09\x03\x0c?\x0e\x03\x0c?" +
+ "\x04\x03\x0c?\x05\x03\x0c<?\x03\x0c=\x00\x03\x0c=\x06\x03\x0c=\x05\x03" +
+ "\x0c=\x0c\x03\x0c=\x0f\x03\x0c=\x0d\x03\x0c=\x0b\x03\x0c=\x07\x03\x0c=" +
+ "\x19\x03\x0c=\x15\x03\x0c=\x11\x03\x0c=1\x03\x0c=3\x03\x0c=0\x03\x0c=>" +
+ "\x03\x0c=2\x03\x0c=6\x03\x0c<\x07\x03\x0c<\x05\x03\x0e:!\x03\x0e:#\x03" +
+ "\x0e8\x09\x03\x0e:&\x03\x0e8\x0b\x03\x0e:$\x03\x0e:,\x03\x0e8\x1a\x03" +
+ "\x0e8\x1e\x03\x0e:*\x03\x0e:7\x03\x0e:5\x03\x0e:;\x03\x0e:\x15\x03\x0e:<" +
+ "\x03\x0e:4\x03\x0e:'\x03\x0e:-\x03\x0e:%\x03\x0e:?\x03\x0e:=\x03\x0e:)" +
+ "\x03\x0e:/\x03\xcfs'\x03\x0d=\x0f\x03\x0d+*\x03\x0d99\x03\x0d9;\x03\x0d9" +
+ "?\x03\x0d)\x0d\x03\x0d(%\x02\x01\x18\x02\x01(\x02\x01\x1e\x03\x0f$!\x03" +
+ "\x0f87\x03\x0f4\x0e\x03\x0f5\x1d\x03\x06'\x03\x03\x0f\x08\x18\x03\x0f" +
+ "\x0d\x1b\x03\x0e2=\x03\x0e;\x08\x03\x0e:\x0b\x03\x0e\x06$\x03\x0e\x0d)" +
+ "\x03\x0e\x16\x1f\x03\x0e\x16\x1b\x03\x0d$\x0a\x03\x05,\x1d\x03\x0d. \x03" +
+ "\x0d.#\x03\x0c(/\x03\x09%\x02\x03\x0d90\x03\x0d\x0e4\x03\x0d\x0d\x0f\x03" +
+ "\x0c#\x00\x03\x0c,\x1e\x03\x0c2\x0e\x03\x0c\x01\x17\x03\x0c\x09:\x03\x0e" +
+ "\x173\x03\x0c\x08\x03\x03\x0c\x11\x07\x03\x0c\x10\x18\x03\x0c\x1f\x1c" +
+ "\x03\x0c\x19\x0e\x03\x0c\x1a\x1f\x03\x0f0>\x03\x0b->\x03\x0b<+\x03\x0b8" +
+ "\x13\x03\x0b\x043\x03\x0b\x14\x03\x03\x0b\x16%\x03\x0d\x22&\x03\x0b\x1a" +
+ "\x1a\x03\x0b\x1a\x04\x03\x0a%9\x03\x0a&2\x03\x0a&0\x03\x0a!\x1a\x03\x0a!" +
+ "7\x03\x0a5\x10\x03\x0a=4\x03\x0a?\x0e\x03\x0a>\x10\x03\x0a\x00 \x03\x0a" +
+ "\x0f:\x03\x0a\x0f9\x03\x0a\x0b\x0a\x03\x0a\x17%\x03\x0a\x1b-\x03\x09-" +
+ "\x1a\x03\x09,4\x03\x09.,\x03\x09)\x09\x03\x096!\x03\x091\x1f\x03\x093" +
+ "\x16\x03\x0c+\x1f\x03\x098 \x03\x098=\x03\x0c(\x1a\x03\x0c(\x16\x03\x09" +
+ "\x0a+\x03\x09\x16\x12\x03\x09\x13\x0e\x03\x09\x153\x03\x08)!\x03\x09\x1a" +
+ "\x01\x03\x09\x18\x01\x03\x08%#\x03\x08>\x22\x03\x08\x05%\x03\x08\x02*" +
+ "\x03\x08\x15;\x03\x08\x1b7\x03\x0f\x07\x1d\x03\x0f\x04\x03\x03\x070\x0c" +
+ "\x03\x07;\x0b\x03\x07\x08\x17\x03\x07\x12\x06\x03\x06/-\x03\x0671\x03" +
+ "\x065+\x03\x06>7\x03\x06\x049\x03\x05+\x1e\x03\x05,\x17\x03\x05 \x1d\x03" +
+ "\x05\x22\x05\x03\x050\x1d"
+
+// lookup returns the trie value for the first UTF-8 encoding in s and
+// the width in bytes of this encoding. The size will be 0 if s does not
+// hold enough bytes to complete the encoding. len(s) must be greater than 0.
+func (t *idnaTrie) lookup(s []byte) (v uint16, sz int) {
+ c0 := s[0]
+ switch {
+ case c0 < 0x80: // is ASCII
+ return idnaValues[c0], 1
+ case c0 < 0xC2:
+ return 0, 1 // Illegal UTF-8: not a starter, not ASCII.
+ case c0 < 0xE0: // 2-byte UTF-8
+ if len(s) < 2 {
+ return 0, 0
+ }
+ i := idnaIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c1), 2
+ case c0 < 0xF0: // 3-byte UTF-8
+ if len(s) < 3 {
+ return 0, 0
+ }
+ i := idnaIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = idnaIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c2), 3
+ case c0 < 0xF8: // 4-byte UTF-8
+ if len(s) < 4 {
+ return 0, 0
+ }
+ i := idnaIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = idnaIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ o = uint32(i)<<6 + uint32(c2)
+ i = idnaIndex[o]
+ c3 := s[3]
+ if c3 < 0x80 || 0xC0 <= c3 {
+ return 0, 3 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c3), 4
+ }
+ // Illegal rune
+ return 0, 1
+}
+
+// lookupUnsafe returns the trie value for the first UTF-8 encoding in s.
+// s must start with a full and valid UTF-8 encoded rune.
+func (t *idnaTrie) lookupUnsafe(s []byte) uint16 {
+ c0 := s[0]
+ if c0 < 0x80 { // is ASCII
+ return idnaValues[c0]
+ }
+ i := idnaIndex[c0]
+ if c0 < 0xE0 { // 2-byte UTF-8
+ return t.lookupValue(uint32(i), s[1])
+ }
+ i = idnaIndex[uint32(i)<<6+uint32(s[1])]
+ if c0 < 0xF0 { // 3-byte UTF-8
+ return t.lookupValue(uint32(i), s[2])
+ }
+ i = idnaIndex[uint32(i)<<6+uint32(s[2])]
+ if c0 < 0xF8 { // 4-byte UTF-8
+ return t.lookupValue(uint32(i), s[3])
+ }
+ return 0
+}
+
+// lookupString returns the trie value for the first UTF-8 encoding in s and
+// the width in bytes of this encoding. The size will be 0 if s does not
+// hold enough bytes to complete the encoding. len(s) must be greater than 0.
+func (t *idnaTrie) lookupString(s string) (v uint16, sz int) {
+ c0 := s[0]
+ switch {
+ case c0 < 0x80: // is ASCII
+ return idnaValues[c0], 1
+ case c0 < 0xC2:
+ return 0, 1 // Illegal UTF-8: not a starter, not ASCII.
+ case c0 < 0xE0: // 2-byte UTF-8
+ if len(s) < 2 {
+ return 0, 0
+ }
+ i := idnaIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c1), 2
+ case c0 < 0xF0: // 3-byte UTF-8
+ if len(s) < 3 {
+ return 0, 0
+ }
+ i := idnaIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = idnaIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c2), 3
+ case c0 < 0xF8: // 4-byte UTF-8
+ if len(s) < 4 {
+ return 0, 0
+ }
+ i := idnaIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = idnaIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ o = uint32(i)<<6 + uint32(c2)
+ i = idnaIndex[o]
+ c3 := s[3]
+ if c3 < 0x80 || 0xC0 <= c3 {
+ return 0, 3 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c3), 4
+ }
+ // Illegal rune
+ return 0, 1
+}
+
+// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s.
+// s must start with a full and valid UTF-8 encoded rune.
+func (t *idnaTrie) lookupStringUnsafe(s string) uint16 {
+ c0 := s[0]
+ if c0 < 0x80 { // is ASCII
+ return idnaValues[c0]
+ }
+ i := idnaIndex[c0]
+ if c0 < 0xE0 { // 2-byte UTF-8
+ return t.lookupValue(uint32(i), s[1])
+ }
+ i = idnaIndex[uint32(i)<<6+uint32(s[1])]
+ if c0 < 0xF0 { // 3-byte UTF-8
+ return t.lookupValue(uint32(i), s[2])
+ }
+ i = idnaIndex[uint32(i)<<6+uint32(s[2])]
+ if c0 < 0xF8 { // 4-byte UTF-8
+ return t.lookupValue(uint32(i), s[3])
+ }
+ return 0
+}
+
+// idnaTrie. Total size: 28496 bytes (27.83 KiB). Checksum: 43288b883596640e.
+type idnaTrie struct{}
+
+func newIdnaTrie(i int) *idnaTrie {
+ return &idnaTrie{}
+}
+
+// lookupValue determines the type of block n and looks up the value for b.
+func (t *idnaTrie) lookupValue(n uint32, b byte) uint16 {
+ switch {
+ case n < 123:
+ return uint16(idnaValues[n<<6+uint32(b)])
+ default:
+ n -= 123
+ return uint16(idnaSparse.lookup(n, b))
+ }
+}
+
+// idnaValues: 125 blocks, 8000 entries, 16000 bytes
+// The third block is the zero block.
+var idnaValues = [8000]uint16{
+ // Block 0x0, offset 0x0
+ 0x00: 0x0080, 0x01: 0x0080, 0x02: 0x0080, 0x03: 0x0080, 0x04: 0x0080, 0x05: 0x0080,
+ 0x06: 0x0080, 0x07: 0x0080, 0x08: 0x0080, 0x09: 0x0080, 0x0a: 0x0080, 0x0b: 0x0080,
+ 0x0c: 0x0080, 0x0d: 0x0080, 0x0e: 0x0080, 0x0f: 0x0080, 0x10: 0x0080, 0x11: 0x0080,
+ 0x12: 0x0080, 0x13: 0x0080, 0x14: 0x0080, 0x15: 0x0080, 0x16: 0x0080, 0x17: 0x0080,
+ 0x18: 0x0080, 0x19: 0x0080, 0x1a: 0x0080, 0x1b: 0x0080, 0x1c: 0x0080, 0x1d: 0x0080,
+ 0x1e: 0x0080, 0x1f: 0x0080, 0x20: 0x0080, 0x21: 0x0080, 0x22: 0x0080, 0x23: 0x0080,
+ 0x24: 0x0080, 0x25: 0x0080, 0x26: 0x0080, 0x27: 0x0080, 0x28: 0x0080, 0x29: 0x0080,
+ 0x2a: 0x0080, 0x2b: 0x0080, 0x2c: 0x0080, 0x2d: 0x0008, 0x2e: 0x0008, 0x2f: 0x0080,
+ 0x30: 0x0008, 0x31: 0x0008, 0x32: 0x0008, 0x33: 0x0008, 0x34: 0x0008, 0x35: 0x0008,
+ 0x36: 0x0008, 0x37: 0x0008, 0x38: 0x0008, 0x39: 0x0008, 0x3a: 0x0080, 0x3b: 0x0080,
+ 0x3c: 0x0080, 0x3d: 0x0080, 0x3e: 0x0080, 0x3f: 0x0080,
+ // Block 0x1, offset 0x40
+ 0x40: 0x0080, 0x41: 0xe105, 0x42: 0xe105, 0x43: 0xe105, 0x44: 0xe105, 0x45: 0xe105,
+ 0x46: 0xe105, 0x47: 0xe105, 0x48: 0xe105, 0x49: 0xe105, 0x4a: 0xe105, 0x4b: 0xe105,
+ 0x4c: 0xe105, 0x4d: 0xe105, 0x4e: 0xe105, 0x4f: 0xe105, 0x50: 0xe105, 0x51: 0xe105,
+ 0x52: 0xe105, 0x53: 0xe105, 0x54: 0xe105, 0x55: 0xe105, 0x56: 0xe105, 0x57: 0xe105,
+ 0x58: 0xe105, 0x59: 0xe105, 0x5a: 0xe105, 0x5b: 0x0080, 0x5c: 0x0080, 0x5d: 0x0080,
+ 0x5e: 0x0080, 0x5f: 0x0080, 0x60: 0x0080, 0x61: 0x0008, 0x62: 0x0008, 0x63: 0x0008,
+ 0x64: 0x0008, 0x65: 0x0008, 0x66: 0x0008, 0x67: 0x0008, 0x68: 0x0008, 0x69: 0x0008,
+ 0x6a: 0x0008, 0x6b: 0x0008, 0x6c: 0x0008, 0x6d: 0x0008, 0x6e: 0x0008, 0x6f: 0x0008,
+ 0x70: 0x0008, 0x71: 0x0008, 0x72: 0x0008, 0x73: 0x0008, 0x74: 0x0008, 0x75: 0x0008,
+ 0x76: 0x0008, 0x77: 0x0008, 0x78: 0x0008, 0x79: 0x0008, 0x7a: 0x0008, 0x7b: 0x0080,
+ 0x7c: 0x0080, 0x7d: 0x0080, 0x7e: 0x0080, 0x7f: 0x0080,
+ // Block 0x2, offset 0x80
+ // Block 0x3, offset 0xc0
+ 0xc0: 0x0040, 0xc1: 0x0040, 0xc2: 0x0040, 0xc3: 0x0040, 0xc4: 0x0040, 0xc5: 0x0040,
+ 0xc6: 0x0040, 0xc7: 0x0040, 0xc8: 0x0040, 0xc9: 0x0040, 0xca: 0x0040, 0xcb: 0x0040,
+ 0xcc: 0x0040, 0xcd: 0x0040, 0xce: 0x0040, 0xcf: 0x0040, 0xd0: 0x0040, 0xd1: 0x0040,
+ 0xd2: 0x0040, 0xd3: 0x0040, 0xd4: 0x0040, 0xd5: 0x0040, 0xd6: 0x0040, 0xd7: 0x0040,
+ 0xd8: 0x0040, 0xd9: 0x0040, 0xda: 0x0040, 0xdb: 0x0040, 0xdc: 0x0040, 0xdd: 0x0040,
+ 0xde: 0x0040, 0xdf: 0x0040, 0xe0: 0x000a, 0xe1: 0x0018, 0xe2: 0x0018, 0xe3: 0x0018,
+ 0xe4: 0x0018, 0xe5: 0x0018, 0xe6: 0x0018, 0xe7: 0x0018, 0xe8: 0x001a, 0xe9: 0x0018,
+ 0xea: 0x0039, 0xeb: 0x0018, 0xec: 0x0018, 0xed: 0x03c0, 0xee: 0x0018, 0xef: 0x004a,
+ 0xf0: 0x0018, 0xf1: 0x0018, 0xf2: 0x0069, 0xf3: 0x0079, 0xf4: 0x008a, 0xf5: 0x0005,
+ 0xf6: 0x0018, 0xf7: 0x0008, 0xf8: 0x00aa, 0xf9: 0x00c9, 0xfa: 0x00d9, 0xfb: 0x0018,
+ 0xfc: 0x00e9, 0xfd: 0x0119, 0xfe: 0x0149, 0xff: 0x0018,
+ // Block 0x4, offset 0x100
+ 0x100: 0xe00d, 0x101: 0x0008, 0x102: 0xe00d, 0x103: 0x0008, 0x104: 0xe00d, 0x105: 0x0008,
+ 0x106: 0xe00d, 0x107: 0x0008, 0x108: 0xe00d, 0x109: 0x0008, 0x10a: 0xe00d, 0x10b: 0x0008,
+ 0x10c: 0xe00d, 0x10d: 0x0008, 0x10e: 0xe00d, 0x10f: 0x0008, 0x110: 0xe00d, 0x111: 0x0008,
+ 0x112: 0xe00d, 0x113: 0x0008, 0x114: 0xe00d, 0x115: 0x0008, 0x116: 0xe00d, 0x117: 0x0008,
+ 0x118: 0xe00d, 0x119: 0x0008, 0x11a: 0xe00d, 0x11b: 0x0008, 0x11c: 0xe00d, 0x11d: 0x0008,
+ 0x11e: 0xe00d, 0x11f: 0x0008, 0x120: 0xe00d, 0x121: 0x0008, 0x122: 0xe00d, 0x123: 0x0008,
+ 0x124: 0xe00d, 0x125: 0x0008, 0x126: 0xe00d, 0x127: 0x0008, 0x128: 0xe00d, 0x129: 0x0008,
+ 0x12a: 0xe00d, 0x12b: 0x0008, 0x12c: 0xe00d, 0x12d: 0x0008, 0x12e: 0xe00d, 0x12f: 0x0008,
+ 0x130: 0x0179, 0x131: 0x0008, 0x132: 0x0035, 0x133: 0x004d, 0x134: 0xe00d, 0x135: 0x0008,
+ 0x136: 0xe00d, 0x137: 0x0008, 0x138: 0x0008, 0x139: 0xe01d, 0x13a: 0x0008, 0x13b: 0xe03d,
+ 0x13c: 0x0008, 0x13d: 0xe01d, 0x13e: 0x0008, 0x13f: 0x0199,
+ // Block 0x5, offset 0x140
+ 0x140: 0x0199, 0x141: 0xe01d, 0x142: 0x0008, 0x143: 0xe03d, 0x144: 0x0008, 0x145: 0xe01d,
+ 0x146: 0x0008, 0x147: 0xe07d, 0x148: 0x0008, 0x149: 0x01b9, 0x14a: 0xe00d, 0x14b: 0x0008,
+ 0x14c: 0xe00d, 0x14d: 0x0008, 0x14e: 0xe00d, 0x14f: 0x0008, 0x150: 0xe00d, 0x151: 0x0008,
+ 0x152: 0xe00d, 0x153: 0x0008, 0x154: 0xe00d, 0x155: 0x0008, 0x156: 0xe00d, 0x157: 0x0008,
+ 0x158: 0xe00d, 0x159: 0x0008, 0x15a: 0xe00d, 0x15b: 0x0008, 0x15c: 0xe00d, 0x15d: 0x0008,
+ 0x15e: 0xe00d, 0x15f: 0x0008, 0x160: 0xe00d, 0x161: 0x0008, 0x162: 0xe00d, 0x163: 0x0008,
+ 0x164: 0xe00d, 0x165: 0x0008, 0x166: 0xe00d, 0x167: 0x0008, 0x168: 0xe00d, 0x169: 0x0008,
+ 0x16a: 0xe00d, 0x16b: 0x0008, 0x16c: 0xe00d, 0x16d: 0x0008, 0x16e: 0xe00d, 0x16f: 0x0008,
+ 0x170: 0xe00d, 0x171: 0x0008, 0x172: 0xe00d, 0x173: 0x0008, 0x174: 0xe00d, 0x175: 0x0008,
+ 0x176: 0xe00d, 0x177: 0x0008, 0x178: 0x0065, 0x179: 0xe01d, 0x17a: 0x0008, 0x17b: 0xe03d,
+ 0x17c: 0x0008, 0x17d: 0xe01d, 0x17e: 0x0008, 0x17f: 0x01d9,
+ // Block 0x6, offset 0x180
+ 0x180: 0x0008, 0x181: 0x007d, 0x182: 0xe00d, 0x183: 0x0008, 0x184: 0xe00d, 0x185: 0x0008,
+ 0x186: 0x007d, 0x187: 0xe07d, 0x188: 0x0008, 0x189: 0x0095, 0x18a: 0x00ad, 0x18b: 0xe03d,
+ 0x18c: 0x0008, 0x18d: 0x0008, 0x18e: 0x00c5, 0x18f: 0x00dd, 0x190: 0x00f5, 0x191: 0xe01d,
+ 0x192: 0x0008, 0x193: 0x010d, 0x194: 0x0125, 0x195: 0x0008, 0x196: 0x013d, 0x197: 0x013d,
+ 0x198: 0xe00d, 0x199: 0x0008, 0x19a: 0x0008, 0x19b: 0x0008, 0x19c: 0x010d, 0x19d: 0x0155,
+ 0x19e: 0x0008, 0x19f: 0x016d, 0x1a0: 0xe00d, 0x1a1: 0x0008, 0x1a2: 0xe00d, 0x1a3: 0x0008,
+ 0x1a4: 0xe00d, 0x1a5: 0x0008, 0x1a6: 0x0185, 0x1a7: 0xe07d, 0x1a8: 0x0008, 0x1a9: 0x019d,
+ 0x1aa: 0x0008, 0x1ab: 0x0008, 0x1ac: 0xe00d, 0x1ad: 0x0008, 0x1ae: 0x0185, 0x1af: 0xe0fd,
+ 0x1b0: 0x0008, 0x1b1: 0x01b5, 0x1b2: 0x01cd, 0x1b3: 0xe03d, 0x1b4: 0x0008, 0x1b5: 0xe01d,
+ 0x1b6: 0x0008, 0x1b7: 0x01e5, 0x1b8: 0xe00d, 0x1b9: 0x0008, 0x1ba: 0x0008, 0x1bb: 0x0008,
+ 0x1bc: 0xe00d, 0x1bd: 0x0008, 0x1be: 0x0008, 0x1bf: 0x0008,
+ // Block 0x7, offset 0x1c0
+ 0x1c0: 0x0008, 0x1c1: 0x0008, 0x1c2: 0x0008, 0x1c3: 0x0008, 0x1c4: 0x01e9, 0x1c5: 0x01e9,
+ 0x1c6: 0x01e9, 0x1c7: 0x01fd, 0x1c8: 0x0215, 0x1c9: 0x022d, 0x1ca: 0x0245, 0x1cb: 0x025d,
+ 0x1cc: 0x0275, 0x1cd: 0xe01d, 0x1ce: 0x0008, 0x1cf: 0xe0fd, 0x1d0: 0x0008, 0x1d1: 0xe01d,
+ 0x1d2: 0x0008, 0x1d3: 0xe03d, 0x1d4: 0x0008, 0x1d5: 0xe01d, 0x1d6: 0x0008, 0x1d7: 0xe07d,
+ 0x1d8: 0x0008, 0x1d9: 0xe01d, 0x1da: 0x0008, 0x1db: 0xe03d, 0x1dc: 0x0008, 0x1dd: 0x0008,
+ 0x1de: 0xe00d, 0x1df: 0x0008, 0x1e0: 0xe00d, 0x1e1: 0x0008, 0x1e2: 0xe00d, 0x1e3: 0x0008,
+ 0x1e4: 0xe00d, 0x1e5: 0x0008, 0x1e6: 0xe00d, 0x1e7: 0x0008, 0x1e8: 0xe00d, 0x1e9: 0x0008,
+ 0x1ea: 0xe00d, 0x1eb: 0x0008, 0x1ec: 0xe00d, 0x1ed: 0x0008, 0x1ee: 0xe00d, 0x1ef: 0x0008,
+ 0x1f0: 0x0008, 0x1f1: 0x028d, 0x1f2: 0x02a5, 0x1f3: 0x02bd, 0x1f4: 0xe00d, 0x1f5: 0x0008,
+ 0x1f6: 0x02d5, 0x1f7: 0x02ed, 0x1f8: 0xe00d, 0x1f9: 0x0008, 0x1fa: 0xe00d, 0x1fb: 0x0008,
+ 0x1fc: 0xe00d, 0x1fd: 0x0008, 0x1fe: 0xe00d, 0x1ff: 0x0008,
+ // Block 0x8, offset 0x200
+ 0x200: 0xe00d, 0x201: 0x0008, 0x202: 0xe00d, 0x203: 0x0008, 0x204: 0xe00d, 0x205: 0x0008,
+ 0x206: 0xe00d, 0x207: 0x0008, 0x208: 0xe00d, 0x209: 0x0008, 0x20a: 0xe00d, 0x20b: 0x0008,
+ 0x20c: 0xe00d, 0x20d: 0x0008, 0x20e: 0xe00d, 0x20f: 0x0008, 0x210: 0xe00d, 0x211: 0x0008,
+ 0x212: 0xe00d, 0x213: 0x0008, 0x214: 0xe00d, 0x215: 0x0008, 0x216: 0xe00d, 0x217: 0x0008,
+ 0x218: 0xe00d, 0x219: 0x0008, 0x21a: 0xe00d, 0x21b: 0x0008, 0x21c: 0xe00d, 0x21d: 0x0008,
+ 0x21e: 0xe00d, 0x21f: 0x0008, 0x220: 0x0305, 0x221: 0x0008, 0x222: 0xe00d, 0x223: 0x0008,
+ 0x224: 0xe00d, 0x225: 0x0008, 0x226: 0xe00d, 0x227: 0x0008, 0x228: 0xe00d, 0x229: 0x0008,
+ 0x22a: 0xe00d, 0x22b: 0x0008, 0x22c: 0xe00d, 0x22d: 0x0008, 0x22e: 0xe00d, 0x22f: 0x0008,
+ 0x230: 0xe00d, 0x231: 0x0008, 0x232: 0xe00d, 0x233: 0x0008, 0x234: 0x0008, 0x235: 0x0008,
+ 0x236: 0x0008, 0x237: 0x0008, 0x238: 0x0008, 0x239: 0x0008, 0x23a: 0x0209, 0x23b: 0xe03d,
+ 0x23c: 0x0008, 0x23d: 0x031d, 0x23e: 0x0229, 0x23f: 0x0008,
+ // Block 0x9, offset 0x240
+ 0x240: 0x0008, 0x241: 0x0008, 0x242: 0x0018, 0x243: 0x0018, 0x244: 0x0018, 0x245: 0x0018,
+ 0x246: 0x0008, 0x247: 0x0008, 0x248: 0x0008, 0x249: 0x0008, 0x24a: 0x0008, 0x24b: 0x0008,
+ 0x24c: 0x0008, 0x24d: 0x0008, 0x24e: 0x0008, 0x24f: 0x0008, 0x250: 0x0008, 0x251: 0x0008,
+ 0x252: 0x0018, 0x253: 0x0018, 0x254: 0x0018, 0x255: 0x0018, 0x256: 0x0018, 0x257: 0x0018,
+ 0x258: 0x029a, 0x259: 0x02ba, 0x25a: 0x02da, 0x25b: 0x02fa, 0x25c: 0x031a, 0x25d: 0x033a,
+ 0x25e: 0x0018, 0x25f: 0x0018, 0x260: 0x03ad, 0x261: 0x0359, 0x262: 0x01d9, 0x263: 0x0369,
+ 0x264: 0x03c5, 0x265: 0x0018, 0x266: 0x0018, 0x267: 0x0018, 0x268: 0x0018, 0x269: 0x0018,
+ 0x26a: 0x0018, 0x26b: 0x0018, 0x26c: 0x0008, 0x26d: 0x0018, 0x26e: 0x0008, 0x26f: 0x0018,
+ 0x270: 0x0018, 0x271: 0x0018, 0x272: 0x0018, 0x273: 0x0018, 0x274: 0x0018, 0x275: 0x0018,
+ 0x276: 0x0018, 0x277: 0x0018, 0x278: 0x0018, 0x279: 0x0018, 0x27a: 0x0018, 0x27b: 0x0018,
+ 0x27c: 0x0018, 0x27d: 0x0018, 0x27e: 0x0018, 0x27f: 0x0018,
+ // Block 0xa, offset 0x280
+ 0x280: 0x03dd, 0x281: 0x03dd, 0x282: 0x1308, 0x283: 0x03f5, 0x284: 0x0379, 0x285: 0x040d,
+ 0x286: 0x1308, 0x287: 0x1308, 0x288: 0x1308, 0x289: 0x1308, 0x28a: 0x1308, 0x28b: 0x1308,
+ 0x28c: 0x1308, 0x28d: 0x1308, 0x28e: 0x1308, 0x28f: 0x13c0, 0x290: 0x1308, 0x291: 0x1308,
+ 0x292: 0x1308, 0x293: 0x1308, 0x294: 0x1308, 0x295: 0x1308, 0x296: 0x1308, 0x297: 0x1308,
+ 0x298: 0x1308, 0x299: 0x1308, 0x29a: 0x1308, 0x29b: 0x1308, 0x29c: 0x1308, 0x29d: 0x1308,
+ 0x29e: 0x1308, 0x29f: 0x1308, 0x2a0: 0x1308, 0x2a1: 0x1308, 0x2a2: 0x1308, 0x2a3: 0x1308,
+ 0x2a4: 0x1308, 0x2a5: 0x1308, 0x2a6: 0x1308, 0x2a7: 0x1308, 0x2a8: 0x1308, 0x2a9: 0x1308,
+ 0x2aa: 0x1308, 0x2ab: 0x1308, 0x2ac: 0x1308, 0x2ad: 0x1308, 0x2ae: 0x1308, 0x2af: 0x1308,
+ 0x2b0: 0xe00d, 0x2b1: 0x0008, 0x2b2: 0xe00d, 0x2b3: 0x0008, 0x2b4: 0x0425, 0x2b5: 0x0008,
+ 0x2b6: 0xe00d, 0x2b7: 0x0008, 0x2b8: 0x0040, 0x2b9: 0x0040, 0x2ba: 0x03a2, 0x2bb: 0x0008,
+ 0x2bc: 0x0008, 0x2bd: 0x0008, 0x2be: 0x03c2, 0x2bf: 0x043d,
+ // Block 0xb, offset 0x2c0
+ 0x2c0: 0x0040, 0x2c1: 0x0040, 0x2c2: 0x0040, 0x2c3: 0x0040, 0x2c4: 0x008a, 0x2c5: 0x03d2,
+ 0x2c6: 0xe155, 0x2c7: 0x0455, 0x2c8: 0xe12d, 0x2c9: 0xe13d, 0x2ca: 0xe12d, 0x2cb: 0x0040,
+ 0x2cc: 0x03dd, 0x2cd: 0x0040, 0x2ce: 0x046d, 0x2cf: 0x0485, 0x2d0: 0x0008, 0x2d1: 0xe105,
+ 0x2d2: 0xe105, 0x2d3: 0xe105, 0x2d4: 0xe105, 0x2d5: 0xe105, 0x2d6: 0xe105, 0x2d7: 0xe105,
+ 0x2d8: 0xe105, 0x2d9: 0xe105, 0x2da: 0xe105, 0x2db: 0xe105, 0x2dc: 0xe105, 0x2dd: 0xe105,
+ 0x2de: 0xe105, 0x2df: 0xe105, 0x2e0: 0x049d, 0x2e1: 0x049d, 0x2e2: 0x0040, 0x2e3: 0x049d,
+ 0x2e4: 0x049d, 0x2e5: 0x049d, 0x2e6: 0x049d, 0x2e7: 0x049d, 0x2e8: 0x049d, 0x2e9: 0x049d,
+ 0x2ea: 0x049d, 0x2eb: 0x049d, 0x2ec: 0x0008, 0x2ed: 0x0008, 0x2ee: 0x0008, 0x2ef: 0x0008,
+ 0x2f0: 0x0008, 0x2f1: 0x0008, 0x2f2: 0x0008, 0x2f3: 0x0008, 0x2f4: 0x0008, 0x2f5: 0x0008,
+ 0x2f6: 0x0008, 0x2f7: 0x0008, 0x2f8: 0x0008, 0x2f9: 0x0008, 0x2fa: 0x0008, 0x2fb: 0x0008,
+ 0x2fc: 0x0008, 0x2fd: 0x0008, 0x2fe: 0x0008, 0x2ff: 0x0008,
+ // Block 0xc, offset 0x300
+ 0x300: 0x0008, 0x301: 0x0008, 0x302: 0xe00f, 0x303: 0x0008, 0x304: 0x0008, 0x305: 0x0008,
+ 0x306: 0x0008, 0x307: 0x0008, 0x308: 0x0008, 0x309: 0x0008, 0x30a: 0x0008, 0x30b: 0x0008,
+ 0x30c: 0x0008, 0x30d: 0x0008, 0x30e: 0x0008, 0x30f: 0xe0c5, 0x310: 0x04b5, 0x311: 0x04cd,
+ 0x312: 0xe0bd, 0x313: 0xe0f5, 0x314: 0xe0fd, 0x315: 0xe09d, 0x316: 0xe0b5, 0x317: 0x0008,
+ 0x318: 0xe00d, 0x319: 0x0008, 0x31a: 0xe00d, 0x31b: 0x0008, 0x31c: 0xe00d, 0x31d: 0x0008,
+ 0x31e: 0xe00d, 0x31f: 0x0008, 0x320: 0xe00d, 0x321: 0x0008, 0x322: 0xe00d, 0x323: 0x0008,
+ 0x324: 0xe00d, 0x325: 0x0008, 0x326: 0xe00d, 0x327: 0x0008, 0x328: 0xe00d, 0x329: 0x0008,
+ 0x32a: 0xe00d, 0x32b: 0x0008, 0x32c: 0xe00d, 0x32d: 0x0008, 0x32e: 0xe00d, 0x32f: 0x0008,
+ 0x330: 0x04e5, 0x331: 0xe185, 0x332: 0xe18d, 0x333: 0x0008, 0x334: 0x04fd, 0x335: 0x03dd,
+ 0x336: 0x0018, 0x337: 0xe07d, 0x338: 0x0008, 0x339: 0xe1d5, 0x33a: 0xe00d, 0x33b: 0x0008,
+ 0x33c: 0x0008, 0x33d: 0x0515, 0x33e: 0x052d, 0x33f: 0x052d,
+ // Block 0xd, offset 0x340
+ 0x340: 0x0008, 0x341: 0x0008, 0x342: 0x0008, 0x343: 0x0008, 0x344: 0x0008, 0x345: 0x0008,
+ 0x346: 0x0008, 0x347: 0x0008, 0x348: 0x0008, 0x349: 0x0008, 0x34a: 0x0008, 0x34b: 0x0008,
+ 0x34c: 0x0008, 0x34d: 0x0008, 0x34e: 0x0008, 0x34f: 0x0008, 0x350: 0x0008, 0x351: 0x0008,
+ 0x352: 0x0008, 0x353: 0x0008, 0x354: 0x0008, 0x355: 0x0008, 0x356: 0x0008, 0x357: 0x0008,
+ 0x358: 0x0008, 0x359: 0x0008, 0x35a: 0x0008, 0x35b: 0x0008, 0x35c: 0x0008, 0x35d: 0x0008,
+ 0x35e: 0x0008, 0x35f: 0x0008, 0x360: 0xe00d, 0x361: 0x0008, 0x362: 0xe00d, 0x363: 0x0008,
+ 0x364: 0xe00d, 0x365: 0x0008, 0x366: 0xe00d, 0x367: 0x0008, 0x368: 0xe00d, 0x369: 0x0008,
+ 0x36a: 0xe00d, 0x36b: 0x0008, 0x36c: 0xe00d, 0x36d: 0x0008, 0x36e: 0xe00d, 0x36f: 0x0008,
+ 0x370: 0xe00d, 0x371: 0x0008, 0x372: 0xe00d, 0x373: 0x0008, 0x374: 0xe00d, 0x375: 0x0008,
+ 0x376: 0xe00d, 0x377: 0x0008, 0x378: 0xe00d, 0x379: 0x0008, 0x37a: 0xe00d, 0x37b: 0x0008,
+ 0x37c: 0xe00d, 0x37d: 0x0008, 0x37e: 0xe00d, 0x37f: 0x0008,
+ // Block 0xe, offset 0x380
+ 0x380: 0xe00d, 0x381: 0x0008, 0x382: 0x0018, 0x383: 0x1308, 0x384: 0x1308, 0x385: 0x1308,
+ 0x386: 0x1308, 0x387: 0x1308, 0x388: 0x1318, 0x389: 0x1318, 0x38a: 0xe00d, 0x38b: 0x0008,
+ 0x38c: 0xe00d, 0x38d: 0x0008, 0x38e: 0xe00d, 0x38f: 0x0008, 0x390: 0xe00d, 0x391: 0x0008,
+ 0x392: 0xe00d, 0x393: 0x0008, 0x394: 0xe00d, 0x395: 0x0008, 0x396: 0xe00d, 0x397: 0x0008,
+ 0x398: 0xe00d, 0x399: 0x0008, 0x39a: 0xe00d, 0x39b: 0x0008, 0x39c: 0xe00d, 0x39d: 0x0008,
+ 0x39e: 0xe00d, 0x39f: 0x0008, 0x3a0: 0xe00d, 0x3a1: 0x0008, 0x3a2: 0xe00d, 0x3a3: 0x0008,
+ 0x3a4: 0xe00d, 0x3a5: 0x0008, 0x3a6: 0xe00d, 0x3a7: 0x0008, 0x3a8: 0xe00d, 0x3a9: 0x0008,
+ 0x3aa: 0xe00d, 0x3ab: 0x0008, 0x3ac: 0xe00d, 0x3ad: 0x0008, 0x3ae: 0xe00d, 0x3af: 0x0008,
+ 0x3b0: 0xe00d, 0x3b1: 0x0008, 0x3b2: 0xe00d, 0x3b3: 0x0008, 0x3b4: 0xe00d, 0x3b5: 0x0008,
+ 0x3b6: 0xe00d, 0x3b7: 0x0008, 0x3b8: 0xe00d, 0x3b9: 0x0008, 0x3ba: 0xe00d, 0x3bb: 0x0008,
+ 0x3bc: 0xe00d, 0x3bd: 0x0008, 0x3be: 0xe00d, 0x3bf: 0x0008,
+ // Block 0xf, offset 0x3c0
+ 0x3c0: 0x0040, 0x3c1: 0xe01d, 0x3c2: 0x0008, 0x3c3: 0xe03d, 0x3c4: 0x0008, 0x3c5: 0xe01d,
+ 0x3c6: 0x0008, 0x3c7: 0xe07d, 0x3c8: 0x0008, 0x3c9: 0xe01d, 0x3ca: 0x0008, 0x3cb: 0xe03d,
+ 0x3cc: 0x0008, 0x3cd: 0xe01d, 0x3ce: 0x0008, 0x3cf: 0x0008, 0x3d0: 0xe00d, 0x3d1: 0x0008,
+ 0x3d2: 0xe00d, 0x3d3: 0x0008, 0x3d4: 0xe00d, 0x3d5: 0x0008, 0x3d6: 0xe00d, 0x3d7: 0x0008,
+ 0x3d8: 0xe00d, 0x3d9: 0x0008, 0x3da: 0xe00d, 0x3db: 0x0008, 0x3dc: 0xe00d, 0x3dd: 0x0008,
+ 0x3de: 0xe00d, 0x3df: 0x0008, 0x3e0: 0xe00d, 0x3e1: 0x0008, 0x3e2: 0xe00d, 0x3e3: 0x0008,
+ 0x3e4: 0xe00d, 0x3e5: 0x0008, 0x3e6: 0xe00d, 0x3e7: 0x0008, 0x3e8: 0xe00d, 0x3e9: 0x0008,
+ 0x3ea: 0xe00d, 0x3eb: 0x0008, 0x3ec: 0xe00d, 0x3ed: 0x0008, 0x3ee: 0xe00d, 0x3ef: 0x0008,
+ 0x3f0: 0xe00d, 0x3f1: 0x0008, 0x3f2: 0xe00d, 0x3f3: 0x0008, 0x3f4: 0xe00d, 0x3f5: 0x0008,
+ 0x3f6: 0xe00d, 0x3f7: 0x0008, 0x3f8: 0xe00d, 0x3f9: 0x0008, 0x3fa: 0xe00d, 0x3fb: 0x0008,
+ 0x3fc: 0xe00d, 0x3fd: 0x0008, 0x3fe: 0xe00d, 0x3ff: 0x0008,
+ // Block 0x10, offset 0x400
+ 0x400: 0xe00d, 0x401: 0x0008, 0x402: 0xe00d, 0x403: 0x0008, 0x404: 0xe00d, 0x405: 0x0008,
+ 0x406: 0xe00d, 0x407: 0x0008, 0x408: 0xe00d, 0x409: 0x0008, 0x40a: 0xe00d, 0x40b: 0x0008,
+ 0x40c: 0xe00d, 0x40d: 0x0008, 0x40e: 0xe00d, 0x40f: 0x0008, 0x410: 0xe00d, 0x411: 0x0008,
+ 0x412: 0xe00d, 0x413: 0x0008, 0x414: 0xe00d, 0x415: 0x0008, 0x416: 0xe00d, 0x417: 0x0008,
+ 0x418: 0xe00d, 0x419: 0x0008, 0x41a: 0xe00d, 0x41b: 0x0008, 0x41c: 0xe00d, 0x41d: 0x0008,
+ 0x41e: 0xe00d, 0x41f: 0x0008, 0x420: 0xe00d, 0x421: 0x0008, 0x422: 0xe00d, 0x423: 0x0008,
+ 0x424: 0xe00d, 0x425: 0x0008, 0x426: 0xe00d, 0x427: 0x0008, 0x428: 0xe00d, 0x429: 0x0008,
+ 0x42a: 0xe00d, 0x42b: 0x0008, 0x42c: 0xe00d, 0x42d: 0x0008, 0x42e: 0xe00d, 0x42f: 0x0008,
+ 0x430: 0x0040, 0x431: 0x03f5, 0x432: 0x03f5, 0x433: 0x03f5, 0x434: 0x03f5, 0x435: 0x03f5,
+ 0x436: 0x03f5, 0x437: 0x03f5, 0x438: 0x03f5, 0x439: 0x03f5, 0x43a: 0x03f5, 0x43b: 0x03f5,
+ 0x43c: 0x03f5, 0x43d: 0x03f5, 0x43e: 0x03f5, 0x43f: 0x03f5,
+ // Block 0x11, offset 0x440
+ 0x440: 0x0040, 0x441: 0x0040, 0x442: 0x0040, 0x443: 0x0040, 0x444: 0x0040, 0x445: 0x0040,
+ 0x446: 0x0018, 0x447: 0x0018, 0x448: 0x0018, 0x449: 0x0018, 0x44a: 0x0018, 0x44b: 0x0018,
+ 0x44c: 0x0018, 0x44d: 0x0018, 0x44e: 0x0018, 0x44f: 0x0018, 0x450: 0x1308, 0x451: 0x1308,
+ 0x452: 0x1308, 0x453: 0x1308, 0x454: 0x1308, 0x455: 0x1308, 0x456: 0x1308, 0x457: 0x1308,
+ 0x458: 0x1308, 0x459: 0x1308, 0x45a: 0x1308, 0x45b: 0x0018, 0x45c: 0x0340, 0x45d: 0x0040,
+ 0x45e: 0x0018, 0x45f: 0x0018, 0x460: 0x0208, 0x461: 0x0008, 0x462: 0x0408, 0x463: 0x0408,
+ 0x464: 0x0408, 0x465: 0x0408, 0x466: 0x0208, 0x467: 0x0408, 0x468: 0x0208, 0x469: 0x0408,
+ 0x46a: 0x0208, 0x46b: 0x0208, 0x46c: 0x0208, 0x46d: 0x0208, 0x46e: 0x0208, 0x46f: 0x0408,
+ 0x470: 0x0408, 0x471: 0x0408, 0x472: 0x0408, 0x473: 0x0208, 0x474: 0x0208, 0x475: 0x0208,
+ 0x476: 0x0208, 0x477: 0x0208, 0x478: 0x0208, 0x479: 0x0208, 0x47a: 0x0208, 0x47b: 0x0208,
+ 0x47c: 0x0208, 0x47d: 0x0208, 0x47e: 0x0208, 0x47f: 0x0208,
+ // Block 0x12, offset 0x480
+ 0x480: 0x0408, 0x481: 0x0208, 0x482: 0x0208, 0x483: 0x0408, 0x484: 0x0408, 0x485: 0x0408,
+ 0x486: 0x0408, 0x487: 0x0408, 0x488: 0x0408, 0x489: 0x0408, 0x48a: 0x0408, 0x48b: 0x0408,
+ 0x48c: 0x0208, 0x48d: 0x0408, 0x48e: 0x0208, 0x48f: 0x0408, 0x490: 0x0208, 0x491: 0x0208,
+ 0x492: 0x0408, 0x493: 0x0408, 0x494: 0x0018, 0x495: 0x0408, 0x496: 0x1308, 0x497: 0x1308,
+ 0x498: 0x1308, 0x499: 0x1308, 0x49a: 0x1308, 0x49b: 0x1308, 0x49c: 0x1308, 0x49d: 0x0040,
+ 0x49e: 0x0018, 0x49f: 0x1308, 0x4a0: 0x1308, 0x4a1: 0x1308, 0x4a2: 0x1308, 0x4a3: 0x1308,
+ 0x4a4: 0x1308, 0x4a5: 0x0008, 0x4a6: 0x0008, 0x4a7: 0x1308, 0x4a8: 0x1308, 0x4a9: 0x0018,
+ 0x4aa: 0x1308, 0x4ab: 0x1308, 0x4ac: 0x1308, 0x4ad: 0x1308, 0x4ae: 0x0408, 0x4af: 0x0408,
+ 0x4b0: 0x0008, 0x4b1: 0x0008, 0x4b2: 0x0008, 0x4b3: 0x0008, 0x4b4: 0x0008, 0x4b5: 0x0008,
+ 0x4b6: 0x0008, 0x4b7: 0x0008, 0x4b8: 0x0008, 0x4b9: 0x0008, 0x4ba: 0x0208, 0x4bb: 0x0208,
+ 0x4bc: 0x0208, 0x4bd: 0x0008, 0x4be: 0x0008, 0x4bf: 0x0208,
+ // Block 0x13, offset 0x4c0
+ 0x4c0: 0x0018, 0x4c1: 0x0018, 0x4c2: 0x0018, 0x4c3: 0x0018, 0x4c4: 0x0018, 0x4c5: 0x0018,
+ 0x4c6: 0x0018, 0x4c7: 0x0018, 0x4c8: 0x0018, 0x4c9: 0x0018, 0x4ca: 0x0018, 0x4cb: 0x0018,
+ 0x4cc: 0x0018, 0x4cd: 0x0018, 0x4ce: 0x0040, 0x4cf: 0x0340, 0x4d0: 0x0408, 0x4d1: 0x1308,
+ 0x4d2: 0x0208, 0x4d3: 0x0208, 0x4d4: 0x0208, 0x4d5: 0x0408, 0x4d6: 0x0408, 0x4d7: 0x0408,
+ 0x4d8: 0x0408, 0x4d9: 0x0408, 0x4da: 0x0208, 0x4db: 0x0208, 0x4dc: 0x0208, 0x4dd: 0x0208,
+ 0x4de: 0x0408, 0x4df: 0x0208, 0x4e0: 0x0208, 0x4e1: 0x0208, 0x4e2: 0x0208, 0x4e3: 0x0208,
+ 0x4e4: 0x0208, 0x4e5: 0x0208, 0x4e6: 0x0208, 0x4e7: 0x0208, 0x4e8: 0x0408, 0x4e9: 0x0208,
+ 0x4ea: 0x0408, 0x4eb: 0x0208, 0x4ec: 0x0408, 0x4ed: 0x0208, 0x4ee: 0x0208, 0x4ef: 0x0408,
+ 0x4f0: 0x1308, 0x4f1: 0x1308, 0x4f2: 0x1308, 0x4f3: 0x1308, 0x4f4: 0x1308, 0x4f5: 0x1308,
+ 0x4f6: 0x1308, 0x4f7: 0x1308, 0x4f8: 0x1308, 0x4f9: 0x1308, 0x4fa: 0x1308, 0x4fb: 0x1308,
+ 0x4fc: 0x1308, 0x4fd: 0x1308, 0x4fe: 0x1308, 0x4ff: 0x1308,
+ // Block 0x14, offset 0x500
+ 0x500: 0x1008, 0x501: 0x1308, 0x502: 0x1308, 0x503: 0x1308, 0x504: 0x1308, 0x505: 0x1308,
+ 0x506: 0x1308, 0x507: 0x1308, 0x508: 0x1308, 0x509: 0x1008, 0x50a: 0x1008, 0x50b: 0x1008,
+ 0x50c: 0x1008, 0x50d: 0x1b08, 0x50e: 0x1008, 0x50f: 0x1008, 0x510: 0x0008, 0x511: 0x1308,
+ 0x512: 0x1308, 0x513: 0x1308, 0x514: 0x1308, 0x515: 0x1308, 0x516: 0x1308, 0x517: 0x1308,
+ 0x518: 0x04c9, 0x519: 0x0501, 0x51a: 0x0539, 0x51b: 0x0571, 0x51c: 0x05a9, 0x51d: 0x05e1,
+ 0x51e: 0x0619, 0x51f: 0x0651, 0x520: 0x0008, 0x521: 0x0008, 0x522: 0x1308, 0x523: 0x1308,
+ 0x524: 0x0018, 0x525: 0x0018, 0x526: 0x0008, 0x527: 0x0008, 0x528: 0x0008, 0x529: 0x0008,
+ 0x52a: 0x0008, 0x52b: 0x0008, 0x52c: 0x0008, 0x52d: 0x0008, 0x52e: 0x0008, 0x52f: 0x0008,
+ 0x530: 0x0018, 0x531: 0x0008, 0x532: 0x0008, 0x533: 0x0008, 0x534: 0x0008, 0x535: 0x0008,
+ 0x536: 0x0008, 0x537: 0x0008, 0x538: 0x0008, 0x539: 0x0008, 0x53a: 0x0008, 0x53b: 0x0008,
+ 0x53c: 0x0008, 0x53d: 0x0008, 0x53e: 0x0008, 0x53f: 0x0008,
+ // Block 0x15, offset 0x540
+ 0x540: 0x0008, 0x541: 0x1308, 0x542: 0x1008, 0x543: 0x1008, 0x544: 0x0040, 0x545: 0x0008,
+ 0x546: 0x0008, 0x547: 0x0008, 0x548: 0x0008, 0x549: 0x0008, 0x54a: 0x0008, 0x54b: 0x0008,
+ 0x54c: 0x0008, 0x54d: 0x0040, 0x54e: 0x0040, 0x54f: 0x0008, 0x550: 0x0008, 0x551: 0x0040,
+ 0x552: 0x0040, 0x553: 0x0008, 0x554: 0x0008, 0x555: 0x0008, 0x556: 0x0008, 0x557: 0x0008,
+ 0x558: 0x0008, 0x559: 0x0008, 0x55a: 0x0008, 0x55b: 0x0008, 0x55c: 0x0008, 0x55d: 0x0008,
+ 0x55e: 0x0008, 0x55f: 0x0008, 0x560: 0x0008, 0x561: 0x0008, 0x562: 0x0008, 0x563: 0x0008,
+ 0x564: 0x0008, 0x565: 0x0008, 0x566: 0x0008, 0x567: 0x0008, 0x568: 0x0008, 0x569: 0x0040,
+ 0x56a: 0x0008, 0x56b: 0x0008, 0x56c: 0x0008, 0x56d: 0x0008, 0x56e: 0x0008, 0x56f: 0x0008,
+ 0x570: 0x0008, 0x571: 0x0040, 0x572: 0x0008, 0x573: 0x0040, 0x574: 0x0040, 0x575: 0x0040,
+ 0x576: 0x0008, 0x577: 0x0008, 0x578: 0x0008, 0x579: 0x0008, 0x57a: 0x0040, 0x57b: 0x0040,
+ 0x57c: 0x1308, 0x57d: 0x0008, 0x57e: 0x1008, 0x57f: 0x1008,
+ // Block 0x16, offset 0x580
+ 0x580: 0x1008, 0x581: 0x1308, 0x582: 0x1308, 0x583: 0x1308, 0x584: 0x1308, 0x585: 0x0040,
+ 0x586: 0x0040, 0x587: 0x1008, 0x588: 0x1008, 0x589: 0x0040, 0x58a: 0x0040, 0x58b: 0x1008,
+ 0x58c: 0x1008, 0x58d: 0x1b08, 0x58e: 0x0008, 0x58f: 0x0040, 0x590: 0x0040, 0x591: 0x0040,
+ 0x592: 0x0040, 0x593: 0x0040, 0x594: 0x0040, 0x595: 0x0040, 0x596: 0x0040, 0x597: 0x1008,
+ 0x598: 0x0040, 0x599: 0x0040, 0x59a: 0x0040, 0x59b: 0x0040, 0x59c: 0x0689, 0x59d: 0x06c1,
+ 0x59e: 0x0040, 0x59f: 0x06f9, 0x5a0: 0x0008, 0x5a1: 0x0008, 0x5a2: 0x1308, 0x5a3: 0x1308,
+ 0x5a4: 0x0040, 0x5a5: 0x0040, 0x5a6: 0x0008, 0x5a7: 0x0008, 0x5a8: 0x0008, 0x5a9: 0x0008,
+ 0x5aa: 0x0008, 0x5ab: 0x0008, 0x5ac: 0x0008, 0x5ad: 0x0008, 0x5ae: 0x0008, 0x5af: 0x0008,
+ 0x5b0: 0x0008, 0x5b1: 0x0008, 0x5b2: 0x0018, 0x5b3: 0x0018, 0x5b4: 0x0018, 0x5b5: 0x0018,
+ 0x5b6: 0x0018, 0x5b7: 0x0018, 0x5b8: 0x0018, 0x5b9: 0x0018, 0x5ba: 0x0018, 0x5bb: 0x0018,
+ 0x5bc: 0x0040, 0x5bd: 0x0040, 0x5be: 0x0040, 0x5bf: 0x0040,
+ // Block 0x17, offset 0x5c0
+ 0x5c0: 0x0040, 0x5c1: 0x1308, 0x5c2: 0x1308, 0x5c3: 0x1008, 0x5c4: 0x0040, 0x5c5: 0x0008,
+ 0x5c6: 0x0008, 0x5c7: 0x0008, 0x5c8: 0x0008, 0x5c9: 0x0008, 0x5ca: 0x0008, 0x5cb: 0x0040,
+ 0x5cc: 0x0040, 0x5cd: 0x0040, 0x5ce: 0x0040, 0x5cf: 0x0008, 0x5d0: 0x0008, 0x5d1: 0x0040,
+ 0x5d2: 0x0040, 0x5d3: 0x0008, 0x5d4: 0x0008, 0x5d5: 0x0008, 0x5d6: 0x0008, 0x5d7: 0x0008,
+ 0x5d8: 0x0008, 0x5d9: 0x0008, 0x5da: 0x0008, 0x5db: 0x0008, 0x5dc: 0x0008, 0x5dd: 0x0008,
+ 0x5de: 0x0008, 0x5df: 0x0008, 0x5e0: 0x0008, 0x5e1: 0x0008, 0x5e2: 0x0008, 0x5e3: 0x0008,
+ 0x5e4: 0x0008, 0x5e5: 0x0008, 0x5e6: 0x0008, 0x5e7: 0x0008, 0x5e8: 0x0008, 0x5e9: 0x0040,
+ 0x5ea: 0x0008, 0x5eb: 0x0008, 0x5ec: 0x0008, 0x5ed: 0x0008, 0x5ee: 0x0008, 0x5ef: 0x0008,
+ 0x5f0: 0x0008, 0x5f1: 0x0040, 0x5f2: 0x0008, 0x5f3: 0x0731, 0x5f4: 0x0040, 0x5f5: 0x0008,
+ 0x5f6: 0x0769, 0x5f7: 0x0040, 0x5f8: 0x0008, 0x5f9: 0x0008, 0x5fa: 0x0040, 0x5fb: 0x0040,
+ 0x5fc: 0x1308, 0x5fd: 0x0040, 0x5fe: 0x1008, 0x5ff: 0x1008,
+ // Block 0x18, offset 0x600
+ 0x600: 0x1008, 0x601: 0x1308, 0x602: 0x1308, 0x603: 0x0040, 0x604: 0x0040, 0x605: 0x0040,
+ 0x606: 0x0040, 0x607: 0x1308, 0x608: 0x1308, 0x609: 0x0040, 0x60a: 0x0040, 0x60b: 0x1308,
+ 0x60c: 0x1308, 0x60d: 0x1b08, 0x60e: 0x0040, 0x60f: 0x0040, 0x610: 0x0040, 0x611: 0x1308,
+ 0x612: 0x0040, 0x613: 0x0040, 0x614: 0x0040, 0x615: 0x0040, 0x616: 0x0040, 0x617: 0x0040,
+ 0x618: 0x0040, 0x619: 0x07a1, 0x61a: 0x07d9, 0x61b: 0x0811, 0x61c: 0x0008, 0x61d: 0x0040,
+ 0x61e: 0x0849, 0x61f: 0x0040, 0x620: 0x0040, 0x621: 0x0040, 0x622: 0x0040, 0x623: 0x0040,
+ 0x624: 0x0040, 0x625: 0x0040, 0x626: 0x0008, 0x627: 0x0008, 0x628: 0x0008, 0x629: 0x0008,
+ 0x62a: 0x0008, 0x62b: 0x0008, 0x62c: 0x0008, 0x62d: 0x0008, 0x62e: 0x0008, 0x62f: 0x0008,
+ 0x630: 0x1308, 0x631: 0x1308, 0x632: 0x0008, 0x633: 0x0008, 0x634: 0x0008, 0x635: 0x1308,
+ 0x636: 0x0040, 0x637: 0x0040, 0x638: 0x0040, 0x639: 0x0040, 0x63a: 0x0040, 0x63b: 0x0040,
+ 0x63c: 0x0040, 0x63d: 0x0040, 0x63e: 0x0040, 0x63f: 0x0040,
+ // Block 0x19, offset 0x640
+ 0x640: 0x0040, 0x641: 0x1308, 0x642: 0x1308, 0x643: 0x1008, 0x644: 0x0040, 0x645: 0x0008,
+ 0x646: 0x0008, 0x647: 0x0008, 0x648: 0x0008, 0x649: 0x0008, 0x64a: 0x0008, 0x64b: 0x0008,
+ 0x64c: 0x0008, 0x64d: 0x0008, 0x64e: 0x0040, 0x64f: 0x0008, 0x650: 0x0008, 0x651: 0x0008,
+ 0x652: 0x0040, 0x653: 0x0008, 0x654: 0x0008, 0x655: 0x0008, 0x656: 0x0008, 0x657: 0x0008,
+ 0x658: 0x0008, 0x659: 0x0008, 0x65a: 0x0008, 0x65b: 0x0008, 0x65c: 0x0008, 0x65d: 0x0008,
+ 0x65e: 0x0008, 0x65f: 0x0008, 0x660: 0x0008, 0x661: 0x0008, 0x662: 0x0008, 0x663: 0x0008,
+ 0x664: 0x0008, 0x665: 0x0008, 0x666: 0x0008, 0x667: 0x0008, 0x668: 0x0008, 0x669: 0x0040,
+ 0x66a: 0x0008, 0x66b: 0x0008, 0x66c: 0x0008, 0x66d: 0x0008, 0x66e: 0x0008, 0x66f: 0x0008,
+ 0x670: 0x0008, 0x671: 0x0040, 0x672: 0x0008, 0x673: 0x0008, 0x674: 0x0040, 0x675: 0x0008,
+ 0x676: 0x0008, 0x677: 0x0008, 0x678: 0x0008, 0x679: 0x0008, 0x67a: 0x0040, 0x67b: 0x0040,
+ 0x67c: 0x1308, 0x67d: 0x0008, 0x67e: 0x1008, 0x67f: 0x1008,
+ // Block 0x1a, offset 0x680
+ 0x680: 0x1008, 0x681: 0x1308, 0x682: 0x1308, 0x683: 0x1308, 0x684: 0x1308, 0x685: 0x1308,
+ 0x686: 0x0040, 0x687: 0x1308, 0x688: 0x1308, 0x689: 0x1008, 0x68a: 0x0040, 0x68b: 0x1008,
+ 0x68c: 0x1008, 0x68d: 0x1b08, 0x68e: 0x0040, 0x68f: 0x0040, 0x690: 0x0008, 0x691: 0x0040,
+ 0x692: 0x0040, 0x693: 0x0040, 0x694: 0x0040, 0x695: 0x0040, 0x696: 0x0040, 0x697: 0x0040,
+ 0x698: 0x0040, 0x699: 0x0040, 0x69a: 0x0040, 0x69b: 0x0040, 0x69c: 0x0040, 0x69d: 0x0040,
+ 0x69e: 0x0040, 0x69f: 0x0040, 0x6a0: 0x0008, 0x6a1: 0x0008, 0x6a2: 0x1308, 0x6a3: 0x1308,
+ 0x6a4: 0x0040, 0x6a5: 0x0040, 0x6a6: 0x0008, 0x6a7: 0x0008, 0x6a8: 0x0008, 0x6a9: 0x0008,
+ 0x6aa: 0x0008, 0x6ab: 0x0008, 0x6ac: 0x0008, 0x6ad: 0x0008, 0x6ae: 0x0008, 0x6af: 0x0008,
+ 0x6b0: 0x0018, 0x6b1: 0x0018, 0x6b2: 0x0040, 0x6b3: 0x0040, 0x6b4: 0x0040, 0x6b5: 0x0040,
+ 0x6b6: 0x0040, 0x6b7: 0x0040, 0x6b8: 0x0040, 0x6b9: 0x0008, 0x6ba: 0x0040, 0x6bb: 0x0040,
+ 0x6bc: 0x0040, 0x6bd: 0x0040, 0x6be: 0x0040, 0x6bf: 0x0040,
+ // Block 0x1b, offset 0x6c0
+ 0x6c0: 0x0040, 0x6c1: 0x1308, 0x6c2: 0x1008, 0x6c3: 0x1008, 0x6c4: 0x0040, 0x6c5: 0x0008,
+ 0x6c6: 0x0008, 0x6c7: 0x0008, 0x6c8: 0x0008, 0x6c9: 0x0008, 0x6ca: 0x0008, 0x6cb: 0x0008,
+ 0x6cc: 0x0008, 0x6cd: 0x0040, 0x6ce: 0x0040, 0x6cf: 0x0008, 0x6d0: 0x0008, 0x6d1: 0x0040,
+ 0x6d2: 0x0040, 0x6d3: 0x0008, 0x6d4: 0x0008, 0x6d5: 0x0008, 0x6d6: 0x0008, 0x6d7: 0x0008,
+ 0x6d8: 0x0008, 0x6d9: 0x0008, 0x6da: 0x0008, 0x6db: 0x0008, 0x6dc: 0x0008, 0x6dd: 0x0008,
+ 0x6de: 0x0008, 0x6df: 0x0008, 0x6e0: 0x0008, 0x6e1: 0x0008, 0x6e2: 0x0008, 0x6e3: 0x0008,
+ 0x6e4: 0x0008, 0x6e5: 0x0008, 0x6e6: 0x0008, 0x6e7: 0x0008, 0x6e8: 0x0008, 0x6e9: 0x0040,
+ 0x6ea: 0x0008, 0x6eb: 0x0008, 0x6ec: 0x0008, 0x6ed: 0x0008, 0x6ee: 0x0008, 0x6ef: 0x0008,
+ 0x6f0: 0x0008, 0x6f1: 0x0040, 0x6f2: 0x0008, 0x6f3: 0x0008, 0x6f4: 0x0040, 0x6f5: 0x0008,
+ 0x6f6: 0x0008, 0x6f7: 0x0008, 0x6f8: 0x0008, 0x6f9: 0x0008, 0x6fa: 0x0040, 0x6fb: 0x0040,
+ 0x6fc: 0x1308, 0x6fd: 0x0008, 0x6fe: 0x1008, 0x6ff: 0x1308,
+ // Block 0x1c, offset 0x700
+ 0x700: 0x1008, 0x701: 0x1308, 0x702: 0x1308, 0x703: 0x1308, 0x704: 0x1308, 0x705: 0x0040,
+ 0x706: 0x0040, 0x707: 0x1008, 0x708: 0x1008, 0x709: 0x0040, 0x70a: 0x0040, 0x70b: 0x1008,
+ 0x70c: 0x1008, 0x70d: 0x1b08, 0x70e: 0x0040, 0x70f: 0x0040, 0x710: 0x0040, 0x711: 0x0040,
+ 0x712: 0x0040, 0x713: 0x0040, 0x714: 0x0040, 0x715: 0x0040, 0x716: 0x1308, 0x717: 0x1008,
+ 0x718: 0x0040, 0x719: 0x0040, 0x71a: 0x0040, 0x71b: 0x0040, 0x71c: 0x0881, 0x71d: 0x08b9,
+ 0x71e: 0x0040, 0x71f: 0x0008, 0x720: 0x0008, 0x721: 0x0008, 0x722: 0x1308, 0x723: 0x1308,
+ 0x724: 0x0040, 0x725: 0x0040, 0x726: 0x0008, 0x727: 0x0008, 0x728: 0x0008, 0x729: 0x0008,
+ 0x72a: 0x0008, 0x72b: 0x0008, 0x72c: 0x0008, 0x72d: 0x0008, 0x72e: 0x0008, 0x72f: 0x0008,
+ 0x730: 0x0018, 0x731: 0x0008, 0x732: 0x0018, 0x733: 0x0018, 0x734: 0x0018, 0x735: 0x0018,
+ 0x736: 0x0018, 0x737: 0x0018, 0x738: 0x0040, 0x739: 0x0040, 0x73a: 0x0040, 0x73b: 0x0040,
+ 0x73c: 0x0040, 0x73d: 0x0040, 0x73e: 0x0040, 0x73f: 0x0040,
+ // Block 0x1d, offset 0x740
+ 0x740: 0x0040, 0x741: 0x0040, 0x742: 0x1308, 0x743: 0x0008, 0x744: 0x0040, 0x745: 0x0008,
+ 0x746: 0x0008, 0x747: 0x0008, 0x748: 0x0008, 0x749: 0x0008, 0x74a: 0x0008, 0x74b: 0x0040,
+ 0x74c: 0x0040, 0x74d: 0x0040, 0x74e: 0x0008, 0x74f: 0x0008, 0x750: 0x0008, 0x751: 0x0040,
+ 0x752: 0x0008, 0x753: 0x0008, 0x754: 0x0008, 0x755: 0x0008, 0x756: 0x0040, 0x757: 0x0040,
+ 0x758: 0x0040, 0x759: 0x0008, 0x75a: 0x0008, 0x75b: 0x0040, 0x75c: 0x0008, 0x75d: 0x0040,
+ 0x75e: 0x0008, 0x75f: 0x0008, 0x760: 0x0040, 0x761: 0x0040, 0x762: 0x0040, 0x763: 0x0008,
+ 0x764: 0x0008, 0x765: 0x0040, 0x766: 0x0040, 0x767: 0x0040, 0x768: 0x0008, 0x769: 0x0008,
+ 0x76a: 0x0008, 0x76b: 0x0040, 0x76c: 0x0040, 0x76d: 0x0040, 0x76e: 0x0008, 0x76f: 0x0008,
+ 0x770: 0x0008, 0x771: 0x0008, 0x772: 0x0008, 0x773: 0x0008, 0x774: 0x0008, 0x775: 0x0008,
+ 0x776: 0x0008, 0x777: 0x0008, 0x778: 0x0008, 0x779: 0x0008, 0x77a: 0x0040, 0x77b: 0x0040,
+ 0x77c: 0x0040, 0x77d: 0x0040, 0x77e: 0x1008, 0x77f: 0x1008,
+ // Block 0x1e, offset 0x780
+ 0x780: 0x1308, 0x781: 0x1008, 0x782: 0x1008, 0x783: 0x1008, 0x784: 0x1008, 0x785: 0x0040,
+ 0x786: 0x1308, 0x787: 0x1308, 0x788: 0x1308, 0x789: 0x0040, 0x78a: 0x1308, 0x78b: 0x1308,
+ 0x78c: 0x1308, 0x78d: 0x1b08, 0x78e: 0x0040, 0x78f: 0x0040, 0x790: 0x0040, 0x791: 0x0040,
+ 0x792: 0x0040, 0x793: 0x0040, 0x794: 0x0040, 0x795: 0x1308, 0x796: 0x1308, 0x797: 0x0040,
+ 0x798: 0x0008, 0x799: 0x0008, 0x79a: 0x0008, 0x79b: 0x0040, 0x79c: 0x0040, 0x79d: 0x0040,
+ 0x79e: 0x0040, 0x79f: 0x0040, 0x7a0: 0x0008, 0x7a1: 0x0008, 0x7a2: 0x1308, 0x7a3: 0x1308,
+ 0x7a4: 0x0040, 0x7a5: 0x0040, 0x7a6: 0x0008, 0x7a7: 0x0008, 0x7a8: 0x0008, 0x7a9: 0x0008,
+ 0x7aa: 0x0008, 0x7ab: 0x0008, 0x7ac: 0x0008, 0x7ad: 0x0008, 0x7ae: 0x0008, 0x7af: 0x0008,
+ 0x7b0: 0x0040, 0x7b1: 0x0040, 0x7b2: 0x0040, 0x7b3: 0x0040, 0x7b4: 0x0040, 0x7b5: 0x0040,
+ 0x7b6: 0x0040, 0x7b7: 0x0040, 0x7b8: 0x0018, 0x7b9: 0x0018, 0x7ba: 0x0018, 0x7bb: 0x0018,
+ 0x7bc: 0x0018, 0x7bd: 0x0018, 0x7be: 0x0018, 0x7bf: 0x0018,
+ // Block 0x1f, offset 0x7c0
+ 0x7c0: 0x0008, 0x7c1: 0x1308, 0x7c2: 0x1008, 0x7c3: 0x1008, 0x7c4: 0x0040, 0x7c5: 0x0008,
+ 0x7c6: 0x0008, 0x7c7: 0x0008, 0x7c8: 0x0008, 0x7c9: 0x0008, 0x7ca: 0x0008, 0x7cb: 0x0008,
+ 0x7cc: 0x0008, 0x7cd: 0x0040, 0x7ce: 0x0008, 0x7cf: 0x0008, 0x7d0: 0x0008, 0x7d1: 0x0040,
+ 0x7d2: 0x0008, 0x7d3: 0x0008, 0x7d4: 0x0008, 0x7d5: 0x0008, 0x7d6: 0x0008, 0x7d7: 0x0008,
+ 0x7d8: 0x0008, 0x7d9: 0x0008, 0x7da: 0x0008, 0x7db: 0x0008, 0x7dc: 0x0008, 0x7dd: 0x0008,
+ 0x7de: 0x0008, 0x7df: 0x0008, 0x7e0: 0x0008, 0x7e1: 0x0008, 0x7e2: 0x0008, 0x7e3: 0x0008,
+ 0x7e4: 0x0008, 0x7e5: 0x0008, 0x7e6: 0x0008, 0x7e7: 0x0008, 0x7e8: 0x0008, 0x7e9: 0x0040,
+ 0x7ea: 0x0008, 0x7eb: 0x0008, 0x7ec: 0x0008, 0x7ed: 0x0008, 0x7ee: 0x0008, 0x7ef: 0x0008,
+ 0x7f0: 0x0008, 0x7f1: 0x0008, 0x7f2: 0x0008, 0x7f3: 0x0008, 0x7f4: 0x0040, 0x7f5: 0x0008,
+ 0x7f6: 0x0008, 0x7f7: 0x0008, 0x7f8: 0x0008, 0x7f9: 0x0008, 0x7fa: 0x0040, 0x7fb: 0x0040,
+ 0x7fc: 0x1308, 0x7fd: 0x0008, 0x7fe: 0x1008, 0x7ff: 0x1308,
+ // Block 0x20, offset 0x800
+ 0x800: 0x1008, 0x801: 0x1008, 0x802: 0x1008, 0x803: 0x1008, 0x804: 0x1008, 0x805: 0x0040,
+ 0x806: 0x1308, 0x807: 0x1008, 0x808: 0x1008, 0x809: 0x0040, 0x80a: 0x1008, 0x80b: 0x1008,
+ 0x80c: 0x1308, 0x80d: 0x1b08, 0x80e: 0x0040, 0x80f: 0x0040, 0x810: 0x0040, 0x811: 0x0040,
+ 0x812: 0x0040, 0x813: 0x0040, 0x814: 0x0040, 0x815: 0x1008, 0x816: 0x1008, 0x817: 0x0040,
+ 0x818: 0x0040, 0x819: 0x0040, 0x81a: 0x0040, 0x81b: 0x0040, 0x81c: 0x0040, 0x81d: 0x0040,
+ 0x81e: 0x0008, 0x81f: 0x0040, 0x820: 0x0008, 0x821: 0x0008, 0x822: 0x1308, 0x823: 0x1308,
+ 0x824: 0x0040, 0x825: 0x0040, 0x826: 0x0008, 0x827: 0x0008, 0x828: 0x0008, 0x829: 0x0008,
+ 0x82a: 0x0008, 0x82b: 0x0008, 0x82c: 0x0008, 0x82d: 0x0008, 0x82e: 0x0008, 0x82f: 0x0008,
+ 0x830: 0x0040, 0x831: 0x0008, 0x832: 0x0008, 0x833: 0x0040, 0x834: 0x0040, 0x835: 0x0040,
+ 0x836: 0x0040, 0x837: 0x0040, 0x838: 0x0040, 0x839: 0x0040, 0x83a: 0x0040, 0x83b: 0x0040,
+ 0x83c: 0x0040, 0x83d: 0x0040, 0x83e: 0x0040, 0x83f: 0x0040,
+ // Block 0x21, offset 0x840
+ 0x840: 0x1008, 0x841: 0x1308, 0x842: 0x1308, 0x843: 0x1308, 0x844: 0x1308, 0x845: 0x0040,
+ 0x846: 0x1008, 0x847: 0x1008, 0x848: 0x1008, 0x849: 0x0040, 0x84a: 0x1008, 0x84b: 0x1008,
+ 0x84c: 0x1008, 0x84d: 0x1b08, 0x84e: 0x0008, 0x84f: 0x0018, 0x850: 0x0040, 0x851: 0x0040,
+ 0x852: 0x0040, 0x853: 0x0040, 0x854: 0x0008, 0x855: 0x0008, 0x856: 0x0008, 0x857: 0x1008,
+ 0x858: 0x0018, 0x859: 0x0018, 0x85a: 0x0018, 0x85b: 0x0018, 0x85c: 0x0018, 0x85d: 0x0018,
+ 0x85e: 0x0018, 0x85f: 0x0008, 0x860: 0x0008, 0x861: 0x0008, 0x862: 0x1308, 0x863: 0x1308,
+ 0x864: 0x0040, 0x865: 0x0040, 0x866: 0x0008, 0x867: 0x0008, 0x868: 0x0008, 0x869: 0x0008,
+ 0x86a: 0x0008, 0x86b: 0x0008, 0x86c: 0x0008, 0x86d: 0x0008, 0x86e: 0x0008, 0x86f: 0x0008,
+ 0x870: 0x0018, 0x871: 0x0018, 0x872: 0x0018, 0x873: 0x0018, 0x874: 0x0018, 0x875: 0x0018,
+ 0x876: 0x0018, 0x877: 0x0018, 0x878: 0x0018, 0x879: 0x0018, 0x87a: 0x0008, 0x87b: 0x0008,
+ 0x87c: 0x0008, 0x87d: 0x0008, 0x87e: 0x0008, 0x87f: 0x0008,
+ // Block 0x22, offset 0x880
+ 0x880: 0x0040, 0x881: 0x0008, 0x882: 0x0008, 0x883: 0x0040, 0x884: 0x0008, 0x885: 0x0040,
+ 0x886: 0x0040, 0x887: 0x0008, 0x888: 0x0008, 0x889: 0x0040, 0x88a: 0x0008, 0x88b: 0x0040,
+ 0x88c: 0x0040, 0x88d: 0x0008, 0x88e: 0x0040, 0x88f: 0x0040, 0x890: 0x0040, 0x891: 0x0040,
+ 0x892: 0x0040, 0x893: 0x0040, 0x894: 0x0008, 0x895: 0x0008, 0x896: 0x0008, 0x897: 0x0008,
+ 0x898: 0x0040, 0x899: 0x0008, 0x89a: 0x0008, 0x89b: 0x0008, 0x89c: 0x0008, 0x89d: 0x0008,
+ 0x89e: 0x0008, 0x89f: 0x0008, 0x8a0: 0x0040, 0x8a1: 0x0008, 0x8a2: 0x0008, 0x8a3: 0x0008,
+ 0x8a4: 0x0040, 0x8a5: 0x0008, 0x8a6: 0x0040, 0x8a7: 0x0008, 0x8a8: 0x0040, 0x8a9: 0x0040,
+ 0x8aa: 0x0008, 0x8ab: 0x0008, 0x8ac: 0x0040, 0x8ad: 0x0008, 0x8ae: 0x0008, 0x8af: 0x0008,
+ 0x8b0: 0x0008, 0x8b1: 0x1308, 0x8b2: 0x0008, 0x8b3: 0x0929, 0x8b4: 0x1308, 0x8b5: 0x1308,
+ 0x8b6: 0x1308, 0x8b7: 0x1308, 0x8b8: 0x1308, 0x8b9: 0x1308, 0x8ba: 0x0040, 0x8bb: 0x1308,
+ 0x8bc: 0x1308, 0x8bd: 0x0008, 0x8be: 0x0040, 0x8bf: 0x0040,
+ // Block 0x23, offset 0x8c0
+ 0x8c0: 0x0008, 0x8c1: 0x0008, 0x8c2: 0x0008, 0x8c3: 0x09d1, 0x8c4: 0x0008, 0x8c5: 0x0008,
+ 0x8c6: 0x0008, 0x8c7: 0x0008, 0x8c8: 0x0040, 0x8c9: 0x0008, 0x8ca: 0x0008, 0x8cb: 0x0008,
+ 0x8cc: 0x0008, 0x8cd: 0x0a09, 0x8ce: 0x0008, 0x8cf: 0x0008, 0x8d0: 0x0008, 0x8d1: 0x0008,
+ 0x8d2: 0x0a41, 0x8d3: 0x0008, 0x8d4: 0x0008, 0x8d5: 0x0008, 0x8d6: 0x0008, 0x8d7: 0x0a79,
+ 0x8d8: 0x0008, 0x8d9: 0x0008, 0x8da: 0x0008, 0x8db: 0x0008, 0x8dc: 0x0ab1, 0x8dd: 0x0008,
+ 0x8de: 0x0008, 0x8df: 0x0008, 0x8e0: 0x0008, 0x8e1: 0x0008, 0x8e2: 0x0008, 0x8e3: 0x0008,
+ 0x8e4: 0x0008, 0x8e5: 0x0008, 0x8e6: 0x0008, 0x8e7: 0x0008, 0x8e8: 0x0008, 0x8e9: 0x0ae9,
+ 0x8ea: 0x0008, 0x8eb: 0x0008, 0x8ec: 0x0008, 0x8ed: 0x0040, 0x8ee: 0x0040, 0x8ef: 0x0040,
+ 0x8f0: 0x0040, 0x8f1: 0x1308, 0x8f2: 0x1308, 0x8f3: 0x0b21, 0x8f4: 0x1308, 0x8f5: 0x0b59,
+ 0x8f6: 0x0b91, 0x8f7: 0x0bc9, 0x8f8: 0x0c19, 0x8f9: 0x0c51, 0x8fa: 0x1308, 0x8fb: 0x1308,
+ 0x8fc: 0x1308, 0x8fd: 0x1308, 0x8fe: 0x1308, 0x8ff: 0x1008,
+ // Block 0x24, offset 0x900
+ 0x900: 0x1308, 0x901: 0x0ca1, 0x902: 0x1308, 0x903: 0x1308, 0x904: 0x1b08, 0x905: 0x0018,
+ 0x906: 0x1308, 0x907: 0x1308, 0x908: 0x0008, 0x909: 0x0008, 0x90a: 0x0008, 0x90b: 0x0008,
+ 0x90c: 0x0008, 0x90d: 0x1308, 0x90e: 0x1308, 0x90f: 0x1308, 0x910: 0x1308, 0x911: 0x1308,
+ 0x912: 0x1308, 0x913: 0x0cd9, 0x914: 0x1308, 0x915: 0x1308, 0x916: 0x1308, 0x917: 0x1308,
+ 0x918: 0x0040, 0x919: 0x1308, 0x91a: 0x1308, 0x91b: 0x1308, 0x91c: 0x1308, 0x91d: 0x0d11,
+ 0x91e: 0x1308, 0x91f: 0x1308, 0x920: 0x1308, 0x921: 0x1308, 0x922: 0x0d49, 0x923: 0x1308,
+ 0x924: 0x1308, 0x925: 0x1308, 0x926: 0x1308, 0x927: 0x0d81, 0x928: 0x1308, 0x929: 0x1308,
+ 0x92a: 0x1308, 0x92b: 0x1308, 0x92c: 0x0db9, 0x92d: 0x1308, 0x92e: 0x1308, 0x92f: 0x1308,
+ 0x930: 0x1308, 0x931: 0x1308, 0x932: 0x1308, 0x933: 0x1308, 0x934: 0x1308, 0x935: 0x1308,
+ 0x936: 0x1308, 0x937: 0x1308, 0x938: 0x1308, 0x939: 0x0df1, 0x93a: 0x1308, 0x93b: 0x1308,
+ 0x93c: 0x1308, 0x93d: 0x0040, 0x93e: 0x0018, 0x93f: 0x0018,
+ // Block 0x25, offset 0x940
+ 0x940: 0x0008, 0x941: 0x0008, 0x942: 0x0008, 0x943: 0x0008, 0x944: 0x0008, 0x945: 0x0008,
+ 0x946: 0x0008, 0x947: 0x0008, 0x948: 0x0008, 0x949: 0x0008, 0x94a: 0x0008, 0x94b: 0x0008,
+ 0x94c: 0x0008, 0x94d: 0x0008, 0x94e: 0x0008, 0x94f: 0x0008, 0x950: 0x0008, 0x951: 0x0008,
+ 0x952: 0x0008, 0x953: 0x0008, 0x954: 0x0008, 0x955: 0x0008, 0x956: 0x0008, 0x957: 0x0008,
+ 0x958: 0x0008, 0x959: 0x0008, 0x95a: 0x0008, 0x95b: 0x0008, 0x95c: 0x0008, 0x95d: 0x0008,
+ 0x95e: 0x0008, 0x95f: 0x0008, 0x960: 0x0008, 0x961: 0x0008, 0x962: 0x0008, 0x963: 0x0008,
+ 0x964: 0x0008, 0x965: 0x0008, 0x966: 0x0008, 0x967: 0x0008, 0x968: 0x0008, 0x969: 0x0008,
+ 0x96a: 0x0008, 0x96b: 0x0008, 0x96c: 0x0039, 0x96d: 0x0ed1, 0x96e: 0x0ee9, 0x96f: 0x0008,
+ 0x970: 0x0ef9, 0x971: 0x0f09, 0x972: 0x0f19, 0x973: 0x0f31, 0x974: 0x0249, 0x975: 0x0f41,
+ 0x976: 0x0259, 0x977: 0x0f51, 0x978: 0x0359, 0x979: 0x0f61, 0x97a: 0x0f71, 0x97b: 0x0008,
+ 0x97c: 0x00d9, 0x97d: 0x0f81, 0x97e: 0x0f99, 0x97f: 0x0269,
+ // Block 0x26, offset 0x980
+ 0x980: 0x0fa9, 0x981: 0x0fb9, 0x982: 0x0279, 0x983: 0x0039, 0x984: 0x0fc9, 0x985: 0x0fe1,
+ 0x986: 0x059d, 0x987: 0x0ee9, 0x988: 0x0ef9, 0x989: 0x0f09, 0x98a: 0x0ff9, 0x98b: 0x1011,
+ 0x98c: 0x1029, 0x98d: 0x0f31, 0x98e: 0x0008, 0x98f: 0x0f51, 0x990: 0x0f61, 0x991: 0x1041,
+ 0x992: 0x00d9, 0x993: 0x1059, 0x994: 0x05b5, 0x995: 0x05b5, 0x996: 0x0f99, 0x997: 0x0fa9,
+ 0x998: 0x0fb9, 0x999: 0x059d, 0x99a: 0x1071, 0x99b: 0x1089, 0x99c: 0x05cd, 0x99d: 0x1099,
+ 0x99e: 0x10b1, 0x99f: 0x10c9, 0x9a0: 0x10e1, 0x9a1: 0x10f9, 0x9a2: 0x0f41, 0x9a3: 0x0269,
+ 0x9a4: 0x0fb9, 0x9a5: 0x1089, 0x9a6: 0x1099, 0x9a7: 0x10b1, 0x9a8: 0x1111, 0x9a9: 0x10e1,
+ 0x9aa: 0x10f9, 0x9ab: 0x0008, 0x9ac: 0x0008, 0x9ad: 0x0008, 0x9ae: 0x0008, 0x9af: 0x0008,
+ 0x9b0: 0x0008, 0x9b1: 0x0008, 0x9b2: 0x0008, 0x9b3: 0x0008, 0x9b4: 0x0008, 0x9b5: 0x0008,
+ 0x9b6: 0x0008, 0x9b7: 0x0008, 0x9b8: 0x1129, 0x9b9: 0x0008, 0x9ba: 0x0008, 0x9bb: 0x0008,
+ 0x9bc: 0x0008, 0x9bd: 0x0008, 0x9be: 0x0008, 0x9bf: 0x0008,
+ // Block 0x27, offset 0x9c0
+ 0x9c0: 0x0008, 0x9c1: 0x0008, 0x9c2: 0x0008, 0x9c3: 0x0008, 0x9c4: 0x0008, 0x9c5: 0x0008,
+ 0x9c6: 0x0008, 0x9c7: 0x0008, 0x9c8: 0x0008, 0x9c9: 0x0008, 0x9ca: 0x0008, 0x9cb: 0x0008,
+ 0x9cc: 0x0008, 0x9cd: 0x0008, 0x9ce: 0x0008, 0x9cf: 0x0008, 0x9d0: 0x0008, 0x9d1: 0x0008,
+ 0x9d2: 0x0008, 0x9d3: 0x0008, 0x9d4: 0x0008, 0x9d5: 0x0008, 0x9d6: 0x0008, 0x9d7: 0x0008,
+ 0x9d8: 0x0008, 0x9d9: 0x0008, 0x9da: 0x0008, 0x9db: 0x1141, 0x9dc: 0x1159, 0x9dd: 0x1169,
+ 0x9de: 0x1181, 0x9df: 0x1029, 0x9e0: 0x1199, 0x9e1: 0x11a9, 0x9e2: 0x11c1, 0x9e3: 0x11d9,
+ 0x9e4: 0x11f1, 0x9e5: 0x1209, 0x9e6: 0x1221, 0x9e7: 0x05e5, 0x9e8: 0x1239, 0x9e9: 0x1251,
+ 0x9ea: 0xe17d, 0x9eb: 0x1269, 0x9ec: 0x1281, 0x9ed: 0x1299, 0x9ee: 0x12b1, 0x9ef: 0x12c9,
+ 0x9f0: 0x12e1, 0x9f1: 0x12f9, 0x9f2: 0x1311, 0x9f3: 0x1329, 0x9f4: 0x1341, 0x9f5: 0x1359,
+ 0x9f6: 0x1371, 0x9f7: 0x1389, 0x9f8: 0x05fd, 0x9f9: 0x13a1, 0x9fa: 0x13b9, 0x9fb: 0x13d1,
+ 0x9fc: 0x13e1, 0x9fd: 0x13f9, 0x9fe: 0x1411, 0x9ff: 0x1429,
+ // Block 0x28, offset 0xa00
+ 0xa00: 0xe00d, 0xa01: 0x0008, 0xa02: 0xe00d, 0xa03: 0x0008, 0xa04: 0xe00d, 0xa05: 0x0008,
+ 0xa06: 0xe00d, 0xa07: 0x0008, 0xa08: 0xe00d, 0xa09: 0x0008, 0xa0a: 0xe00d, 0xa0b: 0x0008,
+ 0xa0c: 0xe00d, 0xa0d: 0x0008, 0xa0e: 0xe00d, 0xa0f: 0x0008, 0xa10: 0xe00d, 0xa11: 0x0008,
+ 0xa12: 0xe00d, 0xa13: 0x0008, 0xa14: 0xe00d, 0xa15: 0x0008, 0xa16: 0xe00d, 0xa17: 0x0008,
+ 0xa18: 0xe00d, 0xa19: 0x0008, 0xa1a: 0xe00d, 0xa1b: 0x0008, 0xa1c: 0xe00d, 0xa1d: 0x0008,
+ 0xa1e: 0xe00d, 0xa1f: 0x0008, 0xa20: 0xe00d, 0xa21: 0x0008, 0xa22: 0xe00d, 0xa23: 0x0008,
+ 0xa24: 0xe00d, 0xa25: 0x0008, 0xa26: 0xe00d, 0xa27: 0x0008, 0xa28: 0xe00d, 0xa29: 0x0008,
+ 0xa2a: 0xe00d, 0xa2b: 0x0008, 0xa2c: 0xe00d, 0xa2d: 0x0008, 0xa2e: 0xe00d, 0xa2f: 0x0008,
+ 0xa30: 0xe00d, 0xa31: 0x0008, 0xa32: 0xe00d, 0xa33: 0x0008, 0xa34: 0xe00d, 0xa35: 0x0008,
+ 0xa36: 0xe00d, 0xa37: 0x0008, 0xa38: 0xe00d, 0xa39: 0x0008, 0xa3a: 0xe00d, 0xa3b: 0x0008,
+ 0xa3c: 0xe00d, 0xa3d: 0x0008, 0xa3e: 0xe00d, 0xa3f: 0x0008,
+ // Block 0x29, offset 0xa40
+ 0xa40: 0xe00d, 0xa41: 0x0008, 0xa42: 0xe00d, 0xa43: 0x0008, 0xa44: 0xe00d, 0xa45: 0x0008,
+ 0xa46: 0xe00d, 0xa47: 0x0008, 0xa48: 0xe00d, 0xa49: 0x0008, 0xa4a: 0xe00d, 0xa4b: 0x0008,
+ 0xa4c: 0xe00d, 0xa4d: 0x0008, 0xa4e: 0xe00d, 0xa4f: 0x0008, 0xa50: 0xe00d, 0xa51: 0x0008,
+ 0xa52: 0xe00d, 0xa53: 0x0008, 0xa54: 0xe00d, 0xa55: 0x0008, 0xa56: 0x0008, 0xa57: 0x0008,
+ 0xa58: 0x0008, 0xa59: 0x0008, 0xa5a: 0x0615, 0xa5b: 0x0635, 0xa5c: 0x0008, 0xa5d: 0x0008,
+ 0xa5e: 0x1441, 0xa5f: 0x0008, 0xa60: 0xe00d, 0xa61: 0x0008, 0xa62: 0xe00d, 0xa63: 0x0008,
+ 0xa64: 0xe00d, 0xa65: 0x0008, 0xa66: 0xe00d, 0xa67: 0x0008, 0xa68: 0xe00d, 0xa69: 0x0008,
+ 0xa6a: 0xe00d, 0xa6b: 0x0008, 0xa6c: 0xe00d, 0xa6d: 0x0008, 0xa6e: 0xe00d, 0xa6f: 0x0008,
+ 0xa70: 0xe00d, 0xa71: 0x0008, 0xa72: 0xe00d, 0xa73: 0x0008, 0xa74: 0xe00d, 0xa75: 0x0008,
+ 0xa76: 0xe00d, 0xa77: 0x0008, 0xa78: 0xe00d, 0xa79: 0x0008, 0xa7a: 0xe00d, 0xa7b: 0x0008,
+ 0xa7c: 0xe00d, 0xa7d: 0x0008, 0xa7e: 0xe00d, 0xa7f: 0x0008,
+ // Block 0x2a, offset 0xa80
+ 0xa80: 0x0008, 0xa81: 0x0008, 0xa82: 0x0008, 0xa83: 0x0008, 0xa84: 0x0008, 0xa85: 0x0008,
+ 0xa86: 0x0040, 0xa87: 0x0040, 0xa88: 0xe045, 0xa89: 0xe045, 0xa8a: 0xe045, 0xa8b: 0xe045,
+ 0xa8c: 0xe045, 0xa8d: 0xe045, 0xa8e: 0x0040, 0xa8f: 0x0040, 0xa90: 0x0008, 0xa91: 0x0008,
+ 0xa92: 0x0008, 0xa93: 0x0008, 0xa94: 0x0008, 0xa95: 0x0008, 0xa96: 0x0008, 0xa97: 0x0008,
+ 0xa98: 0x0040, 0xa99: 0xe045, 0xa9a: 0x0040, 0xa9b: 0xe045, 0xa9c: 0x0040, 0xa9d: 0xe045,
+ 0xa9e: 0x0040, 0xa9f: 0xe045, 0xaa0: 0x0008, 0xaa1: 0x0008, 0xaa2: 0x0008, 0xaa3: 0x0008,
+ 0xaa4: 0x0008, 0xaa5: 0x0008, 0xaa6: 0x0008, 0xaa7: 0x0008, 0xaa8: 0xe045, 0xaa9: 0xe045,
+ 0xaaa: 0xe045, 0xaab: 0xe045, 0xaac: 0xe045, 0xaad: 0xe045, 0xaae: 0xe045, 0xaaf: 0xe045,
+ 0xab0: 0x0008, 0xab1: 0x1459, 0xab2: 0x0008, 0xab3: 0x1471, 0xab4: 0x0008, 0xab5: 0x1489,
+ 0xab6: 0x0008, 0xab7: 0x14a1, 0xab8: 0x0008, 0xab9: 0x14b9, 0xaba: 0x0008, 0xabb: 0x14d1,
+ 0xabc: 0x0008, 0xabd: 0x14e9, 0xabe: 0x0040, 0xabf: 0x0040,
+ // Block 0x2b, offset 0xac0
+ 0xac0: 0x1501, 0xac1: 0x1531, 0xac2: 0x1561, 0xac3: 0x1591, 0xac4: 0x15c1, 0xac5: 0x15f1,
+ 0xac6: 0x1621, 0xac7: 0x1651, 0xac8: 0x1501, 0xac9: 0x1531, 0xaca: 0x1561, 0xacb: 0x1591,
+ 0xacc: 0x15c1, 0xacd: 0x15f1, 0xace: 0x1621, 0xacf: 0x1651, 0xad0: 0x1681, 0xad1: 0x16b1,
+ 0xad2: 0x16e1, 0xad3: 0x1711, 0xad4: 0x1741, 0xad5: 0x1771, 0xad6: 0x17a1, 0xad7: 0x17d1,
+ 0xad8: 0x1681, 0xad9: 0x16b1, 0xada: 0x16e1, 0xadb: 0x1711, 0xadc: 0x1741, 0xadd: 0x1771,
+ 0xade: 0x17a1, 0xadf: 0x17d1, 0xae0: 0x1801, 0xae1: 0x1831, 0xae2: 0x1861, 0xae3: 0x1891,
+ 0xae4: 0x18c1, 0xae5: 0x18f1, 0xae6: 0x1921, 0xae7: 0x1951, 0xae8: 0x1801, 0xae9: 0x1831,
+ 0xaea: 0x1861, 0xaeb: 0x1891, 0xaec: 0x18c1, 0xaed: 0x18f1, 0xaee: 0x1921, 0xaef: 0x1951,
+ 0xaf0: 0x0008, 0xaf1: 0x0008, 0xaf2: 0x1981, 0xaf3: 0x19b1, 0xaf4: 0x19d9, 0xaf5: 0x0040,
+ 0xaf6: 0x0008, 0xaf7: 0x1a01, 0xaf8: 0xe045, 0xaf9: 0xe045, 0xafa: 0x064d, 0xafb: 0x1459,
+ 0xafc: 0x19b1, 0xafd: 0x0666, 0xafe: 0x1a31, 0xaff: 0x0686,
+ // Block 0x2c, offset 0xb00
+ 0xb00: 0x06a6, 0xb01: 0x1a4a, 0xb02: 0x1a79, 0xb03: 0x1aa9, 0xb04: 0x1ad1, 0xb05: 0x0040,
+ 0xb06: 0x0008, 0xb07: 0x1af9, 0xb08: 0x06c5, 0xb09: 0x1471, 0xb0a: 0x06dd, 0xb0b: 0x1489,
+ 0xb0c: 0x1aa9, 0xb0d: 0x1b2a, 0xb0e: 0x1b5a, 0xb0f: 0x1b8a, 0xb10: 0x0008, 0xb11: 0x0008,
+ 0xb12: 0x0008, 0xb13: 0x1bb9, 0xb14: 0x0040, 0xb15: 0x0040, 0xb16: 0x0008, 0xb17: 0x0008,
+ 0xb18: 0xe045, 0xb19: 0xe045, 0xb1a: 0x06f5, 0xb1b: 0x14a1, 0xb1c: 0x0040, 0xb1d: 0x1bd2,
+ 0xb1e: 0x1c02, 0xb1f: 0x1c32, 0xb20: 0x0008, 0xb21: 0x0008, 0xb22: 0x0008, 0xb23: 0x1c61,
+ 0xb24: 0x0008, 0xb25: 0x0008, 0xb26: 0x0008, 0xb27: 0x0008, 0xb28: 0xe045, 0xb29: 0xe045,
+ 0xb2a: 0x070d, 0xb2b: 0x14d1, 0xb2c: 0xe04d, 0xb2d: 0x1c7a, 0xb2e: 0x03d2, 0xb2f: 0x1caa,
+ 0xb30: 0x0040, 0xb31: 0x0040, 0xb32: 0x1cb9, 0xb33: 0x1ce9, 0xb34: 0x1d11, 0xb35: 0x0040,
+ 0xb36: 0x0008, 0xb37: 0x1d39, 0xb38: 0x0725, 0xb39: 0x14b9, 0xb3a: 0x0515, 0xb3b: 0x14e9,
+ 0xb3c: 0x1ce9, 0xb3d: 0x073e, 0xb3e: 0x075e, 0xb3f: 0x0040,
+ // Block 0x2d, offset 0xb40
+ 0xb40: 0x000a, 0xb41: 0x000a, 0xb42: 0x000a, 0xb43: 0x000a, 0xb44: 0x000a, 0xb45: 0x000a,
+ 0xb46: 0x000a, 0xb47: 0x000a, 0xb48: 0x000a, 0xb49: 0x000a, 0xb4a: 0x000a, 0xb4b: 0x03c0,
+ 0xb4c: 0x0003, 0xb4d: 0x0003, 0xb4e: 0x0340, 0xb4f: 0x0340, 0xb50: 0x0018, 0xb51: 0xe00d,
+ 0xb52: 0x0018, 0xb53: 0x0018, 0xb54: 0x0018, 0xb55: 0x0018, 0xb56: 0x0018, 0xb57: 0x077e,
+ 0xb58: 0x0018, 0xb59: 0x0018, 0xb5a: 0x0018, 0xb5b: 0x0018, 0xb5c: 0x0018, 0xb5d: 0x0018,
+ 0xb5e: 0x0018, 0xb5f: 0x0018, 0xb60: 0x0018, 0xb61: 0x0018, 0xb62: 0x0018, 0xb63: 0x0018,
+ 0xb64: 0x0040, 0xb65: 0x0040, 0xb66: 0x0040, 0xb67: 0x0018, 0xb68: 0x0040, 0xb69: 0x0040,
+ 0xb6a: 0x0340, 0xb6b: 0x0340, 0xb6c: 0x0340, 0xb6d: 0x0340, 0xb6e: 0x0340, 0xb6f: 0x000a,
+ 0xb70: 0x0018, 0xb71: 0x0018, 0xb72: 0x0018, 0xb73: 0x1d69, 0xb74: 0x1da1, 0xb75: 0x0018,
+ 0xb76: 0x1df1, 0xb77: 0x1e29, 0xb78: 0x0018, 0xb79: 0x0018, 0xb7a: 0x0018, 0xb7b: 0x0018,
+ 0xb7c: 0x1e7a, 0xb7d: 0x0018, 0xb7e: 0x079e, 0xb7f: 0x0018,
+ // Block 0x2e, offset 0xb80
+ 0xb80: 0x0018, 0xb81: 0x0018, 0xb82: 0x0018, 0xb83: 0x0018, 0xb84: 0x0018, 0xb85: 0x0018,
+ 0xb86: 0x0018, 0xb87: 0x1e92, 0xb88: 0x1eaa, 0xb89: 0x1ec2, 0xb8a: 0x0018, 0xb8b: 0x0018,
+ 0xb8c: 0x0018, 0xb8d: 0x0018, 0xb8e: 0x0018, 0xb8f: 0x0018, 0xb90: 0x0018, 0xb91: 0x0018,
+ 0xb92: 0x0018, 0xb93: 0x0018, 0xb94: 0x0018, 0xb95: 0x0018, 0xb96: 0x0018, 0xb97: 0x1ed9,
+ 0xb98: 0x0018, 0xb99: 0x0018, 0xb9a: 0x0018, 0xb9b: 0x0018, 0xb9c: 0x0018, 0xb9d: 0x0018,
+ 0xb9e: 0x0018, 0xb9f: 0x000a, 0xba0: 0x03c0, 0xba1: 0x0340, 0xba2: 0x0340, 0xba3: 0x0340,
+ 0xba4: 0x03c0, 0xba5: 0x0040, 0xba6: 0x0040, 0xba7: 0x0040, 0xba8: 0x0040, 0xba9: 0x0040,
+ 0xbaa: 0x0340, 0xbab: 0x0340, 0xbac: 0x0340, 0xbad: 0x0340, 0xbae: 0x0340, 0xbaf: 0x0340,
+ 0xbb0: 0x1f41, 0xbb1: 0x0f41, 0xbb2: 0x0040, 0xbb3: 0x0040, 0xbb4: 0x1f51, 0xbb5: 0x1f61,
+ 0xbb6: 0x1f71, 0xbb7: 0x1f81, 0xbb8: 0x1f91, 0xbb9: 0x1fa1, 0xbba: 0x1fb2, 0xbbb: 0x07bd,
+ 0xbbc: 0x1fc2, 0xbbd: 0x1fd2, 0xbbe: 0x1fe2, 0xbbf: 0x0f71,
+ // Block 0x2f, offset 0xbc0
+ 0xbc0: 0x1f41, 0xbc1: 0x00c9, 0xbc2: 0x0069, 0xbc3: 0x0079, 0xbc4: 0x1f51, 0xbc5: 0x1f61,
+ 0xbc6: 0x1f71, 0xbc7: 0x1f81, 0xbc8: 0x1f91, 0xbc9: 0x1fa1, 0xbca: 0x1fb2, 0xbcb: 0x07d5,
+ 0xbcc: 0x1fc2, 0xbcd: 0x1fd2, 0xbce: 0x1fe2, 0xbcf: 0x0040, 0xbd0: 0x0039, 0xbd1: 0x0f09,
+ 0xbd2: 0x00d9, 0xbd3: 0x0369, 0xbd4: 0x0ff9, 0xbd5: 0x0249, 0xbd6: 0x0f51, 0xbd7: 0x0359,
+ 0xbd8: 0x0f61, 0xbd9: 0x0f71, 0xbda: 0x0f99, 0xbdb: 0x01d9, 0xbdc: 0x0fa9, 0xbdd: 0x0040,
+ 0xbde: 0x0040, 0xbdf: 0x0040, 0xbe0: 0x0018, 0xbe1: 0x0018, 0xbe2: 0x0018, 0xbe3: 0x0018,
+ 0xbe4: 0x0018, 0xbe5: 0x0018, 0xbe6: 0x0018, 0xbe7: 0x0018, 0xbe8: 0x1ff1, 0xbe9: 0x0018,
+ 0xbea: 0x0018, 0xbeb: 0x0018, 0xbec: 0x0018, 0xbed: 0x0018, 0xbee: 0x0018, 0xbef: 0x0018,
+ 0xbf0: 0x0018, 0xbf1: 0x0018, 0xbf2: 0x0018, 0xbf3: 0x0018, 0xbf4: 0x0018, 0xbf5: 0x0018,
+ 0xbf6: 0x0018, 0xbf7: 0x0018, 0xbf8: 0x0018, 0xbf9: 0x0018, 0xbfa: 0x0018, 0xbfb: 0x0018,
+ 0xbfc: 0x0018, 0xbfd: 0x0018, 0xbfe: 0x0018, 0xbff: 0x0040,
+ // Block 0x30, offset 0xc00
+ 0xc00: 0x07ee, 0xc01: 0x080e, 0xc02: 0x1159, 0xc03: 0x082d, 0xc04: 0x0018, 0xc05: 0x084e,
+ 0xc06: 0x086e, 0xc07: 0x1011, 0xc08: 0x0018, 0xc09: 0x088d, 0xc0a: 0x0f31, 0xc0b: 0x0249,
+ 0xc0c: 0x0249, 0xc0d: 0x0249, 0xc0e: 0x0249, 0xc0f: 0x2009, 0xc10: 0x0f41, 0xc11: 0x0f41,
+ 0xc12: 0x0359, 0xc13: 0x0359, 0xc14: 0x0018, 0xc15: 0x0f71, 0xc16: 0x2021, 0xc17: 0x0018,
+ 0xc18: 0x0018, 0xc19: 0x0f99, 0xc1a: 0x2039, 0xc1b: 0x0269, 0xc1c: 0x0269, 0xc1d: 0x0269,
+ 0xc1e: 0x0018, 0xc1f: 0x0018, 0xc20: 0x2049, 0xc21: 0x08ad, 0xc22: 0x2061, 0xc23: 0x0018,
+ 0xc24: 0x13d1, 0xc25: 0x0018, 0xc26: 0x2079, 0xc27: 0x0018, 0xc28: 0x13d1, 0xc29: 0x0018,
+ 0xc2a: 0x0f51, 0xc2b: 0x2091, 0xc2c: 0x0ee9, 0xc2d: 0x1159, 0xc2e: 0x0018, 0xc2f: 0x0f09,
+ 0xc30: 0x0f09, 0xc31: 0x1199, 0xc32: 0x0040, 0xc33: 0x0f61, 0xc34: 0x00d9, 0xc35: 0x20a9,
+ 0xc36: 0x20c1, 0xc37: 0x20d9, 0xc38: 0x20f1, 0xc39: 0x0f41, 0xc3a: 0x0018, 0xc3b: 0x08cd,
+ 0xc3c: 0x2109, 0xc3d: 0x10b1, 0xc3e: 0x10b1, 0xc3f: 0x2109,
+ // Block 0x31, offset 0xc40
+ 0xc40: 0x08ed, 0xc41: 0x0018, 0xc42: 0x0018, 0xc43: 0x0018, 0xc44: 0x0018, 0xc45: 0x0ef9,
+ 0xc46: 0x0ef9, 0xc47: 0x0f09, 0xc48: 0x0f41, 0xc49: 0x0259, 0xc4a: 0x0018, 0xc4b: 0x0018,
+ 0xc4c: 0x0018, 0xc4d: 0x0018, 0xc4e: 0x0008, 0xc4f: 0x0018, 0xc50: 0x2121, 0xc51: 0x2151,
+ 0xc52: 0x2181, 0xc53: 0x21b9, 0xc54: 0x21e9, 0xc55: 0x2219, 0xc56: 0x2249, 0xc57: 0x2279,
+ 0xc58: 0x22a9, 0xc59: 0x22d9, 0xc5a: 0x2309, 0xc5b: 0x2339, 0xc5c: 0x2369, 0xc5d: 0x2399,
+ 0xc5e: 0x23c9, 0xc5f: 0x23f9, 0xc60: 0x0f41, 0xc61: 0x2421, 0xc62: 0x0905, 0xc63: 0x2439,
+ 0xc64: 0x1089, 0xc65: 0x2451, 0xc66: 0x0925, 0xc67: 0x2469, 0xc68: 0x2491, 0xc69: 0x0369,
+ 0xc6a: 0x24a9, 0xc6b: 0x0945, 0xc6c: 0x0359, 0xc6d: 0x1159, 0xc6e: 0x0ef9, 0xc6f: 0x0f61,
+ 0xc70: 0x0f41, 0xc71: 0x2421, 0xc72: 0x0965, 0xc73: 0x2439, 0xc74: 0x1089, 0xc75: 0x2451,
+ 0xc76: 0x0985, 0xc77: 0x2469, 0xc78: 0x2491, 0xc79: 0x0369, 0xc7a: 0x24a9, 0xc7b: 0x09a5,
+ 0xc7c: 0x0359, 0xc7d: 0x1159, 0xc7e: 0x0ef9, 0xc7f: 0x0f61,
+ // Block 0x32, offset 0xc80
+ 0xc80: 0x0018, 0xc81: 0x0018, 0xc82: 0x0018, 0xc83: 0x0018, 0xc84: 0x0018, 0xc85: 0x0018,
+ 0xc86: 0x0018, 0xc87: 0x0018, 0xc88: 0x0018, 0xc89: 0x0018, 0xc8a: 0x0018, 0xc8b: 0x0040,
+ 0xc8c: 0x0040, 0xc8d: 0x0040, 0xc8e: 0x0040, 0xc8f: 0x0040, 0xc90: 0x0040, 0xc91: 0x0040,
+ 0xc92: 0x0040, 0xc93: 0x0040, 0xc94: 0x0040, 0xc95: 0x0040, 0xc96: 0x0040, 0xc97: 0x0040,
+ 0xc98: 0x0040, 0xc99: 0x0040, 0xc9a: 0x0040, 0xc9b: 0x0040, 0xc9c: 0x0040, 0xc9d: 0x0040,
+ 0xc9e: 0x0040, 0xc9f: 0x0040, 0xca0: 0x00c9, 0xca1: 0x0069, 0xca2: 0x0079, 0xca3: 0x1f51,
+ 0xca4: 0x1f61, 0xca5: 0x1f71, 0xca6: 0x1f81, 0xca7: 0x1f91, 0xca8: 0x1fa1, 0xca9: 0x2601,
+ 0xcaa: 0x2619, 0xcab: 0x2631, 0xcac: 0x2649, 0xcad: 0x2661, 0xcae: 0x2679, 0xcaf: 0x2691,
+ 0xcb0: 0x26a9, 0xcb1: 0x26c1, 0xcb2: 0x26d9, 0xcb3: 0x26f1, 0xcb4: 0x0a06, 0xcb5: 0x0a26,
+ 0xcb6: 0x0a46, 0xcb7: 0x0a66, 0xcb8: 0x0a86, 0xcb9: 0x0aa6, 0xcba: 0x0ac6, 0xcbb: 0x0ae6,
+ 0xcbc: 0x0b06, 0xcbd: 0x270a, 0xcbe: 0x2732, 0xcbf: 0x275a,
+ // Block 0x33, offset 0xcc0
+ 0xcc0: 0x2782, 0xcc1: 0x27aa, 0xcc2: 0x27d2, 0xcc3: 0x27fa, 0xcc4: 0x2822, 0xcc5: 0x284a,
+ 0xcc6: 0x2872, 0xcc7: 0x289a, 0xcc8: 0x0040, 0xcc9: 0x0040, 0xcca: 0x0040, 0xccb: 0x0040,
+ 0xccc: 0x0040, 0xccd: 0x0040, 0xcce: 0x0040, 0xccf: 0x0040, 0xcd0: 0x0040, 0xcd1: 0x0040,
+ 0xcd2: 0x0040, 0xcd3: 0x0040, 0xcd4: 0x0040, 0xcd5: 0x0040, 0xcd6: 0x0040, 0xcd7: 0x0040,
+ 0xcd8: 0x0040, 0xcd9: 0x0040, 0xcda: 0x0040, 0xcdb: 0x0040, 0xcdc: 0x0b26, 0xcdd: 0x0b46,
+ 0xcde: 0x0b66, 0xcdf: 0x0b86, 0xce0: 0x0ba6, 0xce1: 0x0bc6, 0xce2: 0x0be6, 0xce3: 0x0c06,
+ 0xce4: 0x0c26, 0xce5: 0x0c46, 0xce6: 0x0c66, 0xce7: 0x0c86, 0xce8: 0x0ca6, 0xce9: 0x0cc6,
+ 0xcea: 0x0ce6, 0xceb: 0x0d06, 0xcec: 0x0d26, 0xced: 0x0d46, 0xcee: 0x0d66, 0xcef: 0x0d86,
+ 0xcf0: 0x0da6, 0xcf1: 0x0dc6, 0xcf2: 0x0de6, 0xcf3: 0x0e06, 0xcf4: 0x0e26, 0xcf5: 0x0e46,
+ 0xcf6: 0x0039, 0xcf7: 0x0ee9, 0xcf8: 0x1159, 0xcf9: 0x0ef9, 0xcfa: 0x0f09, 0xcfb: 0x1199,
+ 0xcfc: 0x0f31, 0xcfd: 0x0249, 0xcfe: 0x0f41, 0xcff: 0x0259,
+ // Block 0x34, offset 0xd00
+ 0xd00: 0x0f51, 0xd01: 0x0359, 0xd02: 0x0f61, 0xd03: 0x0f71, 0xd04: 0x00d9, 0xd05: 0x0f99,
+ 0xd06: 0x2039, 0xd07: 0x0269, 0xd08: 0x01d9, 0xd09: 0x0fa9, 0xd0a: 0x0fb9, 0xd0b: 0x1089,
+ 0xd0c: 0x0279, 0xd0d: 0x0369, 0xd0e: 0x0289, 0xd0f: 0x13d1, 0xd10: 0x0039, 0xd11: 0x0ee9,
+ 0xd12: 0x1159, 0xd13: 0x0ef9, 0xd14: 0x0f09, 0xd15: 0x1199, 0xd16: 0x0f31, 0xd17: 0x0249,
+ 0xd18: 0x0f41, 0xd19: 0x0259, 0xd1a: 0x0f51, 0xd1b: 0x0359, 0xd1c: 0x0f61, 0xd1d: 0x0f71,
+ 0xd1e: 0x00d9, 0xd1f: 0x0f99, 0xd20: 0x2039, 0xd21: 0x0269, 0xd22: 0x01d9, 0xd23: 0x0fa9,
+ 0xd24: 0x0fb9, 0xd25: 0x1089, 0xd26: 0x0279, 0xd27: 0x0369, 0xd28: 0x0289, 0xd29: 0x13d1,
+ 0xd2a: 0x1f41, 0xd2b: 0x0018, 0xd2c: 0x0018, 0xd2d: 0x0018, 0xd2e: 0x0018, 0xd2f: 0x0018,
+ 0xd30: 0x0018, 0xd31: 0x0018, 0xd32: 0x0018, 0xd33: 0x0018, 0xd34: 0x0018, 0xd35: 0x0018,
+ 0xd36: 0x0018, 0xd37: 0x0018, 0xd38: 0x0018, 0xd39: 0x0018, 0xd3a: 0x0018, 0xd3b: 0x0018,
+ 0xd3c: 0x0018, 0xd3d: 0x0018, 0xd3e: 0x0018, 0xd3f: 0x0018,
+ // Block 0x35, offset 0xd40
+ 0xd40: 0x0008, 0xd41: 0x0008, 0xd42: 0x0008, 0xd43: 0x0008, 0xd44: 0x0008, 0xd45: 0x0008,
+ 0xd46: 0x0008, 0xd47: 0x0008, 0xd48: 0x0008, 0xd49: 0x0008, 0xd4a: 0x0008, 0xd4b: 0x0008,
+ 0xd4c: 0x0008, 0xd4d: 0x0008, 0xd4e: 0x0008, 0xd4f: 0x0008, 0xd50: 0x0008, 0xd51: 0x0008,
+ 0xd52: 0x0008, 0xd53: 0x0008, 0xd54: 0x0008, 0xd55: 0x0008, 0xd56: 0x0008, 0xd57: 0x0008,
+ 0xd58: 0x0008, 0xd59: 0x0008, 0xd5a: 0x0008, 0xd5b: 0x0008, 0xd5c: 0x0008, 0xd5d: 0x0008,
+ 0xd5e: 0x0008, 0xd5f: 0x0040, 0xd60: 0xe00d, 0xd61: 0x0008, 0xd62: 0x2971, 0xd63: 0x0ebd,
+ 0xd64: 0x2989, 0xd65: 0x0008, 0xd66: 0x0008, 0xd67: 0xe07d, 0xd68: 0x0008, 0xd69: 0xe01d,
+ 0xd6a: 0x0008, 0xd6b: 0xe03d, 0xd6c: 0x0008, 0xd6d: 0x0fe1, 0xd6e: 0x1281, 0xd6f: 0x0fc9,
+ 0xd70: 0x1141, 0xd71: 0x0008, 0xd72: 0xe00d, 0xd73: 0x0008, 0xd74: 0x0008, 0xd75: 0xe01d,
+ 0xd76: 0x0008, 0xd77: 0x0008, 0xd78: 0x0008, 0xd79: 0x0008, 0xd7a: 0x0008, 0xd7b: 0x0008,
+ 0xd7c: 0x0259, 0xd7d: 0x1089, 0xd7e: 0x29a1, 0xd7f: 0x29b9,
+ // Block 0x36, offset 0xd80
+ 0xd80: 0xe00d, 0xd81: 0x0008, 0xd82: 0xe00d, 0xd83: 0x0008, 0xd84: 0xe00d, 0xd85: 0x0008,
+ 0xd86: 0xe00d, 0xd87: 0x0008, 0xd88: 0xe00d, 0xd89: 0x0008, 0xd8a: 0xe00d, 0xd8b: 0x0008,
+ 0xd8c: 0xe00d, 0xd8d: 0x0008, 0xd8e: 0xe00d, 0xd8f: 0x0008, 0xd90: 0xe00d, 0xd91: 0x0008,
+ 0xd92: 0xe00d, 0xd93: 0x0008, 0xd94: 0xe00d, 0xd95: 0x0008, 0xd96: 0xe00d, 0xd97: 0x0008,
+ 0xd98: 0xe00d, 0xd99: 0x0008, 0xd9a: 0xe00d, 0xd9b: 0x0008, 0xd9c: 0xe00d, 0xd9d: 0x0008,
+ 0xd9e: 0xe00d, 0xd9f: 0x0008, 0xda0: 0xe00d, 0xda1: 0x0008, 0xda2: 0xe00d, 0xda3: 0x0008,
+ 0xda4: 0x0008, 0xda5: 0x0018, 0xda6: 0x0018, 0xda7: 0x0018, 0xda8: 0x0018, 0xda9: 0x0018,
+ 0xdaa: 0x0018, 0xdab: 0xe03d, 0xdac: 0x0008, 0xdad: 0xe01d, 0xdae: 0x0008, 0xdaf: 0x1308,
+ 0xdb0: 0x1308, 0xdb1: 0x1308, 0xdb2: 0xe00d, 0xdb3: 0x0008, 0xdb4: 0x0040, 0xdb5: 0x0040,
+ 0xdb6: 0x0040, 0xdb7: 0x0040, 0xdb8: 0x0040, 0xdb9: 0x0018, 0xdba: 0x0018, 0xdbb: 0x0018,
+ 0xdbc: 0x0018, 0xdbd: 0x0018, 0xdbe: 0x0018, 0xdbf: 0x0018,
+ // Block 0x37, offset 0xdc0
+ 0xdc0: 0x26fd, 0xdc1: 0x271d, 0xdc2: 0x273d, 0xdc3: 0x275d, 0xdc4: 0x277d, 0xdc5: 0x279d,
+ 0xdc6: 0x27bd, 0xdc7: 0x27dd, 0xdc8: 0x27fd, 0xdc9: 0x281d, 0xdca: 0x283d, 0xdcb: 0x285d,
+ 0xdcc: 0x287d, 0xdcd: 0x289d, 0xdce: 0x28bd, 0xdcf: 0x28dd, 0xdd0: 0x28fd, 0xdd1: 0x291d,
+ 0xdd2: 0x293d, 0xdd3: 0x295d, 0xdd4: 0x297d, 0xdd5: 0x299d, 0xdd6: 0x0040, 0xdd7: 0x0040,
+ 0xdd8: 0x0040, 0xdd9: 0x0040, 0xdda: 0x0040, 0xddb: 0x0040, 0xddc: 0x0040, 0xddd: 0x0040,
+ 0xdde: 0x0040, 0xddf: 0x0040, 0xde0: 0x0040, 0xde1: 0x0040, 0xde2: 0x0040, 0xde3: 0x0040,
+ 0xde4: 0x0040, 0xde5: 0x0040, 0xde6: 0x0040, 0xde7: 0x0040, 0xde8: 0x0040, 0xde9: 0x0040,
+ 0xdea: 0x0040, 0xdeb: 0x0040, 0xdec: 0x0040, 0xded: 0x0040, 0xdee: 0x0040, 0xdef: 0x0040,
+ 0xdf0: 0x0040, 0xdf1: 0x0040, 0xdf2: 0x0040, 0xdf3: 0x0040, 0xdf4: 0x0040, 0xdf5: 0x0040,
+ 0xdf6: 0x0040, 0xdf7: 0x0040, 0xdf8: 0x0040, 0xdf9: 0x0040, 0xdfa: 0x0040, 0xdfb: 0x0040,
+ 0xdfc: 0x0040, 0xdfd: 0x0040, 0xdfe: 0x0040, 0xdff: 0x0040,
+ // Block 0x38, offset 0xe00
+ 0xe00: 0x000a, 0xe01: 0x0018, 0xe02: 0x29d1, 0xe03: 0x0018, 0xe04: 0x0018, 0xe05: 0x0008,
+ 0xe06: 0x0008, 0xe07: 0x0008, 0xe08: 0x0018, 0xe09: 0x0018, 0xe0a: 0x0018, 0xe0b: 0x0018,
+ 0xe0c: 0x0018, 0xe0d: 0x0018, 0xe0e: 0x0018, 0xe0f: 0x0018, 0xe10: 0x0018, 0xe11: 0x0018,
+ 0xe12: 0x0018, 0xe13: 0x0018, 0xe14: 0x0018, 0xe15: 0x0018, 0xe16: 0x0018, 0xe17: 0x0018,
+ 0xe18: 0x0018, 0xe19: 0x0018, 0xe1a: 0x0018, 0xe1b: 0x0018, 0xe1c: 0x0018, 0xe1d: 0x0018,
+ 0xe1e: 0x0018, 0xe1f: 0x0018, 0xe20: 0x0018, 0xe21: 0x0018, 0xe22: 0x0018, 0xe23: 0x0018,
+ 0xe24: 0x0018, 0xe25: 0x0018, 0xe26: 0x0018, 0xe27: 0x0018, 0xe28: 0x0018, 0xe29: 0x0018,
+ 0xe2a: 0x1308, 0xe2b: 0x1308, 0xe2c: 0x1308, 0xe2d: 0x1308, 0xe2e: 0x1018, 0xe2f: 0x1018,
+ 0xe30: 0x0018, 0xe31: 0x0018, 0xe32: 0x0018, 0xe33: 0x0018, 0xe34: 0x0018, 0xe35: 0x0018,
+ 0xe36: 0xe125, 0xe37: 0x0018, 0xe38: 0x29bd, 0xe39: 0x29dd, 0xe3a: 0x29fd, 0xe3b: 0x0018,
+ 0xe3c: 0x0008, 0xe3d: 0x0018, 0xe3e: 0x0018, 0xe3f: 0x0018,
+ // Block 0x39, offset 0xe40
+ 0xe40: 0x2b3d, 0xe41: 0x2b5d, 0xe42: 0x2b7d, 0xe43: 0x2b9d, 0xe44: 0x2bbd, 0xe45: 0x2bdd,
+ 0xe46: 0x2bdd, 0xe47: 0x2bdd, 0xe48: 0x2bfd, 0xe49: 0x2bfd, 0xe4a: 0x2bfd, 0xe4b: 0x2bfd,
+ 0xe4c: 0x2c1d, 0xe4d: 0x2c1d, 0xe4e: 0x2c1d, 0xe4f: 0x2c3d, 0xe50: 0x2c5d, 0xe51: 0x2c5d,
+ 0xe52: 0x2a7d, 0xe53: 0x2a7d, 0xe54: 0x2c5d, 0xe55: 0x2c5d, 0xe56: 0x2c7d, 0xe57: 0x2c7d,
+ 0xe58: 0x2c5d, 0xe59: 0x2c5d, 0xe5a: 0x2a7d, 0xe5b: 0x2a7d, 0xe5c: 0x2c5d, 0xe5d: 0x2c5d,
+ 0xe5e: 0x2c3d, 0xe5f: 0x2c3d, 0xe60: 0x2c9d, 0xe61: 0x2c9d, 0xe62: 0x2cbd, 0xe63: 0x2cbd,
+ 0xe64: 0x0040, 0xe65: 0x2cdd, 0xe66: 0x2cfd, 0xe67: 0x2d1d, 0xe68: 0x2d1d, 0xe69: 0x2d3d,
+ 0xe6a: 0x2d5d, 0xe6b: 0x2d7d, 0xe6c: 0x2d9d, 0xe6d: 0x2dbd, 0xe6e: 0x2ddd, 0xe6f: 0x2dfd,
+ 0xe70: 0x2e1d, 0xe71: 0x2e3d, 0xe72: 0x2e3d, 0xe73: 0x2e5d, 0xe74: 0x2e7d, 0xe75: 0x2e7d,
+ 0xe76: 0x2e9d, 0xe77: 0x2ebd, 0xe78: 0x2e5d, 0xe79: 0x2edd, 0xe7a: 0x2efd, 0xe7b: 0x2edd,
+ 0xe7c: 0x2e5d, 0xe7d: 0x2f1d, 0xe7e: 0x2f3d, 0xe7f: 0x2f5d,
+ // Block 0x3a, offset 0xe80
+ 0xe80: 0x2f7d, 0xe81: 0x2f9d, 0xe82: 0x2cfd, 0xe83: 0x2cdd, 0xe84: 0x2fbd, 0xe85: 0x2fdd,
+ 0xe86: 0x2ffd, 0xe87: 0x301d, 0xe88: 0x303d, 0xe89: 0x305d, 0xe8a: 0x307d, 0xe8b: 0x309d,
+ 0xe8c: 0x30bd, 0xe8d: 0x30dd, 0xe8e: 0x30fd, 0xe8f: 0x0040, 0xe90: 0x0018, 0xe91: 0x0018,
+ 0xe92: 0x311d, 0xe93: 0x313d, 0xe94: 0x315d, 0xe95: 0x317d, 0xe96: 0x319d, 0xe97: 0x31bd,
+ 0xe98: 0x31dd, 0xe99: 0x31fd, 0xe9a: 0x321d, 0xe9b: 0x323d, 0xe9c: 0x315d, 0xe9d: 0x325d,
+ 0xe9e: 0x327d, 0xe9f: 0x329d, 0xea0: 0x0008, 0xea1: 0x0008, 0xea2: 0x0008, 0xea3: 0x0008,
+ 0xea4: 0x0008, 0xea5: 0x0008, 0xea6: 0x0008, 0xea7: 0x0008, 0xea8: 0x0008, 0xea9: 0x0008,
+ 0xeaa: 0x0008, 0xeab: 0x0008, 0xeac: 0x0008, 0xead: 0x0008, 0xeae: 0x0008, 0xeaf: 0x0008,
+ 0xeb0: 0x0008, 0xeb1: 0x0008, 0xeb2: 0x0008, 0xeb3: 0x0008, 0xeb4: 0x0008, 0xeb5: 0x0008,
+ 0xeb6: 0x0008, 0xeb7: 0x0008, 0xeb8: 0x0008, 0xeb9: 0x0008, 0xeba: 0x0008, 0xebb: 0x0040,
+ 0xebc: 0x0040, 0xebd: 0x0040, 0xebe: 0x0040, 0xebf: 0x0040,
+ // Block 0x3b, offset 0xec0
+ 0xec0: 0x36a2, 0xec1: 0x36d2, 0xec2: 0x3702, 0xec3: 0x3732, 0xec4: 0x32bd, 0xec5: 0x32dd,
+ 0xec6: 0x32fd, 0xec7: 0x331d, 0xec8: 0x0018, 0xec9: 0x0018, 0xeca: 0x0018, 0xecb: 0x0018,
+ 0xecc: 0x0018, 0xecd: 0x0018, 0xece: 0x0018, 0xecf: 0x0018, 0xed0: 0x333d, 0xed1: 0x3761,
+ 0xed2: 0x3779, 0xed3: 0x3791, 0xed4: 0x37a9, 0xed5: 0x37c1, 0xed6: 0x37d9, 0xed7: 0x37f1,
+ 0xed8: 0x3809, 0xed9: 0x3821, 0xeda: 0x3839, 0xedb: 0x3851, 0xedc: 0x3869, 0xedd: 0x3881,
+ 0xede: 0x3899, 0xedf: 0x38b1, 0xee0: 0x335d, 0xee1: 0x337d, 0xee2: 0x339d, 0xee3: 0x33bd,
+ 0xee4: 0x33dd, 0xee5: 0x33dd, 0xee6: 0x33fd, 0xee7: 0x341d, 0xee8: 0x343d, 0xee9: 0x345d,
+ 0xeea: 0x347d, 0xeeb: 0x349d, 0xeec: 0x34bd, 0xeed: 0x34dd, 0xeee: 0x34fd, 0xeef: 0x351d,
+ 0xef0: 0x353d, 0xef1: 0x355d, 0xef2: 0x357d, 0xef3: 0x359d, 0xef4: 0x35bd, 0xef5: 0x35dd,
+ 0xef6: 0x35fd, 0xef7: 0x361d, 0xef8: 0x363d, 0xef9: 0x365d, 0xefa: 0x367d, 0xefb: 0x369d,
+ 0xefc: 0x38c9, 0xefd: 0x3901, 0xefe: 0x36bd, 0xeff: 0x0018,
+ // Block 0x3c, offset 0xf00
+ 0xf00: 0x36dd, 0xf01: 0x36fd, 0xf02: 0x371d, 0xf03: 0x373d, 0xf04: 0x375d, 0xf05: 0x377d,
+ 0xf06: 0x379d, 0xf07: 0x37bd, 0xf08: 0x37dd, 0xf09: 0x37fd, 0xf0a: 0x381d, 0xf0b: 0x383d,
+ 0xf0c: 0x385d, 0xf0d: 0x387d, 0xf0e: 0x389d, 0xf0f: 0x38bd, 0xf10: 0x38dd, 0xf11: 0x38fd,
+ 0xf12: 0x391d, 0xf13: 0x393d, 0xf14: 0x395d, 0xf15: 0x397d, 0xf16: 0x399d, 0xf17: 0x39bd,
+ 0xf18: 0x39dd, 0xf19: 0x39fd, 0xf1a: 0x3a1d, 0xf1b: 0x3a3d, 0xf1c: 0x3a5d, 0xf1d: 0x3a7d,
+ 0xf1e: 0x3a9d, 0xf1f: 0x3abd, 0xf20: 0x3add, 0xf21: 0x3afd, 0xf22: 0x3b1d, 0xf23: 0x3b3d,
+ 0xf24: 0x3b5d, 0xf25: 0x3b7d, 0xf26: 0x127d, 0xf27: 0x3b9d, 0xf28: 0x3bbd, 0xf29: 0x3bdd,
+ 0xf2a: 0x3bfd, 0xf2b: 0x3c1d, 0xf2c: 0x3c3d, 0xf2d: 0x3c5d, 0xf2e: 0x239d, 0xf2f: 0x3c7d,
+ 0xf30: 0x3c9d, 0xf31: 0x3939, 0xf32: 0x3951, 0xf33: 0x3969, 0xf34: 0x3981, 0xf35: 0x3999,
+ 0xf36: 0x39b1, 0xf37: 0x39c9, 0xf38: 0x39e1, 0xf39: 0x39f9, 0xf3a: 0x3a11, 0xf3b: 0x3a29,
+ 0xf3c: 0x3a41, 0xf3d: 0x3a59, 0xf3e: 0x3a71, 0xf3f: 0x3a89,
+ // Block 0x3d, offset 0xf40
+ 0xf40: 0x3aa1, 0xf41: 0x3ac9, 0xf42: 0x3af1, 0xf43: 0x3b19, 0xf44: 0x3b41, 0xf45: 0x3b69,
+ 0xf46: 0x3b91, 0xf47: 0x3bb9, 0xf48: 0x3be1, 0xf49: 0x3c09, 0xf4a: 0x3c39, 0xf4b: 0x3c69,
+ 0xf4c: 0x3c99, 0xf4d: 0x3cbd, 0xf4e: 0x3cb1, 0xf4f: 0x3cdd, 0xf50: 0x3cfd, 0xf51: 0x3d15,
+ 0xf52: 0x3d2d, 0xf53: 0x3d45, 0xf54: 0x3d5d, 0xf55: 0x3d5d, 0xf56: 0x3d45, 0xf57: 0x3d75,
+ 0xf58: 0x07bd, 0xf59: 0x3d8d, 0xf5a: 0x3da5, 0xf5b: 0x3dbd, 0xf5c: 0x3dd5, 0xf5d: 0x3ded,
+ 0xf5e: 0x3e05, 0xf5f: 0x3e1d, 0xf60: 0x3e35, 0xf61: 0x3e4d, 0xf62: 0x3e65, 0xf63: 0x3e7d,
+ 0xf64: 0x3e95, 0xf65: 0x3e95, 0xf66: 0x3ead, 0xf67: 0x3ead, 0xf68: 0x3ec5, 0xf69: 0x3ec5,
+ 0xf6a: 0x3edd, 0xf6b: 0x3ef5, 0xf6c: 0x3f0d, 0xf6d: 0x3f25, 0xf6e: 0x3f3d, 0xf6f: 0x3f3d,
+ 0xf70: 0x3f55, 0xf71: 0x3f55, 0xf72: 0x3f55, 0xf73: 0x3f6d, 0xf74: 0x3f85, 0xf75: 0x3f9d,
+ 0xf76: 0x3fb5, 0xf77: 0x3f9d, 0xf78: 0x3fcd, 0xf79: 0x3fe5, 0xf7a: 0x3f6d, 0xf7b: 0x3ffd,
+ 0xf7c: 0x4015, 0xf7d: 0x4015, 0xf7e: 0x4015, 0xf7f: 0x0040,
+ // Block 0x3e, offset 0xf80
+ 0xf80: 0x3cc9, 0xf81: 0x3d31, 0xf82: 0x3d99, 0xf83: 0x3e01, 0xf84: 0x3e51, 0xf85: 0x3eb9,
+ 0xf86: 0x3f09, 0xf87: 0x3f59, 0xf88: 0x3fd9, 0xf89: 0x4041, 0xf8a: 0x4091, 0xf8b: 0x40e1,
+ 0xf8c: 0x4131, 0xf8d: 0x4199, 0xf8e: 0x4201, 0xf8f: 0x4251, 0xf90: 0x42a1, 0xf91: 0x42d9,
+ 0xf92: 0x4329, 0xf93: 0x4391, 0xf94: 0x43f9, 0xf95: 0x4431, 0xf96: 0x44b1, 0xf97: 0x4549,
+ 0xf98: 0x45c9, 0xf99: 0x4619, 0xf9a: 0x4699, 0xf9b: 0x4719, 0xf9c: 0x4781, 0xf9d: 0x47d1,
+ 0xf9e: 0x4821, 0xf9f: 0x4871, 0xfa0: 0x48d9, 0xfa1: 0x4959, 0xfa2: 0x49c1, 0xfa3: 0x4a11,
+ 0xfa4: 0x4a61, 0xfa5: 0x4ab1, 0xfa6: 0x4ae9, 0xfa7: 0x4b21, 0xfa8: 0x4b59, 0xfa9: 0x4b91,
+ 0xfaa: 0x4be1, 0xfab: 0x4c31, 0xfac: 0x4cb1, 0xfad: 0x4d01, 0xfae: 0x4d69, 0xfaf: 0x4de9,
+ 0xfb0: 0x4e39, 0xfb1: 0x4e71, 0xfb2: 0x4ea9, 0xfb3: 0x4f29, 0xfb4: 0x4f91, 0xfb5: 0x5011,
+ 0xfb6: 0x5061, 0xfb7: 0x50e1, 0xfb8: 0x5119, 0xfb9: 0x5169, 0xfba: 0x51b9, 0xfbb: 0x5209,
+ 0xfbc: 0x5259, 0xfbd: 0x52a9, 0xfbe: 0x5311, 0xfbf: 0x5361,
+ // Block 0x3f, offset 0xfc0
+ 0xfc0: 0x5399, 0xfc1: 0x53e9, 0xfc2: 0x5439, 0xfc3: 0x5489, 0xfc4: 0x54f1, 0xfc5: 0x5541,
+ 0xfc6: 0x5591, 0xfc7: 0x55e1, 0xfc8: 0x5661, 0xfc9: 0x56c9, 0xfca: 0x5701, 0xfcb: 0x5781,
+ 0xfcc: 0x57b9, 0xfcd: 0x5821, 0xfce: 0x5889, 0xfcf: 0x58d9, 0xfd0: 0x5929, 0xfd1: 0x5979,
+ 0xfd2: 0x59e1, 0xfd3: 0x5a19, 0xfd4: 0x5a69, 0xfd5: 0x5ad1, 0xfd6: 0x5b09, 0xfd7: 0x5b89,
+ 0xfd8: 0x5bd9, 0xfd9: 0x5c01, 0xfda: 0x5c29, 0xfdb: 0x5c51, 0xfdc: 0x5c79, 0xfdd: 0x5ca1,
+ 0xfde: 0x5cc9, 0xfdf: 0x5cf1, 0xfe0: 0x5d19, 0xfe1: 0x5d41, 0xfe2: 0x5d69, 0xfe3: 0x5d99,
+ 0xfe4: 0x5dc9, 0xfe5: 0x5df9, 0xfe6: 0x5e29, 0xfe7: 0x5e59, 0xfe8: 0x5e89, 0xfe9: 0x5eb9,
+ 0xfea: 0x5ee9, 0xfeb: 0x5f19, 0xfec: 0x5f49, 0xfed: 0x5f79, 0xfee: 0x5fa9, 0xfef: 0x5fd9,
+ 0xff0: 0x6009, 0xff1: 0x402d, 0xff2: 0x6039, 0xff3: 0x6051, 0xff4: 0x404d, 0xff5: 0x6069,
+ 0xff6: 0x6081, 0xff7: 0x6099, 0xff8: 0x406d, 0xff9: 0x406d, 0xffa: 0x60b1, 0xffb: 0x60c9,
+ 0xffc: 0x6101, 0xffd: 0x6139, 0xffe: 0x6171, 0xfff: 0x61a9,
+ // Block 0x40, offset 0x1000
+ 0x1000: 0x6211, 0x1001: 0x6229, 0x1002: 0x408d, 0x1003: 0x6241, 0x1004: 0x6259, 0x1005: 0x6271,
+ 0x1006: 0x6289, 0x1007: 0x62a1, 0x1008: 0x40ad, 0x1009: 0x62b9, 0x100a: 0x62e1, 0x100b: 0x62f9,
+ 0x100c: 0x40cd, 0x100d: 0x40cd, 0x100e: 0x6311, 0x100f: 0x6329, 0x1010: 0x6341, 0x1011: 0x40ed,
+ 0x1012: 0x410d, 0x1013: 0x412d, 0x1014: 0x414d, 0x1015: 0x416d, 0x1016: 0x6359, 0x1017: 0x6371,
+ 0x1018: 0x6389, 0x1019: 0x63a1, 0x101a: 0x63b9, 0x101b: 0x418d, 0x101c: 0x63d1, 0x101d: 0x63e9,
+ 0x101e: 0x6401, 0x101f: 0x41ad, 0x1020: 0x41cd, 0x1021: 0x6419, 0x1022: 0x41ed, 0x1023: 0x420d,
+ 0x1024: 0x422d, 0x1025: 0x6431, 0x1026: 0x424d, 0x1027: 0x6449, 0x1028: 0x6479, 0x1029: 0x6211,
+ 0x102a: 0x426d, 0x102b: 0x428d, 0x102c: 0x42ad, 0x102d: 0x42cd, 0x102e: 0x64b1, 0x102f: 0x64f1,
+ 0x1030: 0x6539, 0x1031: 0x6551, 0x1032: 0x42ed, 0x1033: 0x6569, 0x1034: 0x6581, 0x1035: 0x6599,
+ 0x1036: 0x430d, 0x1037: 0x65b1, 0x1038: 0x65c9, 0x1039: 0x65b1, 0x103a: 0x65e1, 0x103b: 0x65f9,
+ 0x103c: 0x432d, 0x103d: 0x6611, 0x103e: 0x6629, 0x103f: 0x6611,
+ // Block 0x41, offset 0x1040
+ 0x1040: 0x434d, 0x1041: 0x436d, 0x1042: 0x0040, 0x1043: 0x6641, 0x1044: 0x6659, 0x1045: 0x6671,
+ 0x1046: 0x6689, 0x1047: 0x0040, 0x1048: 0x66c1, 0x1049: 0x66d9, 0x104a: 0x66f1, 0x104b: 0x6709,
+ 0x104c: 0x6721, 0x104d: 0x6739, 0x104e: 0x6401, 0x104f: 0x6751, 0x1050: 0x6769, 0x1051: 0x6781,
+ 0x1052: 0x438d, 0x1053: 0x6799, 0x1054: 0x6289, 0x1055: 0x43ad, 0x1056: 0x43cd, 0x1057: 0x67b1,
+ 0x1058: 0x0040, 0x1059: 0x43ed, 0x105a: 0x67c9, 0x105b: 0x67e1, 0x105c: 0x67f9, 0x105d: 0x6811,
+ 0x105e: 0x6829, 0x105f: 0x6859, 0x1060: 0x6889, 0x1061: 0x68b1, 0x1062: 0x68d9, 0x1063: 0x6901,
+ 0x1064: 0x6929, 0x1065: 0x6951, 0x1066: 0x6979, 0x1067: 0x69a1, 0x1068: 0x69c9, 0x1069: 0x69f1,
+ 0x106a: 0x6a21, 0x106b: 0x6a51, 0x106c: 0x6a81, 0x106d: 0x6ab1, 0x106e: 0x6ae1, 0x106f: 0x6b11,
+ 0x1070: 0x6b41, 0x1071: 0x6b71, 0x1072: 0x6ba1, 0x1073: 0x6bd1, 0x1074: 0x6c01, 0x1075: 0x6c31,
+ 0x1076: 0x6c61, 0x1077: 0x6c91, 0x1078: 0x6cc1, 0x1079: 0x6cf1, 0x107a: 0x6d21, 0x107b: 0x6d51,
+ 0x107c: 0x6d81, 0x107d: 0x6db1, 0x107e: 0x6de1, 0x107f: 0x440d,
+ // Block 0x42, offset 0x1080
+ 0x1080: 0xe00d, 0x1081: 0x0008, 0x1082: 0xe00d, 0x1083: 0x0008, 0x1084: 0xe00d, 0x1085: 0x0008,
+ 0x1086: 0xe00d, 0x1087: 0x0008, 0x1088: 0xe00d, 0x1089: 0x0008, 0x108a: 0xe00d, 0x108b: 0x0008,
+ 0x108c: 0xe00d, 0x108d: 0x0008, 0x108e: 0xe00d, 0x108f: 0x0008, 0x1090: 0xe00d, 0x1091: 0x0008,
+ 0x1092: 0xe00d, 0x1093: 0x0008, 0x1094: 0xe00d, 0x1095: 0x0008, 0x1096: 0xe00d, 0x1097: 0x0008,
+ 0x1098: 0xe00d, 0x1099: 0x0008, 0x109a: 0xe00d, 0x109b: 0x0008, 0x109c: 0xe00d, 0x109d: 0x0008,
+ 0x109e: 0xe00d, 0x109f: 0x0008, 0x10a0: 0xe00d, 0x10a1: 0x0008, 0x10a2: 0xe00d, 0x10a3: 0x0008,
+ 0x10a4: 0xe00d, 0x10a5: 0x0008, 0x10a6: 0xe00d, 0x10a7: 0x0008, 0x10a8: 0xe00d, 0x10a9: 0x0008,
+ 0x10aa: 0xe00d, 0x10ab: 0x0008, 0x10ac: 0xe00d, 0x10ad: 0x0008, 0x10ae: 0x0008, 0x10af: 0x1308,
+ 0x10b0: 0x1318, 0x10b1: 0x1318, 0x10b2: 0x1318, 0x10b3: 0x0018, 0x10b4: 0x1308, 0x10b5: 0x1308,
+ 0x10b6: 0x1308, 0x10b7: 0x1308, 0x10b8: 0x1308, 0x10b9: 0x1308, 0x10ba: 0x1308, 0x10bb: 0x1308,
+ 0x10bc: 0x1308, 0x10bd: 0x1308, 0x10be: 0x0018, 0x10bf: 0x0008,
+ // Block 0x43, offset 0x10c0
+ 0x10c0: 0xe00d, 0x10c1: 0x0008, 0x10c2: 0xe00d, 0x10c3: 0x0008, 0x10c4: 0xe00d, 0x10c5: 0x0008,
+ 0x10c6: 0xe00d, 0x10c7: 0x0008, 0x10c8: 0xe00d, 0x10c9: 0x0008, 0x10ca: 0xe00d, 0x10cb: 0x0008,
+ 0x10cc: 0xe00d, 0x10cd: 0x0008, 0x10ce: 0xe00d, 0x10cf: 0x0008, 0x10d0: 0xe00d, 0x10d1: 0x0008,
+ 0x10d2: 0xe00d, 0x10d3: 0x0008, 0x10d4: 0xe00d, 0x10d5: 0x0008, 0x10d6: 0xe00d, 0x10d7: 0x0008,
+ 0x10d8: 0xe00d, 0x10d9: 0x0008, 0x10da: 0xe00d, 0x10db: 0x0008, 0x10dc: 0x0ea1, 0x10dd: 0x6e11,
+ 0x10de: 0x1308, 0x10df: 0x1308, 0x10e0: 0x0008, 0x10e1: 0x0008, 0x10e2: 0x0008, 0x10e3: 0x0008,
+ 0x10e4: 0x0008, 0x10e5: 0x0008, 0x10e6: 0x0008, 0x10e7: 0x0008, 0x10e8: 0x0008, 0x10e9: 0x0008,
+ 0x10ea: 0x0008, 0x10eb: 0x0008, 0x10ec: 0x0008, 0x10ed: 0x0008, 0x10ee: 0x0008, 0x10ef: 0x0008,
+ 0x10f0: 0x0008, 0x10f1: 0x0008, 0x10f2: 0x0008, 0x10f3: 0x0008, 0x10f4: 0x0008, 0x10f5: 0x0008,
+ 0x10f6: 0x0008, 0x10f7: 0x0008, 0x10f8: 0x0008, 0x10f9: 0x0008, 0x10fa: 0x0008, 0x10fb: 0x0008,
+ 0x10fc: 0x0008, 0x10fd: 0x0008, 0x10fe: 0x0008, 0x10ff: 0x0008,
+ // Block 0x44, offset 0x1100
+ 0x1100: 0x0018, 0x1101: 0x0018, 0x1102: 0x0018, 0x1103: 0x0018, 0x1104: 0x0018, 0x1105: 0x0018,
+ 0x1106: 0x0018, 0x1107: 0x0018, 0x1108: 0x0018, 0x1109: 0x0018, 0x110a: 0x0018, 0x110b: 0x0018,
+ 0x110c: 0x0018, 0x110d: 0x0018, 0x110e: 0x0018, 0x110f: 0x0018, 0x1110: 0x0018, 0x1111: 0x0018,
+ 0x1112: 0x0018, 0x1113: 0x0018, 0x1114: 0x0018, 0x1115: 0x0018, 0x1116: 0x0018, 0x1117: 0x0008,
+ 0x1118: 0x0008, 0x1119: 0x0008, 0x111a: 0x0008, 0x111b: 0x0008, 0x111c: 0x0008, 0x111d: 0x0008,
+ 0x111e: 0x0008, 0x111f: 0x0008, 0x1120: 0x0018, 0x1121: 0x0018, 0x1122: 0xe00d, 0x1123: 0x0008,
+ 0x1124: 0xe00d, 0x1125: 0x0008, 0x1126: 0xe00d, 0x1127: 0x0008, 0x1128: 0xe00d, 0x1129: 0x0008,
+ 0x112a: 0xe00d, 0x112b: 0x0008, 0x112c: 0xe00d, 0x112d: 0x0008, 0x112e: 0xe00d, 0x112f: 0x0008,
+ 0x1130: 0x0008, 0x1131: 0x0008, 0x1132: 0xe00d, 0x1133: 0x0008, 0x1134: 0xe00d, 0x1135: 0x0008,
+ 0x1136: 0xe00d, 0x1137: 0x0008, 0x1138: 0xe00d, 0x1139: 0x0008, 0x113a: 0xe00d, 0x113b: 0x0008,
+ 0x113c: 0xe00d, 0x113d: 0x0008, 0x113e: 0xe00d, 0x113f: 0x0008,
+ // Block 0x45, offset 0x1140
+ 0x1140: 0xe00d, 0x1141: 0x0008, 0x1142: 0xe00d, 0x1143: 0x0008, 0x1144: 0xe00d, 0x1145: 0x0008,
+ 0x1146: 0xe00d, 0x1147: 0x0008, 0x1148: 0xe00d, 0x1149: 0x0008, 0x114a: 0xe00d, 0x114b: 0x0008,
+ 0x114c: 0xe00d, 0x114d: 0x0008, 0x114e: 0xe00d, 0x114f: 0x0008, 0x1150: 0xe00d, 0x1151: 0x0008,
+ 0x1152: 0xe00d, 0x1153: 0x0008, 0x1154: 0xe00d, 0x1155: 0x0008, 0x1156: 0xe00d, 0x1157: 0x0008,
+ 0x1158: 0xe00d, 0x1159: 0x0008, 0x115a: 0xe00d, 0x115b: 0x0008, 0x115c: 0xe00d, 0x115d: 0x0008,
+ 0x115e: 0xe00d, 0x115f: 0x0008, 0x1160: 0xe00d, 0x1161: 0x0008, 0x1162: 0xe00d, 0x1163: 0x0008,
+ 0x1164: 0xe00d, 0x1165: 0x0008, 0x1166: 0xe00d, 0x1167: 0x0008, 0x1168: 0xe00d, 0x1169: 0x0008,
+ 0x116a: 0xe00d, 0x116b: 0x0008, 0x116c: 0xe00d, 0x116d: 0x0008, 0x116e: 0xe00d, 0x116f: 0x0008,
+ 0x1170: 0xe0fd, 0x1171: 0x0008, 0x1172: 0x0008, 0x1173: 0x0008, 0x1174: 0x0008, 0x1175: 0x0008,
+ 0x1176: 0x0008, 0x1177: 0x0008, 0x1178: 0x0008, 0x1179: 0xe01d, 0x117a: 0x0008, 0x117b: 0xe03d,
+ 0x117c: 0x0008, 0x117d: 0x442d, 0x117e: 0xe00d, 0x117f: 0x0008,
+ // Block 0x46, offset 0x1180
+ 0x1180: 0xe00d, 0x1181: 0x0008, 0x1182: 0xe00d, 0x1183: 0x0008, 0x1184: 0xe00d, 0x1185: 0x0008,
+ 0x1186: 0xe00d, 0x1187: 0x0008, 0x1188: 0x0008, 0x1189: 0x0018, 0x118a: 0x0018, 0x118b: 0xe03d,
+ 0x118c: 0x0008, 0x118d: 0x11d9, 0x118e: 0x0008, 0x118f: 0x0008, 0x1190: 0xe00d, 0x1191: 0x0008,
+ 0x1192: 0xe00d, 0x1193: 0x0008, 0x1194: 0x0008, 0x1195: 0x0008, 0x1196: 0xe00d, 0x1197: 0x0008,
+ 0x1198: 0xe00d, 0x1199: 0x0008, 0x119a: 0xe00d, 0x119b: 0x0008, 0x119c: 0xe00d, 0x119d: 0x0008,
+ 0x119e: 0xe00d, 0x119f: 0x0008, 0x11a0: 0xe00d, 0x11a1: 0x0008, 0x11a2: 0xe00d, 0x11a3: 0x0008,
+ 0x11a4: 0xe00d, 0x11a5: 0x0008, 0x11a6: 0xe00d, 0x11a7: 0x0008, 0x11a8: 0xe00d, 0x11a9: 0x0008,
+ 0x11aa: 0x6e29, 0x11ab: 0x1029, 0x11ac: 0x11c1, 0x11ad: 0x6e41, 0x11ae: 0x1221, 0x11af: 0x0040,
+ 0x11b0: 0x6e59, 0x11b1: 0x6e71, 0x11b2: 0x1239, 0x11b3: 0x444d, 0x11b4: 0xe00d, 0x11b5: 0x0008,
+ 0x11b6: 0xe00d, 0x11b7: 0x0008, 0x11b8: 0x0040, 0x11b9: 0x0040, 0x11ba: 0x0040, 0x11bb: 0x0040,
+ 0x11bc: 0x0040, 0x11bd: 0x0040, 0x11be: 0x0040, 0x11bf: 0x0040,
+ // Block 0x47, offset 0x11c0
+ 0x11c0: 0x64d5, 0x11c1: 0x64f5, 0x11c2: 0x6515, 0x11c3: 0x6535, 0x11c4: 0x6555, 0x11c5: 0x6575,
+ 0x11c6: 0x6595, 0x11c7: 0x65b5, 0x11c8: 0x65d5, 0x11c9: 0x65f5, 0x11ca: 0x6615, 0x11cb: 0x6635,
+ 0x11cc: 0x6655, 0x11cd: 0x6675, 0x11ce: 0x0008, 0x11cf: 0x0008, 0x11d0: 0x6695, 0x11d1: 0x0008,
+ 0x11d2: 0x66b5, 0x11d3: 0x0008, 0x11d4: 0x0008, 0x11d5: 0x66d5, 0x11d6: 0x66f5, 0x11d7: 0x6715,
+ 0x11d8: 0x6735, 0x11d9: 0x6755, 0x11da: 0x6775, 0x11db: 0x6795, 0x11dc: 0x67b5, 0x11dd: 0x67d5,
+ 0x11de: 0x67f5, 0x11df: 0x0008, 0x11e0: 0x6815, 0x11e1: 0x0008, 0x11e2: 0x6835, 0x11e3: 0x0008,
+ 0x11e4: 0x0008, 0x11e5: 0x6855, 0x11e6: 0x6875, 0x11e7: 0x0008, 0x11e8: 0x0008, 0x11e9: 0x0008,
+ 0x11ea: 0x6895, 0x11eb: 0x68b5, 0x11ec: 0x68d5, 0x11ed: 0x68f5, 0x11ee: 0x6915, 0x11ef: 0x6935,
+ 0x11f0: 0x6955, 0x11f1: 0x6975, 0x11f2: 0x6995, 0x11f3: 0x69b5, 0x11f4: 0x69d5, 0x11f5: 0x69f5,
+ 0x11f6: 0x6a15, 0x11f7: 0x6a35, 0x11f8: 0x6a55, 0x11f9: 0x6a75, 0x11fa: 0x6a95, 0x11fb: 0x6ab5,
+ 0x11fc: 0x6ad5, 0x11fd: 0x6af5, 0x11fe: 0x6b15, 0x11ff: 0x6b35,
+ // Block 0x48, offset 0x1200
+ 0x1200: 0x7a95, 0x1201: 0x7ab5, 0x1202: 0x7ad5, 0x1203: 0x7af5, 0x1204: 0x7b15, 0x1205: 0x7b35,
+ 0x1206: 0x7b55, 0x1207: 0x7b75, 0x1208: 0x7b95, 0x1209: 0x7bb5, 0x120a: 0x7bd5, 0x120b: 0x7bf5,
+ 0x120c: 0x7c15, 0x120d: 0x7c35, 0x120e: 0x7c55, 0x120f: 0x6ec9, 0x1210: 0x6ef1, 0x1211: 0x6f19,
+ 0x1212: 0x7c75, 0x1213: 0x7c95, 0x1214: 0x7cb5, 0x1215: 0x6f41, 0x1216: 0x6f69, 0x1217: 0x6f91,
+ 0x1218: 0x7cd5, 0x1219: 0x7cf5, 0x121a: 0x0040, 0x121b: 0x0040, 0x121c: 0x0040, 0x121d: 0x0040,
+ 0x121e: 0x0040, 0x121f: 0x0040, 0x1220: 0x0040, 0x1221: 0x0040, 0x1222: 0x0040, 0x1223: 0x0040,
+ 0x1224: 0x0040, 0x1225: 0x0040, 0x1226: 0x0040, 0x1227: 0x0040, 0x1228: 0x0040, 0x1229: 0x0040,
+ 0x122a: 0x0040, 0x122b: 0x0040, 0x122c: 0x0040, 0x122d: 0x0040, 0x122e: 0x0040, 0x122f: 0x0040,
+ 0x1230: 0x0040, 0x1231: 0x0040, 0x1232: 0x0040, 0x1233: 0x0040, 0x1234: 0x0040, 0x1235: 0x0040,
+ 0x1236: 0x0040, 0x1237: 0x0040, 0x1238: 0x0040, 0x1239: 0x0040, 0x123a: 0x0040, 0x123b: 0x0040,
+ 0x123c: 0x0040, 0x123d: 0x0040, 0x123e: 0x0040, 0x123f: 0x0040,
+ // Block 0x49, offset 0x1240
+ 0x1240: 0x6fb9, 0x1241: 0x6fd1, 0x1242: 0x6fe9, 0x1243: 0x7d15, 0x1244: 0x7d35, 0x1245: 0x7001,
+ 0x1246: 0x7001, 0x1247: 0x0040, 0x1248: 0x0040, 0x1249: 0x0040, 0x124a: 0x0040, 0x124b: 0x0040,
+ 0x124c: 0x0040, 0x124d: 0x0040, 0x124e: 0x0040, 0x124f: 0x0040, 0x1250: 0x0040, 0x1251: 0x0040,
+ 0x1252: 0x0040, 0x1253: 0x7019, 0x1254: 0x7041, 0x1255: 0x7069, 0x1256: 0x7091, 0x1257: 0x70b9,
+ 0x1258: 0x0040, 0x1259: 0x0040, 0x125a: 0x0040, 0x125b: 0x0040, 0x125c: 0x0040, 0x125d: 0x70e1,
+ 0x125e: 0x1308, 0x125f: 0x7109, 0x1260: 0x7131, 0x1261: 0x20a9, 0x1262: 0x20f1, 0x1263: 0x7149,
+ 0x1264: 0x7161, 0x1265: 0x7179, 0x1266: 0x7191, 0x1267: 0x71a9, 0x1268: 0x71c1, 0x1269: 0x1fb2,
+ 0x126a: 0x71d9, 0x126b: 0x7201, 0x126c: 0x7229, 0x126d: 0x7261, 0x126e: 0x7299, 0x126f: 0x72c1,
+ 0x1270: 0x72e9, 0x1271: 0x7311, 0x1272: 0x7339, 0x1273: 0x7361, 0x1274: 0x7389, 0x1275: 0x73b1,
+ 0x1276: 0x73d9, 0x1277: 0x0040, 0x1278: 0x7401, 0x1279: 0x7429, 0x127a: 0x7451, 0x127b: 0x7479,
+ 0x127c: 0x74a1, 0x127d: 0x0040, 0x127e: 0x74c9, 0x127f: 0x0040,
+ // Block 0x4a, offset 0x1280
+ 0x1280: 0x74f1, 0x1281: 0x7519, 0x1282: 0x0040, 0x1283: 0x7541, 0x1284: 0x7569, 0x1285: 0x0040,
+ 0x1286: 0x7591, 0x1287: 0x75b9, 0x1288: 0x75e1, 0x1289: 0x7609, 0x128a: 0x7631, 0x128b: 0x7659,
+ 0x128c: 0x7681, 0x128d: 0x76a9, 0x128e: 0x76d1, 0x128f: 0x76f9, 0x1290: 0x7721, 0x1291: 0x7721,
+ 0x1292: 0x7739, 0x1293: 0x7739, 0x1294: 0x7739, 0x1295: 0x7739, 0x1296: 0x7751, 0x1297: 0x7751,
+ 0x1298: 0x7751, 0x1299: 0x7751, 0x129a: 0x7769, 0x129b: 0x7769, 0x129c: 0x7769, 0x129d: 0x7769,
+ 0x129e: 0x7781, 0x129f: 0x7781, 0x12a0: 0x7781, 0x12a1: 0x7781, 0x12a2: 0x7799, 0x12a3: 0x7799,
+ 0x12a4: 0x7799, 0x12a5: 0x7799, 0x12a6: 0x77b1, 0x12a7: 0x77b1, 0x12a8: 0x77b1, 0x12a9: 0x77b1,
+ 0x12aa: 0x77c9, 0x12ab: 0x77c9, 0x12ac: 0x77c9, 0x12ad: 0x77c9, 0x12ae: 0x77e1, 0x12af: 0x77e1,
+ 0x12b0: 0x77e1, 0x12b1: 0x77e1, 0x12b2: 0x77f9, 0x12b3: 0x77f9, 0x12b4: 0x77f9, 0x12b5: 0x77f9,
+ 0x12b6: 0x7811, 0x12b7: 0x7811, 0x12b8: 0x7811, 0x12b9: 0x7811, 0x12ba: 0x7829, 0x12bb: 0x7829,
+ 0x12bc: 0x7829, 0x12bd: 0x7829, 0x12be: 0x7841, 0x12bf: 0x7841,
+ // Block 0x4b, offset 0x12c0
+ 0x12c0: 0x7841, 0x12c1: 0x7841, 0x12c2: 0x7859, 0x12c3: 0x7859, 0x12c4: 0x7871, 0x12c5: 0x7871,
+ 0x12c6: 0x7889, 0x12c7: 0x7889, 0x12c8: 0x78a1, 0x12c9: 0x78a1, 0x12ca: 0x78b9, 0x12cb: 0x78b9,
+ 0x12cc: 0x78d1, 0x12cd: 0x78d1, 0x12ce: 0x78e9, 0x12cf: 0x78e9, 0x12d0: 0x78e9, 0x12d1: 0x78e9,
+ 0x12d2: 0x7901, 0x12d3: 0x7901, 0x12d4: 0x7901, 0x12d5: 0x7901, 0x12d6: 0x7919, 0x12d7: 0x7919,
+ 0x12d8: 0x7919, 0x12d9: 0x7919, 0x12da: 0x7931, 0x12db: 0x7931, 0x12dc: 0x7931, 0x12dd: 0x7931,
+ 0x12de: 0x7949, 0x12df: 0x7949, 0x12e0: 0x7961, 0x12e1: 0x7961, 0x12e2: 0x7961, 0x12e3: 0x7961,
+ 0x12e4: 0x7979, 0x12e5: 0x7979, 0x12e6: 0x7991, 0x12e7: 0x7991, 0x12e8: 0x7991, 0x12e9: 0x7991,
+ 0x12ea: 0x79a9, 0x12eb: 0x79a9, 0x12ec: 0x79a9, 0x12ed: 0x79a9, 0x12ee: 0x79c1, 0x12ef: 0x79c1,
+ 0x12f0: 0x79d9, 0x12f1: 0x79d9, 0x12f2: 0x0018, 0x12f3: 0x0018, 0x12f4: 0x0018, 0x12f5: 0x0018,
+ 0x12f6: 0x0018, 0x12f7: 0x0018, 0x12f8: 0x0018, 0x12f9: 0x0018, 0x12fa: 0x0018, 0x12fb: 0x0018,
+ 0x12fc: 0x0018, 0x12fd: 0x0018, 0x12fe: 0x0018, 0x12ff: 0x0018,
+ // Block 0x4c, offset 0x1300
+ 0x1300: 0x0018, 0x1301: 0x0018, 0x1302: 0x0040, 0x1303: 0x0040, 0x1304: 0x0040, 0x1305: 0x0040,
+ 0x1306: 0x0040, 0x1307: 0x0040, 0x1308: 0x0040, 0x1309: 0x0040, 0x130a: 0x0040, 0x130b: 0x0040,
+ 0x130c: 0x0040, 0x130d: 0x0040, 0x130e: 0x0040, 0x130f: 0x0040, 0x1310: 0x0040, 0x1311: 0x0040,
+ 0x1312: 0x0040, 0x1313: 0x79f1, 0x1314: 0x79f1, 0x1315: 0x79f1, 0x1316: 0x79f1, 0x1317: 0x7a09,
+ 0x1318: 0x7a09, 0x1319: 0x7a21, 0x131a: 0x7a21, 0x131b: 0x7a39, 0x131c: 0x7a39, 0x131d: 0x0479,
+ 0x131e: 0x7a51, 0x131f: 0x7a51, 0x1320: 0x7a69, 0x1321: 0x7a69, 0x1322: 0x7a81, 0x1323: 0x7a81,
+ 0x1324: 0x7a99, 0x1325: 0x7a99, 0x1326: 0x7a99, 0x1327: 0x7a99, 0x1328: 0x7ab1, 0x1329: 0x7ab1,
+ 0x132a: 0x7ac9, 0x132b: 0x7ac9, 0x132c: 0x7af1, 0x132d: 0x7af1, 0x132e: 0x7b19, 0x132f: 0x7b19,
+ 0x1330: 0x7b41, 0x1331: 0x7b41, 0x1332: 0x7b69, 0x1333: 0x7b69, 0x1334: 0x7b91, 0x1335: 0x7b91,
+ 0x1336: 0x7bb9, 0x1337: 0x7bb9, 0x1338: 0x7bb9, 0x1339: 0x7be1, 0x133a: 0x7be1, 0x133b: 0x7be1,
+ 0x133c: 0x7c09, 0x133d: 0x7c09, 0x133e: 0x7c09, 0x133f: 0x7c09,
+ // Block 0x4d, offset 0x1340
+ 0x1340: 0x85f9, 0x1341: 0x8621, 0x1342: 0x8649, 0x1343: 0x8671, 0x1344: 0x8699, 0x1345: 0x86c1,
+ 0x1346: 0x86e9, 0x1347: 0x8711, 0x1348: 0x8739, 0x1349: 0x8761, 0x134a: 0x8789, 0x134b: 0x87b1,
+ 0x134c: 0x87d9, 0x134d: 0x8801, 0x134e: 0x8829, 0x134f: 0x8851, 0x1350: 0x8879, 0x1351: 0x88a1,
+ 0x1352: 0x88c9, 0x1353: 0x88f1, 0x1354: 0x8919, 0x1355: 0x8941, 0x1356: 0x8969, 0x1357: 0x8991,
+ 0x1358: 0x89b9, 0x1359: 0x89e1, 0x135a: 0x8a09, 0x135b: 0x8a31, 0x135c: 0x8a59, 0x135d: 0x8a81,
+ 0x135e: 0x8aaa, 0x135f: 0x8ada, 0x1360: 0x8b0a, 0x1361: 0x8b3a, 0x1362: 0x8b6a, 0x1363: 0x8b9a,
+ 0x1364: 0x8bc9, 0x1365: 0x8bf1, 0x1366: 0x7c71, 0x1367: 0x8c19, 0x1368: 0x7be1, 0x1369: 0x7c99,
+ 0x136a: 0x8c41, 0x136b: 0x8c69, 0x136c: 0x7d39, 0x136d: 0x8c91, 0x136e: 0x7d61, 0x136f: 0x7d89,
+ 0x1370: 0x8cb9, 0x1371: 0x8ce1, 0x1372: 0x7e29, 0x1373: 0x8d09, 0x1374: 0x7e51, 0x1375: 0x7e79,
+ 0x1376: 0x8d31, 0x1377: 0x8d59, 0x1378: 0x7ec9, 0x1379: 0x8d81, 0x137a: 0x7ef1, 0x137b: 0x7f19,
+ 0x137c: 0x83a1, 0x137d: 0x83c9, 0x137e: 0x8441, 0x137f: 0x8469,
+ // Block 0x4e, offset 0x1380
+ 0x1380: 0x8491, 0x1381: 0x8531, 0x1382: 0x8559, 0x1383: 0x8581, 0x1384: 0x85a9, 0x1385: 0x8649,
+ 0x1386: 0x8671, 0x1387: 0x8699, 0x1388: 0x8da9, 0x1389: 0x8739, 0x138a: 0x8dd1, 0x138b: 0x8df9,
+ 0x138c: 0x8829, 0x138d: 0x8e21, 0x138e: 0x8851, 0x138f: 0x8879, 0x1390: 0x8a81, 0x1391: 0x8e49,
+ 0x1392: 0x8e71, 0x1393: 0x89b9, 0x1394: 0x8e99, 0x1395: 0x89e1, 0x1396: 0x8a09, 0x1397: 0x7c21,
+ 0x1398: 0x7c49, 0x1399: 0x8ec1, 0x139a: 0x7c71, 0x139b: 0x8ee9, 0x139c: 0x7cc1, 0x139d: 0x7ce9,
+ 0x139e: 0x7d11, 0x139f: 0x7d39, 0x13a0: 0x8f11, 0x13a1: 0x7db1, 0x13a2: 0x7dd9, 0x13a3: 0x7e01,
+ 0x13a4: 0x7e29, 0x13a5: 0x8f39, 0x13a6: 0x7ec9, 0x13a7: 0x7f41, 0x13a8: 0x7f69, 0x13a9: 0x7f91,
+ 0x13aa: 0x7fb9, 0x13ab: 0x7fe1, 0x13ac: 0x8031, 0x13ad: 0x8059, 0x13ae: 0x8081, 0x13af: 0x80a9,
+ 0x13b0: 0x80d1, 0x13b1: 0x80f9, 0x13b2: 0x8f61, 0x13b3: 0x8121, 0x13b4: 0x8149, 0x13b5: 0x8171,
+ 0x13b6: 0x8199, 0x13b7: 0x81c1, 0x13b8: 0x81e9, 0x13b9: 0x8239, 0x13ba: 0x8261, 0x13bb: 0x8289,
+ 0x13bc: 0x82b1, 0x13bd: 0x82d9, 0x13be: 0x8301, 0x13bf: 0x8329,
+ // Block 0x4f, offset 0x13c0
+ 0x13c0: 0x8351, 0x13c1: 0x8379, 0x13c2: 0x83f1, 0x13c3: 0x8419, 0x13c4: 0x84b9, 0x13c5: 0x84e1,
+ 0x13c6: 0x8509, 0x13c7: 0x8531, 0x13c8: 0x8559, 0x13c9: 0x85d1, 0x13ca: 0x85f9, 0x13cb: 0x8621,
+ 0x13cc: 0x8649, 0x13cd: 0x8f89, 0x13ce: 0x86c1, 0x13cf: 0x86e9, 0x13d0: 0x8711, 0x13d1: 0x8739,
+ 0x13d2: 0x87b1, 0x13d3: 0x87d9, 0x13d4: 0x8801, 0x13d5: 0x8829, 0x13d6: 0x8fb1, 0x13d7: 0x88a1,
+ 0x13d8: 0x88c9, 0x13d9: 0x8fd9, 0x13da: 0x8941, 0x13db: 0x8969, 0x13dc: 0x8991, 0x13dd: 0x89b9,
+ 0x13de: 0x9001, 0x13df: 0x7c71, 0x13e0: 0x8ee9, 0x13e1: 0x7d39, 0x13e2: 0x8f11, 0x13e3: 0x7e29,
+ 0x13e4: 0x8f39, 0x13e5: 0x7ec9, 0x13e6: 0x9029, 0x13e7: 0x80d1, 0x13e8: 0x9051, 0x13e9: 0x9079,
+ 0x13ea: 0x90a1, 0x13eb: 0x8531, 0x13ec: 0x8559, 0x13ed: 0x8649, 0x13ee: 0x8829, 0x13ef: 0x8fb1,
+ 0x13f0: 0x89b9, 0x13f1: 0x9001, 0x13f2: 0x90c9, 0x13f3: 0x9101, 0x13f4: 0x9139, 0x13f5: 0x9171,
+ 0x13f6: 0x9199, 0x13f7: 0x91c1, 0x13f8: 0x91e9, 0x13f9: 0x9211, 0x13fa: 0x9239, 0x13fb: 0x9261,
+ 0x13fc: 0x9289, 0x13fd: 0x92b1, 0x13fe: 0x92d9, 0x13ff: 0x9301,
+ // Block 0x50, offset 0x1400
+ 0x1400: 0x9329, 0x1401: 0x9351, 0x1402: 0x9379, 0x1403: 0x93a1, 0x1404: 0x93c9, 0x1405: 0x93f1,
+ 0x1406: 0x9419, 0x1407: 0x9441, 0x1408: 0x9469, 0x1409: 0x9491, 0x140a: 0x94b9, 0x140b: 0x94e1,
+ 0x140c: 0x9079, 0x140d: 0x9509, 0x140e: 0x9531, 0x140f: 0x9559, 0x1410: 0x9581, 0x1411: 0x9171,
+ 0x1412: 0x9199, 0x1413: 0x91c1, 0x1414: 0x91e9, 0x1415: 0x9211, 0x1416: 0x9239, 0x1417: 0x9261,
+ 0x1418: 0x9289, 0x1419: 0x92b1, 0x141a: 0x92d9, 0x141b: 0x9301, 0x141c: 0x9329, 0x141d: 0x9351,
+ 0x141e: 0x9379, 0x141f: 0x93a1, 0x1420: 0x93c9, 0x1421: 0x93f1, 0x1422: 0x9419, 0x1423: 0x9441,
+ 0x1424: 0x9469, 0x1425: 0x9491, 0x1426: 0x94b9, 0x1427: 0x94e1, 0x1428: 0x9079, 0x1429: 0x9509,
+ 0x142a: 0x9531, 0x142b: 0x9559, 0x142c: 0x9581, 0x142d: 0x9491, 0x142e: 0x94b9, 0x142f: 0x94e1,
+ 0x1430: 0x9079, 0x1431: 0x9051, 0x1432: 0x90a1, 0x1433: 0x8211, 0x1434: 0x8059, 0x1435: 0x8081,
+ 0x1436: 0x80a9, 0x1437: 0x9491, 0x1438: 0x94b9, 0x1439: 0x94e1, 0x143a: 0x8211, 0x143b: 0x8239,
+ 0x143c: 0x95a9, 0x143d: 0x95a9, 0x143e: 0x0018, 0x143f: 0x0018,
+ // Block 0x51, offset 0x1440
+ 0x1440: 0x0040, 0x1441: 0x0040, 0x1442: 0x0040, 0x1443: 0x0040, 0x1444: 0x0040, 0x1445: 0x0040,
+ 0x1446: 0x0040, 0x1447: 0x0040, 0x1448: 0x0040, 0x1449: 0x0040, 0x144a: 0x0040, 0x144b: 0x0040,
+ 0x144c: 0x0040, 0x144d: 0x0040, 0x144e: 0x0040, 0x144f: 0x0040, 0x1450: 0x95d1, 0x1451: 0x9609,
+ 0x1452: 0x9609, 0x1453: 0x9641, 0x1454: 0x9679, 0x1455: 0x96b1, 0x1456: 0x96e9, 0x1457: 0x9721,
+ 0x1458: 0x9759, 0x1459: 0x9759, 0x145a: 0x9791, 0x145b: 0x97c9, 0x145c: 0x9801, 0x145d: 0x9839,
+ 0x145e: 0x9871, 0x145f: 0x98a9, 0x1460: 0x98a9, 0x1461: 0x98e1, 0x1462: 0x9919, 0x1463: 0x9919,
+ 0x1464: 0x9951, 0x1465: 0x9951, 0x1466: 0x9989, 0x1467: 0x99c1, 0x1468: 0x99c1, 0x1469: 0x99f9,
+ 0x146a: 0x9a31, 0x146b: 0x9a31, 0x146c: 0x9a69, 0x146d: 0x9a69, 0x146e: 0x9aa1, 0x146f: 0x9ad9,
+ 0x1470: 0x9ad9, 0x1471: 0x9b11, 0x1472: 0x9b11, 0x1473: 0x9b49, 0x1474: 0x9b81, 0x1475: 0x9bb9,
+ 0x1476: 0x9bf1, 0x1477: 0x9bf1, 0x1478: 0x9c29, 0x1479: 0x9c61, 0x147a: 0x9c99, 0x147b: 0x9cd1,
+ 0x147c: 0x9d09, 0x147d: 0x9d09, 0x147e: 0x9d41, 0x147f: 0x9d79,
+ // Block 0x52, offset 0x1480
+ 0x1480: 0xa949, 0x1481: 0xa981, 0x1482: 0xa9b9, 0x1483: 0xa8a1, 0x1484: 0x9bb9, 0x1485: 0x9989,
+ 0x1486: 0xa9f1, 0x1487: 0xaa29, 0x1488: 0x0040, 0x1489: 0x0040, 0x148a: 0x0040, 0x148b: 0x0040,
+ 0x148c: 0x0040, 0x148d: 0x0040, 0x148e: 0x0040, 0x148f: 0x0040, 0x1490: 0x0040, 0x1491: 0x0040,
+ 0x1492: 0x0040, 0x1493: 0x0040, 0x1494: 0x0040, 0x1495: 0x0040, 0x1496: 0x0040, 0x1497: 0x0040,
+ 0x1498: 0x0040, 0x1499: 0x0040, 0x149a: 0x0040, 0x149b: 0x0040, 0x149c: 0x0040, 0x149d: 0x0040,
+ 0x149e: 0x0040, 0x149f: 0x0040, 0x14a0: 0x0040, 0x14a1: 0x0040, 0x14a2: 0x0040, 0x14a3: 0x0040,
+ 0x14a4: 0x0040, 0x14a5: 0x0040, 0x14a6: 0x0040, 0x14a7: 0x0040, 0x14a8: 0x0040, 0x14a9: 0x0040,
+ 0x14aa: 0x0040, 0x14ab: 0x0040, 0x14ac: 0x0040, 0x14ad: 0x0040, 0x14ae: 0x0040, 0x14af: 0x0040,
+ 0x14b0: 0xaa61, 0x14b1: 0xaa99, 0x14b2: 0xaad1, 0x14b3: 0xab19, 0x14b4: 0xab61, 0x14b5: 0xaba9,
+ 0x14b6: 0xabf1, 0x14b7: 0xac39, 0x14b8: 0xac81, 0x14b9: 0xacc9, 0x14ba: 0xad02, 0x14bb: 0xae12,
+ 0x14bc: 0xae91, 0x14bd: 0x0018, 0x14be: 0x0040, 0x14bf: 0x0040,
+ // Block 0x53, offset 0x14c0
+ 0x14c0: 0x13c0, 0x14c1: 0x13c0, 0x14c2: 0x13c0, 0x14c3: 0x13c0, 0x14c4: 0x13c0, 0x14c5: 0x13c0,
+ 0x14c6: 0x13c0, 0x14c7: 0x13c0, 0x14c8: 0x13c0, 0x14c9: 0x13c0, 0x14ca: 0x13c0, 0x14cb: 0x13c0,
+ 0x14cc: 0x13c0, 0x14cd: 0x13c0, 0x14ce: 0x13c0, 0x14cf: 0x13c0, 0x14d0: 0xaeda, 0x14d1: 0x7d55,
+ 0x14d2: 0x0040, 0x14d3: 0xaeea, 0x14d4: 0x03c2, 0x14d5: 0xaefa, 0x14d6: 0xaf0a, 0x14d7: 0x7d75,
+ 0x14d8: 0x7d95, 0x14d9: 0x0040, 0x14da: 0x0040, 0x14db: 0x0040, 0x14dc: 0x0040, 0x14dd: 0x0040,
+ 0x14de: 0x0040, 0x14df: 0x0040, 0x14e0: 0x1308, 0x14e1: 0x1308, 0x14e2: 0x1308, 0x14e3: 0x1308,
+ 0x14e4: 0x1308, 0x14e5: 0x1308, 0x14e6: 0x1308, 0x14e7: 0x1308, 0x14e8: 0x1308, 0x14e9: 0x1308,
+ 0x14ea: 0x1308, 0x14eb: 0x1308, 0x14ec: 0x1308, 0x14ed: 0x1308, 0x14ee: 0x1308, 0x14ef: 0x1308,
+ 0x14f0: 0x0040, 0x14f1: 0x7db5, 0x14f2: 0x7dd5, 0x14f3: 0xaf1a, 0x14f4: 0xaf1a, 0x14f5: 0x1fd2,
+ 0x14f6: 0x1fe2, 0x14f7: 0xaf2a, 0x14f8: 0xaf3a, 0x14f9: 0x7df5, 0x14fa: 0x7e15, 0x14fb: 0x7e35,
+ 0x14fc: 0x7df5, 0x14fd: 0x7e55, 0x14fe: 0x7e75, 0x14ff: 0x7e55,
+ // Block 0x54, offset 0x1500
+ 0x1500: 0x7e95, 0x1501: 0x7eb5, 0x1502: 0x7ed5, 0x1503: 0x7eb5, 0x1504: 0x7ef5, 0x1505: 0x0018,
+ 0x1506: 0x0018, 0x1507: 0xaf4a, 0x1508: 0xaf5a, 0x1509: 0x7f16, 0x150a: 0x7f36, 0x150b: 0x7f56,
+ 0x150c: 0x7f76, 0x150d: 0xaf1a, 0x150e: 0xaf1a, 0x150f: 0xaf1a, 0x1510: 0xaeda, 0x1511: 0x7f95,
+ 0x1512: 0x0040, 0x1513: 0x0040, 0x1514: 0x03c2, 0x1515: 0xaeea, 0x1516: 0xaf0a, 0x1517: 0xaefa,
+ 0x1518: 0x7fb5, 0x1519: 0x1fd2, 0x151a: 0x1fe2, 0x151b: 0xaf2a, 0x151c: 0xaf3a, 0x151d: 0x7e95,
+ 0x151e: 0x7ef5, 0x151f: 0xaf6a, 0x1520: 0xaf7a, 0x1521: 0xaf8a, 0x1522: 0x1fb2, 0x1523: 0xaf99,
+ 0x1524: 0xafaa, 0x1525: 0xafba, 0x1526: 0x1fc2, 0x1527: 0x0040, 0x1528: 0xafca, 0x1529: 0xafda,
+ 0x152a: 0xafea, 0x152b: 0xaffa, 0x152c: 0x0040, 0x152d: 0x0040, 0x152e: 0x0040, 0x152f: 0x0040,
+ 0x1530: 0x7fd6, 0x1531: 0xb009, 0x1532: 0x7ff6, 0x1533: 0x0008, 0x1534: 0x8016, 0x1535: 0x0040,
+ 0x1536: 0x8036, 0x1537: 0xb031, 0x1538: 0x8056, 0x1539: 0xb059, 0x153a: 0x8076, 0x153b: 0xb081,
+ 0x153c: 0x8096, 0x153d: 0xb0a9, 0x153e: 0x80b6, 0x153f: 0xb0d1,
+ // Block 0x55, offset 0x1540
+ 0x1540: 0xb0f9, 0x1541: 0xb111, 0x1542: 0xb111, 0x1543: 0xb129, 0x1544: 0xb129, 0x1545: 0xb141,
+ 0x1546: 0xb141, 0x1547: 0xb159, 0x1548: 0xb159, 0x1549: 0xb171, 0x154a: 0xb171, 0x154b: 0xb171,
+ 0x154c: 0xb171, 0x154d: 0xb189, 0x154e: 0xb189, 0x154f: 0xb1a1, 0x1550: 0xb1a1, 0x1551: 0xb1a1,
+ 0x1552: 0xb1a1, 0x1553: 0xb1b9, 0x1554: 0xb1b9, 0x1555: 0xb1d1, 0x1556: 0xb1d1, 0x1557: 0xb1d1,
+ 0x1558: 0xb1d1, 0x1559: 0xb1e9, 0x155a: 0xb1e9, 0x155b: 0xb1e9, 0x155c: 0xb1e9, 0x155d: 0xb201,
+ 0x155e: 0xb201, 0x155f: 0xb201, 0x1560: 0xb201, 0x1561: 0xb219, 0x1562: 0xb219, 0x1563: 0xb219,
+ 0x1564: 0xb219, 0x1565: 0xb231, 0x1566: 0xb231, 0x1567: 0xb231, 0x1568: 0xb231, 0x1569: 0xb249,
+ 0x156a: 0xb249, 0x156b: 0xb261, 0x156c: 0xb261, 0x156d: 0xb279, 0x156e: 0xb279, 0x156f: 0xb291,
+ 0x1570: 0xb291, 0x1571: 0xb2a9, 0x1572: 0xb2a9, 0x1573: 0xb2a9, 0x1574: 0xb2a9, 0x1575: 0xb2c1,
+ 0x1576: 0xb2c1, 0x1577: 0xb2c1, 0x1578: 0xb2c1, 0x1579: 0xb2d9, 0x157a: 0xb2d9, 0x157b: 0xb2d9,
+ 0x157c: 0xb2d9, 0x157d: 0xb2f1, 0x157e: 0xb2f1, 0x157f: 0xb2f1,
+ // Block 0x56, offset 0x1580
+ 0x1580: 0xb2f1, 0x1581: 0xb309, 0x1582: 0xb309, 0x1583: 0xb309, 0x1584: 0xb309, 0x1585: 0xb321,
+ 0x1586: 0xb321, 0x1587: 0xb321, 0x1588: 0xb321, 0x1589: 0xb339, 0x158a: 0xb339, 0x158b: 0xb339,
+ 0x158c: 0xb339, 0x158d: 0xb351, 0x158e: 0xb351, 0x158f: 0xb351, 0x1590: 0xb351, 0x1591: 0xb369,
+ 0x1592: 0xb369, 0x1593: 0xb369, 0x1594: 0xb369, 0x1595: 0xb381, 0x1596: 0xb381, 0x1597: 0xb381,
+ 0x1598: 0xb381, 0x1599: 0xb399, 0x159a: 0xb399, 0x159b: 0xb399, 0x159c: 0xb399, 0x159d: 0xb3b1,
+ 0x159e: 0xb3b1, 0x159f: 0xb3b1, 0x15a0: 0xb3b1, 0x15a1: 0xb3c9, 0x15a2: 0xb3c9, 0x15a3: 0xb3c9,
+ 0x15a4: 0xb3c9, 0x15a5: 0xb3e1, 0x15a6: 0xb3e1, 0x15a7: 0xb3e1, 0x15a8: 0xb3e1, 0x15a9: 0xb3f9,
+ 0x15aa: 0xb3f9, 0x15ab: 0xb3f9, 0x15ac: 0xb3f9, 0x15ad: 0xb411, 0x15ae: 0xb411, 0x15af: 0x7ab1,
+ 0x15b0: 0x7ab1, 0x15b1: 0xb429, 0x15b2: 0xb429, 0x15b3: 0xb429, 0x15b4: 0xb429, 0x15b5: 0xb441,
+ 0x15b6: 0xb441, 0x15b7: 0xb469, 0x15b8: 0xb469, 0x15b9: 0xb491, 0x15ba: 0xb491, 0x15bb: 0xb4b9,
+ 0x15bc: 0xb4b9, 0x15bd: 0x0040, 0x15be: 0x0040, 0x15bf: 0x03c0,
+ // Block 0x57, offset 0x15c0
+ 0x15c0: 0x0040, 0x15c1: 0xaefa, 0x15c2: 0xb4e2, 0x15c3: 0xaf6a, 0x15c4: 0xafda, 0x15c5: 0xafea,
+ 0x15c6: 0xaf7a, 0x15c7: 0xb4f2, 0x15c8: 0x1fd2, 0x15c9: 0x1fe2, 0x15ca: 0xaf8a, 0x15cb: 0x1fb2,
+ 0x15cc: 0xaeda, 0x15cd: 0xaf99, 0x15ce: 0x29d1, 0x15cf: 0xb502, 0x15d0: 0x1f41, 0x15d1: 0x00c9,
+ 0x15d2: 0x0069, 0x15d3: 0x0079, 0x15d4: 0x1f51, 0x15d5: 0x1f61, 0x15d6: 0x1f71, 0x15d7: 0x1f81,
+ 0x15d8: 0x1f91, 0x15d9: 0x1fa1, 0x15da: 0xaeea, 0x15db: 0x03c2, 0x15dc: 0xafaa, 0x15dd: 0x1fc2,
+ 0x15de: 0xafba, 0x15df: 0xaf0a, 0x15e0: 0xaffa, 0x15e1: 0x0039, 0x15e2: 0x0ee9, 0x15e3: 0x1159,
+ 0x15e4: 0x0ef9, 0x15e5: 0x0f09, 0x15e6: 0x1199, 0x15e7: 0x0f31, 0x15e8: 0x0249, 0x15e9: 0x0f41,
+ 0x15ea: 0x0259, 0x15eb: 0x0f51, 0x15ec: 0x0359, 0x15ed: 0x0f61, 0x15ee: 0x0f71, 0x15ef: 0x00d9,
+ 0x15f0: 0x0f99, 0x15f1: 0x2039, 0x15f2: 0x0269, 0x15f3: 0x01d9, 0x15f4: 0x0fa9, 0x15f5: 0x0fb9,
+ 0x15f6: 0x1089, 0x15f7: 0x0279, 0x15f8: 0x0369, 0x15f9: 0x0289, 0x15fa: 0x13d1, 0x15fb: 0xaf4a,
+ 0x15fc: 0xafca, 0x15fd: 0xaf5a, 0x15fe: 0xb512, 0x15ff: 0xaf1a,
+ // Block 0x58, offset 0x1600
+ 0x1600: 0x1caa, 0x1601: 0x0039, 0x1602: 0x0ee9, 0x1603: 0x1159, 0x1604: 0x0ef9, 0x1605: 0x0f09,
+ 0x1606: 0x1199, 0x1607: 0x0f31, 0x1608: 0x0249, 0x1609: 0x0f41, 0x160a: 0x0259, 0x160b: 0x0f51,
+ 0x160c: 0x0359, 0x160d: 0x0f61, 0x160e: 0x0f71, 0x160f: 0x00d9, 0x1610: 0x0f99, 0x1611: 0x2039,
+ 0x1612: 0x0269, 0x1613: 0x01d9, 0x1614: 0x0fa9, 0x1615: 0x0fb9, 0x1616: 0x1089, 0x1617: 0x0279,
+ 0x1618: 0x0369, 0x1619: 0x0289, 0x161a: 0x13d1, 0x161b: 0xaf2a, 0x161c: 0xb522, 0x161d: 0xaf3a,
+ 0x161e: 0xb532, 0x161f: 0x80d5, 0x1620: 0x80f5, 0x1621: 0x29d1, 0x1622: 0x8115, 0x1623: 0x8115,
+ 0x1624: 0x8135, 0x1625: 0x8155, 0x1626: 0x8175, 0x1627: 0x8195, 0x1628: 0x81b5, 0x1629: 0x81d5,
+ 0x162a: 0x81f5, 0x162b: 0x8215, 0x162c: 0x8235, 0x162d: 0x8255, 0x162e: 0x8275, 0x162f: 0x8295,
+ 0x1630: 0x82b5, 0x1631: 0x82d5, 0x1632: 0x82f5, 0x1633: 0x8315, 0x1634: 0x8335, 0x1635: 0x8355,
+ 0x1636: 0x8375, 0x1637: 0x8395, 0x1638: 0x83b5, 0x1639: 0x83d5, 0x163a: 0x83f5, 0x163b: 0x8415,
+ 0x163c: 0x81b5, 0x163d: 0x8435, 0x163e: 0x8455, 0x163f: 0x8215,
+ // Block 0x59, offset 0x1640
+ 0x1640: 0x8475, 0x1641: 0x8495, 0x1642: 0x84b5, 0x1643: 0x84d5, 0x1644: 0x84f5, 0x1645: 0x8515,
+ 0x1646: 0x8535, 0x1647: 0x8555, 0x1648: 0x84d5, 0x1649: 0x8575, 0x164a: 0x84d5, 0x164b: 0x8595,
+ 0x164c: 0x8595, 0x164d: 0x85b5, 0x164e: 0x85b5, 0x164f: 0x85d5, 0x1650: 0x8515, 0x1651: 0x85f5,
+ 0x1652: 0x8615, 0x1653: 0x85f5, 0x1654: 0x8635, 0x1655: 0x8615, 0x1656: 0x8655, 0x1657: 0x8655,
+ 0x1658: 0x8675, 0x1659: 0x8675, 0x165a: 0x8695, 0x165b: 0x8695, 0x165c: 0x8615, 0x165d: 0x8115,
+ 0x165e: 0x86b5, 0x165f: 0x86d5, 0x1660: 0x0040, 0x1661: 0x86f5, 0x1662: 0x8715, 0x1663: 0x8735,
+ 0x1664: 0x8755, 0x1665: 0x8735, 0x1666: 0x8775, 0x1667: 0x8795, 0x1668: 0x87b5, 0x1669: 0x87b5,
+ 0x166a: 0x87d5, 0x166b: 0x87d5, 0x166c: 0x87f5, 0x166d: 0x87f5, 0x166e: 0x87d5, 0x166f: 0x87d5,
+ 0x1670: 0x8815, 0x1671: 0x8835, 0x1672: 0x8855, 0x1673: 0x8875, 0x1674: 0x8895, 0x1675: 0x88b5,
+ 0x1676: 0x88b5, 0x1677: 0x88b5, 0x1678: 0x88d5, 0x1679: 0x88d5, 0x167a: 0x88d5, 0x167b: 0x88d5,
+ 0x167c: 0x87b5, 0x167d: 0x87b5, 0x167e: 0x87b5, 0x167f: 0x0040,
+ // Block 0x5a, offset 0x1680
+ 0x1680: 0x0040, 0x1681: 0x0040, 0x1682: 0x8715, 0x1683: 0x86f5, 0x1684: 0x88f5, 0x1685: 0x86f5,
+ 0x1686: 0x8715, 0x1687: 0x86f5, 0x1688: 0x0040, 0x1689: 0x0040, 0x168a: 0x8915, 0x168b: 0x8715,
+ 0x168c: 0x8935, 0x168d: 0x88f5, 0x168e: 0x8935, 0x168f: 0x8715, 0x1690: 0x0040, 0x1691: 0x0040,
+ 0x1692: 0x8955, 0x1693: 0x8975, 0x1694: 0x8875, 0x1695: 0x8935, 0x1696: 0x88f5, 0x1697: 0x8935,
+ 0x1698: 0x0040, 0x1699: 0x0040, 0x169a: 0x8995, 0x169b: 0x89b5, 0x169c: 0x8995, 0x169d: 0x0040,
+ 0x169e: 0x0040, 0x169f: 0x0040, 0x16a0: 0xb541, 0x16a1: 0xb559, 0x16a2: 0xb571, 0x16a3: 0x89d6,
+ 0x16a4: 0xb589, 0x16a5: 0xb5a1, 0x16a6: 0x89f5, 0x16a7: 0x0040, 0x16a8: 0x8a15, 0x16a9: 0x8a35,
+ 0x16aa: 0x8a55, 0x16ab: 0x8a35, 0x16ac: 0x8a75, 0x16ad: 0x8a95, 0x16ae: 0x8ab5, 0x16af: 0x0040,
+ 0x16b0: 0x0040, 0x16b1: 0x0040, 0x16b2: 0x0040, 0x16b3: 0x0040, 0x16b4: 0x0040, 0x16b5: 0x0040,
+ 0x16b6: 0x0040, 0x16b7: 0x0040, 0x16b8: 0x0040, 0x16b9: 0x0340, 0x16ba: 0x0340, 0x16bb: 0x0340,
+ 0x16bc: 0x0040, 0x16bd: 0x0040, 0x16be: 0x0040, 0x16bf: 0x0040,
+ // Block 0x5b, offset 0x16c0
+ 0x16c0: 0x0208, 0x16c1: 0x0208, 0x16c2: 0x0208, 0x16c3: 0x0208, 0x16c4: 0x0208, 0x16c5: 0x0408,
+ 0x16c6: 0x0008, 0x16c7: 0x0408, 0x16c8: 0x0018, 0x16c9: 0x0408, 0x16ca: 0x0408, 0x16cb: 0x0008,
+ 0x16cc: 0x0008, 0x16cd: 0x0108, 0x16ce: 0x0408, 0x16cf: 0x0408, 0x16d0: 0x0408, 0x16d1: 0x0408,
+ 0x16d2: 0x0408, 0x16d3: 0x0208, 0x16d4: 0x0208, 0x16d5: 0x0208, 0x16d6: 0x0208, 0x16d7: 0x0108,
+ 0x16d8: 0x0208, 0x16d9: 0x0208, 0x16da: 0x0208, 0x16db: 0x0208, 0x16dc: 0x0208, 0x16dd: 0x0408,
+ 0x16de: 0x0208, 0x16df: 0x0208, 0x16e0: 0x0208, 0x16e1: 0x0408, 0x16e2: 0x0008, 0x16e3: 0x0008,
+ 0x16e4: 0x0408, 0x16e5: 0x1308, 0x16e6: 0x1308, 0x16e7: 0x0040, 0x16e8: 0x0040, 0x16e9: 0x0040,
+ 0x16ea: 0x0040, 0x16eb: 0x0218, 0x16ec: 0x0218, 0x16ed: 0x0218, 0x16ee: 0x0218, 0x16ef: 0x0418,
+ 0x16f0: 0x0018, 0x16f1: 0x0018, 0x16f2: 0x0018, 0x16f3: 0x0018, 0x16f4: 0x0018, 0x16f5: 0x0018,
+ 0x16f6: 0x0018, 0x16f7: 0x0040, 0x16f8: 0x0040, 0x16f9: 0x0040, 0x16fa: 0x0040, 0x16fb: 0x0040,
+ 0x16fc: 0x0040, 0x16fd: 0x0040, 0x16fe: 0x0040, 0x16ff: 0x0040,
+ // Block 0x5c, offset 0x1700
+ 0x1700: 0x0208, 0x1701: 0x0408, 0x1702: 0x0208, 0x1703: 0x0408, 0x1704: 0x0408, 0x1705: 0x0408,
+ 0x1706: 0x0208, 0x1707: 0x0208, 0x1708: 0x0208, 0x1709: 0x0408, 0x170a: 0x0208, 0x170b: 0x0208,
+ 0x170c: 0x0408, 0x170d: 0x0208, 0x170e: 0x0408, 0x170f: 0x0408, 0x1710: 0x0208, 0x1711: 0x0408,
+ 0x1712: 0x0040, 0x1713: 0x0040, 0x1714: 0x0040, 0x1715: 0x0040, 0x1716: 0x0040, 0x1717: 0x0040,
+ 0x1718: 0x0040, 0x1719: 0x0018, 0x171a: 0x0018, 0x171b: 0x0018, 0x171c: 0x0018, 0x171d: 0x0040,
+ 0x171e: 0x0040, 0x171f: 0x0040, 0x1720: 0x0040, 0x1721: 0x0040, 0x1722: 0x0040, 0x1723: 0x0040,
+ 0x1724: 0x0040, 0x1725: 0x0040, 0x1726: 0x0040, 0x1727: 0x0040, 0x1728: 0x0040, 0x1729: 0x0418,
+ 0x172a: 0x0418, 0x172b: 0x0418, 0x172c: 0x0418, 0x172d: 0x0218, 0x172e: 0x0218, 0x172f: 0x0018,
+ 0x1730: 0x0040, 0x1731: 0x0040, 0x1732: 0x0040, 0x1733: 0x0040, 0x1734: 0x0040, 0x1735: 0x0040,
+ 0x1736: 0x0040, 0x1737: 0x0040, 0x1738: 0x0040, 0x1739: 0x0040, 0x173a: 0x0040, 0x173b: 0x0040,
+ 0x173c: 0x0040, 0x173d: 0x0040, 0x173e: 0x0040, 0x173f: 0x0040,
+ // Block 0x5d, offset 0x1740
+ 0x1740: 0x1308, 0x1741: 0x1308, 0x1742: 0x1008, 0x1743: 0x1008, 0x1744: 0x0040, 0x1745: 0x0008,
+ 0x1746: 0x0008, 0x1747: 0x0008, 0x1748: 0x0008, 0x1749: 0x0008, 0x174a: 0x0008, 0x174b: 0x0008,
+ 0x174c: 0x0008, 0x174d: 0x0040, 0x174e: 0x0040, 0x174f: 0x0008, 0x1750: 0x0008, 0x1751: 0x0040,
+ 0x1752: 0x0040, 0x1753: 0x0008, 0x1754: 0x0008, 0x1755: 0x0008, 0x1756: 0x0008, 0x1757: 0x0008,
+ 0x1758: 0x0008, 0x1759: 0x0008, 0x175a: 0x0008, 0x175b: 0x0008, 0x175c: 0x0008, 0x175d: 0x0008,
+ 0x175e: 0x0008, 0x175f: 0x0008, 0x1760: 0x0008, 0x1761: 0x0008, 0x1762: 0x0008, 0x1763: 0x0008,
+ 0x1764: 0x0008, 0x1765: 0x0008, 0x1766: 0x0008, 0x1767: 0x0008, 0x1768: 0x0008, 0x1769: 0x0040,
+ 0x176a: 0x0008, 0x176b: 0x0008, 0x176c: 0x0008, 0x176d: 0x0008, 0x176e: 0x0008, 0x176f: 0x0008,
+ 0x1770: 0x0008, 0x1771: 0x0040, 0x1772: 0x0008, 0x1773: 0x0008, 0x1774: 0x0040, 0x1775: 0x0008,
+ 0x1776: 0x0008, 0x1777: 0x0008, 0x1778: 0x0008, 0x1779: 0x0008, 0x177a: 0x0040, 0x177b: 0x0040,
+ 0x177c: 0x1308, 0x177d: 0x0008, 0x177e: 0x1008, 0x177f: 0x1008,
+ // Block 0x5e, offset 0x1780
+ 0x1780: 0x1308, 0x1781: 0x1008, 0x1782: 0x1008, 0x1783: 0x1008, 0x1784: 0x1008, 0x1785: 0x0040,
+ 0x1786: 0x0040, 0x1787: 0x1008, 0x1788: 0x1008, 0x1789: 0x0040, 0x178a: 0x0040, 0x178b: 0x1008,
+ 0x178c: 0x1008, 0x178d: 0x1808, 0x178e: 0x0040, 0x178f: 0x0040, 0x1790: 0x0008, 0x1791: 0x0040,
+ 0x1792: 0x0040, 0x1793: 0x0040, 0x1794: 0x0040, 0x1795: 0x0040, 0x1796: 0x0040, 0x1797: 0x1008,
+ 0x1798: 0x0040, 0x1799: 0x0040, 0x179a: 0x0040, 0x179b: 0x0040, 0x179c: 0x0040, 0x179d: 0x0008,
+ 0x179e: 0x0008, 0x179f: 0x0008, 0x17a0: 0x0008, 0x17a1: 0x0008, 0x17a2: 0x1008, 0x17a3: 0x1008,
+ 0x17a4: 0x0040, 0x17a5: 0x0040, 0x17a6: 0x1308, 0x17a7: 0x1308, 0x17a8: 0x1308, 0x17a9: 0x1308,
+ 0x17aa: 0x1308, 0x17ab: 0x1308, 0x17ac: 0x1308, 0x17ad: 0x0040, 0x17ae: 0x0040, 0x17af: 0x0040,
+ 0x17b0: 0x1308, 0x17b1: 0x1308, 0x17b2: 0x1308, 0x17b3: 0x1308, 0x17b4: 0x1308, 0x17b5: 0x0040,
+ 0x17b6: 0x0040, 0x17b7: 0x0040, 0x17b8: 0x0040, 0x17b9: 0x0040, 0x17ba: 0x0040, 0x17bb: 0x0040,
+ 0x17bc: 0x0040, 0x17bd: 0x0040, 0x17be: 0x0040, 0x17bf: 0x0040,
+ // Block 0x5f, offset 0x17c0
+ 0x17c0: 0x0039, 0x17c1: 0x0ee9, 0x17c2: 0x1159, 0x17c3: 0x0ef9, 0x17c4: 0x0f09, 0x17c5: 0x1199,
+ 0x17c6: 0x0f31, 0x17c7: 0x0249, 0x17c8: 0x0f41, 0x17c9: 0x0259, 0x17ca: 0x0f51, 0x17cb: 0x0359,
+ 0x17cc: 0x0f61, 0x17cd: 0x0f71, 0x17ce: 0x00d9, 0x17cf: 0x0f99, 0x17d0: 0x2039, 0x17d1: 0x0269,
+ 0x17d2: 0x01d9, 0x17d3: 0x0fa9, 0x17d4: 0x0fb9, 0x17d5: 0x1089, 0x17d6: 0x0279, 0x17d7: 0x0369,
+ 0x17d8: 0x0289, 0x17d9: 0x13d1, 0x17da: 0x0039, 0x17db: 0x0ee9, 0x17dc: 0x1159, 0x17dd: 0x0ef9,
+ 0x17de: 0x0f09, 0x17df: 0x1199, 0x17e0: 0x0f31, 0x17e1: 0x0249, 0x17e2: 0x0f41, 0x17e3: 0x0259,
+ 0x17e4: 0x0f51, 0x17e5: 0x0359, 0x17e6: 0x0f61, 0x17e7: 0x0f71, 0x17e8: 0x00d9, 0x17e9: 0x0f99,
+ 0x17ea: 0x2039, 0x17eb: 0x0269, 0x17ec: 0x01d9, 0x17ed: 0x0fa9, 0x17ee: 0x0fb9, 0x17ef: 0x1089,
+ 0x17f0: 0x0279, 0x17f1: 0x0369, 0x17f2: 0x0289, 0x17f3: 0x13d1, 0x17f4: 0x0039, 0x17f5: 0x0ee9,
+ 0x17f6: 0x1159, 0x17f7: 0x0ef9, 0x17f8: 0x0f09, 0x17f9: 0x1199, 0x17fa: 0x0f31, 0x17fb: 0x0249,
+ 0x17fc: 0x0f41, 0x17fd: 0x0259, 0x17fe: 0x0f51, 0x17ff: 0x0359,
+ // Block 0x60, offset 0x1800
+ 0x1800: 0x0f61, 0x1801: 0x0f71, 0x1802: 0x00d9, 0x1803: 0x0f99, 0x1804: 0x2039, 0x1805: 0x0269,
+ 0x1806: 0x01d9, 0x1807: 0x0fa9, 0x1808: 0x0fb9, 0x1809: 0x1089, 0x180a: 0x0279, 0x180b: 0x0369,
+ 0x180c: 0x0289, 0x180d: 0x13d1, 0x180e: 0x0039, 0x180f: 0x0ee9, 0x1810: 0x1159, 0x1811: 0x0ef9,
+ 0x1812: 0x0f09, 0x1813: 0x1199, 0x1814: 0x0f31, 0x1815: 0x0040, 0x1816: 0x0f41, 0x1817: 0x0259,
+ 0x1818: 0x0f51, 0x1819: 0x0359, 0x181a: 0x0f61, 0x181b: 0x0f71, 0x181c: 0x00d9, 0x181d: 0x0f99,
+ 0x181e: 0x2039, 0x181f: 0x0269, 0x1820: 0x01d9, 0x1821: 0x0fa9, 0x1822: 0x0fb9, 0x1823: 0x1089,
+ 0x1824: 0x0279, 0x1825: 0x0369, 0x1826: 0x0289, 0x1827: 0x13d1, 0x1828: 0x0039, 0x1829: 0x0ee9,
+ 0x182a: 0x1159, 0x182b: 0x0ef9, 0x182c: 0x0f09, 0x182d: 0x1199, 0x182e: 0x0f31, 0x182f: 0x0249,
+ 0x1830: 0x0f41, 0x1831: 0x0259, 0x1832: 0x0f51, 0x1833: 0x0359, 0x1834: 0x0f61, 0x1835: 0x0f71,
+ 0x1836: 0x00d9, 0x1837: 0x0f99, 0x1838: 0x2039, 0x1839: 0x0269, 0x183a: 0x01d9, 0x183b: 0x0fa9,
+ 0x183c: 0x0fb9, 0x183d: 0x1089, 0x183e: 0x0279, 0x183f: 0x0369,
+ // Block 0x61, offset 0x1840
+ 0x1840: 0x0289, 0x1841: 0x13d1, 0x1842: 0x0039, 0x1843: 0x0ee9, 0x1844: 0x1159, 0x1845: 0x0ef9,
+ 0x1846: 0x0f09, 0x1847: 0x1199, 0x1848: 0x0f31, 0x1849: 0x0249, 0x184a: 0x0f41, 0x184b: 0x0259,
+ 0x184c: 0x0f51, 0x184d: 0x0359, 0x184e: 0x0f61, 0x184f: 0x0f71, 0x1850: 0x00d9, 0x1851: 0x0f99,
+ 0x1852: 0x2039, 0x1853: 0x0269, 0x1854: 0x01d9, 0x1855: 0x0fa9, 0x1856: 0x0fb9, 0x1857: 0x1089,
+ 0x1858: 0x0279, 0x1859: 0x0369, 0x185a: 0x0289, 0x185b: 0x13d1, 0x185c: 0x0039, 0x185d: 0x0040,
+ 0x185e: 0x1159, 0x185f: 0x0ef9, 0x1860: 0x0040, 0x1861: 0x0040, 0x1862: 0x0f31, 0x1863: 0x0040,
+ 0x1864: 0x0040, 0x1865: 0x0259, 0x1866: 0x0f51, 0x1867: 0x0040, 0x1868: 0x0040, 0x1869: 0x0f71,
+ 0x186a: 0x00d9, 0x186b: 0x0f99, 0x186c: 0x2039, 0x186d: 0x0040, 0x186e: 0x01d9, 0x186f: 0x0fa9,
+ 0x1870: 0x0fb9, 0x1871: 0x1089, 0x1872: 0x0279, 0x1873: 0x0369, 0x1874: 0x0289, 0x1875: 0x13d1,
+ 0x1876: 0x0039, 0x1877: 0x0ee9, 0x1878: 0x1159, 0x1879: 0x0ef9, 0x187a: 0x0040, 0x187b: 0x1199,
+ 0x187c: 0x0040, 0x187d: 0x0249, 0x187e: 0x0f41, 0x187f: 0x0259,
+ // Block 0x62, offset 0x1880
+ 0x1880: 0x0f51, 0x1881: 0x0359, 0x1882: 0x0f61, 0x1883: 0x0f71, 0x1884: 0x0040, 0x1885: 0x0f99,
+ 0x1886: 0x2039, 0x1887: 0x0269, 0x1888: 0x01d9, 0x1889: 0x0fa9, 0x188a: 0x0fb9, 0x188b: 0x1089,
+ 0x188c: 0x0279, 0x188d: 0x0369, 0x188e: 0x0289, 0x188f: 0x13d1, 0x1890: 0x0039, 0x1891: 0x0ee9,
+ 0x1892: 0x1159, 0x1893: 0x0ef9, 0x1894: 0x0f09, 0x1895: 0x1199, 0x1896: 0x0f31, 0x1897: 0x0249,
+ 0x1898: 0x0f41, 0x1899: 0x0259, 0x189a: 0x0f51, 0x189b: 0x0359, 0x189c: 0x0f61, 0x189d: 0x0f71,
+ 0x189e: 0x00d9, 0x189f: 0x0f99, 0x18a0: 0x2039, 0x18a1: 0x0269, 0x18a2: 0x01d9, 0x18a3: 0x0fa9,
+ 0x18a4: 0x0fb9, 0x18a5: 0x1089, 0x18a6: 0x0279, 0x18a7: 0x0369, 0x18a8: 0x0289, 0x18a9: 0x13d1,
+ 0x18aa: 0x0039, 0x18ab: 0x0ee9, 0x18ac: 0x1159, 0x18ad: 0x0ef9, 0x18ae: 0x0f09, 0x18af: 0x1199,
+ 0x18b0: 0x0f31, 0x18b1: 0x0249, 0x18b2: 0x0f41, 0x18b3: 0x0259, 0x18b4: 0x0f51, 0x18b5: 0x0359,
+ 0x18b6: 0x0f61, 0x18b7: 0x0f71, 0x18b8: 0x00d9, 0x18b9: 0x0f99, 0x18ba: 0x2039, 0x18bb: 0x0269,
+ 0x18bc: 0x01d9, 0x18bd: 0x0fa9, 0x18be: 0x0fb9, 0x18bf: 0x1089,
+ // Block 0x63, offset 0x18c0
+ 0x18c0: 0x0279, 0x18c1: 0x0369, 0x18c2: 0x0289, 0x18c3: 0x13d1, 0x18c4: 0x0039, 0x18c5: 0x0ee9,
+ 0x18c6: 0x0040, 0x18c7: 0x0ef9, 0x18c8: 0x0f09, 0x18c9: 0x1199, 0x18ca: 0x0f31, 0x18cb: 0x0040,
+ 0x18cc: 0x0040, 0x18cd: 0x0259, 0x18ce: 0x0f51, 0x18cf: 0x0359, 0x18d0: 0x0f61, 0x18d1: 0x0f71,
+ 0x18d2: 0x00d9, 0x18d3: 0x0f99, 0x18d4: 0x2039, 0x18d5: 0x0040, 0x18d6: 0x01d9, 0x18d7: 0x0fa9,
+ 0x18d8: 0x0fb9, 0x18d9: 0x1089, 0x18da: 0x0279, 0x18db: 0x0369, 0x18dc: 0x0289, 0x18dd: 0x0040,
+ 0x18de: 0x0039, 0x18df: 0x0ee9, 0x18e0: 0x1159, 0x18e1: 0x0ef9, 0x18e2: 0x0f09, 0x18e3: 0x1199,
+ 0x18e4: 0x0f31, 0x18e5: 0x0249, 0x18e6: 0x0f41, 0x18e7: 0x0259, 0x18e8: 0x0f51, 0x18e9: 0x0359,
+ 0x18ea: 0x0f61, 0x18eb: 0x0f71, 0x18ec: 0x00d9, 0x18ed: 0x0f99, 0x18ee: 0x2039, 0x18ef: 0x0269,
+ 0x18f0: 0x01d9, 0x18f1: 0x0fa9, 0x18f2: 0x0fb9, 0x18f3: 0x1089, 0x18f4: 0x0279, 0x18f5: 0x0369,
+ 0x18f6: 0x0289, 0x18f7: 0x13d1, 0x18f8: 0x0039, 0x18f9: 0x0ee9, 0x18fa: 0x0040, 0x18fb: 0x0ef9,
+ 0x18fc: 0x0f09, 0x18fd: 0x1199, 0x18fe: 0x0f31, 0x18ff: 0x0040,
+ // Block 0x64, offset 0x1900
+ 0x1900: 0x0f41, 0x1901: 0x0259, 0x1902: 0x0f51, 0x1903: 0x0359, 0x1904: 0x0f61, 0x1905: 0x0040,
+ 0x1906: 0x00d9, 0x1907: 0x0040, 0x1908: 0x0040, 0x1909: 0x0040, 0x190a: 0x01d9, 0x190b: 0x0fa9,
+ 0x190c: 0x0fb9, 0x190d: 0x1089, 0x190e: 0x0279, 0x190f: 0x0369, 0x1910: 0x0289, 0x1911: 0x0040,
+ 0x1912: 0x0039, 0x1913: 0x0ee9, 0x1914: 0x1159, 0x1915: 0x0ef9, 0x1916: 0x0f09, 0x1917: 0x1199,
+ 0x1918: 0x0f31, 0x1919: 0x0249, 0x191a: 0x0f41, 0x191b: 0x0259, 0x191c: 0x0f51, 0x191d: 0x0359,
+ 0x191e: 0x0f61, 0x191f: 0x0f71, 0x1920: 0x00d9, 0x1921: 0x0f99, 0x1922: 0x2039, 0x1923: 0x0269,
+ 0x1924: 0x01d9, 0x1925: 0x0fa9, 0x1926: 0x0fb9, 0x1927: 0x1089, 0x1928: 0x0279, 0x1929: 0x0369,
+ 0x192a: 0x0289, 0x192b: 0x13d1, 0x192c: 0x0039, 0x192d: 0x0ee9, 0x192e: 0x1159, 0x192f: 0x0ef9,
+ 0x1930: 0x0f09, 0x1931: 0x1199, 0x1932: 0x0f31, 0x1933: 0x0249, 0x1934: 0x0f41, 0x1935: 0x0259,
+ 0x1936: 0x0f51, 0x1937: 0x0359, 0x1938: 0x0f61, 0x1939: 0x0f71, 0x193a: 0x00d9, 0x193b: 0x0f99,
+ 0x193c: 0x2039, 0x193d: 0x0269, 0x193e: 0x01d9, 0x193f: 0x0fa9,
+ // Block 0x65, offset 0x1940
+ 0x1940: 0x0fb9, 0x1941: 0x1089, 0x1942: 0x0279, 0x1943: 0x0369, 0x1944: 0x0289, 0x1945: 0x13d1,
+ 0x1946: 0x0039, 0x1947: 0x0ee9, 0x1948: 0x1159, 0x1949: 0x0ef9, 0x194a: 0x0f09, 0x194b: 0x1199,
+ 0x194c: 0x0f31, 0x194d: 0x0249, 0x194e: 0x0f41, 0x194f: 0x0259, 0x1950: 0x0f51, 0x1951: 0x0359,
+ 0x1952: 0x0f61, 0x1953: 0x0f71, 0x1954: 0x00d9, 0x1955: 0x0f99, 0x1956: 0x2039, 0x1957: 0x0269,
+ 0x1958: 0x01d9, 0x1959: 0x0fa9, 0x195a: 0x0fb9, 0x195b: 0x1089, 0x195c: 0x0279, 0x195d: 0x0369,
+ 0x195e: 0x0289, 0x195f: 0x13d1, 0x1960: 0x0039, 0x1961: 0x0ee9, 0x1962: 0x1159, 0x1963: 0x0ef9,
+ 0x1964: 0x0f09, 0x1965: 0x1199, 0x1966: 0x0f31, 0x1967: 0x0249, 0x1968: 0x0f41, 0x1969: 0x0259,
+ 0x196a: 0x0f51, 0x196b: 0x0359, 0x196c: 0x0f61, 0x196d: 0x0f71, 0x196e: 0x00d9, 0x196f: 0x0f99,
+ 0x1970: 0x2039, 0x1971: 0x0269, 0x1972: 0x01d9, 0x1973: 0x0fa9, 0x1974: 0x0fb9, 0x1975: 0x1089,
+ 0x1976: 0x0279, 0x1977: 0x0369, 0x1978: 0x0289, 0x1979: 0x13d1, 0x197a: 0x0039, 0x197b: 0x0ee9,
+ 0x197c: 0x1159, 0x197d: 0x0ef9, 0x197e: 0x0f09, 0x197f: 0x1199,
+ // Block 0x66, offset 0x1980
+ 0x1980: 0x0f31, 0x1981: 0x0249, 0x1982: 0x0f41, 0x1983: 0x0259, 0x1984: 0x0f51, 0x1985: 0x0359,
+ 0x1986: 0x0f61, 0x1987: 0x0f71, 0x1988: 0x00d9, 0x1989: 0x0f99, 0x198a: 0x2039, 0x198b: 0x0269,
+ 0x198c: 0x01d9, 0x198d: 0x0fa9, 0x198e: 0x0fb9, 0x198f: 0x1089, 0x1990: 0x0279, 0x1991: 0x0369,
+ 0x1992: 0x0289, 0x1993: 0x13d1, 0x1994: 0x0039, 0x1995: 0x0ee9, 0x1996: 0x1159, 0x1997: 0x0ef9,
+ 0x1998: 0x0f09, 0x1999: 0x1199, 0x199a: 0x0f31, 0x199b: 0x0249, 0x199c: 0x0f41, 0x199d: 0x0259,
+ 0x199e: 0x0f51, 0x199f: 0x0359, 0x19a0: 0x0f61, 0x19a1: 0x0f71, 0x19a2: 0x00d9, 0x19a3: 0x0f99,
+ 0x19a4: 0x2039, 0x19a5: 0x0269, 0x19a6: 0x01d9, 0x19a7: 0x0fa9, 0x19a8: 0x0fb9, 0x19a9: 0x1089,
+ 0x19aa: 0x0279, 0x19ab: 0x0369, 0x19ac: 0x0289, 0x19ad: 0x13d1, 0x19ae: 0x0039, 0x19af: 0x0ee9,
+ 0x19b0: 0x1159, 0x19b1: 0x0ef9, 0x19b2: 0x0f09, 0x19b3: 0x1199, 0x19b4: 0x0f31, 0x19b5: 0x0249,
+ 0x19b6: 0x0f41, 0x19b7: 0x0259, 0x19b8: 0x0f51, 0x19b9: 0x0359, 0x19ba: 0x0f61, 0x19bb: 0x0f71,
+ 0x19bc: 0x00d9, 0x19bd: 0x0f99, 0x19be: 0x2039, 0x19bf: 0x0269,
+ // Block 0x67, offset 0x19c0
+ 0x19c0: 0x01d9, 0x19c1: 0x0fa9, 0x19c2: 0x0fb9, 0x19c3: 0x1089, 0x19c4: 0x0279, 0x19c5: 0x0369,
+ 0x19c6: 0x0289, 0x19c7: 0x13d1, 0x19c8: 0x0039, 0x19c9: 0x0ee9, 0x19ca: 0x1159, 0x19cb: 0x0ef9,
+ 0x19cc: 0x0f09, 0x19cd: 0x1199, 0x19ce: 0x0f31, 0x19cf: 0x0249, 0x19d0: 0x0f41, 0x19d1: 0x0259,
+ 0x19d2: 0x0f51, 0x19d3: 0x0359, 0x19d4: 0x0f61, 0x19d5: 0x0f71, 0x19d6: 0x00d9, 0x19d7: 0x0f99,
+ 0x19d8: 0x2039, 0x19d9: 0x0269, 0x19da: 0x01d9, 0x19db: 0x0fa9, 0x19dc: 0x0fb9, 0x19dd: 0x1089,
+ 0x19de: 0x0279, 0x19df: 0x0369, 0x19e0: 0x0289, 0x19e1: 0x13d1, 0x19e2: 0x0039, 0x19e3: 0x0ee9,
+ 0x19e4: 0x1159, 0x19e5: 0x0ef9, 0x19e6: 0x0f09, 0x19e7: 0x1199, 0x19e8: 0x0f31, 0x19e9: 0x0249,
+ 0x19ea: 0x0f41, 0x19eb: 0x0259, 0x19ec: 0x0f51, 0x19ed: 0x0359, 0x19ee: 0x0f61, 0x19ef: 0x0f71,
+ 0x19f0: 0x00d9, 0x19f1: 0x0f99, 0x19f2: 0x2039, 0x19f3: 0x0269, 0x19f4: 0x01d9, 0x19f5: 0x0fa9,
+ 0x19f6: 0x0fb9, 0x19f7: 0x1089, 0x19f8: 0x0279, 0x19f9: 0x0369, 0x19fa: 0x0289, 0x19fb: 0x13d1,
+ 0x19fc: 0x0039, 0x19fd: 0x0ee9, 0x19fe: 0x1159, 0x19ff: 0x0ef9,
+ // Block 0x68, offset 0x1a00
+ 0x1a00: 0x0f09, 0x1a01: 0x1199, 0x1a02: 0x0f31, 0x1a03: 0x0249, 0x1a04: 0x0f41, 0x1a05: 0x0259,
+ 0x1a06: 0x0f51, 0x1a07: 0x0359, 0x1a08: 0x0f61, 0x1a09: 0x0f71, 0x1a0a: 0x00d9, 0x1a0b: 0x0f99,
+ 0x1a0c: 0x2039, 0x1a0d: 0x0269, 0x1a0e: 0x01d9, 0x1a0f: 0x0fa9, 0x1a10: 0x0fb9, 0x1a11: 0x1089,
+ 0x1a12: 0x0279, 0x1a13: 0x0369, 0x1a14: 0x0289, 0x1a15: 0x13d1, 0x1a16: 0x0039, 0x1a17: 0x0ee9,
+ 0x1a18: 0x1159, 0x1a19: 0x0ef9, 0x1a1a: 0x0f09, 0x1a1b: 0x1199, 0x1a1c: 0x0f31, 0x1a1d: 0x0249,
+ 0x1a1e: 0x0f41, 0x1a1f: 0x0259, 0x1a20: 0x0f51, 0x1a21: 0x0359, 0x1a22: 0x0f61, 0x1a23: 0x0f71,
+ 0x1a24: 0x00d9, 0x1a25: 0x0f99, 0x1a26: 0x2039, 0x1a27: 0x0269, 0x1a28: 0x01d9, 0x1a29: 0x0fa9,
+ 0x1a2a: 0x0fb9, 0x1a2b: 0x1089, 0x1a2c: 0x0279, 0x1a2d: 0x0369, 0x1a2e: 0x0289, 0x1a2f: 0x13d1,
+ 0x1a30: 0x0039, 0x1a31: 0x0ee9, 0x1a32: 0x1159, 0x1a33: 0x0ef9, 0x1a34: 0x0f09, 0x1a35: 0x1199,
+ 0x1a36: 0x0f31, 0x1a37: 0x0249, 0x1a38: 0x0f41, 0x1a39: 0x0259, 0x1a3a: 0x0f51, 0x1a3b: 0x0359,
+ 0x1a3c: 0x0f61, 0x1a3d: 0x0f71, 0x1a3e: 0x00d9, 0x1a3f: 0x0f99,
+ // Block 0x69, offset 0x1a40
+ 0x1a40: 0x2039, 0x1a41: 0x0269, 0x1a42: 0x01d9, 0x1a43: 0x0fa9, 0x1a44: 0x0fb9, 0x1a45: 0x1089,
+ 0x1a46: 0x0279, 0x1a47: 0x0369, 0x1a48: 0x0289, 0x1a49: 0x13d1, 0x1a4a: 0x0039, 0x1a4b: 0x0ee9,
+ 0x1a4c: 0x1159, 0x1a4d: 0x0ef9, 0x1a4e: 0x0f09, 0x1a4f: 0x1199, 0x1a50: 0x0f31, 0x1a51: 0x0249,
+ 0x1a52: 0x0f41, 0x1a53: 0x0259, 0x1a54: 0x0f51, 0x1a55: 0x0359, 0x1a56: 0x0f61, 0x1a57: 0x0f71,
+ 0x1a58: 0x00d9, 0x1a59: 0x0f99, 0x1a5a: 0x2039, 0x1a5b: 0x0269, 0x1a5c: 0x01d9, 0x1a5d: 0x0fa9,
+ 0x1a5e: 0x0fb9, 0x1a5f: 0x1089, 0x1a60: 0x0279, 0x1a61: 0x0369, 0x1a62: 0x0289, 0x1a63: 0x13d1,
+ 0x1a64: 0xba81, 0x1a65: 0xba99, 0x1a66: 0x0040, 0x1a67: 0x0040, 0x1a68: 0xbab1, 0x1a69: 0x1099,
+ 0x1a6a: 0x10b1, 0x1a6b: 0x10c9, 0x1a6c: 0xbac9, 0x1a6d: 0xbae1, 0x1a6e: 0xbaf9, 0x1a6f: 0x1429,
+ 0x1a70: 0x1a31, 0x1a71: 0xbb11, 0x1a72: 0xbb29, 0x1a73: 0xbb41, 0x1a74: 0xbb59, 0x1a75: 0xbb71,
+ 0x1a76: 0xbb89, 0x1a77: 0x2109, 0x1a78: 0x1111, 0x1a79: 0x1429, 0x1a7a: 0xbba1, 0x1a7b: 0xbbb9,
+ 0x1a7c: 0xbbd1, 0x1a7d: 0x10e1, 0x1a7e: 0x10f9, 0x1a7f: 0xbbe9,
+ // Block 0x6a, offset 0x1a80
+ 0x1a80: 0x2079, 0x1a81: 0xbc01, 0x1a82: 0xbab1, 0x1a83: 0x1099, 0x1a84: 0x10b1, 0x1a85: 0x10c9,
+ 0x1a86: 0xbac9, 0x1a87: 0xbae1, 0x1a88: 0xbaf9, 0x1a89: 0x1429, 0x1a8a: 0x1a31, 0x1a8b: 0xbb11,
+ 0x1a8c: 0xbb29, 0x1a8d: 0xbb41, 0x1a8e: 0xbb59, 0x1a8f: 0xbb71, 0x1a90: 0xbb89, 0x1a91: 0x2109,
+ 0x1a92: 0x1111, 0x1a93: 0xbba1, 0x1a94: 0xbba1, 0x1a95: 0xbbb9, 0x1a96: 0xbbd1, 0x1a97: 0x10e1,
+ 0x1a98: 0x10f9, 0x1a99: 0xbbe9, 0x1a9a: 0x2079, 0x1a9b: 0xbc21, 0x1a9c: 0xbac9, 0x1a9d: 0x1429,
+ 0x1a9e: 0xbb11, 0x1a9f: 0x10e1, 0x1aa0: 0x1111, 0x1aa1: 0x2109, 0x1aa2: 0xbab1, 0x1aa3: 0x1099,
+ 0x1aa4: 0x10b1, 0x1aa5: 0x10c9, 0x1aa6: 0xbac9, 0x1aa7: 0xbae1, 0x1aa8: 0xbaf9, 0x1aa9: 0x1429,
+ 0x1aaa: 0x1a31, 0x1aab: 0xbb11, 0x1aac: 0xbb29, 0x1aad: 0xbb41, 0x1aae: 0xbb59, 0x1aaf: 0xbb71,
+ 0x1ab0: 0xbb89, 0x1ab1: 0x2109, 0x1ab2: 0x1111, 0x1ab3: 0x1429, 0x1ab4: 0xbba1, 0x1ab5: 0xbbb9,
+ 0x1ab6: 0xbbd1, 0x1ab7: 0x10e1, 0x1ab8: 0x10f9, 0x1ab9: 0xbbe9, 0x1aba: 0x2079, 0x1abb: 0xbc01,
+ 0x1abc: 0xbab1, 0x1abd: 0x1099, 0x1abe: 0x10b1, 0x1abf: 0x10c9,
+ // Block 0x6b, offset 0x1ac0
+ 0x1ac0: 0xbac9, 0x1ac1: 0xbae1, 0x1ac2: 0xbaf9, 0x1ac3: 0x1429, 0x1ac4: 0x1a31, 0x1ac5: 0xbb11,
+ 0x1ac6: 0xbb29, 0x1ac7: 0xbb41, 0x1ac8: 0xbb59, 0x1ac9: 0xbb71, 0x1aca: 0xbb89, 0x1acb: 0x2109,
+ 0x1acc: 0x1111, 0x1acd: 0xbba1, 0x1ace: 0xbba1, 0x1acf: 0xbbb9, 0x1ad0: 0xbbd1, 0x1ad1: 0x10e1,
+ 0x1ad2: 0x10f9, 0x1ad3: 0xbbe9, 0x1ad4: 0x2079, 0x1ad5: 0xbc21, 0x1ad6: 0xbac9, 0x1ad7: 0x1429,
+ 0x1ad8: 0xbb11, 0x1ad9: 0x10e1, 0x1ada: 0x1111, 0x1adb: 0x2109, 0x1adc: 0xbab1, 0x1add: 0x1099,
+ 0x1ade: 0x10b1, 0x1adf: 0x10c9, 0x1ae0: 0xbac9, 0x1ae1: 0xbae1, 0x1ae2: 0xbaf9, 0x1ae3: 0x1429,
+ 0x1ae4: 0x1a31, 0x1ae5: 0xbb11, 0x1ae6: 0xbb29, 0x1ae7: 0xbb41, 0x1ae8: 0xbb59, 0x1ae9: 0xbb71,
+ 0x1aea: 0xbb89, 0x1aeb: 0x2109, 0x1aec: 0x1111, 0x1aed: 0x1429, 0x1aee: 0xbba1, 0x1aef: 0xbbb9,
+ 0x1af0: 0xbbd1, 0x1af1: 0x10e1, 0x1af2: 0x10f9, 0x1af3: 0xbbe9, 0x1af4: 0x2079, 0x1af5: 0xbc01,
+ 0x1af6: 0xbab1, 0x1af7: 0x1099, 0x1af8: 0x10b1, 0x1af9: 0x10c9, 0x1afa: 0xbac9, 0x1afb: 0xbae1,
+ 0x1afc: 0xbaf9, 0x1afd: 0x1429, 0x1afe: 0x1a31, 0x1aff: 0xbb11,
+ // Block 0x6c, offset 0x1b00
+ 0x1b00: 0xbb29, 0x1b01: 0xbb41, 0x1b02: 0xbb59, 0x1b03: 0xbb71, 0x1b04: 0xbb89, 0x1b05: 0x2109,
+ 0x1b06: 0x1111, 0x1b07: 0xbba1, 0x1b08: 0xbba1, 0x1b09: 0xbbb9, 0x1b0a: 0xbbd1, 0x1b0b: 0x10e1,
+ 0x1b0c: 0x10f9, 0x1b0d: 0xbbe9, 0x1b0e: 0x2079, 0x1b0f: 0xbc21, 0x1b10: 0xbac9, 0x1b11: 0x1429,
+ 0x1b12: 0xbb11, 0x1b13: 0x10e1, 0x1b14: 0x1111, 0x1b15: 0x2109, 0x1b16: 0xbab1, 0x1b17: 0x1099,
+ 0x1b18: 0x10b1, 0x1b19: 0x10c9, 0x1b1a: 0xbac9, 0x1b1b: 0xbae1, 0x1b1c: 0xbaf9, 0x1b1d: 0x1429,
+ 0x1b1e: 0x1a31, 0x1b1f: 0xbb11, 0x1b20: 0xbb29, 0x1b21: 0xbb41, 0x1b22: 0xbb59, 0x1b23: 0xbb71,
+ 0x1b24: 0xbb89, 0x1b25: 0x2109, 0x1b26: 0x1111, 0x1b27: 0x1429, 0x1b28: 0xbba1, 0x1b29: 0xbbb9,
+ 0x1b2a: 0xbbd1, 0x1b2b: 0x10e1, 0x1b2c: 0x10f9, 0x1b2d: 0xbbe9, 0x1b2e: 0x2079, 0x1b2f: 0xbc01,
+ 0x1b30: 0xbab1, 0x1b31: 0x1099, 0x1b32: 0x10b1, 0x1b33: 0x10c9, 0x1b34: 0xbac9, 0x1b35: 0xbae1,
+ 0x1b36: 0xbaf9, 0x1b37: 0x1429, 0x1b38: 0x1a31, 0x1b39: 0xbb11, 0x1b3a: 0xbb29, 0x1b3b: 0xbb41,
+ 0x1b3c: 0xbb59, 0x1b3d: 0xbb71, 0x1b3e: 0xbb89, 0x1b3f: 0x2109,
+ // Block 0x6d, offset 0x1b40
+ 0x1b40: 0x1111, 0x1b41: 0xbba1, 0x1b42: 0xbba1, 0x1b43: 0xbbb9, 0x1b44: 0xbbd1, 0x1b45: 0x10e1,
+ 0x1b46: 0x10f9, 0x1b47: 0xbbe9, 0x1b48: 0x2079, 0x1b49: 0xbc21, 0x1b4a: 0xbac9, 0x1b4b: 0x1429,
+ 0x1b4c: 0xbb11, 0x1b4d: 0x10e1, 0x1b4e: 0x1111, 0x1b4f: 0x2109, 0x1b50: 0xbab1, 0x1b51: 0x1099,
+ 0x1b52: 0x10b1, 0x1b53: 0x10c9, 0x1b54: 0xbac9, 0x1b55: 0xbae1, 0x1b56: 0xbaf9, 0x1b57: 0x1429,
+ 0x1b58: 0x1a31, 0x1b59: 0xbb11, 0x1b5a: 0xbb29, 0x1b5b: 0xbb41, 0x1b5c: 0xbb59, 0x1b5d: 0xbb71,
+ 0x1b5e: 0xbb89, 0x1b5f: 0x2109, 0x1b60: 0x1111, 0x1b61: 0x1429, 0x1b62: 0xbba1, 0x1b63: 0xbbb9,
+ 0x1b64: 0xbbd1, 0x1b65: 0x10e1, 0x1b66: 0x10f9, 0x1b67: 0xbbe9, 0x1b68: 0x2079, 0x1b69: 0xbc01,
+ 0x1b6a: 0xbab1, 0x1b6b: 0x1099, 0x1b6c: 0x10b1, 0x1b6d: 0x10c9, 0x1b6e: 0xbac9, 0x1b6f: 0xbae1,
+ 0x1b70: 0xbaf9, 0x1b71: 0x1429, 0x1b72: 0x1a31, 0x1b73: 0xbb11, 0x1b74: 0xbb29, 0x1b75: 0xbb41,
+ 0x1b76: 0xbb59, 0x1b77: 0xbb71, 0x1b78: 0xbb89, 0x1b79: 0x2109, 0x1b7a: 0x1111, 0x1b7b: 0xbba1,
+ 0x1b7c: 0xbba1, 0x1b7d: 0xbbb9, 0x1b7e: 0xbbd1, 0x1b7f: 0x10e1,
+ // Block 0x6e, offset 0x1b80
+ 0x1b80: 0x10f9, 0x1b81: 0xbbe9, 0x1b82: 0x2079, 0x1b83: 0xbc21, 0x1b84: 0xbac9, 0x1b85: 0x1429,
+ 0x1b86: 0xbb11, 0x1b87: 0x10e1, 0x1b88: 0x1111, 0x1b89: 0x2109, 0x1b8a: 0xbc41, 0x1b8b: 0xbc41,
+ 0x1b8c: 0x0040, 0x1b8d: 0x0040, 0x1b8e: 0x1f41, 0x1b8f: 0x00c9, 0x1b90: 0x0069, 0x1b91: 0x0079,
+ 0x1b92: 0x1f51, 0x1b93: 0x1f61, 0x1b94: 0x1f71, 0x1b95: 0x1f81, 0x1b96: 0x1f91, 0x1b97: 0x1fa1,
+ 0x1b98: 0x1f41, 0x1b99: 0x00c9, 0x1b9a: 0x0069, 0x1b9b: 0x0079, 0x1b9c: 0x1f51, 0x1b9d: 0x1f61,
+ 0x1b9e: 0x1f71, 0x1b9f: 0x1f81, 0x1ba0: 0x1f91, 0x1ba1: 0x1fa1, 0x1ba2: 0x1f41, 0x1ba3: 0x00c9,
+ 0x1ba4: 0x0069, 0x1ba5: 0x0079, 0x1ba6: 0x1f51, 0x1ba7: 0x1f61, 0x1ba8: 0x1f71, 0x1ba9: 0x1f81,
+ 0x1baa: 0x1f91, 0x1bab: 0x1fa1, 0x1bac: 0x1f41, 0x1bad: 0x00c9, 0x1bae: 0x0069, 0x1baf: 0x0079,
+ 0x1bb0: 0x1f51, 0x1bb1: 0x1f61, 0x1bb2: 0x1f71, 0x1bb3: 0x1f81, 0x1bb4: 0x1f91, 0x1bb5: 0x1fa1,
+ 0x1bb6: 0x1f41, 0x1bb7: 0x00c9, 0x1bb8: 0x0069, 0x1bb9: 0x0079, 0x1bba: 0x1f51, 0x1bbb: 0x1f61,
+ 0x1bbc: 0x1f71, 0x1bbd: 0x1f81, 0x1bbe: 0x1f91, 0x1bbf: 0x1fa1,
+ // Block 0x6f, offset 0x1bc0
+ 0x1bc0: 0xe115, 0x1bc1: 0xe115, 0x1bc2: 0xe135, 0x1bc3: 0xe135, 0x1bc4: 0xe115, 0x1bc5: 0xe115,
+ 0x1bc6: 0xe175, 0x1bc7: 0xe175, 0x1bc8: 0xe115, 0x1bc9: 0xe115, 0x1bca: 0xe135, 0x1bcb: 0xe135,
+ 0x1bcc: 0xe115, 0x1bcd: 0xe115, 0x1bce: 0xe1f5, 0x1bcf: 0xe1f5, 0x1bd0: 0xe115, 0x1bd1: 0xe115,
+ 0x1bd2: 0xe135, 0x1bd3: 0xe135, 0x1bd4: 0xe115, 0x1bd5: 0xe115, 0x1bd6: 0xe175, 0x1bd7: 0xe175,
+ 0x1bd8: 0xe115, 0x1bd9: 0xe115, 0x1bda: 0xe135, 0x1bdb: 0xe135, 0x1bdc: 0xe115, 0x1bdd: 0xe115,
+ 0x1bde: 0x8b05, 0x1bdf: 0x8b05, 0x1be0: 0x04b5, 0x1be1: 0x04b5, 0x1be2: 0x0208, 0x1be3: 0x0208,
+ 0x1be4: 0x0208, 0x1be5: 0x0208, 0x1be6: 0x0208, 0x1be7: 0x0208, 0x1be8: 0x0208, 0x1be9: 0x0208,
+ 0x1bea: 0x0208, 0x1beb: 0x0208, 0x1bec: 0x0208, 0x1bed: 0x0208, 0x1bee: 0x0208, 0x1bef: 0x0208,
+ 0x1bf0: 0x0208, 0x1bf1: 0x0208, 0x1bf2: 0x0208, 0x1bf3: 0x0208, 0x1bf4: 0x0208, 0x1bf5: 0x0208,
+ 0x1bf6: 0x0208, 0x1bf7: 0x0208, 0x1bf8: 0x0208, 0x1bf9: 0x0208, 0x1bfa: 0x0208, 0x1bfb: 0x0208,
+ 0x1bfc: 0x0208, 0x1bfd: 0x0208, 0x1bfe: 0x0208, 0x1bff: 0x0208,
+ // Block 0x70, offset 0x1c00
+ 0x1c00: 0xb189, 0x1c01: 0xb1a1, 0x1c02: 0xb201, 0x1c03: 0xb249, 0x1c04: 0x0040, 0x1c05: 0xb411,
+ 0x1c06: 0xb291, 0x1c07: 0xb219, 0x1c08: 0xb309, 0x1c09: 0xb429, 0x1c0a: 0xb399, 0x1c0b: 0xb3b1,
+ 0x1c0c: 0xb3c9, 0x1c0d: 0xb3e1, 0x1c0e: 0xb2a9, 0x1c0f: 0xb339, 0x1c10: 0xb369, 0x1c11: 0xb2d9,
+ 0x1c12: 0xb381, 0x1c13: 0xb279, 0x1c14: 0xb2c1, 0x1c15: 0xb1d1, 0x1c16: 0xb1e9, 0x1c17: 0xb231,
+ 0x1c18: 0xb261, 0x1c19: 0xb2f1, 0x1c1a: 0xb321, 0x1c1b: 0xb351, 0x1c1c: 0xbc59, 0x1c1d: 0x7949,
+ 0x1c1e: 0xbc71, 0x1c1f: 0xbc89, 0x1c20: 0x0040, 0x1c21: 0xb1a1, 0x1c22: 0xb201, 0x1c23: 0x0040,
+ 0x1c24: 0xb3f9, 0x1c25: 0x0040, 0x1c26: 0x0040, 0x1c27: 0xb219, 0x1c28: 0x0040, 0x1c29: 0xb429,
+ 0x1c2a: 0xb399, 0x1c2b: 0xb3b1, 0x1c2c: 0xb3c9, 0x1c2d: 0xb3e1, 0x1c2e: 0xb2a9, 0x1c2f: 0xb339,
+ 0x1c30: 0xb369, 0x1c31: 0xb2d9, 0x1c32: 0xb381, 0x1c33: 0x0040, 0x1c34: 0xb2c1, 0x1c35: 0xb1d1,
+ 0x1c36: 0xb1e9, 0x1c37: 0xb231, 0x1c38: 0x0040, 0x1c39: 0xb2f1, 0x1c3a: 0x0040, 0x1c3b: 0xb351,
+ 0x1c3c: 0x0040, 0x1c3d: 0x0040, 0x1c3e: 0x0040, 0x1c3f: 0x0040,
+ // Block 0x71, offset 0x1c40
+ 0x1c40: 0x0040, 0x1c41: 0x0040, 0x1c42: 0xb201, 0x1c43: 0x0040, 0x1c44: 0x0040, 0x1c45: 0x0040,
+ 0x1c46: 0x0040, 0x1c47: 0xb219, 0x1c48: 0x0040, 0x1c49: 0xb429, 0x1c4a: 0x0040, 0x1c4b: 0xb3b1,
+ 0x1c4c: 0x0040, 0x1c4d: 0xb3e1, 0x1c4e: 0xb2a9, 0x1c4f: 0xb339, 0x1c50: 0x0040, 0x1c51: 0xb2d9,
+ 0x1c52: 0xb381, 0x1c53: 0x0040, 0x1c54: 0xb2c1, 0x1c55: 0x0040, 0x1c56: 0x0040, 0x1c57: 0xb231,
+ 0x1c58: 0x0040, 0x1c59: 0xb2f1, 0x1c5a: 0x0040, 0x1c5b: 0xb351, 0x1c5c: 0x0040, 0x1c5d: 0x7949,
+ 0x1c5e: 0x0040, 0x1c5f: 0xbc89, 0x1c60: 0x0040, 0x1c61: 0xb1a1, 0x1c62: 0xb201, 0x1c63: 0x0040,
+ 0x1c64: 0xb3f9, 0x1c65: 0x0040, 0x1c66: 0x0040, 0x1c67: 0xb219, 0x1c68: 0xb309, 0x1c69: 0xb429,
+ 0x1c6a: 0xb399, 0x1c6b: 0x0040, 0x1c6c: 0xb3c9, 0x1c6d: 0xb3e1, 0x1c6e: 0xb2a9, 0x1c6f: 0xb339,
+ 0x1c70: 0xb369, 0x1c71: 0xb2d9, 0x1c72: 0xb381, 0x1c73: 0x0040, 0x1c74: 0xb2c1, 0x1c75: 0xb1d1,
+ 0x1c76: 0xb1e9, 0x1c77: 0xb231, 0x1c78: 0x0040, 0x1c79: 0xb2f1, 0x1c7a: 0xb321, 0x1c7b: 0xb351,
+ 0x1c7c: 0xbc59, 0x1c7d: 0x0040, 0x1c7e: 0xbc71, 0x1c7f: 0x0040,
+ // Block 0x72, offset 0x1c80
+ 0x1c80: 0xb189, 0x1c81: 0xb1a1, 0x1c82: 0xb201, 0x1c83: 0xb249, 0x1c84: 0xb3f9, 0x1c85: 0xb411,
+ 0x1c86: 0xb291, 0x1c87: 0xb219, 0x1c88: 0xb309, 0x1c89: 0xb429, 0x1c8a: 0x0040, 0x1c8b: 0xb3b1,
+ 0x1c8c: 0xb3c9, 0x1c8d: 0xb3e1, 0x1c8e: 0xb2a9, 0x1c8f: 0xb339, 0x1c90: 0xb369, 0x1c91: 0xb2d9,
+ 0x1c92: 0xb381, 0x1c93: 0xb279, 0x1c94: 0xb2c1, 0x1c95: 0xb1d1, 0x1c96: 0xb1e9, 0x1c97: 0xb231,
+ 0x1c98: 0xb261, 0x1c99: 0xb2f1, 0x1c9a: 0xb321, 0x1c9b: 0xb351, 0x1c9c: 0x0040, 0x1c9d: 0x0040,
+ 0x1c9e: 0x0040, 0x1c9f: 0x0040, 0x1ca0: 0x0040, 0x1ca1: 0xb1a1, 0x1ca2: 0xb201, 0x1ca3: 0xb249,
+ 0x1ca4: 0x0040, 0x1ca5: 0xb411, 0x1ca6: 0xb291, 0x1ca7: 0xb219, 0x1ca8: 0xb309, 0x1ca9: 0xb429,
+ 0x1caa: 0x0040, 0x1cab: 0xb3b1, 0x1cac: 0xb3c9, 0x1cad: 0xb3e1, 0x1cae: 0xb2a9, 0x1caf: 0xb339,
+ 0x1cb0: 0xb369, 0x1cb1: 0xb2d9, 0x1cb2: 0xb381, 0x1cb3: 0xb279, 0x1cb4: 0xb2c1, 0x1cb5: 0xb1d1,
+ 0x1cb6: 0xb1e9, 0x1cb7: 0xb231, 0x1cb8: 0xb261, 0x1cb9: 0xb2f1, 0x1cba: 0xb321, 0x1cbb: 0xb351,
+ 0x1cbc: 0x0040, 0x1cbd: 0x0040, 0x1cbe: 0x0040, 0x1cbf: 0x0040,
+ // Block 0x73, offset 0x1cc0
+ 0x1cc0: 0x0040, 0x1cc1: 0xbca2, 0x1cc2: 0xbcba, 0x1cc3: 0xbcd2, 0x1cc4: 0xbcea, 0x1cc5: 0xbd02,
+ 0x1cc6: 0xbd1a, 0x1cc7: 0xbd32, 0x1cc8: 0xbd4a, 0x1cc9: 0xbd62, 0x1cca: 0xbd7a, 0x1ccb: 0x0018,
+ 0x1ccc: 0x0018, 0x1ccd: 0x0040, 0x1cce: 0x0040, 0x1ccf: 0x0040, 0x1cd0: 0xbd92, 0x1cd1: 0xbdb2,
+ 0x1cd2: 0xbdd2, 0x1cd3: 0xbdf2, 0x1cd4: 0xbe12, 0x1cd5: 0xbe32, 0x1cd6: 0xbe52, 0x1cd7: 0xbe72,
+ 0x1cd8: 0xbe92, 0x1cd9: 0xbeb2, 0x1cda: 0xbed2, 0x1cdb: 0xbef2, 0x1cdc: 0xbf12, 0x1cdd: 0xbf32,
+ 0x1cde: 0xbf52, 0x1cdf: 0xbf72, 0x1ce0: 0xbf92, 0x1ce1: 0xbfb2, 0x1ce2: 0xbfd2, 0x1ce3: 0xbff2,
+ 0x1ce4: 0xc012, 0x1ce5: 0xc032, 0x1ce6: 0xc052, 0x1ce7: 0xc072, 0x1ce8: 0xc092, 0x1ce9: 0xc0b2,
+ 0x1cea: 0xc0d1, 0x1ceb: 0x1159, 0x1cec: 0x0269, 0x1ced: 0x6671, 0x1cee: 0xc111, 0x1cef: 0x0040,
+ 0x1cf0: 0x0039, 0x1cf1: 0x0ee9, 0x1cf2: 0x1159, 0x1cf3: 0x0ef9, 0x1cf4: 0x0f09, 0x1cf5: 0x1199,
+ 0x1cf6: 0x0f31, 0x1cf7: 0x0249, 0x1cf8: 0x0f41, 0x1cf9: 0x0259, 0x1cfa: 0x0f51, 0x1cfb: 0x0359,
+ 0x1cfc: 0x0f61, 0x1cfd: 0x0f71, 0x1cfe: 0x00d9, 0x1cff: 0x0f99,
+ // Block 0x74, offset 0x1d00
+ 0x1d00: 0x2039, 0x1d01: 0x0269, 0x1d02: 0x01d9, 0x1d03: 0x0fa9, 0x1d04: 0x0fb9, 0x1d05: 0x1089,
+ 0x1d06: 0x0279, 0x1d07: 0x0369, 0x1d08: 0x0289, 0x1d09: 0x13d1, 0x1d0a: 0xc129, 0x1d0b: 0x65b1,
+ 0x1d0c: 0xc141, 0x1d0d: 0x1441, 0x1d0e: 0xc159, 0x1d0f: 0xc179, 0x1d10: 0x0018, 0x1d11: 0x0018,
+ 0x1d12: 0x0018, 0x1d13: 0x0018, 0x1d14: 0x0018, 0x1d15: 0x0018, 0x1d16: 0x0018, 0x1d17: 0x0018,
+ 0x1d18: 0x0018, 0x1d19: 0x0018, 0x1d1a: 0x0018, 0x1d1b: 0x0018, 0x1d1c: 0x0018, 0x1d1d: 0x0018,
+ 0x1d1e: 0x0018, 0x1d1f: 0x0018, 0x1d20: 0x0018, 0x1d21: 0x0018, 0x1d22: 0x0018, 0x1d23: 0x0018,
+ 0x1d24: 0x0018, 0x1d25: 0x0018, 0x1d26: 0x0018, 0x1d27: 0x0018, 0x1d28: 0x0018, 0x1d29: 0x0018,
+ 0x1d2a: 0xc191, 0x1d2b: 0xc1a9, 0x1d2c: 0x0040, 0x1d2d: 0x0040, 0x1d2e: 0x0040, 0x1d2f: 0x0040,
+ 0x1d30: 0x0018, 0x1d31: 0x0018, 0x1d32: 0x0018, 0x1d33: 0x0018, 0x1d34: 0x0018, 0x1d35: 0x0018,
+ 0x1d36: 0x0018, 0x1d37: 0x0018, 0x1d38: 0x0018, 0x1d39: 0x0018, 0x1d3a: 0x0018, 0x1d3b: 0x0018,
+ 0x1d3c: 0x0018, 0x1d3d: 0x0018, 0x1d3e: 0x0018, 0x1d3f: 0x0018,
+ // Block 0x75, offset 0x1d40
+ 0x1d40: 0xc1d9, 0x1d41: 0xc211, 0x1d42: 0xc249, 0x1d43: 0x0040, 0x1d44: 0x0040, 0x1d45: 0x0040,
+ 0x1d46: 0x0040, 0x1d47: 0x0040, 0x1d48: 0x0040, 0x1d49: 0x0040, 0x1d4a: 0x0040, 0x1d4b: 0x0040,
+ 0x1d4c: 0x0040, 0x1d4d: 0x0040, 0x1d4e: 0x0040, 0x1d4f: 0x0040, 0x1d50: 0xc269, 0x1d51: 0xc289,
+ 0x1d52: 0xc2a9, 0x1d53: 0xc2c9, 0x1d54: 0xc2e9, 0x1d55: 0xc309, 0x1d56: 0xc329, 0x1d57: 0xc349,
+ 0x1d58: 0xc369, 0x1d59: 0xc389, 0x1d5a: 0xc3a9, 0x1d5b: 0xc3c9, 0x1d5c: 0xc3e9, 0x1d5d: 0xc409,
+ 0x1d5e: 0xc429, 0x1d5f: 0xc449, 0x1d60: 0xc469, 0x1d61: 0xc489, 0x1d62: 0xc4a9, 0x1d63: 0xc4c9,
+ 0x1d64: 0xc4e9, 0x1d65: 0xc509, 0x1d66: 0xc529, 0x1d67: 0xc549, 0x1d68: 0xc569, 0x1d69: 0xc589,
+ 0x1d6a: 0xc5a9, 0x1d6b: 0xc5c9, 0x1d6c: 0xc5e9, 0x1d6d: 0xc609, 0x1d6e: 0xc629, 0x1d6f: 0xc649,
+ 0x1d70: 0xc669, 0x1d71: 0xc689, 0x1d72: 0xc6a9, 0x1d73: 0xc6c9, 0x1d74: 0xc6e9, 0x1d75: 0xc709,
+ 0x1d76: 0xc729, 0x1d77: 0xc749, 0x1d78: 0xc769, 0x1d79: 0xc789, 0x1d7a: 0xc7a9, 0x1d7b: 0xc7c9,
+ 0x1d7c: 0x0040, 0x1d7d: 0x0040, 0x1d7e: 0x0040, 0x1d7f: 0x0040,
+ // Block 0x76, offset 0x1d80
+ 0x1d80: 0xcaf9, 0x1d81: 0xcb19, 0x1d82: 0xcb39, 0x1d83: 0x8b1d, 0x1d84: 0xcb59, 0x1d85: 0xcb79,
+ 0x1d86: 0xcb99, 0x1d87: 0xcbb9, 0x1d88: 0xcbd9, 0x1d89: 0xcbf9, 0x1d8a: 0xcc19, 0x1d8b: 0xcc39,
+ 0x1d8c: 0xcc59, 0x1d8d: 0x8b3d, 0x1d8e: 0xcc79, 0x1d8f: 0xcc99, 0x1d90: 0xccb9, 0x1d91: 0xccd9,
+ 0x1d92: 0x8b5d, 0x1d93: 0xccf9, 0x1d94: 0xcd19, 0x1d95: 0xc429, 0x1d96: 0x8b7d, 0x1d97: 0xcd39,
+ 0x1d98: 0xcd59, 0x1d99: 0xcd79, 0x1d9a: 0xcd99, 0x1d9b: 0xcdb9, 0x1d9c: 0x8b9d, 0x1d9d: 0xcdd9,
+ 0x1d9e: 0xcdf9, 0x1d9f: 0xce19, 0x1da0: 0xce39, 0x1da1: 0xce59, 0x1da2: 0xc789, 0x1da3: 0xce79,
+ 0x1da4: 0xce99, 0x1da5: 0xceb9, 0x1da6: 0xced9, 0x1da7: 0xcef9, 0x1da8: 0xcf19, 0x1da9: 0xcf39,
+ 0x1daa: 0xcf59, 0x1dab: 0xcf79, 0x1dac: 0xcf99, 0x1dad: 0xcfb9, 0x1dae: 0xcfd9, 0x1daf: 0xcff9,
+ 0x1db0: 0xd019, 0x1db1: 0xd039, 0x1db2: 0xd039, 0x1db3: 0xd039, 0x1db4: 0x8bbd, 0x1db5: 0xd059,
+ 0x1db6: 0xd079, 0x1db7: 0xd099, 0x1db8: 0x8bdd, 0x1db9: 0xd0b9, 0x1dba: 0xd0d9, 0x1dbb: 0xd0f9,
+ 0x1dbc: 0xd119, 0x1dbd: 0xd139, 0x1dbe: 0xd159, 0x1dbf: 0xd179,
+ // Block 0x77, offset 0x1dc0
+ 0x1dc0: 0xd199, 0x1dc1: 0xd1b9, 0x1dc2: 0xd1d9, 0x1dc3: 0xd1f9, 0x1dc4: 0xd219, 0x1dc5: 0xd239,
+ 0x1dc6: 0xd239, 0x1dc7: 0xd259, 0x1dc8: 0xd279, 0x1dc9: 0xd299, 0x1dca: 0xd2b9, 0x1dcb: 0xd2d9,
+ 0x1dcc: 0xd2f9, 0x1dcd: 0xd319, 0x1dce: 0xd339, 0x1dcf: 0xd359, 0x1dd0: 0xd379, 0x1dd1: 0xd399,
+ 0x1dd2: 0xd3b9, 0x1dd3: 0xd3d9, 0x1dd4: 0xd3f9, 0x1dd5: 0xd419, 0x1dd6: 0xd439, 0x1dd7: 0xd459,
+ 0x1dd8: 0xd479, 0x1dd9: 0x8bfd, 0x1dda: 0xd499, 0x1ddb: 0xd4b9, 0x1ddc: 0xd4d9, 0x1ddd: 0xc309,
+ 0x1dde: 0xd4f9, 0x1ddf: 0xd519, 0x1de0: 0x8c1d, 0x1de1: 0x8c3d, 0x1de2: 0xd539, 0x1de3: 0xd559,
+ 0x1de4: 0xd579, 0x1de5: 0xd599, 0x1de6: 0xd5b9, 0x1de7: 0xd5d9, 0x1de8: 0x0040, 0x1de9: 0xd5f9,
+ 0x1dea: 0xd619, 0x1deb: 0xd619, 0x1dec: 0x8c5d, 0x1ded: 0xd639, 0x1dee: 0xd659, 0x1def: 0xd679,
+ 0x1df0: 0xd699, 0x1df1: 0x8c7d, 0x1df2: 0xd6b9, 0x1df3: 0xd6d9, 0x1df4: 0x0040, 0x1df5: 0xd6f9,
+ 0x1df6: 0xd719, 0x1df7: 0xd739, 0x1df8: 0xd759, 0x1df9: 0xd779, 0x1dfa: 0xd799, 0x1dfb: 0x8c9d,
+ 0x1dfc: 0xd7b9, 0x1dfd: 0x8cbd, 0x1dfe: 0xd7d9, 0x1dff: 0xd7f9,
+ // Block 0x78, offset 0x1e00
+ 0x1e00: 0xd819, 0x1e01: 0xd839, 0x1e02: 0xd859, 0x1e03: 0xd879, 0x1e04: 0xd899, 0x1e05: 0xd8b9,
+ 0x1e06: 0xd8d9, 0x1e07: 0xd8f9, 0x1e08: 0xd919, 0x1e09: 0x8cdd, 0x1e0a: 0xd939, 0x1e0b: 0xd959,
+ 0x1e0c: 0xd979, 0x1e0d: 0xd999, 0x1e0e: 0xd9b9, 0x1e0f: 0x8cfd, 0x1e10: 0xd9d9, 0x1e11: 0x8d1d,
+ 0x1e12: 0x8d3d, 0x1e13: 0xd9f9, 0x1e14: 0xda19, 0x1e15: 0xda19, 0x1e16: 0xda39, 0x1e17: 0x8d5d,
+ 0x1e18: 0x8d7d, 0x1e19: 0xda59, 0x1e1a: 0xda79, 0x1e1b: 0xda99, 0x1e1c: 0xdab9, 0x1e1d: 0xdad9,
+ 0x1e1e: 0xdaf9, 0x1e1f: 0xdb19, 0x1e20: 0xdb39, 0x1e21: 0xdb59, 0x1e22: 0xdb79, 0x1e23: 0xdb99,
+ 0x1e24: 0x8d9d, 0x1e25: 0xdbb9, 0x1e26: 0xdbd9, 0x1e27: 0xdbf9, 0x1e28: 0xdc19, 0x1e29: 0xdbf9,
+ 0x1e2a: 0xdc39, 0x1e2b: 0xdc59, 0x1e2c: 0xdc79, 0x1e2d: 0xdc99, 0x1e2e: 0xdcb9, 0x1e2f: 0xdcd9,
+ 0x1e30: 0xdcf9, 0x1e31: 0xdd19, 0x1e32: 0xdd39, 0x1e33: 0xdd59, 0x1e34: 0xdd79, 0x1e35: 0xdd99,
+ 0x1e36: 0xddb9, 0x1e37: 0xddd9, 0x1e38: 0x8dbd, 0x1e39: 0xddf9, 0x1e3a: 0xde19, 0x1e3b: 0xde39,
+ 0x1e3c: 0xde59, 0x1e3d: 0xde79, 0x1e3e: 0x8ddd, 0x1e3f: 0xde99,
+ // Block 0x79, offset 0x1e40
+ 0x1e40: 0xe599, 0x1e41: 0xe5b9, 0x1e42: 0xe5d9, 0x1e43: 0xe5f9, 0x1e44: 0xe619, 0x1e45: 0xe639,
+ 0x1e46: 0x8efd, 0x1e47: 0xe659, 0x1e48: 0xe679, 0x1e49: 0xe699, 0x1e4a: 0xe6b9, 0x1e4b: 0xe6d9,
+ 0x1e4c: 0xe6f9, 0x1e4d: 0x8f1d, 0x1e4e: 0xe719, 0x1e4f: 0xe739, 0x1e50: 0x8f3d, 0x1e51: 0x8f5d,
+ 0x1e52: 0xe759, 0x1e53: 0xe779, 0x1e54: 0xe799, 0x1e55: 0xe7b9, 0x1e56: 0xe7d9, 0x1e57: 0xe7f9,
+ 0x1e58: 0xe819, 0x1e59: 0xe839, 0x1e5a: 0xe859, 0x1e5b: 0x8f7d, 0x1e5c: 0xe879, 0x1e5d: 0x8f9d,
+ 0x1e5e: 0xe899, 0x1e5f: 0x0040, 0x1e60: 0xe8b9, 0x1e61: 0xe8d9, 0x1e62: 0xe8f9, 0x1e63: 0x8fbd,
+ 0x1e64: 0xe919, 0x1e65: 0xe939, 0x1e66: 0x8fdd, 0x1e67: 0x8ffd, 0x1e68: 0xe959, 0x1e69: 0xe979,
+ 0x1e6a: 0xe999, 0x1e6b: 0xe9b9, 0x1e6c: 0xe9d9, 0x1e6d: 0xe9d9, 0x1e6e: 0xe9f9, 0x1e6f: 0xea19,
+ 0x1e70: 0xea39, 0x1e71: 0xea59, 0x1e72: 0xea79, 0x1e73: 0xea99, 0x1e74: 0xeab9, 0x1e75: 0x901d,
+ 0x1e76: 0xead9, 0x1e77: 0x903d, 0x1e78: 0xeaf9, 0x1e79: 0x905d, 0x1e7a: 0xeb19, 0x1e7b: 0x907d,
+ 0x1e7c: 0x909d, 0x1e7d: 0x90bd, 0x1e7e: 0xeb39, 0x1e7f: 0xeb59,
+ // Block 0x7a, offset 0x1e80
+ 0x1e80: 0xeb79, 0x1e81: 0x90dd, 0x1e82: 0x90fd, 0x1e83: 0x911d, 0x1e84: 0x913d, 0x1e85: 0xeb99,
+ 0x1e86: 0xebb9, 0x1e87: 0xebb9, 0x1e88: 0xebd9, 0x1e89: 0xebf9, 0x1e8a: 0xec19, 0x1e8b: 0xec39,
+ 0x1e8c: 0xec59, 0x1e8d: 0x915d, 0x1e8e: 0xec79, 0x1e8f: 0xec99, 0x1e90: 0xecb9, 0x1e91: 0xecd9,
+ 0x1e92: 0x917d, 0x1e93: 0xecf9, 0x1e94: 0x919d, 0x1e95: 0x91bd, 0x1e96: 0xed19, 0x1e97: 0xed39,
+ 0x1e98: 0xed59, 0x1e99: 0xed79, 0x1e9a: 0xed99, 0x1e9b: 0xedb9, 0x1e9c: 0x91dd, 0x1e9d: 0x91fd,
+ 0x1e9e: 0x921d, 0x1e9f: 0x0040, 0x1ea0: 0xedd9, 0x1ea1: 0x923d, 0x1ea2: 0xedf9, 0x1ea3: 0xee19,
+ 0x1ea4: 0xee39, 0x1ea5: 0x925d, 0x1ea6: 0xee59, 0x1ea7: 0xee79, 0x1ea8: 0xee99, 0x1ea9: 0xeeb9,
+ 0x1eaa: 0xeed9, 0x1eab: 0x927d, 0x1eac: 0xeef9, 0x1ead: 0xef19, 0x1eae: 0xef39, 0x1eaf: 0xef59,
+ 0x1eb0: 0xef79, 0x1eb1: 0xef99, 0x1eb2: 0x929d, 0x1eb3: 0x92bd, 0x1eb4: 0xefb9, 0x1eb5: 0x92dd,
+ 0x1eb6: 0xefd9, 0x1eb7: 0x92fd, 0x1eb8: 0xeff9, 0x1eb9: 0xf019, 0x1eba: 0xf039, 0x1ebb: 0x931d,
+ 0x1ebc: 0x933d, 0x1ebd: 0xf059, 0x1ebe: 0x935d, 0x1ebf: 0xf079,
+ // Block 0x7b, offset 0x1ec0
+ 0x1ec0: 0xf6b9, 0x1ec1: 0xf6d9, 0x1ec2: 0xf6f9, 0x1ec3: 0xf719, 0x1ec4: 0xf739, 0x1ec5: 0x951d,
+ 0x1ec6: 0xf759, 0x1ec7: 0xf779, 0x1ec8: 0xf799, 0x1ec9: 0xf7b9, 0x1eca: 0xf7d9, 0x1ecb: 0x953d,
+ 0x1ecc: 0x955d, 0x1ecd: 0xf7f9, 0x1ece: 0xf819, 0x1ecf: 0xf839, 0x1ed0: 0xf859, 0x1ed1: 0xf879,
+ 0x1ed2: 0xf899, 0x1ed3: 0x957d, 0x1ed4: 0xf8b9, 0x1ed5: 0xf8d9, 0x1ed6: 0xf8f9, 0x1ed7: 0xf919,
+ 0x1ed8: 0x959d, 0x1ed9: 0x95bd, 0x1eda: 0xf939, 0x1edb: 0xf959, 0x1edc: 0xf979, 0x1edd: 0x95dd,
+ 0x1ede: 0xf999, 0x1edf: 0xf9b9, 0x1ee0: 0x6815, 0x1ee1: 0x95fd, 0x1ee2: 0xf9d9, 0x1ee3: 0xf9f9,
+ 0x1ee4: 0xfa19, 0x1ee5: 0x961d, 0x1ee6: 0xfa39, 0x1ee7: 0xfa59, 0x1ee8: 0xfa79, 0x1ee9: 0xfa99,
+ 0x1eea: 0xfab9, 0x1eeb: 0xfad9, 0x1eec: 0xfaf9, 0x1eed: 0x963d, 0x1eee: 0xfb19, 0x1eef: 0xfb39,
+ 0x1ef0: 0xfb59, 0x1ef1: 0x965d, 0x1ef2: 0xfb79, 0x1ef3: 0xfb99, 0x1ef4: 0xfbb9, 0x1ef5: 0xfbd9,
+ 0x1ef6: 0x7b35, 0x1ef7: 0x967d, 0x1ef8: 0xfbf9, 0x1ef9: 0xfc19, 0x1efa: 0xfc39, 0x1efb: 0x969d,
+ 0x1efc: 0xfc59, 0x1efd: 0x96bd, 0x1efe: 0xfc79, 0x1eff: 0xfc79,
+ // Block 0x7c, offset 0x1f00
+ 0x1f00: 0xfc99, 0x1f01: 0x96dd, 0x1f02: 0xfcb9, 0x1f03: 0xfcd9, 0x1f04: 0xfcf9, 0x1f05: 0xfd19,
+ 0x1f06: 0xfd39, 0x1f07: 0xfd59, 0x1f08: 0xfd79, 0x1f09: 0x96fd, 0x1f0a: 0xfd99, 0x1f0b: 0xfdb9,
+ 0x1f0c: 0xfdd9, 0x1f0d: 0xfdf9, 0x1f0e: 0xfe19, 0x1f0f: 0xfe39, 0x1f10: 0x971d, 0x1f11: 0xfe59,
+ 0x1f12: 0x973d, 0x1f13: 0x975d, 0x1f14: 0x977d, 0x1f15: 0xfe79, 0x1f16: 0xfe99, 0x1f17: 0xfeb9,
+ 0x1f18: 0xfed9, 0x1f19: 0xfef9, 0x1f1a: 0xff19, 0x1f1b: 0xff39, 0x1f1c: 0xff59, 0x1f1d: 0x979d,
+ 0x1f1e: 0x0040, 0x1f1f: 0x0040, 0x1f20: 0x0040, 0x1f21: 0x0040, 0x1f22: 0x0040, 0x1f23: 0x0040,
+ 0x1f24: 0x0040, 0x1f25: 0x0040, 0x1f26: 0x0040, 0x1f27: 0x0040, 0x1f28: 0x0040, 0x1f29: 0x0040,
+ 0x1f2a: 0x0040, 0x1f2b: 0x0040, 0x1f2c: 0x0040, 0x1f2d: 0x0040, 0x1f2e: 0x0040, 0x1f2f: 0x0040,
+ 0x1f30: 0x0040, 0x1f31: 0x0040, 0x1f32: 0x0040, 0x1f33: 0x0040, 0x1f34: 0x0040, 0x1f35: 0x0040,
+ 0x1f36: 0x0040, 0x1f37: 0x0040, 0x1f38: 0x0040, 0x1f39: 0x0040, 0x1f3a: 0x0040, 0x1f3b: 0x0040,
+ 0x1f3c: 0x0040, 0x1f3d: 0x0040, 0x1f3e: 0x0040, 0x1f3f: 0x0040,
+}
+
+// idnaIndex: 35 blocks, 2240 entries, 4480 bytes
+// Block 0 is the zero block.
+var idnaIndex = [2240]uint16{
+ // Block 0x0, offset 0x0
+ // Block 0x1, offset 0x40
+ // Block 0x2, offset 0x80
+ // Block 0x3, offset 0xc0
+ 0xc2: 0x01, 0xc3: 0x7b, 0xc4: 0x02, 0xc5: 0x03, 0xc6: 0x04, 0xc7: 0x05,
+ 0xc8: 0x06, 0xc9: 0x7c, 0xca: 0x7d, 0xcb: 0x07, 0xcc: 0x7e, 0xcd: 0x08, 0xce: 0x09, 0xcf: 0x0a,
+ 0xd0: 0x7f, 0xd1: 0x0b, 0xd2: 0x0c, 0xd3: 0x0d, 0xd4: 0x0e, 0xd5: 0x80, 0xd6: 0x81, 0xd7: 0x82,
+ 0xd8: 0x0f, 0xd9: 0x83, 0xda: 0x84, 0xdb: 0x10, 0xdc: 0x11, 0xdd: 0x85, 0xde: 0x86, 0xdf: 0x87,
+ 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05, 0xe4: 0x06, 0xe5: 0x07, 0xe6: 0x07, 0xe7: 0x07,
+ 0xe8: 0x07, 0xe9: 0x08, 0xea: 0x09, 0xeb: 0x07, 0xec: 0x07, 0xed: 0x0a, 0xee: 0x0b, 0xef: 0x0c,
+ 0xf0: 0x1c, 0xf1: 0x1d, 0xf2: 0x1d, 0xf3: 0x1f, 0xf4: 0x20,
+ // Block 0x4, offset 0x100
+ 0x120: 0x88, 0x121: 0x89, 0x122: 0x8a, 0x123: 0x8b, 0x124: 0x8c, 0x125: 0x12, 0x126: 0x13, 0x127: 0x14,
+ 0x128: 0x15, 0x129: 0x16, 0x12a: 0x17, 0x12b: 0x18, 0x12c: 0x19, 0x12d: 0x1a, 0x12e: 0x1b, 0x12f: 0x8d,
+ 0x130: 0x8e, 0x131: 0x1c, 0x132: 0x1d, 0x133: 0x1e, 0x134: 0x8f, 0x135: 0x1f, 0x136: 0x90, 0x137: 0x91,
+ 0x138: 0x92, 0x139: 0x93, 0x13a: 0x20, 0x13b: 0x94, 0x13c: 0x95, 0x13d: 0x21, 0x13e: 0x22, 0x13f: 0x96,
+ // Block 0x5, offset 0x140
+ 0x140: 0x97, 0x141: 0x98, 0x142: 0x99, 0x143: 0x9a, 0x144: 0x9b, 0x145: 0x9c, 0x146: 0x9b, 0x147: 0x9b,
+ 0x148: 0x9d, 0x149: 0x9e, 0x14a: 0x9f, 0x14b: 0xa0, 0x14c: 0xa1, 0x14d: 0xa2, 0x14e: 0xa3, 0x14f: 0xa4,
+ 0x150: 0xa5, 0x151: 0x9d, 0x152: 0x9d, 0x153: 0x9d, 0x154: 0x9d, 0x155: 0x9d, 0x156: 0x9d, 0x157: 0x9d,
+ 0x158: 0x9d, 0x159: 0xa6, 0x15a: 0xa7, 0x15b: 0xa8, 0x15c: 0xa9, 0x15d: 0xaa, 0x15e: 0xab, 0x15f: 0xac,
+ 0x160: 0xad, 0x161: 0xae, 0x162: 0xaf, 0x163: 0xb0, 0x164: 0xb1, 0x165: 0xb2, 0x166: 0xb3, 0x167: 0xb4,
+ 0x168: 0xb5, 0x169: 0xb6, 0x16a: 0xb7, 0x16b: 0xb8, 0x16c: 0xb9, 0x16d: 0xba, 0x16e: 0xbb, 0x16f: 0xbc,
+ 0x170: 0xbd, 0x171: 0xbe, 0x172: 0xbf, 0x173: 0xc0, 0x174: 0x23, 0x175: 0x24, 0x176: 0x25, 0x177: 0xc1,
+ 0x178: 0x26, 0x179: 0x26, 0x17a: 0x27, 0x17b: 0x26, 0x17c: 0xc2, 0x17d: 0x28, 0x17e: 0x29, 0x17f: 0x2a,
+ // Block 0x6, offset 0x180
+ 0x180: 0x2b, 0x181: 0x2c, 0x182: 0x2d, 0x183: 0xc3, 0x184: 0x2e, 0x185: 0x2f, 0x186: 0xc4, 0x187: 0x9b,
+ 0x188: 0xc5, 0x189: 0xc6, 0x18a: 0x9b, 0x18b: 0x9b, 0x18c: 0xc7, 0x18d: 0x9b, 0x18e: 0x9b, 0x18f: 0xc8,
+ 0x190: 0xc9, 0x191: 0x30, 0x192: 0x31, 0x193: 0x32, 0x194: 0x9b, 0x195: 0x9b, 0x196: 0x9b, 0x197: 0x9b,
+ 0x198: 0x9b, 0x199: 0x9b, 0x19a: 0x9b, 0x19b: 0x9b, 0x19c: 0x9b, 0x19d: 0x9b, 0x19e: 0x9b, 0x19f: 0x9b,
+ 0x1a0: 0x9b, 0x1a1: 0x9b, 0x1a2: 0x9b, 0x1a3: 0x9b, 0x1a4: 0x9b, 0x1a5: 0x9b, 0x1a6: 0x9b, 0x1a7: 0x9b,
+ 0x1a8: 0xca, 0x1a9: 0xcb, 0x1aa: 0x9b, 0x1ab: 0xcc, 0x1ac: 0x9b, 0x1ad: 0xcd, 0x1ae: 0xce, 0x1af: 0xcf,
+ 0x1b0: 0xd0, 0x1b1: 0x33, 0x1b2: 0x26, 0x1b3: 0x34, 0x1b4: 0xd1, 0x1b5: 0xd2, 0x1b6: 0xd3, 0x1b7: 0xd4,
+ 0x1b8: 0xd5, 0x1b9: 0xd6, 0x1ba: 0xd7, 0x1bb: 0xd8, 0x1bc: 0xd9, 0x1bd: 0xda, 0x1be: 0xdb, 0x1bf: 0x35,
+ // Block 0x7, offset 0x1c0
+ 0x1c0: 0x36, 0x1c1: 0xdc, 0x1c2: 0xdd, 0x1c3: 0xde, 0x1c4: 0xdf, 0x1c5: 0x37, 0x1c6: 0x38, 0x1c7: 0xe0,
+ 0x1c8: 0xe1, 0x1c9: 0x39, 0x1ca: 0x3a, 0x1cb: 0x3b, 0x1cc: 0x3c, 0x1cd: 0x3d, 0x1ce: 0x3e, 0x1cf: 0x3f,
+ 0x1d0: 0x9d, 0x1d1: 0x9d, 0x1d2: 0x9d, 0x1d3: 0x9d, 0x1d4: 0x9d, 0x1d5: 0x9d, 0x1d6: 0x9d, 0x1d7: 0x9d,
+ 0x1d8: 0x9d, 0x1d9: 0x9d, 0x1da: 0x9d, 0x1db: 0x9d, 0x1dc: 0x9d, 0x1dd: 0x9d, 0x1de: 0x9d, 0x1df: 0x9d,
+ 0x1e0: 0x9d, 0x1e1: 0x9d, 0x1e2: 0x9d, 0x1e3: 0x9d, 0x1e4: 0x9d, 0x1e5: 0x9d, 0x1e6: 0x9d, 0x1e7: 0x9d,
+ 0x1e8: 0x9d, 0x1e9: 0x9d, 0x1ea: 0x9d, 0x1eb: 0x9d, 0x1ec: 0x9d, 0x1ed: 0x9d, 0x1ee: 0x9d, 0x1ef: 0x9d,
+ 0x1f0: 0x9d, 0x1f1: 0x9d, 0x1f2: 0x9d, 0x1f3: 0x9d, 0x1f4: 0x9d, 0x1f5: 0x9d, 0x1f6: 0x9d, 0x1f7: 0x9d,
+ 0x1f8: 0x9d, 0x1f9: 0x9d, 0x1fa: 0x9d, 0x1fb: 0x9d, 0x1fc: 0x9d, 0x1fd: 0x9d, 0x1fe: 0x9d, 0x1ff: 0x9d,
+ // Block 0x8, offset 0x200
+ 0x200: 0x9d, 0x201: 0x9d, 0x202: 0x9d, 0x203: 0x9d, 0x204: 0x9d, 0x205: 0x9d, 0x206: 0x9d, 0x207: 0x9d,
+ 0x208: 0x9d, 0x209: 0x9d, 0x20a: 0x9d, 0x20b: 0x9d, 0x20c: 0x9d, 0x20d: 0x9d, 0x20e: 0x9d, 0x20f: 0x9d,
+ 0x210: 0x9d, 0x211: 0x9d, 0x212: 0x9d, 0x213: 0x9d, 0x214: 0x9d, 0x215: 0x9d, 0x216: 0x9d, 0x217: 0x9d,
+ 0x218: 0x9d, 0x219: 0x9d, 0x21a: 0x9d, 0x21b: 0x9d, 0x21c: 0x9d, 0x21d: 0x9d, 0x21e: 0x9d, 0x21f: 0x9d,
+ 0x220: 0x9d, 0x221: 0x9d, 0x222: 0x9d, 0x223: 0x9d, 0x224: 0x9d, 0x225: 0x9d, 0x226: 0x9d, 0x227: 0x9d,
+ 0x228: 0x9d, 0x229: 0x9d, 0x22a: 0x9d, 0x22b: 0x9d, 0x22c: 0x9d, 0x22d: 0x9d, 0x22e: 0x9d, 0x22f: 0x9d,
+ 0x230: 0x9d, 0x231: 0x9d, 0x232: 0x9d, 0x233: 0x9d, 0x234: 0x9d, 0x235: 0x9d, 0x236: 0xb0, 0x237: 0x9b,
+ 0x238: 0x9d, 0x239: 0x9d, 0x23a: 0x9d, 0x23b: 0x9d, 0x23c: 0x9d, 0x23d: 0x9d, 0x23e: 0x9d, 0x23f: 0x9d,
+ // Block 0x9, offset 0x240
+ 0x240: 0x9d, 0x241: 0x9d, 0x242: 0x9d, 0x243: 0x9d, 0x244: 0x9d, 0x245: 0x9d, 0x246: 0x9d, 0x247: 0x9d,
+ 0x248: 0x9d, 0x249: 0x9d, 0x24a: 0x9d, 0x24b: 0x9d, 0x24c: 0x9d, 0x24d: 0x9d, 0x24e: 0x9d, 0x24f: 0x9d,
+ 0x250: 0x9d, 0x251: 0x9d, 0x252: 0x9d, 0x253: 0x9d, 0x254: 0x9d, 0x255: 0x9d, 0x256: 0x9d, 0x257: 0x9d,
+ 0x258: 0x9d, 0x259: 0x9d, 0x25a: 0x9d, 0x25b: 0x9d, 0x25c: 0x9d, 0x25d: 0x9d, 0x25e: 0x9d, 0x25f: 0x9d,
+ 0x260: 0x9d, 0x261: 0x9d, 0x262: 0x9d, 0x263: 0x9d, 0x264: 0x9d, 0x265: 0x9d, 0x266: 0x9d, 0x267: 0x9d,
+ 0x268: 0x9d, 0x269: 0x9d, 0x26a: 0x9d, 0x26b: 0x9d, 0x26c: 0x9d, 0x26d: 0x9d, 0x26e: 0x9d, 0x26f: 0x9d,
+ 0x270: 0x9d, 0x271: 0x9d, 0x272: 0x9d, 0x273: 0x9d, 0x274: 0x9d, 0x275: 0x9d, 0x276: 0x9d, 0x277: 0x9d,
+ 0x278: 0x9d, 0x279: 0x9d, 0x27a: 0x9d, 0x27b: 0x9d, 0x27c: 0x9d, 0x27d: 0x9d, 0x27e: 0x9d, 0x27f: 0x9d,
+ // Block 0xa, offset 0x280
+ 0x280: 0x9d, 0x281: 0x9d, 0x282: 0x9d, 0x283: 0x9d, 0x284: 0x9d, 0x285: 0x9d, 0x286: 0x9d, 0x287: 0x9d,
+ 0x288: 0x9d, 0x289: 0x9d, 0x28a: 0x9d, 0x28b: 0x9d, 0x28c: 0x9d, 0x28d: 0x9d, 0x28e: 0x9d, 0x28f: 0x9d,
+ 0x290: 0x9d, 0x291: 0x9d, 0x292: 0x9d, 0x293: 0x9d, 0x294: 0x9d, 0x295: 0x9d, 0x296: 0x9d, 0x297: 0x9d,
+ 0x298: 0x9d, 0x299: 0x9d, 0x29a: 0x9d, 0x29b: 0x9d, 0x29c: 0x9d, 0x29d: 0x9d, 0x29e: 0x9d, 0x29f: 0x9d,
+ 0x2a0: 0x9d, 0x2a1: 0x9d, 0x2a2: 0x9d, 0x2a3: 0x9d, 0x2a4: 0x9d, 0x2a5: 0x9d, 0x2a6: 0x9d, 0x2a7: 0x9d,
+ 0x2a8: 0x9d, 0x2a9: 0x9d, 0x2aa: 0x9d, 0x2ab: 0x9d, 0x2ac: 0x9d, 0x2ad: 0x9d, 0x2ae: 0x9d, 0x2af: 0x9d,
+ 0x2b0: 0x9d, 0x2b1: 0x9d, 0x2b2: 0x9d, 0x2b3: 0x9d, 0x2b4: 0x9d, 0x2b5: 0x9d, 0x2b6: 0x9d, 0x2b7: 0x9d,
+ 0x2b8: 0x9d, 0x2b9: 0x9d, 0x2ba: 0x9d, 0x2bb: 0x9d, 0x2bc: 0x9d, 0x2bd: 0x9d, 0x2be: 0x9d, 0x2bf: 0xe2,
+ // Block 0xb, offset 0x2c0
+ 0x2c0: 0x9d, 0x2c1: 0x9d, 0x2c2: 0x9d, 0x2c3: 0x9d, 0x2c4: 0x9d, 0x2c5: 0x9d, 0x2c6: 0x9d, 0x2c7: 0x9d,
+ 0x2c8: 0x9d, 0x2c9: 0x9d, 0x2ca: 0x9d, 0x2cb: 0x9d, 0x2cc: 0x9d, 0x2cd: 0x9d, 0x2ce: 0x9d, 0x2cf: 0x9d,
+ 0x2d0: 0x9d, 0x2d1: 0x9d, 0x2d2: 0xe3, 0x2d3: 0xe4, 0x2d4: 0x9d, 0x2d5: 0x9d, 0x2d6: 0x9d, 0x2d7: 0x9d,
+ 0x2d8: 0xe5, 0x2d9: 0x40, 0x2da: 0x41, 0x2db: 0xe6, 0x2dc: 0x42, 0x2dd: 0x43, 0x2de: 0x44, 0x2df: 0xe7,
+ 0x2e0: 0xe8, 0x2e1: 0xe9, 0x2e2: 0xea, 0x2e3: 0xeb, 0x2e4: 0xec, 0x2e5: 0xed, 0x2e6: 0xee, 0x2e7: 0xef,
+ 0x2e8: 0xf0, 0x2e9: 0xf1, 0x2ea: 0xf2, 0x2eb: 0xf3, 0x2ec: 0xf4, 0x2ed: 0xf5, 0x2ee: 0xf6, 0x2ef: 0xf7,
+ 0x2f0: 0x9d, 0x2f1: 0x9d, 0x2f2: 0x9d, 0x2f3: 0x9d, 0x2f4: 0x9d, 0x2f5: 0x9d, 0x2f6: 0x9d, 0x2f7: 0x9d,
+ 0x2f8: 0x9d, 0x2f9: 0x9d, 0x2fa: 0x9d, 0x2fb: 0x9d, 0x2fc: 0x9d, 0x2fd: 0x9d, 0x2fe: 0x9d, 0x2ff: 0x9d,
+ // Block 0xc, offset 0x300
+ 0x300: 0x9d, 0x301: 0x9d, 0x302: 0x9d, 0x303: 0x9d, 0x304: 0x9d, 0x305: 0x9d, 0x306: 0x9d, 0x307: 0x9d,
+ 0x308: 0x9d, 0x309: 0x9d, 0x30a: 0x9d, 0x30b: 0x9d, 0x30c: 0x9d, 0x30d: 0x9d, 0x30e: 0x9d, 0x30f: 0x9d,
+ 0x310: 0x9d, 0x311: 0x9d, 0x312: 0x9d, 0x313: 0x9d, 0x314: 0x9d, 0x315: 0x9d, 0x316: 0x9d, 0x317: 0x9d,
+ 0x318: 0x9d, 0x319: 0x9d, 0x31a: 0x9d, 0x31b: 0x9d, 0x31c: 0x9d, 0x31d: 0x9d, 0x31e: 0xf8, 0x31f: 0xf9,
+ // Block 0xd, offset 0x340
+ 0x340: 0xb8, 0x341: 0xb8, 0x342: 0xb8, 0x343: 0xb8, 0x344: 0xb8, 0x345: 0xb8, 0x346: 0xb8, 0x347: 0xb8,
+ 0x348: 0xb8, 0x349: 0xb8, 0x34a: 0xb8, 0x34b: 0xb8, 0x34c: 0xb8, 0x34d: 0xb8, 0x34e: 0xb8, 0x34f: 0xb8,
+ 0x350: 0xb8, 0x351: 0xb8, 0x352: 0xb8, 0x353: 0xb8, 0x354: 0xb8, 0x355: 0xb8, 0x356: 0xb8, 0x357: 0xb8,
+ 0x358: 0xb8, 0x359: 0xb8, 0x35a: 0xb8, 0x35b: 0xb8, 0x35c: 0xb8, 0x35d: 0xb8, 0x35e: 0xb8, 0x35f: 0xb8,
+ 0x360: 0xb8, 0x361: 0xb8, 0x362: 0xb8, 0x363: 0xb8, 0x364: 0xb8, 0x365: 0xb8, 0x366: 0xb8, 0x367: 0xb8,
+ 0x368: 0xb8, 0x369: 0xb8, 0x36a: 0xb8, 0x36b: 0xb8, 0x36c: 0xb8, 0x36d: 0xb8, 0x36e: 0xb8, 0x36f: 0xb8,
+ 0x370: 0xb8, 0x371: 0xb8, 0x372: 0xb8, 0x373: 0xb8, 0x374: 0xb8, 0x375: 0xb8, 0x376: 0xb8, 0x377: 0xb8,
+ 0x378: 0xb8, 0x379: 0xb8, 0x37a: 0xb8, 0x37b: 0xb8, 0x37c: 0xb8, 0x37d: 0xb8, 0x37e: 0xb8, 0x37f: 0xb8,
+ // Block 0xe, offset 0x380
+ 0x380: 0xb8, 0x381: 0xb8, 0x382: 0xb8, 0x383: 0xb8, 0x384: 0xb8, 0x385: 0xb8, 0x386: 0xb8, 0x387: 0xb8,
+ 0x388: 0xb8, 0x389: 0xb8, 0x38a: 0xb8, 0x38b: 0xb8, 0x38c: 0xb8, 0x38d: 0xb8, 0x38e: 0xb8, 0x38f: 0xb8,
+ 0x390: 0xb8, 0x391: 0xb8, 0x392: 0xb8, 0x393: 0xb8, 0x394: 0xb8, 0x395: 0xb8, 0x396: 0xb8, 0x397: 0xb8,
+ 0x398: 0xb8, 0x399: 0xb8, 0x39a: 0xb8, 0x39b: 0xb8, 0x39c: 0xb8, 0x39d: 0xb8, 0x39e: 0xb8, 0x39f: 0xb8,
+ 0x3a0: 0xb8, 0x3a1: 0xb8, 0x3a2: 0xb8, 0x3a3: 0xb8, 0x3a4: 0xfa, 0x3a5: 0xfb, 0x3a6: 0xfc, 0x3a7: 0xfd,
+ 0x3a8: 0x45, 0x3a9: 0xfe, 0x3aa: 0xff, 0x3ab: 0x46, 0x3ac: 0x47, 0x3ad: 0x48, 0x3ae: 0x49, 0x3af: 0x4a,
+ 0x3b0: 0x100, 0x3b1: 0x4b, 0x3b2: 0x4c, 0x3b3: 0x4d, 0x3b4: 0x4e, 0x3b5: 0x4f, 0x3b6: 0x101, 0x3b7: 0x50,
+ 0x3b8: 0x51, 0x3b9: 0x52, 0x3ba: 0x53, 0x3bb: 0x54, 0x3bc: 0x55, 0x3bd: 0x56, 0x3be: 0x57, 0x3bf: 0x58,
+ // Block 0xf, offset 0x3c0
+ 0x3c0: 0x102, 0x3c1: 0x103, 0x3c2: 0x9d, 0x3c3: 0x104, 0x3c4: 0x105, 0x3c5: 0x9b, 0x3c6: 0x106, 0x3c7: 0x107,
+ 0x3c8: 0xb8, 0x3c9: 0xb8, 0x3ca: 0x108, 0x3cb: 0x109, 0x3cc: 0x10a, 0x3cd: 0x10b, 0x3ce: 0x10c, 0x3cf: 0x10d,
+ 0x3d0: 0x10e, 0x3d1: 0x9d, 0x3d2: 0x10f, 0x3d3: 0x110, 0x3d4: 0x111, 0x3d5: 0x112, 0x3d6: 0xb8, 0x3d7: 0xb8,
+ 0x3d8: 0x9d, 0x3d9: 0x9d, 0x3da: 0x9d, 0x3db: 0x9d, 0x3dc: 0x113, 0x3dd: 0x114, 0x3de: 0xb8, 0x3df: 0xb8,
+ 0x3e0: 0x115, 0x3e1: 0x116, 0x3e2: 0x117, 0x3e3: 0x118, 0x3e4: 0x119, 0x3e5: 0xb8, 0x3e6: 0x11a, 0x3e7: 0x11b,
+ 0x3e8: 0x11c, 0x3e9: 0x11d, 0x3ea: 0x11e, 0x3eb: 0x59, 0x3ec: 0x11f, 0x3ed: 0x120, 0x3ee: 0x5a, 0x3ef: 0xb8,
+ 0x3f0: 0x9d, 0x3f1: 0x121, 0x3f2: 0x122, 0x3f3: 0x123, 0x3f4: 0xb8, 0x3f5: 0xb8, 0x3f6: 0xb8, 0x3f7: 0xb8,
+ 0x3f8: 0xb8, 0x3f9: 0x124, 0x3fa: 0xb8, 0x3fb: 0xb8, 0x3fc: 0xb8, 0x3fd: 0xb8, 0x3fe: 0xb8, 0x3ff: 0xb8,
+ // Block 0x10, offset 0x400
+ 0x400: 0x125, 0x401: 0x126, 0x402: 0x127, 0x403: 0x128, 0x404: 0x129, 0x405: 0x12a, 0x406: 0x12b, 0x407: 0x12c,
+ 0x408: 0x12d, 0x409: 0xb8, 0x40a: 0x12e, 0x40b: 0x12f, 0x40c: 0x5b, 0x40d: 0x5c, 0x40e: 0xb8, 0x40f: 0xb8,
+ 0x410: 0x130, 0x411: 0x131, 0x412: 0x132, 0x413: 0x133, 0x414: 0xb8, 0x415: 0xb8, 0x416: 0x134, 0x417: 0x135,
+ 0x418: 0x136, 0x419: 0x137, 0x41a: 0x138, 0x41b: 0x139, 0x41c: 0x13a, 0x41d: 0xb8, 0x41e: 0xb8, 0x41f: 0xb8,
+ 0x420: 0xb8, 0x421: 0xb8, 0x422: 0x13b, 0x423: 0x13c, 0x424: 0xb8, 0x425: 0xb8, 0x426: 0xb8, 0x427: 0xb8,
+ 0x428: 0xb8, 0x429: 0xb8, 0x42a: 0xb8, 0x42b: 0x13d, 0x42c: 0xb8, 0x42d: 0xb8, 0x42e: 0xb8, 0x42f: 0xb8,
+ 0x430: 0x13e, 0x431: 0x13f, 0x432: 0x140, 0x433: 0xb8, 0x434: 0xb8, 0x435: 0xb8, 0x436: 0xb8, 0x437: 0xb8,
+ 0x438: 0xb8, 0x439: 0xb8, 0x43a: 0xb8, 0x43b: 0xb8, 0x43c: 0xb8, 0x43d: 0xb8, 0x43e: 0xb8, 0x43f: 0xb8,
+ // Block 0x11, offset 0x440
+ 0x440: 0x9d, 0x441: 0x9d, 0x442: 0x9d, 0x443: 0x9d, 0x444: 0x9d, 0x445: 0x9d, 0x446: 0x9d, 0x447: 0x9d,
+ 0x448: 0x9d, 0x449: 0x9d, 0x44a: 0x9d, 0x44b: 0x9d, 0x44c: 0x9d, 0x44d: 0x9d, 0x44e: 0x141, 0x44f: 0xb8,
+ 0x450: 0x9b, 0x451: 0x142, 0x452: 0x9d, 0x453: 0x9d, 0x454: 0x9d, 0x455: 0x143, 0x456: 0xb8, 0x457: 0xb8,
+ 0x458: 0xb8, 0x459: 0xb8, 0x45a: 0xb8, 0x45b: 0xb8, 0x45c: 0xb8, 0x45d: 0xb8, 0x45e: 0xb8, 0x45f: 0xb8,
+ 0x460: 0xb8, 0x461: 0xb8, 0x462: 0xb8, 0x463: 0xb8, 0x464: 0xb8, 0x465: 0xb8, 0x466: 0xb8, 0x467: 0xb8,
+ 0x468: 0xb8, 0x469: 0xb8, 0x46a: 0xb8, 0x46b: 0xb8, 0x46c: 0xb8, 0x46d: 0xb8, 0x46e: 0xb8, 0x46f: 0xb8,
+ 0x470: 0xb8, 0x471: 0xb8, 0x472: 0xb8, 0x473: 0xb8, 0x474: 0xb8, 0x475: 0xb8, 0x476: 0xb8, 0x477: 0xb8,
+ 0x478: 0xb8, 0x479: 0xb8, 0x47a: 0xb8, 0x47b: 0xb8, 0x47c: 0xb8, 0x47d: 0xb8, 0x47e: 0xb8, 0x47f: 0xb8,
+ // Block 0x12, offset 0x480
+ 0x480: 0x9d, 0x481: 0x9d, 0x482: 0x9d, 0x483: 0x9d, 0x484: 0x9d, 0x485: 0x9d, 0x486: 0x9d, 0x487: 0x9d,
+ 0x488: 0x9d, 0x489: 0x9d, 0x48a: 0x9d, 0x48b: 0x9d, 0x48c: 0x9d, 0x48d: 0x9d, 0x48e: 0x9d, 0x48f: 0x9d,
+ 0x490: 0x144, 0x491: 0xb8, 0x492: 0xb8, 0x493: 0xb8, 0x494: 0xb8, 0x495: 0xb8, 0x496: 0xb8, 0x497: 0xb8,
+ 0x498: 0xb8, 0x499: 0xb8, 0x49a: 0xb8, 0x49b: 0xb8, 0x49c: 0xb8, 0x49d: 0xb8, 0x49e: 0xb8, 0x49f: 0xb8,
+ 0x4a0: 0xb8, 0x4a1: 0xb8, 0x4a2: 0xb8, 0x4a3: 0xb8, 0x4a4: 0xb8, 0x4a5: 0xb8, 0x4a6: 0xb8, 0x4a7: 0xb8,
+ 0x4a8: 0xb8, 0x4a9: 0xb8, 0x4aa: 0xb8, 0x4ab: 0xb8, 0x4ac: 0xb8, 0x4ad: 0xb8, 0x4ae: 0xb8, 0x4af: 0xb8,
+ 0x4b0: 0xb8, 0x4b1: 0xb8, 0x4b2: 0xb8, 0x4b3: 0xb8, 0x4b4: 0xb8, 0x4b5: 0xb8, 0x4b6: 0xb8, 0x4b7: 0xb8,
+ 0x4b8: 0xb8, 0x4b9: 0xb8, 0x4ba: 0xb8, 0x4bb: 0xb8, 0x4bc: 0xb8, 0x4bd: 0xb8, 0x4be: 0xb8, 0x4bf: 0xb8,
+ // Block 0x13, offset 0x4c0
+ 0x4c0: 0xb8, 0x4c1: 0xb8, 0x4c2: 0xb8, 0x4c3: 0xb8, 0x4c4: 0xb8, 0x4c5: 0xb8, 0x4c6: 0xb8, 0x4c7: 0xb8,
+ 0x4c8: 0xb8, 0x4c9: 0xb8, 0x4ca: 0xb8, 0x4cb: 0xb8, 0x4cc: 0xb8, 0x4cd: 0xb8, 0x4ce: 0xb8, 0x4cf: 0xb8,
+ 0x4d0: 0x9d, 0x4d1: 0x9d, 0x4d2: 0x9d, 0x4d3: 0x9d, 0x4d4: 0x9d, 0x4d5: 0x9d, 0x4d6: 0x9d, 0x4d7: 0x9d,
+ 0x4d8: 0x9d, 0x4d9: 0x145, 0x4da: 0xb8, 0x4db: 0xb8, 0x4dc: 0xb8, 0x4dd: 0xb8, 0x4de: 0xb8, 0x4df: 0xb8,
+ 0x4e0: 0xb8, 0x4e1: 0xb8, 0x4e2: 0xb8, 0x4e3: 0xb8, 0x4e4: 0xb8, 0x4e5: 0xb8, 0x4e6: 0xb8, 0x4e7: 0xb8,
+ 0x4e8: 0xb8, 0x4e9: 0xb8, 0x4ea: 0xb8, 0x4eb: 0xb8, 0x4ec: 0xb8, 0x4ed: 0xb8, 0x4ee: 0xb8, 0x4ef: 0xb8,
+ 0x4f0: 0xb8, 0x4f1: 0xb8, 0x4f2: 0xb8, 0x4f3: 0xb8, 0x4f4: 0xb8, 0x4f5: 0xb8, 0x4f6: 0xb8, 0x4f7: 0xb8,
+ 0x4f8: 0xb8, 0x4f9: 0xb8, 0x4fa: 0xb8, 0x4fb: 0xb8, 0x4fc: 0xb8, 0x4fd: 0xb8, 0x4fe: 0xb8, 0x4ff: 0xb8,
+ // Block 0x14, offset 0x500
+ 0x500: 0xb8, 0x501: 0xb8, 0x502: 0xb8, 0x503: 0xb8, 0x504: 0xb8, 0x505: 0xb8, 0x506: 0xb8, 0x507: 0xb8,
+ 0x508: 0xb8, 0x509: 0xb8, 0x50a: 0xb8, 0x50b: 0xb8, 0x50c: 0xb8, 0x50d: 0xb8, 0x50e: 0xb8, 0x50f: 0xb8,
+ 0x510: 0xb8, 0x511: 0xb8, 0x512: 0xb8, 0x513: 0xb8, 0x514: 0xb8, 0x515: 0xb8, 0x516: 0xb8, 0x517: 0xb8,
+ 0x518: 0xb8, 0x519: 0xb8, 0x51a: 0xb8, 0x51b: 0xb8, 0x51c: 0xb8, 0x51d: 0xb8, 0x51e: 0xb8, 0x51f: 0xb8,
+ 0x520: 0x9d, 0x521: 0x9d, 0x522: 0x9d, 0x523: 0x9d, 0x524: 0x9d, 0x525: 0x9d, 0x526: 0x9d, 0x527: 0x9d,
+ 0x528: 0x13d, 0x529: 0x146, 0x52a: 0xb8, 0x52b: 0x147, 0x52c: 0x148, 0x52d: 0x149, 0x52e: 0x14a, 0x52f: 0xb8,
+ 0x530: 0xb8, 0x531: 0xb8, 0x532: 0xb8, 0x533: 0xb8, 0x534: 0xb8, 0x535: 0xb8, 0x536: 0xb8, 0x537: 0xb8,
+ 0x538: 0xb8, 0x539: 0xb8, 0x53a: 0xb8, 0x53b: 0xb8, 0x53c: 0x9d, 0x53d: 0x14b, 0x53e: 0x14c, 0x53f: 0x14d,
+ // Block 0x15, offset 0x540
+ 0x540: 0x9d, 0x541: 0x9d, 0x542: 0x9d, 0x543: 0x9d, 0x544: 0x9d, 0x545: 0x9d, 0x546: 0x9d, 0x547: 0x9d,
+ 0x548: 0x9d, 0x549: 0x9d, 0x54a: 0x9d, 0x54b: 0x9d, 0x54c: 0x9d, 0x54d: 0x9d, 0x54e: 0x9d, 0x54f: 0x9d,
+ 0x550: 0x9d, 0x551: 0x9d, 0x552: 0x9d, 0x553: 0x9d, 0x554: 0x9d, 0x555: 0x9d, 0x556: 0x9d, 0x557: 0x9d,
+ 0x558: 0x9d, 0x559: 0x9d, 0x55a: 0x9d, 0x55b: 0x9d, 0x55c: 0x9d, 0x55d: 0x9d, 0x55e: 0x9d, 0x55f: 0x14e,
+ 0x560: 0x9d, 0x561: 0x9d, 0x562: 0x9d, 0x563: 0x9d, 0x564: 0x9d, 0x565: 0x9d, 0x566: 0x9d, 0x567: 0x9d,
+ 0x568: 0x9d, 0x569: 0x9d, 0x56a: 0x9d, 0x56b: 0x14f, 0x56c: 0xb8, 0x56d: 0xb8, 0x56e: 0xb8, 0x56f: 0xb8,
+ 0x570: 0xb8, 0x571: 0xb8, 0x572: 0xb8, 0x573: 0xb8, 0x574: 0xb8, 0x575: 0xb8, 0x576: 0xb8, 0x577: 0xb8,
+ 0x578: 0xb8, 0x579: 0xb8, 0x57a: 0xb8, 0x57b: 0xb8, 0x57c: 0xb8, 0x57d: 0xb8, 0x57e: 0xb8, 0x57f: 0xb8,
+ // Block 0x16, offset 0x580
+ 0x580: 0x150, 0x581: 0xb8, 0x582: 0xb8, 0x583: 0xb8, 0x584: 0xb8, 0x585: 0xb8, 0x586: 0xb8, 0x587: 0xb8,
+ 0x588: 0xb8, 0x589: 0xb8, 0x58a: 0xb8, 0x58b: 0xb8, 0x58c: 0xb8, 0x58d: 0xb8, 0x58e: 0xb8, 0x58f: 0xb8,
+ 0x590: 0xb8, 0x591: 0xb8, 0x592: 0xb8, 0x593: 0xb8, 0x594: 0xb8, 0x595: 0xb8, 0x596: 0xb8, 0x597: 0xb8,
+ 0x598: 0xb8, 0x599: 0xb8, 0x59a: 0xb8, 0x59b: 0xb8, 0x59c: 0xb8, 0x59d: 0xb8, 0x59e: 0xb8, 0x59f: 0xb8,
+ 0x5a0: 0xb8, 0x5a1: 0xb8, 0x5a2: 0xb8, 0x5a3: 0xb8, 0x5a4: 0xb8, 0x5a5: 0xb8, 0x5a6: 0xb8, 0x5a7: 0xb8,
+ 0x5a8: 0xb8, 0x5a9: 0xb8, 0x5aa: 0xb8, 0x5ab: 0xb8, 0x5ac: 0xb8, 0x5ad: 0xb8, 0x5ae: 0xb8, 0x5af: 0xb8,
+ 0x5b0: 0x9d, 0x5b1: 0x151, 0x5b2: 0x152, 0x5b3: 0xb8, 0x5b4: 0xb8, 0x5b5: 0xb8, 0x5b6: 0xb8, 0x5b7: 0xb8,
+ 0x5b8: 0xb8, 0x5b9: 0xb8, 0x5ba: 0xb8, 0x5bb: 0xb8, 0x5bc: 0xb8, 0x5bd: 0xb8, 0x5be: 0xb8, 0x5bf: 0xb8,
+ // Block 0x17, offset 0x5c0
+ 0x5c0: 0x9b, 0x5c1: 0x9b, 0x5c2: 0x9b, 0x5c3: 0x153, 0x5c4: 0x154, 0x5c5: 0x155, 0x5c6: 0x156, 0x5c7: 0x157,
+ 0x5c8: 0x9b, 0x5c9: 0x158, 0x5ca: 0xb8, 0x5cb: 0xb8, 0x5cc: 0x9b, 0x5cd: 0x159, 0x5ce: 0xb8, 0x5cf: 0xb8,
+ 0x5d0: 0x5d, 0x5d1: 0x5e, 0x5d2: 0x5f, 0x5d3: 0x60, 0x5d4: 0x61, 0x5d5: 0x62, 0x5d6: 0x63, 0x5d7: 0x64,
+ 0x5d8: 0x65, 0x5d9: 0x66, 0x5da: 0x67, 0x5db: 0x68, 0x5dc: 0x69, 0x5dd: 0x6a, 0x5de: 0x6b, 0x5df: 0x6c,
+ 0x5e0: 0x9b, 0x5e1: 0x9b, 0x5e2: 0x9b, 0x5e3: 0x9b, 0x5e4: 0x9b, 0x5e5: 0x9b, 0x5e6: 0x9b, 0x5e7: 0x9b,
+ 0x5e8: 0x15a, 0x5e9: 0x15b, 0x5ea: 0x15c, 0x5eb: 0xb8, 0x5ec: 0xb8, 0x5ed: 0xb8, 0x5ee: 0xb8, 0x5ef: 0xb8,
+ 0x5f0: 0xb8, 0x5f1: 0xb8, 0x5f2: 0xb8, 0x5f3: 0xb8, 0x5f4: 0xb8, 0x5f5: 0xb8, 0x5f6: 0xb8, 0x5f7: 0xb8,
+ 0x5f8: 0xb8, 0x5f9: 0xb8, 0x5fa: 0xb8, 0x5fb: 0xb8, 0x5fc: 0xb8, 0x5fd: 0xb8, 0x5fe: 0xb8, 0x5ff: 0xb8,
+ // Block 0x18, offset 0x600
+ 0x600: 0x15d, 0x601: 0xb8, 0x602: 0xb8, 0x603: 0xb8, 0x604: 0xb8, 0x605: 0xb8, 0x606: 0xb8, 0x607: 0xb8,
+ 0x608: 0xb8, 0x609: 0xb8, 0x60a: 0xb8, 0x60b: 0xb8, 0x60c: 0xb8, 0x60d: 0xb8, 0x60e: 0xb8, 0x60f: 0xb8,
+ 0x610: 0xb8, 0x611: 0xb8, 0x612: 0xb8, 0x613: 0xb8, 0x614: 0xb8, 0x615: 0xb8, 0x616: 0xb8, 0x617: 0xb8,
+ 0x618: 0xb8, 0x619: 0xb8, 0x61a: 0xb8, 0x61b: 0xb8, 0x61c: 0xb8, 0x61d: 0xb8, 0x61e: 0xb8, 0x61f: 0xb8,
+ 0x620: 0x9d, 0x621: 0x9d, 0x622: 0x9d, 0x623: 0x15e, 0x624: 0x6d, 0x625: 0x15f, 0x626: 0xb8, 0x627: 0xb8,
+ 0x628: 0xb8, 0x629: 0xb8, 0x62a: 0xb8, 0x62b: 0xb8, 0x62c: 0xb8, 0x62d: 0xb8, 0x62e: 0xb8, 0x62f: 0xb8,
+ 0x630: 0xb8, 0x631: 0xb8, 0x632: 0xb8, 0x633: 0xb8, 0x634: 0xb8, 0x635: 0xb8, 0x636: 0xb8, 0x637: 0xb8,
+ 0x638: 0x6e, 0x639: 0x6f, 0x63a: 0x70, 0x63b: 0x160, 0x63c: 0xb8, 0x63d: 0xb8, 0x63e: 0xb8, 0x63f: 0xb8,
+ // Block 0x19, offset 0x640
+ 0x640: 0x161, 0x641: 0x9b, 0x642: 0x162, 0x643: 0x163, 0x644: 0x71, 0x645: 0x72, 0x646: 0x164, 0x647: 0x165,
+ 0x648: 0x73, 0x649: 0x166, 0x64a: 0xb8, 0x64b: 0xb8, 0x64c: 0x9b, 0x64d: 0x9b, 0x64e: 0x9b, 0x64f: 0x9b,
+ 0x650: 0x9b, 0x651: 0x9b, 0x652: 0x9b, 0x653: 0x9b, 0x654: 0x9b, 0x655: 0x9b, 0x656: 0x9b, 0x657: 0x9b,
+ 0x658: 0x9b, 0x659: 0x9b, 0x65a: 0x9b, 0x65b: 0x167, 0x65c: 0x9b, 0x65d: 0x168, 0x65e: 0x9b, 0x65f: 0x169,
+ 0x660: 0x16a, 0x661: 0x16b, 0x662: 0x16c, 0x663: 0xb8, 0x664: 0x16d, 0x665: 0x16e, 0x666: 0x16f, 0x667: 0x170,
+ 0x668: 0xb8, 0x669: 0xb8, 0x66a: 0xb8, 0x66b: 0xb8, 0x66c: 0xb8, 0x66d: 0xb8, 0x66e: 0xb8, 0x66f: 0xb8,
+ 0x670: 0xb8, 0x671: 0xb8, 0x672: 0xb8, 0x673: 0xb8, 0x674: 0xb8, 0x675: 0xb8, 0x676: 0xb8, 0x677: 0xb8,
+ 0x678: 0xb8, 0x679: 0xb8, 0x67a: 0xb8, 0x67b: 0xb8, 0x67c: 0xb8, 0x67d: 0xb8, 0x67e: 0xb8, 0x67f: 0xb8,
+ // Block 0x1a, offset 0x680
+ 0x680: 0x9d, 0x681: 0x9d, 0x682: 0x9d, 0x683: 0x9d, 0x684: 0x9d, 0x685: 0x9d, 0x686: 0x9d, 0x687: 0x9d,
+ 0x688: 0x9d, 0x689: 0x9d, 0x68a: 0x9d, 0x68b: 0x9d, 0x68c: 0x9d, 0x68d: 0x9d, 0x68e: 0x9d, 0x68f: 0x9d,
+ 0x690: 0x9d, 0x691: 0x9d, 0x692: 0x9d, 0x693: 0x9d, 0x694: 0x9d, 0x695: 0x9d, 0x696: 0x9d, 0x697: 0x9d,
+ 0x698: 0x9d, 0x699: 0x9d, 0x69a: 0x9d, 0x69b: 0x171, 0x69c: 0x9d, 0x69d: 0x9d, 0x69e: 0x9d, 0x69f: 0x9d,
+ 0x6a0: 0x9d, 0x6a1: 0x9d, 0x6a2: 0x9d, 0x6a3: 0x9d, 0x6a4: 0x9d, 0x6a5: 0x9d, 0x6a6: 0x9d, 0x6a7: 0x9d,
+ 0x6a8: 0x9d, 0x6a9: 0x9d, 0x6aa: 0x9d, 0x6ab: 0x9d, 0x6ac: 0x9d, 0x6ad: 0x9d, 0x6ae: 0x9d, 0x6af: 0x9d,
+ 0x6b0: 0x9d, 0x6b1: 0x9d, 0x6b2: 0x9d, 0x6b3: 0x9d, 0x6b4: 0x9d, 0x6b5: 0x9d, 0x6b6: 0x9d, 0x6b7: 0x9d,
+ 0x6b8: 0x9d, 0x6b9: 0x9d, 0x6ba: 0x9d, 0x6bb: 0x9d, 0x6bc: 0x9d, 0x6bd: 0x9d, 0x6be: 0x9d, 0x6bf: 0x9d,
+ // Block 0x1b, offset 0x6c0
+ 0x6c0: 0x9d, 0x6c1: 0x9d, 0x6c2: 0x9d, 0x6c3: 0x9d, 0x6c4: 0x9d, 0x6c5: 0x9d, 0x6c6: 0x9d, 0x6c7: 0x9d,
+ 0x6c8: 0x9d, 0x6c9: 0x9d, 0x6ca: 0x9d, 0x6cb: 0x9d, 0x6cc: 0x9d, 0x6cd: 0x9d, 0x6ce: 0x9d, 0x6cf: 0x9d,
+ 0x6d0: 0x9d, 0x6d1: 0x9d, 0x6d2: 0x9d, 0x6d3: 0x9d, 0x6d4: 0x9d, 0x6d5: 0x9d, 0x6d6: 0x9d, 0x6d7: 0x9d,
+ 0x6d8: 0x9d, 0x6d9: 0x9d, 0x6da: 0x9d, 0x6db: 0x9d, 0x6dc: 0x172, 0x6dd: 0x9d, 0x6de: 0x9d, 0x6df: 0x9d,
+ 0x6e0: 0x173, 0x6e1: 0x9d, 0x6e2: 0x9d, 0x6e3: 0x9d, 0x6e4: 0x9d, 0x6e5: 0x9d, 0x6e6: 0x9d, 0x6e7: 0x9d,
+ 0x6e8: 0x9d, 0x6e9: 0x9d, 0x6ea: 0x9d, 0x6eb: 0x9d, 0x6ec: 0x9d, 0x6ed: 0x9d, 0x6ee: 0x9d, 0x6ef: 0x9d,
+ 0x6f0: 0x9d, 0x6f1: 0x9d, 0x6f2: 0x9d, 0x6f3: 0x9d, 0x6f4: 0x9d, 0x6f5: 0x9d, 0x6f6: 0x9d, 0x6f7: 0x9d,
+ 0x6f8: 0x9d, 0x6f9: 0x9d, 0x6fa: 0x9d, 0x6fb: 0x9d, 0x6fc: 0x9d, 0x6fd: 0x9d, 0x6fe: 0x9d, 0x6ff: 0x9d,
+ // Block 0x1c, offset 0x700
+ 0x700: 0x9d, 0x701: 0x9d, 0x702: 0x9d, 0x703: 0x9d, 0x704: 0x9d, 0x705: 0x9d, 0x706: 0x9d, 0x707: 0x9d,
+ 0x708: 0x9d, 0x709: 0x9d, 0x70a: 0x9d, 0x70b: 0x9d, 0x70c: 0x9d, 0x70d: 0x9d, 0x70e: 0x9d, 0x70f: 0x9d,
+ 0x710: 0x9d, 0x711: 0x9d, 0x712: 0x9d, 0x713: 0x9d, 0x714: 0x9d, 0x715: 0x9d, 0x716: 0x9d, 0x717: 0x9d,
+ 0x718: 0x9d, 0x719: 0x9d, 0x71a: 0x9d, 0x71b: 0x9d, 0x71c: 0x9d, 0x71d: 0x9d, 0x71e: 0x9d, 0x71f: 0x9d,
+ 0x720: 0x9d, 0x721: 0x9d, 0x722: 0x9d, 0x723: 0x9d, 0x724: 0x9d, 0x725: 0x9d, 0x726: 0x9d, 0x727: 0x9d,
+ 0x728: 0x9d, 0x729: 0x9d, 0x72a: 0x9d, 0x72b: 0x9d, 0x72c: 0x9d, 0x72d: 0x9d, 0x72e: 0x9d, 0x72f: 0x9d,
+ 0x730: 0x9d, 0x731: 0x9d, 0x732: 0x9d, 0x733: 0x9d, 0x734: 0x9d, 0x735: 0x9d, 0x736: 0x9d, 0x737: 0x9d,
+ 0x738: 0x9d, 0x739: 0x9d, 0x73a: 0x174, 0x73b: 0xb8, 0x73c: 0xb8, 0x73d: 0xb8, 0x73e: 0xb8, 0x73f: 0xb8,
+ // Block 0x1d, offset 0x740
+ 0x740: 0xb8, 0x741: 0xb8, 0x742: 0xb8, 0x743: 0xb8, 0x744: 0xb8, 0x745: 0xb8, 0x746: 0xb8, 0x747: 0xb8,
+ 0x748: 0xb8, 0x749: 0xb8, 0x74a: 0xb8, 0x74b: 0xb8, 0x74c: 0xb8, 0x74d: 0xb8, 0x74e: 0xb8, 0x74f: 0xb8,
+ 0x750: 0xb8, 0x751: 0xb8, 0x752: 0xb8, 0x753: 0xb8, 0x754: 0xb8, 0x755: 0xb8, 0x756: 0xb8, 0x757: 0xb8,
+ 0x758: 0xb8, 0x759: 0xb8, 0x75a: 0xb8, 0x75b: 0xb8, 0x75c: 0xb8, 0x75d: 0xb8, 0x75e: 0xb8, 0x75f: 0xb8,
+ 0x760: 0x74, 0x761: 0x75, 0x762: 0x76, 0x763: 0x175, 0x764: 0x77, 0x765: 0x78, 0x766: 0x176, 0x767: 0x79,
+ 0x768: 0x7a, 0x769: 0xb8, 0x76a: 0xb8, 0x76b: 0xb8, 0x76c: 0xb8, 0x76d: 0xb8, 0x76e: 0xb8, 0x76f: 0xb8,
+ 0x770: 0xb8, 0x771: 0xb8, 0x772: 0xb8, 0x773: 0xb8, 0x774: 0xb8, 0x775: 0xb8, 0x776: 0xb8, 0x777: 0xb8,
+ 0x778: 0xb8, 0x779: 0xb8, 0x77a: 0xb8, 0x77b: 0xb8, 0x77c: 0xb8, 0x77d: 0xb8, 0x77e: 0xb8, 0x77f: 0xb8,
+ // Block 0x1e, offset 0x780
+ 0x790: 0x0d, 0x791: 0x0e, 0x792: 0x0f, 0x793: 0x10, 0x794: 0x11, 0x795: 0x0b, 0x796: 0x12, 0x797: 0x07,
+ 0x798: 0x13, 0x799: 0x0b, 0x79a: 0x0b, 0x79b: 0x14, 0x79c: 0x0b, 0x79d: 0x15, 0x79e: 0x16, 0x79f: 0x17,
+ 0x7a0: 0x07, 0x7a1: 0x07, 0x7a2: 0x07, 0x7a3: 0x07, 0x7a4: 0x07, 0x7a5: 0x07, 0x7a6: 0x07, 0x7a7: 0x07,
+ 0x7a8: 0x07, 0x7a9: 0x07, 0x7aa: 0x18, 0x7ab: 0x19, 0x7ac: 0x1a, 0x7ad: 0x0b, 0x7ae: 0x0b, 0x7af: 0x1b,
+ 0x7b0: 0x0b, 0x7b1: 0x0b, 0x7b2: 0x0b, 0x7b3: 0x0b, 0x7b4: 0x0b, 0x7b5: 0x0b, 0x7b6: 0x0b, 0x7b7: 0x0b,
+ 0x7b8: 0x0b, 0x7b9: 0x0b, 0x7ba: 0x0b, 0x7bb: 0x0b, 0x7bc: 0x0b, 0x7bd: 0x0b, 0x7be: 0x0b, 0x7bf: 0x0b,
+ // Block 0x1f, offset 0x7c0
+ 0x7c0: 0x0b, 0x7c1: 0x0b, 0x7c2: 0x0b, 0x7c3: 0x0b, 0x7c4: 0x0b, 0x7c5: 0x0b, 0x7c6: 0x0b, 0x7c7: 0x0b,
+ 0x7c8: 0x0b, 0x7c9: 0x0b, 0x7ca: 0x0b, 0x7cb: 0x0b, 0x7cc: 0x0b, 0x7cd: 0x0b, 0x7ce: 0x0b, 0x7cf: 0x0b,
+ 0x7d0: 0x0b, 0x7d1: 0x0b, 0x7d2: 0x0b, 0x7d3: 0x0b, 0x7d4: 0x0b, 0x7d5: 0x0b, 0x7d6: 0x0b, 0x7d7: 0x0b,
+ 0x7d8: 0x0b, 0x7d9: 0x0b, 0x7da: 0x0b, 0x7db: 0x0b, 0x7dc: 0x0b, 0x7dd: 0x0b, 0x7de: 0x0b, 0x7df: 0x0b,
+ 0x7e0: 0x0b, 0x7e1: 0x0b, 0x7e2: 0x0b, 0x7e3: 0x0b, 0x7e4: 0x0b, 0x7e5: 0x0b, 0x7e6: 0x0b, 0x7e7: 0x0b,
+ 0x7e8: 0x0b, 0x7e9: 0x0b, 0x7ea: 0x0b, 0x7eb: 0x0b, 0x7ec: 0x0b, 0x7ed: 0x0b, 0x7ee: 0x0b, 0x7ef: 0x0b,
+ 0x7f0: 0x0b, 0x7f1: 0x0b, 0x7f2: 0x0b, 0x7f3: 0x0b, 0x7f4: 0x0b, 0x7f5: 0x0b, 0x7f6: 0x0b, 0x7f7: 0x0b,
+ 0x7f8: 0x0b, 0x7f9: 0x0b, 0x7fa: 0x0b, 0x7fb: 0x0b, 0x7fc: 0x0b, 0x7fd: 0x0b, 0x7fe: 0x0b, 0x7ff: 0x0b,
+ // Block 0x20, offset 0x800
+ 0x800: 0x177, 0x801: 0x178, 0x802: 0xb8, 0x803: 0xb8, 0x804: 0x179, 0x805: 0x179, 0x806: 0x179, 0x807: 0x17a,
+ 0x808: 0xb8, 0x809: 0xb8, 0x80a: 0xb8, 0x80b: 0xb8, 0x80c: 0xb8, 0x80d: 0xb8, 0x80e: 0xb8, 0x80f: 0xb8,
+ 0x810: 0xb8, 0x811: 0xb8, 0x812: 0xb8, 0x813: 0xb8, 0x814: 0xb8, 0x815: 0xb8, 0x816: 0xb8, 0x817: 0xb8,
+ 0x818: 0xb8, 0x819: 0xb8, 0x81a: 0xb8, 0x81b: 0xb8, 0x81c: 0xb8, 0x81d: 0xb8, 0x81e: 0xb8, 0x81f: 0xb8,
+ 0x820: 0xb8, 0x821: 0xb8, 0x822: 0xb8, 0x823: 0xb8, 0x824: 0xb8, 0x825: 0xb8, 0x826: 0xb8, 0x827: 0xb8,
+ 0x828: 0xb8, 0x829: 0xb8, 0x82a: 0xb8, 0x82b: 0xb8, 0x82c: 0xb8, 0x82d: 0xb8, 0x82e: 0xb8, 0x82f: 0xb8,
+ 0x830: 0xb8, 0x831: 0xb8, 0x832: 0xb8, 0x833: 0xb8, 0x834: 0xb8, 0x835: 0xb8, 0x836: 0xb8, 0x837: 0xb8,
+ 0x838: 0xb8, 0x839: 0xb8, 0x83a: 0xb8, 0x83b: 0xb8, 0x83c: 0xb8, 0x83d: 0xb8, 0x83e: 0xb8, 0x83f: 0xb8,
+ // Block 0x21, offset 0x840
+ 0x840: 0x0b, 0x841: 0x0b, 0x842: 0x0b, 0x843: 0x0b, 0x844: 0x0b, 0x845: 0x0b, 0x846: 0x0b, 0x847: 0x0b,
+ 0x848: 0x0b, 0x849: 0x0b, 0x84a: 0x0b, 0x84b: 0x0b, 0x84c: 0x0b, 0x84d: 0x0b, 0x84e: 0x0b, 0x84f: 0x0b,
+ 0x850: 0x0b, 0x851: 0x0b, 0x852: 0x0b, 0x853: 0x0b, 0x854: 0x0b, 0x855: 0x0b, 0x856: 0x0b, 0x857: 0x0b,
+ 0x858: 0x0b, 0x859: 0x0b, 0x85a: 0x0b, 0x85b: 0x0b, 0x85c: 0x0b, 0x85d: 0x0b, 0x85e: 0x0b, 0x85f: 0x0b,
+ 0x860: 0x1e, 0x861: 0x0b, 0x862: 0x0b, 0x863: 0x0b, 0x864: 0x0b, 0x865: 0x0b, 0x866: 0x0b, 0x867: 0x0b,
+ 0x868: 0x0b, 0x869: 0x0b, 0x86a: 0x0b, 0x86b: 0x0b, 0x86c: 0x0b, 0x86d: 0x0b, 0x86e: 0x0b, 0x86f: 0x0b,
+ 0x870: 0x0b, 0x871: 0x0b, 0x872: 0x0b, 0x873: 0x0b, 0x874: 0x0b, 0x875: 0x0b, 0x876: 0x0b, 0x877: 0x0b,
+ 0x878: 0x0b, 0x879: 0x0b, 0x87a: 0x0b, 0x87b: 0x0b, 0x87c: 0x0b, 0x87d: 0x0b, 0x87e: 0x0b, 0x87f: 0x0b,
+ // Block 0x22, offset 0x880
+ 0x880: 0x0b, 0x881: 0x0b, 0x882: 0x0b, 0x883: 0x0b, 0x884: 0x0b, 0x885: 0x0b, 0x886: 0x0b, 0x887: 0x0b,
+ 0x888: 0x0b, 0x889: 0x0b, 0x88a: 0x0b, 0x88b: 0x0b, 0x88c: 0x0b, 0x88d: 0x0b, 0x88e: 0x0b, 0x88f: 0x0b,
+}
+
+// idnaSparseOffset: 256 entries, 512 bytes
+var idnaSparseOffset = []uint16{0x0, 0x8, 0x19, 0x25, 0x27, 0x2c, 0x34, 0x3f, 0x4b, 0x5c, 0x60, 0x6f, 0x74, 0x7b, 0x87, 0x95, 0xa3, 0xa8, 0xb1, 0xc1, 0xcf, 0xdc, 0xe8, 0xf9, 0x103, 0x10a, 0x117, 0x128, 0x12f, 0x13a, 0x149, 0x157, 0x161, 0x163, 0x167, 0x169, 0x175, 0x180, 0x188, 0x18e, 0x194, 0x199, 0x19e, 0x1a1, 0x1a5, 0x1ab, 0x1b0, 0x1bc, 0x1c6, 0x1cc, 0x1dd, 0x1e7, 0x1ea, 0x1f2, 0x1f5, 0x202, 0x20a, 0x20e, 0x215, 0x21d, 0x22d, 0x239, 0x23b, 0x245, 0x251, 0x25d, 0x269, 0x271, 0x276, 0x280, 0x291, 0x295, 0x2a0, 0x2a4, 0x2ad, 0x2b5, 0x2bb, 0x2c0, 0x2c3, 0x2c6, 0x2ca, 0x2d0, 0x2d4, 0x2d8, 0x2de, 0x2e5, 0x2eb, 0x2f3, 0x2fa, 0x305, 0x30f, 0x313, 0x316, 0x31c, 0x320, 0x322, 0x325, 0x327, 0x32a, 0x334, 0x337, 0x346, 0x34a, 0x34f, 0x352, 0x356, 0x35b, 0x360, 0x366, 0x36c, 0x37b, 0x381, 0x385, 0x394, 0x399, 0x3a1, 0x3ab, 0x3b6, 0x3be, 0x3cf, 0x3d8, 0x3e8, 0x3f5, 0x3ff, 0x404, 0x411, 0x415, 0x41a, 0x41c, 0x420, 0x422, 0x426, 0x42f, 0x435, 0x439, 0x449, 0x453, 0x458, 0x45b, 0x461, 0x468, 0x46d, 0x471, 0x477, 0x47c, 0x485, 0x48a, 0x490, 0x497, 0x49e, 0x4a5, 0x4a9, 0x4ae, 0x4b1, 0x4b6, 0x4c2, 0x4c8, 0x4cd, 0x4d4, 0x4dc, 0x4e1, 0x4e5, 0x4f5, 0x4fc, 0x500, 0x504, 0x50b, 0x50e, 0x511, 0x515, 0x519, 0x51f, 0x528, 0x534, 0x53b, 0x544, 0x54c, 0x553, 0x561, 0x56e, 0x57b, 0x584, 0x588, 0x596, 0x59e, 0x5a9, 0x5b2, 0x5b8, 0x5c0, 0x5c9, 0x5d3, 0x5d6, 0x5e2, 0x5e5, 0x5ea, 0x5ed, 0x5f7, 0x600, 0x60c, 0x60f, 0x614, 0x617, 0x61a, 0x61d, 0x624, 0x62b, 0x62f, 0x63a, 0x63d, 0x643, 0x648, 0x64c, 0x64f, 0x652, 0x655, 0x65a, 0x664, 0x667, 0x66b, 0x67a, 0x686, 0x68a, 0x68f, 0x694, 0x698, 0x69d, 0x6a6, 0x6b1, 0x6b7, 0x6bf, 0x6c3, 0x6c7, 0x6cd, 0x6d3, 0x6d8, 0x6db, 0x6e9, 0x6f0, 0x6f3, 0x6f6, 0x6fa, 0x700, 0x705, 0x70f, 0x714, 0x717, 0x71a, 0x71d, 0x720, 0x724, 0x727, 0x737, 0x748, 0x74d, 0x74f, 0x751}
+
+// idnaSparseValues: 1876 entries, 7504 bytes
+var idnaSparseValues = [1876]valueRange{
+ // Block 0x0, offset 0x0
+ {value: 0x0000, lo: 0x07},
+ {value: 0xe105, lo: 0x80, hi: 0x96},
+ {value: 0x0018, lo: 0x97, hi: 0x97},
+ {value: 0xe105, lo: 0x98, hi: 0x9e},
+ {value: 0x001f, lo: 0x9f, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xb6},
+ {value: 0x0018, lo: 0xb7, hi: 0xb7},
+ {value: 0x0008, lo: 0xb8, hi: 0xbf},
+ // Block 0x1, offset 0x8
+ {value: 0x0000, lo: 0x10},
+ {value: 0x0008, lo: 0x80, hi: 0x80},
+ {value: 0xe01d, lo: 0x81, hi: 0x81},
+ {value: 0x0008, lo: 0x82, hi: 0x82},
+ {value: 0x0335, lo: 0x83, hi: 0x83},
+ {value: 0x034d, lo: 0x84, hi: 0x84},
+ {value: 0x0365, lo: 0x85, hi: 0x85},
+ {value: 0xe00d, lo: 0x86, hi: 0x86},
+ {value: 0x0008, lo: 0x87, hi: 0x87},
+ {value: 0xe00d, lo: 0x88, hi: 0x88},
+ {value: 0x0008, lo: 0x89, hi: 0x89},
+ {value: 0xe00d, lo: 0x8a, hi: 0x8a},
+ {value: 0x0008, lo: 0x8b, hi: 0x8b},
+ {value: 0xe00d, lo: 0x8c, hi: 0x8c},
+ {value: 0x0008, lo: 0x8d, hi: 0x8d},
+ {value: 0xe00d, lo: 0x8e, hi: 0x8e},
+ {value: 0x0008, lo: 0x8f, hi: 0xbf},
+ // Block 0x2, offset 0x19
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0008, lo: 0x80, hi: 0xaf},
+ {value: 0x0249, lo: 0xb0, hi: 0xb0},
+ {value: 0x037d, lo: 0xb1, hi: 0xb1},
+ {value: 0x0259, lo: 0xb2, hi: 0xb2},
+ {value: 0x0269, lo: 0xb3, hi: 0xb3},
+ {value: 0x034d, lo: 0xb4, hi: 0xb4},
+ {value: 0x0395, lo: 0xb5, hi: 0xb5},
+ {value: 0xe1bd, lo: 0xb6, hi: 0xb6},
+ {value: 0x0279, lo: 0xb7, hi: 0xb7},
+ {value: 0x0289, lo: 0xb8, hi: 0xb8},
+ {value: 0x0008, lo: 0xb9, hi: 0xbf},
+ // Block 0x3, offset 0x25
+ {value: 0x0000, lo: 0x01},
+ {value: 0x1308, lo: 0x80, hi: 0xbf},
+ // Block 0x4, offset 0x27
+ {value: 0x0000, lo: 0x04},
+ {value: 0x03f5, lo: 0x80, hi: 0x8f},
+ {value: 0xe105, lo: 0x90, hi: 0x9f},
+ {value: 0x049d, lo: 0xa0, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0x5, offset 0x2c
+ {value: 0x0000, lo: 0x07},
+ {value: 0xe185, lo: 0x80, hi: 0x8f},
+ {value: 0x0545, lo: 0x90, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0x98},
+ {value: 0x0008, lo: 0x99, hi: 0x99},
+ {value: 0x0018, lo: 0x9a, hi: 0x9f},
+ {value: 0x0040, lo: 0xa0, hi: 0xa0},
+ {value: 0x0008, lo: 0xa1, hi: 0xbf},
+ // Block 0x6, offset 0x34
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x0008, lo: 0x80, hi: 0x86},
+ {value: 0x0401, lo: 0x87, hi: 0x87},
+ {value: 0x0040, lo: 0x88, hi: 0x88},
+ {value: 0x0018, lo: 0x89, hi: 0x8a},
+ {value: 0x0040, lo: 0x8b, hi: 0x8c},
+ {value: 0x0018, lo: 0x8d, hi: 0x8f},
+ {value: 0x0040, lo: 0x90, hi: 0x90},
+ {value: 0x1308, lo: 0x91, hi: 0xbd},
+ {value: 0x0018, lo: 0xbe, hi: 0xbe},
+ {value: 0x1308, lo: 0xbf, hi: 0xbf},
+ // Block 0x7, offset 0x3f
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0018, lo: 0x80, hi: 0x80},
+ {value: 0x1308, lo: 0x81, hi: 0x82},
+ {value: 0x0018, lo: 0x83, hi: 0x83},
+ {value: 0x1308, lo: 0x84, hi: 0x85},
+ {value: 0x0018, lo: 0x86, hi: 0x86},
+ {value: 0x1308, lo: 0x87, hi: 0x87},
+ {value: 0x0040, lo: 0x88, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0xaa},
+ {value: 0x0040, lo: 0xab, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xb4},
+ {value: 0x0040, lo: 0xb5, hi: 0xbf},
+ // Block 0x8, offset 0x4b
+ {value: 0x0000, lo: 0x10},
+ {value: 0x0018, lo: 0x80, hi: 0x80},
+ {value: 0x0208, lo: 0x81, hi: 0x87},
+ {value: 0x0408, lo: 0x88, hi: 0x88},
+ {value: 0x0208, lo: 0x89, hi: 0x8a},
+ {value: 0x1308, lo: 0x8b, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa9},
+ {value: 0x0018, lo: 0xaa, hi: 0xad},
+ {value: 0x0208, lo: 0xae, hi: 0xaf},
+ {value: 0x1308, lo: 0xb0, hi: 0xb0},
+ {value: 0x0408, lo: 0xb1, hi: 0xb3},
+ {value: 0x0008, lo: 0xb4, hi: 0xb4},
+ {value: 0x0429, lo: 0xb5, hi: 0xb5},
+ {value: 0x0451, lo: 0xb6, hi: 0xb6},
+ {value: 0x0479, lo: 0xb7, hi: 0xb7},
+ {value: 0x04a1, lo: 0xb8, hi: 0xb8},
+ {value: 0x0208, lo: 0xb9, hi: 0xbf},
+ // Block 0x9, offset 0x5c
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0208, lo: 0x80, hi: 0x87},
+ {value: 0x0408, lo: 0x88, hi: 0x99},
+ {value: 0x0208, lo: 0x9a, hi: 0xbf},
+ // Block 0xa, offset 0x60
+ {value: 0x0000, lo: 0x0e},
+ {value: 0x1308, lo: 0x80, hi: 0x8a},
+ {value: 0x0040, lo: 0x8b, hi: 0x8c},
+ {value: 0x0408, lo: 0x8d, hi: 0x8d},
+ {value: 0x0208, lo: 0x8e, hi: 0x98},
+ {value: 0x0408, lo: 0x99, hi: 0x9b},
+ {value: 0x0208, lo: 0x9c, hi: 0xaa},
+ {value: 0x0408, lo: 0xab, hi: 0xac},
+ {value: 0x0208, lo: 0xad, hi: 0xb0},
+ {value: 0x0408, lo: 0xb1, hi: 0xb1},
+ {value: 0x0208, lo: 0xb2, hi: 0xb2},
+ {value: 0x0408, lo: 0xb3, hi: 0xb4},
+ {value: 0x0208, lo: 0xb5, hi: 0xb7},
+ {value: 0x0408, lo: 0xb8, hi: 0xb9},
+ {value: 0x0208, lo: 0xba, hi: 0xbf},
+ // Block 0xb, offset 0x6f
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0xa5},
+ {value: 0x1308, lo: 0xa6, hi: 0xb0},
+ {value: 0x0008, lo: 0xb1, hi: 0xb1},
+ {value: 0x0040, lo: 0xb2, hi: 0xbf},
+ // Block 0xc, offset 0x74
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0008, lo: 0x80, hi: 0x89},
+ {value: 0x0208, lo: 0x8a, hi: 0xaa},
+ {value: 0x1308, lo: 0xab, hi: 0xb3},
+ {value: 0x0008, lo: 0xb4, hi: 0xb5},
+ {value: 0x0018, lo: 0xb6, hi: 0xba},
+ {value: 0x0040, lo: 0xbb, hi: 0xbf},
+ // Block 0xd, offset 0x7b
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0008, lo: 0x80, hi: 0x95},
+ {value: 0x1308, lo: 0x96, hi: 0x99},
+ {value: 0x0008, lo: 0x9a, hi: 0x9a},
+ {value: 0x1308, lo: 0x9b, hi: 0xa3},
+ {value: 0x0008, lo: 0xa4, hi: 0xa4},
+ {value: 0x1308, lo: 0xa5, hi: 0xa7},
+ {value: 0x0008, lo: 0xa8, hi: 0xa8},
+ {value: 0x1308, lo: 0xa9, hi: 0xad},
+ {value: 0x0040, lo: 0xae, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0xe, offset 0x87
+ {value: 0x0000, lo: 0x0d},
+ {value: 0x0408, lo: 0x80, hi: 0x80},
+ {value: 0x0208, lo: 0x81, hi: 0x85},
+ {value: 0x0408, lo: 0x86, hi: 0x87},
+ {value: 0x0208, lo: 0x88, hi: 0x88},
+ {value: 0x0408, lo: 0x89, hi: 0x89},
+ {value: 0x0208, lo: 0x8a, hi: 0x93},
+ {value: 0x0408, lo: 0x94, hi: 0x94},
+ {value: 0x0208, lo: 0x95, hi: 0x95},
+ {value: 0x0008, lo: 0x96, hi: 0x98},
+ {value: 0x1308, lo: 0x99, hi: 0x9b},
+ {value: 0x0040, lo: 0x9c, hi: 0x9d},
+ {value: 0x0018, lo: 0x9e, hi: 0x9e},
+ {value: 0x0040, lo: 0x9f, hi: 0xbf},
+ // Block 0xf, offset 0x95
+ {value: 0x0000, lo: 0x0d},
+ {value: 0x0040, lo: 0x80, hi: 0x9f},
+ {value: 0x0208, lo: 0xa0, hi: 0xa9},
+ {value: 0x0408, lo: 0xaa, hi: 0xac},
+ {value: 0x0008, lo: 0xad, hi: 0xad},
+ {value: 0x0408, lo: 0xae, hi: 0xae},
+ {value: 0x0208, lo: 0xaf, hi: 0xb0},
+ {value: 0x0408, lo: 0xb1, hi: 0xb2},
+ {value: 0x0208, lo: 0xb3, hi: 0xb4},
+ {value: 0x0040, lo: 0xb5, hi: 0xb5},
+ {value: 0x0208, lo: 0xb6, hi: 0xb8},
+ {value: 0x0408, lo: 0xb9, hi: 0xb9},
+ {value: 0x0208, lo: 0xba, hi: 0xbd},
+ {value: 0x0040, lo: 0xbe, hi: 0xbf},
+ // Block 0x10, offset 0xa3
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0040, lo: 0x80, hi: 0x93},
+ {value: 0x1308, lo: 0x94, hi: 0xa1},
+ {value: 0x0040, lo: 0xa2, hi: 0xa2},
+ {value: 0x1308, lo: 0xa3, hi: 0xbf},
+ // Block 0x11, offset 0xa8
+ {value: 0x0000, lo: 0x08},
+ {value: 0x1308, lo: 0x80, hi: 0x82},
+ {value: 0x1008, lo: 0x83, hi: 0x83},
+ {value: 0x0008, lo: 0x84, hi: 0xb9},
+ {value: 0x1308, lo: 0xba, hi: 0xba},
+ {value: 0x1008, lo: 0xbb, hi: 0xbb},
+ {value: 0x1308, lo: 0xbc, hi: 0xbc},
+ {value: 0x0008, lo: 0xbd, hi: 0xbd},
+ {value: 0x1008, lo: 0xbe, hi: 0xbf},
+ // Block 0x12, offset 0xb1
+ {value: 0x0000, lo: 0x0f},
+ {value: 0x1308, lo: 0x80, hi: 0x80},
+ {value: 0x1008, lo: 0x81, hi: 0x82},
+ {value: 0x0040, lo: 0x83, hi: 0x85},
+ {value: 0x1008, lo: 0x86, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0x89},
+ {value: 0x1008, lo: 0x8a, hi: 0x8c},
+ {value: 0x1b08, lo: 0x8d, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x90},
+ {value: 0x0040, lo: 0x91, hi: 0x96},
+ {value: 0x1008, lo: 0x97, hi: 0x97},
+ {value: 0x0040, lo: 0x98, hi: 0xa5},
+ {value: 0x0008, lo: 0xa6, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xba},
+ {value: 0x0040, lo: 0xbb, hi: 0xbf},
+ // Block 0x13, offset 0xc1
+ {value: 0x0000, lo: 0x0d},
+ {value: 0x1308, lo: 0x80, hi: 0x80},
+ {value: 0x1008, lo: 0x81, hi: 0x83},
+ {value: 0x0040, lo: 0x84, hi: 0x84},
+ {value: 0x0008, lo: 0x85, hi: 0x8c},
+ {value: 0x0040, lo: 0x8d, hi: 0x8d},
+ {value: 0x0008, lo: 0x8e, hi: 0x90},
+ {value: 0x0040, lo: 0x91, hi: 0x91},
+ {value: 0x0008, lo: 0x92, hi: 0xa8},
+ {value: 0x0040, lo: 0xa9, hi: 0xa9},
+ {value: 0x0008, lo: 0xaa, hi: 0xb9},
+ {value: 0x0040, lo: 0xba, hi: 0xbc},
+ {value: 0x0008, lo: 0xbd, hi: 0xbd},
+ {value: 0x1308, lo: 0xbe, hi: 0xbf},
+ // Block 0x14, offset 0xcf
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x0040, lo: 0x80, hi: 0x80},
+ {value: 0x1308, lo: 0x81, hi: 0x81},
+ {value: 0x1008, lo: 0x82, hi: 0x83},
+ {value: 0x0040, lo: 0x84, hi: 0x84},
+ {value: 0x0008, lo: 0x85, hi: 0x8c},
+ {value: 0x0040, lo: 0x8d, hi: 0x8d},
+ {value: 0x0008, lo: 0x8e, hi: 0x90},
+ {value: 0x0040, lo: 0x91, hi: 0x91},
+ {value: 0x0008, lo: 0x92, hi: 0xba},
+ {value: 0x0040, lo: 0xbb, hi: 0xbc},
+ {value: 0x0008, lo: 0xbd, hi: 0xbd},
+ {value: 0x1008, lo: 0xbe, hi: 0xbf},
+ // Block 0x15, offset 0xdc
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0040, lo: 0x80, hi: 0x81},
+ {value: 0x1008, lo: 0x82, hi: 0x83},
+ {value: 0x0040, lo: 0x84, hi: 0x84},
+ {value: 0x0008, lo: 0x85, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0x99},
+ {value: 0x0008, lo: 0x9a, hi: 0xb1},
+ {value: 0x0040, lo: 0xb2, hi: 0xb2},
+ {value: 0x0008, lo: 0xb3, hi: 0xbb},
+ {value: 0x0040, lo: 0xbc, hi: 0xbc},
+ {value: 0x0008, lo: 0xbd, hi: 0xbd},
+ {value: 0x0040, lo: 0xbe, hi: 0xbf},
+ // Block 0x16, offset 0xe8
+ {value: 0x0000, lo: 0x10},
+ {value: 0x0008, lo: 0x80, hi: 0x86},
+ {value: 0x0040, lo: 0x87, hi: 0x89},
+ {value: 0x1b08, lo: 0x8a, hi: 0x8a},
+ {value: 0x0040, lo: 0x8b, hi: 0x8e},
+ {value: 0x1008, lo: 0x8f, hi: 0x91},
+ {value: 0x1308, lo: 0x92, hi: 0x94},
+ {value: 0x0040, lo: 0x95, hi: 0x95},
+ {value: 0x1308, lo: 0x96, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0x97},
+ {value: 0x1008, lo: 0x98, hi: 0x9f},
+ {value: 0x0040, lo: 0xa0, hi: 0xa5},
+ {value: 0x0008, lo: 0xa6, hi: 0xaf},
+ {value: 0x0040, lo: 0xb0, hi: 0xb1},
+ {value: 0x1008, lo: 0xb2, hi: 0xb3},
+ {value: 0x0018, lo: 0xb4, hi: 0xb4},
+ {value: 0x0040, lo: 0xb5, hi: 0xbf},
+ // Block 0x17, offset 0xf9
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0040, lo: 0x80, hi: 0x80},
+ {value: 0x0008, lo: 0x81, hi: 0xb0},
+ {value: 0x1308, lo: 0xb1, hi: 0xb1},
+ {value: 0x0008, lo: 0xb2, hi: 0xb2},
+ {value: 0x08f1, lo: 0xb3, hi: 0xb3},
+ {value: 0x1308, lo: 0xb4, hi: 0xb9},
+ {value: 0x1b08, lo: 0xba, hi: 0xba},
+ {value: 0x0040, lo: 0xbb, hi: 0xbe},
+ {value: 0x0018, lo: 0xbf, hi: 0xbf},
+ // Block 0x18, offset 0x103
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0008, lo: 0x80, hi: 0x86},
+ {value: 0x1308, lo: 0x87, hi: 0x8e},
+ {value: 0x0018, lo: 0x8f, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0018, lo: 0x9a, hi: 0x9b},
+ {value: 0x0040, lo: 0x9c, hi: 0xbf},
+ // Block 0x19, offset 0x10a
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x0008, lo: 0x80, hi: 0x84},
+ {value: 0x0040, lo: 0x85, hi: 0x85},
+ {value: 0x0008, lo: 0x86, hi: 0x86},
+ {value: 0x0040, lo: 0x87, hi: 0x87},
+ {value: 0x1308, lo: 0x88, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9b},
+ {value: 0x0961, lo: 0x9c, hi: 0x9c},
+ {value: 0x0999, lo: 0x9d, hi: 0x9d},
+ {value: 0x0008, lo: 0x9e, hi: 0x9f},
+ {value: 0x0040, lo: 0xa0, hi: 0xbf},
+ // Block 0x1a, offset 0x117
+ {value: 0x0000, lo: 0x10},
+ {value: 0x0008, lo: 0x80, hi: 0x80},
+ {value: 0x0018, lo: 0x81, hi: 0x8a},
+ {value: 0x0008, lo: 0x8b, hi: 0x8b},
+ {value: 0xe03d, lo: 0x8c, hi: 0x8c},
+ {value: 0x0018, lo: 0x8d, hi: 0x97},
+ {value: 0x1308, lo: 0x98, hi: 0x99},
+ {value: 0x0018, lo: 0x9a, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa9},
+ {value: 0x0018, lo: 0xaa, hi: 0xb4},
+ {value: 0x1308, lo: 0xb5, hi: 0xb5},
+ {value: 0x0018, lo: 0xb6, hi: 0xb6},
+ {value: 0x1308, lo: 0xb7, hi: 0xb7},
+ {value: 0x0018, lo: 0xb8, hi: 0xb8},
+ {value: 0x1308, lo: 0xb9, hi: 0xb9},
+ {value: 0x0018, lo: 0xba, hi: 0xbd},
+ {value: 0x1008, lo: 0xbe, hi: 0xbf},
+ // Block 0x1b, offset 0x128
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0018, lo: 0x80, hi: 0x85},
+ {value: 0x1308, lo: 0x86, hi: 0x86},
+ {value: 0x0018, lo: 0x87, hi: 0x8c},
+ {value: 0x0040, lo: 0x8d, hi: 0x8d},
+ {value: 0x0018, lo: 0x8e, hi: 0x9a},
+ {value: 0x0040, lo: 0x9b, hi: 0xbf},
+ // Block 0x1c, offset 0x12f
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x0008, lo: 0x80, hi: 0xaa},
+ {value: 0x1008, lo: 0xab, hi: 0xac},
+ {value: 0x1308, lo: 0xad, hi: 0xb0},
+ {value: 0x1008, lo: 0xb1, hi: 0xb1},
+ {value: 0x1308, lo: 0xb2, hi: 0xb7},
+ {value: 0x1008, lo: 0xb8, hi: 0xb8},
+ {value: 0x1b08, lo: 0xb9, hi: 0xba},
+ {value: 0x1008, lo: 0xbb, hi: 0xbc},
+ {value: 0x1308, lo: 0xbd, hi: 0xbe},
+ {value: 0x0008, lo: 0xbf, hi: 0xbf},
+ // Block 0x1d, offset 0x13a
+ {value: 0x0000, lo: 0x0e},
+ {value: 0x0008, lo: 0x80, hi: 0x89},
+ {value: 0x0018, lo: 0x8a, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x95},
+ {value: 0x1008, lo: 0x96, hi: 0x97},
+ {value: 0x1308, lo: 0x98, hi: 0x99},
+ {value: 0x0008, lo: 0x9a, hi: 0x9d},
+ {value: 0x1308, lo: 0x9e, hi: 0xa0},
+ {value: 0x0008, lo: 0xa1, hi: 0xa1},
+ {value: 0x1008, lo: 0xa2, hi: 0xa4},
+ {value: 0x0008, lo: 0xa5, hi: 0xa6},
+ {value: 0x1008, lo: 0xa7, hi: 0xad},
+ {value: 0x0008, lo: 0xae, hi: 0xb0},
+ {value: 0x1308, lo: 0xb1, hi: 0xb4},
+ {value: 0x0008, lo: 0xb5, hi: 0xbf},
+ // Block 0x1e, offset 0x149
+ {value: 0x0000, lo: 0x0d},
+ {value: 0x0008, lo: 0x80, hi: 0x81},
+ {value: 0x1308, lo: 0x82, hi: 0x82},
+ {value: 0x1008, lo: 0x83, hi: 0x84},
+ {value: 0x1308, lo: 0x85, hi: 0x86},
+ {value: 0x1008, lo: 0x87, hi: 0x8c},
+ {value: 0x1308, lo: 0x8d, hi: 0x8d},
+ {value: 0x0008, lo: 0x8e, hi: 0x8e},
+ {value: 0x1008, lo: 0x8f, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x1008, lo: 0x9a, hi: 0x9c},
+ {value: 0x1308, lo: 0x9d, hi: 0x9d},
+ {value: 0x0018, lo: 0x9e, hi: 0x9f},
+ {value: 0x0040, lo: 0xa0, hi: 0xbf},
+ // Block 0x1f, offset 0x157
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0040, lo: 0x80, hi: 0x86},
+ {value: 0x055d, lo: 0x87, hi: 0x87},
+ {value: 0x0040, lo: 0x88, hi: 0x8c},
+ {value: 0x055d, lo: 0x8d, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0xba},
+ {value: 0x0018, lo: 0xbb, hi: 0xbb},
+ {value: 0xe105, lo: 0xbc, hi: 0xbc},
+ {value: 0x0008, lo: 0xbd, hi: 0xbf},
+ // Block 0x20, offset 0x161
+ {value: 0x0000, lo: 0x01},
+ {value: 0x0018, lo: 0x80, hi: 0xbf},
+ // Block 0x21, offset 0x163
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0x9e},
+ {value: 0x0040, lo: 0x9f, hi: 0xa0},
+ {value: 0x0018, lo: 0xa1, hi: 0xbf},
+ // Block 0x22, offset 0x167
+ {value: 0x0000, lo: 0x01},
+ {value: 0x0008, lo: 0x80, hi: 0xbf},
+ // Block 0x23, offset 0x169
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0008, lo: 0x80, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0x89},
+ {value: 0x0008, lo: 0x8a, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0x97},
+ {value: 0x0008, lo: 0x98, hi: 0x98},
+ {value: 0x0040, lo: 0x99, hi: 0x99},
+ {value: 0x0008, lo: 0x9a, hi: 0x9d},
+ {value: 0x0040, lo: 0x9e, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xbf},
+ // Block 0x24, offset 0x175
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x0008, lo: 0x80, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0x89},
+ {value: 0x0008, lo: 0x8a, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0xb0},
+ {value: 0x0040, lo: 0xb1, hi: 0xb1},
+ {value: 0x0008, lo: 0xb2, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xb7},
+ {value: 0x0008, lo: 0xb8, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0x25, offset 0x180
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0008, lo: 0x80, hi: 0x80},
+ {value: 0x0040, lo: 0x81, hi: 0x81},
+ {value: 0x0008, lo: 0x82, hi: 0x85},
+ {value: 0x0040, lo: 0x86, hi: 0x87},
+ {value: 0x0008, lo: 0x88, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0x97},
+ {value: 0x0008, lo: 0x98, hi: 0xbf},
+ // Block 0x26, offset 0x188
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0008, lo: 0x80, hi: 0x90},
+ {value: 0x0040, lo: 0x91, hi: 0x91},
+ {value: 0x0008, lo: 0x92, hi: 0x95},
+ {value: 0x0040, lo: 0x96, hi: 0x97},
+ {value: 0x0008, lo: 0x98, hi: 0xbf},
+ // Block 0x27, offset 0x18e
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0008, lo: 0x80, hi: 0x9a},
+ {value: 0x0040, lo: 0x9b, hi: 0x9c},
+ {value: 0x1308, lo: 0x9d, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xbc},
+ {value: 0x0040, lo: 0xbd, hi: 0xbf},
+ // Block 0x28, offset 0x194
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xbf},
+ // Block 0x29, offset 0x199
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xb7},
+ {value: 0xe045, lo: 0xb8, hi: 0xbd},
+ {value: 0x0040, lo: 0xbe, hi: 0xbf},
+ // Block 0x2a, offset 0x19e
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0018, lo: 0x80, hi: 0x80},
+ {value: 0x0008, lo: 0x81, hi: 0xbf},
+ // Block 0x2b, offset 0x1a1
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0xac},
+ {value: 0x0018, lo: 0xad, hi: 0xae},
+ {value: 0x0008, lo: 0xaf, hi: 0xbf},
+ // Block 0x2c, offset 0x1a5
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0040, lo: 0x80, hi: 0x80},
+ {value: 0x0008, lo: 0x81, hi: 0x9a},
+ {value: 0x0018, lo: 0x9b, hi: 0x9c},
+ {value: 0x0040, lo: 0x9d, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xbf},
+ // Block 0x2d, offset 0x1ab
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0xaa},
+ {value: 0x0018, lo: 0xab, hi: 0xb0},
+ {value: 0x0008, lo: 0xb1, hi: 0xb8},
+ {value: 0x0040, lo: 0xb9, hi: 0xbf},
+ // Block 0x2e, offset 0x1b0
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0008, lo: 0x80, hi: 0x8c},
+ {value: 0x0040, lo: 0x8d, hi: 0x8d},
+ {value: 0x0008, lo: 0x8e, hi: 0x91},
+ {value: 0x1308, lo: 0x92, hi: 0x93},
+ {value: 0x1b08, lo: 0x94, hi: 0x94},
+ {value: 0x0040, lo: 0x95, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xb1},
+ {value: 0x1308, lo: 0xb2, hi: 0xb3},
+ {value: 0x1b08, lo: 0xb4, hi: 0xb4},
+ {value: 0x0018, lo: 0xb5, hi: 0xb6},
+ {value: 0x0040, lo: 0xb7, hi: 0xbf},
+ // Block 0x2f, offset 0x1bc
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0008, lo: 0x80, hi: 0x91},
+ {value: 0x1308, lo: 0x92, hi: 0x93},
+ {value: 0x0040, lo: 0x94, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xac},
+ {value: 0x0040, lo: 0xad, hi: 0xad},
+ {value: 0x0008, lo: 0xae, hi: 0xb0},
+ {value: 0x0040, lo: 0xb1, hi: 0xb1},
+ {value: 0x1308, lo: 0xb2, hi: 0xb3},
+ {value: 0x0040, lo: 0xb4, hi: 0xbf},
+ // Block 0x30, offset 0x1c6
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0008, lo: 0x80, hi: 0xb3},
+ {value: 0x1340, lo: 0xb4, hi: 0xb5},
+ {value: 0x1008, lo: 0xb6, hi: 0xb6},
+ {value: 0x1308, lo: 0xb7, hi: 0xbd},
+ {value: 0x1008, lo: 0xbe, hi: 0xbf},
+ // Block 0x31, offset 0x1cc
+ {value: 0x0000, lo: 0x10},
+ {value: 0x1008, lo: 0x80, hi: 0x85},
+ {value: 0x1308, lo: 0x86, hi: 0x86},
+ {value: 0x1008, lo: 0x87, hi: 0x88},
+ {value: 0x1308, lo: 0x89, hi: 0x91},
+ {value: 0x1b08, lo: 0x92, hi: 0x92},
+ {value: 0x1308, lo: 0x93, hi: 0x93},
+ {value: 0x0018, lo: 0x94, hi: 0x96},
+ {value: 0x0008, lo: 0x97, hi: 0x97},
+ {value: 0x0018, lo: 0x98, hi: 0x9b},
+ {value: 0x0008, lo: 0x9c, hi: 0x9c},
+ {value: 0x1308, lo: 0x9d, hi: 0x9d},
+ {value: 0x0040, lo: 0x9e, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa9},
+ {value: 0x0040, lo: 0xaa, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xb9},
+ {value: 0x0040, lo: 0xba, hi: 0xbf},
+ // Block 0x32, offset 0x1dd
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0018, lo: 0x80, hi: 0x85},
+ {value: 0x0040, lo: 0x86, hi: 0x86},
+ {value: 0x0218, lo: 0x87, hi: 0x87},
+ {value: 0x0018, lo: 0x88, hi: 0x8a},
+ {value: 0x13c0, lo: 0x8b, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9f},
+ {value: 0x0208, lo: 0xa0, hi: 0xbf},
+ // Block 0x33, offset 0x1e7
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0208, lo: 0x80, hi: 0xb7},
+ {value: 0x0040, lo: 0xb8, hi: 0xbf},
+ // Block 0x34, offset 0x1ea
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0008, lo: 0x80, hi: 0x84},
+ {value: 0x1308, lo: 0x85, hi: 0x86},
+ {value: 0x0208, lo: 0x87, hi: 0xa8},
+ {value: 0x1308, lo: 0xa9, hi: 0xa9},
+ {value: 0x0208, lo: 0xaa, hi: 0xaa},
+ {value: 0x0040, lo: 0xab, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0x35, offset 0x1f2
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xbf},
+ // Block 0x36, offset 0x1f5
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x0008, lo: 0x80, hi: 0x9e},
+ {value: 0x0040, lo: 0x9f, hi: 0x9f},
+ {value: 0x1308, lo: 0xa0, hi: 0xa2},
+ {value: 0x1008, lo: 0xa3, hi: 0xa6},
+ {value: 0x1308, lo: 0xa7, hi: 0xa8},
+ {value: 0x1008, lo: 0xa9, hi: 0xab},
+ {value: 0x0040, lo: 0xac, hi: 0xaf},
+ {value: 0x1008, lo: 0xb0, hi: 0xb1},
+ {value: 0x1308, lo: 0xb2, hi: 0xb2},
+ {value: 0x1008, lo: 0xb3, hi: 0xb8},
+ {value: 0x1308, lo: 0xb9, hi: 0xbb},
+ {value: 0x0040, lo: 0xbc, hi: 0xbf},
+ // Block 0x37, offset 0x202
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0018, lo: 0x80, hi: 0x80},
+ {value: 0x0040, lo: 0x81, hi: 0x83},
+ {value: 0x0018, lo: 0x84, hi: 0x85},
+ {value: 0x0008, lo: 0x86, hi: 0xad},
+ {value: 0x0040, lo: 0xae, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xb4},
+ {value: 0x0040, lo: 0xb5, hi: 0xbf},
+ // Block 0x38, offset 0x20a
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0xab},
+ {value: 0x0040, lo: 0xac, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0x39, offset 0x20e
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0008, lo: 0x80, hi: 0x89},
+ {value: 0x0040, lo: 0x8a, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0028, lo: 0x9a, hi: 0x9a},
+ {value: 0x0040, lo: 0x9b, hi: 0x9d},
+ {value: 0x0018, lo: 0x9e, hi: 0xbf},
+ // Block 0x3a, offset 0x215
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0008, lo: 0x80, hi: 0x96},
+ {value: 0x1308, lo: 0x97, hi: 0x98},
+ {value: 0x1008, lo: 0x99, hi: 0x9a},
+ {value: 0x1308, lo: 0x9b, hi: 0x9b},
+ {value: 0x0040, lo: 0x9c, hi: 0x9d},
+ {value: 0x0018, lo: 0x9e, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xbf},
+ // Block 0x3b, offset 0x21d
+ {value: 0x0000, lo: 0x0f},
+ {value: 0x0008, lo: 0x80, hi: 0x94},
+ {value: 0x1008, lo: 0x95, hi: 0x95},
+ {value: 0x1308, lo: 0x96, hi: 0x96},
+ {value: 0x1008, lo: 0x97, hi: 0x97},
+ {value: 0x1308, lo: 0x98, hi: 0x9e},
+ {value: 0x0040, lo: 0x9f, hi: 0x9f},
+ {value: 0x1b08, lo: 0xa0, hi: 0xa0},
+ {value: 0x1008, lo: 0xa1, hi: 0xa1},
+ {value: 0x1308, lo: 0xa2, hi: 0xa2},
+ {value: 0x1008, lo: 0xa3, hi: 0xa4},
+ {value: 0x1308, lo: 0xa5, hi: 0xac},
+ {value: 0x1008, lo: 0xad, hi: 0xb2},
+ {value: 0x1308, lo: 0xb3, hi: 0xbc},
+ {value: 0x0040, lo: 0xbd, hi: 0xbe},
+ {value: 0x1308, lo: 0xbf, hi: 0xbf},
+ // Block 0x3c, offset 0x22d
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0008, lo: 0x80, hi: 0x89},
+ {value: 0x0040, lo: 0x8a, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xa6},
+ {value: 0x0008, lo: 0xa7, hi: 0xa7},
+ {value: 0x0018, lo: 0xa8, hi: 0xad},
+ {value: 0x0040, lo: 0xae, hi: 0xaf},
+ {value: 0x1308, lo: 0xb0, hi: 0xbd},
+ {value: 0x1318, lo: 0xbe, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0x3d, offset 0x239
+ {value: 0x0000, lo: 0x01},
+ {value: 0x0040, lo: 0x80, hi: 0xbf},
+ // Block 0x3e, offset 0x23b
+ {value: 0x0000, lo: 0x09},
+ {value: 0x1308, lo: 0x80, hi: 0x83},
+ {value: 0x1008, lo: 0x84, hi: 0x84},
+ {value: 0x0008, lo: 0x85, hi: 0xb3},
+ {value: 0x1308, lo: 0xb4, hi: 0xb4},
+ {value: 0x1008, lo: 0xb5, hi: 0xb5},
+ {value: 0x1308, lo: 0xb6, hi: 0xba},
+ {value: 0x1008, lo: 0xbb, hi: 0xbb},
+ {value: 0x1308, lo: 0xbc, hi: 0xbc},
+ {value: 0x1008, lo: 0xbd, hi: 0xbf},
+ // Block 0x3f, offset 0x245
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x1008, lo: 0x80, hi: 0x81},
+ {value: 0x1308, lo: 0x82, hi: 0x82},
+ {value: 0x1008, lo: 0x83, hi: 0x83},
+ {value: 0x1808, lo: 0x84, hi: 0x84},
+ {value: 0x0008, lo: 0x85, hi: 0x8b},
+ {value: 0x0040, lo: 0x8c, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0018, lo: 0x9a, hi: 0xaa},
+ {value: 0x1308, lo: 0xab, hi: 0xb3},
+ {value: 0x0018, lo: 0xb4, hi: 0xbc},
+ {value: 0x0040, lo: 0xbd, hi: 0xbf},
+ // Block 0x40, offset 0x251
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x1308, lo: 0x80, hi: 0x81},
+ {value: 0x1008, lo: 0x82, hi: 0x82},
+ {value: 0x0008, lo: 0x83, hi: 0xa0},
+ {value: 0x1008, lo: 0xa1, hi: 0xa1},
+ {value: 0x1308, lo: 0xa2, hi: 0xa5},
+ {value: 0x1008, lo: 0xa6, hi: 0xa7},
+ {value: 0x1308, lo: 0xa8, hi: 0xa9},
+ {value: 0x1808, lo: 0xaa, hi: 0xaa},
+ {value: 0x1b08, lo: 0xab, hi: 0xab},
+ {value: 0x1308, lo: 0xac, hi: 0xad},
+ {value: 0x0008, lo: 0xae, hi: 0xbf},
+ // Block 0x41, offset 0x25d
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0008, lo: 0x80, hi: 0xa5},
+ {value: 0x1308, lo: 0xa6, hi: 0xa6},
+ {value: 0x1008, lo: 0xa7, hi: 0xa7},
+ {value: 0x1308, lo: 0xa8, hi: 0xa9},
+ {value: 0x1008, lo: 0xaa, hi: 0xac},
+ {value: 0x1308, lo: 0xad, hi: 0xad},
+ {value: 0x1008, lo: 0xae, hi: 0xae},
+ {value: 0x1308, lo: 0xaf, hi: 0xb1},
+ {value: 0x1808, lo: 0xb2, hi: 0xb3},
+ {value: 0x0040, lo: 0xb4, hi: 0xbb},
+ {value: 0x0018, lo: 0xbc, hi: 0xbf},
+ // Block 0x42, offset 0x269
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0008, lo: 0x80, hi: 0xa3},
+ {value: 0x1008, lo: 0xa4, hi: 0xab},
+ {value: 0x1308, lo: 0xac, hi: 0xb3},
+ {value: 0x1008, lo: 0xb4, hi: 0xb5},
+ {value: 0x1308, lo: 0xb6, hi: 0xb7},
+ {value: 0x0040, lo: 0xb8, hi: 0xba},
+ {value: 0x0018, lo: 0xbb, hi: 0xbf},
+ // Block 0x43, offset 0x271
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0x89},
+ {value: 0x0040, lo: 0x8a, hi: 0x8c},
+ {value: 0x0008, lo: 0x8d, hi: 0xbd},
+ {value: 0x0018, lo: 0xbe, hi: 0xbf},
+ // Block 0x44, offset 0x276
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0e29, lo: 0x80, hi: 0x80},
+ {value: 0x0e41, lo: 0x81, hi: 0x81},
+ {value: 0x0e59, lo: 0x82, hi: 0x82},
+ {value: 0x0e71, lo: 0x83, hi: 0x83},
+ {value: 0x0e89, lo: 0x84, hi: 0x85},
+ {value: 0x0ea1, lo: 0x86, hi: 0x86},
+ {value: 0x0eb9, lo: 0x87, hi: 0x87},
+ {value: 0x057d, lo: 0x88, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0xbf},
+ // Block 0x45, offset 0x280
+ {value: 0x0000, lo: 0x10},
+ {value: 0x0018, lo: 0x80, hi: 0x87},
+ {value: 0x0040, lo: 0x88, hi: 0x8f},
+ {value: 0x1308, lo: 0x90, hi: 0x92},
+ {value: 0x0018, lo: 0x93, hi: 0x93},
+ {value: 0x1308, lo: 0x94, hi: 0xa0},
+ {value: 0x1008, lo: 0xa1, hi: 0xa1},
+ {value: 0x1308, lo: 0xa2, hi: 0xa8},
+ {value: 0x0008, lo: 0xa9, hi: 0xac},
+ {value: 0x1308, lo: 0xad, hi: 0xad},
+ {value: 0x0008, lo: 0xae, hi: 0xb1},
+ {value: 0x1008, lo: 0xb2, hi: 0xb3},
+ {value: 0x1308, lo: 0xb4, hi: 0xb4},
+ {value: 0x0008, lo: 0xb5, hi: 0xb6},
+ {value: 0x0040, lo: 0xb7, hi: 0xb7},
+ {value: 0x1308, lo: 0xb8, hi: 0xb9},
+ {value: 0x0040, lo: 0xba, hi: 0xbf},
+ // Block 0x46, offset 0x291
+ {value: 0x0000, lo: 0x03},
+ {value: 0x1308, lo: 0x80, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xba},
+ {value: 0x1308, lo: 0xbb, hi: 0xbf},
+ // Block 0x47, offset 0x295
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x0008, lo: 0x80, hi: 0x87},
+ {value: 0xe045, lo: 0x88, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x95},
+ {value: 0x0040, lo: 0x96, hi: 0x97},
+ {value: 0xe045, lo: 0x98, hi: 0x9d},
+ {value: 0x0040, lo: 0x9e, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa7},
+ {value: 0xe045, lo: 0xa8, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xb7},
+ {value: 0xe045, lo: 0xb8, hi: 0xbf},
+ // Block 0x48, offset 0x2a0
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0040, lo: 0x80, hi: 0x8f},
+ {value: 0x1318, lo: 0x90, hi: 0xb0},
+ {value: 0x0040, lo: 0xb1, hi: 0xbf},
+ // Block 0x49, offset 0x2a4
+ {value: 0x0000, lo: 0x08},
+ {value: 0x0018, lo: 0x80, hi: 0x82},
+ {value: 0x0040, lo: 0x83, hi: 0x83},
+ {value: 0x0008, lo: 0x84, hi: 0x84},
+ {value: 0x0018, lo: 0x85, hi: 0x88},
+ {value: 0x24c1, lo: 0x89, hi: 0x89},
+ {value: 0x0018, lo: 0x8a, hi: 0x8b},
+ {value: 0x0040, lo: 0x8c, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0xbf},
+ // Block 0x4a, offset 0x2ad
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0018, lo: 0x80, hi: 0xab},
+ {value: 0x24f1, lo: 0xac, hi: 0xac},
+ {value: 0x2529, lo: 0xad, hi: 0xad},
+ {value: 0x0018, lo: 0xae, hi: 0xae},
+ {value: 0x2579, lo: 0xaf, hi: 0xaf},
+ {value: 0x25b1, lo: 0xb0, hi: 0xb0},
+ {value: 0x0018, lo: 0xb1, hi: 0xbf},
+ // Block 0x4b, offset 0x2b5
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0018, lo: 0x80, hi: 0x9f},
+ {value: 0x0080, lo: 0xa0, hi: 0xa0},
+ {value: 0x0018, lo: 0xa1, hi: 0xad},
+ {value: 0x0080, lo: 0xae, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xbf},
+ // Block 0x4c, offset 0x2bb
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0018, lo: 0x80, hi: 0xa8},
+ {value: 0x09c5, lo: 0xa9, hi: 0xa9},
+ {value: 0x09e5, lo: 0xaa, hi: 0xaa},
+ {value: 0x0018, lo: 0xab, hi: 0xbf},
+ // Block 0x4d, offset 0x2c0
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0018, lo: 0x80, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0x4e, offset 0x2c3
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0018, lo: 0x80, hi: 0xa6},
+ {value: 0x0040, lo: 0xa7, hi: 0xbf},
+ // Block 0x4f, offset 0x2c6
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0x8b},
+ {value: 0x28c1, lo: 0x8c, hi: 0x8c},
+ {value: 0x0018, lo: 0x8d, hi: 0xbf},
+ // Block 0x50, offset 0x2ca
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0018, lo: 0x80, hi: 0xb3},
+ {value: 0x0e66, lo: 0xb4, hi: 0xb4},
+ {value: 0x292a, lo: 0xb5, hi: 0xb5},
+ {value: 0x0e86, lo: 0xb6, hi: 0xb6},
+ {value: 0x0018, lo: 0xb7, hi: 0xbf},
+ // Block 0x51, offset 0x2d0
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0x9b},
+ {value: 0x2941, lo: 0x9c, hi: 0x9c},
+ {value: 0x0018, lo: 0x9d, hi: 0xbf},
+ // Block 0x52, offset 0x2d4
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0xb3},
+ {value: 0x0040, lo: 0xb4, hi: 0xb5},
+ {value: 0x0018, lo: 0xb6, hi: 0xbf},
+ // Block 0x53, offset 0x2d8
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0018, lo: 0x80, hi: 0x95},
+ {value: 0x0040, lo: 0x96, hi: 0x97},
+ {value: 0x0018, lo: 0x98, hi: 0xb9},
+ {value: 0x0040, lo: 0xba, hi: 0xbc},
+ {value: 0x0018, lo: 0xbd, hi: 0xbf},
+ // Block 0x54, offset 0x2de
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0018, lo: 0x80, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0x89},
+ {value: 0x0018, lo: 0x8a, hi: 0x91},
+ {value: 0x0040, lo: 0x92, hi: 0xab},
+ {value: 0x0018, lo: 0xac, hi: 0xaf},
+ {value: 0x0040, lo: 0xb0, hi: 0xbf},
+ // Block 0x55, offset 0x2e5
+ {value: 0x0000, lo: 0x05},
+ {value: 0xe185, lo: 0x80, hi: 0x8f},
+ {value: 0x03f5, lo: 0x90, hi: 0x9f},
+ {value: 0x0ea5, lo: 0xa0, hi: 0xae},
+ {value: 0x0040, lo: 0xaf, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0x56, offset 0x2eb
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0008, lo: 0x80, hi: 0xa5},
+ {value: 0x0040, lo: 0xa6, hi: 0xa6},
+ {value: 0x0008, lo: 0xa7, hi: 0xa7},
+ {value: 0x0040, lo: 0xa8, hi: 0xac},
+ {value: 0x0008, lo: 0xad, hi: 0xad},
+ {value: 0x0040, lo: 0xae, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0x57, offset 0x2f3
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0008, lo: 0x80, hi: 0xa7},
+ {value: 0x0040, lo: 0xa8, hi: 0xae},
+ {value: 0xe075, lo: 0xaf, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xb0},
+ {value: 0x0040, lo: 0xb1, hi: 0xbe},
+ {value: 0x1b08, lo: 0xbf, hi: 0xbf},
+ // Block 0x58, offset 0x2fa
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x0008, lo: 0x80, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa6},
+ {value: 0x0040, lo: 0xa7, hi: 0xa7},
+ {value: 0x0008, lo: 0xa8, hi: 0xae},
+ {value: 0x0040, lo: 0xaf, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xb6},
+ {value: 0x0040, lo: 0xb7, hi: 0xb7},
+ {value: 0x0008, lo: 0xb8, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0x59, offset 0x305
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0008, lo: 0x80, hi: 0x86},
+ {value: 0x0040, lo: 0x87, hi: 0x87},
+ {value: 0x0008, lo: 0x88, hi: 0x8e},
+ {value: 0x0040, lo: 0x8f, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0x97},
+ {value: 0x0008, lo: 0x98, hi: 0x9e},
+ {value: 0x0040, lo: 0x9f, hi: 0x9f},
+ {value: 0x1308, lo: 0xa0, hi: 0xbf},
+ // Block 0x5a, offset 0x30f
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0xae},
+ {value: 0x0008, lo: 0xaf, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xbf},
+ // Block 0x5b, offset 0x313
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0018, lo: 0x80, hi: 0x84},
+ {value: 0x0040, lo: 0x85, hi: 0xbf},
+ // Block 0x5c, offset 0x316
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0018, lo: 0x80, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9a},
+ {value: 0x0018, lo: 0x9b, hi: 0x9e},
+ {value: 0x0edd, lo: 0x9f, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xbf},
+ // Block 0x5d, offset 0x31c
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0xb2},
+ {value: 0x0efd, lo: 0xb3, hi: 0xb3},
+ {value: 0x0040, lo: 0xb4, hi: 0xbf},
+ // Block 0x5e, offset 0x320
+ {value: 0x0020, lo: 0x01},
+ {value: 0x0f1d, lo: 0x80, hi: 0xbf},
+ // Block 0x5f, offset 0x322
+ {value: 0x0020, lo: 0x02},
+ {value: 0x171d, lo: 0x80, hi: 0x8f},
+ {value: 0x18fd, lo: 0x90, hi: 0xbf},
+ // Block 0x60, offset 0x325
+ {value: 0x0020, lo: 0x01},
+ {value: 0x1efd, lo: 0x80, hi: 0xbf},
+ // Block 0x61, offset 0x327
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0040, lo: 0x80, hi: 0x80},
+ {value: 0x0008, lo: 0x81, hi: 0xbf},
+ // Block 0x62, offset 0x32a
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0008, lo: 0x80, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0x98},
+ {value: 0x1308, lo: 0x99, hi: 0x9a},
+ {value: 0x29e2, lo: 0x9b, hi: 0x9b},
+ {value: 0x2a0a, lo: 0x9c, hi: 0x9c},
+ {value: 0x0008, lo: 0x9d, hi: 0x9e},
+ {value: 0x2a31, lo: 0x9f, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xa0},
+ {value: 0x0008, lo: 0xa1, hi: 0xbf},
+ // Block 0x63, offset 0x334
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0xbe},
+ {value: 0x2a69, lo: 0xbf, hi: 0xbf},
+ // Block 0x64, offset 0x337
+ {value: 0x0000, lo: 0x0e},
+ {value: 0x0040, lo: 0x80, hi: 0x84},
+ {value: 0x0008, lo: 0x85, hi: 0xad},
+ {value: 0x0040, lo: 0xae, hi: 0xb0},
+ {value: 0x2a1d, lo: 0xb1, hi: 0xb1},
+ {value: 0x2a3d, lo: 0xb2, hi: 0xb2},
+ {value: 0x2a5d, lo: 0xb3, hi: 0xb3},
+ {value: 0x2a7d, lo: 0xb4, hi: 0xb4},
+ {value: 0x2a5d, lo: 0xb5, hi: 0xb5},
+ {value: 0x2a9d, lo: 0xb6, hi: 0xb6},
+ {value: 0x2abd, lo: 0xb7, hi: 0xb7},
+ {value: 0x2add, lo: 0xb8, hi: 0xb9},
+ {value: 0x2afd, lo: 0xba, hi: 0xbb},
+ {value: 0x2b1d, lo: 0xbc, hi: 0xbd},
+ {value: 0x2afd, lo: 0xbe, hi: 0xbf},
+ // Block 0x65, offset 0x346
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0xa3},
+ {value: 0x0040, lo: 0xa4, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0x66, offset 0x34a
+ {value: 0x0030, lo: 0x04},
+ {value: 0x2aa2, lo: 0x80, hi: 0x9d},
+ {value: 0x305a, lo: 0x9e, hi: 0x9e},
+ {value: 0x0040, lo: 0x9f, hi: 0x9f},
+ {value: 0x30a2, lo: 0xa0, hi: 0xbf},
+ // Block 0x67, offset 0x34f
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0x95},
+ {value: 0x0040, lo: 0x96, hi: 0xbf},
+ // Block 0x68, offset 0x352
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0x8c},
+ {value: 0x0040, lo: 0x8d, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0xbf},
+ // Block 0x69, offset 0x356
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0018, lo: 0x80, hi: 0x86},
+ {value: 0x0040, lo: 0x87, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0xbd},
+ {value: 0x0018, lo: 0xbe, hi: 0xbf},
+ // Block 0x6a, offset 0x35b
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0x8c},
+ {value: 0x0018, lo: 0x8d, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0xab},
+ {value: 0x0040, lo: 0xac, hi: 0xbf},
+ // Block 0x6b, offset 0x360
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0008, lo: 0x80, hi: 0xa5},
+ {value: 0x0018, lo: 0xa6, hi: 0xaf},
+ {value: 0x1308, lo: 0xb0, hi: 0xb1},
+ {value: 0x0018, lo: 0xb2, hi: 0xb7},
+ {value: 0x0040, lo: 0xb8, hi: 0xbf},
+ // Block 0x6c, offset 0x366
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0040, lo: 0x80, hi: 0xb6},
+ {value: 0x0008, lo: 0xb7, hi: 0xb7},
+ {value: 0x2009, lo: 0xb8, hi: 0xb8},
+ {value: 0x6e89, lo: 0xb9, hi: 0xb9},
+ {value: 0x0008, lo: 0xba, hi: 0xbf},
+ // Block 0x6d, offset 0x36c
+ {value: 0x0000, lo: 0x0e},
+ {value: 0x0008, lo: 0x80, hi: 0x81},
+ {value: 0x1308, lo: 0x82, hi: 0x82},
+ {value: 0x0008, lo: 0x83, hi: 0x85},
+ {value: 0x1b08, lo: 0x86, hi: 0x86},
+ {value: 0x0008, lo: 0x87, hi: 0x8a},
+ {value: 0x1308, lo: 0x8b, hi: 0x8b},
+ {value: 0x0008, lo: 0x8c, hi: 0xa2},
+ {value: 0x1008, lo: 0xa3, hi: 0xa4},
+ {value: 0x1308, lo: 0xa5, hi: 0xa6},
+ {value: 0x1008, lo: 0xa7, hi: 0xa7},
+ {value: 0x0018, lo: 0xa8, hi: 0xab},
+ {value: 0x0040, lo: 0xac, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xb9},
+ {value: 0x0040, lo: 0xba, hi: 0xbf},
+ // Block 0x6e, offset 0x37b
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0208, lo: 0x80, hi: 0xb1},
+ {value: 0x0108, lo: 0xb2, hi: 0xb2},
+ {value: 0x0008, lo: 0xb3, hi: 0xb3},
+ {value: 0x0018, lo: 0xb4, hi: 0xb7},
+ {value: 0x0040, lo: 0xb8, hi: 0xbf},
+ // Block 0x6f, offset 0x381
+ {value: 0x0000, lo: 0x03},
+ {value: 0x1008, lo: 0x80, hi: 0x81},
+ {value: 0x0008, lo: 0x82, hi: 0xb3},
+ {value: 0x1008, lo: 0xb4, hi: 0xbf},
+ // Block 0x70, offset 0x385
+ {value: 0x0000, lo: 0x0e},
+ {value: 0x1008, lo: 0x80, hi: 0x83},
+ {value: 0x1b08, lo: 0x84, hi: 0x84},
+ {value: 0x1308, lo: 0x85, hi: 0x85},
+ {value: 0x0040, lo: 0x86, hi: 0x8d},
+ {value: 0x0018, lo: 0x8e, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9f},
+ {value: 0x1308, lo: 0xa0, hi: 0xb1},
+ {value: 0x0008, lo: 0xb2, hi: 0xb7},
+ {value: 0x0018, lo: 0xb8, hi: 0xba},
+ {value: 0x0008, lo: 0xbb, hi: 0xbb},
+ {value: 0x0018, lo: 0xbc, hi: 0xbc},
+ {value: 0x0008, lo: 0xbd, hi: 0xbd},
+ {value: 0x0040, lo: 0xbe, hi: 0xbf},
+ // Block 0x71, offset 0x394
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0xa5},
+ {value: 0x1308, lo: 0xa6, hi: 0xad},
+ {value: 0x0018, lo: 0xae, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0x72, offset 0x399
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0008, lo: 0x80, hi: 0x86},
+ {value: 0x1308, lo: 0x87, hi: 0x91},
+ {value: 0x1008, lo: 0x92, hi: 0x92},
+ {value: 0x1808, lo: 0x93, hi: 0x93},
+ {value: 0x0040, lo: 0x94, hi: 0x9e},
+ {value: 0x0018, lo: 0x9f, hi: 0xbc},
+ {value: 0x0040, lo: 0xbd, hi: 0xbf},
+ // Block 0x73, offset 0x3a1
+ {value: 0x0000, lo: 0x09},
+ {value: 0x1308, lo: 0x80, hi: 0x82},
+ {value: 0x1008, lo: 0x83, hi: 0x83},
+ {value: 0x0008, lo: 0x84, hi: 0xb2},
+ {value: 0x1308, lo: 0xb3, hi: 0xb3},
+ {value: 0x1008, lo: 0xb4, hi: 0xb5},
+ {value: 0x1308, lo: 0xb6, hi: 0xb9},
+ {value: 0x1008, lo: 0xba, hi: 0xbb},
+ {value: 0x1308, lo: 0xbc, hi: 0xbc},
+ {value: 0x1008, lo: 0xbd, hi: 0xbf},
+ // Block 0x74, offset 0x3ab
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x1808, lo: 0x80, hi: 0x80},
+ {value: 0x0018, lo: 0x81, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8e},
+ {value: 0x0008, lo: 0x8f, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9d},
+ {value: 0x0018, lo: 0x9e, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa4},
+ {value: 0x1308, lo: 0xa5, hi: 0xa5},
+ {value: 0x0008, lo: 0xa6, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0x75, offset 0x3b6
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0008, lo: 0x80, hi: 0xa8},
+ {value: 0x1308, lo: 0xa9, hi: 0xae},
+ {value: 0x1008, lo: 0xaf, hi: 0xb0},
+ {value: 0x1308, lo: 0xb1, hi: 0xb2},
+ {value: 0x1008, lo: 0xb3, hi: 0xb4},
+ {value: 0x1308, lo: 0xb5, hi: 0xb6},
+ {value: 0x0040, lo: 0xb7, hi: 0xbf},
+ // Block 0x76, offset 0x3be
+ {value: 0x0000, lo: 0x10},
+ {value: 0x0008, lo: 0x80, hi: 0x82},
+ {value: 0x1308, lo: 0x83, hi: 0x83},
+ {value: 0x0008, lo: 0x84, hi: 0x8b},
+ {value: 0x1308, lo: 0x8c, hi: 0x8c},
+ {value: 0x1008, lo: 0x8d, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9b},
+ {value: 0x0018, lo: 0x9c, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xb6},
+ {value: 0x0018, lo: 0xb7, hi: 0xb9},
+ {value: 0x0008, lo: 0xba, hi: 0xba},
+ {value: 0x1008, lo: 0xbb, hi: 0xbb},
+ {value: 0x1308, lo: 0xbc, hi: 0xbc},
+ {value: 0x1008, lo: 0xbd, hi: 0xbd},
+ {value: 0x0008, lo: 0xbe, hi: 0xbf},
+ // Block 0x77, offset 0x3cf
+ {value: 0x0000, lo: 0x08},
+ {value: 0x0008, lo: 0x80, hi: 0xaf},
+ {value: 0x1308, lo: 0xb0, hi: 0xb0},
+ {value: 0x0008, lo: 0xb1, hi: 0xb1},
+ {value: 0x1308, lo: 0xb2, hi: 0xb4},
+ {value: 0x0008, lo: 0xb5, hi: 0xb6},
+ {value: 0x1308, lo: 0xb7, hi: 0xb8},
+ {value: 0x0008, lo: 0xb9, hi: 0xbd},
+ {value: 0x1308, lo: 0xbe, hi: 0xbf},
+ // Block 0x78, offset 0x3d8
+ {value: 0x0000, lo: 0x0f},
+ {value: 0x0008, lo: 0x80, hi: 0x80},
+ {value: 0x1308, lo: 0x81, hi: 0x81},
+ {value: 0x0008, lo: 0x82, hi: 0x82},
+ {value: 0x0040, lo: 0x83, hi: 0x9a},
+ {value: 0x0008, lo: 0x9b, hi: 0x9d},
+ {value: 0x0018, lo: 0x9e, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xaa},
+ {value: 0x1008, lo: 0xab, hi: 0xab},
+ {value: 0x1308, lo: 0xac, hi: 0xad},
+ {value: 0x1008, lo: 0xae, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xb1},
+ {value: 0x0008, lo: 0xb2, hi: 0xb4},
+ {value: 0x1008, lo: 0xb5, hi: 0xb5},
+ {value: 0x1b08, lo: 0xb6, hi: 0xb6},
+ {value: 0x0040, lo: 0xb7, hi: 0xbf},
+ // Block 0x79, offset 0x3e8
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x0040, lo: 0x80, hi: 0x80},
+ {value: 0x0008, lo: 0x81, hi: 0x86},
+ {value: 0x0040, lo: 0x87, hi: 0x88},
+ {value: 0x0008, lo: 0x89, hi: 0x8e},
+ {value: 0x0040, lo: 0x8f, hi: 0x90},
+ {value: 0x0008, lo: 0x91, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa6},
+ {value: 0x0040, lo: 0xa7, hi: 0xa7},
+ {value: 0x0008, lo: 0xa8, hi: 0xae},
+ {value: 0x0040, lo: 0xaf, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0x7a, offset 0x3f5
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0008, lo: 0x80, hi: 0x9a},
+ {value: 0x0018, lo: 0x9b, hi: 0x9b},
+ {value: 0x4465, lo: 0x9c, hi: 0x9c},
+ {value: 0x447d, lo: 0x9d, hi: 0x9d},
+ {value: 0x2971, lo: 0x9e, hi: 0x9e},
+ {value: 0xe06d, lo: 0x9f, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa5},
+ {value: 0x0040, lo: 0xa6, hi: 0xaf},
+ {value: 0x4495, lo: 0xb0, hi: 0xbf},
+ // Block 0x7b, offset 0x3ff
+ {value: 0x0000, lo: 0x04},
+ {value: 0x44b5, lo: 0x80, hi: 0x8f},
+ {value: 0x44d5, lo: 0x90, hi: 0x9f},
+ {value: 0x44f5, lo: 0xa0, hi: 0xaf},
+ {value: 0x44d5, lo: 0xb0, hi: 0xbf},
+ // Block 0x7c, offset 0x404
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x0008, lo: 0x80, hi: 0xa2},
+ {value: 0x1008, lo: 0xa3, hi: 0xa4},
+ {value: 0x1308, lo: 0xa5, hi: 0xa5},
+ {value: 0x1008, lo: 0xa6, hi: 0xa7},
+ {value: 0x1308, lo: 0xa8, hi: 0xa8},
+ {value: 0x1008, lo: 0xa9, hi: 0xaa},
+ {value: 0x0018, lo: 0xab, hi: 0xab},
+ {value: 0x1008, lo: 0xac, hi: 0xac},
+ {value: 0x1b08, lo: 0xad, hi: 0xad},
+ {value: 0x0040, lo: 0xae, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xb9},
+ {value: 0x0040, lo: 0xba, hi: 0xbf},
+ // Block 0x7d, offset 0x411
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0xa3},
+ {value: 0x0040, lo: 0xa4, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xbf},
+ // Block 0x7e, offset 0x415
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0018, lo: 0x80, hi: 0x86},
+ {value: 0x0040, lo: 0x87, hi: 0x8a},
+ {value: 0x0018, lo: 0x8b, hi: 0xbb},
+ {value: 0x0040, lo: 0xbc, hi: 0xbf},
+ // Block 0x7f, offset 0x41a
+ {value: 0x0020, lo: 0x01},
+ {value: 0x4515, lo: 0x80, hi: 0xbf},
+ // Block 0x80, offset 0x41c
+ {value: 0x0020, lo: 0x03},
+ {value: 0x4d15, lo: 0x80, hi: 0x94},
+ {value: 0x4ad5, lo: 0x95, hi: 0x95},
+ {value: 0x4fb5, lo: 0x96, hi: 0xbf},
+ // Block 0x81, offset 0x420
+ {value: 0x0020, lo: 0x01},
+ {value: 0x54f5, lo: 0x80, hi: 0xbf},
+ // Block 0x82, offset 0x422
+ {value: 0x0020, lo: 0x03},
+ {value: 0x5cf5, lo: 0x80, hi: 0x84},
+ {value: 0x5655, lo: 0x85, hi: 0x85},
+ {value: 0x5d95, lo: 0x86, hi: 0xbf},
+ // Block 0x83, offset 0x426
+ {value: 0x0020, lo: 0x08},
+ {value: 0x6b55, lo: 0x80, hi: 0x8f},
+ {value: 0x6d15, lo: 0x90, hi: 0x90},
+ {value: 0x6d55, lo: 0x91, hi: 0xab},
+ {value: 0x6ea1, lo: 0xac, hi: 0xac},
+ {value: 0x70b5, lo: 0xad, hi: 0xad},
+ {value: 0x0040, lo: 0xae, hi: 0xae},
+ {value: 0x0040, lo: 0xaf, hi: 0xaf},
+ {value: 0x70d5, lo: 0xb0, hi: 0xbf},
+ // Block 0x84, offset 0x42f
+ {value: 0x0020, lo: 0x05},
+ {value: 0x72d5, lo: 0x80, hi: 0xad},
+ {value: 0x6535, lo: 0xae, hi: 0xae},
+ {value: 0x7895, lo: 0xaf, hi: 0xb5},
+ {value: 0x6f55, lo: 0xb6, hi: 0xb6},
+ {value: 0x7975, lo: 0xb7, hi: 0xbf},
+ // Block 0x85, offset 0x435
+ {value: 0x0028, lo: 0x03},
+ {value: 0x7c21, lo: 0x80, hi: 0x82},
+ {value: 0x7be1, lo: 0x83, hi: 0x83},
+ {value: 0x7c99, lo: 0x84, hi: 0xbf},
+ // Block 0x86, offset 0x439
+ {value: 0x0038, lo: 0x0f},
+ {value: 0x9db1, lo: 0x80, hi: 0x83},
+ {value: 0x9e59, lo: 0x84, hi: 0x85},
+ {value: 0x9e91, lo: 0x86, hi: 0x87},
+ {value: 0x9ec9, lo: 0x88, hi: 0x8f},
+ {value: 0x0040, lo: 0x90, hi: 0x90},
+ {value: 0x0040, lo: 0x91, hi: 0x91},
+ {value: 0xa089, lo: 0x92, hi: 0x97},
+ {value: 0xa1a1, lo: 0x98, hi: 0x9c},
+ {value: 0xa281, lo: 0x9d, hi: 0xb3},
+ {value: 0x9d41, lo: 0xb4, hi: 0xb4},
+ {value: 0x9db1, lo: 0xb5, hi: 0xb5},
+ {value: 0xa789, lo: 0xb6, hi: 0xbb},
+ {value: 0xa869, lo: 0xbc, hi: 0xbc},
+ {value: 0xa7f9, lo: 0xbd, hi: 0xbd},
+ {value: 0xa8d9, lo: 0xbe, hi: 0xbf},
+ // Block 0x87, offset 0x449
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0008, lo: 0x80, hi: 0x8b},
+ {value: 0x0040, lo: 0x8c, hi: 0x8c},
+ {value: 0x0008, lo: 0x8d, hi: 0xa6},
+ {value: 0x0040, lo: 0xa7, hi: 0xa7},
+ {value: 0x0008, lo: 0xa8, hi: 0xba},
+ {value: 0x0040, lo: 0xbb, hi: 0xbb},
+ {value: 0x0008, lo: 0xbc, hi: 0xbd},
+ {value: 0x0040, lo: 0xbe, hi: 0xbe},
+ {value: 0x0008, lo: 0xbf, hi: 0xbf},
+ // Block 0x88, offset 0x453
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x9d},
+ {value: 0x0040, lo: 0x9e, hi: 0xbf},
+ // Block 0x89, offset 0x458
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0xba},
+ {value: 0x0040, lo: 0xbb, hi: 0xbf},
+ // Block 0x8a, offset 0x45b
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0018, lo: 0x80, hi: 0x82},
+ {value: 0x0040, lo: 0x83, hi: 0x86},
+ {value: 0x0018, lo: 0x87, hi: 0xb3},
+ {value: 0x0040, lo: 0xb4, hi: 0xb6},
+ {value: 0x0018, lo: 0xb7, hi: 0xbf},
+ // Block 0x8b, offset 0x461
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0018, lo: 0x80, hi: 0x8e},
+ {value: 0x0040, lo: 0x8f, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0x9b},
+ {value: 0x0040, lo: 0x9c, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xa0},
+ {value: 0x0040, lo: 0xa1, hi: 0xbf},
+ // Block 0x8c, offset 0x468
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0040, lo: 0x80, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0xbc},
+ {value: 0x1308, lo: 0xbd, hi: 0xbd},
+ {value: 0x0040, lo: 0xbe, hi: 0xbf},
+ // Block 0x8d, offset 0x46d
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0x9c},
+ {value: 0x0040, lo: 0x9d, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xbf},
+ // Block 0x8e, offset 0x471
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0008, lo: 0x80, hi: 0x90},
+ {value: 0x0040, lo: 0x91, hi: 0x9f},
+ {value: 0x1308, lo: 0xa0, hi: 0xa0},
+ {value: 0x0018, lo: 0xa1, hi: 0xbb},
+ {value: 0x0040, lo: 0xbc, hi: 0xbf},
+ // Block 0x8f, offset 0x477
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xa3},
+ {value: 0x0040, lo: 0xa4, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0x90, offset 0x47c
+ {value: 0x0000, lo: 0x08},
+ {value: 0x0008, lo: 0x80, hi: 0x80},
+ {value: 0x0018, lo: 0x81, hi: 0x81},
+ {value: 0x0008, lo: 0x82, hi: 0x89},
+ {value: 0x0018, lo: 0x8a, hi: 0x8a},
+ {value: 0x0040, lo: 0x8b, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0xb5},
+ {value: 0x1308, lo: 0xb6, hi: 0xba},
+ {value: 0x0040, lo: 0xbb, hi: 0xbf},
+ // Block 0x91, offset 0x485
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0x9d},
+ {value: 0x0040, lo: 0x9e, hi: 0x9e},
+ {value: 0x0018, lo: 0x9f, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xbf},
+ // Block 0x92, offset 0x48a
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0008, lo: 0x80, hi: 0x83},
+ {value: 0x0040, lo: 0x84, hi: 0x87},
+ {value: 0x0008, lo: 0x88, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0x95},
+ {value: 0x0040, lo: 0x96, hi: 0xbf},
+ // Block 0x93, offset 0x490
+ {value: 0x0000, lo: 0x06},
+ {value: 0xe145, lo: 0x80, hi: 0x87},
+ {value: 0xe1c5, lo: 0x88, hi: 0x8f},
+ {value: 0xe145, lo: 0x90, hi: 0x97},
+ {value: 0x8ad5, lo: 0x98, hi: 0x9f},
+ {value: 0x8aed, lo: 0xa0, hi: 0xa7},
+ {value: 0x0008, lo: 0xa8, hi: 0xbf},
+ // Block 0x94, offset 0x497
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0008, lo: 0x80, hi: 0x9d},
+ {value: 0x0040, lo: 0x9e, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa9},
+ {value: 0x0040, lo: 0xaa, hi: 0xaf},
+ {value: 0x8aed, lo: 0xb0, hi: 0xb7},
+ {value: 0x8ad5, lo: 0xb8, hi: 0xbf},
+ // Block 0x95, offset 0x49e
+ {value: 0x0000, lo: 0x06},
+ {value: 0xe145, lo: 0x80, hi: 0x87},
+ {value: 0xe1c5, lo: 0x88, hi: 0x8f},
+ {value: 0xe145, lo: 0x90, hi: 0x93},
+ {value: 0x0040, lo: 0x94, hi: 0x97},
+ {value: 0x0008, lo: 0x98, hi: 0xbb},
+ {value: 0x0040, lo: 0xbc, hi: 0xbf},
+ // Block 0x96, offset 0x4a5
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0xa7},
+ {value: 0x0040, lo: 0xa8, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0x97, offset 0x4a9
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0xa3},
+ {value: 0x0040, lo: 0xa4, hi: 0xae},
+ {value: 0x0018, lo: 0xaf, hi: 0xaf},
+ {value: 0x0040, lo: 0xb0, hi: 0xbf},
+ // Block 0x98, offset 0x4ae
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0xb6},
+ {value: 0x0040, lo: 0xb7, hi: 0xbf},
+ // Block 0x99, offset 0x4b1
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0x95},
+ {value: 0x0040, lo: 0x96, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa7},
+ {value: 0x0040, lo: 0xa8, hi: 0xbf},
+ // Block 0x9a, offset 0x4b6
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0008, lo: 0x80, hi: 0x85},
+ {value: 0x0040, lo: 0x86, hi: 0x87},
+ {value: 0x0008, lo: 0x88, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0x89},
+ {value: 0x0008, lo: 0x8a, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xb6},
+ {value: 0x0008, lo: 0xb7, hi: 0xb8},
+ {value: 0x0040, lo: 0xb9, hi: 0xbb},
+ {value: 0x0008, lo: 0xbc, hi: 0xbc},
+ {value: 0x0040, lo: 0xbd, hi: 0xbe},
+ {value: 0x0008, lo: 0xbf, hi: 0xbf},
+ // Block 0x9b, offset 0x4c2
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0008, lo: 0x80, hi: 0x95},
+ {value: 0x0040, lo: 0x96, hi: 0x96},
+ {value: 0x0018, lo: 0x97, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xb6},
+ {value: 0x0018, lo: 0xb7, hi: 0xbf},
+ // Block 0x9c, offset 0x4c8
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0x9e},
+ {value: 0x0040, lo: 0x9f, hi: 0xa6},
+ {value: 0x0018, lo: 0xa7, hi: 0xaf},
+ {value: 0x0040, lo: 0xb0, hi: 0xbf},
+ // Block 0x9d, offset 0x4cd
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0040, lo: 0x80, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xb2},
+ {value: 0x0040, lo: 0xb3, hi: 0xb3},
+ {value: 0x0008, lo: 0xb4, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xba},
+ {value: 0x0018, lo: 0xbb, hi: 0xbf},
+ // Block 0x9e, offset 0x4d4
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0008, lo: 0x80, hi: 0x95},
+ {value: 0x0018, lo: 0x96, hi: 0x9b},
+ {value: 0x0040, lo: 0x9c, hi: 0x9e},
+ {value: 0x0018, lo: 0x9f, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xb9},
+ {value: 0x0040, lo: 0xba, hi: 0xbe},
+ {value: 0x0018, lo: 0xbf, hi: 0xbf},
+ // Block 0x9f, offset 0x4dc
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0xb7},
+ {value: 0x0040, lo: 0xb8, hi: 0xbb},
+ {value: 0x0018, lo: 0xbc, hi: 0xbd},
+ {value: 0x0008, lo: 0xbe, hi: 0xbf},
+ // Block 0xa0, offset 0x4e1
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0x8f},
+ {value: 0x0040, lo: 0x90, hi: 0x91},
+ {value: 0x0018, lo: 0x92, hi: 0xbf},
+ // Block 0xa1, offset 0x4e5
+ {value: 0x0000, lo: 0x0f},
+ {value: 0x0008, lo: 0x80, hi: 0x80},
+ {value: 0x1308, lo: 0x81, hi: 0x83},
+ {value: 0x0040, lo: 0x84, hi: 0x84},
+ {value: 0x1308, lo: 0x85, hi: 0x86},
+ {value: 0x0040, lo: 0x87, hi: 0x8b},
+ {value: 0x1308, lo: 0x8c, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x93},
+ {value: 0x0040, lo: 0x94, hi: 0x94},
+ {value: 0x0008, lo: 0x95, hi: 0x97},
+ {value: 0x0040, lo: 0x98, hi: 0x98},
+ {value: 0x0008, lo: 0x99, hi: 0xb3},
+ {value: 0x0040, lo: 0xb4, hi: 0xb7},
+ {value: 0x1308, lo: 0xb8, hi: 0xba},
+ {value: 0x0040, lo: 0xbb, hi: 0xbe},
+ {value: 0x1b08, lo: 0xbf, hi: 0xbf},
+ // Block 0xa2, offset 0x4f5
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0018, lo: 0x80, hi: 0x87},
+ {value: 0x0040, lo: 0x88, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0x98},
+ {value: 0x0040, lo: 0x99, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xbc},
+ {value: 0x0018, lo: 0xbd, hi: 0xbf},
+ // Block 0xa3, offset 0x4fc
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0x9c},
+ {value: 0x0018, lo: 0x9d, hi: 0x9f},
+ {value: 0x0040, lo: 0xa0, hi: 0xbf},
+ // Block 0xa4, offset 0x500
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xb8},
+ {value: 0x0018, lo: 0xb9, hi: 0xbf},
+ // Block 0xa5, offset 0x504
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0008, lo: 0x80, hi: 0x95},
+ {value: 0x0040, lo: 0x96, hi: 0x97},
+ {value: 0x0018, lo: 0x98, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xb2},
+ {value: 0x0040, lo: 0xb3, hi: 0xb7},
+ {value: 0x0018, lo: 0xb8, hi: 0xbf},
+ // Block 0xa6, offset 0x50b
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0xbf},
+ // Block 0xa7, offset 0x50e
+ {value: 0x0000, lo: 0x02},
+ {value: 0x03dd, lo: 0x80, hi: 0xb2},
+ {value: 0x0040, lo: 0xb3, hi: 0xbf},
+ // Block 0xa8, offset 0x511
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0xb2},
+ {value: 0x0040, lo: 0xb3, hi: 0xb9},
+ {value: 0x0018, lo: 0xba, hi: 0xbf},
+ // Block 0xa9, offset 0x515
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0040, lo: 0x80, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0xaa, offset 0x519
+ {value: 0x0000, lo: 0x05},
+ {value: 0x1008, lo: 0x80, hi: 0x80},
+ {value: 0x1308, lo: 0x81, hi: 0x81},
+ {value: 0x1008, lo: 0x82, hi: 0x82},
+ {value: 0x0008, lo: 0x83, hi: 0xb7},
+ {value: 0x1308, lo: 0xb8, hi: 0xbf},
+ // Block 0xab, offset 0x51f
+ {value: 0x0000, lo: 0x08},
+ {value: 0x1308, lo: 0x80, hi: 0x85},
+ {value: 0x1b08, lo: 0x86, hi: 0x86},
+ {value: 0x0018, lo: 0x87, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x91},
+ {value: 0x0018, lo: 0x92, hi: 0xa5},
+ {value: 0x0008, lo: 0xa6, hi: 0xaf},
+ {value: 0x0040, lo: 0xb0, hi: 0xbe},
+ {value: 0x1b08, lo: 0xbf, hi: 0xbf},
+ // Block 0xac, offset 0x528
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x1308, lo: 0x80, hi: 0x81},
+ {value: 0x1008, lo: 0x82, hi: 0x82},
+ {value: 0x0008, lo: 0x83, hi: 0xaf},
+ {value: 0x1008, lo: 0xb0, hi: 0xb2},
+ {value: 0x1308, lo: 0xb3, hi: 0xb6},
+ {value: 0x1008, lo: 0xb7, hi: 0xb8},
+ {value: 0x1b08, lo: 0xb9, hi: 0xb9},
+ {value: 0x1308, lo: 0xba, hi: 0xba},
+ {value: 0x0018, lo: 0xbb, hi: 0xbc},
+ {value: 0x0340, lo: 0xbd, hi: 0xbd},
+ {value: 0x0018, lo: 0xbe, hi: 0xbf},
+ // Block 0xad, offset 0x534
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0018, lo: 0x80, hi: 0x81},
+ {value: 0x0040, lo: 0x82, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0xa8},
+ {value: 0x0040, lo: 0xa9, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xb9},
+ {value: 0x0040, lo: 0xba, hi: 0xbf},
+ // Block 0xae, offset 0x53b
+ {value: 0x0000, lo: 0x08},
+ {value: 0x1308, lo: 0x80, hi: 0x82},
+ {value: 0x0008, lo: 0x83, hi: 0xa6},
+ {value: 0x1308, lo: 0xa7, hi: 0xab},
+ {value: 0x1008, lo: 0xac, hi: 0xac},
+ {value: 0x1308, lo: 0xad, hi: 0xb2},
+ {value: 0x1b08, lo: 0xb3, hi: 0xb4},
+ {value: 0x0040, lo: 0xb5, hi: 0xb5},
+ {value: 0x0008, lo: 0xb6, hi: 0xbf},
+ // Block 0xaf, offset 0x544
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0018, lo: 0x80, hi: 0x83},
+ {value: 0x0040, lo: 0x84, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0xb2},
+ {value: 0x1308, lo: 0xb3, hi: 0xb3},
+ {value: 0x0018, lo: 0xb4, hi: 0xb5},
+ {value: 0x0008, lo: 0xb6, hi: 0xb6},
+ {value: 0x0040, lo: 0xb7, hi: 0xbf},
+ // Block 0xb0, offset 0x54c
+ {value: 0x0000, lo: 0x06},
+ {value: 0x1308, lo: 0x80, hi: 0x81},
+ {value: 0x1008, lo: 0x82, hi: 0x82},
+ {value: 0x0008, lo: 0x83, hi: 0xb2},
+ {value: 0x1008, lo: 0xb3, hi: 0xb5},
+ {value: 0x1308, lo: 0xb6, hi: 0xbe},
+ {value: 0x1008, lo: 0xbf, hi: 0xbf},
+ // Block 0xb1, offset 0x553
+ {value: 0x0000, lo: 0x0d},
+ {value: 0x1808, lo: 0x80, hi: 0x80},
+ {value: 0x0008, lo: 0x81, hi: 0x84},
+ {value: 0x0018, lo: 0x85, hi: 0x89},
+ {value: 0x1308, lo: 0x8a, hi: 0x8c},
+ {value: 0x0018, lo: 0x8d, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x9a},
+ {value: 0x0018, lo: 0x9b, hi: 0x9b},
+ {value: 0x0008, lo: 0x9c, hi: 0x9c},
+ {value: 0x0018, lo: 0x9d, hi: 0x9f},
+ {value: 0x0040, lo: 0xa0, hi: 0xa0},
+ {value: 0x0018, lo: 0xa1, hi: 0xb4},
+ {value: 0x0040, lo: 0xb5, hi: 0xbf},
+ // Block 0xb2, offset 0x561
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x0008, lo: 0x80, hi: 0x91},
+ {value: 0x0040, lo: 0x92, hi: 0x92},
+ {value: 0x0008, lo: 0x93, hi: 0xab},
+ {value: 0x1008, lo: 0xac, hi: 0xae},
+ {value: 0x1308, lo: 0xaf, hi: 0xb1},
+ {value: 0x1008, lo: 0xb2, hi: 0xb3},
+ {value: 0x1308, lo: 0xb4, hi: 0xb4},
+ {value: 0x1808, lo: 0xb5, hi: 0xb5},
+ {value: 0x1308, lo: 0xb6, hi: 0xb7},
+ {value: 0x0018, lo: 0xb8, hi: 0xbd},
+ {value: 0x1308, lo: 0xbe, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0xb3, offset 0x56e
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x0008, lo: 0x80, hi: 0x86},
+ {value: 0x0040, lo: 0x87, hi: 0x87},
+ {value: 0x0008, lo: 0x88, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0x89},
+ {value: 0x0008, lo: 0x8a, hi: 0x8d},
+ {value: 0x0040, lo: 0x8e, hi: 0x8e},
+ {value: 0x0008, lo: 0x8f, hi: 0x9d},
+ {value: 0x0040, lo: 0x9e, hi: 0x9e},
+ {value: 0x0008, lo: 0x9f, hi: 0xa8},
+ {value: 0x0018, lo: 0xa9, hi: 0xa9},
+ {value: 0x0040, lo: 0xaa, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbf},
+ // Block 0xb4, offset 0x57b
+ {value: 0x0000, lo: 0x08},
+ {value: 0x0008, lo: 0x80, hi: 0x9e},
+ {value: 0x1308, lo: 0x9f, hi: 0x9f},
+ {value: 0x1008, lo: 0xa0, hi: 0xa2},
+ {value: 0x1308, lo: 0xa3, hi: 0xa9},
+ {value: 0x1b08, lo: 0xaa, hi: 0xaa},
+ {value: 0x0040, lo: 0xab, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xb9},
+ {value: 0x0040, lo: 0xba, hi: 0xbf},
+ // Block 0xb5, offset 0x584
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0xb4},
+ {value: 0x1008, lo: 0xb5, hi: 0xb7},
+ {value: 0x1308, lo: 0xb8, hi: 0xbf},
+ // Block 0xb6, offset 0x588
+ {value: 0x0000, lo: 0x0d},
+ {value: 0x1008, lo: 0x80, hi: 0x81},
+ {value: 0x1b08, lo: 0x82, hi: 0x82},
+ {value: 0x1308, lo: 0x83, hi: 0x84},
+ {value: 0x1008, lo: 0x85, hi: 0x85},
+ {value: 0x1308, lo: 0x86, hi: 0x86},
+ {value: 0x0008, lo: 0x87, hi: 0x8a},
+ {value: 0x0018, lo: 0x8b, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9a},
+ {value: 0x0018, lo: 0x9b, hi: 0x9b},
+ {value: 0x0040, lo: 0x9c, hi: 0x9c},
+ {value: 0x0018, lo: 0x9d, hi: 0x9d},
+ {value: 0x0040, lo: 0x9e, hi: 0xbf},
+ // Block 0xb7, offset 0x596
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0008, lo: 0x80, hi: 0xaf},
+ {value: 0x1008, lo: 0xb0, hi: 0xb2},
+ {value: 0x1308, lo: 0xb3, hi: 0xb8},
+ {value: 0x1008, lo: 0xb9, hi: 0xb9},
+ {value: 0x1308, lo: 0xba, hi: 0xba},
+ {value: 0x1008, lo: 0xbb, hi: 0xbe},
+ {value: 0x1308, lo: 0xbf, hi: 0xbf},
+ // Block 0xb8, offset 0x59e
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x1308, lo: 0x80, hi: 0x80},
+ {value: 0x1008, lo: 0x81, hi: 0x81},
+ {value: 0x1b08, lo: 0x82, hi: 0x82},
+ {value: 0x1308, lo: 0x83, hi: 0x83},
+ {value: 0x0008, lo: 0x84, hi: 0x85},
+ {value: 0x0018, lo: 0x86, hi: 0x86},
+ {value: 0x0008, lo: 0x87, hi: 0x87},
+ {value: 0x0040, lo: 0x88, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0xbf},
+ // Block 0xb9, offset 0x5a9
+ {value: 0x0000, lo: 0x08},
+ {value: 0x0008, lo: 0x80, hi: 0xae},
+ {value: 0x1008, lo: 0xaf, hi: 0xb1},
+ {value: 0x1308, lo: 0xb2, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xb7},
+ {value: 0x1008, lo: 0xb8, hi: 0xbb},
+ {value: 0x1308, lo: 0xbc, hi: 0xbd},
+ {value: 0x1008, lo: 0xbe, hi: 0xbe},
+ {value: 0x1b08, lo: 0xbf, hi: 0xbf},
+ // Block 0xba, offset 0x5b2
+ {value: 0x0000, lo: 0x05},
+ {value: 0x1308, lo: 0x80, hi: 0x80},
+ {value: 0x0018, lo: 0x81, hi: 0x97},
+ {value: 0x0008, lo: 0x98, hi: 0x9b},
+ {value: 0x1308, lo: 0x9c, hi: 0x9d},
+ {value: 0x0040, lo: 0x9e, hi: 0xbf},
+ // Block 0xbb, offset 0x5b8
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0008, lo: 0x80, hi: 0xaf},
+ {value: 0x1008, lo: 0xb0, hi: 0xb2},
+ {value: 0x1308, lo: 0xb3, hi: 0xba},
+ {value: 0x1008, lo: 0xbb, hi: 0xbc},
+ {value: 0x1308, lo: 0xbd, hi: 0xbd},
+ {value: 0x1008, lo: 0xbe, hi: 0xbe},
+ {value: 0x1b08, lo: 0xbf, hi: 0xbf},
+ // Block 0xbc, offset 0x5c0
+ {value: 0x0000, lo: 0x08},
+ {value: 0x1308, lo: 0x80, hi: 0x80},
+ {value: 0x0018, lo: 0x81, hi: 0x83},
+ {value: 0x0008, lo: 0x84, hi: 0x84},
+ {value: 0x0040, lo: 0x85, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xac},
+ {value: 0x0040, lo: 0xad, hi: 0xbf},
+ // Block 0xbd, offset 0x5c9
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0008, lo: 0x80, hi: 0xaa},
+ {value: 0x1308, lo: 0xab, hi: 0xab},
+ {value: 0x1008, lo: 0xac, hi: 0xac},
+ {value: 0x1308, lo: 0xad, hi: 0xad},
+ {value: 0x1008, lo: 0xae, hi: 0xaf},
+ {value: 0x1308, lo: 0xb0, hi: 0xb5},
+ {value: 0x1808, lo: 0xb6, hi: 0xb6},
+ {value: 0x1308, lo: 0xb7, hi: 0xb7},
+ {value: 0x0040, lo: 0xb8, hi: 0xbf},
+ // Block 0xbe, offset 0x5d3
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0x89},
+ {value: 0x0040, lo: 0x8a, hi: 0xbf},
+ // Block 0xbf, offset 0x5d6
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0008, lo: 0x80, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9c},
+ {value: 0x1308, lo: 0x9d, hi: 0x9f},
+ {value: 0x1008, lo: 0xa0, hi: 0xa1},
+ {value: 0x1308, lo: 0xa2, hi: 0xa5},
+ {value: 0x1008, lo: 0xa6, hi: 0xa6},
+ {value: 0x1308, lo: 0xa7, hi: 0xaa},
+ {value: 0x1b08, lo: 0xab, hi: 0xab},
+ {value: 0x0040, lo: 0xac, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xb9},
+ {value: 0x0018, lo: 0xba, hi: 0xbf},
+ // Block 0xc0, offset 0x5e2
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0040, lo: 0x80, hi: 0x9f},
+ {value: 0x049d, lo: 0xa0, hi: 0xbf},
+ // Block 0xc1, offset 0x5e5
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0xa9},
+ {value: 0x0018, lo: 0xaa, hi: 0xb2},
+ {value: 0x0040, lo: 0xb3, hi: 0xbe},
+ {value: 0x0008, lo: 0xbf, hi: 0xbf},
+ // Block 0xc2, offset 0x5ea
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0xb8},
+ {value: 0x0040, lo: 0xb9, hi: 0xbf},
+ // Block 0xc3, offset 0x5ed
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0008, lo: 0x80, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0x89},
+ {value: 0x0008, lo: 0x8a, hi: 0xae},
+ {value: 0x1008, lo: 0xaf, hi: 0xaf},
+ {value: 0x1308, lo: 0xb0, hi: 0xb6},
+ {value: 0x0040, lo: 0xb7, hi: 0xb7},
+ {value: 0x1308, lo: 0xb8, hi: 0xbd},
+ {value: 0x1008, lo: 0xbe, hi: 0xbe},
+ {value: 0x1b08, lo: 0xbf, hi: 0xbf},
+ // Block 0xc4, offset 0x5f7
+ {value: 0x0000, lo: 0x08},
+ {value: 0x0008, lo: 0x80, hi: 0x80},
+ {value: 0x0018, lo: 0x81, hi: 0x85},
+ {value: 0x0040, lo: 0x86, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0018, lo: 0x9a, hi: 0xac},
+ {value: 0x0040, lo: 0xad, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xb1},
+ {value: 0x0008, lo: 0xb2, hi: 0xbf},
+ // Block 0xc5, offset 0x600
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x0008, lo: 0x80, hi: 0x8f},
+ {value: 0x0040, lo: 0x90, hi: 0x91},
+ {value: 0x1308, lo: 0x92, hi: 0xa7},
+ {value: 0x0040, lo: 0xa8, hi: 0xa8},
+ {value: 0x1008, lo: 0xa9, hi: 0xa9},
+ {value: 0x1308, lo: 0xaa, hi: 0xb0},
+ {value: 0x1008, lo: 0xb1, hi: 0xb1},
+ {value: 0x1308, lo: 0xb2, hi: 0xb3},
+ {value: 0x1008, lo: 0xb4, hi: 0xb4},
+ {value: 0x1308, lo: 0xb5, hi: 0xb6},
+ {value: 0x0040, lo: 0xb7, hi: 0xbf},
+ // Block 0xc6, offset 0x60c
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0xbf},
+ // Block 0xc7, offset 0x60f
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0018, lo: 0x80, hi: 0xae},
+ {value: 0x0040, lo: 0xaf, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xb4},
+ {value: 0x0040, lo: 0xb5, hi: 0xbf},
+ // Block 0xc8, offset 0x614
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0x83},
+ {value: 0x0040, lo: 0x84, hi: 0xbf},
+ // Block 0xc9, offset 0x617
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0xae},
+ {value: 0x0040, lo: 0xaf, hi: 0xbf},
+ // Block 0xca, offset 0x61a
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0x86},
+ {value: 0x0040, lo: 0x87, hi: 0xbf},
+ // Block 0xcb, offset 0x61d
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0008, lo: 0x80, hi: 0x9e},
+ {value: 0x0040, lo: 0x9f, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa9},
+ {value: 0x0040, lo: 0xaa, hi: 0xad},
+ {value: 0x0018, lo: 0xae, hi: 0xaf},
+ {value: 0x0040, lo: 0xb0, hi: 0xbf},
+ // Block 0xcc, offset 0x624
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0040, lo: 0x80, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0xad},
+ {value: 0x0040, lo: 0xae, hi: 0xaf},
+ {value: 0x1308, lo: 0xb0, hi: 0xb4},
+ {value: 0x0018, lo: 0xb5, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xbf},
+ // Block 0xcd, offset 0x62b
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0xaf},
+ {value: 0x1308, lo: 0xb0, hi: 0xb6},
+ {value: 0x0018, lo: 0xb7, hi: 0xbf},
+ // Block 0xce, offset 0x62f
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x0008, lo: 0x80, hi: 0x83},
+ {value: 0x0018, lo: 0x84, hi: 0x85},
+ {value: 0x0040, lo: 0x86, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9a},
+ {value: 0x0018, lo: 0x9b, hi: 0xa1},
+ {value: 0x0040, lo: 0xa2, hi: 0xa2},
+ {value: 0x0008, lo: 0xa3, hi: 0xb7},
+ {value: 0x0040, lo: 0xb8, hi: 0xbc},
+ {value: 0x0008, lo: 0xbd, hi: 0xbf},
+ // Block 0xcf, offset 0x63a
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0x8f},
+ {value: 0x0040, lo: 0x90, hi: 0xbf},
+ // Block 0xd0, offset 0x63d
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0008, lo: 0x80, hi: 0x84},
+ {value: 0x0040, lo: 0x85, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x90},
+ {value: 0x1008, lo: 0x91, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0xd1, offset 0x643
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0040, lo: 0x80, hi: 0x8e},
+ {value: 0x1308, lo: 0x8f, hi: 0x92},
+ {value: 0x0008, lo: 0x93, hi: 0x9f},
+ {value: 0x0040, lo: 0xa0, hi: 0xbf},
+ // Block 0xd2, offset 0x648
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0040, lo: 0x80, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xa0},
+ {value: 0x0040, lo: 0xa1, hi: 0xbf},
+ // Block 0xd3, offset 0x64c
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0xac},
+ {value: 0x0040, lo: 0xad, hi: 0xbf},
+ // Block 0xd4, offset 0x64f
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0xb2},
+ {value: 0x0040, lo: 0xb3, hi: 0xbf},
+ // Block 0xd5, offset 0x652
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0x81},
+ {value: 0x0040, lo: 0x82, hi: 0xbf},
+ // Block 0xd6, offset 0x655
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0008, lo: 0x80, hi: 0xaa},
+ {value: 0x0040, lo: 0xab, hi: 0xaf},
+ {value: 0x0008, lo: 0xb0, hi: 0xbc},
+ {value: 0x0040, lo: 0xbd, hi: 0xbf},
+ // Block 0xd7, offset 0x65a
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0008, lo: 0x80, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9b},
+ {value: 0x0018, lo: 0x9c, hi: 0x9c},
+ {value: 0x1308, lo: 0x9d, hi: 0x9e},
+ {value: 0x0018, lo: 0x9f, hi: 0x9f},
+ {value: 0x03c0, lo: 0xa0, hi: 0xa3},
+ {value: 0x0040, lo: 0xa4, hi: 0xbf},
+ // Block 0xd8, offset 0x664
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0018, lo: 0x80, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xbf},
+ // Block 0xd9, offset 0x667
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0xa6},
+ {value: 0x0040, lo: 0xa7, hi: 0xa8},
+ {value: 0x0018, lo: 0xa9, hi: 0xbf},
+ // Block 0xda, offset 0x66b
+ {value: 0x0000, lo: 0x0e},
+ {value: 0x0018, lo: 0x80, hi: 0x9d},
+ {value: 0xb5b9, lo: 0x9e, hi: 0x9e},
+ {value: 0xb601, lo: 0x9f, hi: 0x9f},
+ {value: 0xb649, lo: 0xa0, hi: 0xa0},
+ {value: 0xb6b1, lo: 0xa1, hi: 0xa1},
+ {value: 0xb719, lo: 0xa2, hi: 0xa2},
+ {value: 0xb781, lo: 0xa3, hi: 0xa3},
+ {value: 0xb7e9, lo: 0xa4, hi: 0xa4},
+ {value: 0x1018, lo: 0xa5, hi: 0xa6},
+ {value: 0x1318, lo: 0xa7, hi: 0xa9},
+ {value: 0x0018, lo: 0xaa, hi: 0xac},
+ {value: 0x1018, lo: 0xad, hi: 0xb2},
+ {value: 0x0340, lo: 0xb3, hi: 0xba},
+ {value: 0x1318, lo: 0xbb, hi: 0xbf},
+ // Block 0xdb, offset 0x67a
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x1318, lo: 0x80, hi: 0x82},
+ {value: 0x0018, lo: 0x83, hi: 0x84},
+ {value: 0x1318, lo: 0x85, hi: 0x8b},
+ {value: 0x0018, lo: 0x8c, hi: 0xa9},
+ {value: 0x1318, lo: 0xaa, hi: 0xad},
+ {value: 0x0018, lo: 0xae, hi: 0xba},
+ {value: 0xb851, lo: 0xbb, hi: 0xbb},
+ {value: 0xb899, lo: 0xbc, hi: 0xbc},
+ {value: 0xb8e1, lo: 0xbd, hi: 0xbd},
+ {value: 0xb949, lo: 0xbe, hi: 0xbe},
+ {value: 0xb9b1, lo: 0xbf, hi: 0xbf},
+ // Block 0xdc, offset 0x686
+ {value: 0x0000, lo: 0x03},
+ {value: 0xba19, lo: 0x80, hi: 0x80},
+ {value: 0x0018, lo: 0x81, hi: 0xa8},
+ {value: 0x0040, lo: 0xa9, hi: 0xbf},
+ // Block 0xdd, offset 0x68a
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0018, lo: 0x80, hi: 0x81},
+ {value: 0x1318, lo: 0x82, hi: 0x84},
+ {value: 0x0018, lo: 0x85, hi: 0x85},
+ {value: 0x0040, lo: 0x86, hi: 0xbf},
+ // Block 0xde, offset 0x68f
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0018, lo: 0x80, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xb1},
+ {value: 0x0040, lo: 0xb2, hi: 0xbf},
+ // Block 0xdf, offset 0x694
+ {value: 0x0000, lo: 0x03},
+ {value: 0x1308, lo: 0x80, hi: 0xb6},
+ {value: 0x0018, lo: 0xb7, hi: 0xba},
+ {value: 0x1308, lo: 0xbb, hi: 0xbf},
+ // Block 0xe0, offset 0x698
+ {value: 0x0000, lo: 0x04},
+ {value: 0x1308, lo: 0x80, hi: 0xac},
+ {value: 0x0018, lo: 0xad, hi: 0xb4},
+ {value: 0x1308, lo: 0xb5, hi: 0xb5},
+ {value: 0x0018, lo: 0xb6, hi: 0xbf},
+ // Block 0xe1, offset 0x69d
+ {value: 0x0000, lo: 0x08},
+ {value: 0x0018, lo: 0x80, hi: 0x83},
+ {value: 0x1308, lo: 0x84, hi: 0x84},
+ {value: 0x0018, lo: 0x85, hi: 0x8b},
+ {value: 0x0040, lo: 0x8c, hi: 0x9a},
+ {value: 0x1308, lo: 0x9b, hi: 0x9f},
+ {value: 0x0040, lo: 0xa0, hi: 0xa0},
+ {value: 0x1308, lo: 0xa1, hi: 0xaf},
+ {value: 0x0040, lo: 0xb0, hi: 0xbf},
+ // Block 0xe2, offset 0x6a6
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x1308, lo: 0x80, hi: 0x86},
+ {value: 0x0040, lo: 0x87, hi: 0x87},
+ {value: 0x1308, lo: 0x88, hi: 0x98},
+ {value: 0x0040, lo: 0x99, hi: 0x9a},
+ {value: 0x1308, lo: 0x9b, hi: 0xa1},
+ {value: 0x0040, lo: 0xa2, hi: 0xa2},
+ {value: 0x1308, lo: 0xa3, hi: 0xa4},
+ {value: 0x0040, lo: 0xa5, hi: 0xa5},
+ {value: 0x1308, lo: 0xa6, hi: 0xaa},
+ {value: 0x0040, lo: 0xab, hi: 0xbf},
+ // Block 0xe3, offset 0x6b1
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0008, lo: 0x80, hi: 0x84},
+ {value: 0x0040, lo: 0x85, hi: 0x86},
+ {value: 0x0018, lo: 0x87, hi: 0x8f},
+ {value: 0x1308, lo: 0x90, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0xbf},
+ // Block 0xe4, offset 0x6b7
+ {value: 0x0000, lo: 0x07},
+ {value: 0x0208, lo: 0x80, hi: 0x83},
+ {value: 0x1308, lo: 0x84, hi: 0x8a},
+ {value: 0x0040, lo: 0x8b, hi: 0x8f},
+ {value: 0x0008, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9d},
+ {value: 0x0018, lo: 0x9e, hi: 0x9f},
+ {value: 0x0040, lo: 0xa0, hi: 0xbf},
+ // Block 0xe5, offset 0x6bf
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0040, lo: 0x80, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xb1},
+ {value: 0x0040, lo: 0xb2, hi: 0xbf},
+ // Block 0xe6, offset 0x6c3
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0xab},
+ {value: 0x0040, lo: 0xac, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xbf},
+ // Block 0xe7, offset 0x6c7
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0018, lo: 0x80, hi: 0x93},
+ {value: 0x0040, lo: 0x94, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xae},
+ {value: 0x0040, lo: 0xaf, hi: 0xb0},
+ {value: 0x0018, lo: 0xb1, hi: 0xbf},
+ // Block 0xe8, offset 0x6cd
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0040, lo: 0x80, hi: 0x80},
+ {value: 0x0018, lo: 0x81, hi: 0x8f},
+ {value: 0x0040, lo: 0x90, hi: 0x90},
+ {value: 0x0018, lo: 0x91, hi: 0xb5},
+ {value: 0x0040, lo: 0xb6, hi: 0xbf},
+ // Block 0xe9, offset 0x6d3
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0018, lo: 0x80, hi: 0x8f},
+ {value: 0xc1c1, lo: 0x90, hi: 0x90},
+ {value: 0x0018, lo: 0x91, hi: 0xac},
+ {value: 0x0040, lo: 0xad, hi: 0xbf},
+ // Block 0xea, offset 0x6d8
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0040, lo: 0x80, hi: 0xa5},
+ {value: 0x0018, lo: 0xa6, hi: 0xbf},
+ // Block 0xeb, offset 0x6db
+ {value: 0x0000, lo: 0x0d},
+ {value: 0xc7e9, lo: 0x80, hi: 0x80},
+ {value: 0xc839, lo: 0x81, hi: 0x81},
+ {value: 0xc889, lo: 0x82, hi: 0x82},
+ {value: 0xc8d9, lo: 0x83, hi: 0x83},
+ {value: 0xc929, lo: 0x84, hi: 0x84},
+ {value: 0xc979, lo: 0x85, hi: 0x85},
+ {value: 0xc9c9, lo: 0x86, hi: 0x86},
+ {value: 0xca19, lo: 0x87, hi: 0x87},
+ {value: 0xca69, lo: 0x88, hi: 0x88},
+ {value: 0x0040, lo: 0x89, hi: 0x8f},
+ {value: 0xcab9, lo: 0x90, hi: 0x90},
+ {value: 0xcad9, lo: 0x91, hi: 0x91},
+ {value: 0x0040, lo: 0x92, hi: 0xbf},
+ // Block 0xec, offset 0x6e9
+ {value: 0x0000, lo: 0x06},
+ {value: 0x0018, lo: 0x80, hi: 0x92},
+ {value: 0x0040, lo: 0x93, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xac},
+ {value: 0x0040, lo: 0xad, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xb6},
+ {value: 0x0040, lo: 0xb7, hi: 0xbf},
+ // Block 0xed, offset 0x6f0
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0018, lo: 0x80, hi: 0xb3},
+ {value: 0x0040, lo: 0xb4, hi: 0xbf},
+ // Block 0xee, offset 0x6f3
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0018, lo: 0x80, hi: 0x94},
+ {value: 0x0040, lo: 0x95, hi: 0xbf},
+ // Block 0xef, offset 0x6f6
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0018, lo: 0x80, hi: 0x8b},
+ {value: 0x0040, lo: 0x8c, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0xbf},
+ // Block 0xf0, offset 0x6fa
+ {value: 0x0000, lo: 0x05},
+ {value: 0x0018, lo: 0x80, hi: 0x87},
+ {value: 0x0040, lo: 0x88, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0x99},
+ {value: 0x0040, lo: 0x9a, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xbf},
+ // Block 0xf1, offset 0x700
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0018, lo: 0x80, hi: 0x87},
+ {value: 0x0040, lo: 0x88, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0xad},
+ {value: 0x0040, lo: 0xae, hi: 0xbf},
+ // Block 0xf2, offset 0x705
+ {value: 0x0000, lo: 0x09},
+ {value: 0x0040, lo: 0x80, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0x9e},
+ {value: 0x0040, lo: 0x9f, hi: 0x9f},
+ {value: 0x0018, lo: 0xa0, hi: 0xa7},
+ {value: 0x0040, lo: 0xa8, hi: 0xaf},
+ {value: 0x0018, lo: 0xb0, hi: 0xb0},
+ {value: 0x0040, lo: 0xb1, hi: 0xb2},
+ {value: 0x0018, lo: 0xb3, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0xf3, offset 0x70f
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0018, lo: 0x80, hi: 0x8b},
+ {value: 0x0040, lo: 0x8c, hi: 0x8f},
+ {value: 0x0018, lo: 0x90, hi: 0x9e},
+ {value: 0x0040, lo: 0x9f, hi: 0xbf},
+ // Block 0xf4, offset 0x714
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0018, lo: 0x80, hi: 0x91},
+ {value: 0x0040, lo: 0x92, hi: 0xbf},
+ // Block 0xf5, offset 0x717
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0018, lo: 0x80, hi: 0x80},
+ {value: 0x0040, lo: 0x81, hi: 0xbf},
+ // Block 0xf6, offset 0x71a
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0x96},
+ {value: 0x0040, lo: 0x97, hi: 0xbf},
+ // Block 0xf7, offset 0x71d
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0xb4},
+ {value: 0x0040, lo: 0xb5, hi: 0xbf},
+ // Block 0xf8, offset 0x720
+ {value: 0x0000, lo: 0x03},
+ {value: 0x0008, lo: 0x80, hi: 0x9d},
+ {value: 0x0040, lo: 0x9e, hi: 0x9f},
+ {value: 0x0008, lo: 0xa0, hi: 0xbf},
+ // Block 0xf9, offset 0x724
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0008, lo: 0x80, hi: 0xa1},
+ {value: 0x0040, lo: 0xa2, hi: 0xbf},
+ // Block 0xfa, offset 0x727
+ {value: 0x0020, lo: 0x0f},
+ {value: 0xdeb9, lo: 0x80, hi: 0x89},
+ {value: 0x8dfd, lo: 0x8a, hi: 0x8a},
+ {value: 0xdff9, lo: 0x8b, hi: 0x9c},
+ {value: 0x8e1d, lo: 0x9d, hi: 0x9d},
+ {value: 0xe239, lo: 0x9e, hi: 0xa2},
+ {value: 0x8e3d, lo: 0xa3, hi: 0xa3},
+ {value: 0xe2d9, lo: 0xa4, hi: 0xab},
+ {value: 0x7ed5, lo: 0xac, hi: 0xac},
+ {value: 0xe3d9, lo: 0xad, hi: 0xaf},
+ {value: 0x8e5d, lo: 0xb0, hi: 0xb0},
+ {value: 0xe439, lo: 0xb1, hi: 0xb6},
+ {value: 0x8e7d, lo: 0xb7, hi: 0xb9},
+ {value: 0xe4f9, lo: 0xba, hi: 0xba},
+ {value: 0x8edd, lo: 0xbb, hi: 0xbb},
+ {value: 0xe519, lo: 0xbc, hi: 0xbf},
+ // Block 0xfb, offset 0x737
+ {value: 0x0020, lo: 0x10},
+ {value: 0x937d, lo: 0x80, hi: 0x80},
+ {value: 0xf099, lo: 0x81, hi: 0x86},
+ {value: 0x939d, lo: 0x87, hi: 0x8a},
+ {value: 0xd9f9, lo: 0x8b, hi: 0x8b},
+ {value: 0xf159, lo: 0x8c, hi: 0x96},
+ {value: 0x941d, lo: 0x97, hi: 0x97},
+ {value: 0xf2b9, lo: 0x98, hi: 0xa3},
+ {value: 0x943d, lo: 0xa4, hi: 0xa6},
+ {value: 0xf439, lo: 0xa7, hi: 0xaa},
+ {value: 0x949d, lo: 0xab, hi: 0xab},
+ {value: 0xf4b9, lo: 0xac, hi: 0xac},
+ {value: 0x94bd, lo: 0xad, hi: 0xad},
+ {value: 0xf4d9, lo: 0xae, hi: 0xaf},
+ {value: 0x94dd, lo: 0xb0, hi: 0xb1},
+ {value: 0xf519, lo: 0xb2, hi: 0xbe},
+ {value: 0x0040, lo: 0xbf, hi: 0xbf},
+ // Block 0xfc, offset 0x748
+ {value: 0x0000, lo: 0x04},
+ {value: 0x0040, lo: 0x80, hi: 0x80},
+ {value: 0x0340, lo: 0x81, hi: 0x81},
+ {value: 0x0040, lo: 0x82, hi: 0x9f},
+ {value: 0x0340, lo: 0xa0, hi: 0xbf},
+ // Block 0xfd, offset 0x74d
+ {value: 0x0000, lo: 0x01},
+ {value: 0x0340, lo: 0x80, hi: 0xbf},
+ // Block 0xfe, offset 0x74f
+ {value: 0x0000, lo: 0x01},
+ {value: 0x13c0, lo: 0x80, hi: 0xbf},
+ // Block 0xff, offset 0x751
+ {value: 0x0000, lo: 0x02},
+ {value: 0x13c0, lo: 0x80, hi: 0xaf},
+ {value: 0x0040, lo: 0xb0, hi: 0xbf},
+}
+
+// Total table size 41559 bytes (40KiB); checksum: F4A1FA4E
diff --git a/vendor/golang.org/x/net/idna/trie.go b/vendor/golang.org/x/net/idna/trie.go
new file mode 100644
index 0000000..c4ef847
--- /dev/null
+++ b/vendor/golang.org/x/net/idna/trie.go
@@ -0,0 +1,72 @@
+// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT.
+
+// 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 idna
+
+// appendMapping appends the mapping for the respective rune. isMapped must be
+// true. A mapping is a categorization of a rune as defined in UTS #46.
+func (c info) appendMapping(b []byte, s string) []byte {
+ index := int(c >> indexShift)
+ if c&xorBit == 0 {
+ s := mappings[index:]
+ return append(b, s[1:s[0]+1]...)
+ }
+ b = append(b, s...)
+ if c&inlineXOR == inlineXOR {
+ // TODO: support and handle two-byte inline masks
+ b[len(b)-1] ^= byte(index)
+ } else {
+ for p := len(b) - int(xorData[index]); p < len(b); p++ {
+ index++
+ b[p] ^= xorData[index]
+ }
+ }
+ return b
+}
+
+// Sparse block handling code.
+
+type valueRange struct {
+ value uint16 // header: value:stride
+ lo, hi byte // header: lo:n
+}
+
+type sparseBlocks struct {
+ values []valueRange
+ offset []uint16
+}
+
+var idnaSparse = sparseBlocks{
+ values: idnaSparseValues[:],
+ offset: idnaSparseOffset[:],
+}
+
+// Don't use newIdnaTrie to avoid unconditional linking in of the table.
+var trie = &idnaTrie{}
+
+// lookup determines the type of block n and looks up the value for b.
+// For n < t.cutoff, the block is a simple lookup table. Otherwise, the block
+// is a list of ranges with an accompanying value. Given a matching range r,
+// the value for b is by r.value + (b - r.lo) * stride.
+func (t *sparseBlocks) lookup(n uint32, b byte) uint16 {
+ offset := t.offset[n]
+ header := t.values[offset]
+ lo := offset + 1
+ hi := lo + uint16(header.lo)
+ for lo < hi {
+ m := lo + (hi-lo)/2
+ r := t.values[m]
+ if r.lo <= b && b <= r.hi {
+ return r.value + uint16(b-r.lo)*header.value
+ }
+ if b < r.lo {
+ hi = m
+ } else {
+ lo = m + 1
+ }
+ }
+ return 0
+}
diff --git a/vendor/golang.org/x/net/idna/trieval.go b/vendor/golang.org/x/net/idna/trieval.go
new file mode 100644
index 0000000..63cb03b
--- /dev/null
+++ b/vendor/golang.org/x/net/idna/trieval.go
@@ -0,0 +1,114 @@
+// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT.
+
+package idna
+
+// This file contains definitions for interpreting the trie value of the idna
+// trie generated by "go run gen*.go". It is shared by both the generator
+// program and the resultant package. Sharing is achieved by the generator
+// copying gen_trieval.go to trieval.go and changing what's above this comment.
+
+// info holds information from the IDNA mapping table for a single rune. It is
+// the value returned by a trie lookup. In most cases, all information fits in
+// a 16-bit value. For mappings, this value may contain an index into a slice
+// with the mapped string. Such mappings can consist of the actual mapped value
+// or an XOR pattern to be applied to the bytes of the UTF8 encoding of the
+// input rune. This technique is used by the cases packages and reduces the
+// table size significantly.
+//
+// The per-rune values have the following format:
+//
+// if mapped {
+// if inlinedXOR {
+// 15..13 inline XOR marker
+// 12..11 unused
+// 10..3 inline XOR mask
+// } else {
+// 15..3 index into xor or mapping table
+// }
+// } else {
+// 15..13 unused
+// 12 modifier (including virama)
+// 11 virama modifier
+// 10..8 joining type
+// 7..3 category type
+// }
+// 2 use xor pattern
+// 1..0 mapped category
+//
+// See the definitions below for a more detailed description of the various
+// bits.
+type info uint16
+
+const (
+ catSmallMask = 0x3
+ catBigMask = 0xF8
+ indexShift = 3
+ xorBit = 0x4 // interpret the index as an xor pattern
+ inlineXOR = 0xE000 // These bits are set if the XOR pattern is inlined.
+
+ joinShift = 8
+ joinMask = 0x07
+
+ viramaModifier = 0x0800
+ modifier = 0x1000
+)
+
+// A category corresponds to a category defined in the IDNA mapping table.
+type category uint16
+
+const (
+ unknown category = 0 // not defined currently in unicode.
+ mapped category = 1
+ disallowedSTD3Mapped category = 2
+ deviation category = 3
+)
+
+const (
+ valid category = 0x08
+ validNV8 category = 0x18
+ validXV8 category = 0x28
+ disallowed category = 0x40
+ disallowedSTD3Valid category = 0x80
+ ignored category = 0xC0
+)
+
+// join types and additional rune information
+const (
+ joiningL = (iota + 1)
+ joiningD
+ joiningT
+ joiningR
+
+ //the following types are derived during processing
+ joinZWJ
+ joinZWNJ
+ joinVirama
+ numJoinTypes
+)
+
+func (c info) isMapped() bool {
+ return c&0x3 != 0
+}
+
+func (c info) category() category {
+ small := c & catSmallMask
+ if small != 0 {
+ return category(small)
+ }
+ return category(c & catBigMask)
+}
+
+func (c info) joinType() info {
+ if c.isMapped() {
+ return 0
+ }
+ return (c >> joinShift) & joinMask
+}
+
+func (c info) isModifier() bool {
+ return c&(modifier|catSmallMask) == modifier
+}
+
+func (c info) isViramaModifier() bool {
+ return c&(viramaModifier|catSmallMask) == viramaModifier
+}
diff --git a/vendor/golang.org/x/net/internal/timeseries/timeseries.go b/vendor/golang.org/x/net/internal/timeseries/timeseries.go
new file mode 100644
index 0000000..685f0e7
--- /dev/null
+++ b/vendor/golang.org/x/net/internal/timeseries/timeseries.go
@@ -0,0 +1,525 @@
+// Copyright 2015 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 timeseries implements a time series structure for stats collection.
+package timeseries // import "golang.org/x/net/internal/timeseries"
+
+import (
+ "fmt"
+ "log"
+ "time"
+)
+
+const (
+ timeSeriesNumBuckets = 64
+ minuteHourSeriesNumBuckets = 60
+)
+
+var timeSeriesResolutions = []time.Duration{
+ 1 * time.Second,
+ 10 * time.Second,
+ 1 * time.Minute,
+ 10 * time.Minute,
+ 1 * time.Hour,
+ 6 * time.Hour,
+ 24 * time.Hour, // 1 day
+ 7 * 24 * time.Hour, // 1 week
+ 4 * 7 * 24 * time.Hour, // 4 weeks
+ 16 * 7 * 24 * time.Hour, // 16 weeks
+}
+
+var minuteHourSeriesResolutions = []time.Duration{
+ 1 * time.Second,
+ 1 * time.Minute,
+}
+
+// An Observable is a kind of data that can be aggregated in a time series.
+type Observable interface {
+ Multiply(ratio float64) // Multiplies the data in self by a given ratio
+ Add(other Observable) // Adds the data from a different observation to self
+ Clear() // Clears the observation so it can be reused.
+ CopyFrom(other Observable) // Copies the contents of a given observation to self
+}
+
+// Float attaches the methods of Observable to a float64.
+type Float float64
+
+// NewFloat returns a Float.
+func NewFloat() Observable {
+ f := Float(0)
+ return &f
+}
+
+// String returns the float as a string.
+func (f *Float) String() string { return fmt.Sprintf("%g", f.Value()) }
+
+// Value returns the float's value.
+func (f *Float) Value() float64 { return float64(*f) }
+
+func (f *Float) Multiply(ratio float64) { *f *= Float(ratio) }
+
+func (f *Float) Add(other Observable) {
+ o := other.(*Float)
+ *f += *o
+}
+
+func (f *Float) Clear() { *f = 0 }
+
+func (f *Float) CopyFrom(other Observable) {
+ o := other.(*Float)
+ *f = *o
+}
+
+// A Clock tells the current time.
+type Clock interface {
+ Time() time.Time
+}
+
+type defaultClock int
+
+var defaultClockInstance defaultClock
+
+func (defaultClock) Time() time.Time { return time.Now() }
+
+// Information kept per level. Each level consists of a circular list of
+// observations. The start of the level may be derived from end and the
+// len(buckets) * sizeInMillis.
+type tsLevel struct {
+ oldest int // index to oldest bucketed Observable
+ newest int // index to newest bucketed Observable
+ end time.Time // end timestamp for this level
+ size time.Duration // duration of the bucketed Observable
+ buckets []Observable // collections of observations
+ provider func() Observable // used for creating new Observable
+}
+
+func (l *tsLevel) Clear() {
+ l.oldest = 0
+ l.newest = len(l.buckets) - 1
+ l.end = time.Time{}
+ for i := range l.buckets {
+ if l.buckets[i] != nil {
+ l.buckets[i].Clear()
+ l.buckets[i] = nil
+ }
+ }
+}
+
+func (l *tsLevel) InitLevel(size time.Duration, numBuckets int, f func() Observable) {
+ l.size = size
+ l.provider = f
+ l.buckets = make([]Observable, numBuckets)
+}
+
+// Keeps a sequence of levels. Each level is responsible for storing data at
+// a given resolution. For example, the first level stores data at a one
+// minute resolution while the second level stores data at a one hour
+// resolution.
+
+// Each level is represented by a sequence of buckets. Each bucket spans an
+// interval equal to the resolution of the level. New observations are added
+// to the last bucket.
+type timeSeries struct {
+ provider func() Observable // make more Observable
+ numBuckets int // number of buckets in each level
+ levels []*tsLevel // levels of bucketed Observable
+ lastAdd time.Time // time of last Observable tracked
+ total Observable // convenient aggregation of all Observable
+ clock Clock // Clock for getting current time
+ pending Observable // observations not yet bucketed
+ pendingTime time.Time // what time are we keeping in pending
+ dirty bool // if there are pending observations
+}
+
+// init initializes a level according to the supplied criteria.
+func (ts *timeSeries) init(resolutions []time.Duration, f func() Observable, numBuckets int, clock Clock) {
+ ts.provider = f
+ ts.numBuckets = numBuckets
+ ts.clock = clock
+ ts.levels = make([]*tsLevel, len(resolutions))
+
+ for i := range resolutions {
+ if i > 0 && resolutions[i-1] >= resolutions[i] {
+ log.Print("timeseries: resolutions must be monotonically increasing")
+ break
+ }
+ newLevel := new(tsLevel)
+ newLevel.InitLevel(resolutions[i], ts.numBuckets, ts.provider)
+ ts.levels[i] = newLevel
+ }
+
+ ts.Clear()
+}
+
+// Clear removes all observations from the time series.
+func (ts *timeSeries) Clear() {
+ ts.lastAdd = time.Time{}
+ ts.total = ts.resetObservation(ts.total)
+ ts.pending = ts.resetObservation(ts.pending)
+ ts.pendingTime = time.Time{}
+ ts.dirty = false
+
+ for i := range ts.levels {
+ ts.levels[i].Clear()
+ }
+}
+
+// Add records an observation at the current time.
+func (ts *timeSeries) Add(observation Observable) {
+ ts.AddWithTime(observation, ts.clock.Time())
+}
+
+// AddWithTime records an observation at the specified time.
+func (ts *timeSeries) AddWithTime(observation Observable, t time.Time) {
+
+ smallBucketDuration := ts.levels[0].size
+
+ if t.After(ts.lastAdd) {
+ ts.lastAdd = t
+ }
+
+ if t.After(ts.pendingTime) {
+ ts.advance(t)
+ ts.mergePendingUpdates()
+ ts.pendingTime = ts.levels[0].end
+ ts.pending.CopyFrom(observation)
+ ts.dirty = true
+ } else if t.After(ts.pendingTime.Add(-1 * smallBucketDuration)) {
+ // The observation is close enough to go into the pending bucket.
+ // This compensates for clock skewing and small scheduling delays
+ // by letting the update stay in the fast path.
+ ts.pending.Add(observation)
+ ts.dirty = true
+ } else {
+ ts.mergeValue(observation, t)
+ }
+}
+
+// mergeValue inserts the observation at the specified time in the past into all levels.
+func (ts *timeSeries) mergeValue(observation Observable, t time.Time) {
+ for _, level := range ts.levels {
+ index := (ts.numBuckets - 1) - int(level.end.Sub(t)/level.size)
+ if 0 <= index && index < ts.numBuckets {
+ bucketNumber := (level.oldest + index) % ts.numBuckets
+ if level.buckets[bucketNumber] == nil {
+ level.buckets[bucketNumber] = level.provider()
+ }
+ level.buckets[bucketNumber].Add(observation)
+ }
+ }
+ ts.total.Add(observation)
+}
+
+// mergePendingUpdates applies the pending updates into all levels.
+func (ts *timeSeries) mergePendingUpdates() {
+ if ts.dirty {
+ ts.mergeValue(ts.pending, ts.pendingTime)
+ ts.pending = ts.resetObservation(ts.pending)
+ ts.dirty = false
+ }
+}
+
+// advance cycles the buckets at each level until the latest bucket in
+// each level can hold the time specified.
+func (ts *timeSeries) advance(t time.Time) {
+ if !t.After(ts.levels[0].end) {
+ return
+ }
+ for i := 0; i < len(ts.levels); i++ {
+ level := ts.levels[i]
+ if !level.end.Before(t) {
+ break
+ }
+
+ // If the time is sufficiently far, just clear the level and advance
+ // directly.
+ if !t.Before(level.end.Add(level.size * time.Duration(ts.numBuckets))) {
+ for _, b := range level.buckets {
+ ts.resetObservation(b)
+ }
+ level.end = time.Unix(0, (t.UnixNano()/level.size.Nanoseconds())*level.size.Nanoseconds())
+ }
+
+ for t.After(level.end) {
+ level.end = level.end.Add(level.size)
+ level.newest = level.oldest
+ level.oldest = (level.oldest + 1) % ts.numBuckets
+ ts.resetObservation(level.buckets[level.newest])
+ }
+
+ t = level.end
+ }
+}
+
+// Latest returns the sum of the num latest buckets from the level.
+func (ts *timeSeries) Latest(level, num int) Observable {
+ now := ts.clock.Time()
+ if ts.levels[0].end.Before(now) {
+ ts.advance(now)
+ }
+
+ ts.mergePendingUpdates()
+
+ result := ts.provider()
+ l := ts.levels[level]
+ index := l.newest
+
+ for i := 0; i < num; i++ {
+ if l.buckets[index] != nil {
+ result.Add(l.buckets[index])
+ }
+ if index == 0 {
+ index = ts.numBuckets
+ }
+ index--
+ }
+
+ return result
+}
+
+// LatestBuckets returns a copy of the num latest buckets from level.
+func (ts *timeSeries) LatestBuckets(level, num int) []Observable {
+ if level < 0 || level > len(ts.levels) {
+ log.Print("timeseries: bad level argument: ", level)
+ return nil
+ }
+ if num < 0 || num >= ts.numBuckets {
+ log.Print("timeseries: bad num argument: ", num)
+ return nil
+ }
+
+ results := make([]Observable, num)
+ now := ts.clock.Time()
+ if ts.levels[0].end.Before(now) {
+ ts.advance(now)
+ }
+
+ ts.mergePendingUpdates()
+
+ l := ts.levels[level]
+ index := l.newest
+
+ for i := 0; i < num; i++ {
+ result := ts.provider()
+ results[i] = result
+ if l.buckets[index] != nil {
+ result.CopyFrom(l.buckets[index])
+ }
+
+ if index == 0 {
+ index = ts.numBuckets
+ }
+ index -= 1
+ }
+ return results
+}
+
+// ScaleBy updates observations by scaling by factor.
+func (ts *timeSeries) ScaleBy(factor float64) {
+ for _, l := range ts.levels {
+ for i := 0; i < ts.numBuckets; i++ {
+ l.buckets[i].Multiply(factor)
+ }
+ }
+
+ ts.total.Multiply(factor)
+ ts.pending.Multiply(factor)
+}
+
+// Range returns the sum of observations added over the specified time range.
+// If start or finish times don't fall on bucket boundaries of the same
+// level, then return values are approximate answers.
+func (ts *timeSeries) Range(start, finish time.Time) Observable {
+ return ts.ComputeRange(start, finish, 1)[0]
+}
+
+// Recent returns the sum of observations from the last delta.
+func (ts *timeSeries) Recent(delta time.Duration) Observable {
+ now := ts.clock.Time()
+ return ts.Range(now.Add(-delta), now)
+}
+
+// Total returns the total of all observations.
+func (ts *timeSeries) Total() Observable {
+ ts.mergePendingUpdates()
+ return ts.total
+}
+
+// ComputeRange computes a specified number of values into a slice using
+// the observations recorded over the specified time period. The return
+// values are approximate if the start or finish times don't fall on the
+// bucket boundaries at the same level or if the number of buckets spanning
+// the range is not an integral multiple of num.
+func (ts *timeSeries) ComputeRange(start, finish time.Time, num int) []Observable {
+ if start.After(finish) {
+ log.Printf("timeseries: start > finish, %v>%v", start, finish)
+ return nil
+ }
+
+ if num < 0 {
+ log.Printf("timeseries: num < 0, %v", num)
+ return nil
+ }
+
+ results := make([]Observable, num)
+
+ for _, l := range ts.levels {
+ if !start.Before(l.end.Add(-l.size * time.Duration(ts.numBuckets))) {
+ ts.extract(l, start, finish, num, results)
+ return results
+ }
+ }
+
+ // Failed to find a level that covers the desired range. So just
+ // extract from the last level, even if it doesn't cover the entire
+ // desired range.
+ ts.extract(ts.levels[len(ts.levels)-1], start, finish, num, results)
+
+ return results
+}
+
+// RecentList returns the specified number of values in slice over the most
+// recent time period of the specified range.
+func (ts *timeSeries) RecentList(delta time.Duration, num int) []Observable {
+ if delta < 0 {
+ return nil
+ }
+ now := ts.clock.Time()
+ return ts.ComputeRange(now.Add(-delta), now, num)
+}
+
+// extract returns a slice of specified number of observations from a given
+// level over a given range.
+func (ts *timeSeries) extract(l *tsLevel, start, finish time.Time, num int, results []Observable) {
+ ts.mergePendingUpdates()
+
+ srcInterval := l.size
+ dstInterval := finish.Sub(start) / time.Duration(num)
+ dstStart := start
+ srcStart := l.end.Add(-srcInterval * time.Duration(ts.numBuckets))
+
+ srcIndex := 0
+
+ // Where should scanning start?
+ if dstStart.After(srcStart) {
+ advance := dstStart.Sub(srcStart) / srcInterval
+ srcIndex += int(advance)
+ srcStart = srcStart.Add(advance * srcInterval)
+ }
+
+ // The i'th value is computed as show below.
+ // interval = (finish/start)/num
+ // i'th value = sum of observation in range
+ // [ start + i * interval,
+ // start + (i + 1) * interval )
+ for i := 0; i < num; i++ {
+ results[i] = ts.resetObservation(results[i])
+ dstEnd := dstStart.Add(dstInterval)
+ for srcIndex < ts.numBuckets && srcStart.Before(dstEnd) {
+ srcEnd := srcStart.Add(srcInterval)
+ if srcEnd.After(ts.lastAdd) {
+ srcEnd = ts.lastAdd
+ }
+
+ if !srcEnd.Before(dstStart) {
+ srcValue := l.buckets[(srcIndex+l.oldest)%ts.numBuckets]
+ if !srcStart.Before(dstStart) && !srcEnd.After(dstEnd) {
+ // dst completely contains src.
+ if srcValue != nil {
+ results[i].Add(srcValue)
+ }
+ } else {
+ // dst partially overlaps src.
+ overlapStart := maxTime(srcStart, dstStart)
+ overlapEnd := minTime(srcEnd, dstEnd)
+ base := srcEnd.Sub(srcStart)
+ fraction := overlapEnd.Sub(overlapStart).Seconds() / base.Seconds()
+
+ used := ts.provider()
+ if srcValue != nil {
+ used.CopyFrom(srcValue)
+ }
+ used.Multiply(fraction)
+ results[i].Add(used)
+ }
+
+ if srcEnd.After(dstEnd) {
+ break
+ }
+ }
+ srcIndex++
+ srcStart = srcStart.Add(srcInterval)
+ }
+ dstStart = dstStart.Add(dstInterval)
+ }
+}
+
+// resetObservation clears the content so the struct may be reused.
+func (ts *timeSeries) resetObservation(observation Observable) Observable {
+ if observation == nil {
+ observation = ts.provider()
+ } else {
+ observation.Clear()
+ }
+ return observation
+}
+
+// TimeSeries tracks data at granularities from 1 second to 16 weeks.
+type TimeSeries struct {
+ timeSeries
+}
+
+// NewTimeSeries creates a new TimeSeries using the function provided for creating new Observable.
+func NewTimeSeries(f func() Observable) *TimeSeries {
+ return NewTimeSeriesWithClock(f, defaultClockInstance)
+}
+
+// NewTimeSeriesWithClock creates a new TimeSeries using the function provided for creating new Observable and the clock for
+// assigning timestamps.
+func NewTimeSeriesWithClock(f func() Observable, clock Clock) *TimeSeries {
+ ts := new(TimeSeries)
+ ts.timeSeries.init(timeSeriesResolutions, f, timeSeriesNumBuckets, clock)
+ return ts
+}
+
+// MinuteHourSeries tracks data at granularities of 1 minute and 1 hour.
+type MinuteHourSeries struct {
+ timeSeries
+}
+
+// NewMinuteHourSeries creates a new MinuteHourSeries using the function provided for creating new Observable.
+func NewMinuteHourSeries(f func() Observable) *MinuteHourSeries {
+ return NewMinuteHourSeriesWithClock(f, defaultClockInstance)
+}
+
+// NewMinuteHourSeriesWithClock creates a new MinuteHourSeries using the function provided for creating new Observable and the clock for
+// assigning timestamps.
+func NewMinuteHourSeriesWithClock(f func() Observable, clock Clock) *MinuteHourSeries {
+ ts := new(MinuteHourSeries)
+ ts.timeSeries.init(minuteHourSeriesResolutions, f,
+ minuteHourSeriesNumBuckets, clock)
+ return ts
+}
+
+func (ts *MinuteHourSeries) Minute() Observable {
+ return ts.timeSeries.Latest(0, 60)
+}
+
+func (ts *MinuteHourSeries) Hour() Observable {
+ return ts.timeSeries.Latest(1, 60)
+}
+
+func minTime(a, b time.Time) time.Time {
+ if a.Before(b) {
+ return a
+ }
+ return b
+}
+
+func maxTime(a, b time.Time) time.Time {
+ if a.After(b) {
+ return a
+ }
+ return b
+}
diff --git a/vendor/golang.org/x/net/lex/httplex/httplex.go b/vendor/golang.org/x/net/lex/httplex/httplex.go
new file mode 100644
index 0000000..20f2b89
--- /dev/null
+++ b/vendor/golang.org/x/net/lex/httplex/httplex.go
@@ -0,0 +1,351 @@
+// 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 httplex contains rules around lexical matters of various
+// HTTP-related specifications.
+//
+// This package is shared by the standard library (which vendors it)
+// and x/net/http2. It comes with no API stability promise.
+package httplex
+
+import (
+ "net"
+ "strings"
+ "unicode/utf8"
+
+ "golang.org/x/net/idna"
+)
+
+var isTokenTable = [127]bool{
+ '!': true,
+ '#': true,
+ '$': true,
+ '%': true,
+ '&': true,
+ '\'': true,
+ '*': true,
+ '+': true,
+ '-': true,
+ '.': true,
+ '0': true,
+ '1': true,
+ '2': true,
+ '3': true,
+ '4': true,
+ '5': true,
+ '6': true,
+ '7': true,
+ '8': true,
+ '9': true,
+ 'A': true,
+ 'B': true,
+ 'C': true,
+ 'D': true,
+ 'E': true,
+ 'F': true,
+ 'G': true,
+ 'H': true,
+ 'I': true,
+ 'J': true,
+ 'K': true,
+ 'L': true,
+ 'M': true,
+ 'N': true,
+ 'O': true,
+ 'P': true,
+ 'Q': true,
+ 'R': true,
+ 'S': true,
+ 'T': true,
+ 'U': true,
+ 'W': true,
+ 'V': true,
+ 'X': true,
+ 'Y': true,
+ 'Z': true,
+ '^': true,
+ '_': true,
+ '`': true,
+ 'a': true,
+ 'b': true,
+ 'c': true,
+ 'd': true,
+ 'e': true,
+ 'f': true,
+ 'g': true,
+ 'h': true,
+ 'i': true,
+ 'j': true,
+ 'k': true,
+ 'l': true,
+ 'm': true,
+ 'n': true,
+ 'o': true,
+ 'p': true,
+ 'q': true,
+ 'r': true,
+ 's': true,
+ 't': true,
+ 'u': true,
+ 'v': true,
+ 'w': true,
+ 'x': true,
+ 'y': true,
+ 'z': true,
+ '|': true,
+ '~': true,
+}
+
+func IsTokenRune(r rune) bool {
+ i := int(r)
+ return i < len(isTokenTable) && isTokenTable[i]
+}
+
+func isNotToken(r rune) bool {
+ return !IsTokenRune(r)
+}
+
+// HeaderValuesContainsToken reports whether any string in values
+// contains the provided token, ASCII case-insensitively.
+func HeaderValuesContainsToken(values []string, token string) bool {
+ for _, v := range values {
+ if headerValueContainsToken(v, token) {
+ return true
+ }
+ }
+ return false
+}
+
+// isOWS reports whether b is an optional whitespace byte, as defined
+// by RFC 7230 section 3.2.3.
+func isOWS(b byte) bool { return b == ' ' || b == '\t' }
+
+// trimOWS returns x with all optional whitespace removes from the
+// beginning and end.
+func trimOWS(x string) string {
+ // TODO: consider using strings.Trim(x, " \t") instead,
+ // if and when it's fast enough. See issue 10292.
+ // But this ASCII-only code will probably always beat UTF-8
+ // aware code.
+ for len(x) > 0 && isOWS(x[0]) {
+ x = x[1:]
+ }
+ for len(x) > 0 && isOWS(x[len(x)-1]) {
+ x = x[:len(x)-1]
+ }
+ return x
+}
+
+// headerValueContainsToken reports whether v (assumed to be a
+// 0#element, in the ABNF extension described in RFC 7230 section 7)
+// contains token amongst its comma-separated tokens, ASCII
+// case-insensitively.
+func headerValueContainsToken(v string, token string) bool {
+ v = trimOWS(v)
+ if comma := strings.IndexByte(v, ','); comma != -1 {
+ return tokenEqual(trimOWS(v[:comma]), token) || headerValueContainsToken(v[comma+1:], token)
+ }
+ return tokenEqual(v, token)
+}
+
+// lowerASCII returns the ASCII lowercase version of b.
+func lowerASCII(b byte) byte {
+ if 'A' <= b && b <= 'Z' {
+ return b + ('a' - 'A')
+ }
+ return b
+}
+
+// tokenEqual reports whether t1 and t2 are equal, ASCII case-insensitively.
+func tokenEqual(t1, t2 string) bool {
+ if len(t1) != len(t2) {
+ return false
+ }
+ for i, b := range t1 {
+ if b >= utf8.RuneSelf {
+ // No UTF-8 or non-ASCII allowed in tokens.
+ return false
+ }
+ if lowerASCII(byte(b)) != lowerASCII(t2[i]) {
+ return false
+ }
+ }
+ return true
+}
+
+// isLWS reports whether b is linear white space, according
+// to http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
+// LWS = [CRLF] 1*( SP | HT )
+func isLWS(b byte) bool { return b == ' ' || b == '\t' }
+
+// isCTL reports whether b is a control byte, according
+// to http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
+// CTL = <any US-ASCII control character
+// (octets 0 - 31) and DEL (127)>
+func isCTL(b byte) bool {
+ const del = 0x7f // a CTL
+ return b < ' ' || b == del
+}
+
+// ValidHeaderFieldName reports whether v is a valid HTTP/1.x header name.
+// HTTP/2 imposes the additional restriction that uppercase ASCII
+// letters are not allowed.
+//
+// RFC 7230 says:
+// header-field = field-name ":" OWS field-value OWS
+// field-name = token
+// token = 1*tchar
+// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
+// "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
+func ValidHeaderFieldName(v string) bool {
+ if len(v) == 0 {
+ return false
+ }
+ for _, r := range v {
+ if !IsTokenRune(r) {
+ return false
+ }
+ }
+ return true
+}
+
+// ValidHostHeader reports whether h is a valid host header.
+func ValidHostHeader(h string) bool {
+ // The latest spec is actually this:
+ //
+ // http://tools.ietf.org/html/rfc7230#section-5.4
+ // Host = uri-host [ ":" port ]
+ //
+ // Where uri-host is:
+ // http://tools.ietf.org/html/rfc3986#section-3.2.2
+ //
+ // But we're going to be much more lenient for now and just
+ // search for any byte that's not a valid byte in any of those
+ // expressions.
+ for i := 0; i < len(h); i++ {
+ if !validHostByte[h[i]] {
+ return false
+ }
+ }
+ return true
+}
+
+// See the validHostHeader comment.
+var validHostByte = [256]bool{
+ '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true,
+ '8': true, '9': true,
+
+ 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true,
+ 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true,
+ 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true,
+ 'y': true, 'z': true,
+
+ 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true,
+ 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true,
+ 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true,
+ 'Y': true, 'Z': true,
+
+ '!': true, // sub-delims
+ '$': true, // sub-delims
+ '%': true, // pct-encoded (and used in IPv6 zones)
+ '&': true, // sub-delims
+ '(': true, // sub-delims
+ ')': true, // sub-delims
+ '*': true, // sub-delims
+ '+': true, // sub-delims
+ ',': true, // sub-delims
+ '-': true, // unreserved
+ '.': true, // unreserved
+ ':': true, // IPv6address + Host expression's optional port
+ ';': true, // sub-delims
+ '=': true, // sub-delims
+ '[': true,
+ '\'': true, // sub-delims
+ ']': true,
+ '_': true, // unreserved
+ '~': true, // unreserved
+}
+
+// ValidHeaderFieldValue reports whether v is a valid "field-value" according to
+// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 :
+//
+// message-header = field-name ":" [ field-value ]
+// field-value = *( field-content | LWS )
+// field-content = <the OCTETs making up the field-value
+// and consisting of either *TEXT or combinations
+// of token, separators, and quoted-string>
+//
+// http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 :
+//
+// TEXT = <any OCTET except CTLs,
+// but including LWS>
+// LWS = [CRLF] 1*( SP | HT )
+// CTL = <any US-ASCII control character
+// (octets 0 - 31) and DEL (127)>
+//
+// RFC 7230 says:
+// field-value = *( field-content / obs-fold )
+// obj-fold = N/A to http2, and deprecated
+// field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
+// field-vchar = VCHAR / obs-text
+// obs-text = %x80-FF
+// VCHAR = "any visible [USASCII] character"
+//
+// http2 further says: "Similarly, HTTP/2 allows header field values
+// that are not valid. While most of the values that can be encoded
+// will not alter header field parsing, carriage return (CR, ASCII
+// 0xd), line feed (LF, ASCII 0xa), and the zero character (NUL, ASCII
+// 0x0) might be exploited by an attacker if they are translated
+// verbatim. Any request or response that contains a character not
+// permitted in a header field value MUST be treated as malformed
+// (Section 8.1.2.6). Valid characters are defined by the
+// field-content ABNF rule in Section 3.2 of [RFC7230]."
+//
+// This function does not (yet?) properly handle the rejection of
+// strings that begin or end with SP or HTAB.
+func ValidHeaderFieldValue(v string) bool {
+ for i := 0; i < len(v); i++ {
+ b := v[i]
+ if isCTL(b) && !isLWS(b) {
+ return false
+ }
+ }
+ return true
+}
+
+func isASCII(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] >= utf8.RuneSelf {
+ return false
+ }
+ }
+ return true
+}
+
+// PunycodeHostPort returns the IDNA Punycode version
+// of the provided "host" or "host:port" string.
+func PunycodeHostPort(v string) (string, error) {
+ if isASCII(v) {
+ return v, nil
+ }
+
+ host, port, err := net.SplitHostPort(v)
+ if err != nil {
+ // The input 'v' argument was just a "host" argument,
+ // without a port. This error should not be returned
+ // to the caller.
+ host = v
+ port = ""
+ }
+ host, err = idna.ToASCII(host)
+ if err != nil {
+ // Non-UTF-8? Not representable in Punycode, in any
+ // case.
+ return "", err
+ }
+ if port == "" {
+ return host, nil
+ }
+ return net.JoinHostPort(host, port), nil
+}
diff --git a/vendor/golang.org/x/net/proxy/direct.go b/vendor/golang.org/x/net/proxy/direct.go
new file mode 100644
index 0000000..4c5ad88
--- /dev/null
+++ b/vendor/golang.org/x/net/proxy/direct.go
@@ -0,0 +1,18 @@
+// 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 proxy
+
+import (
+ "net"
+)
+
+type direct struct{}
+
+// Direct is a direct proxy: one that makes network connections directly.
+var Direct = direct{}
+
+func (direct) Dial(network, addr string) (net.Conn, error) {
+ return net.Dial(network, addr)
+}
diff --git a/vendor/golang.org/x/net/proxy/per_host.go b/vendor/golang.org/x/net/proxy/per_host.go
new file mode 100644
index 0000000..f540b19
--- /dev/null
+++ b/vendor/golang.org/x/net/proxy/per_host.go
@@ -0,0 +1,140 @@
+// 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 proxy
+
+import (
+ "net"
+ "strings"
+)
+
+// A PerHost directs connections to a default Dialer unless the hostname
+// requested matches one of a number of exceptions.
+type PerHost struct {
+ def, bypass Dialer
+
+ bypassNetworks []*net.IPNet
+ bypassIPs []net.IP
+ bypassZones []string
+ bypassHosts []string
+}
+
+// NewPerHost returns a PerHost Dialer that directs connections to either
+// defaultDialer or bypass, depending on whether the connection matches one of
+// the configured rules.
+func NewPerHost(defaultDialer, bypass Dialer) *PerHost {
+ return &PerHost{
+ def: defaultDialer,
+ bypass: bypass,
+ }
+}
+
+// Dial connects to the address addr on the given network through either
+// defaultDialer or bypass.
+func (p *PerHost) Dial(network, addr string) (c net.Conn, err error) {
+ host, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ return nil, err
+ }
+
+ return p.dialerForRequest(host).Dial(network, addr)
+}
+
+func (p *PerHost) dialerForRequest(host string) Dialer {
+ if ip := net.ParseIP(host); ip != nil {
+ for _, net := range p.bypassNetworks {
+ if net.Contains(ip) {
+ return p.bypass
+ }
+ }
+ for _, bypassIP := range p.bypassIPs {
+ if bypassIP.Equal(ip) {
+ return p.bypass
+ }
+ }
+ return p.def
+ }
+
+ for _, zone := range p.bypassZones {
+ if strings.HasSuffix(host, zone) {
+ return p.bypass
+ }
+ if host == zone[1:] {
+ // For a zone "example.com", we match "example.com"
+ // too.
+ return p.bypass
+ }
+ }
+ for _, bypassHost := range p.bypassHosts {
+ if bypassHost == host {
+ return p.bypass
+ }
+ }
+ return p.def
+}
+
+// AddFromString parses a string that contains comma-separated values
+// specifying hosts that should use the bypass proxy. Each value is either an
+// IP address, a CIDR range, a zone (*.example.com) or a hostname
+// (localhost). A best effort is made to parse the string and errors are
+// ignored.
+func (p *PerHost) AddFromString(s string) {
+ hosts := strings.Split(s, ",")
+ for _, host := range hosts {
+ host = strings.TrimSpace(host)
+ if len(host) == 0 {
+ continue
+ }
+ if strings.Contains(host, "/") {
+ // We assume that it's a CIDR address like 127.0.0.0/8
+ if _, net, err := net.ParseCIDR(host); err == nil {
+ p.AddNetwork(net)
+ }
+ continue
+ }
+ if ip := net.ParseIP(host); ip != nil {
+ p.AddIP(ip)
+ continue
+ }
+ if strings.HasPrefix(host, "*.") {
+ p.AddZone(host[1:])
+ continue
+ }
+ p.AddHost(host)
+ }
+}
+
+// AddIP specifies an IP address that will use the bypass proxy. Note that
+// this will only take effect if a literal IP address is dialed. A connection
+// to a named host will never match an IP.
+func (p *PerHost) AddIP(ip net.IP) {
+ p.bypassIPs = append(p.bypassIPs, ip)
+}
+
+// AddNetwork specifies an IP range that will use the bypass proxy. Note that
+// this will only take effect if a literal IP address is dialed. A connection
+// to a named host will never match.
+func (p *PerHost) AddNetwork(net *net.IPNet) {
+ p.bypassNetworks = append(p.bypassNetworks, net)
+}
+
+// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of
+// "example.com" matches "example.com" and all of its subdomains.
+func (p *PerHost) AddZone(zone string) {
+ if strings.HasSuffix(zone, ".") {
+ zone = zone[:len(zone)-1]
+ }
+ if !strings.HasPrefix(zone, ".") {
+ zone = "." + zone
+ }
+ p.bypassZones = append(p.bypassZones, zone)
+}
+
+// AddHost specifies a hostname that will use the bypass proxy.
+func (p *PerHost) AddHost(host string) {
+ if strings.HasSuffix(host, ".") {
+ host = host[:len(host)-1]
+ }
+ p.bypassHosts = append(p.bypassHosts, host)
+}
diff --git a/vendor/golang.org/x/net/proxy/proxy.go b/vendor/golang.org/x/net/proxy/proxy.go
new file mode 100644
index 0000000..78a8b7b
--- /dev/null
+++ b/vendor/golang.org/x/net/proxy/proxy.go
@@ -0,0 +1,94 @@
+// 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 proxy provides support for a variety of protocols to proxy network
+// data.
+package proxy // import "golang.org/x/net/proxy"
+
+import (
+ "errors"
+ "net"
+ "net/url"
+ "os"
+)
+
+// A Dialer is a means to establish a connection.
+type Dialer interface {
+ // Dial connects to the given address via the proxy.
+ Dial(network, addr string) (c net.Conn, err error)
+}
+
+// Auth contains authentication parameters that specific Dialers may require.
+type Auth struct {
+ User, Password string
+}
+
+// FromEnvironment returns the dialer specified by the proxy related variables in
+// the environment.
+func FromEnvironment() Dialer {
+ allProxy := os.Getenv("all_proxy")
+ if len(allProxy) == 0 {
+ return Direct
+ }
+
+ proxyURL, err := url.Parse(allProxy)
+ if err != nil {
+ return Direct
+ }
+ proxy, err := FromURL(proxyURL, Direct)
+ if err != nil {
+ return Direct
+ }
+
+ noProxy := os.Getenv("no_proxy")
+ if len(noProxy) == 0 {
+ return proxy
+ }
+
+ perHost := NewPerHost(proxy, Direct)
+ perHost.AddFromString(noProxy)
+ return perHost
+}
+
+// proxySchemes is a map from URL schemes to a function that creates a Dialer
+// from a URL with such a scheme.
+var proxySchemes map[string]func(*url.URL, Dialer) (Dialer, error)
+
+// RegisterDialerType takes a URL scheme and a function to generate Dialers from
+// a URL with that scheme and a forwarding Dialer. Registered schemes are used
+// by FromURL.
+func RegisterDialerType(scheme string, f func(*url.URL, Dialer) (Dialer, error)) {
+ if proxySchemes == nil {
+ proxySchemes = make(map[string]func(*url.URL, Dialer) (Dialer, error))
+ }
+ proxySchemes[scheme] = f
+}
+
+// FromURL returns a Dialer given a URL specification and an underlying
+// Dialer for it to make network requests.
+func FromURL(u *url.URL, forward Dialer) (Dialer, error) {
+ var auth *Auth
+ if u.User != nil {
+ auth = new(Auth)
+ auth.User = u.User.Username()
+ if p, ok := u.User.Password(); ok {
+ auth.Password = p
+ }
+ }
+
+ switch u.Scheme {
+ case "socks5":
+ return SOCKS5("tcp", u.Host, auth, forward)
+ }
+
+ // If the scheme doesn't match any of the built-in schemes, see if it
+ // was registered by another package.
+ if proxySchemes != nil {
+ if f, ok := proxySchemes[u.Scheme]; ok {
+ return f(u, forward)
+ }
+ }
+
+ return nil, errors.New("proxy: unknown scheme: " + u.Scheme)
+}
diff --git a/vendor/golang.org/x/net/proxy/socks5.go b/vendor/golang.org/x/net/proxy/socks5.go
new file mode 100644
index 0000000..973f57f
--- /dev/null
+++ b/vendor/golang.org/x/net/proxy/socks5.go
@@ -0,0 +1,213 @@
+// 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 proxy
+
+import (
+ "errors"
+ "io"
+ "net"
+ "strconv"
+)
+
+// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address
+// with an optional username and password. See RFC 1928.
+func SOCKS5(network, addr string, auth *Auth, forward Dialer) (Dialer, error) {
+ s := &socks5{
+ network: network,
+ addr: addr,
+ forward: forward,
+ }
+ if auth != nil {
+ s.user = auth.User
+ s.password = auth.Password
+ }
+
+ return s, nil
+}
+
+type socks5 struct {
+ user, password string
+ network, addr string
+ forward Dialer
+}
+
+const socks5Version = 5
+
+const (
+ socks5AuthNone = 0
+ socks5AuthPassword = 2
+)
+
+const socks5Connect = 1
+
+const (
+ socks5IP4 = 1
+ socks5Domain = 3
+ socks5IP6 = 4
+)
+
+var socks5Errors = []string{
+ "",
+ "general failure",
+ "connection forbidden",
+ "network unreachable",
+ "host unreachable",
+ "connection refused",
+ "TTL expired",
+ "command not supported",
+ "address type not supported",
+}
+
+// Dial connects to the address addr on the network net via the SOCKS5 proxy.
+func (s *socks5) Dial(network, addr string) (net.Conn, error) {
+ switch network {
+ case "tcp", "tcp6", "tcp4":
+ default:
+ return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network)
+ }
+
+ conn, err := s.forward.Dial(s.network, s.addr)
+ if err != nil {
+ return nil, err
+ }
+ if err := s.connect(conn, addr); err != nil {
+ conn.Close()
+ return nil, err
+ }
+ return conn, nil
+}
+
+// connect takes an existing connection to a socks5 proxy server,
+// and commands the server to extend that connection to target,
+// which must be a canonical address with a host and port.
+func (s *socks5) connect(conn net.Conn, target string) error {
+ host, portStr, err := net.SplitHostPort(target)
+ if err != nil {
+ return err
+ }
+
+ port, err := strconv.Atoi(portStr)
+ if err != nil {
+ return errors.New("proxy: failed to parse port number: " + portStr)
+ }
+ if port < 1 || port > 0xffff {
+ return errors.New("proxy: port number out of range: " + portStr)
+ }
+
+ // the size here is just an estimate
+ buf := make([]byte, 0, 6+len(host))
+
+ buf = append(buf, socks5Version)
+ if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 {
+ buf = append(buf, 2 /* num auth methods */, socks5AuthNone, socks5AuthPassword)
+ } else {
+ buf = append(buf, 1 /* num auth methods */, socks5AuthNone)
+ }
+
+ if _, err := conn.Write(buf); err != nil {
+ return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error())
+ }
+
+ if _, err := io.ReadFull(conn, buf[:2]); err != nil {
+ return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error())
+ }
+ if buf[0] != 5 {
+ return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0])))
+ }
+ if buf[1] == 0xff {
+ return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication")
+ }
+
+ if buf[1] == socks5AuthPassword {
+ buf = buf[:0]
+ buf = append(buf, 1 /* password protocol version */)
+ buf = append(buf, uint8(len(s.user)))
+ buf = append(buf, s.user...)
+ buf = append(buf, uint8(len(s.password)))
+ buf = append(buf, s.password...)
+
+ if _, err := conn.Write(buf); err != nil {
+ return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error())
+ }
+
+ if _, err := io.ReadFull(conn, buf[:2]); err != nil {
+ return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error())
+ }
+
+ if buf[1] != 0 {
+ return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password")
+ }
+ }
+
+ buf = buf[:0]
+ buf = append(buf, socks5Version, socks5Connect, 0 /* reserved */)
+
+ if ip := net.ParseIP(host); ip != nil {
+ if ip4 := ip.To4(); ip4 != nil {
+ buf = append(buf, socks5IP4)
+ ip = ip4
+ } else {
+ buf = append(buf, socks5IP6)
+ }
+ buf = append(buf, ip...)
+ } else {
+ if len(host) > 255 {
+ return errors.New("proxy: destination hostname too long: " + host)
+ }
+ buf = append(buf, socks5Domain)
+ buf = append(buf, byte(len(host)))
+ buf = append(buf, host...)
+ }
+ buf = append(buf, byte(port>>8), byte(port))
+
+ if _, err := conn.Write(buf); err != nil {
+ return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error())
+ }
+
+ if _, err := io.ReadFull(conn, buf[:4]); err != nil {
+ return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error())
+ }
+
+ failure := "unknown error"
+ if int(buf[1]) < len(socks5Errors) {
+ failure = socks5Errors[buf[1]]
+ }
+
+ if len(failure) > 0 {
+ return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure)
+ }
+
+ bytesToDiscard := 0
+ switch buf[3] {
+ case socks5IP4:
+ bytesToDiscard = net.IPv4len
+ case socks5IP6:
+ bytesToDiscard = net.IPv6len
+ case socks5Domain:
+ _, err := io.ReadFull(conn, buf[:1])
+ if err != nil {
+ return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error())
+ }
+ bytesToDiscard = int(buf[0])
+ default:
+ return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr)
+ }
+
+ if cap(buf) < bytesToDiscard {
+ buf = make([]byte, bytesToDiscard)
+ } else {
+ buf = buf[:bytesToDiscard]
+ }
+ if _, err := io.ReadFull(conn, buf); err != nil {
+ return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error())
+ }
+
+ // Also need to discard the port number
+ if _, err := io.ReadFull(conn, buf[:2]); err != nil {
+ return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error())
+ }
+
+ return nil
+}
diff --git a/vendor/golang.org/x/net/trace/events.go b/vendor/golang.org/x/net/trace/events.go
new file mode 100644
index 0000000..d8daec1
--- /dev/null
+++ b/vendor/golang.org/x/net/trace/events.go
@@ -0,0 +1,532 @@
+// Copyright 2015 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 trace
+
+import (
+ "bytes"
+ "fmt"
+ "html/template"
+ "io"
+ "log"
+ "net/http"
+ "runtime"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "text/tabwriter"
+ "time"
+)
+
+const maxEventsPerLog = 100
+
+type bucket struct {
+ MaxErrAge time.Duration
+ String string
+}
+
+var buckets = []bucket{
+ {0, "total"},
+ {10 * time.Second, "errs<10s"},
+ {1 * time.Minute, "errs<1m"},
+ {10 * time.Minute, "errs<10m"},
+ {1 * time.Hour, "errs<1h"},
+ {10 * time.Hour, "errs<10h"},
+ {24000 * time.Hour, "errors"},
+}
+
+// RenderEvents renders the HTML page typically served at /debug/events.
+// It does not do any auth checking; see AuthRequest for the default auth check
+// used by the handler registered on http.DefaultServeMux.
+// req may be nil.
+func RenderEvents(w http.ResponseWriter, req *http.Request, sensitive bool) {
+ now := time.Now()
+ data := &struct {
+ Families []string // family names
+ Buckets []bucket
+ Counts [][]int // eventLog count per family/bucket
+
+ // Set when a bucket has been selected.
+ Family string
+ Bucket int
+ EventLogs eventLogs
+ Expanded bool
+ }{
+ Buckets: buckets,
+ }
+
+ data.Families = make([]string, 0, len(families))
+ famMu.RLock()
+ for name := range families {
+ data.Families = append(data.Families, name)
+ }
+ famMu.RUnlock()
+ sort.Strings(data.Families)
+
+ // Count the number of eventLogs in each family for each error age.
+ data.Counts = make([][]int, len(data.Families))
+ for i, name := range data.Families {
+ // TODO(sameer): move this loop under the family lock.
+ f := getEventFamily(name)
+ data.Counts[i] = make([]int, len(data.Buckets))
+ for j, b := range data.Buckets {
+ data.Counts[i][j] = f.Count(now, b.MaxErrAge)
+ }
+ }
+
+ if req != nil {
+ var ok bool
+ data.Family, data.Bucket, ok = parseEventsArgs(req)
+ if !ok {
+ // No-op
+ } else {
+ data.EventLogs = getEventFamily(data.Family).Copy(now, buckets[data.Bucket].MaxErrAge)
+ }
+ if data.EventLogs != nil {
+ defer data.EventLogs.Free()
+ sort.Sort(data.EventLogs)
+ }
+ if exp, err := strconv.ParseBool(req.FormValue("exp")); err == nil {
+ data.Expanded = exp
+ }
+ }
+
+ famMu.RLock()
+ defer famMu.RUnlock()
+ if err := eventsTmpl().Execute(w, data); err != nil {
+ log.Printf("net/trace: Failed executing template: %v", err)
+ }
+}
+
+func parseEventsArgs(req *http.Request) (fam string, b int, ok bool) {
+ fam, bStr := req.FormValue("fam"), req.FormValue("b")
+ if fam == "" || bStr == "" {
+ return "", 0, false
+ }
+ b, err := strconv.Atoi(bStr)
+ if err != nil || b < 0 || b >= len(buckets) {
+ return "", 0, false
+ }
+ return fam, b, true
+}
+
+// An EventLog provides a log of events associated with a specific object.
+type EventLog interface {
+ // Printf formats its arguments with fmt.Sprintf and adds the
+ // result to the event log.
+ Printf(format string, a ...interface{})
+
+ // Errorf is like Printf, but it marks this event as an error.
+ Errorf(format string, a ...interface{})
+
+ // Finish declares that this event log is complete.
+ // The event log should not be used after calling this method.
+ Finish()
+}
+
+// NewEventLog returns a new EventLog with the specified family name
+// and title.
+func NewEventLog(family, title string) EventLog {
+ el := newEventLog()
+ el.ref()
+ el.Family, el.Title = family, title
+ el.Start = time.Now()
+ el.events = make([]logEntry, 0, maxEventsPerLog)
+ el.stack = make([]uintptr, 32)
+ n := runtime.Callers(2, el.stack)
+ el.stack = el.stack[:n]
+
+ getEventFamily(family).add(el)
+ return el
+}
+
+func (el *eventLog) Finish() {
+ getEventFamily(el.Family).remove(el)
+ el.unref() // matches ref in New
+}
+
+var (
+ famMu sync.RWMutex
+ families = make(map[string]*eventFamily) // family name => family
+)
+
+func getEventFamily(fam string) *eventFamily {
+ famMu.Lock()
+ defer famMu.Unlock()
+ f := families[fam]
+ if f == nil {
+ f = &eventFamily{}
+ families[fam] = f
+ }
+ return f
+}
+
+type eventFamily struct {
+ mu sync.RWMutex
+ eventLogs eventLogs
+}
+
+func (f *eventFamily) add(el *eventLog) {
+ f.mu.Lock()
+ f.eventLogs = append(f.eventLogs, el)
+ f.mu.Unlock()
+}
+
+func (f *eventFamily) remove(el *eventLog) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ for i, el0 := range f.eventLogs {
+ if el == el0 {
+ copy(f.eventLogs[i:], f.eventLogs[i+1:])
+ f.eventLogs = f.eventLogs[:len(f.eventLogs)-1]
+ return
+ }
+ }
+}
+
+func (f *eventFamily) Count(now time.Time, maxErrAge time.Duration) (n int) {
+ f.mu.RLock()
+ defer f.mu.RUnlock()
+ for _, el := range f.eventLogs {
+ if el.hasRecentError(now, maxErrAge) {
+ n++
+ }
+ }
+ return
+}
+
+func (f *eventFamily) Copy(now time.Time, maxErrAge time.Duration) (els eventLogs) {
+ f.mu.RLock()
+ defer f.mu.RUnlock()
+ els = make(eventLogs, 0, len(f.eventLogs))
+ for _, el := range f.eventLogs {
+ if el.hasRecentError(now, maxErrAge) {
+ el.ref()
+ els = append(els, el)
+ }
+ }
+ return
+}
+
+type eventLogs []*eventLog
+
+// Free calls unref on each element of the list.
+func (els eventLogs) Free() {
+ for _, el := range els {
+ el.unref()
+ }
+}
+
+// eventLogs may be sorted in reverse chronological order.
+func (els eventLogs) Len() int { return len(els) }
+func (els eventLogs) Less(i, j int) bool { return els[i].Start.After(els[j].Start) }
+func (els eventLogs) Swap(i, j int) { els[i], els[j] = els[j], els[i] }
+
+// A logEntry is a timestamped log entry in an event log.
+type logEntry struct {
+ When time.Time
+ Elapsed time.Duration // since previous event in log
+ NewDay bool // whether this event is on a different day to the previous event
+ What string
+ IsErr bool
+}
+
+// WhenString returns a string representation of the elapsed time of the event.
+// It will include the date if midnight was crossed.
+func (e logEntry) WhenString() string {
+ if e.NewDay {
+ return e.When.Format("2006/01/02 15:04:05.000000")
+ }
+ return e.When.Format("15:04:05.000000")
+}
+
+// An eventLog represents an active event log.
+type eventLog struct {
+ // Family is the top-level grouping of event logs to which this belongs.
+ Family string
+
+ // Title is the title of this event log.
+ Title string
+
+ // Timing information.
+ Start time.Time
+
+ // Call stack where this event log was created.
+ stack []uintptr
+
+ // Append-only sequence of events.
+ //
+ // TODO(sameer): change this to a ring buffer to avoid the array copy
+ // when we hit maxEventsPerLog.
+ mu sync.RWMutex
+ events []logEntry
+ LastErrorTime time.Time
+ discarded int
+
+ refs int32 // how many buckets this is in
+}
+
+func (el *eventLog) reset() {
+ // Clear all but the mutex. Mutexes may not be copied, even when unlocked.
+ el.Family = ""
+ el.Title = ""
+ el.Start = time.Time{}
+ el.stack = nil
+ el.events = nil
+ el.LastErrorTime = time.Time{}
+ el.discarded = 0
+ el.refs = 0
+}
+
+func (el *eventLog) hasRecentError(now time.Time, maxErrAge time.Duration) bool {
+ if maxErrAge == 0 {
+ return true
+ }
+ el.mu.RLock()
+ defer el.mu.RUnlock()
+ return now.Sub(el.LastErrorTime) < maxErrAge
+}
+
+// delta returns the elapsed time since the last event or the log start,
+// and whether it spans midnight.
+// L >= el.mu
+func (el *eventLog) delta(t time.Time) (time.Duration, bool) {
+ if len(el.events) == 0 {
+ return t.Sub(el.Start), false
+ }
+ prev := el.events[len(el.events)-1].When
+ return t.Sub(prev), prev.Day() != t.Day()
+
+}
+
+func (el *eventLog) Printf(format string, a ...interface{}) {
+ el.printf(false, format, a...)
+}
+
+func (el *eventLog) Errorf(format string, a ...interface{}) {
+ el.printf(true, format, a...)
+}
+
+func (el *eventLog) printf(isErr bool, format string, a ...interface{}) {
+ e := logEntry{When: time.Now(), IsErr: isErr, What: fmt.Sprintf(format, a...)}
+ el.mu.Lock()
+ e.Elapsed, e.NewDay = el.delta(e.When)
+ if len(el.events) < maxEventsPerLog {
+ el.events = append(el.events, e)
+ } else {
+ // Discard the oldest event.
+ if el.discarded == 0 {
+ // el.discarded starts at two to count for the event it
+ // is replacing, plus the next one that we are about to
+ // drop.
+ el.discarded = 2
+ } else {
+ el.discarded++
+ }
+ // TODO(sameer): if this causes allocations on a critical path,
+ // change eventLog.What to be a fmt.Stringer, as in trace.go.
+ el.events[0].What = fmt.Sprintf("(%d events discarded)", el.discarded)
+ // The timestamp of the discarded meta-event should be
+ // the time of the last event it is representing.
+ el.events[0].When = el.events[1].When
+ copy(el.events[1:], el.events[2:])
+ el.events[maxEventsPerLog-1] = e
+ }
+ if e.IsErr {
+ el.LastErrorTime = e.When
+ }
+ el.mu.Unlock()
+}
+
+func (el *eventLog) ref() {
+ atomic.AddInt32(&el.refs, 1)
+}
+
+func (el *eventLog) unref() {
+ if atomic.AddInt32(&el.refs, -1) == 0 {
+ freeEventLog(el)
+ }
+}
+
+func (el *eventLog) When() string {
+ return el.Start.Format("2006/01/02 15:04:05.000000")
+}
+
+func (el *eventLog) ElapsedTime() string {
+ elapsed := time.Since(el.Start)
+ return fmt.Sprintf("%.6f", elapsed.Seconds())
+}
+
+func (el *eventLog) Stack() string {
+ buf := new(bytes.Buffer)
+ tw := tabwriter.NewWriter(buf, 1, 8, 1, '\t', 0)
+ printStackRecord(tw, el.stack)
+ tw.Flush()
+ return buf.String()
+}
+
+// printStackRecord prints the function + source line information
+// for a single stack trace.
+// Adapted from runtime/pprof/pprof.go.
+func printStackRecord(w io.Writer, stk []uintptr) {
+ for _, pc := range stk {
+ f := runtime.FuncForPC(pc)
+ if f == nil {
+ continue
+ }
+ file, line := f.FileLine(pc)
+ name := f.Name()
+ // Hide runtime.goexit and any runtime functions at the beginning.
+ if strings.HasPrefix(name, "runtime.") {
+ continue
+ }
+ fmt.Fprintf(w, "# %s\t%s:%d\n", name, file, line)
+ }
+}
+
+func (el *eventLog) Events() []logEntry {
+ el.mu.RLock()
+ defer el.mu.RUnlock()
+ return el.events
+}
+
+// freeEventLogs is a freelist of *eventLog
+var freeEventLogs = make(chan *eventLog, 1000)
+
+// newEventLog returns a event log ready to use.
+func newEventLog() *eventLog {
+ select {
+ case el := <-freeEventLogs:
+ return el
+ default:
+ return new(eventLog)
+ }
+}
+
+// freeEventLog adds el to freeEventLogs if there's room.
+// This is non-blocking.
+func freeEventLog(el *eventLog) {
+ el.reset()
+ select {
+ case freeEventLogs <- el:
+ default:
+ }
+}
+
+var eventsTmplCache *template.Template
+var eventsTmplOnce sync.Once
+
+func eventsTmpl() *template.Template {
+ eventsTmplOnce.Do(func() {
+ eventsTmplCache = template.Must(template.New("events").Funcs(template.FuncMap{
+ "elapsed": elapsed,
+ "trimSpace": strings.TrimSpace,
+ }).Parse(eventsHTML))
+ })
+ return eventsTmplCache
+}
+
+const eventsHTML = `
+<html>
+ <head>
+ <title>events</title>
+ </head>
+ <style type="text/css">
+ body {
+ font-family: sans-serif;
+ }
+ table#req-status td.family {
+ padding-right: 2em;
+ }
+ table#req-status td.active {
+ padding-right: 1em;
+ }
+ table#req-status td.empty {
+ color: #aaa;
+ }
+ table#reqs {
+ margin-top: 1em;
+ }
+ table#reqs tr.first {
+ {{if $.Expanded}}font-weight: bold;{{end}}
+ }
+ table#reqs td {
+ font-family: monospace;
+ }
+ table#reqs td.when {
+ text-align: right;
+ white-space: nowrap;
+ }
+ table#reqs td.elapsed {
+ padding: 0 0.5em;
+ text-align: right;
+ white-space: pre;
+ width: 10em;
+ }
+ address {
+ font-size: smaller;
+ margin-top: 5em;
+ }
+ </style>
+ <body>
+
+<h1>/debug/events</h1>
+
+<table id="req-status">
+ {{range $i, $fam := .Families}}
+ <tr>
+ <td class="family">{{$fam}}</td>
+
+ {{range $j, $bucket := $.Buckets}}
+ {{$n := index $.Counts $i $j}}
+ <td class="{{if not $bucket.MaxErrAge}}active{{end}}{{if not $n}}empty{{end}}">
+ {{if $n}}<a href="?fam={{$fam}}&b={{$j}}{{if $.Expanded}}&exp=1{{end}}">{{end}}
+ [{{$n}} {{$bucket.String}}]
+ {{if $n}}</a>{{end}}
+ </td>
+ {{end}}
+
+ </tr>{{end}}
+</table>
+
+{{if $.EventLogs}}
+<hr />
+<h3>Family: {{$.Family}}</h3>
+
+{{if $.Expanded}}<a href="?fam={{$.Family}}&b={{$.Bucket}}">{{end}}
+[Summary]{{if $.Expanded}}</a>{{end}}
+
+{{if not $.Expanded}}<a href="?fam={{$.Family}}&b={{$.Bucket}}&exp=1">{{end}}
+[Expanded]{{if not $.Expanded}}</a>{{end}}
+
+<table id="reqs">
+ <tr><th>When</th><th>Elapsed</th></tr>
+ {{range $el := $.EventLogs}}
+ <tr class="first">
+ <td class="when">{{$el.When}}</td>
+ <td class="elapsed">{{$el.ElapsedTime}}</td>
+ <td>{{$el.Title}}
+ </tr>
+ {{if $.Expanded}}
+ <tr>
+ <td class="when"></td>
+ <td class="elapsed"></td>
+ <td><pre>{{$el.Stack|trimSpace}}</pre></td>
+ </tr>
+ {{range $el.Events}}
+ <tr>
+ <td class="when">{{.WhenString}}</td>
+ <td class="elapsed">{{elapsed .Elapsed}}</td>
+ <td>.{{if .IsErr}}E{{else}}.{{end}}. {{.What}}</td>
+ </tr>
+ {{end}}
+ {{end}}
+ {{end}}
+</table>
+{{end}}
+ </body>
+</html>
+`
diff --git a/vendor/golang.org/x/net/trace/histogram.go b/vendor/golang.org/x/net/trace/histogram.go
new file mode 100644
index 0000000..9bf4286
--- /dev/null
+++ b/vendor/golang.org/x/net/trace/histogram.go
@@ -0,0 +1,365 @@
+// Copyright 2015 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 trace
+
+// This file implements histogramming for RPC statistics collection.
+
+import (
+ "bytes"
+ "fmt"
+ "html/template"
+ "log"
+ "math"
+ "sync"
+
+ "golang.org/x/net/internal/timeseries"
+)
+
+const (
+ bucketCount = 38
+)
+
+// histogram keeps counts of values in buckets that are spaced
+// out in powers of 2: 0-1, 2-3, 4-7...
+// histogram implements timeseries.Observable
+type histogram struct {
+ sum int64 // running total of measurements
+ sumOfSquares float64 // square of running total
+ buckets []int64 // bucketed values for histogram
+ value int // holds a single value as an optimization
+ valueCount int64 // number of values recorded for single value
+}
+
+// AddMeasurement records a value measurement observation to the histogram.
+func (h *histogram) addMeasurement(value int64) {
+ // TODO: assert invariant
+ h.sum += value
+ h.sumOfSquares += float64(value) * float64(value)
+
+ bucketIndex := getBucket(value)
+
+ if h.valueCount == 0 || (h.valueCount > 0 && h.value == bucketIndex) {
+ h.value = bucketIndex
+ h.valueCount++
+ } else {
+ h.allocateBuckets()
+ h.buckets[bucketIndex]++
+ }
+}
+
+func (h *histogram) allocateBuckets() {
+ if h.buckets == nil {
+ h.buckets = make([]int64, bucketCount)
+ h.buckets[h.value] = h.valueCount
+ h.value = 0
+ h.valueCount = -1
+ }
+}
+
+func log2(i int64) int {
+ n := 0
+ for ; i >= 0x100; i >>= 8 {
+ n += 8
+ }
+ for ; i > 0; i >>= 1 {
+ n += 1
+ }
+ return n
+}
+
+func getBucket(i int64) (index int) {
+ index = log2(i) - 1
+ if index < 0 {
+ index = 0
+ }
+ if index >= bucketCount {
+ index = bucketCount - 1
+ }
+ return
+}
+
+// Total returns the number of recorded observations.
+func (h *histogram) total() (total int64) {
+ if h.valueCount >= 0 {
+ total = h.valueCount
+ }
+ for _, val := range h.buckets {
+ total += int64(val)
+ }
+ return
+}
+
+// Average returns the average value of recorded observations.
+func (h *histogram) average() float64 {
+ t := h.total()
+ if t == 0 {
+ return 0
+ }
+ return float64(h.sum) / float64(t)
+}
+
+// Variance returns the variance of recorded observations.
+func (h *histogram) variance() float64 {
+ t := float64(h.total())
+ if t == 0 {
+ return 0
+ }
+ s := float64(h.sum) / t
+ return h.sumOfSquares/t - s*s
+}
+
+// StandardDeviation returns the standard deviation of recorded observations.
+func (h *histogram) standardDeviation() float64 {
+ return math.Sqrt(h.variance())
+}
+
+// PercentileBoundary estimates the value that the given fraction of recorded
+// observations are less than.
+func (h *histogram) percentileBoundary(percentile float64) int64 {
+ total := h.total()
+
+ // Corner cases (make sure result is strictly less than Total())
+ if total == 0 {
+ return 0
+ } else if total == 1 {
+ return int64(h.average())
+ }
+
+ percentOfTotal := round(float64(total) * percentile)
+ var runningTotal int64
+
+ for i := range h.buckets {
+ value := h.buckets[i]
+ runningTotal += value
+ if runningTotal == percentOfTotal {
+ // We hit an exact bucket boundary. If the next bucket has data, it is a
+ // good estimate of the value. If the bucket is empty, we interpolate the
+ // midpoint between the next bucket's boundary and the next non-zero
+ // bucket. If the remaining buckets are all empty, then we use the
+ // boundary for the next bucket as the estimate.
+ j := uint8(i + 1)
+ min := bucketBoundary(j)
+ if runningTotal < total {
+ for h.buckets[j] == 0 {
+ j++
+ }
+ }
+ max := bucketBoundary(j)
+ return min + round(float64(max-min)/2)
+ } else if runningTotal > percentOfTotal {
+ // The value is in this bucket. Interpolate the value.
+ delta := runningTotal - percentOfTotal
+ percentBucket := float64(value-delta) / float64(value)
+ bucketMin := bucketBoundary(uint8(i))
+ nextBucketMin := bucketBoundary(uint8(i + 1))
+ bucketSize := nextBucketMin - bucketMin
+ return bucketMin + round(percentBucket*float64(bucketSize))
+ }
+ }
+ return bucketBoundary(bucketCount - 1)
+}
+
+// Median returns the estimated median of the observed values.
+func (h *histogram) median() int64 {
+ return h.percentileBoundary(0.5)
+}
+
+// Add adds other to h.
+func (h *histogram) Add(other timeseries.Observable) {
+ o := other.(*histogram)
+ if o.valueCount == 0 {
+ // Other histogram is empty
+ } else if h.valueCount >= 0 && o.valueCount > 0 && h.value == o.value {
+ // Both have a single bucketed value, aggregate them
+ h.valueCount += o.valueCount
+ } else {
+ // Two different values necessitate buckets in this histogram
+ h.allocateBuckets()
+ if o.valueCount >= 0 {
+ h.buckets[o.value] += o.valueCount
+ } else {
+ for i := range h.buckets {
+ h.buckets[i] += o.buckets[i]
+ }
+ }
+ }
+ h.sumOfSquares += o.sumOfSquares
+ h.sum += o.sum
+}
+
+// Clear resets the histogram to an empty state, removing all observed values.
+func (h *histogram) Clear() {
+ h.buckets = nil
+ h.value = 0
+ h.valueCount = 0
+ h.sum = 0
+ h.sumOfSquares = 0
+}
+
+// CopyFrom copies from other, which must be a *histogram, into h.
+func (h *histogram) CopyFrom(other timeseries.Observable) {
+ o := other.(*histogram)
+ if o.valueCount == -1 {
+ h.allocateBuckets()
+ copy(h.buckets, o.buckets)
+ }
+ h.sum = o.sum
+ h.sumOfSquares = o.sumOfSquares
+ h.value = o.value
+ h.valueCount = o.valueCount
+}
+
+// Multiply scales the histogram by the specified ratio.
+func (h *histogram) Multiply(ratio float64) {
+ if h.valueCount == -1 {
+ for i := range h.buckets {
+ h.buckets[i] = int64(float64(h.buckets[i]) * ratio)
+ }
+ } else {
+ h.valueCount = int64(float64(h.valueCount) * ratio)
+ }
+ h.sum = int64(float64(h.sum) * ratio)
+ h.sumOfSquares = h.sumOfSquares * ratio
+}
+
+// New creates a new histogram.
+func (h *histogram) New() timeseries.Observable {
+ r := new(histogram)
+ r.Clear()
+ return r
+}
+
+func (h *histogram) String() string {
+ return fmt.Sprintf("%d, %f, %d, %d, %v",
+ h.sum, h.sumOfSquares, h.value, h.valueCount, h.buckets)
+}
+
+// round returns the closest int64 to the argument
+func round(in float64) int64 {
+ return int64(math.Floor(in + 0.5))
+}
+
+// bucketBoundary returns the first value in the bucket.
+func bucketBoundary(bucket uint8) int64 {
+ if bucket == 0 {
+ return 0
+ }
+ return 1 << bucket
+}
+
+// bucketData holds data about a specific bucket for use in distTmpl.
+type bucketData struct {
+ Lower, Upper int64
+ N int64
+ Pct, CumulativePct float64
+ GraphWidth int
+}
+
+// data holds data about a Distribution for use in distTmpl.
+type data struct {
+ Buckets []*bucketData
+ Count, Median int64
+ Mean, StandardDeviation float64
+}
+
+// maxHTMLBarWidth is the maximum width of the HTML bar for visualizing buckets.
+const maxHTMLBarWidth = 350.0
+
+// newData returns data representing h for use in distTmpl.
+func (h *histogram) newData() *data {
+ // Force the allocation of buckets to simplify the rendering implementation
+ h.allocateBuckets()
+ // We scale the bars on the right so that the largest bar is
+ // maxHTMLBarWidth pixels in width.
+ maxBucket := int64(0)
+ for _, n := range h.buckets {
+ if n > maxBucket {
+ maxBucket = n
+ }
+ }
+ total := h.total()
+ barsizeMult := maxHTMLBarWidth / float64(maxBucket)
+ var pctMult float64
+ if total == 0 {
+ pctMult = 1.0
+ } else {
+ pctMult = 100.0 / float64(total)
+ }
+
+ buckets := make([]*bucketData, len(h.buckets))
+ runningTotal := int64(0)
+ for i, n := range h.buckets {
+ if n == 0 {
+ continue
+ }
+ runningTotal += n
+ var upperBound int64
+ if i < bucketCount-1 {
+ upperBound = bucketBoundary(uint8(i + 1))
+ } else {
+ upperBound = math.MaxInt64
+ }
+ buckets[i] = &bucketData{
+ Lower: bucketBoundary(uint8(i)),
+ Upper: upperBound,
+ N: n,
+ Pct: float64(n) * pctMult,
+ CumulativePct: float64(runningTotal) * pctMult,
+ GraphWidth: int(float64(n) * barsizeMult),
+ }
+ }
+ return &data{
+ Buckets: buckets,
+ Count: total,
+ Median: h.median(),
+ Mean: h.average(),
+ StandardDeviation: h.standardDeviation(),
+ }
+}
+
+func (h *histogram) html() template.HTML {
+ buf := new(bytes.Buffer)
+ if err := distTmpl().Execute(buf, h.newData()); err != nil {
+ buf.Reset()
+ log.Printf("net/trace: couldn't execute template: %v", err)
+ }
+ return template.HTML(buf.String())
+}
+
+var distTmplCache *template.Template
+var distTmplOnce sync.Once
+
+func distTmpl() *template.Template {
+ distTmplOnce.Do(func() {
+ // Input: data
+ distTmplCache = template.Must(template.New("distTmpl").Parse(`
+<table>
+<tr>
+ <td style="padding:0.25em">Count: {{.Count}}</td>
+ <td style="padding:0.25em">Mean: {{printf "%.0f" .Mean}}</td>
+ <td style="padding:0.25em">StdDev: {{printf "%.0f" .StandardDeviation}}</td>
+ <td style="padding:0.25em">Median: {{.Median}}</td>
+</tr>
+</table>
+<hr>
+<table>
+{{range $b := .Buckets}}
+{{if $b}}
+ <tr>
+ <td style="padding:0 0 0 0.25em">[</td>
+ <td style="text-align:right;padding:0 0.25em">{{.Lower}},</td>
+ <td style="text-align:right;padding:0 0.25em">{{.Upper}})</td>
+ <td style="text-align:right;padding:0 0.25em">{{.N}}</td>
+ <td style="text-align:right;padding:0 0.25em">{{printf "%#.3f" .Pct}}%</td>
+ <td style="text-align:right;padding:0 0.25em">{{printf "%#.3f" .CumulativePct}}%</td>
+ <td><div style="background-color: blue; height: 1em; width: {{.GraphWidth}};"></div></td>
+ </tr>
+{{end}}
+{{end}}
+</table>
+`))
+ })
+ return distTmplCache
+}
diff --git a/vendor/golang.org/x/net/trace/trace.go b/vendor/golang.org/x/net/trace/trace.go
new file mode 100644
index 0000000..3d9b646
--- /dev/null
+++ b/vendor/golang.org/x/net/trace/trace.go
@@ -0,0 +1,1066 @@
+// Copyright 2015 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 trace implements tracing of requests and long-lived objects.
+It exports HTTP interfaces on /debug/requests and /debug/events.
+
+A trace.Trace provides tracing for short-lived objects, usually requests.
+A request handler might be implemented like this:
+
+ func fooHandler(w http.ResponseWriter, req *http.Request) {
+ tr := trace.New("mypkg.Foo", req.URL.Path)
+ defer tr.Finish()
+ ...
+ tr.LazyPrintf("some event %q happened", str)
+ ...
+ if err := somethingImportant(); err != nil {
+ tr.LazyPrintf("somethingImportant failed: %v", err)
+ tr.SetError()
+ }
+ }
+
+The /debug/requests HTTP endpoint organizes the traces by family,
+errors, and duration. It also provides histogram of request duration
+for each family.
+
+A trace.EventLog provides tracing for long-lived objects, such as RPC
+connections.
+
+ // A Fetcher fetches URL paths for a single domain.
+ type Fetcher struct {
+ domain string
+ events trace.EventLog
+ }
+
+ func NewFetcher(domain string) *Fetcher {
+ return &Fetcher{
+ domain,
+ trace.NewEventLog("mypkg.Fetcher", domain),
+ }
+ }
+
+ func (f *Fetcher) Fetch(path string) (string, error) {
+ resp, err := http.Get("http://" + f.domain + "/" + path)
+ if err != nil {
+ f.events.Errorf("Get(%q) = %v", path, err)
+ return "", err
+ }
+ f.events.Printf("Get(%q) = %s", path, resp.Status)
+ ...
+ }
+
+ func (f *Fetcher) Close() error {
+ f.events.Finish()
+ return nil
+ }
+
+The /debug/events HTTP endpoint organizes the event logs by family and
+by time since the last error. The expanded view displays recent log
+entries and the log's call stack.
+*/
+package trace // import "golang.org/x/net/trace"
+
+import (
+ "bytes"
+ "fmt"
+ "html/template"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "runtime"
+ "sort"
+ "strconv"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "golang.org/x/net/internal/timeseries"
+)
+
+// DebugUseAfterFinish controls whether to debug uses of Trace values after finishing.
+// FOR DEBUGGING ONLY. This will slow down the program.
+var DebugUseAfterFinish = false
+
+// AuthRequest determines whether a specific request is permitted to load the
+// /debug/requests or /debug/events pages.
+//
+// It returns two bools; the first indicates whether the page may be viewed at all,
+// and the second indicates whether sensitive events will be shown.
+//
+// AuthRequest may be replaced by a program to customize its authorization requirements.
+//
+// The default AuthRequest function returns (true, true) if and only if the request
+// comes from localhost/127.0.0.1/[::1].
+var AuthRequest = func(req *http.Request) (any, sensitive bool) {
+ // RemoteAddr is commonly in the form "IP" or "IP:port".
+ // If it is in the form "IP:port", split off the port.
+ host, _, err := net.SplitHostPort(req.RemoteAddr)
+ if err != nil {
+ host = req.RemoteAddr
+ }
+ switch host {
+ case "localhost", "127.0.0.1", "::1":
+ return true, true
+ default:
+ return false, false
+ }
+}
+
+func init() {
+ http.HandleFunc("/debug/requests", func(w http.ResponseWriter, req *http.Request) {
+ any, sensitive := AuthRequest(req)
+ if !any {
+ http.Error(w, "not allowed", http.StatusUnauthorized)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ Render(w, req, sensitive)
+ })
+ http.HandleFunc("/debug/events", func(w http.ResponseWriter, req *http.Request) {
+ any, sensitive := AuthRequest(req)
+ if !any {
+ http.Error(w, "not allowed", http.StatusUnauthorized)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ RenderEvents(w, req, sensitive)
+ })
+}
+
+// Render renders the HTML page typically served at /debug/requests.
+// It does not do any auth checking; see AuthRequest for the default auth check
+// used by the handler registered on http.DefaultServeMux.
+// req may be nil.
+func Render(w io.Writer, req *http.Request, sensitive bool) {
+ data := &struct {
+ Families []string
+ ActiveTraceCount map[string]int
+ CompletedTraces map[string]*family
+
+ // Set when a bucket has been selected.
+ Traces traceList
+ Family string
+ Bucket int
+ Expanded bool
+ Traced bool
+ Active bool
+ ShowSensitive bool // whether to show sensitive events
+
+ Histogram template.HTML
+ HistogramWindow string // e.g. "last minute", "last hour", "all time"
+
+ // If non-zero, the set of traces is a partial set,
+ // and this is the total number.
+ Total int
+ }{
+ CompletedTraces: completedTraces,
+ }
+
+ data.ShowSensitive = sensitive
+ if req != nil {
+ // Allow show_sensitive=0 to force hiding of sensitive data for testing.
+ // This only goes one way; you can't use show_sensitive=1 to see things.
+ if req.FormValue("show_sensitive") == "0" {
+ data.ShowSensitive = false
+ }
+
+ if exp, err := strconv.ParseBool(req.FormValue("exp")); err == nil {
+ data.Expanded = exp
+ }
+ if exp, err := strconv.ParseBool(req.FormValue("rtraced")); err == nil {
+ data.Traced = exp
+ }
+ }
+
+ completedMu.RLock()
+ data.Families = make([]string, 0, len(completedTraces))
+ for fam := range completedTraces {
+ data.Families = append(data.Families, fam)
+ }
+ completedMu.RUnlock()
+ sort.Strings(data.Families)
+
+ // We are careful here to minimize the time spent locking activeMu,
+ // since that lock is required every time an RPC starts and finishes.
+ data.ActiveTraceCount = make(map[string]int, len(data.Families))
+ activeMu.RLock()
+ for fam, s := range activeTraces {
+ data.ActiveTraceCount[fam] = s.Len()
+ }
+ activeMu.RUnlock()
+
+ var ok bool
+ data.Family, data.Bucket, ok = parseArgs(req)
+ switch {
+ case !ok:
+ // No-op
+ case data.Bucket == -1:
+ data.Active = true
+ n := data.ActiveTraceCount[data.Family]
+ data.Traces = getActiveTraces(data.Family)
+ if len(data.Traces) < n {
+ data.Total = n
+ }
+ case data.Bucket < bucketsPerFamily:
+ if b := lookupBucket(data.Family, data.Bucket); b != nil {
+ data.Traces = b.Copy(data.Traced)
+ }
+ default:
+ if f := getFamily(data.Family, false); f != nil {
+ var obs timeseries.Observable
+ f.LatencyMu.RLock()
+ switch o := data.Bucket - bucketsPerFamily; o {
+ case 0:
+ obs = f.Latency.Minute()
+ data.HistogramWindow = "last minute"
+ case 1:
+ obs = f.Latency.Hour()
+ data.HistogramWindow = "last hour"
+ case 2:
+ obs = f.Latency.Total()
+ data.HistogramWindow = "all time"
+ }
+ f.LatencyMu.RUnlock()
+ if obs != nil {
+ data.Histogram = obs.(*histogram).html()
+ }
+ }
+ }
+
+ if data.Traces != nil {
+ defer data.Traces.Free()
+ sort.Sort(data.Traces)
+ }
+
+ completedMu.RLock()
+ defer completedMu.RUnlock()
+ if err := pageTmpl().ExecuteTemplate(w, "Page", data); err != nil {
+ log.Printf("net/trace: Failed executing template: %v", err)
+ }
+}
+
+func parseArgs(req *http.Request) (fam string, b int, ok bool) {
+ if req == nil {
+ return "", 0, false
+ }
+ fam, bStr := req.FormValue("fam"), req.FormValue("b")
+ if fam == "" || bStr == "" {
+ return "", 0, false
+ }
+ b, err := strconv.Atoi(bStr)
+ if err != nil || b < -1 {
+ return "", 0, false
+ }
+
+ return fam, b, true
+}
+
+func lookupBucket(fam string, b int) *traceBucket {
+ f := getFamily(fam, false)
+ if f == nil || b < 0 || b >= len(f.Buckets) {
+ return nil
+ }
+ return f.Buckets[b]
+}
+
+type contextKeyT string
+
+var contextKey = contextKeyT("golang.org/x/net/trace.Trace")
+
+// Trace represents an active request.
+type Trace interface {
+ // LazyLog adds x to the event log. It will be evaluated each time the
+ // /debug/requests page is rendered. Any memory referenced by x will be
+ // pinned until the trace is finished and later discarded.
+ LazyLog(x fmt.Stringer, sensitive bool)
+
+ // LazyPrintf evaluates its arguments with fmt.Sprintf each time the
+ // /debug/requests page is rendered. Any memory referenced by a will be
+ // pinned until the trace is finished and later discarded.
+ LazyPrintf(format string, a ...interface{})
+
+ // SetError declares that this trace resulted in an error.
+ SetError()
+
+ // SetRecycler sets a recycler for the trace.
+ // f will be called for each event passed to LazyLog at a time when
+ // it is no longer required, whether while the trace is still active
+ // and the event is discarded, or when a completed trace is discarded.
+ SetRecycler(f func(interface{}))
+
+ // SetTraceInfo sets the trace info for the trace.
+ // This is currently unused.
+ SetTraceInfo(traceID, spanID uint64)
+
+ // SetMaxEvents sets the maximum number of events that will be stored
+ // in the trace. This has no effect if any events have already been
+ // added to the trace.
+ SetMaxEvents(m int)
+
+ // Finish declares that this trace is complete.
+ // The trace should not be used after calling this method.
+ Finish()
+}
+
+type lazySprintf struct {
+ format string
+ a []interface{}
+}
+
+func (l *lazySprintf) String() string {
+ return fmt.Sprintf(l.format, l.a...)
+}
+
+// New returns a new Trace with the specified family and title.
+func New(family, title string) Trace {
+ tr := newTrace()
+ tr.ref()
+ tr.Family, tr.Title = family, title
+ tr.Start = time.Now()
+ tr.maxEvents = maxEventsPerTrace
+ tr.events = tr.eventsBuf[:0]
+
+ activeMu.RLock()
+ s := activeTraces[tr.Family]
+ activeMu.RUnlock()
+ if s == nil {
+ activeMu.Lock()
+ s = activeTraces[tr.Family] // check again
+ if s == nil {
+ s = new(traceSet)
+ activeTraces[tr.Family] = s
+ }
+ activeMu.Unlock()
+ }
+ s.Add(tr)
+
+ // Trigger allocation of the completed trace structure for this family.
+ // This will cause the family to be present in the request page during
+ // the first trace of this family. We don't care about the return value,
+ // nor is there any need for this to run inline, so we execute it in its
+ // own goroutine, but only if the family isn't allocated yet.
+ completedMu.RLock()
+ if _, ok := completedTraces[tr.Family]; !ok {
+ go allocFamily(tr.Family)
+ }
+ completedMu.RUnlock()
+
+ return tr
+}
+
+func (tr *trace) Finish() {
+ tr.Elapsed = time.Now().Sub(tr.Start)
+ if DebugUseAfterFinish {
+ buf := make([]byte, 4<<10) // 4 KB should be enough
+ n := runtime.Stack(buf, false)
+ tr.finishStack = buf[:n]
+ }
+
+ activeMu.RLock()
+ m := activeTraces[tr.Family]
+ activeMu.RUnlock()
+ m.Remove(tr)
+
+ f := getFamily(tr.Family, true)
+ for _, b := range f.Buckets {
+ if b.Cond.match(tr) {
+ b.Add(tr)
+ }
+ }
+ // Add a sample of elapsed time as microseconds to the family's timeseries
+ h := new(histogram)
+ h.addMeasurement(tr.Elapsed.Nanoseconds() / 1e3)
+ f.LatencyMu.Lock()
+ f.Latency.Add(h)
+ f.LatencyMu.Unlock()
+
+ tr.unref() // matches ref in New
+}
+
+const (
+ bucketsPerFamily = 9
+ tracesPerBucket = 10
+ maxActiveTraces = 20 // Maximum number of active traces to show.
+ maxEventsPerTrace = 10
+ numHistogramBuckets = 38
+)
+
+var (
+ // The active traces.
+ activeMu sync.RWMutex
+ activeTraces = make(map[string]*traceSet) // family -> traces
+
+ // Families of completed traces.
+ completedMu sync.RWMutex
+ completedTraces = make(map[string]*family) // family -> traces
+)
+
+type traceSet struct {
+ mu sync.RWMutex
+ m map[*trace]bool
+
+ // We could avoid the entire map scan in FirstN by having a slice of all the traces
+ // ordered by start time, and an index into that from the trace struct, with a periodic
+ // repack of the slice after enough traces finish; we could also use a skip list or similar.
+ // However, that would shift some of the expense from /debug/requests time to RPC time,
+ // which is probably the wrong trade-off.
+}
+
+func (ts *traceSet) Len() int {
+ ts.mu.RLock()
+ defer ts.mu.RUnlock()
+ return len(ts.m)
+}
+
+func (ts *traceSet) Add(tr *trace) {
+ ts.mu.Lock()
+ if ts.m == nil {
+ ts.m = make(map[*trace]bool)
+ }
+ ts.m[tr] = true
+ ts.mu.Unlock()
+}
+
+func (ts *traceSet) Remove(tr *trace) {
+ ts.mu.Lock()
+ delete(ts.m, tr)
+ ts.mu.Unlock()
+}
+
+// FirstN returns the first n traces ordered by time.
+func (ts *traceSet) FirstN(n int) traceList {
+ ts.mu.RLock()
+ defer ts.mu.RUnlock()
+
+ if n > len(ts.m) {
+ n = len(ts.m)
+ }
+ trl := make(traceList, 0, n)
+
+ // Fast path for when no selectivity is needed.
+ if n == len(ts.m) {
+ for tr := range ts.m {
+ tr.ref()
+ trl = append(trl, tr)
+ }
+ sort.Sort(trl)
+ return trl
+ }
+
+ // Pick the oldest n traces.
+ // This is inefficient. See the comment in the traceSet struct.
+ for tr := range ts.m {
+ // Put the first n traces into trl in the order they occur.
+ // When we have n, sort trl, and thereafter maintain its order.
+ if len(trl) < n {
+ tr.ref()
+ trl = append(trl, tr)
+ if len(trl) == n {
+ // This is guaranteed to happen exactly once during this loop.
+ sort.Sort(trl)
+ }
+ continue
+ }
+ if tr.Start.After(trl[n-1].Start) {
+ continue
+ }
+
+ // Find where to insert this one.
+ tr.ref()
+ i := sort.Search(n, func(i int) bool { return trl[i].Start.After(tr.Start) })
+ trl[n-1].unref()
+ copy(trl[i+1:], trl[i:])
+ trl[i] = tr
+ }
+
+ return trl
+}
+
+func getActiveTraces(fam string) traceList {
+ activeMu.RLock()
+ s := activeTraces[fam]
+ activeMu.RUnlock()
+ if s == nil {
+ return nil
+ }
+ return s.FirstN(maxActiveTraces)
+}
+
+func getFamily(fam string, allocNew bool) *family {
+ completedMu.RLock()
+ f := completedTraces[fam]
+ completedMu.RUnlock()
+ if f == nil && allocNew {
+ f = allocFamily(fam)
+ }
+ return f
+}
+
+func allocFamily(fam string) *family {
+ completedMu.Lock()
+ defer completedMu.Unlock()
+ f := completedTraces[fam]
+ if f == nil {
+ f = newFamily()
+ completedTraces[fam] = f
+ }
+ return f
+}
+
+// family represents a set of trace buckets and associated latency information.
+type family struct {
+ // traces may occur in multiple buckets.
+ Buckets [bucketsPerFamily]*traceBucket
+
+ // latency time series
+ LatencyMu sync.RWMutex
+ Latency *timeseries.MinuteHourSeries
+}
+
+func newFamily() *family {
+ return &family{
+ Buckets: [bucketsPerFamily]*traceBucket{
+ {Cond: minCond(0)},
+ {Cond: minCond(50 * time.Millisecond)},
+ {Cond: minCond(100 * time.Millisecond)},
+ {Cond: minCond(200 * time.Millisecond)},
+ {Cond: minCond(500 * time.Millisecond)},
+ {Cond: minCond(1 * time.Second)},
+ {Cond: minCond(10 * time.Second)},
+ {Cond: minCond(100 * time.Second)},
+ {Cond: errorCond{}},
+ },
+ Latency: timeseries.NewMinuteHourSeries(func() timeseries.Observable { return new(histogram) }),
+ }
+}
+
+// traceBucket represents a size-capped bucket of historic traces,
+// along with a condition for a trace to belong to the bucket.
+type traceBucket struct {
+ Cond cond
+
+ // Ring buffer implementation of a fixed-size FIFO queue.
+ mu sync.RWMutex
+ buf [tracesPerBucket]*trace
+ start int // < tracesPerBucket
+ length int // <= tracesPerBucket
+}
+
+func (b *traceBucket) Add(tr *trace) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+
+ i := b.start + b.length
+ if i >= tracesPerBucket {
+ i -= tracesPerBucket
+ }
+ if b.length == tracesPerBucket {
+ // "Remove" an element from the bucket.
+ b.buf[i].unref()
+ b.start++
+ if b.start == tracesPerBucket {
+ b.start = 0
+ }
+ }
+ b.buf[i] = tr
+ if b.length < tracesPerBucket {
+ b.length++
+ }
+ tr.ref()
+}
+
+// Copy returns a copy of the traces in the bucket.
+// If tracedOnly is true, only the traces with trace information will be returned.
+// The logs will be ref'd before returning; the caller should call
+// the Free method when it is done with them.
+// TODO(dsymonds): keep track of traced requests in separate buckets.
+func (b *traceBucket) Copy(tracedOnly bool) traceList {
+ b.mu.RLock()
+ defer b.mu.RUnlock()
+
+ trl := make(traceList, 0, b.length)
+ for i, x := 0, b.start; i < b.length; i++ {
+ tr := b.buf[x]
+ if !tracedOnly || tr.spanID != 0 {
+ tr.ref()
+ trl = append(trl, tr)
+ }
+ x++
+ if x == b.length {
+ x = 0
+ }
+ }
+ return trl
+}
+
+func (b *traceBucket) Empty() bool {
+ b.mu.RLock()
+ defer b.mu.RUnlock()
+ return b.length == 0
+}
+
+// cond represents a condition on a trace.
+type cond interface {
+ match(t *trace) bool
+ String() string
+}
+
+type minCond time.Duration
+
+func (m minCond) match(t *trace) bool { return t.Elapsed >= time.Duration(m) }
+func (m minCond) String() string { return fmt.Sprintf("≥%gs", time.Duration(m).Seconds()) }
+
+type errorCond struct{}
+
+func (e errorCond) match(t *trace) bool { return t.IsError }
+func (e errorCond) String() string { return "errors" }
+
+type traceList []*trace
+
+// Free calls unref on each element of the list.
+func (trl traceList) Free() {
+ for _, t := range trl {
+ t.unref()
+ }
+}
+
+// traceList may be sorted in reverse chronological order.
+func (trl traceList) Len() int { return len(trl) }
+func (trl traceList) Less(i, j int) bool { return trl[i].Start.After(trl[j].Start) }
+func (trl traceList) Swap(i, j int) { trl[i], trl[j] = trl[j], trl[i] }
+
+// An event is a timestamped log entry in a trace.
+type event struct {
+ When time.Time
+ Elapsed time.Duration // since previous event in trace
+ NewDay bool // whether this event is on a different day to the previous event
+ Recyclable bool // whether this event was passed via LazyLog
+ Sensitive bool // whether this event contains sensitive information
+ What interface{} // string or fmt.Stringer
+}
+
+// WhenString returns a string representation of the elapsed time of the event.
+// It will include the date if midnight was crossed.
+func (e event) WhenString() string {
+ if e.NewDay {
+ return e.When.Format("2006/01/02 15:04:05.000000")
+ }
+ return e.When.Format("15:04:05.000000")
+}
+
+// discarded represents a number of discarded events.
+// It is stored as *discarded to make it easier to update in-place.
+type discarded int
+
+func (d *discarded) String() string {
+ return fmt.Sprintf("(%d events discarded)", int(*d))
+}
+
+// trace represents an active or complete request,
+// either sent or received by this program.
+type trace struct {
+ // Family is the top-level grouping of traces to which this belongs.
+ Family string
+
+ // Title is the title of this trace.
+ Title string
+
+ // Timing information.
+ Start time.Time
+ Elapsed time.Duration // zero while active
+
+ // Trace information if non-zero.
+ traceID uint64
+ spanID uint64
+
+ // Whether this trace resulted in an error.
+ IsError bool
+
+ // Append-only sequence of events (modulo discards).
+ mu sync.RWMutex
+ events []event
+ maxEvents int
+
+ refs int32 // how many buckets this is in
+ recycler func(interface{})
+ disc discarded // scratch space to avoid allocation
+
+ finishStack []byte // where finish was called, if DebugUseAfterFinish is set
+
+ eventsBuf [4]event // preallocated buffer in case we only log a few events
+}
+
+func (tr *trace) reset() {
+ // Clear all but the mutex. Mutexes may not be copied, even when unlocked.
+ tr.Family = ""
+ tr.Title = ""
+ tr.Start = time.Time{}
+ tr.Elapsed = 0
+ tr.traceID = 0
+ tr.spanID = 0
+ tr.IsError = false
+ tr.maxEvents = 0
+ tr.events = nil
+ tr.refs = 0
+ tr.recycler = nil
+ tr.disc = 0
+ tr.finishStack = nil
+ for i := range tr.eventsBuf {
+ tr.eventsBuf[i] = event{}
+ }
+}
+
+// delta returns the elapsed time since the last event or the trace start,
+// and whether it spans midnight.
+// L >= tr.mu
+func (tr *trace) delta(t time.Time) (time.Duration, bool) {
+ if len(tr.events) == 0 {
+ return t.Sub(tr.Start), false
+ }
+ prev := tr.events[len(tr.events)-1].When
+ return t.Sub(prev), prev.Day() != t.Day()
+}
+
+func (tr *trace) addEvent(x interface{}, recyclable, sensitive bool) {
+ if DebugUseAfterFinish && tr.finishStack != nil {
+ buf := make([]byte, 4<<10) // 4 KB should be enough
+ n := runtime.Stack(buf, false)
+ log.Printf("net/trace: trace used after finish:\nFinished at:\n%s\nUsed at:\n%s", tr.finishStack, buf[:n])
+ }
+
+ /*
+ NOTE TO DEBUGGERS
+
+ If you are here because your program panicked in this code,
+ it is almost definitely the fault of code using this package,
+ and very unlikely to be the fault of this code.
+
+ The most likely scenario is that some code elsewhere is using
+ a trace.Trace after its Finish method is called.
+ You can temporarily set the DebugUseAfterFinish var
+ to help discover where that is; do not leave that var set,
+ since it makes this package much less efficient.
+ */
+
+ e := event{When: time.Now(), What: x, Recyclable: recyclable, Sensitive: sensitive}
+ tr.mu.Lock()
+ e.Elapsed, e.NewDay = tr.delta(e.When)
+ if len(tr.events) < tr.maxEvents {
+ tr.events = append(tr.events, e)
+ } else {
+ // Discard the middle events.
+ di := int((tr.maxEvents - 1) / 2)
+ if d, ok := tr.events[di].What.(*discarded); ok {
+ (*d)++
+ } else {
+ // disc starts at two to count for the event it is replacing,
+ // plus the next one that we are about to drop.
+ tr.disc = 2
+ if tr.recycler != nil && tr.events[di].Recyclable {
+ go tr.recycler(tr.events[di].What)
+ }
+ tr.events[di].What = &tr.disc
+ }
+ // The timestamp of the discarded meta-event should be
+ // the time of the last event it is representing.
+ tr.events[di].When = tr.events[di+1].When
+
+ if tr.recycler != nil && tr.events[di+1].Recyclable {
+ go tr.recycler(tr.events[di+1].What)
+ }
+ copy(tr.events[di+1:], tr.events[di+2:])
+ tr.events[tr.maxEvents-1] = e
+ }
+ tr.mu.Unlock()
+}
+
+func (tr *trace) LazyLog(x fmt.Stringer, sensitive bool) {
+ tr.addEvent(x, true, sensitive)
+}
+
+func (tr *trace) LazyPrintf(format string, a ...interface{}) {
+ tr.addEvent(&lazySprintf{format, a}, false, false)
+}
+
+func (tr *trace) SetError() { tr.IsError = true }
+
+func (tr *trace) SetRecycler(f func(interface{})) {
+ tr.recycler = f
+}
+
+func (tr *trace) SetTraceInfo(traceID, spanID uint64) {
+ tr.traceID, tr.spanID = traceID, spanID
+}
+
+func (tr *trace) SetMaxEvents(m int) {
+ // Always keep at least three events: first, discarded count, last.
+ if len(tr.events) == 0 && m > 3 {
+ tr.maxEvents = m
+ }
+}
+
+func (tr *trace) ref() {
+ atomic.AddInt32(&tr.refs, 1)
+}
+
+func (tr *trace) unref() {
+ if atomic.AddInt32(&tr.refs, -1) == 0 {
+ if tr.recycler != nil {
+ // freeTrace clears tr, so we hold tr.recycler and tr.events here.
+ go func(f func(interface{}), es []event) {
+ for _, e := range es {
+ if e.Recyclable {
+ f(e.What)
+ }
+ }
+ }(tr.recycler, tr.events)
+ }
+
+ freeTrace(tr)
+ }
+}
+
+func (tr *trace) When() string {
+ return tr.Start.Format("2006/01/02 15:04:05.000000")
+}
+
+func (tr *trace) ElapsedTime() string {
+ t := tr.Elapsed
+ if t == 0 {
+ // Active trace.
+ t = time.Since(tr.Start)
+ }
+ return fmt.Sprintf("%.6f", t.Seconds())
+}
+
+func (tr *trace) Events() []event {
+ tr.mu.RLock()
+ defer tr.mu.RUnlock()
+ return tr.events
+}
+
+var traceFreeList = make(chan *trace, 1000) // TODO(dsymonds): Use sync.Pool?
+
+// newTrace returns a trace ready to use.
+func newTrace() *trace {
+ select {
+ case tr := <-traceFreeList:
+ return tr
+ default:
+ return new(trace)
+ }
+}
+
+// freeTrace adds tr to traceFreeList if there's room.
+// This is non-blocking.
+func freeTrace(tr *trace) {
+ if DebugUseAfterFinish {
+ return // never reuse
+ }
+ tr.reset()
+ select {
+ case traceFreeList <- tr:
+ default:
+ }
+}
+
+func elapsed(d time.Duration) string {
+ b := []byte(fmt.Sprintf("%.6f", d.Seconds()))
+
+ // For subsecond durations, blank all zeros before decimal point,
+ // and all zeros between the decimal point and the first non-zero digit.
+ if d < time.Second {
+ dot := bytes.IndexByte(b, '.')
+ for i := 0; i < dot; i++ {
+ b[i] = ' '
+ }
+ for i := dot + 1; i < len(b); i++ {
+ if b[i] == '0' {
+ b[i] = ' '
+ } else {
+ break
+ }
+ }
+ }
+
+ return string(b)
+}
+
+var pageTmplCache *template.Template
+var pageTmplOnce sync.Once
+
+func pageTmpl() *template.Template {
+ pageTmplOnce.Do(func() {
+ pageTmplCache = template.Must(template.New("Page").Funcs(template.FuncMap{
+ "elapsed": elapsed,
+ "add": func(a, b int) int { return a + b },
+ }).Parse(pageHTML))
+ })
+ return pageTmplCache
+}
+
+const pageHTML = `
+{{template "Prolog" .}}
+{{template "StatusTable" .}}
+{{template "Epilog" .}}
+
+{{define "Prolog"}}
+<html>
+ <head>
+ <title>/debug/requests</title>
+ <style type="text/css">
+ body {
+ font-family: sans-serif;
+ }
+ table#tr-status td.family {
+ padding-right: 2em;
+ }
+ table#tr-status td.active {
+ padding-right: 1em;
+ }
+ table#tr-status td.latency-first {
+ padding-left: 1em;
+ }
+ table#tr-status td.empty {
+ color: #aaa;
+ }
+ table#reqs {
+ margin-top: 1em;
+ }
+ table#reqs tr.first {
+ {{if $.Expanded}}font-weight: bold;{{end}}
+ }
+ table#reqs td {
+ font-family: monospace;
+ }
+ table#reqs td.when {
+ text-align: right;
+ white-space: nowrap;
+ }
+ table#reqs td.elapsed {
+ padding: 0 0.5em;
+ text-align: right;
+ white-space: pre;
+ width: 10em;
+ }
+ address {
+ font-size: smaller;
+ margin-top: 5em;
+ }
+ </style>
+ </head>
+ <body>
+
+<h1>/debug/requests</h1>
+{{end}} {{/* end of Prolog */}}
+
+{{define "StatusTable"}}
+<table id="tr-status">
+ {{range $fam := .Families}}
+ <tr>
+ <td class="family">{{$fam}}</td>
+
+ {{$n := index $.ActiveTraceCount $fam}}
+ <td class="active {{if not $n}}empty{{end}}">
+ {{if $n}}<a href="?fam={{$fam}}&b=-1{{if $.Expanded}}&exp=1{{end}}">{{end}}
+ [{{$n}} active]
+ {{if $n}}</a>{{end}}
+ </td>
+
+ {{$f := index $.CompletedTraces $fam}}
+ {{range $i, $b := $f.Buckets}}
+ {{$empty := $b.Empty}}
+ <td {{if $empty}}class="empty"{{end}}>
+ {{if not $empty}}<a href="?fam={{$fam}}&b={{$i}}{{if $.Expanded}}&exp=1{{end}}">{{end}}
+ [{{.Cond}}]
+ {{if not $empty}}</a>{{end}}
+ </td>
+ {{end}}
+
+ {{$nb := len $f.Buckets}}
+ <td class="latency-first">
+ <a href="?fam={{$fam}}&b={{$nb}}">[minute]</a>
+ </td>
+ <td>
+ <a href="?fam={{$fam}}&b={{add $nb 1}}">[hour]</a>
+ </td>
+ <td>
+ <a href="?fam={{$fam}}&b={{add $nb 2}}">[total]</a>
+ </td>
+
+ </tr>
+ {{end}}
+</table>
+{{end}} {{/* end of StatusTable */}}
+
+{{define "Epilog"}}
+{{if $.Traces}}
+<hr />
+<h3>Family: {{$.Family}}</h3>
+
+{{if or $.Expanded $.Traced}}
+ <a href="?fam={{$.Family}}&b={{$.Bucket}}">[Normal/Summary]</a>
+{{else}}
+ [Normal/Summary]
+{{end}}
+
+{{if or (not $.Expanded) $.Traced}}
+ <a href="?fam={{$.Family}}&b={{$.Bucket}}&exp=1">[Normal/Expanded]</a>
+{{else}}
+ [Normal/Expanded]
+{{end}}
+
+{{if not $.Active}}
+ {{if or $.Expanded (not $.Traced)}}
+ <a href="?fam={{$.Family}}&b={{$.Bucket}}&rtraced=1">[Traced/Summary]</a>
+ {{else}}
+ [Traced/Summary]
+ {{end}}
+ {{if or (not $.Expanded) (not $.Traced)}}
+ <a href="?fam={{$.Family}}&b={{$.Bucket}}&exp=1&rtraced=1">[Traced/Expanded]</a>
+ {{else}}
+ [Traced/Expanded]
+ {{end}}
+{{end}}
+
+{{if $.Total}}
+<p><em>Showing <b>{{len $.Traces}}</b> of <b>{{$.Total}}</b> traces.</em></p>
+{{end}}
+
+<table id="reqs">
+ <caption>
+ {{if $.Active}}Active{{else}}Completed{{end}} Requests
+ </caption>
+ <tr><th>When</th><th>Elapsed&nbsp;(s)</th></tr>
+ {{range $tr := $.Traces}}
+ <tr class="first">
+ <td class="when">{{$tr.When}}</td>
+ <td class="elapsed">{{$tr.ElapsedTime}}</td>
+ <td>{{$tr.Title}}</td>
+ {{/* TODO: include traceID/spanID */}}
+ </tr>
+ {{if $.Expanded}}
+ {{range $tr.Events}}
+ <tr>
+ <td class="when">{{.WhenString}}</td>
+ <td class="elapsed">{{elapsed .Elapsed}}</td>
+ <td>{{if or $.ShowSensitive (not .Sensitive)}}... {{.What}}{{else}}<em>[redacted]</em>{{end}}</td>
+ </tr>
+ {{end}}
+ {{end}}
+ {{end}}
+</table>
+{{end}} {{/* if $.Traces */}}
+
+{{if $.Histogram}}
+<h4>Latency (&micro;s) of {{$.Family}} over {{$.HistogramWindow}}</h4>
+{{$.Histogram}}
+{{end}} {{/* if $.Histogram */}}
+
+ </body>
+</html>
+{{end}} {{/* end of Epilog */}}
+`
diff --git a/vendor/golang.org/x/net/trace/trace_go16.go b/vendor/golang.org/x/net/trace/trace_go16.go
new file mode 100644
index 0000000..d608191
--- /dev/null
+++ b/vendor/golang.org/x/net/trace/trace_go16.go
@@ -0,0 +1,21 @@
+// Copyright 2017 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 !go1.7
+
+package trace
+
+import "golang.org/x/net/context"
+
+// NewContext returns a copy of the parent context
+// and associates it with a Trace.
+func NewContext(ctx context.Context, tr Trace) context.Context {
+ return context.WithValue(ctx, contextKey, tr)
+}
+
+// FromContext returns the Trace bound to the context, if any.
+func FromContext(ctx context.Context) (tr Trace, ok bool) {
+ tr, ok = ctx.Value(contextKey).(Trace)
+ return
+}
diff --git a/vendor/golang.org/x/net/trace/trace_go17.go b/vendor/golang.org/x/net/trace/trace_go17.go
new file mode 100644
index 0000000..df6e1fb
--- /dev/null
+++ b/vendor/golang.org/x/net/trace/trace_go17.go
@@ -0,0 +1,21 @@
+// Copyright 2017 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 go1.7
+
+package trace
+
+import "context"
+
+// NewContext returns a copy of the parent context
+// and associates it with a Trace.
+func NewContext(ctx context.Context, tr Trace) context.Context {
+ return context.WithValue(ctx, contextKey, tr)
+}
+
+// FromContext returns the Trace bound to the context, if any.
+func FromContext(ctx context.Context) (tr Trace, ok bool) {
+ tr, ok = ctx.Value(contextKey).(Trace)
+ return
+}
diff --git a/vendor/golang.org/x/net/websocket/client.go b/vendor/golang.org/x/net/websocket/client.go
new file mode 100644
index 0000000..69a4ac7
--- /dev/null
+++ b/vendor/golang.org/x/net/websocket/client.go
@@ -0,0 +1,106 @@
+// Copyright 2009 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 websocket
+
+import (
+ "bufio"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+)
+
+// DialError is an error that occurs while dialling a websocket server.
+type DialError struct {
+ *Config
+ Err error
+}
+
+func (e *DialError) Error() string {
+ return "websocket.Dial " + e.Config.Location.String() + ": " + e.Err.Error()
+}
+
+// NewConfig creates a new WebSocket config for client connection.
+func NewConfig(server, origin string) (config *Config, err error) {
+ config = new(Config)
+ config.Version = ProtocolVersionHybi13
+ config.Location, err = url.ParseRequestURI(server)
+ if err != nil {
+ return
+ }
+ config.Origin, err = url.ParseRequestURI(origin)
+ if err != nil {
+ return
+ }
+ config.Header = http.Header(make(map[string][]string))
+ return
+}
+
+// NewClient creates a new WebSocket client connection over rwc.
+func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) {
+ br := bufio.NewReader(rwc)
+ bw := bufio.NewWriter(rwc)
+ err = hybiClientHandshake(config, br, bw)
+ if err != nil {
+ return
+ }
+ buf := bufio.NewReadWriter(br, bw)
+ ws = newHybiClientConn(config, buf, rwc)
+ return
+}
+
+// Dial opens a new client connection to a WebSocket.
+func Dial(url_, protocol, origin string) (ws *Conn, err error) {
+ config, err := NewConfig(url_, origin)
+ if err != nil {
+ return nil, err
+ }
+ if protocol != "" {
+ config.Protocol = []string{protocol}
+ }
+ return DialConfig(config)
+}
+
+var portMap = map[string]string{
+ "ws": "80",
+ "wss": "443",
+}
+
+func parseAuthority(location *url.URL) string {
+ if _, ok := portMap[location.Scheme]; ok {
+ if _, _, err := net.SplitHostPort(location.Host); err != nil {
+ return net.JoinHostPort(location.Host, portMap[location.Scheme])
+ }
+ }
+ return location.Host
+}
+
+// DialConfig opens a new client connection to a WebSocket with a config.
+func DialConfig(config *Config) (ws *Conn, err error) {
+ var client net.Conn
+ if config.Location == nil {
+ return nil, &DialError{config, ErrBadWebSocketLocation}
+ }
+ if config.Origin == nil {
+ return nil, &DialError{config, ErrBadWebSocketOrigin}
+ }
+ dialer := config.Dialer
+ if dialer == nil {
+ dialer = &net.Dialer{}
+ }
+ client, err = dialWithDialer(dialer, config)
+ if err != nil {
+ goto Error
+ }
+ ws, err = NewClient(config, client)
+ if err != nil {
+ client.Close()
+ goto Error
+ }
+ return
+
+Error:
+ return nil, &DialError{config, err}
+}
diff --git a/vendor/golang.org/x/net/websocket/dial.go b/vendor/golang.org/x/net/websocket/dial.go
new file mode 100644
index 0000000..2dab943
--- /dev/null
+++ b/vendor/golang.org/x/net/websocket/dial.go
@@ -0,0 +1,24 @@
+// Copyright 2015 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 websocket
+
+import (
+ "crypto/tls"
+ "net"
+)
+
+func dialWithDialer(dialer *net.Dialer, config *Config) (conn net.Conn, err error) {
+ switch config.Location.Scheme {
+ case "ws":
+ conn, err = dialer.Dial("tcp", parseAuthority(config.Location))
+
+ case "wss":
+ conn, err = tls.DialWithDialer(dialer, "tcp", parseAuthority(config.Location), config.TlsConfig)
+
+ default:
+ err = ErrBadScheme
+ }
+ return
+}
diff --git a/vendor/golang.org/x/net/websocket/hybi.go b/vendor/golang.org/x/net/websocket/hybi.go
new file mode 100644
index 0000000..8cffdd1
--- /dev/null
+++ b/vendor/golang.org/x/net/websocket/hybi.go
@@ -0,0 +1,583 @@
+// 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 websocket
+
+// This file implements a protocol of hybi draft.
+// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17
+
+import (
+ "bufio"
+ "bytes"
+ "crypto/rand"
+ "crypto/sha1"
+ "encoding/base64"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "strings"
+)
+
+const (
+ websocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+
+ closeStatusNormal = 1000
+ closeStatusGoingAway = 1001
+ closeStatusProtocolError = 1002
+ closeStatusUnsupportedData = 1003
+ closeStatusFrameTooLarge = 1004
+ closeStatusNoStatusRcvd = 1005
+ closeStatusAbnormalClosure = 1006
+ closeStatusBadMessageData = 1007
+ closeStatusPolicyViolation = 1008
+ closeStatusTooBigData = 1009
+ closeStatusExtensionMismatch = 1010
+
+ maxControlFramePayloadLength = 125
+)
+
+var (
+ ErrBadMaskingKey = &ProtocolError{"bad masking key"}
+ ErrBadPongMessage = &ProtocolError{"bad pong message"}
+ ErrBadClosingStatus = &ProtocolError{"bad closing status"}
+ ErrUnsupportedExtensions = &ProtocolError{"unsupported extensions"}
+ ErrNotImplemented = &ProtocolError{"not implemented"}
+
+ handshakeHeader = map[string]bool{
+ "Host": true,
+ "Upgrade": true,
+ "Connection": true,
+ "Sec-Websocket-Key": true,
+ "Sec-Websocket-Origin": true,
+ "Sec-Websocket-Version": true,
+ "Sec-Websocket-Protocol": true,
+ "Sec-Websocket-Accept": true,
+ }
+)
+
+// A hybiFrameHeader is a frame header as defined in hybi draft.
+type hybiFrameHeader struct {
+ Fin bool
+ Rsv [3]bool
+ OpCode byte
+ Length int64
+ MaskingKey []byte
+
+ data *bytes.Buffer
+}
+
+// A hybiFrameReader is a reader for hybi frame.
+type hybiFrameReader struct {
+ reader io.Reader
+
+ header hybiFrameHeader
+ pos int64
+ length int
+}
+
+func (frame *hybiFrameReader) Read(msg []byte) (n int, err error) {
+ n, err = frame.reader.Read(msg)
+ if frame.header.MaskingKey != nil {
+ for i := 0; i < n; i++ {
+ msg[i] = msg[i] ^ frame.header.MaskingKey[frame.pos%4]
+ frame.pos++
+ }
+ }
+ return n, err
+}
+
+func (frame *hybiFrameReader) PayloadType() byte { return frame.header.OpCode }
+
+func (frame *hybiFrameReader) HeaderReader() io.Reader {
+ if frame.header.data == nil {
+ return nil
+ }
+ if frame.header.data.Len() == 0 {
+ return nil
+ }
+ return frame.header.data
+}
+
+func (frame *hybiFrameReader) TrailerReader() io.Reader { return nil }
+
+func (frame *hybiFrameReader) Len() (n int) { return frame.length }
+
+// A hybiFrameReaderFactory creates new frame reader based on its frame type.
+type hybiFrameReaderFactory struct {
+ *bufio.Reader
+}
+
+// NewFrameReader reads a frame header from the connection, and creates new reader for the frame.
+// See Section 5.2 Base Framing protocol for detail.
+// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5.2
+func (buf hybiFrameReaderFactory) NewFrameReader() (frame frameReader, err error) {
+ hybiFrame := new(hybiFrameReader)
+ frame = hybiFrame
+ var header []byte
+ var b byte
+ // First byte. FIN/RSV1/RSV2/RSV3/OpCode(4bits)
+ b, err = buf.ReadByte()
+ if err != nil {
+ return
+ }
+ header = append(header, b)
+ hybiFrame.header.Fin = ((header[0] >> 7) & 1) != 0
+ for i := 0; i < 3; i++ {
+ j := uint(6 - i)
+ hybiFrame.header.Rsv[i] = ((header[0] >> j) & 1) != 0
+ }
+ hybiFrame.header.OpCode = header[0] & 0x0f
+
+ // Second byte. Mask/Payload len(7bits)
+ b, err = buf.ReadByte()
+ if err != nil {
+ return
+ }
+ header = append(header, b)
+ mask := (b & 0x80) != 0
+ b &= 0x7f
+ lengthFields := 0
+ switch {
+ case b <= 125: // Payload length 7bits.
+ hybiFrame.header.Length = int64(b)
+ case b == 126: // Payload length 7+16bits
+ lengthFields = 2
+ case b == 127: // Payload length 7+64bits
+ lengthFields = 8
+ }
+ for i := 0; i < lengthFields; i++ {
+ b, err = buf.ReadByte()
+ if err != nil {
+ return
+ }
+ if lengthFields == 8 && i == 0 { // MSB must be zero when 7+64 bits
+ b &= 0x7f
+ }
+ header = append(header, b)
+ hybiFrame.header.Length = hybiFrame.header.Length*256 + int64(b)
+ }
+ if mask {
+ // Masking key. 4 bytes.
+ for i := 0; i < 4; i++ {
+ b, err = buf.ReadByte()
+ if err != nil {
+ return
+ }
+ header = append(header, b)
+ hybiFrame.header.MaskingKey = append(hybiFrame.header.MaskingKey, b)
+ }
+ }
+ hybiFrame.reader = io.LimitReader(buf.Reader, hybiFrame.header.Length)
+ hybiFrame.header.data = bytes.NewBuffer(header)
+ hybiFrame.length = len(header) + int(hybiFrame.header.Length)
+ return
+}
+
+// A HybiFrameWriter is a writer for hybi frame.
+type hybiFrameWriter struct {
+ writer *bufio.Writer
+
+ header *hybiFrameHeader
+}
+
+func (frame *hybiFrameWriter) Write(msg []byte) (n int, err error) {
+ var header []byte
+ var b byte
+ if frame.header.Fin {
+ b |= 0x80
+ }
+ for i := 0; i < 3; i++ {
+ if frame.header.Rsv[i] {
+ j := uint(6 - i)
+ b |= 1 << j
+ }
+ }
+ b |= frame.header.OpCode
+ header = append(header, b)
+ if frame.header.MaskingKey != nil {
+ b = 0x80
+ } else {
+ b = 0
+ }
+ lengthFields := 0
+ length := len(msg)
+ switch {
+ case length <= 125:
+ b |= byte(length)
+ case length < 65536:
+ b |= 126
+ lengthFields = 2
+ default:
+ b |= 127
+ lengthFields = 8
+ }
+ header = append(header, b)
+ for i := 0; i < lengthFields; i++ {
+ j := uint((lengthFields - i - 1) * 8)
+ b = byte((length >> j) & 0xff)
+ header = append(header, b)
+ }
+ if frame.header.MaskingKey != nil {
+ if len(frame.header.MaskingKey) != 4 {
+ return 0, ErrBadMaskingKey
+ }
+ header = append(header, frame.header.MaskingKey...)
+ frame.writer.Write(header)
+ data := make([]byte, length)
+ for i := range data {
+ data[i] = msg[i] ^ frame.header.MaskingKey[i%4]
+ }
+ frame.writer.Write(data)
+ err = frame.writer.Flush()
+ return length, err
+ }
+ frame.writer.Write(header)
+ frame.writer.Write(msg)
+ err = frame.writer.Flush()
+ return length, err
+}
+
+func (frame *hybiFrameWriter) Close() error { return nil }
+
+type hybiFrameWriterFactory struct {
+ *bufio.Writer
+ needMaskingKey bool
+}
+
+func (buf hybiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err error) {
+ frameHeader := &hybiFrameHeader{Fin: true, OpCode: payloadType}
+ if buf.needMaskingKey {
+ frameHeader.MaskingKey, err = generateMaskingKey()
+ if err != nil {
+ return nil, err
+ }
+ }
+ return &hybiFrameWriter{writer: buf.Writer, header: frameHeader}, nil
+}
+
+type hybiFrameHandler struct {
+ conn *Conn
+ payloadType byte
+}
+
+func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (frameReader, error) {
+ if handler.conn.IsServerConn() {
+ // The client MUST mask all frames sent to the server.
+ if frame.(*hybiFrameReader).header.MaskingKey == nil {
+ handler.WriteClose(closeStatusProtocolError)
+ return nil, io.EOF
+ }
+ } else {
+ // The server MUST NOT mask all frames.
+ if frame.(*hybiFrameReader).header.MaskingKey != nil {
+ handler.WriteClose(closeStatusProtocolError)
+ return nil, io.EOF
+ }
+ }
+ if header := frame.HeaderReader(); header != nil {
+ io.Copy(ioutil.Discard, header)
+ }
+ switch frame.PayloadType() {
+ case ContinuationFrame:
+ frame.(*hybiFrameReader).header.OpCode = handler.payloadType
+ case TextFrame, BinaryFrame:
+ handler.payloadType = frame.PayloadType()
+ case CloseFrame:
+ return nil, io.EOF
+ case PingFrame, PongFrame:
+ b := make([]byte, maxControlFramePayloadLength)
+ n, err := io.ReadFull(frame, b)
+ if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
+ return nil, err
+ }
+ io.Copy(ioutil.Discard, frame)
+ if frame.PayloadType() == PingFrame {
+ if _, err := handler.WritePong(b[:n]); err != nil {
+ return nil, err
+ }
+ }
+ return nil, nil
+ }
+ return frame, nil
+}
+
+func (handler *hybiFrameHandler) WriteClose(status int) (err error) {
+ handler.conn.wio.Lock()
+ defer handler.conn.wio.Unlock()
+ w, err := handler.conn.frameWriterFactory.NewFrameWriter(CloseFrame)
+ if err != nil {
+ return err
+ }
+ msg := make([]byte, 2)
+ binary.BigEndian.PutUint16(msg, uint16(status))
+ _, err = w.Write(msg)
+ w.Close()
+ return err
+}
+
+func (handler *hybiFrameHandler) WritePong(msg []byte) (n int, err error) {
+ handler.conn.wio.Lock()
+ defer handler.conn.wio.Unlock()
+ w, err := handler.conn.frameWriterFactory.NewFrameWriter(PongFrame)
+ if err != nil {
+ return 0, err
+ }
+ n, err = w.Write(msg)
+ w.Close()
+ return n, err
+}
+
+// newHybiConn creates a new WebSocket connection speaking hybi draft protocol.
+func newHybiConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn {
+ if buf == nil {
+ br := bufio.NewReader(rwc)
+ bw := bufio.NewWriter(rwc)
+ buf = bufio.NewReadWriter(br, bw)
+ }
+ ws := &Conn{config: config, request: request, buf: buf, rwc: rwc,
+ frameReaderFactory: hybiFrameReaderFactory{buf.Reader},
+ frameWriterFactory: hybiFrameWriterFactory{
+ buf.Writer, request == nil},
+ PayloadType: TextFrame,
+ defaultCloseStatus: closeStatusNormal}
+ ws.frameHandler = &hybiFrameHandler{conn: ws}
+ return ws
+}
+
+// generateMaskingKey generates a masking key for a frame.
+func generateMaskingKey() (maskingKey []byte, err error) {
+ maskingKey = make([]byte, 4)
+ if _, err = io.ReadFull(rand.Reader, maskingKey); err != nil {
+ return
+ }
+ return
+}
+
+// generateNonce generates a nonce consisting of a randomly selected 16-byte
+// value that has been base64-encoded.
+func generateNonce() (nonce []byte) {
+ key := make([]byte, 16)
+ if _, err := io.ReadFull(rand.Reader, key); err != nil {
+ panic(err)
+ }
+ nonce = make([]byte, 24)
+ base64.StdEncoding.Encode(nonce, key)
+ return
+}
+
+// removeZone removes IPv6 zone identifer from host.
+// E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080"
+func removeZone(host string) string {
+ if !strings.HasPrefix(host, "[") {
+ return host
+ }
+ i := strings.LastIndex(host, "]")
+ if i < 0 {
+ return host
+ }
+ j := strings.LastIndex(host[:i], "%")
+ if j < 0 {
+ return host
+ }
+ return host[:j] + host[i:]
+}
+
+// getNonceAccept computes the base64-encoded SHA-1 of the concatenation of
+// the nonce ("Sec-WebSocket-Key" value) with the websocket GUID string.
+func getNonceAccept(nonce []byte) (expected []byte, err error) {
+ h := sha1.New()
+ if _, err = h.Write(nonce); err != nil {
+ return
+ }
+ if _, err = h.Write([]byte(websocketGUID)); err != nil {
+ return
+ }
+ expected = make([]byte, 28)
+ base64.StdEncoding.Encode(expected, h.Sum(nil))
+ return
+}
+
+// Client handshake described in draft-ietf-hybi-thewebsocket-protocol-17
+func hybiClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) {
+ bw.WriteString("GET " + config.Location.RequestURI() + " HTTP/1.1\r\n")
+
+ // According to RFC 6874, an HTTP client, proxy, or other
+ // intermediary must remove any IPv6 zone identifier attached
+ // to an outgoing URI.
+ bw.WriteString("Host: " + removeZone(config.Location.Host) + "\r\n")
+ bw.WriteString("Upgrade: websocket\r\n")
+ bw.WriteString("Connection: Upgrade\r\n")
+ nonce := generateNonce()
+ if config.handshakeData != nil {
+ nonce = []byte(config.handshakeData["key"])
+ }
+ bw.WriteString("Sec-WebSocket-Key: " + string(nonce) + "\r\n")
+ bw.WriteString("Origin: " + strings.ToLower(config.Origin.String()) + "\r\n")
+
+ if config.Version != ProtocolVersionHybi13 {
+ return ErrBadProtocolVersion
+ }
+
+ bw.WriteString("Sec-WebSocket-Version: " + fmt.Sprintf("%d", config.Version) + "\r\n")
+ if len(config.Protocol) > 0 {
+ bw.WriteString("Sec-WebSocket-Protocol: " + strings.Join(config.Protocol, ", ") + "\r\n")
+ }
+ // TODO(ukai): send Sec-WebSocket-Extensions.
+ err = config.Header.WriteSubset(bw, handshakeHeader)
+ if err != nil {
+ return err
+ }
+
+ bw.WriteString("\r\n")
+ if err = bw.Flush(); err != nil {
+ return err
+ }
+
+ resp, err := http.ReadResponse(br, &http.Request{Method: "GET"})
+ if err != nil {
+ return err
+ }
+ if resp.StatusCode != 101 {
+ return ErrBadStatus
+ }
+ if strings.ToLower(resp.Header.Get("Upgrade")) != "websocket" ||
+ strings.ToLower(resp.Header.Get("Connection")) != "upgrade" {
+ return ErrBadUpgrade
+ }
+ expectedAccept, err := getNonceAccept(nonce)
+ if err != nil {
+ return err
+ }
+ if resp.Header.Get("Sec-WebSocket-Accept") != string(expectedAccept) {
+ return ErrChallengeResponse
+ }
+ if resp.Header.Get("Sec-WebSocket-Extensions") != "" {
+ return ErrUnsupportedExtensions
+ }
+ offeredProtocol := resp.Header.Get("Sec-WebSocket-Protocol")
+ if offeredProtocol != "" {
+ protocolMatched := false
+ for i := 0; i < len(config.Protocol); i++ {
+ if config.Protocol[i] == offeredProtocol {
+ protocolMatched = true
+ break
+ }
+ }
+ if !protocolMatched {
+ return ErrBadWebSocketProtocol
+ }
+ config.Protocol = []string{offeredProtocol}
+ }
+
+ return nil
+}
+
+// newHybiClientConn creates a client WebSocket connection after handshake.
+func newHybiClientConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser) *Conn {
+ return newHybiConn(config, buf, rwc, nil)
+}
+
+// A HybiServerHandshaker performs a server handshake using hybi draft protocol.
+type hybiServerHandshaker struct {
+ *Config
+ accept []byte
+}
+
+func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) {
+ c.Version = ProtocolVersionHybi13
+ if req.Method != "GET" {
+ return http.StatusMethodNotAllowed, ErrBadRequestMethod
+ }
+ // HTTP version can be safely ignored.
+
+ if strings.ToLower(req.Header.Get("Upgrade")) != "websocket" ||
+ !strings.Contains(strings.ToLower(req.Header.Get("Connection")), "upgrade") {
+ return http.StatusBadRequest, ErrNotWebSocket
+ }
+
+ key := req.Header.Get("Sec-Websocket-Key")
+ if key == "" {
+ return http.StatusBadRequest, ErrChallengeResponse
+ }
+ version := req.Header.Get("Sec-Websocket-Version")
+ switch version {
+ case "13":
+ c.Version = ProtocolVersionHybi13
+ default:
+ return http.StatusBadRequest, ErrBadWebSocketVersion
+ }
+ var scheme string
+ if req.TLS != nil {
+ scheme = "wss"
+ } else {
+ scheme = "ws"
+ }
+ c.Location, err = url.ParseRequestURI(scheme + "://" + req.Host + req.URL.RequestURI())
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+ protocol := strings.TrimSpace(req.Header.Get("Sec-Websocket-Protocol"))
+ if protocol != "" {
+ protocols := strings.Split(protocol, ",")
+ for i := 0; i < len(protocols); i++ {
+ c.Protocol = append(c.Protocol, strings.TrimSpace(protocols[i]))
+ }
+ }
+ c.accept, err = getNonceAccept([]byte(key))
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ return http.StatusSwitchingProtocols, nil
+}
+
+// Origin parses the Origin header in req.
+// If the Origin header is not set, it returns nil and nil.
+func Origin(config *Config, req *http.Request) (*url.URL, error) {
+ var origin string
+ switch config.Version {
+ case ProtocolVersionHybi13:
+ origin = req.Header.Get("Origin")
+ }
+ if origin == "" {
+ return nil, nil
+ }
+ return url.ParseRequestURI(origin)
+}
+
+func (c *hybiServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) {
+ if len(c.Protocol) > 0 {
+ if len(c.Protocol) != 1 {
+ // You need choose a Protocol in Handshake func in Server.
+ return ErrBadWebSocketProtocol
+ }
+ }
+ buf.WriteString("HTTP/1.1 101 Switching Protocols\r\n")
+ buf.WriteString("Upgrade: websocket\r\n")
+ buf.WriteString("Connection: Upgrade\r\n")
+ buf.WriteString("Sec-WebSocket-Accept: " + string(c.accept) + "\r\n")
+ if len(c.Protocol) > 0 {
+ buf.WriteString("Sec-WebSocket-Protocol: " + c.Protocol[0] + "\r\n")
+ }
+ // TODO(ukai): send Sec-WebSocket-Extensions.
+ if c.Header != nil {
+ err := c.Header.WriteSubset(buf, handshakeHeader)
+ if err != nil {
+ return err
+ }
+ }
+ buf.WriteString("\r\n")
+ return buf.Flush()
+}
+
+func (c *hybiServerHandshaker) NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn {
+ return newHybiServerConn(c.Config, buf, rwc, request)
+}
+
+// newHybiServerConn returns a new WebSocket connection speaking hybi draft protocol.
+func newHybiServerConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn {
+ return newHybiConn(config, buf, rwc, request)
+}
diff --git a/vendor/golang.org/x/net/websocket/server.go b/vendor/golang.org/x/net/websocket/server.go
new file mode 100644
index 0000000..0895dea
--- /dev/null
+++ b/vendor/golang.org/x/net/websocket/server.go
@@ -0,0 +1,113 @@
+// Copyright 2009 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 websocket
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "net/http"
+)
+
+func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request, config *Config, handshake func(*Config, *http.Request) error) (conn *Conn, err error) {
+ var hs serverHandshaker = &hybiServerHandshaker{Config: config}
+ code, err := hs.ReadHandshake(buf.Reader, req)
+ if err == ErrBadWebSocketVersion {
+ fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
+ fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion)
+ buf.WriteString("\r\n")
+ buf.WriteString(err.Error())
+ buf.Flush()
+ return
+ }
+ if err != nil {
+ fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
+ buf.WriteString("\r\n")
+ buf.WriteString(err.Error())
+ buf.Flush()
+ return
+ }
+ if handshake != nil {
+ err = handshake(config, req)
+ if err != nil {
+ code = http.StatusForbidden
+ fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
+ buf.WriteString("\r\n")
+ buf.Flush()
+ return
+ }
+ }
+ err = hs.AcceptHandshake(buf.Writer)
+ if err != nil {
+ code = http.StatusBadRequest
+ fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
+ buf.WriteString("\r\n")
+ buf.Flush()
+ return
+ }
+ conn = hs.NewServerConn(buf, rwc, req)
+ return
+}
+
+// Server represents a server of a WebSocket.
+type Server struct {
+ // Config is a WebSocket configuration for new WebSocket connection.
+ Config
+
+ // Handshake is an optional function in WebSocket handshake.
+ // For example, you can check, or don't check Origin header.
+ // Another example, you can select config.Protocol.
+ Handshake func(*Config, *http.Request) error
+
+ // Handler handles a WebSocket connection.
+ Handler
+}
+
+// ServeHTTP implements the http.Handler interface for a WebSocket
+func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
+ s.serveWebSocket(w, req)
+}
+
+func (s Server) serveWebSocket(w http.ResponseWriter, req *http.Request) {
+ rwc, buf, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ panic("Hijack failed: " + err.Error())
+ }
+ // The server should abort the WebSocket connection if it finds
+ // the client did not send a handshake that matches with protocol
+ // specification.
+ defer rwc.Close()
+ conn, err := newServerConn(rwc, buf, req, &s.Config, s.Handshake)
+ if err != nil {
+ return
+ }
+ if conn == nil {
+ panic("unexpected nil conn")
+ }
+ s.Handler(conn)
+}
+
+// Handler is a simple interface to a WebSocket browser client.
+// It checks if Origin header is valid URL by default.
+// You might want to verify websocket.Conn.Config().Origin in the func.
+// If you use Server instead of Handler, you could call websocket.Origin and
+// check the origin in your Handshake func. So, if you want to accept
+// non-browser clients, which do not send an Origin header, set a
+// Server.Handshake that does not check the origin.
+type Handler func(*Conn)
+
+func checkOrigin(config *Config, req *http.Request) (err error) {
+ config.Origin, err = Origin(config, req)
+ if err == nil && config.Origin == nil {
+ return fmt.Errorf("null origin")
+ }
+ return err
+}
+
+// ServeHTTP implements the http.Handler interface for a WebSocket
+func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
+ s := Server{Handler: h, Handshake: checkOrigin}
+ s.serveWebSocket(w, req)
+}
diff --git a/vendor/golang.org/x/net/websocket/websocket.go b/vendor/golang.org/x/net/websocket/websocket.go
new file mode 100644
index 0000000..e242c89
--- /dev/null
+++ b/vendor/golang.org/x/net/websocket/websocket.go
@@ -0,0 +1,448 @@
+// Copyright 2009 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 websocket implements a client and server for the WebSocket protocol
+// as specified in RFC 6455.
+//
+// This package currently lacks some features found in an alternative
+// and more actively maintained WebSocket package:
+//
+// https://godoc.org/github.com/gorilla/websocket
+//
+package websocket // import "golang.org/x/net/websocket"
+
+import (
+ "bufio"
+ "crypto/tls"
+ "encoding/json"
+ "errors"
+ "io"
+ "io/ioutil"
+ "net"
+ "net/http"
+ "net/url"
+ "sync"
+ "time"
+)
+
+const (
+ ProtocolVersionHybi13 = 13
+ ProtocolVersionHybi = ProtocolVersionHybi13
+ SupportedProtocolVersion = "13"
+
+ ContinuationFrame = 0
+ TextFrame = 1
+ BinaryFrame = 2
+ CloseFrame = 8
+ PingFrame = 9
+ PongFrame = 10
+ UnknownFrame = 255
+
+ DefaultMaxPayloadBytes = 32 << 20 // 32MB
+)
+
+// ProtocolError represents WebSocket protocol errors.
+type ProtocolError struct {
+ ErrorString string
+}
+
+func (err *ProtocolError) Error() string { return err.ErrorString }
+
+var (
+ ErrBadProtocolVersion = &ProtocolError{"bad protocol version"}
+ ErrBadScheme = &ProtocolError{"bad scheme"}
+ ErrBadStatus = &ProtocolError{"bad status"}
+ ErrBadUpgrade = &ProtocolError{"missing or bad upgrade"}
+ ErrBadWebSocketOrigin = &ProtocolError{"missing or bad WebSocket-Origin"}
+ ErrBadWebSocketLocation = &ProtocolError{"missing or bad WebSocket-Location"}
+ ErrBadWebSocketProtocol = &ProtocolError{"missing or bad WebSocket-Protocol"}
+ ErrBadWebSocketVersion = &ProtocolError{"missing or bad WebSocket Version"}
+ ErrChallengeResponse = &ProtocolError{"mismatch challenge/response"}
+ ErrBadFrame = &ProtocolError{"bad frame"}
+ ErrBadFrameBoundary = &ProtocolError{"not on frame boundary"}
+ ErrNotWebSocket = &ProtocolError{"not websocket protocol"}
+ ErrBadRequestMethod = &ProtocolError{"bad method"}
+ ErrNotSupported = &ProtocolError{"not supported"}
+)
+
+// ErrFrameTooLarge is returned by Codec's Receive method if payload size
+// exceeds limit set by Conn.MaxPayloadBytes
+var ErrFrameTooLarge = errors.New("websocket: frame payload size exceeds limit")
+
+// Addr is an implementation of net.Addr for WebSocket.
+type Addr struct {
+ *url.URL
+}
+
+// Network returns the network type for a WebSocket, "websocket".
+func (addr *Addr) Network() string { return "websocket" }
+
+// Config is a WebSocket configuration
+type Config struct {
+ // A WebSocket server address.
+ Location *url.URL
+
+ // A Websocket client origin.
+ Origin *url.URL
+
+ // WebSocket subprotocols.
+ Protocol []string
+
+ // WebSocket protocol version.
+ Version int
+
+ // TLS config for secure WebSocket (wss).
+ TlsConfig *tls.Config
+
+ // Additional header fields to be sent in WebSocket opening handshake.
+ Header http.Header
+
+ // Dialer used when opening websocket connections.
+ Dialer *net.Dialer
+
+ handshakeData map[string]string
+}
+
+// serverHandshaker is an interface to handle WebSocket server side handshake.
+type serverHandshaker interface {
+ // ReadHandshake reads handshake request message from client.
+ // Returns http response code and error if any.
+ ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error)
+
+ // AcceptHandshake accepts the client handshake request and sends
+ // handshake response back to client.
+ AcceptHandshake(buf *bufio.Writer) (err error)
+
+ // NewServerConn creates a new WebSocket connection.
+ NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) (conn *Conn)
+}
+
+// frameReader is an interface to read a WebSocket frame.
+type frameReader interface {
+ // Reader is to read payload of the frame.
+ io.Reader
+
+ // PayloadType returns payload type.
+ PayloadType() byte
+
+ // HeaderReader returns a reader to read header of the frame.
+ HeaderReader() io.Reader
+
+ // TrailerReader returns a reader to read trailer of the frame.
+ // If it returns nil, there is no trailer in the frame.
+ TrailerReader() io.Reader
+
+ // Len returns total length of the frame, including header and trailer.
+ Len() int
+}
+
+// frameReaderFactory is an interface to creates new frame reader.
+type frameReaderFactory interface {
+ NewFrameReader() (r frameReader, err error)
+}
+
+// frameWriter is an interface to write a WebSocket frame.
+type frameWriter interface {
+ // Writer is to write payload of the frame.
+ io.WriteCloser
+}
+
+// frameWriterFactory is an interface to create new frame writer.
+type frameWriterFactory interface {
+ NewFrameWriter(payloadType byte) (w frameWriter, err error)
+}
+
+type frameHandler interface {
+ HandleFrame(frame frameReader) (r frameReader, err error)
+ WriteClose(status int) (err error)
+}
+
+// Conn represents a WebSocket connection.
+//
+// Multiple goroutines may invoke methods on a Conn simultaneously.
+type Conn struct {
+ config *Config
+ request *http.Request
+
+ buf *bufio.ReadWriter
+ rwc io.ReadWriteCloser
+
+ rio sync.Mutex
+ frameReaderFactory
+ frameReader
+
+ wio sync.Mutex
+ frameWriterFactory
+
+ frameHandler
+ PayloadType byte
+ defaultCloseStatus int
+
+ // MaxPayloadBytes limits the size of frame payload received over Conn
+ // by Codec's Receive method. If zero, DefaultMaxPayloadBytes is used.
+ MaxPayloadBytes int
+}
+
+// Read implements the io.Reader interface:
+// it reads data of a frame from the WebSocket connection.
+// if msg is not large enough for the frame data, it fills the msg and next Read
+// will read the rest of the frame data.
+// it reads Text frame or Binary frame.
+func (ws *Conn) Read(msg []byte) (n int, err error) {
+ ws.rio.Lock()
+ defer ws.rio.Unlock()
+again:
+ if ws.frameReader == nil {
+ frame, err := ws.frameReaderFactory.NewFrameReader()
+ if err != nil {
+ return 0, err
+ }
+ ws.frameReader, err = ws.frameHandler.HandleFrame(frame)
+ if err != nil {
+ return 0, err
+ }
+ if ws.frameReader == nil {
+ goto again
+ }
+ }
+ n, err = ws.frameReader.Read(msg)
+ if err == io.EOF {
+ if trailer := ws.frameReader.TrailerReader(); trailer != nil {
+ io.Copy(ioutil.Discard, trailer)
+ }
+ ws.frameReader = nil
+ goto again
+ }
+ return n, err
+}
+
+// Write implements the io.Writer interface:
+// it writes data as a frame to the WebSocket connection.
+func (ws *Conn) Write(msg []byte) (n int, err error) {
+ ws.wio.Lock()
+ defer ws.wio.Unlock()
+ w, err := ws.frameWriterFactory.NewFrameWriter(ws.PayloadType)
+ if err != nil {
+ return 0, err
+ }
+ n, err = w.Write(msg)
+ w.Close()
+ return n, err
+}
+
+// Close implements the io.Closer interface.
+func (ws *Conn) Close() error {
+ err := ws.frameHandler.WriteClose(ws.defaultCloseStatus)
+ err1 := ws.rwc.Close()
+ if err != nil {
+ return err
+ }
+ return err1
+}
+
+func (ws *Conn) IsClientConn() bool { return ws.request == nil }
+func (ws *Conn) IsServerConn() bool { return ws.request != nil }
+
+// LocalAddr returns the WebSocket Origin for the connection for client, or
+// the WebSocket location for server.
+func (ws *Conn) LocalAddr() net.Addr {
+ if ws.IsClientConn() {
+ return &Addr{ws.config.Origin}
+ }
+ return &Addr{ws.config.Location}
+}
+
+// RemoteAddr returns the WebSocket location for the connection for client, or
+// the Websocket Origin for server.
+func (ws *Conn) RemoteAddr() net.Addr {
+ if ws.IsClientConn() {
+ return &Addr{ws.config.Location}
+ }
+ return &Addr{ws.config.Origin}
+}
+
+var errSetDeadline = errors.New("websocket: cannot set deadline: not using a net.Conn")
+
+// SetDeadline sets the connection's network read & write deadlines.
+func (ws *Conn) SetDeadline(t time.Time) error {
+ if conn, ok := ws.rwc.(net.Conn); ok {
+ return conn.SetDeadline(t)
+ }
+ return errSetDeadline
+}
+
+// SetReadDeadline sets the connection's network read deadline.
+func (ws *Conn) SetReadDeadline(t time.Time) error {
+ if conn, ok := ws.rwc.(net.Conn); ok {
+ return conn.SetReadDeadline(t)
+ }
+ return errSetDeadline
+}
+
+// SetWriteDeadline sets the connection's network write deadline.
+func (ws *Conn) SetWriteDeadline(t time.Time) error {
+ if conn, ok := ws.rwc.(net.Conn); ok {
+ return conn.SetWriteDeadline(t)
+ }
+ return errSetDeadline
+}
+
+// Config returns the WebSocket config.
+func (ws *Conn) Config() *Config { return ws.config }
+
+// Request returns the http request upgraded to the WebSocket.
+// It is nil for client side.
+func (ws *Conn) Request() *http.Request { return ws.request }
+
+// Codec represents a symmetric pair of functions that implement a codec.
+type Codec struct {
+ Marshal func(v interface{}) (data []byte, payloadType byte, err error)
+ Unmarshal func(data []byte, payloadType byte, v interface{}) (err error)
+}
+
+// Send sends v marshaled by cd.Marshal as single frame to ws.
+func (cd Codec) Send(ws *Conn, v interface{}) (err error) {
+ data, payloadType, err := cd.Marshal(v)
+ if err != nil {
+ return err
+ }
+ ws.wio.Lock()
+ defer ws.wio.Unlock()
+ w, err := ws.frameWriterFactory.NewFrameWriter(payloadType)
+ if err != nil {
+ return err
+ }
+ _, err = w.Write(data)
+ w.Close()
+ return err
+}
+
+// Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores
+// in v. The whole frame payload is read to an in-memory buffer; max size of
+// payload is defined by ws.MaxPayloadBytes. If frame payload size exceeds
+// limit, ErrFrameTooLarge is returned; in this case frame is not read off wire
+// completely. The next call to Receive would read and discard leftover data of
+// previous oversized frame before processing next frame.
+func (cd Codec) Receive(ws *Conn, v interface{}) (err error) {
+ ws.rio.Lock()
+ defer ws.rio.Unlock()
+ if ws.frameReader != nil {
+ _, err = io.Copy(ioutil.Discard, ws.frameReader)
+ if err != nil {
+ return err
+ }
+ ws.frameReader = nil
+ }
+again:
+ frame, err := ws.frameReaderFactory.NewFrameReader()
+ if err != nil {
+ return err
+ }
+ frame, err = ws.frameHandler.HandleFrame(frame)
+ if err != nil {
+ return err
+ }
+ if frame == nil {
+ goto again
+ }
+ maxPayloadBytes := ws.MaxPayloadBytes
+ if maxPayloadBytes == 0 {
+ maxPayloadBytes = DefaultMaxPayloadBytes
+ }
+ if hf, ok := frame.(*hybiFrameReader); ok && hf.header.Length > int64(maxPayloadBytes) {
+ // payload size exceeds limit, no need to call Unmarshal
+ //
+ // set frameReader to current oversized frame so that
+ // the next call to this function can drain leftover
+ // data before processing the next frame
+ ws.frameReader = frame
+ return ErrFrameTooLarge
+ }
+ payloadType := frame.PayloadType()
+ data, err := ioutil.ReadAll(frame)
+ if err != nil {
+ return err
+ }
+ return cd.Unmarshal(data, payloadType, v)
+}
+
+func marshal(v interface{}) (msg []byte, payloadType byte, err error) {
+ switch data := v.(type) {
+ case string:
+ return []byte(data), TextFrame, nil
+ case []byte:
+ return data, BinaryFrame, nil
+ }
+ return nil, UnknownFrame, ErrNotSupported
+}
+
+func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
+ switch data := v.(type) {
+ case *string:
+ *data = string(msg)
+ return nil
+ case *[]byte:
+ *data = msg
+ return nil
+ }
+ return ErrNotSupported
+}
+
+/*
+Message is a codec to send/receive text/binary data in a frame on WebSocket connection.
+To send/receive text frame, use string type.
+To send/receive binary frame, use []byte type.
+
+Trivial usage:
+
+ import "websocket"
+
+ // receive text frame
+ var message string
+ websocket.Message.Receive(ws, &message)
+
+ // send text frame
+ message = "hello"
+ websocket.Message.Send(ws, message)
+
+ // receive binary frame
+ var data []byte
+ websocket.Message.Receive(ws, &data)
+
+ // send binary frame
+ data = []byte{0, 1, 2}
+ websocket.Message.Send(ws, data)
+
+*/
+var Message = Codec{marshal, unmarshal}
+
+func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) {
+ msg, err = json.Marshal(v)
+ return msg, TextFrame, err
+}
+
+func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
+ return json.Unmarshal(msg, v)
+}
+
+/*
+JSON is a codec to send/receive JSON data in a frame from a WebSocket connection.
+
+Trivial usage:
+
+ import "websocket"
+
+ type T struct {
+ Msg string
+ Count int
+ }
+
+ // receive JSON type T
+ var data T
+ websocket.JSON.Receive(ws, &data)
+
+ // send JSON type T
+ websocket.JSON.Send(ws, data)
+*/
+var JSON = Codec{jsonMarshal, jsonUnmarshal}
diff --git a/vendor/golang.org/x/oauth2/LICENSE b/vendor/golang.org/x/oauth2/LICENSE
new file mode 100644
index 0000000..d02f24f
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2009 The oauth2 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/oauth2/README.md b/vendor/golang.org/x/oauth2/README.md
new file mode 100644
index 0000000..1643c08
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/README.md
@@ -0,0 +1,65 @@
+# OAuth2 for Go
+
+[![Build Status](https://travis-ci.org/golang/oauth2.svg?branch=master)](https://travis-ci.org/golang/oauth2)
+[![GoDoc](https://godoc.org/golang.org/x/oauth2?status.svg)](https://godoc.org/golang.org/x/oauth2)
+
+oauth2 package contains a client implementation for OAuth 2.0 spec.
+
+## Installation
+
+~~~~
+go get golang.org/x/oauth2
+~~~~
+
+See godoc for further documentation and examples.
+
+* [godoc.org/golang.org/x/oauth2](http://godoc.org/golang.org/x/oauth2)
+* [godoc.org/golang.org/x/oauth2/google](http://godoc.org/golang.org/x/oauth2/google)
+
+
+## App Engine
+
+In change 96e89be (March 2015) we removed the `oauth2.Context2` type in favor
+of the [`context.Context`](https://golang.org/x/net/context#Context) type from
+the `golang.org/x/net/context` package
+
+This means its no longer possible to use the "Classic App Engine"
+`appengine.Context` type with the `oauth2` package. (You're using
+Classic App Engine if you import the package `"appengine"`.)
+
+To work around this, you may use the new `"google.golang.org/appengine"`
+package. This package has almost the same API as the `"appengine"` package,
+but it can be fetched with `go get` and used on "Managed VMs" and well as
+Classic App Engine.
+
+See the [new `appengine` package's readme](https://github.com/golang/appengine#updating-a-go-app-engine-app)
+for information on updating your app.
+
+If you don't want to update your entire app to use the new App Engine packages,
+you may use both sets of packages in parallel, using only the new packages
+with the `oauth2` package.
+
+ import (
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/google"
+ newappengine "google.golang.org/appengine"
+ newurlfetch "google.golang.org/appengine/urlfetch"
+
+ "appengine"
+ )
+
+ func handler(w http.ResponseWriter, r *http.Request) {
+ var c appengine.Context = appengine.NewContext(r)
+ c.Infof("Logging a message with the old package")
+
+ var ctx context.Context = newappengine.NewContext(r)
+ client := &http.Client{
+ Transport: &oauth2.Transport{
+ Source: google.AppEngineTokenSource(ctx, "scope"),
+ Base: &newurlfetch.Transport{Context: ctx},
+ },
+ }
+ client.Get("...")
+ }
+
diff --git a/vendor/golang.org/x/oauth2/client_appengine.go b/vendor/golang.org/x/oauth2/client_appengine.go
new file mode 100644
index 0000000..8962c49
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/client_appengine.go
@@ -0,0 +1,25 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build appengine
+
+// App Engine hooks.
+
+package oauth2
+
+import (
+ "net/http"
+
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2/internal"
+ "google.golang.org/appengine/urlfetch"
+)
+
+func init() {
+ internal.RegisterContextClientFunc(contextClientAppEngine)
+}
+
+func contextClientAppEngine(ctx context.Context) (*http.Client, error) {
+ return urlfetch.Client(ctx), nil
+}
diff --git a/vendor/golang.org/x/oauth2/google/appengine.go b/vendor/golang.org/x/oauth2/google/appengine.go
new file mode 100644
index 0000000..4243f4c
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/google/appengine.go
@@ -0,0 +1,89 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package google
+
+import (
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2"
+)
+
+// Set at init time by appenginevm_hook.go. If true, we are on App Engine Managed VMs.
+var appengineVM bool
+
+// Set at init time by appengine_hook.go. If nil, we're not on App Engine.
+var appengineTokenFunc func(c context.Context, scopes ...string) (token string, expiry time.Time, err error)
+
+// Set at init time by appengine_hook.go. If nil, we're not on App Engine.
+var appengineAppIDFunc func(c context.Context) string
+
+// AppEngineTokenSource returns a token source that fetches tokens
+// issued to the current App Engine application's service account.
+// If you are implementing a 3-legged OAuth 2.0 flow on App Engine
+// that involves user accounts, see oauth2.Config instead.
+//
+// The provided context must have come from appengine.NewContext.
+func AppEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource {
+ if appengineTokenFunc == nil {
+ panic("google: AppEngineTokenSource can only be used on App Engine.")
+ }
+ scopes := append([]string{}, scope...)
+ sort.Strings(scopes)
+ return &appEngineTokenSource{
+ ctx: ctx,
+ scopes: scopes,
+ key: strings.Join(scopes, " "),
+ }
+}
+
+// aeTokens helps the fetched tokens to be reused until their expiration.
+var (
+ aeTokensMu sync.Mutex
+ aeTokens = make(map[string]*tokenLock) // key is space-separated scopes
+)
+
+type tokenLock struct {
+ mu sync.Mutex // guards t; held while fetching or updating t
+ t *oauth2.Token
+}
+
+type appEngineTokenSource struct {
+ ctx context.Context
+ scopes []string
+ key string // to aeTokens map; space-separated scopes
+}
+
+func (ts *appEngineTokenSource) Token() (*oauth2.Token, error) {
+ if appengineTokenFunc == nil {
+ panic("google: AppEngineTokenSource can only be used on App Engine.")
+ }
+
+ aeTokensMu.Lock()
+ tok, ok := aeTokens[ts.key]
+ if !ok {
+ tok = &tokenLock{}
+ aeTokens[ts.key] = tok
+ }
+ aeTokensMu.Unlock()
+
+ tok.mu.Lock()
+ defer tok.mu.Unlock()
+ if tok.t.Valid() {
+ return tok.t, nil
+ }
+ access, exp, err := appengineTokenFunc(ts.ctx, ts.scopes...)
+ if err != nil {
+ return nil, err
+ }
+ tok.t = &oauth2.Token{
+ AccessToken: access,
+ Expiry: exp,
+ }
+ return tok.t, nil
+}
diff --git a/vendor/golang.org/x/oauth2/google/appengine_hook.go b/vendor/golang.org/x/oauth2/google/appengine_hook.go
new file mode 100644
index 0000000..6f66411
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/google/appengine_hook.go
@@ -0,0 +1,14 @@
+// Copyright 2015 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 appengine
+
+package google
+
+import "google.golang.org/appengine"
+
+func init() {
+ appengineTokenFunc = appengine.AccessToken
+ appengineAppIDFunc = appengine.AppID
+}
diff --git a/vendor/golang.org/x/oauth2/google/appenginevm_hook.go b/vendor/golang.org/x/oauth2/google/appenginevm_hook.go
new file mode 100644
index 0000000..1074780
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/google/appenginevm_hook.go
@@ -0,0 +1,15 @@
+// Copyright 2015 The oauth2 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 appenginevm
+
+package google
+
+import "google.golang.org/appengine"
+
+func init() {
+ appengineVM = true
+ appengineTokenFunc = appengine.AccessToken
+ appengineAppIDFunc = appengine.AppID
+}
diff --git a/vendor/golang.org/x/oauth2/google/default.go b/vendor/golang.org/x/oauth2/google/default.go
new file mode 100644
index 0000000..b45e796
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/google/default.go
@@ -0,0 +1,130 @@
+// Copyright 2015 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 google
+
+import (
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "os"
+ "path/filepath"
+ "runtime"
+
+ "cloud.google.com/go/compute/metadata"
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2"
+)
+
+// DefaultCredentials holds "Application Default Credentials".
+// For more details, see:
+// https://developers.google.com/accounts/docs/application-default-credentials
+type DefaultCredentials struct {
+ ProjectID string // may be empty
+ TokenSource oauth2.TokenSource
+}
+
+// DefaultClient returns an HTTP Client that uses the
+// DefaultTokenSource to obtain authentication credentials.
+func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) {
+ ts, err := DefaultTokenSource(ctx, scope...)
+ if err != nil {
+ return nil, err
+ }
+ return oauth2.NewClient(ctx, ts), nil
+}
+
+// DefaultTokenSource returns the token source for
+// "Application Default Credentials".
+// It is a shortcut for FindDefaultCredentials(ctx, scope).TokenSource.
+func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error) {
+ creds, err := FindDefaultCredentials(ctx, scope...)
+ if err != nil {
+ return nil, err
+ }
+ return creds.TokenSource, nil
+}
+
+// FindDefaultCredentials searches for "Application Default Credentials".
+//
+// It looks for credentials in the following places,
+// preferring the first location found:
+//
+// 1. A JSON file whose path is specified by the
+// GOOGLE_APPLICATION_CREDENTIALS environment variable.
+// 2. A JSON file in a location known to the gcloud command-line tool.
+// On Windows, this is %APPDATA%/gcloud/application_default_credentials.json.
+// On other systems, $HOME/.config/gcloud/application_default_credentials.json.
+// 3. On Google App Engine it uses the appengine.AccessToken function.
+// 4. On Google Compute Engine and Google App Engine Managed VMs, it fetches
+// credentials from the metadata server.
+// (In this final case any provided scopes are ignored.)
+func FindDefaultCredentials(ctx context.Context, scope ...string) (*DefaultCredentials, error) {
+ // First, try the environment variable.
+ const envVar = "GOOGLE_APPLICATION_CREDENTIALS"
+ if filename := os.Getenv(envVar); filename != "" {
+ creds, err := readCredentialsFile(ctx, filename, scope)
+ if err != nil {
+ return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err)
+ }
+ return creds, nil
+ }
+
+ // Second, try a well-known file.
+ filename := wellKnownFile()
+ if creds, err := readCredentialsFile(ctx, filename, scope); err == nil {
+ return creds, nil
+ } else if !os.IsNotExist(err) {
+ return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err)
+ }
+
+ // Third, if we're on Google App Engine use those credentials.
+ if appengineTokenFunc != nil && !appengineVM {
+ return &DefaultCredentials{
+ ProjectID: appengineAppIDFunc(ctx),
+ TokenSource: AppEngineTokenSource(ctx, scope...),
+ }, nil
+ }
+
+ // Fourth, if we're on Google Compute Engine use the metadata server.
+ if metadata.OnGCE() {
+ id, _ := metadata.ProjectID()
+ return &DefaultCredentials{
+ ProjectID: id,
+ TokenSource: ComputeTokenSource(""),
+ }, nil
+ }
+
+ // None are found; return helpful error.
+ const url = "https://developers.google.com/accounts/docs/application-default-credentials"
+ return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url)
+}
+
+func wellKnownFile() string {
+ const f = "application_default_credentials.json"
+ if runtime.GOOS == "windows" {
+ return filepath.Join(os.Getenv("APPDATA"), "gcloud", f)
+ }
+ return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f)
+}
+
+func readCredentialsFile(ctx context.Context, filename string, scopes []string) (*DefaultCredentials, error) {
+ b, err := ioutil.ReadFile(filename)
+ if err != nil {
+ return nil, err
+ }
+ var f credentialsFile
+ if err := json.Unmarshal(b, &f); err != nil {
+ return nil, err
+ }
+ ts, err := f.tokenSource(ctx, append([]string(nil), scopes...))
+ if err != nil {
+ return nil, err
+ }
+ return &DefaultCredentials{
+ ProjectID: f.ProjectID,
+ TokenSource: ts,
+ }, nil
+}
diff --git a/vendor/golang.org/x/oauth2/google/google.go b/vendor/golang.org/x/oauth2/google/google.go
new file mode 100644
index 0000000..66a8b0e
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/google/google.go
@@ -0,0 +1,202 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package google provides support for making OAuth2 authorized and
+// authenticated HTTP requests to Google APIs.
+// It supports the Web server flow, client-side credentials, service accounts,
+// Google Compute Engine service accounts, and Google App Engine service
+// accounts.
+//
+// For more information, please read
+// https://developers.google.com/accounts/docs/OAuth2
+// and
+// https://developers.google.com/accounts/docs/application-default-credentials.
+package google // import "golang.org/x/oauth2/google"
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "cloud.google.com/go/compute/metadata"
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/jwt"
+)
+
+// Endpoint is Google's OAuth 2.0 endpoint.
+var Endpoint = oauth2.Endpoint{
+ AuthURL: "https://accounts.google.com/o/oauth2/auth",
+ TokenURL: "https://accounts.google.com/o/oauth2/token",
+}
+
+// JWTTokenURL is Google's OAuth 2.0 token URL to use with the JWT flow.
+const JWTTokenURL = "https://accounts.google.com/o/oauth2/token"
+
+// ConfigFromJSON uses a Google Developers Console client_credentials.json
+// file to construct a config.
+// client_credentials.json can be downloaded from
+// https://console.developers.google.com, under "Credentials". Download the Web
+// application credentials in the JSON format and provide the contents of the
+// file as jsonKey.
+func ConfigFromJSON(jsonKey []byte, scope ...string) (*oauth2.Config, error) {
+ type cred struct {
+ ClientID string `json:"client_id"`
+ ClientSecret string `json:"client_secret"`
+ RedirectURIs []string `json:"redirect_uris"`
+ AuthURI string `json:"auth_uri"`
+ TokenURI string `json:"token_uri"`
+ }
+ var j struct {
+ Web *cred `json:"web"`
+ Installed *cred `json:"installed"`
+ }
+ if err := json.Unmarshal(jsonKey, &j); err != nil {
+ return nil, err
+ }
+ var c *cred
+ switch {
+ case j.Web != nil:
+ c = j.Web
+ case j.Installed != nil:
+ c = j.Installed
+ default:
+ return nil, fmt.Errorf("oauth2/google: no credentials found")
+ }
+ if len(c.RedirectURIs) < 1 {
+ return nil, errors.New("oauth2/google: missing redirect URL in the client_credentials.json")
+ }
+ return &oauth2.Config{
+ ClientID: c.ClientID,
+ ClientSecret: c.ClientSecret,
+ RedirectURL: c.RedirectURIs[0],
+ Scopes: scope,
+ Endpoint: oauth2.Endpoint{
+ AuthURL: c.AuthURI,
+ TokenURL: c.TokenURI,
+ },
+ }, nil
+}
+
+// JWTConfigFromJSON uses a Google Developers service account JSON key file to read
+// the credentials that authorize and authenticate the requests.
+// Create a service account on "Credentials" for your project at
+// https://console.developers.google.com to download a JSON key file.
+func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error) {
+ var f credentialsFile
+ if err := json.Unmarshal(jsonKey, &f); err != nil {
+ return nil, err
+ }
+ if f.Type != serviceAccountKey {
+ return nil, fmt.Errorf("google: read JWT from JSON credentials: 'type' field is %q (expected %q)", f.Type, serviceAccountKey)
+ }
+ scope = append([]string(nil), scope...) // copy
+ return f.jwtConfig(scope), nil
+}
+
+// JSON key file types.
+const (
+ serviceAccountKey = "service_account"
+ userCredentialsKey = "authorized_user"
+)
+
+// credentialsFile is the unmarshalled representation of a credentials file.
+type credentialsFile struct {
+ Type string `json:"type"` // serviceAccountKey or userCredentialsKey
+
+ // Service Account fields
+ ClientEmail string `json:"client_email"`
+ PrivateKeyID string `json:"private_key_id"`
+ PrivateKey string `json:"private_key"`
+ TokenURL string `json:"token_uri"`
+ ProjectID string `json:"project_id"`
+
+ // User Credential fields
+ // (These typically come from gcloud auth.)
+ ClientSecret string `json:"client_secret"`
+ ClientID string `json:"client_id"`
+ RefreshToken string `json:"refresh_token"`
+}
+
+func (f *credentialsFile) jwtConfig(scopes []string) *jwt.Config {
+ cfg := &jwt.Config{
+ Email: f.ClientEmail,
+ PrivateKey: []byte(f.PrivateKey),
+ PrivateKeyID: f.PrivateKeyID,
+ Scopes: scopes,
+ TokenURL: f.TokenURL,
+ }
+ if cfg.TokenURL == "" {
+ cfg.TokenURL = JWTTokenURL
+ }
+ return cfg
+}
+
+func (f *credentialsFile) tokenSource(ctx context.Context, scopes []string) (oauth2.TokenSource, error) {
+ switch f.Type {
+ case serviceAccountKey:
+ cfg := f.jwtConfig(scopes)
+ return cfg.TokenSource(ctx), nil
+ case userCredentialsKey:
+ cfg := &oauth2.Config{
+ ClientID: f.ClientID,
+ ClientSecret: f.ClientSecret,
+ Scopes: scopes,
+ Endpoint: Endpoint,
+ }
+ tok := &oauth2.Token{RefreshToken: f.RefreshToken}
+ return cfg.TokenSource(ctx, tok), nil
+ case "":
+ return nil, errors.New("missing 'type' field in credentials")
+ default:
+ return nil, fmt.Errorf("unknown credential type: %q", f.Type)
+ }
+}
+
+// ComputeTokenSource returns a token source that fetches access tokens
+// from Google Compute Engine (GCE)'s metadata server. It's only valid to use
+// this token source if your program is running on a GCE instance.
+// If no account is specified, "default" is used.
+// Further information about retrieving access tokens from the GCE metadata
+// server can be found at https://cloud.google.com/compute/docs/authentication.
+func ComputeTokenSource(account string) oauth2.TokenSource {
+ return oauth2.ReuseTokenSource(nil, computeSource{account: account})
+}
+
+type computeSource struct {
+ account string
+}
+
+func (cs computeSource) Token() (*oauth2.Token, error) {
+ if !metadata.OnGCE() {
+ return nil, errors.New("oauth2/google: can't get a token from the metadata service; not running on GCE")
+ }
+ acct := cs.account
+ if acct == "" {
+ acct = "default"
+ }
+ tokenJSON, err := metadata.Get("instance/service-accounts/" + acct + "/token")
+ if err != nil {
+ return nil, err
+ }
+ var res struct {
+ AccessToken string `json:"access_token"`
+ ExpiresInSec int `json:"expires_in"`
+ TokenType string `json:"token_type"`
+ }
+ err = json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res)
+ if err != nil {
+ return nil, fmt.Errorf("oauth2/google: invalid token JSON from metadata: %v", err)
+ }
+ if res.ExpiresInSec == 0 || res.AccessToken == "" {
+ return nil, fmt.Errorf("oauth2/google: incomplete token received from metadata")
+ }
+ return &oauth2.Token{
+ AccessToken: res.AccessToken,
+ TokenType: res.TokenType,
+ Expiry: time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second),
+ }, nil
+}
diff --git a/vendor/golang.org/x/oauth2/google/jwt.go b/vendor/golang.org/x/oauth2/google/jwt.go
new file mode 100644
index 0000000..b0fdb3a
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/google/jwt.go
@@ -0,0 +1,74 @@
+// Copyright 2015 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 google
+
+import (
+ "crypto/rsa"
+ "fmt"
+ "time"
+
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/internal"
+ "golang.org/x/oauth2/jws"
+)
+
+// JWTAccessTokenSourceFromJSON uses a Google Developers service account JSON
+// key file to read the credentials that authorize and authenticate the
+// requests, and returns a TokenSource that does not use any OAuth2 flow but
+// instead creates a JWT and sends that as the access token.
+// The audience is typically a URL that specifies the scope of the credentials.
+//
+// Note that this is not a standard OAuth flow, but rather an
+// optimization supported by a few Google services.
+// Unless you know otherwise, you should use JWTConfigFromJSON instead.
+func JWTAccessTokenSourceFromJSON(jsonKey []byte, audience string) (oauth2.TokenSource, error) {
+ cfg, err := JWTConfigFromJSON(jsonKey)
+ if err != nil {
+ return nil, fmt.Errorf("google: could not parse JSON key: %v", err)
+ }
+ pk, err := internal.ParseKey(cfg.PrivateKey)
+ if err != nil {
+ return nil, fmt.Errorf("google: could not parse key: %v", err)
+ }
+ ts := &jwtAccessTokenSource{
+ email: cfg.Email,
+ audience: audience,
+ pk: pk,
+ pkID: cfg.PrivateKeyID,
+ }
+ tok, err := ts.Token()
+ if err != nil {
+ return nil, err
+ }
+ return oauth2.ReuseTokenSource(tok, ts), nil
+}
+
+type jwtAccessTokenSource struct {
+ email, audience string
+ pk *rsa.PrivateKey
+ pkID string
+}
+
+func (ts *jwtAccessTokenSource) Token() (*oauth2.Token, error) {
+ iat := time.Now()
+ exp := iat.Add(time.Hour)
+ cs := &jws.ClaimSet{
+ Iss: ts.email,
+ Sub: ts.email,
+ Aud: ts.audience,
+ Iat: iat.Unix(),
+ Exp: exp.Unix(),
+ }
+ hdr := &jws.Header{
+ Algorithm: "RS256",
+ Typ: "JWT",
+ KeyID: string(ts.pkID),
+ }
+ msg, err := jws.Encode(hdr, cs, ts.pk)
+ if err != nil {
+ return nil, fmt.Errorf("google: could not encode JWT: %v", err)
+ }
+ return &oauth2.Token{AccessToken: msg, TokenType: "Bearer", Expiry: exp}, nil
+}
diff --git a/vendor/golang.org/x/oauth2/google/sdk.go b/vendor/golang.org/x/oauth2/google/sdk.go
new file mode 100644
index 0000000..bdc1808
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/google/sdk.go
@@ -0,0 +1,172 @@
+// Copyright 2015 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 google
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "os/user"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/internal"
+)
+
+type sdkCredentials struct {
+ Data []struct {
+ Credential struct {
+ ClientID string `json:"client_id"`
+ ClientSecret string `json:"client_secret"`
+ AccessToken string `json:"access_token"`
+ RefreshToken string `json:"refresh_token"`
+ TokenExpiry *time.Time `json:"token_expiry"`
+ } `json:"credential"`
+ Key struct {
+ Account string `json:"account"`
+ Scope string `json:"scope"`
+ } `json:"key"`
+ }
+}
+
+// An SDKConfig provides access to tokens from an account already
+// authorized via the Google Cloud SDK.
+type SDKConfig struct {
+ conf oauth2.Config
+ initialToken *oauth2.Token
+}
+
+// NewSDKConfig creates an SDKConfig for the given Google Cloud SDK
+// account. If account is empty, the account currently active in
+// Google Cloud SDK properties is used.
+// Google Cloud SDK credentials must be created by running `gcloud auth`
+// before using this function.
+// The Google Cloud SDK is available at https://cloud.google.com/sdk/.
+func NewSDKConfig(account string) (*SDKConfig, error) {
+ configPath, err := sdkConfigPath()
+ if err != nil {
+ return nil, fmt.Errorf("oauth2/google: error getting SDK config path: %v", err)
+ }
+ credentialsPath := filepath.Join(configPath, "credentials")
+ f, err := os.Open(credentialsPath)
+ if err != nil {
+ return nil, fmt.Errorf("oauth2/google: failed to load SDK credentials: %v", err)
+ }
+ defer f.Close()
+
+ var c sdkCredentials
+ if err := json.NewDecoder(f).Decode(&c); err != nil {
+ return nil, fmt.Errorf("oauth2/google: failed to decode SDK credentials from %q: %v", credentialsPath, err)
+ }
+ if len(c.Data) == 0 {
+ return nil, fmt.Errorf("oauth2/google: no credentials found in %q, run `gcloud auth login` to create one", credentialsPath)
+ }
+ if account == "" {
+ propertiesPath := filepath.Join(configPath, "properties")
+ f, err := os.Open(propertiesPath)
+ if err != nil {
+ return nil, fmt.Errorf("oauth2/google: failed to load SDK properties: %v", err)
+ }
+ defer f.Close()
+ ini, err := internal.ParseINI(f)
+ if err != nil {
+ return nil, fmt.Errorf("oauth2/google: failed to parse SDK properties %q: %v", propertiesPath, err)
+ }
+ core, ok := ini["core"]
+ if !ok {
+ return nil, fmt.Errorf("oauth2/google: failed to find [core] section in %v", ini)
+ }
+ active, ok := core["account"]
+ if !ok {
+ return nil, fmt.Errorf("oauth2/google: failed to find %q attribute in %v", "account", core)
+ }
+ account = active
+ }
+
+ for _, d := range c.Data {
+ if account == "" || d.Key.Account == account {
+ if d.Credential.AccessToken == "" && d.Credential.RefreshToken == "" {
+ return nil, fmt.Errorf("oauth2/google: no token available for account %q", account)
+ }
+ var expiry time.Time
+ if d.Credential.TokenExpiry != nil {
+ expiry = *d.Credential.TokenExpiry
+ }
+ return &SDKConfig{
+ conf: oauth2.Config{
+ ClientID: d.Credential.ClientID,
+ ClientSecret: d.Credential.ClientSecret,
+ Scopes: strings.Split(d.Key.Scope, " "),
+ Endpoint: Endpoint,
+ RedirectURL: "oob",
+ },
+ initialToken: &oauth2.Token{
+ AccessToken: d.Credential.AccessToken,
+ RefreshToken: d.Credential.RefreshToken,
+ Expiry: expiry,
+ },
+ }, nil
+ }
+ }
+ return nil, fmt.Errorf("oauth2/google: no such credentials for account %q", account)
+}
+
+// Client returns an HTTP client using Google Cloud SDK credentials to
+// authorize requests. The token will auto-refresh as necessary. The
+// underlying http.RoundTripper will be obtained using the provided
+// context. The returned client and its Transport should not be
+// modified.
+func (c *SDKConfig) Client(ctx context.Context) *http.Client {
+ return &http.Client{
+ Transport: &oauth2.Transport{
+ Source: c.TokenSource(ctx),
+ },
+ }
+}
+
+// TokenSource returns an oauth2.TokenSource that retrieve tokens from
+// Google Cloud SDK credentials using the provided context.
+// It will returns the current access token stored in the credentials,
+// and refresh it when it expires, but it won't update the credentials
+// with the new access token.
+func (c *SDKConfig) TokenSource(ctx context.Context) oauth2.TokenSource {
+ return c.conf.TokenSource(ctx, c.initialToken)
+}
+
+// Scopes are the OAuth 2.0 scopes the current account is authorized for.
+func (c *SDKConfig) Scopes() []string {
+ return c.conf.Scopes
+}
+
+// sdkConfigPath tries to guess where the gcloud config is located.
+// It can be overridden during tests.
+var sdkConfigPath = func() (string, error) {
+ if runtime.GOOS == "windows" {
+ return filepath.Join(os.Getenv("APPDATA"), "gcloud"), nil
+ }
+ homeDir := guessUnixHomeDir()
+ if homeDir == "" {
+ return "", errors.New("unable to get current user home directory: os/user lookup failed; $HOME is empty")
+ }
+ return filepath.Join(homeDir, ".config", "gcloud"), nil
+}
+
+func guessUnixHomeDir() string {
+ // Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470
+ if v := os.Getenv("HOME"); v != "" {
+ return v
+ }
+ // Else, fall back to user.Current:
+ if u, err := user.Current(); err == nil {
+ return u.HomeDir
+ }
+ return ""
+}
diff --git a/vendor/golang.org/x/oauth2/internal/oauth2.go b/vendor/golang.org/x/oauth2/internal/oauth2.go
new file mode 100644
index 0000000..fbe1028
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/internal/oauth2.go
@@ -0,0 +1,76 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package internal contains support packages for oauth2 package.
+package internal
+
+import (
+ "bufio"
+ "crypto/rsa"
+ "crypto/x509"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+)
+
+// ParseKey converts the binary contents of a private key file
+// to an *rsa.PrivateKey. It detects whether the private key is in a
+// PEM container or not. If so, it extracts the the private key
+// from PEM container before conversion. It only supports PEM
+// containers with no passphrase.
+func ParseKey(key []byte) (*rsa.PrivateKey, error) {
+ block, _ := pem.Decode(key)
+ if block != nil {
+ key = block.Bytes
+ }
+ parsedKey, err := x509.ParsePKCS8PrivateKey(key)
+ if err != nil {
+ parsedKey, err = x509.ParsePKCS1PrivateKey(key)
+ if err != nil {
+ return nil, fmt.Errorf("private key should be a PEM or plain PKSC1 or PKCS8; parse error: %v", err)
+ }
+ }
+ parsed, ok := parsedKey.(*rsa.PrivateKey)
+ if !ok {
+ return nil, errors.New("private key is invalid")
+ }
+ return parsed, nil
+}
+
+func ParseINI(ini io.Reader) (map[string]map[string]string, error) {
+ result := map[string]map[string]string{
+ "": map[string]string{}, // root section
+ }
+ scanner := bufio.NewScanner(ini)
+ currentSection := ""
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if strings.HasPrefix(line, ";") {
+ // comment.
+ continue
+ }
+ if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
+ currentSection = strings.TrimSpace(line[1 : len(line)-1])
+ result[currentSection] = map[string]string{}
+ continue
+ }
+ parts := strings.SplitN(line, "=", 2)
+ if len(parts) == 2 && parts[0] != "" {
+ result[currentSection][strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ return nil, fmt.Errorf("error scanning ini: %v", err)
+ }
+ return result, nil
+}
+
+func CondVal(v string) []string {
+ if v == "" {
+ return nil
+ }
+ return []string{v}
+}
diff --git a/vendor/golang.org/x/oauth2/internal/token.go b/vendor/golang.org/x/oauth2/internal/token.go
new file mode 100644
index 0000000..1c0ec76
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/internal/token.go
@@ -0,0 +1,227 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package internal contains support packages for oauth2 package.
+package internal
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "mime"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "golang.org/x/net/context"
+)
+
+// Token represents the crendentials used to authorize
+// the requests to access protected resources on the OAuth 2.0
+// provider's backend.
+//
+// This type is a mirror of oauth2.Token and exists to break
+// an otherwise-circular dependency. Other internal packages
+// should convert this Token into an oauth2.Token before use.
+type Token struct {
+ // AccessToken is the token that authorizes and authenticates
+ // the requests.
+ AccessToken string
+
+ // TokenType is the type of token.
+ // The Type method returns either this or "Bearer", the default.
+ TokenType string
+
+ // RefreshToken is a token that's used by the application
+ // (as opposed to the user) to refresh the access token
+ // if it expires.
+ RefreshToken string
+
+ // Expiry is the optional expiration time of the access token.
+ //
+ // If zero, TokenSource implementations will reuse the same
+ // token forever and RefreshToken or equivalent
+ // mechanisms for that TokenSource will not be used.
+ Expiry time.Time
+
+ // Raw optionally contains extra metadata from the server
+ // when updating a token.
+ Raw interface{}
+}
+
+// tokenJSON is the struct representing the HTTP response from OAuth2
+// providers returning a token in JSON form.
+type tokenJSON struct {
+ AccessToken string `json:"access_token"`
+ TokenType string `json:"token_type"`
+ RefreshToken string `json:"refresh_token"`
+ ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number
+ Expires expirationTime `json:"expires"` // broken Facebook spelling of expires_in
+}
+
+func (e *tokenJSON) expiry() (t time.Time) {
+ if v := e.ExpiresIn; v != 0 {
+ return time.Now().Add(time.Duration(v) * time.Second)
+ }
+ if v := e.Expires; v != 0 {
+ return time.Now().Add(time.Duration(v) * time.Second)
+ }
+ return
+}
+
+type expirationTime int32
+
+func (e *expirationTime) UnmarshalJSON(b []byte) error {
+ var n json.Number
+ err := json.Unmarshal(b, &n)
+ if err != nil {
+ return err
+ }
+ i, err := n.Int64()
+ if err != nil {
+ return err
+ }
+ *e = expirationTime(i)
+ return nil
+}
+
+var brokenAuthHeaderProviders = []string{
+ "https://accounts.google.com/",
+ "https://api.dropbox.com/",
+ "https://api.dropboxapi.com/",
+ "https://api.instagram.com/",
+ "https://api.netatmo.net/",
+ "https://api.odnoklassniki.ru/",
+ "https://api.pushbullet.com/",
+ "https://api.soundcloud.com/",
+ "https://api.twitch.tv/",
+ "https://app.box.com/",
+ "https://connect.stripe.com/",
+ "https://login.microsoftonline.com/",
+ "https://login.salesforce.com/",
+ "https://oauth.sandbox.trainingpeaks.com/",
+ "https://oauth.trainingpeaks.com/",
+ "https://oauth.vk.com/",
+ "https://openapi.baidu.com/",
+ "https://slack.com/",
+ "https://test-sandbox.auth.corp.google.com",
+ "https://test.salesforce.com/",
+ "https://user.gini.net/",
+ "https://www.douban.com/",
+ "https://www.googleapis.com/",
+ "https://www.linkedin.com/",
+ "https://www.strava.com/oauth/",
+ "https://www.wunderlist.com/oauth/",
+ "https://api.patreon.com/",
+ "https://sandbox.codeswholesale.com/oauth/token",
+ "https://api.codeswholesale.com/oauth/token",
+}
+
+func RegisterBrokenAuthHeaderProvider(tokenURL string) {
+ brokenAuthHeaderProviders = append(brokenAuthHeaderProviders, tokenURL)
+}
+
+// providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL
+// implements the OAuth2 spec correctly
+// See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
+// In summary:
+// - Reddit only accepts client secret in the Authorization header
+// - Dropbox accepts either it in URL param or Auth header, but not both.
+// - Google only accepts URL param (not spec compliant?), not Auth header
+// - Stripe only accepts client secret in Auth header with Bearer method, not Basic
+func providerAuthHeaderWorks(tokenURL string) bool {
+ for _, s := range brokenAuthHeaderProviders {
+ if strings.HasPrefix(tokenURL, s) {
+ // Some sites fail to implement the OAuth2 spec fully.
+ return false
+ }
+ }
+
+ // Assume the provider implements the spec properly
+ // otherwise. We can add more exceptions as they're
+ // discovered. We will _not_ be adding configurable hooks
+ // to this package to let users select server bugs.
+ return true
+}
+
+func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values) (*Token, error) {
+ hc, err := ContextClient(ctx)
+ if err != nil {
+ return nil, err
+ }
+ v.Set("client_id", clientID)
+ bustedAuth := !providerAuthHeaderWorks(tokenURL)
+ if bustedAuth && clientSecret != "" {
+ v.Set("client_secret", clientSecret)
+ }
+ req, err := http.NewRequest("POST", tokenURL, strings.NewReader(v.Encode()))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if !bustedAuth {
+ req.SetBasicAuth(clientID, clientSecret)
+ }
+ r, err := hc.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer r.Body.Close()
+ body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20))
+ if err != nil {
+ return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
+ }
+ if code := r.StatusCode; code < 200 || code > 299 {
+ return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", r.Status, body)
+ }
+
+ var token *Token
+ content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ switch content {
+ case "application/x-www-form-urlencoded", "text/plain":
+ vals, err := url.ParseQuery(string(body))
+ if err != nil {
+ return nil, err
+ }
+ token = &Token{
+ AccessToken: vals.Get("access_token"),
+ TokenType: vals.Get("token_type"),
+ RefreshToken: vals.Get("refresh_token"),
+ Raw: vals,
+ }
+ e := vals.Get("expires_in")
+ if e == "" {
+ // TODO(jbd): Facebook's OAuth2 implementation is broken and
+ // returns expires_in field in expires. Remove the fallback to expires,
+ // when Facebook fixes their implementation.
+ e = vals.Get("expires")
+ }
+ expires, _ := strconv.Atoi(e)
+ if expires != 0 {
+ token.Expiry = time.Now().Add(time.Duration(expires) * time.Second)
+ }
+ default:
+ var tj tokenJSON
+ if err = json.Unmarshal(body, &tj); err != nil {
+ return nil, err
+ }
+ token = &Token{
+ AccessToken: tj.AccessToken,
+ TokenType: tj.TokenType,
+ RefreshToken: tj.RefreshToken,
+ Expiry: tj.expiry(),
+ Raw: make(map[string]interface{}),
+ }
+ json.Unmarshal(body, &token.Raw) // no error checks for optional fields
+ }
+ // Don't overwrite `RefreshToken` with an empty value
+ // if this was a token refreshing request.
+ if token.RefreshToken == "" {
+ token.RefreshToken = v.Get("refresh_token")
+ }
+ return token, nil
+}
diff --git a/vendor/golang.org/x/oauth2/internal/transport.go b/vendor/golang.org/x/oauth2/internal/transport.go
new file mode 100644
index 0000000..f1f173e
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/internal/transport.go
@@ -0,0 +1,69 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package internal contains support packages for oauth2 package.
+package internal
+
+import (
+ "net/http"
+
+ "golang.org/x/net/context"
+)
+
+// HTTPClient is the context key to use with golang.org/x/net/context's
+// WithValue function to associate an *http.Client value with a context.
+var HTTPClient ContextKey
+
+// ContextKey is just an empty struct. It exists so HTTPClient can be
+// an immutable public variable with a unique type. It's immutable
+// because nobody else can create a ContextKey, being unexported.
+type ContextKey struct{}
+
+// ContextClientFunc is a func which tries to return an *http.Client
+// given a Context value. If it returns an error, the search stops
+// with that error. If it returns (nil, nil), the search continues
+// down the list of registered funcs.
+type ContextClientFunc func(context.Context) (*http.Client, error)
+
+var contextClientFuncs []ContextClientFunc
+
+func RegisterContextClientFunc(fn ContextClientFunc) {
+ contextClientFuncs = append(contextClientFuncs, fn)
+}
+
+func ContextClient(ctx context.Context) (*http.Client, error) {
+ if ctx != nil {
+ if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok {
+ return hc, nil
+ }
+ }
+ for _, fn := range contextClientFuncs {
+ c, err := fn(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if c != nil {
+ return c, nil
+ }
+ }
+ return http.DefaultClient, nil
+}
+
+func ContextTransport(ctx context.Context) http.RoundTripper {
+ hc, err := ContextClient(ctx)
+ // This is a rare error case (somebody using nil on App Engine).
+ if err != nil {
+ return ErrorTransport{err}
+ }
+ return hc.Transport
+}
+
+// ErrorTransport returns the specified error on RoundTrip.
+// This RoundTripper should be used in rare error cases where
+// error handling can be postponed to response handling time.
+type ErrorTransport struct{ Err error }
+
+func (t ErrorTransport) RoundTrip(*http.Request) (*http.Response, error) {
+ return nil, t.Err
+}
diff --git a/vendor/golang.org/x/oauth2/jws/jws.go b/vendor/golang.org/x/oauth2/jws/jws.go
new file mode 100644
index 0000000..683d2d2
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/jws/jws.go
@@ -0,0 +1,182 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package jws provides a partial implementation
+// of JSON Web Signature encoding and decoding.
+// It exists to support the golang.org/x/oauth2 package.
+//
+// See RFC 7515.
+//
+// Deprecated: this package is not intended for public use and might be
+// removed in the future. It exists for internal use only.
+// Please switch to another JWS package or copy this package into your own
+// source tree.
+package jws // import "golang.org/x/oauth2/jws"
+
+import (
+ "bytes"
+ "crypto"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+)
+
+// ClaimSet contains information about the JWT signature including the
+// permissions being requested (scopes), the target of the token, the issuer,
+// the time the token was issued, and the lifetime of the token.
+type ClaimSet struct {
+ Iss string `json:"iss"` // email address of the client_id of the application making the access token request
+ Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests
+ Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional).
+ Exp int64 `json:"exp"` // the expiration time of the assertion (seconds since Unix epoch)
+ Iat int64 `json:"iat"` // the time the assertion was issued (seconds since Unix epoch)
+ Typ string `json:"typ,omitempty"` // token type (Optional).
+
+ // Email for which the application is requesting delegated access (Optional).
+ Sub string `json:"sub,omitempty"`
+
+ // The old name of Sub. Client keeps setting Prn to be
+ // complaint with legacy OAuth 2.0 providers. (Optional)
+ Prn string `json:"prn,omitempty"`
+
+ // See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3
+ // This array is marshalled using custom code (see (c *ClaimSet) encode()).
+ PrivateClaims map[string]interface{} `json:"-"`
+}
+
+func (c *ClaimSet) encode() (string, error) {
+ // Reverting time back for machines whose time is not perfectly in sync.
+ // If client machine's time is in the future according
+ // to Google servers, an access token will not be issued.
+ now := time.Now().Add(-10 * time.Second)
+ if c.Iat == 0 {
+ c.Iat = now.Unix()
+ }
+ if c.Exp == 0 {
+ c.Exp = now.Add(time.Hour).Unix()
+ }
+ if c.Exp < c.Iat {
+ return "", fmt.Errorf("jws: invalid Exp = %v; must be later than Iat = %v", c.Exp, c.Iat)
+ }
+
+ b, err := json.Marshal(c)
+ if err != nil {
+ return "", err
+ }
+
+ if len(c.PrivateClaims) == 0 {
+ return base64.RawURLEncoding.EncodeToString(b), nil
+ }
+
+ // Marshal private claim set and then append it to b.
+ prv, err := json.Marshal(c.PrivateClaims)
+ if err != nil {
+ return "", fmt.Errorf("jws: invalid map of private claims %v", c.PrivateClaims)
+ }
+
+ // Concatenate public and private claim JSON objects.
+ if !bytes.HasSuffix(b, []byte{'}'}) {
+ return "", fmt.Errorf("jws: invalid JSON %s", b)
+ }
+ if !bytes.HasPrefix(prv, []byte{'{'}) {
+ return "", fmt.Errorf("jws: invalid JSON %s", prv)
+ }
+ b[len(b)-1] = ',' // Replace closing curly brace with a comma.
+ b = append(b, prv[1:]...) // Append private claims.
+ return base64.RawURLEncoding.EncodeToString(b), nil
+}
+
+// Header represents the header for the signed JWS payloads.
+type Header struct {
+ // The algorithm used for signature.
+ Algorithm string `json:"alg"`
+
+ // Represents the token type.
+ Typ string `json:"typ"`
+
+ // The optional hint of which key is being used.
+ KeyID string `json:"kid,omitempty"`
+}
+
+func (h *Header) encode() (string, error) {
+ b, err := json.Marshal(h)
+ if err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(b), nil
+}
+
+// Decode decodes a claim set from a JWS payload.
+func Decode(payload string) (*ClaimSet, error) {
+ // decode returned id token to get expiry
+ s := strings.Split(payload, ".")
+ if len(s) < 2 {
+ // TODO(jbd): Provide more context about the error.
+ return nil, errors.New("jws: invalid token received")
+ }
+ decoded, err := base64.RawURLEncoding.DecodeString(s[1])
+ if err != nil {
+ return nil, err
+ }
+ c := &ClaimSet{}
+ err = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c)
+ return c, err
+}
+
+// Signer returns a signature for the given data.
+type Signer func(data []byte) (sig []byte, err error)
+
+// EncodeWithSigner encodes a header and claim set with the provided signer.
+func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error) {
+ head, err := header.encode()
+ if err != nil {
+ return "", err
+ }
+ cs, err := c.encode()
+ if err != nil {
+ return "", err
+ }
+ ss := fmt.Sprintf("%s.%s", head, cs)
+ sig, err := sg([]byte(ss))
+ if err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(sig)), nil
+}
+
+// Encode encodes a signed JWS with provided header and claim set.
+// This invokes EncodeWithSigner using crypto/rsa.SignPKCS1v15 with the given RSA private key.
+func Encode(header *Header, c *ClaimSet, key *rsa.PrivateKey) (string, error) {
+ sg := func(data []byte) (sig []byte, err error) {
+ h := sha256.New()
+ h.Write(data)
+ return rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil))
+ }
+ return EncodeWithSigner(header, c, sg)
+}
+
+// Verify tests whether the provided JWT token's signature was produced by the private key
+// associated with the supplied public key.
+func Verify(token string, key *rsa.PublicKey) error {
+ parts := strings.Split(token, ".")
+ if len(parts) != 3 {
+ return errors.New("jws: invalid token received, token must have 3 parts")
+ }
+
+ signedContent := parts[0] + "." + parts[1]
+ signatureString, err := base64.RawURLEncoding.DecodeString(parts[2])
+ if err != nil {
+ return err
+ }
+
+ h := sha256.New()
+ h.Write([]byte(signedContent))
+ return rsa.VerifyPKCS1v15(key, crypto.SHA256, h.Sum(nil), []byte(signatureString))
+}
diff --git a/vendor/golang.org/x/oauth2/jwt/jwt.go b/vendor/golang.org/x/oauth2/jwt/jwt.go
new file mode 100644
index 0000000..f4b9523
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/jwt/jwt.go
@@ -0,0 +1,157 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly
+// known as "two-legged OAuth 2.0".
+//
+// See: https://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer-12
+package jwt
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/internal"
+ "golang.org/x/oauth2/jws"
+)
+
+var (
+ defaultGrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
+ defaultHeader = &jws.Header{Algorithm: "RS256", Typ: "JWT"}
+)
+
+// Config is the configuration for using JWT to fetch tokens,
+// commonly known as "two-legged OAuth 2.0".
+type Config struct {
+ // Email is the OAuth client identifier used when communicating with
+ // the configured OAuth provider.
+ Email string
+
+ // PrivateKey contains the contents of an RSA private key or the
+ // contents of a PEM file that contains a private key. The provided
+ // private key is used to sign JWT payloads.
+ // PEM containers with a passphrase are not supported.
+ // Use the following command to convert a PKCS 12 file into a PEM.
+ //
+ // $ openssl pkcs12 -in key.p12 -out key.pem -nodes
+ //
+ PrivateKey []byte
+
+ // PrivateKeyID contains an optional hint indicating which key is being
+ // used.
+ PrivateKeyID string
+
+ // Subject is the optional user to impersonate.
+ Subject string
+
+ // Scopes optionally specifies a list of requested permission scopes.
+ Scopes []string
+
+ // TokenURL is the endpoint required to complete the 2-legged JWT flow.
+ TokenURL string
+
+ // Expires optionally specifies how long the token is valid for.
+ Expires time.Duration
+}
+
+// TokenSource returns a JWT TokenSource using the configuration
+// in c and the HTTP client from the provided context.
+func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource {
+ return oauth2.ReuseTokenSource(nil, jwtSource{ctx, c})
+}
+
+// Client returns an HTTP client wrapping the context's
+// HTTP transport and adding Authorization headers with tokens
+// obtained from c.
+//
+// The returned client and its Transport should not be modified.
+func (c *Config) Client(ctx context.Context) *http.Client {
+ return oauth2.NewClient(ctx, c.TokenSource(ctx))
+}
+
+// jwtSource is a source that always does a signed JWT request for a token.
+// It should typically be wrapped with a reuseTokenSource.
+type jwtSource struct {
+ ctx context.Context
+ conf *Config
+}
+
+func (js jwtSource) Token() (*oauth2.Token, error) {
+ pk, err := internal.ParseKey(js.conf.PrivateKey)
+ if err != nil {
+ return nil, err
+ }
+ hc := oauth2.NewClient(js.ctx, nil)
+ claimSet := &jws.ClaimSet{
+ Iss: js.conf.Email,
+ Scope: strings.Join(js.conf.Scopes, " "),
+ Aud: js.conf.TokenURL,
+ }
+ if subject := js.conf.Subject; subject != "" {
+ claimSet.Sub = subject
+ // prn is the old name of sub. Keep setting it
+ // to be compatible with legacy OAuth 2.0 providers.
+ claimSet.Prn = subject
+ }
+ if t := js.conf.Expires; t > 0 {
+ claimSet.Exp = time.Now().Add(t).Unix()
+ }
+ payload, err := jws.Encode(defaultHeader, claimSet, pk)
+ if err != nil {
+ return nil, err
+ }
+ v := url.Values{}
+ v.Set("grant_type", defaultGrantType)
+ v.Set("assertion", payload)
+ resp, err := hc.PostForm(js.conf.TokenURL, v)
+ if err != nil {
+ return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
+ }
+ defer resp.Body.Close()
+ body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if err != nil {
+ return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
+ }
+ if c := resp.StatusCode; c < 200 || c > 299 {
+ return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", resp.Status, body)
+ }
+ // tokenRes is the JSON response body.
+ var tokenRes struct {
+ AccessToken string `json:"access_token"`
+ TokenType string `json:"token_type"`
+ IDToken string `json:"id_token"`
+ ExpiresIn int64 `json:"expires_in"` // relative seconds from now
+ }
+ if err := json.Unmarshal(body, &tokenRes); err != nil {
+ return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
+ }
+ token := &oauth2.Token{
+ AccessToken: tokenRes.AccessToken,
+ TokenType: tokenRes.TokenType,
+ }
+ raw := make(map[string]interface{})
+ json.Unmarshal(body, &raw) // no error checks for optional fields
+ token = token.WithExtra(raw)
+
+ if secs := tokenRes.ExpiresIn; secs > 0 {
+ token.Expiry = time.Now().Add(time.Duration(secs) * time.Second)
+ }
+ if v := tokenRes.IDToken; v != "" {
+ // decode returned id token to get expiry
+ claimSet, err := jws.Decode(v)
+ if err != nil {
+ return nil, fmt.Errorf("oauth2: error decoding JWT token: %v", err)
+ }
+ token.Expiry = time.Unix(claimSet.Exp, 0)
+ }
+ return token, nil
+}
diff --git a/vendor/golang.org/x/oauth2/oauth2.go b/vendor/golang.org/x/oauth2/oauth2.go
new file mode 100644
index 0000000..7b06bfe
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/oauth2.go
@@ -0,0 +1,341 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package oauth2 provides support for making
+// OAuth2 authorized and authenticated HTTP requests.
+// It can additionally grant authorization with Bearer JWT.
+package oauth2 // import "golang.org/x/oauth2"
+
+import (
+ "bytes"
+ "errors"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2/internal"
+)
+
+// NoContext is the default context you should supply if not using
+// your own context.Context (see https://golang.org/x/net/context).
+//
+// Deprecated: Use context.Background() or context.TODO() instead.
+var NoContext = context.TODO()
+
+// RegisterBrokenAuthHeaderProvider registers an OAuth2 server
+// identified by the tokenURL prefix as an OAuth2 implementation
+// which doesn't support the HTTP Basic authentication
+// scheme to authenticate with the authorization server.
+// Once a server is registered, credentials (client_id and client_secret)
+// will be passed as query parameters rather than being present
+// in the Authorization header.
+// See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
+func RegisterBrokenAuthHeaderProvider(tokenURL string) {
+ internal.RegisterBrokenAuthHeaderProvider(tokenURL)
+}
+
+// Config describes a typical 3-legged OAuth2 flow, with both the
+// client application information and the server's endpoint URLs.
+// For the client credentials 2-legged OAuth2 flow, see the clientcredentials
+// package (https://golang.org/x/oauth2/clientcredentials).
+type Config struct {
+ // ClientID is the application's ID.
+ ClientID string
+
+ // ClientSecret is the application's secret.
+ ClientSecret string
+
+ // Endpoint contains the resource server's token endpoint
+ // URLs. These are constants specific to each server and are
+ // often available via site-specific packages, such as
+ // google.Endpoint or github.Endpoint.
+ Endpoint Endpoint
+
+ // RedirectURL is the URL to redirect users going through
+ // the OAuth flow, after the resource owner's URLs.
+ RedirectURL string
+
+ // Scope specifies optional requested permissions.
+ Scopes []string
+}
+
+// A TokenSource is anything that can return a token.
+type TokenSource interface {
+ // Token returns a token or an error.
+ // Token must be safe for concurrent use by multiple goroutines.
+ // The returned Token must not be modified.
+ Token() (*Token, error)
+}
+
+// Endpoint contains the OAuth 2.0 provider's authorization and token
+// endpoint URLs.
+type Endpoint struct {
+ AuthURL string
+ TokenURL string
+}
+
+var (
+ // AccessTypeOnline and AccessTypeOffline are options passed
+ // to the Options.AuthCodeURL method. They modify the
+ // "access_type" field that gets sent in the URL returned by
+ // AuthCodeURL.
+ //
+ // Online is the default if neither is specified. If your
+ // application needs to refresh access tokens when the user
+ // is not present at the browser, then use offline. This will
+ // result in your application obtaining a refresh token the
+ // first time your application exchanges an authorization
+ // code for a user.
+ AccessTypeOnline AuthCodeOption = SetAuthURLParam("access_type", "online")
+ AccessTypeOffline AuthCodeOption = SetAuthURLParam("access_type", "offline")
+
+ // ApprovalForce forces the users to view the consent dialog
+ // and confirm the permissions request at the URL returned
+ // from AuthCodeURL, even if they've already done so.
+ ApprovalForce AuthCodeOption = SetAuthURLParam("approval_prompt", "force")
+)
+
+// An AuthCodeOption is passed to Config.AuthCodeURL.
+type AuthCodeOption interface {
+ setValue(url.Values)
+}
+
+type setParam struct{ k, v string }
+
+func (p setParam) setValue(m url.Values) { m.Set(p.k, p.v) }
+
+// SetAuthURLParam builds an AuthCodeOption which passes key/value parameters
+// to a provider's authorization endpoint.
+func SetAuthURLParam(key, value string) AuthCodeOption {
+ return setParam{key, value}
+}
+
+// AuthCodeURL returns a URL to OAuth 2.0 provider's consent page
+// that asks for permissions for the required scopes explicitly.
+//
+// State is a token to protect the user from CSRF attacks. You must
+// always provide a non-zero string and validate that it matches the
+// the state query parameter on your redirect callback.
+// See http://tools.ietf.org/html/rfc6749#section-10.12 for more info.
+//
+// Opts may include AccessTypeOnline or AccessTypeOffline, as well
+// as ApprovalForce.
+func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string {
+ var buf bytes.Buffer
+ buf.WriteString(c.Endpoint.AuthURL)
+ v := url.Values{
+ "response_type": {"code"},
+ "client_id": {c.ClientID},
+ "redirect_uri": internal.CondVal(c.RedirectURL),
+ "scope": internal.CondVal(strings.Join(c.Scopes, " ")),
+ "state": internal.CondVal(state),
+ }
+ for _, opt := range opts {
+ opt.setValue(v)
+ }
+ if strings.Contains(c.Endpoint.AuthURL, "?") {
+ buf.WriteByte('&')
+ } else {
+ buf.WriteByte('?')
+ }
+ buf.WriteString(v.Encode())
+ return buf.String()
+}
+
+// PasswordCredentialsToken converts a resource owner username and password
+// pair into a token.
+//
+// Per the RFC, this grant type should only be used "when there is a high
+// degree of trust between the resource owner and the client (e.g., the client
+// is part of the device operating system or a highly privileged application),
+// and when other authorization grant types are not available."
+// See https://tools.ietf.org/html/rfc6749#section-4.3 for more info.
+//
+// The HTTP client to use is derived from the context.
+// If nil, http.DefaultClient is used.
+func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) {
+ return retrieveToken(ctx, c, url.Values{
+ "grant_type": {"password"},
+ "username": {username},
+ "password": {password},
+ "scope": internal.CondVal(strings.Join(c.Scopes, " ")),
+ })
+}
+
+// Exchange converts an authorization code into a token.
+//
+// It is used after a resource provider redirects the user back
+// to the Redirect URI (the URL obtained from AuthCodeURL).
+//
+// The HTTP client to use is derived from the context.
+// If a client is not provided via the context, http.DefaultClient is used.
+//
+// The code will be in the *http.Request.FormValue("code"). Before
+// calling Exchange, be sure to validate FormValue("state").
+func (c *Config) Exchange(ctx context.Context, code string) (*Token, error) {
+ return retrieveToken(ctx, c, url.Values{
+ "grant_type": {"authorization_code"},
+ "code": {code},
+ "redirect_uri": internal.CondVal(c.RedirectURL),
+ "scope": internal.CondVal(strings.Join(c.Scopes, " ")),
+ })
+}
+
+// Client returns an HTTP client using the provided token.
+// The token will auto-refresh as necessary. The underlying
+// HTTP transport will be obtained using the provided context.
+// The returned client and its Transport should not be modified.
+func (c *Config) Client(ctx context.Context, t *Token) *http.Client {
+ return NewClient(ctx, c.TokenSource(ctx, t))
+}
+
+// TokenSource returns a TokenSource that returns t until t expires,
+// automatically refreshing it as necessary using the provided context.
+//
+// Most users will use Config.Client instead.
+func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource {
+ tkr := &tokenRefresher{
+ ctx: ctx,
+ conf: c,
+ }
+ if t != nil {
+ tkr.refreshToken = t.RefreshToken
+ }
+ return &reuseTokenSource{
+ t: t,
+ new: tkr,
+ }
+}
+
+// tokenRefresher is a TokenSource that makes "grant_type"=="refresh_token"
+// HTTP requests to renew a token using a RefreshToken.
+type tokenRefresher struct {
+ ctx context.Context // used to get HTTP requests
+ conf *Config
+ refreshToken string
+}
+
+// WARNING: Token is not safe for concurrent access, as it
+// updates the tokenRefresher's refreshToken field.
+// Within this package, it is used by reuseTokenSource which
+// synchronizes calls to this method with its own mutex.
+func (tf *tokenRefresher) Token() (*Token, error) {
+ if tf.refreshToken == "" {
+ return nil, errors.New("oauth2: token expired and refresh token is not set")
+ }
+
+ tk, err := retrieveToken(tf.ctx, tf.conf, url.Values{
+ "grant_type": {"refresh_token"},
+ "refresh_token": {tf.refreshToken},
+ })
+
+ if err != nil {
+ return nil, err
+ }
+ if tf.refreshToken != tk.RefreshToken {
+ tf.refreshToken = tk.RefreshToken
+ }
+ return tk, err
+}
+
+// reuseTokenSource is a TokenSource that holds a single token in memory
+// and validates its expiry before each call to retrieve it with
+// Token. If it's expired, it will be auto-refreshed using the
+// new TokenSource.
+type reuseTokenSource struct {
+ new TokenSource // called when t is expired.
+
+ mu sync.Mutex // guards t
+ t *Token
+}
+
+// Token returns the current token if it's still valid, else will
+// refresh the current token (using r.Context for HTTP client
+// information) and return the new one.
+func (s *reuseTokenSource) Token() (*Token, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.t.Valid() {
+ return s.t, nil
+ }
+ t, err := s.new.Token()
+ if err != nil {
+ return nil, err
+ }
+ s.t = t
+ return t, nil
+}
+
+// StaticTokenSource returns a TokenSource that always returns the same token.
+// Because the provided token t is never refreshed, StaticTokenSource is only
+// useful for tokens that never expire.
+func StaticTokenSource(t *Token) TokenSource {
+ return staticTokenSource{t}
+}
+
+// staticTokenSource is a TokenSource that always returns the same Token.
+type staticTokenSource struct {
+ t *Token
+}
+
+func (s staticTokenSource) Token() (*Token, error) {
+ return s.t, nil
+}
+
+// HTTPClient is the context key to use with golang.org/x/net/context's
+// WithValue function to associate an *http.Client value with a context.
+var HTTPClient internal.ContextKey
+
+// NewClient creates an *http.Client from a Context and TokenSource.
+// The returned client is not valid beyond the lifetime of the context.
+//
+// As a special case, if src is nil, a non-OAuth2 client is returned
+// using the provided context. This exists to support related OAuth2
+// packages.
+func NewClient(ctx context.Context, src TokenSource) *http.Client {
+ if src == nil {
+ c, err := internal.ContextClient(ctx)
+ if err != nil {
+ return &http.Client{Transport: internal.ErrorTransport{Err: err}}
+ }
+ return c
+ }
+ return &http.Client{
+ Transport: &Transport{
+ Base: internal.ContextTransport(ctx),
+ Source: ReuseTokenSource(nil, src),
+ },
+ }
+}
+
+// ReuseTokenSource returns a TokenSource which repeatedly returns the
+// same token as long as it's valid, starting with t.
+// When its cached token is invalid, a new token is obtained from src.
+//
+// ReuseTokenSource is typically used to reuse tokens from a cache
+// (such as a file on disk) between runs of a program, rather than
+// obtaining new tokens unnecessarily.
+//
+// The initial token t may be nil, in which case the TokenSource is
+// wrapped in a caching version if it isn't one already. This also
+// means it's always safe to wrap ReuseTokenSource around any other
+// TokenSource without adverse effects.
+func ReuseTokenSource(t *Token, src TokenSource) TokenSource {
+ // Don't wrap a reuseTokenSource in itself. That would work,
+ // but cause an unnecessary number of mutex operations.
+ // Just build the equivalent one.
+ if rt, ok := src.(*reuseTokenSource); ok {
+ if t == nil {
+ // Just use it directly.
+ return rt
+ }
+ src = rt.new
+ }
+ return &reuseTokenSource{
+ t: t,
+ new: src,
+ }
+}
diff --git a/vendor/golang.org/x/oauth2/token.go b/vendor/golang.org/x/oauth2/token.go
new file mode 100644
index 0000000..7a3167f
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/token.go
@@ -0,0 +1,158 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package oauth2
+
+import (
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2/internal"
+)
+
+// expiryDelta determines how earlier a token should be considered
+// expired than its actual expiration time. It is used to avoid late
+// expirations due to client-server time mismatches.
+const expiryDelta = 10 * time.Second
+
+// Token represents the crendentials used to authorize
+// the requests to access protected resources on the OAuth 2.0
+// provider's backend.
+//
+// Most users of this package should not access fields of Token
+// directly. They're exported mostly for use by related packages
+// implementing derivative OAuth2 flows.
+type Token struct {
+ // AccessToken is the token that authorizes and authenticates
+ // the requests.
+ AccessToken string `json:"access_token"`
+
+ // TokenType is the type of token.
+ // The Type method returns either this or "Bearer", the default.
+ TokenType string `json:"token_type,omitempty"`
+
+ // RefreshToken is a token that's used by the application
+ // (as opposed to the user) to refresh the access token
+ // if it expires.
+ RefreshToken string `json:"refresh_token,omitempty"`
+
+ // Expiry is the optional expiration time of the access token.
+ //
+ // If zero, TokenSource implementations will reuse the same
+ // token forever and RefreshToken or equivalent
+ // mechanisms for that TokenSource will not be used.
+ Expiry time.Time `json:"expiry,omitempty"`
+
+ // raw optionally contains extra metadata from the server
+ // when updating a token.
+ raw interface{}
+}
+
+// Type returns t.TokenType if non-empty, else "Bearer".
+func (t *Token) Type() string {
+ if strings.EqualFold(t.TokenType, "bearer") {
+ return "Bearer"
+ }
+ if strings.EqualFold(t.TokenType, "mac") {
+ return "MAC"
+ }
+ if strings.EqualFold(t.TokenType, "basic") {
+ return "Basic"
+ }
+ if t.TokenType != "" {
+ return t.TokenType
+ }
+ return "Bearer"
+}
+
+// SetAuthHeader sets the Authorization header to r using the access
+// token in t.
+//
+// This method is unnecessary when using Transport or an HTTP Client
+// returned by this package.
+func (t *Token) SetAuthHeader(r *http.Request) {
+ r.Header.Set("Authorization", t.Type()+" "+t.AccessToken)
+}
+
+// WithExtra returns a new Token that's a clone of t, but using the
+// provided raw extra map. This is only intended for use by packages
+// implementing derivative OAuth2 flows.
+func (t *Token) WithExtra(extra interface{}) *Token {
+ t2 := new(Token)
+ *t2 = *t
+ t2.raw = extra
+ return t2
+}
+
+// Extra returns an extra field.
+// Extra fields are key-value pairs returned by the server as a
+// part of the token retrieval response.
+func (t *Token) Extra(key string) interface{} {
+ if raw, ok := t.raw.(map[string]interface{}); ok {
+ return raw[key]
+ }
+
+ vals, ok := t.raw.(url.Values)
+ if !ok {
+ return nil
+ }
+
+ v := vals.Get(key)
+ switch s := strings.TrimSpace(v); strings.Count(s, ".") {
+ case 0: // Contains no "."; try to parse as int
+ if i, err := strconv.ParseInt(s, 10, 64); err == nil {
+ return i
+ }
+ case 1: // Contains a single "."; try to parse as float
+ if f, err := strconv.ParseFloat(s, 64); err == nil {
+ return f
+ }
+ }
+
+ return v
+}
+
+// expired reports whether the token is expired.
+// t must be non-nil.
+func (t *Token) expired() bool {
+ if t.Expiry.IsZero() {
+ return false
+ }
+ return t.Expiry.Add(-expiryDelta).Before(time.Now())
+}
+
+// Valid reports whether t is non-nil, has an AccessToken, and is not expired.
+func (t *Token) Valid() bool {
+ return t != nil && t.AccessToken != "" && !t.expired()
+}
+
+// tokenFromInternal maps an *internal.Token struct into
+// a *Token struct.
+func tokenFromInternal(t *internal.Token) *Token {
+ if t == nil {
+ return nil
+ }
+ return &Token{
+ AccessToken: t.AccessToken,
+ TokenType: t.TokenType,
+ RefreshToken: t.RefreshToken,
+ Expiry: t.Expiry,
+ raw: t.Raw,
+ }
+}
+
+// retrieveToken takes a *Config and uses that to retrieve an *internal.Token.
+// This token is then mapped from *internal.Token into an *oauth2.Token which is returned along
+// with an error..
+func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) {
+ tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v)
+ if err != nil {
+ return nil, err
+ }
+ return tokenFromInternal(tk), nil
+}
diff --git a/vendor/golang.org/x/oauth2/transport.go b/vendor/golang.org/x/oauth2/transport.go
new file mode 100644
index 0000000..92ac7e2
--- /dev/null
+++ b/vendor/golang.org/x/oauth2/transport.go
@@ -0,0 +1,132 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package oauth2
+
+import (
+ "errors"
+ "io"
+ "net/http"
+ "sync"
+)
+
+// Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests,
+// wrapping a base RoundTripper and adding an Authorization header
+// with a token from the supplied Sources.
+//
+// Transport is a low-level mechanism. Most code will use the
+// higher-level Config.Client method instead.
+type Transport struct {
+ // Source supplies the token to add to outgoing requests'
+ // Authorization headers.
+ Source TokenSource
+
+ // Base is the base RoundTripper used to make HTTP requests.
+ // If nil, http.DefaultTransport is used.
+ Base http.RoundTripper
+
+ mu sync.Mutex // guards modReq
+ modReq map[*http.Request]*http.Request // original -> modified
+}
+
+// RoundTrip authorizes and authenticates the request with an
+// access token. If no token exists or token is expired,
+// tries to refresh/fetch a new token.
+func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
+ if t.Source == nil {
+ return nil, errors.New("oauth2: Transport's Source is nil")
+ }
+ token, err := t.Source.Token()
+ if err != nil {
+ return nil, err
+ }
+
+ req2 := cloneRequest(req) // per RoundTripper contract
+ token.SetAuthHeader(req2)
+ t.setModReq(req, req2)
+ res, err := t.base().RoundTrip(req2)
+ if err != nil {
+ t.setModReq(req, nil)
+ return nil, err
+ }
+ res.Body = &onEOFReader{
+ rc: res.Body,
+ fn: func() { t.setModReq(req, nil) },
+ }
+ return res, nil
+}
+
+// CancelRequest cancels an in-flight request by closing its connection.
+func (t *Transport) CancelRequest(req *http.Request) {
+ type canceler interface {
+ CancelRequest(*http.Request)
+ }
+ if cr, ok := t.base().(canceler); ok {
+ t.mu.Lock()
+ modReq := t.modReq[req]
+ delete(t.modReq, req)
+ t.mu.Unlock()
+ cr.CancelRequest(modReq)
+ }
+}
+
+func (t *Transport) base() http.RoundTripper {
+ if t.Base != nil {
+ return t.Base
+ }
+ return http.DefaultTransport
+}
+
+func (t *Transport) setModReq(orig, mod *http.Request) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.modReq == nil {
+ t.modReq = make(map[*http.Request]*http.Request)
+ }
+ if mod == nil {
+ delete(t.modReq, orig)
+ } else {
+ t.modReq[orig] = mod
+ }
+}
+
+// cloneRequest returns a clone of the provided *http.Request.
+// The clone is a shallow copy of the struct and its Header map.
+func cloneRequest(r *http.Request) *http.Request {
+ // shallow copy of the struct
+ r2 := new(http.Request)
+ *r2 = *r
+ // deep copy of the Header
+ r2.Header = make(http.Header, len(r.Header))
+ for k, s := range r.Header {
+ r2.Header[k] = append([]string(nil), s...)
+ }
+ return r2
+}
+
+type onEOFReader struct {
+ rc io.ReadCloser
+ fn func()
+}
+
+func (r *onEOFReader) Read(p []byte) (n int, err error) {
+ n, err = r.rc.Read(p)
+ if err == io.EOF {
+ r.runFunc()
+ }
+ return
+}
+
+func (r *onEOFReader) Close() error {
+ err := r.rc.Close()
+ r.runFunc()
+ return err
+}
+
+func (r *onEOFReader) runFunc() {
+ if fn := r.fn; fn != nil {
+ fn()
+ r.fn = nil
+ }
+}
diff --git a/vendor/golang.org/x/sync/LICENSE b/vendor/golang.org/x/sync/LICENSE
new file mode 100644
index 0000000..6a66aea
--- /dev/null
+++ b/vendor/golang.org/x/sync/LICENSE
@@ -0,0 +1,27 @@
+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/sync/PATENTS b/vendor/golang.org/x/sync/PATENTS
new file mode 100644
index 0000000..7330990
--- /dev/null
+++ b/vendor/golang.org/x/sync/PATENTS
@@ -0,0 +1,22 @@
+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/sync/README b/vendor/golang.org/x/sync/README
new file mode 100644
index 0000000..59c9dcb
--- /dev/null
+++ b/vendor/golang.org/x/sync/README
@@ -0,0 +1,2 @@
+This repository provides Go concurrency primitives in addition to the
+ones provided by the language and "sync" and "sync/atomic" packages.
diff --git a/vendor/golang.org/x/sync/errgroup/errgroup.go b/vendor/golang.org/x/sync/errgroup/errgroup.go
new file mode 100644
index 0000000..533438d
--- /dev/null
+++ b/vendor/golang.org/x/sync/errgroup/errgroup.go
@@ -0,0 +1,67 @@
+// 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 errgroup provides synchronization, error propagation, and Context
+// cancelation for groups of goroutines working on subtasks of a common task.
+package errgroup
+
+import (
+ "sync"
+
+ "golang.org/x/net/context"
+)
+
+// A Group is a collection of goroutines working on subtasks that are part of
+// the same overall task.
+//
+// A zero Group is valid and does not cancel on error.
+type Group struct {
+ cancel func()
+
+ wg sync.WaitGroup
+
+ errOnce sync.Once
+ err error
+}
+
+// WithContext returns a new Group and an associated Context derived from ctx.
+//
+// The derived Context is canceled the first time a function passed to Go
+// returns a non-nil error or the first time Wait returns, whichever occurs
+// first.
+func WithContext(ctx context.Context) (*Group, context.Context) {
+ ctx, cancel := context.WithCancel(ctx)
+ return &Group{cancel: cancel}, ctx
+}
+
+// Wait blocks until all function calls from the Go method have returned, then
+// returns the first non-nil error (if any) from them.
+func (g *Group) Wait() error {
+ g.wg.Wait()
+ if g.cancel != nil {
+ g.cancel()
+ }
+ return g.err
+}
+
+// Go calls the given function in a new goroutine.
+//
+// The first call to return a non-nil error cancels the group; its error will be
+// returned by Wait.
+func (g *Group) Go(f func() error) {
+ g.wg.Add(1)
+
+ go func() {
+ defer g.wg.Done()
+
+ if err := f(); err != nil {
+ g.errOnce.Do(func() {
+ g.err = err
+ if g.cancel != nil {
+ g.cancel()
+ }
+ })
+ }
+ }()
+}
diff --git a/vendor/golang.org/x/sync/singleflight/singleflight.go b/vendor/golang.org/x/sync/singleflight/singleflight.go
new file mode 100644
index 0000000..9a4f8d5
--- /dev/null
+++ b/vendor/golang.org/x/sync/singleflight/singleflight.go
@@ -0,0 +1,111 @@
+// 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 singleflight provides a duplicate function call suppression
+// mechanism.
+package singleflight // import "golang.org/x/sync/singleflight"
+
+import "sync"
+
+// call is an in-flight or completed singleflight.Do call
+type call struct {
+ wg sync.WaitGroup
+
+ // These fields are written once before the WaitGroup is done
+ // and are only read after the WaitGroup is done.
+ val interface{}
+ err error
+
+ // These fields are read and written with the singleflight
+ // mutex held before the WaitGroup is done, and are read but
+ // not written after the WaitGroup is done.
+ dups int
+ chans []chan<- Result
+}
+
+// Group represents a class of work and forms a namespace in
+// which units of work can be executed with duplicate suppression.
+type Group struct {
+ mu sync.Mutex // protects m
+ m map[string]*call // lazily initialized
+}
+
+// Result holds the results of Do, so they can be passed
+// on a channel.
+type Result struct {
+ Val interface{}
+ Err error
+ Shared bool
+}
+
+// Do executes and returns the results of the given function, making
+// sure that only one execution is in-flight for a given key at a
+// time. If a duplicate comes in, the duplicate caller waits for the
+// original to complete and receives the same results.
+// The return value shared indicates whether v was given to multiple callers.
+func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
+ g.mu.Lock()
+ if g.m == nil {
+ g.m = make(map[string]*call)
+ }
+ if c, ok := g.m[key]; ok {
+ c.dups++
+ g.mu.Unlock()
+ c.wg.Wait()
+ return c.val, c.err, true
+ }
+ c := new(call)
+ c.wg.Add(1)
+ g.m[key] = c
+ g.mu.Unlock()
+
+ g.doCall(c, key, fn)
+ return c.val, c.err, c.dups > 0
+}
+
+// DoChan is like Do but returns a channel that will receive the
+// results when they are ready.
+func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result {
+ ch := make(chan Result, 1)
+ g.mu.Lock()
+ if g.m == nil {
+ g.m = make(map[string]*call)
+ }
+ if c, ok := g.m[key]; ok {
+ c.dups++
+ c.chans = append(c.chans, ch)
+ g.mu.Unlock()
+ return ch
+ }
+ c := &call{chans: []chan<- Result{ch}}
+ c.wg.Add(1)
+ g.m[key] = c
+ g.mu.Unlock()
+
+ go g.doCall(c, key, fn)
+
+ return ch
+}
+
+// doCall handles the single call for a key.
+func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) {
+ c.val, c.err = fn()
+ c.wg.Done()
+
+ g.mu.Lock()
+ delete(g.m, key)
+ for _, ch := range c.chans {
+ ch <- Result{c.val, c.err, c.dups > 0}
+ }
+ g.mu.Unlock()
+}
+
+// Forget tells the singleflight to forget about a key. Future calls
+// to Do for this key will call the function rather than waiting for
+// an earlier call to complete.
+func (g *Group) Forget(key string) {
+ g.mu.Lock()
+ delete(g.m, key)
+ g.mu.Unlock()
+}
diff --git a/vendor/golang.org/x/sync/syncmap/map.go b/vendor/golang.org/x/sync/syncmap/map.go
new file mode 100644
index 0000000..80e1584
--- /dev/null
+++ b/vendor/golang.org/x/sync/syncmap/map.go
@@ -0,0 +1,372 @@
+// 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 syncmap provides a concurrent map implementation.
+// It is a prototype for a proposed addition to the sync package
+// in the standard library.
+// (https://golang.org/issue/18177)
+package syncmap
+
+import (
+ "sync"
+ "sync/atomic"
+ "unsafe"
+)
+
+// Map is a concurrent map with amortized-constant-time loads, stores, and deletes.
+// It is safe for multiple goroutines to call a Map's methods concurrently.
+//
+// The zero Map is valid and empty.
+//
+// A Map must not be copied after first use.
+type Map struct {
+ mu sync.Mutex
+
+ // read contains the portion of the map's contents that are safe for
+ // concurrent access (with or without mu held).
+ //
+ // The read field itself is always safe to load, but must only be stored with
+ // mu held.
+ //
+ // Entries stored in read may be updated concurrently without mu, but updating
+ // a previously-expunged entry requires that the entry be copied to the dirty
+ // map and unexpunged with mu held.
+ read atomic.Value // readOnly
+
+ // dirty contains the portion of the map's contents that require mu to be
+ // held. To ensure that the dirty map can be promoted to the read map quickly,
+ // it also includes all of the non-expunged entries in the read map.
+ //
+ // Expunged entries are not stored in the dirty map. An expunged entry in the
+ // clean map must be unexpunged and added to the dirty map before a new value
+ // can be stored to it.
+ //
+ // If the dirty map is nil, the next write to the map will initialize it by
+ // making a shallow copy of the clean map, omitting stale entries.
+ dirty map[interface{}]*entry
+
+ // misses counts the number of loads since the read map was last updated that
+ // needed to lock mu to determine whether the key was present.
+ //
+ // Once enough misses have occurred to cover the cost of copying the dirty
+ // map, the dirty map will be promoted to the read map (in the unamended
+ // state) and the next store to the map will make a new dirty copy.
+ misses int
+}
+
+// readOnly is an immutable struct stored atomically in the Map.read field.
+type readOnly struct {
+ m map[interface{}]*entry
+ amended bool // true if the dirty map contains some key not in m.
+}
+
+// expunged is an arbitrary pointer that marks entries which have been deleted
+// from the dirty map.
+var expunged = unsafe.Pointer(new(interface{}))
+
+// An entry is a slot in the map corresponding to a particular key.
+type entry struct {
+ // p points to the interface{} value stored for the entry.
+ //
+ // If p == nil, the entry has been deleted and m.dirty == nil.
+ //
+ // If p == expunged, the entry has been deleted, m.dirty != nil, and the entry
+ // is missing from m.dirty.
+ //
+ // Otherwise, the entry is valid and recorded in m.read.m[key] and, if m.dirty
+ // != nil, in m.dirty[key].
+ //
+ // An entry can be deleted by atomic replacement with nil: when m.dirty is
+ // next created, it will atomically replace nil with expunged and leave
+ // m.dirty[key] unset.
+ //
+ // An entry's associated value can be updated by atomic replacement, provided
+ // p != expunged. If p == expunged, an entry's associated value can be updated
+ // only after first setting m.dirty[key] = e so that lookups using the dirty
+ // map find the entry.
+ p unsafe.Pointer // *interface{}
+}
+
+func newEntry(i interface{}) *entry {
+ return &entry{p: unsafe.Pointer(&i)}
+}
+
+// Load returns the value stored in the map for a key, or nil if no
+// value is present.
+// The ok result indicates whether value was found in the map.
+func (m *Map) Load(key interface{}) (value interface{}, ok bool) {
+ read, _ := m.read.Load().(readOnly)
+ e, ok := read.m[key]
+ if !ok && read.amended {
+ m.mu.Lock()
+ // Avoid reporting a spurious miss if m.dirty got promoted while we were
+ // blocked on m.mu. (If further loads of the same key will not miss, it's
+ // not worth copying the dirty map for this key.)
+ read, _ = m.read.Load().(readOnly)
+ e, ok = read.m[key]
+ if !ok && read.amended {
+ e, ok = m.dirty[key]
+ // Regardless of whether the entry was present, record a miss: this key
+ // will take the slow path until the dirty map is promoted to the read
+ // map.
+ m.missLocked()
+ }
+ m.mu.Unlock()
+ }
+ if !ok {
+ return nil, false
+ }
+ return e.load()
+}
+
+func (e *entry) load() (value interface{}, ok bool) {
+ p := atomic.LoadPointer(&e.p)
+ if p == nil || p == expunged {
+ return nil, false
+ }
+ return *(*interface{})(p), true
+}
+
+// Store sets the value for a key.
+func (m *Map) Store(key, value interface{}) {
+ read, _ := m.read.Load().(readOnly)
+ if e, ok := read.m[key]; ok && e.tryStore(&value) {
+ return
+ }
+
+ m.mu.Lock()
+ read, _ = m.read.Load().(readOnly)
+ if e, ok := read.m[key]; ok {
+ if e.unexpungeLocked() {
+ // The entry was previously expunged, which implies that there is a
+ // non-nil dirty map and this entry is not in it.
+ m.dirty[key] = e
+ }
+ e.storeLocked(&value)
+ } else if e, ok := m.dirty[key]; ok {
+ e.storeLocked(&value)
+ } else {
+ if !read.amended {
+ // We're adding the first new key to the dirty map.
+ // Make sure it is allocated and mark the read-only map as incomplete.
+ m.dirtyLocked()
+ m.read.Store(readOnly{m: read.m, amended: true})
+ }
+ m.dirty[key] = newEntry(value)
+ }
+ m.mu.Unlock()
+}
+
+// tryStore stores a value if the entry has not been expunged.
+//
+// If the entry is expunged, tryStore returns false and leaves the entry
+// unchanged.
+func (e *entry) tryStore(i *interface{}) bool {
+ p := atomic.LoadPointer(&e.p)
+ if p == expunged {
+ return false
+ }
+ for {
+ if atomic.CompareAndSwapPointer(&e.p, p, unsafe.Pointer(i)) {
+ return true
+ }
+ p = atomic.LoadPointer(&e.p)
+ if p == expunged {
+ return false
+ }
+ }
+}
+
+// unexpungeLocked ensures that the entry is not marked as expunged.
+//
+// If the entry was previously expunged, it must be added to the dirty map
+// before m.mu is unlocked.
+func (e *entry) unexpungeLocked() (wasExpunged bool) {
+ return atomic.CompareAndSwapPointer(&e.p, expunged, nil)
+}
+
+// storeLocked unconditionally stores a value to the entry.
+//
+// The entry must be known not to be expunged.
+func (e *entry) storeLocked(i *interface{}) {
+ atomic.StorePointer(&e.p, unsafe.Pointer(i))
+}
+
+// LoadOrStore returns the existing value for the key if present.
+// Otherwise, it stores and returns the given value.
+// The loaded result is true if the value was loaded, false if stored.
+func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) {
+ // Avoid locking if it's a clean hit.
+ read, _ := m.read.Load().(readOnly)
+ if e, ok := read.m[key]; ok {
+ actual, loaded, ok := e.tryLoadOrStore(value)
+ if ok {
+ return actual, loaded
+ }
+ }
+
+ m.mu.Lock()
+ read, _ = m.read.Load().(readOnly)
+ if e, ok := read.m[key]; ok {
+ if e.unexpungeLocked() {
+ m.dirty[key] = e
+ }
+ actual, loaded, _ = e.tryLoadOrStore(value)
+ } else if e, ok := m.dirty[key]; ok {
+ actual, loaded, _ = e.tryLoadOrStore(value)
+ m.missLocked()
+ } else {
+ if !read.amended {
+ // We're adding the first new key to the dirty map.
+ // Make sure it is allocated and mark the read-only map as incomplete.
+ m.dirtyLocked()
+ m.read.Store(readOnly{m: read.m, amended: true})
+ }
+ m.dirty[key] = newEntry(value)
+ actual, loaded = value, false
+ }
+ m.mu.Unlock()
+
+ return actual, loaded
+}
+
+// tryLoadOrStore atomically loads or stores a value if the entry is not
+// expunged.
+//
+// If the entry is expunged, tryLoadOrStore leaves the entry unchanged and
+// returns with ok==false.
+func (e *entry) tryLoadOrStore(i interface{}) (actual interface{}, loaded, ok bool) {
+ p := atomic.LoadPointer(&e.p)
+ if p == expunged {
+ return nil, false, false
+ }
+ if p != nil {
+ return *(*interface{})(p), true, true
+ }
+
+ // Copy the interface after the first load to make this method more amenable
+ // to escape analysis: if we hit the "load" path or the entry is expunged, we
+ // shouldn't bother heap-allocating.
+ ic := i
+ for {
+ if atomic.CompareAndSwapPointer(&e.p, nil, unsafe.Pointer(&ic)) {
+ return i, false, true
+ }
+ p = atomic.LoadPointer(&e.p)
+ if p == expunged {
+ return nil, false, false
+ }
+ if p != nil {
+ return *(*interface{})(p), true, true
+ }
+ }
+}
+
+// Delete deletes the value for a key.
+func (m *Map) Delete(key interface{}) {
+ read, _ := m.read.Load().(readOnly)
+ e, ok := read.m[key]
+ if !ok && read.amended {
+ m.mu.Lock()
+ read, _ = m.read.Load().(readOnly)
+ e, ok = read.m[key]
+ if !ok && read.amended {
+ delete(m.dirty, key)
+ }
+ m.mu.Unlock()
+ }
+ if ok {
+ e.delete()
+ }
+}
+
+func (e *entry) delete() (hadValue bool) {
+ for {
+ p := atomic.LoadPointer(&e.p)
+ if p == nil || p == expunged {
+ return false
+ }
+ if atomic.CompareAndSwapPointer(&e.p, p, nil) {
+ return true
+ }
+ }
+}
+
+// Range calls f sequentially for each key and value present in the map.
+// If f returns false, range stops the iteration.
+//
+// Range does not necessarily correspond to any consistent snapshot of the Map's
+// contents: no key will be visited more than once, but if the value for any key
+// is stored or deleted concurrently, Range may reflect any mapping for that key
+// from any point during the Range call.
+//
+// Range may be O(N) with the number of elements in the map even if f returns
+// false after a constant number of calls.
+func (m *Map) Range(f func(key, value interface{}) bool) {
+ // We need to be able to iterate over all of the keys that were already
+ // present at the start of the call to Range.
+ // If read.amended is false, then read.m satisfies that property without
+ // requiring us to hold m.mu for a long time.
+ read, _ := m.read.Load().(readOnly)
+ if read.amended {
+ // m.dirty contains keys not in read.m. Fortunately, Range is already O(N)
+ // (assuming the caller does not break out early), so a call to Range
+ // amortizes an entire copy of the map: we can promote the dirty copy
+ // immediately!
+ m.mu.Lock()
+ read, _ = m.read.Load().(readOnly)
+ if read.amended {
+ read = readOnly{m: m.dirty}
+ m.read.Store(read)
+ m.dirty = nil
+ m.misses = 0
+ }
+ m.mu.Unlock()
+ }
+
+ for k, e := range read.m {
+ v, ok := e.load()
+ if !ok {
+ continue
+ }
+ if !f(k, v) {
+ break
+ }
+ }
+}
+
+func (m *Map) missLocked() {
+ m.misses++
+ if m.misses < len(m.dirty) {
+ return
+ }
+ m.read.Store(readOnly{m: m.dirty})
+ m.dirty = nil
+ m.misses = 0
+}
+
+func (m *Map) dirtyLocked() {
+ if m.dirty != nil {
+ return
+ }
+
+ read, _ := m.read.Load().(readOnly)
+ m.dirty = make(map[interface{}]*entry, len(read.m))
+ for k, e := range read.m {
+ if !e.tryExpungeLocked() {
+ m.dirty[k] = e
+ }
+ }
+}
+
+func (e *entry) tryExpungeLocked() (isExpunged bool) {
+ p := atomic.LoadPointer(&e.p)
+ for p == nil {
+ if atomic.CompareAndSwapPointer(&e.p, nil, expunged) {
+ return true
+ }
+ p = atomic.LoadPointer(&e.p)
+ }
+ return p == expunged
+}
diff --git a/vendor/golang.org/x/sys/LICENSE b/vendor/golang.org/x/sys/LICENSE
new file mode 100644
index 0000000..6a66aea
--- /dev/null
+++ b/vendor/golang.org/x/sys/LICENSE
@@ -0,0 +1,27 @@
+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/sys/PATENTS b/vendor/golang.org/x/sys/PATENTS
new file mode 100644
index 0000000..7330990
--- /dev/null
+++ b/vendor/golang.org/x/sys/PATENTS
@@ -0,0 +1,22 @@
+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/sys/README b/vendor/golang.org/x/sys/README
new file mode 100644
index 0000000..bd422b4
--- /dev/null
+++ b/vendor/golang.org/x/sys/README
@@ -0,0 +1,3 @@
+This repository holds supplemental Go packages for low-level interactions with the operating system.
+
+To submit changes to this repository, see http://golang.org/doc/contribute.html.
diff --git a/vendor/golang.org/x/sys/unix/README.md b/vendor/golang.org/x/sys/unix/README.md
new file mode 100644
index 0000000..bc6f603
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/README.md
@@ -0,0 +1,173 @@
+# Building `sys/unix`
+
+The sys/unix package provides access to the raw system call interface of the
+underlying operating system. See: https://godoc.org/golang.org/x/sys/unix
+
+Porting Go to a new architecture/OS combination or adding syscalls, types, or
+constants to an existing architecture/OS pair requires some manual effort;
+however, there are tools that automate much of the process.
+
+## Build Systems
+
+There are currently two ways we generate the necessary files. We are currently
+migrating the build system to use containers so the builds are reproducible.
+This is being done on an OS-by-OS basis. Please update this documentation as
+components of the build system change.
+
+### Old Build System (currently for `GOOS != "Linux" || GOARCH == "sparc64"`)
+
+The old build system generates the Go files based on the C header files
+present on your system. This means that files
+for a given GOOS/GOARCH pair must be generated on a system with that OS and
+architecture. This also means that the generated code can differ from system
+to system, based on differences in the header files.
+
+To avoid this, if you are using the old build system, only generate the Go
+files on an installation with unmodified header files. It is also important to
+keep track of which version of the OS the files were generated from (ex.
+Darwin 14 vs Darwin 15). This makes it easier to track the progress of changes
+and have each OS upgrade correspond to a single change.
+
+To build the files for your current OS and architecture, make sure GOOS and
+GOARCH are set correctly and run `mkall.sh`. This will generate the files for
+your specific system. Running `mkall.sh -n` shows the commands that will be run.
+
+Requirements: bash, perl, go
+
+### New Build System (currently for `GOOS == "Linux" && GOARCH != "sparc64"`)
+
+The new build system uses a Docker container to generate the go files directly
+from source checkouts of the kernel and various system libraries. This means
+that on any platform that supports Docker, all the files using the new build
+system can be generated at once, and generated files will not change based on
+what the person running the scripts has installed on their computer.
+
+The OS specific files for the new build system are located in the `${GOOS}`
+directory, and the build is coordinated by the `${GOOS}/mkall.go` program. When
+the kernel or system library updates, modify the Dockerfile at
+`${GOOS}/Dockerfile` to checkout the new release of the source.
+
+To build all the files under the new build system, you must be on an amd64/Linux
+system and have your GOOS and GOARCH set accordingly. Running `mkall.sh` will
+then generate all of the files for all of the GOOS/GOARCH pairs in the new build
+system. Running `mkall.sh -n` shows the commands that will be run.
+
+Requirements: bash, perl, go, docker
+
+## Component files
+
+This section describes the various files used in the code generation process.
+It also contains instructions on how to modify these files to add a new
+architecture/OS or to add additional syscalls, types, or constants. Note that
+if you are using the new build system, the scripts cannot be called normally.
+They must be called from within the docker container.
+
+### asm files
+
+The hand-written assembly file at `asm_${GOOS}_${GOARCH}.s` implements system
+call dispatch. There are three entry points:
+```
+ func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)
+ func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr)
+ func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)
+```
+The first and second are the standard ones; they differ only in how many
+arguments can be passed to the kernel. The third is for low-level use by the
+ForkExec wrapper. Unlike the first two, it does not call into the scheduler to
+let it know that a system call is running.
+
+When porting Go to an new architecture/OS, this file must be implemented for
+each GOOS/GOARCH pair.
+
+### mksysnum
+
+Mksysnum is a script located at `${GOOS}/mksysnum.pl` (or `mksysnum_${GOOS}.pl`
+for the old system). This script takes in a list of header files containing the
+syscall number declarations and parses them to produce the corresponding list of
+Go numeric constants. See `zsysnum_${GOOS}_${GOARCH}.go` for the generated
+constants.
+
+Adding new syscall numbers is mostly done by running the build on a sufficiently
+new installation of the target OS (or updating the source checkouts for the
+new build system). However, depending on the OS, you make need to update the
+parsing in mksysnum.
+
+### mksyscall.pl
+
+The `syscall.go`, `syscall_${GOOS}.go`, `syscall_${GOOS}_${GOARCH}.go` are
+hand-written Go files which implement system calls (for unix, the specific OS,
+or the specific OS/Architecture pair respectively) that need special handling
+and list `//sys` comments giving prototypes for ones that can be generated.
+
+The mksyscall.pl script takes the `//sys` and `//sysnb` comments and converts
+them into syscalls. This requires the name of the prototype in the comment to
+match a syscall number in the `zsysnum_${GOOS}_${GOARCH}.go` file. The function
+prototype can be exported (capitalized) or not.
+
+Adding a new syscall often just requires adding a new `//sys` function prototype
+with the desired arguments and a capitalized name so it is exported. However, if
+you want the interface to the syscall to be different, often one will make an
+unexported `//sys` prototype, an then write a custom wrapper in
+`syscall_${GOOS}.go`.
+
+### types files
+
+For each OS, there is a hand-written Go file at `${GOOS}/types.go` (or
+`types_${GOOS}.go` on the old system). This file includes standard C headers and
+creates Go type aliases to the corresponding C types. The file is then fed
+through godef to get the Go compatible definitions. Finally, the generated code
+is fed though mkpost.go to format the code correctly and remove any hidden or
+private identifiers. This cleaned-up code is written to
+`ztypes_${GOOS}_${GOARCH}.go`.
+
+The hardest part about preparing this file is figuring out which headers to
+include and which symbols need to be `#define`d to get the actual data
+structures that pass through to the kernel system calls. Some C libraries
+preset alternate versions for binary compatibility and translate them on the
+way in and out of system calls, but there is almost always a `#define` that can
+get the real ones.
+See `types_darwin.go` and `linux/types.go` for examples.
+
+To add a new type, add in the necessary include statement at the top of the
+file (if it is not already there) and add in a type alias line. Note that if
+your type is significantly different on different architectures, you may need
+some `#if/#elif` macros in your include statements.
+
+### mkerrors.sh
+
+This script is used to generate the system's various constants. This doesn't
+just include the error numbers and error strings, but also the signal numbers
+an a wide variety of miscellaneous constants. The constants come from the list
+of include files in the `includes_${uname}` variable. A regex then picks out
+the desired `#define` statements, and generates the corresponding Go constants.
+The error numbers and strings are generated from `#include <errno.h>`, and the
+signal numbers and strings are generated from `#include <signal.h>`. All of
+these constants are written to `zerrors_${GOOS}_${GOARCH}.go` via a C program,
+`_errors.c`, which prints out all the constants.
+
+To add a constant, add the header that includes it to the appropriate variable.
+Then, edit the regex (if necessary) to match the desired constant. Avoid making
+the regex too broad to avoid matching unintended constants.
+
+
+## Generated files
+
+### `zerror_${GOOS}_${GOARCH}.go`
+
+A file containing all of the system's generated error numbers, error strings,
+signal numbers, and constants. Generated by `mkerrors.sh` (see above).
+
+### `zsyscall_${GOOS}_${GOARCH}.go`
+
+A file containing all the generated syscalls for a specific GOOS and GOARCH.
+Generated by `mksyscall.pl` (see above).
+
+### `zsysnum_${GOOS}_${GOARCH}.go`
+
+A list of numeric constants for all the syscall number of the specific GOOS
+and GOARCH. Generated by mksysnum (see above).
+
+### `ztypes_${GOOS}_${GOARCH}.go`
+
+A file containing Go types for passing into (or returning from) syscalls.
+Generated by godefs and the types file (see above).
diff --git a/vendor/golang.org/x/sys/unix/asm_darwin_386.s b/vendor/golang.org/x/sys/unix/asm_darwin_386.s
new file mode 100644
index 0000000..8a72783
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_darwin_386.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for 386, Darwin
+//
+
+// 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/asm_darwin_amd64.s b/vendor/golang.org/x/sys/unix/asm_darwin_amd64.s
new file mode 100644
index 0000000..6321421
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_darwin_amd64.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for AMD64, Darwin
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-56
+ JMP syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-80
+ JMP syscall·Syscall6(SB)
+
+TEXT ·Syscall9(SB),NOSPLIT,$0-104
+ JMP syscall·Syscall9(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-56
+ JMP syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
+ JMP syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_darwin_arm.s b/vendor/golang.org/x/sys/unix/asm_darwin_arm.s
new file mode 100644
index 0000000..333242d
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_darwin_arm.s
@@ -0,0 +1,30 @@
+// Copyright 2015 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 !gccgo
+// +build arm,darwin
+
+#include "textflag.h"
+
+//
+// System call support for ARM, Darwin
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-28
+ B syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-40
+ B syscall·Syscall6(SB)
+
+TEXT ·Syscall9(SB),NOSPLIT,$0-52
+ B syscall·Syscall9(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-28
+ B syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
+ B syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_darwin_arm64.s b/vendor/golang.org/x/sys/unix/asm_darwin_arm64.s
new file mode 100644
index 0000000..97e0174
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_darwin_arm64.s
@@ -0,0 +1,30 @@
+// Copyright 2015 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 !gccgo
+// +build arm64,darwin
+
+#include "textflag.h"
+
+//
+// System call support for AMD64, Darwin
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-56
+ B syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-80
+ B syscall·Syscall6(SB)
+
+TEXT ·Syscall9(SB),NOSPLIT,$0-104
+ B syscall·Syscall9(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-56
+ B syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
+ B syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s b/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s
new file mode 100644
index 0000000..d5ed672
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for AMD64, DragonFly
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-64
+ JMP syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-88
+ JMP syscall·Syscall6(SB)
+
+TEXT ·Syscall9(SB),NOSPLIT,$0-112
+ JMP syscall·Syscall9(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-64
+ JMP syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-88
+ JMP syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_freebsd_386.s b/vendor/golang.org/x/sys/unix/asm_freebsd_386.s
new file mode 100644
index 0000000..c9a0a26
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_freebsd_386.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for 386, FreeBSD
+//
+
+// 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/asm_freebsd_amd64.s b/vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s
new file mode 100644
index 0000000..3517247
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for AMD64, FreeBSD
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-56
+ JMP syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-80
+ JMP syscall·Syscall6(SB)
+
+TEXT ·Syscall9(SB),NOSPLIT,$0-104
+ JMP syscall·Syscall9(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-56
+ JMP syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
+ JMP syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_freebsd_arm.s b/vendor/golang.org/x/sys/unix/asm_freebsd_arm.s
new file mode 100644
index 0000000..9227c87
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_freebsd_arm.s
@@ -0,0 +1,29 @@
+// 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for ARM, FreeBSD
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-28
+ B syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-40
+ B syscall·Syscall6(SB)
+
+TEXT ·Syscall9(SB),NOSPLIT,$0-52
+ B syscall·Syscall9(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-28
+ B syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
+ B syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_linux_386.s b/vendor/golang.org/x/sys/unix/asm_linux_386.s
new file mode 100644
index 0000000..4db2909
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_linux_386.s
@@ -0,0 +1,35 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System calls for 386, 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 ·RawSyscall(SB),NOSPLIT,$0-28
+ JMP syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
+ JMP syscall·RawSyscall6(SB)
+
+TEXT ·socketcall(SB),NOSPLIT,$0-36
+ JMP syscall·socketcall(SB)
+
+TEXT ·rawsocketcall(SB),NOSPLIT,$0-36
+ JMP syscall·rawsocketcall(SB)
+
+TEXT ·seek(SB),NOSPLIT,$0-28
+ JMP syscall·seek(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_linux_amd64.s b/vendor/golang.org/x/sys/unix/asm_linux_amd64.s
new file mode 100644
index 0000000..44e25c6
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_linux_amd64.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System calls for AMD64, Linux
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-56
+ JMP syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-80
+ JMP syscall·Syscall6(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-56
+ JMP syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
+ JMP syscall·RawSyscall6(SB)
+
+TEXT ·gettimeofday(SB),NOSPLIT,$0-16
+ JMP syscall·gettimeofday(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_linux_arm.s b/vendor/golang.org/x/sys/unix/asm_linux_arm.s
new file mode 100644
index 0000000..cf0b574
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_linux_arm.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System calls for arm, Linux
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-28
+ B syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-40
+ B syscall·Syscall6(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-28
+ B syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
+ B syscall·RawSyscall6(SB)
+
+TEXT ·seek(SB),NOSPLIT,$0-32
+ B syscall·seek(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_linux_arm64.s b/vendor/golang.org/x/sys/unix/asm_linux_arm64.s
new file mode 100644
index 0000000..4be9bfe
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_linux_arm64.s
@@ -0,0 +1,24 @@
+// Copyright 2015 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 arm64
+// +build !gccgo
+
+#include "textflag.h"
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-56
+ B syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-80
+ B syscall·Syscall6(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-56
+ B syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
+ B syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s b/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s
new file mode 100644
index 0000000..724e580
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s
@@ -0,0 +1,28 @@
+// Copyright 2015 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 mips64 mips64le
+// +build !gccgo
+
+#include "textflag.h"
+
+//
+// System calls for mips64, Linux
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-56
+ JMP syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-80
+ JMP syscall·Syscall6(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-56
+ JMP syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
+ JMP syscall·RawSyscall6(SB)
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/asm_linux_ppc64x.s b/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s
new file mode 100644
index 0000000..8d231fe
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s
@@ -0,0 +1,28 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build linux
+// +build ppc64 ppc64le
+// +build !gccgo
+
+#include "textflag.h"
+
+//
+// System calls for ppc64, Linux
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-56
+ BR syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-80
+ BR syscall·Syscall6(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-56
+ BR syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
+ BR syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_linux_s390x.s b/vendor/golang.org/x/sys/unix/asm_linux_s390x.s
new file mode 100644
index 0000000..1188985
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_linux_s390x.s
@@ -0,0 +1,28 @@
+// 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 s390x
+// +build linux
+// +build !gccgo
+
+#include "textflag.h"
+
+//
+// System calls for s390x, Linux
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-56
+ BR syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-80
+ BR syscall·Syscall6(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-56
+ BR syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
+ BR syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_netbsd_386.s b/vendor/golang.org/x/sys/unix/asm_netbsd_386.s
new file mode 100644
index 0000000..48bdcd7
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_netbsd_386.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for 386, NetBSD
+//
+
+// 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/asm_netbsd_amd64.s b/vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s
new file mode 100644
index 0000000..2ede05c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for AMD64, NetBSD
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-56
+ JMP syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-80
+ JMP syscall·Syscall6(SB)
+
+TEXT ·Syscall9(SB),NOSPLIT,$0-104
+ JMP syscall·Syscall9(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-56
+ JMP syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
+ JMP syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_netbsd_arm.s b/vendor/golang.org/x/sys/unix/asm_netbsd_arm.s
new file mode 100644
index 0000000..e892857
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_netbsd_arm.s
@@ -0,0 +1,29 @@
+// 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.
+
+// +build !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for ARM, NetBSD
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-28
+ B syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-40
+ B syscall·Syscall6(SB)
+
+TEXT ·Syscall9(SB),NOSPLIT,$0-52
+ B syscall·Syscall9(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-28
+ B syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
+ B syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_openbsd_386.s b/vendor/golang.org/x/sys/unix/asm_openbsd_386.s
new file mode 100644
index 0000000..00576f3
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_openbsd_386.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for 386, OpenBSD
+//
+
+// 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/asm_openbsd_amd64.s b/vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s
new file mode 100644
index 0000000..790ef77
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s
@@ -0,0 +1,29 @@
+// Copyright 2009 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for AMD64, OpenBSD
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-56
+ JMP syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-80
+ JMP syscall·Syscall6(SB)
+
+TEXT ·Syscall9(SB),NOSPLIT,$0-104
+ JMP syscall·Syscall9(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-56
+ JMP syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
+ JMP syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_openbsd_arm.s b/vendor/golang.org/x/sys/unix/asm_openbsd_arm.s
new file mode 100644
index 0000000..469bfa1
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_openbsd_arm.s
@@ -0,0 +1,29 @@
+// Copyright 2017 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 !gccgo
+
+#include "textflag.h"
+
+//
+// System call support for ARM, OpenBSD
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT ·Syscall(SB),NOSPLIT,$0-28
+ B syscall·Syscall(SB)
+
+TEXT ·Syscall6(SB),NOSPLIT,$0-40
+ B syscall·Syscall6(SB)
+
+TEXT ·Syscall9(SB),NOSPLIT,$0-52
+ B syscall·Syscall9(SB)
+
+TEXT ·RawSyscall(SB),NOSPLIT,$0-28
+ B syscall·RawSyscall(SB)
+
+TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
+ B syscall·RawSyscall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s b/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s
new file mode 100644
index 0000000..ded8260
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s
@@ -0,0 +1,17 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build !gccgo
+
+#include "textflag.h"
+
+//
+// System calls for amd64, Solaris are implemented in runtime/syscall_solaris.go
+//
+
+TEXT ·sysvicall6(SB),NOSPLIT,$0-88
+ JMP syscall·sysvicall6(SB)
+
+TEXT ·rawSysvicall6(SB),NOSPLIT,$0-88
+ JMP syscall·rawSysvicall6(SB)
diff --git a/vendor/golang.org/x/sys/unix/bluetooth_linux.go b/vendor/golang.org/x/sys/unix/bluetooth_linux.go
new file mode 100644
index 0000000..6e32296
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/bluetooth_linux.go
@@ -0,0 +1,35 @@
+// 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.
+
+// Bluetooth sockets and messages
+
+package unix
+
+// Bluetooth Protocols
+const (
+ BTPROTO_L2CAP = 0
+ BTPROTO_HCI = 1
+ BTPROTO_SCO = 2
+ BTPROTO_RFCOMM = 3
+ BTPROTO_BNEP = 4
+ BTPROTO_CMTP = 5
+ BTPROTO_HIDP = 6
+ BTPROTO_AVDTP = 7
+)
+
+const (
+ HCI_CHANNEL_RAW = 0
+ HCI_CHANNEL_USER = 1
+ HCI_CHANNEL_MONITOR = 2
+ HCI_CHANNEL_CONTROL = 3
+)
+
+// Socketoption Level
+const (
+ SOL_BLUETOOTH = 0x112
+ SOL_HCI = 0x0
+ SOL_L2CAP = 0x6
+ SOL_RFCOMM = 0x12
+ SOL_SCO = 0x11
+)
diff --git a/vendor/golang.org/x/sys/unix/cap_freebsd.go b/vendor/golang.org/x/sys/unix/cap_freebsd.go
new file mode 100644
index 0000000..83b6bce
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/cap_freebsd.go
@@ -0,0 +1,195 @@
+// Copyright 2017 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 freebsd
+
+package unix
+
+import (
+ errorspkg "errors"
+ "fmt"
+)
+
+// Go implementation of C mostly found in /usr/src/sys/kern/subr_capability.c
+
+const (
+ // This is the version of CapRights this package understands. See C implementation for parallels.
+ capRightsGoVersion = CAP_RIGHTS_VERSION_00
+ capArSizeMin = CAP_RIGHTS_VERSION_00 + 2
+ capArSizeMax = capRightsGoVersion + 2
+)
+
+var (
+ bit2idx = []int{
+ -1, 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1,
+ 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ }
+)
+
+func capidxbit(right uint64) int {
+ return int((right >> 57) & 0x1f)
+}
+
+func rightToIndex(right uint64) (int, error) {
+ idx := capidxbit(right)
+ if idx < 0 || idx >= len(bit2idx) {
+ return -2, fmt.Errorf("index for right 0x%x out of range", right)
+ }
+ return bit2idx[idx], nil
+}
+
+func caprver(right uint64) int {
+ return int(right >> 62)
+}
+
+func capver(rights *CapRights) int {
+ return caprver(rights.Rights[0])
+}
+
+func caparsize(rights *CapRights) int {
+ return capver(rights) + 2
+}
+
+// CapRightsSet sets the permissions in setrights in rights.
+func CapRightsSet(rights *CapRights, setrights []uint64) error {
+ // This is essentially a copy of cap_rights_vset()
+ if capver(rights) != CAP_RIGHTS_VERSION_00 {
+ return fmt.Errorf("bad rights version %d", capver(rights))
+ }
+
+ n := caparsize(rights)
+ if n < capArSizeMin || n > capArSizeMax {
+ return errorspkg.New("bad rights size")
+ }
+
+ for _, right := range setrights {
+ if caprver(right) != CAP_RIGHTS_VERSION_00 {
+ return errorspkg.New("bad right version")
+ }
+ i, err := rightToIndex(right)
+ if err != nil {
+ return err
+ }
+ if i >= n {
+ return errorspkg.New("index overflow")
+ }
+ if capidxbit(rights.Rights[i]) != capidxbit(right) {
+ return errorspkg.New("index mismatch")
+ }
+ rights.Rights[i] |= right
+ if capidxbit(rights.Rights[i]) != capidxbit(right) {
+ return errorspkg.New("index mismatch (after assign)")
+ }
+ }
+
+ return nil
+}
+
+// CapRightsClear clears the permissions in clearrights from rights.
+func CapRightsClear(rights *CapRights, clearrights []uint64) error {
+ // This is essentially a copy of cap_rights_vclear()
+ if capver(rights) != CAP_RIGHTS_VERSION_00 {
+ return fmt.Errorf("bad rights version %d", capver(rights))
+ }
+
+ n := caparsize(rights)
+ if n < capArSizeMin || n > capArSizeMax {
+ return errorspkg.New("bad rights size")
+ }
+
+ for _, right := range clearrights {
+ if caprver(right) != CAP_RIGHTS_VERSION_00 {
+ return errorspkg.New("bad right version")
+ }
+ i, err := rightToIndex(right)
+ if err != nil {
+ return err
+ }
+ if i >= n {
+ return errorspkg.New("index overflow")
+ }
+ if capidxbit(rights.Rights[i]) != capidxbit(right) {
+ return errorspkg.New("index mismatch")
+ }
+ rights.Rights[i] &= ^(right & 0x01FFFFFFFFFFFFFF)
+ if capidxbit(rights.Rights[i]) != capidxbit(right) {
+ return errorspkg.New("index mismatch (after assign)")
+ }
+ }
+
+ return nil
+}
+
+// CapRightsIsSet checks whether all the permissions in setrights are present in rights.
+func CapRightsIsSet(rights *CapRights, setrights []uint64) (bool, error) {
+ // This is essentially a copy of cap_rights_is_vset()
+ if capver(rights) != CAP_RIGHTS_VERSION_00 {
+ return false, fmt.Errorf("bad rights version %d", capver(rights))
+ }
+
+ n := caparsize(rights)
+ if n < capArSizeMin || n > capArSizeMax {
+ return false, errorspkg.New("bad rights size")
+ }
+
+ for _, right := range setrights {
+ if caprver(right) != CAP_RIGHTS_VERSION_00 {
+ return false, errorspkg.New("bad right version")
+ }
+ i, err := rightToIndex(right)
+ if err != nil {
+ return false, err
+ }
+ if i >= n {
+ return false, errorspkg.New("index overflow")
+ }
+ if capidxbit(rights.Rights[i]) != capidxbit(right) {
+ return false, errorspkg.New("index mismatch")
+ }
+ if (rights.Rights[i] & right) != right {
+ return false, nil
+ }
+ }
+
+ return true, nil
+}
+
+func capright(idx uint64, bit uint64) uint64 {
+ return ((1 << (57 + idx)) | bit)
+}
+
+// CapRightsInit returns a pointer to an initialised CapRights structure filled with rights.
+// See man cap_rights_init(3) and rights(4).
+func CapRightsInit(rights []uint64) (*CapRights, error) {
+ var r CapRights
+ r.Rights[0] = (capRightsGoVersion << 62) | capright(0, 0)
+ r.Rights[1] = capright(1, 0)
+
+ err := CapRightsSet(&r, rights)
+ if err != nil {
+ return nil, err
+ }
+ return &r, nil
+}
+
+// CapRightsLimit reduces the operations permitted on fd to at most those contained in rights.
+// The capability rights on fd can never be increased by CapRightsLimit.
+// See man cap_rights_limit(2) and rights(4).
+func CapRightsLimit(fd uintptr, rights *CapRights) error {
+ return capRightsLimit(int(fd), rights)
+}
+
+// CapRightsGet returns a CapRights structure containing the operations permitted on fd.
+// See man cap_rights_get(3) and rights(4).
+func CapRightsGet(fd uintptr) (*CapRights, error) {
+ r, err := CapRightsInit(nil)
+ if err != nil {
+ return nil, err
+ }
+ err = capRightsGet(capRightsGoVersion, int(fd), r)
+ if err != nil {
+ return nil, err
+ }
+ return r, nil
+}
diff --git a/vendor/golang.org/x/sys/unix/constants.go b/vendor/golang.org/x/sys/unix/constants.go
new file mode 100644
index 0000000..a96f0eb
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/constants.go
@@ -0,0 +1,13 @@
+// Copyright 2015 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
+
+package unix
+
+const (
+ R_OK = 0x4
+ W_OK = 0x2
+ X_OK = 0x1
+)
diff --git a/vendor/golang.org/x/sys/unix/dev_linux.go b/vendor/golang.org/x/sys/unix/dev_linux.go
new file mode 100644
index 0000000..c902c39
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/dev_linux.go
@@ -0,0 +1,42 @@
+// Copyright 2017 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.
+
+// Functions to access/create device major and minor numbers matching the
+// encoding used by the Linux kernel and glibc.
+//
+// The information below is extracted and adapted from bits/sysmacros.h in the
+// glibc sources:
+//
+// dev_t in glibc is 64-bit, with 32-bit major and minor numbers. glibc's
+// default encoding is MMMM Mmmm mmmM MMmm, where M is a hex digit of the major
+// number and m is a hex digit of the minor number. This is backward compatible
+// with legacy systems where dev_t is 16 bits wide, encoded as MMmm. It is also
+// backward compatible with the Linux kernel, which for some architectures uses
+// 32-bit dev_t, encoded as mmmM MMmm.
+
+package unix
+
+// Major returns the major component of a Linux device number.
+func Major(dev uint64) uint32 {
+ major := uint32((dev & 0x00000000000fff00) >> 8)
+ major |= uint32((dev & 0xfffff00000000000) >> 32)
+ return major
+}
+
+// Minor returns the minor component of a Linux device number.
+func Minor(dev uint64) uint32 {
+ minor := uint32((dev & 0x00000000000000ff) >> 0)
+ minor |= uint32((dev & 0x00000ffffff00000) >> 12)
+ return minor
+}
+
+// Mkdev returns a Linux device number generated from the given major and minor
+// components.
+func Mkdev(major, minor uint32) uint64 {
+ dev := uint64((major & 0x00000fff) << 8)
+ dev |= uint64((major & 0xfffff000) << 32)
+ dev |= uint64((minor & 0x000000ff) << 0)
+ dev |= uint64((minor & 0xffffff00) << 12)
+ return dev
+}
diff --git a/vendor/golang.org/x/sys/unix/dirent.go b/vendor/golang.org/x/sys/unix/dirent.go
new file mode 100644
index 0000000..bd47581
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/dirent.go
@@ -0,0 +1,102 @@
+// Copyright 2009 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 nacl netbsd openbsd solaris
+
+package unix
+
+import "unsafe"
+
+// readInt returns the size-bytes unsigned integer in native byte order at offset off.
+func readInt(b []byte, off, size uintptr) (u uint64, ok bool) {
+ if len(b) < int(off+size) {
+ return 0, false
+ }
+ if isBigEndian {
+ return readIntBE(b[off:], size), true
+ }
+ return readIntLE(b[off:], size), true
+}
+
+func readIntBE(b []byte, size uintptr) uint64 {
+ switch size {
+ case 1:
+ return uint64(b[0])
+ case 2:
+ _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808
+ return uint64(b[1]) | uint64(b[0])<<8
+ case 4:
+ _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
+ return uint64(b[3]) | uint64(b[2])<<8 | uint64(b[1])<<16 | uint64(b[0])<<24
+ case 8:
+ _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
+ return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |
+ uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56
+ default:
+ panic("syscall: readInt with unsupported size")
+ }
+}
+
+func readIntLE(b []byte, size uintptr) uint64 {
+ switch size {
+ case 1:
+ return uint64(b[0])
+ case 2:
+ _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808
+ return uint64(b[0]) | uint64(b[1])<<8
+ case 4:
+ _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
+ return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24
+ case 8:
+ _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
+ return uint64(b[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
+ default:
+ panic("syscall: readInt with unsupported size")
+ }
+}
+
+// ParseDirent parses up to max directory entries in buf,
+// appending the names to names. It returns the number of
+// bytes consumed from buf, the number of entries added
+// to names, and the new names slice.
+func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) {
+ origlen := len(buf)
+ count = 0
+ for max != 0 && len(buf) > 0 {
+ reclen, ok := direntReclen(buf)
+ if !ok || reclen > uint64(len(buf)) {
+ return origlen, count, names
+ }
+ rec := buf[:reclen]
+ buf = buf[reclen:]
+ ino, ok := direntIno(rec)
+ if !ok {
+ break
+ }
+ if ino == 0 { // File absent in directory.
+ continue
+ }
+ const namoff = uint64(unsafe.Offsetof(Dirent{}.Name))
+ namlen, ok := direntNamlen(rec)
+ if !ok || namoff+namlen > uint64(len(rec)) {
+ break
+ }
+ name := rec[namoff : namoff+namlen]
+ for i, c := range name {
+ if c == 0 {
+ name = name[:i]
+ break
+ }
+ }
+ // Check for useless names before allocating a string.
+ if string(name) == "." || string(name) == ".." {
+ continue
+ }
+ max--
+ count++
+ names = append(names, string(name))
+ }
+ return origlen - len(buf), count, names
+}
diff --git a/vendor/golang.org/x/sys/unix/endian_big.go b/vendor/golang.org/x/sys/unix/endian_big.go
new file mode 100644
index 0000000..5e92690
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/endian_big.go
@@ -0,0 +1,9 @@
+// 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 ppc64 s390x mips mips64
+
+package unix
+
+const isBigEndian = true
diff --git a/vendor/golang.org/x/sys/unix/endian_little.go b/vendor/golang.org/x/sys/unix/endian_little.go
new file mode 100644
index 0000000..085df2d
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/endian_little.go
@@ -0,0 +1,9 @@
+// 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 386 amd64 amd64p32 arm arm64 ppc64le mipsle mips64le
+
+package unix
+
+const isBigEndian = false
diff --git a/vendor/golang.org/x/sys/unix/env_unix.go b/vendor/golang.org/x/sys/unix/env_unix.go
new file mode 100644
index 0000000..45e281a
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/env_unix.go
@@ -0,0 +1,27 @@
+// 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.
+
+// +build darwin dragonfly freebsd linux netbsd openbsd solaris
+
+// Unix environment variables.
+
+package unix
+
+import "syscall"
+
+func Getenv(key string) (value string, found bool) {
+ return syscall.Getenv(key)
+}
+
+func Setenv(key, value string) error {
+ return syscall.Setenv(key, value)
+}
+
+func Clearenv() {
+ syscall.Clearenv()
+}
+
+func Environ() []string {
+ return syscall.Environ()
+}
diff --git a/vendor/golang.org/x/sys/unix/env_unset.go b/vendor/golang.org/x/sys/unix/env_unset.go
new file mode 100644
index 0000000..9222262
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/env_unset.go
@@ -0,0 +1,14 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build go1.4
+
+package unix
+
+import "syscall"
+
+func Unsetenv(key string) error {
+ // This was added in Go 1.4.
+ return syscall.Unsetenv(key)
+}
diff --git a/vendor/golang.org/x/sys/unix/errors_freebsd_386.go b/vendor/golang.org/x/sys/unix/errors_freebsd_386.go
new file mode 100644
index 0000000..c56bc8b
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/errors_freebsd_386.go
@@ -0,0 +1,227 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Constants that were deprecated or moved to enums in the FreeBSD headers. Keep
+// them here for backwards compatibility.
+
+package unix
+
+const (
+ IFF_SMART = 0x20
+ IFT_1822 = 0x2
+ IFT_A12MPPSWITCH = 0x82
+ IFT_AAL2 = 0xbb
+ IFT_AAL5 = 0x31
+ IFT_ADSL = 0x5e
+ IFT_AFLANE8023 = 0x3b
+ IFT_AFLANE8025 = 0x3c
+ IFT_ARAP = 0x58
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ASYNC = 0x54
+ IFT_ATM = 0x25
+ IFT_ATMDXI = 0x69
+ IFT_ATMFUNI = 0x6a
+ IFT_ATMIMA = 0x6b
+ IFT_ATMLOGICAL = 0x50
+ IFT_ATMRADIO = 0xbd
+ IFT_ATMSUBINTERFACE = 0x86
+ IFT_ATMVCIENDPT = 0xc2
+ IFT_ATMVIRTUAL = 0x95
+ IFT_BGPPOLICYACCOUNTING = 0xa2
+ IFT_BSC = 0x53
+ IFT_CCTEMUL = 0x3d
+ IFT_CEPT = 0x13
+ IFT_CES = 0x85
+ IFT_CHANNEL = 0x46
+ IFT_CNR = 0x55
+ IFT_COFFEE = 0x84
+ IFT_COMPOSITELINK = 0x9b
+ IFT_DCN = 0x8d
+ IFT_DIGITALPOWERLINE = 0x8a
+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
+ IFT_DLSW = 0x4a
+ IFT_DOCSCABLEDOWNSTREAM = 0x80
+ IFT_DOCSCABLEMACLAYER = 0x7f
+ IFT_DOCSCABLEUPSTREAM = 0x81
+ IFT_DS0 = 0x51
+ IFT_DS0BUNDLE = 0x52
+ IFT_DS1FDL = 0xaa
+ IFT_DS3 = 0x1e
+ IFT_DTM = 0x8c
+ IFT_DVBASILN = 0xac
+ IFT_DVBASIOUT = 0xad
+ IFT_DVBRCCDOWNSTREAM = 0x93
+ IFT_DVBRCCMACLAYER = 0x92
+ IFT_DVBRCCUPSTREAM = 0x94
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_EPLRS = 0x57
+ IFT_ESCON = 0x49
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0xf2
+ IFT_FAST = 0x7d
+ IFT_FASTETHER = 0x3e
+ IFT_FASTETHERFX = 0x45
+ IFT_FDDI = 0xf
+ IFT_FIBRECHANNEL = 0x38
+ IFT_FRAMERELAYINTERCONNECT = 0x3a
+ IFT_FRAMERELAYMPI = 0x5c
+ IFT_FRDLCIENDPT = 0xc1
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_FRF16MFRBUNDLE = 0xa3
+ IFT_FRFORWARD = 0x9e
+ IFT_G703AT2MB = 0x43
+ IFT_G703AT64K = 0x42
+ IFT_GIF = 0xf0
+ IFT_GIGABITETHERNET = 0x75
+ IFT_GR303IDT = 0xb2
+ IFT_GR303RDT = 0xb1
+ IFT_H323GATEKEEPER = 0xa4
+ IFT_H323PROXY = 0xa5
+ IFT_HDH1822 = 0x3
+ IFT_HDLC = 0x76
+ IFT_HDSL2 = 0xa8
+ IFT_HIPERLAN2 = 0xb7
+ IFT_HIPPI = 0x2f
+ IFT_HIPPIINTERFACE = 0x39
+ IFT_HOSTPAD = 0x5a
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IBM370PARCHAN = 0x48
+ IFT_IDSL = 0x9a
+ IFT_IEEE80211 = 0x47
+ IFT_IEEE80212 = 0x37
+ IFT_IEEE8023ADLAG = 0xa1
+ IFT_IFGSN = 0x91
+ IFT_IMT = 0xbe
+ IFT_INTERLEAVE = 0x7c
+ IFT_IP = 0x7e
+ IFT_IPFORWARD = 0x8e
+ IFT_IPOVERATM = 0x72
+ IFT_IPOVERCDLC = 0x6d
+ IFT_IPOVERCLAW = 0x6e
+ IFT_IPSWITCH = 0x4e
+ IFT_IPXIP = 0xf9
+ IFT_ISDN = 0x3f
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISDNS = 0x4b
+ IFT_ISDNU = 0x4c
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88025CRFPINT = 0x62
+ IFT_ISO88025DTR = 0x56
+ IFT_ISO88025FIBER = 0x73
+ IFT_ISO88026 = 0xa
+ IFT_ISUP = 0xb3
+ IFT_L3IPXVLAN = 0x89
+ IFT_LAPB = 0x10
+ IFT_LAPD = 0x4d
+ IFT_LAPF = 0x77
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MEDIAMAILOVERIP = 0x8b
+ IFT_MFSIGLINK = 0xa7
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_MPC = 0x71
+ IFT_MPLS = 0xa6
+ IFT_MPLSTUNNEL = 0x96
+ IFT_MSDSL = 0x8f
+ IFT_MVL = 0xbf
+ IFT_MYRINET = 0x63
+ IFT_NFAS = 0xaf
+ IFT_NSIP = 0x1b
+ IFT_OPTICALCHANNEL = 0xc3
+ IFT_OPTICALTRANSPORT = 0xc4
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PFLOG = 0xf6
+ IFT_PFSYNC = 0xf7
+ IFT_PLC = 0xae
+ IFT_POS = 0xab
+ IFT_PPPMULTILINKBUNDLE = 0x6c
+ IFT_PROPBWAP2MP = 0xb8
+ IFT_PROPCNLS = 0x59
+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
+ IFT_PROPMUX = 0x36
+ IFT_PROPWIRELESSP2P = 0x9d
+ IFT_PTPSERIAL = 0x16
+ IFT_PVC = 0xf1
+ IFT_QLLC = 0x44
+ IFT_RADIOMAC = 0xbc
+ IFT_RADSL = 0x5f
+ IFT_REACHDSL = 0xc0
+ IFT_RFC1483 = 0x9f
+ IFT_RS232 = 0x21
+ IFT_RSRB = 0x4f
+ IFT_SDLC = 0x11
+ IFT_SDSL = 0x60
+ IFT_SHDSL = 0xa9
+ IFT_SIP = 0x1f
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETOVERHEADCHANNEL = 0xb9
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_SRP = 0x97
+ IFT_SS7SIGLINK = 0x9c
+ IFT_STACKTOSTACK = 0x6f
+ IFT_STARLAN = 0xb
+ IFT_STF = 0xd7
+ IFT_T1 = 0x12
+ IFT_TDLC = 0x74
+ IFT_TERMPAD = 0x5b
+ IFT_TR008 = 0xb0
+ IFT_TRANSPHDLC = 0x7b
+ IFT_TUNNEL = 0x83
+ IFT_ULTRA = 0x1d
+ IFT_USB = 0xa0
+ IFT_V11 = 0x40
+ IFT_V35 = 0x2d
+ IFT_V36 = 0x41
+ IFT_V37 = 0x78
+ IFT_VDSL = 0x61
+ IFT_VIRTUALIPADDRESS = 0x70
+ IFT_VOICEEM = 0x64
+ IFT_VOICEENCAP = 0x67
+ IFT_VOICEFXO = 0x65
+ IFT_VOICEFXS = 0x66
+ IFT_VOICEOVERATM = 0x98
+ IFT_VOICEOVERFRAMERELAY = 0x99
+ IFT_VOICEOVERIP = 0x68
+ IFT_X213 = 0x5d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25HUNTGROUP = 0x7a
+ IFT_X25MLP = 0x79
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IPPROTO_MAXID = 0x34
+ IPV6_FAITH = 0x1d
+ IP_FAITH = 0x16
+ MAP_NORESERVE = 0x40
+ MAP_RENAME = 0x20
+ NET_RT_MAXID = 0x6
+ RTF_PRCLONING = 0x10000
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ SIOCADDRT = 0x8030720a
+ SIOCALIFADDR = 0x8118691b
+ SIOCDELRT = 0x8030720b
+ SIOCDLIFADDR = 0x8118691d
+ SIOCGLIFADDR = 0xc118691c
+ SIOCGLIFPHYADDR = 0xc118694b
+ SIOCSLIFPHYADDR = 0x8118694a
+)
diff --git a/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go
new file mode 100644
index 0000000..3e97711
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go
@@ -0,0 +1,227 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Constants that were deprecated or moved to enums in the FreeBSD headers. Keep
+// them here for backwards compatibility.
+
+package unix
+
+const (
+ IFF_SMART = 0x20
+ IFT_1822 = 0x2
+ IFT_A12MPPSWITCH = 0x82
+ IFT_AAL2 = 0xbb
+ IFT_AAL5 = 0x31
+ IFT_ADSL = 0x5e
+ IFT_AFLANE8023 = 0x3b
+ IFT_AFLANE8025 = 0x3c
+ IFT_ARAP = 0x58
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ASYNC = 0x54
+ IFT_ATM = 0x25
+ IFT_ATMDXI = 0x69
+ IFT_ATMFUNI = 0x6a
+ IFT_ATMIMA = 0x6b
+ IFT_ATMLOGICAL = 0x50
+ IFT_ATMRADIO = 0xbd
+ IFT_ATMSUBINTERFACE = 0x86
+ IFT_ATMVCIENDPT = 0xc2
+ IFT_ATMVIRTUAL = 0x95
+ IFT_BGPPOLICYACCOUNTING = 0xa2
+ IFT_BSC = 0x53
+ IFT_CCTEMUL = 0x3d
+ IFT_CEPT = 0x13
+ IFT_CES = 0x85
+ IFT_CHANNEL = 0x46
+ IFT_CNR = 0x55
+ IFT_COFFEE = 0x84
+ IFT_COMPOSITELINK = 0x9b
+ IFT_DCN = 0x8d
+ IFT_DIGITALPOWERLINE = 0x8a
+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
+ IFT_DLSW = 0x4a
+ IFT_DOCSCABLEDOWNSTREAM = 0x80
+ IFT_DOCSCABLEMACLAYER = 0x7f
+ IFT_DOCSCABLEUPSTREAM = 0x81
+ IFT_DS0 = 0x51
+ IFT_DS0BUNDLE = 0x52
+ IFT_DS1FDL = 0xaa
+ IFT_DS3 = 0x1e
+ IFT_DTM = 0x8c
+ IFT_DVBASILN = 0xac
+ IFT_DVBASIOUT = 0xad
+ IFT_DVBRCCDOWNSTREAM = 0x93
+ IFT_DVBRCCMACLAYER = 0x92
+ IFT_DVBRCCUPSTREAM = 0x94
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_EPLRS = 0x57
+ IFT_ESCON = 0x49
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0xf2
+ IFT_FAST = 0x7d
+ IFT_FASTETHER = 0x3e
+ IFT_FASTETHERFX = 0x45
+ IFT_FDDI = 0xf
+ IFT_FIBRECHANNEL = 0x38
+ IFT_FRAMERELAYINTERCONNECT = 0x3a
+ IFT_FRAMERELAYMPI = 0x5c
+ IFT_FRDLCIENDPT = 0xc1
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_FRF16MFRBUNDLE = 0xa3
+ IFT_FRFORWARD = 0x9e
+ IFT_G703AT2MB = 0x43
+ IFT_G703AT64K = 0x42
+ IFT_GIF = 0xf0
+ IFT_GIGABITETHERNET = 0x75
+ IFT_GR303IDT = 0xb2
+ IFT_GR303RDT = 0xb1
+ IFT_H323GATEKEEPER = 0xa4
+ IFT_H323PROXY = 0xa5
+ IFT_HDH1822 = 0x3
+ IFT_HDLC = 0x76
+ IFT_HDSL2 = 0xa8
+ IFT_HIPERLAN2 = 0xb7
+ IFT_HIPPI = 0x2f
+ IFT_HIPPIINTERFACE = 0x39
+ IFT_HOSTPAD = 0x5a
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IBM370PARCHAN = 0x48
+ IFT_IDSL = 0x9a
+ IFT_IEEE80211 = 0x47
+ IFT_IEEE80212 = 0x37
+ IFT_IEEE8023ADLAG = 0xa1
+ IFT_IFGSN = 0x91
+ IFT_IMT = 0xbe
+ IFT_INTERLEAVE = 0x7c
+ IFT_IP = 0x7e
+ IFT_IPFORWARD = 0x8e
+ IFT_IPOVERATM = 0x72
+ IFT_IPOVERCDLC = 0x6d
+ IFT_IPOVERCLAW = 0x6e
+ IFT_IPSWITCH = 0x4e
+ IFT_IPXIP = 0xf9
+ IFT_ISDN = 0x3f
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISDNS = 0x4b
+ IFT_ISDNU = 0x4c
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88025CRFPINT = 0x62
+ IFT_ISO88025DTR = 0x56
+ IFT_ISO88025FIBER = 0x73
+ IFT_ISO88026 = 0xa
+ IFT_ISUP = 0xb3
+ IFT_L3IPXVLAN = 0x89
+ IFT_LAPB = 0x10
+ IFT_LAPD = 0x4d
+ IFT_LAPF = 0x77
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MEDIAMAILOVERIP = 0x8b
+ IFT_MFSIGLINK = 0xa7
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_MPC = 0x71
+ IFT_MPLS = 0xa6
+ IFT_MPLSTUNNEL = 0x96
+ IFT_MSDSL = 0x8f
+ IFT_MVL = 0xbf
+ IFT_MYRINET = 0x63
+ IFT_NFAS = 0xaf
+ IFT_NSIP = 0x1b
+ IFT_OPTICALCHANNEL = 0xc3
+ IFT_OPTICALTRANSPORT = 0xc4
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PFLOG = 0xf6
+ IFT_PFSYNC = 0xf7
+ IFT_PLC = 0xae
+ IFT_POS = 0xab
+ IFT_PPPMULTILINKBUNDLE = 0x6c
+ IFT_PROPBWAP2MP = 0xb8
+ IFT_PROPCNLS = 0x59
+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
+ IFT_PROPMUX = 0x36
+ IFT_PROPWIRELESSP2P = 0x9d
+ IFT_PTPSERIAL = 0x16
+ IFT_PVC = 0xf1
+ IFT_QLLC = 0x44
+ IFT_RADIOMAC = 0xbc
+ IFT_RADSL = 0x5f
+ IFT_REACHDSL = 0xc0
+ IFT_RFC1483 = 0x9f
+ IFT_RS232 = 0x21
+ IFT_RSRB = 0x4f
+ IFT_SDLC = 0x11
+ IFT_SDSL = 0x60
+ IFT_SHDSL = 0xa9
+ IFT_SIP = 0x1f
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETOVERHEADCHANNEL = 0xb9
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_SRP = 0x97
+ IFT_SS7SIGLINK = 0x9c
+ IFT_STACKTOSTACK = 0x6f
+ IFT_STARLAN = 0xb
+ IFT_STF = 0xd7
+ IFT_T1 = 0x12
+ IFT_TDLC = 0x74
+ IFT_TERMPAD = 0x5b
+ IFT_TR008 = 0xb0
+ IFT_TRANSPHDLC = 0x7b
+ IFT_TUNNEL = 0x83
+ IFT_ULTRA = 0x1d
+ IFT_USB = 0xa0
+ IFT_V11 = 0x40
+ IFT_V35 = 0x2d
+ IFT_V36 = 0x41
+ IFT_V37 = 0x78
+ IFT_VDSL = 0x61
+ IFT_VIRTUALIPADDRESS = 0x70
+ IFT_VOICEEM = 0x64
+ IFT_VOICEENCAP = 0x67
+ IFT_VOICEFXO = 0x65
+ IFT_VOICEFXS = 0x66
+ IFT_VOICEOVERATM = 0x98
+ IFT_VOICEOVERFRAMERELAY = 0x99
+ IFT_VOICEOVERIP = 0x68
+ IFT_X213 = 0x5d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25HUNTGROUP = 0x7a
+ IFT_X25MLP = 0x79
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IPPROTO_MAXID = 0x34
+ IPV6_FAITH = 0x1d
+ IP_FAITH = 0x16
+ MAP_NORESERVE = 0x40
+ MAP_RENAME = 0x20
+ NET_RT_MAXID = 0x6
+ RTF_PRCLONING = 0x10000
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ SIOCADDRT = 0x8040720a
+ SIOCALIFADDR = 0x8118691b
+ SIOCDELRT = 0x8040720b
+ SIOCDLIFADDR = 0x8118691d
+ SIOCGLIFADDR = 0xc118691c
+ SIOCGLIFPHYADDR = 0xc118694b
+ SIOCSLIFPHYADDR = 0x8118694a
+)
diff --git a/vendor/golang.org/x/sys/unix/errors_freebsd_arm.go b/vendor/golang.org/x/sys/unix/errors_freebsd_arm.go
new file mode 100644
index 0000000..856dca3
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/errors_freebsd_arm.go
@@ -0,0 +1,226 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package unix
+
+const (
+ IFT_1822 = 0x2
+ IFT_A12MPPSWITCH = 0x82
+ IFT_AAL2 = 0xbb
+ IFT_AAL5 = 0x31
+ IFT_ADSL = 0x5e
+ IFT_AFLANE8023 = 0x3b
+ IFT_AFLANE8025 = 0x3c
+ IFT_ARAP = 0x58
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ASYNC = 0x54
+ IFT_ATM = 0x25
+ IFT_ATMDXI = 0x69
+ IFT_ATMFUNI = 0x6a
+ IFT_ATMIMA = 0x6b
+ IFT_ATMLOGICAL = 0x50
+ IFT_ATMRADIO = 0xbd
+ IFT_ATMSUBINTERFACE = 0x86
+ IFT_ATMVCIENDPT = 0xc2
+ IFT_ATMVIRTUAL = 0x95
+ IFT_BGPPOLICYACCOUNTING = 0xa2
+ IFT_BSC = 0x53
+ IFT_CCTEMUL = 0x3d
+ IFT_CEPT = 0x13
+ IFT_CES = 0x85
+ IFT_CHANNEL = 0x46
+ IFT_CNR = 0x55
+ IFT_COFFEE = 0x84
+ IFT_COMPOSITELINK = 0x9b
+ IFT_DCN = 0x8d
+ IFT_DIGITALPOWERLINE = 0x8a
+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
+ IFT_DLSW = 0x4a
+ IFT_DOCSCABLEDOWNSTREAM = 0x80
+ IFT_DOCSCABLEMACLAYER = 0x7f
+ IFT_DOCSCABLEUPSTREAM = 0x81
+ IFT_DS0 = 0x51
+ IFT_DS0BUNDLE = 0x52
+ IFT_DS1FDL = 0xaa
+ IFT_DS3 = 0x1e
+ IFT_DTM = 0x8c
+ IFT_DVBASILN = 0xac
+ IFT_DVBASIOUT = 0xad
+ IFT_DVBRCCDOWNSTREAM = 0x93
+ IFT_DVBRCCMACLAYER = 0x92
+ IFT_DVBRCCUPSTREAM = 0x94
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_EPLRS = 0x57
+ IFT_ESCON = 0x49
+ IFT_ETHER = 0x6
+ IFT_FAST = 0x7d
+ IFT_FASTETHER = 0x3e
+ IFT_FASTETHERFX = 0x45
+ IFT_FDDI = 0xf
+ IFT_FIBRECHANNEL = 0x38
+ IFT_FRAMERELAYINTERCONNECT = 0x3a
+ IFT_FRAMERELAYMPI = 0x5c
+ IFT_FRDLCIENDPT = 0xc1
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_FRF16MFRBUNDLE = 0xa3
+ IFT_FRFORWARD = 0x9e
+ IFT_G703AT2MB = 0x43
+ IFT_G703AT64K = 0x42
+ IFT_GIF = 0xf0
+ IFT_GIGABITETHERNET = 0x75
+ IFT_GR303IDT = 0xb2
+ IFT_GR303RDT = 0xb1
+ IFT_H323GATEKEEPER = 0xa4
+ IFT_H323PROXY = 0xa5
+ IFT_HDH1822 = 0x3
+ IFT_HDLC = 0x76
+ IFT_HDSL2 = 0xa8
+ IFT_HIPERLAN2 = 0xb7
+ IFT_HIPPI = 0x2f
+ IFT_HIPPIINTERFACE = 0x39
+ IFT_HOSTPAD = 0x5a
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IBM370PARCHAN = 0x48
+ IFT_IDSL = 0x9a
+ IFT_IEEE80211 = 0x47
+ IFT_IEEE80212 = 0x37
+ IFT_IEEE8023ADLAG = 0xa1
+ IFT_IFGSN = 0x91
+ IFT_IMT = 0xbe
+ IFT_INTERLEAVE = 0x7c
+ IFT_IP = 0x7e
+ IFT_IPFORWARD = 0x8e
+ IFT_IPOVERATM = 0x72
+ IFT_IPOVERCDLC = 0x6d
+ IFT_IPOVERCLAW = 0x6e
+ IFT_IPSWITCH = 0x4e
+ IFT_ISDN = 0x3f
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISDNS = 0x4b
+ IFT_ISDNU = 0x4c
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88025CRFPINT = 0x62
+ IFT_ISO88025DTR = 0x56
+ IFT_ISO88025FIBER = 0x73
+ IFT_ISO88026 = 0xa
+ IFT_ISUP = 0xb3
+ IFT_L3IPXVLAN = 0x89
+ IFT_LAPB = 0x10
+ IFT_LAPD = 0x4d
+ IFT_LAPF = 0x77
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MEDIAMAILOVERIP = 0x8b
+ IFT_MFSIGLINK = 0xa7
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_MPC = 0x71
+ IFT_MPLS = 0xa6
+ IFT_MPLSTUNNEL = 0x96
+ IFT_MSDSL = 0x8f
+ IFT_MVL = 0xbf
+ IFT_MYRINET = 0x63
+ IFT_NFAS = 0xaf
+ IFT_NSIP = 0x1b
+ IFT_OPTICALCHANNEL = 0xc3
+ IFT_OPTICALTRANSPORT = 0xc4
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PFLOG = 0xf6
+ IFT_PFSYNC = 0xf7
+ IFT_PLC = 0xae
+ IFT_POS = 0xab
+ IFT_PPPMULTILINKBUNDLE = 0x6c
+ IFT_PROPBWAP2MP = 0xb8
+ IFT_PROPCNLS = 0x59
+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
+ IFT_PROPMUX = 0x36
+ IFT_PROPWIRELESSP2P = 0x9d
+ IFT_PTPSERIAL = 0x16
+ IFT_PVC = 0xf1
+ IFT_QLLC = 0x44
+ IFT_RADIOMAC = 0xbc
+ IFT_RADSL = 0x5f
+ IFT_REACHDSL = 0xc0
+ IFT_RFC1483 = 0x9f
+ IFT_RS232 = 0x21
+ IFT_RSRB = 0x4f
+ IFT_SDLC = 0x11
+ IFT_SDSL = 0x60
+ IFT_SHDSL = 0xa9
+ IFT_SIP = 0x1f
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETOVERHEADCHANNEL = 0xb9
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_SRP = 0x97
+ IFT_SS7SIGLINK = 0x9c
+ IFT_STACKTOSTACK = 0x6f
+ IFT_STARLAN = 0xb
+ IFT_STF = 0xd7
+ IFT_T1 = 0x12
+ IFT_TDLC = 0x74
+ IFT_TERMPAD = 0x5b
+ IFT_TR008 = 0xb0
+ IFT_TRANSPHDLC = 0x7b
+ IFT_TUNNEL = 0x83
+ IFT_ULTRA = 0x1d
+ IFT_USB = 0xa0
+ IFT_V11 = 0x40
+ IFT_V35 = 0x2d
+ IFT_V36 = 0x41
+ IFT_V37 = 0x78
+ IFT_VDSL = 0x61
+ IFT_VIRTUALIPADDRESS = 0x70
+ IFT_VOICEEM = 0x64
+ IFT_VOICEENCAP = 0x67
+ IFT_VOICEFXO = 0x65
+ IFT_VOICEFXS = 0x66
+ IFT_VOICEOVERATM = 0x98
+ IFT_VOICEOVERFRAMERELAY = 0x99
+ IFT_VOICEOVERIP = 0x68
+ IFT_X213 = 0x5d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25HUNTGROUP = 0x7a
+ IFT_X25MLP = 0x79
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+
+ // missing constants on FreeBSD-11.1-RELEASE, copied from old values in ztypes_freebsd_arm.go
+ IFF_SMART = 0x20
+ IFT_FAITH = 0xf2
+ IFT_IPXIP = 0xf9
+ IPPROTO_MAXID = 0x34
+ IPV6_FAITH = 0x1d
+ IP_FAITH = 0x16
+ MAP_NORESERVE = 0x40
+ MAP_RENAME = 0x20
+ NET_RT_MAXID = 0x6
+ RTF_PRCLONING = 0x10000
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ SIOCADDRT = 0x8030720a
+ SIOCALIFADDR = 0x8118691b
+ SIOCDELRT = 0x8030720b
+ SIOCDLIFADDR = 0x8118691d
+ SIOCGLIFADDR = 0xc118691c
+ SIOCGLIFPHYADDR = 0xc118694b
+ SIOCSLIFPHYADDR = 0x8118694a
+)
diff --git a/vendor/golang.org/x/sys/unix/file_unix.go b/vendor/golang.org/x/sys/unix/file_unix.go
new file mode 100644
index 0000000..47f6a83
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/file_unix.go
@@ -0,0 +1,27 @@
+// Copyright 2017 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package unix
+
+import (
+ "os"
+ "syscall"
+)
+
+// FIXME: unexported function from os
+// syscallMode returns the syscall-specific mode bits from Go's portable mode bits.
+func syscallMode(i os.FileMode) (o uint32) {
+ o |= uint32(i.Perm())
+ if i&os.ModeSetuid != 0 {
+ o |= syscall.S_ISUID
+ }
+ if i&os.ModeSetgid != 0 {
+ o |= syscall.S_ISGID
+ }
+ if i&os.ModeSticky != 0 {
+ o |= syscall.S_ISVTX
+ }
+ // No mapping for Go's ModeTemporary (plan9 only).
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/flock.go b/vendor/golang.org/x/sys/unix/flock.go
new file mode 100644
index 0000000..2994ce7
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/flock.go
@@ -0,0 +1,22 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build darwin dragonfly freebsd linux netbsd openbsd
+
+package unix
+
+import "unsafe"
+
+// fcntl64Syscall is usually SYS_FCNTL, but is overridden on 32-bit Linux
+// systems by flock_linux_32bit.go to be SYS_FCNTL64.
+var fcntl64Syscall uintptr = SYS_FCNTL
+
+// FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command.
+func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {
+ _, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk)))
+ if errno == 0 {
+ return nil
+ }
+ return errno
+}
diff --git a/vendor/golang.org/x/sys/unix/flock_linux_32bit.go b/vendor/golang.org/x/sys/unix/flock_linux_32bit.go
new file mode 100644
index 0000000..fc0e50e
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/flock_linux_32bit.go
@@ -0,0 +1,13 @@
+// +build linux,386 linux,arm linux,mips linux,mipsle
+
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package unix
+
+func init() {
+ // On 32-bit Linux systems, the fcntl syscall that matches Go's
+ // Flock_t type is SYS_FCNTL64, not SYS_FCNTL.
+ fcntl64Syscall = SYS_FCNTL64
+}
diff --git a/vendor/golang.org/x/sys/unix/gccgo.go b/vendor/golang.org/x/sys/unix/gccgo.go
new file mode 100644
index 0000000..94c8232
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/gccgo.go
@@ -0,0 +1,46 @@
+// Copyright 2015 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 gccgo
+
+package unix
+
+import "syscall"
+
+// We can't use the gc-syntax .s files for gccgo. On the plus side
+// much of the functionality can be written directly in Go.
+
+//extern gccgoRealSyscall
+func realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r, errno uintptr)
+
+func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) {
+ syscall.Entersyscall()
+ r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0)
+ syscall.Exitsyscall()
+ return r, 0, syscall.Errno(errno)
+}
+
+func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) {
+ syscall.Entersyscall()
+ r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, 0, 0, 0)
+ syscall.Exitsyscall()
+ return r, 0, syscall.Errno(errno)
+}
+
+func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) {
+ syscall.Entersyscall()
+ r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9)
+ syscall.Exitsyscall()
+ return r, 0, syscall.Errno(errno)
+}
+
+func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) {
+ r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0)
+ return r, 0, syscall.Errno(errno)
+}
+
+func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) {
+ r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, 0, 0, 0)
+ return r, 0, syscall.Errno(errno)
+}
diff --git a/vendor/golang.org/x/sys/unix/gccgo_c.c b/vendor/golang.org/x/sys/unix/gccgo_c.c
new file mode 100644
index 0000000..07f6be0
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/gccgo_c.c
@@ -0,0 +1,41 @@
+// Copyright 2015 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 gccgo
+
+#include <errno.h>
+#include <stdint.h>
+#include <unistd.h>
+
+#define _STRINGIFY2_(x) #x
+#define _STRINGIFY_(x) _STRINGIFY2_(x)
+#define GOSYM_PREFIX _STRINGIFY_(__USER_LABEL_PREFIX__)
+
+// Call syscall from C code because the gccgo support for calling from
+// Go to C does not support varargs functions.
+
+struct ret {
+ uintptr_t r;
+ uintptr_t err;
+};
+
+struct ret
+gccgoRealSyscall(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9)
+{
+ struct ret r;
+
+ errno = 0;
+ r.r = syscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9);
+ r.err = errno;
+ return r;
+}
+
+// Define the use function in C so that it is not inlined.
+
+extern void use(void *) __asm__ (GOSYM_PREFIX GOPKGPATH ".use") __attribute__((noinline));
+
+void
+use(void *p __attribute__ ((unused)))
+{
+}
diff --git a/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go b/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go
new file mode 100644
index 0000000..bffe1a7
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go
@@ -0,0 +1,20 @@
+// Copyright 2015 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 gccgo,linux,amd64
+
+package unix
+
+import "syscall"
+
+//extern gettimeofday
+func realGettimeofday(*Timeval, *byte) int32
+
+func gettimeofday(tv *Timeval) (err syscall.Errno) {
+ r := realGettimeofday(tv, nil)
+ if r < 0 {
+ return syscall.GetErrno()
+ }
+ return 0
+}
diff --git a/vendor/golang.org/x/sys/unix/gccgo_linux_sparc64.go b/vendor/golang.org/x/sys/unix/gccgo_linux_sparc64.go
new file mode 100644
index 0000000..5633269
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/gccgo_linux_sparc64.go
@@ -0,0 +1,20 @@
+// 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 gccgo,linux,sparc64
+
+package unix
+
+import "syscall"
+
+//extern sysconf
+func realSysconf(name int) int64
+
+func sysconf(name int) (n int64, err syscall.Errno) {
+ r := realSysconf(name)
+ if r < 0 {
+ return 0, syscall.GetErrno()
+ }
+ return r, 0
+}
diff --git a/vendor/golang.org/x/sys/unix/openbsd_pledge.go b/vendor/golang.org/x/sys/unix/openbsd_pledge.go
new file mode 100644
index 0000000..db4f72e
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/openbsd_pledge.go
@@ -0,0 +1,38 @@
+// 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 openbsd
+// +build 386 amd64 arm
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+const (
+ SYS_PLEDGE = 108
+)
+
+// Pledge implements the pledge syscall. For more information see pledge(2).
+func Pledge(promises string, paths []string) error {
+ promisesPtr, err := syscall.BytePtrFromString(promises)
+ if err != nil {
+ return err
+ }
+ promisesUnsafe, pathsUnsafe := unsafe.Pointer(promisesPtr), unsafe.Pointer(nil)
+ if paths != nil {
+ var pathsPtr []*byte
+ if pathsPtr, err = syscall.SlicePtrFromStrings(paths); err != nil {
+ return err
+ }
+ pathsUnsafe = unsafe.Pointer(&pathsPtr[0])
+ }
+ _, _, e := syscall.Syscall(SYS_PLEDGE, uintptr(promisesUnsafe), uintptr(pathsUnsafe), 0)
+ if e != 0 {
+ return e
+ }
+ return nil
+}
diff --git a/vendor/golang.org/x/sys/unix/race.go b/vendor/golang.org/x/sys/unix/race.go
new file mode 100644
index 0000000..3c7627e
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/race.go
@@ -0,0 +1,30 @@
+// 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 darwin,race linux,race freebsd,race
+
+package unix
+
+import (
+ "runtime"
+ "unsafe"
+)
+
+const raceenabled = true
+
+func raceAcquire(addr unsafe.Pointer) {
+ runtime.RaceAcquire(addr)
+}
+
+func raceReleaseMerge(addr unsafe.Pointer) {
+ runtime.RaceReleaseMerge(addr)
+}
+
+func raceReadRange(addr unsafe.Pointer, len int) {
+ runtime.RaceReadRange(addr, len)
+}
+
+func raceWriteRange(addr unsafe.Pointer, len int) {
+ runtime.RaceWriteRange(addr, len)
+}
diff --git a/vendor/golang.org/x/sys/unix/race0.go b/vendor/golang.org/x/sys/unix/race0.go
new file mode 100644
index 0000000..f8678e0
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/race0.go
@@ -0,0 +1,25 @@
+// 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 darwin,!race linux,!race freebsd,!race netbsd openbsd solaris dragonfly
+
+package unix
+
+import (
+ "unsafe"
+)
+
+const raceenabled = false
+
+func raceAcquire(addr unsafe.Pointer) {
+}
+
+func raceReleaseMerge(addr unsafe.Pointer) {
+}
+
+func raceReadRange(addr unsafe.Pointer, len int) {
+}
+
+func raceWriteRange(addr unsafe.Pointer, len int) {
+}
diff --git a/vendor/golang.org/x/sys/unix/sockcmsg_linux.go b/vendor/golang.org/x/sys/unix/sockcmsg_linux.go
new file mode 100644
index 0000000..d9ff473
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/sockcmsg_linux.go
@@ -0,0 +1,36 @@
+// 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.
+
+// Socket control messages
+
+package unix
+
+import "unsafe"
+
+// UnixCredentials encodes credentials into a socket control message
+// for sending to another process. This can be used for
+// authentication.
+func UnixCredentials(ucred *Ucred) []byte {
+ b := make([]byte, CmsgSpace(SizeofUcred))
+ h := (*Cmsghdr)(unsafe.Pointer(&b[0]))
+ h.Level = SOL_SOCKET
+ h.Type = SCM_CREDENTIALS
+ h.SetLen(CmsgLen(SizeofUcred))
+ *((*Ucred)(cmsgData(h))) = *ucred
+ return b
+}
+
+// ParseUnixCredentials decodes a socket control message that contains
+// credentials in a Ucred structure. To receive such a message, the
+// SO_PASSCRED option must be enabled on the socket.
+func ParseUnixCredentials(m *SocketControlMessage) (*Ucred, error) {
+ if m.Header.Level != SOL_SOCKET {
+ return nil, EINVAL
+ }
+ if m.Header.Type != SCM_CREDENTIALS {
+ return nil, EINVAL
+ }
+ ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0]))
+ return &ucred, nil
+}
diff --git a/vendor/golang.org/x/sys/unix/sockcmsg_unix.go b/vendor/golang.org/x/sys/unix/sockcmsg_unix.go
new file mode 100644
index 0000000..bb756ec
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/sockcmsg_unix.go
@@ -0,0 +1,104 @@
+// 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.
+
+// +build darwin dragonfly freebsd linux netbsd openbsd solaris
+
+// Socket control messages
+
+package unix
+
+import "unsafe"
+
+// Round the length of a raw sockaddr up to align it properly.
+func cmsgAlignOf(salen int) int {
+ salign := sizeofPtr
+ // NOTE: It seems like 64-bit Darwin, DragonFly BSD and
+ // Solaris kernels still require 32-bit aligned access to
+ // network subsystem.
+ if darwin64Bit || dragonfly64Bit || solaris64Bit {
+ salign = 4
+ }
+ return (salen + salign - 1) & ^(salign - 1)
+}
+
+// CmsgLen returns the value to store in the Len field of the Cmsghdr
+// structure, taking into account any necessary alignment.
+func CmsgLen(datalen int) int {
+ return cmsgAlignOf(SizeofCmsghdr) + datalen
+}
+
+// CmsgSpace returns the number of bytes an ancillary element with
+// payload of the passed data length occupies.
+func CmsgSpace(datalen int) int {
+ return cmsgAlignOf(SizeofCmsghdr) + cmsgAlignOf(datalen)
+}
+
+func cmsgData(h *Cmsghdr) unsafe.Pointer {
+ return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(SizeofCmsghdr)))
+}
+
+// SocketControlMessage represents a socket control message.
+type SocketControlMessage struct {
+ Header Cmsghdr
+ Data []byte
+}
+
+// ParseSocketControlMessage parses b as an array of socket control
+// messages.
+func ParseSocketControlMessage(b []byte) ([]SocketControlMessage, error) {
+ var msgs []SocketControlMessage
+ i := 0
+ for i+CmsgLen(0) <= len(b) {
+ h, dbuf, err := socketControlMessageHeaderAndData(b[i:])
+ if err != nil {
+ return nil, err
+ }
+ m := SocketControlMessage{Header: *h, Data: dbuf}
+ msgs = append(msgs, m)
+ i += cmsgAlignOf(int(h.Len))
+ }
+ return msgs, nil
+}
+
+func socketControlMessageHeaderAndData(b []byte) (*Cmsghdr, []byte, error) {
+ h := (*Cmsghdr)(unsafe.Pointer(&b[0]))
+ if h.Len < SizeofCmsghdr || uint64(h.Len) > uint64(len(b)) {
+ return nil, nil, EINVAL
+ }
+ return h, b[cmsgAlignOf(SizeofCmsghdr):h.Len], nil
+}
+
+// UnixRights encodes a set of open file descriptors into a socket
+// control message for sending to another process.
+func UnixRights(fds ...int) []byte {
+ datalen := len(fds) * 4
+ b := make([]byte, CmsgSpace(datalen))
+ h := (*Cmsghdr)(unsafe.Pointer(&b[0]))
+ h.Level = SOL_SOCKET
+ h.Type = SCM_RIGHTS
+ h.SetLen(CmsgLen(datalen))
+ data := cmsgData(h)
+ for _, fd := range fds {
+ *(*int32)(data) = int32(fd)
+ data = unsafe.Pointer(uintptr(data) + 4)
+ }
+ return b
+}
+
+// ParseUnixRights decodes a socket control message that contains an
+// integer array of open file descriptors from another process.
+func ParseUnixRights(m *SocketControlMessage) ([]int, error) {
+ if m.Header.Level != SOL_SOCKET {
+ return nil, EINVAL
+ }
+ if m.Header.Type != SCM_RIGHTS {
+ return nil, EINVAL
+ }
+ fds := make([]int, len(m.Data)>>2)
+ for i, j := 0, 0; i < len(m.Data); i += 4 {
+ fds[j] = int(*(*int32)(unsafe.Pointer(&m.Data[i])))
+ j++
+ }
+ return fds, nil
+}
diff --git a/vendor/golang.org/x/sys/unix/str.go b/vendor/golang.org/x/sys/unix/str.go
new file mode 100644
index 0000000..35ed664
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/str.go
@@ -0,0 +1,26 @@
+// Copyright 2009 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
+
+package unix
+
+func itoa(val int) string { // do it here rather than with fmt to avoid dependency
+ if val < 0 {
+ return "-" + uitoa(uint(-val))
+ }
+ return uitoa(uint(val))
+}
+
+func uitoa(val uint) string {
+ var buf [32]byte // big enough for int64
+ i := len(buf) - 1
+ for val >= 10 {
+ buf[i] = byte(val%10 + '0')
+ i--
+ val /= 10
+ }
+ buf[i] = byte(val + '0')
+ return string(buf[i:])
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall.go b/vendor/golang.org/x/sys/unix/syscall.go
new file mode 100644
index 0000000..85e3502
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall.go
@@ -0,0 +1,69 @@
+// Copyright 2009 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
+
+// Package unix contains an interface to the low-level operating system
+// primitives. OS details vary depending on the underlying system, and
+// by default, godoc will display OS-specific documentation for the current
+// system. If you want godoc to display OS documentation for another
+// system, set $GOOS and $GOARCH to the desired system. For example, if
+// you want to view documentation for freebsd/arm on linux/amd64, set $GOOS
+// to freebsd and $GOARCH to arm.
+// The primary use of this package is inside other packages that provide a more
+// portable interface to the system, such as "os", "time" and "net". Use
+// those packages rather than this one if you can.
+// For details of the functions and data types in this package consult
+// the manuals for the appropriate operating system.
+// These calls return err == nil to indicate success; otherwise
+// err represents an operating system error describing the failure and
+// holds a value of type syscall.Errno.
+package unix // import "golang.org/x/sys/unix"
+
+// ByteSliceFromString returns a NUL-terminated slice of bytes
+// containing the text of s. If s contains a NUL byte at any
+// location, it returns (nil, EINVAL).
+func ByteSliceFromString(s string) ([]byte, error) {
+ for i := 0; i < len(s); i++ {
+ if s[i] == 0 {
+ return nil, EINVAL
+ }
+ }
+ a := make([]byte, len(s)+1)
+ copy(a, s)
+ return a, nil
+}
+
+// BytePtrFromString returns a pointer to a NUL-terminated array of
+// bytes containing the text of s. If s contains a NUL byte at any
+// location, it returns (nil, EINVAL).
+func BytePtrFromString(s string) (*byte, error) {
+ a, err := ByteSliceFromString(s)
+ if err != nil {
+ return nil, err
+ }
+ return &a[0], nil
+}
+
+// Single-word zero for use when we need a valid pointer to 0 bytes.
+// See mkunix.pl.
+var _zero uintptr
+
+func (ts *Timespec) Unix() (sec int64, nsec int64) {
+ return int64(ts.Sec), int64(ts.Nsec)
+}
+
+func (tv *Timeval) Unix() (sec int64, nsec int64) {
+ return int64(tv.Sec), int64(tv.Usec) * 1000
+}
+
+func (ts *Timespec) Nano() int64 {
+ return int64(ts.Sec)*1e9 + int64(ts.Nsec)
+}
+
+func (tv *Timeval) Nano() int64 {
+ return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000
+}
+
+func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
diff --git a/vendor/golang.org/x/sys/unix/syscall_bsd.go b/vendor/golang.org/x/sys/unix/syscall_bsd.go
new file mode 100644
index 0000000..c2846b3
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_bsd.go
@@ -0,0 +1,635 @@
+// Copyright 2009 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 netbsd openbsd
+
+// BSD system call wrappers shared by *BSD based systems
+// including OS X (Darwin) and FreeBSD. Like the other
+// syscall_*.go files it is compiled as Go code but also
+// used as input to mksyscall which parses the //sys
+// lines and generates system call stubs.
+
+package unix
+
+import (
+ "runtime"
+ "syscall"
+ "unsafe"
+)
+
+/*
+ * Wrapped
+ */
+
+//sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error)
+//sysnb setgroups(ngid int, gid *_Gid_t) (err error)
+
+func Getgroups() (gids []int, err error) {
+ n, err := getgroups(0, nil)
+ if err != nil {
+ return nil, err
+ }
+ if n == 0 {
+ return nil, nil
+ }
+
+ // Sanity check group count. Max is 16 on BSD.
+ if n < 0 || n > 1000 {
+ return nil, EINVAL
+ }
+
+ a := make([]_Gid_t, n)
+ n, err = getgroups(n, &a[0])
+ if err != nil {
+ return nil, err
+ }
+ gids = make([]int, n)
+ for i, v := range a[0:n] {
+ gids[i] = int(v)
+ }
+ return
+}
+
+func Setgroups(gids []int) (err error) {
+ if len(gids) == 0 {
+ return setgroups(0, nil)
+ }
+
+ a := make([]_Gid_t, len(gids))
+ for i, v := range gids {
+ a[i] = _Gid_t(v)
+ }
+ return setgroups(len(a), &a[0])
+}
+
+func ReadDirent(fd int, buf []byte) (n int, err error) {
+ // Final argument is (basep *uintptr) and the syscall doesn't take nil.
+ // 64 bits should be enough. (32 bits isn't even on 386). Since the
+ // actual system call is getdirentries64, 64 is a good guess.
+ // TODO(rsc): Can we use a single global basep for all calls?
+ var base = (*uintptr)(unsafe.Pointer(new(uint64)))
+ return Getdirentries(fd, buf, base)
+}
+
+// Wait status is 7 bits at bottom, either 0 (exited),
+// 0x7F (stopped), or a signal number that caused an exit.
+// The 0x80 bit is whether there was a core dump.
+// An extra number (exit code, signal causing a stop)
+// is in the high bits.
+
+type WaitStatus uint32
+
+const (
+ mask = 0x7F
+ core = 0x80
+ shift = 8
+
+ exited = 0
+ stopped = 0x7F
+)
+
+func (w WaitStatus) Exited() bool { return w&mask == exited }
+
+func (w WaitStatus) ExitStatus() int {
+ if w&mask != exited {
+ return -1
+ }
+ return int(w >> shift)
+}
+
+func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 }
+
+func (w WaitStatus) Signal() syscall.Signal {
+ sig := syscall.Signal(w & mask)
+ if sig == stopped || sig == 0 {
+ return -1
+ }
+ return sig
+}
+
+func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
+
+func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP }
+
+func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP }
+
+func (w WaitStatus) StopSignal() syscall.Signal {
+ if !w.Stopped() {
+ return -1
+ }
+ return syscall.Signal(w>>shift) & 0xFF
+}
+
+func (w WaitStatus) TrapCause() int { return -1 }
+
+//sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
+
+func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
+ var status _C_int
+ wpid, err = wait4(pid, &status, options, rusage)
+ if wstatus != nil {
+ *wstatus = WaitStatus(status)
+ }
+ return
+}
+
+//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (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 socket(domain int, typ int, proto int) (fd int, 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 getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
+//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
+//sys Shutdown(s int, how int) (err error)
+
+func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ if sa.Port < 0 || sa.Port > 0xFFFF {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Len = SizeofSockaddrInet4
+ sa.raw.Family = AF_INET
+ p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
+ p[0] = byte(sa.Port >> 8)
+ p[1] = byte(sa.Port)
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.raw.Addr[i] = sa.Addr[i]
+ }
+ return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
+}
+
+func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ if sa.Port < 0 || sa.Port > 0xFFFF {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Len = SizeofSockaddrInet6
+ sa.raw.Family = AF_INET6
+ p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
+ p[0] = byte(sa.Port >> 8)
+ p[1] = byte(sa.Port)
+ sa.raw.Scope_id = sa.ZoneId
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.raw.Addr[i] = sa.Addr[i]
+ }
+ return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
+}
+
+func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ name := sa.Name
+ n := len(name)
+ if n >= len(sa.raw.Path) || n == 0 {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Len = byte(3 + n) // 2 for Family, Len; 1 for NUL
+ sa.raw.Family = AF_UNIX
+ for i := 0; i < n; i++ {
+ sa.raw.Path[i] = int8(name[i])
+ }
+ return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
+}
+
+func (sa *SockaddrDatalink) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ if sa.Index == 0 {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Len = sa.Len
+ sa.raw.Family = AF_LINK
+ sa.raw.Index = sa.Index
+ sa.raw.Type = sa.Type
+ sa.raw.Nlen = sa.Nlen
+ sa.raw.Alen = sa.Alen
+ sa.raw.Slen = sa.Slen
+ for i := 0; i < len(sa.raw.Data); i++ {
+ sa.raw.Data[i] = sa.Data[i]
+ }
+ return unsafe.Pointer(&sa.raw), SizeofSockaddrDatalink, nil
+}
+
+func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
+ switch rsa.Addr.Family {
+ case AF_LINK:
+ pp := (*RawSockaddrDatalink)(unsafe.Pointer(rsa))
+ sa := new(SockaddrDatalink)
+ sa.Len = pp.Len
+ sa.Family = pp.Family
+ sa.Index = pp.Index
+ sa.Type = pp.Type
+ sa.Nlen = pp.Nlen
+ sa.Alen = pp.Alen
+ sa.Slen = pp.Slen
+ for i := 0; i < len(sa.Data); i++ {
+ sa.Data[i] = pp.Data[i]
+ }
+ return sa, nil
+
+ case AF_UNIX:
+ pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
+ if pp.Len < 2 || pp.Len > SizeofSockaddrUnix {
+ return nil, EINVAL
+ }
+ sa := new(SockaddrUnix)
+
+ // Some BSDs include the trailing NUL in the length, whereas
+ // others do not. Work around this by subtracting the leading
+ // family and len. The path is then scanned to see if a NUL
+ // terminator still exists within the length.
+ n := int(pp.Len) - 2 // subtract leading Family, Len
+ for i := 0; i < n; i++ {
+ if pp.Path[i] == 0 {
+ // found early NUL; assume Len included the NUL
+ // or was overestimating.
+ n = i
+ break
+ }
+ }
+ bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
+ sa.Name = string(bytes)
+ return sa, nil
+
+ case AF_INET:
+ pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
+ sa := new(SockaddrInet4)
+ p := (*[2]byte)(unsafe.Pointer(&pp.Port))
+ sa.Port = int(p[0])<<8 + int(p[1])
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.Addr[i] = pp.Addr[i]
+ }
+ return sa, nil
+
+ case AF_INET6:
+ pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
+ sa := new(SockaddrInet6)
+ p := (*[2]byte)(unsafe.Pointer(&pp.Port))
+ sa.Port = int(p[0])<<8 + int(p[1])
+ sa.ZoneId = pp.Scope_id
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.Addr[i] = pp.Addr[i]
+ }
+ return sa, nil
+ }
+ return nil, EAFNOSUPPORT
+}
+
+func Accept(fd int) (nfd int, sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ nfd, err = accept(fd, &rsa, &len)
+ if err != nil {
+ return
+ }
+ if runtime.GOOS == "darwin" && len == 0 {
+ // Accepted socket has no address.
+ // This is likely due to a bug in xnu kernels,
+ // where instead of ECONNABORTED error socket
+ // is accepted, but has no address.
+ Close(nfd)
+ return 0, nil, ECONNABORTED
+ }
+ sa, err = anyToSockaddr(&rsa)
+ if err != nil {
+ Close(nfd)
+ nfd = 0
+ }
+ return
+}
+
+func Getsockname(fd int) (sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ if err = getsockname(fd, &rsa, &len); err != nil {
+ return
+ }
+ // TODO(jsing): DragonFly has a "bug" (see issue 3349), which should be
+ // reported upstream.
+ if runtime.GOOS == "dragonfly" && rsa.Addr.Family == AF_UNSPEC && rsa.Addr.Len == 0 {
+ rsa.Addr.Family = AF_UNIX
+ rsa.Addr.Len = SizeofSockaddrUnix
+ }
+ return anyToSockaddr(&rsa)
+}
+
+//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
+
+func GetsockoptByte(fd, level, opt int) (value byte, err error) {
+ var n byte
+ vallen := _Socklen(1)
+ err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen)
+ return n, err
+}
+
+func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) {
+ vallen := _Socklen(4)
+ err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
+ return value, err
+}
+
+func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) {
+ var value IPMreq
+ vallen := _Socklen(SizeofIPMreq)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) {
+ var value IPv6Mreq
+ vallen := _Socklen(SizeofIPv6Mreq)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) {
+ var value IPv6MTUInfo
+ vallen := _Socklen(SizeofIPv6MTUInfo)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) {
+ var value ICMPv6Filter
+ vallen := _Socklen(SizeofICMPv6Filter)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+//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)
+
+func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
+ var msg Msghdr
+ var rsa RawSockaddrAny
+ msg.Name = (*byte)(unsafe.Pointer(&rsa))
+ msg.Namelen = uint32(SizeofSockaddrAny)
+ var iov Iovec
+ if len(p) > 0 {
+ iov.Base = (*byte)(unsafe.Pointer(&p[0]))
+ iov.SetLen(len(p))
+ }
+ var dummy byte
+ if len(oob) > 0 {
+ // receive at least one normal byte
+ if len(p) == 0 {
+ iov.Base = &dummy
+ iov.SetLen(1)
+ }
+ msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
+ msg.SetControllen(len(oob))
+ }
+ msg.Iov = &iov
+ msg.Iovlen = 1
+ if n, err = recvmsg(fd, &msg, flags); err != nil {
+ return
+ }
+ oobn = int(msg.Controllen)
+ recvflags = int(msg.Flags)
+ // source address is only specified if the socket is unconnected
+ if rsa.Addr.Family != AF_UNSPEC {
+ from, err = anyToSockaddr(&rsa)
+ }
+ return
+}
+
+//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
+
+func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
+ _, err = SendmsgN(fd, p, oob, to, flags)
+ return
+}
+
+func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
+ var ptr unsafe.Pointer
+ var salen _Socklen
+ if to != nil {
+ ptr, salen, err = to.sockaddr()
+ if err != nil {
+ return 0, err
+ }
+ }
+ var msg Msghdr
+ msg.Name = (*byte)(unsafe.Pointer(ptr))
+ msg.Namelen = uint32(salen)
+ var iov Iovec
+ if len(p) > 0 {
+ iov.Base = (*byte)(unsafe.Pointer(&p[0]))
+ iov.SetLen(len(p))
+ }
+ var dummy byte
+ if len(oob) > 0 {
+ // send at least one normal byte
+ if len(p) == 0 {
+ iov.Base = &dummy
+ iov.SetLen(1)
+ }
+ msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
+ msg.SetControllen(len(oob))
+ }
+ msg.Iov = &iov
+ msg.Iovlen = 1
+ if n, err = sendmsg(fd, &msg, flags); err != nil {
+ return 0, err
+ }
+ if len(oob) > 0 && len(p) == 0 {
+ n = 0
+ }
+ return n, nil
+}
+
+//sys kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error)
+
+func Kevent(kq int, changes, events []Kevent_t, timeout *Timespec) (n int, err error) {
+ var change, event unsafe.Pointer
+ if len(changes) > 0 {
+ change = unsafe.Pointer(&changes[0])
+ }
+ if len(events) > 0 {
+ event = unsafe.Pointer(&events[0])
+ }
+ return kevent(kq, change, len(changes), event, len(events), timeout)
+}
+
+//sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL
+
+// sysctlmib translates name to mib number and appends any additional args.
+func sysctlmib(name string, args ...int) ([]_C_int, error) {
+ // Translate name to mib number.
+ mib, err := nametomib(name)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, a := range args {
+ mib = append(mib, _C_int(a))
+ }
+
+ return mib, nil
+}
+
+func Sysctl(name string) (string, error) {
+ return SysctlArgs(name)
+}
+
+func SysctlArgs(name string, args ...int) (string, error) {
+ buf, err := SysctlRaw(name, args...)
+ if err != nil {
+ return "", err
+ }
+ n := len(buf)
+
+ // Throw away terminating NUL.
+ if n > 0 && buf[n-1] == '\x00' {
+ n--
+ }
+ return string(buf[0:n]), nil
+}
+
+func SysctlUint32(name string) (uint32, error) {
+ return SysctlUint32Args(name)
+}
+
+func SysctlUint32Args(name string, args ...int) (uint32, error) {
+ mib, err := sysctlmib(name, args...)
+ if err != nil {
+ return 0, err
+ }
+
+ n := uintptr(4)
+ buf := make([]byte, 4)
+ if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
+ return 0, err
+ }
+ if n != 4 {
+ return 0, EIO
+ }
+ return *(*uint32)(unsafe.Pointer(&buf[0])), nil
+}
+
+func SysctlUint64(name string, args ...int) (uint64, error) {
+ mib, err := sysctlmib(name, args...)
+ if err != nil {
+ return 0, err
+ }
+
+ n := uintptr(8)
+ buf := make([]byte, 8)
+ if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
+ return 0, err
+ }
+ if n != 8 {
+ return 0, EIO
+ }
+ return *(*uint64)(unsafe.Pointer(&buf[0])), nil
+}
+
+func SysctlRaw(name string, args ...int) ([]byte, error) {
+ mib, err := sysctlmib(name, args...)
+ if err != nil {
+ return nil, err
+ }
+
+ // Find size.
+ n := uintptr(0)
+ if err := sysctl(mib, nil, &n, nil, 0); err != nil {
+ return nil, err
+ }
+ if n == 0 {
+ return nil, nil
+ }
+
+ // Read into buffer of that size.
+ buf := make([]byte, n)
+ if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
+ return nil, err
+ }
+
+ // The actual call may return less than the original reported required
+ // size so ensure we deal with that.
+ return buf[:n], nil
+}
+
+//sys utimes(path string, timeval *[2]Timeval) (err error)
+
+func Utimes(path string, tv []Timeval) error {
+ if tv == nil {
+ return utimes(path, nil)
+ }
+ if len(tv) != 2 {
+ return EINVAL
+ }
+ return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
+}
+
+func UtimesNano(path string, ts []Timespec) error {
+ if ts == nil {
+ err := utimensat(AT_FDCWD, path, nil, 0)
+ if err != ENOSYS {
+ return err
+ }
+ return utimes(path, nil)
+ }
+ if len(ts) != 2 {
+ return EINVAL
+ }
+ err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
+ if err != ENOSYS {
+ return err
+ }
+ // Not as efficient as it could be because Timespec and
+ // Timeval have different types in the different OSes
+ tv := [2]Timeval{
+ NsecToTimeval(TimespecToNsec(ts[0])),
+ NsecToTimeval(TimespecToNsec(ts[1])),
+ }
+ return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
+}
+
+func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
+ if ts == nil {
+ return utimensat(dirfd, path, nil, flags)
+ }
+ if len(ts) != 2 {
+ return EINVAL
+ }
+ return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
+}
+
+//sys futimes(fd int, timeval *[2]Timeval) (err error)
+
+func Futimes(fd int, tv []Timeval) error {
+ if tv == nil {
+ return futimes(fd, nil)
+ }
+ if len(tv) != 2 {
+ return EINVAL
+ }
+ return futimes(fd, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
+}
+
+//sys fcntl(fd int, cmd int, arg int) (val int, err error)
+
+// TODO: wrap
+// Acct(name nil-string) (err error)
+// Gethostuuid(uuid *byte, timeout *Timespec) (err error)
+// Ptrace(req int, pid int, addr uintptr, data int) (ret uintptr, err error)
+
+var mapper = &mmapper{
+ active: make(map[*byte][]byte),
+ mmap: mmap,
+ munmap: munmap,
+}
+
+func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
+ return mapper.Mmap(fd, offset, length, prot, flags)
+}
+
+func Munmap(b []byte) (err error) {
+ return mapper.Munmap(b)
+}
+
+//sys Madvise(b []byte, behav int) (err error)
+//sys Mlock(b []byte) (err error)
+//sys Mlockall(flags int) (err error)
+//sys Mprotect(b []byte, prot int) (err error)
+//sys Msync(b []byte, flags int) (err error)
+//sys Munlock(b []byte) (err error)
+//sys Munlockall() (err error)
diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go
new file mode 100644
index 0000000..ad74a11
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go
@@ -0,0 +1,536 @@
+// Copyright 2009,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.
+
+// Darwin system calls.
+// This file is compiled as ordinary Go code,
+// but it is also input to mksyscall,
+// which parses the //sys lines and generates system call stubs.
+// Note that sometimes we use a lowercase //sys name and wrap
+// it in our own nicer implementation, either here or in
+// syscall_bsd.go or syscall_unix.go.
+
+package unix
+
+import (
+ errorspkg "errors"
+ "syscall"
+ "unsafe"
+)
+
+const ImplementsGetwd = true
+
+func Getwd() (string, error) {
+ buf := make([]byte, 2048)
+ attrs, err := getAttrList(".", attrList{CommonAttr: attrCmnFullpath}, buf, 0)
+ if err == nil && len(attrs) == 1 && len(attrs[0]) >= 2 {
+ wd := string(attrs[0])
+ // Sanity check that it's an absolute path and ends
+ // in a null byte, which we then strip.
+ if wd[0] == '/' && wd[len(wd)-1] == 0 {
+ return wd[:len(wd)-1], nil
+ }
+ }
+ // If pkg/os/getwd.go gets ENOTSUP, it will fall back to the
+ // slow algorithm.
+ return "", ENOTSUP
+}
+
+type SockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+ raw RawSockaddrDatalink
+}
+
+// Translate "kern.hostname" to []_C_int{0,1,2,3}.
+func nametomib(name string) (mib []_C_int, err error) {
+ const siz = unsafe.Sizeof(mib[0])
+
+ // NOTE(rsc): It seems strange to set the buffer to have
+ // size CTL_MAXNAME+2 but use only CTL_MAXNAME
+ // as the size. I don't know why the +2 is here, but the
+ // kernel uses +2 for its own implementation of this function.
+ // I am scared that if we don't include the +2 here, the kernel
+ // will silently write 2 words farther than we specify
+ // and we'll get memory corruption.
+ var buf [CTL_MAXNAME + 2]_C_int
+ n := uintptr(CTL_MAXNAME) * siz
+
+ p := (*byte)(unsafe.Pointer(&buf[0]))
+ bytes, err := ByteSliceFromString(name)
+ if err != nil {
+ return nil, err
+ }
+
+ // Magic sysctl: "setting" 0.3 to a string name
+ // lets you read back the array of integers form.
+ if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil {
+ return nil, err
+ }
+ return buf[0 : n/siz], nil
+}
+
+func direntIno(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
+}
+
+func direntReclen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
+}
+
+func direntNamlen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))
+}
+
+//sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
+func PtraceAttach(pid int) (err error) { return ptrace(PT_ATTACH, pid, 0, 0) }
+func PtraceDetach(pid int) (err error) { return ptrace(PT_DETACH, pid, 0, 0) }
+
+const (
+ attrBitMapCount = 5
+ attrCmnFullpath = 0x08000000
+)
+
+type attrList struct {
+ bitmapCount uint16
+ _ uint16
+ CommonAttr uint32
+ VolAttr uint32
+ DirAttr uint32
+ FileAttr uint32
+ Forkattr uint32
+}
+
+func getAttrList(path string, attrList attrList, attrBuf []byte, options uint) (attrs [][]byte, err error) {
+ if len(attrBuf) < 4 {
+ return nil, errorspkg.New("attrBuf too small")
+ }
+ attrList.bitmapCount = attrBitMapCount
+
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return nil, err
+ }
+
+ _, _, e1 := Syscall6(
+ SYS_GETATTRLIST,
+ uintptr(unsafe.Pointer(_p0)),
+ uintptr(unsafe.Pointer(&attrList)),
+ uintptr(unsafe.Pointer(&attrBuf[0])),
+ uintptr(len(attrBuf)),
+ uintptr(options),
+ 0,
+ )
+ if e1 != 0 {
+ return nil, e1
+ }
+ size := *(*uint32)(unsafe.Pointer(&attrBuf[0]))
+
+ // dat is the section of attrBuf that contains valid data,
+ // without the 4 byte length header. All attribute offsets
+ // are relative to dat.
+ dat := attrBuf
+ if int(size) < len(attrBuf) {
+ dat = dat[:size]
+ }
+ dat = dat[4:] // remove length prefix
+
+ for i := uint32(0); int(i) < len(dat); {
+ header := dat[i:]
+ if len(header) < 8 {
+ return attrs, errorspkg.New("truncated attribute header")
+ }
+ datOff := *(*int32)(unsafe.Pointer(&header[0]))
+ attrLen := *(*uint32)(unsafe.Pointer(&header[4]))
+ if datOff < 0 || uint32(datOff)+attrLen > uint32(len(dat)) {
+ return attrs, errorspkg.New("truncated results; attrBuf too small")
+ }
+ end := uint32(datOff) + attrLen
+ attrs = append(attrs, dat[datOff:end])
+ i = end
+ if r := i % 4; r != 0 {
+ i += (4 - r)
+ }
+ }
+ return
+}
+
+//sysnb pipe() (r int, w int, err error)
+
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ p[0], p[1], err = pipe()
+ return
+}
+
+func Getfsstat(buf []Statfs_t, flags int) (n int, err error) {
+ var _p0 unsafe.Pointer
+ var bufsize uintptr
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf))
+ }
+ r0, _, e1 := Syscall(SYS_GETFSSTAT64, uintptr(_p0), bufsize, uintptr(flags))
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func utimensat(dirfd int, path string, times *[2]Timespec, flags int) error {
+ // Darwin doesn't support SYS_UTIMENSAT
+ return ENOSYS
+}
+
+/*
+ * Wrapped
+ */
+
+//sys kill(pid int, signum int, posix int) (err error)
+
+func Kill(pid int, signum syscall.Signal) (err error) { return kill(pid, int(signum), 1) }
+
+//sys ioctl(fd int, req uint, arg uintptr) (err error)
+
+// ioctl itself should not be exposed directly, but additional get/set
+// functions for specific types are permissible.
+
+// IoctlSetInt performs an ioctl operation which sets an integer value
+// on fd, using the specified request number.
+func IoctlSetInt(fd int, req uint, value int) error {
+ return ioctl(fd, req, uintptr(value))
+}
+
+func IoctlSetWinsize(fd int, req uint, value *Winsize) error {
+ return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
+}
+
+func IoctlSetTermios(fd int, req uint, value *Termios) error {
+ return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
+}
+
+// IoctlGetInt performs an ioctl operation which gets an integer value
+// from fd, using the specified request number.
+func IoctlGetInt(fd int, req uint) (int, error) {
+ var value int
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return value, err
+}
+
+func IoctlGetWinsize(fd int, req uint) (*Winsize, error) {
+ var value Winsize
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return &value, err
+}
+
+func IoctlGetTermios(fd int, req uint) (*Termios, error) {
+ var value Termios
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return &value, err
+}
+
+/*
+ * Exposed directly
+ */
+//sys Access(path string, mode uint32) (err error)
+//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error)
+//sys Chdir(path string) (err error)
+//sys Chflags(path string, flags int) (err error)
+//sys Chmod(path string, mode uint32) (err error)
+//sys Chown(path string, uid int, gid int) (err error)
+//sys Chroot(path string) (err error)
+//sys Close(fd int) (err error)
+//sys Dup(fd int) (nfd int, err error)
+//sys Dup2(from int, to int) (err error)
+//sys Exchangedata(path1 string, path2 string, options int) (err error)
+//sys Exit(code int)
+//sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error)
+//sys Fchdir(fd int) (err error)
+//sys Fchflags(fd int, flags int) (err error)
+//sys Fchmod(fd int, mode uint32) (err error)
+//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
+//sys Flock(fd int, how int) (err error)
+//sys Fpathconf(fd int, name int) (val int, err error)
+//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
+//sys Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64
+//sys Fsync(fd int) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) = SYS_GETDIRENTRIES64
+//sys Getdtablesize() (size int)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (uid int)
+//sysnb Getgid() (gid int)
+//sysnb Getpgid(pid int) (pgid int, err error)
+//sysnb Getpgrp() (pgrp int)
+//sysnb Getpid() (pid int)
+//sysnb Getppid() (ppid int)
+//sys Getpriority(which int, who int) (prio int, err error)
+//sysnb Getrlimit(which int, lim *Rlimit) (err error)
+//sysnb Getrusage(who int, rusage *Rusage) (err error)
+//sysnb Getsid(pid int) (sid int, err error)
+//sysnb Getuid() (uid int)
+//sysnb Issetugid() (tainted bool)
+//sys Kqueue() (fd int, err error)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Link(path string, link string) (err error)
+//sys Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error)
+//sys Listen(s int, backlog int) (err error)
+//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64
+//sys Mkdir(path string, mode uint32) (err error)
+//sys Mkdirat(dirfd int, path string, mode uint32) (err error)
+//sys Mkfifo(path string, mode uint32) (err error)
+//sys Mknod(path string, mode uint32, dev int) (err error)
+//sys Open(path string, mode int, perm uint32) (fd int, err error)
+//sys Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error)
+//sys Pathconf(path string, name int) (val int, err error)
+//sys Pread(fd int, p []byte, offset int64) (n int, err error)
+//sys Pwrite(fd int, p []byte, offset int64) (n int, err error)
+//sys read(fd int, p []byte) (n int, err error)
+//sys Readlink(path string, buf []byte) (n int, err error)
+//sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
+//sys Rename(from string, to string) (err error)
+//sys Renameat(fromfd int, from string, tofd int, to string) (err error)
+//sys Revoke(path string) (err error)
+//sys Rmdir(path string) (err error)
+//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK
+//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error)
+//sys Setegid(egid int) (err error)
+//sysnb Seteuid(euid int) (err error)
+//sysnb Setgid(gid int) (err error)
+//sys Setlogin(name string) (err error)
+//sysnb Setpgid(pid int, pgid int) (err error)
+//sys Setpriority(which int, who int, prio int) (err error)
+//sys Setprivexec(flag int) (err error)
+//sysnb Setregid(rgid int, egid int) (err error)
+//sysnb Setreuid(ruid int, euid int) (err error)
+//sysnb Setrlimit(which int, lim *Rlimit) (err error)
+//sysnb Setsid() (pid int, err error)
+//sysnb Settimeofday(tp *Timeval) (err error)
+//sysnb Setuid(uid int) (err error)
+//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64
+//sys Statfs(path string, stat *Statfs_t) (err error) = SYS_STATFS64
+//sys Symlink(path string, link string) (err error)
+//sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
+//sys Sync() (err error)
+//sys Truncate(path string, length int64) (err error)
+//sys Umask(newmask int) (oldmask int)
+//sys Undelete(path string) (err error)
+//sys Unlink(path string) (err error)
+//sys Unlinkat(dirfd int, path string, flags int) (err error)
+//sys Unmount(path string, flags int) (err error)
+//sys write(fd int, p []byte) (n int, err error)
+//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
+//sys munmap(addr uintptr, length uintptr) (err error)
+//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ
+//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE
+
+/*
+ * Unimplemented
+ */
+// Profil
+// Sigaction
+// Sigprocmask
+// Getlogin
+// Sigpending
+// Sigaltstack
+// Ioctl
+// Reboot
+// Execve
+// Vfork
+// Sbrk
+// Sstk
+// Ovadvise
+// Mincore
+// Setitimer
+// Swapon
+// Select
+// Sigsuspend
+// Readv
+// Writev
+// Nfssvc
+// Getfh
+// Quotactl
+// Mount
+// Csops
+// Waitid
+// Add_profil
+// Kdebug_trace
+// Sigreturn
+// Atsocket
+// Kqueue_from_portset_np
+// Kqueue_portset
+// Getattrlist
+// Setattrlist
+// Getdirentriesattr
+// Searchfs
+// Delete
+// Copyfile
+// Poll
+// Watchevent
+// Waitevent
+// Modwatch
+// Getxattr
+// Fgetxattr
+// Setxattr
+// Fsetxattr
+// Removexattr
+// Fremovexattr
+// Listxattr
+// Flistxattr
+// Fsctl
+// Initgroups
+// Posix_spawn
+// Nfsclnt
+// Fhopen
+// Minherit
+// Semsys
+// Msgsys
+// Shmsys
+// Semctl
+// Semget
+// Semop
+// Msgctl
+// Msgget
+// Msgsnd
+// Msgrcv
+// Shmat
+// Shmctl
+// Shmdt
+// Shmget
+// Shm_open
+// Shm_unlink
+// Sem_open
+// Sem_close
+// Sem_unlink
+// Sem_wait
+// Sem_trywait
+// Sem_post
+// Sem_getvalue
+// Sem_init
+// Sem_destroy
+// Open_extended
+// Umask_extended
+// Stat_extended
+// Lstat_extended
+// Fstat_extended
+// Chmod_extended
+// Fchmod_extended
+// Access_extended
+// Settid
+// Gettid
+// Setsgroups
+// Getsgroups
+// Setwgroups
+// Getwgroups
+// Mkfifo_extended
+// Mkdir_extended
+// Identitysvc
+// Shared_region_check_np
+// Shared_region_map_np
+// __pthread_mutex_destroy
+// __pthread_mutex_init
+// __pthread_mutex_lock
+// __pthread_mutex_trylock
+// __pthread_mutex_unlock
+// __pthread_cond_init
+// __pthread_cond_destroy
+// __pthread_cond_broadcast
+// __pthread_cond_signal
+// Setsid_with_pid
+// __pthread_cond_timedwait
+// Aio_fsync
+// Aio_return
+// Aio_suspend
+// Aio_cancel
+// Aio_error
+// Aio_read
+// Aio_write
+// Lio_listio
+// __pthread_cond_wait
+// Iopolicysys
+// __pthread_kill
+// __pthread_sigmask
+// __sigwait
+// __disable_threadsignal
+// __pthread_markcancel
+// __pthread_canceled
+// __semwait_signal
+// Proc_info
+// sendfile
+// Stat64_extended
+// Lstat64_extended
+// Fstat64_extended
+// __pthread_chdir
+// __pthread_fchdir
+// Audit
+// Auditon
+// Getauid
+// Setauid
+// Getaudit
+// Setaudit
+// Getaudit_addr
+// Setaudit_addr
+// Auditctl
+// Bsdthread_create
+// Bsdthread_terminate
+// Stack_snapshot
+// Bsdthread_register
+// Workq_open
+// Workq_ops
+// __mac_execve
+// __mac_syscall
+// __mac_get_file
+// __mac_set_file
+// __mac_get_link
+// __mac_set_link
+// __mac_get_proc
+// __mac_set_proc
+// __mac_get_fd
+// __mac_set_fd
+// __mac_get_pid
+// __mac_get_lcid
+// __mac_get_lctx
+// __mac_set_lctx
+// Setlcid
+// Read_nocancel
+// Write_nocancel
+// Open_nocancel
+// Close_nocancel
+// Wait4_nocancel
+// Recvmsg_nocancel
+// Sendmsg_nocancel
+// Recvfrom_nocancel
+// Accept_nocancel
+// Fcntl_nocancel
+// Select_nocancel
+// Fsync_nocancel
+// Connect_nocancel
+// Sigsuspend_nocancel
+// Readv_nocancel
+// Writev_nocancel
+// Sendto_nocancel
+// Pread_nocancel
+// Pwrite_nocancel
+// Waitid_nocancel
+// Poll_nocancel
+// Msgsnd_nocancel
+// Msgrcv_nocancel
+// Sem_wait_nocancel
+// Aio_suspend_nocancel
+// __sigwait_nocancel
+// __semwait_signal_nocancel
+// __mac_mount
+// __mac_get_mount
+// __mac_getfsstat
diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin_386.go b/vendor/golang.org/x/sys/unix/syscall_darwin_386.go
new file mode 100644
index 0000000..c172a3d
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_darwin_386.go
@@ -0,0 +1,77 @@
+// Copyright 2009 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 386,darwin
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func Getpagesize() int { return 4096 }
+
+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.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = int32(nsec / 1e9)
+ return
+}
+
+//sysnb gettimeofday(tp *Timeval) (sec int32, usec int32, err error)
+func Gettimeofday(tv *Timeval) (err error) {
+ // The tv passed to gettimeofday must be non-nil
+ // but is otherwise unused. The answers come back
+ // in the two registers.
+ sec, usec, err := gettimeofday(tv)
+ tv.Sec = int32(sec)
+ tv.Usec = int32(usec)
+ return err
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint32(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+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)
+}
+
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ var length = uint64(count)
+
+ _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(*offset>>32), uintptr(unsafe.Pointer(&length)), 0, 0, 0, 0)
+
+ written = int(length)
+
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
+
+// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions
+// of darwin/386 the syscall is called sysctl instead of __sysctl.
+const SYS___SYSCTL = SYS_SYSCTL
diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go
new file mode 100644
index 0000000..c6c99c1
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go
@@ -0,0 +1,77 @@
+// Copyright 2009 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,darwin
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func Getpagesize() int { return 4096 }
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = int64(nsec / 1e9)
+ return
+}
+
+//sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error)
+func Gettimeofday(tv *Timeval) (err error) {
+ // The tv passed to gettimeofday must be non-nil
+ // but is otherwise unused. The answers come back
+ // in the two registers.
+ sec, usec, err := gettimeofday(tv)
+ tv.Sec = sec
+ tv.Usec = usec
+ return err
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint64(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint32(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint32(length)
+}
+
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ var length = uint64(count)
+
+ _, _, e1 := Syscall6(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(unsafe.Pointer(&length)), 0, 0)
+
+ written = int(length)
+
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
+
+// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions
+// of darwin/amd64 the syscall is called sysctl instead of __sysctl.
+const SYS___SYSCTL = SYS_SYSCTL
diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go b/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go
new file mode 100644
index 0000000..d286cf4
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go
@@ -0,0 +1,71 @@
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func Getpagesize() int { return 4096 }
+
+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.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = int32(nsec / 1e9)
+ return
+}
+
+//sysnb gettimeofday(tp *Timeval) (sec int32, usec int32, err error)
+func Gettimeofday(tv *Timeval) (err error) {
+ // The tv passed to gettimeofday must be non-nil
+ // but is otherwise unused. The answers come back
+ // in the two registers.
+ sec, usec, err := gettimeofday(tv)
+ tv.Sec = int32(sec)
+ tv.Usec = int32(usec)
+ return err
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint32(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+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)
+}
+
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ var length = uint64(count)
+
+ _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(*offset>>32), uintptr(unsafe.Pointer(&length)), 0, 0, 0, 0)
+
+ written = int(length)
+
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // sic
diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go
new file mode 100644
index 0000000..c33905c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go
@@ -0,0 +1,77 @@
+// Copyright 2015 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 arm64,darwin
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func Getpagesize() int { return 16384 }
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = int64(nsec / 1e9)
+ return
+}
+
+//sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error)
+func Gettimeofday(tv *Timeval) (err error) {
+ // The tv passed to gettimeofday must be non-nil
+ // but is otherwise unused. The answers come back
+ // in the two registers.
+ sec, usec, err := gettimeofday(tv)
+ tv.Sec = sec
+ tv.Usec = usec
+ return err
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint64(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint32(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint32(length)
+}
+
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ var length = uint64(count)
+
+ _, _, e1 := Syscall6(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(unsafe.Pointer(&length)), 0, 0)
+
+ written = int(length)
+
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // sic
+
+// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions
+// of darwin/arm64 the syscall is called sysctl instead of __sysctl.
+const SYS___SYSCTL = SYS_SYSCTL
diff --git a/vendor/golang.org/x/sys/unix/syscall_dragonfly.go b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go
new file mode 100644
index 0000000..3a48337
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go
@@ -0,0 +1,415 @@
+// Copyright 2009 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.
+
+// DragonFly BSD system calls.
+// This file is compiled as ordinary Go code,
+// but it is also input to mksyscall,
+// which parses the //sys lines and generates system call stubs.
+// Note that sometimes we use a lowercase //sys name and wrap
+// it in our own nicer implementation, either here or in
+// syscall_bsd.go or syscall_unix.go.
+
+package unix
+
+import "unsafe"
+
+type SockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+ Rcf uint16
+ Route [16]uint16
+ raw RawSockaddrDatalink
+}
+
+// Translate "kern.hostname" to []_C_int{0,1,2,3}.
+func nametomib(name string) (mib []_C_int, err error) {
+ const siz = unsafe.Sizeof(mib[0])
+
+ // NOTE(rsc): It seems strange to set the buffer to have
+ // size CTL_MAXNAME+2 but use only CTL_MAXNAME
+ // as the size. I don't know why the +2 is here, but the
+ // kernel uses +2 for its own implementation of this function.
+ // I am scared that if we don't include the +2 here, the kernel
+ // will silently write 2 words farther than we specify
+ // and we'll get memory corruption.
+ var buf [CTL_MAXNAME + 2]_C_int
+ n := uintptr(CTL_MAXNAME) * siz
+
+ p := (*byte)(unsafe.Pointer(&buf[0]))
+ bytes, err := ByteSliceFromString(name)
+ if err != nil {
+ return nil, err
+ }
+
+ // Magic sysctl: "setting" 0.3 to a string name
+ // lets you read back the array of integers form.
+ if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil {
+ return nil, err
+ }
+ return buf[0 : n/siz], nil
+}
+
+func direntIno(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno))
+}
+
+func direntReclen(buf []byte) (uint64, bool) {
+ namlen, ok := direntNamlen(buf)
+ if !ok {
+ return 0, false
+ }
+ return (16 + namlen + 1 + 7) &^ 7, true
+}
+
+func direntNamlen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))
+}
+
+//sysnb pipe() (r int, w int, err error)
+
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ p[0], p[1], err = pipe()
+ return
+}
+
+//sys extpread(fd int, p []byte, flags int, offset int64) (n int, err error)
+func Pread(fd int, p []byte, offset int64) (n int, err error) {
+ return extpread(fd, p, 0, offset)
+}
+
+//sys extpwrite(fd int, p []byte, flags int, offset int64) (n int, err error)
+func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
+ return extpwrite(fd, p, 0, offset)
+}
+
+func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ nfd, err = accept4(fd, &rsa, &len, flags)
+ if err != nil {
+ return
+ }
+ if len > SizeofSockaddrAny {
+ panic("RawSockaddrAny too small")
+ }
+ sa, err = anyToSockaddr(&rsa)
+ if err != nil {
+ Close(nfd)
+ nfd = 0
+ }
+ return
+}
+
+func Getfsstat(buf []Statfs_t, flags int) (n int, err error) {
+ var _p0 unsafe.Pointer
+ var bufsize uintptr
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf))
+ }
+ r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags))
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+/*
+ * Exposed directly
+ */
+//sys Access(path string, mode uint32) (err error)
+//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error)
+//sys Chdir(path string) (err error)
+//sys Chflags(path string, flags int) (err error)
+//sys Chmod(path string, mode uint32) (err error)
+//sys Chown(path string, uid int, gid int) (err error)
+//sys Chroot(path string) (err error)
+//sys Close(fd int) (err error)
+//sys Dup(fd int) (nfd int, err error)
+//sys Dup2(from int, to int) (err error)
+//sys Exit(code int)
+//sys Fchdir(fd int) (err error)
+//sys Fchflags(fd int, flags int) (err error)
+//sys Fchmod(fd int, mode uint32) (err error)
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Flock(fd int, how int) (err error)
+//sys Fpathconf(fd int, name int) (val int, err error)
+//sys Fstat(fd int, stat *Stat_t) (err error)
+//sys Fstatfs(fd int, stat *Statfs_t) (err error)
+//sys Fsync(fd int) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error)
+//sys Getdtablesize() (size int)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (uid int)
+//sysnb Getgid() (gid int)
+//sysnb Getpgid(pid int) (pgid int, err error)
+//sysnb Getpgrp() (pgrp int)
+//sysnb Getpid() (pid int)
+//sysnb Getppid() (ppid int)
+//sys Getpriority(which int, who int) (prio int, err error)
+//sysnb Getrlimit(which int, lim *Rlimit) (err error)
+//sysnb Getrusage(who int, rusage *Rusage) (err error)
+//sysnb Getsid(pid int) (sid int, err error)
+//sysnb Gettimeofday(tv *Timeval) (err error)
+//sysnb Getuid() (uid int)
+//sys Issetugid() (tainted bool)
+//sys Kill(pid int, signum syscall.Signal) (err error)
+//sys Kqueue() (fd int, err error)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Link(path string, link string) (err error)
+//sys Listen(s int, backlog int) (err error)
+//sys Lstat(path string, stat *Stat_t) (err error)
+//sys Mkdir(path string, mode uint32) (err error)
+//sys Mkfifo(path string, mode uint32) (err error)
+//sys Mknod(path string, mode uint32, dev int) (err error)
+//sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
+//sys Open(path string, mode int, perm uint32) (fd int, err error)
+//sys Pathconf(path string, name int) (val int, err error)
+//sys read(fd int, p []byte) (n int, err error)
+//sys Readlink(path string, buf []byte) (n int, err error)
+//sys Rename(from string, to string) (err error)
+//sys Revoke(path string) (err error)
+//sys Rmdir(path string) (err error)
+//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK
+//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error)
+//sysnb Setegid(egid int) (err error)
+//sysnb Seteuid(euid int) (err error)
+//sysnb Setgid(gid int) (err error)
+//sys Setlogin(name string) (err error)
+//sysnb Setpgid(pid int, pgid int) (err error)
+//sys Setpriority(which int, who int, prio int) (err error)
+//sysnb Setregid(rgid int, egid int) (err error)
+//sysnb Setreuid(ruid int, euid int) (err error)
+//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
+//sysnb Setresuid(ruid int, euid int, suid int) (err error)
+//sysnb Setrlimit(which int, lim *Rlimit) (err error)
+//sysnb Setsid() (pid int, err error)
+//sysnb Settimeofday(tp *Timeval) (err error)
+//sysnb Setuid(uid int) (err error)
+//sys Stat(path string, stat *Stat_t) (err error)
+//sys Statfs(path string, stat *Statfs_t) (err error)
+//sys Symlink(path string, link string) (err error)
+//sys Sync() (err error)
+//sys Truncate(path string, length int64) (err error)
+//sys Umask(newmask int) (oldmask int)
+//sys Undelete(path string) (err error)
+//sys Unlink(path string) (err error)
+//sys Unmount(path string, flags int) (err error)
+//sys write(fd int, p []byte) (n int, err error)
+//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
+//sys munmap(addr uintptr, length uintptr) (err error)
+//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ
+//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE
+//sys accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error)
+//sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
+
+/*
+ * Unimplemented
+ * TODO(jsing): Update this list for DragonFly.
+ */
+// Profil
+// Sigaction
+// Sigprocmask
+// Getlogin
+// Sigpending
+// Sigaltstack
+// Ioctl
+// Reboot
+// Execve
+// Vfork
+// Sbrk
+// Sstk
+// Ovadvise
+// Mincore
+// Setitimer
+// Swapon
+// Select
+// Sigsuspend
+// Readv
+// Writev
+// Nfssvc
+// Getfh
+// Quotactl
+// Mount
+// Csops
+// Waitid
+// Add_profil
+// Kdebug_trace
+// Sigreturn
+// Atsocket
+// Kqueue_from_portset_np
+// Kqueue_portset
+// Getattrlist
+// Setattrlist
+// Getdirentriesattr
+// Searchfs
+// Delete
+// Copyfile
+// Poll
+// Watchevent
+// Waitevent
+// Modwatch
+// Getxattr
+// Fgetxattr
+// Setxattr
+// Fsetxattr
+// Removexattr
+// Fremovexattr
+// Listxattr
+// Flistxattr
+// Fsctl
+// Initgroups
+// Posix_spawn
+// Nfsclnt
+// Fhopen
+// Minherit
+// Semsys
+// Msgsys
+// Shmsys
+// Semctl
+// Semget
+// Semop
+// Msgctl
+// Msgget
+// Msgsnd
+// Msgrcv
+// Shmat
+// Shmctl
+// Shmdt
+// Shmget
+// Shm_open
+// Shm_unlink
+// Sem_open
+// Sem_close
+// Sem_unlink
+// Sem_wait
+// Sem_trywait
+// Sem_post
+// Sem_getvalue
+// Sem_init
+// Sem_destroy
+// Open_extended
+// Umask_extended
+// Stat_extended
+// Lstat_extended
+// Fstat_extended
+// Chmod_extended
+// Fchmod_extended
+// Access_extended
+// Settid
+// Gettid
+// Setsgroups
+// Getsgroups
+// Setwgroups
+// Getwgroups
+// Mkfifo_extended
+// Mkdir_extended
+// Identitysvc
+// Shared_region_check_np
+// Shared_region_map_np
+// __pthread_mutex_destroy
+// __pthread_mutex_init
+// __pthread_mutex_lock
+// __pthread_mutex_trylock
+// __pthread_mutex_unlock
+// __pthread_cond_init
+// __pthread_cond_destroy
+// __pthread_cond_broadcast
+// __pthread_cond_signal
+// Setsid_with_pid
+// __pthread_cond_timedwait
+// Aio_fsync
+// Aio_return
+// Aio_suspend
+// Aio_cancel
+// Aio_error
+// Aio_read
+// Aio_write
+// Lio_listio
+// __pthread_cond_wait
+// Iopolicysys
+// __pthread_kill
+// __pthread_sigmask
+// __sigwait
+// __disable_threadsignal
+// __pthread_markcancel
+// __pthread_canceled
+// __semwait_signal
+// Proc_info
+// Stat64_extended
+// Lstat64_extended
+// Fstat64_extended
+// __pthread_chdir
+// __pthread_fchdir
+// Audit
+// Auditon
+// Getauid
+// Setauid
+// Getaudit
+// Setaudit
+// Getaudit_addr
+// Setaudit_addr
+// Auditctl
+// Bsdthread_create
+// Bsdthread_terminate
+// Stack_snapshot
+// Bsdthread_register
+// Workq_open
+// Workq_ops
+// __mac_execve
+// __mac_syscall
+// __mac_get_file
+// __mac_set_file
+// __mac_get_link
+// __mac_set_link
+// __mac_get_proc
+// __mac_set_proc
+// __mac_get_fd
+// __mac_set_fd
+// __mac_get_pid
+// __mac_get_lcid
+// __mac_get_lctx
+// __mac_set_lctx
+// Setlcid
+// Read_nocancel
+// Write_nocancel
+// Open_nocancel
+// Close_nocancel
+// Wait4_nocancel
+// Recvmsg_nocancel
+// Sendmsg_nocancel
+// Recvfrom_nocancel
+// Accept_nocancel
+// Fcntl_nocancel
+// Select_nocancel
+// Fsync_nocancel
+// Connect_nocancel
+// Sigsuspend_nocancel
+// Readv_nocancel
+// Writev_nocancel
+// Sendto_nocancel
+// Pread_nocancel
+// Pwrite_nocancel
+// Waitid_nocancel
+// Poll_nocancel
+// Msgsnd_nocancel
+// Msgrcv_nocancel
+// Sem_wait_nocancel
+// Aio_suspend_nocancel
+// __sigwait_nocancel
+// __semwait_signal_nocancel
+// __mac_mount
+// __mac_get_mount
+// __mac_getfsstat
diff --git a/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go
new file mode 100644
index 0000000..da7cb79
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go
@@ -0,0 +1,61 @@
+// Copyright 2009 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,dragonfly
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func Getpagesize() int { return 4096 }
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = nsec % 1e9 / 1e3
+ tv.Sec = int64(nsec / 1e9)
+ return
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint64(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint32(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint32(length)
+}
+
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ var writtenOut uint64 = 0
+ _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0)
+
+ written = int(writtenOut)
+
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go
new file mode 100644
index 0000000..d26e52e
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_freebsd.go
@@ -0,0 +1,708 @@
+// Copyright 2009,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.
+
+// FreeBSD system calls.
+// This file is compiled as ordinary Go code,
+// but it is also input to mksyscall,
+// which parses the //sys lines and generates system call stubs.
+// Note that sometimes we use a lowercase //sys name and wrap
+// it in our own nicer implementation, either here or in
+// syscall_bsd.go or syscall_unix.go.
+
+package unix
+
+import "unsafe"
+
+type SockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [46]int8
+ raw RawSockaddrDatalink
+}
+
+// Translate "kern.hostname" to []_C_int{0,1,2,3}.
+func nametomib(name string) (mib []_C_int, err error) {
+ const siz = unsafe.Sizeof(mib[0])
+
+ // NOTE(rsc): It seems strange to set the buffer to have
+ // size CTL_MAXNAME+2 but use only CTL_MAXNAME
+ // as the size. I don't know why the +2 is here, but the
+ // kernel uses +2 for its own implementation of this function.
+ // I am scared that if we don't include the +2 here, the kernel
+ // will silently write 2 words farther than we specify
+ // and we'll get memory corruption.
+ var buf [CTL_MAXNAME + 2]_C_int
+ n := uintptr(CTL_MAXNAME) * siz
+
+ p := (*byte)(unsafe.Pointer(&buf[0]))
+ bytes, err := ByteSliceFromString(name)
+ if err != nil {
+ return nil, err
+ }
+
+ // Magic sysctl: "setting" 0.3 to a string name
+ // lets you read back the array of integers form.
+ if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil {
+ return nil, err
+ }
+ return buf[0 : n/siz], nil
+}
+
+func direntIno(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno))
+}
+
+func direntReclen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
+}
+
+func direntNamlen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))
+}
+
+//sysnb pipe() (r int, w int, err error)
+
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ p[0], p[1], err = pipe()
+ return
+}
+
+func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
+ var value IPMreqn
+ vallen := _Socklen(SizeofIPMreqn)
+ errno := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, errno
+}
+
+func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
+ return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
+}
+
+func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ nfd, err = accept4(fd, &rsa, &len, flags)
+ if err != nil {
+ return
+ }
+ if len > SizeofSockaddrAny {
+ panic("RawSockaddrAny too small")
+ }
+ sa, err = anyToSockaddr(&rsa)
+ if err != nil {
+ Close(nfd)
+ nfd = 0
+ }
+ return
+}
+
+func Getfsstat(buf []Statfs_t, flags int) (n int, err error) {
+ var _p0 unsafe.Pointer
+ var bufsize uintptr
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf))
+ }
+ r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags))
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+// Derive extattr namespace and attribute name
+
+func xattrnamespace(fullattr string) (ns int, attr string, err error) {
+ s := -1
+ for idx, val := range fullattr {
+ if val == '.' {
+ s = idx
+ break
+ }
+ }
+
+ if s == -1 {
+ return -1, "", ENOATTR
+ }
+
+ namespace := fullattr[0:s]
+ attr = fullattr[s+1:]
+
+ switch namespace {
+ case "user":
+ return EXTATTR_NAMESPACE_USER, attr, nil
+ case "system":
+ return EXTATTR_NAMESPACE_SYSTEM, attr, nil
+ default:
+ return -1, "", ENOATTR
+ }
+}
+
+func initxattrdest(dest []byte, idx int) (d unsafe.Pointer) {
+ if len(dest) > idx {
+ return unsafe.Pointer(&dest[idx])
+ } else {
+ return unsafe.Pointer(_zero)
+ }
+}
+
+// FreeBSD implements its own syscalls to handle extended attributes
+
+func Getxattr(file string, attr string, dest []byte) (sz int, err error) {
+ d := initxattrdest(dest, 0)
+ destsize := len(dest)
+
+ nsid, a, err := xattrnamespace(attr)
+ if err != nil {
+ return -1, err
+ }
+
+ return ExtattrGetFile(file, nsid, a, uintptr(d), destsize)
+}
+
+func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) {
+ d := initxattrdest(dest, 0)
+ destsize := len(dest)
+
+ nsid, a, err := xattrnamespace(attr)
+ if err != nil {
+ return -1, err
+ }
+
+ return ExtattrGetFd(fd, nsid, a, uintptr(d), destsize)
+}
+
+func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) {
+ d := initxattrdest(dest, 0)
+ destsize := len(dest)
+
+ nsid, a, err := xattrnamespace(attr)
+ if err != nil {
+ return -1, err
+ }
+
+ return ExtattrGetLink(link, nsid, a, uintptr(d), destsize)
+}
+
+// flags are unused on FreeBSD
+
+func Fsetxattr(fd int, attr string, data []byte, flags int) (err error) {
+ d := unsafe.Pointer(&data[0])
+ datasiz := len(data)
+
+ nsid, a, err := xattrnamespace(attr)
+ if err != nil {
+ return
+ }
+
+ _, err = ExtattrSetFd(fd, nsid, a, uintptr(d), datasiz)
+ return
+}
+
+func Setxattr(file string, attr string, data []byte, flags int) (err error) {
+ d := unsafe.Pointer(&data[0])
+ datasiz := len(data)
+
+ nsid, a, err := xattrnamespace(attr)
+ if err != nil {
+ return
+ }
+
+ _, err = ExtattrSetFile(file, nsid, a, uintptr(d), datasiz)
+ return
+}
+
+func Lsetxattr(link string, attr string, data []byte, flags int) (err error) {
+ d := unsafe.Pointer(&data[0])
+ datasiz := len(data)
+
+ nsid, a, err := xattrnamespace(attr)
+ if err != nil {
+ return
+ }
+
+ _, err = ExtattrSetLink(link, nsid, a, uintptr(d), datasiz)
+ return
+}
+
+func Removexattr(file string, attr string) (err error) {
+ nsid, a, err := xattrnamespace(attr)
+ if err != nil {
+ return
+ }
+
+ err = ExtattrDeleteFile(file, nsid, a)
+ return
+}
+
+func Fremovexattr(fd int, attr string) (err error) {
+ nsid, a, err := xattrnamespace(attr)
+ if err != nil {
+ return
+ }
+
+ err = ExtattrDeleteFd(fd, nsid, a)
+ return
+}
+
+func Lremovexattr(link string, attr string) (err error) {
+ nsid, a, err := xattrnamespace(attr)
+ if err != nil {
+ return
+ }
+
+ err = ExtattrDeleteLink(link, nsid, a)
+ return
+}
+
+func Listxattr(file string, dest []byte) (sz int, err error) {
+ d := initxattrdest(dest, 0)
+ destsiz := len(dest)
+
+ // FreeBSD won't allow you to list xattrs from multiple namespaces
+ s := 0
+ var e error
+ for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} {
+ stmp, e := ExtattrListFile(file, nsid, uintptr(d), destsiz)
+
+ /* Errors accessing system attrs are ignored so that
+ * we can implement the Linux-like behavior of omitting errors that
+ * we don't have read permissions on
+ *
+ * Linux will still error if we ask for user attributes on a file that
+ * we don't have read permissions on, so don't ignore those errors
+ */
+ if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER {
+ e = nil
+ continue
+ } else if e != nil {
+ return s, e
+ }
+
+ s += stmp
+ destsiz -= s
+ if destsiz < 0 {
+ destsiz = 0
+ }
+ d = initxattrdest(dest, s)
+ }
+
+ return s, e
+}
+
+func Flistxattr(fd int, dest []byte) (sz int, err error) {
+ d := initxattrdest(dest, 0)
+ destsiz := len(dest)
+
+ s := 0
+ var e error
+ for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} {
+ stmp, e := ExtattrListFd(fd, nsid, uintptr(d), destsiz)
+ if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER {
+ e = nil
+ continue
+ } else if e != nil {
+ return s, e
+ }
+
+ s += stmp
+ destsiz -= s
+ if destsiz < 0 {
+ destsiz = 0
+ }
+ d = initxattrdest(dest, s)
+ }
+
+ return s, e
+}
+
+func Llistxattr(link string, dest []byte) (sz int, err error) {
+ d := initxattrdest(dest, 0)
+ destsiz := len(dest)
+
+ s := 0
+ var e error
+ for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} {
+ stmp, e := ExtattrListLink(link, nsid, uintptr(d), destsiz)
+ if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER {
+ e = nil
+ continue
+ } else if e != nil {
+ return s, e
+ }
+
+ s += stmp
+ destsiz -= s
+ if destsiz < 0 {
+ destsiz = 0
+ }
+ d = initxattrdest(dest, s)
+ }
+
+ return s, e
+}
+
+//sys ioctl(fd int, req uint, arg uintptr) (err error)
+
+// ioctl itself should not be exposed directly, but additional get/set
+// functions for specific types are permissible.
+
+// IoctlSetInt performs an ioctl operation which sets an integer value
+// on fd, using the specified request number.
+func IoctlSetInt(fd int, req uint, value int) error {
+ return ioctl(fd, req, uintptr(value))
+}
+
+func IoctlSetWinsize(fd int, req uint, value *Winsize) error {
+ return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
+}
+
+func IoctlSetTermios(fd int, req uint, value *Termios) error {
+ return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
+}
+
+// IoctlGetInt performs an ioctl operation which gets an integer value
+// from fd, using the specified request number.
+func IoctlGetInt(fd int, req uint) (int, error) {
+ var value int
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return value, err
+}
+
+func IoctlGetWinsize(fd int, req uint) (*Winsize, error) {
+ var value Winsize
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return &value, err
+}
+
+func IoctlGetTermios(fd int, req uint) (*Termios, error) {
+ var value Termios
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return &value, err
+}
+
+/*
+ * Exposed directly
+ */
+//sys Access(path string, mode uint32) (err error)
+//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error)
+//sys CapEnter() (err error)
+//sys capRightsGet(version int, fd int, rightsp *CapRights) (err error) = SYS___CAP_RIGHTS_GET
+//sys capRightsLimit(fd int, rightsp *CapRights) (err error)
+//sys Chdir(path string) (err error)
+//sys Chflags(path string, flags int) (err error)
+//sys Chmod(path string, mode uint32) (err error)
+//sys Chown(path string, uid int, gid int) (err error)
+//sys Chroot(path string) (err error)
+//sys Close(fd int) (err error)
+//sys Dup(fd int) (nfd int, err error)
+//sys Dup2(from int, to int) (err error)
+//sys Exit(code int)
+//sys ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error)
+//sys ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error)
+//sys ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error)
+//sys ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error)
+//sys ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error)
+//sys ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error)
+//sys ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error)
+//sys ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error)
+//sys ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error)
+//sys ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error)
+//sys ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error)
+//sys ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error)
+//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_POSIX_FADVISE
+//sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error)
+//sys Fchdir(fd int) (err error)
+//sys Fchflags(fd int, flags int) (err error)
+//sys Fchmod(fd int, mode uint32) (err error)
+//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
+//sys Flock(fd int, how int) (err error)
+//sys Fpathconf(fd int, name int) (val int, err error)
+//sys Fstat(fd int, stat *Stat_t) (err error)
+//sys Fstatfs(fd int, stat *Statfs_t) (err error)
+//sys Fsync(fd int) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error)
+//sys Getdtablesize() (size int)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (uid int)
+//sysnb Getgid() (gid int)
+//sysnb Getpgid(pid int) (pgid int, err error)
+//sysnb Getpgrp() (pgrp int)
+//sysnb Getpid() (pid int)
+//sysnb Getppid() (ppid int)
+//sys Getpriority(which int, who int) (prio int, err error)
+//sysnb Getrlimit(which int, lim *Rlimit) (err error)
+//sysnb Getrusage(who int, rusage *Rusage) (err error)
+//sysnb Getsid(pid int) (sid int, err error)
+//sysnb Gettimeofday(tv *Timeval) (err error)
+//sysnb Getuid() (uid int)
+//sys Issetugid() (tainted bool)
+//sys Kill(pid int, signum syscall.Signal) (err error)
+//sys Kqueue() (fd int, err error)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Link(path string, link string) (err error)
+//sys Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error)
+//sys Listen(s int, backlog int) (err error)
+//sys Lstat(path string, stat *Stat_t) (err error)
+//sys Mkdir(path string, mode uint32) (err error)
+//sys Mkdirat(dirfd int, path string, mode uint32) (err error)
+//sys Mkfifo(path string, mode uint32) (err error)
+//sys Mknod(path string, mode uint32, dev int) (err error)
+//sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
+//sys Open(path string, mode int, perm uint32) (fd int, err error)
+//sys Openat(fdat int, path string, mode int, perm uint32) (fd int, err error)
+//sys Pathconf(path string, name int) (val int, err error)
+//sys Pread(fd int, p []byte, offset int64) (n int, err error)
+//sys Pwrite(fd int, p []byte, offset int64) (n int, err error)
+//sys read(fd int, p []byte) (n int, err error)
+//sys Readlink(path string, buf []byte) (n int, err error)
+//sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
+//sys Rename(from string, to string) (err error)
+//sys Renameat(fromfd int, from string, tofd int, to string) (err error)
+//sys Revoke(path string) (err error)
+//sys Rmdir(path string) (err error)
+//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK
+//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error)
+//sysnb Setegid(egid int) (err error)
+//sysnb Seteuid(euid int) (err error)
+//sysnb Setgid(gid int) (err error)
+//sys Setlogin(name string) (err error)
+//sysnb Setpgid(pid int, pgid int) (err error)
+//sys Setpriority(which int, who int, prio int) (err error)
+//sysnb Setregid(rgid int, egid int) (err error)
+//sysnb Setreuid(ruid int, euid int) (err error)
+//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
+//sysnb Setresuid(ruid int, euid int, suid int) (err error)
+//sysnb Setrlimit(which int, lim *Rlimit) (err error)
+//sysnb Setsid() (pid int, err error)
+//sysnb Settimeofday(tp *Timeval) (err error)
+//sysnb Setuid(uid int) (err error)
+//sys Stat(path string, stat *Stat_t) (err error)
+//sys Statfs(path string, stat *Statfs_t) (err error)
+//sys Symlink(path string, link string) (err error)
+//sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
+//sys Sync() (err error)
+//sys Truncate(path string, length int64) (err error)
+//sys Umask(newmask int) (oldmask int)
+//sys Undelete(path string) (err error)
+//sys Unlink(path string) (err error)
+//sys Unlinkat(dirfd int, path string, flags int) (err error)
+//sys Unmount(path string, flags int) (err error)
+//sys write(fd int, p []byte) (n int, err error)
+//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
+//sys munmap(addr uintptr, length uintptr) (err error)
+//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ
+//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE
+//sys accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error)
+//sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
+
+/*
+ * Unimplemented
+ */
+// Profil
+// Sigaction
+// Sigprocmask
+// Getlogin
+// Sigpending
+// Sigaltstack
+// Ioctl
+// Reboot
+// Execve
+// Vfork
+// Sbrk
+// Sstk
+// Ovadvise
+// Mincore
+// Setitimer
+// Swapon
+// Select
+// Sigsuspend
+// Readv
+// Writev
+// Nfssvc
+// Getfh
+// Quotactl
+// Mount
+// Csops
+// Waitid
+// Add_profil
+// Kdebug_trace
+// Sigreturn
+// Atsocket
+// Kqueue_from_portset_np
+// Kqueue_portset
+// Getattrlist
+// Setattrlist
+// Getdirentriesattr
+// Searchfs
+// Delete
+// Copyfile
+// Poll
+// Watchevent
+// Waitevent
+// Modwatch
+// Getxattr
+// Fgetxattr
+// Setxattr
+// Fsetxattr
+// Removexattr
+// Fremovexattr
+// Listxattr
+// Flistxattr
+// Fsctl
+// Initgroups
+// Posix_spawn
+// Nfsclnt
+// Fhopen
+// Minherit
+// Semsys
+// Msgsys
+// Shmsys
+// Semctl
+// Semget
+// Semop
+// Msgctl
+// Msgget
+// Msgsnd
+// Msgrcv
+// Shmat
+// Shmctl
+// Shmdt
+// Shmget
+// Shm_open
+// Shm_unlink
+// Sem_open
+// Sem_close
+// Sem_unlink
+// Sem_wait
+// Sem_trywait
+// Sem_post
+// Sem_getvalue
+// Sem_init
+// Sem_destroy
+// Open_extended
+// Umask_extended
+// Stat_extended
+// Lstat_extended
+// Fstat_extended
+// Chmod_extended
+// Fchmod_extended
+// Access_extended
+// Settid
+// Gettid
+// Setsgroups
+// Getsgroups
+// Setwgroups
+// Getwgroups
+// Mkfifo_extended
+// Mkdir_extended
+// Identitysvc
+// Shared_region_check_np
+// Shared_region_map_np
+// __pthread_mutex_destroy
+// __pthread_mutex_init
+// __pthread_mutex_lock
+// __pthread_mutex_trylock
+// __pthread_mutex_unlock
+// __pthread_cond_init
+// __pthread_cond_destroy
+// __pthread_cond_broadcast
+// __pthread_cond_signal
+// Setsid_with_pid
+// __pthread_cond_timedwait
+// Aio_fsync
+// Aio_return
+// Aio_suspend
+// Aio_cancel
+// Aio_error
+// Aio_read
+// Aio_write
+// Lio_listio
+// __pthread_cond_wait
+// Iopolicysys
+// __pthread_kill
+// __pthread_sigmask
+// __sigwait
+// __disable_threadsignal
+// __pthread_markcancel
+// __pthread_canceled
+// __semwait_signal
+// Proc_info
+// Stat64_extended
+// Lstat64_extended
+// Fstat64_extended
+// __pthread_chdir
+// __pthread_fchdir
+// Audit
+// Auditon
+// Getauid
+// Setauid
+// Getaudit
+// Setaudit
+// Getaudit_addr
+// Setaudit_addr
+// Auditctl
+// Bsdthread_create
+// Bsdthread_terminate
+// Stack_snapshot
+// Bsdthread_register
+// Workq_open
+// Workq_ops
+// __mac_execve
+// __mac_syscall
+// __mac_get_file
+// __mac_set_file
+// __mac_get_link
+// __mac_set_link
+// __mac_get_proc
+// __mac_set_proc
+// __mac_get_fd
+// __mac_set_fd
+// __mac_get_pid
+// __mac_get_lcid
+// __mac_get_lctx
+// __mac_set_lctx
+// Setlcid
+// Read_nocancel
+// Write_nocancel
+// Open_nocancel
+// Close_nocancel
+// Wait4_nocancel
+// Recvmsg_nocancel
+// Sendmsg_nocancel
+// Recvfrom_nocancel
+// Accept_nocancel
+// Fcntl_nocancel
+// Select_nocancel
+// Fsync_nocancel
+// Connect_nocancel
+// Sigsuspend_nocancel
+// Readv_nocancel
+// Writev_nocancel
+// Sendto_nocancel
+// Pread_nocancel
+// Pwrite_nocancel
+// Waitid_nocancel
+// Poll_nocancel
+// Msgsnd_nocancel
+// Msgrcv_nocancel
+// Sem_wait_nocancel
+// Aio_suspend_nocancel
+// __sigwait_nocancel
+// __semwait_signal_nocancel
+// __mac_mount
+// __mac_get_mount
+// __mac_getfsstat
diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go
new file mode 100644
index 0000000..6a0cd80
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go
@@ -0,0 +1,61 @@
+// Copyright 2009 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 386,freebsd
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func Getpagesize() int { return 4096 }
+
+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.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = int32(nsec / 1e9)
+ return
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint32(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+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)
+}
+
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ var writtenOut uint64 = 0
+ _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0)
+
+ written = int(writtenOut)
+
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go
new file mode 100644
index 0000000..e142540
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go
@@ -0,0 +1,61 @@
+// Copyright 2009 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,freebsd
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func Getpagesize() int { return 4096 }
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = nsec % 1e9 / 1e3
+ tv.Sec = int64(nsec / 1e9)
+ return
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint64(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint32(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint32(length)
+}
+
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ var writtenOut uint64 = 0
+ _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0)
+
+ written = int(writtenOut)
+
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go
new file mode 100644
index 0000000..5504cb1
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go
@@ -0,0 +1,61 @@
+// 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 arm,freebsd
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func Getpagesize() int { return 4096 }
+
+func TimespecToNsec(ts Timespec) int64 { return ts.Sec*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = int32(nsec % 1e9)
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = nsec / 1e9
+ return
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint32(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+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)
+}
+
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ var writtenOut uint64 = 0
+ _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0)
+
+ written = int(writtenOut)
+
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go
new file mode 100644
index 0000000..2afe62b
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_linux.go
@@ -0,0 +1,1459 @@
+// Copyright 2009 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.
+
+// Linux system calls.
+// This file is compiled as ordinary Go code,
+// but it is also input to mksyscall,
+// which parses the //sys lines and generates system call stubs.
+// Note that sometimes we use a lowercase //sys name and
+// wrap it in our own nicer implementation.
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+/*
+ * Wrapped
+ */
+
+func Access(path string, mode uint32) (err error) {
+ return Faccessat(AT_FDCWD, path, mode, 0)
+}
+
+func Chmod(path string, mode uint32) (err error) {
+ return Fchmodat(AT_FDCWD, path, mode, 0)
+}
+
+func Chown(path string, uid int, gid int) (err error) {
+ return Fchownat(AT_FDCWD, path, uid, gid, 0)
+}
+
+func Creat(path string, mode uint32) (fd int, err error) {
+ return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
+}
+
+//sys fchmodat(dirfd int, path string, mode uint32) (err error)
+
+func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
+ // Linux fchmodat doesn't support the flags parameter. Mimick glibc's behavior
+ // and check the flags. Otherwise the mode would be applied to the symlink
+ // destination which is not what the user expects.
+ if flags&^AT_SYMLINK_NOFOLLOW != 0 {
+ return EINVAL
+ } else if flags&AT_SYMLINK_NOFOLLOW != 0 {
+ return EOPNOTSUPP
+ }
+ return fchmodat(dirfd, path, mode)
+}
+
+//sys ioctl(fd int, req uint, arg uintptr) (err error)
+
+// ioctl itself should not be exposed directly, but additional get/set
+// functions for specific types are permissible.
+
+// IoctlSetInt performs an ioctl operation which sets an integer value
+// on fd, using the specified request number.
+func IoctlSetInt(fd int, req uint, value int) error {
+ return ioctl(fd, req, uintptr(value))
+}
+
+func IoctlSetWinsize(fd int, req uint, value *Winsize) error {
+ return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
+}
+
+func IoctlSetTermios(fd int, req uint, value *Termios) error {
+ return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
+}
+
+// IoctlGetInt performs an ioctl operation which gets an integer value
+// from fd, using the specified request number.
+func IoctlGetInt(fd int, req uint) (int, error) {
+ var value int
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return value, err
+}
+
+func IoctlGetWinsize(fd int, req uint) (*Winsize, error) {
+ var value Winsize
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return &value, err
+}
+
+func IoctlGetTermios(fd int, req uint) (*Termios, error) {
+ var value Termios
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return &value, err
+}
+
+//sys Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
+
+func Link(oldpath string, newpath string) (err error) {
+ return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
+}
+
+func Mkdir(path string, mode uint32) (err error) {
+ return Mkdirat(AT_FDCWD, path, mode)
+}
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ return Mknodat(AT_FDCWD, path, mode, dev)
+}
+
+func Open(path string, mode int, perm uint32) (fd int, err error) {
+ return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm)
+}
+
+//sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
+
+func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
+ return openat(dirfd, path, flags|O_LARGEFILE, mode)
+}
+
+//sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
+
+func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
+ if len(fds) == 0 {
+ return ppoll(nil, 0, timeout, sigmask)
+ }
+ return ppoll(&fds[0], len(fds), timeout, sigmask)
+}
+
+//sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
+
+func Readlink(path string, buf []byte) (n int, err error) {
+ return Readlinkat(AT_FDCWD, path, buf)
+}
+
+func Rename(oldpath string, newpath string) (err error) {
+ return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
+}
+
+func Rmdir(path string) error {
+ return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
+}
+
+//sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
+
+func Symlink(oldpath string, newpath string) (err error) {
+ return Symlinkat(oldpath, AT_FDCWD, newpath)
+}
+
+func Unlink(path string) error {
+ return Unlinkat(AT_FDCWD, path, 0)
+}
+
+//sys Unlinkat(dirfd int, path string, flags int) (err error)
+
+//sys utimes(path string, times *[2]Timeval) (err error)
+
+func Utimes(path string, tv []Timeval) error {
+ if tv == nil {
+ err := utimensat(AT_FDCWD, path, nil, 0)
+ if err != ENOSYS {
+ return err
+ }
+ return utimes(path, nil)
+ }
+ if len(tv) != 2 {
+ return EINVAL
+ }
+ var ts [2]Timespec
+ ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
+ ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
+ err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
+ if err != ENOSYS {
+ return err
+ }
+ return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
+}
+
+//sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
+
+func UtimesNano(path string, ts []Timespec) error {
+ if ts == nil {
+ err := utimensat(AT_FDCWD, path, nil, 0)
+ if err != ENOSYS {
+ return err
+ }
+ return utimes(path, nil)
+ }
+ if len(ts) != 2 {
+ return EINVAL
+ }
+ err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
+ if err != ENOSYS {
+ return err
+ }
+ // If the utimensat syscall isn't available (utimensat was added to Linux
+ // in 2.6.22, Released, 8 July 2007) then fall back to utimes
+ var tv [2]Timeval
+ for i := 0; i < 2; i++ {
+ tv[i] = NsecToTimeval(TimespecToNsec(ts[i]))
+ }
+ return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
+}
+
+func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
+ if ts == nil {
+ return utimensat(dirfd, path, nil, flags)
+ }
+ if len(ts) != 2 {
+ return EINVAL
+ }
+ return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
+}
+
+//sys futimesat(dirfd int, path *byte, times *[2]Timeval) (err error)
+
+func Futimesat(dirfd int, path string, tv []Timeval) error {
+ pathp, err := BytePtrFromString(path)
+ if err != nil {
+ return err
+ }
+ if tv == nil {
+ return futimesat(dirfd, pathp, nil)
+ }
+ if len(tv) != 2 {
+ return EINVAL
+ }
+ return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
+}
+
+func Futimes(fd int, tv []Timeval) (err error) {
+ // Believe it or not, this is the best we can do on Linux
+ // (and is what glibc does).
+ return Utimes("/proc/self/fd/"+itoa(fd), tv)
+}
+
+const ImplementsGetwd = true
+
+//sys Getcwd(buf []byte) (n int, err error)
+
+func Getwd() (wd string, err error) {
+ var buf [PathMax]byte
+ n, err := Getcwd(buf[0:])
+ if err != nil {
+ return "", err
+ }
+ // Getcwd returns the number of bytes written to buf, including the NUL.
+ if n < 1 || n > len(buf) || buf[n-1] != 0 {
+ return "", EINVAL
+ }
+ return string(buf[0 : n-1]), nil
+}
+
+func Getgroups() (gids []int, err error) {
+ n, err := getgroups(0, nil)
+ if err != nil {
+ return nil, err
+ }
+ if n == 0 {
+ return nil, nil
+ }
+
+ // Sanity check group count. Max is 1<<16 on Linux.
+ if n < 0 || n > 1<<20 {
+ return nil, EINVAL
+ }
+
+ a := make([]_Gid_t, n)
+ n, err = getgroups(n, &a[0])
+ if err != nil {
+ return nil, err
+ }
+ gids = make([]int, n)
+ for i, v := range a[0:n] {
+ gids[i] = int(v)
+ }
+ return
+}
+
+func Setgroups(gids []int) (err error) {
+ if len(gids) == 0 {
+ return setgroups(0, nil)
+ }
+
+ a := make([]_Gid_t, len(gids))
+ for i, v := range gids {
+ a[i] = _Gid_t(v)
+ }
+ return setgroups(len(a), &a[0])
+}
+
+type WaitStatus uint32
+
+// Wait status is 7 bits at bottom, either 0 (exited),
+// 0x7F (stopped), or a signal number that caused an exit.
+// The 0x80 bit is whether there was a core dump.
+// An extra number (exit code, signal causing a stop)
+// is in the high bits. At least that's the idea.
+// There are various irregularities. For example, the
+// "continued" status is 0xFFFF, distinguishing itself
+// from stopped via the core dump bit.
+
+const (
+ mask = 0x7F
+ core = 0x80
+ exited = 0x00
+ stopped = 0x7F
+ shift = 8
+)
+
+func (w WaitStatus) Exited() bool { return w&mask == exited }
+
+func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited }
+
+func (w WaitStatus) Stopped() bool { return w&0xFF == stopped }
+
+func (w WaitStatus) Continued() bool { return w == 0xFFFF }
+
+func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
+
+func (w WaitStatus) ExitStatus() int {
+ if !w.Exited() {
+ return -1
+ }
+ return int(w>>shift) & 0xFF
+}
+
+func (w WaitStatus) Signal() syscall.Signal {
+ if !w.Signaled() {
+ return -1
+ }
+ return syscall.Signal(w & mask)
+}
+
+func (w WaitStatus) StopSignal() syscall.Signal {
+ if !w.Stopped() {
+ return -1
+ }
+ return syscall.Signal(w>>shift) & 0xFF
+}
+
+func (w WaitStatus) TrapCause() int {
+ if w.StopSignal() != SIGTRAP {
+ return -1
+ }
+ return int(w>>shift) >> 8
+}
+
+//sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
+
+func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
+ var status _C_int
+ wpid, err = wait4(pid, &status, options, rusage)
+ if wstatus != nil {
+ *wstatus = WaitStatus(status)
+ }
+ return
+}
+
+func Mkfifo(path string, mode uint32) error {
+ return Mknod(path, mode|S_IFIFO, 0)
+}
+
+func Mkfifoat(dirfd int, path string, mode uint32) error {
+ return Mknodat(dirfd, path, mode|S_IFIFO, 0)
+}
+
+func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ if sa.Port < 0 || sa.Port > 0xFFFF {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Family = AF_INET
+ p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
+ p[0] = byte(sa.Port >> 8)
+ p[1] = byte(sa.Port)
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.raw.Addr[i] = sa.Addr[i]
+ }
+ return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
+}
+
+func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ if sa.Port < 0 || sa.Port > 0xFFFF {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Family = AF_INET6
+ p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
+ p[0] = byte(sa.Port >> 8)
+ p[1] = byte(sa.Port)
+ sa.raw.Scope_id = sa.ZoneId
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.raw.Addr[i] = sa.Addr[i]
+ }
+ return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
+}
+
+func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ name := sa.Name
+ n := len(name)
+ if n >= len(sa.raw.Path) {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Family = AF_UNIX
+ for i := 0; i < n; i++ {
+ sa.raw.Path[i] = int8(name[i])
+ }
+ // length is family (uint16), name, NUL.
+ sl := _Socklen(2)
+ if n > 0 {
+ sl += _Socklen(n) + 1
+ }
+ if sa.raw.Path[0] == '@' {
+ sa.raw.Path[0] = 0
+ // Don't count trailing NUL for abstract address.
+ sl--
+ }
+
+ return unsafe.Pointer(&sa.raw), sl, nil
+}
+
+type SockaddrLinklayer struct {
+ Protocol uint16
+ Ifindex int
+ Hatype uint16
+ Pkttype uint8
+ Halen uint8
+ Addr [8]byte
+ raw RawSockaddrLinklayer
+}
+
+func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Family = AF_PACKET
+ sa.raw.Protocol = sa.Protocol
+ sa.raw.Ifindex = int32(sa.Ifindex)
+ sa.raw.Hatype = sa.Hatype
+ sa.raw.Pkttype = sa.Pkttype
+ sa.raw.Halen = sa.Halen
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.raw.Addr[i] = sa.Addr[i]
+ }
+ return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil
+}
+
+type SockaddrNetlink struct {
+ Family uint16
+ Pad uint16
+ Pid uint32
+ Groups uint32
+ raw RawSockaddrNetlink
+}
+
+func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ sa.raw.Family = AF_NETLINK
+ sa.raw.Pad = sa.Pad
+ sa.raw.Pid = sa.Pid
+ sa.raw.Groups = sa.Groups
+ return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
+}
+
+type SockaddrHCI struct {
+ Dev uint16
+ Channel uint16
+ raw RawSockaddrHCI
+}
+
+func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ sa.raw.Family = AF_BLUETOOTH
+ sa.raw.Dev = sa.Dev
+ sa.raw.Channel = sa.Channel
+ 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
+}
+
+// SockaddrALG implements the Sockaddr interface for AF_ALG type sockets.
+// SockaddrALG enables userspace access to the Linux kernel's cryptography
+// subsystem. The Type and Name fields specify which type of hash or cipher
+// should be used with a given socket.
+//
+// To create a file descriptor that provides access to a hash or cipher, both
+// Bind and Accept must be used. Once the setup process is complete, input
+// data can be written to the socket, processed by the kernel, and then read
+// back as hash output or ciphertext.
+//
+// Here is an example of using an AF_ALG socket with SHA1 hashing.
+// The initial socket setup process is as follows:
+//
+// // Open a socket to perform SHA1 hashing.
+// fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0)
+// addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"}
+// unix.Bind(fd, addr)
+// // Note: unix.Accept does not work at this time; must invoke accept()
+// // manually using unix.Syscall.
+// hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0)
+//
+// Once a file descriptor has been returned from Accept, it may be used to
+// perform SHA1 hashing. The descriptor is not safe for concurrent use, but
+// may be re-used repeatedly with subsequent Write and Read operations.
+//
+// When hashing a small byte slice or string, a single Write and Read may
+// be used:
+//
+// // Assume hashfd is already configured using the setup process.
+// hash := os.NewFile(hashfd, "sha1")
+// // Hash an input string and read the results. Each Write discards
+// // previous hash state. Read always reads the current state.
+// b := make([]byte, 20)
+// for i := 0; i < 2; i++ {
+// io.WriteString(hash, "Hello, world.")
+// hash.Read(b)
+// fmt.Println(hex.EncodeToString(b))
+// }
+// // Output:
+// // 2ae01472317d1935a84797ec1983ae243fc6aa28
+// // 2ae01472317d1935a84797ec1983ae243fc6aa28
+//
+// For hashing larger byte slices, or byte streams such as those read from
+// a file or socket, use Sendto with MSG_MORE to instruct the kernel to update
+// the hash digest instead of creating a new one for a given chunk and finalizing it.
+//
+// // Assume hashfd and addr are already configured using the setup process.
+// hash := os.NewFile(hashfd, "sha1")
+// // Hash the contents of a file.
+// f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz")
+// b := make([]byte, 4096)
+// for {
+// n, err := f.Read(b)
+// if err == io.EOF {
+// break
+// }
+// unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr)
+// }
+// hash.Read(b)
+// fmt.Println(hex.EncodeToString(b))
+// // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5
+//
+// For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html.
+type SockaddrALG struct {
+ Type string
+ Name string
+ Feature uint32
+ Mask uint32
+ raw RawSockaddrALG
+}
+
+func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ // Leave room for NUL byte terminator.
+ if len(sa.Type) > 13 {
+ return nil, 0, EINVAL
+ }
+ if len(sa.Name) > 63 {
+ return nil, 0, EINVAL
+ }
+
+ sa.raw.Family = AF_ALG
+ sa.raw.Feat = sa.Feature
+ sa.raw.Mask = sa.Mask
+
+ typ, err := ByteSliceFromString(sa.Type)
+ if err != nil {
+ return nil, 0, err
+ }
+ name, err := ByteSliceFromString(sa.Name)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ copy(sa.raw.Type[:], typ)
+ copy(sa.raw.Name[:], name)
+
+ return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil
+}
+
+// SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets.
+// SockaddrVM provides access to Linux VM sockets: a mechanism that enables
+// bidirectional communication between a hypervisor and its guest virtual
+// machines.
+type SockaddrVM struct {
+ // CID and Port specify a context ID and port address for a VM socket.
+ // Guests have a unique CID, and hosts may have a well-known CID of:
+ // - VMADDR_CID_HYPERVISOR: refers to the hypervisor process.
+ // - VMADDR_CID_HOST: refers to other processes on the host.
+ CID uint32
+ Port uint32
+ raw RawSockaddrVM
+}
+
+func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ sa.raw.Family = AF_VSOCK
+ sa.raw.Port = sa.Port
+ sa.raw.Cid = sa.CID
+
+ return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil
+}
+
+func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
+ switch rsa.Addr.Family {
+ case AF_NETLINK:
+ pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa))
+ sa := new(SockaddrNetlink)
+ sa.Family = pp.Family
+ sa.Pad = pp.Pad
+ sa.Pid = pp.Pid
+ sa.Groups = pp.Groups
+ return sa, nil
+
+ case AF_PACKET:
+ pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa))
+ sa := new(SockaddrLinklayer)
+ sa.Protocol = pp.Protocol
+ sa.Ifindex = int(pp.Ifindex)
+ sa.Hatype = pp.Hatype
+ sa.Pkttype = pp.Pkttype
+ sa.Halen = pp.Halen
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.Addr[i] = pp.Addr[i]
+ }
+ return sa, nil
+
+ case AF_UNIX:
+ pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
+ sa := new(SockaddrUnix)
+ if pp.Path[0] == 0 {
+ // "Abstract" Unix domain socket.
+ // Rewrite leading NUL as @ for textual display.
+ // (This is the standard convention.)
+ // Not friendly to overwrite in place,
+ // but the callers below don't care.
+ pp.Path[0] = '@'
+ }
+
+ // Assume path ends at NUL.
+ // This is not technically the Linux semantics for
+ // abstract Unix domain sockets--they are supposed
+ // to be uninterpreted fixed-size binary blobs--but
+ // everyone uses this convention.
+ n := 0
+ for n < len(pp.Path) && pp.Path[n] != 0 {
+ n++
+ }
+ bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
+ sa.Name = string(bytes)
+ return sa, nil
+
+ case AF_INET:
+ pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
+ sa := new(SockaddrInet4)
+ p := (*[2]byte)(unsafe.Pointer(&pp.Port))
+ sa.Port = int(p[0])<<8 + int(p[1])
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.Addr[i] = pp.Addr[i]
+ }
+ return sa, nil
+
+ case AF_INET6:
+ pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
+ sa := new(SockaddrInet6)
+ p := (*[2]byte)(unsafe.Pointer(&pp.Port))
+ sa.Port = int(p[0])<<8 + int(p[1])
+ sa.ZoneId = pp.Scope_id
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.Addr[i] = pp.Addr[i]
+ }
+ return sa, nil
+
+ case AF_VSOCK:
+ pp := (*RawSockaddrVM)(unsafe.Pointer(rsa))
+ sa := &SockaddrVM{
+ CID: pp.Cid,
+ Port: pp.Port,
+ }
+ return sa, nil
+ }
+ return nil, EAFNOSUPPORT
+}
+
+func Accept(fd int) (nfd int, sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ nfd, err = accept(fd, &rsa, &len)
+ if err != nil {
+ return
+ }
+ sa, err = anyToSockaddr(&rsa)
+ if err != nil {
+ Close(nfd)
+ nfd = 0
+ }
+ return
+}
+
+func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ nfd, err = accept4(fd, &rsa, &len, flags)
+ if err != nil {
+ return
+ }
+ if len > SizeofSockaddrAny {
+ panic("RawSockaddrAny too small")
+ }
+ sa, err = anyToSockaddr(&rsa)
+ if err != nil {
+ Close(nfd)
+ nfd = 0
+ }
+ return
+}
+
+func Getsockname(fd int) (sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ if err = getsockname(fd, &rsa, &len); err != nil {
+ return
+ }
+ return anyToSockaddr(&rsa)
+}
+
+func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) {
+ vallen := _Socklen(4)
+ err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
+ return value, err
+}
+
+func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) {
+ var value IPMreq
+ vallen := _Socklen(SizeofIPMreq)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
+ var value IPMreqn
+ vallen := _Socklen(SizeofIPMreqn)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) {
+ var value IPv6Mreq
+ vallen := _Socklen(SizeofIPv6Mreq)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) {
+ var value IPv6MTUInfo
+ vallen := _Socklen(SizeofIPv6MTUInfo)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) {
+ var value ICMPv6Filter
+ vallen := _Socklen(SizeofICMPv6Filter)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+func GetsockoptUcred(fd, level, opt int) (*Ucred, error) {
+ var value Ucred
+ vallen := _Socklen(SizeofUcred)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) {
+ var value TCPInfo
+ vallen := _Socklen(SizeofTCPInfo)
+ err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
+ return &value, err
+}
+
+func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
+ return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
+}
+
+// Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html)
+
+// KeyctlInt calls keyctl commands in which each argument is an int.
+// These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK,
+// KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT,
+// KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT,
+// KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT.
+//sys KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL
+
+// KeyctlBuffer calls keyctl commands in which the third and fourth
+// arguments are a buffer and its length, respectively.
+// These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE.
+//sys KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL
+
+// KeyctlString calls keyctl commands which return a string.
+// These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY.
+func KeyctlString(cmd int, id int) (string, error) {
+ // We must loop as the string data may change in between the syscalls.
+ // We could allocate a large buffer here to reduce the chance that the
+ // syscall needs to be called twice; however, this is unnecessary as
+ // the performance loss is negligible.
+ var buffer []byte
+ for {
+ // Try to fill the buffer with data
+ length, err := KeyctlBuffer(cmd, id, buffer, 0)
+ if err != nil {
+ return "", err
+ }
+
+ // Check if the data was written
+ if length <= len(buffer) {
+ // Exclude the null terminator
+ return string(buffer[:length-1]), nil
+ }
+
+ // Make a bigger buffer if needed
+ buffer = make([]byte, length)
+ }
+}
+
+// Keyctl commands with special signatures.
+
+// KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
+// See the full documentation at:
+// http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html
+func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
+ createInt := 0
+ if create {
+ createInt = 1
+ }
+ return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
+}
+
+// KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the
+// key handle permission mask as described in the "keyctl setperm" section of
+// http://man7.org/linux/man-pages/man1/keyctl.1.html.
+// See the full documentation at:
+// http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html
+func KeyctlSetperm(id int, perm uint32) error {
+ _, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0)
+ return err
+}
+
+//sys keyctlJoin(cmd int, arg2 string) (ret int, err error) = SYS_KEYCTL
+
+// KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command.
+// See the full documentation at:
+// http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html
+func KeyctlJoinSessionKeyring(name string) (ringid int, err error) {
+ return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name)
+}
+
+//sys keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) = SYS_KEYCTL
+
+// KeyctlSearch implements the KEYCTL_SEARCH command.
+// See the full documentation at:
+// http://man7.org/linux/man-pages/man3/keyctl_search.3.html
+func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) {
+ return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid)
+}
+
+//sys keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) = SYS_KEYCTL
+
+// KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This
+// command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice
+// of Iovec (each of which represents a buffer) instead of a single buffer.
+// See the full documentation at:
+// http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html
+func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error {
+ return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid)
+}
+
+//sys keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) = SYS_KEYCTL
+
+// KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command
+// computes a Diffie-Hellman shared secret based on the provide params. The
+// secret is written to the provided buffer and the returned size is the number
+// of bytes written (returning an error if there is insufficient space in the
+// buffer). If a nil buffer is passed in, this function returns the minimum
+// buffer length needed to store the appropriate data. Note that this differs
+// from KEYCTL_READ's behavior which always returns the requested payload size.
+// See the full documentation at:
+// http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html
+func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) {
+ return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer)
+}
+
+func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
+ var msg Msghdr
+ var rsa RawSockaddrAny
+ msg.Name = (*byte)(unsafe.Pointer(&rsa))
+ msg.Namelen = uint32(SizeofSockaddrAny)
+ var iov Iovec
+ if len(p) > 0 {
+ iov.Base = (*byte)(unsafe.Pointer(&p[0]))
+ iov.SetLen(len(p))
+ }
+ var dummy byte
+ if len(oob) > 0 {
+ // receive at least one normal byte
+ if len(p) == 0 {
+ iov.Base = &dummy
+ iov.SetLen(1)
+ }
+ msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
+ msg.SetControllen(len(oob))
+ }
+ msg.Iov = &iov
+ msg.Iovlen = 1
+ if n, err = recvmsg(fd, &msg, flags); err != nil {
+ return
+ }
+ oobn = int(msg.Controllen)
+ recvflags = int(msg.Flags)
+ // source address is only specified if the socket is unconnected
+ if rsa.Addr.Family != AF_UNSPEC {
+ from, err = anyToSockaddr(&rsa)
+ }
+ return
+}
+
+func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
+ _, err = SendmsgN(fd, p, oob, to, flags)
+ return
+}
+
+func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
+ var ptr unsafe.Pointer
+ var salen _Socklen
+ if to != nil {
+ var err error
+ ptr, salen, err = to.sockaddr()
+ if err != nil {
+ return 0, err
+ }
+ }
+ var msg Msghdr
+ msg.Name = (*byte)(unsafe.Pointer(ptr))
+ msg.Namelen = uint32(salen)
+ var iov Iovec
+ if len(p) > 0 {
+ iov.Base = (*byte)(unsafe.Pointer(&p[0]))
+ iov.SetLen(len(p))
+ }
+ var dummy byte
+ if len(oob) > 0 {
+ // send at least one normal byte
+ if len(p) == 0 {
+ iov.Base = &dummy
+ iov.SetLen(1)
+ }
+ msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
+ msg.SetControllen(len(oob))
+ }
+ msg.Iov = &iov
+ msg.Iovlen = 1
+ if n, err = sendmsg(fd, &msg, flags); err != nil {
+ return 0, err
+ }
+ if len(oob) > 0 && len(p) == 0 {
+ n = 0
+ }
+ return n, nil
+}
+
+// BindToDevice binds the socket associated with fd to device.
+func BindToDevice(fd int, device string) (err error) {
+ return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
+}
+
+//sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
+
+func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
+ // The peek requests are machine-size oriented, so we wrap it
+ // to retrieve arbitrary-length data.
+
+ // The ptrace syscall differs from glibc's ptrace.
+ // Peeks returns the word in *data, not as the return value.
+
+ var buf [sizeofPtr]byte
+
+ // Leading edge. PEEKTEXT/PEEKDATA don't require aligned
+ // access (PEEKUSER warns that it might), but if we don't
+ // align our reads, we might straddle an unmapped page
+ // boundary and not get the bytes leading up to the page
+ // boundary.
+ n := 0
+ if addr%sizeofPtr != 0 {
+ err = ptrace(req, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
+ if err != nil {
+ return 0, err
+ }
+ n += copy(out, buf[addr%sizeofPtr:])
+ out = out[n:]
+ }
+
+ // Remainder.
+ for len(out) > 0 {
+ // We use an internal buffer to guarantee alignment.
+ // It's not documented if this is necessary, but we're paranoid.
+ err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
+ if err != nil {
+ return n, err
+ }
+ copied := copy(out, buf[0:])
+ n += copied
+ out = out[copied:]
+ }
+
+ return n, nil
+}
+
+func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
+ return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
+}
+
+func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
+ return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
+}
+
+func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) {
+ return ptracePeek(PTRACE_PEEKUSR, pid, addr, out)
+}
+
+func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
+ // As for ptracePeek, we need to align our accesses to deal
+ // with the possibility of straddling an invalid page.
+
+ // Leading edge.
+ n := 0
+ if addr%sizeofPtr != 0 {
+ var buf [sizeofPtr]byte
+ err = ptrace(peekReq, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
+ if err != nil {
+ return 0, err
+ }
+ n += copy(buf[addr%sizeofPtr:], data)
+ word := *((*uintptr)(unsafe.Pointer(&buf[0])))
+ err = ptrace(pokeReq, pid, addr-addr%sizeofPtr, word)
+ if err != nil {
+ return 0, err
+ }
+ data = data[n:]
+ }
+
+ // Interior.
+ for len(data) > sizeofPtr {
+ word := *((*uintptr)(unsafe.Pointer(&data[0])))
+ err = ptrace(pokeReq, pid, addr+uintptr(n), word)
+ if err != nil {
+ return n, err
+ }
+ n += sizeofPtr
+ data = data[sizeofPtr:]
+ }
+
+ // Trailing edge.
+ if len(data) > 0 {
+ var buf [sizeofPtr]byte
+ err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
+ if err != nil {
+ return n, err
+ }
+ copy(buf[0:], data)
+ word := *((*uintptr)(unsafe.Pointer(&buf[0])))
+ err = ptrace(pokeReq, pid, addr+uintptr(n), word)
+ if err != nil {
+ return n, err
+ }
+ n += len(data)
+ }
+
+ return n, nil
+}
+
+func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
+ return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
+}
+
+func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
+ return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
+}
+
+func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
+ return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))
+}
+
+func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
+ return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))
+}
+
+func PtraceSetOptions(pid int, options int) (err error) {
+ return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
+}
+
+func PtraceGetEventMsg(pid int) (msg uint, err error) {
+ var data _C_long
+ err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data)))
+ msg = uint(data)
+ return
+}
+
+func PtraceCont(pid int, signal int) (err error) {
+ return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
+}
+
+func PtraceSyscall(pid int, signal int) (err error) {
+ return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
+}
+
+func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
+
+func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
+
+func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
+
+//sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
+
+func Reboot(cmd int) (err error) {
+ return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
+}
+
+func ReadDirent(fd int, buf []byte) (n int, err error) {
+ return Getdents(fd, buf)
+}
+
+func direntIno(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
+}
+
+func direntReclen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
+}
+
+func direntNamlen(buf []byte) (uint64, bool) {
+ reclen, ok := direntReclen(buf)
+ if !ok {
+ return 0, false
+ }
+ return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true
+}
+
+//sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
+
+func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
+ // Certain file systems get rather angry and EINVAL if you give
+ // them an empty string of data, rather than NULL.
+ if data == "" {
+ return mount(source, target, fstype, flags, nil)
+ }
+ datap, err := BytePtrFromString(data)
+ if err != nil {
+ return err
+ }
+ return mount(source, target, fstype, flags, datap)
+}
+
+// Sendto
+// Recvfrom
+// Socketpair
+
+/*
+ * Direct access
+ */
+//sys Acct(path string) (err error)
+//sys AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error)
+//sys Adjtimex(buf *Timex) (state int, err error)
+//sys Chdir(path string) (err error)
+//sys Chroot(path string) (err error)
+//sys ClockGettime(clockid int32, time *Timespec) (err error)
+//sys Close(fd int) (err error)
+//sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
+//sys Dup(oldfd int) (fd int, err error)
+//sys Dup3(oldfd int, newfd int, flags int) (err error)
+//sysnb EpollCreate(size int) (fd int, err error)
+//sysnb EpollCreate1(flag int) (fd int, err error)
+//sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
+//sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2
+//sys Exit(code int) = SYS_EXIT_GROUP
+//sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error)
+//sys Fallocate(fd int, mode uint32, off int64, len int64) (err error)
+//sys Fchdir(fd int) (err error)
+//sys Fchmod(fd int, mode uint32) (err error)
+//sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
+//sys fcntl(fd int, cmd int, arg int) (val int, err error)
+//sys Fdatasync(fd int) (err error)
+//sys Flock(fd int, how int) (err error)
+//sys Fsync(fd int) (err error)
+//sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
+//sysnb Getpgid(pid int) (pgid int, err error)
+
+func Getpgrp() (pid int) {
+ pid, _ = Getpgid(0)
+ return
+}
+
+//sysnb Getpid() (pid int)
+//sysnb Getppid() (ppid int)
+//sys Getpriority(which int, who int) (prio int, err error)
+//sys Getrandom(buf []byte, flags int) (n 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)
+//sysnb InotifyInit1(flags int) (fd int, err error)
+//sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
+//sysnb Kill(pid int, sig syscall.Signal) (err error)
+//sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
+//sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error)
+//sys Listxattr(path string, dest []byte) (sz int, err error)
+//sys Llistxattr(path string, dest []byte) (sz int, err error)
+//sys Lremovexattr(path string, attr string) (err error)
+//sys Lsetxattr(path string, attr string, data []byte, flags int) (err error)
+//sys Mkdirat(dirfd int, path string, mode uint32) (err error)
+//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, 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)
+//sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
+//sys RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error)
+//sys Setdomainname(p []byte) (err error)
+//sys Sethostname(p []byte) (err error)
+//sysnb Setpgid(pid int, pgid int) (err error)
+//sysnb Setsid() (pid int, err error)
+//sysnb Settimeofday(tv *Timeval) (err error)
+//sys Setns(fd int, nstype int) (err error)
+
+// issue 1435.
+// On linux Setuid and Setgid only affects the current thread, not the process.
+// This does not match what most callers expect so we must return an error
+// here rather than letting the caller think that the call succeeded.
+
+func Setuid(uid int) (err error) {
+ return EOPNOTSUPP
+}
+
+func Setgid(uid int) (err error) {
+ return EOPNOTSUPP
+}
+
+//sys Setpriority(which int, who int, prio int) (err error)
+//sys Setxattr(path string, attr string, data []byte, flags int) (err error)
+//sys Sync()
+//sys Syncfs(fd int) (err error)
+//sysnb Sysinfo(info *Sysinfo_t) (err error)
+//sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
+//sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error)
+//sysnb Times(tms *Tms) (ticks uintptr, err error)
+//sysnb Umask(mask int) (oldmask int)
+//sysnb Uname(buf *Utsname) (err error)
+//sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2
+//sys Unshare(flags int) (err error)
+//sys Ustat(dev int, ubuf *Ustat_t) (err error)
+//sys write(fd int, p []byte) (n int, err error)
+//sys exitThread(code int) (err error) = SYS_EXIT
+//sys readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ
+//sys writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE
+
+// mmap varies by architecture; see syscall_linux_*.go.
+//sys munmap(addr uintptr, length uintptr) (err error)
+
+var mapper = &mmapper{
+ active: make(map[*byte][]byte),
+ mmap: mmap,
+ munmap: munmap,
+}
+
+func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
+ return mapper.Mmap(fd, offset, length, prot, flags)
+}
+
+func Munmap(b []byte) (err error) {
+ return mapper.Munmap(b)
+}
+
+//sys Madvise(b []byte, advice int) (err error)
+//sys Mprotect(b []byte, prot int) (err error)
+//sys Mlock(b []byte) (err error)
+//sys Mlockall(flags int) (err error)
+//sys Msync(b []byte, flags int) (err error)
+//sys Munlock(b []byte) (err error)
+//sys Munlockall() (err error)
+
+// Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
+// using the specified flags.
+func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
+ n, _, errno := Syscall6(
+ SYS_VMSPLICE,
+ uintptr(fd),
+ uintptr(unsafe.Pointer(&iovs[0])),
+ uintptr(len(iovs)),
+ uintptr(flags),
+ 0,
+ 0,
+ )
+ if errno != 0 {
+ return 0, syscall.Errno(errno)
+ }
+
+ return int(n), nil
+}
+
+/*
+ * Unimplemented
+ */
+// AfsSyscall
+// Alarm
+// ArchPrctl
+// Brk
+// Capget
+// Capset
+// ClockGetres
+// ClockNanosleep
+// ClockSettime
+// Clone
+// CreateModule
+// DeleteModule
+// EpollCtlOld
+// EpollPwait
+// EpollWaitOld
+// Execve
+// Fgetxattr
+// Flistxattr
+// Fork
+// Fremovexattr
+// Fsetxattr
+// Futex
+// GetKernelSyms
+// GetMempolicy
+// GetRobustList
+// GetThreadArea
+// Getitimer
+// Getpmsg
+// IoCancel
+// IoDestroy
+// IoGetevents
+// IoSetup
+// IoSubmit
+// IoprioGet
+// IoprioSet
+// KexecLoad
+// LookupDcookie
+// Mbind
+// MigratePages
+// Mincore
+// ModifyLdt
+// Mount
+// MovePages
+// MqGetsetattr
+// MqNotify
+// MqOpen
+// MqTimedreceive
+// MqTimedsend
+// MqUnlink
+// Mremap
+// Msgctl
+// Msgget
+// Msgrcv
+// Msgsnd
+// Newfstatat
+// Nfsservctl
+// Personality
+// Pselect6
+// Ptrace
+// Putpmsg
+// QueryModule
+// Quotactl
+// Readahead
+// Readv
+// RemapFilePages
+// RestartSyscall
+// RtSigaction
+// RtSigpending
+// RtSigprocmask
+// RtSigqueueinfo
+// RtSigreturn
+// RtSigsuspend
+// RtSigtimedwait
+// SchedGetPriorityMax
+// SchedGetPriorityMin
+// SchedGetaffinity
+// SchedGetparam
+// SchedGetscheduler
+// SchedRrGetInterval
+// SchedSetaffinity
+// SchedSetparam
+// SchedYield
+// Security
+// Semctl
+// Semget
+// Semop
+// Semtimedop
+// SetMempolicy
+// SetRobustList
+// SetThreadArea
+// SetTidAddress
+// Shmat
+// Shmctl
+// Shmdt
+// Shmget
+// Sigaltstack
+// Signalfd
+// Swapoff
+// Swapon
+// Sysfs
+// TimerCreate
+// TimerDelete
+// TimerGetoverrun
+// TimerGettime
+// TimerSettime
+// Timerfd
+// Tkill (obsolete)
+// Tuxcall
+// Umount2
+// Uselib
+// Utimensat
+// Vfork
+// Vhangup
+// Vserver
+// Waitid
+// _Sysctl
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_386.go b/vendor/golang.org/x/sys/unix/syscall_linux_386.go
new file mode 100644
index 0000000..2b881b9
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_linux_386.go
@@ -0,0 +1,399 @@
+// Copyright 2009 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.
+
+// TODO(rsc): Rewrite all nn(SP) references into name+(nn-8)(FP)
+// so that go vet can check that they are correct.
+
+// +build 386,linux
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func Getpagesize() int { return 4096 }
+
+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 pipe(p *[2]_C_int) (err error)
+
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ var pp [2]_C_int
+ err = pipe(&pp)
+ p[0] = int(pp[0])
+ p[1] = int(pp[1])
+ 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
+}
+
+// 64-bit file system and 32-bit uid calls
+// (386 default is 32-bit file system and 16-bit uid).
+//sys Dup2(oldfd int, newfd int) (err error)
+//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64_64
+//sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32
+//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
+//sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64
+//sysnb Getegid() (egid int) = SYS_GETEGID32
+//sysnb Geteuid() (euid int) = SYS_GETEUID32
+//sysnb Getgid() (gid int) = SYS_GETGID32
+//sysnb Getuid() (uid int) = SYS_GETUID32
+//sysnb InotifyInit() (fd int, err error)
+//sys Ioperm(from int, num int, on int) (err error)
+//sys Iopl(level int) (err error)
+//sys Lchown(path string, uid int, gid int) (err error) = SYS_LCHOWN32
+//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64
+//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 sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64
+//sys Setfsgid(gid int) (err error) = SYS_SETFSGID32
+//sys Setfsuid(uid int) (err error) = SYS_SETFSUID32
+//sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32
+//sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32
+//sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32
+//sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32
+//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
+//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64
+//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
+//sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64
+//sysnb getgroups(n int, list *_Gid_t) (nn int, err error) = SYS_GETGROUPS32
+//sysnb setgroups(n int, list *_Gid_t) (err error) = SYS_SETGROUPS32
+//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT
+
+//sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error)
+//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
+//sys Pause() (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)
+}
+
+type rlimit32 struct {
+ Cur uint32
+ Max uint32
+}
+
+//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT
+
+const rlimInf32 = ^uint32(0)
+const rlimInf64 = ^uint64(0)
+
+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)
+}
+
+// Underlying system call writes to newoffset via pointer.
+// Implemented in assembly to avoid allocation.
+func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno)
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ newoffset, errno := seek(fd, offset, whence)
+ if errno != 0 {
+ return 0, errno
+ }
+ return newoffset, nil
+}
+
+// Vsyscalls on amd64.
+//sysnb Gettimeofday(tv *Timeval) (err error)
+//sysnb Time(t *Time_t) (tt Time_t, err error)
+
+//sys Utime(path string, buf *Utimbuf) (err error)
+
+// On x86 Linux, all the socket calls go through an extra indirection,
+// I think because the 5-register system call interface can't handle
+// the 6-argument calls like sendto and recvfrom. Instead the
+// arguments to the underlying system call are the number below
+// and a pointer to an array of uintptr. We hide the pointer in the
+// socketcall assembly to avoid allocation on every system call.
+
+const (
+ // see linux/net.h
+ _SOCKET = 1
+ _BIND = 2
+ _CONNECT = 3
+ _LISTEN = 4
+ _ACCEPT = 5
+ _GETSOCKNAME = 6
+ _GETPEERNAME = 7
+ _SOCKETPAIR = 8
+ _SEND = 9
+ _RECV = 10
+ _SENDTO = 11
+ _RECVFROM = 12
+ _SHUTDOWN = 13
+ _SETSOCKOPT = 14
+ _GETSOCKOPT = 15
+ _SENDMSG = 16
+ _RECVMSG = 17
+ _ACCEPT4 = 18
+ _RECVMMSG = 19
+ _SENDMMSG = 20
+)
+
+func socketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (n int, err syscall.Errno)
+func rawsocketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (n int, err syscall.Errno)
+
+func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
+ fd, e := socketcall(_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) {
+ fd, e := socketcall(_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func getsockname(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
+ _, e := rawsocketcall(_GETSOCKNAME, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func getpeername(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
+ _, e := rawsocketcall(_GETPEERNAME, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func socketpair(domain int, typ int, flags int, fd *[2]int32) (err error) {
+ _, e := rawsocketcall(_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(flags), uintptr(unsafe.Pointer(fd)), 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
+ _, e := socketcall(_BIND, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
+ _, e := socketcall(_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func socket(domain int, typ int, proto int) (fd int, err error) {
+ fd, e := rawsocketcall(_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto), 0, 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) {
+ _, e := socketcall(_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
+ _, e := socketcall(_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), vallen, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func recvfrom(s int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) {
+ var base uintptr
+ if len(p) > 0 {
+ base = uintptr(unsafe.Pointer(&p[0]))
+ }
+ n, e := socketcall(_RECVFROM, uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func sendto(s int, p []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
+ var base uintptr
+ if len(p) > 0 {
+ base = uintptr(unsafe.Pointer(&p[0]))
+ }
+ _, e := socketcall(_SENDTO, uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(to), uintptr(addrlen))
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) {
+ n, e := socketcall(_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) {
+ n, e := socketcall(_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func Listen(s int, n int) (err error) {
+ _, e := socketcall(_LISTEN, uintptr(s), uintptr(n), 0, 0, 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func Shutdown(s, how int) (err error) {
+ _, e := socketcall(_SHUTDOWN, uintptr(s), uintptr(how), 0, 0, 0, 0)
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func Fstatfs(fd int, buf *Statfs_t) (err error) {
+ _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func Statfs(path string, buf *Statfs_t) (err error) {
+ pathp, err := BytePtrFromString(path)
+ if err != nil {
+ return err
+ }
+ _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func (r *PtraceRegs) PC() uint64 { return uint64(uint32(r.Eip)) }
+
+func (r *PtraceRegs) SetPC(pc uint64) { r.Eip = int32(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)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go
new file mode 100644
index 0000000..9516a3f
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go
@@ -0,0 +1,152 @@
+// Copyright 2009 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
+
+package unix
+
+//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
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Fstat(fd int, stat *Stat_t) (err error)
+//sys Fstatfs(fd int, buf *Statfs_t) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (euid int)
+//sysnb Getgid() (gid int)
+//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
+//sysnb Getuid() (uid int)
+//sysnb InotifyInit() (fd int, err error)
+//sys Ioperm(from int, num int, on int) (err error)
+//sys Iopl(level int) (err error)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Listen(s int, n int) (err error)
+//sys Lstat(path string, stat *Stat_t) (err error)
+//sys Pause() (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 Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
+//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
+//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
+//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 Setrlimit(resource int, rlim *Rlimit) (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 Stat(path string, stat *Stat_t) (err error)
+//sys Statfs(path string, buf *Statfs_t) (err error)
+//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
+//sys Truncate(path string, length int64) (err error)
+//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)
+//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
+
+func Gettimeofday(tv *Timeval) (err error) {
+ errno := gettimeofday(tv)
+ if errno != 0 {
+ return errno
+ }
+ return nil
+}
+
+func Getpagesize() int { return 4096 }
+
+func Time(t *Time_t) (tt Time_t, err error) {
+ var tv Timeval
+ errno := gettimeofday(&tv)
+ if errno != 0 {
+ return 0, errno
+ }
+ if t != nil {
+ *t = Time_t(tv.Sec)
+ }
+ return Time_t(tv.Sec), nil
+}
+
+//sys Utime(path string, buf *Utimbuf) (err error)
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Sec = nsec / 1e9
+ tv.Usec = nsec % 1e9 / 1e3
+ return
+}
+
+//sysnb pipe(p *[2]_C_int) (err error)
+
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ var pp [2]_C_int
+ err = pipe(&pp)
+ p[0] = int(pp[0])
+ p[1] = int(pp[1])
+ 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 (r *PtraceRegs) PC() uint64 { return r.Rip }
+
+func (r *PtraceRegs) SetPC(pc uint64) { r.Rip = pc }
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint64(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint64(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)
+}
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_arm.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go
new file mode 100644
index 0000000..71d8702
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go
@@ -0,0 +1,263 @@
+// Copyright 2009 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 arm,linux
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+func Getpagesize() int { return 4096 }
+
+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
+}
+
+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
+}
+
+//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
+}
+
+// Underlying system call writes to newoffset via pointer.
+// Implemented in assembly to avoid allocation.
+func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno)
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ newoffset, errno := seek(fd, offset, whence)
+ if errno != 0 {
+ return 0, errno
+ }
+ return newoffset, nil
+}
+
+//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) = SYS_GETGROUPS32
+//sysnb setgroups(n int, list *_Gid_t) (err error) = SYS_SETGROUPS32
+//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 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)
+//sysnb socketpair(domain int, typ int, flags int, fd *[2]int32) (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)
+
+// 64-bit file system and 32-bit uid calls
+// (16-bit uid calls are not always supported in newer kernels)
+//sys Dup2(oldfd int, newfd int) (err error)
+//sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32
+//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64
+//sysnb Getegid() (egid int) = SYS_GETEGID32
+//sysnb Geteuid() (euid int) = SYS_GETEUID32
+//sysnb Getgid() (gid int) = SYS_GETGID32
+//sysnb Getuid() (uid int) = SYS_GETUID32
+//sysnb InotifyInit() (fd int, err error)
+//sys Lchown(path string, uid int, gid int) (err error) = SYS_LCHOWN32
+//sys Listen(s int, n int) (err error)
+//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64
+//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64
+//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT
+//sys Setfsgid(gid int) (err error) = SYS_SETFSGID32
+//sys Setfsuid(uid int) (err error) = SYS_SETFSUID32
+//sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32
+//sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32
+//sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32
+//sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32
+//sys Shutdown(fd int, how int) (err error)
+//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
+//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64
+
+// Vsyscalls on amd64.
+//sysnb Gettimeofday(tv *Timeval) (err error)
+//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
+//sys Pause() (err error)
+
+func Time(t *Time_t) (Time_t, error) {
+ var tv Timeval
+ err := Gettimeofday(&tv)
+ if err != nil {
+ return 0, err
+ }
+ if t != nil {
+ *t = Time_t(tv.Sec)
+ }
+ return Time_t(tv.Sec), nil
+}
+
+func Utime(path string, buf *Utimbuf) error {
+ tv := []Timeval{
+ {Sec: buf.Actime},
+ {Sec: buf.Modtime},
+ }
+ return Utimes(path, tv)
+}
+
+//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 Truncate(path string, length int64) (err error) = SYS_TRUNCATE64
+//sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64
+
+func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
+ _, _, e1 := Syscall6(SYS_ARM_FADVISE64_64, uintptr(fd), uintptr(advice), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+//sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error)
+
+func Fstatfs(fd int, buf *Statfs_t) (err error) {
+ _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+func Statfs(path string, buf *Statfs_t) (err error) {
+ pathp, err := BytePtrFromString(path)
+ if err != nil {
+ return err
+ }
+ _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf)))
+ if e != 0 {
+ err = e
+ }
+ return
+}
+
+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)
+}
+
+type rlimit32 struct {
+ Cur uint32
+ Max uint32
+}
+
+//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_UGETRLIMIT
+
+const rlimInf32 = ^uint32(0)
+const rlimInf64 = ^uint64(0)
+
+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.Uregs[15]) }
+
+func (r *PtraceRegs) SetPC(pc uint64) { r.Uregs[15] = 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)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go
new file mode 100644
index 0000000..4196322
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go
@@ -0,0 +1,191 @@
+// Copyright 2015 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 arm64,linux
+
+package unix
+
+//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT
+//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Fstat(fd int, stat *Stat_t) (err error)
+//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error)
+//sys Fstatfs(fd int, buf *Statfs_t) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (euid int)
+//sysnb Getgid() (gid int)
+//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
+//sysnb Getuid() (uid int)
+//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 Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
+//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS_PSELECT6
+//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
+//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 Setrlimit(resource int, rlim *Rlimit) (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)
+
+func Stat(path string, stat *Stat_t) (err error) {
+ return Fstatat(AT_FDCWD, path, stat, 0)
+}
+
+func Lchown(path string, uid int, gid int) (err error) {
+ return Fchownat(AT_FDCWD, path, uid, gid, AT_SYMLINK_NOFOLLOW)
+}
+
+func Lstat(path string, stat *Stat_t) (err error) {
+ return Fstatat(AT_FDCWD, path, stat, AT_SYMLINK_NOFOLLOW)
+}
+
+//sys Statfs(path string, buf *Statfs_t) (err error)
+//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
+//sys Truncate(path string, length int64) (err error)
+//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)
+//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
+
+func Getpagesize() int { return 65536 }
+
+//sysnb Gettimeofday(tv *Timeval) (err error)
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Sec = nsec / 1e9
+ tv.Usec = nsec % 1e9 / 1e3
+ return
+}
+
+func Time(t *Time_t) (Time_t, error) {
+ var tv Timeval
+ err := Gettimeofday(&tv)
+ if err != nil {
+ return 0, err
+ }
+ if t != nil {
+ *t = Time_t(tv.Sec)
+ }
+ return Time_t(tv.Sec), nil
+}
+
+func Utime(path string, buf *Utimbuf) error {
+ tv := []Timeval{
+ {Sec: buf.Actime},
+ {Sec: buf.Modtime},
+ }
+ return Utimes(path, tv)
+}
+
+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
+}
+
+//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 (r *PtraceRegs) PC() uint64 { return r.Pc }
+
+func (r *PtraceRegs) SetPC(pc uint64) { r.Pc = pc }
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint64(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint64(length)
+}
+
+func InotifyInit() (fd int, err error) {
+ return InotifyInit1(0)
+}
+
+func Dup2(oldfd int, newfd int) (err error) {
+ return Dup3(oldfd, newfd, 0)
+}
+
+func Pause() (err error) {
+ _, _, e1 := Syscall6(SYS_PPOLL, 0, 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// TODO(dfc): constants that should be in zsysnum_linux_arm64.go, remove
+// these when the deprecated syscalls that the syscall package relies on
+// are removed.
+const (
+ SYS_GETPGRP = 1060
+ SYS_UTIMES = 1037
+ SYS_FUTIMESAT = 1066
+ SYS_PAUSE = 1061
+ SYS_USTAT = 1070
+ SYS_UTIME = 1063
+ SYS_LCHOWN = 1032
+ SYS_TIME = 1062
+ SYS_EPOLL_CREATE = 1042
+ SYS_EPOLL_WAIT = 1069
+)
+
+func Poll(fds []PollFd, timeout int) (n int, err error) {
+ var ts *Timespec
+ if timeout >= 0 {
+ ts = new(Timespec)
+ *ts = NsecToTimespec(int64(timeout) * 1e6)
+ }
+ if len(fds) == 0 {
+ return ppoll(nil, 0, ts, nil)
+ }
+ return ppoll(&fds[0], len(fds), ts, nil)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go
new file mode 100644
index 0000000..73318e5
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go
@@ -0,0 +1,209 @@
+// Copyright 2015 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 mips64 mips64le
+
+package unix
+
+//sys Dup2(oldfd int, newfd int) (err error)
+//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Fstatfs(fd int, buf *Statfs_t) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (euid int)
+//sysnb Getgid() (gid int)
+//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
+//sysnb Getuid() (uid int)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Listen(s int, n int) (err error)
+//sys Pause() (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 Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
+//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS_PSELECT6
+//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
+//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 Setrlimit(resource int, rlim *Rlimit) (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 Statfs(path string, buf *Statfs_t) (err error)
+//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
+//sys Truncate(path string, length int64) (err error)
+//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)
+//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
+
+func Getpagesize() int { return 65536 }
+
+//sysnb Gettimeofday(tv *Timeval) (err error)
+
+func Time(t *Time_t) (tt Time_t, err error) {
+ var tv Timeval
+ err = Gettimeofday(&tv)
+ if err != nil {
+ return 0, err
+ }
+ if t != nil {
+ *t = Time_t(tv.Sec)
+ }
+ return Time_t(tv.Sec), nil
+}
+
+//sys Utime(path string, buf *Utimbuf) (err error)
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Sec = nsec / 1e9
+ tv.Usec = nsec % 1e9 / 1e3
+ 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
+}
+
+//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 Ioperm(from int, num int, on int) (err error) {
+ return ENOSYS
+}
+
+func Iopl(level int) (err error) {
+ return ENOSYS
+}
+
+type stat_t struct {
+ Dev uint32
+ Pad0 [3]int32
+ Ino uint64
+ Mode uint32
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev uint32
+ Pad1 [3]uint32
+ Size int64
+ Atime uint32
+ Atime_nsec uint32
+ Mtime uint32
+ Mtime_nsec uint32
+ Ctime uint32
+ Ctime_nsec uint32
+ Blksize uint32
+ Pad2 uint32
+ Blocks int64
+}
+
+//sys fstat(fd int, st *stat_t) (err error)
+//sys lstat(path string, st *stat_t) (err error)
+//sys stat(path string, st *stat_t) (err error)
+
+func Fstat(fd int, s *Stat_t) (err error) {
+ st := &stat_t{}
+ err = fstat(fd, st)
+ fillStat_t(s, st)
+ return
+}
+
+func Lstat(path string, s *Stat_t) (err error) {
+ st := &stat_t{}
+ err = lstat(path, st)
+ fillStat_t(s, st)
+ return
+}
+
+func Stat(path string, s *Stat_t) (err error) {
+ st := &stat_t{}
+ err = stat(path, st)
+ fillStat_t(s, st)
+ return
+}
+
+func fillStat_t(s *Stat_t, st *stat_t) {
+ s.Dev = st.Dev
+ s.Ino = st.Ino
+ s.Mode = st.Mode
+ s.Nlink = st.Nlink
+ s.Uid = st.Uid
+ s.Gid = st.Gid
+ s.Rdev = st.Rdev
+ s.Size = st.Size
+ s.Atim = Timespec{int64(st.Atime), int64(st.Atime_nsec)}
+ s.Mtim = Timespec{int64(st.Mtime), int64(st.Mtime_nsec)}
+ s.Ctim = Timespec{int64(st.Ctime), int64(st.Ctime_nsec)}
+ s.Blksize = st.Blksize
+ s.Blocks = st.Blocks
+}
+
+func (r *PtraceRegs) PC() uint64 { return r.Epc }
+
+func (r *PtraceRegs) SetPC(pc uint64) { r.Epc = pc }
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint64(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint64(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)
+}
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..b83d93f
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go
@@ -0,0 +1,239 @@
+// 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)))
+ 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)))
+ 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 r.Epc }
+
+func (r *PtraceRegs) SetPC(pc uint64) { r.Epc = 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_linux_ppc64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go
new file mode 100644
index 0000000..60770f6
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go
@@ -0,0 +1,135 @@
+// Copyright 2009 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 ppc64 ppc64le
+
+package unix
+
+//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
+//sys Dup2(oldfd int, newfd int) (err error)
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Fstat(fd int, stat *Stat_t) (err error)
+//sys Fstatfs(fd int, buf *Statfs_t) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (euid int)
+//sysnb Getgid() (gid int)
+//sysnb Getrlimit(resource int, rlim *Rlimit) (err error) = SYS_UGETRLIMIT
+//sysnb Getuid() (uid int)
+//sysnb InotifyInit() (fd int, err error)
+//sys Ioperm(from int, num int, on int) (err error)
+//sys Iopl(level int) (err error)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Listen(s int, n int) (err error)
+//sys Lstat(path string, stat *Stat_t) (err error)
+//sys Pause() (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 Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
+//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
+//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
+//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 Setrlimit(resource int, rlim *Rlimit) (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 Stat(path string, stat *Stat_t) (err error)
+//sys Statfs(path string, buf *Statfs_t) (err error)
+//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) = SYS_SYNC_FILE_RANGE2
+//sys Truncate(path string, length int64) (err error)
+//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)
+//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
+
+func Getpagesize() int { return 65536 }
+
+//sysnb Gettimeofday(tv *Timeval) (err error)
+//sysnb Time(t *Time_t) (tt Time_t, err error)
+
+//sys Utime(path string, buf *Utimbuf) (err error)
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Sec = nsec / 1e9
+ tv.Usec = nsec % 1e9 / 1e3
+ return
+}
+
+func (r *PtraceRegs) PC() uint64 { return r.Nip }
+
+func (r *PtraceRegs) SetPC(pc uint64) { r.Nip = pc }
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint64(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint64(length)
+}
+
+//sysnb pipe(p *[2]_C_int) (err error)
+
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ var pp [2]_C_int
+ err = pipe(&pp)
+ p[0] = int(pp[0])
+ p[1] = int(pp[1])
+ 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
+}
+
+//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)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go
new file mode 100644
index 0000000..1708a4b
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go
@@ -0,0 +1,328 @@
+// 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 s390x,linux
+
+package unix
+
+import (
+ "unsafe"
+)
+
+//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
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Fstat(fd int, stat *Stat_t) (err error)
+//sys Fstatfs(fd int, buf *Statfs_t) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (euid int)
+//sysnb Getgid() (gid int)
+//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
+//sysnb Getuid() (uid int)
+//sysnb InotifyInit() (fd int, err error)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Lstat(path string, stat *Stat_t) (err error)
+//sys Pause() (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 Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
+//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
+//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
+//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 Setrlimit(resource int, rlim *Rlimit) (err error)
+//sysnb Setreuid(ruid int, euid int) (err error)
+//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
+//sys Stat(path string, stat *Stat_t) (err error)
+//sys Statfs(path string, buf *Statfs_t) (err error)
+//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
+//sys Truncate(path string, length int64) (err error)
+//sysnb getgroups(n int, list *_Gid_t) (nn int, err error)
+//sysnb setgroups(n int, list *_Gid_t) (err error)
+
+func Getpagesize() int { return 4096 }
+
+//sysnb Gettimeofday(tv *Timeval) (err error)
+
+func Time(t *Time_t) (tt Time_t, err error) {
+ var tv Timeval
+ err = Gettimeofday(&tv)
+ if err != nil {
+ return 0, err
+ }
+ if t != nil {
+ *t = Time_t(tv.Sec)
+ }
+ return Time_t(tv.Sec), nil
+}
+
+//sys Utime(path string, buf *Utimbuf) (err error)
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Sec = nsec / 1e9
+ tv.Usec = nsec % 1e9 / 1e3
+ return
+}
+
+//sysnb pipe2(p *[2]_C_int, flags int) (err error)
+
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ var pp [2]_C_int
+ err = pipe2(&pp, 0) // pipe2 is the same as pipe when flags are set to 0.
+ p[0] = int(pp[0])
+ p[1] = int(pp[1])
+ return
+}
+
+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 Ioperm(from int, num int, on int) (err error) {
+ return ENOSYS
+}
+
+func Iopl(level int) (err error) {
+ return ENOSYS
+}
+
+func (r *PtraceRegs) PC() uint64 { return r.Psw.Addr }
+
+func (r *PtraceRegs) SetPC(pc uint64) { r.Psw.Addr = pc }
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint64(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint64(length)
+}
+
+// Linux on s390x uses the old mmap interface, which requires arguments to be passed in a struct.
+// mmap2 also requires arguments to be passed in a struct; it is currently not exposed in <asm/unistd.h>.
+func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
+ mmap_args := [6]uintptr{addr, length, uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)}
+ r0, _, e1 := Syscall(SYS_MMAP, uintptr(unsafe.Pointer(&mmap_args[0])), 0, 0)
+ xaddr = uintptr(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// On s390x Linux, all the socket calls go through an extra indirection.
+// The arguments to the underlying system call (SYS_SOCKETCALL) are the
+// number below and a pointer to an array of uintptr.
+const (
+ // see linux/net.h
+ netSocket = 1
+ netBind = 2
+ netConnect = 3
+ netListen = 4
+ netAccept = 5
+ netGetSockName = 6
+ netGetPeerName = 7
+ netSocketPair = 8
+ netSend = 9
+ netRecv = 10
+ netSendTo = 11
+ netRecvFrom = 12
+ netShutdown = 13
+ netSetSockOpt = 14
+ netGetSockOpt = 15
+ netSendMsg = 16
+ netRecvMsg = 17
+ netAccept4 = 18
+ netRecvMMsg = 19
+ netSendMMsg = 20
+)
+
+func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (int, error) {
+ args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))}
+ fd, _, err := Syscall(SYS_SOCKETCALL, netAccept, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return 0, err
+ }
+ return int(fd), nil
+}
+
+func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (int, error) {
+ args := [4]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags)}
+ fd, _, err := Syscall(SYS_SOCKETCALL, netAccept4, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return 0, err
+ }
+ return int(fd), nil
+}
+
+func getsockname(s int, rsa *RawSockaddrAny, addrlen *_Socklen) error {
+ args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))}
+ _, _, err := RawSyscall(SYS_SOCKETCALL, netGetSockName, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+func getpeername(s int, rsa *RawSockaddrAny, addrlen *_Socklen) error {
+ args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))}
+ _, _, err := RawSyscall(SYS_SOCKETCALL, netGetPeerName, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+func socketpair(domain int, typ int, flags int, fd *[2]int32) error {
+ args := [4]uintptr{uintptr(domain), uintptr(typ), uintptr(flags), uintptr(unsafe.Pointer(fd))}
+ _, _, err := RawSyscall(SYS_SOCKETCALL, netSocketPair, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+func bind(s int, addr unsafe.Pointer, addrlen _Socklen) error {
+ args := [3]uintptr{uintptr(s), uintptr(addr), uintptr(addrlen)}
+ _, _, err := Syscall(SYS_SOCKETCALL, netBind, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+func connect(s int, addr unsafe.Pointer, addrlen _Socklen) error {
+ args := [3]uintptr{uintptr(s), uintptr(addr), uintptr(addrlen)}
+ _, _, err := Syscall(SYS_SOCKETCALL, netConnect, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+func socket(domain int, typ int, proto int) (int, error) {
+ args := [3]uintptr{uintptr(domain), uintptr(typ), uintptr(proto)}
+ fd, _, err := RawSyscall(SYS_SOCKETCALL, netSocket, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return 0, err
+ }
+ return int(fd), nil
+}
+
+func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) error {
+ args := [5]uintptr{uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen))}
+ _, _, err := Syscall(SYS_SOCKETCALL, netGetSockOpt, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) error {
+ args := [4]uintptr{uintptr(s), uintptr(level), uintptr(name), uintptr(val)}
+ _, _, err := Syscall(SYS_SOCKETCALL, netSetSockOpt, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+func recvfrom(s int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (int, error) {
+ var base uintptr
+ if len(p) > 0 {
+ base = uintptr(unsafe.Pointer(&p[0]))
+ }
+ args := [6]uintptr{uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))}
+ n, _, err := Syscall(SYS_SOCKETCALL, netRecvFrom, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return 0, err
+ }
+ return int(n), nil
+}
+
+func sendto(s int, p []byte, flags int, to unsafe.Pointer, addrlen _Socklen) error {
+ var base uintptr
+ if len(p) > 0 {
+ base = uintptr(unsafe.Pointer(&p[0]))
+ }
+ args := [6]uintptr{uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(to), uintptr(addrlen)}
+ _, _, err := Syscall(SYS_SOCKETCALL, netSendTo, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+func recvmsg(s int, msg *Msghdr, flags int) (int, error) {
+ args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)}
+ n, _, err := Syscall(SYS_SOCKETCALL, netRecvMsg, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return 0, err
+ }
+ return int(n), nil
+}
+
+func sendmsg(s int, msg *Msghdr, flags int) (int, error) {
+ args := [3]uintptr{uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)}
+ n, _, err := Syscall(SYS_SOCKETCALL, netSendMsg, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return 0, err
+ }
+ return int(n), nil
+}
+
+func Listen(s int, n int) error {
+ args := [2]uintptr{uintptr(s), uintptr(n)}
+ _, _, err := Syscall(SYS_SOCKETCALL, netListen, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+func Shutdown(s, how int) error {
+ args := [2]uintptr{uintptr(s), uintptr(how)}
+ _, _, err := Syscall(SYS_SOCKETCALL, netShutdown, uintptr(unsafe.Pointer(&args)), 0)
+ if err != 0 {
+ return err
+ }
+ return nil
+}
+
+//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)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go
new file mode 100644
index 0000000..20b7454
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go
@@ -0,0 +1,169 @@
+// Copyright 2009 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 sparc64,linux
+
+package unix
+
+import (
+ "sync/atomic"
+ "syscall"
+)
+
+//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
+//sys Dup2(oldfd int, newfd int) (err error)
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Fstat(fd int, stat *Stat_t) (err error)
+//sys Fstatfs(fd int, buf *Statfs_t) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (euid int)
+//sysnb Getgid() (gid int)
+//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
+//sysnb Getuid() (uid int)
+//sysnb InotifyInit() (fd int, err error)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Listen(s int, n int) (err error)
+//sys Lstat(path string, stat *Stat_t) (err error)
+//sys Pause() (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 Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
+//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
+//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
+//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 Setrlimit(resource int, rlim *Rlimit) (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 Stat(path string, stat *Stat_t) (err error)
+//sys Statfs(path string, buf *Statfs_t) (err error)
+//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
+//sys Truncate(path string, length int64) (err error)
+//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)
+//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
+
+func sysconf(name int) (n int64, err syscall.Errno)
+
+// pageSize caches the value of Getpagesize, since it can't change
+// once the system is booted.
+var pageSize int64 // accessed atomically
+
+func Getpagesize() int {
+ n := atomic.LoadInt64(&pageSize)
+ if n == 0 {
+ n, _ = sysconf(_SC_PAGESIZE)
+ atomic.StoreInt64(&pageSize, n)
+ }
+ return int(n)
+}
+
+func Ioperm(from int, num int, on int) (err error) {
+ return ENOSYS
+}
+
+func Iopl(level int) (err error) {
+ return ENOSYS
+}
+
+//sysnb Gettimeofday(tv *Timeval) (err error)
+
+func Time(t *Time_t) (tt Time_t, err error) {
+ var tv Timeval
+ err = Gettimeofday(&tv)
+ if err != nil {
+ return 0, err
+ }
+ if t != nil {
+ *t = Time_t(tv.Sec)
+ }
+ return Time_t(tv.Sec), nil
+}
+
+//sys Utime(path string, buf *Utimbuf) (err error)
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Sec = nsec / 1e9
+ tv.Usec = int32(nsec % 1e9 / 1e3)
+ return
+}
+
+func (r *PtraceRegs) PC() uint64 { return r.Tpc }
+
+func (r *PtraceRegs) SetPC(pc uint64) { r.Tpc = pc }
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint64(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint64(length)
+}
+
+//sysnb pipe(p *[2]_C_int) (err error)
+
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ var pp [2]_C_int
+ err = pipe(&pp)
+ p[0] = int(pp[0])
+ p[1] = int(pp[1])
+ 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
+}
+
+//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)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/golang.org/x/sys/unix/syscall_netbsd.go
new file mode 100644
index 0000000..e129668
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_netbsd.go
@@ -0,0 +1,472 @@
+// Copyright 2009,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.
+
+// NetBSD system calls.
+// This file is compiled as ordinary Go code,
+// but it is also input to mksyscall,
+// which parses the //sys lines and generates system call stubs.
+// Note that sometimes we use a lowercase //sys name and wrap
+// it in our own nicer implementation, either here or in
+// syscall_bsd.go or syscall_unix.go.
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+type SockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+ raw RawSockaddrDatalink
+}
+
+func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
+
+func sysctlNodes(mib []_C_int) (nodes []Sysctlnode, err error) {
+ var olen uintptr
+
+ // Get a list of all sysctl nodes below the given MIB by performing
+ // a sysctl for the given MIB with CTL_QUERY appended.
+ mib = append(mib, CTL_QUERY)
+ qnode := Sysctlnode{Flags: SYSCTL_VERS_1}
+ qp := (*byte)(unsafe.Pointer(&qnode))
+ sz := unsafe.Sizeof(qnode)
+ if err = sysctl(mib, nil, &olen, qp, sz); err != nil {
+ return nil, err
+ }
+
+ // Now that we know the size, get the actual nodes.
+ nodes = make([]Sysctlnode, olen/sz)
+ np := (*byte)(unsafe.Pointer(&nodes[0]))
+ if err = sysctl(mib, np, &olen, qp, sz); err != nil {
+ return nil, err
+ }
+
+ return nodes, nil
+}
+
+func nametomib(name string) (mib []_C_int, err error) {
+
+ // Split name into components.
+ var parts []string
+ last := 0
+ for i := 0; i < len(name); i++ {
+ if name[i] == '.' {
+ parts = append(parts, name[last:i])
+ last = i + 1
+ }
+ }
+ parts = append(parts, name[last:])
+
+ // Discover the nodes and construct the MIB OID.
+ for partno, part := range parts {
+ nodes, err := sysctlNodes(mib)
+ if err != nil {
+ return nil, err
+ }
+ for _, node := range nodes {
+ n := make([]byte, 0)
+ for i := range node.Name {
+ if node.Name[i] != 0 {
+ n = append(n, byte(node.Name[i]))
+ }
+ }
+ if string(n) == part {
+ mib = append(mib, _C_int(node.Num))
+ break
+ }
+ }
+ if len(mib) != partno+1 {
+ return nil, EINVAL
+ }
+ }
+
+ return mib, nil
+}
+
+func direntIno(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno))
+}
+
+func direntReclen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
+}
+
+func direntNamlen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))
+}
+
+//sysnb pipe() (fd1 int, fd2 int, err error)
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ p[0], p[1], err = pipe()
+ return
+}
+
+//sys getdents(fd int, buf []byte) (n int, err error)
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ return getdents(fd, buf)
+}
+
+// TODO
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ return -1, ENOSYS
+}
+
+/*
+ * Exposed directly
+ */
+//sys Access(path string, mode uint32) (err error)
+//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error)
+//sys Chdir(path string) (err error)
+//sys Chflags(path string, flags int) (err error)
+//sys Chmod(path string, mode uint32) (err error)
+//sys Chown(path string, uid int, gid int) (err error)
+//sys Chroot(path string) (err error)
+//sys Close(fd int) (err error)
+//sys Dup(fd int) (nfd int, err error)
+//sys Dup2(from int, to int) (err error)
+//sys Exit(code int)
+//sys Fchdir(fd int) (err error)
+//sys Fchflags(fd int, flags int) (err error)
+//sys Fchmod(fd int, mode uint32) (err error)
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Flock(fd int, how int) (err error)
+//sys Fpathconf(fd int, name int) (val int, err error)
+//sys Fstat(fd int, stat *Stat_t) (err error)
+//sys Fsync(fd int) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (uid int)
+//sysnb Getgid() (gid int)
+//sysnb Getpgid(pid int) (pgid int, err error)
+//sysnb Getpgrp() (pgrp int)
+//sysnb Getpid() (pid int)
+//sysnb Getppid() (ppid int)
+//sys Getpriority(which int, who int) (prio int, err error)
+//sysnb Getrlimit(which int, lim *Rlimit) (err error)
+//sysnb Getrusage(who int, rusage *Rusage) (err error)
+//sysnb Getsid(pid int) (sid int, err error)
+//sysnb Gettimeofday(tv *Timeval) (err error)
+//sysnb Getuid() (uid int)
+//sys Issetugid() (tainted bool)
+//sys Kill(pid int, signum syscall.Signal) (err error)
+//sys Kqueue() (fd int, err error)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Link(path string, link string) (err error)
+//sys Listen(s int, backlog int) (err error)
+//sys Lstat(path string, stat *Stat_t) (err error)
+//sys Mkdir(path string, mode uint32) (err error)
+//sys Mkfifo(path string, mode uint32) (err error)
+//sys Mknod(path string, mode uint32, dev int) (err error)
+//sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
+//sys Open(path string, mode int, perm uint32) (fd int, err error)
+//sys Pathconf(path string, name int) (val int, err error)
+//sys Pread(fd int, p []byte, offset int64) (n int, err error)
+//sys Pwrite(fd int, p []byte, offset int64) (n int, err error)
+//sys read(fd int, p []byte) (n int, err error)
+//sys Readlink(path string, buf []byte) (n int, err error)
+//sys Rename(from string, to string) (err error)
+//sys Revoke(path string) (err error)
+//sys Rmdir(path string) (err error)
+//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK
+//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error)
+//sysnb Setegid(egid int) (err error)
+//sysnb Seteuid(euid int) (err error)
+//sysnb Setgid(gid int) (err error)
+//sysnb Setpgid(pid int, pgid int) (err error)
+//sys Setpriority(which int, who int, prio int) (err error)
+//sysnb Setregid(rgid int, egid int) (err error)
+//sysnb Setreuid(ruid int, euid int) (err error)
+//sysnb Setrlimit(which int, lim *Rlimit) (err error)
+//sysnb Setsid() (pid int, err error)
+//sysnb Settimeofday(tp *Timeval) (err error)
+//sysnb Setuid(uid int) (err error)
+//sys Stat(path string, stat *Stat_t) (err error)
+//sys Symlink(path string, link string) (err error)
+//sys Sync() (err error)
+//sys Truncate(path string, length int64) (err error)
+//sys Umask(newmask int) (oldmask int)
+//sys Unlink(path string) (err error)
+//sys Unmount(path string, flags int) (err error)
+//sys write(fd int, p []byte) (n int, err error)
+//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
+//sys munmap(addr uintptr, length uintptr) (err error)
+//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ
+//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE
+//sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
+
+/*
+ * Unimplemented
+ */
+// ____semctl13
+// __clone
+// __fhopen40
+// __fhstat40
+// __fhstatvfs140
+// __fstat30
+// __getcwd
+// __getfh30
+// __getlogin
+// __lstat30
+// __mount50
+// __msgctl13
+// __msync13
+// __ntp_gettime30
+// __posix_chown
+// __posix_fadvise50
+// __posix_fchown
+// __posix_lchown
+// __posix_rename
+// __setlogin
+// __shmctl13
+// __sigaction_sigtramp
+// __sigaltstack14
+// __sigpending14
+// __sigprocmask14
+// __sigsuspend14
+// __sigtimedwait
+// __stat30
+// __syscall
+// __vfork14
+// _ksem_close
+// _ksem_destroy
+// _ksem_getvalue
+// _ksem_init
+// _ksem_open
+// _ksem_post
+// _ksem_trywait
+// _ksem_unlink
+// _ksem_wait
+// _lwp_continue
+// _lwp_create
+// _lwp_ctl
+// _lwp_detach
+// _lwp_exit
+// _lwp_getname
+// _lwp_getprivate
+// _lwp_kill
+// _lwp_park
+// _lwp_self
+// _lwp_setname
+// _lwp_setprivate
+// _lwp_suspend
+// _lwp_unpark
+// _lwp_unpark_all
+// _lwp_wait
+// _lwp_wakeup
+// _pset_bind
+// _sched_getaffinity
+// _sched_getparam
+// _sched_setaffinity
+// _sched_setparam
+// acct
+// aio_cancel
+// aio_error
+// aio_fsync
+// aio_read
+// aio_return
+// aio_suspend
+// aio_write
+// break
+// clock_getres
+// clock_gettime
+// clock_settime
+// compat_09_ogetdomainname
+// compat_09_osetdomainname
+// compat_09_ouname
+// compat_10_omsgsys
+// compat_10_osemsys
+// compat_10_oshmsys
+// compat_12_fstat12
+// compat_12_getdirentries
+// compat_12_lstat12
+// compat_12_msync
+// compat_12_oreboot
+// compat_12_oswapon
+// compat_12_stat12
+// compat_13_sigaction13
+// compat_13_sigaltstack13
+// compat_13_sigpending13
+// compat_13_sigprocmask13
+// compat_13_sigreturn13
+// compat_13_sigsuspend13
+// compat_14___semctl
+// compat_14_msgctl
+// compat_14_shmctl
+// compat_16___sigaction14
+// compat_16___sigreturn14
+// compat_20_fhstatfs
+// compat_20_fstatfs
+// compat_20_getfsstat
+// compat_20_statfs
+// compat_30___fhstat30
+// compat_30___fstat13
+// compat_30___lstat13
+// compat_30___stat13
+// compat_30_fhopen
+// compat_30_fhstat
+// compat_30_fhstatvfs1
+// compat_30_getdents
+// compat_30_getfh
+// compat_30_ntp_gettime
+// compat_30_socket
+// compat_40_mount
+// compat_43_fstat43
+// compat_43_lstat43
+// compat_43_oaccept
+// compat_43_ocreat
+// compat_43_oftruncate
+// compat_43_ogetdirentries
+// compat_43_ogetdtablesize
+// compat_43_ogethostid
+// compat_43_ogethostname
+// compat_43_ogetkerninfo
+// compat_43_ogetpagesize
+// compat_43_ogetpeername
+// compat_43_ogetrlimit
+// compat_43_ogetsockname
+// compat_43_okillpg
+// compat_43_olseek
+// compat_43_ommap
+// compat_43_oquota
+// compat_43_orecv
+// compat_43_orecvfrom
+// compat_43_orecvmsg
+// compat_43_osend
+// compat_43_osendmsg
+// compat_43_osethostid
+// compat_43_osethostname
+// compat_43_osetrlimit
+// compat_43_osigblock
+// compat_43_osigsetmask
+// compat_43_osigstack
+// compat_43_osigvec
+// compat_43_otruncate
+// compat_43_owait
+// compat_43_stat43
+// execve
+// extattr_delete_fd
+// extattr_delete_file
+// extattr_delete_link
+// extattr_get_fd
+// extattr_get_file
+// extattr_get_link
+// extattr_list_fd
+// extattr_list_file
+// extattr_list_link
+// extattr_set_fd
+// extattr_set_file
+// extattr_set_link
+// extattrctl
+// fchroot
+// fdatasync
+// fgetxattr
+// fktrace
+// flistxattr
+// fork
+// fremovexattr
+// fsetxattr
+// fstatvfs1
+// fsync_range
+// getcontext
+// getitimer
+// getvfsstat
+// getxattr
+// ioctl
+// ktrace
+// lchflags
+// lchmod
+// lfs_bmapv
+// lfs_markv
+// lfs_segclean
+// lfs_segwait
+// lgetxattr
+// lio_listio
+// listxattr
+// llistxattr
+// lremovexattr
+// lseek
+// lsetxattr
+// lutimes
+// madvise
+// mincore
+// minherit
+// modctl
+// mq_close
+// mq_getattr
+// mq_notify
+// mq_open
+// mq_receive
+// mq_send
+// mq_setattr
+// mq_timedreceive
+// mq_timedsend
+// mq_unlink
+// mremap
+// msgget
+// msgrcv
+// msgsnd
+// nfssvc
+// ntp_adjtime
+// pmc_control
+// pmc_get_info
+// poll
+// pollts
+// preadv
+// profil
+// pselect
+// pset_assign
+// pset_create
+// pset_destroy
+// ptrace
+// pwritev
+// quotactl
+// rasctl
+// readv
+// reboot
+// removexattr
+// sa_enable
+// sa_preempt
+// sa_register
+// sa_setconcurrency
+// sa_stacks
+// sa_yield
+// sbrk
+// sched_yield
+// semconfig
+// semget
+// semop
+// setcontext
+// setitimer
+// setxattr
+// shmat
+// shmdt
+// shmget
+// sstk
+// statvfs1
+// swapctl
+// sysarch
+// syscall
+// timer_create
+// timer_delete
+// timer_getoverrun
+// timer_gettime
+// timer_settime
+// undelete
+// utrace
+// uuidgen
+// vadvise
+// vfork
+// writev
diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd_386.go b/vendor/golang.org/x/sys/unix/syscall_netbsd_386.go
new file mode 100644
index 0000000..afaca09
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_netbsd_386.go
@@ -0,0 +1,42 @@
+// Copyright 2009 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 386,netbsd
+
+package unix
+
+func Getpagesize() int { return 4096 }
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = int64(nsec / 1e9)
+ ts.Nsec = int32(nsec % 1e9)
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = int64(nsec / 1e9)
+ return
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint32(fd)
+ k.Filter = uint32(mode)
+ k.Flags = uint32(flags)
+}
+
+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)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go
new file mode 100644
index 0000000..a6ff04c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go
@@ -0,0 +1,42 @@
+// Copyright 2009 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,netbsd
+
+package unix
+
+func Getpagesize() int { return 4096 }
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = int64(nsec / 1e9)
+ ts.Nsec = int64(nsec % 1e9)
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = int64(nsec / 1e9)
+ return
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint64(fd)
+ k.Filter = uint32(mode)
+ k.Flags = uint32(flags)
+}
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint32(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint32(length)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go b/vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go
new file mode 100644
index 0000000..68a6969
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go
@@ -0,0 +1,42 @@
+// 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.
+
+// +build arm,netbsd
+
+package unix
+
+func Getpagesize() int { return 4096 }
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = int64(nsec / 1e9)
+ ts.Nsec = int32(nsec % 1e9)
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = int64(nsec / 1e9)
+ return
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint32(fd)
+ k.Filter = uint32(mode)
+ k.Flags = uint32(flags)
+}
+
+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)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_no_getwd.go b/vendor/golang.org/x/sys/unix/syscall_no_getwd.go
new file mode 100644
index 0000000..530792e
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_no_getwd.go
@@ -0,0 +1,11 @@
+// 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.
+
+// +build dragonfly freebsd netbsd openbsd
+
+package unix
+
+const ImplementsGetwd = false
+
+func Getwd() (string, error) { return "", ENOTSUP }
diff --git a/vendor/golang.org/x/sys/unix/syscall_openbsd.go b/vendor/golang.org/x/sys/unix/syscall_openbsd.go
new file mode 100644
index 0000000..408e630
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_openbsd.go
@@ -0,0 +1,282 @@
+// Copyright 2009,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.
+
+// OpenBSD system calls.
+// This file is compiled as ordinary Go code,
+// but it is also input to mksyscall,
+// which parses the //sys lines and generates system call stubs.
+// Note that sometimes we use a lowercase //sys name and wrap
+// it in our own nicer implementation, either here or in
+// syscall_bsd.go or syscall_unix.go.
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+type SockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [24]int8
+ raw RawSockaddrDatalink
+}
+
+func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
+
+func nametomib(name string) (mib []_C_int, err error) {
+
+ // Perform lookup via a binary search
+ left := 0
+ right := len(sysctlMib) - 1
+ for {
+ idx := left + (right-left)/2
+ switch {
+ case name == sysctlMib[idx].ctlname:
+ return sysctlMib[idx].ctloid, nil
+ case name > sysctlMib[idx].ctlname:
+ left = idx + 1
+ default:
+ right = idx - 1
+ }
+ if left > right {
+ break
+ }
+ }
+ return nil, EINVAL
+}
+
+func direntIno(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno))
+}
+
+func direntReclen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
+}
+
+func direntNamlen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))
+}
+
+//sysnb pipe(p *[2]_C_int) (err error)
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ var pp [2]_C_int
+ err = pipe(&pp)
+ p[0] = int(pp[0])
+ p[1] = int(pp[1])
+ return
+}
+
+//sys getdents(fd int, buf []byte) (n int, err error)
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ return getdents(fd, buf)
+}
+
+// TODO
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ return -1, ENOSYS
+}
+
+func Getfsstat(buf []Statfs_t, flags int) (n int, err error) {
+ var _p0 unsafe.Pointer
+ var bufsize uintptr
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf))
+ }
+ r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags))
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+/*
+ * Exposed directly
+ */
+//sys Access(path string, mode uint32) (err error)
+//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error)
+//sys Chdir(path string) (err error)
+//sys Chflags(path string, flags int) (err error)
+//sys Chmod(path string, mode uint32) (err error)
+//sys Chown(path string, uid int, gid int) (err error)
+//sys Chroot(path string) (err error)
+//sys Close(fd int) (err error)
+//sys Dup(fd int) (nfd int, err error)
+//sys Dup2(from int, to int) (err error)
+//sys Exit(code int)
+//sys Fchdir(fd int) (err error)
+//sys Fchflags(fd int, flags int) (err error)
+//sys Fchmod(fd int, mode uint32) (err error)
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Flock(fd int, how int) (err error)
+//sys Fpathconf(fd int, name int) (val int, err error)
+//sys Fstat(fd int, stat *Stat_t) (err error)
+//sys Fstatfs(fd int, stat *Statfs_t) (err error)
+//sys Fsync(fd int) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sysnb Getegid() (egid int)
+//sysnb Geteuid() (uid int)
+//sysnb Getgid() (gid int)
+//sysnb Getpgid(pid int) (pgid int, err error)
+//sysnb Getpgrp() (pgrp int)
+//sysnb Getpid() (pid int)
+//sysnb Getppid() (ppid int)
+//sys Getpriority(which int, who int) (prio int, err error)
+//sysnb Getrlimit(which int, lim *Rlimit) (err error)
+//sysnb Getrusage(who int, rusage *Rusage) (err error)
+//sysnb Getsid(pid int) (sid int, err error)
+//sysnb Gettimeofday(tv *Timeval) (err error)
+//sysnb Getuid() (uid int)
+//sys Issetugid() (tainted bool)
+//sys Kill(pid int, signum syscall.Signal) (err error)
+//sys Kqueue() (fd int, err error)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Link(path string, link string) (err error)
+//sys Listen(s int, backlog int) (err error)
+//sys Lstat(path string, stat *Stat_t) (err error)
+//sys Mkdir(path string, mode uint32) (err error)
+//sys Mkfifo(path string, mode uint32) (err error)
+//sys Mknod(path string, mode uint32, dev int) (err error)
+//sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
+//sys Open(path string, mode int, perm uint32) (fd int, err error)
+//sys Pathconf(path string, name int) (val int, err error)
+//sys Pread(fd int, p []byte, offset int64) (n int, err error)
+//sys Pwrite(fd int, p []byte, offset int64) (n int, err error)
+//sys read(fd int, p []byte) (n int, err error)
+//sys Readlink(path string, buf []byte) (n int, err error)
+//sys Rename(from string, to string) (err error)
+//sys Revoke(path string) (err error)
+//sys Rmdir(path string) (err error)
+//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK
+//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error)
+//sysnb Setegid(egid int) (err error)
+//sysnb Seteuid(euid int) (err error)
+//sysnb Setgid(gid int) (err error)
+//sys Setlogin(name string) (err error)
+//sysnb Setpgid(pid int, pgid int) (err error)
+//sys Setpriority(which int, who int, prio int) (err error)
+//sysnb Setregid(rgid int, egid int) (err error)
+//sysnb Setreuid(ruid int, euid int) (err error)
+//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
+//sysnb Setresuid(ruid int, euid int, suid int) (err error)
+//sysnb Setrlimit(which int, lim *Rlimit) (err error)
+//sysnb Setsid() (pid int, err error)
+//sysnb Settimeofday(tp *Timeval) (err error)
+//sysnb Setuid(uid int) (err error)
+//sys Stat(path string, stat *Stat_t) (err error)
+//sys Statfs(path string, stat *Statfs_t) (err error)
+//sys Symlink(path string, link string) (err error)
+//sys Sync() (err error)
+//sys Truncate(path string, length int64) (err error)
+//sys Umask(newmask int) (oldmask int)
+//sys Unlink(path string) (err error)
+//sys Unmount(path string, flags int) (err error)
+//sys write(fd int, p []byte) (n int, err error)
+//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
+//sys munmap(addr uintptr, length uintptr) (err error)
+//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ
+//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE
+//sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
+
+/*
+ * Unimplemented
+ */
+// __getcwd
+// __semctl
+// __syscall
+// __sysctl
+// adjfreq
+// break
+// clock_getres
+// clock_gettime
+// clock_settime
+// closefrom
+// execve
+// faccessat
+// fchmodat
+// fchownat
+// fcntl
+// fhopen
+// fhstat
+// fhstatfs
+// fork
+// fstatat
+// futimens
+// getfh
+// getgid
+// getitimer
+// getlogin
+// getresgid
+// getresuid
+// getrtable
+// getthrid
+// ioctl
+// ktrace
+// lfs_bmapv
+// lfs_markv
+// lfs_segclean
+// lfs_segwait
+// linkat
+// mincore
+// minherit
+// mkdirat
+// mkfifoat
+// mknodat
+// mount
+// mquery
+// msgctl
+// msgget
+// msgrcv
+// msgsnd
+// nfssvc
+// nnpfspioctl
+// openat
+// poll
+// preadv
+// profil
+// pwritev
+// quotactl
+// readlinkat
+// readv
+// reboot
+// renameat
+// rfork
+// sched_yield
+// semget
+// semop
+// setgroups
+// setitimer
+// setrtable
+// setsockopt
+// shmat
+// shmctl
+// shmdt
+// shmget
+// sigaction
+// sigaltstack
+// sigpending
+// sigprocmask
+// sigreturn
+// sigsuspend
+// symlinkat
+// sysarch
+// syscall
+// threxit
+// thrsigdivert
+// thrsleep
+// thrwakeup
+// unlinkat
+// vfork
+// writev
diff --git a/vendor/golang.org/x/sys/unix/syscall_openbsd_386.go b/vendor/golang.org/x/sys/unix/syscall_openbsd_386.go
new file mode 100644
index 0000000..a66ddc5
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_openbsd_386.go
@@ -0,0 +1,42 @@
+// Copyright 2009 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 386,openbsd
+
+package unix
+
+func Getpagesize() int { return 4096 }
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = int64(nsec / 1e9)
+ ts.Nsec = int32(nsec % 1e9)
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = int64(nsec / 1e9)
+ return
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint32(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+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)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go
new file mode 100644
index 0000000..0776c1f
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go
@@ -0,0 +1,42 @@
+// Copyright 2009 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,openbsd
+
+package unix
+
+func Getpagesize() int { return 4096 }
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = nsec % 1e9 / 1e3
+ tv.Sec = nsec / 1e9
+ return
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint64(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (msghdr *Msghdr) SetControllen(length int) {
+ msghdr.Controllen = uint32(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint32(length)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go b/vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go
new file mode 100644
index 0000000..14ddaf3
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go
@@ -0,0 +1,44 @@
+// Copyright 2017 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 arm,openbsd
+
+package unix
+
+import "syscall"
+
+func Getpagesize() int { return syscall.Getpagesize() }
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = int64(nsec / 1e9)
+ ts.Nsec = int32(nsec % 1e9)
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = int32(nsec % 1e9 / 1e3)
+ tv.Sec = int64(nsec / 1e9)
+ return
+}
+
+func SetKevent(k *Kevent_t, fd, mode, flags int) {
+ k.Ident = uint32(fd)
+ k.Filter = int16(mode)
+ k.Flags = uint16(flags)
+}
+
+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)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris.go b/vendor/golang.org/x/sys/unix/syscall_solaris.go
new file mode 100644
index 0000000..0d4e5c4
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_solaris.go
@@ -0,0 +1,716 @@
+// Copyright 2009 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.
+
+// Solaris system calls.
+// This file is compiled as ordinary Go code,
+// but it is also input to mksyscall,
+// which parses the //sys lines and generates system call stubs.
+// Note that sometimes we use a lowercase //sys name and wrap
+// it in our own nicer implementation, either here or in
+// syscall_solaris.go or syscall_unix.go.
+
+package unix
+
+import (
+ "sync/atomic"
+ "syscall"
+ "unsafe"
+)
+
+// Implemented in runtime/syscall_solaris.go.
+type syscallFunc uintptr
+
+func rawSysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
+func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
+
+type SockaddrDatalink struct {
+ Family uint16
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [244]int8
+ raw RawSockaddrDatalink
+}
+
+func clen(n []byte) int {
+ for i := 0; i < len(n); i++ {
+ if n[i] == 0 {
+ return i
+ }
+ }
+ return len(n)
+}
+
+func direntIno(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
+}
+
+func direntReclen(buf []byte) (uint64, bool) {
+ return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
+}
+
+func direntNamlen(buf []byte) (uint64, bool) {
+ reclen, ok := direntReclen(buf)
+ if !ok {
+ return 0, false
+ }
+ return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true
+}
+
+//sysnb pipe(p *[2]_C_int) (n int, err error)
+
+func Pipe(p []int) (err error) {
+ if len(p) != 2 {
+ return EINVAL
+ }
+ var pp [2]_C_int
+ n, err := pipe(&pp)
+ if n != 0 {
+ return err
+ }
+ p[0] = int(pp[0])
+ p[1] = int(pp[1])
+ return nil
+}
+
+func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ if sa.Port < 0 || sa.Port > 0xFFFF {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Family = AF_INET
+ p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
+ p[0] = byte(sa.Port >> 8)
+ p[1] = byte(sa.Port)
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.raw.Addr[i] = sa.Addr[i]
+ }
+ return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
+}
+
+func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ if sa.Port < 0 || sa.Port > 0xFFFF {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Family = AF_INET6
+ p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
+ p[0] = byte(sa.Port >> 8)
+ p[1] = byte(sa.Port)
+ sa.raw.Scope_id = sa.ZoneId
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.raw.Addr[i] = sa.Addr[i]
+ }
+ return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
+}
+
+func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
+ name := sa.Name
+ n := len(name)
+ if n >= len(sa.raw.Path) {
+ return nil, 0, EINVAL
+ }
+ sa.raw.Family = AF_UNIX
+ for i := 0; i < n; i++ {
+ sa.raw.Path[i] = int8(name[i])
+ }
+ // length is family (uint16), name, NUL.
+ sl := _Socklen(2)
+ if n > 0 {
+ sl += _Socklen(n) + 1
+ }
+ if sa.raw.Path[0] == '@' {
+ sa.raw.Path[0] = 0
+ // Don't count trailing NUL for abstract address.
+ sl--
+ }
+
+ return unsafe.Pointer(&sa.raw), sl, nil
+}
+
+//sys getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getsockname
+
+func Getsockname(fd int) (sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ if err = getsockname(fd, &rsa, &len); err != nil {
+ return
+ }
+ return anyToSockaddr(&rsa)
+}
+
+const ImplementsGetwd = true
+
+//sys Getcwd(buf []byte) (n int, err error)
+
+func Getwd() (wd string, err error) {
+ var buf [PathMax]byte
+ // Getcwd will return an error if it failed for any reason.
+ _, err = Getcwd(buf[0:])
+ if err != nil {
+ return "", err
+ }
+ n := clen(buf[:])
+ if n < 1 {
+ return "", EINVAL
+ }
+ return string(buf[:n]), nil
+}
+
+/*
+ * Wrapped
+ */
+
+//sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error)
+//sysnb setgroups(ngid int, gid *_Gid_t) (err error)
+
+func Getgroups() (gids []int, err error) {
+ n, err := getgroups(0, nil)
+ // Check for error and sanity check group count. Newer versions of
+ // Solaris allow up to 1024 (NGROUPS_MAX).
+ if n < 0 || n > 1024 {
+ if err != nil {
+ return nil, err
+ }
+ return nil, EINVAL
+ } else if n == 0 {
+ return nil, nil
+ }
+
+ a := make([]_Gid_t, n)
+ n, err = getgroups(n, &a[0])
+ if n == -1 {
+ return nil, err
+ }
+ gids = make([]int, n)
+ for i, v := range a[0:n] {
+ gids[i] = int(v)
+ }
+ return
+}
+
+func Setgroups(gids []int) (err error) {
+ if len(gids) == 0 {
+ return setgroups(0, nil)
+ }
+
+ a := make([]_Gid_t, len(gids))
+ for i, v := range gids {
+ a[i] = _Gid_t(v)
+ }
+ return setgroups(len(a), &a[0])
+}
+
+func ReadDirent(fd int, buf []byte) (n int, err error) {
+ // Final argument is (basep *uintptr) and the syscall doesn't take nil.
+ // TODO(rsc): Can we use a single global basep for all calls?
+ return Getdents(fd, buf, new(uintptr))
+}
+
+// Wait status is 7 bits at bottom, either 0 (exited),
+// 0x7F (stopped), or a signal number that caused an exit.
+// The 0x80 bit is whether there was a core dump.
+// An extra number (exit code, signal causing a stop)
+// is in the high bits.
+
+type WaitStatus uint32
+
+const (
+ mask = 0x7F
+ core = 0x80
+ shift = 8
+
+ exited = 0
+ stopped = 0x7F
+)
+
+func (w WaitStatus) Exited() bool { return w&mask == exited }
+
+func (w WaitStatus) ExitStatus() int {
+ if w&mask != exited {
+ return -1
+ }
+ return int(w >> shift)
+}
+
+func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 }
+
+func (w WaitStatus) Signal() syscall.Signal {
+ sig := syscall.Signal(w & mask)
+ if sig == stopped || sig == 0 {
+ return -1
+ }
+ return sig
+}
+
+func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
+
+func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP }
+
+func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP }
+
+func (w WaitStatus) StopSignal() syscall.Signal {
+ if !w.Stopped() {
+ return -1
+ }
+ return syscall.Signal(w>>shift) & 0xFF
+}
+
+func (w WaitStatus) TrapCause() int { return -1 }
+
+//sys wait4(pid int32, statusp *_C_int, options int, rusage *Rusage) (wpid int32, err error)
+
+func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (int, error) {
+ var status _C_int
+ rpid, err := wait4(int32(pid), &status, options, rusage)
+ wpid := int(rpid)
+ if wpid == -1 {
+ return wpid, err
+ }
+ if wstatus != nil {
+ *wstatus = WaitStatus(status)
+ }
+ return wpid, nil
+}
+
+//sys gethostname(buf []byte) (n int, err error)
+
+func Gethostname() (name string, err error) {
+ var buf [MaxHostNameLen]byte
+ n, err := gethostname(buf[:])
+ if n != 0 {
+ return "", err
+ }
+ n = clen(buf[:])
+ if n < 1 {
+ return "", EFAULT
+ }
+ return string(buf[:n]), nil
+}
+
+//sys utimes(path string, times *[2]Timeval) (err error)
+
+func Utimes(path string, tv []Timeval) (err error) {
+ if tv == nil {
+ return utimes(path, nil)
+ }
+ if len(tv) != 2 {
+ return EINVAL
+ }
+ return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
+}
+
+//sys utimensat(fd int, path string, times *[2]Timespec, flag int) (err error)
+
+func UtimesNano(path string, ts []Timespec) error {
+ if ts == nil {
+ return utimensat(AT_FDCWD, path, nil, 0)
+ }
+ if len(ts) != 2 {
+ return EINVAL
+ }
+ return utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
+}
+
+func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
+ if ts == nil {
+ return utimensat(dirfd, path, nil, flags)
+ }
+ if len(ts) != 2 {
+ return EINVAL
+ }
+ return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
+}
+
+//sys fcntl(fd int, cmd int, arg int) (val int, err error)
+
+// FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command.
+func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(lk)), 0, 0, 0)
+ if e1 != 0 {
+ return e1
+ }
+ return nil
+}
+
+//sys futimesat(fildes int, path *byte, times *[2]Timeval) (err error)
+
+func Futimesat(dirfd int, path string, tv []Timeval) error {
+ pathp, err := BytePtrFromString(path)
+ if err != nil {
+ return err
+ }
+ if tv == nil {
+ return futimesat(dirfd, pathp, nil)
+ }
+ if len(tv) != 2 {
+ return EINVAL
+ }
+ return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
+}
+
+// Solaris doesn't have an futimes function because it allows NULL to be
+// specified as the path for futimesat. However, Go doesn't like
+// NULL-style string interfaces, so this simple wrapper is provided.
+func Futimes(fd int, tv []Timeval) error {
+ if tv == nil {
+ return futimesat(fd, nil, nil)
+ }
+ if len(tv) != 2 {
+ return EINVAL
+ }
+ return futimesat(fd, nil, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
+}
+
+func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
+ switch rsa.Addr.Family {
+ case AF_UNIX:
+ pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
+ sa := new(SockaddrUnix)
+ // Assume path ends at NUL.
+ // This is not technically the Solaris semantics for
+ // abstract Unix domain sockets -- they are supposed
+ // to be uninterpreted fixed-size binary blobs -- but
+ // everyone uses this convention.
+ n := 0
+ for n < len(pp.Path) && pp.Path[n] != 0 {
+ n++
+ }
+ bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
+ sa.Name = string(bytes)
+ return sa, nil
+
+ case AF_INET:
+ pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
+ sa := new(SockaddrInet4)
+ p := (*[2]byte)(unsafe.Pointer(&pp.Port))
+ sa.Port = int(p[0])<<8 + int(p[1])
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.Addr[i] = pp.Addr[i]
+ }
+ return sa, nil
+
+ case AF_INET6:
+ pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
+ sa := new(SockaddrInet6)
+ p := (*[2]byte)(unsafe.Pointer(&pp.Port))
+ sa.Port = int(p[0])<<8 + int(p[1])
+ sa.ZoneId = pp.Scope_id
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.Addr[i] = pp.Addr[i]
+ }
+ return sa, nil
+ }
+ return nil, EAFNOSUPPORT
+}
+
+//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) = libsocket.accept
+
+func Accept(fd int) (nfd int, sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ nfd, err = accept(fd, &rsa, &len)
+ if nfd == -1 {
+ return
+ }
+ sa, err = anyToSockaddr(&rsa)
+ if err != nil {
+ Close(nfd)
+ nfd = 0
+ }
+ return
+}
+
+//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.__xnet_recvmsg
+
+func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
+ var msg Msghdr
+ var rsa RawSockaddrAny
+ msg.Name = (*byte)(unsafe.Pointer(&rsa))
+ msg.Namelen = uint32(SizeofSockaddrAny)
+ var iov Iovec
+ if len(p) > 0 {
+ iov.Base = (*int8)(unsafe.Pointer(&p[0]))
+ iov.SetLen(len(p))
+ }
+ var dummy int8
+ if len(oob) > 0 {
+ // receive at least one normal byte
+ if len(p) == 0 {
+ iov.Base = &dummy
+ iov.SetLen(1)
+ }
+ msg.Accrightslen = int32(len(oob))
+ }
+ msg.Iov = &iov
+ msg.Iovlen = 1
+ if n, err = recvmsg(fd, &msg, flags); n == -1 {
+ return
+ }
+ oobn = int(msg.Accrightslen)
+ // source address is only specified if the socket is unconnected
+ if rsa.Addr.Family != AF_UNSPEC {
+ from, err = anyToSockaddr(&rsa)
+ }
+ return
+}
+
+func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
+ _, err = SendmsgN(fd, p, oob, to, flags)
+ return
+}
+
+//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.__xnet_sendmsg
+
+func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
+ var ptr unsafe.Pointer
+ var salen _Socklen
+ if to != nil {
+ ptr, salen, err = to.sockaddr()
+ if err != nil {
+ return 0, err
+ }
+ }
+ var msg Msghdr
+ msg.Name = (*byte)(unsafe.Pointer(ptr))
+ msg.Namelen = uint32(salen)
+ var iov Iovec
+ if len(p) > 0 {
+ iov.Base = (*int8)(unsafe.Pointer(&p[0]))
+ iov.SetLen(len(p))
+ }
+ var dummy int8
+ if len(oob) > 0 {
+ // send at least one normal byte
+ if len(p) == 0 {
+ iov.Base = &dummy
+ iov.SetLen(1)
+ }
+ msg.Accrightslen = int32(len(oob))
+ }
+ msg.Iov = &iov
+ msg.Iovlen = 1
+ if n, err = sendmsg(fd, &msg, flags); err != nil {
+ return 0, err
+ }
+ if len(oob) > 0 && len(p) == 0 {
+ n = 0
+ }
+ return n, nil
+}
+
+//sys acct(path *byte) (err error)
+
+func Acct(path string) (err error) {
+ if len(path) == 0 {
+ // Assume caller wants to disable accounting.
+ return acct(nil)
+ }
+
+ pathp, err := BytePtrFromString(path)
+ if err != nil {
+ return err
+ }
+ return acct(pathp)
+}
+
+/*
+ * Expose the ioctl function
+ */
+
+//sys ioctl(fd int, req uint, arg uintptr) (err error)
+
+func IoctlSetInt(fd int, req uint, value int) (err error) {
+ return ioctl(fd, req, uintptr(value))
+}
+
+func IoctlSetWinsize(fd int, req uint, value *Winsize) (err error) {
+ return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
+}
+
+func IoctlSetTermios(fd int, req uint, value *Termios) (err error) {
+ return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
+}
+
+func IoctlSetTermio(fd int, req uint, value *Termio) (err error) {
+ return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
+}
+
+func IoctlGetInt(fd int, req uint) (int, error) {
+ var value int
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return value, err
+}
+
+func IoctlGetWinsize(fd int, req uint) (*Winsize, error) {
+ var value Winsize
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return &value, err
+}
+
+func IoctlGetTermios(fd int, req uint) (*Termios, error) {
+ var value Termios
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return &value, err
+}
+
+func IoctlGetTermio(fd int, req uint) (*Termio, error) {
+ var value Termio
+ err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
+ return &value, err
+}
+
+/*
+ * Exposed directly
+ */
+//sys Access(path string, mode uint32) (err error)
+//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error)
+//sys Chdir(path string) (err error)
+//sys Chmod(path string, mode uint32) (err error)
+//sys Chown(path string, uid int, gid int) (err error)
+//sys Chroot(path string) (err error)
+//sys Close(fd int) (err error)
+//sys Creat(path string, mode uint32) (fd int, err error)
+//sys Dup(fd int) (nfd int, err error)
+//sys Dup2(oldfd int, newfd int) (err error)
+//sys Exit(code int)
+//sys Fchdir(fd int) (err error)
+//sys Fchmod(fd int, mode uint32) (err error)
+//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
+//sys Fchown(fd int, uid int, gid int) (err error)
+//sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
+//sys Fdatasync(fd int) (err error)
+//sys Flock(fd int, how int) (err error)
+//sys Fpathconf(fd int, name int) (val int, err error)
+//sys Fstat(fd int, stat *Stat_t) (err error)
+//sys Fstatvfs(fd int, vfsstat *Statvfs_t) (err error)
+//sys Getdents(fd int, buf []byte, basep *uintptr) (n int, err error)
+//sysnb Getgid() (gid int)
+//sysnb Getpid() (pid int)
+//sysnb Getpgid(pid int) (pgid int, err error)
+//sysnb Getpgrp() (pgid int, err error)
+//sys Geteuid() (euid int)
+//sys Getegid() (egid int)
+//sys Getppid() (ppid int)
+//sys Getpriority(which int, who int) (n int, err error)
+//sysnb Getrlimit(which int, lim *Rlimit) (err error)
+//sysnb Getrusage(who int, rusage *Rusage) (err error)
+//sysnb Gettimeofday(tv *Timeval) (err error)
+//sysnb Getuid() (uid int)
+//sys Kill(pid int, signum syscall.Signal) (err error)
+//sys Lchown(path string, uid int, gid int) (err error)
+//sys Link(path string, link string) (err error)
+//sys Listen(s int, backlog int) (err error) = libsocket.__xnet_llisten
+//sys Lstat(path string, stat *Stat_t) (err error)
+//sys Madvise(b []byte, advice int) (err error)
+//sys Mkdir(path string, mode uint32) (err error)
+//sys Mkdirat(dirfd int, path string, mode uint32) (err error)
+//sys Mkfifo(path string, mode uint32) (err error)
+//sys Mkfifoat(dirfd int, path string, mode uint32) (err error)
+//sys Mknod(path string, mode uint32, dev int) (err error)
+//sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
+//sys Mlock(b []byte) (err error)
+//sys Mlockall(flags int) (err error)
+//sys Mprotect(b []byte, prot int) (err error)
+//sys Munlock(b []byte) (err error)
+//sys Munlockall() (err error)
+//sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
+//sys Open(path string, mode int, perm uint32) (fd int, err error)
+//sys Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
+//sys Pathconf(path string, name int) (val int, err error)
+//sys Pause() (err error)
+//sys Pread(fd int, p []byte, offset int64) (n int, err error)
+//sys Pwrite(fd int, p []byte, offset int64) (n int, err error)
+//sys read(fd int, p []byte) (n int, err error)
+//sys Readlink(path string, buf []byte) (n int, err error)
+//sys Rename(from string, to string) (err error)
+//sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
+//sys Rmdir(path string) (err error)
+//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = lseek
+//sysnb Setegid(egid int) (err error)
+//sysnb Seteuid(euid int) (err error)
+//sysnb Setgid(gid int) (err error)
+//sys Sethostname(p []byte) (err error)
+//sysnb Setpgid(pid int, pgid int) (err error)
+//sys Setpriority(which int, who int, prio int) (err error)
+//sysnb Setregid(rgid int, egid int) (err error)
+//sysnb Setreuid(ruid int, euid int) (err error)
+//sysnb Setrlimit(which int, lim *Rlimit) (err error)
+//sysnb Setsid() (pid int, err error)
+//sysnb Setuid(uid int) (err error)
+//sys Shutdown(s int, how int) (err error) = libsocket.shutdown
+//sys Stat(path string, stat *Stat_t) (err error)
+//sys Statvfs(path string, vfsstat *Statvfs_t) (err error)
+//sys Symlink(path string, link string) (err error)
+//sys Sync() (err error)
+//sysnb Times(tms *Tms) (ticks uintptr, err error)
+//sys Truncate(path string, length int64) (err error)
+//sys Fsync(fd int) (err error)
+//sys Ftruncate(fd int, length int64) (err error)
+//sys Umask(mask int) (oldmask int)
+//sysnb Uname(buf *Utsname) (err error)
+//sys Unmount(target string, flags int) (err error) = libc.umount
+//sys Unlink(path string) (err error)
+//sys Unlinkat(dirfd int, path string, flags int) (err error)
+//sys Ustat(dev int, ubuf *Ustat_t) (err error)
+//sys Utime(path string, buf *Utimbuf) (err error)
+//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_bind
+//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_connect
+//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
+//sys munmap(addr uintptr, length uintptr) (err error)
+//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_sendto
+//sys socket(domain int, typ int, proto int) (fd int, err error) = libsocket.__xnet_socket
+//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) = libsocket.__xnet_socketpair
+//sys write(fd int, p []byte) (n int, err error)
+//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) = libsocket.__xnet_getsockopt
+//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getpeername
+//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) = libsocket.setsockopt
+//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) = libsocket.recvfrom
+
+func readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procread)), 3, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf), 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func writelen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwrite)), 3, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf), 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+var mapper = &mmapper{
+ active: make(map[*byte][]byte),
+ mmap: mmap,
+ munmap: munmap,
+}
+
+func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
+ return mapper.Mmap(fd, offset, length, prot, flags)
+}
+
+func Munmap(b []byte) (err error) {
+ return mapper.Munmap(b)
+}
+
+//sys sysconf(name int) (n int64, err error)
+
+// pageSize caches the value of Getpagesize, since it can't change
+// once the system is booted.
+var pageSize int64 // accessed atomically
+
+func Getpagesize() int {
+ n := atomic.LoadInt64(&pageSize)
+ if n == 0 {
+ n, _ = sysconf(_SC_PAGESIZE)
+ atomic.StoreInt64(&pageSize, n)
+ }
+ return int(n)
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go b/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go
new file mode 100644
index 0000000..5aff62c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go
@@ -0,0 +1,35 @@
+// Copyright 2009 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,solaris
+
+package unix
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ nsec += 999 // round up to microsecond
+ tv.Usec = nsec % 1e9 / 1e3
+ tv.Sec = int64(nsec / 1e9)
+ return
+}
+
+func (iov *Iovec) SetLen(length int) {
+ iov.Len = uint64(length)
+}
+
+func (cmsg *Cmsghdr) SetLen(length int) {
+ cmsg.Len = uint32(length)
+}
+
+func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ // TODO(aram): implement this, see issue 5847.
+ panic("unimplemented")
+}
diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go
new file mode 100644
index 0000000..3ed8a91
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/syscall_unix.go
@@ -0,0 +1,293 @@
+// Copyright 2009 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
+
+package unix
+
+import (
+ "runtime"
+ "sync"
+ "syscall"
+ "unsafe"
+)
+
+var (
+ Stdin = 0
+ Stdout = 1
+ Stderr = 2
+)
+
+const (
+ darwin64Bit = runtime.GOOS == "darwin" && sizeofPtr == 8
+ dragonfly64Bit = runtime.GOOS == "dragonfly" && sizeofPtr == 8
+ netbsd32Bit = runtime.GOOS == "netbsd" && sizeofPtr == 4
+ solaris64Bit = runtime.GOOS == "solaris" && sizeofPtr == 8
+)
+
+// Do the interface allocations only once for common
+// Errno values.
+var (
+ errEAGAIN error = syscall.EAGAIN
+ errEINVAL error = syscall.EINVAL
+ errENOENT error = syscall.ENOENT
+)
+
+// errnoErr returns common boxed Errno values, to prevent
+// allocations at runtime.
+func errnoErr(e syscall.Errno) error {
+ switch e {
+ case 0:
+ return nil
+ case EAGAIN:
+ return errEAGAIN
+ case EINVAL:
+ return errEINVAL
+ case ENOENT:
+ return errENOENT
+ }
+ return e
+}
+
+// Mmap manager, for use by operating system-specific implementations.
+
+type mmapper struct {
+ sync.Mutex
+ active map[*byte][]byte // active mappings; key is last byte in mapping
+ mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error)
+ munmap func(addr uintptr, length uintptr) error
+}
+
+func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
+ if length <= 0 {
+ return nil, EINVAL
+ }
+
+ // Map the requested memory.
+ addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset)
+ if errno != nil {
+ return nil, errno
+ }
+
+ // Slice memory layout
+ var sl = struct {
+ addr uintptr
+ len int
+ cap int
+ }{addr, length, length}
+
+ // Use unsafe to turn sl into a []byte.
+ b := *(*[]byte)(unsafe.Pointer(&sl))
+
+ // Register mapping in m and return it.
+ p := &b[cap(b)-1]
+ m.Lock()
+ defer m.Unlock()
+ m.active[p] = b
+ return b, nil
+}
+
+func (m *mmapper) Munmap(data []byte) (err error) {
+ if len(data) == 0 || len(data) != cap(data) {
+ return EINVAL
+ }
+
+ // Find the base of the mapping.
+ p := &data[cap(data)-1]
+ m.Lock()
+ defer m.Unlock()
+ b := m.active[p]
+ if b == nil || &b[0] != &data[0] {
+ return EINVAL
+ }
+
+ // Unmap the memory and update m.
+ if errno := m.munmap(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))); errno != nil {
+ return errno
+ }
+ delete(m.active, p)
+ return nil
+}
+
+func Read(fd int, p []byte) (n int, err error) {
+ n, err = read(fd, p)
+ if raceenabled {
+ if n > 0 {
+ raceWriteRange(unsafe.Pointer(&p[0]), n)
+ }
+ if err == nil {
+ raceAcquire(unsafe.Pointer(&ioSync))
+ }
+ }
+ return
+}
+
+func Write(fd int, p []byte) (n int, err error) {
+ if raceenabled {
+ raceReleaseMerge(unsafe.Pointer(&ioSync))
+ }
+ n, err = write(fd, p)
+ if raceenabled && n > 0 {
+ raceReadRange(unsafe.Pointer(&p[0]), n)
+ }
+ return
+}
+
+// For testing: clients can set this flag to force
+// creation of IPv6 sockets to return EAFNOSUPPORT.
+var SocketDisableIPv6 bool
+
+type Sockaddr interface {
+ sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs
+}
+
+type SockaddrInet4 struct {
+ Port int
+ Addr [4]byte
+ raw RawSockaddrInet4
+}
+
+type SockaddrInet6 struct {
+ Port int
+ ZoneId uint32
+ Addr [16]byte
+ raw RawSockaddrInet6
+}
+
+type SockaddrUnix struct {
+ Name string
+ raw RawSockaddrUnix
+}
+
+func Bind(fd int, sa Sockaddr) (err error) {
+ ptr, n, err := sa.sockaddr()
+ if err != nil {
+ return err
+ }
+ return bind(fd, ptr, n)
+}
+
+func Connect(fd int, sa Sockaddr) (err error) {
+ ptr, n, err := sa.sockaddr()
+ if err != nil {
+ return err
+ }
+ return connect(fd, ptr, n)
+}
+
+func Getpeername(fd int) (sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ if err = getpeername(fd, &rsa, &len); err != nil {
+ return
+ }
+ return anyToSockaddr(&rsa)
+}
+
+func GetsockoptInt(fd, level, opt int) (value int, err error) {
+ var n int32
+ vallen := _Socklen(4)
+ err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen)
+ return int(n), err
+}
+
+func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ var len _Socklen = SizeofSockaddrAny
+ if n, err = recvfrom(fd, p, flags, &rsa, &len); err != nil {
+ return
+ }
+ if rsa.Addr.Family != AF_UNSPEC {
+ from, err = anyToSockaddr(&rsa)
+ }
+ return
+}
+
+func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error) {
+ ptr, n, err := to.sockaddr()
+ if err != nil {
+ return err
+ }
+ return sendto(fd, p, flags, ptr, n)
+}
+
+func SetsockoptByte(fd, level, opt int, value byte) (err error) {
+ return setsockopt(fd, level, opt, unsafe.Pointer(&value), 1)
+}
+
+func SetsockoptInt(fd, level, opt int, value int) (err error) {
+ var n = int32(value)
+ return setsockopt(fd, level, opt, unsafe.Pointer(&n), 4)
+}
+
+func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error) {
+ return setsockopt(fd, level, opt, unsafe.Pointer(&value[0]), 4)
+}
+
+func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error) {
+ return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPMreq)
+}
+
+func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error) {
+ return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPv6Mreq)
+}
+
+func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error {
+ return setsockopt(fd, level, opt, unsafe.Pointer(filter), SizeofICMPv6Filter)
+}
+
+func SetsockoptLinger(fd, level, opt int, l *Linger) (err error) {
+ return setsockopt(fd, level, opt, unsafe.Pointer(l), SizeofLinger)
+}
+
+func SetsockoptString(fd, level, opt int, s string) (err error) {
+ return setsockopt(fd, level, opt, unsafe.Pointer(&[]byte(s)[0]), uintptr(len(s)))
+}
+
+func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error) {
+ return setsockopt(fd, level, opt, unsafe.Pointer(tv), unsafe.Sizeof(*tv))
+}
+
+func Socket(domain, typ, proto int) (fd int, err error) {
+ if domain == AF_INET6 && SocketDisableIPv6 {
+ return -1, EAFNOSUPPORT
+ }
+ fd, err = socket(domain, typ, proto)
+ return
+}
+
+func Socketpair(domain, typ, proto int) (fd [2]int, err error) {
+ var fdx [2]int32
+ err = socketpair(domain, typ, proto, &fdx)
+ if err == nil {
+ fd[0] = int(fdx[0])
+ fd[1] = int(fdx[1])
+ }
+ return
+}
+
+func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
+ if raceenabled {
+ raceReleaseMerge(unsafe.Pointer(&ioSync))
+ }
+ return sendfile(outfd, infd, offset, count)
+}
+
+var ioSync int64
+
+func CloseOnExec(fd int) { fcntl(fd, F_SETFD, FD_CLOEXEC) }
+
+func SetNonblock(fd int, nonblocking bool) (err error) {
+ flag, err := fcntl(fd, F_GETFL, 0)
+ if err != nil {
+ return err
+ }
+ if nonblocking {
+ flag |= O_NONBLOCK
+ } else {
+ flag &= ^O_NONBLOCK
+ }
+ _, err = fcntl(fd, F_SETFL, flag)
+ return err
+}
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/zerrors_darwin_386.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_386.go
new file mode 100644
index 0000000..1c68758
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_386.go
@@ -0,0 +1,1673 @@
+// mkerrors.sh -m32
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build 386,darwin
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m32 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1c
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x25
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x1e
+ AF_IPX = 0x17
+ AF_ISDN = 0x1c
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x28
+ AF_NATM = 0x1f
+ AF_NDRV = 0x1b
+ AF_NETBIOS = 0x21
+ AF_NS = 0x6
+ AF_OSI = 0x7
+ AF_PPP = 0x22
+ AF_PUP = 0x4
+ AF_RESERVED_36 = 0x24
+ AF_ROUTE = 0x11
+ AF_SIP = 0x18
+ AF_SNA = 0xb
+ AF_SYSTEM = 0x20
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ AF_UTUN = 0x26
+ ALTWERASE = 0x200
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B9600 = 0x2580
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc00c4279
+ BIOCGETIF = 0x4020426b
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044272
+ BIOCGRTIMEOUT = 0x4008426e
+ BIOCGSEESENT = 0x40044276
+ BIOCGSTATS = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDLT = 0x80044278
+ BIOCSETF = 0x80084267
+ BIOCSETFNR = 0x8008427e
+ BIOCSETIF = 0x8020426c
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044273
+ BIOCSRTIMEOUT = 0x8008426d
+ BIOCSSEESENT = 0x80044277
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ 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_MAXBUFSIZE = 0x80000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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 = 0x8000
+ BSDLY = 0x8000
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CLOCK_MONOTONIC = 0x6
+ CLOCK_MONOTONIC_RAW = 0x4
+ CLOCK_MONOTONIC_RAW_APPROX = 0x5
+ CLOCK_PROCESS_CPUTIME_ID = 0xc
+ CLOCK_REALTIME = 0x0
+ CLOCK_THREAD_CPUTIME_ID = 0x10
+ CLOCK_UPTIME_RAW = 0x8
+ CLOCK_UPTIME_RAW_APPROX = 0x9
+ CR0 = 0x0
+ CR1 = 0x1000
+ CR2 = 0x2000
+ CR3 = 0x3000
+ CRDLY = 0x3000
+ CREAD = 0x800
+ CRTSCTS = 0x30000
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_AOS = 0xde
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_CAN20B = 0xbe
+ DLT_CAN_SOCKETCAN = 0xe3
+ DLT_CHAOS = 0x5
+ DLT_CHDLC = 0x68
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DBUS = 0xe7
+ DLT_DECT = 0xdd
+ DLT_DOCSIS = 0x8f
+ DLT_DVB_CI = 0xeb
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FC_2 = 0xe0
+ DLT_FC_2_WITH_FRAME_DELIMS = 0xe1
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_GSMTAP_ABIS = 0xda
+ DLT_GSMTAP_UM = 0xd9
+ DLT_HHDLC = 0x79
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NOFCS = 0xe6
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_IPFILTER = 0x74
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IPNET = 0xe2
+ DLT_IPOIB = 0xf2
+ DLT_IPV4 = 0xe4
+ DLT_IPV6 = 0xe5
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_ATM_CEMIC = 0xee
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FIBRECHANNEL = 0xea
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_SRX_E2E = 0xe9
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_JUNIPER_VS = 0xe8
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_EVDEV = 0xd8
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_PPP_WITHDIRECTION = 0xa6
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MATCHING_MAX = 0xf5
+ DLT_MATCHING_MIN = 0x68
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MPEG_2_TS = 0xf3
+ DLT_MPLS = 0xdb
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_MUX27010 = 0xec
+ DLT_NETANALYZER = 0xf0
+ DLT_NETANALYZER_TRANSPARENT = 0xf1
+ DLT_NFC_LLCP = 0xf5
+ DLT_NFLOG = 0xef
+ DLT_NG40 = 0xf4
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0x10
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PPP_WITH_DIRECTION = 0xa6
+ DLT_PRISM_HEADER = 0x77
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_RIO = 0x7c
+ DLT_SCCP = 0x8e
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xf
+ DLT_STANAG_5066_D_PDU = 0xed
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USB_LINUX = 0xbd
+ DLT_USB_LINUX_MMAPPED = 0xdc
+ DLT_USER0 = 0x93
+ DLT_USER1 = 0x94
+ DLT_USER10 = 0x9d
+ DLT_USER11 = 0x9e
+ DLT_USER12 = 0x9f
+ DLT_USER13 = 0xa0
+ DLT_USER14 = 0xa1
+ DLT_USER15 = 0xa2
+ DLT_USER2 = 0x95
+ DLT_USER3 = 0x96
+ DLT_USER4 = 0x97
+ DLT_USER5 = 0x98
+ DLT_USER6 = 0x99
+ DLT_USER7 = 0x9a
+ DLT_USER8 = 0x9b
+ DLT_USER9 = 0x9c
+ DLT_WIHART = 0xdf
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EVFILT_AIO = -0x3
+ EVFILT_EXCEPT = -0xf
+ EVFILT_FS = -0x9
+ EVFILT_MACHPORT = -0x8
+ EVFILT_PROC = -0x5
+ EVFILT_READ = -0x1
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0xf
+ EVFILT_THREADMARKER = 0xf
+ EVFILT_TIMER = -0x7
+ EVFILT_USER = -0xa
+ EVFILT_VM = -0xc
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_DISPATCH = 0x80
+ EV_DISPATCH2 = 0x180
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG0 = 0x1000
+ EV_FLAG1 = 0x2000
+ EV_ONESHOT = 0x10
+ EV_OOBAND = 0x2000
+ EV_POLL = 0x1000
+ EV_RECEIPT = 0x40
+ EV_SYSFLAGS = 0xf000
+ EV_UDATA_SPECIFIC = 0x100
+ EV_VANISHED = 0x200
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x4000
+ FFDLY = 0x4000
+ FLUSHO = 0x800000
+ F_ADDFILESIGS = 0x3d
+ F_ADDFILESIGS_FOR_DYLD_SIM = 0x53
+ F_ADDFILESIGS_RETURN = 0x61
+ F_ADDSIGS = 0x3b
+ F_ALLOCATEALL = 0x4
+ F_ALLOCATECONTIG = 0x2
+ F_BARRIERFSYNC = 0x55
+ F_CHECK_LV = 0x62
+ F_CHKCLEAN = 0x29
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x43
+ F_FINDSIGS = 0x4e
+ F_FLUSH_DATA = 0x28
+ F_FREEZE_FS = 0x35
+ F_FULLFSYNC = 0x33
+ F_GETCODEDIR = 0x48
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETLKPID = 0x42
+ F_GETNOSIGPIPE = 0x4a
+ F_GETOWN = 0x5
+ F_GETPATH = 0x32
+ F_GETPATH_MTMINFO = 0x47
+ F_GETPROTECTIONCLASS = 0x3f
+ F_GETPROTECTIONLEVEL = 0x4d
+ F_GLOBAL_NOCACHE = 0x37
+ F_LOG2PHYS = 0x31
+ F_LOG2PHYS_EXT = 0x41
+ F_NOCACHE = 0x30
+ F_NODIRECT = 0x3e
+ F_OK = 0x0
+ F_PATHPKG_CHECK = 0x34
+ F_PEOFPOSMODE = 0x3
+ F_PREALLOCATE = 0x2a
+ F_RDADVISE = 0x2c
+ F_RDAHEAD = 0x2d
+ F_RDLCK = 0x1
+ F_SETBACKINGSTORE = 0x46
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETLKWTIMEOUT = 0xa
+ F_SETNOSIGPIPE = 0x49
+ F_SETOWN = 0x6
+ F_SETPROTECTIONCLASS = 0x40
+ F_SETSIZE = 0x2b
+ F_SINGLE_WRITER = 0x4c
+ F_THAW_FS = 0x36
+ F_TRANSCODEKEY = 0x4b
+ F_UNLCK = 0x2
+ F_VOLPOSMODE = 0x4
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFF_ALLMULTI = 0x200
+ IFF_ALTPHYS = 0x4000
+ IFF_BROADCAST = 0x2
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NOTRAILERS = 0x20
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_AAL5 = 0x31
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ATM = 0x25
+ IFT_BRIDGE = 0xd1
+ IFT_CARP = 0xf8
+ IFT_CELLULAR = 0xff
+ IFT_CEPT = 0x13
+ IFT_DS3 = 0x1e
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0x38
+ IFT_FDDI = 0xf
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_GIF = 0x37
+ IFT_HDH1822 = 0x3
+ IFT_HIPPI = 0x2f
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE8023ADLAG = 0x88
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88026 = 0xa
+ IFT_L2VLAN = 0x87
+ IFT_LAPB = 0x10
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_NSIP = 0x1b
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PDP = 0xff
+ IFT_PFLOG = 0xf5
+ IFT_PFSYNC = 0xf6
+ IFT_PKTAP = 0xfe
+ IFT_PPP = 0x17
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PTPSERIAL = 0x16
+ IFT_RS232 = 0x21
+ IFT_SDLC = 0x11
+ IFT_SIP = 0x1f
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_STARLAN = 0xb
+ IFT_STF = 0x39
+ IFT_T1 = 0x12
+ IFT_ULTRA = 0x1d
+ IFT_V35 = 0x2d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LINKLOCALNETNUM = 0xa9fe0000
+ IN_LOOPBACKNET = 0x7f
+ IPPROTO_3PC = 0x22
+ IPPROTO_ADFS = 0x44
+ IPPROTO_AH = 0x33
+ IPPROTO_AHIP = 0x3d
+ IPPROTO_APES = 0x63
+ IPPROTO_ARGUS = 0xd
+ IPPROTO_AX25 = 0x5d
+ IPPROTO_BHA = 0x31
+ IPPROTO_BLT = 0x1e
+ IPPROTO_BRSATMON = 0x4c
+ IPPROTO_CFTP = 0x3e
+ IPPROTO_CHAOS = 0x10
+ IPPROTO_CMTP = 0x26
+ IPPROTO_CPHB = 0x49
+ IPPROTO_CPNX = 0x48
+ IPPROTO_DDP = 0x25
+ IPPROTO_DGP = 0x56
+ IPPROTO_DIVERT = 0xfe
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_EMCON = 0xe
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GMTP = 0x64
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HELLO = 0x3f
+ IPPROTO_HMP = 0x14
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IDPR = 0x23
+ IPPROTO_IDRP = 0x2d
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IGP = 0x55
+ IPPROTO_IGRP = 0x58
+ IPPROTO_IL = 0x28
+ IPPROTO_INLSP = 0x34
+ IPPROTO_INP = 0x20
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPCV = 0x47
+ IPPROTO_IPEIP = 0x5e
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPPC = 0x43
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IRTP = 0x1c
+ IPPROTO_KRYPTOLAN = 0x41
+ IPPROTO_LARP = 0x5b
+ IPPROTO_LEAF1 = 0x19
+ IPPROTO_LEAF2 = 0x1a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x34
+ IPPROTO_MEAS = 0x13
+ IPPROTO_MHRP = 0x30
+ IPPROTO_MICP = 0x5f
+ IPPROTO_MTP = 0x5c
+ IPPROTO_MUX = 0x12
+ IPPROTO_ND = 0x4d
+ IPPROTO_NHRP = 0x36
+ IPPROTO_NONE = 0x3b
+ IPPROTO_NSP = 0x1f
+ IPPROTO_NVPII = 0xb
+ IPPROTO_OSPFIGP = 0x59
+ IPPROTO_PGM = 0x71
+ IPPROTO_PIGP = 0x9
+ IPPROTO_PIM = 0x67
+ IPPROTO_PRM = 0x15
+ IPPROTO_PUP = 0xc
+ IPPROTO_PVP = 0x4b
+ IPPROTO_RAW = 0xff
+ IPPROTO_RCCMON = 0xa
+ IPPROTO_RDP = 0x1b
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_RVD = 0x42
+ IPPROTO_SATEXPAK = 0x40
+ IPPROTO_SATMON = 0x45
+ IPPROTO_SCCSP = 0x60
+ IPPROTO_SCTP = 0x84
+ IPPROTO_SDRP = 0x2a
+ IPPROTO_SEP = 0x21
+ IPPROTO_SRPC = 0x5a
+ IPPROTO_ST = 0x7
+ IPPROTO_SVMTP = 0x52
+ IPPROTO_SWIPE = 0x35
+ IPPROTO_TCF = 0x57
+ IPPROTO_TCP = 0x6
+ IPPROTO_TP = 0x1d
+ IPPROTO_TPXX = 0x27
+ IPPROTO_TRUNK1 = 0x17
+ IPPROTO_TRUNK2 = 0x18
+ IPPROTO_TTP = 0x54
+ IPPROTO_UDP = 0x11
+ IPPROTO_VINES = 0x53
+ IPPROTO_VISA = 0x46
+ IPPROTO_VMTP = 0x51
+ IPPROTO_WBEXPAK = 0x4f
+ IPPROTO_WBMON = 0x4e
+ IPPROTO_WSN = 0x4a
+ IPPROTO_XNET = 0xf
+ IPPROTO_XTP = 0x24
+ IPV6_2292DSTOPTS = 0x17
+ IPV6_2292HOPLIMIT = 0x14
+ IPV6_2292HOPOPTS = 0x16
+ IPV6_2292NEXTHOP = 0x15
+ IPV6_2292PKTINFO = 0x13
+ IPV6_2292PKTOPTIONS = 0x19
+ IPV6_2292RTHDR = 0x18
+ IPV6_BINDV6ONLY = 0x1b
+ IPV6_BOUND_IF = 0x7d
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x3c
+ IPV6_FW_ADD = 0x1e
+ IPV6_FW_DEL = 0x1f
+ IPV6_FW_FLUSH = 0x20
+ IPV6_FW_GET = 0x22
+ IPV6_FW_ZERO = 0x21
+ IPV6_HLIMDEC = 0x1
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXOPTHDR = 0x800
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MAX_GROUP_SRC_FILTER = 0x200
+ IPV6_MAX_MEMBERSHIPS = 0xfff
+ IPV6_MAX_SOCK_SRC_FILTER = 0x80
+ IPV6_MIN_MEMBERSHIPS = 0x1f
+ IPV6_MMTU = 0x500
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_RECVTCLASS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x24
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_ADD_SOURCE_MEMBERSHIP = 0x46
+ IP_BLOCK_SOURCE = 0x48
+ IP_BOUND_IF = 0x19
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_DROP_SOURCE_MEMBERSHIP = 0x47
+ IP_DUMMYNET_CONFIGURE = 0x3c
+ IP_DUMMYNET_DEL = 0x3d
+ IP_DUMMYNET_FLUSH = 0x3e
+ IP_DUMMYNET_GET = 0x40
+ IP_FAITH = 0x16
+ IP_FW_ADD = 0x28
+ IP_FW_DEL = 0x29
+ IP_FW_FLUSH = 0x2a
+ IP_FW_GET = 0x2c
+ IP_FW_RESETLOG = 0x2d
+ IP_FW_ZERO = 0x2b
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x15
+ IP_MAXPACKET = 0xffff
+ IP_MAX_GROUP_SRC_FILTER = 0x200
+ IP_MAX_MEMBERSHIPS = 0xfff
+ IP_MAX_SOCK_MUTE_FILTER = 0x80
+ IP_MAX_SOCK_SRC_FILTER = 0x80
+ IP_MF = 0x2000
+ IP_MIN_MEMBERSHIPS = 0x1f
+ IP_MSFILTER = 0x4a
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_IFINDEX = 0x42
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_MULTICAST_VIF = 0xe
+ IP_NAT__XXX = 0x37
+ IP_OFFMASK = 0x1fff
+ IP_OLD_FW_ADD = 0x32
+ IP_OLD_FW_DEL = 0x33
+ IP_OLD_FW_FLUSH = 0x34
+ IP_OLD_FW_GET = 0x36
+ IP_OLD_FW_RESETLOG = 0x38
+ IP_OLD_FW_ZERO = 0x35
+ IP_OPTIONS = 0x1
+ IP_PKTINFO = 0x1a
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVPKTINFO = 0x1a
+ IP_RECVRETOPTS = 0x6
+ IP_RECVTTL = 0x18
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RSVP_OFF = 0x10
+ IP_RSVP_ON = 0xf
+ IP_RSVP_VIF_OFF = 0x12
+ IP_RSVP_VIF_ON = 0x11
+ IP_STRIPHDR = 0x17
+ IP_TOS = 0x3
+ IP_TRAFFIC_MGT_BACKGROUND = 0x41
+ IP_TTL = 0x4
+ IP_UNBLOCK_SOURCE = 0x49
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IUTF8 = 0x4000
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_CAN_REUSE = 0x9
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x5
+ MADV_FREE_REUSABLE = 0x7
+ MADV_FREE_REUSE = 0x8
+ MADV_NORMAL = 0x0
+ MADV_PAGEOUT = 0xa
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_WILLNEED = 0x3
+ MADV_ZERO_WIRED_PAGES = 0x6
+ MAP_ANON = 0x1000
+ MAP_ANONYMOUS = 0x1000
+ MAP_COPY = 0x2
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_HASSEMAPHORE = 0x200
+ MAP_JIT = 0x800
+ MAP_NOCACHE = 0x400
+ MAP_NOEXTEND = 0x100
+ MAP_NORESERVE = 0x40
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_RESERVED0080 = 0x80
+ MAP_RESILIENT_CODESIGN = 0x2000
+ MAP_RESILIENT_MEDIA = 0x4000
+ MAP_SHARED = 0x1
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MNT_ASYNC = 0x40
+ MNT_AUTOMOUNTED = 0x400000
+ MNT_CMDFLAGS = 0xf0000
+ MNT_CPROTECT = 0x80
+ MNT_DEFWRITE = 0x2000000
+ MNT_DONTBROWSE = 0x100000
+ MNT_DOVOLFS = 0x8000
+ MNT_DWAIT = 0x4
+ MNT_EXPORTED = 0x100
+ MNT_FORCE = 0x80000
+ MNT_IGNORE_OWNERSHIP = 0x200000
+ MNT_JOURNALED = 0x800000
+ MNT_LOCAL = 0x1000
+ MNT_MULTILABEL = 0x4000000
+ MNT_NOATIME = 0x10000000
+ MNT_NOBLOCK = 0x20000
+ MNT_NODEV = 0x10
+ MNT_NOEXEC = 0x4
+ MNT_NOSUID = 0x8
+ MNT_NOUSERXATTR = 0x1000000
+ MNT_NOWAIT = 0x2
+ MNT_QUARANTINE = 0x400
+ MNT_QUOTA = 0x2000
+ MNT_RDONLY = 0x1
+ MNT_RELOAD = 0x40000
+ MNT_ROOTFS = 0x4000
+ MNT_SYNCHRONOUS = 0x2
+ MNT_UNION = 0x20
+ MNT_UNKNOWNPERMISSIONS = 0x200000
+ MNT_UPDATE = 0x10000
+ MNT_VISFLAGMASK = 0x17f0f5ff
+ MNT_WAIT = 0x1
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOF = 0x100
+ MSG_EOR = 0x8
+ MSG_FLUSH = 0x400
+ MSG_HAVEMORE = 0x2000
+ MSG_HOLD = 0x800
+ MSG_NEEDSA = 0x10000
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_RCVMORE = 0x4000
+ MSG_SEND = 0x1000
+ MSG_TRUNC = 0x10
+ MSG_WAITALL = 0x40
+ MSG_WAITSTREAM = 0x200
+ MS_ASYNC = 0x1
+ MS_DEACTIVATE = 0x8
+ MS_INVALIDATE = 0x2
+ MS_KILLPAGES = 0x4
+ MS_SYNC = 0x10
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_DUMP2 = 0x7
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_IFLIST2 = 0x6
+ NET_RT_MAXID = 0xa
+ NET_RT_STAT = 0x4
+ NET_RT_TRASH = 0x5
+ NL0 = 0x0
+ NL1 = 0x100
+ NL2 = 0x200
+ NL3 = 0x300
+ NLDLY = 0x300
+ NOFLSH = 0x80000000
+ NOKERNINFO = 0x2000000
+ NOTE_ABSOLUTE = 0x8
+ NOTE_ATTRIB = 0x8
+ NOTE_BACKGROUND = 0x40
+ NOTE_CHILD = 0x4
+ NOTE_CRITICAL = 0x20
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXITSTATUS = 0x4000000
+ NOTE_EXIT_CSERROR = 0x40000
+ NOTE_EXIT_DECRYPTFAIL = 0x10000
+ NOTE_EXIT_DETAIL = 0x2000000
+ NOTE_EXIT_DETAIL_MASK = 0x70000
+ NOTE_EXIT_MEMORY = 0x20000
+ NOTE_EXIT_REPARENTED = 0x80000
+ NOTE_EXTEND = 0x4
+ NOTE_FFAND = 0x40000000
+ NOTE_FFCOPY = 0xc0000000
+ NOTE_FFCTRLMASK = 0xc0000000
+ NOTE_FFLAGSMASK = 0xffffff
+ NOTE_FFNOP = 0x0
+ NOTE_FFOR = 0x80000000
+ NOTE_FORK = 0x40000000
+ NOTE_FUNLOCK = 0x100
+ NOTE_LEEWAY = 0x10
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_MACH_CONTINUOUS_TIME = 0x80
+ NOTE_NONE = 0x80
+ NOTE_NSECONDS = 0x4
+ NOTE_OOB = 0x2
+ NOTE_PCTRLMASK = -0x100000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_REAP = 0x10000000
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_SECONDS = 0x1
+ NOTE_SIGNAL = 0x8000000
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRIGGER = 0x1000000
+ NOTE_USECONDS = 0x2
+ NOTE_VM_ERROR = 0x10000000
+ NOTE_VM_PRESSURE = 0x80000000
+ NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000
+ NOTE_VM_PRESSURE_TERMINATE = 0x40000000
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ OFDEL = 0x20000
+ OFILL = 0x80
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ OXTABS = 0x4
+ O_ACCMODE = 0x3
+ O_ALERT = 0x20000000
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x1000000
+ O_CREAT = 0x200
+ O_DIRECTORY = 0x100000
+ O_DP_GETRAWENCRYPTED = 0x1
+ O_DP_GETRAWUNENCRYPTED = 0x2
+ O_DSYNC = 0x400000
+ O_EVTONLY = 0x8000
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x20000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_POPUP = 0x80000000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_SHLOCK = 0x10
+ O_SYMLINK = 0x200000
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ PT_ATTACH = 0xa
+ PT_ATTACHEXC = 0xe
+ PT_CONTINUE = 0x7
+ PT_DENY_ATTACH = 0x1f
+ PT_DETACH = 0xb
+ PT_FIRSTMACH = 0x20
+ PT_FORCEQUOTA = 0x1e
+ PT_KILL = 0x8
+ PT_READ_D = 0x2
+ PT_READ_I = 0x1
+ PT_READ_U = 0x3
+ PT_SIGEXC = 0xc
+ PT_STEP = 0x9
+ PT_THUPDATE = 0xd
+ PT_TRACE_ME = 0x0
+ PT_WRITE_D = 0x5
+ PT_WRITE_I = 0x4
+ PT_WRITE_U = 0x6
+ RLIMIT_AS = 0x5
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_CPU_USAGE_MONITOR = 0x2
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_MEMLOCK = 0x6
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_NPROC = 0x7
+ RLIMIT_RSS = 0x5
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x8
+ RTAX_NETMASK = 0x2
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTF_BLACKHOLE = 0x1000
+ RTF_BROADCAST = 0x400000
+ RTF_CLONING = 0x100
+ RTF_CONDEMNED = 0x2000000
+ RTF_DELCLONE = 0x80
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_IFREF = 0x4000000
+ RTF_IFSCOPE = 0x1000000
+ RTF_LLINFO = 0x400
+ RTF_LOCAL = 0x200000
+ RTF_MODIFIED = 0x20
+ RTF_MULTICAST = 0x800000
+ RTF_NOIFREF = 0x2000
+ RTF_PINNED = 0x100000
+ RTF_PRCLONING = 0x10000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x40000
+ RTF_PROXY = 0x8000000
+ RTF_REJECT = 0x8
+ RTF_ROUTER = 0x10000000
+ RTF_STATIC = 0x800
+ RTF_UP = 0x1
+ RTF_WASCLONED = 0x20000
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DELMADDR = 0x10
+ RTM_GET = 0x4
+ RTM_GET2 = 0x14
+ RTM_IFINFO = 0xe
+ RTM_IFINFO2 = 0x12
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_NEWMADDR = 0xf
+ RTM_NEWMADDR2 = 0x13
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x5
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ SCM_CREDS = 0x3
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x2
+ SCM_TIMESTAMP_MONOTONIC = 0x4
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCAIFADDR = 0x8040691a
+ SIOCARPIPLL = 0xc0206928
+ SIOCATMARK = 0x40047307
+ SIOCAUTOADDR = 0xc0206926
+ SIOCAUTONETMASK = 0x80206927
+ SIOCDELMULTI = 0x80206932
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFPHYADDR = 0x80206941
+ SIOCGDRVSPEC = 0xc01c697b
+ SIOCGETVLAN = 0xc020697f
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFALTMTU = 0xc0206948
+ SIOCGIFASYNCMAP = 0xc020697c
+ SIOCGIFBOND = 0xc0206947
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCAP = 0xc020695b
+ SIOCGIFCONF = 0xc0086924
+ SIOCGIFDEVMTU = 0xc0206944
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFKPI = 0xc0206987
+ SIOCGIFMAC = 0xc0206982
+ SIOCGIFMEDIA = 0xc0286938
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc0206933
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206940
+ SIOCGIFPHYS = 0xc0206935
+ SIOCGIFPSRCADDR = 0xc020693f
+ SIOCGIFSTATUS = 0xc331693d
+ SIOCGIFVLAN = 0xc020697f
+ SIOCGIFWAKEFLAGS = 0xc0206988
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCIFCREATE = 0xc0206978
+ SIOCIFCREATE2 = 0xc020697a
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc00c6981
+ SIOCRSLVMULTI = 0xc008693b
+ SIOCSDRVSPEC = 0x801c697b
+ SIOCSETVLAN = 0x8020697e
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFALTMTU = 0x80206945
+ SIOCSIFASYNCMAP = 0x8020697d
+ SIOCSIFBOND = 0x80206946
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFCAP = 0x8020695a
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFKPI = 0x80206986
+ SIOCSIFLLADDR = 0x8020693c
+ SIOCSIFMAC = 0x80206983
+ SIOCSIFMEDIA = 0xc0206937
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x80206934
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x8040693e
+ SIOCSIFPHYS = 0x80206936
+ SIOCSIFVLAN = 0x8020697e
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SOCK_DGRAM = 0x2
+ SOCK_MAXADDRLEN = 0xff
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_DONTTRUNC = 0x2000
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LABEL = 0x1010
+ SO_LINGER = 0x80
+ SO_LINGER_SEC = 0x1080
+ SO_NETSVC_MARKING_LEVEL = 0x1119
+ SO_NET_SERVICE_TYPE = 0x1116
+ SO_NKE = 0x1021
+ SO_NOADDRERR = 0x1023
+ SO_NOSIGPIPE = 0x1022
+ SO_NOTIFYCONFLICT = 0x1026
+ SO_NP_EXTENSIONS = 0x1083
+ SO_NREAD = 0x1020
+ SO_NUMRCVPKT = 0x1112
+ SO_NWRITE = 0x1024
+ SO_OOBINLINE = 0x100
+ SO_PEERLABEL = 0x1011
+ SO_RANDOMPORT = 0x1082
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_REUSESHAREUID = 0x1025
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_TIMESTAMP = 0x400
+ SO_TIMESTAMP_MONOTONIC = 0x800
+ SO_TYPE = 0x1008
+ SO_UPCALLCLOSEWAIT = 0x1027
+ SO_USELOOPBACK = 0x40
+ SO_WANTMORE = 0x4000
+ SO_WANTOOBFLAG = 0x8000
+ 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_IFWHT = 0xe000
+ 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_ISTXT = 0x200
+ 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 = 0x400
+ TAB2 = 0x800
+ TAB3 = 0x4
+ TABDLY = 0xc04
+ TCIFLUSH = 0x1
+ TCIOFF = 0x3
+ TCIOFLUSH = 0x3
+ TCION = 0x4
+ TCOFLUSH = 0x2
+ TCOOFF = 0x1
+ TCOON = 0x2
+ TCP_CONNECTIONTIMEOUT = 0x20
+ TCP_CONNECTION_INFO = 0x106
+ TCP_ENABLE_ECN = 0x104
+ TCP_FASTOPEN = 0x105
+ TCP_KEEPALIVE = 0x10
+ TCP_KEEPCNT = 0x102
+ TCP_KEEPINTVL = 0x101
+ TCP_MAXHLEN = 0x3c
+ TCP_MAXOLEN = 0x28
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_SACK = 0x4
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MINMSS = 0xd8
+ TCP_MSS = 0x200
+ TCP_NODELAY = 0x1
+ TCP_NOOPT = 0x8
+ TCP_NOPUSH = 0x4
+ TCP_NOTSENT_LOWAT = 0x201
+ TCP_RXT_CONNDROPTIME = 0x80
+ TCP_RXT_FINDROP = 0x100
+ TCP_SENDMOREACKS = 0x103
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDCDTIMESTAMP = 0x40087458
+ TIOCDRAIN = 0x2000745e
+ TIOCDSIMICROCODE = 0x20007455
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLUSH = 0x80047410
+ TIOCGDRAINWAIT = 0x40047456
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGPGRP = 0x40047477
+ TIOCGWINSZ = 0x40087468
+ TIOCIXOFF = 0x20007480
+ TIOCIXON = 0x20007481
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGDTRWAIT = 0x4004745a
+ TIOCMGET = 0x4004746a
+ TIOCMODG = 0x40047403
+ TIOCMODS = 0x80047404
+ TIOCMSDTRWAIT = 0x8004745b
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCPTYGNAME = 0x40807453
+ TIOCPTYGRANT = 0x20007454
+ TIOCPTYUNLK = 0x20007452
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCONS = 0x20007463
+ TIOCSCTTY = 0x20007461
+ TIOCSDRAINWAIT = 0x80047457
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSIG = 0x2000745f
+ TIOCSPGRP = 0x80047476
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x20007465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCTIMESTAMP = 0x40087459
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VM_LOADAVG = 0x2
+ VM_MACHFACTOR = 0x4
+ VM_MAXID = 0x6
+ VM_METER = 0x1
+ VM_SWAPUSAGE = 0x5
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VT0 = 0x0
+ VT1 = 0x10000
+ VTDLY = 0x10000
+ VTIME = 0x11
+ VWERASE = 0x4
+ WCONTINUED = 0x10
+ WCOREFLAG = 0x80
+ WEXITED = 0x4
+ WNOHANG = 0x1
+ WNOWAIT = 0x20
+ WORDSIZE = 0x20
+ WSTOPPED = 0x8
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADARCH = syscall.Errno(0x56)
+ EBADEXEC = syscall.Errno(0x55)
+ EBADF = syscall.Errno(0x9)
+ EBADMACHO = syscall.Errno(0x58)
+ EBADMSG = syscall.Errno(0x5e)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x59)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDEVERR = syscall.Errno(0x53)
+ EDOM = syscall.Errno(0x21)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x5a)
+ EILSEQ = syscall.Errno(0x5c)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x6a)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5f)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x5d)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODATA = syscall.Errno(0x60)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x61)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x5b)
+ ENOPOLICY = syscall.Errno(0x67)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x62)
+ ENOSTR = syscall.Errno(0x63)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTRECOVERABLE = syscall.Errno(0x68)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x2d)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x66)
+ EOVERFLOW = syscall.Errno(0x54)
+ EOWNERDEAD = syscall.Errno(0x69)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x64)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ EPWROFF = syscall.Errno(0x52)
+ EQFULL = syscall.Errno(0x6a)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHLIBVERS = syscall.Errno(0x57)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIME = syscall.Errno(0x65)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "resource busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "operation timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "device power is off",
+ 83: "device error",
+ 84: "value too large to be stored in data type",
+ 85: "bad executable (or shared library)",
+ 86: "bad CPU type in executable",
+ 87: "shared library version mismatch",
+ 88: "malformed Mach-o file",
+ 89: "operation canceled",
+ 90: "identifier removed",
+ 91: "no message of desired type",
+ 92: "illegal byte sequence",
+ 93: "attribute not found",
+ 94: "bad message",
+ 95: "EMULTIHOP (Reserved)",
+ 96: "no message available on STREAM",
+ 97: "ENOLINK (Reserved)",
+ 98: "no STREAM resources",
+ 99: "not a STREAM",
+ 100: "protocol error",
+ 101: "STREAM ioctl timeout",
+ 102: "operation not supported on socket",
+ 103: "policy not found",
+ 104: "state not recoverable",
+ 105: "previous owner died",
+ 106: "interface output queue is full",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "suspended (signal)",
+ 18: "suspended",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go
new file mode 100644
index 0000000..48f63d4
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go
@@ -0,0 +1,1673 @@
+// mkerrors.sh -m64
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,darwin
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m64 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1c
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x25
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x1e
+ AF_IPX = 0x17
+ AF_ISDN = 0x1c
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x28
+ AF_NATM = 0x1f
+ AF_NDRV = 0x1b
+ AF_NETBIOS = 0x21
+ AF_NS = 0x6
+ AF_OSI = 0x7
+ AF_PPP = 0x22
+ AF_PUP = 0x4
+ AF_RESERVED_36 = 0x24
+ AF_ROUTE = 0x11
+ AF_SIP = 0x18
+ AF_SNA = 0xb
+ AF_SYSTEM = 0x20
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ AF_UTUN = 0x26
+ ALTWERASE = 0x200
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B9600 = 0x2580
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc00c4279
+ BIOCGETIF = 0x4020426b
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044272
+ BIOCGRTIMEOUT = 0x4010426e
+ BIOCGSEESENT = 0x40044276
+ BIOCGSTATS = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDLT = 0x80044278
+ BIOCSETF = 0x80104267
+ BIOCSETFNR = 0x8010427e
+ BIOCSETIF = 0x8020426c
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044273
+ BIOCSRTIMEOUT = 0x8010426d
+ BIOCSSEESENT = 0x80044277
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ 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_MAXBUFSIZE = 0x80000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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 = 0x8000
+ BSDLY = 0x8000
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CLOCK_MONOTONIC = 0x6
+ CLOCK_MONOTONIC_RAW = 0x4
+ CLOCK_MONOTONIC_RAW_APPROX = 0x5
+ CLOCK_PROCESS_CPUTIME_ID = 0xc
+ CLOCK_REALTIME = 0x0
+ CLOCK_THREAD_CPUTIME_ID = 0x10
+ CLOCK_UPTIME_RAW = 0x8
+ CLOCK_UPTIME_RAW_APPROX = 0x9
+ CR0 = 0x0
+ CR1 = 0x1000
+ CR2 = 0x2000
+ CR3 = 0x3000
+ CRDLY = 0x3000
+ CREAD = 0x800
+ CRTSCTS = 0x30000
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_AOS = 0xde
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_CAN20B = 0xbe
+ DLT_CAN_SOCKETCAN = 0xe3
+ DLT_CHAOS = 0x5
+ DLT_CHDLC = 0x68
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DBUS = 0xe7
+ DLT_DECT = 0xdd
+ DLT_DOCSIS = 0x8f
+ DLT_DVB_CI = 0xeb
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FC_2 = 0xe0
+ DLT_FC_2_WITH_FRAME_DELIMS = 0xe1
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_GSMTAP_ABIS = 0xda
+ DLT_GSMTAP_UM = 0xd9
+ DLT_HHDLC = 0x79
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NOFCS = 0xe6
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_IPFILTER = 0x74
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IPNET = 0xe2
+ DLT_IPOIB = 0xf2
+ DLT_IPV4 = 0xe4
+ DLT_IPV6 = 0xe5
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_ATM_CEMIC = 0xee
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FIBRECHANNEL = 0xea
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_SRX_E2E = 0xe9
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_JUNIPER_VS = 0xe8
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_EVDEV = 0xd8
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_PPP_WITHDIRECTION = 0xa6
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MATCHING_MAX = 0xf5
+ DLT_MATCHING_MIN = 0x68
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MPEG_2_TS = 0xf3
+ DLT_MPLS = 0xdb
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_MUX27010 = 0xec
+ DLT_NETANALYZER = 0xf0
+ DLT_NETANALYZER_TRANSPARENT = 0xf1
+ DLT_NFC_LLCP = 0xf5
+ DLT_NFLOG = 0xef
+ DLT_NG40 = 0xf4
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0x10
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PPP_WITH_DIRECTION = 0xa6
+ DLT_PRISM_HEADER = 0x77
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_RIO = 0x7c
+ DLT_SCCP = 0x8e
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xf
+ DLT_STANAG_5066_D_PDU = 0xed
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USB_LINUX = 0xbd
+ DLT_USB_LINUX_MMAPPED = 0xdc
+ DLT_USER0 = 0x93
+ DLT_USER1 = 0x94
+ DLT_USER10 = 0x9d
+ DLT_USER11 = 0x9e
+ DLT_USER12 = 0x9f
+ DLT_USER13 = 0xa0
+ DLT_USER14 = 0xa1
+ DLT_USER15 = 0xa2
+ DLT_USER2 = 0x95
+ DLT_USER3 = 0x96
+ DLT_USER4 = 0x97
+ DLT_USER5 = 0x98
+ DLT_USER6 = 0x99
+ DLT_USER7 = 0x9a
+ DLT_USER8 = 0x9b
+ DLT_USER9 = 0x9c
+ DLT_WIHART = 0xdf
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EVFILT_AIO = -0x3
+ EVFILT_EXCEPT = -0xf
+ EVFILT_FS = -0x9
+ EVFILT_MACHPORT = -0x8
+ EVFILT_PROC = -0x5
+ EVFILT_READ = -0x1
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0xf
+ EVFILT_THREADMARKER = 0xf
+ EVFILT_TIMER = -0x7
+ EVFILT_USER = -0xa
+ EVFILT_VM = -0xc
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_DISPATCH = 0x80
+ EV_DISPATCH2 = 0x180
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG0 = 0x1000
+ EV_FLAG1 = 0x2000
+ EV_ONESHOT = 0x10
+ EV_OOBAND = 0x2000
+ EV_POLL = 0x1000
+ EV_RECEIPT = 0x40
+ EV_SYSFLAGS = 0xf000
+ EV_UDATA_SPECIFIC = 0x100
+ EV_VANISHED = 0x200
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x4000
+ FFDLY = 0x4000
+ FLUSHO = 0x800000
+ F_ADDFILESIGS = 0x3d
+ F_ADDFILESIGS_FOR_DYLD_SIM = 0x53
+ F_ADDFILESIGS_RETURN = 0x61
+ F_ADDSIGS = 0x3b
+ F_ALLOCATEALL = 0x4
+ F_ALLOCATECONTIG = 0x2
+ F_BARRIERFSYNC = 0x55
+ F_CHECK_LV = 0x62
+ F_CHKCLEAN = 0x29
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x43
+ F_FINDSIGS = 0x4e
+ F_FLUSH_DATA = 0x28
+ F_FREEZE_FS = 0x35
+ F_FULLFSYNC = 0x33
+ F_GETCODEDIR = 0x48
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETLKPID = 0x42
+ F_GETNOSIGPIPE = 0x4a
+ F_GETOWN = 0x5
+ F_GETPATH = 0x32
+ F_GETPATH_MTMINFO = 0x47
+ F_GETPROTECTIONCLASS = 0x3f
+ F_GETPROTECTIONLEVEL = 0x4d
+ F_GLOBAL_NOCACHE = 0x37
+ F_LOG2PHYS = 0x31
+ F_LOG2PHYS_EXT = 0x41
+ F_NOCACHE = 0x30
+ F_NODIRECT = 0x3e
+ F_OK = 0x0
+ F_PATHPKG_CHECK = 0x34
+ F_PEOFPOSMODE = 0x3
+ F_PREALLOCATE = 0x2a
+ F_RDADVISE = 0x2c
+ F_RDAHEAD = 0x2d
+ F_RDLCK = 0x1
+ F_SETBACKINGSTORE = 0x46
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETLKWTIMEOUT = 0xa
+ F_SETNOSIGPIPE = 0x49
+ F_SETOWN = 0x6
+ F_SETPROTECTIONCLASS = 0x40
+ F_SETSIZE = 0x2b
+ F_SINGLE_WRITER = 0x4c
+ F_THAW_FS = 0x36
+ F_TRANSCODEKEY = 0x4b
+ F_UNLCK = 0x2
+ F_VOLPOSMODE = 0x4
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFF_ALLMULTI = 0x200
+ IFF_ALTPHYS = 0x4000
+ IFF_BROADCAST = 0x2
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NOTRAILERS = 0x20
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_AAL5 = 0x31
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ATM = 0x25
+ IFT_BRIDGE = 0xd1
+ IFT_CARP = 0xf8
+ IFT_CELLULAR = 0xff
+ IFT_CEPT = 0x13
+ IFT_DS3 = 0x1e
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0x38
+ IFT_FDDI = 0xf
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_GIF = 0x37
+ IFT_HDH1822 = 0x3
+ IFT_HIPPI = 0x2f
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE8023ADLAG = 0x88
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88026 = 0xa
+ IFT_L2VLAN = 0x87
+ IFT_LAPB = 0x10
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_NSIP = 0x1b
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PDP = 0xff
+ IFT_PFLOG = 0xf5
+ IFT_PFSYNC = 0xf6
+ IFT_PKTAP = 0xfe
+ IFT_PPP = 0x17
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PTPSERIAL = 0x16
+ IFT_RS232 = 0x21
+ IFT_SDLC = 0x11
+ IFT_SIP = 0x1f
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_STARLAN = 0xb
+ IFT_STF = 0x39
+ IFT_T1 = 0x12
+ IFT_ULTRA = 0x1d
+ IFT_V35 = 0x2d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LINKLOCALNETNUM = 0xa9fe0000
+ IN_LOOPBACKNET = 0x7f
+ IPPROTO_3PC = 0x22
+ IPPROTO_ADFS = 0x44
+ IPPROTO_AH = 0x33
+ IPPROTO_AHIP = 0x3d
+ IPPROTO_APES = 0x63
+ IPPROTO_ARGUS = 0xd
+ IPPROTO_AX25 = 0x5d
+ IPPROTO_BHA = 0x31
+ IPPROTO_BLT = 0x1e
+ IPPROTO_BRSATMON = 0x4c
+ IPPROTO_CFTP = 0x3e
+ IPPROTO_CHAOS = 0x10
+ IPPROTO_CMTP = 0x26
+ IPPROTO_CPHB = 0x49
+ IPPROTO_CPNX = 0x48
+ IPPROTO_DDP = 0x25
+ IPPROTO_DGP = 0x56
+ IPPROTO_DIVERT = 0xfe
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_EMCON = 0xe
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GMTP = 0x64
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HELLO = 0x3f
+ IPPROTO_HMP = 0x14
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IDPR = 0x23
+ IPPROTO_IDRP = 0x2d
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IGP = 0x55
+ IPPROTO_IGRP = 0x58
+ IPPROTO_IL = 0x28
+ IPPROTO_INLSP = 0x34
+ IPPROTO_INP = 0x20
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPCV = 0x47
+ IPPROTO_IPEIP = 0x5e
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPPC = 0x43
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IRTP = 0x1c
+ IPPROTO_KRYPTOLAN = 0x41
+ IPPROTO_LARP = 0x5b
+ IPPROTO_LEAF1 = 0x19
+ IPPROTO_LEAF2 = 0x1a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x34
+ IPPROTO_MEAS = 0x13
+ IPPROTO_MHRP = 0x30
+ IPPROTO_MICP = 0x5f
+ IPPROTO_MTP = 0x5c
+ IPPROTO_MUX = 0x12
+ IPPROTO_ND = 0x4d
+ IPPROTO_NHRP = 0x36
+ IPPROTO_NONE = 0x3b
+ IPPROTO_NSP = 0x1f
+ IPPROTO_NVPII = 0xb
+ IPPROTO_OSPFIGP = 0x59
+ IPPROTO_PGM = 0x71
+ IPPROTO_PIGP = 0x9
+ IPPROTO_PIM = 0x67
+ IPPROTO_PRM = 0x15
+ IPPROTO_PUP = 0xc
+ IPPROTO_PVP = 0x4b
+ IPPROTO_RAW = 0xff
+ IPPROTO_RCCMON = 0xa
+ IPPROTO_RDP = 0x1b
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_RVD = 0x42
+ IPPROTO_SATEXPAK = 0x40
+ IPPROTO_SATMON = 0x45
+ IPPROTO_SCCSP = 0x60
+ IPPROTO_SCTP = 0x84
+ IPPROTO_SDRP = 0x2a
+ IPPROTO_SEP = 0x21
+ IPPROTO_SRPC = 0x5a
+ IPPROTO_ST = 0x7
+ IPPROTO_SVMTP = 0x52
+ IPPROTO_SWIPE = 0x35
+ IPPROTO_TCF = 0x57
+ IPPROTO_TCP = 0x6
+ IPPROTO_TP = 0x1d
+ IPPROTO_TPXX = 0x27
+ IPPROTO_TRUNK1 = 0x17
+ IPPROTO_TRUNK2 = 0x18
+ IPPROTO_TTP = 0x54
+ IPPROTO_UDP = 0x11
+ IPPROTO_VINES = 0x53
+ IPPROTO_VISA = 0x46
+ IPPROTO_VMTP = 0x51
+ IPPROTO_WBEXPAK = 0x4f
+ IPPROTO_WBMON = 0x4e
+ IPPROTO_WSN = 0x4a
+ IPPROTO_XNET = 0xf
+ IPPROTO_XTP = 0x24
+ IPV6_2292DSTOPTS = 0x17
+ IPV6_2292HOPLIMIT = 0x14
+ IPV6_2292HOPOPTS = 0x16
+ IPV6_2292NEXTHOP = 0x15
+ IPV6_2292PKTINFO = 0x13
+ IPV6_2292PKTOPTIONS = 0x19
+ IPV6_2292RTHDR = 0x18
+ IPV6_BINDV6ONLY = 0x1b
+ IPV6_BOUND_IF = 0x7d
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x3c
+ IPV6_FW_ADD = 0x1e
+ IPV6_FW_DEL = 0x1f
+ IPV6_FW_FLUSH = 0x20
+ IPV6_FW_GET = 0x22
+ IPV6_FW_ZERO = 0x21
+ IPV6_HLIMDEC = 0x1
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXOPTHDR = 0x800
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MAX_GROUP_SRC_FILTER = 0x200
+ IPV6_MAX_MEMBERSHIPS = 0xfff
+ IPV6_MAX_SOCK_SRC_FILTER = 0x80
+ IPV6_MIN_MEMBERSHIPS = 0x1f
+ IPV6_MMTU = 0x500
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_RECVTCLASS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x24
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_ADD_SOURCE_MEMBERSHIP = 0x46
+ IP_BLOCK_SOURCE = 0x48
+ IP_BOUND_IF = 0x19
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_DROP_SOURCE_MEMBERSHIP = 0x47
+ IP_DUMMYNET_CONFIGURE = 0x3c
+ IP_DUMMYNET_DEL = 0x3d
+ IP_DUMMYNET_FLUSH = 0x3e
+ IP_DUMMYNET_GET = 0x40
+ IP_FAITH = 0x16
+ IP_FW_ADD = 0x28
+ IP_FW_DEL = 0x29
+ IP_FW_FLUSH = 0x2a
+ IP_FW_GET = 0x2c
+ IP_FW_RESETLOG = 0x2d
+ IP_FW_ZERO = 0x2b
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x15
+ IP_MAXPACKET = 0xffff
+ IP_MAX_GROUP_SRC_FILTER = 0x200
+ IP_MAX_MEMBERSHIPS = 0xfff
+ IP_MAX_SOCK_MUTE_FILTER = 0x80
+ IP_MAX_SOCK_SRC_FILTER = 0x80
+ IP_MF = 0x2000
+ IP_MIN_MEMBERSHIPS = 0x1f
+ IP_MSFILTER = 0x4a
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_IFINDEX = 0x42
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_MULTICAST_VIF = 0xe
+ IP_NAT__XXX = 0x37
+ IP_OFFMASK = 0x1fff
+ IP_OLD_FW_ADD = 0x32
+ IP_OLD_FW_DEL = 0x33
+ IP_OLD_FW_FLUSH = 0x34
+ IP_OLD_FW_GET = 0x36
+ IP_OLD_FW_RESETLOG = 0x38
+ IP_OLD_FW_ZERO = 0x35
+ IP_OPTIONS = 0x1
+ IP_PKTINFO = 0x1a
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVPKTINFO = 0x1a
+ IP_RECVRETOPTS = 0x6
+ IP_RECVTTL = 0x18
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RSVP_OFF = 0x10
+ IP_RSVP_ON = 0xf
+ IP_RSVP_VIF_OFF = 0x12
+ IP_RSVP_VIF_ON = 0x11
+ IP_STRIPHDR = 0x17
+ IP_TOS = 0x3
+ IP_TRAFFIC_MGT_BACKGROUND = 0x41
+ IP_TTL = 0x4
+ IP_UNBLOCK_SOURCE = 0x49
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IUTF8 = 0x4000
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_CAN_REUSE = 0x9
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x5
+ MADV_FREE_REUSABLE = 0x7
+ MADV_FREE_REUSE = 0x8
+ MADV_NORMAL = 0x0
+ MADV_PAGEOUT = 0xa
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_WILLNEED = 0x3
+ MADV_ZERO_WIRED_PAGES = 0x6
+ MAP_ANON = 0x1000
+ MAP_ANONYMOUS = 0x1000
+ MAP_COPY = 0x2
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_HASSEMAPHORE = 0x200
+ MAP_JIT = 0x800
+ MAP_NOCACHE = 0x400
+ MAP_NOEXTEND = 0x100
+ MAP_NORESERVE = 0x40
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_RESERVED0080 = 0x80
+ MAP_RESILIENT_CODESIGN = 0x2000
+ MAP_RESILIENT_MEDIA = 0x4000
+ MAP_SHARED = 0x1
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MNT_ASYNC = 0x40
+ MNT_AUTOMOUNTED = 0x400000
+ MNT_CMDFLAGS = 0xf0000
+ MNT_CPROTECT = 0x80
+ MNT_DEFWRITE = 0x2000000
+ MNT_DONTBROWSE = 0x100000
+ MNT_DOVOLFS = 0x8000
+ MNT_DWAIT = 0x4
+ MNT_EXPORTED = 0x100
+ MNT_FORCE = 0x80000
+ MNT_IGNORE_OWNERSHIP = 0x200000
+ MNT_JOURNALED = 0x800000
+ MNT_LOCAL = 0x1000
+ MNT_MULTILABEL = 0x4000000
+ MNT_NOATIME = 0x10000000
+ MNT_NOBLOCK = 0x20000
+ MNT_NODEV = 0x10
+ MNT_NOEXEC = 0x4
+ MNT_NOSUID = 0x8
+ MNT_NOUSERXATTR = 0x1000000
+ MNT_NOWAIT = 0x2
+ MNT_QUARANTINE = 0x400
+ MNT_QUOTA = 0x2000
+ MNT_RDONLY = 0x1
+ MNT_RELOAD = 0x40000
+ MNT_ROOTFS = 0x4000
+ MNT_SYNCHRONOUS = 0x2
+ MNT_UNION = 0x20
+ MNT_UNKNOWNPERMISSIONS = 0x200000
+ MNT_UPDATE = 0x10000
+ MNT_VISFLAGMASK = 0x17f0f5ff
+ MNT_WAIT = 0x1
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOF = 0x100
+ MSG_EOR = 0x8
+ MSG_FLUSH = 0x400
+ MSG_HAVEMORE = 0x2000
+ MSG_HOLD = 0x800
+ MSG_NEEDSA = 0x10000
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_RCVMORE = 0x4000
+ MSG_SEND = 0x1000
+ MSG_TRUNC = 0x10
+ MSG_WAITALL = 0x40
+ MSG_WAITSTREAM = 0x200
+ MS_ASYNC = 0x1
+ MS_DEACTIVATE = 0x8
+ MS_INVALIDATE = 0x2
+ MS_KILLPAGES = 0x4
+ MS_SYNC = 0x10
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_DUMP2 = 0x7
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_IFLIST2 = 0x6
+ NET_RT_MAXID = 0xa
+ NET_RT_STAT = 0x4
+ NET_RT_TRASH = 0x5
+ NL0 = 0x0
+ NL1 = 0x100
+ NL2 = 0x200
+ NL3 = 0x300
+ NLDLY = 0x300
+ NOFLSH = 0x80000000
+ NOKERNINFO = 0x2000000
+ NOTE_ABSOLUTE = 0x8
+ NOTE_ATTRIB = 0x8
+ NOTE_BACKGROUND = 0x40
+ NOTE_CHILD = 0x4
+ NOTE_CRITICAL = 0x20
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXITSTATUS = 0x4000000
+ NOTE_EXIT_CSERROR = 0x40000
+ NOTE_EXIT_DECRYPTFAIL = 0x10000
+ NOTE_EXIT_DETAIL = 0x2000000
+ NOTE_EXIT_DETAIL_MASK = 0x70000
+ NOTE_EXIT_MEMORY = 0x20000
+ NOTE_EXIT_REPARENTED = 0x80000
+ NOTE_EXTEND = 0x4
+ NOTE_FFAND = 0x40000000
+ NOTE_FFCOPY = 0xc0000000
+ NOTE_FFCTRLMASK = 0xc0000000
+ NOTE_FFLAGSMASK = 0xffffff
+ NOTE_FFNOP = 0x0
+ NOTE_FFOR = 0x80000000
+ NOTE_FORK = 0x40000000
+ NOTE_FUNLOCK = 0x100
+ NOTE_LEEWAY = 0x10
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_MACH_CONTINUOUS_TIME = 0x80
+ NOTE_NONE = 0x80
+ NOTE_NSECONDS = 0x4
+ NOTE_OOB = 0x2
+ NOTE_PCTRLMASK = -0x100000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_REAP = 0x10000000
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_SECONDS = 0x1
+ NOTE_SIGNAL = 0x8000000
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRIGGER = 0x1000000
+ NOTE_USECONDS = 0x2
+ NOTE_VM_ERROR = 0x10000000
+ NOTE_VM_PRESSURE = 0x80000000
+ NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000
+ NOTE_VM_PRESSURE_TERMINATE = 0x40000000
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ OFDEL = 0x20000
+ OFILL = 0x80
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ OXTABS = 0x4
+ O_ACCMODE = 0x3
+ O_ALERT = 0x20000000
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x1000000
+ O_CREAT = 0x200
+ O_DIRECTORY = 0x100000
+ O_DP_GETRAWENCRYPTED = 0x1
+ O_DP_GETRAWUNENCRYPTED = 0x2
+ O_DSYNC = 0x400000
+ O_EVTONLY = 0x8000
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x20000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_POPUP = 0x80000000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_SHLOCK = 0x10
+ O_SYMLINK = 0x200000
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ PT_ATTACH = 0xa
+ PT_ATTACHEXC = 0xe
+ PT_CONTINUE = 0x7
+ PT_DENY_ATTACH = 0x1f
+ PT_DETACH = 0xb
+ PT_FIRSTMACH = 0x20
+ PT_FORCEQUOTA = 0x1e
+ PT_KILL = 0x8
+ PT_READ_D = 0x2
+ PT_READ_I = 0x1
+ PT_READ_U = 0x3
+ PT_SIGEXC = 0xc
+ PT_STEP = 0x9
+ PT_THUPDATE = 0xd
+ PT_TRACE_ME = 0x0
+ PT_WRITE_D = 0x5
+ PT_WRITE_I = 0x4
+ PT_WRITE_U = 0x6
+ RLIMIT_AS = 0x5
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_CPU_USAGE_MONITOR = 0x2
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_MEMLOCK = 0x6
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_NPROC = 0x7
+ RLIMIT_RSS = 0x5
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x8
+ RTAX_NETMASK = 0x2
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTF_BLACKHOLE = 0x1000
+ RTF_BROADCAST = 0x400000
+ RTF_CLONING = 0x100
+ RTF_CONDEMNED = 0x2000000
+ RTF_DELCLONE = 0x80
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_IFREF = 0x4000000
+ RTF_IFSCOPE = 0x1000000
+ RTF_LLINFO = 0x400
+ RTF_LOCAL = 0x200000
+ RTF_MODIFIED = 0x20
+ RTF_MULTICAST = 0x800000
+ RTF_NOIFREF = 0x2000
+ RTF_PINNED = 0x100000
+ RTF_PRCLONING = 0x10000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x40000
+ RTF_PROXY = 0x8000000
+ RTF_REJECT = 0x8
+ RTF_ROUTER = 0x10000000
+ RTF_STATIC = 0x800
+ RTF_UP = 0x1
+ RTF_WASCLONED = 0x20000
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DELMADDR = 0x10
+ RTM_GET = 0x4
+ RTM_GET2 = 0x14
+ RTM_IFINFO = 0xe
+ RTM_IFINFO2 = 0x12
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_NEWMADDR = 0xf
+ RTM_NEWMADDR2 = 0x13
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x5
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ SCM_CREDS = 0x3
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x2
+ SCM_TIMESTAMP_MONOTONIC = 0x4
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCAIFADDR = 0x8040691a
+ SIOCARPIPLL = 0xc0206928
+ SIOCATMARK = 0x40047307
+ SIOCAUTOADDR = 0xc0206926
+ SIOCAUTONETMASK = 0x80206927
+ SIOCDELMULTI = 0x80206932
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFPHYADDR = 0x80206941
+ SIOCGDRVSPEC = 0xc028697b
+ SIOCGETVLAN = 0xc020697f
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFALTMTU = 0xc0206948
+ SIOCGIFASYNCMAP = 0xc020697c
+ SIOCGIFBOND = 0xc0206947
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCAP = 0xc020695b
+ SIOCGIFCONF = 0xc00c6924
+ SIOCGIFDEVMTU = 0xc0206944
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFKPI = 0xc0206987
+ SIOCGIFMAC = 0xc0206982
+ SIOCGIFMEDIA = 0xc02c6938
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc0206933
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206940
+ SIOCGIFPHYS = 0xc0206935
+ SIOCGIFPSRCADDR = 0xc020693f
+ SIOCGIFSTATUS = 0xc331693d
+ SIOCGIFVLAN = 0xc020697f
+ SIOCGIFWAKEFLAGS = 0xc0206988
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCIFCREATE = 0xc0206978
+ SIOCIFCREATE2 = 0xc020697a
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc0106981
+ SIOCRSLVMULTI = 0xc010693b
+ SIOCSDRVSPEC = 0x8028697b
+ SIOCSETVLAN = 0x8020697e
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFALTMTU = 0x80206945
+ SIOCSIFASYNCMAP = 0x8020697d
+ SIOCSIFBOND = 0x80206946
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFCAP = 0x8020695a
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFKPI = 0x80206986
+ SIOCSIFLLADDR = 0x8020693c
+ SIOCSIFMAC = 0x80206983
+ SIOCSIFMEDIA = 0xc0206937
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x80206934
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x8040693e
+ SIOCSIFPHYS = 0x80206936
+ SIOCSIFVLAN = 0x8020697e
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SOCK_DGRAM = 0x2
+ SOCK_MAXADDRLEN = 0xff
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_DONTTRUNC = 0x2000
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LABEL = 0x1010
+ SO_LINGER = 0x80
+ SO_LINGER_SEC = 0x1080
+ SO_NETSVC_MARKING_LEVEL = 0x1119
+ SO_NET_SERVICE_TYPE = 0x1116
+ SO_NKE = 0x1021
+ SO_NOADDRERR = 0x1023
+ SO_NOSIGPIPE = 0x1022
+ SO_NOTIFYCONFLICT = 0x1026
+ SO_NP_EXTENSIONS = 0x1083
+ SO_NREAD = 0x1020
+ SO_NUMRCVPKT = 0x1112
+ SO_NWRITE = 0x1024
+ SO_OOBINLINE = 0x100
+ SO_PEERLABEL = 0x1011
+ SO_RANDOMPORT = 0x1082
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_REUSESHAREUID = 0x1025
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_TIMESTAMP = 0x400
+ SO_TIMESTAMP_MONOTONIC = 0x800
+ SO_TYPE = 0x1008
+ SO_UPCALLCLOSEWAIT = 0x1027
+ SO_USELOOPBACK = 0x40
+ SO_WANTMORE = 0x4000
+ SO_WANTOOBFLAG = 0x8000
+ 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_IFWHT = 0xe000
+ 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_ISTXT = 0x200
+ 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 = 0x400
+ TAB2 = 0x800
+ TAB3 = 0x4
+ TABDLY = 0xc04
+ TCIFLUSH = 0x1
+ TCIOFF = 0x3
+ TCIOFLUSH = 0x3
+ TCION = 0x4
+ TCOFLUSH = 0x2
+ TCOOFF = 0x1
+ TCOON = 0x2
+ TCP_CONNECTIONTIMEOUT = 0x20
+ TCP_CONNECTION_INFO = 0x106
+ TCP_ENABLE_ECN = 0x104
+ TCP_FASTOPEN = 0x105
+ TCP_KEEPALIVE = 0x10
+ TCP_KEEPCNT = 0x102
+ TCP_KEEPINTVL = 0x101
+ TCP_MAXHLEN = 0x3c
+ TCP_MAXOLEN = 0x28
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_SACK = 0x4
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MINMSS = 0xd8
+ TCP_MSS = 0x200
+ TCP_NODELAY = 0x1
+ TCP_NOOPT = 0x8
+ TCP_NOPUSH = 0x4
+ TCP_NOTSENT_LOWAT = 0x201
+ TCP_RXT_CONNDROPTIME = 0x80
+ TCP_RXT_FINDROP = 0x100
+ TCP_SENDMOREACKS = 0x103
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDCDTIMESTAMP = 0x40107458
+ TIOCDRAIN = 0x2000745e
+ TIOCDSIMICROCODE = 0x20007455
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLUSH = 0x80047410
+ TIOCGDRAINWAIT = 0x40047456
+ TIOCGETA = 0x40487413
+ TIOCGETD = 0x4004741a
+ TIOCGPGRP = 0x40047477
+ TIOCGWINSZ = 0x40087468
+ TIOCIXOFF = 0x20007480
+ TIOCIXON = 0x20007481
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGDTRWAIT = 0x4004745a
+ TIOCMGET = 0x4004746a
+ TIOCMODG = 0x40047403
+ TIOCMODS = 0x80047404
+ TIOCMSDTRWAIT = 0x8004745b
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCPTYGNAME = 0x40807453
+ TIOCPTYGRANT = 0x20007454
+ TIOCPTYUNLK = 0x20007452
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCONS = 0x20007463
+ TIOCSCTTY = 0x20007461
+ TIOCSDRAINWAIT = 0x80047457
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x80487414
+ TIOCSETAF = 0x80487416
+ TIOCSETAW = 0x80487415
+ TIOCSETD = 0x8004741b
+ TIOCSIG = 0x2000745f
+ TIOCSPGRP = 0x80047476
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x20007465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCTIMESTAMP = 0x40107459
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VM_LOADAVG = 0x2
+ VM_MACHFACTOR = 0x4
+ VM_MAXID = 0x6
+ VM_METER = 0x1
+ VM_SWAPUSAGE = 0x5
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VT0 = 0x0
+ VT1 = 0x10000
+ VTDLY = 0x10000
+ VTIME = 0x11
+ VWERASE = 0x4
+ WCONTINUED = 0x10
+ WCOREFLAG = 0x80
+ WEXITED = 0x4
+ WNOHANG = 0x1
+ WNOWAIT = 0x20
+ WORDSIZE = 0x40
+ WSTOPPED = 0x8
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADARCH = syscall.Errno(0x56)
+ EBADEXEC = syscall.Errno(0x55)
+ EBADF = syscall.Errno(0x9)
+ EBADMACHO = syscall.Errno(0x58)
+ EBADMSG = syscall.Errno(0x5e)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x59)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDEVERR = syscall.Errno(0x53)
+ EDOM = syscall.Errno(0x21)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x5a)
+ EILSEQ = syscall.Errno(0x5c)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x6a)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5f)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x5d)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODATA = syscall.Errno(0x60)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x61)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x5b)
+ ENOPOLICY = syscall.Errno(0x67)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x62)
+ ENOSTR = syscall.Errno(0x63)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTRECOVERABLE = syscall.Errno(0x68)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x2d)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x66)
+ EOVERFLOW = syscall.Errno(0x54)
+ EOWNERDEAD = syscall.Errno(0x69)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x64)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ EPWROFF = syscall.Errno(0x52)
+ EQFULL = syscall.Errno(0x6a)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHLIBVERS = syscall.Errno(0x57)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIME = syscall.Errno(0x65)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "resource busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "operation timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "device power is off",
+ 83: "device error",
+ 84: "value too large to be stored in data type",
+ 85: "bad executable (or shared library)",
+ 86: "bad CPU type in executable",
+ 87: "shared library version mismatch",
+ 88: "malformed Mach-o file",
+ 89: "operation canceled",
+ 90: "identifier removed",
+ 91: "no message of desired type",
+ 92: "illegal byte sequence",
+ 93: "attribute not found",
+ 94: "bad message",
+ 95: "EMULTIHOP (Reserved)",
+ 96: "no message available on STREAM",
+ 97: "ENOLINK (Reserved)",
+ 98: "no STREAM resources",
+ 99: "not a STREAM",
+ 100: "protocol error",
+ 101: "STREAM ioctl timeout",
+ 102: "operation not supported on socket",
+ 103: "policy not found",
+ 104: "state not recoverable",
+ 105: "previous owner died",
+ 106: "interface output queue is full",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "suspended (signal)",
+ 18: "suspended",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go
new file mode 100644
index 0000000..24cb522
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go
@@ -0,0 +1,1673 @@
+// mkerrors.sh
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm,darwin
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1c
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x25
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x1e
+ AF_IPX = 0x17
+ AF_ISDN = 0x1c
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x28
+ AF_NATM = 0x1f
+ AF_NDRV = 0x1b
+ AF_NETBIOS = 0x21
+ AF_NS = 0x6
+ AF_OSI = 0x7
+ AF_PPP = 0x22
+ AF_PUP = 0x4
+ AF_RESERVED_36 = 0x24
+ AF_ROUTE = 0x11
+ AF_SIP = 0x18
+ AF_SNA = 0xb
+ AF_SYSTEM = 0x20
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ AF_UTUN = 0x26
+ ALTWERASE = 0x200
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B9600 = 0x2580
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc00c4279
+ BIOCGETIF = 0x4020426b
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044272
+ BIOCGRTIMEOUT = 0x4010426e
+ BIOCGSEESENT = 0x40044276
+ BIOCGSTATS = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDLT = 0x80044278
+ BIOCSETF = 0x80104267
+ BIOCSETFNR = 0x8010427e
+ BIOCSETIF = 0x8020426c
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044273
+ BIOCSRTIMEOUT = 0x8010426d
+ BIOCSSEESENT = 0x80044277
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ 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_MAXBUFSIZE = 0x80000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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 = 0x8000
+ BSDLY = 0x8000
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CLOCK_MONOTONIC = 0x6
+ CLOCK_MONOTONIC_RAW = 0x4
+ CLOCK_MONOTONIC_RAW_APPROX = 0x5
+ CLOCK_PROCESS_CPUTIME_ID = 0xc
+ CLOCK_REALTIME = 0x0
+ CLOCK_THREAD_CPUTIME_ID = 0x10
+ CLOCK_UPTIME_RAW = 0x8
+ CLOCK_UPTIME_RAW_APPROX = 0x9
+ CR0 = 0x0
+ CR1 = 0x1000
+ CR2 = 0x2000
+ CR3 = 0x3000
+ CRDLY = 0x3000
+ CREAD = 0x800
+ CRTSCTS = 0x30000
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_AOS = 0xde
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_CAN20B = 0xbe
+ DLT_CAN_SOCKETCAN = 0xe3
+ DLT_CHAOS = 0x5
+ DLT_CHDLC = 0x68
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DBUS = 0xe7
+ DLT_DECT = 0xdd
+ DLT_DOCSIS = 0x8f
+ DLT_DVB_CI = 0xeb
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FC_2 = 0xe0
+ DLT_FC_2_WITH_FRAME_DELIMS = 0xe1
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_GSMTAP_ABIS = 0xda
+ DLT_GSMTAP_UM = 0xd9
+ DLT_HHDLC = 0x79
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NOFCS = 0xe6
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_IPFILTER = 0x74
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IPNET = 0xe2
+ DLT_IPOIB = 0xf2
+ DLT_IPV4 = 0xe4
+ DLT_IPV6 = 0xe5
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_ATM_CEMIC = 0xee
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FIBRECHANNEL = 0xea
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_SRX_E2E = 0xe9
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_JUNIPER_VS = 0xe8
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_EVDEV = 0xd8
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_PPP_WITHDIRECTION = 0xa6
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MATCHING_MAX = 0xf5
+ DLT_MATCHING_MIN = 0x68
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MPEG_2_TS = 0xf3
+ DLT_MPLS = 0xdb
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_MUX27010 = 0xec
+ DLT_NETANALYZER = 0xf0
+ DLT_NETANALYZER_TRANSPARENT = 0xf1
+ DLT_NFC_LLCP = 0xf5
+ DLT_NFLOG = 0xef
+ DLT_NG40 = 0xf4
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0x10
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PPP_WITH_DIRECTION = 0xa6
+ DLT_PRISM_HEADER = 0x77
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_RIO = 0x7c
+ DLT_SCCP = 0x8e
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xf
+ DLT_STANAG_5066_D_PDU = 0xed
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USB_LINUX = 0xbd
+ DLT_USB_LINUX_MMAPPED = 0xdc
+ DLT_USER0 = 0x93
+ DLT_USER1 = 0x94
+ DLT_USER10 = 0x9d
+ DLT_USER11 = 0x9e
+ DLT_USER12 = 0x9f
+ DLT_USER13 = 0xa0
+ DLT_USER14 = 0xa1
+ DLT_USER15 = 0xa2
+ DLT_USER2 = 0x95
+ DLT_USER3 = 0x96
+ DLT_USER4 = 0x97
+ DLT_USER5 = 0x98
+ DLT_USER6 = 0x99
+ DLT_USER7 = 0x9a
+ DLT_USER8 = 0x9b
+ DLT_USER9 = 0x9c
+ DLT_WIHART = 0xdf
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EVFILT_AIO = -0x3
+ EVFILT_EXCEPT = -0xf
+ EVFILT_FS = -0x9
+ EVFILT_MACHPORT = -0x8
+ EVFILT_PROC = -0x5
+ EVFILT_READ = -0x1
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0xf
+ EVFILT_THREADMARKER = 0xf
+ EVFILT_TIMER = -0x7
+ EVFILT_USER = -0xa
+ EVFILT_VM = -0xc
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_DISPATCH = 0x80
+ EV_DISPATCH2 = 0x180
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG0 = 0x1000
+ EV_FLAG1 = 0x2000
+ EV_ONESHOT = 0x10
+ EV_OOBAND = 0x2000
+ EV_POLL = 0x1000
+ EV_RECEIPT = 0x40
+ EV_SYSFLAGS = 0xf000
+ EV_UDATA_SPECIFIC = 0x100
+ EV_VANISHED = 0x200
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x4000
+ FFDLY = 0x4000
+ FLUSHO = 0x800000
+ F_ADDFILESIGS = 0x3d
+ F_ADDFILESIGS_FOR_DYLD_SIM = 0x53
+ F_ADDFILESIGS_RETURN = 0x61
+ F_ADDSIGS = 0x3b
+ F_ALLOCATEALL = 0x4
+ F_ALLOCATECONTIG = 0x2
+ F_BARRIERFSYNC = 0x55
+ F_CHECK_LV = 0x62
+ F_CHKCLEAN = 0x29
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x43
+ F_FINDSIGS = 0x4e
+ F_FLUSH_DATA = 0x28
+ F_FREEZE_FS = 0x35
+ F_FULLFSYNC = 0x33
+ F_GETCODEDIR = 0x48
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETLKPID = 0x42
+ F_GETNOSIGPIPE = 0x4a
+ F_GETOWN = 0x5
+ F_GETPATH = 0x32
+ F_GETPATH_MTMINFO = 0x47
+ F_GETPROTECTIONCLASS = 0x3f
+ F_GETPROTECTIONLEVEL = 0x4d
+ F_GLOBAL_NOCACHE = 0x37
+ F_LOG2PHYS = 0x31
+ F_LOG2PHYS_EXT = 0x41
+ F_NOCACHE = 0x30
+ F_NODIRECT = 0x3e
+ F_OK = 0x0
+ F_PATHPKG_CHECK = 0x34
+ F_PEOFPOSMODE = 0x3
+ F_PREALLOCATE = 0x2a
+ F_RDADVISE = 0x2c
+ F_RDAHEAD = 0x2d
+ F_RDLCK = 0x1
+ F_SETBACKINGSTORE = 0x46
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETLKWTIMEOUT = 0xa
+ F_SETNOSIGPIPE = 0x49
+ F_SETOWN = 0x6
+ F_SETPROTECTIONCLASS = 0x40
+ F_SETSIZE = 0x2b
+ F_SINGLE_WRITER = 0x4c
+ F_THAW_FS = 0x36
+ F_TRANSCODEKEY = 0x4b
+ F_UNLCK = 0x2
+ F_VOLPOSMODE = 0x4
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFF_ALLMULTI = 0x200
+ IFF_ALTPHYS = 0x4000
+ IFF_BROADCAST = 0x2
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NOTRAILERS = 0x20
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_AAL5 = 0x31
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ATM = 0x25
+ IFT_BRIDGE = 0xd1
+ IFT_CARP = 0xf8
+ IFT_CELLULAR = 0xff
+ IFT_CEPT = 0x13
+ IFT_DS3 = 0x1e
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0x38
+ IFT_FDDI = 0xf
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_GIF = 0x37
+ IFT_HDH1822 = 0x3
+ IFT_HIPPI = 0x2f
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE8023ADLAG = 0x88
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88026 = 0xa
+ IFT_L2VLAN = 0x87
+ IFT_LAPB = 0x10
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_NSIP = 0x1b
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PDP = 0xff
+ IFT_PFLOG = 0xf5
+ IFT_PFSYNC = 0xf6
+ IFT_PKTAP = 0xfe
+ IFT_PPP = 0x17
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PTPSERIAL = 0x16
+ IFT_RS232 = 0x21
+ IFT_SDLC = 0x11
+ IFT_SIP = 0x1f
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_STARLAN = 0xb
+ IFT_STF = 0x39
+ IFT_T1 = 0x12
+ IFT_ULTRA = 0x1d
+ IFT_V35 = 0x2d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LINKLOCALNETNUM = 0xa9fe0000
+ IN_LOOPBACKNET = 0x7f
+ IPPROTO_3PC = 0x22
+ IPPROTO_ADFS = 0x44
+ IPPROTO_AH = 0x33
+ IPPROTO_AHIP = 0x3d
+ IPPROTO_APES = 0x63
+ IPPROTO_ARGUS = 0xd
+ IPPROTO_AX25 = 0x5d
+ IPPROTO_BHA = 0x31
+ IPPROTO_BLT = 0x1e
+ IPPROTO_BRSATMON = 0x4c
+ IPPROTO_CFTP = 0x3e
+ IPPROTO_CHAOS = 0x10
+ IPPROTO_CMTP = 0x26
+ IPPROTO_CPHB = 0x49
+ IPPROTO_CPNX = 0x48
+ IPPROTO_DDP = 0x25
+ IPPROTO_DGP = 0x56
+ IPPROTO_DIVERT = 0xfe
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_EMCON = 0xe
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GMTP = 0x64
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HELLO = 0x3f
+ IPPROTO_HMP = 0x14
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IDPR = 0x23
+ IPPROTO_IDRP = 0x2d
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IGP = 0x55
+ IPPROTO_IGRP = 0x58
+ IPPROTO_IL = 0x28
+ IPPROTO_INLSP = 0x34
+ IPPROTO_INP = 0x20
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPCV = 0x47
+ IPPROTO_IPEIP = 0x5e
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPPC = 0x43
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IRTP = 0x1c
+ IPPROTO_KRYPTOLAN = 0x41
+ IPPROTO_LARP = 0x5b
+ IPPROTO_LEAF1 = 0x19
+ IPPROTO_LEAF2 = 0x1a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x34
+ IPPROTO_MEAS = 0x13
+ IPPROTO_MHRP = 0x30
+ IPPROTO_MICP = 0x5f
+ IPPROTO_MTP = 0x5c
+ IPPROTO_MUX = 0x12
+ IPPROTO_ND = 0x4d
+ IPPROTO_NHRP = 0x36
+ IPPROTO_NONE = 0x3b
+ IPPROTO_NSP = 0x1f
+ IPPROTO_NVPII = 0xb
+ IPPROTO_OSPFIGP = 0x59
+ IPPROTO_PGM = 0x71
+ IPPROTO_PIGP = 0x9
+ IPPROTO_PIM = 0x67
+ IPPROTO_PRM = 0x15
+ IPPROTO_PUP = 0xc
+ IPPROTO_PVP = 0x4b
+ IPPROTO_RAW = 0xff
+ IPPROTO_RCCMON = 0xa
+ IPPROTO_RDP = 0x1b
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_RVD = 0x42
+ IPPROTO_SATEXPAK = 0x40
+ IPPROTO_SATMON = 0x45
+ IPPROTO_SCCSP = 0x60
+ IPPROTO_SCTP = 0x84
+ IPPROTO_SDRP = 0x2a
+ IPPROTO_SEP = 0x21
+ IPPROTO_SRPC = 0x5a
+ IPPROTO_ST = 0x7
+ IPPROTO_SVMTP = 0x52
+ IPPROTO_SWIPE = 0x35
+ IPPROTO_TCF = 0x57
+ IPPROTO_TCP = 0x6
+ IPPROTO_TP = 0x1d
+ IPPROTO_TPXX = 0x27
+ IPPROTO_TRUNK1 = 0x17
+ IPPROTO_TRUNK2 = 0x18
+ IPPROTO_TTP = 0x54
+ IPPROTO_UDP = 0x11
+ IPPROTO_VINES = 0x53
+ IPPROTO_VISA = 0x46
+ IPPROTO_VMTP = 0x51
+ IPPROTO_WBEXPAK = 0x4f
+ IPPROTO_WBMON = 0x4e
+ IPPROTO_WSN = 0x4a
+ IPPROTO_XNET = 0xf
+ IPPROTO_XTP = 0x24
+ IPV6_2292DSTOPTS = 0x17
+ IPV6_2292HOPLIMIT = 0x14
+ IPV6_2292HOPOPTS = 0x16
+ IPV6_2292NEXTHOP = 0x15
+ IPV6_2292PKTINFO = 0x13
+ IPV6_2292PKTOPTIONS = 0x19
+ IPV6_2292RTHDR = 0x18
+ IPV6_BINDV6ONLY = 0x1b
+ IPV6_BOUND_IF = 0x7d
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x3c
+ IPV6_FW_ADD = 0x1e
+ IPV6_FW_DEL = 0x1f
+ IPV6_FW_FLUSH = 0x20
+ IPV6_FW_GET = 0x22
+ IPV6_FW_ZERO = 0x21
+ IPV6_HLIMDEC = 0x1
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXOPTHDR = 0x800
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MAX_GROUP_SRC_FILTER = 0x200
+ IPV6_MAX_MEMBERSHIPS = 0xfff
+ IPV6_MAX_SOCK_SRC_FILTER = 0x80
+ IPV6_MIN_MEMBERSHIPS = 0x1f
+ IPV6_MMTU = 0x500
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_RECVTCLASS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x24
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_ADD_SOURCE_MEMBERSHIP = 0x46
+ IP_BLOCK_SOURCE = 0x48
+ IP_BOUND_IF = 0x19
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_DROP_SOURCE_MEMBERSHIP = 0x47
+ IP_DUMMYNET_CONFIGURE = 0x3c
+ IP_DUMMYNET_DEL = 0x3d
+ IP_DUMMYNET_FLUSH = 0x3e
+ IP_DUMMYNET_GET = 0x40
+ IP_FAITH = 0x16
+ IP_FW_ADD = 0x28
+ IP_FW_DEL = 0x29
+ IP_FW_FLUSH = 0x2a
+ IP_FW_GET = 0x2c
+ IP_FW_RESETLOG = 0x2d
+ IP_FW_ZERO = 0x2b
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x15
+ IP_MAXPACKET = 0xffff
+ IP_MAX_GROUP_SRC_FILTER = 0x200
+ IP_MAX_MEMBERSHIPS = 0xfff
+ IP_MAX_SOCK_MUTE_FILTER = 0x80
+ IP_MAX_SOCK_SRC_FILTER = 0x80
+ IP_MF = 0x2000
+ IP_MIN_MEMBERSHIPS = 0x1f
+ IP_MSFILTER = 0x4a
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_IFINDEX = 0x42
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_MULTICAST_VIF = 0xe
+ IP_NAT__XXX = 0x37
+ IP_OFFMASK = 0x1fff
+ IP_OLD_FW_ADD = 0x32
+ IP_OLD_FW_DEL = 0x33
+ IP_OLD_FW_FLUSH = 0x34
+ IP_OLD_FW_GET = 0x36
+ IP_OLD_FW_RESETLOG = 0x38
+ IP_OLD_FW_ZERO = 0x35
+ IP_OPTIONS = 0x1
+ IP_PKTINFO = 0x1a
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVPKTINFO = 0x1a
+ IP_RECVRETOPTS = 0x6
+ IP_RECVTTL = 0x18
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RSVP_OFF = 0x10
+ IP_RSVP_ON = 0xf
+ IP_RSVP_VIF_OFF = 0x12
+ IP_RSVP_VIF_ON = 0x11
+ IP_STRIPHDR = 0x17
+ IP_TOS = 0x3
+ IP_TRAFFIC_MGT_BACKGROUND = 0x41
+ IP_TTL = 0x4
+ IP_UNBLOCK_SOURCE = 0x49
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IUTF8 = 0x4000
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_CAN_REUSE = 0x9
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x5
+ MADV_FREE_REUSABLE = 0x7
+ MADV_FREE_REUSE = 0x8
+ MADV_NORMAL = 0x0
+ MADV_PAGEOUT = 0xa
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_WILLNEED = 0x3
+ MADV_ZERO_WIRED_PAGES = 0x6
+ MAP_ANON = 0x1000
+ MAP_ANONYMOUS = 0x1000
+ MAP_COPY = 0x2
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_HASSEMAPHORE = 0x200
+ MAP_JIT = 0x800
+ MAP_NOCACHE = 0x400
+ MAP_NOEXTEND = 0x100
+ MAP_NORESERVE = 0x40
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_RESERVED0080 = 0x80
+ MAP_RESILIENT_CODESIGN = 0x2000
+ MAP_RESILIENT_MEDIA = 0x4000
+ MAP_SHARED = 0x1
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MNT_ASYNC = 0x40
+ MNT_AUTOMOUNTED = 0x400000
+ MNT_CMDFLAGS = 0xf0000
+ MNT_CPROTECT = 0x80
+ MNT_DEFWRITE = 0x2000000
+ MNT_DONTBROWSE = 0x100000
+ MNT_DOVOLFS = 0x8000
+ MNT_DWAIT = 0x4
+ MNT_EXPORTED = 0x100
+ MNT_FORCE = 0x80000
+ MNT_IGNORE_OWNERSHIP = 0x200000
+ MNT_JOURNALED = 0x800000
+ MNT_LOCAL = 0x1000
+ MNT_MULTILABEL = 0x4000000
+ MNT_NOATIME = 0x10000000
+ MNT_NOBLOCK = 0x20000
+ MNT_NODEV = 0x10
+ MNT_NOEXEC = 0x4
+ MNT_NOSUID = 0x8
+ MNT_NOUSERXATTR = 0x1000000
+ MNT_NOWAIT = 0x2
+ MNT_QUARANTINE = 0x400
+ MNT_QUOTA = 0x2000
+ MNT_RDONLY = 0x1
+ MNT_RELOAD = 0x40000
+ MNT_ROOTFS = 0x4000
+ MNT_SYNCHRONOUS = 0x2
+ MNT_UNION = 0x20
+ MNT_UNKNOWNPERMISSIONS = 0x200000
+ MNT_UPDATE = 0x10000
+ MNT_VISFLAGMASK = 0x17f0f5ff
+ MNT_WAIT = 0x1
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOF = 0x100
+ MSG_EOR = 0x8
+ MSG_FLUSH = 0x400
+ MSG_HAVEMORE = 0x2000
+ MSG_HOLD = 0x800
+ MSG_NEEDSA = 0x10000
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_RCVMORE = 0x4000
+ MSG_SEND = 0x1000
+ MSG_TRUNC = 0x10
+ MSG_WAITALL = 0x40
+ MSG_WAITSTREAM = 0x200
+ MS_ASYNC = 0x1
+ MS_DEACTIVATE = 0x8
+ MS_INVALIDATE = 0x2
+ MS_KILLPAGES = 0x4
+ MS_SYNC = 0x10
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_DUMP2 = 0x7
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_IFLIST2 = 0x6
+ NET_RT_MAXID = 0xa
+ NET_RT_STAT = 0x4
+ NET_RT_TRASH = 0x5
+ NL0 = 0x0
+ NL1 = 0x100
+ NL2 = 0x200
+ NL3 = 0x300
+ NLDLY = 0x300
+ NOFLSH = 0x80000000
+ NOKERNINFO = 0x2000000
+ NOTE_ABSOLUTE = 0x8
+ NOTE_ATTRIB = 0x8
+ NOTE_BACKGROUND = 0x40
+ NOTE_CHILD = 0x4
+ NOTE_CRITICAL = 0x20
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXITSTATUS = 0x4000000
+ NOTE_EXIT_CSERROR = 0x40000
+ NOTE_EXIT_DECRYPTFAIL = 0x10000
+ NOTE_EXIT_DETAIL = 0x2000000
+ NOTE_EXIT_DETAIL_MASK = 0x70000
+ NOTE_EXIT_MEMORY = 0x20000
+ NOTE_EXIT_REPARENTED = 0x80000
+ NOTE_EXTEND = 0x4
+ NOTE_FFAND = 0x40000000
+ NOTE_FFCOPY = 0xc0000000
+ NOTE_FFCTRLMASK = 0xc0000000
+ NOTE_FFLAGSMASK = 0xffffff
+ NOTE_FFNOP = 0x0
+ NOTE_FFOR = 0x80000000
+ NOTE_FORK = 0x40000000
+ NOTE_FUNLOCK = 0x100
+ NOTE_LEEWAY = 0x10
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_MACH_CONTINUOUS_TIME = 0x80
+ NOTE_NONE = 0x80
+ NOTE_NSECONDS = 0x4
+ NOTE_OOB = 0x2
+ NOTE_PCTRLMASK = -0x100000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_REAP = 0x10000000
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_SECONDS = 0x1
+ NOTE_SIGNAL = 0x8000000
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRIGGER = 0x1000000
+ NOTE_USECONDS = 0x2
+ NOTE_VM_ERROR = 0x10000000
+ NOTE_VM_PRESSURE = 0x80000000
+ NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000
+ NOTE_VM_PRESSURE_TERMINATE = 0x40000000
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ OFDEL = 0x20000
+ OFILL = 0x80
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ OXTABS = 0x4
+ O_ACCMODE = 0x3
+ O_ALERT = 0x20000000
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x1000000
+ O_CREAT = 0x200
+ O_DIRECTORY = 0x100000
+ O_DP_GETRAWENCRYPTED = 0x1
+ O_DP_GETRAWUNENCRYPTED = 0x2
+ O_DSYNC = 0x400000
+ O_EVTONLY = 0x8000
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x20000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_POPUP = 0x80000000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_SHLOCK = 0x10
+ O_SYMLINK = 0x200000
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ PT_ATTACH = 0xa
+ PT_ATTACHEXC = 0xe
+ PT_CONTINUE = 0x7
+ PT_DENY_ATTACH = 0x1f
+ PT_DETACH = 0xb
+ PT_FIRSTMACH = 0x20
+ PT_FORCEQUOTA = 0x1e
+ PT_KILL = 0x8
+ PT_READ_D = 0x2
+ PT_READ_I = 0x1
+ PT_READ_U = 0x3
+ PT_SIGEXC = 0xc
+ PT_STEP = 0x9
+ PT_THUPDATE = 0xd
+ PT_TRACE_ME = 0x0
+ PT_WRITE_D = 0x5
+ PT_WRITE_I = 0x4
+ PT_WRITE_U = 0x6
+ RLIMIT_AS = 0x5
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_CPU_USAGE_MONITOR = 0x2
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_MEMLOCK = 0x6
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_NPROC = 0x7
+ RLIMIT_RSS = 0x5
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x8
+ RTAX_NETMASK = 0x2
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTF_BLACKHOLE = 0x1000
+ RTF_BROADCAST = 0x400000
+ RTF_CLONING = 0x100
+ RTF_CONDEMNED = 0x2000000
+ RTF_DELCLONE = 0x80
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_IFREF = 0x4000000
+ RTF_IFSCOPE = 0x1000000
+ RTF_LLINFO = 0x400
+ RTF_LOCAL = 0x200000
+ RTF_MODIFIED = 0x20
+ RTF_MULTICAST = 0x800000
+ RTF_NOIFREF = 0x2000
+ RTF_PINNED = 0x100000
+ RTF_PRCLONING = 0x10000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x40000
+ RTF_PROXY = 0x8000000
+ RTF_REJECT = 0x8
+ RTF_ROUTER = 0x10000000
+ RTF_STATIC = 0x800
+ RTF_UP = 0x1
+ RTF_WASCLONED = 0x20000
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DELMADDR = 0x10
+ RTM_GET = 0x4
+ RTM_GET2 = 0x14
+ RTM_IFINFO = 0xe
+ RTM_IFINFO2 = 0x12
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_NEWMADDR = 0xf
+ RTM_NEWMADDR2 = 0x13
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x5
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ SCM_CREDS = 0x3
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x2
+ SCM_TIMESTAMP_MONOTONIC = 0x4
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCAIFADDR = 0x8040691a
+ SIOCARPIPLL = 0xc0206928
+ SIOCATMARK = 0x40047307
+ SIOCAUTOADDR = 0xc0206926
+ SIOCAUTONETMASK = 0x80206927
+ SIOCDELMULTI = 0x80206932
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFPHYADDR = 0x80206941
+ SIOCGDRVSPEC = 0xc028697b
+ SIOCGETVLAN = 0xc020697f
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFALTMTU = 0xc0206948
+ SIOCGIFASYNCMAP = 0xc020697c
+ SIOCGIFBOND = 0xc0206947
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCAP = 0xc020695b
+ SIOCGIFCONF = 0xc00c6924
+ SIOCGIFDEVMTU = 0xc0206944
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFKPI = 0xc0206987
+ SIOCGIFMAC = 0xc0206982
+ SIOCGIFMEDIA = 0xc02c6938
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc0206933
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206940
+ SIOCGIFPHYS = 0xc0206935
+ SIOCGIFPSRCADDR = 0xc020693f
+ SIOCGIFSTATUS = 0xc331693d
+ SIOCGIFVLAN = 0xc020697f
+ SIOCGIFWAKEFLAGS = 0xc0206988
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCIFCREATE = 0xc0206978
+ SIOCIFCREATE2 = 0xc020697a
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc0106981
+ SIOCRSLVMULTI = 0xc010693b
+ SIOCSDRVSPEC = 0x8028697b
+ SIOCSETVLAN = 0x8020697e
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFALTMTU = 0x80206945
+ SIOCSIFASYNCMAP = 0x8020697d
+ SIOCSIFBOND = 0x80206946
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFCAP = 0x8020695a
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFKPI = 0x80206986
+ SIOCSIFLLADDR = 0x8020693c
+ SIOCSIFMAC = 0x80206983
+ SIOCSIFMEDIA = 0xc0206937
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x80206934
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x8040693e
+ SIOCSIFPHYS = 0x80206936
+ SIOCSIFVLAN = 0x8020697e
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SOCK_DGRAM = 0x2
+ SOCK_MAXADDRLEN = 0xff
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_DONTTRUNC = 0x2000
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LABEL = 0x1010
+ SO_LINGER = 0x80
+ SO_LINGER_SEC = 0x1080
+ SO_NETSVC_MARKING_LEVEL = 0x1119
+ SO_NET_SERVICE_TYPE = 0x1116
+ SO_NKE = 0x1021
+ SO_NOADDRERR = 0x1023
+ SO_NOSIGPIPE = 0x1022
+ SO_NOTIFYCONFLICT = 0x1026
+ SO_NP_EXTENSIONS = 0x1083
+ SO_NREAD = 0x1020
+ SO_NUMRCVPKT = 0x1112
+ SO_NWRITE = 0x1024
+ SO_OOBINLINE = 0x100
+ SO_PEERLABEL = 0x1011
+ SO_RANDOMPORT = 0x1082
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_REUSESHAREUID = 0x1025
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_TIMESTAMP = 0x400
+ SO_TIMESTAMP_MONOTONIC = 0x800
+ SO_TYPE = 0x1008
+ SO_UPCALLCLOSEWAIT = 0x1027
+ SO_USELOOPBACK = 0x40
+ SO_WANTMORE = 0x4000
+ SO_WANTOOBFLAG = 0x8000
+ 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_IFWHT = 0xe000
+ 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_ISTXT = 0x200
+ 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 = 0x400
+ TAB2 = 0x800
+ TAB3 = 0x4
+ TABDLY = 0xc04
+ TCIFLUSH = 0x1
+ TCIOFF = 0x3
+ TCIOFLUSH = 0x3
+ TCION = 0x4
+ TCOFLUSH = 0x2
+ TCOOFF = 0x1
+ TCOON = 0x2
+ TCP_CONNECTIONTIMEOUT = 0x20
+ TCP_CONNECTION_INFO = 0x106
+ TCP_ENABLE_ECN = 0x104
+ TCP_FASTOPEN = 0x105
+ TCP_KEEPALIVE = 0x10
+ TCP_KEEPCNT = 0x102
+ TCP_KEEPINTVL = 0x101
+ TCP_MAXHLEN = 0x3c
+ TCP_MAXOLEN = 0x28
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_SACK = 0x4
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MINMSS = 0xd8
+ TCP_MSS = 0x200
+ TCP_NODELAY = 0x1
+ TCP_NOOPT = 0x8
+ TCP_NOPUSH = 0x4
+ TCP_NOTSENT_LOWAT = 0x201
+ TCP_RXT_CONNDROPTIME = 0x80
+ TCP_RXT_FINDROP = 0x100
+ TCP_SENDMOREACKS = 0x103
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDCDTIMESTAMP = 0x40107458
+ TIOCDRAIN = 0x2000745e
+ TIOCDSIMICROCODE = 0x20007455
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLUSH = 0x80047410
+ TIOCGDRAINWAIT = 0x40047456
+ TIOCGETA = 0x40487413
+ TIOCGETD = 0x4004741a
+ TIOCGPGRP = 0x40047477
+ TIOCGWINSZ = 0x40087468
+ TIOCIXOFF = 0x20007480
+ TIOCIXON = 0x20007481
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGDTRWAIT = 0x4004745a
+ TIOCMGET = 0x4004746a
+ TIOCMODG = 0x40047403
+ TIOCMODS = 0x80047404
+ TIOCMSDTRWAIT = 0x8004745b
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCPTYGNAME = 0x40807453
+ TIOCPTYGRANT = 0x20007454
+ TIOCPTYUNLK = 0x20007452
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCONS = 0x20007463
+ TIOCSCTTY = 0x20007461
+ TIOCSDRAINWAIT = 0x80047457
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x80487414
+ TIOCSETAF = 0x80487416
+ TIOCSETAW = 0x80487415
+ TIOCSETD = 0x8004741b
+ TIOCSIG = 0x2000745f
+ TIOCSPGRP = 0x80047476
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x20007465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCTIMESTAMP = 0x40107459
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VM_LOADAVG = 0x2
+ VM_MACHFACTOR = 0x4
+ VM_MAXID = 0x6
+ VM_METER = 0x1
+ VM_SWAPUSAGE = 0x5
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VT0 = 0x0
+ VT1 = 0x10000
+ VTDLY = 0x10000
+ VTIME = 0x11
+ VWERASE = 0x4
+ WCONTINUED = 0x10
+ WCOREFLAG = 0x80
+ WEXITED = 0x4
+ WNOHANG = 0x1
+ WNOWAIT = 0x20
+ WORDSIZE = 0x40
+ WSTOPPED = 0x8
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADARCH = syscall.Errno(0x56)
+ EBADEXEC = syscall.Errno(0x55)
+ EBADF = syscall.Errno(0x9)
+ EBADMACHO = syscall.Errno(0x58)
+ EBADMSG = syscall.Errno(0x5e)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x59)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDEVERR = syscall.Errno(0x53)
+ EDOM = syscall.Errno(0x21)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x5a)
+ EILSEQ = syscall.Errno(0x5c)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x6a)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5f)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x5d)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODATA = syscall.Errno(0x60)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x61)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x5b)
+ ENOPOLICY = syscall.Errno(0x67)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x62)
+ ENOSTR = syscall.Errno(0x63)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTRECOVERABLE = syscall.Errno(0x68)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x2d)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x66)
+ EOVERFLOW = syscall.Errno(0x54)
+ EOWNERDEAD = syscall.Errno(0x69)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x64)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ EPWROFF = syscall.Errno(0x52)
+ EQFULL = syscall.Errno(0x6a)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHLIBVERS = syscall.Errno(0x57)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIME = syscall.Errno(0x65)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "resource busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "operation timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "device power is off",
+ 83: "device error",
+ 84: "value too large to be stored in data type",
+ 85: "bad executable (or shared library)",
+ 86: "bad CPU type in executable",
+ 87: "shared library version mismatch",
+ 88: "malformed Mach-o file",
+ 89: "operation canceled",
+ 90: "identifier removed",
+ 91: "no message of desired type",
+ 92: "illegal byte sequence",
+ 93: "attribute not found",
+ 94: "bad message",
+ 95: "EMULTIHOP (Reserved)",
+ 96: "no message available on STREAM",
+ 97: "ENOLINK (Reserved)",
+ 98: "no STREAM resources",
+ 99: "not a STREAM",
+ 100: "protocol error",
+ 101: "STREAM ioctl timeout",
+ 102: "operation not supported on socket",
+ 103: "policy not found",
+ 104: "state not recoverable",
+ 105: "previous owner died",
+ 106: "interface output queue is full",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "suspended (signal)",
+ 18: "suspended",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go
new file mode 100644
index 0000000..cc8cc5b
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go
@@ -0,0 +1,1673 @@
+// mkerrors.sh -m64
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm64,darwin
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m64 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1c
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x25
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x1e
+ AF_IPX = 0x17
+ AF_ISDN = 0x1c
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x28
+ AF_NATM = 0x1f
+ AF_NDRV = 0x1b
+ AF_NETBIOS = 0x21
+ AF_NS = 0x6
+ AF_OSI = 0x7
+ AF_PPP = 0x22
+ AF_PUP = 0x4
+ AF_RESERVED_36 = 0x24
+ AF_ROUTE = 0x11
+ AF_SIP = 0x18
+ AF_SNA = 0xb
+ AF_SYSTEM = 0x20
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ AF_UTUN = 0x26
+ ALTWERASE = 0x200
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B9600 = 0x2580
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc00c4279
+ BIOCGETIF = 0x4020426b
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044272
+ BIOCGRTIMEOUT = 0x4010426e
+ BIOCGSEESENT = 0x40044276
+ BIOCGSTATS = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDLT = 0x80044278
+ BIOCSETF = 0x80104267
+ BIOCSETFNR = 0x8010427e
+ BIOCSETIF = 0x8020426c
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044273
+ BIOCSRTIMEOUT = 0x8010426d
+ BIOCSSEESENT = 0x80044277
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ 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_MAXBUFSIZE = 0x80000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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 = 0x8000
+ BSDLY = 0x8000
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CLOCK_MONOTONIC = 0x6
+ CLOCK_MONOTONIC_RAW = 0x4
+ CLOCK_MONOTONIC_RAW_APPROX = 0x5
+ CLOCK_PROCESS_CPUTIME_ID = 0xc
+ CLOCK_REALTIME = 0x0
+ CLOCK_THREAD_CPUTIME_ID = 0x10
+ CLOCK_UPTIME_RAW = 0x8
+ CLOCK_UPTIME_RAW_APPROX = 0x9
+ CR0 = 0x0
+ CR1 = 0x1000
+ CR2 = 0x2000
+ CR3 = 0x3000
+ CRDLY = 0x3000
+ CREAD = 0x800
+ CRTSCTS = 0x30000
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_AOS = 0xde
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_CAN20B = 0xbe
+ DLT_CAN_SOCKETCAN = 0xe3
+ DLT_CHAOS = 0x5
+ DLT_CHDLC = 0x68
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DBUS = 0xe7
+ DLT_DECT = 0xdd
+ DLT_DOCSIS = 0x8f
+ DLT_DVB_CI = 0xeb
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FC_2 = 0xe0
+ DLT_FC_2_WITH_FRAME_DELIMS = 0xe1
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_GSMTAP_ABIS = 0xda
+ DLT_GSMTAP_UM = 0xd9
+ DLT_HHDLC = 0x79
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NOFCS = 0xe6
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_IPFILTER = 0x74
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IPNET = 0xe2
+ DLT_IPOIB = 0xf2
+ DLT_IPV4 = 0xe4
+ DLT_IPV6 = 0xe5
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_ATM_CEMIC = 0xee
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FIBRECHANNEL = 0xea
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_SRX_E2E = 0xe9
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_JUNIPER_VS = 0xe8
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_EVDEV = 0xd8
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_PPP_WITHDIRECTION = 0xa6
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MATCHING_MAX = 0xf5
+ DLT_MATCHING_MIN = 0x68
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MPEG_2_TS = 0xf3
+ DLT_MPLS = 0xdb
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_MUX27010 = 0xec
+ DLT_NETANALYZER = 0xf0
+ DLT_NETANALYZER_TRANSPARENT = 0xf1
+ DLT_NFC_LLCP = 0xf5
+ DLT_NFLOG = 0xef
+ DLT_NG40 = 0xf4
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0x10
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PPP_WITH_DIRECTION = 0xa6
+ DLT_PRISM_HEADER = 0x77
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_RIO = 0x7c
+ DLT_SCCP = 0x8e
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xf
+ DLT_STANAG_5066_D_PDU = 0xed
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USB_LINUX = 0xbd
+ DLT_USB_LINUX_MMAPPED = 0xdc
+ DLT_USER0 = 0x93
+ DLT_USER1 = 0x94
+ DLT_USER10 = 0x9d
+ DLT_USER11 = 0x9e
+ DLT_USER12 = 0x9f
+ DLT_USER13 = 0xa0
+ DLT_USER14 = 0xa1
+ DLT_USER15 = 0xa2
+ DLT_USER2 = 0x95
+ DLT_USER3 = 0x96
+ DLT_USER4 = 0x97
+ DLT_USER5 = 0x98
+ DLT_USER6 = 0x99
+ DLT_USER7 = 0x9a
+ DLT_USER8 = 0x9b
+ DLT_USER9 = 0x9c
+ DLT_WIHART = 0xdf
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EVFILT_AIO = -0x3
+ EVFILT_EXCEPT = -0xf
+ EVFILT_FS = -0x9
+ EVFILT_MACHPORT = -0x8
+ EVFILT_PROC = -0x5
+ EVFILT_READ = -0x1
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0xf
+ EVFILT_THREADMARKER = 0xf
+ EVFILT_TIMER = -0x7
+ EVFILT_USER = -0xa
+ EVFILT_VM = -0xc
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_DISPATCH = 0x80
+ EV_DISPATCH2 = 0x180
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG0 = 0x1000
+ EV_FLAG1 = 0x2000
+ EV_ONESHOT = 0x10
+ EV_OOBAND = 0x2000
+ EV_POLL = 0x1000
+ EV_RECEIPT = 0x40
+ EV_SYSFLAGS = 0xf000
+ EV_UDATA_SPECIFIC = 0x100
+ EV_VANISHED = 0x200
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x4000
+ FFDLY = 0x4000
+ FLUSHO = 0x800000
+ F_ADDFILESIGS = 0x3d
+ F_ADDFILESIGS_FOR_DYLD_SIM = 0x53
+ F_ADDFILESIGS_RETURN = 0x61
+ F_ADDSIGS = 0x3b
+ F_ALLOCATEALL = 0x4
+ F_ALLOCATECONTIG = 0x2
+ F_BARRIERFSYNC = 0x55
+ F_CHECK_LV = 0x62
+ F_CHKCLEAN = 0x29
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x43
+ F_FINDSIGS = 0x4e
+ F_FLUSH_DATA = 0x28
+ F_FREEZE_FS = 0x35
+ F_FULLFSYNC = 0x33
+ F_GETCODEDIR = 0x48
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETLKPID = 0x42
+ F_GETNOSIGPIPE = 0x4a
+ F_GETOWN = 0x5
+ F_GETPATH = 0x32
+ F_GETPATH_MTMINFO = 0x47
+ F_GETPROTECTIONCLASS = 0x3f
+ F_GETPROTECTIONLEVEL = 0x4d
+ F_GLOBAL_NOCACHE = 0x37
+ F_LOG2PHYS = 0x31
+ F_LOG2PHYS_EXT = 0x41
+ F_NOCACHE = 0x30
+ F_NODIRECT = 0x3e
+ F_OK = 0x0
+ F_PATHPKG_CHECK = 0x34
+ F_PEOFPOSMODE = 0x3
+ F_PREALLOCATE = 0x2a
+ F_RDADVISE = 0x2c
+ F_RDAHEAD = 0x2d
+ F_RDLCK = 0x1
+ F_SETBACKINGSTORE = 0x46
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETLKWTIMEOUT = 0xa
+ F_SETNOSIGPIPE = 0x49
+ F_SETOWN = 0x6
+ F_SETPROTECTIONCLASS = 0x40
+ F_SETSIZE = 0x2b
+ F_SINGLE_WRITER = 0x4c
+ F_THAW_FS = 0x36
+ F_TRANSCODEKEY = 0x4b
+ F_UNLCK = 0x2
+ F_VOLPOSMODE = 0x4
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFF_ALLMULTI = 0x200
+ IFF_ALTPHYS = 0x4000
+ IFF_BROADCAST = 0x2
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NOTRAILERS = 0x20
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_AAL5 = 0x31
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ATM = 0x25
+ IFT_BRIDGE = 0xd1
+ IFT_CARP = 0xf8
+ IFT_CELLULAR = 0xff
+ IFT_CEPT = 0x13
+ IFT_DS3 = 0x1e
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0x38
+ IFT_FDDI = 0xf
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_GIF = 0x37
+ IFT_HDH1822 = 0x3
+ IFT_HIPPI = 0x2f
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE8023ADLAG = 0x88
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88026 = 0xa
+ IFT_L2VLAN = 0x87
+ IFT_LAPB = 0x10
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_NSIP = 0x1b
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PDP = 0xff
+ IFT_PFLOG = 0xf5
+ IFT_PFSYNC = 0xf6
+ IFT_PKTAP = 0xfe
+ IFT_PPP = 0x17
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PTPSERIAL = 0x16
+ IFT_RS232 = 0x21
+ IFT_SDLC = 0x11
+ IFT_SIP = 0x1f
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_STARLAN = 0xb
+ IFT_STF = 0x39
+ IFT_T1 = 0x12
+ IFT_ULTRA = 0x1d
+ IFT_V35 = 0x2d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LINKLOCALNETNUM = 0xa9fe0000
+ IN_LOOPBACKNET = 0x7f
+ IPPROTO_3PC = 0x22
+ IPPROTO_ADFS = 0x44
+ IPPROTO_AH = 0x33
+ IPPROTO_AHIP = 0x3d
+ IPPROTO_APES = 0x63
+ IPPROTO_ARGUS = 0xd
+ IPPROTO_AX25 = 0x5d
+ IPPROTO_BHA = 0x31
+ IPPROTO_BLT = 0x1e
+ IPPROTO_BRSATMON = 0x4c
+ IPPROTO_CFTP = 0x3e
+ IPPROTO_CHAOS = 0x10
+ IPPROTO_CMTP = 0x26
+ IPPROTO_CPHB = 0x49
+ IPPROTO_CPNX = 0x48
+ IPPROTO_DDP = 0x25
+ IPPROTO_DGP = 0x56
+ IPPROTO_DIVERT = 0xfe
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_EMCON = 0xe
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GMTP = 0x64
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HELLO = 0x3f
+ IPPROTO_HMP = 0x14
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IDPR = 0x23
+ IPPROTO_IDRP = 0x2d
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IGP = 0x55
+ IPPROTO_IGRP = 0x58
+ IPPROTO_IL = 0x28
+ IPPROTO_INLSP = 0x34
+ IPPROTO_INP = 0x20
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPCV = 0x47
+ IPPROTO_IPEIP = 0x5e
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPPC = 0x43
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IRTP = 0x1c
+ IPPROTO_KRYPTOLAN = 0x41
+ IPPROTO_LARP = 0x5b
+ IPPROTO_LEAF1 = 0x19
+ IPPROTO_LEAF2 = 0x1a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x34
+ IPPROTO_MEAS = 0x13
+ IPPROTO_MHRP = 0x30
+ IPPROTO_MICP = 0x5f
+ IPPROTO_MTP = 0x5c
+ IPPROTO_MUX = 0x12
+ IPPROTO_ND = 0x4d
+ IPPROTO_NHRP = 0x36
+ IPPROTO_NONE = 0x3b
+ IPPROTO_NSP = 0x1f
+ IPPROTO_NVPII = 0xb
+ IPPROTO_OSPFIGP = 0x59
+ IPPROTO_PGM = 0x71
+ IPPROTO_PIGP = 0x9
+ IPPROTO_PIM = 0x67
+ IPPROTO_PRM = 0x15
+ IPPROTO_PUP = 0xc
+ IPPROTO_PVP = 0x4b
+ IPPROTO_RAW = 0xff
+ IPPROTO_RCCMON = 0xa
+ IPPROTO_RDP = 0x1b
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_RVD = 0x42
+ IPPROTO_SATEXPAK = 0x40
+ IPPROTO_SATMON = 0x45
+ IPPROTO_SCCSP = 0x60
+ IPPROTO_SCTP = 0x84
+ IPPROTO_SDRP = 0x2a
+ IPPROTO_SEP = 0x21
+ IPPROTO_SRPC = 0x5a
+ IPPROTO_ST = 0x7
+ IPPROTO_SVMTP = 0x52
+ IPPROTO_SWIPE = 0x35
+ IPPROTO_TCF = 0x57
+ IPPROTO_TCP = 0x6
+ IPPROTO_TP = 0x1d
+ IPPROTO_TPXX = 0x27
+ IPPROTO_TRUNK1 = 0x17
+ IPPROTO_TRUNK2 = 0x18
+ IPPROTO_TTP = 0x54
+ IPPROTO_UDP = 0x11
+ IPPROTO_VINES = 0x53
+ IPPROTO_VISA = 0x46
+ IPPROTO_VMTP = 0x51
+ IPPROTO_WBEXPAK = 0x4f
+ IPPROTO_WBMON = 0x4e
+ IPPROTO_WSN = 0x4a
+ IPPROTO_XNET = 0xf
+ IPPROTO_XTP = 0x24
+ IPV6_2292DSTOPTS = 0x17
+ IPV6_2292HOPLIMIT = 0x14
+ IPV6_2292HOPOPTS = 0x16
+ IPV6_2292NEXTHOP = 0x15
+ IPV6_2292PKTINFO = 0x13
+ IPV6_2292PKTOPTIONS = 0x19
+ IPV6_2292RTHDR = 0x18
+ IPV6_BINDV6ONLY = 0x1b
+ IPV6_BOUND_IF = 0x7d
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x3c
+ IPV6_FW_ADD = 0x1e
+ IPV6_FW_DEL = 0x1f
+ IPV6_FW_FLUSH = 0x20
+ IPV6_FW_GET = 0x22
+ IPV6_FW_ZERO = 0x21
+ IPV6_HLIMDEC = 0x1
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXOPTHDR = 0x800
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MAX_GROUP_SRC_FILTER = 0x200
+ IPV6_MAX_MEMBERSHIPS = 0xfff
+ IPV6_MAX_SOCK_SRC_FILTER = 0x80
+ IPV6_MIN_MEMBERSHIPS = 0x1f
+ IPV6_MMTU = 0x500
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_RECVTCLASS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x24
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_ADD_SOURCE_MEMBERSHIP = 0x46
+ IP_BLOCK_SOURCE = 0x48
+ IP_BOUND_IF = 0x19
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_DROP_SOURCE_MEMBERSHIP = 0x47
+ IP_DUMMYNET_CONFIGURE = 0x3c
+ IP_DUMMYNET_DEL = 0x3d
+ IP_DUMMYNET_FLUSH = 0x3e
+ IP_DUMMYNET_GET = 0x40
+ IP_FAITH = 0x16
+ IP_FW_ADD = 0x28
+ IP_FW_DEL = 0x29
+ IP_FW_FLUSH = 0x2a
+ IP_FW_GET = 0x2c
+ IP_FW_RESETLOG = 0x2d
+ IP_FW_ZERO = 0x2b
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x15
+ IP_MAXPACKET = 0xffff
+ IP_MAX_GROUP_SRC_FILTER = 0x200
+ IP_MAX_MEMBERSHIPS = 0xfff
+ IP_MAX_SOCK_MUTE_FILTER = 0x80
+ IP_MAX_SOCK_SRC_FILTER = 0x80
+ IP_MF = 0x2000
+ IP_MIN_MEMBERSHIPS = 0x1f
+ IP_MSFILTER = 0x4a
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_IFINDEX = 0x42
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_MULTICAST_VIF = 0xe
+ IP_NAT__XXX = 0x37
+ IP_OFFMASK = 0x1fff
+ IP_OLD_FW_ADD = 0x32
+ IP_OLD_FW_DEL = 0x33
+ IP_OLD_FW_FLUSH = 0x34
+ IP_OLD_FW_GET = 0x36
+ IP_OLD_FW_RESETLOG = 0x38
+ IP_OLD_FW_ZERO = 0x35
+ IP_OPTIONS = 0x1
+ IP_PKTINFO = 0x1a
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVPKTINFO = 0x1a
+ IP_RECVRETOPTS = 0x6
+ IP_RECVTTL = 0x18
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RSVP_OFF = 0x10
+ IP_RSVP_ON = 0xf
+ IP_RSVP_VIF_OFF = 0x12
+ IP_RSVP_VIF_ON = 0x11
+ IP_STRIPHDR = 0x17
+ IP_TOS = 0x3
+ IP_TRAFFIC_MGT_BACKGROUND = 0x41
+ IP_TTL = 0x4
+ IP_UNBLOCK_SOURCE = 0x49
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IUTF8 = 0x4000
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_CAN_REUSE = 0x9
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x5
+ MADV_FREE_REUSABLE = 0x7
+ MADV_FREE_REUSE = 0x8
+ MADV_NORMAL = 0x0
+ MADV_PAGEOUT = 0xa
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_WILLNEED = 0x3
+ MADV_ZERO_WIRED_PAGES = 0x6
+ MAP_ANON = 0x1000
+ MAP_ANONYMOUS = 0x1000
+ MAP_COPY = 0x2
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_HASSEMAPHORE = 0x200
+ MAP_JIT = 0x800
+ MAP_NOCACHE = 0x400
+ MAP_NOEXTEND = 0x100
+ MAP_NORESERVE = 0x40
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_RESERVED0080 = 0x80
+ MAP_RESILIENT_CODESIGN = 0x2000
+ MAP_RESILIENT_MEDIA = 0x4000
+ MAP_SHARED = 0x1
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MNT_ASYNC = 0x40
+ MNT_AUTOMOUNTED = 0x400000
+ MNT_CMDFLAGS = 0xf0000
+ MNT_CPROTECT = 0x80
+ MNT_DEFWRITE = 0x2000000
+ MNT_DONTBROWSE = 0x100000
+ MNT_DOVOLFS = 0x8000
+ MNT_DWAIT = 0x4
+ MNT_EXPORTED = 0x100
+ MNT_FORCE = 0x80000
+ MNT_IGNORE_OWNERSHIP = 0x200000
+ MNT_JOURNALED = 0x800000
+ MNT_LOCAL = 0x1000
+ MNT_MULTILABEL = 0x4000000
+ MNT_NOATIME = 0x10000000
+ MNT_NOBLOCK = 0x20000
+ MNT_NODEV = 0x10
+ MNT_NOEXEC = 0x4
+ MNT_NOSUID = 0x8
+ MNT_NOUSERXATTR = 0x1000000
+ MNT_NOWAIT = 0x2
+ MNT_QUARANTINE = 0x400
+ MNT_QUOTA = 0x2000
+ MNT_RDONLY = 0x1
+ MNT_RELOAD = 0x40000
+ MNT_ROOTFS = 0x4000
+ MNT_SYNCHRONOUS = 0x2
+ MNT_UNION = 0x20
+ MNT_UNKNOWNPERMISSIONS = 0x200000
+ MNT_UPDATE = 0x10000
+ MNT_VISFLAGMASK = 0x17f0f5ff
+ MNT_WAIT = 0x1
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOF = 0x100
+ MSG_EOR = 0x8
+ MSG_FLUSH = 0x400
+ MSG_HAVEMORE = 0x2000
+ MSG_HOLD = 0x800
+ MSG_NEEDSA = 0x10000
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_RCVMORE = 0x4000
+ MSG_SEND = 0x1000
+ MSG_TRUNC = 0x10
+ MSG_WAITALL = 0x40
+ MSG_WAITSTREAM = 0x200
+ MS_ASYNC = 0x1
+ MS_DEACTIVATE = 0x8
+ MS_INVALIDATE = 0x2
+ MS_KILLPAGES = 0x4
+ MS_SYNC = 0x10
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_DUMP2 = 0x7
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_IFLIST2 = 0x6
+ NET_RT_MAXID = 0xa
+ NET_RT_STAT = 0x4
+ NET_RT_TRASH = 0x5
+ NL0 = 0x0
+ NL1 = 0x100
+ NL2 = 0x200
+ NL3 = 0x300
+ NLDLY = 0x300
+ NOFLSH = 0x80000000
+ NOKERNINFO = 0x2000000
+ NOTE_ABSOLUTE = 0x8
+ NOTE_ATTRIB = 0x8
+ NOTE_BACKGROUND = 0x40
+ NOTE_CHILD = 0x4
+ NOTE_CRITICAL = 0x20
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXITSTATUS = 0x4000000
+ NOTE_EXIT_CSERROR = 0x40000
+ NOTE_EXIT_DECRYPTFAIL = 0x10000
+ NOTE_EXIT_DETAIL = 0x2000000
+ NOTE_EXIT_DETAIL_MASK = 0x70000
+ NOTE_EXIT_MEMORY = 0x20000
+ NOTE_EXIT_REPARENTED = 0x80000
+ NOTE_EXTEND = 0x4
+ NOTE_FFAND = 0x40000000
+ NOTE_FFCOPY = 0xc0000000
+ NOTE_FFCTRLMASK = 0xc0000000
+ NOTE_FFLAGSMASK = 0xffffff
+ NOTE_FFNOP = 0x0
+ NOTE_FFOR = 0x80000000
+ NOTE_FORK = 0x40000000
+ NOTE_FUNLOCK = 0x100
+ NOTE_LEEWAY = 0x10
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_MACH_CONTINUOUS_TIME = 0x80
+ NOTE_NONE = 0x80
+ NOTE_NSECONDS = 0x4
+ NOTE_OOB = 0x2
+ NOTE_PCTRLMASK = -0x100000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_REAP = 0x10000000
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_SECONDS = 0x1
+ NOTE_SIGNAL = 0x8000000
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRIGGER = 0x1000000
+ NOTE_USECONDS = 0x2
+ NOTE_VM_ERROR = 0x10000000
+ NOTE_VM_PRESSURE = 0x80000000
+ NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000
+ NOTE_VM_PRESSURE_TERMINATE = 0x40000000
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ OFDEL = 0x20000
+ OFILL = 0x80
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ OXTABS = 0x4
+ O_ACCMODE = 0x3
+ O_ALERT = 0x20000000
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x1000000
+ O_CREAT = 0x200
+ O_DIRECTORY = 0x100000
+ O_DP_GETRAWENCRYPTED = 0x1
+ O_DP_GETRAWUNENCRYPTED = 0x2
+ O_DSYNC = 0x400000
+ O_EVTONLY = 0x8000
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x20000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_POPUP = 0x80000000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_SHLOCK = 0x10
+ O_SYMLINK = 0x200000
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ PT_ATTACH = 0xa
+ PT_ATTACHEXC = 0xe
+ PT_CONTINUE = 0x7
+ PT_DENY_ATTACH = 0x1f
+ PT_DETACH = 0xb
+ PT_FIRSTMACH = 0x20
+ PT_FORCEQUOTA = 0x1e
+ PT_KILL = 0x8
+ PT_READ_D = 0x2
+ PT_READ_I = 0x1
+ PT_READ_U = 0x3
+ PT_SIGEXC = 0xc
+ PT_STEP = 0x9
+ PT_THUPDATE = 0xd
+ PT_TRACE_ME = 0x0
+ PT_WRITE_D = 0x5
+ PT_WRITE_I = 0x4
+ PT_WRITE_U = 0x6
+ RLIMIT_AS = 0x5
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_CPU_USAGE_MONITOR = 0x2
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_MEMLOCK = 0x6
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_NPROC = 0x7
+ RLIMIT_RSS = 0x5
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x8
+ RTAX_NETMASK = 0x2
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTF_BLACKHOLE = 0x1000
+ RTF_BROADCAST = 0x400000
+ RTF_CLONING = 0x100
+ RTF_CONDEMNED = 0x2000000
+ RTF_DELCLONE = 0x80
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_IFREF = 0x4000000
+ RTF_IFSCOPE = 0x1000000
+ RTF_LLINFO = 0x400
+ RTF_LOCAL = 0x200000
+ RTF_MODIFIED = 0x20
+ RTF_MULTICAST = 0x800000
+ RTF_NOIFREF = 0x2000
+ RTF_PINNED = 0x100000
+ RTF_PRCLONING = 0x10000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x40000
+ RTF_PROXY = 0x8000000
+ RTF_REJECT = 0x8
+ RTF_ROUTER = 0x10000000
+ RTF_STATIC = 0x800
+ RTF_UP = 0x1
+ RTF_WASCLONED = 0x20000
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DELMADDR = 0x10
+ RTM_GET = 0x4
+ RTM_GET2 = 0x14
+ RTM_IFINFO = 0xe
+ RTM_IFINFO2 = 0x12
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_NEWMADDR = 0xf
+ RTM_NEWMADDR2 = 0x13
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x5
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ SCM_CREDS = 0x3
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x2
+ SCM_TIMESTAMP_MONOTONIC = 0x4
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCAIFADDR = 0x8040691a
+ SIOCARPIPLL = 0xc0206928
+ SIOCATMARK = 0x40047307
+ SIOCAUTOADDR = 0xc0206926
+ SIOCAUTONETMASK = 0x80206927
+ SIOCDELMULTI = 0x80206932
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFPHYADDR = 0x80206941
+ SIOCGDRVSPEC = 0xc028697b
+ SIOCGETVLAN = 0xc020697f
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFALTMTU = 0xc0206948
+ SIOCGIFASYNCMAP = 0xc020697c
+ SIOCGIFBOND = 0xc0206947
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCAP = 0xc020695b
+ SIOCGIFCONF = 0xc00c6924
+ SIOCGIFDEVMTU = 0xc0206944
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFKPI = 0xc0206987
+ SIOCGIFMAC = 0xc0206982
+ SIOCGIFMEDIA = 0xc02c6938
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc0206933
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206940
+ SIOCGIFPHYS = 0xc0206935
+ SIOCGIFPSRCADDR = 0xc020693f
+ SIOCGIFSTATUS = 0xc331693d
+ SIOCGIFVLAN = 0xc020697f
+ SIOCGIFWAKEFLAGS = 0xc0206988
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCIFCREATE = 0xc0206978
+ SIOCIFCREATE2 = 0xc020697a
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc0106981
+ SIOCRSLVMULTI = 0xc010693b
+ SIOCSDRVSPEC = 0x8028697b
+ SIOCSETVLAN = 0x8020697e
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFALTMTU = 0x80206945
+ SIOCSIFASYNCMAP = 0x8020697d
+ SIOCSIFBOND = 0x80206946
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFCAP = 0x8020695a
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFKPI = 0x80206986
+ SIOCSIFLLADDR = 0x8020693c
+ SIOCSIFMAC = 0x80206983
+ SIOCSIFMEDIA = 0xc0206937
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x80206934
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x8040693e
+ SIOCSIFPHYS = 0x80206936
+ SIOCSIFVLAN = 0x8020697e
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SOCK_DGRAM = 0x2
+ SOCK_MAXADDRLEN = 0xff
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_DONTTRUNC = 0x2000
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LABEL = 0x1010
+ SO_LINGER = 0x80
+ SO_LINGER_SEC = 0x1080
+ SO_NETSVC_MARKING_LEVEL = 0x1119
+ SO_NET_SERVICE_TYPE = 0x1116
+ SO_NKE = 0x1021
+ SO_NOADDRERR = 0x1023
+ SO_NOSIGPIPE = 0x1022
+ SO_NOTIFYCONFLICT = 0x1026
+ SO_NP_EXTENSIONS = 0x1083
+ SO_NREAD = 0x1020
+ SO_NUMRCVPKT = 0x1112
+ SO_NWRITE = 0x1024
+ SO_OOBINLINE = 0x100
+ SO_PEERLABEL = 0x1011
+ SO_RANDOMPORT = 0x1082
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_REUSESHAREUID = 0x1025
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_TIMESTAMP = 0x400
+ SO_TIMESTAMP_MONOTONIC = 0x800
+ SO_TYPE = 0x1008
+ SO_UPCALLCLOSEWAIT = 0x1027
+ SO_USELOOPBACK = 0x40
+ SO_WANTMORE = 0x4000
+ SO_WANTOOBFLAG = 0x8000
+ 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_IFWHT = 0xe000
+ 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_ISTXT = 0x200
+ 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 = 0x400
+ TAB2 = 0x800
+ TAB3 = 0x4
+ TABDLY = 0xc04
+ TCIFLUSH = 0x1
+ TCIOFF = 0x3
+ TCIOFLUSH = 0x3
+ TCION = 0x4
+ TCOFLUSH = 0x2
+ TCOOFF = 0x1
+ TCOON = 0x2
+ TCP_CONNECTIONTIMEOUT = 0x20
+ TCP_CONNECTION_INFO = 0x106
+ TCP_ENABLE_ECN = 0x104
+ TCP_FASTOPEN = 0x105
+ TCP_KEEPALIVE = 0x10
+ TCP_KEEPCNT = 0x102
+ TCP_KEEPINTVL = 0x101
+ TCP_MAXHLEN = 0x3c
+ TCP_MAXOLEN = 0x28
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_SACK = 0x4
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MINMSS = 0xd8
+ TCP_MSS = 0x200
+ TCP_NODELAY = 0x1
+ TCP_NOOPT = 0x8
+ TCP_NOPUSH = 0x4
+ TCP_NOTSENT_LOWAT = 0x201
+ TCP_RXT_CONNDROPTIME = 0x80
+ TCP_RXT_FINDROP = 0x100
+ TCP_SENDMOREACKS = 0x103
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDCDTIMESTAMP = 0x40107458
+ TIOCDRAIN = 0x2000745e
+ TIOCDSIMICROCODE = 0x20007455
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLUSH = 0x80047410
+ TIOCGDRAINWAIT = 0x40047456
+ TIOCGETA = 0x40487413
+ TIOCGETD = 0x4004741a
+ TIOCGPGRP = 0x40047477
+ TIOCGWINSZ = 0x40087468
+ TIOCIXOFF = 0x20007480
+ TIOCIXON = 0x20007481
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGDTRWAIT = 0x4004745a
+ TIOCMGET = 0x4004746a
+ TIOCMODG = 0x40047403
+ TIOCMODS = 0x80047404
+ TIOCMSDTRWAIT = 0x8004745b
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCPTYGNAME = 0x40807453
+ TIOCPTYGRANT = 0x20007454
+ TIOCPTYUNLK = 0x20007452
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCONS = 0x20007463
+ TIOCSCTTY = 0x20007461
+ TIOCSDRAINWAIT = 0x80047457
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x80487414
+ TIOCSETAF = 0x80487416
+ TIOCSETAW = 0x80487415
+ TIOCSETD = 0x8004741b
+ TIOCSIG = 0x2000745f
+ TIOCSPGRP = 0x80047476
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x20007465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCTIMESTAMP = 0x40107459
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VM_LOADAVG = 0x2
+ VM_MACHFACTOR = 0x4
+ VM_MAXID = 0x6
+ VM_METER = 0x1
+ VM_SWAPUSAGE = 0x5
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VT0 = 0x0
+ VT1 = 0x10000
+ VTDLY = 0x10000
+ VTIME = 0x11
+ VWERASE = 0x4
+ WCONTINUED = 0x10
+ WCOREFLAG = 0x80
+ WEXITED = 0x4
+ WNOHANG = 0x1
+ WNOWAIT = 0x20
+ WORDSIZE = 0x40
+ WSTOPPED = 0x8
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADARCH = syscall.Errno(0x56)
+ EBADEXEC = syscall.Errno(0x55)
+ EBADF = syscall.Errno(0x9)
+ EBADMACHO = syscall.Errno(0x58)
+ EBADMSG = syscall.Errno(0x5e)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x59)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDEVERR = syscall.Errno(0x53)
+ EDOM = syscall.Errno(0x21)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x5a)
+ EILSEQ = syscall.Errno(0x5c)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x6a)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5f)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x5d)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODATA = syscall.Errno(0x60)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x61)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x5b)
+ ENOPOLICY = syscall.Errno(0x67)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x62)
+ ENOSTR = syscall.Errno(0x63)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTRECOVERABLE = syscall.Errno(0x68)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x2d)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x66)
+ EOVERFLOW = syscall.Errno(0x54)
+ EOWNERDEAD = syscall.Errno(0x69)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x64)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ EPWROFF = syscall.Errno(0x52)
+ EQFULL = syscall.Errno(0x6a)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHLIBVERS = syscall.Errno(0x57)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIME = syscall.Errno(0x65)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "resource busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "operation timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "device power is off",
+ 83: "device error",
+ 84: "value too large to be stored in data type",
+ 85: "bad executable (or shared library)",
+ 86: "bad CPU type in executable",
+ 87: "shared library version mismatch",
+ 88: "malformed Mach-o file",
+ 89: "operation canceled",
+ 90: "identifier removed",
+ 91: "no message of desired type",
+ 92: "illegal byte sequence",
+ 93: "attribute not found",
+ 94: "bad message",
+ 95: "EMULTIHOP (Reserved)",
+ 96: "no message available on STREAM",
+ 97: "ENOLINK (Reserved)",
+ 98: "no STREAM resources",
+ 99: "not a STREAM",
+ 100: "protocol error",
+ 101: "STREAM ioctl timeout",
+ 102: "operation not supported on socket",
+ 103: "policy not found",
+ 104: "state not recoverable",
+ 105: "previous owner died",
+ 106: "interface output queue is full",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "suspended (signal)",
+ 18: "suspended",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go
new file mode 100644
index 0000000..8f40598
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go
@@ -0,0 +1,1568 @@
+// mkerrors.sh -m64
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,dragonfly
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m64 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_ATM = 0x1e
+ AF_BLUETOOTH = 0x21
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1a
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x23
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x1c
+ AF_IPX = 0x17
+ AF_ISDN = 0x1a
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x24
+ AF_MPLS = 0x22
+ AF_NATM = 0x1d
+ AF_NETBIOS = 0x6
+ AF_NETGRAPH = 0x20
+ AF_OSI = 0x7
+ AF_PUP = 0x4
+ AF_ROUTE = 0x11
+ AF_SIP = 0x18
+ AF_SNA = 0xb
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ ALTWERASE = 0x200
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B9600 = 0x2580
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc0104279
+ BIOCGETIF = 0x4020426b
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044272
+ BIOCGRTIMEOUT = 0x4010426e
+ BIOCGSEESENT = 0x40044276
+ BIOCGSTATS = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCLOCK = 0x2000427a
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDLT = 0x80044278
+ BIOCSETF = 0x80104267
+ BIOCSETIF = 0x8020426c
+ BIOCSETWF = 0x8010427b
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044273
+ BIOCSRTIMEOUT = 0x8010426d
+ BIOCSSEESENT = 0x80044277
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x8
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_DEFAULTBUFSIZE = 0x1000
+ 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_MAXBUFSIZE = 0x80000
+ BPF_MAXINSNS = 0x200
+ BPF_MAX_CLONES = 0x80
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CLOCK_MONOTONIC = 0x4
+ CLOCK_MONOTONIC_FAST = 0xc
+ CLOCK_MONOTONIC_PRECISE = 0xb
+ CLOCK_PROCESS_CPUTIME_ID = 0xf
+ CLOCK_PROF = 0x2
+ CLOCK_REALTIME = 0x0
+ CLOCK_REALTIME_FAST = 0xa
+ CLOCK_REALTIME_PRECISE = 0x9
+ CLOCK_SECOND = 0xd
+ CLOCK_THREAD_CPUTIME_ID = 0xe
+ CLOCK_UPTIME = 0x5
+ CLOCK_UPTIME_FAST = 0x8
+ CLOCK_UPTIME_PRECISE = 0x7
+ CLOCK_VIRTUAL = 0x1
+ CREAD = 0x800
+ CRTSCTS = 0x30000
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_CAN20B = 0xbe
+ DLT_CHAOS = 0x5
+ DLT_CHDLC = 0x68
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DOCSIS = 0x8f
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_HHDLC = 0x79
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_IPFILTER = 0x74
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0x10
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PRISM_HEADER = 0x77
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_REDBACK_SMARTEDGE = 0x20
+ DLT_RIO = 0x7c
+ DLT_SCCP = 0x8e
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xf
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USB_LINUX = 0xbd
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ DT_BLK = 0x6
+ DT_CHR = 0x2
+ DT_DBF = 0xf
+ DT_DIR = 0x4
+ DT_FIFO = 0x1
+ DT_LNK = 0xa
+ DT_REG = 0x8
+ DT_SOCK = 0xc
+ DT_UNKNOWN = 0x0
+ DT_WHT = 0xe
+ ECHO = 0x8
+ ECHOCTL = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EVFILT_AIO = -0x3
+ EVFILT_EXCEPT = -0x8
+ EVFILT_FS = -0xa
+ EVFILT_MARKER = 0xf
+ EVFILT_PROC = -0x5
+ EVFILT_READ = -0x1
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0xa
+ EVFILT_TIMER = -0x7
+ EVFILT_USER = -0x9
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_DISPATCH = 0x80
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG1 = 0x2000
+ EV_NODATA = 0x1000
+ EV_ONESHOT = 0x10
+ EV_RECEIPT = 0x40
+ EV_SYSFLAGS = 0xf000
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTEXIT_LWP = 0x10000
+ EXTEXIT_PROC = 0x0
+ EXTEXIT_SETINT = 0x1
+ EXTEXIT_SIMPLE = 0x0
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FLUSHO = 0x800000
+ F_DUP2FD = 0xa
+ F_DUP2FD_CLOEXEC = 0x12
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x11
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETOWN = 0x5
+ F_OK = 0x0
+ F_RDLCK = 0x1
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETOWN = 0x6
+ F_UNLCK = 0x2
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFAN_ARRIVAL = 0x0
+ IFAN_DEPARTURE = 0x1
+ IFF_ALLMULTI = 0x200
+ IFF_ALTPHYS = 0x4000
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x118e72
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MONITOR = 0x40000
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NPOLLING = 0x100000
+ IFF_OACTIVE = 0x400
+ IFF_OACTIVE_COMPAT = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_POLLING = 0x10000
+ IFF_POLLING_COMPAT = 0x10000
+ IFF_PPROMISC = 0x20000
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_SMART = 0x20
+ IFF_STATICARP = 0x80000
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_A12MPPSWITCH = 0x82
+ IFT_AAL2 = 0xbb
+ IFT_AAL5 = 0x31
+ IFT_ADSL = 0x5e
+ IFT_AFLANE8023 = 0x3b
+ IFT_AFLANE8025 = 0x3c
+ IFT_ARAP = 0x58
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ASYNC = 0x54
+ IFT_ATM = 0x25
+ IFT_ATMDXI = 0x69
+ IFT_ATMFUNI = 0x6a
+ IFT_ATMIMA = 0x6b
+ IFT_ATMLOGICAL = 0x50
+ IFT_ATMRADIO = 0xbd
+ IFT_ATMSUBINTERFACE = 0x86
+ IFT_ATMVCIENDPT = 0xc2
+ IFT_ATMVIRTUAL = 0x95
+ IFT_BGPPOLICYACCOUNTING = 0xa2
+ IFT_BRIDGE = 0xd1
+ IFT_BSC = 0x53
+ IFT_CARP = 0xf8
+ IFT_CCTEMUL = 0x3d
+ IFT_CEPT = 0x13
+ IFT_CES = 0x85
+ IFT_CHANNEL = 0x46
+ IFT_CNR = 0x55
+ IFT_COFFEE = 0x84
+ IFT_COMPOSITELINK = 0x9b
+ IFT_DCN = 0x8d
+ IFT_DIGITALPOWERLINE = 0x8a
+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
+ IFT_DLSW = 0x4a
+ IFT_DOCSCABLEDOWNSTREAM = 0x80
+ IFT_DOCSCABLEMACLAYER = 0x7f
+ IFT_DOCSCABLEUPSTREAM = 0x81
+ IFT_DS0 = 0x51
+ IFT_DS0BUNDLE = 0x52
+ IFT_DS1FDL = 0xaa
+ IFT_DS3 = 0x1e
+ IFT_DTM = 0x8c
+ IFT_DVBASILN = 0xac
+ IFT_DVBASIOUT = 0xad
+ IFT_DVBRCCDOWNSTREAM = 0x93
+ IFT_DVBRCCMACLAYER = 0x92
+ IFT_DVBRCCUPSTREAM = 0x94
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_EPLRS = 0x57
+ IFT_ESCON = 0x49
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0xf2
+ IFT_FAST = 0x7d
+ IFT_FASTETHER = 0x3e
+ IFT_FASTETHERFX = 0x45
+ IFT_FDDI = 0xf
+ IFT_FIBRECHANNEL = 0x38
+ IFT_FRAMERELAYINTERCONNECT = 0x3a
+ IFT_FRAMERELAYMPI = 0x5c
+ IFT_FRDLCIENDPT = 0xc1
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_FRF16MFRBUNDLE = 0xa3
+ IFT_FRFORWARD = 0x9e
+ IFT_G703AT2MB = 0x43
+ IFT_G703AT64K = 0x42
+ IFT_GIF = 0xf0
+ IFT_GIGABITETHERNET = 0x75
+ IFT_GR303IDT = 0xb2
+ IFT_GR303RDT = 0xb1
+ IFT_H323GATEKEEPER = 0xa4
+ IFT_H323PROXY = 0xa5
+ IFT_HDH1822 = 0x3
+ IFT_HDLC = 0x76
+ IFT_HDSL2 = 0xa8
+ IFT_HIPERLAN2 = 0xb7
+ IFT_HIPPI = 0x2f
+ IFT_HIPPIINTERFACE = 0x39
+ IFT_HOSTPAD = 0x5a
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IBM370PARCHAN = 0x48
+ IFT_IDSL = 0x9a
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE80211 = 0x47
+ IFT_IEEE80212 = 0x37
+ IFT_IEEE8023ADLAG = 0xa1
+ IFT_IFGSN = 0x91
+ IFT_IMT = 0xbe
+ IFT_INTERLEAVE = 0x7c
+ IFT_IP = 0x7e
+ IFT_IPFORWARD = 0x8e
+ IFT_IPOVERATM = 0x72
+ IFT_IPOVERCDLC = 0x6d
+ IFT_IPOVERCLAW = 0x6e
+ IFT_IPSWITCH = 0x4e
+ IFT_ISDN = 0x3f
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISDNS = 0x4b
+ IFT_ISDNU = 0x4c
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88025CRFPINT = 0x62
+ IFT_ISO88025DTR = 0x56
+ IFT_ISO88025FIBER = 0x73
+ IFT_ISO88026 = 0xa
+ IFT_ISUP = 0xb3
+ IFT_L2VLAN = 0x87
+ IFT_L3IPVLAN = 0x88
+ IFT_L3IPXVLAN = 0x89
+ IFT_LAPB = 0x10
+ IFT_LAPD = 0x4d
+ IFT_LAPF = 0x77
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MEDIAMAILOVERIP = 0x8b
+ IFT_MFSIGLINK = 0xa7
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_MPC = 0x71
+ IFT_MPLS = 0xa6
+ IFT_MPLSTUNNEL = 0x96
+ IFT_MSDSL = 0x8f
+ IFT_MVL = 0xbf
+ IFT_MYRINET = 0x63
+ IFT_NFAS = 0xaf
+ IFT_NSIP = 0x1b
+ IFT_OPTICALCHANNEL = 0xc3
+ IFT_OPTICALTRANSPORT = 0xc4
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PFLOG = 0xf5
+ IFT_PFSYNC = 0xf6
+ IFT_PLC = 0xae
+ IFT_POS = 0xab
+ IFT_PPP = 0x17
+ IFT_PPPMULTILINKBUNDLE = 0x6c
+ IFT_PROPBWAP2MP = 0xb8
+ IFT_PROPCNLS = 0x59
+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PROPWIRELESSP2P = 0x9d
+ IFT_PTPSERIAL = 0x16
+ IFT_PVC = 0xf1
+ IFT_QLLC = 0x44
+ IFT_RADIOMAC = 0xbc
+ IFT_RADSL = 0x5f
+ IFT_REACHDSL = 0xc0
+ IFT_RFC1483 = 0x9f
+ IFT_RS232 = 0x21
+ IFT_RSRB = 0x4f
+ IFT_SDLC = 0x11
+ IFT_SDSL = 0x60
+ IFT_SHDSL = 0xa9
+ IFT_SIP = 0x1f
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETOVERHEADCHANNEL = 0xb9
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_SRP = 0x97
+ IFT_SS7SIGLINK = 0x9c
+ IFT_STACKTOSTACK = 0x6f
+ IFT_STARLAN = 0xb
+ IFT_STF = 0xf3
+ IFT_T1 = 0x12
+ IFT_TDLC = 0x74
+ IFT_TERMPAD = 0x5b
+ IFT_TR008 = 0xb0
+ IFT_TRANSPHDLC = 0x7b
+ IFT_TUNNEL = 0x83
+ IFT_ULTRA = 0x1d
+ IFT_USB = 0xa0
+ IFT_V11 = 0x40
+ IFT_V35 = 0x2d
+ IFT_V36 = 0x41
+ IFT_V37 = 0x78
+ IFT_VDSL = 0x61
+ IFT_VIRTUALIPADDRESS = 0x70
+ IFT_VOICEEM = 0x64
+ IFT_VOICEENCAP = 0x67
+ IFT_VOICEFXO = 0x65
+ IFT_VOICEFXS = 0x66
+ IFT_VOICEOVERATM = 0x98
+ IFT_VOICEOVERFRAMERELAY = 0x99
+ IFT_VOICEOVERIP = 0x68
+ IFT_X213 = 0x5d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25HUNTGROUP = 0x7a
+ IFT_X25MLP = 0x79
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LOOPBACKNET = 0x7f
+ IPPROTO_3PC = 0x22
+ IPPROTO_ADFS = 0x44
+ IPPROTO_AH = 0x33
+ IPPROTO_AHIP = 0x3d
+ IPPROTO_APES = 0x63
+ IPPROTO_ARGUS = 0xd
+ IPPROTO_AX25 = 0x5d
+ IPPROTO_BHA = 0x31
+ IPPROTO_BLT = 0x1e
+ IPPROTO_BRSATMON = 0x4c
+ IPPROTO_CARP = 0x70
+ IPPROTO_CFTP = 0x3e
+ IPPROTO_CHAOS = 0x10
+ IPPROTO_CMTP = 0x26
+ IPPROTO_CPHB = 0x49
+ IPPROTO_CPNX = 0x48
+ IPPROTO_DDP = 0x25
+ IPPROTO_DGP = 0x56
+ IPPROTO_DIVERT = 0xfe
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_EMCON = 0xe
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GMTP = 0x64
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HELLO = 0x3f
+ IPPROTO_HMP = 0x14
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IDPR = 0x23
+ IPPROTO_IDRP = 0x2d
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IGP = 0x55
+ IPPROTO_IGRP = 0x58
+ IPPROTO_IL = 0x28
+ IPPROTO_INLSP = 0x34
+ IPPROTO_INP = 0x20
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPCV = 0x47
+ IPPROTO_IPEIP = 0x5e
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPPC = 0x43
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IRTP = 0x1c
+ IPPROTO_KRYPTOLAN = 0x41
+ IPPROTO_LARP = 0x5b
+ IPPROTO_LEAF1 = 0x19
+ IPPROTO_LEAF2 = 0x1a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x34
+ IPPROTO_MEAS = 0x13
+ IPPROTO_MHRP = 0x30
+ IPPROTO_MICP = 0x5f
+ IPPROTO_MOBILE = 0x37
+ IPPROTO_MTP = 0x5c
+ IPPROTO_MUX = 0x12
+ IPPROTO_ND = 0x4d
+ IPPROTO_NHRP = 0x36
+ IPPROTO_NONE = 0x3b
+ IPPROTO_NSP = 0x1f
+ IPPROTO_NVPII = 0xb
+ IPPROTO_OSPFIGP = 0x59
+ IPPROTO_PFSYNC = 0xf0
+ IPPROTO_PGM = 0x71
+ IPPROTO_PIGP = 0x9
+ IPPROTO_PIM = 0x67
+ IPPROTO_PRM = 0x15
+ IPPROTO_PUP = 0xc
+ IPPROTO_PVP = 0x4b
+ IPPROTO_RAW = 0xff
+ IPPROTO_RCCMON = 0xa
+ IPPROTO_RDP = 0x1b
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_RVD = 0x42
+ IPPROTO_SATEXPAK = 0x40
+ IPPROTO_SATMON = 0x45
+ IPPROTO_SCCSP = 0x60
+ IPPROTO_SDRP = 0x2a
+ IPPROTO_SEP = 0x21
+ IPPROTO_SKIP = 0x39
+ IPPROTO_SRPC = 0x5a
+ IPPROTO_ST = 0x7
+ IPPROTO_SVMTP = 0x52
+ IPPROTO_SWIPE = 0x35
+ IPPROTO_TCF = 0x57
+ IPPROTO_TCP = 0x6
+ IPPROTO_TLSP = 0x38
+ IPPROTO_TP = 0x1d
+ IPPROTO_TPXX = 0x27
+ IPPROTO_TRUNK1 = 0x17
+ IPPROTO_TRUNK2 = 0x18
+ IPPROTO_TTP = 0x54
+ IPPROTO_UDP = 0x11
+ IPPROTO_UNKNOWN = 0x102
+ IPPROTO_VINES = 0x53
+ IPPROTO_VISA = 0x46
+ IPPROTO_VMTP = 0x51
+ IPPROTO_WBEXPAK = 0x4f
+ IPPROTO_WBMON = 0x4e
+ IPPROTO_WSN = 0x4a
+ IPPROTO_XNET = 0xf
+ IPPROTO_XTP = 0x24
+ IPV6_AUTOFLOWLABEL = 0x3b
+ IPV6_BINDV6ONLY = 0x1b
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_DONTFRAG = 0x3e
+ IPV6_DSTOPTS = 0x32
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x78
+ IPV6_FW_ADD = 0x1e
+ IPV6_FW_DEL = 0x1f
+ IPV6_FW_FLUSH = 0x20
+ IPV6_FW_GET = 0x22
+ IPV6_FW_ZERO = 0x21
+ IPV6_HLIMDEC = 0x1
+ IPV6_HOPLIMIT = 0x2f
+ IPV6_HOPOPTS = 0x31
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MINHLIM = 0x28
+ IPV6_MMTU = 0x500
+ IPV6_MSFILTER = 0x4a
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_NEXTHOP = 0x30
+ IPV6_PATHMTU = 0x2c
+ IPV6_PKTINFO = 0x2e
+ IPV6_PKTOPTIONS = 0x34
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_PREFER_TEMPADDR = 0x3f
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVHOPLIMIT = 0x25
+ IPV6_RECVHOPOPTS = 0x27
+ IPV6_RECVPATHMTU = 0x2b
+ IPV6_RECVPKTINFO = 0x24
+ IPV6_RECVRTHDR = 0x26
+ IPV6_RECVTCLASS = 0x39
+ IPV6_RTHDR = 0x33
+ IPV6_RTHDRDSTOPTS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x3d
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_USE_MIN_MTU = 0x2a
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_DUMMYNET_CONFIGURE = 0x3c
+ IP_DUMMYNET_DEL = 0x3d
+ IP_DUMMYNET_FLUSH = 0x3e
+ IP_DUMMYNET_GET = 0x40
+ IP_FAITH = 0x16
+ IP_FW_ADD = 0x32
+ IP_FW_DEL = 0x33
+ IP_FW_FLUSH = 0x34
+ IP_FW_GET = 0x36
+ IP_FW_RESETLOG = 0x37
+ IP_FW_X = 0x31
+ IP_FW_ZERO = 0x35
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x15
+ IP_MAXPACKET = 0xffff
+ IP_MAX_MEMBERSHIPS = 0x14
+ IP_MF = 0x2000
+ IP_MINTTL = 0x42
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_MULTICAST_VIF = 0xe
+ IP_OFFMASK = 0x1fff
+ IP_OPTIONS = 0x1
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVRETOPTS = 0x6
+ IP_RECVTTL = 0x41
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RSVP_OFF = 0x10
+ IP_RSVP_ON = 0xf
+ IP_RSVP_VIF_OFF = 0x12
+ IP_RSVP_VIF_ON = 0x11
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_AUTOSYNC = 0x7
+ MADV_CONTROL_END = 0xb
+ MADV_CONTROL_START = 0xa
+ MADV_CORE = 0x9
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x5
+ MADV_INVAL = 0xa
+ MADV_NOCORE = 0x8
+ MADV_NORMAL = 0x0
+ MADV_NOSYNC = 0x6
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_SETMAP = 0xb
+ MADV_WILLNEED = 0x3
+ MAP_ANON = 0x1000
+ MAP_ANONYMOUS = 0x1000
+ MAP_COPY = 0x2
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_HASSEMAPHORE = 0x200
+ MAP_INHERIT = 0x80
+ MAP_NOCORE = 0x20000
+ MAP_NOEXTEND = 0x100
+ MAP_NORESERVE = 0x40
+ MAP_NOSYNC = 0x800
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_SHARED = 0x1
+ MAP_SIZEALIGN = 0x40000
+ MAP_STACK = 0x400
+ MAP_TRYFIXED = 0x10000
+ MAP_VPAGETABLE = 0x2000
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MSG_CMSG_CLOEXEC = 0x1000
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOF = 0x100
+ MSG_EOR = 0x8
+ MSG_FBLOCKING = 0x10000
+ MSG_FMASK = 0xffff0000
+ MSG_FNONBLOCKING = 0x20000
+ MSG_NOSIGNAL = 0x400
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_SYNC = 0x800
+ MSG_TRUNC = 0x10
+ MSG_UNUSED09 = 0x200
+ MSG_WAITALL = 0x40
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x2
+ MS_SYNC = 0x0
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_MAXID = 0x4
+ NOFLSH = 0x80000000
+ NOKERNINFO = 0x2000000
+ NOTE_ATTRIB = 0x8
+ NOTE_CHILD = 0x4
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXTEND = 0x4
+ NOTE_FFAND = 0x40000000
+ NOTE_FFCOPY = 0xc0000000
+ NOTE_FFCTRLMASK = 0xc0000000
+ NOTE_FFLAGSMASK = 0xffffff
+ NOTE_FFNOP = 0x0
+ NOTE_FFOR = 0x80000000
+ NOTE_FORK = 0x40000000
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_OOB = 0x2
+ NOTE_PCTRLMASK = 0xf0000000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRIGGER = 0x1000000
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ OXTABS = 0x4
+ O_ACCMODE = 0x3
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x20000
+ O_CREAT = 0x200
+ O_DIRECT = 0x10000
+ O_DIRECTORY = 0x8000000
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FAPPEND = 0x100000
+ O_FASYNCWRITE = 0x800000
+ O_FBLOCKING = 0x40000
+ O_FMASK = 0xfc0000
+ O_FNONBLOCKING = 0x80000
+ O_FOFFSET = 0x200000
+ O_FSYNC = 0x80
+ O_FSYNCWRITE = 0x400000
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_SHLOCK = 0x10
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ RLIMIT_AS = 0xa
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0xb
+ RTAX_MPLS1 = 0x8
+ RTAX_MPLS2 = 0x9
+ RTAX_MPLS3 = 0xa
+ RTAX_NETMASK = 0x2
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_MPLS1 = 0x100
+ RTA_MPLS2 = 0x200
+ RTA_MPLS3 = 0x400
+ RTA_NETMASK = 0x4
+ RTF_BLACKHOLE = 0x1000
+ RTF_BROADCAST = 0x400000
+ RTF_CLONING = 0x100
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_LLINFO = 0x400
+ RTF_LOCAL = 0x200000
+ RTF_MODIFIED = 0x20
+ RTF_MPLSOPS = 0x1000000
+ RTF_MULTICAST = 0x800000
+ RTF_PINNED = 0x100000
+ RTF_PRCLONING = 0x10000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x40000
+ RTF_REJECT = 0x8
+ RTF_STATIC = 0x800
+ RTF_UP = 0x1
+ RTF_WASCLONED = 0x20000
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DELMADDR = 0x10
+ RTM_GET = 0x4
+ RTM_IEEE80211 = 0x12
+ RTM_IFANNOUNCE = 0x11
+ RTM_IFINFO = 0xe
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_NEWMADDR = 0xf
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x6
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_IWCAPSEGS = 0x400
+ RTV_IWMAXSEGS = 0x200
+ RTV_MSL = 0x100
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ SCM_CREDS = 0x3
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x2
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCADDRT = 0x8040720a
+ SIOCAIFADDR = 0x8040691a
+ SIOCALIFADDR = 0x8118691b
+ SIOCATMARK = 0x40047307
+ SIOCDELMULTI = 0x80206932
+ SIOCDELRT = 0x8040720b
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFPHYADDR = 0x80206949
+ SIOCDLIFADDR = 0x8118691d
+ SIOCGDRVSPEC = 0xc028697b
+ SIOCGETSGCNT = 0xc0207210
+ SIOCGETVIFCNT = 0xc028720f
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCAP = 0xc020691f
+ SIOCGIFCONF = 0xc0106924
+ SIOCGIFDATA = 0xc0206926
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFGMEMB = 0xc028698a
+ SIOCGIFINDEX = 0xc0206920
+ SIOCGIFMEDIA = 0xc0306938
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc0206933
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206948
+ SIOCGIFPHYS = 0xc0206935
+ SIOCGIFPOLLCPU = 0xc020697e
+ SIOCGIFPSRCADDR = 0xc0206947
+ SIOCGIFSTATUS = 0xc331693b
+ SIOCGIFTSOLEN = 0xc0206980
+ SIOCGLIFADDR = 0xc118691c
+ SIOCGLIFPHYADDR = 0xc118694b
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCGPRIVATE_0 = 0xc0206950
+ SIOCGPRIVATE_1 = 0xc0206951
+ SIOCIFCREATE = 0xc020697a
+ SIOCIFCREATE2 = 0xc020697c
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc0106978
+ SIOCSDRVSPEC = 0x8028697b
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFCAP = 0x8020691e
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFLLADDR = 0x8020693c
+ SIOCSIFMEDIA = 0xc0206937
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x80206934
+ SIOCSIFNAME = 0x80206928
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x80406946
+ SIOCSIFPHYS = 0x80206936
+ SIOCSIFPOLLCPU = 0x8020697d
+ SIOCSIFTSOLEN = 0x8020697f
+ SIOCSLIFPHYADDR = 0x8118694a
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SOCK_CLOEXEC = 0x10000000
+ SOCK_DGRAM = 0x2
+ SOCK_MAXADDRLEN = 0xff
+ SOCK_NONBLOCK = 0x20000000
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_ACCEPTFILTER = 0x1000
+ SO_BROADCAST = 0x20
+ SO_CPUHINT = 0x1030
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LINGER = 0x80
+ SO_NOSIGPIPE = 0x800
+ SO_OOBINLINE = 0x100
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDSPACE = 0x100a
+ SO_SNDTIMEO = 0x1005
+ SO_TIMESTAMP = 0x400
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ TCIFLUSH = 0x1
+ TCIOFF = 0x3
+ TCIOFLUSH = 0x3
+ TCION = 0x4
+ TCOFLUSH = 0x2
+ TCOOFF = 0x1
+ TCOON = 0x2
+ TCP_FASTKEEP = 0x80
+ TCP_KEEPCNT = 0x400
+ TCP_KEEPIDLE = 0x100
+ TCP_KEEPINIT = 0x20
+ TCP_KEEPINTVL = 0x200
+ TCP_MAXBURST = 0x4
+ TCP_MAXHLEN = 0x3c
+ TCP_MAXOLEN = 0x28
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MINMSS = 0x100
+ TCP_MIN_WINSHIFT = 0x5
+ TCP_MSS = 0x200
+ TCP_NODELAY = 0x1
+ TCP_NOOPT = 0x8
+ TCP_NOPUSH = 0x4
+ TCP_SIGNATURE_ENABLE = 0x10
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDCDTIMESTAMP = 0x40107458
+ TIOCDRAIN = 0x2000745e
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLUSH = 0x80047410
+ TIOCGDRAINWAIT = 0x40047456
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGPGRP = 0x40047477
+ TIOCGSID = 0x40047463
+ TIOCGSIZE = 0x40087468
+ TIOCGWINSZ = 0x40087468
+ TIOCISPTMASTER = 0x20007455
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGDTRWAIT = 0x4004745a
+ TIOCMGET = 0x4004746a
+ TIOCMODG = 0x40047403
+ TIOCMODS = 0x80047404
+ TIOCMSDTRWAIT = 0x8004745b
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCTTY = 0x20007461
+ TIOCSDRAINWAIT = 0x80047457
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSIG = 0x2000745f
+ TIOCSPGRP = 0x80047476
+ TIOCSSIZE = 0x80087467
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x20007465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCTIMESTAMP = 0x40107459
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VCHECKPT = 0x13
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VERASE2 = 0x7
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VM_BCACHE_SIZE_MAX = 0x0
+ VM_SWZONE_SIZE_MAX = 0x4000000000
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VTIME = 0x11
+ VWERASE = 0x4
+ WCONTINUED = 0x4
+ WCOREFLAG = 0x80
+ WLINUXCLONE = 0x80000000
+ WNOHANG = 0x1
+ WSTOPPED = 0x7f
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EASYNC = syscall.Errno(0x63)
+ EAUTH = syscall.Errno(0x50)
+ EBADF = syscall.Errno(0x9)
+ EBADMSG = syscall.Errno(0x59)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x55)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDOOFUS = syscall.Errno(0x58)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x52)
+ EILSEQ = syscall.Errno(0x56)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x63)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5a)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x57)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x5b)
+ ENOMEDIUM = syscall.Errno(0x5d)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x53)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x2d)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x54)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x5c)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUNUSED94 = syscall.Errno(0x5e)
+ EUNUSED95 = syscall.Errno(0x5f)
+ EUNUSED96 = syscall.Errno(0x60)
+ EUNUSED97 = syscall.Errno(0x61)
+ EUNUSED98 = syscall.Errno(0x62)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCKPT = syscall.Signal(0x21)
+ SIGCKPTEXIT = syscall.Signal(0x22)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTHR = syscall.Signal(0x20)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "operation timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "identifier removed",
+ 83: "no message of desired type",
+ 84: "value too large to be stored in data type",
+ 85: "operation canceled",
+ 86: "illegal byte sequence",
+ 87: "attribute not found",
+ 88: "programming error",
+ 89: "bad message",
+ 90: "multihop attempted",
+ 91: "link has been severed",
+ 92: "protocol error",
+ 93: "no medium found",
+ 94: "unknown error: 94",
+ 95: "unknown error: 95",
+ 96: "unknown error: 96",
+ 97: "unknown error: 97",
+ 98: "unknown error: 98",
+ 99: "unknown error: 99",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "suspended (signal)",
+ 18: "suspended",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+ 32: "thread Scheduler",
+ 33: "checkPoint",
+ 34: "checkPointExit",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go
new file mode 100644
index 0000000..1d3eec4
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go
@@ -0,0 +1,1706 @@
+// mkerrors.sh -m32
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build 386,freebsd
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m32 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_ARP = 0x23
+ AF_ATM = 0x1e
+ AF_BLUETOOTH = 0x24
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1a
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x25
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x1c
+ AF_INET6_SDP = 0x2a
+ AF_INET_SDP = 0x28
+ AF_IPX = 0x17
+ AF_ISDN = 0x1a
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x2a
+ AF_NATM = 0x1d
+ AF_NETBIOS = 0x6
+ AF_NETGRAPH = 0x20
+ AF_OSI = 0x7
+ AF_PUP = 0x4
+ AF_ROUTE = 0x11
+ AF_SCLUSTER = 0x22
+ AF_SIP = 0x18
+ AF_SLOW = 0x21
+ AF_SNA = 0xb
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ AF_VENDOR00 = 0x27
+ AF_VENDOR01 = 0x29
+ AF_VENDOR02 = 0x2b
+ AF_VENDOR03 = 0x2d
+ AF_VENDOR04 = 0x2f
+ AF_VENDOR05 = 0x31
+ AF_VENDOR06 = 0x33
+ AF_VENDOR07 = 0x35
+ AF_VENDOR08 = 0x37
+ AF_VENDOR09 = 0x39
+ AF_VENDOR10 = 0x3b
+ AF_VENDOR11 = 0x3d
+ AF_VENDOR12 = 0x3f
+ AF_VENDOR13 = 0x41
+ AF_VENDOR14 = 0x43
+ AF_VENDOR15 = 0x45
+ AF_VENDOR16 = 0x47
+ AF_VENDOR17 = 0x49
+ AF_VENDOR18 = 0x4b
+ AF_VENDOR19 = 0x4d
+ AF_VENDOR20 = 0x4f
+ AF_VENDOR21 = 0x51
+ AF_VENDOR22 = 0x53
+ AF_VENDOR23 = 0x55
+ AF_VENDOR24 = 0x57
+ AF_VENDOR25 = 0x59
+ AF_VENDOR26 = 0x5b
+ AF_VENDOR27 = 0x5d
+ AF_VENDOR28 = 0x5f
+ AF_VENDOR29 = 0x61
+ AF_VENDOR30 = 0x63
+ AF_VENDOR31 = 0x65
+ AF_VENDOR32 = 0x67
+ AF_VENDOR33 = 0x69
+ AF_VENDOR34 = 0x6b
+ AF_VENDOR35 = 0x6d
+ AF_VENDOR36 = 0x6f
+ AF_VENDOR37 = 0x71
+ AF_VENDOR38 = 0x73
+ AF_VENDOR39 = 0x75
+ AF_VENDOR40 = 0x77
+ AF_VENDOR41 = 0x79
+ AF_VENDOR42 = 0x7b
+ AF_VENDOR43 = 0x7d
+ AF_VENDOR44 = 0x7f
+ AF_VENDOR45 = 0x81
+ AF_VENDOR46 = 0x83
+ AF_VENDOR47 = 0x85
+ ALTWERASE = 0x200
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B460800 = 0x70800
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B921600 = 0xe1000
+ B9600 = 0x2580
+ BIOCFEEDBACK = 0x8004427c
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDIRECTION = 0x40044276
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc0084279
+ BIOCGETBUFMODE = 0x4004427d
+ BIOCGETIF = 0x4020426b
+ BIOCGETZMAX = 0x4004427f
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044272
+ BIOCGRTIMEOUT = 0x4008426e
+ BIOCGSEESENT = 0x40044276
+ BIOCGSTATS = 0x4008426f
+ BIOCGTSTAMP = 0x40044283
+ BIOCIMMEDIATE = 0x80044270
+ BIOCLOCK = 0x2000427a
+ BIOCPROMISC = 0x20004269
+ BIOCROTZBUF = 0x400c4280
+ BIOCSBLEN = 0xc0044266
+ BIOCSDIRECTION = 0x80044277
+ BIOCSDLT = 0x80044278
+ BIOCSETBUFMODE = 0x8004427e
+ BIOCSETF = 0x80084267
+ BIOCSETFNR = 0x80084282
+ BIOCSETIF = 0x8020426c
+ BIOCSETWF = 0x8008427b
+ BIOCSETZBUF = 0x800c4281
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044273
+ BIOCSRTIMEOUT = 0x8008426d
+ BIOCSSEESENT = 0x80044277
+ BIOCSTSTAMP = 0x80044284
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_BUFMODE_BUFFER = 0x1
+ BPF_BUFMODE_ZBUF = 0x2
+ 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_MAXBUFSIZE = 0x80000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MOD = 0x90
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ BPF_RET = 0x6
+ BPF_RSH = 0x70
+ BPF_ST = 0x2
+ BPF_STX = 0x3
+ BPF_SUB = 0x10
+ BPF_TAX = 0x0
+ BPF_TXA = 0x80
+ BPF_T_BINTIME = 0x2
+ BPF_T_BINTIME_FAST = 0x102
+ BPF_T_BINTIME_MONOTONIC = 0x202
+ BPF_T_BINTIME_MONOTONIC_FAST = 0x302
+ BPF_T_FAST = 0x100
+ BPF_T_FLAG_MASK = 0x300
+ BPF_T_FORMAT_MASK = 0x3
+ BPF_T_MICROTIME = 0x0
+ BPF_T_MICROTIME_FAST = 0x100
+ BPF_T_MICROTIME_MONOTONIC = 0x200
+ BPF_T_MICROTIME_MONOTONIC_FAST = 0x300
+ BPF_T_MONOTONIC = 0x200
+ BPF_T_MONOTONIC_FAST = 0x300
+ BPF_T_NANOTIME = 0x1
+ BPF_T_NANOTIME_FAST = 0x101
+ BPF_T_NANOTIME_MONOTONIC = 0x201
+ BPF_T_NANOTIME_MONOTONIC_FAST = 0x301
+ BPF_T_NONE = 0x3
+ BPF_T_NORMAL = 0x0
+ BPF_W = 0x0
+ BPF_X = 0x8
+ BPF_XOR = 0xa0
+ BRKINT = 0x2
+ CAP_ACCEPT = 0x200000020000000
+ CAP_ACL_CHECK = 0x400000000010000
+ CAP_ACL_DELETE = 0x400000000020000
+ CAP_ACL_GET = 0x400000000040000
+ CAP_ACL_SET = 0x400000000080000
+ CAP_ALL0 = 0x20007ffffffffff
+ CAP_ALL1 = 0x4000000001fffff
+ CAP_BIND = 0x200000040000000
+ CAP_BINDAT = 0x200008000000400
+ CAP_CHFLAGSAT = 0x200000000001400
+ CAP_CONNECT = 0x200000080000000
+ CAP_CONNECTAT = 0x200010000000400
+ CAP_CREATE = 0x200000000000040
+ CAP_EVENT = 0x400000000000020
+ CAP_EXTATTR_DELETE = 0x400000000001000
+ CAP_EXTATTR_GET = 0x400000000002000
+ CAP_EXTATTR_LIST = 0x400000000004000
+ CAP_EXTATTR_SET = 0x400000000008000
+ CAP_FCHDIR = 0x200000000000800
+ CAP_FCHFLAGS = 0x200000000001000
+ CAP_FCHMOD = 0x200000000002000
+ CAP_FCHMODAT = 0x200000000002400
+ CAP_FCHOWN = 0x200000000004000
+ CAP_FCHOWNAT = 0x200000000004400
+ CAP_FCNTL = 0x200000000008000
+ CAP_FCNTL_ALL = 0x78
+ CAP_FCNTL_GETFL = 0x8
+ CAP_FCNTL_GETOWN = 0x20
+ CAP_FCNTL_SETFL = 0x10
+ CAP_FCNTL_SETOWN = 0x40
+ CAP_FEXECVE = 0x200000000000080
+ CAP_FLOCK = 0x200000000010000
+ CAP_FPATHCONF = 0x200000000020000
+ CAP_FSCK = 0x200000000040000
+ CAP_FSTAT = 0x200000000080000
+ CAP_FSTATAT = 0x200000000080400
+ CAP_FSTATFS = 0x200000000100000
+ CAP_FSYNC = 0x200000000000100
+ CAP_FTRUNCATE = 0x200000000000200
+ CAP_FUTIMES = 0x200000000200000
+ CAP_FUTIMESAT = 0x200000000200400
+ CAP_GETPEERNAME = 0x200000100000000
+ CAP_GETSOCKNAME = 0x200000200000000
+ CAP_GETSOCKOPT = 0x200000400000000
+ CAP_IOCTL = 0x400000000000080
+ CAP_IOCTLS_ALL = 0x7fffffff
+ CAP_KQUEUE = 0x400000000100040
+ CAP_KQUEUE_CHANGE = 0x400000000100000
+ CAP_KQUEUE_EVENT = 0x400000000000040
+ CAP_LINKAT_SOURCE = 0x200020000000400
+ CAP_LINKAT_TARGET = 0x200000000400400
+ CAP_LISTEN = 0x200000800000000
+ CAP_LOOKUP = 0x200000000000400
+ CAP_MAC_GET = 0x400000000000001
+ CAP_MAC_SET = 0x400000000000002
+ CAP_MKDIRAT = 0x200000000800400
+ CAP_MKFIFOAT = 0x200000001000400
+ CAP_MKNODAT = 0x200000002000400
+ CAP_MMAP = 0x200000000000010
+ CAP_MMAP_R = 0x20000000000001d
+ CAP_MMAP_RW = 0x20000000000001f
+ CAP_MMAP_RWX = 0x20000000000003f
+ CAP_MMAP_RX = 0x20000000000003d
+ CAP_MMAP_W = 0x20000000000001e
+ CAP_MMAP_WX = 0x20000000000003e
+ CAP_MMAP_X = 0x20000000000003c
+ CAP_PDGETPID = 0x400000000000200
+ CAP_PDKILL = 0x400000000000800
+ CAP_PDWAIT = 0x400000000000400
+ CAP_PEELOFF = 0x200001000000000
+ CAP_POLL_EVENT = 0x400000000000020
+ CAP_PREAD = 0x20000000000000d
+ CAP_PWRITE = 0x20000000000000e
+ CAP_READ = 0x200000000000001
+ CAP_RECV = 0x200000000000001
+ CAP_RENAMEAT_SOURCE = 0x200000004000400
+ CAP_RENAMEAT_TARGET = 0x200040000000400
+ CAP_RIGHTS_VERSION = 0x0
+ CAP_RIGHTS_VERSION_00 = 0x0
+ CAP_SEEK = 0x20000000000000c
+ CAP_SEEK_TELL = 0x200000000000004
+ CAP_SEM_GETVALUE = 0x400000000000004
+ CAP_SEM_POST = 0x400000000000008
+ CAP_SEM_WAIT = 0x400000000000010
+ CAP_SEND = 0x200000000000002
+ CAP_SETSOCKOPT = 0x200002000000000
+ CAP_SHUTDOWN = 0x200004000000000
+ CAP_SOCK_CLIENT = 0x200007780000003
+ CAP_SOCK_SERVER = 0x200007f60000003
+ CAP_SYMLINKAT = 0x200000008000400
+ CAP_TTYHOOK = 0x400000000000100
+ CAP_UNLINKAT = 0x200000010000400
+ CAP_UNUSED0_44 = 0x200080000000000
+ CAP_UNUSED0_57 = 0x300000000000000
+ CAP_UNUSED1_22 = 0x400000000200000
+ CAP_UNUSED1_57 = 0x500000000000000
+ CAP_WRITE = 0x200000000000002
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CLOCK_MONOTONIC = 0x4
+ CLOCK_MONOTONIC_FAST = 0xc
+ CLOCK_MONOTONIC_PRECISE = 0xb
+ CLOCK_PROCESS_CPUTIME_ID = 0xf
+ CLOCK_PROF = 0x2
+ CLOCK_REALTIME = 0x0
+ CLOCK_REALTIME_FAST = 0xa
+ CLOCK_REALTIME_PRECISE = 0x9
+ CLOCK_SECOND = 0xd
+ CLOCK_THREAD_CPUTIME_ID = 0xe
+ CLOCK_UPTIME = 0x5
+ CLOCK_UPTIME_FAST = 0x8
+ CLOCK_UPTIME_PRECISE = 0x7
+ CLOCK_VIRTUAL = 0x1
+ CREAD = 0x800
+ CRTSCTS = 0x30000
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0x18
+ CTL_NET = 0x4
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_AOS = 0xde
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_BREDR_BB = 0xff
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_BLUETOOTH_LE_LL = 0xfb
+ DLT_BLUETOOTH_LE_LL_WITH_PHDR = 0x100
+ DLT_BLUETOOTH_LINUX_MONITOR = 0xfe
+ DLT_CAN20B = 0xbe
+ DLT_CAN_SOCKETCAN = 0xe3
+ DLT_CHAOS = 0x5
+ DLT_CHDLC = 0x68
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DBUS = 0xe7
+ DLT_DECT = 0xdd
+ DLT_DOCSIS = 0x8f
+ DLT_DVB_CI = 0xeb
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_EPON = 0x103
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FC_2 = 0xe0
+ DLT_FC_2_WITH_FRAME_DELIMS = 0xe1
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_GSMTAP_ABIS = 0xda
+ DLT_GSMTAP_UM = 0xd9
+ DLT_HHDLC = 0x79
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NOFCS = 0xe6
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_INFINIBAND = 0xf7
+ DLT_IPFILTER = 0x74
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IPMI_HPM_2 = 0x104
+ DLT_IPNET = 0xe2
+ DLT_IPOIB = 0xf2
+ DLT_IPV4 = 0xe4
+ DLT_IPV6 = 0xe5
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_ATM_CEMIC = 0xee
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FIBRECHANNEL = 0xea
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_SRX_E2E = 0xe9
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_JUNIPER_VS = 0xe8
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_EVDEV = 0xd8
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_PPP_WITHDIRECTION = 0xa6
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MATCHING_MAX = 0x104
+ DLT_MATCHING_MIN = 0x68
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MPEG_2_TS = 0xf3
+ DLT_MPLS = 0xdb
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_MUX27010 = 0xec
+ DLT_NETANALYZER = 0xf0
+ DLT_NETANALYZER_TRANSPARENT = 0xf1
+ DLT_NETLINK = 0xfd
+ DLT_NFC_LLCP = 0xf5
+ DLT_NFLOG = 0xef
+ DLT_NG40 = 0xf4
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x79
+ DLT_PKTAP = 0x102
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0x10
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PPP_WITH_DIRECTION = 0xa6
+ DLT_PRISM_HEADER = 0x77
+ DLT_PROFIBUS_DL = 0x101
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_RIO = 0x7c
+ DLT_RTAC_SERIAL = 0xfa
+ DLT_SCCP = 0x8e
+ DLT_SCTP = 0xf8
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xf
+ DLT_STANAG_5066_D_PDU = 0xed
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USBPCAP = 0xf9
+ DLT_USB_LINUX = 0xbd
+ DLT_USB_LINUX_MMAPPED = 0xdc
+ DLT_USER0 = 0x93
+ DLT_USER1 = 0x94
+ DLT_USER10 = 0x9d
+ DLT_USER11 = 0x9e
+ DLT_USER12 = 0x9f
+ DLT_USER13 = 0xa0
+ DLT_USER14 = 0xa1
+ DLT_USER15 = 0xa2
+ DLT_USER2 = 0x95
+ DLT_USER3 = 0x96
+ DLT_USER4 = 0x97
+ DLT_USER5 = 0x98
+ DLT_USER6 = 0x99
+ DLT_USER7 = 0x9a
+ DLT_USER8 = 0x9b
+ DLT_USER9 = 0x9c
+ DLT_WIHART = 0xdf
+ DLT_WIRESHARK_UPPER_PDU = 0xfc
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EVFILT_AIO = -0x3
+ EVFILT_FS = -0x9
+ EVFILT_LIO = -0xa
+ EVFILT_PROC = -0x5
+ EVFILT_PROCDESC = -0x8
+ EVFILT_READ = -0x1
+ EVFILT_SENDFILE = -0xc
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0xc
+ EVFILT_TIMER = -0x7
+ EVFILT_USER = -0xb
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_DISPATCH = 0x80
+ EV_DROP = 0x1000
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG1 = 0x2000
+ EV_FLAG2 = 0x4000
+ EV_FORCEONESHOT = 0x100
+ EV_ONESHOT = 0x10
+ EV_RECEIPT = 0x40
+ EV_SYSFLAGS = 0xf000
+ EXTA = 0x4b00
+ EXTATTR_NAMESPACE_EMPTY = 0x0
+ EXTATTR_NAMESPACE_SYSTEM = 0x2
+ EXTATTR_NAMESPACE_USER = 0x1
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FLUSHO = 0x800000
+ F_CANCEL = 0x5
+ F_DUP2FD = 0xa
+ F_DUP2FD_CLOEXEC = 0x12
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x11
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0xb
+ F_GETOWN = 0x5
+ F_OGETLK = 0x7
+ F_OK = 0x0
+ F_OSETLK = 0x8
+ F_OSETLKW = 0x9
+ F_RDAHEAD = 0x10
+ F_RDLCK = 0x1
+ F_READAHEAD = 0xf
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0xc
+ F_SETLKW = 0xd
+ F_SETLK_REMOTE = 0xe
+ F_SETOWN = 0x6
+ F_UNLCK = 0x2
+ F_UNLCKSYS = 0x4
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFAN_ARRIVAL = 0x0
+ IFAN_DEPARTURE = 0x1
+ IFF_ALLMULTI = 0x200
+ IFF_ALTPHYS = 0x4000
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x218f52
+ IFF_CANTCONFIG = 0x10000
+ IFF_DEBUG = 0x4
+ IFF_DRV_OACTIVE = 0x400
+ IFF_DRV_RUNNING = 0x40
+ IFF_DYING = 0x200000
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MONITOR = 0x40000
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PPROMISC = 0x20000
+ IFF_PROMISC = 0x100
+ IFF_RENAMING = 0x400000
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_STATICARP = 0x80000
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_BRIDGE = 0xd1
+ IFT_CARP = 0xf8
+ IFT_IEEE1394 = 0x90
+ IFT_INFINIBAND = 0xc7
+ IFT_L2VLAN = 0x87
+ IFT_L3IPVLAN = 0x88
+ IFT_PPP = 0x17
+ IFT_PROPVIRTUAL = 0x35
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LOOPBACKNET = 0x7f
+ IN_RFC3021_MASK = 0xfffffffe
+ IPPROTO_3PC = 0x22
+ IPPROTO_ADFS = 0x44
+ IPPROTO_AH = 0x33
+ IPPROTO_AHIP = 0x3d
+ IPPROTO_APES = 0x63
+ IPPROTO_ARGUS = 0xd
+ IPPROTO_AX25 = 0x5d
+ IPPROTO_BHA = 0x31
+ IPPROTO_BLT = 0x1e
+ IPPROTO_BRSATMON = 0x4c
+ IPPROTO_CARP = 0x70
+ IPPROTO_CFTP = 0x3e
+ IPPROTO_CHAOS = 0x10
+ IPPROTO_CMTP = 0x26
+ IPPROTO_CPHB = 0x49
+ IPPROTO_CPNX = 0x48
+ IPPROTO_DDP = 0x25
+ IPPROTO_DGP = 0x56
+ IPPROTO_DIVERT = 0x102
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_EMCON = 0xe
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GMTP = 0x64
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HELLO = 0x3f
+ IPPROTO_HIP = 0x8b
+ IPPROTO_HMP = 0x14
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IDPR = 0x23
+ IPPROTO_IDRP = 0x2d
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IGP = 0x55
+ IPPROTO_IGRP = 0x58
+ IPPROTO_IL = 0x28
+ IPPROTO_INLSP = 0x34
+ IPPROTO_INP = 0x20
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPCV = 0x47
+ IPPROTO_IPEIP = 0x5e
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPPC = 0x43
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IRTP = 0x1c
+ IPPROTO_KRYPTOLAN = 0x41
+ IPPROTO_LARP = 0x5b
+ IPPROTO_LEAF1 = 0x19
+ IPPROTO_LEAF2 = 0x1a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MEAS = 0x13
+ IPPROTO_MH = 0x87
+ IPPROTO_MHRP = 0x30
+ IPPROTO_MICP = 0x5f
+ IPPROTO_MOBILE = 0x37
+ IPPROTO_MPLS = 0x89
+ IPPROTO_MTP = 0x5c
+ IPPROTO_MUX = 0x12
+ IPPROTO_ND = 0x4d
+ IPPROTO_NHRP = 0x36
+ IPPROTO_NONE = 0x3b
+ IPPROTO_NSP = 0x1f
+ IPPROTO_NVPII = 0xb
+ IPPROTO_OLD_DIVERT = 0xfe
+ IPPROTO_OSPFIGP = 0x59
+ IPPROTO_PFSYNC = 0xf0
+ IPPROTO_PGM = 0x71
+ IPPROTO_PIGP = 0x9
+ IPPROTO_PIM = 0x67
+ IPPROTO_PRM = 0x15
+ IPPROTO_PUP = 0xc
+ IPPROTO_PVP = 0x4b
+ IPPROTO_RAW = 0xff
+ IPPROTO_RCCMON = 0xa
+ IPPROTO_RDP = 0x1b
+ IPPROTO_RESERVED_253 = 0xfd
+ IPPROTO_RESERVED_254 = 0xfe
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_RVD = 0x42
+ IPPROTO_SATEXPAK = 0x40
+ IPPROTO_SATMON = 0x45
+ IPPROTO_SCCSP = 0x60
+ IPPROTO_SCTP = 0x84
+ IPPROTO_SDRP = 0x2a
+ IPPROTO_SEND = 0x103
+ IPPROTO_SEP = 0x21
+ IPPROTO_SHIM6 = 0x8c
+ IPPROTO_SKIP = 0x39
+ IPPROTO_SPACER = 0x7fff
+ IPPROTO_SRPC = 0x5a
+ IPPROTO_ST = 0x7
+ IPPROTO_SVMTP = 0x52
+ IPPROTO_SWIPE = 0x35
+ IPPROTO_TCF = 0x57
+ IPPROTO_TCP = 0x6
+ IPPROTO_TLSP = 0x38
+ IPPROTO_TP = 0x1d
+ IPPROTO_TPXX = 0x27
+ IPPROTO_TRUNK1 = 0x17
+ IPPROTO_TRUNK2 = 0x18
+ IPPROTO_TTP = 0x54
+ IPPROTO_UDP = 0x11
+ IPPROTO_UDPLITE = 0x88
+ IPPROTO_VINES = 0x53
+ IPPROTO_VISA = 0x46
+ IPPROTO_VMTP = 0x51
+ IPPROTO_WBEXPAK = 0x4f
+ IPPROTO_WBMON = 0x4e
+ IPPROTO_WSN = 0x4a
+ IPPROTO_XNET = 0xf
+ IPPROTO_XTP = 0x24
+ IPV6_AUTOFLOWLABEL = 0x3b
+ IPV6_BINDANY = 0x40
+ IPV6_BINDMULTI = 0x41
+ IPV6_BINDV6ONLY = 0x1b
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_DONTFRAG = 0x3e
+ IPV6_DSTOPTS = 0x32
+ IPV6_FLOWID = 0x43
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FLOWTYPE = 0x44
+ IPV6_FRAGTTL = 0x78
+ IPV6_FW_ADD = 0x1e
+ IPV6_FW_DEL = 0x1f
+ IPV6_FW_FLUSH = 0x20
+ IPV6_FW_GET = 0x22
+ IPV6_FW_ZERO = 0x21
+ IPV6_HLIMDEC = 0x1
+ IPV6_HOPLIMIT = 0x2f
+ IPV6_HOPOPTS = 0x31
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXOPTHDR = 0x800
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MAX_GROUP_SRC_FILTER = 0x200
+ IPV6_MAX_MEMBERSHIPS = 0xfff
+ IPV6_MAX_SOCK_SRC_FILTER = 0x80
+ IPV6_MIN_MEMBERSHIPS = 0x1f
+ IPV6_MMTU = 0x500
+ IPV6_MSFILTER = 0x4a
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_NEXTHOP = 0x30
+ IPV6_PATHMTU = 0x2c
+ IPV6_PKTINFO = 0x2e
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_PREFER_TEMPADDR = 0x3f
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVFLOWID = 0x46
+ IPV6_RECVHOPLIMIT = 0x25
+ IPV6_RECVHOPOPTS = 0x27
+ IPV6_RECVPATHMTU = 0x2b
+ IPV6_RECVPKTINFO = 0x24
+ IPV6_RECVRSSBUCKETID = 0x47
+ IPV6_RECVRTHDR = 0x26
+ IPV6_RECVTCLASS = 0x39
+ IPV6_RSSBUCKETID = 0x45
+ IPV6_RSS_LISTEN_BUCKET = 0x42
+ IPV6_RTHDR = 0x33
+ IPV6_RTHDRDSTOPTS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x3d
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_USE_MIN_MTU = 0x2a
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_ADD_SOURCE_MEMBERSHIP = 0x46
+ IP_BINDANY = 0x18
+ IP_BINDMULTI = 0x19
+ IP_BLOCK_SOURCE = 0x48
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DONTFRAG = 0x43
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_DROP_SOURCE_MEMBERSHIP = 0x47
+ IP_DUMMYNET3 = 0x31
+ IP_DUMMYNET_CONFIGURE = 0x3c
+ IP_DUMMYNET_DEL = 0x3d
+ IP_DUMMYNET_FLUSH = 0x3e
+ IP_DUMMYNET_GET = 0x40
+ IP_FLOWID = 0x5a
+ IP_FLOWTYPE = 0x5b
+ IP_FW3 = 0x30
+ IP_FW_ADD = 0x32
+ IP_FW_DEL = 0x33
+ IP_FW_FLUSH = 0x34
+ IP_FW_GET = 0x36
+ IP_FW_NAT_CFG = 0x38
+ IP_FW_NAT_DEL = 0x39
+ IP_FW_NAT_GET_CONFIG = 0x3a
+ IP_FW_NAT_GET_LOG = 0x3b
+ IP_FW_RESETLOG = 0x37
+ IP_FW_TABLE_ADD = 0x28
+ IP_FW_TABLE_DEL = 0x29
+ IP_FW_TABLE_FLUSH = 0x2a
+ IP_FW_TABLE_GETSIZE = 0x2b
+ IP_FW_TABLE_LIST = 0x2c
+ IP_FW_ZERO = 0x35
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x15
+ IP_MAXPACKET = 0xffff
+ IP_MAX_GROUP_SRC_FILTER = 0x200
+ IP_MAX_MEMBERSHIPS = 0xfff
+ IP_MAX_SOCK_MUTE_FILTER = 0x80
+ IP_MAX_SOCK_SRC_FILTER = 0x80
+ IP_MAX_SOURCE_FILTER = 0x400
+ IP_MF = 0x2000
+ IP_MINTTL = 0x42
+ IP_MIN_MEMBERSHIPS = 0x1f
+ IP_MSFILTER = 0x4a
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_MULTICAST_VIF = 0xe
+ IP_OFFMASK = 0x1fff
+ IP_ONESBCAST = 0x17
+ IP_OPTIONS = 0x1
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVFLOWID = 0x5d
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVRETOPTS = 0x6
+ IP_RECVRSSBUCKETID = 0x5e
+ IP_RECVTOS = 0x44
+ IP_RECVTTL = 0x41
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RSSBUCKETID = 0x5c
+ IP_RSS_LISTEN_BUCKET = 0x1a
+ IP_RSVP_OFF = 0x10
+ IP_RSVP_ON = 0xf
+ IP_RSVP_VIF_OFF = 0x12
+ IP_RSVP_VIF_ON = 0x11
+ IP_SENDSRCADDR = 0x7
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ IP_UNBLOCK_SOURCE = 0x49
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_AUTOSYNC = 0x7
+ MADV_CORE = 0x9
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x5
+ MADV_NOCORE = 0x8
+ MADV_NORMAL = 0x0
+ MADV_NOSYNC = 0x6
+ MADV_PROTECT = 0xa
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_WILLNEED = 0x3
+ MAP_ALIGNED_SUPER = 0x1000000
+ MAP_ALIGNMENT_MASK = -0x1000000
+ MAP_ALIGNMENT_SHIFT = 0x18
+ MAP_ANON = 0x1000
+ MAP_ANONYMOUS = 0x1000
+ MAP_COPY = 0x2
+ MAP_EXCL = 0x4000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_HASSEMAPHORE = 0x200
+ MAP_NOCORE = 0x20000
+ MAP_NOSYNC = 0x800
+ MAP_PREFAULT_READ = 0x40000
+ MAP_PRIVATE = 0x2
+ MAP_RESERVED0020 = 0x20
+ MAP_RESERVED0040 = 0x40
+ MAP_RESERVED0080 = 0x80
+ MAP_RESERVED0100 = 0x100
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x400
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MSG_CMSG_CLOEXEC = 0x40000
+ MSG_COMPAT = 0x8000
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOF = 0x100
+ MSG_EOR = 0x8
+ MSG_NBIO = 0x4000
+ MSG_NOSIGNAL = 0x20000
+ MSG_NOTIFICATION = 0x2000
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x10
+ MSG_WAITALL = 0x40
+ MSG_WAITFORONE = 0x80000
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x2
+ MS_SYNC = 0x0
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_IFLISTL = 0x5
+ NET_RT_IFMALIST = 0x4
+ NOFLSH = 0x80000000
+ NOKERNINFO = 0x2000000
+ NOTE_ATTRIB = 0x8
+ NOTE_CHILD = 0x4
+ NOTE_CLOSE = 0x100
+ NOTE_CLOSE_WRITE = 0x200
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXTEND = 0x4
+ NOTE_FFAND = 0x40000000
+ NOTE_FFCOPY = 0xc0000000
+ NOTE_FFCTRLMASK = 0xc0000000
+ NOTE_FFLAGSMASK = 0xffffff
+ NOTE_FFNOP = 0x0
+ NOTE_FFOR = 0x80000000
+ NOTE_FILE_POLL = 0x2
+ NOTE_FORK = 0x40000000
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_MSECONDS = 0x2
+ NOTE_NSECONDS = 0x8
+ NOTE_OPEN = 0x80
+ NOTE_PCTRLMASK = 0xf0000000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_READ = 0x400
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_SECONDS = 0x1
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRIGGER = 0x1000000
+ NOTE_USECONDS = 0x4
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ OXTABS = 0x4
+ O_ACCMODE = 0x3
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x100000
+ O_CREAT = 0x200
+ O_DIRECT = 0x10000
+ O_DIRECTORY = 0x20000
+ O_EXCL = 0x800
+ O_EXEC = 0x40000
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_SHLOCK = 0x10
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_TTY_INIT = 0x80000
+ O_VERIFY = 0x200000
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ RLIMIT_AS = 0xa
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_MEMLOCK = 0x6
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_NPROC = 0x7
+ RLIMIT_RSS = 0x5
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x8
+ RTAX_NETMASK = 0x2
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTF_BLACKHOLE = 0x1000
+ RTF_BROADCAST = 0x400000
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_FIXEDMTU = 0x80000
+ RTF_FMASK = 0x1004d808
+ RTF_GATEWAY = 0x2
+ RTF_GWFLAG_COMPAT = 0x80000000
+ RTF_HOST = 0x4
+ RTF_LLDATA = 0x400
+ RTF_LLINFO = 0x400
+ RTF_LOCAL = 0x200000
+ RTF_MODIFIED = 0x20
+ RTF_MULTICAST = 0x800000
+ RTF_PINNED = 0x100000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x40000
+ RTF_REJECT = 0x8
+ RTF_RNH_LOCKED = 0x40000000
+ RTF_STATIC = 0x800
+ RTF_STICKY = 0x10000000
+ RTF_UP = 0x1
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DELMADDR = 0x10
+ RTM_GET = 0x4
+ RTM_IEEE80211 = 0x12
+ RTM_IFANNOUNCE = 0x11
+ RTM_IFINFO = 0xe
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_NEWMADDR = 0xf
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x5
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RTV_WEIGHT = 0x100
+ RT_ALL_FIBS = -0x1
+ RT_BLACKHOLE = 0x40
+ RT_CACHING_CONTEXT = 0x1
+ RT_DEFAULT_FIB = 0x0
+ RT_HAS_GW = 0x80
+ RT_HAS_HEADER = 0x10
+ RT_HAS_HEADER_BIT = 0x4
+ RT_L2_ME = 0x4
+ RT_L2_ME_BIT = 0x2
+ RT_LLE_CACHE = 0x100
+ RT_MAY_LOOP = 0x8
+ RT_MAY_LOOP_BIT = 0x3
+ RT_NORTREF = 0x2
+ RT_REJECT = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ RUSAGE_THREAD = 0x1
+ SCM_BINTIME = 0x4
+ SCM_CREDS = 0x3
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x2
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCAIFADDR = 0x8040691a
+ SIOCAIFGROUP = 0x80246987
+ SIOCATMARK = 0x40047307
+ SIOCDELMULTI = 0x80206932
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFGROUP = 0x80246989
+ SIOCDIFPHYADDR = 0x80206949
+ SIOCGDRVSPEC = 0xc01c697b
+ SIOCGETSGCNT = 0xc0147210
+ SIOCGETVIFCNT = 0xc014720f
+ SIOCGHIWAT = 0x40047301
+ SIOCGI2C = 0xc020693d
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCAP = 0xc020691f
+ SIOCGIFCONF = 0xc0086924
+ SIOCGIFDESCR = 0xc020692a
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFIB = 0xc020695c
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFGMEMB = 0xc024698a
+ SIOCGIFGROUP = 0xc0246988
+ SIOCGIFINDEX = 0xc0206920
+ SIOCGIFMAC = 0xc0206926
+ SIOCGIFMEDIA = 0xc0286938
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc0206933
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206948
+ SIOCGIFPHYS = 0xc0206935
+ SIOCGIFPSRCADDR = 0xc0206947
+ SIOCGIFSTATUS = 0xc331693b
+ SIOCGIFXMEDIA = 0xc028698b
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCGPRIVATE_0 = 0xc0206950
+ SIOCGPRIVATE_1 = 0xc0206951
+ SIOCGTUNFIB = 0xc020695e
+ SIOCIFCREATE = 0xc020697a
+ SIOCIFCREATE2 = 0xc020697c
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc00c6978
+ SIOCSDRVSPEC = 0x801c697b
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFCAP = 0x8020691e
+ SIOCSIFDESCR = 0x80206929
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFIB = 0x8020695d
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFLLADDR = 0x8020693c
+ SIOCSIFMAC = 0x80206927
+ SIOCSIFMEDIA = 0xc0206937
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x80206934
+ SIOCSIFNAME = 0x80206928
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x80406946
+ SIOCSIFPHYS = 0x80206936
+ SIOCSIFRVNET = 0xc020695b
+ SIOCSIFVNET = 0xc020695a
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SIOCSTUNFIB = 0x8020695f
+ SOCK_CLOEXEC = 0x10000000
+ SOCK_DGRAM = 0x2
+ SOCK_MAXADDRLEN = 0xff
+ SOCK_NONBLOCK = 0x20000000
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_ACCEPTFILTER = 0x1000
+ SO_BINTIME = 0x2000
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LABEL = 0x1009
+ SO_LINGER = 0x80
+ SO_LISTENINCQLEN = 0x1013
+ SO_LISTENQLEN = 0x1012
+ SO_LISTENQLIMIT = 0x1011
+ SO_NOSIGPIPE = 0x800
+ SO_NO_DDP = 0x8000
+ SO_NO_OFFLOAD = 0x4000
+ SO_OOBINLINE = 0x100
+ SO_PEERLABEL = 0x1010
+ SO_PROTOCOL = 0x1016
+ SO_PROTOTYPE = 0x1016
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_SETFIB = 0x1014
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_TIMESTAMP = 0x400
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ SO_USER_COOKIE = 0x1015
+ SO_VENDOR = 0x80000000
+ TAB0 = 0x0
+ TAB3 = 0x4
+ TABDLY = 0x4
+ TCIFLUSH = 0x1
+ TCIOFF = 0x3
+ TCIOFLUSH = 0x3
+ TCION = 0x4
+ TCOFLUSH = 0x2
+ TCOOFF = 0x1
+ TCOON = 0x2
+ TCP_CA_NAME_MAX = 0x10
+ TCP_CCALGOOPT = 0x41
+ TCP_CONGESTION = 0x40
+ TCP_FASTOPEN = 0x401
+ TCP_FUNCTION_BLK = 0x2000
+ TCP_FUNCTION_NAME_LEN_MAX = 0x20
+ TCP_INFO = 0x20
+ TCP_KEEPCNT = 0x400
+ TCP_KEEPIDLE = 0x100
+ TCP_KEEPINIT = 0x80
+ TCP_KEEPINTVL = 0x200
+ TCP_MAXBURST = 0x4
+ TCP_MAXHLEN = 0x3c
+ TCP_MAXOLEN = 0x28
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_SACK = 0x4
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MD5SIG = 0x10
+ TCP_MINMSS = 0xd8
+ TCP_MSS = 0x218
+ TCP_NODELAY = 0x1
+ TCP_NOOPT = 0x8
+ TCP_NOPUSH = 0x4
+ TCP_PCAP_IN = 0x1000
+ TCP_PCAP_OUT = 0x800
+ TCP_VENDOR = 0x80000000
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDRAIN = 0x2000745e
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLUSH = 0x80047410
+ TIOCGDRAINWAIT = 0x40047456
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGPGRP = 0x40047477
+ TIOCGPTN = 0x4004740f
+ TIOCGSID = 0x40047463
+ TIOCGWINSZ = 0x40087468
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGDTRWAIT = 0x4004745a
+ TIOCMGET = 0x4004746a
+ TIOCMSDTRWAIT = 0x8004745b
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DCD = 0x40
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCPTMASTER = 0x2000741c
+ TIOCSBRK = 0x2000747b
+ TIOCSCTTY = 0x20007461
+ TIOCSDRAINWAIT = 0x80047457
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSIG = 0x2004745f
+ TIOCSPGRP = 0x80047476
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x20007465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCTIMESTAMP = 0x40087459
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VERASE2 = 0x7
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VTIME = 0x11
+ VWERASE = 0x4
+ WCONTINUED = 0x4
+ WCOREFLAG = 0x80
+ WEXITED = 0x10
+ WLINUXCLONE = 0x80000000
+ WNOHANG = 0x1
+ WNOWAIT = 0x8
+ WSTOPPED = 0x2
+ WTRAPPED = 0x20
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADF = syscall.Errno(0x9)
+ EBADMSG = syscall.Errno(0x59)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x55)
+ ECAPMODE = syscall.Errno(0x5e)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDOOFUS = syscall.Errno(0x58)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x52)
+ EILSEQ = syscall.Errno(0x56)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x60)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5a)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x57)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x5b)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x53)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCAPABLE = syscall.Errno(0x5d)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTRECOVERABLE = syscall.Errno(0x5f)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x2d)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x54)
+ EOWNERDEAD = syscall.Errno(0x60)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x5c)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGLIBRT = syscall.Signal(0x21)
+ SIGLWP = syscall.Signal(0x20)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTHR = syscall.Signal(0x20)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "operation timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "identifier removed",
+ 83: "no message of desired type",
+ 84: "value too large to be stored in data type",
+ 85: "operation canceled",
+ 86: "illegal byte sequence",
+ 87: "attribute not found",
+ 88: "programming error",
+ 89: "bad message",
+ 90: "multihop attempted",
+ 91: "link has been severed",
+ 92: "protocol error",
+ 93: "capabilities insufficient",
+ 94: "not permitted in capability mode",
+ 95: "state not recoverable",
+ 96: "previous owner died",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "suspended (signal)",
+ 18: "suspended",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+ 32: "unknown signal",
+ 33: "unknown signal",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go
new file mode 100644
index 0000000..ac094f9
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go
@@ -0,0 +1,1707 @@
+// mkerrors.sh -m64
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,freebsd
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m64 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_ARP = 0x23
+ AF_ATM = 0x1e
+ AF_BLUETOOTH = 0x24
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1a
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x25
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x1c
+ AF_INET6_SDP = 0x2a
+ AF_INET_SDP = 0x28
+ AF_IPX = 0x17
+ AF_ISDN = 0x1a
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x2a
+ AF_NATM = 0x1d
+ AF_NETBIOS = 0x6
+ AF_NETGRAPH = 0x20
+ AF_OSI = 0x7
+ AF_PUP = 0x4
+ AF_ROUTE = 0x11
+ AF_SCLUSTER = 0x22
+ AF_SIP = 0x18
+ AF_SLOW = 0x21
+ AF_SNA = 0xb
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ AF_VENDOR00 = 0x27
+ AF_VENDOR01 = 0x29
+ AF_VENDOR02 = 0x2b
+ AF_VENDOR03 = 0x2d
+ AF_VENDOR04 = 0x2f
+ AF_VENDOR05 = 0x31
+ AF_VENDOR06 = 0x33
+ AF_VENDOR07 = 0x35
+ AF_VENDOR08 = 0x37
+ AF_VENDOR09 = 0x39
+ AF_VENDOR10 = 0x3b
+ AF_VENDOR11 = 0x3d
+ AF_VENDOR12 = 0x3f
+ AF_VENDOR13 = 0x41
+ AF_VENDOR14 = 0x43
+ AF_VENDOR15 = 0x45
+ AF_VENDOR16 = 0x47
+ AF_VENDOR17 = 0x49
+ AF_VENDOR18 = 0x4b
+ AF_VENDOR19 = 0x4d
+ AF_VENDOR20 = 0x4f
+ AF_VENDOR21 = 0x51
+ AF_VENDOR22 = 0x53
+ AF_VENDOR23 = 0x55
+ AF_VENDOR24 = 0x57
+ AF_VENDOR25 = 0x59
+ AF_VENDOR26 = 0x5b
+ AF_VENDOR27 = 0x5d
+ AF_VENDOR28 = 0x5f
+ AF_VENDOR29 = 0x61
+ AF_VENDOR30 = 0x63
+ AF_VENDOR31 = 0x65
+ AF_VENDOR32 = 0x67
+ AF_VENDOR33 = 0x69
+ AF_VENDOR34 = 0x6b
+ AF_VENDOR35 = 0x6d
+ AF_VENDOR36 = 0x6f
+ AF_VENDOR37 = 0x71
+ AF_VENDOR38 = 0x73
+ AF_VENDOR39 = 0x75
+ AF_VENDOR40 = 0x77
+ AF_VENDOR41 = 0x79
+ AF_VENDOR42 = 0x7b
+ AF_VENDOR43 = 0x7d
+ AF_VENDOR44 = 0x7f
+ AF_VENDOR45 = 0x81
+ AF_VENDOR46 = 0x83
+ AF_VENDOR47 = 0x85
+ ALTWERASE = 0x200
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B460800 = 0x70800
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B921600 = 0xe1000
+ B9600 = 0x2580
+ BIOCFEEDBACK = 0x8004427c
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDIRECTION = 0x40044276
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc0104279
+ BIOCGETBUFMODE = 0x4004427d
+ BIOCGETIF = 0x4020426b
+ BIOCGETZMAX = 0x4008427f
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044272
+ BIOCGRTIMEOUT = 0x4010426e
+ BIOCGSEESENT = 0x40044276
+ BIOCGSTATS = 0x4008426f
+ BIOCGTSTAMP = 0x40044283
+ BIOCIMMEDIATE = 0x80044270
+ BIOCLOCK = 0x2000427a
+ BIOCPROMISC = 0x20004269
+ BIOCROTZBUF = 0x40184280
+ BIOCSBLEN = 0xc0044266
+ BIOCSDIRECTION = 0x80044277
+ BIOCSDLT = 0x80044278
+ BIOCSETBUFMODE = 0x8004427e
+ BIOCSETF = 0x80104267
+ BIOCSETFNR = 0x80104282
+ BIOCSETIF = 0x8020426c
+ BIOCSETWF = 0x8010427b
+ BIOCSETZBUF = 0x80184281
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044273
+ BIOCSRTIMEOUT = 0x8010426d
+ BIOCSSEESENT = 0x80044277
+ BIOCSTSTAMP = 0x80044284
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x8
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_BUFMODE_BUFFER = 0x1
+ BPF_BUFMODE_ZBUF = 0x2
+ 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_MAXBUFSIZE = 0x80000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MOD = 0x90
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ BPF_RET = 0x6
+ BPF_RSH = 0x70
+ BPF_ST = 0x2
+ BPF_STX = 0x3
+ BPF_SUB = 0x10
+ BPF_TAX = 0x0
+ BPF_TXA = 0x80
+ BPF_T_BINTIME = 0x2
+ BPF_T_BINTIME_FAST = 0x102
+ BPF_T_BINTIME_MONOTONIC = 0x202
+ BPF_T_BINTIME_MONOTONIC_FAST = 0x302
+ BPF_T_FAST = 0x100
+ BPF_T_FLAG_MASK = 0x300
+ BPF_T_FORMAT_MASK = 0x3
+ BPF_T_MICROTIME = 0x0
+ BPF_T_MICROTIME_FAST = 0x100
+ BPF_T_MICROTIME_MONOTONIC = 0x200
+ BPF_T_MICROTIME_MONOTONIC_FAST = 0x300
+ BPF_T_MONOTONIC = 0x200
+ BPF_T_MONOTONIC_FAST = 0x300
+ BPF_T_NANOTIME = 0x1
+ BPF_T_NANOTIME_FAST = 0x101
+ BPF_T_NANOTIME_MONOTONIC = 0x201
+ BPF_T_NANOTIME_MONOTONIC_FAST = 0x301
+ BPF_T_NONE = 0x3
+ BPF_T_NORMAL = 0x0
+ BPF_W = 0x0
+ BPF_X = 0x8
+ BPF_XOR = 0xa0
+ BRKINT = 0x2
+ CAP_ACCEPT = 0x200000020000000
+ CAP_ACL_CHECK = 0x400000000010000
+ CAP_ACL_DELETE = 0x400000000020000
+ CAP_ACL_GET = 0x400000000040000
+ CAP_ACL_SET = 0x400000000080000
+ CAP_ALL0 = 0x20007ffffffffff
+ CAP_ALL1 = 0x4000000001fffff
+ CAP_BIND = 0x200000040000000
+ CAP_BINDAT = 0x200008000000400
+ CAP_CHFLAGSAT = 0x200000000001400
+ CAP_CONNECT = 0x200000080000000
+ CAP_CONNECTAT = 0x200010000000400
+ CAP_CREATE = 0x200000000000040
+ CAP_EVENT = 0x400000000000020
+ CAP_EXTATTR_DELETE = 0x400000000001000
+ CAP_EXTATTR_GET = 0x400000000002000
+ CAP_EXTATTR_LIST = 0x400000000004000
+ CAP_EXTATTR_SET = 0x400000000008000
+ CAP_FCHDIR = 0x200000000000800
+ CAP_FCHFLAGS = 0x200000000001000
+ CAP_FCHMOD = 0x200000000002000
+ CAP_FCHMODAT = 0x200000000002400
+ CAP_FCHOWN = 0x200000000004000
+ CAP_FCHOWNAT = 0x200000000004400
+ CAP_FCNTL = 0x200000000008000
+ CAP_FCNTL_ALL = 0x78
+ CAP_FCNTL_GETFL = 0x8
+ CAP_FCNTL_GETOWN = 0x20
+ CAP_FCNTL_SETFL = 0x10
+ CAP_FCNTL_SETOWN = 0x40
+ CAP_FEXECVE = 0x200000000000080
+ CAP_FLOCK = 0x200000000010000
+ CAP_FPATHCONF = 0x200000000020000
+ CAP_FSCK = 0x200000000040000
+ CAP_FSTAT = 0x200000000080000
+ CAP_FSTATAT = 0x200000000080400
+ CAP_FSTATFS = 0x200000000100000
+ CAP_FSYNC = 0x200000000000100
+ CAP_FTRUNCATE = 0x200000000000200
+ CAP_FUTIMES = 0x200000000200000
+ CAP_FUTIMESAT = 0x200000000200400
+ CAP_GETPEERNAME = 0x200000100000000
+ CAP_GETSOCKNAME = 0x200000200000000
+ CAP_GETSOCKOPT = 0x200000400000000
+ CAP_IOCTL = 0x400000000000080
+ CAP_IOCTLS_ALL = 0x7fffffffffffffff
+ CAP_KQUEUE = 0x400000000100040
+ CAP_KQUEUE_CHANGE = 0x400000000100000
+ CAP_KQUEUE_EVENT = 0x400000000000040
+ CAP_LINKAT_SOURCE = 0x200020000000400
+ CAP_LINKAT_TARGET = 0x200000000400400
+ CAP_LISTEN = 0x200000800000000
+ CAP_LOOKUP = 0x200000000000400
+ CAP_MAC_GET = 0x400000000000001
+ CAP_MAC_SET = 0x400000000000002
+ CAP_MKDIRAT = 0x200000000800400
+ CAP_MKFIFOAT = 0x200000001000400
+ CAP_MKNODAT = 0x200000002000400
+ CAP_MMAP = 0x200000000000010
+ CAP_MMAP_R = 0x20000000000001d
+ CAP_MMAP_RW = 0x20000000000001f
+ CAP_MMAP_RWX = 0x20000000000003f
+ CAP_MMAP_RX = 0x20000000000003d
+ CAP_MMAP_W = 0x20000000000001e
+ CAP_MMAP_WX = 0x20000000000003e
+ CAP_MMAP_X = 0x20000000000003c
+ CAP_PDGETPID = 0x400000000000200
+ CAP_PDKILL = 0x400000000000800
+ CAP_PDWAIT = 0x400000000000400
+ CAP_PEELOFF = 0x200001000000000
+ CAP_POLL_EVENT = 0x400000000000020
+ CAP_PREAD = 0x20000000000000d
+ CAP_PWRITE = 0x20000000000000e
+ CAP_READ = 0x200000000000001
+ CAP_RECV = 0x200000000000001
+ CAP_RENAMEAT_SOURCE = 0x200000004000400
+ CAP_RENAMEAT_TARGET = 0x200040000000400
+ CAP_RIGHTS_VERSION = 0x0
+ CAP_RIGHTS_VERSION_00 = 0x0
+ CAP_SEEK = 0x20000000000000c
+ CAP_SEEK_TELL = 0x200000000000004
+ CAP_SEM_GETVALUE = 0x400000000000004
+ CAP_SEM_POST = 0x400000000000008
+ CAP_SEM_WAIT = 0x400000000000010
+ CAP_SEND = 0x200000000000002
+ CAP_SETSOCKOPT = 0x200002000000000
+ CAP_SHUTDOWN = 0x200004000000000
+ CAP_SOCK_CLIENT = 0x200007780000003
+ CAP_SOCK_SERVER = 0x200007f60000003
+ CAP_SYMLINKAT = 0x200000008000400
+ CAP_TTYHOOK = 0x400000000000100
+ CAP_UNLINKAT = 0x200000010000400
+ CAP_UNUSED0_44 = 0x200080000000000
+ CAP_UNUSED0_57 = 0x300000000000000
+ CAP_UNUSED1_22 = 0x400000000200000
+ CAP_UNUSED1_57 = 0x500000000000000
+ CAP_WRITE = 0x200000000000002
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CLOCK_MONOTONIC = 0x4
+ CLOCK_MONOTONIC_FAST = 0xc
+ CLOCK_MONOTONIC_PRECISE = 0xb
+ CLOCK_PROCESS_CPUTIME_ID = 0xf
+ CLOCK_PROF = 0x2
+ CLOCK_REALTIME = 0x0
+ CLOCK_REALTIME_FAST = 0xa
+ CLOCK_REALTIME_PRECISE = 0x9
+ CLOCK_SECOND = 0xd
+ CLOCK_THREAD_CPUTIME_ID = 0xe
+ CLOCK_UPTIME = 0x5
+ CLOCK_UPTIME_FAST = 0x8
+ CLOCK_UPTIME_PRECISE = 0x7
+ CLOCK_VIRTUAL = 0x1
+ CREAD = 0x800
+ CRTSCTS = 0x30000
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0x18
+ CTL_NET = 0x4
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_AOS = 0xde
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_BREDR_BB = 0xff
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_BLUETOOTH_LE_LL = 0xfb
+ DLT_BLUETOOTH_LE_LL_WITH_PHDR = 0x100
+ DLT_BLUETOOTH_LINUX_MONITOR = 0xfe
+ DLT_CAN20B = 0xbe
+ DLT_CAN_SOCKETCAN = 0xe3
+ DLT_CHAOS = 0x5
+ DLT_CHDLC = 0x68
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DBUS = 0xe7
+ DLT_DECT = 0xdd
+ DLT_DOCSIS = 0x8f
+ DLT_DVB_CI = 0xeb
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_EPON = 0x103
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FC_2 = 0xe0
+ DLT_FC_2_WITH_FRAME_DELIMS = 0xe1
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_GSMTAP_ABIS = 0xda
+ DLT_GSMTAP_UM = 0xd9
+ DLT_HHDLC = 0x79
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NOFCS = 0xe6
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_INFINIBAND = 0xf7
+ DLT_IPFILTER = 0x74
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IPMI_HPM_2 = 0x104
+ DLT_IPNET = 0xe2
+ DLT_IPOIB = 0xf2
+ DLT_IPV4 = 0xe4
+ DLT_IPV6 = 0xe5
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_ATM_CEMIC = 0xee
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FIBRECHANNEL = 0xea
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_SRX_E2E = 0xe9
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_JUNIPER_VS = 0xe8
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_EVDEV = 0xd8
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_PPP_WITHDIRECTION = 0xa6
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MATCHING_MAX = 0x104
+ DLT_MATCHING_MIN = 0x68
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MPEG_2_TS = 0xf3
+ DLT_MPLS = 0xdb
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_MUX27010 = 0xec
+ DLT_NETANALYZER = 0xf0
+ DLT_NETANALYZER_TRANSPARENT = 0xf1
+ DLT_NETLINK = 0xfd
+ DLT_NFC_LLCP = 0xf5
+ DLT_NFLOG = 0xef
+ DLT_NG40 = 0xf4
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x79
+ DLT_PKTAP = 0x102
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0x10
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PPP_WITH_DIRECTION = 0xa6
+ DLT_PRISM_HEADER = 0x77
+ DLT_PROFIBUS_DL = 0x101
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_RIO = 0x7c
+ DLT_RTAC_SERIAL = 0xfa
+ DLT_SCCP = 0x8e
+ DLT_SCTP = 0xf8
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xf
+ DLT_STANAG_5066_D_PDU = 0xed
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USBPCAP = 0xf9
+ DLT_USB_LINUX = 0xbd
+ DLT_USB_LINUX_MMAPPED = 0xdc
+ DLT_USER0 = 0x93
+ DLT_USER1 = 0x94
+ DLT_USER10 = 0x9d
+ DLT_USER11 = 0x9e
+ DLT_USER12 = 0x9f
+ DLT_USER13 = 0xa0
+ DLT_USER14 = 0xa1
+ DLT_USER15 = 0xa2
+ DLT_USER2 = 0x95
+ DLT_USER3 = 0x96
+ DLT_USER4 = 0x97
+ DLT_USER5 = 0x98
+ DLT_USER6 = 0x99
+ DLT_USER7 = 0x9a
+ DLT_USER8 = 0x9b
+ DLT_USER9 = 0x9c
+ DLT_WIHART = 0xdf
+ DLT_WIRESHARK_UPPER_PDU = 0xfc
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EVFILT_AIO = -0x3
+ EVFILT_FS = -0x9
+ EVFILT_LIO = -0xa
+ EVFILT_PROC = -0x5
+ EVFILT_PROCDESC = -0x8
+ EVFILT_READ = -0x1
+ EVFILT_SENDFILE = -0xc
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0xc
+ EVFILT_TIMER = -0x7
+ EVFILT_USER = -0xb
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_DISPATCH = 0x80
+ EV_DROP = 0x1000
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG1 = 0x2000
+ EV_FLAG2 = 0x4000
+ EV_FORCEONESHOT = 0x100
+ EV_ONESHOT = 0x10
+ EV_RECEIPT = 0x40
+ EV_SYSFLAGS = 0xf000
+ EXTA = 0x4b00
+ EXTATTR_NAMESPACE_EMPTY = 0x0
+ EXTATTR_NAMESPACE_SYSTEM = 0x2
+ EXTATTR_NAMESPACE_USER = 0x1
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FLUSHO = 0x800000
+ F_CANCEL = 0x5
+ F_DUP2FD = 0xa
+ F_DUP2FD_CLOEXEC = 0x12
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x11
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0xb
+ F_GETOWN = 0x5
+ F_OGETLK = 0x7
+ F_OK = 0x0
+ F_OSETLK = 0x8
+ F_OSETLKW = 0x9
+ F_RDAHEAD = 0x10
+ F_RDLCK = 0x1
+ F_READAHEAD = 0xf
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0xc
+ F_SETLKW = 0xd
+ F_SETLK_REMOTE = 0xe
+ F_SETOWN = 0x6
+ F_UNLCK = 0x2
+ F_UNLCKSYS = 0x4
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFAN_ARRIVAL = 0x0
+ IFAN_DEPARTURE = 0x1
+ IFF_ALLMULTI = 0x200
+ IFF_ALTPHYS = 0x4000
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x218f52
+ IFF_CANTCONFIG = 0x10000
+ IFF_DEBUG = 0x4
+ IFF_DRV_OACTIVE = 0x400
+ IFF_DRV_RUNNING = 0x40
+ IFF_DYING = 0x200000
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MONITOR = 0x40000
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PPROMISC = 0x20000
+ IFF_PROMISC = 0x100
+ IFF_RENAMING = 0x400000
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_STATICARP = 0x80000
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_BRIDGE = 0xd1
+ IFT_CARP = 0xf8
+ IFT_IEEE1394 = 0x90
+ IFT_INFINIBAND = 0xc7
+ IFT_L2VLAN = 0x87
+ IFT_L3IPVLAN = 0x88
+ IFT_PPP = 0x17
+ IFT_PROPVIRTUAL = 0x35
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LOOPBACKNET = 0x7f
+ IN_RFC3021_MASK = 0xfffffffe
+ IPPROTO_3PC = 0x22
+ IPPROTO_ADFS = 0x44
+ IPPROTO_AH = 0x33
+ IPPROTO_AHIP = 0x3d
+ IPPROTO_APES = 0x63
+ IPPROTO_ARGUS = 0xd
+ IPPROTO_AX25 = 0x5d
+ IPPROTO_BHA = 0x31
+ IPPROTO_BLT = 0x1e
+ IPPROTO_BRSATMON = 0x4c
+ IPPROTO_CARP = 0x70
+ IPPROTO_CFTP = 0x3e
+ IPPROTO_CHAOS = 0x10
+ IPPROTO_CMTP = 0x26
+ IPPROTO_CPHB = 0x49
+ IPPROTO_CPNX = 0x48
+ IPPROTO_DDP = 0x25
+ IPPROTO_DGP = 0x56
+ IPPROTO_DIVERT = 0x102
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_EMCON = 0xe
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GMTP = 0x64
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HELLO = 0x3f
+ IPPROTO_HIP = 0x8b
+ IPPROTO_HMP = 0x14
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IDPR = 0x23
+ IPPROTO_IDRP = 0x2d
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IGP = 0x55
+ IPPROTO_IGRP = 0x58
+ IPPROTO_IL = 0x28
+ IPPROTO_INLSP = 0x34
+ IPPROTO_INP = 0x20
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPCV = 0x47
+ IPPROTO_IPEIP = 0x5e
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPPC = 0x43
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IRTP = 0x1c
+ IPPROTO_KRYPTOLAN = 0x41
+ IPPROTO_LARP = 0x5b
+ IPPROTO_LEAF1 = 0x19
+ IPPROTO_LEAF2 = 0x1a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MEAS = 0x13
+ IPPROTO_MH = 0x87
+ IPPROTO_MHRP = 0x30
+ IPPROTO_MICP = 0x5f
+ IPPROTO_MOBILE = 0x37
+ IPPROTO_MPLS = 0x89
+ IPPROTO_MTP = 0x5c
+ IPPROTO_MUX = 0x12
+ IPPROTO_ND = 0x4d
+ IPPROTO_NHRP = 0x36
+ IPPROTO_NONE = 0x3b
+ IPPROTO_NSP = 0x1f
+ IPPROTO_NVPII = 0xb
+ IPPROTO_OLD_DIVERT = 0xfe
+ IPPROTO_OSPFIGP = 0x59
+ IPPROTO_PFSYNC = 0xf0
+ IPPROTO_PGM = 0x71
+ IPPROTO_PIGP = 0x9
+ IPPROTO_PIM = 0x67
+ IPPROTO_PRM = 0x15
+ IPPROTO_PUP = 0xc
+ IPPROTO_PVP = 0x4b
+ IPPROTO_RAW = 0xff
+ IPPROTO_RCCMON = 0xa
+ IPPROTO_RDP = 0x1b
+ IPPROTO_RESERVED_253 = 0xfd
+ IPPROTO_RESERVED_254 = 0xfe
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_RVD = 0x42
+ IPPROTO_SATEXPAK = 0x40
+ IPPROTO_SATMON = 0x45
+ IPPROTO_SCCSP = 0x60
+ IPPROTO_SCTP = 0x84
+ IPPROTO_SDRP = 0x2a
+ IPPROTO_SEND = 0x103
+ IPPROTO_SEP = 0x21
+ IPPROTO_SHIM6 = 0x8c
+ IPPROTO_SKIP = 0x39
+ IPPROTO_SPACER = 0x7fff
+ IPPROTO_SRPC = 0x5a
+ IPPROTO_ST = 0x7
+ IPPROTO_SVMTP = 0x52
+ IPPROTO_SWIPE = 0x35
+ IPPROTO_TCF = 0x57
+ IPPROTO_TCP = 0x6
+ IPPROTO_TLSP = 0x38
+ IPPROTO_TP = 0x1d
+ IPPROTO_TPXX = 0x27
+ IPPROTO_TRUNK1 = 0x17
+ IPPROTO_TRUNK2 = 0x18
+ IPPROTO_TTP = 0x54
+ IPPROTO_UDP = 0x11
+ IPPROTO_UDPLITE = 0x88
+ IPPROTO_VINES = 0x53
+ IPPROTO_VISA = 0x46
+ IPPROTO_VMTP = 0x51
+ IPPROTO_WBEXPAK = 0x4f
+ IPPROTO_WBMON = 0x4e
+ IPPROTO_WSN = 0x4a
+ IPPROTO_XNET = 0xf
+ IPPROTO_XTP = 0x24
+ IPV6_AUTOFLOWLABEL = 0x3b
+ IPV6_BINDANY = 0x40
+ IPV6_BINDMULTI = 0x41
+ IPV6_BINDV6ONLY = 0x1b
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_DONTFRAG = 0x3e
+ IPV6_DSTOPTS = 0x32
+ IPV6_FLOWID = 0x43
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FLOWTYPE = 0x44
+ IPV6_FRAGTTL = 0x78
+ IPV6_FW_ADD = 0x1e
+ IPV6_FW_DEL = 0x1f
+ IPV6_FW_FLUSH = 0x20
+ IPV6_FW_GET = 0x22
+ IPV6_FW_ZERO = 0x21
+ IPV6_HLIMDEC = 0x1
+ IPV6_HOPLIMIT = 0x2f
+ IPV6_HOPOPTS = 0x31
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXOPTHDR = 0x800
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MAX_GROUP_SRC_FILTER = 0x200
+ IPV6_MAX_MEMBERSHIPS = 0xfff
+ IPV6_MAX_SOCK_SRC_FILTER = 0x80
+ IPV6_MIN_MEMBERSHIPS = 0x1f
+ IPV6_MMTU = 0x500
+ IPV6_MSFILTER = 0x4a
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_NEXTHOP = 0x30
+ IPV6_PATHMTU = 0x2c
+ IPV6_PKTINFO = 0x2e
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_PREFER_TEMPADDR = 0x3f
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVFLOWID = 0x46
+ IPV6_RECVHOPLIMIT = 0x25
+ IPV6_RECVHOPOPTS = 0x27
+ IPV6_RECVPATHMTU = 0x2b
+ IPV6_RECVPKTINFO = 0x24
+ IPV6_RECVRSSBUCKETID = 0x47
+ IPV6_RECVRTHDR = 0x26
+ IPV6_RECVTCLASS = 0x39
+ IPV6_RSSBUCKETID = 0x45
+ IPV6_RSS_LISTEN_BUCKET = 0x42
+ IPV6_RTHDR = 0x33
+ IPV6_RTHDRDSTOPTS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x3d
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_USE_MIN_MTU = 0x2a
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_ADD_SOURCE_MEMBERSHIP = 0x46
+ IP_BINDANY = 0x18
+ IP_BINDMULTI = 0x19
+ IP_BLOCK_SOURCE = 0x48
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DONTFRAG = 0x43
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_DROP_SOURCE_MEMBERSHIP = 0x47
+ IP_DUMMYNET3 = 0x31
+ IP_DUMMYNET_CONFIGURE = 0x3c
+ IP_DUMMYNET_DEL = 0x3d
+ IP_DUMMYNET_FLUSH = 0x3e
+ IP_DUMMYNET_GET = 0x40
+ IP_FLOWID = 0x5a
+ IP_FLOWTYPE = 0x5b
+ IP_FW3 = 0x30
+ IP_FW_ADD = 0x32
+ IP_FW_DEL = 0x33
+ IP_FW_FLUSH = 0x34
+ IP_FW_GET = 0x36
+ IP_FW_NAT_CFG = 0x38
+ IP_FW_NAT_DEL = 0x39
+ IP_FW_NAT_GET_CONFIG = 0x3a
+ IP_FW_NAT_GET_LOG = 0x3b
+ IP_FW_RESETLOG = 0x37
+ IP_FW_TABLE_ADD = 0x28
+ IP_FW_TABLE_DEL = 0x29
+ IP_FW_TABLE_FLUSH = 0x2a
+ IP_FW_TABLE_GETSIZE = 0x2b
+ IP_FW_TABLE_LIST = 0x2c
+ IP_FW_ZERO = 0x35
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x15
+ IP_MAXPACKET = 0xffff
+ IP_MAX_GROUP_SRC_FILTER = 0x200
+ IP_MAX_MEMBERSHIPS = 0xfff
+ IP_MAX_SOCK_MUTE_FILTER = 0x80
+ IP_MAX_SOCK_SRC_FILTER = 0x80
+ IP_MAX_SOURCE_FILTER = 0x400
+ IP_MF = 0x2000
+ IP_MINTTL = 0x42
+ IP_MIN_MEMBERSHIPS = 0x1f
+ IP_MSFILTER = 0x4a
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_MULTICAST_VIF = 0xe
+ IP_OFFMASK = 0x1fff
+ IP_ONESBCAST = 0x17
+ IP_OPTIONS = 0x1
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVFLOWID = 0x5d
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVRETOPTS = 0x6
+ IP_RECVRSSBUCKETID = 0x5e
+ IP_RECVTOS = 0x44
+ IP_RECVTTL = 0x41
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RSSBUCKETID = 0x5c
+ IP_RSS_LISTEN_BUCKET = 0x1a
+ IP_RSVP_OFF = 0x10
+ IP_RSVP_ON = 0xf
+ IP_RSVP_VIF_OFF = 0x12
+ IP_RSVP_VIF_ON = 0x11
+ IP_SENDSRCADDR = 0x7
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ IP_UNBLOCK_SOURCE = 0x49
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_AUTOSYNC = 0x7
+ MADV_CORE = 0x9
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x5
+ MADV_NOCORE = 0x8
+ MADV_NORMAL = 0x0
+ MADV_NOSYNC = 0x6
+ MADV_PROTECT = 0xa
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_WILLNEED = 0x3
+ MAP_32BIT = 0x80000
+ MAP_ALIGNED_SUPER = 0x1000000
+ MAP_ALIGNMENT_MASK = -0x1000000
+ MAP_ALIGNMENT_SHIFT = 0x18
+ MAP_ANON = 0x1000
+ MAP_ANONYMOUS = 0x1000
+ MAP_COPY = 0x2
+ MAP_EXCL = 0x4000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_HASSEMAPHORE = 0x200
+ MAP_NOCORE = 0x20000
+ MAP_NOSYNC = 0x800
+ MAP_PREFAULT_READ = 0x40000
+ MAP_PRIVATE = 0x2
+ MAP_RESERVED0020 = 0x20
+ MAP_RESERVED0040 = 0x40
+ MAP_RESERVED0080 = 0x80
+ MAP_RESERVED0100 = 0x100
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x400
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MSG_CMSG_CLOEXEC = 0x40000
+ MSG_COMPAT = 0x8000
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOF = 0x100
+ MSG_EOR = 0x8
+ MSG_NBIO = 0x4000
+ MSG_NOSIGNAL = 0x20000
+ MSG_NOTIFICATION = 0x2000
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x10
+ MSG_WAITALL = 0x40
+ MSG_WAITFORONE = 0x80000
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x2
+ MS_SYNC = 0x0
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_IFLISTL = 0x5
+ NET_RT_IFMALIST = 0x4
+ NOFLSH = 0x80000000
+ NOKERNINFO = 0x2000000
+ NOTE_ATTRIB = 0x8
+ NOTE_CHILD = 0x4
+ NOTE_CLOSE = 0x100
+ NOTE_CLOSE_WRITE = 0x200
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXTEND = 0x4
+ NOTE_FFAND = 0x40000000
+ NOTE_FFCOPY = 0xc0000000
+ NOTE_FFCTRLMASK = 0xc0000000
+ NOTE_FFLAGSMASK = 0xffffff
+ NOTE_FFNOP = 0x0
+ NOTE_FFOR = 0x80000000
+ NOTE_FILE_POLL = 0x2
+ NOTE_FORK = 0x40000000
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_MSECONDS = 0x2
+ NOTE_NSECONDS = 0x8
+ NOTE_OPEN = 0x80
+ NOTE_PCTRLMASK = 0xf0000000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_READ = 0x400
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_SECONDS = 0x1
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRIGGER = 0x1000000
+ NOTE_USECONDS = 0x4
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ OXTABS = 0x4
+ O_ACCMODE = 0x3
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x100000
+ O_CREAT = 0x200
+ O_DIRECT = 0x10000
+ O_DIRECTORY = 0x20000
+ O_EXCL = 0x800
+ O_EXEC = 0x40000
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_SHLOCK = 0x10
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_TTY_INIT = 0x80000
+ O_VERIFY = 0x200000
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ RLIMIT_AS = 0xa
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_MEMLOCK = 0x6
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_NPROC = 0x7
+ RLIMIT_RSS = 0x5
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x8
+ RTAX_NETMASK = 0x2
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTF_BLACKHOLE = 0x1000
+ RTF_BROADCAST = 0x400000
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_FIXEDMTU = 0x80000
+ RTF_FMASK = 0x1004d808
+ RTF_GATEWAY = 0x2
+ RTF_GWFLAG_COMPAT = 0x80000000
+ RTF_HOST = 0x4
+ RTF_LLDATA = 0x400
+ RTF_LLINFO = 0x400
+ RTF_LOCAL = 0x200000
+ RTF_MODIFIED = 0x20
+ RTF_MULTICAST = 0x800000
+ RTF_PINNED = 0x100000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x40000
+ RTF_REJECT = 0x8
+ RTF_RNH_LOCKED = 0x40000000
+ RTF_STATIC = 0x800
+ RTF_STICKY = 0x10000000
+ RTF_UP = 0x1
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DELMADDR = 0x10
+ RTM_GET = 0x4
+ RTM_IEEE80211 = 0x12
+ RTM_IFANNOUNCE = 0x11
+ RTM_IFINFO = 0xe
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_NEWMADDR = 0xf
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x5
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RTV_WEIGHT = 0x100
+ RT_ALL_FIBS = -0x1
+ RT_BLACKHOLE = 0x40
+ RT_CACHING_CONTEXT = 0x1
+ RT_DEFAULT_FIB = 0x0
+ RT_HAS_GW = 0x80
+ RT_HAS_HEADER = 0x10
+ RT_HAS_HEADER_BIT = 0x4
+ RT_L2_ME = 0x4
+ RT_L2_ME_BIT = 0x2
+ RT_LLE_CACHE = 0x100
+ RT_MAY_LOOP = 0x8
+ RT_MAY_LOOP_BIT = 0x3
+ RT_NORTREF = 0x2
+ RT_REJECT = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ RUSAGE_THREAD = 0x1
+ SCM_BINTIME = 0x4
+ SCM_CREDS = 0x3
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x2
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCAIFADDR = 0x8040691a
+ SIOCAIFGROUP = 0x80286987
+ SIOCATMARK = 0x40047307
+ SIOCDELMULTI = 0x80206932
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFGROUP = 0x80286989
+ SIOCDIFPHYADDR = 0x80206949
+ SIOCGDRVSPEC = 0xc028697b
+ SIOCGETSGCNT = 0xc0207210
+ SIOCGETVIFCNT = 0xc028720f
+ SIOCGHIWAT = 0x40047301
+ SIOCGI2C = 0xc020693d
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCAP = 0xc020691f
+ SIOCGIFCONF = 0xc0106924
+ SIOCGIFDESCR = 0xc020692a
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFIB = 0xc020695c
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFGMEMB = 0xc028698a
+ SIOCGIFGROUP = 0xc0286988
+ SIOCGIFINDEX = 0xc0206920
+ SIOCGIFMAC = 0xc0206926
+ SIOCGIFMEDIA = 0xc0306938
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc0206933
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206948
+ SIOCGIFPHYS = 0xc0206935
+ SIOCGIFPSRCADDR = 0xc0206947
+ SIOCGIFSTATUS = 0xc331693b
+ SIOCGIFXMEDIA = 0xc030698b
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCGPRIVATE_0 = 0xc0206950
+ SIOCGPRIVATE_1 = 0xc0206951
+ SIOCGTUNFIB = 0xc020695e
+ SIOCIFCREATE = 0xc020697a
+ SIOCIFCREATE2 = 0xc020697c
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc0106978
+ SIOCSDRVSPEC = 0x8028697b
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFCAP = 0x8020691e
+ SIOCSIFDESCR = 0x80206929
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFIB = 0x8020695d
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFLLADDR = 0x8020693c
+ SIOCSIFMAC = 0x80206927
+ SIOCSIFMEDIA = 0xc0206937
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x80206934
+ SIOCSIFNAME = 0x80206928
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x80406946
+ SIOCSIFPHYS = 0x80206936
+ SIOCSIFRVNET = 0xc020695b
+ SIOCSIFVNET = 0xc020695a
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SIOCSTUNFIB = 0x8020695f
+ SOCK_CLOEXEC = 0x10000000
+ SOCK_DGRAM = 0x2
+ SOCK_MAXADDRLEN = 0xff
+ SOCK_NONBLOCK = 0x20000000
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_ACCEPTFILTER = 0x1000
+ SO_BINTIME = 0x2000
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LABEL = 0x1009
+ SO_LINGER = 0x80
+ SO_LISTENINCQLEN = 0x1013
+ SO_LISTENQLEN = 0x1012
+ SO_LISTENQLIMIT = 0x1011
+ SO_NOSIGPIPE = 0x800
+ SO_NO_DDP = 0x8000
+ SO_NO_OFFLOAD = 0x4000
+ SO_OOBINLINE = 0x100
+ SO_PEERLABEL = 0x1010
+ SO_PROTOCOL = 0x1016
+ SO_PROTOTYPE = 0x1016
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_SETFIB = 0x1014
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_TIMESTAMP = 0x400
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ SO_USER_COOKIE = 0x1015
+ SO_VENDOR = 0x80000000
+ TAB0 = 0x0
+ TAB3 = 0x4
+ TABDLY = 0x4
+ TCIFLUSH = 0x1
+ TCIOFF = 0x3
+ TCIOFLUSH = 0x3
+ TCION = 0x4
+ TCOFLUSH = 0x2
+ TCOOFF = 0x1
+ TCOON = 0x2
+ TCP_CA_NAME_MAX = 0x10
+ TCP_CCALGOOPT = 0x41
+ TCP_CONGESTION = 0x40
+ TCP_FASTOPEN = 0x401
+ TCP_FUNCTION_BLK = 0x2000
+ TCP_FUNCTION_NAME_LEN_MAX = 0x20
+ TCP_INFO = 0x20
+ TCP_KEEPCNT = 0x400
+ TCP_KEEPIDLE = 0x100
+ TCP_KEEPINIT = 0x80
+ TCP_KEEPINTVL = 0x200
+ TCP_MAXBURST = 0x4
+ TCP_MAXHLEN = 0x3c
+ TCP_MAXOLEN = 0x28
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_SACK = 0x4
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MD5SIG = 0x10
+ TCP_MINMSS = 0xd8
+ TCP_MSS = 0x218
+ TCP_NODELAY = 0x1
+ TCP_NOOPT = 0x8
+ TCP_NOPUSH = 0x4
+ TCP_PCAP_IN = 0x1000
+ TCP_PCAP_OUT = 0x800
+ TCP_VENDOR = 0x80000000
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDRAIN = 0x2000745e
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLUSH = 0x80047410
+ TIOCGDRAINWAIT = 0x40047456
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGPGRP = 0x40047477
+ TIOCGPTN = 0x4004740f
+ TIOCGSID = 0x40047463
+ TIOCGWINSZ = 0x40087468
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGDTRWAIT = 0x4004745a
+ TIOCMGET = 0x4004746a
+ TIOCMSDTRWAIT = 0x8004745b
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DCD = 0x40
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCPTMASTER = 0x2000741c
+ TIOCSBRK = 0x2000747b
+ TIOCSCTTY = 0x20007461
+ TIOCSDRAINWAIT = 0x80047457
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSIG = 0x2004745f
+ TIOCSPGRP = 0x80047476
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x20007465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCTIMESTAMP = 0x40107459
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VERASE2 = 0x7
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VTIME = 0x11
+ VWERASE = 0x4
+ WCONTINUED = 0x4
+ WCOREFLAG = 0x80
+ WEXITED = 0x10
+ WLINUXCLONE = 0x80000000
+ WNOHANG = 0x1
+ WNOWAIT = 0x8
+ WSTOPPED = 0x2
+ WTRAPPED = 0x20
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADF = syscall.Errno(0x9)
+ EBADMSG = syscall.Errno(0x59)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x55)
+ ECAPMODE = syscall.Errno(0x5e)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDOOFUS = syscall.Errno(0x58)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x52)
+ EILSEQ = syscall.Errno(0x56)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x60)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5a)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x57)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x5b)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x53)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCAPABLE = syscall.Errno(0x5d)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTRECOVERABLE = syscall.Errno(0x5f)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x2d)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x54)
+ EOWNERDEAD = syscall.Errno(0x60)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x5c)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGLIBRT = syscall.Signal(0x21)
+ SIGLWP = syscall.Signal(0x20)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTHR = syscall.Signal(0x20)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "operation timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "identifier removed",
+ 83: "no message of desired type",
+ 84: "value too large to be stored in data type",
+ 85: "operation canceled",
+ 86: "illegal byte sequence",
+ 87: "attribute not found",
+ 88: "programming error",
+ 89: "bad message",
+ 90: "multihop attempted",
+ 91: "link has been severed",
+ 92: "protocol error",
+ 93: "capabilities insufficient",
+ 94: "not permitted in capability mode",
+ 95: "state not recoverable",
+ 96: "previous owner died",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "suspended (signal)",
+ 18: "suspended",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+ 32: "unknown signal",
+ 33: "unknown signal",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go
new file mode 100644
index 0000000..c5c6f13
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go
@@ -0,0 +1,1715 @@
+// mkerrors.sh
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm,freebsd
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_ARP = 0x23
+ AF_ATM = 0x1e
+ AF_BLUETOOTH = 0x24
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1a
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x25
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x1c
+ AF_INET6_SDP = 0x2a
+ AF_INET_SDP = 0x28
+ AF_IPX = 0x17
+ AF_ISDN = 0x1a
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x2a
+ AF_NATM = 0x1d
+ AF_NETBIOS = 0x6
+ AF_NETGRAPH = 0x20
+ AF_OSI = 0x7
+ AF_PUP = 0x4
+ AF_ROUTE = 0x11
+ AF_SCLUSTER = 0x22
+ AF_SIP = 0x18
+ AF_SLOW = 0x21
+ AF_SNA = 0xb
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ AF_VENDOR00 = 0x27
+ AF_VENDOR01 = 0x29
+ AF_VENDOR02 = 0x2b
+ AF_VENDOR03 = 0x2d
+ AF_VENDOR04 = 0x2f
+ AF_VENDOR05 = 0x31
+ AF_VENDOR06 = 0x33
+ AF_VENDOR07 = 0x35
+ AF_VENDOR08 = 0x37
+ AF_VENDOR09 = 0x39
+ AF_VENDOR10 = 0x3b
+ AF_VENDOR11 = 0x3d
+ AF_VENDOR12 = 0x3f
+ AF_VENDOR13 = 0x41
+ AF_VENDOR14 = 0x43
+ AF_VENDOR15 = 0x45
+ AF_VENDOR16 = 0x47
+ AF_VENDOR17 = 0x49
+ AF_VENDOR18 = 0x4b
+ AF_VENDOR19 = 0x4d
+ AF_VENDOR20 = 0x4f
+ AF_VENDOR21 = 0x51
+ AF_VENDOR22 = 0x53
+ AF_VENDOR23 = 0x55
+ AF_VENDOR24 = 0x57
+ AF_VENDOR25 = 0x59
+ AF_VENDOR26 = 0x5b
+ AF_VENDOR27 = 0x5d
+ AF_VENDOR28 = 0x5f
+ AF_VENDOR29 = 0x61
+ AF_VENDOR30 = 0x63
+ AF_VENDOR31 = 0x65
+ AF_VENDOR32 = 0x67
+ AF_VENDOR33 = 0x69
+ AF_VENDOR34 = 0x6b
+ AF_VENDOR35 = 0x6d
+ AF_VENDOR36 = 0x6f
+ AF_VENDOR37 = 0x71
+ AF_VENDOR38 = 0x73
+ AF_VENDOR39 = 0x75
+ AF_VENDOR40 = 0x77
+ AF_VENDOR41 = 0x79
+ AF_VENDOR42 = 0x7b
+ AF_VENDOR43 = 0x7d
+ AF_VENDOR44 = 0x7f
+ AF_VENDOR45 = 0x81
+ AF_VENDOR46 = 0x83
+ AF_VENDOR47 = 0x85
+ ALTWERASE = 0x200
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B460800 = 0x70800
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B921600 = 0xe1000
+ B9600 = 0x2580
+ BIOCFEEDBACK = 0x8004427c
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDIRECTION = 0x40044276
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc0084279
+ BIOCGETBUFMODE = 0x4004427d
+ BIOCGETIF = 0x4020426b
+ BIOCGETZMAX = 0x4004427f
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044272
+ BIOCGRTIMEOUT = 0x4010426e
+ BIOCGSEESENT = 0x40044276
+ BIOCGSTATS = 0x4008426f
+ BIOCGTSTAMP = 0x40044283
+ BIOCIMMEDIATE = 0x80044270
+ BIOCLOCK = 0x2000427a
+ BIOCPROMISC = 0x20004269
+ BIOCROTZBUF = 0x400c4280
+ BIOCSBLEN = 0xc0044266
+ BIOCSDIRECTION = 0x80044277
+ BIOCSDLT = 0x80044278
+ BIOCSETBUFMODE = 0x8004427e
+ BIOCSETF = 0x80084267
+ BIOCSETFNR = 0x80084282
+ BIOCSETIF = 0x8020426c
+ BIOCSETWF = 0x8008427b
+ BIOCSETZBUF = 0x800c4281
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044273
+ BIOCSRTIMEOUT = 0x8010426d
+ BIOCSSEESENT = 0x80044277
+ BIOCSTSTAMP = 0x80044284
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_BUFMODE_BUFFER = 0x1
+ BPF_BUFMODE_ZBUF = 0x2
+ 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_MAXBUFSIZE = 0x80000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MOD = 0x90
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ BPF_RET = 0x6
+ BPF_RSH = 0x70
+ BPF_ST = 0x2
+ BPF_STX = 0x3
+ BPF_SUB = 0x10
+ BPF_TAX = 0x0
+ BPF_TXA = 0x80
+ BPF_T_BINTIME = 0x2
+ BPF_T_BINTIME_FAST = 0x102
+ BPF_T_BINTIME_MONOTONIC = 0x202
+ BPF_T_BINTIME_MONOTONIC_FAST = 0x302
+ BPF_T_FAST = 0x100
+ BPF_T_FLAG_MASK = 0x300
+ BPF_T_FORMAT_MASK = 0x3
+ BPF_T_MICROTIME = 0x0
+ BPF_T_MICROTIME_FAST = 0x100
+ BPF_T_MICROTIME_MONOTONIC = 0x200
+ BPF_T_MICROTIME_MONOTONIC_FAST = 0x300
+ BPF_T_MONOTONIC = 0x200
+ BPF_T_MONOTONIC_FAST = 0x300
+ BPF_T_NANOTIME = 0x1
+ BPF_T_NANOTIME_FAST = 0x101
+ BPF_T_NANOTIME_MONOTONIC = 0x201
+ BPF_T_NANOTIME_MONOTONIC_FAST = 0x301
+ BPF_T_NONE = 0x3
+ BPF_T_NORMAL = 0x0
+ BPF_W = 0x0
+ BPF_X = 0x8
+ BPF_XOR = 0xa0
+ BRKINT = 0x2
+ CAP_ACCEPT = 0x200000020000000
+ CAP_ACL_CHECK = 0x400000000010000
+ CAP_ACL_DELETE = 0x400000000020000
+ CAP_ACL_GET = 0x400000000040000
+ CAP_ACL_SET = 0x400000000080000
+ CAP_ALL0 = 0x20007ffffffffff
+ CAP_ALL1 = 0x4000000001fffff
+ CAP_BIND = 0x200000040000000
+ CAP_BINDAT = 0x200008000000400
+ CAP_CHFLAGSAT = 0x200000000001400
+ CAP_CONNECT = 0x200000080000000
+ CAP_CONNECTAT = 0x200010000000400
+ CAP_CREATE = 0x200000000000040
+ CAP_EVENT = 0x400000000000020
+ CAP_EXTATTR_DELETE = 0x400000000001000
+ CAP_EXTATTR_GET = 0x400000000002000
+ CAP_EXTATTR_LIST = 0x400000000004000
+ CAP_EXTATTR_SET = 0x400000000008000
+ CAP_FCHDIR = 0x200000000000800
+ CAP_FCHFLAGS = 0x200000000001000
+ CAP_FCHMOD = 0x200000000002000
+ CAP_FCHMODAT = 0x200000000002400
+ CAP_FCHOWN = 0x200000000004000
+ CAP_FCHOWNAT = 0x200000000004400
+ CAP_FCNTL = 0x200000000008000
+ CAP_FCNTL_ALL = 0x78
+ CAP_FCNTL_GETFL = 0x8
+ CAP_FCNTL_GETOWN = 0x20
+ CAP_FCNTL_SETFL = 0x10
+ CAP_FCNTL_SETOWN = 0x40
+ CAP_FEXECVE = 0x200000000000080
+ CAP_FLOCK = 0x200000000010000
+ CAP_FPATHCONF = 0x200000000020000
+ CAP_FSCK = 0x200000000040000
+ CAP_FSTAT = 0x200000000080000
+ CAP_FSTATAT = 0x200000000080400
+ CAP_FSTATFS = 0x200000000100000
+ CAP_FSYNC = 0x200000000000100
+ CAP_FTRUNCATE = 0x200000000000200
+ CAP_FUTIMES = 0x200000000200000
+ CAP_FUTIMESAT = 0x200000000200400
+ CAP_GETPEERNAME = 0x200000100000000
+ CAP_GETSOCKNAME = 0x200000200000000
+ CAP_GETSOCKOPT = 0x200000400000000
+ CAP_IOCTL = 0x400000000000080
+ CAP_IOCTLS_ALL = 0x7fffffff
+ CAP_KQUEUE = 0x400000000100040
+ CAP_KQUEUE_CHANGE = 0x400000000100000
+ CAP_KQUEUE_EVENT = 0x400000000000040
+ CAP_LINKAT_SOURCE = 0x200020000000400
+ CAP_LINKAT_TARGET = 0x200000000400400
+ CAP_LISTEN = 0x200000800000000
+ CAP_LOOKUP = 0x200000000000400
+ CAP_MAC_GET = 0x400000000000001
+ CAP_MAC_SET = 0x400000000000002
+ CAP_MKDIRAT = 0x200000000800400
+ CAP_MKFIFOAT = 0x200000001000400
+ CAP_MKNODAT = 0x200000002000400
+ CAP_MMAP = 0x200000000000010
+ CAP_MMAP_R = 0x20000000000001d
+ CAP_MMAP_RW = 0x20000000000001f
+ CAP_MMAP_RWX = 0x20000000000003f
+ CAP_MMAP_RX = 0x20000000000003d
+ CAP_MMAP_W = 0x20000000000001e
+ CAP_MMAP_WX = 0x20000000000003e
+ CAP_MMAP_X = 0x20000000000003c
+ CAP_PDGETPID = 0x400000000000200
+ CAP_PDKILL = 0x400000000000800
+ CAP_PDWAIT = 0x400000000000400
+ CAP_PEELOFF = 0x200001000000000
+ CAP_POLL_EVENT = 0x400000000000020
+ CAP_PREAD = 0x20000000000000d
+ CAP_PWRITE = 0x20000000000000e
+ CAP_READ = 0x200000000000001
+ CAP_RECV = 0x200000000000001
+ CAP_RENAMEAT_SOURCE = 0x200000004000400
+ CAP_RENAMEAT_TARGET = 0x200040000000400
+ CAP_RIGHTS_VERSION = 0x0
+ CAP_RIGHTS_VERSION_00 = 0x0
+ CAP_SEEK = 0x20000000000000c
+ CAP_SEEK_TELL = 0x200000000000004
+ CAP_SEM_GETVALUE = 0x400000000000004
+ CAP_SEM_POST = 0x400000000000008
+ CAP_SEM_WAIT = 0x400000000000010
+ CAP_SEND = 0x200000000000002
+ CAP_SETSOCKOPT = 0x200002000000000
+ CAP_SHUTDOWN = 0x200004000000000
+ CAP_SOCK_CLIENT = 0x200007780000003
+ CAP_SOCK_SERVER = 0x200007f60000003
+ CAP_SYMLINKAT = 0x200000008000400
+ CAP_TTYHOOK = 0x400000000000100
+ CAP_UNLINKAT = 0x200000010000400
+ CAP_UNUSED0_44 = 0x200080000000000
+ CAP_UNUSED0_57 = 0x300000000000000
+ CAP_UNUSED1_22 = 0x400000000200000
+ CAP_UNUSED1_57 = 0x500000000000000
+ CAP_WRITE = 0x200000000000002
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CLOCK_MONOTONIC = 0x4
+ CLOCK_MONOTONIC_FAST = 0xc
+ CLOCK_MONOTONIC_PRECISE = 0xb
+ CLOCK_PROCESS_CPUTIME_ID = 0xf
+ CLOCK_PROF = 0x2
+ CLOCK_REALTIME = 0x0
+ CLOCK_REALTIME_FAST = 0xa
+ CLOCK_REALTIME_PRECISE = 0x9
+ CLOCK_SECOND = 0xd
+ CLOCK_THREAD_CPUTIME_ID = 0xe
+ CLOCK_UPTIME = 0x5
+ CLOCK_UPTIME_FAST = 0x8
+ CLOCK_UPTIME_PRECISE = 0x7
+ CLOCK_VIRTUAL = 0x1
+ CREAD = 0x800
+ CRTSCTS = 0x30000
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0x18
+ CTL_NET = 0x4
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_AOS = 0xde
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_BREDR_BB = 0xff
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_BLUETOOTH_LE_LL = 0xfb
+ DLT_BLUETOOTH_LE_LL_WITH_PHDR = 0x100
+ DLT_BLUETOOTH_LINUX_MONITOR = 0xfe
+ DLT_CAN20B = 0xbe
+ DLT_CAN_SOCKETCAN = 0xe3
+ DLT_CHAOS = 0x5
+ DLT_CHDLC = 0x68
+ DLT_CISCO_IOS = 0x76
+ DLT_CLASS_NETBSD_RAWAF = 0x2240000
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DBUS = 0xe7
+ DLT_DECT = 0xdd
+ DLT_DOCSIS = 0x8f
+ DLT_DVB_CI = 0xeb
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_EPON = 0x103
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FC_2 = 0xe0
+ DLT_FC_2_WITH_FRAME_DELIMS = 0xe1
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_GSMTAP_ABIS = 0xda
+ DLT_GSMTAP_UM = 0xd9
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NOFCS = 0xe6
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_INFINIBAND = 0xf7
+ DLT_IPFILTER = 0x74
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IPMI_HPM_2 = 0x104
+ DLT_IPNET = 0xe2
+ DLT_IPOIB = 0xf2
+ DLT_IPV4 = 0xe4
+ DLT_IPV6 = 0xe5
+ DLT_IP_OVER_FC = 0x7a
+ DLT_ISO_14443 = 0x108
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_ATM_CEMIC = 0xee
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FIBRECHANNEL = 0xea
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_SRX_E2E = 0xe9
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_JUNIPER_VS = 0xe8
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_EVDEV = 0xd8
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_PPP_WITHDIRECTION = 0xa6
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MATCHING_MAX = 0x109
+ DLT_MATCHING_MIN = 0x68
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MPEG_2_TS = 0xf3
+ DLT_MPLS = 0xdb
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_MUX27010 = 0xec
+ DLT_NETANALYZER = 0xf0
+ DLT_NETANALYZER_TRANSPARENT = 0xf1
+ DLT_NETLINK = 0xfd
+ DLT_NFC_LLCP = 0xf5
+ DLT_NFLOG = 0xef
+ DLT_NG40 = 0xf4
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x79
+ DLT_PKTAP = 0x102
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0xe
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PPP_WITH_DIRECTION = 0xa6
+ DLT_PRISM_HEADER = 0x77
+ DLT_PROFIBUS_DL = 0x101
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_RDS = 0x109
+ DLT_REDBACK_SMARTEDGE = 0x20
+ DLT_RIO = 0x7c
+ DLT_RTAC_SERIAL = 0xfa
+ DLT_SCCP = 0x8e
+ DLT_SCTP = 0xf8
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xd
+ DLT_STANAG_5066_D_PDU = 0xed
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USBPCAP = 0xf9
+ DLT_USB_FREEBSD = 0xba
+ DLT_USB_LINUX = 0xbd
+ DLT_USB_LINUX_MMAPPED = 0xdc
+ DLT_USER0 = 0x93
+ DLT_USER1 = 0x94
+ DLT_USER10 = 0x9d
+ DLT_USER11 = 0x9e
+ DLT_USER12 = 0x9f
+ DLT_USER13 = 0xa0
+ DLT_USER14 = 0xa1
+ DLT_USER15 = 0xa2
+ DLT_USER2 = 0x95
+ DLT_USER3 = 0x96
+ DLT_USER4 = 0x97
+ DLT_USER5 = 0x98
+ DLT_USER6 = 0x99
+ DLT_USER7 = 0x9a
+ DLT_USER8 = 0x9b
+ DLT_USER9 = 0x9c
+ DLT_WATTSTOPPER_DLM = 0x107
+ DLT_WIHART = 0xdf
+ DLT_WIRESHARK_UPPER_PDU = 0xfc
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ DLT_ZWAVE_R1_R2 = 0x105
+ DLT_ZWAVE_R3 = 0x106
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EVFILT_AIO = -0x3
+ EVFILT_FS = -0x9
+ EVFILT_LIO = -0xa
+ EVFILT_PROC = -0x5
+ EVFILT_PROCDESC = -0x8
+ EVFILT_READ = -0x1
+ EVFILT_SENDFILE = -0xc
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0xc
+ EVFILT_TIMER = -0x7
+ EVFILT_USER = -0xb
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_DISPATCH = 0x80
+ EV_DROP = 0x1000
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG1 = 0x2000
+ EV_FLAG2 = 0x4000
+ EV_FORCEONESHOT = 0x100
+ EV_ONESHOT = 0x10
+ EV_RECEIPT = 0x40
+ EV_SYSFLAGS = 0xf000
+ EXTA = 0x4b00
+ EXTATTR_NAMESPACE_EMPTY = 0x0
+ EXTATTR_NAMESPACE_SYSTEM = 0x2
+ EXTATTR_NAMESPACE_USER = 0x1
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FLUSHO = 0x800000
+ F_CANCEL = 0x5
+ F_DUP2FD = 0xa
+ F_DUP2FD_CLOEXEC = 0x12
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x11
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0xb
+ F_GETOWN = 0x5
+ F_OGETLK = 0x7
+ F_OK = 0x0
+ F_OSETLK = 0x8
+ F_OSETLKW = 0x9
+ F_RDAHEAD = 0x10
+ F_RDLCK = 0x1
+ F_READAHEAD = 0xf
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0xc
+ F_SETLKW = 0xd
+ F_SETLK_REMOTE = 0xe
+ F_SETOWN = 0x6
+ F_UNLCK = 0x2
+ F_UNLCKSYS = 0x4
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFAN_ARRIVAL = 0x0
+ IFAN_DEPARTURE = 0x1
+ IFF_ALLMULTI = 0x200
+ IFF_ALTPHYS = 0x4000
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x218f52
+ IFF_CANTCONFIG = 0x10000
+ IFF_DEBUG = 0x4
+ IFF_DRV_OACTIVE = 0x400
+ IFF_DRV_RUNNING = 0x40
+ IFF_DYING = 0x200000
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MONITOR = 0x40000
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PPROMISC = 0x20000
+ IFF_PROMISC = 0x100
+ IFF_RENAMING = 0x400000
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_STATICARP = 0x80000
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_BRIDGE = 0xd1
+ IFT_CARP = 0xf8
+ IFT_IEEE1394 = 0x90
+ IFT_INFINIBAND = 0xc7
+ IFT_L2VLAN = 0x87
+ IFT_L3IPVLAN = 0x88
+ IFT_PPP = 0x17
+ IFT_PROPVIRTUAL = 0x35
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LOOPBACKNET = 0x7f
+ IN_RFC3021_MASK = 0xfffffffe
+ IPPROTO_3PC = 0x22
+ IPPROTO_ADFS = 0x44
+ IPPROTO_AH = 0x33
+ IPPROTO_AHIP = 0x3d
+ IPPROTO_APES = 0x63
+ IPPROTO_ARGUS = 0xd
+ IPPROTO_AX25 = 0x5d
+ IPPROTO_BHA = 0x31
+ IPPROTO_BLT = 0x1e
+ IPPROTO_BRSATMON = 0x4c
+ IPPROTO_CARP = 0x70
+ IPPROTO_CFTP = 0x3e
+ IPPROTO_CHAOS = 0x10
+ IPPROTO_CMTP = 0x26
+ IPPROTO_CPHB = 0x49
+ IPPROTO_CPNX = 0x48
+ IPPROTO_DDP = 0x25
+ IPPROTO_DGP = 0x56
+ IPPROTO_DIVERT = 0x102
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_EMCON = 0xe
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GMTP = 0x64
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HELLO = 0x3f
+ IPPROTO_HIP = 0x8b
+ IPPROTO_HMP = 0x14
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IDPR = 0x23
+ IPPROTO_IDRP = 0x2d
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IGP = 0x55
+ IPPROTO_IGRP = 0x58
+ IPPROTO_IL = 0x28
+ IPPROTO_INLSP = 0x34
+ IPPROTO_INP = 0x20
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPCV = 0x47
+ IPPROTO_IPEIP = 0x5e
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPPC = 0x43
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IRTP = 0x1c
+ IPPROTO_KRYPTOLAN = 0x41
+ IPPROTO_LARP = 0x5b
+ IPPROTO_LEAF1 = 0x19
+ IPPROTO_LEAF2 = 0x1a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MEAS = 0x13
+ IPPROTO_MH = 0x87
+ IPPROTO_MHRP = 0x30
+ IPPROTO_MICP = 0x5f
+ IPPROTO_MOBILE = 0x37
+ IPPROTO_MPLS = 0x89
+ IPPROTO_MTP = 0x5c
+ IPPROTO_MUX = 0x12
+ IPPROTO_ND = 0x4d
+ IPPROTO_NHRP = 0x36
+ IPPROTO_NONE = 0x3b
+ IPPROTO_NSP = 0x1f
+ IPPROTO_NVPII = 0xb
+ IPPROTO_OLD_DIVERT = 0xfe
+ IPPROTO_OSPFIGP = 0x59
+ IPPROTO_PFSYNC = 0xf0
+ IPPROTO_PGM = 0x71
+ IPPROTO_PIGP = 0x9
+ IPPROTO_PIM = 0x67
+ IPPROTO_PRM = 0x15
+ IPPROTO_PUP = 0xc
+ IPPROTO_PVP = 0x4b
+ IPPROTO_RAW = 0xff
+ IPPROTO_RCCMON = 0xa
+ IPPROTO_RDP = 0x1b
+ IPPROTO_RESERVED_253 = 0xfd
+ IPPROTO_RESERVED_254 = 0xfe
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_RVD = 0x42
+ IPPROTO_SATEXPAK = 0x40
+ IPPROTO_SATMON = 0x45
+ IPPROTO_SCCSP = 0x60
+ IPPROTO_SCTP = 0x84
+ IPPROTO_SDRP = 0x2a
+ IPPROTO_SEND = 0x103
+ IPPROTO_SEP = 0x21
+ IPPROTO_SHIM6 = 0x8c
+ IPPROTO_SKIP = 0x39
+ IPPROTO_SPACER = 0x7fff
+ IPPROTO_SRPC = 0x5a
+ IPPROTO_ST = 0x7
+ IPPROTO_SVMTP = 0x52
+ IPPROTO_SWIPE = 0x35
+ IPPROTO_TCF = 0x57
+ IPPROTO_TCP = 0x6
+ IPPROTO_TLSP = 0x38
+ IPPROTO_TP = 0x1d
+ IPPROTO_TPXX = 0x27
+ IPPROTO_TRUNK1 = 0x17
+ IPPROTO_TRUNK2 = 0x18
+ IPPROTO_TTP = 0x54
+ IPPROTO_UDP = 0x11
+ IPPROTO_UDPLITE = 0x88
+ IPPROTO_VINES = 0x53
+ IPPROTO_VISA = 0x46
+ IPPROTO_VMTP = 0x51
+ IPPROTO_WBEXPAK = 0x4f
+ IPPROTO_WBMON = 0x4e
+ IPPROTO_WSN = 0x4a
+ IPPROTO_XNET = 0xf
+ IPPROTO_XTP = 0x24
+ IPV6_AUTOFLOWLABEL = 0x3b
+ IPV6_BINDANY = 0x40
+ IPV6_BINDMULTI = 0x41
+ IPV6_BINDV6ONLY = 0x1b
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_DONTFRAG = 0x3e
+ IPV6_DSTOPTS = 0x32
+ IPV6_FLOWID = 0x43
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FLOWTYPE = 0x44
+ IPV6_FRAGTTL = 0x78
+ IPV6_FW_ADD = 0x1e
+ IPV6_FW_DEL = 0x1f
+ IPV6_FW_FLUSH = 0x20
+ IPV6_FW_GET = 0x22
+ IPV6_FW_ZERO = 0x21
+ IPV6_HLIMDEC = 0x1
+ IPV6_HOPLIMIT = 0x2f
+ IPV6_HOPOPTS = 0x31
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXOPTHDR = 0x800
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MAX_GROUP_SRC_FILTER = 0x200
+ IPV6_MAX_MEMBERSHIPS = 0xfff
+ IPV6_MAX_SOCK_SRC_FILTER = 0x80
+ IPV6_MIN_MEMBERSHIPS = 0x1f
+ IPV6_MMTU = 0x500
+ IPV6_MSFILTER = 0x4a
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_NEXTHOP = 0x30
+ IPV6_PATHMTU = 0x2c
+ IPV6_PKTINFO = 0x2e
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_PREFER_TEMPADDR = 0x3f
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVFLOWID = 0x46
+ IPV6_RECVHOPLIMIT = 0x25
+ IPV6_RECVHOPOPTS = 0x27
+ IPV6_RECVPATHMTU = 0x2b
+ IPV6_RECVPKTINFO = 0x24
+ IPV6_RECVRSSBUCKETID = 0x47
+ IPV6_RECVRTHDR = 0x26
+ IPV6_RECVTCLASS = 0x39
+ IPV6_RSSBUCKETID = 0x45
+ IPV6_RSS_LISTEN_BUCKET = 0x42
+ IPV6_RTHDR = 0x33
+ IPV6_RTHDRDSTOPTS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x3d
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_USE_MIN_MTU = 0x2a
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_ADD_SOURCE_MEMBERSHIP = 0x46
+ IP_BINDANY = 0x18
+ IP_BINDMULTI = 0x19
+ IP_BLOCK_SOURCE = 0x48
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DONTFRAG = 0x43
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_DROP_SOURCE_MEMBERSHIP = 0x47
+ IP_DUMMYNET3 = 0x31
+ IP_DUMMYNET_CONFIGURE = 0x3c
+ IP_DUMMYNET_DEL = 0x3d
+ IP_DUMMYNET_FLUSH = 0x3e
+ IP_DUMMYNET_GET = 0x40
+ IP_FLOWID = 0x5a
+ IP_FLOWTYPE = 0x5b
+ IP_FW3 = 0x30
+ IP_FW_ADD = 0x32
+ IP_FW_DEL = 0x33
+ IP_FW_FLUSH = 0x34
+ IP_FW_GET = 0x36
+ IP_FW_NAT_CFG = 0x38
+ IP_FW_NAT_DEL = 0x39
+ IP_FW_NAT_GET_CONFIG = 0x3a
+ IP_FW_NAT_GET_LOG = 0x3b
+ IP_FW_RESETLOG = 0x37
+ IP_FW_TABLE_ADD = 0x28
+ IP_FW_TABLE_DEL = 0x29
+ IP_FW_TABLE_FLUSH = 0x2a
+ IP_FW_TABLE_GETSIZE = 0x2b
+ IP_FW_TABLE_LIST = 0x2c
+ IP_FW_ZERO = 0x35
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x15
+ IP_MAXPACKET = 0xffff
+ IP_MAX_GROUP_SRC_FILTER = 0x200
+ IP_MAX_MEMBERSHIPS = 0xfff
+ IP_MAX_SOCK_MUTE_FILTER = 0x80
+ IP_MAX_SOCK_SRC_FILTER = 0x80
+ IP_MAX_SOURCE_FILTER = 0x400
+ IP_MF = 0x2000
+ IP_MINTTL = 0x42
+ IP_MIN_MEMBERSHIPS = 0x1f
+ IP_MSFILTER = 0x4a
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_MULTICAST_VIF = 0xe
+ IP_OFFMASK = 0x1fff
+ IP_ONESBCAST = 0x17
+ IP_OPTIONS = 0x1
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVFLOWID = 0x5d
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVRETOPTS = 0x6
+ IP_RECVRSSBUCKETID = 0x5e
+ IP_RECVTOS = 0x44
+ IP_RECVTTL = 0x41
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RSSBUCKETID = 0x5c
+ IP_RSS_LISTEN_BUCKET = 0x1a
+ IP_RSVP_OFF = 0x10
+ IP_RSVP_ON = 0xf
+ IP_RSVP_VIF_OFF = 0x12
+ IP_RSVP_VIF_ON = 0x11
+ IP_SENDSRCADDR = 0x7
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ IP_UNBLOCK_SOURCE = 0x49
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_AUTOSYNC = 0x7
+ MADV_CORE = 0x9
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x5
+ MADV_NOCORE = 0x8
+ MADV_NORMAL = 0x0
+ MADV_NOSYNC = 0x6
+ MADV_PROTECT = 0xa
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_WILLNEED = 0x3
+ MAP_ALIGNED_SUPER = 0x1000000
+ MAP_ALIGNMENT_MASK = -0x1000000
+ MAP_ALIGNMENT_SHIFT = 0x18
+ MAP_ANON = 0x1000
+ MAP_ANONYMOUS = 0x1000
+ MAP_COPY = 0x2
+ MAP_EXCL = 0x4000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_GUARD = 0x2000
+ MAP_HASSEMAPHORE = 0x200
+ MAP_NOCORE = 0x20000
+ MAP_NOSYNC = 0x800
+ MAP_PREFAULT_READ = 0x40000
+ MAP_PRIVATE = 0x2
+ MAP_RESERVED0020 = 0x20
+ MAP_RESERVED0040 = 0x40
+ MAP_RESERVED0080 = 0x80
+ MAP_RESERVED0100 = 0x100
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x400
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MSG_CMSG_CLOEXEC = 0x40000
+ MSG_COMPAT = 0x8000
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOF = 0x100
+ MSG_EOR = 0x8
+ MSG_NBIO = 0x4000
+ MSG_NOSIGNAL = 0x20000
+ MSG_NOTIFICATION = 0x2000
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x10
+ MSG_WAITALL = 0x40
+ MSG_WAITFORONE = 0x80000
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x2
+ MS_SYNC = 0x0
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_IFLISTL = 0x5
+ NET_RT_IFMALIST = 0x4
+ NOFLSH = 0x80000000
+ NOKERNINFO = 0x2000000
+ NOTE_ATTRIB = 0x8
+ NOTE_CHILD = 0x4
+ NOTE_CLOSE = 0x100
+ NOTE_CLOSE_WRITE = 0x200
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXTEND = 0x4
+ NOTE_FFAND = 0x40000000
+ NOTE_FFCOPY = 0xc0000000
+ NOTE_FFCTRLMASK = 0xc0000000
+ NOTE_FFLAGSMASK = 0xffffff
+ NOTE_FFNOP = 0x0
+ NOTE_FFOR = 0x80000000
+ NOTE_FILE_POLL = 0x2
+ NOTE_FORK = 0x40000000
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_MSECONDS = 0x2
+ NOTE_NSECONDS = 0x8
+ NOTE_OPEN = 0x80
+ NOTE_PCTRLMASK = 0xf0000000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_READ = 0x400
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_SECONDS = 0x1
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRIGGER = 0x1000000
+ NOTE_USECONDS = 0x4
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ OXTABS = 0x4
+ O_ACCMODE = 0x3
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x100000
+ O_CREAT = 0x200
+ O_DIRECT = 0x10000
+ O_DIRECTORY = 0x20000
+ O_EXCL = 0x800
+ O_EXEC = 0x40000
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_SHLOCK = 0x10
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_TTY_INIT = 0x80000
+ O_VERIFY = 0x200000
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ RLIMIT_AS = 0xa
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_MEMLOCK = 0x6
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_NPROC = 0x7
+ RLIMIT_RSS = 0x5
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x8
+ RTAX_NETMASK = 0x2
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTF_BLACKHOLE = 0x1000
+ RTF_BROADCAST = 0x400000
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_FIXEDMTU = 0x80000
+ RTF_FMASK = 0x1004d808
+ RTF_GATEWAY = 0x2
+ RTF_GWFLAG_COMPAT = 0x80000000
+ RTF_HOST = 0x4
+ RTF_LLDATA = 0x400
+ RTF_LLINFO = 0x400
+ RTF_LOCAL = 0x200000
+ RTF_MODIFIED = 0x20
+ RTF_MULTICAST = 0x800000
+ RTF_PINNED = 0x100000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x40000
+ RTF_REJECT = 0x8
+ RTF_RNH_LOCKED = 0x40000000
+ RTF_STATIC = 0x800
+ RTF_STICKY = 0x10000000
+ RTF_UP = 0x1
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DELMADDR = 0x10
+ RTM_GET = 0x4
+ RTM_IEEE80211 = 0x12
+ RTM_IFANNOUNCE = 0x11
+ RTM_IFINFO = 0xe
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_NEWMADDR = 0xf
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x5
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RTV_WEIGHT = 0x100
+ RT_ALL_FIBS = -0x1
+ RT_BLACKHOLE = 0x40
+ RT_CACHING_CONTEXT = 0x1
+ RT_DEFAULT_FIB = 0x0
+ RT_HAS_GW = 0x80
+ RT_HAS_HEADER = 0x10
+ RT_HAS_HEADER_BIT = 0x4
+ RT_L2_ME = 0x4
+ RT_L2_ME_BIT = 0x2
+ RT_LLE_CACHE = 0x100
+ RT_MAY_LOOP = 0x8
+ RT_MAY_LOOP_BIT = 0x3
+ RT_NORTREF = 0x2
+ RT_REJECT = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ RUSAGE_THREAD = 0x1
+ SCM_BINTIME = 0x4
+ SCM_CREDS = 0x3
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x2
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCAIFADDR = 0x8040691a
+ SIOCAIFGROUP = 0x80246987
+ SIOCATMARK = 0x40047307
+ SIOCDELMULTI = 0x80206932
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFGROUP = 0x80246989
+ SIOCDIFPHYADDR = 0x80206949
+ SIOCGDRVSPEC = 0xc01c697b
+ SIOCGETSGCNT = 0xc0147210
+ SIOCGETVIFCNT = 0xc014720f
+ SIOCGHIWAT = 0x40047301
+ SIOCGHWADDR = 0xc020693e
+ SIOCGI2C = 0xc020693d
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCAP = 0xc020691f
+ SIOCGIFCONF = 0xc0086924
+ SIOCGIFDESCR = 0xc020692a
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFIB = 0xc020695c
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFGMEMB = 0xc024698a
+ SIOCGIFGROUP = 0xc0246988
+ SIOCGIFINDEX = 0xc0206920
+ SIOCGIFMAC = 0xc0206926
+ SIOCGIFMEDIA = 0xc0286938
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc0206933
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206948
+ SIOCGIFPHYS = 0xc0206935
+ SIOCGIFPSRCADDR = 0xc0206947
+ SIOCGIFSTATUS = 0xc331693b
+ SIOCGIFXMEDIA = 0xc028698b
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCGPRIVATE_0 = 0xc0206950
+ SIOCGPRIVATE_1 = 0xc0206951
+ SIOCGTUNFIB = 0xc020695e
+ SIOCIFCREATE = 0xc020697a
+ SIOCIFCREATE2 = 0xc020697c
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc00c6978
+ SIOCSDRVSPEC = 0x801c697b
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFCAP = 0x8020691e
+ SIOCSIFDESCR = 0x80206929
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFIB = 0x8020695d
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFLLADDR = 0x8020693c
+ SIOCSIFMAC = 0x80206927
+ SIOCSIFMEDIA = 0xc0206937
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x80206934
+ SIOCSIFNAME = 0x80206928
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x80406946
+ SIOCSIFPHYS = 0x80206936
+ SIOCSIFRVNET = 0xc020695b
+ SIOCSIFVNET = 0xc020695a
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SIOCSTUNFIB = 0x8020695f
+ SOCK_CLOEXEC = 0x10000000
+ SOCK_DGRAM = 0x2
+ SOCK_MAXADDRLEN = 0xff
+ SOCK_NONBLOCK = 0x20000000
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_ACCEPTFILTER = 0x1000
+ SO_BINTIME = 0x2000
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LABEL = 0x1009
+ SO_LINGER = 0x80
+ SO_LISTENINCQLEN = 0x1013
+ SO_LISTENQLEN = 0x1012
+ SO_LISTENQLIMIT = 0x1011
+ SO_NOSIGPIPE = 0x800
+ SO_NO_DDP = 0x8000
+ SO_NO_OFFLOAD = 0x4000
+ SO_OOBINLINE = 0x100
+ SO_PEERLABEL = 0x1010
+ SO_PROTOCOL = 0x1016
+ SO_PROTOTYPE = 0x1016
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_SETFIB = 0x1014
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_TIMESTAMP = 0x400
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ SO_USER_COOKIE = 0x1015
+ SO_VENDOR = 0x80000000
+ TAB0 = 0x0
+ TAB3 = 0x4
+ TABDLY = 0x4
+ TCIFLUSH = 0x1
+ TCIOFF = 0x3
+ TCIOFLUSH = 0x3
+ TCION = 0x4
+ TCOFLUSH = 0x2
+ TCOOFF = 0x1
+ TCOON = 0x2
+ TCP_CA_NAME_MAX = 0x10
+ TCP_CCALGOOPT = 0x41
+ TCP_CONGESTION = 0x40
+ TCP_FASTOPEN = 0x401
+ TCP_FUNCTION_BLK = 0x2000
+ TCP_FUNCTION_NAME_LEN_MAX = 0x20
+ TCP_INFO = 0x20
+ TCP_KEEPCNT = 0x400
+ TCP_KEEPIDLE = 0x100
+ TCP_KEEPINIT = 0x80
+ TCP_KEEPINTVL = 0x200
+ TCP_MAXBURST = 0x4
+ TCP_MAXHLEN = 0x3c
+ TCP_MAXOLEN = 0x28
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_SACK = 0x4
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MD5SIG = 0x10
+ TCP_MINMSS = 0xd8
+ TCP_MSS = 0x218
+ TCP_NODELAY = 0x1
+ TCP_NOOPT = 0x8
+ TCP_NOPUSH = 0x4
+ TCP_PCAP_IN = 0x1000
+ TCP_PCAP_OUT = 0x800
+ TCP_VENDOR = 0x80000000
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDRAIN = 0x2000745e
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLUSH = 0x80047410
+ TIOCGDRAINWAIT = 0x40047456
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGPGRP = 0x40047477
+ TIOCGPTN = 0x4004740f
+ TIOCGSID = 0x40047463
+ TIOCGWINSZ = 0x40087468
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGDTRWAIT = 0x4004745a
+ TIOCMGET = 0x4004746a
+ TIOCMSDTRWAIT = 0x8004745b
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DCD = 0x40
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCPTMASTER = 0x2000741c
+ TIOCSBRK = 0x2000747b
+ TIOCSCTTY = 0x20007461
+ TIOCSDRAINWAIT = 0x80047457
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSIG = 0x2004745f
+ TIOCSPGRP = 0x80047476
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x20007465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCTIMESTAMP = 0x40107459
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VERASE2 = 0x7
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VTIME = 0x11
+ VWERASE = 0x4
+ WCONTINUED = 0x4
+ WCOREFLAG = 0x80
+ WEXITED = 0x10
+ WLINUXCLONE = 0x80000000
+ WNOHANG = 0x1
+ WNOWAIT = 0x8
+ WSTOPPED = 0x2
+ WTRAPPED = 0x20
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADF = syscall.Errno(0x9)
+ EBADMSG = syscall.Errno(0x59)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x55)
+ ECAPMODE = syscall.Errno(0x5e)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDOOFUS = syscall.Errno(0x58)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x52)
+ EILSEQ = syscall.Errno(0x56)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x60)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5a)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x57)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x5b)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x53)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCAPABLE = syscall.Errno(0x5d)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTRECOVERABLE = syscall.Errno(0x5f)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x2d)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x54)
+ EOWNERDEAD = syscall.Errno(0x60)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x5c)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGLIBRT = syscall.Signal(0x21)
+ SIGLWP = syscall.Signal(0x20)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTHR = syscall.Signal(0x20)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "operation timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "identifier removed",
+ 83: "no message of desired type",
+ 84: "value too large to be stored in data type",
+ 85: "operation canceled",
+ 86: "illegal byte sequence",
+ 87: "attribute not found",
+ 88: "programming error",
+ 89: "bad message",
+ 90: "multihop attempted",
+ 91: "link has been severed",
+ 92: "protocol error",
+ 93: "capabilities insufficient",
+ 94: "not permitted in capability mode",
+ 95: "state not recoverable",
+ 96: "previous owner died",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "suspended (signal)",
+ 18: "suspended",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+ 32: "unknown signal",
+ 33: "unknown signal",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go
new file mode 100644
index 0000000..c12bbb9
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go
@@ -0,0 +1,2187 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include -m32
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build 386,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include -m32 _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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
+ BLKBSZGET = 0x80041270
+ BLKBSZSET = 0x40041271
+ BLKFLSBUF = 0x1261
+ BLKFRAGET = 0x1265
+ BLKFRASET = 0x1264
+ BLKGETSIZE = 0x1260
+ BLKGETSIZE64 = 0x80041272
+ BLKPBSZGET = 0x127b
+ BLKRAGET = 0x1263
+ BLKRASET = 0x1262
+ BLKROGET = 0x125e
+ BLKROSET = 0x125d
+ BLKRRPART = 0x125f
+ BLKSECTGET = 0x1267
+ BLKSECTSET = 0x1266
+ BLKSSZGET = 0x1268
+ 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_RAW_FILTER_MAX = 0x200
+ 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
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x800
+ EFD_SEMAPHORE = 0x1
+ 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_NCSI = 0x88f8
+ 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
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x8000
+ FFDLY = 0x8000
+ FLUSHO = 0x1000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x406
+ F_EXLCK = 0x4
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLEASE = 0x401
+ F_GETLK = 0xc
+ F_GETLK64 = 0xc
+ F_GETOWN = 0x9
+ 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 = 0xd
+ F_SETLK64 = 0xd
+ F_SETLKW = 0xe
+ F_SETLKW64 = 0xe
+ F_SETOWN = 0x8
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ HUPCL = 0x400
+ IBSHIFT = 0x10
+ ICANON = 0x2
+ ICMPV6_FILTER = 0x1
+ ICRNL = 0x100
+ IEXTEN = 0x8000
+ 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 = 0x800
+ 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
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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_32BIT = 0x40
+ MAP_ANON = 0x20
+ MAP_ANONYMOUS = 0x20
+ MAP_DENYWRITE = 0x800
+ MAP_EXECUTABLE = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_GROWSDOWN = 0x100
+ MAP_HUGETLB = 0x40000
+ MAP_HUGE_MASK = 0x3f
+ MAP_HUGE_SHIFT = 0x1a
+ MAP_LOCKED = 0x2000
+ MAP_NONBLOCK = 0x10000
+ MAP_NORESERVE = 0x4000
+ MAP_POPULATE = 0x8000
+ MAP_PRIVATE = 0x2
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x20000
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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 = 0x400
+ O_ASYNC = 0x2000
+ O_CLOEXEC = 0x80000
+ O_CREAT = 0x40
+ O_DIRECT = 0x4000
+ O_DIRECTORY = 0x10000
+ O_DSYNC = 0x1000
+ O_EXCL = 0x80
+ O_FSYNC = 0x101000
+ O_LARGEFILE = 0x8000
+ O_NDELAY = 0x800
+ O_NOATIME = 0x40000
+ O_NOCTTY = 0x100
+ O_NOFOLLOW = 0x20000
+ O_NONBLOCK = 0x800
+ O_PATH = 0x200000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x101000
+ O_SYNC = 0x101000
+ 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
+ PERF_EVENT_IOC_DISABLE = 0x2401
+ PERF_EVENT_IOC_ENABLE = 0x2400
+ PERF_EVENT_IOC_ID = 0x80042407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409
+ PERF_EVENT_IOC_PERIOD = 0x40082404
+ PERF_EVENT_IOC_REFRESH = 0x2402
+ PERF_EVENT_IOC_RESET = 0x2403
+ PERF_EVENT_IOC_SET_BPF = 0x40042408
+ PERF_EVENT_IOC_SET_FILTER = 0x40042406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x2405
+ 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_GETFPXREGS = 0x12
+ PTRACE_GETREGS = 0xc
+ PTRACE_GETREGSET = 0x4204
+ PTRACE_GETSIGINFO = 0x4202
+ PTRACE_GETSIGMASK = 0x420a
+ PTRACE_GET_THREAD_AREA = 0x19
+ 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_PEEKSIGINFO = 0x4209
+ PTRACE_PEEKSIGINFO_SHARED = 0x1
+ PTRACE_PEEKTEXT = 0x1
+ PTRACE_PEEKUSR = 0x3
+ PTRACE_POKEDATA = 0x5
+ PTRACE_POKETEXT = 0x4
+ PTRACE_POKEUSR = 0x6
+ PTRACE_SECCOMP_GET_FILTER = 0x420c
+ PTRACE_SEIZE = 0x4206
+ PTRACE_SETFPREGS = 0xf
+ PTRACE_SETFPXREGS = 0x13
+ PTRACE_SETOPTIONS = 0x4200
+ PTRACE_SETREGS = 0xd
+ PTRACE_SETREGSET = 0x4205
+ PTRACE_SETSIGINFO = 0x4203
+ PTRACE_SETSIGMASK = 0x420b
+ PTRACE_SET_THREAD_AREA = 0x1a
+ PTRACE_SINGLEBLOCK = 0x21
+ PTRACE_SINGLESTEP = 0x9
+ PTRACE_SYSCALL = 0x18
+ PTRACE_SYSEMU = 0x1f
+ PTRACE_SYSEMU_SINGLESTEP = 0x20
+ PTRACE_TRACEME = 0x0
+ RLIMIT_AS = 0x9
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x8
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x7
+ RLIMIT_NPROC = 0x6
+ RLIMIT_RSS = 0x5
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x8905
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x8904
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x541b
+ SIOCOUTQ = 0x5411
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x8902
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x2
+ SOCK_IOC_TYPE = 0x89
+ SOCK_NONBLOCK = 0x800
+ SOCK_PACKET = 0xa
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ 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 = 0x1
+ SOL_TCP = 0x6
+ SOL_TIPC = 0x10f
+ SOL_X25 = 0x106
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x1e
+ 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 = 0x6
+ SO_BSDCOMPAT = 0xe
+ SO_BUSY_POLL = 0x2e
+ SO_CNX_ADVICE = 0x35
+ SO_DEBUG = 0x1
+ SO_DETACH_BPF = 0x1b
+ SO_DETACH_FILTER = 0x1b
+ SO_DOMAIN = 0x27
+ SO_DONTROUTE = 0x5
+ SO_ERROR = 0x4
+ SO_GET_FILTER = 0x1a
+ SO_INCOMING_CPU = 0x31
+ SO_KEEPALIVE = 0x9
+ SO_LINGER = 0xd
+ SO_LOCK_FILTER = 0x2c
+ SO_MARK = 0x24
+ SO_MAX_PACING_RATE = 0x2f
+ SO_NOFCS = 0x2b
+ SO_NO_CHECK = 0xb
+ SO_OOBINLINE = 0xa
+ SO_PASSCRED = 0x10
+ SO_PASSSEC = 0x22
+ SO_PEEK_OFF = 0x2a
+ SO_PEERCRED = 0x11
+ SO_PEERNAME = 0x1c
+ SO_PEERSEC = 0x1f
+ SO_PRIORITY = 0xc
+ SO_PROTOCOL = 0x26
+ SO_RCVBUF = 0x8
+ SO_RCVBUFFORCE = 0x21
+ SO_RCVLOWAT = 0x12
+ SO_RCVTIMEO = 0x14
+ SO_REUSEADDR = 0x2
+ SO_REUSEPORT = 0xf
+ 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 = 0x7
+ SO_SNDBUFFORCE = 0x20
+ SO_SNDLOWAT = 0x13
+ SO_SNDTIMEO = 0x15
+ SO_TIMESTAMP = 0x1d
+ SO_TIMESTAMPING = 0x25
+ SO_TIMESTAMPNS = 0x23
+ SO_TYPE = 0x3
+ SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ TCFLSH = 0x540b
+ TCGETA = 0x5405
+ TCGETS = 0x5401
+ TCGETS2 = 0x802c542a
+ TCGETX = 0x5432
+ 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_REPAIR_WINDOW = 0x1d
+ 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 = 0x2
+ TCSBRK = 0x5409
+ TCSBRKP = 0x5425
+ TCSETA = 0x5406
+ TCSETAF = 0x5408
+ TCSETAW = 0x5407
+ TCSETS = 0x5402
+ TCSETS2 = 0x402c542b
+ TCSETSF = 0x5404
+ TCSETSF2 = 0x402c542d
+ TCSETSW = 0x5403
+ TCSETSW2 = 0x402c542c
+ TCSETX = 0x5433
+ TCSETXF = 0x5434
+ TCSETXW = 0x5435
+ TCXONC = 0x540a
+ TIOCCBRK = 0x5428
+ TIOCCONS = 0x541d
+ TIOCEXCL = 0x540c
+ TIOCGDEV = 0x80045432
+ TIOCGETD = 0x5424
+ TIOCGEXCL = 0x80045440
+ TIOCGICOUNT = 0x545d
+ TIOCGLCKTRMIOS = 0x5456
+ TIOCGPGRP = 0x540f
+ TIOCGPKT = 0x80045438
+ TIOCGPTLCK = 0x80045439
+ TIOCGPTN = 0x80045430
+ TIOCGRS485 = 0x542e
+ TIOCGSERIAL = 0x541e
+ TIOCGSID = 0x5429
+ TIOCGSOFTCAR = 0x5419
+ TIOCGWINSZ = 0x5413
+ TIOCINQ = 0x541b
+ TIOCLINUX = 0x541c
+ TIOCMBIC = 0x5417
+ TIOCMBIS = 0x5416
+ TIOCMGET = 0x5415
+ TIOCMIWAIT = 0x545c
+ TIOCMSET = 0x5418
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x5422
+ TIOCNXCL = 0x540d
+ TIOCOUTQ = 0x5411
+ TIOCPKT = 0x5420
+ 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 = 0x540e
+ TIOCSERCONFIG = 0x5453
+ TIOCSERGETLSR = 0x5459
+ TIOCSERGETMULTI = 0x545a
+ TIOCSERGSTRUCT = 0x5458
+ TIOCSERGWILD = 0x5454
+ TIOCSERSETMULTI = 0x545b
+ TIOCSERSWILD = 0x5455
+ TIOCSER_TEMT = 0x1
+ TIOCSETD = 0x5423
+ TIOCSIG = 0x40045436
+ TIOCSLCKTRMIOS = 0x5457
+ TIOCSPGRP = 0x5410
+ TIOCSPTLCK = 0x40045431
+ TIOCSRS485 = 0x542f
+ TIOCSSERIAL = 0x541f
+ TIOCSSOFTCAR = 0x541a
+ TIOCSTI = 0x5412
+ TIOCSWINSZ = 0x5414
+ TIOCVHANGUP = 0x5437
+ TOSTOP = 0x100
+ TS_COMM_LEN = 0x20
+ TUNATTACHFILTER = 0x400854d5
+ TUNDETACHFILTER = 0x400854d6
+ TUNGETFEATURES = 0x800454cf
+ TUNGETFILTER = 0x800854db
+ TUNGETIFF = 0x800454d2
+ TUNGETSNDBUF = 0x800454d3
+ TUNGETVNETBE = 0x800454df
+ TUNGETVNETHDRSZ = 0x800454d7
+ TUNGETVNETLE = 0x800454dd
+ TUNSETDEBUG = 0x400454c9
+ TUNSETGROUP = 0x400454ce
+ TUNSETIFF = 0x400454ca
+ TUNSETIFINDEX = 0x400454da
+ TUNSETLINK = 0x400454cd
+ TUNSETNOCSUM = 0x400454c8
+ TUNSETOFFLOAD = 0x400454d0
+ TUNSETOWNER = 0x400454cc
+ TUNSETPERSIST = 0x400454cb
+ TUNSETQUEUE = 0x400454d9
+ TUNSETSNDBUF = 0x400454d4
+ TUNSETTXFILTER = 0x400454d1
+ TUNSETVNETBE = 0x400454de
+ TUNSETVNETHDRSZ = 0x400454d8
+ TUNSETVNETLE = 0x400454dc
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0xd
+ VEOF = 0x4
+ VEOL = 0xb
+ VEOL2 = 0x10
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x6
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ VQUIT = 0x1
+ VREPRINT = 0xc
+ VSTART = 0x8
+ VSTOP = 0x9
+ VSUSP = 0xa
+ VSWTC = 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
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 0x2
+ XCASE = 0x4
+ XTABS = 0x1800
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x62)
+ EADDRNOTAVAIL = syscall.Errno(0x63)
+ EADV = syscall.Errno(0x44)
+ EAFNOSUPPORT = syscall.Errno(0x61)
+ EAGAIN = syscall.Errno(0xb)
+ EALREADY = syscall.Errno(0x72)
+ EBADE = syscall.Errno(0x34)
+ EBADF = syscall.Errno(0x9)
+ EBADFD = syscall.Errno(0x4d)
+ EBADMSG = syscall.Errno(0x4a)
+ EBADR = syscall.Errno(0x35)
+ EBADRQC = syscall.Errno(0x38)
+ EBADSLT = syscall.Errno(0x39)
+ EBFONT = syscall.Errno(0x3b)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x7d)
+ ECHILD = syscall.Errno(0xa)
+ ECHRNG = syscall.Errno(0x2c)
+ ECOMM = syscall.Errno(0x46)
+ ECONNABORTED = syscall.Errno(0x67)
+ ECONNREFUSED = syscall.Errno(0x6f)
+ ECONNRESET = syscall.Errno(0x68)
+ EDEADLK = syscall.Errno(0x23)
+ EDEADLOCK = syscall.Errno(0x23)
+ EDESTADDRREQ = syscall.Errno(0x59)
+ EDOM = syscall.Errno(0x21)
+ EDOTDOT = syscall.Errno(0x49)
+ EDQUOT = syscall.Errno(0x7a)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EHOSTDOWN = syscall.Errno(0x70)
+ EHOSTUNREACH = syscall.Errno(0x71)
+ EHWPOISON = syscall.Errno(0x85)
+ EIDRM = syscall.Errno(0x2b)
+ EILSEQ = syscall.Errno(0x54)
+ EINPROGRESS = syscall.Errno(0x73)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x6a)
+ EISDIR = syscall.Errno(0x15)
+ EISNAM = syscall.Errno(0x78)
+ EKEYEXPIRED = syscall.Errno(0x7f)
+ EKEYREJECTED = syscall.Errno(0x81)
+ EKEYREVOKED = syscall.Errno(0x80)
+ EL2HLT = syscall.Errno(0x33)
+ EL2NSYNC = syscall.Errno(0x2d)
+ EL3HLT = syscall.Errno(0x2e)
+ EL3RST = syscall.Errno(0x2f)
+ ELIBACC = syscall.Errno(0x4f)
+ ELIBBAD = syscall.Errno(0x50)
+ ELIBEXEC = syscall.Errno(0x53)
+ ELIBMAX = syscall.Errno(0x52)
+ ELIBSCN = syscall.Errno(0x51)
+ ELNRNG = syscall.Errno(0x30)
+ ELOOP = syscall.Errno(0x28)
+ EMEDIUMTYPE = syscall.Errno(0x7c)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x5a)
+ EMULTIHOP = syscall.Errno(0x48)
+ ENAMETOOLONG = syscall.Errno(0x24)
+ ENAVAIL = syscall.Errno(0x77)
+ ENETDOWN = syscall.Errno(0x64)
+ ENETRESET = syscall.Errno(0x66)
+ ENETUNREACH = syscall.Errno(0x65)
+ ENFILE = syscall.Errno(0x17)
+ ENOANO = syscall.Errno(0x37)
+ ENOBUFS = syscall.Errno(0x69)
+ ENOCSI = syscall.Errno(0x32)
+ ENODATA = syscall.Errno(0x3d)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOKEY = syscall.Errno(0x7e)
+ ENOLCK = syscall.Errno(0x25)
+ ENOLINK = syscall.Errno(0x43)
+ ENOMEDIUM = syscall.Errno(0x7b)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x2a)
+ ENONET = syscall.Errno(0x40)
+ ENOPKG = syscall.Errno(0x41)
+ ENOPROTOOPT = syscall.Errno(0x5c)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x3f)
+ ENOSTR = syscall.Errno(0x3c)
+ ENOSYS = syscall.Errno(0x26)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x6b)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x27)
+ ENOTNAM = syscall.Errno(0x76)
+ ENOTRECOVERABLE = syscall.Errno(0x83)
+ ENOTSOCK = syscall.Errno(0x58)
+ ENOTSUP = syscall.Errno(0x5f)
+ ENOTTY = syscall.Errno(0x19)
+ ENOTUNIQ = syscall.Errno(0x4c)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x5f)
+ EOVERFLOW = syscall.Errno(0x4b)
+ EOWNERDEAD = syscall.Errno(0x82)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x60)
+ EPIPE = syscall.Errno(0x20)
+ EPROTO = syscall.Errno(0x47)
+ EPROTONOSUPPORT = syscall.Errno(0x5d)
+ EPROTOTYPE = syscall.Errno(0x5b)
+ ERANGE = syscall.Errno(0x22)
+ EREMCHG = syscall.Errno(0x4e)
+ EREMOTE = syscall.Errno(0x42)
+ EREMOTEIO = syscall.Errno(0x79)
+ ERESTART = syscall.Errno(0x55)
+ ERFKILL = syscall.Errno(0x84)
+ EROFS = syscall.Errno(0x1e)
+ ESHUTDOWN = syscall.Errno(0x6c)
+ ESOCKTNOSUPPORT = syscall.Errno(0x5e)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESRMNT = syscall.Errno(0x45)
+ ESTALE = syscall.Errno(0x74)
+ ESTRPIPE = syscall.Errno(0x56)
+ ETIME = syscall.Errno(0x3e)
+ ETIMEDOUT = syscall.Errno(0x6e)
+ ETOOMANYREFS = syscall.Errno(0x6d)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUCLEAN = syscall.Errno(0x75)
+ EUNATCH = syscall.Errno(0x31)
+ EUSERS = syscall.Errno(0x57)
+ EWOULDBLOCK = syscall.Errno(0xb)
+ EXDEV = syscall.Errno(0x12)
+ EXFULL = syscall.Errno(0x36)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0x7)
+ SIGCHLD = syscall.Signal(0x11)
+ SIGCLD = syscall.Signal(0x11)
+ SIGCONT = syscall.Signal(0x12)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x1d)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPOLL = syscall.Signal(0x1d)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x1e)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTKFLT = syscall.Signal(0x10)
+ SIGSTOP = syscall.Signal(0x13)
+ SIGSYS = syscall.Signal(0x1f)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x14)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGUNUSED = syscall.Signal(0x1f)
+ SIGURG = syscall.Signal(0x17)
+ SIGUSR1 = syscall.Signal(0xa)
+ SIGUSR2 = syscall.Signal(0xc)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "resource deadlock avoided",
+ 36: "file name too long",
+ 37: "no locks available",
+ 38: "function not implemented",
+ 39: "directory not empty",
+ 40: "too many levels of symbolic links",
+ 42: "no message of desired type",
+ 43: "identifier removed",
+ 44: "channel number out of range",
+ 45: "level 2 not synchronized",
+ 46: "level 3 halted",
+ 47: "level 3 reset",
+ 48: "link number out of range",
+ 49: "protocol driver not attached",
+ 50: "no CSI structure available",
+ 51: "level 2 halted",
+ 52: "invalid exchange",
+ 53: "invalid request descriptor",
+ 54: "exchange full",
+ 55: "no anode",
+ 56: "invalid request code",
+ 57: "invalid slot",
+ 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",
+ 72: "multihop attempted",
+ 73: "RFS specific error",
+ 74: "bad message",
+ 75: "value too large for defined data type",
+ 76: "name not unique on network",
+ 77: "file descriptor in bad state",
+ 78: "remote address changed",
+ 79: "can not access a needed shared library",
+ 80: "accessing a corrupted shared library",
+ 81: ".lib section in a.out corrupted",
+ 82: "attempting to link in too many shared libraries",
+ 83: "cannot exec a shared library directly",
+ 84: "invalid or incomplete multibyte or wide character",
+ 85: "interrupted system call should be restarted",
+ 86: "streams pipe error",
+ 87: "too many users",
+ 88: "socket operation on non-socket",
+ 89: "destination address required",
+ 90: "message too long",
+ 91: "protocol wrong type for socket",
+ 92: "protocol not available",
+ 93: "protocol not supported",
+ 94: "socket type not supported",
+ 95: "operation not supported",
+ 96: "protocol family not supported",
+ 97: "address family not supported by protocol",
+ 98: "address already in use",
+ 99: "cannot assign requested address",
+ 100: "network is down",
+ 101: "network is unreachable",
+ 102: "network dropped connection on reset",
+ 103: "software caused connection abort",
+ 104: "connection reset by peer",
+ 105: "no buffer space available",
+ 106: "transport endpoint is already connected",
+ 107: "transport endpoint is not connected",
+ 108: "cannot send after transport endpoint shutdown",
+ 109: "too many references: cannot splice",
+ 110: "connection timed out",
+ 111: "connection refused",
+ 112: "host is down",
+ 113: "no route to host",
+ 114: "operation already in progress",
+ 115: "operation now in progress",
+ 116: "stale file handle",
+ 117: "structure needs cleaning",
+ 118: "not a XENIX named type file",
+ 119: "no XENIX semaphores available",
+ 120: "is a named type file",
+ 121: "remote I/O error",
+ 122: "disk quota exceeded",
+ 123: "no medium found",
+ 124: "wrong medium type",
+ 125: "operation canceled",
+ 126: "required key not available",
+ 127: "key has expired",
+ 128: "key has been revoked",
+ 129: "key was rejected by service",
+ 130: "owner died",
+ 131: "state not recoverable",
+ 132: "operation not possible due to RF-kill",
+ 133: "memory page has hardware error",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/breakpoint trap",
+ 6: "aborted",
+ 7: "bus error",
+ 8: "floating point exception",
+ 9: "killed",
+ 10: "user defined signal 1",
+ 11: "segmentation fault",
+ 12: "user defined signal 2",
+ 13: "broken pipe",
+ 14: "alarm clock",
+ 15: "terminated",
+ 16: "stack fault",
+ 17: "child exited",
+ 18: "continued",
+ 19: "stopped (signal)",
+ 20: "stopped",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "urgent I/O condition",
+ 24: "CPU time limit exceeded",
+ 25: "file size limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window changed",
+ 29: "I/O possible",
+ 30: "power failure",
+ 31: "bad system call",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go
new file mode 100644
index 0000000..fc0a79a
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go
@@ -0,0 +1,2188 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include -m64
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include -m64 _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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
+ BLKBSZGET = 0x80081270
+ BLKBSZSET = 0x40081271
+ BLKFLSBUF = 0x1261
+ BLKFRAGET = 0x1265
+ BLKFRASET = 0x1264
+ BLKGETSIZE = 0x1260
+ BLKGETSIZE64 = 0x80081272
+ BLKPBSZGET = 0x127b
+ BLKRAGET = 0x1263
+ BLKRASET = 0x1262
+ BLKROGET = 0x125e
+ BLKROSET = 0x125d
+ BLKRRPART = 0x125f
+ BLKSECTGET = 0x1267
+ BLKSECTSET = 0x1266
+ BLKSSZGET = 0x1268
+ 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_RAW_FILTER_MAX = 0x200
+ 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
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x800
+ EFD_SEMAPHORE = 0x1
+ 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_NCSI = 0x88f8
+ 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
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x8000
+ FFDLY = 0x8000
+ FLUSHO = 0x1000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x406
+ F_EXLCK = 0x4
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLEASE = 0x401
+ F_GETLK = 0x5
+ F_GETLK64 = 0x5
+ F_GETOWN = 0x9
+ 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 = 0x6
+ F_SETLK64 = 0x6
+ F_SETLKW = 0x7
+ F_SETLKW64 = 0x7
+ F_SETOWN = 0x8
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ HUPCL = 0x400
+ IBSHIFT = 0x10
+ ICANON = 0x2
+ ICMPV6_FILTER = 0x1
+ ICRNL = 0x100
+ IEXTEN = 0x8000
+ 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 = 0x800
+ 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
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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_32BIT = 0x40
+ MAP_ANON = 0x20
+ MAP_ANONYMOUS = 0x20
+ MAP_DENYWRITE = 0x800
+ MAP_EXECUTABLE = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_GROWSDOWN = 0x100
+ MAP_HUGETLB = 0x40000
+ MAP_HUGE_MASK = 0x3f
+ MAP_HUGE_SHIFT = 0x1a
+ MAP_LOCKED = 0x2000
+ MAP_NONBLOCK = 0x10000
+ MAP_NORESERVE = 0x4000
+ MAP_POPULATE = 0x8000
+ MAP_PRIVATE = 0x2
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x20000
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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 = 0x400
+ O_ASYNC = 0x2000
+ O_CLOEXEC = 0x80000
+ O_CREAT = 0x40
+ O_DIRECT = 0x4000
+ O_DIRECTORY = 0x10000
+ O_DSYNC = 0x1000
+ O_EXCL = 0x80
+ O_FSYNC = 0x101000
+ O_LARGEFILE = 0x0
+ O_NDELAY = 0x800
+ O_NOATIME = 0x40000
+ O_NOCTTY = 0x100
+ O_NOFOLLOW = 0x20000
+ O_NONBLOCK = 0x800
+ O_PATH = 0x200000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x101000
+ O_SYNC = 0x101000
+ 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
+ PERF_EVENT_IOC_DISABLE = 0x2401
+ PERF_EVENT_IOC_ENABLE = 0x2400
+ PERF_EVENT_IOC_ID = 0x80082407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409
+ PERF_EVENT_IOC_PERIOD = 0x40082404
+ PERF_EVENT_IOC_REFRESH = 0x2402
+ PERF_EVENT_IOC_RESET = 0x2403
+ PERF_EVENT_IOC_SET_BPF = 0x40042408
+ PERF_EVENT_IOC_SET_FILTER = 0x40082406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x2405
+ 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 = -0x1
+ 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_ARCH_PRCTL = 0x1e
+ 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_GETFPXREGS = 0x12
+ PTRACE_GETREGS = 0xc
+ PTRACE_GETREGSET = 0x4204
+ PTRACE_GETSIGINFO = 0x4202
+ PTRACE_GETSIGMASK = 0x420a
+ PTRACE_GET_THREAD_AREA = 0x19
+ 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_PEEKSIGINFO = 0x4209
+ PTRACE_PEEKSIGINFO_SHARED = 0x1
+ PTRACE_PEEKTEXT = 0x1
+ PTRACE_PEEKUSR = 0x3
+ PTRACE_POKEDATA = 0x5
+ PTRACE_POKETEXT = 0x4
+ PTRACE_POKEUSR = 0x6
+ PTRACE_SECCOMP_GET_FILTER = 0x420c
+ PTRACE_SEIZE = 0x4206
+ PTRACE_SETFPREGS = 0xf
+ PTRACE_SETFPXREGS = 0x13
+ PTRACE_SETOPTIONS = 0x4200
+ PTRACE_SETREGS = 0xd
+ PTRACE_SETREGSET = 0x4205
+ PTRACE_SETSIGINFO = 0x4203
+ PTRACE_SETSIGMASK = 0x420b
+ PTRACE_SET_THREAD_AREA = 0x1a
+ PTRACE_SINGLEBLOCK = 0x21
+ PTRACE_SINGLESTEP = 0x9
+ PTRACE_SYSCALL = 0x18
+ PTRACE_SYSEMU = 0x1f
+ PTRACE_SYSEMU_SINGLESTEP = 0x20
+ PTRACE_TRACEME = 0x0
+ RLIMIT_AS = 0x9
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x8
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x7
+ RLIMIT_NPROC = 0x6
+ RLIMIT_RSS = 0x5
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x8905
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x8904
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x541b
+ SIOCOUTQ = 0x5411
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x8902
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x2
+ SOCK_IOC_TYPE = 0x89
+ SOCK_NONBLOCK = 0x800
+ SOCK_PACKET = 0xa
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ 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 = 0x1
+ SOL_TCP = 0x6
+ SOL_TIPC = 0x10f
+ SOL_X25 = 0x106
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x1e
+ 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 = 0x6
+ SO_BSDCOMPAT = 0xe
+ SO_BUSY_POLL = 0x2e
+ SO_CNX_ADVICE = 0x35
+ SO_DEBUG = 0x1
+ SO_DETACH_BPF = 0x1b
+ SO_DETACH_FILTER = 0x1b
+ SO_DOMAIN = 0x27
+ SO_DONTROUTE = 0x5
+ SO_ERROR = 0x4
+ SO_GET_FILTER = 0x1a
+ SO_INCOMING_CPU = 0x31
+ SO_KEEPALIVE = 0x9
+ SO_LINGER = 0xd
+ SO_LOCK_FILTER = 0x2c
+ SO_MARK = 0x24
+ SO_MAX_PACING_RATE = 0x2f
+ SO_NOFCS = 0x2b
+ SO_NO_CHECK = 0xb
+ SO_OOBINLINE = 0xa
+ SO_PASSCRED = 0x10
+ SO_PASSSEC = 0x22
+ SO_PEEK_OFF = 0x2a
+ SO_PEERCRED = 0x11
+ SO_PEERNAME = 0x1c
+ SO_PEERSEC = 0x1f
+ SO_PRIORITY = 0xc
+ SO_PROTOCOL = 0x26
+ SO_RCVBUF = 0x8
+ SO_RCVBUFFORCE = 0x21
+ SO_RCVLOWAT = 0x12
+ SO_RCVTIMEO = 0x14
+ SO_REUSEADDR = 0x2
+ SO_REUSEPORT = 0xf
+ 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 = 0x7
+ SO_SNDBUFFORCE = 0x20
+ SO_SNDLOWAT = 0x13
+ SO_SNDTIMEO = 0x15
+ SO_TIMESTAMP = 0x1d
+ SO_TIMESTAMPING = 0x25
+ SO_TIMESTAMPNS = 0x23
+ SO_TYPE = 0x3
+ SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ TCFLSH = 0x540b
+ TCGETA = 0x5405
+ TCGETS = 0x5401
+ TCGETS2 = 0x802c542a
+ TCGETX = 0x5432
+ 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_REPAIR_WINDOW = 0x1d
+ 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 = 0x2
+ TCSBRK = 0x5409
+ TCSBRKP = 0x5425
+ TCSETA = 0x5406
+ TCSETAF = 0x5408
+ TCSETAW = 0x5407
+ TCSETS = 0x5402
+ TCSETS2 = 0x402c542b
+ TCSETSF = 0x5404
+ TCSETSF2 = 0x402c542d
+ TCSETSW = 0x5403
+ TCSETSW2 = 0x402c542c
+ TCSETX = 0x5433
+ TCSETXF = 0x5434
+ TCSETXW = 0x5435
+ TCXONC = 0x540a
+ TIOCCBRK = 0x5428
+ TIOCCONS = 0x541d
+ TIOCEXCL = 0x540c
+ TIOCGDEV = 0x80045432
+ TIOCGETD = 0x5424
+ TIOCGEXCL = 0x80045440
+ TIOCGICOUNT = 0x545d
+ TIOCGLCKTRMIOS = 0x5456
+ TIOCGPGRP = 0x540f
+ TIOCGPKT = 0x80045438
+ TIOCGPTLCK = 0x80045439
+ TIOCGPTN = 0x80045430
+ TIOCGRS485 = 0x542e
+ TIOCGSERIAL = 0x541e
+ TIOCGSID = 0x5429
+ TIOCGSOFTCAR = 0x5419
+ TIOCGWINSZ = 0x5413
+ TIOCINQ = 0x541b
+ TIOCLINUX = 0x541c
+ TIOCMBIC = 0x5417
+ TIOCMBIS = 0x5416
+ TIOCMGET = 0x5415
+ TIOCMIWAIT = 0x545c
+ TIOCMSET = 0x5418
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x5422
+ TIOCNXCL = 0x540d
+ TIOCOUTQ = 0x5411
+ TIOCPKT = 0x5420
+ 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 = 0x540e
+ TIOCSERCONFIG = 0x5453
+ TIOCSERGETLSR = 0x5459
+ TIOCSERGETMULTI = 0x545a
+ TIOCSERGSTRUCT = 0x5458
+ TIOCSERGWILD = 0x5454
+ TIOCSERSETMULTI = 0x545b
+ TIOCSERSWILD = 0x5455
+ TIOCSER_TEMT = 0x1
+ TIOCSETD = 0x5423
+ TIOCSIG = 0x40045436
+ TIOCSLCKTRMIOS = 0x5457
+ TIOCSPGRP = 0x5410
+ TIOCSPTLCK = 0x40045431
+ TIOCSRS485 = 0x542f
+ TIOCSSERIAL = 0x541f
+ TIOCSSOFTCAR = 0x541a
+ TIOCSTI = 0x5412
+ TIOCSWINSZ = 0x5414
+ TIOCVHANGUP = 0x5437
+ TOSTOP = 0x100
+ TS_COMM_LEN = 0x20
+ TUNATTACHFILTER = 0x401054d5
+ TUNDETACHFILTER = 0x401054d6
+ TUNGETFEATURES = 0x800454cf
+ TUNGETFILTER = 0x801054db
+ TUNGETIFF = 0x800454d2
+ TUNGETSNDBUF = 0x800454d3
+ TUNGETVNETBE = 0x800454df
+ TUNGETVNETHDRSZ = 0x800454d7
+ TUNGETVNETLE = 0x800454dd
+ TUNSETDEBUG = 0x400454c9
+ TUNSETGROUP = 0x400454ce
+ TUNSETIFF = 0x400454ca
+ TUNSETIFINDEX = 0x400454da
+ TUNSETLINK = 0x400454cd
+ TUNSETNOCSUM = 0x400454c8
+ TUNSETOFFLOAD = 0x400454d0
+ TUNSETOWNER = 0x400454cc
+ TUNSETPERSIST = 0x400454cb
+ TUNSETQUEUE = 0x400454d9
+ TUNSETSNDBUF = 0x400454d4
+ TUNSETTXFILTER = 0x400454d1
+ TUNSETVNETBE = 0x400454de
+ TUNSETVNETHDRSZ = 0x400454d8
+ TUNSETVNETLE = 0x400454dc
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0xd
+ VEOF = 0x4
+ VEOL = 0xb
+ VEOL2 = 0x10
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x6
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ VQUIT = 0x1
+ VREPRINT = 0xc
+ VSTART = 0x8
+ VSTOP = 0x9
+ VSUSP = 0xa
+ VSWTC = 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 = 0x40
+ WSTOPPED = 0x2
+ WUNTRACED = 0x2
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 0x2
+ XCASE = 0x4
+ XTABS = 0x1800
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x62)
+ EADDRNOTAVAIL = syscall.Errno(0x63)
+ EADV = syscall.Errno(0x44)
+ EAFNOSUPPORT = syscall.Errno(0x61)
+ EAGAIN = syscall.Errno(0xb)
+ EALREADY = syscall.Errno(0x72)
+ EBADE = syscall.Errno(0x34)
+ EBADF = syscall.Errno(0x9)
+ EBADFD = syscall.Errno(0x4d)
+ EBADMSG = syscall.Errno(0x4a)
+ EBADR = syscall.Errno(0x35)
+ EBADRQC = syscall.Errno(0x38)
+ EBADSLT = syscall.Errno(0x39)
+ EBFONT = syscall.Errno(0x3b)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x7d)
+ ECHILD = syscall.Errno(0xa)
+ ECHRNG = syscall.Errno(0x2c)
+ ECOMM = syscall.Errno(0x46)
+ ECONNABORTED = syscall.Errno(0x67)
+ ECONNREFUSED = syscall.Errno(0x6f)
+ ECONNRESET = syscall.Errno(0x68)
+ EDEADLK = syscall.Errno(0x23)
+ EDEADLOCK = syscall.Errno(0x23)
+ EDESTADDRREQ = syscall.Errno(0x59)
+ EDOM = syscall.Errno(0x21)
+ EDOTDOT = syscall.Errno(0x49)
+ EDQUOT = syscall.Errno(0x7a)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EHOSTDOWN = syscall.Errno(0x70)
+ EHOSTUNREACH = syscall.Errno(0x71)
+ EHWPOISON = syscall.Errno(0x85)
+ EIDRM = syscall.Errno(0x2b)
+ EILSEQ = syscall.Errno(0x54)
+ EINPROGRESS = syscall.Errno(0x73)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x6a)
+ EISDIR = syscall.Errno(0x15)
+ EISNAM = syscall.Errno(0x78)
+ EKEYEXPIRED = syscall.Errno(0x7f)
+ EKEYREJECTED = syscall.Errno(0x81)
+ EKEYREVOKED = syscall.Errno(0x80)
+ EL2HLT = syscall.Errno(0x33)
+ EL2NSYNC = syscall.Errno(0x2d)
+ EL3HLT = syscall.Errno(0x2e)
+ EL3RST = syscall.Errno(0x2f)
+ ELIBACC = syscall.Errno(0x4f)
+ ELIBBAD = syscall.Errno(0x50)
+ ELIBEXEC = syscall.Errno(0x53)
+ ELIBMAX = syscall.Errno(0x52)
+ ELIBSCN = syscall.Errno(0x51)
+ ELNRNG = syscall.Errno(0x30)
+ ELOOP = syscall.Errno(0x28)
+ EMEDIUMTYPE = syscall.Errno(0x7c)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x5a)
+ EMULTIHOP = syscall.Errno(0x48)
+ ENAMETOOLONG = syscall.Errno(0x24)
+ ENAVAIL = syscall.Errno(0x77)
+ ENETDOWN = syscall.Errno(0x64)
+ ENETRESET = syscall.Errno(0x66)
+ ENETUNREACH = syscall.Errno(0x65)
+ ENFILE = syscall.Errno(0x17)
+ ENOANO = syscall.Errno(0x37)
+ ENOBUFS = syscall.Errno(0x69)
+ ENOCSI = syscall.Errno(0x32)
+ ENODATA = syscall.Errno(0x3d)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOKEY = syscall.Errno(0x7e)
+ ENOLCK = syscall.Errno(0x25)
+ ENOLINK = syscall.Errno(0x43)
+ ENOMEDIUM = syscall.Errno(0x7b)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x2a)
+ ENONET = syscall.Errno(0x40)
+ ENOPKG = syscall.Errno(0x41)
+ ENOPROTOOPT = syscall.Errno(0x5c)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x3f)
+ ENOSTR = syscall.Errno(0x3c)
+ ENOSYS = syscall.Errno(0x26)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x6b)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x27)
+ ENOTNAM = syscall.Errno(0x76)
+ ENOTRECOVERABLE = syscall.Errno(0x83)
+ ENOTSOCK = syscall.Errno(0x58)
+ ENOTSUP = syscall.Errno(0x5f)
+ ENOTTY = syscall.Errno(0x19)
+ ENOTUNIQ = syscall.Errno(0x4c)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x5f)
+ EOVERFLOW = syscall.Errno(0x4b)
+ EOWNERDEAD = syscall.Errno(0x82)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x60)
+ EPIPE = syscall.Errno(0x20)
+ EPROTO = syscall.Errno(0x47)
+ EPROTONOSUPPORT = syscall.Errno(0x5d)
+ EPROTOTYPE = syscall.Errno(0x5b)
+ ERANGE = syscall.Errno(0x22)
+ EREMCHG = syscall.Errno(0x4e)
+ EREMOTE = syscall.Errno(0x42)
+ EREMOTEIO = syscall.Errno(0x79)
+ ERESTART = syscall.Errno(0x55)
+ ERFKILL = syscall.Errno(0x84)
+ EROFS = syscall.Errno(0x1e)
+ ESHUTDOWN = syscall.Errno(0x6c)
+ ESOCKTNOSUPPORT = syscall.Errno(0x5e)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESRMNT = syscall.Errno(0x45)
+ ESTALE = syscall.Errno(0x74)
+ ESTRPIPE = syscall.Errno(0x56)
+ ETIME = syscall.Errno(0x3e)
+ ETIMEDOUT = syscall.Errno(0x6e)
+ ETOOMANYREFS = syscall.Errno(0x6d)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUCLEAN = syscall.Errno(0x75)
+ EUNATCH = syscall.Errno(0x31)
+ EUSERS = syscall.Errno(0x57)
+ EWOULDBLOCK = syscall.Errno(0xb)
+ EXDEV = syscall.Errno(0x12)
+ EXFULL = syscall.Errno(0x36)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0x7)
+ SIGCHLD = syscall.Signal(0x11)
+ SIGCLD = syscall.Signal(0x11)
+ SIGCONT = syscall.Signal(0x12)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x1d)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPOLL = syscall.Signal(0x1d)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x1e)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTKFLT = syscall.Signal(0x10)
+ SIGSTOP = syscall.Signal(0x13)
+ SIGSYS = syscall.Signal(0x1f)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x14)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGUNUSED = syscall.Signal(0x1f)
+ SIGURG = syscall.Signal(0x17)
+ SIGUSR1 = syscall.Signal(0xa)
+ SIGUSR2 = syscall.Signal(0xc)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "resource deadlock avoided",
+ 36: "file name too long",
+ 37: "no locks available",
+ 38: "function not implemented",
+ 39: "directory not empty",
+ 40: "too many levels of symbolic links",
+ 42: "no message of desired type",
+ 43: "identifier removed",
+ 44: "channel number out of range",
+ 45: "level 2 not synchronized",
+ 46: "level 3 halted",
+ 47: "level 3 reset",
+ 48: "link number out of range",
+ 49: "protocol driver not attached",
+ 50: "no CSI structure available",
+ 51: "level 2 halted",
+ 52: "invalid exchange",
+ 53: "invalid request descriptor",
+ 54: "exchange full",
+ 55: "no anode",
+ 56: "invalid request code",
+ 57: "invalid slot",
+ 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",
+ 72: "multihop attempted",
+ 73: "RFS specific error",
+ 74: "bad message",
+ 75: "value too large for defined data type",
+ 76: "name not unique on network",
+ 77: "file descriptor in bad state",
+ 78: "remote address changed",
+ 79: "can not access a needed shared library",
+ 80: "accessing a corrupted shared library",
+ 81: ".lib section in a.out corrupted",
+ 82: "attempting to link in too many shared libraries",
+ 83: "cannot exec a shared library directly",
+ 84: "invalid or incomplete multibyte or wide character",
+ 85: "interrupted system call should be restarted",
+ 86: "streams pipe error",
+ 87: "too many users",
+ 88: "socket operation on non-socket",
+ 89: "destination address required",
+ 90: "message too long",
+ 91: "protocol wrong type for socket",
+ 92: "protocol not available",
+ 93: "protocol not supported",
+ 94: "socket type not supported",
+ 95: "operation not supported",
+ 96: "protocol family not supported",
+ 97: "address family not supported by protocol",
+ 98: "address already in use",
+ 99: "cannot assign requested address",
+ 100: "network is down",
+ 101: "network is unreachable",
+ 102: "network dropped connection on reset",
+ 103: "software caused connection abort",
+ 104: "connection reset by peer",
+ 105: "no buffer space available",
+ 106: "transport endpoint is already connected",
+ 107: "transport endpoint is not connected",
+ 108: "cannot send after transport endpoint shutdown",
+ 109: "too many references: cannot splice",
+ 110: "connection timed out",
+ 111: "connection refused",
+ 112: "host is down",
+ 113: "no route to host",
+ 114: "operation already in progress",
+ 115: "operation now in progress",
+ 116: "stale file handle",
+ 117: "structure needs cleaning",
+ 118: "not a XENIX named type file",
+ 119: "no XENIX semaphores available",
+ 120: "is a named type file",
+ 121: "remote I/O error",
+ 122: "disk quota exceeded",
+ 123: "no medium found",
+ 124: "wrong medium type",
+ 125: "operation canceled",
+ 126: "required key not available",
+ 127: "key has expired",
+ 128: "key has been revoked",
+ 129: "key was rejected by service",
+ 130: "owner died",
+ 131: "state not recoverable",
+ 132: "operation not possible due to RF-kill",
+ 133: "memory page has hardware error",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/breakpoint trap",
+ 6: "aborted",
+ 7: "bus error",
+ 8: "floating point exception",
+ 9: "killed",
+ 10: "user defined signal 1",
+ 11: "segmentation fault",
+ 12: "user defined signal 2",
+ 13: "broken pipe",
+ 14: "alarm clock",
+ 15: "terminated",
+ 16: "stack fault",
+ 17: "child exited",
+ 18: "continued",
+ 19: "stopped (signal)",
+ 20: "stopped",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "urgent I/O condition",
+ 24: "CPU time limit exceeded",
+ 25: "file size limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window changed",
+ 29: "I/O possible",
+ 30: "power failure",
+ 31: "bad system call",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go
new file mode 100644
index 0000000..a6657d3
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go
@@ -0,0 +1,2192 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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
+ BLKBSZGET = 0x80041270
+ BLKBSZSET = 0x40041271
+ BLKFLSBUF = 0x1261
+ BLKFRAGET = 0x1265
+ BLKFRASET = 0x1264
+ BLKGETSIZE = 0x1260
+ BLKGETSIZE64 = 0x80041272
+ BLKPBSZGET = 0x127b
+ BLKRAGET = 0x1263
+ BLKRASET = 0x1262
+ BLKROGET = 0x125e
+ BLKROSET = 0x125d
+ BLKRRPART = 0x125f
+ BLKSECTGET = 0x1267
+ BLKSECTSET = 0x1266
+ BLKSSZGET = 0x1268
+ 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_RAW_FILTER_MAX = 0x200
+ 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
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x800
+ EFD_SEMAPHORE = 0x1
+ 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_NCSI = 0x88f8
+ 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
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x8000
+ FFDLY = 0x8000
+ FLUSHO = 0x1000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x406
+ F_EXLCK = 0x4
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLEASE = 0x401
+ F_GETLK = 0xc
+ F_GETLK64 = 0xc
+ F_GETOWN = 0x9
+ 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 = 0xd
+ F_SETLK64 = 0xd
+ F_SETLKW = 0xe
+ F_SETLKW64 = 0xe
+ F_SETOWN = 0x8
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ HUPCL = 0x400
+ IBSHIFT = 0x10
+ ICANON = 0x2
+ ICMPV6_FILTER = 0x1
+ ICRNL = 0x100
+ IEXTEN = 0x8000
+ 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 = 0x800
+ 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
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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 = 0x20
+ MAP_ANONYMOUS = 0x20
+ MAP_DENYWRITE = 0x800
+ MAP_EXECUTABLE = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_GROWSDOWN = 0x100
+ MAP_HUGETLB = 0x40000
+ MAP_HUGE_MASK = 0x3f
+ MAP_HUGE_SHIFT = 0x1a
+ MAP_LOCKED = 0x2000
+ MAP_NONBLOCK = 0x10000
+ MAP_NORESERVE = 0x4000
+ MAP_POPULATE = 0x8000
+ MAP_PRIVATE = 0x2
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x20000
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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 = 0x400
+ O_ASYNC = 0x2000
+ O_CLOEXEC = 0x80000
+ O_CREAT = 0x40
+ O_DIRECT = 0x10000
+ O_DIRECTORY = 0x4000
+ O_DSYNC = 0x1000
+ O_EXCL = 0x80
+ O_FSYNC = 0x101000
+ O_LARGEFILE = 0x20000
+ O_NDELAY = 0x800
+ O_NOATIME = 0x40000
+ O_NOCTTY = 0x100
+ O_NOFOLLOW = 0x8000
+ O_NONBLOCK = 0x800
+ O_PATH = 0x200000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x101000
+ O_SYNC = 0x101000
+ O_TMPFILE = 0x404000
+ 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
+ PERF_EVENT_IOC_DISABLE = 0x2401
+ PERF_EVENT_IOC_ENABLE = 0x2400
+ PERF_EVENT_IOC_ID = 0x80042407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409
+ PERF_EVENT_IOC_PERIOD = 0x40082404
+ PERF_EVENT_IOC_REFRESH = 0x2402
+ PERF_EVENT_IOC_RESET = 0x2403
+ PERF_EVENT_IOC_SET_BPF = 0x40042408
+ PERF_EVENT_IOC_SET_FILTER = 0x40042406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x2405
+ 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_GETCRUNCHREGS = 0x19
+ PTRACE_GETEVENTMSG = 0x4201
+ PTRACE_GETFPREGS = 0xe
+ PTRACE_GETHBPREGS = 0x1d
+ PTRACE_GETREGS = 0xc
+ PTRACE_GETREGSET = 0x4204
+ PTRACE_GETSIGINFO = 0x4202
+ PTRACE_GETSIGMASK = 0x420a
+ PTRACE_GETVFPREGS = 0x1b
+ PTRACE_GETWMMXREGS = 0x12
+ PTRACE_GET_THREAD_AREA = 0x16
+ 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_PEEKSIGINFO = 0x4209
+ PTRACE_PEEKSIGINFO_SHARED = 0x1
+ PTRACE_PEEKTEXT = 0x1
+ PTRACE_PEEKUSR = 0x3
+ PTRACE_POKEDATA = 0x5
+ PTRACE_POKETEXT = 0x4
+ PTRACE_POKEUSR = 0x6
+ PTRACE_SECCOMP_GET_FILTER = 0x420c
+ PTRACE_SEIZE = 0x4206
+ PTRACE_SETCRUNCHREGS = 0x1a
+ PTRACE_SETFPREGS = 0xf
+ PTRACE_SETHBPREGS = 0x1e
+ PTRACE_SETOPTIONS = 0x4200
+ PTRACE_SETREGS = 0xd
+ PTRACE_SETREGSET = 0x4205
+ PTRACE_SETSIGINFO = 0x4203
+ PTRACE_SETSIGMASK = 0x420b
+ PTRACE_SETVFPREGS = 0x1c
+ PTRACE_SETWMMXREGS = 0x13
+ PTRACE_SET_SYSCALL = 0x17
+ PTRACE_SINGLESTEP = 0x9
+ PTRACE_SYSCALL = 0x18
+ PTRACE_TRACEME = 0x0
+ PT_DATA_ADDR = 0x10004
+ PT_TEXT_ADDR = 0x10000
+ PT_TEXT_END_ADDR = 0x10008
+ RLIMIT_AS = 0x9
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x8
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x7
+ RLIMIT_NPROC = 0x6
+ RLIMIT_RSS = 0x5
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x8905
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x8904
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x541b
+ SIOCOUTQ = 0x5411
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x8902
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x2
+ SOCK_IOC_TYPE = 0x89
+ SOCK_NONBLOCK = 0x800
+ SOCK_PACKET = 0xa
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ 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 = 0x1
+ SOL_TCP = 0x6
+ SOL_TIPC = 0x10f
+ SOL_X25 = 0x106
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x1e
+ 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 = 0x6
+ SO_BSDCOMPAT = 0xe
+ SO_BUSY_POLL = 0x2e
+ SO_CNX_ADVICE = 0x35
+ SO_DEBUG = 0x1
+ SO_DETACH_BPF = 0x1b
+ SO_DETACH_FILTER = 0x1b
+ SO_DOMAIN = 0x27
+ SO_DONTROUTE = 0x5
+ SO_ERROR = 0x4
+ SO_GET_FILTER = 0x1a
+ SO_INCOMING_CPU = 0x31
+ SO_KEEPALIVE = 0x9
+ SO_LINGER = 0xd
+ SO_LOCK_FILTER = 0x2c
+ SO_MARK = 0x24
+ SO_MAX_PACING_RATE = 0x2f
+ SO_NOFCS = 0x2b
+ SO_NO_CHECK = 0xb
+ SO_OOBINLINE = 0xa
+ SO_PASSCRED = 0x10
+ SO_PASSSEC = 0x22
+ SO_PEEK_OFF = 0x2a
+ SO_PEERCRED = 0x11
+ SO_PEERNAME = 0x1c
+ SO_PEERSEC = 0x1f
+ SO_PRIORITY = 0xc
+ SO_PROTOCOL = 0x26
+ SO_RCVBUF = 0x8
+ SO_RCVBUFFORCE = 0x21
+ SO_RCVLOWAT = 0x12
+ SO_RCVTIMEO = 0x14
+ SO_REUSEADDR = 0x2
+ SO_REUSEPORT = 0xf
+ 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 = 0x7
+ SO_SNDBUFFORCE = 0x20
+ SO_SNDLOWAT = 0x13
+ SO_SNDTIMEO = 0x15
+ SO_TIMESTAMP = 0x1d
+ SO_TIMESTAMPING = 0x25
+ SO_TIMESTAMPNS = 0x23
+ SO_TYPE = 0x3
+ SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ TCFLSH = 0x540b
+ TCGETA = 0x5405
+ TCGETS = 0x5401
+ TCGETS2 = 0x802c542a
+ TCGETX = 0x5432
+ 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_REPAIR_WINDOW = 0x1d
+ 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 = 0x2
+ TCSBRK = 0x5409
+ TCSBRKP = 0x5425
+ TCSETA = 0x5406
+ TCSETAF = 0x5408
+ TCSETAW = 0x5407
+ TCSETS = 0x5402
+ TCSETS2 = 0x402c542b
+ TCSETSF = 0x5404
+ TCSETSF2 = 0x402c542d
+ TCSETSW = 0x5403
+ TCSETSW2 = 0x402c542c
+ TCSETX = 0x5433
+ TCSETXF = 0x5434
+ TCSETXW = 0x5435
+ TCXONC = 0x540a
+ TIOCCBRK = 0x5428
+ TIOCCONS = 0x541d
+ TIOCEXCL = 0x540c
+ TIOCGDEV = 0x80045432
+ TIOCGETD = 0x5424
+ TIOCGEXCL = 0x80045440
+ TIOCGICOUNT = 0x545d
+ TIOCGLCKTRMIOS = 0x5456
+ TIOCGPGRP = 0x540f
+ TIOCGPKT = 0x80045438
+ TIOCGPTLCK = 0x80045439
+ TIOCGPTN = 0x80045430
+ TIOCGRS485 = 0x542e
+ TIOCGSERIAL = 0x541e
+ TIOCGSID = 0x5429
+ TIOCGSOFTCAR = 0x5419
+ TIOCGWINSZ = 0x5413
+ TIOCINQ = 0x541b
+ TIOCLINUX = 0x541c
+ TIOCMBIC = 0x5417
+ TIOCMBIS = 0x5416
+ TIOCMGET = 0x5415
+ TIOCMIWAIT = 0x545c
+ TIOCMSET = 0x5418
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x5422
+ TIOCNXCL = 0x540d
+ TIOCOUTQ = 0x5411
+ TIOCPKT = 0x5420
+ 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 = 0x540e
+ TIOCSERCONFIG = 0x5453
+ TIOCSERGETLSR = 0x5459
+ TIOCSERGETMULTI = 0x545a
+ TIOCSERGSTRUCT = 0x5458
+ TIOCSERGWILD = 0x5454
+ TIOCSERSETMULTI = 0x545b
+ TIOCSERSWILD = 0x5455
+ TIOCSER_TEMT = 0x1
+ TIOCSETD = 0x5423
+ TIOCSIG = 0x40045436
+ TIOCSLCKTRMIOS = 0x5457
+ TIOCSPGRP = 0x5410
+ TIOCSPTLCK = 0x40045431
+ TIOCSRS485 = 0x542f
+ TIOCSSERIAL = 0x541f
+ TIOCSSOFTCAR = 0x541a
+ TIOCSTI = 0x5412
+ TIOCSWINSZ = 0x5414
+ TIOCVHANGUP = 0x5437
+ TOSTOP = 0x100
+ TS_COMM_LEN = 0x20
+ TUNATTACHFILTER = 0x400854d5
+ TUNDETACHFILTER = 0x400854d6
+ TUNGETFEATURES = 0x800454cf
+ TUNGETFILTER = 0x800854db
+ TUNGETIFF = 0x800454d2
+ TUNGETSNDBUF = 0x800454d3
+ TUNGETVNETBE = 0x800454df
+ TUNGETVNETHDRSZ = 0x800454d7
+ TUNGETVNETLE = 0x800454dd
+ TUNSETDEBUG = 0x400454c9
+ TUNSETGROUP = 0x400454ce
+ TUNSETIFF = 0x400454ca
+ TUNSETIFINDEX = 0x400454da
+ TUNSETLINK = 0x400454cd
+ TUNSETNOCSUM = 0x400454c8
+ TUNSETOFFLOAD = 0x400454d0
+ TUNSETOWNER = 0x400454cc
+ TUNSETPERSIST = 0x400454cb
+ TUNSETQUEUE = 0x400454d9
+ TUNSETSNDBUF = 0x400454d4
+ TUNSETTXFILTER = 0x400454d1
+ TUNSETVNETBE = 0x400454de
+ TUNSETVNETHDRSZ = 0x400454d8
+ TUNSETVNETLE = 0x400454dc
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0xd
+ VEOF = 0x4
+ VEOL = 0xb
+ VEOL2 = 0x10
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x6
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ VQUIT = 0x1
+ VREPRINT = 0xc
+ VSTART = 0x8
+ VSTOP = 0x9
+ VSUSP = 0xa
+ VSWTC = 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
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 0x2
+ XCASE = 0x4
+ XTABS = 0x1800
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x62)
+ EADDRNOTAVAIL = syscall.Errno(0x63)
+ EADV = syscall.Errno(0x44)
+ EAFNOSUPPORT = syscall.Errno(0x61)
+ EAGAIN = syscall.Errno(0xb)
+ EALREADY = syscall.Errno(0x72)
+ EBADE = syscall.Errno(0x34)
+ EBADF = syscall.Errno(0x9)
+ EBADFD = syscall.Errno(0x4d)
+ EBADMSG = syscall.Errno(0x4a)
+ EBADR = syscall.Errno(0x35)
+ EBADRQC = syscall.Errno(0x38)
+ EBADSLT = syscall.Errno(0x39)
+ EBFONT = syscall.Errno(0x3b)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x7d)
+ ECHILD = syscall.Errno(0xa)
+ ECHRNG = syscall.Errno(0x2c)
+ ECOMM = syscall.Errno(0x46)
+ ECONNABORTED = syscall.Errno(0x67)
+ ECONNREFUSED = syscall.Errno(0x6f)
+ ECONNRESET = syscall.Errno(0x68)
+ EDEADLK = syscall.Errno(0x23)
+ EDEADLOCK = syscall.Errno(0x23)
+ EDESTADDRREQ = syscall.Errno(0x59)
+ EDOM = syscall.Errno(0x21)
+ EDOTDOT = syscall.Errno(0x49)
+ EDQUOT = syscall.Errno(0x7a)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EHOSTDOWN = syscall.Errno(0x70)
+ EHOSTUNREACH = syscall.Errno(0x71)
+ EHWPOISON = syscall.Errno(0x85)
+ EIDRM = syscall.Errno(0x2b)
+ EILSEQ = syscall.Errno(0x54)
+ EINPROGRESS = syscall.Errno(0x73)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x6a)
+ EISDIR = syscall.Errno(0x15)
+ EISNAM = syscall.Errno(0x78)
+ EKEYEXPIRED = syscall.Errno(0x7f)
+ EKEYREJECTED = syscall.Errno(0x81)
+ EKEYREVOKED = syscall.Errno(0x80)
+ EL2HLT = syscall.Errno(0x33)
+ EL2NSYNC = syscall.Errno(0x2d)
+ EL3HLT = syscall.Errno(0x2e)
+ EL3RST = syscall.Errno(0x2f)
+ ELIBACC = syscall.Errno(0x4f)
+ ELIBBAD = syscall.Errno(0x50)
+ ELIBEXEC = syscall.Errno(0x53)
+ ELIBMAX = syscall.Errno(0x52)
+ ELIBSCN = syscall.Errno(0x51)
+ ELNRNG = syscall.Errno(0x30)
+ ELOOP = syscall.Errno(0x28)
+ EMEDIUMTYPE = syscall.Errno(0x7c)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x5a)
+ EMULTIHOP = syscall.Errno(0x48)
+ ENAMETOOLONG = syscall.Errno(0x24)
+ ENAVAIL = syscall.Errno(0x77)
+ ENETDOWN = syscall.Errno(0x64)
+ ENETRESET = syscall.Errno(0x66)
+ ENETUNREACH = syscall.Errno(0x65)
+ ENFILE = syscall.Errno(0x17)
+ ENOANO = syscall.Errno(0x37)
+ ENOBUFS = syscall.Errno(0x69)
+ ENOCSI = syscall.Errno(0x32)
+ ENODATA = syscall.Errno(0x3d)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOKEY = syscall.Errno(0x7e)
+ ENOLCK = syscall.Errno(0x25)
+ ENOLINK = syscall.Errno(0x43)
+ ENOMEDIUM = syscall.Errno(0x7b)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x2a)
+ ENONET = syscall.Errno(0x40)
+ ENOPKG = syscall.Errno(0x41)
+ ENOPROTOOPT = syscall.Errno(0x5c)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x3f)
+ ENOSTR = syscall.Errno(0x3c)
+ ENOSYS = syscall.Errno(0x26)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x6b)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x27)
+ ENOTNAM = syscall.Errno(0x76)
+ ENOTRECOVERABLE = syscall.Errno(0x83)
+ ENOTSOCK = syscall.Errno(0x58)
+ ENOTSUP = syscall.Errno(0x5f)
+ ENOTTY = syscall.Errno(0x19)
+ ENOTUNIQ = syscall.Errno(0x4c)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x5f)
+ EOVERFLOW = syscall.Errno(0x4b)
+ EOWNERDEAD = syscall.Errno(0x82)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x60)
+ EPIPE = syscall.Errno(0x20)
+ EPROTO = syscall.Errno(0x47)
+ EPROTONOSUPPORT = syscall.Errno(0x5d)
+ EPROTOTYPE = syscall.Errno(0x5b)
+ ERANGE = syscall.Errno(0x22)
+ EREMCHG = syscall.Errno(0x4e)
+ EREMOTE = syscall.Errno(0x42)
+ EREMOTEIO = syscall.Errno(0x79)
+ ERESTART = syscall.Errno(0x55)
+ ERFKILL = syscall.Errno(0x84)
+ EROFS = syscall.Errno(0x1e)
+ ESHUTDOWN = syscall.Errno(0x6c)
+ ESOCKTNOSUPPORT = syscall.Errno(0x5e)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESRMNT = syscall.Errno(0x45)
+ ESTALE = syscall.Errno(0x74)
+ ESTRPIPE = syscall.Errno(0x56)
+ ETIME = syscall.Errno(0x3e)
+ ETIMEDOUT = syscall.Errno(0x6e)
+ ETOOMANYREFS = syscall.Errno(0x6d)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUCLEAN = syscall.Errno(0x75)
+ EUNATCH = syscall.Errno(0x31)
+ EUSERS = syscall.Errno(0x57)
+ EWOULDBLOCK = syscall.Errno(0xb)
+ EXDEV = syscall.Errno(0x12)
+ EXFULL = syscall.Errno(0x36)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0x7)
+ SIGCHLD = syscall.Signal(0x11)
+ SIGCLD = syscall.Signal(0x11)
+ SIGCONT = syscall.Signal(0x12)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x1d)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPOLL = syscall.Signal(0x1d)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x1e)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTKFLT = syscall.Signal(0x10)
+ SIGSTOP = syscall.Signal(0x13)
+ SIGSYS = syscall.Signal(0x1f)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x14)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGUNUSED = syscall.Signal(0x1f)
+ SIGURG = syscall.Signal(0x17)
+ SIGUSR1 = syscall.Signal(0xa)
+ SIGUSR2 = syscall.Signal(0xc)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "resource deadlock avoided",
+ 36: "file name too long",
+ 37: "no locks available",
+ 38: "function not implemented",
+ 39: "directory not empty",
+ 40: "too many levels of symbolic links",
+ 42: "no message of desired type",
+ 43: "identifier removed",
+ 44: "channel number out of range",
+ 45: "level 2 not synchronized",
+ 46: "level 3 halted",
+ 47: "level 3 reset",
+ 48: "link number out of range",
+ 49: "protocol driver not attached",
+ 50: "no CSI structure available",
+ 51: "level 2 halted",
+ 52: "invalid exchange",
+ 53: "invalid request descriptor",
+ 54: "exchange full",
+ 55: "no anode",
+ 56: "invalid request code",
+ 57: "invalid slot",
+ 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",
+ 72: "multihop attempted",
+ 73: "RFS specific error",
+ 74: "bad message",
+ 75: "value too large for defined data type",
+ 76: "name not unique on network",
+ 77: "file descriptor in bad state",
+ 78: "remote address changed",
+ 79: "can not access a needed shared library",
+ 80: "accessing a corrupted shared library",
+ 81: ".lib section in a.out corrupted",
+ 82: "attempting to link in too many shared libraries",
+ 83: "cannot exec a shared library directly",
+ 84: "invalid or incomplete multibyte or wide character",
+ 85: "interrupted system call should be restarted",
+ 86: "streams pipe error",
+ 87: "too many users",
+ 88: "socket operation on non-socket",
+ 89: "destination address required",
+ 90: "message too long",
+ 91: "protocol wrong type for socket",
+ 92: "protocol not available",
+ 93: "protocol not supported",
+ 94: "socket type not supported",
+ 95: "operation not supported",
+ 96: "protocol family not supported",
+ 97: "address family not supported by protocol",
+ 98: "address already in use",
+ 99: "cannot assign requested address",
+ 100: "network is down",
+ 101: "network is unreachable",
+ 102: "network dropped connection on reset",
+ 103: "software caused connection abort",
+ 104: "connection reset by peer",
+ 105: "no buffer space available",
+ 106: "transport endpoint is already connected",
+ 107: "transport endpoint is not connected",
+ 108: "cannot send after transport endpoint shutdown",
+ 109: "too many references: cannot splice",
+ 110: "connection timed out",
+ 111: "connection refused",
+ 112: "host is down",
+ 113: "no route to host",
+ 114: "operation already in progress",
+ 115: "operation now in progress",
+ 116: "stale file handle",
+ 117: "structure needs cleaning",
+ 118: "not a XENIX named type file",
+ 119: "no XENIX semaphores available",
+ 120: "is a named type file",
+ 121: "remote I/O error",
+ 122: "disk quota exceeded",
+ 123: "no medium found",
+ 124: "wrong medium type",
+ 125: "operation canceled",
+ 126: "required key not available",
+ 127: "key has expired",
+ 128: "key has been revoked",
+ 129: "key was rejected by service",
+ 130: "owner died",
+ 131: "state not recoverable",
+ 132: "operation not possible due to RF-kill",
+ 133: "memory page has hardware error",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/breakpoint trap",
+ 6: "aborted",
+ 7: "bus error",
+ 8: "floating point exception",
+ 9: "killed",
+ 10: "user defined signal 1",
+ 11: "segmentation fault",
+ 12: "user defined signal 2",
+ 13: "broken pipe",
+ 14: "alarm clock",
+ 15: "terminated",
+ 16: "stack fault",
+ 17: "child exited",
+ 18: "continued",
+ 19: "stopped (signal)",
+ 20: "stopped",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "urgent I/O condition",
+ 24: "CPU time limit exceeded",
+ 25: "file size limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window changed",
+ 29: "I/O possible",
+ 30: "power failure",
+ 31: "bad system call",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go
new file mode 100644
index 0000000..ad9b8b2
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go
@@ -0,0 +1,2177 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include -fsigned-char
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm64,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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
+ BLKBSZGET = 0x80081270
+ BLKBSZSET = 0x40081271
+ BLKFLSBUF = 0x1261
+ BLKFRAGET = 0x1265
+ BLKFRASET = 0x1264
+ BLKGETSIZE = 0x1260
+ BLKGETSIZE64 = 0x80081272
+ BLKPBSZGET = 0x127b
+ BLKRAGET = 0x1263
+ BLKRASET = 0x1262
+ BLKROGET = 0x125e
+ BLKROSET = 0x125d
+ BLKRRPART = 0x125f
+ BLKSECTGET = 0x1267
+ BLKSECTSET = 0x1266
+ BLKSSZGET = 0x1268
+ 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_RAW_FILTER_MAX = 0x200
+ 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
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x800
+ EFD_SEMAPHORE = 0x1
+ 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
+ ESR_MAGIC = 0x45535201
+ 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_NCSI = 0x88f8
+ 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
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x8000
+ FFDLY = 0x8000
+ FLUSHO = 0x1000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x406
+ F_EXLCK = 0x4
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLEASE = 0x401
+ F_GETLK = 0x5
+ F_GETLK64 = 0x5
+ F_GETOWN = 0x9
+ 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 = 0x6
+ F_SETLK64 = 0x6
+ F_SETLKW = 0x7
+ F_SETLKW64 = 0x7
+ F_SETOWN = 0x8
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ HUPCL = 0x400
+ IBSHIFT = 0x10
+ ICANON = 0x2
+ ICMPV6_FILTER = 0x1
+ ICRNL = 0x100
+ IEXTEN = 0x8000
+ 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 = 0x800
+ 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
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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 = 0x20
+ MAP_ANONYMOUS = 0x20
+ MAP_DENYWRITE = 0x800
+ MAP_EXECUTABLE = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_GROWSDOWN = 0x100
+ MAP_HUGETLB = 0x40000
+ MAP_HUGE_MASK = 0x3f
+ MAP_HUGE_SHIFT = 0x1a
+ MAP_LOCKED = 0x2000
+ MAP_NONBLOCK = 0x10000
+ MAP_NORESERVE = 0x4000
+ MAP_POPULATE = 0x8000
+ MAP_PRIVATE = 0x2
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x20000
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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 = 0x400
+ O_ASYNC = 0x2000
+ O_CLOEXEC = 0x80000
+ O_CREAT = 0x40
+ O_DIRECT = 0x10000
+ O_DIRECTORY = 0x4000
+ O_DSYNC = 0x1000
+ O_EXCL = 0x80
+ O_FSYNC = 0x101000
+ O_LARGEFILE = 0x0
+ O_NDELAY = 0x800
+ O_NOATIME = 0x40000
+ O_NOCTTY = 0x100
+ O_NOFOLLOW = 0x8000
+ O_NONBLOCK = 0x800
+ O_PATH = 0x200000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x101000
+ O_SYNC = 0x101000
+ O_TMPFILE = 0x404000
+ 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
+ PERF_EVENT_IOC_DISABLE = 0x2401
+ PERF_EVENT_IOC_ENABLE = 0x2400
+ PERF_EVENT_IOC_ID = 0x80082407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409
+ PERF_EVENT_IOC_PERIOD = 0x40082404
+ PERF_EVENT_IOC_REFRESH = 0x2402
+ PERF_EVENT_IOC_RESET = 0x2403
+ PERF_EVENT_IOC_SET_BPF = 0x40042408
+ PERF_EVENT_IOC_SET_FILTER = 0x40082406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x2405
+ 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 = -0x1
+ 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_GETREGS = 0xc
+ PTRACE_GETREGSET = 0x4204
+ PTRACE_GETSIGINFO = 0x4202
+ PTRACE_GETSIGMASK = 0x420a
+ PTRACE_INTERRUPT = 0x4207
+ PTRACE_KILL = 0x8
+ PTRACE_LISTEN = 0x4208
+ 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_PEEKSIGINFO = 0x4209
+ PTRACE_PEEKSIGINFO_SHARED = 0x1
+ PTRACE_PEEKTEXT = 0x1
+ PTRACE_PEEKUSR = 0x3
+ PTRACE_POKEDATA = 0x5
+ PTRACE_POKETEXT = 0x4
+ PTRACE_POKEUSR = 0x6
+ PTRACE_SECCOMP_GET_FILTER = 0x420c
+ PTRACE_SEIZE = 0x4206
+ PTRACE_SETOPTIONS = 0x4200
+ PTRACE_SETREGS = 0xd
+ PTRACE_SETREGSET = 0x4205
+ PTRACE_SETSIGINFO = 0x4203
+ PTRACE_SETSIGMASK = 0x420b
+ PTRACE_SINGLESTEP = 0x9
+ PTRACE_SYSCALL = 0x18
+ PTRACE_TRACEME = 0x0
+ RLIMIT_AS = 0x9
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x8
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x7
+ RLIMIT_NPROC = 0x6
+ RLIMIT_RSS = 0x5
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x8905
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x8904
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x541b
+ SIOCOUTQ = 0x5411
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x8902
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x2
+ SOCK_IOC_TYPE = 0x89
+ SOCK_NONBLOCK = 0x800
+ SOCK_PACKET = 0xa
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ 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 = 0x1
+ SOL_TCP = 0x6
+ SOL_TIPC = 0x10f
+ SOL_X25 = 0x106
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x1e
+ 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 = 0x6
+ SO_BSDCOMPAT = 0xe
+ SO_BUSY_POLL = 0x2e
+ SO_CNX_ADVICE = 0x35
+ SO_DEBUG = 0x1
+ SO_DETACH_BPF = 0x1b
+ SO_DETACH_FILTER = 0x1b
+ SO_DOMAIN = 0x27
+ SO_DONTROUTE = 0x5
+ SO_ERROR = 0x4
+ SO_GET_FILTER = 0x1a
+ SO_INCOMING_CPU = 0x31
+ SO_KEEPALIVE = 0x9
+ SO_LINGER = 0xd
+ SO_LOCK_FILTER = 0x2c
+ SO_MARK = 0x24
+ SO_MAX_PACING_RATE = 0x2f
+ SO_NOFCS = 0x2b
+ SO_NO_CHECK = 0xb
+ SO_OOBINLINE = 0xa
+ SO_PASSCRED = 0x10
+ SO_PASSSEC = 0x22
+ SO_PEEK_OFF = 0x2a
+ SO_PEERCRED = 0x11
+ SO_PEERNAME = 0x1c
+ SO_PEERSEC = 0x1f
+ SO_PRIORITY = 0xc
+ SO_PROTOCOL = 0x26
+ SO_RCVBUF = 0x8
+ SO_RCVBUFFORCE = 0x21
+ SO_RCVLOWAT = 0x12
+ SO_RCVTIMEO = 0x14
+ SO_REUSEADDR = 0x2
+ SO_REUSEPORT = 0xf
+ 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 = 0x7
+ SO_SNDBUFFORCE = 0x20
+ SO_SNDLOWAT = 0x13
+ SO_SNDTIMEO = 0x15
+ SO_TIMESTAMP = 0x1d
+ SO_TIMESTAMPING = 0x25
+ SO_TIMESTAMPNS = 0x23
+ SO_TYPE = 0x3
+ SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ TCFLSH = 0x540b
+ TCGETA = 0x5405
+ TCGETS = 0x5401
+ TCGETS2 = 0x802c542a
+ TCGETX = 0x5432
+ 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_REPAIR_WINDOW = 0x1d
+ 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 = 0x2
+ TCSBRK = 0x5409
+ TCSBRKP = 0x5425
+ TCSETA = 0x5406
+ TCSETAF = 0x5408
+ TCSETAW = 0x5407
+ TCSETS = 0x5402
+ TCSETS2 = 0x402c542b
+ TCSETSF = 0x5404
+ TCSETSF2 = 0x402c542d
+ TCSETSW = 0x5403
+ TCSETSW2 = 0x402c542c
+ TCSETX = 0x5433
+ TCSETXF = 0x5434
+ TCSETXW = 0x5435
+ TCXONC = 0x540a
+ TIOCCBRK = 0x5428
+ TIOCCONS = 0x541d
+ TIOCEXCL = 0x540c
+ TIOCGDEV = 0x80045432
+ TIOCGETD = 0x5424
+ TIOCGEXCL = 0x80045440
+ TIOCGICOUNT = 0x545d
+ TIOCGLCKTRMIOS = 0x5456
+ TIOCGPGRP = 0x540f
+ TIOCGPKT = 0x80045438
+ TIOCGPTLCK = 0x80045439
+ TIOCGPTN = 0x80045430
+ TIOCGRS485 = 0x542e
+ TIOCGSERIAL = 0x541e
+ TIOCGSID = 0x5429
+ TIOCGSOFTCAR = 0x5419
+ TIOCGWINSZ = 0x5413
+ TIOCINQ = 0x541b
+ TIOCLINUX = 0x541c
+ TIOCMBIC = 0x5417
+ TIOCMBIS = 0x5416
+ TIOCMGET = 0x5415
+ TIOCMIWAIT = 0x545c
+ TIOCMSET = 0x5418
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x5422
+ TIOCNXCL = 0x540d
+ TIOCOUTQ = 0x5411
+ TIOCPKT = 0x5420
+ 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 = 0x540e
+ TIOCSERCONFIG = 0x5453
+ TIOCSERGETLSR = 0x5459
+ TIOCSERGETMULTI = 0x545a
+ TIOCSERGSTRUCT = 0x5458
+ TIOCSERGWILD = 0x5454
+ TIOCSERSETMULTI = 0x545b
+ TIOCSERSWILD = 0x5455
+ TIOCSER_TEMT = 0x1
+ TIOCSETD = 0x5423
+ TIOCSIG = 0x40045436
+ TIOCSLCKTRMIOS = 0x5457
+ TIOCSPGRP = 0x5410
+ TIOCSPTLCK = 0x40045431
+ TIOCSRS485 = 0x542f
+ TIOCSSERIAL = 0x541f
+ TIOCSSOFTCAR = 0x541a
+ TIOCSTI = 0x5412
+ TIOCSWINSZ = 0x5414
+ TIOCVHANGUP = 0x5437
+ TOSTOP = 0x100
+ TS_COMM_LEN = 0x20
+ TUNATTACHFILTER = 0x401054d5
+ TUNDETACHFILTER = 0x401054d6
+ TUNGETFEATURES = 0x800454cf
+ TUNGETFILTER = 0x801054db
+ TUNGETIFF = 0x800454d2
+ TUNGETSNDBUF = 0x800454d3
+ TUNGETVNETBE = 0x800454df
+ TUNGETVNETHDRSZ = 0x800454d7
+ TUNGETVNETLE = 0x800454dd
+ TUNSETDEBUG = 0x400454c9
+ TUNSETGROUP = 0x400454ce
+ TUNSETIFF = 0x400454ca
+ TUNSETIFINDEX = 0x400454da
+ TUNSETLINK = 0x400454cd
+ TUNSETNOCSUM = 0x400454c8
+ TUNSETOFFLOAD = 0x400454d0
+ TUNSETOWNER = 0x400454cc
+ TUNSETPERSIST = 0x400454cb
+ TUNSETQUEUE = 0x400454d9
+ TUNSETSNDBUF = 0x400454d4
+ TUNSETTXFILTER = 0x400454d1
+ TUNSETVNETBE = 0x400454de
+ TUNSETVNETHDRSZ = 0x400454d8
+ TUNSETVNETLE = 0x400454dc
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0xd
+ VEOF = 0x4
+ VEOL = 0xb
+ VEOL2 = 0x10
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x6
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ VQUIT = 0x1
+ VREPRINT = 0xc
+ VSTART = 0x8
+ VSTOP = 0x9
+ VSUSP = 0xa
+ VSWTC = 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 = 0x40
+ WSTOPPED = 0x2
+ WUNTRACED = 0x2
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 0x2
+ XCASE = 0x4
+ XTABS = 0x1800
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x62)
+ EADDRNOTAVAIL = syscall.Errno(0x63)
+ EADV = syscall.Errno(0x44)
+ EAFNOSUPPORT = syscall.Errno(0x61)
+ EAGAIN = syscall.Errno(0xb)
+ EALREADY = syscall.Errno(0x72)
+ EBADE = syscall.Errno(0x34)
+ EBADF = syscall.Errno(0x9)
+ EBADFD = syscall.Errno(0x4d)
+ EBADMSG = syscall.Errno(0x4a)
+ EBADR = syscall.Errno(0x35)
+ EBADRQC = syscall.Errno(0x38)
+ EBADSLT = syscall.Errno(0x39)
+ EBFONT = syscall.Errno(0x3b)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x7d)
+ ECHILD = syscall.Errno(0xa)
+ ECHRNG = syscall.Errno(0x2c)
+ ECOMM = syscall.Errno(0x46)
+ ECONNABORTED = syscall.Errno(0x67)
+ ECONNREFUSED = syscall.Errno(0x6f)
+ ECONNRESET = syscall.Errno(0x68)
+ EDEADLK = syscall.Errno(0x23)
+ EDEADLOCK = syscall.Errno(0x23)
+ EDESTADDRREQ = syscall.Errno(0x59)
+ EDOM = syscall.Errno(0x21)
+ EDOTDOT = syscall.Errno(0x49)
+ EDQUOT = syscall.Errno(0x7a)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EHOSTDOWN = syscall.Errno(0x70)
+ EHOSTUNREACH = syscall.Errno(0x71)
+ EHWPOISON = syscall.Errno(0x85)
+ EIDRM = syscall.Errno(0x2b)
+ EILSEQ = syscall.Errno(0x54)
+ EINPROGRESS = syscall.Errno(0x73)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x6a)
+ EISDIR = syscall.Errno(0x15)
+ EISNAM = syscall.Errno(0x78)
+ EKEYEXPIRED = syscall.Errno(0x7f)
+ EKEYREJECTED = syscall.Errno(0x81)
+ EKEYREVOKED = syscall.Errno(0x80)
+ EL2HLT = syscall.Errno(0x33)
+ EL2NSYNC = syscall.Errno(0x2d)
+ EL3HLT = syscall.Errno(0x2e)
+ EL3RST = syscall.Errno(0x2f)
+ ELIBACC = syscall.Errno(0x4f)
+ ELIBBAD = syscall.Errno(0x50)
+ ELIBEXEC = syscall.Errno(0x53)
+ ELIBMAX = syscall.Errno(0x52)
+ ELIBSCN = syscall.Errno(0x51)
+ ELNRNG = syscall.Errno(0x30)
+ ELOOP = syscall.Errno(0x28)
+ EMEDIUMTYPE = syscall.Errno(0x7c)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x5a)
+ EMULTIHOP = syscall.Errno(0x48)
+ ENAMETOOLONG = syscall.Errno(0x24)
+ ENAVAIL = syscall.Errno(0x77)
+ ENETDOWN = syscall.Errno(0x64)
+ ENETRESET = syscall.Errno(0x66)
+ ENETUNREACH = syscall.Errno(0x65)
+ ENFILE = syscall.Errno(0x17)
+ ENOANO = syscall.Errno(0x37)
+ ENOBUFS = syscall.Errno(0x69)
+ ENOCSI = syscall.Errno(0x32)
+ ENODATA = syscall.Errno(0x3d)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOKEY = syscall.Errno(0x7e)
+ ENOLCK = syscall.Errno(0x25)
+ ENOLINK = syscall.Errno(0x43)
+ ENOMEDIUM = syscall.Errno(0x7b)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x2a)
+ ENONET = syscall.Errno(0x40)
+ ENOPKG = syscall.Errno(0x41)
+ ENOPROTOOPT = syscall.Errno(0x5c)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x3f)
+ ENOSTR = syscall.Errno(0x3c)
+ ENOSYS = syscall.Errno(0x26)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x6b)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x27)
+ ENOTNAM = syscall.Errno(0x76)
+ ENOTRECOVERABLE = syscall.Errno(0x83)
+ ENOTSOCK = syscall.Errno(0x58)
+ ENOTSUP = syscall.Errno(0x5f)
+ ENOTTY = syscall.Errno(0x19)
+ ENOTUNIQ = syscall.Errno(0x4c)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x5f)
+ EOVERFLOW = syscall.Errno(0x4b)
+ EOWNERDEAD = syscall.Errno(0x82)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x60)
+ EPIPE = syscall.Errno(0x20)
+ EPROTO = syscall.Errno(0x47)
+ EPROTONOSUPPORT = syscall.Errno(0x5d)
+ EPROTOTYPE = syscall.Errno(0x5b)
+ ERANGE = syscall.Errno(0x22)
+ EREMCHG = syscall.Errno(0x4e)
+ EREMOTE = syscall.Errno(0x42)
+ EREMOTEIO = syscall.Errno(0x79)
+ ERESTART = syscall.Errno(0x55)
+ ERFKILL = syscall.Errno(0x84)
+ EROFS = syscall.Errno(0x1e)
+ ESHUTDOWN = syscall.Errno(0x6c)
+ ESOCKTNOSUPPORT = syscall.Errno(0x5e)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESRMNT = syscall.Errno(0x45)
+ ESTALE = syscall.Errno(0x74)
+ ESTRPIPE = syscall.Errno(0x56)
+ ETIME = syscall.Errno(0x3e)
+ ETIMEDOUT = syscall.Errno(0x6e)
+ ETOOMANYREFS = syscall.Errno(0x6d)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUCLEAN = syscall.Errno(0x75)
+ EUNATCH = syscall.Errno(0x31)
+ EUSERS = syscall.Errno(0x57)
+ EWOULDBLOCK = syscall.Errno(0xb)
+ EXDEV = syscall.Errno(0x12)
+ EXFULL = syscall.Errno(0x36)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0x7)
+ SIGCHLD = syscall.Signal(0x11)
+ SIGCLD = syscall.Signal(0x11)
+ SIGCONT = syscall.Signal(0x12)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x1d)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPOLL = syscall.Signal(0x1d)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x1e)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTKFLT = syscall.Signal(0x10)
+ SIGSTOP = syscall.Signal(0x13)
+ SIGSYS = syscall.Signal(0x1f)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x14)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGUNUSED = syscall.Signal(0x1f)
+ SIGURG = syscall.Signal(0x17)
+ SIGUSR1 = syscall.Signal(0xa)
+ SIGUSR2 = syscall.Signal(0xc)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "resource deadlock avoided",
+ 36: "file name too long",
+ 37: "no locks available",
+ 38: "function not implemented",
+ 39: "directory not empty",
+ 40: "too many levels of symbolic links",
+ 42: "no message of desired type",
+ 43: "identifier removed",
+ 44: "channel number out of range",
+ 45: "level 2 not synchronized",
+ 46: "level 3 halted",
+ 47: "level 3 reset",
+ 48: "link number out of range",
+ 49: "protocol driver not attached",
+ 50: "no CSI structure available",
+ 51: "level 2 halted",
+ 52: "invalid exchange",
+ 53: "invalid request descriptor",
+ 54: "exchange full",
+ 55: "no anode",
+ 56: "invalid request code",
+ 57: "invalid slot",
+ 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",
+ 72: "multihop attempted",
+ 73: "RFS specific error",
+ 74: "bad message",
+ 75: "value too large for defined data type",
+ 76: "name not unique on network",
+ 77: "file descriptor in bad state",
+ 78: "remote address changed",
+ 79: "can not access a needed shared library",
+ 80: "accessing a corrupted shared library",
+ 81: ".lib section in a.out corrupted",
+ 82: "attempting to link in too many shared libraries",
+ 83: "cannot exec a shared library directly",
+ 84: "invalid or incomplete multibyte or wide character",
+ 85: "interrupted system call should be restarted",
+ 86: "streams pipe error",
+ 87: "too many users",
+ 88: "socket operation on non-socket",
+ 89: "destination address required",
+ 90: "message too long",
+ 91: "protocol wrong type for socket",
+ 92: "protocol not available",
+ 93: "protocol not supported",
+ 94: "socket type not supported",
+ 95: "operation not supported",
+ 96: "protocol family not supported",
+ 97: "address family not supported by protocol",
+ 98: "address already in use",
+ 99: "cannot assign requested address",
+ 100: "network is down",
+ 101: "network is unreachable",
+ 102: "network dropped connection on reset",
+ 103: "software caused connection abort",
+ 104: "connection reset by peer",
+ 105: "no buffer space available",
+ 106: "transport endpoint is already connected",
+ 107: "transport endpoint is not connected",
+ 108: "cannot send after transport endpoint shutdown",
+ 109: "too many references: cannot splice",
+ 110: "connection timed out",
+ 111: "connection refused",
+ 112: "host is down",
+ 113: "no route to host",
+ 114: "operation already in progress",
+ 115: "operation now in progress",
+ 116: "stale file handle",
+ 117: "structure needs cleaning",
+ 118: "not a XENIX named type file",
+ 119: "no XENIX semaphores available",
+ 120: "is a named type file",
+ 121: "remote I/O error",
+ 122: "disk quota exceeded",
+ 123: "no medium found",
+ 124: "wrong medium type",
+ 125: "operation canceled",
+ 126: "required key not available",
+ 127: "key has expired",
+ 128: "key has been revoked",
+ 129: "key was rejected by service",
+ 130: "owner died",
+ 131: "state not recoverable",
+ 132: "operation not possible due to RF-kill",
+ 133: "memory page has hardware error",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/breakpoint trap",
+ 6: "aborted",
+ 7: "bus error",
+ 8: "floating point exception",
+ 9: "killed",
+ 10: "user defined signal 1",
+ 11: "segmentation fault",
+ 12: "user defined signal 2",
+ 13: "broken pipe",
+ 14: "alarm clock",
+ 15: "terminated",
+ 16: "stack fault",
+ 17: "child exited",
+ 18: "continued",
+ 19: "stopped (signal)",
+ 20: "stopped",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "urgent I/O condition",
+ 24: "CPU time limit exceeded",
+ 25: "file size limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window changed",
+ 29: "I/O possible",
+ 30: "power failure",
+ 31: "bad system call",
+}
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..8806a2c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go
@@ -0,0 +1,2196 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build mips,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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
+ BLKBSZGET = 0x40041270
+ BLKBSZSET = 0x80041271
+ BLKFLSBUF = 0x20001261
+ BLKFRAGET = 0x20001265
+ BLKFRASET = 0x20001264
+ BLKGETSIZE = 0x20001260
+ BLKGETSIZE64 = 0x40041272
+ BLKPBSZGET = 0x2000127b
+ BLKRAGET = 0x20001263
+ BLKRASET = 0x20001262
+ BLKROGET = 0x2000125e
+ BLKROSET = 0x2000125d
+ BLKRRPART = 0x2000125f
+ BLKSECTGET = 0x20001267
+ BLKSECTSET = 0x20001266
+ BLKSSZGET = 0x20001268
+ 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_RAW_FILTER_MAX = 0x200
+ 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
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x80
+ EFD_SEMAPHORE = 0x1
+ 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_NCSI = 0x88f8
+ 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
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x8000
+ FFDLY = 0x8000
+ FLUSHO = 0x2000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ 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
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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
+ PERF_EVENT_IOC_DISABLE = 0x20002401
+ PERF_EVENT_IOC_ENABLE = 0x20002400
+ PERF_EVENT_IOC_ID = 0x40042407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409
+ PERF_EVENT_IOC_PERIOD = 0x80082404
+ PERF_EVENT_IOC_REFRESH = 0x20002402
+ PERF_EVENT_IOC_RESET = 0x20002403
+ PERF_EVENT_IOC_SET_BPF = 0x80042408
+ PERF_EVENT_IOC_SET_FILTER = 0x80042406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x20002405
+ 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_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x9
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x5
+ RLIMIT_NPROC = 0x8
+ RLIMIT_RSS = 0x7
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x40047307
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x40047309
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x467f
+ SIOCOUTQ = 0x7472
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x80047308
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x1
+ SOCK_IOC_TYPE = 0x89
+ 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_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ 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_REPAIR_WINDOW = 0x1d
+ 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
+ TS_COMM_LEN = 0x20
+ 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
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0xd
+ VEOF = 0x10
+ VEOL = 0x11
+ VEOL2 = 0x6
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x4
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ 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
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 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_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go
new file mode 100644
index 0000000..b05a532
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go
@@ -0,0 +1,2196 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build mips64,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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
+ BLKBSZGET = 0x40081270
+ BLKBSZSET = 0x80081271
+ BLKFLSBUF = 0x20001261
+ BLKFRAGET = 0x20001265
+ BLKFRASET = 0x20001264
+ BLKGETSIZE = 0x20001260
+ BLKGETSIZE64 = 0x40081272
+ BLKPBSZGET = 0x2000127b
+ BLKRAGET = 0x20001263
+ BLKRASET = 0x20001262
+ BLKROGET = 0x2000125e
+ BLKROSET = 0x2000125d
+ BLKRRPART = 0x2000125f
+ BLKSECTGET = 0x20001267
+ BLKSECTSET = 0x20001266
+ BLKSSZGET = 0x20001268
+ 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_RAW_FILTER_MAX = 0x200
+ 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
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x80
+ EFD_SEMAPHORE = 0x1
+ 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_NCSI = 0x88f8
+ 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
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x8000
+ FFDLY = 0x8000
+ FLUSHO = 0x2000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x406
+ F_EXLCK = 0x4
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLEASE = 0x401
+ F_GETLK = 0xe
+ F_GETLK64 = 0xe
+ 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 = 0x6
+ F_SETLK64 = 0x6
+ F_SETLKW = 0x7
+ F_SETLKW64 = 0x7
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ 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
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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 = 0x0
+ 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
+ PERF_EVENT_IOC_DISABLE = 0x20002401
+ PERF_EVENT_IOC_ENABLE = 0x20002400
+ PERF_EVENT_IOC_ID = 0x40082407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409
+ PERF_EVENT_IOC_PERIOD = 0x80082404
+ PERF_EVENT_IOC_REFRESH = 0x20002402
+ PERF_EVENT_IOC_RESET = 0x20002403
+ PERF_EVENT_IOC_SET_BPF = 0x80042408
+ PERF_EVENT_IOC_SET_FILTER = 0x80082406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x20002405
+ 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 = -0x1
+ 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_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x9
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x5
+ RLIMIT_NPROC = 0x8
+ RLIMIT_RSS = 0x7
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x40047307
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x40047309
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x467f
+ SIOCOUTQ = 0x7472
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x80047308
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x1
+ SOCK_IOC_TYPE = 0x89
+ 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_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ 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_REPAIR_WINDOW = 0x1d
+ 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
+ TS_COMM_LEN = 0x20
+ TUNATTACHFILTER = 0x801054d5
+ TUNDETACHFILTER = 0x801054d6
+ TUNGETFEATURES = 0x400454cf
+ TUNGETFILTER = 0x401054db
+ 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
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0xd
+ VEOF = 0x10
+ VEOL = 0x11
+ VEOL2 = 0x6
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x4
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ 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 = 0x40
+ WSTOPPED = 0x2
+ WUNTRACED = 0x2
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 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_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go
new file mode 100644
index 0000000..7a5e9e4
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go
@@ -0,0 +1,2196 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build mips64le,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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
+ BLKBSZGET = 0x40081270
+ BLKBSZSET = 0x80081271
+ BLKFLSBUF = 0x20001261
+ BLKFRAGET = 0x20001265
+ BLKFRASET = 0x20001264
+ BLKGETSIZE = 0x20001260
+ BLKGETSIZE64 = 0x40081272
+ BLKPBSZGET = 0x2000127b
+ BLKRAGET = 0x20001263
+ BLKRASET = 0x20001262
+ BLKROGET = 0x2000125e
+ BLKROSET = 0x2000125d
+ BLKRRPART = 0x2000125f
+ BLKSECTGET = 0x20001267
+ BLKSECTSET = 0x20001266
+ BLKSSZGET = 0x20001268
+ 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_RAW_FILTER_MAX = 0x200
+ 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
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x80
+ EFD_SEMAPHORE = 0x1
+ 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_NCSI = 0x88f8
+ 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
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x8000
+ FFDLY = 0x8000
+ FLUSHO = 0x2000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x406
+ F_EXLCK = 0x4
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLEASE = 0x401
+ F_GETLK = 0xe
+ F_GETLK64 = 0xe
+ 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 = 0x6
+ F_SETLK64 = 0x6
+ F_SETLKW = 0x7
+ F_SETLKW64 = 0x7
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ 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
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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 = 0x0
+ 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
+ PERF_EVENT_IOC_DISABLE = 0x20002401
+ PERF_EVENT_IOC_ENABLE = 0x20002400
+ PERF_EVENT_IOC_ID = 0x40082407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409
+ PERF_EVENT_IOC_PERIOD = 0x80082404
+ PERF_EVENT_IOC_REFRESH = 0x20002402
+ PERF_EVENT_IOC_RESET = 0x20002403
+ PERF_EVENT_IOC_SET_BPF = 0x80042408
+ PERF_EVENT_IOC_SET_FILTER = 0x80082406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x20002405
+ 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 = -0x1
+ 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_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x9
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x5
+ RLIMIT_NPROC = 0x8
+ RLIMIT_RSS = 0x7
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x40047307
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x40047309
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x467f
+ SIOCOUTQ = 0x7472
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x80047308
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x1
+ SOCK_IOC_TYPE = 0x89
+ 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_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ 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_REPAIR_WINDOW = 0x1d
+ 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
+ TS_COMM_LEN = 0x20
+ TUNATTACHFILTER = 0x801054d5
+ TUNDETACHFILTER = 0x801054d6
+ TUNGETFEATURES = 0x400454cf
+ TUNGETFILTER = 0x401054db
+ 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
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0xd
+ VEOF = 0x10
+ VEOL = 0x11
+ VEOL2 = 0x6
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x4
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ 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 = 0x40
+ WSTOPPED = 0x2
+ WUNTRACED = 0x2
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 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_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go
new file mode 100644
index 0000000..549ffce
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go
@@ -0,0 +1,2196 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build mipsle,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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
+ BLKBSZGET = 0x40041270
+ BLKBSZSET = 0x80041271
+ BLKFLSBUF = 0x20001261
+ BLKFRAGET = 0x20001265
+ BLKFRASET = 0x20001264
+ BLKGETSIZE = 0x20001260
+ BLKGETSIZE64 = 0x40041272
+ BLKPBSZGET = 0x2000127b
+ BLKRAGET = 0x20001263
+ BLKRASET = 0x20001262
+ BLKROGET = 0x2000125e
+ BLKROSET = 0x2000125d
+ BLKRRPART = 0x2000125f
+ BLKSECTGET = 0x20001267
+ BLKSECTSET = 0x20001266
+ BLKSSZGET = 0x20001268
+ 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_RAW_FILTER_MAX = 0x200
+ 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
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x80
+ EFD_SEMAPHORE = 0x1
+ 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_NCSI = 0x88f8
+ 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
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x8000
+ FFDLY = 0x8000
+ FLUSHO = 0x2000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ 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
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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
+ PERF_EVENT_IOC_DISABLE = 0x20002401
+ PERF_EVENT_IOC_ENABLE = 0x20002400
+ PERF_EVENT_IOC_ID = 0x40042407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409
+ PERF_EVENT_IOC_PERIOD = 0x80082404
+ PERF_EVENT_IOC_REFRESH = 0x20002402
+ PERF_EVENT_IOC_RESET = 0x20002403
+ PERF_EVENT_IOC_SET_BPF = 0x80042408
+ PERF_EVENT_IOC_SET_FILTER = 0x80042406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x20002405
+ 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_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x9
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x5
+ RLIMIT_NPROC = 0x8
+ RLIMIT_RSS = 0x7
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x40047307
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x40047309
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x467f
+ SIOCOUTQ = 0x7472
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x80047308
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x1
+ SOCK_IOC_TYPE = 0x89
+ 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_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ 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_REPAIR_WINDOW = 0x1d
+ 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
+ TS_COMM_LEN = 0x20
+ 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
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0xd
+ VEOF = 0x10
+ VEOL = 0x11
+ VEOL2 = 0x6
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x4
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ 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
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 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
new file mode 100644
index 0000000..7d31113
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go
@@ -0,0 +1,2250 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build ppc64,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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 = 0x17
+ B110 = 0x3
+ B115200 = 0x11
+ B1152000 = 0x18
+ B1200 = 0x9
+ B134 = 0x4
+ B150 = 0x5
+ B1500000 = 0x19
+ B1800 = 0xa
+ B19200 = 0xe
+ B200 = 0x6
+ B2000000 = 0x1a
+ B230400 = 0x12
+ B2400 = 0xb
+ B2500000 = 0x1b
+ B300 = 0x7
+ B3000000 = 0x1c
+ B3500000 = 0x1d
+ B38400 = 0xf
+ B4000000 = 0x1e
+ B460800 = 0x13
+ B4800 = 0xc
+ B50 = 0x1
+ B500000 = 0x14
+ B57600 = 0x10
+ B576000 = 0x15
+ B600 = 0x8
+ B75 = 0x2
+ B921600 = 0x16
+ B9600 = 0xd
+ BLKBSZGET = 0x40081270
+ BLKBSZSET = 0x80081271
+ BLKFLSBUF = 0x20001261
+ BLKFRAGET = 0x20001265
+ BLKFRASET = 0x20001264
+ BLKGETSIZE = 0x20001260
+ BLKGETSIZE64 = 0x40081272
+ BLKPBSZGET = 0x2000127b
+ BLKRAGET = 0x20001263
+ BLKRASET = 0x20001262
+ BLKROGET = 0x2000125e
+ BLKROSET = 0x2000125d
+ BLKRRPART = 0x2000125f
+ BLKSECTGET = 0x20001267
+ BLKSECTSET = 0x20001266
+ BLKSSZGET = 0x20001268
+ BOTHER = 0x1f
+ 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 = 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_RAW_FILTER_MAX = 0x200
+ 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
+ CIBAUD = 0xff0000
+ CLOCAL = 0x8000
+ 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 = 0x1000
+ CR2 = 0x2000
+ CR3 = 0x3000
+ CRDLY = 0x3000
+ CREAD = 0x800
+ CRTSCTS = 0x80000000
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIGNAL = 0xff
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x0
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x800
+ EFD_SEMAPHORE = 0x1
+ 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_NCSI = 0x88f8
+ 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 = 0x10000000
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x4000
+ FFDLY = 0x4000
+ FLUSHO = 0x800000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x406
+ F_EXLCK = 0x4
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLEASE = 0x401
+ F_GETLK = 0x5
+ F_GETLK64 = 0xc
+ F_GETOWN = 0x9
+ 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 = 0x6
+ F_SETLK64 = 0xd
+ F_SETLKW = 0x7
+ F_SETLKW64 = 0xe
+ F_SETOWN = 0x8
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ HUPCL = 0x4000
+ IBSHIFT = 0x10
+ ICANON = 0x100
+ ICMPV6_FILTER = 0x1
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ 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 = 0x800
+ 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 = 0x80
+ ISTRIP = 0x20
+ IUCLC = 0x1000
+ IUTF8 = 0x4000
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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 = 0x20
+ MAP_ANONYMOUS = 0x20
+ MAP_DENYWRITE = 0x800
+ MAP_EXECUTABLE = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_GROWSDOWN = 0x100
+ MAP_HUGETLB = 0x40000
+ MAP_HUGE_MASK = 0x3f
+ MAP_HUGE_SHIFT = 0x1a
+ MAP_LOCKED = 0x80
+ MAP_NONBLOCK = 0x10000
+ MAP_NORESERVE = 0x40
+ MAP_POPULATE = 0x8000
+ MAP_PRIVATE = 0x2
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x20000
+ MAP_TYPE = 0xf
+ MCL_CURRENT = 0x2000
+ MCL_FUTURE = 0x4000
+ MCL_ONFAULT = 0x8000
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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
+ NL2 = 0x200
+ NL3 = 0x300
+ NLA_ALIGNTO = 0x4
+ NLA_F_NESTED = 0x8000
+ NLA_F_NET_BYTEORDER = 0x4000
+ NLA_HDRLEN = 0x4
+ NLDLY = 0x300
+ 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 = 0x80000000
+ OCRNL = 0x8
+ OFDEL = 0x80
+ OFILL = 0x40
+ OLCUC = 0x4
+ ONLCR = 0x2
+ ONLRET = 0x20
+ ONOCR = 0x10
+ OPOST = 0x1
+ O_ACCMODE = 0x3
+ O_APPEND = 0x400
+ O_ASYNC = 0x2000
+ O_CLOEXEC = 0x80000
+ O_CREAT = 0x40
+ O_DIRECT = 0x20000
+ O_DIRECTORY = 0x4000
+ O_DSYNC = 0x1000
+ O_EXCL = 0x80
+ O_FSYNC = 0x101000
+ O_LARGEFILE = 0x0
+ O_NDELAY = 0x800
+ O_NOATIME = 0x40000
+ O_NOCTTY = 0x100
+ O_NOFOLLOW = 0x8000
+ O_NONBLOCK = 0x800
+ O_PATH = 0x200000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x101000
+ O_SYNC = 0x101000
+ O_TMPFILE = 0x404000
+ 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 = 0x1000
+ 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 = 0x2000
+ PENDIN = 0x20000000
+ PERF_EVENT_IOC_DISABLE = 0x20002401
+ PERF_EVENT_IOC_ENABLE = 0x20002400
+ PERF_EVENT_IOC_ID = 0x40082407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409
+ PERF_EVENT_IOC_PERIOD = 0x80082404
+ PERF_EVENT_IOC_REFRESH = 0x20002402
+ PERF_EVENT_IOC_RESET = 0x20002403
+ PERF_EVENT_IOC_SET_BPF = 0x80042408
+ PERF_EVENT_IOC_SET_FILTER = 0x80082406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x20002405
+ 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_SAO = 0x10
+ 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 = -0x1
+ 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_GETEVRREGS = 0x14
+ PTRACE_GETFPREGS = 0xe
+ PTRACE_GETREGS = 0xc
+ PTRACE_GETREGS64 = 0x16
+ PTRACE_GETREGSET = 0x4204
+ PTRACE_GETSIGINFO = 0x4202
+ PTRACE_GETSIGMASK = 0x420a
+ PTRACE_GETVRREGS = 0x12
+ PTRACE_GETVSRREGS = 0x1b
+ PTRACE_GET_DEBUGREG = 0x19
+ PTRACE_INTERRUPT = 0x4207
+ PTRACE_KILL = 0x8
+ PTRACE_LISTEN = 0x4208
+ 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_PEEKSIGINFO = 0x4209
+ PTRACE_PEEKSIGINFO_SHARED = 0x1
+ PTRACE_PEEKTEXT = 0x1
+ PTRACE_PEEKUSR = 0x3
+ PTRACE_POKEDATA = 0x5
+ PTRACE_POKETEXT = 0x4
+ PTRACE_POKEUSR = 0x6
+ PTRACE_SECCOMP_GET_FILTER = 0x420c
+ PTRACE_SEIZE = 0x4206
+ PTRACE_SETEVRREGS = 0x15
+ PTRACE_SETFPREGS = 0xf
+ PTRACE_SETOPTIONS = 0x4200
+ PTRACE_SETREGS = 0xd
+ PTRACE_SETREGS64 = 0x17
+ PTRACE_SETREGSET = 0x4205
+ PTRACE_SETSIGINFO = 0x4203
+ PTRACE_SETSIGMASK = 0x420b
+ PTRACE_SETVRREGS = 0x13
+ PTRACE_SETVSRREGS = 0x1c
+ PTRACE_SET_DEBUGREG = 0x1a
+ PTRACE_SINGLEBLOCK = 0x100
+ PTRACE_SINGLESTEP = 0x9
+ PTRACE_SYSCALL = 0x18
+ PTRACE_TRACEME = 0x0
+ PT_CCR = 0x26
+ PT_CTR = 0x23
+ PT_DAR = 0x29
+ PT_DSCR = 0x2c
+ PT_DSISR = 0x2a
+ PT_FPR0 = 0x30
+ PT_FPSCR = 0x50
+ PT_LNK = 0x24
+ PT_MSR = 0x21
+ PT_NIP = 0x20
+ PT_ORIG_R3 = 0x22
+ PT_R0 = 0x0
+ PT_R1 = 0x1
+ PT_R10 = 0xa
+ PT_R11 = 0xb
+ PT_R12 = 0xc
+ PT_R13 = 0xd
+ PT_R14 = 0xe
+ PT_R15 = 0xf
+ PT_R16 = 0x10
+ PT_R17 = 0x11
+ PT_R18 = 0x12
+ PT_R19 = 0x13
+ PT_R2 = 0x2
+ PT_R20 = 0x14
+ PT_R21 = 0x15
+ PT_R22 = 0x16
+ PT_R23 = 0x17
+ PT_R24 = 0x18
+ PT_R25 = 0x19
+ PT_R26 = 0x1a
+ PT_R27 = 0x1b
+ PT_R28 = 0x1c
+ PT_R29 = 0x1d
+ PT_R3 = 0x3
+ PT_R30 = 0x1e
+ PT_R31 = 0x1f
+ PT_R4 = 0x4
+ PT_R5 = 0x5
+ PT_R6 = 0x6
+ PT_R7 = 0x7
+ PT_R8 = 0x8
+ PT_R9 = 0x9
+ PT_REGS_COUNT = 0x2c
+ PT_RESULT = 0x2b
+ PT_SOFTE = 0x27
+ PT_TRAP = 0x28
+ PT_VR0 = 0x52
+ PT_VRSAVE = 0x94
+ PT_VSCR = 0x93
+ PT_VSR0 = 0x96
+ PT_VSR31 = 0xd4
+ PT_XER = 0x25
+ RLIMIT_AS = 0x9
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x8
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x7
+ RLIMIT_NPROC = 0x6
+ RLIMIT_RSS = 0x5
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x8905
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x8904
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x4004667f
+ SIOCOUTQ = 0x40047473
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x8902
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x2
+ SOCK_IOC_TYPE = 0x89
+ SOCK_NONBLOCK = 0x800
+ SOCK_PACKET = 0xa
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ 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 = 0x1
+ SOL_TCP = 0x6
+ SOL_TIPC = 0x10f
+ SOL_X25 = 0x106
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x1e
+ 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 = 0x6
+ SO_BSDCOMPAT = 0xe
+ SO_BUSY_POLL = 0x2e
+ SO_CNX_ADVICE = 0x35
+ SO_DEBUG = 0x1
+ SO_DETACH_BPF = 0x1b
+ SO_DETACH_FILTER = 0x1b
+ SO_DOMAIN = 0x27
+ SO_DONTROUTE = 0x5
+ SO_ERROR = 0x4
+ SO_GET_FILTER = 0x1a
+ SO_INCOMING_CPU = 0x31
+ SO_KEEPALIVE = 0x9
+ SO_LINGER = 0xd
+ SO_LOCK_FILTER = 0x2c
+ SO_MARK = 0x24
+ SO_MAX_PACING_RATE = 0x2f
+ SO_NOFCS = 0x2b
+ SO_NO_CHECK = 0xb
+ SO_OOBINLINE = 0xa
+ SO_PASSCRED = 0x14
+ SO_PASSSEC = 0x22
+ SO_PEEK_OFF = 0x2a
+ SO_PEERCRED = 0x15
+ SO_PEERNAME = 0x1c
+ SO_PEERSEC = 0x1f
+ SO_PRIORITY = 0xc
+ SO_PROTOCOL = 0x26
+ SO_RCVBUF = 0x8
+ SO_RCVBUFFORCE = 0x21
+ SO_RCVLOWAT = 0x10
+ SO_RCVTIMEO = 0x12
+ SO_REUSEADDR = 0x2
+ SO_REUSEPORT = 0xf
+ 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 = 0x7
+ SO_SNDBUFFORCE = 0x20
+ SO_SNDLOWAT = 0x11
+ SO_SNDTIMEO = 0x13
+ SO_TIMESTAMP = 0x1d
+ SO_TIMESTAMPING = 0x25
+ SO_TIMESTAMPNS = 0x23
+ SO_TYPE = 0x3
+ SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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 = 0x400
+ TAB2 = 0x800
+ TAB3 = 0xc00
+ TABDLY = 0xc00
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ TCFLSH = 0x2000741f
+ TCGETA = 0x40147417
+ TCGETS = 0x402c7413
+ 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_REPAIR_WINDOW = 0x1d
+ 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 = 0x2
+ TCSBRK = 0x2000741d
+ TCSBRKP = 0x5425
+ TCSETA = 0x80147418
+ TCSETAF = 0x8014741c
+ TCSETAW = 0x80147419
+ TCSETS = 0x802c7414
+ TCSETSF = 0x802c7416
+ TCSETSW = 0x802c7415
+ TCXONC = 0x2000741e
+ TIOCCBRK = 0x5428
+ TIOCCONS = 0x541d
+ TIOCEXCL = 0x540c
+ TIOCGDEV = 0x40045432
+ TIOCGETC = 0x40067412
+ TIOCGETD = 0x5424
+ TIOCGETP = 0x40067408
+ TIOCGEXCL = 0x40045440
+ TIOCGICOUNT = 0x545d
+ TIOCGLCKTRMIOS = 0x5456
+ TIOCGLTC = 0x40067474
+ TIOCGPGRP = 0x40047477
+ TIOCGPKT = 0x40045438
+ TIOCGPTLCK = 0x40045439
+ TIOCGPTN = 0x40045430
+ TIOCGRS485 = 0x542e
+ TIOCGSERIAL = 0x541e
+ TIOCGSID = 0x5429
+ TIOCGSOFTCAR = 0x5419
+ TIOCGWINSZ = 0x40087468
+ TIOCINQ = 0x4004667f
+ TIOCLINUX = 0x541c
+ TIOCMBIC = 0x5417
+ TIOCMBIS = 0x5416
+ TIOCMGET = 0x5415
+ TIOCMIWAIT = 0x545c
+ TIOCMSET = 0x5418
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_LOOP = 0x8000
+ TIOCM_OUT1 = 0x2000
+ TIOCM_OUT2 = 0x4000
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x5422
+ TIOCNXCL = 0x540d
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x5420
+ 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 = 0x540e
+ TIOCSERCONFIG = 0x5453
+ TIOCSERGETLSR = 0x5459
+ TIOCSERGETMULTI = 0x545a
+ TIOCSERGSTRUCT = 0x5458
+ TIOCSERGWILD = 0x5454
+ TIOCSERSETMULTI = 0x545b
+ TIOCSERSWILD = 0x5455
+ TIOCSER_TEMT = 0x1
+ TIOCSETC = 0x80067411
+ TIOCSETD = 0x5423
+ TIOCSETN = 0x8006740a
+ TIOCSETP = 0x80067409
+ TIOCSIG = 0x80045436
+ TIOCSLCKTRMIOS = 0x5457
+ TIOCSLTC = 0x80067475
+ TIOCSPGRP = 0x80047476
+ TIOCSPTLCK = 0x80045431
+ TIOCSRS485 = 0x542f
+ TIOCSSERIAL = 0x541f
+ TIOCSSOFTCAR = 0x541a
+ TIOCSTART = 0x2000746e
+ TIOCSTI = 0x5412
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCVHANGUP = 0x5437
+ TOSTOP = 0x400000
+ TS_COMM_LEN = 0x20
+ TUNATTACHFILTER = 0x801054d5
+ TUNDETACHFILTER = 0x801054d6
+ TUNGETFEATURES = 0x400454cf
+ TUNGETFILTER = 0x401054db
+ 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
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0x10
+ VEOF = 0x4
+ VEOL = 0x6
+ VEOL2 = 0x8
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x5
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ VQUIT = 0x1
+ VREPRINT = 0xb
+ VSTART = 0xd
+ VSTOP = 0xe
+ VSUSP = 0xc
+ VSWTC = 0x9
+ VT0 = 0x0
+ VT1 = 0x10000
+ VTDLY = 0x10000
+ VTIME = 0x7
+ VWERASE = 0xa
+ WALL = 0x40000000
+ WCLONE = 0x80000000
+ WCONTINUED = 0x8
+ WEXITED = 0x4
+ WNOHANG = 0x1
+ WNOTHREAD = 0x20000000
+ WNOWAIT = 0x1000000
+ WORDSIZE = 0x40
+ WSTOPPED = 0x2
+ WUNTRACED = 0x2
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 0x2
+ XCASE = 0x4000
+ XTABS = 0xc00
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x62)
+ EADDRNOTAVAIL = syscall.Errno(0x63)
+ EADV = syscall.Errno(0x44)
+ EAFNOSUPPORT = syscall.Errno(0x61)
+ EAGAIN = syscall.Errno(0xb)
+ EALREADY = syscall.Errno(0x72)
+ EBADE = syscall.Errno(0x34)
+ EBADF = syscall.Errno(0x9)
+ EBADFD = syscall.Errno(0x4d)
+ EBADMSG = syscall.Errno(0x4a)
+ EBADR = syscall.Errno(0x35)
+ EBADRQC = syscall.Errno(0x38)
+ EBADSLT = syscall.Errno(0x39)
+ EBFONT = syscall.Errno(0x3b)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x7d)
+ ECHILD = syscall.Errno(0xa)
+ ECHRNG = syscall.Errno(0x2c)
+ ECOMM = syscall.Errno(0x46)
+ ECONNABORTED = syscall.Errno(0x67)
+ ECONNREFUSED = syscall.Errno(0x6f)
+ ECONNRESET = syscall.Errno(0x68)
+ EDEADLK = syscall.Errno(0x23)
+ EDEADLOCK = syscall.Errno(0x3a)
+ EDESTADDRREQ = syscall.Errno(0x59)
+ EDOM = syscall.Errno(0x21)
+ EDOTDOT = syscall.Errno(0x49)
+ EDQUOT = syscall.Errno(0x7a)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EHOSTDOWN = syscall.Errno(0x70)
+ EHOSTUNREACH = syscall.Errno(0x71)
+ EHWPOISON = syscall.Errno(0x85)
+ EIDRM = syscall.Errno(0x2b)
+ EILSEQ = syscall.Errno(0x54)
+ EINPROGRESS = syscall.Errno(0x73)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x6a)
+ EISDIR = syscall.Errno(0x15)
+ EISNAM = syscall.Errno(0x78)
+ EKEYEXPIRED = syscall.Errno(0x7f)
+ EKEYREJECTED = syscall.Errno(0x81)
+ EKEYREVOKED = syscall.Errno(0x80)
+ EL2HLT = syscall.Errno(0x33)
+ EL2NSYNC = syscall.Errno(0x2d)
+ EL3HLT = syscall.Errno(0x2e)
+ EL3RST = syscall.Errno(0x2f)
+ ELIBACC = syscall.Errno(0x4f)
+ ELIBBAD = syscall.Errno(0x50)
+ ELIBEXEC = syscall.Errno(0x53)
+ ELIBMAX = syscall.Errno(0x52)
+ ELIBSCN = syscall.Errno(0x51)
+ ELNRNG = syscall.Errno(0x30)
+ ELOOP = syscall.Errno(0x28)
+ EMEDIUMTYPE = syscall.Errno(0x7c)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x5a)
+ EMULTIHOP = syscall.Errno(0x48)
+ ENAMETOOLONG = syscall.Errno(0x24)
+ ENAVAIL = syscall.Errno(0x77)
+ ENETDOWN = syscall.Errno(0x64)
+ ENETRESET = syscall.Errno(0x66)
+ ENETUNREACH = syscall.Errno(0x65)
+ ENFILE = syscall.Errno(0x17)
+ ENOANO = syscall.Errno(0x37)
+ ENOBUFS = syscall.Errno(0x69)
+ ENOCSI = syscall.Errno(0x32)
+ ENODATA = syscall.Errno(0x3d)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOKEY = syscall.Errno(0x7e)
+ ENOLCK = syscall.Errno(0x25)
+ ENOLINK = syscall.Errno(0x43)
+ ENOMEDIUM = syscall.Errno(0x7b)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x2a)
+ ENONET = syscall.Errno(0x40)
+ ENOPKG = syscall.Errno(0x41)
+ ENOPROTOOPT = syscall.Errno(0x5c)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x3f)
+ ENOSTR = syscall.Errno(0x3c)
+ ENOSYS = syscall.Errno(0x26)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x6b)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x27)
+ ENOTNAM = syscall.Errno(0x76)
+ ENOTRECOVERABLE = syscall.Errno(0x83)
+ ENOTSOCK = syscall.Errno(0x58)
+ ENOTSUP = syscall.Errno(0x5f)
+ ENOTTY = syscall.Errno(0x19)
+ ENOTUNIQ = syscall.Errno(0x4c)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x5f)
+ EOVERFLOW = syscall.Errno(0x4b)
+ EOWNERDEAD = syscall.Errno(0x82)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x60)
+ EPIPE = syscall.Errno(0x20)
+ EPROTO = syscall.Errno(0x47)
+ EPROTONOSUPPORT = syscall.Errno(0x5d)
+ EPROTOTYPE = syscall.Errno(0x5b)
+ ERANGE = syscall.Errno(0x22)
+ EREMCHG = syscall.Errno(0x4e)
+ EREMOTE = syscall.Errno(0x42)
+ EREMOTEIO = syscall.Errno(0x79)
+ ERESTART = syscall.Errno(0x55)
+ ERFKILL = syscall.Errno(0x84)
+ EROFS = syscall.Errno(0x1e)
+ ESHUTDOWN = syscall.Errno(0x6c)
+ ESOCKTNOSUPPORT = syscall.Errno(0x5e)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESRMNT = syscall.Errno(0x45)
+ ESTALE = syscall.Errno(0x74)
+ ESTRPIPE = syscall.Errno(0x56)
+ ETIME = syscall.Errno(0x3e)
+ ETIMEDOUT = syscall.Errno(0x6e)
+ ETOOMANYREFS = syscall.Errno(0x6d)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUCLEAN = syscall.Errno(0x75)
+ EUNATCH = syscall.Errno(0x31)
+ EUSERS = syscall.Errno(0x57)
+ EWOULDBLOCK = syscall.Errno(0xb)
+ EXDEV = syscall.Errno(0x12)
+ EXFULL = syscall.Errno(0x36)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0x7)
+ SIGCHLD = syscall.Signal(0x11)
+ SIGCLD = syscall.Signal(0x11)
+ SIGCONT = syscall.Signal(0x12)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x1d)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPOLL = syscall.Signal(0x1d)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x1e)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTKFLT = syscall.Signal(0x10)
+ SIGSTOP = syscall.Signal(0x13)
+ SIGSYS = syscall.Signal(0x1f)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x14)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGUNUSED = syscall.Signal(0x1f)
+ SIGURG = syscall.Signal(0x17)
+ SIGUSR1 = syscall.Signal(0xa)
+ SIGUSR2 = syscall.Signal(0xc)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "resource deadlock avoided",
+ 36: "file name too long",
+ 37: "no locks available",
+ 38: "function not implemented",
+ 39: "directory not empty",
+ 40: "too many levels of symbolic links",
+ 42: "no message of desired type",
+ 43: "identifier removed",
+ 44: "channel number out of range",
+ 45: "level 2 not synchronized",
+ 46: "level 3 halted",
+ 47: "level 3 reset",
+ 48: "link number out of range",
+ 49: "protocol driver not attached",
+ 50: "no CSI structure available",
+ 51: "level 2 halted",
+ 52: "invalid exchange",
+ 53: "invalid request descriptor",
+ 54: "exchange full",
+ 55: "no anode",
+ 56: "invalid request code",
+ 57: "invalid slot",
+ 58: "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",
+ 72: "multihop attempted",
+ 73: "RFS specific error",
+ 74: "bad message",
+ 75: "value too large for defined data type",
+ 76: "name not unique on network",
+ 77: "file descriptor in bad state",
+ 78: "remote address changed",
+ 79: "can not access a needed shared library",
+ 80: "accessing a corrupted shared library",
+ 81: ".lib section in a.out corrupted",
+ 82: "attempting to link in too many shared libraries",
+ 83: "cannot exec a shared library directly",
+ 84: "invalid or incomplete multibyte or wide character",
+ 85: "interrupted system call should be restarted",
+ 86: "streams pipe error",
+ 87: "too many users",
+ 88: "socket operation on non-socket",
+ 89: "destination address required",
+ 90: "message too long",
+ 91: "protocol wrong type for socket",
+ 92: "protocol not available",
+ 93: "protocol not supported",
+ 94: "socket type not supported",
+ 95: "operation not supported",
+ 96: "protocol family not supported",
+ 97: "address family not supported by protocol",
+ 98: "address already in use",
+ 99: "cannot assign requested address",
+ 100: "network is down",
+ 101: "network is unreachable",
+ 102: "network dropped connection on reset",
+ 103: "software caused connection abort",
+ 104: "connection reset by peer",
+ 105: "no buffer space available",
+ 106: "transport endpoint is already connected",
+ 107: "transport endpoint is not connected",
+ 108: "cannot send after transport endpoint shutdown",
+ 109: "too many references: cannot splice",
+ 110: "connection timed out",
+ 111: "connection refused",
+ 112: "host is down",
+ 113: "no route to host",
+ 114: "operation already in progress",
+ 115: "operation now in progress",
+ 116: "stale file handle",
+ 117: "structure needs cleaning",
+ 118: "not a XENIX named type file",
+ 119: "no XENIX semaphores available",
+ 120: "is a named type file",
+ 121: "remote I/O error",
+ 122: "disk quota exceeded",
+ 123: "no medium found",
+ 124: "wrong medium type",
+ 125: "operation canceled",
+ 126: "required key not available",
+ 127: "key has expired",
+ 128: "key has been revoked",
+ 129: "key was rejected by service",
+ 130: "owner died",
+ 131: "state not recoverable",
+ 132: "operation not possible due to RF-kill",
+ 133: "memory page has hardware error",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/breakpoint trap",
+ 6: "aborted",
+ 7: "bus error",
+ 8: "floating point exception",
+ 9: "killed",
+ 10: "user defined signal 1",
+ 11: "segmentation fault",
+ 12: "user defined signal 2",
+ 13: "broken pipe",
+ 14: "alarm clock",
+ 15: "terminated",
+ 16: "stack fault",
+ 17: "child exited",
+ 18: "continued",
+ 19: "stopped (signal)",
+ 20: "stopped",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "urgent I/O condition",
+ 24: "CPU time limit exceeded",
+ 25: "file size limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window changed",
+ 29: "I/O possible",
+ 30: "power failure",
+ 31: "bad system call",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go
new file mode 100644
index 0000000..9a2b3b3
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go
@@ -0,0 +1,2250 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build ppc64le,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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 = 0x17
+ B110 = 0x3
+ B115200 = 0x11
+ B1152000 = 0x18
+ B1200 = 0x9
+ B134 = 0x4
+ B150 = 0x5
+ B1500000 = 0x19
+ B1800 = 0xa
+ B19200 = 0xe
+ B200 = 0x6
+ B2000000 = 0x1a
+ B230400 = 0x12
+ B2400 = 0xb
+ B2500000 = 0x1b
+ B300 = 0x7
+ B3000000 = 0x1c
+ B3500000 = 0x1d
+ B38400 = 0xf
+ B4000000 = 0x1e
+ B460800 = 0x13
+ B4800 = 0xc
+ B50 = 0x1
+ B500000 = 0x14
+ B57600 = 0x10
+ B576000 = 0x15
+ B600 = 0x8
+ B75 = 0x2
+ B921600 = 0x16
+ B9600 = 0xd
+ BLKBSZGET = 0x40081270
+ BLKBSZSET = 0x80081271
+ BLKFLSBUF = 0x20001261
+ BLKFRAGET = 0x20001265
+ BLKFRASET = 0x20001264
+ BLKGETSIZE = 0x20001260
+ BLKGETSIZE64 = 0x40081272
+ BLKPBSZGET = 0x2000127b
+ BLKRAGET = 0x20001263
+ BLKRASET = 0x20001262
+ BLKROGET = 0x2000125e
+ BLKROSET = 0x2000125d
+ BLKRRPART = 0x2000125f
+ BLKSECTGET = 0x20001267
+ BLKSECTSET = 0x20001266
+ BLKSSZGET = 0x20001268
+ BOTHER = 0x1f
+ 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 = 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_RAW_FILTER_MAX = 0x200
+ 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
+ CIBAUD = 0xff0000
+ CLOCAL = 0x8000
+ 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 = 0x1000
+ CR2 = 0x2000
+ CR3 = 0x3000
+ CRDLY = 0x3000
+ CREAD = 0x800
+ CRTSCTS = 0x80000000
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIGNAL = 0xff
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x0
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x800
+ EFD_SEMAPHORE = 0x1
+ 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_NCSI = 0x88f8
+ 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 = 0x10000000
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x4000
+ FFDLY = 0x4000
+ FLUSHO = 0x800000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x406
+ F_EXLCK = 0x4
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLEASE = 0x401
+ F_GETLK = 0x5
+ F_GETLK64 = 0xc
+ F_GETOWN = 0x9
+ 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 = 0x6
+ F_SETLK64 = 0xd
+ F_SETLKW = 0x7
+ F_SETLKW64 = 0xe
+ F_SETOWN = 0x8
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ HUPCL = 0x4000
+ IBSHIFT = 0x10
+ ICANON = 0x100
+ ICMPV6_FILTER = 0x1
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ 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 = 0x800
+ 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 = 0x80
+ ISTRIP = 0x20
+ IUCLC = 0x1000
+ IUTF8 = 0x4000
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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 = 0x20
+ MAP_ANONYMOUS = 0x20
+ MAP_DENYWRITE = 0x800
+ MAP_EXECUTABLE = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_GROWSDOWN = 0x100
+ MAP_HUGETLB = 0x40000
+ MAP_HUGE_MASK = 0x3f
+ MAP_HUGE_SHIFT = 0x1a
+ MAP_LOCKED = 0x80
+ MAP_NONBLOCK = 0x10000
+ MAP_NORESERVE = 0x40
+ MAP_POPULATE = 0x8000
+ MAP_PRIVATE = 0x2
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x20000
+ MAP_TYPE = 0xf
+ MCL_CURRENT = 0x2000
+ MCL_FUTURE = 0x4000
+ MCL_ONFAULT = 0x8000
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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
+ NL2 = 0x200
+ NL3 = 0x300
+ NLA_ALIGNTO = 0x4
+ NLA_F_NESTED = 0x8000
+ NLA_F_NET_BYTEORDER = 0x4000
+ NLA_HDRLEN = 0x4
+ NLDLY = 0x300
+ 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 = 0x80000000
+ OCRNL = 0x8
+ OFDEL = 0x80
+ OFILL = 0x40
+ OLCUC = 0x4
+ ONLCR = 0x2
+ ONLRET = 0x20
+ ONOCR = 0x10
+ OPOST = 0x1
+ O_ACCMODE = 0x3
+ O_APPEND = 0x400
+ O_ASYNC = 0x2000
+ O_CLOEXEC = 0x80000
+ O_CREAT = 0x40
+ O_DIRECT = 0x20000
+ O_DIRECTORY = 0x4000
+ O_DSYNC = 0x1000
+ O_EXCL = 0x80
+ O_FSYNC = 0x101000
+ O_LARGEFILE = 0x0
+ O_NDELAY = 0x800
+ O_NOATIME = 0x40000
+ O_NOCTTY = 0x100
+ O_NOFOLLOW = 0x8000
+ O_NONBLOCK = 0x800
+ O_PATH = 0x200000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x101000
+ O_SYNC = 0x101000
+ O_TMPFILE = 0x404000
+ 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 = 0x1000
+ 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 = 0x2000
+ PENDIN = 0x20000000
+ PERF_EVENT_IOC_DISABLE = 0x20002401
+ PERF_EVENT_IOC_ENABLE = 0x20002400
+ PERF_EVENT_IOC_ID = 0x40082407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409
+ PERF_EVENT_IOC_PERIOD = 0x80082404
+ PERF_EVENT_IOC_REFRESH = 0x20002402
+ PERF_EVENT_IOC_RESET = 0x20002403
+ PERF_EVENT_IOC_SET_BPF = 0x80042408
+ PERF_EVENT_IOC_SET_FILTER = 0x80082406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x20002405
+ 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_SAO = 0x10
+ 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 = -0x1
+ 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_GETEVRREGS = 0x14
+ PTRACE_GETFPREGS = 0xe
+ PTRACE_GETREGS = 0xc
+ PTRACE_GETREGS64 = 0x16
+ PTRACE_GETREGSET = 0x4204
+ PTRACE_GETSIGINFO = 0x4202
+ PTRACE_GETSIGMASK = 0x420a
+ PTRACE_GETVRREGS = 0x12
+ PTRACE_GETVSRREGS = 0x1b
+ PTRACE_GET_DEBUGREG = 0x19
+ PTRACE_INTERRUPT = 0x4207
+ PTRACE_KILL = 0x8
+ PTRACE_LISTEN = 0x4208
+ 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_PEEKSIGINFO = 0x4209
+ PTRACE_PEEKSIGINFO_SHARED = 0x1
+ PTRACE_PEEKTEXT = 0x1
+ PTRACE_PEEKUSR = 0x3
+ PTRACE_POKEDATA = 0x5
+ PTRACE_POKETEXT = 0x4
+ PTRACE_POKEUSR = 0x6
+ PTRACE_SECCOMP_GET_FILTER = 0x420c
+ PTRACE_SEIZE = 0x4206
+ PTRACE_SETEVRREGS = 0x15
+ PTRACE_SETFPREGS = 0xf
+ PTRACE_SETOPTIONS = 0x4200
+ PTRACE_SETREGS = 0xd
+ PTRACE_SETREGS64 = 0x17
+ PTRACE_SETREGSET = 0x4205
+ PTRACE_SETSIGINFO = 0x4203
+ PTRACE_SETSIGMASK = 0x420b
+ PTRACE_SETVRREGS = 0x13
+ PTRACE_SETVSRREGS = 0x1c
+ PTRACE_SET_DEBUGREG = 0x1a
+ PTRACE_SINGLEBLOCK = 0x100
+ PTRACE_SINGLESTEP = 0x9
+ PTRACE_SYSCALL = 0x18
+ PTRACE_TRACEME = 0x0
+ PT_CCR = 0x26
+ PT_CTR = 0x23
+ PT_DAR = 0x29
+ PT_DSCR = 0x2c
+ PT_DSISR = 0x2a
+ PT_FPR0 = 0x30
+ PT_FPSCR = 0x50
+ PT_LNK = 0x24
+ PT_MSR = 0x21
+ PT_NIP = 0x20
+ PT_ORIG_R3 = 0x22
+ PT_R0 = 0x0
+ PT_R1 = 0x1
+ PT_R10 = 0xa
+ PT_R11 = 0xb
+ PT_R12 = 0xc
+ PT_R13 = 0xd
+ PT_R14 = 0xe
+ PT_R15 = 0xf
+ PT_R16 = 0x10
+ PT_R17 = 0x11
+ PT_R18 = 0x12
+ PT_R19 = 0x13
+ PT_R2 = 0x2
+ PT_R20 = 0x14
+ PT_R21 = 0x15
+ PT_R22 = 0x16
+ PT_R23 = 0x17
+ PT_R24 = 0x18
+ PT_R25 = 0x19
+ PT_R26 = 0x1a
+ PT_R27 = 0x1b
+ PT_R28 = 0x1c
+ PT_R29 = 0x1d
+ PT_R3 = 0x3
+ PT_R30 = 0x1e
+ PT_R31 = 0x1f
+ PT_R4 = 0x4
+ PT_R5 = 0x5
+ PT_R6 = 0x6
+ PT_R7 = 0x7
+ PT_R8 = 0x8
+ PT_R9 = 0x9
+ PT_REGS_COUNT = 0x2c
+ PT_RESULT = 0x2b
+ PT_SOFTE = 0x27
+ PT_TRAP = 0x28
+ PT_VR0 = 0x52
+ PT_VRSAVE = 0x94
+ PT_VSCR = 0x93
+ PT_VSR0 = 0x96
+ PT_VSR31 = 0xd4
+ PT_XER = 0x25
+ RLIMIT_AS = 0x9
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x8
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x7
+ RLIMIT_NPROC = 0x6
+ RLIMIT_RSS = 0x5
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x8905
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x8904
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x4004667f
+ SIOCOUTQ = 0x40047473
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x8902
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x2
+ SOCK_IOC_TYPE = 0x89
+ SOCK_NONBLOCK = 0x800
+ SOCK_PACKET = 0xa
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ 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 = 0x1
+ SOL_TCP = 0x6
+ SOL_TIPC = 0x10f
+ SOL_X25 = 0x106
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x1e
+ 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 = 0x6
+ SO_BSDCOMPAT = 0xe
+ SO_BUSY_POLL = 0x2e
+ SO_CNX_ADVICE = 0x35
+ SO_DEBUG = 0x1
+ SO_DETACH_BPF = 0x1b
+ SO_DETACH_FILTER = 0x1b
+ SO_DOMAIN = 0x27
+ SO_DONTROUTE = 0x5
+ SO_ERROR = 0x4
+ SO_GET_FILTER = 0x1a
+ SO_INCOMING_CPU = 0x31
+ SO_KEEPALIVE = 0x9
+ SO_LINGER = 0xd
+ SO_LOCK_FILTER = 0x2c
+ SO_MARK = 0x24
+ SO_MAX_PACING_RATE = 0x2f
+ SO_NOFCS = 0x2b
+ SO_NO_CHECK = 0xb
+ SO_OOBINLINE = 0xa
+ SO_PASSCRED = 0x14
+ SO_PASSSEC = 0x22
+ SO_PEEK_OFF = 0x2a
+ SO_PEERCRED = 0x15
+ SO_PEERNAME = 0x1c
+ SO_PEERSEC = 0x1f
+ SO_PRIORITY = 0xc
+ SO_PROTOCOL = 0x26
+ SO_RCVBUF = 0x8
+ SO_RCVBUFFORCE = 0x21
+ SO_RCVLOWAT = 0x10
+ SO_RCVTIMEO = 0x12
+ SO_REUSEADDR = 0x2
+ SO_REUSEPORT = 0xf
+ 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 = 0x7
+ SO_SNDBUFFORCE = 0x20
+ SO_SNDLOWAT = 0x11
+ SO_SNDTIMEO = 0x13
+ SO_TIMESTAMP = 0x1d
+ SO_TIMESTAMPING = 0x25
+ SO_TIMESTAMPNS = 0x23
+ SO_TYPE = 0x3
+ SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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 = 0x400
+ TAB2 = 0x800
+ TAB3 = 0xc00
+ TABDLY = 0xc00
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ TCFLSH = 0x2000741f
+ TCGETA = 0x40147417
+ TCGETS = 0x402c7413
+ 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_REPAIR_WINDOW = 0x1d
+ 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 = 0x2
+ TCSBRK = 0x2000741d
+ TCSBRKP = 0x5425
+ TCSETA = 0x80147418
+ TCSETAF = 0x8014741c
+ TCSETAW = 0x80147419
+ TCSETS = 0x802c7414
+ TCSETSF = 0x802c7416
+ TCSETSW = 0x802c7415
+ TCXONC = 0x2000741e
+ TIOCCBRK = 0x5428
+ TIOCCONS = 0x541d
+ TIOCEXCL = 0x540c
+ TIOCGDEV = 0x40045432
+ TIOCGETC = 0x40067412
+ TIOCGETD = 0x5424
+ TIOCGETP = 0x40067408
+ TIOCGEXCL = 0x40045440
+ TIOCGICOUNT = 0x545d
+ TIOCGLCKTRMIOS = 0x5456
+ TIOCGLTC = 0x40067474
+ TIOCGPGRP = 0x40047477
+ TIOCGPKT = 0x40045438
+ TIOCGPTLCK = 0x40045439
+ TIOCGPTN = 0x40045430
+ TIOCGRS485 = 0x542e
+ TIOCGSERIAL = 0x541e
+ TIOCGSID = 0x5429
+ TIOCGSOFTCAR = 0x5419
+ TIOCGWINSZ = 0x40087468
+ TIOCINQ = 0x4004667f
+ TIOCLINUX = 0x541c
+ TIOCMBIC = 0x5417
+ TIOCMBIS = 0x5416
+ TIOCMGET = 0x5415
+ TIOCMIWAIT = 0x545c
+ TIOCMSET = 0x5418
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_LOOP = 0x8000
+ TIOCM_OUT1 = 0x2000
+ TIOCM_OUT2 = 0x4000
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x5422
+ TIOCNXCL = 0x540d
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x5420
+ 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 = 0x540e
+ TIOCSERCONFIG = 0x5453
+ TIOCSERGETLSR = 0x5459
+ TIOCSERGETMULTI = 0x545a
+ TIOCSERGSTRUCT = 0x5458
+ TIOCSERGWILD = 0x5454
+ TIOCSERSETMULTI = 0x545b
+ TIOCSERSWILD = 0x5455
+ TIOCSER_TEMT = 0x1
+ TIOCSETC = 0x80067411
+ TIOCSETD = 0x5423
+ TIOCSETN = 0x8006740a
+ TIOCSETP = 0x80067409
+ TIOCSIG = 0x80045436
+ TIOCSLCKTRMIOS = 0x5457
+ TIOCSLTC = 0x80067475
+ TIOCSPGRP = 0x80047476
+ TIOCSPTLCK = 0x80045431
+ TIOCSRS485 = 0x542f
+ TIOCSSERIAL = 0x541f
+ TIOCSSOFTCAR = 0x541a
+ TIOCSTART = 0x2000746e
+ TIOCSTI = 0x5412
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCVHANGUP = 0x5437
+ TOSTOP = 0x400000
+ TS_COMM_LEN = 0x20
+ TUNATTACHFILTER = 0x801054d5
+ TUNDETACHFILTER = 0x801054d6
+ TUNGETFEATURES = 0x400454cf
+ TUNGETFILTER = 0x401054db
+ 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
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0x10
+ VEOF = 0x4
+ VEOL = 0x6
+ VEOL2 = 0x8
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x5
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ VQUIT = 0x1
+ VREPRINT = 0xb
+ VSTART = 0xd
+ VSTOP = 0xe
+ VSUSP = 0xc
+ VSWTC = 0x9
+ VT0 = 0x0
+ VT1 = 0x10000
+ VTDLY = 0x10000
+ VTIME = 0x7
+ VWERASE = 0xa
+ WALL = 0x40000000
+ WCLONE = 0x80000000
+ WCONTINUED = 0x8
+ WEXITED = 0x4
+ WNOHANG = 0x1
+ WNOTHREAD = 0x20000000
+ WNOWAIT = 0x1000000
+ WORDSIZE = 0x40
+ WSTOPPED = 0x2
+ WUNTRACED = 0x2
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 0x2
+ XCASE = 0x4000
+ XTABS = 0xc00
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x62)
+ EADDRNOTAVAIL = syscall.Errno(0x63)
+ EADV = syscall.Errno(0x44)
+ EAFNOSUPPORT = syscall.Errno(0x61)
+ EAGAIN = syscall.Errno(0xb)
+ EALREADY = syscall.Errno(0x72)
+ EBADE = syscall.Errno(0x34)
+ EBADF = syscall.Errno(0x9)
+ EBADFD = syscall.Errno(0x4d)
+ EBADMSG = syscall.Errno(0x4a)
+ EBADR = syscall.Errno(0x35)
+ EBADRQC = syscall.Errno(0x38)
+ EBADSLT = syscall.Errno(0x39)
+ EBFONT = syscall.Errno(0x3b)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x7d)
+ ECHILD = syscall.Errno(0xa)
+ ECHRNG = syscall.Errno(0x2c)
+ ECOMM = syscall.Errno(0x46)
+ ECONNABORTED = syscall.Errno(0x67)
+ ECONNREFUSED = syscall.Errno(0x6f)
+ ECONNRESET = syscall.Errno(0x68)
+ EDEADLK = syscall.Errno(0x23)
+ EDEADLOCK = syscall.Errno(0x3a)
+ EDESTADDRREQ = syscall.Errno(0x59)
+ EDOM = syscall.Errno(0x21)
+ EDOTDOT = syscall.Errno(0x49)
+ EDQUOT = syscall.Errno(0x7a)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EHOSTDOWN = syscall.Errno(0x70)
+ EHOSTUNREACH = syscall.Errno(0x71)
+ EHWPOISON = syscall.Errno(0x85)
+ EIDRM = syscall.Errno(0x2b)
+ EILSEQ = syscall.Errno(0x54)
+ EINPROGRESS = syscall.Errno(0x73)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x6a)
+ EISDIR = syscall.Errno(0x15)
+ EISNAM = syscall.Errno(0x78)
+ EKEYEXPIRED = syscall.Errno(0x7f)
+ EKEYREJECTED = syscall.Errno(0x81)
+ EKEYREVOKED = syscall.Errno(0x80)
+ EL2HLT = syscall.Errno(0x33)
+ EL2NSYNC = syscall.Errno(0x2d)
+ EL3HLT = syscall.Errno(0x2e)
+ EL3RST = syscall.Errno(0x2f)
+ ELIBACC = syscall.Errno(0x4f)
+ ELIBBAD = syscall.Errno(0x50)
+ ELIBEXEC = syscall.Errno(0x53)
+ ELIBMAX = syscall.Errno(0x52)
+ ELIBSCN = syscall.Errno(0x51)
+ ELNRNG = syscall.Errno(0x30)
+ ELOOP = syscall.Errno(0x28)
+ EMEDIUMTYPE = syscall.Errno(0x7c)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x5a)
+ EMULTIHOP = syscall.Errno(0x48)
+ ENAMETOOLONG = syscall.Errno(0x24)
+ ENAVAIL = syscall.Errno(0x77)
+ ENETDOWN = syscall.Errno(0x64)
+ ENETRESET = syscall.Errno(0x66)
+ ENETUNREACH = syscall.Errno(0x65)
+ ENFILE = syscall.Errno(0x17)
+ ENOANO = syscall.Errno(0x37)
+ ENOBUFS = syscall.Errno(0x69)
+ ENOCSI = syscall.Errno(0x32)
+ ENODATA = syscall.Errno(0x3d)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOKEY = syscall.Errno(0x7e)
+ ENOLCK = syscall.Errno(0x25)
+ ENOLINK = syscall.Errno(0x43)
+ ENOMEDIUM = syscall.Errno(0x7b)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x2a)
+ ENONET = syscall.Errno(0x40)
+ ENOPKG = syscall.Errno(0x41)
+ ENOPROTOOPT = syscall.Errno(0x5c)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x3f)
+ ENOSTR = syscall.Errno(0x3c)
+ ENOSYS = syscall.Errno(0x26)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x6b)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x27)
+ ENOTNAM = syscall.Errno(0x76)
+ ENOTRECOVERABLE = syscall.Errno(0x83)
+ ENOTSOCK = syscall.Errno(0x58)
+ ENOTSUP = syscall.Errno(0x5f)
+ ENOTTY = syscall.Errno(0x19)
+ ENOTUNIQ = syscall.Errno(0x4c)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x5f)
+ EOVERFLOW = syscall.Errno(0x4b)
+ EOWNERDEAD = syscall.Errno(0x82)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x60)
+ EPIPE = syscall.Errno(0x20)
+ EPROTO = syscall.Errno(0x47)
+ EPROTONOSUPPORT = syscall.Errno(0x5d)
+ EPROTOTYPE = syscall.Errno(0x5b)
+ ERANGE = syscall.Errno(0x22)
+ EREMCHG = syscall.Errno(0x4e)
+ EREMOTE = syscall.Errno(0x42)
+ EREMOTEIO = syscall.Errno(0x79)
+ ERESTART = syscall.Errno(0x55)
+ ERFKILL = syscall.Errno(0x84)
+ EROFS = syscall.Errno(0x1e)
+ ESHUTDOWN = syscall.Errno(0x6c)
+ ESOCKTNOSUPPORT = syscall.Errno(0x5e)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESRMNT = syscall.Errno(0x45)
+ ESTALE = syscall.Errno(0x74)
+ ESTRPIPE = syscall.Errno(0x56)
+ ETIME = syscall.Errno(0x3e)
+ ETIMEDOUT = syscall.Errno(0x6e)
+ ETOOMANYREFS = syscall.Errno(0x6d)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUCLEAN = syscall.Errno(0x75)
+ EUNATCH = syscall.Errno(0x31)
+ EUSERS = syscall.Errno(0x57)
+ EWOULDBLOCK = syscall.Errno(0xb)
+ EXDEV = syscall.Errno(0x12)
+ EXFULL = syscall.Errno(0x36)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0x7)
+ SIGCHLD = syscall.Signal(0x11)
+ SIGCLD = syscall.Signal(0x11)
+ SIGCONT = syscall.Signal(0x12)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x1d)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPOLL = syscall.Signal(0x1d)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x1e)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTKFLT = syscall.Signal(0x10)
+ SIGSTOP = syscall.Signal(0x13)
+ SIGSYS = syscall.Signal(0x1f)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x14)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGUNUSED = syscall.Signal(0x1f)
+ SIGURG = syscall.Signal(0x17)
+ SIGUSR1 = syscall.Signal(0xa)
+ SIGUSR2 = syscall.Signal(0xc)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "resource deadlock avoided",
+ 36: "file name too long",
+ 37: "no locks available",
+ 38: "function not implemented",
+ 39: "directory not empty",
+ 40: "too many levels of symbolic links",
+ 42: "no message of desired type",
+ 43: "identifier removed",
+ 44: "channel number out of range",
+ 45: "level 2 not synchronized",
+ 46: "level 3 halted",
+ 47: "level 3 reset",
+ 48: "link number out of range",
+ 49: "protocol driver not attached",
+ 50: "no CSI structure available",
+ 51: "level 2 halted",
+ 52: "invalid exchange",
+ 53: "invalid request descriptor",
+ 54: "exchange full",
+ 55: "no anode",
+ 56: "invalid request code",
+ 57: "invalid slot",
+ 58: "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",
+ 72: "multihop attempted",
+ 73: "RFS specific error",
+ 74: "bad message",
+ 75: "value too large for defined data type",
+ 76: "name not unique on network",
+ 77: "file descriptor in bad state",
+ 78: "remote address changed",
+ 79: "can not access a needed shared library",
+ 80: "accessing a corrupted shared library",
+ 81: ".lib section in a.out corrupted",
+ 82: "attempting to link in too many shared libraries",
+ 83: "cannot exec a shared library directly",
+ 84: "invalid or incomplete multibyte or wide character",
+ 85: "interrupted system call should be restarted",
+ 86: "streams pipe error",
+ 87: "too many users",
+ 88: "socket operation on non-socket",
+ 89: "destination address required",
+ 90: "message too long",
+ 91: "protocol wrong type for socket",
+ 92: "protocol not available",
+ 93: "protocol not supported",
+ 94: "socket type not supported",
+ 95: "operation not supported",
+ 96: "protocol family not supported",
+ 97: "address family not supported by protocol",
+ 98: "address already in use",
+ 99: "cannot assign requested address",
+ 100: "network is down",
+ 101: "network is unreachable",
+ 102: "network dropped connection on reset",
+ 103: "software caused connection abort",
+ 104: "connection reset by peer",
+ 105: "no buffer space available",
+ 106: "transport endpoint is already connected",
+ 107: "transport endpoint is not connected",
+ 108: "cannot send after transport endpoint shutdown",
+ 109: "too many references: cannot splice",
+ 110: "connection timed out",
+ 111: "connection refused",
+ 112: "host is down",
+ 113: "no route to host",
+ 114: "operation already in progress",
+ 115: "operation now in progress",
+ 116: "stale file handle",
+ 117: "structure needs cleaning",
+ 118: "not a XENIX named type file",
+ 119: "no XENIX semaphores available",
+ 120: "is a named type file",
+ 121: "remote I/O error",
+ 122: "disk quota exceeded",
+ 123: "no medium found",
+ 124: "wrong medium type",
+ 125: "operation canceled",
+ 126: "required key not available",
+ 127: "key has expired",
+ 128: "key has been revoked",
+ 129: "key was rejected by service",
+ 130: "owner died",
+ 131: "state not recoverable",
+ 132: "operation not possible due to RF-kill",
+ 133: "memory page has hardware error",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/breakpoint trap",
+ 6: "aborted",
+ 7: "bus error",
+ 8: "floating point exception",
+ 9: "killed",
+ 10: "user defined signal 1",
+ 11: "segmentation fault",
+ 12: "user defined signal 2",
+ 13: "broken pipe",
+ 14: "alarm clock",
+ 15: "terminated",
+ 16: "stack fault",
+ 17: "child exited",
+ 18: "continued",
+ 19: "stopped (signal)",
+ 20: "stopped",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "urgent I/O condition",
+ 24: "CPU time limit exceeded",
+ 25: "file size limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window changed",
+ 29: "I/O possible",
+ 30: "power failure",
+ 31: "bad system call",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go
new file mode 100644
index 0000000..2805f2d
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go
@@ -0,0 +1,2249 @@
+// mkerrors.sh -Wall -Werror -static -I/tmp/include -fsigned-char
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build s390x,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char _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 = 0x2b
+ 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_QIPCRTR = 0x2a
+ 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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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
+ BLKBSZGET = 0x80081270
+ BLKBSZSET = 0x40081271
+ BLKFLSBUF = 0x1261
+ BLKFRAGET = 0x1265
+ BLKFRASET = 0x1264
+ BLKGETSIZE = 0x1260
+ BLKGETSIZE64 = 0x80081272
+ BLKPBSZGET = 0x127b
+ BLKRAGET = 0x1263
+ BLKRASET = 0x1262
+ BLKROGET = 0x125e
+ BLKROSET = 0x125d
+ BLKRRPART = 0x125f
+ BLKSECTGET = 0x1267
+ BLKSECTSET = 0x1266
+ BLKSSZGET = 0x1268
+ 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_RAW_FILTER_MAX = 0x200
+ 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
+ EFD_CLOEXEC = 0x80000
+ EFD_NONBLOCK = 0x800
+ EFD_SEMAPHORE = 0x1
+ 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_NCSI = 0x88f8
+ 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
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_UNSHARE_RANGE = 0x40
+ FALLOC_FL_ZERO_RANGE = 0x10
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FF0 = 0x0
+ FF1 = 0x8000
+ FFDLY = 0x8000
+ FLUSHO = 0x1000
+ FS_ENCRYPTION_MODE_AES_256_CBC = 0x3
+ FS_ENCRYPTION_MODE_AES_256_CTS = 0x4
+ FS_ENCRYPTION_MODE_AES_256_GCM = 0x2
+ FS_ENCRYPTION_MODE_AES_256_XTS = 0x1
+ FS_ENCRYPTION_MODE_INVALID = 0x0
+ FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615
+ FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614
+ FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613
+ FS_KEY_DESCRIPTOR_SIZE = 0x8
+ FS_KEY_DESC_PREFIX = "fscrypt:"
+ FS_KEY_DESC_PREFIX_SIZE = 0x8
+ FS_MAX_KEY_SIZE = 0x40
+ FS_POLICY_FLAGS_PAD_16 = 0x2
+ FS_POLICY_FLAGS_PAD_32 = 0x3
+ FS_POLICY_FLAGS_PAD_4 = 0x0
+ FS_POLICY_FLAGS_PAD_8 = 0x1
+ FS_POLICY_FLAGS_PAD_MASK = 0x3
+ FS_POLICY_FLAGS_VALID = 0x3
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x406
+ F_EXLCK = 0x4
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLEASE = 0x401
+ F_GETLK = 0x5
+ F_GETLK64 = 0x5
+ F_GETOWN = 0x9
+ 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 = 0x6
+ F_SETLK64 = 0x6
+ F_SETLKW = 0x7
+ F_SETLKW64 = 0x7
+ F_SETOWN = 0x8
+ 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
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ HUPCL = 0x400
+ IBSHIFT = 0x10
+ ICANON = 0x2
+ ICMPV6_FILTER = 0x1
+ ICRNL = 0x100
+ IEXTEN = 0x8000
+ 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 = 0x800
+ 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
+ KEYCTL_ASSUME_AUTHORITY = 0x10
+ KEYCTL_CHOWN = 0x4
+ KEYCTL_CLEAR = 0x7
+ KEYCTL_DESCRIBE = 0x6
+ KEYCTL_DH_COMPUTE = 0x17
+ KEYCTL_GET_KEYRING_ID = 0x0
+ KEYCTL_GET_PERSISTENT = 0x16
+ KEYCTL_GET_SECURITY = 0x11
+ KEYCTL_INSTANTIATE = 0xc
+ KEYCTL_INSTANTIATE_IOV = 0x14
+ KEYCTL_INVALIDATE = 0x15
+ KEYCTL_JOIN_SESSION_KEYRING = 0x1
+ KEYCTL_LINK = 0x8
+ KEYCTL_NEGATE = 0xd
+ KEYCTL_READ = 0xb
+ KEYCTL_REJECT = 0x13
+ KEYCTL_REVOKE = 0x3
+ KEYCTL_SEARCH = 0xa
+ KEYCTL_SESSION_TO_PARENT = 0x12
+ KEYCTL_SETPERM = 0x5
+ KEYCTL_SET_REQKEY_KEYRING = 0xe
+ KEYCTL_SET_TIMEOUT = 0xf
+ KEYCTL_UNLINK = 0x9
+ KEYCTL_UPDATE = 0x2
+ KEY_REQKEY_DEFL_DEFAULT = 0x0
+ KEY_REQKEY_DEFL_GROUP_KEYRING = 0x6
+ KEY_REQKEY_DEFL_NO_CHANGE = -0x1
+ KEY_REQKEY_DEFL_PROCESS_KEYRING = 0x2
+ KEY_REQKEY_DEFL_REQUESTOR_KEYRING = 0x7
+ KEY_REQKEY_DEFL_SESSION_KEYRING = 0x3
+ KEY_REQKEY_DEFL_THREAD_KEYRING = 0x1
+ KEY_REQKEY_DEFL_USER_KEYRING = 0x4
+ KEY_REQKEY_DEFL_USER_SESSION_KEYRING = 0x5
+ KEY_SPEC_GROUP_KEYRING = -0x6
+ KEY_SPEC_PROCESS_KEYRING = -0x2
+ KEY_SPEC_REQKEY_AUTH_KEY = -0x7
+ KEY_SPEC_REQUESTOR_KEYRING = -0x8
+ KEY_SPEC_SESSION_KEYRING = -0x3
+ KEY_SPEC_THREAD_KEYRING = -0x1
+ KEY_SPEC_USER_KEYRING = -0x4
+ KEY_SPEC_USER_SESSION_KEYRING = -0x5
+ 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 = 0x20
+ MAP_ANONYMOUS = 0x20
+ MAP_DENYWRITE = 0x800
+ MAP_EXECUTABLE = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_GROWSDOWN = 0x100
+ MAP_HUGETLB = 0x40000
+ MAP_HUGE_MASK = 0x3f
+ MAP_HUGE_SHIFT = 0x1a
+ MAP_LOCKED = 0x2000
+ MAP_NONBLOCK = 0x10000
+ MAP_NORESERVE = 0x4000
+ MAP_POPULATE = 0x8000
+ MAP_PRIVATE = 0x2
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x20000
+ 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_BORN = 0x20000000
+ 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_NOREMOTELOCK = 0x8000000
+ MS_NOSEC = 0x10000000
+ 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
+ MS_VERBOSE = 0x8000
+ 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 = 0x400
+ O_ASYNC = 0x2000
+ O_CLOEXEC = 0x80000
+ O_CREAT = 0x40
+ O_DIRECT = 0x4000
+ O_DIRECTORY = 0x10000
+ O_DSYNC = 0x1000
+ O_EXCL = 0x80
+ O_FSYNC = 0x101000
+ O_LARGEFILE = 0x0
+ O_NDELAY = 0x800
+ O_NOATIME = 0x40000
+ O_NOCTTY = 0x100
+ O_NOFOLLOW = 0x20000
+ O_NONBLOCK = 0x800
+ O_PATH = 0x200000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x101000
+ O_SYNC = 0x101000
+ 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
+ PERF_EVENT_IOC_DISABLE = 0x2401
+ PERF_EVENT_IOC_ENABLE = 0x2400
+ PERF_EVENT_IOC_ID = 0x80082407
+ PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409
+ PERF_EVENT_IOC_PERIOD = 0x40082404
+ PERF_EVENT_IOC_REFRESH = 0x2402
+ PERF_EVENT_IOC_RESET = 0x2403
+ PERF_EVENT_IOC_SET_BPF = 0x40042408
+ PERF_EVENT_IOC_SET_FILTER = 0x40082406
+ PERF_EVENT_IOC_SET_OUTPUT = 0x2405
+ 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 = -0x1
+ 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_DISABLE_TE = 0x5010
+ PTRACE_ENABLE_TE = 0x5009
+ 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_GETREGS = 0xc
+ PTRACE_GETREGSET = 0x4204
+ PTRACE_GETSIGINFO = 0x4202
+ PTRACE_GETSIGMASK = 0x420a
+ PTRACE_GET_LAST_BREAK = 0x5006
+ 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_AREA = 0x5003
+ PTRACE_PEEKSIGINFO = 0x4209
+ PTRACE_PEEKSIGINFO_SHARED = 0x1
+ PTRACE_PEEKTEXT = 0x1
+ PTRACE_PEEKTEXT_AREA = 0x5002
+ PTRACE_PEEKUSR = 0x3
+ PTRACE_PEEKUSR_AREA = 0x5000
+ PTRACE_PEEK_SYSTEM_CALL = 0x5007
+ PTRACE_POKEDATA = 0x5
+ PTRACE_POKEDATA_AREA = 0x5005
+ PTRACE_POKETEXT = 0x4
+ PTRACE_POKETEXT_AREA = 0x5004
+ PTRACE_POKEUSR = 0x6
+ PTRACE_POKEUSR_AREA = 0x5001
+ PTRACE_POKE_SYSTEM_CALL = 0x5008
+ PTRACE_PROT = 0x15
+ PTRACE_SECCOMP_GET_FILTER = 0x420c
+ PTRACE_SEIZE = 0x4206
+ PTRACE_SETOPTIONS = 0x4200
+ PTRACE_SETREGS = 0xd
+ PTRACE_SETREGSET = 0x4205
+ PTRACE_SETSIGINFO = 0x4203
+ PTRACE_SETSIGMASK = 0x420b
+ PTRACE_SINGLEBLOCK = 0xc
+ PTRACE_SINGLESTEP = 0x9
+ PTRACE_SYSCALL = 0x18
+ PTRACE_TE_ABORT_RAND = 0x5011
+ PTRACE_TRACEME = 0x0
+ PT_ACR0 = 0x90
+ PT_ACR1 = 0x94
+ PT_ACR10 = 0xb8
+ PT_ACR11 = 0xbc
+ PT_ACR12 = 0xc0
+ PT_ACR13 = 0xc4
+ PT_ACR14 = 0xc8
+ PT_ACR15 = 0xcc
+ PT_ACR2 = 0x98
+ PT_ACR3 = 0x9c
+ PT_ACR4 = 0xa0
+ PT_ACR5 = 0xa4
+ PT_ACR6 = 0xa8
+ PT_ACR7 = 0xac
+ PT_ACR8 = 0xb0
+ PT_ACR9 = 0xb4
+ PT_CR_10 = 0x168
+ PT_CR_11 = 0x170
+ PT_CR_9 = 0x160
+ PT_ENDREGS = 0x1af
+ PT_FPC = 0xd8
+ PT_FPR0 = 0xe0
+ PT_FPR1 = 0xe8
+ PT_FPR10 = 0x130
+ PT_FPR11 = 0x138
+ PT_FPR12 = 0x140
+ PT_FPR13 = 0x148
+ PT_FPR14 = 0x150
+ PT_FPR15 = 0x158
+ PT_FPR2 = 0xf0
+ PT_FPR3 = 0xf8
+ PT_FPR4 = 0x100
+ PT_FPR5 = 0x108
+ PT_FPR6 = 0x110
+ PT_FPR7 = 0x118
+ PT_FPR8 = 0x120
+ PT_FPR9 = 0x128
+ PT_GPR0 = 0x10
+ PT_GPR1 = 0x18
+ PT_GPR10 = 0x60
+ PT_GPR11 = 0x68
+ PT_GPR12 = 0x70
+ PT_GPR13 = 0x78
+ PT_GPR14 = 0x80
+ PT_GPR15 = 0x88
+ PT_GPR2 = 0x20
+ PT_GPR3 = 0x28
+ PT_GPR4 = 0x30
+ PT_GPR5 = 0x38
+ PT_GPR6 = 0x40
+ PT_GPR7 = 0x48
+ PT_GPR8 = 0x50
+ PT_GPR9 = 0x58
+ PT_IEEE_IP = 0x1a8
+ PT_LASTOFF = 0x1a8
+ PT_ORIGGPR2 = 0xd0
+ PT_PSWADDR = 0x8
+ PT_PSWMASK = 0x0
+ RLIMIT_AS = 0x9
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_LOCKS = 0xa
+ RLIMIT_MEMLOCK = 0x8
+ RLIMIT_MSGQUEUE = 0xc
+ RLIMIT_NICE = 0xd
+ RLIMIT_NOFILE = 0x7
+ RLIMIT_NPROC = 0x6
+ RLIMIT_RSS = 0x5
+ RLIMIT_RTPRIO = 0xe
+ RLIMIT_RTTIME = 0xf
+ RLIMIT_SIGPENDING = 0xb
+ 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 = 0x19
+ 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 = 0x19
+ 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_TIMESTAMPING_OPT_STATS = 0x36
+ SCM_TIMESTAMPNS = 0x23
+ SCM_WIFI_STATUS = 0x29
+ SECCOMP_MODE_DISABLED = 0x0
+ SECCOMP_MODE_FILTER = 0x2
+ SECCOMP_MODE_STRICT = 0x1
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x8905
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x8904
+ SIOCGRARP = 0x8961
+ SIOCGSKNS = 0x894c
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x541b
+ SIOCOUTQ = 0x5411
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x8902
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x2
+ SOCK_IOC_TYPE = 0x89
+ SOCK_NONBLOCK = 0x800
+ SOCK_PACKET = 0xa
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ 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 = 0x1
+ SOL_TCP = 0x6
+ SOL_TIPC = 0x10f
+ SOL_X25 = 0x106
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x1e
+ 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 = 0x6
+ SO_BSDCOMPAT = 0xe
+ SO_BUSY_POLL = 0x2e
+ SO_CNX_ADVICE = 0x35
+ SO_DEBUG = 0x1
+ SO_DETACH_BPF = 0x1b
+ SO_DETACH_FILTER = 0x1b
+ SO_DOMAIN = 0x27
+ SO_DONTROUTE = 0x5
+ SO_ERROR = 0x4
+ SO_GET_FILTER = 0x1a
+ SO_INCOMING_CPU = 0x31
+ SO_KEEPALIVE = 0x9
+ SO_LINGER = 0xd
+ SO_LOCK_FILTER = 0x2c
+ SO_MARK = 0x24
+ SO_MAX_PACING_RATE = 0x2f
+ SO_NOFCS = 0x2b
+ SO_NO_CHECK = 0xb
+ SO_OOBINLINE = 0xa
+ SO_PASSCRED = 0x10
+ SO_PASSSEC = 0x22
+ SO_PEEK_OFF = 0x2a
+ SO_PEERCRED = 0x11
+ SO_PEERNAME = 0x1c
+ SO_PEERSEC = 0x1f
+ SO_PRIORITY = 0xc
+ SO_PROTOCOL = 0x26
+ SO_RCVBUF = 0x8
+ SO_RCVBUFFORCE = 0x21
+ SO_RCVLOWAT = 0x12
+ SO_RCVTIMEO = 0x14
+ SO_REUSEADDR = 0x2
+ SO_REUSEPORT = 0xf
+ 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 = 0x7
+ SO_SNDBUFFORCE = 0x20
+ SO_SNDLOWAT = 0x13
+ SO_SNDTIMEO = 0x15
+ SO_TIMESTAMP = 0x1d
+ SO_TIMESTAMPING = 0x25
+ SO_TIMESTAMPNS = 0x23
+ SO_TYPE = 0x3
+ SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x29
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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
+ TASKSTATS_CMD_ATTR_MAX = 0x4
+ TASKSTATS_CMD_MAX = 0x2
+ TASKSTATS_GENL_NAME = "TASKSTATS"
+ TASKSTATS_GENL_VERSION = 0x1
+ TASKSTATS_TYPE_MAX = 0x6
+ TASKSTATS_VERSION = 0x8
+ TCFLSH = 0x540b
+ TCGETA = 0x5405
+ TCGETS = 0x5401
+ TCGETS2 = 0x802c542a
+ TCGETX = 0x5432
+ 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_REPAIR_WINDOW = 0x1d
+ 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 = 0x2
+ TCSBRK = 0x5409
+ TCSBRKP = 0x5425
+ TCSETA = 0x5406
+ TCSETAF = 0x5408
+ TCSETAW = 0x5407
+ TCSETS = 0x5402
+ TCSETS2 = 0x402c542b
+ TCSETSF = 0x5404
+ TCSETSF2 = 0x402c542d
+ TCSETSW = 0x5403
+ TCSETSW2 = 0x402c542c
+ TCSETX = 0x5433
+ TCSETXF = 0x5434
+ TCSETXW = 0x5435
+ TCXONC = 0x540a
+ TIOCCBRK = 0x5428
+ TIOCCONS = 0x541d
+ TIOCEXCL = 0x540c
+ TIOCGDEV = 0x80045432
+ TIOCGETD = 0x5424
+ TIOCGEXCL = 0x80045440
+ TIOCGICOUNT = 0x545d
+ TIOCGLCKTRMIOS = 0x5456
+ TIOCGPGRP = 0x540f
+ TIOCGPKT = 0x80045438
+ TIOCGPTLCK = 0x80045439
+ TIOCGPTN = 0x80045430
+ TIOCGRS485 = 0x542e
+ TIOCGSERIAL = 0x541e
+ TIOCGSID = 0x5429
+ TIOCGSOFTCAR = 0x5419
+ TIOCGWINSZ = 0x5413
+ TIOCINQ = 0x541b
+ TIOCLINUX = 0x541c
+ TIOCMBIC = 0x5417
+ TIOCMBIS = 0x5416
+ TIOCMGET = 0x5415
+ TIOCMIWAIT = 0x545c
+ TIOCMSET = 0x5418
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x5422
+ TIOCNXCL = 0x540d
+ TIOCOUTQ = 0x5411
+ TIOCPKT = 0x5420
+ 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 = 0x540e
+ TIOCSERCONFIG = 0x5453
+ TIOCSERGETLSR = 0x5459
+ TIOCSERGETMULTI = 0x545a
+ TIOCSERGSTRUCT = 0x5458
+ TIOCSERGWILD = 0x5454
+ TIOCSERSETMULTI = 0x545b
+ TIOCSERSWILD = 0x5455
+ TIOCSER_TEMT = 0x1
+ TIOCSETD = 0x5423
+ TIOCSIG = 0x40045436
+ TIOCSLCKTRMIOS = 0x5457
+ TIOCSPGRP = 0x5410
+ TIOCSPTLCK = 0x40045431
+ TIOCSRS485 = 0x542f
+ TIOCSSERIAL = 0x541f
+ TIOCSSOFTCAR = 0x541a
+ TIOCSTI = 0x5412
+ TIOCSWINSZ = 0x5414
+ TIOCVHANGUP = 0x5437
+ TOSTOP = 0x100
+ TS_COMM_LEN = 0x20
+ TUNATTACHFILTER = 0x401054d5
+ TUNDETACHFILTER = 0x401054d6
+ TUNGETFEATURES = 0x800454cf
+ TUNGETFILTER = 0x801054db
+ TUNGETIFF = 0x800454d2
+ TUNGETSNDBUF = 0x800454d3
+ TUNGETVNETBE = 0x800454df
+ TUNGETVNETHDRSZ = 0x800454d7
+ TUNGETVNETLE = 0x800454dd
+ TUNSETDEBUG = 0x400454c9
+ TUNSETGROUP = 0x400454ce
+ TUNSETIFF = 0x400454ca
+ TUNSETIFINDEX = 0x400454da
+ TUNSETLINK = 0x400454cd
+ TUNSETNOCSUM = 0x400454c8
+ TUNSETOFFLOAD = 0x400454d0
+ TUNSETOWNER = 0x400454cc
+ TUNSETPERSIST = 0x400454cb
+ TUNSETQUEUE = 0x400454d9
+ TUNSETSNDBUF = 0x400454d4
+ TUNSETTXFILTER = 0x400454d1
+ TUNSETVNETBE = 0x400454de
+ TUNSETVNETHDRSZ = 0x400454d8
+ TUNSETVNETLE = 0x400454dc
+ UMOUNT_NOFOLLOW = 0x8
+ VDISCARD = 0xd
+ VEOF = 0x4
+ VEOL = 0xb
+ VEOL2 = 0x10
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x6
+ VM_SOCKETS_INVALID_VERSION = 0xffffffff
+ VQUIT = 0x1
+ VREPRINT = 0xc
+ VSTART = 0x8
+ VSTOP = 0x9
+ VSUSP = 0xa
+ VSWTC = 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 = 0x40
+ WSTOPPED = 0x2
+ WUNTRACED = 0x2
+ XATTR_CREATE = 0x1
+ XATTR_REPLACE = 0x2
+ XCASE = 0x4
+ XTABS = 0x1800
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x62)
+ EADDRNOTAVAIL = syscall.Errno(0x63)
+ EADV = syscall.Errno(0x44)
+ EAFNOSUPPORT = syscall.Errno(0x61)
+ EAGAIN = syscall.Errno(0xb)
+ EALREADY = syscall.Errno(0x72)
+ EBADE = syscall.Errno(0x34)
+ EBADF = syscall.Errno(0x9)
+ EBADFD = syscall.Errno(0x4d)
+ EBADMSG = syscall.Errno(0x4a)
+ EBADR = syscall.Errno(0x35)
+ EBADRQC = syscall.Errno(0x38)
+ EBADSLT = syscall.Errno(0x39)
+ EBFONT = syscall.Errno(0x3b)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x7d)
+ ECHILD = syscall.Errno(0xa)
+ ECHRNG = syscall.Errno(0x2c)
+ ECOMM = syscall.Errno(0x46)
+ ECONNABORTED = syscall.Errno(0x67)
+ ECONNREFUSED = syscall.Errno(0x6f)
+ ECONNRESET = syscall.Errno(0x68)
+ EDEADLK = syscall.Errno(0x23)
+ EDEADLOCK = syscall.Errno(0x23)
+ EDESTADDRREQ = syscall.Errno(0x59)
+ EDOM = syscall.Errno(0x21)
+ EDOTDOT = syscall.Errno(0x49)
+ EDQUOT = syscall.Errno(0x7a)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EHOSTDOWN = syscall.Errno(0x70)
+ EHOSTUNREACH = syscall.Errno(0x71)
+ EHWPOISON = syscall.Errno(0x85)
+ EIDRM = syscall.Errno(0x2b)
+ EILSEQ = syscall.Errno(0x54)
+ EINPROGRESS = syscall.Errno(0x73)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x6a)
+ EISDIR = syscall.Errno(0x15)
+ EISNAM = syscall.Errno(0x78)
+ EKEYEXPIRED = syscall.Errno(0x7f)
+ EKEYREJECTED = syscall.Errno(0x81)
+ EKEYREVOKED = syscall.Errno(0x80)
+ EL2HLT = syscall.Errno(0x33)
+ EL2NSYNC = syscall.Errno(0x2d)
+ EL3HLT = syscall.Errno(0x2e)
+ EL3RST = syscall.Errno(0x2f)
+ ELIBACC = syscall.Errno(0x4f)
+ ELIBBAD = syscall.Errno(0x50)
+ ELIBEXEC = syscall.Errno(0x53)
+ ELIBMAX = syscall.Errno(0x52)
+ ELIBSCN = syscall.Errno(0x51)
+ ELNRNG = syscall.Errno(0x30)
+ ELOOP = syscall.Errno(0x28)
+ EMEDIUMTYPE = syscall.Errno(0x7c)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x5a)
+ EMULTIHOP = syscall.Errno(0x48)
+ ENAMETOOLONG = syscall.Errno(0x24)
+ ENAVAIL = syscall.Errno(0x77)
+ ENETDOWN = syscall.Errno(0x64)
+ ENETRESET = syscall.Errno(0x66)
+ ENETUNREACH = syscall.Errno(0x65)
+ ENFILE = syscall.Errno(0x17)
+ ENOANO = syscall.Errno(0x37)
+ ENOBUFS = syscall.Errno(0x69)
+ ENOCSI = syscall.Errno(0x32)
+ ENODATA = syscall.Errno(0x3d)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOKEY = syscall.Errno(0x7e)
+ ENOLCK = syscall.Errno(0x25)
+ ENOLINK = syscall.Errno(0x43)
+ ENOMEDIUM = syscall.Errno(0x7b)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x2a)
+ ENONET = syscall.Errno(0x40)
+ ENOPKG = syscall.Errno(0x41)
+ ENOPROTOOPT = syscall.Errno(0x5c)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x3f)
+ ENOSTR = syscall.Errno(0x3c)
+ ENOSYS = syscall.Errno(0x26)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x6b)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x27)
+ ENOTNAM = syscall.Errno(0x76)
+ ENOTRECOVERABLE = syscall.Errno(0x83)
+ ENOTSOCK = syscall.Errno(0x58)
+ ENOTSUP = syscall.Errno(0x5f)
+ ENOTTY = syscall.Errno(0x19)
+ ENOTUNIQ = syscall.Errno(0x4c)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x5f)
+ EOVERFLOW = syscall.Errno(0x4b)
+ EOWNERDEAD = syscall.Errno(0x82)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x60)
+ EPIPE = syscall.Errno(0x20)
+ EPROTO = syscall.Errno(0x47)
+ EPROTONOSUPPORT = syscall.Errno(0x5d)
+ EPROTOTYPE = syscall.Errno(0x5b)
+ ERANGE = syscall.Errno(0x22)
+ EREMCHG = syscall.Errno(0x4e)
+ EREMOTE = syscall.Errno(0x42)
+ EREMOTEIO = syscall.Errno(0x79)
+ ERESTART = syscall.Errno(0x55)
+ ERFKILL = syscall.Errno(0x84)
+ EROFS = syscall.Errno(0x1e)
+ ESHUTDOWN = syscall.Errno(0x6c)
+ ESOCKTNOSUPPORT = syscall.Errno(0x5e)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESRMNT = syscall.Errno(0x45)
+ ESTALE = syscall.Errno(0x74)
+ ESTRPIPE = syscall.Errno(0x56)
+ ETIME = syscall.Errno(0x3e)
+ ETIMEDOUT = syscall.Errno(0x6e)
+ ETOOMANYREFS = syscall.Errno(0x6d)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUCLEAN = syscall.Errno(0x75)
+ EUNATCH = syscall.Errno(0x31)
+ EUSERS = syscall.Errno(0x57)
+ EWOULDBLOCK = syscall.Errno(0xb)
+ EXDEV = syscall.Errno(0x12)
+ EXFULL = syscall.Errno(0x36)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0x7)
+ SIGCHLD = syscall.Signal(0x11)
+ SIGCLD = syscall.Signal(0x11)
+ SIGCONT = syscall.Signal(0x12)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x1d)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPOLL = syscall.Signal(0x1d)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x1e)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTKFLT = syscall.Signal(0x10)
+ SIGSTOP = syscall.Signal(0x13)
+ SIGSYS = syscall.Signal(0x1f)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x14)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGUNUSED = syscall.Signal(0x1f)
+ SIGURG = syscall.Signal(0x17)
+ SIGUSR1 = syscall.Signal(0xa)
+ SIGUSR2 = syscall.Signal(0xc)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "resource deadlock avoided",
+ 36: "file name too long",
+ 37: "no locks available",
+ 38: "function not implemented",
+ 39: "directory not empty",
+ 40: "too many levels of symbolic links",
+ 42: "no message of desired type",
+ 43: "identifier removed",
+ 44: "channel number out of range",
+ 45: "level 2 not synchronized",
+ 46: "level 3 halted",
+ 47: "level 3 reset",
+ 48: "link number out of range",
+ 49: "protocol driver not attached",
+ 50: "no CSI structure available",
+ 51: "level 2 halted",
+ 52: "invalid exchange",
+ 53: "invalid request descriptor",
+ 54: "exchange full",
+ 55: "no anode",
+ 56: "invalid request code",
+ 57: "invalid slot",
+ 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",
+ 72: "multihop attempted",
+ 73: "RFS specific error",
+ 74: "bad message",
+ 75: "value too large for defined data type",
+ 76: "name not unique on network",
+ 77: "file descriptor in bad state",
+ 78: "remote address changed",
+ 79: "can not access a needed shared library",
+ 80: "accessing a corrupted shared library",
+ 81: ".lib section in a.out corrupted",
+ 82: "attempting to link in too many shared libraries",
+ 83: "cannot exec a shared library directly",
+ 84: "invalid or incomplete multibyte or wide character",
+ 85: "interrupted system call should be restarted",
+ 86: "streams pipe error",
+ 87: "too many users",
+ 88: "socket operation on non-socket",
+ 89: "destination address required",
+ 90: "message too long",
+ 91: "protocol wrong type for socket",
+ 92: "protocol not available",
+ 93: "protocol not supported",
+ 94: "socket type not supported",
+ 95: "operation not supported",
+ 96: "protocol family not supported",
+ 97: "address family not supported by protocol",
+ 98: "address already in use",
+ 99: "cannot assign requested address",
+ 100: "network is down",
+ 101: "network is unreachable",
+ 102: "network dropped connection on reset",
+ 103: "software caused connection abort",
+ 104: "connection reset by peer",
+ 105: "no buffer space available",
+ 106: "transport endpoint is already connected",
+ 107: "transport endpoint is not connected",
+ 108: "cannot send after transport endpoint shutdown",
+ 109: "too many references: cannot splice",
+ 110: "connection timed out",
+ 111: "connection refused",
+ 112: "host is down",
+ 113: "no route to host",
+ 114: "operation already in progress",
+ 115: "operation now in progress",
+ 116: "stale file handle",
+ 117: "structure needs cleaning",
+ 118: "not a XENIX named type file",
+ 119: "no XENIX semaphores available",
+ 120: "is a named type file",
+ 121: "remote I/O error",
+ 122: "disk quota exceeded",
+ 123: "no medium found",
+ 124: "wrong medium type",
+ 125: "operation canceled",
+ 126: "required key not available",
+ 127: "key has expired",
+ 128: "key has been revoked",
+ 129: "key was rejected by service",
+ 130: "owner died",
+ 131: "state not recoverable",
+ 132: "operation not possible due to RF-kill",
+ 133: "memory page has hardware error",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/breakpoint trap",
+ 6: "aborted",
+ 7: "bus error",
+ 8: "floating point exception",
+ 9: "killed",
+ 10: "user defined signal 1",
+ 11: "segmentation fault",
+ 12: "user defined signal 2",
+ 13: "broken pipe",
+ 14: "alarm clock",
+ 15: "terminated",
+ 16: "stack fault",
+ 17: "child exited",
+ 18: "continued",
+ 19: "stopped (signal)",
+ 20: "stopped",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "urgent I/O condition",
+ 24: "CPU time limit exceeded",
+ 25: "file size limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window changed",
+ 29: "I/O possible",
+ 30: "power failure",
+ 31: "bad system call",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go
new file mode 100644
index 0000000..95de199
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go
@@ -0,0 +1,2142 @@
+// mkerrors.sh -m64
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+// +build sparc64,linux
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m64 _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
+ ALG_OP_DECRYPT = 0x0
+ ALG_OP_ENCRYPT = 0x1
+ ALG_SET_AEAD_ASSOCLEN = 0x4
+ ALG_SET_AEAD_AUTHSIZE = 0x5
+ ALG_SET_IV = 0x2
+ ALG_SET_KEY = 0x1
+ ALG_SET_OP = 0x3
+ 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
+ ASI_LEON_DFLUSH = 0x11
+ ASI_LEON_IFLUSH = 0x10
+ ASI_LEON_MMUFLUSH = 0x18
+ B0 = 0x0
+ B1000000 = 0x100c
+ B110 = 0x3
+ B115200 = 0x1002
+ B1152000 = 0x100d
+ B1200 = 0x9
+ B134 = 0x4
+ B150 = 0x5
+ B1500000 = 0x100e
+ B153600 = 0x1006
+ B1800 = 0xa
+ B19200 = 0xe
+ B200 = 0x6
+ B2000000 = 0x100f
+ B230400 = 0x1003
+ B2400 = 0xb
+ B300 = 0x7
+ B307200 = 0x1007
+ B38400 = 0xf
+ B460800 = 0x1004
+ B4800 = 0xc
+ B50 = 0x1
+ B500000 = 0x100a
+ B57600 = 0x1001
+ B576000 = 0x100b
+ B600 = 0x8
+ B614400 = 0x1008
+ B75 = 0x2
+ B76800 = 0x1005
+ B921600 = 0x1009
+ B9600 = 0xd
+ BLKBSZGET = 0x80081270
+ BLKBSZSET = 0x40081271
+ BLKFLSBUF = 0x1261
+ BLKFRAGET = 0x1265
+ BLKFRASET = 0x1264
+ BLKGETSIZE = 0x1260
+ BLKGETSIZE64 = 0x80081272
+ BLKRAGET = 0x1263
+ BLKRASET = 0x1262
+ BLKROGET = 0x125e
+ BLKROSET = 0x125d
+ BLKRRPART = 0x125f
+ BLKSECTGET = 0x1267
+ BLKSECTSET = 0x1266
+ BLKSSZGET = 0x1268
+ 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
+ EMT_TAGOVF = 0x1
+ 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 = 0x400000
+ 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
+ FALLOC_FL_COLLAPSE_RANGE = 0x8
+ FALLOC_FL_INSERT_RANGE = 0x20
+ FALLOC_FL_KEEP_SIZE = 0x1
+ FALLOC_FL_NO_HIDE_STALE = 0x4
+ FALLOC_FL_PUNCH_HOLE = 0x2
+ FALLOC_FL_ZERO_RANGE = 0x10
+ 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 = 0x7
+ F_GETLK64 = 0x7
+ F_GETOWN = 0x5
+ 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 = 0x1
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLEASE = 0x400
+ F_SETLK = 0x8
+ F_SETLK64 = 0x8
+ F_SETLKW = 0x9
+ F_SETLKW64 = 0x9
+ F_SETOWN = 0x6
+ 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 = 0x3
+ F_WRLCK = 0x2
+ GRND_NONBLOCK = 0x1
+ GRND_RANDOM = 0x2
+ HUPCL = 0x400
+ IBSHIFT = 0x10
+ ICANON = 0x2
+ ICMPV6_FILTER = 0x1
+ ICRNL = 0x100
+ IEXTEN = 0x8000
+ 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 = 0x400000
+ 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 = 0x4000
+ 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 = 0x20
+ MAP_ANONYMOUS = 0x20
+ MAP_DENYWRITE = 0x800
+ MAP_EXECUTABLE = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_GROWSDOWN = 0x200
+ MAP_HUGETLB = 0x40000
+ MAP_HUGE_MASK = 0x3f
+ MAP_HUGE_SHIFT = 0x1a
+ MAP_LOCKED = 0x100
+ MAP_NONBLOCK = 0x10000
+ MAP_NORESERVE = 0x40
+ MAP_POPULATE = 0x8000
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x20000
+ MAP_TYPE = 0xf
+ MCL_CURRENT = 0x2000
+ MCL_FUTURE = 0x4000
+ MCL_ONFAULT = 0x8000
+ 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 = 0x40
+ O_CLOEXEC = 0x400000
+ O_CREAT = 0x200
+ O_DIRECT = 0x100000
+ O_DIRECTORY = 0x10000
+ O_DSYNC = 0x2000
+ O_EXCL = 0x800
+ O_FSYNC = 0x802000
+ O_LARGEFILE = 0x0
+ O_NDELAY = 0x4004
+ O_NOATIME = 0x200000
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x20000
+ O_NONBLOCK = 0x4000
+ O_PATH = 0x1000000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x802000
+ O_SYNC = 0x802000
+ O_TMPFILE = 0x2010000
+ O_TRUNC = 0x400
+ 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 = -0x1
+ 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_GETFPAREGS = 0x14
+ PTRACE_GETFPREGS = 0xe
+ PTRACE_GETFPREGS64 = 0x19
+ PTRACE_GETREGS = 0xc
+ PTRACE_GETREGS64 = 0x16
+ PTRACE_GETREGSET = 0x4204
+ PTRACE_GETSIGINFO = 0x4202
+ PTRACE_GETSIGMASK = 0x420a
+ PTRACE_INTERRUPT = 0x4207
+ PTRACE_KILL = 0x8
+ PTRACE_LISTEN = 0x4208
+ 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_PEEKSIGINFO = 0x4209
+ PTRACE_PEEKSIGINFO_SHARED = 0x1
+ PTRACE_PEEKTEXT = 0x1
+ PTRACE_PEEKUSR = 0x3
+ PTRACE_POKEDATA = 0x5
+ PTRACE_POKETEXT = 0x4
+ PTRACE_POKEUSR = 0x6
+ PTRACE_READDATA = 0x10
+ PTRACE_READTEXT = 0x12
+ PTRACE_SECCOMP_GET_FILTER = 0x420c
+ PTRACE_SEIZE = 0x4206
+ PTRACE_SETFPAREGS = 0x15
+ PTRACE_SETFPREGS = 0xf
+ PTRACE_SETFPREGS64 = 0x1a
+ PTRACE_SETOPTIONS = 0x4200
+ PTRACE_SETREGS = 0xd
+ PTRACE_SETREGS64 = 0x17
+ PTRACE_SETREGSET = 0x4205
+ PTRACE_SETSIGINFO = 0x4203
+ PTRACE_SETSIGMASK = 0x420b
+ PTRACE_SINGLESTEP = 0x9
+ PTRACE_SPARC_DETACH = 0xb
+ PTRACE_SYSCALL = 0x18
+ PTRACE_TRACEME = 0x0
+ PTRACE_WRITEDATA = 0x11
+ PTRACE_WRITETEXT = 0x13
+ PT_FP = 0x48
+ PT_G0 = 0x10
+ PT_G1 = 0x14
+ PT_G2 = 0x18
+ PT_G3 = 0x1c
+ PT_G4 = 0x20
+ PT_G5 = 0x24
+ PT_G6 = 0x28
+ PT_G7 = 0x2c
+ PT_I0 = 0x30
+ PT_I1 = 0x34
+ PT_I2 = 0x38
+ PT_I3 = 0x3c
+ PT_I4 = 0x40
+ PT_I5 = 0x44
+ PT_I6 = 0x48
+ PT_I7 = 0x4c
+ PT_NPC = 0x8
+ PT_PC = 0x4
+ PT_PSR = 0x0
+ PT_REGS_MAGIC = 0x57ac6c00
+ PT_TNPC = 0x90
+ PT_TPC = 0x88
+ PT_TSTATE = 0x80
+ PT_V9_FP = 0x70
+ PT_V9_G0 = 0x0
+ PT_V9_G1 = 0x8
+ PT_V9_G2 = 0x10
+ PT_V9_G3 = 0x18
+ PT_V9_G4 = 0x20
+ PT_V9_G5 = 0x28
+ PT_V9_G6 = 0x30
+ PT_V9_G7 = 0x38
+ PT_V9_I0 = 0x40
+ PT_V9_I1 = 0x48
+ PT_V9_I2 = 0x50
+ PT_V9_I3 = 0x58
+ PT_V9_I4 = 0x60
+ PT_V9_I5 = 0x68
+ PT_V9_I6 = 0x70
+ PT_V9_I7 = 0x78
+ PT_V9_MAGIC = 0x9c
+ PT_V9_TNPC = 0x90
+ PT_V9_TPC = 0x88
+ PT_V9_TSTATE = 0x80
+ PT_V9_Y = 0x98
+ PT_WIM = 0x10
+ PT_Y = 0xc
+ RLIMIT_AS = 0x9
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_NOFILE = 0x6
+ 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 = 0x23
+ SCM_TIMESTAMPNS = 0x21
+ SCM_WIFI_STATUS = 0x25
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDDLCI = 0x8980
+ SIOCADDMULTI = 0x8931
+ SIOCADDRT = 0x890b
+ SIOCATMARK = 0x8905
+ SIOCBONDCHANGEACTIVE = 0x8995
+ SIOCBONDENSLAVE = 0x8990
+ SIOCBONDINFOQUERY = 0x8994
+ SIOCBONDRELEASE = 0x8991
+ SIOCBONDSETHWADDR = 0x8992
+ SIOCBONDSLAVEINFOQUERY = 0x8993
+ SIOCBRADDBR = 0x89a0
+ SIOCBRADDIF = 0x89a2
+ SIOCBRDELBR = 0x89a1
+ SIOCBRDELIF = 0x89a3
+ SIOCDARP = 0x8953
+ SIOCDELDLCI = 0x8981
+ SIOCDELMULTI = 0x8932
+ SIOCDELRT = 0x890c
+ SIOCDEVPRIVATE = 0x89f0
+ SIOCDIFADDR = 0x8936
+ SIOCDRARP = 0x8960
+ SIOCETHTOOL = 0x8946
+ SIOCGARP = 0x8954
+ SIOCGHWTSTAMP = 0x89b1
+ 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
+ SIOCGIFVLAN = 0x8982
+ SIOCGMIIPHY = 0x8947
+ SIOCGMIIREG = 0x8948
+ SIOCGPGRP = 0x8904
+ SIOCGRARP = 0x8961
+ SIOCGSTAMP = 0x8906
+ SIOCGSTAMPNS = 0x8907
+ SIOCINQ = 0x4004667f
+ SIOCOUTQ = 0x40047473
+ SIOCOUTQNSD = 0x894b
+ SIOCPROTOPRIVATE = 0x89e0
+ SIOCRTMSG = 0x890d
+ SIOCSARP = 0x8955
+ SIOCSHWTSTAMP = 0x89b0
+ 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
+ SIOCSIFVLAN = 0x8983
+ SIOCSMIIREG = 0x8949
+ SIOCSPGRP = 0x8902
+ SIOCSRARP = 0x8962
+ SIOCWANDEV = 0x894a
+ SOCK_CLOEXEC = 0x400000
+ SOCK_DCCP = 0x6
+ SOCK_DGRAM = 0x2
+ SOCK_NONBLOCK = 0x4000
+ SOCK_PACKET = 0xa
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_AAL = 0x109
+ SOL_ALG = 0x117
+ SOL_ATM = 0x108
+ SOL_CAIF = 0x116
+ 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 = 0x8000
+ SO_ATTACH_BPF = 0x34
+ SO_ATTACH_FILTER = 0x1a
+ SO_ATTACH_REUSEPORT_CBPF = 0x35
+ SO_ATTACH_REUSEPORT_EBPF = 0x36
+ SO_BINDTODEVICE = 0xd
+ SO_BPF_EXTENSIONS = 0x32
+ SO_BROADCAST = 0x20
+ SO_BSDCOMPAT = 0x400
+ SO_BUSY_POLL = 0x30
+ SO_CNX_ADVICE = 0x37
+ 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 = 0x33
+ SO_KEEPALIVE = 0x8
+ SO_LINGER = 0x80
+ SO_LOCK_FILTER = 0x28
+ SO_MARK = 0x22
+ SO_MAX_PACING_RATE = 0x31
+ SO_NOFCS = 0x27
+ SO_NO_CHECK = 0xb
+ SO_OOBINLINE = 0x100
+ SO_PASSCRED = 0x2
+ SO_PASSSEC = 0x1f
+ SO_PEEK_OFF = 0x26
+ SO_PEERCRED = 0x40
+ SO_PEERNAME = 0x1c
+ SO_PEERSEC = 0x1e
+ SO_PRIORITY = 0xc
+ SO_PROTOCOL = 0x1028
+ SO_RCVBUF = 0x1002
+ SO_RCVBUFFORCE = 0x100b
+ SO_RCVLOWAT = 0x800
+ SO_RCVTIMEO = 0x2000
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_RXQ_OVFL = 0x24
+ SO_SECURITY_AUTHENTICATION = 0x5001
+ SO_SECURITY_ENCRYPTION_NETWORK = 0x5004
+ SO_SECURITY_ENCRYPTION_TRANSPORT = 0x5002
+ SO_SELECT_ERR_QUEUE = 0x29
+ SO_SNDBUF = 0x1001
+ SO_SNDBUFFORCE = 0x100a
+ SO_SNDLOWAT = 0x1000
+ SO_SNDTIMEO = 0x4000
+ SO_TIMESTAMP = 0x1d
+ SO_TIMESTAMPING = 0x23
+ SO_TIMESTAMPNS = 0x21
+ SO_TYPE = 0x1008
+ SO_VM_SOCKETS_BUFFER_MAX_SIZE = 0x2
+ SO_VM_SOCKETS_BUFFER_MIN_SIZE = 0x1
+ SO_VM_SOCKETS_BUFFER_SIZE = 0x0
+ SO_VM_SOCKETS_CONNECT_TIMEOUT = 0x6
+ SO_VM_SOCKETS_NONBLOCK_TXRX = 0x7
+ SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3
+ SO_VM_SOCKETS_TRUSTED = 0x5
+ SO_WIFI_STATUS = 0x25
+ SPLICE_F_GIFT = 0x8
+ SPLICE_F_MORE = 0x4
+ SPLICE_F_MOVE = 0x1
+ SPLICE_F_NONBLOCK = 0x2
+ 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 = 0x20005407
+ TCGETA = 0x40125401
+ TCGETS = 0x40245408
+ TCGETS2 = 0x402c540c
+ 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 = 0x2
+ TCSBRK = 0x20005405
+ TCSBRKP = 0x5425
+ TCSETA = 0x80125402
+ TCSETAF = 0x80125404
+ TCSETAW = 0x80125403
+ TCSETS = 0x80245409
+ TCSETS2 = 0x802c540d
+ TCSETSF = 0x8024540b
+ TCSETSF2 = 0x802c540f
+ TCSETSW = 0x8024540a
+ TCSETSW2 = 0x802c540e
+ TCXONC = 0x20005406
+ TIOCCBRK = 0x2000747a
+ TIOCCONS = 0x20007424
+ TIOCEXCL = 0x2000740d
+ TIOCGDEV = 0x40045432
+ TIOCGETD = 0x40047400
+ TIOCGEXCL = 0x40045440
+ TIOCGICOUNT = 0x545d
+ TIOCGLCKTRMIOS = 0x5456
+ TIOCGPGRP = 0x40047483
+ TIOCGPKT = 0x40045438
+ TIOCGPTLCK = 0x40045439
+ TIOCGPTN = 0x40047486
+ TIOCGRS485 = 0x40205441
+ TIOCGSERIAL = 0x541e
+ TIOCGSID = 0x40047485
+ TIOCGSOFTCAR = 0x40047464
+ TIOCGWINSZ = 0x40087468
+ TIOCINQ = 0x4004667f
+ TIOCLINUX = 0x541c
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGET = 0x4004746a
+ TIOCMIWAIT = 0x545c
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_LOOP = 0x8000
+ TIOCM_OUT1 = 0x2000
+ TIOCM_OUT2 = 0x4000
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ 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 = 0x2000747b
+ TIOCSCTTY = 0x20007484
+ TIOCSERCONFIG = 0x5453
+ TIOCSERGETLSR = 0x5459
+ TIOCSERGETMULTI = 0x545a
+ TIOCSERGSTRUCT = 0x5458
+ TIOCSERGWILD = 0x5454
+ TIOCSERSETMULTI = 0x545b
+ TIOCSERSWILD = 0x5455
+ TIOCSER_TEMT = 0x1
+ TIOCSETD = 0x80047401
+ TIOCSIG = 0x80047488
+ TIOCSLCKTRMIOS = 0x5457
+ TIOCSPGRP = 0x80047482
+ TIOCSPTLCK = 0x80047487
+ TIOCSRS485 = 0xc0205442
+ TIOCSSERIAL = 0x541f
+ TIOCSSOFTCAR = 0x80047465
+ TIOCSTART = 0x2000746e
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCVHANGUP = 0x20005437
+ TOSTOP = 0x100
+ TUNATTACHFILTER = 0x801054d5
+ TUNDETACHFILTER = 0x801054d6
+ TUNGETFEATURES = 0x400454cf
+ TUNGETFILTER = 0x401054db
+ 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
+ VDSUSP = 0xb
+ VEOF = 0x4
+ VEOL = 0x5
+ VEOL2 = 0x6
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMADDR_CID_ANY = 0xffffffff
+ VMADDR_CID_HOST = 0x2
+ VMADDR_CID_HYPERVISOR = 0x0
+ VMADDR_CID_RESERVED = 0x1
+ VMADDR_PORT_ANY = 0xffffffff
+ VMIN = 0x4
+ VQUIT = 0x1
+ VREPRINT = 0xc
+ VSTART = 0x8
+ VSTOP = 0x9
+ VSUSP = 0xa
+ VSWTC = 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 = 0x40
+ WRAP = 0x20000
+ WSTOPPED = 0x2
+ WUNTRACED = 0x2
+ XCASE = 0x4
+ XTABS = 0x1800
+ __TIOCFLUSH = 0x80047410
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EADV = syscall.Errno(0x53)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0xb)
+ EALREADY = syscall.Errno(0x25)
+ EBADE = syscall.Errno(0x66)
+ EBADF = syscall.Errno(0x9)
+ EBADFD = syscall.Errno(0x5d)
+ EBADMSG = syscall.Errno(0x4c)
+ EBADR = syscall.Errno(0x67)
+ EBADRQC = syscall.Errno(0x6a)
+ EBADSLT = syscall.Errno(0x6b)
+ EBFONT = syscall.Errno(0x6d)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x7f)
+ ECHILD = syscall.Errno(0xa)
+ ECHRNG = syscall.Errno(0x5e)
+ ECOMM = syscall.Errno(0x55)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0x4e)
+ EDEADLOCK = syscall.Errno(0x6c)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDOTDOT = syscall.Errno(0x58)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EHWPOISON = syscall.Errno(0x87)
+ EIDRM = syscall.Errno(0x4d)
+ EILSEQ = syscall.Errno(0x7a)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ EISNAM = syscall.Errno(0x78)
+ EKEYEXPIRED = syscall.Errno(0x81)
+ EKEYREJECTED = syscall.Errno(0x83)
+ EKEYREVOKED = syscall.Errno(0x82)
+ EL2HLT = syscall.Errno(0x65)
+ EL2NSYNC = syscall.Errno(0x5f)
+ EL3HLT = syscall.Errno(0x60)
+ EL3RST = syscall.Errno(0x61)
+ ELIBACC = syscall.Errno(0x72)
+ ELIBBAD = syscall.Errno(0x70)
+ ELIBEXEC = syscall.Errno(0x6e)
+ ELIBMAX = syscall.Errno(0x7b)
+ ELIBSCN = syscall.Errno(0x7c)
+ ELNRNG = syscall.Errno(0x62)
+ ELOOP = syscall.Errno(0x3e)
+ EMEDIUMTYPE = syscall.Errno(0x7e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x57)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENAVAIL = syscall.Errno(0x77)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOANO = syscall.Errno(0x69)
+ ENOBUFS = syscall.Errno(0x37)
+ ENOCSI = syscall.Errno(0x64)
+ ENODATA = syscall.Errno(0x6f)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOKEY = syscall.Errno(0x80)
+ ENOLCK = syscall.Errno(0x4f)
+ ENOLINK = syscall.Errno(0x52)
+ ENOMEDIUM = syscall.Errno(0x7d)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x4b)
+ ENONET = syscall.Errno(0x50)
+ ENOPKG = syscall.Errno(0x71)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x4a)
+ ENOSTR = syscall.Errno(0x48)
+ ENOSYS = syscall.Errno(0x5a)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTNAM = syscall.Errno(0x76)
+ ENOTRECOVERABLE = syscall.Errno(0x85)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x2d)
+ ENOTTY = syscall.Errno(0x19)
+ ENOTUNIQ = syscall.Errno(0x73)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x5c)
+ EOWNERDEAD = syscall.Errno(0x84)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROTO = syscall.Errno(0x56)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMCHG = syscall.Errno(0x59)
+ EREMOTE = syscall.Errno(0x47)
+ EREMOTEIO = syscall.Errno(0x79)
+ ERESTART = syscall.Errno(0x74)
+ ERFKILL = syscall.Errno(0x86)
+ EROFS = syscall.Errno(0x1e)
+ ERREMOTE = syscall.Errno(0x51)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESRMNT = syscall.Errno(0x54)
+ ESTALE = syscall.Errno(0x46)
+ ESTRPIPE = syscall.Errno(0x5b)
+ ETIME = syscall.Errno(0x49)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUCLEAN = syscall.Errno(0x75)
+ EUNATCH = syscall.Errno(0x63)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0xb)
+ EXDEV = syscall.Errno(0x12)
+ EXFULL = syscall.Errno(0x68)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGLOST = syscall.Signal(0x1d)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPOLL = syscall.Signal(0x17)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x1d)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol",
+ 48: "address already in use",
+ 49: "cannot assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "transport endpoint is already connected",
+ 57: "transport endpoint is not connected",
+ 58: "cannot send after transport endpoint shutdown",
+ 59: "too many references: cannot splice",
+ 60: "connection timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disk quota exceeded",
+ 70: "stale file handle",
+ 71: "object is remote",
+ 72: "device not a stream",
+ 73: "timer expired",
+ 74: "out of streams resources",
+ 75: "no message of desired type",
+ 76: "bad message",
+ 77: "identifier removed",
+ 78: "resource deadlock avoided",
+ 79: "no locks available",
+ 80: "machine is not on the network",
+ 81: "unknown error 81",
+ 82: "link has been severed",
+ 83: "advertise error",
+ 84: "srmount error",
+ 85: "communication error on send",
+ 86: "protocol error",
+ 87: "multihop attempted",
+ 88: "RFS specific error",
+ 89: "remote address changed",
+ 90: "function not implemented",
+ 91: "streams pipe error",
+ 92: "value too large for defined data type",
+ 93: "file descriptor in bad state",
+ 94: "channel number out of range",
+ 95: "level 2 not synchronized",
+ 96: "level 3 halted",
+ 97: "level 3 reset",
+ 98: "link number out of range",
+ 99: "protocol driver not attached",
+ 100: "no CSI structure available",
+ 101: "level 2 halted",
+ 102: "invalid exchange",
+ 103: "invalid request descriptor",
+ 104: "exchange full",
+ 105: "no anode",
+ 106: "invalid request code",
+ 107: "invalid slot",
+ 108: "file locking deadlock error",
+ 109: "bad font file format",
+ 110: "cannot exec a shared library directly",
+ 111: "no data available",
+ 112: "accessing a corrupted shared library",
+ 113: "package not installed",
+ 114: "can not access a needed shared library",
+ 115: "name not unique on network",
+ 116: "interrupted system call should be restarted",
+ 117: "structure needs cleaning",
+ 118: "not a XENIX named type file",
+ 119: "no XENIX semaphores available",
+ 120: "is a named type file",
+ 121: "remote I/O error",
+ 122: "invalid or incomplete multibyte or wide character",
+ 123: "attempting to link in too many shared libraries",
+ 124: ".lib section in a.out corrupted",
+ 125: "no medium found",
+ 126: "wrong medium type",
+ 127: "operation canceled",
+ 128: "required key not available",
+ 129: "key has expired",
+ 130: "key has been revoked",
+ 131: "key was rejected by service",
+ 132: "owner died",
+ 133: "state not recoverable",
+ 134: "operation not possible due to RF-kill",
+ 135: "memory page has hardware error",
+}
+
+// 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: "urgent I/O condition",
+ 17: "stopped (signal)",
+ 18: "stopped",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "CPU time limit exceeded",
+ 25: "file size limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window changed",
+ 29: "resource lost",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go b/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go
new file mode 100644
index 0000000..b4338d5
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go
@@ -0,0 +1,1712 @@
+// mkerrors.sh -m32
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+// +build 386,netbsd
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m32 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_ARP = 0x1c
+ AF_BLUETOOTH = 0x1f
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1a
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x20
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x18
+ AF_IPX = 0x17
+ AF_ISDN = 0x1a
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x23
+ AF_MPLS = 0x21
+ AF_NATM = 0x1b
+ AF_NS = 0x6
+ AF_OROUTE = 0x11
+ AF_OSI = 0x7
+ AF_PUP = 0x4
+ AF_ROUTE = 0x22
+ AF_SNA = 0xb
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ ARPHRD_ARCNET = 0x7
+ ARPHRD_ETHER = 0x1
+ ARPHRD_FRELAY = 0xf
+ ARPHRD_IEEE1394 = 0x18
+ ARPHRD_IEEE802 = 0x6
+ ARPHRD_STRIP = 0x17
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B460800 = 0x70800
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B921600 = 0xe1000
+ B9600 = 0x2580
+ BIOCFEEDBACK = 0x8004427d
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc0084277
+ BIOCGETIF = 0x4090426b
+ BIOCGFEEDBACK = 0x4004427c
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRTIMEOUT = 0x400c427b
+ BIOCGSEESENT = 0x40044278
+ BIOCGSTATS = 0x4080426f
+ BIOCGSTATSOLD = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDLT = 0x80044276
+ BIOCSETF = 0x80084267
+ BIOCSETIF = 0x8090426c
+ BIOCSFEEDBACK = 0x8004427d
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRTIMEOUT = 0x800c427a
+ BIOCSSEESENT = 0x80044279
+ BIOCSTCPF = 0x80084272
+ BIOCSUDPF = 0x80084273
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ BPF_ALIGNMENT32 = 0x4
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_DFLTBUFSIZE = 0x100000
+ 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_MAXBUFSIZE = 0x1000000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CLONE_CSIGNAL = 0xff
+ CLONE_FILES = 0x400
+ CLONE_FS = 0x200
+ CLONE_PID = 0x1000
+ CLONE_PTRACE = 0x2000
+ CLONE_SIGHAND = 0x800
+ CLONE_VFORK = 0x4000
+ CLONE_VM = 0x100
+ CREAD = 0x800
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ CTL_QUERY = -0x2
+ DIOCBSFLUSH = 0x20006478
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_AOS = 0xde
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_CAN20B = 0xbe
+ DLT_CAN_SOCKETCAN = 0xe3
+ DLT_CHAOS = 0x5
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DECT = 0xdd
+ DLT_DOCSIS = 0x8f
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FC_2 = 0xe0
+ DLT_FC_2_WITH_FRAME_DELIMS = 0xe1
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_GSMTAP_ABIS = 0xda
+ DLT_GSMTAP_UM = 0xd9
+ DLT_HDLC = 0x10
+ DLT_HHDLC = 0x79
+ DLT_HIPPI = 0xf
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IPNET = 0xe2
+ DLT_IPV4 = 0xe4
+ DLT_IPV6 = 0xe5
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_EVDEV = 0xd8
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MPLS = 0xdb
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0xe
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PRISM_HEADER = 0x77
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_RAWAF_MASK = 0x2240000
+ DLT_RIO = 0x7c
+ DLT_SCCP = 0x8e
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xd
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USB_LINUX = 0xbd
+ DLT_USB_LINUX_MMAPPED = 0xdc
+ DLT_WIHART = 0xdf
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EMUL_LINUX = 0x1
+ EMUL_LINUX32 = 0x5
+ EMUL_MAXID = 0x6
+ EN_SW_CTL_INF = 0x1000
+ EN_SW_CTL_PREC = 0x300
+ EN_SW_CTL_ROUND = 0xc00
+ EN_SW_DATACHAIN = 0x80
+ EN_SW_DENORM = 0x2
+ EN_SW_INVOP = 0x1
+ EN_SW_OVERFLOW = 0x8
+ EN_SW_PRECLOSS = 0x20
+ EN_SW_UNDERFLOW = 0x10
+ EN_SW_ZERODIV = 0x4
+ ETHERCAP_JUMBO_MTU = 0x4
+ ETHERCAP_VLAN_HWTAGGING = 0x2
+ ETHERCAP_VLAN_MTU = 0x1
+ ETHERMIN = 0x2e
+ ETHERMTU = 0x5dc
+ ETHERMTU_JUMBO = 0x2328
+ ETHERTYPE_8023 = 0x4
+ ETHERTYPE_AARP = 0x80f3
+ ETHERTYPE_ACCTON = 0x8390
+ ETHERTYPE_AEONIC = 0x8036
+ ETHERTYPE_ALPHA = 0x814a
+ ETHERTYPE_AMBER = 0x6008
+ ETHERTYPE_AMOEBA = 0x8145
+ ETHERTYPE_APOLLO = 0x80f7
+ ETHERTYPE_APOLLODOMAIN = 0x8019
+ ETHERTYPE_APPLETALK = 0x809b
+ ETHERTYPE_APPLITEK = 0x80c7
+ ETHERTYPE_ARGONAUT = 0x803a
+ ETHERTYPE_ARP = 0x806
+ ETHERTYPE_AT = 0x809b
+ ETHERTYPE_ATALK = 0x809b
+ ETHERTYPE_ATOMIC = 0x86df
+ ETHERTYPE_ATT = 0x8069
+ ETHERTYPE_ATTSTANFORD = 0x8008
+ ETHERTYPE_AUTOPHON = 0x806a
+ ETHERTYPE_AXIS = 0x8856
+ ETHERTYPE_BCLOOP = 0x9003
+ ETHERTYPE_BOFL = 0x8102
+ ETHERTYPE_CABLETRON = 0x7034
+ ETHERTYPE_CHAOS = 0x804
+ ETHERTYPE_COMDESIGN = 0x806c
+ ETHERTYPE_COMPUGRAPHIC = 0x806d
+ ETHERTYPE_COUNTERPOINT = 0x8062
+ ETHERTYPE_CRONUS = 0x8004
+ ETHERTYPE_CRONUSVLN = 0x8003
+ ETHERTYPE_DCA = 0x1234
+ ETHERTYPE_DDE = 0x807b
+ ETHERTYPE_DEBNI = 0xaaaa
+ ETHERTYPE_DECAM = 0x8048
+ ETHERTYPE_DECCUST = 0x6006
+ ETHERTYPE_DECDIAG = 0x6005
+ ETHERTYPE_DECDNS = 0x803c
+ ETHERTYPE_DECDTS = 0x803e
+ ETHERTYPE_DECEXPER = 0x6000
+ ETHERTYPE_DECLAST = 0x8041
+ ETHERTYPE_DECLTM = 0x803f
+ ETHERTYPE_DECMUMPS = 0x6009
+ ETHERTYPE_DECNETBIOS = 0x8040
+ ETHERTYPE_DELTACON = 0x86de
+ ETHERTYPE_DIDDLE = 0x4321
+ ETHERTYPE_DLOG1 = 0x660
+ ETHERTYPE_DLOG2 = 0x661
+ ETHERTYPE_DN = 0x6003
+ ETHERTYPE_DOGFIGHT = 0x1989
+ ETHERTYPE_DSMD = 0x8039
+ ETHERTYPE_ECMA = 0x803
+ ETHERTYPE_ENCRYPT = 0x803d
+ ETHERTYPE_ES = 0x805d
+ ETHERTYPE_EXCELAN = 0x8010
+ ETHERTYPE_EXPERDATA = 0x8049
+ ETHERTYPE_FLIP = 0x8146
+ ETHERTYPE_FLOWCONTROL = 0x8808
+ ETHERTYPE_FRARP = 0x808
+ ETHERTYPE_GENDYN = 0x8068
+ ETHERTYPE_HAYES = 0x8130
+ ETHERTYPE_HIPPI_FP = 0x8180
+ ETHERTYPE_HITACHI = 0x8820
+ ETHERTYPE_HP = 0x8005
+ ETHERTYPE_IEEEPUP = 0xa00
+ ETHERTYPE_IEEEPUPAT = 0xa01
+ ETHERTYPE_IMLBL = 0x4c42
+ ETHERTYPE_IMLBLDIAG = 0x424c
+ ETHERTYPE_IP = 0x800
+ ETHERTYPE_IPAS = 0x876c
+ ETHERTYPE_IPV6 = 0x86dd
+ ETHERTYPE_IPX = 0x8137
+ ETHERTYPE_IPXNEW = 0x8037
+ ETHERTYPE_KALPANA = 0x8582
+ ETHERTYPE_LANBRIDGE = 0x8038
+ ETHERTYPE_LANPROBE = 0x8888
+ ETHERTYPE_LAT = 0x6004
+ ETHERTYPE_LBACK = 0x9000
+ ETHERTYPE_LITTLE = 0x8060
+ ETHERTYPE_LOGICRAFT = 0x8148
+ ETHERTYPE_LOOPBACK = 0x9000
+ ETHERTYPE_MATRA = 0x807a
+ ETHERTYPE_MAX = 0xffff
+ ETHERTYPE_MERIT = 0x807c
+ ETHERTYPE_MICP = 0x873a
+ ETHERTYPE_MOPDL = 0x6001
+ ETHERTYPE_MOPRC = 0x6002
+ ETHERTYPE_MOTOROLA = 0x818d
+ ETHERTYPE_MPLS = 0x8847
+ ETHERTYPE_MPLS_MCAST = 0x8848
+ ETHERTYPE_MUMPS = 0x813f
+ ETHERTYPE_NBPCC = 0x3c04
+ ETHERTYPE_NBPCLAIM = 0x3c09
+ ETHERTYPE_NBPCLREQ = 0x3c05
+ ETHERTYPE_NBPCLRSP = 0x3c06
+ ETHERTYPE_NBPCREQ = 0x3c02
+ ETHERTYPE_NBPCRSP = 0x3c03
+ ETHERTYPE_NBPDG = 0x3c07
+ ETHERTYPE_NBPDGB = 0x3c08
+ ETHERTYPE_NBPDLTE = 0x3c0a
+ ETHERTYPE_NBPRAR = 0x3c0c
+ ETHERTYPE_NBPRAS = 0x3c0b
+ ETHERTYPE_NBPRST = 0x3c0d
+ ETHERTYPE_NBPSCD = 0x3c01
+ ETHERTYPE_NBPVCD = 0x3c00
+ ETHERTYPE_NBS = 0x802
+ ETHERTYPE_NCD = 0x8149
+ ETHERTYPE_NESTAR = 0x8006
+ ETHERTYPE_NETBEUI = 0x8191
+ ETHERTYPE_NOVELL = 0x8138
+ ETHERTYPE_NS = 0x600
+ ETHERTYPE_NSAT = 0x601
+ ETHERTYPE_NSCOMPAT = 0x807
+ ETHERTYPE_NTRAILER = 0x10
+ ETHERTYPE_OS9 = 0x7007
+ ETHERTYPE_OS9NET = 0x7009
+ ETHERTYPE_PACER = 0x80c6
+ ETHERTYPE_PAE = 0x888e
+ ETHERTYPE_PCS = 0x4242
+ ETHERTYPE_PLANNING = 0x8044
+ ETHERTYPE_PPP = 0x880b
+ ETHERTYPE_PPPOE = 0x8864
+ ETHERTYPE_PPPOEDISC = 0x8863
+ ETHERTYPE_PRIMENTS = 0x7031
+ ETHERTYPE_PUP = 0x200
+ ETHERTYPE_PUPAT = 0x200
+ ETHERTYPE_RACAL = 0x7030
+ ETHERTYPE_RATIONAL = 0x8150
+ ETHERTYPE_RAWFR = 0x6559
+ ETHERTYPE_RCL = 0x1995
+ ETHERTYPE_RDP = 0x8739
+ ETHERTYPE_RETIX = 0x80f2
+ ETHERTYPE_REVARP = 0x8035
+ ETHERTYPE_SCA = 0x6007
+ ETHERTYPE_SECTRA = 0x86db
+ ETHERTYPE_SECUREDATA = 0x876d
+ ETHERTYPE_SGITW = 0x817e
+ ETHERTYPE_SG_BOUNCE = 0x8016
+ ETHERTYPE_SG_DIAG = 0x8013
+ ETHERTYPE_SG_NETGAMES = 0x8014
+ ETHERTYPE_SG_RESV = 0x8015
+ ETHERTYPE_SIMNET = 0x5208
+ ETHERTYPE_SLOWPROTOCOLS = 0x8809
+ ETHERTYPE_SNA = 0x80d5
+ ETHERTYPE_SNMP = 0x814c
+ ETHERTYPE_SONIX = 0xfaf5
+ ETHERTYPE_SPIDER = 0x809f
+ ETHERTYPE_SPRITE = 0x500
+ ETHERTYPE_STP = 0x8181
+ ETHERTYPE_TALARIS = 0x812b
+ ETHERTYPE_TALARISMC = 0x852b
+ ETHERTYPE_TCPCOMP = 0x876b
+ ETHERTYPE_TCPSM = 0x9002
+ ETHERTYPE_TEC = 0x814f
+ ETHERTYPE_TIGAN = 0x802f
+ ETHERTYPE_TRAIL = 0x1000
+ ETHERTYPE_TRANSETHER = 0x6558
+ ETHERTYPE_TYMSHARE = 0x802e
+ ETHERTYPE_UBBST = 0x7005
+ ETHERTYPE_UBDEBUG = 0x900
+ ETHERTYPE_UBDIAGLOOP = 0x7002
+ ETHERTYPE_UBDL = 0x7000
+ ETHERTYPE_UBNIU = 0x7001
+ ETHERTYPE_UBNMC = 0x7003
+ ETHERTYPE_VALID = 0x1600
+ ETHERTYPE_VARIAN = 0x80dd
+ ETHERTYPE_VAXELN = 0x803b
+ ETHERTYPE_VEECO = 0x8067
+ ETHERTYPE_VEXP = 0x805b
+ ETHERTYPE_VGLAB = 0x8131
+ ETHERTYPE_VINES = 0xbad
+ ETHERTYPE_VINESECHO = 0xbaf
+ ETHERTYPE_VINESLOOP = 0xbae
+ ETHERTYPE_VITAL = 0xff00
+ ETHERTYPE_VLAN = 0x8100
+ ETHERTYPE_VLTLMAN = 0x8080
+ ETHERTYPE_VPROD = 0x805c
+ ETHERTYPE_VURESERVED = 0x8147
+ ETHERTYPE_WATERLOO = 0x8130
+ ETHERTYPE_WELLFLEET = 0x8103
+ ETHERTYPE_X25 = 0x805
+ ETHERTYPE_X75 = 0x801
+ ETHERTYPE_XNSSM = 0x9001
+ ETHERTYPE_XTP = 0x817d
+ ETHER_ADDR_LEN = 0x6
+ ETHER_CRC_LEN = 0x4
+ ETHER_CRC_POLY_BE = 0x4c11db6
+ ETHER_CRC_POLY_LE = 0xedb88320
+ ETHER_HDR_LEN = 0xe
+ ETHER_MAX_LEN = 0x5ee
+ ETHER_MAX_LEN_JUMBO = 0x233a
+ ETHER_MIN_LEN = 0x40
+ ETHER_PPPOE_ENCAP_LEN = 0x8
+ ETHER_TYPE_LEN = 0x2
+ ETHER_VLAN_ENCAP_LEN = 0x4
+ EVFILT_AIO = 0x2
+ EVFILT_PROC = 0x4
+ EVFILT_READ = 0x0
+ EVFILT_SIGNAL = 0x5
+ EVFILT_SYSCOUNT = 0x7
+ EVFILT_TIMER = 0x6
+ EVFILT_VNODE = 0x3
+ EVFILT_WRITE = 0x1
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG1 = 0x2000
+ EV_ONESHOT = 0x10
+ EV_SYSFLAGS = 0xf000
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x100
+ FLUSHO = 0x800000
+ F_CLOSEM = 0xa
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0xc
+ F_FSCTL = -0x80000000
+ F_FSDIRMASK = 0x70000000
+ F_FSIN = 0x10000000
+ F_FSINOUT = 0x30000000
+ F_FSOUT = 0x20000000
+ F_FSPRIV = 0x8000
+ F_FSVOID = 0x40000000
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETNOSIGPIPE = 0xd
+ F_GETOWN = 0x5
+ F_MAXFD = 0xb
+ F_OK = 0x0
+ F_PARAM_MASK = 0xfff
+ F_PARAM_MAX = 0xfff
+ F_RDLCK = 0x1
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETNOSIGPIPE = 0xe
+ F_SETOWN = 0x6
+ F_UNLCK = 0x2
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFAN_ARRIVAL = 0x0
+ IFAN_DEPARTURE = 0x1
+ IFA_ROUTE = 0x1
+ IFF_ALLMULTI = 0x200
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x8f52
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NOTRAILERS = 0x20
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_A12MPPSWITCH = 0x82
+ IFT_AAL2 = 0xbb
+ IFT_AAL5 = 0x31
+ IFT_ADSL = 0x5e
+ IFT_AFLANE8023 = 0x3b
+ IFT_AFLANE8025 = 0x3c
+ IFT_ARAP = 0x58
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ASYNC = 0x54
+ IFT_ATM = 0x25
+ IFT_ATMDXI = 0x69
+ IFT_ATMFUNI = 0x6a
+ IFT_ATMIMA = 0x6b
+ IFT_ATMLOGICAL = 0x50
+ IFT_ATMRADIO = 0xbd
+ IFT_ATMSUBINTERFACE = 0x86
+ IFT_ATMVCIENDPT = 0xc2
+ IFT_ATMVIRTUAL = 0x95
+ IFT_BGPPOLICYACCOUNTING = 0xa2
+ IFT_BRIDGE = 0xd1
+ IFT_BSC = 0x53
+ IFT_CARP = 0xf8
+ IFT_CCTEMUL = 0x3d
+ IFT_CEPT = 0x13
+ IFT_CES = 0x85
+ IFT_CHANNEL = 0x46
+ IFT_CNR = 0x55
+ IFT_COFFEE = 0x84
+ IFT_COMPOSITELINK = 0x9b
+ IFT_DCN = 0x8d
+ IFT_DIGITALPOWERLINE = 0x8a
+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
+ IFT_DLSW = 0x4a
+ IFT_DOCSCABLEDOWNSTREAM = 0x80
+ IFT_DOCSCABLEMACLAYER = 0x7f
+ IFT_DOCSCABLEUPSTREAM = 0x81
+ IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd
+ IFT_DS0 = 0x51
+ IFT_DS0BUNDLE = 0x52
+ IFT_DS1FDL = 0xaa
+ IFT_DS3 = 0x1e
+ IFT_DTM = 0x8c
+ IFT_DVBASILN = 0xac
+ IFT_DVBASIOUT = 0xad
+ IFT_DVBRCCDOWNSTREAM = 0x93
+ IFT_DVBRCCMACLAYER = 0x92
+ IFT_DVBRCCUPSTREAM = 0x94
+ IFT_ECONET = 0xce
+ IFT_EON = 0x19
+ IFT_EPLRS = 0x57
+ IFT_ESCON = 0x49
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0xf2
+ IFT_FAST = 0x7d
+ IFT_FASTETHER = 0x3e
+ IFT_FASTETHERFX = 0x45
+ IFT_FDDI = 0xf
+ IFT_FIBRECHANNEL = 0x38
+ IFT_FRAMERELAYINTERCONNECT = 0x3a
+ IFT_FRAMERELAYMPI = 0x5c
+ IFT_FRDLCIENDPT = 0xc1
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_FRF16MFRBUNDLE = 0xa3
+ IFT_FRFORWARD = 0x9e
+ IFT_G703AT2MB = 0x43
+ IFT_G703AT64K = 0x42
+ IFT_GIF = 0xf0
+ IFT_GIGABITETHERNET = 0x75
+ IFT_GR303IDT = 0xb2
+ IFT_GR303RDT = 0xb1
+ IFT_H323GATEKEEPER = 0xa4
+ IFT_H323PROXY = 0xa5
+ IFT_HDH1822 = 0x3
+ IFT_HDLC = 0x76
+ IFT_HDSL2 = 0xa8
+ IFT_HIPERLAN2 = 0xb7
+ IFT_HIPPI = 0x2f
+ IFT_HIPPIINTERFACE = 0x39
+ IFT_HOSTPAD = 0x5a
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IBM370PARCHAN = 0x48
+ IFT_IDSL = 0x9a
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE80211 = 0x47
+ IFT_IEEE80212 = 0x37
+ IFT_IEEE8023ADLAG = 0xa1
+ IFT_IFGSN = 0x91
+ IFT_IMT = 0xbe
+ IFT_INFINIBAND = 0xc7
+ IFT_INTERLEAVE = 0x7c
+ IFT_IP = 0x7e
+ IFT_IPFORWARD = 0x8e
+ IFT_IPOVERATM = 0x72
+ IFT_IPOVERCDLC = 0x6d
+ IFT_IPOVERCLAW = 0x6e
+ IFT_IPSWITCH = 0x4e
+ IFT_ISDN = 0x3f
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISDNS = 0x4b
+ IFT_ISDNU = 0x4c
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88025CRFPINT = 0x62
+ IFT_ISO88025DTR = 0x56
+ IFT_ISO88025FIBER = 0x73
+ IFT_ISO88026 = 0xa
+ IFT_ISUP = 0xb3
+ IFT_L2VLAN = 0x87
+ IFT_L3IPVLAN = 0x88
+ IFT_L3IPXVLAN = 0x89
+ IFT_LAPB = 0x10
+ IFT_LAPD = 0x4d
+ IFT_LAPF = 0x77
+ IFT_LINEGROUP = 0xd2
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MEDIAMAILOVERIP = 0x8b
+ IFT_MFSIGLINK = 0xa7
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_MPC = 0x71
+ IFT_MPLS = 0xa6
+ IFT_MPLSTUNNEL = 0x96
+ IFT_MSDSL = 0x8f
+ IFT_MVL = 0xbf
+ IFT_MYRINET = 0x63
+ IFT_NFAS = 0xaf
+ IFT_NSIP = 0x1b
+ IFT_OPTICALCHANNEL = 0xc3
+ IFT_OPTICALTRANSPORT = 0xc4
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PFLOG = 0xf5
+ IFT_PFSYNC = 0xf6
+ IFT_PLC = 0xae
+ IFT_PON155 = 0xcf
+ IFT_PON622 = 0xd0
+ IFT_POS = 0xab
+ IFT_PPP = 0x17
+ IFT_PPPMULTILINKBUNDLE = 0x6c
+ IFT_PROPATM = 0xc5
+ IFT_PROPBWAP2MP = 0xb8
+ IFT_PROPCNLS = 0x59
+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PROPWIRELESSP2P = 0x9d
+ IFT_PTPSERIAL = 0x16
+ IFT_PVC = 0xf1
+ IFT_Q2931 = 0xc9
+ IFT_QLLC = 0x44
+ IFT_RADIOMAC = 0xbc
+ IFT_RADSL = 0x5f
+ IFT_REACHDSL = 0xc0
+ IFT_RFC1483 = 0x9f
+ IFT_RS232 = 0x21
+ IFT_RSRB = 0x4f
+ IFT_SDLC = 0x11
+ IFT_SDSL = 0x60
+ IFT_SHDSL = 0xa9
+ IFT_SIP = 0x1f
+ IFT_SIPSIG = 0xcc
+ IFT_SIPTG = 0xcb
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETOVERHEADCHANNEL = 0xb9
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_SRP = 0x97
+ IFT_SS7SIGLINK = 0x9c
+ IFT_STACKTOSTACK = 0x6f
+ IFT_STARLAN = 0xb
+ IFT_STF = 0xd7
+ IFT_T1 = 0x12
+ IFT_TDLC = 0x74
+ IFT_TELINK = 0xc8
+ IFT_TERMPAD = 0x5b
+ IFT_TR008 = 0xb0
+ IFT_TRANSPHDLC = 0x7b
+ IFT_TUNNEL = 0x83
+ IFT_ULTRA = 0x1d
+ IFT_USB = 0xa0
+ IFT_V11 = 0x40
+ IFT_V35 = 0x2d
+ IFT_V36 = 0x41
+ IFT_V37 = 0x78
+ IFT_VDSL = 0x61
+ IFT_VIRTUALIPADDRESS = 0x70
+ IFT_VIRTUALTG = 0xca
+ IFT_VOICEDID = 0xd5
+ IFT_VOICEEM = 0x64
+ IFT_VOICEEMFGD = 0xd3
+ IFT_VOICEENCAP = 0x67
+ IFT_VOICEFGDEANA = 0xd4
+ IFT_VOICEFXO = 0x65
+ IFT_VOICEFXS = 0x66
+ IFT_VOICEOVERATM = 0x98
+ IFT_VOICEOVERCABLE = 0xc6
+ IFT_VOICEOVERFRAMERELAY = 0x99
+ IFT_VOICEOVERIP = 0x68
+ IFT_X213 = 0x5d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25HUNTGROUP = 0x7a
+ IFT_X25MLP = 0x79
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LOOPBACKNET = 0x7f
+ IPPROTO_AH = 0x33
+ IPPROTO_CARP = 0x70
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IPV6_ICMP = 0x3a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x34
+ IPPROTO_MOBILE = 0x37
+ IPPROTO_NONE = 0x3b
+ IPPROTO_PFSYNC = 0xf0
+ IPPROTO_PIM = 0x67
+ IPPROTO_PUP = 0xc
+ IPPROTO_RAW = 0xff
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_TCP = 0x6
+ IPPROTO_TP = 0x1d
+ IPPROTO_UDP = 0x11
+ IPPROTO_VRRP = 0x70
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_DONTFRAG = 0x3e
+ IPV6_DSTOPTS = 0x32
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x78
+ IPV6_HLIMDEC = 0x1
+ IPV6_HOPLIMIT = 0x2f
+ IPV6_HOPOPTS = 0x31
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MMTU = 0x500
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_NEXTHOP = 0x30
+ IPV6_PATHMTU = 0x2c
+ IPV6_PKTINFO = 0x2e
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVHOPLIMIT = 0x25
+ IPV6_RECVHOPOPTS = 0x27
+ IPV6_RECVPATHMTU = 0x2b
+ IPV6_RECVPKTINFO = 0x24
+ IPV6_RECVRTHDR = 0x26
+ IPV6_RECVTCLASS = 0x39
+ IPV6_RTHDR = 0x33
+ IPV6_RTHDRDSTOPTS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x3d
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_USE_MIN_MTU = 0x2a
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_EF = 0x8000
+ IP_ERRORMTU = 0x15
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x16
+ IP_MAXPACKET = 0xffff
+ IP_MAX_MEMBERSHIPS = 0x14
+ IP_MF = 0x2000
+ IP_MINFRAGSIZE = 0x45
+ IP_MINTTL = 0x18
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_OFFMASK = 0x1fff
+ IP_OPTIONS = 0x1
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVRETOPTS = 0x6
+ IP_RECVTTL = 0x17
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x6
+ MADV_NORMAL = 0x0
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_SPACEAVAIL = 0x5
+ MADV_WILLNEED = 0x3
+ MAP_ALIGNMENT_16MB = 0x18000000
+ MAP_ALIGNMENT_1TB = 0x28000000
+ MAP_ALIGNMENT_256TB = 0x30000000
+ MAP_ALIGNMENT_4GB = 0x20000000
+ MAP_ALIGNMENT_64KB = 0x10000000
+ MAP_ALIGNMENT_64PB = 0x38000000
+ MAP_ALIGNMENT_MASK = -0x1000000
+ MAP_ALIGNMENT_SHIFT = 0x18
+ MAP_ANON = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_HASSEMAPHORE = 0x200
+ MAP_INHERIT = 0x80
+ MAP_INHERIT_COPY = 0x1
+ MAP_INHERIT_DEFAULT = 0x1
+ MAP_INHERIT_DONATE_COPY = 0x3
+ MAP_INHERIT_NONE = 0x2
+ MAP_INHERIT_SHARE = 0x0
+ MAP_NORESERVE = 0x40
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x2000
+ MAP_TRYFIXED = 0x400
+ MAP_WIRED = 0x800
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MSG_BCAST = 0x100
+ MSG_CMSG_CLOEXEC = 0x800
+ MSG_CONTROLMBUF = 0x2000000
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOR = 0x8
+ MSG_IOVUSRSPACE = 0x4000000
+ MSG_LENUSRSPACE = 0x8000000
+ MSG_MCAST = 0x200
+ MSG_NAMEMBUF = 0x1000000
+ MSG_NBIO = 0x1000
+ MSG_NOSIGNAL = 0x400
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x10
+ MSG_USERFLAGS = 0xffffff
+ MSG_WAITALL = 0x40
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x2
+ MS_SYNC = 0x4
+ NAME_MAX = 0x1ff
+ NET_RT_DUMP = 0x1
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x5
+ NET_RT_MAXID = 0x6
+ NET_RT_OIFLIST = 0x4
+ NET_RT_OOIFLIST = 0x3
+ NOFLSH = 0x80000000
+ NOTE_ATTRIB = 0x8
+ NOTE_CHILD = 0x4
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXTEND = 0x4
+ NOTE_FORK = 0x40000000
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_PCTRLMASK = 0xf0000000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ OFIOGETBMAP = 0xc004667a
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ O_ACCMODE = 0x3
+ O_ALT_IO = 0x40000
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x400000
+ O_CREAT = 0x200
+ O_DIRECT = 0x80000
+ O_DIRECTORY = 0x200000
+ O_DSYNC = 0x10000
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_NOSIGPIPE = 0x1000000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x20000
+ O_SHLOCK = 0x10
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PRI_IOFLUSH = 0x7c
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ RLIMIT_AS = 0xa
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x9
+ RTAX_NETMASK = 0x2
+ RTAX_TAG = 0x8
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTA_TAG = 0x100
+ RTF_ANNOUNCE = 0x20000
+ RTF_BLACKHOLE = 0x1000
+ RTF_CLONED = 0x2000
+ RTF_CLONING = 0x100
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_LLINFO = 0x400
+ RTF_MASK = 0x80
+ RTF_MODIFIED = 0x20
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_REJECT = 0x8
+ RTF_SRC = 0x10000
+ RTF_STATIC = 0x800
+ RTF_UP = 0x1
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_CHGADDR = 0x15
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_GET = 0x4
+ RTM_IEEE80211 = 0x11
+ RTM_IFANNOUNCE = 0x10
+ RTM_IFINFO = 0x14
+ RTM_LLINFO_UPD = 0x13
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_OIFINFO = 0xf
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ RTM_OOIFINFO = 0xe
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_SETGATE = 0x12
+ RTM_VERSION = 0x4
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ SCM_CREDS = 0x4
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x8
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80906931
+ SIOCADDRT = 0x8030720a
+ SIOCAIFADDR = 0x8040691a
+ SIOCALIFADDR = 0x8118691c
+ SIOCATMARK = 0x40047307
+ SIOCDELMULTI = 0x80906932
+ SIOCDELRT = 0x8030720b
+ SIOCDIFADDR = 0x80906919
+ SIOCDIFPHYADDR = 0x80906949
+ SIOCDLIFADDR = 0x8118691e
+ SIOCGDRVSPEC = 0xc01c697b
+ SIOCGETPFSYNC = 0xc09069f8
+ SIOCGETSGCNT = 0xc0147534
+ SIOCGETVIFCNT = 0xc0147533
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0906921
+ SIOCGIFADDRPREF = 0xc0946920
+ SIOCGIFALIAS = 0xc040691b
+ SIOCGIFBRDADDR = 0xc0906923
+ SIOCGIFCAP = 0xc0206976
+ SIOCGIFCONF = 0xc0086926
+ SIOCGIFDATA = 0xc0946985
+ SIOCGIFDLT = 0xc0906977
+ SIOCGIFDSTADDR = 0xc0906922
+ SIOCGIFFLAGS = 0xc0906911
+ SIOCGIFGENERIC = 0xc090693a
+ SIOCGIFMEDIA = 0xc0286936
+ SIOCGIFMETRIC = 0xc0906917
+ SIOCGIFMTU = 0xc090697e
+ SIOCGIFNETMASK = 0xc0906925
+ SIOCGIFPDSTADDR = 0xc0906948
+ SIOCGIFPSRCADDR = 0xc0906947
+ SIOCGLIFADDR = 0xc118691d
+ SIOCGLIFPHYADDR = 0xc118694b
+ SIOCGLINKSTR = 0xc01c6987
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCGVH = 0xc0906983
+ SIOCIFCREATE = 0x8090697a
+ SIOCIFDESTROY = 0x80906979
+ SIOCIFGCLONERS = 0xc00c6978
+ SIOCINITIFADDR = 0xc0446984
+ SIOCSDRVSPEC = 0x801c697b
+ SIOCSETPFSYNC = 0x809069f7
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8090690c
+ SIOCSIFADDRPREF = 0x8094691f
+ SIOCSIFBRDADDR = 0x80906913
+ SIOCSIFCAP = 0x80206975
+ SIOCSIFDSTADDR = 0x8090690e
+ SIOCSIFFLAGS = 0x80906910
+ SIOCSIFGENERIC = 0x80906939
+ SIOCSIFMEDIA = 0xc0906935
+ SIOCSIFMETRIC = 0x80906918
+ SIOCSIFMTU = 0x8090697f
+ SIOCSIFNETMASK = 0x80906916
+ SIOCSIFPHYADDR = 0x80406946
+ SIOCSLIFPHYADDR = 0x8118694a
+ SIOCSLINKSTR = 0x801c6988
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SIOCSVH = 0xc0906982
+ SIOCZIFDATA = 0xc0946986
+ SOCK_CLOEXEC = 0x10000000
+ SOCK_DGRAM = 0x2
+ SOCK_FLAGS_MASK = 0xf0000000
+ SOCK_NONBLOCK = 0x20000000
+ SOCK_NOSIGPIPE = 0x40000000
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_ACCEPTFILTER = 0x1000
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LINGER = 0x80
+ SO_NOHEADER = 0x100a
+ SO_NOSIGPIPE = 0x800
+ SO_OOBINLINE = 0x100
+ SO_OVERFLOWED = 0x1009
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x100c
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x100b
+ SO_TIMESTAMP = 0x2000
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ SYSCTL_VERSION = 0x1000000
+ SYSCTL_VERS_0 = 0x0
+ SYSCTL_VERS_1 = 0x1000000
+ SYSCTL_VERS_MASK = 0xff000000
+ S_ARCH1 = 0x10000
+ S_ARCH2 = 0x20000
+ 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_IFWHT = 0xe000
+ 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_ISTXT = 0x200
+ 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
+ S_LOGIN_SET = 0x1
+ TCIFLUSH = 0x1
+ TCIOFLUSH = 0x3
+ TCOFLUSH = 0x2
+ TCP_CONGCTL = 0x20
+ TCP_KEEPCNT = 0x6
+ TCP_KEEPIDLE = 0x3
+ TCP_KEEPINIT = 0x7
+ TCP_KEEPINTVL = 0x5
+ TCP_MAXBURST = 0x4
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MD5SIG = 0x10
+ TCP_MINMSS = 0xd8
+ TCP_MSS = 0x218
+ TCP_NODELAY = 0x1
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDCDTIMESTAMP = 0x400c7458
+ TIOCDRAIN = 0x2000745e
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLAG_CDTRCTS = 0x10
+ TIOCFLAG_CLOCAL = 0x2
+ TIOCFLAG_CRTSCTS = 0x4
+ TIOCFLAG_MDMBUF = 0x8
+ TIOCFLAG_SOFTCAR = 0x1
+ TIOCFLUSH = 0x80047410
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGFLAGS = 0x4004745d
+ TIOCGLINED = 0x40207442
+ TIOCGPGRP = 0x40047477
+ TIOCGQSIZE = 0x40047481
+ TIOCGRANTPT = 0x20007447
+ TIOCGSID = 0x40047463
+ TIOCGSIZE = 0x40087468
+ TIOCGWINSZ = 0x40087468
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGET = 0x4004746a
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCPTMGET = 0x40287446
+ TIOCPTSNAME = 0x40287448
+ TIOCRCVFRAME = 0x80047445
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCTTY = 0x20007461
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSFLAGS = 0x8004745c
+ TIOCSIG = 0x2000745f
+ TIOCSLINED = 0x80207443
+ TIOCSPGRP = 0x80047476
+ TIOCSQSIZE = 0x80047480
+ TIOCSSIZE = 0x80087467
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x80047465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCUCNTL = 0x80047466
+ TIOCXMTFRAME = 0x80047444
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VTIME = 0x11
+ VWERASE = 0x4
+ WALL = 0x8
+ WALLSIG = 0x8
+ WALTSIG = 0x4
+ WCLONE = 0x4
+ WCOREFLAG = 0x80
+ WNOHANG = 0x1
+ WNOWAIT = 0x10000
+ WNOZOMBIE = 0x20000
+ WOPTSCHECKED = 0x40000
+ WSTOPPED = 0x7f
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADF = syscall.Errno(0x9)
+ EBADMSG = syscall.Errno(0x58)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x57)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x52)
+ EILSEQ = syscall.Errno(0x55)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x60)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5e)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x5d)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODATA = syscall.Errno(0x59)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x5f)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x53)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x5a)
+ ENOSTR = syscall.Errno(0x5b)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x56)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x54)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x60)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIME = syscall.Errno(0x5c)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x20)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large or too small",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol option not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "connection timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "identifier removed",
+ 83: "no message of desired type",
+ 84: "value too large to be stored in data type",
+ 85: "illegal byte sequence",
+ 86: "not supported",
+ 87: "operation Canceled",
+ 88: "bad or Corrupt message",
+ 89: "no message available",
+ 90: "no STREAM resources",
+ 91: "not a STREAM",
+ 92: "STREAM ioctl timeout",
+ 93: "attribute not found",
+ 94: "multihop attempted",
+ 95: "link has been severed",
+ 96: "protocol error",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "stopped (signal)",
+ 18: "stopped",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+ 32: "power fail/restart",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go
new file mode 100644
index 0000000..4994437
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go
@@ -0,0 +1,1702 @@
+// mkerrors.sh -m64
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+// +build amd64,netbsd
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m64 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_ARP = 0x1c
+ AF_BLUETOOTH = 0x1f
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1a
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x20
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x18
+ AF_IPX = 0x17
+ AF_ISDN = 0x1a
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x23
+ AF_MPLS = 0x21
+ AF_NATM = 0x1b
+ AF_NS = 0x6
+ AF_OROUTE = 0x11
+ AF_OSI = 0x7
+ AF_PUP = 0x4
+ AF_ROUTE = 0x22
+ AF_SNA = 0xb
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ ARPHRD_ARCNET = 0x7
+ ARPHRD_ETHER = 0x1
+ ARPHRD_FRELAY = 0xf
+ ARPHRD_IEEE1394 = 0x18
+ ARPHRD_IEEE802 = 0x6
+ ARPHRD_STRIP = 0x17
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B460800 = 0x70800
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B921600 = 0xe1000
+ B9600 = 0x2580
+ BIOCFEEDBACK = 0x8004427d
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc0104277
+ BIOCGETIF = 0x4090426b
+ BIOCGFEEDBACK = 0x4004427c
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRTIMEOUT = 0x4010427b
+ BIOCGSEESENT = 0x40044278
+ BIOCGSTATS = 0x4080426f
+ BIOCGSTATSOLD = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDLT = 0x80044276
+ BIOCSETF = 0x80104267
+ BIOCSETIF = 0x8090426c
+ BIOCSFEEDBACK = 0x8004427d
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRTIMEOUT = 0x8010427a
+ BIOCSSEESENT = 0x80044279
+ BIOCSTCPF = 0x80104272
+ BIOCSUDPF = 0x80104273
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x8
+ BPF_ALIGNMENT32 = 0x4
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_DFLTBUFSIZE = 0x100000
+ 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_MAXBUFSIZE = 0x1000000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CLONE_CSIGNAL = 0xff
+ CLONE_FILES = 0x400
+ CLONE_FS = 0x200
+ CLONE_PID = 0x1000
+ CLONE_PTRACE = 0x2000
+ CLONE_SIGHAND = 0x800
+ CLONE_VFORK = 0x4000
+ CLONE_VM = 0x100
+ CREAD = 0x800
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ CTL_QUERY = -0x2
+ DIOCBSFLUSH = 0x20006478
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_AOS = 0xde
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_CAN20B = 0xbe
+ DLT_CAN_SOCKETCAN = 0xe3
+ DLT_CHAOS = 0x5
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DECT = 0xdd
+ DLT_DOCSIS = 0x8f
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FC_2 = 0xe0
+ DLT_FC_2_WITH_FRAME_DELIMS = 0xe1
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_GSMTAP_ABIS = 0xda
+ DLT_GSMTAP_UM = 0xd9
+ DLT_HDLC = 0x10
+ DLT_HHDLC = 0x79
+ DLT_HIPPI = 0xf
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IPNET = 0xe2
+ DLT_IPV4 = 0xe4
+ DLT_IPV6 = 0xe5
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_EVDEV = 0xd8
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MPLS = 0xdb
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0xe
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PRISM_HEADER = 0x77
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_RAWAF_MASK = 0x2240000
+ DLT_RIO = 0x7c
+ DLT_SCCP = 0x8e
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xd
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USB_LINUX = 0xbd
+ DLT_USB_LINUX_MMAPPED = 0xdc
+ DLT_WIHART = 0xdf
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EMUL_LINUX = 0x1
+ EMUL_LINUX32 = 0x5
+ EMUL_MAXID = 0x6
+ ETHERCAP_JUMBO_MTU = 0x4
+ ETHERCAP_VLAN_HWTAGGING = 0x2
+ ETHERCAP_VLAN_MTU = 0x1
+ ETHERMIN = 0x2e
+ ETHERMTU = 0x5dc
+ ETHERMTU_JUMBO = 0x2328
+ ETHERTYPE_8023 = 0x4
+ ETHERTYPE_AARP = 0x80f3
+ ETHERTYPE_ACCTON = 0x8390
+ ETHERTYPE_AEONIC = 0x8036
+ ETHERTYPE_ALPHA = 0x814a
+ ETHERTYPE_AMBER = 0x6008
+ ETHERTYPE_AMOEBA = 0x8145
+ ETHERTYPE_APOLLO = 0x80f7
+ ETHERTYPE_APOLLODOMAIN = 0x8019
+ ETHERTYPE_APPLETALK = 0x809b
+ ETHERTYPE_APPLITEK = 0x80c7
+ ETHERTYPE_ARGONAUT = 0x803a
+ ETHERTYPE_ARP = 0x806
+ ETHERTYPE_AT = 0x809b
+ ETHERTYPE_ATALK = 0x809b
+ ETHERTYPE_ATOMIC = 0x86df
+ ETHERTYPE_ATT = 0x8069
+ ETHERTYPE_ATTSTANFORD = 0x8008
+ ETHERTYPE_AUTOPHON = 0x806a
+ ETHERTYPE_AXIS = 0x8856
+ ETHERTYPE_BCLOOP = 0x9003
+ ETHERTYPE_BOFL = 0x8102
+ ETHERTYPE_CABLETRON = 0x7034
+ ETHERTYPE_CHAOS = 0x804
+ ETHERTYPE_COMDESIGN = 0x806c
+ ETHERTYPE_COMPUGRAPHIC = 0x806d
+ ETHERTYPE_COUNTERPOINT = 0x8062
+ ETHERTYPE_CRONUS = 0x8004
+ ETHERTYPE_CRONUSVLN = 0x8003
+ ETHERTYPE_DCA = 0x1234
+ ETHERTYPE_DDE = 0x807b
+ ETHERTYPE_DEBNI = 0xaaaa
+ ETHERTYPE_DECAM = 0x8048
+ ETHERTYPE_DECCUST = 0x6006
+ ETHERTYPE_DECDIAG = 0x6005
+ ETHERTYPE_DECDNS = 0x803c
+ ETHERTYPE_DECDTS = 0x803e
+ ETHERTYPE_DECEXPER = 0x6000
+ ETHERTYPE_DECLAST = 0x8041
+ ETHERTYPE_DECLTM = 0x803f
+ ETHERTYPE_DECMUMPS = 0x6009
+ ETHERTYPE_DECNETBIOS = 0x8040
+ ETHERTYPE_DELTACON = 0x86de
+ ETHERTYPE_DIDDLE = 0x4321
+ ETHERTYPE_DLOG1 = 0x660
+ ETHERTYPE_DLOG2 = 0x661
+ ETHERTYPE_DN = 0x6003
+ ETHERTYPE_DOGFIGHT = 0x1989
+ ETHERTYPE_DSMD = 0x8039
+ ETHERTYPE_ECMA = 0x803
+ ETHERTYPE_ENCRYPT = 0x803d
+ ETHERTYPE_ES = 0x805d
+ ETHERTYPE_EXCELAN = 0x8010
+ ETHERTYPE_EXPERDATA = 0x8049
+ ETHERTYPE_FLIP = 0x8146
+ ETHERTYPE_FLOWCONTROL = 0x8808
+ ETHERTYPE_FRARP = 0x808
+ ETHERTYPE_GENDYN = 0x8068
+ ETHERTYPE_HAYES = 0x8130
+ ETHERTYPE_HIPPI_FP = 0x8180
+ ETHERTYPE_HITACHI = 0x8820
+ ETHERTYPE_HP = 0x8005
+ ETHERTYPE_IEEEPUP = 0xa00
+ ETHERTYPE_IEEEPUPAT = 0xa01
+ ETHERTYPE_IMLBL = 0x4c42
+ ETHERTYPE_IMLBLDIAG = 0x424c
+ ETHERTYPE_IP = 0x800
+ ETHERTYPE_IPAS = 0x876c
+ ETHERTYPE_IPV6 = 0x86dd
+ ETHERTYPE_IPX = 0x8137
+ ETHERTYPE_IPXNEW = 0x8037
+ ETHERTYPE_KALPANA = 0x8582
+ ETHERTYPE_LANBRIDGE = 0x8038
+ ETHERTYPE_LANPROBE = 0x8888
+ ETHERTYPE_LAT = 0x6004
+ ETHERTYPE_LBACK = 0x9000
+ ETHERTYPE_LITTLE = 0x8060
+ ETHERTYPE_LOGICRAFT = 0x8148
+ ETHERTYPE_LOOPBACK = 0x9000
+ ETHERTYPE_MATRA = 0x807a
+ ETHERTYPE_MAX = 0xffff
+ ETHERTYPE_MERIT = 0x807c
+ ETHERTYPE_MICP = 0x873a
+ ETHERTYPE_MOPDL = 0x6001
+ ETHERTYPE_MOPRC = 0x6002
+ ETHERTYPE_MOTOROLA = 0x818d
+ ETHERTYPE_MPLS = 0x8847
+ ETHERTYPE_MPLS_MCAST = 0x8848
+ ETHERTYPE_MUMPS = 0x813f
+ ETHERTYPE_NBPCC = 0x3c04
+ ETHERTYPE_NBPCLAIM = 0x3c09
+ ETHERTYPE_NBPCLREQ = 0x3c05
+ ETHERTYPE_NBPCLRSP = 0x3c06
+ ETHERTYPE_NBPCREQ = 0x3c02
+ ETHERTYPE_NBPCRSP = 0x3c03
+ ETHERTYPE_NBPDG = 0x3c07
+ ETHERTYPE_NBPDGB = 0x3c08
+ ETHERTYPE_NBPDLTE = 0x3c0a
+ ETHERTYPE_NBPRAR = 0x3c0c
+ ETHERTYPE_NBPRAS = 0x3c0b
+ ETHERTYPE_NBPRST = 0x3c0d
+ ETHERTYPE_NBPSCD = 0x3c01
+ ETHERTYPE_NBPVCD = 0x3c00
+ ETHERTYPE_NBS = 0x802
+ ETHERTYPE_NCD = 0x8149
+ ETHERTYPE_NESTAR = 0x8006
+ ETHERTYPE_NETBEUI = 0x8191
+ ETHERTYPE_NOVELL = 0x8138
+ ETHERTYPE_NS = 0x600
+ ETHERTYPE_NSAT = 0x601
+ ETHERTYPE_NSCOMPAT = 0x807
+ ETHERTYPE_NTRAILER = 0x10
+ ETHERTYPE_OS9 = 0x7007
+ ETHERTYPE_OS9NET = 0x7009
+ ETHERTYPE_PACER = 0x80c6
+ ETHERTYPE_PAE = 0x888e
+ ETHERTYPE_PCS = 0x4242
+ ETHERTYPE_PLANNING = 0x8044
+ ETHERTYPE_PPP = 0x880b
+ ETHERTYPE_PPPOE = 0x8864
+ ETHERTYPE_PPPOEDISC = 0x8863
+ ETHERTYPE_PRIMENTS = 0x7031
+ ETHERTYPE_PUP = 0x200
+ ETHERTYPE_PUPAT = 0x200
+ ETHERTYPE_RACAL = 0x7030
+ ETHERTYPE_RATIONAL = 0x8150
+ ETHERTYPE_RAWFR = 0x6559
+ ETHERTYPE_RCL = 0x1995
+ ETHERTYPE_RDP = 0x8739
+ ETHERTYPE_RETIX = 0x80f2
+ ETHERTYPE_REVARP = 0x8035
+ ETHERTYPE_SCA = 0x6007
+ ETHERTYPE_SECTRA = 0x86db
+ ETHERTYPE_SECUREDATA = 0x876d
+ ETHERTYPE_SGITW = 0x817e
+ ETHERTYPE_SG_BOUNCE = 0x8016
+ ETHERTYPE_SG_DIAG = 0x8013
+ ETHERTYPE_SG_NETGAMES = 0x8014
+ ETHERTYPE_SG_RESV = 0x8015
+ ETHERTYPE_SIMNET = 0x5208
+ ETHERTYPE_SLOWPROTOCOLS = 0x8809
+ ETHERTYPE_SNA = 0x80d5
+ ETHERTYPE_SNMP = 0x814c
+ ETHERTYPE_SONIX = 0xfaf5
+ ETHERTYPE_SPIDER = 0x809f
+ ETHERTYPE_SPRITE = 0x500
+ ETHERTYPE_STP = 0x8181
+ ETHERTYPE_TALARIS = 0x812b
+ ETHERTYPE_TALARISMC = 0x852b
+ ETHERTYPE_TCPCOMP = 0x876b
+ ETHERTYPE_TCPSM = 0x9002
+ ETHERTYPE_TEC = 0x814f
+ ETHERTYPE_TIGAN = 0x802f
+ ETHERTYPE_TRAIL = 0x1000
+ ETHERTYPE_TRANSETHER = 0x6558
+ ETHERTYPE_TYMSHARE = 0x802e
+ ETHERTYPE_UBBST = 0x7005
+ ETHERTYPE_UBDEBUG = 0x900
+ ETHERTYPE_UBDIAGLOOP = 0x7002
+ ETHERTYPE_UBDL = 0x7000
+ ETHERTYPE_UBNIU = 0x7001
+ ETHERTYPE_UBNMC = 0x7003
+ ETHERTYPE_VALID = 0x1600
+ ETHERTYPE_VARIAN = 0x80dd
+ ETHERTYPE_VAXELN = 0x803b
+ ETHERTYPE_VEECO = 0x8067
+ ETHERTYPE_VEXP = 0x805b
+ ETHERTYPE_VGLAB = 0x8131
+ ETHERTYPE_VINES = 0xbad
+ ETHERTYPE_VINESECHO = 0xbaf
+ ETHERTYPE_VINESLOOP = 0xbae
+ ETHERTYPE_VITAL = 0xff00
+ ETHERTYPE_VLAN = 0x8100
+ ETHERTYPE_VLTLMAN = 0x8080
+ ETHERTYPE_VPROD = 0x805c
+ ETHERTYPE_VURESERVED = 0x8147
+ ETHERTYPE_WATERLOO = 0x8130
+ ETHERTYPE_WELLFLEET = 0x8103
+ ETHERTYPE_X25 = 0x805
+ ETHERTYPE_X75 = 0x801
+ ETHERTYPE_XNSSM = 0x9001
+ ETHERTYPE_XTP = 0x817d
+ ETHER_ADDR_LEN = 0x6
+ ETHER_CRC_LEN = 0x4
+ ETHER_CRC_POLY_BE = 0x4c11db6
+ ETHER_CRC_POLY_LE = 0xedb88320
+ ETHER_HDR_LEN = 0xe
+ ETHER_MAX_LEN = 0x5ee
+ ETHER_MAX_LEN_JUMBO = 0x233a
+ ETHER_MIN_LEN = 0x40
+ ETHER_PPPOE_ENCAP_LEN = 0x8
+ ETHER_TYPE_LEN = 0x2
+ ETHER_VLAN_ENCAP_LEN = 0x4
+ EVFILT_AIO = 0x2
+ EVFILT_PROC = 0x4
+ EVFILT_READ = 0x0
+ EVFILT_SIGNAL = 0x5
+ EVFILT_SYSCOUNT = 0x7
+ EVFILT_TIMER = 0x6
+ EVFILT_VNODE = 0x3
+ EVFILT_WRITE = 0x1
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG1 = 0x2000
+ EV_ONESHOT = 0x10
+ EV_SYSFLAGS = 0xf000
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x100
+ FLUSHO = 0x800000
+ F_CLOSEM = 0xa
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0xc
+ F_FSCTL = -0x80000000
+ F_FSDIRMASK = 0x70000000
+ F_FSIN = 0x10000000
+ F_FSINOUT = 0x30000000
+ F_FSOUT = 0x20000000
+ F_FSPRIV = 0x8000
+ F_FSVOID = 0x40000000
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETNOSIGPIPE = 0xd
+ F_GETOWN = 0x5
+ F_MAXFD = 0xb
+ F_OK = 0x0
+ F_PARAM_MASK = 0xfff
+ F_PARAM_MAX = 0xfff
+ F_RDLCK = 0x1
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETNOSIGPIPE = 0xe
+ F_SETOWN = 0x6
+ F_UNLCK = 0x2
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFAN_ARRIVAL = 0x0
+ IFAN_DEPARTURE = 0x1
+ IFA_ROUTE = 0x1
+ IFF_ALLMULTI = 0x200
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x8f52
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NOTRAILERS = 0x20
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_A12MPPSWITCH = 0x82
+ IFT_AAL2 = 0xbb
+ IFT_AAL5 = 0x31
+ IFT_ADSL = 0x5e
+ IFT_AFLANE8023 = 0x3b
+ IFT_AFLANE8025 = 0x3c
+ IFT_ARAP = 0x58
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ASYNC = 0x54
+ IFT_ATM = 0x25
+ IFT_ATMDXI = 0x69
+ IFT_ATMFUNI = 0x6a
+ IFT_ATMIMA = 0x6b
+ IFT_ATMLOGICAL = 0x50
+ IFT_ATMRADIO = 0xbd
+ IFT_ATMSUBINTERFACE = 0x86
+ IFT_ATMVCIENDPT = 0xc2
+ IFT_ATMVIRTUAL = 0x95
+ IFT_BGPPOLICYACCOUNTING = 0xa2
+ IFT_BRIDGE = 0xd1
+ IFT_BSC = 0x53
+ IFT_CARP = 0xf8
+ IFT_CCTEMUL = 0x3d
+ IFT_CEPT = 0x13
+ IFT_CES = 0x85
+ IFT_CHANNEL = 0x46
+ IFT_CNR = 0x55
+ IFT_COFFEE = 0x84
+ IFT_COMPOSITELINK = 0x9b
+ IFT_DCN = 0x8d
+ IFT_DIGITALPOWERLINE = 0x8a
+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
+ IFT_DLSW = 0x4a
+ IFT_DOCSCABLEDOWNSTREAM = 0x80
+ IFT_DOCSCABLEMACLAYER = 0x7f
+ IFT_DOCSCABLEUPSTREAM = 0x81
+ IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd
+ IFT_DS0 = 0x51
+ IFT_DS0BUNDLE = 0x52
+ IFT_DS1FDL = 0xaa
+ IFT_DS3 = 0x1e
+ IFT_DTM = 0x8c
+ IFT_DVBASILN = 0xac
+ IFT_DVBASIOUT = 0xad
+ IFT_DVBRCCDOWNSTREAM = 0x93
+ IFT_DVBRCCMACLAYER = 0x92
+ IFT_DVBRCCUPSTREAM = 0x94
+ IFT_ECONET = 0xce
+ IFT_EON = 0x19
+ IFT_EPLRS = 0x57
+ IFT_ESCON = 0x49
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0xf2
+ IFT_FAST = 0x7d
+ IFT_FASTETHER = 0x3e
+ IFT_FASTETHERFX = 0x45
+ IFT_FDDI = 0xf
+ IFT_FIBRECHANNEL = 0x38
+ IFT_FRAMERELAYINTERCONNECT = 0x3a
+ IFT_FRAMERELAYMPI = 0x5c
+ IFT_FRDLCIENDPT = 0xc1
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_FRF16MFRBUNDLE = 0xa3
+ IFT_FRFORWARD = 0x9e
+ IFT_G703AT2MB = 0x43
+ IFT_G703AT64K = 0x42
+ IFT_GIF = 0xf0
+ IFT_GIGABITETHERNET = 0x75
+ IFT_GR303IDT = 0xb2
+ IFT_GR303RDT = 0xb1
+ IFT_H323GATEKEEPER = 0xa4
+ IFT_H323PROXY = 0xa5
+ IFT_HDH1822 = 0x3
+ IFT_HDLC = 0x76
+ IFT_HDSL2 = 0xa8
+ IFT_HIPERLAN2 = 0xb7
+ IFT_HIPPI = 0x2f
+ IFT_HIPPIINTERFACE = 0x39
+ IFT_HOSTPAD = 0x5a
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IBM370PARCHAN = 0x48
+ IFT_IDSL = 0x9a
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE80211 = 0x47
+ IFT_IEEE80212 = 0x37
+ IFT_IEEE8023ADLAG = 0xa1
+ IFT_IFGSN = 0x91
+ IFT_IMT = 0xbe
+ IFT_INFINIBAND = 0xc7
+ IFT_INTERLEAVE = 0x7c
+ IFT_IP = 0x7e
+ IFT_IPFORWARD = 0x8e
+ IFT_IPOVERATM = 0x72
+ IFT_IPOVERCDLC = 0x6d
+ IFT_IPOVERCLAW = 0x6e
+ IFT_IPSWITCH = 0x4e
+ IFT_ISDN = 0x3f
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISDNS = 0x4b
+ IFT_ISDNU = 0x4c
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88025CRFPINT = 0x62
+ IFT_ISO88025DTR = 0x56
+ IFT_ISO88025FIBER = 0x73
+ IFT_ISO88026 = 0xa
+ IFT_ISUP = 0xb3
+ IFT_L2VLAN = 0x87
+ IFT_L3IPVLAN = 0x88
+ IFT_L3IPXVLAN = 0x89
+ IFT_LAPB = 0x10
+ IFT_LAPD = 0x4d
+ IFT_LAPF = 0x77
+ IFT_LINEGROUP = 0xd2
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MEDIAMAILOVERIP = 0x8b
+ IFT_MFSIGLINK = 0xa7
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_MPC = 0x71
+ IFT_MPLS = 0xa6
+ IFT_MPLSTUNNEL = 0x96
+ IFT_MSDSL = 0x8f
+ IFT_MVL = 0xbf
+ IFT_MYRINET = 0x63
+ IFT_NFAS = 0xaf
+ IFT_NSIP = 0x1b
+ IFT_OPTICALCHANNEL = 0xc3
+ IFT_OPTICALTRANSPORT = 0xc4
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PFLOG = 0xf5
+ IFT_PFSYNC = 0xf6
+ IFT_PLC = 0xae
+ IFT_PON155 = 0xcf
+ IFT_PON622 = 0xd0
+ IFT_POS = 0xab
+ IFT_PPP = 0x17
+ IFT_PPPMULTILINKBUNDLE = 0x6c
+ IFT_PROPATM = 0xc5
+ IFT_PROPBWAP2MP = 0xb8
+ IFT_PROPCNLS = 0x59
+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PROPWIRELESSP2P = 0x9d
+ IFT_PTPSERIAL = 0x16
+ IFT_PVC = 0xf1
+ IFT_Q2931 = 0xc9
+ IFT_QLLC = 0x44
+ IFT_RADIOMAC = 0xbc
+ IFT_RADSL = 0x5f
+ IFT_REACHDSL = 0xc0
+ IFT_RFC1483 = 0x9f
+ IFT_RS232 = 0x21
+ IFT_RSRB = 0x4f
+ IFT_SDLC = 0x11
+ IFT_SDSL = 0x60
+ IFT_SHDSL = 0xa9
+ IFT_SIP = 0x1f
+ IFT_SIPSIG = 0xcc
+ IFT_SIPTG = 0xcb
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETOVERHEADCHANNEL = 0xb9
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_SRP = 0x97
+ IFT_SS7SIGLINK = 0x9c
+ IFT_STACKTOSTACK = 0x6f
+ IFT_STARLAN = 0xb
+ IFT_STF = 0xd7
+ IFT_T1 = 0x12
+ IFT_TDLC = 0x74
+ IFT_TELINK = 0xc8
+ IFT_TERMPAD = 0x5b
+ IFT_TR008 = 0xb0
+ IFT_TRANSPHDLC = 0x7b
+ IFT_TUNNEL = 0x83
+ IFT_ULTRA = 0x1d
+ IFT_USB = 0xa0
+ IFT_V11 = 0x40
+ IFT_V35 = 0x2d
+ IFT_V36 = 0x41
+ IFT_V37 = 0x78
+ IFT_VDSL = 0x61
+ IFT_VIRTUALIPADDRESS = 0x70
+ IFT_VIRTUALTG = 0xca
+ IFT_VOICEDID = 0xd5
+ IFT_VOICEEM = 0x64
+ IFT_VOICEEMFGD = 0xd3
+ IFT_VOICEENCAP = 0x67
+ IFT_VOICEFGDEANA = 0xd4
+ IFT_VOICEFXO = 0x65
+ IFT_VOICEFXS = 0x66
+ IFT_VOICEOVERATM = 0x98
+ IFT_VOICEOVERCABLE = 0xc6
+ IFT_VOICEOVERFRAMERELAY = 0x99
+ IFT_VOICEOVERIP = 0x68
+ IFT_X213 = 0x5d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25HUNTGROUP = 0x7a
+ IFT_X25MLP = 0x79
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LOOPBACKNET = 0x7f
+ IPPROTO_AH = 0x33
+ IPPROTO_CARP = 0x70
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IPV6_ICMP = 0x3a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x34
+ IPPROTO_MOBILE = 0x37
+ IPPROTO_NONE = 0x3b
+ IPPROTO_PFSYNC = 0xf0
+ IPPROTO_PIM = 0x67
+ IPPROTO_PUP = 0xc
+ IPPROTO_RAW = 0xff
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_TCP = 0x6
+ IPPROTO_TP = 0x1d
+ IPPROTO_UDP = 0x11
+ IPPROTO_VRRP = 0x70
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_DONTFRAG = 0x3e
+ IPV6_DSTOPTS = 0x32
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x78
+ IPV6_HLIMDEC = 0x1
+ IPV6_HOPLIMIT = 0x2f
+ IPV6_HOPOPTS = 0x31
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MMTU = 0x500
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_NEXTHOP = 0x30
+ IPV6_PATHMTU = 0x2c
+ IPV6_PKTINFO = 0x2e
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVHOPLIMIT = 0x25
+ IPV6_RECVHOPOPTS = 0x27
+ IPV6_RECVPATHMTU = 0x2b
+ IPV6_RECVPKTINFO = 0x24
+ IPV6_RECVRTHDR = 0x26
+ IPV6_RECVTCLASS = 0x39
+ IPV6_RTHDR = 0x33
+ IPV6_RTHDRDSTOPTS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x3d
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_USE_MIN_MTU = 0x2a
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_EF = 0x8000
+ IP_ERRORMTU = 0x15
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x16
+ IP_MAXPACKET = 0xffff
+ IP_MAX_MEMBERSHIPS = 0x14
+ IP_MF = 0x2000
+ IP_MINFRAGSIZE = 0x45
+ IP_MINTTL = 0x18
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_OFFMASK = 0x1fff
+ IP_OPTIONS = 0x1
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVRETOPTS = 0x6
+ IP_RECVTTL = 0x17
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x6
+ MADV_NORMAL = 0x0
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_SPACEAVAIL = 0x5
+ MADV_WILLNEED = 0x3
+ MAP_ALIGNMENT_16MB = 0x18000000
+ MAP_ALIGNMENT_1TB = 0x28000000
+ MAP_ALIGNMENT_256TB = 0x30000000
+ MAP_ALIGNMENT_4GB = 0x20000000
+ MAP_ALIGNMENT_64KB = 0x10000000
+ MAP_ALIGNMENT_64PB = 0x38000000
+ MAP_ALIGNMENT_MASK = -0x1000000
+ MAP_ALIGNMENT_SHIFT = 0x18
+ MAP_ANON = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_HASSEMAPHORE = 0x200
+ MAP_INHERIT = 0x80
+ MAP_INHERIT_COPY = 0x1
+ MAP_INHERIT_DEFAULT = 0x1
+ MAP_INHERIT_DONATE_COPY = 0x3
+ MAP_INHERIT_NONE = 0x2
+ MAP_INHERIT_SHARE = 0x0
+ MAP_NORESERVE = 0x40
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x2000
+ MAP_TRYFIXED = 0x400
+ MAP_WIRED = 0x800
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MSG_BCAST = 0x100
+ MSG_CMSG_CLOEXEC = 0x800
+ MSG_CONTROLMBUF = 0x2000000
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOR = 0x8
+ MSG_IOVUSRSPACE = 0x4000000
+ MSG_LENUSRSPACE = 0x8000000
+ MSG_MCAST = 0x200
+ MSG_NAMEMBUF = 0x1000000
+ MSG_NBIO = 0x1000
+ MSG_NOSIGNAL = 0x400
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x10
+ MSG_USERFLAGS = 0xffffff
+ MSG_WAITALL = 0x40
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x2
+ MS_SYNC = 0x4
+ NAME_MAX = 0x1ff
+ NET_RT_DUMP = 0x1
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x5
+ NET_RT_MAXID = 0x6
+ NET_RT_OIFLIST = 0x4
+ NET_RT_OOIFLIST = 0x3
+ NOFLSH = 0x80000000
+ NOTE_ATTRIB = 0x8
+ NOTE_CHILD = 0x4
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXTEND = 0x4
+ NOTE_FORK = 0x40000000
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_PCTRLMASK = 0xf0000000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ OFIOGETBMAP = 0xc004667a
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ O_ACCMODE = 0x3
+ O_ALT_IO = 0x40000
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x400000
+ O_CREAT = 0x200
+ O_DIRECT = 0x80000
+ O_DIRECTORY = 0x200000
+ O_DSYNC = 0x10000
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_NOSIGPIPE = 0x1000000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x20000
+ O_SHLOCK = 0x10
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PRI_IOFLUSH = 0x7c
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ RLIMIT_AS = 0xa
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x9
+ RTAX_NETMASK = 0x2
+ RTAX_TAG = 0x8
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTA_TAG = 0x100
+ RTF_ANNOUNCE = 0x20000
+ RTF_BLACKHOLE = 0x1000
+ RTF_CLONED = 0x2000
+ RTF_CLONING = 0x100
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_LLINFO = 0x400
+ RTF_MASK = 0x80
+ RTF_MODIFIED = 0x20
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_REJECT = 0x8
+ RTF_SRC = 0x10000
+ RTF_STATIC = 0x800
+ RTF_UP = 0x1
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_CHGADDR = 0x15
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_GET = 0x4
+ RTM_IEEE80211 = 0x11
+ RTM_IFANNOUNCE = 0x10
+ RTM_IFINFO = 0x14
+ RTM_LLINFO_UPD = 0x13
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_OIFINFO = 0xf
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ RTM_OOIFINFO = 0xe
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_SETGATE = 0x12
+ RTM_VERSION = 0x4
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ SCM_CREDS = 0x4
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x8
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80906931
+ SIOCADDRT = 0x8038720a
+ SIOCAIFADDR = 0x8040691a
+ SIOCALIFADDR = 0x8118691c
+ SIOCATMARK = 0x40047307
+ SIOCDELMULTI = 0x80906932
+ SIOCDELRT = 0x8038720b
+ SIOCDIFADDR = 0x80906919
+ SIOCDIFPHYADDR = 0x80906949
+ SIOCDLIFADDR = 0x8118691e
+ SIOCGDRVSPEC = 0xc028697b
+ SIOCGETPFSYNC = 0xc09069f8
+ SIOCGETSGCNT = 0xc0207534
+ SIOCGETVIFCNT = 0xc0287533
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0906921
+ SIOCGIFADDRPREF = 0xc0986920
+ SIOCGIFALIAS = 0xc040691b
+ SIOCGIFBRDADDR = 0xc0906923
+ SIOCGIFCAP = 0xc0206976
+ SIOCGIFCONF = 0xc0106926
+ SIOCGIFDATA = 0xc0986985
+ SIOCGIFDLT = 0xc0906977
+ SIOCGIFDSTADDR = 0xc0906922
+ SIOCGIFFLAGS = 0xc0906911
+ SIOCGIFGENERIC = 0xc090693a
+ SIOCGIFMEDIA = 0xc0306936
+ SIOCGIFMETRIC = 0xc0906917
+ SIOCGIFMTU = 0xc090697e
+ SIOCGIFNETMASK = 0xc0906925
+ SIOCGIFPDSTADDR = 0xc0906948
+ SIOCGIFPSRCADDR = 0xc0906947
+ SIOCGLIFADDR = 0xc118691d
+ SIOCGLIFPHYADDR = 0xc118694b
+ SIOCGLINKSTR = 0xc0286987
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCGVH = 0xc0906983
+ SIOCIFCREATE = 0x8090697a
+ SIOCIFDESTROY = 0x80906979
+ SIOCIFGCLONERS = 0xc0106978
+ SIOCINITIFADDR = 0xc0706984
+ SIOCSDRVSPEC = 0x8028697b
+ SIOCSETPFSYNC = 0x809069f7
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8090690c
+ SIOCSIFADDRPREF = 0x8098691f
+ SIOCSIFBRDADDR = 0x80906913
+ SIOCSIFCAP = 0x80206975
+ SIOCSIFDSTADDR = 0x8090690e
+ SIOCSIFFLAGS = 0x80906910
+ SIOCSIFGENERIC = 0x80906939
+ SIOCSIFMEDIA = 0xc0906935
+ SIOCSIFMETRIC = 0x80906918
+ SIOCSIFMTU = 0x8090697f
+ SIOCSIFNETMASK = 0x80906916
+ SIOCSIFPHYADDR = 0x80406946
+ SIOCSLIFPHYADDR = 0x8118694a
+ SIOCSLINKSTR = 0x80286988
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SIOCSVH = 0xc0906982
+ SIOCZIFDATA = 0xc0986986
+ SOCK_CLOEXEC = 0x10000000
+ SOCK_DGRAM = 0x2
+ SOCK_FLAGS_MASK = 0xf0000000
+ SOCK_NONBLOCK = 0x20000000
+ SOCK_NOSIGPIPE = 0x40000000
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_ACCEPTFILTER = 0x1000
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LINGER = 0x80
+ SO_NOHEADER = 0x100a
+ SO_NOSIGPIPE = 0x800
+ SO_OOBINLINE = 0x100
+ SO_OVERFLOWED = 0x1009
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x100c
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x100b
+ SO_TIMESTAMP = 0x2000
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ SYSCTL_VERSION = 0x1000000
+ SYSCTL_VERS_0 = 0x0
+ SYSCTL_VERS_1 = 0x1000000
+ SYSCTL_VERS_MASK = 0xff000000
+ S_ARCH1 = 0x10000
+ S_ARCH2 = 0x20000
+ 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_IFWHT = 0xe000
+ 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_ISTXT = 0x200
+ 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
+ S_LOGIN_SET = 0x1
+ TCIFLUSH = 0x1
+ TCIOFLUSH = 0x3
+ TCOFLUSH = 0x2
+ TCP_CONGCTL = 0x20
+ TCP_KEEPCNT = 0x6
+ TCP_KEEPIDLE = 0x3
+ TCP_KEEPINIT = 0x7
+ TCP_KEEPINTVL = 0x5
+ TCP_MAXBURST = 0x4
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MD5SIG = 0x10
+ TCP_MINMSS = 0xd8
+ TCP_MSS = 0x218
+ TCP_NODELAY = 0x1
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDCDTIMESTAMP = 0x40107458
+ TIOCDRAIN = 0x2000745e
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLAG_CDTRCTS = 0x10
+ TIOCFLAG_CLOCAL = 0x2
+ TIOCFLAG_CRTSCTS = 0x4
+ TIOCFLAG_MDMBUF = 0x8
+ TIOCFLAG_SOFTCAR = 0x1
+ TIOCFLUSH = 0x80047410
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGFLAGS = 0x4004745d
+ TIOCGLINED = 0x40207442
+ TIOCGPGRP = 0x40047477
+ TIOCGQSIZE = 0x40047481
+ TIOCGRANTPT = 0x20007447
+ TIOCGSID = 0x40047463
+ TIOCGSIZE = 0x40087468
+ TIOCGWINSZ = 0x40087468
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGET = 0x4004746a
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCPTMGET = 0x40287446
+ TIOCPTSNAME = 0x40287448
+ TIOCRCVFRAME = 0x80087445
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCTTY = 0x20007461
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSFLAGS = 0x8004745c
+ TIOCSIG = 0x2000745f
+ TIOCSLINED = 0x80207443
+ TIOCSPGRP = 0x80047476
+ TIOCSQSIZE = 0x80047480
+ TIOCSSIZE = 0x80087467
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x80047465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCUCNTL = 0x80047466
+ TIOCXMTFRAME = 0x80087444
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VTIME = 0x11
+ VWERASE = 0x4
+ WALL = 0x8
+ WALLSIG = 0x8
+ WALTSIG = 0x4
+ WCLONE = 0x4
+ WCOREFLAG = 0x80
+ WNOHANG = 0x1
+ WNOWAIT = 0x10000
+ WNOZOMBIE = 0x20000
+ WOPTSCHECKED = 0x40000
+ WSTOPPED = 0x7f
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADF = syscall.Errno(0x9)
+ EBADMSG = syscall.Errno(0x58)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x57)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x52)
+ EILSEQ = syscall.Errno(0x55)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x60)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5e)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x5d)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODATA = syscall.Errno(0x59)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x5f)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x53)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x5a)
+ ENOSTR = syscall.Errno(0x5b)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x56)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x54)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x60)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIME = syscall.Errno(0x5c)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x20)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large or too small",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol option not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "connection timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "identifier removed",
+ 83: "no message of desired type",
+ 84: "value too large to be stored in data type",
+ 85: "illegal byte sequence",
+ 86: "not supported",
+ 87: "operation Canceled",
+ 88: "bad or Corrupt message",
+ 89: "no message available",
+ 90: "no STREAM resources",
+ 91: "not a STREAM",
+ 92: "STREAM ioctl timeout",
+ 93: "attribute not found",
+ 94: "multihop attempted",
+ 95: "link has been severed",
+ 96: "protocol error",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "stopped (signal)",
+ 18: "stopped",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+ 32: "power fail/restart",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go
new file mode 100644
index 0000000..206c75f
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go
@@ -0,0 +1,1691 @@
+// mkerrors.sh -marm
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+// +build arm,netbsd
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -marm _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_ARP = 0x1c
+ AF_BLUETOOTH = 0x1f
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1a
+ AF_ECMA = 0x8
+ AF_HYLINK = 0xf
+ AF_IEEE80211 = 0x20
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x18
+ AF_IPX = 0x17
+ AF_ISDN = 0x1a
+ AF_ISO = 0x7
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x23
+ AF_MPLS = 0x21
+ AF_NATM = 0x1b
+ AF_NS = 0x6
+ AF_OROUTE = 0x11
+ AF_OSI = 0x7
+ AF_PUP = 0x4
+ AF_ROUTE = 0x22
+ AF_SNA = 0xb
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ ARPHRD_ARCNET = 0x7
+ ARPHRD_ETHER = 0x1
+ ARPHRD_FRELAY = 0xf
+ ARPHRD_IEEE1394 = 0x18
+ ARPHRD_IEEE802 = 0x6
+ ARPHRD_STRIP = 0x17
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B460800 = 0x70800
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B921600 = 0xe1000
+ B9600 = 0x2580
+ BIOCFEEDBACK = 0x8004427d
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc0084277
+ BIOCGETIF = 0x4090426b
+ BIOCGFEEDBACK = 0x4004427c
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRTIMEOUT = 0x400c427b
+ BIOCGSEESENT = 0x40044278
+ BIOCGSTATS = 0x4080426f
+ BIOCGSTATSOLD = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDLT = 0x80044276
+ BIOCSETF = 0x80084267
+ BIOCSETIF = 0x8090426c
+ BIOCSFEEDBACK = 0x8004427d
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRTIMEOUT = 0x800c427a
+ BIOCSSEESENT = 0x80044279
+ BIOCSTCPF = 0x80084272
+ BIOCSUDPF = 0x80084273
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ BPF_ALIGNMENT32 = 0x4
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_DFLTBUFSIZE = 0x100000
+ 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_MAXBUFSIZE = 0x1000000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CREAD = 0x800
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ CTL_QUERY = -0x2
+ DIOCBSFLUSH = 0x20006478
+ DLT_A429 = 0xb8
+ DLT_A653_ICM = 0xb9
+ DLT_AIRONET_HEADER = 0x78
+ DLT_AOS = 0xde
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_AX25_KISS = 0xca
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_BLUETOOTH_HCI_H4 = 0xbb
+ DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
+ DLT_CAN20B = 0xbe
+ DLT_CAN_SOCKETCAN = 0xe3
+ DLT_CHAOS = 0x5
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_C_HDLC_WITH_DIR = 0xcd
+ DLT_DECT = 0xdd
+ DLT_DOCSIS = 0x8f
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_ERF = 0xc5
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FC_2 = 0xe0
+ DLT_FC_2_WITH_FRAME_DELIMS = 0xe1
+ DLT_FDDI = 0xa
+ DLT_FLEXRAY = 0xd2
+ DLT_FRELAY = 0x6b
+ DLT_FRELAY_WITH_DIR = 0xce
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_GSMTAP_ABIS = 0xda
+ DLT_GSMTAP_UM = 0xd9
+ DLT_HDLC = 0x10
+ DLT_HHDLC = 0x79
+ DLT_HIPPI = 0xf
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IEEE802_15_4 = 0xc3
+ DLT_IEEE802_15_4_LINUX = 0xbf
+ DLT_IEEE802_15_4_NONASK_PHY = 0xd7
+ DLT_IEEE802_16_MAC_CPS = 0xbc
+ DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
+ DLT_IPMB = 0xc7
+ DLT_IPMB_LINUX = 0xd1
+ DLT_IPNET = 0xe2
+ DLT_IPV4 = 0xe4
+ DLT_IPV6 = 0xe5
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_ISM = 0xc2
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_JUNIPER_ST = 0xc8
+ DLT_JUNIPER_VP = 0xb7
+ DLT_LAPB_WITH_DIR = 0xcf
+ DLT_LAPD = 0xcb
+ DLT_LIN = 0xd4
+ DLT_LINUX_EVDEV = 0xd8
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MFR = 0xb6
+ DLT_MOST = 0xd3
+ DLT_MPLS = 0xdb
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPI = 0xc0
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0xe
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_PPPD = 0xa6
+ DLT_PPP_SERIAL = 0x32
+ DLT_PPP_WITH_DIR = 0xcc
+ DLT_PRISM_HEADER = 0x77
+ DLT_PRONET = 0x4
+ DLT_RAIF1 = 0xc6
+ DLT_RAW = 0xc
+ DLT_RAWAF_MASK = 0x2240000
+ DLT_RIO = 0x7c
+ DLT_SCCP = 0x8e
+ DLT_SITA = 0xc4
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xd
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ DLT_USB = 0xba
+ DLT_USB_LINUX = 0xbd
+ DLT_USB_LINUX_MMAPPED = 0xdc
+ DLT_WIHART = 0xdf
+ DLT_X2E_SERIAL = 0xd5
+ DLT_X2E_XORAYA = 0xd6
+ 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 = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EMUL_LINUX = 0x1
+ EMUL_LINUX32 = 0x5
+ EMUL_MAXID = 0x6
+ ETHERCAP_JUMBO_MTU = 0x4
+ ETHERCAP_VLAN_HWTAGGING = 0x2
+ ETHERCAP_VLAN_MTU = 0x1
+ ETHERMIN = 0x2e
+ ETHERMTU = 0x5dc
+ ETHERMTU_JUMBO = 0x2328
+ ETHERTYPE_8023 = 0x4
+ ETHERTYPE_AARP = 0x80f3
+ ETHERTYPE_ACCTON = 0x8390
+ ETHERTYPE_AEONIC = 0x8036
+ ETHERTYPE_ALPHA = 0x814a
+ ETHERTYPE_AMBER = 0x6008
+ ETHERTYPE_AMOEBA = 0x8145
+ ETHERTYPE_APOLLO = 0x80f7
+ ETHERTYPE_APOLLODOMAIN = 0x8019
+ ETHERTYPE_APPLETALK = 0x809b
+ ETHERTYPE_APPLITEK = 0x80c7
+ ETHERTYPE_ARGONAUT = 0x803a
+ ETHERTYPE_ARP = 0x806
+ ETHERTYPE_AT = 0x809b
+ ETHERTYPE_ATALK = 0x809b
+ ETHERTYPE_ATOMIC = 0x86df
+ ETHERTYPE_ATT = 0x8069
+ ETHERTYPE_ATTSTANFORD = 0x8008
+ ETHERTYPE_AUTOPHON = 0x806a
+ ETHERTYPE_AXIS = 0x8856
+ ETHERTYPE_BCLOOP = 0x9003
+ ETHERTYPE_BOFL = 0x8102
+ ETHERTYPE_CABLETRON = 0x7034
+ ETHERTYPE_CHAOS = 0x804
+ ETHERTYPE_COMDESIGN = 0x806c
+ ETHERTYPE_COMPUGRAPHIC = 0x806d
+ ETHERTYPE_COUNTERPOINT = 0x8062
+ ETHERTYPE_CRONUS = 0x8004
+ ETHERTYPE_CRONUSVLN = 0x8003
+ ETHERTYPE_DCA = 0x1234
+ ETHERTYPE_DDE = 0x807b
+ ETHERTYPE_DEBNI = 0xaaaa
+ ETHERTYPE_DECAM = 0x8048
+ ETHERTYPE_DECCUST = 0x6006
+ ETHERTYPE_DECDIAG = 0x6005
+ ETHERTYPE_DECDNS = 0x803c
+ ETHERTYPE_DECDTS = 0x803e
+ ETHERTYPE_DECEXPER = 0x6000
+ ETHERTYPE_DECLAST = 0x8041
+ ETHERTYPE_DECLTM = 0x803f
+ ETHERTYPE_DECMUMPS = 0x6009
+ ETHERTYPE_DECNETBIOS = 0x8040
+ ETHERTYPE_DELTACON = 0x86de
+ ETHERTYPE_DIDDLE = 0x4321
+ ETHERTYPE_DLOG1 = 0x660
+ ETHERTYPE_DLOG2 = 0x661
+ ETHERTYPE_DN = 0x6003
+ ETHERTYPE_DOGFIGHT = 0x1989
+ ETHERTYPE_DSMD = 0x8039
+ ETHERTYPE_ECMA = 0x803
+ ETHERTYPE_ENCRYPT = 0x803d
+ ETHERTYPE_ES = 0x805d
+ ETHERTYPE_EXCELAN = 0x8010
+ ETHERTYPE_EXPERDATA = 0x8049
+ ETHERTYPE_FLIP = 0x8146
+ ETHERTYPE_FLOWCONTROL = 0x8808
+ ETHERTYPE_FRARP = 0x808
+ ETHERTYPE_GENDYN = 0x8068
+ ETHERTYPE_HAYES = 0x8130
+ ETHERTYPE_HIPPI_FP = 0x8180
+ ETHERTYPE_HITACHI = 0x8820
+ ETHERTYPE_HP = 0x8005
+ ETHERTYPE_IEEEPUP = 0xa00
+ ETHERTYPE_IEEEPUPAT = 0xa01
+ ETHERTYPE_IMLBL = 0x4c42
+ ETHERTYPE_IMLBLDIAG = 0x424c
+ ETHERTYPE_IP = 0x800
+ ETHERTYPE_IPAS = 0x876c
+ ETHERTYPE_IPV6 = 0x86dd
+ ETHERTYPE_IPX = 0x8137
+ ETHERTYPE_IPXNEW = 0x8037
+ ETHERTYPE_KALPANA = 0x8582
+ ETHERTYPE_LANBRIDGE = 0x8038
+ ETHERTYPE_LANPROBE = 0x8888
+ ETHERTYPE_LAT = 0x6004
+ ETHERTYPE_LBACK = 0x9000
+ ETHERTYPE_LITTLE = 0x8060
+ ETHERTYPE_LOGICRAFT = 0x8148
+ ETHERTYPE_LOOPBACK = 0x9000
+ ETHERTYPE_MATRA = 0x807a
+ ETHERTYPE_MAX = 0xffff
+ ETHERTYPE_MERIT = 0x807c
+ ETHERTYPE_MICP = 0x873a
+ ETHERTYPE_MOPDL = 0x6001
+ ETHERTYPE_MOPRC = 0x6002
+ ETHERTYPE_MOTOROLA = 0x818d
+ ETHERTYPE_MPLS = 0x8847
+ ETHERTYPE_MPLS_MCAST = 0x8848
+ ETHERTYPE_MUMPS = 0x813f
+ ETHERTYPE_NBPCC = 0x3c04
+ ETHERTYPE_NBPCLAIM = 0x3c09
+ ETHERTYPE_NBPCLREQ = 0x3c05
+ ETHERTYPE_NBPCLRSP = 0x3c06
+ ETHERTYPE_NBPCREQ = 0x3c02
+ ETHERTYPE_NBPCRSP = 0x3c03
+ ETHERTYPE_NBPDG = 0x3c07
+ ETHERTYPE_NBPDGB = 0x3c08
+ ETHERTYPE_NBPDLTE = 0x3c0a
+ ETHERTYPE_NBPRAR = 0x3c0c
+ ETHERTYPE_NBPRAS = 0x3c0b
+ ETHERTYPE_NBPRST = 0x3c0d
+ ETHERTYPE_NBPSCD = 0x3c01
+ ETHERTYPE_NBPVCD = 0x3c00
+ ETHERTYPE_NBS = 0x802
+ ETHERTYPE_NCD = 0x8149
+ ETHERTYPE_NESTAR = 0x8006
+ ETHERTYPE_NETBEUI = 0x8191
+ ETHERTYPE_NOVELL = 0x8138
+ ETHERTYPE_NS = 0x600
+ ETHERTYPE_NSAT = 0x601
+ ETHERTYPE_NSCOMPAT = 0x807
+ ETHERTYPE_NTRAILER = 0x10
+ ETHERTYPE_OS9 = 0x7007
+ ETHERTYPE_OS9NET = 0x7009
+ ETHERTYPE_PACER = 0x80c6
+ ETHERTYPE_PAE = 0x888e
+ ETHERTYPE_PCS = 0x4242
+ ETHERTYPE_PLANNING = 0x8044
+ ETHERTYPE_PPP = 0x880b
+ ETHERTYPE_PPPOE = 0x8864
+ ETHERTYPE_PPPOEDISC = 0x8863
+ ETHERTYPE_PRIMENTS = 0x7031
+ ETHERTYPE_PUP = 0x200
+ ETHERTYPE_PUPAT = 0x200
+ ETHERTYPE_RACAL = 0x7030
+ ETHERTYPE_RATIONAL = 0x8150
+ ETHERTYPE_RAWFR = 0x6559
+ ETHERTYPE_RCL = 0x1995
+ ETHERTYPE_RDP = 0x8739
+ ETHERTYPE_RETIX = 0x80f2
+ ETHERTYPE_REVARP = 0x8035
+ ETHERTYPE_SCA = 0x6007
+ ETHERTYPE_SECTRA = 0x86db
+ ETHERTYPE_SECUREDATA = 0x876d
+ ETHERTYPE_SGITW = 0x817e
+ ETHERTYPE_SG_BOUNCE = 0x8016
+ ETHERTYPE_SG_DIAG = 0x8013
+ ETHERTYPE_SG_NETGAMES = 0x8014
+ ETHERTYPE_SG_RESV = 0x8015
+ ETHERTYPE_SIMNET = 0x5208
+ ETHERTYPE_SLOWPROTOCOLS = 0x8809
+ ETHERTYPE_SNA = 0x80d5
+ ETHERTYPE_SNMP = 0x814c
+ ETHERTYPE_SONIX = 0xfaf5
+ ETHERTYPE_SPIDER = 0x809f
+ ETHERTYPE_SPRITE = 0x500
+ ETHERTYPE_STP = 0x8181
+ ETHERTYPE_TALARIS = 0x812b
+ ETHERTYPE_TALARISMC = 0x852b
+ ETHERTYPE_TCPCOMP = 0x876b
+ ETHERTYPE_TCPSM = 0x9002
+ ETHERTYPE_TEC = 0x814f
+ ETHERTYPE_TIGAN = 0x802f
+ ETHERTYPE_TRAIL = 0x1000
+ ETHERTYPE_TRANSETHER = 0x6558
+ ETHERTYPE_TYMSHARE = 0x802e
+ ETHERTYPE_UBBST = 0x7005
+ ETHERTYPE_UBDEBUG = 0x900
+ ETHERTYPE_UBDIAGLOOP = 0x7002
+ ETHERTYPE_UBDL = 0x7000
+ ETHERTYPE_UBNIU = 0x7001
+ ETHERTYPE_UBNMC = 0x7003
+ ETHERTYPE_VALID = 0x1600
+ ETHERTYPE_VARIAN = 0x80dd
+ ETHERTYPE_VAXELN = 0x803b
+ ETHERTYPE_VEECO = 0x8067
+ ETHERTYPE_VEXP = 0x805b
+ ETHERTYPE_VGLAB = 0x8131
+ ETHERTYPE_VINES = 0xbad
+ ETHERTYPE_VINESECHO = 0xbaf
+ ETHERTYPE_VINESLOOP = 0xbae
+ ETHERTYPE_VITAL = 0xff00
+ ETHERTYPE_VLAN = 0x8100
+ ETHERTYPE_VLTLMAN = 0x8080
+ ETHERTYPE_VPROD = 0x805c
+ ETHERTYPE_VURESERVED = 0x8147
+ ETHERTYPE_WATERLOO = 0x8130
+ ETHERTYPE_WELLFLEET = 0x8103
+ ETHERTYPE_X25 = 0x805
+ ETHERTYPE_X75 = 0x801
+ ETHERTYPE_XNSSM = 0x9001
+ ETHERTYPE_XTP = 0x817d
+ ETHER_ADDR_LEN = 0x6
+ ETHER_CRC_LEN = 0x4
+ ETHER_CRC_POLY_BE = 0x4c11db6
+ ETHER_CRC_POLY_LE = 0xedb88320
+ ETHER_HDR_LEN = 0xe
+ ETHER_MAX_LEN = 0x5ee
+ ETHER_MAX_LEN_JUMBO = 0x233a
+ ETHER_MIN_LEN = 0x40
+ ETHER_PPPOE_ENCAP_LEN = 0x8
+ ETHER_TYPE_LEN = 0x2
+ ETHER_VLAN_ENCAP_LEN = 0x4
+ EVFILT_AIO = 0x2
+ EVFILT_PROC = 0x4
+ EVFILT_READ = 0x0
+ EVFILT_SIGNAL = 0x5
+ EVFILT_SYSCOUNT = 0x7
+ EVFILT_TIMER = 0x6
+ EVFILT_VNODE = 0x3
+ EVFILT_WRITE = 0x1
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG1 = 0x2000
+ EV_ONESHOT = 0x10
+ EV_SYSFLAGS = 0xf000
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x100
+ FLUSHO = 0x800000
+ F_CLOSEM = 0xa
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0xc
+ F_FSCTL = -0x80000000
+ F_FSDIRMASK = 0x70000000
+ F_FSIN = 0x10000000
+ F_FSINOUT = 0x30000000
+ F_FSOUT = 0x20000000
+ F_FSPRIV = 0x8000
+ F_FSVOID = 0x40000000
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETNOSIGPIPE = 0xd
+ F_GETOWN = 0x5
+ F_MAXFD = 0xb
+ F_OK = 0x0
+ F_PARAM_MASK = 0xfff
+ F_PARAM_MAX = 0xfff
+ F_RDLCK = 0x1
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETNOSIGPIPE = 0xe
+ F_SETOWN = 0x6
+ F_UNLCK = 0x2
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFAN_ARRIVAL = 0x0
+ IFAN_DEPARTURE = 0x1
+ IFA_ROUTE = 0x1
+ IFF_ALLMULTI = 0x200
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x8f52
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NOTRAILERS = 0x20
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_A12MPPSWITCH = 0x82
+ IFT_AAL2 = 0xbb
+ IFT_AAL5 = 0x31
+ IFT_ADSL = 0x5e
+ IFT_AFLANE8023 = 0x3b
+ IFT_AFLANE8025 = 0x3c
+ IFT_ARAP = 0x58
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ASYNC = 0x54
+ IFT_ATM = 0x25
+ IFT_ATMDXI = 0x69
+ IFT_ATMFUNI = 0x6a
+ IFT_ATMIMA = 0x6b
+ IFT_ATMLOGICAL = 0x50
+ IFT_ATMRADIO = 0xbd
+ IFT_ATMSUBINTERFACE = 0x86
+ IFT_ATMVCIENDPT = 0xc2
+ IFT_ATMVIRTUAL = 0x95
+ IFT_BGPPOLICYACCOUNTING = 0xa2
+ IFT_BRIDGE = 0xd1
+ IFT_BSC = 0x53
+ IFT_CARP = 0xf8
+ IFT_CCTEMUL = 0x3d
+ IFT_CEPT = 0x13
+ IFT_CES = 0x85
+ IFT_CHANNEL = 0x46
+ IFT_CNR = 0x55
+ IFT_COFFEE = 0x84
+ IFT_COMPOSITELINK = 0x9b
+ IFT_DCN = 0x8d
+ IFT_DIGITALPOWERLINE = 0x8a
+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
+ IFT_DLSW = 0x4a
+ IFT_DOCSCABLEDOWNSTREAM = 0x80
+ IFT_DOCSCABLEMACLAYER = 0x7f
+ IFT_DOCSCABLEUPSTREAM = 0x81
+ IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd
+ IFT_DS0 = 0x51
+ IFT_DS0BUNDLE = 0x52
+ IFT_DS1FDL = 0xaa
+ IFT_DS3 = 0x1e
+ IFT_DTM = 0x8c
+ IFT_DVBASILN = 0xac
+ IFT_DVBASIOUT = 0xad
+ IFT_DVBRCCDOWNSTREAM = 0x93
+ IFT_DVBRCCMACLAYER = 0x92
+ IFT_DVBRCCUPSTREAM = 0x94
+ IFT_ECONET = 0xce
+ IFT_EON = 0x19
+ IFT_EPLRS = 0x57
+ IFT_ESCON = 0x49
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0xf2
+ IFT_FAST = 0x7d
+ IFT_FASTETHER = 0x3e
+ IFT_FASTETHERFX = 0x45
+ IFT_FDDI = 0xf
+ IFT_FIBRECHANNEL = 0x38
+ IFT_FRAMERELAYINTERCONNECT = 0x3a
+ IFT_FRAMERELAYMPI = 0x5c
+ IFT_FRDLCIENDPT = 0xc1
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_FRF16MFRBUNDLE = 0xa3
+ IFT_FRFORWARD = 0x9e
+ IFT_G703AT2MB = 0x43
+ IFT_G703AT64K = 0x42
+ IFT_GIF = 0xf0
+ IFT_GIGABITETHERNET = 0x75
+ IFT_GR303IDT = 0xb2
+ IFT_GR303RDT = 0xb1
+ IFT_H323GATEKEEPER = 0xa4
+ IFT_H323PROXY = 0xa5
+ IFT_HDH1822 = 0x3
+ IFT_HDLC = 0x76
+ IFT_HDSL2 = 0xa8
+ IFT_HIPERLAN2 = 0xb7
+ IFT_HIPPI = 0x2f
+ IFT_HIPPIINTERFACE = 0x39
+ IFT_HOSTPAD = 0x5a
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IBM370PARCHAN = 0x48
+ IFT_IDSL = 0x9a
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE80211 = 0x47
+ IFT_IEEE80212 = 0x37
+ IFT_IEEE8023ADLAG = 0xa1
+ IFT_IFGSN = 0x91
+ IFT_IMT = 0xbe
+ IFT_INFINIBAND = 0xc7
+ IFT_INTERLEAVE = 0x7c
+ IFT_IP = 0x7e
+ IFT_IPFORWARD = 0x8e
+ IFT_IPOVERATM = 0x72
+ IFT_IPOVERCDLC = 0x6d
+ IFT_IPOVERCLAW = 0x6e
+ IFT_IPSWITCH = 0x4e
+ IFT_ISDN = 0x3f
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISDNS = 0x4b
+ IFT_ISDNU = 0x4c
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88025CRFPINT = 0x62
+ IFT_ISO88025DTR = 0x56
+ IFT_ISO88025FIBER = 0x73
+ IFT_ISO88026 = 0xa
+ IFT_ISUP = 0xb3
+ IFT_L2VLAN = 0x87
+ IFT_L3IPVLAN = 0x88
+ IFT_L3IPXVLAN = 0x89
+ IFT_LAPB = 0x10
+ IFT_LAPD = 0x4d
+ IFT_LAPF = 0x77
+ IFT_LINEGROUP = 0xd2
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MEDIAMAILOVERIP = 0x8b
+ IFT_MFSIGLINK = 0xa7
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_MPC = 0x71
+ IFT_MPLS = 0xa6
+ IFT_MPLSTUNNEL = 0x96
+ IFT_MSDSL = 0x8f
+ IFT_MVL = 0xbf
+ IFT_MYRINET = 0x63
+ IFT_NFAS = 0xaf
+ IFT_NSIP = 0x1b
+ IFT_OPTICALCHANNEL = 0xc3
+ IFT_OPTICALTRANSPORT = 0xc4
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PFLOG = 0xf5
+ IFT_PFSYNC = 0xf6
+ IFT_PLC = 0xae
+ IFT_PON155 = 0xcf
+ IFT_PON622 = 0xd0
+ IFT_POS = 0xab
+ IFT_PPP = 0x17
+ IFT_PPPMULTILINKBUNDLE = 0x6c
+ IFT_PROPATM = 0xc5
+ IFT_PROPBWAP2MP = 0xb8
+ IFT_PROPCNLS = 0x59
+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PROPWIRELESSP2P = 0x9d
+ IFT_PTPSERIAL = 0x16
+ IFT_PVC = 0xf1
+ IFT_Q2931 = 0xc9
+ IFT_QLLC = 0x44
+ IFT_RADIOMAC = 0xbc
+ IFT_RADSL = 0x5f
+ IFT_REACHDSL = 0xc0
+ IFT_RFC1483 = 0x9f
+ IFT_RS232 = 0x21
+ IFT_RSRB = 0x4f
+ IFT_SDLC = 0x11
+ IFT_SDSL = 0x60
+ IFT_SHDSL = 0xa9
+ IFT_SIP = 0x1f
+ IFT_SIPSIG = 0xcc
+ IFT_SIPTG = 0xcb
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETOVERHEADCHANNEL = 0xb9
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_SRP = 0x97
+ IFT_SS7SIGLINK = 0x9c
+ IFT_STACKTOSTACK = 0x6f
+ IFT_STARLAN = 0xb
+ IFT_STF = 0xd7
+ IFT_T1 = 0x12
+ IFT_TDLC = 0x74
+ IFT_TELINK = 0xc8
+ IFT_TERMPAD = 0x5b
+ IFT_TR008 = 0xb0
+ IFT_TRANSPHDLC = 0x7b
+ IFT_TUNNEL = 0x83
+ IFT_ULTRA = 0x1d
+ IFT_USB = 0xa0
+ IFT_V11 = 0x40
+ IFT_V35 = 0x2d
+ IFT_V36 = 0x41
+ IFT_V37 = 0x78
+ IFT_VDSL = 0x61
+ IFT_VIRTUALIPADDRESS = 0x70
+ IFT_VIRTUALTG = 0xca
+ IFT_VOICEDID = 0xd5
+ IFT_VOICEEM = 0x64
+ IFT_VOICEEMFGD = 0xd3
+ IFT_VOICEENCAP = 0x67
+ IFT_VOICEFGDEANA = 0xd4
+ IFT_VOICEFXO = 0x65
+ IFT_VOICEFXS = 0x66
+ IFT_VOICEOVERATM = 0x98
+ IFT_VOICEOVERCABLE = 0xc6
+ IFT_VOICEOVERFRAMERELAY = 0x99
+ IFT_VOICEOVERIP = 0x68
+ IFT_X213 = 0x5d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25HUNTGROUP = 0x7a
+ IFT_X25MLP = 0x79
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LOOPBACKNET = 0x7f
+ IPPROTO_AH = 0x33
+ IPPROTO_CARP = 0x70
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_IPV6_ICMP = 0x3a
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x34
+ IPPROTO_MOBILE = 0x37
+ IPPROTO_NONE = 0x3b
+ IPPROTO_PFSYNC = 0xf0
+ IPPROTO_PIM = 0x67
+ IPPROTO_PUP = 0xc
+ IPPROTO_RAW = 0xff
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_TCP = 0x6
+ IPPROTO_TP = 0x1d
+ IPPROTO_UDP = 0x11
+ IPPROTO_VRRP = 0x70
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_DONTFRAG = 0x3e
+ IPV6_DSTOPTS = 0x32
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x78
+ IPV6_HLIMDEC = 0x1
+ IPV6_HOPLIMIT = 0x2f
+ IPV6_HOPOPTS = 0x31
+ IPV6_IPSEC_POLICY = 0x1c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MMTU = 0x500
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_NEXTHOP = 0x30
+ IPV6_PATHMTU = 0x2c
+ IPV6_PKTINFO = 0x2e
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVHOPLIMIT = 0x25
+ IPV6_RECVHOPOPTS = 0x27
+ IPV6_RECVPATHMTU = 0x2b
+ IPV6_RECVPKTINFO = 0x24
+ IPV6_RECVRTHDR = 0x26
+ IPV6_RECVTCLASS = 0x39
+ IPV6_RTHDR = 0x33
+ IPV6_RTHDRDSTOPTS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x3d
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_USE_MIN_MTU = 0x2a
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_EF = 0x8000
+ IP_ERRORMTU = 0x15
+ IP_HDRINCL = 0x2
+ IP_IPSEC_POLICY = 0x16
+ IP_MAXPACKET = 0xffff
+ IP_MAX_MEMBERSHIPS = 0x14
+ IP_MF = 0x2000
+ IP_MINFRAGSIZE = 0x45
+ IP_MINTTL = 0x18
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_OFFMASK = 0x1fff
+ IP_OPTIONS = 0x1
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVIF = 0x14
+ IP_RECVOPTS = 0x5
+ IP_RECVRETOPTS = 0x6
+ IP_RECVTTL = 0x17
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x6
+ MADV_NORMAL = 0x0
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_SPACEAVAIL = 0x5
+ MADV_WILLNEED = 0x3
+ MAP_ALIGNMENT_16MB = 0x18000000
+ MAP_ALIGNMENT_1TB = 0x28000000
+ MAP_ALIGNMENT_256TB = 0x30000000
+ MAP_ALIGNMENT_4GB = 0x20000000
+ MAP_ALIGNMENT_64KB = 0x10000000
+ MAP_ALIGNMENT_64PB = 0x38000000
+ MAP_ALIGNMENT_MASK = -0x1000000
+ MAP_ALIGNMENT_SHIFT = 0x18
+ MAP_ANON = 0x1000
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_HASSEMAPHORE = 0x200
+ MAP_INHERIT = 0x80
+ MAP_INHERIT_COPY = 0x1
+ MAP_INHERIT_DEFAULT = 0x1
+ MAP_INHERIT_DONATE_COPY = 0x3
+ MAP_INHERIT_NONE = 0x2
+ MAP_INHERIT_SHARE = 0x0
+ MAP_NORESERVE = 0x40
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_SHARED = 0x1
+ MAP_STACK = 0x2000
+ MAP_TRYFIXED = 0x400
+ MAP_WIRED = 0x800
+ MSG_BCAST = 0x100
+ MSG_CMSG_CLOEXEC = 0x800
+ MSG_CONTROLMBUF = 0x2000000
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOR = 0x8
+ MSG_IOVUSRSPACE = 0x4000000
+ MSG_LENUSRSPACE = 0x8000000
+ MSG_MCAST = 0x200
+ MSG_NAMEMBUF = 0x1000000
+ MSG_NBIO = 0x1000
+ MSG_NOSIGNAL = 0x400
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x10
+ MSG_USERFLAGS = 0xffffff
+ MSG_WAITALL = 0x40
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x2
+ MS_SYNC = 0x4
+ NAME_MAX = 0x1ff
+ NET_RT_DUMP = 0x1
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x5
+ NET_RT_MAXID = 0x6
+ NET_RT_OIFLIST = 0x4
+ NET_RT_OOIFLIST = 0x3
+ NOFLSH = 0x80000000
+ NOTE_ATTRIB = 0x8
+ NOTE_CHILD = 0x4
+ NOTE_DELETE = 0x1
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXTEND = 0x4
+ NOTE_FORK = 0x40000000
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_PCTRLMASK = 0xf0000000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ OFIOGETBMAP = 0xc004667a
+ ONLCR = 0x2
+ ONLRET = 0x40
+ ONOCR = 0x20
+ ONOEOT = 0x8
+ OPOST = 0x1
+ O_ACCMODE = 0x3
+ O_ALT_IO = 0x40000
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x400000
+ O_CREAT = 0x200
+ O_DIRECT = 0x80000
+ O_DIRECTORY = 0x200000
+ O_DSYNC = 0x10000
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_NOSIGPIPE = 0x1000000
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x20000
+ O_SHLOCK = 0x10
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ PRI_IOFLUSH = 0x7c
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ RLIMIT_AS = 0xa
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x9
+ RTAX_NETMASK = 0x2
+ RTAX_TAG = 0x8
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTA_TAG = 0x100
+ RTF_ANNOUNCE = 0x20000
+ RTF_BLACKHOLE = 0x1000
+ RTF_CLONED = 0x2000
+ RTF_CLONING = 0x100
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_LLINFO = 0x400
+ RTF_MASK = 0x80
+ RTF_MODIFIED = 0x20
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_REJECT = 0x8
+ RTF_SRC = 0x10000
+ RTF_STATIC = 0x800
+ RTF_UP = 0x1
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_CHGADDR = 0x15
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_GET = 0x4
+ RTM_IEEE80211 = 0x11
+ RTM_IFANNOUNCE = 0x10
+ RTM_IFINFO = 0x14
+ RTM_LLINFO_UPD = 0x13
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_OIFINFO = 0xf
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ RTM_OOIFINFO = 0xe
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_SETGATE = 0x12
+ RTM_VERSION = 0x4
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ SCM_CREDS = 0x4
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x8
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80906931
+ SIOCADDRT = 0x8030720a
+ SIOCAIFADDR = 0x8040691a
+ SIOCALIFADDR = 0x8118691c
+ SIOCATMARK = 0x40047307
+ SIOCDELMULTI = 0x80906932
+ SIOCDELRT = 0x8030720b
+ SIOCDIFADDR = 0x80906919
+ SIOCDIFPHYADDR = 0x80906949
+ SIOCDLIFADDR = 0x8118691e
+ SIOCGDRVSPEC = 0xc01c697b
+ SIOCGETPFSYNC = 0xc09069f8
+ SIOCGETSGCNT = 0xc0147534
+ SIOCGETVIFCNT = 0xc0147533
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0906921
+ SIOCGIFADDRPREF = 0xc0946920
+ SIOCGIFALIAS = 0xc040691b
+ SIOCGIFBRDADDR = 0xc0906923
+ SIOCGIFCAP = 0xc0206976
+ SIOCGIFCONF = 0xc0086926
+ SIOCGIFDATA = 0xc0946985
+ SIOCGIFDLT = 0xc0906977
+ SIOCGIFDSTADDR = 0xc0906922
+ SIOCGIFFLAGS = 0xc0906911
+ SIOCGIFGENERIC = 0xc090693a
+ SIOCGIFMEDIA = 0xc0286936
+ SIOCGIFMETRIC = 0xc0906917
+ SIOCGIFMTU = 0xc090697e
+ SIOCGIFNETMASK = 0xc0906925
+ SIOCGIFPDSTADDR = 0xc0906948
+ SIOCGIFPSRCADDR = 0xc0906947
+ SIOCGLIFADDR = 0xc118691d
+ SIOCGLIFPHYADDR = 0xc118694b
+ SIOCGLINKSTR = 0xc01c6987
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCGVH = 0xc0906983
+ SIOCIFCREATE = 0x8090697a
+ SIOCIFDESTROY = 0x80906979
+ SIOCIFGCLONERS = 0xc00c6978
+ SIOCINITIFADDR = 0xc0446984
+ SIOCSDRVSPEC = 0x801c697b
+ SIOCSETPFSYNC = 0x809069f7
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8090690c
+ SIOCSIFADDRPREF = 0x8094691f
+ SIOCSIFBRDADDR = 0x80906913
+ SIOCSIFCAP = 0x80206975
+ SIOCSIFDSTADDR = 0x8090690e
+ SIOCSIFFLAGS = 0x80906910
+ SIOCSIFGENERIC = 0x80906939
+ SIOCSIFMEDIA = 0xc0906935
+ SIOCSIFMETRIC = 0x80906918
+ SIOCSIFMTU = 0x8090697f
+ SIOCSIFNETMASK = 0x80906916
+ SIOCSIFPHYADDR = 0x80406946
+ SIOCSLIFPHYADDR = 0x8118694a
+ SIOCSLINKSTR = 0x801c6988
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SIOCSVH = 0xc0906982
+ SIOCZIFDATA = 0xc0946986
+ SOCK_CLOEXEC = 0x10000000
+ SOCK_DGRAM = 0x2
+ SOCK_FLAGS_MASK = 0xf0000000
+ SOCK_NONBLOCK = 0x20000000
+ SOCK_NOSIGPIPE = 0x40000000
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_ACCEPTFILTER = 0x1000
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LINGER = 0x80
+ SO_NOHEADER = 0x100a
+ SO_NOSIGPIPE = 0x800
+ SO_OOBINLINE = 0x100
+ SO_OVERFLOWED = 0x1009
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x100c
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x100b
+ SO_TIMESTAMP = 0x2000
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ SYSCTL_VERSION = 0x1000000
+ SYSCTL_VERS_0 = 0x0
+ SYSCTL_VERS_1 = 0x1000000
+ SYSCTL_VERS_MASK = 0xff000000
+ S_ARCH1 = 0x10000
+ S_ARCH2 = 0x20000
+ 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_IFWHT = 0xe000
+ 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_ISTXT = 0x200
+ 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
+ TCIFLUSH = 0x1
+ TCIOFLUSH = 0x3
+ TCOFLUSH = 0x2
+ TCP_CONGCTL = 0x20
+ TCP_KEEPCNT = 0x6
+ TCP_KEEPIDLE = 0x3
+ TCP_KEEPINIT = 0x7
+ TCP_KEEPINTVL = 0x5
+ TCP_MAXBURST = 0x4
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MD5SIG = 0x10
+ TCP_MINMSS = 0xd8
+ TCP_MSS = 0x218
+ TCP_NODELAY = 0x1
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDCDTIMESTAMP = 0x400c7458
+ TIOCDRAIN = 0x2000745e
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLAG_CDTRCTS = 0x10
+ TIOCFLAG_CLOCAL = 0x2
+ TIOCFLAG_CRTSCTS = 0x4
+ TIOCFLAG_MDMBUF = 0x8
+ TIOCFLAG_SOFTCAR = 0x1
+ TIOCFLUSH = 0x80047410
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGFLAGS = 0x4004745d
+ TIOCGLINED = 0x40207442
+ TIOCGPGRP = 0x40047477
+ TIOCGQSIZE = 0x40047481
+ TIOCGRANTPT = 0x20007447
+ TIOCGSID = 0x40047463
+ TIOCGSIZE = 0x40087468
+ TIOCGWINSZ = 0x40087468
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGET = 0x4004746a
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCPTMGET = 0x48087446
+ TIOCPTSNAME = 0x48087448
+ TIOCRCVFRAME = 0x80047445
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCTTY = 0x20007461
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSFLAGS = 0x8004745c
+ TIOCSIG = 0x2000745f
+ TIOCSLINED = 0x80207443
+ TIOCSPGRP = 0x80047476
+ TIOCSQSIZE = 0x80047480
+ TIOCSSIZE = 0x80087467
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x80047465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSWINSZ = 0x80087467
+ TIOCUCNTL = 0x80047466
+ TIOCXMTFRAME = 0x80047444
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VTIME = 0x11
+ VWERASE = 0x4
+ WALL = 0x8
+ WALLSIG = 0x8
+ WALTSIG = 0x4
+ WCLONE = 0x4
+ WCOREFLAG = 0x80
+ WNOHANG = 0x1
+ WNOWAIT = 0x10000
+ WNOZOMBIE = 0x20000
+ WOPTSCHECKED = 0x40000
+ WSTOPPED = 0x7f
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADF = syscall.Errno(0x9)
+ EBADMSG = syscall.Errno(0x58)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x57)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x52)
+ EILSEQ = syscall.Errno(0x55)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x60)
+ ELOOP = syscall.Errno(0x3e)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ EMULTIHOP = syscall.Errno(0x5e)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x5d)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODATA = syscall.Errno(0x59)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOLINK = syscall.Errno(0x5f)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x53)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSR = syscall.Errno(0x5a)
+ ENOSTR = syscall.Errno(0x5b)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x56)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x54)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTO = syscall.Errno(0x60)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIME = syscall.Errno(0x5c)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGPWR = syscall.Signal(0x20)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large or too small",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol option not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "connection timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "identifier removed",
+ 83: "no message of desired type",
+ 84: "value too large to be stored in data type",
+ 85: "illegal byte sequence",
+ 86: "not supported",
+ 87: "operation Canceled",
+ 88: "bad or Corrupt message",
+ 89: "no message available",
+ 90: "no STREAM resources",
+ 91: "not a STREAM",
+ 92: "STREAM ioctl timeout",
+ 93: "attribute not found",
+ 94: "multihop attempted",
+ 95: "link has been severed",
+ 96: "protocol error",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "stopped (signal)",
+ 18: "stopped",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+ 32: "power fail/restart",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go b/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go
new file mode 100644
index 0000000..3322e99
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go
@@ -0,0 +1,1584 @@
+// mkerrors.sh -m32
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+// +build 386,openbsd
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m32 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_BLUETOOTH = 0x20
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1a
+ AF_ECMA = 0x8
+ AF_ENCAP = 0x1c
+ AF_HYLINK = 0xf
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x18
+ AF_IPX = 0x17
+ AF_ISDN = 0x1a
+ AF_ISO = 0x7
+ AF_KEY = 0x1e
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x24
+ AF_MPLS = 0x21
+ AF_NATM = 0x1b
+ AF_NS = 0x6
+ AF_OSI = 0x7
+ AF_PUP = 0x4
+ AF_ROUTE = 0x11
+ AF_SIP = 0x1d
+ AF_SNA = 0xb
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ ARPHRD_ETHER = 0x1
+ ARPHRD_FRELAY = 0xf
+ ARPHRD_IEEE1394 = 0x18
+ ARPHRD_IEEE802 = 0x6
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B9600 = 0x2580
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDIRFILT = 0x4004427c
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc008427b
+ BIOCGETIF = 0x4020426b
+ BIOCGFILDROP = 0x40044278
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044273
+ BIOCGRTIMEOUT = 0x400c426e
+ BIOCGSTATS = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCLOCK = 0x20004276
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDIRFILT = 0x8004427d
+ BIOCSDLT = 0x8004427a
+ BIOCSETF = 0x80084267
+ BIOCSETIF = 0x8020426c
+ BIOCSETWF = 0x80084277
+ BIOCSFILDROP = 0x80044279
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044272
+ BIOCSRTIMEOUT = 0x800c426d
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_DIRECTION_IN = 0x1
+ BPF_DIRECTION_OUT = 0x2
+ 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_MAXBUFSIZE = 0x200000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CREAD = 0x800
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0xff
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ DIOCOSFPFLUSH = 0x2000444e
+ DLT_ARCNET = 0x7
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AX25 = 0x3
+ DLT_CHAOS = 0x5
+ DLT_C_HDLC = 0x68
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0xd
+ DLT_FDDI = 0xa
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_LOOP = 0xc
+ DLT_MPLS = 0xdb
+ DLT_NULL = 0x0
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0x10
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_SERIAL = 0x32
+ DLT_PRONET = 0x4
+ DLT_RAW = 0xe
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xf
+ DT_BLK = 0x6
+ DT_CHR = 0x2
+ DT_DIR = 0x4
+ DT_FIFO = 0x1
+ DT_LNK = 0xa
+ DT_REG = 0x8
+ DT_SOCK = 0xc
+ DT_UNKNOWN = 0x0
+ ECHO = 0x8
+ ECHOCTL = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EMT_TAGOVF = 0x1
+ EMUL_ENABLED = 0x1
+ EMUL_NATIVE = 0x2
+ ENDRUNDISC = 0x9
+ ETHERMIN = 0x2e
+ ETHERMTU = 0x5dc
+ ETHERTYPE_8023 = 0x4
+ ETHERTYPE_AARP = 0x80f3
+ ETHERTYPE_ACCTON = 0x8390
+ ETHERTYPE_AEONIC = 0x8036
+ ETHERTYPE_ALPHA = 0x814a
+ ETHERTYPE_AMBER = 0x6008
+ ETHERTYPE_AMOEBA = 0x8145
+ ETHERTYPE_AOE = 0x88a2
+ ETHERTYPE_APOLLO = 0x80f7
+ ETHERTYPE_APOLLODOMAIN = 0x8019
+ ETHERTYPE_APPLETALK = 0x809b
+ ETHERTYPE_APPLITEK = 0x80c7
+ ETHERTYPE_ARGONAUT = 0x803a
+ ETHERTYPE_ARP = 0x806
+ ETHERTYPE_AT = 0x809b
+ ETHERTYPE_ATALK = 0x809b
+ ETHERTYPE_ATOMIC = 0x86df
+ ETHERTYPE_ATT = 0x8069
+ ETHERTYPE_ATTSTANFORD = 0x8008
+ ETHERTYPE_AUTOPHON = 0x806a
+ ETHERTYPE_AXIS = 0x8856
+ ETHERTYPE_BCLOOP = 0x9003
+ ETHERTYPE_BOFL = 0x8102
+ ETHERTYPE_CABLETRON = 0x7034
+ ETHERTYPE_CHAOS = 0x804
+ ETHERTYPE_COMDESIGN = 0x806c
+ ETHERTYPE_COMPUGRAPHIC = 0x806d
+ ETHERTYPE_COUNTERPOINT = 0x8062
+ ETHERTYPE_CRONUS = 0x8004
+ ETHERTYPE_CRONUSVLN = 0x8003
+ ETHERTYPE_DCA = 0x1234
+ ETHERTYPE_DDE = 0x807b
+ ETHERTYPE_DEBNI = 0xaaaa
+ ETHERTYPE_DECAM = 0x8048
+ ETHERTYPE_DECCUST = 0x6006
+ ETHERTYPE_DECDIAG = 0x6005
+ ETHERTYPE_DECDNS = 0x803c
+ ETHERTYPE_DECDTS = 0x803e
+ ETHERTYPE_DECEXPER = 0x6000
+ ETHERTYPE_DECLAST = 0x8041
+ ETHERTYPE_DECLTM = 0x803f
+ ETHERTYPE_DECMUMPS = 0x6009
+ ETHERTYPE_DECNETBIOS = 0x8040
+ ETHERTYPE_DELTACON = 0x86de
+ ETHERTYPE_DIDDLE = 0x4321
+ ETHERTYPE_DLOG1 = 0x660
+ ETHERTYPE_DLOG2 = 0x661
+ ETHERTYPE_DN = 0x6003
+ ETHERTYPE_DOGFIGHT = 0x1989
+ ETHERTYPE_DSMD = 0x8039
+ ETHERTYPE_ECMA = 0x803
+ ETHERTYPE_ENCRYPT = 0x803d
+ ETHERTYPE_ES = 0x805d
+ ETHERTYPE_EXCELAN = 0x8010
+ ETHERTYPE_EXPERDATA = 0x8049
+ ETHERTYPE_FLIP = 0x8146
+ ETHERTYPE_FLOWCONTROL = 0x8808
+ ETHERTYPE_FRARP = 0x808
+ ETHERTYPE_GENDYN = 0x8068
+ ETHERTYPE_HAYES = 0x8130
+ ETHERTYPE_HIPPI_FP = 0x8180
+ ETHERTYPE_HITACHI = 0x8820
+ ETHERTYPE_HP = 0x8005
+ ETHERTYPE_IEEEPUP = 0xa00
+ ETHERTYPE_IEEEPUPAT = 0xa01
+ ETHERTYPE_IMLBL = 0x4c42
+ ETHERTYPE_IMLBLDIAG = 0x424c
+ ETHERTYPE_IP = 0x800
+ ETHERTYPE_IPAS = 0x876c
+ ETHERTYPE_IPV6 = 0x86dd
+ ETHERTYPE_IPX = 0x8137
+ ETHERTYPE_IPXNEW = 0x8037
+ ETHERTYPE_KALPANA = 0x8582
+ ETHERTYPE_LANBRIDGE = 0x8038
+ ETHERTYPE_LANPROBE = 0x8888
+ ETHERTYPE_LAT = 0x6004
+ ETHERTYPE_LBACK = 0x9000
+ ETHERTYPE_LITTLE = 0x8060
+ ETHERTYPE_LLDP = 0x88cc
+ ETHERTYPE_LOGICRAFT = 0x8148
+ ETHERTYPE_LOOPBACK = 0x9000
+ ETHERTYPE_MATRA = 0x807a
+ ETHERTYPE_MAX = 0xffff
+ ETHERTYPE_MERIT = 0x807c
+ ETHERTYPE_MICP = 0x873a
+ ETHERTYPE_MOPDL = 0x6001
+ ETHERTYPE_MOPRC = 0x6002
+ ETHERTYPE_MOTOROLA = 0x818d
+ ETHERTYPE_MPLS = 0x8847
+ ETHERTYPE_MPLS_MCAST = 0x8848
+ ETHERTYPE_MUMPS = 0x813f
+ ETHERTYPE_NBPCC = 0x3c04
+ ETHERTYPE_NBPCLAIM = 0x3c09
+ ETHERTYPE_NBPCLREQ = 0x3c05
+ ETHERTYPE_NBPCLRSP = 0x3c06
+ ETHERTYPE_NBPCREQ = 0x3c02
+ ETHERTYPE_NBPCRSP = 0x3c03
+ ETHERTYPE_NBPDG = 0x3c07
+ ETHERTYPE_NBPDGB = 0x3c08
+ ETHERTYPE_NBPDLTE = 0x3c0a
+ ETHERTYPE_NBPRAR = 0x3c0c
+ ETHERTYPE_NBPRAS = 0x3c0b
+ ETHERTYPE_NBPRST = 0x3c0d
+ ETHERTYPE_NBPSCD = 0x3c01
+ ETHERTYPE_NBPVCD = 0x3c00
+ ETHERTYPE_NBS = 0x802
+ ETHERTYPE_NCD = 0x8149
+ ETHERTYPE_NESTAR = 0x8006
+ ETHERTYPE_NETBEUI = 0x8191
+ ETHERTYPE_NOVELL = 0x8138
+ ETHERTYPE_NS = 0x600
+ ETHERTYPE_NSAT = 0x601
+ ETHERTYPE_NSCOMPAT = 0x807
+ ETHERTYPE_NTRAILER = 0x10
+ ETHERTYPE_OS9 = 0x7007
+ ETHERTYPE_OS9NET = 0x7009
+ ETHERTYPE_PACER = 0x80c6
+ ETHERTYPE_PAE = 0x888e
+ ETHERTYPE_PCS = 0x4242
+ ETHERTYPE_PLANNING = 0x8044
+ ETHERTYPE_PPP = 0x880b
+ ETHERTYPE_PPPOE = 0x8864
+ ETHERTYPE_PPPOEDISC = 0x8863
+ ETHERTYPE_PRIMENTS = 0x7031
+ ETHERTYPE_PUP = 0x200
+ ETHERTYPE_PUPAT = 0x200
+ ETHERTYPE_QINQ = 0x88a8
+ ETHERTYPE_RACAL = 0x7030
+ ETHERTYPE_RATIONAL = 0x8150
+ ETHERTYPE_RAWFR = 0x6559
+ ETHERTYPE_RCL = 0x1995
+ ETHERTYPE_RDP = 0x8739
+ ETHERTYPE_RETIX = 0x80f2
+ ETHERTYPE_REVARP = 0x8035
+ ETHERTYPE_SCA = 0x6007
+ ETHERTYPE_SECTRA = 0x86db
+ ETHERTYPE_SECUREDATA = 0x876d
+ ETHERTYPE_SGITW = 0x817e
+ ETHERTYPE_SG_BOUNCE = 0x8016
+ ETHERTYPE_SG_DIAG = 0x8013
+ ETHERTYPE_SG_NETGAMES = 0x8014
+ ETHERTYPE_SG_RESV = 0x8015
+ ETHERTYPE_SIMNET = 0x5208
+ ETHERTYPE_SLOW = 0x8809
+ ETHERTYPE_SNA = 0x80d5
+ ETHERTYPE_SNMP = 0x814c
+ ETHERTYPE_SONIX = 0xfaf5
+ ETHERTYPE_SPIDER = 0x809f
+ ETHERTYPE_SPRITE = 0x500
+ ETHERTYPE_STP = 0x8181
+ ETHERTYPE_TALARIS = 0x812b
+ ETHERTYPE_TALARISMC = 0x852b
+ ETHERTYPE_TCPCOMP = 0x876b
+ ETHERTYPE_TCPSM = 0x9002
+ ETHERTYPE_TEC = 0x814f
+ ETHERTYPE_TIGAN = 0x802f
+ ETHERTYPE_TRAIL = 0x1000
+ ETHERTYPE_TRANSETHER = 0x6558
+ ETHERTYPE_TYMSHARE = 0x802e
+ ETHERTYPE_UBBST = 0x7005
+ ETHERTYPE_UBDEBUG = 0x900
+ ETHERTYPE_UBDIAGLOOP = 0x7002
+ ETHERTYPE_UBDL = 0x7000
+ ETHERTYPE_UBNIU = 0x7001
+ ETHERTYPE_UBNMC = 0x7003
+ ETHERTYPE_VALID = 0x1600
+ ETHERTYPE_VARIAN = 0x80dd
+ ETHERTYPE_VAXELN = 0x803b
+ ETHERTYPE_VEECO = 0x8067
+ ETHERTYPE_VEXP = 0x805b
+ ETHERTYPE_VGLAB = 0x8131
+ ETHERTYPE_VINES = 0xbad
+ ETHERTYPE_VINESECHO = 0xbaf
+ ETHERTYPE_VINESLOOP = 0xbae
+ ETHERTYPE_VITAL = 0xff00
+ ETHERTYPE_VLAN = 0x8100
+ ETHERTYPE_VLTLMAN = 0x8080
+ ETHERTYPE_VPROD = 0x805c
+ ETHERTYPE_VURESERVED = 0x8147
+ ETHERTYPE_WATERLOO = 0x8130
+ ETHERTYPE_WELLFLEET = 0x8103
+ ETHERTYPE_X25 = 0x805
+ ETHERTYPE_X75 = 0x801
+ ETHERTYPE_XNSSM = 0x9001
+ ETHERTYPE_XTP = 0x817d
+ ETHER_ADDR_LEN = 0x6
+ ETHER_ALIGN = 0x2
+ ETHER_CRC_LEN = 0x4
+ ETHER_CRC_POLY_BE = 0x4c11db6
+ ETHER_CRC_POLY_LE = 0xedb88320
+ ETHER_HDR_LEN = 0xe
+ ETHER_MAX_DIX_LEN = 0x600
+ ETHER_MAX_LEN = 0x5ee
+ ETHER_MIN_LEN = 0x40
+ ETHER_TYPE_LEN = 0x2
+ ETHER_VLAN_ENCAP_LEN = 0x4
+ EVFILT_AIO = -0x3
+ EVFILT_PROC = -0x5
+ EVFILT_READ = -0x1
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0x7
+ EVFILT_TIMER = -0x7
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG1 = 0x2000
+ EV_ONESHOT = 0x10
+ EV_SYSFLAGS = 0xf000
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FLUSHO = 0x800000
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0xa
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETOWN = 0x5
+ F_OK = 0x0
+ F_RDLCK = 0x1
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETOWN = 0x6
+ F_UNLCK = 0x2
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFAN_ARRIVAL = 0x0
+ IFAN_DEPARTURE = 0x1
+ IFA_ROUTE = 0x1
+ IFF_ALLMULTI = 0x200
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x8e52
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NOTRAILERS = 0x20
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_A12MPPSWITCH = 0x82
+ IFT_AAL2 = 0xbb
+ IFT_AAL5 = 0x31
+ IFT_ADSL = 0x5e
+ IFT_AFLANE8023 = 0x3b
+ IFT_AFLANE8025 = 0x3c
+ IFT_ARAP = 0x58
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ASYNC = 0x54
+ IFT_ATM = 0x25
+ IFT_ATMDXI = 0x69
+ IFT_ATMFUNI = 0x6a
+ IFT_ATMIMA = 0x6b
+ IFT_ATMLOGICAL = 0x50
+ IFT_ATMRADIO = 0xbd
+ IFT_ATMSUBINTERFACE = 0x86
+ IFT_ATMVCIENDPT = 0xc2
+ IFT_ATMVIRTUAL = 0x95
+ IFT_BGPPOLICYACCOUNTING = 0xa2
+ IFT_BLUETOOTH = 0xf8
+ IFT_BRIDGE = 0xd1
+ IFT_BSC = 0x53
+ IFT_CARP = 0xf7
+ IFT_CCTEMUL = 0x3d
+ IFT_CEPT = 0x13
+ IFT_CES = 0x85
+ IFT_CHANNEL = 0x46
+ IFT_CNR = 0x55
+ IFT_COFFEE = 0x84
+ IFT_COMPOSITELINK = 0x9b
+ IFT_DCN = 0x8d
+ IFT_DIGITALPOWERLINE = 0x8a
+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
+ IFT_DLSW = 0x4a
+ IFT_DOCSCABLEDOWNSTREAM = 0x80
+ IFT_DOCSCABLEMACLAYER = 0x7f
+ IFT_DOCSCABLEUPSTREAM = 0x81
+ IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd
+ IFT_DS0 = 0x51
+ IFT_DS0BUNDLE = 0x52
+ IFT_DS1FDL = 0xaa
+ IFT_DS3 = 0x1e
+ IFT_DTM = 0x8c
+ IFT_DUMMY = 0xf1
+ IFT_DVBASILN = 0xac
+ IFT_DVBASIOUT = 0xad
+ IFT_DVBRCCDOWNSTREAM = 0x93
+ IFT_DVBRCCMACLAYER = 0x92
+ IFT_DVBRCCUPSTREAM = 0x94
+ IFT_ECONET = 0xce
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_EPLRS = 0x57
+ IFT_ESCON = 0x49
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0xf3
+ IFT_FAST = 0x7d
+ IFT_FASTETHER = 0x3e
+ IFT_FASTETHERFX = 0x45
+ IFT_FDDI = 0xf
+ IFT_FIBRECHANNEL = 0x38
+ IFT_FRAMERELAYINTERCONNECT = 0x3a
+ IFT_FRAMERELAYMPI = 0x5c
+ IFT_FRDLCIENDPT = 0xc1
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_FRF16MFRBUNDLE = 0xa3
+ IFT_FRFORWARD = 0x9e
+ IFT_G703AT2MB = 0x43
+ IFT_G703AT64K = 0x42
+ IFT_GIF = 0xf0
+ IFT_GIGABITETHERNET = 0x75
+ IFT_GR303IDT = 0xb2
+ IFT_GR303RDT = 0xb1
+ IFT_H323GATEKEEPER = 0xa4
+ IFT_H323PROXY = 0xa5
+ IFT_HDH1822 = 0x3
+ IFT_HDLC = 0x76
+ IFT_HDSL2 = 0xa8
+ IFT_HIPERLAN2 = 0xb7
+ IFT_HIPPI = 0x2f
+ IFT_HIPPIINTERFACE = 0x39
+ IFT_HOSTPAD = 0x5a
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IBM370PARCHAN = 0x48
+ IFT_IDSL = 0x9a
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE80211 = 0x47
+ IFT_IEEE80212 = 0x37
+ IFT_IEEE8023ADLAG = 0xa1
+ IFT_IFGSN = 0x91
+ IFT_IMT = 0xbe
+ IFT_INFINIBAND = 0xc7
+ IFT_INTERLEAVE = 0x7c
+ IFT_IP = 0x7e
+ IFT_IPFORWARD = 0x8e
+ IFT_IPOVERATM = 0x72
+ IFT_IPOVERCDLC = 0x6d
+ IFT_IPOVERCLAW = 0x6e
+ IFT_IPSWITCH = 0x4e
+ IFT_ISDN = 0x3f
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISDNS = 0x4b
+ IFT_ISDNU = 0x4c
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88025CRFPINT = 0x62
+ IFT_ISO88025DTR = 0x56
+ IFT_ISO88025FIBER = 0x73
+ IFT_ISO88026 = 0xa
+ IFT_ISUP = 0xb3
+ IFT_L2VLAN = 0x87
+ IFT_L3IPVLAN = 0x88
+ IFT_L3IPXVLAN = 0x89
+ IFT_LAPB = 0x10
+ IFT_LAPD = 0x4d
+ IFT_LAPF = 0x77
+ IFT_LINEGROUP = 0xd2
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MEDIAMAILOVERIP = 0x8b
+ IFT_MFSIGLINK = 0xa7
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_MPC = 0x71
+ IFT_MPLS = 0xa6
+ IFT_MPLSTUNNEL = 0x96
+ IFT_MSDSL = 0x8f
+ IFT_MVL = 0xbf
+ IFT_MYRINET = 0x63
+ IFT_NFAS = 0xaf
+ IFT_NSIP = 0x1b
+ IFT_OPTICALCHANNEL = 0xc3
+ IFT_OPTICALTRANSPORT = 0xc4
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PFLOG = 0xf5
+ IFT_PFLOW = 0xf9
+ IFT_PFSYNC = 0xf6
+ IFT_PLC = 0xae
+ IFT_PON155 = 0xcf
+ IFT_PON622 = 0xd0
+ IFT_POS = 0xab
+ IFT_PPP = 0x17
+ IFT_PPPMULTILINKBUNDLE = 0x6c
+ IFT_PROPATM = 0xc5
+ IFT_PROPBWAP2MP = 0xb8
+ IFT_PROPCNLS = 0x59
+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PROPWIRELESSP2P = 0x9d
+ IFT_PTPSERIAL = 0x16
+ IFT_PVC = 0xf2
+ IFT_Q2931 = 0xc9
+ IFT_QLLC = 0x44
+ IFT_RADIOMAC = 0xbc
+ IFT_RADSL = 0x5f
+ IFT_REACHDSL = 0xc0
+ IFT_RFC1483 = 0x9f
+ IFT_RS232 = 0x21
+ IFT_RSRB = 0x4f
+ IFT_SDLC = 0x11
+ IFT_SDSL = 0x60
+ IFT_SHDSL = 0xa9
+ IFT_SIP = 0x1f
+ IFT_SIPSIG = 0xcc
+ IFT_SIPTG = 0xcb
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETOVERHEADCHANNEL = 0xb9
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_SRP = 0x97
+ IFT_SS7SIGLINK = 0x9c
+ IFT_STACKTOSTACK = 0x6f
+ IFT_STARLAN = 0xb
+ IFT_T1 = 0x12
+ IFT_TDLC = 0x74
+ IFT_TELINK = 0xc8
+ IFT_TERMPAD = 0x5b
+ IFT_TR008 = 0xb0
+ IFT_TRANSPHDLC = 0x7b
+ IFT_TUNNEL = 0x83
+ IFT_ULTRA = 0x1d
+ IFT_USB = 0xa0
+ IFT_V11 = 0x40
+ IFT_V35 = 0x2d
+ IFT_V36 = 0x41
+ IFT_V37 = 0x78
+ IFT_VDSL = 0x61
+ IFT_VIRTUALIPADDRESS = 0x70
+ IFT_VIRTUALTG = 0xca
+ IFT_VOICEDID = 0xd5
+ IFT_VOICEEM = 0x64
+ IFT_VOICEEMFGD = 0xd3
+ IFT_VOICEENCAP = 0x67
+ IFT_VOICEFGDEANA = 0xd4
+ IFT_VOICEFXO = 0x65
+ IFT_VOICEFXS = 0x66
+ IFT_VOICEOVERATM = 0x98
+ IFT_VOICEOVERCABLE = 0xc6
+ IFT_VOICEOVERFRAMERELAY = 0x99
+ IFT_VOICEOVERIP = 0x68
+ IFT_X213 = 0x5d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25HUNTGROUP = 0x7a
+ IFT_X25MLP = 0x79
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LOOPBACKNET = 0x7f
+ IN_RFC3021_HOST = 0x1
+ IN_RFC3021_NET = 0xfffffffe
+ IN_RFC3021_NSHIFT = 0x1f
+ IPPROTO_AH = 0x33
+ IPPROTO_CARP = 0x70
+ IPPROTO_DIVERT = 0x102
+ IPPROTO_DIVERT_INIT = 0x2
+ IPPROTO_DIVERT_RESP = 0x1
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x103
+ IPPROTO_MOBILE = 0x37
+ IPPROTO_MPLS = 0x89
+ IPPROTO_NONE = 0x3b
+ IPPROTO_PFSYNC = 0xf0
+ IPPROTO_PIM = 0x67
+ IPPROTO_PUP = 0xc
+ IPPROTO_RAW = 0xff
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_TCP = 0x6
+ IPPROTO_TP = 0x1d
+ IPPROTO_UDP = 0x11
+ IPV6_AUTH_LEVEL = 0x35
+ IPV6_AUTOFLOWLABEL = 0x3b
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_DONTFRAG = 0x3e
+ IPV6_DSTOPTS = 0x32
+ IPV6_ESP_NETWORK_LEVEL = 0x37
+ IPV6_ESP_TRANS_LEVEL = 0x36
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x78
+ IPV6_HLIMDEC = 0x1
+ IPV6_HOPLIMIT = 0x2f
+ IPV6_HOPOPTS = 0x31
+ IPV6_IPCOMP_LEVEL = 0x3c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MMTU = 0x500
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_NEXTHOP = 0x30
+ IPV6_OPTIONS = 0x1
+ IPV6_PATHMTU = 0x2c
+ IPV6_PIPEX = 0x3f
+ IPV6_PKTINFO = 0x2e
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVDSTPORT = 0x40
+ IPV6_RECVHOPLIMIT = 0x25
+ IPV6_RECVHOPOPTS = 0x27
+ IPV6_RECVPATHMTU = 0x2b
+ IPV6_RECVPKTINFO = 0x24
+ IPV6_RECVRTHDR = 0x26
+ IPV6_RECVTCLASS = 0x39
+ IPV6_RTABLE = 0x1021
+ IPV6_RTHDR = 0x33
+ IPV6_RTHDRDSTOPTS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x3d
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_USE_MIN_MTU = 0x2a
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_AUTH_LEVEL = 0x14
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DIVERTFL = 0x1022
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_ESP_NETWORK_LEVEL = 0x16
+ IP_ESP_TRANS_LEVEL = 0x15
+ IP_HDRINCL = 0x2
+ IP_IPCOMP_LEVEL = 0x1d
+ IP_IPSECFLOWINFO = 0x24
+ IP_IPSEC_LOCAL_AUTH = 0x1b
+ IP_IPSEC_LOCAL_CRED = 0x19
+ IP_IPSEC_LOCAL_ID = 0x17
+ IP_IPSEC_REMOTE_AUTH = 0x1c
+ IP_IPSEC_REMOTE_CRED = 0x1a
+ IP_IPSEC_REMOTE_ID = 0x18
+ IP_MAXPACKET = 0xffff
+ IP_MAX_MEMBERSHIPS = 0xfff
+ IP_MF = 0x2000
+ IP_MINTTL = 0x20
+ IP_MIN_MEMBERSHIPS = 0xf
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_OFFMASK = 0x1fff
+ IP_OPTIONS = 0x1
+ IP_PIPEX = 0x22
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVDSTPORT = 0x21
+ IP_RECVIF = 0x1e
+ IP_RECVOPTS = 0x5
+ IP_RECVRETOPTS = 0x6
+ IP_RECVRTABLE = 0x23
+ IP_RECVTTL = 0x1f
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RTABLE = 0x1021
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LCNT_OVERLOAD_FLUSH = 0x6
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x6
+ MADV_NORMAL = 0x0
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_SPACEAVAIL = 0x5
+ MADV_WILLNEED = 0x3
+ MAP_ANON = 0x1000
+ MAP_COPY = 0x4
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_FLAGMASK = 0x1ff7
+ MAP_HASSEMAPHORE = 0x200
+ MAP_INHERIT = 0x80
+ MAP_INHERIT_COPY = 0x1
+ MAP_INHERIT_DONATE_COPY = 0x3
+ MAP_INHERIT_NONE = 0x2
+ MAP_INHERIT_SHARE = 0x0
+ MAP_NOEXTEND = 0x100
+ MAP_NORESERVE = 0x40
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_SHARED = 0x1
+ MAP_TRYFIXED = 0x400
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MSG_BCAST = 0x100
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOR = 0x8
+ MSG_MCAST = 0x200
+ MSG_NOSIGNAL = 0x400
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x10
+ MSG_WAITALL = 0x40
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x4
+ MS_SYNC = 0x2
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_MAXID = 0x6
+ NET_RT_STATS = 0x4
+ NET_RT_TABLE = 0x5
+ NOFLSH = 0x80000000
+ NOTE_ATTRIB = 0x8
+ NOTE_CHILD = 0x4
+ NOTE_DELETE = 0x1
+ NOTE_EOF = 0x2
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXTEND = 0x4
+ NOTE_FORK = 0x40000000
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_PCTRLMASK = 0xf0000000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRUNCATE = 0x80
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ ONLCR = 0x2
+ ONLRET = 0x80
+ ONOCR = 0x40
+ ONOEOT = 0x8
+ OPOST = 0x1
+ O_ACCMODE = 0x3
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x10000
+ O_CREAT = 0x200
+ O_DIRECTORY = 0x20000
+ O_DSYNC = 0x80
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x80
+ O_SHLOCK = 0x10
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PF_FLUSH = 0x1
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ PT_MASK = 0x3ff000
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_LABEL = 0xa
+ RTAX_MAX = 0xb
+ RTAX_NETMASK = 0x2
+ RTAX_SRC = 0x8
+ RTAX_SRCMASK = 0x9
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_LABEL = 0x400
+ RTA_NETMASK = 0x4
+ RTA_SRC = 0x100
+ RTA_SRCMASK = 0x200
+ RTF_ANNOUNCE = 0x4000
+ RTF_BLACKHOLE = 0x1000
+ RTF_CLONED = 0x10000
+ RTF_CLONING = 0x100
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_FMASK = 0x10f808
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_LLINFO = 0x400
+ RTF_MASK = 0x80
+ RTF_MODIFIED = 0x20
+ RTF_MPATH = 0x40000
+ RTF_MPLS = 0x100000
+ RTF_PERMANENT_ARP = 0x2000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x2000
+ RTF_REJECT = 0x8
+ RTF_SOURCE = 0x20000
+ RTF_STATIC = 0x800
+ RTF_TUNNEL = 0x100000
+ RTF_UP = 0x1
+ RTF_USETRAILERS = 0x8000
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DESYNC = 0x10
+ RTM_GET = 0x4
+ RTM_IFANNOUNCE = 0xf
+ RTM_IFINFO = 0xe
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MAXSIZE = 0x800
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x5
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RT_TABLEID_MAX = 0xff
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ RUSAGE_THREAD = 0x1
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x4
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCAIFADDR = 0x8040691a
+ SIOCAIFGROUP = 0x80246987
+ SIOCALIFADDR = 0x8218691c
+ SIOCATMARK = 0x40047307
+ SIOCBRDGADD = 0x8054693c
+ SIOCBRDGADDS = 0x80546941
+ SIOCBRDGARL = 0x806e694d
+ SIOCBRDGDADDR = 0x81286947
+ SIOCBRDGDEL = 0x8054693d
+ SIOCBRDGDELS = 0x80546942
+ SIOCBRDGFLUSH = 0x80546948
+ SIOCBRDGFRL = 0x806e694e
+ SIOCBRDGGCACHE = 0xc0146941
+ SIOCBRDGGFD = 0xc0146952
+ SIOCBRDGGHT = 0xc0146951
+ SIOCBRDGGIFFLGS = 0xc054693e
+ SIOCBRDGGMA = 0xc0146953
+ SIOCBRDGGPARAM = 0xc03c6958
+ SIOCBRDGGPRI = 0xc0146950
+ SIOCBRDGGRL = 0xc028694f
+ SIOCBRDGGSIFS = 0xc054693c
+ SIOCBRDGGTO = 0xc0146946
+ SIOCBRDGIFS = 0xc0546942
+ SIOCBRDGRTS = 0xc0186943
+ SIOCBRDGSADDR = 0xc1286944
+ SIOCBRDGSCACHE = 0x80146940
+ SIOCBRDGSFD = 0x80146952
+ SIOCBRDGSHT = 0x80146951
+ SIOCBRDGSIFCOST = 0x80546955
+ SIOCBRDGSIFFLGS = 0x8054693f
+ SIOCBRDGSIFPRIO = 0x80546954
+ SIOCBRDGSMA = 0x80146953
+ SIOCBRDGSPRI = 0x80146950
+ SIOCBRDGSPROTO = 0x8014695a
+ SIOCBRDGSTO = 0x80146945
+ SIOCBRDGSTXHC = 0x80146959
+ SIOCDELMULTI = 0x80206932
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFGROUP = 0x80246989
+ SIOCDIFPHYADDR = 0x80206949
+ SIOCDLIFADDR = 0x8218691e
+ SIOCGETKALIVE = 0xc01869a4
+ SIOCGETLABEL = 0x8020699a
+ SIOCGETPFLOW = 0xc02069fe
+ SIOCGETPFSYNC = 0xc02069f8
+ SIOCGETSGCNT = 0xc0147534
+ SIOCGETVIFCNT = 0xc0147533
+ SIOCGETVLAN = 0xc0206990
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFASYNCMAP = 0xc020697c
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCONF = 0xc0086924
+ SIOCGIFDATA = 0xc020691b
+ SIOCGIFDESCR = 0xc0206981
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGATTR = 0xc024698b
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFGMEMB = 0xc024698a
+ SIOCGIFGROUP = 0xc0246988
+ SIOCGIFHARDMTU = 0xc02069a5
+ SIOCGIFMEDIA = 0xc0286936
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc020697e
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206948
+ SIOCGIFPRIORITY = 0xc020699c
+ SIOCGIFPSRCADDR = 0xc0206947
+ SIOCGIFRDOMAIN = 0xc02069a0
+ SIOCGIFRTLABEL = 0xc0206983
+ SIOCGIFTIMESLOT = 0xc0206986
+ SIOCGIFXFLAGS = 0xc020699e
+ SIOCGLIFADDR = 0xc218691d
+ SIOCGLIFPHYADDR = 0xc218694b
+ SIOCGLIFPHYRTABLE = 0xc02069a2
+ SIOCGLIFPHYTTL = 0xc02069a9
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCGSPPPPARAMS = 0xc0206994
+ SIOCGVH = 0xc02069f6
+ SIOCGVNETID = 0xc02069a7
+ SIOCIFCREATE = 0x8020697a
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc00c6978
+ SIOCSETKALIVE = 0x801869a3
+ SIOCSETLABEL = 0x80206999
+ SIOCSETPFLOW = 0x802069fd
+ SIOCSETPFSYNC = 0x802069f7
+ SIOCSETVLAN = 0x8020698f
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFASYNCMAP = 0x8020697d
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFDESCR = 0x80206980
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGATTR = 0x8024698c
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFLLADDR = 0x8020691f
+ SIOCSIFMEDIA = 0xc0206935
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x8020697f
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x80406946
+ SIOCSIFPRIORITY = 0x8020699b
+ SIOCSIFRDOMAIN = 0x8020699f
+ SIOCSIFRTLABEL = 0x80206982
+ SIOCSIFTIMESLOT = 0x80206985
+ SIOCSIFXFLAGS = 0x8020699d
+ SIOCSLIFPHYADDR = 0x8218694a
+ SIOCSLIFPHYRTABLE = 0x802069a1
+ SIOCSLIFPHYTTL = 0x802069a8
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SIOCSSPPPPARAMS = 0x80206993
+ SIOCSVH = 0xc02069f5
+ SIOCSVNETID = 0x802069a6
+ SOCK_DGRAM = 0x2
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_BINDANY = 0x1000
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LINGER = 0x80
+ SO_NETPROC = 0x1020
+ SO_OOBINLINE = 0x100
+ SO_PEERCRED = 0x1022
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_RTABLE = 0x1021
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_SPLICE = 0x1023
+ SO_TIMESTAMP = 0x800
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ TCIFLUSH = 0x1
+ TCIOFLUSH = 0x3
+ TCOFLUSH = 0x2
+ TCP_MAXBURST = 0x4
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_SACK = 0x3
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MD5SIG = 0x4
+ TCP_MSS = 0x200
+ TCP_NODELAY = 0x1
+ TCP_NOPUSH = 0x10
+ TCP_NSTATES = 0xb
+ TCP_SACK_ENABLE = 0x8
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDRAIN = 0x2000745e
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLAG_CLOCAL = 0x2
+ TIOCFLAG_CRTSCTS = 0x4
+ TIOCFLAG_MDMBUF = 0x8
+ TIOCFLAG_PPS = 0x10
+ TIOCFLAG_SOFTCAR = 0x1
+ TIOCFLUSH = 0x80047410
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGFLAGS = 0x4004745d
+ TIOCGPGRP = 0x40047477
+ TIOCGSID = 0x40047463
+ TIOCGTSTAMP = 0x400c745b
+ TIOCGWINSZ = 0x40087468
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGET = 0x4004746a
+ TIOCMODG = 0x4004746a
+ TIOCMODS = 0x8004746d
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCTTY = 0x20007461
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSFLAGS = 0x8004745c
+ TIOCSIG = 0x8004745f
+ TIOCSPGRP = 0x80047476
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x80047465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSTSTAMP = 0x8008745a
+ TIOCSWINSZ = 0x80087467
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VTIME = 0x11
+ VWERASE = 0x4
+ WALTSIG = 0x4
+ WCONTINUED = 0x8
+ WCOREFLAG = 0x80
+ WNOHANG = 0x1
+ WSTOPPED = 0x7f
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADF = syscall.Errno(0x9)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x58)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x59)
+ EILSEQ = syscall.Errno(0x54)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EIPSEC = syscall.Errno(0x52)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x5b)
+ ELOOP = syscall.Errno(0x3e)
+ EMEDIUMTYPE = syscall.Errno(0x56)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x53)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOMEDIUM = syscall.Errno(0x55)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x5a)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x5b)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x57)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTHR = syscall.Signal(0x20)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "connection timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "IPsec processing failure",
+ 83: "attribute not found",
+ 84: "illegal byte sequence",
+ 85: "no medium found",
+ 86: "wrong medium type",
+ 87: "value too large to be stored in data type",
+ 88: "operation canceled",
+ 89: "identifier removed",
+ 90: "no message of desired type",
+ 91: "not supported",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "stopped (signal)",
+ 18: "stopped",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+ 32: "thread AST",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go
new file mode 100644
index 0000000..1758ecc
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go
@@ -0,0 +1,1583 @@
+// mkerrors.sh -m64
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+// +build amd64,openbsd
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m64 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_BLUETOOTH = 0x20
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1a
+ AF_ECMA = 0x8
+ AF_ENCAP = 0x1c
+ AF_HYLINK = 0xf
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x18
+ AF_IPX = 0x17
+ AF_ISDN = 0x1a
+ AF_ISO = 0x7
+ AF_KEY = 0x1e
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x24
+ AF_MPLS = 0x21
+ AF_NATM = 0x1b
+ AF_NS = 0x6
+ AF_OSI = 0x7
+ AF_PUP = 0x4
+ AF_ROUTE = 0x11
+ AF_SIP = 0x1d
+ AF_SNA = 0xb
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ ARPHRD_ETHER = 0x1
+ ARPHRD_FRELAY = 0xf
+ ARPHRD_IEEE1394 = 0x18
+ ARPHRD_IEEE802 = 0x6
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B9600 = 0x2580
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDIRFILT = 0x4004427c
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc010427b
+ BIOCGETIF = 0x4020426b
+ BIOCGFILDROP = 0x40044278
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044273
+ BIOCGRTIMEOUT = 0x4010426e
+ BIOCGSTATS = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCLOCK = 0x20004276
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDIRFILT = 0x8004427d
+ BIOCSDLT = 0x8004427a
+ BIOCSETF = 0x80104267
+ BIOCSETIF = 0x8020426c
+ BIOCSETWF = 0x80104277
+ BIOCSFILDROP = 0x80044279
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044272
+ BIOCSRTIMEOUT = 0x8010426d
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_DIRECTION_IN = 0x1
+ BPF_DIRECTION_OUT = 0x2
+ 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_MAXBUFSIZE = 0x200000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CREAD = 0x800
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0xff
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ DIOCOSFPFLUSH = 0x2000444e
+ DLT_ARCNET = 0x7
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AX25 = 0x3
+ DLT_CHAOS = 0x5
+ DLT_C_HDLC = 0x68
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0xd
+ DLT_FDDI = 0xa
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_LOOP = 0xc
+ DLT_MPLS = 0xdb
+ DLT_NULL = 0x0
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0x10
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_SERIAL = 0x32
+ DLT_PRONET = 0x4
+ DLT_RAW = 0xe
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xf
+ DT_BLK = 0x6
+ DT_CHR = 0x2
+ DT_DIR = 0x4
+ DT_FIFO = 0x1
+ DT_LNK = 0xa
+ DT_REG = 0x8
+ DT_SOCK = 0xc
+ DT_UNKNOWN = 0x0
+ ECHO = 0x8
+ ECHOCTL = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EMT_TAGOVF = 0x1
+ EMUL_ENABLED = 0x1
+ EMUL_NATIVE = 0x2
+ ENDRUNDISC = 0x9
+ ETHERMIN = 0x2e
+ ETHERMTU = 0x5dc
+ ETHERTYPE_8023 = 0x4
+ ETHERTYPE_AARP = 0x80f3
+ ETHERTYPE_ACCTON = 0x8390
+ ETHERTYPE_AEONIC = 0x8036
+ ETHERTYPE_ALPHA = 0x814a
+ ETHERTYPE_AMBER = 0x6008
+ ETHERTYPE_AMOEBA = 0x8145
+ ETHERTYPE_AOE = 0x88a2
+ ETHERTYPE_APOLLO = 0x80f7
+ ETHERTYPE_APOLLODOMAIN = 0x8019
+ ETHERTYPE_APPLETALK = 0x809b
+ ETHERTYPE_APPLITEK = 0x80c7
+ ETHERTYPE_ARGONAUT = 0x803a
+ ETHERTYPE_ARP = 0x806
+ ETHERTYPE_AT = 0x809b
+ ETHERTYPE_ATALK = 0x809b
+ ETHERTYPE_ATOMIC = 0x86df
+ ETHERTYPE_ATT = 0x8069
+ ETHERTYPE_ATTSTANFORD = 0x8008
+ ETHERTYPE_AUTOPHON = 0x806a
+ ETHERTYPE_AXIS = 0x8856
+ ETHERTYPE_BCLOOP = 0x9003
+ ETHERTYPE_BOFL = 0x8102
+ ETHERTYPE_CABLETRON = 0x7034
+ ETHERTYPE_CHAOS = 0x804
+ ETHERTYPE_COMDESIGN = 0x806c
+ ETHERTYPE_COMPUGRAPHIC = 0x806d
+ ETHERTYPE_COUNTERPOINT = 0x8062
+ ETHERTYPE_CRONUS = 0x8004
+ ETHERTYPE_CRONUSVLN = 0x8003
+ ETHERTYPE_DCA = 0x1234
+ ETHERTYPE_DDE = 0x807b
+ ETHERTYPE_DEBNI = 0xaaaa
+ ETHERTYPE_DECAM = 0x8048
+ ETHERTYPE_DECCUST = 0x6006
+ ETHERTYPE_DECDIAG = 0x6005
+ ETHERTYPE_DECDNS = 0x803c
+ ETHERTYPE_DECDTS = 0x803e
+ ETHERTYPE_DECEXPER = 0x6000
+ ETHERTYPE_DECLAST = 0x8041
+ ETHERTYPE_DECLTM = 0x803f
+ ETHERTYPE_DECMUMPS = 0x6009
+ ETHERTYPE_DECNETBIOS = 0x8040
+ ETHERTYPE_DELTACON = 0x86de
+ ETHERTYPE_DIDDLE = 0x4321
+ ETHERTYPE_DLOG1 = 0x660
+ ETHERTYPE_DLOG2 = 0x661
+ ETHERTYPE_DN = 0x6003
+ ETHERTYPE_DOGFIGHT = 0x1989
+ ETHERTYPE_DSMD = 0x8039
+ ETHERTYPE_ECMA = 0x803
+ ETHERTYPE_ENCRYPT = 0x803d
+ ETHERTYPE_ES = 0x805d
+ ETHERTYPE_EXCELAN = 0x8010
+ ETHERTYPE_EXPERDATA = 0x8049
+ ETHERTYPE_FLIP = 0x8146
+ ETHERTYPE_FLOWCONTROL = 0x8808
+ ETHERTYPE_FRARP = 0x808
+ ETHERTYPE_GENDYN = 0x8068
+ ETHERTYPE_HAYES = 0x8130
+ ETHERTYPE_HIPPI_FP = 0x8180
+ ETHERTYPE_HITACHI = 0x8820
+ ETHERTYPE_HP = 0x8005
+ ETHERTYPE_IEEEPUP = 0xa00
+ ETHERTYPE_IEEEPUPAT = 0xa01
+ ETHERTYPE_IMLBL = 0x4c42
+ ETHERTYPE_IMLBLDIAG = 0x424c
+ ETHERTYPE_IP = 0x800
+ ETHERTYPE_IPAS = 0x876c
+ ETHERTYPE_IPV6 = 0x86dd
+ ETHERTYPE_IPX = 0x8137
+ ETHERTYPE_IPXNEW = 0x8037
+ ETHERTYPE_KALPANA = 0x8582
+ ETHERTYPE_LANBRIDGE = 0x8038
+ ETHERTYPE_LANPROBE = 0x8888
+ ETHERTYPE_LAT = 0x6004
+ ETHERTYPE_LBACK = 0x9000
+ ETHERTYPE_LITTLE = 0x8060
+ ETHERTYPE_LLDP = 0x88cc
+ ETHERTYPE_LOGICRAFT = 0x8148
+ ETHERTYPE_LOOPBACK = 0x9000
+ ETHERTYPE_MATRA = 0x807a
+ ETHERTYPE_MAX = 0xffff
+ ETHERTYPE_MERIT = 0x807c
+ ETHERTYPE_MICP = 0x873a
+ ETHERTYPE_MOPDL = 0x6001
+ ETHERTYPE_MOPRC = 0x6002
+ ETHERTYPE_MOTOROLA = 0x818d
+ ETHERTYPE_MPLS = 0x8847
+ ETHERTYPE_MPLS_MCAST = 0x8848
+ ETHERTYPE_MUMPS = 0x813f
+ ETHERTYPE_NBPCC = 0x3c04
+ ETHERTYPE_NBPCLAIM = 0x3c09
+ ETHERTYPE_NBPCLREQ = 0x3c05
+ ETHERTYPE_NBPCLRSP = 0x3c06
+ ETHERTYPE_NBPCREQ = 0x3c02
+ ETHERTYPE_NBPCRSP = 0x3c03
+ ETHERTYPE_NBPDG = 0x3c07
+ ETHERTYPE_NBPDGB = 0x3c08
+ ETHERTYPE_NBPDLTE = 0x3c0a
+ ETHERTYPE_NBPRAR = 0x3c0c
+ ETHERTYPE_NBPRAS = 0x3c0b
+ ETHERTYPE_NBPRST = 0x3c0d
+ ETHERTYPE_NBPSCD = 0x3c01
+ ETHERTYPE_NBPVCD = 0x3c00
+ ETHERTYPE_NBS = 0x802
+ ETHERTYPE_NCD = 0x8149
+ ETHERTYPE_NESTAR = 0x8006
+ ETHERTYPE_NETBEUI = 0x8191
+ ETHERTYPE_NOVELL = 0x8138
+ ETHERTYPE_NS = 0x600
+ ETHERTYPE_NSAT = 0x601
+ ETHERTYPE_NSCOMPAT = 0x807
+ ETHERTYPE_NTRAILER = 0x10
+ ETHERTYPE_OS9 = 0x7007
+ ETHERTYPE_OS9NET = 0x7009
+ ETHERTYPE_PACER = 0x80c6
+ ETHERTYPE_PAE = 0x888e
+ ETHERTYPE_PCS = 0x4242
+ ETHERTYPE_PLANNING = 0x8044
+ ETHERTYPE_PPP = 0x880b
+ ETHERTYPE_PPPOE = 0x8864
+ ETHERTYPE_PPPOEDISC = 0x8863
+ ETHERTYPE_PRIMENTS = 0x7031
+ ETHERTYPE_PUP = 0x200
+ ETHERTYPE_PUPAT = 0x200
+ ETHERTYPE_QINQ = 0x88a8
+ ETHERTYPE_RACAL = 0x7030
+ ETHERTYPE_RATIONAL = 0x8150
+ ETHERTYPE_RAWFR = 0x6559
+ ETHERTYPE_RCL = 0x1995
+ ETHERTYPE_RDP = 0x8739
+ ETHERTYPE_RETIX = 0x80f2
+ ETHERTYPE_REVARP = 0x8035
+ ETHERTYPE_SCA = 0x6007
+ ETHERTYPE_SECTRA = 0x86db
+ ETHERTYPE_SECUREDATA = 0x876d
+ ETHERTYPE_SGITW = 0x817e
+ ETHERTYPE_SG_BOUNCE = 0x8016
+ ETHERTYPE_SG_DIAG = 0x8013
+ ETHERTYPE_SG_NETGAMES = 0x8014
+ ETHERTYPE_SG_RESV = 0x8015
+ ETHERTYPE_SIMNET = 0x5208
+ ETHERTYPE_SLOW = 0x8809
+ ETHERTYPE_SNA = 0x80d5
+ ETHERTYPE_SNMP = 0x814c
+ ETHERTYPE_SONIX = 0xfaf5
+ ETHERTYPE_SPIDER = 0x809f
+ ETHERTYPE_SPRITE = 0x500
+ ETHERTYPE_STP = 0x8181
+ ETHERTYPE_TALARIS = 0x812b
+ ETHERTYPE_TALARISMC = 0x852b
+ ETHERTYPE_TCPCOMP = 0x876b
+ ETHERTYPE_TCPSM = 0x9002
+ ETHERTYPE_TEC = 0x814f
+ ETHERTYPE_TIGAN = 0x802f
+ ETHERTYPE_TRAIL = 0x1000
+ ETHERTYPE_TRANSETHER = 0x6558
+ ETHERTYPE_TYMSHARE = 0x802e
+ ETHERTYPE_UBBST = 0x7005
+ ETHERTYPE_UBDEBUG = 0x900
+ ETHERTYPE_UBDIAGLOOP = 0x7002
+ ETHERTYPE_UBDL = 0x7000
+ ETHERTYPE_UBNIU = 0x7001
+ ETHERTYPE_UBNMC = 0x7003
+ ETHERTYPE_VALID = 0x1600
+ ETHERTYPE_VARIAN = 0x80dd
+ ETHERTYPE_VAXELN = 0x803b
+ ETHERTYPE_VEECO = 0x8067
+ ETHERTYPE_VEXP = 0x805b
+ ETHERTYPE_VGLAB = 0x8131
+ ETHERTYPE_VINES = 0xbad
+ ETHERTYPE_VINESECHO = 0xbaf
+ ETHERTYPE_VINESLOOP = 0xbae
+ ETHERTYPE_VITAL = 0xff00
+ ETHERTYPE_VLAN = 0x8100
+ ETHERTYPE_VLTLMAN = 0x8080
+ ETHERTYPE_VPROD = 0x805c
+ ETHERTYPE_VURESERVED = 0x8147
+ ETHERTYPE_WATERLOO = 0x8130
+ ETHERTYPE_WELLFLEET = 0x8103
+ ETHERTYPE_X25 = 0x805
+ ETHERTYPE_X75 = 0x801
+ ETHERTYPE_XNSSM = 0x9001
+ ETHERTYPE_XTP = 0x817d
+ ETHER_ADDR_LEN = 0x6
+ ETHER_ALIGN = 0x2
+ ETHER_CRC_LEN = 0x4
+ ETHER_CRC_POLY_BE = 0x4c11db6
+ ETHER_CRC_POLY_LE = 0xedb88320
+ ETHER_HDR_LEN = 0xe
+ ETHER_MAX_DIX_LEN = 0x600
+ ETHER_MAX_LEN = 0x5ee
+ ETHER_MIN_LEN = 0x40
+ ETHER_TYPE_LEN = 0x2
+ ETHER_VLAN_ENCAP_LEN = 0x4
+ EVFILT_AIO = -0x3
+ EVFILT_PROC = -0x5
+ EVFILT_READ = -0x1
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0x7
+ EVFILT_TIMER = -0x7
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG1 = 0x2000
+ EV_ONESHOT = 0x10
+ EV_SYSFLAGS = 0xf000
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FLUSHO = 0x800000
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0xa
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETOWN = 0x5
+ F_OK = 0x0
+ F_RDLCK = 0x1
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETOWN = 0x6
+ F_UNLCK = 0x2
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFAN_ARRIVAL = 0x0
+ IFAN_DEPARTURE = 0x1
+ IFA_ROUTE = 0x1
+ IFF_ALLMULTI = 0x200
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x8e52
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NOTRAILERS = 0x20
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_A12MPPSWITCH = 0x82
+ IFT_AAL2 = 0xbb
+ IFT_AAL5 = 0x31
+ IFT_ADSL = 0x5e
+ IFT_AFLANE8023 = 0x3b
+ IFT_AFLANE8025 = 0x3c
+ IFT_ARAP = 0x58
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ASYNC = 0x54
+ IFT_ATM = 0x25
+ IFT_ATMDXI = 0x69
+ IFT_ATMFUNI = 0x6a
+ IFT_ATMIMA = 0x6b
+ IFT_ATMLOGICAL = 0x50
+ IFT_ATMRADIO = 0xbd
+ IFT_ATMSUBINTERFACE = 0x86
+ IFT_ATMVCIENDPT = 0xc2
+ IFT_ATMVIRTUAL = 0x95
+ IFT_BGPPOLICYACCOUNTING = 0xa2
+ IFT_BLUETOOTH = 0xf8
+ IFT_BRIDGE = 0xd1
+ IFT_BSC = 0x53
+ IFT_CARP = 0xf7
+ IFT_CCTEMUL = 0x3d
+ IFT_CEPT = 0x13
+ IFT_CES = 0x85
+ IFT_CHANNEL = 0x46
+ IFT_CNR = 0x55
+ IFT_COFFEE = 0x84
+ IFT_COMPOSITELINK = 0x9b
+ IFT_DCN = 0x8d
+ IFT_DIGITALPOWERLINE = 0x8a
+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
+ IFT_DLSW = 0x4a
+ IFT_DOCSCABLEDOWNSTREAM = 0x80
+ IFT_DOCSCABLEMACLAYER = 0x7f
+ IFT_DOCSCABLEUPSTREAM = 0x81
+ IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd
+ IFT_DS0 = 0x51
+ IFT_DS0BUNDLE = 0x52
+ IFT_DS1FDL = 0xaa
+ IFT_DS3 = 0x1e
+ IFT_DTM = 0x8c
+ IFT_DUMMY = 0xf1
+ IFT_DVBASILN = 0xac
+ IFT_DVBASIOUT = 0xad
+ IFT_DVBRCCDOWNSTREAM = 0x93
+ IFT_DVBRCCMACLAYER = 0x92
+ IFT_DVBRCCUPSTREAM = 0x94
+ IFT_ECONET = 0xce
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_EPLRS = 0x57
+ IFT_ESCON = 0x49
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0xf3
+ IFT_FAST = 0x7d
+ IFT_FASTETHER = 0x3e
+ IFT_FASTETHERFX = 0x45
+ IFT_FDDI = 0xf
+ IFT_FIBRECHANNEL = 0x38
+ IFT_FRAMERELAYINTERCONNECT = 0x3a
+ IFT_FRAMERELAYMPI = 0x5c
+ IFT_FRDLCIENDPT = 0xc1
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_FRF16MFRBUNDLE = 0xa3
+ IFT_FRFORWARD = 0x9e
+ IFT_G703AT2MB = 0x43
+ IFT_G703AT64K = 0x42
+ IFT_GIF = 0xf0
+ IFT_GIGABITETHERNET = 0x75
+ IFT_GR303IDT = 0xb2
+ IFT_GR303RDT = 0xb1
+ IFT_H323GATEKEEPER = 0xa4
+ IFT_H323PROXY = 0xa5
+ IFT_HDH1822 = 0x3
+ IFT_HDLC = 0x76
+ IFT_HDSL2 = 0xa8
+ IFT_HIPERLAN2 = 0xb7
+ IFT_HIPPI = 0x2f
+ IFT_HIPPIINTERFACE = 0x39
+ IFT_HOSTPAD = 0x5a
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IBM370PARCHAN = 0x48
+ IFT_IDSL = 0x9a
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE80211 = 0x47
+ IFT_IEEE80212 = 0x37
+ IFT_IEEE8023ADLAG = 0xa1
+ IFT_IFGSN = 0x91
+ IFT_IMT = 0xbe
+ IFT_INFINIBAND = 0xc7
+ IFT_INTERLEAVE = 0x7c
+ IFT_IP = 0x7e
+ IFT_IPFORWARD = 0x8e
+ IFT_IPOVERATM = 0x72
+ IFT_IPOVERCDLC = 0x6d
+ IFT_IPOVERCLAW = 0x6e
+ IFT_IPSWITCH = 0x4e
+ IFT_ISDN = 0x3f
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISDNS = 0x4b
+ IFT_ISDNU = 0x4c
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88025CRFPINT = 0x62
+ IFT_ISO88025DTR = 0x56
+ IFT_ISO88025FIBER = 0x73
+ IFT_ISO88026 = 0xa
+ IFT_ISUP = 0xb3
+ IFT_L2VLAN = 0x87
+ IFT_L3IPVLAN = 0x88
+ IFT_L3IPXVLAN = 0x89
+ IFT_LAPB = 0x10
+ IFT_LAPD = 0x4d
+ IFT_LAPF = 0x77
+ IFT_LINEGROUP = 0xd2
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MEDIAMAILOVERIP = 0x8b
+ IFT_MFSIGLINK = 0xa7
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_MPC = 0x71
+ IFT_MPLS = 0xa6
+ IFT_MPLSTUNNEL = 0x96
+ IFT_MSDSL = 0x8f
+ IFT_MVL = 0xbf
+ IFT_MYRINET = 0x63
+ IFT_NFAS = 0xaf
+ IFT_NSIP = 0x1b
+ IFT_OPTICALCHANNEL = 0xc3
+ IFT_OPTICALTRANSPORT = 0xc4
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PFLOG = 0xf5
+ IFT_PFLOW = 0xf9
+ IFT_PFSYNC = 0xf6
+ IFT_PLC = 0xae
+ IFT_PON155 = 0xcf
+ IFT_PON622 = 0xd0
+ IFT_POS = 0xab
+ IFT_PPP = 0x17
+ IFT_PPPMULTILINKBUNDLE = 0x6c
+ IFT_PROPATM = 0xc5
+ IFT_PROPBWAP2MP = 0xb8
+ IFT_PROPCNLS = 0x59
+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PROPWIRELESSP2P = 0x9d
+ IFT_PTPSERIAL = 0x16
+ IFT_PVC = 0xf2
+ IFT_Q2931 = 0xc9
+ IFT_QLLC = 0x44
+ IFT_RADIOMAC = 0xbc
+ IFT_RADSL = 0x5f
+ IFT_REACHDSL = 0xc0
+ IFT_RFC1483 = 0x9f
+ IFT_RS232 = 0x21
+ IFT_RSRB = 0x4f
+ IFT_SDLC = 0x11
+ IFT_SDSL = 0x60
+ IFT_SHDSL = 0xa9
+ IFT_SIP = 0x1f
+ IFT_SIPSIG = 0xcc
+ IFT_SIPTG = 0xcb
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETOVERHEADCHANNEL = 0xb9
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_SRP = 0x97
+ IFT_SS7SIGLINK = 0x9c
+ IFT_STACKTOSTACK = 0x6f
+ IFT_STARLAN = 0xb
+ IFT_T1 = 0x12
+ IFT_TDLC = 0x74
+ IFT_TELINK = 0xc8
+ IFT_TERMPAD = 0x5b
+ IFT_TR008 = 0xb0
+ IFT_TRANSPHDLC = 0x7b
+ IFT_TUNNEL = 0x83
+ IFT_ULTRA = 0x1d
+ IFT_USB = 0xa0
+ IFT_V11 = 0x40
+ IFT_V35 = 0x2d
+ IFT_V36 = 0x41
+ IFT_V37 = 0x78
+ IFT_VDSL = 0x61
+ IFT_VIRTUALIPADDRESS = 0x70
+ IFT_VIRTUALTG = 0xca
+ IFT_VOICEDID = 0xd5
+ IFT_VOICEEM = 0x64
+ IFT_VOICEEMFGD = 0xd3
+ IFT_VOICEENCAP = 0x67
+ IFT_VOICEFGDEANA = 0xd4
+ IFT_VOICEFXO = 0x65
+ IFT_VOICEFXS = 0x66
+ IFT_VOICEOVERATM = 0x98
+ IFT_VOICEOVERCABLE = 0xc6
+ IFT_VOICEOVERFRAMERELAY = 0x99
+ IFT_VOICEOVERIP = 0x68
+ IFT_X213 = 0x5d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25HUNTGROUP = 0x7a
+ IFT_X25MLP = 0x79
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LOOPBACKNET = 0x7f
+ IN_RFC3021_HOST = 0x1
+ IN_RFC3021_NET = 0xfffffffe
+ IN_RFC3021_NSHIFT = 0x1f
+ IPPROTO_AH = 0x33
+ IPPROTO_CARP = 0x70
+ IPPROTO_DIVERT = 0x102
+ IPPROTO_DIVERT_INIT = 0x2
+ IPPROTO_DIVERT_RESP = 0x1
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x103
+ IPPROTO_MOBILE = 0x37
+ IPPROTO_MPLS = 0x89
+ IPPROTO_NONE = 0x3b
+ IPPROTO_PFSYNC = 0xf0
+ IPPROTO_PIM = 0x67
+ IPPROTO_PUP = 0xc
+ IPPROTO_RAW = 0xff
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_TCP = 0x6
+ IPPROTO_TP = 0x1d
+ IPPROTO_UDP = 0x11
+ IPV6_AUTH_LEVEL = 0x35
+ IPV6_AUTOFLOWLABEL = 0x3b
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_DONTFRAG = 0x3e
+ IPV6_DSTOPTS = 0x32
+ IPV6_ESP_NETWORK_LEVEL = 0x37
+ IPV6_ESP_TRANS_LEVEL = 0x36
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x78
+ IPV6_HLIMDEC = 0x1
+ IPV6_HOPLIMIT = 0x2f
+ IPV6_HOPOPTS = 0x31
+ IPV6_IPCOMP_LEVEL = 0x3c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MMTU = 0x500
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_NEXTHOP = 0x30
+ IPV6_OPTIONS = 0x1
+ IPV6_PATHMTU = 0x2c
+ IPV6_PIPEX = 0x3f
+ IPV6_PKTINFO = 0x2e
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVDSTPORT = 0x40
+ IPV6_RECVHOPLIMIT = 0x25
+ IPV6_RECVHOPOPTS = 0x27
+ IPV6_RECVPATHMTU = 0x2b
+ IPV6_RECVPKTINFO = 0x24
+ IPV6_RECVRTHDR = 0x26
+ IPV6_RECVTCLASS = 0x39
+ IPV6_RTABLE = 0x1021
+ IPV6_RTHDR = 0x33
+ IPV6_RTHDRDSTOPTS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x3d
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_USE_MIN_MTU = 0x2a
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_AUTH_LEVEL = 0x14
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DIVERTFL = 0x1022
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_ESP_NETWORK_LEVEL = 0x16
+ IP_ESP_TRANS_LEVEL = 0x15
+ IP_HDRINCL = 0x2
+ IP_IPCOMP_LEVEL = 0x1d
+ IP_IPSECFLOWINFO = 0x24
+ IP_IPSEC_LOCAL_AUTH = 0x1b
+ IP_IPSEC_LOCAL_CRED = 0x19
+ IP_IPSEC_LOCAL_ID = 0x17
+ IP_IPSEC_REMOTE_AUTH = 0x1c
+ IP_IPSEC_REMOTE_CRED = 0x1a
+ IP_IPSEC_REMOTE_ID = 0x18
+ IP_MAXPACKET = 0xffff
+ IP_MAX_MEMBERSHIPS = 0xfff
+ IP_MF = 0x2000
+ IP_MINTTL = 0x20
+ IP_MIN_MEMBERSHIPS = 0xf
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_OFFMASK = 0x1fff
+ IP_OPTIONS = 0x1
+ IP_PIPEX = 0x22
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVDSTPORT = 0x21
+ IP_RECVIF = 0x1e
+ IP_RECVOPTS = 0x5
+ IP_RECVRETOPTS = 0x6
+ IP_RECVRTABLE = 0x23
+ IP_RECVTTL = 0x1f
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RTABLE = 0x1021
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LCNT_OVERLOAD_FLUSH = 0x6
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x6
+ MADV_NORMAL = 0x0
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_SPACEAVAIL = 0x5
+ MADV_WILLNEED = 0x3
+ MAP_ANON = 0x1000
+ MAP_COPY = 0x4
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_FLAGMASK = 0x1ff7
+ MAP_HASSEMAPHORE = 0x200
+ MAP_INHERIT = 0x80
+ MAP_INHERIT_COPY = 0x1
+ MAP_INHERIT_DONATE_COPY = 0x3
+ MAP_INHERIT_NONE = 0x2
+ MAP_INHERIT_SHARE = 0x0
+ MAP_NOEXTEND = 0x100
+ MAP_NORESERVE = 0x40
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_SHARED = 0x1
+ MAP_TRYFIXED = 0x400
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MSG_BCAST = 0x100
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOR = 0x8
+ MSG_MCAST = 0x200
+ MSG_NOSIGNAL = 0x400
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x10
+ MSG_WAITALL = 0x40
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x4
+ MS_SYNC = 0x2
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_MAXID = 0x6
+ NET_RT_STATS = 0x4
+ NET_RT_TABLE = 0x5
+ NOFLSH = 0x80000000
+ NOTE_ATTRIB = 0x8
+ NOTE_CHILD = 0x4
+ NOTE_DELETE = 0x1
+ NOTE_EOF = 0x2
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXTEND = 0x4
+ NOTE_FORK = 0x40000000
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_PCTRLMASK = 0xf0000000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRUNCATE = 0x80
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ ONLCR = 0x2
+ ONLRET = 0x80
+ ONOCR = 0x40
+ ONOEOT = 0x8
+ OPOST = 0x1
+ O_ACCMODE = 0x3
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x10000
+ O_CREAT = 0x200
+ O_DIRECTORY = 0x20000
+ O_DSYNC = 0x80
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x80
+ O_SHLOCK = 0x10
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PF_FLUSH = 0x1
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_LABEL = 0xa
+ RTAX_MAX = 0xb
+ RTAX_NETMASK = 0x2
+ RTAX_SRC = 0x8
+ RTAX_SRCMASK = 0x9
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_LABEL = 0x400
+ RTA_NETMASK = 0x4
+ RTA_SRC = 0x100
+ RTA_SRCMASK = 0x200
+ RTF_ANNOUNCE = 0x4000
+ RTF_BLACKHOLE = 0x1000
+ RTF_CLONED = 0x10000
+ RTF_CLONING = 0x100
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_FMASK = 0x10f808
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_LLINFO = 0x400
+ RTF_MASK = 0x80
+ RTF_MODIFIED = 0x20
+ RTF_MPATH = 0x40000
+ RTF_MPLS = 0x100000
+ RTF_PERMANENT_ARP = 0x2000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x2000
+ RTF_REJECT = 0x8
+ RTF_SOURCE = 0x20000
+ RTF_STATIC = 0x800
+ RTF_TUNNEL = 0x100000
+ RTF_UP = 0x1
+ RTF_USETRAILERS = 0x8000
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DESYNC = 0x10
+ RTM_GET = 0x4
+ RTM_IFANNOUNCE = 0xf
+ RTM_IFINFO = 0xe
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MAXSIZE = 0x800
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x5
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RT_TABLEID_MAX = 0xff
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ RUSAGE_THREAD = 0x1
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x4
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCAIFADDR = 0x8040691a
+ SIOCAIFGROUP = 0x80286987
+ SIOCALIFADDR = 0x8218691c
+ SIOCATMARK = 0x40047307
+ SIOCBRDGADD = 0x8058693c
+ SIOCBRDGADDS = 0x80586941
+ SIOCBRDGARL = 0x806e694d
+ SIOCBRDGDADDR = 0x81286947
+ SIOCBRDGDEL = 0x8058693d
+ SIOCBRDGDELS = 0x80586942
+ SIOCBRDGFLUSH = 0x80586948
+ SIOCBRDGFRL = 0x806e694e
+ SIOCBRDGGCACHE = 0xc0146941
+ SIOCBRDGGFD = 0xc0146952
+ SIOCBRDGGHT = 0xc0146951
+ SIOCBRDGGIFFLGS = 0xc058693e
+ SIOCBRDGGMA = 0xc0146953
+ SIOCBRDGGPARAM = 0xc0406958
+ SIOCBRDGGPRI = 0xc0146950
+ SIOCBRDGGRL = 0xc030694f
+ SIOCBRDGGSIFS = 0xc058693c
+ SIOCBRDGGTO = 0xc0146946
+ SIOCBRDGIFS = 0xc0586942
+ SIOCBRDGRTS = 0xc0206943
+ SIOCBRDGSADDR = 0xc1286944
+ SIOCBRDGSCACHE = 0x80146940
+ SIOCBRDGSFD = 0x80146952
+ SIOCBRDGSHT = 0x80146951
+ SIOCBRDGSIFCOST = 0x80586955
+ SIOCBRDGSIFFLGS = 0x8058693f
+ SIOCBRDGSIFPRIO = 0x80586954
+ SIOCBRDGSMA = 0x80146953
+ SIOCBRDGSPRI = 0x80146950
+ SIOCBRDGSPROTO = 0x8014695a
+ SIOCBRDGSTO = 0x80146945
+ SIOCBRDGSTXHC = 0x80146959
+ SIOCDELMULTI = 0x80206932
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFGROUP = 0x80286989
+ SIOCDIFPHYADDR = 0x80206949
+ SIOCDLIFADDR = 0x8218691e
+ SIOCGETKALIVE = 0xc01869a4
+ SIOCGETLABEL = 0x8020699a
+ SIOCGETPFLOW = 0xc02069fe
+ SIOCGETPFSYNC = 0xc02069f8
+ SIOCGETSGCNT = 0xc0207534
+ SIOCGETVIFCNT = 0xc0287533
+ SIOCGETVLAN = 0xc0206990
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFASYNCMAP = 0xc020697c
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCONF = 0xc0106924
+ SIOCGIFDATA = 0xc020691b
+ SIOCGIFDESCR = 0xc0206981
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGATTR = 0xc028698b
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFGMEMB = 0xc028698a
+ SIOCGIFGROUP = 0xc0286988
+ SIOCGIFHARDMTU = 0xc02069a5
+ SIOCGIFMEDIA = 0xc0306936
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc020697e
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206948
+ SIOCGIFPRIORITY = 0xc020699c
+ SIOCGIFPSRCADDR = 0xc0206947
+ SIOCGIFRDOMAIN = 0xc02069a0
+ SIOCGIFRTLABEL = 0xc0206983
+ SIOCGIFTIMESLOT = 0xc0206986
+ SIOCGIFXFLAGS = 0xc020699e
+ SIOCGLIFADDR = 0xc218691d
+ SIOCGLIFPHYADDR = 0xc218694b
+ SIOCGLIFPHYRTABLE = 0xc02069a2
+ SIOCGLIFPHYTTL = 0xc02069a9
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCGSPPPPARAMS = 0xc0206994
+ SIOCGVH = 0xc02069f6
+ SIOCGVNETID = 0xc02069a7
+ SIOCIFCREATE = 0x8020697a
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc0106978
+ SIOCSETKALIVE = 0x801869a3
+ SIOCSETLABEL = 0x80206999
+ SIOCSETPFLOW = 0x802069fd
+ SIOCSETPFSYNC = 0x802069f7
+ SIOCSETVLAN = 0x8020698f
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFASYNCMAP = 0x8020697d
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFDESCR = 0x80206980
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGATTR = 0x8028698c
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFLLADDR = 0x8020691f
+ SIOCSIFMEDIA = 0xc0206935
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x8020697f
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x80406946
+ SIOCSIFPRIORITY = 0x8020699b
+ SIOCSIFRDOMAIN = 0x8020699f
+ SIOCSIFRTLABEL = 0x80206982
+ SIOCSIFTIMESLOT = 0x80206985
+ SIOCSIFXFLAGS = 0x8020699d
+ SIOCSLIFPHYADDR = 0x8218694a
+ SIOCSLIFPHYRTABLE = 0x802069a1
+ SIOCSLIFPHYTTL = 0x802069a8
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SIOCSSPPPPARAMS = 0x80206993
+ SIOCSVH = 0xc02069f5
+ SIOCSVNETID = 0x802069a6
+ SOCK_DGRAM = 0x2
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_BINDANY = 0x1000
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LINGER = 0x80
+ SO_NETPROC = 0x1020
+ SO_OOBINLINE = 0x100
+ SO_PEERCRED = 0x1022
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_RTABLE = 0x1021
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_SPLICE = 0x1023
+ SO_TIMESTAMP = 0x800
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ TCIFLUSH = 0x1
+ TCIOFLUSH = 0x3
+ TCOFLUSH = 0x2
+ TCP_MAXBURST = 0x4
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_SACK = 0x3
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MD5SIG = 0x4
+ TCP_MSS = 0x200
+ TCP_NODELAY = 0x1
+ TCP_NOPUSH = 0x10
+ TCP_NSTATES = 0xb
+ TCP_SACK_ENABLE = 0x8
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDRAIN = 0x2000745e
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLAG_CLOCAL = 0x2
+ TIOCFLAG_CRTSCTS = 0x4
+ TIOCFLAG_MDMBUF = 0x8
+ TIOCFLAG_PPS = 0x10
+ TIOCFLAG_SOFTCAR = 0x1
+ TIOCFLUSH = 0x80047410
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGFLAGS = 0x4004745d
+ TIOCGPGRP = 0x40047477
+ TIOCGSID = 0x40047463
+ TIOCGTSTAMP = 0x4010745b
+ TIOCGWINSZ = 0x40087468
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGET = 0x4004746a
+ TIOCMODG = 0x4004746a
+ TIOCMODS = 0x8004746d
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCTTY = 0x20007461
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSFLAGS = 0x8004745c
+ TIOCSIG = 0x8004745f
+ TIOCSPGRP = 0x80047476
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x80047465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSTSTAMP = 0x8008745a
+ TIOCSWINSZ = 0x80087467
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VTIME = 0x11
+ VWERASE = 0x4
+ WALTSIG = 0x4
+ WCONTINUED = 0x8
+ WCOREFLAG = 0x80
+ WNOHANG = 0x1
+ WSTOPPED = 0x7f
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADF = syscall.Errno(0x9)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x58)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x59)
+ EILSEQ = syscall.Errno(0x54)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EIPSEC = syscall.Errno(0x52)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x5b)
+ ELOOP = syscall.Errno(0x3e)
+ EMEDIUMTYPE = syscall.Errno(0x56)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x53)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOMEDIUM = syscall.Errno(0x55)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x5a)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x5b)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x57)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTHR = syscall.Signal(0x20)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "connection timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "IPsec processing failure",
+ 83: "attribute not found",
+ 84: "illegal byte sequence",
+ 85: "no medium found",
+ 86: "wrong medium type",
+ 87: "value too large to be stored in data type",
+ 88: "operation canceled",
+ 89: "identifier removed",
+ 90: "no message of desired type",
+ 91: "not supported",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "stopped (signal)",
+ 18: "stopped",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+ 32: "thread AST",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go b/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go
new file mode 100644
index 0000000..3ed0b26
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go
@@ -0,0 +1,1586 @@
+// mkerrors.sh
+// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- _const.go
+
+// +build arm,openbsd
+
+package unix
+
+import "syscall"
+
+const (
+ AF_APPLETALK = 0x10
+ AF_BLUETOOTH = 0x20
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_CNT = 0x15
+ AF_COIP = 0x14
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_E164 = 0x1a
+ AF_ECMA = 0x8
+ AF_ENCAP = 0x1c
+ AF_HYLINK = 0xf
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x18
+ AF_IPX = 0x17
+ AF_ISDN = 0x1a
+ AF_ISO = 0x7
+ AF_KEY = 0x1e
+ AF_LAT = 0xe
+ AF_LINK = 0x12
+ AF_LOCAL = 0x1
+ AF_MAX = 0x24
+ AF_MPLS = 0x21
+ AF_NATM = 0x1b
+ AF_NS = 0x6
+ AF_OSI = 0x7
+ AF_PUP = 0x4
+ AF_ROUTE = 0x11
+ AF_SIP = 0x1d
+ AF_SNA = 0xb
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ ARPHRD_ETHER = 0x1
+ ARPHRD_FRELAY = 0xf
+ ARPHRD_IEEE1394 = 0x18
+ ARPHRD_IEEE802 = 0x6
+ B0 = 0x0
+ B110 = 0x6e
+ B115200 = 0x1c200
+ B1200 = 0x4b0
+ B134 = 0x86
+ B14400 = 0x3840
+ B150 = 0x96
+ B1800 = 0x708
+ B19200 = 0x4b00
+ B200 = 0xc8
+ B230400 = 0x38400
+ B2400 = 0x960
+ B28800 = 0x7080
+ B300 = 0x12c
+ B38400 = 0x9600
+ B4800 = 0x12c0
+ B50 = 0x32
+ B57600 = 0xe100
+ B600 = 0x258
+ B7200 = 0x1c20
+ B75 = 0x4b
+ B76800 = 0x12c00
+ B9600 = 0x2580
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDIRFILT = 0x4004427c
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = 0xc008427b
+ BIOCGETIF = 0x4020426b
+ BIOCGFILDROP = 0x40044278
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRSIG = 0x40044273
+ BIOCGRTIMEOUT = 0x400c426e
+ BIOCGSTATS = 0x4008426f
+ BIOCIMMEDIATE = 0x80044270
+ BIOCLOCK = 0x20004276
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = 0xc0044266
+ BIOCSDIRFILT = 0x8004427d
+ BIOCSDLT = 0x8004427a
+ BIOCSETF = 0x80084267
+ BIOCSETIF = 0x8020426c
+ BIOCSETWF = 0x80084277
+ BIOCSFILDROP = 0x80044279
+ BIOCSHDRCMPLT = 0x80044275
+ BIOCSRSIG = 0x80044272
+ BIOCSRTIMEOUT = 0x800c426d
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_DIRECTION_IN = 0x1
+ BPF_DIRECTION_OUT = 0x2
+ 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_MAXBUFSIZE = 0x200000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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
+ CFLUSH = 0xf
+ CLOCAL = 0x8000
+ CREAD = 0x800
+ CS5 = 0x0
+ CS6 = 0x100
+ CS7 = 0x200
+ CS8 = 0x300
+ CSIZE = 0x300
+ CSTART = 0x11
+ CSTATUS = 0xff
+ CSTOP = 0x13
+ CSTOPB = 0x400
+ CSUSP = 0x1a
+ CTL_MAXNAME = 0xc
+ CTL_NET = 0x4
+ DIOCOSFPFLUSH = 0x2000444e
+ DLT_ARCNET = 0x7
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AX25 = 0x3
+ DLT_CHAOS = 0x5
+ DLT_C_HDLC = 0x68
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0xd
+ DLT_FDDI = 0xa
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_LOOP = 0xc
+ DLT_MPLS = 0xdb
+ DLT_NULL = 0x0
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0x10
+ DLT_PPP_ETHER = 0x33
+ DLT_PPP_SERIAL = 0x32
+ DLT_PRONET = 0x4
+ DLT_RAW = 0xe
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xf
+ DT_BLK = 0x6
+ DT_CHR = 0x2
+ DT_DIR = 0x4
+ DT_FIFO = 0x1
+ DT_LNK = 0xa
+ DT_REG = 0x8
+ DT_SOCK = 0xc
+ DT_UNKNOWN = 0x0
+ ECHO = 0x8
+ ECHOCTL = 0x40
+ ECHOE = 0x2
+ ECHOK = 0x4
+ ECHOKE = 0x1
+ ECHONL = 0x10
+ ECHOPRT = 0x20
+ EMT_TAGOVF = 0x1
+ EMUL_ENABLED = 0x1
+ EMUL_NATIVE = 0x2
+ ENDRUNDISC = 0x9
+ ETHERMIN = 0x2e
+ ETHERMTU = 0x5dc
+ ETHERTYPE_8023 = 0x4
+ ETHERTYPE_AARP = 0x80f3
+ ETHERTYPE_ACCTON = 0x8390
+ ETHERTYPE_AEONIC = 0x8036
+ ETHERTYPE_ALPHA = 0x814a
+ ETHERTYPE_AMBER = 0x6008
+ ETHERTYPE_AMOEBA = 0x8145
+ ETHERTYPE_AOE = 0x88a2
+ ETHERTYPE_APOLLO = 0x80f7
+ ETHERTYPE_APOLLODOMAIN = 0x8019
+ ETHERTYPE_APPLETALK = 0x809b
+ ETHERTYPE_APPLITEK = 0x80c7
+ ETHERTYPE_ARGONAUT = 0x803a
+ ETHERTYPE_ARP = 0x806
+ ETHERTYPE_AT = 0x809b
+ ETHERTYPE_ATALK = 0x809b
+ ETHERTYPE_ATOMIC = 0x86df
+ ETHERTYPE_ATT = 0x8069
+ ETHERTYPE_ATTSTANFORD = 0x8008
+ ETHERTYPE_AUTOPHON = 0x806a
+ ETHERTYPE_AXIS = 0x8856
+ ETHERTYPE_BCLOOP = 0x9003
+ ETHERTYPE_BOFL = 0x8102
+ ETHERTYPE_CABLETRON = 0x7034
+ ETHERTYPE_CHAOS = 0x804
+ ETHERTYPE_COMDESIGN = 0x806c
+ ETHERTYPE_COMPUGRAPHIC = 0x806d
+ ETHERTYPE_COUNTERPOINT = 0x8062
+ ETHERTYPE_CRONUS = 0x8004
+ ETHERTYPE_CRONUSVLN = 0x8003
+ ETHERTYPE_DCA = 0x1234
+ ETHERTYPE_DDE = 0x807b
+ ETHERTYPE_DEBNI = 0xaaaa
+ ETHERTYPE_DECAM = 0x8048
+ ETHERTYPE_DECCUST = 0x6006
+ ETHERTYPE_DECDIAG = 0x6005
+ ETHERTYPE_DECDNS = 0x803c
+ ETHERTYPE_DECDTS = 0x803e
+ ETHERTYPE_DECEXPER = 0x6000
+ ETHERTYPE_DECLAST = 0x8041
+ ETHERTYPE_DECLTM = 0x803f
+ ETHERTYPE_DECMUMPS = 0x6009
+ ETHERTYPE_DECNETBIOS = 0x8040
+ ETHERTYPE_DELTACON = 0x86de
+ ETHERTYPE_DIDDLE = 0x4321
+ ETHERTYPE_DLOG1 = 0x660
+ ETHERTYPE_DLOG2 = 0x661
+ ETHERTYPE_DN = 0x6003
+ ETHERTYPE_DOGFIGHT = 0x1989
+ ETHERTYPE_DSMD = 0x8039
+ ETHERTYPE_ECMA = 0x803
+ ETHERTYPE_ENCRYPT = 0x803d
+ ETHERTYPE_ES = 0x805d
+ ETHERTYPE_EXCELAN = 0x8010
+ ETHERTYPE_EXPERDATA = 0x8049
+ ETHERTYPE_FLIP = 0x8146
+ ETHERTYPE_FLOWCONTROL = 0x8808
+ ETHERTYPE_FRARP = 0x808
+ ETHERTYPE_GENDYN = 0x8068
+ ETHERTYPE_HAYES = 0x8130
+ ETHERTYPE_HIPPI_FP = 0x8180
+ ETHERTYPE_HITACHI = 0x8820
+ ETHERTYPE_HP = 0x8005
+ ETHERTYPE_IEEEPUP = 0xa00
+ ETHERTYPE_IEEEPUPAT = 0xa01
+ ETHERTYPE_IMLBL = 0x4c42
+ ETHERTYPE_IMLBLDIAG = 0x424c
+ ETHERTYPE_IP = 0x800
+ ETHERTYPE_IPAS = 0x876c
+ ETHERTYPE_IPV6 = 0x86dd
+ ETHERTYPE_IPX = 0x8137
+ ETHERTYPE_IPXNEW = 0x8037
+ ETHERTYPE_KALPANA = 0x8582
+ ETHERTYPE_LANBRIDGE = 0x8038
+ ETHERTYPE_LANPROBE = 0x8888
+ ETHERTYPE_LAT = 0x6004
+ ETHERTYPE_LBACK = 0x9000
+ ETHERTYPE_LITTLE = 0x8060
+ ETHERTYPE_LLDP = 0x88cc
+ ETHERTYPE_LOGICRAFT = 0x8148
+ ETHERTYPE_LOOPBACK = 0x9000
+ ETHERTYPE_MATRA = 0x807a
+ ETHERTYPE_MAX = 0xffff
+ ETHERTYPE_MERIT = 0x807c
+ ETHERTYPE_MICP = 0x873a
+ ETHERTYPE_MOPDL = 0x6001
+ ETHERTYPE_MOPRC = 0x6002
+ ETHERTYPE_MOTOROLA = 0x818d
+ ETHERTYPE_MPLS = 0x8847
+ ETHERTYPE_MPLS_MCAST = 0x8848
+ ETHERTYPE_MUMPS = 0x813f
+ ETHERTYPE_NBPCC = 0x3c04
+ ETHERTYPE_NBPCLAIM = 0x3c09
+ ETHERTYPE_NBPCLREQ = 0x3c05
+ ETHERTYPE_NBPCLRSP = 0x3c06
+ ETHERTYPE_NBPCREQ = 0x3c02
+ ETHERTYPE_NBPCRSP = 0x3c03
+ ETHERTYPE_NBPDG = 0x3c07
+ ETHERTYPE_NBPDGB = 0x3c08
+ ETHERTYPE_NBPDLTE = 0x3c0a
+ ETHERTYPE_NBPRAR = 0x3c0c
+ ETHERTYPE_NBPRAS = 0x3c0b
+ ETHERTYPE_NBPRST = 0x3c0d
+ ETHERTYPE_NBPSCD = 0x3c01
+ ETHERTYPE_NBPVCD = 0x3c00
+ ETHERTYPE_NBS = 0x802
+ ETHERTYPE_NCD = 0x8149
+ ETHERTYPE_NESTAR = 0x8006
+ ETHERTYPE_NETBEUI = 0x8191
+ ETHERTYPE_NOVELL = 0x8138
+ ETHERTYPE_NS = 0x600
+ ETHERTYPE_NSAT = 0x601
+ ETHERTYPE_NSCOMPAT = 0x807
+ ETHERTYPE_NTRAILER = 0x10
+ ETHERTYPE_OS9 = 0x7007
+ ETHERTYPE_OS9NET = 0x7009
+ ETHERTYPE_PACER = 0x80c6
+ ETHERTYPE_PAE = 0x888e
+ ETHERTYPE_PCS = 0x4242
+ ETHERTYPE_PLANNING = 0x8044
+ ETHERTYPE_PPP = 0x880b
+ ETHERTYPE_PPPOE = 0x8864
+ ETHERTYPE_PPPOEDISC = 0x8863
+ ETHERTYPE_PRIMENTS = 0x7031
+ ETHERTYPE_PUP = 0x200
+ ETHERTYPE_PUPAT = 0x200
+ ETHERTYPE_QINQ = 0x88a8
+ ETHERTYPE_RACAL = 0x7030
+ ETHERTYPE_RATIONAL = 0x8150
+ ETHERTYPE_RAWFR = 0x6559
+ ETHERTYPE_RCL = 0x1995
+ ETHERTYPE_RDP = 0x8739
+ ETHERTYPE_RETIX = 0x80f2
+ ETHERTYPE_REVARP = 0x8035
+ ETHERTYPE_SCA = 0x6007
+ ETHERTYPE_SECTRA = 0x86db
+ ETHERTYPE_SECUREDATA = 0x876d
+ ETHERTYPE_SGITW = 0x817e
+ ETHERTYPE_SG_BOUNCE = 0x8016
+ ETHERTYPE_SG_DIAG = 0x8013
+ ETHERTYPE_SG_NETGAMES = 0x8014
+ ETHERTYPE_SG_RESV = 0x8015
+ ETHERTYPE_SIMNET = 0x5208
+ ETHERTYPE_SLOW = 0x8809
+ ETHERTYPE_SNA = 0x80d5
+ ETHERTYPE_SNMP = 0x814c
+ ETHERTYPE_SONIX = 0xfaf5
+ ETHERTYPE_SPIDER = 0x809f
+ ETHERTYPE_SPRITE = 0x500
+ ETHERTYPE_STP = 0x8181
+ ETHERTYPE_TALARIS = 0x812b
+ ETHERTYPE_TALARISMC = 0x852b
+ ETHERTYPE_TCPCOMP = 0x876b
+ ETHERTYPE_TCPSM = 0x9002
+ ETHERTYPE_TEC = 0x814f
+ ETHERTYPE_TIGAN = 0x802f
+ ETHERTYPE_TRAIL = 0x1000
+ ETHERTYPE_TRANSETHER = 0x6558
+ ETHERTYPE_TYMSHARE = 0x802e
+ ETHERTYPE_UBBST = 0x7005
+ ETHERTYPE_UBDEBUG = 0x900
+ ETHERTYPE_UBDIAGLOOP = 0x7002
+ ETHERTYPE_UBDL = 0x7000
+ ETHERTYPE_UBNIU = 0x7001
+ ETHERTYPE_UBNMC = 0x7003
+ ETHERTYPE_VALID = 0x1600
+ ETHERTYPE_VARIAN = 0x80dd
+ ETHERTYPE_VAXELN = 0x803b
+ ETHERTYPE_VEECO = 0x8067
+ ETHERTYPE_VEXP = 0x805b
+ ETHERTYPE_VGLAB = 0x8131
+ ETHERTYPE_VINES = 0xbad
+ ETHERTYPE_VINESECHO = 0xbaf
+ ETHERTYPE_VINESLOOP = 0xbae
+ ETHERTYPE_VITAL = 0xff00
+ ETHERTYPE_VLAN = 0x8100
+ ETHERTYPE_VLTLMAN = 0x8080
+ ETHERTYPE_VPROD = 0x805c
+ ETHERTYPE_VURESERVED = 0x8147
+ ETHERTYPE_WATERLOO = 0x8130
+ ETHERTYPE_WELLFLEET = 0x8103
+ ETHERTYPE_X25 = 0x805
+ ETHERTYPE_X75 = 0x801
+ ETHERTYPE_XNSSM = 0x9001
+ ETHERTYPE_XTP = 0x817d
+ ETHER_ADDR_LEN = 0x6
+ ETHER_ALIGN = 0x2
+ ETHER_CRC_LEN = 0x4
+ ETHER_CRC_POLY_BE = 0x4c11db6
+ ETHER_CRC_POLY_LE = 0xedb88320
+ ETHER_HDR_LEN = 0xe
+ ETHER_MAX_DIX_LEN = 0x600
+ ETHER_MAX_LEN = 0x5ee
+ ETHER_MIN_LEN = 0x40
+ ETHER_TYPE_LEN = 0x2
+ ETHER_VLAN_ENCAP_LEN = 0x4
+ EVFILT_AIO = -0x3
+ EVFILT_PROC = -0x5
+ EVFILT_READ = -0x1
+ EVFILT_SIGNAL = -0x6
+ EVFILT_SYSCOUNT = 0x7
+ EVFILT_TIMER = -0x7
+ EVFILT_VNODE = -0x4
+ EVFILT_WRITE = -0x2
+ EV_ADD = 0x1
+ EV_CLEAR = 0x20
+ EV_DELETE = 0x2
+ EV_DISABLE = 0x8
+ EV_ENABLE = 0x4
+ EV_EOF = 0x8000
+ EV_ERROR = 0x4000
+ EV_FLAG1 = 0x2000
+ EV_ONESHOT = 0x10
+ EV_SYSFLAGS = 0xf000
+ EXTA = 0x4b00
+ EXTB = 0x9600
+ EXTPROC = 0x800
+ FD_CLOEXEC = 0x1
+ FD_SETSIZE = 0x400
+ FLUSHO = 0x800000
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0xa
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0x7
+ F_GETOWN = 0x5
+ F_RDLCK = 0x1
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x8
+ F_SETLKW = 0x9
+ F_SETOWN = 0x6
+ F_UNLCK = 0x2
+ F_WRLCK = 0x3
+ HUPCL = 0x4000
+ ICANON = 0x100
+ ICMP6_FILTER = 0x12
+ ICRNL = 0x100
+ IEXTEN = 0x400
+ IFAN_ARRIVAL = 0x0
+ IFAN_DEPARTURE = 0x1
+ IFA_ROUTE = 0x1
+ IFF_ALLMULTI = 0x200
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x8e52
+ IFF_DEBUG = 0x4
+ IFF_LINK0 = 0x1000
+ IFF_LINK1 = 0x2000
+ IFF_LINK2 = 0x4000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x8000
+ IFF_NOARP = 0x80
+ IFF_NOTRAILERS = 0x20
+ IFF_OACTIVE = 0x400
+ IFF_POINTOPOINT = 0x10
+ IFF_PROMISC = 0x100
+ IFF_RUNNING = 0x40
+ IFF_SIMPLEX = 0x800
+ IFF_UP = 0x1
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_A12MPPSWITCH = 0x82
+ IFT_AAL2 = 0xbb
+ IFT_AAL5 = 0x31
+ IFT_ADSL = 0x5e
+ IFT_AFLANE8023 = 0x3b
+ IFT_AFLANE8025 = 0x3c
+ IFT_ARAP = 0x58
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ASYNC = 0x54
+ IFT_ATM = 0x25
+ IFT_ATMDXI = 0x69
+ IFT_ATMFUNI = 0x6a
+ IFT_ATMIMA = 0x6b
+ IFT_ATMLOGICAL = 0x50
+ IFT_ATMRADIO = 0xbd
+ IFT_ATMSUBINTERFACE = 0x86
+ IFT_ATMVCIENDPT = 0xc2
+ IFT_ATMVIRTUAL = 0x95
+ IFT_BGPPOLICYACCOUNTING = 0xa2
+ IFT_BLUETOOTH = 0xf8
+ IFT_BRIDGE = 0xd1
+ IFT_BSC = 0x53
+ IFT_CARP = 0xf7
+ IFT_CCTEMUL = 0x3d
+ IFT_CEPT = 0x13
+ IFT_CES = 0x85
+ IFT_CHANNEL = 0x46
+ IFT_CNR = 0x55
+ IFT_COFFEE = 0x84
+ IFT_COMPOSITELINK = 0x9b
+ IFT_DCN = 0x8d
+ IFT_DIGITALPOWERLINE = 0x8a
+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
+ IFT_DLSW = 0x4a
+ IFT_DOCSCABLEDOWNSTREAM = 0x80
+ IFT_DOCSCABLEMACLAYER = 0x7f
+ IFT_DOCSCABLEUPSTREAM = 0x81
+ IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd
+ IFT_DS0 = 0x51
+ IFT_DS0BUNDLE = 0x52
+ IFT_DS1FDL = 0xaa
+ IFT_DS3 = 0x1e
+ IFT_DTM = 0x8c
+ IFT_DUMMY = 0xf1
+ IFT_DVBASILN = 0xac
+ IFT_DVBASIOUT = 0xad
+ IFT_DVBRCCDOWNSTREAM = 0x93
+ IFT_DVBRCCMACLAYER = 0x92
+ IFT_DVBRCCUPSTREAM = 0x94
+ IFT_ECONET = 0xce
+ IFT_ENC = 0xf4
+ IFT_EON = 0x19
+ IFT_EPLRS = 0x57
+ IFT_ESCON = 0x49
+ IFT_ETHER = 0x6
+ IFT_FAITH = 0xf3
+ IFT_FAST = 0x7d
+ IFT_FASTETHER = 0x3e
+ IFT_FASTETHERFX = 0x45
+ IFT_FDDI = 0xf
+ IFT_FIBRECHANNEL = 0x38
+ IFT_FRAMERELAYINTERCONNECT = 0x3a
+ IFT_FRAMERELAYMPI = 0x5c
+ IFT_FRDLCIENDPT = 0xc1
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_FRF16MFRBUNDLE = 0xa3
+ IFT_FRFORWARD = 0x9e
+ IFT_G703AT2MB = 0x43
+ IFT_G703AT64K = 0x42
+ IFT_GIF = 0xf0
+ IFT_GIGABITETHERNET = 0x75
+ IFT_GR303IDT = 0xb2
+ IFT_GR303RDT = 0xb1
+ IFT_H323GATEKEEPER = 0xa4
+ IFT_H323PROXY = 0xa5
+ IFT_HDH1822 = 0x3
+ IFT_HDLC = 0x76
+ IFT_HDSL2 = 0xa8
+ IFT_HIPERLAN2 = 0xb7
+ IFT_HIPPI = 0x2f
+ IFT_HIPPIINTERFACE = 0x39
+ IFT_HOSTPAD = 0x5a
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IBM370PARCHAN = 0x48
+ IFT_IDSL = 0x9a
+ IFT_IEEE1394 = 0x90
+ IFT_IEEE80211 = 0x47
+ IFT_IEEE80212 = 0x37
+ IFT_IEEE8023ADLAG = 0xa1
+ IFT_IFGSN = 0x91
+ IFT_IMT = 0xbe
+ IFT_INFINIBAND = 0xc7
+ IFT_INTERLEAVE = 0x7c
+ IFT_IP = 0x7e
+ IFT_IPFORWARD = 0x8e
+ IFT_IPOVERATM = 0x72
+ IFT_IPOVERCDLC = 0x6d
+ IFT_IPOVERCLAW = 0x6e
+ IFT_IPSWITCH = 0x4e
+ IFT_ISDN = 0x3f
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISDNS = 0x4b
+ IFT_ISDNU = 0x4c
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88025CRFPINT = 0x62
+ IFT_ISO88025DTR = 0x56
+ IFT_ISO88025FIBER = 0x73
+ IFT_ISO88026 = 0xa
+ IFT_ISUP = 0xb3
+ IFT_L2VLAN = 0x87
+ IFT_L3IPVLAN = 0x88
+ IFT_L3IPXVLAN = 0x89
+ IFT_LAPB = 0x10
+ IFT_LAPD = 0x4d
+ IFT_LAPF = 0x77
+ IFT_LINEGROUP = 0xd2
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MEDIAMAILOVERIP = 0x8b
+ IFT_MFSIGLINK = 0xa7
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_MPC = 0x71
+ IFT_MPLS = 0xa6
+ IFT_MPLSTUNNEL = 0x96
+ IFT_MSDSL = 0x8f
+ IFT_MVL = 0xbf
+ IFT_MYRINET = 0x63
+ IFT_NFAS = 0xaf
+ IFT_NSIP = 0x1b
+ IFT_OPTICALCHANNEL = 0xc3
+ IFT_OPTICALTRANSPORT = 0xc4
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PFLOG = 0xf5
+ IFT_PFLOW = 0xf9
+ IFT_PFSYNC = 0xf6
+ IFT_PLC = 0xae
+ IFT_PON155 = 0xcf
+ IFT_PON622 = 0xd0
+ IFT_POS = 0xab
+ IFT_PPP = 0x17
+ IFT_PPPMULTILINKBUNDLE = 0x6c
+ IFT_PROPATM = 0xc5
+ IFT_PROPBWAP2MP = 0xb8
+ IFT_PROPCNLS = 0x59
+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PROPWIRELESSP2P = 0x9d
+ IFT_PTPSERIAL = 0x16
+ IFT_PVC = 0xf2
+ IFT_Q2931 = 0xc9
+ IFT_QLLC = 0x44
+ IFT_RADIOMAC = 0xbc
+ IFT_RADSL = 0x5f
+ IFT_REACHDSL = 0xc0
+ IFT_RFC1483 = 0x9f
+ IFT_RS232 = 0x21
+ IFT_RSRB = 0x4f
+ IFT_SDLC = 0x11
+ IFT_SDSL = 0x60
+ IFT_SHDSL = 0xa9
+ IFT_SIP = 0x1f
+ IFT_SIPSIG = 0xcc
+ IFT_SIPTG = 0xcb
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETOVERHEADCHANNEL = 0xb9
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_SRP = 0x97
+ IFT_SS7SIGLINK = 0x9c
+ IFT_STACKTOSTACK = 0x6f
+ IFT_STARLAN = 0xb
+ IFT_T1 = 0x12
+ IFT_TDLC = 0x74
+ IFT_TELINK = 0xc8
+ IFT_TERMPAD = 0x5b
+ IFT_TR008 = 0xb0
+ IFT_TRANSPHDLC = 0x7b
+ IFT_TUNNEL = 0x83
+ IFT_ULTRA = 0x1d
+ IFT_USB = 0xa0
+ IFT_V11 = 0x40
+ IFT_V35 = 0x2d
+ IFT_V36 = 0x41
+ IFT_V37 = 0x78
+ IFT_VDSL = 0x61
+ IFT_VIRTUALIPADDRESS = 0x70
+ IFT_VIRTUALTG = 0xca
+ IFT_VOICEDID = 0xd5
+ IFT_VOICEEM = 0x64
+ IFT_VOICEEMFGD = 0xd3
+ IFT_VOICEENCAP = 0x67
+ IFT_VOICEFGDEANA = 0xd4
+ IFT_VOICEFXO = 0x65
+ IFT_VOICEFXS = 0x66
+ IFT_VOICEOVERATM = 0x98
+ IFT_VOICEOVERCABLE = 0xc6
+ IFT_VOICEOVERFRAMERELAY = 0x99
+ IFT_VOICEOVERIP = 0x68
+ IFT_X213 = 0x5d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25HUNTGROUP = 0x7a
+ IFT_X25MLP = 0x79
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_LOOPBACKNET = 0x7f
+ IN_RFC3021_HOST = 0x1
+ IN_RFC3021_NET = 0xfffffffe
+ IN_RFC3021_NSHIFT = 0x1f
+ IPPROTO_AH = 0x33
+ IPPROTO_CARP = 0x70
+ IPPROTO_DIVERT = 0x102
+ IPPROTO_DIVERT_INIT = 0x2
+ IPPROTO_DIVERT_RESP = 0x1
+ IPPROTO_DONE = 0x101
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_ENCAP = 0x62
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_ETHERIP = 0x61
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_GRE = 0x2f
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IP = 0x0
+ IPPROTO_IPCOMP = 0x6c
+ IPPROTO_IPIP = 0x4
+ IPPROTO_IPV4 = 0x4
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_MAX = 0x100
+ IPPROTO_MAXID = 0x103
+ IPPROTO_MOBILE = 0x37
+ IPPROTO_MPLS = 0x89
+ IPPROTO_NONE = 0x3b
+ IPPROTO_PFSYNC = 0xf0
+ IPPROTO_PIM = 0x67
+ IPPROTO_PUP = 0xc
+ IPPROTO_RAW = 0xff
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_TCP = 0x6
+ IPPROTO_TP = 0x1d
+ IPPROTO_UDP = 0x11
+ IPV6_AUTH_LEVEL = 0x35
+ IPV6_AUTOFLOWLABEL = 0x3b
+ IPV6_CHECKSUM = 0x1a
+ IPV6_DEFAULT_MULTICAST_HOPS = 0x1
+ IPV6_DEFAULT_MULTICAST_LOOP = 0x1
+ IPV6_DEFHLIM = 0x40
+ IPV6_DONTFRAG = 0x3e
+ IPV6_DSTOPTS = 0x32
+ IPV6_ESP_NETWORK_LEVEL = 0x37
+ IPV6_ESP_TRANS_LEVEL = 0x36
+ IPV6_FAITH = 0x1d
+ IPV6_FLOWINFO_MASK = 0xffffff0f
+ IPV6_FLOWLABEL_MASK = 0xffff0f00
+ IPV6_FRAGTTL = 0x78
+ IPV6_HLIMDEC = 0x1
+ IPV6_HOPLIMIT = 0x2f
+ IPV6_HOPOPTS = 0x31
+ IPV6_IPCOMP_LEVEL = 0x3c
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+ IPV6_MAXHLIM = 0xff
+ IPV6_MAXPACKET = 0xffff
+ IPV6_MMTU = 0x500
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_NEXTHOP = 0x30
+ IPV6_OPTIONS = 0x1
+ IPV6_PATHMTU = 0x2c
+ IPV6_PIPEX = 0x3f
+ IPV6_PKTINFO = 0x2e
+ IPV6_PORTRANGE = 0xe
+ IPV6_PORTRANGE_DEFAULT = 0x0
+ IPV6_PORTRANGE_HIGH = 0x1
+ IPV6_PORTRANGE_LOW = 0x2
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVDSTPORT = 0x40
+ IPV6_RECVHOPLIMIT = 0x25
+ IPV6_RECVHOPOPTS = 0x27
+ IPV6_RECVPATHMTU = 0x2b
+ IPV6_RECVPKTINFO = 0x24
+ IPV6_RECVRTHDR = 0x26
+ IPV6_RECVTCLASS = 0x39
+ IPV6_RTABLE = 0x1021
+ IPV6_RTHDR = 0x33
+ IPV6_RTHDRDSTOPTS = 0x23
+ IPV6_RTHDR_LOOSE = 0x0
+ IPV6_RTHDR_STRICT = 0x1
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SOCKOPT_RESERVED1 = 0x3
+ IPV6_TCLASS = 0x3d
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_USE_MIN_MTU = 0x2a
+ IPV6_V6ONLY = 0x1b
+ IPV6_VERSION = 0x60
+ IPV6_VERSION_MASK = 0xf0
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_AUTH_LEVEL = 0x14
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DIVERTFL = 0x1022
+ IP_DROP_MEMBERSHIP = 0xd
+ IP_ESP_NETWORK_LEVEL = 0x16
+ IP_ESP_TRANS_LEVEL = 0x15
+ IP_HDRINCL = 0x2
+ IP_IPCOMP_LEVEL = 0x1d
+ IP_IPSECFLOWINFO = 0x24
+ IP_IPSEC_LOCAL_AUTH = 0x1b
+ IP_IPSEC_LOCAL_CRED = 0x19
+ IP_IPSEC_LOCAL_ID = 0x17
+ IP_IPSEC_REMOTE_AUTH = 0x1c
+ IP_IPSEC_REMOTE_CRED = 0x1a
+ IP_IPSEC_REMOTE_ID = 0x18
+ IP_MAXPACKET = 0xffff
+ IP_MAX_MEMBERSHIPS = 0xfff
+ IP_MF = 0x2000
+ IP_MINTTL = 0x20
+ IP_MIN_MEMBERSHIPS = 0xf
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_LOOP = 0xb
+ IP_MULTICAST_TTL = 0xa
+ IP_OFFMASK = 0x1fff
+ IP_OPTIONS = 0x1
+ IP_PIPEX = 0x22
+ IP_PORTRANGE = 0x13
+ IP_PORTRANGE_DEFAULT = 0x0
+ IP_PORTRANGE_HIGH = 0x1
+ IP_PORTRANGE_LOW = 0x2
+ IP_RECVDSTADDR = 0x7
+ IP_RECVDSTPORT = 0x21
+ IP_RECVIF = 0x1e
+ IP_RECVOPTS = 0x5
+ IP_RECVRETOPTS = 0x6
+ IP_RECVRTABLE = 0x23
+ IP_RECVTTL = 0x1f
+ IP_RETOPTS = 0x8
+ IP_RF = 0x8000
+ IP_RTABLE = 0x1021
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ ISIG = 0x80
+ ISTRIP = 0x20
+ IXANY = 0x800
+ IXOFF = 0x400
+ IXON = 0x200
+ LCNT_OVERLOAD_FLUSH = 0x6
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x6
+ MADV_NORMAL = 0x0
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_SPACEAVAIL = 0x5
+ MADV_WILLNEED = 0x3
+ MAP_ANON = 0x1000
+ MAP_ANONYMOUS = 0x1000
+ MAP_COPY = 0x2
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_FLAGMASK = 0x3ff7
+ MAP_HASSEMAPHORE = 0x0
+ MAP_INHERIT = 0x0
+ MAP_INHERIT_COPY = 0x1
+ MAP_INHERIT_NONE = 0x2
+ MAP_INHERIT_SHARE = 0x0
+ MAP_INHERIT_ZERO = 0x3
+ MAP_NOEXTEND = 0x0
+ MAP_NORESERVE = 0x0
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x0
+ MAP_SHARED = 0x1
+ MAP_TRYFIXED = 0x0
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MSG_BCAST = 0x100
+ MSG_CMSG_CLOEXEC = 0x800
+ MSG_CTRUNC = 0x20
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_EOR = 0x8
+ MSG_MCAST = 0x200
+ MSG_NOSIGNAL = 0x400
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x10
+ MSG_WAITALL = 0x40
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x4
+ MS_SYNC = 0x2
+ NAME_MAX = 0xff
+ NET_RT_DUMP = 0x1
+ NET_RT_FLAGS = 0x2
+ NET_RT_IFLIST = 0x3
+ NET_RT_MAXID = 0x6
+ NET_RT_STATS = 0x4
+ NET_RT_TABLE = 0x5
+ NOFLSH = 0x80000000
+ NOTE_ATTRIB = 0x8
+ NOTE_CHILD = 0x4
+ NOTE_DELETE = 0x1
+ NOTE_EOF = 0x2
+ NOTE_EXEC = 0x20000000
+ NOTE_EXIT = 0x80000000
+ NOTE_EXTEND = 0x4
+ NOTE_FORK = 0x40000000
+ NOTE_LINK = 0x10
+ NOTE_LOWAT = 0x1
+ NOTE_PCTRLMASK = 0xf0000000
+ NOTE_PDATAMASK = 0xfffff
+ NOTE_RENAME = 0x20
+ NOTE_REVOKE = 0x40
+ NOTE_TRACK = 0x1
+ NOTE_TRACKERR = 0x2
+ NOTE_TRUNCATE = 0x80
+ NOTE_WRITE = 0x2
+ OCRNL = 0x10
+ ONLCR = 0x2
+ ONLRET = 0x80
+ ONOCR = 0x40
+ ONOEOT = 0x8
+ OPOST = 0x1
+ O_ACCMODE = 0x3
+ O_APPEND = 0x8
+ O_ASYNC = 0x40
+ O_CLOEXEC = 0x10000
+ O_CREAT = 0x200
+ O_DIRECTORY = 0x20000
+ O_DSYNC = 0x80
+ O_EXCL = 0x800
+ O_EXLOCK = 0x20
+ O_FSYNC = 0x80
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x8000
+ O_NOFOLLOW = 0x100
+ O_NONBLOCK = 0x4
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x80
+ O_SHLOCK = 0x10
+ O_SYNC = 0x80
+ O_TRUNC = 0x400
+ O_WRONLY = 0x1
+ PARENB = 0x1000
+ PARMRK = 0x8
+ PARODD = 0x2000
+ PENDIN = 0x20000000
+ PF_FLUSH = 0x1
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_NOFILE = 0x8
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_LABEL = 0xa
+ RTAX_MAX = 0xb
+ RTAX_NETMASK = 0x2
+ RTAX_SRC = 0x8
+ RTAX_SRCMASK = 0x9
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_LABEL = 0x400
+ RTA_NETMASK = 0x4
+ RTA_SRC = 0x100
+ RTA_SRCMASK = 0x200
+ RTF_ANNOUNCE = 0x4000
+ RTF_BLACKHOLE = 0x1000
+ RTF_BROADCAST = 0x400000
+ RTF_CLONED = 0x10000
+ RTF_CLONING = 0x100
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_FMASK = 0x70f808
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_LLINFO = 0x400
+ RTF_LOCAL = 0x200000
+ RTF_MASK = 0x80
+ RTF_MODIFIED = 0x20
+ RTF_MPATH = 0x40000
+ RTF_MPLS = 0x100000
+ RTF_PERMANENT_ARP = 0x2000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_PROTO3 = 0x2000
+ RTF_REJECT = 0x8
+ RTF_STATIC = 0x800
+ RTF_UP = 0x1
+ RTF_USETRAILERS = 0x8000
+ RTF_XRESOLVE = 0x200
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_DESYNC = 0x10
+ RTM_GET = 0x4
+ RTM_IFANNOUNCE = 0xf
+ RTM_IFINFO = 0xe
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MAXSIZE = 0x800
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_RTTUNIT = 0xf4240
+ RTM_VERSION = 0x5
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RT_TABLEID_MAX = 0xff
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ RUSAGE_THREAD = 0x1
+ SCM_RIGHTS = 0x1
+ SCM_TIMESTAMP = 0x4
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIOCADDMULTI = 0x80206931
+ SIOCAIFADDR = 0x8040691a
+ SIOCAIFGROUP = 0x80246987
+ SIOCALIFADDR = 0x8218691c
+ SIOCATMARK = 0x40047307
+ SIOCBRDGADD = 0x8054693c
+ SIOCBRDGADDS = 0x80546941
+ SIOCBRDGARL = 0x806e694d
+ SIOCBRDGDADDR = 0x81286947
+ SIOCBRDGDEL = 0x8054693d
+ SIOCBRDGDELS = 0x80546942
+ SIOCBRDGFLUSH = 0x80546948
+ SIOCBRDGFRL = 0x806e694e
+ SIOCBRDGGCACHE = 0xc0146941
+ SIOCBRDGGFD = 0xc0146952
+ SIOCBRDGGHT = 0xc0146951
+ SIOCBRDGGIFFLGS = 0xc054693e
+ SIOCBRDGGMA = 0xc0146953
+ SIOCBRDGGPARAM = 0xc03c6958
+ SIOCBRDGGPRI = 0xc0146950
+ SIOCBRDGGRL = 0xc028694f
+ SIOCBRDGGSIFS = 0xc054693c
+ SIOCBRDGGTO = 0xc0146946
+ SIOCBRDGIFS = 0xc0546942
+ SIOCBRDGRTS = 0xc0186943
+ SIOCBRDGSADDR = 0xc1286944
+ SIOCBRDGSCACHE = 0x80146940
+ SIOCBRDGSFD = 0x80146952
+ SIOCBRDGSHT = 0x80146951
+ SIOCBRDGSIFCOST = 0x80546955
+ SIOCBRDGSIFFLGS = 0x8054693f
+ SIOCBRDGSIFPRIO = 0x80546954
+ SIOCBRDGSMA = 0x80146953
+ SIOCBRDGSPRI = 0x80146950
+ SIOCBRDGSPROTO = 0x8014695a
+ SIOCBRDGSTO = 0x80146945
+ SIOCBRDGSTXHC = 0x80146959
+ SIOCDELMULTI = 0x80206932
+ SIOCDIFADDR = 0x80206919
+ SIOCDIFGROUP = 0x80246989
+ SIOCDIFPHYADDR = 0x80206949
+ SIOCDLIFADDR = 0x8218691e
+ SIOCGETKALIVE = 0xc01869a4
+ SIOCGETLABEL = 0x8020699a
+ SIOCGETPFLOW = 0xc02069fe
+ SIOCGETPFSYNC = 0xc02069f8
+ SIOCGETSGCNT = 0xc0147534
+ SIOCGETVIFCNT = 0xc0147533
+ SIOCGETVLAN = 0xc0206990
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = 0xc0206921
+ SIOCGIFASYNCMAP = 0xc020697c
+ SIOCGIFBRDADDR = 0xc0206923
+ SIOCGIFCONF = 0xc0086924
+ SIOCGIFDATA = 0xc020691b
+ SIOCGIFDESCR = 0xc0206981
+ SIOCGIFDSTADDR = 0xc0206922
+ SIOCGIFFLAGS = 0xc0206911
+ SIOCGIFGATTR = 0xc024698b
+ SIOCGIFGENERIC = 0xc020693a
+ SIOCGIFGMEMB = 0xc024698a
+ SIOCGIFGROUP = 0xc0246988
+ SIOCGIFHARDMTU = 0xc02069a5
+ SIOCGIFMEDIA = 0xc0286936
+ SIOCGIFMETRIC = 0xc0206917
+ SIOCGIFMTU = 0xc020697e
+ SIOCGIFNETMASK = 0xc0206925
+ SIOCGIFPDSTADDR = 0xc0206948
+ SIOCGIFPRIORITY = 0xc020699c
+ SIOCGIFPSRCADDR = 0xc0206947
+ SIOCGIFRDOMAIN = 0xc02069a0
+ SIOCGIFRTLABEL = 0xc0206983
+ SIOCGIFRXR = 0x802069aa
+ SIOCGIFTIMESLOT = 0xc0206986
+ SIOCGIFXFLAGS = 0xc020699e
+ SIOCGLIFADDR = 0xc218691d
+ SIOCGLIFPHYADDR = 0xc218694b
+ SIOCGLIFPHYRTABLE = 0xc02069a2
+ SIOCGLIFPHYTTL = 0xc02069a9
+ SIOCGLOWAT = 0x40047303
+ SIOCGPGRP = 0x40047309
+ SIOCGSPPPPARAMS = 0xc0206994
+ SIOCGVH = 0xc02069f6
+ SIOCGVNETID = 0xc02069a7
+ SIOCIFCREATE = 0x8020697a
+ SIOCIFDESTROY = 0x80206979
+ SIOCIFGCLONERS = 0xc00c6978
+ SIOCSETKALIVE = 0x801869a3
+ SIOCSETLABEL = 0x80206999
+ SIOCSETPFLOW = 0x802069fd
+ SIOCSETPFSYNC = 0x802069f7
+ SIOCSETVLAN = 0x8020698f
+ SIOCSHIWAT = 0x80047300
+ SIOCSIFADDR = 0x8020690c
+ SIOCSIFASYNCMAP = 0x8020697d
+ SIOCSIFBRDADDR = 0x80206913
+ SIOCSIFDESCR = 0x80206980
+ SIOCSIFDSTADDR = 0x8020690e
+ SIOCSIFFLAGS = 0x80206910
+ SIOCSIFGATTR = 0x8024698c
+ SIOCSIFGENERIC = 0x80206939
+ SIOCSIFLLADDR = 0x8020691f
+ SIOCSIFMEDIA = 0xc0206935
+ SIOCSIFMETRIC = 0x80206918
+ SIOCSIFMTU = 0x8020697f
+ SIOCSIFNETMASK = 0x80206916
+ SIOCSIFPHYADDR = 0x80406946
+ SIOCSIFPRIORITY = 0x8020699b
+ SIOCSIFRDOMAIN = 0x8020699f
+ SIOCSIFRTLABEL = 0x80206982
+ SIOCSIFTIMESLOT = 0x80206985
+ SIOCSIFXFLAGS = 0x8020699d
+ SIOCSLIFPHYADDR = 0x8218694a
+ SIOCSLIFPHYRTABLE = 0x802069a1
+ SIOCSLIFPHYTTL = 0x802069a8
+ SIOCSLOWAT = 0x80047302
+ SIOCSPGRP = 0x80047308
+ SIOCSSPPPPARAMS = 0x80206993
+ SIOCSVH = 0xc02069f5
+ SIOCSVNETID = 0x802069a6
+ SOCK_CLOEXEC = 0x8000
+ SOCK_DGRAM = 0x2
+ SOCK_NONBLOCK = 0x4000
+ SOCK_RAW = 0x3
+ SOCK_RDM = 0x4
+ SOCK_SEQPACKET = 0x5
+ SOCK_STREAM = 0x1
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_BINDANY = 0x1000
+ SO_BROADCAST = 0x20
+ SO_DEBUG = 0x1
+ SO_DONTROUTE = 0x10
+ SO_ERROR = 0x1007
+ SO_KEEPALIVE = 0x8
+ SO_LINGER = 0x80
+ SO_NETPROC = 0x1020
+ SO_OOBINLINE = 0x100
+ SO_PEERCRED = 0x1022
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVTIMEO = 0x1006
+ SO_REUSEADDR = 0x4
+ SO_REUSEPORT = 0x200
+ SO_RTABLE = 0x1021
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_SPLICE = 0x1023
+ SO_TIMESTAMP = 0x800
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ TCIFLUSH = 0x1
+ TCIOFLUSH = 0x3
+ TCOFLUSH = 0x2
+ TCP_MAXBURST = 0x4
+ TCP_MAXSEG = 0x2
+ TCP_MAXWIN = 0xffff
+ TCP_MAX_SACK = 0x3
+ TCP_MAX_WINSHIFT = 0xe
+ TCP_MD5SIG = 0x4
+ TCP_MSS = 0x200
+ TCP_NODELAY = 0x1
+ TCP_NOPUSH = 0x10
+ TCP_NSTATES = 0xb
+ TCP_SACK_ENABLE = 0x8
+ TCSAFLUSH = 0x2
+ TIOCCBRK = 0x2000747a
+ TIOCCDTR = 0x20007478
+ TIOCCONS = 0x80047462
+ TIOCDRAIN = 0x2000745e
+ TIOCEXCL = 0x2000740d
+ TIOCEXT = 0x80047460
+ TIOCFLAG_CLOCAL = 0x2
+ TIOCFLAG_CRTSCTS = 0x4
+ TIOCFLAG_MDMBUF = 0x8
+ TIOCFLAG_PPS = 0x10
+ TIOCFLAG_SOFTCAR = 0x1
+ TIOCFLUSH = 0x80047410
+ TIOCGETA = 0x402c7413
+ TIOCGETD = 0x4004741a
+ TIOCGFLAGS = 0x4004745d
+ TIOCGPGRP = 0x40047477
+ TIOCGSID = 0x40047463
+ TIOCGTSTAMP = 0x400c745b
+ TIOCGWINSZ = 0x40087468
+ TIOCMBIC = 0x8004746b
+ TIOCMBIS = 0x8004746c
+ TIOCMGET = 0x4004746a
+ TIOCMODG = 0x4004746a
+ TIOCMODS = 0x8004746d
+ TIOCMSET = 0x8004746d
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x20007471
+ TIOCNXCL = 0x2000740e
+ TIOCOUTQ = 0x40047473
+ TIOCPKT = 0x80047470
+ TIOCPKT_DATA = 0x0
+ TIOCPKT_DOSTOP = 0x20
+ TIOCPKT_FLUSHREAD = 0x1
+ TIOCPKT_FLUSHWRITE = 0x2
+ TIOCPKT_IOCTL = 0x40
+ TIOCPKT_NOSTOP = 0x10
+ TIOCPKT_START = 0x8
+ TIOCPKT_STOP = 0x4
+ TIOCREMOTE = 0x80047469
+ TIOCSBRK = 0x2000747b
+ TIOCSCTTY = 0x20007461
+ TIOCSDTR = 0x20007479
+ TIOCSETA = 0x802c7414
+ TIOCSETAF = 0x802c7416
+ TIOCSETAW = 0x802c7415
+ TIOCSETD = 0x8004741b
+ TIOCSFLAGS = 0x8004745c
+ TIOCSIG = 0x8004745f
+ TIOCSPGRP = 0x80047476
+ TIOCSTART = 0x2000746e
+ TIOCSTAT = 0x80047465
+ TIOCSTI = 0x80017472
+ TIOCSTOP = 0x2000746f
+ TIOCSTSTAMP = 0x8008745a
+ TIOCSWINSZ = 0x80087467
+ TIOCUCNTL = 0x80047466
+ TOSTOP = 0x400000
+ VDISCARD = 0xf
+ VDSUSP = 0xb
+ VEOF = 0x0
+ VEOL = 0x1
+ VEOL2 = 0x2
+ VERASE = 0x3
+ VINTR = 0x8
+ VKILL = 0x5
+ VLNEXT = 0xe
+ VMIN = 0x10
+ VQUIT = 0x9
+ VREPRINT = 0x6
+ VSTART = 0xc
+ VSTATUS = 0x12
+ VSTOP = 0xd
+ VSUSP = 0xa
+ VTIME = 0x11
+ VWERASE = 0x4
+ WALTSIG = 0x4
+ WCONTINUED = 0x8
+ WCOREFLAG = 0x80
+ WNOHANG = 0x1
+ WUNTRACED = 0x2
+)
+
+// Errors
+const (
+ E2BIG = syscall.Errno(0x7)
+ EACCES = syscall.Errno(0xd)
+ EADDRINUSE = syscall.Errno(0x30)
+ EADDRNOTAVAIL = syscall.Errno(0x31)
+ EAFNOSUPPORT = syscall.Errno(0x2f)
+ EAGAIN = syscall.Errno(0x23)
+ EALREADY = syscall.Errno(0x25)
+ EAUTH = syscall.Errno(0x50)
+ EBADF = syscall.Errno(0x9)
+ EBADRPC = syscall.Errno(0x48)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x58)
+ ECHILD = syscall.Errno(0xa)
+ ECONNABORTED = syscall.Errno(0x35)
+ ECONNREFUSED = syscall.Errno(0x3d)
+ ECONNRESET = syscall.Errno(0x36)
+ EDEADLK = syscall.Errno(0xb)
+ EDESTADDRREQ = syscall.Errno(0x27)
+ EDOM = syscall.Errno(0x21)
+ EDQUOT = syscall.Errno(0x45)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EFTYPE = syscall.Errno(0x4f)
+ EHOSTDOWN = syscall.Errno(0x40)
+ EHOSTUNREACH = syscall.Errno(0x41)
+ EIDRM = syscall.Errno(0x59)
+ EILSEQ = syscall.Errno(0x54)
+ EINPROGRESS = syscall.Errno(0x24)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EIPSEC = syscall.Errno(0x52)
+ EISCONN = syscall.Errno(0x38)
+ EISDIR = syscall.Errno(0x15)
+ ELAST = syscall.Errno(0x5b)
+ ELOOP = syscall.Errno(0x3e)
+ EMEDIUMTYPE = syscall.Errno(0x56)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x28)
+ ENAMETOOLONG = syscall.Errno(0x3f)
+ ENEEDAUTH = syscall.Errno(0x51)
+ ENETDOWN = syscall.Errno(0x32)
+ ENETRESET = syscall.Errno(0x34)
+ ENETUNREACH = syscall.Errno(0x33)
+ ENFILE = syscall.Errno(0x17)
+ ENOATTR = syscall.Errno(0x53)
+ ENOBUFS = syscall.Errno(0x37)
+ ENODEV = syscall.Errno(0x13)
+ ENOENT = syscall.Errno(0x2)
+ ENOEXEC = syscall.Errno(0x8)
+ ENOLCK = syscall.Errno(0x4d)
+ ENOMEDIUM = syscall.Errno(0x55)
+ ENOMEM = syscall.Errno(0xc)
+ ENOMSG = syscall.Errno(0x5a)
+ ENOPROTOOPT = syscall.Errno(0x2a)
+ ENOSPC = syscall.Errno(0x1c)
+ ENOSYS = syscall.Errno(0x4e)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x39)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x42)
+ ENOTSOCK = syscall.Errno(0x26)
+ ENOTSUP = syscall.Errno(0x5b)
+ ENOTTY = syscall.Errno(0x19)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x2d)
+ EOVERFLOW = syscall.Errno(0x57)
+ EPERM = syscall.Errno(0x1)
+ EPFNOSUPPORT = syscall.Errno(0x2e)
+ EPIPE = syscall.Errno(0x20)
+ EPROCLIM = syscall.Errno(0x43)
+ EPROCUNAVAIL = syscall.Errno(0x4c)
+ EPROGMISMATCH = syscall.Errno(0x4b)
+ EPROGUNAVAIL = syscall.Errno(0x4a)
+ EPROTONOSUPPORT = syscall.Errno(0x2b)
+ EPROTOTYPE = syscall.Errno(0x29)
+ ERANGE = syscall.Errno(0x22)
+ EREMOTE = syscall.Errno(0x47)
+ EROFS = syscall.Errno(0x1e)
+ ERPCMISMATCH = syscall.Errno(0x49)
+ ESHUTDOWN = syscall.Errno(0x3a)
+ ESOCKTNOSUPPORT = syscall.Errno(0x2c)
+ ESPIPE = syscall.Errno(0x1d)
+ ESRCH = syscall.Errno(0x3)
+ ESTALE = syscall.Errno(0x46)
+ ETIMEDOUT = syscall.Errno(0x3c)
+ ETOOMANYREFS = syscall.Errno(0x3b)
+ ETXTBSY = syscall.Errno(0x1a)
+ EUSERS = syscall.Errno(0x44)
+ EWOULDBLOCK = syscall.Errno(0x23)
+ EXDEV = syscall.Errno(0x12)
+)
+
+// Signals
+const (
+ SIGABRT = syscall.Signal(0x6)
+ SIGALRM = syscall.Signal(0xe)
+ SIGBUS = syscall.Signal(0xa)
+ SIGCHLD = syscall.Signal(0x14)
+ SIGCONT = syscall.Signal(0x13)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x1d)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x17)
+ SIGIOT = syscall.Signal(0x6)
+ SIGKILL = syscall.Signal(0x9)
+ SIGPIPE = syscall.Signal(0xd)
+ SIGPROF = syscall.Signal(0x1b)
+ SIGQUIT = syscall.Signal(0x3)
+ SIGSEGV = syscall.Signal(0xb)
+ SIGSTOP = syscall.Signal(0x11)
+ SIGSYS = syscall.Signal(0xc)
+ SIGTERM = syscall.Signal(0xf)
+ SIGTHR = syscall.Signal(0x20)
+ SIGTRAP = syscall.Signal(0x5)
+ SIGTSTP = syscall.Signal(0x12)
+ SIGTTIN = syscall.Signal(0x15)
+ SIGTTOU = syscall.Signal(0x16)
+ SIGURG = syscall.Signal(0x10)
+ SIGUSR1 = syscall.Signal(0x1e)
+ SIGUSR2 = syscall.Signal(0x1f)
+ SIGVTALRM = syscall.Signal(0x1a)
+ SIGWINCH = syscall.Signal(0x1c)
+ SIGXCPU = syscall.Signal(0x18)
+ SIGXFSZ = syscall.Signal(0x19)
+)
+
+// 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: "device not configured",
+ 7: "argument list too long",
+ 8: "exec format error",
+ 9: "bad file descriptor",
+ 10: "no child processes",
+ 11: "resource deadlock avoided",
+ 12: "cannot allocate memory",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "operation not supported by 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: "result too large",
+ 35: "resource temporarily unavailable",
+ 36: "operation now in progress",
+ 37: "operation already in progress",
+ 38: "socket operation on non-socket",
+ 39: "destination address required",
+ 40: "message too long",
+ 41: "protocol wrong type for socket",
+ 42: "protocol not available",
+ 43: "protocol not supported",
+ 44: "socket type not supported",
+ 45: "operation not supported",
+ 46: "protocol family not supported",
+ 47: "address family not supported by protocol family",
+ 48: "address already in use",
+ 49: "can't assign requested address",
+ 50: "network is down",
+ 51: "network is unreachable",
+ 52: "network dropped connection on reset",
+ 53: "software caused connection abort",
+ 54: "connection reset by peer",
+ 55: "no buffer space available",
+ 56: "socket is already connected",
+ 57: "socket is not connected",
+ 58: "can't send after socket shutdown",
+ 59: "too many references: can't splice",
+ 60: "connection timed out",
+ 61: "connection refused",
+ 62: "too many levels of symbolic links",
+ 63: "file name too long",
+ 64: "host is down",
+ 65: "no route to host",
+ 66: "directory not empty",
+ 67: "too many processes",
+ 68: "too many users",
+ 69: "disc quota exceeded",
+ 70: "stale NFS file handle",
+ 71: "too many levels of remote in path",
+ 72: "RPC struct is bad",
+ 73: "RPC version wrong",
+ 74: "RPC prog. not avail",
+ 75: "program version wrong",
+ 76: "bad procedure for program",
+ 77: "no locks available",
+ 78: "function not implemented",
+ 79: "inappropriate file type or format",
+ 80: "authentication error",
+ 81: "need authenticator",
+ 82: "IPsec processing failure",
+ 83: "attribute not found",
+ 84: "illegal byte sequence",
+ 85: "no medium found",
+ 86: "wrong medium type",
+ 87: "value too large to be stored in data type",
+ 88: "operation canceled",
+ 89: "identifier removed",
+ 90: "no message of desired type",
+ 91: "not supported",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/BPT trap",
+ 6: "abort trap",
+ 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: "urgent I/O condition",
+ 17: "stopped (signal)",
+ 18: "stopped",
+ 19: "continued",
+ 20: "child exited",
+ 21: "stopped (tty input)",
+ 22: "stopped (tty output)",
+ 23: "I/O possible",
+ 24: "cputime limit exceeded",
+ 25: "filesize limit exceeded",
+ 26: "virtual timer expired",
+ 27: "profiling timer expired",
+ 28: "window size changes",
+ 29: "information request",
+ 30: "user defined signal 1",
+ 31: "user defined signal 2",
+ 32: "thread AST",
+}
diff --git a/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go
new file mode 100644
index 0000000..81e83d7
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go
@@ -0,0 +1,1483 @@
+// mkerrors.sh -m64
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,solaris
+
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs -- -m64 _const.go
+
+package unix
+
+import "syscall"
+
+const (
+ AF_802 = 0x12
+ AF_APPLETALK = 0x10
+ AF_CCITT = 0xa
+ AF_CHAOS = 0x5
+ AF_DATAKIT = 0x9
+ AF_DECnet = 0xc
+ AF_DLI = 0xd
+ AF_ECMA = 0x8
+ AF_FILE = 0x1
+ AF_GOSIP = 0x16
+ AF_HYLINK = 0xf
+ AF_IMPLINK = 0x3
+ AF_INET = 0x2
+ AF_INET6 = 0x1a
+ AF_INET_OFFLOAD = 0x1e
+ AF_IPX = 0x17
+ AF_KEY = 0x1b
+ AF_LAT = 0xe
+ AF_LINK = 0x19
+ AF_LOCAL = 0x1
+ AF_MAX = 0x20
+ AF_NBS = 0x7
+ AF_NCA = 0x1c
+ AF_NIT = 0x11
+ AF_NS = 0x6
+ AF_OSI = 0x13
+ AF_OSINET = 0x15
+ AF_PACKET = 0x20
+ AF_POLICY = 0x1d
+ AF_PUP = 0x4
+ AF_ROUTE = 0x18
+ AF_SNA = 0xb
+ AF_TRILL = 0x1f
+ AF_UNIX = 0x1
+ AF_UNSPEC = 0x0
+ AF_X25 = 0x14
+ ARPHRD_ARCNET = 0x7
+ ARPHRD_ATM = 0x10
+ ARPHRD_AX25 = 0x3
+ ARPHRD_CHAOS = 0x5
+ ARPHRD_EETHER = 0x2
+ ARPHRD_ETHER = 0x1
+ ARPHRD_FC = 0x12
+ ARPHRD_FRAME = 0xf
+ ARPHRD_HDLC = 0x11
+ ARPHRD_IB = 0x20
+ ARPHRD_IEEE802 = 0x6
+ ARPHRD_IPATM = 0x13
+ ARPHRD_METRICOM = 0x17
+ ARPHRD_TUNNEL = 0x1f
+ B0 = 0x0
+ B110 = 0x3
+ B115200 = 0x12
+ B1200 = 0x9
+ B134 = 0x4
+ B150 = 0x5
+ B153600 = 0x13
+ B1800 = 0xa
+ B19200 = 0xe
+ B200 = 0x6
+ B230400 = 0x14
+ B2400 = 0xb
+ B300 = 0x7
+ B307200 = 0x15
+ B38400 = 0xf
+ B460800 = 0x16
+ B4800 = 0xc
+ B50 = 0x1
+ B57600 = 0x10
+ B600 = 0x8
+ B75 = 0x2
+ B76800 = 0x11
+ B921600 = 0x17
+ B9600 = 0xd
+ BIOCFLUSH = 0x20004268
+ BIOCGBLEN = 0x40044266
+ BIOCGDLT = 0x4004426a
+ BIOCGDLTLIST = -0x3fefbd89
+ BIOCGDLTLIST32 = -0x3ff7bd89
+ BIOCGETIF = 0x4020426b
+ BIOCGETLIF = 0x4078426b
+ BIOCGHDRCMPLT = 0x40044274
+ BIOCGRTIMEOUT = 0x4010427b
+ BIOCGRTIMEOUT32 = 0x4008427b
+ BIOCGSEESENT = 0x40044278
+ BIOCGSTATS = 0x4080426f
+ BIOCGSTATSOLD = 0x4008426f
+ BIOCIMMEDIATE = -0x7ffbbd90
+ BIOCPROMISC = 0x20004269
+ BIOCSBLEN = -0x3ffbbd9a
+ BIOCSDLT = -0x7ffbbd8a
+ BIOCSETF = -0x7fefbd99
+ BIOCSETF32 = -0x7ff7bd99
+ BIOCSETIF = -0x7fdfbd94
+ BIOCSETLIF = -0x7f87bd94
+ BIOCSHDRCMPLT = -0x7ffbbd8b
+ BIOCSRTIMEOUT = -0x7fefbd86
+ BIOCSRTIMEOUT32 = -0x7ff7bd86
+ BIOCSSEESENT = -0x7ffbbd87
+ BIOCSTCPF = -0x7fefbd8e
+ BIOCSUDPF = -0x7fefbd8d
+ BIOCVERSION = 0x40044271
+ BPF_A = 0x10
+ BPF_ABS = 0x20
+ BPF_ADD = 0x0
+ BPF_ALIGNMENT = 0x4
+ BPF_ALU = 0x4
+ BPF_AND = 0x50
+ BPF_B = 0x10
+ BPF_DFLTBUFSIZE = 0x100000
+ 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_MAXBUFSIZE = 0x1000000
+ BPF_MAXINSNS = 0x200
+ BPF_MEM = 0x60
+ BPF_MEMWORDS = 0x10
+ BPF_MINBUFSIZE = 0x20
+ BPF_MINOR_VERSION = 0x1
+ BPF_MISC = 0x7
+ BPF_MSH = 0xa0
+ BPF_MUL = 0x20
+ BPF_NEG = 0x80
+ BPF_OR = 0x40
+ BPF_RELEASE = 0x30bb6
+ 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
+ CBAUD = 0xf
+ CFLUSH = 0xf
+ CIBAUD = 0xf0000
+ CLOCAL = 0x800
+ CLOCK_HIGHRES = 0x4
+ CLOCK_LEVEL = 0xa
+ CLOCK_MONOTONIC = 0x4
+ CLOCK_PROCESS_CPUTIME_ID = 0x5
+ CLOCK_PROF = 0x2
+ CLOCK_REALTIME = 0x3
+ CLOCK_THREAD_CPUTIME_ID = 0x2
+ CLOCK_VIRTUAL = 0x1
+ CR0 = 0x0
+ CR1 = 0x200
+ CR2 = 0x400
+ CR3 = 0x600
+ CRDLY = 0x600
+ CREAD = 0x80
+ CRTSCTS = 0x80000000
+ CS5 = 0x0
+ CS6 = 0x10
+ CS7 = 0x20
+ CS8 = 0x30
+ CSIZE = 0x30
+ CSTART = 0x11
+ CSTATUS = 0x14
+ CSTOP = 0x13
+ CSTOPB = 0x40
+ CSUSP = 0x1a
+ CSWTCH = 0x1a
+ DLT_AIRONET_HEADER = 0x78
+ DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
+ DLT_ARCNET = 0x7
+ DLT_ARCNET_LINUX = 0x81
+ DLT_ATM_CLIP = 0x13
+ DLT_ATM_RFC1483 = 0xb
+ DLT_AURORA = 0x7e
+ DLT_AX25 = 0x3
+ DLT_BACNET_MS_TP = 0xa5
+ DLT_CHAOS = 0x5
+ DLT_CISCO_IOS = 0x76
+ DLT_C_HDLC = 0x68
+ DLT_DOCSIS = 0x8f
+ DLT_ECONET = 0x73
+ DLT_EN10MB = 0x1
+ DLT_EN3MB = 0x2
+ DLT_ENC = 0x6d
+ DLT_ERF_ETH = 0xaf
+ DLT_ERF_POS = 0xb0
+ DLT_FDDI = 0xa
+ DLT_FRELAY = 0x6b
+ DLT_GCOM_SERIAL = 0xad
+ DLT_GCOM_T1E1 = 0xac
+ DLT_GPF_F = 0xab
+ DLT_GPF_T = 0xaa
+ DLT_GPRS_LLC = 0xa9
+ DLT_HDLC = 0x10
+ DLT_HHDLC = 0x79
+ DLT_HIPPI = 0xf
+ DLT_IBM_SN = 0x92
+ DLT_IBM_SP = 0x91
+ DLT_IEEE802 = 0x6
+ DLT_IEEE802_11 = 0x69
+ DLT_IEEE802_11_RADIO = 0x7f
+ DLT_IEEE802_11_RADIO_AVS = 0xa3
+ DLT_IPNET = 0xe2
+ DLT_IPOIB = 0xa2
+ DLT_IP_OVER_FC = 0x7a
+ DLT_JUNIPER_ATM1 = 0x89
+ DLT_JUNIPER_ATM2 = 0x87
+ DLT_JUNIPER_CHDLC = 0xb5
+ DLT_JUNIPER_ES = 0x84
+ DLT_JUNIPER_ETHER = 0xb2
+ DLT_JUNIPER_FRELAY = 0xb4
+ DLT_JUNIPER_GGSN = 0x85
+ DLT_JUNIPER_MFR = 0x86
+ DLT_JUNIPER_MLFR = 0x83
+ DLT_JUNIPER_MLPPP = 0x82
+ DLT_JUNIPER_MONITOR = 0xa4
+ DLT_JUNIPER_PIC_PEER = 0xae
+ DLT_JUNIPER_PPP = 0xb3
+ DLT_JUNIPER_PPPOE = 0xa7
+ DLT_JUNIPER_PPPOE_ATM = 0xa8
+ DLT_JUNIPER_SERVICES = 0x88
+ DLT_LINUX_IRDA = 0x90
+ DLT_LINUX_LAPD = 0xb1
+ DLT_LINUX_SLL = 0x71
+ DLT_LOOP = 0x6c
+ DLT_LTALK = 0x72
+ DLT_MTP2 = 0x8c
+ DLT_MTP2_WITH_PHDR = 0x8b
+ DLT_MTP3 = 0x8d
+ DLT_NULL = 0x0
+ DLT_PCI_EXP = 0x7d
+ DLT_PFLOG = 0x75
+ DLT_PFSYNC = 0x12
+ DLT_PPP = 0x9
+ DLT_PPP_BSDOS = 0xe
+ DLT_PPP_PPPD = 0xa6
+ DLT_PRISM_HEADER = 0x77
+ DLT_PRONET = 0x4
+ DLT_RAW = 0xc
+ DLT_RAWAF_MASK = 0x2240000
+ DLT_RIO = 0x7c
+ DLT_SCCP = 0x8e
+ DLT_SLIP = 0x8
+ DLT_SLIP_BSDOS = 0xd
+ DLT_SUNATM = 0x7b
+ DLT_SYMANTEC_FIREWALL = 0x63
+ DLT_TZSP = 0x80
+ ECHO = 0x8
+ ECHOCTL = 0x200
+ ECHOE = 0x10
+ ECHOK = 0x20
+ ECHOKE = 0x800
+ ECHONL = 0x40
+ ECHOPRT = 0x400
+ EMPTY_SET = 0x0
+ EMT_CPCOVF = 0x1
+ EQUALITY_CHECK = 0x0
+ EXTA = 0xe
+ EXTB = 0xf
+ FD_CLOEXEC = 0x1
+ FD_NFDBITS = 0x40
+ FD_SETSIZE = 0x10000
+ FF0 = 0x0
+ FF1 = 0x8000
+ FFDLY = 0x8000
+ FLUSHALL = 0x1
+ FLUSHDATA = 0x0
+ FLUSHO = 0x2000
+ F_ALLOCSP = 0xa
+ F_ALLOCSP64 = 0xa
+ F_BADFD = 0x2e
+ F_BLKSIZE = 0x13
+ F_BLOCKS = 0x12
+ F_CHKFL = 0x8
+ F_COMPAT = 0x8
+ F_DUP2FD = 0x9
+ F_DUP2FD_CLOEXEC = 0x24
+ F_DUPFD = 0x0
+ F_DUPFD_CLOEXEC = 0x25
+ F_FLOCK = 0x35
+ F_FLOCK64 = 0x35
+ F_FLOCKW = 0x36
+ F_FLOCKW64 = 0x36
+ F_FREESP = 0xb
+ F_FREESP64 = 0xb
+ F_GETFD = 0x1
+ F_GETFL = 0x3
+ F_GETLK = 0xe
+ F_GETLK64 = 0xe
+ F_GETOWN = 0x17
+ F_GETXFL = 0x2d
+ F_HASREMOTELOCKS = 0x1a
+ F_ISSTREAM = 0xd
+ F_MANDDNY = 0x10
+ F_MDACC = 0x20
+ F_NODNY = 0x0
+ F_NPRIV = 0x10
+ F_OFD_GETLK = 0x2f
+ F_OFD_GETLK64 = 0x2f
+ F_OFD_SETLK = 0x30
+ F_OFD_SETLK64 = 0x30
+ F_OFD_SETLKW = 0x31
+ F_OFD_SETLKW64 = 0x31
+ F_PRIV = 0xf
+ F_QUOTACTL = 0x11
+ F_RDACC = 0x1
+ F_RDDNY = 0x1
+ F_RDLCK = 0x1
+ F_REVOKE = 0x19
+ F_RMACC = 0x4
+ F_RMDNY = 0x4
+ F_RWACC = 0x3
+ F_RWDNY = 0x3
+ F_SETFD = 0x2
+ F_SETFL = 0x4
+ F_SETLK = 0x6
+ F_SETLK64 = 0x6
+ F_SETLK64_NBMAND = 0x2a
+ F_SETLKW = 0x7
+ F_SETLKW64 = 0x7
+ F_SETLK_NBMAND = 0x2a
+ F_SETOWN = 0x18
+ F_SHARE = 0x28
+ F_SHARE_NBMAND = 0x2b
+ F_UNLCK = 0x3
+ F_UNLKSYS = 0x4
+ F_UNSHARE = 0x29
+ F_WRACC = 0x2
+ F_WRDNY = 0x2
+ F_WRLCK = 0x2
+ HUPCL = 0x400
+ IBSHIFT = 0x10
+ ICANON = 0x2
+ ICRNL = 0x100
+ IEXTEN = 0x8000
+ IFF_ADDRCONF = 0x80000
+ IFF_ALLMULTI = 0x200
+ IFF_ANYCAST = 0x400000
+ IFF_BROADCAST = 0x2
+ IFF_CANTCHANGE = 0x7f203003b5a
+ IFF_COS_ENABLED = 0x200000000
+ IFF_DEBUG = 0x4
+ IFF_DEPRECATED = 0x40000
+ IFF_DHCPRUNNING = 0x4000
+ IFF_DUPLICATE = 0x4000000000
+ IFF_FAILED = 0x10000000
+ IFF_FIXEDMTU = 0x1000000000
+ IFF_INACTIVE = 0x40000000
+ IFF_INTELLIGENT = 0x400
+ IFF_IPMP = 0x8000000000
+ IFF_IPMP_CANTCHANGE = 0x10000000
+ IFF_IPMP_INVALID = 0x1ec200080
+ IFF_IPV4 = 0x1000000
+ IFF_IPV6 = 0x2000000
+ IFF_L3PROTECT = 0x40000000000
+ IFF_LOOPBACK = 0x8
+ IFF_MULTICAST = 0x800
+ IFF_MULTI_BCAST = 0x1000
+ IFF_NOACCEPT = 0x4000000
+ IFF_NOARP = 0x80
+ IFF_NOFAILOVER = 0x8000000
+ IFF_NOLINKLOCAL = 0x20000000000
+ IFF_NOLOCAL = 0x20000
+ IFF_NONUD = 0x200000
+ IFF_NORTEXCH = 0x800000
+ IFF_NOTRAILERS = 0x20
+ IFF_NOXMIT = 0x10000
+ IFF_OFFLINE = 0x80000000
+ IFF_POINTOPOINT = 0x10
+ IFF_PREFERRED = 0x400000000
+ IFF_PRIVATE = 0x8000
+ IFF_PROMISC = 0x100
+ IFF_ROUTER = 0x100000
+ IFF_RUNNING = 0x40
+ IFF_STANDBY = 0x20000000
+ IFF_TEMPORARY = 0x800000000
+ IFF_UNNUMBERED = 0x2000
+ IFF_UP = 0x1
+ IFF_VIRTUAL = 0x2000000000
+ IFF_VRRP = 0x10000000000
+ IFF_XRESOLV = 0x100000000
+ IFNAMSIZ = 0x10
+ IFT_1822 = 0x2
+ IFT_6TO4 = 0xca
+ IFT_AAL5 = 0x31
+ IFT_ARCNET = 0x23
+ IFT_ARCNETPLUS = 0x24
+ IFT_ATM = 0x25
+ IFT_CEPT = 0x13
+ IFT_DS3 = 0x1e
+ IFT_EON = 0x19
+ IFT_ETHER = 0x6
+ IFT_FDDI = 0xf
+ IFT_FRELAY = 0x20
+ IFT_FRELAYDCE = 0x2c
+ IFT_HDH1822 = 0x3
+ IFT_HIPPI = 0x2f
+ IFT_HSSI = 0x2e
+ IFT_HY = 0xe
+ IFT_IB = 0xc7
+ IFT_IPV4 = 0xc8
+ IFT_IPV6 = 0xc9
+ IFT_ISDNBASIC = 0x14
+ IFT_ISDNPRIMARY = 0x15
+ IFT_ISO88022LLC = 0x29
+ IFT_ISO88023 = 0x7
+ IFT_ISO88024 = 0x8
+ IFT_ISO88025 = 0x9
+ IFT_ISO88026 = 0xa
+ IFT_LAPB = 0x10
+ IFT_LOCALTALK = 0x2a
+ IFT_LOOP = 0x18
+ IFT_MIOX25 = 0x26
+ IFT_MODEM = 0x30
+ IFT_NSIP = 0x1b
+ IFT_OTHER = 0x1
+ IFT_P10 = 0xc
+ IFT_P80 = 0xd
+ IFT_PARA = 0x22
+ IFT_PPP = 0x17
+ IFT_PROPMUX = 0x36
+ IFT_PROPVIRTUAL = 0x35
+ IFT_PTPSERIAL = 0x16
+ IFT_RS232 = 0x21
+ IFT_SDLC = 0x11
+ IFT_SIP = 0x1f
+ IFT_SLIP = 0x1c
+ IFT_SMDSDXI = 0x2b
+ IFT_SMDSICIP = 0x34
+ IFT_SONET = 0x27
+ IFT_SONETPATH = 0x32
+ IFT_SONETVT = 0x33
+ IFT_STARLAN = 0xb
+ IFT_T1 = 0x12
+ IFT_ULTRA = 0x1d
+ IFT_V35 = 0x2d
+ IFT_X25 = 0x5
+ IFT_X25DDN = 0x4
+ IFT_X25PLE = 0x28
+ IFT_XETHER = 0x1a
+ IGNBRK = 0x1
+ IGNCR = 0x80
+ IGNPAR = 0x4
+ IMAXBEL = 0x2000
+ INLCR = 0x40
+ INPCK = 0x10
+ IN_AUTOCONF_MASK = 0xffff0000
+ IN_AUTOCONF_NET = 0xa9fe0000
+ 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_CLASSD_HOST = 0xfffffff
+ IN_CLASSD_NET = 0xf0000000
+ IN_CLASSD_NSHIFT = 0x1c
+ IN_CLASSE_NET = 0xffffffff
+ IN_LOOPBACKNET = 0x7f
+ IN_PRIVATE12_MASK = 0xfff00000
+ IN_PRIVATE12_NET = 0xac100000
+ IN_PRIVATE16_MASK = 0xffff0000
+ IN_PRIVATE16_NET = 0xc0a80000
+ IN_PRIVATE8_MASK = 0xff000000
+ IN_PRIVATE8_NET = 0xa000000
+ IPPROTO_AH = 0x33
+ IPPROTO_DSTOPTS = 0x3c
+ IPPROTO_EGP = 0x8
+ IPPROTO_ENCAP = 0x4
+ IPPROTO_EON = 0x50
+ IPPROTO_ESP = 0x32
+ IPPROTO_FRAGMENT = 0x2c
+ IPPROTO_GGP = 0x3
+ IPPROTO_HELLO = 0x3f
+ IPPROTO_HOPOPTS = 0x0
+ IPPROTO_ICMP = 0x1
+ IPPROTO_ICMPV6 = 0x3a
+ IPPROTO_IDP = 0x16
+ IPPROTO_IGMP = 0x2
+ IPPROTO_IP = 0x0
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_MAX = 0x100
+ IPPROTO_ND = 0x4d
+ IPPROTO_NONE = 0x3b
+ IPPROTO_OSPF = 0x59
+ IPPROTO_PIM = 0x67
+ IPPROTO_PUP = 0xc
+ IPPROTO_RAW = 0xff
+ IPPROTO_ROUTING = 0x2b
+ IPPROTO_RSVP = 0x2e
+ IPPROTO_SCTP = 0x84
+ IPPROTO_TCP = 0x6
+ IPPROTO_UDP = 0x11
+ IPV6_ADD_MEMBERSHIP = 0x9
+ IPV6_BOUND_IF = 0x41
+ IPV6_CHECKSUM = 0x18
+ IPV6_DONTFRAG = 0x21
+ IPV6_DROP_MEMBERSHIP = 0xa
+ IPV6_DSTOPTS = 0xf
+ IPV6_FLOWINFO_FLOWLABEL = 0xffff0f00
+ IPV6_FLOWINFO_TCLASS = 0xf00f
+ IPV6_HOPLIMIT = 0xc
+ IPV6_HOPOPTS = 0xe
+ IPV6_JOIN_GROUP = 0x9
+ IPV6_LEAVE_GROUP = 0xa
+ IPV6_MULTICAST_HOPS = 0x7
+ IPV6_MULTICAST_IF = 0x6
+ IPV6_MULTICAST_LOOP = 0x8
+ IPV6_NEXTHOP = 0xd
+ IPV6_PAD1_OPT = 0x0
+ IPV6_PATHMTU = 0x25
+ IPV6_PKTINFO = 0xb
+ IPV6_PREFER_SRC_CGA = 0x20
+ IPV6_PREFER_SRC_CGADEFAULT = 0x10
+ IPV6_PREFER_SRC_CGAMASK = 0x30
+ IPV6_PREFER_SRC_COA = 0x2
+ IPV6_PREFER_SRC_DEFAULT = 0x15
+ IPV6_PREFER_SRC_HOME = 0x1
+ IPV6_PREFER_SRC_MASK = 0x3f
+ IPV6_PREFER_SRC_MIPDEFAULT = 0x1
+ IPV6_PREFER_SRC_MIPMASK = 0x3
+ IPV6_PREFER_SRC_NONCGA = 0x10
+ IPV6_PREFER_SRC_PUBLIC = 0x4
+ IPV6_PREFER_SRC_TMP = 0x8
+ IPV6_PREFER_SRC_TMPDEFAULT = 0x4
+ IPV6_PREFER_SRC_TMPMASK = 0xc
+ IPV6_RECVDSTOPTS = 0x28
+ IPV6_RECVHOPLIMIT = 0x13
+ IPV6_RECVHOPOPTS = 0x14
+ IPV6_RECVPATHMTU = 0x24
+ IPV6_RECVPKTINFO = 0x12
+ IPV6_RECVRTHDR = 0x16
+ IPV6_RECVRTHDRDSTOPTS = 0x17
+ IPV6_RECVTCLASS = 0x19
+ IPV6_RTHDR = 0x10
+ IPV6_RTHDRDSTOPTS = 0x11
+ IPV6_RTHDR_TYPE_0 = 0x0
+ IPV6_SEC_OPT = 0x22
+ IPV6_SRC_PREFERENCES = 0x23
+ IPV6_TCLASS = 0x26
+ IPV6_UNICAST_HOPS = 0x5
+ IPV6_UNSPEC_SRC = 0x42
+ IPV6_USE_MIN_MTU = 0x20
+ IPV6_V6ONLY = 0x27
+ IP_ADD_MEMBERSHIP = 0x13
+ IP_ADD_SOURCE_MEMBERSHIP = 0x17
+ IP_BLOCK_SOURCE = 0x15
+ IP_BOUND_IF = 0x41
+ IP_BROADCAST = 0x106
+ IP_BROADCAST_TTL = 0x43
+ IP_DEFAULT_MULTICAST_LOOP = 0x1
+ IP_DEFAULT_MULTICAST_TTL = 0x1
+ IP_DF = 0x4000
+ IP_DHCPINIT_IF = 0x45
+ IP_DONTFRAG = 0x1b
+ IP_DONTROUTE = 0x105
+ IP_DROP_MEMBERSHIP = 0x14
+ IP_DROP_SOURCE_MEMBERSHIP = 0x18
+ IP_HDRINCL = 0x2
+ IP_MAXPACKET = 0xffff
+ IP_MF = 0x2000
+ IP_MSS = 0x240
+ IP_MULTICAST_IF = 0x10
+ IP_MULTICAST_LOOP = 0x12
+ IP_MULTICAST_TTL = 0x11
+ IP_NEXTHOP = 0x19
+ IP_OPTIONS = 0x1
+ IP_PKTINFO = 0x1a
+ IP_RECVDSTADDR = 0x7
+ IP_RECVIF = 0x9
+ IP_RECVOPTS = 0x5
+ IP_RECVPKTINFO = 0x1a
+ IP_RECVRETOPTS = 0x6
+ IP_RECVSLLA = 0xa
+ IP_RECVTTL = 0xb
+ IP_RETOPTS = 0x8
+ IP_REUSEADDR = 0x104
+ IP_SEC_OPT = 0x22
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ IP_UNBLOCK_SOURCE = 0x16
+ IP_UNSPEC_SRC = 0x42
+ ISIG = 0x1
+ ISTRIP = 0x20
+ IUCLC = 0x200
+ IXANY = 0x800
+ IXOFF = 0x1000
+ IXON = 0x400
+ LOCK_EX = 0x2
+ LOCK_NB = 0x4
+ LOCK_SH = 0x1
+ LOCK_UN = 0x8
+ MADV_ACCESS_DEFAULT = 0x6
+ MADV_ACCESS_LWP = 0x7
+ MADV_ACCESS_MANY = 0x8
+ MADV_DONTNEED = 0x4
+ MADV_FREE = 0x5
+ MADV_NORMAL = 0x0
+ MADV_PURGE = 0x9
+ MADV_RANDOM = 0x1
+ MADV_SEQUENTIAL = 0x2
+ MADV_WILLNEED = 0x3
+ MAP_32BIT = 0x80
+ MAP_ALIGN = 0x200
+ MAP_ANON = 0x100
+ MAP_ANONYMOUS = 0x100
+ MAP_FILE = 0x0
+ MAP_FIXED = 0x10
+ MAP_INITDATA = 0x800
+ MAP_NORESERVE = 0x40
+ MAP_PRIVATE = 0x2
+ MAP_RENAME = 0x20
+ MAP_SHARED = 0x1
+ MAP_TEXT = 0x400
+ MAP_TYPE = 0xf
+ MCL_CURRENT = 0x1
+ MCL_FUTURE = 0x2
+ MSG_CTRUNC = 0x10
+ MSG_DONTROUTE = 0x4
+ MSG_DONTWAIT = 0x80
+ MSG_DUPCTRL = 0x800
+ MSG_EOR = 0x8
+ MSG_MAXIOVLEN = 0x10
+ MSG_NOTIFICATION = 0x100
+ MSG_OOB = 0x1
+ MSG_PEEK = 0x2
+ MSG_TRUNC = 0x20
+ MSG_WAITALL = 0x40
+ MSG_XPG4_2 = 0x8000
+ MS_ASYNC = 0x1
+ MS_INVALIDATE = 0x2
+ MS_OLDSYNC = 0x0
+ MS_SYNC = 0x4
+ M_FLUSH = 0x86
+ NL0 = 0x0
+ NL1 = 0x100
+ NLDLY = 0x100
+ NOFLSH = 0x80
+ OCRNL = 0x8
+ OFDEL = 0x80
+ OFILL = 0x40
+ OLCUC = 0x2
+ ONLCR = 0x4
+ ONLRET = 0x20
+ ONOCR = 0x10
+ OPENFAIL = -0x1
+ OPOST = 0x1
+ O_ACCMODE = 0x600003
+ O_APPEND = 0x8
+ O_CLOEXEC = 0x800000
+ O_CREAT = 0x100
+ O_DSYNC = 0x40
+ O_EXCL = 0x400
+ O_EXEC = 0x400000
+ O_LARGEFILE = 0x2000
+ O_NDELAY = 0x4
+ O_NOCTTY = 0x800
+ O_NOFOLLOW = 0x20000
+ O_NOLINKS = 0x40000
+ O_NONBLOCK = 0x80
+ O_RDONLY = 0x0
+ O_RDWR = 0x2
+ O_RSYNC = 0x8000
+ O_SEARCH = 0x200000
+ O_SIOCGIFCONF = -0x3ff796ec
+ O_SIOCGLIFCONF = -0x3fef9688
+ O_SYNC = 0x10
+ O_TRUNC = 0x200
+ O_WRONLY = 0x1
+ O_XATTR = 0x4000
+ PARENB = 0x100
+ PAREXT = 0x100000
+ PARMRK = 0x8
+ PARODD = 0x200
+ PENDIN = 0x4000
+ PRIO_PGRP = 0x1
+ PRIO_PROCESS = 0x0
+ PRIO_USER = 0x2
+ PROT_EXEC = 0x4
+ PROT_NONE = 0x0
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ RLIMIT_AS = 0x6
+ RLIMIT_CORE = 0x4
+ RLIMIT_CPU = 0x0
+ RLIMIT_DATA = 0x2
+ RLIMIT_FSIZE = 0x1
+ RLIMIT_NOFILE = 0x5
+ RLIMIT_STACK = 0x3
+ RLIM_INFINITY = -0x3
+ RTAX_AUTHOR = 0x6
+ RTAX_BRD = 0x7
+ RTAX_DST = 0x0
+ RTAX_GATEWAY = 0x1
+ RTAX_GENMASK = 0x3
+ RTAX_IFA = 0x5
+ RTAX_IFP = 0x4
+ RTAX_MAX = 0x9
+ RTAX_NETMASK = 0x2
+ RTAX_SRC = 0x8
+ RTA_AUTHOR = 0x40
+ RTA_BRD = 0x80
+ RTA_DST = 0x1
+ RTA_GATEWAY = 0x2
+ RTA_GENMASK = 0x8
+ RTA_IFA = 0x20
+ RTA_IFP = 0x10
+ RTA_NETMASK = 0x4
+ RTA_NUMBITS = 0x9
+ RTA_SRC = 0x100
+ RTF_BLACKHOLE = 0x1000
+ RTF_CLONING = 0x100
+ RTF_DONE = 0x40
+ RTF_DYNAMIC = 0x10
+ RTF_GATEWAY = 0x2
+ RTF_HOST = 0x4
+ RTF_INDIRECT = 0x40000
+ RTF_KERNEL = 0x80000
+ RTF_LLINFO = 0x400
+ RTF_MASK = 0x80
+ RTF_MODIFIED = 0x20
+ RTF_MULTIRT = 0x10000
+ RTF_PRIVATE = 0x2000
+ RTF_PROTO1 = 0x8000
+ RTF_PROTO2 = 0x4000
+ RTF_REJECT = 0x8
+ RTF_SETSRC = 0x20000
+ RTF_STATIC = 0x800
+ RTF_UP = 0x1
+ RTF_XRESOLVE = 0x200
+ RTF_ZONE = 0x100000
+ RTM_ADD = 0x1
+ RTM_CHANGE = 0x3
+ RTM_CHGADDR = 0xf
+ RTM_DELADDR = 0xd
+ RTM_DELETE = 0x2
+ RTM_FREEADDR = 0x10
+ RTM_GET = 0x4
+ RTM_IFINFO = 0xe
+ RTM_LOCK = 0x8
+ RTM_LOSING = 0x5
+ RTM_MISS = 0x7
+ RTM_NEWADDR = 0xc
+ RTM_OLDADD = 0x9
+ RTM_OLDDEL = 0xa
+ RTM_REDIRECT = 0x6
+ RTM_RESOLVE = 0xb
+ RTM_VERSION = 0x3
+ RTV_EXPIRE = 0x4
+ RTV_HOPCOUNT = 0x2
+ RTV_MTU = 0x1
+ RTV_RPIPE = 0x8
+ RTV_RTT = 0x40
+ RTV_RTTVAR = 0x80
+ RTV_SPIPE = 0x10
+ RTV_SSTHRESH = 0x20
+ RT_AWARE = 0x1
+ RUSAGE_CHILDREN = -0x1
+ RUSAGE_SELF = 0x0
+ SCM_RIGHTS = 0x1010
+ SCM_TIMESTAMP = 0x1013
+ SCM_UCRED = 0x1012
+ SHUT_RD = 0x0
+ SHUT_RDWR = 0x2
+ SHUT_WR = 0x1
+ SIG2STR_MAX = 0x20
+ SIOCADDMULTI = -0x7fdf96cf
+ SIOCADDRT = -0x7fcf8df6
+ SIOCATMARK = 0x40047307
+ SIOCDARP = -0x7fdb96e0
+ SIOCDELMULTI = -0x7fdf96ce
+ SIOCDELRT = -0x7fcf8df5
+ SIOCDXARP = -0x7fff9658
+ SIOCGARP = -0x3fdb96e1
+ SIOCGDSTINFO = -0x3fff965c
+ SIOCGENADDR = -0x3fdf96ab
+ SIOCGENPSTATS = -0x3fdf96c7
+ SIOCGETLSGCNT = -0x3fef8deb
+ SIOCGETNAME = 0x40107334
+ SIOCGETPEER = 0x40107335
+ SIOCGETPROP = -0x3fff8f44
+ SIOCGETSGCNT = -0x3feb8deb
+ SIOCGETSYNC = -0x3fdf96d3
+ SIOCGETVIFCNT = -0x3feb8dec
+ SIOCGHIWAT = 0x40047301
+ SIOCGIFADDR = -0x3fdf96f3
+ SIOCGIFBRDADDR = -0x3fdf96e9
+ SIOCGIFCONF = -0x3ff796a4
+ SIOCGIFDSTADDR = -0x3fdf96f1
+ SIOCGIFFLAGS = -0x3fdf96ef
+ SIOCGIFHWADDR = -0x3fdf9647
+ SIOCGIFINDEX = -0x3fdf96a6
+ SIOCGIFMEM = -0x3fdf96ed
+ SIOCGIFMETRIC = -0x3fdf96e5
+ SIOCGIFMTU = -0x3fdf96ea
+ SIOCGIFMUXID = -0x3fdf96a8
+ SIOCGIFNETMASK = -0x3fdf96e7
+ SIOCGIFNUM = 0x40046957
+ SIOCGIP6ADDRPOLICY = -0x3fff965e
+ SIOCGIPMSFILTER = -0x3ffb964c
+ SIOCGLIFADDR = -0x3f87968f
+ SIOCGLIFBINDING = -0x3f879666
+ SIOCGLIFBRDADDR = -0x3f879685
+ SIOCGLIFCONF = -0x3fef965b
+ SIOCGLIFDADSTATE = -0x3f879642
+ SIOCGLIFDSTADDR = -0x3f87968d
+ SIOCGLIFFLAGS = -0x3f87968b
+ SIOCGLIFGROUPINFO = -0x3f4b9663
+ SIOCGLIFGROUPNAME = -0x3f879664
+ SIOCGLIFHWADDR = -0x3f879640
+ SIOCGLIFINDEX = -0x3f87967b
+ SIOCGLIFLNKINFO = -0x3f879674
+ SIOCGLIFMETRIC = -0x3f879681
+ SIOCGLIFMTU = -0x3f879686
+ SIOCGLIFMUXID = -0x3f87967d
+ SIOCGLIFNETMASK = -0x3f879683
+ SIOCGLIFNUM = -0x3ff3967e
+ SIOCGLIFSRCOF = -0x3fef964f
+ SIOCGLIFSUBNET = -0x3f879676
+ SIOCGLIFTOKEN = -0x3f879678
+ SIOCGLIFUSESRC = -0x3f879651
+ SIOCGLIFZONE = -0x3f879656
+ SIOCGLOWAT = 0x40047303
+ SIOCGMSFILTER = -0x3ffb964e
+ SIOCGPGRP = 0x40047309
+ SIOCGSTAMP = -0x3fef9646
+ SIOCGXARP = -0x3fff9659
+ SIOCIFDETACH = -0x7fdf96c8
+ SIOCILB = -0x3ffb9645
+ SIOCLIFADDIF = -0x3f879691
+ SIOCLIFDELND = -0x7f879673
+ SIOCLIFGETND = -0x3f879672
+ SIOCLIFREMOVEIF = -0x7f879692
+ SIOCLIFSETND = -0x7f879671
+ SIOCLOWER = -0x7fdf96d7
+ SIOCSARP = -0x7fdb96e2
+ SIOCSCTPGOPT = -0x3fef9653
+ SIOCSCTPPEELOFF = -0x3ffb9652
+ SIOCSCTPSOPT = -0x7fef9654
+ SIOCSENABLESDP = -0x3ffb9649
+ SIOCSETPROP = -0x7ffb8f43
+ SIOCSETSYNC = -0x7fdf96d4
+ SIOCSHIWAT = -0x7ffb8d00
+ SIOCSIFADDR = -0x7fdf96f4
+ SIOCSIFBRDADDR = -0x7fdf96e8
+ SIOCSIFDSTADDR = -0x7fdf96f2
+ SIOCSIFFLAGS = -0x7fdf96f0
+ SIOCSIFINDEX = -0x7fdf96a5
+ SIOCSIFMEM = -0x7fdf96ee
+ SIOCSIFMETRIC = -0x7fdf96e4
+ SIOCSIFMTU = -0x7fdf96eb
+ SIOCSIFMUXID = -0x7fdf96a7
+ SIOCSIFNAME = -0x7fdf96b7
+ SIOCSIFNETMASK = -0x7fdf96e6
+ SIOCSIP6ADDRPOLICY = -0x7fff965d
+ SIOCSIPMSFILTER = -0x7ffb964b
+ SIOCSLGETREQ = -0x3fdf96b9
+ SIOCSLIFADDR = -0x7f879690
+ SIOCSLIFBRDADDR = -0x7f879684
+ SIOCSLIFDSTADDR = -0x7f87968e
+ SIOCSLIFFLAGS = -0x7f87968c
+ SIOCSLIFGROUPNAME = -0x7f879665
+ SIOCSLIFINDEX = -0x7f87967a
+ SIOCSLIFLNKINFO = -0x7f879675
+ SIOCSLIFMETRIC = -0x7f879680
+ SIOCSLIFMTU = -0x7f879687
+ SIOCSLIFMUXID = -0x7f87967c
+ SIOCSLIFNAME = -0x3f87967f
+ SIOCSLIFNETMASK = -0x7f879682
+ SIOCSLIFPREFIX = -0x3f879641
+ SIOCSLIFSUBNET = -0x7f879677
+ SIOCSLIFTOKEN = -0x7f879679
+ SIOCSLIFUSESRC = -0x7f879650
+ SIOCSLIFZONE = -0x7f879655
+ SIOCSLOWAT = -0x7ffb8cfe
+ SIOCSLSTAT = -0x7fdf96b8
+ SIOCSMSFILTER = -0x7ffb964d
+ SIOCSPGRP = -0x7ffb8cf8
+ SIOCSPROMISC = -0x7ffb96d0
+ SIOCSQPTR = -0x3ffb9648
+ SIOCSSDSTATS = -0x3fdf96d2
+ SIOCSSESTATS = -0x3fdf96d1
+ SIOCSXARP = -0x7fff965a
+ SIOCTMYADDR = -0x3ff79670
+ SIOCTMYSITE = -0x3ff7966e
+ SIOCTONLINK = -0x3ff7966f
+ SIOCUPPER = -0x7fdf96d8
+ SIOCX25RCV = -0x3fdf96c4
+ SIOCX25TBL = -0x3fdf96c3
+ SIOCX25XMT = -0x3fdf96c5
+ SIOCXPROTO = 0x20007337
+ SOCK_CLOEXEC = 0x80000
+ SOCK_DGRAM = 0x1
+ SOCK_NDELAY = 0x200000
+ SOCK_NONBLOCK = 0x100000
+ SOCK_RAW = 0x4
+ SOCK_RDM = 0x5
+ SOCK_SEQPACKET = 0x6
+ SOCK_STREAM = 0x2
+ SOCK_TYPE_MASK = 0xffff
+ SOL_FILTER = 0xfffc
+ SOL_PACKET = 0xfffd
+ SOL_ROUTE = 0xfffe
+ SOL_SOCKET = 0xffff
+ SOMAXCONN = 0x80
+ SO_ACCEPTCONN = 0x2
+ SO_ALL = 0x3f
+ SO_ALLZONES = 0x1014
+ SO_ANON_MLP = 0x100a
+ SO_ATTACH_FILTER = 0x40000001
+ SO_BAND = 0x4000
+ SO_BROADCAST = 0x20
+ SO_COPYOPT = 0x80000
+ SO_DEBUG = 0x1
+ SO_DELIM = 0x8000
+ SO_DETACH_FILTER = 0x40000002
+ SO_DGRAM_ERRIND = 0x200
+ SO_DOMAIN = 0x100c
+ SO_DONTLINGER = -0x81
+ SO_DONTROUTE = 0x10
+ SO_ERROPT = 0x40000
+ SO_ERROR = 0x1007
+ SO_EXCLBIND = 0x1015
+ SO_HIWAT = 0x10
+ SO_ISNTTY = 0x800
+ SO_ISTTY = 0x400
+ SO_KEEPALIVE = 0x8
+ SO_LINGER = 0x80
+ SO_LOWAT = 0x20
+ SO_MAC_EXEMPT = 0x100b
+ SO_MAC_IMPLICIT = 0x1016
+ SO_MAXBLK = 0x100000
+ SO_MAXPSZ = 0x8
+ SO_MINPSZ = 0x4
+ SO_MREADOFF = 0x80
+ SO_MREADON = 0x40
+ SO_NDELOFF = 0x200
+ SO_NDELON = 0x100
+ SO_NODELIM = 0x10000
+ SO_OOBINLINE = 0x100
+ SO_PROTOTYPE = 0x1009
+ SO_RCVBUF = 0x1002
+ SO_RCVLOWAT = 0x1004
+ SO_RCVPSH = 0x100d
+ SO_RCVTIMEO = 0x1006
+ SO_READOPT = 0x1
+ SO_RECVUCRED = 0x400
+ SO_REUSEADDR = 0x4
+ SO_SECATTR = 0x1011
+ SO_SNDBUF = 0x1001
+ SO_SNDLOWAT = 0x1003
+ SO_SNDTIMEO = 0x1005
+ SO_STRHOLD = 0x20000
+ SO_TAIL = 0x200000
+ SO_TIMESTAMP = 0x1013
+ SO_TONSTOP = 0x2000
+ SO_TOSTOP = 0x1000
+ SO_TYPE = 0x1008
+ SO_USELOOPBACK = 0x40
+ SO_VRRP = 0x1017
+ SO_WROFF = 0x2
+ TAB0 = 0x0
+ TAB1 = 0x800
+ TAB2 = 0x1000
+ TAB3 = 0x1800
+ TABDLY = 0x1800
+ TCFLSH = 0x5407
+ TCGETA = 0x5401
+ TCGETS = 0x540d
+ TCIFLUSH = 0x0
+ TCIOFF = 0x2
+ TCIOFLUSH = 0x2
+ TCION = 0x3
+ TCOFLUSH = 0x1
+ TCOOFF = 0x0
+ TCOON = 0x1
+ TCP_ABORT_THRESHOLD = 0x11
+ TCP_ANONPRIVBIND = 0x20
+ TCP_CONN_ABORT_THRESHOLD = 0x13
+ TCP_CONN_NOTIFY_THRESHOLD = 0x12
+ TCP_CORK = 0x18
+ TCP_EXCLBIND = 0x21
+ TCP_INIT_CWND = 0x15
+ TCP_KEEPALIVE = 0x8
+ TCP_KEEPALIVE_ABORT_THRESHOLD = 0x17
+ TCP_KEEPALIVE_THRESHOLD = 0x16
+ TCP_KEEPCNT = 0x23
+ TCP_KEEPIDLE = 0x22
+ TCP_KEEPINTVL = 0x24
+ TCP_LINGER2 = 0x1c
+ TCP_MAXSEG = 0x2
+ TCP_MSS = 0x218
+ TCP_NODELAY = 0x1
+ TCP_NOTIFY_THRESHOLD = 0x10
+ TCP_RECVDSTADDR = 0x14
+ TCP_RTO_INITIAL = 0x19
+ TCP_RTO_MAX = 0x1b
+ TCP_RTO_MIN = 0x1a
+ TCSAFLUSH = 0x5410
+ TCSBRK = 0x5405
+ TCSETA = 0x5402
+ TCSETAF = 0x5404
+ TCSETAW = 0x5403
+ TCSETS = 0x540e
+ TCSETSF = 0x5410
+ TCSETSW = 0x540f
+ TCXONC = 0x5406
+ TIOC = 0x5400
+ TIOCCBRK = 0x747a
+ TIOCCDTR = 0x7478
+ TIOCCILOOP = 0x746c
+ TIOCEXCL = 0x740d
+ TIOCFLUSH = 0x7410
+ TIOCGETC = 0x7412
+ TIOCGETD = 0x7400
+ TIOCGETP = 0x7408
+ TIOCGLTC = 0x7474
+ TIOCGPGRP = 0x7414
+ TIOCGPPS = 0x547d
+ TIOCGPPSEV = 0x547f
+ TIOCGSID = 0x7416
+ TIOCGSOFTCAR = 0x5469
+ TIOCGWINSZ = 0x5468
+ TIOCHPCL = 0x7402
+ TIOCKBOF = 0x5409
+ TIOCKBON = 0x5408
+ TIOCLBIC = 0x747e
+ TIOCLBIS = 0x747f
+ TIOCLGET = 0x747c
+ TIOCLSET = 0x747d
+ TIOCMBIC = 0x741c
+ TIOCMBIS = 0x741b
+ TIOCMGET = 0x741d
+ TIOCMSET = 0x741a
+ TIOCM_CAR = 0x40
+ TIOCM_CD = 0x40
+ TIOCM_CTS = 0x20
+ TIOCM_DSR = 0x100
+ TIOCM_DTR = 0x2
+ TIOCM_LE = 0x1
+ TIOCM_RI = 0x80
+ TIOCM_RNG = 0x80
+ TIOCM_RTS = 0x4
+ TIOCM_SR = 0x10
+ TIOCM_ST = 0x8
+ TIOCNOTTY = 0x7471
+ TIOCNXCL = 0x740e
+ TIOCOUTQ = 0x7473
+ TIOCREMOTE = 0x741e
+ TIOCSBRK = 0x747b
+ TIOCSCTTY = 0x7484
+ TIOCSDTR = 0x7479
+ TIOCSETC = 0x7411
+ TIOCSETD = 0x7401
+ TIOCSETN = 0x740a
+ TIOCSETP = 0x7409
+ TIOCSIGNAL = 0x741f
+ TIOCSILOOP = 0x746d
+ TIOCSLTC = 0x7475
+ TIOCSPGRP = 0x7415
+ TIOCSPPS = 0x547e
+ TIOCSSOFTCAR = 0x546a
+ TIOCSTART = 0x746e
+ TIOCSTI = 0x7417
+ TIOCSTOP = 0x746f
+ TIOCSWINSZ = 0x5467
+ TOSTOP = 0x100
+ VCEOF = 0x8
+ VCEOL = 0x9
+ VDISCARD = 0xd
+ VDSUSP = 0xb
+ VEOF = 0x4
+ VEOL = 0x5
+ VEOL2 = 0x6
+ VERASE = 0x2
+ VINTR = 0x0
+ VKILL = 0x3
+ VLNEXT = 0xf
+ VMIN = 0x4
+ VQUIT = 0x1
+ VREPRINT = 0xc
+ VSTART = 0x8
+ VSTATUS = 0x10
+ VSTOP = 0x9
+ VSUSP = 0xa
+ VSWTCH = 0x7
+ VT0 = 0x0
+ VT1 = 0x4000
+ VTDLY = 0x4000
+ VTIME = 0x5
+ VWERASE = 0xe
+ WCONTFLG = 0xffff
+ WCONTINUED = 0x8
+ WCOREFLG = 0x80
+ WEXITED = 0x1
+ WNOHANG = 0x40
+ WNOWAIT = 0x80
+ WOPTMASK = 0xcf
+ WRAP = 0x20000
+ WSIGMASK = 0x7f
+ WSTOPFLG = 0x7f
+ WSTOPPED = 0x4
+ WTRAPPED = 0x2
+ WUNTRACED = 0x4
+ 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(0x39)
+ EBUSY = syscall.Errno(0x10)
+ ECANCELED = syscall.Errno(0x2f)
+ 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)
+ EDQUOT = syscall.Errno(0x31)
+ EEXIST = syscall.Errno(0x11)
+ EFAULT = syscall.Errno(0xe)
+ EFBIG = syscall.Errno(0x1b)
+ EHOSTDOWN = syscall.Errno(0x93)
+ EHOSTUNREACH = syscall.Errno(0x94)
+ EIDRM = syscall.Errno(0x24)
+ EILSEQ = syscall.Errno(0x58)
+ EINPROGRESS = syscall.Errno(0x96)
+ EINTR = syscall.Errno(0x4)
+ EINVAL = syscall.Errno(0x16)
+ EIO = syscall.Errno(0x5)
+ EISCONN = syscall.Errno(0x85)
+ EISDIR = syscall.Errno(0x15)
+ 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)
+ ELOCKUNMAPPED = syscall.Errno(0x48)
+ ELOOP = syscall.Errno(0x5a)
+ EMFILE = syscall.Errno(0x18)
+ EMLINK = syscall.Errno(0x1f)
+ EMSGSIZE = syscall.Errno(0x61)
+ EMULTIHOP = syscall.Errno(0x4a)
+ ENAMETOOLONG = syscall.Errno(0x4e)
+ 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)
+ ENOLCK = syscall.Errno(0x2e)
+ ENOLINK = syscall.Errno(0x43)
+ 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)
+ ENOTACTIVE = syscall.Errno(0x49)
+ ENOTBLK = syscall.Errno(0xf)
+ ENOTCONN = syscall.Errno(0x86)
+ ENOTDIR = syscall.Errno(0x14)
+ ENOTEMPTY = syscall.Errno(0x5d)
+ ENOTRECOVERABLE = syscall.Errno(0x3b)
+ ENOTSOCK = syscall.Errno(0x5f)
+ ENOTSUP = syscall.Errno(0x30)
+ ENOTTY = syscall.Errno(0x19)
+ ENOTUNIQ = syscall.Errno(0x50)
+ ENXIO = syscall.Errno(0x6)
+ EOPNOTSUPP = syscall.Errno(0x7a)
+ EOVERFLOW = syscall.Errno(0x4f)
+ EOWNERDEAD = syscall.Errno(0x3a)
+ 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)
+ EREMOTE = syscall.Errno(0x42)
+ ERESTART = syscall.Errno(0x5b)
+ 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)
+ 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)
+ SIGCANCEL = syscall.Signal(0x24)
+ SIGCHLD = syscall.Signal(0x12)
+ SIGCLD = syscall.Signal(0x12)
+ SIGCONT = syscall.Signal(0x19)
+ SIGEMT = syscall.Signal(0x7)
+ SIGFPE = syscall.Signal(0x8)
+ SIGFREEZE = syscall.Signal(0x22)
+ SIGHUP = syscall.Signal(0x1)
+ SIGILL = syscall.Signal(0x4)
+ SIGINFO = syscall.Signal(0x29)
+ SIGINT = syscall.Signal(0x2)
+ SIGIO = syscall.Signal(0x16)
+ SIGIOT = syscall.Signal(0x6)
+ SIGJVM1 = syscall.Signal(0x27)
+ SIGJVM2 = syscall.Signal(0x28)
+ SIGKILL = syscall.Signal(0x9)
+ SIGLOST = syscall.Signal(0x25)
+ SIGLWP = syscall.Signal(0x21)
+ 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)
+ SIGTHAW = syscall.Signal(0x23)
+ 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)
+ SIGWAITING = syscall.Signal(0x20)
+ SIGWINCH = syscall.Signal(0x14)
+ SIGXCPU = syscall.Signal(0x1e)
+ SIGXFSZ = syscall.Signal(0x1f)
+ SIGXRES = syscall.Signal(0x26)
+)
+
+// Error table
+var errors = [...]string{
+ 1: "not owner",
+ 2: "no such file or directory",
+ 3: "no such process",
+ 4: "interrupted system call",
+ 5: "I/O error",
+ 6: "no such device or address",
+ 7: "arg list too long",
+ 8: "exec format error",
+ 9: "bad file number",
+ 10: "no child processes",
+ 11: "resource temporarily unavailable",
+ 12: "not enough space",
+ 13: "permission denied",
+ 14: "bad address",
+ 15: "block device required",
+ 16: "device busy",
+ 17: "file exists",
+ 18: "cross-device link",
+ 19: "no such device",
+ 20: "not a directory",
+ 21: "is a directory",
+ 22: "invalid argument",
+ 23: "file table overflow",
+ 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: "argument out of domain",
+ 34: "result too large",
+ 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: "deadlock situation detected/avoided",
+ 46: "no record locks available",
+ 47: "operation canceled",
+ 48: "operation not supported",
+ 49: "disc quota exceeded",
+ 50: "bad exchange descriptor",
+ 51: "bad request descriptor",
+ 52: "message tables full",
+ 53: "anode table overflow",
+ 54: "bad request code",
+ 55: "invalid slot",
+ 56: "file locking deadlock",
+ 57: "bad font file format",
+ 58: "owner of the lock died",
+ 59: "lock is not recoverable",
+ 60: "not a stream device",
+ 61: "no data available",
+ 62: "timer expired",
+ 63: "out of stream 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",
+ 72: "locked lock was unmapped ",
+ 73: "facility is not active",
+ 74: "multihop attempted",
+ 77: "not a data 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 more shared libraries than system limit",
+ 87: "can not exec a shared library directly",
+ 88: "illegal byte sequence",
+ 89: "operation not applicable",
+ 90: "number of symbolic links encountered during path name traversal exceeds MAXSYMLINKS",
+ 91: "error 91",
+ 92: "error 92",
+ 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: "option not supported by protocol",
+ 120: "protocol not supported",
+ 121: "socket type not supported",
+ 122: "operation not supported on transport endpoint",
+ 123: "protocol family not supported",
+ 124: "address family not supported by protocol family",
+ 125: "address already in use",
+ 126: "cannot assign requested address",
+ 127: "network is down",
+ 128: "network is unreachable",
+ 129: "network dropped connection because of 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",
+ 143: "cannot send after socket 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",
+}
+
+// Signal table
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal Instruction",
+ 5: "trace/Breakpoint Trap",
+ 6: "abort",
+ 7: "emulation Trap",
+ 8: "arithmetic Exception",
+ 9: "killed",
+ 10: "bus Error",
+ 11: "segmentation Fault",
+ 12: "bad System Call",
+ 13: "broken Pipe",
+ 14: "alarm Clock",
+ 15: "terminated",
+ 16: "user Signal 1",
+ 17: "user Signal 2",
+ 18: "child Status Changed",
+ 19: "power-Fail/Restart",
+ 20: "window Size Change",
+ 21: "urgent Socket Condition",
+ 22: "pollable Event",
+ 23: "stopped (signal)",
+ 24: "stopped (user)",
+ 25: "continued",
+ 26: "stopped (tty input)",
+ 27: "stopped (tty output)",
+ 28: "virtual Timer Expired",
+ 29: "profiling Timer Expired",
+ 30: "cpu Limit Exceeded",
+ 31: "file Size Limit Exceeded",
+ 32: "no runnable lwp",
+ 33: "inter-lwp signal",
+ 34: "checkpoint Freeze",
+ 35: "checkpoint Thaw",
+ 36: "thread Cancellation",
+ 37: "resource Lost",
+ 38: "resource Control Exceeded",
+ 39: "reserved for JVM 1",
+ 40: "reserved for JVM 2",
+ 41: "information Request",
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go
new file mode 100644
index 0000000..10491e9
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go
@@ -0,0 +1,1609 @@
+// mksyscall.pl -l32 -tags darwin,386 syscall_bsd.go syscall_darwin.go syscall_darwin_386.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build darwin,386
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 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 pipe() (r int, w int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ r = int(r0)
+ w = int(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func kill(pid int, signum int, posix int) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Exchangedata(path1 string, path2 string, options int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path1)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(path2)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
+ 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, 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)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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)
+ 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 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)
+ 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS64, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), uintptr(length>>32))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 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 Getdtablesize() (size int) {
+ r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
+ size = int(r0)
+ 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ 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, mode int, perm 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(mode), uintptr(perm), 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 Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 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 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_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 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)
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Renameat(fromfd int, from string, tofd int, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(whence), 0, 0)
+ newoffset = 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 Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 Setprivexec(flag int) (err error) {
+ _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ 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)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Undelete(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos), uintptr(pos>>32), 0, 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) {
+ r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ sec = int32(r0)
+ usec = int32(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go
new file mode 100644
index 0000000..5f1f6bf
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go
@@ -0,0 +1,1609 @@
+// mksyscall.pl -tags darwin,amd64 syscall_bsd.go syscall_darwin.go syscall_darwin_amd64.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build darwin,amd64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 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 pipe() (r int, w int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ r = int(r0)
+ w = int(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func kill(pid int, signum int, posix int) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Exchangedata(path1 string, path2 string, options int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path1)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(path2)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
+ 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, 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)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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)
+ 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 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)
+ 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS64, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 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 Getdtablesize() (size int) {
+ r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
+ size = int(r0)
+ 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ 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, mode int, perm 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(mode), uintptr(perm), 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 Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 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 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_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 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)
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Renameat(fromfd int, from string, tofd int, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ newoffset = int64(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 Setprivexec(flag int) (err error) {
+ _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ 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)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Undelete(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos))
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) {
+ r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ sec = int64(r0)
+ usec = int32(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go
new file mode 100644
index 0000000..7a40974
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go
@@ -0,0 +1,1609 @@
+// mksyscall.pl -tags darwin,arm syscall_bsd.go syscall_darwin.go syscall_darwin_arm.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build darwin,arm
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 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 pipe() (r int, w int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ r = int(r0)
+ w = int(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func kill(pid int, signum int, posix int) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Exchangedata(path1 string, path2 string, options int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path1)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(path2)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
+ 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, 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)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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)
+ 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 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)
+ 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS64, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), uintptr(length>>32))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 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 Getdtablesize() (size int) {
+ r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
+ size = int(r0)
+ 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ 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, mode int, perm 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(mode), uintptr(perm), 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 Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 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 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_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 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)
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Renameat(fromfd int, from string, tofd int, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(whence), 0, 0)
+ newoffset = 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 Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 Setprivexec(flag int) (err error) {
+ _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ 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)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Undelete(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos), uintptr(pos>>32), 0, 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) {
+ r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ sec = int32(r0)
+ usec = int32(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go
new file mode 100644
index 0000000..07c6ebc
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go
@@ -0,0 +1,1609 @@
+// mksyscall.pl -tags darwin,arm64 syscall_bsd.go syscall_darwin.go syscall_darwin_arm64.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build darwin,arm64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 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 pipe() (r int, w int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ r = int(r0)
+ w = int(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func kill(pid int, signum int, posix int) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Exchangedata(path1 string, path2 string, options int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path1)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(path2)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
+ 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, 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)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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)
+ 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 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)
+ 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS64, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 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 Getdtablesize() (size int) {
+ r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
+ size = int(r0)
+ 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ 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, mode int, perm 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(mode), uintptr(perm), 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 Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 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 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_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 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)
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Renameat(fromfd int, from string, tofd int, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ newoffset = int64(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 Setprivexec(flag int) (err error) {
+ _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ 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)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Undelete(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos))
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) {
+ r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ sec = int64(r0)
+ usec = int32(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go
new file mode 100644
index 0000000..7fa205c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go
@@ -0,0 +1,1440 @@
+// mksyscall.pl -dragonfly -tags dragonfly,amd64 syscall_bsd.go syscall_dragonfly.go syscall_dragonfly_amd64.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build dragonfly,amd64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 pipe() (r int, w int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ r = int(r0)
+ w = int(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func extpread(fd int, p []byte, flags int, 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_EXTPREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(offset), 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 extpwrite(fd int, p []byte, flags int, 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_EXTPWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(offset), 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 Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 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, uintptr(code), 0, 0)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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 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 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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_FSTAT, 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 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 Getdtablesize() (size int) {
+ r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
+ size = int(r0)
+ 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ 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 Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0)
+ newoffset = int64(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 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 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Undelete(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) {
+ r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0)
+ nfd = int(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go
new file mode 100644
index 0000000..1a0bb4c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go
@@ -0,0 +1,1877 @@
+// mksyscall.pl -l32 -tags freebsd,386 syscall_bsd.go syscall_freebsd.go syscall_freebsd_386.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build freebsd,386
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 pipe() (r int, w int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ r = int(r0)
+ w = int(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func CapEnter() (err error) {
+ _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func capRightsGet(version int, fd int, rightsp *CapRights) (err error) {
+ _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func capRightsLimit(fd int, rightsp *CapRights) (err error) {
+ _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 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, uintptr(code), 0, 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
+ _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ 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)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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)
+ 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 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)
+ 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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_FSTAT, 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), uintptr(length>>32))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 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 Getdtablesize() (size int) {
+ r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
+ size = int(r0)
+ 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ 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 Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 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 Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 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 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_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 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)
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Renameat(fromfd int, from string, tofd int, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(whence), 0, 0)
+ newoffset = 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 Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 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 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ 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)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Undelete(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos), uintptr(pos>>32), 0, 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) {
+ r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0)
+ nfd = int(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go
new file mode 100644
index 0000000..ac1e8e0
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go
@@ -0,0 +1,1877 @@
+// mksyscall.pl -tags freebsd,amd64 syscall_bsd.go syscall_freebsd.go syscall_freebsd_amd64.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build freebsd,amd64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 pipe() (r int, w int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ r = int(r0)
+ w = int(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func CapEnter() (err error) {
+ _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func capRightsGet(version int, fd int, rightsp *CapRights) (err error) {
+ _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func capRightsLimit(fd int, rightsp *CapRights) (err error) {
+ _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 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, uintptr(code), 0, 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
+ _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ 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)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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)
+ 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 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)
+ 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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_FSTAT, 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 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 Getdtablesize() (size int) {
+ r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
+ size = int(r0)
+ 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ 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 Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 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 Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 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 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_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 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)
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Renameat(fromfd int, from string, tofd int, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ newoffset = int64(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 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 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ 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)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Undelete(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos))
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) {
+ r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0)
+ nfd = int(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go
new file mode 100644
index 0000000..2b4e6ac
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go
@@ -0,0 +1,1877 @@
+// mksyscall.pl -l32 -arm -tags freebsd,arm syscall_bsd.go syscall_freebsd.go syscall_freebsd_arm.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build freebsd,arm
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 pipe() (r int, w int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ r = int(r0)
+ w = int(r1)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func CapEnter() (err error) {
+ _, _, e1 := Syscall(SYS_CAP_ENTER, 0, 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func capRightsGet(version int, fd int, rightsp *CapRights) (err error) {
+ _, _, e1 := Syscall(SYS___CAP_RIGHTS_GET, uintptr(version), uintptr(fd), uintptr(unsafe.Pointer(rightsp)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func capRightsLimit(fd int, rightsp *CapRights) (err error) {
+ _, _, e1 := Syscall(SYS_CAP_RIGHTS_LIMIT, uintptr(fd), uintptr(unsafe.Pointer(rightsp)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 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, uintptr(code), 0, 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXTATTR_DELETE_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(file)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(attrname)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_EXTATTR_DELETE_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Fadvise(fd int, offset int64, length int64, advice int) (err error) {
+ _, _, e1 := Syscall9(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ 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)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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)
+ 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 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)
+ 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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_FSTAT, 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall6(SYS_FTRUNCATE, 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 Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 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 Getdtablesize() (size int) {
+ r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
+ size = int(r0)
+ 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ 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 Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(fdat), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 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 Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, 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_PWRITE, 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 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)
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Renameat(fromfd int, from string, tofd int, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0)
+ newoffset = 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 Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 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 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ 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)))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 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 Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Undelete(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) {
+ r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0)
+ nfd = int(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go
new file mode 100644
index 0000000..38c1bbd
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go
@@ -0,0 +1,1953 @@
+// mksyscall.pl -l32 -tags linux,386 syscall_linux.go syscall_linux_386.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,386
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 pipe(p *[2]_C_int) (err error) {
+ _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 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 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 Fadvise(fd int, offset int64, length int64, advice int) (err error) {
+ _, _, e1 := Syscall6(SYS_FADVISE64_64, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice))
+ 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_FCHOWN32, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall(SYS_FTRUNCATE64, uintptr(fd), uintptr(length), uintptr(length>>32))
+ 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_GETEGID32, 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_GETEUID32, 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_GETGID32, 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_GETUID32, 0, 0, 0)
+ uid = int(r0)
+ 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 Lchown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LCHOWN32, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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)), uintptr(offset), uintptr(offset>>32), 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 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)), uintptr(offset), uintptr(offset>>32), 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_SETFSGID32, 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_SETFSUID32, 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_SETREGID32, 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_SETRESGID32, 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_SETRESUID32, 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_SETREUID32, 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 Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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)
+ 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 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(off>>32), uintptr(n), uintptr(n>>32), uintptr(flags))
+ 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 := Syscall(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32))
+ 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_GETGROUPS32, 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_SETGROUPS32, 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 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 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 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 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 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 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)
+ 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_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go
new file mode 100644
index 0000000..dc8fe0a
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go
@@ -0,0 +1,2146 @@
+// mksyscall.pl -tags linux,amd64 syscall_linux.go syscall_linux_amd64.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,amd64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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(len), 0, 0)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0)
+ n = 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 Fadvise(fd int, offset int64, length int64, advice int) (err error) {
+ _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 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 Fstat(fd int, stat *Stat_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTAT, 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 Fstatfs(fd int, buf *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 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 Getrlimit(resource int, rlim *Rlimit) (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 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 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 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))
+ 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 Lstat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 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 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)), uintptr(offset), 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 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)), uintptr(offset), 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 Seek(fd int, offset int64, whence int) (off int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ off = int64(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_SELECT, 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_SENDFILE, 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 Setrlimit(resource int, rlim *Rlimit) (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 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, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags))
+ n = int64(r0)
+ 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_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, buf *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ 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 mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
+ r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset))
+ xaddr = uintptr(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func pipe(p *[2]_C_int) (err error) {
+ _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 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 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_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go
new file mode 100644
index 0000000..4d28042
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go
@@ -0,0 +1,2055 @@
+// mksyscall.pl -l32 -arm -tags linux,arm syscall_linux.go syscall_linux_arm.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,arm
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 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_GETGROUPS32, 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_SETGROUPS32, 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 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 socketpair(domain int, typ int, flags int, fd *[2]int32) (err error) {
+ _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(flags), 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 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 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_FCHOWN32, 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 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 Getegid() (egid int) {
+ r0, _, _ := RawSyscall(SYS_GETEGID32, 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_GETEUID32, 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_GETGID32, 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_GETUID32, 0, 0, 0)
+ uid = int(r0)
+ 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 Lchown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LCHOWN32, uintptr(unsafe.Pointer(_p0)), 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 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 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)
+ 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 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 Setfsgid(gid int) (err error) {
+ _, _, e1 := Syscall(SYS_SETFSGID32, 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_SETFSUID32, 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_SETREGID32, 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_SETRESGID32, 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_SETRESUID32, 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_SETREUID32, 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 int, err error) {
+ r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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)
+ 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 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 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 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)
+ 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 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_UGETRLIMIT, 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_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go
new file mode 100644
index 0000000..784bc3f
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go
@@ -0,0 +1,2039 @@
+// mksyscall.pl -tags linux,arm64 syscall_linux.go syscall_linux_arm64.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,arm64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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(len), 0, 0)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0)
+ n = 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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_PWAIT, 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 Fadvise(fd int, offset int64, length int64, advice int) (err error) {
+ _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 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 Fstat(fd int, stat *Stat_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTAT, 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 Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 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 Fstatfs(fd int, buf *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 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 Getrlimit(resource int, rlim *Rlimit) (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 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 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)), uintptr(offset), 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 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)), uintptr(offset), 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 Seek(fd int, offset int64, whence int) (off int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ off = int64(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_PSELECT6, 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_SENDFILE, 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 Setrlimit(resource int, rlim *Rlimit) (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 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, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags))
+ n = int64(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Statfs(path string, buf *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ 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 mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
+ r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset))
+ xaddr = uintptr(r0)
+ 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 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
+}
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..9f194dc
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go
@@ -0,0 +1,2111 @@
+// mksyscall.pl -b32 -arm -tags linux,mips syscall_linux.go syscall_linux_mipsx.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,mips
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ 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
new file mode 100644
index 0000000..4fde3ef
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go
@@ -0,0 +1,2105 @@
+// mksyscall.pl -tags linux,mips64 syscall_linux.go syscall_linux_mips64x.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,mips64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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(len), 0, 0)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0)
+ n = 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 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 Fstatfs(fd int, buf *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 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 Getrlimit(resource int, rlim *Rlimit) (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 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))
+ 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 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 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)), uintptr(offset), 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 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)), uintptr(offset), 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 Seek(fd int, offset int64, whence int) (off int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ off = int64(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_PSELECT6, 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_SENDFILE, 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 Setrlimit(resource int, rlim *Rlimit) (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 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, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags))
+ n = int64(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Statfs(path string, buf *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ 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 mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
+ r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset))
+ xaddr = uintptr(r0)
+ 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 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)
+ 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 fstat(fd int, st *stat_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(st)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func lstat(path string, st *stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 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, st *stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 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_mips64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go
new file mode 100644
index 0000000..f646342
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go
@@ -0,0 +1,2105 @@
+// mksyscall.pl -tags linux,mips64le syscall_linux.go syscall_linux_mips64x.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,mips64le
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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(len), 0, 0)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0)
+ n = 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 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 Fstatfs(fd int, buf *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 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 Getrlimit(resource int, rlim *Rlimit) (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 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))
+ 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 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 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)), uintptr(offset), 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 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)), uintptr(offset), 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 Seek(fd int, offset int64, whence int) (off int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ off = int64(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_PSELECT6, 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_SENDFILE, 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 Setrlimit(resource int, rlim *Rlimit) (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 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, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags))
+ n = int64(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Statfs(path string, buf *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ 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 mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
+ r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset))
+ xaddr = uintptr(r0)
+ 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 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)
+ 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 fstat(fd int, st *stat_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(st)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func lstat(path string, st *stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 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, st *stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(st)), 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_mipsle.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go
new file mode 100644
index 0000000..964591e
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go
@@ -0,0 +1,2111 @@
+// mksyscall.pl -l32 -arm -tags linux,mipsle syscall_linux.go syscall_linux_mipsx.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,mipsle
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ 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
new file mode 100644
index 0000000..204ab1a
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go
@@ -0,0 +1,2157 @@
+// mksyscall.pl -tags linux,ppc64 syscall_linux.go syscall_linux_ppc64x.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,ppc64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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(len), 0, 0)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0)
+ n = 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 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 Fstat(fd int, stat *Stat_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTAT, 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 Fstatfs(fd int, buf *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 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 Getrlimit(resource int, rlim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_UGETRLIMIT, 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 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 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 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))
+ 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 Lstat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 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 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)), uintptr(offset), 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 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)), uintptr(offset), 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 Seek(fd int, offset int64, whence int) (off int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ off = int64(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_SELECT, 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_SENDFILE, 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 Setrlimit(resource int, rlim *Rlimit) (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 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, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags))
+ n = int64(r0)
+ 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_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, buf *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall6(SYS_SYNC_FILE_RANGE2, uintptr(fd), uintptr(off), 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ 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 mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
+ r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset))
+ xaddr = uintptr(r0)
+ 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 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func pipe(p *[2]_C_int) (err error) {
+ _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 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 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_ppc64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go
new file mode 100644
index 0000000..a8a2b0b
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go
@@ -0,0 +1,2157 @@
+// mksyscall.pl -tags linux,ppc64le syscall_linux.go syscall_linux_ppc64x.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,ppc64le
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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(len), 0, 0)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0)
+ n = 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 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 Fstat(fd int, stat *Stat_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTAT, 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 Fstatfs(fd int, buf *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 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 Getrlimit(resource int, rlim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_UGETRLIMIT, 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 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 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 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))
+ 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 Lstat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 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 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)), uintptr(offset), 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 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)), uintptr(offset), 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 Seek(fd int, offset int64, whence int) (off int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ off = int64(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_SELECT, 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_SENDFILE, 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 Setrlimit(resource int, rlim *Rlimit) (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 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, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags))
+ n = int64(r0)
+ 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_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, buf *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall6(SYS_SYNC_FILE_RANGE2, uintptr(fd), uintptr(off), 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ 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 mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
+ r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset))
+ xaddr = uintptr(r0)
+ 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 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func pipe(p *[2]_C_int) (err error) {
+ _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 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 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_s390x.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go
new file mode 100644
index 0000000..b6ff9e3
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go
@@ -0,0 +1,1937 @@
+// mksyscall.pl -tags linux,s390x syscall_linux.go syscall_linux_s390x.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,s390x
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func fchmodat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// 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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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 KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(buf)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlJoin(cmd int, arg2 string) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg2)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(arg3)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(arg4)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(arg5), 0)
+ ret = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(payload) > 0 {
+ _p0 = unsafe.Pointer(&payload[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(arg2), uintptr(_p0), uintptr(len(payload)), uintptr(arg5), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) {
+ var _p0 unsafe.Pointer
+ if len(buf) > 0 {
+ _p0 = unsafe.Pointer(&buf[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_KEYCTL, uintptr(cmd), uintptr(unsafe.Pointer(arg2)), uintptr(_p0), uintptr(len(buf)), 0, 0)
+ ret = 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 unsafe.Pointer
+ if len(payload) > 0 {
+ _p2 = unsafe.Pointer(&payload[0])
+ } else {
+ _p2 = unsafe.Pointer(&_zero)
+ }
+ r0, _, e1 := Syscall6(SYS_ADD_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(payload)), uintptr(ringid), 0)
+ id = int(r0)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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 Eventfd(initval uint, flags int) (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_EVENTFD2, uintptr(initval), uintptr(flags), 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 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)
+ 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(len), 0, 0)
+ 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 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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 Lgetxattr(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_LGETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0)
+ sz = 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)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Llistxattr(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_LLISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest)))
+ sz = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lremovexattr(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_LREMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Lsetxattr(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_LSETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0)
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(keyType)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(description)
+ if err != nil {
+ return
+ }
+ var _p2 *byte
+ _p2, err = BytePtrFromString(callback)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall6(SYS_REQUEST_KEY, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(destRingid), 0, 0)
+ id = int(r0)
+ 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)
+ 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 Syncfs(fd int) (err error) {
+ _, _, e1 := Syscall(SYS_SYNCFS, 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 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, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0)
+ n = 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)
+ 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 Fadvise(fd int, offset int64, length int64, advice int) (err error) {
+ _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 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 Fstat(fd int, stat *Stat_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTAT, 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 Fstatfs(fd int, buf *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 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 Getrlimit(resource int, rlim *Rlimit) (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 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 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 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))
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 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 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)), uintptr(offset), 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 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)), uintptr(offset), 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 Seek(fd int, offset int64, whence int) (off int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ off = int64(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_SELECT, 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_SENDFILE, 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 Setrlimit(resource int, rlim *Rlimit) (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 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 Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) {
+ r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags))
+ n = int64(r0)
+ 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_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, buf *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ 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 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 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)
+ 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 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_sparc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go
new file mode 100644
index 0000000..2dd9843
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go
@@ -0,0 +1,1833 @@
+// mksyscall.pl -tags linux,sparc64 syscall_linux.go syscall_linux_sparc64.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build linux,sparc64
+
+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)
+ 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)
+ 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)
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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 CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_COPY_FILE_RANGE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), 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 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)
+ 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(len), 0, 0)
+ 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)
+ 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)
+ 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 Getrandom(buf []byte, flags int) (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_GETRANDOM, uintptr(_p0), uintptr(len(buf)), 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 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)
+ 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))
+ 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)))
+ 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))
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0)
+ n = 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)
+ 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 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 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 Fstat(fd int, stat *Stat_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTAT, 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 Fstatfs(fd int, buf *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 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 Getrlimit(resource int, rlim *Rlimit) (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 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 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 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))
+ 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 Lstat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 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 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)), uintptr(offset), 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 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)), uintptr(offset), 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 Seek(fd int, offset int64, whence int) (off int64, err error) {
+ r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
+ off = int64(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_SELECT, 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_SENDFILE, 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 Setrlimit(resource int, rlim *Rlimit) (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 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, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags))
+ n = int64(r0)
+ 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_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, buf *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0)
+ 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 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
+ 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 mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) {
+ r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset))
+ xaddr = uintptr(r0)
+ 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 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func pipe(p *[2]_C_int) (err error) {
+ _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 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 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_netbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go
new file mode 100644
index 0000000..db99fd0
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go
@@ -0,0 +1,1346 @@
+// mksyscall.pl -l32 -netbsd -tags netbsd,386 syscall_bsd.go syscall_netbsd.go syscall_netbsd_386.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build netbsd,386
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 pipe() (fd1 int, fd2 int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ fd1 = int(r0)
+ fd2 = int(r1)
+ 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_GETDENTS, 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 Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 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, uintptr(code), 0, 0)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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 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 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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_FSTAT, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall6(SYS_FTRUNCATE, 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ 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 Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, 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_PWRITE, 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0)
+ newoffset = 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 Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 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 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 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 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 Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go
new file mode 100644
index 0000000..7b6c2c8
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go
@@ -0,0 +1,1346 @@
+// mksyscall.pl -netbsd -tags netbsd,amd64 syscall_bsd.go syscall_netbsd.go syscall_netbsd_amd64.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build netbsd,amd64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 pipe() (fd1 int, fd2 int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ fd1 = int(r0)
+ fd2 = int(r1)
+ 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_GETDENTS, 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 Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 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, uintptr(code), 0, 0)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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 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 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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_FSTAT, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length))
+ 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ 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 Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 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 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_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0)
+ newoffset = int64(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 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 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 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go
new file mode 100644
index 0000000..0f4cc3b
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go
@@ -0,0 +1,1346 @@
+// mksyscall.pl -l32 -netbsd -arm -tags netbsd,arm syscall_bsd.go syscall_netbsd.go syscall_netbsd_arm.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build netbsd,arm
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 pipe() (fd1 int, fd2 int, err error) {
+ r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
+ fd1 = int(r0)
+ fd2 = int(r1)
+ 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_GETDENTS, 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 Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 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, uintptr(code), 0, 0)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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 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 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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_FSTAT, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall6(SYS_FTRUNCATE, 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ 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 Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, 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_PWRITE, 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0)
+ newoffset = 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 Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 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 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 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 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 Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go
new file mode 100644
index 0000000..7baea87
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go
@@ -0,0 +1,1404 @@
+// mksyscall.pl -l32 -openbsd -tags openbsd,386 syscall_bsd.go syscall_openbsd.go syscall_openbsd_386.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build openbsd,386
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 pipe(p *[2]_C_int) (err error) {
+ _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 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_GETDENTS, 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 Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 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, uintptr(code), 0, 0)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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 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 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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_FSTAT, 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall6(SYS_FTRUNCATE, 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ 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 Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, 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_PWRITE, 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0)
+ newoffset = 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 Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 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 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 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 Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go
new file mode 100644
index 0000000..0d69ce6
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go
@@ -0,0 +1,1404 @@
+// mksyscall.pl -openbsd -tags openbsd,amd64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build openbsd,amd64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 pipe(p *[2]_C_int) (err error) {
+ _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 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_GETDENTS, 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 Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 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, uintptr(code), 0, 0)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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 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 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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_FSTAT, 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length))
+ 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ 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 Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 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 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_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0)
+ newoffset = int64(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 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 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go
new file mode 100644
index 0000000..41572c2
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go
@@ -0,0 +1,1404 @@
+// mksyscall.pl -l32 -openbsd -arm -tags openbsd,arm syscall_bsd.go syscall_openbsd.go syscall_openbsd_arm.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build openbsd,arm
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ syscall.Errno
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 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 setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
+ 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 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 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 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 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 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 Shutdown(s int, how int) (err error) {
+ _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
+ 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 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 kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
+ r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
+ n = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
+ var _p0 unsafe.Pointer
+ if len(mib) > 0 {
+ _p0 = unsafe.Pointer(&mib[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func utimes(path string, timeval *[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(timeval)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func futimes(fd int, timeval *[2]Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
+ 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 Madvise(b []byte, behav 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(behav))
+ 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 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 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 Msync(b []byte, flags int) (err error) {
+ var _p0 unsafe.Pointer
+ if len(b) > 0 {
+ _p0 = unsafe.Pointer(&b[0])
+ } else {
+ _p0 = unsafe.Pointer(&_zero)
+ }
+ _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
+ 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 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 pipe(p *[2]_C_int) (err error) {
+ _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 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_GETDENTS, 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 Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chflags(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), 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 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)
+ 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(fd int) (nfd int, err error) {
+ r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Dup2(from int, to int) (err error) {
+ _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 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, uintptr(code), 0, 0)
+ 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 Fchflags(fd int, flags int) (err error) {
+ _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 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 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 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 Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
+ val = int(r0)
+ 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_FSTAT, 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 Fstatfs(fd int, stat *Statfs_t) (err error) {
+ _, _, e1 := Syscall(SYS_FSTATFS, 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 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 Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := Syscall6(SYS_FTRUNCATE, 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() (uid int) {
+ r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
+ uid = 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 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 Getpgrp() (pgrp int) {
+ r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
+ pgrp = int(r0)
+ 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 Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
+ 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 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 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 Issetugid() (tainted bool) {
+ r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
+ tainted = bool(r0 != 0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Kqueue() (fd int, err error) {
+ r0, _, e1 := Syscall(SYS_KQUEUE, 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 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))
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
+ 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_LSTAT, uintptr(unsafe.Pointer(_p0)), 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 Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
+ 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 Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
+ fd = int(r0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
+ val = int(r0)
+ 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_PREAD, 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_PWRITE, 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 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 Readlink(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 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), 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 Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Revoke(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0)
+ newoffset = 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 Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
+ _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETGID, 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 Setlogin(name string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 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 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 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 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 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 Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 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(tp *Timeval) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := RawSyscall(SYS_SETUID, 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 Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), 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 Statfs(path string, stat *Statfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), 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 Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Sync() (err error) {
+ _, _, e1 := Syscall(SYS_SYNC, 0, 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_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 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 Umask(newmask int) (oldmask int) {
+ r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
+
+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
+
+func Unmount(path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 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 mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0)
+ ret = uintptr(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 readlen(fd int, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ 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, buf *byte, nbuf int) (n int, err error) {
+ r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
+ n = int(r0)
+ 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)
+ if e1 != 0 {
+ err = errnoErr(e1)
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go
new file mode 100644
index 0000000..4287133
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go
@@ -0,0 +1,1600 @@
+// mksyscall_solaris.pl -tags solaris,amd64 syscall_solaris.go syscall_solaris_amd64.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build solaris,amd64
+
+package unix
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+//go:cgo_import_dynamic libc_pipe pipe "libc.so"
+//go:cgo_import_dynamic libc_getsockname getsockname "libsocket.so"
+//go:cgo_import_dynamic libc_getcwd getcwd "libc.so"
+//go:cgo_import_dynamic libc_getgroups getgroups "libc.so"
+//go:cgo_import_dynamic libc_setgroups setgroups "libc.so"
+//go:cgo_import_dynamic libc_wait4 wait4 "libc.so"
+//go:cgo_import_dynamic libc_gethostname gethostname "libc.so"
+//go:cgo_import_dynamic libc_utimes utimes "libc.so"
+//go:cgo_import_dynamic libc_utimensat utimensat "libc.so"
+//go:cgo_import_dynamic libc_fcntl fcntl "libc.so"
+//go:cgo_import_dynamic libc_futimesat futimesat "libc.so"
+//go:cgo_import_dynamic libc_accept accept "libsocket.so"
+//go:cgo_import_dynamic libc___xnet_recvmsg __xnet_recvmsg "libsocket.so"
+//go:cgo_import_dynamic libc___xnet_sendmsg __xnet_sendmsg "libsocket.so"
+//go:cgo_import_dynamic libc_acct acct "libc.so"
+//go:cgo_import_dynamic libc_ioctl ioctl "libc.so"
+//go:cgo_import_dynamic libc_access access "libc.so"
+//go:cgo_import_dynamic libc_adjtime adjtime "libc.so"
+//go:cgo_import_dynamic libc_chdir chdir "libc.so"
+//go:cgo_import_dynamic libc_chmod chmod "libc.so"
+//go:cgo_import_dynamic libc_chown chown "libc.so"
+//go:cgo_import_dynamic libc_chroot chroot "libc.so"
+//go:cgo_import_dynamic libc_close close "libc.so"
+//go:cgo_import_dynamic libc_creat creat "libc.so"
+//go:cgo_import_dynamic libc_dup dup "libc.so"
+//go:cgo_import_dynamic libc_dup2 dup2 "libc.so"
+//go:cgo_import_dynamic libc_exit exit "libc.so"
+//go:cgo_import_dynamic libc_fchdir fchdir "libc.so"
+//go:cgo_import_dynamic libc_fchmod fchmod "libc.so"
+//go:cgo_import_dynamic libc_fchmodat fchmodat "libc.so"
+//go:cgo_import_dynamic libc_fchown fchown "libc.so"
+//go:cgo_import_dynamic libc_fchownat fchownat "libc.so"
+//go:cgo_import_dynamic libc_fdatasync fdatasync "libc.so"
+//go:cgo_import_dynamic libc_flock flock "libc.so"
+//go:cgo_import_dynamic libc_fpathconf fpathconf "libc.so"
+//go:cgo_import_dynamic libc_fstat fstat "libc.so"
+//go:cgo_import_dynamic libc_fstatvfs fstatvfs "libc.so"
+//go:cgo_import_dynamic libc_getdents getdents "libc.so"
+//go:cgo_import_dynamic libc_getgid getgid "libc.so"
+//go:cgo_import_dynamic libc_getpid getpid "libc.so"
+//go:cgo_import_dynamic libc_getpgid getpgid "libc.so"
+//go:cgo_import_dynamic libc_getpgrp getpgrp "libc.so"
+//go:cgo_import_dynamic libc_geteuid geteuid "libc.so"
+//go:cgo_import_dynamic libc_getegid getegid "libc.so"
+//go:cgo_import_dynamic libc_getppid getppid "libc.so"
+//go:cgo_import_dynamic libc_getpriority getpriority "libc.so"
+//go:cgo_import_dynamic libc_getrlimit getrlimit "libc.so"
+//go:cgo_import_dynamic libc_getrusage getrusage "libc.so"
+//go:cgo_import_dynamic libc_gettimeofday gettimeofday "libc.so"
+//go:cgo_import_dynamic libc_getuid getuid "libc.so"
+//go:cgo_import_dynamic libc_kill kill "libc.so"
+//go:cgo_import_dynamic libc_lchown lchown "libc.so"
+//go:cgo_import_dynamic libc_link link "libc.so"
+//go:cgo_import_dynamic libc___xnet_llisten __xnet_llisten "libsocket.so"
+//go:cgo_import_dynamic libc_lstat lstat "libc.so"
+//go:cgo_import_dynamic libc_madvise madvise "libc.so"
+//go:cgo_import_dynamic libc_mkdir mkdir "libc.so"
+//go:cgo_import_dynamic libc_mkdirat mkdirat "libc.so"
+//go:cgo_import_dynamic libc_mkfifo mkfifo "libc.so"
+//go:cgo_import_dynamic libc_mkfifoat mkfifoat "libc.so"
+//go:cgo_import_dynamic libc_mknod mknod "libc.so"
+//go:cgo_import_dynamic libc_mknodat mknodat "libc.so"
+//go:cgo_import_dynamic libc_mlock mlock "libc.so"
+//go:cgo_import_dynamic libc_mlockall mlockall "libc.so"
+//go:cgo_import_dynamic libc_mprotect mprotect "libc.so"
+//go:cgo_import_dynamic libc_munlock munlock "libc.so"
+//go:cgo_import_dynamic libc_munlockall munlockall "libc.so"
+//go:cgo_import_dynamic libc_nanosleep nanosleep "libc.so"
+//go:cgo_import_dynamic libc_open open "libc.so"
+//go:cgo_import_dynamic libc_openat openat "libc.so"
+//go:cgo_import_dynamic libc_pathconf pathconf "libc.so"
+//go:cgo_import_dynamic libc_pause pause "libc.so"
+//go:cgo_import_dynamic libc_pread pread "libc.so"
+//go:cgo_import_dynamic libc_pwrite pwrite "libc.so"
+//go:cgo_import_dynamic libc_read read "libc.so"
+//go:cgo_import_dynamic libc_readlink readlink "libc.so"
+//go:cgo_import_dynamic libc_rename rename "libc.so"
+//go:cgo_import_dynamic libc_renameat renameat "libc.so"
+//go:cgo_import_dynamic libc_rmdir rmdir "libc.so"
+//go:cgo_import_dynamic libc_lseek lseek "libc.so"
+//go:cgo_import_dynamic libc_setegid setegid "libc.so"
+//go:cgo_import_dynamic libc_seteuid seteuid "libc.so"
+//go:cgo_import_dynamic libc_setgid setgid "libc.so"
+//go:cgo_import_dynamic libc_sethostname sethostname "libc.so"
+//go:cgo_import_dynamic libc_setpgid setpgid "libc.so"
+//go:cgo_import_dynamic libc_setpriority setpriority "libc.so"
+//go:cgo_import_dynamic libc_setregid setregid "libc.so"
+//go:cgo_import_dynamic libc_setreuid setreuid "libc.so"
+//go:cgo_import_dynamic libc_setrlimit setrlimit "libc.so"
+//go:cgo_import_dynamic libc_setsid setsid "libc.so"
+//go:cgo_import_dynamic libc_setuid setuid "libc.so"
+//go:cgo_import_dynamic libc_shutdown shutdown "libsocket.so"
+//go:cgo_import_dynamic libc_stat stat "libc.so"
+//go:cgo_import_dynamic libc_statvfs statvfs "libc.so"
+//go:cgo_import_dynamic libc_symlink symlink "libc.so"
+//go:cgo_import_dynamic libc_sync sync "libc.so"
+//go:cgo_import_dynamic libc_times times "libc.so"
+//go:cgo_import_dynamic libc_truncate truncate "libc.so"
+//go:cgo_import_dynamic libc_fsync fsync "libc.so"
+//go:cgo_import_dynamic libc_ftruncate ftruncate "libc.so"
+//go:cgo_import_dynamic libc_umask umask "libc.so"
+//go:cgo_import_dynamic libc_uname uname "libc.so"
+//go:cgo_import_dynamic libc_umount umount "libc.so"
+//go:cgo_import_dynamic libc_unlink unlink "libc.so"
+//go:cgo_import_dynamic libc_unlinkat unlinkat "libc.so"
+//go:cgo_import_dynamic libc_ustat ustat "libc.so"
+//go:cgo_import_dynamic libc_utime utime "libc.so"
+//go:cgo_import_dynamic libc___xnet_bind __xnet_bind "libsocket.so"
+//go:cgo_import_dynamic libc___xnet_connect __xnet_connect "libsocket.so"
+//go:cgo_import_dynamic libc_mmap mmap "libc.so"
+//go:cgo_import_dynamic libc_munmap munmap "libc.so"
+//go:cgo_import_dynamic libc___xnet_sendto __xnet_sendto "libsocket.so"
+//go:cgo_import_dynamic libc___xnet_socket __xnet_socket "libsocket.so"
+//go:cgo_import_dynamic libc___xnet_socketpair __xnet_socketpair "libsocket.so"
+//go:cgo_import_dynamic libc_write write "libc.so"
+//go:cgo_import_dynamic libc___xnet_getsockopt __xnet_getsockopt "libsocket.so"
+//go:cgo_import_dynamic libc_getpeername getpeername "libsocket.so"
+//go:cgo_import_dynamic libc_setsockopt setsockopt "libsocket.so"
+//go:cgo_import_dynamic libc_recvfrom recvfrom "libsocket.so"
+//go:cgo_import_dynamic libc_sysconf sysconf "libc.so"
+
+//go:linkname procpipe libc_pipe
+//go:linkname procgetsockname libc_getsockname
+//go:linkname procGetcwd libc_getcwd
+//go:linkname procgetgroups libc_getgroups
+//go:linkname procsetgroups libc_setgroups
+//go:linkname procwait4 libc_wait4
+//go:linkname procgethostname libc_gethostname
+//go:linkname procutimes libc_utimes
+//go:linkname procutimensat libc_utimensat
+//go:linkname procfcntl libc_fcntl
+//go:linkname procfutimesat libc_futimesat
+//go:linkname procaccept libc_accept
+//go:linkname proc__xnet_recvmsg libc___xnet_recvmsg
+//go:linkname proc__xnet_sendmsg libc___xnet_sendmsg
+//go:linkname procacct libc_acct
+//go:linkname procioctl libc_ioctl
+//go:linkname procAccess libc_access
+//go:linkname procAdjtime libc_adjtime
+//go:linkname procChdir libc_chdir
+//go:linkname procChmod libc_chmod
+//go:linkname procChown libc_chown
+//go:linkname procChroot libc_chroot
+//go:linkname procClose libc_close
+//go:linkname procCreat libc_creat
+//go:linkname procDup libc_dup
+//go:linkname procDup2 libc_dup2
+//go:linkname procExit libc_exit
+//go:linkname procFchdir libc_fchdir
+//go:linkname procFchmod libc_fchmod
+//go:linkname procFchmodat libc_fchmodat
+//go:linkname procFchown libc_fchown
+//go:linkname procFchownat libc_fchownat
+//go:linkname procFdatasync libc_fdatasync
+//go:linkname procFlock libc_flock
+//go:linkname procFpathconf libc_fpathconf
+//go:linkname procFstat libc_fstat
+//go:linkname procFstatvfs libc_fstatvfs
+//go:linkname procGetdents libc_getdents
+//go:linkname procGetgid libc_getgid
+//go:linkname procGetpid libc_getpid
+//go:linkname procGetpgid libc_getpgid
+//go:linkname procGetpgrp libc_getpgrp
+//go:linkname procGeteuid libc_geteuid
+//go:linkname procGetegid libc_getegid
+//go:linkname procGetppid libc_getppid
+//go:linkname procGetpriority libc_getpriority
+//go:linkname procGetrlimit libc_getrlimit
+//go:linkname procGetrusage libc_getrusage
+//go:linkname procGettimeofday libc_gettimeofday
+//go:linkname procGetuid libc_getuid
+//go:linkname procKill libc_kill
+//go:linkname procLchown libc_lchown
+//go:linkname procLink libc_link
+//go:linkname proc__xnet_llisten libc___xnet_llisten
+//go:linkname procLstat libc_lstat
+//go:linkname procMadvise libc_madvise
+//go:linkname procMkdir libc_mkdir
+//go:linkname procMkdirat libc_mkdirat
+//go:linkname procMkfifo libc_mkfifo
+//go:linkname procMkfifoat libc_mkfifoat
+//go:linkname procMknod libc_mknod
+//go:linkname procMknodat libc_mknodat
+//go:linkname procMlock libc_mlock
+//go:linkname procMlockall libc_mlockall
+//go:linkname procMprotect libc_mprotect
+//go:linkname procMunlock libc_munlock
+//go:linkname procMunlockall libc_munlockall
+//go:linkname procNanosleep libc_nanosleep
+//go:linkname procOpen libc_open
+//go:linkname procOpenat libc_openat
+//go:linkname procPathconf libc_pathconf
+//go:linkname procPause libc_pause
+//go:linkname procPread libc_pread
+//go:linkname procPwrite libc_pwrite
+//go:linkname procread libc_read
+//go:linkname procReadlink libc_readlink
+//go:linkname procRename libc_rename
+//go:linkname procRenameat libc_renameat
+//go:linkname procRmdir libc_rmdir
+//go:linkname proclseek libc_lseek
+//go:linkname procSetegid libc_setegid
+//go:linkname procSeteuid libc_seteuid
+//go:linkname procSetgid libc_setgid
+//go:linkname procSethostname libc_sethostname
+//go:linkname procSetpgid libc_setpgid
+//go:linkname procSetpriority libc_setpriority
+//go:linkname procSetregid libc_setregid
+//go:linkname procSetreuid libc_setreuid
+//go:linkname procSetrlimit libc_setrlimit
+//go:linkname procSetsid libc_setsid
+//go:linkname procSetuid libc_setuid
+//go:linkname procshutdown libc_shutdown
+//go:linkname procStat libc_stat
+//go:linkname procStatvfs libc_statvfs
+//go:linkname procSymlink libc_symlink
+//go:linkname procSync libc_sync
+//go:linkname procTimes libc_times
+//go:linkname procTruncate libc_truncate
+//go:linkname procFsync libc_fsync
+//go:linkname procFtruncate libc_ftruncate
+//go:linkname procUmask libc_umask
+//go:linkname procUname libc_uname
+//go:linkname procumount libc_umount
+//go:linkname procUnlink libc_unlink
+//go:linkname procUnlinkat libc_unlinkat
+//go:linkname procUstat libc_ustat
+//go:linkname procUtime libc_utime
+//go:linkname proc__xnet_bind libc___xnet_bind
+//go:linkname proc__xnet_connect libc___xnet_connect
+//go:linkname procmmap libc_mmap
+//go:linkname procmunmap libc_munmap
+//go:linkname proc__xnet_sendto libc___xnet_sendto
+//go:linkname proc__xnet_socket libc___xnet_socket
+//go:linkname proc__xnet_socketpair libc___xnet_socketpair
+//go:linkname procwrite libc_write
+//go:linkname proc__xnet_getsockopt libc___xnet_getsockopt
+//go:linkname procgetpeername libc_getpeername
+//go:linkname procsetsockopt libc_setsockopt
+//go:linkname procrecvfrom libc_recvfrom
+//go:linkname procsysconf libc_sysconf
+
+var (
+ procpipe,
+ procgetsockname,
+ procGetcwd,
+ procgetgroups,
+ procsetgroups,
+ procwait4,
+ procgethostname,
+ procutimes,
+ procutimensat,
+ procfcntl,
+ procfutimesat,
+ procaccept,
+ proc__xnet_recvmsg,
+ proc__xnet_sendmsg,
+ procacct,
+ procioctl,
+ procAccess,
+ procAdjtime,
+ procChdir,
+ procChmod,
+ procChown,
+ procChroot,
+ procClose,
+ procCreat,
+ procDup,
+ procDup2,
+ procExit,
+ procFchdir,
+ procFchmod,
+ procFchmodat,
+ procFchown,
+ procFchownat,
+ procFdatasync,
+ procFlock,
+ procFpathconf,
+ procFstat,
+ procFstatvfs,
+ procGetdents,
+ procGetgid,
+ procGetpid,
+ procGetpgid,
+ procGetpgrp,
+ procGeteuid,
+ procGetegid,
+ procGetppid,
+ procGetpriority,
+ procGetrlimit,
+ procGetrusage,
+ procGettimeofday,
+ procGetuid,
+ procKill,
+ procLchown,
+ procLink,
+ proc__xnet_llisten,
+ procLstat,
+ procMadvise,
+ procMkdir,
+ procMkdirat,
+ procMkfifo,
+ procMkfifoat,
+ procMknod,
+ procMknodat,
+ procMlock,
+ procMlockall,
+ procMprotect,
+ procMunlock,
+ procMunlockall,
+ procNanosleep,
+ procOpen,
+ procOpenat,
+ procPathconf,
+ procPause,
+ procPread,
+ procPwrite,
+ procread,
+ procReadlink,
+ procRename,
+ procRenameat,
+ procRmdir,
+ proclseek,
+ procSetegid,
+ procSeteuid,
+ procSetgid,
+ procSethostname,
+ procSetpgid,
+ procSetpriority,
+ procSetregid,
+ procSetreuid,
+ procSetrlimit,
+ procSetsid,
+ procSetuid,
+ procshutdown,
+ procStat,
+ procStatvfs,
+ procSymlink,
+ procSync,
+ procTimes,
+ procTruncate,
+ procFsync,
+ procFtruncate,
+ procUmask,
+ procUname,
+ procumount,
+ procUnlink,
+ procUnlinkat,
+ procUstat,
+ procUtime,
+ proc__xnet_bind,
+ proc__xnet_connect,
+ procmmap,
+ procmunmap,
+ proc__xnet_sendto,
+ proc__xnet_socket,
+ proc__xnet_socketpair,
+ procwrite,
+ proc__xnet_getsockopt,
+ procgetpeername,
+ procsetsockopt,
+ procrecvfrom,
+ procsysconf syscallFunc
+)
+
+func pipe(p *[2]_C_int) (n int, err error) {
+ r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procpipe)), 1, uintptr(unsafe.Pointer(p)), 0, 0, 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgetsockname)), 3, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Getcwd(buf []byte) (n int, err error) {
+ var _p0 *byte
+ if len(buf) > 0 {
+ _p0 = &buf[0]
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetcwd)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0, 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
+ r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procgetgroups)), 2, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0, 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func setgroups(ngid int, gid *_Gid_t) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procsetgroups)), 2, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func wait4(pid int32, statusp *_C_int, options int, rusage *Rusage) (wpid int32, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwait4)), 4, uintptr(pid), uintptr(unsafe.Pointer(statusp)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0)
+ wpid = int32(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func gethostname(buf []byte) (n int, err error) {
+ var _p0 *byte
+ if len(buf) > 0 {
+ _p0 = &buf[0]
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgethostname)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0, 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func utimes(path string, times *[2]Timeval) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procutimes)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func utimensat(fd int, path string, times *[2]Timespec, flag int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procutimensat)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flag), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func fcntl(fd int, cmd int, arg int) (val int, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0)
+ val = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func futimesat(fildes int, path *byte, times *[2]Timeval) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfutimesat)), 3, uintptr(fildes), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times)), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procaccept)), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0)
+ fd = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_recvmsg)), 3, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_sendmsg)), 3, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func acct(path *byte) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procacct)), 1, uintptr(unsafe.Pointer(path)), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func ioctl(fd int, req uint, arg uintptr) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procioctl)), 3, uintptr(fd), uintptr(req), uintptr(arg), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Access(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procAccess)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procAdjtime)), 2, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Chdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChdir)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Chmod(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChmod)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Chown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChown)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Chroot(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChroot)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Close(fd int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procClose)), 1, uintptr(fd), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Creat(path string, mode uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procCreat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0)
+ fd = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Dup(fd int) (nfd int, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procDup)), 1, uintptr(fd), 0, 0, 0, 0, 0)
+ nfd = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Dup2(oldfd int, newfd int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procDup2)), 2, uintptr(oldfd), uintptr(newfd), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Exit(code int) {
+ sysvicall6(uintptr(unsafe.Pointer(&procExit)), 1, uintptr(code), 0, 0, 0, 0, 0)
+ return
+}
+
+func Fchdir(fd int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchdir)), 1, uintptr(fd), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Fchmod(fd int, mode uint32) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchmod)), 2, uintptr(fd), uintptr(mode), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchmodat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Fchown(fd int, uid int, gid int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchown)), 3, uintptr(fd), uintptr(uid), uintptr(gid), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+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 := sysvicall6(uintptr(unsafe.Pointer(&procFchownat)), 5, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Fdatasync(fd int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFdatasync)), 1, uintptr(fd), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Flock(fd int, how int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFlock)), 2, uintptr(fd), uintptr(how), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Fpathconf(fd int, name int) (val int, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFpathconf)), 2, uintptr(fd), uintptr(name), 0, 0, 0, 0)
+ val = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Fstat(fd int, stat *Stat_t) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstat)), 2, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Fstatvfs(fd int, vfsstat *Statvfs_t) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstatvfs)), 2, uintptr(fd), uintptr(unsafe.Pointer(vfsstat)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Getdents(fd int, buf []byte, basep *uintptr) (n int, err error) {
+ var _p0 *byte
+ if len(buf) > 0 {
+ _p0 = &buf[0]
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetdents)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Getgid() (gid int) {
+ r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetgid)), 0, 0, 0, 0, 0, 0, 0)
+ gid = int(r0)
+ return
+}
+
+func Getpid() (pid int) {
+ r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpid)), 0, 0, 0, 0, 0, 0, 0)
+ pid = int(r0)
+ return
+}
+
+func Getpgid(pid int) (pgid int, err error) {
+ r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpgid)), 1, uintptr(pid), 0, 0, 0, 0, 0)
+ pgid = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Getpgrp() (pgid int, err error) {
+ r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpgrp)), 0, 0, 0, 0, 0, 0, 0)
+ pgid = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Geteuid() (euid int) {
+ r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGeteuid)), 0, 0, 0, 0, 0, 0, 0)
+ euid = int(r0)
+ return
+}
+
+func Getegid() (egid int) {
+ r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGetegid)), 0, 0, 0, 0, 0, 0, 0)
+ egid = int(r0)
+ return
+}
+
+func Getppid() (ppid int) {
+ r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGetppid)), 0, 0, 0, 0, 0, 0, 0)
+ ppid = int(r0)
+ return
+}
+
+func Getpriority(which int, who int) (n int, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetpriority)), 2, uintptr(which), uintptr(who), 0, 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Getrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetrlimit)), 2, uintptr(which), uintptr(unsafe.Pointer(lim)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Getrusage(who int, rusage *Rusage) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetrusage)), 2, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Gettimeofday(tv *Timeval) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGettimeofday)), 1, uintptr(unsafe.Pointer(tv)), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Getuid() (uid int) {
+ r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetuid)), 0, 0, 0, 0, 0, 0, 0)
+ uid = int(r0)
+ return
+}
+
+func Kill(pid int, signum syscall.Signal) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procKill)), 2, uintptr(pid), uintptr(signum), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Lchown(path string, uid int, gid int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLchown)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Link(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLink)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Listen(s int, backlog int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_llisten)), 2, uintptr(s), uintptr(backlog), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Lstat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLstat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Madvise(b []byte, advice int) (err error) {
+ var _p0 *byte
+ if len(b) > 0 {
+ _p0 = &b[0]
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMadvise)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(advice), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Mkdir(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkdir)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Mkdirat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkdirat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Mkfifo(path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkfifo)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Mkfifoat(dirfd int, path string, mode uint32) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkfifoat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Mknod(path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMknod)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMknodat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Mlock(b []byte) (err error) {
+ var _p0 *byte
+ if len(b) > 0 {
+ _p0 = &b[0]
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMlock)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Mlockall(flags int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMlockall)), 1, uintptr(flags), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Mprotect(b []byte, prot int) (err error) {
+ var _p0 *byte
+ if len(b) > 0 {
+ _p0 = &b[0]
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMprotect)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(prot), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Munlock(b []byte) (err error) {
+ var _p0 *byte
+ if len(b) > 0 {
+ _p0 = &b[0]
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMunlock)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Munlockall() (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMunlockall)), 0, 0, 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Nanosleep(time *Timespec, leftover *Timespec) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procNanosleep)), 2, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Open(path string, mode int, perm uint32) (fd int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procOpen)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0, 0)
+ fd = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+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 := sysvicall6(uintptr(unsafe.Pointer(&procOpenat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0)
+ fd = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Pathconf(path string, name int) (val int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPathconf)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0, 0, 0, 0)
+ val = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Pause() (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPause)), 0, 0, 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Pread(fd int, p []byte, offset int64) (n int, err error) {
+ var _p0 *byte
+ if len(p) > 0 {
+ _p0 = &p[0]
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPread)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
+ var _p0 *byte
+ if len(p) > 0 {
+ _p0 = &p[0]
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPwrite)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func read(fd int, p []byte) (n int, err error) {
+ var _p0 *byte
+ if len(p) > 0 {
+ _p0 = &p[0]
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procread)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Readlink(path string, buf []byte) (n int, err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ if len(buf) > 0 {
+ _p1 = &buf[0]
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procReadlink)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(len(buf)), 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Rename(from string, to string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(from)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(to)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRename)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+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 := sysvicall6(uintptr(unsafe.Pointer(&procRenameat)), 4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Rmdir(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRmdir)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proclseek)), 3, uintptr(fd), uintptr(offset), uintptr(whence), 0, 0, 0)
+ newoffset = int64(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Setegid(egid int) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetegid)), 1, uintptr(egid), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Seteuid(euid int) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSeteuid)), 1, uintptr(euid), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Setgid(gid int) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetgid)), 1, uintptr(gid), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Sethostname(p []byte) (err error) {
+ var _p0 *byte
+ if len(p) > 0 {
+ _p0 = &p[0]
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSethostname)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Setpgid(pid int, pgid int) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetpgid)), 2, uintptr(pid), uintptr(pgid), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Setpriority(which int, who int, prio int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSetpriority)), 3, uintptr(which), uintptr(who), uintptr(prio), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Setregid(rgid int, egid int) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetregid)), 2, uintptr(rgid), uintptr(egid), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Setreuid(ruid int, euid int) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetreuid)), 2, uintptr(ruid), uintptr(euid), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Setrlimit(which int, lim *Rlimit) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetrlimit)), 2, uintptr(which), uintptr(unsafe.Pointer(lim)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Setsid() (pid int, err error) {
+ r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetsid)), 0, 0, 0, 0, 0, 0, 0)
+ pid = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Setuid(uid int) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetuid)), 1, uintptr(uid), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Shutdown(s int, how int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procshutdown)), 2, uintptr(s), uintptr(how), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Stat(path string, stat *Stat_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procStat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Statvfs(path string, vfsstat *Statvfs_t) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procStatvfs)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(vfsstat)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Symlink(path string, link string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = BytePtrFromString(link)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSymlink)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Sync() (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSync)), 0, 0, 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Times(tms *Tms) (ticks uintptr, err error) {
+ r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procTimes)), 1, uintptr(unsafe.Pointer(tms)), 0, 0, 0, 0, 0)
+ ticks = uintptr(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Truncate(path string, length int64) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procTruncate)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Fsync(fd int) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFsync)), 1, uintptr(fd), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Ftruncate(fd int, length int64) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFtruncate)), 2, uintptr(fd), uintptr(length), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Umask(mask int) (oldmask int) {
+ r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procUmask)), 1, uintptr(mask), 0, 0, 0, 0, 0)
+ oldmask = int(r0)
+ return
+}
+
+func Uname(buf *Utsname) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procUname)), 1, uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Unmount(target string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(target)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procumount)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Unlink(path string) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlink)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Unlinkat(dirfd int, path string, flags int) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlinkat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Ustat(dev int, ubuf *Ustat_t) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUstat)), 2, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func Utime(path string, buf *Utimbuf) (err error) {
+ var _p0 *byte
+ _p0, err = BytePtrFromString(path)
+ if err != nil {
+ return
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUtime)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_bind)), 3, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_connect)), 3, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procmmap)), 6, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos))
+ ret = uintptr(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func munmap(addr uintptr, length uintptr) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procmunmap)), 2, uintptr(addr), uintptr(length), 0, 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
+ var _p0 *byte
+ if len(buf) > 0 {
+ _p0 = &buf[0]
+ }
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_sendto)), 6, uintptr(s), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func socket(domain int, typ int, proto int) (fd int, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_socket)), 3, uintptr(domain), uintptr(typ), uintptr(proto), 0, 0, 0)
+ fd = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&proc__xnet_socketpair)), 4, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func write(fd int, p []byte) (n int, err error) {
+ var _p0 *byte
+ if len(p) > 0 {
+ _p0 = &p[0]
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwrite)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0)
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_getsockopt)), 5, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
+ _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procgetpeername)), 3, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
+ _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsetsockopt)), 5, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) {
+ var _p0 *byte
+ if len(p) > 0 {
+ _p0 = &p[0]
+ }
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procrecvfrom)), 6, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
+ n = int(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
+
+func sysconf(name int) (n int64, err error) {
+ r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsysconf)), 1, uintptr(name), 0, 0, 0, 0, 0)
+ n = int64(r0)
+ if e1 != 0 {
+ err = e1
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/unix/zsysctl_openbsd.go b/vendor/golang.org/x/sys/unix/zsysctl_openbsd.go
new file mode 100644
index 0000000..83bb935
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysctl_openbsd.go
@@ -0,0 +1,270 @@
+// mksysctl_openbsd.pl
+// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT
+
+package unix
+
+type mibentry struct {
+ ctlname string
+ ctloid []_C_int
+}
+
+var sysctlMib = []mibentry{
+ {"ddb.console", []_C_int{9, 6}},
+ {"ddb.log", []_C_int{9, 7}},
+ {"ddb.max_line", []_C_int{9, 3}},
+ {"ddb.max_width", []_C_int{9, 2}},
+ {"ddb.panic", []_C_int{9, 5}},
+ {"ddb.radix", []_C_int{9, 1}},
+ {"ddb.tab_stop_width", []_C_int{9, 4}},
+ {"ddb.trigger", []_C_int{9, 8}},
+ {"fs.posix.setuid", []_C_int{3, 1, 1}},
+ {"hw.allowpowerdown", []_C_int{6, 22}},
+ {"hw.byteorder", []_C_int{6, 4}},
+ {"hw.cpuspeed", []_C_int{6, 12}},
+ {"hw.diskcount", []_C_int{6, 10}},
+ {"hw.disknames", []_C_int{6, 8}},
+ {"hw.diskstats", []_C_int{6, 9}},
+ {"hw.machine", []_C_int{6, 1}},
+ {"hw.model", []_C_int{6, 2}},
+ {"hw.ncpu", []_C_int{6, 3}},
+ {"hw.ncpufound", []_C_int{6, 21}},
+ {"hw.pagesize", []_C_int{6, 7}},
+ {"hw.physmem", []_C_int{6, 19}},
+ {"hw.product", []_C_int{6, 15}},
+ {"hw.serialno", []_C_int{6, 17}},
+ {"hw.setperf", []_C_int{6, 13}},
+ {"hw.usermem", []_C_int{6, 20}},
+ {"hw.uuid", []_C_int{6, 18}},
+ {"hw.vendor", []_C_int{6, 14}},
+ {"hw.version", []_C_int{6, 16}},
+ {"kern.arandom", []_C_int{1, 37}},
+ {"kern.argmax", []_C_int{1, 8}},
+ {"kern.boottime", []_C_int{1, 21}},
+ {"kern.bufcachepercent", []_C_int{1, 72}},
+ {"kern.ccpu", []_C_int{1, 45}},
+ {"kern.clockrate", []_C_int{1, 12}},
+ {"kern.consdev", []_C_int{1, 75}},
+ {"kern.cp_time", []_C_int{1, 40}},
+ {"kern.cp_time2", []_C_int{1, 71}},
+ {"kern.cryptodevallowsoft", []_C_int{1, 53}},
+ {"kern.domainname", []_C_int{1, 22}},
+ {"kern.file", []_C_int{1, 73}},
+ {"kern.forkstat", []_C_int{1, 42}},
+ {"kern.fscale", []_C_int{1, 46}},
+ {"kern.fsync", []_C_int{1, 33}},
+ {"kern.hostid", []_C_int{1, 11}},
+ {"kern.hostname", []_C_int{1, 10}},
+ {"kern.intrcnt.nintrcnt", []_C_int{1, 63, 1}},
+ {"kern.job_control", []_C_int{1, 19}},
+ {"kern.malloc.buckets", []_C_int{1, 39, 1}},
+ {"kern.malloc.kmemnames", []_C_int{1, 39, 3}},
+ {"kern.maxclusters", []_C_int{1, 67}},
+ {"kern.maxfiles", []_C_int{1, 7}},
+ {"kern.maxlocksperuid", []_C_int{1, 70}},
+ {"kern.maxpartitions", []_C_int{1, 23}},
+ {"kern.maxproc", []_C_int{1, 6}},
+ {"kern.maxthread", []_C_int{1, 25}},
+ {"kern.maxvnodes", []_C_int{1, 5}},
+ {"kern.mbstat", []_C_int{1, 59}},
+ {"kern.msgbuf", []_C_int{1, 48}},
+ {"kern.msgbufsize", []_C_int{1, 38}},
+ {"kern.nchstats", []_C_int{1, 41}},
+ {"kern.netlivelocks", []_C_int{1, 76}},
+ {"kern.nfiles", []_C_int{1, 56}},
+ {"kern.ngroups", []_C_int{1, 18}},
+ {"kern.nosuidcoredump", []_C_int{1, 32}},
+ {"kern.nprocs", []_C_int{1, 47}},
+ {"kern.nselcoll", []_C_int{1, 43}},
+ {"kern.nthreads", []_C_int{1, 26}},
+ {"kern.numvnodes", []_C_int{1, 58}},
+ {"kern.osrelease", []_C_int{1, 2}},
+ {"kern.osrevision", []_C_int{1, 3}},
+ {"kern.ostype", []_C_int{1, 1}},
+ {"kern.osversion", []_C_int{1, 27}},
+ {"kern.pool_debug", []_C_int{1, 77}},
+ {"kern.posix1version", []_C_int{1, 17}},
+ {"kern.proc", []_C_int{1, 66}},
+ {"kern.random", []_C_int{1, 31}},
+ {"kern.rawpartition", []_C_int{1, 24}},
+ {"kern.saved_ids", []_C_int{1, 20}},
+ {"kern.securelevel", []_C_int{1, 9}},
+ {"kern.seminfo", []_C_int{1, 61}},
+ {"kern.shminfo", []_C_int{1, 62}},
+ {"kern.somaxconn", []_C_int{1, 28}},
+ {"kern.sominconn", []_C_int{1, 29}},
+ {"kern.splassert", []_C_int{1, 54}},
+ {"kern.stackgap_random", []_C_int{1, 50}},
+ {"kern.sysvipc_info", []_C_int{1, 51}},
+ {"kern.sysvmsg", []_C_int{1, 34}},
+ {"kern.sysvsem", []_C_int{1, 35}},
+ {"kern.sysvshm", []_C_int{1, 36}},
+ {"kern.timecounter.choice", []_C_int{1, 69, 4}},
+ {"kern.timecounter.hardware", []_C_int{1, 69, 3}},
+ {"kern.timecounter.tick", []_C_int{1, 69, 1}},
+ {"kern.timecounter.timestepwarnings", []_C_int{1, 69, 2}},
+ {"kern.tty.maxptys", []_C_int{1, 44, 6}},
+ {"kern.tty.nptys", []_C_int{1, 44, 7}},
+ {"kern.tty.tk_cancc", []_C_int{1, 44, 4}},
+ {"kern.tty.tk_nin", []_C_int{1, 44, 1}},
+ {"kern.tty.tk_nout", []_C_int{1, 44, 2}},
+ {"kern.tty.tk_rawcc", []_C_int{1, 44, 3}},
+ {"kern.tty.ttyinfo", []_C_int{1, 44, 5}},
+ {"kern.ttycount", []_C_int{1, 57}},
+ {"kern.userasymcrypto", []_C_int{1, 60}},
+ {"kern.usercrypto", []_C_int{1, 52}},
+ {"kern.usermount", []_C_int{1, 30}},
+ {"kern.version", []_C_int{1, 4}},
+ {"kern.vnode", []_C_int{1, 13}},
+ {"kern.watchdog.auto", []_C_int{1, 64, 2}},
+ {"kern.watchdog.period", []_C_int{1, 64, 1}},
+ {"net.bpf.bufsize", []_C_int{4, 31, 1}},
+ {"net.bpf.maxbufsize", []_C_int{4, 31, 2}},
+ {"net.inet.ah.enable", []_C_int{4, 2, 51, 1}},
+ {"net.inet.ah.stats", []_C_int{4, 2, 51, 2}},
+ {"net.inet.carp.allow", []_C_int{4, 2, 112, 1}},
+ {"net.inet.carp.log", []_C_int{4, 2, 112, 3}},
+ {"net.inet.carp.preempt", []_C_int{4, 2, 112, 2}},
+ {"net.inet.carp.stats", []_C_int{4, 2, 112, 4}},
+ {"net.inet.divert.recvspace", []_C_int{4, 2, 258, 1}},
+ {"net.inet.divert.sendspace", []_C_int{4, 2, 258, 2}},
+ {"net.inet.divert.stats", []_C_int{4, 2, 258, 3}},
+ {"net.inet.esp.enable", []_C_int{4, 2, 50, 1}},
+ {"net.inet.esp.stats", []_C_int{4, 2, 50, 4}},
+ {"net.inet.esp.udpencap", []_C_int{4, 2, 50, 2}},
+ {"net.inet.esp.udpencap_port", []_C_int{4, 2, 50, 3}},
+ {"net.inet.etherip.allow", []_C_int{4, 2, 97, 1}},
+ {"net.inet.etherip.stats", []_C_int{4, 2, 97, 2}},
+ {"net.inet.gre.allow", []_C_int{4, 2, 47, 1}},
+ {"net.inet.gre.wccp", []_C_int{4, 2, 47, 2}},
+ {"net.inet.icmp.bmcastecho", []_C_int{4, 2, 1, 2}},
+ {"net.inet.icmp.errppslimit", []_C_int{4, 2, 1, 3}},
+ {"net.inet.icmp.maskrepl", []_C_int{4, 2, 1, 1}},
+ {"net.inet.icmp.rediraccept", []_C_int{4, 2, 1, 4}},
+ {"net.inet.icmp.redirtimeout", []_C_int{4, 2, 1, 5}},
+ {"net.inet.icmp.stats", []_C_int{4, 2, 1, 7}},
+ {"net.inet.icmp.tstamprepl", []_C_int{4, 2, 1, 6}},
+ {"net.inet.igmp.stats", []_C_int{4, 2, 2, 1}},
+ {"net.inet.ip.arpqueued", []_C_int{4, 2, 0, 36}},
+ {"net.inet.ip.encdebug", []_C_int{4, 2, 0, 12}},
+ {"net.inet.ip.forwarding", []_C_int{4, 2, 0, 1}},
+ {"net.inet.ip.ifq.congestion", []_C_int{4, 2, 0, 30, 4}},
+ {"net.inet.ip.ifq.drops", []_C_int{4, 2, 0, 30, 3}},
+ {"net.inet.ip.ifq.len", []_C_int{4, 2, 0, 30, 1}},
+ {"net.inet.ip.ifq.maxlen", []_C_int{4, 2, 0, 30, 2}},
+ {"net.inet.ip.maxqueue", []_C_int{4, 2, 0, 11}},
+ {"net.inet.ip.mforwarding", []_C_int{4, 2, 0, 31}},
+ {"net.inet.ip.mrtproto", []_C_int{4, 2, 0, 34}},
+ {"net.inet.ip.mrtstats", []_C_int{4, 2, 0, 35}},
+ {"net.inet.ip.mtu", []_C_int{4, 2, 0, 4}},
+ {"net.inet.ip.mtudisc", []_C_int{4, 2, 0, 27}},
+ {"net.inet.ip.mtudisctimeout", []_C_int{4, 2, 0, 28}},
+ {"net.inet.ip.multipath", []_C_int{4, 2, 0, 32}},
+ {"net.inet.ip.portfirst", []_C_int{4, 2, 0, 7}},
+ {"net.inet.ip.porthifirst", []_C_int{4, 2, 0, 9}},
+ {"net.inet.ip.porthilast", []_C_int{4, 2, 0, 10}},
+ {"net.inet.ip.portlast", []_C_int{4, 2, 0, 8}},
+ {"net.inet.ip.redirect", []_C_int{4, 2, 0, 2}},
+ {"net.inet.ip.sourceroute", []_C_int{4, 2, 0, 5}},
+ {"net.inet.ip.stats", []_C_int{4, 2, 0, 33}},
+ {"net.inet.ip.ttl", []_C_int{4, 2, 0, 3}},
+ {"net.inet.ipcomp.enable", []_C_int{4, 2, 108, 1}},
+ {"net.inet.ipcomp.stats", []_C_int{4, 2, 108, 2}},
+ {"net.inet.ipip.allow", []_C_int{4, 2, 4, 1}},
+ {"net.inet.ipip.stats", []_C_int{4, 2, 4, 2}},
+ {"net.inet.mobileip.allow", []_C_int{4, 2, 55, 1}},
+ {"net.inet.pfsync.stats", []_C_int{4, 2, 240, 1}},
+ {"net.inet.pim.stats", []_C_int{4, 2, 103, 1}},
+ {"net.inet.tcp.ackonpush", []_C_int{4, 2, 6, 13}},
+ {"net.inet.tcp.always_keepalive", []_C_int{4, 2, 6, 22}},
+ {"net.inet.tcp.baddynamic", []_C_int{4, 2, 6, 6}},
+ {"net.inet.tcp.drop", []_C_int{4, 2, 6, 19}},
+ {"net.inet.tcp.ecn", []_C_int{4, 2, 6, 14}},
+ {"net.inet.tcp.ident", []_C_int{4, 2, 6, 9}},
+ {"net.inet.tcp.keepidle", []_C_int{4, 2, 6, 3}},
+ {"net.inet.tcp.keepinittime", []_C_int{4, 2, 6, 2}},
+ {"net.inet.tcp.keepintvl", []_C_int{4, 2, 6, 4}},
+ {"net.inet.tcp.mssdflt", []_C_int{4, 2, 6, 11}},
+ {"net.inet.tcp.reasslimit", []_C_int{4, 2, 6, 18}},
+ {"net.inet.tcp.rfc1323", []_C_int{4, 2, 6, 1}},
+ {"net.inet.tcp.rfc3390", []_C_int{4, 2, 6, 17}},
+ {"net.inet.tcp.rstppslimit", []_C_int{4, 2, 6, 12}},
+ {"net.inet.tcp.sack", []_C_int{4, 2, 6, 10}},
+ {"net.inet.tcp.sackholelimit", []_C_int{4, 2, 6, 20}},
+ {"net.inet.tcp.slowhz", []_C_int{4, 2, 6, 5}},
+ {"net.inet.tcp.stats", []_C_int{4, 2, 6, 21}},
+ {"net.inet.tcp.synbucketlimit", []_C_int{4, 2, 6, 16}},
+ {"net.inet.tcp.syncachelimit", []_C_int{4, 2, 6, 15}},
+ {"net.inet.udp.baddynamic", []_C_int{4, 2, 17, 2}},
+ {"net.inet.udp.checksum", []_C_int{4, 2, 17, 1}},
+ {"net.inet.udp.recvspace", []_C_int{4, 2, 17, 3}},
+ {"net.inet.udp.sendspace", []_C_int{4, 2, 17, 4}},
+ {"net.inet.udp.stats", []_C_int{4, 2, 17, 5}},
+ {"net.inet6.divert.recvspace", []_C_int{4, 24, 86, 1}},
+ {"net.inet6.divert.sendspace", []_C_int{4, 24, 86, 2}},
+ {"net.inet6.divert.stats", []_C_int{4, 24, 86, 3}},
+ {"net.inet6.icmp6.errppslimit", []_C_int{4, 24, 30, 14}},
+ {"net.inet6.icmp6.mtudisc_hiwat", []_C_int{4, 24, 30, 16}},
+ {"net.inet6.icmp6.mtudisc_lowat", []_C_int{4, 24, 30, 17}},
+ {"net.inet6.icmp6.nd6_debug", []_C_int{4, 24, 30, 18}},
+ {"net.inet6.icmp6.nd6_delay", []_C_int{4, 24, 30, 8}},
+ {"net.inet6.icmp6.nd6_maxnudhint", []_C_int{4, 24, 30, 15}},
+ {"net.inet6.icmp6.nd6_mmaxtries", []_C_int{4, 24, 30, 10}},
+ {"net.inet6.icmp6.nd6_prune", []_C_int{4, 24, 30, 6}},
+ {"net.inet6.icmp6.nd6_umaxtries", []_C_int{4, 24, 30, 9}},
+ {"net.inet6.icmp6.nd6_useloopback", []_C_int{4, 24, 30, 11}},
+ {"net.inet6.icmp6.nodeinfo", []_C_int{4, 24, 30, 13}},
+ {"net.inet6.icmp6.rediraccept", []_C_int{4, 24, 30, 2}},
+ {"net.inet6.icmp6.redirtimeout", []_C_int{4, 24, 30, 3}},
+ {"net.inet6.ip6.accept_rtadv", []_C_int{4, 24, 17, 12}},
+ {"net.inet6.ip6.auto_flowlabel", []_C_int{4, 24, 17, 17}},
+ {"net.inet6.ip6.dad_count", []_C_int{4, 24, 17, 16}},
+ {"net.inet6.ip6.dad_pending", []_C_int{4, 24, 17, 49}},
+ {"net.inet6.ip6.defmcasthlim", []_C_int{4, 24, 17, 18}},
+ {"net.inet6.ip6.forwarding", []_C_int{4, 24, 17, 1}},
+ {"net.inet6.ip6.forwsrcrt", []_C_int{4, 24, 17, 5}},
+ {"net.inet6.ip6.hdrnestlimit", []_C_int{4, 24, 17, 15}},
+ {"net.inet6.ip6.hlim", []_C_int{4, 24, 17, 3}},
+ {"net.inet6.ip6.log_interval", []_C_int{4, 24, 17, 14}},
+ {"net.inet6.ip6.maxdynroutes", []_C_int{4, 24, 17, 48}},
+ {"net.inet6.ip6.maxfragpackets", []_C_int{4, 24, 17, 9}},
+ {"net.inet6.ip6.maxfrags", []_C_int{4, 24, 17, 41}},
+ {"net.inet6.ip6.maxifdefrouters", []_C_int{4, 24, 17, 47}},
+ {"net.inet6.ip6.maxifprefixes", []_C_int{4, 24, 17, 46}},
+ {"net.inet6.ip6.mforwarding", []_C_int{4, 24, 17, 42}},
+ {"net.inet6.ip6.mrtproto", []_C_int{4, 24, 17, 8}},
+ {"net.inet6.ip6.mtudisctimeout", []_C_int{4, 24, 17, 50}},
+ {"net.inet6.ip6.multicast_mtudisc", []_C_int{4, 24, 17, 44}},
+ {"net.inet6.ip6.multipath", []_C_int{4, 24, 17, 43}},
+ {"net.inet6.ip6.neighborgcthresh", []_C_int{4, 24, 17, 45}},
+ {"net.inet6.ip6.redirect", []_C_int{4, 24, 17, 2}},
+ {"net.inet6.ip6.rr_prune", []_C_int{4, 24, 17, 22}},
+ {"net.inet6.ip6.sourcecheck", []_C_int{4, 24, 17, 10}},
+ {"net.inet6.ip6.sourcecheck_logint", []_C_int{4, 24, 17, 11}},
+ {"net.inet6.ip6.use_deprecated", []_C_int{4, 24, 17, 21}},
+ {"net.inet6.ip6.v6only", []_C_int{4, 24, 17, 24}},
+ {"net.key.sadb_dump", []_C_int{4, 30, 1}},
+ {"net.key.spd_dump", []_C_int{4, 30, 2}},
+ {"net.mpls.ifq.congestion", []_C_int{4, 33, 3, 4}},
+ {"net.mpls.ifq.drops", []_C_int{4, 33, 3, 3}},
+ {"net.mpls.ifq.len", []_C_int{4, 33, 3, 1}},
+ {"net.mpls.ifq.maxlen", []_C_int{4, 33, 3, 2}},
+ {"net.mpls.mapttl_ip", []_C_int{4, 33, 5}},
+ {"net.mpls.mapttl_ip6", []_C_int{4, 33, 6}},
+ {"net.mpls.maxloop_inkernel", []_C_int{4, 33, 4}},
+ {"net.mpls.ttl", []_C_int{4, 33, 2}},
+ {"net.pflow.stats", []_C_int{4, 34, 1}},
+ {"net.pipex.enable", []_C_int{4, 35, 1}},
+ {"vm.anonmin", []_C_int{2, 7}},
+ {"vm.loadavg", []_C_int{2, 2}},
+ {"vm.maxslp", []_C_int{2, 10}},
+ {"vm.nkmempages", []_C_int{2, 6}},
+ {"vm.psstrings", []_C_int{2, 3}},
+ {"vm.swapencrypt.enable", []_C_int{2, 5, 0}},
+ {"vm.swapencrypt.keyscreated", []_C_int{2, 5, 1}},
+ {"vm.swapencrypt.keysdeleted", []_C_int{2, 5, 2}},
+ {"vm.uspace", []_C_int{2, 11}},
+ {"vm.uvmexp", []_C_int{2, 4}},
+ {"vm.vmmeter", []_C_int{2, 1}},
+ {"vm.vnodemin", []_C_int{2, 9}},
+ {"vm.vtextmin", []_C_int{2, 8}},
+}
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_darwin_386.go b/vendor/golang.org/x/sys/unix/zsysnum_darwin_386.go
new file mode 100644
index 0000000..2786773
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_darwin_386.go
@@ -0,0 +1,398 @@
+// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/sys/syscall.h
+// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT
+
+// +build 386,darwin
+
+package unix
+
+const (
+ SYS_SYSCALL = 0
+ SYS_EXIT = 1
+ SYS_FORK = 2
+ SYS_READ = 3
+ SYS_WRITE = 4
+ SYS_OPEN = 5
+ SYS_CLOSE = 6
+ SYS_WAIT4 = 7
+ SYS_LINK = 9
+ SYS_UNLINK = 10
+ SYS_CHDIR = 12
+ SYS_FCHDIR = 13
+ SYS_MKNOD = 14
+ SYS_CHMOD = 15
+ SYS_CHOWN = 16
+ SYS_GETFSSTAT = 18
+ SYS_GETPID = 20
+ SYS_SETUID = 23
+ SYS_GETUID = 24
+ SYS_GETEUID = 25
+ SYS_PTRACE = 26
+ SYS_RECVMSG = 27
+ SYS_SENDMSG = 28
+ SYS_RECVFROM = 29
+ SYS_ACCEPT = 30
+ SYS_GETPEERNAME = 31
+ SYS_GETSOCKNAME = 32
+ SYS_ACCESS = 33
+ SYS_CHFLAGS = 34
+ SYS_FCHFLAGS = 35
+ SYS_SYNC = 36
+ SYS_KILL = 37
+ SYS_GETPPID = 39
+ SYS_DUP = 41
+ SYS_PIPE = 42
+ SYS_GETEGID = 43
+ SYS_SIGACTION = 46
+ SYS_GETGID = 47
+ SYS_SIGPROCMASK = 48
+ SYS_GETLOGIN = 49
+ SYS_SETLOGIN = 50
+ SYS_ACCT = 51
+ SYS_SIGPENDING = 52
+ SYS_SIGALTSTACK = 53
+ SYS_IOCTL = 54
+ SYS_REBOOT = 55
+ SYS_REVOKE = 56
+ SYS_SYMLINK = 57
+ SYS_READLINK = 58
+ SYS_EXECVE = 59
+ SYS_UMASK = 60
+ SYS_CHROOT = 61
+ SYS_MSYNC = 65
+ SYS_VFORK = 66
+ SYS_MUNMAP = 73
+ SYS_MPROTECT = 74
+ SYS_MADVISE = 75
+ SYS_MINCORE = 78
+ SYS_GETGROUPS = 79
+ SYS_SETGROUPS = 80
+ SYS_GETPGRP = 81
+ SYS_SETPGID = 82
+ SYS_SETITIMER = 83
+ SYS_SWAPON = 85
+ SYS_GETITIMER = 86
+ SYS_GETDTABLESIZE = 89
+ SYS_DUP2 = 90
+ SYS_FCNTL = 92
+ SYS_SELECT = 93
+ SYS_FSYNC = 95
+ SYS_SETPRIORITY = 96
+ SYS_SOCKET = 97
+ SYS_CONNECT = 98
+ SYS_GETPRIORITY = 100
+ SYS_BIND = 104
+ SYS_SETSOCKOPT = 105
+ SYS_LISTEN = 106
+ SYS_SIGSUSPEND = 111
+ SYS_GETTIMEOFDAY = 116
+ SYS_GETRUSAGE = 117
+ SYS_GETSOCKOPT = 118
+ SYS_READV = 120
+ SYS_WRITEV = 121
+ SYS_SETTIMEOFDAY = 122
+ SYS_FCHOWN = 123
+ SYS_FCHMOD = 124
+ SYS_SETREUID = 126
+ SYS_SETREGID = 127
+ SYS_RENAME = 128
+ SYS_FLOCK = 131
+ SYS_MKFIFO = 132
+ SYS_SENDTO = 133
+ SYS_SHUTDOWN = 134
+ SYS_SOCKETPAIR = 135
+ SYS_MKDIR = 136
+ SYS_RMDIR = 137
+ SYS_UTIMES = 138
+ SYS_FUTIMES = 139
+ SYS_ADJTIME = 140
+ SYS_GETHOSTUUID = 142
+ SYS_SETSID = 147
+ SYS_GETPGID = 151
+ SYS_SETPRIVEXEC = 152
+ SYS_PREAD = 153
+ SYS_PWRITE = 154
+ SYS_NFSSVC = 155
+ SYS_STATFS = 157
+ SYS_FSTATFS = 158
+ SYS_UNMOUNT = 159
+ SYS_GETFH = 161
+ SYS_QUOTACTL = 165
+ SYS_MOUNT = 167
+ SYS_CSOPS = 169
+ SYS_CSOPS_AUDITTOKEN = 170
+ SYS_WAITID = 173
+ SYS_KDEBUG_TRACE64 = 179
+ SYS_KDEBUG_TRACE = 180
+ SYS_SETGID = 181
+ SYS_SETEGID = 182
+ SYS_SETEUID = 183
+ SYS_SIGRETURN = 184
+ SYS_CHUD = 185
+ SYS_FDATASYNC = 187
+ SYS_STAT = 188
+ SYS_FSTAT = 189
+ SYS_LSTAT = 190
+ SYS_PATHCONF = 191
+ SYS_FPATHCONF = 192
+ SYS_GETRLIMIT = 194
+ SYS_SETRLIMIT = 195
+ SYS_GETDIRENTRIES = 196
+ SYS_MMAP = 197
+ SYS_LSEEK = 199
+ SYS_TRUNCATE = 200
+ SYS_FTRUNCATE = 201
+ SYS_SYSCTL = 202
+ SYS_MLOCK = 203
+ SYS_MUNLOCK = 204
+ SYS_UNDELETE = 205
+ SYS_OPEN_DPROTECTED_NP = 216
+ SYS_GETATTRLIST = 220
+ SYS_SETATTRLIST = 221
+ SYS_GETDIRENTRIESATTR = 222
+ SYS_EXCHANGEDATA = 223
+ SYS_SEARCHFS = 225
+ SYS_DELETE = 226
+ SYS_COPYFILE = 227
+ SYS_FGETATTRLIST = 228
+ SYS_FSETATTRLIST = 229
+ SYS_POLL = 230
+ SYS_WATCHEVENT = 231
+ SYS_WAITEVENT = 232
+ SYS_MODWATCH = 233
+ SYS_GETXATTR = 234
+ SYS_FGETXATTR = 235
+ SYS_SETXATTR = 236
+ SYS_FSETXATTR = 237
+ SYS_REMOVEXATTR = 238
+ SYS_FREMOVEXATTR = 239
+ SYS_LISTXATTR = 240
+ SYS_FLISTXATTR = 241
+ SYS_FSCTL = 242
+ SYS_INITGROUPS = 243
+ SYS_POSIX_SPAWN = 244
+ SYS_FFSCTL = 245
+ SYS_NFSCLNT = 247
+ SYS_FHOPEN = 248
+ SYS_MINHERIT = 250
+ SYS_SEMSYS = 251
+ SYS_MSGSYS = 252
+ SYS_SHMSYS = 253
+ SYS_SEMCTL = 254
+ SYS_SEMGET = 255
+ SYS_SEMOP = 256
+ SYS_MSGCTL = 258
+ SYS_MSGGET = 259
+ SYS_MSGSND = 260
+ SYS_MSGRCV = 261
+ SYS_SHMAT = 262
+ SYS_SHMCTL = 263
+ SYS_SHMDT = 264
+ SYS_SHMGET = 265
+ SYS_SHM_OPEN = 266
+ SYS_SHM_UNLINK = 267
+ SYS_SEM_OPEN = 268
+ SYS_SEM_CLOSE = 269
+ SYS_SEM_UNLINK = 270
+ SYS_SEM_WAIT = 271
+ SYS_SEM_TRYWAIT = 272
+ SYS_SEM_POST = 273
+ SYS_SYSCTLBYNAME = 274
+ SYS_OPEN_EXTENDED = 277
+ SYS_UMASK_EXTENDED = 278
+ SYS_STAT_EXTENDED = 279
+ SYS_LSTAT_EXTENDED = 280
+ SYS_FSTAT_EXTENDED = 281
+ SYS_CHMOD_EXTENDED = 282
+ SYS_FCHMOD_EXTENDED = 283
+ SYS_ACCESS_EXTENDED = 284
+ SYS_SETTID = 285
+ SYS_GETTID = 286
+ SYS_SETSGROUPS = 287
+ SYS_GETSGROUPS = 288
+ SYS_SETWGROUPS = 289
+ SYS_GETWGROUPS = 290
+ SYS_MKFIFO_EXTENDED = 291
+ SYS_MKDIR_EXTENDED = 292
+ SYS_IDENTITYSVC = 293
+ SYS_SHARED_REGION_CHECK_NP = 294
+ SYS_VM_PRESSURE_MONITOR = 296
+ SYS_PSYNCH_RW_LONGRDLOCK = 297
+ SYS_PSYNCH_RW_YIELDWRLOCK = 298
+ SYS_PSYNCH_RW_DOWNGRADE = 299
+ SYS_PSYNCH_RW_UPGRADE = 300
+ SYS_PSYNCH_MUTEXWAIT = 301
+ SYS_PSYNCH_MUTEXDROP = 302
+ SYS_PSYNCH_CVBROAD = 303
+ SYS_PSYNCH_CVSIGNAL = 304
+ SYS_PSYNCH_CVWAIT = 305
+ SYS_PSYNCH_RW_RDLOCK = 306
+ SYS_PSYNCH_RW_WRLOCK = 307
+ SYS_PSYNCH_RW_UNLOCK = 308
+ SYS_PSYNCH_RW_UNLOCK2 = 309
+ SYS_GETSID = 310
+ SYS_SETTID_WITH_PID = 311
+ SYS_PSYNCH_CVCLRPREPOST = 312
+ SYS_AIO_FSYNC = 313
+ SYS_AIO_RETURN = 314
+ SYS_AIO_SUSPEND = 315
+ SYS_AIO_CANCEL = 316
+ SYS_AIO_ERROR = 317
+ SYS_AIO_READ = 318
+ SYS_AIO_WRITE = 319
+ SYS_LIO_LISTIO = 320
+ SYS_IOPOLICYSYS = 322
+ SYS_PROCESS_POLICY = 323
+ SYS_MLOCKALL = 324
+ SYS_MUNLOCKALL = 325
+ SYS_ISSETUGID = 327
+ SYS___PTHREAD_KILL = 328
+ SYS___PTHREAD_SIGMASK = 329
+ SYS___SIGWAIT = 330
+ SYS___DISABLE_THREADSIGNAL = 331
+ SYS___PTHREAD_MARKCANCEL = 332
+ SYS___PTHREAD_CANCELED = 333
+ SYS___SEMWAIT_SIGNAL = 334
+ SYS_PROC_INFO = 336
+ SYS_SENDFILE = 337
+ SYS_STAT64 = 338
+ SYS_FSTAT64 = 339
+ SYS_LSTAT64 = 340
+ SYS_STAT64_EXTENDED = 341
+ SYS_LSTAT64_EXTENDED = 342
+ SYS_FSTAT64_EXTENDED = 343
+ SYS_GETDIRENTRIES64 = 344
+ SYS_STATFS64 = 345
+ SYS_FSTATFS64 = 346
+ SYS_GETFSSTAT64 = 347
+ SYS___PTHREAD_CHDIR = 348
+ SYS___PTHREAD_FCHDIR = 349
+ SYS_AUDIT = 350
+ SYS_AUDITON = 351
+ SYS_GETAUID = 353
+ SYS_SETAUID = 354
+ SYS_GETAUDIT_ADDR = 357
+ SYS_SETAUDIT_ADDR = 358
+ SYS_AUDITCTL = 359
+ SYS_BSDTHREAD_CREATE = 360
+ SYS_BSDTHREAD_TERMINATE = 361
+ SYS_KQUEUE = 362
+ SYS_KEVENT = 363
+ SYS_LCHOWN = 364
+ SYS_STACK_SNAPSHOT = 365
+ SYS_BSDTHREAD_REGISTER = 366
+ SYS_WORKQ_OPEN = 367
+ SYS_WORKQ_KERNRETURN = 368
+ SYS_KEVENT64 = 369
+ SYS___OLD_SEMWAIT_SIGNAL = 370
+ SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371
+ SYS_THREAD_SELFID = 372
+ SYS_LEDGER = 373
+ SYS___MAC_EXECVE = 380
+ SYS___MAC_SYSCALL = 381
+ SYS___MAC_GET_FILE = 382
+ SYS___MAC_SET_FILE = 383
+ SYS___MAC_GET_LINK = 384
+ SYS___MAC_SET_LINK = 385
+ SYS___MAC_GET_PROC = 386
+ SYS___MAC_SET_PROC = 387
+ SYS___MAC_GET_FD = 388
+ SYS___MAC_SET_FD = 389
+ SYS___MAC_GET_PID = 390
+ SYS___MAC_GET_LCID = 391
+ SYS___MAC_GET_LCTX = 392
+ SYS___MAC_SET_LCTX = 393
+ SYS_SETLCID = 394
+ SYS_GETLCID = 395
+ SYS_READ_NOCANCEL = 396
+ SYS_WRITE_NOCANCEL = 397
+ SYS_OPEN_NOCANCEL = 398
+ SYS_CLOSE_NOCANCEL = 399
+ SYS_WAIT4_NOCANCEL = 400
+ SYS_RECVMSG_NOCANCEL = 401
+ SYS_SENDMSG_NOCANCEL = 402
+ SYS_RECVFROM_NOCANCEL = 403
+ SYS_ACCEPT_NOCANCEL = 404
+ SYS_MSYNC_NOCANCEL = 405
+ SYS_FCNTL_NOCANCEL = 406
+ SYS_SELECT_NOCANCEL = 407
+ SYS_FSYNC_NOCANCEL = 408
+ SYS_CONNECT_NOCANCEL = 409
+ SYS_SIGSUSPEND_NOCANCEL = 410
+ SYS_READV_NOCANCEL = 411
+ SYS_WRITEV_NOCANCEL = 412
+ SYS_SENDTO_NOCANCEL = 413
+ SYS_PREAD_NOCANCEL = 414
+ SYS_PWRITE_NOCANCEL = 415
+ SYS_WAITID_NOCANCEL = 416
+ SYS_POLL_NOCANCEL = 417
+ SYS_MSGSND_NOCANCEL = 418
+ SYS_MSGRCV_NOCANCEL = 419
+ SYS_SEM_WAIT_NOCANCEL = 420
+ SYS_AIO_SUSPEND_NOCANCEL = 421
+ SYS___SIGWAIT_NOCANCEL = 422
+ SYS___SEMWAIT_SIGNAL_NOCANCEL = 423
+ SYS___MAC_MOUNT = 424
+ SYS___MAC_GET_MOUNT = 425
+ SYS___MAC_GETFSSTAT = 426
+ SYS_FSGETPATH = 427
+ SYS_AUDIT_SESSION_SELF = 428
+ SYS_AUDIT_SESSION_JOIN = 429
+ SYS_FILEPORT_MAKEPORT = 430
+ SYS_FILEPORT_MAKEFD = 431
+ SYS_AUDIT_SESSION_PORT = 432
+ SYS_PID_SUSPEND = 433
+ SYS_PID_RESUME = 434
+ SYS_PID_HIBERNATE = 435
+ SYS_PID_SHUTDOWN_SOCKETS = 436
+ SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438
+ SYS_KAS_INFO = 439
+ SYS_MEMORYSTATUS_CONTROL = 440
+ SYS_GUARDED_OPEN_NP = 441
+ SYS_GUARDED_CLOSE_NP = 442
+ SYS_GUARDED_KQUEUE_NP = 443
+ SYS_CHANGE_FDGUARD_NP = 444
+ SYS_PROC_RLIMIT_CONTROL = 446
+ SYS_CONNECTX = 447
+ SYS_DISCONNECTX = 448
+ SYS_PEELOFF = 449
+ SYS_SOCKET_DELEGATE = 450
+ SYS_TELEMETRY = 451
+ SYS_PROC_UUID_POLICY = 452
+ SYS_MEMORYSTATUS_GET_LEVEL = 453
+ SYS_SYSTEM_OVERRIDE = 454
+ SYS_VFS_PURGE = 455
+ SYS_SFI_CTL = 456
+ SYS_SFI_PIDCTL = 457
+ SYS_COALITION = 458
+ SYS_COALITION_INFO = 459
+ SYS_NECP_MATCH_POLICY = 460
+ SYS_GETATTRLISTBULK = 461
+ SYS_OPENAT = 463
+ SYS_OPENAT_NOCANCEL = 464
+ SYS_RENAMEAT = 465
+ SYS_FACCESSAT = 466
+ SYS_FCHMODAT = 467
+ SYS_FCHOWNAT = 468
+ SYS_FSTATAT = 469
+ SYS_FSTATAT64 = 470
+ SYS_LINKAT = 471
+ SYS_UNLINKAT = 472
+ SYS_READLINKAT = 473
+ SYS_SYMLINKAT = 474
+ SYS_MKDIRAT = 475
+ SYS_GETATTRLISTAT = 476
+ SYS_PROC_TRACE_LOG = 477
+ SYS_BSDTHREAD_CTL = 478
+ SYS_OPENBYID_NP = 479
+ SYS_RECVMSG_X = 480
+ SYS_SENDMSG_X = 481
+ SYS_THREAD_SELFUSAGE = 482
+ SYS_CSRCTL = 483
+ SYS_GUARDED_OPEN_DPROTECTED_NP = 484
+ SYS_GUARDED_WRITE_NP = 485
+ SYS_GUARDED_PWRITE_NP = 486
+ SYS_GUARDED_WRITEV_NP = 487
+ SYS_RENAME_EXT = 488
+ SYS_MREMAP_ENCRYPTED = 489
+ SYS_MAXSYSCALL = 490
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go
new file mode 100644
index 0000000..09de240
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go
@@ -0,0 +1,398 @@
+// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/sys/syscall.h
+// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT
+
+// +build amd64,darwin
+
+package unix
+
+const (
+ SYS_SYSCALL = 0
+ SYS_EXIT = 1
+ SYS_FORK = 2
+ SYS_READ = 3
+ SYS_WRITE = 4
+ SYS_OPEN = 5
+ SYS_CLOSE = 6
+ SYS_WAIT4 = 7
+ SYS_LINK = 9
+ SYS_UNLINK = 10
+ SYS_CHDIR = 12
+ SYS_FCHDIR = 13
+ SYS_MKNOD = 14
+ SYS_CHMOD = 15
+ SYS_CHOWN = 16
+ SYS_GETFSSTAT = 18
+ SYS_GETPID = 20
+ SYS_SETUID = 23
+ SYS_GETUID = 24
+ SYS_GETEUID = 25
+ SYS_PTRACE = 26
+ SYS_RECVMSG = 27
+ SYS_SENDMSG = 28
+ SYS_RECVFROM = 29
+ SYS_ACCEPT = 30
+ SYS_GETPEERNAME = 31
+ SYS_GETSOCKNAME = 32
+ SYS_ACCESS = 33
+ SYS_CHFLAGS = 34
+ SYS_FCHFLAGS = 35
+ SYS_SYNC = 36
+ SYS_KILL = 37
+ SYS_GETPPID = 39
+ SYS_DUP = 41
+ SYS_PIPE = 42
+ SYS_GETEGID = 43
+ SYS_SIGACTION = 46
+ SYS_GETGID = 47
+ SYS_SIGPROCMASK = 48
+ SYS_GETLOGIN = 49
+ SYS_SETLOGIN = 50
+ SYS_ACCT = 51
+ SYS_SIGPENDING = 52
+ SYS_SIGALTSTACK = 53
+ SYS_IOCTL = 54
+ SYS_REBOOT = 55
+ SYS_REVOKE = 56
+ SYS_SYMLINK = 57
+ SYS_READLINK = 58
+ SYS_EXECVE = 59
+ SYS_UMASK = 60
+ SYS_CHROOT = 61
+ SYS_MSYNC = 65
+ SYS_VFORK = 66
+ SYS_MUNMAP = 73
+ SYS_MPROTECT = 74
+ SYS_MADVISE = 75
+ SYS_MINCORE = 78
+ SYS_GETGROUPS = 79
+ SYS_SETGROUPS = 80
+ SYS_GETPGRP = 81
+ SYS_SETPGID = 82
+ SYS_SETITIMER = 83
+ SYS_SWAPON = 85
+ SYS_GETITIMER = 86
+ SYS_GETDTABLESIZE = 89
+ SYS_DUP2 = 90
+ SYS_FCNTL = 92
+ SYS_SELECT = 93
+ SYS_FSYNC = 95
+ SYS_SETPRIORITY = 96
+ SYS_SOCKET = 97
+ SYS_CONNECT = 98
+ SYS_GETPRIORITY = 100
+ SYS_BIND = 104
+ SYS_SETSOCKOPT = 105
+ SYS_LISTEN = 106
+ SYS_SIGSUSPEND = 111
+ SYS_GETTIMEOFDAY = 116
+ SYS_GETRUSAGE = 117
+ SYS_GETSOCKOPT = 118
+ SYS_READV = 120
+ SYS_WRITEV = 121
+ SYS_SETTIMEOFDAY = 122
+ SYS_FCHOWN = 123
+ SYS_FCHMOD = 124
+ SYS_SETREUID = 126
+ SYS_SETREGID = 127
+ SYS_RENAME = 128
+ SYS_FLOCK = 131
+ SYS_MKFIFO = 132
+ SYS_SENDTO = 133
+ SYS_SHUTDOWN = 134
+ SYS_SOCKETPAIR = 135
+ SYS_MKDIR = 136
+ SYS_RMDIR = 137
+ SYS_UTIMES = 138
+ SYS_FUTIMES = 139
+ SYS_ADJTIME = 140
+ SYS_GETHOSTUUID = 142
+ SYS_SETSID = 147
+ SYS_GETPGID = 151
+ SYS_SETPRIVEXEC = 152
+ SYS_PREAD = 153
+ SYS_PWRITE = 154
+ SYS_NFSSVC = 155
+ SYS_STATFS = 157
+ SYS_FSTATFS = 158
+ SYS_UNMOUNT = 159
+ SYS_GETFH = 161
+ SYS_QUOTACTL = 165
+ SYS_MOUNT = 167
+ SYS_CSOPS = 169
+ SYS_CSOPS_AUDITTOKEN = 170
+ SYS_WAITID = 173
+ SYS_KDEBUG_TRACE64 = 179
+ SYS_KDEBUG_TRACE = 180
+ SYS_SETGID = 181
+ SYS_SETEGID = 182
+ SYS_SETEUID = 183
+ SYS_SIGRETURN = 184
+ SYS_CHUD = 185
+ SYS_FDATASYNC = 187
+ SYS_STAT = 188
+ SYS_FSTAT = 189
+ SYS_LSTAT = 190
+ SYS_PATHCONF = 191
+ SYS_FPATHCONF = 192
+ SYS_GETRLIMIT = 194
+ SYS_SETRLIMIT = 195
+ SYS_GETDIRENTRIES = 196
+ SYS_MMAP = 197
+ SYS_LSEEK = 199
+ SYS_TRUNCATE = 200
+ SYS_FTRUNCATE = 201
+ SYS_SYSCTL = 202
+ SYS_MLOCK = 203
+ SYS_MUNLOCK = 204
+ SYS_UNDELETE = 205
+ SYS_OPEN_DPROTECTED_NP = 216
+ SYS_GETATTRLIST = 220
+ SYS_SETATTRLIST = 221
+ SYS_GETDIRENTRIESATTR = 222
+ SYS_EXCHANGEDATA = 223
+ SYS_SEARCHFS = 225
+ SYS_DELETE = 226
+ SYS_COPYFILE = 227
+ SYS_FGETATTRLIST = 228
+ SYS_FSETATTRLIST = 229
+ SYS_POLL = 230
+ SYS_WATCHEVENT = 231
+ SYS_WAITEVENT = 232
+ SYS_MODWATCH = 233
+ SYS_GETXATTR = 234
+ SYS_FGETXATTR = 235
+ SYS_SETXATTR = 236
+ SYS_FSETXATTR = 237
+ SYS_REMOVEXATTR = 238
+ SYS_FREMOVEXATTR = 239
+ SYS_LISTXATTR = 240
+ SYS_FLISTXATTR = 241
+ SYS_FSCTL = 242
+ SYS_INITGROUPS = 243
+ SYS_POSIX_SPAWN = 244
+ SYS_FFSCTL = 245
+ SYS_NFSCLNT = 247
+ SYS_FHOPEN = 248
+ SYS_MINHERIT = 250
+ SYS_SEMSYS = 251
+ SYS_MSGSYS = 252
+ SYS_SHMSYS = 253
+ SYS_SEMCTL = 254
+ SYS_SEMGET = 255
+ SYS_SEMOP = 256
+ SYS_MSGCTL = 258
+ SYS_MSGGET = 259
+ SYS_MSGSND = 260
+ SYS_MSGRCV = 261
+ SYS_SHMAT = 262
+ SYS_SHMCTL = 263
+ SYS_SHMDT = 264
+ SYS_SHMGET = 265
+ SYS_SHM_OPEN = 266
+ SYS_SHM_UNLINK = 267
+ SYS_SEM_OPEN = 268
+ SYS_SEM_CLOSE = 269
+ SYS_SEM_UNLINK = 270
+ SYS_SEM_WAIT = 271
+ SYS_SEM_TRYWAIT = 272
+ SYS_SEM_POST = 273
+ SYS_SYSCTLBYNAME = 274
+ SYS_OPEN_EXTENDED = 277
+ SYS_UMASK_EXTENDED = 278
+ SYS_STAT_EXTENDED = 279
+ SYS_LSTAT_EXTENDED = 280
+ SYS_FSTAT_EXTENDED = 281
+ SYS_CHMOD_EXTENDED = 282
+ SYS_FCHMOD_EXTENDED = 283
+ SYS_ACCESS_EXTENDED = 284
+ SYS_SETTID = 285
+ SYS_GETTID = 286
+ SYS_SETSGROUPS = 287
+ SYS_GETSGROUPS = 288
+ SYS_SETWGROUPS = 289
+ SYS_GETWGROUPS = 290
+ SYS_MKFIFO_EXTENDED = 291
+ SYS_MKDIR_EXTENDED = 292
+ SYS_IDENTITYSVC = 293
+ SYS_SHARED_REGION_CHECK_NP = 294
+ SYS_VM_PRESSURE_MONITOR = 296
+ SYS_PSYNCH_RW_LONGRDLOCK = 297
+ SYS_PSYNCH_RW_YIELDWRLOCK = 298
+ SYS_PSYNCH_RW_DOWNGRADE = 299
+ SYS_PSYNCH_RW_UPGRADE = 300
+ SYS_PSYNCH_MUTEXWAIT = 301
+ SYS_PSYNCH_MUTEXDROP = 302
+ SYS_PSYNCH_CVBROAD = 303
+ SYS_PSYNCH_CVSIGNAL = 304
+ SYS_PSYNCH_CVWAIT = 305
+ SYS_PSYNCH_RW_RDLOCK = 306
+ SYS_PSYNCH_RW_WRLOCK = 307
+ SYS_PSYNCH_RW_UNLOCK = 308
+ SYS_PSYNCH_RW_UNLOCK2 = 309
+ SYS_GETSID = 310
+ SYS_SETTID_WITH_PID = 311
+ SYS_PSYNCH_CVCLRPREPOST = 312
+ SYS_AIO_FSYNC = 313
+ SYS_AIO_RETURN = 314
+ SYS_AIO_SUSPEND = 315
+ SYS_AIO_CANCEL = 316
+ SYS_AIO_ERROR = 317
+ SYS_AIO_READ = 318
+ SYS_AIO_WRITE = 319
+ SYS_LIO_LISTIO = 320
+ SYS_IOPOLICYSYS = 322
+ SYS_PROCESS_POLICY = 323
+ SYS_MLOCKALL = 324
+ SYS_MUNLOCKALL = 325
+ SYS_ISSETUGID = 327
+ SYS___PTHREAD_KILL = 328
+ SYS___PTHREAD_SIGMASK = 329
+ SYS___SIGWAIT = 330
+ SYS___DISABLE_THREADSIGNAL = 331
+ SYS___PTHREAD_MARKCANCEL = 332
+ SYS___PTHREAD_CANCELED = 333
+ SYS___SEMWAIT_SIGNAL = 334
+ SYS_PROC_INFO = 336
+ SYS_SENDFILE = 337
+ SYS_STAT64 = 338
+ SYS_FSTAT64 = 339
+ SYS_LSTAT64 = 340
+ SYS_STAT64_EXTENDED = 341
+ SYS_LSTAT64_EXTENDED = 342
+ SYS_FSTAT64_EXTENDED = 343
+ SYS_GETDIRENTRIES64 = 344
+ SYS_STATFS64 = 345
+ SYS_FSTATFS64 = 346
+ SYS_GETFSSTAT64 = 347
+ SYS___PTHREAD_CHDIR = 348
+ SYS___PTHREAD_FCHDIR = 349
+ SYS_AUDIT = 350
+ SYS_AUDITON = 351
+ SYS_GETAUID = 353
+ SYS_SETAUID = 354
+ SYS_GETAUDIT_ADDR = 357
+ SYS_SETAUDIT_ADDR = 358
+ SYS_AUDITCTL = 359
+ SYS_BSDTHREAD_CREATE = 360
+ SYS_BSDTHREAD_TERMINATE = 361
+ SYS_KQUEUE = 362
+ SYS_KEVENT = 363
+ SYS_LCHOWN = 364
+ SYS_STACK_SNAPSHOT = 365
+ SYS_BSDTHREAD_REGISTER = 366
+ SYS_WORKQ_OPEN = 367
+ SYS_WORKQ_KERNRETURN = 368
+ SYS_KEVENT64 = 369
+ SYS___OLD_SEMWAIT_SIGNAL = 370
+ SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371
+ SYS_THREAD_SELFID = 372
+ SYS_LEDGER = 373
+ SYS___MAC_EXECVE = 380
+ SYS___MAC_SYSCALL = 381
+ SYS___MAC_GET_FILE = 382
+ SYS___MAC_SET_FILE = 383
+ SYS___MAC_GET_LINK = 384
+ SYS___MAC_SET_LINK = 385
+ SYS___MAC_GET_PROC = 386
+ SYS___MAC_SET_PROC = 387
+ SYS___MAC_GET_FD = 388
+ SYS___MAC_SET_FD = 389
+ SYS___MAC_GET_PID = 390
+ SYS___MAC_GET_LCID = 391
+ SYS___MAC_GET_LCTX = 392
+ SYS___MAC_SET_LCTX = 393
+ SYS_SETLCID = 394
+ SYS_GETLCID = 395
+ SYS_READ_NOCANCEL = 396
+ SYS_WRITE_NOCANCEL = 397
+ SYS_OPEN_NOCANCEL = 398
+ SYS_CLOSE_NOCANCEL = 399
+ SYS_WAIT4_NOCANCEL = 400
+ SYS_RECVMSG_NOCANCEL = 401
+ SYS_SENDMSG_NOCANCEL = 402
+ SYS_RECVFROM_NOCANCEL = 403
+ SYS_ACCEPT_NOCANCEL = 404
+ SYS_MSYNC_NOCANCEL = 405
+ SYS_FCNTL_NOCANCEL = 406
+ SYS_SELECT_NOCANCEL = 407
+ SYS_FSYNC_NOCANCEL = 408
+ SYS_CONNECT_NOCANCEL = 409
+ SYS_SIGSUSPEND_NOCANCEL = 410
+ SYS_READV_NOCANCEL = 411
+ SYS_WRITEV_NOCANCEL = 412
+ SYS_SENDTO_NOCANCEL = 413
+ SYS_PREAD_NOCANCEL = 414
+ SYS_PWRITE_NOCANCEL = 415
+ SYS_WAITID_NOCANCEL = 416
+ SYS_POLL_NOCANCEL = 417
+ SYS_MSGSND_NOCANCEL = 418
+ SYS_MSGRCV_NOCANCEL = 419
+ SYS_SEM_WAIT_NOCANCEL = 420
+ SYS_AIO_SUSPEND_NOCANCEL = 421
+ SYS___SIGWAIT_NOCANCEL = 422
+ SYS___SEMWAIT_SIGNAL_NOCANCEL = 423
+ SYS___MAC_MOUNT = 424
+ SYS___MAC_GET_MOUNT = 425
+ SYS___MAC_GETFSSTAT = 426
+ SYS_FSGETPATH = 427
+ SYS_AUDIT_SESSION_SELF = 428
+ SYS_AUDIT_SESSION_JOIN = 429
+ SYS_FILEPORT_MAKEPORT = 430
+ SYS_FILEPORT_MAKEFD = 431
+ SYS_AUDIT_SESSION_PORT = 432
+ SYS_PID_SUSPEND = 433
+ SYS_PID_RESUME = 434
+ SYS_PID_HIBERNATE = 435
+ SYS_PID_SHUTDOWN_SOCKETS = 436
+ SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438
+ SYS_KAS_INFO = 439
+ SYS_MEMORYSTATUS_CONTROL = 440
+ SYS_GUARDED_OPEN_NP = 441
+ SYS_GUARDED_CLOSE_NP = 442
+ SYS_GUARDED_KQUEUE_NP = 443
+ SYS_CHANGE_FDGUARD_NP = 444
+ SYS_PROC_RLIMIT_CONTROL = 446
+ SYS_CONNECTX = 447
+ SYS_DISCONNECTX = 448
+ SYS_PEELOFF = 449
+ SYS_SOCKET_DELEGATE = 450
+ SYS_TELEMETRY = 451
+ SYS_PROC_UUID_POLICY = 452
+ SYS_MEMORYSTATUS_GET_LEVEL = 453
+ SYS_SYSTEM_OVERRIDE = 454
+ SYS_VFS_PURGE = 455
+ SYS_SFI_CTL = 456
+ SYS_SFI_PIDCTL = 457
+ SYS_COALITION = 458
+ SYS_COALITION_INFO = 459
+ SYS_NECP_MATCH_POLICY = 460
+ SYS_GETATTRLISTBULK = 461
+ SYS_OPENAT = 463
+ SYS_OPENAT_NOCANCEL = 464
+ SYS_RENAMEAT = 465
+ SYS_FACCESSAT = 466
+ SYS_FCHMODAT = 467
+ SYS_FCHOWNAT = 468
+ SYS_FSTATAT = 469
+ SYS_FSTATAT64 = 470
+ SYS_LINKAT = 471
+ SYS_UNLINKAT = 472
+ SYS_READLINKAT = 473
+ SYS_SYMLINKAT = 474
+ SYS_MKDIRAT = 475
+ SYS_GETATTRLISTAT = 476
+ SYS_PROC_TRACE_LOG = 477
+ SYS_BSDTHREAD_CTL = 478
+ SYS_OPENBYID_NP = 479
+ SYS_RECVMSG_X = 480
+ SYS_SENDMSG_X = 481
+ SYS_THREAD_SELFUSAGE = 482
+ SYS_CSRCTL = 483
+ SYS_GUARDED_OPEN_DPROTECTED_NP = 484
+ SYS_GUARDED_WRITE_NP = 485
+ SYS_GUARDED_PWRITE_NP = 486
+ SYS_GUARDED_WRITEV_NP = 487
+ SYS_RENAME_EXT = 488
+ SYS_MREMAP_ENCRYPTED = 489
+ SYS_MAXSYSCALL = 490
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm.go
new file mode 100644
index 0000000..41cb6ed
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm.go
@@ -0,0 +1,426 @@
+// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.2.sdk/usr/include/sys/syscall.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm,darwin
+
+package unix
+
+const (
+ SYS_SYSCALL = 0
+ SYS_EXIT = 1
+ SYS_FORK = 2
+ SYS_READ = 3
+ SYS_WRITE = 4
+ SYS_OPEN = 5
+ SYS_CLOSE = 6
+ SYS_WAIT4 = 7
+ SYS_LINK = 9
+ SYS_UNLINK = 10
+ SYS_CHDIR = 12
+ SYS_FCHDIR = 13
+ SYS_MKNOD = 14
+ SYS_CHMOD = 15
+ SYS_CHOWN = 16
+ SYS_GETFSSTAT = 18
+ SYS_GETPID = 20
+ SYS_SETUID = 23
+ SYS_GETUID = 24
+ SYS_GETEUID = 25
+ SYS_PTRACE = 26
+ SYS_RECVMSG = 27
+ SYS_SENDMSG = 28
+ SYS_RECVFROM = 29
+ SYS_ACCEPT = 30
+ SYS_GETPEERNAME = 31
+ SYS_GETSOCKNAME = 32
+ SYS_ACCESS = 33
+ SYS_CHFLAGS = 34
+ SYS_FCHFLAGS = 35
+ SYS_SYNC = 36
+ SYS_KILL = 37
+ SYS_GETPPID = 39
+ SYS_DUP = 41
+ SYS_PIPE = 42
+ SYS_GETEGID = 43
+ SYS_SIGACTION = 46
+ SYS_GETGID = 47
+ SYS_SIGPROCMASK = 48
+ SYS_GETLOGIN = 49
+ SYS_SETLOGIN = 50
+ SYS_ACCT = 51
+ SYS_SIGPENDING = 52
+ SYS_SIGALTSTACK = 53
+ SYS_IOCTL = 54
+ SYS_REBOOT = 55
+ SYS_REVOKE = 56
+ SYS_SYMLINK = 57
+ SYS_READLINK = 58
+ SYS_EXECVE = 59
+ SYS_UMASK = 60
+ SYS_CHROOT = 61
+ SYS_MSYNC = 65
+ SYS_VFORK = 66
+ SYS_MUNMAP = 73
+ SYS_MPROTECT = 74
+ SYS_MADVISE = 75
+ SYS_MINCORE = 78
+ SYS_GETGROUPS = 79
+ SYS_SETGROUPS = 80
+ SYS_GETPGRP = 81
+ SYS_SETPGID = 82
+ SYS_SETITIMER = 83
+ SYS_SWAPON = 85
+ SYS_GETITIMER = 86
+ SYS_GETDTABLESIZE = 89
+ SYS_DUP2 = 90
+ SYS_FCNTL = 92
+ SYS_SELECT = 93
+ SYS_FSYNC = 95
+ SYS_SETPRIORITY = 96
+ SYS_SOCKET = 97
+ SYS_CONNECT = 98
+ SYS_GETPRIORITY = 100
+ SYS_BIND = 104
+ SYS_SETSOCKOPT = 105
+ SYS_LISTEN = 106
+ SYS_SIGSUSPEND = 111
+ SYS_GETTIMEOFDAY = 116
+ SYS_GETRUSAGE = 117
+ SYS_GETSOCKOPT = 118
+ SYS_READV = 120
+ SYS_WRITEV = 121
+ SYS_SETTIMEOFDAY = 122
+ SYS_FCHOWN = 123
+ SYS_FCHMOD = 124
+ SYS_SETREUID = 126
+ SYS_SETREGID = 127
+ SYS_RENAME = 128
+ SYS_FLOCK = 131
+ SYS_MKFIFO = 132
+ SYS_SENDTO = 133
+ SYS_SHUTDOWN = 134
+ SYS_SOCKETPAIR = 135
+ SYS_MKDIR = 136
+ SYS_RMDIR = 137
+ SYS_UTIMES = 138
+ SYS_FUTIMES = 139
+ SYS_ADJTIME = 140
+ SYS_GETHOSTUUID = 142
+ SYS_SETSID = 147
+ SYS_GETPGID = 151
+ SYS_SETPRIVEXEC = 152
+ SYS_PREAD = 153
+ SYS_PWRITE = 154
+ SYS_NFSSVC = 155
+ SYS_STATFS = 157
+ SYS_FSTATFS = 158
+ SYS_UNMOUNT = 159
+ SYS_GETFH = 161
+ SYS_QUOTACTL = 165
+ SYS_MOUNT = 167
+ SYS_CSOPS = 169
+ SYS_CSOPS_AUDITTOKEN = 170
+ SYS_WAITID = 173
+ SYS_KDEBUG_TYPEFILTER = 177
+ SYS_KDEBUG_TRACE_STRING = 178
+ SYS_KDEBUG_TRACE64 = 179
+ SYS_KDEBUG_TRACE = 180
+ SYS_SETGID = 181
+ SYS_SETEGID = 182
+ SYS_SETEUID = 183
+ SYS_SIGRETURN = 184
+ SYS_FDATASYNC = 187
+ SYS_STAT = 188
+ SYS_FSTAT = 189
+ SYS_LSTAT = 190
+ SYS_PATHCONF = 191
+ SYS_FPATHCONF = 192
+ SYS_GETRLIMIT = 194
+ SYS_SETRLIMIT = 195
+ SYS_GETDIRENTRIES = 196
+ SYS_MMAP = 197
+ SYS_LSEEK = 199
+ SYS_TRUNCATE = 200
+ SYS_FTRUNCATE = 201
+ SYS_SYSCTL = 202
+ SYS_MLOCK = 203
+ SYS_MUNLOCK = 204
+ SYS_UNDELETE = 205
+ SYS_OPEN_DPROTECTED_NP = 216
+ SYS_GETATTRLIST = 220
+ SYS_SETATTRLIST = 221
+ SYS_GETDIRENTRIESATTR = 222
+ SYS_EXCHANGEDATA = 223
+ SYS_SEARCHFS = 225
+ SYS_DELETE = 226
+ SYS_COPYFILE = 227
+ SYS_FGETATTRLIST = 228
+ SYS_FSETATTRLIST = 229
+ SYS_POLL = 230
+ SYS_WATCHEVENT = 231
+ SYS_WAITEVENT = 232
+ SYS_MODWATCH = 233
+ SYS_GETXATTR = 234
+ SYS_FGETXATTR = 235
+ SYS_SETXATTR = 236
+ SYS_FSETXATTR = 237
+ SYS_REMOVEXATTR = 238
+ SYS_FREMOVEXATTR = 239
+ SYS_LISTXATTR = 240
+ SYS_FLISTXATTR = 241
+ SYS_FSCTL = 242
+ SYS_INITGROUPS = 243
+ SYS_POSIX_SPAWN = 244
+ SYS_FFSCTL = 245
+ SYS_NFSCLNT = 247
+ SYS_FHOPEN = 248
+ SYS_MINHERIT = 250
+ SYS_SEMSYS = 251
+ SYS_MSGSYS = 252
+ SYS_SHMSYS = 253
+ SYS_SEMCTL = 254
+ SYS_SEMGET = 255
+ SYS_SEMOP = 256
+ SYS_MSGCTL = 258
+ SYS_MSGGET = 259
+ SYS_MSGSND = 260
+ SYS_MSGRCV = 261
+ SYS_SHMAT = 262
+ SYS_SHMCTL = 263
+ SYS_SHMDT = 264
+ SYS_SHMGET = 265
+ SYS_SHM_OPEN = 266
+ SYS_SHM_UNLINK = 267
+ SYS_SEM_OPEN = 268
+ SYS_SEM_CLOSE = 269
+ SYS_SEM_UNLINK = 270
+ SYS_SEM_WAIT = 271
+ SYS_SEM_TRYWAIT = 272
+ SYS_SEM_POST = 273
+ SYS_SYSCTLBYNAME = 274
+ SYS_OPEN_EXTENDED = 277
+ SYS_UMASK_EXTENDED = 278
+ SYS_STAT_EXTENDED = 279
+ SYS_LSTAT_EXTENDED = 280
+ SYS_FSTAT_EXTENDED = 281
+ SYS_CHMOD_EXTENDED = 282
+ SYS_FCHMOD_EXTENDED = 283
+ SYS_ACCESS_EXTENDED = 284
+ SYS_SETTID = 285
+ SYS_GETTID = 286
+ SYS_SETSGROUPS = 287
+ SYS_GETSGROUPS = 288
+ SYS_SETWGROUPS = 289
+ SYS_GETWGROUPS = 290
+ SYS_MKFIFO_EXTENDED = 291
+ SYS_MKDIR_EXTENDED = 292
+ SYS_IDENTITYSVC = 293
+ SYS_SHARED_REGION_CHECK_NP = 294
+ SYS_VM_PRESSURE_MONITOR = 296
+ SYS_PSYNCH_RW_LONGRDLOCK = 297
+ SYS_PSYNCH_RW_YIELDWRLOCK = 298
+ SYS_PSYNCH_RW_DOWNGRADE = 299
+ SYS_PSYNCH_RW_UPGRADE = 300
+ SYS_PSYNCH_MUTEXWAIT = 301
+ SYS_PSYNCH_MUTEXDROP = 302
+ SYS_PSYNCH_CVBROAD = 303
+ SYS_PSYNCH_CVSIGNAL = 304
+ SYS_PSYNCH_CVWAIT = 305
+ SYS_PSYNCH_RW_RDLOCK = 306
+ SYS_PSYNCH_RW_WRLOCK = 307
+ SYS_PSYNCH_RW_UNLOCK = 308
+ SYS_PSYNCH_RW_UNLOCK2 = 309
+ SYS_GETSID = 310
+ SYS_SETTID_WITH_PID = 311
+ SYS_PSYNCH_CVCLRPREPOST = 312
+ SYS_AIO_FSYNC = 313
+ SYS_AIO_RETURN = 314
+ SYS_AIO_SUSPEND = 315
+ SYS_AIO_CANCEL = 316
+ SYS_AIO_ERROR = 317
+ SYS_AIO_READ = 318
+ SYS_AIO_WRITE = 319
+ SYS_LIO_LISTIO = 320
+ SYS_IOPOLICYSYS = 322
+ SYS_PROCESS_POLICY = 323
+ SYS_MLOCKALL = 324
+ SYS_MUNLOCKALL = 325
+ SYS_ISSETUGID = 327
+ SYS___PTHREAD_KILL = 328
+ SYS___PTHREAD_SIGMASK = 329
+ SYS___SIGWAIT = 330
+ SYS___DISABLE_THREADSIGNAL = 331
+ SYS___PTHREAD_MARKCANCEL = 332
+ SYS___PTHREAD_CANCELED = 333
+ SYS___SEMWAIT_SIGNAL = 334
+ SYS_PROC_INFO = 336
+ SYS_SENDFILE = 337
+ SYS_STAT64 = 338
+ SYS_FSTAT64 = 339
+ SYS_LSTAT64 = 340
+ SYS_STAT64_EXTENDED = 341
+ SYS_LSTAT64_EXTENDED = 342
+ SYS_FSTAT64_EXTENDED = 343
+ SYS_GETDIRENTRIES64 = 344
+ SYS_STATFS64 = 345
+ SYS_FSTATFS64 = 346
+ SYS_GETFSSTAT64 = 347
+ SYS___PTHREAD_CHDIR = 348
+ SYS___PTHREAD_FCHDIR = 349
+ SYS_AUDIT = 350
+ SYS_AUDITON = 351
+ SYS_GETAUID = 353
+ SYS_SETAUID = 354
+ SYS_GETAUDIT_ADDR = 357
+ SYS_SETAUDIT_ADDR = 358
+ SYS_AUDITCTL = 359
+ SYS_BSDTHREAD_CREATE = 360
+ SYS_BSDTHREAD_TERMINATE = 361
+ SYS_KQUEUE = 362
+ SYS_KEVENT = 363
+ SYS_LCHOWN = 364
+ SYS_BSDTHREAD_REGISTER = 366
+ SYS_WORKQ_OPEN = 367
+ SYS_WORKQ_KERNRETURN = 368
+ SYS_KEVENT64 = 369
+ SYS___OLD_SEMWAIT_SIGNAL = 370
+ SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371
+ SYS_THREAD_SELFID = 372
+ SYS_LEDGER = 373
+ SYS_KEVENT_QOS = 374
+ SYS___MAC_EXECVE = 380
+ SYS___MAC_SYSCALL = 381
+ SYS___MAC_GET_FILE = 382
+ SYS___MAC_SET_FILE = 383
+ SYS___MAC_GET_LINK = 384
+ SYS___MAC_SET_LINK = 385
+ SYS___MAC_GET_PROC = 386
+ SYS___MAC_SET_PROC = 387
+ SYS___MAC_GET_FD = 388
+ SYS___MAC_SET_FD = 389
+ SYS___MAC_GET_PID = 390
+ SYS_PSELECT = 394
+ SYS_PSELECT_NOCANCEL = 395
+ SYS_READ_NOCANCEL = 396
+ SYS_WRITE_NOCANCEL = 397
+ SYS_OPEN_NOCANCEL = 398
+ SYS_CLOSE_NOCANCEL = 399
+ SYS_WAIT4_NOCANCEL = 400
+ SYS_RECVMSG_NOCANCEL = 401
+ SYS_SENDMSG_NOCANCEL = 402
+ SYS_RECVFROM_NOCANCEL = 403
+ SYS_ACCEPT_NOCANCEL = 404
+ SYS_MSYNC_NOCANCEL = 405
+ SYS_FCNTL_NOCANCEL = 406
+ SYS_SELECT_NOCANCEL = 407
+ SYS_FSYNC_NOCANCEL = 408
+ SYS_CONNECT_NOCANCEL = 409
+ SYS_SIGSUSPEND_NOCANCEL = 410
+ SYS_READV_NOCANCEL = 411
+ SYS_WRITEV_NOCANCEL = 412
+ SYS_SENDTO_NOCANCEL = 413
+ SYS_PREAD_NOCANCEL = 414
+ SYS_PWRITE_NOCANCEL = 415
+ SYS_WAITID_NOCANCEL = 416
+ SYS_POLL_NOCANCEL = 417
+ SYS_MSGSND_NOCANCEL = 418
+ SYS_MSGRCV_NOCANCEL = 419
+ SYS_SEM_WAIT_NOCANCEL = 420
+ SYS_AIO_SUSPEND_NOCANCEL = 421
+ SYS___SIGWAIT_NOCANCEL = 422
+ SYS___SEMWAIT_SIGNAL_NOCANCEL = 423
+ SYS___MAC_MOUNT = 424
+ SYS___MAC_GET_MOUNT = 425
+ SYS___MAC_GETFSSTAT = 426
+ SYS_FSGETPATH = 427
+ SYS_AUDIT_SESSION_SELF = 428
+ SYS_AUDIT_SESSION_JOIN = 429
+ SYS_FILEPORT_MAKEPORT = 430
+ SYS_FILEPORT_MAKEFD = 431
+ SYS_AUDIT_SESSION_PORT = 432
+ SYS_PID_SUSPEND = 433
+ SYS_PID_RESUME = 434
+ SYS_PID_HIBERNATE = 435
+ SYS_PID_SHUTDOWN_SOCKETS = 436
+ SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438
+ SYS_KAS_INFO = 439
+ SYS_MEMORYSTATUS_CONTROL = 440
+ SYS_GUARDED_OPEN_NP = 441
+ SYS_GUARDED_CLOSE_NP = 442
+ SYS_GUARDED_KQUEUE_NP = 443
+ SYS_CHANGE_FDGUARD_NP = 444
+ SYS_USRCTL = 445
+ SYS_PROC_RLIMIT_CONTROL = 446
+ SYS_CONNECTX = 447
+ SYS_DISCONNECTX = 448
+ SYS_PEELOFF = 449
+ SYS_SOCKET_DELEGATE = 450
+ SYS_TELEMETRY = 451
+ SYS_PROC_UUID_POLICY = 452
+ SYS_MEMORYSTATUS_GET_LEVEL = 453
+ SYS_SYSTEM_OVERRIDE = 454
+ SYS_VFS_PURGE = 455
+ SYS_SFI_CTL = 456
+ SYS_SFI_PIDCTL = 457
+ SYS_COALITION = 458
+ SYS_COALITION_INFO = 459
+ SYS_NECP_MATCH_POLICY = 460
+ SYS_GETATTRLISTBULK = 461
+ SYS_CLONEFILEAT = 462
+ SYS_OPENAT = 463
+ SYS_OPENAT_NOCANCEL = 464
+ SYS_RENAMEAT = 465
+ SYS_FACCESSAT = 466
+ SYS_FCHMODAT = 467
+ SYS_FCHOWNAT = 468
+ SYS_FSTATAT = 469
+ SYS_FSTATAT64 = 470
+ SYS_LINKAT = 471
+ SYS_UNLINKAT = 472
+ SYS_READLINKAT = 473
+ SYS_SYMLINKAT = 474
+ SYS_MKDIRAT = 475
+ SYS_GETATTRLISTAT = 476
+ SYS_PROC_TRACE_LOG = 477
+ SYS_BSDTHREAD_CTL = 478
+ SYS_OPENBYID_NP = 479
+ SYS_RECVMSG_X = 480
+ SYS_SENDMSG_X = 481
+ SYS_THREAD_SELFUSAGE = 482
+ SYS_CSRCTL = 483
+ SYS_GUARDED_OPEN_DPROTECTED_NP = 484
+ SYS_GUARDED_WRITE_NP = 485
+ SYS_GUARDED_PWRITE_NP = 486
+ SYS_GUARDED_WRITEV_NP = 487
+ SYS_RENAMEATX_NP = 488
+ SYS_MREMAP_ENCRYPTED = 489
+ SYS_NETAGENT_TRIGGER = 490
+ SYS_STACK_SNAPSHOT_WITH_CONFIG = 491
+ SYS_MICROSTACKSHOT = 492
+ SYS_GRAB_PGO_DATA = 493
+ SYS_PERSONA = 494
+ SYS_WORK_INTERVAL_CTL = 499
+ SYS_GETENTROPY = 500
+ SYS_NECP_OPEN = 501
+ SYS_NECP_CLIENT_ACTION = 502
+ SYS___NEXUS_OPEN = 503
+ SYS___NEXUS_REGISTER = 504
+ SYS___NEXUS_DEREGISTER = 505
+ SYS___NEXUS_CREATE = 506
+ SYS___NEXUS_DESTROY = 507
+ SYS___NEXUS_GET_OPT = 508
+ SYS___NEXUS_SET_OPT = 509
+ SYS___CHANNEL_OPEN = 510
+ SYS___CHANNEL_GET_INFO = 511
+ SYS___CHANNEL_SYNC = 512
+ SYS___CHANNEL_GET_OPT = 513
+ SYS___CHANNEL_SET_OPT = 514
+ SYS_ULOCK_WAIT = 515
+ SYS_ULOCK_WAKE = 516
+ SYS_FCLONEFILEAT = 517
+ SYS_FS_SNAPSHOT = 518
+ SYS_TERMINATE_WITH_PAYLOAD = 520
+ SYS_ABORT_WITH_PAYLOAD = 521
+ SYS_MAXSYSCALL = 522
+ SYS_INVALID = 63
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go
new file mode 100644
index 0000000..075816c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go
@@ -0,0 +1,426 @@
+// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.2.sdk/usr/include/sys/syscall.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm64,darwin
+
+package unix
+
+const (
+ SYS_SYSCALL = 0
+ SYS_EXIT = 1
+ SYS_FORK = 2
+ SYS_READ = 3
+ SYS_WRITE = 4
+ SYS_OPEN = 5
+ SYS_CLOSE = 6
+ SYS_WAIT4 = 7
+ SYS_LINK = 9
+ SYS_UNLINK = 10
+ SYS_CHDIR = 12
+ SYS_FCHDIR = 13
+ SYS_MKNOD = 14
+ SYS_CHMOD = 15
+ SYS_CHOWN = 16
+ SYS_GETFSSTAT = 18
+ SYS_GETPID = 20
+ SYS_SETUID = 23
+ SYS_GETUID = 24
+ SYS_GETEUID = 25
+ SYS_PTRACE = 26
+ SYS_RECVMSG = 27
+ SYS_SENDMSG = 28
+ SYS_RECVFROM = 29
+ SYS_ACCEPT = 30
+ SYS_GETPEERNAME = 31
+ SYS_GETSOCKNAME = 32
+ SYS_ACCESS = 33
+ SYS_CHFLAGS = 34
+ SYS_FCHFLAGS = 35
+ SYS_SYNC = 36
+ SYS_KILL = 37
+ SYS_GETPPID = 39
+ SYS_DUP = 41
+ SYS_PIPE = 42
+ SYS_GETEGID = 43
+ SYS_SIGACTION = 46
+ SYS_GETGID = 47
+ SYS_SIGPROCMASK = 48
+ SYS_GETLOGIN = 49
+ SYS_SETLOGIN = 50
+ SYS_ACCT = 51
+ SYS_SIGPENDING = 52
+ SYS_SIGALTSTACK = 53
+ SYS_IOCTL = 54
+ SYS_REBOOT = 55
+ SYS_REVOKE = 56
+ SYS_SYMLINK = 57
+ SYS_READLINK = 58
+ SYS_EXECVE = 59
+ SYS_UMASK = 60
+ SYS_CHROOT = 61
+ SYS_MSYNC = 65
+ SYS_VFORK = 66
+ SYS_MUNMAP = 73
+ SYS_MPROTECT = 74
+ SYS_MADVISE = 75
+ SYS_MINCORE = 78
+ SYS_GETGROUPS = 79
+ SYS_SETGROUPS = 80
+ SYS_GETPGRP = 81
+ SYS_SETPGID = 82
+ SYS_SETITIMER = 83
+ SYS_SWAPON = 85
+ SYS_GETITIMER = 86
+ SYS_GETDTABLESIZE = 89
+ SYS_DUP2 = 90
+ SYS_FCNTL = 92
+ SYS_SELECT = 93
+ SYS_FSYNC = 95
+ SYS_SETPRIORITY = 96
+ SYS_SOCKET = 97
+ SYS_CONNECT = 98
+ SYS_GETPRIORITY = 100
+ SYS_BIND = 104
+ SYS_SETSOCKOPT = 105
+ SYS_LISTEN = 106
+ SYS_SIGSUSPEND = 111
+ SYS_GETTIMEOFDAY = 116
+ SYS_GETRUSAGE = 117
+ SYS_GETSOCKOPT = 118
+ SYS_READV = 120
+ SYS_WRITEV = 121
+ SYS_SETTIMEOFDAY = 122
+ SYS_FCHOWN = 123
+ SYS_FCHMOD = 124
+ SYS_SETREUID = 126
+ SYS_SETREGID = 127
+ SYS_RENAME = 128
+ SYS_FLOCK = 131
+ SYS_MKFIFO = 132
+ SYS_SENDTO = 133
+ SYS_SHUTDOWN = 134
+ SYS_SOCKETPAIR = 135
+ SYS_MKDIR = 136
+ SYS_RMDIR = 137
+ SYS_UTIMES = 138
+ SYS_FUTIMES = 139
+ SYS_ADJTIME = 140
+ SYS_GETHOSTUUID = 142
+ SYS_SETSID = 147
+ SYS_GETPGID = 151
+ SYS_SETPRIVEXEC = 152
+ SYS_PREAD = 153
+ SYS_PWRITE = 154
+ SYS_NFSSVC = 155
+ SYS_STATFS = 157
+ SYS_FSTATFS = 158
+ SYS_UNMOUNT = 159
+ SYS_GETFH = 161
+ SYS_QUOTACTL = 165
+ SYS_MOUNT = 167
+ SYS_CSOPS = 169
+ SYS_CSOPS_AUDITTOKEN = 170
+ SYS_WAITID = 173
+ SYS_KDEBUG_TYPEFILTER = 177
+ SYS_KDEBUG_TRACE_STRING = 178
+ SYS_KDEBUG_TRACE64 = 179
+ SYS_KDEBUG_TRACE = 180
+ SYS_SETGID = 181
+ SYS_SETEGID = 182
+ SYS_SETEUID = 183
+ SYS_SIGRETURN = 184
+ SYS_FDATASYNC = 187
+ SYS_STAT = 188
+ SYS_FSTAT = 189
+ SYS_LSTAT = 190
+ SYS_PATHCONF = 191
+ SYS_FPATHCONF = 192
+ SYS_GETRLIMIT = 194
+ SYS_SETRLIMIT = 195
+ SYS_GETDIRENTRIES = 196
+ SYS_MMAP = 197
+ SYS_LSEEK = 199
+ SYS_TRUNCATE = 200
+ SYS_FTRUNCATE = 201
+ SYS_SYSCTL = 202
+ SYS_MLOCK = 203
+ SYS_MUNLOCK = 204
+ SYS_UNDELETE = 205
+ SYS_OPEN_DPROTECTED_NP = 216
+ SYS_GETATTRLIST = 220
+ SYS_SETATTRLIST = 221
+ SYS_GETDIRENTRIESATTR = 222
+ SYS_EXCHANGEDATA = 223
+ SYS_SEARCHFS = 225
+ SYS_DELETE = 226
+ SYS_COPYFILE = 227
+ SYS_FGETATTRLIST = 228
+ SYS_FSETATTRLIST = 229
+ SYS_POLL = 230
+ SYS_WATCHEVENT = 231
+ SYS_WAITEVENT = 232
+ SYS_MODWATCH = 233
+ SYS_GETXATTR = 234
+ SYS_FGETXATTR = 235
+ SYS_SETXATTR = 236
+ SYS_FSETXATTR = 237
+ SYS_REMOVEXATTR = 238
+ SYS_FREMOVEXATTR = 239
+ SYS_LISTXATTR = 240
+ SYS_FLISTXATTR = 241
+ SYS_FSCTL = 242
+ SYS_INITGROUPS = 243
+ SYS_POSIX_SPAWN = 244
+ SYS_FFSCTL = 245
+ SYS_NFSCLNT = 247
+ SYS_FHOPEN = 248
+ SYS_MINHERIT = 250
+ SYS_SEMSYS = 251
+ SYS_MSGSYS = 252
+ SYS_SHMSYS = 253
+ SYS_SEMCTL = 254
+ SYS_SEMGET = 255
+ SYS_SEMOP = 256
+ SYS_MSGCTL = 258
+ SYS_MSGGET = 259
+ SYS_MSGSND = 260
+ SYS_MSGRCV = 261
+ SYS_SHMAT = 262
+ SYS_SHMCTL = 263
+ SYS_SHMDT = 264
+ SYS_SHMGET = 265
+ SYS_SHM_OPEN = 266
+ SYS_SHM_UNLINK = 267
+ SYS_SEM_OPEN = 268
+ SYS_SEM_CLOSE = 269
+ SYS_SEM_UNLINK = 270
+ SYS_SEM_WAIT = 271
+ SYS_SEM_TRYWAIT = 272
+ SYS_SEM_POST = 273
+ SYS_SYSCTLBYNAME = 274
+ SYS_OPEN_EXTENDED = 277
+ SYS_UMASK_EXTENDED = 278
+ SYS_STAT_EXTENDED = 279
+ SYS_LSTAT_EXTENDED = 280
+ SYS_FSTAT_EXTENDED = 281
+ SYS_CHMOD_EXTENDED = 282
+ SYS_FCHMOD_EXTENDED = 283
+ SYS_ACCESS_EXTENDED = 284
+ SYS_SETTID = 285
+ SYS_GETTID = 286
+ SYS_SETSGROUPS = 287
+ SYS_GETSGROUPS = 288
+ SYS_SETWGROUPS = 289
+ SYS_GETWGROUPS = 290
+ SYS_MKFIFO_EXTENDED = 291
+ SYS_MKDIR_EXTENDED = 292
+ SYS_IDENTITYSVC = 293
+ SYS_SHARED_REGION_CHECK_NP = 294
+ SYS_VM_PRESSURE_MONITOR = 296
+ SYS_PSYNCH_RW_LONGRDLOCK = 297
+ SYS_PSYNCH_RW_YIELDWRLOCK = 298
+ SYS_PSYNCH_RW_DOWNGRADE = 299
+ SYS_PSYNCH_RW_UPGRADE = 300
+ SYS_PSYNCH_MUTEXWAIT = 301
+ SYS_PSYNCH_MUTEXDROP = 302
+ SYS_PSYNCH_CVBROAD = 303
+ SYS_PSYNCH_CVSIGNAL = 304
+ SYS_PSYNCH_CVWAIT = 305
+ SYS_PSYNCH_RW_RDLOCK = 306
+ SYS_PSYNCH_RW_WRLOCK = 307
+ SYS_PSYNCH_RW_UNLOCK = 308
+ SYS_PSYNCH_RW_UNLOCK2 = 309
+ SYS_GETSID = 310
+ SYS_SETTID_WITH_PID = 311
+ SYS_PSYNCH_CVCLRPREPOST = 312
+ SYS_AIO_FSYNC = 313
+ SYS_AIO_RETURN = 314
+ SYS_AIO_SUSPEND = 315
+ SYS_AIO_CANCEL = 316
+ SYS_AIO_ERROR = 317
+ SYS_AIO_READ = 318
+ SYS_AIO_WRITE = 319
+ SYS_LIO_LISTIO = 320
+ SYS_IOPOLICYSYS = 322
+ SYS_PROCESS_POLICY = 323
+ SYS_MLOCKALL = 324
+ SYS_MUNLOCKALL = 325
+ SYS_ISSETUGID = 327
+ SYS___PTHREAD_KILL = 328
+ SYS___PTHREAD_SIGMASK = 329
+ SYS___SIGWAIT = 330
+ SYS___DISABLE_THREADSIGNAL = 331
+ SYS___PTHREAD_MARKCANCEL = 332
+ SYS___PTHREAD_CANCELED = 333
+ SYS___SEMWAIT_SIGNAL = 334
+ SYS_PROC_INFO = 336
+ SYS_SENDFILE = 337
+ SYS_STAT64 = 338
+ SYS_FSTAT64 = 339
+ SYS_LSTAT64 = 340
+ SYS_STAT64_EXTENDED = 341
+ SYS_LSTAT64_EXTENDED = 342
+ SYS_FSTAT64_EXTENDED = 343
+ SYS_GETDIRENTRIES64 = 344
+ SYS_STATFS64 = 345
+ SYS_FSTATFS64 = 346
+ SYS_GETFSSTAT64 = 347
+ SYS___PTHREAD_CHDIR = 348
+ SYS___PTHREAD_FCHDIR = 349
+ SYS_AUDIT = 350
+ SYS_AUDITON = 351
+ SYS_GETAUID = 353
+ SYS_SETAUID = 354
+ SYS_GETAUDIT_ADDR = 357
+ SYS_SETAUDIT_ADDR = 358
+ SYS_AUDITCTL = 359
+ SYS_BSDTHREAD_CREATE = 360
+ SYS_BSDTHREAD_TERMINATE = 361
+ SYS_KQUEUE = 362
+ SYS_KEVENT = 363
+ SYS_LCHOWN = 364
+ SYS_BSDTHREAD_REGISTER = 366
+ SYS_WORKQ_OPEN = 367
+ SYS_WORKQ_KERNRETURN = 368
+ SYS_KEVENT64 = 369
+ SYS___OLD_SEMWAIT_SIGNAL = 370
+ SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371
+ SYS_THREAD_SELFID = 372
+ SYS_LEDGER = 373
+ SYS_KEVENT_QOS = 374
+ SYS___MAC_EXECVE = 380
+ SYS___MAC_SYSCALL = 381
+ SYS___MAC_GET_FILE = 382
+ SYS___MAC_SET_FILE = 383
+ SYS___MAC_GET_LINK = 384
+ SYS___MAC_SET_LINK = 385
+ SYS___MAC_GET_PROC = 386
+ SYS___MAC_SET_PROC = 387
+ SYS___MAC_GET_FD = 388
+ SYS___MAC_SET_FD = 389
+ SYS___MAC_GET_PID = 390
+ SYS_PSELECT = 394
+ SYS_PSELECT_NOCANCEL = 395
+ SYS_READ_NOCANCEL = 396
+ SYS_WRITE_NOCANCEL = 397
+ SYS_OPEN_NOCANCEL = 398
+ SYS_CLOSE_NOCANCEL = 399
+ SYS_WAIT4_NOCANCEL = 400
+ SYS_RECVMSG_NOCANCEL = 401
+ SYS_SENDMSG_NOCANCEL = 402
+ SYS_RECVFROM_NOCANCEL = 403
+ SYS_ACCEPT_NOCANCEL = 404
+ SYS_MSYNC_NOCANCEL = 405
+ SYS_FCNTL_NOCANCEL = 406
+ SYS_SELECT_NOCANCEL = 407
+ SYS_FSYNC_NOCANCEL = 408
+ SYS_CONNECT_NOCANCEL = 409
+ SYS_SIGSUSPEND_NOCANCEL = 410
+ SYS_READV_NOCANCEL = 411
+ SYS_WRITEV_NOCANCEL = 412
+ SYS_SENDTO_NOCANCEL = 413
+ SYS_PREAD_NOCANCEL = 414
+ SYS_PWRITE_NOCANCEL = 415
+ SYS_WAITID_NOCANCEL = 416
+ SYS_POLL_NOCANCEL = 417
+ SYS_MSGSND_NOCANCEL = 418
+ SYS_MSGRCV_NOCANCEL = 419
+ SYS_SEM_WAIT_NOCANCEL = 420
+ SYS_AIO_SUSPEND_NOCANCEL = 421
+ SYS___SIGWAIT_NOCANCEL = 422
+ SYS___SEMWAIT_SIGNAL_NOCANCEL = 423
+ SYS___MAC_MOUNT = 424
+ SYS___MAC_GET_MOUNT = 425
+ SYS___MAC_GETFSSTAT = 426
+ SYS_FSGETPATH = 427
+ SYS_AUDIT_SESSION_SELF = 428
+ SYS_AUDIT_SESSION_JOIN = 429
+ SYS_FILEPORT_MAKEPORT = 430
+ SYS_FILEPORT_MAKEFD = 431
+ SYS_AUDIT_SESSION_PORT = 432
+ SYS_PID_SUSPEND = 433
+ SYS_PID_RESUME = 434
+ SYS_PID_HIBERNATE = 435
+ SYS_PID_SHUTDOWN_SOCKETS = 436
+ SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438
+ SYS_KAS_INFO = 439
+ SYS_MEMORYSTATUS_CONTROL = 440
+ SYS_GUARDED_OPEN_NP = 441
+ SYS_GUARDED_CLOSE_NP = 442
+ SYS_GUARDED_KQUEUE_NP = 443
+ SYS_CHANGE_FDGUARD_NP = 444
+ SYS_USRCTL = 445
+ SYS_PROC_RLIMIT_CONTROL = 446
+ SYS_CONNECTX = 447
+ SYS_DISCONNECTX = 448
+ SYS_PEELOFF = 449
+ SYS_SOCKET_DELEGATE = 450
+ SYS_TELEMETRY = 451
+ SYS_PROC_UUID_POLICY = 452
+ SYS_MEMORYSTATUS_GET_LEVEL = 453
+ SYS_SYSTEM_OVERRIDE = 454
+ SYS_VFS_PURGE = 455
+ SYS_SFI_CTL = 456
+ SYS_SFI_PIDCTL = 457
+ SYS_COALITION = 458
+ SYS_COALITION_INFO = 459
+ SYS_NECP_MATCH_POLICY = 460
+ SYS_GETATTRLISTBULK = 461
+ SYS_CLONEFILEAT = 462
+ SYS_OPENAT = 463
+ SYS_OPENAT_NOCANCEL = 464
+ SYS_RENAMEAT = 465
+ SYS_FACCESSAT = 466
+ SYS_FCHMODAT = 467
+ SYS_FCHOWNAT = 468
+ SYS_FSTATAT = 469
+ SYS_FSTATAT64 = 470
+ SYS_LINKAT = 471
+ SYS_UNLINKAT = 472
+ SYS_READLINKAT = 473
+ SYS_SYMLINKAT = 474
+ SYS_MKDIRAT = 475
+ SYS_GETATTRLISTAT = 476
+ SYS_PROC_TRACE_LOG = 477
+ SYS_BSDTHREAD_CTL = 478
+ SYS_OPENBYID_NP = 479
+ SYS_RECVMSG_X = 480
+ SYS_SENDMSG_X = 481
+ SYS_THREAD_SELFUSAGE = 482
+ SYS_CSRCTL = 483
+ SYS_GUARDED_OPEN_DPROTECTED_NP = 484
+ SYS_GUARDED_WRITE_NP = 485
+ SYS_GUARDED_PWRITE_NP = 486
+ SYS_GUARDED_WRITEV_NP = 487
+ SYS_RENAMEATX_NP = 488
+ SYS_MREMAP_ENCRYPTED = 489
+ SYS_NETAGENT_TRIGGER = 490
+ SYS_STACK_SNAPSHOT_WITH_CONFIG = 491
+ SYS_MICROSTACKSHOT = 492
+ SYS_GRAB_PGO_DATA = 493
+ SYS_PERSONA = 494
+ SYS_WORK_INTERVAL_CTL = 499
+ SYS_GETENTROPY = 500
+ SYS_NECP_OPEN = 501
+ SYS_NECP_CLIENT_ACTION = 502
+ SYS___NEXUS_OPEN = 503
+ SYS___NEXUS_REGISTER = 504
+ SYS___NEXUS_DEREGISTER = 505
+ SYS___NEXUS_CREATE = 506
+ SYS___NEXUS_DESTROY = 507
+ SYS___NEXUS_GET_OPT = 508
+ SYS___NEXUS_SET_OPT = 509
+ SYS___CHANNEL_OPEN = 510
+ SYS___CHANNEL_GET_INFO = 511
+ SYS___CHANNEL_SYNC = 512
+ SYS___CHANNEL_GET_OPT = 513
+ SYS___CHANNEL_SET_OPT = 514
+ SYS_ULOCK_WAIT = 515
+ SYS_ULOCK_WAKE = 516
+ SYS_FCLONEFILEAT = 517
+ SYS_FS_SNAPSHOT = 518
+ SYS_TERMINATE_WITH_PAYLOAD = 520
+ SYS_ABORT_WITH_PAYLOAD = 521
+ SYS_MAXSYSCALL = 522
+ SYS_INVALID = 63
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go
new file mode 100644
index 0000000..b2c9ef8
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go
@@ -0,0 +1,315 @@
+// mksysnum_dragonfly.pl
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,dragonfly
+
+package unix
+
+const (
+ // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int
+ SYS_EXIT = 1 // { void exit(int rval); }
+ SYS_FORK = 2 // { int fork(void); }
+ SYS_READ = 3 // { ssize_t read(int fd, void *buf, size_t nbyte); }
+ SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, size_t nbyte); }
+ SYS_OPEN = 5 // { int open(char *path, int flags, int mode); }
+ SYS_CLOSE = 6 // { int close(int fd); }
+ SYS_WAIT4 = 7 // { int wait4(int pid, int *status, int options, \
+ SYS_LINK = 9 // { int link(char *path, char *link); }
+ SYS_UNLINK = 10 // { int unlink(char *path); }
+ SYS_CHDIR = 12 // { int chdir(char *path); }
+ SYS_FCHDIR = 13 // { int fchdir(int fd); }
+ SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); }
+ SYS_CHMOD = 15 // { int chmod(char *path, int mode); }
+ SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); }
+ SYS_OBREAK = 17 // { int obreak(char *nsize); } break obreak_args int
+ SYS_GETFSSTAT = 18 // { int getfsstat(struct statfs *buf, long bufsize, \
+ SYS_GETPID = 20 // { pid_t getpid(void); }
+ SYS_MOUNT = 21 // { int mount(char *type, char *path, int flags, \
+ SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); }
+ SYS_SETUID = 23 // { int setuid(uid_t uid); }
+ SYS_GETUID = 24 // { uid_t getuid(void); }
+ SYS_GETEUID = 25 // { uid_t geteuid(void); }
+ SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, caddr_t addr, \
+ SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, int flags); }
+ SYS_SENDMSG = 28 // { int sendmsg(int s, caddr_t msg, int flags); }
+ SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, size_t len, \
+ SYS_ACCEPT = 30 // { int accept(int s, caddr_t name, int *anamelen); }
+ SYS_GETPEERNAME = 31 // { int getpeername(int fdes, caddr_t asa, int *alen); }
+ SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, caddr_t asa, int *alen); }
+ SYS_ACCESS = 33 // { int access(char *path, int flags); }
+ SYS_CHFLAGS = 34 // { int chflags(char *path, int flags); }
+ SYS_FCHFLAGS = 35 // { int fchflags(int fd, int flags); }
+ SYS_SYNC = 36 // { int sync(void); }
+ SYS_KILL = 37 // { int kill(int pid, int signum); }
+ SYS_GETPPID = 39 // { pid_t getppid(void); }
+ SYS_DUP = 41 // { int dup(int fd); }
+ SYS_PIPE = 42 // { int pipe(void); }
+ SYS_GETEGID = 43 // { gid_t getegid(void); }
+ SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \
+ SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, int facs, \
+ SYS_GETGID = 47 // { gid_t getgid(void); }
+ SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int namelen); }
+ SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); }
+ SYS_ACCT = 51 // { int acct(char *path); }
+ SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, stack_t *oss); }
+ SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, caddr_t data); }
+ SYS_REBOOT = 55 // { int reboot(int opt); }
+ SYS_REVOKE = 56 // { int revoke(char *path); }
+ SYS_SYMLINK = 57 // { int symlink(char *path, char *link); }
+ SYS_READLINK = 58 // { int readlink(char *path, char *buf, int count); }
+ SYS_EXECVE = 59 // { int execve(char *fname, char **argv, char **envv); }
+ SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args int
+ SYS_CHROOT = 61 // { int chroot(char *path); }
+ SYS_MSYNC = 65 // { int msync(void *addr, size_t len, int flags); }
+ SYS_VFORK = 66 // { pid_t vfork(void); }
+ SYS_SBRK = 69 // { int sbrk(int incr); }
+ SYS_SSTK = 70 // { int sstk(int incr); }
+ SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); }
+ SYS_MPROTECT = 74 // { int mprotect(void *addr, size_t len, int prot); }
+ SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, int behav); }
+ SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \
+ SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, gid_t *gidset); }
+ SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, gid_t *gidset); }
+ SYS_GETPGRP = 81 // { int getpgrp(void); }
+ SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); }
+ SYS_SETITIMER = 83 // { int setitimer(u_int which, struct itimerval *itv, \
+ SYS_SWAPON = 85 // { int swapon(char *name); }
+ SYS_GETITIMER = 86 // { int getitimer(u_int which, struct itimerval *itv); }
+ SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); }
+ SYS_DUP2 = 90 // { int dup2(int from, int to); }
+ SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); }
+ SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \
+ SYS_FSYNC = 95 // { int fsync(int fd); }
+ SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, int prio); }
+ SYS_SOCKET = 97 // { int socket(int domain, int type, int protocol); }
+ SYS_CONNECT = 98 // { int connect(int s, caddr_t name, int namelen); }
+ SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); }
+ SYS_BIND = 104 // { int bind(int s, caddr_t name, int namelen); }
+ SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \
+ SYS_LISTEN = 106 // { int listen(int s, int backlog); }
+ SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \
+ SYS_GETRUSAGE = 117 // { int getrusage(int who, struct rusage *rusage); }
+ SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \
+ SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, u_int iovcnt); }
+ SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \
+ SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \
+ SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); }
+ SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); }
+ SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); }
+ SYS_SETREGID = 127 // { int setregid(int rgid, int egid); }
+ SYS_RENAME = 128 // { int rename(char *from, char *to); }
+ SYS_FLOCK = 131 // { int flock(int fd, int how); }
+ SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); }
+ SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \
+ SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); }
+ SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, int protocol, \
+ SYS_MKDIR = 136 // { int mkdir(char *path, int mode); }
+ SYS_RMDIR = 137 // { int rmdir(char *path); }
+ SYS_UTIMES = 138 // { int utimes(char *path, struct timeval *tptr); }
+ SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \
+ SYS_SETSID = 147 // { int setsid(void); }
+ SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \
+ SYS_STATFS = 157 // { int statfs(char *path, struct statfs *buf); }
+ SYS_FSTATFS = 158 // { int fstatfs(int fd, struct statfs *buf); }
+ SYS_GETFH = 161 // { int getfh(char *fname, struct fhandle *fhp); }
+ SYS_GETDOMAINNAME = 162 // { int getdomainname(char *domainname, int len); }
+ SYS_SETDOMAINNAME = 163 // { int setdomainname(char *domainname, int len); }
+ SYS_UNAME = 164 // { int uname(struct utsname *name); }
+ SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); }
+ SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \
+ SYS_EXTPREAD = 173 // { ssize_t extpread(int fd, void *buf, \
+ SYS_EXTPWRITE = 174 // { ssize_t extpwrite(int fd, const void *buf, \
+ SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); }
+ SYS_SETGID = 181 // { int setgid(gid_t gid); }
+ SYS_SETEGID = 182 // { int setegid(gid_t egid); }
+ SYS_SETEUID = 183 // { int seteuid(uid_t euid); }
+ SYS_PATHCONF = 191 // { int pathconf(char *path, int name); }
+ SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); }
+ SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \
+ SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \
+ SYS_MMAP = 197 // { caddr_t mmap(caddr_t addr, size_t len, int prot, \
+ // SYS_NOSYS = 198; // { int nosys(void); } __syscall __syscall_args int
+ SYS_LSEEK = 199 // { off_t lseek(int fd, int pad, off_t offset, \
+ SYS_TRUNCATE = 200 // { int truncate(char *path, int pad, off_t length); }
+ SYS_FTRUNCATE = 201 // { int ftruncate(int fd, int pad, off_t length); }
+ SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, void *old, \
+ SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); }
+ SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); }
+ SYS_UNDELETE = 205 // { int undelete(char *path); }
+ SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); }
+ SYS_GETPGID = 207 // { int getpgid(pid_t pid); }
+ SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \
+ SYS___SEMCTL = 220 // { int __semctl(int semid, int semnum, int cmd, \
+ SYS_SEMGET = 221 // { int semget(key_t key, int nsems, int semflg); }
+ SYS_SEMOP = 222 // { int semop(int semid, struct sembuf *sops, \
+ SYS_MSGCTL = 224 // { int msgctl(int msqid, int cmd, \
+ SYS_MSGGET = 225 // { int msgget(key_t key, int msgflg); }
+ SYS_MSGSND = 226 // { int msgsnd(int msqid, const void *msgp, size_t msgsz, \
+ SYS_MSGRCV = 227 // { int msgrcv(int msqid, void *msgp, size_t msgsz, \
+ SYS_SHMAT = 228 // { caddr_t shmat(int shmid, const void *shmaddr, \
+ SYS_SHMCTL = 229 // { int shmctl(int shmid, int cmd, \
+ SYS_SHMDT = 230 // { int shmdt(const void *shmaddr); }
+ SYS_SHMGET = 231 // { int shmget(key_t key, size_t size, int shmflg); }
+ SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \
+ SYS_CLOCK_SETTIME = 233 // { int clock_settime(clockid_t clock_id, \
+ SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \
+ SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \
+ SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, int inherit); }
+ SYS_RFORK = 251 // { int rfork(int flags); }
+ SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, u_int nfds, \
+ SYS_ISSETUGID = 253 // { int issetugid(void); }
+ SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); }
+ SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); }
+ SYS_LUTIMES = 276 // { int lutimes(char *path, struct timeval *tptr); }
+ SYS_EXTPREADV = 289 // { ssize_t extpreadv(int fd, struct iovec *iovp, \
+ SYS_EXTPWRITEV = 290 // { ssize_t extpwritev(int fd, struct iovec *iovp,\
+ SYS_FHSTATFS = 297 // { int fhstatfs(const struct fhandle *u_fhp, struct statfs *buf); }
+ SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, int flags); }
+ SYS_MODNEXT = 300 // { int modnext(int modid); }
+ SYS_MODSTAT = 301 // { int modstat(int modid, struct module_stat* stat); }
+ SYS_MODFNEXT = 302 // { int modfnext(int modid); }
+ SYS_MODFIND = 303 // { int modfind(const char *name); }
+ SYS_KLDLOAD = 304 // { int kldload(const char *file); }
+ SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); }
+ SYS_KLDFIND = 306 // { int kldfind(const char *file); }
+ SYS_KLDNEXT = 307 // { int kldnext(int fileid); }
+ SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct kld_file_stat* stat); }
+ SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); }
+ SYS_GETSID = 310 // { int getsid(pid_t pid); }
+ SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, uid_t suid); }
+ SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, gid_t sgid); }
+ SYS_AIO_RETURN = 314 // { int aio_return(struct aiocb *aiocbp); }
+ SYS_AIO_SUSPEND = 315 // { int aio_suspend(struct aiocb * const * aiocbp, int nent, const struct timespec *timeout); }
+ SYS_AIO_CANCEL = 316 // { int aio_cancel(int fd, struct aiocb *aiocbp); }
+ SYS_AIO_ERROR = 317 // { int aio_error(struct aiocb *aiocbp); }
+ SYS_AIO_READ = 318 // { int aio_read(struct aiocb *aiocbp); }
+ SYS_AIO_WRITE = 319 // { int aio_write(struct aiocb *aiocbp); }
+ SYS_LIO_LISTIO = 320 // { int lio_listio(int mode, struct aiocb * const *acb_list, int nent, struct sigevent *sig); }
+ SYS_YIELD = 321 // { int yield(void); }
+ SYS_MLOCKALL = 324 // { int mlockall(int how); }
+ SYS_MUNLOCKALL = 325 // { int munlockall(void); }
+ SYS___GETCWD = 326 // { int __getcwd(u_char *buf, u_int buflen); }
+ SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, const struct sched_param *param); }
+ SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct sched_param *param); }
+ SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int policy, const struct sched_param *param); }
+ SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); }
+ SYS_SCHED_YIELD = 331 // { int sched_yield (void); }
+ SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); }
+ SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); }
+ SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, struct timespec *interval); }
+ SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); }
+ SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, void *data); }
+ SYS_JAIL = 338 // { int jail(struct jail *jail); }
+ SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, const sigset_t *set, \
+ SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); }
+ SYS_SIGACTION = 342 // { int sigaction(int sig, const struct sigaction *act, \
+ SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); }
+ SYS_SIGRETURN = 344 // { int sigreturn(ucontext_t *sigcntxp); }
+ SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set,\
+ SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set,\
+ SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \
+ SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \
+ SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, acl_type_t type, \
+ SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, acl_type_t type, \
+ SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \
+ SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, acl_type_t type); }
+ SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \
+ SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, acl_type_t type, \
+ SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \
+ SYS_EXTATTR_SET_FILE = 356 // { int extattr_set_file(const char *path, \
+ SYS_EXTATTR_GET_FILE = 357 // { int extattr_get_file(const char *path, \
+ SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \
+ SYS_AIO_WAITCOMPLETE = 359 // { int aio_waitcomplete(struct aiocb **aiocbp, struct timespec *timeout); }
+ SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid); }
+ SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid); }
+ SYS_KQUEUE = 362 // { int kqueue(void); }
+ SYS_KEVENT = 363 // { int kevent(int fd, \
+ SYS_KENV = 390 // { int kenv(int what, const char *name, char *value, int len); }
+ SYS_LCHFLAGS = 391 // { int lchflags(char *path, int flags); }
+ SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, int count); }
+ SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, size_t nbytes, \
+ SYS_VARSYM_SET = 450 // { int varsym_set(int level, const char *name, const char *data); }
+ SYS_VARSYM_GET = 451 // { int varsym_get(int mask, const char *wild, char *buf, int bufsize); }
+ SYS_VARSYM_LIST = 452 // { int varsym_list(int level, char *buf, int maxsize, int *marker); }
+ SYS_EXEC_SYS_REGISTER = 465 // { int exec_sys_register(void *entry); }
+ SYS_EXEC_SYS_UNREGISTER = 466 // { int exec_sys_unregister(int id); }
+ SYS_SYS_CHECKPOINT = 467 // { int sys_checkpoint(int type, int fd, pid_t pid, int retval); }
+ SYS_MOUNTCTL = 468 // { int mountctl(const char *path, int op, int fd, const void *ctl, int ctllen, void *buf, int buflen); }
+ SYS_UMTX_SLEEP = 469 // { int umtx_sleep(volatile const int *ptr, int value, int timeout); }
+ SYS_UMTX_WAKEUP = 470 // { int umtx_wakeup(volatile const int *ptr, int count); }
+ SYS_JAIL_ATTACH = 471 // { int jail_attach(int jid); }
+ SYS_SET_TLS_AREA = 472 // { int set_tls_area(int which, struct tls_info *info, size_t infosize); }
+ SYS_GET_TLS_AREA = 473 // { int get_tls_area(int which, struct tls_info *info, size_t infosize); }
+ SYS_CLOSEFROM = 474 // { int closefrom(int fd); }
+ SYS_STAT = 475 // { int stat(const char *path, struct stat *ub); }
+ SYS_FSTAT = 476 // { int fstat(int fd, struct stat *sb); }
+ SYS_LSTAT = 477 // { int lstat(const char *path, struct stat *ub); }
+ SYS_FHSTAT = 478 // { int fhstat(const struct fhandle *u_fhp, struct stat *sb); }
+ SYS_GETDIRENTRIES = 479 // { int getdirentries(int fd, char *buf, u_int count, \
+ SYS_GETDENTS = 480 // { int getdents(int fd, char *buf, size_t count); }
+ SYS_USCHED_SET = 481 // { int usched_set(pid_t pid, int cmd, void *data, \
+ SYS_EXTACCEPT = 482 // { int extaccept(int s, int flags, caddr_t name, int *anamelen); }
+ SYS_EXTCONNECT = 483 // { int extconnect(int s, int flags, caddr_t name, int namelen); }
+ SYS_MCONTROL = 485 // { int mcontrol(void *addr, size_t len, int behav, off_t value); }
+ SYS_VMSPACE_CREATE = 486 // { int vmspace_create(void *id, int type, void *data); }
+ SYS_VMSPACE_DESTROY = 487 // { int vmspace_destroy(void *id); }
+ SYS_VMSPACE_CTL = 488 // { int vmspace_ctl(void *id, int cmd, \
+ SYS_VMSPACE_MMAP = 489 // { int vmspace_mmap(void *id, void *addr, size_t len, \
+ SYS_VMSPACE_MUNMAP = 490 // { int vmspace_munmap(void *id, void *addr, \
+ SYS_VMSPACE_MCONTROL = 491 // { int vmspace_mcontrol(void *id, void *addr, \
+ SYS_VMSPACE_PREAD = 492 // { ssize_t vmspace_pread(void *id, void *buf, \
+ SYS_VMSPACE_PWRITE = 493 // { ssize_t vmspace_pwrite(void *id, const void *buf, \
+ SYS_EXTEXIT = 494 // { void extexit(int how, int status, void *addr); }
+ SYS_LWP_CREATE = 495 // { int lwp_create(struct lwp_params *params); }
+ SYS_LWP_GETTID = 496 // { lwpid_t lwp_gettid(void); }
+ SYS_LWP_KILL = 497 // { int lwp_kill(pid_t pid, lwpid_t tid, int signum); }
+ SYS_LWP_RTPRIO = 498 // { int lwp_rtprio(int function, pid_t pid, lwpid_t tid, struct rtprio *rtp); }
+ SYS_PSELECT = 499 // { int pselect(int nd, fd_set *in, fd_set *ou, \
+ SYS_STATVFS = 500 // { int statvfs(const char *path, struct statvfs *buf); }
+ SYS_FSTATVFS = 501 // { int fstatvfs(int fd, struct statvfs *buf); }
+ SYS_FHSTATVFS = 502 // { int fhstatvfs(const struct fhandle *u_fhp, struct statvfs *buf); }
+ SYS_GETVFSSTAT = 503 // { int getvfsstat(struct statfs *buf, \
+ SYS_OPENAT = 504 // { int openat(int fd, char *path, int flags, int mode); }
+ SYS_FSTATAT = 505 // { int fstatat(int fd, char *path, \
+ SYS_FCHMODAT = 506 // { int fchmodat(int fd, char *path, int mode, \
+ SYS_FCHOWNAT = 507 // { int fchownat(int fd, char *path, int uid, int gid, \
+ SYS_UNLINKAT = 508 // { int unlinkat(int fd, char *path, int flags); }
+ SYS_FACCESSAT = 509 // { int faccessat(int fd, char *path, int amode, \
+ SYS_MQ_OPEN = 510 // { mqd_t mq_open(const char * name, int oflag, \
+ SYS_MQ_CLOSE = 511 // { int mq_close(mqd_t mqdes); }
+ SYS_MQ_UNLINK = 512 // { int mq_unlink(const char *name); }
+ SYS_MQ_GETATTR = 513 // { int mq_getattr(mqd_t mqdes, \
+ SYS_MQ_SETATTR = 514 // { int mq_setattr(mqd_t mqdes, \
+ SYS_MQ_NOTIFY = 515 // { int mq_notify(mqd_t mqdes, \
+ SYS_MQ_SEND = 516 // { int mq_send(mqd_t mqdes, const char *msg_ptr, \
+ SYS_MQ_RECEIVE = 517 // { ssize_t mq_receive(mqd_t mqdes, char *msg_ptr, \
+ SYS_MQ_TIMEDSEND = 518 // { int mq_timedsend(mqd_t mqdes, \
+ SYS_MQ_TIMEDRECEIVE = 519 // { ssize_t mq_timedreceive(mqd_t mqdes, \
+ SYS_IOPRIO_SET = 520 // { int ioprio_set(int which, int who, int prio); }
+ SYS_IOPRIO_GET = 521 // { int ioprio_get(int which, int who); }
+ SYS_CHROOT_KERNEL = 522 // { int chroot_kernel(char *path); }
+ SYS_RENAMEAT = 523 // { int renameat(int oldfd, char *old, int newfd, \
+ SYS_MKDIRAT = 524 // { int mkdirat(int fd, char *path, mode_t mode); }
+ SYS_MKFIFOAT = 525 // { int mkfifoat(int fd, char *path, mode_t mode); }
+ SYS_MKNODAT = 526 // { int mknodat(int fd, char *path, mode_t mode, \
+ SYS_READLINKAT = 527 // { int readlinkat(int fd, char *path, char *buf, \
+ SYS_SYMLINKAT = 528 // { int symlinkat(char *path1, int fd, char *path2); }
+ SYS_SWAPOFF = 529 // { int swapoff(char *name); }
+ SYS_VQUOTACTL = 530 // { int vquotactl(const char *path, \
+ SYS_LINKAT = 531 // { int linkat(int fd1, char *path1, int fd2, \
+ SYS_EACCESS = 532 // { int eaccess(char *path, int flags); }
+ SYS_LPATHCONF = 533 // { int lpathconf(char *path, int name); }
+ SYS_VMM_GUEST_CTL = 534 // { int vmm_guest_ctl(int op, struct vmm_guest_options *options); }
+ SYS_VMM_GUEST_SYNC_ADDR = 535 // { int vmm_guest_sync_addr(long *dstaddr, long *srcaddr); }
+ SYS_PROCCTL = 536 // { int procctl(idtype_t idtype, id_t id, int cmd, void *data); }
+ SYS_CHFLAGSAT = 537 // { int chflagsat(int fd, const char *path, int flags, int atflags);}
+ SYS_PIPE2 = 538 // { int pipe2(int *fildes, int flags); }
+ SYS_UTIMENSAT = 539 // { int utimensat(int fd, const char *path, const struct timespec *ts, int flags); }
+ SYS_FUTIMENS = 540 // { int futimens(int fd, const struct timespec *ts); }
+ SYS_ACCEPT4 = 541 // { int accept4(int s, caddr_t name, int *anamelen, int flags); }
+ SYS_LWP_SETNAME = 542 // { int lwp_setname(lwpid_t tid, const char *name); }
+ SYS_PPOLL = 543 // { int ppoll(struct pollfd *fds, u_int nfds, \
+ SYS_LWP_SETAFFINITY = 544 // { int lwp_setaffinity(pid_t pid, lwpid_t tid, const cpumask_t *mask); }
+ SYS_LWP_GETAFFINITY = 545 // { int lwp_getaffinity(pid_t pid, lwpid_t tid, cpumask_t *mask); }
+ SYS_LWP_CREATE2 = 546 // { int lwp_create2(struct lwp_params *params, const cpumask_t *mask); }
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go b/vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go
new file mode 100644
index 0000000..b64a812
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go
@@ -0,0 +1,353 @@
+// mksysnum_freebsd.pl
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build 386,freebsd
+
+package unix
+
+const (
+ // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int
+ SYS_EXIT = 1 // { void sys_exit(int rval); } exit \
+ SYS_FORK = 2 // { int fork(void); }
+ SYS_READ = 3 // { ssize_t read(int fd, void *buf, \
+ SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, \
+ SYS_OPEN = 5 // { int open(char *path, int flags, int mode); }
+ SYS_CLOSE = 6 // { int close(int fd); }
+ SYS_WAIT4 = 7 // { int wait4(int pid, int *status, \
+ SYS_LINK = 9 // { int link(char *path, char *link); }
+ SYS_UNLINK = 10 // { int unlink(char *path); }
+ SYS_CHDIR = 12 // { int chdir(char *path); }
+ SYS_FCHDIR = 13 // { int fchdir(int fd); }
+ SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); }
+ SYS_CHMOD = 15 // { int chmod(char *path, int mode); }
+ SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); }
+ SYS_OBREAK = 17 // { int obreak(char *nsize); } break \
+ SYS_GETPID = 20 // { pid_t getpid(void); }
+ SYS_MOUNT = 21 // { int mount(char *type, char *path, \
+ SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); }
+ SYS_SETUID = 23 // { int setuid(uid_t uid); }
+ SYS_GETUID = 24 // { uid_t getuid(void); }
+ SYS_GETEUID = 25 // { uid_t geteuid(void); }
+ SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, \
+ SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, \
+ SYS_SENDMSG = 28 // { int sendmsg(int s, struct msghdr *msg, \
+ SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, \
+ SYS_ACCEPT = 30 // { int accept(int s, \
+ SYS_GETPEERNAME = 31 // { int getpeername(int fdes, \
+ SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, \
+ SYS_ACCESS = 33 // { int access(char *path, int amode); }
+ SYS_CHFLAGS = 34 // { int chflags(const char *path, u_long flags); }
+ SYS_FCHFLAGS = 35 // { int fchflags(int fd, u_long flags); }
+ SYS_SYNC = 36 // { int sync(void); }
+ SYS_KILL = 37 // { int kill(int pid, int signum); }
+ SYS_GETPPID = 39 // { pid_t getppid(void); }
+ SYS_DUP = 41 // { int dup(u_int fd); }
+ SYS_PIPE = 42 // { int pipe(void); }
+ SYS_GETEGID = 43 // { gid_t getegid(void); }
+ SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \
+ SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, \
+ SYS_GETGID = 47 // { gid_t getgid(void); }
+ SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int \
+ SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); }
+ SYS_ACCT = 51 // { int acct(char *path); }
+ SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, \
+ SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, \
+ SYS_REBOOT = 55 // { int reboot(int opt); }
+ SYS_REVOKE = 56 // { int revoke(char *path); }
+ SYS_SYMLINK = 57 // { int symlink(char *path, char *link); }
+ SYS_READLINK = 58 // { ssize_t readlink(char *path, char *buf, \
+ SYS_EXECVE = 59 // { int execve(char *fname, char **argv, \
+ SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args \
+ SYS_CHROOT = 61 // { int chroot(char *path); }
+ SYS_MSYNC = 65 // { int msync(void *addr, size_t len, \
+ SYS_VFORK = 66 // { int vfork(void); }
+ SYS_SBRK = 69 // { int sbrk(int incr); }
+ SYS_SSTK = 70 // { int sstk(int incr); }
+ SYS_OVADVISE = 72 // { int ovadvise(int anom); } vadvise \
+ SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); }
+ SYS_MPROTECT = 74 // { int mprotect(const void *addr, size_t len, \
+ SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, \
+ SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \
+ SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, \
+ SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, \
+ SYS_GETPGRP = 81 // { int getpgrp(void); }
+ SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); }
+ SYS_SETITIMER = 83 // { int setitimer(u_int which, struct \
+ SYS_SWAPON = 85 // { int swapon(char *name); }
+ SYS_GETITIMER = 86 // { int getitimer(u_int which, \
+ SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); }
+ SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); }
+ SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); }
+ SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \
+ SYS_FSYNC = 95 // { int fsync(int fd); }
+ SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, \
+ SYS_SOCKET = 97 // { int socket(int domain, int type, \
+ SYS_CONNECT = 98 // { int connect(int s, caddr_t name, \
+ SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); }
+ SYS_BIND = 104 // { int bind(int s, caddr_t name, \
+ SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \
+ SYS_LISTEN = 106 // { int listen(int s, int backlog); }
+ SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \
+ SYS_GETRUSAGE = 117 // { int getrusage(int who, \
+ SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \
+ SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, \
+ SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \
+ SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \
+ SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); }
+ SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); }
+ SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); }
+ SYS_SETREGID = 127 // { int setregid(int rgid, int egid); }
+ SYS_RENAME = 128 // { int rename(char *from, char *to); }
+ SYS_FLOCK = 131 // { int flock(int fd, int how); }
+ SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); }
+ SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \
+ SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); }
+ SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, \
+ SYS_MKDIR = 136 // { int mkdir(char *path, int mode); }
+ SYS_RMDIR = 137 // { int rmdir(char *path); }
+ SYS_UTIMES = 138 // { int utimes(char *path, \
+ SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \
+ SYS_SETSID = 147 // { int setsid(void); }
+ SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \
+ SYS_LGETFH = 160 // { int lgetfh(char *fname, \
+ SYS_GETFH = 161 // { int getfh(char *fname, \
+ SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); }
+ SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \
+ SYS_FREEBSD6_PREAD = 173 // { ssize_t freebsd6_pread(int fd, void *buf, \
+ SYS_FREEBSD6_PWRITE = 174 // { ssize_t freebsd6_pwrite(int fd, \
+ SYS_SETFIB = 175 // { int setfib(int fibnum); }
+ SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); }
+ SYS_SETGID = 181 // { int setgid(gid_t gid); }
+ SYS_SETEGID = 182 // { int setegid(gid_t egid); }
+ SYS_SETEUID = 183 // { int seteuid(uid_t euid); }
+ SYS_STAT = 188 // { int stat(char *path, struct stat *ub); }
+ SYS_FSTAT = 189 // { int fstat(int fd, struct stat *sb); }
+ SYS_LSTAT = 190 // { int lstat(char *path, struct stat *ub); }
+ SYS_PATHCONF = 191 // { int pathconf(char *path, int name); }
+ SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); }
+ SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \
+ SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \
+ SYS_GETDIRENTRIES = 196 // { int getdirentries(int fd, char *buf, \
+ SYS_FREEBSD6_MMAP = 197 // { caddr_t freebsd6_mmap(caddr_t addr, \
+ SYS_FREEBSD6_LSEEK = 199 // { off_t freebsd6_lseek(int fd, int pad, \
+ SYS_FREEBSD6_TRUNCATE = 200 // { int freebsd6_truncate(char *path, int pad, \
+ SYS_FREEBSD6_FTRUNCATE = 201 // { int freebsd6_ftruncate(int fd, int pad, \
+ SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, \
+ SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); }
+ SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); }
+ SYS_UNDELETE = 205 // { int undelete(char *path); }
+ SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); }
+ SYS_GETPGID = 207 // { int getpgid(pid_t pid); }
+ SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \
+ SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \
+ SYS_CLOCK_SETTIME = 233 // { int clock_settime( \
+ SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \
+ SYS_KTIMER_CREATE = 235 // { int ktimer_create(clockid_t clock_id, \
+ SYS_KTIMER_DELETE = 236 // { int ktimer_delete(int timerid); }
+ SYS_KTIMER_SETTIME = 237 // { int ktimer_settime(int timerid, int flags, \
+ SYS_KTIMER_GETTIME = 238 // { int ktimer_gettime(int timerid, struct \
+ SYS_KTIMER_GETOVERRUN = 239 // { int ktimer_getoverrun(int timerid); }
+ SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \
+ SYS_FFCLOCK_GETCOUNTER = 241 // { int ffclock_getcounter(ffcounter *ffcount); }
+ SYS_FFCLOCK_SETESTIMATE = 242 // { int ffclock_setestimate( \
+ SYS_FFCLOCK_GETESTIMATE = 243 // { int ffclock_getestimate( \
+ SYS_CLOCK_GETCPUCLOCKID2 = 247 // { int clock_getcpuclockid2(id_t id,\
+ SYS_NTP_GETTIME = 248 // { int ntp_gettime(struct ntptimeval *ntvp); }
+ SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, \
+ SYS_RFORK = 251 // { int rfork(int flags); }
+ SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, \
+ SYS_ISSETUGID = 253 // { int issetugid(void); }
+ SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); }
+ SYS_GETDENTS = 272 // { int getdents(int fd, char *buf, \
+ SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); }
+ SYS_LUTIMES = 276 // { int lutimes(char *path, \
+ SYS_NSTAT = 278 // { int nstat(char *path, struct nstat *ub); }
+ SYS_NFSTAT = 279 // { int nfstat(int fd, struct nstat *sb); }
+ SYS_NLSTAT = 280 // { int nlstat(char *path, struct nstat *ub); }
+ SYS_PREADV = 289 // { ssize_t preadv(int fd, struct iovec *iovp, \
+ SYS_PWRITEV = 290 // { ssize_t pwritev(int fd, struct iovec *iovp, \
+ SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, \
+ SYS_FHSTAT = 299 // { int fhstat(const struct fhandle *u_fhp, \
+ SYS_MODNEXT = 300 // { int modnext(int modid); }
+ SYS_MODSTAT = 301 // { int modstat(int modid, \
+ SYS_MODFNEXT = 302 // { int modfnext(int modid); }
+ SYS_MODFIND = 303 // { int modfind(const char *name); }
+ SYS_KLDLOAD = 304 // { int kldload(const char *file); }
+ SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); }
+ SYS_KLDFIND = 306 // { int kldfind(const char *file); }
+ SYS_KLDNEXT = 307 // { int kldnext(int fileid); }
+ SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct \
+ SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); }
+ SYS_GETSID = 310 // { int getsid(pid_t pid); }
+ SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, \
+ SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, \
+ SYS_YIELD = 321 // { int yield(void); }
+ SYS_MLOCKALL = 324 // { int mlockall(int how); }
+ SYS_MUNLOCKALL = 325 // { int munlockall(void); }
+ SYS___GETCWD = 326 // { int __getcwd(char *buf, u_int buflen); }
+ SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, \
+ SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct \
+ SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int \
+ SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); }
+ SYS_SCHED_YIELD = 331 // { int sched_yield (void); }
+ SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); }
+ SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); }
+ SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, \
+ SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); }
+ SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, \
+ SYS_JAIL = 338 // { int jail(struct jail *jail); }
+ SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, \
+ SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); }
+ SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); }
+ SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set, \
+ SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set, \
+ SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \
+ SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \
+ SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, \
+ SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, \
+ SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \
+ SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, \
+ SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \
+ SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, \
+ SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \
+ SYS_EXTATTR_SET_FILE = 356 // { ssize_t extattr_set_file( \
+ SYS_EXTATTR_GET_FILE = 357 // { ssize_t extattr_get_file( \
+ SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \
+ SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, \
+ SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, \
+ SYS_KQUEUE = 362 // { int kqueue(void); }
+ SYS_KEVENT = 363 // { int kevent(int fd, \
+ SYS_EXTATTR_SET_FD = 371 // { ssize_t extattr_set_fd(int fd, \
+ SYS_EXTATTR_GET_FD = 372 // { ssize_t extattr_get_fd(int fd, \
+ SYS_EXTATTR_DELETE_FD = 373 // { int extattr_delete_fd(int fd, \
+ SYS___SETUGID = 374 // { int __setugid(int flag); }
+ SYS_EACCESS = 376 // { int eaccess(char *path, int amode); }
+ SYS_NMOUNT = 378 // { int nmount(struct iovec *iovp, \
+ SYS___MAC_GET_PROC = 384 // { int __mac_get_proc(struct mac *mac_p); }
+ SYS___MAC_SET_PROC = 385 // { int __mac_set_proc(struct mac *mac_p); }
+ SYS___MAC_GET_FD = 386 // { int __mac_get_fd(int fd, \
+ SYS___MAC_GET_FILE = 387 // { int __mac_get_file(const char *path_p, \
+ SYS___MAC_SET_FD = 388 // { int __mac_set_fd(int fd, \
+ SYS___MAC_SET_FILE = 389 // { int __mac_set_file(const char *path_p, \
+ SYS_KENV = 390 // { int kenv(int what, const char *name, \
+ SYS_LCHFLAGS = 391 // { int lchflags(const char *path, \
+ SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, \
+ SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, \
+ SYS_MAC_SYSCALL = 394 // { int mac_syscall(const char *policy, \
+ SYS_GETFSSTAT = 395 // { int getfsstat(struct statfs *buf, \
+ SYS_STATFS = 396 // { int statfs(char *path, \
+ SYS_FSTATFS = 397 // { int fstatfs(int fd, struct statfs *buf); }
+ SYS_FHSTATFS = 398 // { int fhstatfs(const struct fhandle *u_fhp, \
+ SYS___MAC_GET_PID = 409 // { int __mac_get_pid(pid_t pid, \
+ SYS___MAC_GET_LINK = 410 // { int __mac_get_link(const char *path_p, \
+ SYS___MAC_SET_LINK = 411 // { int __mac_set_link(const char *path_p, \
+ SYS_EXTATTR_SET_LINK = 412 // { ssize_t extattr_set_link( \
+ SYS_EXTATTR_GET_LINK = 413 // { ssize_t extattr_get_link( \
+ SYS_EXTATTR_DELETE_LINK = 414 // { int extattr_delete_link( \
+ SYS___MAC_EXECVE = 415 // { int __mac_execve(char *fname, char **argv, \
+ SYS_SIGACTION = 416 // { int sigaction(int sig, \
+ SYS_SIGRETURN = 417 // { int sigreturn( \
+ SYS_GETCONTEXT = 421 // { int getcontext(struct __ucontext *ucp); }
+ SYS_SETCONTEXT = 422 // { int setcontext( \
+ SYS_SWAPCONTEXT = 423 // { int swapcontext(struct __ucontext *oucp, \
+ SYS_SWAPOFF = 424 // { int swapoff(const char *name); }
+ SYS___ACL_GET_LINK = 425 // { int __acl_get_link(const char *path, \
+ SYS___ACL_SET_LINK = 426 // { int __acl_set_link(const char *path, \
+ SYS___ACL_DELETE_LINK = 427 // { int __acl_delete_link(const char *path, \
+ SYS___ACL_ACLCHECK_LINK = 428 // { int __acl_aclcheck_link(const char *path, \
+ SYS_SIGWAIT = 429 // { int sigwait(const sigset_t *set, \
+ SYS_THR_CREATE = 430 // { int thr_create(ucontext_t *ctx, long *id, \
+ SYS_THR_EXIT = 431 // { void thr_exit(long *state); }
+ SYS_THR_SELF = 432 // { int thr_self(long *id); }
+ SYS_THR_KILL = 433 // { int thr_kill(long id, int sig); }
+ SYS__UMTX_LOCK = 434 // { int _umtx_lock(struct umtx *umtx); }
+ SYS__UMTX_UNLOCK = 435 // { int _umtx_unlock(struct umtx *umtx); }
+ SYS_JAIL_ATTACH = 436 // { int jail_attach(int jid); }
+ SYS_EXTATTR_LIST_FD = 437 // { ssize_t extattr_list_fd(int fd, \
+ SYS_EXTATTR_LIST_FILE = 438 // { ssize_t extattr_list_file( \
+ SYS_EXTATTR_LIST_LINK = 439 // { ssize_t extattr_list_link( \
+ SYS_THR_SUSPEND = 442 // { int thr_suspend( \
+ SYS_THR_WAKE = 443 // { int thr_wake(long id); }
+ SYS_KLDUNLOADF = 444 // { int kldunloadf(int fileid, int flags); }
+ SYS_AUDIT = 445 // { int audit(const void *record, \
+ SYS_AUDITON = 446 // { int auditon(int cmd, void *data, \
+ SYS_GETAUID = 447 // { int getauid(uid_t *auid); }
+ SYS_SETAUID = 448 // { int setauid(uid_t *auid); }
+ SYS_GETAUDIT = 449 // { int getaudit(struct auditinfo *auditinfo); }
+ SYS_SETAUDIT = 450 // { int setaudit(struct auditinfo *auditinfo); }
+ SYS_GETAUDIT_ADDR = 451 // { int getaudit_addr( \
+ SYS_SETAUDIT_ADDR = 452 // { int setaudit_addr( \
+ SYS_AUDITCTL = 453 // { int auditctl(char *path); }
+ SYS__UMTX_OP = 454 // { int _umtx_op(void *obj, int op, \
+ SYS_THR_NEW = 455 // { int thr_new(struct thr_param *param, \
+ SYS_SIGQUEUE = 456 // { int sigqueue(pid_t pid, int signum, void *value); }
+ SYS_ABORT2 = 463 // { int abort2(const char *why, int nargs, void **args); }
+ SYS_THR_SET_NAME = 464 // { int thr_set_name(long id, const char *name); }
+ SYS_RTPRIO_THREAD = 466 // { int rtprio_thread(int function, \
+ SYS_PREAD = 475 // { ssize_t pread(int fd, void *buf, \
+ SYS_PWRITE = 476 // { ssize_t pwrite(int fd, const void *buf, \
+ SYS_MMAP = 477 // { caddr_t mmap(caddr_t addr, size_t len, \
+ SYS_LSEEK = 478 // { off_t lseek(int fd, off_t offset, \
+ SYS_TRUNCATE = 479 // { int truncate(char *path, off_t length); }
+ SYS_FTRUNCATE = 480 // { int ftruncate(int fd, off_t length); }
+ SYS_THR_KILL2 = 481 // { int thr_kill2(pid_t pid, long id, int sig); }
+ SYS_SHM_OPEN = 482 // { int shm_open(const char *path, int flags, \
+ SYS_SHM_UNLINK = 483 // { int shm_unlink(const char *path); }
+ SYS_CPUSET = 484 // { int cpuset(cpusetid_t *setid); }
+ SYS_CPUSET_SETID = 485 // { int cpuset_setid(cpuwhich_t which, id_t id, \
+ SYS_CPUSET_GETID = 486 // { int cpuset_getid(cpulevel_t level, \
+ SYS_CPUSET_GETAFFINITY = 487 // { int cpuset_getaffinity(cpulevel_t level, \
+ SYS_CPUSET_SETAFFINITY = 488 // { int cpuset_setaffinity(cpulevel_t level, \
+ SYS_FACCESSAT = 489 // { int faccessat(int fd, char *path, int amode, \
+ SYS_FCHMODAT = 490 // { int fchmodat(int fd, char *path, mode_t mode, \
+ SYS_FCHOWNAT = 491 // { int fchownat(int fd, char *path, uid_t uid, \
+ SYS_FEXECVE = 492 // { int fexecve(int fd, char **argv, \
+ SYS_FSTATAT = 493 // { int fstatat(int fd, char *path, \
+ SYS_FUTIMESAT = 494 // { int futimesat(int fd, char *path, \
+ SYS_LINKAT = 495 // { int linkat(int fd1, char *path1, int fd2, \
+ SYS_MKDIRAT = 496 // { int mkdirat(int fd, char *path, mode_t mode); }
+ SYS_MKFIFOAT = 497 // { int mkfifoat(int fd, char *path, mode_t mode); }
+ SYS_MKNODAT = 498 // { int mknodat(int fd, char *path, mode_t mode, \
+ SYS_OPENAT = 499 // { int openat(int fd, char *path, int flag, \
+ SYS_READLINKAT = 500 // { int readlinkat(int fd, char *path, char *buf, \
+ SYS_RENAMEAT = 501 // { int renameat(int oldfd, char *old, int newfd, \
+ SYS_SYMLINKAT = 502 // { int symlinkat(char *path1, int fd, \
+ SYS_UNLINKAT = 503 // { int unlinkat(int fd, char *path, int flag); }
+ SYS_POSIX_OPENPT = 504 // { int posix_openpt(int flags); }
+ SYS_JAIL_GET = 506 // { int jail_get(struct iovec *iovp, \
+ SYS_JAIL_SET = 507 // { int jail_set(struct iovec *iovp, \
+ SYS_JAIL_REMOVE = 508 // { int jail_remove(int jid); }
+ SYS_CLOSEFROM = 509 // { int closefrom(int lowfd); }
+ SYS_LPATHCONF = 513 // { int lpathconf(char *path, int name); }
+ SYS___CAP_RIGHTS_GET = 515 // { int __cap_rights_get(int version, \
+ SYS_CAP_ENTER = 516 // { int cap_enter(void); }
+ SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); }
+ SYS_PDFORK = 518 // { int pdfork(int *fdp, int flags); }
+ SYS_PDKILL = 519 // { int pdkill(int fd, int signum); }
+ SYS_PDGETPID = 520 // { int pdgetpid(int fd, pid_t *pidp); }
+ SYS_PSELECT = 522 // { int pselect(int nd, fd_set *in, \
+ SYS_GETLOGINCLASS = 523 // { int getloginclass(char *namebuf, \
+ SYS_SETLOGINCLASS = 524 // { int setloginclass(const char *namebuf); }
+ SYS_RCTL_GET_RACCT = 525 // { int rctl_get_racct(const void *inbufp, \
+ SYS_RCTL_GET_RULES = 526 // { int rctl_get_rules(const void *inbufp, \
+ SYS_RCTL_GET_LIMITS = 527 // { int rctl_get_limits(const void *inbufp, \
+ SYS_RCTL_ADD_RULE = 528 // { int rctl_add_rule(const void *inbufp, \
+ SYS_RCTL_REMOVE_RULE = 529 // { int rctl_remove_rule(const void *inbufp, \
+ SYS_POSIX_FALLOCATE = 530 // { int posix_fallocate(int fd, \
+ SYS_POSIX_FADVISE = 531 // { int posix_fadvise(int fd, off_t offset, \
+ SYS_WAIT6 = 532 // { int wait6(idtype_t idtype, id_t id, \
+ SYS_CAP_RIGHTS_LIMIT = 533 // { int cap_rights_limit(int fd, \
+ SYS_CAP_IOCTLS_LIMIT = 534 // { int cap_ioctls_limit(int fd, \
+ SYS_CAP_IOCTLS_GET = 535 // { ssize_t cap_ioctls_get(int fd, \
+ SYS_CAP_FCNTLS_LIMIT = 536 // { int cap_fcntls_limit(int fd, \
+ SYS_CAP_FCNTLS_GET = 537 // { int cap_fcntls_get(int fd, \
+ SYS_BINDAT = 538 // { int bindat(int fd, int s, caddr_t name, \
+ SYS_CONNECTAT = 539 // { int connectat(int fd, int s, caddr_t name, \
+ SYS_CHFLAGSAT = 540 // { int chflagsat(int fd, const char *path, \
+ SYS_ACCEPT4 = 541 // { int accept4(int s, \
+ SYS_PIPE2 = 542 // { int pipe2(int *fildes, int flags); }
+ SYS_PROCCTL = 544 // { int procctl(idtype_t idtype, id_t id, \
+ SYS_PPOLL = 545 // { int ppoll(struct pollfd *fds, u_int nfds, \
+ SYS_FUTIMENS = 546 // { int futimens(int fd, \
+ SYS_UTIMENSAT = 547 // { int utimensat(int fd, \
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go
new file mode 100644
index 0000000..81722ac
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go
@@ -0,0 +1,353 @@
+// mksysnum_freebsd.pl
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,freebsd
+
+package unix
+
+const (
+ // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int
+ SYS_EXIT = 1 // { void sys_exit(int rval); } exit \
+ SYS_FORK = 2 // { int fork(void); }
+ SYS_READ = 3 // { ssize_t read(int fd, void *buf, \
+ SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, \
+ SYS_OPEN = 5 // { int open(char *path, int flags, int mode); }
+ SYS_CLOSE = 6 // { int close(int fd); }
+ SYS_WAIT4 = 7 // { int wait4(int pid, int *status, \
+ SYS_LINK = 9 // { int link(char *path, char *link); }
+ SYS_UNLINK = 10 // { int unlink(char *path); }
+ SYS_CHDIR = 12 // { int chdir(char *path); }
+ SYS_FCHDIR = 13 // { int fchdir(int fd); }
+ SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); }
+ SYS_CHMOD = 15 // { int chmod(char *path, int mode); }
+ SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); }
+ SYS_OBREAK = 17 // { int obreak(char *nsize); } break \
+ SYS_GETPID = 20 // { pid_t getpid(void); }
+ SYS_MOUNT = 21 // { int mount(char *type, char *path, \
+ SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); }
+ SYS_SETUID = 23 // { int setuid(uid_t uid); }
+ SYS_GETUID = 24 // { uid_t getuid(void); }
+ SYS_GETEUID = 25 // { uid_t geteuid(void); }
+ SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, \
+ SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, \
+ SYS_SENDMSG = 28 // { int sendmsg(int s, struct msghdr *msg, \
+ SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, \
+ SYS_ACCEPT = 30 // { int accept(int s, \
+ SYS_GETPEERNAME = 31 // { int getpeername(int fdes, \
+ SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, \
+ SYS_ACCESS = 33 // { int access(char *path, int amode); }
+ SYS_CHFLAGS = 34 // { int chflags(const char *path, u_long flags); }
+ SYS_FCHFLAGS = 35 // { int fchflags(int fd, u_long flags); }
+ SYS_SYNC = 36 // { int sync(void); }
+ SYS_KILL = 37 // { int kill(int pid, int signum); }
+ SYS_GETPPID = 39 // { pid_t getppid(void); }
+ SYS_DUP = 41 // { int dup(u_int fd); }
+ SYS_PIPE = 42 // { int pipe(void); }
+ SYS_GETEGID = 43 // { gid_t getegid(void); }
+ SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \
+ SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, \
+ SYS_GETGID = 47 // { gid_t getgid(void); }
+ SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int \
+ SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); }
+ SYS_ACCT = 51 // { int acct(char *path); }
+ SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, \
+ SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, \
+ SYS_REBOOT = 55 // { int reboot(int opt); }
+ SYS_REVOKE = 56 // { int revoke(char *path); }
+ SYS_SYMLINK = 57 // { int symlink(char *path, char *link); }
+ SYS_READLINK = 58 // { ssize_t readlink(char *path, char *buf, \
+ SYS_EXECVE = 59 // { int execve(char *fname, char **argv, \
+ SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args \
+ SYS_CHROOT = 61 // { int chroot(char *path); }
+ SYS_MSYNC = 65 // { int msync(void *addr, size_t len, \
+ SYS_VFORK = 66 // { int vfork(void); }
+ SYS_SBRK = 69 // { int sbrk(int incr); }
+ SYS_SSTK = 70 // { int sstk(int incr); }
+ SYS_OVADVISE = 72 // { int ovadvise(int anom); } vadvise \
+ SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); }
+ SYS_MPROTECT = 74 // { int mprotect(const void *addr, size_t len, \
+ SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, \
+ SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \
+ SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, \
+ SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, \
+ SYS_GETPGRP = 81 // { int getpgrp(void); }
+ SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); }
+ SYS_SETITIMER = 83 // { int setitimer(u_int which, struct \
+ SYS_SWAPON = 85 // { int swapon(char *name); }
+ SYS_GETITIMER = 86 // { int getitimer(u_int which, \
+ SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); }
+ SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); }
+ SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); }
+ SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \
+ SYS_FSYNC = 95 // { int fsync(int fd); }
+ SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, \
+ SYS_SOCKET = 97 // { int socket(int domain, int type, \
+ SYS_CONNECT = 98 // { int connect(int s, caddr_t name, \
+ SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); }
+ SYS_BIND = 104 // { int bind(int s, caddr_t name, \
+ SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \
+ SYS_LISTEN = 106 // { int listen(int s, int backlog); }
+ SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \
+ SYS_GETRUSAGE = 117 // { int getrusage(int who, \
+ SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \
+ SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, \
+ SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \
+ SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \
+ SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); }
+ SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); }
+ SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); }
+ SYS_SETREGID = 127 // { int setregid(int rgid, int egid); }
+ SYS_RENAME = 128 // { int rename(char *from, char *to); }
+ SYS_FLOCK = 131 // { int flock(int fd, int how); }
+ SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); }
+ SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \
+ SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); }
+ SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, \
+ SYS_MKDIR = 136 // { int mkdir(char *path, int mode); }
+ SYS_RMDIR = 137 // { int rmdir(char *path); }
+ SYS_UTIMES = 138 // { int utimes(char *path, \
+ SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \
+ SYS_SETSID = 147 // { int setsid(void); }
+ SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \
+ SYS_LGETFH = 160 // { int lgetfh(char *fname, \
+ SYS_GETFH = 161 // { int getfh(char *fname, \
+ SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); }
+ SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \
+ SYS_FREEBSD6_PREAD = 173 // { ssize_t freebsd6_pread(int fd, void *buf, \
+ SYS_FREEBSD6_PWRITE = 174 // { ssize_t freebsd6_pwrite(int fd, \
+ SYS_SETFIB = 175 // { int setfib(int fibnum); }
+ SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); }
+ SYS_SETGID = 181 // { int setgid(gid_t gid); }
+ SYS_SETEGID = 182 // { int setegid(gid_t egid); }
+ SYS_SETEUID = 183 // { int seteuid(uid_t euid); }
+ SYS_STAT = 188 // { int stat(char *path, struct stat *ub); }
+ SYS_FSTAT = 189 // { int fstat(int fd, struct stat *sb); }
+ SYS_LSTAT = 190 // { int lstat(char *path, struct stat *ub); }
+ SYS_PATHCONF = 191 // { int pathconf(char *path, int name); }
+ SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); }
+ SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \
+ SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \
+ SYS_GETDIRENTRIES = 196 // { int getdirentries(int fd, char *buf, \
+ SYS_FREEBSD6_MMAP = 197 // { caddr_t freebsd6_mmap(caddr_t addr, \
+ SYS_FREEBSD6_LSEEK = 199 // { off_t freebsd6_lseek(int fd, int pad, \
+ SYS_FREEBSD6_TRUNCATE = 200 // { int freebsd6_truncate(char *path, int pad, \
+ SYS_FREEBSD6_FTRUNCATE = 201 // { int freebsd6_ftruncate(int fd, int pad, \
+ SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, \
+ SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); }
+ SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); }
+ SYS_UNDELETE = 205 // { int undelete(char *path); }
+ SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); }
+ SYS_GETPGID = 207 // { int getpgid(pid_t pid); }
+ SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \
+ SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \
+ SYS_CLOCK_SETTIME = 233 // { int clock_settime( \
+ SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \
+ SYS_KTIMER_CREATE = 235 // { int ktimer_create(clockid_t clock_id, \
+ SYS_KTIMER_DELETE = 236 // { int ktimer_delete(int timerid); }
+ SYS_KTIMER_SETTIME = 237 // { int ktimer_settime(int timerid, int flags, \
+ SYS_KTIMER_GETTIME = 238 // { int ktimer_gettime(int timerid, struct \
+ SYS_KTIMER_GETOVERRUN = 239 // { int ktimer_getoverrun(int timerid); }
+ SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \
+ SYS_FFCLOCK_GETCOUNTER = 241 // { int ffclock_getcounter(ffcounter *ffcount); }
+ SYS_FFCLOCK_SETESTIMATE = 242 // { int ffclock_setestimate( \
+ SYS_FFCLOCK_GETESTIMATE = 243 // { int ffclock_getestimate( \
+ SYS_CLOCK_GETCPUCLOCKID2 = 247 // { int clock_getcpuclockid2(id_t id,\
+ SYS_NTP_GETTIME = 248 // { int ntp_gettime(struct ntptimeval *ntvp); }
+ SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, \
+ SYS_RFORK = 251 // { int rfork(int flags); }
+ SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, \
+ SYS_ISSETUGID = 253 // { int issetugid(void); }
+ SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); }
+ SYS_GETDENTS = 272 // { int getdents(int fd, char *buf, \
+ SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); }
+ SYS_LUTIMES = 276 // { int lutimes(char *path, \
+ SYS_NSTAT = 278 // { int nstat(char *path, struct nstat *ub); }
+ SYS_NFSTAT = 279 // { int nfstat(int fd, struct nstat *sb); }
+ SYS_NLSTAT = 280 // { int nlstat(char *path, struct nstat *ub); }
+ SYS_PREADV = 289 // { ssize_t preadv(int fd, struct iovec *iovp, \
+ SYS_PWRITEV = 290 // { ssize_t pwritev(int fd, struct iovec *iovp, \
+ SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, \
+ SYS_FHSTAT = 299 // { int fhstat(const struct fhandle *u_fhp, \
+ SYS_MODNEXT = 300 // { int modnext(int modid); }
+ SYS_MODSTAT = 301 // { int modstat(int modid, \
+ SYS_MODFNEXT = 302 // { int modfnext(int modid); }
+ SYS_MODFIND = 303 // { int modfind(const char *name); }
+ SYS_KLDLOAD = 304 // { int kldload(const char *file); }
+ SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); }
+ SYS_KLDFIND = 306 // { int kldfind(const char *file); }
+ SYS_KLDNEXT = 307 // { int kldnext(int fileid); }
+ SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct \
+ SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); }
+ SYS_GETSID = 310 // { int getsid(pid_t pid); }
+ SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, \
+ SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, \
+ SYS_YIELD = 321 // { int yield(void); }
+ SYS_MLOCKALL = 324 // { int mlockall(int how); }
+ SYS_MUNLOCKALL = 325 // { int munlockall(void); }
+ SYS___GETCWD = 326 // { int __getcwd(char *buf, u_int buflen); }
+ SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, \
+ SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct \
+ SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int \
+ SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); }
+ SYS_SCHED_YIELD = 331 // { int sched_yield (void); }
+ SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); }
+ SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); }
+ SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, \
+ SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); }
+ SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, \
+ SYS_JAIL = 338 // { int jail(struct jail *jail); }
+ SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, \
+ SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); }
+ SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); }
+ SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set, \
+ SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set, \
+ SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \
+ SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \
+ SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, \
+ SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, \
+ SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \
+ SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, \
+ SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \
+ SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, \
+ SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \
+ SYS_EXTATTR_SET_FILE = 356 // { ssize_t extattr_set_file( \
+ SYS_EXTATTR_GET_FILE = 357 // { ssize_t extattr_get_file( \
+ SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \
+ SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, \
+ SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, \
+ SYS_KQUEUE = 362 // { int kqueue(void); }
+ SYS_KEVENT = 363 // { int kevent(int fd, \
+ SYS_EXTATTR_SET_FD = 371 // { ssize_t extattr_set_fd(int fd, \
+ SYS_EXTATTR_GET_FD = 372 // { ssize_t extattr_get_fd(int fd, \
+ SYS_EXTATTR_DELETE_FD = 373 // { int extattr_delete_fd(int fd, \
+ SYS___SETUGID = 374 // { int __setugid(int flag); }
+ SYS_EACCESS = 376 // { int eaccess(char *path, int amode); }
+ SYS_NMOUNT = 378 // { int nmount(struct iovec *iovp, \
+ SYS___MAC_GET_PROC = 384 // { int __mac_get_proc(struct mac *mac_p); }
+ SYS___MAC_SET_PROC = 385 // { int __mac_set_proc(struct mac *mac_p); }
+ SYS___MAC_GET_FD = 386 // { int __mac_get_fd(int fd, \
+ SYS___MAC_GET_FILE = 387 // { int __mac_get_file(const char *path_p, \
+ SYS___MAC_SET_FD = 388 // { int __mac_set_fd(int fd, \
+ SYS___MAC_SET_FILE = 389 // { int __mac_set_file(const char *path_p, \
+ SYS_KENV = 390 // { int kenv(int what, const char *name, \
+ SYS_LCHFLAGS = 391 // { int lchflags(const char *path, \
+ SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, \
+ SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, \
+ SYS_MAC_SYSCALL = 394 // { int mac_syscall(const char *policy, \
+ SYS_GETFSSTAT = 395 // { int getfsstat(struct statfs *buf, \
+ SYS_STATFS = 396 // { int statfs(char *path, \
+ SYS_FSTATFS = 397 // { int fstatfs(int fd, struct statfs *buf); }
+ SYS_FHSTATFS = 398 // { int fhstatfs(const struct fhandle *u_fhp, \
+ SYS___MAC_GET_PID = 409 // { int __mac_get_pid(pid_t pid, \
+ SYS___MAC_GET_LINK = 410 // { int __mac_get_link(const char *path_p, \
+ SYS___MAC_SET_LINK = 411 // { int __mac_set_link(const char *path_p, \
+ SYS_EXTATTR_SET_LINK = 412 // { ssize_t extattr_set_link( \
+ SYS_EXTATTR_GET_LINK = 413 // { ssize_t extattr_get_link( \
+ SYS_EXTATTR_DELETE_LINK = 414 // { int extattr_delete_link( \
+ SYS___MAC_EXECVE = 415 // { int __mac_execve(char *fname, char **argv, \
+ SYS_SIGACTION = 416 // { int sigaction(int sig, \
+ SYS_SIGRETURN = 417 // { int sigreturn( \
+ SYS_GETCONTEXT = 421 // { int getcontext(struct __ucontext *ucp); }
+ SYS_SETCONTEXT = 422 // { int setcontext( \
+ SYS_SWAPCONTEXT = 423 // { int swapcontext(struct __ucontext *oucp, \
+ SYS_SWAPOFF = 424 // { int swapoff(const char *name); }
+ SYS___ACL_GET_LINK = 425 // { int __acl_get_link(const char *path, \
+ SYS___ACL_SET_LINK = 426 // { int __acl_set_link(const char *path, \
+ SYS___ACL_DELETE_LINK = 427 // { int __acl_delete_link(const char *path, \
+ SYS___ACL_ACLCHECK_LINK = 428 // { int __acl_aclcheck_link(const char *path, \
+ SYS_SIGWAIT = 429 // { int sigwait(const sigset_t *set, \
+ SYS_THR_CREATE = 430 // { int thr_create(ucontext_t *ctx, long *id, \
+ SYS_THR_EXIT = 431 // { void thr_exit(long *state); }
+ SYS_THR_SELF = 432 // { int thr_self(long *id); }
+ SYS_THR_KILL = 433 // { int thr_kill(long id, int sig); }
+ SYS__UMTX_LOCK = 434 // { int _umtx_lock(struct umtx *umtx); }
+ SYS__UMTX_UNLOCK = 435 // { int _umtx_unlock(struct umtx *umtx); }
+ SYS_JAIL_ATTACH = 436 // { int jail_attach(int jid); }
+ SYS_EXTATTR_LIST_FD = 437 // { ssize_t extattr_list_fd(int fd, \
+ SYS_EXTATTR_LIST_FILE = 438 // { ssize_t extattr_list_file( \
+ SYS_EXTATTR_LIST_LINK = 439 // { ssize_t extattr_list_link( \
+ SYS_THR_SUSPEND = 442 // { int thr_suspend( \
+ SYS_THR_WAKE = 443 // { int thr_wake(long id); }
+ SYS_KLDUNLOADF = 444 // { int kldunloadf(int fileid, int flags); }
+ SYS_AUDIT = 445 // { int audit(const void *record, \
+ SYS_AUDITON = 446 // { int auditon(int cmd, void *data, \
+ SYS_GETAUID = 447 // { int getauid(uid_t *auid); }
+ SYS_SETAUID = 448 // { int setauid(uid_t *auid); }
+ SYS_GETAUDIT = 449 // { int getaudit(struct auditinfo *auditinfo); }
+ SYS_SETAUDIT = 450 // { int setaudit(struct auditinfo *auditinfo); }
+ SYS_GETAUDIT_ADDR = 451 // { int getaudit_addr( \
+ SYS_SETAUDIT_ADDR = 452 // { int setaudit_addr( \
+ SYS_AUDITCTL = 453 // { int auditctl(char *path); }
+ SYS__UMTX_OP = 454 // { int _umtx_op(void *obj, int op, \
+ SYS_THR_NEW = 455 // { int thr_new(struct thr_param *param, \
+ SYS_SIGQUEUE = 456 // { int sigqueue(pid_t pid, int signum, void *value); }
+ SYS_ABORT2 = 463 // { int abort2(const char *why, int nargs, void **args); }
+ SYS_THR_SET_NAME = 464 // { int thr_set_name(long id, const char *name); }
+ SYS_RTPRIO_THREAD = 466 // { int rtprio_thread(int function, \
+ SYS_PREAD = 475 // { ssize_t pread(int fd, void *buf, \
+ SYS_PWRITE = 476 // { ssize_t pwrite(int fd, const void *buf, \
+ SYS_MMAP = 477 // { caddr_t mmap(caddr_t addr, size_t len, \
+ SYS_LSEEK = 478 // { off_t lseek(int fd, off_t offset, \
+ SYS_TRUNCATE = 479 // { int truncate(char *path, off_t length); }
+ SYS_FTRUNCATE = 480 // { int ftruncate(int fd, off_t length); }
+ SYS_THR_KILL2 = 481 // { int thr_kill2(pid_t pid, long id, int sig); }
+ SYS_SHM_OPEN = 482 // { int shm_open(const char *path, int flags, \
+ SYS_SHM_UNLINK = 483 // { int shm_unlink(const char *path); }
+ SYS_CPUSET = 484 // { int cpuset(cpusetid_t *setid); }
+ SYS_CPUSET_SETID = 485 // { int cpuset_setid(cpuwhich_t which, id_t id, \
+ SYS_CPUSET_GETID = 486 // { int cpuset_getid(cpulevel_t level, \
+ SYS_CPUSET_GETAFFINITY = 487 // { int cpuset_getaffinity(cpulevel_t level, \
+ SYS_CPUSET_SETAFFINITY = 488 // { int cpuset_setaffinity(cpulevel_t level, \
+ SYS_FACCESSAT = 489 // { int faccessat(int fd, char *path, int amode, \
+ SYS_FCHMODAT = 490 // { int fchmodat(int fd, char *path, mode_t mode, \
+ SYS_FCHOWNAT = 491 // { int fchownat(int fd, char *path, uid_t uid, \
+ SYS_FEXECVE = 492 // { int fexecve(int fd, char **argv, \
+ SYS_FSTATAT = 493 // { int fstatat(int fd, char *path, \
+ SYS_FUTIMESAT = 494 // { int futimesat(int fd, char *path, \
+ SYS_LINKAT = 495 // { int linkat(int fd1, char *path1, int fd2, \
+ SYS_MKDIRAT = 496 // { int mkdirat(int fd, char *path, mode_t mode); }
+ SYS_MKFIFOAT = 497 // { int mkfifoat(int fd, char *path, mode_t mode); }
+ SYS_MKNODAT = 498 // { int mknodat(int fd, char *path, mode_t mode, \
+ SYS_OPENAT = 499 // { int openat(int fd, char *path, int flag, \
+ SYS_READLINKAT = 500 // { int readlinkat(int fd, char *path, char *buf, \
+ SYS_RENAMEAT = 501 // { int renameat(int oldfd, char *old, int newfd, \
+ SYS_SYMLINKAT = 502 // { int symlinkat(char *path1, int fd, \
+ SYS_UNLINKAT = 503 // { int unlinkat(int fd, char *path, int flag); }
+ SYS_POSIX_OPENPT = 504 // { int posix_openpt(int flags); }
+ SYS_JAIL_GET = 506 // { int jail_get(struct iovec *iovp, \
+ SYS_JAIL_SET = 507 // { int jail_set(struct iovec *iovp, \
+ SYS_JAIL_REMOVE = 508 // { int jail_remove(int jid); }
+ SYS_CLOSEFROM = 509 // { int closefrom(int lowfd); }
+ SYS_LPATHCONF = 513 // { int lpathconf(char *path, int name); }
+ SYS___CAP_RIGHTS_GET = 515 // { int __cap_rights_get(int version, \
+ SYS_CAP_ENTER = 516 // { int cap_enter(void); }
+ SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); }
+ SYS_PDFORK = 518 // { int pdfork(int *fdp, int flags); }
+ SYS_PDKILL = 519 // { int pdkill(int fd, int signum); }
+ SYS_PDGETPID = 520 // { int pdgetpid(int fd, pid_t *pidp); }
+ SYS_PSELECT = 522 // { int pselect(int nd, fd_set *in, \
+ SYS_GETLOGINCLASS = 523 // { int getloginclass(char *namebuf, \
+ SYS_SETLOGINCLASS = 524 // { int setloginclass(const char *namebuf); }
+ SYS_RCTL_GET_RACCT = 525 // { int rctl_get_racct(const void *inbufp, \
+ SYS_RCTL_GET_RULES = 526 // { int rctl_get_rules(const void *inbufp, \
+ SYS_RCTL_GET_LIMITS = 527 // { int rctl_get_limits(const void *inbufp, \
+ SYS_RCTL_ADD_RULE = 528 // { int rctl_add_rule(const void *inbufp, \
+ SYS_RCTL_REMOVE_RULE = 529 // { int rctl_remove_rule(const void *inbufp, \
+ SYS_POSIX_FALLOCATE = 530 // { int posix_fallocate(int fd, \
+ SYS_POSIX_FADVISE = 531 // { int posix_fadvise(int fd, off_t offset, \
+ SYS_WAIT6 = 532 // { int wait6(idtype_t idtype, id_t id, \
+ SYS_CAP_RIGHTS_LIMIT = 533 // { int cap_rights_limit(int fd, \
+ SYS_CAP_IOCTLS_LIMIT = 534 // { int cap_ioctls_limit(int fd, \
+ SYS_CAP_IOCTLS_GET = 535 // { ssize_t cap_ioctls_get(int fd, \
+ SYS_CAP_FCNTLS_LIMIT = 536 // { int cap_fcntls_limit(int fd, \
+ SYS_CAP_FCNTLS_GET = 537 // { int cap_fcntls_get(int fd, \
+ SYS_BINDAT = 538 // { int bindat(int fd, int s, caddr_t name, \
+ SYS_CONNECTAT = 539 // { int connectat(int fd, int s, caddr_t name, \
+ SYS_CHFLAGSAT = 540 // { int chflagsat(int fd, const char *path, \
+ SYS_ACCEPT4 = 541 // { int accept4(int s, \
+ SYS_PIPE2 = 542 // { int pipe2(int *fildes, int flags); }
+ SYS_PROCCTL = 544 // { int procctl(idtype_t idtype, id_t id, \
+ SYS_PPOLL = 545 // { int ppoll(struct pollfd *fds, u_int nfds, \
+ SYS_FUTIMENS = 546 // { int futimens(int fd, \
+ SYS_UTIMENSAT = 547 // { int utimensat(int fd, \
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go
new file mode 100644
index 0000000..4488314
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go
@@ -0,0 +1,353 @@
+// mksysnum_freebsd.pl
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm,freebsd
+
+package unix
+
+const (
+ // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int
+ SYS_EXIT = 1 // { void sys_exit(int rval); } exit \
+ SYS_FORK = 2 // { int fork(void); }
+ SYS_READ = 3 // { ssize_t read(int fd, void *buf, \
+ SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, \
+ SYS_OPEN = 5 // { int open(char *path, int flags, int mode); }
+ SYS_CLOSE = 6 // { int close(int fd); }
+ SYS_WAIT4 = 7 // { int wait4(int pid, int *status, \
+ SYS_LINK = 9 // { int link(char *path, char *link); }
+ SYS_UNLINK = 10 // { int unlink(char *path); }
+ SYS_CHDIR = 12 // { int chdir(char *path); }
+ SYS_FCHDIR = 13 // { int fchdir(int fd); }
+ SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); }
+ SYS_CHMOD = 15 // { int chmod(char *path, int mode); }
+ SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); }
+ SYS_OBREAK = 17 // { int obreak(char *nsize); } break \
+ SYS_GETPID = 20 // { pid_t getpid(void); }
+ SYS_MOUNT = 21 // { int mount(char *type, char *path, \
+ SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); }
+ SYS_SETUID = 23 // { int setuid(uid_t uid); }
+ SYS_GETUID = 24 // { uid_t getuid(void); }
+ SYS_GETEUID = 25 // { uid_t geteuid(void); }
+ SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, \
+ SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, \
+ SYS_SENDMSG = 28 // { int sendmsg(int s, struct msghdr *msg, \
+ SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, \
+ SYS_ACCEPT = 30 // { int accept(int s, \
+ SYS_GETPEERNAME = 31 // { int getpeername(int fdes, \
+ SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, \
+ SYS_ACCESS = 33 // { int access(char *path, int amode); }
+ SYS_CHFLAGS = 34 // { int chflags(const char *path, u_long flags); }
+ SYS_FCHFLAGS = 35 // { int fchflags(int fd, u_long flags); }
+ SYS_SYNC = 36 // { int sync(void); }
+ SYS_KILL = 37 // { int kill(int pid, int signum); }
+ SYS_GETPPID = 39 // { pid_t getppid(void); }
+ SYS_DUP = 41 // { int dup(u_int fd); }
+ SYS_PIPE = 42 // { int pipe(void); }
+ SYS_GETEGID = 43 // { gid_t getegid(void); }
+ SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \
+ SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, \
+ SYS_GETGID = 47 // { gid_t getgid(void); }
+ SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int \
+ SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); }
+ SYS_ACCT = 51 // { int acct(char *path); }
+ SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, \
+ SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, \
+ SYS_REBOOT = 55 // { int reboot(int opt); }
+ SYS_REVOKE = 56 // { int revoke(char *path); }
+ SYS_SYMLINK = 57 // { int symlink(char *path, char *link); }
+ SYS_READLINK = 58 // { ssize_t readlink(char *path, char *buf, \
+ SYS_EXECVE = 59 // { int execve(char *fname, char **argv, \
+ SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args \
+ SYS_CHROOT = 61 // { int chroot(char *path); }
+ SYS_MSYNC = 65 // { int msync(void *addr, size_t len, \
+ SYS_VFORK = 66 // { int vfork(void); }
+ SYS_SBRK = 69 // { int sbrk(int incr); }
+ SYS_SSTK = 70 // { int sstk(int incr); }
+ SYS_OVADVISE = 72 // { int ovadvise(int anom); } vadvise \
+ SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); }
+ SYS_MPROTECT = 74 // { int mprotect(const void *addr, size_t len, \
+ SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, \
+ SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \
+ SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, \
+ SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, \
+ SYS_GETPGRP = 81 // { int getpgrp(void); }
+ SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); }
+ SYS_SETITIMER = 83 // { int setitimer(u_int which, struct \
+ SYS_SWAPON = 85 // { int swapon(char *name); }
+ SYS_GETITIMER = 86 // { int getitimer(u_int which, \
+ SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); }
+ SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); }
+ SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); }
+ SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \
+ SYS_FSYNC = 95 // { int fsync(int fd); }
+ SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, \
+ SYS_SOCKET = 97 // { int socket(int domain, int type, \
+ SYS_CONNECT = 98 // { int connect(int s, caddr_t name, \
+ SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); }
+ SYS_BIND = 104 // { int bind(int s, caddr_t name, \
+ SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \
+ SYS_LISTEN = 106 // { int listen(int s, int backlog); }
+ SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \
+ SYS_GETRUSAGE = 117 // { int getrusage(int who, \
+ SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \
+ SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, \
+ SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \
+ SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \
+ SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); }
+ SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); }
+ SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); }
+ SYS_SETREGID = 127 // { int setregid(int rgid, int egid); }
+ SYS_RENAME = 128 // { int rename(char *from, char *to); }
+ SYS_FLOCK = 131 // { int flock(int fd, int how); }
+ SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); }
+ SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \
+ SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); }
+ SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, \
+ SYS_MKDIR = 136 // { int mkdir(char *path, int mode); }
+ SYS_RMDIR = 137 // { int rmdir(char *path); }
+ SYS_UTIMES = 138 // { int utimes(char *path, \
+ SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \
+ SYS_SETSID = 147 // { int setsid(void); }
+ SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \
+ SYS_LGETFH = 160 // { int lgetfh(char *fname, \
+ SYS_GETFH = 161 // { int getfh(char *fname, \
+ SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); }
+ SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \
+ SYS_FREEBSD6_PREAD = 173 // { ssize_t freebsd6_pread(int fd, void *buf, \
+ SYS_FREEBSD6_PWRITE = 174 // { ssize_t freebsd6_pwrite(int fd, \
+ SYS_SETFIB = 175 // { int setfib(int fibnum); }
+ SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); }
+ SYS_SETGID = 181 // { int setgid(gid_t gid); }
+ SYS_SETEGID = 182 // { int setegid(gid_t egid); }
+ SYS_SETEUID = 183 // { int seteuid(uid_t euid); }
+ SYS_STAT = 188 // { int stat(char *path, struct stat *ub); }
+ SYS_FSTAT = 189 // { int fstat(int fd, struct stat *sb); }
+ SYS_LSTAT = 190 // { int lstat(char *path, struct stat *ub); }
+ SYS_PATHCONF = 191 // { int pathconf(char *path, int name); }
+ SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); }
+ SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \
+ SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \
+ SYS_GETDIRENTRIES = 196 // { int getdirentries(int fd, char *buf, \
+ SYS_FREEBSD6_MMAP = 197 // { caddr_t freebsd6_mmap(caddr_t addr, \
+ SYS_FREEBSD6_LSEEK = 199 // { off_t freebsd6_lseek(int fd, int pad, \
+ SYS_FREEBSD6_TRUNCATE = 200 // { int freebsd6_truncate(char *path, int pad, \
+ SYS_FREEBSD6_FTRUNCATE = 201 // { int freebsd6_ftruncate(int fd, int pad, \
+ SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, \
+ SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); }
+ SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); }
+ SYS_UNDELETE = 205 // { int undelete(char *path); }
+ SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); }
+ SYS_GETPGID = 207 // { int getpgid(pid_t pid); }
+ SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \
+ SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \
+ SYS_CLOCK_SETTIME = 233 // { int clock_settime( \
+ SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \
+ SYS_KTIMER_CREATE = 235 // { int ktimer_create(clockid_t clock_id, \
+ SYS_KTIMER_DELETE = 236 // { int ktimer_delete(int timerid); }
+ SYS_KTIMER_SETTIME = 237 // { int ktimer_settime(int timerid, int flags, \
+ SYS_KTIMER_GETTIME = 238 // { int ktimer_gettime(int timerid, struct \
+ SYS_KTIMER_GETOVERRUN = 239 // { int ktimer_getoverrun(int timerid); }
+ SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \
+ SYS_FFCLOCK_GETCOUNTER = 241 // { int ffclock_getcounter(ffcounter *ffcount); }
+ SYS_FFCLOCK_SETESTIMATE = 242 // { int ffclock_setestimate( \
+ SYS_FFCLOCK_GETESTIMATE = 243 // { int ffclock_getestimate( \
+ SYS_CLOCK_GETCPUCLOCKID2 = 247 // { int clock_getcpuclockid2(id_t id,\
+ SYS_NTP_GETTIME = 248 // { int ntp_gettime(struct ntptimeval *ntvp); }
+ SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, \
+ SYS_RFORK = 251 // { int rfork(int flags); }
+ SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, \
+ SYS_ISSETUGID = 253 // { int issetugid(void); }
+ SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); }
+ SYS_GETDENTS = 272 // { int getdents(int fd, char *buf, \
+ SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); }
+ SYS_LUTIMES = 276 // { int lutimes(char *path, \
+ SYS_NSTAT = 278 // { int nstat(char *path, struct nstat *ub); }
+ SYS_NFSTAT = 279 // { int nfstat(int fd, struct nstat *sb); }
+ SYS_NLSTAT = 280 // { int nlstat(char *path, struct nstat *ub); }
+ SYS_PREADV = 289 // { ssize_t preadv(int fd, struct iovec *iovp, \
+ SYS_PWRITEV = 290 // { ssize_t pwritev(int fd, struct iovec *iovp, \
+ SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, \
+ SYS_FHSTAT = 299 // { int fhstat(const struct fhandle *u_fhp, \
+ SYS_MODNEXT = 300 // { int modnext(int modid); }
+ SYS_MODSTAT = 301 // { int modstat(int modid, \
+ SYS_MODFNEXT = 302 // { int modfnext(int modid); }
+ SYS_MODFIND = 303 // { int modfind(const char *name); }
+ SYS_KLDLOAD = 304 // { int kldload(const char *file); }
+ SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); }
+ SYS_KLDFIND = 306 // { int kldfind(const char *file); }
+ SYS_KLDNEXT = 307 // { int kldnext(int fileid); }
+ SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct \
+ SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); }
+ SYS_GETSID = 310 // { int getsid(pid_t pid); }
+ SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, \
+ SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, \
+ SYS_YIELD = 321 // { int yield(void); }
+ SYS_MLOCKALL = 324 // { int mlockall(int how); }
+ SYS_MUNLOCKALL = 325 // { int munlockall(void); }
+ SYS___GETCWD = 326 // { int __getcwd(char *buf, u_int buflen); }
+ SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, \
+ SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct \
+ SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int \
+ SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); }
+ SYS_SCHED_YIELD = 331 // { int sched_yield (void); }
+ SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); }
+ SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); }
+ SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, \
+ SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); }
+ SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, \
+ SYS_JAIL = 338 // { int jail(struct jail *jail); }
+ SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, \
+ SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); }
+ SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); }
+ SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set, \
+ SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set, \
+ SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \
+ SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \
+ SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, \
+ SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, \
+ SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \
+ SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, \
+ SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \
+ SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, \
+ SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \
+ SYS_EXTATTR_SET_FILE = 356 // { ssize_t extattr_set_file( \
+ SYS_EXTATTR_GET_FILE = 357 // { ssize_t extattr_get_file( \
+ SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \
+ SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, \
+ SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, \
+ SYS_KQUEUE = 362 // { int kqueue(void); }
+ SYS_KEVENT = 363 // { int kevent(int fd, \
+ SYS_EXTATTR_SET_FD = 371 // { ssize_t extattr_set_fd(int fd, \
+ SYS_EXTATTR_GET_FD = 372 // { ssize_t extattr_get_fd(int fd, \
+ SYS_EXTATTR_DELETE_FD = 373 // { int extattr_delete_fd(int fd, \
+ SYS___SETUGID = 374 // { int __setugid(int flag); }
+ SYS_EACCESS = 376 // { int eaccess(char *path, int amode); }
+ SYS_NMOUNT = 378 // { int nmount(struct iovec *iovp, \
+ SYS___MAC_GET_PROC = 384 // { int __mac_get_proc(struct mac *mac_p); }
+ SYS___MAC_SET_PROC = 385 // { int __mac_set_proc(struct mac *mac_p); }
+ SYS___MAC_GET_FD = 386 // { int __mac_get_fd(int fd, \
+ SYS___MAC_GET_FILE = 387 // { int __mac_get_file(const char *path_p, \
+ SYS___MAC_SET_FD = 388 // { int __mac_set_fd(int fd, \
+ SYS___MAC_SET_FILE = 389 // { int __mac_set_file(const char *path_p, \
+ SYS_KENV = 390 // { int kenv(int what, const char *name, \
+ SYS_LCHFLAGS = 391 // { int lchflags(const char *path, \
+ SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, \
+ SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, \
+ SYS_MAC_SYSCALL = 394 // { int mac_syscall(const char *policy, \
+ SYS_GETFSSTAT = 395 // { int getfsstat(struct statfs *buf, \
+ SYS_STATFS = 396 // { int statfs(char *path, \
+ SYS_FSTATFS = 397 // { int fstatfs(int fd, struct statfs *buf); }
+ SYS_FHSTATFS = 398 // { int fhstatfs(const struct fhandle *u_fhp, \
+ SYS___MAC_GET_PID = 409 // { int __mac_get_pid(pid_t pid, \
+ SYS___MAC_GET_LINK = 410 // { int __mac_get_link(const char *path_p, \
+ SYS___MAC_SET_LINK = 411 // { int __mac_set_link(const char *path_p, \
+ SYS_EXTATTR_SET_LINK = 412 // { ssize_t extattr_set_link( \
+ SYS_EXTATTR_GET_LINK = 413 // { ssize_t extattr_get_link( \
+ SYS_EXTATTR_DELETE_LINK = 414 // { int extattr_delete_link( \
+ SYS___MAC_EXECVE = 415 // { int __mac_execve(char *fname, char **argv, \
+ SYS_SIGACTION = 416 // { int sigaction(int sig, \
+ SYS_SIGRETURN = 417 // { int sigreturn( \
+ SYS_GETCONTEXT = 421 // { int getcontext(struct __ucontext *ucp); }
+ SYS_SETCONTEXT = 422 // { int setcontext( \
+ SYS_SWAPCONTEXT = 423 // { int swapcontext(struct __ucontext *oucp, \
+ SYS_SWAPOFF = 424 // { int swapoff(const char *name); }
+ SYS___ACL_GET_LINK = 425 // { int __acl_get_link(const char *path, \
+ SYS___ACL_SET_LINK = 426 // { int __acl_set_link(const char *path, \
+ SYS___ACL_DELETE_LINK = 427 // { int __acl_delete_link(const char *path, \
+ SYS___ACL_ACLCHECK_LINK = 428 // { int __acl_aclcheck_link(const char *path, \
+ SYS_SIGWAIT = 429 // { int sigwait(const sigset_t *set, \
+ SYS_THR_CREATE = 430 // { int thr_create(ucontext_t *ctx, long *id, \
+ SYS_THR_EXIT = 431 // { void thr_exit(long *state); }
+ SYS_THR_SELF = 432 // { int thr_self(long *id); }
+ SYS_THR_KILL = 433 // { int thr_kill(long id, int sig); }
+ SYS__UMTX_LOCK = 434 // { int _umtx_lock(struct umtx *umtx); }
+ SYS__UMTX_UNLOCK = 435 // { int _umtx_unlock(struct umtx *umtx); }
+ SYS_JAIL_ATTACH = 436 // { int jail_attach(int jid); }
+ SYS_EXTATTR_LIST_FD = 437 // { ssize_t extattr_list_fd(int fd, \
+ SYS_EXTATTR_LIST_FILE = 438 // { ssize_t extattr_list_file( \
+ SYS_EXTATTR_LIST_LINK = 439 // { ssize_t extattr_list_link( \
+ SYS_THR_SUSPEND = 442 // { int thr_suspend( \
+ SYS_THR_WAKE = 443 // { int thr_wake(long id); }
+ SYS_KLDUNLOADF = 444 // { int kldunloadf(int fileid, int flags); }
+ SYS_AUDIT = 445 // { int audit(const void *record, \
+ SYS_AUDITON = 446 // { int auditon(int cmd, void *data, \
+ SYS_GETAUID = 447 // { int getauid(uid_t *auid); }
+ SYS_SETAUID = 448 // { int setauid(uid_t *auid); }
+ SYS_GETAUDIT = 449 // { int getaudit(struct auditinfo *auditinfo); }
+ SYS_SETAUDIT = 450 // { int setaudit(struct auditinfo *auditinfo); }
+ SYS_GETAUDIT_ADDR = 451 // { int getaudit_addr( \
+ SYS_SETAUDIT_ADDR = 452 // { int setaudit_addr( \
+ SYS_AUDITCTL = 453 // { int auditctl(char *path); }
+ SYS__UMTX_OP = 454 // { int _umtx_op(void *obj, int op, \
+ SYS_THR_NEW = 455 // { int thr_new(struct thr_param *param, \
+ SYS_SIGQUEUE = 456 // { int sigqueue(pid_t pid, int signum, void *value); }
+ SYS_ABORT2 = 463 // { int abort2(const char *why, int nargs, void **args); }
+ SYS_THR_SET_NAME = 464 // { int thr_set_name(long id, const char *name); }
+ SYS_RTPRIO_THREAD = 466 // { int rtprio_thread(int function, \
+ SYS_PREAD = 475 // { ssize_t pread(int fd, void *buf, \
+ SYS_PWRITE = 476 // { ssize_t pwrite(int fd, const void *buf, \
+ SYS_MMAP = 477 // { caddr_t mmap(caddr_t addr, size_t len, \
+ SYS_LSEEK = 478 // { off_t lseek(int fd, off_t offset, \
+ SYS_TRUNCATE = 479 // { int truncate(char *path, off_t length); }
+ SYS_FTRUNCATE = 480 // { int ftruncate(int fd, off_t length); }
+ SYS_THR_KILL2 = 481 // { int thr_kill2(pid_t pid, long id, int sig); }
+ SYS_SHM_OPEN = 482 // { int shm_open(const char *path, int flags, \
+ SYS_SHM_UNLINK = 483 // { int shm_unlink(const char *path); }
+ SYS_CPUSET = 484 // { int cpuset(cpusetid_t *setid); }
+ SYS_CPUSET_SETID = 485 // { int cpuset_setid(cpuwhich_t which, id_t id, \
+ SYS_CPUSET_GETID = 486 // { int cpuset_getid(cpulevel_t level, \
+ SYS_CPUSET_GETAFFINITY = 487 // { int cpuset_getaffinity(cpulevel_t level, \
+ SYS_CPUSET_SETAFFINITY = 488 // { int cpuset_setaffinity(cpulevel_t level, \
+ SYS_FACCESSAT = 489 // { int faccessat(int fd, char *path, int amode, \
+ SYS_FCHMODAT = 490 // { int fchmodat(int fd, char *path, mode_t mode, \
+ SYS_FCHOWNAT = 491 // { int fchownat(int fd, char *path, uid_t uid, \
+ SYS_FEXECVE = 492 // { int fexecve(int fd, char **argv, \
+ SYS_FSTATAT = 493 // { int fstatat(int fd, char *path, \
+ SYS_FUTIMESAT = 494 // { int futimesat(int fd, char *path, \
+ SYS_LINKAT = 495 // { int linkat(int fd1, char *path1, int fd2, \
+ SYS_MKDIRAT = 496 // { int mkdirat(int fd, char *path, mode_t mode); }
+ SYS_MKFIFOAT = 497 // { int mkfifoat(int fd, char *path, mode_t mode); }
+ SYS_MKNODAT = 498 // { int mknodat(int fd, char *path, mode_t mode, \
+ SYS_OPENAT = 499 // { int openat(int fd, char *path, int flag, \
+ SYS_READLINKAT = 500 // { int readlinkat(int fd, char *path, char *buf, \
+ SYS_RENAMEAT = 501 // { int renameat(int oldfd, char *old, int newfd, \
+ SYS_SYMLINKAT = 502 // { int symlinkat(char *path1, int fd, \
+ SYS_UNLINKAT = 503 // { int unlinkat(int fd, char *path, int flag); }
+ SYS_POSIX_OPENPT = 504 // { int posix_openpt(int flags); }
+ SYS_JAIL_GET = 506 // { int jail_get(struct iovec *iovp, \
+ SYS_JAIL_SET = 507 // { int jail_set(struct iovec *iovp, \
+ SYS_JAIL_REMOVE = 508 // { int jail_remove(int jid); }
+ SYS_CLOSEFROM = 509 // { int closefrom(int lowfd); }
+ SYS_LPATHCONF = 513 // { int lpathconf(char *path, int name); }
+ SYS___CAP_RIGHTS_GET = 515 // { int __cap_rights_get(int version, \
+ SYS_CAP_ENTER = 516 // { int cap_enter(void); }
+ SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); }
+ SYS_PDFORK = 518 // { int pdfork(int *fdp, int flags); }
+ SYS_PDKILL = 519 // { int pdkill(int fd, int signum); }
+ SYS_PDGETPID = 520 // { int pdgetpid(int fd, pid_t *pidp); }
+ SYS_PSELECT = 522 // { int pselect(int nd, fd_set *in, \
+ SYS_GETLOGINCLASS = 523 // { int getloginclass(char *namebuf, \
+ SYS_SETLOGINCLASS = 524 // { int setloginclass(const char *namebuf); }
+ SYS_RCTL_GET_RACCT = 525 // { int rctl_get_racct(const void *inbufp, \
+ SYS_RCTL_GET_RULES = 526 // { int rctl_get_rules(const void *inbufp, \
+ SYS_RCTL_GET_LIMITS = 527 // { int rctl_get_limits(const void *inbufp, \
+ SYS_RCTL_ADD_RULE = 528 // { int rctl_add_rule(const void *inbufp, \
+ SYS_RCTL_REMOVE_RULE = 529 // { int rctl_remove_rule(const void *inbufp, \
+ SYS_POSIX_FALLOCATE = 530 // { int posix_fallocate(int fd, \
+ SYS_POSIX_FADVISE = 531 // { int posix_fadvise(int fd, off_t offset, \
+ SYS_WAIT6 = 532 // { int wait6(idtype_t idtype, id_t id, \
+ SYS_CAP_RIGHTS_LIMIT = 533 // { int cap_rights_limit(int fd, \
+ SYS_CAP_IOCTLS_LIMIT = 534 // { int cap_ioctls_limit(int fd, \
+ SYS_CAP_IOCTLS_GET = 535 // { ssize_t cap_ioctls_get(int fd, \
+ SYS_CAP_FCNTLS_LIMIT = 536 // { int cap_fcntls_limit(int fd, \
+ SYS_CAP_FCNTLS_GET = 537 // { int cap_fcntls_get(int fd, \
+ SYS_BINDAT = 538 // { int bindat(int fd, int s, caddr_t name, \
+ SYS_CONNECTAT = 539 // { int connectat(int fd, int s, caddr_t name, \
+ SYS_CHFLAGSAT = 540 // { int chflagsat(int fd, const char *path, \
+ SYS_ACCEPT4 = 541 // { int accept4(int s, \
+ SYS_PIPE2 = 542 // { int pipe2(int *fildes, int flags); }
+ SYS_PROCCTL = 544 // { int procctl(idtype_t idtype, id_t id, \
+ SYS_PPOLL = 545 // { int ppoll(struct pollfd *fds, u_int nfds, \
+ SYS_FUTIMENS = 546 // { int futimens(int fd, \
+ SYS_UTIMENSAT = 547 // { int utimensat(int fd, \
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go
new file mode 100644
index 0000000..cef4fed
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go
@@ -0,0 +1,388 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include -m32 /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build 386,linux
+
+package unix
+
+const (
+ SYS_RESTART_SYSCALL = 0
+ SYS_EXIT = 1
+ SYS_FORK = 2
+ SYS_READ = 3
+ SYS_WRITE = 4
+ SYS_OPEN = 5
+ SYS_CLOSE = 6
+ SYS_WAITPID = 7
+ SYS_CREAT = 8
+ SYS_LINK = 9
+ SYS_UNLINK = 10
+ SYS_EXECVE = 11
+ SYS_CHDIR = 12
+ SYS_TIME = 13
+ SYS_MKNOD = 14
+ SYS_CHMOD = 15
+ SYS_LCHOWN = 16
+ SYS_BREAK = 17
+ SYS_OLDSTAT = 18
+ SYS_LSEEK = 19
+ SYS_GETPID = 20
+ SYS_MOUNT = 21
+ SYS_UMOUNT = 22
+ SYS_SETUID = 23
+ SYS_GETUID = 24
+ SYS_STIME = 25
+ SYS_PTRACE = 26
+ SYS_ALARM = 27
+ SYS_OLDFSTAT = 28
+ SYS_PAUSE = 29
+ SYS_UTIME = 30
+ SYS_STTY = 31
+ SYS_GTTY = 32
+ SYS_ACCESS = 33
+ SYS_NICE = 34
+ SYS_FTIME = 35
+ SYS_SYNC = 36
+ SYS_KILL = 37
+ SYS_RENAME = 38
+ SYS_MKDIR = 39
+ SYS_RMDIR = 40
+ SYS_DUP = 41
+ SYS_PIPE = 42
+ SYS_TIMES = 43
+ SYS_PROF = 44
+ SYS_BRK = 45
+ SYS_SETGID = 46
+ SYS_GETGID = 47
+ SYS_SIGNAL = 48
+ SYS_GETEUID = 49
+ SYS_GETEGID = 50
+ SYS_ACCT = 51
+ SYS_UMOUNT2 = 52
+ SYS_LOCK = 53
+ SYS_IOCTL = 54
+ SYS_FCNTL = 55
+ SYS_MPX = 56
+ SYS_SETPGID = 57
+ SYS_ULIMIT = 58
+ SYS_OLDOLDUNAME = 59
+ SYS_UMASK = 60
+ SYS_CHROOT = 61
+ SYS_USTAT = 62
+ SYS_DUP2 = 63
+ SYS_GETPPID = 64
+ SYS_GETPGRP = 65
+ SYS_SETSID = 66
+ SYS_SIGACTION = 67
+ SYS_SGETMASK = 68
+ SYS_SSETMASK = 69
+ SYS_SETREUID = 70
+ SYS_SETREGID = 71
+ SYS_SIGSUSPEND = 72
+ SYS_SIGPENDING = 73
+ SYS_SETHOSTNAME = 74
+ SYS_SETRLIMIT = 75
+ SYS_GETRLIMIT = 76
+ SYS_GETRUSAGE = 77
+ SYS_GETTIMEOFDAY = 78
+ SYS_SETTIMEOFDAY = 79
+ SYS_GETGROUPS = 80
+ SYS_SETGROUPS = 81
+ SYS_SELECT = 82
+ SYS_SYMLINK = 83
+ SYS_OLDLSTAT = 84
+ SYS_READLINK = 85
+ SYS_USELIB = 86
+ SYS_SWAPON = 87
+ SYS_REBOOT = 88
+ SYS_READDIR = 89
+ SYS_MMAP = 90
+ SYS_MUNMAP = 91
+ SYS_TRUNCATE = 92
+ SYS_FTRUNCATE = 93
+ SYS_FCHMOD = 94
+ SYS_FCHOWN = 95
+ SYS_GETPRIORITY = 96
+ SYS_SETPRIORITY = 97
+ SYS_PROFIL = 98
+ SYS_STATFS = 99
+ SYS_FSTATFS = 100
+ SYS_IOPERM = 101
+ SYS_SOCKETCALL = 102
+ SYS_SYSLOG = 103
+ SYS_SETITIMER = 104
+ SYS_GETITIMER = 105
+ SYS_STAT = 106
+ SYS_LSTAT = 107
+ SYS_FSTAT = 108
+ SYS_OLDUNAME = 109
+ SYS_IOPL = 110
+ SYS_VHANGUP = 111
+ SYS_IDLE = 112
+ SYS_VM86OLD = 113
+ SYS_WAIT4 = 114
+ SYS_SWAPOFF = 115
+ SYS_SYSINFO = 116
+ SYS_IPC = 117
+ SYS_FSYNC = 118
+ SYS_SIGRETURN = 119
+ SYS_CLONE = 120
+ SYS_SETDOMAINNAME = 121
+ SYS_UNAME = 122
+ SYS_MODIFY_LDT = 123
+ SYS_ADJTIMEX = 124
+ SYS_MPROTECT = 125
+ SYS_SIGPROCMASK = 126
+ SYS_CREATE_MODULE = 127
+ SYS_INIT_MODULE = 128
+ SYS_DELETE_MODULE = 129
+ SYS_GET_KERNEL_SYMS = 130
+ SYS_QUOTACTL = 131
+ SYS_GETPGID = 132
+ SYS_FCHDIR = 133
+ SYS_BDFLUSH = 134
+ SYS_SYSFS = 135
+ SYS_PERSONALITY = 136
+ SYS_AFS_SYSCALL = 137
+ SYS_SETFSUID = 138
+ SYS_SETFSGID = 139
+ SYS__LLSEEK = 140
+ SYS_GETDENTS = 141
+ SYS__NEWSELECT = 142
+ SYS_FLOCK = 143
+ SYS_MSYNC = 144
+ SYS_READV = 145
+ SYS_WRITEV = 146
+ SYS_GETSID = 147
+ SYS_FDATASYNC = 148
+ SYS__SYSCTL = 149
+ SYS_MLOCK = 150
+ SYS_MUNLOCK = 151
+ SYS_MLOCKALL = 152
+ SYS_MUNLOCKALL = 153
+ SYS_SCHED_SETPARAM = 154
+ SYS_SCHED_GETPARAM = 155
+ SYS_SCHED_SETSCHEDULER = 156
+ SYS_SCHED_GETSCHEDULER = 157
+ SYS_SCHED_YIELD = 158
+ SYS_SCHED_GET_PRIORITY_MAX = 159
+ SYS_SCHED_GET_PRIORITY_MIN = 160
+ SYS_SCHED_RR_GET_INTERVAL = 161
+ SYS_NANOSLEEP = 162
+ SYS_MREMAP = 163
+ SYS_SETRESUID = 164
+ SYS_GETRESUID = 165
+ SYS_VM86 = 166
+ SYS_QUERY_MODULE = 167
+ SYS_POLL = 168
+ SYS_NFSSERVCTL = 169
+ SYS_SETRESGID = 170
+ SYS_GETRESGID = 171
+ SYS_PRCTL = 172
+ SYS_RT_SIGRETURN = 173
+ SYS_RT_SIGACTION = 174
+ SYS_RT_SIGPROCMASK = 175
+ SYS_RT_SIGPENDING = 176
+ SYS_RT_SIGTIMEDWAIT = 177
+ SYS_RT_SIGQUEUEINFO = 178
+ SYS_RT_SIGSUSPEND = 179
+ SYS_PREAD64 = 180
+ SYS_PWRITE64 = 181
+ SYS_CHOWN = 182
+ SYS_GETCWD = 183
+ SYS_CAPGET = 184
+ SYS_CAPSET = 185
+ SYS_SIGALTSTACK = 186
+ SYS_SENDFILE = 187
+ SYS_GETPMSG = 188
+ SYS_PUTPMSG = 189
+ SYS_VFORK = 190
+ SYS_UGETRLIMIT = 191
+ SYS_MMAP2 = 192
+ SYS_TRUNCATE64 = 193
+ SYS_FTRUNCATE64 = 194
+ SYS_STAT64 = 195
+ SYS_LSTAT64 = 196
+ SYS_FSTAT64 = 197
+ SYS_LCHOWN32 = 198
+ SYS_GETUID32 = 199
+ SYS_GETGID32 = 200
+ SYS_GETEUID32 = 201
+ SYS_GETEGID32 = 202
+ SYS_SETREUID32 = 203
+ SYS_SETREGID32 = 204
+ SYS_GETGROUPS32 = 205
+ SYS_SETGROUPS32 = 206
+ SYS_FCHOWN32 = 207
+ SYS_SETRESUID32 = 208
+ SYS_GETRESUID32 = 209
+ SYS_SETRESGID32 = 210
+ SYS_GETRESGID32 = 211
+ SYS_CHOWN32 = 212
+ SYS_SETUID32 = 213
+ SYS_SETGID32 = 214
+ SYS_SETFSUID32 = 215
+ SYS_SETFSGID32 = 216
+ SYS_PIVOT_ROOT = 217
+ SYS_MINCORE = 218
+ SYS_MADVISE = 219
+ SYS_GETDENTS64 = 220
+ SYS_FCNTL64 = 221
+ SYS_GETTID = 224
+ SYS_READAHEAD = 225
+ SYS_SETXATTR = 226
+ SYS_LSETXATTR = 227
+ SYS_FSETXATTR = 228
+ SYS_GETXATTR = 229
+ SYS_LGETXATTR = 230
+ SYS_FGETXATTR = 231
+ SYS_LISTXATTR = 232
+ SYS_LLISTXATTR = 233
+ SYS_FLISTXATTR = 234
+ SYS_REMOVEXATTR = 235
+ SYS_LREMOVEXATTR = 236
+ SYS_FREMOVEXATTR = 237
+ SYS_TKILL = 238
+ SYS_SENDFILE64 = 239
+ SYS_FUTEX = 240
+ SYS_SCHED_SETAFFINITY = 241
+ SYS_SCHED_GETAFFINITY = 242
+ SYS_SET_THREAD_AREA = 243
+ SYS_GET_THREAD_AREA = 244
+ SYS_IO_SETUP = 245
+ SYS_IO_DESTROY = 246
+ SYS_IO_GETEVENTS = 247
+ SYS_IO_SUBMIT = 248
+ SYS_IO_CANCEL = 249
+ SYS_FADVISE64 = 250
+ SYS_EXIT_GROUP = 252
+ SYS_LOOKUP_DCOOKIE = 253
+ SYS_EPOLL_CREATE = 254
+ SYS_EPOLL_CTL = 255
+ SYS_EPOLL_WAIT = 256
+ SYS_REMAP_FILE_PAGES = 257
+ SYS_SET_TID_ADDRESS = 258
+ SYS_TIMER_CREATE = 259
+ SYS_TIMER_SETTIME = 260
+ SYS_TIMER_GETTIME = 261
+ SYS_TIMER_GETOVERRUN = 262
+ SYS_TIMER_DELETE = 263
+ SYS_CLOCK_SETTIME = 264
+ SYS_CLOCK_GETTIME = 265
+ SYS_CLOCK_GETRES = 266
+ SYS_CLOCK_NANOSLEEP = 267
+ SYS_STATFS64 = 268
+ SYS_FSTATFS64 = 269
+ SYS_TGKILL = 270
+ SYS_UTIMES = 271
+ SYS_FADVISE64_64 = 272
+ SYS_VSERVER = 273
+ SYS_MBIND = 274
+ SYS_GET_MEMPOLICY = 275
+ SYS_SET_MEMPOLICY = 276
+ SYS_MQ_OPEN = 277
+ SYS_MQ_UNLINK = 278
+ SYS_MQ_TIMEDSEND = 279
+ SYS_MQ_TIMEDRECEIVE = 280
+ SYS_MQ_NOTIFY = 281
+ SYS_MQ_GETSETATTR = 282
+ SYS_KEXEC_LOAD = 283
+ SYS_WAITID = 284
+ SYS_ADD_KEY = 286
+ SYS_REQUEST_KEY = 287
+ SYS_KEYCTL = 288
+ SYS_IOPRIO_SET = 289
+ SYS_IOPRIO_GET = 290
+ SYS_INOTIFY_INIT = 291
+ SYS_INOTIFY_ADD_WATCH = 292
+ SYS_INOTIFY_RM_WATCH = 293
+ SYS_MIGRATE_PAGES = 294
+ SYS_OPENAT = 295
+ SYS_MKDIRAT = 296
+ SYS_MKNODAT = 297
+ SYS_FCHOWNAT = 298
+ SYS_FUTIMESAT = 299
+ SYS_FSTATAT64 = 300
+ SYS_UNLINKAT = 301
+ SYS_RENAMEAT = 302
+ SYS_LINKAT = 303
+ SYS_SYMLINKAT = 304
+ SYS_READLINKAT = 305
+ SYS_FCHMODAT = 306
+ SYS_FACCESSAT = 307
+ SYS_PSELECT6 = 308
+ SYS_PPOLL = 309
+ SYS_UNSHARE = 310
+ SYS_SET_ROBUST_LIST = 311
+ SYS_GET_ROBUST_LIST = 312
+ SYS_SPLICE = 313
+ SYS_SYNC_FILE_RANGE = 314
+ SYS_TEE = 315
+ SYS_VMSPLICE = 316
+ SYS_MOVE_PAGES = 317
+ SYS_GETCPU = 318
+ SYS_EPOLL_PWAIT = 319
+ SYS_UTIMENSAT = 320
+ SYS_SIGNALFD = 321
+ SYS_TIMERFD_CREATE = 322
+ SYS_EVENTFD = 323
+ SYS_FALLOCATE = 324
+ SYS_TIMERFD_SETTIME = 325
+ SYS_TIMERFD_GETTIME = 326
+ SYS_SIGNALFD4 = 327
+ SYS_EVENTFD2 = 328
+ SYS_EPOLL_CREATE1 = 329
+ SYS_DUP3 = 330
+ SYS_PIPE2 = 331
+ SYS_INOTIFY_INIT1 = 332
+ SYS_PREADV = 333
+ SYS_PWRITEV = 334
+ SYS_RT_TGSIGQUEUEINFO = 335
+ SYS_PERF_EVENT_OPEN = 336
+ SYS_RECVMMSG = 337
+ SYS_FANOTIFY_INIT = 338
+ SYS_FANOTIFY_MARK = 339
+ SYS_PRLIMIT64 = 340
+ SYS_NAME_TO_HANDLE_AT = 341
+ SYS_OPEN_BY_HANDLE_AT = 342
+ SYS_CLOCK_ADJTIME = 343
+ SYS_SYNCFS = 344
+ SYS_SENDMMSG = 345
+ SYS_SETNS = 346
+ SYS_PROCESS_VM_READV = 347
+ SYS_PROCESS_VM_WRITEV = 348
+ SYS_KCMP = 349
+ SYS_FINIT_MODULE = 350
+ SYS_SCHED_SETATTR = 351
+ SYS_SCHED_GETATTR = 352
+ SYS_RENAMEAT2 = 353
+ SYS_SECCOMP = 354
+ SYS_GETRANDOM = 355
+ SYS_MEMFD_CREATE = 356
+ SYS_BPF = 357
+ SYS_EXECVEAT = 358
+ SYS_SOCKET = 359
+ SYS_SOCKETPAIR = 360
+ SYS_BIND = 361
+ SYS_CONNECT = 362
+ SYS_LISTEN = 363
+ SYS_ACCEPT4 = 364
+ SYS_GETSOCKOPT = 365
+ SYS_SETSOCKOPT = 366
+ SYS_GETSOCKNAME = 367
+ SYS_GETPEERNAME = 368
+ SYS_SENDTO = 369
+ SYS_SENDMSG = 370
+ SYS_RECVFROM = 371
+ SYS_RECVMSG = 372
+ SYS_SHUTDOWN = 373
+ SYS_USERFAULTFD = 374
+ SYS_MEMBARRIER = 375
+ SYS_MLOCK2 = 376
+ SYS_COPY_FILE_RANGE = 377
+ SYS_PREADV2 = 378
+ SYS_PWRITEV2 = 379
+ SYS_PKEY_MPROTECT = 380
+ SYS_PKEY_ALLOC = 381
+ SYS_PKEY_FREE = 382
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go
new file mode 100644
index 0000000..49bfa12
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go
@@ -0,0 +1,341 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include -m64 /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,linux
+
+package unix
+
+const (
+ SYS_READ = 0
+ SYS_WRITE = 1
+ SYS_OPEN = 2
+ SYS_CLOSE = 3
+ SYS_STAT = 4
+ SYS_FSTAT = 5
+ SYS_LSTAT = 6
+ SYS_POLL = 7
+ SYS_LSEEK = 8
+ SYS_MMAP = 9
+ SYS_MPROTECT = 10
+ SYS_MUNMAP = 11
+ SYS_BRK = 12
+ SYS_RT_SIGACTION = 13
+ SYS_RT_SIGPROCMASK = 14
+ SYS_RT_SIGRETURN = 15
+ SYS_IOCTL = 16
+ SYS_PREAD64 = 17
+ SYS_PWRITE64 = 18
+ SYS_READV = 19
+ SYS_WRITEV = 20
+ SYS_ACCESS = 21
+ SYS_PIPE = 22
+ SYS_SELECT = 23
+ SYS_SCHED_YIELD = 24
+ SYS_MREMAP = 25
+ SYS_MSYNC = 26
+ SYS_MINCORE = 27
+ SYS_MADVISE = 28
+ SYS_SHMGET = 29
+ SYS_SHMAT = 30
+ SYS_SHMCTL = 31
+ SYS_DUP = 32
+ SYS_DUP2 = 33
+ SYS_PAUSE = 34
+ SYS_NANOSLEEP = 35
+ SYS_GETITIMER = 36
+ SYS_ALARM = 37
+ SYS_SETITIMER = 38
+ SYS_GETPID = 39
+ SYS_SENDFILE = 40
+ SYS_SOCKET = 41
+ SYS_CONNECT = 42
+ SYS_ACCEPT = 43
+ SYS_SENDTO = 44
+ SYS_RECVFROM = 45
+ SYS_SENDMSG = 46
+ SYS_RECVMSG = 47
+ SYS_SHUTDOWN = 48
+ SYS_BIND = 49
+ SYS_LISTEN = 50
+ SYS_GETSOCKNAME = 51
+ SYS_GETPEERNAME = 52
+ SYS_SOCKETPAIR = 53
+ SYS_SETSOCKOPT = 54
+ SYS_GETSOCKOPT = 55
+ SYS_CLONE = 56
+ SYS_FORK = 57
+ SYS_VFORK = 58
+ SYS_EXECVE = 59
+ SYS_EXIT = 60
+ SYS_WAIT4 = 61
+ SYS_KILL = 62
+ SYS_UNAME = 63
+ SYS_SEMGET = 64
+ SYS_SEMOP = 65
+ SYS_SEMCTL = 66
+ SYS_SHMDT = 67
+ SYS_MSGGET = 68
+ SYS_MSGSND = 69
+ SYS_MSGRCV = 70
+ SYS_MSGCTL = 71
+ SYS_FCNTL = 72
+ SYS_FLOCK = 73
+ SYS_FSYNC = 74
+ SYS_FDATASYNC = 75
+ SYS_TRUNCATE = 76
+ SYS_FTRUNCATE = 77
+ SYS_GETDENTS = 78
+ SYS_GETCWD = 79
+ SYS_CHDIR = 80
+ SYS_FCHDIR = 81
+ SYS_RENAME = 82
+ SYS_MKDIR = 83
+ SYS_RMDIR = 84
+ SYS_CREAT = 85
+ SYS_LINK = 86
+ SYS_UNLINK = 87
+ SYS_SYMLINK = 88
+ SYS_READLINK = 89
+ SYS_CHMOD = 90
+ SYS_FCHMOD = 91
+ SYS_CHOWN = 92
+ SYS_FCHOWN = 93
+ SYS_LCHOWN = 94
+ SYS_UMASK = 95
+ SYS_GETTIMEOFDAY = 96
+ SYS_GETRLIMIT = 97
+ SYS_GETRUSAGE = 98
+ SYS_SYSINFO = 99
+ SYS_TIMES = 100
+ SYS_PTRACE = 101
+ SYS_GETUID = 102
+ SYS_SYSLOG = 103
+ SYS_GETGID = 104
+ SYS_SETUID = 105
+ SYS_SETGID = 106
+ SYS_GETEUID = 107
+ SYS_GETEGID = 108
+ SYS_SETPGID = 109
+ SYS_GETPPID = 110
+ SYS_GETPGRP = 111
+ SYS_SETSID = 112
+ SYS_SETREUID = 113
+ SYS_SETREGID = 114
+ SYS_GETGROUPS = 115
+ SYS_SETGROUPS = 116
+ SYS_SETRESUID = 117
+ SYS_GETRESUID = 118
+ SYS_SETRESGID = 119
+ SYS_GETRESGID = 120
+ SYS_GETPGID = 121
+ SYS_SETFSUID = 122
+ SYS_SETFSGID = 123
+ SYS_GETSID = 124
+ SYS_CAPGET = 125
+ SYS_CAPSET = 126
+ SYS_RT_SIGPENDING = 127
+ SYS_RT_SIGTIMEDWAIT = 128
+ SYS_RT_SIGQUEUEINFO = 129
+ SYS_RT_SIGSUSPEND = 130
+ SYS_SIGALTSTACK = 131
+ SYS_UTIME = 132
+ SYS_MKNOD = 133
+ SYS_USELIB = 134
+ SYS_PERSONALITY = 135
+ SYS_USTAT = 136
+ SYS_STATFS = 137
+ SYS_FSTATFS = 138
+ SYS_SYSFS = 139
+ SYS_GETPRIORITY = 140
+ SYS_SETPRIORITY = 141
+ SYS_SCHED_SETPARAM = 142
+ SYS_SCHED_GETPARAM = 143
+ SYS_SCHED_SETSCHEDULER = 144
+ SYS_SCHED_GETSCHEDULER = 145
+ SYS_SCHED_GET_PRIORITY_MAX = 146
+ SYS_SCHED_GET_PRIORITY_MIN = 147
+ SYS_SCHED_RR_GET_INTERVAL = 148
+ SYS_MLOCK = 149
+ SYS_MUNLOCK = 150
+ SYS_MLOCKALL = 151
+ SYS_MUNLOCKALL = 152
+ SYS_VHANGUP = 153
+ SYS_MODIFY_LDT = 154
+ SYS_PIVOT_ROOT = 155
+ SYS__SYSCTL = 156
+ SYS_PRCTL = 157
+ SYS_ARCH_PRCTL = 158
+ SYS_ADJTIMEX = 159
+ SYS_SETRLIMIT = 160
+ SYS_CHROOT = 161
+ SYS_SYNC = 162
+ SYS_ACCT = 163
+ SYS_SETTIMEOFDAY = 164
+ SYS_MOUNT = 165
+ SYS_UMOUNT2 = 166
+ SYS_SWAPON = 167
+ SYS_SWAPOFF = 168
+ SYS_REBOOT = 169
+ SYS_SETHOSTNAME = 170
+ SYS_SETDOMAINNAME = 171
+ SYS_IOPL = 172
+ SYS_IOPERM = 173
+ SYS_CREATE_MODULE = 174
+ SYS_INIT_MODULE = 175
+ SYS_DELETE_MODULE = 176
+ SYS_GET_KERNEL_SYMS = 177
+ SYS_QUERY_MODULE = 178
+ SYS_QUOTACTL = 179
+ SYS_NFSSERVCTL = 180
+ SYS_GETPMSG = 181
+ SYS_PUTPMSG = 182
+ SYS_AFS_SYSCALL = 183
+ SYS_TUXCALL = 184
+ SYS_SECURITY = 185
+ SYS_GETTID = 186
+ SYS_READAHEAD = 187
+ SYS_SETXATTR = 188
+ SYS_LSETXATTR = 189
+ SYS_FSETXATTR = 190
+ SYS_GETXATTR = 191
+ SYS_LGETXATTR = 192
+ SYS_FGETXATTR = 193
+ SYS_LISTXATTR = 194
+ SYS_LLISTXATTR = 195
+ SYS_FLISTXATTR = 196
+ SYS_REMOVEXATTR = 197
+ SYS_LREMOVEXATTR = 198
+ SYS_FREMOVEXATTR = 199
+ SYS_TKILL = 200
+ SYS_TIME = 201
+ SYS_FUTEX = 202
+ SYS_SCHED_SETAFFINITY = 203
+ SYS_SCHED_GETAFFINITY = 204
+ SYS_SET_THREAD_AREA = 205
+ SYS_IO_SETUP = 206
+ SYS_IO_DESTROY = 207
+ SYS_IO_GETEVENTS = 208
+ SYS_IO_SUBMIT = 209
+ SYS_IO_CANCEL = 210
+ SYS_GET_THREAD_AREA = 211
+ SYS_LOOKUP_DCOOKIE = 212
+ SYS_EPOLL_CREATE = 213
+ SYS_EPOLL_CTL_OLD = 214
+ SYS_EPOLL_WAIT_OLD = 215
+ SYS_REMAP_FILE_PAGES = 216
+ SYS_GETDENTS64 = 217
+ SYS_SET_TID_ADDRESS = 218
+ SYS_RESTART_SYSCALL = 219
+ SYS_SEMTIMEDOP = 220
+ SYS_FADVISE64 = 221
+ SYS_TIMER_CREATE = 222
+ SYS_TIMER_SETTIME = 223
+ SYS_TIMER_GETTIME = 224
+ SYS_TIMER_GETOVERRUN = 225
+ SYS_TIMER_DELETE = 226
+ SYS_CLOCK_SETTIME = 227
+ SYS_CLOCK_GETTIME = 228
+ SYS_CLOCK_GETRES = 229
+ SYS_CLOCK_NANOSLEEP = 230
+ SYS_EXIT_GROUP = 231
+ SYS_EPOLL_WAIT = 232
+ SYS_EPOLL_CTL = 233
+ SYS_TGKILL = 234
+ SYS_UTIMES = 235
+ SYS_VSERVER = 236
+ SYS_MBIND = 237
+ SYS_SET_MEMPOLICY = 238
+ SYS_GET_MEMPOLICY = 239
+ SYS_MQ_OPEN = 240
+ SYS_MQ_UNLINK = 241
+ SYS_MQ_TIMEDSEND = 242
+ SYS_MQ_TIMEDRECEIVE = 243
+ SYS_MQ_NOTIFY = 244
+ SYS_MQ_GETSETATTR = 245
+ SYS_KEXEC_LOAD = 246
+ SYS_WAITID = 247
+ SYS_ADD_KEY = 248
+ SYS_REQUEST_KEY = 249
+ SYS_KEYCTL = 250
+ SYS_IOPRIO_SET = 251
+ SYS_IOPRIO_GET = 252
+ SYS_INOTIFY_INIT = 253
+ SYS_INOTIFY_ADD_WATCH = 254
+ SYS_INOTIFY_RM_WATCH = 255
+ SYS_MIGRATE_PAGES = 256
+ SYS_OPENAT = 257
+ SYS_MKDIRAT = 258
+ SYS_MKNODAT = 259
+ SYS_FCHOWNAT = 260
+ SYS_FUTIMESAT = 261
+ SYS_NEWFSTATAT = 262
+ SYS_UNLINKAT = 263
+ SYS_RENAMEAT = 264
+ SYS_LINKAT = 265
+ SYS_SYMLINKAT = 266
+ SYS_READLINKAT = 267
+ SYS_FCHMODAT = 268
+ SYS_FACCESSAT = 269
+ SYS_PSELECT6 = 270
+ SYS_PPOLL = 271
+ SYS_UNSHARE = 272
+ SYS_SET_ROBUST_LIST = 273
+ SYS_GET_ROBUST_LIST = 274
+ SYS_SPLICE = 275
+ SYS_TEE = 276
+ SYS_SYNC_FILE_RANGE = 277
+ SYS_VMSPLICE = 278
+ SYS_MOVE_PAGES = 279
+ SYS_UTIMENSAT = 280
+ SYS_EPOLL_PWAIT = 281
+ SYS_SIGNALFD = 282
+ SYS_TIMERFD_CREATE = 283
+ SYS_EVENTFD = 284
+ SYS_FALLOCATE = 285
+ SYS_TIMERFD_SETTIME = 286
+ SYS_TIMERFD_GETTIME = 287
+ SYS_ACCEPT4 = 288
+ SYS_SIGNALFD4 = 289
+ SYS_EVENTFD2 = 290
+ SYS_EPOLL_CREATE1 = 291
+ SYS_DUP3 = 292
+ SYS_PIPE2 = 293
+ SYS_INOTIFY_INIT1 = 294
+ SYS_PREADV = 295
+ SYS_PWRITEV = 296
+ SYS_RT_TGSIGQUEUEINFO = 297
+ SYS_PERF_EVENT_OPEN = 298
+ SYS_RECVMMSG = 299
+ SYS_FANOTIFY_INIT = 300
+ SYS_FANOTIFY_MARK = 301
+ SYS_PRLIMIT64 = 302
+ SYS_NAME_TO_HANDLE_AT = 303
+ SYS_OPEN_BY_HANDLE_AT = 304
+ SYS_CLOCK_ADJTIME = 305
+ SYS_SYNCFS = 306
+ SYS_SENDMMSG = 307
+ SYS_SETNS = 308
+ SYS_GETCPU = 309
+ SYS_PROCESS_VM_READV = 310
+ SYS_PROCESS_VM_WRITEV = 311
+ SYS_KCMP = 312
+ SYS_FINIT_MODULE = 313
+ SYS_SCHED_SETATTR = 314
+ SYS_SCHED_GETATTR = 315
+ SYS_RENAMEAT2 = 316
+ SYS_SECCOMP = 317
+ SYS_GETRANDOM = 318
+ SYS_MEMFD_CREATE = 319
+ SYS_KEXEC_FILE_LOAD = 320
+ SYS_BPF = 321
+ SYS_EXECVEAT = 322
+ SYS_USERFAULTFD = 323
+ SYS_MEMBARRIER = 324
+ SYS_MLOCK2 = 325
+ SYS_COPY_FILE_RANGE = 326
+ SYS_PREADV2 = 327
+ SYS_PWRITEV2 = 328
+ SYS_PKEY_MPROTECT = 329
+ SYS_PKEY_ALLOC = 330
+ SYS_PKEY_FREE = 331
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go
new file mode 100644
index 0000000..97b182e
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go
@@ -0,0 +1,361 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm,linux
+
+package unix
+
+const (
+ SYS_RESTART_SYSCALL = 0
+ SYS_EXIT = 1
+ SYS_FORK = 2
+ SYS_READ = 3
+ SYS_WRITE = 4
+ SYS_OPEN = 5
+ SYS_CLOSE = 6
+ SYS_CREAT = 8
+ SYS_LINK = 9
+ SYS_UNLINK = 10
+ SYS_EXECVE = 11
+ SYS_CHDIR = 12
+ SYS_MKNOD = 14
+ SYS_CHMOD = 15
+ SYS_LCHOWN = 16
+ SYS_LSEEK = 19
+ SYS_GETPID = 20
+ SYS_MOUNT = 21
+ SYS_SETUID = 23
+ SYS_GETUID = 24
+ SYS_PTRACE = 26
+ SYS_PAUSE = 29
+ SYS_ACCESS = 33
+ SYS_NICE = 34
+ SYS_SYNC = 36
+ SYS_KILL = 37
+ SYS_RENAME = 38
+ SYS_MKDIR = 39
+ SYS_RMDIR = 40
+ SYS_DUP = 41
+ SYS_PIPE = 42
+ SYS_TIMES = 43
+ SYS_BRK = 45
+ SYS_SETGID = 46
+ SYS_GETGID = 47
+ SYS_GETEUID = 49
+ SYS_GETEGID = 50
+ SYS_ACCT = 51
+ SYS_UMOUNT2 = 52
+ SYS_IOCTL = 54
+ SYS_FCNTL = 55
+ SYS_SETPGID = 57
+ SYS_UMASK = 60
+ SYS_CHROOT = 61
+ SYS_USTAT = 62
+ SYS_DUP2 = 63
+ SYS_GETPPID = 64
+ SYS_GETPGRP = 65
+ SYS_SETSID = 66
+ SYS_SIGACTION = 67
+ SYS_SETREUID = 70
+ SYS_SETREGID = 71
+ SYS_SIGSUSPEND = 72
+ SYS_SIGPENDING = 73
+ SYS_SETHOSTNAME = 74
+ SYS_SETRLIMIT = 75
+ SYS_GETRUSAGE = 77
+ SYS_GETTIMEOFDAY = 78
+ SYS_SETTIMEOFDAY = 79
+ SYS_GETGROUPS = 80
+ SYS_SETGROUPS = 81
+ SYS_SYMLINK = 83
+ SYS_READLINK = 85
+ SYS_USELIB = 86
+ SYS_SWAPON = 87
+ SYS_REBOOT = 88
+ SYS_MUNMAP = 91
+ SYS_TRUNCATE = 92
+ SYS_FTRUNCATE = 93
+ SYS_FCHMOD = 94
+ SYS_FCHOWN = 95
+ SYS_GETPRIORITY = 96
+ SYS_SETPRIORITY = 97
+ SYS_STATFS = 99
+ SYS_FSTATFS = 100
+ SYS_SYSLOG = 103
+ SYS_SETITIMER = 104
+ SYS_GETITIMER = 105
+ SYS_STAT = 106
+ SYS_LSTAT = 107
+ SYS_FSTAT = 108
+ SYS_VHANGUP = 111
+ SYS_WAIT4 = 114
+ SYS_SWAPOFF = 115
+ SYS_SYSINFO = 116
+ SYS_FSYNC = 118
+ SYS_SIGRETURN = 119
+ SYS_CLONE = 120
+ SYS_SETDOMAINNAME = 121
+ SYS_UNAME = 122
+ SYS_ADJTIMEX = 124
+ SYS_MPROTECT = 125
+ SYS_SIGPROCMASK = 126
+ SYS_INIT_MODULE = 128
+ SYS_DELETE_MODULE = 129
+ SYS_QUOTACTL = 131
+ SYS_GETPGID = 132
+ SYS_FCHDIR = 133
+ SYS_BDFLUSH = 134
+ SYS_SYSFS = 135
+ SYS_PERSONALITY = 136
+ SYS_SETFSUID = 138
+ SYS_SETFSGID = 139
+ SYS__LLSEEK = 140
+ SYS_GETDENTS = 141
+ SYS__NEWSELECT = 142
+ SYS_FLOCK = 143
+ SYS_MSYNC = 144
+ SYS_READV = 145
+ SYS_WRITEV = 146
+ SYS_GETSID = 147
+ SYS_FDATASYNC = 148
+ SYS__SYSCTL = 149
+ SYS_MLOCK = 150
+ SYS_MUNLOCK = 151
+ SYS_MLOCKALL = 152
+ SYS_MUNLOCKALL = 153
+ SYS_SCHED_SETPARAM = 154
+ SYS_SCHED_GETPARAM = 155
+ SYS_SCHED_SETSCHEDULER = 156
+ SYS_SCHED_GETSCHEDULER = 157
+ SYS_SCHED_YIELD = 158
+ SYS_SCHED_GET_PRIORITY_MAX = 159
+ SYS_SCHED_GET_PRIORITY_MIN = 160
+ SYS_SCHED_RR_GET_INTERVAL = 161
+ SYS_NANOSLEEP = 162
+ SYS_MREMAP = 163
+ SYS_SETRESUID = 164
+ SYS_GETRESUID = 165
+ SYS_POLL = 168
+ SYS_NFSSERVCTL = 169
+ SYS_SETRESGID = 170
+ SYS_GETRESGID = 171
+ SYS_PRCTL = 172
+ SYS_RT_SIGRETURN = 173
+ SYS_RT_SIGACTION = 174
+ SYS_RT_SIGPROCMASK = 175
+ SYS_RT_SIGPENDING = 176
+ SYS_RT_SIGTIMEDWAIT = 177
+ SYS_RT_SIGQUEUEINFO = 178
+ SYS_RT_SIGSUSPEND = 179
+ SYS_PREAD64 = 180
+ SYS_PWRITE64 = 181
+ SYS_CHOWN = 182
+ SYS_GETCWD = 183
+ SYS_CAPGET = 184
+ SYS_CAPSET = 185
+ SYS_SIGALTSTACK = 186
+ SYS_SENDFILE = 187
+ SYS_VFORK = 190
+ SYS_UGETRLIMIT = 191
+ SYS_MMAP2 = 192
+ SYS_TRUNCATE64 = 193
+ SYS_FTRUNCATE64 = 194
+ SYS_STAT64 = 195
+ SYS_LSTAT64 = 196
+ SYS_FSTAT64 = 197
+ SYS_LCHOWN32 = 198
+ SYS_GETUID32 = 199
+ SYS_GETGID32 = 200
+ SYS_GETEUID32 = 201
+ SYS_GETEGID32 = 202
+ SYS_SETREUID32 = 203
+ SYS_SETREGID32 = 204
+ SYS_GETGROUPS32 = 205
+ SYS_SETGROUPS32 = 206
+ SYS_FCHOWN32 = 207
+ SYS_SETRESUID32 = 208
+ SYS_GETRESUID32 = 209
+ SYS_SETRESGID32 = 210
+ SYS_GETRESGID32 = 211
+ SYS_CHOWN32 = 212
+ SYS_SETUID32 = 213
+ SYS_SETGID32 = 214
+ SYS_SETFSUID32 = 215
+ SYS_SETFSGID32 = 216
+ SYS_GETDENTS64 = 217
+ SYS_PIVOT_ROOT = 218
+ SYS_MINCORE = 219
+ SYS_MADVISE = 220
+ SYS_FCNTL64 = 221
+ SYS_GETTID = 224
+ SYS_READAHEAD = 225
+ SYS_SETXATTR = 226
+ SYS_LSETXATTR = 227
+ SYS_FSETXATTR = 228
+ SYS_GETXATTR = 229
+ SYS_LGETXATTR = 230
+ SYS_FGETXATTR = 231
+ SYS_LISTXATTR = 232
+ SYS_LLISTXATTR = 233
+ SYS_FLISTXATTR = 234
+ SYS_REMOVEXATTR = 235
+ SYS_LREMOVEXATTR = 236
+ SYS_FREMOVEXATTR = 237
+ SYS_TKILL = 238
+ SYS_SENDFILE64 = 239
+ SYS_FUTEX = 240
+ SYS_SCHED_SETAFFINITY = 241
+ SYS_SCHED_GETAFFINITY = 242
+ SYS_IO_SETUP = 243
+ SYS_IO_DESTROY = 244
+ SYS_IO_GETEVENTS = 245
+ SYS_IO_SUBMIT = 246
+ SYS_IO_CANCEL = 247
+ SYS_EXIT_GROUP = 248
+ SYS_LOOKUP_DCOOKIE = 249
+ SYS_EPOLL_CREATE = 250
+ SYS_EPOLL_CTL = 251
+ SYS_EPOLL_WAIT = 252
+ SYS_REMAP_FILE_PAGES = 253
+ SYS_SET_TID_ADDRESS = 256
+ SYS_TIMER_CREATE = 257
+ SYS_TIMER_SETTIME = 258
+ SYS_TIMER_GETTIME = 259
+ SYS_TIMER_GETOVERRUN = 260
+ SYS_TIMER_DELETE = 261
+ SYS_CLOCK_SETTIME = 262
+ SYS_CLOCK_GETTIME = 263
+ SYS_CLOCK_GETRES = 264
+ SYS_CLOCK_NANOSLEEP = 265
+ SYS_STATFS64 = 266
+ SYS_FSTATFS64 = 267
+ SYS_TGKILL = 268
+ SYS_UTIMES = 269
+ SYS_ARM_FADVISE64_64 = 270
+ SYS_PCICONFIG_IOBASE = 271
+ SYS_PCICONFIG_READ = 272
+ SYS_PCICONFIG_WRITE = 273
+ SYS_MQ_OPEN = 274
+ SYS_MQ_UNLINK = 275
+ SYS_MQ_TIMEDSEND = 276
+ SYS_MQ_TIMEDRECEIVE = 277
+ SYS_MQ_NOTIFY = 278
+ SYS_MQ_GETSETATTR = 279
+ SYS_WAITID = 280
+ SYS_SOCKET = 281
+ SYS_BIND = 282
+ SYS_CONNECT = 283
+ SYS_LISTEN = 284
+ SYS_ACCEPT = 285
+ SYS_GETSOCKNAME = 286
+ SYS_GETPEERNAME = 287
+ SYS_SOCKETPAIR = 288
+ SYS_SEND = 289
+ SYS_SENDTO = 290
+ SYS_RECV = 291
+ SYS_RECVFROM = 292
+ SYS_SHUTDOWN = 293
+ SYS_SETSOCKOPT = 294
+ SYS_GETSOCKOPT = 295
+ SYS_SENDMSG = 296
+ SYS_RECVMSG = 297
+ SYS_SEMOP = 298
+ SYS_SEMGET = 299
+ SYS_SEMCTL = 300
+ SYS_MSGSND = 301
+ SYS_MSGRCV = 302
+ SYS_MSGGET = 303
+ SYS_MSGCTL = 304
+ SYS_SHMAT = 305
+ SYS_SHMDT = 306
+ SYS_SHMGET = 307
+ SYS_SHMCTL = 308
+ SYS_ADD_KEY = 309
+ SYS_REQUEST_KEY = 310
+ SYS_KEYCTL = 311
+ SYS_SEMTIMEDOP = 312
+ SYS_VSERVER = 313
+ SYS_IOPRIO_SET = 314
+ SYS_IOPRIO_GET = 315
+ SYS_INOTIFY_INIT = 316
+ SYS_INOTIFY_ADD_WATCH = 317
+ SYS_INOTIFY_RM_WATCH = 318
+ SYS_MBIND = 319
+ SYS_GET_MEMPOLICY = 320
+ SYS_SET_MEMPOLICY = 321
+ SYS_OPENAT = 322
+ SYS_MKDIRAT = 323
+ SYS_MKNODAT = 324
+ SYS_FCHOWNAT = 325
+ SYS_FUTIMESAT = 326
+ SYS_FSTATAT64 = 327
+ SYS_UNLINKAT = 328
+ SYS_RENAMEAT = 329
+ SYS_LINKAT = 330
+ SYS_SYMLINKAT = 331
+ SYS_READLINKAT = 332
+ SYS_FCHMODAT = 333
+ SYS_FACCESSAT = 334
+ SYS_PSELECT6 = 335
+ SYS_PPOLL = 336
+ SYS_UNSHARE = 337
+ SYS_SET_ROBUST_LIST = 338
+ SYS_GET_ROBUST_LIST = 339
+ SYS_SPLICE = 340
+ SYS_ARM_SYNC_FILE_RANGE = 341
+ SYS_TEE = 342
+ SYS_VMSPLICE = 343
+ SYS_MOVE_PAGES = 344
+ SYS_GETCPU = 345
+ SYS_EPOLL_PWAIT = 346
+ SYS_KEXEC_LOAD = 347
+ SYS_UTIMENSAT = 348
+ SYS_SIGNALFD = 349
+ SYS_TIMERFD_CREATE = 350
+ SYS_EVENTFD = 351
+ SYS_FALLOCATE = 352
+ SYS_TIMERFD_SETTIME = 353
+ SYS_TIMERFD_GETTIME = 354
+ SYS_SIGNALFD4 = 355
+ SYS_EVENTFD2 = 356
+ SYS_EPOLL_CREATE1 = 357
+ SYS_DUP3 = 358
+ SYS_PIPE2 = 359
+ SYS_INOTIFY_INIT1 = 360
+ SYS_PREADV = 361
+ SYS_PWRITEV = 362
+ SYS_RT_TGSIGQUEUEINFO = 363
+ SYS_PERF_EVENT_OPEN = 364
+ SYS_RECVMMSG = 365
+ SYS_ACCEPT4 = 366
+ SYS_FANOTIFY_INIT = 367
+ SYS_FANOTIFY_MARK = 368
+ SYS_PRLIMIT64 = 369
+ SYS_NAME_TO_HANDLE_AT = 370
+ SYS_OPEN_BY_HANDLE_AT = 371
+ SYS_CLOCK_ADJTIME = 372
+ SYS_SYNCFS = 373
+ SYS_SENDMMSG = 374
+ SYS_SETNS = 375
+ SYS_PROCESS_VM_READV = 376
+ SYS_PROCESS_VM_WRITEV = 377
+ SYS_KCMP = 378
+ SYS_FINIT_MODULE = 379
+ SYS_SCHED_SETATTR = 380
+ SYS_SCHED_GETATTR = 381
+ SYS_RENAMEAT2 = 382
+ SYS_SECCOMP = 383
+ SYS_GETRANDOM = 384
+ SYS_MEMFD_CREATE = 385
+ SYS_BPF = 386
+ SYS_EXECVEAT = 387
+ SYS_USERFAULTFD = 388
+ SYS_MEMBARRIER = 389
+ SYS_MLOCK2 = 390
+ SYS_COPY_FILE_RANGE = 391
+ SYS_PREADV2 = 392
+ SYS_PWRITEV2 = 393
+ SYS_PKEY_MPROTECT = 394
+ SYS_PKEY_ALLOC = 395
+ SYS_PKEY_FREE = 396
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go
new file mode 100644
index 0000000..6407843
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go
@@ -0,0 +1,285 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include -fsigned-char /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm64,linux
+
+package unix
+
+const (
+ SYS_IO_SETUP = 0
+ SYS_IO_DESTROY = 1
+ SYS_IO_SUBMIT = 2
+ SYS_IO_CANCEL = 3
+ SYS_IO_GETEVENTS = 4
+ SYS_SETXATTR = 5
+ SYS_LSETXATTR = 6
+ SYS_FSETXATTR = 7
+ SYS_GETXATTR = 8
+ SYS_LGETXATTR = 9
+ SYS_FGETXATTR = 10
+ SYS_LISTXATTR = 11
+ SYS_LLISTXATTR = 12
+ SYS_FLISTXATTR = 13
+ SYS_REMOVEXATTR = 14
+ SYS_LREMOVEXATTR = 15
+ SYS_FREMOVEXATTR = 16
+ SYS_GETCWD = 17
+ SYS_LOOKUP_DCOOKIE = 18
+ SYS_EVENTFD2 = 19
+ SYS_EPOLL_CREATE1 = 20
+ SYS_EPOLL_CTL = 21
+ SYS_EPOLL_PWAIT = 22
+ SYS_DUP = 23
+ SYS_DUP3 = 24
+ SYS_FCNTL = 25
+ SYS_INOTIFY_INIT1 = 26
+ SYS_INOTIFY_ADD_WATCH = 27
+ SYS_INOTIFY_RM_WATCH = 28
+ SYS_IOCTL = 29
+ SYS_IOPRIO_SET = 30
+ SYS_IOPRIO_GET = 31
+ SYS_FLOCK = 32
+ SYS_MKNODAT = 33
+ SYS_MKDIRAT = 34
+ SYS_UNLINKAT = 35
+ SYS_SYMLINKAT = 36
+ SYS_LINKAT = 37
+ SYS_RENAMEAT = 38
+ SYS_UMOUNT2 = 39
+ SYS_MOUNT = 40
+ SYS_PIVOT_ROOT = 41
+ SYS_NFSSERVCTL = 42
+ SYS_STATFS = 43
+ SYS_FSTATFS = 44
+ SYS_TRUNCATE = 45
+ SYS_FTRUNCATE = 46
+ SYS_FALLOCATE = 47
+ SYS_FACCESSAT = 48
+ SYS_CHDIR = 49
+ SYS_FCHDIR = 50
+ SYS_CHROOT = 51
+ SYS_FCHMOD = 52
+ SYS_FCHMODAT = 53
+ SYS_FCHOWNAT = 54
+ SYS_FCHOWN = 55
+ SYS_OPENAT = 56
+ SYS_CLOSE = 57
+ SYS_VHANGUP = 58
+ SYS_PIPE2 = 59
+ SYS_QUOTACTL = 60
+ SYS_GETDENTS64 = 61
+ SYS_LSEEK = 62
+ SYS_READ = 63
+ SYS_WRITE = 64
+ SYS_READV = 65
+ SYS_WRITEV = 66
+ SYS_PREAD64 = 67
+ SYS_PWRITE64 = 68
+ SYS_PREADV = 69
+ SYS_PWRITEV = 70
+ SYS_SENDFILE = 71
+ SYS_PSELECT6 = 72
+ SYS_PPOLL = 73
+ SYS_SIGNALFD4 = 74
+ SYS_VMSPLICE = 75
+ SYS_SPLICE = 76
+ SYS_TEE = 77
+ SYS_READLINKAT = 78
+ SYS_FSTATAT = 79
+ SYS_FSTAT = 80
+ SYS_SYNC = 81
+ SYS_FSYNC = 82
+ SYS_FDATASYNC = 83
+ SYS_SYNC_FILE_RANGE = 84
+ SYS_TIMERFD_CREATE = 85
+ SYS_TIMERFD_SETTIME = 86
+ SYS_TIMERFD_GETTIME = 87
+ SYS_UTIMENSAT = 88
+ SYS_ACCT = 89
+ SYS_CAPGET = 90
+ SYS_CAPSET = 91
+ SYS_PERSONALITY = 92
+ SYS_EXIT = 93
+ SYS_EXIT_GROUP = 94
+ SYS_WAITID = 95
+ SYS_SET_TID_ADDRESS = 96
+ SYS_UNSHARE = 97
+ SYS_FUTEX = 98
+ SYS_SET_ROBUST_LIST = 99
+ SYS_GET_ROBUST_LIST = 100
+ SYS_NANOSLEEP = 101
+ SYS_GETITIMER = 102
+ SYS_SETITIMER = 103
+ SYS_KEXEC_LOAD = 104
+ SYS_INIT_MODULE = 105
+ SYS_DELETE_MODULE = 106
+ SYS_TIMER_CREATE = 107
+ SYS_TIMER_GETTIME = 108
+ SYS_TIMER_GETOVERRUN = 109
+ SYS_TIMER_SETTIME = 110
+ SYS_TIMER_DELETE = 111
+ SYS_CLOCK_SETTIME = 112
+ SYS_CLOCK_GETTIME = 113
+ SYS_CLOCK_GETRES = 114
+ SYS_CLOCK_NANOSLEEP = 115
+ SYS_SYSLOG = 116
+ SYS_PTRACE = 117
+ SYS_SCHED_SETPARAM = 118
+ SYS_SCHED_SETSCHEDULER = 119
+ SYS_SCHED_GETSCHEDULER = 120
+ SYS_SCHED_GETPARAM = 121
+ SYS_SCHED_SETAFFINITY = 122
+ SYS_SCHED_GETAFFINITY = 123
+ SYS_SCHED_YIELD = 124
+ SYS_SCHED_GET_PRIORITY_MAX = 125
+ SYS_SCHED_GET_PRIORITY_MIN = 126
+ SYS_SCHED_RR_GET_INTERVAL = 127
+ SYS_RESTART_SYSCALL = 128
+ SYS_KILL = 129
+ SYS_TKILL = 130
+ SYS_TGKILL = 131
+ SYS_SIGALTSTACK = 132
+ SYS_RT_SIGSUSPEND = 133
+ SYS_RT_SIGACTION = 134
+ SYS_RT_SIGPROCMASK = 135
+ SYS_RT_SIGPENDING = 136
+ SYS_RT_SIGTIMEDWAIT = 137
+ SYS_RT_SIGQUEUEINFO = 138
+ SYS_RT_SIGRETURN = 139
+ SYS_SETPRIORITY = 140
+ SYS_GETPRIORITY = 141
+ SYS_REBOOT = 142
+ SYS_SETREGID = 143
+ SYS_SETGID = 144
+ SYS_SETREUID = 145
+ SYS_SETUID = 146
+ SYS_SETRESUID = 147
+ SYS_GETRESUID = 148
+ SYS_SETRESGID = 149
+ SYS_GETRESGID = 150
+ SYS_SETFSUID = 151
+ SYS_SETFSGID = 152
+ SYS_TIMES = 153
+ SYS_SETPGID = 154
+ SYS_GETPGID = 155
+ SYS_GETSID = 156
+ SYS_SETSID = 157
+ SYS_GETGROUPS = 158
+ SYS_SETGROUPS = 159
+ SYS_UNAME = 160
+ SYS_SETHOSTNAME = 161
+ SYS_SETDOMAINNAME = 162
+ SYS_GETRLIMIT = 163
+ SYS_SETRLIMIT = 164
+ SYS_GETRUSAGE = 165
+ SYS_UMASK = 166
+ SYS_PRCTL = 167
+ SYS_GETCPU = 168
+ SYS_GETTIMEOFDAY = 169
+ SYS_SETTIMEOFDAY = 170
+ SYS_ADJTIMEX = 171
+ SYS_GETPID = 172
+ SYS_GETPPID = 173
+ SYS_GETUID = 174
+ SYS_GETEUID = 175
+ SYS_GETGID = 176
+ SYS_GETEGID = 177
+ SYS_GETTID = 178
+ SYS_SYSINFO = 179
+ SYS_MQ_OPEN = 180
+ SYS_MQ_UNLINK = 181
+ SYS_MQ_TIMEDSEND = 182
+ SYS_MQ_TIMEDRECEIVE = 183
+ SYS_MQ_NOTIFY = 184
+ SYS_MQ_GETSETATTR = 185
+ SYS_MSGGET = 186
+ SYS_MSGCTL = 187
+ SYS_MSGRCV = 188
+ SYS_MSGSND = 189
+ SYS_SEMGET = 190
+ SYS_SEMCTL = 191
+ SYS_SEMTIMEDOP = 192
+ SYS_SEMOP = 193
+ SYS_SHMGET = 194
+ SYS_SHMCTL = 195
+ SYS_SHMAT = 196
+ SYS_SHMDT = 197
+ SYS_SOCKET = 198
+ SYS_SOCKETPAIR = 199
+ SYS_BIND = 200
+ SYS_LISTEN = 201
+ SYS_ACCEPT = 202
+ SYS_CONNECT = 203
+ SYS_GETSOCKNAME = 204
+ SYS_GETPEERNAME = 205
+ SYS_SENDTO = 206
+ SYS_RECVFROM = 207
+ SYS_SETSOCKOPT = 208
+ SYS_GETSOCKOPT = 209
+ SYS_SHUTDOWN = 210
+ SYS_SENDMSG = 211
+ SYS_RECVMSG = 212
+ SYS_READAHEAD = 213
+ SYS_BRK = 214
+ SYS_MUNMAP = 215
+ SYS_MREMAP = 216
+ SYS_ADD_KEY = 217
+ SYS_REQUEST_KEY = 218
+ SYS_KEYCTL = 219
+ SYS_CLONE = 220
+ SYS_EXECVE = 221
+ SYS_MMAP = 222
+ SYS_FADVISE64 = 223
+ SYS_SWAPON = 224
+ SYS_SWAPOFF = 225
+ SYS_MPROTECT = 226
+ SYS_MSYNC = 227
+ SYS_MLOCK = 228
+ SYS_MUNLOCK = 229
+ SYS_MLOCKALL = 230
+ SYS_MUNLOCKALL = 231
+ SYS_MINCORE = 232
+ SYS_MADVISE = 233
+ SYS_REMAP_FILE_PAGES = 234
+ SYS_MBIND = 235
+ SYS_GET_MEMPOLICY = 236
+ SYS_SET_MEMPOLICY = 237
+ SYS_MIGRATE_PAGES = 238
+ SYS_MOVE_PAGES = 239
+ SYS_RT_TGSIGQUEUEINFO = 240
+ SYS_PERF_EVENT_OPEN = 241
+ SYS_ACCEPT4 = 242
+ SYS_RECVMMSG = 243
+ SYS_ARCH_SPECIFIC_SYSCALL = 244
+ SYS_WAIT4 = 260
+ SYS_PRLIMIT64 = 261
+ SYS_FANOTIFY_INIT = 262
+ SYS_FANOTIFY_MARK = 263
+ SYS_NAME_TO_HANDLE_AT = 264
+ SYS_OPEN_BY_HANDLE_AT = 265
+ SYS_CLOCK_ADJTIME = 266
+ SYS_SYNCFS = 267
+ SYS_SETNS = 268
+ SYS_SENDMMSG = 269
+ SYS_PROCESS_VM_READV = 270
+ SYS_PROCESS_VM_WRITEV = 271
+ SYS_KCMP = 272
+ SYS_FINIT_MODULE = 273
+ SYS_SCHED_SETATTR = 274
+ SYS_SCHED_GETATTR = 275
+ SYS_RENAMEAT2 = 276
+ SYS_SECCOMP = 277
+ SYS_GETRANDOM = 278
+ SYS_MEMFD_CREATE = 279
+ SYS_BPF = 280
+ SYS_EXECVEAT = 281
+ SYS_USERFAULTFD = 282
+ SYS_MEMBARRIER = 283
+ SYS_MLOCK2 = 284
+ SYS_COPY_FILE_RANGE = 285
+ SYS_PREADV2 = 286
+ SYS_PWRITEV2 = 287
+ SYS_PKEY_MPROTECT = 288
+ SYS_PKEY_ALLOC = 289
+ SYS_PKEY_FREE = 290
+)
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..939567c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go
@@ -0,0 +1,374 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. 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_KCMP = 4347
+ SYS_FINIT_MODULE = 4348
+ SYS_SCHED_SETATTR = 4349
+ SYS_SCHED_GETATTR = 4350
+ SYS_RENAMEAT2 = 4351
+ SYS_SECCOMP = 4352
+ SYS_GETRANDOM = 4353
+ SYS_MEMFD_CREATE = 4354
+ SYS_BPF = 4355
+ SYS_EXECVEAT = 4356
+ SYS_USERFAULTFD = 4357
+ SYS_MEMBARRIER = 4358
+ SYS_MLOCK2 = 4359
+ SYS_COPY_FILE_RANGE = 4360
+ SYS_PREADV2 = 4361
+ SYS_PWRITEV2 = 4362
+ SYS_PKEY_MPROTECT = 4363
+ SYS_PKEY_ALLOC = 4364
+ SYS_PKEY_FREE = 4365
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go
new file mode 100644
index 0000000..09db959
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go
@@ -0,0 +1,334 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build mips64,linux
+
+package unix
+
+const (
+ SYS_READ = 5000
+ SYS_WRITE = 5001
+ SYS_OPEN = 5002
+ SYS_CLOSE = 5003
+ SYS_STAT = 5004
+ SYS_FSTAT = 5005
+ SYS_LSTAT = 5006
+ SYS_POLL = 5007
+ SYS_LSEEK = 5008
+ SYS_MMAP = 5009
+ SYS_MPROTECT = 5010
+ SYS_MUNMAP = 5011
+ SYS_BRK = 5012
+ SYS_RT_SIGACTION = 5013
+ SYS_RT_SIGPROCMASK = 5014
+ SYS_IOCTL = 5015
+ SYS_PREAD64 = 5016
+ SYS_PWRITE64 = 5017
+ SYS_READV = 5018
+ SYS_WRITEV = 5019
+ SYS_ACCESS = 5020
+ SYS_PIPE = 5021
+ SYS__NEWSELECT = 5022
+ SYS_SCHED_YIELD = 5023
+ SYS_MREMAP = 5024
+ SYS_MSYNC = 5025
+ SYS_MINCORE = 5026
+ SYS_MADVISE = 5027
+ SYS_SHMGET = 5028
+ SYS_SHMAT = 5029
+ SYS_SHMCTL = 5030
+ SYS_DUP = 5031
+ SYS_DUP2 = 5032
+ SYS_PAUSE = 5033
+ SYS_NANOSLEEP = 5034
+ SYS_GETITIMER = 5035
+ SYS_SETITIMER = 5036
+ SYS_ALARM = 5037
+ SYS_GETPID = 5038
+ SYS_SENDFILE = 5039
+ SYS_SOCKET = 5040
+ SYS_CONNECT = 5041
+ SYS_ACCEPT = 5042
+ SYS_SENDTO = 5043
+ SYS_RECVFROM = 5044
+ SYS_SENDMSG = 5045
+ SYS_RECVMSG = 5046
+ SYS_SHUTDOWN = 5047
+ SYS_BIND = 5048
+ SYS_LISTEN = 5049
+ SYS_GETSOCKNAME = 5050
+ SYS_GETPEERNAME = 5051
+ SYS_SOCKETPAIR = 5052
+ SYS_SETSOCKOPT = 5053
+ SYS_GETSOCKOPT = 5054
+ SYS_CLONE = 5055
+ SYS_FORK = 5056
+ SYS_EXECVE = 5057
+ SYS_EXIT = 5058
+ SYS_WAIT4 = 5059
+ SYS_KILL = 5060
+ SYS_UNAME = 5061
+ SYS_SEMGET = 5062
+ SYS_SEMOP = 5063
+ SYS_SEMCTL = 5064
+ SYS_SHMDT = 5065
+ SYS_MSGGET = 5066
+ SYS_MSGSND = 5067
+ SYS_MSGRCV = 5068
+ SYS_MSGCTL = 5069
+ SYS_FCNTL = 5070
+ SYS_FLOCK = 5071
+ SYS_FSYNC = 5072
+ SYS_FDATASYNC = 5073
+ SYS_TRUNCATE = 5074
+ SYS_FTRUNCATE = 5075
+ SYS_GETDENTS = 5076
+ SYS_GETCWD = 5077
+ SYS_CHDIR = 5078
+ SYS_FCHDIR = 5079
+ SYS_RENAME = 5080
+ SYS_MKDIR = 5081
+ SYS_RMDIR = 5082
+ SYS_CREAT = 5083
+ SYS_LINK = 5084
+ SYS_UNLINK = 5085
+ SYS_SYMLINK = 5086
+ SYS_READLINK = 5087
+ SYS_CHMOD = 5088
+ SYS_FCHMOD = 5089
+ SYS_CHOWN = 5090
+ SYS_FCHOWN = 5091
+ SYS_LCHOWN = 5092
+ SYS_UMASK = 5093
+ SYS_GETTIMEOFDAY = 5094
+ SYS_GETRLIMIT = 5095
+ SYS_GETRUSAGE = 5096
+ SYS_SYSINFO = 5097
+ SYS_TIMES = 5098
+ SYS_PTRACE = 5099
+ SYS_GETUID = 5100
+ SYS_SYSLOG = 5101
+ SYS_GETGID = 5102
+ SYS_SETUID = 5103
+ SYS_SETGID = 5104
+ SYS_GETEUID = 5105
+ SYS_GETEGID = 5106
+ SYS_SETPGID = 5107
+ SYS_GETPPID = 5108
+ SYS_GETPGRP = 5109
+ SYS_SETSID = 5110
+ SYS_SETREUID = 5111
+ SYS_SETREGID = 5112
+ SYS_GETGROUPS = 5113
+ SYS_SETGROUPS = 5114
+ SYS_SETRESUID = 5115
+ SYS_GETRESUID = 5116
+ SYS_SETRESGID = 5117
+ SYS_GETRESGID = 5118
+ SYS_GETPGID = 5119
+ SYS_SETFSUID = 5120
+ SYS_SETFSGID = 5121
+ SYS_GETSID = 5122
+ SYS_CAPGET = 5123
+ SYS_CAPSET = 5124
+ SYS_RT_SIGPENDING = 5125
+ SYS_RT_SIGTIMEDWAIT = 5126
+ SYS_RT_SIGQUEUEINFO = 5127
+ SYS_RT_SIGSUSPEND = 5128
+ SYS_SIGALTSTACK = 5129
+ SYS_UTIME = 5130
+ SYS_MKNOD = 5131
+ SYS_PERSONALITY = 5132
+ SYS_USTAT = 5133
+ SYS_STATFS = 5134
+ SYS_FSTATFS = 5135
+ SYS_SYSFS = 5136
+ SYS_GETPRIORITY = 5137
+ SYS_SETPRIORITY = 5138
+ SYS_SCHED_SETPARAM = 5139
+ SYS_SCHED_GETPARAM = 5140
+ SYS_SCHED_SETSCHEDULER = 5141
+ SYS_SCHED_GETSCHEDULER = 5142
+ SYS_SCHED_GET_PRIORITY_MAX = 5143
+ SYS_SCHED_GET_PRIORITY_MIN = 5144
+ SYS_SCHED_RR_GET_INTERVAL = 5145
+ SYS_MLOCK = 5146
+ SYS_MUNLOCK = 5147
+ SYS_MLOCKALL = 5148
+ SYS_MUNLOCKALL = 5149
+ SYS_VHANGUP = 5150
+ SYS_PIVOT_ROOT = 5151
+ SYS__SYSCTL = 5152
+ SYS_PRCTL = 5153
+ SYS_ADJTIMEX = 5154
+ SYS_SETRLIMIT = 5155
+ SYS_CHROOT = 5156
+ SYS_SYNC = 5157
+ SYS_ACCT = 5158
+ SYS_SETTIMEOFDAY = 5159
+ SYS_MOUNT = 5160
+ SYS_UMOUNT2 = 5161
+ SYS_SWAPON = 5162
+ SYS_SWAPOFF = 5163
+ SYS_REBOOT = 5164
+ SYS_SETHOSTNAME = 5165
+ SYS_SETDOMAINNAME = 5166
+ SYS_CREATE_MODULE = 5167
+ SYS_INIT_MODULE = 5168
+ SYS_DELETE_MODULE = 5169
+ SYS_GET_KERNEL_SYMS = 5170
+ SYS_QUERY_MODULE = 5171
+ SYS_QUOTACTL = 5172
+ SYS_NFSSERVCTL = 5173
+ SYS_GETPMSG = 5174
+ SYS_PUTPMSG = 5175
+ SYS_AFS_SYSCALL = 5176
+ SYS_RESERVED177 = 5177
+ SYS_GETTID = 5178
+ SYS_READAHEAD = 5179
+ SYS_SETXATTR = 5180
+ SYS_LSETXATTR = 5181
+ SYS_FSETXATTR = 5182
+ SYS_GETXATTR = 5183
+ SYS_LGETXATTR = 5184
+ SYS_FGETXATTR = 5185
+ SYS_LISTXATTR = 5186
+ SYS_LLISTXATTR = 5187
+ SYS_FLISTXATTR = 5188
+ SYS_REMOVEXATTR = 5189
+ SYS_LREMOVEXATTR = 5190
+ SYS_FREMOVEXATTR = 5191
+ SYS_TKILL = 5192
+ SYS_RESERVED193 = 5193
+ SYS_FUTEX = 5194
+ SYS_SCHED_SETAFFINITY = 5195
+ SYS_SCHED_GETAFFINITY = 5196
+ SYS_CACHEFLUSH = 5197
+ SYS_CACHECTL = 5198
+ SYS_SYSMIPS = 5199
+ SYS_IO_SETUP = 5200
+ SYS_IO_DESTROY = 5201
+ SYS_IO_GETEVENTS = 5202
+ SYS_IO_SUBMIT = 5203
+ SYS_IO_CANCEL = 5204
+ SYS_EXIT_GROUP = 5205
+ SYS_LOOKUP_DCOOKIE = 5206
+ SYS_EPOLL_CREATE = 5207
+ SYS_EPOLL_CTL = 5208
+ SYS_EPOLL_WAIT = 5209
+ SYS_REMAP_FILE_PAGES = 5210
+ SYS_RT_SIGRETURN = 5211
+ SYS_SET_TID_ADDRESS = 5212
+ SYS_RESTART_SYSCALL = 5213
+ SYS_SEMTIMEDOP = 5214
+ SYS_FADVISE64 = 5215
+ SYS_TIMER_CREATE = 5216
+ SYS_TIMER_SETTIME = 5217
+ SYS_TIMER_GETTIME = 5218
+ SYS_TIMER_GETOVERRUN = 5219
+ SYS_TIMER_DELETE = 5220
+ SYS_CLOCK_SETTIME = 5221
+ SYS_CLOCK_GETTIME = 5222
+ SYS_CLOCK_GETRES = 5223
+ SYS_CLOCK_NANOSLEEP = 5224
+ SYS_TGKILL = 5225
+ SYS_UTIMES = 5226
+ SYS_MBIND = 5227
+ SYS_GET_MEMPOLICY = 5228
+ SYS_SET_MEMPOLICY = 5229
+ SYS_MQ_OPEN = 5230
+ SYS_MQ_UNLINK = 5231
+ SYS_MQ_TIMEDSEND = 5232
+ SYS_MQ_TIMEDRECEIVE = 5233
+ SYS_MQ_NOTIFY = 5234
+ SYS_MQ_GETSETATTR = 5235
+ SYS_VSERVER = 5236
+ SYS_WAITID = 5237
+ SYS_ADD_KEY = 5239
+ SYS_REQUEST_KEY = 5240
+ SYS_KEYCTL = 5241
+ SYS_SET_THREAD_AREA = 5242
+ SYS_INOTIFY_INIT = 5243
+ SYS_INOTIFY_ADD_WATCH = 5244
+ SYS_INOTIFY_RM_WATCH = 5245
+ SYS_MIGRATE_PAGES = 5246
+ SYS_OPENAT = 5247
+ SYS_MKDIRAT = 5248
+ SYS_MKNODAT = 5249
+ SYS_FCHOWNAT = 5250
+ SYS_FUTIMESAT = 5251
+ SYS_NEWFSTATAT = 5252
+ SYS_UNLINKAT = 5253
+ SYS_RENAMEAT = 5254
+ SYS_LINKAT = 5255
+ SYS_SYMLINKAT = 5256
+ SYS_READLINKAT = 5257
+ SYS_FCHMODAT = 5258
+ SYS_FACCESSAT = 5259
+ SYS_PSELECT6 = 5260
+ SYS_PPOLL = 5261
+ SYS_UNSHARE = 5262
+ SYS_SPLICE = 5263
+ SYS_SYNC_FILE_RANGE = 5264
+ SYS_TEE = 5265
+ SYS_VMSPLICE = 5266
+ SYS_MOVE_PAGES = 5267
+ SYS_SET_ROBUST_LIST = 5268
+ SYS_GET_ROBUST_LIST = 5269
+ SYS_KEXEC_LOAD = 5270
+ SYS_GETCPU = 5271
+ SYS_EPOLL_PWAIT = 5272
+ SYS_IOPRIO_SET = 5273
+ SYS_IOPRIO_GET = 5274
+ SYS_UTIMENSAT = 5275
+ SYS_SIGNALFD = 5276
+ SYS_TIMERFD = 5277
+ SYS_EVENTFD = 5278
+ SYS_FALLOCATE = 5279
+ SYS_TIMERFD_CREATE = 5280
+ SYS_TIMERFD_GETTIME = 5281
+ SYS_TIMERFD_SETTIME = 5282
+ SYS_SIGNALFD4 = 5283
+ SYS_EVENTFD2 = 5284
+ SYS_EPOLL_CREATE1 = 5285
+ SYS_DUP3 = 5286
+ SYS_PIPE2 = 5287
+ SYS_INOTIFY_INIT1 = 5288
+ SYS_PREADV = 5289
+ SYS_PWRITEV = 5290
+ SYS_RT_TGSIGQUEUEINFO = 5291
+ SYS_PERF_EVENT_OPEN = 5292
+ SYS_ACCEPT4 = 5293
+ SYS_RECVMMSG = 5294
+ SYS_FANOTIFY_INIT = 5295
+ SYS_FANOTIFY_MARK = 5296
+ SYS_PRLIMIT64 = 5297
+ SYS_NAME_TO_HANDLE_AT = 5298
+ SYS_OPEN_BY_HANDLE_AT = 5299
+ SYS_CLOCK_ADJTIME = 5300
+ SYS_SYNCFS = 5301
+ SYS_SENDMMSG = 5302
+ SYS_SETNS = 5303
+ SYS_PROCESS_VM_READV = 5304
+ SYS_PROCESS_VM_WRITEV = 5305
+ SYS_KCMP = 5306
+ SYS_FINIT_MODULE = 5307
+ SYS_GETDENTS64 = 5308
+ SYS_SCHED_SETATTR = 5309
+ SYS_SCHED_GETATTR = 5310
+ SYS_RENAMEAT2 = 5311
+ SYS_SECCOMP = 5312
+ SYS_GETRANDOM = 5313
+ SYS_MEMFD_CREATE = 5314
+ SYS_BPF = 5315
+ SYS_EXECVEAT = 5316
+ SYS_USERFAULTFD = 5317
+ SYS_MEMBARRIER = 5318
+ SYS_MLOCK2 = 5319
+ SYS_COPY_FILE_RANGE = 5320
+ SYS_PREADV2 = 5321
+ SYS_PWRITEV2 = 5322
+ SYS_PKEY_MPROTECT = 5323
+ SYS_PKEY_ALLOC = 5324
+ SYS_PKEY_FREE = 5325
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go
new file mode 100644
index 0000000..d1b872a
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go
@@ -0,0 +1,334 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build mips64le,linux
+
+package unix
+
+const (
+ SYS_READ = 5000
+ SYS_WRITE = 5001
+ SYS_OPEN = 5002
+ SYS_CLOSE = 5003
+ SYS_STAT = 5004
+ SYS_FSTAT = 5005
+ SYS_LSTAT = 5006
+ SYS_POLL = 5007
+ SYS_LSEEK = 5008
+ SYS_MMAP = 5009
+ SYS_MPROTECT = 5010
+ SYS_MUNMAP = 5011
+ SYS_BRK = 5012
+ SYS_RT_SIGACTION = 5013
+ SYS_RT_SIGPROCMASK = 5014
+ SYS_IOCTL = 5015
+ SYS_PREAD64 = 5016
+ SYS_PWRITE64 = 5017
+ SYS_READV = 5018
+ SYS_WRITEV = 5019
+ SYS_ACCESS = 5020
+ SYS_PIPE = 5021
+ SYS__NEWSELECT = 5022
+ SYS_SCHED_YIELD = 5023
+ SYS_MREMAP = 5024
+ SYS_MSYNC = 5025
+ SYS_MINCORE = 5026
+ SYS_MADVISE = 5027
+ SYS_SHMGET = 5028
+ SYS_SHMAT = 5029
+ SYS_SHMCTL = 5030
+ SYS_DUP = 5031
+ SYS_DUP2 = 5032
+ SYS_PAUSE = 5033
+ SYS_NANOSLEEP = 5034
+ SYS_GETITIMER = 5035
+ SYS_SETITIMER = 5036
+ SYS_ALARM = 5037
+ SYS_GETPID = 5038
+ SYS_SENDFILE = 5039
+ SYS_SOCKET = 5040
+ SYS_CONNECT = 5041
+ SYS_ACCEPT = 5042
+ SYS_SENDTO = 5043
+ SYS_RECVFROM = 5044
+ SYS_SENDMSG = 5045
+ SYS_RECVMSG = 5046
+ SYS_SHUTDOWN = 5047
+ SYS_BIND = 5048
+ SYS_LISTEN = 5049
+ SYS_GETSOCKNAME = 5050
+ SYS_GETPEERNAME = 5051
+ SYS_SOCKETPAIR = 5052
+ SYS_SETSOCKOPT = 5053
+ SYS_GETSOCKOPT = 5054
+ SYS_CLONE = 5055
+ SYS_FORK = 5056
+ SYS_EXECVE = 5057
+ SYS_EXIT = 5058
+ SYS_WAIT4 = 5059
+ SYS_KILL = 5060
+ SYS_UNAME = 5061
+ SYS_SEMGET = 5062
+ SYS_SEMOP = 5063
+ SYS_SEMCTL = 5064
+ SYS_SHMDT = 5065
+ SYS_MSGGET = 5066
+ SYS_MSGSND = 5067
+ SYS_MSGRCV = 5068
+ SYS_MSGCTL = 5069
+ SYS_FCNTL = 5070
+ SYS_FLOCK = 5071
+ SYS_FSYNC = 5072
+ SYS_FDATASYNC = 5073
+ SYS_TRUNCATE = 5074
+ SYS_FTRUNCATE = 5075
+ SYS_GETDENTS = 5076
+ SYS_GETCWD = 5077
+ SYS_CHDIR = 5078
+ SYS_FCHDIR = 5079
+ SYS_RENAME = 5080
+ SYS_MKDIR = 5081
+ SYS_RMDIR = 5082
+ SYS_CREAT = 5083
+ SYS_LINK = 5084
+ SYS_UNLINK = 5085
+ SYS_SYMLINK = 5086
+ SYS_READLINK = 5087
+ SYS_CHMOD = 5088
+ SYS_FCHMOD = 5089
+ SYS_CHOWN = 5090
+ SYS_FCHOWN = 5091
+ SYS_LCHOWN = 5092
+ SYS_UMASK = 5093
+ SYS_GETTIMEOFDAY = 5094
+ SYS_GETRLIMIT = 5095
+ SYS_GETRUSAGE = 5096
+ SYS_SYSINFO = 5097
+ SYS_TIMES = 5098
+ SYS_PTRACE = 5099
+ SYS_GETUID = 5100
+ SYS_SYSLOG = 5101
+ SYS_GETGID = 5102
+ SYS_SETUID = 5103
+ SYS_SETGID = 5104
+ SYS_GETEUID = 5105
+ SYS_GETEGID = 5106
+ SYS_SETPGID = 5107
+ SYS_GETPPID = 5108
+ SYS_GETPGRP = 5109
+ SYS_SETSID = 5110
+ SYS_SETREUID = 5111
+ SYS_SETREGID = 5112
+ SYS_GETGROUPS = 5113
+ SYS_SETGROUPS = 5114
+ SYS_SETRESUID = 5115
+ SYS_GETRESUID = 5116
+ SYS_SETRESGID = 5117
+ SYS_GETRESGID = 5118
+ SYS_GETPGID = 5119
+ SYS_SETFSUID = 5120
+ SYS_SETFSGID = 5121
+ SYS_GETSID = 5122
+ SYS_CAPGET = 5123
+ SYS_CAPSET = 5124
+ SYS_RT_SIGPENDING = 5125
+ SYS_RT_SIGTIMEDWAIT = 5126
+ SYS_RT_SIGQUEUEINFO = 5127
+ SYS_RT_SIGSUSPEND = 5128
+ SYS_SIGALTSTACK = 5129
+ SYS_UTIME = 5130
+ SYS_MKNOD = 5131
+ SYS_PERSONALITY = 5132
+ SYS_USTAT = 5133
+ SYS_STATFS = 5134
+ SYS_FSTATFS = 5135
+ SYS_SYSFS = 5136
+ SYS_GETPRIORITY = 5137
+ SYS_SETPRIORITY = 5138
+ SYS_SCHED_SETPARAM = 5139
+ SYS_SCHED_GETPARAM = 5140
+ SYS_SCHED_SETSCHEDULER = 5141
+ SYS_SCHED_GETSCHEDULER = 5142
+ SYS_SCHED_GET_PRIORITY_MAX = 5143
+ SYS_SCHED_GET_PRIORITY_MIN = 5144
+ SYS_SCHED_RR_GET_INTERVAL = 5145
+ SYS_MLOCK = 5146
+ SYS_MUNLOCK = 5147
+ SYS_MLOCKALL = 5148
+ SYS_MUNLOCKALL = 5149
+ SYS_VHANGUP = 5150
+ SYS_PIVOT_ROOT = 5151
+ SYS__SYSCTL = 5152
+ SYS_PRCTL = 5153
+ SYS_ADJTIMEX = 5154
+ SYS_SETRLIMIT = 5155
+ SYS_CHROOT = 5156
+ SYS_SYNC = 5157
+ SYS_ACCT = 5158
+ SYS_SETTIMEOFDAY = 5159
+ SYS_MOUNT = 5160
+ SYS_UMOUNT2 = 5161
+ SYS_SWAPON = 5162
+ SYS_SWAPOFF = 5163
+ SYS_REBOOT = 5164
+ SYS_SETHOSTNAME = 5165
+ SYS_SETDOMAINNAME = 5166
+ SYS_CREATE_MODULE = 5167
+ SYS_INIT_MODULE = 5168
+ SYS_DELETE_MODULE = 5169
+ SYS_GET_KERNEL_SYMS = 5170
+ SYS_QUERY_MODULE = 5171
+ SYS_QUOTACTL = 5172
+ SYS_NFSSERVCTL = 5173
+ SYS_GETPMSG = 5174
+ SYS_PUTPMSG = 5175
+ SYS_AFS_SYSCALL = 5176
+ SYS_RESERVED177 = 5177
+ SYS_GETTID = 5178
+ SYS_READAHEAD = 5179
+ SYS_SETXATTR = 5180
+ SYS_LSETXATTR = 5181
+ SYS_FSETXATTR = 5182
+ SYS_GETXATTR = 5183
+ SYS_LGETXATTR = 5184
+ SYS_FGETXATTR = 5185
+ SYS_LISTXATTR = 5186
+ SYS_LLISTXATTR = 5187
+ SYS_FLISTXATTR = 5188
+ SYS_REMOVEXATTR = 5189
+ SYS_LREMOVEXATTR = 5190
+ SYS_FREMOVEXATTR = 5191
+ SYS_TKILL = 5192
+ SYS_RESERVED193 = 5193
+ SYS_FUTEX = 5194
+ SYS_SCHED_SETAFFINITY = 5195
+ SYS_SCHED_GETAFFINITY = 5196
+ SYS_CACHEFLUSH = 5197
+ SYS_CACHECTL = 5198
+ SYS_SYSMIPS = 5199
+ SYS_IO_SETUP = 5200
+ SYS_IO_DESTROY = 5201
+ SYS_IO_GETEVENTS = 5202
+ SYS_IO_SUBMIT = 5203
+ SYS_IO_CANCEL = 5204
+ SYS_EXIT_GROUP = 5205
+ SYS_LOOKUP_DCOOKIE = 5206
+ SYS_EPOLL_CREATE = 5207
+ SYS_EPOLL_CTL = 5208
+ SYS_EPOLL_WAIT = 5209
+ SYS_REMAP_FILE_PAGES = 5210
+ SYS_RT_SIGRETURN = 5211
+ SYS_SET_TID_ADDRESS = 5212
+ SYS_RESTART_SYSCALL = 5213
+ SYS_SEMTIMEDOP = 5214
+ SYS_FADVISE64 = 5215
+ SYS_TIMER_CREATE = 5216
+ SYS_TIMER_SETTIME = 5217
+ SYS_TIMER_GETTIME = 5218
+ SYS_TIMER_GETOVERRUN = 5219
+ SYS_TIMER_DELETE = 5220
+ SYS_CLOCK_SETTIME = 5221
+ SYS_CLOCK_GETTIME = 5222
+ SYS_CLOCK_GETRES = 5223
+ SYS_CLOCK_NANOSLEEP = 5224
+ SYS_TGKILL = 5225
+ SYS_UTIMES = 5226
+ SYS_MBIND = 5227
+ SYS_GET_MEMPOLICY = 5228
+ SYS_SET_MEMPOLICY = 5229
+ SYS_MQ_OPEN = 5230
+ SYS_MQ_UNLINK = 5231
+ SYS_MQ_TIMEDSEND = 5232
+ SYS_MQ_TIMEDRECEIVE = 5233
+ SYS_MQ_NOTIFY = 5234
+ SYS_MQ_GETSETATTR = 5235
+ SYS_VSERVER = 5236
+ SYS_WAITID = 5237
+ SYS_ADD_KEY = 5239
+ SYS_REQUEST_KEY = 5240
+ SYS_KEYCTL = 5241
+ SYS_SET_THREAD_AREA = 5242
+ SYS_INOTIFY_INIT = 5243
+ SYS_INOTIFY_ADD_WATCH = 5244
+ SYS_INOTIFY_RM_WATCH = 5245
+ SYS_MIGRATE_PAGES = 5246
+ SYS_OPENAT = 5247
+ SYS_MKDIRAT = 5248
+ SYS_MKNODAT = 5249
+ SYS_FCHOWNAT = 5250
+ SYS_FUTIMESAT = 5251
+ SYS_NEWFSTATAT = 5252
+ SYS_UNLINKAT = 5253
+ SYS_RENAMEAT = 5254
+ SYS_LINKAT = 5255
+ SYS_SYMLINKAT = 5256
+ SYS_READLINKAT = 5257
+ SYS_FCHMODAT = 5258
+ SYS_FACCESSAT = 5259
+ SYS_PSELECT6 = 5260
+ SYS_PPOLL = 5261
+ SYS_UNSHARE = 5262
+ SYS_SPLICE = 5263
+ SYS_SYNC_FILE_RANGE = 5264
+ SYS_TEE = 5265
+ SYS_VMSPLICE = 5266
+ SYS_MOVE_PAGES = 5267
+ SYS_SET_ROBUST_LIST = 5268
+ SYS_GET_ROBUST_LIST = 5269
+ SYS_KEXEC_LOAD = 5270
+ SYS_GETCPU = 5271
+ SYS_EPOLL_PWAIT = 5272
+ SYS_IOPRIO_SET = 5273
+ SYS_IOPRIO_GET = 5274
+ SYS_UTIMENSAT = 5275
+ SYS_SIGNALFD = 5276
+ SYS_TIMERFD = 5277
+ SYS_EVENTFD = 5278
+ SYS_FALLOCATE = 5279
+ SYS_TIMERFD_CREATE = 5280
+ SYS_TIMERFD_GETTIME = 5281
+ SYS_TIMERFD_SETTIME = 5282
+ SYS_SIGNALFD4 = 5283
+ SYS_EVENTFD2 = 5284
+ SYS_EPOLL_CREATE1 = 5285
+ SYS_DUP3 = 5286
+ SYS_PIPE2 = 5287
+ SYS_INOTIFY_INIT1 = 5288
+ SYS_PREADV = 5289
+ SYS_PWRITEV = 5290
+ SYS_RT_TGSIGQUEUEINFO = 5291
+ SYS_PERF_EVENT_OPEN = 5292
+ SYS_ACCEPT4 = 5293
+ SYS_RECVMMSG = 5294
+ SYS_FANOTIFY_INIT = 5295
+ SYS_FANOTIFY_MARK = 5296
+ SYS_PRLIMIT64 = 5297
+ SYS_NAME_TO_HANDLE_AT = 5298
+ SYS_OPEN_BY_HANDLE_AT = 5299
+ SYS_CLOCK_ADJTIME = 5300
+ SYS_SYNCFS = 5301
+ SYS_SENDMMSG = 5302
+ SYS_SETNS = 5303
+ SYS_PROCESS_VM_READV = 5304
+ SYS_PROCESS_VM_WRITEV = 5305
+ SYS_KCMP = 5306
+ SYS_FINIT_MODULE = 5307
+ SYS_GETDENTS64 = 5308
+ SYS_SCHED_SETATTR = 5309
+ SYS_SCHED_GETATTR = 5310
+ SYS_RENAMEAT2 = 5311
+ SYS_SECCOMP = 5312
+ SYS_GETRANDOM = 5313
+ SYS_MEMFD_CREATE = 5314
+ SYS_BPF = 5315
+ SYS_EXECVEAT = 5316
+ SYS_USERFAULTFD = 5317
+ SYS_MEMBARRIER = 5318
+ SYS_MLOCK2 = 5319
+ SYS_COPY_FILE_RANGE = 5320
+ SYS_PREADV2 = 5321
+ SYS_PWRITEV2 = 5322
+ SYS_PKEY_MPROTECT = 5323
+ SYS_PKEY_ALLOC = 5324
+ SYS_PKEY_FREE = 5325
+)
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..82ba20f
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go
@@ -0,0 +1,374 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. 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_KCMP = 4347
+ SYS_FINIT_MODULE = 4348
+ SYS_SCHED_SETATTR = 4349
+ SYS_SCHED_GETATTR = 4350
+ SYS_RENAMEAT2 = 4351
+ SYS_SECCOMP = 4352
+ SYS_GETRANDOM = 4353
+ SYS_MEMFD_CREATE = 4354
+ SYS_BPF = 4355
+ SYS_EXECVEAT = 4356
+ SYS_USERFAULTFD = 4357
+ SYS_MEMBARRIER = 4358
+ SYS_MLOCK2 = 4359
+ SYS_COPY_FILE_RANGE = 4360
+ SYS_PREADV2 = 4361
+ SYS_PWRITEV2 = 4362
+ SYS_PKEY_MPROTECT = 4363
+ SYS_PKEY_ALLOC = 4364
+ SYS_PKEY_FREE = 4365
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go
new file mode 100644
index 0000000..8944448
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go
@@ -0,0 +1,369 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build ppc64,linux
+
+package unix
+
+const (
+ SYS_RESTART_SYSCALL = 0
+ SYS_EXIT = 1
+ SYS_FORK = 2
+ SYS_READ = 3
+ SYS_WRITE = 4
+ SYS_OPEN = 5
+ SYS_CLOSE = 6
+ SYS_WAITPID = 7
+ SYS_CREAT = 8
+ SYS_LINK = 9
+ SYS_UNLINK = 10
+ SYS_EXECVE = 11
+ SYS_CHDIR = 12
+ SYS_TIME = 13
+ SYS_MKNOD = 14
+ SYS_CHMOD = 15
+ SYS_LCHOWN = 16
+ SYS_BREAK = 17
+ SYS_OLDSTAT = 18
+ SYS_LSEEK = 19
+ SYS_GETPID = 20
+ SYS_MOUNT = 21
+ SYS_UMOUNT = 22
+ SYS_SETUID = 23
+ SYS_GETUID = 24
+ SYS_STIME = 25
+ SYS_PTRACE = 26
+ SYS_ALARM = 27
+ SYS_OLDFSTAT = 28
+ SYS_PAUSE = 29
+ SYS_UTIME = 30
+ SYS_STTY = 31
+ SYS_GTTY = 32
+ SYS_ACCESS = 33
+ SYS_NICE = 34
+ SYS_FTIME = 35
+ SYS_SYNC = 36
+ SYS_KILL = 37
+ SYS_RENAME = 38
+ SYS_MKDIR = 39
+ SYS_RMDIR = 40
+ SYS_DUP = 41
+ SYS_PIPE = 42
+ SYS_TIMES = 43
+ SYS_PROF = 44
+ SYS_BRK = 45
+ SYS_SETGID = 46
+ SYS_GETGID = 47
+ SYS_SIGNAL = 48
+ SYS_GETEUID = 49
+ SYS_GETEGID = 50
+ SYS_ACCT = 51
+ SYS_UMOUNT2 = 52
+ SYS_LOCK = 53
+ SYS_IOCTL = 54
+ SYS_FCNTL = 55
+ SYS_MPX = 56
+ SYS_SETPGID = 57
+ SYS_ULIMIT = 58
+ SYS_OLDOLDUNAME = 59
+ SYS_UMASK = 60
+ SYS_CHROOT = 61
+ SYS_USTAT = 62
+ SYS_DUP2 = 63
+ SYS_GETPPID = 64
+ SYS_GETPGRP = 65
+ SYS_SETSID = 66
+ SYS_SIGACTION = 67
+ SYS_SGETMASK = 68
+ SYS_SSETMASK = 69
+ SYS_SETREUID = 70
+ SYS_SETREGID = 71
+ SYS_SIGSUSPEND = 72
+ SYS_SIGPENDING = 73
+ SYS_SETHOSTNAME = 74
+ SYS_SETRLIMIT = 75
+ SYS_GETRLIMIT = 76
+ SYS_GETRUSAGE = 77
+ SYS_GETTIMEOFDAY = 78
+ SYS_SETTIMEOFDAY = 79
+ SYS_GETGROUPS = 80
+ SYS_SETGROUPS = 81
+ SYS_SELECT = 82
+ SYS_SYMLINK = 83
+ SYS_OLDLSTAT = 84
+ SYS_READLINK = 85
+ SYS_USELIB = 86
+ SYS_SWAPON = 87
+ SYS_REBOOT = 88
+ SYS_READDIR = 89
+ SYS_MMAP = 90
+ SYS_MUNMAP = 91
+ SYS_TRUNCATE = 92
+ SYS_FTRUNCATE = 93
+ SYS_FCHMOD = 94
+ SYS_FCHOWN = 95
+ SYS_GETPRIORITY = 96
+ SYS_SETPRIORITY = 97
+ SYS_PROFIL = 98
+ SYS_STATFS = 99
+ SYS_FSTATFS = 100
+ SYS_IOPERM = 101
+ SYS_SOCKETCALL = 102
+ SYS_SYSLOG = 103
+ SYS_SETITIMER = 104
+ SYS_GETITIMER = 105
+ SYS_STAT = 106
+ SYS_LSTAT = 107
+ SYS_FSTAT = 108
+ SYS_OLDUNAME = 109
+ SYS_IOPL = 110
+ SYS_VHANGUP = 111
+ SYS_IDLE = 112
+ SYS_VM86 = 113
+ SYS_WAIT4 = 114
+ SYS_SWAPOFF = 115
+ SYS_SYSINFO = 116
+ SYS_IPC = 117
+ SYS_FSYNC = 118
+ SYS_SIGRETURN = 119
+ SYS_CLONE = 120
+ SYS_SETDOMAINNAME = 121
+ SYS_UNAME = 122
+ SYS_MODIFY_LDT = 123
+ SYS_ADJTIMEX = 124
+ SYS_MPROTECT = 125
+ SYS_SIGPROCMASK = 126
+ SYS_CREATE_MODULE = 127
+ SYS_INIT_MODULE = 128
+ SYS_DELETE_MODULE = 129
+ SYS_GET_KERNEL_SYMS = 130
+ SYS_QUOTACTL = 131
+ SYS_GETPGID = 132
+ SYS_FCHDIR = 133
+ SYS_BDFLUSH = 134
+ SYS_SYSFS = 135
+ SYS_PERSONALITY = 136
+ SYS_AFS_SYSCALL = 137
+ SYS_SETFSUID = 138
+ SYS_SETFSGID = 139
+ SYS__LLSEEK = 140
+ SYS_GETDENTS = 141
+ SYS__NEWSELECT = 142
+ SYS_FLOCK = 143
+ SYS_MSYNC = 144
+ SYS_READV = 145
+ SYS_WRITEV = 146
+ SYS_GETSID = 147
+ SYS_FDATASYNC = 148
+ SYS__SYSCTL = 149
+ SYS_MLOCK = 150
+ SYS_MUNLOCK = 151
+ SYS_MLOCKALL = 152
+ SYS_MUNLOCKALL = 153
+ SYS_SCHED_SETPARAM = 154
+ SYS_SCHED_GETPARAM = 155
+ SYS_SCHED_SETSCHEDULER = 156
+ SYS_SCHED_GETSCHEDULER = 157
+ SYS_SCHED_YIELD = 158
+ SYS_SCHED_GET_PRIORITY_MAX = 159
+ SYS_SCHED_GET_PRIORITY_MIN = 160
+ SYS_SCHED_RR_GET_INTERVAL = 161
+ SYS_NANOSLEEP = 162
+ SYS_MREMAP = 163
+ SYS_SETRESUID = 164
+ SYS_GETRESUID = 165
+ SYS_QUERY_MODULE = 166
+ SYS_POLL = 167
+ SYS_NFSSERVCTL = 168
+ SYS_SETRESGID = 169
+ SYS_GETRESGID = 170
+ SYS_PRCTL = 171
+ SYS_RT_SIGRETURN = 172
+ SYS_RT_SIGACTION = 173
+ SYS_RT_SIGPROCMASK = 174
+ SYS_RT_SIGPENDING = 175
+ SYS_RT_SIGTIMEDWAIT = 176
+ SYS_RT_SIGQUEUEINFO = 177
+ SYS_RT_SIGSUSPEND = 178
+ SYS_PREAD64 = 179
+ SYS_PWRITE64 = 180
+ SYS_CHOWN = 181
+ SYS_GETCWD = 182
+ SYS_CAPGET = 183
+ SYS_CAPSET = 184
+ SYS_SIGALTSTACK = 185
+ SYS_SENDFILE = 186
+ SYS_GETPMSG = 187
+ SYS_PUTPMSG = 188
+ SYS_VFORK = 189
+ SYS_UGETRLIMIT = 190
+ SYS_READAHEAD = 191
+ SYS_PCICONFIG_READ = 198
+ SYS_PCICONFIG_WRITE = 199
+ SYS_PCICONFIG_IOBASE = 200
+ SYS_MULTIPLEXER = 201
+ SYS_GETDENTS64 = 202
+ SYS_PIVOT_ROOT = 203
+ SYS_MADVISE = 205
+ SYS_MINCORE = 206
+ SYS_GETTID = 207
+ SYS_TKILL = 208
+ SYS_SETXATTR = 209
+ SYS_LSETXATTR = 210
+ SYS_FSETXATTR = 211
+ SYS_GETXATTR = 212
+ SYS_LGETXATTR = 213
+ SYS_FGETXATTR = 214
+ SYS_LISTXATTR = 215
+ SYS_LLISTXATTR = 216
+ SYS_FLISTXATTR = 217
+ SYS_REMOVEXATTR = 218
+ SYS_LREMOVEXATTR = 219
+ SYS_FREMOVEXATTR = 220
+ SYS_FUTEX = 221
+ SYS_SCHED_SETAFFINITY = 222
+ SYS_SCHED_GETAFFINITY = 223
+ SYS_TUXCALL = 225
+ SYS_IO_SETUP = 227
+ SYS_IO_DESTROY = 228
+ SYS_IO_GETEVENTS = 229
+ SYS_IO_SUBMIT = 230
+ SYS_IO_CANCEL = 231
+ SYS_SET_TID_ADDRESS = 232
+ SYS_FADVISE64 = 233
+ SYS_EXIT_GROUP = 234
+ SYS_LOOKUP_DCOOKIE = 235
+ SYS_EPOLL_CREATE = 236
+ SYS_EPOLL_CTL = 237
+ SYS_EPOLL_WAIT = 238
+ SYS_REMAP_FILE_PAGES = 239
+ SYS_TIMER_CREATE = 240
+ SYS_TIMER_SETTIME = 241
+ SYS_TIMER_GETTIME = 242
+ SYS_TIMER_GETOVERRUN = 243
+ SYS_TIMER_DELETE = 244
+ SYS_CLOCK_SETTIME = 245
+ SYS_CLOCK_GETTIME = 246
+ SYS_CLOCK_GETRES = 247
+ SYS_CLOCK_NANOSLEEP = 248
+ SYS_SWAPCONTEXT = 249
+ SYS_TGKILL = 250
+ SYS_UTIMES = 251
+ SYS_STATFS64 = 252
+ SYS_FSTATFS64 = 253
+ SYS_RTAS = 255
+ SYS_SYS_DEBUG_SETCONTEXT = 256
+ SYS_MIGRATE_PAGES = 258
+ SYS_MBIND = 259
+ SYS_GET_MEMPOLICY = 260
+ SYS_SET_MEMPOLICY = 261
+ SYS_MQ_OPEN = 262
+ SYS_MQ_UNLINK = 263
+ SYS_MQ_TIMEDSEND = 264
+ SYS_MQ_TIMEDRECEIVE = 265
+ SYS_MQ_NOTIFY = 266
+ SYS_MQ_GETSETATTR = 267
+ SYS_KEXEC_LOAD = 268
+ SYS_ADD_KEY = 269
+ SYS_REQUEST_KEY = 270
+ SYS_KEYCTL = 271
+ SYS_WAITID = 272
+ SYS_IOPRIO_SET = 273
+ SYS_IOPRIO_GET = 274
+ SYS_INOTIFY_INIT = 275
+ SYS_INOTIFY_ADD_WATCH = 276
+ SYS_INOTIFY_RM_WATCH = 277
+ SYS_SPU_RUN = 278
+ SYS_SPU_CREATE = 279
+ SYS_PSELECT6 = 280
+ SYS_PPOLL = 281
+ SYS_UNSHARE = 282
+ SYS_SPLICE = 283
+ SYS_TEE = 284
+ SYS_VMSPLICE = 285
+ SYS_OPENAT = 286
+ SYS_MKDIRAT = 287
+ SYS_MKNODAT = 288
+ SYS_FCHOWNAT = 289
+ SYS_FUTIMESAT = 290
+ SYS_NEWFSTATAT = 291
+ SYS_UNLINKAT = 292
+ SYS_RENAMEAT = 293
+ SYS_LINKAT = 294
+ SYS_SYMLINKAT = 295
+ SYS_READLINKAT = 296
+ SYS_FCHMODAT = 297
+ SYS_FACCESSAT = 298
+ SYS_GET_ROBUST_LIST = 299
+ SYS_SET_ROBUST_LIST = 300
+ SYS_MOVE_PAGES = 301
+ SYS_GETCPU = 302
+ SYS_EPOLL_PWAIT = 303
+ SYS_UTIMENSAT = 304
+ SYS_SIGNALFD = 305
+ SYS_TIMERFD_CREATE = 306
+ SYS_EVENTFD = 307
+ SYS_SYNC_FILE_RANGE2 = 308
+ SYS_FALLOCATE = 309
+ SYS_SUBPAGE_PROT = 310
+ SYS_TIMERFD_SETTIME = 311
+ SYS_TIMERFD_GETTIME = 312
+ SYS_SIGNALFD4 = 313
+ SYS_EVENTFD2 = 314
+ SYS_EPOLL_CREATE1 = 315
+ SYS_DUP3 = 316
+ SYS_PIPE2 = 317
+ SYS_INOTIFY_INIT1 = 318
+ SYS_PERF_EVENT_OPEN = 319
+ SYS_PREADV = 320
+ SYS_PWRITEV = 321
+ SYS_RT_TGSIGQUEUEINFO = 322
+ SYS_FANOTIFY_INIT = 323
+ SYS_FANOTIFY_MARK = 324
+ SYS_PRLIMIT64 = 325
+ SYS_SOCKET = 326
+ SYS_BIND = 327
+ SYS_CONNECT = 328
+ SYS_LISTEN = 329
+ SYS_ACCEPT = 330
+ SYS_GETSOCKNAME = 331
+ SYS_GETPEERNAME = 332
+ SYS_SOCKETPAIR = 333
+ SYS_SEND = 334
+ SYS_SENDTO = 335
+ SYS_RECV = 336
+ SYS_RECVFROM = 337
+ SYS_SHUTDOWN = 338
+ SYS_SETSOCKOPT = 339
+ SYS_GETSOCKOPT = 340
+ SYS_SENDMSG = 341
+ SYS_RECVMSG = 342
+ SYS_RECVMMSG = 343
+ SYS_ACCEPT4 = 344
+ SYS_NAME_TO_HANDLE_AT = 345
+ SYS_OPEN_BY_HANDLE_AT = 346
+ SYS_CLOCK_ADJTIME = 347
+ SYS_SYNCFS = 348
+ SYS_SENDMMSG = 349
+ SYS_SETNS = 350
+ SYS_PROCESS_VM_READV = 351
+ SYS_PROCESS_VM_WRITEV = 352
+ SYS_FINIT_MODULE = 353
+ SYS_KCMP = 354
+ SYS_SCHED_SETATTR = 355
+ SYS_SCHED_GETATTR = 356
+ SYS_RENAMEAT2 = 357
+ SYS_SECCOMP = 358
+ SYS_GETRANDOM = 359
+ SYS_MEMFD_CREATE = 360
+ SYS_BPF = 361
+ SYS_EXECVEAT = 362
+ SYS_SWITCH_ENDIAN = 363
+ SYS_USERFAULTFD = 364
+ SYS_MEMBARRIER = 365
+ SYS_MLOCK2 = 378
+ SYS_COPY_FILE_RANGE = 379
+ SYS_PREADV2 = 380
+ SYS_PWRITEV2 = 381
+ SYS_KEXEC_FILE_LOAD = 382
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go
new file mode 100644
index 0000000..90a039b
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go
@@ -0,0 +1,369 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build ppc64le,linux
+
+package unix
+
+const (
+ SYS_RESTART_SYSCALL = 0
+ SYS_EXIT = 1
+ SYS_FORK = 2
+ SYS_READ = 3
+ SYS_WRITE = 4
+ SYS_OPEN = 5
+ SYS_CLOSE = 6
+ SYS_WAITPID = 7
+ SYS_CREAT = 8
+ SYS_LINK = 9
+ SYS_UNLINK = 10
+ SYS_EXECVE = 11
+ SYS_CHDIR = 12
+ SYS_TIME = 13
+ SYS_MKNOD = 14
+ SYS_CHMOD = 15
+ SYS_LCHOWN = 16
+ SYS_BREAK = 17
+ SYS_OLDSTAT = 18
+ SYS_LSEEK = 19
+ SYS_GETPID = 20
+ SYS_MOUNT = 21
+ SYS_UMOUNT = 22
+ SYS_SETUID = 23
+ SYS_GETUID = 24
+ SYS_STIME = 25
+ SYS_PTRACE = 26
+ SYS_ALARM = 27
+ SYS_OLDFSTAT = 28
+ SYS_PAUSE = 29
+ SYS_UTIME = 30
+ SYS_STTY = 31
+ SYS_GTTY = 32
+ SYS_ACCESS = 33
+ SYS_NICE = 34
+ SYS_FTIME = 35
+ SYS_SYNC = 36
+ SYS_KILL = 37
+ SYS_RENAME = 38
+ SYS_MKDIR = 39
+ SYS_RMDIR = 40
+ SYS_DUP = 41
+ SYS_PIPE = 42
+ SYS_TIMES = 43
+ SYS_PROF = 44
+ SYS_BRK = 45
+ SYS_SETGID = 46
+ SYS_GETGID = 47
+ SYS_SIGNAL = 48
+ SYS_GETEUID = 49
+ SYS_GETEGID = 50
+ SYS_ACCT = 51
+ SYS_UMOUNT2 = 52
+ SYS_LOCK = 53
+ SYS_IOCTL = 54
+ SYS_FCNTL = 55
+ SYS_MPX = 56
+ SYS_SETPGID = 57
+ SYS_ULIMIT = 58
+ SYS_OLDOLDUNAME = 59
+ SYS_UMASK = 60
+ SYS_CHROOT = 61
+ SYS_USTAT = 62
+ SYS_DUP2 = 63
+ SYS_GETPPID = 64
+ SYS_GETPGRP = 65
+ SYS_SETSID = 66
+ SYS_SIGACTION = 67
+ SYS_SGETMASK = 68
+ SYS_SSETMASK = 69
+ SYS_SETREUID = 70
+ SYS_SETREGID = 71
+ SYS_SIGSUSPEND = 72
+ SYS_SIGPENDING = 73
+ SYS_SETHOSTNAME = 74
+ SYS_SETRLIMIT = 75
+ SYS_GETRLIMIT = 76
+ SYS_GETRUSAGE = 77
+ SYS_GETTIMEOFDAY = 78
+ SYS_SETTIMEOFDAY = 79
+ SYS_GETGROUPS = 80
+ SYS_SETGROUPS = 81
+ SYS_SELECT = 82
+ SYS_SYMLINK = 83
+ SYS_OLDLSTAT = 84
+ SYS_READLINK = 85
+ SYS_USELIB = 86
+ SYS_SWAPON = 87
+ SYS_REBOOT = 88
+ SYS_READDIR = 89
+ SYS_MMAP = 90
+ SYS_MUNMAP = 91
+ SYS_TRUNCATE = 92
+ SYS_FTRUNCATE = 93
+ SYS_FCHMOD = 94
+ SYS_FCHOWN = 95
+ SYS_GETPRIORITY = 96
+ SYS_SETPRIORITY = 97
+ SYS_PROFIL = 98
+ SYS_STATFS = 99
+ SYS_FSTATFS = 100
+ SYS_IOPERM = 101
+ SYS_SOCKETCALL = 102
+ SYS_SYSLOG = 103
+ SYS_SETITIMER = 104
+ SYS_GETITIMER = 105
+ SYS_STAT = 106
+ SYS_LSTAT = 107
+ SYS_FSTAT = 108
+ SYS_OLDUNAME = 109
+ SYS_IOPL = 110
+ SYS_VHANGUP = 111
+ SYS_IDLE = 112
+ SYS_VM86 = 113
+ SYS_WAIT4 = 114
+ SYS_SWAPOFF = 115
+ SYS_SYSINFO = 116
+ SYS_IPC = 117
+ SYS_FSYNC = 118
+ SYS_SIGRETURN = 119
+ SYS_CLONE = 120
+ SYS_SETDOMAINNAME = 121
+ SYS_UNAME = 122
+ SYS_MODIFY_LDT = 123
+ SYS_ADJTIMEX = 124
+ SYS_MPROTECT = 125
+ SYS_SIGPROCMASK = 126
+ SYS_CREATE_MODULE = 127
+ SYS_INIT_MODULE = 128
+ SYS_DELETE_MODULE = 129
+ SYS_GET_KERNEL_SYMS = 130
+ SYS_QUOTACTL = 131
+ SYS_GETPGID = 132
+ SYS_FCHDIR = 133
+ SYS_BDFLUSH = 134
+ SYS_SYSFS = 135
+ SYS_PERSONALITY = 136
+ SYS_AFS_SYSCALL = 137
+ SYS_SETFSUID = 138
+ SYS_SETFSGID = 139
+ SYS__LLSEEK = 140
+ SYS_GETDENTS = 141
+ SYS__NEWSELECT = 142
+ SYS_FLOCK = 143
+ SYS_MSYNC = 144
+ SYS_READV = 145
+ SYS_WRITEV = 146
+ SYS_GETSID = 147
+ SYS_FDATASYNC = 148
+ SYS__SYSCTL = 149
+ SYS_MLOCK = 150
+ SYS_MUNLOCK = 151
+ SYS_MLOCKALL = 152
+ SYS_MUNLOCKALL = 153
+ SYS_SCHED_SETPARAM = 154
+ SYS_SCHED_GETPARAM = 155
+ SYS_SCHED_SETSCHEDULER = 156
+ SYS_SCHED_GETSCHEDULER = 157
+ SYS_SCHED_YIELD = 158
+ SYS_SCHED_GET_PRIORITY_MAX = 159
+ SYS_SCHED_GET_PRIORITY_MIN = 160
+ SYS_SCHED_RR_GET_INTERVAL = 161
+ SYS_NANOSLEEP = 162
+ SYS_MREMAP = 163
+ SYS_SETRESUID = 164
+ SYS_GETRESUID = 165
+ SYS_QUERY_MODULE = 166
+ SYS_POLL = 167
+ SYS_NFSSERVCTL = 168
+ SYS_SETRESGID = 169
+ SYS_GETRESGID = 170
+ SYS_PRCTL = 171
+ SYS_RT_SIGRETURN = 172
+ SYS_RT_SIGACTION = 173
+ SYS_RT_SIGPROCMASK = 174
+ SYS_RT_SIGPENDING = 175
+ SYS_RT_SIGTIMEDWAIT = 176
+ SYS_RT_SIGQUEUEINFO = 177
+ SYS_RT_SIGSUSPEND = 178
+ SYS_PREAD64 = 179
+ SYS_PWRITE64 = 180
+ SYS_CHOWN = 181
+ SYS_GETCWD = 182
+ SYS_CAPGET = 183
+ SYS_CAPSET = 184
+ SYS_SIGALTSTACK = 185
+ SYS_SENDFILE = 186
+ SYS_GETPMSG = 187
+ SYS_PUTPMSG = 188
+ SYS_VFORK = 189
+ SYS_UGETRLIMIT = 190
+ SYS_READAHEAD = 191
+ SYS_PCICONFIG_READ = 198
+ SYS_PCICONFIG_WRITE = 199
+ SYS_PCICONFIG_IOBASE = 200
+ SYS_MULTIPLEXER = 201
+ SYS_GETDENTS64 = 202
+ SYS_PIVOT_ROOT = 203
+ SYS_MADVISE = 205
+ SYS_MINCORE = 206
+ SYS_GETTID = 207
+ SYS_TKILL = 208
+ SYS_SETXATTR = 209
+ SYS_LSETXATTR = 210
+ SYS_FSETXATTR = 211
+ SYS_GETXATTR = 212
+ SYS_LGETXATTR = 213
+ SYS_FGETXATTR = 214
+ SYS_LISTXATTR = 215
+ SYS_LLISTXATTR = 216
+ SYS_FLISTXATTR = 217
+ SYS_REMOVEXATTR = 218
+ SYS_LREMOVEXATTR = 219
+ SYS_FREMOVEXATTR = 220
+ SYS_FUTEX = 221
+ SYS_SCHED_SETAFFINITY = 222
+ SYS_SCHED_GETAFFINITY = 223
+ SYS_TUXCALL = 225
+ SYS_IO_SETUP = 227
+ SYS_IO_DESTROY = 228
+ SYS_IO_GETEVENTS = 229
+ SYS_IO_SUBMIT = 230
+ SYS_IO_CANCEL = 231
+ SYS_SET_TID_ADDRESS = 232
+ SYS_FADVISE64 = 233
+ SYS_EXIT_GROUP = 234
+ SYS_LOOKUP_DCOOKIE = 235
+ SYS_EPOLL_CREATE = 236
+ SYS_EPOLL_CTL = 237
+ SYS_EPOLL_WAIT = 238
+ SYS_REMAP_FILE_PAGES = 239
+ SYS_TIMER_CREATE = 240
+ SYS_TIMER_SETTIME = 241
+ SYS_TIMER_GETTIME = 242
+ SYS_TIMER_GETOVERRUN = 243
+ SYS_TIMER_DELETE = 244
+ SYS_CLOCK_SETTIME = 245
+ SYS_CLOCK_GETTIME = 246
+ SYS_CLOCK_GETRES = 247
+ SYS_CLOCK_NANOSLEEP = 248
+ SYS_SWAPCONTEXT = 249
+ SYS_TGKILL = 250
+ SYS_UTIMES = 251
+ SYS_STATFS64 = 252
+ SYS_FSTATFS64 = 253
+ SYS_RTAS = 255
+ SYS_SYS_DEBUG_SETCONTEXT = 256
+ SYS_MIGRATE_PAGES = 258
+ SYS_MBIND = 259
+ SYS_GET_MEMPOLICY = 260
+ SYS_SET_MEMPOLICY = 261
+ SYS_MQ_OPEN = 262
+ SYS_MQ_UNLINK = 263
+ SYS_MQ_TIMEDSEND = 264
+ SYS_MQ_TIMEDRECEIVE = 265
+ SYS_MQ_NOTIFY = 266
+ SYS_MQ_GETSETATTR = 267
+ SYS_KEXEC_LOAD = 268
+ SYS_ADD_KEY = 269
+ SYS_REQUEST_KEY = 270
+ SYS_KEYCTL = 271
+ SYS_WAITID = 272
+ SYS_IOPRIO_SET = 273
+ SYS_IOPRIO_GET = 274
+ SYS_INOTIFY_INIT = 275
+ SYS_INOTIFY_ADD_WATCH = 276
+ SYS_INOTIFY_RM_WATCH = 277
+ SYS_SPU_RUN = 278
+ SYS_SPU_CREATE = 279
+ SYS_PSELECT6 = 280
+ SYS_PPOLL = 281
+ SYS_UNSHARE = 282
+ SYS_SPLICE = 283
+ SYS_TEE = 284
+ SYS_VMSPLICE = 285
+ SYS_OPENAT = 286
+ SYS_MKDIRAT = 287
+ SYS_MKNODAT = 288
+ SYS_FCHOWNAT = 289
+ SYS_FUTIMESAT = 290
+ SYS_NEWFSTATAT = 291
+ SYS_UNLINKAT = 292
+ SYS_RENAMEAT = 293
+ SYS_LINKAT = 294
+ SYS_SYMLINKAT = 295
+ SYS_READLINKAT = 296
+ SYS_FCHMODAT = 297
+ SYS_FACCESSAT = 298
+ SYS_GET_ROBUST_LIST = 299
+ SYS_SET_ROBUST_LIST = 300
+ SYS_MOVE_PAGES = 301
+ SYS_GETCPU = 302
+ SYS_EPOLL_PWAIT = 303
+ SYS_UTIMENSAT = 304
+ SYS_SIGNALFD = 305
+ SYS_TIMERFD_CREATE = 306
+ SYS_EVENTFD = 307
+ SYS_SYNC_FILE_RANGE2 = 308
+ SYS_FALLOCATE = 309
+ SYS_SUBPAGE_PROT = 310
+ SYS_TIMERFD_SETTIME = 311
+ SYS_TIMERFD_GETTIME = 312
+ SYS_SIGNALFD4 = 313
+ SYS_EVENTFD2 = 314
+ SYS_EPOLL_CREATE1 = 315
+ SYS_DUP3 = 316
+ SYS_PIPE2 = 317
+ SYS_INOTIFY_INIT1 = 318
+ SYS_PERF_EVENT_OPEN = 319
+ SYS_PREADV = 320
+ SYS_PWRITEV = 321
+ SYS_RT_TGSIGQUEUEINFO = 322
+ SYS_FANOTIFY_INIT = 323
+ SYS_FANOTIFY_MARK = 324
+ SYS_PRLIMIT64 = 325
+ SYS_SOCKET = 326
+ SYS_BIND = 327
+ SYS_CONNECT = 328
+ SYS_LISTEN = 329
+ SYS_ACCEPT = 330
+ SYS_GETSOCKNAME = 331
+ SYS_GETPEERNAME = 332
+ SYS_SOCKETPAIR = 333
+ SYS_SEND = 334
+ SYS_SENDTO = 335
+ SYS_RECV = 336
+ SYS_RECVFROM = 337
+ SYS_SHUTDOWN = 338
+ SYS_SETSOCKOPT = 339
+ SYS_GETSOCKOPT = 340
+ SYS_SENDMSG = 341
+ SYS_RECVMSG = 342
+ SYS_RECVMMSG = 343
+ SYS_ACCEPT4 = 344
+ SYS_NAME_TO_HANDLE_AT = 345
+ SYS_OPEN_BY_HANDLE_AT = 346
+ SYS_CLOCK_ADJTIME = 347
+ SYS_SYNCFS = 348
+ SYS_SENDMMSG = 349
+ SYS_SETNS = 350
+ SYS_PROCESS_VM_READV = 351
+ SYS_PROCESS_VM_WRITEV = 352
+ SYS_FINIT_MODULE = 353
+ SYS_KCMP = 354
+ SYS_SCHED_SETATTR = 355
+ SYS_SCHED_GETATTR = 356
+ SYS_RENAMEAT2 = 357
+ SYS_SECCOMP = 358
+ SYS_GETRANDOM = 359
+ SYS_MEMFD_CREATE = 360
+ SYS_BPF = 361
+ SYS_EXECVEAT = 362
+ SYS_SWITCH_ENDIAN = 363
+ SYS_USERFAULTFD = 364
+ SYS_MEMBARRIER = 365
+ SYS_MLOCK2 = 378
+ SYS_COPY_FILE_RANGE = 379
+ SYS_PREADV2 = 380
+ SYS_PWRITEV2 = 381
+ SYS_KEXEC_FILE_LOAD = 382
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go
new file mode 100644
index 0000000..aab0cdb
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go
@@ -0,0 +1,331 @@
+// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include -fsigned-char /tmp/include/asm/unistd.h
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build s390x,linux
+
+package unix
+
+const (
+ SYS_EXIT = 1
+ SYS_FORK = 2
+ SYS_READ = 3
+ SYS_WRITE = 4
+ SYS_OPEN = 5
+ SYS_CLOSE = 6
+ SYS_RESTART_SYSCALL = 7
+ SYS_CREAT = 8
+ SYS_LINK = 9
+ SYS_UNLINK = 10
+ SYS_EXECVE = 11
+ SYS_CHDIR = 12
+ SYS_MKNOD = 14
+ SYS_CHMOD = 15
+ SYS_LSEEK = 19
+ SYS_GETPID = 20
+ SYS_MOUNT = 21
+ SYS_UMOUNT = 22
+ SYS_PTRACE = 26
+ SYS_ALARM = 27
+ SYS_PAUSE = 29
+ SYS_UTIME = 30
+ SYS_ACCESS = 33
+ SYS_NICE = 34
+ SYS_SYNC = 36
+ SYS_KILL = 37
+ SYS_RENAME = 38
+ SYS_MKDIR = 39
+ SYS_RMDIR = 40
+ SYS_DUP = 41
+ SYS_PIPE = 42
+ SYS_TIMES = 43
+ SYS_BRK = 45
+ SYS_SIGNAL = 48
+ SYS_ACCT = 51
+ SYS_UMOUNT2 = 52
+ SYS_IOCTL = 54
+ SYS_FCNTL = 55
+ SYS_SETPGID = 57
+ SYS_UMASK = 60
+ SYS_CHROOT = 61
+ SYS_USTAT = 62
+ SYS_DUP2 = 63
+ SYS_GETPPID = 64
+ SYS_GETPGRP = 65
+ SYS_SETSID = 66
+ SYS_SIGACTION = 67
+ SYS_SIGSUSPEND = 72
+ SYS_SIGPENDING = 73
+ SYS_SETHOSTNAME = 74
+ SYS_SETRLIMIT = 75
+ SYS_GETRUSAGE = 77
+ SYS_GETTIMEOFDAY = 78
+ SYS_SETTIMEOFDAY = 79
+ SYS_SYMLINK = 83
+ SYS_READLINK = 85
+ SYS_USELIB = 86
+ SYS_SWAPON = 87
+ SYS_REBOOT = 88
+ SYS_READDIR = 89
+ SYS_MMAP = 90
+ SYS_MUNMAP = 91
+ SYS_TRUNCATE = 92
+ SYS_FTRUNCATE = 93
+ SYS_FCHMOD = 94
+ SYS_GETPRIORITY = 96
+ SYS_SETPRIORITY = 97
+ SYS_STATFS = 99
+ SYS_FSTATFS = 100
+ SYS_SOCKETCALL = 102
+ SYS_SYSLOG = 103
+ SYS_SETITIMER = 104
+ SYS_GETITIMER = 105
+ SYS_STAT = 106
+ SYS_LSTAT = 107
+ SYS_FSTAT = 108
+ SYS_LOOKUP_DCOOKIE = 110
+ SYS_VHANGUP = 111
+ SYS_IDLE = 112
+ SYS_WAIT4 = 114
+ SYS_SWAPOFF = 115
+ SYS_SYSINFO = 116
+ SYS_IPC = 117
+ SYS_FSYNC = 118
+ SYS_SIGRETURN = 119
+ SYS_CLONE = 120
+ SYS_SETDOMAINNAME = 121
+ SYS_UNAME = 122
+ SYS_ADJTIMEX = 124
+ SYS_MPROTECT = 125
+ SYS_SIGPROCMASK = 126
+ SYS_CREATE_MODULE = 127
+ SYS_INIT_MODULE = 128
+ SYS_DELETE_MODULE = 129
+ SYS_GET_KERNEL_SYMS = 130
+ SYS_QUOTACTL = 131
+ SYS_GETPGID = 132
+ SYS_FCHDIR = 133
+ SYS_BDFLUSH = 134
+ SYS_SYSFS = 135
+ SYS_PERSONALITY = 136
+ SYS_AFS_SYSCALL = 137
+ SYS_GETDENTS = 141
+ SYS_FLOCK = 143
+ SYS_MSYNC = 144
+ SYS_READV = 145
+ SYS_WRITEV = 146
+ SYS_GETSID = 147
+ SYS_FDATASYNC = 148
+ SYS__SYSCTL = 149
+ SYS_MLOCK = 150
+ SYS_MUNLOCK = 151
+ SYS_MLOCKALL = 152
+ SYS_MUNLOCKALL = 153
+ SYS_SCHED_SETPARAM = 154
+ SYS_SCHED_GETPARAM = 155
+ SYS_SCHED_SETSCHEDULER = 156
+ SYS_SCHED_GETSCHEDULER = 157
+ SYS_SCHED_YIELD = 158
+ SYS_SCHED_GET_PRIORITY_MAX = 159
+ SYS_SCHED_GET_PRIORITY_MIN = 160
+ SYS_SCHED_RR_GET_INTERVAL = 161
+ SYS_NANOSLEEP = 162
+ SYS_MREMAP = 163
+ SYS_QUERY_MODULE = 167
+ SYS_POLL = 168
+ SYS_NFSSERVCTL = 169
+ SYS_PRCTL = 172
+ SYS_RT_SIGRETURN = 173
+ SYS_RT_SIGACTION = 174
+ SYS_RT_SIGPROCMASK = 175
+ SYS_RT_SIGPENDING = 176
+ SYS_RT_SIGTIMEDWAIT = 177
+ SYS_RT_SIGQUEUEINFO = 178
+ SYS_RT_SIGSUSPEND = 179
+ SYS_PREAD64 = 180
+ SYS_PWRITE64 = 181
+ SYS_GETCWD = 183
+ SYS_CAPGET = 184
+ SYS_CAPSET = 185
+ SYS_SIGALTSTACK = 186
+ SYS_SENDFILE = 187
+ SYS_GETPMSG = 188
+ SYS_PUTPMSG = 189
+ SYS_VFORK = 190
+ SYS_PIVOT_ROOT = 217
+ SYS_MINCORE = 218
+ SYS_MADVISE = 219
+ SYS_GETDENTS64 = 220
+ SYS_READAHEAD = 222
+ SYS_SETXATTR = 224
+ SYS_LSETXATTR = 225
+ SYS_FSETXATTR = 226
+ SYS_GETXATTR = 227
+ SYS_LGETXATTR = 228
+ SYS_FGETXATTR = 229
+ SYS_LISTXATTR = 230
+ SYS_LLISTXATTR = 231
+ SYS_FLISTXATTR = 232
+ SYS_REMOVEXATTR = 233
+ SYS_LREMOVEXATTR = 234
+ SYS_FREMOVEXATTR = 235
+ SYS_GETTID = 236
+ SYS_TKILL = 237
+ SYS_FUTEX = 238
+ SYS_SCHED_SETAFFINITY = 239
+ SYS_SCHED_GETAFFINITY = 240
+ SYS_TGKILL = 241
+ SYS_IO_SETUP = 243
+ SYS_IO_DESTROY = 244
+ SYS_IO_GETEVENTS = 245
+ SYS_IO_SUBMIT = 246
+ SYS_IO_CANCEL = 247
+ SYS_EXIT_GROUP = 248
+ SYS_EPOLL_CREATE = 249
+ SYS_EPOLL_CTL = 250
+ SYS_EPOLL_WAIT = 251
+ SYS_SET_TID_ADDRESS = 252
+ SYS_FADVISE64 = 253
+ SYS_TIMER_CREATE = 254
+ SYS_TIMER_SETTIME = 255
+ SYS_TIMER_GETTIME = 256
+ SYS_TIMER_GETOVERRUN = 257
+ SYS_TIMER_DELETE = 258
+ SYS_CLOCK_SETTIME = 259
+ SYS_CLOCK_GETTIME = 260
+ SYS_CLOCK_GETRES = 261
+ SYS_CLOCK_NANOSLEEP = 262
+ SYS_STATFS64 = 265
+ SYS_FSTATFS64 = 266
+ SYS_REMAP_FILE_PAGES = 267
+ SYS_MBIND = 268
+ SYS_GET_MEMPOLICY = 269
+ SYS_SET_MEMPOLICY = 270
+ SYS_MQ_OPEN = 271
+ SYS_MQ_UNLINK = 272
+ SYS_MQ_TIMEDSEND = 273
+ SYS_MQ_TIMEDRECEIVE = 274
+ SYS_MQ_NOTIFY = 275
+ SYS_MQ_GETSETATTR = 276
+ SYS_KEXEC_LOAD = 277
+ SYS_ADD_KEY = 278
+ SYS_REQUEST_KEY = 279
+ SYS_KEYCTL = 280
+ SYS_WAITID = 281
+ SYS_IOPRIO_SET = 282
+ SYS_IOPRIO_GET = 283
+ SYS_INOTIFY_INIT = 284
+ SYS_INOTIFY_ADD_WATCH = 285
+ SYS_INOTIFY_RM_WATCH = 286
+ SYS_MIGRATE_PAGES = 287
+ SYS_OPENAT = 288
+ SYS_MKDIRAT = 289
+ SYS_MKNODAT = 290
+ SYS_FCHOWNAT = 291
+ SYS_FUTIMESAT = 292
+ SYS_UNLINKAT = 294
+ SYS_RENAMEAT = 295
+ SYS_LINKAT = 296
+ SYS_SYMLINKAT = 297
+ SYS_READLINKAT = 298
+ SYS_FCHMODAT = 299
+ SYS_FACCESSAT = 300
+ SYS_PSELECT6 = 301
+ SYS_PPOLL = 302
+ SYS_UNSHARE = 303
+ SYS_SET_ROBUST_LIST = 304
+ SYS_GET_ROBUST_LIST = 305
+ SYS_SPLICE = 306
+ SYS_SYNC_FILE_RANGE = 307
+ SYS_TEE = 308
+ SYS_VMSPLICE = 309
+ SYS_MOVE_PAGES = 310
+ SYS_GETCPU = 311
+ SYS_EPOLL_PWAIT = 312
+ SYS_UTIMES = 313
+ SYS_FALLOCATE = 314
+ SYS_UTIMENSAT = 315
+ SYS_SIGNALFD = 316
+ SYS_TIMERFD = 317
+ SYS_EVENTFD = 318
+ SYS_TIMERFD_CREATE = 319
+ SYS_TIMERFD_SETTIME = 320
+ SYS_TIMERFD_GETTIME = 321
+ SYS_SIGNALFD4 = 322
+ SYS_EVENTFD2 = 323
+ SYS_INOTIFY_INIT1 = 324
+ SYS_PIPE2 = 325
+ SYS_DUP3 = 326
+ SYS_EPOLL_CREATE1 = 327
+ SYS_PREADV = 328
+ SYS_PWRITEV = 329
+ SYS_RT_TGSIGQUEUEINFO = 330
+ SYS_PERF_EVENT_OPEN = 331
+ SYS_FANOTIFY_INIT = 332
+ SYS_FANOTIFY_MARK = 333
+ SYS_PRLIMIT64 = 334
+ SYS_NAME_TO_HANDLE_AT = 335
+ SYS_OPEN_BY_HANDLE_AT = 336
+ SYS_CLOCK_ADJTIME = 337
+ SYS_SYNCFS = 338
+ SYS_SETNS = 339
+ SYS_PROCESS_VM_READV = 340
+ SYS_PROCESS_VM_WRITEV = 341
+ SYS_S390_RUNTIME_INSTR = 342
+ SYS_KCMP = 343
+ SYS_FINIT_MODULE = 344
+ SYS_SCHED_SETATTR = 345
+ SYS_SCHED_GETATTR = 346
+ SYS_RENAMEAT2 = 347
+ SYS_SECCOMP = 348
+ SYS_GETRANDOM = 349
+ SYS_MEMFD_CREATE = 350
+ SYS_BPF = 351
+ SYS_S390_PCI_MMIO_WRITE = 352
+ SYS_S390_PCI_MMIO_READ = 353
+ SYS_EXECVEAT = 354
+ SYS_USERFAULTFD = 355
+ SYS_MEMBARRIER = 356
+ SYS_RECVMMSG = 357
+ SYS_SENDMMSG = 358
+ SYS_SOCKET = 359
+ SYS_SOCKETPAIR = 360
+ SYS_BIND = 361
+ SYS_CONNECT = 362
+ SYS_LISTEN = 363
+ SYS_ACCEPT4 = 364
+ SYS_GETSOCKOPT = 365
+ SYS_SETSOCKOPT = 366
+ SYS_GETSOCKNAME = 367
+ SYS_GETPEERNAME = 368
+ SYS_SENDTO = 369
+ SYS_SENDMSG = 370
+ SYS_RECVFROM = 371
+ SYS_RECVMSG = 372
+ SYS_SHUTDOWN = 373
+ SYS_MLOCK2 = 374
+ SYS_COPY_FILE_RANGE = 375
+ SYS_PREADV2 = 376
+ SYS_PWRITEV2 = 377
+ SYS_SELECT = 142
+ SYS_GETRLIMIT = 191
+ SYS_LCHOWN = 198
+ SYS_GETUID = 199
+ SYS_GETGID = 200
+ SYS_GETEUID = 201
+ SYS_GETEGID = 202
+ SYS_SETREUID = 203
+ SYS_SETREGID = 204
+ SYS_GETGROUPS = 205
+ SYS_SETGROUPS = 206
+ SYS_FCHOWN = 207
+ SYS_SETRESUID = 208
+ SYS_GETRESUID = 209
+ SYS_SETRESGID = 210
+ SYS_GETRESGID = 211
+ SYS_CHOWN = 212
+ SYS_SETUID = 213
+ SYS_SETGID = 214
+ SYS_SETFSUID = 215
+ SYS_SETFSGID = 216
+ SYS_NEWFSTATAT = 293
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go
new file mode 100644
index 0000000..c9c129d
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go
@@ -0,0 +1,348 @@
+// mksysnum_linux.pl -Ilinux/usr/include -m64 -D__arch64__ linux/usr/include/asm/unistd.h
+// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT
+
+// +build sparc64,linux
+
+package unix
+
+const (
+ SYS_RESTART_SYSCALL = 0
+ SYS_EXIT = 1
+ SYS_FORK = 2
+ SYS_READ = 3
+ SYS_WRITE = 4
+ SYS_OPEN = 5
+ SYS_CLOSE = 6
+ SYS_WAIT4 = 7
+ SYS_CREAT = 8
+ SYS_LINK = 9
+ SYS_UNLINK = 10
+ SYS_EXECV = 11
+ SYS_CHDIR = 12
+ SYS_CHOWN = 13
+ SYS_MKNOD = 14
+ SYS_CHMOD = 15
+ SYS_LCHOWN = 16
+ SYS_BRK = 17
+ SYS_PERFCTR = 18
+ SYS_LSEEK = 19
+ SYS_GETPID = 20
+ SYS_CAPGET = 21
+ SYS_CAPSET = 22
+ SYS_SETUID = 23
+ SYS_GETUID = 24
+ SYS_VMSPLICE = 25
+ SYS_PTRACE = 26
+ SYS_ALARM = 27
+ SYS_SIGALTSTACK = 28
+ SYS_PAUSE = 29
+ SYS_UTIME = 30
+ SYS_ACCESS = 33
+ SYS_NICE = 34
+ SYS_SYNC = 36
+ SYS_KILL = 37
+ SYS_STAT = 38
+ SYS_SENDFILE = 39
+ SYS_LSTAT = 40
+ SYS_DUP = 41
+ SYS_PIPE = 42
+ SYS_TIMES = 43
+ SYS_UMOUNT2 = 45
+ SYS_SETGID = 46
+ SYS_GETGID = 47
+ SYS_SIGNAL = 48
+ SYS_GETEUID = 49
+ SYS_GETEGID = 50
+ SYS_ACCT = 51
+ SYS_MEMORY_ORDERING = 52
+ SYS_IOCTL = 54
+ SYS_REBOOT = 55
+ SYS_SYMLINK = 57
+ SYS_READLINK = 58
+ SYS_EXECVE = 59
+ SYS_UMASK = 60
+ SYS_CHROOT = 61
+ SYS_FSTAT = 62
+ SYS_FSTAT64 = 63
+ SYS_GETPAGESIZE = 64
+ SYS_MSYNC = 65
+ SYS_VFORK = 66
+ SYS_PREAD64 = 67
+ SYS_PWRITE64 = 68
+ SYS_MMAP = 71
+ SYS_MUNMAP = 73
+ SYS_MPROTECT = 74
+ SYS_MADVISE = 75
+ SYS_VHANGUP = 76
+ SYS_MINCORE = 78
+ SYS_GETGROUPS = 79
+ SYS_SETGROUPS = 80
+ SYS_GETPGRP = 81
+ SYS_SETITIMER = 83
+ SYS_SWAPON = 85
+ SYS_GETITIMER = 86
+ SYS_SETHOSTNAME = 88
+ SYS_DUP2 = 90
+ SYS_FCNTL = 92
+ SYS_SELECT = 93
+ SYS_FSYNC = 95
+ SYS_SETPRIORITY = 96
+ SYS_SOCKET = 97
+ SYS_CONNECT = 98
+ SYS_ACCEPT = 99
+ SYS_GETPRIORITY = 100
+ SYS_RT_SIGRETURN = 101
+ SYS_RT_SIGACTION = 102
+ SYS_RT_SIGPROCMASK = 103
+ SYS_RT_SIGPENDING = 104
+ SYS_RT_SIGTIMEDWAIT = 105
+ SYS_RT_SIGQUEUEINFO = 106
+ SYS_RT_SIGSUSPEND = 107
+ SYS_SETRESUID = 108
+ SYS_GETRESUID = 109
+ SYS_SETRESGID = 110
+ SYS_GETRESGID = 111
+ SYS_RECVMSG = 113
+ SYS_SENDMSG = 114
+ SYS_GETTIMEOFDAY = 116
+ SYS_GETRUSAGE = 117
+ SYS_GETSOCKOPT = 118
+ SYS_GETCWD = 119
+ SYS_READV = 120
+ SYS_WRITEV = 121
+ SYS_SETTIMEOFDAY = 122
+ SYS_FCHOWN = 123
+ SYS_FCHMOD = 124
+ SYS_RECVFROM = 125
+ SYS_SETREUID = 126
+ SYS_SETREGID = 127
+ SYS_RENAME = 128
+ SYS_TRUNCATE = 129
+ SYS_FTRUNCATE = 130
+ SYS_FLOCK = 131
+ SYS_LSTAT64 = 132
+ SYS_SENDTO = 133
+ SYS_SHUTDOWN = 134
+ SYS_SOCKETPAIR = 135
+ SYS_MKDIR = 136
+ SYS_RMDIR = 137
+ SYS_UTIMES = 138
+ SYS_STAT64 = 139
+ SYS_SENDFILE64 = 140
+ SYS_GETPEERNAME = 141
+ SYS_FUTEX = 142
+ SYS_GETTID = 143
+ SYS_GETRLIMIT = 144
+ SYS_SETRLIMIT = 145
+ SYS_PIVOT_ROOT = 146
+ SYS_PRCTL = 147
+ SYS_PCICONFIG_READ = 148
+ SYS_PCICONFIG_WRITE = 149
+ SYS_GETSOCKNAME = 150
+ SYS_INOTIFY_INIT = 151
+ SYS_INOTIFY_ADD_WATCH = 152
+ SYS_POLL = 153
+ SYS_GETDENTS64 = 154
+ SYS_INOTIFY_RM_WATCH = 156
+ SYS_STATFS = 157
+ SYS_FSTATFS = 158
+ SYS_UMOUNT = 159
+ SYS_SCHED_SET_AFFINITY = 160
+ SYS_SCHED_GET_AFFINITY = 161
+ SYS_GETDOMAINNAME = 162
+ SYS_SETDOMAINNAME = 163
+ SYS_UTRAP_INSTALL = 164
+ SYS_QUOTACTL = 165
+ SYS_SET_TID_ADDRESS = 166
+ SYS_MOUNT = 167
+ SYS_USTAT = 168
+ SYS_SETXATTR = 169
+ SYS_LSETXATTR = 170
+ SYS_FSETXATTR = 171
+ SYS_GETXATTR = 172
+ SYS_LGETXATTR = 173
+ SYS_GETDENTS = 174
+ SYS_SETSID = 175
+ SYS_FCHDIR = 176
+ SYS_FGETXATTR = 177
+ SYS_LISTXATTR = 178
+ SYS_LLISTXATTR = 179
+ SYS_FLISTXATTR = 180
+ SYS_REMOVEXATTR = 181
+ SYS_LREMOVEXATTR = 182
+ SYS_SIGPENDING = 183
+ SYS_QUERY_MODULE = 184
+ SYS_SETPGID = 185
+ SYS_FREMOVEXATTR = 186
+ SYS_TKILL = 187
+ SYS_EXIT_GROUP = 188
+ SYS_UNAME = 189
+ SYS_INIT_MODULE = 190
+ SYS_PERSONALITY = 191
+ SYS_REMAP_FILE_PAGES = 192
+ SYS_EPOLL_CREATE = 193
+ SYS_EPOLL_CTL = 194
+ SYS_EPOLL_WAIT = 195
+ SYS_IOPRIO_SET = 196
+ SYS_GETPPID = 197
+ SYS_SIGACTION = 198
+ SYS_SGETMASK = 199
+ SYS_SSETMASK = 200
+ SYS_SIGSUSPEND = 201
+ SYS_OLDLSTAT = 202
+ SYS_USELIB = 203
+ SYS_READDIR = 204
+ SYS_READAHEAD = 205
+ SYS_SOCKETCALL = 206
+ SYS_SYSLOG = 207
+ SYS_LOOKUP_DCOOKIE = 208
+ SYS_FADVISE64 = 209
+ SYS_FADVISE64_64 = 210
+ SYS_TGKILL = 211
+ SYS_WAITPID = 212
+ SYS_SWAPOFF = 213
+ SYS_SYSINFO = 214
+ SYS_IPC = 215
+ SYS_SIGRETURN = 216
+ SYS_CLONE = 217
+ SYS_IOPRIO_GET = 218
+ SYS_ADJTIMEX = 219
+ SYS_SIGPROCMASK = 220
+ SYS_CREATE_MODULE = 221
+ SYS_DELETE_MODULE = 222
+ SYS_GET_KERNEL_SYMS = 223
+ SYS_GETPGID = 224
+ SYS_BDFLUSH = 225
+ SYS_SYSFS = 226
+ SYS_AFS_SYSCALL = 227
+ SYS_SETFSUID = 228
+ SYS_SETFSGID = 229
+ SYS__NEWSELECT = 230
+ SYS_SPLICE = 232
+ SYS_STIME = 233
+ SYS_STATFS64 = 234
+ SYS_FSTATFS64 = 235
+ SYS__LLSEEK = 236
+ SYS_MLOCK = 237
+ SYS_MUNLOCK = 238
+ SYS_MLOCKALL = 239
+ SYS_MUNLOCKALL = 240
+ SYS_SCHED_SETPARAM = 241
+ SYS_SCHED_GETPARAM = 242
+ SYS_SCHED_SETSCHEDULER = 243
+ SYS_SCHED_GETSCHEDULER = 244
+ SYS_SCHED_YIELD = 245
+ SYS_SCHED_GET_PRIORITY_MAX = 246
+ SYS_SCHED_GET_PRIORITY_MIN = 247
+ SYS_SCHED_RR_GET_INTERVAL = 248
+ SYS_NANOSLEEP = 249
+ SYS_MREMAP = 250
+ SYS__SYSCTL = 251
+ SYS_GETSID = 252
+ SYS_FDATASYNC = 253
+ SYS_NFSSERVCTL = 254
+ SYS_SYNC_FILE_RANGE = 255
+ SYS_CLOCK_SETTIME = 256
+ SYS_CLOCK_GETTIME = 257
+ SYS_CLOCK_GETRES = 258
+ SYS_CLOCK_NANOSLEEP = 259
+ SYS_SCHED_GETAFFINITY = 260
+ SYS_SCHED_SETAFFINITY = 261
+ SYS_TIMER_SETTIME = 262
+ SYS_TIMER_GETTIME = 263
+ SYS_TIMER_GETOVERRUN = 264
+ SYS_TIMER_DELETE = 265
+ SYS_TIMER_CREATE = 266
+ SYS_IO_SETUP = 268
+ SYS_IO_DESTROY = 269
+ SYS_IO_SUBMIT = 270
+ SYS_IO_CANCEL = 271
+ SYS_IO_GETEVENTS = 272
+ SYS_MQ_OPEN = 273
+ SYS_MQ_UNLINK = 274
+ SYS_MQ_TIMEDSEND = 275
+ SYS_MQ_TIMEDRECEIVE = 276
+ SYS_MQ_NOTIFY = 277
+ SYS_MQ_GETSETATTR = 278
+ SYS_WAITID = 279
+ SYS_TEE = 280
+ SYS_ADD_KEY = 281
+ SYS_REQUEST_KEY = 282
+ SYS_KEYCTL = 283
+ SYS_OPENAT = 284
+ SYS_MKDIRAT = 285
+ SYS_MKNODAT = 286
+ SYS_FCHOWNAT = 287
+ SYS_FUTIMESAT = 288
+ SYS_FSTATAT64 = 289
+ SYS_UNLINKAT = 290
+ SYS_RENAMEAT = 291
+ SYS_LINKAT = 292
+ SYS_SYMLINKAT = 293
+ SYS_READLINKAT = 294
+ SYS_FCHMODAT = 295
+ SYS_FACCESSAT = 296
+ SYS_PSELECT6 = 297
+ SYS_PPOLL = 298
+ SYS_UNSHARE = 299
+ SYS_SET_ROBUST_LIST = 300
+ SYS_GET_ROBUST_LIST = 301
+ SYS_MIGRATE_PAGES = 302
+ SYS_MBIND = 303
+ SYS_GET_MEMPOLICY = 304
+ SYS_SET_MEMPOLICY = 305
+ SYS_KEXEC_LOAD = 306
+ SYS_MOVE_PAGES = 307
+ SYS_GETCPU = 308
+ SYS_EPOLL_PWAIT = 309
+ SYS_UTIMENSAT = 310
+ SYS_SIGNALFD = 311
+ SYS_TIMERFD_CREATE = 312
+ SYS_EVENTFD = 313
+ SYS_FALLOCATE = 314
+ SYS_TIMERFD_SETTIME = 315
+ SYS_TIMERFD_GETTIME = 316
+ SYS_SIGNALFD4 = 317
+ SYS_EVENTFD2 = 318
+ SYS_EPOLL_CREATE1 = 319
+ SYS_DUP3 = 320
+ SYS_PIPE2 = 321
+ SYS_INOTIFY_INIT1 = 322
+ SYS_ACCEPT4 = 323
+ SYS_PREADV = 324
+ SYS_PWRITEV = 325
+ SYS_RT_TGSIGQUEUEINFO = 326
+ SYS_PERF_EVENT_OPEN = 327
+ SYS_RECVMMSG = 328
+ SYS_FANOTIFY_INIT = 329
+ SYS_FANOTIFY_MARK = 330
+ SYS_PRLIMIT64 = 331
+ SYS_NAME_TO_HANDLE_AT = 332
+ SYS_OPEN_BY_HANDLE_AT = 333
+ SYS_CLOCK_ADJTIME = 334
+ SYS_SYNCFS = 335
+ SYS_SENDMMSG = 336
+ SYS_SETNS = 337
+ SYS_PROCESS_VM_READV = 338
+ SYS_PROCESS_VM_WRITEV = 339
+ SYS_KERN_FEATURES = 340
+ SYS_KCMP = 341
+ SYS_FINIT_MODULE = 342
+ SYS_SCHED_SETATTR = 343
+ SYS_SCHED_GETATTR = 344
+ SYS_RENAMEAT2 = 345
+ SYS_SECCOMP = 346
+ SYS_GETRANDOM = 347
+ SYS_MEMFD_CREATE = 348
+ SYS_BPF = 349
+ SYS_EXECVEAT = 350
+ SYS_MEMBARRIER = 351
+ SYS_USERFAULTFD = 352
+ SYS_BIND = 353
+ SYS_LISTEN = 354
+ SYS_SETSOCKOPT = 355
+ SYS_MLOCK2 = 356
+ SYS_COPY_FILE_RANGE = 357
+ SYS_PREADV2 = 358
+ SYS_PWRITEV2 = 359
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go
new file mode 100644
index 0000000..8afda9c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go
@@ -0,0 +1,274 @@
+// mksysnum_netbsd.pl
+// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT
+
+// +build 386,netbsd
+
+package unix
+
+const (
+ SYS_EXIT = 1 // { void|sys||exit(int rval); }
+ SYS_FORK = 2 // { int|sys||fork(void); }
+ SYS_READ = 3 // { ssize_t|sys||read(int fd, void *buf, size_t nbyte); }
+ SYS_WRITE = 4 // { ssize_t|sys||write(int fd, const void *buf, size_t nbyte); }
+ SYS_OPEN = 5 // { int|sys||open(const char *path, int flags, ... mode_t mode); }
+ SYS_CLOSE = 6 // { int|sys||close(int fd); }
+ SYS_LINK = 9 // { int|sys||link(const char *path, const char *link); }
+ SYS_UNLINK = 10 // { int|sys||unlink(const char *path); }
+ SYS_CHDIR = 12 // { int|sys||chdir(const char *path); }
+ SYS_FCHDIR = 13 // { int|sys||fchdir(int fd); }
+ SYS_CHMOD = 15 // { int|sys||chmod(const char *path, mode_t mode); }
+ SYS_CHOWN = 16 // { int|sys||chown(const char *path, uid_t uid, gid_t gid); }
+ SYS_BREAK = 17 // { int|sys||obreak(char *nsize); }
+ SYS_GETPID = 20 // { pid_t|sys||getpid_with_ppid(void); }
+ SYS_UNMOUNT = 22 // { int|sys||unmount(const char *path, int flags); }
+ SYS_SETUID = 23 // { int|sys||setuid(uid_t uid); }
+ SYS_GETUID = 24 // { uid_t|sys||getuid_with_euid(void); }
+ SYS_GETEUID = 25 // { uid_t|sys||geteuid(void); }
+ SYS_PTRACE = 26 // { int|sys||ptrace(int req, pid_t pid, void *addr, int data); }
+ SYS_RECVMSG = 27 // { ssize_t|sys||recvmsg(int s, struct msghdr *msg, int flags); }
+ SYS_SENDMSG = 28 // { ssize_t|sys||sendmsg(int s, const struct msghdr *msg, int flags); }
+ SYS_RECVFROM = 29 // { ssize_t|sys||recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlenaddr); }
+ SYS_ACCEPT = 30 // { int|sys||accept(int s, struct sockaddr *name, socklen_t *anamelen); }
+ SYS_GETPEERNAME = 31 // { int|sys||getpeername(int fdes, struct sockaddr *asa, socklen_t *alen); }
+ SYS_GETSOCKNAME = 32 // { int|sys||getsockname(int fdes, struct sockaddr *asa, socklen_t *alen); }
+ SYS_ACCESS = 33 // { int|sys||access(const char *path, int flags); }
+ SYS_CHFLAGS = 34 // { int|sys||chflags(const char *path, u_long flags); }
+ SYS_FCHFLAGS = 35 // { int|sys||fchflags(int fd, u_long flags); }
+ SYS_SYNC = 36 // { void|sys||sync(void); }
+ SYS_KILL = 37 // { int|sys||kill(pid_t pid, int signum); }
+ SYS_GETPPID = 39 // { pid_t|sys||getppid(void); }
+ SYS_DUP = 41 // { int|sys||dup(int fd); }
+ SYS_PIPE = 42 // { int|sys||pipe(void); }
+ SYS_GETEGID = 43 // { gid_t|sys||getegid(void); }
+ SYS_PROFIL = 44 // { int|sys||profil(char *samples, size_t size, u_long offset, u_int scale); }
+ SYS_KTRACE = 45 // { int|sys||ktrace(const char *fname, int ops, int facs, pid_t pid); }
+ SYS_GETGID = 47 // { gid_t|sys||getgid_with_egid(void); }
+ SYS___GETLOGIN = 49 // { int|sys||__getlogin(char *namebuf, size_t namelen); }
+ SYS___SETLOGIN = 50 // { int|sys||__setlogin(const char *namebuf); }
+ SYS_ACCT = 51 // { int|sys||acct(const char *path); }
+ SYS_IOCTL = 54 // { int|sys||ioctl(int fd, u_long com, ... void *data); }
+ SYS_REVOKE = 56 // { int|sys||revoke(const char *path); }
+ SYS_SYMLINK = 57 // { int|sys||symlink(const char *path, const char *link); }
+ SYS_READLINK = 58 // { ssize_t|sys||readlink(const char *path, char *buf, size_t count); }
+ SYS_EXECVE = 59 // { int|sys||execve(const char *path, char * const *argp, char * const *envp); }
+ SYS_UMASK = 60 // { mode_t|sys||umask(mode_t newmask); }
+ SYS_CHROOT = 61 // { int|sys||chroot(const char *path); }
+ SYS_VFORK = 66 // { int|sys||vfork(void); }
+ SYS_SBRK = 69 // { int|sys||sbrk(intptr_t incr); }
+ SYS_SSTK = 70 // { int|sys||sstk(int incr); }
+ SYS_VADVISE = 72 // { int|sys||ovadvise(int anom); }
+ SYS_MUNMAP = 73 // { int|sys||munmap(void *addr, size_t len); }
+ SYS_MPROTECT = 74 // { int|sys||mprotect(void *addr, size_t len, int prot); }
+ SYS_MADVISE = 75 // { int|sys||madvise(void *addr, size_t len, int behav); }
+ SYS_MINCORE = 78 // { int|sys||mincore(void *addr, size_t len, char *vec); }
+ SYS_GETGROUPS = 79 // { int|sys||getgroups(int gidsetsize, gid_t *gidset); }
+ SYS_SETGROUPS = 80 // { int|sys||setgroups(int gidsetsize, const gid_t *gidset); }
+ SYS_GETPGRP = 81 // { int|sys||getpgrp(void); }
+ SYS_SETPGID = 82 // { int|sys||setpgid(pid_t pid, pid_t pgid); }
+ SYS_DUP2 = 90 // { int|sys||dup2(int from, int to); }
+ SYS_FCNTL = 92 // { int|sys||fcntl(int fd, int cmd, ... void *arg); }
+ SYS_FSYNC = 95 // { int|sys||fsync(int fd); }
+ SYS_SETPRIORITY = 96 // { int|sys||setpriority(int which, id_t who, int prio); }
+ SYS_CONNECT = 98 // { int|sys||connect(int s, const struct sockaddr *name, socklen_t namelen); }
+ SYS_GETPRIORITY = 100 // { int|sys||getpriority(int which, id_t who); }
+ SYS_BIND = 104 // { int|sys||bind(int s, const struct sockaddr *name, socklen_t namelen); }
+ SYS_SETSOCKOPT = 105 // { int|sys||setsockopt(int s, int level, int name, const void *val, socklen_t valsize); }
+ SYS_LISTEN = 106 // { int|sys||listen(int s, int backlog); }
+ SYS_GETSOCKOPT = 118 // { int|sys||getsockopt(int s, int level, int name, void *val, socklen_t *avalsize); }
+ SYS_READV = 120 // { ssize_t|sys||readv(int fd, const struct iovec *iovp, int iovcnt); }
+ SYS_WRITEV = 121 // { ssize_t|sys||writev(int fd, const struct iovec *iovp, int iovcnt); }
+ SYS_FCHOWN = 123 // { int|sys||fchown(int fd, uid_t uid, gid_t gid); }
+ SYS_FCHMOD = 124 // { int|sys||fchmod(int fd, mode_t mode); }
+ SYS_SETREUID = 126 // { int|sys||setreuid(uid_t ruid, uid_t euid); }
+ SYS_SETREGID = 127 // { int|sys||setregid(gid_t rgid, gid_t egid); }
+ SYS_RENAME = 128 // { int|sys||rename(const char *from, const char *to); }
+ SYS_FLOCK = 131 // { int|sys||flock(int fd, int how); }
+ SYS_MKFIFO = 132 // { int|sys||mkfifo(const char *path, mode_t mode); }
+ SYS_SENDTO = 133 // { ssize_t|sys||sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); }
+ SYS_SHUTDOWN = 134 // { int|sys||shutdown(int s, int how); }
+ SYS_SOCKETPAIR = 135 // { int|sys||socketpair(int domain, int type, int protocol, int *rsv); }
+ SYS_MKDIR = 136 // { int|sys||mkdir(const char *path, mode_t mode); }
+ SYS_RMDIR = 137 // { int|sys||rmdir(const char *path); }
+ SYS_SETSID = 147 // { int|sys||setsid(void); }
+ SYS_SYSARCH = 165 // { int|sys||sysarch(int op, void *parms); }
+ SYS_PREAD = 173 // { ssize_t|sys||pread(int fd, void *buf, size_t nbyte, int PAD, off_t offset); }
+ SYS_PWRITE = 174 // { ssize_t|sys||pwrite(int fd, const void *buf, size_t nbyte, int PAD, off_t offset); }
+ SYS_NTP_ADJTIME = 176 // { int|sys||ntp_adjtime(struct timex *tp); }
+ SYS_SETGID = 181 // { int|sys||setgid(gid_t gid); }
+ SYS_SETEGID = 182 // { int|sys||setegid(gid_t egid); }
+ SYS_SETEUID = 183 // { int|sys||seteuid(uid_t euid); }
+ SYS_PATHCONF = 191 // { long|sys||pathconf(const char *path, int name); }
+ SYS_FPATHCONF = 192 // { long|sys||fpathconf(int fd, int name); }
+ SYS_GETRLIMIT = 194 // { int|sys||getrlimit(int which, struct rlimit *rlp); }
+ SYS_SETRLIMIT = 195 // { int|sys||setrlimit(int which, const struct rlimit *rlp); }
+ SYS_MMAP = 197 // { void *|sys||mmap(void *addr, size_t len, int prot, int flags, int fd, long PAD, off_t pos); }
+ SYS_LSEEK = 199 // { off_t|sys||lseek(int fd, int PAD, off_t offset, int whence); }
+ SYS_TRUNCATE = 200 // { int|sys||truncate(const char *path, int PAD, off_t length); }
+ SYS_FTRUNCATE = 201 // { int|sys||ftruncate(int fd, int PAD, off_t length); }
+ SYS___SYSCTL = 202 // { int|sys||__sysctl(const int *name, u_int namelen, void *old, size_t *oldlenp, const void *new, size_t newlen); }
+ SYS_MLOCK = 203 // { int|sys||mlock(const void *addr, size_t len); }
+ SYS_MUNLOCK = 204 // { int|sys||munlock(const void *addr, size_t len); }
+ SYS_UNDELETE = 205 // { int|sys||undelete(const char *path); }
+ SYS_GETPGID = 207 // { pid_t|sys||getpgid(pid_t pid); }
+ SYS_REBOOT = 208 // { int|sys||reboot(int opt, char *bootstr); }
+ SYS_POLL = 209 // { int|sys||poll(struct pollfd *fds, u_int nfds, int timeout); }
+ SYS_SEMGET = 221 // { int|sys||semget(key_t key, int nsems, int semflg); }
+ SYS_SEMOP = 222 // { int|sys||semop(int semid, struct sembuf *sops, size_t nsops); }
+ SYS_SEMCONFIG = 223 // { int|sys||semconfig(int flag); }
+ SYS_MSGGET = 225 // { int|sys||msgget(key_t key, int msgflg); }
+ SYS_MSGSND = 226 // { int|sys||msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); }
+ SYS_MSGRCV = 227 // { ssize_t|sys||msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); }
+ SYS_SHMAT = 228 // { void *|sys||shmat(int shmid, const void *shmaddr, int shmflg); }
+ SYS_SHMDT = 230 // { int|sys||shmdt(const void *shmaddr); }
+ SYS_SHMGET = 231 // { int|sys||shmget(key_t key, size_t size, int shmflg); }
+ SYS_TIMER_CREATE = 235 // { int|sys||timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); }
+ SYS_TIMER_DELETE = 236 // { int|sys||timer_delete(timer_t timerid); }
+ SYS_TIMER_GETOVERRUN = 239 // { int|sys||timer_getoverrun(timer_t timerid); }
+ SYS_FDATASYNC = 241 // { int|sys||fdatasync(int fd); }
+ SYS_MLOCKALL = 242 // { int|sys||mlockall(int flags); }
+ SYS_MUNLOCKALL = 243 // { int|sys||munlockall(void); }
+ SYS_SIGQUEUEINFO = 245 // { int|sys||sigqueueinfo(pid_t pid, const siginfo_t *info); }
+ SYS_MODCTL = 246 // { int|sys||modctl(int cmd, void *arg); }
+ SYS___POSIX_RENAME = 270 // { int|sys||__posix_rename(const char *from, const char *to); }
+ SYS_SWAPCTL = 271 // { int|sys||swapctl(int cmd, void *arg, int misc); }
+ SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); }
+ SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); }
+ SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); }
+ SYS_MSYNC = 277 // { int|sys|13|msync(void *addr, size_t len, int flags); }
+ SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); }
+ SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); }
+ SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); }
+ SYS_GETSID = 286 // { pid_t|sys||getsid(pid_t pid); }
+ SYS___CLONE = 287 // { pid_t|sys||__clone(int flags, void *stack); }
+ SYS_FKTRACE = 288 // { int|sys||fktrace(int fd, int ops, int facs, pid_t pid); }
+ SYS_PREADV = 289 // { ssize_t|sys||preadv(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); }
+ SYS_PWRITEV = 290 // { ssize_t|sys||pwritev(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); }
+ SYS___GETCWD = 296 // { int|sys||__getcwd(char *bufp, size_t length); }
+ SYS_FCHROOT = 297 // { int|sys||fchroot(int fd); }
+ SYS_LCHFLAGS = 304 // { int|sys||lchflags(const char *path, u_long flags); }
+ SYS_ISSETUGID = 305 // { int|sys||issetugid(void); }
+ SYS_UTRACE = 306 // { int|sys||utrace(const char *label, void *addr, size_t len); }
+ SYS_GETCONTEXT = 307 // { int|sys||getcontext(struct __ucontext *ucp); }
+ SYS_SETCONTEXT = 308 // { int|sys||setcontext(const struct __ucontext *ucp); }
+ SYS__LWP_CREATE = 309 // { int|sys||_lwp_create(const struct __ucontext *ucp, u_long flags, lwpid_t *new_lwp); }
+ SYS__LWP_EXIT = 310 // { int|sys||_lwp_exit(void); }
+ SYS__LWP_SELF = 311 // { lwpid_t|sys||_lwp_self(void); }
+ SYS__LWP_WAIT = 312 // { int|sys||_lwp_wait(lwpid_t wait_for, lwpid_t *departed); }
+ SYS__LWP_SUSPEND = 313 // { int|sys||_lwp_suspend(lwpid_t target); }
+ SYS__LWP_CONTINUE = 314 // { int|sys||_lwp_continue(lwpid_t target); }
+ SYS__LWP_WAKEUP = 315 // { int|sys||_lwp_wakeup(lwpid_t target); }
+ SYS__LWP_GETPRIVATE = 316 // { void *|sys||_lwp_getprivate(void); }
+ SYS__LWP_SETPRIVATE = 317 // { void|sys||_lwp_setprivate(void *ptr); }
+ SYS__LWP_KILL = 318 // { int|sys||_lwp_kill(lwpid_t target, int signo); }
+ SYS__LWP_DETACH = 319 // { int|sys||_lwp_detach(lwpid_t target); }
+ SYS__LWP_UNPARK = 321 // { int|sys||_lwp_unpark(lwpid_t target, const void *hint); }
+ SYS__LWP_UNPARK_ALL = 322 // { ssize_t|sys||_lwp_unpark_all(const lwpid_t *targets, size_t ntargets, const void *hint); }
+ SYS__LWP_SETNAME = 323 // { int|sys||_lwp_setname(lwpid_t target, const char *name); }
+ SYS__LWP_GETNAME = 324 // { int|sys||_lwp_getname(lwpid_t target, char *name, size_t len); }
+ SYS__LWP_CTL = 325 // { int|sys||_lwp_ctl(int features, struct lwpctl **address); }
+ SYS___SIGACTION_SIGTRAMP = 340 // { int|sys||__sigaction_sigtramp(int signum, const struct sigaction *nsa, struct sigaction *osa, const void *tramp, int vers); }
+ SYS_PMC_GET_INFO = 341 // { int|sys||pmc_get_info(int ctr, int op, void *args); }
+ SYS_PMC_CONTROL = 342 // { int|sys||pmc_control(int ctr, int op, void *args); }
+ SYS_RASCTL = 343 // { int|sys||rasctl(void *addr, size_t len, int op); }
+ SYS_KQUEUE = 344 // { int|sys||kqueue(void); }
+ SYS__SCHED_SETPARAM = 346 // { int|sys||_sched_setparam(pid_t pid, lwpid_t lid, int policy, const struct sched_param *params); }
+ SYS__SCHED_GETPARAM = 347 // { int|sys||_sched_getparam(pid_t pid, lwpid_t lid, int *policy, struct sched_param *params); }
+ SYS__SCHED_SETAFFINITY = 348 // { int|sys||_sched_setaffinity(pid_t pid, lwpid_t lid, size_t size, const cpuset_t *cpuset); }
+ SYS__SCHED_GETAFFINITY = 349 // { int|sys||_sched_getaffinity(pid_t pid, lwpid_t lid, size_t size, cpuset_t *cpuset); }
+ SYS_SCHED_YIELD = 350 // { int|sys||sched_yield(void); }
+ SYS_FSYNC_RANGE = 354 // { int|sys||fsync_range(int fd, int flags, off_t start, off_t length); }
+ SYS_UUIDGEN = 355 // { int|sys||uuidgen(struct uuid *store, int count); }
+ SYS_GETVFSSTAT = 356 // { int|sys||getvfsstat(struct statvfs *buf, size_t bufsize, int flags); }
+ SYS_STATVFS1 = 357 // { int|sys||statvfs1(const char *path, struct statvfs *buf, int flags); }
+ SYS_FSTATVFS1 = 358 // { int|sys||fstatvfs1(int fd, struct statvfs *buf, int flags); }
+ SYS_EXTATTRCTL = 360 // { int|sys||extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_SET_FILE = 361 // { int|sys||extattr_set_file(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); }
+ SYS_EXTATTR_GET_FILE = 362 // { ssize_t|sys||extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
+ SYS_EXTATTR_DELETE_FILE = 363 // { int|sys||extattr_delete_file(const char *path, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_SET_FD = 364 // { int|sys||extattr_set_fd(int fd, int attrnamespace, const char *attrname, const void *data, size_t nbytes); }
+ SYS_EXTATTR_GET_FD = 365 // { ssize_t|sys||extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
+ SYS_EXTATTR_DELETE_FD = 366 // { int|sys||extattr_delete_fd(int fd, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_SET_LINK = 367 // { int|sys||extattr_set_link(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); }
+ SYS_EXTATTR_GET_LINK = 368 // { ssize_t|sys||extattr_get_link(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
+ SYS_EXTATTR_DELETE_LINK = 369 // { int|sys||extattr_delete_link(const char *path, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_LIST_FD = 370 // { ssize_t|sys||extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); }
+ SYS_EXTATTR_LIST_FILE = 371 // { ssize_t|sys||extattr_list_file(const char *path, int attrnamespace, void *data, size_t nbytes); }
+ SYS_EXTATTR_LIST_LINK = 372 // { ssize_t|sys||extattr_list_link(const char *path, int attrnamespace, void *data, size_t nbytes); }
+ SYS_SETXATTR = 375 // { int|sys||setxattr(const char *path, const char *name, const void *value, size_t size, int flags); }
+ SYS_LSETXATTR = 376 // { int|sys||lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags); }
+ SYS_FSETXATTR = 377 // { int|sys||fsetxattr(int fd, const char *name, const void *value, size_t size, int flags); }
+ SYS_GETXATTR = 378 // { int|sys||getxattr(const char *path, const char *name, void *value, size_t size); }
+ SYS_LGETXATTR = 379 // { int|sys||lgetxattr(const char *path, const char *name, void *value, size_t size); }
+ SYS_FGETXATTR = 380 // { int|sys||fgetxattr(int fd, const char *name, void *value, size_t size); }
+ SYS_LISTXATTR = 381 // { int|sys||listxattr(const char *path, char *list, size_t size); }
+ SYS_LLISTXATTR = 382 // { int|sys||llistxattr(const char *path, char *list, size_t size); }
+ SYS_FLISTXATTR = 383 // { int|sys||flistxattr(int fd, char *list, size_t size); }
+ SYS_REMOVEXATTR = 384 // { int|sys||removexattr(const char *path, const char *name); }
+ SYS_LREMOVEXATTR = 385 // { int|sys||lremovexattr(const char *path, const char *name); }
+ SYS_FREMOVEXATTR = 386 // { int|sys||fremovexattr(int fd, const char *name); }
+ SYS_GETDENTS = 390 // { int|sys|30|getdents(int fd, char *buf, size_t count); }
+ SYS_SOCKET = 394 // { int|sys|30|socket(int domain, int type, int protocol); }
+ SYS_GETFH = 395 // { int|sys|30|getfh(const char *fname, void *fhp, size_t *fh_size); }
+ SYS_MOUNT = 410 // { int|sys|50|mount(const char *type, const char *path, int flags, void *data, size_t data_len); }
+ SYS_MREMAP = 411 // { void *|sys||mremap(void *old_address, size_t old_size, void *new_address, size_t new_size, int flags); }
+ SYS_PSET_CREATE = 412 // { int|sys||pset_create(psetid_t *psid); }
+ SYS_PSET_DESTROY = 413 // { int|sys||pset_destroy(psetid_t psid); }
+ SYS_PSET_ASSIGN = 414 // { int|sys||pset_assign(psetid_t psid, cpuid_t cpuid, psetid_t *opsid); }
+ SYS__PSET_BIND = 415 // { int|sys||_pset_bind(idtype_t idtype, id_t first_id, id_t second_id, psetid_t psid, psetid_t *opsid); }
+ SYS_POSIX_FADVISE = 416 // { int|sys|50|posix_fadvise(int fd, int PAD, off_t offset, off_t len, int advice); }
+ SYS_SELECT = 417 // { int|sys|50|select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); }
+ SYS_GETTIMEOFDAY = 418 // { int|sys|50|gettimeofday(struct timeval *tp, void *tzp); }
+ SYS_SETTIMEOFDAY = 419 // { int|sys|50|settimeofday(const struct timeval *tv, const void *tzp); }
+ SYS_UTIMES = 420 // { int|sys|50|utimes(const char *path, const struct timeval *tptr); }
+ SYS_ADJTIME = 421 // { int|sys|50|adjtime(const struct timeval *delta, struct timeval *olddelta); }
+ SYS_FUTIMES = 423 // { int|sys|50|futimes(int fd, const struct timeval *tptr); }
+ SYS_LUTIMES = 424 // { int|sys|50|lutimes(const char *path, const struct timeval *tptr); }
+ SYS_SETITIMER = 425 // { int|sys|50|setitimer(int which, const struct itimerval *itv, struct itimerval *oitv); }
+ SYS_GETITIMER = 426 // { int|sys|50|getitimer(int which, struct itimerval *itv); }
+ SYS_CLOCK_GETTIME = 427 // { int|sys|50|clock_gettime(clockid_t clock_id, struct timespec *tp); }
+ SYS_CLOCK_SETTIME = 428 // { int|sys|50|clock_settime(clockid_t clock_id, const struct timespec *tp); }
+ SYS_CLOCK_GETRES = 429 // { int|sys|50|clock_getres(clockid_t clock_id, struct timespec *tp); }
+ SYS_NANOSLEEP = 430 // { int|sys|50|nanosleep(const struct timespec *rqtp, struct timespec *rmtp); }
+ SYS___SIGTIMEDWAIT = 431 // { int|sys|50|__sigtimedwait(const sigset_t *set, siginfo_t *info, struct timespec *timeout); }
+ SYS__LWP_PARK = 434 // { int|sys|50|_lwp_park(const struct timespec *ts, lwpid_t unpark, const void *hint, const void *unparkhint); }
+ SYS_KEVENT = 435 // { int|sys|50|kevent(int fd, const struct kevent *changelist, size_t nchanges, struct kevent *eventlist, size_t nevents, const struct timespec *timeout); }
+ SYS_PSELECT = 436 // { int|sys|50|pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *mask); }
+ SYS_POLLTS = 437 // { int|sys|50|pollts(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *mask); }
+ SYS_STAT = 439 // { int|sys|50|stat(const char *path, struct stat *ub); }
+ SYS_FSTAT = 440 // { int|sys|50|fstat(int fd, struct stat *sb); }
+ SYS_LSTAT = 441 // { int|sys|50|lstat(const char *path, struct stat *ub); }
+ SYS___SEMCTL = 442 // { int|sys|50|__semctl(int semid, int semnum, int cmd, ... union __semun *arg); }
+ SYS_SHMCTL = 443 // { int|sys|50|shmctl(int shmid, int cmd, struct shmid_ds *buf); }
+ SYS_MSGCTL = 444 // { int|sys|50|msgctl(int msqid, int cmd, struct msqid_ds *buf); }
+ SYS_GETRUSAGE = 445 // { int|sys|50|getrusage(int who, struct rusage *rusage); }
+ SYS_TIMER_SETTIME = 446 // { int|sys|50|timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); }
+ SYS_TIMER_GETTIME = 447 // { int|sys|50|timer_gettime(timer_t timerid, struct itimerspec *value); }
+ SYS_NTP_GETTIME = 448 // { int|sys|50|ntp_gettime(struct ntptimeval *ntvp); }
+ SYS_WAIT4 = 449 // { int|sys|50|wait4(pid_t pid, int *status, int options, struct rusage *rusage); }
+ SYS_MKNOD = 450 // { int|sys|50|mknod(const char *path, mode_t mode, dev_t dev); }
+ SYS_FHSTAT = 451 // { int|sys|50|fhstat(const void *fhp, size_t fh_size, struct stat *sb); }
+ SYS_PIPE2 = 453 // { int|sys||pipe2(int *fildes, int flags); }
+ SYS_DUP3 = 454 // { int|sys||dup3(int from, int to, int flags); }
+ SYS_KQUEUE1 = 455 // { int|sys||kqueue1(int flags); }
+ SYS_PACCEPT = 456 // { int|sys||paccept(int s, struct sockaddr *name, socklen_t *anamelen, const sigset_t *mask, int flags); }
+ SYS_LINKAT = 457 // { int|sys||linkat(int fd1, const char *name1, int fd2, const char *name2, int flags); }
+ SYS_RENAMEAT = 458 // { int|sys||renameat(int fromfd, const char *from, int tofd, const char *to); }
+ SYS_MKFIFOAT = 459 // { int|sys||mkfifoat(int fd, const char *path, mode_t mode); }
+ SYS_MKNODAT = 460 // { int|sys||mknodat(int fd, const char *path, mode_t mode, uint32_t dev); }
+ SYS_MKDIRAT = 461 // { int|sys||mkdirat(int fd, const char *path, mode_t mode); }
+ SYS_FACCESSAT = 462 // { int|sys||faccessat(int fd, const char *path, int amode, int flag); }
+ SYS_FCHMODAT = 463 // { int|sys||fchmodat(int fd, const char *path, mode_t mode, int flag); }
+ SYS_FCHOWNAT = 464 // { int|sys||fchownat(int fd, const char *path, uid_t owner, gid_t group, int flag); }
+ SYS_FEXECVE = 465 // { int|sys||fexecve(int fd, char * const *argp, char * const *envp); }
+ SYS_FSTATAT = 466 // { int|sys||fstatat(int fd, const char *path, struct stat *buf, int flag); }
+ SYS_UTIMENSAT = 467 // { int|sys||utimensat(int fd, const char *path, const struct timespec *tptr, int flag); }
+ SYS_OPENAT = 468 // { int|sys||openat(int fd, const char *path, int oflags, ... mode_t mode); }
+ SYS_READLINKAT = 469 // { int|sys||readlinkat(int fd, const char *path, char *buf, size_t bufsize); }
+ SYS_SYMLINKAT = 470 // { int|sys||symlinkat(const char *path1, int fd, const char *path2); }
+ SYS_UNLINKAT = 471 // { int|sys||unlinkat(int fd, const char *path, int flag); }
+ SYS_FUTIMENS = 472 // { int|sys||futimens(int fd, const struct timespec *tptr); }
+ SYS___QUOTACTL = 473 // { int|sys||__quotactl(const char *path, struct quotactl_args *args); }
+ SYS_POSIX_SPAWN = 474 // { int|sys||posix_spawn(pid_t *pid, const char *path, const struct posix_spawn_file_actions *file_actions, const struct posix_spawnattr *attrp, char *const *argv, char *const *envp); }
+ SYS_RECVMMSG = 475 // { int|sys||recvmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout); }
+ SYS_SENDMMSG = 476 // { int|sys||sendmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags); }
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go
new file mode 100644
index 0000000..aea8dbe
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go
@@ -0,0 +1,274 @@
+// mksysnum_netbsd.pl
+// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT
+
+// +build amd64,netbsd
+
+package unix
+
+const (
+ SYS_EXIT = 1 // { void|sys||exit(int rval); }
+ SYS_FORK = 2 // { int|sys||fork(void); }
+ SYS_READ = 3 // { ssize_t|sys||read(int fd, void *buf, size_t nbyte); }
+ SYS_WRITE = 4 // { ssize_t|sys||write(int fd, const void *buf, size_t nbyte); }
+ SYS_OPEN = 5 // { int|sys||open(const char *path, int flags, ... mode_t mode); }
+ SYS_CLOSE = 6 // { int|sys||close(int fd); }
+ SYS_LINK = 9 // { int|sys||link(const char *path, const char *link); }
+ SYS_UNLINK = 10 // { int|sys||unlink(const char *path); }
+ SYS_CHDIR = 12 // { int|sys||chdir(const char *path); }
+ SYS_FCHDIR = 13 // { int|sys||fchdir(int fd); }
+ SYS_CHMOD = 15 // { int|sys||chmod(const char *path, mode_t mode); }
+ SYS_CHOWN = 16 // { int|sys||chown(const char *path, uid_t uid, gid_t gid); }
+ SYS_BREAK = 17 // { int|sys||obreak(char *nsize); }
+ SYS_GETPID = 20 // { pid_t|sys||getpid_with_ppid(void); }
+ SYS_UNMOUNT = 22 // { int|sys||unmount(const char *path, int flags); }
+ SYS_SETUID = 23 // { int|sys||setuid(uid_t uid); }
+ SYS_GETUID = 24 // { uid_t|sys||getuid_with_euid(void); }
+ SYS_GETEUID = 25 // { uid_t|sys||geteuid(void); }
+ SYS_PTRACE = 26 // { int|sys||ptrace(int req, pid_t pid, void *addr, int data); }
+ SYS_RECVMSG = 27 // { ssize_t|sys||recvmsg(int s, struct msghdr *msg, int flags); }
+ SYS_SENDMSG = 28 // { ssize_t|sys||sendmsg(int s, const struct msghdr *msg, int flags); }
+ SYS_RECVFROM = 29 // { ssize_t|sys||recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlenaddr); }
+ SYS_ACCEPT = 30 // { int|sys||accept(int s, struct sockaddr *name, socklen_t *anamelen); }
+ SYS_GETPEERNAME = 31 // { int|sys||getpeername(int fdes, struct sockaddr *asa, socklen_t *alen); }
+ SYS_GETSOCKNAME = 32 // { int|sys||getsockname(int fdes, struct sockaddr *asa, socklen_t *alen); }
+ SYS_ACCESS = 33 // { int|sys||access(const char *path, int flags); }
+ SYS_CHFLAGS = 34 // { int|sys||chflags(const char *path, u_long flags); }
+ SYS_FCHFLAGS = 35 // { int|sys||fchflags(int fd, u_long flags); }
+ SYS_SYNC = 36 // { void|sys||sync(void); }
+ SYS_KILL = 37 // { int|sys||kill(pid_t pid, int signum); }
+ SYS_GETPPID = 39 // { pid_t|sys||getppid(void); }
+ SYS_DUP = 41 // { int|sys||dup(int fd); }
+ SYS_PIPE = 42 // { int|sys||pipe(void); }
+ SYS_GETEGID = 43 // { gid_t|sys||getegid(void); }
+ SYS_PROFIL = 44 // { int|sys||profil(char *samples, size_t size, u_long offset, u_int scale); }
+ SYS_KTRACE = 45 // { int|sys||ktrace(const char *fname, int ops, int facs, pid_t pid); }
+ SYS_GETGID = 47 // { gid_t|sys||getgid_with_egid(void); }
+ SYS___GETLOGIN = 49 // { int|sys||__getlogin(char *namebuf, size_t namelen); }
+ SYS___SETLOGIN = 50 // { int|sys||__setlogin(const char *namebuf); }
+ SYS_ACCT = 51 // { int|sys||acct(const char *path); }
+ SYS_IOCTL = 54 // { int|sys||ioctl(int fd, u_long com, ... void *data); }
+ SYS_REVOKE = 56 // { int|sys||revoke(const char *path); }
+ SYS_SYMLINK = 57 // { int|sys||symlink(const char *path, const char *link); }
+ SYS_READLINK = 58 // { ssize_t|sys||readlink(const char *path, char *buf, size_t count); }
+ SYS_EXECVE = 59 // { int|sys||execve(const char *path, char * const *argp, char * const *envp); }
+ SYS_UMASK = 60 // { mode_t|sys||umask(mode_t newmask); }
+ SYS_CHROOT = 61 // { int|sys||chroot(const char *path); }
+ SYS_VFORK = 66 // { int|sys||vfork(void); }
+ SYS_SBRK = 69 // { int|sys||sbrk(intptr_t incr); }
+ SYS_SSTK = 70 // { int|sys||sstk(int incr); }
+ SYS_VADVISE = 72 // { int|sys||ovadvise(int anom); }
+ SYS_MUNMAP = 73 // { int|sys||munmap(void *addr, size_t len); }
+ SYS_MPROTECT = 74 // { int|sys||mprotect(void *addr, size_t len, int prot); }
+ SYS_MADVISE = 75 // { int|sys||madvise(void *addr, size_t len, int behav); }
+ SYS_MINCORE = 78 // { int|sys||mincore(void *addr, size_t len, char *vec); }
+ SYS_GETGROUPS = 79 // { int|sys||getgroups(int gidsetsize, gid_t *gidset); }
+ SYS_SETGROUPS = 80 // { int|sys||setgroups(int gidsetsize, const gid_t *gidset); }
+ SYS_GETPGRP = 81 // { int|sys||getpgrp(void); }
+ SYS_SETPGID = 82 // { int|sys||setpgid(pid_t pid, pid_t pgid); }
+ SYS_DUP2 = 90 // { int|sys||dup2(int from, int to); }
+ SYS_FCNTL = 92 // { int|sys||fcntl(int fd, int cmd, ... void *arg); }
+ SYS_FSYNC = 95 // { int|sys||fsync(int fd); }
+ SYS_SETPRIORITY = 96 // { int|sys||setpriority(int which, id_t who, int prio); }
+ SYS_CONNECT = 98 // { int|sys||connect(int s, const struct sockaddr *name, socklen_t namelen); }
+ SYS_GETPRIORITY = 100 // { int|sys||getpriority(int which, id_t who); }
+ SYS_BIND = 104 // { int|sys||bind(int s, const struct sockaddr *name, socklen_t namelen); }
+ SYS_SETSOCKOPT = 105 // { int|sys||setsockopt(int s, int level, int name, const void *val, socklen_t valsize); }
+ SYS_LISTEN = 106 // { int|sys||listen(int s, int backlog); }
+ SYS_GETSOCKOPT = 118 // { int|sys||getsockopt(int s, int level, int name, void *val, socklen_t *avalsize); }
+ SYS_READV = 120 // { ssize_t|sys||readv(int fd, const struct iovec *iovp, int iovcnt); }
+ SYS_WRITEV = 121 // { ssize_t|sys||writev(int fd, const struct iovec *iovp, int iovcnt); }
+ SYS_FCHOWN = 123 // { int|sys||fchown(int fd, uid_t uid, gid_t gid); }
+ SYS_FCHMOD = 124 // { int|sys||fchmod(int fd, mode_t mode); }
+ SYS_SETREUID = 126 // { int|sys||setreuid(uid_t ruid, uid_t euid); }
+ SYS_SETREGID = 127 // { int|sys||setregid(gid_t rgid, gid_t egid); }
+ SYS_RENAME = 128 // { int|sys||rename(const char *from, const char *to); }
+ SYS_FLOCK = 131 // { int|sys||flock(int fd, int how); }
+ SYS_MKFIFO = 132 // { int|sys||mkfifo(const char *path, mode_t mode); }
+ SYS_SENDTO = 133 // { ssize_t|sys||sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); }
+ SYS_SHUTDOWN = 134 // { int|sys||shutdown(int s, int how); }
+ SYS_SOCKETPAIR = 135 // { int|sys||socketpair(int domain, int type, int protocol, int *rsv); }
+ SYS_MKDIR = 136 // { int|sys||mkdir(const char *path, mode_t mode); }
+ SYS_RMDIR = 137 // { int|sys||rmdir(const char *path); }
+ SYS_SETSID = 147 // { int|sys||setsid(void); }
+ SYS_SYSARCH = 165 // { int|sys||sysarch(int op, void *parms); }
+ SYS_PREAD = 173 // { ssize_t|sys||pread(int fd, void *buf, size_t nbyte, int PAD, off_t offset); }
+ SYS_PWRITE = 174 // { ssize_t|sys||pwrite(int fd, const void *buf, size_t nbyte, int PAD, off_t offset); }
+ SYS_NTP_ADJTIME = 176 // { int|sys||ntp_adjtime(struct timex *tp); }
+ SYS_SETGID = 181 // { int|sys||setgid(gid_t gid); }
+ SYS_SETEGID = 182 // { int|sys||setegid(gid_t egid); }
+ SYS_SETEUID = 183 // { int|sys||seteuid(uid_t euid); }
+ SYS_PATHCONF = 191 // { long|sys||pathconf(const char *path, int name); }
+ SYS_FPATHCONF = 192 // { long|sys||fpathconf(int fd, int name); }
+ SYS_GETRLIMIT = 194 // { int|sys||getrlimit(int which, struct rlimit *rlp); }
+ SYS_SETRLIMIT = 195 // { int|sys||setrlimit(int which, const struct rlimit *rlp); }
+ SYS_MMAP = 197 // { void *|sys||mmap(void *addr, size_t len, int prot, int flags, int fd, long PAD, off_t pos); }
+ SYS_LSEEK = 199 // { off_t|sys||lseek(int fd, int PAD, off_t offset, int whence); }
+ SYS_TRUNCATE = 200 // { int|sys||truncate(const char *path, int PAD, off_t length); }
+ SYS_FTRUNCATE = 201 // { int|sys||ftruncate(int fd, int PAD, off_t length); }
+ SYS___SYSCTL = 202 // { int|sys||__sysctl(const int *name, u_int namelen, void *old, size_t *oldlenp, const void *new, size_t newlen); }
+ SYS_MLOCK = 203 // { int|sys||mlock(const void *addr, size_t len); }
+ SYS_MUNLOCK = 204 // { int|sys||munlock(const void *addr, size_t len); }
+ SYS_UNDELETE = 205 // { int|sys||undelete(const char *path); }
+ SYS_GETPGID = 207 // { pid_t|sys||getpgid(pid_t pid); }
+ SYS_REBOOT = 208 // { int|sys||reboot(int opt, char *bootstr); }
+ SYS_POLL = 209 // { int|sys||poll(struct pollfd *fds, u_int nfds, int timeout); }
+ SYS_SEMGET = 221 // { int|sys||semget(key_t key, int nsems, int semflg); }
+ SYS_SEMOP = 222 // { int|sys||semop(int semid, struct sembuf *sops, size_t nsops); }
+ SYS_SEMCONFIG = 223 // { int|sys||semconfig(int flag); }
+ SYS_MSGGET = 225 // { int|sys||msgget(key_t key, int msgflg); }
+ SYS_MSGSND = 226 // { int|sys||msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); }
+ SYS_MSGRCV = 227 // { ssize_t|sys||msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); }
+ SYS_SHMAT = 228 // { void *|sys||shmat(int shmid, const void *shmaddr, int shmflg); }
+ SYS_SHMDT = 230 // { int|sys||shmdt(const void *shmaddr); }
+ SYS_SHMGET = 231 // { int|sys||shmget(key_t key, size_t size, int shmflg); }
+ SYS_TIMER_CREATE = 235 // { int|sys||timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); }
+ SYS_TIMER_DELETE = 236 // { int|sys||timer_delete(timer_t timerid); }
+ SYS_TIMER_GETOVERRUN = 239 // { int|sys||timer_getoverrun(timer_t timerid); }
+ SYS_FDATASYNC = 241 // { int|sys||fdatasync(int fd); }
+ SYS_MLOCKALL = 242 // { int|sys||mlockall(int flags); }
+ SYS_MUNLOCKALL = 243 // { int|sys||munlockall(void); }
+ SYS_SIGQUEUEINFO = 245 // { int|sys||sigqueueinfo(pid_t pid, const siginfo_t *info); }
+ SYS_MODCTL = 246 // { int|sys||modctl(int cmd, void *arg); }
+ SYS___POSIX_RENAME = 270 // { int|sys||__posix_rename(const char *from, const char *to); }
+ SYS_SWAPCTL = 271 // { int|sys||swapctl(int cmd, void *arg, int misc); }
+ SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); }
+ SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); }
+ SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); }
+ SYS_MSYNC = 277 // { int|sys|13|msync(void *addr, size_t len, int flags); }
+ SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); }
+ SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); }
+ SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); }
+ SYS_GETSID = 286 // { pid_t|sys||getsid(pid_t pid); }
+ SYS___CLONE = 287 // { pid_t|sys||__clone(int flags, void *stack); }
+ SYS_FKTRACE = 288 // { int|sys||fktrace(int fd, int ops, int facs, pid_t pid); }
+ SYS_PREADV = 289 // { ssize_t|sys||preadv(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); }
+ SYS_PWRITEV = 290 // { ssize_t|sys||pwritev(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); }
+ SYS___GETCWD = 296 // { int|sys||__getcwd(char *bufp, size_t length); }
+ SYS_FCHROOT = 297 // { int|sys||fchroot(int fd); }
+ SYS_LCHFLAGS = 304 // { int|sys||lchflags(const char *path, u_long flags); }
+ SYS_ISSETUGID = 305 // { int|sys||issetugid(void); }
+ SYS_UTRACE = 306 // { int|sys||utrace(const char *label, void *addr, size_t len); }
+ SYS_GETCONTEXT = 307 // { int|sys||getcontext(struct __ucontext *ucp); }
+ SYS_SETCONTEXT = 308 // { int|sys||setcontext(const struct __ucontext *ucp); }
+ SYS__LWP_CREATE = 309 // { int|sys||_lwp_create(const struct __ucontext *ucp, u_long flags, lwpid_t *new_lwp); }
+ SYS__LWP_EXIT = 310 // { int|sys||_lwp_exit(void); }
+ SYS__LWP_SELF = 311 // { lwpid_t|sys||_lwp_self(void); }
+ SYS__LWP_WAIT = 312 // { int|sys||_lwp_wait(lwpid_t wait_for, lwpid_t *departed); }
+ SYS__LWP_SUSPEND = 313 // { int|sys||_lwp_suspend(lwpid_t target); }
+ SYS__LWP_CONTINUE = 314 // { int|sys||_lwp_continue(lwpid_t target); }
+ SYS__LWP_WAKEUP = 315 // { int|sys||_lwp_wakeup(lwpid_t target); }
+ SYS__LWP_GETPRIVATE = 316 // { void *|sys||_lwp_getprivate(void); }
+ SYS__LWP_SETPRIVATE = 317 // { void|sys||_lwp_setprivate(void *ptr); }
+ SYS__LWP_KILL = 318 // { int|sys||_lwp_kill(lwpid_t target, int signo); }
+ SYS__LWP_DETACH = 319 // { int|sys||_lwp_detach(lwpid_t target); }
+ SYS__LWP_UNPARK = 321 // { int|sys||_lwp_unpark(lwpid_t target, const void *hint); }
+ SYS__LWP_UNPARK_ALL = 322 // { ssize_t|sys||_lwp_unpark_all(const lwpid_t *targets, size_t ntargets, const void *hint); }
+ SYS__LWP_SETNAME = 323 // { int|sys||_lwp_setname(lwpid_t target, const char *name); }
+ SYS__LWP_GETNAME = 324 // { int|sys||_lwp_getname(lwpid_t target, char *name, size_t len); }
+ SYS__LWP_CTL = 325 // { int|sys||_lwp_ctl(int features, struct lwpctl **address); }
+ SYS___SIGACTION_SIGTRAMP = 340 // { int|sys||__sigaction_sigtramp(int signum, const struct sigaction *nsa, struct sigaction *osa, const void *tramp, int vers); }
+ SYS_PMC_GET_INFO = 341 // { int|sys||pmc_get_info(int ctr, int op, void *args); }
+ SYS_PMC_CONTROL = 342 // { int|sys||pmc_control(int ctr, int op, void *args); }
+ SYS_RASCTL = 343 // { int|sys||rasctl(void *addr, size_t len, int op); }
+ SYS_KQUEUE = 344 // { int|sys||kqueue(void); }
+ SYS__SCHED_SETPARAM = 346 // { int|sys||_sched_setparam(pid_t pid, lwpid_t lid, int policy, const struct sched_param *params); }
+ SYS__SCHED_GETPARAM = 347 // { int|sys||_sched_getparam(pid_t pid, lwpid_t lid, int *policy, struct sched_param *params); }
+ SYS__SCHED_SETAFFINITY = 348 // { int|sys||_sched_setaffinity(pid_t pid, lwpid_t lid, size_t size, const cpuset_t *cpuset); }
+ SYS__SCHED_GETAFFINITY = 349 // { int|sys||_sched_getaffinity(pid_t pid, lwpid_t lid, size_t size, cpuset_t *cpuset); }
+ SYS_SCHED_YIELD = 350 // { int|sys||sched_yield(void); }
+ SYS_FSYNC_RANGE = 354 // { int|sys||fsync_range(int fd, int flags, off_t start, off_t length); }
+ SYS_UUIDGEN = 355 // { int|sys||uuidgen(struct uuid *store, int count); }
+ SYS_GETVFSSTAT = 356 // { int|sys||getvfsstat(struct statvfs *buf, size_t bufsize, int flags); }
+ SYS_STATVFS1 = 357 // { int|sys||statvfs1(const char *path, struct statvfs *buf, int flags); }
+ SYS_FSTATVFS1 = 358 // { int|sys||fstatvfs1(int fd, struct statvfs *buf, int flags); }
+ SYS_EXTATTRCTL = 360 // { int|sys||extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_SET_FILE = 361 // { int|sys||extattr_set_file(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); }
+ SYS_EXTATTR_GET_FILE = 362 // { ssize_t|sys||extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
+ SYS_EXTATTR_DELETE_FILE = 363 // { int|sys||extattr_delete_file(const char *path, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_SET_FD = 364 // { int|sys||extattr_set_fd(int fd, int attrnamespace, const char *attrname, const void *data, size_t nbytes); }
+ SYS_EXTATTR_GET_FD = 365 // { ssize_t|sys||extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
+ SYS_EXTATTR_DELETE_FD = 366 // { int|sys||extattr_delete_fd(int fd, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_SET_LINK = 367 // { int|sys||extattr_set_link(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); }
+ SYS_EXTATTR_GET_LINK = 368 // { ssize_t|sys||extattr_get_link(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
+ SYS_EXTATTR_DELETE_LINK = 369 // { int|sys||extattr_delete_link(const char *path, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_LIST_FD = 370 // { ssize_t|sys||extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); }
+ SYS_EXTATTR_LIST_FILE = 371 // { ssize_t|sys||extattr_list_file(const char *path, int attrnamespace, void *data, size_t nbytes); }
+ SYS_EXTATTR_LIST_LINK = 372 // { ssize_t|sys||extattr_list_link(const char *path, int attrnamespace, void *data, size_t nbytes); }
+ SYS_SETXATTR = 375 // { int|sys||setxattr(const char *path, const char *name, const void *value, size_t size, int flags); }
+ SYS_LSETXATTR = 376 // { int|sys||lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags); }
+ SYS_FSETXATTR = 377 // { int|sys||fsetxattr(int fd, const char *name, const void *value, size_t size, int flags); }
+ SYS_GETXATTR = 378 // { int|sys||getxattr(const char *path, const char *name, void *value, size_t size); }
+ SYS_LGETXATTR = 379 // { int|sys||lgetxattr(const char *path, const char *name, void *value, size_t size); }
+ SYS_FGETXATTR = 380 // { int|sys||fgetxattr(int fd, const char *name, void *value, size_t size); }
+ SYS_LISTXATTR = 381 // { int|sys||listxattr(const char *path, char *list, size_t size); }
+ SYS_LLISTXATTR = 382 // { int|sys||llistxattr(const char *path, char *list, size_t size); }
+ SYS_FLISTXATTR = 383 // { int|sys||flistxattr(int fd, char *list, size_t size); }
+ SYS_REMOVEXATTR = 384 // { int|sys||removexattr(const char *path, const char *name); }
+ SYS_LREMOVEXATTR = 385 // { int|sys||lremovexattr(const char *path, const char *name); }
+ SYS_FREMOVEXATTR = 386 // { int|sys||fremovexattr(int fd, const char *name); }
+ SYS_GETDENTS = 390 // { int|sys|30|getdents(int fd, char *buf, size_t count); }
+ SYS_SOCKET = 394 // { int|sys|30|socket(int domain, int type, int protocol); }
+ SYS_GETFH = 395 // { int|sys|30|getfh(const char *fname, void *fhp, size_t *fh_size); }
+ SYS_MOUNT = 410 // { int|sys|50|mount(const char *type, const char *path, int flags, void *data, size_t data_len); }
+ SYS_MREMAP = 411 // { void *|sys||mremap(void *old_address, size_t old_size, void *new_address, size_t new_size, int flags); }
+ SYS_PSET_CREATE = 412 // { int|sys||pset_create(psetid_t *psid); }
+ SYS_PSET_DESTROY = 413 // { int|sys||pset_destroy(psetid_t psid); }
+ SYS_PSET_ASSIGN = 414 // { int|sys||pset_assign(psetid_t psid, cpuid_t cpuid, psetid_t *opsid); }
+ SYS__PSET_BIND = 415 // { int|sys||_pset_bind(idtype_t idtype, id_t first_id, id_t second_id, psetid_t psid, psetid_t *opsid); }
+ SYS_POSIX_FADVISE = 416 // { int|sys|50|posix_fadvise(int fd, int PAD, off_t offset, off_t len, int advice); }
+ SYS_SELECT = 417 // { int|sys|50|select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); }
+ SYS_GETTIMEOFDAY = 418 // { int|sys|50|gettimeofday(struct timeval *tp, void *tzp); }
+ SYS_SETTIMEOFDAY = 419 // { int|sys|50|settimeofday(const struct timeval *tv, const void *tzp); }
+ SYS_UTIMES = 420 // { int|sys|50|utimes(const char *path, const struct timeval *tptr); }
+ SYS_ADJTIME = 421 // { int|sys|50|adjtime(const struct timeval *delta, struct timeval *olddelta); }
+ SYS_FUTIMES = 423 // { int|sys|50|futimes(int fd, const struct timeval *tptr); }
+ SYS_LUTIMES = 424 // { int|sys|50|lutimes(const char *path, const struct timeval *tptr); }
+ SYS_SETITIMER = 425 // { int|sys|50|setitimer(int which, const struct itimerval *itv, struct itimerval *oitv); }
+ SYS_GETITIMER = 426 // { int|sys|50|getitimer(int which, struct itimerval *itv); }
+ SYS_CLOCK_GETTIME = 427 // { int|sys|50|clock_gettime(clockid_t clock_id, struct timespec *tp); }
+ SYS_CLOCK_SETTIME = 428 // { int|sys|50|clock_settime(clockid_t clock_id, const struct timespec *tp); }
+ SYS_CLOCK_GETRES = 429 // { int|sys|50|clock_getres(clockid_t clock_id, struct timespec *tp); }
+ SYS_NANOSLEEP = 430 // { int|sys|50|nanosleep(const struct timespec *rqtp, struct timespec *rmtp); }
+ SYS___SIGTIMEDWAIT = 431 // { int|sys|50|__sigtimedwait(const sigset_t *set, siginfo_t *info, struct timespec *timeout); }
+ SYS__LWP_PARK = 434 // { int|sys|50|_lwp_park(const struct timespec *ts, lwpid_t unpark, const void *hint, const void *unparkhint); }
+ SYS_KEVENT = 435 // { int|sys|50|kevent(int fd, const struct kevent *changelist, size_t nchanges, struct kevent *eventlist, size_t nevents, const struct timespec *timeout); }
+ SYS_PSELECT = 436 // { int|sys|50|pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *mask); }
+ SYS_POLLTS = 437 // { int|sys|50|pollts(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *mask); }
+ SYS_STAT = 439 // { int|sys|50|stat(const char *path, struct stat *ub); }
+ SYS_FSTAT = 440 // { int|sys|50|fstat(int fd, struct stat *sb); }
+ SYS_LSTAT = 441 // { int|sys|50|lstat(const char *path, struct stat *ub); }
+ SYS___SEMCTL = 442 // { int|sys|50|__semctl(int semid, int semnum, int cmd, ... union __semun *arg); }
+ SYS_SHMCTL = 443 // { int|sys|50|shmctl(int shmid, int cmd, struct shmid_ds *buf); }
+ SYS_MSGCTL = 444 // { int|sys|50|msgctl(int msqid, int cmd, struct msqid_ds *buf); }
+ SYS_GETRUSAGE = 445 // { int|sys|50|getrusage(int who, struct rusage *rusage); }
+ SYS_TIMER_SETTIME = 446 // { int|sys|50|timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); }
+ SYS_TIMER_GETTIME = 447 // { int|sys|50|timer_gettime(timer_t timerid, struct itimerspec *value); }
+ SYS_NTP_GETTIME = 448 // { int|sys|50|ntp_gettime(struct ntptimeval *ntvp); }
+ SYS_WAIT4 = 449 // { int|sys|50|wait4(pid_t pid, int *status, int options, struct rusage *rusage); }
+ SYS_MKNOD = 450 // { int|sys|50|mknod(const char *path, mode_t mode, dev_t dev); }
+ SYS_FHSTAT = 451 // { int|sys|50|fhstat(const void *fhp, size_t fh_size, struct stat *sb); }
+ SYS_PIPE2 = 453 // { int|sys||pipe2(int *fildes, int flags); }
+ SYS_DUP3 = 454 // { int|sys||dup3(int from, int to, int flags); }
+ SYS_KQUEUE1 = 455 // { int|sys||kqueue1(int flags); }
+ SYS_PACCEPT = 456 // { int|sys||paccept(int s, struct sockaddr *name, socklen_t *anamelen, const sigset_t *mask, int flags); }
+ SYS_LINKAT = 457 // { int|sys||linkat(int fd1, const char *name1, int fd2, const char *name2, int flags); }
+ SYS_RENAMEAT = 458 // { int|sys||renameat(int fromfd, const char *from, int tofd, const char *to); }
+ SYS_MKFIFOAT = 459 // { int|sys||mkfifoat(int fd, const char *path, mode_t mode); }
+ SYS_MKNODAT = 460 // { int|sys||mknodat(int fd, const char *path, mode_t mode, uint32_t dev); }
+ SYS_MKDIRAT = 461 // { int|sys||mkdirat(int fd, const char *path, mode_t mode); }
+ SYS_FACCESSAT = 462 // { int|sys||faccessat(int fd, const char *path, int amode, int flag); }
+ SYS_FCHMODAT = 463 // { int|sys||fchmodat(int fd, const char *path, mode_t mode, int flag); }
+ SYS_FCHOWNAT = 464 // { int|sys||fchownat(int fd, const char *path, uid_t owner, gid_t group, int flag); }
+ SYS_FEXECVE = 465 // { int|sys||fexecve(int fd, char * const *argp, char * const *envp); }
+ SYS_FSTATAT = 466 // { int|sys||fstatat(int fd, const char *path, struct stat *buf, int flag); }
+ SYS_UTIMENSAT = 467 // { int|sys||utimensat(int fd, const char *path, const struct timespec *tptr, int flag); }
+ SYS_OPENAT = 468 // { int|sys||openat(int fd, const char *path, int oflags, ... mode_t mode); }
+ SYS_READLINKAT = 469 // { int|sys||readlinkat(int fd, const char *path, char *buf, size_t bufsize); }
+ SYS_SYMLINKAT = 470 // { int|sys||symlinkat(const char *path1, int fd, const char *path2); }
+ SYS_UNLINKAT = 471 // { int|sys||unlinkat(int fd, const char *path, int flag); }
+ SYS_FUTIMENS = 472 // { int|sys||futimens(int fd, const struct timespec *tptr); }
+ SYS___QUOTACTL = 473 // { int|sys||__quotactl(const char *path, struct quotactl_args *args); }
+ SYS_POSIX_SPAWN = 474 // { int|sys||posix_spawn(pid_t *pid, const char *path, const struct posix_spawn_file_actions *file_actions, const struct posix_spawnattr *attrp, char *const *argv, char *const *envp); }
+ SYS_RECVMMSG = 475 // { int|sys||recvmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout); }
+ SYS_SENDMMSG = 476 // { int|sys||sendmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags); }
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go
new file mode 100644
index 0000000..c6158a7
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go
@@ -0,0 +1,274 @@
+// mksysnum_netbsd.pl
+// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT
+
+// +build arm,netbsd
+
+package unix
+
+const (
+ SYS_EXIT = 1 // { void|sys||exit(int rval); }
+ SYS_FORK = 2 // { int|sys||fork(void); }
+ SYS_READ = 3 // { ssize_t|sys||read(int fd, void *buf, size_t nbyte); }
+ SYS_WRITE = 4 // { ssize_t|sys||write(int fd, const void *buf, size_t nbyte); }
+ SYS_OPEN = 5 // { int|sys||open(const char *path, int flags, ... mode_t mode); }
+ SYS_CLOSE = 6 // { int|sys||close(int fd); }
+ SYS_LINK = 9 // { int|sys||link(const char *path, const char *link); }
+ SYS_UNLINK = 10 // { int|sys||unlink(const char *path); }
+ SYS_CHDIR = 12 // { int|sys||chdir(const char *path); }
+ SYS_FCHDIR = 13 // { int|sys||fchdir(int fd); }
+ SYS_CHMOD = 15 // { int|sys||chmod(const char *path, mode_t mode); }
+ SYS_CHOWN = 16 // { int|sys||chown(const char *path, uid_t uid, gid_t gid); }
+ SYS_BREAK = 17 // { int|sys||obreak(char *nsize); }
+ SYS_GETPID = 20 // { pid_t|sys||getpid_with_ppid(void); }
+ SYS_UNMOUNT = 22 // { int|sys||unmount(const char *path, int flags); }
+ SYS_SETUID = 23 // { int|sys||setuid(uid_t uid); }
+ SYS_GETUID = 24 // { uid_t|sys||getuid_with_euid(void); }
+ SYS_GETEUID = 25 // { uid_t|sys||geteuid(void); }
+ SYS_PTRACE = 26 // { int|sys||ptrace(int req, pid_t pid, void *addr, int data); }
+ SYS_RECVMSG = 27 // { ssize_t|sys||recvmsg(int s, struct msghdr *msg, int flags); }
+ SYS_SENDMSG = 28 // { ssize_t|sys||sendmsg(int s, const struct msghdr *msg, int flags); }
+ SYS_RECVFROM = 29 // { ssize_t|sys||recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlenaddr); }
+ SYS_ACCEPT = 30 // { int|sys||accept(int s, struct sockaddr *name, socklen_t *anamelen); }
+ SYS_GETPEERNAME = 31 // { int|sys||getpeername(int fdes, struct sockaddr *asa, socklen_t *alen); }
+ SYS_GETSOCKNAME = 32 // { int|sys||getsockname(int fdes, struct sockaddr *asa, socklen_t *alen); }
+ SYS_ACCESS = 33 // { int|sys||access(const char *path, int flags); }
+ SYS_CHFLAGS = 34 // { int|sys||chflags(const char *path, u_long flags); }
+ SYS_FCHFLAGS = 35 // { int|sys||fchflags(int fd, u_long flags); }
+ SYS_SYNC = 36 // { void|sys||sync(void); }
+ SYS_KILL = 37 // { int|sys||kill(pid_t pid, int signum); }
+ SYS_GETPPID = 39 // { pid_t|sys||getppid(void); }
+ SYS_DUP = 41 // { int|sys||dup(int fd); }
+ SYS_PIPE = 42 // { int|sys||pipe(void); }
+ SYS_GETEGID = 43 // { gid_t|sys||getegid(void); }
+ SYS_PROFIL = 44 // { int|sys||profil(char *samples, size_t size, u_long offset, u_int scale); }
+ SYS_KTRACE = 45 // { int|sys||ktrace(const char *fname, int ops, int facs, pid_t pid); }
+ SYS_GETGID = 47 // { gid_t|sys||getgid_with_egid(void); }
+ SYS___GETLOGIN = 49 // { int|sys||__getlogin(char *namebuf, size_t namelen); }
+ SYS___SETLOGIN = 50 // { int|sys||__setlogin(const char *namebuf); }
+ SYS_ACCT = 51 // { int|sys||acct(const char *path); }
+ SYS_IOCTL = 54 // { int|sys||ioctl(int fd, u_long com, ... void *data); }
+ SYS_REVOKE = 56 // { int|sys||revoke(const char *path); }
+ SYS_SYMLINK = 57 // { int|sys||symlink(const char *path, const char *link); }
+ SYS_READLINK = 58 // { ssize_t|sys||readlink(const char *path, char *buf, size_t count); }
+ SYS_EXECVE = 59 // { int|sys||execve(const char *path, char * const *argp, char * const *envp); }
+ SYS_UMASK = 60 // { mode_t|sys||umask(mode_t newmask); }
+ SYS_CHROOT = 61 // { int|sys||chroot(const char *path); }
+ SYS_VFORK = 66 // { int|sys||vfork(void); }
+ SYS_SBRK = 69 // { int|sys||sbrk(intptr_t incr); }
+ SYS_SSTK = 70 // { int|sys||sstk(int incr); }
+ SYS_VADVISE = 72 // { int|sys||ovadvise(int anom); }
+ SYS_MUNMAP = 73 // { int|sys||munmap(void *addr, size_t len); }
+ SYS_MPROTECT = 74 // { int|sys||mprotect(void *addr, size_t len, int prot); }
+ SYS_MADVISE = 75 // { int|sys||madvise(void *addr, size_t len, int behav); }
+ SYS_MINCORE = 78 // { int|sys||mincore(void *addr, size_t len, char *vec); }
+ SYS_GETGROUPS = 79 // { int|sys||getgroups(int gidsetsize, gid_t *gidset); }
+ SYS_SETGROUPS = 80 // { int|sys||setgroups(int gidsetsize, const gid_t *gidset); }
+ SYS_GETPGRP = 81 // { int|sys||getpgrp(void); }
+ SYS_SETPGID = 82 // { int|sys||setpgid(pid_t pid, pid_t pgid); }
+ SYS_DUP2 = 90 // { int|sys||dup2(int from, int to); }
+ SYS_FCNTL = 92 // { int|sys||fcntl(int fd, int cmd, ... void *arg); }
+ SYS_FSYNC = 95 // { int|sys||fsync(int fd); }
+ SYS_SETPRIORITY = 96 // { int|sys||setpriority(int which, id_t who, int prio); }
+ SYS_CONNECT = 98 // { int|sys||connect(int s, const struct sockaddr *name, socklen_t namelen); }
+ SYS_GETPRIORITY = 100 // { int|sys||getpriority(int which, id_t who); }
+ SYS_BIND = 104 // { int|sys||bind(int s, const struct sockaddr *name, socklen_t namelen); }
+ SYS_SETSOCKOPT = 105 // { int|sys||setsockopt(int s, int level, int name, const void *val, socklen_t valsize); }
+ SYS_LISTEN = 106 // { int|sys||listen(int s, int backlog); }
+ SYS_GETSOCKOPT = 118 // { int|sys||getsockopt(int s, int level, int name, void *val, socklen_t *avalsize); }
+ SYS_READV = 120 // { ssize_t|sys||readv(int fd, const struct iovec *iovp, int iovcnt); }
+ SYS_WRITEV = 121 // { ssize_t|sys||writev(int fd, const struct iovec *iovp, int iovcnt); }
+ SYS_FCHOWN = 123 // { int|sys||fchown(int fd, uid_t uid, gid_t gid); }
+ SYS_FCHMOD = 124 // { int|sys||fchmod(int fd, mode_t mode); }
+ SYS_SETREUID = 126 // { int|sys||setreuid(uid_t ruid, uid_t euid); }
+ SYS_SETREGID = 127 // { int|sys||setregid(gid_t rgid, gid_t egid); }
+ SYS_RENAME = 128 // { int|sys||rename(const char *from, const char *to); }
+ SYS_FLOCK = 131 // { int|sys||flock(int fd, int how); }
+ SYS_MKFIFO = 132 // { int|sys||mkfifo(const char *path, mode_t mode); }
+ SYS_SENDTO = 133 // { ssize_t|sys||sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); }
+ SYS_SHUTDOWN = 134 // { int|sys||shutdown(int s, int how); }
+ SYS_SOCKETPAIR = 135 // { int|sys||socketpair(int domain, int type, int protocol, int *rsv); }
+ SYS_MKDIR = 136 // { int|sys||mkdir(const char *path, mode_t mode); }
+ SYS_RMDIR = 137 // { int|sys||rmdir(const char *path); }
+ SYS_SETSID = 147 // { int|sys||setsid(void); }
+ SYS_SYSARCH = 165 // { int|sys||sysarch(int op, void *parms); }
+ SYS_PREAD = 173 // { ssize_t|sys||pread(int fd, void *buf, size_t nbyte, int PAD, off_t offset); }
+ SYS_PWRITE = 174 // { ssize_t|sys||pwrite(int fd, const void *buf, size_t nbyte, int PAD, off_t offset); }
+ SYS_NTP_ADJTIME = 176 // { int|sys||ntp_adjtime(struct timex *tp); }
+ SYS_SETGID = 181 // { int|sys||setgid(gid_t gid); }
+ SYS_SETEGID = 182 // { int|sys||setegid(gid_t egid); }
+ SYS_SETEUID = 183 // { int|sys||seteuid(uid_t euid); }
+ SYS_PATHCONF = 191 // { long|sys||pathconf(const char *path, int name); }
+ SYS_FPATHCONF = 192 // { long|sys||fpathconf(int fd, int name); }
+ SYS_GETRLIMIT = 194 // { int|sys||getrlimit(int which, struct rlimit *rlp); }
+ SYS_SETRLIMIT = 195 // { int|sys||setrlimit(int which, const struct rlimit *rlp); }
+ SYS_MMAP = 197 // { void *|sys||mmap(void *addr, size_t len, int prot, int flags, int fd, long PAD, off_t pos); }
+ SYS_LSEEK = 199 // { off_t|sys||lseek(int fd, int PAD, off_t offset, int whence); }
+ SYS_TRUNCATE = 200 // { int|sys||truncate(const char *path, int PAD, off_t length); }
+ SYS_FTRUNCATE = 201 // { int|sys||ftruncate(int fd, int PAD, off_t length); }
+ SYS___SYSCTL = 202 // { int|sys||__sysctl(const int *name, u_int namelen, void *old, size_t *oldlenp, const void *new, size_t newlen); }
+ SYS_MLOCK = 203 // { int|sys||mlock(const void *addr, size_t len); }
+ SYS_MUNLOCK = 204 // { int|sys||munlock(const void *addr, size_t len); }
+ SYS_UNDELETE = 205 // { int|sys||undelete(const char *path); }
+ SYS_GETPGID = 207 // { pid_t|sys||getpgid(pid_t pid); }
+ SYS_REBOOT = 208 // { int|sys||reboot(int opt, char *bootstr); }
+ SYS_POLL = 209 // { int|sys||poll(struct pollfd *fds, u_int nfds, int timeout); }
+ SYS_SEMGET = 221 // { int|sys||semget(key_t key, int nsems, int semflg); }
+ SYS_SEMOP = 222 // { int|sys||semop(int semid, struct sembuf *sops, size_t nsops); }
+ SYS_SEMCONFIG = 223 // { int|sys||semconfig(int flag); }
+ SYS_MSGGET = 225 // { int|sys||msgget(key_t key, int msgflg); }
+ SYS_MSGSND = 226 // { int|sys||msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); }
+ SYS_MSGRCV = 227 // { ssize_t|sys||msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); }
+ SYS_SHMAT = 228 // { void *|sys||shmat(int shmid, const void *shmaddr, int shmflg); }
+ SYS_SHMDT = 230 // { int|sys||shmdt(const void *shmaddr); }
+ SYS_SHMGET = 231 // { int|sys||shmget(key_t key, size_t size, int shmflg); }
+ SYS_TIMER_CREATE = 235 // { int|sys||timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); }
+ SYS_TIMER_DELETE = 236 // { int|sys||timer_delete(timer_t timerid); }
+ SYS_TIMER_GETOVERRUN = 239 // { int|sys||timer_getoverrun(timer_t timerid); }
+ SYS_FDATASYNC = 241 // { int|sys||fdatasync(int fd); }
+ SYS_MLOCKALL = 242 // { int|sys||mlockall(int flags); }
+ SYS_MUNLOCKALL = 243 // { int|sys||munlockall(void); }
+ SYS_SIGQUEUEINFO = 245 // { int|sys||sigqueueinfo(pid_t pid, const siginfo_t *info); }
+ SYS_MODCTL = 246 // { int|sys||modctl(int cmd, void *arg); }
+ SYS___POSIX_RENAME = 270 // { int|sys||__posix_rename(const char *from, const char *to); }
+ SYS_SWAPCTL = 271 // { int|sys||swapctl(int cmd, void *arg, int misc); }
+ SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); }
+ SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); }
+ SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); }
+ SYS_MSYNC = 277 // { int|sys|13|msync(void *addr, size_t len, int flags); }
+ SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); }
+ SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); }
+ SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); }
+ SYS_GETSID = 286 // { pid_t|sys||getsid(pid_t pid); }
+ SYS___CLONE = 287 // { pid_t|sys||__clone(int flags, void *stack); }
+ SYS_FKTRACE = 288 // { int|sys||fktrace(int fd, int ops, int facs, pid_t pid); }
+ SYS_PREADV = 289 // { ssize_t|sys||preadv(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); }
+ SYS_PWRITEV = 290 // { ssize_t|sys||pwritev(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); }
+ SYS___GETCWD = 296 // { int|sys||__getcwd(char *bufp, size_t length); }
+ SYS_FCHROOT = 297 // { int|sys||fchroot(int fd); }
+ SYS_LCHFLAGS = 304 // { int|sys||lchflags(const char *path, u_long flags); }
+ SYS_ISSETUGID = 305 // { int|sys||issetugid(void); }
+ SYS_UTRACE = 306 // { int|sys||utrace(const char *label, void *addr, size_t len); }
+ SYS_GETCONTEXT = 307 // { int|sys||getcontext(struct __ucontext *ucp); }
+ SYS_SETCONTEXT = 308 // { int|sys||setcontext(const struct __ucontext *ucp); }
+ SYS__LWP_CREATE = 309 // { int|sys||_lwp_create(const struct __ucontext *ucp, u_long flags, lwpid_t *new_lwp); }
+ SYS__LWP_EXIT = 310 // { int|sys||_lwp_exit(void); }
+ SYS__LWP_SELF = 311 // { lwpid_t|sys||_lwp_self(void); }
+ SYS__LWP_WAIT = 312 // { int|sys||_lwp_wait(lwpid_t wait_for, lwpid_t *departed); }
+ SYS__LWP_SUSPEND = 313 // { int|sys||_lwp_suspend(lwpid_t target); }
+ SYS__LWP_CONTINUE = 314 // { int|sys||_lwp_continue(lwpid_t target); }
+ SYS__LWP_WAKEUP = 315 // { int|sys||_lwp_wakeup(lwpid_t target); }
+ SYS__LWP_GETPRIVATE = 316 // { void *|sys||_lwp_getprivate(void); }
+ SYS__LWP_SETPRIVATE = 317 // { void|sys||_lwp_setprivate(void *ptr); }
+ SYS__LWP_KILL = 318 // { int|sys||_lwp_kill(lwpid_t target, int signo); }
+ SYS__LWP_DETACH = 319 // { int|sys||_lwp_detach(lwpid_t target); }
+ SYS__LWP_UNPARK = 321 // { int|sys||_lwp_unpark(lwpid_t target, const void *hint); }
+ SYS__LWP_UNPARK_ALL = 322 // { ssize_t|sys||_lwp_unpark_all(const lwpid_t *targets, size_t ntargets, const void *hint); }
+ SYS__LWP_SETNAME = 323 // { int|sys||_lwp_setname(lwpid_t target, const char *name); }
+ SYS__LWP_GETNAME = 324 // { int|sys||_lwp_getname(lwpid_t target, char *name, size_t len); }
+ SYS__LWP_CTL = 325 // { int|sys||_lwp_ctl(int features, struct lwpctl **address); }
+ SYS___SIGACTION_SIGTRAMP = 340 // { int|sys||__sigaction_sigtramp(int signum, const struct sigaction *nsa, struct sigaction *osa, const void *tramp, int vers); }
+ SYS_PMC_GET_INFO = 341 // { int|sys||pmc_get_info(int ctr, int op, void *args); }
+ SYS_PMC_CONTROL = 342 // { int|sys||pmc_control(int ctr, int op, void *args); }
+ SYS_RASCTL = 343 // { int|sys||rasctl(void *addr, size_t len, int op); }
+ SYS_KQUEUE = 344 // { int|sys||kqueue(void); }
+ SYS__SCHED_SETPARAM = 346 // { int|sys||_sched_setparam(pid_t pid, lwpid_t lid, int policy, const struct sched_param *params); }
+ SYS__SCHED_GETPARAM = 347 // { int|sys||_sched_getparam(pid_t pid, lwpid_t lid, int *policy, struct sched_param *params); }
+ SYS__SCHED_SETAFFINITY = 348 // { int|sys||_sched_setaffinity(pid_t pid, lwpid_t lid, size_t size, const cpuset_t *cpuset); }
+ SYS__SCHED_GETAFFINITY = 349 // { int|sys||_sched_getaffinity(pid_t pid, lwpid_t lid, size_t size, cpuset_t *cpuset); }
+ SYS_SCHED_YIELD = 350 // { int|sys||sched_yield(void); }
+ SYS_FSYNC_RANGE = 354 // { int|sys||fsync_range(int fd, int flags, off_t start, off_t length); }
+ SYS_UUIDGEN = 355 // { int|sys||uuidgen(struct uuid *store, int count); }
+ SYS_GETVFSSTAT = 356 // { int|sys||getvfsstat(struct statvfs *buf, size_t bufsize, int flags); }
+ SYS_STATVFS1 = 357 // { int|sys||statvfs1(const char *path, struct statvfs *buf, int flags); }
+ SYS_FSTATVFS1 = 358 // { int|sys||fstatvfs1(int fd, struct statvfs *buf, int flags); }
+ SYS_EXTATTRCTL = 360 // { int|sys||extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_SET_FILE = 361 // { int|sys||extattr_set_file(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); }
+ SYS_EXTATTR_GET_FILE = 362 // { ssize_t|sys||extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
+ SYS_EXTATTR_DELETE_FILE = 363 // { int|sys||extattr_delete_file(const char *path, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_SET_FD = 364 // { int|sys||extattr_set_fd(int fd, int attrnamespace, const char *attrname, const void *data, size_t nbytes); }
+ SYS_EXTATTR_GET_FD = 365 // { ssize_t|sys||extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
+ SYS_EXTATTR_DELETE_FD = 366 // { int|sys||extattr_delete_fd(int fd, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_SET_LINK = 367 // { int|sys||extattr_set_link(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); }
+ SYS_EXTATTR_GET_LINK = 368 // { ssize_t|sys||extattr_get_link(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); }
+ SYS_EXTATTR_DELETE_LINK = 369 // { int|sys||extattr_delete_link(const char *path, int attrnamespace, const char *attrname); }
+ SYS_EXTATTR_LIST_FD = 370 // { ssize_t|sys||extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); }
+ SYS_EXTATTR_LIST_FILE = 371 // { ssize_t|sys||extattr_list_file(const char *path, int attrnamespace, void *data, size_t nbytes); }
+ SYS_EXTATTR_LIST_LINK = 372 // { ssize_t|sys||extattr_list_link(const char *path, int attrnamespace, void *data, size_t nbytes); }
+ SYS_SETXATTR = 375 // { int|sys||setxattr(const char *path, const char *name, const void *value, size_t size, int flags); }
+ SYS_LSETXATTR = 376 // { int|sys||lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags); }
+ SYS_FSETXATTR = 377 // { int|sys||fsetxattr(int fd, const char *name, const void *value, size_t size, int flags); }
+ SYS_GETXATTR = 378 // { int|sys||getxattr(const char *path, const char *name, void *value, size_t size); }
+ SYS_LGETXATTR = 379 // { int|sys||lgetxattr(const char *path, const char *name, void *value, size_t size); }
+ SYS_FGETXATTR = 380 // { int|sys||fgetxattr(int fd, const char *name, void *value, size_t size); }
+ SYS_LISTXATTR = 381 // { int|sys||listxattr(const char *path, char *list, size_t size); }
+ SYS_LLISTXATTR = 382 // { int|sys||llistxattr(const char *path, char *list, size_t size); }
+ SYS_FLISTXATTR = 383 // { int|sys||flistxattr(int fd, char *list, size_t size); }
+ SYS_REMOVEXATTR = 384 // { int|sys||removexattr(const char *path, const char *name); }
+ SYS_LREMOVEXATTR = 385 // { int|sys||lremovexattr(const char *path, const char *name); }
+ SYS_FREMOVEXATTR = 386 // { int|sys||fremovexattr(int fd, const char *name); }
+ SYS_GETDENTS = 390 // { int|sys|30|getdents(int fd, char *buf, size_t count); }
+ SYS_SOCKET = 394 // { int|sys|30|socket(int domain, int type, int protocol); }
+ SYS_GETFH = 395 // { int|sys|30|getfh(const char *fname, void *fhp, size_t *fh_size); }
+ SYS_MOUNT = 410 // { int|sys|50|mount(const char *type, const char *path, int flags, void *data, size_t data_len); }
+ SYS_MREMAP = 411 // { void *|sys||mremap(void *old_address, size_t old_size, void *new_address, size_t new_size, int flags); }
+ SYS_PSET_CREATE = 412 // { int|sys||pset_create(psetid_t *psid); }
+ SYS_PSET_DESTROY = 413 // { int|sys||pset_destroy(psetid_t psid); }
+ SYS_PSET_ASSIGN = 414 // { int|sys||pset_assign(psetid_t psid, cpuid_t cpuid, psetid_t *opsid); }
+ SYS__PSET_BIND = 415 // { int|sys||_pset_bind(idtype_t idtype, id_t first_id, id_t second_id, psetid_t psid, psetid_t *opsid); }
+ SYS_POSIX_FADVISE = 416 // { int|sys|50|posix_fadvise(int fd, int PAD, off_t offset, off_t len, int advice); }
+ SYS_SELECT = 417 // { int|sys|50|select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); }
+ SYS_GETTIMEOFDAY = 418 // { int|sys|50|gettimeofday(struct timeval *tp, void *tzp); }
+ SYS_SETTIMEOFDAY = 419 // { int|sys|50|settimeofday(const struct timeval *tv, const void *tzp); }
+ SYS_UTIMES = 420 // { int|sys|50|utimes(const char *path, const struct timeval *tptr); }
+ SYS_ADJTIME = 421 // { int|sys|50|adjtime(const struct timeval *delta, struct timeval *olddelta); }
+ SYS_FUTIMES = 423 // { int|sys|50|futimes(int fd, const struct timeval *tptr); }
+ SYS_LUTIMES = 424 // { int|sys|50|lutimes(const char *path, const struct timeval *tptr); }
+ SYS_SETITIMER = 425 // { int|sys|50|setitimer(int which, const struct itimerval *itv, struct itimerval *oitv); }
+ SYS_GETITIMER = 426 // { int|sys|50|getitimer(int which, struct itimerval *itv); }
+ SYS_CLOCK_GETTIME = 427 // { int|sys|50|clock_gettime(clockid_t clock_id, struct timespec *tp); }
+ SYS_CLOCK_SETTIME = 428 // { int|sys|50|clock_settime(clockid_t clock_id, const struct timespec *tp); }
+ SYS_CLOCK_GETRES = 429 // { int|sys|50|clock_getres(clockid_t clock_id, struct timespec *tp); }
+ SYS_NANOSLEEP = 430 // { int|sys|50|nanosleep(const struct timespec *rqtp, struct timespec *rmtp); }
+ SYS___SIGTIMEDWAIT = 431 // { int|sys|50|__sigtimedwait(const sigset_t *set, siginfo_t *info, struct timespec *timeout); }
+ SYS__LWP_PARK = 434 // { int|sys|50|_lwp_park(const struct timespec *ts, lwpid_t unpark, const void *hint, const void *unparkhint); }
+ SYS_KEVENT = 435 // { int|sys|50|kevent(int fd, const struct kevent *changelist, size_t nchanges, struct kevent *eventlist, size_t nevents, const struct timespec *timeout); }
+ SYS_PSELECT = 436 // { int|sys|50|pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *mask); }
+ SYS_POLLTS = 437 // { int|sys|50|pollts(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *mask); }
+ SYS_STAT = 439 // { int|sys|50|stat(const char *path, struct stat *ub); }
+ SYS_FSTAT = 440 // { int|sys|50|fstat(int fd, struct stat *sb); }
+ SYS_LSTAT = 441 // { int|sys|50|lstat(const char *path, struct stat *ub); }
+ SYS___SEMCTL = 442 // { int|sys|50|__semctl(int semid, int semnum, int cmd, ... union __semun *arg); }
+ SYS_SHMCTL = 443 // { int|sys|50|shmctl(int shmid, int cmd, struct shmid_ds *buf); }
+ SYS_MSGCTL = 444 // { int|sys|50|msgctl(int msqid, int cmd, struct msqid_ds *buf); }
+ SYS_GETRUSAGE = 445 // { int|sys|50|getrusage(int who, struct rusage *rusage); }
+ SYS_TIMER_SETTIME = 446 // { int|sys|50|timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); }
+ SYS_TIMER_GETTIME = 447 // { int|sys|50|timer_gettime(timer_t timerid, struct itimerspec *value); }
+ SYS_NTP_GETTIME = 448 // { int|sys|50|ntp_gettime(struct ntptimeval *ntvp); }
+ SYS_WAIT4 = 449 // { int|sys|50|wait4(pid_t pid, int *status, int options, struct rusage *rusage); }
+ SYS_MKNOD = 450 // { int|sys|50|mknod(const char *path, mode_t mode, dev_t dev); }
+ SYS_FHSTAT = 451 // { int|sys|50|fhstat(const void *fhp, size_t fh_size, struct stat *sb); }
+ SYS_PIPE2 = 453 // { int|sys||pipe2(int *fildes, int flags); }
+ SYS_DUP3 = 454 // { int|sys||dup3(int from, int to, int flags); }
+ SYS_KQUEUE1 = 455 // { int|sys||kqueue1(int flags); }
+ SYS_PACCEPT = 456 // { int|sys||paccept(int s, struct sockaddr *name, socklen_t *anamelen, const sigset_t *mask, int flags); }
+ SYS_LINKAT = 457 // { int|sys||linkat(int fd1, const char *name1, int fd2, const char *name2, int flags); }
+ SYS_RENAMEAT = 458 // { int|sys||renameat(int fromfd, const char *from, int tofd, const char *to); }
+ SYS_MKFIFOAT = 459 // { int|sys||mkfifoat(int fd, const char *path, mode_t mode); }
+ SYS_MKNODAT = 460 // { int|sys||mknodat(int fd, const char *path, mode_t mode, uint32_t dev); }
+ SYS_MKDIRAT = 461 // { int|sys||mkdirat(int fd, const char *path, mode_t mode); }
+ SYS_FACCESSAT = 462 // { int|sys||faccessat(int fd, const char *path, int amode, int flag); }
+ SYS_FCHMODAT = 463 // { int|sys||fchmodat(int fd, const char *path, mode_t mode, int flag); }
+ SYS_FCHOWNAT = 464 // { int|sys||fchownat(int fd, const char *path, uid_t owner, gid_t group, int flag); }
+ SYS_FEXECVE = 465 // { int|sys||fexecve(int fd, char * const *argp, char * const *envp); }
+ SYS_FSTATAT = 466 // { int|sys||fstatat(int fd, const char *path, struct stat *buf, int flag); }
+ SYS_UTIMENSAT = 467 // { int|sys||utimensat(int fd, const char *path, const struct timespec *tptr, int flag); }
+ SYS_OPENAT = 468 // { int|sys||openat(int fd, const char *path, int oflags, ... mode_t mode); }
+ SYS_READLINKAT = 469 // { int|sys||readlinkat(int fd, const char *path, char *buf, size_t bufsize); }
+ SYS_SYMLINKAT = 470 // { int|sys||symlinkat(const char *path1, int fd, const char *path2); }
+ SYS_UNLINKAT = 471 // { int|sys||unlinkat(int fd, const char *path, int flag); }
+ SYS_FUTIMENS = 472 // { int|sys||futimens(int fd, const struct timespec *tptr); }
+ SYS___QUOTACTL = 473 // { int|sys||__quotactl(const char *path, struct quotactl_args *args); }
+ SYS_POSIX_SPAWN = 474 // { int|sys||posix_spawn(pid_t *pid, const char *path, const struct posix_spawn_file_actions *file_actions, const struct posix_spawnattr *attrp, char *const *argv, char *const *envp); }
+ SYS_RECVMMSG = 475 // { int|sys||recvmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout); }
+ SYS_SENDMMSG = 476 // { int|sys||sendmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags); }
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go b/vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go
new file mode 100644
index 0000000..3e8ce2a
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go
@@ -0,0 +1,207 @@
+// mksysnum_openbsd.pl
+// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT
+
+// +build 386,openbsd
+
+package unix
+
+const (
+ SYS_EXIT = 1 // { void sys_exit(int rval); }
+ SYS_FORK = 2 // { int sys_fork(void); }
+ SYS_READ = 3 // { ssize_t sys_read(int fd, void *buf, size_t nbyte); }
+ SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, \
+ SYS_OPEN = 5 // { int sys_open(const char *path, \
+ SYS_CLOSE = 6 // { int sys_close(int fd); }
+ SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, \
+ SYS_LINK = 9 // { int sys_link(const char *path, const char *link); }
+ SYS_UNLINK = 10 // { int sys_unlink(const char *path); }
+ SYS_WAIT4 = 11 // { pid_t sys_wait4(pid_t pid, int *status, \
+ SYS_CHDIR = 12 // { int sys_chdir(const char *path); }
+ SYS_FCHDIR = 13 // { int sys_fchdir(int fd); }
+ SYS_MKNOD = 14 // { int sys_mknod(const char *path, mode_t mode, \
+ SYS_CHMOD = 15 // { int sys_chmod(const char *path, mode_t mode); }
+ SYS_CHOWN = 16 // { int sys_chown(const char *path, uid_t uid, \
+ SYS_OBREAK = 17 // { int sys_obreak(char *nsize); } break
+ SYS_GETDTABLECOUNT = 18 // { int sys_getdtablecount(void); }
+ SYS_GETRUSAGE = 19 // { int sys_getrusage(int who, \
+ SYS_GETPID = 20 // { pid_t sys_getpid(void); }
+ SYS_MOUNT = 21 // { int sys_mount(const char *type, const char *path, \
+ SYS_UNMOUNT = 22 // { int sys_unmount(const char *path, int flags); }
+ SYS_SETUID = 23 // { int sys_setuid(uid_t uid); }
+ SYS_GETUID = 24 // { uid_t sys_getuid(void); }
+ SYS_GETEUID = 25 // { uid_t sys_geteuid(void); }
+ SYS_PTRACE = 26 // { int sys_ptrace(int req, pid_t pid, caddr_t addr, \
+ SYS_RECVMSG = 27 // { ssize_t sys_recvmsg(int s, struct msghdr *msg, \
+ SYS_SENDMSG = 28 // { ssize_t sys_sendmsg(int s, \
+ SYS_RECVFROM = 29 // { ssize_t sys_recvfrom(int s, void *buf, size_t len, \
+ SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, \
+ SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, \
+ SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, \
+ SYS_ACCESS = 33 // { int sys_access(const char *path, int flags); }
+ SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); }
+ SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); }
+ SYS_SYNC = 36 // { void sys_sync(void); }
+ SYS_KILL = 37 // { int sys_kill(int pid, int signum); }
+ SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); }
+ SYS_GETPPID = 39 // { pid_t sys_getppid(void); }
+ SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); }
+ SYS_DUP = 41 // { int sys_dup(int fd); }
+ SYS_FSTATAT = 42 // { int sys_fstatat(int fd, const char *path, \
+ SYS_GETEGID = 43 // { gid_t sys_getegid(void); }
+ SYS_PROFIL = 44 // { int sys_profil(caddr_t samples, size_t size, \
+ SYS_KTRACE = 45 // { int sys_ktrace(const char *fname, int ops, \
+ SYS_SIGACTION = 46 // { int sys_sigaction(int signum, \
+ SYS_GETGID = 47 // { gid_t sys_getgid(void); }
+ SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); }
+ SYS_GETLOGIN = 49 // { int sys_getlogin(char *namebuf, u_int namelen); }
+ SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); }
+ SYS_ACCT = 51 // { int sys_acct(const char *path); }
+ SYS_SIGPENDING = 52 // { int sys_sigpending(void); }
+ SYS_FSTAT = 53 // { int sys_fstat(int fd, struct stat *sb); }
+ SYS_IOCTL = 54 // { int sys_ioctl(int fd, \
+ SYS_REBOOT = 55 // { int sys_reboot(int opt); }
+ SYS_REVOKE = 56 // { int sys_revoke(const char *path); }
+ SYS_SYMLINK = 57 // { int sys_symlink(const char *path, \
+ SYS_READLINK = 58 // { int sys_readlink(const char *path, char *buf, \
+ SYS_EXECVE = 59 // { int sys_execve(const char *path, \
+ SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); }
+ SYS_CHROOT = 61 // { int sys_chroot(const char *path); }
+ SYS_GETFSSTAT = 62 // { int sys_getfsstat(struct statfs *buf, size_t bufsize, \
+ SYS_STATFS = 63 // { int sys_statfs(const char *path, \
+ SYS_FSTATFS = 64 // { int sys_fstatfs(int fd, struct statfs *buf); }
+ SYS_FHSTATFS = 65 // { int sys_fhstatfs(const fhandle_t *fhp, \
+ SYS_VFORK = 66 // { int sys_vfork(void); }
+ SYS_GETTIMEOFDAY = 67 // { int sys_gettimeofday(struct timeval *tp, \
+ SYS_SETTIMEOFDAY = 68 // { int sys_settimeofday(const struct timeval *tv, \
+ SYS_SETITIMER = 69 // { int sys_setitimer(int which, \
+ SYS_GETITIMER = 70 // { int sys_getitimer(int which, \
+ SYS_SELECT = 71 // { int sys_select(int nd, fd_set *in, fd_set *ou, \
+ SYS_KEVENT = 72 // { int sys_kevent(int fd, \
+ SYS_MUNMAP = 73 // { int sys_munmap(void *addr, size_t len); }
+ SYS_MPROTECT = 74 // { int sys_mprotect(void *addr, size_t len, \
+ SYS_MADVISE = 75 // { int sys_madvise(void *addr, size_t len, \
+ SYS_UTIMES = 76 // { int sys_utimes(const char *path, \
+ SYS_FUTIMES = 77 // { int sys_futimes(int fd, \
+ SYS_MINCORE = 78 // { int sys_mincore(void *addr, size_t len, \
+ SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, \
+ SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, \
+ SYS_GETPGRP = 81 // { int sys_getpgrp(void); }
+ SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, int pgid); }
+ SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, \
+ SYS_FUTIMENS = 85 // { int sys_futimens(int fd, \
+ SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, \
+ SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, \
+ SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, \
+ SYS_DUP2 = 90 // { int sys_dup2(int from, int to); }
+ SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, \
+ SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); }
+ SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, \
+ SYS_FSYNC = 95 // { int sys_fsync(int fd); }
+ SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); }
+ SYS_SOCKET = 97 // { int sys_socket(int domain, int type, int protocol); }
+ SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, \
+ SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); }
+ SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); }
+ SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); }
+ SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, \
+ SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, \
+ SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); }
+ SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, \
+ SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \
+ SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); }
+ SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, \
+ SYS_READV = 120 // { ssize_t sys_readv(int fd, \
+ SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, \
+ SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); }
+ SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); }
+ SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); }
+ SYS_SETREGID = 127 // { int sys_setregid(gid_t rgid, gid_t egid); }
+ SYS_RENAME = 128 // { int sys_rename(const char *from, const char *to); }
+ SYS_FLOCK = 131 // { int sys_flock(int fd, int how); }
+ SYS_MKFIFO = 132 // { int sys_mkfifo(const char *path, mode_t mode); }
+ SYS_SENDTO = 133 // { ssize_t sys_sendto(int s, const void *buf, \
+ SYS_SHUTDOWN = 134 // { int sys_shutdown(int s, int how); }
+ SYS_SOCKETPAIR = 135 // { int sys_socketpair(int domain, int type, \
+ SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); }
+ SYS_RMDIR = 137 // { int sys_rmdir(const char *path); }
+ SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, \
+ SYS_SETSID = 147 // { int sys_setsid(void); }
+ SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, \
+ SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); }
+ SYS_GETFH = 161 // { int sys_getfh(const char *fname, fhandle_t *fhp); }
+ SYS_SYSARCH = 165 // { int sys_sysarch(int op, void *parms); }
+ SYS_PREAD = 173 // { ssize_t sys_pread(int fd, void *buf, \
+ SYS_PWRITE = 174 // { ssize_t sys_pwrite(int fd, const void *buf, \
+ SYS_SETGID = 181 // { int sys_setgid(gid_t gid); }
+ SYS_SETEGID = 182 // { int sys_setegid(gid_t egid); }
+ SYS_SETEUID = 183 // { int sys_seteuid(uid_t euid); }
+ SYS_PATHCONF = 191 // { long sys_pathconf(const char *path, int name); }
+ SYS_FPATHCONF = 192 // { long sys_fpathconf(int fd, int name); }
+ SYS_SWAPCTL = 193 // { int sys_swapctl(int cmd, const void *arg, int misc); }
+ SYS_GETRLIMIT = 194 // { int sys_getrlimit(int which, \
+ SYS_SETRLIMIT = 195 // { int sys_setrlimit(int which, \
+ SYS_MMAP = 197 // { void *sys_mmap(void *addr, size_t len, int prot, \
+ SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, \
+ SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, \
+ SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); }
+ SYS___SYSCTL = 202 // { int sys___sysctl(const int *name, u_int namelen, \
+ SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); }
+ SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); }
+ SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); }
+ SYS_UTRACE = 209 // { int sys_utrace(const char *label, const void *addr, \
+ SYS_SEMGET = 221 // { int sys_semget(key_t key, int nsems, int semflg); }
+ SYS_MSGGET = 225 // { int sys_msgget(key_t key, int msgflg); }
+ SYS_MSGSND = 226 // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, \
+ SYS_MSGRCV = 227 // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, \
+ SYS_SHMAT = 228 // { void *sys_shmat(int shmid, const void *shmaddr, \
+ SYS_SHMDT = 230 // { int sys_shmdt(const void *shmaddr); }
+ SYS_MINHERIT = 250 // { int sys_minherit(void *addr, size_t len, \
+ SYS_POLL = 252 // { int sys_poll(struct pollfd *fds, \
+ SYS_ISSETUGID = 253 // { int sys_issetugid(void); }
+ SYS_LCHOWN = 254 // { int sys_lchown(const char *path, uid_t uid, gid_t gid); }
+ SYS_GETSID = 255 // { pid_t sys_getsid(pid_t pid); }
+ SYS_MSYNC = 256 // { int sys_msync(void *addr, size_t len, int flags); }
+ SYS_PIPE = 263 // { int sys_pipe(int *fdp); }
+ SYS_FHOPEN = 264 // { int sys_fhopen(const fhandle_t *fhp, int flags); }
+ SYS_PREADV = 267 // { ssize_t sys_preadv(int fd, \
+ SYS_PWRITEV = 268 // { ssize_t sys_pwritev(int fd, \
+ SYS_KQUEUE = 269 // { int sys_kqueue(void); }
+ SYS_MLOCKALL = 271 // { int sys_mlockall(int flags); }
+ SYS_MUNLOCKALL = 272 // { int sys_munlockall(void); }
+ SYS_GETRESUID = 281 // { int sys_getresuid(uid_t *ruid, uid_t *euid, \
+ SYS_SETRESUID = 282 // { int sys_setresuid(uid_t ruid, uid_t euid, \
+ SYS_GETRESGID = 283 // { int sys_getresgid(gid_t *rgid, gid_t *egid, \
+ SYS_SETRESGID = 284 // { int sys_setresgid(gid_t rgid, gid_t egid, \
+ SYS_MQUERY = 286 // { void *sys_mquery(void *addr, size_t len, int prot, \
+ SYS_CLOSEFROM = 287 // { int sys_closefrom(int fd); }
+ SYS_SIGALTSTACK = 288 // { int sys_sigaltstack(const struct sigaltstack *nss, \
+ SYS_SHMGET = 289 // { int sys_shmget(key_t key, size_t size, int shmflg); }
+ SYS_SEMOP = 290 // { int sys_semop(int semid, struct sembuf *sops, \
+ SYS_FHSTAT = 294 // { int sys_fhstat(const fhandle_t *fhp, \
+ SYS___SEMCTL = 295 // { int sys___semctl(int semid, int semnum, int cmd, \
+ SYS_SHMCTL = 296 // { int sys_shmctl(int shmid, int cmd, \
+ SYS_MSGCTL = 297 // { int sys_msgctl(int msqid, int cmd, \
+ SYS_SCHED_YIELD = 298 // { int sys_sched_yield(void); }
+ SYS_GETTHRID = 299 // { pid_t sys_getthrid(void); }
+ SYS___THRWAKEUP = 301 // { int sys___thrwakeup(const volatile void *ident, \
+ SYS___THREXIT = 302 // { void sys___threxit(pid_t *notdead); }
+ SYS___THRSIGDIVERT = 303 // { int sys___thrsigdivert(sigset_t sigmask, \
+ SYS___GETCWD = 304 // { int sys___getcwd(char *buf, size_t len); }
+ SYS_ADJFREQ = 305 // { int sys_adjfreq(const int64_t *freq, \
+ SYS_SETRTABLE = 310 // { int sys_setrtable(int rtableid); }
+ SYS_GETRTABLE = 311 // { int sys_getrtable(void); }
+ SYS_FACCESSAT = 313 // { int sys_faccessat(int fd, const char *path, \
+ SYS_FCHMODAT = 314 // { int sys_fchmodat(int fd, const char *path, \
+ SYS_FCHOWNAT = 315 // { int sys_fchownat(int fd, const char *path, \
+ SYS_LINKAT = 317 // { int sys_linkat(int fd1, const char *path1, int fd2, \
+ SYS_MKDIRAT = 318 // { int sys_mkdirat(int fd, const char *path, \
+ SYS_MKFIFOAT = 319 // { int sys_mkfifoat(int fd, const char *path, \
+ SYS_MKNODAT = 320 // { int sys_mknodat(int fd, const char *path, \
+ SYS_OPENAT = 321 // { int sys_openat(int fd, const char *path, int flags, \
+ SYS_READLINKAT = 322 // { ssize_t sys_readlinkat(int fd, const char *path, \
+ SYS_RENAMEAT = 323 // { int sys_renameat(int fromfd, const char *from, \
+ SYS_SYMLINKAT = 324 // { int sys_symlinkat(const char *path, int fd, \
+ SYS_UNLINKAT = 325 // { int sys_unlinkat(int fd, const char *path, \
+ SYS___SET_TCB = 329 // { void sys___set_tcb(void *tcb); }
+ SYS___GET_TCB = 330 // { void *sys___get_tcb(void); }
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go
new file mode 100644
index 0000000..bd28146
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go
@@ -0,0 +1,207 @@
+// mksysnum_openbsd.pl
+// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT
+
+// +build amd64,openbsd
+
+package unix
+
+const (
+ SYS_EXIT = 1 // { void sys_exit(int rval); }
+ SYS_FORK = 2 // { int sys_fork(void); }
+ SYS_READ = 3 // { ssize_t sys_read(int fd, void *buf, size_t nbyte); }
+ SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, \
+ SYS_OPEN = 5 // { int sys_open(const char *path, \
+ SYS_CLOSE = 6 // { int sys_close(int fd); }
+ SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, \
+ SYS_LINK = 9 // { int sys_link(const char *path, const char *link); }
+ SYS_UNLINK = 10 // { int sys_unlink(const char *path); }
+ SYS_WAIT4 = 11 // { pid_t sys_wait4(pid_t pid, int *status, \
+ SYS_CHDIR = 12 // { int sys_chdir(const char *path); }
+ SYS_FCHDIR = 13 // { int sys_fchdir(int fd); }
+ SYS_MKNOD = 14 // { int sys_mknod(const char *path, mode_t mode, \
+ SYS_CHMOD = 15 // { int sys_chmod(const char *path, mode_t mode); }
+ SYS_CHOWN = 16 // { int sys_chown(const char *path, uid_t uid, \
+ SYS_OBREAK = 17 // { int sys_obreak(char *nsize); } break
+ SYS_GETDTABLECOUNT = 18 // { int sys_getdtablecount(void); }
+ SYS_GETRUSAGE = 19 // { int sys_getrusage(int who, \
+ SYS_GETPID = 20 // { pid_t sys_getpid(void); }
+ SYS_MOUNT = 21 // { int sys_mount(const char *type, const char *path, \
+ SYS_UNMOUNT = 22 // { int sys_unmount(const char *path, int flags); }
+ SYS_SETUID = 23 // { int sys_setuid(uid_t uid); }
+ SYS_GETUID = 24 // { uid_t sys_getuid(void); }
+ SYS_GETEUID = 25 // { uid_t sys_geteuid(void); }
+ SYS_PTRACE = 26 // { int sys_ptrace(int req, pid_t pid, caddr_t addr, \
+ SYS_RECVMSG = 27 // { ssize_t sys_recvmsg(int s, struct msghdr *msg, \
+ SYS_SENDMSG = 28 // { ssize_t sys_sendmsg(int s, \
+ SYS_RECVFROM = 29 // { ssize_t sys_recvfrom(int s, void *buf, size_t len, \
+ SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, \
+ SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, \
+ SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, \
+ SYS_ACCESS = 33 // { int sys_access(const char *path, int flags); }
+ SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); }
+ SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); }
+ SYS_SYNC = 36 // { void sys_sync(void); }
+ SYS_KILL = 37 // { int sys_kill(int pid, int signum); }
+ SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); }
+ SYS_GETPPID = 39 // { pid_t sys_getppid(void); }
+ SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); }
+ SYS_DUP = 41 // { int sys_dup(int fd); }
+ SYS_FSTATAT = 42 // { int sys_fstatat(int fd, const char *path, \
+ SYS_GETEGID = 43 // { gid_t sys_getegid(void); }
+ SYS_PROFIL = 44 // { int sys_profil(caddr_t samples, size_t size, \
+ SYS_KTRACE = 45 // { int sys_ktrace(const char *fname, int ops, \
+ SYS_SIGACTION = 46 // { int sys_sigaction(int signum, \
+ SYS_GETGID = 47 // { gid_t sys_getgid(void); }
+ SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); }
+ SYS_GETLOGIN = 49 // { int sys_getlogin(char *namebuf, u_int namelen); }
+ SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); }
+ SYS_ACCT = 51 // { int sys_acct(const char *path); }
+ SYS_SIGPENDING = 52 // { int sys_sigpending(void); }
+ SYS_FSTAT = 53 // { int sys_fstat(int fd, struct stat *sb); }
+ SYS_IOCTL = 54 // { int sys_ioctl(int fd, \
+ SYS_REBOOT = 55 // { int sys_reboot(int opt); }
+ SYS_REVOKE = 56 // { int sys_revoke(const char *path); }
+ SYS_SYMLINK = 57 // { int sys_symlink(const char *path, \
+ SYS_READLINK = 58 // { int sys_readlink(const char *path, char *buf, \
+ SYS_EXECVE = 59 // { int sys_execve(const char *path, \
+ SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); }
+ SYS_CHROOT = 61 // { int sys_chroot(const char *path); }
+ SYS_GETFSSTAT = 62 // { int sys_getfsstat(struct statfs *buf, size_t bufsize, \
+ SYS_STATFS = 63 // { int sys_statfs(const char *path, \
+ SYS_FSTATFS = 64 // { int sys_fstatfs(int fd, struct statfs *buf); }
+ SYS_FHSTATFS = 65 // { int sys_fhstatfs(const fhandle_t *fhp, \
+ SYS_VFORK = 66 // { int sys_vfork(void); }
+ SYS_GETTIMEOFDAY = 67 // { int sys_gettimeofday(struct timeval *tp, \
+ SYS_SETTIMEOFDAY = 68 // { int sys_settimeofday(const struct timeval *tv, \
+ SYS_SETITIMER = 69 // { int sys_setitimer(int which, \
+ SYS_GETITIMER = 70 // { int sys_getitimer(int which, \
+ SYS_SELECT = 71 // { int sys_select(int nd, fd_set *in, fd_set *ou, \
+ SYS_KEVENT = 72 // { int sys_kevent(int fd, \
+ SYS_MUNMAP = 73 // { int sys_munmap(void *addr, size_t len); }
+ SYS_MPROTECT = 74 // { int sys_mprotect(void *addr, size_t len, \
+ SYS_MADVISE = 75 // { int sys_madvise(void *addr, size_t len, \
+ SYS_UTIMES = 76 // { int sys_utimes(const char *path, \
+ SYS_FUTIMES = 77 // { int sys_futimes(int fd, \
+ SYS_MINCORE = 78 // { int sys_mincore(void *addr, size_t len, \
+ SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, \
+ SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, \
+ SYS_GETPGRP = 81 // { int sys_getpgrp(void); }
+ SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, int pgid); }
+ SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, \
+ SYS_FUTIMENS = 85 // { int sys_futimens(int fd, \
+ SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, \
+ SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, \
+ SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, \
+ SYS_DUP2 = 90 // { int sys_dup2(int from, int to); }
+ SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, \
+ SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); }
+ SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, \
+ SYS_FSYNC = 95 // { int sys_fsync(int fd); }
+ SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); }
+ SYS_SOCKET = 97 // { int sys_socket(int domain, int type, int protocol); }
+ SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, \
+ SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); }
+ SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); }
+ SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); }
+ SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, \
+ SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, \
+ SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); }
+ SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, \
+ SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \
+ SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); }
+ SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, \
+ SYS_READV = 120 // { ssize_t sys_readv(int fd, \
+ SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, \
+ SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); }
+ SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); }
+ SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); }
+ SYS_SETREGID = 127 // { int sys_setregid(gid_t rgid, gid_t egid); }
+ SYS_RENAME = 128 // { int sys_rename(const char *from, const char *to); }
+ SYS_FLOCK = 131 // { int sys_flock(int fd, int how); }
+ SYS_MKFIFO = 132 // { int sys_mkfifo(const char *path, mode_t mode); }
+ SYS_SENDTO = 133 // { ssize_t sys_sendto(int s, const void *buf, \
+ SYS_SHUTDOWN = 134 // { int sys_shutdown(int s, int how); }
+ SYS_SOCKETPAIR = 135 // { int sys_socketpair(int domain, int type, \
+ SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); }
+ SYS_RMDIR = 137 // { int sys_rmdir(const char *path); }
+ SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, \
+ SYS_SETSID = 147 // { int sys_setsid(void); }
+ SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, \
+ SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); }
+ SYS_GETFH = 161 // { int sys_getfh(const char *fname, fhandle_t *fhp); }
+ SYS_SYSARCH = 165 // { int sys_sysarch(int op, void *parms); }
+ SYS_PREAD = 173 // { ssize_t sys_pread(int fd, void *buf, \
+ SYS_PWRITE = 174 // { ssize_t sys_pwrite(int fd, const void *buf, \
+ SYS_SETGID = 181 // { int sys_setgid(gid_t gid); }
+ SYS_SETEGID = 182 // { int sys_setegid(gid_t egid); }
+ SYS_SETEUID = 183 // { int sys_seteuid(uid_t euid); }
+ SYS_PATHCONF = 191 // { long sys_pathconf(const char *path, int name); }
+ SYS_FPATHCONF = 192 // { long sys_fpathconf(int fd, int name); }
+ SYS_SWAPCTL = 193 // { int sys_swapctl(int cmd, const void *arg, int misc); }
+ SYS_GETRLIMIT = 194 // { int sys_getrlimit(int which, \
+ SYS_SETRLIMIT = 195 // { int sys_setrlimit(int which, \
+ SYS_MMAP = 197 // { void *sys_mmap(void *addr, size_t len, int prot, \
+ SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, \
+ SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, \
+ SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); }
+ SYS___SYSCTL = 202 // { int sys___sysctl(const int *name, u_int namelen, \
+ SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); }
+ SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); }
+ SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); }
+ SYS_UTRACE = 209 // { int sys_utrace(const char *label, const void *addr, \
+ SYS_SEMGET = 221 // { int sys_semget(key_t key, int nsems, int semflg); }
+ SYS_MSGGET = 225 // { int sys_msgget(key_t key, int msgflg); }
+ SYS_MSGSND = 226 // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, \
+ SYS_MSGRCV = 227 // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, \
+ SYS_SHMAT = 228 // { void *sys_shmat(int shmid, const void *shmaddr, \
+ SYS_SHMDT = 230 // { int sys_shmdt(const void *shmaddr); }
+ SYS_MINHERIT = 250 // { int sys_minherit(void *addr, size_t len, \
+ SYS_POLL = 252 // { int sys_poll(struct pollfd *fds, \
+ SYS_ISSETUGID = 253 // { int sys_issetugid(void); }
+ SYS_LCHOWN = 254 // { int sys_lchown(const char *path, uid_t uid, gid_t gid); }
+ SYS_GETSID = 255 // { pid_t sys_getsid(pid_t pid); }
+ SYS_MSYNC = 256 // { int sys_msync(void *addr, size_t len, int flags); }
+ SYS_PIPE = 263 // { int sys_pipe(int *fdp); }
+ SYS_FHOPEN = 264 // { int sys_fhopen(const fhandle_t *fhp, int flags); }
+ SYS_PREADV = 267 // { ssize_t sys_preadv(int fd, \
+ SYS_PWRITEV = 268 // { ssize_t sys_pwritev(int fd, \
+ SYS_KQUEUE = 269 // { int sys_kqueue(void); }
+ SYS_MLOCKALL = 271 // { int sys_mlockall(int flags); }
+ SYS_MUNLOCKALL = 272 // { int sys_munlockall(void); }
+ SYS_GETRESUID = 281 // { int sys_getresuid(uid_t *ruid, uid_t *euid, \
+ SYS_SETRESUID = 282 // { int sys_setresuid(uid_t ruid, uid_t euid, \
+ SYS_GETRESGID = 283 // { int sys_getresgid(gid_t *rgid, gid_t *egid, \
+ SYS_SETRESGID = 284 // { int sys_setresgid(gid_t rgid, gid_t egid, \
+ SYS_MQUERY = 286 // { void *sys_mquery(void *addr, size_t len, int prot, \
+ SYS_CLOSEFROM = 287 // { int sys_closefrom(int fd); }
+ SYS_SIGALTSTACK = 288 // { int sys_sigaltstack(const struct sigaltstack *nss, \
+ SYS_SHMGET = 289 // { int sys_shmget(key_t key, size_t size, int shmflg); }
+ SYS_SEMOP = 290 // { int sys_semop(int semid, struct sembuf *sops, \
+ SYS_FHSTAT = 294 // { int sys_fhstat(const fhandle_t *fhp, \
+ SYS___SEMCTL = 295 // { int sys___semctl(int semid, int semnum, int cmd, \
+ SYS_SHMCTL = 296 // { int sys_shmctl(int shmid, int cmd, \
+ SYS_MSGCTL = 297 // { int sys_msgctl(int msqid, int cmd, \
+ SYS_SCHED_YIELD = 298 // { int sys_sched_yield(void); }
+ SYS_GETTHRID = 299 // { pid_t sys_getthrid(void); }
+ SYS___THRWAKEUP = 301 // { int sys___thrwakeup(const volatile void *ident, \
+ SYS___THREXIT = 302 // { void sys___threxit(pid_t *notdead); }
+ SYS___THRSIGDIVERT = 303 // { int sys___thrsigdivert(sigset_t sigmask, \
+ SYS___GETCWD = 304 // { int sys___getcwd(char *buf, size_t len); }
+ SYS_ADJFREQ = 305 // { int sys_adjfreq(const int64_t *freq, \
+ SYS_SETRTABLE = 310 // { int sys_setrtable(int rtableid); }
+ SYS_GETRTABLE = 311 // { int sys_getrtable(void); }
+ SYS_FACCESSAT = 313 // { int sys_faccessat(int fd, const char *path, \
+ SYS_FCHMODAT = 314 // { int sys_fchmodat(int fd, const char *path, \
+ SYS_FCHOWNAT = 315 // { int sys_fchownat(int fd, const char *path, \
+ SYS_LINKAT = 317 // { int sys_linkat(int fd1, const char *path1, int fd2, \
+ SYS_MKDIRAT = 318 // { int sys_mkdirat(int fd, const char *path, \
+ SYS_MKFIFOAT = 319 // { int sys_mkfifoat(int fd, const char *path, \
+ SYS_MKNODAT = 320 // { int sys_mknodat(int fd, const char *path, \
+ SYS_OPENAT = 321 // { int sys_openat(int fd, const char *path, int flags, \
+ SYS_READLINKAT = 322 // { ssize_t sys_readlinkat(int fd, const char *path, \
+ SYS_RENAMEAT = 323 // { int sys_renameat(int fromfd, const char *from, \
+ SYS_SYMLINKAT = 324 // { int sys_symlinkat(const char *path, int fd, \
+ SYS_UNLINKAT = 325 // { int sys_unlinkat(int fd, const char *path, \
+ SYS___SET_TCB = 329 // { void sys___set_tcb(void *tcb); }
+ SYS___GET_TCB = 330 // { void *sys___get_tcb(void); }
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go
new file mode 100644
index 0000000..32653e5
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go
@@ -0,0 +1,213 @@
+// mksysnum_openbsd.pl
+// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT
+
+// +build arm,openbsd
+
+package unix
+
+const (
+ SYS_EXIT = 1 // { void sys_exit(int rval); }
+ SYS_FORK = 2 // { int sys_fork(void); }
+ SYS_READ = 3 // { ssize_t sys_read(int fd, void *buf, size_t nbyte); }
+ SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, \
+ SYS_OPEN = 5 // { int sys_open(const char *path, \
+ SYS_CLOSE = 6 // { int sys_close(int fd); }
+ SYS_GETENTROPY = 7 // { int sys_getentropy(void *buf, size_t nbyte); }
+ SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, \
+ SYS_LINK = 9 // { int sys_link(const char *path, const char *link); }
+ SYS_UNLINK = 10 // { int sys_unlink(const char *path); }
+ SYS_WAIT4 = 11 // { pid_t sys_wait4(pid_t pid, int *status, \
+ SYS_CHDIR = 12 // { int sys_chdir(const char *path); }
+ SYS_FCHDIR = 13 // { int sys_fchdir(int fd); }
+ SYS_MKNOD = 14 // { int sys_mknod(const char *path, mode_t mode, \
+ SYS_CHMOD = 15 // { int sys_chmod(const char *path, mode_t mode); }
+ SYS_CHOWN = 16 // { int sys_chown(const char *path, uid_t uid, \
+ SYS_OBREAK = 17 // { int sys_obreak(char *nsize); } break
+ SYS_GETDTABLECOUNT = 18 // { int sys_getdtablecount(void); }
+ SYS_GETRUSAGE = 19 // { int sys_getrusage(int who, \
+ SYS_GETPID = 20 // { pid_t sys_getpid(void); }
+ SYS_MOUNT = 21 // { int sys_mount(const char *type, const char *path, \
+ SYS_UNMOUNT = 22 // { int sys_unmount(const char *path, int flags); }
+ SYS_SETUID = 23 // { int sys_setuid(uid_t uid); }
+ SYS_GETUID = 24 // { uid_t sys_getuid(void); }
+ SYS_GETEUID = 25 // { uid_t sys_geteuid(void); }
+ SYS_PTRACE = 26 // { int sys_ptrace(int req, pid_t pid, caddr_t addr, \
+ SYS_RECVMSG = 27 // { ssize_t sys_recvmsg(int s, struct msghdr *msg, \
+ SYS_SENDMSG = 28 // { ssize_t sys_sendmsg(int s, \
+ SYS_RECVFROM = 29 // { ssize_t sys_recvfrom(int s, void *buf, size_t len, \
+ SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, \
+ SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, \
+ SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, \
+ SYS_ACCESS = 33 // { int sys_access(const char *path, int amode); }
+ SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); }
+ SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); }
+ SYS_SYNC = 36 // { void sys_sync(void); }
+ SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); }
+ SYS_GETPPID = 39 // { pid_t sys_getppid(void); }
+ SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); }
+ SYS_DUP = 41 // { int sys_dup(int fd); }
+ SYS_FSTATAT = 42 // { int sys_fstatat(int fd, const char *path, \
+ SYS_GETEGID = 43 // { gid_t sys_getegid(void); }
+ SYS_PROFIL = 44 // { int sys_profil(caddr_t samples, size_t size, \
+ SYS_KTRACE = 45 // { int sys_ktrace(const char *fname, int ops, \
+ SYS_SIGACTION = 46 // { int sys_sigaction(int signum, \
+ SYS_GETGID = 47 // { gid_t sys_getgid(void); }
+ SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); }
+ SYS_GETLOGIN = 49 // { int sys_getlogin(char *namebuf, u_int namelen); }
+ SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); }
+ SYS_ACCT = 51 // { int sys_acct(const char *path); }
+ SYS_SIGPENDING = 52 // { int sys_sigpending(void); }
+ SYS_FSTAT = 53 // { int sys_fstat(int fd, struct stat *sb); }
+ SYS_IOCTL = 54 // { int sys_ioctl(int fd, \
+ SYS_REBOOT = 55 // { int sys_reboot(int opt); }
+ SYS_REVOKE = 56 // { int sys_revoke(const char *path); }
+ SYS_SYMLINK = 57 // { int sys_symlink(const char *path, \
+ SYS_READLINK = 58 // { ssize_t sys_readlink(const char *path, \
+ SYS_EXECVE = 59 // { int sys_execve(const char *path, \
+ SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); }
+ SYS_CHROOT = 61 // { int sys_chroot(const char *path); }
+ SYS_GETFSSTAT = 62 // { int sys_getfsstat(struct statfs *buf, size_t bufsize, \
+ SYS_STATFS = 63 // { int sys_statfs(const char *path, \
+ SYS_FSTATFS = 64 // { int sys_fstatfs(int fd, struct statfs *buf); }
+ SYS_FHSTATFS = 65 // { int sys_fhstatfs(const fhandle_t *fhp, \
+ SYS_VFORK = 66 // { int sys_vfork(void); }
+ SYS_GETTIMEOFDAY = 67 // { int sys_gettimeofday(struct timeval *tp, \
+ SYS_SETTIMEOFDAY = 68 // { int sys_settimeofday(const struct timeval *tv, \
+ SYS_SETITIMER = 69 // { int sys_setitimer(int which, \
+ SYS_GETITIMER = 70 // { int sys_getitimer(int which, \
+ SYS_SELECT = 71 // { int sys_select(int nd, fd_set *in, fd_set *ou, \
+ SYS_KEVENT = 72 // { int sys_kevent(int fd, \
+ SYS_MUNMAP = 73 // { int sys_munmap(void *addr, size_t len); }
+ SYS_MPROTECT = 74 // { int sys_mprotect(void *addr, size_t len, \
+ SYS_MADVISE = 75 // { int sys_madvise(void *addr, size_t len, \
+ SYS_UTIMES = 76 // { int sys_utimes(const char *path, \
+ SYS_FUTIMES = 77 // { int sys_futimes(int fd, \
+ SYS_MINCORE = 78 // { int sys_mincore(void *addr, size_t len, \
+ SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, \
+ SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, \
+ SYS_GETPGRP = 81 // { int sys_getpgrp(void); }
+ SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, pid_t pgid); }
+ SYS_SENDSYSLOG = 83 // { int sys_sendsyslog(const void *buf, size_t nbyte); }
+ SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, \
+ SYS_FUTIMENS = 85 // { int sys_futimens(int fd, \
+ SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, \
+ SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, \
+ SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, \
+ SYS_DUP2 = 90 // { int sys_dup2(int from, int to); }
+ SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, \
+ SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); }
+ SYS_ACCEPT4 = 93 // { int sys_accept4(int s, struct sockaddr *name, \
+ SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, \
+ SYS_FSYNC = 95 // { int sys_fsync(int fd); }
+ SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); }
+ SYS_SOCKET = 97 // { int sys_socket(int domain, int type, int protocol); }
+ SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, \
+ SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); }
+ SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); }
+ SYS_PIPE2 = 101 // { int sys_pipe2(int *fdp, int flags); }
+ SYS_DUP3 = 102 // { int sys_dup3(int from, int to, int flags); }
+ SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); }
+ SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, \
+ SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, \
+ SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); }
+ SYS_CHFLAGSAT = 107 // { int sys_chflagsat(int fd, const char *path, \
+ SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, \
+ SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \
+ SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); }
+ SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, \
+ SYS_READV = 120 // { ssize_t sys_readv(int fd, \
+ SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, \
+ SYS_KILL = 122 // { int sys_kill(int pid, int signum); }
+ SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); }
+ SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); }
+ SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); }
+ SYS_SETREGID = 127 // { int sys_setregid(gid_t rgid, gid_t egid); }
+ SYS_RENAME = 128 // { int sys_rename(const char *from, const char *to); }
+ SYS_FLOCK = 131 // { int sys_flock(int fd, int how); }
+ SYS_MKFIFO = 132 // { int sys_mkfifo(const char *path, mode_t mode); }
+ SYS_SENDTO = 133 // { ssize_t sys_sendto(int s, const void *buf, \
+ SYS_SHUTDOWN = 134 // { int sys_shutdown(int s, int how); }
+ SYS_SOCKETPAIR = 135 // { int sys_socketpair(int domain, int type, \
+ SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); }
+ SYS_RMDIR = 137 // { int sys_rmdir(const char *path); }
+ SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, \
+ SYS_SETSID = 147 // { int sys_setsid(void); }
+ SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, \
+ SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); }
+ SYS_GETFH = 161 // { int sys_getfh(const char *fname, fhandle_t *fhp); }
+ SYS_SYSARCH = 165 // { int sys_sysarch(int op, void *parms); }
+ SYS_PREAD = 173 // { ssize_t sys_pread(int fd, void *buf, \
+ SYS_PWRITE = 174 // { ssize_t sys_pwrite(int fd, const void *buf, \
+ SYS_SETGID = 181 // { int sys_setgid(gid_t gid); }
+ SYS_SETEGID = 182 // { int sys_setegid(gid_t egid); }
+ SYS_SETEUID = 183 // { int sys_seteuid(uid_t euid); }
+ SYS_PATHCONF = 191 // { long sys_pathconf(const char *path, int name); }
+ SYS_FPATHCONF = 192 // { long sys_fpathconf(int fd, int name); }
+ SYS_SWAPCTL = 193 // { int sys_swapctl(int cmd, const void *arg, int misc); }
+ SYS_GETRLIMIT = 194 // { int sys_getrlimit(int which, \
+ SYS_SETRLIMIT = 195 // { int sys_setrlimit(int which, \
+ SYS_MMAP = 197 // { void *sys_mmap(void *addr, size_t len, int prot, \
+ SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, \
+ SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, \
+ SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); }
+ SYS___SYSCTL = 202 // { int sys___sysctl(const int *name, u_int namelen, \
+ SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); }
+ SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); }
+ SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); }
+ SYS_UTRACE = 209 // { int sys_utrace(const char *label, const void *addr, \
+ SYS_SEMGET = 221 // { int sys_semget(key_t key, int nsems, int semflg); }
+ SYS_MSGGET = 225 // { int sys_msgget(key_t key, int msgflg); }
+ SYS_MSGSND = 226 // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, \
+ SYS_MSGRCV = 227 // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, \
+ SYS_SHMAT = 228 // { void *sys_shmat(int shmid, const void *shmaddr, \
+ SYS_SHMDT = 230 // { int sys_shmdt(const void *shmaddr); }
+ SYS_MINHERIT = 250 // { int sys_minherit(void *addr, size_t len, \
+ SYS_POLL = 252 // { int sys_poll(struct pollfd *fds, \
+ SYS_ISSETUGID = 253 // { int sys_issetugid(void); }
+ SYS_LCHOWN = 254 // { int sys_lchown(const char *path, uid_t uid, gid_t gid); }
+ SYS_GETSID = 255 // { pid_t sys_getsid(pid_t pid); }
+ SYS_MSYNC = 256 // { int sys_msync(void *addr, size_t len, int flags); }
+ SYS_PIPE = 263 // { int sys_pipe(int *fdp); }
+ SYS_FHOPEN = 264 // { int sys_fhopen(const fhandle_t *fhp, int flags); }
+ SYS_PREADV = 267 // { ssize_t sys_preadv(int fd, \
+ SYS_PWRITEV = 268 // { ssize_t sys_pwritev(int fd, \
+ SYS_KQUEUE = 269 // { int sys_kqueue(void); }
+ SYS_MLOCKALL = 271 // { int sys_mlockall(int flags); }
+ SYS_MUNLOCKALL = 272 // { int sys_munlockall(void); }
+ SYS_GETRESUID = 281 // { int sys_getresuid(uid_t *ruid, uid_t *euid, \
+ SYS_SETRESUID = 282 // { int sys_setresuid(uid_t ruid, uid_t euid, \
+ SYS_GETRESGID = 283 // { int sys_getresgid(gid_t *rgid, gid_t *egid, \
+ SYS_SETRESGID = 284 // { int sys_setresgid(gid_t rgid, gid_t egid, \
+ SYS_MQUERY = 286 // { void *sys_mquery(void *addr, size_t len, int prot, \
+ SYS_CLOSEFROM = 287 // { int sys_closefrom(int fd); }
+ SYS_SIGALTSTACK = 288 // { int sys_sigaltstack(const struct sigaltstack *nss, \
+ SYS_SHMGET = 289 // { int sys_shmget(key_t key, size_t size, int shmflg); }
+ SYS_SEMOP = 290 // { int sys_semop(int semid, struct sembuf *sops, \
+ SYS_FHSTAT = 294 // { int sys_fhstat(const fhandle_t *fhp, \
+ SYS___SEMCTL = 295 // { int sys___semctl(int semid, int semnum, int cmd, \
+ SYS_SHMCTL = 296 // { int sys_shmctl(int shmid, int cmd, \
+ SYS_MSGCTL = 297 // { int sys_msgctl(int msqid, int cmd, \
+ SYS_SCHED_YIELD = 298 // { int sys_sched_yield(void); }
+ SYS_GETTHRID = 299 // { pid_t sys_getthrid(void); }
+ SYS___THRWAKEUP = 301 // { int sys___thrwakeup(const volatile void *ident, \
+ SYS___THREXIT = 302 // { void sys___threxit(pid_t *notdead); }
+ SYS___THRSIGDIVERT = 303 // { int sys___thrsigdivert(sigset_t sigmask, \
+ SYS___GETCWD = 304 // { int sys___getcwd(char *buf, size_t len); }
+ SYS_ADJFREQ = 305 // { int sys_adjfreq(const int64_t *freq, \
+ SYS_SETRTABLE = 310 // { int sys_setrtable(int rtableid); }
+ SYS_GETRTABLE = 311 // { int sys_getrtable(void); }
+ SYS_FACCESSAT = 313 // { int sys_faccessat(int fd, const char *path, \
+ SYS_FCHMODAT = 314 // { int sys_fchmodat(int fd, const char *path, \
+ SYS_FCHOWNAT = 315 // { int sys_fchownat(int fd, const char *path, \
+ SYS_LINKAT = 317 // { int sys_linkat(int fd1, const char *path1, int fd2, \
+ SYS_MKDIRAT = 318 // { int sys_mkdirat(int fd, const char *path, \
+ SYS_MKFIFOAT = 319 // { int sys_mkfifoat(int fd, const char *path, \
+ SYS_MKNODAT = 320 // { int sys_mknodat(int fd, const char *path, \
+ SYS_OPENAT = 321 // { int sys_openat(int fd, const char *path, int flags, \
+ SYS_READLINKAT = 322 // { ssize_t sys_readlinkat(int fd, const char *path, \
+ SYS_RENAMEAT = 323 // { int sys_renameat(int fromfd, const char *from, \
+ SYS_SYMLINKAT = 324 // { int sys_symlinkat(const char *path, int fd, \
+ SYS_UNLINKAT = 325 // { int sys_unlinkat(int fd, const char *path, \
+ SYS___SET_TCB = 329 // { void sys___set_tcb(void *tcb); }
+ SYS___GET_TCB = 330 // { void *sys___get_tcb(void); }
+)
diff --git a/vendor/golang.org/x/sys/unix/zsysnum_solaris_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_solaris_amd64.go
new file mode 100644
index 0000000..c708659
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/zsysnum_solaris_amd64.go
@@ -0,0 +1,13 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build amd64,solaris
+
+package unix
+
+// TODO(aram): remove these before Go 1.3.
+const (
+ SYS_EXECVE = 59
+ SYS_FCNTL = 62
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_386.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_386.go
new file mode 100644
index 0000000..e61d78a
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_386.go
@@ -0,0 +1,462 @@
+// cgo -godefs types_darwin.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build 386,darwin
+
+package unix
+
+const (
+ sizeofPtr = 0x4
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x4
+ sizeofLongLong = 0x8
+)
+
+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 Timeval32 struct{}
+
+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 int32
+ Mode uint16
+ Nlink uint16
+ Ino uint64
+ Uid uint32
+ Gid uint32
+ Rdev int32
+ Atimespec Timespec
+ Mtimespec Timespec
+ Ctimespec Timespec
+ Birthtimespec Timespec
+ Size int64
+ Blocks int64
+ Blksize int32
+ Flags uint32
+ Gen uint32
+ Lspare int32
+ Qspare [2]int64
+}
+
+type Statfs_t struct {
+ Bsize uint32
+ Iosize int32
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Owner uint32
+ Type uint32
+ Flags uint32
+ Fssubtype uint32
+ Fstypename [16]int8
+ Mntonname [1024]int8
+ Mntfromname [1024]int8
+ Reserved [8]uint32
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Fstore_t struct {
+ Flags uint32
+ Posmode int32
+ Offset int64
+ Length int64
+ Bytesalloc int64
+}
+
+type Radvisory_t struct {
+ Offset int64
+ Count int32
+}
+
+type Fbootstraptransfer_t struct {
+ Offset int64
+ Length uint32
+ Buffer *byte
+}
+
+type Log2phys_t struct {
+ Flags uint32
+ Contigbytes int64
+ Devoffset int64
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+type Dirent struct {
+ Ino uint64
+ Seekoff uint64
+ Reclen uint16
+ Namlen uint16
+ Type uint8
+ Name [1024]int8
+ Pad_cgo_0 [3]byte
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]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 IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Iov *Iovec
+ Iovlen int32
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet4Pktinfo struct {
+ Ifindex uint32
+ 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 {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x14
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x1c
+ SizeofCmsghdr = 0xc
+ SizeofInet4Pktinfo = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint32
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int32
+ Udata *byte
+}
+
+type FdSet struct {
+ Bits [32]int32
+}
+
+const (
+ SizeofIfMsghdr = 0x70
+ SizeofIfData = 0x60
+ SizeofIfaMsghdr = 0x14
+ SizeofIfmaMsghdr = 0x10
+ SizeofIfmaMsghdr2 = 0x14
+ SizeofRtMsghdr = 0x5c
+ SizeofRtMetrics = 0x38
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Typelen uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Recvquota uint8
+ Xmitquota uint8
+ Unused1 uint8
+ Mtu uint32
+ Metric uint32
+ Baudrate uint32
+ Ipackets uint32
+ Ierrors uint32
+ Opackets uint32
+ Oerrors uint32
+ Collisions uint32
+ Ibytes uint32
+ Obytes uint32
+ Imcasts uint32
+ Omcasts uint32
+ Iqdrops uint32
+ Noproto uint32
+ Recvtiming uint32
+ Xmittiming uint32
+ Lastchange Timeval
+ Unused2 uint32
+ Hwassist uint32
+ Reserved1 uint32
+ Reserved2 uint32
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Metric int32
+}
+
+type IfmaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+}
+
+type IfmaMsghdr2 struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Refcount int32
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Use int32
+ Inits uint32
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint32
+ Mtu uint32
+ Hopcount uint32
+ Expire int32
+ Recvpipe uint32
+ Sendpipe uint32
+ Ssthresh uint32
+ Rtt uint32
+ Rttvar uint32
+ Pksent uint32
+ Filler [4]uint32
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfProgram = 0x8
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfProgram struct {
+ Len uint32
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp Timeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+const (
+ AT_FDCWD = -0x2
+ AT_REMOVEDIR = 0x80
+ AT_SYMLINK_FOLLOW = 0x40
+ AT_SYMLINK_NOFOLLOW = 0x20
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go
new file mode 100644
index 0000000..2619155
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go
@@ -0,0 +1,472 @@
+// cgo -godefs types_darwin.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,darwin
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int32
+ Pad_cgo_0 [4]byte
+}
+
+type Timeval32 struct {
+ Sec int32
+ Usec int32
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev int32
+ Mode uint16
+ Nlink uint16
+ Ino uint64
+ Uid uint32
+ Gid uint32
+ Rdev int32
+ Pad_cgo_0 [4]byte
+ Atimespec Timespec
+ Mtimespec Timespec
+ Ctimespec Timespec
+ Birthtimespec Timespec
+ Size int64
+ Blocks int64
+ Blksize int32
+ Flags uint32
+ Gen uint32
+ Lspare int32
+ Qspare [2]int64
+}
+
+type Statfs_t struct {
+ Bsize uint32
+ Iosize int32
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Owner uint32
+ Type uint32
+ Flags uint32
+ Fssubtype uint32
+ Fstypename [16]int8
+ Mntonname [1024]int8
+ Mntfromname [1024]int8
+ Reserved [8]uint32
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Fstore_t struct {
+ Flags uint32
+ Posmode int32
+ Offset int64
+ Length int64
+ Bytesalloc int64
+}
+
+type Radvisory_t struct {
+ Offset int64
+ Count int32
+ Pad_cgo_0 [4]byte
+}
+
+type Fbootstraptransfer_t struct {
+ Offset int64
+ Length uint64
+ Buffer *byte
+}
+
+type Log2phys_t struct {
+ Flags uint32
+ Pad_cgo_0 [8]byte
+ Pad_cgo_1 [8]byte
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+type Dirent struct {
+ Ino uint64
+ Seekoff uint64
+ Reclen uint16
+ Namlen uint16
+ Type uint8
+ Name [1024]int8
+ Pad_cgo_0 [3]byte
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]int8
+}
+
+type _Socklen uint32
+
+type Linger struct {
+ Onoff int32
+ Linger int32
+}
+
+type Iovec struct {
+ Base *byte
+ Len uint64
+}
+
+type IPMreq struct {
+ Multiaddr [4]byte /* in_addr */
+ Interface [4]byte /* in_addr */
+}
+
+type IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen int32
+ Pad_cgo_1 [4]byte
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet4Pktinfo struct {
+ Ifindex uint32
+ 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 {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x14
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x30
+ SizeofCmsghdr = 0xc
+ SizeofInet4Pktinfo = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint64
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int64
+ Udata *byte
+}
+
+type FdSet struct {
+ Bits [32]int32
+}
+
+const (
+ SizeofIfMsghdr = 0x70
+ SizeofIfData = 0x60
+ SizeofIfaMsghdr = 0x14
+ SizeofIfmaMsghdr = 0x10
+ SizeofIfmaMsghdr2 = 0x14
+ SizeofRtMsghdr = 0x5c
+ SizeofRtMetrics = 0x38
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Typelen uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Recvquota uint8
+ Xmitquota uint8
+ Unused1 uint8
+ Mtu uint32
+ Metric uint32
+ Baudrate uint32
+ Ipackets uint32
+ Ierrors uint32
+ Opackets uint32
+ Oerrors uint32
+ Collisions uint32
+ Ibytes uint32
+ Obytes uint32
+ Imcasts uint32
+ Omcasts uint32
+ Iqdrops uint32
+ Noproto uint32
+ Recvtiming uint32
+ Xmittiming uint32
+ Lastchange Timeval32
+ Unused2 uint32
+ Hwassist uint32
+ Reserved1 uint32
+ Reserved2 uint32
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Metric int32
+}
+
+type IfmaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+}
+
+type IfmaMsghdr2 struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Refcount int32
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Use int32
+ Inits uint32
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint32
+ Mtu uint32
+ Hopcount uint32
+ Expire int32
+ Recvpipe uint32
+ Sendpipe uint32
+ Ssthresh uint32
+ Rtt uint32
+ Rttvar uint32
+ Pksent uint32
+ Filler [4]uint32
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfProgram = 0x10
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfProgram struct {
+ Len uint32
+ Pad_cgo_0 [4]byte
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp Timeval32
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+type Termios struct {
+ Iflag uint64
+ Oflag uint64
+ Cflag uint64
+ Lflag uint64
+ Cc [20]uint8
+ Pad_cgo_0 [4]byte
+ Ispeed uint64
+ Ospeed uint64
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+const (
+ AT_FDCWD = -0x2
+ AT_REMOVEDIR = 0x80
+ AT_SYMLINK_FOLLOW = 0x40
+ AT_SYMLINK_NOFOLLOW = 0x20
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go
new file mode 100644
index 0000000..4dca0d4
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go
@@ -0,0 +1,463 @@
+// NOTE: cgo can't generate struct Stat_t and struct Statfs_t yet
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_darwin.go
+
+// +build arm,darwin
+
+package unix
+
+const (
+ sizeofPtr = 0x4
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x4
+ sizeofLongLong = 0x8
+)
+
+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 Timeval32 [0]byte
+
+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 int32
+ Mode uint16
+ Nlink uint16
+ Ino uint64
+ Uid uint32
+ Gid uint32
+ Rdev int32
+ Atimespec Timespec
+ Mtimespec Timespec
+ Ctimespec Timespec
+ Birthtimespec Timespec
+ Size int64
+ Blocks int64
+ Blksize int32
+ Flags uint32
+ Gen uint32
+ Lspare int32
+ Qspare [2]int64
+}
+
+type Statfs_t struct {
+ Bsize uint32
+ Iosize int32
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Owner uint32
+ Type uint32
+ Flags uint32
+ Fssubtype uint32
+ Fstypename [16]int8
+ Mntonname [1024]int8
+ Mntfromname [1024]int8
+ Reserved [8]uint32
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Fstore_t struct {
+ Flags uint32
+ Posmode int32
+ Offset int64
+ Length int64
+ Bytesalloc int64
+}
+
+type Radvisory_t struct {
+ Offset int64
+ Count int32
+}
+
+type Fbootstraptransfer_t struct {
+ Offset int64
+ Length uint32
+ Buffer *byte
+}
+
+type Log2phys_t struct {
+ Flags uint32
+ Contigbytes int64
+ Devoffset int64
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+type Dirent struct {
+ Ino uint64
+ Seekoff uint64
+ Reclen uint16
+ Namlen uint16
+ Type uint8
+ Name [1024]int8
+ Pad_cgo_0 [3]byte
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]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 IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Iov *Iovec
+ Iovlen int32
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet4Pktinfo struct {
+ Ifindex uint32
+ 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 {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x14
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x1c
+ SizeofCmsghdr = 0xc
+ SizeofInet4Pktinfo = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint32
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int32
+ Udata *byte
+}
+
+type FdSet struct {
+ Bits [32]int32
+}
+
+const (
+ SizeofIfMsghdr = 0x70
+ SizeofIfData = 0x60
+ SizeofIfaMsghdr = 0x14
+ SizeofIfmaMsghdr = 0x10
+ SizeofIfmaMsghdr2 = 0x14
+ SizeofRtMsghdr = 0x5c
+ SizeofRtMetrics = 0x38
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Typelen uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Recvquota uint8
+ Xmitquota uint8
+ Unused1 uint8
+ Mtu uint32
+ Metric uint32
+ Baudrate uint32
+ Ipackets uint32
+ Ierrors uint32
+ Opackets uint32
+ Oerrors uint32
+ Collisions uint32
+ Ibytes uint32
+ Obytes uint32
+ Imcasts uint32
+ Omcasts uint32
+ Iqdrops uint32
+ Noproto uint32
+ Recvtiming uint32
+ Xmittiming uint32
+ Lastchange Timeval
+ Unused2 uint32
+ Hwassist uint32
+ Reserved1 uint32
+ Reserved2 uint32
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Metric int32
+}
+
+type IfmaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+}
+
+type IfmaMsghdr2 struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Refcount int32
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Use int32
+ Inits uint32
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint32
+ Mtu uint32
+ Hopcount uint32
+ Expire int32
+ Recvpipe uint32
+ Sendpipe uint32
+ Ssthresh uint32
+ Rtt uint32
+ Rttvar uint32
+ Pksent uint32
+ Filler [4]uint32
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfProgram = 0x8
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfProgram struct {
+ Len uint32
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp Timeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+const (
+ AT_FDCWD = -0x2
+ AT_REMOVEDIR = 0x80
+ AT_SYMLINK_FOLLOW = 0x40
+ AT_SYMLINK_NOFOLLOW = 0x20
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go
new file mode 100644
index 0000000..f2881fd
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go
@@ -0,0 +1,471 @@
+// +build arm64,darwin
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_darwin.go
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int32
+ Pad_cgo_0 [4]byte
+}
+
+type Timeval32 struct {
+ Sec int32
+ Usec int32
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev int32
+ Mode uint16
+ Nlink uint16
+ Ino uint64
+ Uid uint32
+ Gid uint32
+ Rdev int32
+ Pad_cgo_0 [4]byte
+ Atimespec Timespec
+ Mtimespec Timespec
+ Ctimespec Timespec
+ Birthtimespec Timespec
+ Size int64
+ Blocks int64
+ Blksize int32
+ Flags uint32
+ Gen uint32
+ Lspare int32
+ Qspare [2]int64
+}
+
+type Statfs_t struct {
+ Bsize uint32
+ Iosize int32
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Owner uint32
+ Type uint32
+ Flags uint32
+ Fssubtype uint32
+ Fstypename [16]int8
+ Mntonname [1024]int8
+ Mntfromname [1024]int8
+ Reserved [8]uint32
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Fstore_t struct {
+ Flags uint32
+ Posmode int32
+ Offset int64
+ Length int64
+ Bytesalloc int64
+}
+
+type Radvisory_t struct {
+ Offset int64
+ Count int32
+ Pad_cgo_0 [4]byte
+}
+
+type Fbootstraptransfer_t struct {
+ Offset int64
+ Length uint64
+ Buffer *byte
+}
+
+type Log2phys_t struct {
+ Flags uint32
+ Pad_cgo_0 [8]byte
+ Pad_cgo_1 [8]byte
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+type Dirent struct {
+ Ino uint64
+ Seekoff uint64
+ Reclen uint16
+ Namlen uint16
+ Type uint8
+ Name [1024]int8
+ Pad_cgo_0 [3]byte
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]int8
+}
+
+type _Socklen uint32
+
+type Linger struct {
+ Onoff int32
+ Linger int32
+}
+
+type Iovec struct {
+ Base *byte
+ Len uint64
+}
+
+type IPMreq struct {
+ Multiaddr [4]byte /* in_addr */
+ Interface [4]byte /* in_addr */
+}
+
+type IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen int32
+ Pad_cgo_1 [4]byte
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet4Pktinfo struct {
+ Ifindex uint32
+ 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 {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x14
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x30
+ SizeofCmsghdr = 0xc
+ SizeofInet4Pktinfo = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint64
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int64
+ Udata *byte
+}
+
+type FdSet struct {
+ Bits [32]int32
+}
+
+const (
+ SizeofIfMsghdr = 0x70
+ SizeofIfData = 0x60
+ SizeofIfaMsghdr = 0x14
+ SizeofIfmaMsghdr = 0x10
+ SizeofIfmaMsghdr2 = 0x14
+ SizeofRtMsghdr = 0x5c
+ SizeofRtMetrics = 0x38
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Typelen uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Recvquota uint8
+ Xmitquota uint8
+ Unused1 uint8
+ Mtu uint32
+ Metric uint32
+ Baudrate uint32
+ Ipackets uint32
+ Ierrors uint32
+ Opackets uint32
+ Oerrors uint32
+ Collisions uint32
+ Ibytes uint32
+ Obytes uint32
+ Imcasts uint32
+ Omcasts uint32
+ Iqdrops uint32
+ Noproto uint32
+ Recvtiming uint32
+ Xmittiming uint32
+ Lastchange Timeval32
+ Unused2 uint32
+ Hwassist uint32
+ Reserved1 uint32
+ Reserved2 uint32
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Metric int32
+}
+
+type IfmaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+}
+
+type IfmaMsghdr2 struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Refcount int32
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Use int32
+ Inits uint32
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint32
+ Mtu uint32
+ Hopcount uint32
+ Expire int32
+ Recvpipe uint32
+ Sendpipe uint32
+ Ssthresh uint32
+ Rtt uint32
+ Rttvar uint32
+ Pksent uint32
+ Filler [4]uint32
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfProgram = 0x10
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfProgram struct {
+ Len uint32
+ Pad_cgo_0 [4]byte
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp Timeval32
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+type Termios struct {
+ Iflag uint64
+ Oflag uint64
+ Cflag uint64
+ Lflag uint64
+ Cc [20]uint8
+ Pad_cgo_0 [4]byte
+ Ispeed uint64
+ Ospeed uint64
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+const (
+ AT_FDCWD = -0x2
+ AT_REMOVEDIR = 0x80
+ AT_SYMLINK_FOLLOW = 0x40
+ AT_SYMLINK_NOFOLLOW = 0x20
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go
new file mode 100644
index 0000000..67c6bf8
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go
@@ -0,0 +1,448 @@
+// cgo -godefs types_dragonfly.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,dragonfly
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur int64
+ Max int64
+}
+
+type _Gid_t uint32
+
+const (
+ S_IFMT = 0xf000
+ S_IFIFO = 0x1000
+ S_IFCHR = 0x2000
+ S_IFDIR = 0x4000
+ S_IFBLK = 0x6000
+ S_IFREG = 0x8000
+ S_IFLNK = 0xa000
+ S_IFSOCK = 0xc000
+ S_ISUID = 0x800
+ S_ISGID = 0x400
+ S_ISVTX = 0x200
+ S_IRUSR = 0x100
+ S_IWUSR = 0x80
+ S_IXUSR = 0x40
+)
+
+type Stat_t struct {
+ Ino uint64
+ Nlink uint32
+ Dev uint32
+ Mode uint16
+ Padding1 uint16
+ Uid uint32
+ Gid uint32
+ Rdev uint32
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ Size int64
+ Blocks int64
+ Blksize uint32
+ Flags uint32
+ Gen uint32
+ Lspare int32
+ Qspare1 int64
+ Qspare2 int64
+}
+
+type Statfs_t struct {
+ Spare2 int64
+ Bsize int64
+ Iosize int64
+ Blocks int64
+ Bfree int64
+ Bavail int64
+ Files int64
+ Ffree int64
+ Fsid Fsid
+ Owner uint32
+ Type int32
+ Flags int32
+ Pad_cgo_0 [4]byte
+ Syncwrites int64
+ Asyncwrites int64
+ Fstypename [16]int8
+ Mntonname [80]int8
+ Syncreads int64
+ Asyncreads int64
+ Spares1 int16
+ Mntfromname [80]int8
+ Spares2 int16
+ Pad_cgo_1 [4]byte
+ Spare [2]int64
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Dirent struct {
+ Fileno uint64
+ Namlen uint16
+ Type uint8
+ Unused1 uint8
+ Unused2 uint32
+ Name [256]int8
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+ Rcf uint16
+ Route [16]uint16
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]int8
+}
+
+type _Socklen uint32
+
+type Linger struct {
+ Onoff int32
+ Linger int32
+}
+
+type Iovec struct {
+ Base *byte
+ Len uint64
+}
+
+type IPMreq struct {
+ Multiaddr [4]byte /* in_addr */
+ Interface [4]byte /* in_addr */
+}
+
+type IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen int32
+ Pad_cgo_1 [4]byte
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x36
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x30
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint64
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int64
+ Udata *byte
+}
+
+type FdSet struct {
+ Bits [16]uint64
+}
+
+const (
+ SizeofIfMsghdr = 0xb0
+ SizeofIfData = 0xa0
+ SizeofIfaMsghdr = 0x14
+ SizeofIfmaMsghdr = 0x10
+ SizeofIfAnnounceMsghdr = 0x18
+ SizeofRtMsghdr = 0x98
+ SizeofRtMetrics = 0x70
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Recvquota uint8
+ Xmitquota uint8
+ Pad_cgo_0 [2]byte
+ Mtu uint64
+ Metric uint64
+ Link_state uint64
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Noproto uint64
+ Hwassist uint64
+ Oqdrops uint64
+ Lastchange Timeval
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Metric int32
+}
+
+type IfmaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+}
+
+type IfAnnounceMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Name [16]int8
+ What uint16
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Use int32
+ Inits uint64
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint64
+ Mtu uint64
+ Pksent uint64
+ Expire uint64
+ Sendpipe uint64
+ Ssthresh uint64
+ Rtt uint64
+ Rttvar uint64
+ Recvpipe uint64
+ Hopcount uint64
+ Mssopt uint16
+ Pad uint16
+ Pad_cgo_0 [4]byte
+ Msl uint64
+ Iwmaxsegs uint64
+ Iwcapsegs uint64
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfProgram = 0x10
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x20
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfProgram struct {
+ Len uint32
+ Pad_cgo_0 [4]byte
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp Timeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [6]byte
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+const (
+ AT_FDCWD = 0xfffafdcd
+ AT_SYMLINK_NOFOLLOW = 0x1
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go
new file mode 100644
index 0000000..5b28bcb
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go
@@ -0,0 +1,521 @@
+// cgo -godefs types_freebsd.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build 386,freebsd
+
+package unix
+
+const (
+ sizeofPtr = 0x4
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x4
+ sizeofLongLong = 0x8
+)
+
+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 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 int64
+ Max int64
+}
+
+type _Gid_t uint32
+
+const (
+ S_IFMT = 0xf000
+ S_IFIFO = 0x1000
+ S_IFCHR = 0x2000
+ S_IFDIR = 0x4000
+ S_IFBLK = 0x6000
+ S_IFREG = 0x8000
+ S_IFLNK = 0xa000
+ S_IFSOCK = 0xc000
+ S_ISUID = 0x800
+ S_ISGID = 0x400
+ S_ISVTX = 0x200
+ S_IRUSR = 0x100
+ S_IWUSR = 0x80
+ S_IXUSR = 0x40
+)
+
+type Stat_t struct {
+ Dev uint32
+ Ino uint32
+ Mode uint16
+ Nlink uint16
+ Uid uint32
+ Gid uint32
+ Rdev uint32
+ Atimespec Timespec
+ Mtimespec Timespec
+ Ctimespec Timespec
+ Size int64
+ Blocks int64
+ Blksize int32
+ Flags uint32
+ Gen uint32
+ Lspare int32
+ Birthtimespec Timespec
+ Pad_cgo_0 [8]byte
+}
+
+type Statfs_t struct {
+ Version uint32
+ Type uint32
+ Flags uint64
+ Bsize uint64
+ Iosize uint64
+ Blocks uint64
+ Bfree uint64
+ Bavail int64
+ Files uint64
+ Ffree int64
+ Syncwrites uint64
+ Asyncwrites uint64
+ Syncreads uint64
+ Asyncreads uint64
+ Spare [10]uint64
+ Namemax uint32
+ Owner uint32
+ Fsid Fsid
+ Charspare [80]int8
+ Fstypename [16]int8
+ Mntfromname [88]int8
+ Mntonname [88]int8
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+ Sysid int32
+}
+
+type Dirent struct {
+ Fileno uint32
+ Reclen uint16
+ Type uint8
+ Namlen uint8
+ Name [256]int8
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+const (
+ FADV_NORMAL = 0x0
+ FADV_RANDOM = 0x1
+ FADV_SEQUENTIAL = 0x2
+ FADV_WILLNEED = 0x3
+ FADV_DONTNEED = 0x4
+ FADV_NOREUSE = 0x5
+)
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [46]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]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 int32
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x36
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x1c
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint32
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int32
+ Udata *byte
+}
+
+type FdSet struct {
+ X__fds_bits [32]uint32
+}
+
+const (
+ sizeofIfMsghdr = 0xa8
+ SizeofIfMsghdr = 0x60
+ sizeofIfData = 0x98
+ SizeofIfData = 0x50
+ SizeofIfaMsghdr = 0x14
+ SizeofIfmaMsghdr = 0x10
+ SizeofIfAnnounceMsghdr = 0x18
+ SizeofRtMsghdr = 0x5c
+ SizeofRtMetrics = 0x38
+)
+
+type ifMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data ifData
+}
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type ifData struct {
+ Type uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Link_state uint8
+ Vhid uint8
+ Datalen uint16
+ Mtu uint32
+ Metric uint32
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Oqdrops uint64
+ Noproto uint64
+ Hwassist uint64
+ X__ifi_epoch [8]byte
+ X__ifi_lastchange [16]byte
+}
+
+type IfData struct {
+ Type uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Link_state uint8
+ Spare_char1 uint8
+ Spare_char2 uint8
+ Datalen uint8
+ Mtu uint32
+ Metric uint32
+ Baudrate uint32
+ Ipackets uint32
+ Ierrors uint32
+ Opackets uint32
+ Oerrors uint32
+ Collisions uint32
+ Ibytes uint32
+ Obytes uint32
+ Imcasts uint32
+ Omcasts uint32
+ Iqdrops uint32
+ Noproto uint32
+ Hwassist uint32
+ Epoch int32
+ Lastchange Timeval
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Metric int32
+}
+
+type IfmaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+}
+
+type IfAnnounceMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Name [16]int8
+ What uint16
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Fmask int32
+ Inits uint32
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint32
+ Mtu uint32
+ Hopcount uint32
+ Expire uint32
+ Recvpipe uint32
+ Sendpipe uint32
+ Ssthresh uint32
+ Rtt uint32
+ Rttvar uint32
+ Pksent uint32
+ Weight uint32
+ Filler [3]uint32
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfZbuf = 0xc
+ SizeofBpfProgram = 0x8
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+ SizeofBpfZbufHeader = 0x20
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfZbuf struct {
+ Bufa *byte
+ Bufb *byte
+ Buflen uint32
+}
+
+type BpfProgram struct {
+ Len uint32
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp Timeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+type BpfZbufHeader struct {
+ Kernel_gen uint32
+ Kernel_len uint32
+ User_gen uint32
+ X_bzh_pad [5]uint32
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+const (
+ AT_FDCWD = -0x64
+ AT_REMOVEDIR = 0x800
+ AT_SYMLINK_FOLLOW = 0x400
+ AT_SYMLINK_NOFOLLOW = 0x200
+)
+
+type CapRights struct {
+ Rights [2]uint64
+}
diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go
new file mode 100644
index 0000000..c65d89e
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go
@@ -0,0 +1,524 @@
+// cgo -godefs types_freebsd.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,freebsd
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur int64
+ Max int64
+}
+
+type _Gid_t uint32
+
+const (
+ S_IFMT = 0xf000
+ S_IFIFO = 0x1000
+ S_IFCHR = 0x2000
+ S_IFDIR = 0x4000
+ S_IFBLK = 0x6000
+ S_IFREG = 0x8000
+ S_IFLNK = 0xa000
+ S_IFSOCK = 0xc000
+ S_ISUID = 0x800
+ S_ISGID = 0x400
+ S_ISVTX = 0x200
+ S_IRUSR = 0x100
+ S_IWUSR = 0x80
+ S_IXUSR = 0x40
+)
+
+type Stat_t struct {
+ Dev uint32
+ Ino uint32
+ Mode uint16
+ Nlink uint16
+ Uid uint32
+ Gid uint32
+ Rdev uint32
+ Atimespec Timespec
+ Mtimespec Timespec
+ Ctimespec Timespec
+ Size int64
+ Blocks int64
+ Blksize int32
+ Flags uint32
+ Gen uint32
+ Lspare int32
+ Birthtimespec Timespec
+}
+
+type Statfs_t struct {
+ Version uint32
+ Type uint32
+ Flags uint64
+ Bsize uint64
+ Iosize uint64
+ Blocks uint64
+ Bfree uint64
+ Bavail int64
+ Files uint64
+ Ffree int64
+ Syncwrites uint64
+ Asyncwrites uint64
+ Syncreads uint64
+ Asyncreads uint64
+ Spare [10]uint64
+ Namemax uint32
+ Owner uint32
+ Fsid Fsid
+ Charspare [80]int8
+ Fstypename [16]int8
+ Mntfromname [88]int8
+ Mntonname [88]int8
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+ Sysid int32
+ Pad_cgo_0 [4]byte
+}
+
+type Dirent struct {
+ Fileno uint32
+ Reclen uint16
+ Type uint8
+ Namlen uint8
+ Name [256]int8
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+const (
+ FADV_NORMAL = 0x0
+ FADV_RANDOM = 0x1
+ FADV_SEQUENTIAL = 0x2
+ FADV_WILLNEED = 0x3
+ FADV_DONTNEED = 0x4
+ FADV_NOREUSE = 0x5
+)
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [46]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]int8
+}
+
+type _Socklen uint32
+
+type Linger struct {
+ Onoff int32
+ Linger int32
+}
+
+type Iovec struct {
+ Base *byte
+ Len uint64
+}
+
+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
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen int32
+ Pad_cgo_1 [4]byte
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x36
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x30
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint64
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int64
+ Udata *byte
+}
+
+type FdSet struct {
+ X__fds_bits [16]uint64
+}
+
+const (
+ sizeofIfMsghdr = 0xa8
+ SizeofIfMsghdr = 0xa8
+ sizeofIfData = 0x98
+ SizeofIfData = 0x98
+ SizeofIfaMsghdr = 0x14
+ SizeofIfmaMsghdr = 0x10
+ SizeofIfAnnounceMsghdr = 0x18
+ SizeofRtMsghdr = 0x98
+ SizeofRtMetrics = 0x70
+)
+
+type ifMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data ifData
+}
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type ifData struct {
+ Type uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Link_state uint8
+ Vhid uint8
+ Datalen uint16
+ Mtu uint32
+ Metric uint32
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Oqdrops uint64
+ Noproto uint64
+ Hwassist uint64
+ X__ifi_epoch [8]byte
+ X__ifi_lastchange [16]byte
+}
+
+type IfData struct {
+ Type uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Link_state uint8
+ Spare_char1 uint8
+ Spare_char2 uint8
+ Datalen uint8
+ Mtu uint64
+ Metric uint64
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Noproto uint64
+ Hwassist uint64
+ Epoch int64
+ Lastchange Timeval
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Metric int32
+}
+
+type IfmaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+}
+
+type IfAnnounceMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Name [16]int8
+ What uint16
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Fmask int32
+ Inits uint64
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint64
+ Mtu uint64
+ Hopcount uint64
+ Expire uint64
+ Recvpipe uint64
+ Sendpipe uint64
+ Ssthresh uint64
+ Rtt uint64
+ Rttvar uint64
+ Pksent uint64
+ Weight uint64
+ Filler [3]uint64
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfZbuf = 0x18
+ SizeofBpfProgram = 0x10
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x20
+ SizeofBpfZbufHeader = 0x20
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfZbuf struct {
+ Bufa *byte
+ Bufb *byte
+ Buflen uint64
+}
+
+type BpfProgram struct {
+ Len uint32
+ Pad_cgo_0 [4]byte
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp Timeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [6]byte
+}
+
+type BpfZbufHeader struct {
+ Kernel_gen uint32
+ Kernel_len uint32
+ User_gen uint32
+ X_bzh_pad [5]uint32
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+const (
+ AT_FDCWD = -0x64
+ AT_REMOVEDIR = 0x800
+ AT_SYMLINK_FOLLOW = 0x400
+ AT_SYMLINK_NOFOLLOW = 0x200
+)
+
+type CapRights struct {
+ Rights [2]uint64
+}
diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go
new file mode 100644
index 0000000..42c0a50
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go
@@ -0,0 +1,524 @@
+// cgo -godefs -- -fsigned-char types_freebsd.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm,freebsd
+
+package unix
+
+const (
+ sizeofPtr = 0x4
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x4
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int32
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int32
+ Pad_cgo_0 [4]byte
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int32
+ Pad_cgo_0 [4]byte
+}
+
+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 int64
+ Max int64
+}
+
+type _Gid_t uint32
+
+const (
+ S_IFMT = 0xf000
+ S_IFIFO = 0x1000
+ S_IFCHR = 0x2000
+ S_IFDIR = 0x4000
+ S_IFBLK = 0x6000
+ S_IFREG = 0x8000
+ S_IFLNK = 0xa000
+ S_IFSOCK = 0xc000
+ S_ISUID = 0x800
+ S_ISGID = 0x400
+ S_ISVTX = 0x200
+ S_IRUSR = 0x100
+ S_IWUSR = 0x80
+ S_IXUSR = 0x40
+)
+
+type Stat_t struct {
+ Dev uint32
+ Ino uint32
+ Mode uint16
+ Nlink uint16
+ Uid uint32
+ Gid uint32
+ Rdev uint32
+ Atimespec Timespec
+ Mtimespec Timespec
+ Ctimespec Timespec
+ Size int64
+ Blocks int64
+ Blksize int32
+ Flags uint32
+ Gen uint32
+ Lspare int32
+ Birthtimespec Timespec
+}
+
+type Statfs_t struct {
+ Version uint32
+ Type uint32
+ Flags uint64
+ Bsize uint64
+ Iosize uint64
+ Blocks uint64
+ Bfree uint64
+ Bavail int64
+ Files uint64
+ Ffree int64
+ Syncwrites uint64
+ Asyncwrites uint64
+ Syncreads uint64
+ Asyncreads uint64
+ Spare [10]uint64
+ Namemax uint32
+ Owner uint32
+ Fsid Fsid
+ Charspare [80]int8
+ Fstypename [16]int8
+ Mntfromname [88]int8
+ Mntonname [88]int8
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+ Sysid int32
+ Pad_cgo_0 [4]byte
+}
+
+type Dirent struct {
+ Fileno uint32
+ Reclen uint16
+ Type uint8
+ Namlen uint8
+ Name [256]int8
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+const (
+ FADV_NORMAL = 0x0
+ FADV_RANDOM = 0x1
+ FADV_SEQUENTIAL = 0x2
+ FADV_WILLNEED = 0x3
+ FADV_DONTNEED = 0x4
+ FADV_NOREUSE = 0x5
+)
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [46]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]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 int32
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x36
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x1c
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint32
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int32
+ Udata *byte
+}
+
+type FdSet struct {
+ X__fds_bits [32]uint32
+}
+
+const (
+ sizeofIfMsghdr = 0xa8
+ SizeofIfMsghdr = 0x70
+ sizeofIfData = 0x98
+ SizeofIfData = 0x60
+ SizeofIfaMsghdr = 0x14
+ SizeofIfmaMsghdr = 0x10
+ SizeofIfAnnounceMsghdr = 0x18
+ SizeofRtMsghdr = 0x5c
+ SizeofRtMetrics = 0x38
+)
+
+type ifMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data ifData
+}
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type ifData struct {
+ Type uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Link_state uint8
+ Vhid uint8
+ Datalen uint16
+ Mtu uint32
+ Metric uint32
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Oqdrops uint64
+ Noproto uint64
+ Hwassist uint64
+ X__ifi_epoch [8]byte
+ X__ifi_lastchange [16]byte
+}
+
+type IfData struct {
+ Type uint8
+ Physical uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Link_state uint8
+ Spare_char1 uint8
+ Spare_char2 uint8
+ Datalen uint8
+ Mtu uint32
+ Metric uint32
+ Baudrate uint32
+ Ipackets uint32
+ Ierrors uint32
+ Opackets uint32
+ Oerrors uint32
+ Collisions uint32
+ Ibytes uint32
+ Obytes uint32
+ Imcasts uint32
+ Omcasts uint32
+ Iqdrops uint32
+ Noproto uint32
+ Hwassist uint32
+ Pad_cgo_0 [4]byte
+ Epoch int64
+ Lastchange Timeval
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Metric int32
+}
+
+type IfmaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+}
+
+type IfAnnounceMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Name [16]int8
+ What uint16
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Fmask int32
+ Inits uint32
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint32
+ Mtu uint32
+ Hopcount uint32
+ Expire uint32
+ Recvpipe uint32
+ Sendpipe uint32
+ Ssthresh uint32
+ Rtt uint32
+ Rttvar uint32
+ Pksent uint32
+ Weight uint32
+ Filler [3]uint32
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfZbuf = 0xc
+ SizeofBpfProgram = 0x8
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x20
+ SizeofBpfZbufHeader = 0x20
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfZbuf struct {
+ Bufa *byte
+ Bufb *byte
+ Buflen uint32
+}
+
+type BpfProgram struct {
+ Len uint32
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp Timeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [6]byte
+}
+
+type BpfZbufHeader struct {
+ Kernel_gen uint32
+ Kernel_len uint32
+ User_gen uint32
+ X_bzh_pad [5]uint32
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+const (
+ AT_FDCWD = -0x64
+ AT_REMOVEDIR = 0x800
+ AT_SYMLINK_FOLLOW = 0x400
+ AT_SYMLINK_NOFOLLOW = 0x200
+)
+
+type CapRights struct {
+ Rights [2]uint64
+}
diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go
new file mode 100644
index 0000000..1e190b1
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go
@@ -0,0 +1,762 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include -m32 linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build 386,linux
+
+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 uint64
+ X__pad1 uint16
+ Pad_cgo_0 [2]byte
+ X__st_ino uint32
+ Mode uint32
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev uint64
+ X__pad2 uint16
+ Pad_cgo_1 [2]byte
+ Size int64
+ Blksize int32
+ Blocks int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ Ino uint64
+}
+
+type Statfs_t struct {
+ Type int32
+ Bsize int32
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Namelen int32
+ Frsize int32
+ Flags int32
+ Spare [4]int32
+}
+
+type Dirent struct {
+ Ino uint64
+ Off int64
+ Reclen uint16
+ Type uint8
+ Name [256]int8
+ Pad_cgo_0 [1]byte
+}
+
+type Fsid struct {
+ X__val [2]int32
+}
+
+type Flock_t struct {
+ Type int16
+ Whence int16
+ Start int64
+ Len int64
+ Pid int32
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ 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 = 0x2b
+ 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 {
+ Ebx int32
+ Ecx int32
+ Edx int32
+ Esi int32
+ Edi int32
+ Ebp int32
+ Eax int32
+ Xds int32
+ Xes int32
+ Xfs int32
+ Xgs int32
+ Orig_eax int32
+ Eip int32
+ Xcs int32
+ Eflags int32
+ Esp int32
+ Xss int32
+}
+
+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
+ 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 RNDGETENTCNT = 0x80045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Line uint8
+ Cc [19]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ Pad_cgo_0 [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ Pad_cgo_1 [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]int8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ Pad_cgo_2 [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ Pad_cgo_3 [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go
new file mode 100644
index 0000000..7fe5eef
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go
@@ -0,0 +1,780 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include -m64 linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,linux
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+ PathMax = 0x1000
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Timex struct {
+ Modes uint32
+ Pad_cgo_0 [4]byte
+ Offset int64
+ Freq int64
+ Maxerror int64
+ Esterror int64
+ Status int32
+ Pad_cgo_1 [4]byte
+ Constant int64
+ Precision int64
+ Tolerance int64
+ Time Timeval
+ Tick int64
+ Ppsfreq int64
+ Jitter int64
+ Shift int32
+ Pad_cgo_2 [4]byte
+ Stabil int64
+ Jitcnt int64
+ Calcnt int64
+ Errcnt int64
+ Stbcnt int64
+ Tai int32
+ Pad_cgo_3 [44]byte
+}
+
+type Time_t int64
+
+type Tms struct {
+ Utime int64
+ Stime int64
+ Cutime int64
+ Cstime int64
+}
+
+type Utimbuf struct {
+ Actime int64
+ Modtime int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev uint64
+ Ino uint64
+ Nlink uint64
+ Mode uint32
+ Uid uint32
+ Gid uint32
+ X__pad0 int32
+ Rdev uint64
+ Size int64
+ Blksize int64
+ Blocks int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ _ [3]int64
+}
+
+type Statfs_t struct {
+ Type int64
+ Bsize int64
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Namelen int64
+ Frsize int64
+ Flags int64
+ Spare [4]int64
+}
+
+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
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+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 uint64
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen uint64
+ Control *byte
+ Controllen uint64
+ Flags int32
+ Pad_cgo_1 [4]byte
+}
+
+type Cmsghdr struct {
+ Len uint64
+ 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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x10
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ SizeofMsghdr = 0x38
+ SizeofCmsghdr = 0x10
+ 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 = 0x2b
+ 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 = 0x10
+)
+
+type SockFilter struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type SockFprog struct {
+ Len uint16
+ Pad_cgo_0 [6]byte
+ Filter *SockFilter
+}
+
+type InotifyEvent struct {
+ Wd int32
+ Mask uint32
+ Cookie uint32
+ Len uint32
+}
+
+const SizeofInotifyEvent = 0x10
+
+type PtraceRegs struct {
+ R15 uint64
+ R14 uint64
+ R13 uint64
+ R12 uint64
+ Rbp uint64
+ Rbx uint64
+ R11 uint64
+ R10 uint64
+ R9 uint64
+ R8 uint64
+ Rax uint64
+ Rcx uint64
+ Rdx uint64
+ Rsi uint64
+ Rdi uint64
+ Orig_rax uint64
+ Rip uint64
+ Cs uint64
+ Eflags uint64
+ Rsp uint64
+ Ss uint64
+ Fs_base uint64
+ Gs_base uint64
+ Ds uint64
+ Es uint64
+ Fs uint64
+ Gs uint64
+}
+
+type FdSet struct {
+ Bits [16]int64
+}
+
+type Sysinfo_t struct {
+ Uptime int64
+ Loads [3]uint64
+ Totalram uint64
+ Freeram uint64
+ Sharedram uint64
+ Bufferram uint64
+ Totalswap uint64
+ Freeswap uint64
+ Procs uint16
+ Pad uint16
+ Pad_cgo_0 [4]byte
+ Totalhigh uint64
+ Freehigh uint64
+ Unit uint32
+ X_f [0]int8
+ Pad_cgo_1 [4]byte
+}
+
+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
+ Pad_cgo_0 [4]byte
+ Tinode uint64
+ Fname [6]int8
+ Fpack [6]int8
+ Pad_cgo_1 [4]byte
+}
+
+type EpollEvent struct {
+ Events uint32
+ 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 [16]uint64
+}
+
+const RNDGETENTCNT = 0x80045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Line uint8
+ Cc [19]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ Pad_cgo_0 [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ Pad_cgo_1 [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]int8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ Pad_cgo_2 [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ Pad_cgo_3 [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go
new file mode 100644
index 0000000..9cc3c39
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go
@@ -0,0 +1,751 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm,linux
+
+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 uint64
+ X__pad1 uint16
+ Pad_cgo_0 [2]byte
+ X__st_ino uint32
+ Mode uint32
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev uint64
+ X__pad2 uint16
+ Pad_cgo_1 [6]byte
+ Size int64
+ Blksize int32
+ Pad_cgo_2 [4]byte
+ Blocks int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ Ino uint64
+}
+
+type Statfs_t struct {
+ Type int32
+ Bsize int32
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Namelen int32
+ Frsize int32
+ Flags int32
+ Spare [4]int32
+ Pad_cgo_0 [4]byte
+}
+
+type Dirent struct {
+ Ino uint64
+ Off int64
+ Reclen uint16
+ Type uint8
+ Name [256]uint8
+ 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
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+type RawSockaddr struct {
+ Family uint16
+ Data [14]uint8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [96]uint8
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ 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 = 0x2b
+ 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 {
+ Uregs [18]uint32
+}
+
+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]uint8
+}
+
+type Utsname struct {
+ Sysname [65]uint8
+ Nodename [65]uint8
+ Release [65]uint8
+ Version [65]uint8
+ Machine [65]uint8
+ Domainname [65]uint8
+}
+
+type Ustat_t struct {
+ Tfree int32
+ Tinode uint32
+ Fname [6]uint8
+ Fpack [6]uint8
+}
+
+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 RNDGETENTCNT = 0x80045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Line uint8
+ Cc [19]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ Pad_cgo_0 [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ Pad_cgo_1 [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]uint8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ Pad_cgo_2 [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ Pad_cgo_3 [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go
new file mode 100644
index 0000000..ce1e5db
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go
@@ -0,0 +1,759 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build arm64,linux
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+ PathMax = 0x1000
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Timex struct {
+ Modes uint32
+ Pad_cgo_0 [4]byte
+ Offset int64
+ Freq int64
+ Maxerror int64
+ Esterror int64
+ Status int32
+ Pad_cgo_1 [4]byte
+ Constant int64
+ Precision int64
+ Tolerance int64
+ Time Timeval
+ Tick int64
+ Ppsfreq int64
+ Jitter int64
+ Shift int32
+ Pad_cgo_2 [4]byte
+ Stabil int64
+ Jitcnt int64
+ Calcnt int64
+ Errcnt int64
+ Stbcnt int64
+ Tai int32
+ Pad_cgo_3 [44]byte
+}
+
+type Time_t int64
+
+type Tms struct {
+ Utime int64
+ Stime int64
+ Cutime int64
+ Cstime int64
+}
+
+type Utimbuf struct {
+ Actime int64
+ Modtime int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev uint64
+ Ino uint64
+ Mode uint32
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev uint64
+ X__pad1 uint64
+ Size int64
+ Blksize int32
+ X__pad2 int32
+ Blocks int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ _ [2]int32
+}
+
+type Statfs_t struct {
+ Type int64
+ Bsize int64
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Namelen int64
+ Frsize int64
+ Flags int64
+ Spare [4]int64
+}
+
+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
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+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 uint64
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen uint64
+ Control *byte
+ Controllen uint64
+ Flags int32
+ Pad_cgo_1 [4]byte
+}
+
+type Cmsghdr struct {
+ Len uint64
+ 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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x10
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ SizeofMsghdr = 0x38
+ SizeofCmsghdr = 0x10
+ 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 = 0x2b
+ 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 = 0x10
+)
+
+type SockFilter struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type SockFprog struct {
+ Len uint16
+ Pad_cgo_0 [6]byte
+ Filter *SockFilter
+}
+
+type InotifyEvent struct {
+ Wd int32
+ Mask uint32
+ Cookie uint32
+ Len uint32
+}
+
+const SizeofInotifyEvent = 0x10
+
+type PtraceRegs struct {
+ Regs [31]uint64
+ Sp uint64
+ Pc uint64
+ Pstate uint64
+}
+
+type FdSet struct {
+ Bits [16]int64
+}
+
+type Sysinfo_t struct {
+ Uptime int64
+ Loads [3]uint64
+ Totalram uint64
+ Freeram uint64
+ Sharedram uint64
+ Bufferram uint64
+ Totalswap uint64
+ Freeswap uint64
+ Procs uint16
+ Pad uint16
+ Pad_cgo_0 [4]byte
+ Totalhigh uint64
+ Freehigh uint64
+ Unit uint32
+ X_f [0]int8
+ Pad_cgo_1 [4]byte
+}
+
+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
+ Pad_cgo_0 [4]byte
+ Tinode uint64
+ Fname [6]int8
+ Fpack [6]int8
+ Pad_cgo_1 [4]byte
+}
+
+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 [16]uint64
+}
+
+const RNDGETENTCNT = 0x80045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Line uint8
+ Cc [19]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ Pad_cgo_0 [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ Pad_cgo_1 [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]int8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ Pad_cgo_2 [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ Pad_cgo_3 [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
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..9193286
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go
@@ -0,0 +1,756 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build mips,linux
+
+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
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ 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 = 0x2b
+ 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 [32]uint64
+ Lo uint64
+ Hi uint64
+ Epc uint64
+ Badvaddr uint64
+ Status uint64
+ Cause uint64
+}
+
+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 RNDGETENTCNT = 0x40045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Line uint8
+ Cc [23]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ Pad_cgo_0 [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ Pad_cgo_1 [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]int8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ Pad_cgo_2 [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ Pad_cgo_3 [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go
new file mode 100644
index 0000000..e7ac623
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go
@@ -0,0 +1,761 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build mips64,linux
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+ PathMax = 0x1000
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Timex struct {
+ Modes uint32
+ Pad_cgo_0 [4]byte
+ Offset int64
+ Freq int64
+ Maxerror int64
+ Esterror int64
+ Status int32
+ Pad_cgo_1 [4]byte
+ Constant int64
+ Precision int64
+ Tolerance int64
+ Time Timeval
+ Tick int64
+ Ppsfreq int64
+ Jitter int64
+ Shift int32
+ Pad_cgo_2 [4]byte
+ Stabil int64
+ Jitcnt int64
+ Calcnt int64
+ Errcnt int64
+ Stbcnt int64
+ Tai int32
+ Pad_cgo_3 [44]byte
+}
+
+type Time_t int64
+
+type Tms struct {
+ Utime int64
+ Stime int64
+ Cutime int64
+ Cstime int64
+}
+
+type Utimbuf struct {
+ Actime int64
+ Modtime int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev uint32
+ Pad1 [3]uint32
+ Ino uint64
+ Mode uint32
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev uint32
+ Pad2 [3]uint32
+ Size int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ Blksize uint32
+ Pad4 uint32
+ Blocks int64
+}
+
+type Statfs_t struct {
+ Type int64
+ Bsize int64
+ Frsize int64
+ Blocks uint64
+ Bfree uint64
+ Files uint64
+ Ffree uint64
+ Bavail uint64
+ Fsid Fsid
+ Namelen int64
+ Flags int64
+ Spare [5]int64
+}
+
+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
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+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 uint64
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen uint64
+ Control *byte
+ Controllen uint64
+ Flags int32
+ Pad_cgo_1 [4]byte
+}
+
+type Cmsghdr struct {
+ Len uint64
+ 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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x10
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ SizeofMsghdr = 0x38
+ SizeofCmsghdr = 0x10
+ 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 = 0x2b
+ 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 = 0x10
+)
+
+type SockFilter struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type SockFprog struct {
+ Len uint16
+ Pad_cgo_0 [6]byte
+ Filter *SockFilter
+}
+
+type InotifyEvent struct {
+ Wd int32
+ Mask uint32
+ Cookie uint32
+ Len uint32
+}
+
+const SizeofInotifyEvent = 0x10
+
+type PtraceRegs struct {
+ Regs [32]uint64
+ Lo uint64
+ Hi uint64
+ Epc uint64
+ Badvaddr uint64
+ Status uint64
+ Cause uint64
+}
+
+type FdSet struct {
+ Bits [16]int64
+}
+
+type Sysinfo_t struct {
+ Uptime int64
+ Loads [3]uint64
+ Totalram uint64
+ Freeram uint64
+ Sharedram uint64
+ Bufferram uint64
+ Totalswap uint64
+ Freeswap uint64
+ Procs uint16
+ Pad uint16
+ Pad_cgo_0 [4]byte
+ Totalhigh uint64
+ Freehigh uint64
+ Unit uint32
+ X_f [0]int8
+ Pad_cgo_1 [4]byte
+}
+
+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
+ Pad_cgo_0 [4]byte
+ Tinode uint64
+ Fname [6]int8
+ Fpack [6]int8
+ Pad_cgo_1 [4]byte
+}
+
+type EpollEvent struct {
+ Events uint32
+ 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 [16]uint64
+}
+
+const RNDGETENTCNT = 0x40045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Line uint8
+ Cc [23]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ Pad_cgo_0 [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ Pad_cgo_1 [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]int8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ Pad_cgo_2 [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ Pad_cgo_3 [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go
new file mode 100644
index 0000000..11190f0
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go
@@ -0,0 +1,761 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build mips64le,linux
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+ PathMax = 0x1000
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Timex struct {
+ Modes uint32
+ Pad_cgo_0 [4]byte
+ Offset int64
+ Freq int64
+ Maxerror int64
+ Esterror int64
+ Status int32
+ Pad_cgo_1 [4]byte
+ Constant int64
+ Precision int64
+ Tolerance int64
+ Time Timeval
+ Tick int64
+ Ppsfreq int64
+ Jitter int64
+ Shift int32
+ Pad_cgo_2 [4]byte
+ Stabil int64
+ Jitcnt int64
+ Calcnt int64
+ Errcnt int64
+ Stbcnt int64
+ Tai int32
+ Pad_cgo_3 [44]byte
+}
+
+type Time_t int64
+
+type Tms struct {
+ Utime int64
+ Stime int64
+ Cutime int64
+ Cstime int64
+}
+
+type Utimbuf struct {
+ Actime int64
+ Modtime int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev uint32
+ Pad1 [3]uint32
+ Ino uint64
+ Mode uint32
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev uint32
+ Pad2 [3]uint32
+ Size int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ Blksize uint32
+ Pad4 uint32
+ Blocks int64
+}
+
+type Statfs_t struct {
+ Type int64
+ Bsize int64
+ Frsize int64
+ Blocks uint64
+ Bfree uint64
+ Files uint64
+ Ffree uint64
+ Bavail uint64
+ Fsid Fsid
+ Namelen int64
+ Flags int64
+ Spare [5]int64
+}
+
+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
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+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 uint64
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen uint64
+ Control *byte
+ Controllen uint64
+ Flags int32
+ Pad_cgo_1 [4]byte
+}
+
+type Cmsghdr struct {
+ Len uint64
+ 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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x10
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ SizeofMsghdr = 0x38
+ SizeofCmsghdr = 0x10
+ 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 = 0x2b
+ 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 = 0x10
+)
+
+type SockFilter struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type SockFprog struct {
+ Len uint16
+ Pad_cgo_0 [6]byte
+ Filter *SockFilter
+}
+
+type InotifyEvent struct {
+ Wd int32
+ Mask uint32
+ Cookie uint32
+ Len uint32
+}
+
+const SizeofInotifyEvent = 0x10
+
+type PtraceRegs struct {
+ Regs [32]uint64
+ Lo uint64
+ Hi uint64
+ Epc uint64
+ Badvaddr uint64
+ Status uint64
+ Cause uint64
+}
+
+type FdSet struct {
+ Bits [16]int64
+}
+
+type Sysinfo_t struct {
+ Uptime int64
+ Loads [3]uint64
+ Totalram uint64
+ Freeram uint64
+ Sharedram uint64
+ Bufferram uint64
+ Totalswap uint64
+ Freeswap uint64
+ Procs uint16
+ Pad uint16
+ Pad_cgo_0 [4]byte
+ Totalhigh uint64
+ Freehigh uint64
+ Unit uint32
+ X_f [0]int8
+ Pad_cgo_1 [4]byte
+}
+
+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
+ Pad_cgo_0 [4]byte
+ Tinode uint64
+ Fname [6]int8
+ Fpack [6]int8
+ Pad_cgo_1 [4]byte
+}
+
+type EpollEvent struct {
+ Events uint32
+ 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 [16]uint64
+}
+
+const RNDGETENTCNT = 0x40045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Line uint8
+ Cc [23]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ Pad_cgo_0 [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ Pad_cgo_1 [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]int8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ Pad_cgo_2 [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ Pad_cgo_3 [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
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..a55a584
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go
@@ -0,0 +1,756 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build mipsle,linux
+
+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
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ 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 = 0x2b
+ 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 [32]uint64
+ Lo uint64
+ Hi uint64
+ Epc uint64
+ Badvaddr uint64
+ Status uint64
+ Cause uint64
+}
+
+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 RNDGETENTCNT = 0x40045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Line uint8
+ Cc [23]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ Pad_cgo_0 [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ Pad_cgo_1 [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]int8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ Pad_cgo_2 [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ Pad_cgo_3 [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go
new file mode 100644
index 0000000..251a021
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go
@@ -0,0 +1,769 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build ppc64,linux
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+ PathMax = 0x1000
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Timex struct {
+ Modes uint32
+ Pad_cgo_0 [4]byte
+ Offset int64
+ Freq int64
+ Maxerror int64
+ Esterror int64
+ Status int32
+ Pad_cgo_1 [4]byte
+ Constant int64
+ Precision int64
+ Tolerance int64
+ Time Timeval
+ Tick int64
+ Ppsfreq int64
+ Jitter int64
+ Shift int32
+ Pad_cgo_2 [4]byte
+ Stabil int64
+ Jitcnt int64
+ Calcnt int64
+ Errcnt int64
+ Stbcnt int64
+ Tai int32
+ Pad_cgo_3 [44]byte
+}
+
+type Time_t int64
+
+type Tms struct {
+ Utime int64
+ Stime int64
+ Cutime int64
+ Cstime int64
+}
+
+type Utimbuf struct {
+ Actime int64
+ Modtime int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev uint64
+ Ino uint64
+ Nlink uint64
+ Mode uint32
+ Uid uint32
+ Gid uint32
+ X__pad2 int32
+ Rdev uint64
+ Size int64
+ Blksize int64
+ Blocks int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ _ uint64
+ _ uint64
+ _ uint64
+}
+
+type Statfs_t struct {
+ Type int64
+ Bsize int64
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Namelen int64
+ Frsize int64
+ Flags int64
+ Spare [4]int64
+}
+
+type Dirent struct {
+ Ino uint64
+ Off int64
+ Reclen uint16
+ Type uint8
+ Name [256]uint8
+ 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
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+type RawSockaddr struct {
+ Family uint16
+ Data [14]uint8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [96]uint8
+}
+
+type _Socklen uint32
+
+type Linger struct {
+ Onoff int32
+ Linger int32
+}
+
+type Iovec struct {
+ Base *byte
+ Len uint64
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen uint64
+ Control *byte
+ Controllen uint64
+ Flags int32
+ Pad_cgo_1 [4]byte
+}
+
+type Cmsghdr struct {
+ Len uint64
+ 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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x10
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ SizeofMsghdr = 0x38
+ SizeofCmsghdr = 0x10
+ 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 = 0x2b
+ 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 = 0x10
+)
+
+type SockFilter struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type SockFprog struct {
+ Len uint16
+ Pad_cgo_0 [6]byte
+ Filter *SockFilter
+}
+
+type InotifyEvent struct {
+ Wd int32
+ Mask uint32
+ Cookie uint32
+ Len uint32
+}
+
+const SizeofInotifyEvent = 0x10
+
+type PtraceRegs struct {
+ Gpr [32]uint64
+ Nip uint64
+ Msr uint64
+ Orig_gpr3 uint64
+ Ctr uint64
+ Link uint64
+ Xer uint64
+ Ccr uint64
+ Softe uint64
+ Trap uint64
+ Dar uint64
+ Dsisr uint64
+ Result uint64
+}
+
+type FdSet struct {
+ Bits [16]int64
+}
+
+type Sysinfo_t struct {
+ Uptime int64
+ Loads [3]uint64
+ Totalram uint64
+ Freeram uint64
+ Sharedram uint64
+ Bufferram uint64
+ Totalswap uint64
+ Freeswap uint64
+ Procs uint16
+ Pad uint16
+ Pad_cgo_0 [4]byte
+ Totalhigh uint64
+ Freehigh uint64
+ Unit uint32
+ X_f [0]uint8
+ Pad_cgo_1 [4]byte
+}
+
+type Utsname struct {
+ Sysname [65]uint8
+ Nodename [65]uint8
+ Release [65]uint8
+ Version [65]uint8
+ Machine [65]uint8
+ Domainname [65]uint8
+}
+
+type Ustat_t struct {
+ Tfree int32
+ Pad_cgo_0 [4]byte
+ Tinode uint64
+ Fname [6]uint8
+ Fpack [6]uint8
+ Pad_cgo_1 [4]byte
+}
+
+type EpollEvent struct {
+ Events uint32
+ X_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 [16]uint64
+}
+
+const RNDGETENTCNT = 0x40045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [19]uint8
+ Line uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ Pad_cgo_0 [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ Pad_cgo_1 [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]uint8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ Pad_cgo_2 [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ Pad_cgo_3 [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go
new file mode 100644
index 0000000..b7d7028
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go
@@ -0,0 +1,769 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build ppc64le,linux
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+ PathMax = 0x1000
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Timex struct {
+ Modes uint32
+ Pad_cgo_0 [4]byte
+ Offset int64
+ Freq int64
+ Maxerror int64
+ Esterror int64
+ Status int32
+ Pad_cgo_1 [4]byte
+ Constant int64
+ Precision int64
+ Tolerance int64
+ Time Timeval
+ Tick int64
+ Ppsfreq int64
+ Jitter int64
+ Shift int32
+ Pad_cgo_2 [4]byte
+ Stabil int64
+ Jitcnt int64
+ Calcnt int64
+ Errcnt int64
+ Stbcnt int64
+ Tai int32
+ Pad_cgo_3 [44]byte
+}
+
+type Time_t int64
+
+type Tms struct {
+ Utime int64
+ Stime int64
+ Cutime int64
+ Cstime int64
+}
+
+type Utimbuf struct {
+ Actime int64
+ Modtime int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev uint64
+ Ino uint64
+ Nlink uint64
+ Mode uint32
+ Uid uint32
+ Gid uint32
+ X__pad2 int32
+ Rdev uint64
+ Size int64
+ Blksize int64
+ Blocks int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ _ uint64
+ _ uint64
+ _ uint64
+}
+
+type Statfs_t struct {
+ Type int64
+ Bsize int64
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Namelen int64
+ Frsize int64
+ Flags int64
+ Spare [4]int64
+}
+
+type Dirent struct {
+ Ino uint64
+ Off int64
+ Reclen uint16
+ Type uint8
+ Name [256]uint8
+ 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
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+type RawSockaddr struct {
+ Family uint16
+ Data [14]uint8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [96]uint8
+}
+
+type _Socklen uint32
+
+type Linger struct {
+ Onoff int32
+ Linger int32
+}
+
+type Iovec struct {
+ Base *byte
+ Len uint64
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen uint64
+ Control *byte
+ Controllen uint64
+ Flags int32
+ Pad_cgo_1 [4]byte
+}
+
+type Cmsghdr struct {
+ Len uint64
+ 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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x10
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ SizeofMsghdr = 0x38
+ SizeofCmsghdr = 0x10
+ 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 = 0x2b
+ 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 = 0x10
+)
+
+type SockFilter struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type SockFprog struct {
+ Len uint16
+ Pad_cgo_0 [6]byte
+ Filter *SockFilter
+}
+
+type InotifyEvent struct {
+ Wd int32
+ Mask uint32
+ Cookie uint32
+ Len uint32
+}
+
+const SizeofInotifyEvent = 0x10
+
+type PtraceRegs struct {
+ Gpr [32]uint64
+ Nip uint64
+ Msr uint64
+ Orig_gpr3 uint64
+ Ctr uint64
+ Link uint64
+ Xer uint64
+ Ccr uint64
+ Softe uint64
+ Trap uint64
+ Dar uint64
+ Dsisr uint64
+ Result uint64
+}
+
+type FdSet struct {
+ Bits [16]int64
+}
+
+type Sysinfo_t struct {
+ Uptime int64
+ Loads [3]uint64
+ Totalram uint64
+ Freeram uint64
+ Sharedram uint64
+ Bufferram uint64
+ Totalswap uint64
+ Freeswap uint64
+ Procs uint16
+ Pad uint16
+ Pad_cgo_0 [4]byte
+ Totalhigh uint64
+ Freehigh uint64
+ Unit uint32
+ X_f [0]uint8
+ Pad_cgo_1 [4]byte
+}
+
+type Utsname struct {
+ Sysname [65]uint8
+ Nodename [65]uint8
+ Release [65]uint8
+ Version [65]uint8
+ Machine [65]uint8
+ Domainname [65]uint8
+}
+
+type Ustat_t struct {
+ Tfree int32
+ Pad_cgo_0 [4]byte
+ Tinode uint64
+ Fname [6]uint8
+ Fpack [6]uint8
+ Pad_cgo_1 [4]byte
+}
+
+type EpollEvent struct {
+ Events uint32
+ X_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 [16]uint64
+}
+
+const RNDGETENTCNT = 0x40045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [19]uint8
+ Line uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ Pad_cgo_0 [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ Pad_cgo_1 [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]uint8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ Pad_cgo_2 [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ Pad_cgo_3 [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go
new file mode 100644
index 0000000..f06b2ed
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go
@@ -0,0 +1,786 @@
+// cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char linux/types.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build s390x,linux
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+ PathMax = 0x1000
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Timex struct {
+ Modes uint32
+ _ [4]byte
+ Offset int64
+ Freq int64
+ Maxerror int64
+ Esterror int64
+ Status int32
+ _ [4]byte
+ Constant int64
+ Precision int64
+ Tolerance int64
+ Time Timeval
+ Tick int64
+ Ppsfreq int64
+ Jitter int64
+ Shift int32
+ _ [4]byte
+ Stabil int64
+ Jitcnt int64
+ Calcnt int64
+ Errcnt int64
+ Stbcnt int64
+ Tai int32
+ _ [44]byte
+}
+
+type Time_t int64
+
+type Tms struct {
+ Utime int64
+ Stime int64
+ Cutime int64
+ Cstime int64
+}
+
+type Utimbuf struct {
+ Actime int64
+ Modtime int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev uint64
+ Ino uint64
+ Nlink uint64
+ Mode uint32
+ Uid uint32
+ Gid uint32
+ _ int32
+ Rdev uint64
+ Size int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ Blksize int64
+ Blocks int64
+ _ [3]int64
+}
+
+type Statfs_t struct {
+ Type uint32
+ Bsize uint32
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Namelen uint32
+ Frsize uint32
+ Flags uint32
+ Spare [4]uint32
+ _ [4]byte
+}
+
+type Dirent struct {
+ Ino uint64
+ Off int64
+ Reclen uint16
+ Type uint8
+ Name [256]int8
+ _ [5]byte
+}
+
+type Fsid struct {
+ _ [2]int32
+}
+
+type Flock_t struct {
+ Type int16
+ Whence int16
+ _ [4]byte
+ Start int64
+ Len int64
+ Pid int32
+ _ [4]byte
+}
+
+type FscryptPolicy struct {
+ Version uint8
+ Contents_encryption_mode uint8
+ Filenames_encryption_mode uint8
+ Flags uint8
+ Master_key_descriptor [8]uint8
+}
+
+type FscryptKey struct {
+ Mode uint32
+ Raw [64]uint8
+ Size uint32
+}
+
+type KeyctlDHParams struct {
+ Private int32
+ Prime int32
+ Base int32
+}
+
+const (
+ FADV_NORMAL = 0x0
+ FADV_RANDOM = 0x1
+ FADV_SEQUENTIAL = 0x2
+ FADV_WILLNEED = 0x3
+ FADV_DONTNEED = 0x6
+ FADV_NOREUSE = 0x7
+)
+
+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
+ _ [2]byte
+ Ifindex int32
+ Addr [8]byte
+}
+
+type RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+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 uint64
+}
+
+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 PacketMreq struct {
+ Ifindex int32
+ Type uint16
+ Alen uint16
+ Address [8]uint8
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ _ [4]byte
+ Iov *Iovec
+ Iovlen uint64
+ Control *byte
+ Controllen uint64
+ Flags int32
+ _ [4]byte
+}
+
+type Cmsghdr struct {
+ Len uint64
+ 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
+ _ [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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIovec = 0x10
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofPacketMreq = 0x10
+ SizeofMsghdr = 0x38
+ SizeofCmsghdr = 0x10
+ 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 = 0x2b
+ 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
+ _ 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 = 0x10
+)
+
+type SockFilter struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type SockFprog struct {
+ Len uint16
+ _ [6]byte
+ Filter *SockFilter
+}
+
+type InotifyEvent struct {
+ Wd int32
+ Mask uint32
+ Cookie uint32
+ Len uint32
+}
+
+const SizeofInotifyEvent = 0x10
+
+type PtraceRegs struct {
+ Psw PtracePsw
+ Gprs [16]uint64
+ Acrs [16]uint32
+ Orig_gpr2 uint64
+ Fp_regs PtraceFpregs
+ Per_info PtracePer
+ Ieee_instruction_pointer uint64
+}
+
+type PtracePsw struct {
+ Mask uint64
+ Addr uint64
+}
+
+type PtraceFpregs struct {
+ Fpc uint32
+ _ [4]byte
+ Fprs [16]float64
+}
+
+type PtracePer struct {
+ _ [0]uint64
+ _ [24]byte
+ _ [8]byte
+ Starting_addr uint64
+ Ending_addr uint64
+ Perc_atmid uint16
+ _ [6]byte
+ Address uint64
+ Access_id uint8
+ _ [7]byte
+}
+
+type FdSet struct {
+ Bits [16]int64
+}
+
+type Sysinfo_t struct {
+ Uptime int64
+ Loads [3]uint64
+ Totalram uint64
+ Freeram uint64
+ Sharedram uint64
+ Bufferram uint64
+ Totalswap uint64
+ Freeswap uint64
+ Procs uint16
+ Pad uint16
+ _ [4]byte
+ Totalhigh uint64
+ Freehigh uint64
+ Unit uint32
+ _ [0]int8
+ _ [4]byte
+}
+
+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
+ _ [4]byte
+ Tinode uint64
+ Fname [6]int8
+ Fpack [6]int8
+ _ [4]byte
+}
+
+type EpollEvent struct {
+ Events uint32
+ _ 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 {
+ _ [16]uint64
+}
+
+const RNDGETENTCNT = 0x80045200
+
+const PERF_IOC_FLAG_GROUP = 0x1
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Line uint8
+ Cc [19]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
+
+type Taskstats struct {
+ Version uint16
+ _ [2]byte
+ Ac_exitcode uint32
+ Ac_flag uint8
+ Ac_nice uint8
+ _ [6]byte
+ Cpu_count uint64
+ Cpu_delay_total uint64
+ Blkio_count uint64
+ Blkio_delay_total uint64
+ Swapin_count uint64
+ Swapin_delay_total uint64
+ Cpu_run_real_total uint64
+ Cpu_run_virtual_total uint64
+ Ac_comm [32]int8
+ Ac_sched uint8
+ Ac_pad [3]uint8
+ _ [4]byte
+ Ac_uid uint32
+ Ac_gid uint32
+ Ac_pid uint32
+ Ac_ppid uint32
+ Ac_btime uint32
+ _ [4]byte
+ Ac_etime uint64
+ Ac_utime uint64
+ Ac_stime uint64
+ Ac_minflt uint64
+ Ac_majflt uint64
+ Coremem uint64
+ Virtmem uint64
+ Hiwater_rss uint64
+ Hiwater_vm uint64
+ Read_char uint64
+ Write_char uint64
+ Read_syscalls uint64
+ Write_syscalls uint64
+ Read_bytes uint64
+ Write_bytes uint64
+ Cancelled_write_bytes uint64
+ Nvcsw uint64
+ Nivcsw uint64
+ Ac_utimescaled uint64
+ Ac_stimescaled uint64
+ Cpu_scaled_run_real_total uint64
+ Freepages_count uint64
+ Freepages_delay_total uint64
+}
+
+const (
+ TASKSTATS_CMD_UNSPEC = 0x0
+ TASKSTATS_CMD_GET = 0x1
+ TASKSTATS_CMD_NEW = 0x2
+ TASKSTATS_TYPE_UNSPEC = 0x0
+ TASKSTATS_TYPE_PID = 0x1
+ TASKSTATS_TYPE_TGID = 0x2
+ TASKSTATS_TYPE_STATS = 0x3
+ TASKSTATS_TYPE_AGGR_PID = 0x4
+ TASKSTATS_TYPE_AGGR_TGID = 0x5
+ TASKSTATS_TYPE_NULL = 0x6
+ TASKSTATS_CMD_ATTR_UNSPEC = 0x0
+ TASKSTATS_CMD_ATTR_PID = 0x1
+ TASKSTATS_CMD_ATTR_TGID = 0x2
+ TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
+ TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go
new file mode 100644
index 0000000..22bdab9
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go
@@ -0,0 +1,666 @@
+// +build sparc64,linux
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_linux.go | go run mkpost.go
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+ PathMax = 0x1000
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int32
+ Pad_cgo_0 [4]byte
+}
+
+type Timex struct {
+ Modes uint32
+ Pad_cgo_0 [4]byte
+ Offset int64
+ Freq int64
+ Maxerror int64
+ Esterror int64
+ Status int32
+ Pad_cgo_1 [4]byte
+ Constant int64
+ Precision int64
+ Tolerance int64
+ Time Timeval
+ Tick int64
+ Ppsfreq int64
+ Jitter int64
+ Shift int32
+ Pad_cgo_2 [4]byte
+ Stabil int64
+ Jitcnt int64
+ Calcnt int64
+ Errcnt int64
+ Stbcnt int64
+ Tai int32
+ Pad_cgo_3 [44]byte
+}
+
+type Time_t int64
+
+type Tms struct {
+ Utime int64
+ Stime int64
+ Cutime int64
+ Cstime int64
+}
+
+type Utimbuf struct {
+ Actime int64
+ Modtime int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev uint64
+ X__pad1 uint16
+ Pad_cgo_0 [6]byte
+ Ino uint64
+ Mode uint32
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev uint64
+ X__pad2 uint16
+ Pad_cgo_1 [6]byte
+ Size int64
+ Blksize int64
+ Blocks int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ X__glibc_reserved4 uint64
+ X__glibc_reserved5 uint64
+}
+
+type Statfs_t struct {
+ Type int64
+ Bsize int64
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid Fsid
+ Namelen int64
+ Frsize int64
+ Flags int64
+ Spare [4]int64
+}
+
+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
+ X__glibc_reserved int16
+ Pad_cgo_1 [2]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 RawSockaddrALG struct {
+ Family uint16
+ Type [14]uint8
+ Feat uint32
+ Mask uint32
+ Name [64]uint8
+}
+
+type RawSockaddrVM struct {
+ Family uint16
+ Reserved1 uint16
+ Port uint32
+ Cid uint32
+ Zero [4]uint8
+}
+
+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 uint64
+}
+
+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
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen uint64
+ Control *byte
+ Controllen uint64
+ Flags int32
+ Pad_cgo_1 [4]byte
+}
+
+type Cmsghdr struct {
+ Len uint64
+ 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
+ SizeofSockaddrALG = 0x58
+ SizeofSockaddrVM = 0x10
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPMreqn = 0xc
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x38
+ SizeofCmsghdr = 0x10
+ 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 = 0x10
+)
+
+type SockFilter struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type SockFprog struct {
+ Len uint16
+ Pad_cgo_0 [6]byte
+ Filter *SockFilter
+}
+
+type InotifyEvent struct {
+ Wd int32
+ Mask uint32
+ Cookie uint32
+ Len uint32
+}
+
+const SizeofInotifyEvent = 0x10
+
+type PtraceRegs struct {
+ Regs [16]uint64
+ Tstate uint64
+ Tpc uint64
+ Tnpc uint64
+ Y uint32
+ Magic uint32
+}
+
+type ptracePsw struct {
+}
+
+type ptraceFpregs struct {
+}
+
+type ptracePer struct {
+}
+
+type FdSet struct {
+ Bits [16]int64
+}
+
+type Sysinfo_t struct {
+ Uptime int64
+ Loads [3]uint64
+ Totalram uint64
+ Freeram uint64
+ Sharedram uint64
+ Bufferram uint64
+ Totalswap uint64
+ Freeswap uint64
+ Procs uint16
+ Pad uint16
+ Pad_cgo_0 [4]byte
+ Totalhigh uint64
+ Freehigh uint64
+ Unit uint32
+ X_f [0]int8
+ Pad_cgo_1 [4]byte
+}
+
+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
+ Pad_cgo_0 [4]byte
+ Tinode uint64
+ Fname [6]int8
+ Fpack [6]int8
+ Pad_cgo_1 [4]byte
+}
+
+type EpollEvent struct {
+ Events uint32
+ X_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 = 0x800
+ POLLERR = 0x8
+ POLLHUP = 0x10
+ POLLNVAL = 0x20
+)
+
+type Sigset_t struct {
+ X__val [16]uint64
+}
+
+const _SC_PAGESIZE = 0x1e
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Line uint8
+ Cc [19]uint8
+ Ispeed uint32
+ Ospeed uint32
+}
diff --git a/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go b/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go
new file mode 100644
index 0000000..42f99c0
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go
@@ -0,0 +1,401 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_netbsd.go
+
+// +build 386,netbsd
+
+package unix
+
+const (
+ sizeofPtr = 0x4
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x4
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int32
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int32
+}
+
+type Timeval struct {
+ Sec int64
+ Usec 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 uint64
+ Mode uint32
+ Ino uint64
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev uint64
+ Atimespec Timespec
+ Mtimespec Timespec
+ Ctimespec Timespec
+ Birthtimespec Timespec
+ Size int64
+ Blocks int64
+ Blksize uint32
+ Flags uint32
+ Gen uint32
+ Spare [2]uint32
+}
+
+type Statfs_t [0]byte
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Dirent struct {
+ Fileno uint64
+ Reclen uint16
+ Namlen uint16
+ Type uint8
+ Name [512]int8
+ Pad_cgo_0 [3]byte
+}
+
+type Fsid struct {
+ X__fsid_val [2]int32
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]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 IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Iov *Iovec
+ Iovlen int32
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x14
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x1c
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint32
+ Filter uint32
+ Flags uint32
+ Fflags uint32
+ Data int64
+ Udata int32
+}
+
+type FdSet struct {
+ Bits [8]uint32
+}
+
+const (
+ SizeofIfMsghdr = 0x98
+ SizeofIfData = 0x84
+ SizeofIfaMsghdr = 0x18
+ SizeofIfAnnounceMsghdr = 0x18
+ SizeofRtMsghdr = 0x78
+ SizeofRtMetrics = 0x50
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+ Pad_cgo_1 [4]byte
+}
+
+type IfData struct {
+ Type uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Pad_cgo_0 [1]byte
+ Link_state int32
+ Mtu uint64
+ Metric uint64
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Noproto uint64
+ Lastchange Timespec
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Metric int32
+ Index uint16
+ Pad_cgo_0 [6]byte
+}
+
+type IfAnnounceMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Name [16]int8
+ What uint16
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Use int32
+ Inits int32
+ Pad_cgo_1 [4]byte
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint64
+ Mtu uint64
+ Hopcount uint64
+ Recvpipe uint64
+ Sendpipe uint64
+ Ssthresh uint64
+ Rtt uint64
+ Rttvar uint64
+ Expire int64
+ Pksent int64
+}
+
+type Mclpool [0]byte
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x80
+ SizeofBpfProgram = 0x8
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint64
+ Drop uint64
+ Capt uint64
+ Padding [13]uint64
+}
+
+type BpfProgram struct {
+ Len uint32
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp BpfTimeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+type BpfTimeval struct {
+ Sec int32
+ Usec int32
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed int32
+ Ospeed int32
+}
+
+const (
+ AT_FDCWD = -0x64
+ AT_SYMLINK_NOFOLLOW = 0x200
+)
+
+type Sysctlnode struct {
+ Flags uint32
+ Num int32
+ Name [32]int8
+ Ver uint32
+ X__rsvd uint32
+ Un [16]byte
+ X_sysctl_size [8]byte
+ X_sysctl_func [8]byte
+ X_sysctl_parent [8]byte
+ X_sysctl_desc [8]byte
+}
diff --git a/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go
new file mode 100644
index 0000000..ff290ba
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go
@@ -0,0 +1,408 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_netbsd.go
+
+// +build amd64,netbsd
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int32
+ Pad_cgo_0 [4]byte
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+type Stat_t struct {
+ Dev uint64
+ Mode uint32
+ Pad_cgo_0 [4]byte
+ Ino uint64
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Pad_cgo_1 [4]byte
+ Rdev uint64
+ Atimespec Timespec
+ Mtimespec Timespec
+ Ctimespec Timespec
+ Birthtimespec Timespec
+ Size int64
+ Blocks int64
+ Blksize uint32
+ Flags uint32
+ Gen uint32
+ Spare [2]uint32
+ Pad_cgo_2 [4]byte
+}
+
+type Statfs_t [0]byte
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Dirent struct {
+ Fileno uint64
+ Reclen uint16
+ Namlen uint16
+ Type uint8
+ Name [512]int8
+ Pad_cgo_0 [3]byte
+}
+
+type Fsid struct {
+ X__fsid_val [2]int32
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]int8
+}
+
+type _Socklen uint32
+
+type Linger struct {
+ Onoff int32
+ Linger int32
+}
+
+type Iovec struct {
+ Base *byte
+ Len uint64
+}
+
+type IPMreq struct {
+ Multiaddr [4]byte /* in_addr */
+ Interface [4]byte /* in_addr */
+}
+
+type IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen int32
+ Pad_cgo_1 [4]byte
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x14
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x30
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint64
+ Filter uint32
+ Flags uint32
+ Fflags uint32
+ Pad_cgo_0 [4]byte
+ Data int64
+ Udata int64
+}
+
+type FdSet struct {
+ Bits [8]uint32
+}
+
+const (
+ SizeofIfMsghdr = 0x98
+ SizeofIfData = 0x88
+ SizeofIfaMsghdr = 0x18
+ SizeofIfAnnounceMsghdr = 0x18
+ SizeofRtMsghdr = 0x78
+ SizeofRtMetrics = 0x50
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Pad_cgo_0 [1]byte
+ Link_state int32
+ Mtu uint64
+ Metric uint64
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Noproto uint64
+ Lastchange Timespec
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Metric int32
+ Index uint16
+ Pad_cgo_0 [6]byte
+}
+
+type IfAnnounceMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Name [16]int8
+ What uint16
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Use int32
+ Inits int32
+ Pad_cgo_1 [4]byte
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint64
+ Mtu uint64
+ Hopcount uint64
+ Recvpipe uint64
+ Sendpipe uint64
+ Ssthresh uint64
+ Rtt uint64
+ Rttvar uint64
+ Expire int64
+ Pksent int64
+}
+
+type Mclpool [0]byte
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x80
+ SizeofBpfProgram = 0x10
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x20
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint64
+ Drop uint64
+ Capt uint64
+ Padding [13]uint64
+}
+
+type BpfProgram struct {
+ Len uint32
+ Pad_cgo_0 [4]byte
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp BpfTimeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [6]byte
+}
+
+type BpfTimeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed int32
+ Ospeed int32
+}
+
+const (
+ AT_FDCWD = -0x64
+ AT_SYMLINK_NOFOLLOW = 0x200
+)
+
+type Sysctlnode struct {
+ Flags uint32
+ Num int32
+ Name [32]int8
+ Ver uint32
+ X__rsvd uint32
+ Un [16]byte
+ X_sysctl_size [8]byte
+ X_sysctl_func [8]byte
+ X_sysctl_parent [8]byte
+ X_sysctl_desc [8]byte
+}
diff --git a/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go b/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go
new file mode 100644
index 0000000..66dbd7c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go
@@ -0,0 +1,406 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_netbsd.go
+
+// +build arm,netbsd
+
+package unix
+
+const (
+ sizeofPtr = 0x4
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x4
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int32
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int32
+ Pad_cgo_0 [4]byte
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int32
+ Pad_cgo_0 [4]byte
+}
+
+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 uint64
+ Mode uint32
+ Pad_cgo_0 [4]byte
+ Ino uint64
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Pad_cgo_1 [4]byte
+ Rdev uint64
+ Atimespec Timespec
+ Mtimespec Timespec
+ Ctimespec Timespec
+ Birthtimespec Timespec
+ Size int64
+ Blocks int64
+ Blksize uint32
+ Flags uint32
+ Gen uint32
+ Spare [2]uint32
+ Pad_cgo_2 [4]byte
+}
+
+type Statfs_t [0]byte
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Dirent struct {
+ Fileno uint64
+ Reclen uint16
+ Namlen uint16
+ Type uint8
+ Name [512]int8
+ Pad_cgo_0 [3]byte
+}
+
+type Fsid struct {
+ X__fsid_val [2]int32
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [12]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]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 IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Iov *Iovec
+ Iovlen int32
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x14
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x1c
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint32
+ Filter uint32
+ Flags uint32
+ Fflags uint32
+ Data int64
+ Udata int32
+ Pad_cgo_0 [4]byte
+}
+
+type FdSet struct {
+ Bits [8]uint32
+}
+
+const (
+ SizeofIfMsghdr = 0x98
+ SizeofIfData = 0x88
+ SizeofIfaMsghdr = 0x18
+ SizeofIfAnnounceMsghdr = 0x18
+ SizeofRtMsghdr = 0x78
+ SizeofRtMetrics = 0x50
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Pad_cgo_0 [1]byte
+ Link_state int32
+ Mtu uint64
+ Metric uint64
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Noproto uint64
+ Lastchange Timespec
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Metric int32
+ Index uint16
+ Pad_cgo_0 [6]byte
+}
+
+type IfAnnounceMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Name [16]int8
+ What uint16
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Use int32
+ Inits int32
+ Pad_cgo_1 [4]byte
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint64
+ Mtu uint64
+ Hopcount uint64
+ Recvpipe uint64
+ Sendpipe uint64
+ Ssthresh uint64
+ Rtt uint64
+ Rttvar uint64
+ Expire int64
+ Pksent int64
+}
+
+type Mclpool [0]byte
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x80
+ SizeofBpfProgram = 0x8
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint64
+ Drop uint64
+ Capt uint64
+ Padding [13]uint64
+}
+
+type BpfProgram struct {
+ Len uint32
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp BpfTimeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+type BpfTimeval struct {
+ Sec int32
+ Usec int32
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed int32
+ Ospeed int32
+}
+
+const (
+ AT_FDCWD = -0x64
+ AT_SYMLINK_NOFOLLOW = 0x200
+)
+
+type Sysctlnode struct {
+ Flags uint32
+ Num int32
+ Name [32]int8
+ Ver uint32
+ X__rsvd uint32
+ Un [16]byte
+ X_sysctl_size [8]byte
+ X_sysctl_func [8]byte
+ X_sysctl_parent [8]byte
+ X_sysctl_desc [8]byte
+}
diff --git a/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go b/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go
new file mode 100644
index 0000000..20fc9f4
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go
@@ -0,0 +1,446 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_openbsd.go
+
+// +build 386,openbsd
+
+package unix
+
+const (
+ sizeofPtr = 0x4
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x4
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int32
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int32
+}
+
+type Timeval struct {
+ Sec int64
+ Usec 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
+
+const (
+ S_IFMT = 0xf000
+ S_IFIFO = 0x1000
+ S_IFCHR = 0x2000
+ S_IFDIR = 0x4000
+ S_IFBLK = 0x6000
+ S_IFREG = 0x8000
+ S_IFLNK = 0xa000
+ S_IFSOCK = 0xc000
+ S_ISUID = 0x800
+ S_ISGID = 0x400
+ S_ISVTX = 0x200
+ S_IRUSR = 0x100
+ S_IWUSR = 0x80
+ S_IXUSR = 0x40
+)
+
+type Stat_t struct {
+ Mode uint32
+ Dev int32
+ Ino uint64
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev int32
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ Size int64
+ Blocks int64
+ Blksize uint32
+ Flags uint32
+ Gen uint32
+ X__st_birthtim Timespec
+}
+
+type Statfs_t struct {
+ F_flags uint32
+ F_bsize uint32
+ F_iosize uint32
+ F_blocks uint64
+ F_bfree uint64
+ F_bavail int64
+ F_files uint64
+ F_ffree uint64
+ F_favail int64
+ F_syncwrites uint64
+ F_syncreads uint64
+ F_asyncwrites uint64
+ F_asyncreads uint64
+ F_fsid Fsid
+ F_namemax uint32
+ F_owner uint32
+ F_ctime uint64
+ F_fstypename [16]int8
+ F_mntonname [90]int8
+ F_mntfromname [90]int8
+ F_mntfromspec [90]int8
+ Pad_cgo_0 [2]byte
+ Mount_info [160]byte
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Dirent struct {
+ Fileno uint64
+ Off int64
+ Reclen uint16
+ Type uint8
+ Namlen uint8
+ X__d_padding [4]uint8
+ Name [256]int8
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [24]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]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 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 Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x20
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x1c
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint32
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int64
+ Udata *byte
+}
+
+type FdSet struct {
+ Bits [32]uint32
+}
+
+const (
+ SizeofIfMsghdr = 0xec
+ SizeofIfData = 0xd4
+ SizeofIfaMsghdr = 0x18
+ SizeofIfAnnounceMsghdr = 0x1a
+ SizeofRtMsghdr = 0x60
+ SizeofRtMetrics = 0x38
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ Tableid uint16
+ Pad1 uint8
+ Pad2 uint8
+ Addrs int32
+ Flags int32
+ Xflags int32
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Link_state uint8
+ Mtu uint32
+ Metric uint32
+ Pad uint32
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Noproto uint64
+ Capabilities uint32
+ Lastchange Timeval
+ Mclpool [7]Mclpool
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ Tableid uint16
+ Pad1 uint8
+ Pad2 uint8
+ Addrs int32
+ Flags int32
+ Metric int32
+}
+
+type IfAnnounceMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ What uint16
+ Name [16]int8
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ Tableid uint16
+ Priority uint8
+ Mpls uint8
+ Addrs int32
+ Flags int32
+ Fmask int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Inits uint32
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Pksent uint64
+ Expire int64
+ Locks uint32
+ Mtu uint32
+ Refcnt uint32
+ Hopcount uint32
+ Recvpipe uint32
+ Sendpipe uint32
+ Ssthresh uint32
+ Rtt uint32
+ Rttvar uint32
+ Pad uint32
+}
+
+type Mclpool struct {
+ Grown int32
+ Alive uint16
+ Hwm uint16
+ Cwm uint16
+ Lwm uint16
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfProgram = 0x8
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfProgram struct {
+ Len uint32
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp BpfTimeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+type BpfTimeval struct {
+ Sec uint32
+ Usec uint32
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed int32
+ Ospeed int32
+}
+
+const (
+ AT_FDCWD = -0x64
+ AT_SYMLINK_NOFOLLOW = 0x2
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go
new file mode 100644
index 0000000..46fe949
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go
@@ -0,0 +1,453 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_openbsd.go
+
+// +build amd64,openbsd
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+const (
+ S_IFMT = 0xf000
+ S_IFIFO = 0x1000
+ S_IFCHR = 0x2000
+ S_IFDIR = 0x4000
+ S_IFBLK = 0x6000
+ S_IFREG = 0x8000
+ S_IFLNK = 0xa000
+ S_IFSOCK = 0xc000
+ S_ISUID = 0x800
+ S_ISGID = 0x400
+ S_ISVTX = 0x200
+ S_IRUSR = 0x100
+ S_IWUSR = 0x80
+ S_IXUSR = 0x40
+)
+
+type Stat_t struct {
+ Mode uint32
+ Dev int32
+ Ino uint64
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev int32
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ Size int64
+ Blocks int64
+ Blksize uint32
+ Flags uint32
+ Gen uint32
+ Pad_cgo_0 [4]byte
+ X__st_birthtim Timespec
+}
+
+type Statfs_t struct {
+ F_flags uint32
+ F_bsize uint32
+ F_iosize uint32
+ Pad_cgo_0 [4]byte
+ F_blocks uint64
+ F_bfree uint64
+ F_bavail int64
+ F_files uint64
+ F_ffree uint64
+ F_favail int64
+ F_syncwrites uint64
+ F_syncreads uint64
+ F_asyncwrites uint64
+ F_asyncreads uint64
+ F_fsid Fsid
+ F_namemax uint32
+ F_owner uint32
+ F_ctime uint64
+ F_fstypename [16]int8
+ F_mntonname [90]int8
+ F_mntfromname [90]int8
+ F_mntfromspec [90]int8
+ Pad_cgo_1 [2]byte
+ Mount_info [160]byte
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Dirent struct {
+ Fileno uint64
+ Off int64
+ Reclen uint16
+ Type uint8
+ Namlen uint8
+ X__d_padding [4]uint8
+ Name [256]int8
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [24]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]int8
+}
+
+type _Socklen uint32
+
+type Linger struct {
+ Onoff int32
+ Linger int32
+}
+
+type Iovec struct {
+ Base *byte
+ Len uint64
+}
+
+type IPMreq struct {
+ Multiaddr [4]byte /* in_addr */
+ Interface [4]byte /* in_addr */
+}
+
+type IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen uint32
+ Pad_cgo_1 [4]byte
+ Control *byte
+ Controllen uint32
+ Flags int32
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x20
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x30
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint64
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int64
+ Udata *byte
+}
+
+type FdSet struct {
+ Bits [32]uint32
+}
+
+const (
+ SizeofIfMsghdr = 0xf8
+ SizeofIfData = 0xe0
+ SizeofIfaMsghdr = 0x18
+ SizeofIfAnnounceMsghdr = 0x1a
+ SizeofRtMsghdr = 0x60
+ SizeofRtMetrics = 0x38
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ Tableid uint16
+ Pad1 uint8
+ Pad2 uint8
+ Addrs int32
+ Flags int32
+ Xflags int32
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Link_state uint8
+ Mtu uint32
+ Metric uint32
+ Pad uint32
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Noproto uint64
+ Capabilities uint32
+ Pad_cgo_0 [4]byte
+ Lastchange Timeval
+ Mclpool [7]Mclpool
+ Pad_cgo_1 [4]byte
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ Tableid uint16
+ Pad1 uint8
+ Pad2 uint8
+ Addrs int32
+ Flags int32
+ Metric int32
+}
+
+type IfAnnounceMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ What uint16
+ Name [16]int8
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ Tableid uint16
+ Priority uint8
+ Mpls uint8
+ Addrs int32
+ Flags int32
+ Fmask int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Inits uint32
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Pksent uint64
+ Expire int64
+ Locks uint32
+ Mtu uint32
+ Refcnt uint32
+ Hopcount uint32
+ Recvpipe uint32
+ Sendpipe uint32
+ Ssthresh uint32
+ Rtt uint32
+ Rttvar uint32
+ Pad uint32
+}
+
+type Mclpool struct {
+ Grown int32
+ Alive uint16
+ Hwm uint16
+ Cwm uint16
+ Lwm uint16
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfProgram = 0x10
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfProgram struct {
+ Len uint32
+ Pad_cgo_0 [4]byte
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp BpfTimeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+type BpfTimeval struct {
+ Sec uint32
+ Usec uint32
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed int32
+ Ospeed int32
+}
+
+const (
+ AT_FDCWD = -0x64
+ AT_SYMLINK_NOFOLLOW = 0x2
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go b/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go
new file mode 100644
index 0000000..62e1f7c
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go
@@ -0,0 +1,439 @@
+// Created by cgo -godefs - DO NOT EDIT
+// cgo -godefs types_openbsd.go
+
+// +build arm,openbsd
+
+package unix
+
+const (
+ sizeofPtr = 0x4
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x4
+ sizeofLongLong = 0x8
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int32
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int32
+}
+
+type Timeval struct {
+ Sec int64
+ Usec 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
+
+const (
+ S_IFMT = 0xf000
+ S_IFIFO = 0x1000
+ S_IFCHR = 0x2000
+ S_IFDIR = 0x4000
+ S_IFBLK = 0x6000
+ S_IFREG = 0x8000
+ S_IFLNK = 0xa000
+ S_IFSOCK = 0xc000
+ S_ISUID = 0x800
+ S_ISGID = 0x400
+ S_ISVTX = 0x200
+ S_IRUSR = 0x100
+ S_IWUSR = 0x80
+ S_IXUSR = 0x40
+)
+
+type Stat_t struct {
+ Mode uint32
+ Dev int32
+ Ino uint64
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev int32
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ Size int64
+ Blocks int64
+ Blksize int32
+ Flags uint32
+ Gen uint32
+ X__st_birthtim Timespec
+}
+
+type Statfs_t struct {
+ F_flags uint32
+ F_bsize uint32
+ F_iosize uint32
+ F_blocks uint64
+ F_bfree uint64
+ F_bavail int64
+ F_files uint64
+ F_ffree uint64
+ F_favail int64
+ F_syncwrites uint64
+ F_syncreads uint64
+ F_asyncwrites uint64
+ F_asyncreads uint64
+ F_fsid Fsid
+ F_namemax uint32
+ F_owner uint32
+ F_ctime uint64
+ F_fstypename [16]uint8
+ F_mntonname [90]uint8
+ F_mntfromname [90]uint8
+ F_mntfromspec [90]uint8
+ Pad_cgo_0 [2]byte
+ Mount_info [160]byte
+}
+
+type Flock_t struct {
+ Start int64
+ Len int64
+ Pid int32
+ Type int16
+ Whence int16
+}
+
+type Dirent struct {
+ Fileno uint64
+ Off int64
+ Reclen uint16
+ Type uint8
+ Namlen uint8
+ X__d_padding [4]uint8
+ Name [256]uint8
+}
+
+type Fsid struct {
+ Val [2]int32
+}
+
+type RawSockaddrInet4 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Len uint8
+ Family uint8
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Len uint8
+ Family uint8
+ Path [104]int8
+}
+
+type RawSockaddrDatalink struct {
+ Len uint8
+ Family uint8
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [24]int8
+}
+
+type RawSockaddr struct {
+ Len uint8
+ Family uint8
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [92]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 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 Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ Filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x1c
+ SizeofSockaddrAny = 0x6c
+ SizeofSockaddrUnix = 0x6a
+ SizeofSockaddrDatalink = 0x20
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x1c
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x20
+ SizeofICMPv6Filter = 0x20
+)
+
+const (
+ PTRACE_TRACEME = 0x0
+ PTRACE_CONT = 0x7
+ PTRACE_KILL = 0x8
+)
+
+type Kevent_t struct {
+ Ident uint32
+ Filter int16
+ Flags uint16
+ Fflags uint32
+ Data int64
+ Udata *byte
+}
+
+type FdSet struct {
+ Bits [32]uint32
+}
+
+const (
+ SizeofIfMsghdr = 0x98
+ SizeofIfData = 0x80
+ SizeofIfaMsghdr = 0x18
+ SizeofIfAnnounceMsghdr = 0x1a
+ SizeofRtMsghdr = 0x60
+ SizeofRtMetrics = 0x38
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ Tableid uint16
+ Pad1 uint8
+ Pad2 uint8
+ Addrs int32
+ Flags int32
+ Xflags int32
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Link_state uint8
+ Mtu uint32
+ Metric uint32
+ Pad uint32
+ Baudrate uint64
+ Ipackets uint64
+ Ierrors uint64
+ Opackets uint64
+ Oerrors uint64
+ Collisions uint64
+ Ibytes uint64
+ Obytes uint64
+ Imcasts uint64
+ Omcasts uint64
+ Iqdrops uint64
+ Noproto uint64
+ Capabilities uint32
+ Lastchange Timeval
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ Tableid uint16
+ Pad1 uint8
+ Pad2 uint8
+ Addrs int32
+ Flags int32
+ Metric int32
+}
+
+type IfAnnounceMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ What uint16
+ Name [16]uint8
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Hdrlen uint16
+ Index uint16
+ Tableid uint16
+ Priority uint8
+ Mpls uint8
+ Addrs int32
+ Flags int32
+ Fmask int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Inits uint32
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Pksent uint64
+ Expire int64
+ Locks uint32
+ Mtu uint32
+ Refcnt uint32
+ Hopcount uint32
+ Recvpipe uint32
+ Sendpipe uint32
+ Ssthresh uint32
+ Rtt uint32
+ Rttvar uint32
+ Pad uint32
+}
+
+type Mclpool struct{}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x8
+ SizeofBpfProgram = 0x8
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint32
+ Drop uint32
+}
+
+type BpfProgram struct {
+ Len uint32
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfHdr struct {
+ Tstamp BpfTimeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+type BpfTimeval struct {
+ Sec uint32
+ Usec uint32
+}
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [20]uint8
+ Ispeed int32
+ Ospeed int32
+}
+
+const (
+ AT_FDCWD = -0x64
+ AT_SYMLINK_NOFOLLOW = 0x2
+)
diff --git a/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go
new file mode 100644
index 0000000..92336f9
--- /dev/null
+++ b/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go
@@ -0,0 +1,442 @@
+// cgo -godefs types_solaris.go | go run mkpost.go
+// Code generated by the command above; see README.md. DO NOT EDIT.
+
+// +build amd64,solaris
+
+package unix
+
+const (
+ sizeofPtr = 0x8
+ sizeofShort = 0x2
+ sizeofInt = 0x4
+ sizeofLong = 0x8
+ sizeofLongLong = 0x8
+ PathMax = 0x400
+ MaxHostNameLen = 0x100
+)
+
+type (
+ _C_short int16
+ _C_int int32
+ _C_long int64
+ _C_long_long int64
+)
+
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+type Timeval struct {
+ Sec int64
+ Usec int64
+}
+
+type Timeval32 struct {
+ Sec int32
+ Usec int32
+}
+
+type Tms struct {
+ Utime int64
+ Stime int64
+ Cutime int64
+ Cstime int64
+}
+
+type Utimbuf struct {
+ Actime int64
+ Modtime int64
+}
+
+type Rusage struct {
+ Utime Timeval
+ Stime Timeval
+ Maxrss int64
+ Ixrss int64
+ Idrss int64
+ Isrss int64
+ Minflt int64
+ Majflt int64
+ Nswap int64
+ Inblock int64
+ Oublock int64
+ Msgsnd int64
+ Msgrcv int64
+ Nsignals int64
+ Nvcsw int64
+ Nivcsw int64
+}
+
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+type _Gid_t uint32
+
+const (
+ S_IFMT = 0xf000
+ S_IFIFO = 0x1000
+ S_IFCHR = 0x2000
+ S_IFDIR = 0x4000
+ S_IFBLK = 0x6000
+ S_IFREG = 0x8000
+ S_IFLNK = 0xa000
+ S_IFSOCK = 0xc000
+ S_ISUID = 0x800
+ S_ISGID = 0x400
+ S_ISVTX = 0x200
+ S_IRUSR = 0x100
+ S_IWUSR = 0x80
+ S_IXUSR = 0x40
+)
+
+type Stat_t struct {
+ Dev uint64
+ Ino uint64
+ Mode uint32
+ Nlink uint32
+ Uid uint32
+ Gid uint32
+ Rdev uint64
+ Size int64
+ Atim Timespec
+ Mtim Timespec
+ Ctim Timespec
+ Blksize int32
+ Pad_cgo_0 [4]byte
+ Blocks int64
+ Fstype [16]int8
+}
+
+type Flock_t struct {
+ Type int16
+ Whence int16
+ Pad_cgo_0 [4]byte
+ Start int64
+ Len int64
+ Sysid int32
+ Pid int32
+ Pad [4]int64
+}
+
+type Dirent struct {
+ Ino uint64
+ Off int64
+ Reclen uint16
+ Name [1]int8
+ Pad_cgo_0 [5]byte
+}
+
+type _Fsblkcnt_t uint64
+
+type Statvfs_t struct {
+ Bsize uint64
+ Frsize uint64
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Favail uint64
+ Fsid uint64
+ Basetype [16]int8
+ Flag uint64
+ Namemax uint64
+ Fstr [32]int8
+}
+
+type RawSockaddrInet4 struct {
+ Family uint16
+ Port uint16
+ Addr [4]byte /* in_addr */
+ Zero [8]int8
+}
+
+type RawSockaddrInet6 struct {
+ Family uint16
+ Port uint16
+ Flowinfo uint32
+ Addr [16]byte /* in6_addr */
+ Scope_id uint32
+ X__sin6_src_id uint32
+}
+
+type RawSockaddrUnix struct {
+ Family uint16
+ Path [108]int8
+}
+
+type RawSockaddrDatalink struct {
+ Family uint16
+ Index uint16
+ Type uint8
+ Nlen uint8
+ Alen uint8
+ Slen uint8
+ Data [244]int8
+}
+
+type RawSockaddr struct {
+ Family uint16
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [236]int8
+}
+
+type _Socklen uint32
+
+type Linger struct {
+ Onoff int32
+ Linger int32
+}
+
+type Iovec struct {
+ Base *int8
+ Len uint64
+}
+
+type IPMreq struct {
+ Multiaddr [4]byte /* in_addr */
+ Interface [4]byte /* in_addr */
+}
+
+type IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+type Msghdr struct {
+ Name *byte
+ Namelen uint32
+ Pad_cgo_0 [4]byte
+ Iov *Iovec
+ Iovlen int32
+ Pad_cgo_1 [4]byte
+ Accrights *int8
+ Accrightslen int32
+ Pad_cgo_2 [4]byte
+}
+
+type Cmsghdr struct {
+ Len uint32
+ Level int32
+ Type int32
+}
+
+type Inet6Pktinfo struct {
+ Addr [16]byte /* in6_addr */
+ Ifindex uint32
+}
+
+type IPv6MTUInfo struct {
+ Addr RawSockaddrInet6
+ Mtu uint32
+}
+
+type ICMPv6Filter struct {
+ X__icmp6_filt [8]uint32
+}
+
+const (
+ SizeofSockaddrInet4 = 0x10
+ SizeofSockaddrInet6 = 0x20
+ SizeofSockaddrAny = 0xfc
+ SizeofSockaddrUnix = 0x6e
+ SizeofSockaddrDatalink = 0xfc
+ SizeofLinger = 0x8
+ SizeofIPMreq = 0x8
+ SizeofIPv6Mreq = 0x14
+ SizeofMsghdr = 0x30
+ SizeofCmsghdr = 0xc
+ SizeofInet6Pktinfo = 0x14
+ SizeofIPv6MTUInfo = 0x24
+ SizeofICMPv6Filter = 0x20
+)
+
+type FdSet struct {
+ Bits [1024]int64
+}
+
+type Utsname struct {
+ Sysname [257]int8
+ Nodename [257]int8
+ Release [257]int8
+ Version [257]int8
+ Machine [257]int8
+}
+
+type Ustat_t struct {
+ Tfree int64
+ Tinode uint64
+ Fname [6]int8
+ Fpack [6]int8
+ Pad_cgo_0 [4]byte
+}
+
+const (
+ AT_FDCWD = 0xffd19553
+ AT_SYMLINK_NOFOLLOW = 0x1000
+ AT_SYMLINK_FOLLOW = 0x2000
+ AT_REMOVEDIR = 0x1
+ AT_EACCESS = 0x4
+)
+
+const (
+ SizeofIfMsghdr = 0x54
+ SizeofIfData = 0x44
+ SizeofIfaMsghdr = 0x14
+ SizeofRtMsghdr = 0x4c
+ SizeofRtMetrics = 0x28
+)
+
+type IfMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Data IfData
+}
+
+type IfData struct {
+ Type uint8
+ Addrlen uint8
+ Hdrlen uint8
+ Pad_cgo_0 [1]byte
+ Mtu uint32
+ Metric uint32
+ Baudrate uint32
+ Ipackets uint32
+ Ierrors uint32
+ Opackets uint32
+ Oerrors uint32
+ Collisions uint32
+ Ibytes uint32
+ Obytes uint32
+ Imcasts uint32
+ Omcasts uint32
+ Iqdrops uint32
+ Noproto uint32
+ Lastchange Timeval32
+}
+
+type IfaMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Addrs int32
+ Flags int32
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Metric int32
+}
+
+type RtMsghdr struct {
+ Msglen uint16
+ Version uint8
+ Type uint8
+ Index uint16
+ Pad_cgo_0 [2]byte
+ Flags int32
+ Addrs int32
+ Pid int32
+ Seq int32
+ Errno int32
+ Use int32
+ Inits uint32
+ Rmx RtMetrics
+}
+
+type RtMetrics struct {
+ Locks uint32
+ Mtu uint32
+ Hopcount uint32
+ Expire uint32
+ Recvpipe uint32
+ Sendpipe uint32
+ Ssthresh uint32
+ Rtt uint32
+ Rttvar uint32
+ Pksent uint32
+}
+
+const (
+ SizeofBpfVersion = 0x4
+ SizeofBpfStat = 0x80
+ SizeofBpfProgram = 0x10
+ SizeofBpfInsn = 0x8
+ SizeofBpfHdr = 0x14
+)
+
+type BpfVersion struct {
+ Major uint16
+ Minor uint16
+}
+
+type BpfStat struct {
+ Recv uint64
+ Drop uint64
+ Capt uint64
+ Padding [13]uint64
+}
+
+type BpfProgram struct {
+ Len uint32
+ Pad_cgo_0 [4]byte
+ Insns *BpfInsn
+}
+
+type BpfInsn struct {
+ Code uint16
+ Jt uint8
+ Jf uint8
+ K uint32
+}
+
+type BpfTimeval struct {
+ Sec int32
+ Usec int32
+}
+
+type BpfHdr struct {
+ Tstamp BpfTimeval
+ Caplen uint32
+ Datalen uint32
+ Hdrlen uint16
+ Pad_cgo_0 [2]byte
+}
+
+const _SC_PAGESIZE = 0xb
+
+type Termios struct {
+ Iflag uint32
+ Oflag uint32
+ Cflag uint32
+ Lflag uint32
+ Cc [19]uint8
+ Pad_cgo_0 [1]byte
+}
+
+type Termio struct {
+ Iflag uint16
+ Oflag uint16
+ Cflag uint16
+ Lflag uint16
+ Line int8
+ Cc [8]uint8
+ Pad_cgo_0 [1]byte
+}
+
+type Winsize struct {
+ Row uint16
+ Col uint16
+ Xpixel uint16
+ Ypixel uint16
+}
diff --git a/vendor/golang.org/x/sys/windows/asm_windows_386.s b/vendor/golang.org/x/sys/windows/asm_windows_386.s
new file mode 100644
index 0000000..1c20dd2
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/asm_windows_386.s
@@ -0,0 +1,13 @@
+// Copyright 2009 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.
+
+//
+// System calls for 386, Windows are implemented in runtime/syscall_windows.goc
+//
+
+TEXT ·getprocaddress(SB), 7, $0-8
+ JMP syscall·getprocaddress(SB)
+
+TEXT ·loadlibrary(SB), 7, $0-4
+ JMP syscall·loadlibrary(SB)
diff --git a/vendor/golang.org/x/sys/windows/asm_windows_amd64.s b/vendor/golang.org/x/sys/windows/asm_windows_amd64.s
new file mode 100644
index 0000000..4d025ab
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/asm_windows_amd64.s
@@ -0,0 +1,13 @@
+// Copyright 2009 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.
+
+//
+// System calls for amd64, Windows are implemented in runtime/syscall_windows.goc
+//
+
+TEXT ·getprocaddress(SB), 7, $0-32
+ JMP syscall·getprocaddress(SB)
+
+TEXT ·loadlibrary(SB), 7, $0-8
+ JMP syscall·loadlibrary(SB)
diff --git a/vendor/golang.org/x/sys/windows/dll_windows.go b/vendor/golang.org/x/sys/windows/dll_windows.go
new file mode 100644
index 0000000..e77a370
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/dll_windows.go
@@ -0,0 +1,377 @@
+// 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 windows
+
+import (
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "unsafe"
+)
+
+// DLLError describes reasons for DLL load failures.
+type DLLError struct {
+ Err error
+ ObjName string
+ Msg string
+}
+
+func (e *DLLError) Error() string { return e.Msg }
+
+// Implemented in runtime/syscall_windows.goc; we provide jumps to them in our assembly file.
+func loadlibrary(filename *uint16) (handle uintptr, err syscall.Errno)
+func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err syscall.Errno)
+
+// A DLL implements access to a single DLL.
+type DLL struct {
+ Name string
+ Handle Handle
+}
+
+// LoadDLL loads DLL file into memory.
+//
+// Warning: using LoadDLL without an absolute path name is subject to
+// DLL preloading attacks. To safely load a system DLL, use LazyDLL
+// with System set to true, or use LoadLibraryEx directly.
+func LoadDLL(name string) (dll *DLL, err error) {
+ namep, err := UTF16PtrFromString(name)
+ if err != nil {
+ return nil, err
+ }
+ h, e := loadlibrary(namep)
+ if e != 0 {
+ return nil, &DLLError{
+ Err: e,
+ ObjName: name,
+ Msg: "Failed to load " + name + ": " + e.Error(),
+ }
+ }
+ d := &DLL{
+ Name: name,
+ Handle: Handle(h),
+ }
+ return d, nil
+}
+
+// MustLoadDLL is like LoadDLL but panics if load operation failes.
+func MustLoadDLL(name string) *DLL {
+ d, e := LoadDLL(name)
+ if e != nil {
+ panic(e)
+ }
+ return d
+}
+
+// FindProc searches DLL d for procedure named name and returns *Proc
+// if found. It returns an error if search fails.
+func (d *DLL) FindProc(name string) (proc *Proc, err error) {
+ namep, err := BytePtrFromString(name)
+ if err != nil {
+ return nil, err
+ }
+ a, e := getprocaddress(uintptr(d.Handle), namep)
+ if e != 0 {
+ return nil, &DLLError{
+ Err: e,
+ ObjName: name,
+ Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(),
+ }
+ }
+ p := &Proc{
+ Dll: d,
+ Name: name,
+ addr: a,
+ }
+ return p, nil
+}
+
+// MustFindProc is like FindProc but panics if search fails.
+func (d *DLL) MustFindProc(name string) *Proc {
+ p, e := d.FindProc(name)
+ if e != nil {
+ panic(e)
+ }
+ return p
+}
+
+// Release unloads DLL d from memory.
+func (d *DLL) Release() (err error) {
+ return FreeLibrary(d.Handle)
+}
+
+// A Proc implements access to a procedure inside a DLL.
+type Proc struct {
+ Dll *DLL
+ Name string
+ addr uintptr
+}
+
+// Addr returns the address of the procedure represented by p.
+// The return value can be passed to Syscall to run the procedure.
+func (p *Proc) Addr() uintptr {
+ return p.addr
+}
+
+//go:uintptrescapes
+
+// Call executes procedure p with arguments a. It will panic, if more then 15 arguments
+// are supplied.
+//
+// The returned error is always non-nil, constructed from the result of GetLastError.
+// Callers must inspect the primary return value to decide whether an error occurred
+// (according to the semantics of the specific function being called) before consulting
+// the error. The error will be guaranteed to contain windows.Errno.
+func (p *Proc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) {
+ switch len(a) {
+ case 0:
+ return syscall.Syscall(p.Addr(), uintptr(len(a)), 0, 0, 0)
+ case 1:
+ return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], 0, 0)
+ case 2:
+ return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], 0)
+ case 3:
+ return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], a[2])
+ case 4:
+ return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], 0, 0)
+ case 5:
+ return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], 0)
+ case 6:
+ return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5])
+ case 7:
+ return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], 0, 0)
+ case 8:
+ return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], 0)
+ case 9:
+ return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8])
+ case 10:
+ return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], 0, 0)
+ case 11:
+ return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], 0)
+ case 12:
+ return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11])
+ case 13:
+ return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], 0, 0)
+ case 14:
+ return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], 0)
+ case 15:
+ return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14])
+ default:
+ panic("Call " + p.Name + " with too many arguments " + itoa(len(a)) + ".")
+ }
+}
+
+// A LazyDLL implements access to a single DLL.
+// It will delay the load of the DLL until the first
+// call to its Handle method or to one of its
+// LazyProc's Addr method.
+type LazyDLL struct {
+ Name string
+
+ // System determines whether the DLL must be loaded from the
+ // Windows System directory, bypassing the normal DLL search
+ // path.
+ System bool
+
+ mu sync.Mutex
+ dll *DLL // non nil once DLL is loaded
+}
+
+// Load loads DLL file d.Name into memory. It returns an error if fails.
+// Load will not try to load DLL, if it is already loaded into memory.
+func (d *LazyDLL) Load() error {
+ // Non-racy version of:
+ // if d.dll != nil {
+ if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll))) != nil {
+ return nil
+ }
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if d.dll != nil {
+ return nil
+ }
+
+ // kernel32.dll is special, since it's where LoadLibraryEx comes from.
+ // The kernel already special-cases its name, so it's always
+ // loaded from system32.
+ var dll *DLL
+ var err error
+ if d.Name == "kernel32.dll" {
+ dll, err = LoadDLL(d.Name)
+ } else {
+ dll, err = loadLibraryEx(d.Name, d.System)
+ }
+ if err != nil {
+ return err
+ }
+
+ // Non-racy version of:
+ // d.dll = dll
+ atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll)), unsafe.Pointer(dll))
+ return nil
+}
+
+// mustLoad is like Load but panics if search fails.
+func (d *LazyDLL) mustLoad() {
+ e := d.Load()
+ if e != nil {
+ panic(e)
+ }
+}
+
+// Handle returns d's module handle.
+func (d *LazyDLL) Handle() uintptr {
+ d.mustLoad()
+ return uintptr(d.dll.Handle)
+}
+
+// NewProc returns a LazyProc for accessing the named procedure in the DLL d.
+func (d *LazyDLL) NewProc(name string) *LazyProc {
+ return &LazyProc{l: d, Name: name}
+}
+
+// NewLazyDLL creates new LazyDLL associated with DLL file.
+func NewLazyDLL(name string) *LazyDLL {
+ return &LazyDLL{Name: name}
+}
+
+// NewLazySystemDLL is like NewLazyDLL, but will only
+// search Windows System directory for the DLL if name is
+// a base name (like "advapi32.dll").
+func NewLazySystemDLL(name string) *LazyDLL {
+ return &LazyDLL{Name: name, System: true}
+}
+
+// A LazyProc implements access to a procedure inside a LazyDLL.
+// It delays the lookup until the Addr method is called.
+type LazyProc struct {
+ Name string
+
+ mu sync.Mutex
+ l *LazyDLL
+ proc *Proc
+}
+
+// Find searches DLL for procedure named p.Name. It returns
+// an error if search fails. Find will not search procedure,
+// if it is already found and loaded into memory.
+func (p *LazyProc) Find() error {
+ // Non-racy version of:
+ // if p.proc == nil {
+ if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc))) == nil {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.proc == nil {
+ e := p.l.Load()
+ if e != nil {
+ return e
+ }
+ proc, e := p.l.dll.FindProc(p.Name)
+ if e != nil {
+ return e
+ }
+ // Non-racy version of:
+ // p.proc = proc
+ atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc)), unsafe.Pointer(proc))
+ }
+ }
+ return nil
+}
+
+// mustFind is like Find but panics if search fails.
+func (p *LazyProc) mustFind() {
+ e := p.Find()
+ if e != nil {
+ panic(e)
+ }
+}
+
+// Addr returns the address of the procedure represented by p.
+// The return value can be passed to Syscall to run the procedure.
+func (p *LazyProc) Addr() uintptr {
+ p.mustFind()
+ return p.proc.Addr()
+}
+
+//go:uintptrescapes
+
+// Call executes procedure p with arguments a. It will panic, if more then 15 arguments
+// are supplied.
+//
+// The returned error is always non-nil, constructed from the result of GetLastError.
+// Callers must inspect the primary return value to decide whether an error occurred
+// (according to the semantics of the specific function being called) before consulting
+// the error. The error will be guaranteed to contain windows.Errno.
+func (p *LazyProc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) {
+ p.mustFind()
+ return p.proc.Call(a...)
+}
+
+var canDoSearchSystem32Once struct {
+ sync.Once
+ v bool
+}
+
+func initCanDoSearchSystem32() {
+ // https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
+ // "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
+ // Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
+ // systems that have KB2533623 installed. To determine whether the
+ // flags are available, use GetProcAddress to get the address of the
+ // AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
+ // function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
+ // flags can be used with LoadLibraryEx."
+ canDoSearchSystem32Once.v = (modkernel32.NewProc("AddDllDirectory").Find() == nil)
+}
+
+func canDoSearchSystem32() bool {
+ canDoSearchSystem32Once.Do(initCanDoSearchSystem32)
+ return canDoSearchSystem32Once.v
+}
+
+func isBaseName(name string) bool {
+ for _, c := range name {
+ if c == ':' || c == '/' || c == '\\' {
+ return false
+ }
+ }
+ return true
+}
+
+// loadLibraryEx wraps the Windows LoadLibraryEx function.
+//
+// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx
+//
+// If name is not an absolute path, LoadLibraryEx searches for the DLL
+// in a variety of automatic locations unless constrained by flags.
+// See: https://msdn.microsoft.com/en-us/library/ff919712%28VS.85%29.aspx
+func loadLibraryEx(name string, system bool) (*DLL, error) {
+ loadDLL := name
+ var flags uintptr
+ if system {
+ if canDoSearchSystem32() {
+ const LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
+ flags = LOAD_LIBRARY_SEARCH_SYSTEM32
+ } else if isBaseName(name) {
+ // WindowsXP or unpatched Windows machine
+ // trying to load "foo.dll" out of the system
+ // folder, but LoadLibraryEx doesn't support
+ // that yet on their system, so emulate it.
+ windir, _ := Getenv("WINDIR") // old var; apparently works on XP
+ if windir == "" {
+ return nil, errString("%WINDIR% not defined")
+ }
+ loadDLL = windir + "\\System32\\" + name
+ }
+ }
+ h, err := LoadLibraryEx(loadDLL, 0, flags)
+ if err != nil {
+ return nil, err
+ }
+ return &DLL{Name: name, Handle: h}, nil
+}
+
+type errString string
+
+func (s errString) Error() string { return string(s) }
diff --git a/vendor/golang.org/x/sys/windows/env_unset.go b/vendor/golang.org/x/sys/windows/env_unset.go
new file mode 100644
index 0000000..4ed03ae
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/env_unset.go
@@ -0,0 +1,15 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build windows
+// +build go1.4
+
+package windows
+
+import "syscall"
+
+func Unsetenv(key string) error {
+ // This was added in Go 1.4.
+ return syscall.Unsetenv(key)
+}
diff --git a/vendor/golang.org/x/sys/windows/env_windows.go b/vendor/golang.org/x/sys/windows/env_windows.go
new file mode 100644
index 0000000..a9d8ef4
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/env_windows.go
@@ -0,0 +1,25 @@
+// 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.
+
+// Windows environment variables.
+
+package windows
+
+import "syscall"
+
+func Getenv(key string) (value string, found bool) {
+ return syscall.Getenv(key)
+}
+
+func Setenv(key, value string) error {
+ return syscall.Setenv(key, value)
+}
+
+func Clearenv() {
+ syscall.Clearenv()
+}
+
+func Environ() []string {
+ return syscall.Environ()
+}
diff --git a/vendor/golang.org/x/sys/windows/eventlog.go b/vendor/golang.org/x/sys/windows/eventlog.go
new file mode 100644
index 0000000..40af946
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/eventlog.go
@@ -0,0 +1,20 @@
+// 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 windows
+
+package windows
+
+const (
+ EVENTLOG_SUCCESS = 0
+ EVENTLOG_ERROR_TYPE = 1
+ EVENTLOG_WARNING_TYPE = 2
+ EVENTLOG_INFORMATION_TYPE = 4
+ EVENTLOG_AUDIT_SUCCESS = 8
+ EVENTLOG_AUDIT_FAILURE = 16
+)
+
+//sys RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error) [failretval==0] = advapi32.RegisterEventSourceW
+//sys DeregisterEventSource(handle Handle) (err error) = advapi32.DeregisterEventSource
+//sys ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) = advapi32.ReportEventW
diff --git a/vendor/golang.org/x/sys/windows/exec_windows.go b/vendor/golang.org/x/sys/windows/exec_windows.go
new file mode 100644
index 0000000..3606c3a
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/exec_windows.go
@@ -0,0 +1,97 @@
+// Copyright 2009 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.
+
+// Fork, exec, wait, etc.
+
+package windows
+
+// EscapeArg rewrites command line argument s as prescribed
+// in http://msdn.microsoft.com/en-us/library/ms880421.
+// This function returns "" (2 double quotes) if s is empty.
+// Alternatively, these transformations are done:
+// - every back slash (\) is doubled, but only if immediately
+// followed by double quote (");
+// - every double quote (") is escaped by back slash (\);
+// - finally, s is wrapped with double quotes (arg -> "arg"),
+// but only if there is space or tab inside s.
+func EscapeArg(s string) string {
+ if len(s) == 0 {
+ return "\"\""
+ }
+ n := len(s)
+ hasSpace := false
+ for i := 0; i < len(s); i++ {
+ switch s[i] {
+ case '"', '\\':
+ n++
+ case ' ', '\t':
+ hasSpace = true
+ }
+ }
+ if hasSpace {
+ n += 2
+ }
+ if n == len(s) {
+ return s
+ }
+
+ qs := make([]byte, n)
+ j := 0
+ if hasSpace {
+ qs[j] = '"'
+ j++
+ }
+ slashes := 0
+ for i := 0; i < len(s); i++ {
+ switch s[i] {
+ default:
+ slashes = 0
+ qs[j] = s[i]
+ case '\\':
+ slashes++
+ qs[j] = s[i]
+ case '"':
+ for ; slashes > 0; slashes-- {
+ qs[j] = '\\'
+ j++
+ }
+ qs[j] = '\\'
+ j++
+ qs[j] = s[i]
+ }
+ j++
+ }
+ if hasSpace {
+ for ; slashes > 0; slashes-- {
+ qs[j] = '\\'
+ j++
+ }
+ qs[j] = '"'
+ j++
+ }
+ return string(qs[:j])
+}
+
+func CloseOnExec(fd Handle) {
+ SetHandleInformation(Handle(fd), HANDLE_FLAG_INHERIT, 0)
+}
+
+// FullPath retrieves the full path of the specified file.
+func FullPath(name string) (path string, err error) {
+ p, err := UTF16PtrFromString(name)
+ if err != nil {
+ return "", err
+ }
+ n := uint32(100)
+ for {
+ buf := make([]uint16, n)
+ n, err = GetFullPathName(p, uint32(len(buf)), &buf[0], nil)
+ if err != nil {
+ return "", err
+ }
+ if n <= uint32(len(buf)) {
+ return UTF16ToString(buf[:n]), nil
+ }
+ }
+}
diff --git a/vendor/golang.org/x/sys/windows/memory_windows.go b/vendor/golang.org/x/sys/windows/memory_windows.go
new file mode 100644
index 0000000..f63e899
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/memory_windows.go
@@ -0,0 +1,26 @@
+// Copyright 2017 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 windows
+
+const (
+ MEM_COMMIT = 0x00001000
+ MEM_RESERVE = 0x00002000
+ MEM_DECOMMIT = 0x00004000
+ MEM_RELEASE = 0x00008000
+ MEM_RESET = 0x00080000
+ MEM_TOP_DOWN = 0x00100000
+ MEM_WRITE_WATCH = 0x00200000
+ MEM_PHYSICAL = 0x00400000
+ MEM_RESET_UNDO = 0x01000000
+ MEM_LARGE_PAGES = 0x20000000
+
+ PAGE_NOACCESS = 0x01
+ PAGE_READONLY = 0x02
+ PAGE_READWRITE = 0x04
+ PAGE_WRITECOPY = 0x08
+ PAGE_EXECUTE_READ = 0x20
+ PAGE_EXECUTE_READWRITE = 0x40
+ PAGE_EXECUTE_WRITECOPY = 0x80
+)
diff --git a/vendor/golang.org/x/sys/windows/mksyscall.go b/vendor/golang.org/x/sys/windows/mksyscall.go
new file mode 100644
index 0000000..e1c88c9
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/mksyscall.go
@@ -0,0 +1,7 @@
+// Copyright 2009 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 windows
+
+//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go eventlog.go service.go syscall_windows.go security_windows.go
diff --git a/vendor/golang.org/x/sys/windows/race.go b/vendor/golang.org/x/sys/windows/race.go
new file mode 100644
index 0000000..343e18a
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/race.go
@@ -0,0 +1,30 @@
+// 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 windows,race
+
+package windows
+
+import (
+ "runtime"
+ "unsafe"
+)
+
+const raceenabled = true
+
+func raceAcquire(addr unsafe.Pointer) {
+ runtime.RaceAcquire(addr)
+}
+
+func raceReleaseMerge(addr unsafe.Pointer) {
+ runtime.RaceReleaseMerge(addr)
+}
+
+func raceReadRange(addr unsafe.Pointer, len int) {
+ runtime.RaceReadRange(addr, len)
+}
+
+func raceWriteRange(addr unsafe.Pointer, len int) {
+ runtime.RaceWriteRange(addr, len)
+}
diff --git a/vendor/golang.org/x/sys/windows/race0.go b/vendor/golang.org/x/sys/windows/race0.go
new file mode 100644
index 0000000..17af843
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/race0.go
@@ -0,0 +1,25 @@
+// 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 windows,!race
+
+package windows
+
+import (
+ "unsafe"
+)
+
+const raceenabled = false
+
+func raceAcquire(addr unsafe.Pointer) {
+}
+
+func raceReleaseMerge(addr unsafe.Pointer) {
+}
+
+func raceReadRange(addr unsafe.Pointer, len int) {
+}
+
+func raceWriteRange(addr unsafe.Pointer, len int) {
+}
diff --git a/vendor/golang.org/x/sys/windows/registry/key.go b/vendor/golang.org/x/sys/windows/registry/key.go
new file mode 100644
index 0000000..d0beb19
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/registry/key.go
@@ -0,0 +1,200 @@
+// Copyright 2015 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 windows
+
+// Package registry provides access to the Windows registry.
+//
+// Here is a simple example, opening a registry key and reading a string value from it.
+//
+// k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
+// if err != nil {
+// log.Fatal(err)
+// }
+// defer k.Close()
+//
+// s, _, err := k.GetStringValue("SystemRoot")
+// if err != nil {
+// log.Fatal(err)
+// }
+// fmt.Printf("Windows system root is %q\n", s)
+//
+package registry
+
+import (
+ "io"
+ "syscall"
+ "time"
+)
+
+const (
+ // Registry key security and access rights.
+ // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724878.aspx
+ // for details.
+ ALL_ACCESS = 0xf003f
+ CREATE_LINK = 0x00020
+ CREATE_SUB_KEY = 0x00004
+ ENUMERATE_SUB_KEYS = 0x00008
+ EXECUTE = 0x20019
+ NOTIFY = 0x00010
+ QUERY_VALUE = 0x00001
+ READ = 0x20019
+ SET_VALUE = 0x00002
+ WOW64_32KEY = 0x00200
+ WOW64_64KEY = 0x00100
+ WRITE = 0x20006
+)
+
+// Key is a handle to an open Windows registry key.
+// Keys can be obtained by calling OpenKey; there are
+// also some predefined root keys such as CURRENT_USER.
+// Keys can be used directly in the Windows API.
+type Key syscall.Handle
+
+const (
+ // Windows defines some predefined root keys that are always open.
+ // An application can use these keys as entry points to the registry.
+ // Normally these keys are used in OpenKey to open new keys,
+ // but they can also be used anywhere a Key is required.
+ CLASSES_ROOT = Key(syscall.HKEY_CLASSES_ROOT)
+ CURRENT_USER = Key(syscall.HKEY_CURRENT_USER)
+ LOCAL_MACHINE = Key(syscall.HKEY_LOCAL_MACHINE)
+ USERS = Key(syscall.HKEY_USERS)
+ CURRENT_CONFIG = Key(syscall.HKEY_CURRENT_CONFIG)
+ PERFORMANCE_DATA = Key(syscall.HKEY_PERFORMANCE_DATA)
+)
+
+// Close closes open key k.
+func (k Key) Close() error {
+ return syscall.RegCloseKey(syscall.Handle(k))
+}
+
+// OpenKey opens a new key with path name relative to key k.
+// It accepts any open key, including CURRENT_USER and others,
+// and returns the new key and an error.
+// The access parameter specifies desired access rights to the
+// key to be opened.
+func OpenKey(k Key, path string, access uint32) (Key, error) {
+ p, err := syscall.UTF16PtrFromString(path)
+ if err != nil {
+ return 0, err
+ }
+ var subkey syscall.Handle
+ err = syscall.RegOpenKeyEx(syscall.Handle(k), p, 0, access, &subkey)
+ if err != nil {
+ return 0, err
+ }
+ return Key(subkey), nil
+}
+
+// OpenRemoteKey opens a predefined registry key on another
+// computer pcname. The key to be opened is specified by k, but
+// can only be one of LOCAL_MACHINE, PERFORMANCE_DATA or USERS.
+// If pcname is "", OpenRemoteKey returns local computer key.
+func OpenRemoteKey(pcname string, k Key) (Key, error) {
+ var err error
+ var p *uint16
+ if pcname != "" {
+ p, err = syscall.UTF16PtrFromString(`\\` + pcname)
+ if err != nil {
+ return 0, err
+ }
+ }
+ var remoteKey syscall.Handle
+ err = regConnectRegistry(p, syscall.Handle(k), &remoteKey)
+ if err != nil {
+ return 0, err
+ }
+ return Key(remoteKey), nil
+}
+
+// ReadSubKeyNames returns the names of subkeys of key k.
+// The parameter n controls the number of returned names,
+// analogous to the way os.File.Readdirnames works.
+func (k Key) ReadSubKeyNames(n int) ([]string, error) {
+ ki, err := k.Stat()
+ if err != nil {
+ return nil, err
+ }
+ names := make([]string, 0, ki.SubKeyCount)
+ buf := make([]uint16, ki.MaxSubKeyLen+1) // extra room for terminating zero byte
+loopItems:
+ for i := uint32(0); ; i++ {
+ if n > 0 {
+ if len(names) == n {
+ return names, nil
+ }
+ }
+ l := uint32(len(buf))
+ for {
+ err := syscall.RegEnumKeyEx(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil)
+ if err == nil {
+ break
+ }
+ if err == syscall.ERROR_MORE_DATA {
+ // Double buffer size and try again.
+ l = uint32(2 * len(buf))
+ buf = make([]uint16, l)
+ continue
+ }
+ if err == _ERROR_NO_MORE_ITEMS {
+ break loopItems
+ }
+ return names, err
+ }
+ names = append(names, syscall.UTF16ToString(buf[:l]))
+ }
+ if n > len(names) {
+ return names, io.EOF
+ }
+ return names, nil
+}
+
+// CreateKey creates a key named path under open key k.
+// CreateKey returns the new key and a boolean flag that reports
+// whether the key already existed.
+// The access parameter specifies the access rights for the key
+// to be created.
+func CreateKey(k Key, path string, access uint32) (newk Key, openedExisting bool, err error) {
+ var h syscall.Handle
+ var d uint32
+ err = regCreateKeyEx(syscall.Handle(k), syscall.StringToUTF16Ptr(path),
+ 0, nil, _REG_OPTION_NON_VOLATILE, access, nil, &h, &d)
+ if err != nil {
+ return 0, false, err
+ }
+ return Key(h), d == _REG_OPENED_EXISTING_KEY, nil
+}
+
+// DeleteKey deletes the subkey path of key k and its values.
+func DeleteKey(k Key, path string) error {
+ return regDeleteKey(syscall.Handle(k), syscall.StringToUTF16Ptr(path))
+}
+
+// A KeyInfo describes the statistics of a key. It is returned by Stat.
+type KeyInfo struct {
+ SubKeyCount uint32
+ MaxSubKeyLen uint32 // size of the key's subkey with the longest name, in Unicode characters, not including the terminating zero byte
+ ValueCount uint32
+ MaxValueNameLen uint32 // size of the key's longest value name, in Unicode characters, not including the terminating zero byte
+ MaxValueLen uint32 // longest data component among the key's values, in bytes
+ lastWriteTime syscall.Filetime
+}
+
+// ModTime returns the key's last write time.
+func (ki *KeyInfo) ModTime() time.Time {
+ return time.Unix(0, ki.lastWriteTime.Nanoseconds())
+}
+
+// Stat retrieves information about the open key k.
+func (k Key) Stat() (*KeyInfo, error) {
+ var ki KeyInfo
+ err := syscall.RegQueryInfoKey(syscall.Handle(k), nil, nil, nil,
+ &ki.SubKeyCount, &ki.MaxSubKeyLen, nil, &ki.ValueCount,
+ &ki.MaxValueNameLen, &ki.MaxValueLen, nil, &ki.lastWriteTime)
+ if err != nil {
+ return nil, err
+ }
+ return &ki, nil
+}
diff --git a/vendor/golang.org/x/sys/windows/registry/mksyscall.go b/vendor/golang.org/x/sys/windows/registry/mksyscall.go
new file mode 100644
index 0000000..0ac95ff
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/registry/mksyscall.go
@@ -0,0 +1,7 @@
+// Copyright 2015 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 registry
+
+//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go syscall.go
diff --git a/vendor/golang.org/x/sys/windows/registry/syscall.go b/vendor/golang.org/x/sys/windows/registry/syscall.go
new file mode 100644
index 0000000..e66643c
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/registry/syscall.go
@@ -0,0 +1,32 @@
+// Copyright 2015 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 windows
+
+package registry
+
+import "syscall"
+
+const (
+ _REG_OPTION_NON_VOLATILE = 0
+
+ _REG_CREATED_NEW_KEY = 1
+ _REG_OPENED_EXISTING_KEY = 2
+
+ _ERROR_NO_MORE_ITEMS syscall.Errno = 259
+)
+
+func LoadRegLoadMUIString() error {
+ return procRegLoadMUIStringW.Find()
+}
+
+//sys regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) = advapi32.RegCreateKeyExW
+//sys regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) = advapi32.RegDeleteKeyW
+//sys regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) = advapi32.RegSetValueExW
+//sys regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegEnumValueW
+//sys regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) = advapi32.RegDeleteValueW
+//sys regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) = advapi32.RegLoadMUIStringW
+//sys regConnectRegistry(machinename *uint16, key syscall.Handle, result *syscall.Handle) (regerrno error) = advapi32.RegConnectRegistryW
+
+//sys expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW
diff --git a/vendor/golang.org/x/sys/windows/registry/value.go b/vendor/golang.org/x/sys/windows/registry/value.go
new file mode 100644
index 0000000..71d4e15
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/registry/value.go
@@ -0,0 +1,384 @@
+// Copyright 2015 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 windows
+
+package registry
+
+import (
+ "errors"
+ "io"
+ "syscall"
+ "unicode/utf16"
+ "unsafe"
+)
+
+const (
+ // Registry value types.
+ NONE = 0
+ SZ = 1
+ EXPAND_SZ = 2
+ BINARY = 3
+ DWORD = 4
+ DWORD_BIG_ENDIAN = 5
+ LINK = 6
+ MULTI_SZ = 7
+ RESOURCE_LIST = 8
+ FULL_RESOURCE_DESCRIPTOR = 9
+ RESOURCE_REQUIREMENTS_LIST = 10
+ QWORD = 11
+)
+
+var (
+ // ErrShortBuffer is returned when the buffer was too short for the operation.
+ ErrShortBuffer = syscall.ERROR_MORE_DATA
+
+ // ErrNotExist is returned when a registry key or value does not exist.
+ ErrNotExist = syscall.ERROR_FILE_NOT_FOUND
+
+ // ErrUnexpectedType is returned by Get*Value when the value's type was unexpected.
+ ErrUnexpectedType = errors.New("unexpected key value type")
+)
+
+// GetValue retrieves the type and data for the specified value associated
+// with an open key k. It fills up buffer buf and returns the retrieved
+// byte count n. If buf is too small to fit the stored value it returns
+// ErrShortBuffer error along with the required buffer size n.
+// If no buffer is provided, it returns true and actual buffer size n.
+// If no buffer is provided, GetValue returns the value's type only.
+// If the value does not exist, the error returned is ErrNotExist.
+//
+// GetValue is a low level function. If value's type is known, use the appropriate
+// Get*Value function instead.
+func (k Key) GetValue(name string, buf []byte) (n int, valtype uint32, err error) {
+ pname, err := syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return 0, 0, err
+ }
+ var pbuf *byte
+ if len(buf) > 0 {
+ pbuf = (*byte)(unsafe.Pointer(&buf[0]))
+ }
+ l := uint32(len(buf))
+ err = syscall.RegQueryValueEx(syscall.Handle(k), pname, nil, &valtype, pbuf, &l)
+ if err != nil {
+ return int(l), valtype, err
+ }
+ return int(l), valtype, nil
+}
+
+func (k Key) getValue(name string, buf []byte) (date []byte, valtype uint32, err error) {
+ p, err := syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return nil, 0, err
+ }
+ var t uint32
+ n := uint32(len(buf))
+ for {
+ err = syscall.RegQueryValueEx(syscall.Handle(k), p, nil, &t, (*byte)(unsafe.Pointer(&buf[0])), &n)
+ if err == nil {
+ return buf[:n], t, nil
+ }
+ if err != syscall.ERROR_MORE_DATA {
+ return nil, 0, err
+ }
+ if n <= uint32(len(buf)) {
+ return nil, 0, err
+ }
+ buf = make([]byte, n)
+ }
+}
+
+// GetStringValue retrieves the string value for the specified
+// value name associated with an open key k. It also returns the value's type.
+// If value does not exist, GetStringValue returns ErrNotExist.
+// If value is not SZ or EXPAND_SZ, it will return the correct value
+// type and ErrUnexpectedType.
+func (k Key) GetStringValue(name string) (val string, valtype uint32, err error) {
+ data, typ, err2 := k.getValue(name, make([]byte, 64))
+ if err2 != nil {
+ return "", typ, err2
+ }
+ switch typ {
+ case SZ, EXPAND_SZ:
+ default:
+ return "", typ, ErrUnexpectedType
+ }
+ if len(data) == 0 {
+ return "", typ, nil
+ }
+ u := (*[1 << 29]uint16)(unsafe.Pointer(&data[0]))[:]
+ return syscall.UTF16ToString(u), typ, nil
+}
+
+// GetMUIStringValue retrieves the localized string value for
+// the specified value name associated with an open key k.
+// If the value name doesn't exist or the localized string value
+// can't be resolved, GetMUIStringValue returns ErrNotExist.
+// GetMUIStringValue panics if the system doesn't support
+// regLoadMUIString; use LoadRegLoadMUIString to check if
+// regLoadMUIString is supported before calling this function.
+func (k Key) GetMUIStringValue(name string) (string, error) {
+ pname, err := syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return "", err
+ }
+
+ buf := make([]uint16, 1024)
+ var buflen uint32
+ var pdir *uint16
+
+ err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir)
+ if err == syscall.ERROR_FILE_NOT_FOUND { // Try fallback path
+
+ // Try to resolve the string value using the system directory as
+ // a DLL search path; this assumes the string value is of the form
+ // @[path]\dllname,-strID but with no path given, e.g. @tzres.dll,-320.
+
+ // This approach works with tzres.dll but may have to be revised
+ // in the future to allow callers to provide custom search paths.
+
+ var s string
+ s, err = ExpandString("%SystemRoot%\\system32\\")
+ if err != nil {
+ return "", err
+ }
+ pdir, err = syscall.UTF16PtrFromString(s)
+ if err != nil {
+ return "", err
+ }
+
+ err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir)
+ }
+
+ for err == syscall.ERROR_MORE_DATA { // Grow buffer if needed
+ if buflen <= uint32(len(buf)) {
+ break // Buffer not growing, assume race; break
+ }
+ buf = make([]uint16, buflen)
+ err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir)
+ }
+
+ if err != nil {
+ return "", err
+ }
+
+ return syscall.UTF16ToString(buf), nil
+}
+
+// ExpandString expands environment-variable strings and replaces
+// them with the values defined for the current user.
+// Use ExpandString to expand EXPAND_SZ strings.
+func ExpandString(value string) (string, error) {
+ if value == "" {
+ return "", nil
+ }
+ p, err := syscall.UTF16PtrFromString(value)
+ if err != nil {
+ return "", err
+ }
+ r := make([]uint16, 100)
+ for {
+ n, err := expandEnvironmentStrings(p, &r[0], uint32(len(r)))
+ if err != nil {
+ return "", err
+ }
+ if n <= uint32(len(r)) {
+ u := (*[1 << 29]uint16)(unsafe.Pointer(&r[0]))[:]
+ return syscall.UTF16ToString(u), nil
+ }
+ r = make([]uint16, n)
+ }
+}
+
+// GetStringsValue retrieves the []string value for the specified
+// value name associated with an open key k. It also returns the value's type.
+// If value does not exist, GetStringsValue returns ErrNotExist.
+// If value is not MULTI_SZ, it will return the correct value
+// type and ErrUnexpectedType.
+func (k Key) GetStringsValue(name string) (val []string, valtype uint32, err error) {
+ data, typ, err2 := k.getValue(name, make([]byte, 64))
+ if err2 != nil {
+ return nil, typ, err2
+ }
+ if typ != MULTI_SZ {
+ return nil, typ, ErrUnexpectedType
+ }
+ if len(data) == 0 {
+ return nil, typ, nil
+ }
+ p := (*[1 << 29]uint16)(unsafe.Pointer(&data[0]))[:len(data)/2]
+ if len(p) == 0 {
+ return nil, typ, nil
+ }
+ if p[len(p)-1] == 0 {
+ p = p[:len(p)-1] // remove terminating null
+ }
+ val = make([]string, 0, 5)
+ from := 0
+ for i, c := range p {
+ if c == 0 {
+ val = append(val, string(utf16.Decode(p[from:i])))
+ from = i + 1
+ }
+ }
+ return val, typ, nil
+}
+
+// GetIntegerValue retrieves the integer value for the specified
+// value name associated with an open key k. It also returns the value's type.
+// If value does not exist, GetIntegerValue returns ErrNotExist.
+// If value is not DWORD or QWORD, it will return the correct value
+// type and ErrUnexpectedType.
+func (k Key) GetIntegerValue(name string) (val uint64, valtype uint32, err error) {
+ data, typ, err2 := k.getValue(name, make([]byte, 8))
+ if err2 != nil {
+ return 0, typ, err2
+ }
+ switch typ {
+ case DWORD:
+ if len(data) != 4 {
+ return 0, typ, errors.New("DWORD value is not 4 bytes long")
+ }
+ return uint64(*(*uint32)(unsafe.Pointer(&data[0]))), DWORD, nil
+ case QWORD:
+ if len(data) != 8 {
+ return 0, typ, errors.New("QWORD value is not 8 bytes long")
+ }
+ return uint64(*(*uint64)(unsafe.Pointer(&data[0]))), QWORD, nil
+ default:
+ return 0, typ, ErrUnexpectedType
+ }
+}
+
+// GetBinaryValue retrieves the binary value for the specified
+// value name associated with an open key k. It also returns the value's type.
+// If value does not exist, GetBinaryValue returns ErrNotExist.
+// If value is not BINARY, it will return the correct value
+// type and ErrUnexpectedType.
+func (k Key) GetBinaryValue(name string) (val []byte, valtype uint32, err error) {
+ data, typ, err2 := k.getValue(name, make([]byte, 64))
+ if err2 != nil {
+ return nil, typ, err2
+ }
+ if typ != BINARY {
+ return nil, typ, ErrUnexpectedType
+ }
+ return data, typ, nil
+}
+
+func (k Key) setValue(name string, valtype uint32, data []byte) error {
+ p, err := syscall.UTF16PtrFromString(name)
+ if err != nil {
+ return err
+ }
+ if len(data) == 0 {
+ return regSetValueEx(syscall.Handle(k), p, 0, valtype, nil, 0)
+ }
+ return regSetValueEx(syscall.Handle(k), p, 0, valtype, &data[0], uint32(len(data)))
+}
+
+// SetDWordValue sets the data and type of a name value
+// under key k to value and DWORD.
+func (k Key) SetDWordValue(name string, value uint32) error {
+ return k.setValue(name, DWORD, (*[4]byte)(unsafe.Pointer(&value))[:])
+}
+
+// SetQWordValue sets the data and type of a name value
+// under key k to value and QWORD.
+func (k Key) SetQWordValue(name string, value uint64) error {
+ return k.setValue(name, QWORD, (*[8]byte)(unsafe.Pointer(&value))[:])
+}
+
+func (k Key) setStringValue(name string, valtype uint32, value string) error {
+ v, err := syscall.UTF16FromString(value)
+ if err != nil {
+ return err
+ }
+ buf := (*[1 << 29]byte)(unsafe.Pointer(&v[0]))[:len(v)*2]
+ return k.setValue(name, valtype, buf)
+}
+
+// SetStringValue sets the data and type of a name value
+// under key k to value and SZ. The value must not contain a zero byte.
+func (k Key) SetStringValue(name, value string) error {
+ return k.setStringValue(name, SZ, value)
+}
+
+// SetExpandStringValue sets the data and type of a name value
+// under key k to value and EXPAND_SZ. The value must not contain a zero byte.
+func (k Key) SetExpandStringValue(name, value string) error {
+ return k.setStringValue(name, EXPAND_SZ, value)
+}
+
+// SetStringsValue sets the data and type of a name value
+// under key k to value and MULTI_SZ. The value strings
+// must not contain a zero byte.
+func (k Key) SetStringsValue(name string, value []string) error {
+ ss := ""
+ for _, s := range value {
+ for i := 0; i < len(s); i++ {
+ if s[i] == 0 {
+ return errors.New("string cannot have 0 inside")
+ }
+ }
+ ss += s + "\x00"
+ }
+ v := utf16.Encode([]rune(ss + "\x00"))
+ buf := (*[1 << 29]byte)(unsafe.Pointer(&v[0]))[:len(v)*2]
+ return k.setValue(name, MULTI_SZ, buf)
+}
+
+// SetBinaryValue sets the data and type of a name value
+// under key k to value and BINARY.
+func (k Key) SetBinaryValue(name string, value []byte) error {
+ return k.setValue(name, BINARY, value)
+}
+
+// DeleteValue removes a named value from the key k.
+func (k Key) DeleteValue(name string) error {
+ return regDeleteValue(syscall.Handle(k), syscall.StringToUTF16Ptr(name))
+}
+
+// ReadValueNames returns the value names of key k.
+// The parameter n controls the number of returned names,
+// analogous to the way os.File.Readdirnames works.
+func (k Key) ReadValueNames(n int) ([]string, error) {
+ ki, err := k.Stat()
+ if err != nil {
+ return nil, err
+ }
+ names := make([]string, 0, ki.ValueCount)
+ buf := make([]uint16, ki.MaxValueNameLen+1) // extra room for terminating null character
+loopItems:
+ for i := uint32(0); ; i++ {
+ if n > 0 {
+ if len(names) == n {
+ return names, nil
+ }
+ }
+ l := uint32(len(buf))
+ for {
+ err := regEnumValue(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil)
+ if err == nil {
+ break
+ }
+ if err == syscall.ERROR_MORE_DATA {
+ // Double buffer size and try again.
+ l = uint32(2 * len(buf))
+ buf = make([]uint16, l)
+ continue
+ }
+ if err == _ERROR_NO_MORE_ITEMS {
+ break loopItems
+ }
+ return names, err
+ }
+ names = append(names, syscall.UTF16ToString(buf[:l]))
+ }
+ if n > len(names) {
+ return names, io.EOF
+ }
+ return names, nil
+}
diff --git a/vendor/golang.org/x/sys/windows/registry/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/registry/zsyscall_windows.go
new file mode 100644
index 0000000..ceebdd7
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/registry/zsyscall_windows.go
@@ -0,0 +1,120 @@
+// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT
+
+package registry
+
+import (
+ "syscall"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+var _ unsafe.Pointer
+
+// Do the interface allocations only once for common
+// Errno values.
+const (
+ errnoERROR_IO_PENDING = 997
+)
+
+var (
+ errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
+)
+
+// errnoErr returns common boxed Errno values, to prevent
+// allocations at runtime.
+func errnoErr(e syscall.Errno) error {
+ switch e {
+ case 0:
+ return nil
+ case errnoERROR_IO_PENDING:
+ return errERROR_IO_PENDING
+ }
+ // TODO: add more here, after collecting data on the common
+ // error values see on Windows. (perhaps when running
+ // all.bat?)
+ return e
+}
+
+var (
+ modadvapi32 = windows.NewLazySystemDLL("advapi32.dll")
+ modkernel32 = windows.NewLazySystemDLL("kernel32.dll")
+
+ procRegCreateKeyExW = modadvapi32.NewProc("RegCreateKeyExW")
+ procRegDeleteKeyW = modadvapi32.NewProc("RegDeleteKeyW")
+ procRegSetValueExW = modadvapi32.NewProc("RegSetValueExW")
+ procRegEnumValueW = modadvapi32.NewProc("RegEnumValueW")
+ procRegDeleteValueW = modadvapi32.NewProc("RegDeleteValueW")
+ procRegLoadMUIStringW = modadvapi32.NewProc("RegLoadMUIStringW")
+ procRegConnectRegistryW = modadvapi32.NewProc("RegConnectRegistryW")
+ procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW")
+)
+
+func regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) {
+ r0, _, _ := syscall.Syscall9(procRegCreateKeyExW.Addr(), 9, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(reserved), uintptr(unsafe.Pointer(class)), uintptr(options), uintptr(desired), uintptr(unsafe.Pointer(sa)), uintptr(unsafe.Pointer(result)), uintptr(unsafe.Pointer(disposition)))
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) {
+ r0, _, _ := syscall.Syscall(procRegDeleteKeyW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(subkey)), 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) {
+ r0, _, _ := syscall.Syscall6(procRegSetValueExW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(valueName)), uintptr(reserved), uintptr(vtype), uintptr(unsafe.Pointer(buf)), uintptr(bufsize))
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) {
+ r0, _, _ := syscall.Syscall9(procRegEnumValueW.Addr(), 8, uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen)), 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) {
+ r0, _, _ := syscall.Syscall(procRegDeleteValueW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(name)), 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) {
+ r0, _, _ := syscall.Syscall9(procRegLoadMUIStringW.Addr(), 7, uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(unsafe.Pointer(buflenCopied)), uintptr(flags), uintptr(unsafe.Pointer(dir)), 0, 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func regConnectRegistry(machinename *uint16, key syscall.Handle, result *syscall.Handle) (regerrno error) {
+ r0, _, _ := syscall.Syscall(procRegConnectRegistryW.Addr(), 3, uintptr(unsafe.Pointer(machinename)), uintptr(key), uintptr(unsafe.Pointer(result)))
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procExpandEnvironmentStringsW.Addr(), 3, uintptr(unsafe.Pointer(src)), uintptr(unsafe.Pointer(dst)), uintptr(size))
+ n = uint32(r0)
+ if n == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
diff --git a/vendor/golang.org/x/sys/windows/security_windows.go b/vendor/golang.org/x/sys/windows/security_windows.go
new file mode 100644
index 0000000..ca09bdd
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/security_windows.go
@@ -0,0 +1,435 @@
+// 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 windows
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+const (
+ STANDARD_RIGHTS_REQUIRED = 0xf0000
+ STANDARD_RIGHTS_READ = 0x20000
+ STANDARD_RIGHTS_WRITE = 0x20000
+ STANDARD_RIGHTS_EXECUTE = 0x20000
+ STANDARD_RIGHTS_ALL = 0x1F0000
+)
+
+const (
+ NameUnknown = 0
+ NameFullyQualifiedDN = 1
+ NameSamCompatible = 2
+ NameDisplay = 3
+ NameUniqueId = 6
+ NameCanonical = 7
+ NameUserPrincipal = 8
+ NameCanonicalEx = 9
+ NameServicePrincipal = 10
+ NameDnsDomain = 12
+)
+
+// This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
+// http://blogs.msdn.com/b/drnick/archive/2007/12/19/windows-and-upn-format-credentials.aspx
+//sys TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.TranslateNameW
+//sys GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.GetUserNameExW
+
+// TranslateAccountName converts a directory service
+// object name from one format to another.
+func TranslateAccountName(username string, from, to uint32, initSize int) (string, error) {
+ u, e := UTF16PtrFromString(username)
+ if e != nil {
+ return "", e
+ }
+ n := uint32(50)
+ for {
+ b := make([]uint16, n)
+ e = TranslateName(u, from, to, &b[0], &n)
+ if e == nil {
+ return UTF16ToString(b[:n]), nil
+ }
+ if e != ERROR_INSUFFICIENT_BUFFER {
+ return "", e
+ }
+ if n <= uint32(len(b)) {
+ return "", e
+ }
+ }
+}
+
+const (
+ // do not reorder
+ NetSetupUnknownStatus = iota
+ NetSetupUnjoined
+ NetSetupWorkgroupName
+ NetSetupDomainName
+)
+
+type UserInfo10 struct {
+ Name *uint16
+ Comment *uint16
+ UsrComment *uint16
+ FullName *uint16
+}
+
+//sys NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) = netapi32.NetUserGetInfo
+//sys NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) = netapi32.NetGetJoinInformation
+//sys NetApiBufferFree(buf *byte) (neterr error) = netapi32.NetApiBufferFree
+
+const (
+ // do not reorder
+ SidTypeUser = 1 + iota
+ SidTypeGroup
+ SidTypeDomain
+ SidTypeAlias
+ SidTypeWellKnownGroup
+ SidTypeDeletedAccount
+ SidTypeInvalid
+ SidTypeUnknown
+ SidTypeComputer
+ SidTypeLabel
+)
+
+type SidIdentifierAuthority struct {
+ Value [6]byte
+}
+
+var (
+ SECURITY_NULL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 0}}
+ SECURITY_WORLD_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 1}}
+ SECURITY_LOCAL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 2}}
+ SECURITY_CREATOR_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 3}}
+ SECURITY_NON_UNIQUE_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 4}}
+ SECURITY_NT_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 5}}
+ SECURITY_MANDATORY_LABEL_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 16}}
+)
+
+const (
+ SECURITY_NULL_RID = 0
+ SECURITY_WORLD_RID = 0
+ SECURITY_LOCAL_RID = 0
+ SECURITY_CREATOR_OWNER_RID = 0
+ SECURITY_CREATOR_GROUP_RID = 1
+ SECURITY_DIALUP_RID = 1
+ SECURITY_NETWORK_RID = 2
+ SECURITY_BATCH_RID = 3
+ SECURITY_INTERACTIVE_RID = 4
+ SECURITY_LOGON_IDS_RID = 5
+ SECURITY_SERVICE_RID = 6
+ SECURITY_LOCAL_SYSTEM_RID = 18
+ SECURITY_BUILTIN_DOMAIN_RID = 32
+ SECURITY_PRINCIPAL_SELF_RID = 10
+ SECURITY_CREATOR_OWNER_SERVER_RID = 0x2
+ SECURITY_CREATOR_GROUP_SERVER_RID = 0x3
+ SECURITY_LOGON_IDS_RID_COUNT = 0x3
+ SECURITY_ANONYMOUS_LOGON_RID = 0x7
+ SECURITY_PROXY_RID = 0x8
+ SECURITY_ENTERPRISE_CONTROLLERS_RID = 0x9
+ SECURITY_SERVER_LOGON_RID = SECURITY_ENTERPRISE_CONTROLLERS_RID
+ SECURITY_AUTHENTICATED_USER_RID = 0xb
+ SECURITY_RESTRICTED_CODE_RID = 0xc
+ SECURITY_NT_NON_UNIQUE_RID = 0x15
+)
+
+//sys LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountSidW
+//sys LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountNameW
+//sys ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) = advapi32.ConvertSidToStringSidW
+//sys ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) = advapi32.ConvertStringSidToSidW
+//sys GetLengthSid(sid *SID) (len uint32) = advapi32.GetLengthSid
+//sys CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) = advapi32.CopySid
+//sys AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) = advapi32.AllocateAndInitializeSid
+//sys FreeSid(sid *SID) (err error) [failretval!=0] = advapi32.FreeSid
+//sys EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) = advapi32.EqualSid
+
+// The security identifier (SID) structure is a variable-length
+// structure used to uniquely identify users or groups.
+type SID struct{}
+
+// StringToSid converts a string-format security identifier
+// sid into a valid, functional sid.
+func StringToSid(s string) (*SID, error) {
+ var sid *SID
+ p, e := UTF16PtrFromString(s)
+ if e != nil {
+ return nil, e
+ }
+ e = ConvertStringSidToSid(p, &sid)
+ if e != nil {
+ return nil, e
+ }
+ defer LocalFree((Handle)(unsafe.Pointer(sid)))
+ return sid.Copy()
+}
+
+// LookupSID retrieves a security identifier sid for the account
+// and the name of the domain on which the account was found.
+// System specify target computer to search.
+func LookupSID(system, account string) (sid *SID, domain string, accType uint32, err error) {
+ if len(account) == 0 {
+ return nil, "", 0, syscall.EINVAL
+ }
+ acc, e := UTF16PtrFromString(account)
+ if e != nil {
+ return nil, "", 0, e
+ }
+ var sys *uint16
+ if len(system) > 0 {
+ sys, e = UTF16PtrFromString(system)
+ if e != nil {
+ return nil, "", 0, e
+ }
+ }
+ n := uint32(50)
+ dn := uint32(50)
+ for {
+ b := make([]byte, n)
+ db := make([]uint16, dn)
+ sid = (*SID)(unsafe.Pointer(&b[0]))
+ e = LookupAccountName(sys, acc, sid, &n, &db[0], &dn, &accType)
+ if e == nil {
+ return sid, UTF16ToString(db), accType, nil
+ }
+ if e != ERROR_INSUFFICIENT_BUFFER {
+ return nil, "", 0, e
+ }
+ if n <= uint32(len(b)) {
+ return nil, "", 0, e
+ }
+ }
+}
+
+// String converts sid to a string format
+// suitable for display, storage, or transmission.
+func (sid *SID) String() (string, error) {
+ var s *uint16
+ e := ConvertSidToStringSid(sid, &s)
+ if e != nil {
+ return "", e
+ }
+ defer LocalFree((Handle)(unsafe.Pointer(s)))
+ return UTF16ToString((*[256]uint16)(unsafe.Pointer(s))[:]), nil
+}
+
+// Len returns the length, in bytes, of a valid security identifier sid.
+func (sid *SID) Len() int {
+ return int(GetLengthSid(sid))
+}
+
+// Copy creates a duplicate of security identifier sid.
+func (sid *SID) Copy() (*SID, error) {
+ b := make([]byte, sid.Len())
+ sid2 := (*SID)(unsafe.Pointer(&b[0]))
+ e := CopySid(uint32(len(b)), sid2, sid)
+ if e != nil {
+ return nil, e
+ }
+ return sid2, nil
+}
+
+// LookupAccount retrieves the name of the account for this sid
+// and the name of the first domain on which this sid is found.
+// System specify target computer to search for.
+func (sid *SID) LookupAccount(system string) (account, domain string, accType uint32, err error) {
+ var sys *uint16
+ if len(system) > 0 {
+ sys, err = UTF16PtrFromString(system)
+ if err != nil {
+ return "", "", 0, err
+ }
+ }
+ n := uint32(50)
+ dn := uint32(50)
+ for {
+ b := make([]uint16, n)
+ db := make([]uint16, dn)
+ e := LookupAccountSid(sys, sid, &b[0], &n, &db[0], &dn, &accType)
+ if e == nil {
+ return UTF16ToString(b), UTF16ToString(db), accType, nil
+ }
+ if e != ERROR_INSUFFICIENT_BUFFER {
+ return "", "", 0, e
+ }
+ if n <= uint32(len(b)) {
+ return "", "", 0, e
+ }
+ }
+}
+
+const (
+ // do not reorder
+ TOKEN_ASSIGN_PRIMARY = 1 << iota
+ TOKEN_DUPLICATE
+ TOKEN_IMPERSONATE
+ TOKEN_QUERY
+ TOKEN_QUERY_SOURCE
+ TOKEN_ADJUST_PRIVILEGES
+ TOKEN_ADJUST_GROUPS
+ TOKEN_ADJUST_DEFAULT
+
+ TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED |
+ TOKEN_ASSIGN_PRIMARY |
+ TOKEN_DUPLICATE |
+ TOKEN_IMPERSONATE |
+ TOKEN_QUERY |
+ TOKEN_QUERY_SOURCE |
+ TOKEN_ADJUST_PRIVILEGES |
+ TOKEN_ADJUST_GROUPS |
+ TOKEN_ADJUST_DEFAULT
+ TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY
+ TOKEN_WRITE = STANDARD_RIGHTS_WRITE |
+ TOKEN_ADJUST_PRIVILEGES |
+ TOKEN_ADJUST_GROUPS |
+ TOKEN_ADJUST_DEFAULT
+ TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE
+)
+
+const (
+ // do not reorder
+ TokenUser = 1 + iota
+ TokenGroups
+ TokenPrivileges
+ TokenOwner
+ TokenPrimaryGroup
+ TokenDefaultDacl
+ TokenSource
+ TokenType
+ TokenImpersonationLevel
+ TokenStatistics
+ TokenRestrictedSids
+ TokenSessionId
+ TokenGroupsAndPrivileges
+ TokenSessionReference
+ TokenSandBoxInert
+ TokenAuditPolicy
+ TokenOrigin
+ TokenElevationType
+ TokenLinkedToken
+ TokenElevation
+ TokenHasRestrictions
+ TokenAccessInformation
+ TokenVirtualizationAllowed
+ TokenVirtualizationEnabled
+ TokenIntegrityLevel
+ TokenUIAccess
+ TokenMandatoryPolicy
+ TokenLogonSid
+ MaxTokenInfoClass
+)
+
+type SIDAndAttributes struct {
+ Sid *SID
+ Attributes uint32
+}
+
+type Tokenuser struct {
+ User SIDAndAttributes
+}
+
+type Tokenprimarygroup struct {
+ PrimaryGroup *SID
+}
+
+type Tokengroups struct {
+ GroupCount uint32
+ Groups [1]SIDAndAttributes
+}
+
+//sys OpenProcessToken(h Handle, access uint32, token *Token) (err error) = advapi32.OpenProcessToken
+//sys GetTokenInformation(t Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) = advapi32.GetTokenInformation
+//sys GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) = userenv.GetUserProfileDirectoryW
+
+// An access token contains the security information for a logon session.
+// The system creates an access token when a user logs on, and every
+// process executed on behalf of the user has a copy of the token.
+// The token identifies the user, the user's groups, and the user's
+// privileges. The system uses the token to control access to securable
+// objects and to control the ability of the user to perform various
+// system-related operations on the local computer.
+type Token Handle
+
+// OpenCurrentProcessToken opens the access token
+// associated with current process.
+func OpenCurrentProcessToken() (Token, error) {
+ p, e := GetCurrentProcess()
+ if e != nil {
+ return 0, e
+ }
+ var t Token
+ e = OpenProcessToken(p, TOKEN_QUERY, &t)
+ if e != nil {
+ return 0, e
+ }
+ return t, nil
+}
+
+// Close releases access to access token.
+func (t Token) Close() error {
+ return CloseHandle(Handle(t))
+}
+
+// getInfo retrieves a specified type of information about an access token.
+func (t Token) getInfo(class uint32, initSize int) (unsafe.Pointer, error) {
+ n := uint32(initSize)
+ for {
+ b := make([]byte, n)
+ e := GetTokenInformation(t, class, &b[0], uint32(len(b)), &n)
+ if e == nil {
+ return unsafe.Pointer(&b[0]), nil
+ }
+ if e != ERROR_INSUFFICIENT_BUFFER {
+ return nil, e
+ }
+ if n <= uint32(len(b)) {
+ return nil, e
+ }
+ }
+}
+
+// GetTokenUser retrieves access token t user account information.
+func (t Token) GetTokenUser() (*Tokenuser, error) {
+ i, e := t.getInfo(TokenUser, 50)
+ if e != nil {
+ return nil, e
+ }
+ return (*Tokenuser)(i), nil
+}
+
+// GetTokenGroups retrieves group accounts associated with access token t.
+func (t Token) GetTokenGroups() (*Tokengroups, error) {
+ i, e := t.getInfo(TokenGroups, 50)
+ if e != nil {
+ return nil, e
+ }
+ return (*Tokengroups)(i), nil
+}
+
+// GetTokenPrimaryGroup retrieves access token t primary group information.
+// A pointer to a SID structure representing a group that will become
+// the primary group of any objects created by a process using this access token.
+func (t Token) GetTokenPrimaryGroup() (*Tokenprimarygroup, error) {
+ i, e := t.getInfo(TokenPrimaryGroup, 50)
+ if e != nil {
+ return nil, e
+ }
+ return (*Tokenprimarygroup)(i), nil
+}
+
+// GetUserProfileDirectory retrieves path to the
+// root directory of the access token t user's profile.
+func (t Token) GetUserProfileDirectory() (string, error) {
+ n := uint32(100)
+ for {
+ b := make([]uint16, n)
+ e := GetUserProfileDirectory(t, &b[0], &n)
+ if e == nil {
+ return UTF16ToString(b), nil
+ }
+ if e != ERROR_INSUFFICIENT_BUFFER {
+ return "", e
+ }
+ if n <= uint32(len(b)) {
+ return "", e
+ }
+ }
+}
diff --git a/vendor/golang.org/x/sys/windows/service.go b/vendor/golang.org/x/sys/windows/service.go
new file mode 100644
index 0000000..a500dd7
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/service.go
@@ -0,0 +1,164 @@
+// 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 windows
+
+package windows
+
+const (
+ SC_MANAGER_CONNECT = 1
+ SC_MANAGER_CREATE_SERVICE = 2
+ SC_MANAGER_ENUMERATE_SERVICE = 4
+ SC_MANAGER_LOCK = 8
+ SC_MANAGER_QUERY_LOCK_STATUS = 16
+ SC_MANAGER_MODIFY_BOOT_CONFIG = 32
+ SC_MANAGER_ALL_ACCESS = 0xf003f
+)
+
+//sys OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenSCManagerW
+
+const (
+ SERVICE_KERNEL_DRIVER = 1
+ SERVICE_FILE_SYSTEM_DRIVER = 2
+ SERVICE_ADAPTER = 4
+ SERVICE_RECOGNIZER_DRIVER = 8
+ SERVICE_WIN32_OWN_PROCESS = 16
+ SERVICE_WIN32_SHARE_PROCESS = 32
+ SERVICE_WIN32 = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS
+ SERVICE_INTERACTIVE_PROCESS = 256
+ SERVICE_DRIVER = SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_RECOGNIZER_DRIVER
+ SERVICE_TYPE_ALL = SERVICE_WIN32 | SERVICE_ADAPTER | SERVICE_DRIVER | SERVICE_INTERACTIVE_PROCESS
+
+ SERVICE_BOOT_START = 0
+ SERVICE_SYSTEM_START = 1
+ SERVICE_AUTO_START = 2
+ SERVICE_DEMAND_START = 3
+ SERVICE_DISABLED = 4
+
+ SERVICE_ERROR_IGNORE = 0
+ SERVICE_ERROR_NORMAL = 1
+ SERVICE_ERROR_SEVERE = 2
+ SERVICE_ERROR_CRITICAL = 3
+
+ SC_STATUS_PROCESS_INFO = 0
+
+ SERVICE_STOPPED = 1
+ SERVICE_START_PENDING = 2
+ SERVICE_STOP_PENDING = 3
+ SERVICE_RUNNING = 4
+ SERVICE_CONTINUE_PENDING = 5
+ SERVICE_PAUSE_PENDING = 6
+ SERVICE_PAUSED = 7
+ SERVICE_NO_CHANGE = 0xffffffff
+
+ SERVICE_ACCEPT_STOP = 1
+ SERVICE_ACCEPT_PAUSE_CONTINUE = 2
+ SERVICE_ACCEPT_SHUTDOWN = 4
+ SERVICE_ACCEPT_PARAMCHANGE = 8
+ SERVICE_ACCEPT_NETBINDCHANGE = 16
+ SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 32
+ SERVICE_ACCEPT_POWEREVENT = 64
+ SERVICE_ACCEPT_SESSIONCHANGE = 128
+
+ SERVICE_CONTROL_STOP = 1
+ SERVICE_CONTROL_PAUSE = 2
+ SERVICE_CONTROL_CONTINUE = 3
+ SERVICE_CONTROL_INTERROGATE = 4
+ SERVICE_CONTROL_SHUTDOWN = 5
+ SERVICE_CONTROL_PARAMCHANGE = 6
+ SERVICE_CONTROL_NETBINDADD = 7
+ SERVICE_CONTROL_NETBINDREMOVE = 8
+ SERVICE_CONTROL_NETBINDENABLE = 9
+ SERVICE_CONTROL_NETBINDDISABLE = 10
+ SERVICE_CONTROL_DEVICEEVENT = 11
+ SERVICE_CONTROL_HARDWAREPROFILECHANGE = 12
+ SERVICE_CONTROL_POWEREVENT = 13
+ SERVICE_CONTROL_SESSIONCHANGE = 14
+
+ SERVICE_ACTIVE = 1
+ SERVICE_INACTIVE = 2
+ SERVICE_STATE_ALL = 3
+
+ SERVICE_QUERY_CONFIG = 1
+ SERVICE_CHANGE_CONFIG = 2
+ SERVICE_QUERY_STATUS = 4
+ SERVICE_ENUMERATE_DEPENDENTS = 8
+ SERVICE_START = 16
+ SERVICE_STOP = 32
+ SERVICE_PAUSE_CONTINUE = 64
+ SERVICE_INTERROGATE = 128
+ SERVICE_USER_DEFINED_CONTROL = 256
+ SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL
+ SERVICE_RUNS_IN_SYSTEM_PROCESS = 1
+ SERVICE_CONFIG_DESCRIPTION = 1
+ SERVICE_CONFIG_FAILURE_ACTIONS = 2
+
+ NO_ERROR = 0
+
+ SC_ENUM_PROCESS_INFO = 0
+)
+
+type SERVICE_STATUS struct {
+ ServiceType uint32
+ CurrentState uint32
+ ControlsAccepted uint32
+ Win32ExitCode uint32
+ ServiceSpecificExitCode uint32
+ CheckPoint uint32
+ WaitHint uint32
+}
+
+type SERVICE_TABLE_ENTRY struct {
+ ServiceName *uint16
+ ServiceProc uintptr
+}
+
+type QUERY_SERVICE_CONFIG struct {
+ ServiceType uint32
+ StartType uint32
+ ErrorControl uint32
+ BinaryPathName *uint16
+ LoadOrderGroup *uint16
+ TagId uint32
+ Dependencies *uint16
+ ServiceStartName *uint16
+ DisplayName *uint16
+}
+
+type SERVICE_DESCRIPTION struct {
+ Description *uint16
+}
+
+type SERVICE_STATUS_PROCESS struct {
+ ServiceType uint32
+ CurrentState uint32
+ ControlsAccepted uint32
+ Win32ExitCode uint32
+ ServiceSpecificExitCode uint32
+ CheckPoint uint32
+ WaitHint uint32
+ ProcessId uint32
+ ServiceFlags uint32
+}
+
+type ENUM_SERVICE_STATUS_PROCESS struct {
+ ServiceName *uint16
+ DisplayName *uint16
+ ServiceStatusProcess SERVICE_STATUS_PROCESS
+}
+
+//sys CloseServiceHandle(handle Handle) (err error) = advapi32.CloseServiceHandle
+//sys CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) [failretval==0] = advapi32.CreateServiceW
+//sys OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenServiceW
+//sys DeleteService(service Handle) (err error) = advapi32.DeleteService
+//sys StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) = advapi32.StartServiceW
+//sys QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) = advapi32.QueryServiceStatus
+//sys ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) = advapi32.ControlService
+//sys StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) = advapi32.StartServiceCtrlDispatcherW
+//sys SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) = advapi32.SetServiceStatus
+//sys ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) = advapi32.ChangeServiceConfigW
+//sys QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfigW
+//sys ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) = advapi32.ChangeServiceConfig2W
+//sys QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfig2W
+//sys EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error) = advapi32.EnumServicesStatusExW
diff --git a/vendor/golang.org/x/sys/windows/str.go b/vendor/golang.org/x/sys/windows/str.go
new file mode 100644
index 0000000..917cc2a
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/str.go
@@ -0,0 +1,22 @@
+// Copyright 2009 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 windows
+
+package windows
+
+func itoa(val int) string { // do it here rather than with fmt to avoid dependency
+ if val < 0 {
+ return "-" + itoa(-val)
+ }
+ var buf [32]byte // big enough for int64
+ i := len(buf) - 1
+ for val >= 10 {
+ buf[i] = byte(val%10 + '0')
+ i--
+ val /= 10
+ }
+ buf[i] = byte(val + '0')
+ return string(buf[i:])
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/debug/log.go b/vendor/golang.org/x/sys/windows/svc/debug/log.go
new file mode 100644
index 0000000..e51ab42
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/debug/log.go
@@ -0,0 +1,56 @@
+// 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 windows
+
+package debug
+
+import (
+ "os"
+ "strconv"
+)
+
+// Log interface allows different log implementations to be used.
+type Log interface {
+ Close() error
+ Info(eid uint32, msg string) error
+ Warning(eid uint32, msg string) error
+ Error(eid uint32, msg string) error
+}
+
+// ConsoleLog provides access to the console.
+type ConsoleLog struct {
+ Name string
+}
+
+// New creates new ConsoleLog.
+func New(source string) *ConsoleLog {
+ return &ConsoleLog{Name: source}
+}
+
+// Close closes console log l.
+func (l *ConsoleLog) Close() error {
+ return nil
+}
+
+func (l *ConsoleLog) report(kind string, eid uint32, msg string) error {
+ s := l.Name + "." + kind + "(" + strconv.Itoa(int(eid)) + "): " + msg + "\n"
+ _, err := os.Stdout.Write([]byte(s))
+ return err
+}
+
+// Info writes an information event msg with event id eid to the console l.
+func (l *ConsoleLog) Info(eid uint32, msg string) error {
+ return l.report("info", eid, msg)
+}
+
+// Warning writes an warning event msg with event id eid to the console l.
+func (l *ConsoleLog) Warning(eid uint32, msg string) error {
+ return l.report("warn", eid, msg)
+}
+
+// Error writes an error event msg with event id eid to the console l.
+func (l *ConsoleLog) Error(eid uint32, msg string) error {
+ return l.report("error", eid, msg)
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/debug/service.go b/vendor/golang.org/x/sys/windows/svc/debug/service.go
new file mode 100644
index 0000000..123df98
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/debug/service.go
@@ -0,0 +1,45 @@
+// 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 windows
+
+// Package debug provides facilities to execute svc.Handler on console.
+//
+package debug
+
+import (
+ "os"
+ "os/signal"
+ "syscall"
+
+ "golang.org/x/sys/windows/svc"
+)
+
+// Run executes service name by calling appropriate handler function.
+// The process is running on console, unlike real service. Use Ctrl+C to
+// send "Stop" command to your service.
+func Run(name string, handler svc.Handler) error {
+ cmds := make(chan svc.ChangeRequest)
+ changes := make(chan svc.Status)
+
+ sig := make(chan os.Signal)
+ signal.Notify(sig)
+
+ go func() {
+ status := svc.Status{State: svc.Stopped}
+ for {
+ select {
+ case <-sig:
+ cmds <- svc.ChangeRequest{svc.Stop, 0, 0, status}
+ case status = <-changes:
+ }
+ }
+ }()
+
+ _, errno := handler.Execute([]string{name}, cmds, changes)
+ if errno != 0 {
+ return syscall.Errno(errno)
+ }
+ return nil
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/event.go b/vendor/golang.org/x/sys/windows/svc/event.go
new file mode 100644
index 0000000..0508e22
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/event.go
@@ -0,0 +1,48 @@
+// 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 windows
+
+package svc
+
+import (
+ "errors"
+
+ "golang.org/x/sys/windows"
+)
+
+// event represents auto-reset, initially non-signaled Windows event.
+// It is used to communicate between go and asm parts of this package.
+type event struct {
+ h windows.Handle
+}
+
+func newEvent() (*event, error) {
+ h, err := windows.CreateEvent(nil, 0, 0, nil)
+ if err != nil {
+ return nil, err
+ }
+ return &event{h: h}, nil
+}
+
+func (e *event) Close() error {
+ return windows.CloseHandle(e.h)
+}
+
+func (e *event) Set() error {
+ return windows.SetEvent(e.h)
+}
+
+func (e *event) Wait() error {
+ s, err := windows.WaitForSingleObject(e.h, windows.INFINITE)
+ switch s {
+ case windows.WAIT_OBJECT_0:
+ break
+ case windows.WAIT_FAILED:
+ return err
+ default:
+ return errors.New("unexpected result from WaitForSingleObject")
+ }
+ return nil
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/eventlog/install.go b/vendor/golang.org/x/sys/windows/svc/eventlog/install.go
new file mode 100644
index 0000000..c76a376
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/eventlog/install.go
@@ -0,0 +1,80 @@
+// 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 windows
+
+package eventlog
+
+import (
+ "errors"
+
+ "golang.org/x/sys/windows"
+ "golang.org/x/sys/windows/registry"
+)
+
+const (
+ // Log levels.
+ Info = windows.EVENTLOG_INFORMATION_TYPE
+ Warning = windows.EVENTLOG_WARNING_TYPE
+ Error = windows.EVENTLOG_ERROR_TYPE
+)
+
+const addKeyName = `SYSTEM\CurrentControlSet\Services\EventLog\Application`
+
+// Install modifies PC registry to allow logging with an event source src.
+// It adds all required keys and values to the event log registry key.
+// Install uses msgFile as the event message file. If useExpandKey is true,
+// the event message file is installed as REG_EXPAND_SZ value,
+// otherwise as REG_SZ. Use bitwise of log.Error, log.Warning and
+// log.Info to specify events supported by the new event source.
+func Install(src, msgFile string, useExpandKey bool, eventsSupported uint32) error {
+ appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.CREATE_SUB_KEY)
+ if err != nil {
+ return err
+ }
+ defer appkey.Close()
+
+ sk, alreadyExist, err := registry.CreateKey(appkey, src, registry.SET_VALUE)
+ if err != nil {
+ return err
+ }
+ defer sk.Close()
+ if alreadyExist {
+ return errors.New(addKeyName + `\` + src + " registry key already exists")
+ }
+
+ err = sk.SetDWordValue("CustomSource", 1)
+ if err != nil {
+ return err
+ }
+ if useExpandKey {
+ err = sk.SetExpandStringValue("EventMessageFile", msgFile)
+ } else {
+ err = sk.SetStringValue("EventMessageFile", msgFile)
+ }
+ if err != nil {
+ return err
+ }
+ err = sk.SetDWordValue("TypesSupported", eventsSupported)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+// InstallAsEventCreate is the same as Install, but uses
+// %SystemRoot%\System32\EventCreate.exe as the event message file.
+func InstallAsEventCreate(src string, eventsSupported uint32) error {
+ return Install(src, "%SystemRoot%\\System32\\EventCreate.exe", true, eventsSupported)
+}
+
+// Remove deletes all registry elements installed by the correspondent Install.
+func Remove(src string) error {
+ appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.SET_VALUE)
+ if err != nil {
+ return err
+ }
+ defer appkey.Close()
+ return registry.DeleteKey(appkey, src)
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/eventlog/log.go b/vendor/golang.org/x/sys/windows/svc/eventlog/log.go
new file mode 100644
index 0000000..46e5153
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/eventlog/log.go
@@ -0,0 +1,70 @@
+// 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 windows
+
+// Package eventlog implements access to Windows event log.
+//
+package eventlog
+
+import (
+ "errors"
+ "syscall"
+
+ "golang.org/x/sys/windows"
+)
+
+// Log provides access to the system log.
+type Log struct {
+ Handle windows.Handle
+}
+
+// Open retrieves a handle to the specified event log.
+func Open(source string) (*Log, error) {
+ return OpenRemote("", source)
+}
+
+// OpenRemote does the same as Open, but on different computer host.
+func OpenRemote(host, source string) (*Log, error) {
+ if source == "" {
+ return nil, errors.New("Specify event log source")
+ }
+ var s *uint16
+ if host != "" {
+ s = syscall.StringToUTF16Ptr(host)
+ }
+ h, err := windows.RegisterEventSource(s, syscall.StringToUTF16Ptr(source))
+ if err != nil {
+ return nil, err
+ }
+ return &Log{Handle: h}, nil
+}
+
+// Close closes event log l.
+func (l *Log) Close() error {
+ return windows.DeregisterEventSource(l.Handle)
+}
+
+func (l *Log) report(etype uint16, eid uint32, msg string) error {
+ ss := []*uint16{syscall.StringToUTF16Ptr(msg)}
+ return windows.ReportEvent(l.Handle, etype, 0, eid, 0, 1, 0, &ss[0], nil)
+}
+
+// Info writes an information event msg with event id eid to the end of event log l.
+// When EventCreate.exe is used, eid must be between 1 and 1000.
+func (l *Log) Info(eid uint32, msg string) error {
+ return l.report(windows.EVENTLOG_INFORMATION_TYPE, eid, msg)
+}
+
+// Warning writes an warning event msg with event id eid to the end of event log l.
+// When EventCreate.exe is used, eid must be between 1 and 1000.
+func (l *Log) Warning(eid uint32, msg string) error {
+ return l.report(windows.EVENTLOG_WARNING_TYPE, eid, msg)
+}
+
+// Error writes an error event msg with event id eid to the end of event log l.
+// When EventCreate.exe is used, eid must be between 1 and 1000.
+func (l *Log) Error(eid uint32, msg string) error {
+ return l.report(windows.EVENTLOG_ERROR_TYPE, eid, msg)
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/go12.c b/vendor/golang.org/x/sys/windows/svc/go12.c
new file mode 100644
index 0000000..6f1be1f
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/go12.c
@@ -0,0 +1,24 @@
+// 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 windows
+// +build !go1.3
+
+// copied from pkg/runtime
+typedef unsigned int uint32;
+typedef unsigned long long int uint64;
+#ifdef _64BIT
+typedef uint64 uintptr;
+#else
+typedef uint32 uintptr;
+#endif
+
+// from sys_386.s or sys_amd64.s
+void ·servicemain(void);
+
+void
+·getServiceMain(uintptr *r)
+{
+ *r = (uintptr)·servicemain;
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/go12.go b/vendor/golang.org/x/sys/windows/svc/go12.go
new file mode 100644
index 0000000..6f0a924
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/go12.go
@@ -0,0 +1,11 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build windows
+// +build !go1.3
+
+package svc
+
+// from go12.c
+func getServiceMain(r *uintptr)
diff --git a/vendor/golang.org/x/sys/windows/svc/go13.go b/vendor/golang.org/x/sys/windows/svc/go13.go
new file mode 100644
index 0000000..432a9e7
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/go13.go
@@ -0,0 +1,31 @@
+// Copyright 2014 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build windows
+// +build go1.3
+
+package svc
+
+import "unsafe"
+
+const ptrSize = 4 << (^uintptr(0) >> 63) // unsafe.Sizeof(uintptr(0)) but an ideal const
+
+// Should be a built-in for unsafe.Pointer?
+func add(p unsafe.Pointer, x uintptr) unsafe.Pointer {
+ return unsafe.Pointer(uintptr(p) + x)
+}
+
+// funcPC returns the entry PC of the function f.
+// It assumes that f is a func value. Otherwise the behavior is undefined.
+func funcPC(f interface{}) uintptr {
+ return **(**uintptr)(add(unsafe.Pointer(&f), ptrSize))
+}
+
+// from sys_386.s and sys_amd64.s
+func servicectlhandler(ctl uint32) uintptr
+func servicemain(argc uint32, argv **uint16)
+
+func getServiceMain(r *uintptr) {
+ *r = funcPC(servicemain)
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/mgr/config.go b/vendor/golang.org/x/sys/windows/svc/mgr/config.go
new file mode 100644
index 0000000..0a6edba
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/mgr/config.go
@@ -0,0 +1,139 @@
+// 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 windows
+
+package mgr
+
+import (
+ "syscall"
+ "unicode/utf16"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+const (
+ // Service start types.
+ StartManual = windows.SERVICE_DEMAND_START // the service must be started manually
+ StartAutomatic = windows.SERVICE_AUTO_START // the service will start by itself whenever the computer reboots
+ StartDisabled = windows.SERVICE_DISABLED // the service cannot be started
+
+ // The severity of the error, and action taken,
+ // if this service fails to start.
+ ErrorCritical = windows.SERVICE_ERROR_CRITICAL
+ ErrorIgnore = windows.SERVICE_ERROR_IGNORE
+ ErrorNormal = windows.SERVICE_ERROR_NORMAL
+ ErrorSevere = windows.SERVICE_ERROR_SEVERE
+)
+
+// TODO(brainman): Password is not returned by windows.QueryServiceConfig, not sure how to get it.
+
+type Config struct {
+ ServiceType uint32
+ StartType uint32
+ ErrorControl uint32
+ BinaryPathName string // fully qualified path to the service binary file, can also include arguments for an auto-start service
+ LoadOrderGroup string
+ TagId uint32
+ Dependencies []string
+ ServiceStartName string // name of the account under which the service should run
+ DisplayName string
+ Password string
+ Description string
+}
+
+func toString(p *uint16) string {
+ if p == nil {
+ return ""
+ }
+ return syscall.UTF16ToString((*[4096]uint16)(unsafe.Pointer(p))[:])
+}
+
+func toStringSlice(ps *uint16) []string {
+ if ps == nil {
+ return nil
+ }
+ r := make([]string, 0)
+ for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(ps)); true; i++ {
+ if p[i] == 0 {
+ // empty string marks the end
+ if i <= from {
+ break
+ }
+ r = append(r, string(utf16.Decode(p[from:i])))
+ from = i + 1
+ }
+ }
+ return r
+}
+
+// Config retrieves service s configuration paramteres.
+func (s *Service) Config() (Config, error) {
+ var p *windows.QUERY_SERVICE_CONFIG
+ n := uint32(1024)
+ for {
+ b := make([]byte, n)
+ p = (*windows.QUERY_SERVICE_CONFIG)(unsafe.Pointer(&b[0]))
+ err := windows.QueryServiceConfig(s.Handle, p, n, &n)
+ if err == nil {
+ break
+ }
+ if err.(syscall.Errno) != syscall.ERROR_INSUFFICIENT_BUFFER {
+ return Config{}, err
+ }
+ if n <= uint32(len(b)) {
+ return Config{}, err
+ }
+ }
+
+ var p2 *windows.SERVICE_DESCRIPTION
+ n = uint32(1024)
+ for {
+ b := make([]byte, n)
+ p2 = (*windows.SERVICE_DESCRIPTION)(unsafe.Pointer(&b[0]))
+ err := windows.QueryServiceConfig2(s.Handle,
+ windows.SERVICE_CONFIG_DESCRIPTION, &b[0], n, &n)
+ if err == nil {
+ break
+ }
+ if err.(syscall.Errno) != syscall.ERROR_INSUFFICIENT_BUFFER {
+ return Config{}, err
+ }
+ if n <= uint32(len(b)) {
+ return Config{}, err
+ }
+ }
+
+ return Config{
+ ServiceType: p.ServiceType,
+ StartType: p.StartType,
+ ErrorControl: p.ErrorControl,
+ BinaryPathName: toString(p.BinaryPathName),
+ LoadOrderGroup: toString(p.LoadOrderGroup),
+ TagId: p.TagId,
+ Dependencies: toStringSlice(p.Dependencies),
+ ServiceStartName: toString(p.ServiceStartName),
+ DisplayName: toString(p.DisplayName),
+ Description: toString(p2.Description),
+ }, nil
+}
+
+func updateDescription(handle windows.Handle, desc string) error {
+ d := windows.SERVICE_DESCRIPTION{toPtr(desc)}
+ return windows.ChangeServiceConfig2(handle,
+ windows.SERVICE_CONFIG_DESCRIPTION, (*byte)(unsafe.Pointer(&d)))
+}
+
+// UpdateConfig updates service s configuration parameters.
+func (s *Service) UpdateConfig(c Config) error {
+ err := windows.ChangeServiceConfig(s.Handle, c.ServiceType, c.StartType,
+ c.ErrorControl, toPtr(c.BinaryPathName), toPtr(c.LoadOrderGroup),
+ nil, toStringBlock(c.Dependencies), toPtr(c.ServiceStartName),
+ toPtr(c.Password), toPtr(c.DisplayName))
+ if err != nil {
+ return err
+ }
+ return updateDescription(s.Handle, c.Description)
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/mgr/mgr.go b/vendor/golang.org/x/sys/windows/svc/mgr/mgr.go
new file mode 100644
index 0000000..76965b5
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/mgr/mgr.go
@@ -0,0 +1,162 @@
+// 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 windows
+
+// Package mgr can be used to manage Windows service programs.
+// It can be used to install and remove them. It can also start,
+// stop and pause them. The package can query / change current
+// service state and config parameters.
+//
+package mgr
+
+import (
+ "syscall"
+ "unicode/utf16"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+// Mgr is used to manage Windows service.
+type Mgr struct {
+ Handle windows.Handle
+}
+
+// Connect establishes a connection to the service control manager.
+func Connect() (*Mgr, error) {
+ return ConnectRemote("")
+}
+
+// ConnectRemote establishes a connection to the
+// service control manager on computer named host.
+func ConnectRemote(host string) (*Mgr, error) {
+ var s *uint16
+ if host != "" {
+ s = syscall.StringToUTF16Ptr(host)
+ }
+ h, err := windows.OpenSCManager(s, nil, windows.SC_MANAGER_ALL_ACCESS)
+ if err != nil {
+ return nil, err
+ }
+ return &Mgr{Handle: h}, nil
+}
+
+// Disconnect closes connection to the service control manager m.
+func (m *Mgr) Disconnect() error {
+ return windows.CloseServiceHandle(m.Handle)
+}
+
+func toPtr(s string) *uint16 {
+ if len(s) == 0 {
+ return nil
+ }
+ return syscall.StringToUTF16Ptr(s)
+}
+
+// toStringBlock terminates strings in ss with 0, and then
+// concatenates them together. It also adds extra 0 at the end.
+func toStringBlock(ss []string) *uint16 {
+ if len(ss) == 0 {
+ return nil
+ }
+ t := ""
+ for _, s := range ss {
+ if s != "" {
+ t += s + "\x00"
+ }
+ }
+ if t == "" {
+ return nil
+ }
+ t += "\x00"
+ return &utf16.Encode([]rune(t))[0]
+}
+
+// CreateService installs new service name on the system.
+// The service will be executed by running exepath binary.
+// Use config c to specify service parameters.
+// Any args will be passed as command-line arguments when
+// the service is started; these arguments are distinct from
+// the arguments passed to Service.Start or via the "Start
+// parameters" field in the service's Properties dialog box.
+func (m *Mgr) CreateService(name, exepath string, c Config, args ...string) (*Service, error) {
+ if c.StartType == 0 {
+ c.StartType = StartManual
+ }
+ if c.ErrorControl == 0 {
+ c.ErrorControl = ErrorNormal
+ }
+ if c.ServiceType == 0 {
+ c.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS
+ }
+ s := syscall.EscapeArg(exepath)
+ for _, v := range args {
+ s += " " + syscall.EscapeArg(v)
+ }
+ h, err := windows.CreateService(m.Handle, toPtr(name), toPtr(c.DisplayName),
+ windows.SERVICE_ALL_ACCESS, c.ServiceType,
+ c.StartType, c.ErrorControl, toPtr(s), toPtr(c.LoadOrderGroup),
+ nil, toStringBlock(c.Dependencies), toPtr(c.ServiceStartName), toPtr(c.Password))
+ if err != nil {
+ return nil, err
+ }
+ if c.Description != "" {
+ err = updateDescription(h, c.Description)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return &Service{Name: name, Handle: h}, nil
+}
+
+// OpenService retrieves access to service name, so it can
+// be interrogated and controlled.
+func (m *Mgr) OpenService(name string) (*Service, error) {
+ h, err := windows.OpenService(m.Handle, syscall.StringToUTF16Ptr(name), windows.SERVICE_ALL_ACCESS)
+ if err != nil {
+ return nil, err
+ }
+ return &Service{Name: name, Handle: h}, nil
+}
+
+// ListServices enumerates services in the specified
+// service control manager database m.
+// If the caller does not have the SERVICE_QUERY_STATUS
+// access right to a service, the service is silently
+// omitted from the list of services returned.
+func (m *Mgr) ListServices() ([]string, error) {
+ var err error
+ var bytesNeeded, servicesReturned uint32
+ var buf []byte
+ for {
+ var p *byte
+ if len(buf) > 0 {
+ p = &buf[0]
+ }
+ err = windows.EnumServicesStatusEx(m.Handle, windows.SC_ENUM_PROCESS_INFO,
+ windows.SERVICE_WIN32, windows.SERVICE_STATE_ALL,
+ p, uint32(len(buf)), &bytesNeeded, &servicesReturned, nil, nil)
+ if err == nil {
+ break
+ }
+ if err != syscall.ERROR_MORE_DATA {
+ return nil, err
+ }
+ if bytesNeeded <= uint32(len(buf)) {
+ return nil, err
+ }
+ buf = make([]byte, bytesNeeded)
+ }
+ if servicesReturned == 0 {
+ return nil, nil
+ }
+ services := (*[1 << 20]windows.ENUM_SERVICE_STATUS_PROCESS)(unsafe.Pointer(&buf[0]))[:servicesReturned]
+ var names []string
+ for _, s := range services {
+ name := syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(s.ServiceName))[:])
+ names = append(names, name)
+ }
+ return names, nil
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/mgr/service.go b/vendor/golang.org/x/sys/windows/svc/mgr/service.go
new file mode 100644
index 0000000..fdc46af
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/mgr/service.go
@@ -0,0 +1,72 @@
+// 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 windows
+
+package mgr
+
+import (
+ "syscall"
+
+ "golang.org/x/sys/windows"
+ "golang.org/x/sys/windows/svc"
+)
+
+// TODO(brainman): Use EnumDependentServices to enumerate dependent services.
+
+// Service is used to access Windows service.
+type Service struct {
+ Name string
+ Handle windows.Handle
+}
+
+// Delete marks service s for deletion from the service control manager database.
+func (s *Service) Delete() error {
+ return windows.DeleteService(s.Handle)
+}
+
+// Close relinquish access to the service s.
+func (s *Service) Close() error {
+ return windows.CloseServiceHandle(s.Handle)
+}
+
+// Start starts service s.
+// args will be passed to svc.Handler.Execute.
+func (s *Service) Start(args ...string) error {
+ var p **uint16
+ if len(args) > 0 {
+ vs := make([]*uint16, len(args))
+ for i := range vs {
+ vs[i] = syscall.StringToUTF16Ptr(args[i])
+ }
+ p = &vs[0]
+ }
+ return windows.StartService(s.Handle, uint32(len(args)), p)
+}
+
+// Control sends state change request c to the servce s.
+func (s *Service) Control(c svc.Cmd) (svc.Status, error) {
+ var t windows.SERVICE_STATUS
+ err := windows.ControlService(s.Handle, uint32(c), &t)
+ if err != nil {
+ return svc.Status{}, err
+ }
+ return svc.Status{
+ State: svc.State(t.CurrentState),
+ Accepts: svc.Accepted(t.ControlsAccepted),
+ }, nil
+}
+
+// Query returns current status of service s.
+func (s *Service) Query() (svc.Status, error) {
+ var t windows.SERVICE_STATUS
+ err := windows.QueryServiceStatus(s.Handle, &t)
+ if err != nil {
+ return svc.Status{}, err
+ }
+ return svc.Status{
+ State: svc.State(t.CurrentState),
+ Accepts: svc.Accepted(t.ControlsAccepted),
+ }, nil
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/security.go b/vendor/golang.org/x/sys/windows/svc/security.go
new file mode 100644
index 0000000..6fbc923
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/security.go
@@ -0,0 +1,62 @@
+// 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 windows
+
+package svc
+
+import (
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+func allocSid(subAuth0 uint32) (*windows.SID, error) {
+ var sid *windows.SID
+ err := windows.AllocateAndInitializeSid(&windows.SECURITY_NT_AUTHORITY,
+ 1, subAuth0, 0, 0, 0, 0, 0, 0, 0, &sid)
+ if err != nil {
+ return nil, err
+ }
+ return sid, nil
+}
+
+// IsAnInteractiveSession determines if calling process is running interactively.
+// It queries the process token for membership in the Interactive group.
+// http://stackoverflow.com/questions/2668851/how-do-i-detect-that-my-application-is-running-as-service-or-in-an-interactive-s
+func IsAnInteractiveSession() (bool, error) {
+ interSid, err := allocSid(windows.SECURITY_INTERACTIVE_RID)
+ if err != nil {
+ return false, err
+ }
+ defer windows.FreeSid(interSid)
+
+ serviceSid, err := allocSid(windows.SECURITY_SERVICE_RID)
+ if err != nil {
+ return false, err
+ }
+ defer windows.FreeSid(serviceSid)
+
+ t, err := windows.OpenCurrentProcessToken()
+ if err != nil {
+ return false, err
+ }
+ defer t.Close()
+
+ gs, err := t.GetTokenGroups()
+ if err != nil {
+ return false, err
+ }
+ p := unsafe.Pointer(&gs.Groups[0])
+ groups := (*[2 << 20]windows.SIDAndAttributes)(p)[:gs.GroupCount]
+ for _, g := range groups {
+ if windows.EqualSid(g.Sid, interSid) {
+ return true, nil
+ }
+ if windows.EqualSid(g.Sid, serviceSid) {
+ return false, nil
+ }
+ }
+ return false, nil
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/service.go b/vendor/golang.org/x/sys/windows/svc/service.go
new file mode 100644
index 0000000..903cba3
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/service.go
@@ -0,0 +1,363 @@
+// 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 windows
+
+// Package svc provides everything required to build Windows service.
+//
+package svc
+
+import (
+ "errors"
+ "runtime"
+ "syscall"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+// State describes service execution state (Stopped, Running and so on).
+type State uint32
+
+const (
+ Stopped = State(windows.SERVICE_STOPPED)
+ StartPending = State(windows.SERVICE_START_PENDING)
+ StopPending = State(windows.SERVICE_STOP_PENDING)
+ Running = State(windows.SERVICE_RUNNING)
+ ContinuePending = State(windows.SERVICE_CONTINUE_PENDING)
+ PausePending = State(windows.SERVICE_PAUSE_PENDING)
+ Paused = State(windows.SERVICE_PAUSED)
+)
+
+// Cmd represents service state change request. It is sent to a service
+// by the service manager, and should be actioned upon by the service.
+type Cmd uint32
+
+const (
+ Stop = Cmd(windows.SERVICE_CONTROL_STOP)
+ Pause = Cmd(windows.SERVICE_CONTROL_PAUSE)
+ Continue = Cmd(windows.SERVICE_CONTROL_CONTINUE)
+ Interrogate = Cmd(windows.SERVICE_CONTROL_INTERROGATE)
+ Shutdown = Cmd(windows.SERVICE_CONTROL_SHUTDOWN)
+ ParamChange = Cmd(windows.SERVICE_CONTROL_PARAMCHANGE)
+ NetBindAdd = Cmd(windows.SERVICE_CONTROL_NETBINDADD)
+ NetBindRemove = Cmd(windows.SERVICE_CONTROL_NETBINDREMOVE)
+ NetBindEnable = Cmd(windows.SERVICE_CONTROL_NETBINDENABLE)
+ NetBindDisable = Cmd(windows.SERVICE_CONTROL_NETBINDDISABLE)
+ DeviceEvent = Cmd(windows.SERVICE_CONTROL_DEVICEEVENT)
+ HardwareProfileChange = Cmd(windows.SERVICE_CONTROL_HARDWAREPROFILECHANGE)
+ PowerEvent = Cmd(windows.SERVICE_CONTROL_POWEREVENT)
+ SessionChange = Cmd(windows.SERVICE_CONTROL_SESSIONCHANGE)
+)
+
+// Accepted is used to describe commands accepted by the service.
+// Note that Interrogate is always accepted.
+type Accepted uint32
+
+const (
+ AcceptStop = Accepted(windows.SERVICE_ACCEPT_STOP)
+ AcceptShutdown = Accepted(windows.SERVICE_ACCEPT_SHUTDOWN)
+ AcceptPauseAndContinue = Accepted(windows.SERVICE_ACCEPT_PAUSE_CONTINUE)
+ AcceptParamChange = Accepted(windows.SERVICE_ACCEPT_PARAMCHANGE)
+ AcceptNetBindChange = Accepted(windows.SERVICE_ACCEPT_NETBINDCHANGE)
+ AcceptHardwareProfileChange = Accepted(windows.SERVICE_ACCEPT_HARDWAREPROFILECHANGE)
+ AcceptPowerEvent = Accepted(windows.SERVICE_ACCEPT_POWEREVENT)
+ AcceptSessionChange = Accepted(windows.SERVICE_ACCEPT_SESSIONCHANGE)
+)
+
+// Status combines State and Accepted commands to fully describe running service.
+type Status struct {
+ State State
+ Accepts Accepted
+ CheckPoint uint32 // used to report progress during a lengthy operation
+ WaitHint uint32 // estimated time required for a pending operation, in milliseconds
+}
+
+// ChangeRequest is sent to the service Handler to request service status change.
+type ChangeRequest struct {
+ Cmd Cmd
+ EventType uint32
+ EventData uintptr
+ CurrentStatus Status
+}
+
+// Handler is the interface that must be implemented to build Windows service.
+type Handler interface {
+
+ // Execute will be called by the package code at the start of
+ // the service, and the service will exit once Execute completes.
+ // Inside Execute you must read service change requests from r and
+ // act accordingly. You must keep service control manager up to date
+ // about state of your service by writing into s as required.
+ // args contains service name followed by argument strings passed
+ // to the service.
+ // You can provide service exit code in exitCode return parameter,
+ // with 0 being "no error". You can also indicate if exit code,
+ // if any, is service specific or not by using svcSpecificEC
+ // parameter.
+ Execute(args []string, r <-chan ChangeRequest, s chan<- Status) (svcSpecificEC bool, exitCode uint32)
+}
+
+var (
+ // These are used by asm code.
+ goWaitsH uintptr
+ cWaitsH uintptr
+ ssHandle uintptr
+ sName *uint16
+ sArgc uintptr
+ sArgv **uint16
+ ctlHandlerExProc uintptr
+ cSetEvent uintptr
+ cWaitForSingleObject uintptr
+ cRegisterServiceCtrlHandlerExW uintptr
+)
+
+func init() {
+ k := syscall.MustLoadDLL("kernel32.dll")
+ cSetEvent = k.MustFindProc("SetEvent").Addr()
+ cWaitForSingleObject = k.MustFindProc("WaitForSingleObject").Addr()
+ a := syscall.MustLoadDLL("advapi32.dll")
+ cRegisterServiceCtrlHandlerExW = a.MustFindProc("RegisterServiceCtrlHandlerExW").Addr()
+}
+
+// The HandlerEx prototype also has a context pointer but since we don't use
+// it at start-up time we don't have to pass it over either.
+type ctlEvent struct {
+ cmd Cmd
+ eventType uint32
+ eventData uintptr
+ errno uint32
+}
+
+// service provides access to windows service api.
+type service struct {
+ name string
+ h windows.Handle
+ cWaits *event
+ goWaits *event
+ c chan ctlEvent
+ handler Handler
+}
+
+func newService(name string, handler Handler) (*service, error) {
+ var s service
+ var err error
+ s.name = name
+ s.c = make(chan ctlEvent)
+ s.handler = handler
+ s.cWaits, err = newEvent()
+ if err != nil {
+ return nil, err
+ }
+ s.goWaits, err = newEvent()
+ if err != nil {
+ s.cWaits.Close()
+ return nil, err
+ }
+ return &s, nil
+}
+
+func (s *service) close() error {
+ s.cWaits.Close()
+ s.goWaits.Close()
+ return nil
+}
+
+type exitCode struct {
+ isSvcSpecific bool
+ errno uint32
+}
+
+func (s *service) updateStatus(status *Status, ec *exitCode) error {
+ if s.h == 0 {
+ return errors.New("updateStatus with no service status handle")
+ }
+ var t windows.SERVICE_STATUS
+ t.ServiceType = windows.SERVICE_WIN32_OWN_PROCESS
+ t.CurrentState = uint32(status.State)
+ if status.Accepts&AcceptStop != 0 {
+ t.ControlsAccepted |= windows.SERVICE_ACCEPT_STOP
+ }
+ if status.Accepts&AcceptShutdown != 0 {
+ t.ControlsAccepted |= windows.SERVICE_ACCEPT_SHUTDOWN
+ }
+ if status.Accepts&AcceptPauseAndContinue != 0 {
+ t.ControlsAccepted |= windows.SERVICE_ACCEPT_PAUSE_CONTINUE
+ }
+ if status.Accepts&AcceptParamChange != 0 {
+ t.ControlsAccepted |= windows.SERVICE_ACCEPT_PARAMCHANGE
+ }
+ if status.Accepts&AcceptNetBindChange != 0 {
+ t.ControlsAccepted |= windows.SERVICE_ACCEPT_NETBINDCHANGE
+ }
+ if status.Accepts&AcceptHardwareProfileChange != 0 {
+ t.ControlsAccepted |= windows.SERVICE_ACCEPT_HARDWAREPROFILECHANGE
+ }
+ if status.Accepts&AcceptPowerEvent != 0 {
+ t.ControlsAccepted |= windows.SERVICE_ACCEPT_POWEREVENT
+ }
+ if status.Accepts&AcceptSessionChange != 0 {
+ t.ControlsAccepted |= windows.SERVICE_ACCEPT_SESSIONCHANGE
+ }
+ if ec.errno == 0 {
+ t.Win32ExitCode = windows.NO_ERROR
+ t.ServiceSpecificExitCode = windows.NO_ERROR
+ } else if ec.isSvcSpecific {
+ t.Win32ExitCode = uint32(windows.ERROR_SERVICE_SPECIFIC_ERROR)
+ t.ServiceSpecificExitCode = ec.errno
+ } else {
+ t.Win32ExitCode = ec.errno
+ t.ServiceSpecificExitCode = windows.NO_ERROR
+ }
+ t.CheckPoint = status.CheckPoint
+ t.WaitHint = status.WaitHint
+ return windows.SetServiceStatus(s.h, &t)
+}
+
+const (
+ sysErrSetServiceStatusFailed = uint32(syscall.APPLICATION_ERROR) + iota
+ sysErrNewThreadInCallback
+)
+
+func (s *service) run() {
+ s.goWaits.Wait()
+ s.h = windows.Handle(ssHandle)
+ argv := (*[100]*int16)(unsafe.Pointer(sArgv))[:sArgc]
+ args := make([]string, len(argv))
+ for i, a := range argv {
+ args[i] = syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(a))[:])
+ }
+
+ cmdsToHandler := make(chan ChangeRequest)
+ changesFromHandler := make(chan Status)
+ exitFromHandler := make(chan exitCode)
+
+ go func() {
+ ss, errno := s.handler.Execute(args, cmdsToHandler, changesFromHandler)
+ exitFromHandler <- exitCode{ss, errno}
+ }()
+
+ status := Status{State: Stopped}
+ ec := exitCode{isSvcSpecific: true, errno: 0}
+ var outch chan ChangeRequest
+ inch := s.c
+ var cmd Cmd
+ var evtype uint32
+ var evdata uintptr
+loop:
+ for {
+ select {
+ case r := <-inch:
+ if r.errno != 0 {
+ ec.errno = r.errno
+ break loop
+ }
+ inch = nil
+ outch = cmdsToHandler
+ cmd = r.cmd
+ evtype = r.eventType
+ evdata = r.eventData
+ case outch <- ChangeRequest{cmd, evtype, evdata, status}:
+ inch = s.c
+ outch = nil
+ case c := <-changesFromHandler:
+ err := s.updateStatus(&c, &ec)
+ if err != nil {
+ // best suitable error number
+ ec.errno = sysErrSetServiceStatusFailed
+ if err2, ok := err.(syscall.Errno); ok {
+ ec.errno = uint32(err2)
+ }
+ break loop
+ }
+ status = c
+ case ec = <-exitFromHandler:
+ break loop
+ }
+ }
+
+ s.updateStatus(&Status{State: Stopped}, &ec)
+ s.cWaits.Set()
+}
+
+func newCallback(fn interface{}) (cb uintptr, err error) {
+ defer func() {
+ r := recover()
+ if r == nil {
+ return
+ }
+ cb = 0
+ switch v := r.(type) {
+ case string:
+ err = errors.New(v)
+ case error:
+ err = v
+ default:
+ err = errors.New("unexpected panic in syscall.NewCallback")
+ }
+ }()
+ return syscall.NewCallback(fn), nil
+}
+
+// BUG(brainman): There is no mechanism to run multiple services
+// inside one single executable. Perhaps, it can be overcome by
+// using RegisterServiceCtrlHandlerEx Windows api.
+
+// Run executes service name by calling appropriate handler function.
+func Run(name string, handler Handler) error {
+ runtime.LockOSThread()
+
+ tid := windows.GetCurrentThreadId()
+
+ s, err := newService(name, handler)
+ if err != nil {
+ return err
+ }
+
+ ctlHandler := func(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr {
+ e := ctlEvent{cmd: Cmd(ctl), eventType: evtype, eventData: evdata}
+ // We assume that this callback function is running on
+ // the same thread as Run. Nowhere in MS documentation
+ // I could find statement to guarantee that. So putting
+ // check here to verify, otherwise things will go bad
+ // quickly, if ignored.
+ i := windows.GetCurrentThreadId()
+ if i != tid {
+ e.errno = sysErrNewThreadInCallback
+ }
+ s.c <- e
+ // Always return NO_ERROR (0) for now.
+ return 0
+ }
+
+ var svcmain uintptr
+ getServiceMain(&svcmain)
+ t := []windows.SERVICE_TABLE_ENTRY{
+ {syscall.StringToUTF16Ptr(s.name), svcmain},
+ {nil, 0},
+ }
+
+ goWaitsH = uintptr(s.goWaits.h)
+ cWaitsH = uintptr(s.cWaits.h)
+ sName = t[0].ServiceName
+ ctlHandlerExProc, err = newCallback(ctlHandler)
+ if err != nil {
+ return err
+ }
+
+ go s.run()
+
+ err = windows.StartServiceCtrlDispatcher(&t[0])
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+// StatusHandle returns service status handle. It is safe to call this function
+// from inside the Handler.Execute because then it is guaranteed to be set.
+// This code will have to change once multiple services are possible per process.
+func StatusHandle() windows.Handle {
+ return windows.Handle(ssHandle)
+}
diff --git a/vendor/golang.org/x/sys/windows/svc/sys_386.s b/vendor/golang.org/x/sys/windows/svc/sys_386.s
new file mode 100644
index 0000000..2c82a9d
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/sys_386.s
@@ -0,0 +1,68 @@
+// 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 windows
+
+// func servicemain(argc uint32, argv **uint16)
+TEXT ·servicemain(SB),7,$0
+ MOVL argc+0(FP), AX
+ MOVL AX, ·sArgc(SB)
+ MOVL argv+4(FP), AX
+ MOVL AX, ·sArgv(SB)
+
+ PUSHL BP
+ PUSHL BX
+ PUSHL SI
+ PUSHL DI
+
+ SUBL $12, SP
+
+ MOVL ·sName(SB), AX
+ MOVL AX, (SP)
+ MOVL $·servicectlhandler(SB), AX
+ MOVL AX, 4(SP)
+ MOVL $0, 8(SP)
+ MOVL ·cRegisterServiceCtrlHandlerExW(SB), AX
+ MOVL SP, BP
+ CALL AX
+ MOVL BP, SP
+ CMPL AX, $0
+ JE exit
+ MOVL AX, ·ssHandle(SB)
+
+ MOVL ·goWaitsH(SB), AX
+ MOVL AX, (SP)
+ MOVL ·cSetEvent(SB), AX
+ MOVL SP, BP
+ CALL AX
+ MOVL BP, SP
+
+ MOVL ·cWaitsH(SB), AX
+ MOVL AX, (SP)
+ MOVL $-1, AX
+ MOVL AX, 4(SP)
+ MOVL ·cWaitForSingleObject(SB), AX
+ MOVL SP, BP
+ CALL AX
+ MOVL BP, SP
+
+exit:
+ ADDL $12, SP
+
+ POPL DI
+ POPL SI
+ POPL BX
+ POPL BP
+
+ MOVL 0(SP), CX
+ ADDL $12, SP
+ JMP CX
+
+// I do not know why, but this seems to be the only way to call
+// ctlHandlerProc on Windows 7.
+
+// func servicectlhandler(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr {
+TEXT ·servicectlhandler(SB),7,$0
+ MOVL ·ctlHandlerExProc(SB), CX
+ JMP CX
diff --git a/vendor/golang.org/x/sys/windows/svc/sys_amd64.s b/vendor/golang.org/x/sys/windows/svc/sys_amd64.s
new file mode 100644
index 0000000..06b4259
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/svc/sys_amd64.s
@@ -0,0 +1,42 @@
+// 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 windows
+
+// func servicemain(argc uint32, argv **uint16)
+TEXT ·servicemain(SB),7,$0
+ MOVL CX, ·sArgc(SB)
+ MOVL DX, ·sArgv(SB)
+
+ SUBQ $32, SP // stack for the first 4 syscall params
+
+ MOVQ ·sName(SB), CX
+ MOVQ $·servicectlhandler(SB), DX
+ // BUG(pastarmovj): Figure out a way to pass in context in R8.
+ MOVQ ·cRegisterServiceCtrlHandlerExW(SB), AX
+ CALL AX
+ CMPQ AX, $0
+ JE exit
+ MOVQ AX, ·ssHandle(SB)
+
+ MOVQ ·goWaitsH(SB), CX
+ MOVQ ·cSetEvent(SB), AX
+ CALL AX
+
+ MOVQ ·cWaitsH(SB), CX
+ MOVQ $4294967295, DX
+ MOVQ ·cWaitForSingleObject(SB), AX
+ CALL AX
+
+exit:
+ ADDQ $32, SP
+ RET
+
+// I do not know why, but this seems to be the only way to call
+// ctlHandlerProc on Windows 7.
+
+// func ·servicectlhandler(ctl uint32, evtype uint32, evdata uintptr, context uintptr) uintptr {
+TEXT ·servicectlhandler(SB),7,$0
+ MOVQ ·ctlHandlerExProc(SB), AX
+ JMP AX
diff --git a/vendor/golang.org/x/sys/windows/syscall.go b/vendor/golang.org/x/sys/windows/syscall.go
new file mode 100644
index 0000000..4e2fbe8
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/syscall.go
@@ -0,0 +1,71 @@
+// Copyright 2009 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 windows
+
+// Package windows contains an interface to the low-level operating system
+// primitives. OS details vary depending on the underlying system, and
+// by default, godoc will display the OS-specific documentation for the current
+// system. If you want godoc to display syscall documentation for another
+// system, set $GOOS and $GOARCH to the desired system. For example, if
+// you want to view documentation for freebsd/arm on linux/amd64, set $GOOS
+// to freebsd and $GOARCH to arm.
+// The primary use of this package is inside other packages that provide a more
+// portable interface to the system, such as "os", "time" and "net". Use
+// those packages rather than this one if you can.
+// For details of the functions and data types in this package consult
+// the manuals for the appropriate operating system.
+// These calls return err == nil to indicate success; otherwise
+// err represents an operating system error describing the failure and
+// holds a value of type syscall.Errno.
+package windows // import "golang.org/x/sys/windows"
+
+import (
+ "syscall"
+)
+
+// ByteSliceFromString returns a NUL-terminated slice of bytes
+// containing the text of s. If s contains a NUL byte at any
+// location, it returns (nil, syscall.EINVAL).
+func ByteSliceFromString(s string) ([]byte, error) {
+ for i := 0; i < len(s); i++ {
+ if s[i] == 0 {
+ return nil, syscall.EINVAL
+ }
+ }
+ a := make([]byte, len(s)+1)
+ copy(a, s)
+ return a, nil
+}
+
+// BytePtrFromString returns a pointer to a NUL-terminated array of
+// bytes containing the text of s. If s contains a NUL byte at any
+// location, it returns (nil, syscall.EINVAL).
+func BytePtrFromString(s string) (*byte, error) {
+ a, err := ByteSliceFromString(s)
+ if err != nil {
+ return nil, err
+ }
+ return &a[0], nil
+}
+
+// Single-word zero for use when we need a valid pointer to 0 bytes.
+// See mksyscall.pl.
+var _zero uintptr
+
+func (ts *Timespec) Unix() (sec int64, nsec int64) {
+ return int64(ts.Sec), int64(ts.Nsec)
+}
+
+func (tv *Timeval) Unix() (sec int64, nsec int64) {
+ return int64(tv.Sec), int64(tv.Usec) * 1000
+}
+
+func (ts *Timespec) Nano() int64 {
+ return int64(ts.Sec)*1e9 + int64(ts.Nsec)
+}
+
+func (tv *Timeval) Nano() int64 {
+ return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000
+}
diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go
new file mode 100644
index 0000000..c7ff24b
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/syscall_windows.go
@@ -0,0 +1,1004 @@
+// Copyright 2009 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.
+
+// Windows system calls.
+
+package windows
+
+import (
+ errorspkg "errors"
+ "sync"
+ "syscall"
+ "unicode/utf16"
+ "unsafe"
+)
+
+type Handle uintptr
+
+const InvalidHandle = ^Handle(0)
+
+// StringToUTF16 is deprecated. Use UTF16FromString instead.
+// If s contains a NUL byte this function panics instead of
+// returning an error.
+func StringToUTF16(s string) []uint16 {
+ a, err := UTF16FromString(s)
+ if err != nil {
+ panic("windows: string with NUL passed to StringToUTF16")
+ }
+ return a
+}
+
+// UTF16FromString returns the UTF-16 encoding of the UTF-8 string
+// s, with a terminating NUL added. If s contains a NUL byte at any
+// location, it returns (nil, syscall.EINVAL).
+func UTF16FromString(s string) ([]uint16, error) {
+ for i := 0; i < len(s); i++ {
+ if s[i] == 0 {
+ return nil, syscall.EINVAL
+ }
+ }
+ return utf16.Encode([]rune(s + "\x00")), nil
+}
+
+// UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
+// with a terminating NUL removed.
+func UTF16ToString(s []uint16) string {
+ for i, v := range s {
+ if v == 0 {
+ s = s[0:i]
+ break
+ }
+ }
+ return string(utf16.Decode(s))
+}
+
+// StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead.
+// If s contains a NUL byte this function panics instead of
+// returning an error.
+func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] }
+
+// UTF16PtrFromString returns pointer to the UTF-16 encoding of
+// the UTF-8 string s, with a terminating NUL added. If s
+// contains a NUL byte at any location, it returns (nil, syscall.EINVAL).
+func UTF16PtrFromString(s string) (*uint16, error) {
+ a, err := UTF16FromString(s)
+ if err != nil {
+ return nil, err
+ }
+ return &a[0], nil
+}
+
+func Getpagesize() int { return 4096 }
+
+// Converts a Go function to a function pointer conforming
+// to the stdcall or cdecl calling convention. This is useful when
+// interoperating with Windows code requiring callbacks.
+// Implemented in runtime/syscall_windows.goc
+func NewCallback(fn interface{}) uintptr
+func NewCallbackCDecl(fn interface{}) uintptr
+
+// windows api calls
+
+//sys GetLastError() (lasterr error)
+//sys LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW
+//sys LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) = LoadLibraryExW
+//sys FreeLibrary(handle Handle) (err error)
+//sys GetProcAddress(module Handle, procname string) (proc uintptr, err error)
+//sys GetVersion() (ver uint32, err error)
+//sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW
+//sys ExitProcess(exitcode uint32)
+//sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile int32) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW
+//sys ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)
+//sys WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)
+//sys SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff]
+//sys CloseHandle(handle Handle) (err error)
+//sys GetStdHandle(stdhandle uint32) (handle Handle, err error) [failretval==InvalidHandle]
+//sys SetStdHandle(stdhandle uint32, handle Handle) (err error)
+//sys findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW
+//sys findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW
+//sys FindClose(handle Handle) (err error)
+//sys GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error)
+//sys GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW
+//sys SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW
+//sys CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW
+//sys RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW
+//sys DeleteFile(path *uint16) (err error) = DeleteFileW
+//sys MoveFile(from *uint16, to *uint16) (err error) = MoveFileW
+//sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW
+//sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW
+//sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW
+//sys SetEndOfFile(handle Handle) (err error)
+//sys GetSystemTimeAsFileTime(time *Filetime)
+//sys GetSystemTimePreciseAsFileTime(time *Filetime)
+//sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff]
+//sys CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (handle Handle, err error)
+//sys GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) (err error)
+//sys PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) (err error)
+//sys CancelIo(s Handle) (err error)
+//sys CancelIoEx(s Handle, o *Overlapped) (err error)
+//sys CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = CreateProcessW
+//sys OpenProcess(da uint32, inheritHandle bool, pid uint32) (handle Handle, err error)
+//sys TerminateProcess(handle Handle, exitcode uint32) (err error)
+//sys GetExitCodeProcess(handle Handle, exitcode *uint32) (err error)
+//sys GetStartupInfo(startupInfo *StartupInfo) (err error) = GetStartupInfoW
+//sys GetCurrentProcess() (pseudoHandle Handle, err error)
+//sys GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error)
+//sys DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error)
+//sys WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff]
+//sys GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW
+//sys CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error)
+//sys GetFileType(filehandle Handle) (n uint32, err error)
+//sys CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW
+//sys CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext
+//sys CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom
+//sys GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW
+//sys FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW
+//sys GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW
+//sys SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW
+//sys SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)
+//sys GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW
+//sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW
+//sys GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW
+//sys GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW
+//sys CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW
+//sys LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0]
+//sys SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error)
+//sys FlushFileBuffers(handle Handle) (err error)
+//sys GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW
+//sys GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW
+//sys GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW
+//sys CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) = kernel32.CreateFileMappingW
+//sys MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error)
+//sys UnmapViewOfFile(addr uintptr) (err error)
+//sys FlushViewOfFile(addr uintptr, length uintptr) (err error)
+//sys VirtualLock(addr uintptr, length uintptr) (err error)
+//sys VirtualUnlock(addr uintptr, length uintptr) (err error)
+//sys VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) = kernel32.VirtualAlloc
+//sys VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) = kernel32.VirtualFree
+//sys VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) = kernel32.VirtualProtect
+//sys TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile
+//sys ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW
+//sys CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW
+//sys CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) [failretval==InvalidHandle] = crypt32.CertOpenStore
+//sys CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore
+//sys CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore
+//sys CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore
+//sys CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain
+//sys CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain
+//sys CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext
+//sys CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext
+//sys CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy
+//sys RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW
+//sys RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey
+//sys RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegQueryInfoKeyW
+//sys RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW
+//sys RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW
+//sys getCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId
+//sys GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode
+//sys SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode
+//sys GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo
+//sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW
+//sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW
+//sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot
+//sys Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW
+//sys Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW
+//sys DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error)
+// This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
+//sys CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW
+//sys CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW
+//sys GetCurrentThreadId() (id uint32)
+//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) = kernel32.CreateEventW
+//sys CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) = kernel32.CreateEventExW
+//sys OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenEventW
+//sys SetEvent(event Handle) (err error) = kernel32.SetEvent
+//sys ResetEvent(event Handle) (err error) = kernel32.ResetEvent
+//sys PulseEvent(event Handle) (err error) = kernel32.PulseEvent
+
+// syscall interface implementation for other packages
+
+func Exit(code int) { ExitProcess(uint32(code)) }
+
+func makeInheritSa() *SecurityAttributes {
+ var sa SecurityAttributes
+ sa.Length = uint32(unsafe.Sizeof(sa))
+ sa.InheritHandle = 1
+ return &sa
+}
+
+func Open(path string, mode int, perm uint32) (fd Handle, err error) {
+ if len(path) == 0 {
+ return InvalidHandle, ERROR_FILE_NOT_FOUND
+ }
+ pathp, err := UTF16PtrFromString(path)
+ if err != nil {
+ return InvalidHandle, err
+ }
+ var access uint32
+ switch mode & (O_RDONLY | O_WRONLY | O_RDWR) {
+ case O_RDONLY:
+ access = GENERIC_READ
+ case O_WRONLY:
+ access = GENERIC_WRITE
+ case O_RDWR:
+ access = GENERIC_READ | GENERIC_WRITE
+ }
+ if mode&O_CREAT != 0 {
+ access |= GENERIC_WRITE
+ }
+ if mode&O_APPEND != 0 {
+ access &^= GENERIC_WRITE
+ access |= FILE_APPEND_DATA
+ }
+ sharemode := uint32(FILE_SHARE_READ | FILE_SHARE_WRITE)
+ var sa *SecurityAttributes
+ if mode&O_CLOEXEC == 0 {
+ sa = makeInheritSa()
+ }
+ var createmode uint32
+ switch {
+ case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL):
+ createmode = CREATE_NEW
+ case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC):
+ createmode = CREATE_ALWAYS
+ case mode&O_CREAT == O_CREAT:
+ createmode = OPEN_ALWAYS
+ case mode&O_TRUNC == O_TRUNC:
+ createmode = TRUNCATE_EXISTING
+ default:
+ createmode = OPEN_EXISTING
+ }
+ h, e := CreateFile(pathp, access, sharemode, sa, createmode, FILE_ATTRIBUTE_NORMAL, 0)
+ return h, e
+}
+
+func Read(fd Handle, p []byte) (n int, err error) {
+ var done uint32
+ e := ReadFile(fd, p, &done, nil)
+ if e != nil {
+ if e == ERROR_BROKEN_PIPE {
+ // NOTE(brainman): work around ERROR_BROKEN_PIPE is returned on reading EOF from stdin
+ return 0, nil
+ }
+ return 0, e
+ }
+ if raceenabled {
+ if done > 0 {
+ raceWriteRange(unsafe.Pointer(&p[0]), int(done))
+ }
+ raceAcquire(unsafe.Pointer(&ioSync))
+ }
+ return int(done), nil
+}
+
+func Write(fd Handle, p []byte) (n int, err error) {
+ if raceenabled {
+ raceReleaseMerge(unsafe.Pointer(&ioSync))
+ }
+ var done uint32
+ e := WriteFile(fd, p, &done, nil)
+ if e != nil {
+ return 0, e
+ }
+ if raceenabled && done > 0 {
+ raceReadRange(unsafe.Pointer(&p[0]), int(done))
+ }
+ return int(done), nil
+}
+
+var ioSync int64
+
+func Seek(fd Handle, offset int64, whence int) (newoffset int64, err error) {
+ var w uint32
+ switch whence {
+ case 0:
+ w = FILE_BEGIN
+ case 1:
+ w = FILE_CURRENT
+ case 2:
+ w = FILE_END
+ }
+ hi := int32(offset >> 32)
+ lo := int32(offset)
+ // use GetFileType to check pipe, pipe can't do seek
+ ft, _ := GetFileType(fd)
+ if ft == FILE_TYPE_PIPE {
+ return 0, syscall.EPIPE
+ }
+ rlo, e := SetFilePointer(fd, lo, &hi, w)
+ if e != nil {
+ return 0, e
+ }
+ return int64(hi)<<32 + int64(rlo), nil
+}
+
+func Close(fd Handle) (err error) {
+ return CloseHandle(fd)
+}
+
+var (
+ Stdin = getStdHandle(STD_INPUT_HANDLE)
+ Stdout = getStdHandle(STD_OUTPUT_HANDLE)
+ Stderr = getStdHandle(STD_ERROR_HANDLE)
+)
+
+func getStdHandle(stdhandle uint32) (fd Handle) {
+ r, _ := GetStdHandle(stdhandle)
+ CloseOnExec(r)
+ return r
+}
+
+const ImplementsGetwd = true
+
+func Getwd() (wd string, err error) {
+ b := make([]uint16, 300)
+ n, e := GetCurrentDirectory(uint32(len(b)), &b[0])
+ if e != nil {
+ return "", e
+ }
+ return string(utf16.Decode(b[0:n])), nil
+}
+
+func Chdir(path string) (err error) {
+ pathp, err := UTF16PtrFromString(path)
+ if err != nil {
+ return err
+ }
+ return SetCurrentDirectory(pathp)
+}
+
+func Mkdir(path string, mode uint32) (err error) {
+ pathp, err := UTF16PtrFromString(path)
+ if err != nil {
+ return err
+ }
+ return CreateDirectory(pathp, nil)
+}
+
+func Rmdir(path string) (err error) {
+ pathp, err := UTF16PtrFromString(path)
+ if err != nil {
+ return err
+ }
+ return RemoveDirectory(pathp)
+}
+
+func Unlink(path string) (err error) {
+ pathp, err := UTF16PtrFromString(path)
+ if err != nil {
+ return err
+ }
+ return DeleteFile(pathp)
+}
+
+func Rename(oldpath, newpath string) (err error) {
+ from, err := UTF16PtrFromString(oldpath)
+ if err != nil {
+ return err
+ }
+ to, err := UTF16PtrFromString(newpath)
+ if err != nil {
+ return err
+ }
+ return MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING)
+}
+
+func ComputerName() (name string, err error) {
+ var n uint32 = MAX_COMPUTERNAME_LENGTH + 1
+ b := make([]uint16, n)
+ e := GetComputerName(&b[0], &n)
+ if e != nil {
+ return "", e
+ }
+ return string(utf16.Decode(b[0:n])), nil
+}
+
+func Ftruncate(fd Handle, length int64) (err error) {
+ curoffset, e := Seek(fd, 0, 1)
+ if e != nil {
+ return e
+ }
+ defer Seek(fd, curoffset, 0)
+ _, e = Seek(fd, length, 0)
+ if e != nil {
+ return e
+ }
+ e = SetEndOfFile(fd)
+ if e != nil {
+ return e
+ }
+ return nil
+}
+
+func Gettimeofday(tv *Timeval) (err error) {
+ var ft Filetime
+ GetSystemTimeAsFileTime(&ft)
+ *tv = NsecToTimeval(ft.Nanoseconds())
+ return nil
+}
+
+func Pipe(p []Handle) (err error) {
+ if len(p) != 2 {
+ return syscall.EINVAL
+ }
+ var r, w Handle
+ e := CreatePipe(&r, &w, makeInheritSa(), 0)
+ if e != nil {
+ return e
+ }
+ p[0] = r
+ p[1] = w
+ return nil
+}
+
+func Utimes(path string, tv []Timeval) (err error) {
+ if len(tv) != 2 {
+ return syscall.EINVAL
+ }
+ pathp, e := UTF16PtrFromString(path)
+ if e != nil {
+ return e
+ }
+ h, e := CreateFile(pathp,
+ FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
+ OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
+ if e != nil {
+ return e
+ }
+ defer Close(h)
+ a := NsecToFiletime(tv[0].Nanoseconds())
+ w := NsecToFiletime(tv[1].Nanoseconds())
+ return SetFileTime(h, nil, &a, &w)
+}
+
+func UtimesNano(path string, ts []Timespec) (err error) {
+ if len(ts) != 2 {
+ return syscall.EINVAL
+ }
+ pathp, e := UTF16PtrFromString(path)
+ if e != nil {
+ return e
+ }
+ h, e := CreateFile(pathp,
+ FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, nil,
+ OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
+ if e != nil {
+ return e
+ }
+ defer Close(h)
+ a := NsecToFiletime(TimespecToNsec(ts[0]))
+ w := NsecToFiletime(TimespecToNsec(ts[1]))
+ return SetFileTime(h, nil, &a, &w)
+}
+
+func Fsync(fd Handle) (err error) {
+ return FlushFileBuffers(fd)
+}
+
+func Chmod(path string, mode uint32) (err error) {
+ if mode == 0 {
+ return syscall.EINVAL
+ }
+ p, e := UTF16PtrFromString(path)
+ if e != nil {
+ return e
+ }
+ attrs, e := GetFileAttributes(p)
+ if e != nil {
+ return e
+ }
+ if mode&S_IWRITE != 0 {
+ attrs &^= FILE_ATTRIBUTE_READONLY
+ } else {
+ attrs |= FILE_ATTRIBUTE_READONLY
+ }
+ return SetFileAttributes(p, attrs)
+}
+
+func LoadGetSystemTimePreciseAsFileTime() error {
+ return procGetSystemTimePreciseAsFileTime.Find()
+}
+
+func LoadCancelIoEx() error {
+ return procCancelIoEx.Find()
+}
+
+func LoadSetFileCompletionNotificationModes() error {
+ return procSetFileCompletionNotificationModes.Find()
+}
+
+// net api calls
+
+const socket_error = uintptr(^uint32(0))
+
+//sys WSAStartup(verreq uint32, data *WSAData) (sockerr error) = ws2_32.WSAStartup
+//sys WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup
+//sys WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) [failretval==socket_error] = ws2_32.WSAIoctl
+//sys socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket
+//sys Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt
+//sys Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt
+//sys bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind
+//sys connect(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.connect
+//sys getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockname
+//sys getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) [failretval==socket_error] = ws2_32.getpeername
+//sys listen(s Handle, backlog int32) (err error) [failretval==socket_error] = ws2_32.listen
+//sys shutdown(s Handle, how int32) (err error) [failretval==socket_error] = ws2_32.shutdown
+//sys Closesocket(s Handle) (err error) [failretval==socket_error] = ws2_32.closesocket
+//sys AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) = mswsock.AcceptEx
+//sys GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) = mswsock.GetAcceptExSockaddrs
+//sys WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecv
+//sys WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASend
+//sys WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSARecvFrom
+//sys WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error) [failretval==socket_error] = ws2_32.WSASendTo
+//sys GetHostByName(name string) (h *Hostent, err error) [failretval==nil] = ws2_32.gethostbyname
+//sys GetServByName(name string, proto string) (s *Servent, err error) [failretval==nil] = ws2_32.getservbyname
+//sys Ntohs(netshort uint16) (u uint16) = ws2_32.ntohs
+//sys GetProtoByName(name string) (p *Protoent, err error) [failretval==nil] = ws2_32.getprotobyname
+//sys DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) = dnsapi.DnsQuery_W
+//sys DnsRecordListFree(rl *DNSRecord, freetype uint32) = dnsapi.DnsRecordListFree
+//sys DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) = dnsapi.DnsNameCompare_W
+//sys GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) = ws2_32.GetAddrInfoW
+//sys FreeAddrInfoW(addrinfo *AddrinfoW) = ws2_32.FreeAddrInfoW
+//sys GetIfEntry(pIfRow *MibIfRow) (errcode error) = iphlpapi.GetIfEntry
+//sys GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) = iphlpapi.GetAdaptersInfo
+//sys SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) = kernel32.SetFileCompletionNotificationModes
+//sys WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) [failretval==-1] = ws2_32.WSAEnumProtocolsW
+//sys GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) = iphlpapi.GetAdaptersAddresses
+//sys GetACP() (acp uint32) = kernel32.GetACP
+//sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar
+
+// For testing: clients can set this flag to force
+// creation of IPv6 sockets to return EAFNOSUPPORT.
+var SocketDisableIPv6 bool
+
+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 RawSockaddr struct {
+ Family uint16
+ Data [14]int8
+}
+
+type RawSockaddrAny struct {
+ Addr RawSockaddr
+ Pad [96]int8
+}
+
+type Sockaddr interface {
+ sockaddr() (ptr unsafe.Pointer, len int32, err error) // lowercase; only we can define Sockaddrs
+}
+
+type SockaddrInet4 struct {
+ Port int
+ Addr [4]byte
+ raw RawSockaddrInet4
+}
+
+func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, int32, error) {
+ if sa.Port < 0 || sa.Port > 0xFFFF {
+ return nil, 0, syscall.EINVAL
+ }
+ sa.raw.Family = AF_INET
+ p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
+ p[0] = byte(sa.Port >> 8)
+ p[1] = byte(sa.Port)
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.raw.Addr[i] = sa.Addr[i]
+ }
+ return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
+}
+
+type SockaddrInet6 struct {
+ Port int
+ ZoneId uint32
+ Addr [16]byte
+ raw RawSockaddrInet6
+}
+
+func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, int32, error) {
+ if sa.Port < 0 || sa.Port > 0xFFFF {
+ return nil, 0, syscall.EINVAL
+ }
+ sa.raw.Family = AF_INET6
+ p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
+ p[0] = byte(sa.Port >> 8)
+ p[1] = byte(sa.Port)
+ sa.raw.Scope_id = sa.ZoneId
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.raw.Addr[i] = sa.Addr[i]
+ }
+ return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil
+}
+
+type SockaddrUnix struct {
+ Name string
+}
+
+func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) {
+ // TODO(brainman): implement SockaddrUnix.sockaddr()
+ return nil, 0, syscall.EWINDOWS
+}
+
+func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) {
+ switch rsa.Addr.Family {
+ case AF_UNIX:
+ return nil, syscall.EWINDOWS
+
+ case AF_INET:
+ pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
+ sa := new(SockaddrInet4)
+ p := (*[2]byte)(unsafe.Pointer(&pp.Port))
+ sa.Port = int(p[0])<<8 + int(p[1])
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.Addr[i] = pp.Addr[i]
+ }
+ return sa, nil
+
+ case AF_INET6:
+ pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
+ sa := new(SockaddrInet6)
+ p := (*[2]byte)(unsafe.Pointer(&pp.Port))
+ sa.Port = int(p[0])<<8 + int(p[1])
+ sa.ZoneId = pp.Scope_id
+ for i := 0; i < len(sa.Addr); i++ {
+ sa.Addr[i] = pp.Addr[i]
+ }
+ return sa, nil
+ }
+ return nil, syscall.EAFNOSUPPORT
+}
+
+func Socket(domain, typ, proto int) (fd Handle, err error) {
+ if domain == AF_INET6 && SocketDisableIPv6 {
+ return InvalidHandle, syscall.EAFNOSUPPORT
+ }
+ return socket(int32(domain), int32(typ), int32(proto))
+}
+
+func SetsockoptInt(fd Handle, level, opt int, value int) (err error) {
+ v := int32(value)
+ return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&v)), int32(unsafe.Sizeof(v)))
+}
+
+func Bind(fd Handle, sa Sockaddr) (err error) {
+ ptr, n, err := sa.sockaddr()
+ if err != nil {
+ return err
+ }
+ return bind(fd, ptr, n)
+}
+
+func Connect(fd Handle, sa Sockaddr) (err error) {
+ ptr, n, err := sa.sockaddr()
+ if err != nil {
+ return err
+ }
+ return connect(fd, ptr, n)
+}
+
+func Getsockname(fd Handle) (sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ l := int32(unsafe.Sizeof(rsa))
+ if err = getsockname(fd, &rsa, &l); err != nil {
+ return
+ }
+ return rsa.Sockaddr()
+}
+
+func Getpeername(fd Handle) (sa Sockaddr, err error) {
+ var rsa RawSockaddrAny
+ l := int32(unsafe.Sizeof(rsa))
+ if err = getpeername(fd, &rsa, &l); err != nil {
+ return
+ }
+ return rsa.Sockaddr()
+}
+
+func Listen(s Handle, n int) (err error) {
+ return listen(s, int32(n))
+}
+
+func Shutdown(fd Handle, how int) (err error) {
+ return shutdown(fd, int32(how))
+}
+
+func WSASendto(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to Sockaddr, overlapped *Overlapped, croutine *byte) (err error) {
+ rsa, l, err := to.sockaddr()
+ if err != nil {
+ return err
+ }
+ return WSASendTo(s, bufs, bufcnt, sent, flags, (*RawSockaddrAny)(unsafe.Pointer(rsa)), l, overlapped, croutine)
+}
+
+func LoadGetAddrInfo() error {
+ return procGetAddrInfoW.Find()
+}
+
+var connectExFunc struct {
+ once sync.Once
+ addr uintptr
+ err error
+}
+
+func LoadConnectEx() error {
+ connectExFunc.once.Do(func() {
+ var s Handle
+ s, connectExFunc.err = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
+ if connectExFunc.err != nil {
+ return
+ }
+ defer CloseHandle(s)
+ var n uint32
+ connectExFunc.err = WSAIoctl(s,
+ SIO_GET_EXTENSION_FUNCTION_POINTER,
+ (*byte)(unsafe.Pointer(&WSAID_CONNECTEX)),
+ uint32(unsafe.Sizeof(WSAID_CONNECTEX)),
+ (*byte)(unsafe.Pointer(&connectExFunc.addr)),
+ uint32(unsafe.Sizeof(connectExFunc.addr)),
+ &n, nil, 0)
+ })
+ return connectExFunc.err
+}
+
+func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) {
+ r1, _, e1 := syscall.Syscall9(connectExFunc.addr, 7, uintptr(s), uintptr(name), uintptr(namelen), uintptr(unsafe.Pointer(sendBuf)), uintptr(sendDataLen), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = error(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ConnectEx(fd Handle, sa Sockaddr, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) error {
+ err := LoadConnectEx()
+ if err != nil {
+ return errorspkg.New("failed to find ConnectEx: " + err.Error())
+ }
+ ptr, n, err := sa.sockaddr()
+ if err != nil {
+ return err
+ }
+ return connectEx(fd, ptr, n, sendBuf, sendDataLen, bytesSent, overlapped)
+}
+
+// Invented structures to support what package os expects.
+type Rusage struct {
+ CreationTime Filetime
+ ExitTime Filetime
+ KernelTime Filetime
+ UserTime Filetime
+}
+
+type WaitStatus struct {
+ ExitCode uint32
+}
+
+func (w WaitStatus) Exited() bool { return true }
+
+func (w WaitStatus) ExitStatus() int { return int(w.ExitCode) }
+
+func (w WaitStatus) Signal() Signal { return -1 }
+
+func (w WaitStatus) CoreDump() bool { return false }
+
+func (w WaitStatus) Stopped() bool { return false }
+
+func (w WaitStatus) Continued() bool { return false }
+
+func (w WaitStatus) StopSignal() Signal { return -1 }
+
+func (w WaitStatus) Signaled() bool { return false }
+
+func (w WaitStatus) TrapCause() int { return -1 }
+
+// Timespec is an invented structure on Windows, but here for
+// consistency with the corresponding package for other operating systems.
+type Timespec struct {
+ Sec int64
+ Nsec int64
+}
+
+func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
+
+func NsecToTimespec(nsec int64) (ts Timespec) {
+ ts.Sec = nsec / 1e9
+ ts.Nsec = nsec % 1e9
+ return
+}
+
+// TODO(brainman): fix all needed for net
+
+func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, syscall.EWINDOWS }
+func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) {
+ return 0, nil, syscall.EWINDOWS
+}
+func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) { return syscall.EWINDOWS }
+func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return syscall.EWINDOWS }
+
+// The Linger struct is wrong but we only noticed after Go 1.
+// sysLinger is the real system call structure.
+
+// BUG(brainman): The definition of Linger is not appropriate for direct use
+// with Setsockopt and Getsockopt.
+// Use SetsockoptLinger instead.
+
+type Linger struct {
+ Onoff int32
+ Linger int32
+}
+
+type sysLinger struct {
+ Onoff uint16
+ Linger uint16
+}
+
+type IPMreq struct {
+ Multiaddr [4]byte /* in_addr */
+ Interface [4]byte /* in_addr */
+}
+
+type IPv6Mreq struct {
+ Multiaddr [16]byte /* in6_addr */
+ Interface uint32
+}
+
+func GetsockoptInt(fd Handle, level, opt int) (int, error) { return -1, syscall.EWINDOWS }
+
+func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) {
+ sys := sysLinger{Onoff: uint16(l.Onoff), Linger: uint16(l.Linger)}
+ return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&sys)), int32(unsafe.Sizeof(sys)))
+}
+
+func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) {
+ return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4)
+}
+func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) {
+ return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq)))
+}
+func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) {
+ return syscall.EWINDOWS
+}
+
+func Getpid() (pid int) { return int(getCurrentProcessId()) }
+
+func FindFirstFile(name *uint16, data *Win32finddata) (handle Handle, err error) {
+ // NOTE(rsc): The Win32finddata struct is wrong for the system call:
+ // the two paths are each one uint16 short. Use the correct struct,
+ // a win32finddata1, and then copy the results out.
+ // There is no loss of expressivity here, because the final
+ // uint16, if it is used, is supposed to be a NUL, and Go doesn't need that.
+ // For Go 1.1, we might avoid the allocation of win32finddata1 here
+ // by adding a final Bug [2]uint16 field to the struct and then
+ // adjusting the fields in the result directly.
+ var data1 win32finddata1
+ handle, err = findFirstFile1(name, &data1)
+ if err == nil {
+ copyFindData(data, &data1)
+ }
+ return
+}
+
+func FindNextFile(handle Handle, data *Win32finddata) (err error) {
+ var data1 win32finddata1
+ err = findNextFile1(handle, &data1)
+ if err == nil {
+ copyFindData(data, &data1)
+ }
+ return
+}
+
+func getProcessEntry(pid int) (*ProcessEntry32, error) {
+ snapshot, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
+ if err != nil {
+ return nil, err
+ }
+ defer CloseHandle(snapshot)
+ var procEntry ProcessEntry32
+ procEntry.Size = uint32(unsafe.Sizeof(procEntry))
+ if err = Process32First(snapshot, &procEntry); err != nil {
+ return nil, err
+ }
+ for {
+ if procEntry.ProcessID == uint32(pid) {
+ return &procEntry, nil
+ }
+ err = Process32Next(snapshot, &procEntry)
+ if err != nil {
+ return nil, err
+ }
+ }
+}
+
+func Getppid() (ppid int) {
+ pe, err := getProcessEntry(Getpid())
+ if err != nil {
+ return -1
+ }
+ return int(pe.ParentProcessID)
+}
+
+// TODO(brainman): fix all needed for os
+func Fchdir(fd Handle) (err error) { return syscall.EWINDOWS }
+func Link(oldpath, newpath string) (err error) { return syscall.EWINDOWS }
+func Symlink(path, link string) (err error) { return syscall.EWINDOWS }
+
+func Fchmod(fd Handle, mode uint32) (err error) { return syscall.EWINDOWS }
+func Chown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS }
+func Lchown(path string, uid int, gid int) (err error) { return syscall.EWINDOWS }
+func Fchown(fd Handle, uid int, gid int) (err error) { return syscall.EWINDOWS }
+
+func Getuid() (uid int) { return -1 }
+func Geteuid() (euid int) { return -1 }
+func Getgid() (gid int) { return -1 }
+func Getegid() (egid int) { return -1 }
+func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS }
+
+type Signal int
+
+func (s Signal) Signal() {}
+
+func (s Signal) String() string {
+ if 0 <= s && int(s) < len(signals) {
+ str := signals[s]
+ if str != "" {
+ return str
+ }
+ }
+ return "signal " + itoa(int(s))
+}
+
+func LoadCreateSymbolicLink() error {
+ return procCreateSymbolicLinkW.Find()
+}
+
+// Readlink returns the destination of the named symbolic link.
+func Readlink(path string, buf []byte) (n int, err error) {
+ fd, err := CreateFile(StringToUTF16Ptr(path), GENERIC_READ, 0, nil, OPEN_EXISTING,
+ FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS, 0)
+ if err != nil {
+ return -1, err
+ }
+ defer CloseHandle(fd)
+
+ rdbbuf := make([]byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
+ var bytesReturned uint32
+ err = DeviceIoControl(fd, FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil)
+ if err != nil {
+ return -1, err
+ }
+
+ rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0]))
+ var s string
+ switch rdb.ReparseTag {
+ case IO_REPARSE_TAG_SYMLINK:
+ data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
+ p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
+ s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2])
+ case IO_REPARSE_TAG_MOUNT_POINT:
+ data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
+ p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
+ s = UTF16ToString(p[data.PrintNameOffset/2 : (data.PrintNameLength-data.PrintNameOffset)/2])
+ default:
+ // the path is not a symlink or junction but another type of reparse
+ // point
+ return -1, syscall.ENOENT
+ }
+ n = copy(buf, []byte(s))
+
+ return n, nil
+}
diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go
new file mode 100644
index 0000000..401a5f2
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/types_windows.go
@@ -0,0 +1,1282 @@
+// 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 windows
+
+import "syscall"
+
+const (
+ // Windows errors.
+ ERROR_FILE_NOT_FOUND syscall.Errno = 2
+ ERROR_PATH_NOT_FOUND syscall.Errno = 3
+ ERROR_ACCESS_DENIED syscall.Errno = 5
+ ERROR_NO_MORE_FILES syscall.Errno = 18
+ ERROR_HANDLE_EOF syscall.Errno = 38
+ ERROR_NETNAME_DELETED syscall.Errno = 64
+ ERROR_FILE_EXISTS syscall.Errno = 80
+ ERROR_BROKEN_PIPE syscall.Errno = 109
+ ERROR_BUFFER_OVERFLOW syscall.Errno = 111
+ ERROR_INSUFFICIENT_BUFFER syscall.Errno = 122
+ ERROR_MOD_NOT_FOUND syscall.Errno = 126
+ ERROR_PROC_NOT_FOUND syscall.Errno = 127
+ ERROR_ALREADY_EXISTS syscall.Errno = 183
+ ERROR_ENVVAR_NOT_FOUND syscall.Errno = 203
+ ERROR_MORE_DATA syscall.Errno = 234
+ ERROR_OPERATION_ABORTED syscall.Errno = 995
+ ERROR_IO_PENDING syscall.Errno = 997
+ ERROR_SERVICE_SPECIFIC_ERROR syscall.Errno = 1066
+ ERROR_NOT_FOUND syscall.Errno = 1168
+ ERROR_PRIVILEGE_NOT_HELD syscall.Errno = 1314
+ WSAEACCES syscall.Errno = 10013
+ WSAECONNRESET syscall.Errno = 10054
+)
+
+const (
+ // Invented values to support what package os expects.
+ O_RDONLY = 0x00000
+ O_WRONLY = 0x00001
+ O_RDWR = 0x00002
+ O_CREAT = 0x00040
+ O_EXCL = 0x00080
+ O_NOCTTY = 0x00100
+ O_TRUNC = 0x00200
+ O_NONBLOCK = 0x00800
+ O_APPEND = 0x00400
+ O_SYNC = 0x01000
+ O_ASYNC = 0x02000
+ O_CLOEXEC = 0x80000
+)
+
+const (
+ // More invented values for signals
+ SIGHUP = Signal(0x1)
+ SIGINT = Signal(0x2)
+ SIGQUIT = Signal(0x3)
+ SIGILL = Signal(0x4)
+ SIGTRAP = Signal(0x5)
+ SIGABRT = Signal(0x6)
+ SIGBUS = Signal(0x7)
+ SIGFPE = Signal(0x8)
+ SIGKILL = Signal(0x9)
+ SIGSEGV = Signal(0xb)
+ SIGPIPE = Signal(0xd)
+ SIGALRM = Signal(0xe)
+ SIGTERM = Signal(0xf)
+)
+
+var signals = [...]string{
+ 1: "hangup",
+ 2: "interrupt",
+ 3: "quit",
+ 4: "illegal instruction",
+ 5: "trace/breakpoint trap",
+ 6: "aborted",
+ 7: "bus error",
+ 8: "floating point exception",
+ 9: "killed",
+ 10: "user defined signal 1",
+ 11: "segmentation fault",
+ 12: "user defined signal 2",
+ 13: "broken pipe",
+ 14: "alarm clock",
+ 15: "terminated",
+}
+
+const (
+ GENERIC_READ = 0x80000000
+ GENERIC_WRITE = 0x40000000
+ GENERIC_EXECUTE = 0x20000000
+ GENERIC_ALL = 0x10000000
+
+ FILE_LIST_DIRECTORY = 0x00000001
+ FILE_APPEND_DATA = 0x00000004
+ FILE_WRITE_ATTRIBUTES = 0x00000100
+
+ FILE_SHARE_READ = 0x00000001
+ FILE_SHARE_WRITE = 0x00000002
+ FILE_SHARE_DELETE = 0x00000004
+ FILE_ATTRIBUTE_READONLY = 0x00000001
+ FILE_ATTRIBUTE_HIDDEN = 0x00000002
+ FILE_ATTRIBUTE_SYSTEM = 0x00000004
+ FILE_ATTRIBUTE_DIRECTORY = 0x00000010
+ FILE_ATTRIBUTE_ARCHIVE = 0x00000020
+ FILE_ATTRIBUTE_NORMAL = 0x00000080
+ FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400
+
+ INVALID_FILE_ATTRIBUTES = 0xffffffff
+
+ CREATE_NEW = 1
+ CREATE_ALWAYS = 2
+ OPEN_EXISTING = 3
+ OPEN_ALWAYS = 4
+ TRUNCATE_EXISTING = 5
+
+ FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
+ FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
+ FILE_FLAG_OVERLAPPED = 0x40000000
+
+ HANDLE_FLAG_INHERIT = 0x00000001
+ STARTF_USESTDHANDLES = 0x00000100
+ STARTF_USESHOWWINDOW = 0x00000001
+ DUPLICATE_CLOSE_SOURCE = 0x00000001
+ DUPLICATE_SAME_ACCESS = 0x00000002
+
+ STD_INPUT_HANDLE = -10 & (1<<32 - 1)
+ STD_OUTPUT_HANDLE = -11 & (1<<32 - 1)
+ STD_ERROR_HANDLE = -12 & (1<<32 - 1)
+
+ FILE_BEGIN = 0
+ FILE_CURRENT = 1
+ FILE_END = 2
+
+ LANG_ENGLISH = 0x09
+ SUBLANG_ENGLISH_US = 0x01
+
+ FORMAT_MESSAGE_ALLOCATE_BUFFER = 256
+ FORMAT_MESSAGE_IGNORE_INSERTS = 512
+ FORMAT_MESSAGE_FROM_STRING = 1024
+ FORMAT_MESSAGE_FROM_HMODULE = 2048
+ FORMAT_MESSAGE_FROM_SYSTEM = 4096
+ FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192
+ FORMAT_MESSAGE_MAX_WIDTH_MASK = 255
+
+ MAX_PATH = 260
+ MAX_LONG_PATH = 32768
+
+ MAX_COMPUTERNAME_LENGTH = 15
+
+ TIME_ZONE_ID_UNKNOWN = 0
+ TIME_ZONE_ID_STANDARD = 1
+
+ TIME_ZONE_ID_DAYLIGHT = 2
+ IGNORE = 0
+ INFINITE = 0xffffffff
+
+ WAIT_TIMEOUT = 258
+ WAIT_ABANDONED = 0x00000080
+ WAIT_OBJECT_0 = 0x00000000
+ WAIT_FAILED = 0xFFFFFFFF
+
+ CREATE_NEW_PROCESS_GROUP = 0x00000200
+ CREATE_UNICODE_ENVIRONMENT = 0x00000400
+
+ PROCESS_TERMINATE = 1
+ PROCESS_QUERY_INFORMATION = 0x00000400
+ SYNCHRONIZE = 0x00100000
+
+ FILE_MAP_COPY = 0x01
+ FILE_MAP_WRITE = 0x02
+ FILE_MAP_READ = 0x04
+ FILE_MAP_EXECUTE = 0x20
+
+ CTRL_C_EVENT = 0
+ CTRL_BREAK_EVENT = 1
+
+ // Windows reserves errors >= 1<<29 for application use.
+ APPLICATION_ERROR = 1 << 29
+)
+
+const (
+ // flags for CreateToolhelp32Snapshot
+ TH32CS_SNAPHEAPLIST = 0x01
+ TH32CS_SNAPPROCESS = 0x02
+ TH32CS_SNAPTHREAD = 0x04
+ TH32CS_SNAPMODULE = 0x08
+ TH32CS_SNAPMODULE32 = 0x10
+ TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST | TH32CS_SNAPMODULE | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD
+ TH32CS_INHERIT = 0x80000000
+)
+
+const (
+ // filters for ReadDirectoryChangesW
+ FILE_NOTIFY_CHANGE_FILE_NAME = 0x001
+ FILE_NOTIFY_CHANGE_DIR_NAME = 0x002
+ FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x004
+ FILE_NOTIFY_CHANGE_SIZE = 0x008
+ FILE_NOTIFY_CHANGE_LAST_WRITE = 0x010
+ FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x020
+ FILE_NOTIFY_CHANGE_CREATION = 0x040
+ FILE_NOTIFY_CHANGE_SECURITY = 0x100
+)
+
+const (
+ // do not reorder
+ FILE_ACTION_ADDED = iota + 1
+ FILE_ACTION_REMOVED
+ FILE_ACTION_MODIFIED
+ FILE_ACTION_RENAMED_OLD_NAME
+ FILE_ACTION_RENAMED_NEW_NAME
+)
+
+const (
+ // wincrypt.h
+ PROV_RSA_FULL = 1
+ PROV_RSA_SIG = 2
+ PROV_DSS = 3
+ PROV_FORTEZZA = 4
+ PROV_MS_EXCHANGE = 5
+ PROV_SSL = 6
+ PROV_RSA_SCHANNEL = 12
+ PROV_DSS_DH = 13
+ PROV_EC_ECDSA_SIG = 14
+ PROV_EC_ECNRA_SIG = 15
+ PROV_EC_ECDSA_FULL = 16
+ PROV_EC_ECNRA_FULL = 17
+ PROV_DH_SCHANNEL = 18
+ PROV_SPYRUS_LYNKS = 20
+ PROV_RNG = 21
+ PROV_INTEL_SEC = 22
+ PROV_REPLACE_OWF = 23
+ PROV_RSA_AES = 24
+ CRYPT_VERIFYCONTEXT = 0xF0000000
+ CRYPT_NEWKEYSET = 0x00000008
+ CRYPT_DELETEKEYSET = 0x00000010
+ CRYPT_MACHINE_KEYSET = 0x00000020
+ CRYPT_SILENT = 0x00000040
+ CRYPT_DEFAULT_CONTAINER_OPTIONAL = 0x00000080
+
+ USAGE_MATCH_TYPE_AND = 0
+ USAGE_MATCH_TYPE_OR = 1
+
+ X509_ASN_ENCODING = 0x00000001
+ PKCS_7_ASN_ENCODING = 0x00010000
+
+ CERT_STORE_PROV_MEMORY = 2
+
+ CERT_STORE_ADD_ALWAYS = 4
+
+ CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004
+
+ CERT_TRUST_NO_ERROR = 0x00000000
+ CERT_TRUST_IS_NOT_TIME_VALID = 0x00000001
+ CERT_TRUST_IS_REVOKED = 0x00000004
+ CERT_TRUST_IS_NOT_SIGNATURE_VALID = 0x00000008
+ CERT_TRUST_IS_NOT_VALID_FOR_USAGE = 0x00000010
+ CERT_TRUST_IS_UNTRUSTED_ROOT = 0x00000020
+ CERT_TRUST_REVOCATION_STATUS_UNKNOWN = 0x00000040
+ CERT_TRUST_IS_CYCLIC = 0x00000080
+ CERT_TRUST_INVALID_EXTENSION = 0x00000100
+ CERT_TRUST_INVALID_POLICY_CONSTRAINTS = 0x00000200
+ CERT_TRUST_INVALID_BASIC_CONSTRAINTS = 0x00000400
+ CERT_TRUST_INVALID_NAME_CONSTRAINTS = 0x00000800
+ CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT = 0x00001000
+ CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT = 0x00002000
+ CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT = 0x00004000
+ CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT = 0x00008000
+ CERT_TRUST_IS_OFFLINE_REVOCATION = 0x01000000
+ CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY = 0x02000000
+ CERT_TRUST_IS_EXPLICIT_DISTRUST = 0x04000000
+ CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT = 0x08000000
+
+ CERT_CHAIN_POLICY_BASE = 1
+ CERT_CHAIN_POLICY_AUTHENTICODE = 2
+ CERT_CHAIN_POLICY_AUTHENTICODE_TS = 3
+ CERT_CHAIN_POLICY_SSL = 4
+ CERT_CHAIN_POLICY_BASIC_CONSTRAINTS = 5
+ CERT_CHAIN_POLICY_NT_AUTH = 6
+ CERT_CHAIN_POLICY_MICROSOFT_ROOT = 7
+ CERT_CHAIN_POLICY_EV = 8
+
+ CERT_E_EXPIRED = 0x800B0101
+ CERT_E_ROLE = 0x800B0103
+ CERT_E_PURPOSE = 0x800B0106
+ CERT_E_UNTRUSTEDROOT = 0x800B0109
+ CERT_E_CN_NO_MATCH = 0x800B010F
+
+ AUTHTYPE_CLIENT = 1
+ AUTHTYPE_SERVER = 2
+)
+
+var (
+ OID_PKIX_KP_SERVER_AUTH = []byte("1.3.6.1.5.5.7.3.1\x00")
+ OID_SERVER_GATED_CRYPTO = []byte("1.3.6.1.4.1.311.10.3.3\x00")
+ OID_SGC_NETSCAPE = []byte("2.16.840.1.113730.4.1\x00")
+)
+
+// Invented values to support what package os expects.
+type Timeval struct {
+ Sec int32
+ Usec int32
+}
+
+func (tv *Timeval) Nanoseconds() int64 {
+ return (int64(tv.Sec)*1e6 + int64(tv.Usec)) * 1e3
+}
+
+func NsecToTimeval(nsec int64) (tv Timeval) {
+ tv.Sec = int32(nsec / 1e9)
+ tv.Usec = int32(nsec % 1e9 / 1e3)
+ return
+}
+
+type SecurityAttributes struct {
+ Length uint32
+ SecurityDescriptor uintptr
+ InheritHandle uint32
+}
+
+type Overlapped struct {
+ Internal uintptr
+ InternalHigh uintptr
+ Offset uint32
+ OffsetHigh uint32
+ HEvent Handle
+}
+
+type FileNotifyInformation struct {
+ NextEntryOffset uint32
+ Action uint32
+ FileNameLength uint32
+ FileName uint16
+}
+
+type Filetime struct {
+ LowDateTime uint32
+ HighDateTime uint32
+}
+
+// Nanoseconds returns Filetime ft in nanoseconds
+// since Epoch (00:00:00 UTC, January 1, 1970).
+func (ft *Filetime) Nanoseconds() int64 {
+ // 100-nanosecond intervals since January 1, 1601
+ nsec := int64(ft.HighDateTime)<<32 + int64(ft.LowDateTime)
+ // change starting time to the Epoch (00:00:00 UTC, January 1, 1970)
+ nsec -= 116444736000000000
+ // convert into nanoseconds
+ nsec *= 100
+ return nsec
+}
+
+func NsecToFiletime(nsec int64) (ft Filetime) {
+ // convert into 100-nanosecond
+ nsec /= 100
+ // change starting time to January 1, 1601
+ nsec += 116444736000000000
+ // split into high / low
+ ft.LowDateTime = uint32(nsec & 0xffffffff)
+ ft.HighDateTime = uint32(nsec >> 32 & 0xffffffff)
+ return ft
+}
+
+type Win32finddata struct {
+ FileAttributes uint32
+ CreationTime Filetime
+ LastAccessTime Filetime
+ LastWriteTime Filetime
+ FileSizeHigh uint32
+ FileSizeLow uint32
+ Reserved0 uint32
+ Reserved1 uint32
+ FileName [MAX_PATH - 1]uint16
+ AlternateFileName [13]uint16
+}
+
+// This is the actual system call structure.
+// Win32finddata is what we committed to in Go 1.
+type win32finddata1 struct {
+ FileAttributes uint32
+ CreationTime Filetime
+ LastAccessTime Filetime
+ LastWriteTime Filetime
+ FileSizeHigh uint32
+ FileSizeLow uint32
+ Reserved0 uint32
+ Reserved1 uint32
+ FileName [MAX_PATH]uint16
+ AlternateFileName [14]uint16
+}
+
+func copyFindData(dst *Win32finddata, src *win32finddata1) {
+ dst.FileAttributes = src.FileAttributes
+ dst.CreationTime = src.CreationTime
+ dst.LastAccessTime = src.LastAccessTime
+ dst.LastWriteTime = src.LastWriteTime
+ dst.FileSizeHigh = src.FileSizeHigh
+ dst.FileSizeLow = src.FileSizeLow
+ dst.Reserved0 = src.Reserved0
+ dst.Reserved1 = src.Reserved1
+
+ // The src is 1 element bigger than dst, but it must be NUL.
+ copy(dst.FileName[:], src.FileName[:])
+ copy(dst.AlternateFileName[:], src.AlternateFileName[:])
+}
+
+type ByHandleFileInformation struct {
+ FileAttributes uint32
+ CreationTime Filetime
+ LastAccessTime Filetime
+ LastWriteTime Filetime
+ VolumeSerialNumber uint32
+ FileSizeHigh uint32
+ FileSizeLow uint32
+ NumberOfLinks uint32
+ FileIndexHigh uint32
+ FileIndexLow uint32
+}
+
+const (
+ GetFileExInfoStandard = 0
+ GetFileExMaxInfoLevel = 1
+)
+
+type Win32FileAttributeData struct {
+ FileAttributes uint32
+ CreationTime Filetime
+ LastAccessTime Filetime
+ LastWriteTime Filetime
+ FileSizeHigh uint32
+ FileSizeLow uint32
+}
+
+// ShowWindow constants
+const (
+ // winuser.h
+ SW_HIDE = 0
+ SW_NORMAL = 1
+ SW_SHOWNORMAL = 1
+ SW_SHOWMINIMIZED = 2
+ SW_SHOWMAXIMIZED = 3
+ SW_MAXIMIZE = 3
+ SW_SHOWNOACTIVATE = 4
+ SW_SHOW = 5
+ SW_MINIMIZE = 6
+ SW_SHOWMINNOACTIVE = 7
+ SW_SHOWNA = 8
+ SW_RESTORE = 9
+ SW_SHOWDEFAULT = 10
+ SW_FORCEMINIMIZE = 11
+)
+
+type StartupInfo struct {
+ Cb uint32
+ _ *uint16
+ Desktop *uint16
+ Title *uint16
+ X uint32
+ Y uint32
+ XSize uint32
+ YSize uint32
+ XCountChars uint32
+ YCountChars uint32
+ FillAttribute uint32
+ Flags uint32
+ ShowWindow uint16
+ _ uint16
+ _ *byte
+ StdInput Handle
+ StdOutput Handle
+ StdErr Handle
+}
+
+type ProcessInformation struct {
+ Process Handle
+ Thread Handle
+ ProcessId uint32
+ ThreadId uint32
+}
+
+type ProcessEntry32 struct {
+ Size uint32
+ Usage uint32
+ ProcessID uint32
+ DefaultHeapID uintptr
+ ModuleID uint32
+ Threads uint32
+ ParentProcessID uint32
+ PriClassBase int32
+ Flags uint32
+ ExeFile [MAX_PATH]uint16
+}
+
+type Systemtime struct {
+ Year uint16
+ Month uint16
+ DayOfWeek uint16
+ Day uint16
+ Hour uint16
+ Minute uint16
+ Second uint16
+ Milliseconds uint16
+}
+
+type Timezoneinformation struct {
+ Bias int32
+ StandardName [32]uint16
+ StandardDate Systemtime
+ StandardBias int32
+ DaylightName [32]uint16
+ DaylightDate Systemtime
+ DaylightBias int32
+}
+
+// Socket related.
+
+const (
+ AF_UNSPEC = 0
+ AF_UNIX = 1
+ AF_INET = 2
+ AF_INET6 = 23
+ AF_NETBIOS = 17
+
+ SOCK_STREAM = 1
+ SOCK_DGRAM = 2
+ SOCK_RAW = 3
+ SOCK_SEQPACKET = 5
+
+ IPPROTO_IP = 0
+ IPPROTO_IPV6 = 0x29
+ IPPROTO_TCP = 6
+ IPPROTO_UDP = 17
+
+ SOL_SOCKET = 0xffff
+ SO_REUSEADDR = 4
+ SO_KEEPALIVE = 8
+ SO_DONTROUTE = 16
+ SO_BROADCAST = 32
+ SO_LINGER = 128
+ SO_RCVBUF = 0x1002
+ SO_SNDBUF = 0x1001
+ SO_UPDATE_ACCEPT_CONTEXT = 0x700b
+ SO_UPDATE_CONNECT_CONTEXT = 0x7010
+
+ IOC_OUT = 0x40000000
+ IOC_IN = 0x80000000
+ IOC_VENDOR = 0x18000000
+ IOC_INOUT = IOC_IN | IOC_OUT
+ IOC_WS2 = 0x08000000
+ SIO_GET_EXTENSION_FUNCTION_POINTER = IOC_INOUT | IOC_WS2 | 6
+ SIO_KEEPALIVE_VALS = IOC_IN | IOC_VENDOR | 4
+ SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12
+
+ // cf. http://support.microsoft.com/default.aspx?scid=kb;en-us;257460
+
+ IP_TOS = 0x3
+ IP_TTL = 0x4
+ IP_MULTICAST_IF = 0x9
+ IP_MULTICAST_TTL = 0xa
+ IP_MULTICAST_LOOP = 0xb
+ IP_ADD_MEMBERSHIP = 0xc
+ IP_DROP_MEMBERSHIP = 0xd
+
+ IPV6_V6ONLY = 0x1b
+ IPV6_UNICAST_HOPS = 0x4
+ IPV6_MULTICAST_IF = 0x9
+ IPV6_MULTICAST_HOPS = 0xa
+ IPV6_MULTICAST_LOOP = 0xb
+ IPV6_JOIN_GROUP = 0xc
+ IPV6_LEAVE_GROUP = 0xd
+
+ SOMAXCONN = 0x7fffffff
+
+ TCP_NODELAY = 1
+
+ SHUT_RD = 0
+ SHUT_WR = 1
+ SHUT_RDWR = 2
+
+ WSADESCRIPTION_LEN = 256
+ WSASYS_STATUS_LEN = 128
+)
+
+type WSABuf struct {
+ Len uint32
+ Buf *byte
+}
+
+// Invented values to support what package os expects.
+const (
+ S_IFMT = 0x1f000
+ S_IFIFO = 0x1000
+ S_IFCHR = 0x2000
+ S_IFDIR = 0x4000
+ S_IFBLK = 0x6000
+ S_IFREG = 0x8000
+ S_IFLNK = 0xa000
+ S_IFSOCK = 0xc000
+ S_ISUID = 0x800
+ S_ISGID = 0x400
+ S_ISVTX = 0x200
+ S_IRUSR = 0x100
+ S_IWRITE = 0x80
+ S_IWUSR = 0x80
+ S_IXUSR = 0x40
+)
+
+const (
+ FILE_TYPE_CHAR = 0x0002
+ FILE_TYPE_DISK = 0x0001
+ FILE_TYPE_PIPE = 0x0003
+ FILE_TYPE_REMOTE = 0x8000
+ FILE_TYPE_UNKNOWN = 0x0000
+)
+
+type Hostent struct {
+ Name *byte
+ Aliases **byte
+ AddrType uint16
+ Length uint16
+ AddrList **byte
+}
+
+type Protoent struct {
+ Name *byte
+ Aliases **byte
+ Proto uint16
+}
+
+const (
+ DNS_TYPE_A = 0x0001
+ DNS_TYPE_NS = 0x0002
+ DNS_TYPE_MD = 0x0003
+ DNS_TYPE_MF = 0x0004
+ DNS_TYPE_CNAME = 0x0005
+ DNS_TYPE_SOA = 0x0006
+ DNS_TYPE_MB = 0x0007
+ DNS_TYPE_MG = 0x0008
+ DNS_TYPE_MR = 0x0009
+ DNS_TYPE_NULL = 0x000a
+ DNS_TYPE_WKS = 0x000b
+ DNS_TYPE_PTR = 0x000c
+ DNS_TYPE_HINFO = 0x000d
+ DNS_TYPE_MINFO = 0x000e
+ DNS_TYPE_MX = 0x000f
+ DNS_TYPE_TEXT = 0x0010
+ DNS_TYPE_RP = 0x0011
+ DNS_TYPE_AFSDB = 0x0012
+ DNS_TYPE_X25 = 0x0013
+ DNS_TYPE_ISDN = 0x0014
+ DNS_TYPE_RT = 0x0015
+ DNS_TYPE_NSAP = 0x0016
+ DNS_TYPE_NSAPPTR = 0x0017
+ DNS_TYPE_SIG = 0x0018
+ DNS_TYPE_KEY = 0x0019
+ DNS_TYPE_PX = 0x001a
+ DNS_TYPE_GPOS = 0x001b
+ DNS_TYPE_AAAA = 0x001c
+ DNS_TYPE_LOC = 0x001d
+ DNS_TYPE_NXT = 0x001e
+ DNS_TYPE_EID = 0x001f
+ DNS_TYPE_NIMLOC = 0x0020
+ DNS_TYPE_SRV = 0x0021
+ DNS_TYPE_ATMA = 0x0022
+ DNS_TYPE_NAPTR = 0x0023
+ DNS_TYPE_KX = 0x0024
+ DNS_TYPE_CERT = 0x0025
+ DNS_TYPE_A6 = 0x0026
+ DNS_TYPE_DNAME = 0x0027
+ DNS_TYPE_SINK = 0x0028
+ DNS_TYPE_OPT = 0x0029
+ DNS_TYPE_DS = 0x002B
+ DNS_TYPE_RRSIG = 0x002E
+ DNS_TYPE_NSEC = 0x002F
+ DNS_TYPE_DNSKEY = 0x0030
+ DNS_TYPE_DHCID = 0x0031
+ DNS_TYPE_UINFO = 0x0064
+ DNS_TYPE_UID = 0x0065
+ DNS_TYPE_GID = 0x0066
+ DNS_TYPE_UNSPEC = 0x0067
+ DNS_TYPE_ADDRS = 0x00f8
+ DNS_TYPE_TKEY = 0x00f9
+ DNS_TYPE_TSIG = 0x00fa
+ DNS_TYPE_IXFR = 0x00fb
+ DNS_TYPE_AXFR = 0x00fc
+ DNS_TYPE_MAILB = 0x00fd
+ DNS_TYPE_MAILA = 0x00fe
+ DNS_TYPE_ALL = 0x00ff
+ DNS_TYPE_ANY = 0x00ff
+ DNS_TYPE_WINS = 0xff01
+ DNS_TYPE_WINSR = 0xff02
+ DNS_TYPE_NBSTAT = 0xff01
+)
+
+const (
+ DNS_INFO_NO_RECORDS = 0x251D
+)
+
+const (
+ // flags inside DNSRecord.Dw
+ DnsSectionQuestion = 0x0000
+ DnsSectionAnswer = 0x0001
+ DnsSectionAuthority = 0x0002
+ DnsSectionAdditional = 0x0003
+)
+
+type DNSSRVData struct {
+ Target *uint16
+ Priority uint16
+ Weight uint16
+ Port uint16
+ Pad uint16
+}
+
+type DNSPTRData struct {
+ Host *uint16
+}
+
+type DNSMXData struct {
+ NameExchange *uint16
+ Preference uint16
+ Pad uint16
+}
+
+type DNSTXTData struct {
+ StringCount uint16
+ StringArray [1]*uint16
+}
+
+type DNSRecord struct {
+ Next *DNSRecord
+ Name *uint16
+ Type uint16
+ Length uint16
+ Dw uint32
+ Ttl uint32
+ Reserved uint32
+ Data [40]byte
+}
+
+const (
+ TF_DISCONNECT = 1
+ TF_REUSE_SOCKET = 2
+ TF_WRITE_BEHIND = 4
+ TF_USE_DEFAULT_WORKER = 0
+ TF_USE_SYSTEM_THREAD = 16
+ TF_USE_KERNEL_APC = 32
+)
+
+type TransmitFileBuffers struct {
+ Head uintptr
+ HeadLength uint32
+ Tail uintptr
+ TailLength uint32
+}
+
+const (
+ IFF_UP = 1
+ IFF_BROADCAST = 2
+ IFF_LOOPBACK = 4
+ IFF_POINTTOPOINT = 8
+ IFF_MULTICAST = 16
+)
+
+const SIO_GET_INTERFACE_LIST = 0x4004747F
+
+// TODO(mattn): SockaddrGen is union of sockaddr/sockaddr_in/sockaddr_in6_old.
+// will be fixed to change variable type as suitable.
+
+type SockaddrGen [24]byte
+
+type InterfaceInfo struct {
+ Flags uint32
+ Address SockaddrGen
+ BroadcastAddress SockaddrGen
+ Netmask SockaddrGen
+}
+
+type IpAddressString struct {
+ String [16]byte
+}
+
+type IpMaskString IpAddressString
+
+type IpAddrString struct {
+ Next *IpAddrString
+ IpAddress IpAddressString
+ IpMask IpMaskString
+ Context uint32
+}
+
+const MAX_ADAPTER_NAME_LENGTH = 256
+const MAX_ADAPTER_DESCRIPTION_LENGTH = 128
+const MAX_ADAPTER_ADDRESS_LENGTH = 8
+
+type IpAdapterInfo struct {
+ Next *IpAdapterInfo
+ ComboIndex uint32
+ AdapterName [MAX_ADAPTER_NAME_LENGTH + 4]byte
+ Description [MAX_ADAPTER_DESCRIPTION_LENGTH + 4]byte
+ AddressLength uint32
+ Address [MAX_ADAPTER_ADDRESS_LENGTH]byte
+ Index uint32
+ Type uint32
+ DhcpEnabled uint32
+ CurrentIpAddress *IpAddrString
+ IpAddressList IpAddrString
+ GatewayList IpAddrString
+ DhcpServer IpAddrString
+ HaveWins bool
+ PrimaryWinsServer IpAddrString
+ SecondaryWinsServer IpAddrString
+ LeaseObtained int64
+ LeaseExpires int64
+}
+
+const MAXLEN_PHYSADDR = 8
+const MAX_INTERFACE_NAME_LEN = 256
+const MAXLEN_IFDESCR = 256
+
+type MibIfRow struct {
+ Name [MAX_INTERFACE_NAME_LEN]uint16
+ Index uint32
+ Type uint32
+ Mtu uint32
+ Speed uint32
+ PhysAddrLen uint32
+ PhysAddr [MAXLEN_PHYSADDR]byte
+ AdminStatus uint32
+ OperStatus uint32
+ LastChange uint32
+ InOctets uint32
+ InUcastPkts uint32
+ InNUcastPkts uint32
+ InDiscards uint32
+ InErrors uint32
+ InUnknownProtos uint32
+ OutOctets uint32
+ OutUcastPkts uint32
+ OutNUcastPkts uint32
+ OutDiscards uint32
+ OutErrors uint32
+ OutQLen uint32
+ DescrLen uint32
+ Descr [MAXLEN_IFDESCR]byte
+}
+
+type CertContext struct {
+ EncodingType uint32
+ EncodedCert *byte
+ Length uint32
+ CertInfo uintptr
+ Store Handle
+}
+
+type CertChainContext struct {
+ Size uint32
+ TrustStatus CertTrustStatus
+ ChainCount uint32
+ Chains **CertSimpleChain
+ LowerQualityChainCount uint32
+ LowerQualityChains **CertChainContext
+ HasRevocationFreshnessTime uint32
+ RevocationFreshnessTime uint32
+}
+
+type CertSimpleChain struct {
+ Size uint32
+ TrustStatus CertTrustStatus
+ NumElements uint32
+ Elements **CertChainElement
+ TrustListInfo uintptr
+ HasRevocationFreshnessTime uint32
+ RevocationFreshnessTime uint32
+}
+
+type CertChainElement struct {
+ Size uint32
+ CertContext *CertContext
+ TrustStatus CertTrustStatus
+ RevocationInfo *CertRevocationInfo
+ IssuanceUsage *CertEnhKeyUsage
+ ApplicationUsage *CertEnhKeyUsage
+ ExtendedErrorInfo *uint16
+}
+
+type CertRevocationInfo struct {
+ Size uint32
+ RevocationResult uint32
+ RevocationOid *byte
+ OidSpecificInfo uintptr
+ HasFreshnessTime uint32
+ FreshnessTime uint32
+ CrlInfo uintptr // *CertRevocationCrlInfo
+}
+
+type CertTrustStatus struct {
+ ErrorStatus uint32
+ InfoStatus uint32
+}
+
+type CertUsageMatch struct {
+ Type uint32
+ Usage CertEnhKeyUsage
+}
+
+type CertEnhKeyUsage struct {
+ Length uint32
+ UsageIdentifiers **byte
+}
+
+type CertChainPara struct {
+ Size uint32
+ RequestedUsage CertUsageMatch
+ RequstedIssuancePolicy CertUsageMatch
+ URLRetrievalTimeout uint32
+ CheckRevocationFreshnessTime uint32
+ RevocationFreshnessTime uint32
+ CacheResync *Filetime
+}
+
+type CertChainPolicyPara struct {
+ Size uint32
+ Flags uint32
+ ExtraPolicyPara uintptr
+}
+
+type SSLExtraCertChainPolicyPara struct {
+ Size uint32
+ AuthType uint32
+ Checks uint32
+ ServerName *uint16
+}
+
+type CertChainPolicyStatus struct {
+ Size uint32
+ Error uint32
+ ChainIndex uint32
+ ElementIndex uint32
+ ExtraPolicyStatus uintptr
+}
+
+const (
+ // do not reorder
+ HKEY_CLASSES_ROOT = 0x80000000 + iota
+ HKEY_CURRENT_USER
+ HKEY_LOCAL_MACHINE
+ HKEY_USERS
+ HKEY_PERFORMANCE_DATA
+ HKEY_CURRENT_CONFIG
+ HKEY_DYN_DATA
+
+ KEY_QUERY_VALUE = 1
+ KEY_SET_VALUE = 2
+ KEY_CREATE_SUB_KEY = 4
+ KEY_ENUMERATE_SUB_KEYS = 8
+ KEY_NOTIFY = 16
+ KEY_CREATE_LINK = 32
+ KEY_WRITE = 0x20006
+ KEY_EXECUTE = 0x20019
+ KEY_READ = 0x20019
+ KEY_WOW64_64KEY = 0x0100
+ KEY_WOW64_32KEY = 0x0200
+ KEY_ALL_ACCESS = 0xf003f
+)
+
+const (
+ // do not reorder
+ REG_NONE = iota
+ REG_SZ
+ REG_EXPAND_SZ
+ REG_BINARY
+ REG_DWORD_LITTLE_ENDIAN
+ REG_DWORD_BIG_ENDIAN
+ REG_LINK
+ REG_MULTI_SZ
+ REG_RESOURCE_LIST
+ REG_FULL_RESOURCE_DESCRIPTOR
+ REG_RESOURCE_REQUIREMENTS_LIST
+ REG_QWORD_LITTLE_ENDIAN
+ REG_DWORD = REG_DWORD_LITTLE_ENDIAN
+ REG_QWORD = REG_QWORD_LITTLE_ENDIAN
+)
+
+type AddrinfoW struct {
+ Flags int32
+ Family int32
+ Socktype int32
+ Protocol int32
+ Addrlen uintptr
+ Canonname *uint16
+ Addr uintptr
+ Next *AddrinfoW
+}
+
+const (
+ AI_PASSIVE = 1
+ AI_CANONNAME = 2
+ AI_NUMERICHOST = 4
+)
+
+type GUID struct {
+ Data1 uint32
+ Data2 uint16
+ Data3 uint16
+ Data4 [8]byte
+}
+
+var WSAID_CONNECTEX = GUID{
+ 0x25a207b9,
+ 0xddf3,
+ 0x4660,
+ [8]byte{0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e},
+}
+
+const (
+ FILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1
+ FILE_SKIP_SET_EVENT_ON_HANDLE = 2
+)
+
+const (
+ WSAPROTOCOL_LEN = 255
+ MAX_PROTOCOL_CHAIN = 7
+ BASE_PROTOCOL = 1
+ LAYERED_PROTOCOL = 0
+
+ XP1_CONNECTIONLESS = 0x00000001
+ XP1_GUARANTEED_DELIVERY = 0x00000002
+ XP1_GUARANTEED_ORDER = 0x00000004
+ XP1_MESSAGE_ORIENTED = 0x00000008
+ XP1_PSEUDO_STREAM = 0x00000010
+ XP1_GRACEFUL_CLOSE = 0x00000020
+ XP1_EXPEDITED_DATA = 0x00000040
+ XP1_CONNECT_DATA = 0x00000080
+ XP1_DISCONNECT_DATA = 0x00000100
+ XP1_SUPPORT_BROADCAST = 0x00000200
+ XP1_SUPPORT_MULTIPOINT = 0x00000400
+ XP1_MULTIPOINT_CONTROL_PLANE = 0x00000800
+ XP1_MULTIPOINT_DATA_PLANE = 0x00001000
+ XP1_QOS_SUPPORTED = 0x00002000
+ XP1_UNI_SEND = 0x00008000
+ XP1_UNI_RECV = 0x00010000
+ XP1_IFS_HANDLES = 0x00020000
+ XP1_PARTIAL_MESSAGE = 0x00040000
+ XP1_SAN_SUPPORT_SDP = 0x00080000
+
+ PFL_MULTIPLE_PROTO_ENTRIES = 0x00000001
+ PFL_RECOMMENDED_PROTO_ENTRY = 0x00000002
+ PFL_HIDDEN = 0x00000004
+ PFL_MATCHES_PROTOCOL_ZERO = 0x00000008
+ PFL_NETWORKDIRECT_PROVIDER = 0x00000010
+)
+
+type WSAProtocolInfo struct {
+ ServiceFlags1 uint32
+ ServiceFlags2 uint32
+ ServiceFlags3 uint32
+ ServiceFlags4 uint32
+ ProviderFlags uint32
+ ProviderId GUID
+ CatalogEntryId uint32
+ ProtocolChain WSAProtocolChain
+ Version int32
+ AddressFamily int32
+ MaxSockAddr int32
+ MinSockAddr int32
+ SocketType int32
+ Protocol int32
+ ProtocolMaxOffset int32
+ NetworkByteOrder int32
+ SecurityScheme int32
+ MessageSize uint32
+ ProviderReserved uint32
+ ProtocolName [WSAPROTOCOL_LEN + 1]uint16
+}
+
+type WSAProtocolChain struct {
+ ChainLen int32
+ ChainEntries [MAX_PROTOCOL_CHAIN]uint32
+}
+
+type TCPKeepalive struct {
+ OnOff uint32
+ Time uint32
+ Interval uint32
+}
+
+type symbolicLinkReparseBuffer struct {
+ SubstituteNameOffset uint16
+ SubstituteNameLength uint16
+ PrintNameOffset uint16
+ PrintNameLength uint16
+ Flags uint32
+ PathBuffer [1]uint16
+}
+
+type mountPointReparseBuffer struct {
+ SubstituteNameOffset uint16
+ SubstituteNameLength uint16
+ PrintNameOffset uint16
+ PrintNameLength uint16
+ PathBuffer [1]uint16
+}
+
+type reparseDataBuffer struct {
+ ReparseTag uint32
+ ReparseDataLength uint16
+ Reserved uint16
+
+ // GenericReparseBuffer
+ reparseBuffer byte
+}
+
+const (
+ FSCTL_GET_REPARSE_POINT = 0x900A8
+ MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024
+ IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
+ IO_REPARSE_TAG_SYMLINK = 0xA000000C
+ SYMBOLIC_LINK_FLAG_DIRECTORY = 0x1
+)
+
+const (
+ ComputerNameNetBIOS = 0
+ ComputerNameDnsHostname = 1
+ ComputerNameDnsDomain = 2
+ ComputerNameDnsFullyQualified = 3
+ ComputerNamePhysicalNetBIOS = 4
+ ComputerNamePhysicalDnsHostname = 5
+ ComputerNamePhysicalDnsDomain = 6
+ ComputerNamePhysicalDnsFullyQualified = 7
+ ComputerNameMax = 8
+)
+
+const (
+ MOVEFILE_REPLACE_EXISTING = 0x1
+ MOVEFILE_COPY_ALLOWED = 0x2
+ MOVEFILE_DELAY_UNTIL_REBOOT = 0x4
+ MOVEFILE_WRITE_THROUGH = 0x8
+ MOVEFILE_CREATE_HARDLINK = 0x10
+ MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20
+)
+
+const GAA_FLAG_INCLUDE_PREFIX = 0x00000010
+
+const (
+ IF_TYPE_OTHER = 1
+ IF_TYPE_ETHERNET_CSMACD = 6
+ IF_TYPE_ISO88025_TOKENRING = 9
+ IF_TYPE_PPP = 23
+ IF_TYPE_SOFTWARE_LOOPBACK = 24
+ IF_TYPE_ATM = 37
+ IF_TYPE_IEEE80211 = 71
+ IF_TYPE_TUNNEL = 131
+ IF_TYPE_IEEE1394 = 144
+)
+
+type SocketAddress struct {
+ Sockaddr *syscall.RawSockaddrAny
+ SockaddrLength int32
+}
+
+type IpAdapterUnicastAddress struct {
+ Length uint32
+ Flags uint32
+ Next *IpAdapterUnicastAddress
+ Address SocketAddress
+ PrefixOrigin int32
+ SuffixOrigin int32
+ DadState int32
+ ValidLifetime uint32
+ PreferredLifetime uint32
+ LeaseLifetime uint32
+ OnLinkPrefixLength uint8
+}
+
+type IpAdapterAnycastAddress struct {
+ Length uint32
+ Flags uint32
+ Next *IpAdapterAnycastAddress
+ Address SocketAddress
+}
+
+type IpAdapterMulticastAddress struct {
+ Length uint32
+ Flags uint32
+ Next *IpAdapterMulticastAddress
+ Address SocketAddress
+}
+
+type IpAdapterDnsServerAdapter struct {
+ Length uint32
+ Reserved uint32
+ Next *IpAdapterDnsServerAdapter
+ Address SocketAddress
+}
+
+type IpAdapterPrefix struct {
+ Length uint32
+ Flags uint32
+ Next *IpAdapterPrefix
+ Address SocketAddress
+ PrefixLength uint32
+}
+
+type IpAdapterAddresses struct {
+ Length uint32
+ IfIndex uint32
+ Next *IpAdapterAddresses
+ AdapterName *byte
+ FirstUnicastAddress *IpAdapterUnicastAddress
+ FirstAnycastAddress *IpAdapterAnycastAddress
+ FirstMulticastAddress *IpAdapterMulticastAddress
+ FirstDnsServerAddress *IpAdapterDnsServerAdapter
+ DnsSuffix *uint16
+ Description *uint16
+ FriendlyName *uint16
+ PhysicalAddress [syscall.MAX_ADAPTER_ADDRESS_LENGTH]byte
+ PhysicalAddressLength uint32
+ Flags uint32
+ Mtu uint32
+ IfType uint32
+ OperStatus uint32
+ Ipv6IfIndex uint32
+ ZoneIndices [16]uint32
+ FirstPrefix *IpAdapterPrefix
+ /* more fields might be present here. */
+}
+
+const (
+ IfOperStatusUp = 1
+ IfOperStatusDown = 2
+ IfOperStatusTesting = 3
+ IfOperStatusUnknown = 4
+ IfOperStatusDormant = 5
+ IfOperStatusNotPresent = 6
+ IfOperStatusLowerLayerDown = 7
+)
+
+// Console related constants used for the mode parameter to SetConsoleMode. See
+// https://docs.microsoft.com/en-us/windows/console/setconsolemode for details.
+
+const (
+ ENABLE_PROCESSED_INPUT = 0x1
+ ENABLE_LINE_INPUT = 0x2
+ ENABLE_ECHO_INPUT = 0x4
+ ENABLE_WINDOW_INPUT = 0x8
+ ENABLE_MOUSE_INPUT = 0x10
+ ENABLE_INSERT_MODE = 0x20
+ ENABLE_QUICK_EDIT_MODE = 0x40
+ ENABLE_EXTENDED_FLAGS = 0x80
+ ENABLE_AUTO_POSITION = 0x100
+ ENABLE_VIRTUAL_TERMINAL_INPUT = 0x200
+
+ ENABLE_PROCESSED_OUTPUT = 0x1
+ ENABLE_WRAP_AT_EOL_OUTPUT = 0x2
+ ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4
+ DISABLE_NEWLINE_AUTO_RETURN = 0x8
+ ENABLE_LVB_GRID_WORLDWIDE = 0x10
+)
+
+type Coord struct {
+ X int16
+ Y int16
+}
+
+type SmallRect struct {
+ Left int16
+ Top int16
+ Right int16
+ Bottom int16
+}
+
+// Used with GetConsoleScreenBuffer to retreive information about a console
+// screen buffer. See
+// https://docs.microsoft.com/en-us/windows/console/console-screen-buffer-info-str
+// for details.
+
+type ConsoleScreenBufferInfo struct {
+ Size Coord
+ CursorPosition Coord
+ Attributes uint16
+ Window SmallRect
+ MaximumWindowSize Coord
+}
diff --git a/vendor/golang.org/x/sys/windows/types_windows_386.go b/vendor/golang.org/x/sys/windows/types_windows_386.go
new file mode 100644
index 0000000..10f33be
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/types_windows_386.go
@@ -0,0 +1,22 @@
+// 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 windows
+
+type WSAData struct {
+ Version uint16
+ HighVersion uint16
+ Description [WSADESCRIPTION_LEN + 1]byte
+ SystemStatus [WSASYS_STATUS_LEN + 1]byte
+ MaxSockets uint16
+ MaxUdpDg uint16
+ VendorInfo *byte
+}
+
+type Servent struct {
+ Name *byte
+ Aliases **byte
+ Port uint16
+ Proto *byte
+}
diff --git a/vendor/golang.org/x/sys/windows/types_windows_amd64.go b/vendor/golang.org/x/sys/windows/types_windows_amd64.go
new file mode 100644
index 0000000..3f272c2
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/types_windows_amd64.go
@@ -0,0 +1,22 @@
+// 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 windows
+
+type WSAData struct {
+ Version uint16
+ HighVersion uint16
+ MaxSockets uint16
+ MaxUdpDg uint16
+ VendorInfo *byte
+ Description [WSADESCRIPTION_LEN + 1]byte
+ SystemStatus [WSASYS_STATUS_LEN + 1]byte
+}
+
+type Servent struct {
+ Name *byte
+ Aliases **byte
+ Proto *byte
+ Port uint16
+}
diff --git a/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/zsyscall_windows.go
new file mode 100644
index 0000000..2f893d2
--- /dev/null
+++ b/vendor/golang.org/x/sys/windows/zsyscall_windows.go
@@ -0,0 +1,2428 @@
+// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT
+
+package windows
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var _ unsafe.Pointer
+
+// Do the interface allocations only once for common
+// Errno values.
+const (
+ errnoERROR_IO_PENDING = 997
+)
+
+var (
+ errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
+)
+
+// errnoErr returns common boxed Errno values, to prevent
+// allocations at runtime.
+func errnoErr(e syscall.Errno) error {
+ switch e {
+ case 0:
+ return nil
+ case errnoERROR_IO_PENDING:
+ return errERROR_IO_PENDING
+ }
+ // TODO: add more here, after collecting data on the common
+ // error values see on Windows. (perhaps when running
+ // all.bat?)
+ return e
+}
+
+var (
+ modadvapi32 = NewLazySystemDLL("advapi32.dll")
+ modkernel32 = NewLazySystemDLL("kernel32.dll")
+ modshell32 = NewLazySystemDLL("shell32.dll")
+ modmswsock = NewLazySystemDLL("mswsock.dll")
+ modcrypt32 = NewLazySystemDLL("crypt32.dll")
+ modws2_32 = NewLazySystemDLL("ws2_32.dll")
+ moddnsapi = NewLazySystemDLL("dnsapi.dll")
+ modiphlpapi = NewLazySystemDLL("iphlpapi.dll")
+ modsecur32 = NewLazySystemDLL("secur32.dll")
+ modnetapi32 = NewLazySystemDLL("netapi32.dll")
+ moduserenv = NewLazySystemDLL("userenv.dll")
+
+ procRegisterEventSourceW = modadvapi32.NewProc("RegisterEventSourceW")
+ procDeregisterEventSource = modadvapi32.NewProc("DeregisterEventSource")
+ procReportEventW = modadvapi32.NewProc("ReportEventW")
+ procOpenSCManagerW = modadvapi32.NewProc("OpenSCManagerW")
+ procCloseServiceHandle = modadvapi32.NewProc("CloseServiceHandle")
+ procCreateServiceW = modadvapi32.NewProc("CreateServiceW")
+ procOpenServiceW = modadvapi32.NewProc("OpenServiceW")
+ procDeleteService = modadvapi32.NewProc("DeleteService")
+ procStartServiceW = modadvapi32.NewProc("StartServiceW")
+ procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
+ procControlService = modadvapi32.NewProc("ControlService")
+ procStartServiceCtrlDispatcherW = modadvapi32.NewProc("StartServiceCtrlDispatcherW")
+ procSetServiceStatus = modadvapi32.NewProc("SetServiceStatus")
+ procChangeServiceConfigW = modadvapi32.NewProc("ChangeServiceConfigW")
+ procQueryServiceConfigW = modadvapi32.NewProc("QueryServiceConfigW")
+ procChangeServiceConfig2W = modadvapi32.NewProc("ChangeServiceConfig2W")
+ procQueryServiceConfig2W = modadvapi32.NewProc("QueryServiceConfig2W")
+ procEnumServicesStatusExW = modadvapi32.NewProc("EnumServicesStatusExW")
+ procGetLastError = modkernel32.NewProc("GetLastError")
+ procLoadLibraryW = modkernel32.NewProc("LoadLibraryW")
+ procLoadLibraryExW = modkernel32.NewProc("LoadLibraryExW")
+ procFreeLibrary = modkernel32.NewProc("FreeLibrary")
+ procGetProcAddress = modkernel32.NewProc("GetProcAddress")
+ procGetVersion = modkernel32.NewProc("GetVersion")
+ procFormatMessageW = modkernel32.NewProc("FormatMessageW")
+ procExitProcess = modkernel32.NewProc("ExitProcess")
+ procCreateFileW = modkernel32.NewProc("CreateFileW")
+ procReadFile = modkernel32.NewProc("ReadFile")
+ procWriteFile = modkernel32.NewProc("WriteFile")
+ procSetFilePointer = modkernel32.NewProc("SetFilePointer")
+ procCloseHandle = modkernel32.NewProc("CloseHandle")
+ procGetStdHandle = modkernel32.NewProc("GetStdHandle")
+ procSetStdHandle = modkernel32.NewProc("SetStdHandle")
+ procFindFirstFileW = modkernel32.NewProc("FindFirstFileW")
+ procFindNextFileW = modkernel32.NewProc("FindNextFileW")
+ procFindClose = modkernel32.NewProc("FindClose")
+ procGetFileInformationByHandle = modkernel32.NewProc("GetFileInformationByHandle")
+ procGetCurrentDirectoryW = modkernel32.NewProc("GetCurrentDirectoryW")
+ procSetCurrentDirectoryW = modkernel32.NewProc("SetCurrentDirectoryW")
+ procCreateDirectoryW = modkernel32.NewProc("CreateDirectoryW")
+ procRemoveDirectoryW = modkernel32.NewProc("RemoveDirectoryW")
+ procDeleteFileW = modkernel32.NewProc("DeleteFileW")
+ procMoveFileW = modkernel32.NewProc("MoveFileW")
+ procMoveFileExW = modkernel32.NewProc("MoveFileExW")
+ procGetComputerNameW = modkernel32.NewProc("GetComputerNameW")
+ procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW")
+ procSetEndOfFile = modkernel32.NewProc("SetEndOfFile")
+ procGetSystemTimeAsFileTime = modkernel32.NewProc("GetSystemTimeAsFileTime")
+ procGetSystemTimePreciseAsFileTime = modkernel32.NewProc("GetSystemTimePreciseAsFileTime")
+ procGetTimeZoneInformation = modkernel32.NewProc("GetTimeZoneInformation")
+ procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort")
+ procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus")
+ procPostQueuedCompletionStatus = modkernel32.NewProc("PostQueuedCompletionStatus")
+ procCancelIo = modkernel32.NewProc("CancelIo")
+ procCancelIoEx = modkernel32.NewProc("CancelIoEx")
+ procCreateProcessW = modkernel32.NewProc("CreateProcessW")
+ procOpenProcess = modkernel32.NewProc("OpenProcess")
+ procTerminateProcess = modkernel32.NewProc("TerminateProcess")
+ procGetExitCodeProcess = modkernel32.NewProc("GetExitCodeProcess")
+ procGetStartupInfoW = modkernel32.NewProc("GetStartupInfoW")
+ procGetCurrentProcess = modkernel32.NewProc("GetCurrentProcess")
+ procGetProcessTimes = modkernel32.NewProc("GetProcessTimes")
+ procDuplicateHandle = modkernel32.NewProc("DuplicateHandle")
+ procWaitForSingleObject = modkernel32.NewProc("WaitForSingleObject")
+ procGetTempPathW = modkernel32.NewProc("GetTempPathW")
+ procCreatePipe = modkernel32.NewProc("CreatePipe")
+ procGetFileType = modkernel32.NewProc("GetFileType")
+ procCryptAcquireContextW = modadvapi32.NewProc("CryptAcquireContextW")
+ procCryptReleaseContext = modadvapi32.NewProc("CryptReleaseContext")
+ procCryptGenRandom = modadvapi32.NewProc("CryptGenRandom")
+ procGetEnvironmentStringsW = modkernel32.NewProc("GetEnvironmentStringsW")
+ procFreeEnvironmentStringsW = modkernel32.NewProc("FreeEnvironmentStringsW")
+ procGetEnvironmentVariableW = modkernel32.NewProc("GetEnvironmentVariableW")
+ procSetEnvironmentVariableW = modkernel32.NewProc("SetEnvironmentVariableW")
+ procSetFileTime = modkernel32.NewProc("SetFileTime")
+ procGetFileAttributesW = modkernel32.NewProc("GetFileAttributesW")
+ procSetFileAttributesW = modkernel32.NewProc("SetFileAttributesW")
+ procGetFileAttributesExW = modkernel32.NewProc("GetFileAttributesExW")
+ procGetCommandLineW = modkernel32.NewProc("GetCommandLineW")
+ procCommandLineToArgvW = modshell32.NewProc("CommandLineToArgvW")
+ procLocalFree = modkernel32.NewProc("LocalFree")
+ procSetHandleInformation = modkernel32.NewProc("SetHandleInformation")
+ procFlushFileBuffers = modkernel32.NewProc("FlushFileBuffers")
+ procGetFullPathNameW = modkernel32.NewProc("GetFullPathNameW")
+ procGetLongPathNameW = modkernel32.NewProc("GetLongPathNameW")
+ procGetShortPathNameW = modkernel32.NewProc("GetShortPathNameW")
+ procCreateFileMappingW = modkernel32.NewProc("CreateFileMappingW")
+ procMapViewOfFile = modkernel32.NewProc("MapViewOfFile")
+ procUnmapViewOfFile = modkernel32.NewProc("UnmapViewOfFile")
+ procFlushViewOfFile = modkernel32.NewProc("FlushViewOfFile")
+ procVirtualLock = modkernel32.NewProc("VirtualLock")
+ procVirtualUnlock = modkernel32.NewProc("VirtualUnlock")
+ procVirtualAlloc = modkernel32.NewProc("VirtualAlloc")
+ procVirtualFree = modkernel32.NewProc("VirtualFree")
+ procVirtualProtect = modkernel32.NewProc("VirtualProtect")
+ procTransmitFile = modmswsock.NewProc("TransmitFile")
+ procReadDirectoryChangesW = modkernel32.NewProc("ReadDirectoryChangesW")
+ procCertOpenSystemStoreW = modcrypt32.NewProc("CertOpenSystemStoreW")
+ procCertOpenStore = modcrypt32.NewProc("CertOpenStore")
+ procCertEnumCertificatesInStore = modcrypt32.NewProc("CertEnumCertificatesInStore")
+ procCertAddCertificateContextToStore = modcrypt32.NewProc("CertAddCertificateContextToStore")
+ procCertCloseStore = modcrypt32.NewProc("CertCloseStore")
+ procCertGetCertificateChain = modcrypt32.NewProc("CertGetCertificateChain")
+ procCertFreeCertificateChain = modcrypt32.NewProc("CertFreeCertificateChain")
+ procCertCreateCertificateContext = modcrypt32.NewProc("CertCreateCertificateContext")
+ procCertFreeCertificateContext = modcrypt32.NewProc("CertFreeCertificateContext")
+ procCertVerifyCertificateChainPolicy = modcrypt32.NewProc("CertVerifyCertificateChainPolicy")
+ procRegOpenKeyExW = modadvapi32.NewProc("RegOpenKeyExW")
+ procRegCloseKey = modadvapi32.NewProc("RegCloseKey")
+ procRegQueryInfoKeyW = modadvapi32.NewProc("RegQueryInfoKeyW")
+ procRegEnumKeyExW = modadvapi32.NewProc("RegEnumKeyExW")
+ procRegQueryValueExW = modadvapi32.NewProc("RegQueryValueExW")
+ procGetCurrentProcessId = modkernel32.NewProc("GetCurrentProcessId")
+ procGetConsoleMode = modkernel32.NewProc("GetConsoleMode")
+ procSetConsoleMode = modkernel32.NewProc("SetConsoleMode")
+ procGetConsoleScreenBufferInfo = modkernel32.NewProc("GetConsoleScreenBufferInfo")
+ procWriteConsoleW = modkernel32.NewProc("WriteConsoleW")
+ procReadConsoleW = modkernel32.NewProc("ReadConsoleW")
+ procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot")
+ procProcess32FirstW = modkernel32.NewProc("Process32FirstW")
+ procProcess32NextW = modkernel32.NewProc("Process32NextW")
+ procDeviceIoControl = modkernel32.NewProc("DeviceIoControl")
+ procCreateSymbolicLinkW = modkernel32.NewProc("CreateSymbolicLinkW")
+ procCreateHardLinkW = modkernel32.NewProc("CreateHardLinkW")
+ procGetCurrentThreadId = modkernel32.NewProc("GetCurrentThreadId")
+ procCreateEventW = modkernel32.NewProc("CreateEventW")
+ procCreateEventExW = modkernel32.NewProc("CreateEventExW")
+ procOpenEventW = modkernel32.NewProc("OpenEventW")
+ procSetEvent = modkernel32.NewProc("SetEvent")
+ procResetEvent = modkernel32.NewProc("ResetEvent")
+ procPulseEvent = modkernel32.NewProc("PulseEvent")
+ procWSAStartup = modws2_32.NewProc("WSAStartup")
+ procWSACleanup = modws2_32.NewProc("WSACleanup")
+ procWSAIoctl = modws2_32.NewProc("WSAIoctl")
+ procsocket = modws2_32.NewProc("socket")
+ procsetsockopt = modws2_32.NewProc("setsockopt")
+ procgetsockopt = modws2_32.NewProc("getsockopt")
+ procbind = modws2_32.NewProc("bind")
+ procconnect = modws2_32.NewProc("connect")
+ procgetsockname = modws2_32.NewProc("getsockname")
+ procgetpeername = modws2_32.NewProc("getpeername")
+ proclisten = modws2_32.NewProc("listen")
+ procshutdown = modws2_32.NewProc("shutdown")
+ procclosesocket = modws2_32.NewProc("closesocket")
+ procAcceptEx = modmswsock.NewProc("AcceptEx")
+ procGetAcceptExSockaddrs = modmswsock.NewProc("GetAcceptExSockaddrs")
+ procWSARecv = modws2_32.NewProc("WSARecv")
+ procWSASend = modws2_32.NewProc("WSASend")
+ procWSARecvFrom = modws2_32.NewProc("WSARecvFrom")
+ procWSASendTo = modws2_32.NewProc("WSASendTo")
+ procgethostbyname = modws2_32.NewProc("gethostbyname")
+ procgetservbyname = modws2_32.NewProc("getservbyname")
+ procntohs = modws2_32.NewProc("ntohs")
+ procgetprotobyname = modws2_32.NewProc("getprotobyname")
+ procDnsQuery_W = moddnsapi.NewProc("DnsQuery_W")
+ procDnsRecordListFree = moddnsapi.NewProc("DnsRecordListFree")
+ procDnsNameCompare_W = moddnsapi.NewProc("DnsNameCompare_W")
+ procGetAddrInfoW = modws2_32.NewProc("GetAddrInfoW")
+ procFreeAddrInfoW = modws2_32.NewProc("FreeAddrInfoW")
+ procGetIfEntry = modiphlpapi.NewProc("GetIfEntry")
+ procGetAdaptersInfo = modiphlpapi.NewProc("GetAdaptersInfo")
+ procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes")
+ procWSAEnumProtocolsW = modws2_32.NewProc("WSAEnumProtocolsW")
+ procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
+ procGetACP = modkernel32.NewProc("GetACP")
+ procMultiByteToWideChar = modkernel32.NewProc("MultiByteToWideChar")
+ procTranslateNameW = modsecur32.NewProc("TranslateNameW")
+ procGetUserNameExW = modsecur32.NewProc("GetUserNameExW")
+ procNetUserGetInfo = modnetapi32.NewProc("NetUserGetInfo")
+ procNetGetJoinInformation = modnetapi32.NewProc("NetGetJoinInformation")
+ procNetApiBufferFree = modnetapi32.NewProc("NetApiBufferFree")
+ procLookupAccountSidW = modadvapi32.NewProc("LookupAccountSidW")
+ procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW")
+ procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW")
+ procConvertStringSidToSidW = modadvapi32.NewProc("ConvertStringSidToSidW")
+ procGetLengthSid = modadvapi32.NewProc("GetLengthSid")
+ procCopySid = modadvapi32.NewProc("CopySid")
+ procAllocateAndInitializeSid = modadvapi32.NewProc("AllocateAndInitializeSid")
+ procFreeSid = modadvapi32.NewProc("FreeSid")
+ procEqualSid = modadvapi32.NewProc("EqualSid")
+ procOpenProcessToken = modadvapi32.NewProc("OpenProcessToken")
+ procGetTokenInformation = modadvapi32.NewProc("GetTokenInformation")
+ procGetUserProfileDirectoryW = moduserenv.NewProc("GetUserProfileDirectoryW")
+)
+
+func RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procRegisterEventSourceW.Addr(), 2, uintptr(unsafe.Pointer(uncServerName)), uintptr(unsafe.Pointer(sourceName)), 0)
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func DeregisterEventSource(handle Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procDeregisterEventSource.Addr(), 1, uintptr(handle), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) {
+ r1, _, e1 := syscall.Syscall9(procReportEventW.Addr(), 9, uintptr(log), uintptr(etype), uintptr(category), uintptr(eventId), uintptr(usrSId), uintptr(numStrings), uintptr(dataSize), uintptr(unsafe.Pointer(strings)), uintptr(unsafe.Pointer(rawData)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procOpenSCManagerW.Addr(), 3, uintptr(unsafe.Pointer(machineName)), uintptr(unsafe.Pointer(databaseName)), uintptr(access))
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CloseServiceHandle(handle Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procCloseServiceHandle.Addr(), 1, uintptr(handle), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall15(procCreateServiceW.Addr(), 13, uintptr(mgr), uintptr(unsafe.Pointer(serviceName)), uintptr(unsafe.Pointer(displayName)), uintptr(access), uintptr(srvType), uintptr(startType), uintptr(errCtl), uintptr(unsafe.Pointer(pathName)), uintptr(unsafe.Pointer(loadOrderGroup)), uintptr(unsafe.Pointer(tagId)), uintptr(unsafe.Pointer(dependencies)), uintptr(unsafe.Pointer(serviceStartName)), uintptr(unsafe.Pointer(password)), 0, 0)
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procOpenServiceW.Addr(), 3, uintptr(mgr), uintptr(unsafe.Pointer(serviceName)), uintptr(access))
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func DeleteService(service Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procDeleteService.Addr(), 1, uintptr(service), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) {
+ r1, _, e1 := syscall.Syscall(procStartServiceW.Addr(), 3, uintptr(service), uintptr(numArgs), uintptr(unsafe.Pointer(argVectors)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) {
+ r1, _, e1 := syscall.Syscall(procQueryServiceStatus.Addr(), 2, uintptr(service), uintptr(unsafe.Pointer(status)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) {
+ r1, _, e1 := syscall.Syscall(procControlService.Addr(), 3, uintptr(service), uintptr(control), uintptr(unsafe.Pointer(status)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) {
+ r1, _, e1 := syscall.Syscall(procStartServiceCtrlDispatcherW.Addr(), 1, uintptr(unsafe.Pointer(serviceTable)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetServiceStatus.Addr(), 2, uintptr(service), uintptr(unsafe.Pointer(serviceStatus)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) {
+ r1, _, e1 := syscall.Syscall12(procChangeServiceConfigW.Addr(), 11, uintptr(service), uintptr(serviceType), uintptr(startType), uintptr(errorControl), uintptr(unsafe.Pointer(binaryPathName)), uintptr(unsafe.Pointer(loadOrderGroup)), uintptr(unsafe.Pointer(tagId)), uintptr(unsafe.Pointer(dependencies)), uintptr(unsafe.Pointer(serviceStartName)), uintptr(unsafe.Pointer(password)), uintptr(unsafe.Pointer(displayName)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procQueryServiceConfigW.Addr(), 4, uintptr(service), uintptr(unsafe.Pointer(serviceConfig)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) {
+ r1, _, e1 := syscall.Syscall(procChangeServiceConfig2W.Addr(), 3, uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(info)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procQueryServiceConfig2W.Addr(), 5, uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(buff)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error) {
+ r1, _, e1 := syscall.Syscall12(procEnumServicesStatusExW.Addr(), 10, uintptr(mgr), uintptr(infoLevel), uintptr(serviceType), uintptr(serviceState), uintptr(unsafe.Pointer(services)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded)), uintptr(unsafe.Pointer(servicesReturned)), uintptr(unsafe.Pointer(resumeHandle)), uintptr(unsafe.Pointer(groupName)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetLastError() (lasterr error) {
+ r0, _, _ := syscall.Syscall(procGetLastError.Addr(), 0, 0, 0, 0)
+ if r0 != 0 {
+ lasterr = syscall.Errno(r0)
+ }
+ return
+}
+
+func LoadLibrary(libname string) (handle Handle, err error) {
+ var _p0 *uint16
+ _p0, err = syscall.UTF16PtrFromString(libname)
+ if err != nil {
+ return
+ }
+ return _LoadLibrary(_p0)
+}
+
+func _LoadLibrary(libname *uint16) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procLoadLibraryW.Addr(), 1, uintptr(unsafe.Pointer(libname)), 0, 0)
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) {
+ var _p0 *uint16
+ _p0, err = syscall.UTF16PtrFromString(libname)
+ if err != nil {
+ return
+ }
+ return _LoadLibraryEx(_p0, zero, flags)
+}
+
+func _LoadLibraryEx(libname *uint16, zero Handle, flags uintptr) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procLoadLibraryExW.Addr(), 3, uintptr(unsafe.Pointer(libname)), uintptr(zero), uintptr(flags))
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func FreeLibrary(handle Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procFreeLibrary.Addr(), 1, uintptr(handle), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetProcAddress(module Handle, procname string) (proc uintptr, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(procname)
+ if err != nil {
+ return
+ }
+ return _GetProcAddress(module, _p0)
+}
+
+func _GetProcAddress(module Handle, procname *byte) (proc uintptr, err error) {
+ r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), uintptr(unsafe.Pointer(procname)), 0)
+ proc = uintptr(r0)
+ if proc == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetVersion() (ver uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetVersion.Addr(), 0, 0, 0, 0)
+ ver = uint32(r0)
+ if ver == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) {
+ var _p0 *uint16
+ if len(buf) > 0 {
+ _p0 = &buf[0]
+ }
+ r0, _, e1 := syscall.Syscall9(procFormatMessageW.Addr(), 7, uintptr(flags), uintptr(msgsrc), uintptr(msgid), uintptr(langid), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(args)), 0, 0)
+ n = uint32(r0)
+ if n == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ExitProcess(exitcode uint32) {
+ syscall.Syscall(procExitProcess.Addr(), 1, uintptr(exitcode), 0, 0)
+ return
+}
+
+func CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile int32) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0)
+ handle = Handle(r0)
+ if handle == InvalidHandle {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) {
+ var _p0 *byte
+ if len(buf) > 0 {
+ _p0 = &buf[0]
+ }
+ r1, _, e1 := syscall.Syscall6(procReadFile.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(done)), uintptr(unsafe.Pointer(overlapped)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func WriteFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) {
+ var _p0 *byte
+ if len(buf) > 0 {
+ _p0 = &buf[0]
+ }
+ r1, _, e1 := syscall.Syscall6(procWriteFile.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(done)), uintptr(unsafe.Pointer(overlapped)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) {
+ r0, _, e1 := syscall.Syscall6(procSetFilePointer.Addr(), 4, uintptr(handle), uintptr(lowoffset), uintptr(unsafe.Pointer(highoffsetptr)), uintptr(whence), 0, 0)
+ newlowoffset = uint32(r0)
+ if newlowoffset == 0xffffffff {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CloseHandle(handle Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procCloseHandle.Addr(), 1, uintptr(handle), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetStdHandle(stdhandle uint32) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procGetStdHandle.Addr(), 1, uintptr(stdhandle), 0, 0)
+ handle = Handle(r0)
+ if handle == InvalidHandle {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetStdHandle(stdhandle uint32, handle Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetStdHandle.Addr(), 2, uintptr(stdhandle), uintptr(handle), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procFindFirstFileW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(data)), 0)
+ handle = Handle(r0)
+ if handle == InvalidHandle {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func findNextFile1(handle Handle, data *win32finddata1) (err error) {
+ r1, _, e1 := syscall.Syscall(procFindNextFileW.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(data)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func FindClose(handle Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procFindClose.Addr(), 1, uintptr(handle), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetFileInformationByHandle.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(data)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetCurrentDirectoryW.Addr(), 2, uintptr(buflen), uintptr(unsafe.Pointer(buf)), 0)
+ n = uint32(r0)
+ if n == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetCurrentDirectory(path *uint16) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetCurrentDirectoryW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) {
+ r1, _, e1 := syscall.Syscall(procCreateDirectoryW.Addr(), 2, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(sa)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func RemoveDirectory(path *uint16) (err error) {
+ r1, _, e1 := syscall.Syscall(procRemoveDirectoryW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func DeleteFile(path *uint16) (err error) {
+ r1, _, e1 := syscall.Syscall(procDeleteFileW.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func MoveFile(from *uint16, to *uint16) (err error) {
+ r1, _, e1 := syscall.Syscall(procMoveFileW.Addr(), 2, uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procMoveFileExW.Addr(), 3, uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), uintptr(flags))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetComputerName(buf *uint16, n *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetComputerNameW.Addr(), 2, uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetComputerNameExW.Addr(), 3, uintptr(nametype), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetEndOfFile(handle Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetEndOfFile.Addr(), 1, uintptr(handle), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetSystemTimeAsFileTime(time *Filetime) {
+ syscall.Syscall(procGetSystemTimeAsFileTime.Addr(), 1, uintptr(unsafe.Pointer(time)), 0, 0)
+ return
+}
+
+func GetSystemTimePreciseAsFileTime(time *Filetime) {
+ syscall.Syscall(procGetSystemTimePreciseAsFileTime.Addr(), 1, uintptr(unsafe.Pointer(time)), 0, 0)
+ return
+}
+
+func GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetTimeZoneInformation.Addr(), 1, uintptr(unsafe.Pointer(tzi)), 0, 0)
+ rc = uint32(r0)
+ if rc == 0xffffffff {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(filehandle), uintptr(cphandle), uintptr(key), uintptr(threadcnt), 0, 0)
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(cphandle), uintptr(unsafe.Pointer(qty)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(overlapped)), uintptr(timeout), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) (err error) {
+ r1, _, e1 := syscall.Syscall6(procPostQueuedCompletionStatus.Addr(), 4, uintptr(cphandle), uintptr(qty), uintptr(key), uintptr(unsafe.Pointer(overlapped)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CancelIo(s Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procCancelIo.Addr(), 1, uintptr(s), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CancelIoEx(s Handle, o *Overlapped) (err error) {
+ r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(s), uintptr(unsafe.Pointer(o)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) {
+ var _p0 uint32
+ if inheritHandles {
+ _p0 = 1
+ } else {
+ _p0 = 0
+ }
+ r1, _, e1 := syscall.Syscall12(procCreateProcessW.Addr(), 10, uintptr(unsafe.Pointer(appName)), uintptr(unsafe.Pointer(commandLine)), uintptr(unsafe.Pointer(procSecurity)), uintptr(unsafe.Pointer(threadSecurity)), uintptr(_p0), uintptr(creationFlags), uintptr(unsafe.Pointer(env)), uintptr(unsafe.Pointer(currentDir)), uintptr(unsafe.Pointer(startupInfo)), uintptr(unsafe.Pointer(outProcInfo)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func OpenProcess(da uint32, inheritHandle bool, pid uint32) (handle Handle, err error) {
+ var _p0 uint32
+ if inheritHandle {
+ _p0 = 1
+ } else {
+ _p0 = 0
+ }
+ r0, _, e1 := syscall.Syscall(procOpenProcess.Addr(), 3, uintptr(da), uintptr(_p0), uintptr(pid))
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func TerminateProcess(handle Handle, exitcode uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procTerminateProcess.Addr(), 2, uintptr(handle), uintptr(exitcode), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetExitCodeProcess.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(exitcode)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetStartupInfo(startupInfo *StartupInfo) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetStartupInfoW.Addr(), 1, uintptr(unsafe.Pointer(startupInfo)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetCurrentProcess() (pseudoHandle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procGetCurrentProcess.Addr(), 0, 0, 0, 0)
+ pseudoHandle = Handle(r0)
+ if pseudoHandle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error) {
+ r1, _, e1 := syscall.Syscall6(procGetProcessTimes.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(creationTime)), uintptr(unsafe.Pointer(exitTime)), uintptr(unsafe.Pointer(kernelTime)), uintptr(unsafe.Pointer(userTime)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) {
+ var _p0 uint32
+ if bInheritHandle {
+ _p0 = 1
+ } else {
+ _p0 = 0
+ }
+ r1, _, e1 := syscall.Syscall9(procDuplicateHandle.Addr(), 7, uintptr(hSourceProcessHandle), uintptr(hSourceHandle), uintptr(hTargetProcessHandle), uintptr(unsafe.Pointer(lpTargetHandle)), uintptr(dwDesiredAccess), uintptr(_p0), uintptr(dwOptions), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procWaitForSingleObject.Addr(), 2, uintptr(handle), uintptr(waitMilliseconds), 0)
+ event = uint32(r0)
+ if event == 0xffffffff {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetTempPathW.Addr(), 2, uintptr(buflen), uintptr(unsafe.Pointer(buf)), 0)
+ n = uint32(r0)
+ if n == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procCreatePipe.Addr(), 4, uintptr(unsafe.Pointer(readhandle)), uintptr(unsafe.Pointer(writehandle)), uintptr(unsafe.Pointer(sa)), uintptr(size), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetFileType(filehandle Handle) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetFileType.Addr(), 1, uintptr(filehandle), 0, 0)
+ n = uint32(r0)
+ if n == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procCryptAcquireContextW.Addr(), 5, uintptr(unsafe.Pointer(provhandle)), uintptr(unsafe.Pointer(container)), uintptr(unsafe.Pointer(provider)), uintptr(provtype), uintptr(flags), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CryptReleaseContext(provhandle Handle, flags uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procCryptReleaseContext.Addr(), 2, uintptr(provhandle), uintptr(flags), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) {
+ r1, _, e1 := syscall.Syscall(procCryptGenRandom.Addr(), 3, uintptr(provhandle), uintptr(buflen), uintptr(unsafe.Pointer(buf)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetEnvironmentStrings() (envs *uint16, err error) {
+ r0, _, e1 := syscall.Syscall(procGetEnvironmentStringsW.Addr(), 0, 0, 0, 0)
+ envs = (*uint16)(unsafe.Pointer(r0))
+ if envs == nil {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func FreeEnvironmentStrings(envs *uint16) (err error) {
+ r1, _, e1 := syscall.Syscall(procFreeEnvironmentStringsW.Addr(), 1, uintptr(unsafe.Pointer(envs)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetEnvironmentVariableW.Addr(), 3, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(size))
+ n = uint32(r0)
+ if n == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetEnvironmentVariable(name *uint16, value *uint16) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetEnvironmentVariableW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(value)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) {
+ r1, _, e1 := syscall.Syscall6(procSetFileTime.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(ctime)), uintptr(unsafe.Pointer(atime)), uintptr(unsafe.Pointer(wtime)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetFileAttributes(name *uint16) (attrs uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetFileAttributesW.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0)
+ attrs = uint32(r0)
+ if attrs == INVALID_FILE_ATTRIBUTES {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetFileAttributes(name *uint16, attrs uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetFileAttributesW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(attrs), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetFileAttributesExW.Addr(), 3, uintptr(unsafe.Pointer(name)), uintptr(level), uintptr(unsafe.Pointer(info)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetCommandLine() (cmd *uint16) {
+ r0, _, _ := syscall.Syscall(procGetCommandLineW.Addr(), 0, 0, 0, 0)
+ cmd = (*uint16)(unsafe.Pointer(r0))
+ return
+}
+
+func CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) {
+ r0, _, e1 := syscall.Syscall(procCommandLineToArgvW.Addr(), 2, uintptr(unsafe.Pointer(cmd)), uintptr(unsafe.Pointer(argc)), 0)
+ argv = (*[8192]*[8192]uint16)(unsafe.Pointer(r0))
+ if argv == nil {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func LocalFree(hmem Handle) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procLocalFree.Addr(), 1, uintptr(hmem), 0, 0)
+ handle = Handle(r0)
+ if handle != 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetHandleInformation.Addr(), 3, uintptr(handle), uintptr(mask), uintptr(flags))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func FlushFileBuffers(handle Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procFlushFileBuffers.Addr(), 1, uintptr(handle), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall6(procGetFullPathNameW.Addr(), 4, uintptr(unsafe.Pointer(path)), uintptr(buflen), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(fname)), 0, 0)
+ n = uint32(r0)
+ if n == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetLongPathNameW.Addr(), 3, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(buf)), uintptr(buflen))
+ n = uint32(r0)
+ if n == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) {
+ r0, _, e1 := syscall.Syscall(procGetShortPathNameW.Addr(), 3, uintptr(unsafe.Pointer(longpath)), uintptr(unsafe.Pointer(shortpath)), uintptr(buflen))
+ n = uint32(r0)
+ if n == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall6(procCreateFileMappingW.Addr(), 6, uintptr(fhandle), uintptr(unsafe.Pointer(sa)), uintptr(prot), uintptr(maxSizeHigh), uintptr(maxSizeLow), uintptr(unsafe.Pointer(name)))
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error) {
+ r0, _, e1 := syscall.Syscall6(procMapViewOfFile.Addr(), 5, uintptr(handle), uintptr(access), uintptr(offsetHigh), uintptr(offsetLow), uintptr(length), 0)
+ addr = uintptr(r0)
+ if addr == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func UnmapViewOfFile(addr uintptr) (err error) {
+ r1, _, e1 := syscall.Syscall(procUnmapViewOfFile.Addr(), 1, uintptr(addr), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func FlushViewOfFile(addr uintptr, length uintptr) (err error) {
+ r1, _, e1 := syscall.Syscall(procFlushViewOfFile.Addr(), 2, uintptr(addr), uintptr(length), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func VirtualLock(addr uintptr, length uintptr) (err error) {
+ r1, _, e1 := syscall.Syscall(procVirtualLock.Addr(), 2, uintptr(addr), uintptr(length), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func VirtualUnlock(addr uintptr, length uintptr) (err error) {
+ r1, _, e1 := syscall.Syscall(procVirtualUnlock.Addr(), 2, uintptr(addr), uintptr(length), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) {
+ r0, _, e1 := syscall.Syscall6(procVirtualAlloc.Addr(), 4, uintptr(address), uintptr(size), uintptr(alloctype), uintptr(protect), 0, 0)
+ value = uintptr(r0)
+ if value == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procVirtualFree.Addr(), 3, uintptr(address), uintptr(size), uintptr(freetype))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procVirtualProtect.Addr(), 4, uintptr(address), uintptr(size), uintptr(newprotect), uintptr(unsafe.Pointer(oldprotect)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) {
+ r1, _, e1 := syscall.Syscall9(procTransmitFile.Addr(), 7, uintptr(s), uintptr(handle), uintptr(bytesToWrite), uintptr(bytsPerSend), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transmitFileBuf)), uintptr(flags), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) {
+ var _p0 uint32
+ if watchSubTree {
+ _p0 = 1
+ } else {
+ _p0 = 0
+ }
+ r1, _, e1 := syscall.Syscall9(procReadDirectoryChangesW.Addr(), 8, uintptr(handle), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(_p0), uintptr(mask), uintptr(unsafe.Pointer(retlen)), uintptr(unsafe.Pointer(overlapped)), uintptr(completionRoutine), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procCertOpenSystemStoreW.Addr(), 2, uintptr(hprov), uintptr(unsafe.Pointer(name)), 0)
+ store = Handle(r0)
+ if store == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall6(procCertOpenStore.Addr(), 5, uintptr(storeProvider), uintptr(msgAndCertEncodingType), uintptr(cryptProv), uintptr(flags), uintptr(para), 0)
+ handle = Handle(r0)
+ if handle == InvalidHandle {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) {
+ r0, _, e1 := syscall.Syscall(procCertEnumCertificatesInStore.Addr(), 2, uintptr(store), uintptr(unsafe.Pointer(prevContext)), 0)
+ context = (*CertContext)(unsafe.Pointer(r0))
+ if context == nil {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) {
+ r1, _, e1 := syscall.Syscall6(procCertAddCertificateContextToStore.Addr(), 4, uintptr(store), uintptr(unsafe.Pointer(certContext)), uintptr(addDisposition), uintptr(unsafe.Pointer(storeContext)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CertCloseStore(store Handle, flags uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procCertCloseStore.Addr(), 2, uintptr(store), uintptr(flags), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) {
+ r1, _, e1 := syscall.Syscall9(procCertGetCertificateChain.Addr(), 8, uintptr(engine), uintptr(unsafe.Pointer(leaf)), uintptr(unsafe.Pointer(time)), uintptr(additionalStore), uintptr(unsafe.Pointer(para)), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(chainCtx)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CertFreeCertificateChain(ctx *CertChainContext) {
+ syscall.Syscall(procCertFreeCertificateChain.Addr(), 1, uintptr(unsafe.Pointer(ctx)), 0, 0)
+ return
+}
+
+func CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) {
+ r0, _, e1 := syscall.Syscall(procCertCreateCertificateContext.Addr(), 3, uintptr(certEncodingType), uintptr(unsafe.Pointer(certEncoded)), uintptr(encodedLen))
+ context = (*CertContext)(unsafe.Pointer(r0))
+ if context == nil {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CertFreeCertificateContext(ctx *CertContext) (err error) {
+ r1, _, e1 := syscall.Syscall(procCertFreeCertificateContext.Addr(), 1, uintptr(unsafe.Pointer(ctx)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) {
+ r1, _, e1 := syscall.Syscall6(procCertVerifyCertificateChainPolicy.Addr(), 4, uintptr(policyOID), uintptr(unsafe.Pointer(chain)), uintptr(unsafe.Pointer(para)), uintptr(unsafe.Pointer(status)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) {
+ r0, _, _ := syscall.Syscall6(procRegOpenKeyExW.Addr(), 5, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(options), uintptr(desiredAccess), uintptr(unsafe.Pointer(result)), 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func RegCloseKey(key Handle) (regerrno error) {
+ r0, _, _ := syscall.Syscall(procRegCloseKey.Addr(), 1, uintptr(key), 0, 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) {
+ r0, _, _ := syscall.Syscall12(procRegQueryInfoKeyW.Addr(), 12, uintptr(key), uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(classLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(subkeysLen)), uintptr(unsafe.Pointer(maxSubkeyLen)), uintptr(unsafe.Pointer(maxClassLen)), uintptr(unsafe.Pointer(valuesLen)), uintptr(unsafe.Pointer(maxValueNameLen)), uintptr(unsafe.Pointer(maxValueLen)), uintptr(unsafe.Pointer(saLen)), uintptr(unsafe.Pointer(lastWriteTime)))
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) {
+ r0, _, _ := syscall.Syscall9(procRegEnumKeyExW.Addr(), 8, uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(classLen)), uintptr(unsafe.Pointer(lastWriteTime)), 0)
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) {
+ r0, _, _ := syscall.Syscall6(procRegQueryValueExW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen)))
+ if r0 != 0 {
+ regerrno = syscall.Errno(r0)
+ }
+ return
+}
+
+func getCurrentProcessId() (pid uint32) {
+ r0, _, _ := syscall.Syscall(procGetCurrentProcessId.Addr(), 0, 0, 0, 0)
+ pid = uint32(r0)
+ return
+}
+
+func GetConsoleMode(console Handle, mode *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(mode)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetConsoleMode(console Handle, mode uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(console), uintptr(mode), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(info)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) {
+ r1, _, e1 := syscall.Syscall6(procWriteConsoleW.Addr(), 5, uintptr(console), uintptr(unsafe.Pointer(buf)), uintptr(towrite), uintptr(unsafe.Pointer(written)), uintptr(unsafe.Pointer(reserved)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) {
+ r1, _, e1 := syscall.Syscall6(procReadConsoleW.Addr(), 5, uintptr(console), uintptr(unsafe.Pointer(buf)), uintptr(toread), uintptr(unsafe.Pointer(read)), uintptr(unsafe.Pointer(inputControl)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procCreateToolhelp32Snapshot.Addr(), 2, uintptr(flags), uintptr(processId), 0)
+ handle = Handle(r0)
+ if handle == InvalidHandle {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) {
+ r1, _, e1 := syscall.Syscall(procProcess32FirstW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(procEntry)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) {
+ r1, _, e1 := syscall.Syscall(procProcess32NextW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(procEntry)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error) {
+ r1, _, e1 := syscall.Syscall9(procDeviceIoControl.Addr(), 8, uintptr(handle), uintptr(ioControlCode), uintptr(unsafe.Pointer(inBuffer)), uintptr(inBufferSize), uintptr(unsafe.Pointer(outBuffer)), uintptr(outBufferSize), uintptr(unsafe.Pointer(bytesReturned)), uintptr(unsafe.Pointer(overlapped)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procCreateSymbolicLinkW.Addr(), 3, uintptr(unsafe.Pointer(symlinkfilename)), uintptr(unsafe.Pointer(targetfilename)), uintptr(flags))
+ if r1&0xff == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) {
+ r1, _, e1 := syscall.Syscall(procCreateHardLinkW.Addr(), 3, uintptr(unsafe.Pointer(filename)), uintptr(unsafe.Pointer(existingfilename)), uintptr(reserved))
+ if r1&0xff == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetCurrentThreadId() (id uint32) {
+ r0, _, _ := syscall.Syscall(procGetCurrentThreadId.Addr(), 0, 0, 0, 0)
+ id = uint32(r0)
+ return
+}
+
+func CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(manualReset), uintptr(initialState), uintptr(unsafe.Pointer(name)), 0, 0)
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall6(procCreateEventExW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(desiredAccess), 0, 0)
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) {
+ var _p0 uint32
+ if inheritHandle {
+ _p0 = 1
+ } else {
+ _p0 = 0
+ }
+ r0, _, e1 := syscall.Syscall(procOpenEventW.Addr(), 3, uintptr(desiredAccess), uintptr(_p0), uintptr(unsafe.Pointer(name)))
+ handle = Handle(r0)
+ if handle == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func SetEvent(event Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetEvent.Addr(), 1, uintptr(event), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ResetEvent(event Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procResetEvent.Addr(), 1, uintptr(event), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func PulseEvent(event Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procPulseEvent.Addr(), 1, uintptr(event), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func WSAStartup(verreq uint32, data *WSAData) (sockerr error) {
+ r0, _, _ := syscall.Syscall(procWSAStartup.Addr(), 2, uintptr(verreq), uintptr(unsafe.Pointer(data)), 0)
+ if r0 != 0 {
+ sockerr = syscall.Errno(r0)
+ }
+ return
+}
+
+func WSACleanup() (err error) {
+ r1, _, e1 := syscall.Syscall(procWSACleanup.Addr(), 0, 0, 0, 0)
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) {
+ r1, _, e1 := syscall.Syscall9(procWSAIoctl.Addr(), 9, uintptr(s), uintptr(iocc), uintptr(unsafe.Pointer(inbuf)), uintptr(cbif), uintptr(unsafe.Pointer(outbuf)), uintptr(cbob), uintptr(unsafe.Pointer(cbbr)), uintptr(unsafe.Pointer(overlapped)), uintptr(completionRoutine))
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func socket(af int32, typ int32, protocol int32) (handle Handle, err error) {
+ r0, _, e1 := syscall.Syscall(procsocket.Addr(), 3, uintptr(af), uintptr(typ), uintptr(protocol))
+ handle = Handle(r0)
+ if handle == InvalidHandle {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procsetsockopt.Addr(), 5, uintptr(s), uintptr(level), uintptr(optname), uintptr(unsafe.Pointer(optval)), uintptr(optlen), 0)
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procgetsockopt.Addr(), 5, uintptr(s), uintptr(level), uintptr(optname), uintptr(unsafe.Pointer(optval)), uintptr(unsafe.Pointer(optlen)), 0)
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func bind(s Handle, name unsafe.Pointer, namelen int32) (err error) {
+ r1, _, e1 := syscall.Syscall(procbind.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen))
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func connect(s Handle, name unsafe.Pointer, namelen int32) (err error) {
+ r1, _, e1 := syscall.Syscall(procconnect.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen))
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func getsockname(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) {
+ r1, _, e1 := syscall.Syscall(procgetsockname.Addr(), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func getpeername(s Handle, rsa *RawSockaddrAny, addrlen *int32) (err error) {
+ r1, _, e1 := syscall.Syscall(procgetpeername.Addr(), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func listen(s Handle, backlog int32) (err error) {
+ r1, _, e1 := syscall.Syscall(proclisten.Addr(), 2, uintptr(s), uintptr(backlog), 0)
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func shutdown(s Handle, how int32) (err error) {
+ r1, _, e1 := syscall.Syscall(procshutdown.Addr(), 2, uintptr(s), uintptr(how), 0)
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func Closesocket(s Handle) (err error) {
+ r1, _, e1 := syscall.Syscall(procclosesocket.Addr(), 1, uintptr(s), 0, 0)
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) {
+ r1, _, e1 := syscall.Syscall9(procAcceptEx.Addr(), 8, uintptr(ls), uintptr(as), uintptr(unsafe.Pointer(buf)), uintptr(rxdatalen), uintptr(laddrlen), uintptr(raddrlen), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(overlapped)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, lrsa **RawSockaddrAny, lrsalen *int32, rrsa **RawSockaddrAny, rrsalen *int32) {
+ syscall.Syscall9(procGetAcceptExSockaddrs.Addr(), 8, uintptr(unsafe.Pointer(buf)), uintptr(rxdatalen), uintptr(laddrlen), uintptr(raddrlen), uintptr(unsafe.Pointer(lrsa)), uintptr(unsafe.Pointer(lrsalen)), uintptr(unsafe.Pointer(rrsa)), uintptr(unsafe.Pointer(rrsalen)), 0)
+ return
+}
+
+func WSARecv(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, overlapped *Overlapped, croutine *byte) (err error) {
+ r1, _, e1 := syscall.Syscall9(procWSARecv.Addr(), 7, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0, 0)
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func WSASend(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, overlapped *Overlapped, croutine *byte) (err error) {
+ r1, _, e1 := syscall.Syscall9(procWSASend.Addr(), 7, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0, 0)
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func WSARecvFrom(s Handle, bufs *WSABuf, bufcnt uint32, recvd *uint32, flags *uint32, from *RawSockaddrAny, fromlen *int32, overlapped *Overlapped, croutine *byte) (err error) {
+ r1, _, e1 := syscall.Syscall9(procWSARecvFrom.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)))
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func WSASendTo(s Handle, bufs *WSABuf, bufcnt uint32, sent *uint32, flags uint32, to *RawSockaddrAny, tolen int32, overlapped *Overlapped, croutine *byte) (err error) {
+ r1, _, e1 := syscall.Syscall9(procWSASendTo.Addr(), 9, uintptr(s), uintptr(unsafe.Pointer(bufs)), uintptr(bufcnt), uintptr(unsafe.Pointer(sent)), uintptr(flags), uintptr(unsafe.Pointer(to)), uintptr(tolen), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)))
+ if r1 == socket_error {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetHostByName(name string) (h *Hostent, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ return _GetHostByName(_p0)
+}
+
+func _GetHostByName(name *byte) (h *Hostent, err error) {
+ r0, _, e1 := syscall.Syscall(procgethostbyname.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0)
+ h = (*Hostent)(unsafe.Pointer(r0))
+ if h == nil {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetServByName(name string, proto string) (s *Servent, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ var _p1 *byte
+ _p1, err = syscall.BytePtrFromString(proto)
+ if err != nil {
+ return
+ }
+ return _GetServByName(_p0, _p1)
+}
+
+func _GetServByName(name *byte, proto *byte) (s *Servent, err error) {
+ r0, _, e1 := syscall.Syscall(procgetservbyname.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(proto)), 0)
+ s = (*Servent)(unsafe.Pointer(r0))
+ if s == nil {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func Ntohs(netshort uint16) (u uint16) {
+ r0, _, _ := syscall.Syscall(procntohs.Addr(), 1, uintptr(netshort), 0, 0)
+ u = uint16(r0)
+ return
+}
+
+func GetProtoByName(name string) (p *Protoent, err error) {
+ var _p0 *byte
+ _p0, err = syscall.BytePtrFromString(name)
+ if err != nil {
+ return
+ }
+ return _GetProtoByName(_p0)
+}
+
+func _GetProtoByName(name *byte) (p *Protoent, err error) {
+ r0, _, e1 := syscall.Syscall(procgetprotobyname.Addr(), 1, uintptr(unsafe.Pointer(name)), 0, 0)
+ p = (*Protoent)(unsafe.Pointer(r0))
+ if p == nil {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) {
+ var _p0 *uint16
+ _p0, status = syscall.UTF16PtrFromString(name)
+ if status != nil {
+ return
+ }
+ return _DnsQuery(_p0, qtype, options, extra, qrs, pr)
+}
+
+func _DnsQuery(name *uint16, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) {
+ r0, _, _ := syscall.Syscall6(procDnsQuery_W.Addr(), 6, uintptr(unsafe.Pointer(name)), uintptr(qtype), uintptr(options), uintptr(unsafe.Pointer(extra)), uintptr(unsafe.Pointer(qrs)), uintptr(unsafe.Pointer(pr)))
+ if r0 != 0 {
+ status = syscall.Errno(r0)
+ }
+ return
+}
+
+func DnsRecordListFree(rl *DNSRecord, freetype uint32) {
+ syscall.Syscall(procDnsRecordListFree.Addr(), 2, uintptr(unsafe.Pointer(rl)), uintptr(freetype), 0)
+ return
+}
+
+func DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) {
+ r0, _, _ := syscall.Syscall(procDnsNameCompare_W.Addr(), 2, uintptr(unsafe.Pointer(name1)), uintptr(unsafe.Pointer(name2)), 0)
+ same = r0 != 0
+ return
+}
+
+func GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) {
+ r0, _, _ := syscall.Syscall6(procGetAddrInfoW.Addr(), 4, uintptr(unsafe.Pointer(nodename)), uintptr(unsafe.Pointer(servicename)), uintptr(unsafe.Pointer(hints)), uintptr(unsafe.Pointer(result)), 0, 0)
+ if r0 != 0 {
+ sockerr = syscall.Errno(r0)
+ }
+ return
+}
+
+func FreeAddrInfoW(addrinfo *AddrinfoW) {
+ syscall.Syscall(procFreeAddrInfoW.Addr(), 1, uintptr(unsafe.Pointer(addrinfo)), 0, 0)
+ return
+}
+
+func GetIfEntry(pIfRow *MibIfRow) (errcode error) {
+ r0, _, _ := syscall.Syscall(procGetIfEntry.Addr(), 1, uintptr(unsafe.Pointer(pIfRow)), 0, 0)
+ if r0 != 0 {
+ errcode = syscall.Errno(r0)
+ }
+ return
+}
+
+func GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) {
+ r0, _, _ := syscall.Syscall(procGetAdaptersInfo.Addr(), 2, uintptr(unsafe.Pointer(ai)), uintptr(unsafe.Pointer(ol)), 0)
+ if r0 != 0 {
+ errcode = syscall.Errno(r0)
+ }
+ return
+}
+
+func SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) {
+ r1, _, e1 := syscall.Syscall(procSetFileCompletionNotificationModes.Addr(), 2, uintptr(handle), uintptr(flags), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func WSAEnumProtocols(protocols *int32, protocolBuffer *WSAProtocolInfo, bufferLength *uint32) (n int32, err error) {
+ r0, _, e1 := syscall.Syscall(procWSAEnumProtocolsW.Addr(), 3, uintptr(unsafe.Pointer(protocols)), uintptr(unsafe.Pointer(protocolBuffer)), uintptr(unsafe.Pointer(bufferLength)))
+ n = int32(r0)
+ if n == -1 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) {
+ r0, _, _ := syscall.Syscall6(procGetAdaptersAddresses.Addr(), 5, uintptr(family), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(adapterAddresses)), uintptr(unsafe.Pointer(sizePointer)), 0)
+ if r0 != 0 {
+ errcode = syscall.Errno(r0)
+ }
+ return
+}
+
+func GetACP() (acp uint32) {
+ r0, _, _ := syscall.Syscall(procGetACP.Addr(), 0, 0, 0, 0)
+ acp = uint32(r0)
+ return
+}
+
+func MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) {
+ r0, _, e1 := syscall.Syscall6(procMultiByteToWideChar.Addr(), 6, uintptr(codePage), uintptr(dwFlags), uintptr(unsafe.Pointer(str)), uintptr(nstr), uintptr(unsafe.Pointer(wchar)), uintptr(nwchar))
+ nwrite = int32(r0)
+ if nwrite == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procTranslateNameW.Addr(), 5, uintptr(unsafe.Pointer(accName)), uintptr(accNameFormat), uintptr(desiredNameFormat), uintptr(unsafe.Pointer(translatedName)), uintptr(unsafe.Pointer(nSize)), 0)
+ if r1&0xff == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetUserNameExW.Addr(), 3, uintptr(nameFormat), uintptr(unsafe.Pointer(nameBuffre)), uintptr(unsafe.Pointer(nSize)))
+ if r1&0xff == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) {
+ r0, _, _ := syscall.Syscall6(procNetUserGetInfo.Addr(), 4, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(userName)), uintptr(level), uintptr(unsafe.Pointer(buf)), 0, 0)
+ if r0 != 0 {
+ neterr = syscall.Errno(r0)
+ }
+ return
+}
+
+func NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) {
+ r0, _, _ := syscall.Syscall(procNetGetJoinInformation.Addr(), 3, uintptr(unsafe.Pointer(server)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(bufType)))
+ if r0 != 0 {
+ neterr = syscall.Errno(r0)
+ }
+ return
+}
+
+func NetApiBufferFree(buf *byte) (neterr error) {
+ r0, _, _ := syscall.Syscall(procNetApiBufferFree.Addr(), 1, uintptr(unsafe.Pointer(buf)), 0, 0)
+ if r0 != 0 {
+ neterr = syscall.Errno(r0)
+ }
+ return
+}
+
+func LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall9(procLookupAccountSidW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(refdDomainName)), uintptr(unsafe.Pointer(refdDomainNameLen)), uintptr(unsafe.Pointer(use)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall9(procLookupAccountNameW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidLen)), uintptr(unsafe.Pointer(refdDomainName)), uintptr(unsafe.Pointer(refdDomainNameLen)), uintptr(unsafe.Pointer(use)), 0, 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) {
+ r1, _, e1 := syscall.Syscall(procConvertSidToStringSidW.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(stringSid)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) {
+ r1, _, e1 := syscall.Syscall(procConvertStringSidToSidW.Addr(), 2, uintptr(unsafe.Pointer(stringSid)), uintptr(unsafe.Pointer(sid)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetLengthSid(sid *SID) (len uint32) {
+ r0, _, _ := syscall.Syscall(procGetLengthSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0)
+ len = uint32(r0)
+ return
+}
+
+func CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) {
+ r1, _, e1 := syscall.Syscall(procCopySid.Addr(), 3, uintptr(destSidLen), uintptr(unsafe.Pointer(destSid)), uintptr(unsafe.Pointer(srcSid)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) {
+ r1, _, e1 := syscall.Syscall12(procAllocateAndInitializeSid.Addr(), 11, uintptr(unsafe.Pointer(identAuth)), uintptr(subAuth), uintptr(subAuth0), uintptr(subAuth1), uintptr(subAuth2), uintptr(subAuth3), uintptr(subAuth4), uintptr(subAuth5), uintptr(subAuth6), uintptr(subAuth7), uintptr(unsafe.Pointer(sid)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func FreeSid(sid *SID) (err error) {
+ r1, _, e1 := syscall.Syscall(procFreeSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0)
+ if r1 != 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) {
+ r0, _, _ := syscall.Syscall(procEqualSid.Addr(), 2, uintptr(unsafe.Pointer(sid1)), uintptr(unsafe.Pointer(sid2)), 0)
+ isEqual = r0 != 0
+ return
+}
+
+func OpenProcessToken(h Handle, access uint32, token *Token) (err error) {
+ r1, _, e1 := syscall.Syscall(procOpenProcessToken.Addr(), 3, uintptr(h), uintptr(access), uintptr(unsafe.Pointer(token)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetTokenInformation(t Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall6(procGetTokenInformation.Addr(), 5, uintptr(t), uintptr(infoClass), uintptr(unsafe.Pointer(info)), uintptr(infoLen), uintptr(unsafe.Pointer(returnedLen)), 0)
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
+
+func GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) {
+ r1, _, e1 := syscall.Syscall(procGetUserProfileDirectoryW.Addr(), 3, uintptr(t), uintptr(unsafe.Pointer(dir)), uintptr(unsafe.Pointer(dirLen)))
+ if r1 == 0 {
+ if e1 != 0 {
+ err = errnoErr(e1)
+ } else {
+ err = syscall.EINVAL
+ }
+ }
+ return
+}
diff --git a/vendor/golang.org/x/text/LICENSE b/vendor/golang.org/x/text/LICENSE
new file mode 100644
index 0000000..6a66aea
--- /dev/null
+++ b/vendor/golang.org/x/text/LICENSE
@@ -0,0 +1,27 @@
+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/text/PATENTS b/vendor/golang.org/x/text/PATENTS
new file mode 100644
index 0000000..7330990
--- /dev/null
+++ b/vendor/golang.org/x/text/PATENTS
@@ -0,0 +1,22 @@
+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/text/README b/vendor/golang.org/x/text/README
new file mode 100644
index 0000000..4826fe8
--- /dev/null
+++ b/vendor/golang.org/x/text/README
@@ -0,0 +1,23 @@
+This repository holds supplementary Go libraries for text processing, many involving Unicode.
+
+To submit changes to this repository, see http://golang.org/doc/contribute.html.
+
+To generate the tables in this repository (except for the encoding tables),
+run go generate from this directory. By default tables are generated for the
+Unicode version in core and the CLDR version defined in
+golang.org/x/text/unicode/cldr.
+
+Running go generate will as a side effect create a DATA subdirectory in this
+directory which holds all files that are used as a source for generating the
+tables. This directory will also serve as a cache.
+
+Run
+
+ go test ./...
+
+from this directory to run all tests. Add the "-tags icu" flag to also run
+ICU conformance tests (if available). This requires that you have the correct
+ICU version installed on your system.
+
+TODO:
+- updating unversioned source files. \ No newline at end of file
diff --git a/vendor/golang.org/x/text/secure/bidirule/bidirule.go b/vendor/golang.org/x/text/secure/bidirule/bidirule.go
new file mode 100644
index 0000000..a7161bd
--- /dev/null
+++ b/vendor/golang.org/x/text/secure/bidirule/bidirule.go
@@ -0,0 +1,342 @@
+// 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 bidirule implements the Bidi Rule defined by RFC 5893.
+//
+// This package is under development. The API may change without notice and
+// without preserving backward compatibility.
+package bidirule
+
+import (
+ "errors"
+ "unicode/utf8"
+
+ "golang.org/x/text/transform"
+ "golang.org/x/text/unicode/bidi"
+)
+
+// This file contains an implementation of RFC 5893: Right-to-Left Scripts for
+// Internationalized Domain Names for Applications (IDNA)
+//
+// A label is an individual component of a domain name. Labels are usually
+// shown separated by dots; for example, the domain name "www.example.com" is
+// composed of three labels: "www", "example", and "com".
+//
+// An RTL label is a label that contains at least one character of class R, AL,
+// or AN. An LTR label is any label that is not an RTL label.
+//
+// A "Bidi domain name" is a domain name that contains at least one RTL label.
+//
+// The following guarantees can be made based on the above:
+//
+// o In a domain name consisting of only labels that satisfy the rule,
+// the requirements of Section 3 are satisfied. Note that even LTR
+// labels and pure ASCII labels have to be tested.
+//
+// o In a domain name consisting of only LDH labels (as defined in the
+// Definitions document [RFC5890]) and labels that satisfy the rule,
+// the requirements of Section 3 are satisfied as long as a label
+// that starts with an ASCII digit does not come after a
+// right-to-left label.
+//
+// No guarantee is given for other combinations.
+
+// ErrInvalid indicates a label is invalid according to the Bidi Rule.
+var ErrInvalid = errors.New("bidirule: failed Bidi Rule")
+
+type ruleState uint8
+
+const (
+ ruleInitial ruleState = iota
+ ruleLTR
+ ruleLTRFinal
+ ruleRTL
+ ruleRTLFinal
+ ruleInvalid
+)
+
+type ruleTransition struct {
+ next ruleState
+ mask uint16
+}
+
+var transitions = [...][2]ruleTransition{
+ // [2.1] The first character must be a character with Bidi property L, R, or
+ // AL. If it has the R or AL property, it is an RTL label; if it has the L
+ // property, it is an LTR label.
+ ruleInitial: {
+ {ruleLTRFinal, 1 << bidi.L},
+ {ruleRTLFinal, 1<<bidi.R | 1<<bidi.AL},
+ },
+ ruleRTL: {
+ // [2.3] In an RTL label, the end of the label must be a character with
+ // Bidi property R, AL, EN, or AN, followed by zero or more characters
+ // with Bidi property NSM.
+ {ruleRTLFinal, 1<<bidi.R | 1<<bidi.AL | 1<<bidi.EN | 1<<bidi.AN},
+
+ // [2.2] In an RTL label, only characters with the Bidi properties R,
+ // AL, AN, EN, ES, CS, ET, ON, BN, or NSM are allowed.
+ // We exclude the entries from [2.3]
+ {ruleRTL, 1<<bidi.ES | 1<<bidi.CS | 1<<bidi.ET | 1<<bidi.ON | 1<<bidi.BN | 1<<bidi.NSM},
+ },
+ ruleRTLFinal: {
+ // [2.3] In an RTL label, the end of the label must be a character with
+ // Bidi property R, AL, EN, or AN, followed by zero or more characters
+ // with Bidi property NSM.
+ {ruleRTLFinal, 1<<bidi.R | 1<<bidi.AL | 1<<bidi.EN | 1<<bidi.AN | 1<<bidi.NSM},
+
+ // [2.2] In an RTL label, only characters with the Bidi properties R,
+ // AL, AN, EN, ES, CS, ET, ON, BN, or NSM are allowed.
+ // We exclude the entries from [2.3] and NSM.
+ {ruleRTL, 1<<bidi.ES | 1<<bidi.CS | 1<<bidi.ET | 1<<bidi.ON | 1<<bidi.BN},
+ },
+ ruleLTR: {
+ // [2.6] In an LTR label, the end of the label must be a character with
+ // Bidi property L or EN, followed by zero or more characters with Bidi
+ // property NSM.
+ {ruleLTRFinal, 1<<bidi.L | 1<<bidi.EN},
+
+ // [2.5] In an LTR label, only characters with the Bidi properties L,
+ // EN, ES, CS, ET, ON, BN, or NSM are allowed.
+ // We exclude the entries from [2.6].
+ {ruleLTR, 1<<bidi.ES | 1<<bidi.CS | 1<<bidi.ET | 1<<bidi.ON | 1<<bidi.BN | 1<<bidi.NSM},
+ },
+ ruleLTRFinal: {
+ // [2.6] In an LTR label, the end of the label must be a character with
+ // Bidi property L or EN, followed by zero or more characters with Bidi
+ // property NSM.
+ {ruleLTRFinal, 1<<bidi.L | 1<<bidi.EN | 1<<bidi.NSM},
+
+ // [2.5] In an LTR label, only characters with the Bidi properties L,
+ // EN, ES, CS, ET, ON, BN, or NSM are allowed.
+ // We exclude the entries from [2.6].
+ {ruleLTR, 1<<bidi.ES | 1<<bidi.CS | 1<<bidi.ET | 1<<bidi.ON | 1<<bidi.BN},
+ },
+ ruleInvalid: {
+ {ruleInvalid, 0},
+ {ruleInvalid, 0},
+ },
+}
+
+// [2.4] In an RTL label, if an EN is present, no AN may be present, and
+// vice versa.
+const exclusiveRTL = uint16(1<<bidi.EN | 1<<bidi.AN)
+
+// From RFC 5893
+// An RTL label is a label that contains at least one character of type
+// R, AL, or AN.
+//
+// An LTR label is any label that is not an RTL label.
+
+// Direction reports the direction of the given label as defined by RFC 5893.
+// The Bidi Rule does not have to be applied to labels of the category
+// LeftToRight.
+func Direction(b []byte) bidi.Direction {
+ for i := 0; i < len(b); {
+ e, sz := bidi.Lookup(b[i:])
+ if sz == 0 {
+ i++
+ }
+ c := e.Class()
+ if c == bidi.R || c == bidi.AL || c == bidi.AN {
+ return bidi.RightToLeft
+ }
+ i += sz
+ }
+ return bidi.LeftToRight
+}
+
+// DirectionString reports the direction of the given label as defined by RFC
+// 5893. The Bidi Rule does not have to be applied to labels of the category
+// LeftToRight.
+func DirectionString(s string) bidi.Direction {
+ for i := 0; i < len(s); {
+ e, sz := bidi.LookupString(s[i:])
+ if sz == 0 {
+ i++
+ }
+ c := e.Class()
+ if c == bidi.R || c == bidi.AL || c == bidi.AN {
+ return bidi.RightToLeft
+ }
+ i += sz
+ }
+ return bidi.LeftToRight
+}
+
+// Valid reports whether b conforms to the BiDi rule.
+func Valid(b []byte) bool {
+ var t Transformer
+ if n, ok := t.advance(b); !ok || n < len(b) {
+ return false
+ }
+ return t.isFinal()
+}
+
+// ValidString reports whether s conforms to the BiDi rule.
+func ValidString(s string) bool {
+ var t Transformer
+ if n, ok := t.advanceString(s); !ok || n < len(s) {
+ return false
+ }
+ return t.isFinal()
+}
+
+// New returns a Transformer that verifies that input adheres to the Bidi Rule.
+func New() *Transformer {
+ return &Transformer{}
+}
+
+// Transformer implements transform.Transform.
+type Transformer struct {
+ state ruleState
+ hasRTL bool
+ seen uint16
+}
+
+// A rule can only be violated for "Bidi Domain names", meaning if one of the
+// following categories has been observed.
+func (t *Transformer) isRTL() bool {
+ const isRTL = 1<<bidi.R | 1<<bidi.AL | 1<<bidi.AN
+ return t.seen&isRTL != 0
+}
+
+func (t *Transformer) isFinal() bool {
+ if !t.isRTL() {
+ return true
+ }
+ return t.state == ruleLTRFinal || t.state == ruleRTLFinal || t.state == ruleInitial
+}
+
+// Reset implements transform.Transformer.
+func (t *Transformer) Reset() { *t = Transformer{} }
+
+// Transform implements transform.Transformer. This Transformer has state and
+// needs to be reset between uses.
+func (t *Transformer) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
+ if len(dst) < len(src) {
+ src = src[:len(dst)]
+ atEOF = false
+ err = transform.ErrShortDst
+ }
+ n, err1 := t.Span(src, atEOF)
+ copy(dst, src[:n])
+ if err == nil || err1 != nil && err1 != transform.ErrShortSrc {
+ err = err1
+ }
+ return n, n, err
+}
+
+// Span returns the first n bytes of src that conform to the Bidi rule.
+func (t *Transformer) Span(src []byte, atEOF bool) (n int, err error) {
+ if t.state == ruleInvalid && t.isRTL() {
+ return 0, ErrInvalid
+ }
+ n, ok := t.advance(src)
+ switch {
+ case !ok:
+ err = ErrInvalid
+ case n < len(src):
+ if !atEOF {
+ err = transform.ErrShortSrc
+ break
+ }
+ err = ErrInvalid
+ case !t.isFinal():
+ err = ErrInvalid
+ }
+ return n, err
+}
+
+// Precomputing the ASCII values decreases running time for the ASCII fast path
+// by about 30%.
+var asciiTable [128]bidi.Properties
+
+func init() {
+ for i := range asciiTable {
+ p, _ := bidi.LookupRune(rune(i))
+ asciiTable[i] = p
+ }
+}
+
+func (t *Transformer) advance(s []byte) (n int, ok bool) {
+ var e bidi.Properties
+ var sz int
+ for n < len(s) {
+ if s[n] < utf8.RuneSelf {
+ e, sz = asciiTable[s[n]], 1
+ } else {
+ e, sz = bidi.Lookup(s[n:])
+ if sz <= 1 {
+ if sz == 1 {
+ // We always consider invalid UTF-8 to be invalid, even if
+ // the string has not yet been determined to be RTL.
+ // TODO: is this correct?
+ return n, false
+ }
+ return n, true // incomplete UTF-8 encoding
+ }
+ }
+ // TODO: using CompactClass would result in noticeable speedup.
+ // See unicode/bidi/prop.go:Properties.CompactClass.
+ c := uint16(1 << e.Class())
+ t.seen |= c
+ if t.seen&exclusiveRTL == exclusiveRTL {
+ t.state = ruleInvalid
+ return n, false
+ }
+ switch tr := transitions[t.state]; {
+ case tr[0].mask&c != 0:
+ t.state = tr[0].next
+ case tr[1].mask&c != 0:
+ t.state = tr[1].next
+ default:
+ t.state = ruleInvalid
+ if t.isRTL() {
+ return n, false
+ }
+ }
+ n += sz
+ }
+ return n, true
+}
+
+func (t *Transformer) advanceString(s string) (n int, ok bool) {
+ var e bidi.Properties
+ var sz int
+ for n < len(s) {
+ if s[n] < utf8.RuneSelf {
+ e, sz = asciiTable[s[n]], 1
+ } else {
+ e, sz = bidi.LookupString(s[n:])
+ if sz <= 1 {
+ if sz == 1 {
+ return n, false // invalid UTF-8
+ }
+ return n, true // incomplete UTF-8 encoding
+ }
+ }
+ // TODO: using CompactClass results in noticeable speedup.
+ // See unicode/bidi/prop.go:Properties.CompactClass.
+ c := uint16(1 << e.Class())
+ t.seen |= c
+ if t.seen&exclusiveRTL == exclusiveRTL {
+ t.state = ruleInvalid
+ return n, false
+ }
+ switch tr := transitions[t.state]; {
+ case tr[0].mask&c != 0:
+ t.state = tr[0].next
+ case tr[1].mask&c != 0:
+ t.state = tr[1].next
+ default:
+ t.state = ruleInvalid
+ if t.isRTL() {
+ return n, false
+ }
+ }
+ n += sz
+ }
+ return n, true
+}
diff --git a/vendor/golang.org/x/text/transform/transform.go b/vendor/golang.org/x/text/transform/transform.go
new file mode 100644
index 0000000..fe47b9b
--- /dev/null
+++ b/vendor/golang.org/x/text/transform/transform.go
@@ -0,0 +1,705 @@
+// 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 transform provides reader and writer wrappers that transform the
+// bytes passing through as well as various transformations. Example
+// transformations provided by other packages include normalization and
+// conversion between character sets.
+package transform // import "golang.org/x/text/transform"
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "unicode/utf8"
+)
+
+var (
+ // ErrShortDst means that the destination buffer was too short to
+ // receive all of the transformed bytes.
+ ErrShortDst = errors.New("transform: short destination buffer")
+
+ // ErrShortSrc means that the source buffer has insufficient data to
+ // complete the transformation.
+ ErrShortSrc = errors.New("transform: short source buffer")
+
+ // ErrEndOfSpan means that the input and output (the transformed input)
+ // are not identical.
+ ErrEndOfSpan = errors.New("transform: input and output are not identical")
+
+ // errInconsistentByteCount means that Transform returned success (nil
+ // error) but also returned nSrc inconsistent with the src argument.
+ errInconsistentByteCount = errors.New("transform: inconsistent byte count returned")
+
+ // errShortInternal means that an internal buffer is not large enough
+ // to make progress and the Transform operation must be aborted.
+ errShortInternal = errors.New("transform: short internal buffer")
+)
+
+// Transformer transforms bytes.
+type Transformer interface {
+ // Transform writes to dst the transformed bytes read from src, and
+ // returns the number of dst bytes written and src bytes read. The
+ // atEOF argument tells whether src represents the last bytes of the
+ // input.
+ //
+ // Callers should always process the nDst bytes produced and account
+ // for the nSrc bytes consumed before considering the error err.
+ //
+ // A nil error means that all of the transformed bytes (whether freshly
+ // transformed from src or left over from previous Transform calls)
+ // were written to dst. A nil error can be returned regardless of
+ // whether atEOF is true. If err is nil then nSrc must equal len(src);
+ // the converse is not necessarily true.
+ //
+ // ErrShortDst means that dst was too short to receive all of the
+ // transformed bytes. ErrShortSrc means that src had insufficient data
+ // to complete the transformation. If both conditions apply, then
+ // either error may be returned. Other than the error conditions listed
+ // here, implementations are free to report other errors that arise.
+ Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error)
+
+ // Reset resets the state and allows a Transformer to be reused.
+ Reset()
+}
+
+// SpanningTransformer extends the Transformer interface with a Span method
+// that determines how much of the input already conforms to the Transformer.
+type SpanningTransformer interface {
+ Transformer
+
+ // Span returns a position in src such that transforming src[:n] results in
+ // identical output src[:n] for these bytes. It does not necessarily return
+ // the largest such n. The atEOF argument tells whether src represents the
+ // last bytes of the input.
+ //
+ // Callers should always account for the n bytes consumed before
+ // considering the error err.
+ //
+ // A nil error means that all input bytes are known to be identical to the
+ // output produced by the Transformer. A nil error can be be returned
+ // regardless of whether atEOF is true. If err is nil, then then n must
+ // equal len(src); the converse is not necessarily true.
+ //
+ // ErrEndOfSpan means that the Transformer output may differ from the
+ // input after n bytes. Note that n may be len(src), meaning that the output
+ // would contain additional bytes after otherwise identical output.
+ // ErrShortSrc means that src had insufficient data to determine whether the
+ // remaining bytes would change. Other than the error conditions listed
+ // here, implementations are free to report other errors that arise.
+ //
+ // Calling Span can modify the Transformer state as a side effect. In
+ // effect, it does the transformation just as calling Transform would, only
+ // without copying to a destination buffer and only up to a point it can
+ // determine the input and output bytes are the same. This is obviously more
+ // limited than calling Transform, but can be more efficient in terms of
+ // copying and allocating buffers. Calls to Span and Transform may be
+ // interleaved.
+ Span(src []byte, atEOF bool) (n int, err error)
+}
+
+// NopResetter can be embedded by implementations of Transformer to add a nop
+// Reset method.
+type NopResetter struct{}
+
+// Reset implements the Reset method of the Transformer interface.
+func (NopResetter) Reset() {}
+
+// Reader wraps another io.Reader by transforming the bytes read.
+type Reader struct {
+ r io.Reader
+ t Transformer
+ err error
+
+ // dst[dst0:dst1] contains bytes that have been transformed by t but
+ // not yet copied out via Read.
+ dst []byte
+ dst0, dst1 int
+
+ // src[src0:src1] contains bytes that have been read from r but not
+ // yet transformed through t.
+ src []byte
+ src0, src1 int
+
+ // transformComplete is whether the transformation is complete,
+ // regardless of whether or not it was successful.
+ transformComplete bool
+}
+
+const defaultBufSize = 4096
+
+// NewReader returns a new Reader that wraps r by transforming the bytes read
+// via t. It calls Reset on t.
+func NewReader(r io.Reader, t Transformer) *Reader {
+ t.Reset()
+ return &Reader{
+ r: r,
+ t: t,
+ dst: make([]byte, defaultBufSize),
+ src: make([]byte, defaultBufSize),
+ }
+}
+
+// Read implements the io.Reader interface.
+func (r *Reader) Read(p []byte) (int, error) {
+ n, err := 0, error(nil)
+ for {
+ // Copy out any transformed bytes and return the final error if we are done.
+ if r.dst0 != r.dst1 {
+ n = copy(p, r.dst[r.dst0:r.dst1])
+ r.dst0 += n
+ if r.dst0 == r.dst1 && r.transformComplete {
+ return n, r.err
+ }
+ return n, nil
+ } else if r.transformComplete {
+ return 0, r.err
+ }
+
+ // Try to transform some source bytes, or to flush the transformer if we
+ // are out of source bytes. We do this even if r.r.Read returned an error.
+ // As the io.Reader documentation says, "process the n > 0 bytes returned
+ // before considering the error".
+ if r.src0 != r.src1 || r.err != nil {
+ r.dst0 = 0
+ r.dst1, n, err = r.t.Transform(r.dst, r.src[r.src0:r.src1], r.err == io.EOF)
+ r.src0 += n
+
+ switch {
+ case err == nil:
+ if r.src0 != r.src1 {
+ r.err = errInconsistentByteCount
+ }
+ // The Transform call was successful; we are complete if we
+ // cannot read more bytes into src.
+ r.transformComplete = r.err != nil
+ continue
+ case err == ErrShortDst && (r.dst1 != 0 || n != 0):
+ // Make room in dst by copying out, and try again.
+ continue
+ case err == ErrShortSrc && r.src1-r.src0 != len(r.src) && r.err == nil:
+ // Read more bytes into src via the code below, and try again.
+ default:
+ r.transformComplete = true
+ // The reader error (r.err) takes precedence over the
+ // transformer error (err) unless r.err is nil or io.EOF.
+ if r.err == nil || r.err == io.EOF {
+ r.err = err
+ }
+ continue
+ }
+ }
+
+ // Move any untransformed source bytes to the start of the buffer
+ // and read more bytes.
+ if r.src0 != 0 {
+ r.src0, r.src1 = 0, copy(r.src, r.src[r.src0:r.src1])
+ }
+ n, r.err = r.r.Read(r.src[r.src1:])
+ r.src1 += n
+ }
+}
+
+// TODO: implement ReadByte (and ReadRune??).
+
+// Writer wraps another io.Writer by transforming the bytes read.
+// The user needs to call Close to flush unwritten bytes that may
+// be buffered.
+type Writer struct {
+ w io.Writer
+ t Transformer
+ dst []byte
+
+ // src[:n] contains bytes that have not yet passed through t.
+ src []byte
+ n int
+}
+
+// NewWriter returns a new Writer that wraps w by transforming the bytes written
+// via t. It calls Reset on t.
+func NewWriter(w io.Writer, t Transformer) *Writer {
+ t.Reset()
+ return &Writer{
+ w: w,
+ t: t,
+ dst: make([]byte, defaultBufSize),
+ src: make([]byte, defaultBufSize),
+ }
+}
+
+// Write implements the io.Writer interface. If there are not enough
+// bytes available to complete a Transform, the bytes will be buffered
+// for the next write. Call Close to convert the remaining bytes.
+func (w *Writer) Write(data []byte) (n int, err error) {
+ src := data
+ if w.n > 0 {
+ // Append bytes from data to the last remainder.
+ // TODO: limit the amount copied on first try.
+ n = copy(w.src[w.n:], data)
+ w.n += n
+ src = w.src[:w.n]
+ }
+ for {
+ nDst, nSrc, err := w.t.Transform(w.dst, src, false)
+ if _, werr := w.w.Write(w.dst[:nDst]); werr != nil {
+ return n, werr
+ }
+ src = src[nSrc:]
+ if w.n == 0 {
+ n += nSrc
+ } else if len(src) <= n {
+ // Enough bytes from w.src have been consumed. We make src point
+ // to data instead to reduce the copying.
+ w.n = 0
+ n -= len(src)
+ src = data[n:]
+ if n < len(data) && (err == nil || err == ErrShortSrc) {
+ continue
+ }
+ }
+ switch err {
+ case ErrShortDst:
+ // This error is okay as long as we are making progress.
+ if nDst > 0 || nSrc > 0 {
+ continue
+ }
+ case ErrShortSrc:
+ if len(src) < len(w.src) {
+ m := copy(w.src, src)
+ // If w.n > 0, bytes from data were already copied to w.src and n
+ // was already set to the number of bytes consumed.
+ if w.n == 0 {
+ n += m
+ }
+ w.n = m
+ err = nil
+ } else if nDst > 0 || nSrc > 0 {
+ // Not enough buffer to store the remainder. Keep processing as
+ // long as there is progress. Without this case, transforms that
+ // require a lookahead larger than the buffer may result in an
+ // error. This is not something one may expect to be common in
+ // practice, but it may occur when buffers are set to small
+ // sizes during testing.
+ continue
+ }
+ case nil:
+ if w.n > 0 {
+ err = errInconsistentByteCount
+ }
+ }
+ return n, err
+ }
+}
+
+// Close implements the io.Closer interface.
+func (w *Writer) Close() error {
+ src := w.src[:w.n]
+ for {
+ nDst, nSrc, err := w.t.Transform(w.dst, src, true)
+ if _, werr := w.w.Write(w.dst[:nDst]); werr != nil {
+ return werr
+ }
+ if err != ErrShortDst {
+ return err
+ }
+ src = src[nSrc:]
+ }
+}
+
+type nop struct{ NopResetter }
+
+func (nop) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
+ n := copy(dst, src)
+ if n < len(src) {
+ err = ErrShortDst
+ }
+ return n, n, err
+}
+
+func (nop) Span(src []byte, atEOF bool) (n int, err error) {
+ return len(src), nil
+}
+
+type discard struct{ NopResetter }
+
+func (discard) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
+ return 0, len(src), nil
+}
+
+var (
+ // Discard is a Transformer for which all Transform calls succeed
+ // by consuming all bytes and writing nothing.
+ Discard Transformer = discard{}
+
+ // Nop is a SpanningTransformer that copies src to dst.
+ Nop SpanningTransformer = nop{}
+)
+
+// chain is a sequence of links. A chain with N Transformers has N+1 links and
+// N+1 buffers. Of those N+1 buffers, the first and last are the src and dst
+// buffers given to chain.Transform and the middle N-1 buffers are intermediate
+// buffers owned by the chain. The i'th link transforms bytes from the i'th
+// buffer chain.link[i].b at read offset chain.link[i].p to the i+1'th buffer
+// chain.link[i+1].b at write offset chain.link[i+1].n, for i in [0, N).
+type chain struct {
+ link []link
+ err error
+ // errStart is the index at which the error occurred plus 1. Processing
+ // errStart at this level at the next call to Transform. As long as
+ // errStart > 0, chain will not consume any more source bytes.
+ errStart int
+}
+
+func (c *chain) fatalError(errIndex int, err error) {
+ if i := errIndex + 1; i > c.errStart {
+ c.errStart = i
+ c.err = err
+ }
+}
+
+type link struct {
+ t Transformer
+ // b[p:n] holds the bytes to be transformed by t.
+ b []byte
+ p int
+ n int
+}
+
+func (l *link) src() []byte {
+ return l.b[l.p:l.n]
+}
+
+func (l *link) dst() []byte {
+ return l.b[l.n:]
+}
+
+// Chain returns a Transformer that applies t in sequence.
+func Chain(t ...Transformer) Transformer {
+ if len(t) == 0 {
+ return nop{}
+ }
+ c := &chain{link: make([]link, len(t)+1)}
+ for i, tt := range t {
+ c.link[i].t = tt
+ }
+ // Allocate intermediate buffers.
+ b := make([][defaultBufSize]byte, len(t)-1)
+ for i := range b {
+ c.link[i+1].b = b[i][:]
+ }
+ return c
+}
+
+// Reset resets the state of Chain. It calls Reset on all the Transformers.
+func (c *chain) Reset() {
+ for i, l := range c.link {
+ if l.t != nil {
+ l.t.Reset()
+ }
+ c.link[i].p, c.link[i].n = 0, 0
+ }
+}
+
+// TODO: make chain use Span (is going to be fun to implement!)
+
+// Transform applies the transformers of c in sequence.
+func (c *chain) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
+ // Set up src and dst in the chain.
+ srcL := &c.link[0]
+ dstL := &c.link[len(c.link)-1]
+ srcL.b, srcL.p, srcL.n = src, 0, len(src)
+ dstL.b, dstL.n = dst, 0
+ var lastFull, needProgress bool // for detecting progress
+
+ // i is the index of the next Transformer to apply, for i in [low, high].
+ // low is the lowest index for which c.link[low] may still produce bytes.
+ // high is the highest index for which c.link[high] has a Transformer.
+ // The error returned by Transform determines whether to increase or
+ // decrease i. We try to completely fill a buffer before converting it.
+ for low, i, high := c.errStart, c.errStart, len(c.link)-2; low <= i && i <= high; {
+ in, out := &c.link[i], &c.link[i+1]
+ nDst, nSrc, err0 := in.t.Transform(out.dst(), in.src(), atEOF && low == i)
+ out.n += nDst
+ in.p += nSrc
+ if i > 0 && in.p == in.n {
+ in.p, in.n = 0, 0
+ }
+ needProgress, lastFull = lastFull, false
+ switch err0 {
+ case ErrShortDst:
+ // Process the destination buffer next. Return if we are already
+ // at the high index.
+ if i == high {
+ return dstL.n, srcL.p, ErrShortDst
+ }
+ if out.n != 0 {
+ i++
+ // If the Transformer at the next index is not able to process any
+ // source bytes there is nothing that can be done to make progress
+ // and the bytes will remain unprocessed. lastFull is used to
+ // detect this and break out of the loop with a fatal error.
+ lastFull = true
+ continue
+ }
+ // The destination buffer was too small, but is completely empty.
+ // Return a fatal error as this transformation can never complete.
+ c.fatalError(i, errShortInternal)
+ case ErrShortSrc:
+ if i == 0 {
+ // Save ErrShortSrc in err. All other errors take precedence.
+ err = ErrShortSrc
+ break
+ }
+ // Source bytes were depleted before filling up the destination buffer.
+ // Verify we made some progress, move the remaining bytes to the errStart
+ // and try to get more source bytes.
+ if needProgress && nSrc == 0 || in.n-in.p == len(in.b) {
+ // There were not enough source bytes to proceed while the source
+ // buffer cannot hold any more bytes. Return a fatal error as this
+ // transformation can never complete.
+ c.fatalError(i, errShortInternal)
+ break
+ }
+ // in.b is an internal buffer and we can make progress.
+ in.p, in.n = 0, copy(in.b, in.src())
+ fallthrough
+ case nil:
+ // if i == low, we have depleted the bytes at index i or any lower levels.
+ // In that case we increase low and i. In all other cases we decrease i to
+ // fetch more bytes before proceeding to the next index.
+ if i > low {
+ i--
+ continue
+ }
+ default:
+ c.fatalError(i, err0)
+ }
+ // Exhausted level low or fatal error: increase low and continue
+ // to process the bytes accepted so far.
+ i++
+ low = i
+ }
+
+ // If c.errStart > 0, this means we found a fatal error. We will clear
+ // all upstream buffers. At this point, no more progress can be made
+ // downstream, as Transform would have bailed while handling ErrShortDst.
+ if c.errStart > 0 {
+ for i := 1; i < c.errStart; i++ {
+ c.link[i].p, c.link[i].n = 0, 0
+ }
+ err, c.errStart, c.err = c.err, 0, nil
+ }
+ return dstL.n, srcL.p, err
+}
+
+// Deprecated: use runes.Remove instead.
+func RemoveFunc(f func(r rune) bool) Transformer {
+ return removeF(f)
+}
+
+type removeF func(r rune) bool
+
+func (removeF) Reset() {}
+
+// Transform implements the Transformer interface.
+func (t removeF) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
+ for r, sz := rune(0), 0; len(src) > 0; src = src[sz:] {
+
+ if r = rune(src[0]); r < utf8.RuneSelf {
+ sz = 1
+ } else {
+ r, sz = utf8.DecodeRune(src)
+
+ if sz == 1 {
+ // Invalid rune.
+ if !atEOF && !utf8.FullRune(src) {
+ err = ErrShortSrc
+ break
+ }
+ // We replace illegal bytes with RuneError. Not doing so might
+ // otherwise turn a sequence of invalid UTF-8 into valid UTF-8.
+ // The resulting byte sequence may subsequently contain runes
+ // for which t(r) is true that were passed unnoticed.
+ if !t(r) {
+ if nDst+3 > len(dst) {
+ err = ErrShortDst
+ break
+ }
+ nDst += copy(dst[nDst:], "\uFFFD")
+ }
+ nSrc++
+ continue
+ }
+ }
+
+ if !t(r) {
+ if nDst+sz > len(dst) {
+ err = ErrShortDst
+ break
+ }
+ nDst += copy(dst[nDst:], src[:sz])
+ }
+ nSrc += sz
+ }
+ return
+}
+
+// grow returns a new []byte that is longer than b, and copies the first n bytes
+// of b to the start of the new slice.
+func grow(b []byte, n int) []byte {
+ m := len(b)
+ if m <= 32 {
+ m = 64
+ } else if m <= 256 {
+ m *= 2
+ } else {
+ m += m >> 1
+ }
+ buf := make([]byte, m)
+ copy(buf, b[:n])
+ return buf
+}
+
+const initialBufSize = 128
+
+// String returns a string with the result of converting s[:n] using t, where
+// n <= len(s). If err == nil, n will be len(s). It calls Reset on t.
+func String(t Transformer, s string) (result string, n int, err error) {
+ t.Reset()
+ if s == "" {
+ // Fast path for the common case for empty input. Results in about a
+ // 86% reduction of running time for BenchmarkStringLowerEmpty.
+ if _, _, err := t.Transform(nil, nil, true); err == nil {
+ return "", 0, nil
+ }
+ }
+
+ // Allocate only once. Note that both dst and src escape when passed to
+ // Transform.
+ buf := [2 * initialBufSize]byte{}
+ dst := buf[:initialBufSize:initialBufSize]
+ src := buf[initialBufSize : 2*initialBufSize]
+
+ // The input string s is transformed in multiple chunks (starting with a
+ // chunk size of initialBufSize). nDst and nSrc are per-chunk (or
+ // per-Transform-call) indexes, pDst and pSrc are overall indexes.
+ nDst, nSrc := 0, 0
+ pDst, pSrc := 0, 0
+
+ // pPrefix is the length of a common prefix: the first pPrefix bytes of the
+ // result will equal the first pPrefix bytes of s. It is not guaranteed to
+ // be the largest such value, but if pPrefix, len(result) and len(s) are
+ // all equal after the final transform (i.e. calling Transform with atEOF
+ // being true returned nil error) then we don't need to allocate a new
+ // result string.
+ pPrefix := 0
+ for {
+ // Invariant: pDst == pPrefix && pSrc == pPrefix.
+
+ n := copy(src, s[pSrc:])
+ nDst, nSrc, err = t.Transform(dst, src[:n], pSrc+n == len(s))
+ pDst += nDst
+ pSrc += nSrc
+
+ // TODO: let transformers implement an optional Spanner interface, akin
+ // to norm's QuickSpan. This would even allow us to avoid any allocation.
+ if !bytes.Equal(dst[:nDst], src[:nSrc]) {
+ break
+ }
+ pPrefix = pSrc
+ if err == ErrShortDst {
+ // A buffer can only be short if a transformer modifies its input.
+ break
+ } else if err == ErrShortSrc {
+ if nSrc == 0 {
+ // No progress was made.
+ break
+ }
+ // Equal so far and !atEOF, so continue checking.
+ } else if err != nil || pPrefix == len(s) {
+ return string(s[:pPrefix]), pPrefix, err
+ }
+ }
+ // Post-condition: pDst == pPrefix + nDst && pSrc == pPrefix + nSrc.
+
+ // We have transformed the first pSrc bytes of the input s to become pDst
+ // transformed bytes. Those transformed bytes are discontiguous: the first
+ // pPrefix of them equal s[:pPrefix] and the last nDst of them equal
+ // dst[:nDst]. We copy them around, into a new dst buffer if necessary, so
+ // that they become one contiguous slice: dst[:pDst].
+ if pPrefix != 0 {
+ newDst := dst
+ if pDst > len(newDst) {
+ newDst = make([]byte, len(s)+nDst-nSrc)
+ }
+ copy(newDst[pPrefix:pDst], dst[:nDst])
+ copy(newDst[:pPrefix], s[:pPrefix])
+ dst = newDst
+ }
+
+ // Prevent duplicate Transform calls with atEOF being true at the end of
+ // the input. Also return if we have an unrecoverable error.
+ if (err == nil && pSrc == len(s)) ||
+ (err != nil && err != ErrShortDst && err != ErrShortSrc) {
+ return string(dst[:pDst]), pSrc, err
+ }
+
+ // Transform the remaining input, growing dst and src buffers as necessary.
+ for {
+ n := copy(src, s[pSrc:])
+ nDst, nSrc, err := t.Transform(dst[pDst:], src[:n], pSrc+n == len(s))
+ pDst += nDst
+ pSrc += nSrc
+
+ // If we got ErrShortDst or ErrShortSrc, do not grow as long as we can
+ // make progress. This may avoid excessive allocations.
+ if err == ErrShortDst {
+ if nDst == 0 {
+ dst = grow(dst, pDst)
+ }
+ } else if err == ErrShortSrc {
+ if nSrc == 0 {
+ src = grow(src, 0)
+ }
+ } else if err != nil || pSrc == len(s) {
+ return string(dst[:pDst]), pSrc, err
+ }
+ }
+}
+
+// Bytes returns a new byte slice with the result of converting b[:n] using t,
+// where n <= len(b). If err == nil, n will be len(b). It calls Reset on t.
+func Bytes(t Transformer, b []byte) (result []byte, n int, err error) {
+ return doAppend(t, 0, make([]byte, len(b)), b)
+}
+
+// Append appends the result of converting src[:n] using t to dst, where
+// n <= len(src), If err == nil, n will be len(src). It calls Reset on t.
+func Append(t Transformer, dst, src []byte) (result []byte, n int, err error) {
+ if len(dst) == cap(dst) {
+ n := len(src) + len(dst) // It is okay for this to be 0.
+ b := make([]byte, n)
+ dst = b[:copy(b, dst)]
+ }
+ return doAppend(t, len(dst), dst[:cap(dst)], src)
+}
+
+func doAppend(t Transformer, pDst int, dst, src []byte) (result []byte, n int, err error) {
+ t.Reset()
+ pSrc := 0
+ for {
+ nDst, nSrc, err := t.Transform(dst[pDst:], src[pSrc:], true)
+ pDst += nDst
+ pSrc += nSrc
+ if err != ErrShortDst {
+ return dst[:pDst], pSrc, err
+ }
+
+ // Grow the destination buffer, but do not grow as long as we can make
+ // progress. This may avoid excessive allocations.
+ if nDst == 0 {
+ dst = grow(dst, pDst)
+ }
+ }
+}
diff --git a/vendor/golang.org/x/text/unicode/bidi/bidi.go b/vendor/golang.org/x/text/unicode/bidi/bidi.go
new file mode 100644
index 0000000..3fc4a62
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/bidi/bidi.go
@@ -0,0 +1,198 @@
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:generate go run gen.go gen_trieval.go gen_ranges.go
+
+// Package bidi contains functionality for bidirectional text support.
+//
+// See http://www.unicode.org/reports/tr9.
+//
+// NOTE: UNDER CONSTRUCTION. This API may change in backwards incompatible ways
+// and without notice.
+package bidi // import "golang.org/x/text/unicode/bidi"
+
+// TODO:
+// The following functionality would not be hard to implement, but hinges on
+// the definition of a Segmenter interface. For now this is up to the user.
+// - Iterate over paragraphs
+// - Segmenter to iterate over runs directly from a given text.
+// Also:
+// - Transformer for reordering?
+// - Transformer (validator, really) for Bidi Rule.
+
+// This API tries to avoid dealing with embedding levels for now. Under the hood
+// these will be computed, but the question is to which extent the user should
+// know they exist. We should at some point allow the user to specify an
+// embedding hierarchy, though.
+
+// A Direction indicates the overall flow of text.
+type Direction int
+
+const (
+ // LeftToRight indicates the text contains no right-to-left characters and
+ // that either there are some left-to-right characters or the option
+ // DefaultDirection(LeftToRight) was passed.
+ LeftToRight Direction = iota
+
+ // RightToLeft indicates the text contains no left-to-right characters and
+ // that either there are some right-to-left characters or the option
+ // DefaultDirection(RightToLeft) was passed.
+ RightToLeft
+
+ // Mixed indicates text contains both left-to-right and right-to-left
+ // characters.
+ Mixed
+
+ // Neutral means that text contains no left-to-right and right-to-left
+ // characters and that no default direction has been set.
+ Neutral
+)
+
+type options struct{}
+
+// An Option is an option for Bidi processing.
+type Option func(*options)
+
+// ICU allows the user to define embedding levels. This may be used, for example,
+// to use hierarchical structure of markup languages to define embeddings.
+// The following option may be a way to expose this functionality in this API.
+// // LevelFunc sets a function that associates nesting levels with the given text.
+// // The levels function will be called with monotonically increasing values for p.
+// func LevelFunc(levels func(p int) int) Option {
+// panic("unimplemented")
+// }
+
+// DefaultDirection sets the default direction for a Paragraph. The direction is
+// overridden if the text contains directional characters.
+func DefaultDirection(d Direction) Option {
+ panic("unimplemented")
+}
+
+// A Paragraph holds a single Paragraph for Bidi processing.
+type Paragraph struct {
+ // buffers
+}
+
+// SetBytes configures p for the given paragraph text. It replaces text
+// previously set by SetBytes or SetString. If b contains a paragraph separator
+// it will only process the first paragraph and report the number of bytes
+// consumed from b including this separator. Error may be non-nil if options are
+// given.
+func (p *Paragraph) SetBytes(b []byte, opts ...Option) (n int, err error) {
+ panic("unimplemented")
+}
+
+// SetString configures p for the given paragraph text. It replaces text
+// previously set by SetBytes or SetString. If b contains a paragraph separator
+// it will only process the first paragraph and report the number of bytes
+// consumed from b including this separator. Error may be non-nil if options are
+// given.
+func (p *Paragraph) SetString(s string, opts ...Option) (n int, err error) {
+ panic("unimplemented")
+}
+
+// IsLeftToRight reports whether the principle direction of rendering for this
+// paragraphs is left-to-right. If this returns false, the principle direction
+// of rendering is right-to-left.
+func (p *Paragraph) IsLeftToRight() bool {
+ panic("unimplemented")
+}
+
+// Direction returns the direction of the text of this paragraph.
+//
+// The direction may be LeftToRight, RightToLeft, Mixed, or Neutral.
+func (p *Paragraph) Direction() Direction {
+ panic("unimplemented")
+}
+
+// RunAt reports the Run at the given position of the input text.
+//
+// This method can be used for computing line breaks on paragraphs.
+func (p *Paragraph) RunAt(pos int) Run {
+ panic("unimplemented")
+}
+
+// Order computes the visual ordering of all the runs in a Paragraph.
+func (p *Paragraph) Order() (Ordering, error) {
+ panic("unimplemented")
+}
+
+// Line computes the visual ordering of runs for a single line starting and
+// ending at the given positions in the original text.
+func (p *Paragraph) Line(start, end int) (Ordering, error) {
+ panic("unimplemented")
+}
+
+// An Ordering holds the computed visual order of runs of a Paragraph. Calling
+// SetBytes or SetString on the originating Paragraph invalidates an Ordering.
+// The methods of an Ordering should only be called by one goroutine at a time.
+type Ordering struct{}
+
+// Direction reports the directionality of the runs.
+//
+// The direction may be LeftToRight, RightToLeft, Mixed, or Neutral.
+func (o *Ordering) Direction() Direction {
+ panic("unimplemented")
+}
+
+// NumRuns returns the number of runs.
+func (o *Ordering) NumRuns() int {
+ panic("unimplemented")
+}
+
+// Run returns the ith run within the ordering.
+func (o *Ordering) Run(i int) Run {
+ panic("unimplemented")
+}
+
+// TODO: perhaps with options.
+// // Reorder creates a reader that reads the runes in visual order per character.
+// // Modifiers remain after the runes they modify.
+// func (l *Runs) Reorder() io.Reader {
+// panic("unimplemented")
+// }
+
+// A Run is a continuous sequence of characters of a single direction.
+type Run struct {
+}
+
+// String returns the text of the run in its original order.
+func (r *Run) String() string {
+ panic("unimplemented")
+}
+
+// Bytes returns the text of the run in its original order.
+func (r *Run) Bytes() []byte {
+ panic("unimplemented")
+}
+
+// TODO: methods for
+// - Display order
+// - headers and footers
+// - bracket replacement.
+
+// Direction reports the direction of the run.
+func (r *Run) Direction() Direction {
+ panic("unimplemented")
+}
+
+// Position of the Run within the text passed to SetBytes or SetString of the
+// originating Paragraph value.
+func (r *Run) Pos() (start, end int) {
+ panic("unimplemented")
+}
+
+// AppendReverse reverses the order of characters of in, appends them to out,
+// and returns the result. Modifiers will still follow the runes they modify.
+// Brackets are replaced with their counterparts.
+func AppendReverse(out, in []byte) []byte {
+ panic("unimplemented")
+}
+
+// ReverseString reverses the order of characters in s and returns a new string.
+// Modifiers will still follow the runes they modify. Brackets are replaced with
+// their counterparts.
+func ReverseString(s string) string {
+ panic("unimplemented")
+}
diff --git a/vendor/golang.org/x/text/unicode/bidi/bracket.go b/vendor/golang.org/x/text/unicode/bidi/bracket.go
new file mode 100644
index 0000000..601e259
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/bidi/bracket.go
@@ -0,0 +1,335 @@
+// Copyright 2015 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 bidi
+
+import (
+ "container/list"
+ "fmt"
+ "sort"
+)
+
+// This file contains a port of the reference implementation of the
+// Bidi Parentheses Algorithm:
+// http://www.unicode.org/Public/PROGRAMS/BidiReferenceJava/BidiPBAReference.java
+//
+// The implementation in this file covers definitions BD14-BD16 and rule N0
+// of UAX#9.
+//
+// Some preprocessing is done for each rune before data is passed to this
+// algorithm:
+// - opening and closing brackets are identified
+// - a bracket pair type, like '(' and ')' is assigned a unique identifier that
+// is identical for the opening and closing bracket. It is left to do these
+// mappings.
+// - The BPA algorithm requires that bracket characters that are canonical
+// equivalents of each other be able to be substituted for each other.
+// It is the responsibility of the caller to do this canonicalization.
+//
+// In implementing BD16, this implementation departs slightly from the "logical"
+// algorithm defined in UAX#9. In particular, the stack referenced there
+// supports operations that go beyond a "basic" stack. An equivalent
+// implementation based on a linked list is used here.
+
+// Bidi_Paired_Bracket_Type
+// BD14. An opening paired bracket is a character whose
+// Bidi_Paired_Bracket_Type property value is Open.
+//
+// BD15. A closing paired bracket is a character whose
+// Bidi_Paired_Bracket_Type property value is Close.
+type bracketType byte
+
+const (
+ bpNone bracketType = iota
+ bpOpen
+ bpClose
+)
+
+// bracketPair holds a pair of index values for opening and closing bracket
+// location of a bracket pair.
+type bracketPair struct {
+ opener int
+ closer int
+}
+
+func (b *bracketPair) String() string {
+ return fmt.Sprintf("(%v, %v)", b.opener, b.closer)
+}
+
+// bracketPairs is a slice of bracketPairs with a sort.Interface implementation.
+type bracketPairs []bracketPair
+
+func (b bracketPairs) Len() int { return len(b) }
+func (b bracketPairs) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
+func (b bracketPairs) Less(i, j int) bool { return b[i].opener < b[j].opener }
+
+// resolvePairedBrackets runs the paired bracket part of the UBA algorithm.
+//
+// For each rune, it takes the indexes into the original string, the class the
+// bracket type (in pairTypes) and the bracket identifier (pairValues). It also
+// takes the direction type for the start-of-sentence and the embedding level.
+//
+// The identifiers for bracket types are the rune of the canonicalized opening
+// bracket for brackets (open or close) or 0 for runes that are not brackets.
+func resolvePairedBrackets(s *isolatingRunSequence) {
+ p := bracketPairer{
+ sos: s.sos,
+ openers: list.New(),
+ codesIsolatedRun: s.types,
+ indexes: s.indexes,
+ }
+ dirEmbed := L
+ if s.level&1 != 0 {
+ dirEmbed = R
+ }
+ p.locateBrackets(s.p.pairTypes, s.p.pairValues)
+ p.resolveBrackets(dirEmbed, s.p.initialTypes)
+}
+
+type bracketPairer struct {
+ sos Class // direction corresponding to start of sequence
+
+ // The following is a restatement of BD 16 using non-algorithmic language.
+ //
+ // A bracket pair is a pair of characters consisting of an opening
+ // paired bracket and a closing paired bracket such that the
+ // Bidi_Paired_Bracket property value of the former equals the latter,
+ // subject to the following constraints.
+ // - both characters of a pair occur in the same isolating run sequence
+ // - the closing character of a pair follows the opening character
+ // - any bracket character can belong at most to one pair, the earliest possible one
+ // - any bracket character not part of a pair is treated like an ordinary character
+ // - pairs may nest properly, but their spans may not overlap otherwise
+
+ // Bracket characters with canonical decompositions are supposed to be
+ // treated as if they had been normalized, to allow normalized and non-
+ // normalized text to give the same result. In this implementation that step
+ // is pushed out to the caller. The caller has to ensure that the pairValue
+ // slices contain the rune of the opening bracket after normalization for
+ // any opening or closing bracket.
+
+ openers *list.List // list of positions for opening brackets
+
+ // bracket pair positions sorted by location of opening bracket
+ pairPositions bracketPairs
+
+ codesIsolatedRun []Class // directional bidi codes for an isolated run
+ indexes []int // array of index values into the original string
+
+}
+
+// matchOpener reports whether characters at given positions form a matching
+// bracket pair.
+func (p *bracketPairer) matchOpener(pairValues []rune, opener, closer int) bool {
+ return pairValues[p.indexes[opener]] == pairValues[p.indexes[closer]]
+}
+
+const maxPairingDepth = 63
+
+// locateBrackets locates matching bracket pairs according to BD16.
+//
+// This implementation uses a linked list instead of a stack, because, while
+// elements are added at the front (like a push) they are not generally removed
+// in atomic 'pop' operations, reducing the benefit of the stack archetype.
+func (p *bracketPairer) locateBrackets(pairTypes []bracketType, pairValues []rune) {
+ // traverse the run
+ // do that explicitly (not in a for-each) so we can record position
+ for i, index := range p.indexes {
+
+ // look at the bracket type for each character
+ if pairTypes[index] == bpNone || p.codesIsolatedRun[i] != ON {
+ // continue scanning
+ continue
+ }
+ switch pairTypes[index] {
+ case bpOpen:
+ // check if maximum pairing depth reached
+ if p.openers.Len() == maxPairingDepth {
+ p.openers.Init()
+ return
+ }
+ // remember opener location, most recent first
+ p.openers.PushFront(i)
+
+ case bpClose:
+ // see if there is a match
+ count := 0
+ for elem := p.openers.Front(); elem != nil; elem = elem.Next() {
+ count++
+ opener := elem.Value.(int)
+ if p.matchOpener(pairValues, opener, i) {
+ // if the opener matches, add nested pair to the ordered list
+ p.pairPositions = append(p.pairPositions, bracketPair{opener, i})
+ // remove up to and including matched opener
+ for ; count > 0; count-- {
+ p.openers.Remove(p.openers.Front())
+ }
+ break
+ }
+ }
+ sort.Sort(p.pairPositions)
+ // if we get here, the closing bracket matched no openers
+ // and gets ignored
+ }
+ }
+}
+
+// Bracket pairs within an isolating run sequence are processed as units so
+// that both the opening and the closing paired bracket in a pair resolve to
+// the same direction.
+//
+// N0. Process bracket pairs in an isolating run sequence sequentially in
+// the logical order of the text positions of the opening paired brackets
+// using the logic given below. Within this scope, bidirectional types EN
+// and AN are treated as R.
+//
+// Identify the bracket pairs in the current isolating run sequence
+// according to BD16. For each bracket-pair element in the list of pairs of
+// text positions:
+//
+// a Inspect the bidirectional types of the characters enclosed within the
+// bracket pair.
+//
+// b If any strong type (either L or R) matching the embedding direction is
+// found, set the type for both brackets in the pair to match the embedding
+// direction.
+//
+// o [ e ] o -> o e e e o
+//
+// o [ o e ] -> o e o e e
+//
+// o [ NI e ] -> o e NI e e
+//
+// c Otherwise, if a strong type (opposite the embedding direction) is
+// found, test for adjacent strong types as follows: 1 First, check
+// backwards before the opening paired bracket until the first strong type
+// (L, R, or sos) is found. If that first preceding strong type is opposite
+// the embedding direction, then set the type for both brackets in the pair
+// to that type. 2 Otherwise, set the type for both brackets in the pair to
+// the embedding direction.
+//
+// o [ o ] e -> o o o o e
+//
+// o [ o NI ] o -> o o o NI o o
+//
+// e [ o ] o -> e e o e o
+//
+// e [ o ] e -> e e o e e
+//
+// e ( o [ o ] NI ) e -> e e o o o o NI e e
+//
+// d Otherwise, do not set the type for the current bracket pair. Note that
+// if the enclosed text contains no strong types the paired brackets will
+// both resolve to the same level when resolved individually using rules N1
+// and N2.
+//
+// e ( NI ) o -> e ( NI ) o
+
+// getStrongTypeN0 maps character's directional code to strong type as required
+// by rule N0.
+//
+// TODO: have separate type for "strong" directionality.
+func (p *bracketPairer) getStrongTypeN0(index int) Class {
+ switch p.codesIsolatedRun[index] {
+ // in the scope of N0, number types are treated as R
+ case EN, AN, AL, R:
+ return R
+ case L:
+ return L
+ default:
+ return ON
+ }
+}
+
+// classifyPairContent reports the strong types contained inside a Bracket Pair,
+// assuming the given embedding direction.
+//
+// It returns ON if no strong type is found. If a single strong type is found,
+// it returns this this type. Otherwise it returns the embedding direction.
+//
+// TODO: use separate type for "strong" directionality.
+func (p *bracketPairer) classifyPairContent(loc bracketPair, dirEmbed Class) Class {
+ dirOpposite := ON
+ for i := loc.opener + 1; i < loc.closer; i++ {
+ dir := p.getStrongTypeN0(i)
+ if dir == ON {
+ continue
+ }
+ if dir == dirEmbed {
+ return dir // type matching embedding direction found
+ }
+ dirOpposite = dir
+ }
+ // return ON if no strong type found, or class opposite to dirEmbed
+ return dirOpposite
+}
+
+// classBeforePair determines which strong types are present before a Bracket
+// Pair. Return R or L if strong type found, otherwise ON.
+func (p *bracketPairer) classBeforePair(loc bracketPair) Class {
+ for i := loc.opener - 1; i >= 0; i-- {
+ if dir := p.getStrongTypeN0(i); dir != ON {
+ return dir
+ }
+ }
+ // no strong types found, return sos
+ return p.sos
+}
+
+// assignBracketType implements rule N0 for a single bracket pair.
+func (p *bracketPairer) assignBracketType(loc bracketPair, dirEmbed Class, initialTypes []Class) {
+ // rule "N0, a", inspect contents of pair
+ dirPair := p.classifyPairContent(loc, dirEmbed)
+
+ // dirPair is now L, R, or N (no strong type found)
+
+ // the following logical tests are performed out of order compared to
+ // the statement of the rules but yield the same results
+ if dirPair == ON {
+ return // case "d" - nothing to do
+ }
+
+ if dirPair != dirEmbed {
+ // case "c": strong type found, opposite - check before (c.1)
+ dirPair = p.classBeforePair(loc)
+ if dirPair == dirEmbed || dirPair == ON {
+ // no strong opposite type found before - use embedding (c.2)
+ dirPair = dirEmbed
+ }
+ }
+ // else: case "b", strong type found matching embedding,
+ // no explicit action needed, as dirPair is already set to embedding
+ // direction
+
+ // set the bracket types to the type found
+ p.setBracketsToType(loc, dirPair, initialTypes)
+}
+
+func (p *bracketPairer) setBracketsToType(loc bracketPair, dirPair Class, initialTypes []Class) {
+ p.codesIsolatedRun[loc.opener] = dirPair
+ p.codesIsolatedRun[loc.closer] = dirPair
+
+ for i := loc.opener + 1; i < loc.closer; i++ {
+ index := p.indexes[i]
+ if initialTypes[index] != NSM {
+ break
+ }
+ p.codesIsolatedRun[i] = dirPair
+ }
+
+ for i := loc.closer + 1; i < len(p.indexes); i++ {
+ index := p.indexes[i]
+ if initialTypes[index] != NSM {
+ break
+ }
+ p.codesIsolatedRun[i] = dirPair
+ }
+}
+
+// resolveBrackets implements rule N0 for a list of pairs.
+func (p *bracketPairer) resolveBrackets(dirEmbed Class, initialTypes []Class) {
+ for _, loc := range p.pairPositions {
+ p.assignBracketType(loc, dirEmbed, initialTypes)
+ }
+}
diff --git a/vendor/golang.org/x/text/unicode/bidi/core.go b/vendor/golang.org/x/text/unicode/bidi/core.go
new file mode 100644
index 0000000..ec52f14
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/bidi/core.go
@@ -0,0 +1,1058 @@
+// Copyright 2015 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 bidi
+
+import "log"
+
+// This implementation is a port based on the reference implementation found at:
+// http://www.unicode.org/Public/PROGRAMS/BidiReferenceJava/
+//
+// described in Unicode Bidirectional Algorithm (UAX #9).
+//
+// Input:
+// There are two levels of input to the algorithm, since clients may prefer to
+// supply some information from out-of-band sources rather than relying on the
+// default behavior.
+//
+// - Bidi class array
+// - Bidi class array, with externally supplied base line direction
+//
+// Output:
+// Output is separated into several stages:
+//
+// - levels array over entire paragraph
+// - reordering array over entire paragraph
+// - levels array over line
+// - reordering array over line
+//
+// Note that for conformance to the Unicode Bidirectional Algorithm,
+// implementations are only required to generate correct reordering and
+// character directionality (odd or even levels) over a line. Generating
+// identical level arrays over a line is not required. Bidi explicit format
+// codes (LRE, RLE, LRO, RLO, PDF) and BN can be assigned arbitrary levels and
+// positions as long as the rest of the input is properly reordered.
+//
+// As the algorithm is defined to operate on a single paragraph at a time, this
+// implementation is written to handle single paragraphs. Thus rule P1 is
+// presumed by this implementation-- the data provided to the implementation is
+// assumed to be a single paragraph, and either contains no 'B' codes, or a
+// single 'B' code at the end of the input. 'B' is allowed as input to
+// illustrate how the algorithm assigns it a level.
+//
+// Also note that rules L3 and L4 depend on the rendering engine that uses the
+// result of the bidi algorithm. This implementation assumes that the rendering
+// engine expects combining marks in visual order (e.g. to the left of their
+// base character in RTL runs) and that it adjusts the glyphs used to render
+// mirrored characters that are in RTL runs so that they render appropriately.
+
+// level is the embedding level of a character. Even embedding levels indicate
+// left-to-right order and odd levels indicate right-to-left order. The special
+// level of -1 is reserved for undefined order.
+type level int8
+
+const implicitLevel level = -1
+
+// in returns if x is equal to any of the values in set.
+func (c Class) in(set ...Class) bool {
+ for _, s := range set {
+ if c == s {
+ return true
+ }
+ }
+ return false
+}
+
+// A paragraph contains the state of a paragraph.
+type paragraph struct {
+ initialTypes []Class
+
+ // Arrays of properties needed for paired bracket evaluation in N0
+ pairTypes []bracketType // paired Bracket types for paragraph
+ pairValues []rune // rune for opening bracket or pbOpen and pbClose; 0 for pbNone
+
+ embeddingLevel level // default: = implicitLevel;
+
+ // at the paragraph levels
+ resultTypes []Class
+ resultLevels []level
+
+ // Index of matching PDI for isolate initiator characters. For other
+ // characters, the value of matchingPDI will be set to -1. For isolate
+ // initiators with no matching PDI, matchingPDI will be set to the length of
+ // the input string.
+ matchingPDI []int
+
+ // Index of matching isolate initiator for PDI characters. For other
+ // characters, and for PDIs with no matching isolate initiator, the value of
+ // matchingIsolateInitiator will be set to -1.
+ matchingIsolateInitiator []int
+}
+
+// newParagraph initializes a paragraph. The user needs to supply a few arrays
+// corresponding to the preprocessed text input. The types correspond to the
+// Unicode BiDi classes for each rune. pairTypes indicates the bracket type for
+// each rune. pairValues provides a unique bracket class identifier for each
+// rune (suggested is the rune of the open bracket for opening and matching
+// close brackets, after normalization). The embedding levels are optional, but
+// may be supplied to encode embedding levels of styled text.
+//
+// TODO: return an error.
+func newParagraph(types []Class, pairTypes []bracketType, pairValues []rune, levels level) *paragraph {
+ validateTypes(types)
+ validatePbTypes(pairTypes)
+ validatePbValues(pairValues, pairTypes)
+ validateParagraphEmbeddingLevel(levels)
+
+ p := &paragraph{
+ initialTypes: append([]Class(nil), types...),
+ embeddingLevel: levels,
+
+ pairTypes: pairTypes,
+ pairValues: pairValues,
+
+ resultTypes: append([]Class(nil), types...),
+ }
+ p.run()
+ return p
+}
+
+func (p *paragraph) Len() int { return len(p.initialTypes) }
+
+// The algorithm. Does not include line-based processing (Rules L1, L2).
+// These are applied later in the line-based phase of the algorithm.
+func (p *paragraph) run() {
+ p.determineMatchingIsolates()
+
+ // 1) determining the paragraph level
+ // Rule P1 is the requirement for entering this algorithm.
+ // Rules P2, P3.
+ // If no externally supplied paragraph embedding level, use default.
+ if p.embeddingLevel == implicitLevel {
+ p.embeddingLevel = p.determineParagraphEmbeddingLevel(0, p.Len())
+ }
+
+ // Initialize result levels to paragraph embedding level.
+ p.resultLevels = make([]level, p.Len())
+ setLevels(p.resultLevels, p.embeddingLevel)
+
+ // 2) Explicit levels and directions
+ // Rules X1-X8.
+ p.determineExplicitEmbeddingLevels()
+
+ // Rule X9.
+ // We do not remove the embeddings, the overrides, the PDFs, and the BNs
+ // from the string explicitly. But they are not copied into isolating run
+ // sequences when they are created, so they are removed for all
+ // practical purposes.
+
+ // Rule X10.
+ // Run remainder of algorithm one isolating run sequence at a time
+ for _, seq := range p.determineIsolatingRunSequences() {
+ // 3) resolving weak types
+ // Rules W1-W7.
+ seq.resolveWeakTypes()
+
+ // 4a) resolving paired brackets
+ // Rule N0
+ resolvePairedBrackets(seq)
+
+ // 4b) resolving neutral types
+ // Rules N1-N3.
+ seq.resolveNeutralTypes()
+
+ // 5) resolving implicit embedding levels
+ // Rules I1, I2.
+ seq.resolveImplicitLevels()
+
+ // Apply the computed levels and types
+ seq.applyLevelsAndTypes()
+ }
+
+ // Assign appropriate levels to 'hide' LREs, RLEs, LROs, RLOs, PDFs, and
+ // BNs. This is for convenience, so the resulting level array will have
+ // a value for every character.
+ p.assignLevelsToCharactersRemovedByX9()
+}
+
+// determineMatchingIsolates determines the matching PDI for each isolate
+// initiator and vice versa.
+//
+// Definition BD9.
+//
+// At the end of this function:
+//
+// - The member variable matchingPDI is set to point to the index of the
+// matching PDI character for each isolate initiator character. If there is
+// no matching PDI, it is set to the length of the input text. For other
+// characters, it is set to -1.
+// - The member variable matchingIsolateInitiator is set to point to the
+// index of the matching isolate initiator character for each PDI character.
+// If there is no matching isolate initiator, or the character is not a PDI,
+// it is set to -1.
+func (p *paragraph) determineMatchingIsolates() {
+ p.matchingPDI = make([]int, p.Len())
+ p.matchingIsolateInitiator = make([]int, p.Len())
+
+ for i := range p.matchingIsolateInitiator {
+ p.matchingIsolateInitiator[i] = -1
+ }
+
+ for i := range p.matchingPDI {
+ p.matchingPDI[i] = -1
+
+ if t := p.resultTypes[i]; t.in(LRI, RLI, FSI) {
+ depthCounter := 1
+ for j := i + 1; j < p.Len(); j++ {
+ if u := p.resultTypes[j]; u.in(LRI, RLI, FSI) {
+ depthCounter++
+ } else if u == PDI {
+ if depthCounter--; depthCounter == 0 {
+ p.matchingPDI[i] = j
+ p.matchingIsolateInitiator[j] = i
+ break
+ }
+ }
+ }
+ if p.matchingPDI[i] == -1 {
+ p.matchingPDI[i] = p.Len()
+ }
+ }
+ }
+}
+
+// determineParagraphEmbeddingLevel reports the resolved paragraph direction of
+// the substring limited by the given range [start, end).
+//
+// Determines the paragraph level based on rules P2, P3. This is also used
+// in rule X5c to find if an FSI should resolve to LRI or RLI.
+func (p *paragraph) determineParagraphEmbeddingLevel(start, end int) level {
+ var strongType Class = unknownClass
+
+ // Rule P2.
+ for i := start; i < end; i++ {
+ if t := p.resultTypes[i]; t.in(L, AL, R) {
+ strongType = t
+ break
+ } else if t.in(FSI, LRI, RLI) {
+ i = p.matchingPDI[i] // skip over to the matching PDI
+ if i > end {
+ log.Panic("assert (i <= end)")
+ }
+ }
+ }
+ // Rule P3.
+ switch strongType {
+ case unknownClass: // none found
+ // default embedding level when no strong types found is 0.
+ return 0
+ case L:
+ return 0
+ default: // AL, R
+ return 1
+ }
+}
+
+const maxDepth = 125
+
+// This stack will store the embedding levels and override and isolated
+// statuses
+type directionalStatusStack struct {
+ stackCounter int
+ embeddingLevelStack [maxDepth + 1]level
+ overrideStatusStack [maxDepth + 1]Class
+ isolateStatusStack [maxDepth + 1]bool
+}
+
+func (s *directionalStatusStack) empty() { s.stackCounter = 0 }
+func (s *directionalStatusStack) pop() { s.stackCounter-- }
+func (s *directionalStatusStack) depth() int { return s.stackCounter }
+
+func (s *directionalStatusStack) push(level level, overrideStatus Class, isolateStatus bool) {
+ s.embeddingLevelStack[s.stackCounter] = level
+ s.overrideStatusStack[s.stackCounter] = overrideStatus
+ s.isolateStatusStack[s.stackCounter] = isolateStatus
+ s.stackCounter++
+}
+
+func (s *directionalStatusStack) lastEmbeddingLevel() level {
+ return s.embeddingLevelStack[s.stackCounter-1]
+}
+
+func (s *directionalStatusStack) lastDirectionalOverrideStatus() Class {
+ return s.overrideStatusStack[s.stackCounter-1]
+}
+
+func (s *directionalStatusStack) lastDirectionalIsolateStatus() bool {
+ return s.isolateStatusStack[s.stackCounter-1]
+}
+
+// Determine explicit levels using rules X1 - X8
+func (p *paragraph) determineExplicitEmbeddingLevels() {
+ var stack directionalStatusStack
+ var overflowIsolateCount, overflowEmbeddingCount, validIsolateCount int
+
+ // Rule X1.
+ stack.push(p.embeddingLevel, ON, false)
+
+ for i, t := range p.resultTypes {
+ // Rules X2, X3, X4, X5, X5a, X5b, X5c
+ switch t {
+ case RLE, LRE, RLO, LRO, RLI, LRI, FSI:
+ isIsolate := t.in(RLI, LRI, FSI)
+ isRTL := t.in(RLE, RLO, RLI)
+
+ // override if this is an FSI that resolves to RLI
+ if t == FSI {
+ isRTL = (p.determineParagraphEmbeddingLevel(i+1, p.matchingPDI[i]) == 1)
+ }
+ if isIsolate {
+ p.resultLevels[i] = stack.lastEmbeddingLevel()
+ if stack.lastDirectionalOverrideStatus() != ON {
+ p.resultTypes[i] = stack.lastDirectionalOverrideStatus()
+ }
+ }
+
+ var newLevel level
+ if isRTL {
+ // least greater odd
+ newLevel = (stack.lastEmbeddingLevel() + 1) | 1
+ } else {
+ // least greater even
+ newLevel = (stack.lastEmbeddingLevel() + 2) &^ 1
+ }
+
+ if newLevel <= maxDepth && overflowIsolateCount == 0 && overflowEmbeddingCount == 0 {
+ if isIsolate {
+ validIsolateCount++
+ }
+ // Push new embedding level, override status, and isolated
+ // status.
+ // No check for valid stack counter, since the level check
+ // suffices.
+ switch t {
+ case LRO:
+ stack.push(newLevel, L, isIsolate)
+ case RLO:
+ stack.push(newLevel, R, isIsolate)
+ default:
+ stack.push(newLevel, ON, isIsolate)
+ }
+ // Not really part of the spec
+ if !isIsolate {
+ p.resultLevels[i] = newLevel
+ }
+ } else {
+ // This is an invalid explicit formatting character,
+ // so apply the "Otherwise" part of rules X2-X5b.
+ if isIsolate {
+ overflowIsolateCount++
+ } else { // !isIsolate
+ if overflowIsolateCount == 0 {
+ overflowEmbeddingCount++
+ }
+ }
+ }
+
+ // Rule X6a
+ case PDI:
+ if overflowIsolateCount > 0 {
+ overflowIsolateCount--
+ } else if validIsolateCount == 0 {
+ // do nothing
+ } else {
+ overflowEmbeddingCount = 0
+ for !stack.lastDirectionalIsolateStatus() {
+ stack.pop()
+ }
+ stack.pop()
+ validIsolateCount--
+ }
+ p.resultLevels[i] = stack.lastEmbeddingLevel()
+
+ // Rule X7
+ case PDF:
+ // Not really part of the spec
+ p.resultLevels[i] = stack.lastEmbeddingLevel()
+
+ if overflowIsolateCount > 0 {
+ // do nothing
+ } else if overflowEmbeddingCount > 0 {
+ overflowEmbeddingCount--
+ } else if !stack.lastDirectionalIsolateStatus() && stack.depth() >= 2 {
+ stack.pop()
+ }
+
+ case B: // paragraph separator.
+ // Rule X8.
+
+ // These values are reset for clarity, in this implementation B
+ // can only occur as the last code in the array.
+ stack.empty()
+ overflowIsolateCount = 0
+ overflowEmbeddingCount = 0
+ validIsolateCount = 0
+ p.resultLevels[i] = p.embeddingLevel
+
+ default:
+ p.resultLevels[i] = stack.lastEmbeddingLevel()
+ if stack.lastDirectionalOverrideStatus() != ON {
+ p.resultTypes[i] = stack.lastDirectionalOverrideStatus()
+ }
+ }
+ }
+}
+
+type isolatingRunSequence struct {
+ p *paragraph
+
+ indexes []int // indexes to the original string
+
+ types []Class // type of each character using the index
+ resolvedLevels []level // resolved levels after application of rules
+ level level
+ sos, eos Class
+}
+
+func (i *isolatingRunSequence) Len() int { return len(i.indexes) }
+
+func maxLevel(a, b level) level {
+ if a > b {
+ return a
+ }
+ return b
+}
+
+// Rule X10, second bullet: Determine the start-of-sequence (sos) and end-of-sequence (eos) types,
+// either L or R, for each isolating run sequence.
+func (p *paragraph) isolatingRunSequence(indexes []int) *isolatingRunSequence {
+ length := len(indexes)
+ types := make([]Class, length)
+ for i, x := range indexes {
+ types[i] = p.resultTypes[x]
+ }
+
+ // assign level, sos and eos
+ prevChar := indexes[0] - 1
+ for prevChar >= 0 && isRemovedByX9(p.initialTypes[prevChar]) {
+ prevChar--
+ }
+ prevLevel := p.embeddingLevel
+ if prevChar >= 0 {
+ prevLevel = p.resultLevels[prevChar]
+ }
+
+ var succLevel level
+ lastType := types[length-1]
+ if lastType.in(LRI, RLI, FSI) {
+ succLevel = p.embeddingLevel
+ } else {
+ // the first character after the end of run sequence
+ limit := indexes[length-1] + 1
+ for ; limit < p.Len() && isRemovedByX9(p.initialTypes[limit]); limit++ {
+
+ }
+ succLevel = p.embeddingLevel
+ if limit < p.Len() {
+ succLevel = p.resultLevels[limit]
+ }
+ }
+ level := p.resultLevels[indexes[0]]
+ return &isolatingRunSequence{
+ p: p,
+ indexes: indexes,
+ types: types,
+ level: level,
+ sos: typeForLevel(maxLevel(prevLevel, level)),
+ eos: typeForLevel(maxLevel(succLevel, level)),
+ }
+}
+
+// Resolving weak types Rules W1-W7.
+//
+// Note that some weak types (EN, AN) remain after this processing is
+// complete.
+func (s *isolatingRunSequence) resolveWeakTypes() {
+
+ // on entry, only these types remain
+ s.assertOnly(L, R, AL, EN, ES, ET, AN, CS, B, S, WS, ON, NSM, LRI, RLI, FSI, PDI)
+
+ // Rule W1.
+ // Changes all NSMs.
+ preceedingCharacterType := s.sos
+ for i, t := range s.types {
+ if t == NSM {
+ s.types[i] = preceedingCharacterType
+ } else {
+ if t.in(LRI, RLI, FSI, PDI) {
+ preceedingCharacterType = ON
+ }
+ preceedingCharacterType = t
+ }
+ }
+
+ // Rule W2.
+ // EN does not change at the start of the run, because sos != AL.
+ for i, t := range s.types {
+ if t == EN {
+ for j := i - 1; j >= 0; j-- {
+ if t := s.types[j]; t.in(L, R, AL) {
+ if t == AL {
+ s.types[i] = AN
+ }
+ break
+ }
+ }
+ }
+ }
+
+ // Rule W3.
+ for i, t := range s.types {
+ if t == AL {
+ s.types[i] = R
+ }
+ }
+
+ // Rule W4.
+ // Since there must be values on both sides for this rule to have an
+ // effect, the scan skips the first and last value.
+ //
+ // Although the scan proceeds left to right, and changes the type
+ // values in a way that would appear to affect the computations
+ // later in the scan, there is actually no problem. A change in the
+ // current value can only affect the value to its immediate right,
+ // and only affect it if it is ES or CS. But the current value can
+ // only change if the value to its right is not ES or CS. Thus
+ // either the current value will not change, or its change will have
+ // no effect on the remainder of the analysis.
+
+ for i := 1; i < s.Len()-1; i++ {
+ t := s.types[i]
+ if t == ES || t == CS {
+ prevSepType := s.types[i-1]
+ succSepType := s.types[i+1]
+ if prevSepType == EN && succSepType == EN {
+ s.types[i] = EN
+ } else if s.types[i] == CS && prevSepType == AN && succSepType == AN {
+ s.types[i] = AN
+ }
+ }
+ }
+
+ // Rule W5.
+ for i, t := range s.types {
+ if t == ET {
+ // locate end of sequence
+ runStart := i
+ runEnd := s.findRunLimit(runStart, ET)
+
+ // check values at ends of sequence
+ t := s.sos
+ if runStart > 0 {
+ t = s.types[runStart-1]
+ }
+ if t != EN {
+ t = s.eos
+ if runEnd < len(s.types) {
+ t = s.types[runEnd]
+ }
+ }
+ if t == EN {
+ setTypes(s.types[runStart:runEnd], EN)
+ }
+ // continue at end of sequence
+ i = runEnd
+ }
+ }
+
+ // Rule W6.
+ for i, t := range s.types {
+ if t.in(ES, ET, CS) {
+ s.types[i] = ON
+ }
+ }
+
+ // Rule W7.
+ for i, t := range s.types {
+ if t == EN {
+ // set default if we reach start of run
+ prevStrongType := s.sos
+ for j := i - 1; j >= 0; j-- {
+ t = s.types[j]
+ if t == L || t == R { // AL's have been changed to R
+ prevStrongType = t
+ break
+ }
+ }
+ if prevStrongType == L {
+ s.types[i] = L
+ }
+ }
+ }
+}
+
+// 6) resolving neutral types Rules N1-N2.
+func (s *isolatingRunSequence) resolveNeutralTypes() {
+
+ // on entry, only these types can be in resultTypes
+ s.assertOnly(L, R, EN, AN, B, S, WS, ON, RLI, LRI, FSI, PDI)
+
+ for i, t := range s.types {
+ switch t {
+ case WS, ON, B, S, RLI, LRI, FSI, PDI:
+ // find bounds of run of neutrals
+ runStart := i
+ runEnd := s.findRunLimit(runStart, B, S, WS, ON, RLI, LRI, FSI, PDI)
+
+ // determine effective types at ends of run
+ var leadType, trailType Class
+
+ // Note that the character found can only be L, R, AN, or
+ // EN.
+ if runStart == 0 {
+ leadType = s.sos
+ } else {
+ leadType = s.types[runStart-1]
+ if leadType.in(AN, EN) {
+ leadType = R
+ }
+ }
+ if runEnd == len(s.types) {
+ trailType = s.eos
+ } else {
+ trailType = s.types[runEnd]
+ if trailType.in(AN, EN) {
+ trailType = R
+ }
+ }
+
+ var resolvedType Class
+ if leadType == trailType {
+ // Rule N1.
+ resolvedType = leadType
+ } else {
+ // Rule N2.
+ // Notice the embedding level of the run is used, not
+ // the paragraph embedding level.
+ resolvedType = typeForLevel(s.level)
+ }
+
+ setTypes(s.types[runStart:runEnd], resolvedType)
+
+ // skip over run of (former) neutrals
+ i = runEnd
+ }
+ }
+}
+
+func setLevels(levels []level, newLevel level) {
+ for i := range levels {
+ levels[i] = newLevel
+ }
+}
+
+func setTypes(types []Class, newType Class) {
+ for i := range types {
+ types[i] = newType
+ }
+}
+
+// 7) resolving implicit embedding levels Rules I1, I2.
+func (s *isolatingRunSequence) resolveImplicitLevels() {
+
+ // on entry, only these types can be in resultTypes
+ s.assertOnly(L, R, EN, AN)
+
+ s.resolvedLevels = make([]level, len(s.types))
+ setLevels(s.resolvedLevels, s.level)
+
+ if (s.level & 1) == 0 { // even level
+ for i, t := range s.types {
+ // Rule I1.
+ if t == L {
+ // no change
+ } else if t == R {
+ s.resolvedLevels[i] += 1
+ } else { // t == AN || t == EN
+ s.resolvedLevels[i] += 2
+ }
+ }
+ } else { // odd level
+ for i, t := range s.types {
+ // Rule I2.
+ if t == R {
+ // no change
+ } else { // t == L || t == AN || t == EN
+ s.resolvedLevels[i] += 1
+ }
+ }
+ }
+}
+
+// Applies the levels and types resolved in rules W1-I2 to the
+// resultLevels array.
+func (s *isolatingRunSequence) applyLevelsAndTypes() {
+ for i, x := range s.indexes {
+ s.p.resultTypes[x] = s.types[i]
+ s.p.resultLevels[x] = s.resolvedLevels[i]
+ }
+}
+
+// Return the limit of the run consisting only of the types in validSet
+// starting at index. This checks the value at index, and will return
+// index if that value is not in validSet.
+func (s *isolatingRunSequence) findRunLimit(index int, validSet ...Class) int {
+loop:
+ for ; index < len(s.types); index++ {
+ t := s.types[index]
+ for _, valid := range validSet {
+ if t == valid {
+ continue loop
+ }
+ }
+ return index // didn't find a match in validSet
+ }
+ return len(s.types)
+}
+
+// Algorithm validation. Assert that all values in types are in the
+// provided set.
+func (s *isolatingRunSequence) assertOnly(codes ...Class) {
+loop:
+ for i, t := range s.types {
+ for _, c := range codes {
+ if t == c {
+ continue loop
+ }
+ }
+ log.Panicf("invalid bidi code %s present in assertOnly at position %d", t, s.indexes[i])
+ }
+}
+
+// determineLevelRuns returns an array of level runs. Each level run is
+// described as an array of indexes into the input string.
+//
+// Determines the level runs. Rule X9 will be applied in determining the
+// runs, in the way that makes sure the characters that are supposed to be
+// removed are not included in the runs.
+func (p *paragraph) determineLevelRuns() [][]int {
+ run := []int{}
+ allRuns := [][]int{}
+ currentLevel := implicitLevel
+
+ for i := range p.initialTypes {
+ if !isRemovedByX9(p.initialTypes[i]) {
+ if p.resultLevels[i] != currentLevel {
+ // we just encountered a new run; wrap up last run
+ if currentLevel >= 0 { // only wrap it up if there was a run
+ allRuns = append(allRuns, run)
+ run = nil
+ }
+ // Start new run
+ currentLevel = p.resultLevels[i]
+ }
+ run = append(run, i)
+ }
+ }
+ // Wrap up the final run, if any
+ if len(run) > 0 {
+ allRuns = append(allRuns, run)
+ }
+ return allRuns
+}
+
+// Definition BD13. Determine isolating run sequences.
+func (p *paragraph) determineIsolatingRunSequences() []*isolatingRunSequence {
+ levelRuns := p.determineLevelRuns()
+
+ // Compute the run that each character belongs to
+ runForCharacter := make([]int, p.Len())
+ for i, run := range levelRuns {
+ for _, index := range run {
+ runForCharacter[index] = i
+ }
+ }
+
+ sequences := []*isolatingRunSequence{}
+
+ var currentRunSequence []int
+
+ for _, run := range levelRuns {
+ first := run[0]
+ if p.initialTypes[first] != PDI || p.matchingIsolateInitiator[first] == -1 {
+ currentRunSequence = nil
+ // int run = i;
+ for {
+ // Copy this level run into currentRunSequence
+ currentRunSequence = append(currentRunSequence, run...)
+
+ last := currentRunSequence[len(currentRunSequence)-1]
+ lastT := p.initialTypes[last]
+ if lastT.in(LRI, RLI, FSI) && p.matchingPDI[last] != p.Len() {
+ run = levelRuns[runForCharacter[p.matchingPDI[last]]]
+ } else {
+ break
+ }
+ }
+ sequences = append(sequences, p.isolatingRunSequence(currentRunSequence))
+ }
+ }
+ return sequences
+}
+
+// Assign level information to characters removed by rule X9. This is for
+// ease of relating the level information to the original input data. Note
+// that the levels assigned to these codes are arbitrary, they're chosen so
+// as to avoid breaking level runs.
+func (p *paragraph) assignLevelsToCharactersRemovedByX9() {
+ for i, t := range p.initialTypes {
+ if t.in(LRE, RLE, LRO, RLO, PDF, BN) {
+ p.resultTypes[i] = t
+ p.resultLevels[i] = -1
+ }
+ }
+ // now propagate forward the levels information (could have
+ // propagated backward, the main thing is not to introduce a level
+ // break where one doesn't already exist).
+
+ if p.resultLevels[0] == -1 {
+ p.resultLevels[0] = p.embeddingLevel
+ }
+ for i := 1; i < len(p.initialTypes); i++ {
+ if p.resultLevels[i] == -1 {
+ p.resultLevels[i] = p.resultLevels[i-1]
+ }
+ }
+ // Embedding information is for informational purposes only so need not be
+ // adjusted.
+}
+
+//
+// Output
+//
+
+// getLevels computes levels array breaking lines at offsets in linebreaks.
+// Rule L1.
+//
+// The linebreaks array must include at least one value. The values must be
+// in strictly increasing order (no duplicates) between 1 and the length of
+// the text, inclusive. The last value must be the length of the text.
+func (p *paragraph) getLevels(linebreaks []int) []level {
+ // Note that since the previous processing has removed all
+ // P, S, and WS values from resultTypes, the values referred to
+ // in these rules are the initial types, before any processing
+ // has been applied (including processing of overrides).
+ //
+ // This example implementation has reinserted explicit format codes
+ // and BN, in order that the levels array correspond to the
+ // initial text. Their final placement is not normative.
+ // These codes are treated like WS in this implementation,
+ // so they don't interrupt sequences of WS.
+
+ validateLineBreaks(linebreaks, p.Len())
+
+ result := append([]level(nil), p.resultLevels...)
+
+ // don't worry about linebreaks since if there is a break within
+ // a series of WS values preceding S, the linebreak itself
+ // causes the reset.
+ for i, t := range p.initialTypes {
+ if t.in(B, S) {
+ // Rule L1, clauses one and two.
+ result[i] = p.embeddingLevel
+
+ // Rule L1, clause three.
+ for j := i - 1; j >= 0; j-- {
+ if isWhitespace(p.initialTypes[j]) { // including format codes
+ result[j] = p.embeddingLevel
+ } else {
+ break
+ }
+ }
+ }
+ }
+
+ // Rule L1, clause four.
+ start := 0
+ for _, limit := range linebreaks {
+ for j := limit - 1; j >= start; j-- {
+ if isWhitespace(p.initialTypes[j]) { // including format codes
+ result[j] = p.embeddingLevel
+ } else {
+ break
+ }
+ }
+ start = limit
+ }
+
+ return result
+}
+
+// getReordering returns the reordering of lines from a visual index to a
+// logical index for line breaks at the given offsets.
+//
+// Lines are concatenated from left to right. So for example, the fifth
+// character from the left on the third line is
+//
+// getReordering(linebreaks)[linebreaks[1] + 4]
+//
+// (linebreaks[1] is the position after the last character of the second
+// line, which is also the index of the first character on the third line,
+// and adding four gets the fifth character from the left).
+//
+// The linebreaks array must include at least one value. The values must be
+// in strictly increasing order (no duplicates) between 1 and the length of
+// the text, inclusive. The last value must be the length of the text.
+func (p *paragraph) getReordering(linebreaks []int) []int {
+ validateLineBreaks(linebreaks, p.Len())
+
+ return computeMultilineReordering(p.getLevels(linebreaks), linebreaks)
+}
+
+// Return multiline reordering array for a given level array. Reordering
+// does not occur across a line break.
+func computeMultilineReordering(levels []level, linebreaks []int) []int {
+ result := make([]int, len(levels))
+
+ start := 0
+ for _, limit := range linebreaks {
+ tempLevels := make([]level, limit-start)
+ copy(tempLevels, levels[start:])
+
+ for j, order := range computeReordering(tempLevels) {
+ result[start+j] = order + start
+ }
+ start = limit
+ }
+ return result
+}
+
+// Return reordering array for a given level array. This reorders a single
+// line. The reordering is a visual to logical map. For example, the
+// leftmost char is string.charAt(order[0]). Rule L2.
+func computeReordering(levels []level) []int {
+ result := make([]int, len(levels))
+ // initialize order
+ for i := range result {
+ result[i] = i
+ }
+
+ // locate highest level found on line.
+ // Note the rules say text, but no reordering across line bounds is
+ // performed, so this is sufficient.
+ highestLevel := level(0)
+ lowestOddLevel := level(maxDepth + 2)
+ for _, level := range levels {
+ if level > highestLevel {
+ highestLevel = level
+ }
+ if level&1 != 0 && level < lowestOddLevel {
+ lowestOddLevel = level
+ }
+ }
+
+ for level := highestLevel; level >= lowestOddLevel; level-- {
+ for i := 0; i < len(levels); i++ {
+ if levels[i] >= level {
+ // find range of text at or above this level
+ start := i
+ limit := i + 1
+ for limit < len(levels) && levels[limit] >= level {
+ limit++
+ }
+
+ for j, k := start, limit-1; j < k; j, k = j+1, k-1 {
+ result[j], result[k] = result[k], result[j]
+ }
+ // skip to end of level run
+ i = limit
+ }
+ }
+ }
+
+ return result
+}
+
+// isWhitespace reports whether the type is considered a whitespace type for the
+// line break rules.
+func isWhitespace(c Class) bool {
+ switch c {
+ case LRE, RLE, LRO, RLO, PDF, LRI, RLI, FSI, PDI, BN, WS:
+ return true
+ }
+ return false
+}
+
+// isRemovedByX9 reports whether the type is one of the types removed in X9.
+func isRemovedByX9(c Class) bool {
+ switch c {
+ case LRE, RLE, LRO, RLO, PDF, BN:
+ return true
+ }
+ return false
+}
+
+// typeForLevel reports the strong type (L or R) corresponding to the level.
+func typeForLevel(level level) Class {
+ if (level & 0x1) == 0 {
+ return L
+ }
+ return R
+}
+
+// TODO: change validation to not panic
+
+func validateTypes(types []Class) {
+ if len(types) == 0 {
+ log.Panic("types is null")
+ }
+ for i, t := range types[:len(types)-1] {
+ if t == B {
+ log.Panicf("B type before end of paragraph at index: %d", i)
+ }
+ }
+}
+
+func validateParagraphEmbeddingLevel(embeddingLevel level) {
+ if embeddingLevel != implicitLevel &&
+ embeddingLevel != 0 &&
+ embeddingLevel != 1 {
+ log.Panicf("illegal paragraph embedding level: %d", embeddingLevel)
+ }
+}
+
+func validateLineBreaks(linebreaks []int, textLength int) {
+ prev := 0
+ for i, next := range linebreaks {
+ if next <= prev {
+ log.Panicf("bad linebreak: %d at index: %d", next, i)
+ }
+ prev = next
+ }
+ if prev != textLength {
+ log.Panicf("last linebreak was %d, want %d", prev, textLength)
+ }
+}
+
+func validatePbTypes(pairTypes []bracketType) {
+ if len(pairTypes) == 0 {
+ log.Panic("pairTypes is null")
+ }
+ for i, pt := range pairTypes {
+ switch pt {
+ case bpNone, bpOpen, bpClose:
+ default:
+ log.Panicf("illegal pairType value at %d: %v", i, pairTypes[i])
+ }
+ }
+}
+
+func validatePbValues(pairValues []rune, pairTypes []bracketType) {
+ if pairValues == nil {
+ log.Panic("pairValues is null")
+ }
+ if len(pairTypes) != len(pairValues) {
+ log.Panic("pairTypes is different length from pairValues")
+ }
+}
diff --git a/vendor/golang.org/x/text/unicode/bidi/prop.go b/vendor/golang.org/x/text/unicode/bidi/prop.go
new file mode 100644
index 0000000..7c9484e
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/bidi/prop.go
@@ -0,0 +1,206 @@
+// 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 bidi
+
+import "unicode/utf8"
+
+// Properties provides access to BiDi properties of runes.
+type Properties struct {
+ entry uint8
+ last uint8
+}
+
+var trie = newBidiTrie(0)
+
+// TODO: using this for bidirule reduces the running time by about 5%. Consider
+// if this is worth exposing or if we can find a way to speed up the Class
+// method.
+//
+// // CompactClass is like Class, but maps all of the BiDi control classes
+// // (LRO, RLO, LRE, RLE, PDF, LRI, RLI, FSI, PDI) to the class Control.
+// func (p Properties) CompactClass() Class {
+// return Class(p.entry & 0x0F)
+// }
+
+// Class returns the Bidi class for p.
+func (p Properties) Class() Class {
+ c := Class(p.entry & 0x0F)
+ if c == Control {
+ c = controlByteToClass[p.last&0xF]
+ }
+ return c
+}
+
+// IsBracket reports whether the rune is a bracket.
+func (p Properties) IsBracket() bool { return p.entry&0xF0 != 0 }
+
+// IsOpeningBracket reports whether the rune is an opening bracket.
+// IsBracket must return true.
+func (p Properties) IsOpeningBracket() bool { return p.entry&openMask != 0 }
+
+// TODO: find a better API and expose.
+func (p Properties) reverseBracket(r rune) rune {
+ return xorMasks[p.entry>>xorMaskShift] ^ r
+}
+
+var controlByteToClass = [16]Class{
+ 0xD: LRO, // U+202D LeftToRightOverride,
+ 0xE: RLO, // U+202E RightToLeftOverride,
+ 0xA: LRE, // U+202A LeftToRightEmbedding,
+ 0xB: RLE, // U+202B RightToLeftEmbedding,
+ 0xC: PDF, // U+202C PopDirectionalFormat,
+ 0x6: LRI, // U+2066 LeftToRightIsolate,
+ 0x7: RLI, // U+2067 RightToLeftIsolate,
+ 0x8: FSI, // U+2068 FirstStrongIsolate,
+ 0x9: PDI, // U+2069 PopDirectionalIsolate,
+}
+
+// LookupRune returns properties for r.
+func LookupRune(r rune) (p Properties, size int) {
+ var buf [4]byte
+ n := utf8.EncodeRune(buf[:], r)
+ return Lookup(buf[:n])
+}
+
+// TODO: these lookup methods are based on the generated trie code. The returned
+// sizes have slightly different semantics from the generated code, in that it
+// always returns size==1 for an illegal UTF-8 byte (instead of the length
+// of the maximum invalid subsequence). Most Transformers, like unicode/norm,
+// leave invalid UTF-8 untouched, in which case it has performance benefits to
+// do so (without changing the semantics). Bidi requires the semantics used here
+// for the bidirule implementation to be compatible with the Go semantics.
+// They ultimately should perhaps be adopted by all trie implementations, for
+// convenience sake.
+// This unrolled code also boosts performance of the secure/bidirule package by
+// about 30%.
+// So, to remove this code:
+// - add option to trie generator to define return type.
+// - always return 1 byte size for ill-formed UTF-8 runes.
+
+// Lookup returns properties for the first rune in s and the width in bytes of
+// its encoding. The size will be 0 if s does not hold enough bytes to complete
+// the encoding.
+func Lookup(s []byte) (p Properties, sz int) {
+ c0 := s[0]
+ switch {
+ case c0 < 0x80: // is ASCII
+ return Properties{entry: bidiValues[c0]}, 1
+ case c0 < 0xC2:
+ return Properties{}, 1
+ case c0 < 0xE0: // 2-byte UTF-8
+ if len(s) < 2 {
+ return Properties{}, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return Properties{}, 1
+ }
+ return Properties{entry: trie.lookupValue(uint32(i), c1)}, 2
+ case c0 < 0xF0: // 3-byte UTF-8
+ if len(s) < 3 {
+ return Properties{}, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return Properties{}, 1
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = bidiIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return Properties{}, 1
+ }
+ return Properties{entry: trie.lookupValue(uint32(i), c2), last: c2}, 3
+ case c0 < 0xF8: // 4-byte UTF-8
+ if len(s) < 4 {
+ return Properties{}, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return Properties{}, 1
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = bidiIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return Properties{}, 1
+ }
+ o = uint32(i)<<6 + uint32(c2)
+ i = bidiIndex[o]
+ c3 := s[3]
+ if c3 < 0x80 || 0xC0 <= c3 {
+ return Properties{}, 1
+ }
+ return Properties{entry: trie.lookupValue(uint32(i), c3)}, 4
+ }
+ // Illegal rune
+ return Properties{}, 1
+}
+
+// LookupString returns properties for the first rune in s and the width in
+// bytes of its encoding. The size will be 0 if s does not hold enough bytes to
+// complete the encoding.
+func LookupString(s string) (p Properties, sz int) {
+ c0 := s[0]
+ switch {
+ case c0 < 0x80: // is ASCII
+ return Properties{entry: bidiValues[c0]}, 1
+ case c0 < 0xC2:
+ return Properties{}, 1
+ case c0 < 0xE0: // 2-byte UTF-8
+ if len(s) < 2 {
+ return Properties{}, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return Properties{}, 1
+ }
+ return Properties{entry: trie.lookupValue(uint32(i), c1)}, 2
+ case c0 < 0xF0: // 3-byte UTF-8
+ if len(s) < 3 {
+ return Properties{}, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return Properties{}, 1
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = bidiIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return Properties{}, 1
+ }
+ return Properties{entry: trie.lookupValue(uint32(i), c2), last: c2}, 3
+ case c0 < 0xF8: // 4-byte UTF-8
+ if len(s) < 4 {
+ return Properties{}, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return Properties{}, 1
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = bidiIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return Properties{}, 1
+ }
+ o = uint32(i)<<6 + uint32(c2)
+ i = bidiIndex[o]
+ c3 := s[3]
+ if c3 < 0x80 || 0xC0 <= c3 {
+ return Properties{}, 1
+ }
+ return Properties{entry: trie.lookupValue(uint32(i), c3)}, 4
+ }
+ // Illegal rune
+ return Properties{}, 1
+}
diff --git a/vendor/golang.org/x/text/unicode/bidi/tables.go b/vendor/golang.org/x/text/unicode/bidi/tables.go
new file mode 100644
index 0000000..2d4dde0
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/bidi/tables.go
@@ -0,0 +1,1779 @@
+// This file was generated by go generate; DO NOT EDIT
+
+package bidi
+
+// UnicodeVersion is the Unicode version from which the tables in this package are derived.
+const UnicodeVersion = "9.0.0"
+
+// xorMasks contains masks to be xor-ed with brackets to get the reverse
+// version.
+var xorMasks = []int32{ // 8 elements
+ 0, 1, 6, 7, 3, 15, 29, 63,
+} // Size: 56 bytes
+
+// lookup returns the trie value for the first UTF-8 encoding in s and
+// the width in bytes of this encoding. The size will be 0 if s does not
+// hold enough bytes to complete the encoding. len(s) must be greater than 0.
+func (t *bidiTrie) lookup(s []byte) (v uint8, sz int) {
+ c0 := s[0]
+ switch {
+ case c0 < 0x80: // is ASCII
+ return bidiValues[c0], 1
+ case c0 < 0xC2:
+ return 0, 1 // Illegal UTF-8: not a starter, not ASCII.
+ case c0 < 0xE0: // 2-byte UTF-8
+ if len(s) < 2 {
+ return 0, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c1), 2
+ case c0 < 0xF0: // 3-byte UTF-8
+ if len(s) < 3 {
+ return 0, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = bidiIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c2), 3
+ case c0 < 0xF8: // 4-byte UTF-8
+ if len(s) < 4 {
+ return 0, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = bidiIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ o = uint32(i)<<6 + uint32(c2)
+ i = bidiIndex[o]
+ c3 := s[3]
+ if c3 < 0x80 || 0xC0 <= c3 {
+ return 0, 3 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c3), 4
+ }
+ // Illegal rune
+ return 0, 1
+}
+
+// lookupUnsafe returns the trie value for the first UTF-8 encoding in s.
+// s must start with a full and valid UTF-8 encoded rune.
+func (t *bidiTrie) lookupUnsafe(s []byte) uint8 {
+ c0 := s[0]
+ if c0 < 0x80 { // is ASCII
+ return bidiValues[c0]
+ }
+ i := bidiIndex[c0]
+ if c0 < 0xE0 { // 2-byte UTF-8
+ return t.lookupValue(uint32(i), s[1])
+ }
+ i = bidiIndex[uint32(i)<<6+uint32(s[1])]
+ if c0 < 0xF0 { // 3-byte UTF-8
+ return t.lookupValue(uint32(i), s[2])
+ }
+ i = bidiIndex[uint32(i)<<6+uint32(s[2])]
+ if c0 < 0xF8 { // 4-byte UTF-8
+ return t.lookupValue(uint32(i), s[3])
+ }
+ return 0
+}
+
+// lookupString returns the trie value for the first UTF-8 encoding in s and
+// the width in bytes of this encoding. The size will be 0 if s does not
+// hold enough bytes to complete the encoding. len(s) must be greater than 0.
+func (t *bidiTrie) lookupString(s string) (v uint8, sz int) {
+ c0 := s[0]
+ switch {
+ case c0 < 0x80: // is ASCII
+ return bidiValues[c0], 1
+ case c0 < 0xC2:
+ return 0, 1 // Illegal UTF-8: not a starter, not ASCII.
+ case c0 < 0xE0: // 2-byte UTF-8
+ if len(s) < 2 {
+ return 0, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c1), 2
+ case c0 < 0xF0: // 3-byte UTF-8
+ if len(s) < 3 {
+ return 0, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = bidiIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c2), 3
+ case c0 < 0xF8: // 4-byte UTF-8
+ if len(s) < 4 {
+ return 0, 0
+ }
+ i := bidiIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = bidiIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ o = uint32(i)<<6 + uint32(c2)
+ i = bidiIndex[o]
+ c3 := s[3]
+ if c3 < 0x80 || 0xC0 <= c3 {
+ return 0, 3 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c3), 4
+ }
+ // Illegal rune
+ return 0, 1
+}
+
+// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s.
+// s must start with a full and valid UTF-8 encoded rune.
+func (t *bidiTrie) lookupStringUnsafe(s string) uint8 {
+ c0 := s[0]
+ if c0 < 0x80 { // is ASCII
+ return bidiValues[c0]
+ }
+ i := bidiIndex[c0]
+ if c0 < 0xE0 { // 2-byte UTF-8
+ return t.lookupValue(uint32(i), s[1])
+ }
+ i = bidiIndex[uint32(i)<<6+uint32(s[1])]
+ if c0 < 0xF0 { // 3-byte UTF-8
+ return t.lookupValue(uint32(i), s[2])
+ }
+ i = bidiIndex[uint32(i)<<6+uint32(s[2])]
+ if c0 < 0xF8 { // 4-byte UTF-8
+ return t.lookupValue(uint32(i), s[3])
+ }
+ return 0
+}
+
+// bidiTrie. Total size: 15744 bytes (15.38 KiB). Checksum: b4c3b70954803b86.
+type bidiTrie struct{}
+
+func newBidiTrie(i int) *bidiTrie {
+ return &bidiTrie{}
+}
+
+// lookupValue determines the type of block n and looks up the value for b.
+func (t *bidiTrie) lookupValue(n uint32, b byte) uint8 {
+ switch {
+ default:
+ return uint8(bidiValues[n<<6+uint32(b)])
+ }
+}
+
+// bidiValues: 222 blocks, 14208 entries, 14208 bytes
+// The third block is the zero block.
+var bidiValues = [14208]uint8{
+ // Block 0x0, offset 0x0
+ 0x00: 0x000b, 0x01: 0x000b, 0x02: 0x000b, 0x03: 0x000b, 0x04: 0x000b, 0x05: 0x000b,
+ 0x06: 0x000b, 0x07: 0x000b, 0x08: 0x000b, 0x09: 0x0008, 0x0a: 0x0007, 0x0b: 0x0008,
+ 0x0c: 0x0009, 0x0d: 0x0007, 0x0e: 0x000b, 0x0f: 0x000b, 0x10: 0x000b, 0x11: 0x000b,
+ 0x12: 0x000b, 0x13: 0x000b, 0x14: 0x000b, 0x15: 0x000b, 0x16: 0x000b, 0x17: 0x000b,
+ 0x18: 0x000b, 0x19: 0x000b, 0x1a: 0x000b, 0x1b: 0x000b, 0x1c: 0x0007, 0x1d: 0x0007,
+ 0x1e: 0x0007, 0x1f: 0x0008, 0x20: 0x0009, 0x21: 0x000a, 0x22: 0x000a, 0x23: 0x0004,
+ 0x24: 0x0004, 0x25: 0x0004, 0x26: 0x000a, 0x27: 0x000a, 0x28: 0x003a, 0x29: 0x002a,
+ 0x2a: 0x000a, 0x2b: 0x0003, 0x2c: 0x0006, 0x2d: 0x0003, 0x2e: 0x0006, 0x2f: 0x0006,
+ 0x30: 0x0002, 0x31: 0x0002, 0x32: 0x0002, 0x33: 0x0002, 0x34: 0x0002, 0x35: 0x0002,
+ 0x36: 0x0002, 0x37: 0x0002, 0x38: 0x0002, 0x39: 0x0002, 0x3a: 0x0006, 0x3b: 0x000a,
+ 0x3c: 0x000a, 0x3d: 0x000a, 0x3e: 0x000a, 0x3f: 0x000a,
+ // Block 0x1, offset 0x40
+ 0x40: 0x000a,
+ 0x5b: 0x005a, 0x5c: 0x000a, 0x5d: 0x004a,
+ 0x5e: 0x000a, 0x5f: 0x000a, 0x60: 0x000a,
+ 0x7b: 0x005a,
+ 0x7c: 0x000a, 0x7d: 0x004a, 0x7e: 0x000a, 0x7f: 0x000b,
+ // Block 0x2, offset 0x80
+ // Block 0x3, offset 0xc0
+ 0xc0: 0x000b, 0xc1: 0x000b, 0xc2: 0x000b, 0xc3: 0x000b, 0xc4: 0x000b, 0xc5: 0x0007,
+ 0xc6: 0x000b, 0xc7: 0x000b, 0xc8: 0x000b, 0xc9: 0x000b, 0xca: 0x000b, 0xcb: 0x000b,
+ 0xcc: 0x000b, 0xcd: 0x000b, 0xce: 0x000b, 0xcf: 0x000b, 0xd0: 0x000b, 0xd1: 0x000b,
+ 0xd2: 0x000b, 0xd3: 0x000b, 0xd4: 0x000b, 0xd5: 0x000b, 0xd6: 0x000b, 0xd7: 0x000b,
+ 0xd8: 0x000b, 0xd9: 0x000b, 0xda: 0x000b, 0xdb: 0x000b, 0xdc: 0x000b, 0xdd: 0x000b,
+ 0xde: 0x000b, 0xdf: 0x000b, 0xe0: 0x0006, 0xe1: 0x000a, 0xe2: 0x0004, 0xe3: 0x0004,
+ 0xe4: 0x0004, 0xe5: 0x0004, 0xe6: 0x000a, 0xe7: 0x000a, 0xe8: 0x000a, 0xe9: 0x000a,
+ 0xeb: 0x000a, 0xec: 0x000a, 0xed: 0x000b, 0xee: 0x000a, 0xef: 0x000a,
+ 0xf0: 0x0004, 0xf1: 0x0004, 0xf2: 0x0002, 0xf3: 0x0002, 0xf4: 0x000a,
+ 0xf6: 0x000a, 0xf7: 0x000a, 0xf8: 0x000a, 0xf9: 0x0002, 0xfb: 0x000a,
+ 0xfc: 0x000a, 0xfd: 0x000a, 0xfe: 0x000a, 0xff: 0x000a,
+ // Block 0x4, offset 0x100
+ 0x117: 0x000a,
+ 0x137: 0x000a,
+ // Block 0x5, offset 0x140
+ 0x179: 0x000a, 0x17a: 0x000a,
+ // Block 0x6, offset 0x180
+ 0x182: 0x000a, 0x183: 0x000a, 0x184: 0x000a, 0x185: 0x000a,
+ 0x186: 0x000a, 0x187: 0x000a, 0x188: 0x000a, 0x189: 0x000a, 0x18a: 0x000a, 0x18b: 0x000a,
+ 0x18c: 0x000a, 0x18d: 0x000a, 0x18e: 0x000a, 0x18f: 0x000a,
+ 0x192: 0x000a, 0x193: 0x000a, 0x194: 0x000a, 0x195: 0x000a, 0x196: 0x000a, 0x197: 0x000a,
+ 0x198: 0x000a, 0x199: 0x000a, 0x19a: 0x000a, 0x19b: 0x000a, 0x19c: 0x000a, 0x19d: 0x000a,
+ 0x19e: 0x000a, 0x19f: 0x000a,
+ 0x1a5: 0x000a, 0x1a6: 0x000a, 0x1a7: 0x000a, 0x1a8: 0x000a, 0x1a9: 0x000a,
+ 0x1aa: 0x000a, 0x1ab: 0x000a, 0x1ac: 0x000a, 0x1ad: 0x000a, 0x1af: 0x000a,
+ 0x1b0: 0x000a, 0x1b1: 0x000a, 0x1b2: 0x000a, 0x1b3: 0x000a, 0x1b4: 0x000a, 0x1b5: 0x000a,
+ 0x1b6: 0x000a, 0x1b7: 0x000a, 0x1b8: 0x000a, 0x1b9: 0x000a, 0x1ba: 0x000a, 0x1bb: 0x000a,
+ 0x1bc: 0x000a, 0x1bd: 0x000a, 0x1be: 0x000a, 0x1bf: 0x000a,
+ // Block 0x7, offset 0x1c0
+ 0x1c0: 0x000c, 0x1c1: 0x000c, 0x1c2: 0x000c, 0x1c3: 0x000c, 0x1c4: 0x000c, 0x1c5: 0x000c,
+ 0x1c6: 0x000c, 0x1c7: 0x000c, 0x1c8: 0x000c, 0x1c9: 0x000c, 0x1ca: 0x000c, 0x1cb: 0x000c,
+ 0x1cc: 0x000c, 0x1cd: 0x000c, 0x1ce: 0x000c, 0x1cf: 0x000c, 0x1d0: 0x000c, 0x1d1: 0x000c,
+ 0x1d2: 0x000c, 0x1d3: 0x000c, 0x1d4: 0x000c, 0x1d5: 0x000c, 0x1d6: 0x000c, 0x1d7: 0x000c,
+ 0x1d8: 0x000c, 0x1d9: 0x000c, 0x1da: 0x000c, 0x1db: 0x000c, 0x1dc: 0x000c, 0x1dd: 0x000c,
+ 0x1de: 0x000c, 0x1df: 0x000c, 0x1e0: 0x000c, 0x1e1: 0x000c, 0x1e2: 0x000c, 0x1e3: 0x000c,
+ 0x1e4: 0x000c, 0x1e5: 0x000c, 0x1e6: 0x000c, 0x1e7: 0x000c, 0x1e8: 0x000c, 0x1e9: 0x000c,
+ 0x1ea: 0x000c, 0x1eb: 0x000c, 0x1ec: 0x000c, 0x1ed: 0x000c, 0x1ee: 0x000c, 0x1ef: 0x000c,
+ 0x1f0: 0x000c, 0x1f1: 0x000c, 0x1f2: 0x000c, 0x1f3: 0x000c, 0x1f4: 0x000c, 0x1f5: 0x000c,
+ 0x1f6: 0x000c, 0x1f7: 0x000c, 0x1f8: 0x000c, 0x1f9: 0x000c, 0x1fa: 0x000c, 0x1fb: 0x000c,
+ 0x1fc: 0x000c, 0x1fd: 0x000c, 0x1fe: 0x000c, 0x1ff: 0x000c,
+ // Block 0x8, offset 0x200
+ 0x200: 0x000c, 0x201: 0x000c, 0x202: 0x000c, 0x203: 0x000c, 0x204: 0x000c, 0x205: 0x000c,
+ 0x206: 0x000c, 0x207: 0x000c, 0x208: 0x000c, 0x209: 0x000c, 0x20a: 0x000c, 0x20b: 0x000c,
+ 0x20c: 0x000c, 0x20d: 0x000c, 0x20e: 0x000c, 0x20f: 0x000c, 0x210: 0x000c, 0x211: 0x000c,
+ 0x212: 0x000c, 0x213: 0x000c, 0x214: 0x000c, 0x215: 0x000c, 0x216: 0x000c, 0x217: 0x000c,
+ 0x218: 0x000c, 0x219: 0x000c, 0x21a: 0x000c, 0x21b: 0x000c, 0x21c: 0x000c, 0x21d: 0x000c,
+ 0x21e: 0x000c, 0x21f: 0x000c, 0x220: 0x000c, 0x221: 0x000c, 0x222: 0x000c, 0x223: 0x000c,
+ 0x224: 0x000c, 0x225: 0x000c, 0x226: 0x000c, 0x227: 0x000c, 0x228: 0x000c, 0x229: 0x000c,
+ 0x22a: 0x000c, 0x22b: 0x000c, 0x22c: 0x000c, 0x22d: 0x000c, 0x22e: 0x000c, 0x22f: 0x000c,
+ 0x234: 0x000a, 0x235: 0x000a,
+ 0x23e: 0x000a,
+ // Block 0x9, offset 0x240
+ 0x244: 0x000a, 0x245: 0x000a,
+ 0x247: 0x000a,
+ // Block 0xa, offset 0x280
+ 0x2b6: 0x000a,
+ // Block 0xb, offset 0x2c0
+ 0x2c3: 0x000c, 0x2c4: 0x000c, 0x2c5: 0x000c,
+ 0x2c6: 0x000c, 0x2c7: 0x000c, 0x2c8: 0x000c, 0x2c9: 0x000c,
+ // Block 0xc, offset 0x300
+ 0x30a: 0x000a,
+ 0x30d: 0x000a, 0x30e: 0x000a, 0x30f: 0x0004, 0x310: 0x0001, 0x311: 0x000c,
+ 0x312: 0x000c, 0x313: 0x000c, 0x314: 0x000c, 0x315: 0x000c, 0x316: 0x000c, 0x317: 0x000c,
+ 0x318: 0x000c, 0x319: 0x000c, 0x31a: 0x000c, 0x31b: 0x000c, 0x31c: 0x000c, 0x31d: 0x000c,
+ 0x31e: 0x000c, 0x31f: 0x000c, 0x320: 0x000c, 0x321: 0x000c, 0x322: 0x000c, 0x323: 0x000c,
+ 0x324: 0x000c, 0x325: 0x000c, 0x326: 0x000c, 0x327: 0x000c, 0x328: 0x000c, 0x329: 0x000c,
+ 0x32a: 0x000c, 0x32b: 0x000c, 0x32c: 0x000c, 0x32d: 0x000c, 0x32e: 0x000c, 0x32f: 0x000c,
+ 0x330: 0x000c, 0x331: 0x000c, 0x332: 0x000c, 0x333: 0x000c, 0x334: 0x000c, 0x335: 0x000c,
+ 0x336: 0x000c, 0x337: 0x000c, 0x338: 0x000c, 0x339: 0x000c, 0x33a: 0x000c, 0x33b: 0x000c,
+ 0x33c: 0x000c, 0x33d: 0x000c, 0x33e: 0x0001, 0x33f: 0x000c,
+ // Block 0xd, offset 0x340
+ 0x340: 0x0001, 0x341: 0x000c, 0x342: 0x000c, 0x343: 0x0001, 0x344: 0x000c, 0x345: 0x000c,
+ 0x346: 0x0001, 0x347: 0x000c, 0x348: 0x0001, 0x349: 0x0001, 0x34a: 0x0001, 0x34b: 0x0001,
+ 0x34c: 0x0001, 0x34d: 0x0001, 0x34e: 0x0001, 0x34f: 0x0001, 0x350: 0x0001, 0x351: 0x0001,
+ 0x352: 0x0001, 0x353: 0x0001, 0x354: 0x0001, 0x355: 0x0001, 0x356: 0x0001, 0x357: 0x0001,
+ 0x358: 0x0001, 0x359: 0x0001, 0x35a: 0x0001, 0x35b: 0x0001, 0x35c: 0x0001, 0x35d: 0x0001,
+ 0x35e: 0x0001, 0x35f: 0x0001, 0x360: 0x0001, 0x361: 0x0001, 0x362: 0x0001, 0x363: 0x0001,
+ 0x364: 0x0001, 0x365: 0x0001, 0x366: 0x0001, 0x367: 0x0001, 0x368: 0x0001, 0x369: 0x0001,
+ 0x36a: 0x0001, 0x36b: 0x0001, 0x36c: 0x0001, 0x36d: 0x0001, 0x36e: 0x0001, 0x36f: 0x0001,
+ 0x370: 0x0001, 0x371: 0x0001, 0x372: 0x0001, 0x373: 0x0001, 0x374: 0x0001, 0x375: 0x0001,
+ 0x376: 0x0001, 0x377: 0x0001, 0x378: 0x0001, 0x379: 0x0001, 0x37a: 0x0001, 0x37b: 0x0001,
+ 0x37c: 0x0001, 0x37d: 0x0001, 0x37e: 0x0001, 0x37f: 0x0001,
+ // Block 0xe, offset 0x380
+ 0x380: 0x0005, 0x381: 0x0005, 0x382: 0x0005, 0x383: 0x0005, 0x384: 0x0005, 0x385: 0x0005,
+ 0x386: 0x000a, 0x387: 0x000a, 0x388: 0x000d, 0x389: 0x0004, 0x38a: 0x0004, 0x38b: 0x000d,
+ 0x38c: 0x0006, 0x38d: 0x000d, 0x38e: 0x000a, 0x38f: 0x000a, 0x390: 0x000c, 0x391: 0x000c,
+ 0x392: 0x000c, 0x393: 0x000c, 0x394: 0x000c, 0x395: 0x000c, 0x396: 0x000c, 0x397: 0x000c,
+ 0x398: 0x000c, 0x399: 0x000c, 0x39a: 0x000c, 0x39b: 0x000d, 0x39c: 0x000d, 0x39d: 0x000d,
+ 0x39e: 0x000d, 0x39f: 0x000d, 0x3a0: 0x000d, 0x3a1: 0x000d, 0x3a2: 0x000d, 0x3a3: 0x000d,
+ 0x3a4: 0x000d, 0x3a5: 0x000d, 0x3a6: 0x000d, 0x3a7: 0x000d, 0x3a8: 0x000d, 0x3a9: 0x000d,
+ 0x3aa: 0x000d, 0x3ab: 0x000d, 0x3ac: 0x000d, 0x3ad: 0x000d, 0x3ae: 0x000d, 0x3af: 0x000d,
+ 0x3b0: 0x000d, 0x3b1: 0x000d, 0x3b2: 0x000d, 0x3b3: 0x000d, 0x3b4: 0x000d, 0x3b5: 0x000d,
+ 0x3b6: 0x000d, 0x3b7: 0x000d, 0x3b8: 0x000d, 0x3b9: 0x000d, 0x3ba: 0x000d, 0x3bb: 0x000d,
+ 0x3bc: 0x000d, 0x3bd: 0x000d, 0x3be: 0x000d, 0x3bf: 0x000d,
+ // Block 0xf, offset 0x3c0
+ 0x3c0: 0x000d, 0x3c1: 0x000d, 0x3c2: 0x000d, 0x3c3: 0x000d, 0x3c4: 0x000d, 0x3c5: 0x000d,
+ 0x3c6: 0x000d, 0x3c7: 0x000d, 0x3c8: 0x000d, 0x3c9: 0x000d, 0x3ca: 0x000d, 0x3cb: 0x000c,
+ 0x3cc: 0x000c, 0x3cd: 0x000c, 0x3ce: 0x000c, 0x3cf: 0x000c, 0x3d0: 0x000c, 0x3d1: 0x000c,
+ 0x3d2: 0x000c, 0x3d3: 0x000c, 0x3d4: 0x000c, 0x3d5: 0x000c, 0x3d6: 0x000c, 0x3d7: 0x000c,
+ 0x3d8: 0x000c, 0x3d9: 0x000c, 0x3da: 0x000c, 0x3db: 0x000c, 0x3dc: 0x000c, 0x3dd: 0x000c,
+ 0x3de: 0x000c, 0x3df: 0x000c, 0x3e0: 0x0005, 0x3e1: 0x0005, 0x3e2: 0x0005, 0x3e3: 0x0005,
+ 0x3e4: 0x0005, 0x3e5: 0x0005, 0x3e6: 0x0005, 0x3e7: 0x0005, 0x3e8: 0x0005, 0x3e9: 0x0005,
+ 0x3ea: 0x0004, 0x3eb: 0x0005, 0x3ec: 0x0005, 0x3ed: 0x000d, 0x3ee: 0x000d, 0x3ef: 0x000d,
+ 0x3f0: 0x000c, 0x3f1: 0x000d, 0x3f2: 0x000d, 0x3f3: 0x000d, 0x3f4: 0x000d, 0x3f5: 0x000d,
+ 0x3f6: 0x000d, 0x3f7: 0x000d, 0x3f8: 0x000d, 0x3f9: 0x000d, 0x3fa: 0x000d, 0x3fb: 0x000d,
+ 0x3fc: 0x000d, 0x3fd: 0x000d, 0x3fe: 0x000d, 0x3ff: 0x000d,
+ // Block 0x10, offset 0x400
+ 0x400: 0x000d, 0x401: 0x000d, 0x402: 0x000d, 0x403: 0x000d, 0x404: 0x000d, 0x405: 0x000d,
+ 0x406: 0x000d, 0x407: 0x000d, 0x408: 0x000d, 0x409: 0x000d, 0x40a: 0x000d, 0x40b: 0x000d,
+ 0x40c: 0x000d, 0x40d: 0x000d, 0x40e: 0x000d, 0x40f: 0x000d, 0x410: 0x000d, 0x411: 0x000d,
+ 0x412: 0x000d, 0x413: 0x000d, 0x414: 0x000d, 0x415: 0x000d, 0x416: 0x000d, 0x417: 0x000d,
+ 0x418: 0x000d, 0x419: 0x000d, 0x41a: 0x000d, 0x41b: 0x000d, 0x41c: 0x000d, 0x41d: 0x000d,
+ 0x41e: 0x000d, 0x41f: 0x000d, 0x420: 0x000d, 0x421: 0x000d, 0x422: 0x000d, 0x423: 0x000d,
+ 0x424: 0x000d, 0x425: 0x000d, 0x426: 0x000d, 0x427: 0x000d, 0x428: 0x000d, 0x429: 0x000d,
+ 0x42a: 0x000d, 0x42b: 0x000d, 0x42c: 0x000d, 0x42d: 0x000d, 0x42e: 0x000d, 0x42f: 0x000d,
+ 0x430: 0x000d, 0x431: 0x000d, 0x432: 0x000d, 0x433: 0x000d, 0x434: 0x000d, 0x435: 0x000d,
+ 0x436: 0x000d, 0x437: 0x000d, 0x438: 0x000d, 0x439: 0x000d, 0x43a: 0x000d, 0x43b: 0x000d,
+ 0x43c: 0x000d, 0x43d: 0x000d, 0x43e: 0x000d, 0x43f: 0x000d,
+ // Block 0x11, offset 0x440
+ 0x440: 0x000d, 0x441: 0x000d, 0x442: 0x000d, 0x443: 0x000d, 0x444: 0x000d, 0x445: 0x000d,
+ 0x446: 0x000d, 0x447: 0x000d, 0x448: 0x000d, 0x449: 0x000d, 0x44a: 0x000d, 0x44b: 0x000d,
+ 0x44c: 0x000d, 0x44d: 0x000d, 0x44e: 0x000d, 0x44f: 0x000d, 0x450: 0x000d, 0x451: 0x000d,
+ 0x452: 0x000d, 0x453: 0x000d, 0x454: 0x000d, 0x455: 0x000d, 0x456: 0x000c, 0x457: 0x000c,
+ 0x458: 0x000c, 0x459: 0x000c, 0x45a: 0x000c, 0x45b: 0x000c, 0x45c: 0x000c, 0x45d: 0x0005,
+ 0x45e: 0x000a, 0x45f: 0x000c, 0x460: 0x000c, 0x461: 0x000c, 0x462: 0x000c, 0x463: 0x000c,
+ 0x464: 0x000c, 0x465: 0x000d, 0x466: 0x000d, 0x467: 0x000c, 0x468: 0x000c, 0x469: 0x000a,
+ 0x46a: 0x000c, 0x46b: 0x000c, 0x46c: 0x000c, 0x46d: 0x000c, 0x46e: 0x000d, 0x46f: 0x000d,
+ 0x470: 0x0002, 0x471: 0x0002, 0x472: 0x0002, 0x473: 0x0002, 0x474: 0x0002, 0x475: 0x0002,
+ 0x476: 0x0002, 0x477: 0x0002, 0x478: 0x0002, 0x479: 0x0002, 0x47a: 0x000d, 0x47b: 0x000d,
+ 0x47c: 0x000d, 0x47d: 0x000d, 0x47e: 0x000d, 0x47f: 0x000d,
+ // Block 0x12, offset 0x480
+ 0x480: 0x000d, 0x481: 0x000d, 0x482: 0x000d, 0x483: 0x000d, 0x484: 0x000d, 0x485: 0x000d,
+ 0x486: 0x000d, 0x487: 0x000d, 0x488: 0x000d, 0x489: 0x000d, 0x48a: 0x000d, 0x48b: 0x000d,
+ 0x48c: 0x000d, 0x48d: 0x000d, 0x48e: 0x000d, 0x48f: 0x000d, 0x490: 0x000d, 0x491: 0x000c,
+ 0x492: 0x000d, 0x493: 0x000d, 0x494: 0x000d, 0x495: 0x000d, 0x496: 0x000d, 0x497: 0x000d,
+ 0x498: 0x000d, 0x499: 0x000d, 0x49a: 0x000d, 0x49b: 0x000d, 0x49c: 0x000d, 0x49d: 0x000d,
+ 0x49e: 0x000d, 0x49f: 0x000d, 0x4a0: 0x000d, 0x4a1: 0x000d, 0x4a2: 0x000d, 0x4a3: 0x000d,
+ 0x4a4: 0x000d, 0x4a5: 0x000d, 0x4a6: 0x000d, 0x4a7: 0x000d, 0x4a8: 0x000d, 0x4a9: 0x000d,
+ 0x4aa: 0x000d, 0x4ab: 0x000d, 0x4ac: 0x000d, 0x4ad: 0x000d, 0x4ae: 0x000d, 0x4af: 0x000d,
+ 0x4b0: 0x000c, 0x4b1: 0x000c, 0x4b2: 0x000c, 0x4b3: 0x000c, 0x4b4: 0x000c, 0x4b5: 0x000c,
+ 0x4b6: 0x000c, 0x4b7: 0x000c, 0x4b8: 0x000c, 0x4b9: 0x000c, 0x4ba: 0x000c, 0x4bb: 0x000c,
+ 0x4bc: 0x000c, 0x4bd: 0x000c, 0x4be: 0x000c, 0x4bf: 0x000c,
+ // Block 0x13, offset 0x4c0
+ 0x4c0: 0x000c, 0x4c1: 0x000c, 0x4c2: 0x000c, 0x4c3: 0x000c, 0x4c4: 0x000c, 0x4c5: 0x000c,
+ 0x4c6: 0x000c, 0x4c7: 0x000c, 0x4c8: 0x000c, 0x4c9: 0x000c, 0x4ca: 0x000c, 0x4cb: 0x000d,
+ 0x4cc: 0x000d, 0x4cd: 0x000d, 0x4ce: 0x000d, 0x4cf: 0x000d, 0x4d0: 0x000d, 0x4d1: 0x000d,
+ 0x4d2: 0x000d, 0x4d3: 0x000d, 0x4d4: 0x000d, 0x4d5: 0x000d, 0x4d6: 0x000d, 0x4d7: 0x000d,
+ 0x4d8: 0x000d, 0x4d9: 0x000d, 0x4da: 0x000d, 0x4db: 0x000d, 0x4dc: 0x000d, 0x4dd: 0x000d,
+ 0x4de: 0x000d, 0x4df: 0x000d, 0x4e0: 0x000d, 0x4e1: 0x000d, 0x4e2: 0x000d, 0x4e3: 0x000d,
+ 0x4e4: 0x000d, 0x4e5: 0x000d, 0x4e6: 0x000d, 0x4e7: 0x000d, 0x4e8: 0x000d, 0x4e9: 0x000d,
+ 0x4ea: 0x000d, 0x4eb: 0x000d, 0x4ec: 0x000d, 0x4ed: 0x000d, 0x4ee: 0x000d, 0x4ef: 0x000d,
+ 0x4f0: 0x000d, 0x4f1: 0x000d, 0x4f2: 0x000d, 0x4f3: 0x000d, 0x4f4: 0x000d, 0x4f5: 0x000d,
+ 0x4f6: 0x000d, 0x4f7: 0x000d, 0x4f8: 0x000d, 0x4f9: 0x000d, 0x4fa: 0x000d, 0x4fb: 0x000d,
+ 0x4fc: 0x000d, 0x4fd: 0x000d, 0x4fe: 0x000d, 0x4ff: 0x000d,
+ // Block 0x14, offset 0x500
+ 0x500: 0x000d, 0x501: 0x000d, 0x502: 0x000d, 0x503: 0x000d, 0x504: 0x000d, 0x505: 0x000d,
+ 0x506: 0x000d, 0x507: 0x000d, 0x508: 0x000d, 0x509: 0x000d, 0x50a: 0x000d, 0x50b: 0x000d,
+ 0x50c: 0x000d, 0x50d: 0x000d, 0x50e: 0x000d, 0x50f: 0x000d, 0x510: 0x000d, 0x511: 0x000d,
+ 0x512: 0x000d, 0x513: 0x000d, 0x514: 0x000d, 0x515: 0x000d, 0x516: 0x000d, 0x517: 0x000d,
+ 0x518: 0x000d, 0x519: 0x000d, 0x51a: 0x000d, 0x51b: 0x000d, 0x51c: 0x000d, 0x51d: 0x000d,
+ 0x51e: 0x000d, 0x51f: 0x000d, 0x520: 0x000d, 0x521: 0x000d, 0x522: 0x000d, 0x523: 0x000d,
+ 0x524: 0x000d, 0x525: 0x000d, 0x526: 0x000c, 0x527: 0x000c, 0x528: 0x000c, 0x529: 0x000c,
+ 0x52a: 0x000c, 0x52b: 0x000c, 0x52c: 0x000c, 0x52d: 0x000c, 0x52e: 0x000c, 0x52f: 0x000c,
+ 0x530: 0x000c, 0x531: 0x000d, 0x532: 0x000d, 0x533: 0x000d, 0x534: 0x000d, 0x535: 0x000d,
+ 0x536: 0x000d, 0x537: 0x000d, 0x538: 0x000d, 0x539: 0x000d, 0x53a: 0x000d, 0x53b: 0x000d,
+ 0x53c: 0x000d, 0x53d: 0x000d, 0x53e: 0x000d, 0x53f: 0x000d,
+ // Block 0x15, offset 0x540
+ 0x540: 0x0001, 0x541: 0x0001, 0x542: 0x0001, 0x543: 0x0001, 0x544: 0x0001, 0x545: 0x0001,
+ 0x546: 0x0001, 0x547: 0x0001, 0x548: 0x0001, 0x549: 0x0001, 0x54a: 0x0001, 0x54b: 0x0001,
+ 0x54c: 0x0001, 0x54d: 0x0001, 0x54e: 0x0001, 0x54f: 0x0001, 0x550: 0x0001, 0x551: 0x0001,
+ 0x552: 0x0001, 0x553: 0x0001, 0x554: 0x0001, 0x555: 0x0001, 0x556: 0x0001, 0x557: 0x0001,
+ 0x558: 0x0001, 0x559: 0x0001, 0x55a: 0x0001, 0x55b: 0x0001, 0x55c: 0x0001, 0x55d: 0x0001,
+ 0x55e: 0x0001, 0x55f: 0x0001, 0x560: 0x0001, 0x561: 0x0001, 0x562: 0x0001, 0x563: 0x0001,
+ 0x564: 0x0001, 0x565: 0x0001, 0x566: 0x0001, 0x567: 0x0001, 0x568: 0x0001, 0x569: 0x0001,
+ 0x56a: 0x0001, 0x56b: 0x000c, 0x56c: 0x000c, 0x56d: 0x000c, 0x56e: 0x000c, 0x56f: 0x000c,
+ 0x570: 0x000c, 0x571: 0x000c, 0x572: 0x000c, 0x573: 0x000c, 0x574: 0x0001, 0x575: 0x0001,
+ 0x576: 0x000a, 0x577: 0x000a, 0x578: 0x000a, 0x579: 0x000a, 0x57a: 0x0001, 0x57b: 0x0001,
+ 0x57c: 0x0001, 0x57d: 0x0001, 0x57e: 0x0001, 0x57f: 0x0001,
+ // Block 0x16, offset 0x580
+ 0x580: 0x0001, 0x581: 0x0001, 0x582: 0x0001, 0x583: 0x0001, 0x584: 0x0001, 0x585: 0x0001,
+ 0x586: 0x0001, 0x587: 0x0001, 0x588: 0x0001, 0x589: 0x0001, 0x58a: 0x0001, 0x58b: 0x0001,
+ 0x58c: 0x0001, 0x58d: 0x0001, 0x58e: 0x0001, 0x58f: 0x0001, 0x590: 0x0001, 0x591: 0x0001,
+ 0x592: 0x0001, 0x593: 0x0001, 0x594: 0x0001, 0x595: 0x0001, 0x596: 0x000c, 0x597: 0x000c,
+ 0x598: 0x000c, 0x599: 0x000c, 0x59a: 0x0001, 0x59b: 0x000c, 0x59c: 0x000c, 0x59d: 0x000c,
+ 0x59e: 0x000c, 0x59f: 0x000c, 0x5a0: 0x000c, 0x5a1: 0x000c, 0x5a2: 0x000c, 0x5a3: 0x000c,
+ 0x5a4: 0x0001, 0x5a5: 0x000c, 0x5a6: 0x000c, 0x5a7: 0x000c, 0x5a8: 0x0001, 0x5a9: 0x000c,
+ 0x5aa: 0x000c, 0x5ab: 0x000c, 0x5ac: 0x000c, 0x5ad: 0x000c, 0x5ae: 0x0001, 0x5af: 0x0001,
+ 0x5b0: 0x0001, 0x5b1: 0x0001, 0x5b2: 0x0001, 0x5b3: 0x0001, 0x5b4: 0x0001, 0x5b5: 0x0001,
+ 0x5b6: 0x0001, 0x5b7: 0x0001, 0x5b8: 0x0001, 0x5b9: 0x0001, 0x5ba: 0x0001, 0x5bb: 0x0001,
+ 0x5bc: 0x0001, 0x5bd: 0x0001, 0x5be: 0x0001, 0x5bf: 0x0001,
+ // Block 0x17, offset 0x5c0
+ 0x5c0: 0x0001, 0x5c1: 0x0001, 0x5c2: 0x0001, 0x5c3: 0x0001, 0x5c4: 0x0001, 0x5c5: 0x0001,
+ 0x5c6: 0x0001, 0x5c7: 0x0001, 0x5c8: 0x0001, 0x5c9: 0x0001, 0x5ca: 0x0001, 0x5cb: 0x0001,
+ 0x5cc: 0x0001, 0x5cd: 0x0001, 0x5ce: 0x0001, 0x5cf: 0x0001, 0x5d0: 0x0001, 0x5d1: 0x0001,
+ 0x5d2: 0x0001, 0x5d3: 0x0001, 0x5d4: 0x0001, 0x5d5: 0x0001, 0x5d6: 0x0001, 0x5d7: 0x0001,
+ 0x5d8: 0x0001, 0x5d9: 0x000c, 0x5da: 0x000c, 0x5db: 0x000c, 0x5dc: 0x0001, 0x5dd: 0x0001,
+ 0x5de: 0x0001, 0x5df: 0x0001, 0x5e0: 0x0001, 0x5e1: 0x0001, 0x5e2: 0x0001, 0x5e3: 0x0001,
+ 0x5e4: 0x0001, 0x5e5: 0x0001, 0x5e6: 0x0001, 0x5e7: 0x0001, 0x5e8: 0x0001, 0x5e9: 0x0001,
+ 0x5ea: 0x0001, 0x5eb: 0x0001, 0x5ec: 0x0001, 0x5ed: 0x0001, 0x5ee: 0x0001, 0x5ef: 0x0001,
+ 0x5f0: 0x0001, 0x5f1: 0x0001, 0x5f2: 0x0001, 0x5f3: 0x0001, 0x5f4: 0x0001, 0x5f5: 0x0001,
+ 0x5f6: 0x0001, 0x5f7: 0x0001, 0x5f8: 0x0001, 0x5f9: 0x0001, 0x5fa: 0x0001, 0x5fb: 0x0001,
+ 0x5fc: 0x0001, 0x5fd: 0x0001, 0x5fe: 0x0001, 0x5ff: 0x0001,
+ // Block 0x18, offset 0x600
+ 0x600: 0x0001, 0x601: 0x0001, 0x602: 0x0001, 0x603: 0x0001, 0x604: 0x0001, 0x605: 0x0001,
+ 0x606: 0x0001, 0x607: 0x0001, 0x608: 0x0001, 0x609: 0x0001, 0x60a: 0x0001, 0x60b: 0x0001,
+ 0x60c: 0x0001, 0x60d: 0x0001, 0x60e: 0x0001, 0x60f: 0x0001, 0x610: 0x0001, 0x611: 0x0001,
+ 0x612: 0x0001, 0x613: 0x0001, 0x614: 0x0001, 0x615: 0x0001, 0x616: 0x0001, 0x617: 0x0001,
+ 0x618: 0x0001, 0x619: 0x0001, 0x61a: 0x0001, 0x61b: 0x0001, 0x61c: 0x0001, 0x61d: 0x0001,
+ 0x61e: 0x0001, 0x61f: 0x0001, 0x620: 0x000d, 0x621: 0x000d, 0x622: 0x000d, 0x623: 0x000d,
+ 0x624: 0x000d, 0x625: 0x000d, 0x626: 0x000d, 0x627: 0x000d, 0x628: 0x000d, 0x629: 0x000d,
+ 0x62a: 0x000d, 0x62b: 0x000d, 0x62c: 0x000d, 0x62d: 0x000d, 0x62e: 0x000d, 0x62f: 0x000d,
+ 0x630: 0x000d, 0x631: 0x000d, 0x632: 0x000d, 0x633: 0x000d, 0x634: 0x000d, 0x635: 0x000d,
+ 0x636: 0x000d, 0x637: 0x000d, 0x638: 0x000d, 0x639: 0x000d, 0x63a: 0x000d, 0x63b: 0x000d,
+ 0x63c: 0x000d, 0x63d: 0x000d, 0x63e: 0x000d, 0x63f: 0x000d,
+ // Block 0x19, offset 0x640
+ 0x640: 0x000d, 0x641: 0x000d, 0x642: 0x000d, 0x643: 0x000d, 0x644: 0x000d, 0x645: 0x000d,
+ 0x646: 0x000d, 0x647: 0x000d, 0x648: 0x000d, 0x649: 0x000d, 0x64a: 0x000d, 0x64b: 0x000d,
+ 0x64c: 0x000d, 0x64d: 0x000d, 0x64e: 0x000d, 0x64f: 0x000d, 0x650: 0x000d, 0x651: 0x000d,
+ 0x652: 0x000d, 0x653: 0x000d, 0x654: 0x000c, 0x655: 0x000c, 0x656: 0x000c, 0x657: 0x000c,
+ 0x658: 0x000c, 0x659: 0x000c, 0x65a: 0x000c, 0x65b: 0x000c, 0x65c: 0x000c, 0x65d: 0x000c,
+ 0x65e: 0x000c, 0x65f: 0x000c, 0x660: 0x000c, 0x661: 0x000c, 0x662: 0x0005, 0x663: 0x000c,
+ 0x664: 0x000c, 0x665: 0x000c, 0x666: 0x000c, 0x667: 0x000c, 0x668: 0x000c, 0x669: 0x000c,
+ 0x66a: 0x000c, 0x66b: 0x000c, 0x66c: 0x000c, 0x66d: 0x000c, 0x66e: 0x000c, 0x66f: 0x000c,
+ 0x670: 0x000c, 0x671: 0x000c, 0x672: 0x000c, 0x673: 0x000c, 0x674: 0x000c, 0x675: 0x000c,
+ 0x676: 0x000c, 0x677: 0x000c, 0x678: 0x000c, 0x679: 0x000c, 0x67a: 0x000c, 0x67b: 0x000c,
+ 0x67c: 0x000c, 0x67d: 0x000c, 0x67e: 0x000c, 0x67f: 0x000c,
+ // Block 0x1a, offset 0x680
+ 0x680: 0x000c, 0x681: 0x000c, 0x682: 0x000c,
+ 0x6ba: 0x000c,
+ 0x6bc: 0x000c,
+ // Block 0x1b, offset 0x6c0
+ 0x6c1: 0x000c, 0x6c2: 0x000c, 0x6c3: 0x000c, 0x6c4: 0x000c, 0x6c5: 0x000c,
+ 0x6c6: 0x000c, 0x6c7: 0x000c, 0x6c8: 0x000c,
+ 0x6cd: 0x000c, 0x6d1: 0x000c,
+ 0x6d2: 0x000c, 0x6d3: 0x000c, 0x6d4: 0x000c, 0x6d5: 0x000c, 0x6d6: 0x000c, 0x6d7: 0x000c,
+ 0x6e2: 0x000c, 0x6e3: 0x000c,
+ // Block 0x1c, offset 0x700
+ 0x701: 0x000c,
+ 0x73c: 0x000c,
+ // Block 0x1d, offset 0x740
+ 0x741: 0x000c, 0x742: 0x000c, 0x743: 0x000c, 0x744: 0x000c,
+ 0x74d: 0x000c,
+ 0x762: 0x000c, 0x763: 0x000c,
+ 0x772: 0x0004, 0x773: 0x0004,
+ 0x77b: 0x0004,
+ // Block 0x1e, offset 0x780
+ 0x781: 0x000c, 0x782: 0x000c,
+ 0x7bc: 0x000c,
+ // Block 0x1f, offset 0x7c0
+ 0x7c1: 0x000c, 0x7c2: 0x000c,
+ 0x7c7: 0x000c, 0x7c8: 0x000c, 0x7cb: 0x000c,
+ 0x7cc: 0x000c, 0x7cd: 0x000c, 0x7d1: 0x000c,
+ 0x7f0: 0x000c, 0x7f1: 0x000c, 0x7f5: 0x000c,
+ // Block 0x20, offset 0x800
+ 0x801: 0x000c, 0x802: 0x000c, 0x803: 0x000c, 0x804: 0x000c, 0x805: 0x000c,
+ 0x807: 0x000c, 0x808: 0x000c,
+ 0x80d: 0x000c,
+ 0x822: 0x000c, 0x823: 0x000c,
+ 0x831: 0x0004,
+ // Block 0x21, offset 0x840
+ 0x841: 0x000c,
+ 0x87c: 0x000c, 0x87f: 0x000c,
+ // Block 0x22, offset 0x880
+ 0x881: 0x000c, 0x882: 0x000c, 0x883: 0x000c, 0x884: 0x000c,
+ 0x88d: 0x000c,
+ 0x896: 0x000c,
+ 0x8a2: 0x000c, 0x8a3: 0x000c,
+ // Block 0x23, offset 0x8c0
+ 0x8c2: 0x000c,
+ // Block 0x24, offset 0x900
+ 0x900: 0x000c,
+ 0x90d: 0x000c,
+ 0x933: 0x000a, 0x934: 0x000a, 0x935: 0x000a,
+ 0x936: 0x000a, 0x937: 0x000a, 0x938: 0x000a, 0x939: 0x0004, 0x93a: 0x000a,
+ // Block 0x25, offset 0x940
+ 0x940: 0x000c,
+ 0x97e: 0x000c, 0x97f: 0x000c,
+ // Block 0x26, offset 0x980
+ 0x980: 0x000c,
+ 0x986: 0x000c, 0x987: 0x000c, 0x988: 0x000c, 0x98a: 0x000c, 0x98b: 0x000c,
+ 0x98c: 0x000c, 0x98d: 0x000c,
+ 0x995: 0x000c, 0x996: 0x000c,
+ 0x9a2: 0x000c, 0x9a3: 0x000c,
+ 0x9b8: 0x000a, 0x9b9: 0x000a, 0x9ba: 0x000a, 0x9bb: 0x000a,
+ 0x9bc: 0x000a, 0x9bd: 0x000a, 0x9be: 0x000a,
+ // Block 0x27, offset 0x9c0
+ 0x9cc: 0x000c, 0x9cd: 0x000c,
+ 0x9e2: 0x000c, 0x9e3: 0x000c,
+ // Block 0x28, offset 0xa00
+ 0xa01: 0x000c,
+ // Block 0x29, offset 0xa40
+ 0xa41: 0x000c, 0xa42: 0x000c, 0xa43: 0x000c, 0xa44: 0x000c,
+ 0xa4d: 0x000c,
+ 0xa62: 0x000c, 0xa63: 0x000c,
+ // Block 0x2a, offset 0xa80
+ 0xa8a: 0x000c,
+ 0xa92: 0x000c, 0xa93: 0x000c, 0xa94: 0x000c, 0xa96: 0x000c,
+ // Block 0x2b, offset 0xac0
+ 0xaf1: 0x000c, 0xaf4: 0x000c, 0xaf5: 0x000c,
+ 0xaf6: 0x000c, 0xaf7: 0x000c, 0xaf8: 0x000c, 0xaf9: 0x000c, 0xafa: 0x000c,
+ 0xaff: 0x0004,
+ // Block 0x2c, offset 0xb00
+ 0xb07: 0x000c, 0xb08: 0x000c, 0xb09: 0x000c, 0xb0a: 0x000c, 0xb0b: 0x000c,
+ 0xb0c: 0x000c, 0xb0d: 0x000c, 0xb0e: 0x000c,
+ // Block 0x2d, offset 0xb40
+ 0xb71: 0x000c, 0xb74: 0x000c, 0xb75: 0x000c,
+ 0xb76: 0x000c, 0xb77: 0x000c, 0xb78: 0x000c, 0xb79: 0x000c, 0xb7b: 0x000c,
+ 0xb7c: 0x000c,
+ // Block 0x2e, offset 0xb80
+ 0xb88: 0x000c, 0xb89: 0x000c, 0xb8a: 0x000c, 0xb8b: 0x000c,
+ 0xb8c: 0x000c, 0xb8d: 0x000c,
+ // Block 0x2f, offset 0xbc0
+ 0xbd8: 0x000c, 0xbd9: 0x000c,
+ 0xbf5: 0x000c,
+ 0xbf7: 0x000c, 0xbf9: 0x000c, 0xbfa: 0x003a, 0xbfb: 0x002a,
+ 0xbfc: 0x003a, 0xbfd: 0x002a,
+ // Block 0x30, offset 0xc00
+ 0xc31: 0x000c, 0xc32: 0x000c, 0xc33: 0x000c, 0xc34: 0x000c, 0xc35: 0x000c,
+ 0xc36: 0x000c, 0xc37: 0x000c, 0xc38: 0x000c, 0xc39: 0x000c, 0xc3a: 0x000c, 0xc3b: 0x000c,
+ 0xc3c: 0x000c, 0xc3d: 0x000c, 0xc3e: 0x000c,
+ // Block 0x31, offset 0xc40
+ 0xc40: 0x000c, 0xc41: 0x000c, 0xc42: 0x000c, 0xc43: 0x000c, 0xc44: 0x000c,
+ 0xc46: 0x000c, 0xc47: 0x000c,
+ 0xc4d: 0x000c, 0xc4e: 0x000c, 0xc4f: 0x000c, 0xc50: 0x000c, 0xc51: 0x000c,
+ 0xc52: 0x000c, 0xc53: 0x000c, 0xc54: 0x000c, 0xc55: 0x000c, 0xc56: 0x000c, 0xc57: 0x000c,
+ 0xc59: 0x000c, 0xc5a: 0x000c, 0xc5b: 0x000c, 0xc5c: 0x000c, 0xc5d: 0x000c,
+ 0xc5e: 0x000c, 0xc5f: 0x000c, 0xc60: 0x000c, 0xc61: 0x000c, 0xc62: 0x000c, 0xc63: 0x000c,
+ 0xc64: 0x000c, 0xc65: 0x000c, 0xc66: 0x000c, 0xc67: 0x000c, 0xc68: 0x000c, 0xc69: 0x000c,
+ 0xc6a: 0x000c, 0xc6b: 0x000c, 0xc6c: 0x000c, 0xc6d: 0x000c, 0xc6e: 0x000c, 0xc6f: 0x000c,
+ 0xc70: 0x000c, 0xc71: 0x000c, 0xc72: 0x000c, 0xc73: 0x000c, 0xc74: 0x000c, 0xc75: 0x000c,
+ 0xc76: 0x000c, 0xc77: 0x000c, 0xc78: 0x000c, 0xc79: 0x000c, 0xc7a: 0x000c, 0xc7b: 0x000c,
+ 0xc7c: 0x000c,
+ // Block 0x32, offset 0xc80
+ 0xc86: 0x000c,
+ // Block 0x33, offset 0xcc0
+ 0xced: 0x000c, 0xcee: 0x000c, 0xcef: 0x000c,
+ 0xcf0: 0x000c, 0xcf2: 0x000c, 0xcf3: 0x000c, 0xcf4: 0x000c, 0xcf5: 0x000c,
+ 0xcf6: 0x000c, 0xcf7: 0x000c, 0xcf9: 0x000c, 0xcfa: 0x000c,
+ 0xcfd: 0x000c, 0xcfe: 0x000c,
+ // Block 0x34, offset 0xd00
+ 0xd18: 0x000c, 0xd19: 0x000c,
+ 0xd1e: 0x000c, 0xd1f: 0x000c, 0xd20: 0x000c,
+ 0xd31: 0x000c, 0xd32: 0x000c, 0xd33: 0x000c, 0xd34: 0x000c,
+ // Block 0x35, offset 0xd40
+ 0xd42: 0x000c, 0xd45: 0x000c,
+ 0xd46: 0x000c,
+ 0xd4d: 0x000c,
+ 0xd5d: 0x000c,
+ // Block 0x36, offset 0xd80
+ 0xd9d: 0x000c,
+ 0xd9e: 0x000c, 0xd9f: 0x000c,
+ // Block 0x37, offset 0xdc0
+ 0xdd0: 0x000a, 0xdd1: 0x000a,
+ 0xdd2: 0x000a, 0xdd3: 0x000a, 0xdd4: 0x000a, 0xdd5: 0x000a, 0xdd6: 0x000a, 0xdd7: 0x000a,
+ 0xdd8: 0x000a, 0xdd9: 0x000a,
+ // Block 0x38, offset 0xe00
+ 0xe00: 0x000a,
+ // Block 0x39, offset 0xe40
+ 0xe40: 0x0009,
+ 0xe5b: 0x007a, 0xe5c: 0x006a,
+ // Block 0x3a, offset 0xe80
+ 0xe92: 0x000c, 0xe93: 0x000c, 0xe94: 0x000c,
+ 0xeb2: 0x000c, 0xeb3: 0x000c, 0xeb4: 0x000c,
+ // Block 0x3b, offset 0xec0
+ 0xed2: 0x000c, 0xed3: 0x000c,
+ 0xef2: 0x000c, 0xef3: 0x000c,
+ // Block 0x3c, offset 0xf00
+ 0xf34: 0x000c, 0xf35: 0x000c,
+ 0xf37: 0x000c, 0xf38: 0x000c, 0xf39: 0x000c, 0xf3a: 0x000c, 0xf3b: 0x000c,
+ 0xf3c: 0x000c, 0xf3d: 0x000c,
+ // Block 0x3d, offset 0xf40
+ 0xf46: 0x000c, 0xf49: 0x000c, 0xf4a: 0x000c, 0xf4b: 0x000c,
+ 0xf4c: 0x000c, 0xf4d: 0x000c, 0xf4e: 0x000c, 0xf4f: 0x000c, 0xf50: 0x000c, 0xf51: 0x000c,
+ 0xf52: 0x000c, 0xf53: 0x000c,
+ 0xf5b: 0x0004, 0xf5d: 0x000c,
+ 0xf70: 0x000a, 0xf71: 0x000a, 0xf72: 0x000a, 0xf73: 0x000a, 0xf74: 0x000a, 0xf75: 0x000a,
+ 0xf76: 0x000a, 0xf77: 0x000a, 0xf78: 0x000a, 0xf79: 0x000a,
+ // Block 0x3e, offset 0xf80
+ 0xf80: 0x000a, 0xf81: 0x000a, 0xf82: 0x000a, 0xf83: 0x000a, 0xf84: 0x000a, 0xf85: 0x000a,
+ 0xf86: 0x000a, 0xf87: 0x000a, 0xf88: 0x000a, 0xf89: 0x000a, 0xf8a: 0x000a, 0xf8b: 0x000c,
+ 0xf8c: 0x000c, 0xf8d: 0x000c, 0xf8e: 0x000b,
+ // Block 0x3f, offset 0xfc0
+ 0xfc5: 0x000c,
+ 0xfc6: 0x000c,
+ 0xfe9: 0x000c,
+ // Block 0x40, offset 0x1000
+ 0x1020: 0x000c, 0x1021: 0x000c, 0x1022: 0x000c,
+ 0x1027: 0x000c, 0x1028: 0x000c,
+ 0x1032: 0x000c,
+ 0x1039: 0x000c, 0x103a: 0x000c, 0x103b: 0x000c,
+ // Block 0x41, offset 0x1040
+ 0x1040: 0x000a, 0x1044: 0x000a, 0x1045: 0x000a,
+ // Block 0x42, offset 0x1080
+ 0x109e: 0x000a, 0x109f: 0x000a, 0x10a0: 0x000a, 0x10a1: 0x000a, 0x10a2: 0x000a, 0x10a3: 0x000a,
+ 0x10a4: 0x000a, 0x10a5: 0x000a, 0x10a6: 0x000a, 0x10a7: 0x000a, 0x10a8: 0x000a, 0x10a9: 0x000a,
+ 0x10aa: 0x000a, 0x10ab: 0x000a, 0x10ac: 0x000a, 0x10ad: 0x000a, 0x10ae: 0x000a, 0x10af: 0x000a,
+ 0x10b0: 0x000a, 0x10b1: 0x000a, 0x10b2: 0x000a, 0x10b3: 0x000a, 0x10b4: 0x000a, 0x10b5: 0x000a,
+ 0x10b6: 0x000a, 0x10b7: 0x000a, 0x10b8: 0x000a, 0x10b9: 0x000a, 0x10ba: 0x000a, 0x10bb: 0x000a,
+ 0x10bc: 0x000a, 0x10bd: 0x000a, 0x10be: 0x000a, 0x10bf: 0x000a,
+ // Block 0x43, offset 0x10c0
+ 0x10d7: 0x000c,
+ 0x10d8: 0x000c, 0x10db: 0x000c,
+ // Block 0x44, offset 0x1100
+ 0x1116: 0x000c,
+ 0x1118: 0x000c, 0x1119: 0x000c, 0x111a: 0x000c, 0x111b: 0x000c, 0x111c: 0x000c, 0x111d: 0x000c,
+ 0x111e: 0x000c, 0x1120: 0x000c, 0x1122: 0x000c,
+ 0x1125: 0x000c, 0x1126: 0x000c, 0x1127: 0x000c, 0x1128: 0x000c, 0x1129: 0x000c,
+ 0x112a: 0x000c, 0x112b: 0x000c, 0x112c: 0x000c,
+ 0x1133: 0x000c, 0x1134: 0x000c, 0x1135: 0x000c,
+ 0x1136: 0x000c, 0x1137: 0x000c, 0x1138: 0x000c, 0x1139: 0x000c, 0x113a: 0x000c, 0x113b: 0x000c,
+ 0x113c: 0x000c, 0x113f: 0x000c,
+ // Block 0x45, offset 0x1140
+ 0x1170: 0x000c, 0x1171: 0x000c, 0x1172: 0x000c, 0x1173: 0x000c, 0x1174: 0x000c, 0x1175: 0x000c,
+ 0x1176: 0x000c, 0x1177: 0x000c, 0x1178: 0x000c, 0x1179: 0x000c, 0x117a: 0x000c, 0x117b: 0x000c,
+ 0x117c: 0x000c, 0x117d: 0x000c, 0x117e: 0x000c,
+ // Block 0x46, offset 0x1180
+ 0x1180: 0x000c, 0x1181: 0x000c, 0x1182: 0x000c, 0x1183: 0x000c,
+ 0x11b4: 0x000c,
+ 0x11b6: 0x000c, 0x11b7: 0x000c, 0x11b8: 0x000c, 0x11b9: 0x000c, 0x11ba: 0x000c,
+ 0x11bc: 0x000c,
+ // Block 0x47, offset 0x11c0
+ 0x11c2: 0x000c,
+ 0x11eb: 0x000c, 0x11ec: 0x000c, 0x11ed: 0x000c, 0x11ee: 0x000c, 0x11ef: 0x000c,
+ 0x11f0: 0x000c, 0x11f1: 0x000c, 0x11f2: 0x000c, 0x11f3: 0x000c,
+ // Block 0x48, offset 0x1200
+ 0x1200: 0x000c, 0x1201: 0x000c,
+ 0x1222: 0x000c, 0x1223: 0x000c,
+ 0x1224: 0x000c, 0x1225: 0x000c, 0x1228: 0x000c, 0x1229: 0x000c,
+ 0x122b: 0x000c, 0x122c: 0x000c, 0x122d: 0x000c,
+ // Block 0x49, offset 0x1240
+ 0x1266: 0x000c, 0x1268: 0x000c, 0x1269: 0x000c,
+ 0x126d: 0x000c, 0x126f: 0x000c,
+ 0x1270: 0x000c, 0x1271: 0x000c,
+ // Block 0x4a, offset 0x1280
+ 0x12ac: 0x000c, 0x12ad: 0x000c, 0x12ae: 0x000c, 0x12af: 0x000c,
+ 0x12b0: 0x000c, 0x12b1: 0x000c, 0x12b2: 0x000c, 0x12b3: 0x000c,
+ 0x12b6: 0x000c, 0x12b7: 0x000c,
+ // Block 0x4b, offset 0x12c0
+ 0x12d0: 0x000c, 0x12d1: 0x000c,
+ 0x12d2: 0x000c, 0x12d4: 0x000c, 0x12d5: 0x000c, 0x12d6: 0x000c, 0x12d7: 0x000c,
+ 0x12d8: 0x000c, 0x12d9: 0x000c, 0x12da: 0x000c, 0x12db: 0x000c, 0x12dc: 0x000c, 0x12dd: 0x000c,
+ 0x12de: 0x000c, 0x12df: 0x000c, 0x12e0: 0x000c, 0x12e2: 0x000c, 0x12e3: 0x000c,
+ 0x12e4: 0x000c, 0x12e5: 0x000c, 0x12e6: 0x000c, 0x12e7: 0x000c, 0x12e8: 0x000c,
+ 0x12ed: 0x000c,
+ 0x12f4: 0x000c,
+ 0x12f8: 0x000c, 0x12f9: 0x000c,
+ // Block 0x4c, offset 0x1300
+ 0x1300: 0x000c, 0x1301: 0x000c, 0x1302: 0x000c, 0x1303: 0x000c, 0x1304: 0x000c, 0x1305: 0x000c,
+ 0x1306: 0x000c, 0x1307: 0x000c, 0x1308: 0x000c, 0x1309: 0x000c, 0x130a: 0x000c, 0x130b: 0x000c,
+ 0x130c: 0x000c, 0x130d: 0x000c, 0x130e: 0x000c, 0x130f: 0x000c, 0x1310: 0x000c, 0x1311: 0x000c,
+ 0x1312: 0x000c, 0x1313: 0x000c, 0x1314: 0x000c, 0x1315: 0x000c, 0x1316: 0x000c, 0x1317: 0x000c,
+ 0x1318: 0x000c, 0x1319: 0x000c, 0x131a: 0x000c, 0x131b: 0x000c, 0x131c: 0x000c, 0x131d: 0x000c,
+ 0x131e: 0x000c, 0x131f: 0x000c, 0x1320: 0x000c, 0x1321: 0x000c, 0x1322: 0x000c, 0x1323: 0x000c,
+ 0x1324: 0x000c, 0x1325: 0x000c, 0x1326: 0x000c, 0x1327: 0x000c, 0x1328: 0x000c, 0x1329: 0x000c,
+ 0x132a: 0x000c, 0x132b: 0x000c, 0x132c: 0x000c, 0x132d: 0x000c, 0x132e: 0x000c, 0x132f: 0x000c,
+ 0x1330: 0x000c, 0x1331: 0x000c, 0x1332: 0x000c, 0x1333: 0x000c, 0x1334: 0x000c, 0x1335: 0x000c,
+ 0x133b: 0x000c,
+ 0x133c: 0x000c, 0x133d: 0x000c, 0x133e: 0x000c, 0x133f: 0x000c,
+ // Block 0x4d, offset 0x1340
+ 0x137d: 0x000a, 0x137f: 0x000a,
+ // Block 0x4e, offset 0x1380
+ 0x1380: 0x000a, 0x1381: 0x000a,
+ 0x138d: 0x000a, 0x138e: 0x000a, 0x138f: 0x000a,
+ 0x139d: 0x000a,
+ 0x139e: 0x000a, 0x139f: 0x000a,
+ 0x13ad: 0x000a, 0x13ae: 0x000a, 0x13af: 0x000a,
+ 0x13bd: 0x000a, 0x13be: 0x000a,
+ // Block 0x4f, offset 0x13c0
+ 0x13c0: 0x0009, 0x13c1: 0x0009, 0x13c2: 0x0009, 0x13c3: 0x0009, 0x13c4: 0x0009, 0x13c5: 0x0009,
+ 0x13c6: 0x0009, 0x13c7: 0x0009, 0x13c8: 0x0009, 0x13c9: 0x0009, 0x13ca: 0x0009, 0x13cb: 0x000b,
+ 0x13cc: 0x000b, 0x13cd: 0x000b, 0x13cf: 0x0001, 0x13d0: 0x000a, 0x13d1: 0x000a,
+ 0x13d2: 0x000a, 0x13d3: 0x000a, 0x13d4: 0x000a, 0x13d5: 0x000a, 0x13d6: 0x000a, 0x13d7: 0x000a,
+ 0x13d8: 0x000a, 0x13d9: 0x000a, 0x13da: 0x000a, 0x13db: 0x000a, 0x13dc: 0x000a, 0x13dd: 0x000a,
+ 0x13de: 0x000a, 0x13df: 0x000a, 0x13e0: 0x000a, 0x13e1: 0x000a, 0x13e2: 0x000a, 0x13e3: 0x000a,
+ 0x13e4: 0x000a, 0x13e5: 0x000a, 0x13e6: 0x000a, 0x13e7: 0x000a, 0x13e8: 0x0009, 0x13e9: 0x0007,
+ 0x13ea: 0x000e, 0x13eb: 0x000e, 0x13ec: 0x000e, 0x13ed: 0x000e, 0x13ee: 0x000e, 0x13ef: 0x0006,
+ 0x13f0: 0x0004, 0x13f1: 0x0004, 0x13f2: 0x0004, 0x13f3: 0x0004, 0x13f4: 0x0004, 0x13f5: 0x000a,
+ 0x13f6: 0x000a, 0x13f7: 0x000a, 0x13f8: 0x000a, 0x13f9: 0x000a, 0x13fa: 0x000a, 0x13fb: 0x000a,
+ 0x13fc: 0x000a, 0x13fd: 0x000a, 0x13fe: 0x000a, 0x13ff: 0x000a,
+ // Block 0x50, offset 0x1400
+ 0x1400: 0x000a, 0x1401: 0x000a, 0x1402: 0x000a, 0x1403: 0x000a, 0x1404: 0x0006, 0x1405: 0x009a,
+ 0x1406: 0x008a, 0x1407: 0x000a, 0x1408: 0x000a, 0x1409: 0x000a, 0x140a: 0x000a, 0x140b: 0x000a,
+ 0x140c: 0x000a, 0x140d: 0x000a, 0x140e: 0x000a, 0x140f: 0x000a, 0x1410: 0x000a, 0x1411: 0x000a,
+ 0x1412: 0x000a, 0x1413: 0x000a, 0x1414: 0x000a, 0x1415: 0x000a, 0x1416: 0x000a, 0x1417: 0x000a,
+ 0x1418: 0x000a, 0x1419: 0x000a, 0x141a: 0x000a, 0x141b: 0x000a, 0x141c: 0x000a, 0x141d: 0x000a,
+ 0x141e: 0x000a, 0x141f: 0x0009, 0x1420: 0x000b, 0x1421: 0x000b, 0x1422: 0x000b, 0x1423: 0x000b,
+ 0x1424: 0x000b, 0x1425: 0x000b, 0x1426: 0x000e, 0x1427: 0x000e, 0x1428: 0x000e, 0x1429: 0x000e,
+ 0x142a: 0x000b, 0x142b: 0x000b, 0x142c: 0x000b, 0x142d: 0x000b, 0x142e: 0x000b, 0x142f: 0x000b,
+ 0x1430: 0x0002, 0x1434: 0x0002, 0x1435: 0x0002,
+ 0x1436: 0x0002, 0x1437: 0x0002, 0x1438: 0x0002, 0x1439: 0x0002, 0x143a: 0x0003, 0x143b: 0x0003,
+ 0x143c: 0x000a, 0x143d: 0x009a, 0x143e: 0x008a,
+ // Block 0x51, offset 0x1440
+ 0x1440: 0x0002, 0x1441: 0x0002, 0x1442: 0x0002, 0x1443: 0x0002, 0x1444: 0x0002, 0x1445: 0x0002,
+ 0x1446: 0x0002, 0x1447: 0x0002, 0x1448: 0x0002, 0x1449: 0x0002, 0x144a: 0x0003, 0x144b: 0x0003,
+ 0x144c: 0x000a, 0x144d: 0x009a, 0x144e: 0x008a,
+ 0x1460: 0x0004, 0x1461: 0x0004, 0x1462: 0x0004, 0x1463: 0x0004,
+ 0x1464: 0x0004, 0x1465: 0x0004, 0x1466: 0x0004, 0x1467: 0x0004, 0x1468: 0x0004, 0x1469: 0x0004,
+ 0x146a: 0x0004, 0x146b: 0x0004, 0x146c: 0x0004, 0x146d: 0x0004, 0x146e: 0x0004, 0x146f: 0x0004,
+ 0x1470: 0x0004, 0x1471: 0x0004, 0x1472: 0x0004, 0x1473: 0x0004, 0x1474: 0x0004, 0x1475: 0x0004,
+ 0x1476: 0x0004, 0x1477: 0x0004, 0x1478: 0x0004, 0x1479: 0x0004, 0x147a: 0x0004, 0x147b: 0x0004,
+ 0x147c: 0x0004, 0x147d: 0x0004, 0x147e: 0x0004, 0x147f: 0x0004,
+ // Block 0x52, offset 0x1480
+ 0x1480: 0x0004, 0x1481: 0x0004, 0x1482: 0x0004, 0x1483: 0x0004, 0x1484: 0x0004, 0x1485: 0x0004,
+ 0x1486: 0x0004, 0x1487: 0x0004, 0x1488: 0x0004, 0x1489: 0x0004, 0x148a: 0x0004, 0x148b: 0x0004,
+ 0x148c: 0x0004, 0x148d: 0x0004, 0x148e: 0x0004, 0x148f: 0x0004, 0x1490: 0x000c, 0x1491: 0x000c,
+ 0x1492: 0x000c, 0x1493: 0x000c, 0x1494: 0x000c, 0x1495: 0x000c, 0x1496: 0x000c, 0x1497: 0x000c,
+ 0x1498: 0x000c, 0x1499: 0x000c, 0x149a: 0x000c, 0x149b: 0x000c, 0x149c: 0x000c, 0x149d: 0x000c,
+ 0x149e: 0x000c, 0x149f: 0x000c, 0x14a0: 0x000c, 0x14a1: 0x000c, 0x14a2: 0x000c, 0x14a3: 0x000c,
+ 0x14a4: 0x000c, 0x14a5: 0x000c, 0x14a6: 0x000c, 0x14a7: 0x000c, 0x14a8: 0x000c, 0x14a9: 0x000c,
+ 0x14aa: 0x000c, 0x14ab: 0x000c, 0x14ac: 0x000c, 0x14ad: 0x000c, 0x14ae: 0x000c, 0x14af: 0x000c,
+ 0x14b0: 0x000c,
+ // Block 0x53, offset 0x14c0
+ 0x14c0: 0x000a, 0x14c1: 0x000a, 0x14c3: 0x000a, 0x14c4: 0x000a, 0x14c5: 0x000a,
+ 0x14c6: 0x000a, 0x14c8: 0x000a, 0x14c9: 0x000a,
+ 0x14d4: 0x000a, 0x14d6: 0x000a, 0x14d7: 0x000a,
+ 0x14d8: 0x000a,
+ 0x14de: 0x000a, 0x14df: 0x000a, 0x14e0: 0x000a, 0x14e1: 0x000a, 0x14e2: 0x000a, 0x14e3: 0x000a,
+ 0x14e5: 0x000a, 0x14e7: 0x000a, 0x14e9: 0x000a,
+ 0x14ee: 0x0004,
+ 0x14fa: 0x000a, 0x14fb: 0x000a,
+ // Block 0x54, offset 0x1500
+ 0x1500: 0x000a, 0x1501: 0x000a, 0x1502: 0x000a, 0x1503: 0x000a, 0x1504: 0x000a,
+ 0x150a: 0x000a, 0x150b: 0x000a,
+ 0x150c: 0x000a, 0x150d: 0x000a, 0x1510: 0x000a, 0x1511: 0x000a,
+ 0x1512: 0x000a, 0x1513: 0x000a, 0x1514: 0x000a, 0x1515: 0x000a, 0x1516: 0x000a, 0x1517: 0x000a,
+ 0x1518: 0x000a, 0x1519: 0x000a, 0x151a: 0x000a, 0x151b: 0x000a, 0x151c: 0x000a, 0x151d: 0x000a,
+ 0x151e: 0x000a, 0x151f: 0x000a,
+ // Block 0x55, offset 0x1540
+ 0x1549: 0x000a, 0x154a: 0x000a, 0x154b: 0x000a,
+ 0x1550: 0x000a, 0x1551: 0x000a,
+ 0x1552: 0x000a, 0x1553: 0x000a, 0x1554: 0x000a, 0x1555: 0x000a, 0x1556: 0x000a, 0x1557: 0x000a,
+ 0x1558: 0x000a, 0x1559: 0x000a, 0x155a: 0x000a, 0x155b: 0x000a, 0x155c: 0x000a, 0x155d: 0x000a,
+ 0x155e: 0x000a, 0x155f: 0x000a, 0x1560: 0x000a, 0x1561: 0x000a, 0x1562: 0x000a, 0x1563: 0x000a,
+ 0x1564: 0x000a, 0x1565: 0x000a, 0x1566: 0x000a, 0x1567: 0x000a, 0x1568: 0x000a, 0x1569: 0x000a,
+ 0x156a: 0x000a, 0x156b: 0x000a, 0x156c: 0x000a, 0x156d: 0x000a, 0x156e: 0x000a, 0x156f: 0x000a,
+ 0x1570: 0x000a, 0x1571: 0x000a, 0x1572: 0x000a, 0x1573: 0x000a, 0x1574: 0x000a, 0x1575: 0x000a,
+ 0x1576: 0x000a, 0x1577: 0x000a, 0x1578: 0x000a, 0x1579: 0x000a, 0x157a: 0x000a, 0x157b: 0x000a,
+ 0x157c: 0x000a, 0x157d: 0x000a, 0x157e: 0x000a, 0x157f: 0x000a,
+ // Block 0x56, offset 0x1580
+ 0x1580: 0x000a, 0x1581: 0x000a, 0x1582: 0x000a, 0x1583: 0x000a, 0x1584: 0x000a, 0x1585: 0x000a,
+ 0x1586: 0x000a, 0x1587: 0x000a, 0x1588: 0x000a, 0x1589: 0x000a, 0x158a: 0x000a, 0x158b: 0x000a,
+ 0x158c: 0x000a, 0x158d: 0x000a, 0x158e: 0x000a, 0x158f: 0x000a, 0x1590: 0x000a, 0x1591: 0x000a,
+ 0x1592: 0x000a, 0x1593: 0x000a, 0x1594: 0x000a, 0x1595: 0x000a, 0x1596: 0x000a, 0x1597: 0x000a,
+ 0x1598: 0x000a, 0x1599: 0x000a, 0x159a: 0x000a, 0x159b: 0x000a, 0x159c: 0x000a, 0x159d: 0x000a,
+ 0x159e: 0x000a, 0x159f: 0x000a, 0x15a0: 0x000a, 0x15a1: 0x000a, 0x15a2: 0x000a, 0x15a3: 0x000a,
+ 0x15a4: 0x000a, 0x15a5: 0x000a, 0x15a6: 0x000a, 0x15a7: 0x000a, 0x15a8: 0x000a, 0x15a9: 0x000a,
+ 0x15aa: 0x000a, 0x15ab: 0x000a, 0x15ac: 0x000a, 0x15ad: 0x000a, 0x15ae: 0x000a, 0x15af: 0x000a,
+ 0x15b0: 0x000a, 0x15b1: 0x000a, 0x15b2: 0x000a, 0x15b3: 0x000a, 0x15b4: 0x000a, 0x15b5: 0x000a,
+ 0x15b6: 0x000a, 0x15b7: 0x000a, 0x15b8: 0x000a, 0x15b9: 0x000a, 0x15ba: 0x000a, 0x15bb: 0x000a,
+ 0x15bc: 0x000a, 0x15bd: 0x000a, 0x15be: 0x000a, 0x15bf: 0x000a,
+ // Block 0x57, offset 0x15c0
+ 0x15c0: 0x000a, 0x15c1: 0x000a, 0x15c2: 0x000a, 0x15c3: 0x000a, 0x15c4: 0x000a, 0x15c5: 0x000a,
+ 0x15c6: 0x000a, 0x15c7: 0x000a, 0x15c8: 0x000a, 0x15c9: 0x000a, 0x15ca: 0x000a, 0x15cb: 0x000a,
+ 0x15cc: 0x000a, 0x15cd: 0x000a, 0x15ce: 0x000a, 0x15cf: 0x000a, 0x15d0: 0x000a, 0x15d1: 0x000a,
+ 0x15d2: 0x0003, 0x15d3: 0x0004, 0x15d4: 0x000a, 0x15d5: 0x000a, 0x15d6: 0x000a, 0x15d7: 0x000a,
+ 0x15d8: 0x000a, 0x15d9: 0x000a, 0x15da: 0x000a, 0x15db: 0x000a, 0x15dc: 0x000a, 0x15dd: 0x000a,
+ 0x15de: 0x000a, 0x15df: 0x000a, 0x15e0: 0x000a, 0x15e1: 0x000a, 0x15e2: 0x000a, 0x15e3: 0x000a,
+ 0x15e4: 0x000a, 0x15e5: 0x000a, 0x15e6: 0x000a, 0x15e7: 0x000a, 0x15e8: 0x000a, 0x15e9: 0x000a,
+ 0x15ea: 0x000a, 0x15eb: 0x000a, 0x15ec: 0x000a, 0x15ed: 0x000a, 0x15ee: 0x000a, 0x15ef: 0x000a,
+ 0x15f0: 0x000a, 0x15f1: 0x000a, 0x15f2: 0x000a, 0x15f3: 0x000a, 0x15f4: 0x000a, 0x15f5: 0x000a,
+ 0x15f6: 0x000a, 0x15f7: 0x000a, 0x15f8: 0x000a, 0x15f9: 0x000a, 0x15fa: 0x000a, 0x15fb: 0x000a,
+ 0x15fc: 0x000a, 0x15fd: 0x000a, 0x15fe: 0x000a, 0x15ff: 0x000a,
+ // Block 0x58, offset 0x1600
+ 0x1600: 0x000a, 0x1601: 0x000a, 0x1602: 0x000a, 0x1603: 0x000a, 0x1604: 0x000a, 0x1605: 0x000a,
+ 0x1606: 0x000a, 0x1607: 0x000a, 0x1608: 0x003a, 0x1609: 0x002a, 0x160a: 0x003a, 0x160b: 0x002a,
+ 0x160c: 0x000a, 0x160d: 0x000a, 0x160e: 0x000a, 0x160f: 0x000a, 0x1610: 0x000a, 0x1611: 0x000a,
+ 0x1612: 0x000a, 0x1613: 0x000a, 0x1614: 0x000a, 0x1615: 0x000a, 0x1616: 0x000a, 0x1617: 0x000a,
+ 0x1618: 0x000a, 0x1619: 0x000a, 0x161a: 0x000a, 0x161b: 0x000a, 0x161c: 0x000a, 0x161d: 0x000a,
+ 0x161e: 0x000a, 0x161f: 0x000a, 0x1620: 0x000a, 0x1621: 0x000a, 0x1622: 0x000a, 0x1623: 0x000a,
+ 0x1624: 0x000a, 0x1625: 0x000a, 0x1626: 0x000a, 0x1627: 0x000a, 0x1628: 0x000a, 0x1629: 0x009a,
+ 0x162a: 0x008a, 0x162b: 0x000a, 0x162c: 0x000a, 0x162d: 0x000a, 0x162e: 0x000a, 0x162f: 0x000a,
+ 0x1630: 0x000a, 0x1631: 0x000a, 0x1632: 0x000a, 0x1633: 0x000a, 0x1634: 0x000a, 0x1635: 0x000a,
+ // Block 0x59, offset 0x1640
+ 0x167b: 0x000a,
+ 0x167c: 0x000a, 0x167d: 0x000a, 0x167e: 0x000a, 0x167f: 0x000a,
+ // Block 0x5a, offset 0x1680
+ 0x1680: 0x000a, 0x1681: 0x000a, 0x1682: 0x000a, 0x1683: 0x000a, 0x1684: 0x000a, 0x1685: 0x000a,
+ 0x1686: 0x000a, 0x1687: 0x000a, 0x1688: 0x000a, 0x1689: 0x000a, 0x168a: 0x000a, 0x168b: 0x000a,
+ 0x168c: 0x000a, 0x168d: 0x000a, 0x168e: 0x000a, 0x168f: 0x000a, 0x1690: 0x000a, 0x1691: 0x000a,
+ 0x1692: 0x000a, 0x1693: 0x000a, 0x1694: 0x000a, 0x1696: 0x000a, 0x1697: 0x000a,
+ 0x1698: 0x000a, 0x1699: 0x000a, 0x169a: 0x000a, 0x169b: 0x000a, 0x169c: 0x000a, 0x169d: 0x000a,
+ 0x169e: 0x000a, 0x169f: 0x000a, 0x16a0: 0x000a, 0x16a1: 0x000a, 0x16a2: 0x000a, 0x16a3: 0x000a,
+ 0x16a4: 0x000a, 0x16a5: 0x000a, 0x16a6: 0x000a, 0x16a7: 0x000a, 0x16a8: 0x000a, 0x16a9: 0x000a,
+ 0x16aa: 0x000a, 0x16ab: 0x000a, 0x16ac: 0x000a, 0x16ad: 0x000a, 0x16ae: 0x000a, 0x16af: 0x000a,
+ 0x16b0: 0x000a, 0x16b1: 0x000a, 0x16b2: 0x000a, 0x16b3: 0x000a, 0x16b4: 0x000a, 0x16b5: 0x000a,
+ 0x16b6: 0x000a, 0x16b7: 0x000a, 0x16b8: 0x000a, 0x16b9: 0x000a, 0x16ba: 0x000a, 0x16bb: 0x000a,
+ 0x16bc: 0x000a, 0x16bd: 0x000a, 0x16be: 0x000a, 0x16bf: 0x000a,
+ // Block 0x5b, offset 0x16c0
+ 0x16c0: 0x000a, 0x16c1: 0x000a, 0x16c2: 0x000a, 0x16c3: 0x000a, 0x16c4: 0x000a, 0x16c5: 0x000a,
+ 0x16c6: 0x000a, 0x16c7: 0x000a, 0x16c8: 0x000a, 0x16c9: 0x000a, 0x16ca: 0x000a, 0x16cb: 0x000a,
+ 0x16cc: 0x000a, 0x16cd: 0x000a, 0x16ce: 0x000a, 0x16cf: 0x000a, 0x16d0: 0x000a, 0x16d1: 0x000a,
+ 0x16d2: 0x000a, 0x16d3: 0x000a, 0x16d4: 0x000a, 0x16d5: 0x000a, 0x16d6: 0x000a, 0x16d7: 0x000a,
+ 0x16d8: 0x000a, 0x16d9: 0x000a, 0x16da: 0x000a, 0x16db: 0x000a, 0x16dc: 0x000a, 0x16dd: 0x000a,
+ 0x16de: 0x000a, 0x16df: 0x000a, 0x16e0: 0x000a, 0x16e1: 0x000a, 0x16e2: 0x000a, 0x16e3: 0x000a,
+ 0x16e4: 0x000a, 0x16e5: 0x000a, 0x16e6: 0x000a, 0x16e7: 0x000a, 0x16e8: 0x000a, 0x16e9: 0x000a,
+ 0x16ea: 0x000a, 0x16eb: 0x000a, 0x16ec: 0x000a, 0x16ed: 0x000a, 0x16ee: 0x000a, 0x16ef: 0x000a,
+ 0x16f0: 0x000a, 0x16f1: 0x000a, 0x16f2: 0x000a, 0x16f3: 0x000a, 0x16f4: 0x000a, 0x16f5: 0x000a,
+ 0x16f6: 0x000a, 0x16f7: 0x000a, 0x16f8: 0x000a, 0x16f9: 0x000a, 0x16fa: 0x000a, 0x16fb: 0x000a,
+ 0x16fc: 0x000a, 0x16fd: 0x000a, 0x16fe: 0x000a,
+ // Block 0x5c, offset 0x1700
+ 0x1700: 0x000a, 0x1701: 0x000a, 0x1702: 0x000a, 0x1703: 0x000a, 0x1704: 0x000a, 0x1705: 0x000a,
+ 0x1706: 0x000a, 0x1707: 0x000a, 0x1708: 0x000a, 0x1709: 0x000a, 0x170a: 0x000a, 0x170b: 0x000a,
+ 0x170c: 0x000a, 0x170d: 0x000a, 0x170e: 0x000a, 0x170f: 0x000a, 0x1710: 0x000a, 0x1711: 0x000a,
+ 0x1712: 0x000a, 0x1713: 0x000a, 0x1714: 0x000a, 0x1715: 0x000a, 0x1716: 0x000a, 0x1717: 0x000a,
+ 0x1718: 0x000a, 0x1719: 0x000a, 0x171a: 0x000a, 0x171b: 0x000a, 0x171c: 0x000a, 0x171d: 0x000a,
+ 0x171e: 0x000a, 0x171f: 0x000a, 0x1720: 0x000a, 0x1721: 0x000a, 0x1722: 0x000a, 0x1723: 0x000a,
+ 0x1724: 0x000a, 0x1725: 0x000a, 0x1726: 0x000a,
+ // Block 0x5d, offset 0x1740
+ 0x1740: 0x000a, 0x1741: 0x000a, 0x1742: 0x000a, 0x1743: 0x000a, 0x1744: 0x000a, 0x1745: 0x000a,
+ 0x1746: 0x000a, 0x1747: 0x000a, 0x1748: 0x000a, 0x1749: 0x000a, 0x174a: 0x000a,
+ 0x1760: 0x000a, 0x1761: 0x000a, 0x1762: 0x000a, 0x1763: 0x000a,
+ 0x1764: 0x000a, 0x1765: 0x000a, 0x1766: 0x000a, 0x1767: 0x000a, 0x1768: 0x000a, 0x1769: 0x000a,
+ 0x176a: 0x000a, 0x176b: 0x000a, 0x176c: 0x000a, 0x176d: 0x000a, 0x176e: 0x000a, 0x176f: 0x000a,
+ 0x1770: 0x000a, 0x1771: 0x000a, 0x1772: 0x000a, 0x1773: 0x000a, 0x1774: 0x000a, 0x1775: 0x000a,
+ 0x1776: 0x000a, 0x1777: 0x000a, 0x1778: 0x000a, 0x1779: 0x000a, 0x177a: 0x000a, 0x177b: 0x000a,
+ 0x177c: 0x000a, 0x177d: 0x000a, 0x177e: 0x000a, 0x177f: 0x000a,
+ // Block 0x5e, offset 0x1780
+ 0x1780: 0x000a, 0x1781: 0x000a, 0x1782: 0x000a, 0x1783: 0x000a, 0x1784: 0x000a, 0x1785: 0x000a,
+ 0x1786: 0x000a, 0x1787: 0x000a, 0x1788: 0x0002, 0x1789: 0x0002, 0x178a: 0x0002, 0x178b: 0x0002,
+ 0x178c: 0x0002, 0x178d: 0x0002, 0x178e: 0x0002, 0x178f: 0x0002, 0x1790: 0x0002, 0x1791: 0x0002,
+ 0x1792: 0x0002, 0x1793: 0x0002, 0x1794: 0x0002, 0x1795: 0x0002, 0x1796: 0x0002, 0x1797: 0x0002,
+ 0x1798: 0x0002, 0x1799: 0x0002, 0x179a: 0x0002, 0x179b: 0x0002,
+ // Block 0x5f, offset 0x17c0
+ 0x17ea: 0x000a, 0x17eb: 0x000a, 0x17ec: 0x000a, 0x17ed: 0x000a, 0x17ee: 0x000a, 0x17ef: 0x000a,
+ 0x17f0: 0x000a, 0x17f1: 0x000a, 0x17f2: 0x000a, 0x17f3: 0x000a, 0x17f4: 0x000a, 0x17f5: 0x000a,
+ 0x17f6: 0x000a, 0x17f7: 0x000a, 0x17f8: 0x000a, 0x17f9: 0x000a, 0x17fa: 0x000a, 0x17fb: 0x000a,
+ 0x17fc: 0x000a, 0x17fd: 0x000a, 0x17fe: 0x000a, 0x17ff: 0x000a,
+ // Block 0x60, offset 0x1800
+ 0x1800: 0x000a, 0x1801: 0x000a, 0x1802: 0x000a, 0x1803: 0x000a, 0x1804: 0x000a, 0x1805: 0x000a,
+ 0x1806: 0x000a, 0x1807: 0x000a, 0x1808: 0x000a, 0x1809: 0x000a, 0x180a: 0x000a, 0x180b: 0x000a,
+ 0x180c: 0x000a, 0x180d: 0x000a, 0x180e: 0x000a, 0x180f: 0x000a, 0x1810: 0x000a, 0x1811: 0x000a,
+ 0x1812: 0x000a, 0x1813: 0x000a, 0x1814: 0x000a, 0x1815: 0x000a, 0x1816: 0x000a, 0x1817: 0x000a,
+ 0x1818: 0x000a, 0x1819: 0x000a, 0x181a: 0x000a, 0x181b: 0x000a, 0x181c: 0x000a, 0x181d: 0x000a,
+ 0x181e: 0x000a, 0x181f: 0x000a, 0x1820: 0x000a, 0x1821: 0x000a, 0x1822: 0x000a, 0x1823: 0x000a,
+ 0x1824: 0x000a, 0x1825: 0x000a, 0x1826: 0x000a, 0x1827: 0x000a, 0x1828: 0x000a, 0x1829: 0x000a,
+ 0x182a: 0x000a, 0x182b: 0x000a, 0x182d: 0x000a, 0x182e: 0x000a, 0x182f: 0x000a,
+ 0x1830: 0x000a, 0x1831: 0x000a, 0x1832: 0x000a, 0x1833: 0x000a, 0x1834: 0x000a, 0x1835: 0x000a,
+ 0x1836: 0x000a, 0x1837: 0x000a, 0x1838: 0x000a, 0x1839: 0x000a, 0x183a: 0x000a, 0x183b: 0x000a,
+ 0x183c: 0x000a, 0x183d: 0x000a, 0x183e: 0x000a, 0x183f: 0x000a,
+ // Block 0x61, offset 0x1840
+ 0x1840: 0x000a, 0x1841: 0x000a, 0x1842: 0x000a, 0x1843: 0x000a, 0x1844: 0x000a, 0x1845: 0x000a,
+ 0x1846: 0x000a, 0x1847: 0x000a, 0x1848: 0x000a, 0x1849: 0x000a, 0x184a: 0x000a, 0x184b: 0x000a,
+ 0x184c: 0x000a, 0x184d: 0x000a, 0x184e: 0x000a, 0x184f: 0x000a, 0x1850: 0x000a, 0x1851: 0x000a,
+ 0x1852: 0x000a, 0x1853: 0x000a, 0x1854: 0x000a, 0x1855: 0x000a, 0x1856: 0x000a, 0x1857: 0x000a,
+ 0x1858: 0x000a, 0x1859: 0x000a, 0x185a: 0x000a, 0x185b: 0x000a, 0x185c: 0x000a, 0x185d: 0x000a,
+ 0x185e: 0x000a, 0x185f: 0x000a, 0x1860: 0x000a, 0x1861: 0x000a, 0x1862: 0x000a, 0x1863: 0x000a,
+ 0x1864: 0x000a, 0x1865: 0x000a, 0x1866: 0x000a, 0x1867: 0x000a, 0x1868: 0x003a, 0x1869: 0x002a,
+ 0x186a: 0x003a, 0x186b: 0x002a, 0x186c: 0x003a, 0x186d: 0x002a, 0x186e: 0x003a, 0x186f: 0x002a,
+ 0x1870: 0x003a, 0x1871: 0x002a, 0x1872: 0x003a, 0x1873: 0x002a, 0x1874: 0x003a, 0x1875: 0x002a,
+ 0x1876: 0x000a, 0x1877: 0x000a, 0x1878: 0x000a, 0x1879: 0x000a, 0x187a: 0x000a, 0x187b: 0x000a,
+ 0x187c: 0x000a, 0x187d: 0x000a, 0x187e: 0x000a, 0x187f: 0x000a,
+ // Block 0x62, offset 0x1880
+ 0x1880: 0x000a, 0x1881: 0x000a, 0x1882: 0x000a, 0x1883: 0x000a, 0x1884: 0x000a, 0x1885: 0x009a,
+ 0x1886: 0x008a, 0x1887: 0x000a, 0x1888: 0x000a, 0x1889: 0x000a, 0x188a: 0x000a, 0x188b: 0x000a,
+ 0x188c: 0x000a, 0x188d: 0x000a, 0x188e: 0x000a, 0x188f: 0x000a, 0x1890: 0x000a, 0x1891: 0x000a,
+ 0x1892: 0x000a, 0x1893: 0x000a, 0x1894: 0x000a, 0x1895: 0x000a, 0x1896: 0x000a, 0x1897: 0x000a,
+ 0x1898: 0x000a, 0x1899: 0x000a, 0x189a: 0x000a, 0x189b: 0x000a, 0x189c: 0x000a, 0x189d: 0x000a,
+ 0x189e: 0x000a, 0x189f: 0x000a, 0x18a0: 0x000a, 0x18a1: 0x000a, 0x18a2: 0x000a, 0x18a3: 0x000a,
+ 0x18a4: 0x000a, 0x18a5: 0x000a, 0x18a6: 0x003a, 0x18a7: 0x002a, 0x18a8: 0x003a, 0x18a9: 0x002a,
+ 0x18aa: 0x003a, 0x18ab: 0x002a, 0x18ac: 0x003a, 0x18ad: 0x002a, 0x18ae: 0x003a, 0x18af: 0x002a,
+ 0x18b0: 0x000a, 0x18b1: 0x000a, 0x18b2: 0x000a, 0x18b3: 0x000a, 0x18b4: 0x000a, 0x18b5: 0x000a,
+ 0x18b6: 0x000a, 0x18b7: 0x000a, 0x18b8: 0x000a, 0x18b9: 0x000a, 0x18ba: 0x000a, 0x18bb: 0x000a,
+ 0x18bc: 0x000a, 0x18bd: 0x000a, 0x18be: 0x000a, 0x18bf: 0x000a,
+ // Block 0x63, offset 0x18c0
+ 0x18c0: 0x000a, 0x18c1: 0x000a, 0x18c2: 0x000a, 0x18c3: 0x007a, 0x18c4: 0x006a, 0x18c5: 0x009a,
+ 0x18c6: 0x008a, 0x18c7: 0x00ba, 0x18c8: 0x00aa, 0x18c9: 0x009a, 0x18ca: 0x008a, 0x18cb: 0x007a,
+ 0x18cc: 0x006a, 0x18cd: 0x00da, 0x18ce: 0x002a, 0x18cf: 0x003a, 0x18d0: 0x00ca, 0x18d1: 0x009a,
+ 0x18d2: 0x008a, 0x18d3: 0x007a, 0x18d4: 0x006a, 0x18d5: 0x009a, 0x18d6: 0x008a, 0x18d7: 0x00ba,
+ 0x18d8: 0x00aa, 0x18d9: 0x000a, 0x18da: 0x000a, 0x18db: 0x000a, 0x18dc: 0x000a, 0x18dd: 0x000a,
+ 0x18de: 0x000a, 0x18df: 0x000a, 0x18e0: 0x000a, 0x18e1: 0x000a, 0x18e2: 0x000a, 0x18e3: 0x000a,
+ 0x18e4: 0x000a, 0x18e5: 0x000a, 0x18e6: 0x000a, 0x18e7: 0x000a, 0x18e8: 0x000a, 0x18e9: 0x000a,
+ 0x18ea: 0x000a, 0x18eb: 0x000a, 0x18ec: 0x000a, 0x18ed: 0x000a, 0x18ee: 0x000a, 0x18ef: 0x000a,
+ 0x18f0: 0x000a, 0x18f1: 0x000a, 0x18f2: 0x000a, 0x18f3: 0x000a, 0x18f4: 0x000a, 0x18f5: 0x000a,
+ 0x18f6: 0x000a, 0x18f7: 0x000a, 0x18f8: 0x000a, 0x18f9: 0x000a, 0x18fa: 0x000a, 0x18fb: 0x000a,
+ 0x18fc: 0x000a, 0x18fd: 0x000a, 0x18fe: 0x000a, 0x18ff: 0x000a,
+ // Block 0x64, offset 0x1900
+ 0x1900: 0x000a, 0x1901: 0x000a, 0x1902: 0x000a, 0x1903: 0x000a, 0x1904: 0x000a, 0x1905: 0x000a,
+ 0x1906: 0x000a, 0x1907: 0x000a, 0x1908: 0x000a, 0x1909: 0x000a, 0x190a: 0x000a, 0x190b: 0x000a,
+ 0x190c: 0x000a, 0x190d: 0x000a, 0x190e: 0x000a, 0x190f: 0x000a, 0x1910: 0x000a, 0x1911: 0x000a,
+ 0x1912: 0x000a, 0x1913: 0x000a, 0x1914: 0x000a, 0x1915: 0x000a, 0x1916: 0x000a, 0x1917: 0x000a,
+ 0x1918: 0x003a, 0x1919: 0x002a, 0x191a: 0x003a, 0x191b: 0x002a, 0x191c: 0x000a, 0x191d: 0x000a,
+ 0x191e: 0x000a, 0x191f: 0x000a, 0x1920: 0x000a, 0x1921: 0x000a, 0x1922: 0x000a, 0x1923: 0x000a,
+ 0x1924: 0x000a, 0x1925: 0x000a, 0x1926: 0x000a, 0x1927: 0x000a, 0x1928: 0x000a, 0x1929: 0x000a,
+ 0x192a: 0x000a, 0x192b: 0x000a, 0x192c: 0x000a, 0x192d: 0x000a, 0x192e: 0x000a, 0x192f: 0x000a,
+ 0x1930: 0x000a, 0x1931: 0x000a, 0x1932: 0x000a, 0x1933: 0x000a, 0x1934: 0x000a, 0x1935: 0x000a,
+ 0x1936: 0x000a, 0x1937: 0x000a, 0x1938: 0x000a, 0x1939: 0x000a, 0x193a: 0x000a, 0x193b: 0x000a,
+ 0x193c: 0x003a, 0x193d: 0x002a, 0x193e: 0x000a, 0x193f: 0x000a,
+ // Block 0x65, offset 0x1940
+ 0x1940: 0x000a, 0x1941: 0x000a, 0x1942: 0x000a, 0x1943: 0x000a, 0x1944: 0x000a, 0x1945: 0x000a,
+ 0x1946: 0x000a, 0x1947: 0x000a, 0x1948: 0x000a, 0x1949: 0x000a, 0x194a: 0x000a, 0x194b: 0x000a,
+ 0x194c: 0x000a, 0x194d: 0x000a, 0x194e: 0x000a, 0x194f: 0x000a, 0x1950: 0x000a, 0x1951: 0x000a,
+ 0x1952: 0x000a, 0x1953: 0x000a, 0x1954: 0x000a, 0x1955: 0x000a, 0x1956: 0x000a, 0x1957: 0x000a,
+ 0x1958: 0x000a, 0x1959: 0x000a, 0x195a: 0x000a, 0x195b: 0x000a, 0x195c: 0x000a, 0x195d: 0x000a,
+ 0x195e: 0x000a, 0x195f: 0x000a, 0x1960: 0x000a, 0x1961: 0x000a, 0x1962: 0x000a, 0x1963: 0x000a,
+ 0x1964: 0x000a, 0x1965: 0x000a, 0x1966: 0x000a, 0x1967: 0x000a, 0x1968: 0x000a, 0x1969: 0x000a,
+ 0x196a: 0x000a, 0x196b: 0x000a, 0x196c: 0x000a, 0x196d: 0x000a, 0x196e: 0x000a, 0x196f: 0x000a,
+ 0x1970: 0x000a, 0x1971: 0x000a, 0x1972: 0x000a, 0x1973: 0x000a,
+ 0x1976: 0x000a, 0x1977: 0x000a, 0x1978: 0x000a, 0x1979: 0x000a, 0x197a: 0x000a, 0x197b: 0x000a,
+ 0x197c: 0x000a, 0x197d: 0x000a, 0x197e: 0x000a, 0x197f: 0x000a,
+ // Block 0x66, offset 0x1980
+ 0x1980: 0x000a, 0x1981: 0x000a, 0x1982: 0x000a, 0x1983: 0x000a, 0x1984: 0x000a, 0x1985: 0x000a,
+ 0x1986: 0x000a, 0x1987: 0x000a, 0x1988: 0x000a, 0x1989: 0x000a, 0x198a: 0x000a, 0x198b: 0x000a,
+ 0x198c: 0x000a, 0x198d: 0x000a, 0x198e: 0x000a, 0x198f: 0x000a, 0x1990: 0x000a, 0x1991: 0x000a,
+ 0x1992: 0x000a, 0x1993: 0x000a, 0x1994: 0x000a, 0x1995: 0x000a,
+ 0x1998: 0x000a, 0x1999: 0x000a, 0x199a: 0x000a, 0x199b: 0x000a, 0x199c: 0x000a, 0x199d: 0x000a,
+ 0x199e: 0x000a, 0x199f: 0x000a, 0x19a0: 0x000a, 0x19a1: 0x000a, 0x19a2: 0x000a, 0x19a3: 0x000a,
+ 0x19a4: 0x000a, 0x19a5: 0x000a, 0x19a6: 0x000a, 0x19a7: 0x000a, 0x19a8: 0x000a, 0x19a9: 0x000a,
+ 0x19aa: 0x000a, 0x19ab: 0x000a, 0x19ac: 0x000a, 0x19ad: 0x000a, 0x19ae: 0x000a, 0x19af: 0x000a,
+ 0x19b0: 0x000a, 0x19b1: 0x000a, 0x19b2: 0x000a, 0x19b3: 0x000a, 0x19b4: 0x000a, 0x19b5: 0x000a,
+ 0x19b6: 0x000a, 0x19b7: 0x000a, 0x19b8: 0x000a, 0x19b9: 0x000a,
+ 0x19bd: 0x000a, 0x19be: 0x000a, 0x19bf: 0x000a,
+ // Block 0x67, offset 0x19c0
+ 0x19c0: 0x000a, 0x19c1: 0x000a, 0x19c2: 0x000a, 0x19c3: 0x000a, 0x19c4: 0x000a, 0x19c5: 0x000a,
+ 0x19c6: 0x000a, 0x19c7: 0x000a, 0x19c8: 0x000a, 0x19ca: 0x000a, 0x19cb: 0x000a,
+ 0x19cc: 0x000a, 0x19cd: 0x000a, 0x19ce: 0x000a, 0x19cf: 0x000a, 0x19d0: 0x000a, 0x19d1: 0x000a,
+ 0x19ec: 0x000a, 0x19ed: 0x000a, 0x19ee: 0x000a, 0x19ef: 0x000a,
+ // Block 0x68, offset 0x1a00
+ 0x1a25: 0x000a, 0x1a26: 0x000a, 0x1a27: 0x000a, 0x1a28: 0x000a, 0x1a29: 0x000a,
+ 0x1a2a: 0x000a, 0x1a2f: 0x000c,
+ 0x1a30: 0x000c, 0x1a31: 0x000c,
+ 0x1a39: 0x000a, 0x1a3a: 0x000a, 0x1a3b: 0x000a,
+ 0x1a3c: 0x000a, 0x1a3d: 0x000a, 0x1a3e: 0x000a, 0x1a3f: 0x000a,
+ // Block 0x69, offset 0x1a40
+ 0x1a7f: 0x000c,
+ // Block 0x6a, offset 0x1a80
+ 0x1aa0: 0x000c, 0x1aa1: 0x000c, 0x1aa2: 0x000c, 0x1aa3: 0x000c,
+ 0x1aa4: 0x000c, 0x1aa5: 0x000c, 0x1aa6: 0x000c, 0x1aa7: 0x000c, 0x1aa8: 0x000c, 0x1aa9: 0x000c,
+ 0x1aaa: 0x000c, 0x1aab: 0x000c, 0x1aac: 0x000c, 0x1aad: 0x000c, 0x1aae: 0x000c, 0x1aaf: 0x000c,
+ 0x1ab0: 0x000c, 0x1ab1: 0x000c, 0x1ab2: 0x000c, 0x1ab3: 0x000c, 0x1ab4: 0x000c, 0x1ab5: 0x000c,
+ 0x1ab6: 0x000c, 0x1ab7: 0x000c, 0x1ab8: 0x000c, 0x1ab9: 0x000c, 0x1aba: 0x000c, 0x1abb: 0x000c,
+ 0x1abc: 0x000c, 0x1abd: 0x000c, 0x1abe: 0x000c, 0x1abf: 0x000c,
+ // Block 0x6b, offset 0x1ac0
+ 0x1ac0: 0x000a, 0x1ac1: 0x000a, 0x1ac2: 0x000a, 0x1ac3: 0x000a, 0x1ac4: 0x000a, 0x1ac5: 0x000a,
+ 0x1ac6: 0x000a, 0x1ac7: 0x000a, 0x1ac8: 0x000a, 0x1ac9: 0x000a, 0x1aca: 0x000a, 0x1acb: 0x000a,
+ 0x1acc: 0x000a, 0x1acd: 0x000a, 0x1ace: 0x000a, 0x1acf: 0x000a, 0x1ad0: 0x000a, 0x1ad1: 0x000a,
+ 0x1ad2: 0x000a, 0x1ad3: 0x000a, 0x1ad4: 0x000a, 0x1ad5: 0x000a, 0x1ad6: 0x000a, 0x1ad7: 0x000a,
+ 0x1ad8: 0x000a, 0x1ad9: 0x000a, 0x1ada: 0x000a, 0x1adb: 0x000a, 0x1adc: 0x000a, 0x1add: 0x000a,
+ 0x1ade: 0x000a, 0x1adf: 0x000a, 0x1ae0: 0x000a, 0x1ae1: 0x000a, 0x1ae2: 0x003a, 0x1ae3: 0x002a,
+ 0x1ae4: 0x003a, 0x1ae5: 0x002a, 0x1ae6: 0x003a, 0x1ae7: 0x002a, 0x1ae8: 0x003a, 0x1ae9: 0x002a,
+ 0x1aea: 0x000a, 0x1aeb: 0x000a, 0x1aec: 0x000a, 0x1aed: 0x000a, 0x1aee: 0x000a, 0x1aef: 0x000a,
+ 0x1af0: 0x000a, 0x1af1: 0x000a, 0x1af2: 0x000a, 0x1af3: 0x000a, 0x1af4: 0x000a, 0x1af5: 0x000a,
+ 0x1af6: 0x000a, 0x1af7: 0x000a, 0x1af8: 0x000a, 0x1af9: 0x000a, 0x1afa: 0x000a, 0x1afb: 0x000a,
+ 0x1afc: 0x000a, 0x1afd: 0x000a, 0x1afe: 0x000a, 0x1aff: 0x000a,
+ // Block 0x6c, offset 0x1b00
+ 0x1b00: 0x000a, 0x1b01: 0x000a, 0x1b02: 0x000a, 0x1b03: 0x000a, 0x1b04: 0x000a,
+ // Block 0x6d, offset 0x1b40
+ 0x1b40: 0x000a, 0x1b41: 0x000a, 0x1b42: 0x000a, 0x1b43: 0x000a, 0x1b44: 0x000a, 0x1b45: 0x000a,
+ 0x1b46: 0x000a, 0x1b47: 0x000a, 0x1b48: 0x000a, 0x1b49: 0x000a, 0x1b4a: 0x000a, 0x1b4b: 0x000a,
+ 0x1b4c: 0x000a, 0x1b4d: 0x000a, 0x1b4e: 0x000a, 0x1b4f: 0x000a, 0x1b50: 0x000a, 0x1b51: 0x000a,
+ 0x1b52: 0x000a, 0x1b53: 0x000a, 0x1b54: 0x000a, 0x1b55: 0x000a, 0x1b56: 0x000a, 0x1b57: 0x000a,
+ 0x1b58: 0x000a, 0x1b59: 0x000a, 0x1b5b: 0x000a, 0x1b5c: 0x000a, 0x1b5d: 0x000a,
+ 0x1b5e: 0x000a, 0x1b5f: 0x000a, 0x1b60: 0x000a, 0x1b61: 0x000a, 0x1b62: 0x000a, 0x1b63: 0x000a,
+ 0x1b64: 0x000a, 0x1b65: 0x000a, 0x1b66: 0x000a, 0x1b67: 0x000a, 0x1b68: 0x000a, 0x1b69: 0x000a,
+ 0x1b6a: 0x000a, 0x1b6b: 0x000a, 0x1b6c: 0x000a, 0x1b6d: 0x000a, 0x1b6e: 0x000a, 0x1b6f: 0x000a,
+ 0x1b70: 0x000a, 0x1b71: 0x000a, 0x1b72: 0x000a, 0x1b73: 0x000a, 0x1b74: 0x000a, 0x1b75: 0x000a,
+ 0x1b76: 0x000a, 0x1b77: 0x000a, 0x1b78: 0x000a, 0x1b79: 0x000a, 0x1b7a: 0x000a, 0x1b7b: 0x000a,
+ 0x1b7c: 0x000a, 0x1b7d: 0x000a, 0x1b7e: 0x000a, 0x1b7f: 0x000a,
+ // Block 0x6e, offset 0x1b80
+ 0x1b80: 0x000a, 0x1b81: 0x000a, 0x1b82: 0x000a, 0x1b83: 0x000a, 0x1b84: 0x000a, 0x1b85: 0x000a,
+ 0x1b86: 0x000a, 0x1b87: 0x000a, 0x1b88: 0x000a, 0x1b89: 0x000a, 0x1b8a: 0x000a, 0x1b8b: 0x000a,
+ 0x1b8c: 0x000a, 0x1b8d: 0x000a, 0x1b8e: 0x000a, 0x1b8f: 0x000a, 0x1b90: 0x000a, 0x1b91: 0x000a,
+ 0x1b92: 0x000a, 0x1b93: 0x000a, 0x1b94: 0x000a, 0x1b95: 0x000a, 0x1b96: 0x000a, 0x1b97: 0x000a,
+ 0x1b98: 0x000a, 0x1b99: 0x000a, 0x1b9a: 0x000a, 0x1b9b: 0x000a, 0x1b9c: 0x000a, 0x1b9d: 0x000a,
+ 0x1b9e: 0x000a, 0x1b9f: 0x000a, 0x1ba0: 0x000a, 0x1ba1: 0x000a, 0x1ba2: 0x000a, 0x1ba3: 0x000a,
+ 0x1ba4: 0x000a, 0x1ba5: 0x000a, 0x1ba6: 0x000a, 0x1ba7: 0x000a, 0x1ba8: 0x000a, 0x1ba9: 0x000a,
+ 0x1baa: 0x000a, 0x1bab: 0x000a, 0x1bac: 0x000a, 0x1bad: 0x000a, 0x1bae: 0x000a, 0x1baf: 0x000a,
+ 0x1bb0: 0x000a, 0x1bb1: 0x000a, 0x1bb2: 0x000a, 0x1bb3: 0x000a,
+ // Block 0x6f, offset 0x1bc0
+ 0x1bc0: 0x000a, 0x1bc1: 0x000a, 0x1bc2: 0x000a, 0x1bc3: 0x000a, 0x1bc4: 0x000a, 0x1bc5: 0x000a,
+ 0x1bc6: 0x000a, 0x1bc7: 0x000a, 0x1bc8: 0x000a, 0x1bc9: 0x000a, 0x1bca: 0x000a, 0x1bcb: 0x000a,
+ 0x1bcc: 0x000a, 0x1bcd: 0x000a, 0x1bce: 0x000a, 0x1bcf: 0x000a, 0x1bd0: 0x000a, 0x1bd1: 0x000a,
+ 0x1bd2: 0x000a, 0x1bd3: 0x000a, 0x1bd4: 0x000a, 0x1bd5: 0x000a,
+ 0x1bf0: 0x000a, 0x1bf1: 0x000a, 0x1bf2: 0x000a, 0x1bf3: 0x000a, 0x1bf4: 0x000a, 0x1bf5: 0x000a,
+ 0x1bf6: 0x000a, 0x1bf7: 0x000a, 0x1bf8: 0x000a, 0x1bf9: 0x000a, 0x1bfa: 0x000a, 0x1bfb: 0x000a,
+ // Block 0x70, offset 0x1c00
+ 0x1c00: 0x0009, 0x1c01: 0x000a, 0x1c02: 0x000a, 0x1c03: 0x000a, 0x1c04: 0x000a,
+ 0x1c08: 0x003a, 0x1c09: 0x002a, 0x1c0a: 0x003a, 0x1c0b: 0x002a,
+ 0x1c0c: 0x003a, 0x1c0d: 0x002a, 0x1c0e: 0x003a, 0x1c0f: 0x002a, 0x1c10: 0x003a, 0x1c11: 0x002a,
+ 0x1c12: 0x000a, 0x1c13: 0x000a, 0x1c14: 0x003a, 0x1c15: 0x002a, 0x1c16: 0x003a, 0x1c17: 0x002a,
+ 0x1c18: 0x003a, 0x1c19: 0x002a, 0x1c1a: 0x003a, 0x1c1b: 0x002a, 0x1c1c: 0x000a, 0x1c1d: 0x000a,
+ 0x1c1e: 0x000a, 0x1c1f: 0x000a, 0x1c20: 0x000a,
+ 0x1c2a: 0x000c, 0x1c2b: 0x000c, 0x1c2c: 0x000c, 0x1c2d: 0x000c,
+ 0x1c30: 0x000a,
+ 0x1c36: 0x000a, 0x1c37: 0x000a,
+ 0x1c3d: 0x000a, 0x1c3e: 0x000a, 0x1c3f: 0x000a,
+ // Block 0x71, offset 0x1c40
+ 0x1c59: 0x000c, 0x1c5a: 0x000c, 0x1c5b: 0x000a, 0x1c5c: 0x000a,
+ 0x1c60: 0x000a,
+ // Block 0x72, offset 0x1c80
+ 0x1cbb: 0x000a,
+ // Block 0x73, offset 0x1cc0
+ 0x1cc0: 0x000a, 0x1cc1: 0x000a, 0x1cc2: 0x000a, 0x1cc3: 0x000a, 0x1cc4: 0x000a, 0x1cc5: 0x000a,
+ 0x1cc6: 0x000a, 0x1cc7: 0x000a, 0x1cc8: 0x000a, 0x1cc9: 0x000a, 0x1cca: 0x000a, 0x1ccb: 0x000a,
+ 0x1ccc: 0x000a, 0x1ccd: 0x000a, 0x1cce: 0x000a, 0x1ccf: 0x000a, 0x1cd0: 0x000a, 0x1cd1: 0x000a,
+ 0x1cd2: 0x000a, 0x1cd3: 0x000a, 0x1cd4: 0x000a, 0x1cd5: 0x000a, 0x1cd6: 0x000a, 0x1cd7: 0x000a,
+ 0x1cd8: 0x000a, 0x1cd9: 0x000a, 0x1cda: 0x000a, 0x1cdb: 0x000a, 0x1cdc: 0x000a, 0x1cdd: 0x000a,
+ 0x1cde: 0x000a, 0x1cdf: 0x000a, 0x1ce0: 0x000a, 0x1ce1: 0x000a, 0x1ce2: 0x000a, 0x1ce3: 0x000a,
+ // Block 0x74, offset 0x1d00
+ 0x1d1d: 0x000a,
+ 0x1d1e: 0x000a,
+ // Block 0x75, offset 0x1d40
+ 0x1d50: 0x000a, 0x1d51: 0x000a,
+ 0x1d52: 0x000a, 0x1d53: 0x000a, 0x1d54: 0x000a, 0x1d55: 0x000a, 0x1d56: 0x000a, 0x1d57: 0x000a,
+ 0x1d58: 0x000a, 0x1d59: 0x000a, 0x1d5a: 0x000a, 0x1d5b: 0x000a, 0x1d5c: 0x000a, 0x1d5d: 0x000a,
+ 0x1d5e: 0x000a, 0x1d5f: 0x000a,
+ 0x1d7c: 0x000a, 0x1d7d: 0x000a, 0x1d7e: 0x000a,
+ // Block 0x76, offset 0x1d80
+ 0x1db1: 0x000a, 0x1db2: 0x000a, 0x1db3: 0x000a, 0x1db4: 0x000a, 0x1db5: 0x000a,
+ 0x1db6: 0x000a, 0x1db7: 0x000a, 0x1db8: 0x000a, 0x1db9: 0x000a, 0x1dba: 0x000a, 0x1dbb: 0x000a,
+ 0x1dbc: 0x000a, 0x1dbd: 0x000a, 0x1dbe: 0x000a, 0x1dbf: 0x000a,
+ // Block 0x77, offset 0x1dc0
+ 0x1dcc: 0x000a, 0x1dcd: 0x000a, 0x1dce: 0x000a, 0x1dcf: 0x000a,
+ // Block 0x78, offset 0x1e00
+ 0x1e37: 0x000a, 0x1e38: 0x000a, 0x1e39: 0x000a, 0x1e3a: 0x000a,
+ // Block 0x79, offset 0x1e40
+ 0x1e5e: 0x000a, 0x1e5f: 0x000a,
+ 0x1e7f: 0x000a,
+ // Block 0x7a, offset 0x1e80
+ 0x1e90: 0x000a, 0x1e91: 0x000a,
+ 0x1e92: 0x000a, 0x1e93: 0x000a, 0x1e94: 0x000a, 0x1e95: 0x000a, 0x1e96: 0x000a, 0x1e97: 0x000a,
+ 0x1e98: 0x000a, 0x1e99: 0x000a, 0x1e9a: 0x000a, 0x1e9b: 0x000a, 0x1e9c: 0x000a, 0x1e9d: 0x000a,
+ 0x1e9e: 0x000a, 0x1e9f: 0x000a, 0x1ea0: 0x000a, 0x1ea1: 0x000a, 0x1ea2: 0x000a, 0x1ea3: 0x000a,
+ 0x1ea4: 0x000a, 0x1ea5: 0x000a, 0x1ea6: 0x000a, 0x1ea7: 0x000a, 0x1ea8: 0x000a, 0x1ea9: 0x000a,
+ 0x1eaa: 0x000a, 0x1eab: 0x000a, 0x1eac: 0x000a, 0x1ead: 0x000a, 0x1eae: 0x000a, 0x1eaf: 0x000a,
+ 0x1eb0: 0x000a, 0x1eb1: 0x000a, 0x1eb2: 0x000a, 0x1eb3: 0x000a, 0x1eb4: 0x000a, 0x1eb5: 0x000a,
+ 0x1eb6: 0x000a, 0x1eb7: 0x000a, 0x1eb8: 0x000a, 0x1eb9: 0x000a, 0x1eba: 0x000a, 0x1ebb: 0x000a,
+ 0x1ebc: 0x000a, 0x1ebd: 0x000a, 0x1ebe: 0x000a, 0x1ebf: 0x000a,
+ // Block 0x7b, offset 0x1ec0
+ 0x1ec0: 0x000a, 0x1ec1: 0x000a, 0x1ec2: 0x000a, 0x1ec3: 0x000a, 0x1ec4: 0x000a, 0x1ec5: 0x000a,
+ 0x1ec6: 0x000a,
+ // Block 0x7c, offset 0x1f00
+ 0x1f0d: 0x000a, 0x1f0e: 0x000a, 0x1f0f: 0x000a,
+ // Block 0x7d, offset 0x1f40
+ 0x1f6f: 0x000c,
+ 0x1f70: 0x000c, 0x1f71: 0x000c, 0x1f72: 0x000c, 0x1f73: 0x000a, 0x1f74: 0x000c, 0x1f75: 0x000c,
+ 0x1f76: 0x000c, 0x1f77: 0x000c, 0x1f78: 0x000c, 0x1f79: 0x000c, 0x1f7a: 0x000c, 0x1f7b: 0x000c,
+ 0x1f7c: 0x000c, 0x1f7d: 0x000c, 0x1f7e: 0x000a, 0x1f7f: 0x000a,
+ // Block 0x7e, offset 0x1f80
+ 0x1f9e: 0x000c, 0x1f9f: 0x000c,
+ // Block 0x7f, offset 0x1fc0
+ 0x1ff0: 0x000c, 0x1ff1: 0x000c,
+ // Block 0x80, offset 0x2000
+ 0x2000: 0x000a, 0x2001: 0x000a, 0x2002: 0x000a, 0x2003: 0x000a, 0x2004: 0x000a, 0x2005: 0x000a,
+ 0x2006: 0x000a, 0x2007: 0x000a, 0x2008: 0x000a, 0x2009: 0x000a, 0x200a: 0x000a, 0x200b: 0x000a,
+ 0x200c: 0x000a, 0x200d: 0x000a, 0x200e: 0x000a, 0x200f: 0x000a, 0x2010: 0x000a, 0x2011: 0x000a,
+ 0x2012: 0x000a, 0x2013: 0x000a, 0x2014: 0x000a, 0x2015: 0x000a, 0x2016: 0x000a, 0x2017: 0x000a,
+ 0x2018: 0x000a, 0x2019: 0x000a, 0x201a: 0x000a, 0x201b: 0x000a, 0x201c: 0x000a, 0x201d: 0x000a,
+ 0x201e: 0x000a, 0x201f: 0x000a, 0x2020: 0x000a, 0x2021: 0x000a,
+ // Block 0x81, offset 0x2040
+ 0x2048: 0x000a,
+ // Block 0x82, offset 0x2080
+ 0x2082: 0x000c,
+ 0x2086: 0x000c, 0x208b: 0x000c,
+ 0x20a5: 0x000c, 0x20a6: 0x000c, 0x20a8: 0x000a, 0x20a9: 0x000a,
+ 0x20aa: 0x000a, 0x20ab: 0x000a,
+ 0x20b8: 0x0004, 0x20b9: 0x0004,
+ // Block 0x83, offset 0x20c0
+ 0x20f4: 0x000a, 0x20f5: 0x000a,
+ 0x20f6: 0x000a, 0x20f7: 0x000a,
+ // Block 0x84, offset 0x2100
+ 0x2104: 0x000c, 0x2105: 0x000c,
+ 0x2120: 0x000c, 0x2121: 0x000c, 0x2122: 0x000c, 0x2123: 0x000c,
+ 0x2124: 0x000c, 0x2125: 0x000c, 0x2126: 0x000c, 0x2127: 0x000c, 0x2128: 0x000c, 0x2129: 0x000c,
+ 0x212a: 0x000c, 0x212b: 0x000c, 0x212c: 0x000c, 0x212d: 0x000c, 0x212e: 0x000c, 0x212f: 0x000c,
+ 0x2130: 0x000c, 0x2131: 0x000c,
+ // Block 0x85, offset 0x2140
+ 0x2166: 0x000c, 0x2167: 0x000c, 0x2168: 0x000c, 0x2169: 0x000c,
+ 0x216a: 0x000c, 0x216b: 0x000c, 0x216c: 0x000c, 0x216d: 0x000c,
+ // Block 0x86, offset 0x2180
+ 0x2187: 0x000c, 0x2188: 0x000c, 0x2189: 0x000c, 0x218a: 0x000c, 0x218b: 0x000c,
+ 0x218c: 0x000c, 0x218d: 0x000c, 0x218e: 0x000c, 0x218f: 0x000c, 0x2190: 0x000c, 0x2191: 0x000c,
+ // Block 0x87, offset 0x21c0
+ 0x21c0: 0x000c, 0x21c1: 0x000c, 0x21c2: 0x000c,
+ 0x21f3: 0x000c,
+ 0x21f6: 0x000c, 0x21f7: 0x000c, 0x21f8: 0x000c, 0x21f9: 0x000c,
+ 0x21fc: 0x000c,
+ // Block 0x88, offset 0x2200
+ 0x2225: 0x000c,
+ // Block 0x89, offset 0x2240
+ 0x2269: 0x000c,
+ 0x226a: 0x000c, 0x226b: 0x000c, 0x226c: 0x000c, 0x226d: 0x000c, 0x226e: 0x000c,
+ 0x2271: 0x000c, 0x2272: 0x000c, 0x2275: 0x000c,
+ 0x2276: 0x000c,
+ // Block 0x8a, offset 0x2280
+ 0x2283: 0x000c,
+ 0x228c: 0x000c,
+ 0x22bc: 0x000c,
+ // Block 0x8b, offset 0x22c0
+ 0x22f0: 0x000c, 0x22f2: 0x000c, 0x22f3: 0x000c, 0x22f4: 0x000c,
+ 0x22f7: 0x000c, 0x22f8: 0x000c,
+ 0x22fe: 0x000c, 0x22ff: 0x000c,
+ // Block 0x8c, offset 0x2300
+ 0x2301: 0x000c,
+ 0x232c: 0x000c, 0x232d: 0x000c,
+ 0x2336: 0x000c,
+ // Block 0x8d, offset 0x2340
+ 0x2365: 0x000c, 0x2368: 0x000c,
+ 0x236d: 0x000c,
+ // Block 0x8e, offset 0x2380
+ 0x239d: 0x0001,
+ 0x239e: 0x000c, 0x239f: 0x0001, 0x23a0: 0x0001, 0x23a1: 0x0001, 0x23a2: 0x0001, 0x23a3: 0x0001,
+ 0x23a4: 0x0001, 0x23a5: 0x0001, 0x23a6: 0x0001, 0x23a7: 0x0001, 0x23a8: 0x0001, 0x23a9: 0x0003,
+ 0x23aa: 0x0001, 0x23ab: 0x0001, 0x23ac: 0x0001, 0x23ad: 0x0001, 0x23ae: 0x0001, 0x23af: 0x0001,
+ 0x23b0: 0x0001, 0x23b1: 0x0001, 0x23b2: 0x0001, 0x23b3: 0x0001, 0x23b4: 0x0001, 0x23b5: 0x0001,
+ 0x23b6: 0x0001, 0x23b7: 0x0001, 0x23b8: 0x0001, 0x23b9: 0x0001, 0x23ba: 0x0001, 0x23bb: 0x0001,
+ 0x23bc: 0x0001, 0x23bd: 0x0001, 0x23be: 0x0001, 0x23bf: 0x0001,
+ // Block 0x8f, offset 0x23c0
+ 0x23c0: 0x0001, 0x23c1: 0x0001, 0x23c2: 0x0001, 0x23c3: 0x0001, 0x23c4: 0x0001, 0x23c5: 0x0001,
+ 0x23c6: 0x0001, 0x23c7: 0x0001, 0x23c8: 0x0001, 0x23c9: 0x0001, 0x23ca: 0x0001, 0x23cb: 0x0001,
+ 0x23cc: 0x0001, 0x23cd: 0x0001, 0x23ce: 0x0001, 0x23cf: 0x0001, 0x23d0: 0x000d, 0x23d1: 0x000d,
+ 0x23d2: 0x000d, 0x23d3: 0x000d, 0x23d4: 0x000d, 0x23d5: 0x000d, 0x23d6: 0x000d, 0x23d7: 0x000d,
+ 0x23d8: 0x000d, 0x23d9: 0x000d, 0x23da: 0x000d, 0x23db: 0x000d, 0x23dc: 0x000d, 0x23dd: 0x000d,
+ 0x23de: 0x000d, 0x23df: 0x000d, 0x23e0: 0x000d, 0x23e1: 0x000d, 0x23e2: 0x000d, 0x23e3: 0x000d,
+ 0x23e4: 0x000d, 0x23e5: 0x000d, 0x23e6: 0x000d, 0x23e7: 0x000d, 0x23e8: 0x000d, 0x23e9: 0x000d,
+ 0x23ea: 0x000d, 0x23eb: 0x000d, 0x23ec: 0x000d, 0x23ed: 0x000d, 0x23ee: 0x000d, 0x23ef: 0x000d,
+ 0x23f0: 0x000d, 0x23f1: 0x000d, 0x23f2: 0x000d, 0x23f3: 0x000d, 0x23f4: 0x000d, 0x23f5: 0x000d,
+ 0x23f6: 0x000d, 0x23f7: 0x000d, 0x23f8: 0x000d, 0x23f9: 0x000d, 0x23fa: 0x000d, 0x23fb: 0x000d,
+ 0x23fc: 0x000d, 0x23fd: 0x000d, 0x23fe: 0x000d, 0x23ff: 0x000d,
+ // Block 0x90, offset 0x2400
+ 0x2400: 0x000d, 0x2401: 0x000d, 0x2402: 0x000d, 0x2403: 0x000d, 0x2404: 0x000d, 0x2405: 0x000d,
+ 0x2406: 0x000d, 0x2407: 0x000d, 0x2408: 0x000d, 0x2409: 0x000d, 0x240a: 0x000d, 0x240b: 0x000d,
+ 0x240c: 0x000d, 0x240d: 0x000d, 0x240e: 0x000d, 0x240f: 0x000d, 0x2410: 0x000d, 0x2411: 0x000d,
+ 0x2412: 0x000d, 0x2413: 0x000d, 0x2414: 0x000d, 0x2415: 0x000d, 0x2416: 0x000d, 0x2417: 0x000d,
+ 0x2418: 0x000d, 0x2419: 0x000d, 0x241a: 0x000d, 0x241b: 0x000d, 0x241c: 0x000d, 0x241d: 0x000d,
+ 0x241e: 0x000d, 0x241f: 0x000d, 0x2420: 0x000d, 0x2421: 0x000d, 0x2422: 0x000d, 0x2423: 0x000d,
+ 0x2424: 0x000d, 0x2425: 0x000d, 0x2426: 0x000d, 0x2427: 0x000d, 0x2428: 0x000d, 0x2429: 0x000d,
+ 0x242a: 0x000d, 0x242b: 0x000d, 0x242c: 0x000d, 0x242d: 0x000d, 0x242e: 0x000d, 0x242f: 0x000d,
+ 0x2430: 0x000d, 0x2431: 0x000d, 0x2432: 0x000d, 0x2433: 0x000d, 0x2434: 0x000d, 0x2435: 0x000d,
+ 0x2436: 0x000d, 0x2437: 0x000d, 0x2438: 0x000d, 0x2439: 0x000d, 0x243a: 0x000d, 0x243b: 0x000d,
+ 0x243c: 0x000d, 0x243d: 0x000d, 0x243e: 0x000a, 0x243f: 0x000a,
+ // Block 0x91, offset 0x2440
+ 0x2440: 0x000d, 0x2441: 0x000d, 0x2442: 0x000d, 0x2443: 0x000d, 0x2444: 0x000d, 0x2445: 0x000d,
+ 0x2446: 0x000d, 0x2447: 0x000d, 0x2448: 0x000d, 0x2449: 0x000d, 0x244a: 0x000d, 0x244b: 0x000d,
+ 0x244c: 0x000d, 0x244d: 0x000d, 0x244e: 0x000d, 0x244f: 0x000d, 0x2450: 0x000b, 0x2451: 0x000b,
+ 0x2452: 0x000b, 0x2453: 0x000b, 0x2454: 0x000b, 0x2455: 0x000b, 0x2456: 0x000b, 0x2457: 0x000b,
+ 0x2458: 0x000b, 0x2459: 0x000b, 0x245a: 0x000b, 0x245b: 0x000b, 0x245c: 0x000b, 0x245d: 0x000b,
+ 0x245e: 0x000b, 0x245f: 0x000b, 0x2460: 0x000b, 0x2461: 0x000b, 0x2462: 0x000b, 0x2463: 0x000b,
+ 0x2464: 0x000b, 0x2465: 0x000b, 0x2466: 0x000b, 0x2467: 0x000b, 0x2468: 0x000b, 0x2469: 0x000b,
+ 0x246a: 0x000b, 0x246b: 0x000b, 0x246c: 0x000b, 0x246d: 0x000b, 0x246e: 0x000b, 0x246f: 0x000b,
+ 0x2470: 0x000d, 0x2471: 0x000d, 0x2472: 0x000d, 0x2473: 0x000d, 0x2474: 0x000d, 0x2475: 0x000d,
+ 0x2476: 0x000d, 0x2477: 0x000d, 0x2478: 0x000d, 0x2479: 0x000d, 0x247a: 0x000d, 0x247b: 0x000d,
+ 0x247c: 0x000d, 0x247d: 0x000a, 0x247e: 0x000d, 0x247f: 0x000d,
+ // Block 0x92, offset 0x2480
+ 0x2480: 0x000c, 0x2481: 0x000c, 0x2482: 0x000c, 0x2483: 0x000c, 0x2484: 0x000c, 0x2485: 0x000c,
+ 0x2486: 0x000c, 0x2487: 0x000c, 0x2488: 0x000c, 0x2489: 0x000c, 0x248a: 0x000c, 0x248b: 0x000c,
+ 0x248c: 0x000c, 0x248d: 0x000c, 0x248e: 0x000c, 0x248f: 0x000c, 0x2490: 0x000a, 0x2491: 0x000a,
+ 0x2492: 0x000a, 0x2493: 0x000a, 0x2494: 0x000a, 0x2495: 0x000a, 0x2496: 0x000a, 0x2497: 0x000a,
+ 0x2498: 0x000a, 0x2499: 0x000a,
+ 0x24a0: 0x000c, 0x24a1: 0x000c, 0x24a2: 0x000c, 0x24a3: 0x000c,
+ 0x24a4: 0x000c, 0x24a5: 0x000c, 0x24a6: 0x000c, 0x24a7: 0x000c, 0x24a8: 0x000c, 0x24a9: 0x000c,
+ 0x24aa: 0x000c, 0x24ab: 0x000c, 0x24ac: 0x000c, 0x24ad: 0x000c, 0x24ae: 0x000c, 0x24af: 0x000c,
+ 0x24b0: 0x000a, 0x24b1: 0x000a, 0x24b2: 0x000a, 0x24b3: 0x000a, 0x24b4: 0x000a, 0x24b5: 0x000a,
+ 0x24b6: 0x000a, 0x24b7: 0x000a, 0x24b8: 0x000a, 0x24b9: 0x000a, 0x24ba: 0x000a, 0x24bb: 0x000a,
+ 0x24bc: 0x000a, 0x24bd: 0x000a, 0x24be: 0x000a, 0x24bf: 0x000a,
+ // Block 0x93, offset 0x24c0
+ 0x24c0: 0x000a, 0x24c1: 0x000a, 0x24c2: 0x000a, 0x24c3: 0x000a, 0x24c4: 0x000a, 0x24c5: 0x000a,
+ 0x24c6: 0x000a, 0x24c7: 0x000a, 0x24c8: 0x000a, 0x24c9: 0x000a, 0x24ca: 0x000a, 0x24cb: 0x000a,
+ 0x24cc: 0x000a, 0x24cd: 0x000a, 0x24ce: 0x000a, 0x24cf: 0x000a, 0x24d0: 0x0006, 0x24d1: 0x000a,
+ 0x24d2: 0x0006, 0x24d4: 0x000a, 0x24d5: 0x0006, 0x24d6: 0x000a, 0x24d7: 0x000a,
+ 0x24d8: 0x000a, 0x24d9: 0x009a, 0x24da: 0x008a, 0x24db: 0x007a, 0x24dc: 0x006a, 0x24dd: 0x009a,
+ 0x24de: 0x008a, 0x24df: 0x0004, 0x24e0: 0x000a, 0x24e1: 0x000a, 0x24e2: 0x0003, 0x24e3: 0x0003,
+ 0x24e4: 0x000a, 0x24e5: 0x000a, 0x24e6: 0x000a, 0x24e8: 0x000a, 0x24e9: 0x0004,
+ 0x24ea: 0x0004, 0x24eb: 0x000a,
+ 0x24f0: 0x000d, 0x24f1: 0x000d, 0x24f2: 0x000d, 0x24f3: 0x000d, 0x24f4: 0x000d, 0x24f5: 0x000d,
+ 0x24f6: 0x000d, 0x24f7: 0x000d, 0x24f8: 0x000d, 0x24f9: 0x000d, 0x24fa: 0x000d, 0x24fb: 0x000d,
+ 0x24fc: 0x000d, 0x24fd: 0x000d, 0x24fe: 0x000d, 0x24ff: 0x000d,
+ // Block 0x94, offset 0x2500
+ 0x2500: 0x000d, 0x2501: 0x000d, 0x2502: 0x000d, 0x2503: 0x000d, 0x2504: 0x000d, 0x2505: 0x000d,
+ 0x2506: 0x000d, 0x2507: 0x000d, 0x2508: 0x000d, 0x2509: 0x000d, 0x250a: 0x000d, 0x250b: 0x000d,
+ 0x250c: 0x000d, 0x250d: 0x000d, 0x250e: 0x000d, 0x250f: 0x000d, 0x2510: 0x000d, 0x2511: 0x000d,
+ 0x2512: 0x000d, 0x2513: 0x000d, 0x2514: 0x000d, 0x2515: 0x000d, 0x2516: 0x000d, 0x2517: 0x000d,
+ 0x2518: 0x000d, 0x2519: 0x000d, 0x251a: 0x000d, 0x251b: 0x000d, 0x251c: 0x000d, 0x251d: 0x000d,
+ 0x251e: 0x000d, 0x251f: 0x000d, 0x2520: 0x000d, 0x2521: 0x000d, 0x2522: 0x000d, 0x2523: 0x000d,
+ 0x2524: 0x000d, 0x2525: 0x000d, 0x2526: 0x000d, 0x2527: 0x000d, 0x2528: 0x000d, 0x2529: 0x000d,
+ 0x252a: 0x000d, 0x252b: 0x000d, 0x252c: 0x000d, 0x252d: 0x000d, 0x252e: 0x000d, 0x252f: 0x000d,
+ 0x2530: 0x000d, 0x2531: 0x000d, 0x2532: 0x000d, 0x2533: 0x000d, 0x2534: 0x000d, 0x2535: 0x000d,
+ 0x2536: 0x000d, 0x2537: 0x000d, 0x2538: 0x000d, 0x2539: 0x000d, 0x253a: 0x000d, 0x253b: 0x000d,
+ 0x253c: 0x000d, 0x253d: 0x000d, 0x253e: 0x000d, 0x253f: 0x000b,
+ // Block 0x95, offset 0x2540
+ 0x2541: 0x000a, 0x2542: 0x000a, 0x2543: 0x0004, 0x2544: 0x0004, 0x2545: 0x0004,
+ 0x2546: 0x000a, 0x2547: 0x000a, 0x2548: 0x003a, 0x2549: 0x002a, 0x254a: 0x000a, 0x254b: 0x0003,
+ 0x254c: 0x0006, 0x254d: 0x0003, 0x254e: 0x0006, 0x254f: 0x0006, 0x2550: 0x0002, 0x2551: 0x0002,
+ 0x2552: 0x0002, 0x2553: 0x0002, 0x2554: 0x0002, 0x2555: 0x0002, 0x2556: 0x0002, 0x2557: 0x0002,
+ 0x2558: 0x0002, 0x2559: 0x0002, 0x255a: 0x0006, 0x255b: 0x000a, 0x255c: 0x000a, 0x255d: 0x000a,
+ 0x255e: 0x000a, 0x255f: 0x000a, 0x2560: 0x000a,
+ 0x257b: 0x005a,
+ 0x257c: 0x000a, 0x257d: 0x004a, 0x257e: 0x000a, 0x257f: 0x000a,
+ // Block 0x96, offset 0x2580
+ 0x2580: 0x000a,
+ 0x259b: 0x005a, 0x259c: 0x000a, 0x259d: 0x004a,
+ 0x259e: 0x000a, 0x259f: 0x00fa, 0x25a0: 0x00ea, 0x25a1: 0x000a, 0x25a2: 0x003a, 0x25a3: 0x002a,
+ 0x25a4: 0x000a, 0x25a5: 0x000a,
+ // Block 0x97, offset 0x25c0
+ 0x25e0: 0x0004, 0x25e1: 0x0004, 0x25e2: 0x000a, 0x25e3: 0x000a,
+ 0x25e4: 0x000a, 0x25e5: 0x0004, 0x25e6: 0x0004, 0x25e8: 0x000a, 0x25e9: 0x000a,
+ 0x25ea: 0x000a, 0x25eb: 0x000a, 0x25ec: 0x000a, 0x25ed: 0x000a, 0x25ee: 0x000a,
+ 0x25f0: 0x000b, 0x25f1: 0x000b, 0x25f2: 0x000b, 0x25f3: 0x000b, 0x25f4: 0x000b, 0x25f5: 0x000b,
+ 0x25f6: 0x000b, 0x25f7: 0x000b, 0x25f8: 0x000b, 0x25f9: 0x000a, 0x25fa: 0x000a, 0x25fb: 0x000a,
+ 0x25fc: 0x000a, 0x25fd: 0x000a, 0x25fe: 0x000b, 0x25ff: 0x000b,
+ // Block 0x98, offset 0x2600
+ 0x2601: 0x000a,
+ // Block 0x99, offset 0x2640
+ 0x2640: 0x000a, 0x2641: 0x000a, 0x2642: 0x000a, 0x2643: 0x000a, 0x2644: 0x000a, 0x2645: 0x000a,
+ 0x2646: 0x000a, 0x2647: 0x000a, 0x2648: 0x000a, 0x2649: 0x000a, 0x264a: 0x000a, 0x264b: 0x000a,
+ 0x264c: 0x000a, 0x2650: 0x000a, 0x2651: 0x000a,
+ 0x2652: 0x000a, 0x2653: 0x000a, 0x2654: 0x000a, 0x2655: 0x000a, 0x2656: 0x000a, 0x2657: 0x000a,
+ 0x2658: 0x000a, 0x2659: 0x000a, 0x265a: 0x000a, 0x265b: 0x000a,
+ 0x2660: 0x000a,
+ // Block 0x9a, offset 0x2680
+ 0x26bd: 0x000c,
+ // Block 0x9b, offset 0x26c0
+ 0x26e0: 0x000c, 0x26e1: 0x0002, 0x26e2: 0x0002, 0x26e3: 0x0002,
+ 0x26e4: 0x0002, 0x26e5: 0x0002, 0x26e6: 0x0002, 0x26e7: 0x0002, 0x26e8: 0x0002, 0x26e9: 0x0002,
+ 0x26ea: 0x0002, 0x26eb: 0x0002, 0x26ec: 0x0002, 0x26ed: 0x0002, 0x26ee: 0x0002, 0x26ef: 0x0002,
+ 0x26f0: 0x0002, 0x26f1: 0x0002, 0x26f2: 0x0002, 0x26f3: 0x0002, 0x26f4: 0x0002, 0x26f5: 0x0002,
+ 0x26f6: 0x0002, 0x26f7: 0x0002, 0x26f8: 0x0002, 0x26f9: 0x0002, 0x26fa: 0x0002, 0x26fb: 0x0002,
+ // Block 0x9c, offset 0x2700
+ 0x2736: 0x000c, 0x2737: 0x000c, 0x2738: 0x000c, 0x2739: 0x000c, 0x273a: 0x000c,
+ // Block 0x9d, offset 0x2740
+ 0x2740: 0x0001, 0x2741: 0x0001, 0x2742: 0x0001, 0x2743: 0x0001, 0x2744: 0x0001, 0x2745: 0x0001,
+ 0x2746: 0x0001, 0x2747: 0x0001, 0x2748: 0x0001, 0x2749: 0x0001, 0x274a: 0x0001, 0x274b: 0x0001,
+ 0x274c: 0x0001, 0x274d: 0x0001, 0x274e: 0x0001, 0x274f: 0x0001, 0x2750: 0x0001, 0x2751: 0x0001,
+ 0x2752: 0x0001, 0x2753: 0x0001, 0x2754: 0x0001, 0x2755: 0x0001, 0x2756: 0x0001, 0x2757: 0x0001,
+ 0x2758: 0x0001, 0x2759: 0x0001, 0x275a: 0x0001, 0x275b: 0x0001, 0x275c: 0x0001, 0x275d: 0x0001,
+ 0x275e: 0x0001, 0x275f: 0x0001, 0x2760: 0x0001, 0x2761: 0x0001, 0x2762: 0x0001, 0x2763: 0x0001,
+ 0x2764: 0x0001, 0x2765: 0x0001, 0x2766: 0x0001, 0x2767: 0x0001, 0x2768: 0x0001, 0x2769: 0x0001,
+ 0x276a: 0x0001, 0x276b: 0x0001, 0x276c: 0x0001, 0x276d: 0x0001, 0x276e: 0x0001, 0x276f: 0x0001,
+ 0x2770: 0x0001, 0x2771: 0x0001, 0x2772: 0x0001, 0x2773: 0x0001, 0x2774: 0x0001, 0x2775: 0x0001,
+ 0x2776: 0x0001, 0x2777: 0x0001, 0x2778: 0x0001, 0x2779: 0x0001, 0x277a: 0x0001, 0x277b: 0x0001,
+ 0x277c: 0x0001, 0x277d: 0x0001, 0x277e: 0x0001, 0x277f: 0x0001,
+ // Block 0x9e, offset 0x2780
+ 0x2780: 0x0001, 0x2781: 0x0001, 0x2782: 0x0001, 0x2783: 0x0001, 0x2784: 0x0001, 0x2785: 0x0001,
+ 0x2786: 0x0001, 0x2787: 0x0001, 0x2788: 0x0001, 0x2789: 0x0001, 0x278a: 0x0001, 0x278b: 0x0001,
+ 0x278c: 0x0001, 0x278d: 0x0001, 0x278e: 0x0001, 0x278f: 0x0001, 0x2790: 0x0001, 0x2791: 0x0001,
+ 0x2792: 0x0001, 0x2793: 0x0001, 0x2794: 0x0001, 0x2795: 0x0001, 0x2796: 0x0001, 0x2797: 0x0001,
+ 0x2798: 0x0001, 0x2799: 0x0001, 0x279a: 0x0001, 0x279b: 0x0001, 0x279c: 0x0001, 0x279d: 0x0001,
+ 0x279e: 0x0001, 0x279f: 0x000a, 0x27a0: 0x0001, 0x27a1: 0x0001, 0x27a2: 0x0001, 0x27a3: 0x0001,
+ 0x27a4: 0x0001, 0x27a5: 0x0001, 0x27a6: 0x0001, 0x27a7: 0x0001, 0x27a8: 0x0001, 0x27a9: 0x0001,
+ 0x27aa: 0x0001, 0x27ab: 0x0001, 0x27ac: 0x0001, 0x27ad: 0x0001, 0x27ae: 0x0001, 0x27af: 0x0001,
+ 0x27b0: 0x0001, 0x27b1: 0x0001, 0x27b2: 0x0001, 0x27b3: 0x0001, 0x27b4: 0x0001, 0x27b5: 0x0001,
+ 0x27b6: 0x0001, 0x27b7: 0x0001, 0x27b8: 0x0001, 0x27b9: 0x0001, 0x27ba: 0x0001, 0x27bb: 0x0001,
+ 0x27bc: 0x0001, 0x27bd: 0x0001, 0x27be: 0x0001, 0x27bf: 0x0001,
+ // Block 0x9f, offset 0x27c0
+ 0x27c0: 0x0001, 0x27c1: 0x000c, 0x27c2: 0x000c, 0x27c3: 0x000c, 0x27c4: 0x0001, 0x27c5: 0x000c,
+ 0x27c6: 0x000c, 0x27c7: 0x0001, 0x27c8: 0x0001, 0x27c9: 0x0001, 0x27ca: 0x0001, 0x27cb: 0x0001,
+ 0x27cc: 0x000c, 0x27cd: 0x000c, 0x27ce: 0x000c, 0x27cf: 0x000c, 0x27d0: 0x0001, 0x27d1: 0x0001,
+ 0x27d2: 0x0001, 0x27d3: 0x0001, 0x27d4: 0x0001, 0x27d5: 0x0001, 0x27d6: 0x0001, 0x27d7: 0x0001,
+ 0x27d8: 0x0001, 0x27d9: 0x0001, 0x27da: 0x0001, 0x27db: 0x0001, 0x27dc: 0x0001, 0x27dd: 0x0001,
+ 0x27de: 0x0001, 0x27df: 0x0001, 0x27e0: 0x0001, 0x27e1: 0x0001, 0x27e2: 0x0001, 0x27e3: 0x0001,
+ 0x27e4: 0x0001, 0x27e5: 0x0001, 0x27e6: 0x0001, 0x27e7: 0x0001, 0x27e8: 0x0001, 0x27e9: 0x0001,
+ 0x27ea: 0x0001, 0x27eb: 0x0001, 0x27ec: 0x0001, 0x27ed: 0x0001, 0x27ee: 0x0001, 0x27ef: 0x0001,
+ 0x27f0: 0x0001, 0x27f1: 0x0001, 0x27f2: 0x0001, 0x27f3: 0x0001, 0x27f4: 0x0001, 0x27f5: 0x0001,
+ 0x27f6: 0x0001, 0x27f7: 0x0001, 0x27f8: 0x000c, 0x27f9: 0x000c, 0x27fa: 0x000c, 0x27fb: 0x0001,
+ 0x27fc: 0x0001, 0x27fd: 0x0001, 0x27fe: 0x0001, 0x27ff: 0x000c,
+ // Block 0xa0, offset 0x2800
+ 0x2800: 0x0001, 0x2801: 0x0001, 0x2802: 0x0001, 0x2803: 0x0001, 0x2804: 0x0001, 0x2805: 0x0001,
+ 0x2806: 0x0001, 0x2807: 0x0001, 0x2808: 0x0001, 0x2809: 0x0001, 0x280a: 0x0001, 0x280b: 0x0001,
+ 0x280c: 0x0001, 0x280d: 0x0001, 0x280e: 0x0001, 0x280f: 0x0001, 0x2810: 0x0001, 0x2811: 0x0001,
+ 0x2812: 0x0001, 0x2813: 0x0001, 0x2814: 0x0001, 0x2815: 0x0001, 0x2816: 0x0001, 0x2817: 0x0001,
+ 0x2818: 0x0001, 0x2819: 0x0001, 0x281a: 0x0001, 0x281b: 0x0001, 0x281c: 0x0001, 0x281d: 0x0001,
+ 0x281e: 0x0001, 0x281f: 0x0001, 0x2820: 0x0001, 0x2821: 0x0001, 0x2822: 0x0001, 0x2823: 0x0001,
+ 0x2824: 0x0001, 0x2825: 0x000c, 0x2826: 0x000c, 0x2827: 0x0001, 0x2828: 0x0001, 0x2829: 0x0001,
+ 0x282a: 0x0001, 0x282b: 0x0001, 0x282c: 0x0001, 0x282d: 0x0001, 0x282e: 0x0001, 0x282f: 0x0001,
+ 0x2830: 0x0001, 0x2831: 0x0001, 0x2832: 0x0001, 0x2833: 0x0001, 0x2834: 0x0001, 0x2835: 0x0001,
+ 0x2836: 0x0001, 0x2837: 0x0001, 0x2838: 0x0001, 0x2839: 0x0001, 0x283a: 0x0001, 0x283b: 0x0001,
+ 0x283c: 0x0001, 0x283d: 0x0001, 0x283e: 0x0001, 0x283f: 0x0001,
+ // Block 0xa1, offset 0x2840
+ 0x2840: 0x0001, 0x2841: 0x0001, 0x2842: 0x0001, 0x2843: 0x0001, 0x2844: 0x0001, 0x2845: 0x0001,
+ 0x2846: 0x0001, 0x2847: 0x0001, 0x2848: 0x0001, 0x2849: 0x0001, 0x284a: 0x0001, 0x284b: 0x0001,
+ 0x284c: 0x0001, 0x284d: 0x0001, 0x284e: 0x0001, 0x284f: 0x0001, 0x2850: 0x0001, 0x2851: 0x0001,
+ 0x2852: 0x0001, 0x2853: 0x0001, 0x2854: 0x0001, 0x2855: 0x0001, 0x2856: 0x0001, 0x2857: 0x0001,
+ 0x2858: 0x0001, 0x2859: 0x0001, 0x285a: 0x0001, 0x285b: 0x0001, 0x285c: 0x0001, 0x285d: 0x0001,
+ 0x285e: 0x0001, 0x285f: 0x0001, 0x2860: 0x0001, 0x2861: 0x0001, 0x2862: 0x0001, 0x2863: 0x0001,
+ 0x2864: 0x0001, 0x2865: 0x0001, 0x2866: 0x0001, 0x2867: 0x0001, 0x2868: 0x0001, 0x2869: 0x0001,
+ 0x286a: 0x0001, 0x286b: 0x0001, 0x286c: 0x0001, 0x286d: 0x0001, 0x286e: 0x0001, 0x286f: 0x0001,
+ 0x2870: 0x0001, 0x2871: 0x0001, 0x2872: 0x0001, 0x2873: 0x0001, 0x2874: 0x0001, 0x2875: 0x0001,
+ 0x2876: 0x0001, 0x2877: 0x0001, 0x2878: 0x0001, 0x2879: 0x000a, 0x287a: 0x000a, 0x287b: 0x000a,
+ 0x287c: 0x000a, 0x287d: 0x000a, 0x287e: 0x000a, 0x287f: 0x000a,
+ // Block 0xa2, offset 0x2880
+ 0x2880: 0x0001, 0x2881: 0x0001, 0x2882: 0x0001, 0x2883: 0x0001, 0x2884: 0x0001, 0x2885: 0x0001,
+ 0x2886: 0x0001, 0x2887: 0x0001, 0x2888: 0x0001, 0x2889: 0x0001, 0x288a: 0x0001, 0x288b: 0x0001,
+ 0x288c: 0x0001, 0x288d: 0x0001, 0x288e: 0x0001, 0x288f: 0x0001, 0x2890: 0x0001, 0x2891: 0x0001,
+ 0x2892: 0x0001, 0x2893: 0x0001, 0x2894: 0x0001, 0x2895: 0x0001, 0x2896: 0x0001, 0x2897: 0x0001,
+ 0x2898: 0x0001, 0x2899: 0x0001, 0x289a: 0x0001, 0x289b: 0x0001, 0x289c: 0x0001, 0x289d: 0x0001,
+ 0x289e: 0x0001, 0x289f: 0x0001, 0x28a0: 0x0005, 0x28a1: 0x0005, 0x28a2: 0x0005, 0x28a3: 0x0005,
+ 0x28a4: 0x0005, 0x28a5: 0x0005, 0x28a6: 0x0005, 0x28a7: 0x0005, 0x28a8: 0x0005, 0x28a9: 0x0005,
+ 0x28aa: 0x0005, 0x28ab: 0x0005, 0x28ac: 0x0005, 0x28ad: 0x0005, 0x28ae: 0x0005, 0x28af: 0x0005,
+ 0x28b0: 0x0005, 0x28b1: 0x0005, 0x28b2: 0x0005, 0x28b3: 0x0005, 0x28b4: 0x0005, 0x28b5: 0x0005,
+ 0x28b6: 0x0005, 0x28b7: 0x0005, 0x28b8: 0x0005, 0x28b9: 0x0005, 0x28ba: 0x0005, 0x28bb: 0x0005,
+ 0x28bc: 0x0005, 0x28bd: 0x0005, 0x28be: 0x0005, 0x28bf: 0x0001,
+ // Block 0xa3, offset 0x28c0
+ 0x28c1: 0x000c,
+ 0x28f8: 0x000c, 0x28f9: 0x000c, 0x28fa: 0x000c, 0x28fb: 0x000c,
+ 0x28fc: 0x000c, 0x28fd: 0x000c, 0x28fe: 0x000c, 0x28ff: 0x000c,
+ // Block 0xa4, offset 0x2900
+ 0x2900: 0x000c, 0x2901: 0x000c, 0x2902: 0x000c, 0x2903: 0x000c, 0x2904: 0x000c, 0x2905: 0x000c,
+ 0x2906: 0x000c,
+ 0x2912: 0x000a, 0x2913: 0x000a, 0x2914: 0x000a, 0x2915: 0x000a, 0x2916: 0x000a, 0x2917: 0x000a,
+ 0x2918: 0x000a, 0x2919: 0x000a, 0x291a: 0x000a, 0x291b: 0x000a, 0x291c: 0x000a, 0x291d: 0x000a,
+ 0x291e: 0x000a, 0x291f: 0x000a, 0x2920: 0x000a, 0x2921: 0x000a, 0x2922: 0x000a, 0x2923: 0x000a,
+ 0x2924: 0x000a, 0x2925: 0x000a,
+ 0x293f: 0x000c,
+ // Block 0xa5, offset 0x2940
+ 0x2940: 0x000c, 0x2941: 0x000c,
+ 0x2973: 0x000c, 0x2974: 0x000c, 0x2975: 0x000c,
+ 0x2976: 0x000c, 0x2979: 0x000c, 0x297a: 0x000c,
+ // Block 0xa6, offset 0x2980
+ 0x2980: 0x000c, 0x2981: 0x000c, 0x2982: 0x000c,
+ 0x29a7: 0x000c, 0x29a8: 0x000c, 0x29a9: 0x000c,
+ 0x29aa: 0x000c, 0x29ab: 0x000c, 0x29ad: 0x000c, 0x29ae: 0x000c, 0x29af: 0x000c,
+ 0x29b0: 0x000c, 0x29b1: 0x000c, 0x29b2: 0x000c, 0x29b3: 0x000c, 0x29b4: 0x000c,
+ // Block 0xa7, offset 0x29c0
+ 0x29f3: 0x000c,
+ // Block 0xa8, offset 0x2a00
+ 0x2a00: 0x000c, 0x2a01: 0x000c,
+ 0x2a36: 0x000c, 0x2a37: 0x000c, 0x2a38: 0x000c, 0x2a39: 0x000c, 0x2a3a: 0x000c, 0x2a3b: 0x000c,
+ 0x2a3c: 0x000c, 0x2a3d: 0x000c, 0x2a3e: 0x000c,
+ // Block 0xa9, offset 0x2a40
+ 0x2a4a: 0x000c, 0x2a4b: 0x000c,
+ 0x2a4c: 0x000c,
+ // Block 0xaa, offset 0x2a80
+ 0x2aaf: 0x000c,
+ 0x2ab0: 0x000c, 0x2ab1: 0x000c, 0x2ab4: 0x000c,
+ 0x2ab6: 0x000c, 0x2ab7: 0x000c,
+ 0x2abe: 0x000c,
+ // Block 0xab, offset 0x2ac0
+ 0x2adf: 0x000c, 0x2ae3: 0x000c,
+ 0x2ae4: 0x000c, 0x2ae5: 0x000c, 0x2ae6: 0x000c, 0x2ae7: 0x000c, 0x2ae8: 0x000c, 0x2ae9: 0x000c,
+ 0x2aea: 0x000c,
+ // Block 0xac, offset 0x2b00
+ 0x2b00: 0x000c, 0x2b01: 0x000c,
+ 0x2b3c: 0x000c,
+ // Block 0xad, offset 0x2b40
+ 0x2b40: 0x000c,
+ 0x2b66: 0x000c, 0x2b67: 0x000c, 0x2b68: 0x000c, 0x2b69: 0x000c,
+ 0x2b6a: 0x000c, 0x2b6b: 0x000c, 0x2b6c: 0x000c,
+ 0x2b70: 0x000c, 0x2b71: 0x000c, 0x2b72: 0x000c, 0x2b73: 0x000c, 0x2b74: 0x000c,
+ // Block 0xae, offset 0x2b80
+ 0x2bb8: 0x000c, 0x2bb9: 0x000c, 0x2bba: 0x000c, 0x2bbb: 0x000c,
+ 0x2bbc: 0x000c, 0x2bbd: 0x000c, 0x2bbe: 0x000c, 0x2bbf: 0x000c,
+ // Block 0xaf, offset 0x2bc0
+ 0x2bc2: 0x000c, 0x2bc3: 0x000c, 0x2bc4: 0x000c,
+ 0x2bc6: 0x000c,
+ // Block 0xb0, offset 0x2c00
+ 0x2c33: 0x000c, 0x2c34: 0x000c, 0x2c35: 0x000c,
+ 0x2c36: 0x000c, 0x2c37: 0x000c, 0x2c38: 0x000c, 0x2c3a: 0x000c,
+ 0x2c3f: 0x000c,
+ // Block 0xb1, offset 0x2c40
+ 0x2c40: 0x000c, 0x2c42: 0x000c, 0x2c43: 0x000c,
+ // Block 0xb2, offset 0x2c80
+ 0x2cb2: 0x000c, 0x2cb3: 0x000c, 0x2cb4: 0x000c, 0x2cb5: 0x000c,
+ 0x2cbc: 0x000c, 0x2cbd: 0x000c, 0x2cbf: 0x000c,
+ // Block 0xb3, offset 0x2cc0
+ 0x2cc0: 0x000c,
+ 0x2cdc: 0x000c, 0x2cdd: 0x000c,
+ // Block 0xb4, offset 0x2d00
+ 0x2d33: 0x000c, 0x2d34: 0x000c, 0x2d35: 0x000c,
+ 0x2d36: 0x000c, 0x2d37: 0x000c, 0x2d38: 0x000c, 0x2d39: 0x000c, 0x2d3a: 0x000c,
+ 0x2d3d: 0x000c, 0x2d3f: 0x000c,
+ // Block 0xb5, offset 0x2d40
+ 0x2d40: 0x000c,
+ 0x2d60: 0x000a, 0x2d61: 0x000a, 0x2d62: 0x000a, 0x2d63: 0x000a,
+ 0x2d64: 0x000a, 0x2d65: 0x000a, 0x2d66: 0x000a, 0x2d67: 0x000a, 0x2d68: 0x000a, 0x2d69: 0x000a,
+ 0x2d6a: 0x000a, 0x2d6b: 0x000a, 0x2d6c: 0x000a,
+ // Block 0xb6, offset 0x2d80
+ 0x2dab: 0x000c, 0x2dad: 0x000c,
+ 0x2db0: 0x000c, 0x2db1: 0x000c, 0x2db2: 0x000c, 0x2db3: 0x000c, 0x2db4: 0x000c, 0x2db5: 0x000c,
+ 0x2db7: 0x000c,
+ // Block 0xb7, offset 0x2dc0
+ 0x2ddd: 0x000c,
+ 0x2dde: 0x000c, 0x2ddf: 0x000c, 0x2de2: 0x000c, 0x2de3: 0x000c,
+ 0x2de4: 0x000c, 0x2de5: 0x000c, 0x2de7: 0x000c, 0x2de8: 0x000c, 0x2de9: 0x000c,
+ 0x2dea: 0x000c, 0x2deb: 0x000c,
+ // Block 0xb8, offset 0x2e00
+ 0x2e30: 0x000c, 0x2e31: 0x000c, 0x2e32: 0x000c, 0x2e33: 0x000c, 0x2e34: 0x000c, 0x2e35: 0x000c,
+ 0x2e36: 0x000c, 0x2e38: 0x000c, 0x2e39: 0x000c, 0x2e3a: 0x000c, 0x2e3b: 0x000c,
+ 0x2e3c: 0x000c, 0x2e3d: 0x000c,
+ // Block 0xb9, offset 0x2e40
+ 0x2e52: 0x000c, 0x2e53: 0x000c, 0x2e54: 0x000c, 0x2e55: 0x000c, 0x2e56: 0x000c, 0x2e57: 0x000c,
+ 0x2e58: 0x000c, 0x2e59: 0x000c, 0x2e5a: 0x000c, 0x2e5b: 0x000c, 0x2e5c: 0x000c, 0x2e5d: 0x000c,
+ 0x2e5e: 0x000c, 0x2e5f: 0x000c, 0x2e60: 0x000c, 0x2e61: 0x000c, 0x2e62: 0x000c, 0x2e63: 0x000c,
+ 0x2e64: 0x000c, 0x2e65: 0x000c, 0x2e66: 0x000c, 0x2e67: 0x000c,
+ 0x2e6a: 0x000c, 0x2e6b: 0x000c, 0x2e6c: 0x000c, 0x2e6d: 0x000c, 0x2e6e: 0x000c, 0x2e6f: 0x000c,
+ 0x2e70: 0x000c, 0x2e72: 0x000c, 0x2e73: 0x000c, 0x2e75: 0x000c,
+ 0x2e76: 0x000c,
+ // Block 0xba, offset 0x2e80
+ 0x2eb0: 0x000c, 0x2eb1: 0x000c, 0x2eb2: 0x000c, 0x2eb3: 0x000c, 0x2eb4: 0x000c,
+ // Block 0xbb, offset 0x2ec0
+ 0x2ef0: 0x000c, 0x2ef1: 0x000c, 0x2ef2: 0x000c, 0x2ef3: 0x000c, 0x2ef4: 0x000c, 0x2ef5: 0x000c,
+ 0x2ef6: 0x000c,
+ // Block 0xbc, offset 0x2f00
+ 0x2f0f: 0x000c, 0x2f10: 0x000c, 0x2f11: 0x000c,
+ 0x2f12: 0x000c,
+ // Block 0xbd, offset 0x2f40
+ 0x2f5d: 0x000c,
+ 0x2f5e: 0x000c, 0x2f60: 0x000b, 0x2f61: 0x000b, 0x2f62: 0x000b, 0x2f63: 0x000b,
+ // Block 0xbe, offset 0x2f80
+ 0x2fa7: 0x000c, 0x2fa8: 0x000c, 0x2fa9: 0x000c,
+ 0x2fb3: 0x000b, 0x2fb4: 0x000b, 0x2fb5: 0x000b,
+ 0x2fb6: 0x000b, 0x2fb7: 0x000b, 0x2fb8: 0x000b, 0x2fb9: 0x000b, 0x2fba: 0x000b, 0x2fbb: 0x000c,
+ 0x2fbc: 0x000c, 0x2fbd: 0x000c, 0x2fbe: 0x000c, 0x2fbf: 0x000c,
+ // Block 0xbf, offset 0x2fc0
+ 0x2fc0: 0x000c, 0x2fc1: 0x000c, 0x2fc2: 0x000c, 0x2fc5: 0x000c,
+ 0x2fc6: 0x000c, 0x2fc7: 0x000c, 0x2fc8: 0x000c, 0x2fc9: 0x000c, 0x2fca: 0x000c, 0x2fcb: 0x000c,
+ 0x2fea: 0x000c, 0x2feb: 0x000c, 0x2fec: 0x000c, 0x2fed: 0x000c,
+ // Block 0xc0, offset 0x3000
+ 0x3000: 0x000a, 0x3001: 0x000a, 0x3002: 0x000c, 0x3003: 0x000c, 0x3004: 0x000c, 0x3005: 0x000a,
+ // Block 0xc1, offset 0x3040
+ 0x3040: 0x000a, 0x3041: 0x000a, 0x3042: 0x000a, 0x3043: 0x000a, 0x3044: 0x000a, 0x3045: 0x000a,
+ 0x3046: 0x000a, 0x3047: 0x000a, 0x3048: 0x000a, 0x3049: 0x000a, 0x304a: 0x000a, 0x304b: 0x000a,
+ 0x304c: 0x000a, 0x304d: 0x000a, 0x304e: 0x000a, 0x304f: 0x000a, 0x3050: 0x000a, 0x3051: 0x000a,
+ 0x3052: 0x000a, 0x3053: 0x000a, 0x3054: 0x000a, 0x3055: 0x000a, 0x3056: 0x000a,
+ // Block 0xc2, offset 0x3080
+ 0x309b: 0x000a,
+ // Block 0xc3, offset 0x30c0
+ 0x30d5: 0x000a,
+ // Block 0xc4, offset 0x3100
+ 0x310f: 0x000a,
+ // Block 0xc5, offset 0x3140
+ 0x3149: 0x000a,
+ // Block 0xc6, offset 0x3180
+ 0x3183: 0x000a,
+ 0x318e: 0x0002, 0x318f: 0x0002, 0x3190: 0x0002, 0x3191: 0x0002,
+ 0x3192: 0x0002, 0x3193: 0x0002, 0x3194: 0x0002, 0x3195: 0x0002, 0x3196: 0x0002, 0x3197: 0x0002,
+ 0x3198: 0x0002, 0x3199: 0x0002, 0x319a: 0x0002, 0x319b: 0x0002, 0x319c: 0x0002, 0x319d: 0x0002,
+ 0x319e: 0x0002, 0x319f: 0x0002, 0x31a0: 0x0002, 0x31a1: 0x0002, 0x31a2: 0x0002, 0x31a3: 0x0002,
+ 0x31a4: 0x0002, 0x31a5: 0x0002, 0x31a6: 0x0002, 0x31a7: 0x0002, 0x31a8: 0x0002, 0x31a9: 0x0002,
+ 0x31aa: 0x0002, 0x31ab: 0x0002, 0x31ac: 0x0002, 0x31ad: 0x0002, 0x31ae: 0x0002, 0x31af: 0x0002,
+ 0x31b0: 0x0002, 0x31b1: 0x0002, 0x31b2: 0x0002, 0x31b3: 0x0002, 0x31b4: 0x0002, 0x31b5: 0x0002,
+ 0x31b6: 0x0002, 0x31b7: 0x0002, 0x31b8: 0x0002, 0x31b9: 0x0002, 0x31ba: 0x0002, 0x31bb: 0x0002,
+ 0x31bc: 0x0002, 0x31bd: 0x0002, 0x31be: 0x0002, 0x31bf: 0x0002,
+ // Block 0xc7, offset 0x31c0
+ 0x31c0: 0x000c, 0x31c1: 0x000c, 0x31c2: 0x000c, 0x31c3: 0x000c, 0x31c4: 0x000c, 0x31c5: 0x000c,
+ 0x31c6: 0x000c, 0x31c7: 0x000c, 0x31c8: 0x000c, 0x31c9: 0x000c, 0x31ca: 0x000c, 0x31cb: 0x000c,
+ 0x31cc: 0x000c, 0x31cd: 0x000c, 0x31ce: 0x000c, 0x31cf: 0x000c, 0x31d0: 0x000c, 0x31d1: 0x000c,
+ 0x31d2: 0x000c, 0x31d3: 0x000c, 0x31d4: 0x000c, 0x31d5: 0x000c, 0x31d6: 0x000c, 0x31d7: 0x000c,
+ 0x31d8: 0x000c, 0x31d9: 0x000c, 0x31da: 0x000c, 0x31db: 0x000c, 0x31dc: 0x000c, 0x31dd: 0x000c,
+ 0x31de: 0x000c, 0x31df: 0x000c, 0x31e0: 0x000c, 0x31e1: 0x000c, 0x31e2: 0x000c, 0x31e3: 0x000c,
+ 0x31e4: 0x000c, 0x31e5: 0x000c, 0x31e6: 0x000c, 0x31e7: 0x000c, 0x31e8: 0x000c, 0x31e9: 0x000c,
+ 0x31ea: 0x000c, 0x31eb: 0x000c, 0x31ec: 0x000c, 0x31ed: 0x000c, 0x31ee: 0x000c, 0x31ef: 0x000c,
+ 0x31f0: 0x000c, 0x31f1: 0x000c, 0x31f2: 0x000c, 0x31f3: 0x000c, 0x31f4: 0x000c, 0x31f5: 0x000c,
+ 0x31f6: 0x000c, 0x31fb: 0x000c,
+ 0x31fc: 0x000c, 0x31fd: 0x000c, 0x31fe: 0x000c, 0x31ff: 0x000c,
+ // Block 0xc8, offset 0x3200
+ 0x3200: 0x000c, 0x3201: 0x000c, 0x3202: 0x000c, 0x3203: 0x000c, 0x3204: 0x000c, 0x3205: 0x000c,
+ 0x3206: 0x000c, 0x3207: 0x000c, 0x3208: 0x000c, 0x3209: 0x000c, 0x320a: 0x000c, 0x320b: 0x000c,
+ 0x320c: 0x000c, 0x320d: 0x000c, 0x320e: 0x000c, 0x320f: 0x000c, 0x3210: 0x000c, 0x3211: 0x000c,
+ 0x3212: 0x000c, 0x3213: 0x000c, 0x3214: 0x000c, 0x3215: 0x000c, 0x3216: 0x000c, 0x3217: 0x000c,
+ 0x3218: 0x000c, 0x3219: 0x000c, 0x321a: 0x000c, 0x321b: 0x000c, 0x321c: 0x000c, 0x321d: 0x000c,
+ 0x321e: 0x000c, 0x321f: 0x000c, 0x3220: 0x000c, 0x3221: 0x000c, 0x3222: 0x000c, 0x3223: 0x000c,
+ 0x3224: 0x000c, 0x3225: 0x000c, 0x3226: 0x000c, 0x3227: 0x000c, 0x3228: 0x000c, 0x3229: 0x000c,
+ 0x322a: 0x000c, 0x322b: 0x000c, 0x322c: 0x000c,
+ 0x3235: 0x000c,
+ // Block 0xc9, offset 0x3240
+ 0x3244: 0x000c,
+ 0x325b: 0x000c, 0x325c: 0x000c, 0x325d: 0x000c,
+ 0x325e: 0x000c, 0x325f: 0x000c, 0x3261: 0x000c, 0x3262: 0x000c, 0x3263: 0x000c,
+ 0x3264: 0x000c, 0x3265: 0x000c, 0x3266: 0x000c, 0x3267: 0x000c, 0x3268: 0x000c, 0x3269: 0x000c,
+ 0x326a: 0x000c, 0x326b: 0x000c, 0x326c: 0x000c, 0x326d: 0x000c, 0x326e: 0x000c, 0x326f: 0x000c,
+ // Block 0xca, offset 0x3280
+ 0x3280: 0x000c, 0x3281: 0x000c, 0x3282: 0x000c, 0x3283: 0x000c, 0x3284: 0x000c, 0x3285: 0x000c,
+ 0x3286: 0x000c, 0x3288: 0x000c, 0x3289: 0x000c, 0x328a: 0x000c, 0x328b: 0x000c,
+ 0x328c: 0x000c, 0x328d: 0x000c, 0x328e: 0x000c, 0x328f: 0x000c, 0x3290: 0x000c, 0x3291: 0x000c,
+ 0x3292: 0x000c, 0x3293: 0x000c, 0x3294: 0x000c, 0x3295: 0x000c, 0x3296: 0x000c, 0x3297: 0x000c,
+ 0x3298: 0x000c, 0x329b: 0x000c, 0x329c: 0x000c, 0x329d: 0x000c,
+ 0x329e: 0x000c, 0x329f: 0x000c, 0x32a0: 0x000c, 0x32a1: 0x000c, 0x32a3: 0x000c,
+ 0x32a4: 0x000c, 0x32a6: 0x000c, 0x32a7: 0x000c, 0x32a8: 0x000c, 0x32a9: 0x000c,
+ 0x32aa: 0x000c,
+ // Block 0xcb, offset 0x32c0
+ 0x32c0: 0x0001, 0x32c1: 0x0001, 0x32c2: 0x0001, 0x32c3: 0x0001, 0x32c4: 0x0001, 0x32c5: 0x0001,
+ 0x32c6: 0x0001, 0x32c7: 0x0001, 0x32c8: 0x0001, 0x32c9: 0x0001, 0x32ca: 0x0001, 0x32cb: 0x0001,
+ 0x32cc: 0x0001, 0x32cd: 0x0001, 0x32ce: 0x0001, 0x32cf: 0x0001, 0x32d0: 0x000c, 0x32d1: 0x000c,
+ 0x32d2: 0x000c, 0x32d3: 0x000c, 0x32d4: 0x000c, 0x32d5: 0x000c, 0x32d6: 0x000c, 0x32d7: 0x0001,
+ 0x32d8: 0x0001, 0x32d9: 0x0001, 0x32da: 0x0001, 0x32db: 0x0001, 0x32dc: 0x0001, 0x32dd: 0x0001,
+ 0x32de: 0x0001, 0x32df: 0x0001, 0x32e0: 0x0001, 0x32e1: 0x0001, 0x32e2: 0x0001, 0x32e3: 0x0001,
+ 0x32e4: 0x0001, 0x32e5: 0x0001, 0x32e6: 0x0001, 0x32e7: 0x0001, 0x32e8: 0x0001, 0x32e9: 0x0001,
+ 0x32ea: 0x0001, 0x32eb: 0x0001, 0x32ec: 0x0001, 0x32ed: 0x0001, 0x32ee: 0x0001, 0x32ef: 0x0001,
+ 0x32f0: 0x0001, 0x32f1: 0x0001, 0x32f2: 0x0001, 0x32f3: 0x0001, 0x32f4: 0x0001, 0x32f5: 0x0001,
+ 0x32f6: 0x0001, 0x32f7: 0x0001, 0x32f8: 0x0001, 0x32f9: 0x0001, 0x32fa: 0x0001, 0x32fb: 0x0001,
+ 0x32fc: 0x0001, 0x32fd: 0x0001, 0x32fe: 0x0001, 0x32ff: 0x0001,
+ // Block 0xcc, offset 0x3300
+ 0x3300: 0x0001, 0x3301: 0x0001, 0x3302: 0x0001, 0x3303: 0x0001, 0x3304: 0x000c, 0x3305: 0x000c,
+ 0x3306: 0x000c, 0x3307: 0x000c, 0x3308: 0x000c, 0x3309: 0x000c, 0x330a: 0x000c, 0x330b: 0x0001,
+ 0x330c: 0x0001, 0x330d: 0x0001, 0x330e: 0x0001, 0x330f: 0x0001, 0x3310: 0x0001, 0x3311: 0x0001,
+ 0x3312: 0x0001, 0x3313: 0x0001, 0x3314: 0x0001, 0x3315: 0x0001, 0x3316: 0x0001, 0x3317: 0x0001,
+ 0x3318: 0x0001, 0x3319: 0x0001, 0x331a: 0x0001, 0x331b: 0x0001, 0x331c: 0x0001, 0x331d: 0x0001,
+ 0x331e: 0x0001, 0x331f: 0x0001, 0x3320: 0x0001, 0x3321: 0x0001, 0x3322: 0x0001, 0x3323: 0x0001,
+ 0x3324: 0x0001, 0x3325: 0x0001, 0x3326: 0x0001, 0x3327: 0x0001, 0x3328: 0x0001, 0x3329: 0x0001,
+ 0x332a: 0x0001, 0x332b: 0x0001, 0x332c: 0x0001, 0x332d: 0x0001, 0x332e: 0x0001, 0x332f: 0x0001,
+ 0x3330: 0x0001, 0x3331: 0x0001, 0x3332: 0x0001, 0x3333: 0x0001, 0x3334: 0x0001, 0x3335: 0x0001,
+ 0x3336: 0x0001, 0x3337: 0x0001, 0x3338: 0x0001, 0x3339: 0x0001, 0x333a: 0x0001, 0x333b: 0x0001,
+ 0x333c: 0x0001, 0x333d: 0x0001, 0x333e: 0x0001, 0x333f: 0x0001,
+ // Block 0xcd, offset 0x3340
+ 0x3340: 0x000d, 0x3341: 0x000d, 0x3342: 0x000d, 0x3343: 0x000d, 0x3344: 0x000d, 0x3345: 0x000d,
+ 0x3346: 0x000d, 0x3347: 0x000d, 0x3348: 0x000d, 0x3349: 0x000d, 0x334a: 0x000d, 0x334b: 0x000d,
+ 0x334c: 0x000d, 0x334d: 0x000d, 0x334e: 0x000d, 0x334f: 0x000d, 0x3350: 0x000d, 0x3351: 0x000d,
+ 0x3352: 0x000d, 0x3353: 0x000d, 0x3354: 0x000d, 0x3355: 0x000d, 0x3356: 0x000d, 0x3357: 0x000d,
+ 0x3358: 0x000d, 0x3359: 0x000d, 0x335a: 0x000d, 0x335b: 0x000d, 0x335c: 0x000d, 0x335d: 0x000d,
+ 0x335e: 0x000d, 0x335f: 0x000d, 0x3360: 0x000d, 0x3361: 0x000d, 0x3362: 0x000d, 0x3363: 0x000d,
+ 0x3364: 0x000d, 0x3365: 0x000d, 0x3366: 0x000d, 0x3367: 0x000d, 0x3368: 0x000d, 0x3369: 0x000d,
+ 0x336a: 0x000d, 0x336b: 0x000d, 0x336c: 0x000d, 0x336d: 0x000d, 0x336e: 0x000d, 0x336f: 0x000d,
+ 0x3370: 0x000a, 0x3371: 0x000a, 0x3372: 0x000d, 0x3373: 0x000d, 0x3374: 0x000d, 0x3375: 0x000d,
+ 0x3376: 0x000d, 0x3377: 0x000d, 0x3378: 0x000d, 0x3379: 0x000d, 0x337a: 0x000d, 0x337b: 0x000d,
+ 0x337c: 0x000d, 0x337d: 0x000d, 0x337e: 0x000d, 0x337f: 0x000d,
+ // Block 0xce, offset 0x3380
+ 0x3380: 0x000a, 0x3381: 0x000a, 0x3382: 0x000a, 0x3383: 0x000a, 0x3384: 0x000a, 0x3385: 0x000a,
+ 0x3386: 0x000a, 0x3387: 0x000a, 0x3388: 0x000a, 0x3389: 0x000a, 0x338a: 0x000a, 0x338b: 0x000a,
+ 0x338c: 0x000a, 0x338d: 0x000a, 0x338e: 0x000a, 0x338f: 0x000a, 0x3390: 0x000a, 0x3391: 0x000a,
+ 0x3392: 0x000a, 0x3393: 0x000a, 0x3394: 0x000a, 0x3395: 0x000a, 0x3396: 0x000a, 0x3397: 0x000a,
+ 0x3398: 0x000a, 0x3399: 0x000a, 0x339a: 0x000a, 0x339b: 0x000a, 0x339c: 0x000a, 0x339d: 0x000a,
+ 0x339e: 0x000a, 0x339f: 0x000a, 0x33a0: 0x000a, 0x33a1: 0x000a, 0x33a2: 0x000a, 0x33a3: 0x000a,
+ 0x33a4: 0x000a, 0x33a5: 0x000a, 0x33a6: 0x000a, 0x33a7: 0x000a, 0x33a8: 0x000a, 0x33a9: 0x000a,
+ 0x33aa: 0x000a, 0x33ab: 0x000a,
+ 0x33b0: 0x000a, 0x33b1: 0x000a, 0x33b2: 0x000a, 0x33b3: 0x000a, 0x33b4: 0x000a, 0x33b5: 0x000a,
+ 0x33b6: 0x000a, 0x33b7: 0x000a, 0x33b8: 0x000a, 0x33b9: 0x000a, 0x33ba: 0x000a, 0x33bb: 0x000a,
+ 0x33bc: 0x000a, 0x33bd: 0x000a, 0x33be: 0x000a, 0x33bf: 0x000a,
+ // Block 0xcf, offset 0x33c0
+ 0x33c0: 0x000a, 0x33c1: 0x000a, 0x33c2: 0x000a, 0x33c3: 0x000a, 0x33c4: 0x000a, 0x33c5: 0x000a,
+ 0x33c6: 0x000a, 0x33c7: 0x000a, 0x33c8: 0x000a, 0x33c9: 0x000a, 0x33ca: 0x000a, 0x33cb: 0x000a,
+ 0x33cc: 0x000a, 0x33cd: 0x000a, 0x33ce: 0x000a, 0x33cf: 0x000a, 0x33d0: 0x000a, 0x33d1: 0x000a,
+ 0x33d2: 0x000a, 0x33d3: 0x000a,
+ 0x33e0: 0x000a, 0x33e1: 0x000a, 0x33e2: 0x000a, 0x33e3: 0x000a,
+ 0x33e4: 0x000a, 0x33e5: 0x000a, 0x33e6: 0x000a, 0x33e7: 0x000a, 0x33e8: 0x000a, 0x33e9: 0x000a,
+ 0x33ea: 0x000a, 0x33eb: 0x000a, 0x33ec: 0x000a, 0x33ed: 0x000a, 0x33ee: 0x000a,
+ 0x33f1: 0x000a, 0x33f2: 0x000a, 0x33f3: 0x000a, 0x33f4: 0x000a, 0x33f5: 0x000a,
+ 0x33f6: 0x000a, 0x33f7: 0x000a, 0x33f8: 0x000a, 0x33f9: 0x000a, 0x33fa: 0x000a, 0x33fb: 0x000a,
+ 0x33fc: 0x000a, 0x33fd: 0x000a, 0x33fe: 0x000a, 0x33ff: 0x000a,
+ // Block 0xd0, offset 0x3400
+ 0x3401: 0x000a, 0x3402: 0x000a, 0x3403: 0x000a, 0x3404: 0x000a, 0x3405: 0x000a,
+ 0x3406: 0x000a, 0x3407: 0x000a, 0x3408: 0x000a, 0x3409: 0x000a, 0x340a: 0x000a, 0x340b: 0x000a,
+ 0x340c: 0x000a, 0x340d: 0x000a, 0x340e: 0x000a, 0x340f: 0x000a, 0x3411: 0x000a,
+ 0x3412: 0x000a, 0x3413: 0x000a, 0x3414: 0x000a, 0x3415: 0x000a, 0x3416: 0x000a, 0x3417: 0x000a,
+ 0x3418: 0x000a, 0x3419: 0x000a, 0x341a: 0x000a, 0x341b: 0x000a, 0x341c: 0x000a, 0x341d: 0x000a,
+ 0x341e: 0x000a, 0x341f: 0x000a, 0x3420: 0x000a, 0x3421: 0x000a, 0x3422: 0x000a, 0x3423: 0x000a,
+ 0x3424: 0x000a, 0x3425: 0x000a, 0x3426: 0x000a, 0x3427: 0x000a, 0x3428: 0x000a, 0x3429: 0x000a,
+ 0x342a: 0x000a, 0x342b: 0x000a, 0x342c: 0x000a, 0x342d: 0x000a, 0x342e: 0x000a, 0x342f: 0x000a,
+ 0x3430: 0x000a, 0x3431: 0x000a, 0x3432: 0x000a, 0x3433: 0x000a, 0x3434: 0x000a, 0x3435: 0x000a,
+ // Block 0xd1, offset 0x3440
+ 0x3440: 0x0002, 0x3441: 0x0002, 0x3442: 0x0002, 0x3443: 0x0002, 0x3444: 0x0002, 0x3445: 0x0002,
+ 0x3446: 0x0002, 0x3447: 0x0002, 0x3448: 0x0002, 0x3449: 0x0002, 0x344a: 0x0002, 0x344b: 0x000a,
+ 0x344c: 0x000a,
+ // Block 0xd2, offset 0x3480
+ 0x34aa: 0x000a, 0x34ab: 0x000a,
+ // Block 0xd3, offset 0x34c0
+ 0x34c0: 0x000a, 0x34c1: 0x000a, 0x34c2: 0x000a, 0x34c3: 0x000a, 0x34c4: 0x000a, 0x34c5: 0x000a,
+ 0x34c6: 0x000a, 0x34c7: 0x000a, 0x34c8: 0x000a, 0x34c9: 0x000a, 0x34ca: 0x000a, 0x34cb: 0x000a,
+ 0x34cc: 0x000a, 0x34cd: 0x000a, 0x34ce: 0x000a, 0x34cf: 0x000a, 0x34d0: 0x000a, 0x34d1: 0x000a,
+ 0x34d2: 0x000a,
+ 0x34e0: 0x000a, 0x34e1: 0x000a, 0x34e2: 0x000a, 0x34e3: 0x000a,
+ 0x34e4: 0x000a, 0x34e5: 0x000a, 0x34e6: 0x000a, 0x34e7: 0x000a, 0x34e8: 0x000a, 0x34e9: 0x000a,
+ 0x34ea: 0x000a, 0x34eb: 0x000a, 0x34ec: 0x000a,
+ 0x34f0: 0x000a, 0x34f1: 0x000a, 0x34f2: 0x000a, 0x34f3: 0x000a, 0x34f4: 0x000a, 0x34f5: 0x000a,
+ 0x34f6: 0x000a,
+ // Block 0xd4, offset 0x3500
+ 0x3500: 0x000a, 0x3501: 0x000a, 0x3502: 0x000a, 0x3503: 0x000a, 0x3504: 0x000a, 0x3505: 0x000a,
+ 0x3506: 0x000a, 0x3507: 0x000a, 0x3508: 0x000a, 0x3509: 0x000a, 0x350a: 0x000a, 0x350b: 0x000a,
+ 0x350c: 0x000a, 0x350d: 0x000a, 0x350e: 0x000a, 0x350f: 0x000a, 0x3510: 0x000a, 0x3511: 0x000a,
+ 0x3512: 0x000a, 0x3513: 0x000a, 0x3514: 0x000a,
+ // Block 0xd5, offset 0x3540
+ 0x3540: 0x000a, 0x3541: 0x000a, 0x3542: 0x000a, 0x3543: 0x000a, 0x3544: 0x000a, 0x3545: 0x000a,
+ 0x3546: 0x000a, 0x3547: 0x000a, 0x3548: 0x000a, 0x3549: 0x000a, 0x354a: 0x000a, 0x354b: 0x000a,
+ 0x3550: 0x000a, 0x3551: 0x000a,
+ 0x3552: 0x000a, 0x3553: 0x000a, 0x3554: 0x000a, 0x3555: 0x000a, 0x3556: 0x000a, 0x3557: 0x000a,
+ 0x3558: 0x000a, 0x3559: 0x000a, 0x355a: 0x000a, 0x355b: 0x000a, 0x355c: 0x000a, 0x355d: 0x000a,
+ 0x355e: 0x000a, 0x355f: 0x000a, 0x3560: 0x000a, 0x3561: 0x000a, 0x3562: 0x000a, 0x3563: 0x000a,
+ 0x3564: 0x000a, 0x3565: 0x000a, 0x3566: 0x000a, 0x3567: 0x000a, 0x3568: 0x000a, 0x3569: 0x000a,
+ 0x356a: 0x000a, 0x356b: 0x000a, 0x356c: 0x000a, 0x356d: 0x000a, 0x356e: 0x000a, 0x356f: 0x000a,
+ 0x3570: 0x000a, 0x3571: 0x000a, 0x3572: 0x000a, 0x3573: 0x000a, 0x3574: 0x000a, 0x3575: 0x000a,
+ 0x3576: 0x000a, 0x3577: 0x000a, 0x3578: 0x000a, 0x3579: 0x000a, 0x357a: 0x000a, 0x357b: 0x000a,
+ 0x357c: 0x000a, 0x357d: 0x000a, 0x357e: 0x000a, 0x357f: 0x000a,
+ // Block 0xd6, offset 0x3580
+ 0x3580: 0x000a, 0x3581: 0x000a, 0x3582: 0x000a, 0x3583: 0x000a, 0x3584: 0x000a, 0x3585: 0x000a,
+ 0x3586: 0x000a, 0x3587: 0x000a,
+ 0x3590: 0x000a, 0x3591: 0x000a,
+ 0x3592: 0x000a, 0x3593: 0x000a, 0x3594: 0x000a, 0x3595: 0x000a, 0x3596: 0x000a, 0x3597: 0x000a,
+ 0x3598: 0x000a, 0x3599: 0x000a,
+ 0x35a0: 0x000a, 0x35a1: 0x000a, 0x35a2: 0x000a, 0x35a3: 0x000a,
+ 0x35a4: 0x000a, 0x35a5: 0x000a, 0x35a6: 0x000a, 0x35a7: 0x000a, 0x35a8: 0x000a, 0x35a9: 0x000a,
+ 0x35aa: 0x000a, 0x35ab: 0x000a, 0x35ac: 0x000a, 0x35ad: 0x000a, 0x35ae: 0x000a, 0x35af: 0x000a,
+ 0x35b0: 0x000a, 0x35b1: 0x000a, 0x35b2: 0x000a, 0x35b3: 0x000a, 0x35b4: 0x000a, 0x35b5: 0x000a,
+ 0x35b6: 0x000a, 0x35b7: 0x000a, 0x35b8: 0x000a, 0x35b9: 0x000a, 0x35ba: 0x000a, 0x35bb: 0x000a,
+ 0x35bc: 0x000a, 0x35bd: 0x000a, 0x35be: 0x000a, 0x35bf: 0x000a,
+ // Block 0xd7, offset 0x35c0
+ 0x35c0: 0x000a, 0x35c1: 0x000a, 0x35c2: 0x000a, 0x35c3: 0x000a, 0x35c4: 0x000a, 0x35c5: 0x000a,
+ 0x35c6: 0x000a, 0x35c7: 0x000a,
+ 0x35d0: 0x000a, 0x35d1: 0x000a,
+ 0x35d2: 0x000a, 0x35d3: 0x000a, 0x35d4: 0x000a, 0x35d5: 0x000a, 0x35d6: 0x000a, 0x35d7: 0x000a,
+ 0x35d8: 0x000a, 0x35d9: 0x000a, 0x35da: 0x000a, 0x35db: 0x000a, 0x35dc: 0x000a, 0x35dd: 0x000a,
+ 0x35de: 0x000a, 0x35df: 0x000a, 0x35e0: 0x000a, 0x35e1: 0x000a, 0x35e2: 0x000a, 0x35e3: 0x000a,
+ 0x35e4: 0x000a, 0x35e5: 0x000a, 0x35e6: 0x000a, 0x35e7: 0x000a, 0x35e8: 0x000a, 0x35e9: 0x000a,
+ 0x35ea: 0x000a, 0x35eb: 0x000a, 0x35ec: 0x000a, 0x35ed: 0x000a,
+ // Block 0xd8, offset 0x3600
+ 0x3610: 0x000a, 0x3611: 0x000a,
+ 0x3612: 0x000a, 0x3613: 0x000a, 0x3614: 0x000a, 0x3615: 0x000a, 0x3616: 0x000a, 0x3617: 0x000a,
+ 0x3618: 0x000a, 0x3619: 0x000a, 0x361a: 0x000a, 0x361b: 0x000a, 0x361c: 0x000a, 0x361d: 0x000a,
+ 0x361e: 0x000a, 0x3620: 0x000a, 0x3621: 0x000a, 0x3622: 0x000a, 0x3623: 0x000a,
+ 0x3624: 0x000a, 0x3625: 0x000a, 0x3626: 0x000a, 0x3627: 0x000a,
+ 0x3630: 0x000a, 0x3633: 0x000a, 0x3634: 0x000a, 0x3635: 0x000a,
+ 0x3636: 0x000a, 0x3637: 0x000a, 0x3638: 0x000a, 0x3639: 0x000a, 0x363a: 0x000a, 0x363b: 0x000a,
+ 0x363c: 0x000a, 0x363d: 0x000a, 0x363e: 0x000a,
+ // Block 0xd9, offset 0x3640
+ 0x3640: 0x000a, 0x3641: 0x000a, 0x3642: 0x000a, 0x3643: 0x000a, 0x3644: 0x000a, 0x3645: 0x000a,
+ 0x3646: 0x000a, 0x3647: 0x000a, 0x3648: 0x000a, 0x3649: 0x000a, 0x364a: 0x000a, 0x364b: 0x000a,
+ 0x3650: 0x000a, 0x3651: 0x000a,
+ 0x3652: 0x000a, 0x3653: 0x000a, 0x3654: 0x000a, 0x3655: 0x000a, 0x3656: 0x000a, 0x3657: 0x000a,
+ 0x3658: 0x000a, 0x3659: 0x000a, 0x365a: 0x000a, 0x365b: 0x000a, 0x365c: 0x000a, 0x365d: 0x000a,
+ 0x365e: 0x000a,
+ // Block 0xda, offset 0x3680
+ 0x3680: 0x000a, 0x3681: 0x000a, 0x3682: 0x000a, 0x3683: 0x000a, 0x3684: 0x000a, 0x3685: 0x000a,
+ 0x3686: 0x000a, 0x3687: 0x000a, 0x3688: 0x000a, 0x3689: 0x000a, 0x368a: 0x000a, 0x368b: 0x000a,
+ 0x368c: 0x000a, 0x368d: 0x000a, 0x368e: 0x000a, 0x368f: 0x000a, 0x3690: 0x000a, 0x3691: 0x000a,
+ // Block 0xdb, offset 0x36c0
+ 0x36fe: 0x000b, 0x36ff: 0x000b,
+ // Block 0xdc, offset 0x3700
+ 0x3700: 0x000b, 0x3701: 0x000b, 0x3702: 0x000b, 0x3703: 0x000b, 0x3704: 0x000b, 0x3705: 0x000b,
+ 0x3706: 0x000b, 0x3707: 0x000b, 0x3708: 0x000b, 0x3709: 0x000b, 0x370a: 0x000b, 0x370b: 0x000b,
+ 0x370c: 0x000b, 0x370d: 0x000b, 0x370e: 0x000b, 0x370f: 0x000b, 0x3710: 0x000b, 0x3711: 0x000b,
+ 0x3712: 0x000b, 0x3713: 0x000b, 0x3714: 0x000b, 0x3715: 0x000b, 0x3716: 0x000b, 0x3717: 0x000b,
+ 0x3718: 0x000b, 0x3719: 0x000b, 0x371a: 0x000b, 0x371b: 0x000b, 0x371c: 0x000b, 0x371d: 0x000b,
+ 0x371e: 0x000b, 0x371f: 0x000b, 0x3720: 0x000b, 0x3721: 0x000b, 0x3722: 0x000b, 0x3723: 0x000b,
+ 0x3724: 0x000b, 0x3725: 0x000b, 0x3726: 0x000b, 0x3727: 0x000b, 0x3728: 0x000b, 0x3729: 0x000b,
+ 0x372a: 0x000b, 0x372b: 0x000b, 0x372c: 0x000b, 0x372d: 0x000b, 0x372e: 0x000b, 0x372f: 0x000b,
+ 0x3730: 0x000b, 0x3731: 0x000b, 0x3732: 0x000b, 0x3733: 0x000b, 0x3734: 0x000b, 0x3735: 0x000b,
+ 0x3736: 0x000b, 0x3737: 0x000b, 0x3738: 0x000b, 0x3739: 0x000b, 0x373a: 0x000b, 0x373b: 0x000b,
+ 0x373c: 0x000b, 0x373d: 0x000b, 0x373e: 0x000b, 0x373f: 0x000b,
+ // Block 0xdd, offset 0x3740
+ 0x3740: 0x000c, 0x3741: 0x000c, 0x3742: 0x000c, 0x3743: 0x000c, 0x3744: 0x000c, 0x3745: 0x000c,
+ 0x3746: 0x000c, 0x3747: 0x000c, 0x3748: 0x000c, 0x3749: 0x000c, 0x374a: 0x000c, 0x374b: 0x000c,
+ 0x374c: 0x000c, 0x374d: 0x000c, 0x374e: 0x000c, 0x374f: 0x000c, 0x3750: 0x000c, 0x3751: 0x000c,
+ 0x3752: 0x000c, 0x3753: 0x000c, 0x3754: 0x000c, 0x3755: 0x000c, 0x3756: 0x000c, 0x3757: 0x000c,
+ 0x3758: 0x000c, 0x3759: 0x000c, 0x375a: 0x000c, 0x375b: 0x000c, 0x375c: 0x000c, 0x375d: 0x000c,
+ 0x375e: 0x000c, 0x375f: 0x000c, 0x3760: 0x000c, 0x3761: 0x000c, 0x3762: 0x000c, 0x3763: 0x000c,
+ 0x3764: 0x000c, 0x3765: 0x000c, 0x3766: 0x000c, 0x3767: 0x000c, 0x3768: 0x000c, 0x3769: 0x000c,
+ 0x376a: 0x000c, 0x376b: 0x000c, 0x376c: 0x000c, 0x376d: 0x000c, 0x376e: 0x000c, 0x376f: 0x000c,
+ 0x3770: 0x000b, 0x3771: 0x000b, 0x3772: 0x000b, 0x3773: 0x000b, 0x3774: 0x000b, 0x3775: 0x000b,
+ 0x3776: 0x000b, 0x3777: 0x000b, 0x3778: 0x000b, 0x3779: 0x000b, 0x377a: 0x000b, 0x377b: 0x000b,
+ 0x377c: 0x000b, 0x377d: 0x000b, 0x377e: 0x000b, 0x377f: 0x000b,
+}
+
+// bidiIndex: 24 blocks, 1536 entries, 1536 bytes
+// Block 0 is the zero block.
+var bidiIndex = [1536]uint8{
+ // Block 0x0, offset 0x0
+ // Block 0x1, offset 0x40
+ // Block 0x2, offset 0x80
+ // Block 0x3, offset 0xc0
+ 0xc2: 0x01, 0xc3: 0x02,
+ 0xca: 0x03, 0xcb: 0x04, 0xcc: 0x05, 0xcd: 0x06, 0xce: 0x07, 0xcf: 0x08,
+ 0xd2: 0x09, 0xd6: 0x0a, 0xd7: 0x0b,
+ 0xd8: 0x0c, 0xd9: 0x0d, 0xda: 0x0e, 0xdb: 0x0f, 0xdc: 0x10, 0xdd: 0x11, 0xde: 0x12, 0xdf: 0x13,
+ 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05, 0xe4: 0x06,
+ 0xea: 0x07, 0xef: 0x08,
+ 0xf0: 0x11, 0xf1: 0x12, 0xf2: 0x12, 0xf3: 0x14, 0xf4: 0x15,
+ // Block 0x4, offset 0x100
+ 0x120: 0x14, 0x121: 0x15, 0x122: 0x16, 0x123: 0x17, 0x124: 0x18, 0x125: 0x19, 0x126: 0x1a, 0x127: 0x1b,
+ 0x128: 0x1c, 0x129: 0x1d, 0x12a: 0x1c, 0x12b: 0x1e, 0x12c: 0x1f, 0x12d: 0x20, 0x12e: 0x21, 0x12f: 0x22,
+ 0x130: 0x23, 0x131: 0x24, 0x132: 0x1a, 0x133: 0x25, 0x134: 0x26, 0x135: 0x27, 0x137: 0x28,
+ 0x138: 0x29, 0x139: 0x2a, 0x13a: 0x2b, 0x13b: 0x2c, 0x13c: 0x2d, 0x13d: 0x2e, 0x13e: 0x2f, 0x13f: 0x30,
+ // Block 0x5, offset 0x140
+ 0x140: 0x31, 0x141: 0x32, 0x142: 0x33,
+ 0x14d: 0x34, 0x14e: 0x35,
+ 0x150: 0x36,
+ 0x15a: 0x37, 0x15c: 0x38, 0x15d: 0x39, 0x15e: 0x3a, 0x15f: 0x3b,
+ 0x160: 0x3c, 0x162: 0x3d, 0x164: 0x3e, 0x165: 0x3f, 0x167: 0x40,
+ 0x168: 0x41, 0x169: 0x42, 0x16a: 0x43, 0x16c: 0x44, 0x16d: 0x45, 0x16e: 0x46, 0x16f: 0x47,
+ 0x170: 0x48, 0x173: 0x49, 0x177: 0x4a,
+ 0x17e: 0x4b, 0x17f: 0x4c,
+ // Block 0x6, offset 0x180
+ 0x180: 0x4d, 0x181: 0x4e, 0x182: 0x4f, 0x183: 0x50, 0x184: 0x51, 0x185: 0x52, 0x186: 0x53, 0x187: 0x54,
+ 0x188: 0x55, 0x189: 0x54, 0x18a: 0x54, 0x18b: 0x54, 0x18c: 0x56, 0x18d: 0x57, 0x18e: 0x58, 0x18f: 0x59,
+ 0x190: 0x5a, 0x191: 0x5b, 0x192: 0x5c, 0x193: 0x5d, 0x194: 0x54, 0x195: 0x54, 0x196: 0x54, 0x197: 0x54,
+ 0x198: 0x54, 0x199: 0x54, 0x19a: 0x5e, 0x19b: 0x54, 0x19c: 0x54, 0x19d: 0x5f, 0x19e: 0x54, 0x19f: 0x60,
+ 0x1a4: 0x54, 0x1a5: 0x54, 0x1a6: 0x61, 0x1a7: 0x62,
+ 0x1a8: 0x54, 0x1a9: 0x54, 0x1aa: 0x54, 0x1ab: 0x54, 0x1ac: 0x54, 0x1ad: 0x63, 0x1ae: 0x64, 0x1af: 0x65,
+ 0x1b3: 0x66, 0x1b5: 0x67, 0x1b7: 0x68,
+ 0x1b8: 0x69, 0x1b9: 0x6a, 0x1ba: 0x6b, 0x1bb: 0x6c, 0x1bc: 0x54, 0x1bd: 0x54, 0x1be: 0x54, 0x1bf: 0x6d,
+ // Block 0x7, offset 0x1c0
+ 0x1c0: 0x6e, 0x1c2: 0x6f, 0x1c3: 0x70, 0x1c7: 0x71,
+ 0x1c8: 0x72, 0x1c9: 0x73, 0x1ca: 0x74, 0x1cb: 0x75, 0x1cd: 0x76, 0x1cf: 0x77,
+ // Block 0x8, offset 0x200
+ 0x237: 0x54,
+ // Block 0x9, offset 0x240
+ 0x252: 0x78, 0x253: 0x79,
+ 0x258: 0x7a, 0x259: 0x7b, 0x25a: 0x7c, 0x25b: 0x7d, 0x25c: 0x7e, 0x25e: 0x7f,
+ 0x260: 0x80, 0x261: 0x81, 0x263: 0x82, 0x264: 0x83, 0x265: 0x84, 0x266: 0x85, 0x267: 0x86,
+ 0x268: 0x87, 0x269: 0x88, 0x26a: 0x89, 0x26b: 0x8a, 0x26f: 0x8b,
+ // Block 0xa, offset 0x280
+ 0x2ac: 0x8c, 0x2ad: 0x8d, 0x2ae: 0x0e, 0x2af: 0x0e,
+ 0x2b0: 0x0e, 0x2b1: 0x0e, 0x2b2: 0x0e, 0x2b3: 0x0e, 0x2b4: 0x8e, 0x2b5: 0x0e, 0x2b6: 0x0e, 0x2b7: 0x8f,
+ 0x2b8: 0x90, 0x2b9: 0x91, 0x2ba: 0x0e, 0x2bb: 0x92, 0x2bc: 0x93, 0x2bd: 0x94, 0x2bf: 0x95,
+ // Block 0xb, offset 0x2c0
+ 0x2c4: 0x96, 0x2c5: 0x54, 0x2c6: 0x97, 0x2c7: 0x98,
+ 0x2cb: 0x99, 0x2cd: 0x9a,
+ 0x2e0: 0x9b, 0x2e1: 0x9b, 0x2e2: 0x9b, 0x2e3: 0x9b, 0x2e4: 0x9c, 0x2e5: 0x9b, 0x2e6: 0x9b, 0x2e7: 0x9b,
+ 0x2e8: 0x9d, 0x2e9: 0x9b, 0x2ea: 0x9b, 0x2eb: 0x9e, 0x2ec: 0x9f, 0x2ed: 0x9b, 0x2ee: 0x9b, 0x2ef: 0x9b,
+ 0x2f0: 0x9b, 0x2f1: 0x9b, 0x2f2: 0x9b, 0x2f3: 0x9b, 0x2f4: 0x9b, 0x2f5: 0x9b, 0x2f6: 0x9b, 0x2f7: 0x9b,
+ 0x2f8: 0x9b, 0x2f9: 0xa0, 0x2fa: 0x9b, 0x2fb: 0x9b, 0x2fc: 0x9b, 0x2fd: 0x9b, 0x2fe: 0x9b, 0x2ff: 0x9b,
+ // Block 0xc, offset 0x300
+ 0x300: 0xa1, 0x301: 0xa2, 0x302: 0xa3, 0x304: 0xa4, 0x305: 0xa5, 0x306: 0xa6, 0x307: 0xa7,
+ 0x308: 0xa8, 0x30b: 0xa9, 0x30c: 0xaa, 0x30d: 0xab,
+ 0x310: 0xac, 0x311: 0xad, 0x312: 0xae, 0x313: 0xaf, 0x316: 0xb0, 0x317: 0xb1,
+ 0x318: 0xb2, 0x319: 0xb3, 0x31a: 0xb4, 0x31c: 0xb5,
+ 0x330: 0xb6, 0x332: 0xb7,
+ // Block 0xd, offset 0x340
+ 0x36b: 0xb8, 0x36c: 0xb9,
+ 0x37e: 0xba,
+ // Block 0xe, offset 0x380
+ 0x3b2: 0xbb,
+ // Block 0xf, offset 0x3c0
+ 0x3c5: 0xbc, 0x3c6: 0xbd,
+ 0x3c8: 0x54, 0x3c9: 0xbe, 0x3cc: 0x54, 0x3cd: 0xbf,
+ 0x3db: 0xc0, 0x3dc: 0xc1, 0x3dd: 0xc2, 0x3de: 0xc3, 0x3df: 0xc4,
+ 0x3e8: 0xc5, 0x3e9: 0xc6, 0x3ea: 0xc7,
+ // Block 0x10, offset 0x400
+ 0x400: 0xc8,
+ 0x420: 0x9b, 0x421: 0x9b, 0x422: 0x9b, 0x423: 0xc9, 0x424: 0x9b, 0x425: 0xca, 0x426: 0x9b, 0x427: 0x9b,
+ 0x428: 0x9b, 0x429: 0x9b, 0x42a: 0x9b, 0x42b: 0x9b, 0x42c: 0x9b, 0x42d: 0x9b, 0x42e: 0x9b, 0x42f: 0x9b,
+ 0x430: 0x9b, 0x431: 0x9b, 0x432: 0x9b, 0x433: 0x9b, 0x434: 0x9b, 0x435: 0x9b, 0x436: 0x9b, 0x437: 0x9b,
+ 0x438: 0x0e, 0x439: 0x0e, 0x43a: 0x0e, 0x43b: 0xcb, 0x43c: 0x9b, 0x43d: 0x9b, 0x43e: 0x9b, 0x43f: 0x9b,
+ // Block 0x11, offset 0x440
+ 0x440: 0xcc, 0x441: 0x54, 0x442: 0xcd, 0x443: 0xce, 0x444: 0xcf, 0x445: 0xd0,
+ 0x44c: 0x54, 0x44d: 0x54, 0x44e: 0x54, 0x44f: 0x54,
+ 0x450: 0x54, 0x451: 0x54, 0x452: 0x54, 0x453: 0x54, 0x454: 0x54, 0x455: 0x54, 0x456: 0x54, 0x457: 0x54,
+ 0x458: 0x54, 0x459: 0x54, 0x45a: 0x54, 0x45b: 0xd1, 0x45c: 0x54, 0x45d: 0x6c, 0x45e: 0x54, 0x45f: 0xd2,
+ 0x460: 0xd3, 0x461: 0xd4, 0x462: 0xd5, 0x464: 0xd6, 0x465: 0xd7, 0x466: 0xd8, 0x467: 0x36,
+ 0x47f: 0xd9,
+ // Block 0x12, offset 0x480
+ 0x4bf: 0xd9,
+ // Block 0x13, offset 0x4c0
+ 0x4d0: 0x09, 0x4d1: 0x0a, 0x4d6: 0x0b,
+ 0x4db: 0x0c, 0x4dd: 0x0d, 0x4de: 0x0e, 0x4df: 0x0f,
+ 0x4ef: 0x10,
+ 0x4ff: 0x10,
+ // Block 0x14, offset 0x500
+ 0x50f: 0x10,
+ 0x51f: 0x10,
+ 0x52f: 0x10,
+ 0x53f: 0x10,
+ // Block 0x15, offset 0x540
+ 0x540: 0xda, 0x541: 0xda, 0x542: 0xda, 0x543: 0xda, 0x544: 0x05, 0x545: 0x05, 0x546: 0x05, 0x547: 0xdb,
+ 0x548: 0xda, 0x549: 0xda, 0x54a: 0xda, 0x54b: 0xda, 0x54c: 0xda, 0x54d: 0xda, 0x54e: 0xda, 0x54f: 0xda,
+ 0x550: 0xda, 0x551: 0xda, 0x552: 0xda, 0x553: 0xda, 0x554: 0xda, 0x555: 0xda, 0x556: 0xda, 0x557: 0xda,
+ 0x558: 0xda, 0x559: 0xda, 0x55a: 0xda, 0x55b: 0xda, 0x55c: 0xda, 0x55d: 0xda, 0x55e: 0xda, 0x55f: 0xda,
+ 0x560: 0xda, 0x561: 0xda, 0x562: 0xda, 0x563: 0xda, 0x564: 0xda, 0x565: 0xda, 0x566: 0xda, 0x567: 0xda,
+ 0x568: 0xda, 0x569: 0xda, 0x56a: 0xda, 0x56b: 0xda, 0x56c: 0xda, 0x56d: 0xda, 0x56e: 0xda, 0x56f: 0xda,
+ 0x570: 0xda, 0x571: 0xda, 0x572: 0xda, 0x573: 0xda, 0x574: 0xda, 0x575: 0xda, 0x576: 0xda, 0x577: 0xda,
+ 0x578: 0xda, 0x579: 0xda, 0x57a: 0xda, 0x57b: 0xda, 0x57c: 0xda, 0x57d: 0xda, 0x57e: 0xda, 0x57f: 0xda,
+ // Block 0x16, offset 0x580
+ 0x58f: 0x10,
+ 0x59f: 0x10,
+ 0x5a0: 0x13,
+ 0x5af: 0x10,
+ 0x5bf: 0x10,
+ // Block 0x17, offset 0x5c0
+ 0x5cf: 0x10,
+}
+
+// Total table size 15800 bytes (15KiB); checksum: F50EF68C
diff --git a/vendor/golang.org/x/text/unicode/bidi/trieval.go b/vendor/golang.org/x/text/unicode/bidi/trieval.go
new file mode 100644
index 0000000..bebd855
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/bidi/trieval.go
@@ -0,0 +1,60 @@
+// This file was generated by go generate; DO NOT EDIT
+
+package bidi
+
+// Class is the Unicode BiDi class. Each rune has a single class.
+type Class uint
+
+const (
+ L Class = iota // LeftToRight
+ R // RightToLeft
+ EN // EuropeanNumber
+ ES // EuropeanSeparator
+ ET // EuropeanTerminator
+ AN // ArabicNumber
+ CS // CommonSeparator
+ B // ParagraphSeparator
+ S // SegmentSeparator
+ WS // WhiteSpace
+ ON // OtherNeutral
+ BN // BoundaryNeutral
+ NSM // NonspacingMark
+ AL // ArabicLetter
+ Control // Control LRO - PDI
+
+ numClass
+
+ LRO // LeftToRightOverride
+ RLO // RightToLeftOverride
+ LRE // LeftToRightEmbedding
+ RLE // RightToLeftEmbedding
+ PDF // PopDirectionalFormat
+ LRI // LeftToRightIsolate
+ RLI // RightToLeftIsolate
+ FSI // FirstStrongIsolate
+ PDI // PopDirectionalIsolate
+
+ unknownClass = ^Class(0)
+)
+
+var controlToClass = map[rune]Class{
+ 0x202D: LRO, // LeftToRightOverride,
+ 0x202E: RLO, // RightToLeftOverride,
+ 0x202A: LRE, // LeftToRightEmbedding,
+ 0x202B: RLE, // RightToLeftEmbedding,
+ 0x202C: PDF, // PopDirectionalFormat,
+ 0x2066: LRI, // LeftToRightIsolate,
+ 0x2067: RLI, // RightToLeftIsolate,
+ 0x2068: FSI, // FirstStrongIsolate,
+ 0x2069: PDI, // PopDirectionalIsolate,
+}
+
+// A trie entry has the following bits:
+// 7..5 XOR mask for brackets
+// 4 1: Bracket open, 0: Bracket close
+// 3..0 Class type
+
+const (
+ openMask = 0x10
+ xorMaskShift = 5
+)
diff --git a/vendor/golang.org/x/text/unicode/norm/composition.go b/vendor/golang.org/x/text/unicode/norm/composition.go
new file mode 100644
index 0000000..d17b278
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/norm/composition.go
@@ -0,0 +1,514 @@
+// 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 norm
+
+import "unicode/utf8"
+
+const (
+ maxNonStarters = 30
+ // The maximum number of characters needed for a buffer is
+ // maxNonStarters + 1 for the starter + 1 for the GCJ
+ maxBufferSize = maxNonStarters + 2
+ maxNFCExpansion = 3 // NFC(0x1D160)
+ maxNFKCExpansion = 18 // NFKC(0xFDFA)
+
+ maxByteBufferSize = utf8.UTFMax * maxBufferSize // 128
+)
+
+// ssState is used for reporting the segment state after inserting a rune.
+// It is returned by streamSafe.next.
+type ssState int
+
+const (
+ // Indicates a rune was successfully added to the segment.
+ ssSuccess ssState = iota
+ // Indicates a rune starts a new segment and should not be added.
+ ssStarter
+ // Indicates a rune caused a segment overflow and a CGJ should be inserted.
+ ssOverflow
+)
+
+// streamSafe implements the policy of when a CGJ should be inserted.
+type streamSafe uint8
+
+// mkStreamSafe is a shorthand for declaring a streamSafe var and calling
+// first on it.
+func mkStreamSafe(p Properties) streamSafe {
+ return streamSafe(p.nTrailingNonStarters())
+}
+
+// first inserts the first rune of a segment.
+func (ss *streamSafe) first(p Properties) {
+ if *ss != 0 {
+ panic("!= 0")
+ }
+ *ss = streamSafe(p.nTrailingNonStarters())
+}
+
+// insert returns a ssState value to indicate whether a rune represented by p
+// can be inserted.
+func (ss *streamSafe) next(p Properties) ssState {
+ if *ss > maxNonStarters {
+ panic("streamSafe was not reset")
+ }
+ n := p.nLeadingNonStarters()
+ if *ss += streamSafe(n); *ss > maxNonStarters {
+ *ss = 0
+ return ssOverflow
+ }
+ // The Stream-Safe Text Processing prescribes that the counting can stop
+ // as soon as a starter is encountered. However, there are some starters,
+ // like Jamo V and T, that can combine with other runes, leaving their
+ // successive non-starters appended to the previous, possibly causing an
+ // overflow. We will therefore consider any rune with a non-zero nLead to
+ // be a non-starter. Note that it always hold that if nLead > 0 then
+ // nLead == nTrail.
+ if n == 0 {
+ *ss = 0
+ return ssStarter
+ }
+ return ssSuccess
+}
+
+// backwards is used for checking for overflow and segment starts
+// when traversing a string backwards. Users do not need to call first
+// for the first rune. The state of the streamSafe retains the count of
+// the non-starters loaded.
+func (ss *streamSafe) backwards(p Properties) ssState {
+ if *ss > maxNonStarters {
+ panic("streamSafe was not reset")
+ }
+ c := *ss + streamSafe(p.nTrailingNonStarters())
+ if c > maxNonStarters {
+ return ssOverflow
+ }
+ *ss = c
+ if p.nLeadingNonStarters() == 0 {
+ return ssStarter
+ }
+ return ssSuccess
+}
+
+func (ss streamSafe) isMax() bool {
+ return ss == maxNonStarters
+}
+
+// GraphemeJoiner is inserted after maxNonStarters non-starter runes.
+const GraphemeJoiner = "\u034F"
+
+// reorderBuffer is used to normalize a single segment. Characters inserted with
+// insert are decomposed and reordered based on CCC. The compose method can
+// be used to recombine characters. Note that the byte buffer does not hold
+// the UTF-8 characters in order. Only the rune array is maintained in sorted
+// order. flush writes the resulting segment to a byte array.
+type reorderBuffer struct {
+ rune [maxBufferSize]Properties // Per character info.
+ byte [maxByteBufferSize]byte // UTF-8 buffer. Referenced by runeInfo.pos.
+ nbyte uint8 // Number or bytes.
+ ss streamSafe // For limiting length of non-starter sequence.
+ nrune int // Number of runeInfos.
+ f formInfo
+
+ src input
+ nsrc int
+ tmpBytes input
+
+ out []byte
+ flushF func(*reorderBuffer) bool
+}
+
+func (rb *reorderBuffer) init(f Form, src []byte) {
+ rb.f = *formTable[f]
+ rb.src.setBytes(src)
+ rb.nsrc = len(src)
+ rb.ss = 0
+}
+
+func (rb *reorderBuffer) initString(f Form, src string) {
+ rb.f = *formTable[f]
+ rb.src.setString(src)
+ rb.nsrc = len(src)
+ rb.ss = 0
+}
+
+func (rb *reorderBuffer) setFlusher(out []byte, f func(*reorderBuffer) bool) {
+ rb.out = out
+ rb.flushF = f
+}
+
+// reset discards all characters from the buffer.
+func (rb *reorderBuffer) reset() {
+ rb.nrune = 0
+ rb.nbyte = 0
+ rb.ss = 0
+}
+
+func (rb *reorderBuffer) doFlush() bool {
+ if rb.f.composing {
+ rb.compose()
+ }
+ res := rb.flushF(rb)
+ rb.reset()
+ return res
+}
+
+// appendFlush appends the normalized segment to rb.out.
+func appendFlush(rb *reorderBuffer) bool {
+ for i := 0; i < rb.nrune; i++ {
+ start := rb.rune[i].pos
+ end := start + rb.rune[i].size
+ rb.out = append(rb.out, rb.byte[start:end]...)
+ }
+ return true
+}
+
+// flush appends the normalized segment to out and resets rb.
+func (rb *reorderBuffer) flush(out []byte) []byte {
+ for i := 0; i < rb.nrune; i++ {
+ start := rb.rune[i].pos
+ end := start + rb.rune[i].size
+ out = append(out, rb.byte[start:end]...)
+ }
+ rb.reset()
+ return out
+}
+
+// flushCopy copies the normalized segment to buf and resets rb.
+// It returns the number of bytes written to buf.
+func (rb *reorderBuffer) flushCopy(buf []byte) int {
+ p := 0
+ for i := 0; i < rb.nrune; i++ {
+ runep := rb.rune[i]
+ p += copy(buf[p:], rb.byte[runep.pos:runep.pos+runep.size])
+ }
+ rb.reset()
+ return p
+}
+
+// insertOrdered inserts a rune in the buffer, ordered by Canonical Combining Class.
+// It returns false if the buffer is not large enough to hold the rune.
+// It is used internally by insert and insertString only.
+func (rb *reorderBuffer) insertOrdered(info Properties) {
+ n := rb.nrune
+ b := rb.rune[:]
+ cc := info.ccc
+ if cc > 0 {
+ // Find insertion position + move elements to make room.
+ for ; n > 0; n-- {
+ if b[n-1].ccc <= cc {
+ break
+ }
+ b[n] = b[n-1]
+ }
+ }
+ rb.nrune += 1
+ pos := uint8(rb.nbyte)
+ rb.nbyte += utf8.UTFMax
+ info.pos = pos
+ b[n] = info
+}
+
+// insertErr is an error code returned by insert. Using this type instead
+// of error improves performance up to 20% for many of the benchmarks.
+type insertErr int
+
+const (
+ iSuccess insertErr = -iota
+ iShortDst
+ iShortSrc
+)
+
+// insertFlush inserts the given rune in the buffer ordered by CCC.
+// If a decomposition with multiple segments are encountered, they leading
+// ones are flushed.
+// It returns a non-zero error code if the rune was not inserted.
+func (rb *reorderBuffer) insertFlush(src input, i int, info Properties) insertErr {
+ if rune := src.hangul(i); rune != 0 {
+ rb.decomposeHangul(rune)
+ return iSuccess
+ }
+ if info.hasDecomposition() {
+ return rb.insertDecomposed(info.Decomposition())
+ }
+ rb.insertSingle(src, i, info)
+ return iSuccess
+}
+
+// insertUnsafe inserts the given rune in the buffer ordered by CCC.
+// It is assumed there is sufficient space to hold the runes. It is the
+// responsibility of the caller to ensure this. This can be done by checking
+// the state returned by the streamSafe type.
+func (rb *reorderBuffer) insertUnsafe(src input, i int, info Properties) {
+ if rune := src.hangul(i); rune != 0 {
+ rb.decomposeHangul(rune)
+ }
+ if info.hasDecomposition() {
+ // TODO: inline.
+ rb.insertDecomposed(info.Decomposition())
+ } else {
+ rb.insertSingle(src, i, info)
+ }
+}
+
+// insertDecomposed inserts an entry in to the reorderBuffer for each rune
+// in dcomp. dcomp must be a sequence of decomposed UTF-8-encoded runes.
+// It flushes the buffer on each new segment start.
+func (rb *reorderBuffer) insertDecomposed(dcomp []byte) insertErr {
+ rb.tmpBytes.setBytes(dcomp)
+ for i := 0; i < len(dcomp); {
+ info := rb.f.info(rb.tmpBytes, i)
+ if info.BoundaryBefore() && rb.nrune > 0 && !rb.doFlush() {
+ return iShortDst
+ }
+ i += copy(rb.byte[rb.nbyte:], dcomp[i:i+int(info.size)])
+ rb.insertOrdered(info)
+ }
+ return iSuccess
+}
+
+// insertSingle inserts an entry in the reorderBuffer for the rune at
+// position i. info is the runeInfo for the rune at position i.
+func (rb *reorderBuffer) insertSingle(src input, i int, info Properties) {
+ src.copySlice(rb.byte[rb.nbyte:], i, i+int(info.size))
+ rb.insertOrdered(info)
+}
+
+// insertCGJ inserts a Combining Grapheme Joiner (0x034f) into rb.
+func (rb *reorderBuffer) insertCGJ() {
+ rb.insertSingle(input{str: GraphemeJoiner}, 0, Properties{size: uint8(len(GraphemeJoiner))})
+}
+
+// appendRune inserts a rune at the end of the buffer. It is used for Hangul.
+func (rb *reorderBuffer) appendRune(r rune) {
+ bn := rb.nbyte
+ sz := utf8.EncodeRune(rb.byte[bn:], rune(r))
+ rb.nbyte += utf8.UTFMax
+ rb.rune[rb.nrune] = Properties{pos: bn, size: uint8(sz)}
+ rb.nrune++
+}
+
+// assignRune sets a rune at position pos. It is used for Hangul and recomposition.
+func (rb *reorderBuffer) assignRune(pos int, r rune) {
+ bn := rb.rune[pos].pos
+ sz := utf8.EncodeRune(rb.byte[bn:], rune(r))
+ rb.rune[pos] = Properties{pos: bn, size: uint8(sz)}
+}
+
+// runeAt returns the rune at position n. It is used for Hangul and recomposition.
+func (rb *reorderBuffer) runeAt(n int) rune {
+ inf := rb.rune[n]
+ r, _ := utf8.DecodeRune(rb.byte[inf.pos : inf.pos+inf.size])
+ return r
+}
+
+// bytesAt returns the UTF-8 encoding of the rune at position n.
+// It is used for Hangul and recomposition.
+func (rb *reorderBuffer) bytesAt(n int) []byte {
+ inf := rb.rune[n]
+ return rb.byte[inf.pos : int(inf.pos)+int(inf.size)]
+}
+
+// For Hangul we combine algorithmically, instead of using tables.
+const (
+ hangulBase = 0xAC00 // UTF-8(hangulBase) -> EA B0 80
+ hangulBase0 = 0xEA
+ hangulBase1 = 0xB0
+ hangulBase2 = 0x80
+
+ hangulEnd = hangulBase + jamoLVTCount // UTF-8(0xD7A4) -> ED 9E A4
+ hangulEnd0 = 0xED
+ hangulEnd1 = 0x9E
+ hangulEnd2 = 0xA4
+
+ jamoLBase = 0x1100 // UTF-8(jamoLBase) -> E1 84 00
+ jamoLBase0 = 0xE1
+ jamoLBase1 = 0x84
+ jamoLEnd = 0x1113
+ jamoVBase = 0x1161
+ jamoVEnd = 0x1176
+ jamoTBase = 0x11A7
+ jamoTEnd = 0x11C3
+
+ jamoTCount = 28
+ jamoVCount = 21
+ jamoVTCount = 21 * 28
+ jamoLVTCount = 19 * 21 * 28
+)
+
+const hangulUTF8Size = 3
+
+func isHangul(b []byte) bool {
+ if len(b) < hangulUTF8Size {
+ return false
+ }
+ b0 := b[0]
+ if b0 < hangulBase0 {
+ return false
+ }
+ b1 := b[1]
+ switch {
+ case b0 == hangulBase0:
+ return b1 >= hangulBase1
+ case b0 < hangulEnd0:
+ return true
+ case b0 > hangulEnd0:
+ return false
+ case b1 < hangulEnd1:
+ return true
+ }
+ return b1 == hangulEnd1 && b[2] < hangulEnd2
+}
+
+func isHangulString(b string) bool {
+ if len(b) < hangulUTF8Size {
+ return false
+ }
+ b0 := b[0]
+ if b0 < hangulBase0 {
+ return false
+ }
+ b1 := b[1]
+ switch {
+ case b0 == hangulBase0:
+ return b1 >= hangulBase1
+ case b0 < hangulEnd0:
+ return true
+ case b0 > hangulEnd0:
+ return false
+ case b1 < hangulEnd1:
+ return true
+ }
+ return b1 == hangulEnd1 && b[2] < hangulEnd2
+}
+
+// Caller must ensure len(b) >= 2.
+func isJamoVT(b []byte) bool {
+ // True if (rune & 0xff00) == jamoLBase
+ return b[0] == jamoLBase0 && (b[1]&0xFC) == jamoLBase1
+}
+
+func isHangulWithoutJamoT(b []byte) bool {
+ c, _ := utf8.DecodeRune(b)
+ c -= hangulBase
+ return c < jamoLVTCount && c%jamoTCount == 0
+}
+
+// decomposeHangul writes the decomposed Hangul to buf and returns the number
+// of bytes written. len(buf) should be at least 9.
+func decomposeHangul(buf []byte, r rune) int {
+ const JamoUTF8Len = 3
+ r -= hangulBase
+ x := r % jamoTCount
+ r /= jamoTCount
+ utf8.EncodeRune(buf, jamoLBase+r/jamoVCount)
+ utf8.EncodeRune(buf[JamoUTF8Len:], jamoVBase+r%jamoVCount)
+ if x != 0 {
+ utf8.EncodeRune(buf[2*JamoUTF8Len:], jamoTBase+x)
+ return 3 * JamoUTF8Len
+ }
+ return 2 * JamoUTF8Len
+}
+
+// decomposeHangul algorithmically decomposes a Hangul rune into
+// its Jamo components.
+// See http://unicode.org/reports/tr15/#Hangul for details on decomposing Hangul.
+func (rb *reorderBuffer) decomposeHangul(r rune) {
+ r -= hangulBase
+ x := r % jamoTCount
+ r /= jamoTCount
+ rb.appendRune(jamoLBase + r/jamoVCount)
+ rb.appendRune(jamoVBase + r%jamoVCount)
+ if x != 0 {
+ rb.appendRune(jamoTBase + x)
+ }
+}
+
+// combineHangul algorithmically combines Jamo character components into Hangul.
+// See http://unicode.org/reports/tr15/#Hangul for details on combining Hangul.
+func (rb *reorderBuffer) combineHangul(s, i, k int) {
+ b := rb.rune[:]
+ bn := rb.nrune
+ for ; i < bn; i++ {
+ cccB := b[k-1].ccc
+ cccC := b[i].ccc
+ if cccB == 0 {
+ s = k - 1
+ }
+ if s != k-1 && cccB >= cccC {
+ // b[i] is blocked by greater-equal cccX below it
+ b[k] = b[i]
+ k++
+ } else {
+ l := rb.runeAt(s) // also used to compare to hangulBase
+ v := rb.runeAt(i) // also used to compare to jamoT
+ switch {
+ case jamoLBase <= l && l < jamoLEnd &&
+ jamoVBase <= v && v < jamoVEnd:
+ // 11xx plus 116x to LV
+ rb.assignRune(s, hangulBase+
+ (l-jamoLBase)*jamoVTCount+(v-jamoVBase)*jamoTCount)
+ case hangulBase <= l && l < hangulEnd &&
+ jamoTBase < v && v < jamoTEnd &&
+ ((l-hangulBase)%jamoTCount) == 0:
+ // ACxx plus 11Ax to LVT
+ rb.assignRune(s, l+v-jamoTBase)
+ default:
+ b[k] = b[i]
+ k++
+ }
+ }
+ }
+ rb.nrune = k
+}
+
+// compose recombines the runes in the buffer.
+// It should only be used to recompose a single segment, as it will not
+// handle alternations between Hangul and non-Hangul characters correctly.
+func (rb *reorderBuffer) compose() {
+ // UAX #15, section X5 , including Corrigendum #5
+ // "In any character sequence beginning with starter S, a character C is
+ // blocked from S if and only if there is some character B between S
+ // and C, and either B is a starter or it has the same or higher
+ // combining class as C."
+ bn := rb.nrune
+ if bn == 0 {
+ return
+ }
+ k := 1
+ b := rb.rune[:]
+ for s, i := 0, 1; i < bn; i++ {
+ if isJamoVT(rb.bytesAt(i)) {
+ // Redo from start in Hangul mode. Necessary to support
+ // U+320E..U+321E in NFKC mode.
+ rb.combineHangul(s, i, k)
+ return
+ }
+ ii := b[i]
+ // We can only use combineForward as a filter if we later
+ // get the info for the combined character. This is more
+ // expensive than using the filter. Using combinesBackward()
+ // is safe.
+ if ii.combinesBackward() {
+ cccB := b[k-1].ccc
+ cccC := ii.ccc
+ blocked := false // b[i] blocked by starter or greater or equal CCC?
+ if cccB == 0 {
+ s = k - 1
+ } else {
+ blocked = s != k-1 && cccB >= cccC
+ }
+ if !blocked {
+ combined := combine(rb.runeAt(s), rb.runeAt(i))
+ if combined != 0 {
+ rb.assignRune(s, combined)
+ continue
+ }
+ }
+ }
+ b[k] = b[i]
+ k++
+ }
+ rb.nrune = k
+}
diff --git a/vendor/golang.org/x/text/unicode/norm/forminfo.go b/vendor/golang.org/x/text/unicode/norm/forminfo.go
new file mode 100644
index 0000000..15a67c6
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/norm/forminfo.go
@@ -0,0 +1,256 @@
+// 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 norm
+
+// This file contains Form-specific logic and wrappers for data in tables.go.
+
+// Rune info is stored in a separate trie per composing form. A composing form
+// and its corresponding decomposing form share the same trie. Each trie maps
+// a rune to a uint16. The values take two forms. For v >= 0x8000:
+// bits
+// 15: 1 (inverse of NFD_QD bit of qcInfo)
+// 13..7: qcInfo (see below). isYesD is always true (no decompostion).
+// 6..0: ccc (compressed CCC value).
+// For v < 0x8000, the respective rune has a decomposition and v is an index
+// into a byte array of UTF-8 decomposition sequences and additional info and
+// has the form:
+// <header> <decomp_byte>* [<tccc> [<lccc>]]
+// The header contains the number of bytes in the decomposition (excluding this
+// length byte). The two most significant bits of this length byte correspond
+// to bit 5 and 4 of qcInfo (see below). The byte sequence itself starts at v+1.
+// The byte sequence is followed by a trailing and leading CCC if the values
+// for these are not zero. The value of v determines which ccc are appended
+// to the sequences. For v < firstCCC, there are none, for v >= firstCCC,
+// the sequence is followed by a trailing ccc, and for v >= firstLeadingCC
+// there is an additional leading ccc. The value of tccc itself is the
+// trailing CCC shifted left 2 bits. The two least-significant bits of tccc
+// are the number of trailing non-starters.
+
+const (
+ qcInfoMask = 0x3F // to clear all but the relevant bits in a qcInfo
+ headerLenMask = 0x3F // extract the length value from the header byte
+ headerFlagsMask = 0xC0 // extract the qcInfo bits from the header byte
+)
+
+// Properties provides access to normalization properties of a rune.
+type Properties struct {
+ pos uint8 // start position in reorderBuffer; used in composition.go
+ size uint8 // length of UTF-8 encoding of this rune
+ ccc uint8 // leading canonical combining class (ccc if not decomposition)
+ tccc uint8 // trailing canonical combining class (ccc if not decomposition)
+ nLead uint8 // number of leading non-starters.
+ flags qcInfo // quick check flags
+ index uint16
+}
+
+// functions dispatchable per form
+type lookupFunc func(b input, i int) Properties
+
+// formInfo holds Form-specific functions and tables.
+type formInfo struct {
+ form Form
+ composing, compatibility bool // form type
+ info lookupFunc
+ nextMain iterFunc
+}
+
+var formTable []*formInfo
+
+func init() {
+ formTable = make([]*formInfo, 4)
+
+ for i := range formTable {
+ f := &formInfo{}
+ formTable[i] = f
+ f.form = Form(i)
+ if Form(i) == NFKD || Form(i) == NFKC {
+ f.compatibility = true
+ f.info = lookupInfoNFKC
+ } else {
+ f.info = lookupInfoNFC
+ }
+ f.nextMain = nextDecomposed
+ if Form(i) == NFC || Form(i) == NFKC {
+ f.nextMain = nextComposed
+ f.composing = true
+ }
+ }
+}
+
+// We do not distinguish between boundaries for NFC, NFD, etc. to avoid
+// unexpected behavior for the user. For example, in NFD, there is a boundary
+// after 'a'. However, 'a' might combine with modifiers, so from the application's
+// perspective it is not a good boundary. We will therefore always use the
+// boundaries for the combining variants.
+
+// BoundaryBefore returns true if this rune starts a new segment and
+// cannot combine with any rune on the left.
+func (p Properties) BoundaryBefore() bool {
+ if p.ccc == 0 && !p.combinesBackward() {
+ return true
+ }
+ // We assume that the CCC of the first character in a decomposition
+ // is always non-zero if different from info.ccc and that we can return
+ // false at this point. This is verified by maketables.
+ return false
+}
+
+// BoundaryAfter returns true if runes cannot combine with or otherwise
+// interact with this or previous runes.
+func (p Properties) BoundaryAfter() bool {
+ // TODO: loosen these conditions.
+ return p.isInert()
+}
+
+// We pack quick check data in 4 bits:
+// 5: Combines forward (0 == false, 1 == true)
+// 4..3: NFC_QC Yes(00), No (10), or Maybe (11)
+// 2: NFD_QC Yes (0) or No (1). No also means there is a decomposition.
+// 1..0: Number of trailing non-starters.
+//
+// When all 4 bits are zero, the character is inert, meaning it is never
+// influenced by normalization.
+type qcInfo uint8
+
+func (p Properties) isYesC() bool { return p.flags&0x10 == 0 }
+func (p Properties) isYesD() bool { return p.flags&0x4 == 0 }
+
+func (p Properties) combinesForward() bool { return p.flags&0x20 != 0 }
+func (p Properties) combinesBackward() bool { return p.flags&0x8 != 0 } // == isMaybe
+func (p Properties) hasDecomposition() bool { return p.flags&0x4 != 0 } // == isNoD
+
+func (p Properties) isInert() bool {
+ return p.flags&qcInfoMask == 0 && p.ccc == 0
+}
+
+func (p Properties) multiSegment() bool {
+ return p.index >= firstMulti && p.index < endMulti
+}
+
+func (p Properties) nLeadingNonStarters() uint8 {
+ return p.nLead
+}
+
+func (p Properties) nTrailingNonStarters() uint8 {
+ return uint8(p.flags & 0x03)
+}
+
+// Decomposition returns the decomposition for the underlying rune
+// or nil if there is none.
+func (p Properties) Decomposition() []byte {
+ // TODO: create the decomposition for Hangul?
+ if p.index == 0 {
+ return nil
+ }
+ i := p.index
+ n := decomps[i] & headerLenMask
+ i++
+ return decomps[i : i+uint16(n)]
+}
+
+// Size returns the length of UTF-8 encoding of the rune.
+func (p Properties) Size() int {
+ return int(p.size)
+}
+
+// CCC returns the canonical combining class of the underlying rune.
+func (p Properties) CCC() uint8 {
+ if p.index >= firstCCCZeroExcept {
+ return 0
+ }
+ return ccc[p.ccc]
+}
+
+// LeadCCC returns the CCC of the first rune in the decomposition.
+// If there is no decomposition, LeadCCC equals CCC.
+func (p Properties) LeadCCC() uint8 {
+ return ccc[p.ccc]
+}
+
+// TrailCCC returns the CCC of the last rune in the decomposition.
+// If there is no decomposition, TrailCCC equals CCC.
+func (p Properties) TrailCCC() uint8 {
+ return ccc[p.tccc]
+}
+
+// Recomposition
+// We use 32-bit keys instead of 64-bit for the two codepoint keys.
+// This clips off the bits of three entries, but we know this will not
+// result in a collision. In the unlikely event that changes to
+// UnicodeData.txt introduce collisions, the compiler will catch it.
+// Note that the recomposition map for NFC and NFKC are identical.
+
+// combine returns the combined rune or 0 if it doesn't exist.
+func combine(a, b rune) rune {
+ key := uint32(uint16(a))<<16 + uint32(uint16(b))
+ return recompMap[key]
+}
+
+func lookupInfoNFC(b input, i int) Properties {
+ v, sz := b.charinfoNFC(i)
+ return compInfo(v, sz)
+}
+
+func lookupInfoNFKC(b input, i int) Properties {
+ v, sz := b.charinfoNFKC(i)
+ return compInfo(v, sz)
+}
+
+// Properties returns properties for the first rune in s.
+func (f Form) Properties(s []byte) Properties {
+ if f == NFC || f == NFD {
+ return compInfo(nfcData.lookup(s))
+ }
+ return compInfo(nfkcData.lookup(s))
+}
+
+// PropertiesString returns properties for the first rune in s.
+func (f Form) PropertiesString(s string) Properties {
+ if f == NFC || f == NFD {
+ return compInfo(nfcData.lookupString(s))
+ }
+ return compInfo(nfkcData.lookupString(s))
+}
+
+// compInfo converts the information contained in v and sz
+// to a Properties. See the comment at the top of the file
+// for more information on the format.
+func compInfo(v uint16, sz int) Properties {
+ if v == 0 {
+ return Properties{size: uint8(sz)}
+ } else if v >= 0x8000 {
+ p := Properties{
+ size: uint8(sz),
+ ccc: uint8(v),
+ tccc: uint8(v),
+ flags: qcInfo(v >> 8),
+ }
+ if p.ccc > 0 || p.combinesBackward() {
+ p.nLead = uint8(p.flags & 0x3)
+ }
+ return p
+ }
+ // has decomposition
+ h := decomps[v]
+ f := (qcInfo(h&headerFlagsMask) >> 2) | 0x4
+ p := Properties{size: uint8(sz), flags: f, index: v}
+ if v >= firstCCC {
+ v += uint16(h&headerLenMask) + 1
+ c := decomps[v]
+ p.tccc = c >> 2
+ p.flags |= qcInfo(c & 0x3)
+ if v >= firstLeadingCCC {
+ p.nLead = c & 0x3
+ if v >= firstStarterWithNLead {
+ // We were tricked. Remove the decomposition.
+ p.flags &= 0x03
+ p.index = 0
+ return p
+ }
+ p.ccc = decomps[v+1]
+ }
+ }
+ return p
+}
diff --git a/vendor/golang.org/x/text/unicode/norm/input.go b/vendor/golang.org/x/text/unicode/norm/input.go
new file mode 100644
index 0000000..045d4cc
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/norm/input.go
@@ -0,0 +1,105 @@
+// 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 norm
+
+import "unicode/utf8"
+
+type input struct {
+ str string
+ bytes []byte
+}
+
+func inputBytes(str []byte) input {
+ return input{bytes: str}
+}
+
+func inputString(str string) input {
+ return input{str: str}
+}
+
+func (in *input) setBytes(str []byte) {
+ in.str = ""
+ in.bytes = str
+}
+
+func (in *input) setString(str string) {
+ in.str = str
+ in.bytes = nil
+}
+
+func (in *input) _byte(p int) byte {
+ if in.bytes == nil {
+ return in.str[p]
+ }
+ return in.bytes[p]
+}
+
+func (in *input) skipASCII(p, max int) int {
+ if in.bytes == nil {
+ for ; p < max && in.str[p] < utf8.RuneSelf; p++ {
+ }
+ } else {
+ for ; p < max && in.bytes[p] < utf8.RuneSelf; p++ {
+ }
+ }
+ return p
+}
+
+func (in *input) skipContinuationBytes(p int) int {
+ if in.bytes == nil {
+ for ; p < len(in.str) && !utf8.RuneStart(in.str[p]); p++ {
+ }
+ } else {
+ for ; p < len(in.bytes) && !utf8.RuneStart(in.bytes[p]); p++ {
+ }
+ }
+ return p
+}
+
+func (in *input) appendSlice(buf []byte, b, e int) []byte {
+ if in.bytes != nil {
+ return append(buf, in.bytes[b:e]...)
+ }
+ for i := b; i < e; i++ {
+ buf = append(buf, in.str[i])
+ }
+ return buf
+}
+
+func (in *input) copySlice(buf []byte, b, e int) int {
+ if in.bytes == nil {
+ return copy(buf, in.str[b:e])
+ }
+ return copy(buf, in.bytes[b:e])
+}
+
+func (in *input) charinfoNFC(p int) (uint16, int) {
+ if in.bytes == nil {
+ return nfcData.lookupString(in.str[p:])
+ }
+ return nfcData.lookup(in.bytes[p:])
+}
+
+func (in *input) charinfoNFKC(p int) (uint16, int) {
+ if in.bytes == nil {
+ return nfkcData.lookupString(in.str[p:])
+ }
+ return nfkcData.lookup(in.bytes[p:])
+}
+
+func (in *input) hangul(p int) (r rune) {
+ if in.bytes == nil {
+ if !isHangulString(in.str[p:]) {
+ return 0
+ }
+ r, _ = utf8.DecodeRuneInString(in.str[p:])
+ } else {
+ if !isHangul(in.bytes[p:]) {
+ return 0
+ }
+ r, _ = utf8.DecodeRune(in.bytes[p:])
+ }
+ return r
+}
diff --git a/vendor/golang.org/x/text/unicode/norm/iter.go b/vendor/golang.org/x/text/unicode/norm/iter.go
new file mode 100644
index 0000000..0a42a72
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/norm/iter.go
@@ -0,0 +1,450 @@
+// 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 norm
+
+import (
+ "fmt"
+ "unicode/utf8"
+)
+
+// MaxSegmentSize is the maximum size of a byte buffer needed to consider any
+// sequence of starter and non-starter runes for the purpose of normalization.
+const MaxSegmentSize = maxByteBufferSize
+
+// An Iter iterates over a string or byte slice, while normalizing it
+// to a given Form.
+type Iter struct {
+ rb reorderBuffer
+ buf [maxByteBufferSize]byte
+ info Properties // first character saved from previous iteration
+ next iterFunc // implementation of next depends on form
+ asciiF iterFunc
+
+ p int // current position in input source
+ multiSeg []byte // remainder of multi-segment decomposition
+}
+
+type iterFunc func(*Iter) []byte
+
+// Init initializes i to iterate over src after normalizing it to Form f.
+func (i *Iter) Init(f Form, src []byte) {
+ i.p = 0
+ if len(src) == 0 {
+ i.setDone()
+ i.rb.nsrc = 0
+ return
+ }
+ i.multiSeg = nil
+ i.rb.init(f, src)
+ i.next = i.rb.f.nextMain
+ i.asciiF = nextASCIIBytes
+ i.info = i.rb.f.info(i.rb.src, i.p)
+}
+
+// InitString initializes i to iterate over src after normalizing it to Form f.
+func (i *Iter) InitString(f Form, src string) {
+ i.p = 0
+ if len(src) == 0 {
+ i.setDone()
+ i.rb.nsrc = 0
+ return
+ }
+ i.multiSeg = nil
+ i.rb.initString(f, src)
+ i.next = i.rb.f.nextMain
+ i.asciiF = nextASCIIString
+ i.info = i.rb.f.info(i.rb.src, i.p)
+}
+
+// Seek sets the segment to be returned by the next call to Next to start
+// at position p. It is the responsibility of the caller to set p to the
+// start of a UTF8 rune.
+func (i *Iter) Seek(offset int64, whence int) (int64, error) {
+ var abs int64
+ switch whence {
+ case 0:
+ abs = offset
+ case 1:
+ abs = int64(i.p) + offset
+ case 2:
+ abs = int64(i.rb.nsrc) + offset
+ default:
+ return 0, fmt.Errorf("norm: invalid whence")
+ }
+ if abs < 0 {
+ return 0, fmt.Errorf("norm: negative position")
+ }
+ if int(abs) >= i.rb.nsrc {
+ i.setDone()
+ return int64(i.p), nil
+ }
+ i.p = int(abs)
+ i.multiSeg = nil
+ i.next = i.rb.f.nextMain
+ i.info = i.rb.f.info(i.rb.src, i.p)
+ return abs, nil
+}
+
+// returnSlice returns a slice of the underlying input type as a byte slice.
+// If the underlying is of type []byte, it will simply return a slice.
+// If the underlying is of type string, it will copy the slice to the buffer
+// and return that.
+func (i *Iter) returnSlice(a, b int) []byte {
+ if i.rb.src.bytes == nil {
+ return i.buf[:copy(i.buf[:], i.rb.src.str[a:b])]
+ }
+ return i.rb.src.bytes[a:b]
+}
+
+// Pos returns the byte position at which the next call to Next will commence processing.
+func (i *Iter) Pos() int {
+ return i.p
+}
+
+func (i *Iter) setDone() {
+ i.next = nextDone
+ i.p = i.rb.nsrc
+}
+
+// Done returns true if there is no more input to process.
+func (i *Iter) Done() bool {
+ return i.p >= i.rb.nsrc
+}
+
+// Next returns f(i.input[i.Pos():n]), where n is a boundary of i.input.
+// For any input a and b for which f(a) == f(b), subsequent calls
+// to Next will return the same segments.
+// Modifying runes are grouped together with the preceding starter, if such a starter exists.
+// Although not guaranteed, n will typically be the smallest possible n.
+func (i *Iter) Next() []byte {
+ return i.next(i)
+}
+
+func nextASCIIBytes(i *Iter) []byte {
+ p := i.p + 1
+ if p >= i.rb.nsrc {
+ i.setDone()
+ return i.rb.src.bytes[i.p:p]
+ }
+ if i.rb.src.bytes[p] < utf8.RuneSelf {
+ p0 := i.p
+ i.p = p
+ return i.rb.src.bytes[p0:p]
+ }
+ i.info = i.rb.f.info(i.rb.src, i.p)
+ i.next = i.rb.f.nextMain
+ return i.next(i)
+}
+
+func nextASCIIString(i *Iter) []byte {
+ p := i.p + 1
+ if p >= i.rb.nsrc {
+ i.buf[0] = i.rb.src.str[i.p]
+ i.setDone()
+ return i.buf[:1]
+ }
+ if i.rb.src.str[p] < utf8.RuneSelf {
+ i.buf[0] = i.rb.src.str[i.p]
+ i.p = p
+ return i.buf[:1]
+ }
+ i.info = i.rb.f.info(i.rb.src, i.p)
+ i.next = i.rb.f.nextMain
+ return i.next(i)
+}
+
+func nextHangul(i *Iter) []byte {
+ p := i.p
+ next := p + hangulUTF8Size
+ if next >= i.rb.nsrc {
+ i.setDone()
+ } else if i.rb.src.hangul(next) == 0 {
+ i.info = i.rb.f.info(i.rb.src, i.p)
+ i.next = i.rb.f.nextMain
+ return i.next(i)
+ }
+ i.p = next
+ return i.buf[:decomposeHangul(i.buf[:], i.rb.src.hangul(p))]
+}
+
+func nextDone(i *Iter) []byte {
+ return nil
+}
+
+// nextMulti is used for iterating over multi-segment decompositions
+// for decomposing normal forms.
+func nextMulti(i *Iter) []byte {
+ j := 0
+ d := i.multiSeg
+ // skip first rune
+ for j = 1; j < len(d) && !utf8.RuneStart(d[j]); j++ {
+ }
+ for j < len(d) {
+ info := i.rb.f.info(input{bytes: d}, j)
+ if info.BoundaryBefore() {
+ i.multiSeg = d[j:]
+ return d[:j]
+ }
+ j += int(info.size)
+ }
+ // treat last segment as normal decomposition
+ i.next = i.rb.f.nextMain
+ return i.next(i)
+}
+
+// nextMultiNorm is used for iterating over multi-segment decompositions
+// for composing normal forms.
+func nextMultiNorm(i *Iter) []byte {
+ j := 0
+ d := i.multiSeg
+ for j < len(d) {
+ info := i.rb.f.info(input{bytes: d}, j)
+ if info.BoundaryBefore() {
+ i.rb.compose()
+ seg := i.buf[:i.rb.flushCopy(i.buf[:])]
+ i.rb.ss.first(info)
+ i.rb.insertUnsafe(input{bytes: d}, j, info)
+ i.multiSeg = d[j+int(info.size):]
+ return seg
+ }
+ i.rb.ss.next(info)
+ i.rb.insertUnsafe(input{bytes: d}, j, info)
+ j += int(info.size)
+ }
+ i.multiSeg = nil
+ i.next = nextComposed
+ return doNormComposed(i)
+}
+
+// nextDecomposed is the implementation of Next for forms NFD and NFKD.
+func nextDecomposed(i *Iter) (next []byte) {
+ outp := 0
+ inCopyStart, outCopyStart := i.p, 0
+ ss := mkStreamSafe(i.info)
+ for {
+ if sz := int(i.info.size); sz <= 1 {
+ p := i.p
+ i.p++ // ASCII or illegal byte. Either way, advance by 1.
+ if i.p >= i.rb.nsrc {
+ i.setDone()
+ return i.returnSlice(p, i.p)
+ } else if i.rb.src._byte(i.p) < utf8.RuneSelf {
+ i.next = i.asciiF
+ return i.returnSlice(p, i.p)
+ }
+ outp++
+ } else if d := i.info.Decomposition(); d != nil {
+ // Note: If leading CCC != 0, then len(d) == 2 and last is also non-zero.
+ // Case 1: there is a leftover to copy. In this case the decomposition
+ // must begin with a modifier and should always be appended.
+ // Case 2: no leftover. Simply return d if followed by a ccc == 0 value.
+ p := outp + len(d)
+ if outp > 0 {
+ i.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p)
+ if p > len(i.buf) {
+ return i.buf[:outp]
+ }
+ } else if i.info.multiSegment() {
+ // outp must be 0 as multi-segment decompositions always
+ // start a new segment.
+ if i.multiSeg == nil {
+ i.multiSeg = d
+ i.next = nextMulti
+ return nextMulti(i)
+ }
+ // We are in the last segment. Treat as normal decomposition.
+ d = i.multiSeg
+ i.multiSeg = nil
+ p = len(d)
+ }
+ prevCC := i.info.tccc
+ if i.p += sz; i.p >= i.rb.nsrc {
+ i.setDone()
+ i.info = Properties{} // Force BoundaryBefore to succeed.
+ } else {
+ i.info = i.rb.f.info(i.rb.src, i.p)
+ }
+ switch ss.next(i.info) {
+ case ssOverflow:
+ i.next = nextCGJDecompose
+ fallthrough
+ case ssStarter:
+ if outp > 0 {
+ copy(i.buf[outp:], d)
+ return i.buf[:p]
+ }
+ return d
+ }
+ copy(i.buf[outp:], d)
+ outp = p
+ inCopyStart, outCopyStart = i.p, outp
+ if i.info.ccc < prevCC {
+ goto doNorm
+ }
+ continue
+ } else if r := i.rb.src.hangul(i.p); r != 0 {
+ outp = decomposeHangul(i.buf[:], r)
+ i.p += hangulUTF8Size
+ inCopyStart, outCopyStart = i.p, outp
+ if i.p >= i.rb.nsrc {
+ i.setDone()
+ break
+ } else if i.rb.src.hangul(i.p) != 0 {
+ i.next = nextHangul
+ return i.buf[:outp]
+ }
+ } else {
+ p := outp + sz
+ if p > len(i.buf) {
+ break
+ }
+ outp = p
+ i.p += sz
+ }
+ if i.p >= i.rb.nsrc {
+ i.setDone()
+ break
+ }
+ prevCC := i.info.tccc
+ i.info = i.rb.f.info(i.rb.src, i.p)
+ if v := ss.next(i.info); v == ssStarter {
+ break
+ } else if v == ssOverflow {
+ i.next = nextCGJDecompose
+ break
+ }
+ if i.info.ccc < prevCC {
+ goto doNorm
+ }
+ }
+ if outCopyStart == 0 {
+ return i.returnSlice(inCopyStart, i.p)
+ } else if inCopyStart < i.p {
+ i.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p)
+ }
+ return i.buf[:outp]
+doNorm:
+ // Insert what we have decomposed so far in the reorderBuffer.
+ // As we will only reorder, there will always be enough room.
+ i.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p)
+ i.rb.insertDecomposed(i.buf[0:outp])
+ return doNormDecomposed(i)
+}
+
+func doNormDecomposed(i *Iter) []byte {
+ for {
+ if s := i.rb.ss.next(i.info); s == ssOverflow {
+ i.next = nextCGJDecompose
+ break
+ }
+ i.rb.insertUnsafe(i.rb.src, i.p, i.info)
+ if i.p += int(i.info.size); i.p >= i.rb.nsrc {
+ i.setDone()
+ break
+ }
+ i.info = i.rb.f.info(i.rb.src, i.p)
+ if i.info.ccc == 0 {
+ break
+ }
+ }
+ // new segment or too many combining characters: exit normalization
+ return i.buf[:i.rb.flushCopy(i.buf[:])]
+}
+
+func nextCGJDecompose(i *Iter) []byte {
+ i.rb.ss = 0
+ i.rb.insertCGJ()
+ i.next = nextDecomposed
+ buf := doNormDecomposed(i)
+ return buf
+}
+
+// nextComposed is the implementation of Next for forms NFC and NFKC.
+func nextComposed(i *Iter) []byte {
+ outp, startp := 0, i.p
+ var prevCC uint8
+ ss := mkStreamSafe(i.info)
+ for {
+ if !i.info.isYesC() {
+ goto doNorm
+ }
+ prevCC = i.info.tccc
+ sz := int(i.info.size)
+ if sz == 0 {
+ sz = 1 // illegal rune: copy byte-by-byte
+ }
+ p := outp + sz
+ if p > len(i.buf) {
+ break
+ }
+ outp = p
+ i.p += sz
+ if i.p >= i.rb.nsrc {
+ i.setDone()
+ break
+ } else if i.rb.src._byte(i.p) < utf8.RuneSelf {
+ i.next = i.asciiF
+ break
+ }
+ i.info = i.rb.f.info(i.rb.src, i.p)
+ if v := ss.next(i.info); v == ssStarter {
+ break
+ } else if v == ssOverflow {
+ i.next = nextCGJCompose
+ break
+ }
+ if i.info.ccc < prevCC {
+ goto doNorm
+ }
+ }
+ return i.returnSlice(startp, i.p)
+doNorm:
+ i.p = startp
+ i.info = i.rb.f.info(i.rb.src, i.p)
+ if i.info.multiSegment() {
+ d := i.info.Decomposition()
+ info := i.rb.f.info(input{bytes: d}, 0)
+ i.rb.insertUnsafe(input{bytes: d}, 0, info)
+ i.multiSeg = d[int(info.size):]
+ i.next = nextMultiNorm
+ return nextMultiNorm(i)
+ }
+ i.rb.ss.first(i.info)
+ i.rb.insertUnsafe(i.rb.src, i.p, i.info)
+ return doNormComposed(i)
+}
+
+func doNormComposed(i *Iter) []byte {
+ // First rune should already be inserted.
+ for {
+ if i.p += int(i.info.size); i.p >= i.rb.nsrc {
+ i.setDone()
+ break
+ }
+ i.info = i.rb.f.info(i.rb.src, i.p)
+ if s := i.rb.ss.next(i.info); s == ssStarter {
+ break
+ } else if s == ssOverflow {
+ i.next = nextCGJCompose
+ break
+ }
+ i.rb.insertUnsafe(i.rb.src, i.p, i.info)
+ }
+ i.rb.compose()
+ seg := i.buf[:i.rb.flushCopy(i.buf[:])]
+ return seg
+}
+
+func nextCGJCompose(i *Iter) []byte {
+ i.rb.ss = 0 // instead of first
+ i.rb.insertCGJ()
+ i.next = nextComposed
+ // Note that we treat any rune with nLeadingNonStarters > 0 as a non-starter,
+ // even if they are not. This is particularly dubious for U+FF9E and UFF9A.
+ // If we ever change that, insert a check here.
+ i.rb.ss.first(i.info)
+ i.rb.insertUnsafe(i.rb.src, i.p, i.info)
+ return doNormComposed(i)
+}
diff --git a/vendor/golang.org/x/text/unicode/norm/normalize.go b/vendor/golang.org/x/text/unicode/norm/normalize.go
new file mode 100644
index 0000000..bba8ce9
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/norm/normalize.go
@@ -0,0 +1,608 @@
+// 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.
+
+//go:generate go run maketables.go triegen.go
+//go:generate go run maketables.go triegen.go -test
+
+// Package norm contains types and functions for normalizing Unicode strings.
+package norm // import "golang.org/x/text/unicode/norm"
+
+import (
+ "unicode/utf8"
+
+ "golang.org/x/text/transform"
+)
+
+// A Form denotes a canonical representation of Unicode code points.
+// The Unicode-defined normalization and equivalence forms are:
+//
+// NFC Unicode Normalization Form C
+// NFD Unicode Normalization Form D
+// NFKC Unicode Normalization Form KC
+// NFKD Unicode Normalization Form KD
+//
+// For a Form f, this documentation uses the notation f(x) to mean
+// the bytes or string x converted to the given form.
+// A position n in x is called a boundary if conversion to the form can
+// proceed independently on both sides:
+// f(x) == append(f(x[0:n]), f(x[n:])...)
+//
+// References: http://unicode.org/reports/tr15/ and
+// http://unicode.org/notes/tn5/.
+type Form int
+
+const (
+ NFC Form = iota
+ NFD
+ NFKC
+ NFKD
+)
+
+// Bytes returns f(b). May return b if f(b) = b.
+func (f Form) Bytes(b []byte) []byte {
+ src := inputBytes(b)
+ ft := formTable[f]
+ n, ok := ft.quickSpan(src, 0, len(b), true)
+ if ok {
+ return b
+ }
+ out := make([]byte, n, len(b))
+ copy(out, b[0:n])
+ rb := reorderBuffer{f: *ft, src: src, nsrc: len(b), out: out, flushF: appendFlush}
+ return doAppendInner(&rb, n)
+}
+
+// String returns f(s).
+func (f Form) String(s string) string {
+ src := inputString(s)
+ ft := formTable[f]
+ n, ok := ft.quickSpan(src, 0, len(s), true)
+ if ok {
+ return s
+ }
+ out := make([]byte, n, len(s))
+ copy(out, s[0:n])
+ rb := reorderBuffer{f: *ft, src: src, nsrc: len(s), out: out, flushF: appendFlush}
+ return string(doAppendInner(&rb, n))
+}
+
+// IsNormal returns true if b == f(b).
+func (f Form) IsNormal(b []byte) bool {
+ src := inputBytes(b)
+ ft := formTable[f]
+ bp, ok := ft.quickSpan(src, 0, len(b), true)
+ if ok {
+ return true
+ }
+ rb := reorderBuffer{f: *ft, src: src, nsrc: len(b)}
+ rb.setFlusher(nil, cmpNormalBytes)
+ for bp < len(b) {
+ rb.out = b[bp:]
+ if bp = decomposeSegment(&rb, bp, true); bp < 0 {
+ return false
+ }
+ bp, _ = rb.f.quickSpan(rb.src, bp, len(b), true)
+ }
+ return true
+}
+
+func cmpNormalBytes(rb *reorderBuffer) bool {
+ b := rb.out
+ for i := 0; i < rb.nrune; i++ {
+ info := rb.rune[i]
+ if int(info.size) > len(b) {
+ return false
+ }
+ p := info.pos
+ pe := p + info.size
+ for ; p < pe; p++ {
+ if b[0] != rb.byte[p] {
+ return false
+ }
+ b = b[1:]
+ }
+ }
+ return true
+}
+
+// IsNormalString returns true if s == f(s).
+func (f Form) IsNormalString(s string) bool {
+ src := inputString(s)
+ ft := formTable[f]
+ bp, ok := ft.quickSpan(src, 0, len(s), true)
+ if ok {
+ return true
+ }
+ rb := reorderBuffer{f: *ft, src: src, nsrc: len(s)}
+ rb.setFlusher(nil, func(rb *reorderBuffer) bool {
+ for i := 0; i < rb.nrune; i++ {
+ info := rb.rune[i]
+ if bp+int(info.size) > len(s) {
+ return false
+ }
+ p := info.pos
+ pe := p + info.size
+ for ; p < pe; p++ {
+ if s[bp] != rb.byte[p] {
+ return false
+ }
+ bp++
+ }
+ }
+ return true
+ })
+ for bp < len(s) {
+ if bp = decomposeSegment(&rb, bp, true); bp < 0 {
+ return false
+ }
+ bp, _ = rb.f.quickSpan(rb.src, bp, len(s), true)
+ }
+ return true
+}
+
+// patchTail fixes a case where a rune may be incorrectly normalized
+// if it is followed by illegal continuation bytes. It returns the
+// patched buffer and whether the decomposition is still in progress.
+func patchTail(rb *reorderBuffer) bool {
+ info, p := lastRuneStart(&rb.f, rb.out)
+ if p == -1 || info.size == 0 {
+ return true
+ }
+ end := p + int(info.size)
+ extra := len(rb.out) - end
+ if extra > 0 {
+ // Potentially allocating memory. However, this only
+ // happens with ill-formed UTF-8.
+ x := make([]byte, 0)
+ x = append(x, rb.out[len(rb.out)-extra:]...)
+ rb.out = rb.out[:end]
+ decomposeToLastBoundary(rb)
+ rb.doFlush()
+ rb.out = append(rb.out, x...)
+ return false
+ }
+ buf := rb.out[p:]
+ rb.out = rb.out[:p]
+ decomposeToLastBoundary(rb)
+ if s := rb.ss.next(info); s == ssStarter {
+ rb.doFlush()
+ rb.ss.first(info)
+ } else if s == ssOverflow {
+ rb.doFlush()
+ rb.insertCGJ()
+ rb.ss = 0
+ }
+ rb.insertUnsafe(inputBytes(buf), 0, info)
+ return true
+}
+
+func appendQuick(rb *reorderBuffer, i int) int {
+ if rb.nsrc == i {
+ return i
+ }
+ end, _ := rb.f.quickSpan(rb.src, i, rb.nsrc, true)
+ rb.out = rb.src.appendSlice(rb.out, i, end)
+ return end
+}
+
+// Append returns f(append(out, b...)).
+// The buffer out must be nil, empty, or equal to f(out).
+func (f Form) Append(out []byte, src ...byte) []byte {
+ return f.doAppend(out, inputBytes(src), len(src))
+}
+
+func (f Form) doAppend(out []byte, src input, n int) []byte {
+ if n == 0 {
+ return out
+ }
+ ft := formTable[f]
+ // Attempt to do a quickSpan first so we can avoid initializing the reorderBuffer.
+ if len(out) == 0 {
+ p, _ := ft.quickSpan(src, 0, n, true)
+ out = src.appendSlice(out, 0, p)
+ if p == n {
+ return out
+ }
+ rb := reorderBuffer{f: *ft, src: src, nsrc: n, out: out, flushF: appendFlush}
+ return doAppendInner(&rb, p)
+ }
+ rb := reorderBuffer{f: *ft, src: src, nsrc: n}
+ return doAppend(&rb, out, 0)
+}
+
+func doAppend(rb *reorderBuffer, out []byte, p int) []byte {
+ rb.setFlusher(out, appendFlush)
+ src, n := rb.src, rb.nsrc
+ doMerge := len(out) > 0
+ if q := src.skipContinuationBytes(p); q > p {
+ // Move leading non-starters to destination.
+ rb.out = src.appendSlice(rb.out, p, q)
+ p = q
+ doMerge = patchTail(rb)
+ }
+ fd := &rb.f
+ if doMerge {
+ var info Properties
+ if p < n {
+ info = fd.info(src, p)
+ if !info.BoundaryBefore() || info.nLeadingNonStarters() > 0 {
+ if p == 0 {
+ decomposeToLastBoundary(rb)
+ }
+ p = decomposeSegment(rb, p, true)
+ }
+ }
+ if info.size == 0 {
+ rb.doFlush()
+ // Append incomplete UTF-8 encoding.
+ return src.appendSlice(rb.out, p, n)
+ }
+ if rb.nrune > 0 {
+ return doAppendInner(rb, p)
+ }
+ }
+ p = appendQuick(rb, p)
+ return doAppendInner(rb, p)
+}
+
+func doAppendInner(rb *reorderBuffer, p int) []byte {
+ for n := rb.nsrc; p < n; {
+ p = decomposeSegment(rb, p, true)
+ p = appendQuick(rb, p)
+ }
+ return rb.out
+}
+
+// AppendString returns f(append(out, []byte(s))).
+// The buffer out must be nil, empty, or equal to f(out).
+func (f Form) AppendString(out []byte, src string) []byte {
+ return f.doAppend(out, inputString(src), len(src))
+}
+
+// QuickSpan returns a boundary n such that b[0:n] == f(b[0:n]).
+// It is not guaranteed to return the largest such n.
+func (f Form) QuickSpan(b []byte) int {
+ n, _ := formTable[f].quickSpan(inputBytes(b), 0, len(b), true)
+ return n
+}
+
+// Span implements transform.SpanningTransformer. It returns a boundary n such
+// that b[0:n] == f(b[0:n]). It is not guaranteed to return the largest such n.
+func (f Form) Span(b []byte, atEOF bool) (n int, err error) {
+ n, ok := formTable[f].quickSpan(inputBytes(b), 0, len(b), atEOF)
+ if n < len(b) {
+ if !ok {
+ err = transform.ErrEndOfSpan
+ } else {
+ err = transform.ErrShortSrc
+ }
+ }
+ return n, err
+}
+
+// SpanString returns a boundary n such that s[0:n] == f(s[0:n]).
+// It is not guaranteed to return the largest such n.
+func (f Form) SpanString(s string, atEOF bool) (n int, err error) {
+ n, ok := formTable[f].quickSpan(inputString(s), 0, len(s), atEOF)
+ if n < len(s) {
+ if !ok {
+ err = transform.ErrEndOfSpan
+ } else {
+ err = transform.ErrShortSrc
+ }
+ }
+ return n, err
+}
+
+// quickSpan returns a boundary n such that src[0:n] == f(src[0:n]) and
+// whether any non-normalized parts were found. If atEOF is false, n will
+// not point past the last segment if this segment might be become
+// non-normalized by appending other runes.
+func (f *formInfo) quickSpan(src input, i, end int, atEOF bool) (n int, ok bool) {
+ var lastCC uint8
+ ss := streamSafe(0)
+ lastSegStart := i
+ for n = end; i < n; {
+ if j := src.skipASCII(i, n); i != j {
+ i = j
+ lastSegStart = i - 1
+ lastCC = 0
+ ss = 0
+ continue
+ }
+ info := f.info(src, i)
+ if info.size == 0 {
+ if atEOF {
+ // include incomplete runes
+ return n, true
+ }
+ return lastSegStart, true
+ }
+ // This block needs to be before the next, because it is possible to
+ // have an overflow for runes that are starters (e.g. with U+FF9E).
+ switch ss.next(info) {
+ case ssStarter:
+ ss.first(info)
+ lastSegStart = i
+ case ssOverflow:
+ return lastSegStart, false
+ case ssSuccess:
+ if lastCC > info.ccc {
+ return lastSegStart, false
+ }
+ }
+ if f.composing {
+ if !info.isYesC() {
+ break
+ }
+ } else {
+ if !info.isYesD() {
+ break
+ }
+ }
+ lastCC = info.ccc
+ i += int(info.size)
+ }
+ if i == n {
+ if !atEOF {
+ n = lastSegStart
+ }
+ return n, true
+ }
+ return lastSegStart, false
+}
+
+// QuickSpanString returns a boundary n such that s[0:n] == f(s[0:n]).
+// It is not guaranteed to return the largest such n.
+func (f Form) QuickSpanString(s string) int {
+ n, _ := formTable[f].quickSpan(inputString(s), 0, len(s), true)
+ return n
+}
+
+// FirstBoundary returns the position i of the first boundary in b
+// or -1 if b contains no boundary.
+func (f Form) FirstBoundary(b []byte) int {
+ return f.firstBoundary(inputBytes(b), len(b))
+}
+
+func (f Form) firstBoundary(src input, nsrc int) int {
+ i := src.skipContinuationBytes(0)
+ if i >= nsrc {
+ return -1
+ }
+ fd := formTable[f]
+ ss := streamSafe(0)
+ // We should call ss.first here, but we can't as the first rune is
+ // skipped already. This means FirstBoundary can't really determine
+ // CGJ insertion points correctly. Luckily it doesn't have to.
+ for {
+ info := fd.info(src, i)
+ if info.size == 0 {
+ return -1
+ }
+ if s := ss.next(info); s != ssSuccess {
+ return i
+ }
+ i += int(info.size)
+ if i >= nsrc {
+ if !info.BoundaryAfter() && !ss.isMax() {
+ return -1
+ }
+ return nsrc
+ }
+ }
+}
+
+// FirstBoundaryInString returns the position i of the first boundary in s
+// or -1 if s contains no boundary.
+func (f Form) FirstBoundaryInString(s string) int {
+ return f.firstBoundary(inputString(s), len(s))
+}
+
+// NextBoundary reports the index of the boundary between the first and next
+// segment in b or -1 if atEOF is false and there are not enough bytes to
+// determine this boundary.
+func (f Form) NextBoundary(b []byte, atEOF bool) int {
+ return f.nextBoundary(inputBytes(b), len(b), atEOF)
+}
+
+// NextBoundaryInString reports the index of the boundary between the first and
+// next segment in b or -1 if atEOF is false and there are not enough bytes to
+// determine this boundary.
+func (f Form) NextBoundaryInString(s string, atEOF bool) int {
+ return f.nextBoundary(inputString(s), len(s), atEOF)
+}
+
+func (f Form) nextBoundary(src input, nsrc int, atEOF bool) int {
+ if nsrc == 0 {
+ if atEOF {
+ return 0
+ }
+ return -1
+ }
+ fd := formTable[f]
+ info := fd.info(src, 0)
+ if info.size == 0 {
+ if atEOF {
+ return 1
+ }
+ return -1
+ }
+ ss := streamSafe(0)
+ ss.first(info)
+
+ for i := int(info.size); i < nsrc; i += int(info.size) {
+ info = fd.info(src, i)
+ if info.size == 0 {
+ if atEOF {
+ return i
+ }
+ return -1
+ }
+ if s := ss.next(info); s != ssSuccess {
+ return i
+ }
+ }
+ if !atEOF && !info.BoundaryAfter() && !ss.isMax() {
+ return -1
+ }
+ return nsrc
+}
+
+// LastBoundary returns the position i of the last boundary in b
+// or -1 if b contains no boundary.
+func (f Form) LastBoundary(b []byte) int {
+ return lastBoundary(formTable[f], b)
+}
+
+func lastBoundary(fd *formInfo, b []byte) int {
+ i := len(b)
+ info, p := lastRuneStart(fd, b)
+ if p == -1 {
+ return -1
+ }
+ if info.size == 0 { // ends with incomplete rune
+ if p == 0 { // starts with incomplete rune
+ return -1
+ }
+ i = p
+ info, p = lastRuneStart(fd, b[:i])
+ if p == -1 { // incomplete UTF-8 encoding or non-starter bytes without a starter
+ return i
+ }
+ }
+ if p+int(info.size) != i { // trailing non-starter bytes: illegal UTF-8
+ return i
+ }
+ if info.BoundaryAfter() {
+ return i
+ }
+ ss := streamSafe(0)
+ v := ss.backwards(info)
+ for i = p; i >= 0 && v != ssStarter; i = p {
+ info, p = lastRuneStart(fd, b[:i])
+ if v = ss.backwards(info); v == ssOverflow {
+ break
+ }
+ if p+int(info.size) != i {
+ if p == -1 { // no boundary found
+ return -1
+ }
+ return i // boundary after an illegal UTF-8 encoding
+ }
+ }
+ return i
+}
+
+// decomposeSegment scans the first segment in src into rb. It inserts 0x034f
+// (Grapheme Joiner) when it encounters a sequence of more than 30 non-starters
+// and returns the number of bytes consumed from src or iShortDst or iShortSrc.
+func decomposeSegment(rb *reorderBuffer, sp int, atEOF bool) int {
+ // Force one character to be consumed.
+ info := rb.f.info(rb.src, sp)
+ if info.size == 0 {
+ return 0
+ }
+ if rb.nrune > 0 {
+ if s := rb.ss.next(info); s == ssStarter {
+ goto end
+ } else if s == ssOverflow {
+ rb.insertCGJ()
+ goto end
+ }
+ } else {
+ rb.ss.first(info)
+ }
+ if err := rb.insertFlush(rb.src, sp, info); err != iSuccess {
+ return int(err)
+ }
+ for {
+ sp += int(info.size)
+ if sp >= rb.nsrc {
+ if !atEOF && !info.BoundaryAfter() {
+ return int(iShortSrc)
+ }
+ break
+ }
+ info = rb.f.info(rb.src, sp)
+ if info.size == 0 {
+ if !atEOF {
+ return int(iShortSrc)
+ }
+ break
+ }
+ if s := rb.ss.next(info); s == ssStarter {
+ break
+ } else if s == ssOverflow {
+ rb.insertCGJ()
+ break
+ }
+ if err := rb.insertFlush(rb.src, sp, info); err != iSuccess {
+ return int(err)
+ }
+ }
+end:
+ if !rb.doFlush() {
+ return int(iShortDst)
+ }
+ return sp
+}
+
+// lastRuneStart returns the runeInfo and position of the last
+// rune in buf or the zero runeInfo and -1 if no rune was found.
+func lastRuneStart(fd *formInfo, buf []byte) (Properties, int) {
+ p := len(buf) - 1
+ for ; p >= 0 && !utf8.RuneStart(buf[p]); p-- {
+ }
+ if p < 0 {
+ return Properties{}, -1
+ }
+ return fd.info(inputBytes(buf), p), p
+}
+
+// decomposeToLastBoundary finds an open segment at the end of the buffer
+// and scans it into rb. Returns the buffer minus the last segment.
+func decomposeToLastBoundary(rb *reorderBuffer) {
+ fd := &rb.f
+ info, i := lastRuneStart(fd, rb.out)
+ if int(info.size) != len(rb.out)-i {
+ // illegal trailing continuation bytes
+ return
+ }
+ if info.BoundaryAfter() {
+ return
+ }
+ var add [maxNonStarters + 1]Properties // stores runeInfo in reverse order
+ padd := 0
+ ss := streamSafe(0)
+ p := len(rb.out)
+ for {
+ add[padd] = info
+ v := ss.backwards(info)
+ if v == ssOverflow {
+ // Note that if we have an overflow, it the string we are appending to
+ // is not correctly normalized. In this case the behavior is undefined.
+ break
+ }
+ padd++
+ p -= int(info.size)
+ if v == ssStarter || p < 0 {
+ break
+ }
+ info, i = lastRuneStart(fd, rb.out[:p])
+ if int(info.size) != p-i {
+ break
+ }
+ }
+ rb.ss = ss
+ // Copy bytes for insertion as we may need to overwrite rb.out.
+ var buf [maxBufferSize * utf8.UTFMax]byte
+ cp := buf[:copy(buf[:], rb.out[p:])]
+ rb.out = rb.out[:p]
+ for padd--; padd >= 0; padd-- {
+ info = add[padd]
+ rb.insertUnsafe(inputBytes(cp), 0, info)
+ cp = cp[info.size:]
+ }
+}
diff --git a/vendor/golang.org/x/text/unicode/norm/readwriter.go b/vendor/golang.org/x/text/unicode/norm/readwriter.go
new file mode 100644
index 0000000..d926ee9
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/norm/readwriter.go
@@ -0,0 +1,125 @@
+// 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 norm
+
+import "io"
+
+type normWriter struct {
+ rb reorderBuffer
+ w io.Writer
+ buf []byte
+}
+
+// Write implements the standard write interface. If the last characters are
+// not at a normalization boundary, the bytes will be buffered for the next
+// write. The remaining bytes will be written on close.
+func (w *normWriter) Write(data []byte) (n int, err error) {
+ // Process data in pieces to keep w.buf size bounded.
+ const chunk = 4000
+
+ for len(data) > 0 {
+ // Normalize into w.buf.
+ m := len(data)
+ if m > chunk {
+ m = chunk
+ }
+ w.rb.src = inputBytes(data[:m])
+ w.rb.nsrc = m
+ w.buf = doAppend(&w.rb, w.buf, 0)
+ data = data[m:]
+ n += m
+
+ // Write out complete prefix, save remainder.
+ // Note that lastBoundary looks back at most 31 runes.
+ i := lastBoundary(&w.rb.f, w.buf)
+ if i == -1 {
+ i = 0
+ }
+ if i > 0 {
+ if _, err = w.w.Write(w.buf[:i]); err != nil {
+ break
+ }
+ bn := copy(w.buf, w.buf[i:])
+ w.buf = w.buf[:bn]
+ }
+ }
+ return n, err
+}
+
+// Close forces data that remains in the buffer to be written.
+func (w *normWriter) Close() error {
+ if len(w.buf) > 0 {
+ _, err := w.w.Write(w.buf)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Writer returns a new writer that implements Write(b)
+// by writing f(b) to w. The returned writer may use an
+// an internal buffer to maintain state across Write calls.
+// Calling its Close method writes any buffered data to w.
+func (f Form) Writer(w io.Writer) io.WriteCloser {
+ wr := &normWriter{rb: reorderBuffer{}, w: w}
+ wr.rb.init(f, nil)
+ return wr
+}
+
+type normReader struct {
+ rb reorderBuffer
+ r io.Reader
+ inbuf []byte
+ outbuf []byte
+ bufStart int
+ lastBoundary int
+ err error
+}
+
+// Read implements the standard read interface.
+func (r *normReader) Read(p []byte) (int, error) {
+ for {
+ if r.lastBoundary-r.bufStart > 0 {
+ n := copy(p, r.outbuf[r.bufStart:r.lastBoundary])
+ r.bufStart += n
+ if r.lastBoundary-r.bufStart > 0 {
+ return n, nil
+ }
+ return n, r.err
+ }
+ if r.err != nil {
+ return 0, r.err
+ }
+ outn := copy(r.outbuf, r.outbuf[r.lastBoundary:])
+ r.outbuf = r.outbuf[0:outn]
+ r.bufStart = 0
+
+ n, err := r.r.Read(r.inbuf)
+ r.rb.src = inputBytes(r.inbuf[0:n])
+ r.rb.nsrc, r.err = n, err
+ if n > 0 {
+ r.outbuf = doAppend(&r.rb, r.outbuf, 0)
+ }
+ if err == io.EOF {
+ r.lastBoundary = len(r.outbuf)
+ } else {
+ r.lastBoundary = lastBoundary(&r.rb.f, r.outbuf)
+ if r.lastBoundary == -1 {
+ r.lastBoundary = 0
+ }
+ }
+ }
+}
+
+// Reader returns a new reader that implements Read
+// by reading data from r and returning f(data).
+func (f Form) Reader(r io.Reader) io.Reader {
+ const chunk = 4000
+ buf := make([]byte, chunk)
+ rr := &normReader{rb: reorderBuffer{}, r: r, inbuf: buf}
+ rr.rb.init(f, buf)
+ return rr
+}
diff --git a/vendor/golang.org/x/text/unicode/norm/tables.go b/vendor/golang.org/x/text/unicode/norm/tables.go
new file mode 100644
index 0000000..a56697b
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/norm/tables.go
@@ -0,0 +1,7627 @@
+// This file was generated by go generate; DO NOT EDIT
+
+package norm
+
+const (
+ // Version is the Unicode edition from which the tables are derived.
+ Version = "9.0.0"
+
+ // MaxTransformChunkSize indicates the maximum number of bytes that Transform
+ // may need to write atomically for any Form. Making a destination buffer at
+ // least this size ensures that Transform can always make progress and that
+ // the user does not need to grow the buffer on an ErrShortDst.
+ MaxTransformChunkSize = 35 + maxNonStarters*4
+)
+
+var ccc = [55]uint8{
+ 0, 1, 7, 8, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18, 19, 20,
+ 21, 22, 23, 24, 25, 26, 27, 28,
+ 29, 30, 31, 32, 33, 34, 35, 36,
+ 84, 91, 103, 107, 118, 122, 129, 130,
+ 132, 202, 214, 216, 218, 220, 222, 224,
+ 226, 228, 230, 232, 233, 234, 240,
+}
+
+const (
+ firstMulti = 0x186D
+ firstCCC = 0x2C9E
+ endMulti = 0x2F60
+ firstLeadingCCC = 0x4A44
+ firstCCCZeroExcept = 0x4A5A
+ firstStarterWithNLead = 0x4A81
+ lastDecomp = 0x4A83
+ maxDecomp = 0x8000
+)
+
+// decomps: 19075 bytes
+var decomps = [...]byte{
+ // Bytes 0 - 3f
+ 0x00, 0x41, 0x20, 0x41, 0x21, 0x41, 0x22, 0x41,
+ 0x23, 0x41, 0x24, 0x41, 0x25, 0x41, 0x26, 0x41,
+ 0x27, 0x41, 0x28, 0x41, 0x29, 0x41, 0x2A, 0x41,
+ 0x2B, 0x41, 0x2C, 0x41, 0x2D, 0x41, 0x2E, 0x41,
+ 0x2F, 0x41, 0x30, 0x41, 0x31, 0x41, 0x32, 0x41,
+ 0x33, 0x41, 0x34, 0x41, 0x35, 0x41, 0x36, 0x41,
+ 0x37, 0x41, 0x38, 0x41, 0x39, 0x41, 0x3A, 0x41,
+ 0x3B, 0x41, 0x3C, 0x41, 0x3D, 0x41, 0x3E, 0x41,
+ // Bytes 40 - 7f
+ 0x3F, 0x41, 0x40, 0x41, 0x41, 0x41, 0x42, 0x41,
+ 0x43, 0x41, 0x44, 0x41, 0x45, 0x41, 0x46, 0x41,
+ 0x47, 0x41, 0x48, 0x41, 0x49, 0x41, 0x4A, 0x41,
+ 0x4B, 0x41, 0x4C, 0x41, 0x4D, 0x41, 0x4E, 0x41,
+ 0x4F, 0x41, 0x50, 0x41, 0x51, 0x41, 0x52, 0x41,
+ 0x53, 0x41, 0x54, 0x41, 0x55, 0x41, 0x56, 0x41,
+ 0x57, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5A, 0x41,
+ 0x5B, 0x41, 0x5C, 0x41, 0x5D, 0x41, 0x5E, 0x41,
+ // Bytes 80 - bf
+ 0x5F, 0x41, 0x60, 0x41, 0x61, 0x41, 0x62, 0x41,
+ 0x63, 0x41, 0x64, 0x41, 0x65, 0x41, 0x66, 0x41,
+ 0x67, 0x41, 0x68, 0x41, 0x69, 0x41, 0x6A, 0x41,
+ 0x6B, 0x41, 0x6C, 0x41, 0x6D, 0x41, 0x6E, 0x41,
+ 0x6F, 0x41, 0x70, 0x41, 0x71, 0x41, 0x72, 0x41,
+ 0x73, 0x41, 0x74, 0x41, 0x75, 0x41, 0x76, 0x41,
+ 0x77, 0x41, 0x78, 0x41, 0x79, 0x41, 0x7A, 0x41,
+ 0x7B, 0x41, 0x7C, 0x41, 0x7D, 0x41, 0x7E, 0x42,
+ // Bytes c0 - ff
+ 0xC2, 0xA2, 0x42, 0xC2, 0xA3, 0x42, 0xC2, 0xA5,
+ 0x42, 0xC2, 0xA6, 0x42, 0xC2, 0xAC, 0x42, 0xC2,
+ 0xB7, 0x42, 0xC3, 0x86, 0x42, 0xC3, 0xB0, 0x42,
+ 0xC4, 0xA6, 0x42, 0xC4, 0xA7, 0x42, 0xC4, 0xB1,
+ 0x42, 0xC5, 0x8B, 0x42, 0xC5, 0x93, 0x42, 0xC6,
+ 0x8E, 0x42, 0xC6, 0x90, 0x42, 0xC6, 0xAB, 0x42,
+ 0xC8, 0xA2, 0x42, 0xC8, 0xB7, 0x42, 0xC9, 0x90,
+ 0x42, 0xC9, 0x91, 0x42, 0xC9, 0x92, 0x42, 0xC9,
+ // Bytes 100 - 13f
+ 0x94, 0x42, 0xC9, 0x95, 0x42, 0xC9, 0x99, 0x42,
+ 0xC9, 0x9B, 0x42, 0xC9, 0x9C, 0x42, 0xC9, 0x9F,
+ 0x42, 0xC9, 0xA1, 0x42, 0xC9, 0xA3, 0x42, 0xC9,
+ 0xA5, 0x42, 0xC9, 0xA6, 0x42, 0xC9, 0xA8, 0x42,
+ 0xC9, 0xA9, 0x42, 0xC9, 0xAA, 0x42, 0xC9, 0xAB,
+ 0x42, 0xC9, 0xAD, 0x42, 0xC9, 0xAF, 0x42, 0xC9,
+ 0xB0, 0x42, 0xC9, 0xB1, 0x42, 0xC9, 0xB2, 0x42,
+ 0xC9, 0xB3, 0x42, 0xC9, 0xB4, 0x42, 0xC9, 0xB5,
+ // Bytes 140 - 17f
+ 0x42, 0xC9, 0xB8, 0x42, 0xC9, 0xB9, 0x42, 0xC9,
+ 0xBB, 0x42, 0xCA, 0x81, 0x42, 0xCA, 0x82, 0x42,
+ 0xCA, 0x83, 0x42, 0xCA, 0x89, 0x42, 0xCA, 0x8A,
+ 0x42, 0xCA, 0x8B, 0x42, 0xCA, 0x8C, 0x42, 0xCA,
+ 0x90, 0x42, 0xCA, 0x91, 0x42, 0xCA, 0x92, 0x42,
+ 0xCA, 0x95, 0x42, 0xCA, 0x9D, 0x42, 0xCA, 0x9F,
+ 0x42, 0xCA, 0xB9, 0x42, 0xCE, 0x91, 0x42, 0xCE,
+ 0x92, 0x42, 0xCE, 0x93, 0x42, 0xCE, 0x94, 0x42,
+ // Bytes 180 - 1bf
+ 0xCE, 0x95, 0x42, 0xCE, 0x96, 0x42, 0xCE, 0x97,
+ 0x42, 0xCE, 0x98, 0x42, 0xCE, 0x99, 0x42, 0xCE,
+ 0x9A, 0x42, 0xCE, 0x9B, 0x42, 0xCE, 0x9C, 0x42,
+ 0xCE, 0x9D, 0x42, 0xCE, 0x9E, 0x42, 0xCE, 0x9F,
+ 0x42, 0xCE, 0xA0, 0x42, 0xCE, 0xA1, 0x42, 0xCE,
+ 0xA3, 0x42, 0xCE, 0xA4, 0x42, 0xCE, 0xA5, 0x42,
+ 0xCE, 0xA6, 0x42, 0xCE, 0xA7, 0x42, 0xCE, 0xA8,
+ 0x42, 0xCE, 0xA9, 0x42, 0xCE, 0xB1, 0x42, 0xCE,
+ // Bytes 1c0 - 1ff
+ 0xB2, 0x42, 0xCE, 0xB3, 0x42, 0xCE, 0xB4, 0x42,
+ 0xCE, 0xB5, 0x42, 0xCE, 0xB6, 0x42, 0xCE, 0xB7,
+ 0x42, 0xCE, 0xB8, 0x42, 0xCE, 0xB9, 0x42, 0xCE,
+ 0xBA, 0x42, 0xCE, 0xBB, 0x42, 0xCE, 0xBC, 0x42,
+ 0xCE, 0xBD, 0x42, 0xCE, 0xBE, 0x42, 0xCE, 0xBF,
+ 0x42, 0xCF, 0x80, 0x42, 0xCF, 0x81, 0x42, 0xCF,
+ 0x82, 0x42, 0xCF, 0x83, 0x42, 0xCF, 0x84, 0x42,
+ 0xCF, 0x85, 0x42, 0xCF, 0x86, 0x42, 0xCF, 0x87,
+ // Bytes 200 - 23f
+ 0x42, 0xCF, 0x88, 0x42, 0xCF, 0x89, 0x42, 0xCF,
+ 0x9C, 0x42, 0xCF, 0x9D, 0x42, 0xD0, 0xBD, 0x42,
+ 0xD1, 0x8A, 0x42, 0xD1, 0x8C, 0x42, 0xD7, 0x90,
+ 0x42, 0xD7, 0x91, 0x42, 0xD7, 0x92, 0x42, 0xD7,
+ 0x93, 0x42, 0xD7, 0x94, 0x42, 0xD7, 0x9B, 0x42,
+ 0xD7, 0x9C, 0x42, 0xD7, 0x9D, 0x42, 0xD7, 0xA2,
+ 0x42, 0xD7, 0xA8, 0x42, 0xD7, 0xAA, 0x42, 0xD8,
+ 0xA1, 0x42, 0xD8, 0xA7, 0x42, 0xD8, 0xA8, 0x42,
+ // Bytes 240 - 27f
+ 0xD8, 0xA9, 0x42, 0xD8, 0xAA, 0x42, 0xD8, 0xAB,
+ 0x42, 0xD8, 0xAC, 0x42, 0xD8, 0xAD, 0x42, 0xD8,
+ 0xAE, 0x42, 0xD8, 0xAF, 0x42, 0xD8, 0xB0, 0x42,
+ 0xD8, 0xB1, 0x42, 0xD8, 0xB2, 0x42, 0xD8, 0xB3,
+ 0x42, 0xD8, 0xB4, 0x42, 0xD8, 0xB5, 0x42, 0xD8,
+ 0xB6, 0x42, 0xD8, 0xB7, 0x42, 0xD8, 0xB8, 0x42,
+ 0xD8, 0xB9, 0x42, 0xD8, 0xBA, 0x42, 0xD9, 0x81,
+ 0x42, 0xD9, 0x82, 0x42, 0xD9, 0x83, 0x42, 0xD9,
+ // Bytes 280 - 2bf
+ 0x84, 0x42, 0xD9, 0x85, 0x42, 0xD9, 0x86, 0x42,
+ 0xD9, 0x87, 0x42, 0xD9, 0x88, 0x42, 0xD9, 0x89,
+ 0x42, 0xD9, 0x8A, 0x42, 0xD9, 0xAE, 0x42, 0xD9,
+ 0xAF, 0x42, 0xD9, 0xB1, 0x42, 0xD9, 0xB9, 0x42,
+ 0xD9, 0xBA, 0x42, 0xD9, 0xBB, 0x42, 0xD9, 0xBE,
+ 0x42, 0xD9, 0xBF, 0x42, 0xDA, 0x80, 0x42, 0xDA,
+ 0x83, 0x42, 0xDA, 0x84, 0x42, 0xDA, 0x86, 0x42,
+ 0xDA, 0x87, 0x42, 0xDA, 0x88, 0x42, 0xDA, 0x8C,
+ // Bytes 2c0 - 2ff
+ 0x42, 0xDA, 0x8D, 0x42, 0xDA, 0x8E, 0x42, 0xDA,
+ 0x91, 0x42, 0xDA, 0x98, 0x42, 0xDA, 0xA1, 0x42,
+ 0xDA, 0xA4, 0x42, 0xDA, 0xA6, 0x42, 0xDA, 0xA9,
+ 0x42, 0xDA, 0xAD, 0x42, 0xDA, 0xAF, 0x42, 0xDA,
+ 0xB1, 0x42, 0xDA, 0xB3, 0x42, 0xDA, 0xBA, 0x42,
+ 0xDA, 0xBB, 0x42, 0xDA, 0xBE, 0x42, 0xDB, 0x81,
+ 0x42, 0xDB, 0x85, 0x42, 0xDB, 0x86, 0x42, 0xDB,
+ 0x87, 0x42, 0xDB, 0x88, 0x42, 0xDB, 0x89, 0x42,
+ // Bytes 300 - 33f
+ 0xDB, 0x8B, 0x42, 0xDB, 0x8C, 0x42, 0xDB, 0x90,
+ 0x42, 0xDB, 0x92, 0x43, 0xE0, 0xBC, 0x8B, 0x43,
+ 0xE1, 0x83, 0x9C, 0x43, 0xE1, 0x84, 0x80, 0x43,
+ 0xE1, 0x84, 0x81, 0x43, 0xE1, 0x84, 0x82, 0x43,
+ 0xE1, 0x84, 0x83, 0x43, 0xE1, 0x84, 0x84, 0x43,
+ 0xE1, 0x84, 0x85, 0x43, 0xE1, 0x84, 0x86, 0x43,
+ 0xE1, 0x84, 0x87, 0x43, 0xE1, 0x84, 0x88, 0x43,
+ 0xE1, 0x84, 0x89, 0x43, 0xE1, 0x84, 0x8A, 0x43,
+ // Bytes 340 - 37f
+ 0xE1, 0x84, 0x8B, 0x43, 0xE1, 0x84, 0x8C, 0x43,
+ 0xE1, 0x84, 0x8D, 0x43, 0xE1, 0x84, 0x8E, 0x43,
+ 0xE1, 0x84, 0x8F, 0x43, 0xE1, 0x84, 0x90, 0x43,
+ 0xE1, 0x84, 0x91, 0x43, 0xE1, 0x84, 0x92, 0x43,
+ 0xE1, 0x84, 0x94, 0x43, 0xE1, 0x84, 0x95, 0x43,
+ 0xE1, 0x84, 0x9A, 0x43, 0xE1, 0x84, 0x9C, 0x43,
+ 0xE1, 0x84, 0x9D, 0x43, 0xE1, 0x84, 0x9E, 0x43,
+ 0xE1, 0x84, 0xA0, 0x43, 0xE1, 0x84, 0xA1, 0x43,
+ // Bytes 380 - 3bf
+ 0xE1, 0x84, 0xA2, 0x43, 0xE1, 0x84, 0xA3, 0x43,
+ 0xE1, 0x84, 0xA7, 0x43, 0xE1, 0x84, 0xA9, 0x43,
+ 0xE1, 0x84, 0xAB, 0x43, 0xE1, 0x84, 0xAC, 0x43,
+ 0xE1, 0x84, 0xAD, 0x43, 0xE1, 0x84, 0xAE, 0x43,
+ 0xE1, 0x84, 0xAF, 0x43, 0xE1, 0x84, 0xB2, 0x43,
+ 0xE1, 0x84, 0xB6, 0x43, 0xE1, 0x85, 0x80, 0x43,
+ 0xE1, 0x85, 0x87, 0x43, 0xE1, 0x85, 0x8C, 0x43,
+ 0xE1, 0x85, 0x97, 0x43, 0xE1, 0x85, 0x98, 0x43,
+ // Bytes 3c0 - 3ff
+ 0xE1, 0x85, 0x99, 0x43, 0xE1, 0x85, 0xA0, 0x43,
+ 0xE1, 0x86, 0x84, 0x43, 0xE1, 0x86, 0x85, 0x43,
+ 0xE1, 0x86, 0x88, 0x43, 0xE1, 0x86, 0x91, 0x43,
+ 0xE1, 0x86, 0x92, 0x43, 0xE1, 0x86, 0x94, 0x43,
+ 0xE1, 0x86, 0x9E, 0x43, 0xE1, 0x86, 0xA1, 0x43,
+ 0xE1, 0x87, 0x87, 0x43, 0xE1, 0x87, 0x88, 0x43,
+ 0xE1, 0x87, 0x8C, 0x43, 0xE1, 0x87, 0x8E, 0x43,
+ 0xE1, 0x87, 0x93, 0x43, 0xE1, 0x87, 0x97, 0x43,
+ // Bytes 400 - 43f
+ 0xE1, 0x87, 0x99, 0x43, 0xE1, 0x87, 0x9D, 0x43,
+ 0xE1, 0x87, 0x9F, 0x43, 0xE1, 0x87, 0xB1, 0x43,
+ 0xE1, 0x87, 0xB2, 0x43, 0xE1, 0xB4, 0x82, 0x43,
+ 0xE1, 0xB4, 0x96, 0x43, 0xE1, 0xB4, 0x97, 0x43,
+ 0xE1, 0xB4, 0x9C, 0x43, 0xE1, 0xB4, 0x9D, 0x43,
+ 0xE1, 0xB4, 0xA5, 0x43, 0xE1, 0xB5, 0xBB, 0x43,
+ 0xE1, 0xB6, 0x85, 0x43, 0xE2, 0x80, 0x82, 0x43,
+ 0xE2, 0x80, 0x83, 0x43, 0xE2, 0x80, 0x90, 0x43,
+ // Bytes 440 - 47f
+ 0xE2, 0x80, 0x93, 0x43, 0xE2, 0x80, 0x94, 0x43,
+ 0xE2, 0x82, 0xA9, 0x43, 0xE2, 0x86, 0x90, 0x43,
+ 0xE2, 0x86, 0x91, 0x43, 0xE2, 0x86, 0x92, 0x43,
+ 0xE2, 0x86, 0x93, 0x43, 0xE2, 0x88, 0x82, 0x43,
+ 0xE2, 0x88, 0x87, 0x43, 0xE2, 0x88, 0x91, 0x43,
+ 0xE2, 0x88, 0x92, 0x43, 0xE2, 0x94, 0x82, 0x43,
+ 0xE2, 0x96, 0xA0, 0x43, 0xE2, 0x97, 0x8B, 0x43,
+ 0xE2, 0xA6, 0x85, 0x43, 0xE2, 0xA6, 0x86, 0x43,
+ // Bytes 480 - 4bf
+ 0xE2, 0xB5, 0xA1, 0x43, 0xE3, 0x80, 0x81, 0x43,
+ 0xE3, 0x80, 0x82, 0x43, 0xE3, 0x80, 0x88, 0x43,
+ 0xE3, 0x80, 0x89, 0x43, 0xE3, 0x80, 0x8A, 0x43,
+ 0xE3, 0x80, 0x8B, 0x43, 0xE3, 0x80, 0x8C, 0x43,
+ 0xE3, 0x80, 0x8D, 0x43, 0xE3, 0x80, 0x8E, 0x43,
+ 0xE3, 0x80, 0x8F, 0x43, 0xE3, 0x80, 0x90, 0x43,
+ 0xE3, 0x80, 0x91, 0x43, 0xE3, 0x80, 0x92, 0x43,
+ 0xE3, 0x80, 0x94, 0x43, 0xE3, 0x80, 0x95, 0x43,
+ // Bytes 4c0 - 4ff
+ 0xE3, 0x80, 0x96, 0x43, 0xE3, 0x80, 0x97, 0x43,
+ 0xE3, 0x82, 0xA1, 0x43, 0xE3, 0x82, 0xA2, 0x43,
+ 0xE3, 0x82, 0xA3, 0x43, 0xE3, 0x82, 0xA4, 0x43,
+ 0xE3, 0x82, 0xA5, 0x43, 0xE3, 0x82, 0xA6, 0x43,
+ 0xE3, 0x82, 0xA7, 0x43, 0xE3, 0x82, 0xA8, 0x43,
+ 0xE3, 0x82, 0xA9, 0x43, 0xE3, 0x82, 0xAA, 0x43,
+ 0xE3, 0x82, 0xAB, 0x43, 0xE3, 0x82, 0xAD, 0x43,
+ 0xE3, 0x82, 0xAF, 0x43, 0xE3, 0x82, 0xB1, 0x43,
+ // Bytes 500 - 53f
+ 0xE3, 0x82, 0xB3, 0x43, 0xE3, 0x82, 0xB5, 0x43,
+ 0xE3, 0x82, 0xB7, 0x43, 0xE3, 0x82, 0xB9, 0x43,
+ 0xE3, 0x82, 0xBB, 0x43, 0xE3, 0x82, 0xBD, 0x43,
+ 0xE3, 0x82, 0xBF, 0x43, 0xE3, 0x83, 0x81, 0x43,
+ 0xE3, 0x83, 0x83, 0x43, 0xE3, 0x83, 0x84, 0x43,
+ 0xE3, 0x83, 0x86, 0x43, 0xE3, 0x83, 0x88, 0x43,
+ 0xE3, 0x83, 0x8A, 0x43, 0xE3, 0x83, 0x8B, 0x43,
+ 0xE3, 0x83, 0x8C, 0x43, 0xE3, 0x83, 0x8D, 0x43,
+ // Bytes 540 - 57f
+ 0xE3, 0x83, 0x8E, 0x43, 0xE3, 0x83, 0x8F, 0x43,
+ 0xE3, 0x83, 0x92, 0x43, 0xE3, 0x83, 0x95, 0x43,
+ 0xE3, 0x83, 0x98, 0x43, 0xE3, 0x83, 0x9B, 0x43,
+ 0xE3, 0x83, 0x9E, 0x43, 0xE3, 0x83, 0x9F, 0x43,
+ 0xE3, 0x83, 0xA0, 0x43, 0xE3, 0x83, 0xA1, 0x43,
+ 0xE3, 0x83, 0xA2, 0x43, 0xE3, 0x83, 0xA3, 0x43,
+ 0xE3, 0x83, 0xA4, 0x43, 0xE3, 0x83, 0xA5, 0x43,
+ 0xE3, 0x83, 0xA6, 0x43, 0xE3, 0x83, 0xA7, 0x43,
+ // Bytes 580 - 5bf
+ 0xE3, 0x83, 0xA8, 0x43, 0xE3, 0x83, 0xA9, 0x43,
+ 0xE3, 0x83, 0xAA, 0x43, 0xE3, 0x83, 0xAB, 0x43,
+ 0xE3, 0x83, 0xAC, 0x43, 0xE3, 0x83, 0xAD, 0x43,
+ 0xE3, 0x83, 0xAF, 0x43, 0xE3, 0x83, 0xB0, 0x43,
+ 0xE3, 0x83, 0xB1, 0x43, 0xE3, 0x83, 0xB2, 0x43,
+ 0xE3, 0x83, 0xB3, 0x43, 0xE3, 0x83, 0xBB, 0x43,
+ 0xE3, 0x83, 0xBC, 0x43, 0xE3, 0x92, 0x9E, 0x43,
+ 0xE3, 0x92, 0xB9, 0x43, 0xE3, 0x92, 0xBB, 0x43,
+ // Bytes 5c0 - 5ff
+ 0xE3, 0x93, 0x9F, 0x43, 0xE3, 0x94, 0x95, 0x43,
+ 0xE3, 0x9B, 0xAE, 0x43, 0xE3, 0x9B, 0xBC, 0x43,
+ 0xE3, 0x9E, 0x81, 0x43, 0xE3, 0xA0, 0xAF, 0x43,
+ 0xE3, 0xA1, 0xA2, 0x43, 0xE3, 0xA1, 0xBC, 0x43,
+ 0xE3, 0xA3, 0x87, 0x43, 0xE3, 0xA3, 0xA3, 0x43,
+ 0xE3, 0xA4, 0x9C, 0x43, 0xE3, 0xA4, 0xBA, 0x43,
+ 0xE3, 0xA8, 0xAE, 0x43, 0xE3, 0xA9, 0xAC, 0x43,
+ 0xE3, 0xAB, 0xA4, 0x43, 0xE3, 0xAC, 0x88, 0x43,
+ // Bytes 600 - 63f
+ 0xE3, 0xAC, 0x99, 0x43, 0xE3, 0xAD, 0x89, 0x43,
+ 0xE3, 0xAE, 0x9D, 0x43, 0xE3, 0xB0, 0x98, 0x43,
+ 0xE3, 0xB1, 0x8E, 0x43, 0xE3, 0xB4, 0xB3, 0x43,
+ 0xE3, 0xB6, 0x96, 0x43, 0xE3, 0xBA, 0xAC, 0x43,
+ 0xE3, 0xBA, 0xB8, 0x43, 0xE3, 0xBC, 0x9B, 0x43,
+ 0xE3, 0xBF, 0xBC, 0x43, 0xE4, 0x80, 0x88, 0x43,
+ 0xE4, 0x80, 0x98, 0x43, 0xE4, 0x80, 0xB9, 0x43,
+ 0xE4, 0x81, 0x86, 0x43, 0xE4, 0x82, 0x96, 0x43,
+ // Bytes 640 - 67f
+ 0xE4, 0x83, 0xA3, 0x43, 0xE4, 0x84, 0xAF, 0x43,
+ 0xE4, 0x88, 0x82, 0x43, 0xE4, 0x88, 0xA7, 0x43,
+ 0xE4, 0x8A, 0xA0, 0x43, 0xE4, 0x8C, 0x81, 0x43,
+ 0xE4, 0x8C, 0xB4, 0x43, 0xE4, 0x8D, 0x99, 0x43,
+ 0xE4, 0x8F, 0x95, 0x43, 0xE4, 0x8F, 0x99, 0x43,
+ 0xE4, 0x90, 0x8B, 0x43, 0xE4, 0x91, 0xAB, 0x43,
+ 0xE4, 0x94, 0xAB, 0x43, 0xE4, 0x95, 0x9D, 0x43,
+ 0xE4, 0x95, 0xA1, 0x43, 0xE4, 0x95, 0xAB, 0x43,
+ // Bytes 680 - 6bf
+ 0xE4, 0x97, 0x97, 0x43, 0xE4, 0x97, 0xB9, 0x43,
+ 0xE4, 0x98, 0xB5, 0x43, 0xE4, 0x9A, 0xBE, 0x43,
+ 0xE4, 0x9B, 0x87, 0x43, 0xE4, 0xA6, 0x95, 0x43,
+ 0xE4, 0xA7, 0xA6, 0x43, 0xE4, 0xA9, 0xAE, 0x43,
+ 0xE4, 0xA9, 0xB6, 0x43, 0xE4, 0xAA, 0xB2, 0x43,
+ 0xE4, 0xAC, 0xB3, 0x43, 0xE4, 0xAF, 0x8E, 0x43,
+ 0xE4, 0xB3, 0x8E, 0x43, 0xE4, 0xB3, 0xAD, 0x43,
+ 0xE4, 0xB3, 0xB8, 0x43, 0xE4, 0xB5, 0x96, 0x43,
+ // Bytes 6c0 - 6ff
+ 0xE4, 0xB8, 0x80, 0x43, 0xE4, 0xB8, 0x81, 0x43,
+ 0xE4, 0xB8, 0x83, 0x43, 0xE4, 0xB8, 0x89, 0x43,
+ 0xE4, 0xB8, 0x8A, 0x43, 0xE4, 0xB8, 0x8B, 0x43,
+ 0xE4, 0xB8, 0x8D, 0x43, 0xE4, 0xB8, 0x99, 0x43,
+ 0xE4, 0xB8, 0xA6, 0x43, 0xE4, 0xB8, 0xA8, 0x43,
+ 0xE4, 0xB8, 0xAD, 0x43, 0xE4, 0xB8, 0xB2, 0x43,
+ 0xE4, 0xB8, 0xB6, 0x43, 0xE4, 0xB8, 0xB8, 0x43,
+ 0xE4, 0xB8, 0xB9, 0x43, 0xE4, 0xB8, 0xBD, 0x43,
+ // Bytes 700 - 73f
+ 0xE4, 0xB8, 0xBF, 0x43, 0xE4, 0xB9, 0x81, 0x43,
+ 0xE4, 0xB9, 0x99, 0x43, 0xE4, 0xB9, 0x9D, 0x43,
+ 0xE4, 0xBA, 0x82, 0x43, 0xE4, 0xBA, 0x85, 0x43,
+ 0xE4, 0xBA, 0x86, 0x43, 0xE4, 0xBA, 0x8C, 0x43,
+ 0xE4, 0xBA, 0x94, 0x43, 0xE4, 0xBA, 0xA0, 0x43,
+ 0xE4, 0xBA, 0xA4, 0x43, 0xE4, 0xBA, 0xAE, 0x43,
+ 0xE4, 0xBA, 0xBA, 0x43, 0xE4, 0xBB, 0x80, 0x43,
+ 0xE4, 0xBB, 0x8C, 0x43, 0xE4, 0xBB, 0xA4, 0x43,
+ // Bytes 740 - 77f
+ 0xE4, 0xBC, 0x81, 0x43, 0xE4, 0xBC, 0x91, 0x43,
+ 0xE4, 0xBD, 0xA0, 0x43, 0xE4, 0xBE, 0x80, 0x43,
+ 0xE4, 0xBE, 0x86, 0x43, 0xE4, 0xBE, 0x8B, 0x43,
+ 0xE4, 0xBE, 0xAE, 0x43, 0xE4, 0xBE, 0xBB, 0x43,
+ 0xE4, 0xBE, 0xBF, 0x43, 0xE5, 0x80, 0x82, 0x43,
+ 0xE5, 0x80, 0xAB, 0x43, 0xE5, 0x81, 0xBA, 0x43,
+ 0xE5, 0x82, 0x99, 0x43, 0xE5, 0x83, 0x8F, 0x43,
+ 0xE5, 0x83, 0x9A, 0x43, 0xE5, 0x83, 0xA7, 0x43,
+ // Bytes 780 - 7bf
+ 0xE5, 0x84, 0xAA, 0x43, 0xE5, 0x84, 0xBF, 0x43,
+ 0xE5, 0x85, 0x80, 0x43, 0xE5, 0x85, 0x85, 0x43,
+ 0xE5, 0x85, 0x8D, 0x43, 0xE5, 0x85, 0x94, 0x43,
+ 0xE5, 0x85, 0xA4, 0x43, 0xE5, 0x85, 0xA5, 0x43,
+ 0xE5, 0x85, 0xA7, 0x43, 0xE5, 0x85, 0xA8, 0x43,
+ 0xE5, 0x85, 0xA9, 0x43, 0xE5, 0x85, 0xAB, 0x43,
+ 0xE5, 0x85, 0xAD, 0x43, 0xE5, 0x85, 0xB7, 0x43,
+ 0xE5, 0x86, 0x80, 0x43, 0xE5, 0x86, 0x82, 0x43,
+ // Bytes 7c0 - 7ff
+ 0xE5, 0x86, 0x8D, 0x43, 0xE5, 0x86, 0x92, 0x43,
+ 0xE5, 0x86, 0x95, 0x43, 0xE5, 0x86, 0x96, 0x43,
+ 0xE5, 0x86, 0x97, 0x43, 0xE5, 0x86, 0x99, 0x43,
+ 0xE5, 0x86, 0xA4, 0x43, 0xE5, 0x86, 0xAB, 0x43,
+ 0xE5, 0x86, 0xAC, 0x43, 0xE5, 0x86, 0xB5, 0x43,
+ 0xE5, 0x86, 0xB7, 0x43, 0xE5, 0x87, 0x89, 0x43,
+ 0xE5, 0x87, 0x8C, 0x43, 0xE5, 0x87, 0x9C, 0x43,
+ 0xE5, 0x87, 0x9E, 0x43, 0xE5, 0x87, 0xA0, 0x43,
+ // Bytes 800 - 83f
+ 0xE5, 0x87, 0xB5, 0x43, 0xE5, 0x88, 0x80, 0x43,
+ 0xE5, 0x88, 0x83, 0x43, 0xE5, 0x88, 0x87, 0x43,
+ 0xE5, 0x88, 0x97, 0x43, 0xE5, 0x88, 0x9D, 0x43,
+ 0xE5, 0x88, 0xA9, 0x43, 0xE5, 0x88, 0xBA, 0x43,
+ 0xE5, 0x88, 0xBB, 0x43, 0xE5, 0x89, 0x86, 0x43,
+ 0xE5, 0x89, 0x8D, 0x43, 0xE5, 0x89, 0xB2, 0x43,
+ 0xE5, 0x89, 0xB7, 0x43, 0xE5, 0x8A, 0x89, 0x43,
+ 0xE5, 0x8A, 0x9B, 0x43, 0xE5, 0x8A, 0xA3, 0x43,
+ // Bytes 840 - 87f
+ 0xE5, 0x8A, 0xB3, 0x43, 0xE5, 0x8A, 0xB4, 0x43,
+ 0xE5, 0x8B, 0x87, 0x43, 0xE5, 0x8B, 0x89, 0x43,
+ 0xE5, 0x8B, 0x92, 0x43, 0xE5, 0x8B, 0x9E, 0x43,
+ 0xE5, 0x8B, 0xA4, 0x43, 0xE5, 0x8B, 0xB5, 0x43,
+ 0xE5, 0x8B, 0xB9, 0x43, 0xE5, 0x8B, 0xBA, 0x43,
+ 0xE5, 0x8C, 0x85, 0x43, 0xE5, 0x8C, 0x86, 0x43,
+ 0xE5, 0x8C, 0x95, 0x43, 0xE5, 0x8C, 0x97, 0x43,
+ 0xE5, 0x8C, 0x9A, 0x43, 0xE5, 0x8C, 0xB8, 0x43,
+ // Bytes 880 - 8bf
+ 0xE5, 0x8C, 0xBB, 0x43, 0xE5, 0x8C, 0xBF, 0x43,
+ 0xE5, 0x8D, 0x81, 0x43, 0xE5, 0x8D, 0x84, 0x43,
+ 0xE5, 0x8D, 0x85, 0x43, 0xE5, 0x8D, 0x89, 0x43,
+ 0xE5, 0x8D, 0x91, 0x43, 0xE5, 0x8D, 0x94, 0x43,
+ 0xE5, 0x8D, 0x9A, 0x43, 0xE5, 0x8D, 0x9C, 0x43,
+ 0xE5, 0x8D, 0xA9, 0x43, 0xE5, 0x8D, 0xB0, 0x43,
+ 0xE5, 0x8D, 0xB3, 0x43, 0xE5, 0x8D, 0xB5, 0x43,
+ 0xE5, 0x8D, 0xBD, 0x43, 0xE5, 0x8D, 0xBF, 0x43,
+ // Bytes 8c0 - 8ff
+ 0xE5, 0x8E, 0x82, 0x43, 0xE5, 0x8E, 0xB6, 0x43,
+ 0xE5, 0x8F, 0x83, 0x43, 0xE5, 0x8F, 0x88, 0x43,
+ 0xE5, 0x8F, 0x8A, 0x43, 0xE5, 0x8F, 0x8C, 0x43,
+ 0xE5, 0x8F, 0x9F, 0x43, 0xE5, 0x8F, 0xA3, 0x43,
+ 0xE5, 0x8F, 0xA5, 0x43, 0xE5, 0x8F, 0xAB, 0x43,
+ 0xE5, 0x8F, 0xAF, 0x43, 0xE5, 0x8F, 0xB1, 0x43,
+ 0xE5, 0x8F, 0xB3, 0x43, 0xE5, 0x90, 0x86, 0x43,
+ 0xE5, 0x90, 0x88, 0x43, 0xE5, 0x90, 0x8D, 0x43,
+ // Bytes 900 - 93f
+ 0xE5, 0x90, 0x8F, 0x43, 0xE5, 0x90, 0x9D, 0x43,
+ 0xE5, 0x90, 0xB8, 0x43, 0xE5, 0x90, 0xB9, 0x43,
+ 0xE5, 0x91, 0x82, 0x43, 0xE5, 0x91, 0x88, 0x43,
+ 0xE5, 0x91, 0xA8, 0x43, 0xE5, 0x92, 0x9E, 0x43,
+ 0xE5, 0x92, 0xA2, 0x43, 0xE5, 0x92, 0xBD, 0x43,
+ 0xE5, 0x93, 0xB6, 0x43, 0xE5, 0x94, 0x90, 0x43,
+ 0xE5, 0x95, 0x8F, 0x43, 0xE5, 0x95, 0x93, 0x43,
+ 0xE5, 0x95, 0x95, 0x43, 0xE5, 0x95, 0xA3, 0x43,
+ // Bytes 940 - 97f
+ 0xE5, 0x96, 0x84, 0x43, 0xE5, 0x96, 0x87, 0x43,
+ 0xE5, 0x96, 0x99, 0x43, 0xE5, 0x96, 0x9D, 0x43,
+ 0xE5, 0x96, 0xAB, 0x43, 0xE5, 0x96, 0xB3, 0x43,
+ 0xE5, 0x96, 0xB6, 0x43, 0xE5, 0x97, 0x80, 0x43,
+ 0xE5, 0x97, 0x82, 0x43, 0xE5, 0x97, 0xA2, 0x43,
+ 0xE5, 0x98, 0x86, 0x43, 0xE5, 0x99, 0x91, 0x43,
+ 0xE5, 0x99, 0xA8, 0x43, 0xE5, 0x99, 0xB4, 0x43,
+ 0xE5, 0x9B, 0x97, 0x43, 0xE5, 0x9B, 0x9B, 0x43,
+ // Bytes 980 - 9bf
+ 0xE5, 0x9B, 0xB9, 0x43, 0xE5, 0x9C, 0x96, 0x43,
+ 0xE5, 0x9C, 0x97, 0x43, 0xE5, 0x9C, 0x9F, 0x43,
+ 0xE5, 0x9C, 0xB0, 0x43, 0xE5, 0x9E, 0x8B, 0x43,
+ 0xE5, 0x9F, 0x8E, 0x43, 0xE5, 0x9F, 0xB4, 0x43,
+ 0xE5, 0xA0, 0x8D, 0x43, 0xE5, 0xA0, 0xB1, 0x43,
+ 0xE5, 0xA0, 0xB2, 0x43, 0xE5, 0xA1, 0x80, 0x43,
+ 0xE5, 0xA1, 0x9A, 0x43, 0xE5, 0xA1, 0x9E, 0x43,
+ 0xE5, 0xA2, 0xA8, 0x43, 0xE5, 0xA2, 0xAC, 0x43,
+ // Bytes 9c0 - 9ff
+ 0xE5, 0xA2, 0xB3, 0x43, 0xE5, 0xA3, 0x98, 0x43,
+ 0xE5, 0xA3, 0x9F, 0x43, 0xE5, 0xA3, 0xAB, 0x43,
+ 0xE5, 0xA3, 0xAE, 0x43, 0xE5, 0xA3, 0xB0, 0x43,
+ 0xE5, 0xA3, 0xB2, 0x43, 0xE5, 0xA3, 0xB7, 0x43,
+ 0xE5, 0xA4, 0x82, 0x43, 0xE5, 0xA4, 0x86, 0x43,
+ 0xE5, 0xA4, 0x8A, 0x43, 0xE5, 0xA4, 0x95, 0x43,
+ 0xE5, 0xA4, 0x9A, 0x43, 0xE5, 0xA4, 0x9C, 0x43,
+ 0xE5, 0xA4, 0xA2, 0x43, 0xE5, 0xA4, 0xA7, 0x43,
+ // Bytes a00 - a3f
+ 0xE5, 0xA4, 0xA9, 0x43, 0xE5, 0xA5, 0x84, 0x43,
+ 0xE5, 0xA5, 0x88, 0x43, 0xE5, 0xA5, 0x91, 0x43,
+ 0xE5, 0xA5, 0x94, 0x43, 0xE5, 0xA5, 0xA2, 0x43,
+ 0xE5, 0xA5, 0xB3, 0x43, 0xE5, 0xA7, 0x98, 0x43,
+ 0xE5, 0xA7, 0xAC, 0x43, 0xE5, 0xA8, 0x9B, 0x43,
+ 0xE5, 0xA8, 0xA7, 0x43, 0xE5, 0xA9, 0xA2, 0x43,
+ 0xE5, 0xA9, 0xA6, 0x43, 0xE5, 0xAA, 0xB5, 0x43,
+ 0xE5, 0xAC, 0x88, 0x43, 0xE5, 0xAC, 0xA8, 0x43,
+ // Bytes a40 - a7f
+ 0xE5, 0xAC, 0xBE, 0x43, 0xE5, 0xAD, 0x90, 0x43,
+ 0xE5, 0xAD, 0x97, 0x43, 0xE5, 0xAD, 0xA6, 0x43,
+ 0xE5, 0xAE, 0x80, 0x43, 0xE5, 0xAE, 0x85, 0x43,
+ 0xE5, 0xAE, 0x97, 0x43, 0xE5, 0xAF, 0x83, 0x43,
+ 0xE5, 0xAF, 0x98, 0x43, 0xE5, 0xAF, 0xA7, 0x43,
+ 0xE5, 0xAF, 0xAE, 0x43, 0xE5, 0xAF, 0xB3, 0x43,
+ 0xE5, 0xAF, 0xB8, 0x43, 0xE5, 0xAF, 0xBF, 0x43,
+ 0xE5, 0xB0, 0x86, 0x43, 0xE5, 0xB0, 0x8F, 0x43,
+ // Bytes a80 - abf
+ 0xE5, 0xB0, 0xA2, 0x43, 0xE5, 0xB0, 0xB8, 0x43,
+ 0xE5, 0xB0, 0xBF, 0x43, 0xE5, 0xB1, 0xA0, 0x43,
+ 0xE5, 0xB1, 0xA2, 0x43, 0xE5, 0xB1, 0xA4, 0x43,
+ 0xE5, 0xB1, 0xA5, 0x43, 0xE5, 0xB1, 0xAE, 0x43,
+ 0xE5, 0xB1, 0xB1, 0x43, 0xE5, 0xB2, 0x8D, 0x43,
+ 0xE5, 0xB3, 0x80, 0x43, 0xE5, 0xB4, 0x99, 0x43,
+ 0xE5, 0xB5, 0x83, 0x43, 0xE5, 0xB5, 0x90, 0x43,
+ 0xE5, 0xB5, 0xAB, 0x43, 0xE5, 0xB5, 0xAE, 0x43,
+ // Bytes ac0 - aff
+ 0xE5, 0xB5, 0xBC, 0x43, 0xE5, 0xB6, 0xB2, 0x43,
+ 0xE5, 0xB6, 0xBA, 0x43, 0xE5, 0xB7, 0x9B, 0x43,
+ 0xE5, 0xB7, 0xA1, 0x43, 0xE5, 0xB7, 0xA2, 0x43,
+ 0xE5, 0xB7, 0xA5, 0x43, 0xE5, 0xB7, 0xA6, 0x43,
+ 0xE5, 0xB7, 0xB1, 0x43, 0xE5, 0xB7, 0xBD, 0x43,
+ 0xE5, 0xB7, 0xBE, 0x43, 0xE5, 0xB8, 0xA8, 0x43,
+ 0xE5, 0xB8, 0xBD, 0x43, 0xE5, 0xB9, 0xA9, 0x43,
+ 0xE5, 0xB9, 0xB2, 0x43, 0xE5, 0xB9, 0xB4, 0x43,
+ // Bytes b00 - b3f
+ 0xE5, 0xB9, 0xBA, 0x43, 0xE5, 0xB9, 0xBC, 0x43,
+ 0xE5, 0xB9, 0xBF, 0x43, 0xE5, 0xBA, 0xA6, 0x43,
+ 0xE5, 0xBA, 0xB0, 0x43, 0xE5, 0xBA, 0xB3, 0x43,
+ 0xE5, 0xBA, 0xB6, 0x43, 0xE5, 0xBB, 0x89, 0x43,
+ 0xE5, 0xBB, 0x8A, 0x43, 0xE5, 0xBB, 0x92, 0x43,
+ 0xE5, 0xBB, 0x93, 0x43, 0xE5, 0xBB, 0x99, 0x43,
+ 0xE5, 0xBB, 0xAC, 0x43, 0xE5, 0xBB, 0xB4, 0x43,
+ 0xE5, 0xBB, 0xBE, 0x43, 0xE5, 0xBC, 0x84, 0x43,
+ // Bytes b40 - b7f
+ 0xE5, 0xBC, 0x8B, 0x43, 0xE5, 0xBC, 0x93, 0x43,
+ 0xE5, 0xBC, 0xA2, 0x43, 0xE5, 0xBD, 0x90, 0x43,
+ 0xE5, 0xBD, 0x93, 0x43, 0xE5, 0xBD, 0xA1, 0x43,
+ 0xE5, 0xBD, 0xA2, 0x43, 0xE5, 0xBD, 0xA9, 0x43,
+ 0xE5, 0xBD, 0xAB, 0x43, 0xE5, 0xBD, 0xB3, 0x43,
+ 0xE5, 0xBE, 0x8B, 0x43, 0xE5, 0xBE, 0x8C, 0x43,
+ 0xE5, 0xBE, 0x97, 0x43, 0xE5, 0xBE, 0x9A, 0x43,
+ 0xE5, 0xBE, 0xA9, 0x43, 0xE5, 0xBE, 0xAD, 0x43,
+ // Bytes b80 - bbf
+ 0xE5, 0xBF, 0x83, 0x43, 0xE5, 0xBF, 0x8D, 0x43,
+ 0xE5, 0xBF, 0x97, 0x43, 0xE5, 0xBF, 0xB5, 0x43,
+ 0xE5, 0xBF, 0xB9, 0x43, 0xE6, 0x80, 0x92, 0x43,
+ 0xE6, 0x80, 0x9C, 0x43, 0xE6, 0x81, 0xB5, 0x43,
+ 0xE6, 0x82, 0x81, 0x43, 0xE6, 0x82, 0x94, 0x43,
+ 0xE6, 0x83, 0x87, 0x43, 0xE6, 0x83, 0x98, 0x43,
+ 0xE6, 0x83, 0xA1, 0x43, 0xE6, 0x84, 0x88, 0x43,
+ 0xE6, 0x85, 0x84, 0x43, 0xE6, 0x85, 0x88, 0x43,
+ // Bytes bc0 - bff
+ 0xE6, 0x85, 0x8C, 0x43, 0xE6, 0x85, 0x8E, 0x43,
+ 0xE6, 0x85, 0xA0, 0x43, 0xE6, 0x85, 0xA8, 0x43,
+ 0xE6, 0x85, 0xBA, 0x43, 0xE6, 0x86, 0x8E, 0x43,
+ 0xE6, 0x86, 0x90, 0x43, 0xE6, 0x86, 0xA4, 0x43,
+ 0xE6, 0x86, 0xAF, 0x43, 0xE6, 0x86, 0xB2, 0x43,
+ 0xE6, 0x87, 0x9E, 0x43, 0xE6, 0x87, 0xB2, 0x43,
+ 0xE6, 0x87, 0xB6, 0x43, 0xE6, 0x88, 0x80, 0x43,
+ 0xE6, 0x88, 0x88, 0x43, 0xE6, 0x88, 0x90, 0x43,
+ // Bytes c00 - c3f
+ 0xE6, 0x88, 0x9B, 0x43, 0xE6, 0x88, 0xAE, 0x43,
+ 0xE6, 0x88, 0xB4, 0x43, 0xE6, 0x88, 0xB6, 0x43,
+ 0xE6, 0x89, 0x8B, 0x43, 0xE6, 0x89, 0x93, 0x43,
+ 0xE6, 0x89, 0x9D, 0x43, 0xE6, 0x8A, 0x95, 0x43,
+ 0xE6, 0x8A, 0xB1, 0x43, 0xE6, 0x8B, 0x89, 0x43,
+ 0xE6, 0x8B, 0x8F, 0x43, 0xE6, 0x8B, 0x93, 0x43,
+ 0xE6, 0x8B, 0x94, 0x43, 0xE6, 0x8B, 0xBC, 0x43,
+ 0xE6, 0x8B, 0xBE, 0x43, 0xE6, 0x8C, 0x87, 0x43,
+ // Bytes c40 - c7f
+ 0xE6, 0x8C, 0xBD, 0x43, 0xE6, 0x8D, 0x90, 0x43,
+ 0xE6, 0x8D, 0x95, 0x43, 0xE6, 0x8D, 0xA8, 0x43,
+ 0xE6, 0x8D, 0xBB, 0x43, 0xE6, 0x8E, 0x83, 0x43,
+ 0xE6, 0x8E, 0xA0, 0x43, 0xE6, 0x8E, 0xA9, 0x43,
+ 0xE6, 0x8F, 0x84, 0x43, 0xE6, 0x8F, 0x85, 0x43,
+ 0xE6, 0x8F, 0xA4, 0x43, 0xE6, 0x90, 0x9C, 0x43,
+ 0xE6, 0x90, 0xA2, 0x43, 0xE6, 0x91, 0x92, 0x43,
+ 0xE6, 0x91, 0xA9, 0x43, 0xE6, 0x91, 0xB7, 0x43,
+ // Bytes c80 - cbf
+ 0xE6, 0x91, 0xBE, 0x43, 0xE6, 0x92, 0x9A, 0x43,
+ 0xE6, 0x92, 0x9D, 0x43, 0xE6, 0x93, 0x84, 0x43,
+ 0xE6, 0x94, 0xAF, 0x43, 0xE6, 0x94, 0xB4, 0x43,
+ 0xE6, 0x95, 0x8F, 0x43, 0xE6, 0x95, 0x96, 0x43,
+ 0xE6, 0x95, 0xAC, 0x43, 0xE6, 0x95, 0xB8, 0x43,
+ 0xE6, 0x96, 0x87, 0x43, 0xE6, 0x96, 0x97, 0x43,
+ 0xE6, 0x96, 0x99, 0x43, 0xE6, 0x96, 0xA4, 0x43,
+ 0xE6, 0x96, 0xB0, 0x43, 0xE6, 0x96, 0xB9, 0x43,
+ // Bytes cc0 - cff
+ 0xE6, 0x97, 0x85, 0x43, 0xE6, 0x97, 0xA0, 0x43,
+ 0xE6, 0x97, 0xA2, 0x43, 0xE6, 0x97, 0xA3, 0x43,
+ 0xE6, 0x97, 0xA5, 0x43, 0xE6, 0x98, 0x93, 0x43,
+ 0xE6, 0x98, 0xA0, 0x43, 0xE6, 0x99, 0x89, 0x43,
+ 0xE6, 0x99, 0xB4, 0x43, 0xE6, 0x9A, 0x88, 0x43,
+ 0xE6, 0x9A, 0x91, 0x43, 0xE6, 0x9A, 0x9C, 0x43,
+ 0xE6, 0x9A, 0xB4, 0x43, 0xE6, 0x9B, 0x86, 0x43,
+ 0xE6, 0x9B, 0xB0, 0x43, 0xE6, 0x9B, 0xB4, 0x43,
+ // Bytes d00 - d3f
+ 0xE6, 0x9B, 0xB8, 0x43, 0xE6, 0x9C, 0x80, 0x43,
+ 0xE6, 0x9C, 0x88, 0x43, 0xE6, 0x9C, 0x89, 0x43,
+ 0xE6, 0x9C, 0x97, 0x43, 0xE6, 0x9C, 0x9B, 0x43,
+ 0xE6, 0x9C, 0xA1, 0x43, 0xE6, 0x9C, 0xA8, 0x43,
+ 0xE6, 0x9D, 0x8E, 0x43, 0xE6, 0x9D, 0x93, 0x43,
+ 0xE6, 0x9D, 0x96, 0x43, 0xE6, 0x9D, 0x9E, 0x43,
+ 0xE6, 0x9D, 0xBB, 0x43, 0xE6, 0x9E, 0x85, 0x43,
+ 0xE6, 0x9E, 0x97, 0x43, 0xE6, 0x9F, 0xB3, 0x43,
+ // Bytes d40 - d7f
+ 0xE6, 0x9F, 0xBA, 0x43, 0xE6, 0xA0, 0x97, 0x43,
+ 0xE6, 0xA0, 0x9F, 0x43, 0xE6, 0xA0, 0xAA, 0x43,
+ 0xE6, 0xA1, 0x92, 0x43, 0xE6, 0xA2, 0x81, 0x43,
+ 0xE6, 0xA2, 0x85, 0x43, 0xE6, 0xA2, 0x8E, 0x43,
+ 0xE6, 0xA2, 0xA8, 0x43, 0xE6, 0xA4, 0x94, 0x43,
+ 0xE6, 0xA5, 0x82, 0x43, 0xE6, 0xA6, 0xA3, 0x43,
+ 0xE6, 0xA7, 0xAA, 0x43, 0xE6, 0xA8, 0x82, 0x43,
+ 0xE6, 0xA8, 0x93, 0x43, 0xE6, 0xAA, 0xA8, 0x43,
+ // Bytes d80 - dbf
+ 0xE6, 0xAB, 0x93, 0x43, 0xE6, 0xAB, 0x9B, 0x43,
+ 0xE6, 0xAC, 0x84, 0x43, 0xE6, 0xAC, 0xA0, 0x43,
+ 0xE6, 0xAC, 0xA1, 0x43, 0xE6, 0xAD, 0x94, 0x43,
+ 0xE6, 0xAD, 0xA2, 0x43, 0xE6, 0xAD, 0xA3, 0x43,
+ 0xE6, 0xAD, 0xB2, 0x43, 0xE6, 0xAD, 0xB7, 0x43,
+ 0xE6, 0xAD, 0xB9, 0x43, 0xE6, 0xAE, 0x9F, 0x43,
+ 0xE6, 0xAE, 0xAE, 0x43, 0xE6, 0xAE, 0xB3, 0x43,
+ 0xE6, 0xAE, 0xBA, 0x43, 0xE6, 0xAE, 0xBB, 0x43,
+ // Bytes dc0 - dff
+ 0xE6, 0xAF, 0x8B, 0x43, 0xE6, 0xAF, 0x8D, 0x43,
+ 0xE6, 0xAF, 0x94, 0x43, 0xE6, 0xAF, 0x9B, 0x43,
+ 0xE6, 0xB0, 0x8F, 0x43, 0xE6, 0xB0, 0x94, 0x43,
+ 0xE6, 0xB0, 0xB4, 0x43, 0xE6, 0xB1, 0x8E, 0x43,
+ 0xE6, 0xB1, 0xA7, 0x43, 0xE6, 0xB2, 0x88, 0x43,
+ 0xE6, 0xB2, 0xBF, 0x43, 0xE6, 0xB3, 0x8C, 0x43,
+ 0xE6, 0xB3, 0x8D, 0x43, 0xE6, 0xB3, 0xA5, 0x43,
+ 0xE6, 0xB3, 0xA8, 0x43, 0xE6, 0xB4, 0x96, 0x43,
+ // Bytes e00 - e3f
+ 0xE6, 0xB4, 0x9B, 0x43, 0xE6, 0xB4, 0x9E, 0x43,
+ 0xE6, 0xB4, 0xB4, 0x43, 0xE6, 0xB4, 0xBE, 0x43,
+ 0xE6, 0xB5, 0x81, 0x43, 0xE6, 0xB5, 0xA9, 0x43,
+ 0xE6, 0xB5, 0xAA, 0x43, 0xE6, 0xB5, 0xB7, 0x43,
+ 0xE6, 0xB5, 0xB8, 0x43, 0xE6, 0xB6, 0x85, 0x43,
+ 0xE6, 0xB7, 0x8B, 0x43, 0xE6, 0xB7, 0x9A, 0x43,
+ 0xE6, 0xB7, 0xAA, 0x43, 0xE6, 0xB7, 0xB9, 0x43,
+ 0xE6, 0xB8, 0x9A, 0x43, 0xE6, 0xB8, 0xAF, 0x43,
+ // Bytes e40 - e7f
+ 0xE6, 0xB9, 0xAE, 0x43, 0xE6, 0xBA, 0x80, 0x43,
+ 0xE6, 0xBA, 0x9C, 0x43, 0xE6, 0xBA, 0xBA, 0x43,
+ 0xE6, 0xBB, 0x87, 0x43, 0xE6, 0xBB, 0x8B, 0x43,
+ 0xE6, 0xBB, 0x91, 0x43, 0xE6, 0xBB, 0x9B, 0x43,
+ 0xE6, 0xBC, 0x8F, 0x43, 0xE6, 0xBC, 0x94, 0x43,
+ 0xE6, 0xBC, 0xA2, 0x43, 0xE6, 0xBC, 0xA3, 0x43,
+ 0xE6, 0xBD, 0xAE, 0x43, 0xE6, 0xBF, 0x86, 0x43,
+ 0xE6, 0xBF, 0xAB, 0x43, 0xE6, 0xBF, 0xBE, 0x43,
+ // Bytes e80 - ebf
+ 0xE7, 0x80, 0x9B, 0x43, 0xE7, 0x80, 0x9E, 0x43,
+ 0xE7, 0x80, 0xB9, 0x43, 0xE7, 0x81, 0x8A, 0x43,
+ 0xE7, 0x81, 0xAB, 0x43, 0xE7, 0x81, 0xB0, 0x43,
+ 0xE7, 0x81, 0xB7, 0x43, 0xE7, 0x81, 0xBD, 0x43,
+ 0xE7, 0x82, 0x99, 0x43, 0xE7, 0x82, 0xAD, 0x43,
+ 0xE7, 0x83, 0x88, 0x43, 0xE7, 0x83, 0x99, 0x43,
+ 0xE7, 0x84, 0xA1, 0x43, 0xE7, 0x85, 0x85, 0x43,
+ 0xE7, 0x85, 0x89, 0x43, 0xE7, 0x85, 0xAE, 0x43,
+ // Bytes ec0 - eff
+ 0xE7, 0x86, 0x9C, 0x43, 0xE7, 0x87, 0x8E, 0x43,
+ 0xE7, 0x87, 0x90, 0x43, 0xE7, 0x88, 0x90, 0x43,
+ 0xE7, 0x88, 0x9B, 0x43, 0xE7, 0x88, 0xA8, 0x43,
+ 0xE7, 0x88, 0xAA, 0x43, 0xE7, 0x88, 0xAB, 0x43,
+ 0xE7, 0x88, 0xB5, 0x43, 0xE7, 0x88, 0xB6, 0x43,
+ 0xE7, 0x88, 0xBB, 0x43, 0xE7, 0x88, 0xBF, 0x43,
+ 0xE7, 0x89, 0x87, 0x43, 0xE7, 0x89, 0x90, 0x43,
+ 0xE7, 0x89, 0x99, 0x43, 0xE7, 0x89, 0x9B, 0x43,
+ // Bytes f00 - f3f
+ 0xE7, 0x89, 0xA2, 0x43, 0xE7, 0x89, 0xB9, 0x43,
+ 0xE7, 0x8A, 0x80, 0x43, 0xE7, 0x8A, 0x95, 0x43,
+ 0xE7, 0x8A, 0xAC, 0x43, 0xE7, 0x8A, 0xAF, 0x43,
+ 0xE7, 0x8B, 0x80, 0x43, 0xE7, 0x8B, 0xBC, 0x43,
+ 0xE7, 0x8C, 0xAA, 0x43, 0xE7, 0x8D, 0xB5, 0x43,
+ 0xE7, 0x8D, 0xBA, 0x43, 0xE7, 0x8E, 0x84, 0x43,
+ 0xE7, 0x8E, 0x87, 0x43, 0xE7, 0x8E, 0x89, 0x43,
+ 0xE7, 0x8E, 0x8B, 0x43, 0xE7, 0x8E, 0xA5, 0x43,
+ // Bytes f40 - f7f
+ 0xE7, 0x8E, 0xB2, 0x43, 0xE7, 0x8F, 0x9E, 0x43,
+ 0xE7, 0x90, 0x86, 0x43, 0xE7, 0x90, 0x89, 0x43,
+ 0xE7, 0x90, 0xA2, 0x43, 0xE7, 0x91, 0x87, 0x43,
+ 0xE7, 0x91, 0x9C, 0x43, 0xE7, 0x91, 0xA9, 0x43,
+ 0xE7, 0x91, 0xB1, 0x43, 0xE7, 0x92, 0x85, 0x43,
+ 0xE7, 0x92, 0x89, 0x43, 0xE7, 0x92, 0x98, 0x43,
+ 0xE7, 0x93, 0x8A, 0x43, 0xE7, 0x93, 0x9C, 0x43,
+ 0xE7, 0x93, 0xA6, 0x43, 0xE7, 0x94, 0x86, 0x43,
+ // Bytes f80 - fbf
+ 0xE7, 0x94, 0x98, 0x43, 0xE7, 0x94, 0x9F, 0x43,
+ 0xE7, 0x94, 0xA4, 0x43, 0xE7, 0x94, 0xA8, 0x43,
+ 0xE7, 0x94, 0xB0, 0x43, 0xE7, 0x94, 0xB2, 0x43,
+ 0xE7, 0x94, 0xB3, 0x43, 0xE7, 0x94, 0xB7, 0x43,
+ 0xE7, 0x94, 0xBB, 0x43, 0xE7, 0x94, 0xBE, 0x43,
+ 0xE7, 0x95, 0x99, 0x43, 0xE7, 0x95, 0xA5, 0x43,
+ 0xE7, 0x95, 0xB0, 0x43, 0xE7, 0x96, 0x8B, 0x43,
+ 0xE7, 0x96, 0x92, 0x43, 0xE7, 0x97, 0xA2, 0x43,
+ // Bytes fc0 - fff
+ 0xE7, 0x98, 0x90, 0x43, 0xE7, 0x98, 0x9D, 0x43,
+ 0xE7, 0x98, 0x9F, 0x43, 0xE7, 0x99, 0x82, 0x43,
+ 0xE7, 0x99, 0xA9, 0x43, 0xE7, 0x99, 0xB6, 0x43,
+ 0xE7, 0x99, 0xBD, 0x43, 0xE7, 0x9A, 0xAE, 0x43,
+ 0xE7, 0x9A, 0xBF, 0x43, 0xE7, 0x9B, 0x8A, 0x43,
+ 0xE7, 0x9B, 0x9B, 0x43, 0xE7, 0x9B, 0xA3, 0x43,
+ 0xE7, 0x9B, 0xA7, 0x43, 0xE7, 0x9B, 0xAE, 0x43,
+ 0xE7, 0x9B, 0xB4, 0x43, 0xE7, 0x9C, 0x81, 0x43,
+ // Bytes 1000 - 103f
+ 0xE7, 0x9C, 0x9E, 0x43, 0xE7, 0x9C, 0x9F, 0x43,
+ 0xE7, 0x9D, 0x80, 0x43, 0xE7, 0x9D, 0x8A, 0x43,
+ 0xE7, 0x9E, 0x8B, 0x43, 0xE7, 0x9E, 0xA7, 0x43,
+ 0xE7, 0x9F, 0x9B, 0x43, 0xE7, 0x9F, 0xA2, 0x43,
+ 0xE7, 0x9F, 0xB3, 0x43, 0xE7, 0xA1, 0x8E, 0x43,
+ 0xE7, 0xA1, 0xAB, 0x43, 0xE7, 0xA2, 0x8C, 0x43,
+ 0xE7, 0xA2, 0x91, 0x43, 0xE7, 0xA3, 0x8A, 0x43,
+ 0xE7, 0xA3, 0x8C, 0x43, 0xE7, 0xA3, 0xBB, 0x43,
+ // Bytes 1040 - 107f
+ 0xE7, 0xA4, 0xAA, 0x43, 0xE7, 0xA4, 0xBA, 0x43,
+ 0xE7, 0xA4, 0xBC, 0x43, 0xE7, 0xA4, 0xBE, 0x43,
+ 0xE7, 0xA5, 0x88, 0x43, 0xE7, 0xA5, 0x89, 0x43,
+ 0xE7, 0xA5, 0x90, 0x43, 0xE7, 0xA5, 0x96, 0x43,
+ 0xE7, 0xA5, 0x9D, 0x43, 0xE7, 0xA5, 0x9E, 0x43,
+ 0xE7, 0xA5, 0xA5, 0x43, 0xE7, 0xA5, 0xBF, 0x43,
+ 0xE7, 0xA6, 0x81, 0x43, 0xE7, 0xA6, 0x8D, 0x43,
+ 0xE7, 0xA6, 0x8E, 0x43, 0xE7, 0xA6, 0x8F, 0x43,
+ // Bytes 1080 - 10bf
+ 0xE7, 0xA6, 0xAE, 0x43, 0xE7, 0xA6, 0xB8, 0x43,
+ 0xE7, 0xA6, 0xBE, 0x43, 0xE7, 0xA7, 0x8A, 0x43,
+ 0xE7, 0xA7, 0x98, 0x43, 0xE7, 0xA7, 0xAB, 0x43,
+ 0xE7, 0xA8, 0x9C, 0x43, 0xE7, 0xA9, 0x80, 0x43,
+ 0xE7, 0xA9, 0x8A, 0x43, 0xE7, 0xA9, 0x8F, 0x43,
+ 0xE7, 0xA9, 0xB4, 0x43, 0xE7, 0xA9, 0xBA, 0x43,
+ 0xE7, 0xAA, 0x81, 0x43, 0xE7, 0xAA, 0xB1, 0x43,
+ 0xE7, 0xAB, 0x8B, 0x43, 0xE7, 0xAB, 0xAE, 0x43,
+ // Bytes 10c0 - 10ff
+ 0xE7, 0xAB, 0xB9, 0x43, 0xE7, 0xAC, 0xA0, 0x43,
+ 0xE7, 0xAE, 0x8F, 0x43, 0xE7, 0xAF, 0x80, 0x43,
+ 0xE7, 0xAF, 0x86, 0x43, 0xE7, 0xAF, 0x89, 0x43,
+ 0xE7, 0xB0, 0xBE, 0x43, 0xE7, 0xB1, 0xA0, 0x43,
+ 0xE7, 0xB1, 0xB3, 0x43, 0xE7, 0xB1, 0xBB, 0x43,
+ 0xE7, 0xB2, 0x92, 0x43, 0xE7, 0xB2, 0xBE, 0x43,
+ 0xE7, 0xB3, 0x92, 0x43, 0xE7, 0xB3, 0x96, 0x43,
+ 0xE7, 0xB3, 0xA3, 0x43, 0xE7, 0xB3, 0xA7, 0x43,
+ // Bytes 1100 - 113f
+ 0xE7, 0xB3, 0xA8, 0x43, 0xE7, 0xB3, 0xB8, 0x43,
+ 0xE7, 0xB4, 0x80, 0x43, 0xE7, 0xB4, 0x90, 0x43,
+ 0xE7, 0xB4, 0xA2, 0x43, 0xE7, 0xB4, 0xAF, 0x43,
+ 0xE7, 0xB5, 0x82, 0x43, 0xE7, 0xB5, 0x9B, 0x43,
+ 0xE7, 0xB5, 0xA3, 0x43, 0xE7, 0xB6, 0xA0, 0x43,
+ 0xE7, 0xB6, 0xBE, 0x43, 0xE7, 0xB7, 0x87, 0x43,
+ 0xE7, 0xB7, 0xB4, 0x43, 0xE7, 0xB8, 0x82, 0x43,
+ 0xE7, 0xB8, 0x89, 0x43, 0xE7, 0xB8, 0xB7, 0x43,
+ // Bytes 1140 - 117f
+ 0xE7, 0xB9, 0x81, 0x43, 0xE7, 0xB9, 0x85, 0x43,
+ 0xE7, 0xBC, 0xB6, 0x43, 0xE7, 0xBC, 0xBE, 0x43,
+ 0xE7, 0xBD, 0x91, 0x43, 0xE7, 0xBD, 0xB2, 0x43,
+ 0xE7, 0xBD, 0xB9, 0x43, 0xE7, 0xBD, 0xBA, 0x43,
+ 0xE7, 0xBE, 0x85, 0x43, 0xE7, 0xBE, 0x8A, 0x43,
+ 0xE7, 0xBE, 0x95, 0x43, 0xE7, 0xBE, 0x9A, 0x43,
+ 0xE7, 0xBE, 0xBD, 0x43, 0xE7, 0xBF, 0xBA, 0x43,
+ 0xE8, 0x80, 0x81, 0x43, 0xE8, 0x80, 0x85, 0x43,
+ // Bytes 1180 - 11bf
+ 0xE8, 0x80, 0x8C, 0x43, 0xE8, 0x80, 0x92, 0x43,
+ 0xE8, 0x80, 0xB3, 0x43, 0xE8, 0x81, 0x86, 0x43,
+ 0xE8, 0x81, 0xA0, 0x43, 0xE8, 0x81, 0xAF, 0x43,
+ 0xE8, 0x81, 0xB0, 0x43, 0xE8, 0x81, 0xBE, 0x43,
+ 0xE8, 0x81, 0xBF, 0x43, 0xE8, 0x82, 0x89, 0x43,
+ 0xE8, 0x82, 0x8B, 0x43, 0xE8, 0x82, 0xAD, 0x43,
+ 0xE8, 0x82, 0xB2, 0x43, 0xE8, 0x84, 0x83, 0x43,
+ 0xE8, 0x84, 0xBE, 0x43, 0xE8, 0x87, 0x98, 0x43,
+ // Bytes 11c0 - 11ff
+ 0xE8, 0x87, 0xA3, 0x43, 0xE8, 0x87, 0xA8, 0x43,
+ 0xE8, 0x87, 0xAA, 0x43, 0xE8, 0x87, 0xAD, 0x43,
+ 0xE8, 0x87, 0xB3, 0x43, 0xE8, 0x87, 0xBC, 0x43,
+ 0xE8, 0x88, 0x81, 0x43, 0xE8, 0x88, 0x84, 0x43,
+ 0xE8, 0x88, 0x8C, 0x43, 0xE8, 0x88, 0x98, 0x43,
+ 0xE8, 0x88, 0x9B, 0x43, 0xE8, 0x88, 0x9F, 0x43,
+ 0xE8, 0x89, 0xAE, 0x43, 0xE8, 0x89, 0xAF, 0x43,
+ 0xE8, 0x89, 0xB2, 0x43, 0xE8, 0x89, 0xB8, 0x43,
+ // Bytes 1200 - 123f
+ 0xE8, 0x89, 0xB9, 0x43, 0xE8, 0x8A, 0x8B, 0x43,
+ 0xE8, 0x8A, 0x91, 0x43, 0xE8, 0x8A, 0x9D, 0x43,
+ 0xE8, 0x8A, 0xB1, 0x43, 0xE8, 0x8A, 0xB3, 0x43,
+ 0xE8, 0x8A, 0xBD, 0x43, 0xE8, 0x8B, 0xA5, 0x43,
+ 0xE8, 0x8B, 0xA6, 0x43, 0xE8, 0x8C, 0x9D, 0x43,
+ 0xE8, 0x8C, 0xA3, 0x43, 0xE8, 0x8C, 0xB6, 0x43,
+ 0xE8, 0x8D, 0x92, 0x43, 0xE8, 0x8D, 0x93, 0x43,
+ 0xE8, 0x8D, 0xA3, 0x43, 0xE8, 0x8E, 0xAD, 0x43,
+ // Bytes 1240 - 127f
+ 0xE8, 0x8E, 0xBD, 0x43, 0xE8, 0x8F, 0x89, 0x43,
+ 0xE8, 0x8F, 0x8A, 0x43, 0xE8, 0x8F, 0x8C, 0x43,
+ 0xE8, 0x8F, 0x9C, 0x43, 0xE8, 0x8F, 0xA7, 0x43,
+ 0xE8, 0x8F, 0xAF, 0x43, 0xE8, 0x8F, 0xB1, 0x43,
+ 0xE8, 0x90, 0xBD, 0x43, 0xE8, 0x91, 0x89, 0x43,
+ 0xE8, 0x91, 0x97, 0x43, 0xE8, 0x93, 0xAE, 0x43,
+ 0xE8, 0x93, 0xB1, 0x43, 0xE8, 0x93, 0xB3, 0x43,
+ 0xE8, 0x93, 0xBC, 0x43, 0xE8, 0x94, 0x96, 0x43,
+ // Bytes 1280 - 12bf
+ 0xE8, 0x95, 0xA4, 0x43, 0xE8, 0x97, 0x8D, 0x43,
+ 0xE8, 0x97, 0xBA, 0x43, 0xE8, 0x98, 0x86, 0x43,
+ 0xE8, 0x98, 0x92, 0x43, 0xE8, 0x98, 0xAD, 0x43,
+ 0xE8, 0x98, 0xBF, 0x43, 0xE8, 0x99, 0x8D, 0x43,
+ 0xE8, 0x99, 0x90, 0x43, 0xE8, 0x99, 0x9C, 0x43,
+ 0xE8, 0x99, 0xA7, 0x43, 0xE8, 0x99, 0xA9, 0x43,
+ 0xE8, 0x99, 0xAB, 0x43, 0xE8, 0x9A, 0x88, 0x43,
+ 0xE8, 0x9A, 0xA9, 0x43, 0xE8, 0x9B, 0xA2, 0x43,
+ // Bytes 12c0 - 12ff
+ 0xE8, 0x9C, 0x8E, 0x43, 0xE8, 0x9C, 0xA8, 0x43,
+ 0xE8, 0x9D, 0xAB, 0x43, 0xE8, 0x9D, 0xB9, 0x43,
+ 0xE8, 0x9E, 0x86, 0x43, 0xE8, 0x9E, 0xBA, 0x43,
+ 0xE8, 0x9F, 0xA1, 0x43, 0xE8, 0xA0, 0x81, 0x43,
+ 0xE8, 0xA0, 0x9F, 0x43, 0xE8, 0xA1, 0x80, 0x43,
+ 0xE8, 0xA1, 0x8C, 0x43, 0xE8, 0xA1, 0xA0, 0x43,
+ 0xE8, 0xA1, 0xA3, 0x43, 0xE8, 0xA3, 0x82, 0x43,
+ 0xE8, 0xA3, 0x8F, 0x43, 0xE8, 0xA3, 0x97, 0x43,
+ // Bytes 1300 - 133f
+ 0xE8, 0xA3, 0x9E, 0x43, 0xE8, 0xA3, 0xA1, 0x43,
+ 0xE8, 0xA3, 0xB8, 0x43, 0xE8, 0xA3, 0xBA, 0x43,
+ 0xE8, 0xA4, 0x90, 0x43, 0xE8, 0xA5, 0x81, 0x43,
+ 0xE8, 0xA5, 0xA4, 0x43, 0xE8, 0xA5, 0xBE, 0x43,
+ 0xE8, 0xA6, 0x86, 0x43, 0xE8, 0xA6, 0x8B, 0x43,
+ 0xE8, 0xA6, 0x96, 0x43, 0xE8, 0xA7, 0x92, 0x43,
+ 0xE8, 0xA7, 0xA3, 0x43, 0xE8, 0xA8, 0x80, 0x43,
+ 0xE8, 0xAA, 0xA0, 0x43, 0xE8, 0xAA, 0xAA, 0x43,
+ // Bytes 1340 - 137f
+ 0xE8, 0xAA, 0xBF, 0x43, 0xE8, 0xAB, 0x8B, 0x43,
+ 0xE8, 0xAB, 0x92, 0x43, 0xE8, 0xAB, 0x96, 0x43,
+ 0xE8, 0xAB, 0xAD, 0x43, 0xE8, 0xAB, 0xB8, 0x43,
+ 0xE8, 0xAB, 0xBE, 0x43, 0xE8, 0xAC, 0x81, 0x43,
+ 0xE8, 0xAC, 0xB9, 0x43, 0xE8, 0xAD, 0x98, 0x43,
+ 0xE8, 0xAE, 0x80, 0x43, 0xE8, 0xAE, 0x8A, 0x43,
+ 0xE8, 0xB0, 0xB7, 0x43, 0xE8, 0xB1, 0x86, 0x43,
+ 0xE8, 0xB1, 0x88, 0x43, 0xE8, 0xB1, 0x95, 0x43,
+ // Bytes 1380 - 13bf
+ 0xE8, 0xB1, 0xB8, 0x43, 0xE8, 0xB2, 0x9D, 0x43,
+ 0xE8, 0xB2, 0xA1, 0x43, 0xE8, 0xB2, 0xA9, 0x43,
+ 0xE8, 0xB2, 0xAB, 0x43, 0xE8, 0xB3, 0x81, 0x43,
+ 0xE8, 0xB3, 0x82, 0x43, 0xE8, 0xB3, 0x87, 0x43,
+ 0xE8, 0xB3, 0x88, 0x43, 0xE8, 0xB3, 0x93, 0x43,
+ 0xE8, 0xB4, 0x88, 0x43, 0xE8, 0xB4, 0x9B, 0x43,
+ 0xE8, 0xB5, 0xA4, 0x43, 0xE8, 0xB5, 0xB0, 0x43,
+ 0xE8, 0xB5, 0xB7, 0x43, 0xE8, 0xB6, 0xB3, 0x43,
+ // Bytes 13c0 - 13ff
+ 0xE8, 0xB6, 0xBC, 0x43, 0xE8, 0xB7, 0x8B, 0x43,
+ 0xE8, 0xB7, 0xAF, 0x43, 0xE8, 0xB7, 0xB0, 0x43,
+ 0xE8, 0xBA, 0xAB, 0x43, 0xE8, 0xBB, 0x8A, 0x43,
+ 0xE8, 0xBB, 0x94, 0x43, 0xE8, 0xBC, 0xA6, 0x43,
+ 0xE8, 0xBC, 0xAA, 0x43, 0xE8, 0xBC, 0xB8, 0x43,
+ 0xE8, 0xBC, 0xBB, 0x43, 0xE8, 0xBD, 0xA2, 0x43,
+ 0xE8, 0xBE, 0x9B, 0x43, 0xE8, 0xBE, 0x9E, 0x43,
+ 0xE8, 0xBE, 0xB0, 0x43, 0xE8, 0xBE, 0xB5, 0x43,
+ // Bytes 1400 - 143f
+ 0xE8, 0xBE, 0xB6, 0x43, 0xE9, 0x80, 0xA3, 0x43,
+ 0xE9, 0x80, 0xB8, 0x43, 0xE9, 0x81, 0x8A, 0x43,
+ 0xE9, 0x81, 0xA9, 0x43, 0xE9, 0x81, 0xB2, 0x43,
+ 0xE9, 0x81, 0xBC, 0x43, 0xE9, 0x82, 0x8F, 0x43,
+ 0xE9, 0x82, 0x91, 0x43, 0xE9, 0x82, 0x94, 0x43,
+ 0xE9, 0x83, 0x8E, 0x43, 0xE9, 0x83, 0x9E, 0x43,
+ 0xE9, 0x83, 0xB1, 0x43, 0xE9, 0x83, 0xBD, 0x43,
+ 0xE9, 0x84, 0x91, 0x43, 0xE9, 0x84, 0x9B, 0x43,
+ // Bytes 1440 - 147f
+ 0xE9, 0x85, 0x89, 0x43, 0xE9, 0x85, 0x8D, 0x43,
+ 0xE9, 0x85, 0xAA, 0x43, 0xE9, 0x86, 0x99, 0x43,
+ 0xE9, 0x86, 0xB4, 0x43, 0xE9, 0x87, 0x86, 0x43,
+ 0xE9, 0x87, 0x8C, 0x43, 0xE9, 0x87, 0x8F, 0x43,
+ 0xE9, 0x87, 0x91, 0x43, 0xE9, 0x88, 0xB4, 0x43,
+ 0xE9, 0x88, 0xB8, 0x43, 0xE9, 0x89, 0xB6, 0x43,
+ 0xE9, 0x89, 0xBC, 0x43, 0xE9, 0x8B, 0x97, 0x43,
+ 0xE9, 0x8B, 0x98, 0x43, 0xE9, 0x8C, 0x84, 0x43,
+ // Bytes 1480 - 14bf
+ 0xE9, 0x8D, 0x8A, 0x43, 0xE9, 0x8F, 0xB9, 0x43,
+ 0xE9, 0x90, 0x95, 0x43, 0xE9, 0x95, 0xB7, 0x43,
+ 0xE9, 0x96, 0x80, 0x43, 0xE9, 0x96, 0x8B, 0x43,
+ 0xE9, 0x96, 0xAD, 0x43, 0xE9, 0x96, 0xB7, 0x43,
+ 0xE9, 0x98, 0x9C, 0x43, 0xE9, 0x98, 0xAE, 0x43,
+ 0xE9, 0x99, 0x8B, 0x43, 0xE9, 0x99, 0x8D, 0x43,
+ 0xE9, 0x99, 0xB5, 0x43, 0xE9, 0x99, 0xB8, 0x43,
+ 0xE9, 0x99, 0xBC, 0x43, 0xE9, 0x9A, 0x86, 0x43,
+ // Bytes 14c0 - 14ff
+ 0xE9, 0x9A, 0xA3, 0x43, 0xE9, 0x9A, 0xB6, 0x43,
+ 0xE9, 0x9A, 0xB7, 0x43, 0xE9, 0x9A, 0xB8, 0x43,
+ 0xE9, 0x9A, 0xB9, 0x43, 0xE9, 0x9B, 0x83, 0x43,
+ 0xE9, 0x9B, 0xA2, 0x43, 0xE9, 0x9B, 0xA3, 0x43,
+ 0xE9, 0x9B, 0xA8, 0x43, 0xE9, 0x9B, 0xB6, 0x43,
+ 0xE9, 0x9B, 0xB7, 0x43, 0xE9, 0x9C, 0xA3, 0x43,
+ 0xE9, 0x9C, 0xB2, 0x43, 0xE9, 0x9D, 0x88, 0x43,
+ 0xE9, 0x9D, 0x91, 0x43, 0xE9, 0x9D, 0x96, 0x43,
+ // Bytes 1500 - 153f
+ 0xE9, 0x9D, 0x9E, 0x43, 0xE9, 0x9D, 0xA2, 0x43,
+ 0xE9, 0x9D, 0xA9, 0x43, 0xE9, 0x9F, 0x8B, 0x43,
+ 0xE9, 0x9F, 0x9B, 0x43, 0xE9, 0x9F, 0xA0, 0x43,
+ 0xE9, 0x9F, 0xAD, 0x43, 0xE9, 0x9F, 0xB3, 0x43,
+ 0xE9, 0x9F, 0xBF, 0x43, 0xE9, 0xA0, 0x81, 0x43,
+ 0xE9, 0xA0, 0x85, 0x43, 0xE9, 0xA0, 0x8B, 0x43,
+ 0xE9, 0xA0, 0x98, 0x43, 0xE9, 0xA0, 0xA9, 0x43,
+ 0xE9, 0xA0, 0xBB, 0x43, 0xE9, 0xA1, 0x9E, 0x43,
+ // Bytes 1540 - 157f
+ 0xE9, 0xA2, 0xA8, 0x43, 0xE9, 0xA3, 0x9B, 0x43,
+ 0xE9, 0xA3, 0x9F, 0x43, 0xE9, 0xA3, 0xA2, 0x43,
+ 0xE9, 0xA3, 0xAF, 0x43, 0xE9, 0xA3, 0xBC, 0x43,
+ 0xE9, 0xA4, 0xA8, 0x43, 0xE9, 0xA4, 0xA9, 0x43,
+ 0xE9, 0xA6, 0x96, 0x43, 0xE9, 0xA6, 0x99, 0x43,
+ 0xE9, 0xA6, 0xA7, 0x43, 0xE9, 0xA6, 0xAC, 0x43,
+ 0xE9, 0xA7, 0x82, 0x43, 0xE9, 0xA7, 0xB1, 0x43,
+ 0xE9, 0xA7, 0xBE, 0x43, 0xE9, 0xA9, 0xAA, 0x43,
+ // Bytes 1580 - 15bf
+ 0xE9, 0xAA, 0xA8, 0x43, 0xE9, 0xAB, 0x98, 0x43,
+ 0xE9, 0xAB, 0x9F, 0x43, 0xE9, 0xAC, 0x92, 0x43,
+ 0xE9, 0xAC, 0xA5, 0x43, 0xE9, 0xAC, 0xAF, 0x43,
+ 0xE9, 0xAC, 0xB2, 0x43, 0xE9, 0xAC, 0xBC, 0x43,
+ 0xE9, 0xAD, 0x9A, 0x43, 0xE9, 0xAD, 0xAF, 0x43,
+ 0xE9, 0xB1, 0x80, 0x43, 0xE9, 0xB1, 0x97, 0x43,
+ 0xE9, 0xB3, 0xA5, 0x43, 0xE9, 0xB3, 0xBD, 0x43,
+ 0xE9, 0xB5, 0xA7, 0x43, 0xE9, 0xB6, 0xB4, 0x43,
+ // Bytes 15c0 - 15ff
+ 0xE9, 0xB7, 0xBA, 0x43, 0xE9, 0xB8, 0x9E, 0x43,
+ 0xE9, 0xB9, 0xB5, 0x43, 0xE9, 0xB9, 0xBF, 0x43,
+ 0xE9, 0xBA, 0x97, 0x43, 0xE9, 0xBA, 0x9F, 0x43,
+ 0xE9, 0xBA, 0xA5, 0x43, 0xE9, 0xBA, 0xBB, 0x43,
+ 0xE9, 0xBB, 0x83, 0x43, 0xE9, 0xBB, 0x8D, 0x43,
+ 0xE9, 0xBB, 0x8E, 0x43, 0xE9, 0xBB, 0x91, 0x43,
+ 0xE9, 0xBB, 0xB9, 0x43, 0xE9, 0xBB, 0xBD, 0x43,
+ 0xE9, 0xBB, 0xBE, 0x43, 0xE9, 0xBC, 0x85, 0x43,
+ // Bytes 1600 - 163f
+ 0xE9, 0xBC, 0x8E, 0x43, 0xE9, 0xBC, 0x8F, 0x43,
+ 0xE9, 0xBC, 0x93, 0x43, 0xE9, 0xBC, 0x96, 0x43,
+ 0xE9, 0xBC, 0xA0, 0x43, 0xE9, 0xBC, 0xBB, 0x43,
+ 0xE9, 0xBD, 0x83, 0x43, 0xE9, 0xBD, 0x8A, 0x43,
+ 0xE9, 0xBD, 0x92, 0x43, 0xE9, 0xBE, 0x8D, 0x43,
+ 0xE9, 0xBE, 0x8E, 0x43, 0xE9, 0xBE, 0x9C, 0x43,
+ 0xE9, 0xBE, 0x9F, 0x43, 0xE9, 0xBE, 0xA0, 0x43,
+ 0xEA, 0x9C, 0xA7, 0x43, 0xEA, 0x9D, 0xAF, 0x43,
+ // Bytes 1640 - 167f
+ 0xEA, 0xAC, 0xB7, 0x43, 0xEA, 0xAD, 0x92, 0x44,
+ 0xF0, 0xA0, 0x84, 0xA2, 0x44, 0xF0, 0xA0, 0x94,
+ 0x9C, 0x44, 0xF0, 0xA0, 0x94, 0xA5, 0x44, 0xF0,
+ 0xA0, 0x95, 0x8B, 0x44, 0xF0, 0xA0, 0x98, 0xBA,
+ 0x44, 0xF0, 0xA0, 0xA0, 0x84, 0x44, 0xF0, 0xA0,
+ 0xA3, 0x9E, 0x44, 0xF0, 0xA0, 0xA8, 0xAC, 0x44,
+ 0xF0, 0xA0, 0xAD, 0xA3, 0x44, 0xF0, 0xA1, 0x93,
+ 0xA4, 0x44, 0xF0, 0xA1, 0x9A, 0xA8, 0x44, 0xF0,
+ // Bytes 1680 - 16bf
+ 0xA1, 0x9B, 0xAA, 0x44, 0xF0, 0xA1, 0xA7, 0x88,
+ 0x44, 0xF0, 0xA1, 0xAC, 0x98, 0x44, 0xF0, 0xA1,
+ 0xB4, 0x8B, 0x44, 0xF0, 0xA1, 0xB7, 0xA4, 0x44,
+ 0xF0, 0xA1, 0xB7, 0xA6, 0x44, 0xF0, 0xA2, 0x86,
+ 0x83, 0x44, 0xF0, 0xA2, 0x86, 0x9F, 0x44, 0xF0,
+ 0xA2, 0x8C, 0xB1, 0x44, 0xF0, 0xA2, 0x9B, 0x94,
+ 0x44, 0xF0, 0xA2, 0xA1, 0x84, 0x44, 0xF0, 0xA2,
+ 0xA1, 0x8A, 0x44, 0xF0, 0xA2, 0xAC, 0x8C, 0x44,
+ // Bytes 16c0 - 16ff
+ 0xF0, 0xA2, 0xAF, 0xB1, 0x44, 0xF0, 0xA3, 0x80,
+ 0x8A, 0x44, 0xF0, 0xA3, 0x8A, 0xB8, 0x44, 0xF0,
+ 0xA3, 0x8D, 0x9F, 0x44, 0xF0, 0xA3, 0x8E, 0x93,
+ 0x44, 0xF0, 0xA3, 0x8E, 0x9C, 0x44, 0xF0, 0xA3,
+ 0x8F, 0x83, 0x44, 0xF0, 0xA3, 0x8F, 0x95, 0x44,
+ 0xF0, 0xA3, 0x91, 0xAD, 0x44, 0xF0, 0xA3, 0x9A,
+ 0xA3, 0x44, 0xF0, 0xA3, 0xA2, 0xA7, 0x44, 0xF0,
+ 0xA3, 0xAA, 0x8D, 0x44, 0xF0, 0xA3, 0xAB, 0xBA,
+ // Bytes 1700 - 173f
+ 0x44, 0xF0, 0xA3, 0xB2, 0xBC, 0x44, 0xF0, 0xA3,
+ 0xB4, 0x9E, 0x44, 0xF0, 0xA3, 0xBB, 0x91, 0x44,
+ 0xF0, 0xA3, 0xBD, 0x9E, 0x44, 0xF0, 0xA3, 0xBE,
+ 0x8E, 0x44, 0xF0, 0xA4, 0x89, 0xA3, 0x44, 0xF0,
+ 0xA4, 0x8B, 0xAE, 0x44, 0xF0, 0xA4, 0x8E, 0xAB,
+ 0x44, 0xF0, 0xA4, 0x98, 0x88, 0x44, 0xF0, 0xA4,
+ 0x9C, 0xB5, 0x44, 0xF0, 0xA4, 0xA0, 0x94, 0x44,
+ 0xF0, 0xA4, 0xB0, 0xB6, 0x44, 0xF0, 0xA4, 0xB2,
+ // Bytes 1740 - 177f
+ 0x92, 0x44, 0xF0, 0xA4, 0xBE, 0xA1, 0x44, 0xF0,
+ 0xA4, 0xBE, 0xB8, 0x44, 0xF0, 0xA5, 0x81, 0x84,
+ 0x44, 0xF0, 0xA5, 0x83, 0xB2, 0x44, 0xF0, 0xA5,
+ 0x83, 0xB3, 0x44, 0xF0, 0xA5, 0x84, 0x99, 0x44,
+ 0xF0, 0xA5, 0x84, 0xB3, 0x44, 0xF0, 0xA5, 0x89,
+ 0x89, 0x44, 0xF0, 0xA5, 0x90, 0x9D, 0x44, 0xF0,
+ 0xA5, 0x98, 0xA6, 0x44, 0xF0, 0xA5, 0x9A, 0x9A,
+ 0x44, 0xF0, 0xA5, 0x9B, 0x85, 0x44, 0xF0, 0xA5,
+ // Bytes 1780 - 17bf
+ 0xA5, 0xBC, 0x44, 0xF0, 0xA5, 0xAA, 0xA7, 0x44,
+ 0xF0, 0xA5, 0xAE, 0xAB, 0x44, 0xF0, 0xA5, 0xB2,
+ 0x80, 0x44, 0xF0, 0xA5, 0xB3, 0x90, 0x44, 0xF0,
+ 0xA5, 0xBE, 0x86, 0x44, 0xF0, 0xA6, 0x87, 0x9A,
+ 0x44, 0xF0, 0xA6, 0x88, 0xA8, 0x44, 0xF0, 0xA6,
+ 0x89, 0x87, 0x44, 0xF0, 0xA6, 0x8B, 0x99, 0x44,
+ 0xF0, 0xA6, 0x8C, 0xBE, 0x44, 0xF0, 0xA6, 0x93,
+ 0x9A, 0x44, 0xF0, 0xA6, 0x94, 0xA3, 0x44, 0xF0,
+ // Bytes 17c0 - 17ff
+ 0xA6, 0x96, 0xA8, 0x44, 0xF0, 0xA6, 0x9E, 0xA7,
+ 0x44, 0xF0, 0xA6, 0x9E, 0xB5, 0x44, 0xF0, 0xA6,
+ 0xAC, 0xBC, 0x44, 0xF0, 0xA6, 0xB0, 0xB6, 0x44,
+ 0xF0, 0xA6, 0xB3, 0x95, 0x44, 0xF0, 0xA6, 0xB5,
+ 0xAB, 0x44, 0xF0, 0xA6, 0xBC, 0xAC, 0x44, 0xF0,
+ 0xA6, 0xBE, 0xB1, 0x44, 0xF0, 0xA7, 0x83, 0x92,
+ 0x44, 0xF0, 0xA7, 0x8F, 0x8A, 0x44, 0xF0, 0xA7,
+ 0x99, 0xA7, 0x44, 0xF0, 0xA7, 0xA2, 0xAE, 0x44,
+ // Bytes 1800 - 183f
+ 0xF0, 0xA7, 0xA5, 0xA6, 0x44, 0xF0, 0xA7, 0xB2,
+ 0xA8, 0x44, 0xF0, 0xA7, 0xBB, 0x93, 0x44, 0xF0,
+ 0xA7, 0xBC, 0xAF, 0x44, 0xF0, 0xA8, 0x97, 0x92,
+ 0x44, 0xF0, 0xA8, 0x97, 0xAD, 0x44, 0xF0, 0xA8,
+ 0x9C, 0xAE, 0x44, 0xF0, 0xA8, 0xAF, 0xBA, 0x44,
+ 0xF0, 0xA8, 0xB5, 0xB7, 0x44, 0xF0, 0xA9, 0x85,
+ 0x85, 0x44, 0xF0, 0xA9, 0x87, 0x9F, 0x44, 0xF0,
+ 0xA9, 0x88, 0x9A, 0x44, 0xF0, 0xA9, 0x90, 0x8A,
+ // Bytes 1840 - 187f
+ 0x44, 0xF0, 0xA9, 0x92, 0x96, 0x44, 0xF0, 0xA9,
+ 0x96, 0xB6, 0x44, 0xF0, 0xA9, 0xAC, 0xB0, 0x44,
+ 0xF0, 0xAA, 0x83, 0x8E, 0x44, 0xF0, 0xAA, 0x84,
+ 0x85, 0x44, 0xF0, 0xAA, 0x88, 0x8E, 0x44, 0xF0,
+ 0xAA, 0x8A, 0x91, 0x44, 0xF0, 0xAA, 0x8E, 0x92,
+ 0x44, 0xF0, 0xAA, 0x98, 0x80, 0x42, 0x21, 0x21,
+ 0x42, 0x21, 0x3F, 0x42, 0x2E, 0x2E, 0x42, 0x30,
+ 0x2C, 0x42, 0x30, 0x2E, 0x42, 0x31, 0x2C, 0x42,
+ // Bytes 1880 - 18bf
+ 0x31, 0x2E, 0x42, 0x31, 0x30, 0x42, 0x31, 0x31,
+ 0x42, 0x31, 0x32, 0x42, 0x31, 0x33, 0x42, 0x31,
+ 0x34, 0x42, 0x31, 0x35, 0x42, 0x31, 0x36, 0x42,
+ 0x31, 0x37, 0x42, 0x31, 0x38, 0x42, 0x31, 0x39,
+ 0x42, 0x32, 0x2C, 0x42, 0x32, 0x2E, 0x42, 0x32,
+ 0x30, 0x42, 0x32, 0x31, 0x42, 0x32, 0x32, 0x42,
+ 0x32, 0x33, 0x42, 0x32, 0x34, 0x42, 0x32, 0x35,
+ 0x42, 0x32, 0x36, 0x42, 0x32, 0x37, 0x42, 0x32,
+ // Bytes 18c0 - 18ff
+ 0x38, 0x42, 0x32, 0x39, 0x42, 0x33, 0x2C, 0x42,
+ 0x33, 0x2E, 0x42, 0x33, 0x30, 0x42, 0x33, 0x31,
+ 0x42, 0x33, 0x32, 0x42, 0x33, 0x33, 0x42, 0x33,
+ 0x34, 0x42, 0x33, 0x35, 0x42, 0x33, 0x36, 0x42,
+ 0x33, 0x37, 0x42, 0x33, 0x38, 0x42, 0x33, 0x39,
+ 0x42, 0x34, 0x2C, 0x42, 0x34, 0x2E, 0x42, 0x34,
+ 0x30, 0x42, 0x34, 0x31, 0x42, 0x34, 0x32, 0x42,
+ 0x34, 0x33, 0x42, 0x34, 0x34, 0x42, 0x34, 0x35,
+ // Bytes 1900 - 193f
+ 0x42, 0x34, 0x36, 0x42, 0x34, 0x37, 0x42, 0x34,
+ 0x38, 0x42, 0x34, 0x39, 0x42, 0x35, 0x2C, 0x42,
+ 0x35, 0x2E, 0x42, 0x35, 0x30, 0x42, 0x36, 0x2C,
+ 0x42, 0x36, 0x2E, 0x42, 0x37, 0x2C, 0x42, 0x37,
+ 0x2E, 0x42, 0x38, 0x2C, 0x42, 0x38, 0x2E, 0x42,
+ 0x39, 0x2C, 0x42, 0x39, 0x2E, 0x42, 0x3D, 0x3D,
+ 0x42, 0x3F, 0x21, 0x42, 0x3F, 0x3F, 0x42, 0x41,
+ 0x55, 0x42, 0x42, 0x71, 0x42, 0x43, 0x44, 0x42,
+ // Bytes 1940 - 197f
+ 0x44, 0x4A, 0x42, 0x44, 0x5A, 0x42, 0x44, 0x7A,
+ 0x42, 0x47, 0x42, 0x42, 0x47, 0x79, 0x42, 0x48,
+ 0x50, 0x42, 0x48, 0x56, 0x42, 0x48, 0x67, 0x42,
+ 0x48, 0x7A, 0x42, 0x49, 0x49, 0x42, 0x49, 0x4A,
+ 0x42, 0x49, 0x55, 0x42, 0x49, 0x56, 0x42, 0x49,
+ 0x58, 0x42, 0x4B, 0x42, 0x42, 0x4B, 0x4B, 0x42,
+ 0x4B, 0x4D, 0x42, 0x4C, 0x4A, 0x42, 0x4C, 0x6A,
+ 0x42, 0x4D, 0x42, 0x42, 0x4D, 0x43, 0x42, 0x4D,
+ // Bytes 1980 - 19bf
+ 0x44, 0x42, 0x4D, 0x56, 0x42, 0x4D, 0x57, 0x42,
+ 0x4E, 0x4A, 0x42, 0x4E, 0x6A, 0x42, 0x4E, 0x6F,
+ 0x42, 0x50, 0x48, 0x42, 0x50, 0x52, 0x42, 0x50,
+ 0x61, 0x42, 0x52, 0x73, 0x42, 0x53, 0x44, 0x42,
+ 0x53, 0x4D, 0x42, 0x53, 0x53, 0x42, 0x53, 0x76,
+ 0x42, 0x54, 0x4D, 0x42, 0x56, 0x49, 0x42, 0x57,
+ 0x43, 0x42, 0x57, 0x5A, 0x42, 0x57, 0x62, 0x42,
+ 0x58, 0x49, 0x42, 0x63, 0x63, 0x42, 0x63, 0x64,
+ // Bytes 19c0 - 19ff
+ 0x42, 0x63, 0x6D, 0x42, 0x64, 0x42, 0x42, 0x64,
+ 0x61, 0x42, 0x64, 0x6C, 0x42, 0x64, 0x6D, 0x42,
+ 0x64, 0x7A, 0x42, 0x65, 0x56, 0x42, 0x66, 0x66,
+ 0x42, 0x66, 0x69, 0x42, 0x66, 0x6C, 0x42, 0x66,
+ 0x6D, 0x42, 0x68, 0x61, 0x42, 0x69, 0x69, 0x42,
+ 0x69, 0x6A, 0x42, 0x69, 0x6E, 0x42, 0x69, 0x76,
+ 0x42, 0x69, 0x78, 0x42, 0x6B, 0x41, 0x42, 0x6B,
+ 0x56, 0x42, 0x6B, 0x57, 0x42, 0x6B, 0x67, 0x42,
+ // Bytes 1a00 - 1a3f
+ 0x6B, 0x6C, 0x42, 0x6B, 0x6D, 0x42, 0x6B, 0x74,
+ 0x42, 0x6C, 0x6A, 0x42, 0x6C, 0x6D, 0x42, 0x6C,
+ 0x6E, 0x42, 0x6C, 0x78, 0x42, 0x6D, 0x32, 0x42,
+ 0x6D, 0x33, 0x42, 0x6D, 0x41, 0x42, 0x6D, 0x56,
+ 0x42, 0x6D, 0x57, 0x42, 0x6D, 0x62, 0x42, 0x6D,
+ 0x67, 0x42, 0x6D, 0x6C, 0x42, 0x6D, 0x6D, 0x42,
+ 0x6D, 0x73, 0x42, 0x6E, 0x41, 0x42, 0x6E, 0x46,
+ 0x42, 0x6E, 0x56, 0x42, 0x6E, 0x57, 0x42, 0x6E,
+ // Bytes 1a40 - 1a7f
+ 0x6A, 0x42, 0x6E, 0x6D, 0x42, 0x6E, 0x73, 0x42,
+ 0x6F, 0x56, 0x42, 0x70, 0x41, 0x42, 0x70, 0x46,
+ 0x42, 0x70, 0x56, 0x42, 0x70, 0x57, 0x42, 0x70,
+ 0x63, 0x42, 0x70, 0x73, 0x42, 0x73, 0x72, 0x42,
+ 0x73, 0x74, 0x42, 0x76, 0x69, 0x42, 0x78, 0x69,
+ 0x43, 0x28, 0x31, 0x29, 0x43, 0x28, 0x32, 0x29,
+ 0x43, 0x28, 0x33, 0x29, 0x43, 0x28, 0x34, 0x29,
+ 0x43, 0x28, 0x35, 0x29, 0x43, 0x28, 0x36, 0x29,
+ // Bytes 1a80 - 1abf
+ 0x43, 0x28, 0x37, 0x29, 0x43, 0x28, 0x38, 0x29,
+ 0x43, 0x28, 0x39, 0x29, 0x43, 0x28, 0x41, 0x29,
+ 0x43, 0x28, 0x42, 0x29, 0x43, 0x28, 0x43, 0x29,
+ 0x43, 0x28, 0x44, 0x29, 0x43, 0x28, 0x45, 0x29,
+ 0x43, 0x28, 0x46, 0x29, 0x43, 0x28, 0x47, 0x29,
+ 0x43, 0x28, 0x48, 0x29, 0x43, 0x28, 0x49, 0x29,
+ 0x43, 0x28, 0x4A, 0x29, 0x43, 0x28, 0x4B, 0x29,
+ 0x43, 0x28, 0x4C, 0x29, 0x43, 0x28, 0x4D, 0x29,
+ // Bytes 1ac0 - 1aff
+ 0x43, 0x28, 0x4E, 0x29, 0x43, 0x28, 0x4F, 0x29,
+ 0x43, 0x28, 0x50, 0x29, 0x43, 0x28, 0x51, 0x29,
+ 0x43, 0x28, 0x52, 0x29, 0x43, 0x28, 0x53, 0x29,
+ 0x43, 0x28, 0x54, 0x29, 0x43, 0x28, 0x55, 0x29,
+ 0x43, 0x28, 0x56, 0x29, 0x43, 0x28, 0x57, 0x29,
+ 0x43, 0x28, 0x58, 0x29, 0x43, 0x28, 0x59, 0x29,
+ 0x43, 0x28, 0x5A, 0x29, 0x43, 0x28, 0x61, 0x29,
+ 0x43, 0x28, 0x62, 0x29, 0x43, 0x28, 0x63, 0x29,
+ // Bytes 1b00 - 1b3f
+ 0x43, 0x28, 0x64, 0x29, 0x43, 0x28, 0x65, 0x29,
+ 0x43, 0x28, 0x66, 0x29, 0x43, 0x28, 0x67, 0x29,
+ 0x43, 0x28, 0x68, 0x29, 0x43, 0x28, 0x69, 0x29,
+ 0x43, 0x28, 0x6A, 0x29, 0x43, 0x28, 0x6B, 0x29,
+ 0x43, 0x28, 0x6C, 0x29, 0x43, 0x28, 0x6D, 0x29,
+ 0x43, 0x28, 0x6E, 0x29, 0x43, 0x28, 0x6F, 0x29,
+ 0x43, 0x28, 0x70, 0x29, 0x43, 0x28, 0x71, 0x29,
+ 0x43, 0x28, 0x72, 0x29, 0x43, 0x28, 0x73, 0x29,
+ // Bytes 1b40 - 1b7f
+ 0x43, 0x28, 0x74, 0x29, 0x43, 0x28, 0x75, 0x29,
+ 0x43, 0x28, 0x76, 0x29, 0x43, 0x28, 0x77, 0x29,
+ 0x43, 0x28, 0x78, 0x29, 0x43, 0x28, 0x79, 0x29,
+ 0x43, 0x28, 0x7A, 0x29, 0x43, 0x2E, 0x2E, 0x2E,
+ 0x43, 0x31, 0x30, 0x2E, 0x43, 0x31, 0x31, 0x2E,
+ 0x43, 0x31, 0x32, 0x2E, 0x43, 0x31, 0x33, 0x2E,
+ 0x43, 0x31, 0x34, 0x2E, 0x43, 0x31, 0x35, 0x2E,
+ 0x43, 0x31, 0x36, 0x2E, 0x43, 0x31, 0x37, 0x2E,
+ // Bytes 1b80 - 1bbf
+ 0x43, 0x31, 0x38, 0x2E, 0x43, 0x31, 0x39, 0x2E,
+ 0x43, 0x32, 0x30, 0x2E, 0x43, 0x3A, 0x3A, 0x3D,
+ 0x43, 0x3D, 0x3D, 0x3D, 0x43, 0x43, 0x6F, 0x2E,
+ 0x43, 0x46, 0x41, 0x58, 0x43, 0x47, 0x48, 0x7A,
+ 0x43, 0x47, 0x50, 0x61, 0x43, 0x49, 0x49, 0x49,
+ 0x43, 0x4C, 0x54, 0x44, 0x43, 0x4C, 0xC2, 0xB7,
+ 0x43, 0x4D, 0x48, 0x7A, 0x43, 0x4D, 0x50, 0x61,
+ 0x43, 0x4D, 0xCE, 0xA9, 0x43, 0x50, 0x50, 0x4D,
+ // Bytes 1bc0 - 1bff
+ 0x43, 0x50, 0x50, 0x56, 0x43, 0x50, 0x54, 0x45,
+ 0x43, 0x54, 0x45, 0x4C, 0x43, 0x54, 0x48, 0x7A,
+ 0x43, 0x56, 0x49, 0x49, 0x43, 0x58, 0x49, 0x49,
+ 0x43, 0x61, 0x2F, 0x63, 0x43, 0x61, 0x2F, 0x73,
+ 0x43, 0x61, 0xCA, 0xBE, 0x43, 0x62, 0x61, 0x72,
+ 0x43, 0x63, 0x2F, 0x6F, 0x43, 0x63, 0x2F, 0x75,
+ 0x43, 0x63, 0x61, 0x6C, 0x43, 0x63, 0x6D, 0x32,
+ 0x43, 0x63, 0x6D, 0x33, 0x43, 0x64, 0x6D, 0x32,
+ // Bytes 1c00 - 1c3f
+ 0x43, 0x64, 0x6D, 0x33, 0x43, 0x65, 0x72, 0x67,
+ 0x43, 0x66, 0x66, 0x69, 0x43, 0x66, 0x66, 0x6C,
+ 0x43, 0x67, 0x61, 0x6C, 0x43, 0x68, 0x50, 0x61,
+ 0x43, 0x69, 0x69, 0x69, 0x43, 0x6B, 0x48, 0x7A,
+ 0x43, 0x6B, 0x50, 0x61, 0x43, 0x6B, 0x6D, 0x32,
+ 0x43, 0x6B, 0x6D, 0x33, 0x43, 0x6B, 0xCE, 0xA9,
+ 0x43, 0x6C, 0x6F, 0x67, 0x43, 0x6C, 0xC2, 0xB7,
+ 0x43, 0x6D, 0x69, 0x6C, 0x43, 0x6D, 0x6D, 0x32,
+ // Bytes 1c40 - 1c7f
+ 0x43, 0x6D, 0x6D, 0x33, 0x43, 0x6D, 0x6F, 0x6C,
+ 0x43, 0x72, 0x61, 0x64, 0x43, 0x76, 0x69, 0x69,
+ 0x43, 0x78, 0x69, 0x69, 0x43, 0xC2, 0xB0, 0x43,
+ 0x43, 0xC2, 0xB0, 0x46, 0x43, 0xCA, 0xBC, 0x6E,
+ 0x43, 0xCE, 0xBC, 0x41, 0x43, 0xCE, 0xBC, 0x46,
+ 0x43, 0xCE, 0xBC, 0x56, 0x43, 0xCE, 0xBC, 0x57,
+ 0x43, 0xCE, 0xBC, 0x67, 0x43, 0xCE, 0xBC, 0x6C,
+ 0x43, 0xCE, 0xBC, 0x6D, 0x43, 0xCE, 0xBC, 0x73,
+ // Bytes 1c80 - 1cbf
+ 0x44, 0x28, 0x31, 0x30, 0x29, 0x44, 0x28, 0x31,
+ 0x31, 0x29, 0x44, 0x28, 0x31, 0x32, 0x29, 0x44,
+ 0x28, 0x31, 0x33, 0x29, 0x44, 0x28, 0x31, 0x34,
+ 0x29, 0x44, 0x28, 0x31, 0x35, 0x29, 0x44, 0x28,
+ 0x31, 0x36, 0x29, 0x44, 0x28, 0x31, 0x37, 0x29,
+ 0x44, 0x28, 0x31, 0x38, 0x29, 0x44, 0x28, 0x31,
+ 0x39, 0x29, 0x44, 0x28, 0x32, 0x30, 0x29, 0x44,
+ 0x30, 0xE7, 0x82, 0xB9, 0x44, 0x31, 0xE2, 0x81,
+ // Bytes 1cc0 - 1cff
+ 0x84, 0x44, 0x31, 0xE6, 0x97, 0xA5, 0x44, 0x31,
+ 0xE6, 0x9C, 0x88, 0x44, 0x31, 0xE7, 0x82, 0xB9,
+ 0x44, 0x32, 0xE6, 0x97, 0xA5, 0x44, 0x32, 0xE6,
+ 0x9C, 0x88, 0x44, 0x32, 0xE7, 0x82, 0xB9, 0x44,
+ 0x33, 0xE6, 0x97, 0xA5, 0x44, 0x33, 0xE6, 0x9C,
+ 0x88, 0x44, 0x33, 0xE7, 0x82, 0xB9, 0x44, 0x34,
+ 0xE6, 0x97, 0xA5, 0x44, 0x34, 0xE6, 0x9C, 0x88,
+ 0x44, 0x34, 0xE7, 0x82, 0xB9, 0x44, 0x35, 0xE6,
+ // Bytes 1d00 - 1d3f
+ 0x97, 0xA5, 0x44, 0x35, 0xE6, 0x9C, 0x88, 0x44,
+ 0x35, 0xE7, 0x82, 0xB9, 0x44, 0x36, 0xE6, 0x97,
+ 0xA5, 0x44, 0x36, 0xE6, 0x9C, 0x88, 0x44, 0x36,
+ 0xE7, 0x82, 0xB9, 0x44, 0x37, 0xE6, 0x97, 0xA5,
+ 0x44, 0x37, 0xE6, 0x9C, 0x88, 0x44, 0x37, 0xE7,
+ 0x82, 0xB9, 0x44, 0x38, 0xE6, 0x97, 0xA5, 0x44,
+ 0x38, 0xE6, 0x9C, 0x88, 0x44, 0x38, 0xE7, 0x82,
+ 0xB9, 0x44, 0x39, 0xE6, 0x97, 0xA5, 0x44, 0x39,
+ // Bytes 1d40 - 1d7f
+ 0xE6, 0x9C, 0x88, 0x44, 0x39, 0xE7, 0x82, 0xB9,
+ 0x44, 0x56, 0x49, 0x49, 0x49, 0x44, 0x61, 0x2E,
+ 0x6D, 0x2E, 0x44, 0x6B, 0x63, 0x61, 0x6C, 0x44,
+ 0x70, 0x2E, 0x6D, 0x2E, 0x44, 0x76, 0x69, 0x69,
+ 0x69, 0x44, 0xD5, 0xA5, 0xD6, 0x82, 0x44, 0xD5,
+ 0xB4, 0xD5, 0xA5, 0x44, 0xD5, 0xB4, 0xD5, 0xAB,
+ 0x44, 0xD5, 0xB4, 0xD5, 0xAD, 0x44, 0xD5, 0xB4,
+ 0xD5, 0xB6, 0x44, 0xD5, 0xBE, 0xD5, 0xB6, 0x44,
+ // Bytes 1d80 - 1dbf
+ 0xD7, 0x90, 0xD7, 0x9C, 0x44, 0xD8, 0xA7, 0xD9,
+ 0xB4, 0x44, 0xD8, 0xA8, 0xD8, 0xAC, 0x44, 0xD8,
+ 0xA8, 0xD8, 0xAD, 0x44, 0xD8, 0xA8, 0xD8, 0xAE,
+ 0x44, 0xD8, 0xA8, 0xD8, 0xB1, 0x44, 0xD8, 0xA8,
+ 0xD8, 0xB2, 0x44, 0xD8, 0xA8, 0xD9, 0x85, 0x44,
+ 0xD8, 0xA8, 0xD9, 0x86, 0x44, 0xD8, 0xA8, 0xD9,
+ 0x87, 0x44, 0xD8, 0xA8, 0xD9, 0x89, 0x44, 0xD8,
+ 0xA8, 0xD9, 0x8A, 0x44, 0xD8, 0xAA, 0xD8, 0xAC,
+ // Bytes 1dc0 - 1dff
+ 0x44, 0xD8, 0xAA, 0xD8, 0xAD, 0x44, 0xD8, 0xAA,
+ 0xD8, 0xAE, 0x44, 0xD8, 0xAA, 0xD8, 0xB1, 0x44,
+ 0xD8, 0xAA, 0xD8, 0xB2, 0x44, 0xD8, 0xAA, 0xD9,
+ 0x85, 0x44, 0xD8, 0xAA, 0xD9, 0x86, 0x44, 0xD8,
+ 0xAA, 0xD9, 0x87, 0x44, 0xD8, 0xAA, 0xD9, 0x89,
+ 0x44, 0xD8, 0xAA, 0xD9, 0x8A, 0x44, 0xD8, 0xAB,
+ 0xD8, 0xAC, 0x44, 0xD8, 0xAB, 0xD8, 0xB1, 0x44,
+ 0xD8, 0xAB, 0xD8, 0xB2, 0x44, 0xD8, 0xAB, 0xD9,
+ // Bytes 1e00 - 1e3f
+ 0x85, 0x44, 0xD8, 0xAB, 0xD9, 0x86, 0x44, 0xD8,
+ 0xAB, 0xD9, 0x87, 0x44, 0xD8, 0xAB, 0xD9, 0x89,
+ 0x44, 0xD8, 0xAB, 0xD9, 0x8A, 0x44, 0xD8, 0xAC,
+ 0xD8, 0xAD, 0x44, 0xD8, 0xAC, 0xD9, 0x85, 0x44,
+ 0xD8, 0xAC, 0xD9, 0x89, 0x44, 0xD8, 0xAC, 0xD9,
+ 0x8A, 0x44, 0xD8, 0xAD, 0xD8, 0xAC, 0x44, 0xD8,
+ 0xAD, 0xD9, 0x85, 0x44, 0xD8, 0xAD, 0xD9, 0x89,
+ 0x44, 0xD8, 0xAD, 0xD9, 0x8A, 0x44, 0xD8, 0xAE,
+ // Bytes 1e40 - 1e7f
+ 0xD8, 0xAC, 0x44, 0xD8, 0xAE, 0xD8, 0xAD, 0x44,
+ 0xD8, 0xAE, 0xD9, 0x85, 0x44, 0xD8, 0xAE, 0xD9,
+ 0x89, 0x44, 0xD8, 0xAE, 0xD9, 0x8A, 0x44, 0xD8,
+ 0xB3, 0xD8, 0xAC, 0x44, 0xD8, 0xB3, 0xD8, 0xAD,
+ 0x44, 0xD8, 0xB3, 0xD8, 0xAE, 0x44, 0xD8, 0xB3,
+ 0xD8, 0xB1, 0x44, 0xD8, 0xB3, 0xD9, 0x85, 0x44,
+ 0xD8, 0xB3, 0xD9, 0x87, 0x44, 0xD8, 0xB3, 0xD9,
+ 0x89, 0x44, 0xD8, 0xB3, 0xD9, 0x8A, 0x44, 0xD8,
+ // Bytes 1e80 - 1ebf
+ 0xB4, 0xD8, 0xAC, 0x44, 0xD8, 0xB4, 0xD8, 0xAD,
+ 0x44, 0xD8, 0xB4, 0xD8, 0xAE, 0x44, 0xD8, 0xB4,
+ 0xD8, 0xB1, 0x44, 0xD8, 0xB4, 0xD9, 0x85, 0x44,
+ 0xD8, 0xB4, 0xD9, 0x87, 0x44, 0xD8, 0xB4, 0xD9,
+ 0x89, 0x44, 0xD8, 0xB4, 0xD9, 0x8A, 0x44, 0xD8,
+ 0xB5, 0xD8, 0xAD, 0x44, 0xD8, 0xB5, 0xD8, 0xAE,
+ 0x44, 0xD8, 0xB5, 0xD8, 0xB1, 0x44, 0xD8, 0xB5,
+ 0xD9, 0x85, 0x44, 0xD8, 0xB5, 0xD9, 0x89, 0x44,
+ // Bytes 1ec0 - 1eff
+ 0xD8, 0xB5, 0xD9, 0x8A, 0x44, 0xD8, 0xB6, 0xD8,
+ 0xAC, 0x44, 0xD8, 0xB6, 0xD8, 0xAD, 0x44, 0xD8,
+ 0xB6, 0xD8, 0xAE, 0x44, 0xD8, 0xB6, 0xD8, 0xB1,
+ 0x44, 0xD8, 0xB6, 0xD9, 0x85, 0x44, 0xD8, 0xB6,
+ 0xD9, 0x89, 0x44, 0xD8, 0xB6, 0xD9, 0x8A, 0x44,
+ 0xD8, 0xB7, 0xD8, 0xAD, 0x44, 0xD8, 0xB7, 0xD9,
+ 0x85, 0x44, 0xD8, 0xB7, 0xD9, 0x89, 0x44, 0xD8,
+ 0xB7, 0xD9, 0x8A, 0x44, 0xD8, 0xB8, 0xD9, 0x85,
+ // Bytes 1f00 - 1f3f
+ 0x44, 0xD8, 0xB9, 0xD8, 0xAC, 0x44, 0xD8, 0xB9,
+ 0xD9, 0x85, 0x44, 0xD8, 0xB9, 0xD9, 0x89, 0x44,
+ 0xD8, 0xB9, 0xD9, 0x8A, 0x44, 0xD8, 0xBA, 0xD8,
+ 0xAC, 0x44, 0xD8, 0xBA, 0xD9, 0x85, 0x44, 0xD8,
+ 0xBA, 0xD9, 0x89, 0x44, 0xD8, 0xBA, 0xD9, 0x8A,
+ 0x44, 0xD9, 0x81, 0xD8, 0xAC, 0x44, 0xD9, 0x81,
+ 0xD8, 0xAD, 0x44, 0xD9, 0x81, 0xD8, 0xAE, 0x44,
+ 0xD9, 0x81, 0xD9, 0x85, 0x44, 0xD9, 0x81, 0xD9,
+ // Bytes 1f40 - 1f7f
+ 0x89, 0x44, 0xD9, 0x81, 0xD9, 0x8A, 0x44, 0xD9,
+ 0x82, 0xD8, 0xAD, 0x44, 0xD9, 0x82, 0xD9, 0x85,
+ 0x44, 0xD9, 0x82, 0xD9, 0x89, 0x44, 0xD9, 0x82,
+ 0xD9, 0x8A, 0x44, 0xD9, 0x83, 0xD8, 0xA7, 0x44,
+ 0xD9, 0x83, 0xD8, 0xAC, 0x44, 0xD9, 0x83, 0xD8,
+ 0xAD, 0x44, 0xD9, 0x83, 0xD8, 0xAE, 0x44, 0xD9,
+ 0x83, 0xD9, 0x84, 0x44, 0xD9, 0x83, 0xD9, 0x85,
+ 0x44, 0xD9, 0x83, 0xD9, 0x89, 0x44, 0xD9, 0x83,
+ // Bytes 1f80 - 1fbf
+ 0xD9, 0x8A, 0x44, 0xD9, 0x84, 0xD8, 0xA7, 0x44,
+ 0xD9, 0x84, 0xD8, 0xAC, 0x44, 0xD9, 0x84, 0xD8,
+ 0xAD, 0x44, 0xD9, 0x84, 0xD8, 0xAE, 0x44, 0xD9,
+ 0x84, 0xD9, 0x85, 0x44, 0xD9, 0x84, 0xD9, 0x87,
+ 0x44, 0xD9, 0x84, 0xD9, 0x89, 0x44, 0xD9, 0x84,
+ 0xD9, 0x8A, 0x44, 0xD9, 0x85, 0xD8, 0xA7, 0x44,
+ 0xD9, 0x85, 0xD8, 0xAC, 0x44, 0xD9, 0x85, 0xD8,
+ 0xAD, 0x44, 0xD9, 0x85, 0xD8, 0xAE, 0x44, 0xD9,
+ // Bytes 1fc0 - 1fff
+ 0x85, 0xD9, 0x85, 0x44, 0xD9, 0x85, 0xD9, 0x89,
+ 0x44, 0xD9, 0x85, 0xD9, 0x8A, 0x44, 0xD9, 0x86,
+ 0xD8, 0xAC, 0x44, 0xD9, 0x86, 0xD8, 0xAD, 0x44,
+ 0xD9, 0x86, 0xD8, 0xAE, 0x44, 0xD9, 0x86, 0xD8,
+ 0xB1, 0x44, 0xD9, 0x86, 0xD8, 0xB2, 0x44, 0xD9,
+ 0x86, 0xD9, 0x85, 0x44, 0xD9, 0x86, 0xD9, 0x86,
+ 0x44, 0xD9, 0x86, 0xD9, 0x87, 0x44, 0xD9, 0x86,
+ 0xD9, 0x89, 0x44, 0xD9, 0x86, 0xD9, 0x8A, 0x44,
+ // Bytes 2000 - 203f
+ 0xD9, 0x87, 0xD8, 0xAC, 0x44, 0xD9, 0x87, 0xD9,
+ 0x85, 0x44, 0xD9, 0x87, 0xD9, 0x89, 0x44, 0xD9,
+ 0x87, 0xD9, 0x8A, 0x44, 0xD9, 0x88, 0xD9, 0xB4,
+ 0x44, 0xD9, 0x8A, 0xD8, 0xAC, 0x44, 0xD9, 0x8A,
+ 0xD8, 0xAD, 0x44, 0xD9, 0x8A, 0xD8, 0xAE, 0x44,
+ 0xD9, 0x8A, 0xD8, 0xB1, 0x44, 0xD9, 0x8A, 0xD8,
+ 0xB2, 0x44, 0xD9, 0x8A, 0xD9, 0x85, 0x44, 0xD9,
+ 0x8A, 0xD9, 0x86, 0x44, 0xD9, 0x8A, 0xD9, 0x87,
+ // Bytes 2040 - 207f
+ 0x44, 0xD9, 0x8A, 0xD9, 0x89, 0x44, 0xD9, 0x8A,
+ 0xD9, 0x8A, 0x44, 0xD9, 0x8A, 0xD9, 0xB4, 0x44,
+ 0xDB, 0x87, 0xD9, 0xB4, 0x45, 0x28, 0xE1, 0x84,
+ 0x80, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x82, 0x29,
+ 0x45, 0x28, 0xE1, 0x84, 0x83, 0x29, 0x45, 0x28,
+ 0xE1, 0x84, 0x85, 0x29, 0x45, 0x28, 0xE1, 0x84,
+ 0x86, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x87, 0x29,
+ 0x45, 0x28, 0xE1, 0x84, 0x89, 0x29, 0x45, 0x28,
+ // Bytes 2080 - 20bf
+ 0xE1, 0x84, 0x8B, 0x29, 0x45, 0x28, 0xE1, 0x84,
+ 0x8C, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x8E, 0x29,
+ 0x45, 0x28, 0xE1, 0x84, 0x8F, 0x29, 0x45, 0x28,
+ 0xE1, 0x84, 0x90, 0x29, 0x45, 0x28, 0xE1, 0x84,
+ 0x91, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x92, 0x29,
+ 0x45, 0x28, 0xE4, 0xB8, 0x80, 0x29, 0x45, 0x28,
+ 0xE4, 0xB8, 0x83, 0x29, 0x45, 0x28, 0xE4, 0xB8,
+ 0x89, 0x29, 0x45, 0x28, 0xE4, 0xB9, 0x9D, 0x29,
+ // Bytes 20c0 - 20ff
+ 0x45, 0x28, 0xE4, 0xBA, 0x8C, 0x29, 0x45, 0x28,
+ 0xE4, 0xBA, 0x94, 0x29, 0x45, 0x28, 0xE4, 0xBB,
+ 0xA3, 0x29, 0x45, 0x28, 0xE4, 0xBC, 0x81, 0x29,
+ 0x45, 0x28, 0xE4, 0xBC, 0x91, 0x29, 0x45, 0x28,
+ 0xE5, 0x85, 0xAB, 0x29, 0x45, 0x28, 0xE5, 0x85,
+ 0xAD, 0x29, 0x45, 0x28, 0xE5, 0x8A, 0xB4, 0x29,
+ 0x45, 0x28, 0xE5, 0x8D, 0x81, 0x29, 0x45, 0x28,
+ 0xE5, 0x8D, 0x94, 0x29, 0x45, 0x28, 0xE5, 0x90,
+ // Bytes 2100 - 213f
+ 0x8D, 0x29, 0x45, 0x28, 0xE5, 0x91, 0xBC, 0x29,
+ 0x45, 0x28, 0xE5, 0x9B, 0x9B, 0x29, 0x45, 0x28,
+ 0xE5, 0x9C, 0x9F, 0x29, 0x45, 0x28, 0xE5, 0xAD,
+ 0xA6, 0x29, 0x45, 0x28, 0xE6, 0x97, 0xA5, 0x29,
+ 0x45, 0x28, 0xE6, 0x9C, 0x88, 0x29, 0x45, 0x28,
+ 0xE6, 0x9C, 0x89, 0x29, 0x45, 0x28, 0xE6, 0x9C,
+ 0xA8, 0x29, 0x45, 0x28, 0xE6, 0xA0, 0xAA, 0x29,
+ 0x45, 0x28, 0xE6, 0xB0, 0xB4, 0x29, 0x45, 0x28,
+ // Bytes 2140 - 217f
+ 0xE7, 0x81, 0xAB, 0x29, 0x45, 0x28, 0xE7, 0x89,
+ 0xB9, 0x29, 0x45, 0x28, 0xE7, 0x9B, 0xA3, 0x29,
+ 0x45, 0x28, 0xE7, 0xA4, 0xBE, 0x29, 0x45, 0x28,
+ 0xE7, 0xA5, 0x9D, 0x29, 0x45, 0x28, 0xE7, 0xA5,
+ 0xAD, 0x29, 0x45, 0x28, 0xE8, 0x87, 0xAA, 0x29,
+ 0x45, 0x28, 0xE8, 0x87, 0xB3, 0x29, 0x45, 0x28,
+ 0xE8, 0xB2, 0xA1, 0x29, 0x45, 0x28, 0xE8, 0xB3,
+ 0x87, 0x29, 0x45, 0x28, 0xE9, 0x87, 0x91, 0x29,
+ // Bytes 2180 - 21bf
+ 0x45, 0x30, 0xE2, 0x81, 0x84, 0x33, 0x45, 0x31,
+ 0x30, 0xE6, 0x97, 0xA5, 0x45, 0x31, 0x30, 0xE6,
+ 0x9C, 0x88, 0x45, 0x31, 0x30, 0xE7, 0x82, 0xB9,
+ 0x45, 0x31, 0x31, 0xE6, 0x97, 0xA5, 0x45, 0x31,
+ 0x31, 0xE6, 0x9C, 0x88, 0x45, 0x31, 0x31, 0xE7,
+ 0x82, 0xB9, 0x45, 0x31, 0x32, 0xE6, 0x97, 0xA5,
+ 0x45, 0x31, 0x32, 0xE6, 0x9C, 0x88, 0x45, 0x31,
+ 0x32, 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x33, 0xE6,
+ // Bytes 21c0 - 21ff
+ 0x97, 0xA5, 0x45, 0x31, 0x33, 0xE7, 0x82, 0xB9,
+ 0x45, 0x31, 0x34, 0xE6, 0x97, 0xA5, 0x45, 0x31,
+ 0x34, 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x35, 0xE6,
+ 0x97, 0xA5, 0x45, 0x31, 0x35, 0xE7, 0x82, 0xB9,
+ 0x45, 0x31, 0x36, 0xE6, 0x97, 0xA5, 0x45, 0x31,
+ 0x36, 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x37, 0xE6,
+ 0x97, 0xA5, 0x45, 0x31, 0x37, 0xE7, 0x82, 0xB9,
+ 0x45, 0x31, 0x38, 0xE6, 0x97, 0xA5, 0x45, 0x31,
+ // Bytes 2200 - 223f
+ 0x38, 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x39, 0xE6,
+ 0x97, 0xA5, 0x45, 0x31, 0x39, 0xE7, 0x82, 0xB9,
+ 0x45, 0x31, 0xE2, 0x81, 0x84, 0x32, 0x45, 0x31,
+ 0xE2, 0x81, 0x84, 0x33, 0x45, 0x31, 0xE2, 0x81,
+ 0x84, 0x34, 0x45, 0x31, 0xE2, 0x81, 0x84, 0x35,
+ 0x45, 0x31, 0xE2, 0x81, 0x84, 0x36, 0x45, 0x31,
+ 0xE2, 0x81, 0x84, 0x37, 0x45, 0x31, 0xE2, 0x81,
+ 0x84, 0x38, 0x45, 0x31, 0xE2, 0x81, 0x84, 0x39,
+ // Bytes 2240 - 227f
+ 0x45, 0x32, 0x30, 0xE6, 0x97, 0xA5, 0x45, 0x32,
+ 0x30, 0xE7, 0x82, 0xB9, 0x45, 0x32, 0x31, 0xE6,
+ 0x97, 0xA5, 0x45, 0x32, 0x31, 0xE7, 0x82, 0xB9,
+ 0x45, 0x32, 0x32, 0xE6, 0x97, 0xA5, 0x45, 0x32,
+ 0x32, 0xE7, 0x82, 0xB9, 0x45, 0x32, 0x33, 0xE6,
+ 0x97, 0xA5, 0x45, 0x32, 0x33, 0xE7, 0x82, 0xB9,
+ 0x45, 0x32, 0x34, 0xE6, 0x97, 0xA5, 0x45, 0x32,
+ 0x34, 0xE7, 0x82, 0xB9, 0x45, 0x32, 0x35, 0xE6,
+ // Bytes 2280 - 22bf
+ 0x97, 0xA5, 0x45, 0x32, 0x36, 0xE6, 0x97, 0xA5,
+ 0x45, 0x32, 0x37, 0xE6, 0x97, 0xA5, 0x45, 0x32,
+ 0x38, 0xE6, 0x97, 0xA5, 0x45, 0x32, 0x39, 0xE6,
+ 0x97, 0xA5, 0x45, 0x32, 0xE2, 0x81, 0x84, 0x33,
+ 0x45, 0x32, 0xE2, 0x81, 0x84, 0x35, 0x45, 0x33,
+ 0x30, 0xE6, 0x97, 0xA5, 0x45, 0x33, 0x31, 0xE6,
+ 0x97, 0xA5, 0x45, 0x33, 0xE2, 0x81, 0x84, 0x34,
+ 0x45, 0x33, 0xE2, 0x81, 0x84, 0x35, 0x45, 0x33,
+ // Bytes 22c0 - 22ff
+ 0xE2, 0x81, 0x84, 0x38, 0x45, 0x34, 0xE2, 0x81,
+ 0x84, 0x35, 0x45, 0x35, 0xE2, 0x81, 0x84, 0x36,
+ 0x45, 0x35, 0xE2, 0x81, 0x84, 0x38, 0x45, 0x37,
+ 0xE2, 0x81, 0x84, 0x38, 0x45, 0x41, 0xE2, 0x88,
+ 0x95, 0x6D, 0x45, 0x56, 0xE2, 0x88, 0x95, 0x6D,
+ 0x45, 0x6D, 0xE2, 0x88, 0x95, 0x73, 0x46, 0x31,
+ 0xE2, 0x81, 0x84, 0x31, 0x30, 0x46, 0x43, 0xE2,
+ 0x88, 0x95, 0x6B, 0x67, 0x46, 0x6D, 0xE2, 0x88,
+ // Bytes 2300 - 233f
+ 0x95, 0x73, 0x32, 0x46, 0xD8, 0xA8, 0xD8, 0xAD,
+ 0xD9, 0x8A, 0x46, 0xD8, 0xA8, 0xD8, 0xAE, 0xD9,
+ 0x8A, 0x46, 0xD8, 0xAA, 0xD8, 0xAC, 0xD9, 0x85,
+ 0x46, 0xD8, 0xAA, 0xD8, 0xAC, 0xD9, 0x89, 0x46,
+ 0xD8, 0xAA, 0xD8, 0xAC, 0xD9, 0x8A, 0x46, 0xD8,
+ 0xAA, 0xD8, 0xAD, 0xD8, 0xAC, 0x46, 0xD8, 0xAA,
+ 0xD8, 0xAD, 0xD9, 0x85, 0x46, 0xD8, 0xAA, 0xD8,
+ 0xAE, 0xD9, 0x85, 0x46, 0xD8, 0xAA, 0xD8, 0xAE,
+ // Bytes 2340 - 237f
+ 0xD9, 0x89, 0x46, 0xD8, 0xAA, 0xD8, 0xAE, 0xD9,
+ 0x8A, 0x46, 0xD8, 0xAA, 0xD9, 0x85, 0xD8, 0xAC,
+ 0x46, 0xD8, 0xAA, 0xD9, 0x85, 0xD8, 0xAD, 0x46,
+ 0xD8, 0xAA, 0xD9, 0x85, 0xD8, 0xAE, 0x46, 0xD8,
+ 0xAA, 0xD9, 0x85, 0xD9, 0x89, 0x46, 0xD8, 0xAA,
+ 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD8, 0xAC, 0xD8,
+ 0xAD, 0xD9, 0x89, 0x46, 0xD8, 0xAC, 0xD8, 0xAD,
+ 0xD9, 0x8A, 0x46, 0xD8, 0xAC, 0xD9, 0x85, 0xD8,
+ // Bytes 2380 - 23bf
+ 0xAD, 0x46, 0xD8, 0xAC, 0xD9, 0x85, 0xD9, 0x89,
+ 0x46, 0xD8, 0xAC, 0xD9, 0x85, 0xD9, 0x8A, 0x46,
+ 0xD8, 0xAD, 0xD8, 0xAC, 0xD9, 0x8A, 0x46, 0xD8,
+ 0xAD, 0xD9, 0x85, 0xD9, 0x89, 0x46, 0xD8, 0xAD,
+ 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD8, 0xB3, 0xD8,
+ 0xAC, 0xD8, 0xAD, 0x46, 0xD8, 0xB3, 0xD8, 0xAC,
+ 0xD9, 0x89, 0x46, 0xD8, 0xB3, 0xD8, 0xAD, 0xD8,
+ 0xAC, 0x46, 0xD8, 0xB3, 0xD8, 0xAE, 0xD9, 0x89,
+ // Bytes 23c0 - 23ff
+ 0x46, 0xD8, 0xB3, 0xD8, 0xAE, 0xD9, 0x8A, 0x46,
+ 0xD8, 0xB3, 0xD9, 0x85, 0xD8, 0xAC, 0x46, 0xD8,
+ 0xB3, 0xD9, 0x85, 0xD8, 0xAD, 0x46, 0xD8, 0xB3,
+ 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD8, 0xB4, 0xD8,
+ 0xAC, 0xD9, 0x8A, 0x46, 0xD8, 0xB4, 0xD8, 0xAD,
+ 0xD9, 0x85, 0x46, 0xD8, 0xB4, 0xD8, 0xAD, 0xD9,
+ 0x8A, 0x46, 0xD8, 0xB4, 0xD9, 0x85, 0xD8, 0xAE,
+ 0x46, 0xD8, 0xB4, 0xD9, 0x85, 0xD9, 0x85, 0x46,
+ // Bytes 2400 - 243f
+ 0xD8, 0xB5, 0xD8, 0xAD, 0xD8, 0xAD, 0x46, 0xD8,
+ 0xB5, 0xD8, 0xAD, 0xD9, 0x8A, 0x46, 0xD8, 0xB5,
+ 0xD9, 0x84, 0xD9, 0x89, 0x46, 0xD8, 0xB5, 0xD9,
+ 0x84, 0xDB, 0x92, 0x46, 0xD8, 0xB5, 0xD9, 0x85,
+ 0xD9, 0x85, 0x46, 0xD8, 0xB6, 0xD8, 0xAD, 0xD9,
+ 0x89, 0x46, 0xD8, 0xB6, 0xD8, 0xAD, 0xD9, 0x8A,
+ 0x46, 0xD8, 0xB6, 0xD8, 0xAE, 0xD9, 0x85, 0x46,
+ 0xD8, 0xB7, 0xD9, 0x85, 0xD8, 0xAD, 0x46, 0xD8,
+ // Bytes 2440 - 247f
+ 0xB7, 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD8, 0xB7,
+ 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD8, 0xB9, 0xD8,
+ 0xAC, 0xD9, 0x85, 0x46, 0xD8, 0xB9, 0xD9, 0x85,
+ 0xD9, 0x85, 0x46, 0xD8, 0xB9, 0xD9, 0x85, 0xD9,
+ 0x89, 0x46, 0xD8, 0xB9, 0xD9, 0x85, 0xD9, 0x8A,
+ 0x46, 0xD8, 0xBA, 0xD9, 0x85, 0xD9, 0x85, 0x46,
+ 0xD8, 0xBA, 0xD9, 0x85, 0xD9, 0x89, 0x46, 0xD8,
+ 0xBA, 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x81,
+ // Bytes 2480 - 24bf
+ 0xD8, 0xAE, 0xD9, 0x85, 0x46, 0xD9, 0x81, 0xD9,
+ 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x82, 0xD9, 0x84,
+ 0xDB, 0x92, 0x46, 0xD9, 0x82, 0xD9, 0x85, 0xD8,
+ 0xAD, 0x46, 0xD9, 0x82, 0xD9, 0x85, 0xD9, 0x85,
+ 0x46, 0xD9, 0x82, 0xD9, 0x85, 0xD9, 0x8A, 0x46,
+ 0xD9, 0x83, 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD9,
+ 0x83, 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x84,
+ 0xD8, 0xAC, 0xD8, 0xAC, 0x46, 0xD9, 0x84, 0xD8,
+ // Bytes 24c0 - 24ff
+ 0xAC, 0xD9, 0x85, 0x46, 0xD9, 0x84, 0xD8, 0xAC,
+ 0xD9, 0x8A, 0x46, 0xD9, 0x84, 0xD8, 0xAD, 0xD9,
+ 0x85, 0x46, 0xD9, 0x84, 0xD8, 0xAD, 0xD9, 0x89,
+ 0x46, 0xD9, 0x84, 0xD8, 0xAD, 0xD9, 0x8A, 0x46,
+ 0xD9, 0x84, 0xD8, 0xAE, 0xD9, 0x85, 0x46, 0xD9,
+ 0x84, 0xD9, 0x85, 0xD8, 0xAD, 0x46, 0xD9, 0x84,
+ 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x85, 0xD8,
+ 0xAC, 0xD8, 0xAD, 0x46, 0xD9, 0x85, 0xD8, 0xAC,
+ // Bytes 2500 - 253f
+ 0xD8, 0xAE, 0x46, 0xD9, 0x85, 0xD8, 0xAC, 0xD9,
+ 0x85, 0x46, 0xD9, 0x85, 0xD8, 0xAC, 0xD9, 0x8A,
+ 0x46, 0xD9, 0x85, 0xD8, 0xAD, 0xD8, 0xAC, 0x46,
+ 0xD9, 0x85, 0xD8, 0xAD, 0xD9, 0x85, 0x46, 0xD9,
+ 0x85, 0xD8, 0xAD, 0xD9, 0x8A, 0x46, 0xD9, 0x85,
+ 0xD8, 0xAE, 0xD8, 0xAC, 0x46, 0xD9, 0x85, 0xD8,
+ 0xAE, 0xD9, 0x85, 0x46, 0xD9, 0x85, 0xD8, 0xAE,
+ 0xD9, 0x8A, 0x46, 0xD9, 0x85, 0xD9, 0x85, 0xD9,
+ // Bytes 2540 - 257f
+ 0x8A, 0x46, 0xD9, 0x86, 0xD8, 0xAC, 0xD8, 0xAD,
+ 0x46, 0xD9, 0x86, 0xD8, 0xAC, 0xD9, 0x85, 0x46,
+ 0xD9, 0x86, 0xD8, 0xAC, 0xD9, 0x89, 0x46, 0xD9,
+ 0x86, 0xD8, 0xAC, 0xD9, 0x8A, 0x46, 0xD9, 0x86,
+ 0xD8, 0xAD, 0xD9, 0x85, 0x46, 0xD9, 0x86, 0xD8,
+ 0xAD, 0xD9, 0x89, 0x46, 0xD9, 0x86, 0xD8, 0xAD,
+ 0xD9, 0x8A, 0x46, 0xD9, 0x86, 0xD9, 0x85, 0xD9,
+ 0x89, 0x46, 0xD9, 0x86, 0xD9, 0x85, 0xD9, 0x8A,
+ // Bytes 2580 - 25bf
+ 0x46, 0xD9, 0x87, 0xD9, 0x85, 0xD8, 0xAC, 0x46,
+ 0xD9, 0x87, 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD9,
+ 0x8A, 0xD8, 0xAC, 0xD9, 0x8A, 0x46, 0xD9, 0x8A,
+ 0xD8, 0xAD, 0xD9, 0x8A, 0x46, 0xD9, 0x8A, 0xD9,
+ 0x85, 0xD9, 0x85, 0x46, 0xD9, 0x8A, 0xD9, 0x85,
+ 0xD9, 0x8A, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD8,
+ 0xA7, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD8, 0xAC,
+ 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD8, 0xAD, 0x46,
+ // Bytes 25c0 - 25ff
+ 0xD9, 0x8A, 0xD9, 0x94, 0xD8, 0xAE, 0x46, 0xD9,
+ 0x8A, 0xD9, 0x94, 0xD8, 0xB1, 0x46, 0xD9, 0x8A,
+ 0xD9, 0x94, 0xD8, 0xB2, 0x46, 0xD9, 0x8A, 0xD9,
+ 0x94, 0xD9, 0x85, 0x46, 0xD9, 0x8A, 0xD9, 0x94,
+ 0xD9, 0x86, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD9,
+ 0x87, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD9, 0x88,
+ 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD9, 0x89, 0x46,
+ 0xD9, 0x8A, 0xD9, 0x94, 0xD9, 0x8A, 0x46, 0xD9,
+ // Bytes 2600 - 263f
+ 0x8A, 0xD9, 0x94, 0xDB, 0x86, 0x46, 0xD9, 0x8A,
+ 0xD9, 0x94, 0xDB, 0x87, 0x46, 0xD9, 0x8A, 0xD9,
+ 0x94, 0xDB, 0x88, 0x46, 0xD9, 0x8A, 0xD9, 0x94,
+ 0xDB, 0x90, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xDB,
+ 0x95, 0x46, 0xE0, 0xB9, 0x8D, 0xE0, 0xB8, 0xB2,
+ 0x46, 0xE0, 0xBA, 0xAB, 0xE0, 0xBA, 0x99, 0x46,
+ 0xE0, 0xBA, 0xAB, 0xE0, 0xBA, 0xA1, 0x46, 0xE0,
+ 0xBB, 0x8D, 0xE0, 0xBA, 0xB2, 0x46, 0xE0, 0xBD,
+ // Bytes 2640 - 267f
+ 0x80, 0xE0, 0xBE, 0xB5, 0x46, 0xE0, 0xBD, 0x82,
+ 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBD, 0x8C, 0xE0,
+ 0xBE, 0xB7, 0x46, 0xE0, 0xBD, 0x91, 0xE0, 0xBE,
+ 0xB7, 0x46, 0xE0, 0xBD, 0x96, 0xE0, 0xBE, 0xB7,
+ 0x46, 0xE0, 0xBD, 0x9B, 0xE0, 0xBE, 0xB7, 0x46,
+ 0xE0, 0xBE, 0x90, 0xE0, 0xBE, 0xB5, 0x46, 0xE0,
+ 0xBE, 0x92, 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBE,
+ 0x9C, 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBE, 0xA1,
+ // Bytes 2680 - 26bf
+ 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBE, 0xA6, 0xE0,
+ 0xBE, 0xB7, 0x46, 0xE0, 0xBE, 0xAB, 0xE0, 0xBE,
+ 0xB7, 0x46, 0xE2, 0x80, 0xB2, 0xE2, 0x80, 0xB2,
+ 0x46, 0xE2, 0x80, 0xB5, 0xE2, 0x80, 0xB5, 0x46,
+ 0xE2, 0x88, 0xAB, 0xE2, 0x88, 0xAB, 0x46, 0xE2,
+ 0x88, 0xAE, 0xE2, 0x88, 0xAE, 0x46, 0xE3, 0x81,
+ 0xBB, 0xE3, 0x81, 0x8B, 0x46, 0xE3, 0x82, 0x88,
+ 0xE3, 0x82, 0x8A, 0x46, 0xE3, 0x82, 0xAD, 0xE3,
+ // Bytes 26c0 - 26ff
+ 0x83, 0xAD, 0x46, 0xE3, 0x82, 0xB3, 0xE3, 0x82,
+ 0xB3, 0x46, 0xE3, 0x82, 0xB3, 0xE3, 0x83, 0x88,
+ 0x46, 0xE3, 0x83, 0x88, 0xE3, 0x83, 0xB3, 0x46,
+ 0xE3, 0x83, 0x8A, 0xE3, 0x83, 0x8E, 0x46, 0xE3,
+ 0x83, 0x9B, 0xE3, 0x83, 0xB3, 0x46, 0xE3, 0x83,
+ 0x9F, 0xE3, 0x83, 0xAA, 0x46, 0xE3, 0x83, 0xAA,
+ 0xE3, 0x83, 0xA9, 0x46, 0xE3, 0x83, 0xAC, 0xE3,
+ 0x83, 0xA0, 0x46, 0xE5, 0xA4, 0xA7, 0xE6, 0xAD,
+ // Bytes 2700 - 273f
+ 0xA3, 0x46, 0xE5, 0xB9, 0xB3, 0xE6, 0x88, 0x90,
+ 0x46, 0xE6, 0x98, 0x8E, 0xE6, 0xB2, 0xBB, 0x46,
+ 0xE6, 0x98, 0xAD, 0xE5, 0x92, 0x8C, 0x47, 0x72,
+ 0x61, 0x64, 0xE2, 0x88, 0x95, 0x73, 0x47, 0xE3,
+ 0x80, 0x94, 0x53, 0xE3, 0x80, 0x95, 0x48, 0x28,
+ 0xE1, 0x84, 0x80, 0xE1, 0x85, 0xA1, 0x29, 0x48,
+ 0x28, 0xE1, 0x84, 0x82, 0xE1, 0x85, 0xA1, 0x29,
+ 0x48, 0x28, 0xE1, 0x84, 0x83, 0xE1, 0x85, 0xA1,
+ // Bytes 2740 - 277f
+ 0x29, 0x48, 0x28, 0xE1, 0x84, 0x85, 0xE1, 0x85,
+ 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x86, 0xE1,
+ 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x87,
+ 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84,
+ 0x89, 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1,
+ 0x84, 0x8B, 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28,
+ 0xE1, 0x84, 0x8C, 0xE1, 0x85, 0xA1, 0x29, 0x48,
+ 0x28, 0xE1, 0x84, 0x8C, 0xE1, 0x85, 0xAE, 0x29,
+ // Bytes 2780 - 27bf
+ 0x48, 0x28, 0xE1, 0x84, 0x8E, 0xE1, 0x85, 0xA1,
+ 0x29, 0x48, 0x28, 0xE1, 0x84, 0x8F, 0xE1, 0x85,
+ 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x90, 0xE1,
+ 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x91,
+ 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84,
+ 0x92, 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x72, 0x61,
+ 0x64, 0xE2, 0x88, 0x95, 0x73, 0x32, 0x48, 0xD8,
+ 0xA7, 0xD9, 0x83, 0xD8, 0xA8, 0xD8, 0xB1, 0x48,
+ // Bytes 27c0 - 27ff
+ 0xD8, 0xA7, 0xD9, 0x84, 0xD9, 0x84, 0xD9, 0x87,
+ 0x48, 0xD8, 0xB1, 0xD8, 0xB3, 0xD9, 0x88, 0xD9,
+ 0x84, 0x48, 0xD8, 0xB1, 0xDB, 0x8C, 0xD8, 0xA7,
+ 0xD9, 0x84, 0x48, 0xD8, 0xB5, 0xD9, 0x84, 0xD8,
+ 0xB9, 0xD9, 0x85, 0x48, 0xD8, 0xB9, 0xD9, 0x84,
+ 0xD9, 0x8A, 0xD9, 0x87, 0x48, 0xD9, 0x85, 0xD8,
+ 0xAD, 0xD9, 0x85, 0xD8, 0xAF, 0x48, 0xD9, 0x88,
+ 0xD8, 0xB3, 0xD9, 0x84, 0xD9, 0x85, 0x49, 0xE2,
+ // Bytes 2800 - 283f
+ 0x80, 0xB2, 0xE2, 0x80, 0xB2, 0xE2, 0x80, 0xB2,
+ 0x49, 0xE2, 0x80, 0xB5, 0xE2, 0x80, 0xB5, 0xE2,
+ 0x80, 0xB5, 0x49, 0xE2, 0x88, 0xAB, 0xE2, 0x88,
+ 0xAB, 0xE2, 0x88, 0xAB, 0x49, 0xE2, 0x88, 0xAE,
+ 0xE2, 0x88, 0xAE, 0xE2, 0x88, 0xAE, 0x49, 0xE3,
+ 0x80, 0x94, 0xE4, 0xB8, 0x89, 0xE3, 0x80, 0x95,
+ 0x49, 0xE3, 0x80, 0x94, 0xE4, 0xBA, 0x8C, 0xE3,
+ 0x80, 0x95, 0x49, 0xE3, 0x80, 0x94, 0xE5, 0x8B,
+ // Bytes 2840 - 287f
+ 0x9D, 0xE3, 0x80, 0x95, 0x49, 0xE3, 0x80, 0x94,
+ 0xE5, 0xAE, 0x89, 0xE3, 0x80, 0x95, 0x49, 0xE3,
+ 0x80, 0x94, 0xE6, 0x89, 0x93, 0xE3, 0x80, 0x95,
+ 0x49, 0xE3, 0x80, 0x94, 0xE6, 0x95, 0x97, 0xE3,
+ 0x80, 0x95, 0x49, 0xE3, 0x80, 0x94, 0xE6, 0x9C,
+ 0xAC, 0xE3, 0x80, 0x95, 0x49, 0xE3, 0x80, 0x94,
+ 0xE7, 0x82, 0xB9, 0xE3, 0x80, 0x95, 0x49, 0xE3,
+ 0x80, 0x94, 0xE7, 0x9B, 0x97, 0xE3, 0x80, 0x95,
+ // Bytes 2880 - 28bf
+ 0x49, 0xE3, 0x82, 0xA2, 0xE3, 0x83, 0xBC, 0xE3,
+ 0x83, 0xAB, 0x49, 0xE3, 0x82, 0xA4, 0xE3, 0x83,
+ 0xB3, 0xE3, 0x83, 0x81, 0x49, 0xE3, 0x82, 0xA6,
+ 0xE3, 0x82, 0xA9, 0xE3, 0x83, 0xB3, 0x49, 0xE3,
+ 0x82, 0xAA, 0xE3, 0x83, 0xB3, 0xE3, 0x82, 0xB9,
+ 0x49, 0xE3, 0x82, 0xAA, 0xE3, 0x83, 0xBC, 0xE3,
+ 0x83, 0xA0, 0x49, 0xE3, 0x82, 0xAB, 0xE3, 0x82,
+ 0xA4, 0xE3, 0x83, 0xAA, 0x49, 0xE3, 0x82, 0xB1,
+ // Bytes 28c0 - 28ff
+ 0xE3, 0x83, 0xBC, 0xE3, 0x82, 0xB9, 0x49, 0xE3,
+ 0x82, 0xB3, 0xE3, 0x83, 0xAB, 0xE3, 0x83, 0x8A,
+ 0x49, 0xE3, 0x82, 0xBB, 0xE3, 0x83, 0xB3, 0xE3,
+ 0x83, 0x81, 0x49, 0xE3, 0x82, 0xBB, 0xE3, 0x83,
+ 0xB3, 0xE3, 0x83, 0x88, 0x49, 0xE3, 0x83, 0x86,
+ 0xE3, 0x82, 0x99, 0xE3, 0x82, 0xB7, 0x49, 0xE3,
+ 0x83, 0x88, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xAB,
+ 0x49, 0xE3, 0x83, 0x8E, 0xE3, 0x83, 0x83, 0xE3,
+ // Bytes 2900 - 293f
+ 0x83, 0x88, 0x49, 0xE3, 0x83, 0x8F, 0xE3, 0x82,
+ 0xA4, 0xE3, 0x83, 0x84, 0x49, 0xE3, 0x83, 0x92,
+ 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xAB, 0x49, 0xE3,
+ 0x83, 0x92, 0xE3, 0x82, 0x9A, 0xE3, 0x82, 0xB3,
+ 0x49, 0xE3, 0x83, 0x95, 0xE3, 0x83, 0xA9, 0xE3,
+ 0x83, 0xB3, 0x49, 0xE3, 0x83, 0x98, 0xE3, 0x82,
+ 0x9A, 0xE3, 0x82, 0xBD, 0x49, 0xE3, 0x83, 0x98,
+ 0xE3, 0x83, 0xAB, 0xE3, 0x83, 0x84, 0x49, 0xE3,
+ // Bytes 2940 - 297f
+ 0x83, 0x9B, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0xAB,
+ 0x49, 0xE3, 0x83, 0x9B, 0xE3, 0x83, 0xBC, 0xE3,
+ 0x83, 0xB3, 0x49, 0xE3, 0x83, 0x9E, 0xE3, 0x82,
+ 0xA4, 0xE3, 0x83, 0xAB, 0x49, 0xE3, 0x83, 0x9E,
+ 0xE3, 0x83, 0x83, 0xE3, 0x83, 0x8F, 0x49, 0xE3,
+ 0x83, 0x9E, 0xE3, 0x83, 0xAB, 0xE3, 0x82, 0xAF,
+ 0x49, 0xE3, 0x83, 0xA4, 0xE3, 0x83, 0xBC, 0xE3,
+ 0x83, 0xAB, 0x49, 0xE3, 0x83, 0xA6, 0xE3, 0x82,
+ // Bytes 2980 - 29bf
+ 0xA2, 0xE3, 0x83, 0xB3, 0x49, 0xE3, 0x83, 0xAF,
+ 0xE3, 0x83, 0x83, 0xE3, 0x83, 0x88, 0x4C, 0xE2,
+ 0x80, 0xB2, 0xE2, 0x80, 0xB2, 0xE2, 0x80, 0xB2,
+ 0xE2, 0x80, 0xB2, 0x4C, 0xE2, 0x88, 0xAB, 0xE2,
+ 0x88, 0xAB, 0xE2, 0x88, 0xAB, 0xE2, 0x88, 0xAB,
+ 0x4C, 0xE3, 0x82, 0xA2, 0xE3, 0x83, 0xAB, 0xE3,
+ 0x83, 0x95, 0xE3, 0x82, 0xA1, 0x4C, 0xE3, 0x82,
+ 0xA8, 0xE3, 0x83, 0xBC, 0xE3, 0x82, 0xAB, 0xE3,
+ // Bytes 29c0 - 29ff
+ 0x83, 0xBC, 0x4C, 0xE3, 0x82, 0xAB, 0xE3, 0x82,
+ 0x99, 0xE3, 0x83, 0xAD, 0xE3, 0x83, 0xB3, 0x4C,
+ 0xE3, 0x82, 0xAB, 0xE3, 0x82, 0x99, 0xE3, 0x83,
+ 0xB3, 0xE3, 0x83, 0x9E, 0x4C, 0xE3, 0x82, 0xAB,
+ 0xE3, 0x83, 0xA9, 0xE3, 0x83, 0x83, 0xE3, 0x83,
+ 0x88, 0x4C, 0xE3, 0x82, 0xAB, 0xE3, 0x83, 0xAD,
+ 0xE3, 0x83, 0xAA, 0xE3, 0x83, 0xBC, 0x4C, 0xE3,
+ 0x82, 0xAD, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0x8B,
+ // Bytes 2a00 - 2a3f
+ 0xE3, 0x83, 0xBC, 0x4C, 0xE3, 0x82, 0xAD, 0xE3,
+ 0x83, 0xA5, 0xE3, 0x83, 0xAA, 0xE3, 0x83, 0xBC,
+ 0x4C, 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0x99, 0xE3,
+ 0x83, 0xA9, 0xE3, 0x83, 0xA0, 0x4C, 0xE3, 0x82,
+ 0xAF, 0xE3, 0x83, 0xAD, 0xE3, 0x83, 0xBC, 0xE3,
+ 0x83, 0x8D, 0x4C, 0xE3, 0x82, 0xB5, 0xE3, 0x82,
+ 0xA4, 0xE3, 0x82, 0xAF, 0xE3, 0x83, 0xAB, 0x4C,
+ 0xE3, 0x82, 0xBF, 0xE3, 0x82, 0x99, 0xE3, 0x83,
+ // Bytes 2a40 - 2a7f
+ 0xBC, 0xE3, 0x82, 0xB9, 0x4C, 0xE3, 0x83, 0x8F,
+ 0xE3, 0x82, 0x9A, 0xE3, 0x83, 0xBC, 0xE3, 0x83,
+ 0x84, 0x4C, 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x9A,
+ 0xE3, 0x82, 0xAF, 0xE3, 0x83, 0xAB, 0x4C, 0xE3,
+ 0x83, 0x95, 0xE3, 0x82, 0xA3, 0xE3, 0x83, 0xBC,
+ 0xE3, 0x83, 0x88, 0x4C, 0xE3, 0x83, 0x98, 0xE3,
+ 0x82, 0x99, 0xE3, 0x83, 0xBC, 0xE3, 0x82, 0xBF,
+ 0x4C, 0xE3, 0x83, 0x98, 0xE3, 0x82, 0x9A, 0xE3,
+ // Bytes 2a80 - 2abf
+ 0x83, 0x8B, 0xE3, 0x83, 0x92, 0x4C, 0xE3, 0x83,
+ 0x98, 0xE3, 0x82, 0x9A, 0xE3, 0x83, 0xB3, 0xE3,
+ 0x82, 0xB9, 0x4C, 0xE3, 0x83, 0x9B, 0xE3, 0x82,
+ 0x99, 0xE3, 0x83, 0xAB, 0xE3, 0x83, 0x88, 0x4C,
+ 0xE3, 0x83, 0x9E, 0xE3, 0x82, 0xA4, 0xE3, 0x82,
+ 0xAF, 0xE3, 0x83, 0xAD, 0x4C, 0xE3, 0x83, 0x9F,
+ 0xE3, 0x82, 0xAF, 0xE3, 0x83, 0xAD, 0xE3, 0x83,
+ 0xB3, 0x4C, 0xE3, 0x83, 0xA1, 0xE3, 0x83, 0xBC,
+ // Bytes 2ac0 - 2aff
+ 0xE3, 0x83, 0x88, 0xE3, 0x83, 0xAB, 0x4C, 0xE3,
+ 0x83, 0xAA, 0xE3, 0x83, 0x83, 0xE3, 0x83, 0x88,
+ 0xE3, 0x83, 0xAB, 0x4C, 0xE3, 0x83, 0xAB, 0xE3,
+ 0x83, 0x92, 0xE3, 0x82, 0x9A, 0xE3, 0x83, 0xBC,
+ 0x4C, 0xE6, 0xA0, 0xAA, 0xE5, 0xBC, 0x8F, 0xE4,
+ 0xBC, 0x9A, 0xE7, 0xA4, 0xBE, 0x4E, 0x28, 0xE1,
+ 0x84, 0x8B, 0xE1, 0x85, 0xA9, 0xE1, 0x84, 0x92,
+ 0xE1, 0x85, 0xAE, 0x29, 0x4F, 0xD8, 0xAC, 0xD9,
+ // Bytes 2b00 - 2b3f
+ 0x84, 0x20, 0xD8, 0xAC, 0xD9, 0x84, 0xD8, 0xA7,
+ 0xD9, 0x84, 0xD9, 0x87, 0x4F, 0xE3, 0x82, 0xA2,
+ 0xE3, 0x83, 0x8F, 0xE3, 0x82, 0x9A, 0xE3, 0x83,
+ 0xBC, 0xE3, 0x83, 0x88, 0x4F, 0xE3, 0x82, 0xA2,
+ 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x98, 0xE3, 0x82,
+ 0x9A, 0xE3, 0x82, 0xA2, 0x4F, 0xE3, 0x82, 0xAD,
+ 0xE3, 0x83, 0xAD, 0xE3, 0x83, 0xAF, 0xE3, 0x83,
+ 0x83, 0xE3, 0x83, 0x88, 0x4F, 0xE3, 0x82, 0xB5,
+ // Bytes 2b40 - 2b7f
+ 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x81, 0xE3, 0x83,
+ 0xBC, 0xE3, 0x83, 0xA0, 0x4F, 0xE3, 0x83, 0x8F,
+ 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xBC, 0xE3, 0x83,
+ 0xAC, 0xE3, 0x83, 0xAB, 0x4F, 0xE3, 0x83, 0x98,
+ 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0xBF, 0xE3, 0x83,
+ 0xBC, 0xE3, 0x83, 0xAB, 0x4F, 0xE3, 0x83, 0x9B,
+ 0xE3, 0x82, 0x9A, 0xE3, 0x82, 0xA4, 0xE3, 0x83,
+ 0xB3, 0xE3, 0x83, 0x88, 0x4F, 0xE3, 0x83, 0x9E,
+ // Bytes 2b80 - 2bbf
+ 0xE3, 0x83, 0xB3, 0xE3, 0x82, 0xB7, 0xE3, 0x83,
+ 0xA7, 0xE3, 0x83, 0xB3, 0x4F, 0xE3, 0x83, 0xA1,
+ 0xE3, 0x82, 0xAB, 0xE3, 0x82, 0x99, 0xE3, 0x83,
+ 0x88, 0xE3, 0x83, 0xB3, 0x4F, 0xE3, 0x83, 0xAB,
+ 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x95, 0xE3, 0x82,
+ 0x99, 0xE3, 0x83, 0xAB, 0x51, 0x28, 0xE1, 0x84,
+ 0x8B, 0xE1, 0x85, 0xA9, 0xE1, 0x84, 0x8C, 0xE1,
+ 0x85, 0xA5, 0xE1, 0x86, 0xAB, 0x29, 0x52, 0xE3,
+ // Bytes 2bc0 - 2bff
+ 0x82, 0xAD, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xAB,
+ 0xE3, 0x82, 0xBF, 0xE3, 0x82, 0x99, 0xE3, 0x83,
+ 0xBC, 0x52, 0xE3, 0x82, 0xAD, 0xE3, 0x83, 0xAD,
+ 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0x99, 0xE3, 0x83,
+ 0xA9, 0xE3, 0x83, 0xA0, 0x52, 0xE3, 0x82, 0xAD,
+ 0xE3, 0x83, 0xAD, 0xE3, 0x83, 0xA1, 0xE3, 0x83,
+ 0xBC, 0xE3, 0x83, 0x88, 0xE3, 0x83, 0xAB, 0x52,
+ 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0x99, 0xE3, 0x83,
+ // Bytes 2c00 - 2c3f
+ 0xA9, 0xE3, 0x83, 0xA0, 0xE3, 0x83, 0x88, 0xE3,
+ 0x83, 0xB3, 0x52, 0xE3, 0x82, 0xAF, 0xE3, 0x83,
+ 0xAB, 0xE3, 0x82, 0xBB, 0xE3, 0x82, 0x99, 0xE3,
+ 0x82, 0xA4, 0xE3, 0x83, 0xAD, 0x52, 0xE3, 0x83,
+ 0x8F, 0xE3, 0x82, 0x9A, 0xE3, 0x83, 0xBC, 0xE3,
+ 0x82, 0xBB, 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x88,
+ 0x52, 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x9A, 0xE3,
+ 0x82, 0xA2, 0xE3, 0x82, 0xB9, 0xE3, 0x83, 0x88,
+ // Bytes 2c40 - 2c7f
+ 0xE3, 0x83, 0xAB, 0x52, 0xE3, 0x83, 0x95, 0xE3,
+ 0x82, 0x99, 0xE3, 0x83, 0x83, 0xE3, 0x82, 0xB7,
+ 0xE3, 0x82, 0xA7, 0xE3, 0x83, 0xAB, 0x52, 0xE3,
+ 0x83, 0x9F, 0xE3, 0x83, 0xAA, 0xE3, 0x83, 0x8F,
+ 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xBC, 0xE3, 0x83,
+ 0xAB, 0x52, 0xE3, 0x83, 0xAC, 0xE3, 0x83, 0xB3,
+ 0xE3, 0x83, 0x88, 0xE3, 0x82, 0xB1, 0xE3, 0x82,
+ 0x99, 0xE3, 0x83, 0xB3, 0x61, 0xD8, 0xB5, 0xD9,
+ // Bytes 2c80 - 2cbf
+ 0x84, 0xD9, 0x89, 0x20, 0xD8, 0xA7, 0xD9, 0x84,
+ 0xD9, 0x84, 0xD9, 0x87, 0x20, 0xD8, 0xB9, 0xD9,
+ 0x84, 0xD9, 0x8A, 0xD9, 0x87, 0x20, 0xD9, 0x88,
+ 0xD8, 0xB3, 0xD9, 0x84, 0xD9, 0x85, 0x06, 0xE0,
+ 0xA7, 0x87, 0xE0, 0xA6, 0xBE, 0x01, 0x06, 0xE0,
+ 0xA7, 0x87, 0xE0, 0xA7, 0x97, 0x01, 0x06, 0xE0,
+ 0xAD, 0x87, 0xE0, 0xAC, 0xBE, 0x01, 0x06, 0xE0,
+ 0xAD, 0x87, 0xE0, 0xAD, 0x96, 0x01, 0x06, 0xE0,
+ // Bytes 2cc0 - 2cff
+ 0xAD, 0x87, 0xE0, 0xAD, 0x97, 0x01, 0x06, 0xE0,
+ 0xAE, 0x92, 0xE0, 0xAF, 0x97, 0x01, 0x06, 0xE0,
+ 0xAF, 0x86, 0xE0, 0xAE, 0xBE, 0x01, 0x06, 0xE0,
+ 0xAF, 0x86, 0xE0, 0xAF, 0x97, 0x01, 0x06, 0xE0,
+ 0xAF, 0x87, 0xE0, 0xAE, 0xBE, 0x01, 0x06, 0xE0,
+ 0xB2, 0xBF, 0xE0, 0xB3, 0x95, 0x01, 0x06, 0xE0,
+ 0xB3, 0x86, 0xE0, 0xB3, 0x95, 0x01, 0x06, 0xE0,
+ 0xB3, 0x86, 0xE0, 0xB3, 0x96, 0x01, 0x06, 0xE0,
+ // Bytes 2d00 - 2d3f
+ 0xB5, 0x86, 0xE0, 0xB4, 0xBE, 0x01, 0x06, 0xE0,
+ 0xB5, 0x86, 0xE0, 0xB5, 0x97, 0x01, 0x06, 0xE0,
+ 0xB5, 0x87, 0xE0, 0xB4, 0xBE, 0x01, 0x06, 0xE0,
+ 0xB7, 0x99, 0xE0, 0xB7, 0x9F, 0x01, 0x06, 0xE1,
+ 0x80, 0xA5, 0xE1, 0x80, 0xAE, 0x01, 0x06, 0xE1,
+ 0xAC, 0x85, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1,
+ 0xAC, 0x87, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1,
+ 0xAC, 0x89, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1,
+ // Bytes 2d40 - 2d7f
+ 0xAC, 0x8B, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1,
+ 0xAC, 0x8D, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1,
+ 0xAC, 0x91, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1,
+ 0xAC, 0xBA, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1,
+ 0xAC, 0xBC, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1,
+ 0xAC, 0xBE, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1,
+ 0xAC, 0xBF, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1,
+ 0xAD, 0x82, 0xE1, 0xAC, 0xB5, 0x01, 0x08, 0xF0,
+ // Bytes 2d80 - 2dbf
+ 0x91, 0x84, 0xB1, 0xF0, 0x91, 0x84, 0xA7, 0x01,
+ 0x08, 0xF0, 0x91, 0x84, 0xB2, 0xF0, 0x91, 0x84,
+ 0xA7, 0x01, 0x08, 0xF0, 0x91, 0x8D, 0x87, 0xF0,
+ 0x91, 0x8C, 0xBE, 0x01, 0x08, 0xF0, 0x91, 0x8D,
+ 0x87, 0xF0, 0x91, 0x8D, 0x97, 0x01, 0x08, 0xF0,
+ 0x91, 0x92, 0xB9, 0xF0, 0x91, 0x92, 0xB0, 0x01,
+ 0x08, 0xF0, 0x91, 0x92, 0xB9, 0xF0, 0x91, 0x92,
+ 0xBA, 0x01, 0x08, 0xF0, 0x91, 0x92, 0xB9, 0xF0,
+ // Bytes 2dc0 - 2dff
+ 0x91, 0x92, 0xBD, 0x01, 0x08, 0xF0, 0x91, 0x96,
+ 0xB8, 0xF0, 0x91, 0x96, 0xAF, 0x01, 0x08, 0xF0,
+ 0x91, 0x96, 0xB9, 0xF0, 0x91, 0x96, 0xAF, 0x01,
+ 0x09, 0xE0, 0xB3, 0x86, 0xE0, 0xB3, 0x82, 0xE0,
+ 0xB3, 0x95, 0x02, 0x09, 0xE0, 0xB7, 0x99, 0xE0,
+ 0xB7, 0x8F, 0xE0, 0xB7, 0x8A, 0x12, 0x44, 0x44,
+ 0x5A, 0xCC, 0x8C, 0xC9, 0x44, 0x44, 0x7A, 0xCC,
+ 0x8C, 0xC9, 0x44, 0x64, 0x7A, 0xCC, 0x8C, 0xC9,
+ // Bytes 2e00 - 2e3f
+ 0x46, 0xD9, 0x84, 0xD8, 0xA7, 0xD9, 0x93, 0xC9,
+ 0x46, 0xD9, 0x84, 0xD8, 0xA7, 0xD9, 0x94, 0xC9,
+ 0x46, 0xD9, 0x84, 0xD8, 0xA7, 0xD9, 0x95, 0xB5,
+ 0x46, 0xE1, 0x84, 0x80, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x82, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x83, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x85, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x86, 0xE1, 0x85, 0xA1, 0x01,
+ // Bytes 2e40 - 2e7f
+ 0x46, 0xE1, 0x84, 0x87, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x89, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x8B, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x8B, 0xE1, 0x85, 0xAE, 0x01,
+ 0x46, 0xE1, 0x84, 0x8C, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x8E, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x8F, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x90, 0xE1, 0x85, 0xA1, 0x01,
+ // Bytes 2e80 - 2ebf
+ 0x46, 0xE1, 0x84, 0x91, 0xE1, 0x85, 0xA1, 0x01,
+ 0x46, 0xE1, 0x84, 0x92, 0xE1, 0x85, 0xA1, 0x01,
+ 0x49, 0xE3, 0x83, 0xA1, 0xE3, 0x82, 0xAB, 0xE3,
+ 0x82, 0x99, 0x0D, 0x4C, 0xE1, 0x84, 0x8C, 0xE1,
+ 0x85, 0xAE, 0xE1, 0x84, 0x8B, 0xE1, 0x85, 0xB4,
+ 0x01, 0x4C, 0xE3, 0x82, 0xAD, 0xE3, 0x82, 0x99,
+ 0xE3, 0x82, 0xAB, 0xE3, 0x82, 0x99, 0x0D, 0x4C,
+ 0xE3, 0x82, 0xB3, 0xE3, 0x83, 0xBC, 0xE3, 0x83,
+ // Bytes 2ec0 - 2eff
+ 0x9B, 0xE3, 0x82, 0x9A, 0x0D, 0x4C, 0xE3, 0x83,
+ 0xA4, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x88, 0xE3,
+ 0x82, 0x99, 0x0D, 0x4F, 0xE1, 0x84, 0x8E, 0xE1,
+ 0x85, 0xA1, 0xE1, 0x86, 0xB7, 0xE1, 0x84, 0x80,
+ 0xE1, 0x85, 0xA9, 0x01, 0x4F, 0xE3, 0x82, 0xA4,
+ 0xE3, 0x83, 0x8B, 0xE3, 0x83, 0xB3, 0xE3, 0x82,
+ 0xAF, 0xE3, 0x82, 0x99, 0x0D, 0x4F, 0xE3, 0x82,
+ 0xB7, 0xE3, 0x83, 0xAA, 0xE3, 0x83, 0xB3, 0xE3,
+ // Bytes 2f00 - 2f3f
+ 0x82, 0xAF, 0xE3, 0x82, 0x99, 0x0D, 0x4F, 0xE3,
+ 0x83, 0x98, 0xE3, 0x82, 0x9A, 0xE3, 0x83, 0xBC,
+ 0xE3, 0x82, 0xB7, 0xE3, 0x82, 0x99, 0x0D, 0x4F,
+ 0xE3, 0x83, 0x9B, 0xE3, 0x82, 0x9A, 0xE3, 0x83,
+ 0xB3, 0xE3, 0x83, 0x88, 0xE3, 0x82, 0x99, 0x0D,
+ 0x52, 0xE3, 0x82, 0xA8, 0xE3, 0x82, 0xB9, 0xE3,
+ 0x82, 0xAF, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x88,
+ 0xE3, 0x82, 0x99, 0x0D, 0x52, 0xE3, 0x83, 0x95,
+ // Bytes 2f40 - 2f7f
+ 0xE3, 0x82, 0xA1, 0xE3, 0x83, 0xA9, 0xE3, 0x83,
+ 0x83, 0xE3, 0x83, 0x88, 0xE3, 0x82, 0x99, 0x0D,
+ 0x86, 0xE0, 0xB3, 0x86, 0xE0, 0xB3, 0x82, 0x01,
+ 0x86, 0xE0, 0xB7, 0x99, 0xE0, 0xB7, 0x8F, 0x01,
+ 0x03, 0x3C, 0xCC, 0xB8, 0x05, 0x03, 0x3D, 0xCC,
+ 0xB8, 0x05, 0x03, 0x3E, 0xCC, 0xB8, 0x05, 0x03,
+ 0x41, 0xCC, 0x80, 0xC9, 0x03, 0x41, 0xCC, 0x81,
+ 0xC9, 0x03, 0x41, 0xCC, 0x83, 0xC9, 0x03, 0x41,
+ // Bytes 2f80 - 2fbf
+ 0xCC, 0x84, 0xC9, 0x03, 0x41, 0xCC, 0x89, 0xC9,
+ 0x03, 0x41, 0xCC, 0x8C, 0xC9, 0x03, 0x41, 0xCC,
+ 0x8F, 0xC9, 0x03, 0x41, 0xCC, 0x91, 0xC9, 0x03,
+ 0x41, 0xCC, 0xA5, 0xB5, 0x03, 0x41, 0xCC, 0xA8,
+ 0xA5, 0x03, 0x42, 0xCC, 0x87, 0xC9, 0x03, 0x42,
+ 0xCC, 0xA3, 0xB5, 0x03, 0x42, 0xCC, 0xB1, 0xB5,
+ 0x03, 0x43, 0xCC, 0x81, 0xC9, 0x03, 0x43, 0xCC,
+ 0x82, 0xC9, 0x03, 0x43, 0xCC, 0x87, 0xC9, 0x03,
+ // Bytes 2fc0 - 2fff
+ 0x43, 0xCC, 0x8C, 0xC9, 0x03, 0x44, 0xCC, 0x87,
+ 0xC9, 0x03, 0x44, 0xCC, 0x8C, 0xC9, 0x03, 0x44,
+ 0xCC, 0xA3, 0xB5, 0x03, 0x44, 0xCC, 0xA7, 0xA5,
+ 0x03, 0x44, 0xCC, 0xAD, 0xB5, 0x03, 0x44, 0xCC,
+ 0xB1, 0xB5, 0x03, 0x45, 0xCC, 0x80, 0xC9, 0x03,
+ 0x45, 0xCC, 0x81, 0xC9, 0x03, 0x45, 0xCC, 0x83,
+ 0xC9, 0x03, 0x45, 0xCC, 0x86, 0xC9, 0x03, 0x45,
+ 0xCC, 0x87, 0xC9, 0x03, 0x45, 0xCC, 0x88, 0xC9,
+ // Bytes 3000 - 303f
+ 0x03, 0x45, 0xCC, 0x89, 0xC9, 0x03, 0x45, 0xCC,
+ 0x8C, 0xC9, 0x03, 0x45, 0xCC, 0x8F, 0xC9, 0x03,
+ 0x45, 0xCC, 0x91, 0xC9, 0x03, 0x45, 0xCC, 0xA8,
+ 0xA5, 0x03, 0x45, 0xCC, 0xAD, 0xB5, 0x03, 0x45,
+ 0xCC, 0xB0, 0xB5, 0x03, 0x46, 0xCC, 0x87, 0xC9,
+ 0x03, 0x47, 0xCC, 0x81, 0xC9, 0x03, 0x47, 0xCC,
+ 0x82, 0xC9, 0x03, 0x47, 0xCC, 0x84, 0xC9, 0x03,
+ 0x47, 0xCC, 0x86, 0xC9, 0x03, 0x47, 0xCC, 0x87,
+ // Bytes 3040 - 307f
+ 0xC9, 0x03, 0x47, 0xCC, 0x8C, 0xC9, 0x03, 0x47,
+ 0xCC, 0xA7, 0xA5, 0x03, 0x48, 0xCC, 0x82, 0xC9,
+ 0x03, 0x48, 0xCC, 0x87, 0xC9, 0x03, 0x48, 0xCC,
+ 0x88, 0xC9, 0x03, 0x48, 0xCC, 0x8C, 0xC9, 0x03,
+ 0x48, 0xCC, 0xA3, 0xB5, 0x03, 0x48, 0xCC, 0xA7,
+ 0xA5, 0x03, 0x48, 0xCC, 0xAE, 0xB5, 0x03, 0x49,
+ 0xCC, 0x80, 0xC9, 0x03, 0x49, 0xCC, 0x81, 0xC9,
+ 0x03, 0x49, 0xCC, 0x82, 0xC9, 0x03, 0x49, 0xCC,
+ // Bytes 3080 - 30bf
+ 0x83, 0xC9, 0x03, 0x49, 0xCC, 0x84, 0xC9, 0x03,
+ 0x49, 0xCC, 0x86, 0xC9, 0x03, 0x49, 0xCC, 0x87,
+ 0xC9, 0x03, 0x49, 0xCC, 0x89, 0xC9, 0x03, 0x49,
+ 0xCC, 0x8C, 0xC9, 0x03, 0x49, 0xCC, 0x8F, 0xC9,
+ 0x03, 0x49, 0xCC, 0x91, 0xC9, 0x03, 0x49, 0xCC,
+ 0xA3, 0xB5, 0x03, 0x49, 0xCC, 0xA8, 0xA5, 0x03,
+ 0x49, 0xCC, 0xB0, 0xB5, 0x03, 0x4A, 0xCC, 0x82,
+ 0xC9, 0x03, 0x4B, 0xCC, 0x81, 0xC9, 0x03, 0x4B,
+ // Bytes 30c0 - 30ff
+ 0xCC, 0x8C, 0xC9, 0x03, 0x4B, 0xCC, 0xA3, 0xB5,
+ 0x03, 0x4B, 0xCC, 0xA7, 0xA5, 0x03, 0x4B, 0xCC,
+ 0xB1, 0xB5, 0x03, 0x4C, 0xCC, 0x81, 0xC9, 0x03,
+ 0x4C, 0xCC, 0x8C, 0xC9, 0x03, 0x4C, 0xCC, 0xA7,
+ 0xA5, 0x03, 0x4C, 0xCC, 0xAD, 0xB5, 0x03, 0x4C,
+ 0xCC, 0xB1, 0xB5, 0x03, 0x4D, 0xCC, 0x81, 0xC9,
+ 0x03, 0x4D, 0xCC, 0x87, 0xC9, 0x03, 0x4D, 0xCC,
+ 0xA3, 0xB5, 0x03, 0x4E, 0xCC, 0x80, 0xC9, 0x03,
+ // Bytes 3100 - 313f
+ 0x4E, 0xCC, 0x81, 0xC9, 0x03, 0x4E, 0xCC, 0x83,
+ 0xC9, 0x03, 0x4E, 0xCC, 0x87, 0xC9, 0x03, 0x4E,
+ 0xCC, 0x8C, 0xC9, 0x03, 0x4E, 0xCC, 0xA3, 0xB5,
+ 0x03, 0x4E, 0xCC, 0xA7, 0xA5, 0x03, 0x4E, 0xCC,
+ 0xAD, 0xB5, 0x03, 0x4E, 0xCC, 0xB1, 0xB5, 0x03,
+ 0x4F, 0xCC, 0x80, 0xC9, 0x03, 0x4F, 0xCC, 0x81,
+ 0xC9, 0x03, 0x4F, 0xCC, 0x86, 0xC9, 0x03, 0x4F,
+ 0xCC, 0x89, 0xC9, 0x03, 0x4F, 0xCC, 0x8B, 0xC9,
+ // Bytes 3140 - 317f
+ 0x03, 0x4F, 0xCC, 0x8C, 0xC9, 0x03, 0x4F, 0xCC,
+ 0x8F, 0xC9, 0x03, 0x4F, 0xCC, 0x91, 0xC9, 0x03,
+ 0x50, 0xCC, 0x81, 0xC9, 0x03, 0x50, 0xCC, 0x87,
+ 0xC9, 0x03, 0x52, 0xCC, 0x81, 0xC9, 0x03, 0x52,
+ 0xCC, 0x87, 0xC9, 0x03, 0x52, 0xCC, 0x8C, 0xC9,
+ 0x03, 0x52, 0xCC, 0x8F, 0xC9, 0x03, 0x52, 0xCC,
+ 0x91, 0xC9, 0x03, 0x52, 0xCC, 0xA7, 0xA5, 0x03,
+ 0x52, 0xCC, 0xB1, 0xB5, 0x03, 0x53, 0xCC, 0x82,
+ // Bytes 3180 - 31bf
+ 0xC9, 0x03, 0x53, 0xCC, 0x87, 0xC9, 0x03, 0x53,
+ 0xCC, 0xA6, 0xB5, 0x03, 0x53, 0xCC, 0xA7, 0xA5,
+ 0x03, 0x54, 0xCC, 0x87, 0xC9, 0x03, 0x54, 0xCC,
+ 0x8C, 0xC9, 0x03, 0x54, 0xCC, 0xA3, 0xB5, 0x03,
+ 0x54, 0xCC, 0xA6, 0xB5, 0x03, 0x54, 0xCC, 0xA7,
+ 0xA5, 0x03, 0x54, 0xCC, 0xAD, 0xB5, 0x03, 0x54,
+ 0xCC, 0xB1, 0xB5, 0x03, 0x55, 0xCC, 0x80, 0xC9,
+ 0x03, 0x55, 0xCC, 0x81, 0xC9, 0x03, 0x55, 0xCC,
+ // Bytes 31c0 - 31ff
+ 0x82, 0xC9, 0x03, 0x55, 0xCC, 0x86, 0xC9, 0x03,
+ 0x55, 0xCC, 0x89, 0xC9, 0x03, 0x55, 0xCC, 0x8A,
+ 0xC9, 0x03, 0x55, 0xCC, 0x8B, 0xC9, 0x03, 0x55,
+ 0xCC, 0x8C, 0xC9, 0x03, 0x55, 0xCC, 0x8F, 0xC9,
+ 0x03, 0x55, 0xCC, 0x91, 0xC9, 0x03, 0x55, 0xCC,
+ 0xA3, 0xB5, 0x03, 0x55, 0xCC, 0xA4, 0xB5, 0x03,
+ 0x55, 0xCC, 0xA8, 0xA5, 0x03, 0x55, 0xCC, 0xAD,
+ 0xB5, 0x03, 0x55, 0xCC, 0xB0, 0xB5, 0x03, 0x56,
+ // Bytes 3200 - 323f
+ 0xCC, 0x83, 0xC9, 0x03, 0x56, 0xCC, 0xA3, 0xB5,
+ 0x03, 0x57, 0xCC, 0x80, 0xC9, 0x03, 0x57, 0xCC,
+ 0x81, 0xC9, 0x03, 0x57, 0xCC, 0x82, 0xC9, 0x03,
+ 0x57, 0xCC, 0x87, 0xC9, 0x03, 0x57, 0xCC, 0x88,
+ 0xC9, 0x03, 0x57, 0xCC, 0xA3, 0xB5, 0x03, 0x58,
+ 0xCC, 0x87, 0xC9, 0x03, 0x58, 0xCC, 0x88, 0xC9,
+ 0x03, 0x59, 0xCC, 0x80, 0xC9, 0x03, 0x59, 0xCC,
+ 0x81, 0xC9, 0x03, 0x59, 0xCC, 0x82, 0xC9, 0x03,
+ // Bytes 3240 - 327f
+ 0x59, 0xCC, 0x83, 0xC9, 0x03, 0x59, 0xCC, 0x84,
+ 0xC9, 0x03, 0x59, 0xCC, 0x87, 0xC9, 0x03, 0x59,
+ 0xCC, 0x88, 0xC9, 0x03, 0x59, 0xCC, 0x89, 0xC9,
+ 0x03, 0x59, 0xCC, 0xA3, 0xB5, 0x03, 0x5A, 0xCC,
+ 0x81, 0xC9, 0x03, 0x5A, 0xCC, 0x82, 0xC9, 0x03,
+ 0x5A, 0xCC, 0x87, 0xC9, 0x03, 0x5A, 0xCC, 0x8C,
+ 0xC9, 0x03, 0x5A, 0xCC, 0xA3, 0xB5, 0x03, 0x5A,
+ 0xCC, 0xB1, 0xB5, 0x03, 0x61, 0xCC, 0x80, 0xC9,
+ // Bytes 3280 - 32bf
+ 0x03, 0x61, 0xCC, 0x81, 0xC9, 0x03, 0x61, 0xCC,
+ 0x83, 0xC9, 0x03, 0x61, 0xCC, 0x84, 0xC9, 0x03,
+ 0x61, 0xCC, 0x89, 0xC9, 0x03, 0x61, 0xCC, 0x8C,
+ 0xC9, 0x03, 0x61, 0xCC, 0x8F, 0xC9, 0x03, 0x61,
+ 0xCC, 0x91, 0xC9, 0x03, 0x61, 0xCC, 0xA5, 0xB5,
+ 0x03, 0x61, 0xCC, 0xA8, 0xA5, 0x03, 0x62, 0xCC,
+ 0x87, 0xC9, 0x03, 0x62, 0xCC, 0xA3, 0xB5, 0x03,
+ 0x62, 0xCC, 0xB1, 0xB5, 0x03, 0x63, 0xCC, 0x81,
+ // Bytes 32c0 - 32ff
+ 0xC9, 0x03, 0x63, 0xCC, 0x82, 0xC9, 0x03, 0x63,
+ 0xCC, 0x87, 0xC9, 0x03, 0x63, 0xCC, 0x8C, 0xC9,
+ 0x03, 0x64, 0xCC, 0x87, 0xC9, 0x03, 0x64, 0xCC,
+ 0x8C, 0xC9, 0x03, 0x64, 0xCC, 0xA3, 0xB5, 0x03,
+ 0x64, 0xCC, 0xA7, 0xA5, 0x03, 0x64, 0xCC, 0xAD,
+ 0xB5, 0x03, 0x64, 0xCC, 0xB1, 0xB5, 0x03, 0x65,
+ 0xCC, 0x80, 0xC9, 0x03, 0x65, 0xCC, 0x81, 0xC9,
+ 0x03, 0x65, 0xCC, 0x83, 0xC9, 0x03, 0x65, 0xCC,
+ // Bytes 3300 - 333f
+ 0x86, 0xC9, 0x03, 0x65, 0xCC, 0x87, 0xC9, 0x03,
+ 0x65, 0xCC, 0x88, 0xC9, 0x03, 0x65, 0xCC, 0x89,
+ 0xC9, 0x03, 0x65, 0xCC, 0x8C, 0xC9, 0x03, 0x65,
+ 0xCC, 0x8F, 0xC9, 0x03, 0x65, 0xCC, 0x91, 0xC9,
+ 0x03, 0x65, 0xCC, 0xA8, 0xA5, 0x03, 0x65, 0xCC,
+ 0xAD, 0xB5, 0x03, 0x65, 0xCC, 0xB0, 0xB5, 0x03,
+ 0x66, 0xCC, 0x87, 0xC9, 0x03, 0x67, 0xCC, 0x81,
+ 0xC9, 0x03, 0x67, 0xCC, 0x82, 0xC9, 0x03, 0x67,
+ // Bytes 3340 - 337f
+ 0xCC, 0x84, 0xC9, 0x03, 0x67, 0xCC, 0x86, 0xC9,
+ 0x03, 0x67, 0xCC, 0x87, 0xC9, 0x03, 0x67, 0xCC,
+ 0x8C, 0xC9, 0x03, 0x67, 0xCC, 0xA7, 0xA5, 0x03,
+ 0x68, 0xCC, 0x82, 0xC9, 0x03, 0x68, 0xCC, 0x87,
+ 0xC9, 0x03, 0x68, 0xCC, 0x88, 0xC9, 0x03, 0x68,
+ 0xCC, 0x8C, 0xC9, 0x03, 0x68, 0xCC, 0xA3, 0xB5,
+ 0x03, 0x68, 0xCC, 0xA7, 0xA5, 0x03, 0x68, 0xCC,
+ 0xAE, 0xB5, 0x03, 0x68, 0xCC, 0xB1, 0xB5, 0x03,
+ // Bytes 3380 - 33bf
+ 0x69, 0xCC, 0x80, 0xC9, 0x03, 0x69, 0xCC, 0x81,
+ 0xC9, 0x03, 0x69, 0xCC, 0x82, 0xC9, 0x03, 0x69,
+ 0xCC, 0x83, 0xC9, 0x03, 0x69, 0xCC, 0x84, 0xC9,
+ 0x03, 0x69, 0xCC, 0x86, 0xC9, 0x03, 0x69, 0xCC,
+ 0x89, 0xC9, 0x03, 0x69, 0xCC, 0x8C, 0xC9, 0x03,
+ 0x69, 0xCC, 0x8F, 0xC9, 0x03, 0x69, 0xCC, 0x91,
+ 0xC9, 0x03, 0x69, 0xCC, 0xA3, 0xB5, 0x03, 0x69,
+ 0xCC, 0xA8, 0xA5, 0x03, 0x69, 0xCC, 0xB0, 0xB5,
+ // Bytes 33c0 - 33ff
+ 0x03, 0x6A, 0xCC, 0x82, 0xC9, 0x03, 0x6A, 0xCC,
+ 0x8C, 0xC9, 0x03, 0x6B, 0xCC, 0x81, 0xC9, 0x03,
+ 0x6B, 0xCC, 0x8C, 0xC9, 0x03, 0x6B, 0xCC, 0xA3,
+ 0xB5, 0x03, 0x6B, 0xCC, 0xA7, 0xA5, 0x03, 0x6B,
+ 0xCC, 0xB1, 0xB5, 0x03, 0x6C, 0xCC, 0x81, 0xC9,
+ 0x03, 0x6C, 0xCC, 0x8C, 0xC9, 0x03, 0x6C, 0xCC,
+ 0xA7, 0xA5, 0x03, 0x6C, 0xCC, 0xAD, 0xB5, 0x03,
+ 0x6C, 0xCC, 0xB1, 0xB5, 0x03, 0x6D, 0xCC, 0x81,
+ // Bytes 3400 - 343f
+ 0xC9, 0x03, 0x6D, 0xCC, 0x87, 0xC9, 0x03, 0x6D,
+ 0xCC, 0xA3, 0xB5, 0x03, 0x6E, 0xCC, 0x80, 0xC9,
+ 0x03, 0x6E, 0xCC, 0x81, 0xC9, 0x03, 0x6E, 0xCC,
+ 0x83, 0xC9, 0x03, 0x6E, 0xCC, 0x87, 0xC9, 0x03,
+ 0x6E, 0xCC, 0x8C, 0xC9, 0x03, 0x6E, 0xCC, 0xA3,
+ 0xB5, 0x03, 0x6E, 0xCC, 0xA7, 0xA5, 0x03, 0x6E,
+ 0xCC, 0xAD, 0xB5, 0x03, 0x6E, 0xCC, 0xB1, 0xB5,
+ 0x03, 0x6F, 0xCC, 0x80, 0xC9, 0x03, 0x6F, 0xCC,
+ // Bytes 3440 - 347f
+ 0x81, 0xC9, 0x03, 0x6F, 0xCC, 0x86, 0xC9, 0x03,
+ 0x6F, 0xCC, 0x89, 0xC9, 0x03, 0x6F, 0xCC, 0x8B,
+ 0xC9, 0x03, 0x6F, 0xCC, 0x8C, 0xC9, 0x03, 0x6F,
+ 0xCC, 0x8F, 0xC9, 0x03, 0x6F, 0xCC, 0x91, 0xC9,
+ 0x03, 0x70, 0xCC, 0x81, 0xC9, 0x03, 0x70, 0xCC,
+ 0x87, 0xC9, 0x03, 0x72, 0xCC, 0x81, 0xC9, 0x03,
+ 0x72, 0xCC, 0x87, 0xC9, 0x03, 0x72, 0xCC, 0x8C,
+ 0xC9, 0x03, 0x72, 0xCC, 0x8F, 0xC9, 0x03, 0x72,
+ // Bytes 3480 - 34bf
+ 0xCC, 0x91, 0xC9, 0x03, 0x72, 0xCC, 0xA7, 0xA5,
+ 0x03, 0x72, 0xCC, 0xB1, 0xB5, 0x03, 0x73, 0xCC,
+ 0x82, 0xC9, 0x03, 0x73, 0xCC, 0x87, 0xC9, 0x03,
+ 0x73, 0xCC, 0xA6, 0xB5, 0x03, 0x73, 0xCC, 0xA7,
+ 0xA5, 0x03, 0x74, 0xCC, 0x87, 0xC9, 0x03, 0x74,
+ 0xCC, 0x88, 0xC9, 0x03, 0x74, 0xCC, 0x8C, 0xC9,
+ 0x03, 0x74, 0xCC, 0xA3, 0xB5, 0x03, 0x74, 0xCC,
+ 0xA6, 0xB5, 0x03, 0x74, 0xCC, 0xA7, 0xA5, 0x03,
+ // Bytes 34c0 - 34ff
+ 0x74, 0xCC, 0xAD, 0xB5, 0x03, 0x74, 0xCC, 0xB1,
+ 0xB5, 0x03, 0x75, 0xCC, 0x80, 0xC9, 0x03, 0x75,
+ 0xCC, 0x81, 0xC9, 0x03, 0x75, 0xCC, 0x82, 0xC9,
+ 0x03, 0x75, 0xCC, 0x86, 0xC9, 0x03, 0x75, 0xCC,
+ 0x89, 0xC9, 0x03, 0x75, 0xCC, 0x8A, 0xC9, 0x03,
+ 0x75, 0xCC, 0x8B, 0xC9, 0x03, 0x75, 0xCC, 0x8C,
+ 0xC9, 0x03, 0x75, 0xCC, 0x8F, 0xC9, 0x03, 0x75,
+ 0xCC, 0x91, 0xC9, 0x03, 0x75, 0xCC, 0xA3, 0xB5,
+ // Bytes 3500 - 353f
+ 0x03, 0x75, 0xCC, 0xA4, 0xB5, 0x03, 0x75, 0xCC,
+ 0xA8, 0xA5, 0x03, 0x75, 0xCC, 0xAD, 0xB5, 0x03,
+ 0x75, 0xCC, 0xB0, 0xB5, 0x03, 0x76, 0xCC, 0x83,
+ 0xC9, 0x03, 0x76, 0xCC, 0xA3, 0xB5, 0x03, 0x77,
+ 0xCC, 0x80, 0xC9, 0x03, 0x77, 0xCC, 0x81, 0xC9,
+ 0x03, 0x77, 0xCC, 0x82, 0xC9, 0x03, 0x77, 0xCC,
+ 0x87, 0xC9, 0x03, 0x77, 0xCC, 0x88, 0xC9, 0x03,
+ 0x77, 0xCC, 0x8A, 0xC9, 0x03, 0x77, 0xCC, 0xA3,
+ // Bytes 3540 - 357f
+ 0xB5, 0x03, 0x78, 0xCC, 0x87, 0xC9, 0x03, 0x78,
+ 0xCC, 0x88, 0xC9, 0x03, 0x79, 0xCC, 0x80, 0xC9,
+ 0x03, 0x79, 0xCC, 0x81, 0xC9, 0x03, 0x79, 0xCC,
+ 0x82, 0xC9, 0x03, 0x79, 0xCC, 0x83, 0xC9, 0x03,
+ 0x79, 0xCC, 0x84, 0xC9, 0x03, 0x79, 0xCC, 0x87,
+ 0xC9, 0x03, 0x79, 0xCC, 0x88, 0xC9, 0x03, 0x79,
+ 0xCC, 0x89, 0xC9, 0x03, 0x79, 0xCC, 0x8A, 0xC9,
+ 0x03, 0x79, 0xCC, 0xA3, 0xB5, 0x03, 0x7A, 0xCC,
+ // Bytes 3580 - 35bf
+ 0x81, 0xC9, 0x03, 0x7A, 0xCC, 0x82, 0xC9, 0x03,
+ 0x7A, 0xCC, 0x87, 0xC9, 0x03, 0x7A, 0xCC, 0x8C,
+ 0xC9, 0x03, 0x7A, 0xCC, 0xA3, 0xB5, 0x03, 0x7A,
+ 0xCC, 0xB1, 0xB5, 0x04, 0xC2, 0xA8, 0xCC, 0x80,
+ 0xCA, 0x04, 0xC2, 0xA8, 0xCC, 0x81, 0xCA, 0x04,
+ 0xC2, 0xA8, 0xCD, 0x82, 0xCA, 0x04, 0xC3, 0x86,
+ 0xCC, 0x81, 0xC9, 0x04, 0xC3, 0x86, 0xCC, 0x84,
+ 0xC9, 0x04, 0xC3, 0x98, 0xCC, 0x81, 0xC9, 0x04,
+ // Bytes 35c0 - 35ff
+ 0xC3, 0xA6, 0xCC, 0x81, 0xC9, 0x04, 0xC3, 0xA6,
+ 0xCC, 0x84, 0xC9, 0x04, 0xC3, 0xB8, 0xCC, 0x81,
+ 0xC9, 0x04, 0xC5, 0xBF, 0xCC, 0x87, 0xC9, 0x04,
+ 0xC6, 0xB7, 0xCC, 0x8C, 0xC9, 0x04, 0xCA, 0x92,
+ 0xCC, 0x8C, 0xC9, 0x04, 0xCE, 0x91, 0xCC, 0x80,
+ 0xC9, 0x04, 0xCE, 0x91, 0xCC, 0x81, 0xC9, 0x04,
+ 0xCE, 0x91, 0xCC, 0x84, 0xC9, 0x04, 0xCE, 0x91,
+ 0xCC, 0x86, 0xC9, 0x04, 0xCE, 0x91, 0xCD, 0x85,
+ // Bytes 3600 - 363f
+ 0xD9, 0x04, 0xCE, 0x95, 0xCC, 0x80, 0xC9, 0x04,
+ 0xCE, 0x95, 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0x97,
+ 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0x97, 0xCC, 0x81,
+ 0xC9, 0x04, 0xCE, 0x97, 0xCD, 0x85, 0xD9, 0x04,
+ 0xCE, 0x99, 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0x99,
+ 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0x99, 0xCC, 0x84,
+ 0xC9, 0x04, 0xCE, 0x99, 0xCC, 0x86, 0xC9, 0x04,
+ 0xCE, 0x99, 0xCC, 0x88, 0xC9, 0x04, 0xCE, 0x9F,
+ // Bytes 3640 - 367f
+ 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0x9F, 0xCC, 0x81,
+ 0xC9, 0x04, 0xCE, 0xA1, 0xCC, 0x94, 0xC9, 0x04,
+ 0xCE, 0xA5, 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0xA5,
+ 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0xA5, 0xCC, 0x84,
+ 0xC9, 0x04, 0xCE, 0xA5, 0xCC, 0x86, 0xC9, 0x04,
+ 0xCE, 0xA5, 0xCC, 0x88, 0xC9, 0x04, 0xCE, 0xA9,
+ 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0xA9, 0xCC, 0x81,
+ 0xC9, 0x04, 0xCE, 0xA9, 0xCD, 0x85, 0xD9, 0x04,
+ // Bytes 3680 - 36bf
+ 0xCE, 0xB1, 0xCC, 0x84, 0xC9, 0x04, 0xCE, 0xB1,
+ 0xCC, 0x86, 0xC9, 0x04, 0xCE, 0xB1, 0xCD, 0x85,
+ 0xD9, 0x04, 0xCE, 0xB5, 0xCC, 0x80, 0xC9, 0x04,
+ 0xCE, 0xB5, 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0xB7,
+ 0xCD, 0x85, 0xD9, 0x04, 0xCE, 0xB9, 0xCC, 0x80,
+ 0xC9, 0x04, 0xCE, 0xB9, 0xCC, 0x81, 0xC9, 0x04,
+ 0xCE, 0xB9, 0xCC, 0x84, 0xC9, 0x04, 0xCE, 0xB9,
+ 0xCC, 0x86, 0xC9, 0x04, 0xCE, 0xB9, 0xCD, 0x82,
+ // Bytes 36c0 - 36ff
+ 0xC9, 0x04, 0xCE, 0xBF, 0xCC, 0x80, 0xC9, 0x04,
+ 0xCE, 0xBF, 0xCC, 0x81, 0xC9, 0x04, 0xCF, 0x81,
+ 0xCC, 0x93, 0xC9, 0x04, 0xCF, 0x81, 0xCC, 0x94,
+ 0xC9, 0x04, 0xCF, 0x85, 0xCC, 0x80, 0xC9, 0x04,
+ 0xCF, 0x85, 0xCC, 0x81, 0xC9, 0x04, 0xCF, 0x85,
+ 0xCC, 0x84, 0xC9, 0x04, 0xCF, 0x85, 0xCC, 0x86,
+ 0xC9, 0x04, 0xCF, 0x85, 0xCD, 0x82, 0xC9, 0x04,
+ 0xCF, 0x89, 0xCD, 0x85, 0xD9, 0x04, 0xCF, 0x92,
+ // Bytes 3700 - 373f
+ 0xCC, 0x81, 0xC9, 0x04, 0xCF, 0x92, 0xCC, 0x88,
+ 0xC9, 0x04, 0xD0, 0x86, 0xCC, 0x88, 0xC9, 0x04,
+ 0xD0, 0x90, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0x90,
+ 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0x93, 0xCC, 0x81,
+ 0xC9, 0x04, 0xD0, 0x95, 0xCC, 0x80, 0xC9, 0x04,
+ 0xD0, 0x95, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0x95,
+ 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0x96, 0xCC, 0x86,
+ 0xC9, 0x04, 0xD0, 0x96, 0xCC, 0x88, 0xC9, 0x04,
+ // Bytes 3740 - 377f
+ 0xD0, 0x97, 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0x98,
+ 0xCC, 0x80, 0xC9, 0x04, 0xD0, 0x98, 0xCC, 0x84,
+ 0xC9, 0x04, 0xD0, 0x98, 0xCC, 0x86, 0xC9, 0x04,
+ 0xD0, 0x98, 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0x9A,
+ 0xCC, 0x81, 0xC9, 0x04, 0xD0, 0x9E, 0xCC, 0x88,
+ 0xC9, 0x04, 0xD0, 0xA3, 0xCC, 0x84, 0xC9, 0x04,
+ 0xD0, 0xA3, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0xA3,
+ 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xA3, 0xCC, 0x8B,
+ // Bytes 3780 - 37bf
+ 0xC9, 0x04, 0xD0, 0xA7, 0xCC, 0x88, 0xC9, 0x04,
+ 0xD0, 0xAB, 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xAD,
+ 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xB0, 0xCC, 0x86,
+ 0xC9, 0x04, 0xD0, 0xB0, 0xCC, 0x88, 0xC9, 0x04,
+ 0xD0, 0xB3, 0xCC, 0x81, 0xC9, 0x04, 0xD0, 0xB5,
+ 0xCC, 0x80, 0xC9, 0x04, 0xD0, 0xB5, 0xCC, 0x86,
+ 0xC9, 0x04, 0xD0, 0xB5, 0xCC, 0x88, 0xC9, 0x04,
+ 0xD0, 0xB6, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0xB6,
+ // Bytes 37c0 - 37ff
+ 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xB7, 0xCC, 0x88,
+ 0xC9, 0x04, 0xD0, 0xB8, 0xCC, 0x80, 0xC9, 0x04,
+ 0xD0, 0xB8, 0xCC, 0x84, 0xC9, 0x04, 0xD0, 0xB8,
+ 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0xB8, 0xCC, 0x88,
+ 0xC9, 0x04, 0xD0, 0xBA, 0xCC, 0x81, 0xC9, 0x04,
+ 0xD0, 0xBE, 0xCC, 0x88, 0xC9, 0x04, 0xD1, 0x83,
+ 0xCC, 0x84, 0xC9, 0x04, 0xD1, 0x83, 0xCC, 0x86,
+ 0xC9, 0x04, 0xD1, 0x83, 0xCC, 0x88, 0xC9, 0x04,
+ // Bytes 3800 - 383f
+ 0xD1, 0x83, 0xCC, 0x8B, 0xC9, 0x04, 0xD1, 0x87,
+ 0xCC, 0x88, 0xC9, 0x04, 0xD1, 0x8B, 0xCC, 0x88,
+ 0xC9, 0x04, 0xD1, 0x8D, 0xCC, 0x88, 0xC9, 0x04,
+ 0xD1, 0x96, 0xCC, 0x88, 0xC9, 0x04, 0xD1, 0xB4,
+ 0xCC, 0x8F, 0xC9, 0x04, 0xD1, 0xB5, 0xCC, 0x8F,
+ 0xC9, 0x04, 0xD3, 0x98, 0xCC, 0x88, 0xC9, 0x04,
+ 0xD3, 0x99, 0xCC, 0x88, 0xC9, 0x04, 0xD3, 0xA8,
+ 0xCC, 0x88, 0xC9, 0x04, 0xD3, 0xA9, 0xCC, 0x88,
+ // Bytes 3840 - 387f
+ 0xC9, 0x04, 0xD8, 0xA7, 0xD9, 0x93, 0xC9, 0x04,
+ 0xD8, 0xA7, 0xD9, 0x94, 0xC9, 0x04, 0xD8, 0xA7,
+ 0xD9, 0x95, 0xB5, 0x04, 0xD9, 0x88, 0xD9, 0x94,
+ 0xC9, 0x04, 0xD9, 0x8A, 0xD9, 0x94, 0xC9, 0x04,
+ 0xDB, 0x81, 0xD9, 0x94, 0xC9, 0x04, 0xDB, 0x92,
+ 0xD9, 0x94, 0xC9, 0x04, 0xDB, 0x95, 0xD9, 0x94,
+ 0xC9, 0x05, 0x41, 0xCC, 0x82, 0xCC, 0x80, 0xCA,
+ 0x05, 0x41, 0xCC, 0x82, 0xCC, 0x81, 0xCA, 0x05,
+ // Bytes 3880 - 38bf
+ 0x41, 0xCC, 0x82, 0xCC, 0x83, 0xCA, 0x05, 0x41,
+ 0xCC, 0x82, 0xCC, 0x89, 0xCA, 0x05, 0x41, 0xCC,
+ 0x86, 0xCC, 0x80, 0xCA, 0x05, 0x41, 0xCC, 0x86,
+ 0xCC, 0x81, 0xCA, 0x05, 0x41, 0xCC, 0x86, 0xCC,
+ 0x83, 0xCA, 0x05, 0x41, 0xCC, 0x86, 0xCC, 0x89,
+ 0xCA, 0x05, 0x41, 0xCC, 0x87, 0xCC, 0x84, 0xCA,
+ 0x05, 0x41, 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05,
+ 0x41, 0xCC, 0x8A, 0xCC, 0x81, 0xCA, 0x05, 0x41,
+ // Bytes 38c0 - 38ff
+ 0xCC, 0xA3, 0xCC, 0x82, 0xCA, 0x05, 0x41, 0xCC,
+ 0xA3, 0xCC, 0x86, 0xCA, 0x05, 0x43, 0xCC, 0xA7,
+ 0xCC, 0x81, 0xCA, 0x05, 0x45, 0xCC, 0x82, 0xCC,
+ 0x80, 0xCA, 0x05, 0x45, 0xCC, 0x82, 0xCC, 0x81,
+ 0xCA, 0x05, 0x45, 0xCC, 0x82, 0xCC, 0x83, 0xCA,
+ 0x05, 0x45, 0xCC, 0x82, 0xCC, 0x89, 0xCA, 0x05,
+ 0x45, 0xCC, 0x84, 0xCC, 0x80, 0xCA, 0x05, 0x45,
+ 0xCC, 0x84, 0xCC, 0x81, 0xCA, 0x05, 0x45, 0xCC,
+ // Bytes 3900 - 393f
+ 0xA3, 0xCC, 0x82, 0xCA, 0x05, 0x45, 0xCC, 0xA7,
+ 0xCC, 0x86, 0xCA, 0x05, 0x49, 0xCC, 0x88, 0xCC,
+ 0x81, 0xCA, 0x05, 0x4C, 0xCC, 0xA3, 0xCC, 0x84,
+ 0xCA, 0x05, 0x4F, 0xCC, 0x82, 0xCC, 0x80, 0xCA,
+ 0x05, 0x4F, 0xCC, 0x82, 0xCC, 0x81, 0xCA, 0x05,
+ 0x4F, 0xCC, 0x82, 0xCC, 0x83, 0xCA, 0x05, 0x4F,
+ 0xCC, 0x82, 0xCC, 0x89, 0xCA, 0x05, 0x4F, 0xCC,
+ 0x83, 0xCC, 0x81, 0xCA, 0x05, 0x4F, 0xCC, 0x83,
+ // Bytes 3940 - 397f
+ 0xCC, 0x84, 0xCA, 0x05, 0x4F, 0xCC, 0x83, 0xCC,
+ 0x88, 0xCA, 0x05, 0x4F, 0xCC, 0x84, 0xCC, 0x80,
+ 0xCA, 0x05, 0x4F, 0xCC, 0x84, 0xCC, 0x81, 0xCA,
+ 0x05, 0x4F, 0xCC, 0x87, 0xCC, 0x84, 0xCA, 0x05,
+ 0x4F, 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, 0x4F,
+ 0xCC, 0x9B, 0xCC, 0x80, 0xCA, 0x05, 0x4F, 0xCC,
+ 0x9B, 0xCC, 0x81, 0xCA, 0x05, 0x4F, 0xCC, 0x9B,
+ 0xCC, 0x83, 0xCA, 0x05, 0x4F, 0xCC, 0x9B, 0xCC,
+ // Bytes 3980 - 39bf
+ 0x89, 0xCA, 0x05, 0x4F, 0xCC, 0x9B, 0xCC, 0xA3,
+ 0xB6, 0x05, 0x4F, 0xCC, 0xA3, 0xCC, 0x82, 0xCA,
+ 0x05, 0x4F, 0xCC, 0xA8, 0xCC, 0x84, 0xCA, 0x05,
+ 0x52, 0xCC, 0xA3, 0xCC, 0x84, 0xCA, 0x05, 0x53,
+ 0xCC, 0x81, 0xCC, 0x87, 0xCA, 0x05, 0x53, 0xCC,
+ 0x8C, 0xCC, 0x87, 0xCA, 0x05, 0x53, 0xCC, 0xA3,
+ 0xCC, 0x87, 0xCA, 0x05, 0x55, 0xCC, 0x83, 0xCC,
+ 0x81, 0xCA, 0x05, 0x55, 0xCC, 0x84, 0xCC, 0x88,
+ // Bytes 39c0 - 39ff
+ 0xCA, 0x05, 0x55, 0xCC, 0x88, 0xCC, 0x80, 0xCA,
+ 0x05, 0x55, 0xCC, 0x88, 0xCC, 0x81, 0xCA, 0x05,
+ 0x55, 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, 0x55,
+ 0xCC, 0x88, 0xCC, 0x8C, 0xCA, 0x05, 0x55, 0xCC,
+ 0x9B, 0xCC, 0x80, 0xCA, 0x05, 0x55, 0xCC, 0x9B,
+ 0xCC, 0x81, 0xCA, 0x05, 0x55, 0xCC, 0x9B, 0xCC,
+ 0x83, 0xCA, 0x05, 0x55, 0xCC, 0x9B, 0xCC, 0x89,
+ 0xCA, 0x05, 0x55, 0xCC, 0x9B, 0xCC, 0xA3, 0xB6,
+ // Bytes 3a00 - 3a3f
+ 0x05, 0x61, 0xCC, 0x82, 0xCC, 0x80, 0xCA, 0x05,
+ 0x61, 0xCC, 0x82, 0xCC, 0x81, 0xCA, 0x05, 0x61,
+ 0xCC, 0x82, 0xCC, 0x83, 0xCA, 0x05, 0x61, 0xCC,
+ 0x82, 0xCC, 0x89, 0xCA, 0x05, 0x61, 0xCC, 0x86,
+ 0xCC, 0x80, 0xCA, 0x05, 0x61, 0xCC, 0x86, 0xCC,
+ 0x81, 0xCA, 0x05, 0x61, 0xCC, 0x86, 0xCC, 0x83,
+ 0xCA, 0x05, 0x61, 0xCC, 0x86, 0xCC, 0x89, 0xCA,
+ 0x05, 0x61, 0xCC, 0x87, 0xCC, 0x84, 0xCA, 0x05,
+ // Bytes 3a40 - 3a7f
+ 0x61, 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, 0x61,
+ 0xCC, 0x8A, 0xCC, 0x81, 0xCA, 0x05, 0x61, 0xCC,
+ 0xA3, 0xCC, 0x82, 0xCA, 0x05, 0x61, 0xCC, 0xA3,
+ 0xCC, 0x86, 0xCA, 0x05, 0x63, 0xCC, 0xA7, 0xCC,
+ 0x81, 0xCA, 0x05, 0x65, 0xCC, 0x82, 0xCC, 0x80,
+ 0xCA, 0x05, 0x65, 0xCC, 0x82, 0xCC, 0x81, 0xCA,
+ 0x05, 0x65, 0xCC, 0x82, 0xCC, 0x83, 0xCA, 0x05,
+ 0x65, 0xCC, 0x82, 0xCC, 0x89, 0xCA, 0x05, 0x65,
+ // Bytes 3a80 - 3abf
+ 0xCC, 0x84, 0xCC, 0x80, 0xCA, 0x05, 0x65, 0xCC,
+ 0x84, 0xCC, 0x81, 0xCA, 0x05, 0x65, 0xCC, 0xA3,
+ 0xCC, 0x82, 0xCA, 0x05, 0x65, 0xCC, 0xA7, 0xCC,
+ 0x86, 0xCA, 0x05, 0x69, 0xCC, 0x88, 0xCC, 0x81,
+ 0xCA, 0x05, 0x6C, 0xCC, 0xA3, 0xCC, 0x84, 0xCA,
+ 0x05, 0x6F, 0xCC, 0x82, 0xCC, 0x80, 0xCA, 0x05,
+ 0x6F, 0xCC, 0x82, 0xCC, 0x81, 0xCA, 0x05, 0x6F,
+ 0xCC, 0x82, 0xCC, 0x83, 0xCA, 0x05, 0x6F, 0xCC,
+ // Bytes 3ac0 - 3aff
+ 0x82, 0xCC, 0x89, 0xCA, 0x05, 0x6F, 0xCC, 0x83,
+ 0xCC, 0x81, 0xCA, 0x05, 0x6F, 0xCC, 0x83, 0xCC,
+ 0x84, 0xCA, 0x05, 0x6F, 0xCC, 0x83, 0xCC, 0x88,
+ 0xCA, 0x05, 0x6F, 0xCC, 0x84, 0xCC, 0x80, 0xCA,
+ 0x05, 0x6F, 0xCC, 0x84, 0xCC, 0x81, 0xCA, 0x05,
+ 0x6F, 0xCC, 0x87, 0xCC, 0x84, 0xCA, 0x05, 0x6F,
+ 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, 0x6F, 0xCC,
+ 0x9B, 0xCC, 0x80, 0xCA, 0x05, 0x6F, 0xCC, 0x9B,
+ // Bytes 3b00 - 3b3f
+ 0xCC, 0x81, 0xCA, 0x05, 0x6F, 0xCC, 0x9B, 0xCC,
+ 0x83, 0xCA, 0x05, 0x6F, 0xCC, 0x9B, 0xCC, 0x89,
+ 0xCA, 0x05, 0x6F, 0xCC, 0x9B, 0xCC, 0xA3, 0xB6,
+ 0x05, 0x6F, 0xCC, 0xA3, 0xCC, 0x82, 0xCA, 0x05,
+ 0x6F, 0xCC, 0xA8, 0xCC, 0x84, 0xCA, 0x05, 0x72,
+ 0xCC, 0xA3, 0xCC, 0x84, 0xCA, 0x05, 0x73, 0xCC,
+ 0x81, 0xCC, 0x87, 0xCA, 0x05, 0x73, 0xCC, 0x8C,
+ 0xCC, 0x87, 0xCA, 0x05, 0x73, 0xCC, 0xA3, 0xCC,
+ // Bytes 3b40 - 3b7f
+ 0x87, 0xCA, 0x05, 0x75, 0xCC, 0x83, 0xCC, 0x81,
+ 0xCA, 0x05, 0x75, 0xCC, 0x84, 0xCC, 0x88, 0xCA,
+ 0x05, 0x75, 0xCC, 0x88, 0xCC, 0x80, 0xCA, 0x05,
+ 0x75, 0xCC, 0x88, 0xCC, 0x81, 0xCA, 0x05, 0x75,
+ 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, 0x75, 0xCC,
+ 0x88, 0xCC, 0x8C, 0xCA, 0x05, 0x75, 0xCC, 0x9B,
+ 0xCC, 0x80, 0xCA, 0x05, 0x75, 0xCC, 0x9B, 0xCC,
+ 0x81, 0xCA, 0x05, 0x75, 0xCC, 0x9B, 0xCC, 0x83,
+ // Bytes 3b80 - 3bbf
+ 0xCA, 0x05, 0x75, 0xCC, 0x9B, 0xCC, 0x89, 0xCA,
+ 0x05, 0x75, 0xCC, 0x9B, 0xCC, 0xA3, 0xB6, 0x05,
+ 0xE1, 0xBE, 0xBF, 0xCC, 0x80, 0xCA, 0x05, 0xE1,
+ 0xBE, 0xBF, 0xCC, 0x81, 0xCA, 0x05, 0xE1, 0xBE,
+ 0xBF, 0xCD, 0x82, 0xCA, 0x05, 0xE1, 0xBF, 0xBE,
+ 0xCC, 0x80, 0xCA, 0x05, 0xE1, 0xBF, 0xBE, 0xCC,
+ 0x81, 0xCA, 0x05, 0xE1, 0xBF, 0xBE, 0xCD, 0x82,
+ 0xCA, 0x05, 0xE2, 0x86, 0x90, 0xCC, 0xB8, 0x05,
+ // Bytes 3bc0 - 3bff
+ 0x05, 0xE2, 0x86, 0x92, 0xCC, 0xB8, 0x05, 0x05,
+ 0xE2, 0x86, 0x94, 0xCC, 0xB8, 0x05, 0x05, 0xE2,
+ 0x87, 0x90, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x87,
+ 0x92, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x87, 0x94,
+ 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x88, 0x83, 0xCC,
+ 0xB8, 0x05, 0x05, 0xE2, 0x88, 0x88, 0xCC, 0xB8,
+ 0x05, 0x05, 0xE2, 0x88, 0x8B, 0xCC, 0xB8, 0x05,
+ 0x05, 0xE2, 0x88, 0xA3, 0xCC, 0xB8, 0x05, 0x05,
+ // Bytes 3c00 - 3c3f
+ 0xE2, 0x88, 0xA5, 0xCC, 0xB8, 0x05, 0x05, 0xE2,
+ 0x88, 0xBC, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89,
+ 0x83, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0x85,
+ 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0x88, 0xCC,
+ 0xB8, 0x05, 0x05, 0xE2, 0x89, 0x8D, 0xCC, 0xB8,
+ 0x05, 0x05, 0xE2, 0x89, 0xA1, 0xCC, 0xB8, 0x05,
+ 0x05, 0xE2, 0x89, 0xA4, 0xCC, 0xB8, 0x05, 0x05,
+ 0xE2, 0x89, 0xA5, 0xCC, 0xB8, 0x05, 0x05, 0xE2,
+ // Bytes 3c40 - 3c7f
+ 0x89, 0xB2, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89,
+ 0xB3, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xB6,
+ 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xB7, 0xCC,
+ 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xBA, 0xCC, 0xB8,
+ 0x05, 0x05, 0xE2, 0x89, 0xBB, 0xCC, 0xB8, 0x05,
+ 0x05, 0xE2, 0x89, 0xBC, 0xCC, 0xB8, 0x05, 0x05,
+ 0xE2, 0x89, 0xBD, 0xCC, 0xB8, 0x05, 0x05, 0xE2,
+ 0x8A, 0x82, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A,
+ // Bytes 3c80 - 3cbf
+ 0x83, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0x86,
+ 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0x87, 0xCC,
+ 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0x91, 0xCC, 0xB8,
+ 0x05, 0x05, 0xE2, 0x8A, 0x92, 0xCC, 0xB8, 0x05,
+ 0x05, 0xE2, 0x8A, 0xA2, 0xCC, 0xB8, 0x05, 0x05,
+ 0xE2, 0x8A, 0xA8, 0xCC, 0xB8, 0x05, 0x05, 0xE2,
+ 0x8A, 0xA9, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A,
+ 0xAB, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0xB2,
+ // Bytes 3cc0 - 3cff
+ 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0xB3, 0xCC,
+ 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0xB4, 0xCC, 0xB8,
+ 0x05, 0x05, 0xE2, 0x8A, 0xB5, 0xCC, 0xB8, 0x05,
+ 0x06, 0xCE, 0x91, 0xCC, 0x93, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0x91, 0xCC, 0x94, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0x95, 0xCC, 0x93, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0x95, 0xCC, 0x93, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0x95, 0xCC, 0x94, 0xCC, 0x80, 0xCA,
+ // Bytes 3d00 - 3d3f
+ 0x06, 0xCE, 0x95, 0xCC, 0x94, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0x97, 0xCC, 0x93, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0x97, 0xCC, 0x94, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0x99, 0xCC, 0x93, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0x99, 0xCC, 0x93, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0x99, 0xCC, 0x93, 0xCD, 0x82, 0xCA,
+ 0x06, 0xCE, 0x99, 0xCC, 0x94, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0x99, 0xCC, 0x94, 0xCC, 0x81, 0xCA,
+ // Bytes 3d40 - 3d7f
+ 0x06, 0xCE, 0x99, 0xCC, 0x94, 0xCD, 0x82, 0xCA,
+ 0x06, 0xCE, 0x9F, 0xCC, 0x93, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0x9F, 0xCC, 0x93, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0x9F, 0xCC, 0x94, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0x9F, 0xCC, 0x94, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0xA5, 0xCC, 0x94, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0xA5, 0xCC, 0x94, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0xA5, 0xCC, 0x94, 0xCD, 0x82, 0xCA,
+ // Bytes 3d80 - 3dbf
+ 0x06, 0xCE, 0xA9, 0xCC, 0x93, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xA9, 0xCC, 0x94, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xB1, 0xCC, 0x80, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xB1, 0xCC, 0x81, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xB1, 0xCC, 0x93, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xB1, 0xCC, 0x94, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xB1, 0xCD, 0x82, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xB5, 0xCC, 0x93, 0xCC, 0x80, 0xCA,
+ // Bytes 3dc0 - 3dff
+ 0x06, 0xCE, 0xB5, 0xCC, 0x93, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0xB5, 0xCC, 0x94, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0xB5, 0xCC, 0x94, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0xB7, 0xCC, 0x80, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xB7, 0xCC, 0x81, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xB7, 0xCC, 0x93, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xB7, 0xCC, 0x94, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCE, 0xB7, 0xCD, 0x82, 0xCD, 0x85, 0xDA,
+ // Bytes 3e00 - 3e3f
+ 0x06, 0xCE, 0xB9, 0xCC, 0x88, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0xB9, 0xCC, 0x88, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0xB9, 0xCC, 0x88, 0xCD, 0x82, 0xCA,
+ 0x06, 0xCE, 0xB9, 0xCC, 0x93, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0xB9, 0xCC, 0x93, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0xB9, 0xCC, 0x93, 0xCD, 0x82, 0xCA,
+ 0x06, 0xCE, 0xB9, 0xCC, 0x94, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0xB9, 0xCC, 0x94, 0xCC, 0x81, 0xCA,
+ // Bytes 3e40 - 3e7f
+ 0x06, 0xCE, 0xB9, 0xCC, 0x94, 0xCD, 0x82, 0xCA,
+ 0x06, 0xCE, 0xBF, 0xCC, 0x93, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0xBF, 0xCC, 0x93, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCE, 0xBF, 0xCC, 0x94, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCE, 0xBF, 0xCC, 0x94, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCF, 0x85, 0xCC, 0x88, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCF, 0x85, 0xCC, 0x88, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCF, 0x85, 0xCC, 0x88, 0xCD, 0x82, 0xCA,
+ // Bytes 3e80 - 3ebf
+ 0x06, 0xCF, 0x85, 0xCC, 0x93, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCF, 0x85, 0xCC, 0x93, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCF, 0x85, 0xCC, 0x93, 0xCD, 0x82, 0xCA,
+ 0x06, 0xCF, 0x85, 0xCC, 0x94, 0xCC, 0x80, 0xCA,
+ 0x06, 0xCF, 0x85, 0xCC, 0x94, 0xCC, 0x81, 0xCA,
+ 0x06, 0xCF, 0x85, 0xCC, 0x94, 0xCD, 0x82, 0xCA,
+ 0x06, 0xCF, 0x89, 0xCC, 0x80, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCF, 0x89, 0xCC, 0x81, 0xCD, 0x85, 0xDA,
+ // Bytes 3ec0 - 3eff
+ 0x06, 0xCF, 0x89, 0xCC, 0x93, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCF, 0x89, 0xCC, 0x94, 0xCD, 0x85, 0xDA,
+ 0x06, 0xCF, 0x89, 0xCD, 0x82, 0xCD, 0x85, 0xDA,
+ 0x06, 0xE0, 0xA4, 0xA8, 0xE0, 0xA4, 0xBC, 0x09,
+ 0x06, 0xE0, 0xA4, 0xB0, 0xE0, 0xA4, 0xBC, 0x09,
+ 0x06, 0xE0, 0xA4, 0xB3, 0xE0, 0xA4, 0xBC, 0x09,
+ 0x06, 0xE0, 0xB1, 0x86, 0xE0, 0xB1, 0x96, 0x85,
+ 0x06, 0xE0, 0xB7, 0x99, 0xE0, 0xB7, 0x8A, 0x11,
+ // Bytes 3f00 - 3f3f
+ 0x06, 0xE3, 0x81, 0x86, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0x8B, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0x8D, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0x8F, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0x91, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0x93, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0x95, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0x97, 0xE3, 0x82, 0x99, 0x0D,
+ // Bytes 3f40 - 3f7f
+ 0x06, 0xE3, 0x81, 0x99, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0x9B, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0x9D, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0x9F, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0xA4, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0xA6, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0xA8, 0xE3, 0x82, 0x99, 0x0D,
+ // Bytes 3f80 - 3fbf
+ 0x06, 0xE3, 0x81, 0xAF, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0xAF, 0xE3, 0x82, 0x9A, 0x0D,
+ 0x06, 0xE3, 0x81, 0xB2, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0xB2, 0xE3, 0x82, 0x9A, 0x0D,
+ 0x06, 0xE3, 0x81, 0xB5, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0xB5, 0xE3, 0x82, 0x9A, 0x0D,
+ 0x06, 0xE3, 0x81, 0xB8, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0xB8, 0xE3, 0x82, 0x9A, 0x0D,
+ // Bytes 3fc0 - 3fff
+ 0x06, 0xE3, 0x81, 0xBB, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x81, 0xBB, 0xE3, 0x82, 0x9A, 0x0D,
+ 0x06, 0xE3, 0x82, 0x9D, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xA6, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xAB, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xAD, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xB1, 0xE3, 0x82, 0x99, 0x0D,
+ // Bytes 4000 - 403f
+ 0x06, 0xE3, 0x82, 0xB3, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xB5, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xB7, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xB9, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xBB, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xBD, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x82, 0xBF, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0x81, 0xE3, 0x82, 0x99, 0x0D,
+ // Bytes 4040 - 407f
+ 0x06, 0xE3, 0x83, 0x84, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0x86, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0x88, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0x8F, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0x8F, 0xE3, 0x82, 0x9A, 0x0D,
+ 0x06, 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x9A, 0x0D,
+ 0x06, 0xE3, 0x83, 0x95, 0xE3, 0x82, 0x99, 0x0D,
+ // Bytes 4080 - 40bf
+ 0x06, 0xE3, 0x83, 0x95, 0xE3, 0x82, 0x9A, 0x0D,
+ 0x06, 0xE3, 0x83, 0x98, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0x98, 0xE3, 0x82, 0x9A, 0x0D,
+ 0x06, 0xE3, 0x83, 0x9B, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0x9B, 0xE3, 0x82, 0x9A, 0x0D,
+ 0x06, 0xE3, 0x83, 0xAF, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0xB0, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0xB1, 0xE3, 0x82, 0x99, 0x0D,
+ // Bytes 40c0 - 40ff
+ 0x06, 0xE3, 0x83, 0xB2, 0xE3, 0x82, 0x99, 0x0D,
+ 0x06, 0xE3, 0x83, 0xBD, 0xE3, 0x82, 0x99, 0x0D,
+ 0x08, 0xCE, 0x91, 0xCC, 0x93, 0xCC, 0x80, 0xCD,
+ 0x85, 0xDB, 0x08, 0xCE, 0x91, 0xCC, 0x93, 0xCC,
+ 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x91, 0xCC,
+ 0x93, 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE,
+ 0x91, 0xCC, 0x94, 0xCC, 0x80, 0xCD, 0x85, 0xDB,
+ 0x08, 0xCE, 0x91, 0xCC, 0x94, 0xCC, 0x81, 0xCD,
+ // Bytes 4100 - 413f
+ 0x85, 0xDB, 0x08, 0xCE, 0x91, 0xCC, 0x94, 0xCD,
+ 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x97, 0xCC,
+ 0x93, 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE,
+ 0x97, 0xCC, 0x93, 0xCC, 0x81, 0xCD, 0x85, 0xDB,
+ 0x08, 0xCE, 0x97, 0xCC, 0x93, 0xCD, 0x82, 0xCD,
+ 0x85, 0xDB, 0x08, 0xCE, 0x97, 0xCC, 0x94, 0xCC,
+ 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x97, 0xCC,
+ 0x94, 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE,
+ // Bytes 4140 - 417f
+ 0x97, 0xCC, 0x94, 0xCD, 0x82, 0xCD, 0x85, 0xDB,
+ 0x08, 0xCE, 0xA9, 0xCC, 0x93, 0xCC, 0x80, 0xCD,
+ 0x85, 0xDB, 0x08, 0xCE, 0xA9, 0xCC, 0x93, 0xCC,
+ 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xA9, 0xCC,
+ 0x93, 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE,
+ 0xA9, 0xCC, 0x94, 0xCC, 0x80, 0xCD, 0x85, 0xDB,
+ 0x08, 0xCE, 0xA9, 0xCC, 0x94, 0xCC, 0x81, 0xCD,
+ 0x85, 0xDB, 0x08, 0xCE, 0xA9, 0xCC, 0x94, 0xCD,
+ // Bytes 4180 - 41bf
+ 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB1, 0xCC,
+ 0x93, 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE,
+ 0xB1, 0xCC, 0x93, 0xCC, 0x81, 0xCD, 0x85, 0xDB,
+ 0x08, 0xCE, 0xB1, 0xCC, 0x93, 0xCD, 0x82, 0xCD,
+ 0x85, 0xDB, 0x08, 0xCE, 0xB1, 0xCC, 0x94, 0xCC,
+ 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB1, 0xCC,
+ 0x94, 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE,
+ 0xB1, 0xCC, 0x94, 0xCD, 0x82, 0xCD, 0x85, 0xDB,
+ // Bytes 41c0 - 41ff
+ 0x08, 0xCE, 0xB7, 0xCC, 0x93, 0xCC, 0x80, 0xCD,
+ 0x85, 0xDB, 0x08, 0xCE, 0xB7, 0xCC, 0x93, 0xCC,
+ 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB7, 0xCC,
+ 0x93, 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE,
+ 0xB7, 0xCC, 0x94, 0xCC, 0x80, 0xCD, 0x85, 0xDB,
+ 0x08, 0xCE, 0xB7, 0xCC, 0x94, 0xCC, 0x81, 0xCD,
+ 0x85, 0xDB, 0x08, 0xCE, 0xB7, 0xCC, 0x94, 0xCD,
+ 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCF, 0x89, 0xCC,
+ // Bytes 4200 - 423f
+ 0x93, 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCF,
+ 0x89, 0xCC, 0x93, 0xCC, 0x81, 0xCD, 0x85, 0xDB,
+ 0x08, 0xCF, 0x89, 0xCC, 0x93, 0xCD, 0x82, 0xCD,
+ 0x85, 0xDB, 0x08, 0xCF, 0x89, 0xCC, 0x94, 0xCC,
+ 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCF, 0x89, 0xCC,
+ 0x94, 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCF,
+ 0x89, 0xCC, 0x94, 0xCD, 0x82, 0xCD, 0x85, 0xDB,
+ 0x08, 0xF0, 0x91, 0x82, 0x99, 0xF0, 0x91, 0x82,
+ // Bytes 4240 - 427f
+ 0xBA, 0x09, 0x08, 0xF0, 0x91, 0x82, 0x9B, 0xF0,
+ 0x91, 0x82, 0xBA, 0x09, 0x08, 0xF0, 0x91, 0x82,
+ 0xA5, 0xF0, 0x91, 0x82, 0xBA, 0x09, 0x42, 0xC2,
+ 0xB4, 0x01, 0x43, 0x20, 0xCC, 0x81, 0xC9, 0x43,
+ 0x20, 0xCC, 0x83, 0xC9, 0x43, 0x20, 0xCC, 0x84,
+ 0xC9, 0x43, 0x20, 0xCC, 0x85, 0xC9, 0x43, 0x20,
+ 0xCC, 0x86, 0xC9, 0x43, 0x20, 0xCC, 0x87, 0xC9,
+ 0x43, 0x20, 0xCC, 0x88, 0xC9, 0x43, 0x20, 0xCC,
+ // Bytes 4280 - 42bf
+ 0x8A, 0xC9, 0x43, 0x20, 0xCC, 0x8B, 0xC9, 0x43,
+ 0x20, 0xCC, 0x93, 0xC9, 0x43, 0x20, 0xCC, 0x94,
+ 0xC9, 0x43, 0x20, 0xCC, 0xA7, 0xA5, 0x43, 0x20,
+ 0xCC, 0xA8, 0xA5, 0x43, 0x20, 0xCC, 0xB3, 0xB5,
+ 0x43, 0x20, 0xCD, 0x82, 0xC9, 0x43, 0x20, 0xCD,
+ 0x85, 0xD9, 0x43, 0x20, 0xD9, 0x8B, 0x59, 0x43,
+ 0x20, 0xD9, 0x8C, 0x5D, 0x43, 0x20, 0xD9, 0x8D,
+ 0x61, 0x43, 0x20, 0xD9, 0x8E, 0x65, 0x43, 0x20,
+ // Bytes 42c0 - 42ff
+ 0xD9, 0x8F, 0x69, 0x43, 0x20, 0xD9, 0x90, 0x6D,
+ 0x43, 0x20, 0xD9, 0x91, 0x71, 0x43, 0x20, 0xD9,
+ 0x92, 0x75, 0x43, 0x41, 0xCC, 0x8A, 0xC9, 0x43,
+ 0x73, 0xCC, 0x87, 0xC9, 0x43, 0xE1, 0x85, 0xA1,
+ 0x01, 0x43, 0xE1, 0x85, 0xA2, 0x01, 0x43, 0xE1,
+ 0x85, 0xA3, 0x01, 0x43, 0xE1, 0x85, 0xA4, 0x01,
+ 0x43, 0xE1, 0x85, 0xA5, 0x01, 0x43, 0xE1, 0x85,
+ 0xA6, 0x01, 0x43, 0xE1, 0x85, 0xA7, 0x01, 0x43,
+ // Bytes 4300 - 433f
+ 0xE1, 0x85, 0xA8, 0x01, 0x43, 0xE1, 0x85, 0xA9,
+ 0x01, 0x43, 0xE1, 0x85, 0xAA, 0x01, 0x43, 0xE1,
+ 0x85, 0xAB, 0x01, 0x43, 0xE1, 0x85, 0xAC, 0x01,
+ 0x43, 0xE1, 0x85, 0xAD, 0x01, 0x43, 0xE1, 0x85,
+ 0xAE, 0x01, 0x43, 0xE1, 0x85, 0xAF, 0x01, 0x43,
+ 0xE1, 0x85, 0xB0, 0x01, 0x43, 0xE1, 0x85, 0xB1,
+ 0x01, 0x43, 0xE1, 0x85, 0xB2, 0x01, 0x43, 0xE1,
+ 0x85, 0xB3, 0x01, 0x43, 0xE1, 0x85, 0xB4, 0x01,
+ // Bytes 4340 - 437f
+ 0x43, 0xE1, 0x85, 0xB5, 0x01, 0x43, 0xE1, 0x86,
+ 0xAA, 0x01, 0x43, 0xE1, 0x86, 0xAC, 0x01, 0x43,
+ 0xE1, 0x86, 0xAD, 0x01, 0x43, 0xE1, 0x86, 0xB0,
+ 0x01, 0x43, 0xE1, 0x86, 0xB1, 0x01, 0x43, 0xE1,
+ 0x86, 0xB2, 0x01, 0x43, 0xE1, 0x86, 0xB3, 0x01,
+ 0x43, 0xE1, 0x86, 0xB4, 0x01, 0x43, 0xE1, 0x86,
+ 0xB5, 0x01, 0x44, 0x20, 0xE3, 0x82, 0x99, 0x0D,
+ 0x44, 0x20, 0xE3, 0x82, 0x9A, 0x0D, 0x44, 0xC2,
+ // Bytes 4380 - 43bf
+ 0xA8, 0xCC, 0x81, 0xCA, 0x44, 0xCE, 0x91, 0xCC,
+ 0x81, 0xC9, 0x44, 0xCE, 0x95, 0xCC, 0x81, 0xC9,
+ 0x44, 0xCE, 0x97, 0xCC, 0x81, 0xC9, 0x44, 0xCE,
+ 0x99, 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0x9F, 0xCC,
+ 0x81, 0xC9, 0x44, 0xCE, 0xA5, 0xCC, 0x81, 0xC9,
+ 0x44, 0xCE, 0xA5, 0xCC, 0x88, 0xC9, 0x44, 0xCE,
+ 0xA9, 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0xB1, 0xCC,
+ 0x81, 0xC9, 0x44, 0xCE, 0xB5, 0xCC, 0x81, 0xC9,
+ // Bytes 43c0 - 43ff
+ 0x44, 0xCE, 0xB7, 0xCC, 0x81, 0xC9, 0x44, 0xCE,
+ 0xB9, 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0xBF, 0xCC,
+ 0x81, 0xC9, 0x44, 0xCF, 0x85, 0xCC, 0x81, 0xC9,
+ 0x44, 0xCF, 0x89, 0xCC, 0x81, 0xC9, 0x44, 0xD7,
+ 0x90, 0xD6, 0xB7, 0x31, 0x44, 0xD7, 0x90, 0xD6,
+ 0xB8, 0x35, 0x44, 0xD7, 0x90, 0xD6, 0xBC, 0x41,
+ 0x44, 0xD7, 0x91, 0xD6, 0xBC, 0x41, 0x44, 0xD7,
+ 0x91, 0xD6, 0xBF, 0x49, 0x44, 0xD7, 0x92, 0xD6,
+ // Bytes 4400 - 443f
+ 0xBC, 0x41, 0x44, 0xD7, 0x93, 0xD6, 0xBC, 0x41,
+ 0x44, 0xD7, 0x94, 0xD6, 0xBC, 0x41, 0x44, 0xD7,
+ 0x95, 0xD6, 0xB9, 0x39, 0x44, 0xD7, 0x95, 0xD6,
+ 0xBC, 0x41, 0x44, 0xD7, 0x96, 0xD6, 0xBC, 0x41,
+ 0x44, 0xD7, 0x98, 0xD6, 0xBC, 0x41, 0x44, 0xD7,
+ 0x99, 0xD6, 0xB4, 0x25, 0x44, 0xD7, 0x99, 0xD6,
+ 0xBC, 0x41, 0x44, 0xD7, 0x9A, 0xD6, 0xBC, 0x41,
+ 0x44, 0xD7, 0x9B, 0xD6, 0xBC, 0x41, 0x44, 0xD7,
+ // Bytes 4440 - 447f
+ 0x9B, 0xD6, 0xBF, 0x49, 0x44, 0xD7, 0x9C, 0xD6,
+ 0xBC, 0x41, 0x44, 0xD7, 0x9E, 0xD6, 0xBC, 0x41,
+ 0x44, 0xD7, 0xA0, 0xD6, 0xBC, 0x41, 0x44, 0xD7,
+ 0xA1, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0xA3, 0xD6,
+ 0xBC, 0x41, 0x44, 0xD7, 0xA4, 0xD6, 0xBC, 0x41,
+ 0x44, 0xD7, 0xA4, 0xD6, 0xBF, 0x49, 0x44, 0xD7,
+ 0xA6, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0xA7, 0xD6,
+ 0xBC, 0x41, 0x44, 0xD7, 0xA8, 0xD6, 0xBC, 0x41,
+ // Bytes 4480 - 44bf
+ 0x44, 0xD7, 0xA9, 0xD6, 0xBC, 0x41, 0x44, 0xD7,
+ 0xA9, 0xD7, 0x81, 0x4D, 0x44, 0xD7, 0xA9, 0xD7,
+ 0x82, 0x51, 0x44, 0xD7, 0xAA, 0xD6, 0xBC, 0x41,
+ 0x44, 0xD7, 0xB2, 0xD6, 0xB7, 0x31, 0x44, 0xD8,
+ 0xA7, 0xD9, 0x8B, 0x59, 0x44, 0xD8, 0xA7, 0xD9,
+ 0x93, 0xC9, 0x44, 0xD8, 0xA7, 0xD9, 0x94, 0xC9,
+ 0x44, 0xD8, 0xA7, 0xD9, 0x95, 0xB5, 0x44, 0xD8,
+ 0xB0, 0xD9, 0xB0, 0x79, 0x44, 0xD8, 0xB1, 0xD9,
+ // Bytes 44c0 - 44ff
+ 0xB0, 0x79, 0x44, 0xD9, 0x80, 0xD9, 0x8B, 0x59,
+ 0x44, 0xD9, 0x80, 0xD9, 0x8E, 0x65, 0x44, 0xD9,
+ 0x80, 0xD9, 0x8F, 0x69, 0x44, 0xD9, 0x80, 0xD9,
+ 0x90, 0x6D, 0x44, 0xD9, 0x80, 0xD9, 0x91, 0x71,
+ 0x44, 0xD9, 0x80, 0xD9, 0x92, 0x75, 0x44, 0xD9,
+ 0x87, 0xD9, 0xB0, 0x79, 0x44, 0xD9, 0x88, 0xD9,
+ 0x94, 0xC9, 0x44, 0xD9, 0x89, 0xD9, 0xB0, 0x79,
+ 0x44, 0xD9, 0x8A, 0xD9, 0x94, 0xC9, 0x44, 0xDB,
+ // Bytes 4500 - 453f
+ 0x92, 0xD9, 0x94, 0xC9, 0x44, 0xDB, 0x95, 0xD9,
+ 0x94, 0xC9, 0x45, 0x20, 0xCC, 0x88, 0xCC, 0x80,
+ 0xCA, 0x45, 0x20, 0xCC, 0x88, 0xCC, 0x81, 0xCA,
+ 0x45, 0x20, 0xCC, 0x88, 0xCD, 0x82, 0xCA, 0x45,
+ 0x20, 0xCC, 0x93, 0xCC, 0x80, 0xCA, 0x45, 0x20,
+ 0xCC, 0x93, 0xCC, 0x81, 0xCA, 0x45, 0x20, 0xCC,
+ 0x93, 0xCD, 0x82, 0xCA, 0x45, 0x20, 0xCC, 0x94,
+ 0xCC, 0x80, 0xCA, 0x45, 0x20, 0xCC, 0x94, 0xCC,
+ // Bytes 4540 - 457f
+ 0x81, 0xCA, 0x45, 0x20, 0xCC, 0x94, 0xCD, 0x82,
+ 0xCA, 0x45, 0x20, 0xD9, 0x8C, 0xD9, 0x91, 0x72,
+ 0x45, 0x20, 0xD9, 0x8D, 0xD9, 0x91, 0x72, 0x45,
+ 0x20, 0xD9, 0x8E, 0xD9, 0x91, 0x72, 0x45, 0x20,
+ 0xD9, 0x8F, 0xD9, 0x91, 0x72, 0x45, 0x20, 0xD9,
+ 0x90, 0xD9, 0x91, 0x72, 0x45, 0x20, 0xD9, 0x91,
+ 0xD9, 0xB0, 0x7A, 0x45, 0xE2, 0xAB, 0x9D, 0xCC,
+ 0xB8, 0x05, 0x46, 0xCE, 0xB9, 0xCC, 0x88, 0xCC,
+ // Bytes 4580 - 45bf
+ 0x81, 0xCA, 0x46, 0xCF, 0x85, 0xCC, 0x88, 0xCC,
+ 0x81, 0xCA, 0x46, 0xD7, 0xA9, 0xD6, 0xBC, 0xD7,
+ 0x81, 0x4E, 0x46, 0xD7, 0xA9, 0xD6, 0xBC, 0xD7,
+ 0x82, 0x52, 0x46, 0xD9, 0x80, 0xD9, 0x8E, 0xD9,
+ 0x91, 0x72, 0x46, 0xD9, 0x80, 0xD9, 0x8F, 0xD9,
+ 0x91, 0x72, 0x46, 0xD9, 0x80, 0xD9, 0x90, 0xD9,
+ 0x91, 0x72, 0x46, 0xE0, 0xA4, 0x95, 0xE0, 0xA4,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0x96, 0xE0, 0xA4,
+ // Bytes 45c0 - 45ff
+ 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0x97, 0xE0, 0xA4,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0x9C, 0xE0, 0xA4,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0xA1, 0xE0, 0xA4,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0xA2, 0xE0, 0xA4,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0xAB, 0xE0, 0xA4,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0xAF, 0xE0, 0xA4,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA6, 0xA1, 0xE0, 0xA6,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA6, 0xA2, 0xE0, 0xA6,
+ // Bytes 4600 - 463f
+ 0xBC, 0x09, 0x46, 0xE0, 0xA6, 0xAF, 0xE0, 0xA6,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0x96, 0xE0, 0xA8,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0x97, 0xE0, 0xA8,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0x9C, 0xE0, 0xA8,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0xAB, 0xE0, 0xA8,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0xB2, 0xE0, 0xA8,
+ 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0xB8, 0xE0, 0xA8,
+ 0xBC, 0x09, 0x46, 0xE0, 0xAC, 0xA1, 0xE0, 0xAC,
+ // Bytes 4640 - 467f
+ 0xBC, 0x09, 0x46, 0xE0, 0xAC, 0xA2, 0xE0, 0xAC,
+ 0xBC, 0x09, 0x46, 0xE0, 0xBE, 0xB2, 0xE0, 0xBE,
+ 0x80, 0x9D, 0x46, 0xE0, 0xBE, 0xB3, 0xE0, 0xBE,
+ 0x80, 0x9D, 0x46, 0xE3, 0x83, 0x86, 0xE3, 0x82,
+ 0x99, 0x0D, 0x48, 0xF0, 0x9D, 0x85, 0x97, 0xF0,
+ 0x9D, 0x85, 0xA5, 0xAD, 0x48, 0xF0, 0x9D, 0x85,
+ 0x98, 0xF0, 0x9D, 0x85, 0xA5, 0xAD, 0x48, 0xF0,
+ 0x9D, 0x86, 0xB9, 0xF0, 0x9D, 0x85, 0xA5, 0xAD,
+ // Bytes 4680 - 46bf
+ 0x48, 0xF0, 0x9D, 0x86, 0xBA, 0xF0, 0x9D, 0x85,
+ 0xA5, 0xAD, 0x49, 0xE0, 0xBE, 0xB2, 0xE0, 0xBD,
+ 0xB1, 0xE0, 0xBE, 0x80, 0x9E, 0x49, 0xE0, 0xBE,
+ 0xB3, 0xE0, 0xBD, 0xB1, 0xE0, 0xBE, 0x80, 0x9E,
+ 0x4C, 0xF0, 0x9D, 0x85, 0x98, 0xF0, 0x9D, 0x85,
+ 0xA5, 0xF0, 0x9D, 0x85, 0xAE, 0xAE, 0x4C, 0xF0,
+ 0x9D, 0x85, 0x98, 0xF0, 0x9D, 0x85, 0xA5, 0xF0,
+ 0x9D, 0x85, 0xAF, 0xAE, 0x4C, 0xF0, 0x9D, 0x85,
+ // Bytes 46c0 - 46ff
+ 0x98, 0xF0, 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85,
+ 0xB0, 0xAE, 0x4C, 0xF0, 0x9D, 0x85, 0x98, 0xF0,
+ 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85, 0xB1, 0xAE,
+ 0x4C, 0xF0, 0x9D, 0x85, 0x98, 0xF0, 0x9D, 0x85,
+ 0xA5, 0xF0, 0x9D, 0x85, 0xB2, 0xAE, 0x4C, 0xF0,
+ 0x9D, 0x86, 0xB9, 0xF0, 0x9D, 0x85, 0xA5, 0xF0,
+ 0x9D, 0x85, 0xAE, 0xAE, 0x4C, 0xF0, 0x9D, 0x86,
+ 0xB9, 0xF0, 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85,
+ // Bytes 4700 - 473f
+ 0xAF, 0xAE, 0x4C, 0xF0, 0x9D, 0x86, 0xBA, 0xF0,
+ 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85, 0xAE, 0xAE,
+ 0x4C, 0xF0, 0x9D, 0x86, 0xBA, 0xF0, 0x9D, 0x85,
+ 0xA5, 0xF0, 0x9D, 0x85, 0xAF, 0xAE, 0x83, 0x41,
+ 0xCC, 0x82, 0xC9, 0x83, 0x41, 0xCC, 0x86, 0xC9,
+ 0x83, 0x41, 0xCC, 0x87, 0xC9, 0x83, 0x41, 0xCC,
+ 0x88, 0xC9, 0x83, 0x41, 0xCC, 0x8A, 0xC9, 0x83,
+ 0x41, 0xCC, 0xA3, 0xB5, 0x83, 0x43, 0xCC, 0xA7,
+ // Bytes 4740 - 477f
+ 0xA5, 0x83, 0x45, 0xCC, 0x82, 0xC9, 0x83, 0x45,
+ 0xCC, 0x84, 0xC9, 0x83, 0x45, 0xCC, 0xA3, 0xB5,
+ 0x83, 0x45, 0xCC, 0xA7, 0xA5, 0x83, 0x49, 0xCC,
+ 0x88, 0xC9, 0x83, 0x4C, 0xCC, 0xA3, 0xB5, 0x83,
+ 0x4F, 0xCC, 0x82, 0xC9, 0x83, 0x4F, 0xCC, 0x83,
+ 0xC9, 0x83, 0x4F, 0xCC, 0x84, 0xC9, 0x83, 0x4F,
+ 0xCC, 0x87, 0xC9, 0x83, 0x4F, 0xCC, 0x88, 0xC9,
+ 0x83, 0x4F, 0xCC, 0x9B, 0xAD, 0x83, 0x4F, 0xCC,
+ // Bytes 4780 - 47bf
+ 0xA3, 0xB5, 0x83, 0x4F, 0xCC, 0xA8, 0xA5, 0x83,
+ 0x52, 0xCC, 0xA3, 0xB5, 0x83, 0x53, 0xCC, 0x81,
+ 0xC9, 0x83, 0x53, 0xCC, 0x8C, 0xC9, 0x83, 0x53,
+ 0xCC, 0xA3, 0xB5, 0x83, 0x55, 0xCC, 0x83, 0xC9,
+ 0x83, 0x55, 0xCC, 0x84, 0xC9, 0x83, 0x55, 0xCC,
+ 0x88, 0xC9, 0x83, 0x55, 0xCC, 0x9B, 0xAD, 0x83,
+ 0x61, 0xCC, 0x82, 0xC9, 0x83, 0x61, 0xCC, 0x86,
+ 0xC9, 0x83, 0x61, 0xCC, 0x87, 0xC9, 0x83, 0x61,
+ // Bytes 47c0 - 47ff
+ 0xCC, 0x88, 0xC9, 0x83, 0x61, 0xCC, 0x8A, 0xC9,
+ 0x83, 0x61, 0xCC, 0xA3, 0xB5, 0x83, 0x63, 0xCC,
+ 0xA7, 0xA5, 0x83, 0x65, 0xCC, 0x82, 0xC9, 0x83,
+ 0x65, 0xCC, 0x84, 0xC9, 0x83, 0x65, 0xCC, 0xA3,
+ 0xB5, 0x83, 0x65, 0xCC, 0xA7, 0xA5, 0x83, 0x69,
+ 0xCC, 0x88, 0xC9, 0x83, 0x6C, 0xCC, 0xA3, 0xB5,
+ 0x83, 0x6F, 0xCC, 0x82, 0xC9, 0x83, 0x6F, 0xCC,
+ 0x83, 0xC9, 0x83, 0x6F, 0xCC, 0x84, 0xC9, 0x83,
+ // Bytes 4800 - 483f
+ 0x6F, 0xCC, 0x87, 0xC9, 0x83, 0x6F, 0xCC, 0x88,
+ 0xC9, 0x83, 0x6F, 0xCC, 0x9B, 0xAD, 0x83, 0x6F,
+ 0xCC, 0xA3, 0xB5, 0x83, 0x6F, 0xCC, 0xA8, 0xA5,
+ 0x83, 0x72, 0xCC, 0xA3, 0xB5, 0x83, 0x73, 0xCC,
+ 0x81, 0xC9, 0x83, 0x73, 0xCC, 0x8C, 0xC9, 0x83,
+ 0x73, 0xCC, 0xA3, 0xB5, 0x83, 0x75, 0xCC, 0x83,
+ 0xC9, 0x83, 0x75, 0xCC, 0x84, 0xC9, 0x83, 0x75,
+ 0xCC, 0x88, 0xC9, 0x83, 0x75, 0xCC, 0x9B, 0xAD,
+ // Bytes 4840 - 487f
+ 0x84, 0xCE, 0x91, 0xCC, 0x93, 0xC9, 0x84, 0xCE,
+ 0x91, 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0x95, 0xCC,
+ 0x93, 0xC9, 0x84, 0xCE, 0x95, 0xCC, 0x94, 0xC9,
+ 0x84, 0xCE, 0x97, 0xCC, 0x93, 0xC9, 0x84, 0xCE,
+ 0x97, 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0x99, 0xCC,
+ 0x93, 0xC9, 0x84, 0xCE, 0x99, 0xCC, 0x94, 0xC9,
+ 0x84, 0xCE, 0x9F, 0xCC, 0x93, 0xC9, 0x84, 0xCE,
+ 0x9F, 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0xA5, 0xCC,
+ // Bytes 4880 - 48bf
+ 0x94, 0xC9, 0x84, 0xCE, 0xA9, 0xCC, 0x93, 0xC9,
+ 0x84, 0xCE, 0xA9, 0xCC, 0x94, 0xC9, 0x84, 0xCE,
+ 0xB1, 0xCC, 0x80, 0xC9, 0x84, 0xCE, 0xB1, 0xCC,
+ 0x81, 0xC9, 0x84, 0xCE, 0xB1, 0xCC, 0x93, 0xC9,
+ 0x84, 0xCE, 0xB1, 0xCC, 0x94, 0xC9, 0x84, 0xCE,
+ 0xB1, 0xCD, 0x82, 0xC9, 0x84, 0xCE, 0xB5, 0xCC,
+ 0x93, 0xC9, 0x84, 0xCE, 0xB5, 0xCC, 0x94, 0xC9,
+ 0x84, 0xCE, 0xB7, 0xCC, 0x80, 0xC9, 0x84, 0xCE,
+ // Bytes 48c0 - 48ff
+ 0xB7, 0xCC, 0x81, 0xC9, 0x84, 0xCE, 0xB7, 0xCC,
+ 0x93, 0xC9, 0x84, 0xCE, 0xB7, 0xCC, 0x94, 0xC9,
+ 0x84, 0xCE, 0xB7, 0xCD, 0x82, 0xC9, 0x84, 0xCE,
+ 0xB9, 0xCC, 0x88, 0xC9, 0x84, 0xCE, 0xB9, 0xCC,
+ 0x93, 0xC9, 0x84, 0xCE, 0xB9, 0xCC, 0x94, 0xC9,
+ 0x84, 0xCE, 0xBF, 0xCC, 0x93, 0xC9, 0x84, 0xCE,
+ 0xBF, 0xCC, 0x94, 0xC9, 0x84, 0xCF, 0x85, 0xCC,
+ 0x88, 0xC9, 0x84, 0xCF, 0x85, 0xCC, 0x93, 0xC9,
+ // Bytes 4900 - 493f
+ 0x84, 0xCF, 0x85, 0xCC, 0x94, 0xC9, 0x84, 0xCF,
+ 0x89, 0xCC, 0x80, 0xC9, 0x84, 0xCF, 0x89, 0xCC,
+ 0x81, 0xC9, 0x84, 0xCF, 0x89, 0xCC, 0x93, 0xC9,
+ 0x84, 0xCF, 0x89, 0xCC, 0x94, 0xC9, 0x84, 0xCF,
+ 0x89, 0xCD, 0x82, 0xC9, 0x86, 0xCE, 0x91, 0xCC,
+ 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCE, 0x91, 0xCC,
+ 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCE, 0x91, 0xCC,
+ 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCE, 0x91, 0xCC,
+ // Bytes 4940 - 497f
+ 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCE, 0x91, 0xCC,
+ 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCE, 0x91, 0xCC,
+ 0x94, 0xCD, 0x82, 0xCA, 0x86, 0xCE, 0x97, 0xCC,
+ 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCE, 0x97, 0xCC,
+ 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCE, 0x97, 0xCC,
+ 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCE, 0x97, 0xCC,
+ 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCE, 0x97, 0xCC,
+ 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCE, 0x97, 0xCC,
+ // Bytes 4980 - 49bf
+ 0x94, 0xCD, 0x82, 0xCA, 0x86, 0xCE, 0xA9, 0xCC,
+ 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCE, 0xA9, 0xCC,
+ 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCE, 0xA9, 0xCC,
+ 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCE, 0xA9, 0xCC,
+ 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCE, 0xA9, 0xCC,
+ 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCE, 0xA9, 0xCC,
+ 0x94, 0xCD, 0x82, 0xCA, 0x86, 0xCE, 0xB1, 0xCC,
+ 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCE, 0xB1, 0xCC,
+ // Bytes 49c0 - 49ff
+ 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCE, 0xB1, 0xCC,
+ 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCE, 0xB1, 0xCC,
+ 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCE, 0xB1, 0xCC,
+ 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCE, 0xB1, 0xCC,
+ 0x94, 0xCD, 0x82, 0xCA, 0x86, 0xCE, 0xB7, 0xCC,
+ 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCE, 0xB7, 0xCC,
+ 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCE, 0xB7, 0xCC,
+ 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCE, 0xB7, 0xCC,
+ // Bytes 4a00 - 4a3f
+ 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCE, 0xB7, 0xCC,
+ 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCE, 0xB7, 0xCC,
+ 0x94, 0xCD, 0x82, 0xCA, 0x86, 0xCF, 0x89, 0xCC,
+ 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCF, 0x89, 0xCC,
+ 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCF, 0x89, 0xCC,
+ 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCF, 0x89, 0xCC,
+ 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCF, 0x89, 0xCC,
+ 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCF, 0x89, 0xCC,
+ // Bytes 4a40 - 4a7f
+ 0x94, 0xCD, 0x82, 0xCA, 0x42, 0xCC, 0x80, 0xC9,
+ 0x32, 0x42, 0xCC, 0x81, 0xC9, 0x32, 0x42, 0xCC,
+ 0x93, 0xC9, 0x32, 0x44, 0xCC, 0x88, 0xCC, 0x81,
+ 0xCA, 0x32, 0x43, 0xE3, 0x82, 0x99, 0x0D, 0x03,
+ 0x43, 0xE3, 0x82, 0x9A, 0x0D, 0x03, 0x46, 0xE0,
+ 0xBD, 0xB1, 0xE0, 0xBD, 0xB2, 0x9E, 0x26, 0x46,
+ 0xE0, 0xBD, 0xB1, 0xE0, 0xBD, 0xB4, 0xA2, 0x26,
+ 0x46, 0xE0, 0xBD, 0xB1, 0xE0, 0xBE, 0x80, 0x9E,
+ // Bytes 4a80 - 4abf
+ 0x26, 0x00, 0x01,
+}
+
+// lookup returns the trie value for the first UTF-8 encoding in s and
+// the width in bytes of this encoding. The size will be 0 if s does not
+// hold enough bytes to complete the encoding. len(s) must be greater than 0.
+func (t *nfcTrie) lookup(s []byte) (v uint16, sz int) {
+ c0 := s[0]
+ switch {
+ case c0 < 0x80: // is ASCII
+ return nfcValues[c0], 1
+ case c0 < 0xC2:
+ return 0, 1 // Illegal UTF-8: not a starter, not ASCII.
+ case c0 < 0xE0: // 2-byte UTF-8
+ if len(s) < 2 {
+ return 0, 0
+ }
+ i := nfcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c1), 2
+ case c0 < 0xF0: // 3-byte UTF-8
+ if len(s) < 3 {
+ return 0, 0
+ }
+ i := nfcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = nfcIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c2), 3
+ case c0 < 0xF8: // 4-byte UTF-8
+ if len(s) < 4 {
+ return 0, 0
+ }
+ i := nfcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = nfcIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ o = uint32(i)<<6 + uint32(c2)
+ i = nfcIndex[o]
+ c3 := s[3]
+ if c3 < 0x80 || 0xC0 <= c3 {
+ return 0, 3 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c3), 4
+ }
+ // Illegal rune
+ return 0, 1
+}
+
+// lookupUnsafe returns the trie value for the first UTF-8 encoding in s.
+// s must start with a full and valid UTF-8 encoded rune.
+func (t *nfcTrie) lookupUnsafe(s []byte) uint16 {
+ c0 := s[0]
+ if c0 < 0x80 { // is ASCII
+ return nfcValues[c0]
+ }
+ i := nfcIndex[c0]
+ if c0 < 0xE0 { // 2-byte UTF-8
+ return t.lookupValue(uint32(i), s[1])
+ }
+ i = nfcIndex[uint32(i)<<6+uint32(s[1])]
+ if c0 < 0xF0 { // 3-byte UTF-8
+ return t.lookupValue(uint32(i), s[2])
+ }
+ i = nfcIndex[uint32(i)<<6+uint32(s[2])]
+ if c0 < 0xF8 { // 4-byte UTF-8
+ return t.lookupValue(uint32(i), s[3])
+ }
+ return 0
+}
+
+// lookupString returns the trie value for the first UTF-8 encoding in s and
+// the width in bytes of this encoding. The size will be 0 if s does not
+// hold enough bytes to complete the encoding. len(s) must be greater than 0.
+func (t *nfcTrie) lookupString(s string) (v uint16, sz int) {
+ c0 := s[0]
+ switch {
+ case c0 < 0x80: // is ASCII
+ return nfcValues[c0], 1
+ case c0 < 0xC2:
+ return 0, 1 // Illegal UTF-8: not a starter, not ASCII.
+ case c0 < 0xE0: // 2-byte UTF-8
+ if len(s) < 2 {
+ return 0, 0
+ }
+ i := nfcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c1), 2
+ case c0 < 0xF0: // 3-byte UTF-8
+ if len(s) < 3 {
+ return 0, 0
+ }
+ i := nfcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = nfcIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c2), 3
+ case c0 < 0xF8: // 4-byte UTF-8
+ if len(s) < 4 {
+ return 0, 0
+ }
+ i := nfcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = nfcIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ o = uint32(i)<<6 + uint32(c2)
+ i = nfcIndex[o]
+ c3 := s[3]
+ if c3 < 0x80 || 0xC0 <= c3 {
+ return 0, 3 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c3), 4
+ }
+ // Illegal rune
+ return 0, 1
+}
+
+// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s.
+// s must start with a full and valid UTF-8 encoded rune.
+func (t *nfcTrie) lookupStringUnsafe(s string) uint16 {
+ c0 := s[0]
+ if c0 < 0x80 { // is ASCII
+ return nfcValues[c0]
+ }
+ i := nfcIndex[c0]
+ if c0 < 0xE0 { // 2-byte UTF-8
+ return t.lookupValue(uint32(i), s[1])
+ }
+ i = nfcIndex[uint32(i)<<6+uint32(s[1])]
+ if c0 < 0xF0 { // 3-byte UTF-8
+ return t.lookupValue(uint32(i), s[2])
+ }
+ i = nfcIndex[uint32(i)<<6+uint32(s[2])]
+ if c0 < 0xF8 { // 4-byte UTF-8
+ return t.lookupValue(uint32(i), s[3])
+ }
+ return 0
+}
+
+// nfcTrie. Total size: 10332 bytes (10.09 KiB). Checksum: ad355b768fddb1b6.
+type nfcTrie struct{}
+
+func newNfcTrie(i int) *nfcTrie {
+ return &nfcTrie{}
+}
+
+// lookupValue determines the type of block n and looks up the value for b.
+func (t *nfcTrie) lookupValue(n uint32, b byte) uint16 {
+ switch {
+ case n < 44:
+ return uint16(nfcValues[n<<6+uint32(b)])
+ default:
+ n -= 44
+ return uint16(nfcSparse.lookup(n, b))
+ }
+}
+
+// nfcValues: 46 blocks, 2944 entries, 5888 bytes
+// The third block is the zero block.
+var nfcValues = [2944]uint16{
+ // Block 0x0, offset 0x0
+ 0x3c: 0xa000, 0x3d: 0xa000, 0x3e: 0xa000,
+ // Block 0x1, offset 0x40
+ 0x41: 0xa000, 0x42: 0xa000, 0x43: 0xa000, 0x44: 0xa000, 0x45: 0xa000,
+ 0x46: 0xa000, 0x47: 0xa000, 0x48: 0xa000, 0x49: 0xa000, 0x4a: 0xa000, 0x4b: 0xa000,
+ 0x4c: 0xa000, 0x4d: 0xa000, 0x4e: 0xa000, 0x4f: 0xa000, 0x50: 0xa000,
+ 0x52: 0xa000, 0x53: 0xa000, 0x54: 0xa000, 0x55: 0xa000, 0x56: 0xa000, 0x57: 0xa000,
+ 0x58: 0xa000, 0x59: 0xa000, 0x5a: 0xa000,
+ 0x61: 0xa000, 0x62: 0xa000, 0x63: 0xa000,
+ 0x64: 0xa000, 0x65: 0xa000, 0x66: 0xa000, 0x67: 0xa000, 0x68: 0xa000, 0x69: 0xa000,
+ 0x6a: 0xa000, 0x6b: 0xa000, 0x6c: 0xa000, 0x6d: 0xa000, 0x6e: 0xa000, 0x6f: 0xa000,
+ 0x70: 0xa000, 0x72: 0xa000, 0x73: 0xa000, 0x74: 0xa000, 0x75: 0xa000,
+ 0x76: 0xa000, 0x77: 0xa000, 0x78: 0xa000, 0x79: 0xa000, 0x7a: 0xa000,
+ // Block 0x2, offset 0x80
+ // Block 0x3, offset 0xc0
+ 0xc0: 0x2f6f, 0xc1: 0x2f74, 0xc2: 0x471e, 0xc3: 0x2f79, 0xc4: 0x472d, 0xc5: 0x4732,
+ 0xc6: 0xa000, 0xc7: 0x473c, 0xc8: 0x2fe2, 0xc9: 0x2fe7, 0xca: 0x4741, 0xcb: 0x2ffb,
+ 0xcc: 0x306e, 0xcd: 0x3073, 0xce: 0x3078, 0xcf: 0x4755, 0xd1: 0x3104,
+ 0xd2: 0x3127, 0xd3: 0x312c, 0xd4: 0x475f, 0xd5: 0x4764, 0xd6: 0x4773,
+ 0xd8: 0xa000, 0xd9: 0x31b3, 0xda: 0x31b8, 0xdb: 0x31bd, 0xdc: 0x47a5, 0xdd: 0x3235,
+ 0xe0: 0x327b, 0xe1: 0x3280, 0xe2: 0x47af, 0xe3: 0x3285,
+ 0xe4: 0x47be, 0xe5: 0x47c3, 0xe6: 0xa000, 0xe7: 0x47cd, 0xe8: 0x32ee, 0xe9: 0x32f3,
+ 0xea: 0x47d2, 0xeb: 0x3307, 0xec: 0x337f, 0xed: 0x3384, 0xee: 0x3389, 0xef: 0x47e6,
+ 0xf1: 0x3415, 0xf2: 0x3438, 0xf3: 0x343d, 0xf4: 0x47f0, 0xf5: 0x47f5,
+ 0xf6: 0x4804, 0xf8: 0xa000, 0xf9: 0x34c9, 0xfa: 0x34ce, 0xfb: 0x34d3,
+ 0xfc: 0x4836, 0xfd: 0x3550, 0xff: 0x3569,
+ // Block 0x4, offset 0x100
+ 0x100: 0x2f7e, 0x101: 0x328a, 0x102: 0x4723, 0x103: 0x47b4, 0x104: 0x2f9c, 0x105: 0x32a8,
+ 0x106: 0x2fb0, 0x107: 0x32bc, 0x108: 0x2fb5, 0x109: 0x32c1, 0x10a: 0x2fba, 0x10b: 0x32c6,
+ 0x10c: 0x2fbf, 0x10d: 0x32cb, 0x10e: 0x2fc9, 0x10f: 0x32d5,
+ 0x112: 0x4746, 0x113: 0x47d7, 0x114: 0x2ff1, 0x115: 0x32fd, 0x116: 0x2ff6, 0x117: 0x3302,
+ 0x118: 0x3014, 0x119: 0x3320, 0x11a: 0x3005, 0x11b: 0x3311, 0x11c: 0x302d, 0x11d: 0x3339,
+ 0x11e: 0x3037, 0x11f: 0x3343, 0x120: 0x303c, 0x121: 0x3348, 0x122: 0x3046, 0x123: 0x3352,
+ 0x124: 0x304b, 0x125: 0x3357, 0x128: 0x307d, 0x129: 0x338e,
+ 0x12a: 0x3082, 0x12b: 0x3393, 0x12c: 0x3087, 0x12d: 0x3398, 0x12e: 0x30aa, 0x12f: 0x33b6,
+ 0x130: 0x308c, 0x134: 0x30b4, 0x135: 0x33c0,
+ 0x136: 0x30c8, 0x137: 0x33d9, 0x139: 0x30d2, 0x13a: 0x33e3, 0x13b: 0x30dc,
+ 0x13c: 0x33ed, 0x13d: 0x30d7, 0x13e: 0x33e8,
+ // Block 0x5, offset 0x140
+ 0x143: 0x30ff, 0x144: 0x3410, 0x145: 0x3118,
+ 0x146: 0x3429, 0x147: 0x310e, 0x148: 0x341f,
+ 0x14c: 0x4769, 0x14d: 0x47fa, 0x14e: 0x3131, 0x14f: 0x3442, 0x150: 0x313b, 0x151: 0x344c,
+ 0x154: 0x3159, 0x155: 0x346a, 0x156: 0x3172, 0x157: 0x3483,
+ 0x158: 0x3163, 0x159: 0x3474, 0x15a: 0x478c, 0x15b: 0x481d, 0x15c: 0x317c, 0x15d: 0x348d,
+ 0x15e: 0x318b, 0x15f: 0x349c, 0x160: 0x4791, 0x161: 0x4822, 0x162: 0x31a4, 0x163: 0x34ba,
+ 0x164: 0x3195, 0x165: 0x34ab, 0x168: 0x479b, 0x169: 0x482c,
+ 0x16a: 0x47a0, 0x16b: 0x4831, 0x16c: 0x31c2, 0x16d: 0x34d8, 0x16e: 0x31cc, 0x16f: 0x34e2,
+ 0x170: 0x31d1, 0x171: 0x34e7, 0x172: 0x31ef, 0x173: 0x3505, 0x174: 0x3212, 0x175: 0x3528,
+ 0x176: 0x323a, 0x177: 0x3555, 0x178: 0x324e, 0x179: 0x325d, 0x17a: 0x357d, 0x17b: 0x3267,
+ 0x17c: 0x3587, 0x17d: 0x326c, 0x17e: 0x358c, 0x17f: 0xa000,
+ // Block 0x6, offset 0x180
+ 0x184: 0x8100, 0x185: 0x8100,
+ 0x186: 0x8100,
+ 0x18d: 0x2f88, 0x18e: 0x3294, 0x18f: 0x3096, 0x190: 0x33a2, 0x191: 0x3140,
+ 0x192: 0x3451, 0x193: 0x31d6, 0x194: 0x34ec, 0x195: 0x39cf, 0x196: 0x3b5e, 0x197: 0x39c8,
+ 0x198: 0x3b57, 0x199: 0x39d6, 0x19a: 0x3b65, 0x19b: 0x39c1, 0x19c: 0x3b50,
+ 0x19e: 0x38b0, 0x19f: 0x3a3f, 0x1a0: 0x38a9, 0x1a1: 0x3a38, 0x1a2: 0x35b3, 0x1a3: 0x35c5,
+ 0x1a6: 0x3041, 0x1a7: 0x334d, 0x1a8: 0x30be, 0x1a9: 0x33cf,
+ 0x1aa: 0x4782, 0x1ab: 0x4813, 0x1ac: 0x3990, 0x1ad: 0x3b1f, 0x1ae: 0x35d7, 0x1af: 0x35dd,
+ 0x1b0: 0x33c5, 0x1b4: 0x3028, 0x1b5: 0x3334,
+ 0x1b8: 0x30fa, 0x1b9: 0x340b, 0x1ba: 0x38b7, 0x1bb: 0x3a46,
+ 0x1bc: 0x35ad, 0x1bd: 0x35bf, 0x1be: 0x35b9, 0x1bf: 0x35cb,
+ // Block 0x7, offset 0x1c0
+ 0x1c0: 0x2f8d, 0x1c1: 0x3299, 0x1c2: 0x2f92, 0x1c3: 0x329e, 0x1c4: 0x300a, 0x1c5: 0x3316,
+ 0x1c6: 0x300f, 0x1c7: 0x331b, 0x1c8: 0x309b, 0x1c9: 0x33a7, 0x1ca: 0x30a0, 0x1cb: 0x33ac,
+ 0x1cc: 0x3145, 0x1cd: 0x3456, 0x1ce: 0x314a, 0x1cf: 0x345b, 0x1d0: 0x3168, 0x1d1: 0x3479,
+ 0x1d2: 0x316d, 0x1d3: 0x347e, 0x1d4: 0x31db, 0x1d5: 0x34f1, 0x1d6: 0x31e0, 0x1d7: 0x34f6,
+ 0x1d8: 0x3186, 0x1d9: 0x3497, 0x1da: 0x319f, 0x1db: 0x34b5,
+ 0x1de: 0x305a, 0x1df: 0x3366,
+ 0x1e6: 0x4728, 0x1e7: 0x47b9, 0x1e8: 0x4750, 0x1e9: 0x47e1,
+ 0x1ea: 0x395f, 0x1eb: 0x3aee, 0x1ec: 0x393c, 0x1ed: 0x3acb, 0x1ee: 0x476e, 0x1ef: 0x47ff,
+ 0x1f0: 0x3958, 0x1f1: 0x3ae7, 0x1f2: 0x3244, 0x1f3: 0x355f,
+ // Block 0x8, offset 0x200
+ 0x200: 0x9932, 0x201: 0x9932, 0x202: 0x9932, 0x203: 0x9932, 0x204: 0x9932, 0x205: 0x8132,
+ 0x206: 0x9932, 0x207: 0x9932, 0x208: 0x9932, 0x209: 0x9932, 0x20a: 0x9932, 0x20b: 0x9932,
+ 0x20c: 0x9932, 0x20d: 0x8132, 0x20e: 0x8132, 0x20f: 0x9932, 0x210: 0x8132, 0x211: 0x9932,
+ 0x212: 0x8132, 0x213: 0x9932, 0x214: 0x9932, 0x215: 0x8133, 0x216: 0x812d, 0x217: 0x812d,
+ 0x218: 0x812d, 0x219: 0x812d, 0x21a: 0x8133, 0x21b: 0x992b, 0x21c: 0x812d, 0x21d: 0x812d,
+ 0x21e: 0x812d, 0x21f: 0x812d, 0x220: 0x812d, 0x221: 0x8129, 0x222: 0x8129, 0x223: 0x992d,
+ 0x224: 0x992d, 0x225: 0x992d, 0x226: 0x992d, 0x227: 0x9929, 0x228: 0x9929, 0x229: 0x812d,
+ 0x22a: 0x812d, 0x22b: 0x812d, 0x22c: 0x812d, 0x22d: 0x992d, 0x22e: 0x992d, 0x22f: 0x812d,
+ 0x230: 0x992d, 0x231: 0x992d, 0x232: 0x812d, 0x233: 0x812d, 0x234: 0x8101, 0x235: 0x8101,
+ 0x236: 0x8101, 0x237: 0x8101, 0x238: 0x9901, 0x239: 0x812d, 0x23a: 0x812d, 0x23b: 0x812d,
+ 0x23c: 0x812d, 0x23d: 0x8132, 0x23e: 0x8132, 0x23f: 0x8132,
+ // Block 0x9, offset 0x240
+ 0x240: 0x4a44, 0x241: 0x4a49, 0x242: 0x9932, 0x243: 0x4a4e, 0x244: 0x4a53, 0x245: 0x9936,
+ 0x246: 0x8132, 0x247: 0x812d, 0x248: 0x812d, 0x249: 0x812d, 0x24a: 0x8132, 0x24b: 0x8132,
+ 0x24c: 0x8132, 0x24d: 0x812d, 0x24e: 0x812d, 0x250: 0x8132, 0x251: 0x8132,
+ 0x252: 0x8132, 0x253: 0x812d, 0x254: 0x812d, 0x255: 0x812d, 0x256: 0x812d, 0x257: 0x8132,
+ 0x258: 0x8133, 0x259: 0x812d, 0x25a: 0x812d, 0x25b: 0x8132, 0x25c: 0x8134, 0x25d: 0x8135,
+ 0x25e: 0x8135, 0x25f: 0x8134, 0x260: 0x8135, 0x261: 0x8135, 0x262: 0x8134, 0x263: 0x8132,
+ 0x264: 0x8132, 0x265: 0x8132, 0x266: 0x8132, 0x267: 0x8132, 0x268: 0x8132, 0x269: 0x8132,
+ 0x26a: 0x8132, 0x26b: 0x8132, 0x26c: 0x8132, 0x26d: 0x8132, 0x26e: 0x8132, 0x26f: 0x8132,
+ 0x274: 0x0170,
+ 0x27a: 0x8100,
+ 0x27e: 0x0037,
+ // Block 0xa, offset 0x280
+ 0x284: 0x8100, 0x285: 0x35a1,
+ 0x286: 0x35e9, 0x287: 0x00ce, 0x288: 0x3607, 0x289: 0x3613, 0x28a: 0x3625,
+ 0x28c: 0x3643, 0x28e: 0x3655, 0x28f: 0x3673, 0x290: 0x3e08, 0x291: 0xa000,
+ 0x295: 0xa000, 0x297: 0xa000,
+ 0x299: 0xa000,
+ 0x29f: 0xa000, 0x2a1: 0xa000,
+ 0x2a5: 0xa000, 0x2a9: 0xa000,
+ 0x2aa: 0x3637, 0x2ab: 0x3667, 0x2ac: 0x4894, 0x2ad: 0x3697, 0x2ae: 0x48be, 0x2af: 0x36a9,
+ 0x2b0: 0x3e70, 0x2b1: 0xa000, 0x2b5: 0xa000,
+ 0x2b7: 0xa000, 0x2b9: 0xa000,
+ 0x2bf: 0xa000,
+ // Block 0xb, offset 0x2c0
+ 0x2c0: 0x3721, 0x2c1: 0x372d, 0x2c3: 0x371b,
+ 0x2c6: 0xa000, 0x2c7: 0x3709,
+ 0x2cc: 0x375d, 0x2cd: 0x3745, 0x2ce: 0x376f, 0x2d0: 0xa000,
+ 0x2d3: 0xa000, 0x2d5: 0xa000, 0x2d6: 0xa000, 0x2d7: 0xa000,
+ 0x2d8: 0xa000, 0x2d9: 0x3751, 0x2da: 0xa000,
+ 0x2de: 0xa000, 0x2e3: 0xa000,
+ 0x2e7: 0xa000,
+ 0x2eb: 0xa000, 0x2ed: 0xa000,
+ 0x2f0: 0xa000, 0x2f3: 0xa000, 0x2f5: 0xa000,
+ 0x2f6: 0xa000, 0x2f7: 0xa000, 0x2f8: 0xa000, 0x2f9: 0x37d5, 0x2fa: 0xa000,
+ 0x2fe: 0xa000,
+ // Block 0xc, offset 0x300
+ 0x301: 0x3733, 0x302: 0x37b7,
+ 0x310: 0x370f, 0x311: 0x3793,
+ 0x312: 0x3715, 0x313: 0x3799, 0x316: 0x3727, 0x317: 0x37ab,
+ 0x318: 0xa000, 0x319: 0xa000, 0x31a: 0x3829, 0x31b: 0x382f, 0x31c: 0x3739, 0x31d: 0x37bd,
+ 0x31e: 0x373f, 0x31f: 0x37c3, 0x322: 0x374b, 0x323: 0x37cf,
+ 0x324: 0x3757, 0x325: 0x37db, 0x326: 0x3763, 0x327: 0x37e7, 0x328: 0xa000, 0x329: 0xa000,
+ 0x32a: 0x3835, 0x32b: 0x383b, 0x32c: 0x378d, 0x32d: 0x3811, 0x32e: 0x3769, 0x32f: 0x37ed,
+ 0x330: 0x3775, 0x331: 0x37f9, 0x332: 0x377b, 0x333: 0x37ff, 0x334: 0x3781, 0x335: 0x3805,
+ 0x338: 0x3787, 0x339: 0x380b,
+ // Block 0xd, offset 0x340
+ 0x351: 0x812d,
+ 0x352: 0x8132, 0x353: 0x8132, 0x354: 0x8132, 0x355: 0x8132, 0x356: 0x812d, 0x357: 0x8132,
+ 0x358: 0x8132, 0x359: 0x8132, 0x35a: 0x812e, 0x35b: 0x812d, 0x35c: 0x8132, 0x35d: 0x8132,
+ 0x35e: 0x8132, 0x35f: 0x8132, 0x360: 0x8132, 0x361: 0x8132, 0x362: 0x812d, 0x363: 0x812d,
+ 0x364: 0x812d, 0x365: 0x812d, 0x366: 0x812d, 0x367: 0x812d, 0x368: 0x8132, 0x369: 0x8132,
+ 0x36a: 0x812d, 0x36b: 0x8132, 0x36c: 0x8132, 0x36d: 0x812e, 0x36e: 0x8131, 0x36f: 0x8132,
+ 0x370: 0x8105, 0x371: 0x8106, 0x372: 0x8107, 0x373: 0x8108, 0x374: 0x8109, 0x375: 0x810a,
+ 0x376: 0x810b, 0x377: 0x810c, 0x378: 0x810d, 0x379: 0x810e, 0x37a: 0x810e, 0x37b: 0x810f,
+ 0x37c: 0x8110, 0x37d: 0x8111, 0x37f: 0x8112,
+ // Block 0xe, offset 0x380
+ 0x388: 0xa000, 0x38a: 0xa000, 0x38b: 0x8116,
+ 0x38c: 0x8117, 0x38d: 0x8118, 0x38e: 0x8119, 0x38f: 0x811a, 0x390: 0x811b, 0x391: 0x811c,
+ 0x392: 0x811d, 0x393: 0x9932, 0x394: 0x9932, 0x395: 0x992d, 0x396: 0x812d, 0x397: 0x8132,
+ 0x398: 0x8132, 0x399: 0x8132, 0x39a: 0x8132, 0x39b: 0x8132, 0x39c: 0x812d, 0x39d: 0x8132,
+ 0x39e: 0x8132, 0x39f: 0x812d,
+ 0x3b0: 0x811e,
+ // Block 0xf, offset 0x3c0
+ 0x3c5: 0xa000,
+ 0x3c6: 0x2d26, 0x3c7: 0xa000, 0x3c8: 0x2d2e, 0x3c9: 0xa000, 0x3ca: 0x2d36, 0x3cb: 0xa000,
+ 0x3cc: 0x2d3e, 0x3cd: 0xa000, 0x3ce: 0x2d46, 0x3d1: 0xa000,
+ 0x3d2: 0x2d4e,
+ 0x3f4: 0x8102, 0x3f5: 0x9900,
+ 0x3fa: 0xa000, 0x3fb: 0x2d56,
+ 0x3fc: 0xa000, 0x3fd: 0x2d5e, 0x3fe: 0xa000, 0x3ff: 0xa000,
+ // Block 0x10, offset 0x400
+ 0x400: 0x2f97, 0x401: 0x32a3, 0x402: 0x2fa1, 0x403: 0x32ad, 0x404: 0x2fa6, 0x405: 0x32b2,
+ 0x406: 0x2fab, 0x407: 0x32b7, 0x408: 0x38cc, 0x409: 0x3a5b, 0x40a: 0x2fc4, 0x40b: 0x32d0,
+ 0x40c: 0x2fce, 0x40d: 0x32da, 0x40e: 0x2fdd, 0x40f: 0x32e9, 0x410: 0x2fd3, 0x411: 0x32df,
+ 0x412: 0x2fd8, 0x413: 0x32e4, 0x414: 0x38ef, 0x415: 0x3a7e, 0x416: 0x38f6, 0x417: 0x3a85,
+ 0x418: 0x3019, 0x419: 0x3325, 0x41a: 0x301e, 0x41b: 0x332a, 0x41c: 0x3904, 0x41d: 0x3a93,
+ 0x41e: 0x3023, 0x41f: 0x332f, 0x420: 0x3032, 0x421: 0x333e, 0x422: 0x3050, 0x423: 0x335c,
+ 0x424: 0x305f, 0x425: 0x336b, 0x426: 0x3055, 0x427: 0x3361, 0x428: 0x3064, 0x429: 0x3370,
+ 0x42a: 0x3069, 0x42b: 0x3375, 0x42c: 0x30af, 0x42d: 0x33bb, 0x42e: 0x390b, 0x42f: 0x3a9a,
+ 0x430: 0x30b9, 0x431: 0x33ca, 0x432: 0x30c3, 0x433: 0x33d4, 0x434: 0x30cd, 0x435: 0x33de,
+ 0x436: 0x475a, 0x437: 0x47eb, 0x438: 0x3912, 0x439: 0x3aa1, 0x43a: 0x30e6, 0x43b: 0x33f7,
+ 0x43c: 0x30e1, 0x43d: 0x33f2, 0x43e: 0x30eb, 0x43f: 0x33fc,
+ // Block 0x11, offset 0x440
+ 0x440: 0x30f0, 0x441: 0x3401, 0x442: 0x30f5, 0x443: 0x3406, 0x444: 0x3109, 0x445: 0x341a,
+ 0x446: 0x3113, 0x447: 0x3424, 0x448: 0x3122, 0x449: 0x3433, 0x44a: 0x311d, 0x44b: 0x342e,
+ 0x44c: 0x3935, 0x44d: 0x3ac4, 0x44e: 0x3943, 0x44f: 0x3ad2, 0x450: 0x394a, 0x451: 0x3ad9,
+ 0x452: 0x3951, 0x453: 0x3ae0, 0x454: 0x314f, 0x455: 0x3460, 0x456: 0x3154, 0x457: 0x3465,
+ 0x458: 0x315e, 0x459: 0x346f, 0x45a: 0x4787, 0x45b: 0x4818, 0x45c: 0x3997, 0x45d: 0x3b26,
+ 0x45e: 0x3177, 0x45f: 0x3488, 0x460: 0x3181, 0x461: 0x3492, 0x462: 0x4796, 0x463: 0x4827,
+ 0x464: 0x399e, 0x465: 0x3b2d, 0x466: 0x39a5, 0x467: 0x3b34, 0x468: 0x39ac, 0x469: 0x3b3b,
+ 0x46a: 0x3190, 0x46b: 0x34a1, 0x46c: 0x319a, 0x46d: 0x34b0, 0x46e: 0x31ae, 0x46f: 0x34c4,
+ 0x470: 0x31a9, 0x471: 0x34bf, 0x472: 0x31ea, 0x473: 0x3500, 0x474: 0x31f9, 0x475: 0x350f,
+ 0x476: 0x31f4, 0x477: 0x350a, 0x478: 0x39b3, 0x479: 0x3b42, 0x47a: 0x39ba, 0x47b: 0x3b49,
+ 0x47c: 0x31fe, 0x47d: 0x3514, 0x47e: 0x3203, 0x47f: 0x3519,
+ // Block 0x12, offset 0x480
+ 0x480: 0x3208, 0x481: 0x351e, 0x482: 0x320d, 0x483: 0x3523, 0x484: 0x321c, 0x485: 0x3532,
+ 0x486: 0x3217, 0x487: 0x352d, 0x488: 0x3221, 0x489: 0x353c, 0x48a: 0x3226, 0x48b: 0x3541,
+ 0x48c: 0x322b, 0x48d: 0x3546, 0x48e: 0x3249, 0x48f: 0x3564, 0x490: 0x3262, 0x491: 0x3582,
+ 0x492: 0x3271, 0x493: 0x3591, 0x494: 0x3276, 0x495: 0x3596, 0x496: 0x337a, 0x497: 0x34a6,
+ 0x498: 0x3537, 0x499: 0x3573, 0x49b: 0x35d1,
+ 0x4a0: 0x4737, 0x4a1: 0x47c8, 0x4a2: 0x2f83, 0x4a3: 0x328f,
+ 0x4a4: 0x3878, 0x4a5: 0x3a07, 0x4a6: 0x3871, 0x4a7: 0x3a00, 0x4a8: 0x3886, 0x4a9: 0x3a15,
+ 0x4aa: 0x387f, 0x4ab: 0x3a0e, 0x4ac: 0x38be, 0x4ad: 0x3a4d, 0x4ae: 0x3894, 0x4af: 0x3a23,
+ 0x4b0: 0x388d, 0x4b1: 0x3a1c, 0x4b2: 0x38a2, 0x4b3: 0x3a31, 0x4b4: 0x389b, 0x4b5: 0x3a2a,
+ 0x4b6: 0x38c5, 0x4b7: 0x3a54, 0x4b8: 0x474b, 0x4b9: 0x47dc, 0x4ba: 0x3000, 0x4bb: 0x330c,
+ 0x4bc: 0x2fec, 0x4bd: 0x32f8, 0x4be: 0x38da, 0x4bf: 0x3a69,
+ // Block 0x13, offset 0x4c0
+ 0x4c0: 0x38d3, 0x4c1: 0x3a62, 0x4c2: 0x38e8, 0x4c3: 0x3a77, 0x4c4: 0x38e1, 0x4c5: 0x3a70,
+ 0x4c6: 0x38fd, 0x4c7: 0x3a8c, 0x4c8: 0x3091, 0x4c9: 0x339d, 0x4ca: 0x30a5, 0x4cb: 0x33b1,
+ 0x4cc: 0x477d, 0x4cd: 0x480e, 0x4ce: 0x3136, 0x4cf: 0x3447, 0x4d0: 0x3920, 0x4d1: 0x3aaf,
+ 0x4d2: 0x3919, 0x4d3: 0x3aa8, 0x4d4: 0x392e, 0x4d5: 0x3abd, 0x4d6: 0x3927, 0x4d7: 0x3ab6,
+ 0x4d8: 0x3989, 0x4d9: 0x3b18, 0x4da: 0x396d, 0x4db: 0x3afc, 0x4dc: 0x3966, 0x4dd: 0x3af5,
+ 0x4de: 0x397b, 0x4df: 0x3b0a, 0x4e0: 0x3974, 0x4e1: 0x3b03, 0x4e2: 0x3982, 0x4e3: 0x3b11,
+ 0x4e4: 0x31e5, 0x4e5: 0x34fb, 0x4e6: 0x31c7, 0x4e7: 0x34dd, 0x4e8: 0x39e4, 0x4e9: 0x3b73,
+ 0x4ea: 0x39dd, 0x4eb: 0x3b6c, 0x4ec: 0x39f2, 0x4ed: 0x3b81, 0x4ee: 0x39eb, 0x4ef: 0x3b7a,
+ 0x4f0: 0x39f9, 0x4f1: 0x3b88, 0x4f2: 0x3230, 0x4f3: 0x354b, 0x4f4: 0x3258, 0x4f5: 0x3578,
+ 0x4f6: 0x3253, 0x4f7: 0x356e, 0x4f8: 0x323f, 0x4f9: 0x355a,
+ // Block 0x14, offset 0x500
+ 0x500: 0x489a, 0x501: 0x48a0, 0x502: 0x49b4, 0x503: 0x49cc, 0x504: 0x49bc, 0x505: 0x49d4,
+ 0x506: 0x49c4, 0x507: 0x49dc, 0x508: 0x4840, 0x509: 0x4846, 0x50a: 0x4924, 0x50b: 0x493c,
+ 0x50c: 0x492c, 0x50d: 0x4944, 0x50e: 0x4934, 0x50f: 0x494c, 0x510: 0x48ac, 0x511: 0x48b2,
+ 0x512: 0x3db8, 0x513: 0x3dc8, 0x514: 0x3dc0, 0x515: 0x3dd0,
+ 0x518: 0x484c, 0x519: 0x4852, 0x51a: 0x3ce8, 0x51b: 0x3cf8, 0x51c: 0x3cf0, 0x51d: 0x3d00,
+ 0x520: 0x48c4, 0x521: 0x48ca, 0x522: 0x49e4, 0x523: 0x49fc,
+ 0x524: 0x49ec, 0x525: 0x4a04, 0x526: 0x49f4, 0x527: 0x4a0c, 0x528: 0x4858, 0x529: 0x485e,
+ 0x52a: 0x4954, 0x52b: 0x496c, 0x52c: 0x495c, 0x52d: 0x4974, 0x52e: 0x4964, 0x52f: 0x497c,
+ 0x530: 0x48dc, 0x531: 0x48e2, 0x532: 0x3e18, 0x533: 0x3e30, 0x534: 0x3e20, 0x535: 0x3e38,
+ 0x536: 0x3e28, 0x537: 0x3e40, 0x538: 0x4864, 0x539: 0x486a, 0x53a: 0x3d18, 0x53b: 0x3d30,
+ 0x53c: 0x3d20, 0x53d: 0x3d38, 0x53e: 0x3d28, 0x53f: 0x3d40,
+ // Block 0x15, offset 0x540
+ 0x540: 0x48e8, 0x541: 0x48ee, 0x542: 0x3e48, 0x543: 0x3e58, 0x544: 0x3e50, 0x545: 0x3e60,
+ 0x548: 0x4870, 0x549: 0x4876, 0x54a: 0x3d48, 0x54b: 0x3d58,
+ 0x54c: 0x3d50, 0x54d: 0x3d60, 0x550: 0x48fa, 0x551: 0x4900,
+ 0x552: 0x3e80, 0x553: 0x3e98, 0x554: 0x3e88, 0x555: 0x3ea0, 0x556: 0x3e90, 0x557: 0x3ea8,
+ 0x559: 0x487c, 0x55b: 0x3d68, 0x55d: 0x3d70,
+ 0x55f: 0x3d78, 0x560: 0x4912, 0x561: 0x4918, 0x562: 0x4a14, 0x563: 0x4a2c,
+ 0x564: 0x4a1c, 0x565: 0x4a34, 0x566: 0x4a24, 0x567: 0x4a3c, 0x568: 0x4882, 0x569: 0x4888,
+ 0x56a: 0x4984, 0x56b: 0x499c, 0x56c: 0x498c, 0x56d: 0x49a4, 0x56e: 0x4994, 0x56f: 0x49ac,
+ 0x570: 0x488e, 0x571: 0x43b4, 0x572: 0x3691, 0x573: 0x43ba, 0x574: 0x48b8, 0x575: 0x43c0,
+ 0x576: 0x36a3, 0x577: 0x43c6, 0x578: 0x36c1, 0x579: 0x43cc, 0x57a: 0x36d9, 0x57b: 0x43d2,
+ 0x57c: 0x4906, 0x57d: 0x43d8,
+ // Block 0x16, offset 0x580
+ 0x580: 0x3da0, 0x581: 0x3da8, 0x582: 0x4184, 0x583: 0x41a2, 0x584: 0x418e, 0x585: 0x41ac,
+ 0x586: 0x4198, 0x587: 0x41b6, 0x588: 0x3cd8, 0x589: 0x3ce0, 0x58a: 0x40d0, 0x58b: 0x40ee,
+ 0x58c: 0x40da, 0x58d: 0x40f8, 0x58e: 0x40e4, 0x58f: 0x4102, 0x590: 0x3de8, 0x591: 0x3df0,
+ 0x592: 0x41c0, 0x593: 0x41de, 0x594: 0x41ca, 0x595: 0x41e8, 0x596: 0x41d4, 0x597: 0x41f2,
+ 0x598: 0x3d08, 0x599: 0x3d10, 0x59a: 0x410c, 0x59b: 0x412a, 0x59c: 0x4116, 0x59d: 0x4134,
+ 0x59e: 0x4120, 0x59f: 0x413e, 0x5a0: 0x3ec0, 0x5a1: 0x3ec8, 0x5a2: 0x41fc, 0x5a3: 0x421a,
+ 0x5a4: 0x4206, 0x5a5: 0x4224, 0x5a6: 0x4210, 0x5a7: 0x422e, 0x5a8: 0x3d80, 0x5a9: 0x3d88,
+ 0x5aa: 0x4148, 0x5ab: 0x4166, 0x5ac: 0x4152, 0x5ad: 0x4170, 0x5ae: 0x415c, 0x5af: 0x417a,
+ 0x5b0: 0x3685, 0x5b1: 0x367f, 0x5b2: 0x3d90, 0x5b3: 0x368b, 0x5b4: 0x3d98,
+ 0x5b6: 0x48a6, 0x5b7: 0x3db0, 0x5b8: 0x35f5, 0x5b9: 0x35ef, 0x5ba: 0x35e3, 0x5bb: 0x4384,
+ 0x5bc: 0x35fb, 0x5bd: 0x8100, 0x5be: 0x01d3, 0x5bf: 0xa100,
+ // Block 0x17, offset 0x5c0
+ 0x5c0: 0x8100, 0x5c1: 0x35a7, 0x5c2: 0x3dd8, 0x5c3: 0x369d, 0x5c4: 0x3de0,
+ 0x5c6: 0x48d0, 0x5c7: 0x3df8, 0x5c8: 0x3601, 0x5c9: 0x438a, 0x5ca: 0x360d, 0x5cb: 0x4390,
+ 0x5cc: 0x3619, 0x5cd: 0x3b8f, 0x5ce: 0x3b96, 0x5cf: 0x3b9d, 0x5d0: 0x36b5, 0x5d1: 0x36af,
+ 0x5d2: 0x3e00, 0x5d3: 0x457a, 0x5d6: 0x36bb, 0x5d7: 0x3e10,
+ 0x5d8: 0x3631, 0x5d9: 0x362b, 0x5da: 0x361f, 0x5db: 0x4396, 0x5dd: 0x3ba4,
+ 0x5de: 0x3bab, 0x5df: 0x3bb2, 0x5e0: 0x36eb, 0x5e1: 0x36e5, 0x5e2: 0x3e68, 0x5e3: 0x4582,
+ 0x5e4: 0x36cd, 0x5e5: 0x36d3, 0x5e6: 0x36f1, 0x5e7: 0x3e78, 0x5e8: 0x3661, 0x5e9: 0x365b,
+ 0x5ea: 0x364f, 0x5eb: 0x43a2, 0x5ec: 0x3649, 0x5ed: 0x359b, 0x5ee: 0x437e, 0x5ef: 0x0081,
+ 0x5f2: 0x3eb0, 0x5f3: 0x36f7, 0x5f4: 0x3eb8,
+ 0x5f6: 0x491e, 0x5f7: 0x3ed0, 0x5f8: 0x363d, 0x5f9: 0x439c, 0x5fa: 0x366d, 0x5fb: 0x43ae,
+ 0x5fc: 0x3679, 0x5fd: 0x4256, 0x5fe: 0xa100,
+ // Block 0x18, offset 0x600
+ 0x601: 0x3c06, 0x603: 0xa000, 0x604: 0x3c0d, 0x605: 0xa000,
+ 0x607: 0x3c14, 0x608: 0xa000, 0x609: 0x3c1b,
+ 0x60d: 0xa000,
+ 0x620: 0x2f65, 0x621: 0xa000, 0x622: 0x3c29,
+ 0x624: 0xa000, 0x625: 0xa000,
+ 0x62d: 0x3c22, 0x62e: 0x2f60, 0x62f: 0x2f6a,
+ 0x630: 0x3c30, 0x631: 0x3c37, 0x632: 0xa000, 0x633: 0xa000, 0x634: 0x3c3e, 0x635: 0x3c45,
+ 0x636: 0xa000, 0x637: 0xa000, 0x638: 0x3c4c, 0x639: 0x3c53, 0x63a: 0xa000, 0x63b: 0xa000,
+ 0x63c: 0xa000, 0x63d: 0xa000,
+ // Block 0x19, offset 0x640
+ 0x640: 0x3c5a, 0x641: 0x3c61, 0x642: 0xa000, 0x643: 0xa000, 0x644: 0x3c76, 0x645: 0x3c7d,
+ 0x646: 0xa000, 0x647: 0xa000, 0x648: 0x3c84, 0x649: 0x3c8b,
+ 0x651: 0xa000,
+ 0x652: 0xa000,
+ 0x662: 0xa000,
+ 0x668: 0xa000, 0x669: 0xa000,
+ 0x66b: 0xa000, 0x66c: 0x3ca0, 0x66d: 0x3ca7, 0x66e: 0x3cae, 0x66f: 0x3cb5,
+ 0x672: 0xa000, 0x673: 0xa000, 0x674: 0xa000, 0x675: 0xa000,
+ // Block 0x1a, offset 0x680
+ 0x686: 0xa000, 0x68b: 0xa000,
+ 0x68c: 0x3f08, 0x68d: 0xa000, 0x68e: 0x3f10, 0x68f: 0xa000, 0x690: 0x3f18, 0x691: 0xa000,
+ 0x692: 0x3f20, 0x693: 0xa000, 0x694: 0x3f28, 0x695: 0xa000, 0x696: 0x3f30, 0x697: 0xa000,
+ 0x698: 0x3f38, 0x699: 0xa000, 0x69a: 0x3f40, 0x69b: 0xa000, 0x69c: 0x3f48, 0x69d: 0xa000,
+ 0x69e: 0x3f50, 0x69f: 0xa000, 0x6a0: 0x3f58, 0x6a1: 0xa000, 0x6a2: 0x3f60,
+ 0x6a4: 0xa000, 0x6a5: 0x3f68, 0x6a6: 0xa000, 0x6a7: 0x3f70, 0x6a8: 0xa000, 0x6a9: 0x3f78,
+ 0x6af: 0xa000,
+ 0x6b0: 0x3f80, 0x6b1: 0x3f88, 0x6b2: 0xa000, 0x6b3: 0x3f90, 0x6b4: 0x3f98, 0x6b5: 0xa000,
+ 0x6b6: 0x3fa0, 0x6b7: 0x3fa8, 0x6b8: 0xa000, 0x6b9: 0x3fb0, 0x6ba: 0x3fb8, 0x6bb: 0xa000,
+ 0x6bc: 0x3fc0, 0x6bd: 0x3fc8,
+ // Block 0x1b, offset 0x6c0
+ 0x6d4: 0x3f00,
+ 0x6d9: 0x9903, 0x6da: 0x9903, 0x6db: 0x8100, 0x6dc: 0x8100, 0x6dd: 0xa000,
+ 0x6de: 0x3fd0,
+ 0x6e6: 0xa000,
+ 0x6eb: 0xa000, 0x6ec: 0x3fe0, 0x6ed: 0xa000, 0x6ee: 0x3fe8, 0x6ef: 0xa000,
+ 0x6f0: 0x3ff0, 0x6f1: 0xa000, 0x6f2: 0x3ff8, 0x6f3: 0xa000, 0x6f4: 0x4000, 0x6f5: 0xa000,
+ 0x6f6: 0x4008, 0x6f7: 0xa000, 0x6f8: 0x4010, 0x6f9: 0xa000, 0x6fa: 0x4018, 0x6fb: 0xa000,
+ 0x6fc: 0x4020, 0x6fd: 0xa000, 0x6fe: 0x4028, 0x6ff: 0xa000,
+ // Block 0x1c, offset 0x700
+ 0x700: 0x4030, 0x701: 0xa000, 0x702: 0x4038, 0x704: 0xa000, 0x705: 0x4040,
+ 0x706: 0xa000, 0x707: 0x4048, 0x708: 0xa000, 0x709: 0x4050,
+ 0x70f: 0xa000, 0x710: 0x4058, 0x711: 0x4060,
+ 0x712: 0xa000, 0x713: 0x4068, 0x714: 0x4070, 0x715: 0xa000, 0x716: 0x4078, 0x717: 0x4080,
+ 0x718: 0xa000, 0x719: 0x4088, 0x71a: 0x4090, 0x71b: 0xa000, 0x71c: 0x4098, 0x71d: 0x40a0,
+ 0x72f: 0xa000,
+ 0x730: 0xa000, 0x731: 0xa000, 0x732: 0xa000, 0x734: 0x3fd8,
+ 0x737: 0x40a8, 0x738: 0x40b0, 0x739: 0x40b8, 0x73a: 0x40c0,
+ 0x73d: 0xa000, 0x73e: 0x40c8,
+ // Block 0x1d, offset 0x740
+ 0x740: 0x1377, 0x741: 0x0cfb, 0x742: 0x13d3, 0x743: 0x139f, 0x744: 0x0e57, 0x745: 0x06eb,
+ 0x746: 0x08df, 0x747: 0x162b, 0x748: 0x162b, 0x749: 0x0a0b, 0x74a: 0x145f, 0x74b: 0x0943,
+ 0x74c: 0x0a07, 0x74d: 0x0bef, 0x74e: 0x0fcf, 0x74f: 0x115f, 0x750: 0x1297, 0x751: 0x12d3,
+ 0x752: 0x1307, 0x753: 0x141b, 0x754: 0x0d73, 0x755: 0x0dff, 0x756: 0x0eab, 0x757: 0x0f43,
+ 0x758: 0x125f, 0x759: 0x1447, 0x75a: 0x1573, 0x75b: 0x070f, 0x75c: 0x08b3, 0x75d: 0x0d87,
+ 0x75e: 0x0ecf, 0x75f: 0x1293, 0x760: 0x15c3, 0x761: 0x0ab3, 0x762: 0x0e77, 0x763: 0x1283,
+ 0x764: 0x1317, 0x765: 0x0c23, 0x766: 0x11bb, 0x767: 0x12df, 0x768: 0x0b1f, 0x769: 0x0d0f,
+ 0x76a: 0x0e17, 0x76b: 0x0f1b, 0x76c: 0x1427, 0x76d: 0x074f, 0x76e: 0x07e7, 0x76f: 0x0853,
+ 0x770: 0x0c8b, 0x771: 0x0d7f, 0x772: 0x0ecb, 0x773: 0x0fef, 0x774: 0x1177, 0x775: 0x128b,
+ 0x776: 0x12a3, 0x777: 0x13c7, 0x778: 0x14ef, 0x779: 0x15a3, 0x77a: 0x15bf, 0x77b: 0x102b,
+ 0x77c: 0x106b, 0x77d: 0x1123, 0x77e: 0x1243, 0x77f: 0x147b,
+ // Block 0x1e, offset 0x780
+ 0x780: 0x15cb, 0x781: 0x134b, 0x782: 0x09c7, 0x783: 0x0b3b, 0x784: 0x10db, 0x785: 0x119b,
+ 0x786: 0x0eff, 0x787: 0x1033, 0x788: 0x1397, 0x789: 0x14e7, 0x78a: 0x09c3, 0x78b: 0x0a8f,
+ 0x78c: 0x0d77, 0x78d: 0x0e2b, 0x78e: 0x0e5f, 0x78f: 0x1113, 0x790: 0x113b, 0x791: 0x14a7,
+ 0x792: 0x084f, 0x793: 0x11a7, 0x794: 0x07f3, 0x795: 0x07ef, 0x796: 0x1097, 0x797: 0x1127,
+ 0x798: 0x125b, 0x799: 0x14af, 0x79a: 0x1367, 0x79b: 0x0c27, 0x79c: 0x0d73, 0x79d: 0x1357,
+ 0x79e: 0x06f7, 0x79f: 0x0a63, 0x7a0: 0x0b93, 0x7a1: 0x0f2f, 0x7a2: 0x0faf, 0x7a3: 0x0873,
+ 0x7a4: 0x103b, 0x7a5: 0x075f, 0x7a6: 0x0b77, 0x7a7: 0x06d7, 0x7a8: 0x0deb, 0x7a9: 0x0ca3,
+ 0x7aa: 0x110f, 0x7ab: 0x08c7, 0x7ac: 0x09b3, 0x7ad: 0x0ffb, 0x7ae: 0x1263, 0x7af: 0x133b,
+ 0x7b0: 0x0db7, 0x7b1: 0x13f7, 0x7b2: 0x0de3, 0x7b3: 0x0c37, 0x7b4: 0x121b, 0x7b5: 0x0c57,
+ 0x7b6: 0x0fab, 0x7b7: 0x072b, 0x7b8: 0x07a7, 0x7b9: 0x07eb, 0x7ba: 0x0d53, 0x7bb: 0x10fb,
+ 0x7bc: 0x11f3, 0x7bd: 0x1347, 0x7be: 0x145b, 0x7bf: 0x085b,
+ // Block 0x1f, offset 0x7c0
+ 0x7c0: 0x090f, 0x7c1: 0x0a17, 0x7c2: 0x0b2f, 0x7c3: 0x0cbf, 0x7c4: 0x0e7b, 0x7c5: 0x103f,
+ 0x7c6: 0x1497, 0x7c7: 0x157b, 0x7c8: 0x15cf, 0x7c9: 0x15e7, 0x7ca: 0x0837, 0x7cb: 0x0cf3,
+ 0x7cc: 0x0da3, 0x7cd: 0x13eb, 0x7ce: 0x0afb, 0x7cf: 0x0bd7, 0x7d0: 0x0bf3, 0x7d1: 0x0c83,
+ 0x7d2: 0x0e6b, 0x7d3: 0x0eb7, 0x7d4: 0x0f67, 0x7d5: 0x108b, 0x7d6: 0x112f, 0x7d7: 0x1193,
+ 0x7d8: 0x13db, 0x7d9: 0x126b, 0x7da: 0x1403, 0x7db: 0x147f, 0x7dc: 0x080f, 0x7dd: 0x083b,
+ 0x7de: 0x0923, 0x7df: 0x0ea7, 0x7e0: 0x12f3, 0x7e1: 0x133b, 0x7e2: 0x0b1b, 0x7e3: 0x0b8b,
+ 0x7e4: 0x0c4f, 0x7e5: 0x0daf, 0x7e6: 0x10d7, 0x7e7: 0x0f23, 0x7e8: 0x073b, 0x7e9: 0x097f,
+ 0x7ea: 0x0a63, 0x7eb: 0x0ac7, 0x7ec: 0x0b97, 0x7ed: 0x0f3f, 0x7ee: 0x0f5b, 0x7ef: 0x116b,
+ 0x7f0: 0x118b, 0x7f1: 0x1463, 0x7f2: 0x14e3, 0x7f3: 0x14f3, 0x7f4: 0x152f, 0x7f5: 0x0753,
+ 0x7f6: 0x107f, 0x7f7: 0x144f, 0x7f8: 0x14cb, 0x7f9: 0x0baf, 0x7fa: 0x0717, 0x7fb: 0x0777,
+ 0x7fc: 0x0a67, 0x7fd: 0x0a87, 0x7fe: 0x0caf, 0x7ff: 0x0d73,
+ // Block 0x20, offset 0x800
+ 0x800: 0x0ec3, 0x801: 0x0fcb, 0x802: 0x1277, 0x803: 0x1417, 0x804: 0x1623, 0x805: 0x0ce3,
+ 0x806: 0x14a3, 0x807: 0x0833, 0x808: 0x0d2f, 0x809: 0x0d3b, 0x80a: 0x0e0f, 0x80b: 0x0e47,
+ 0x80c: 0x0f4b, 0x80d: 0x0fa7, 0x80e: 0x1027, 0x80f: 0x110b, 0x810: 0x153b, 0x811: 0x07af,
+ 0x812: 0x0c03, 0x813: 0x14b3, 0x814: 0x0767, 0x815: 0x0aab, 0x816: 0x0e2f, 0x817: 0x13df,
+ 0x818: 0x0b67, 0x819: 0x0bb7, 0x81a: 0x0d43, 0x81b: 0x0f2f, 0x81c: 0x14bb, 0x81d: 0x0817,
+ 0x81e: 0x08ff, 0x81f: 0x0a97, 0x820: 0x0cd3, 0x821: 0x0d1f, 0x822: 0x0d5f, 0x823: 0x0df3,
+ 0x824: 0x0f47, 0x825: 0x0fbb, 0x826: 0x1157, 0x827: 0x12f7, 0x828: 0x1303, 0x829: 0x1457,
+ 0x82a: 0x14d7, 0x82b: 0x0883, 0x82c: 0x0e4b, 0x82d: 0x0903, 0x82e: 0x0ec7, 0x82f: 0x0f6b,
+ 0x830: 0x1287, 0x831: 0x14bf, 0x832: 0x15ab, 0x833: 0x15d3, 0x834: 0x0d37, 0x835: 0x0e27,
+ 0x836: 0x11c3, 0x837: 0x10b7, 0x838: 0x10c3, 0x839: 0x10e7, 0x83a: 0x0f17, 0x83b: 0x0e9f,
+ 0x83c: 0x1363, 0x83d: 0x0733, 0x83e: 0x122b, 0x83f: 0x081b,
+ // Block 0x21, offset 0x840
+ 0x840: 0x080b, 0x841: 0x0b0b, 0x842: 0x0c2b, 0x843: 0x10f3, 0x844: 0x0a53, 0x845: 0x0e03,
+ 0x846: 0x0cef, 0x847: 0x13e7, 0x848: 0x12e7, 0x849: 0x14ab, 0x84a: 0x1323, 0x84b: 0x0b27,
+ 0x84c: 0x0787, 0x84d: 0x095b, 0x850: 0x09af,
+ 0x852: 0x0cdf, 0x855: 0x07f7, 0x856: 0x0f1f, 0x857: 0x0fe3,
+ 0x858: 0x1047, 0x859: 0x1063, 0x85a: 0x1067, 0x85b: 0x107b, 0x85c: 0x14fb, 0x85d: 0x10eb,
+ 0x85e: 0x116f, 0x860: 0x128f, 0x862: 0x1353,
+ 0x865: 0x1407, 0x866: 0x1433,
+ 0x86a: 0x154f, 0x86b: 0x1553, 0x86c: 0x1557, 0x86d: 0x15bb, 0x86e: 0x142b, 0x86f: 0x14c7,
+ 0x870: 0x0757, 0x871: 0x077b, 0x872: 0x078f, 0x873: 0x084b, 0x874: 0x0857, 0x875: 0x0897,
+ 0x876: 0x094b, 0x877: 0x0967, 0x878: 0x096f, 0x879: 0x09ab, 0x87a: 0x09b7, 0x87b: 0x0a93,
+ 0x87c: 0x0a9b, 0x87d: 0x0ba3, 0x87e: 0x0bcb, 0x87f: 0x0bd3,
+ // Block 0x22, offset 0x880
+ 0x880: 0x0beb, 0x881: 0x0c97, 0x882: 0x0cc7, 0x883: 0x0ce7, 0x884: 0x0d57, 0x885: 0x0e1b,
+ 0x886: 0x0e37, 0x887: 0x0e67, 0x888: 0x0ebb, 0x889: 0x0edb, 0x88a: 0x0f4f, 0x88b: 0x102f,
+ 0x88c: 0x104b, 0x88d: 0x1053, 0x88e: 0x104f, 0x88f: 0x1057, 0x890: 0x105b, 0x891: 0x105f,
+ 0x892: 0x1073, 0x893: 0x1077, 0x894: 0x109b, 0x895: 0x10af, 0x896: 0x10cb, 0x897: 0x112f,
+ 0x898: 0x1137, 0x899: 0x113f, 0x89a: 0x1153, 0x89b: 0x117b, 0x89c: 0x11cb, 0x89d: 0x11ff,
+ 0x89e: 0x11ff, 0x89f: 0x1267, 0x8a0: 0x130f, 0x8a1: 0x1327, 0x8a2: 0x135b, 0x8a3: 0x135f,
+ 0x8a4: 0x13a3, 0x8a5: 0x13a7, 0x8a6: 0x13ff, 0x8a7: 0x1407, 0x8a8: 0x14db, 0x8a9: 0x151f,
+ 0x8aa: 0x1537, 0x8ab: 0x0b9b, 0x8ac: 0x171e, 0x8ad: 0x11e3,
+ 0x8b0: 0x06df, 0x8b1: 0x07e3, 0x8b2: 0x07a3, 0x8b3: 0x074b, 0x8b4: 0x078b, 0x8b5: 0x07b7,
+ 0x8b6: 0x0847, 0x8b7: 0x0863, 0x8b8: 0x094b, 0x8b9: 0x0937, 0x8ba: 0x0947, 0x8bb: 0x0963,
+ 0x8bc: 0x09af, 0x8bd: 0x09bf, 0x8be: 0x0a03, 0x8bf: 0x0a0f,
+ // Block 0x23, offset 0x8c0
+ 0x8c0: 0x0a2b, 0x8c1: 0x0a3b, 0x8c2: 0x0b23, 0x8c3: 0x0b2b, 0x8c4: 0x0b5b, 0x8c5: 0x0b7b,
+ 0x8c6: 0x0bab, 0x8c7: 0x0bc3, 0x8c8: 0x0bb3, 0x8c9: 0x0bd3, 0x8ca: 0x0bc7, 0x8cb: 0x0beb,
+ 0x8cc: 0x0c07, 0x8cd: 0x0c5f, 0x8ce: 0x0c6b, 0x8cf: 0x0c73, 0x8d0: 0x0c9b, 0x8d1: 0x0cdf,
+ 0x8d2: 0x0d0f, 0x8d3: 0x0d13, 0x8d4: 0x0d27, 0x8d5: 0x0da7, 0x8d6: 0x0db7, 0x8d7: 0x0e0f,
+ 0x8d8: 0x0e5b, 0x8d9: 0x0e53, 0x8da: 0x0e67, 0x8db: 0x0e83, 0x8dc: 0x0ebb, 0x8dd: 0x1013,
+ 0x8de: 0x0edf, 0x8df: 0x0f13, 0x8e0: 0x0f1f, 0x8e1: 0x0f5f, 0x8e2: 0x0f7b, 0x8e3: 0x0f9f,
+ 0x8e4: 0x0fc3, 0x8e5: 0x0fc7, 0x8e6: 0x0fe3, 0x8e7: 0x0fe7, 0x8e8: 0x0ff7, 0x8e9: 0x100b,
+ 0x8ea: 0x1007, 0x8eb: 0x1037, 0x8ec: 0x10b3, 0x8ed: 0x10cb, 0x8ee: 0x10e3, 0x8ef: 0x111b,
+ 0x8f0: 0x112f, 0x8f1: 0x114b, 0x8f2: 0x117b, 0x8f3: 0x122f, 0x8f4: 0x1257, 0x8f5: 0x12cb,
+ 0x8f6: 0x1313, 0x8f7: 0x131f, 0x8f8: 0x1327, 0x8f9: 0x133f, 0x8fa: 0x1353, 0x8fb: 0x1343,
+ 0x8fc: 0x135b, 0x8fd: 0x1357, 0x8fe: 0x134f, 0x8ff: 0x135f,
+ // Block 0x24, offset 0x900
+ 0x900: 0x136b, 0x901: 0x13a7, 0x902: 0x13e3, 0x903: 0x1413, 0x904: 0x144b, 0x905: 0x146b,
+ 0x906: 0x14b7, 0x907: 0x14db, 0x908: 0x14fb, 0x909: 0x150f, 0x90a: 0x151f, 0x90b: 0x152b,
+ 0x90c: 0x1537, 0x90d: 0x158b, 0x90e: 0x162b, 0x90f: 0x16b5, 0x910: 0x16b0, 0x911: 0x16e2,
+ 0x912: 0x0607, 0x913: 0x062f, 0x914: 0x0633, 0x915: 0x1764, 0x916: 0x1791, 0x917: 0x1809,
+ 0x918: 0x1617, 0x919: 0x1627,
+ // Block 0x25, offset 0x940
+ 0x940: 0x06fb, 0x941: 0x06f3, 0x942: 0x0703, 0x943: 0x1647, 0x944: 0x0747, 0x945: 0x0757,
+ 0x946: 0x075b, 0x947: 0x0763, 0x948: 0x076b, 0x949: 0x076f, 0x94a: 0x077b, 0x94b: 0x0773,
+ 0x94c: 0x05b3, 0x94d: 0x165b, 0x94e: 0x078f, 0x94f: 0x0793, 0x950: 0x0797, 0x951: 0x07b3,
+ 0x952: 0x164c, 0x953: 0x05b7, 0x954: 0x079f, 0x955: 0x07bf, 0x956: 0x1656, 0x957: 0x07cf,
+ 0x958: 0x07d7, 0x959: 0x0737, 0x95a: 0x07df, 0x95b: 0x07e3, 0x95c: 0x1831, 0x95d: 0x07ff,
+ 0x95e: 0x0807, 0x95f: 0x05bf, 0x960: 0x081f, 0x961: 0x0823, 0x962: 0x082b, 0x963: 0x082f,
+ 0x964: 0x05c3, 0x965: 0x0847, 0x966: 0x084b, 0x967: 0x0857, 0x968: 0x0863, 0x969: 0x0867,
+ 0x96a: 0x086b, 0x96b: 0x0873, 0x96c: 0x0893, 0x96d: 0x0897, 0x96e: 0x089f, 0x96f: 0x08af,
+ 0x970: 0x08b7, 0x971: 0x08bb, 0x972: 0x08bb, 0x973: 0x08bb, 0x974: 0x166a, 0x975: 0x0e93,
+ 0x976: 0x08cf, 0x977: 0x08d7, 0x978: 0x166f, 0x979: 0x08e3, 0x97a: 0x08eb, 0x97b: 0x08f3,
+ 0x97c: 0x091b, 0x97d: 0x0907, 0x97e: 0x0913, 0x97f: 0x0917,
+ // Block 0x26, offset 0x980
+ 0x980: 0x091f, 0x981: 0x0927, 0x982: 0x092b, 0x983: 0x0933, 0x984: 0x093b, 0x985: 0x093f,
+ 0x986: 0x093f, 0x987: 0x0947, 0x988: 0x094f, 0x989: 0x0953, 0x98a: 0x095f, 0x98b: 0x0983,
+ 0x98c: 0x0967, 0x98d: 0x0987, 0x98e: 0x096b, 0x98f: 0x0973, 0x990: 0x080b, 0x991: 0x09cf,
+ 0x992: 0x0997, 0x993: 0x099b, 0x994: 0x099f, 0x995: 0x0993, 0x996: 0x09a7, 0x997: 0x09a3,
+ 0x998: 0x09bb, 0x999: 0x1674, 0x99a: 0x09d7, 0x99b: 0x09db, 0x99c: 0x09e3, 0x99d: 0x09ef,
+ 0x99e: 0x09f7, 0x99f: 0x0a13, 0x9a0: 0x1679, 0x9a1: 0x167e, 0x9a2: 0x0a1f, 0x9a3: 0x0a23,
+ 0x9a4: 0x0a27, 0x9a5: 0x0a1b, 0x9a6: 0x0a2f, 0x9a7: 0x05c7, 0x9a8: 0x05cb, 0x9a9: 0x0a37,
+ 0x9aa: 0x0a3f, 0x9ab: 0x0a3f, 0x9ac: 0x1683, 0x9ad: 0x0a5b, 0x9ae: 0x0a5f, 0x9af: 0x0a63,
+ 0x9b0: 0x0a6b, 0x9b1: 0x1688, 0x9b2: 0x0a73, 0x9b3: 0x0a77, 0x9b4: 0x0b4f, 0x9b5: 0x0a7f,
+ 0x9b6: 0x05cf, 0x9b7: 0x0a8b, 0x9b8: 0x0a9b, 0x9b9: 0x0aa7, 0x9ba: 0x0aa3, 0x9bb: 0x1692,
+ 0x9bc: 0x0aaf, 0x9bd: 0x1697, 0x9be: 0x0abb, 0x9bf: 0x0ab7,
+ // Block 0x27, offset 0x9c0
+ 0x9c0: 0x0abf, 0x9c1: 0x0acf, 0x9c2: 0x0ad3, 0x9c3: 0x05d3, 0x9c4: 0x0ae3, 0x9c5: 0x0aeb,
+ 0x9c6: 0x0aef, 0x9c7: 0x0af3, 0x9c8: 0x05d7, 0x9c9: 0x169c, 0x9ca: 0x05db, 0x9cb: 0x0b0f,
+ 0x9cc: 0x0b13, 0x9cd: 0x0b17, 0x9ce: 0x0b1f, 0x9cf: 0x1863, 0x9d0: 0x0b37, 0x9d1: 0x16a6,
+ 0x9d2: 0x16a6, 0x9d3: 0x11d7, 0x9d4: 0x0b47, 0x9d5: 0x0b47, 0x9d6: 0x05df, 0x9d7: 0x16c9,
+ 0x9d8: 0x179b, 0x9d9: 0x0b57, 0x9da: 0x0b5f, 0x9db: 0x05e3, 0x9dc: 0x0b73, 0x9dd: 0x0b83,
+ 0x9de: 0x0b87, 0x9df: 0x0b8f, 0x9e0: 0x0b9f, 0x9e1: 0x05eb, 0x9e2: 0x05e7, 0x9e3: 0x0ba3,
+ 0x9e4: 0x16ab, 0x9e5: 0x0ba7, 0x9e6: 0x0bbb, 0x9e7: 0x0bbf, 0x9e8: 0x0bc3, 0x9e9: 0x0bbf,
+ 0x9ea: 0x0bcf, 0x9eb: 0x0bd3, 0x9ec: 0x0be3, 0x9ed: 0x0bdb, 0x9ee: 0x0bdf, 0x9ef: 0x0be7,
+ 0x9f0: 0x0beb, 0x9f1: 0x0bef, 0x9f2: 0x0bfb, 0x9f3: 0x0bff, 0x9f4: 0x0c17, 0x9f5: 0x0c1f,
+ 0x9f6: 0x0c2f, 0x9f7: 0x0c43, 0x9f8: 0x16ba, 0x9f9: 0x0c3f, 0x9fa: 0x0c33, 0x9fb: 0x0c4b,
+ 0x9fc: 0x0c53, 0x9fd: 0x0c67, 0x9fe: 0x16bf, 0x9ff: 0x0c6f,
+ // Block 0x28, offset 0xa00
+ 0xa00: 0x0c63, 0xa01: 0x0c5b, 0xa02: 0x05ef, 0xa03: 0x0c77, 0xa04: 0x0c7f, 0xa05: 0x0c87,
+ 0xa06: 0x0c7b, 0xa07: 0x05f3, 0xa08: 0x0c97, 0xa09: 0x0c9f, 0xa0a: 0x16c4, 0xa0b: 0x0ccb,
+ 0xa0c: 0x0cff, 0xa0d: 0x0cdb, 0xa0e: 0x05ff, 0xa0f: 0x0ce7, 0xa10: 0x05fb, 0xa11: 0x05f7,
+ 0xa12: 0x07c3, 0xa13: 0x07c7, 0xa14: 0x0d03, 0xa15: 0x0ceb, 0xa16: 0x11ab, 0xa17: 0x0663,
+ 0xa18: 0x0d0f, 0xa19: 0x0d13, 0xa1a: 0x0d17, 0xa1b: 0x0d2b, 0xa1c: 0x0d23, 0xa1d: 0x16dd,
+ 0xa1e: 0x0603, 0xa1f: 0x0d3f, 0xa20: 0x0d33, 0xa21: 0x0d4f, 0xa22: 0x0d57, 0xa23: 0x16e7,
+ 0xa24: 0x0d5b, 0xa25: 0x0d47, 0xa26: 0x0d63, 0xa27: 0x0607, 0xa28: 0x0d67, 0xa29: 0x0d6b,
+ 0xa2a: 0x0d6f, 0xa2b: 0x0d7b, 0xa2c: 0x16ec, 0xa2d: 0x0d83, 0xa2e: 0x060b, 0xa2f: 0x0d8f,
+ 0xa30: 0x16f1, 0xa31: 0x0d93, 0xa32: 0x060f, 0xa33: 0x0d9f, 0xa34: 0x0dab, 0xa35: 0x0db7,
+ 0xa36: 0x0dbb, 0xa37: 0x16f6, 0xa38: 0x168d, 0xa39: 0x16fb, 0xa3a: 0x0ddb, 0xa3b: 0x1700,
+ 0xa3c: 0x0de7, 0xa3d: 0x0def, 0xa3e: 0x0ddf, 0xa3f: 0x0dfb,
+ // Block 0x29, offset 0xa40
+ 0xa40: 0x0e0b, 0xa41: 0x0e1b, 0xa42: 0x0e0f, 0xa43: 0x0e13, 0xa44: 0x0e1f, 0xa45: 0x0e23,
+ 0xa46: 0x1705, 0xa47: 0x0e07, 0xa48: 0x0e3b, 0xa49: 0x0e3f, 0xa4a: 0x0613, 0xa4b: 0x0e53,
+ 0xa4c: 0x0e4f, 0xa4d: 0x170a, 0xa4e: 0x0e33, 0xa4f: 0x0e6f, 0xa50: 0x170f, 0xa51: 0x1714,
+ 0xa52: 0x0e73, 0xa53: 0x0e87, 0xa54: 0x0e83, 0xa55: 0x0e7f, 0xa56: 0x0617, 0xa57: 0x0e8b,
+ 0xa58: 0x0e9b, 0xa59: 0x0e97, 0xa5a: 0x0ea3, 0xa5b: 0x1651, 0xa5c: 0x0eb3, 0xa5d: 0x1719,
+ 0xa5e: 0x0ebf, 0xa5f: 0x1723, 0xa60: 0x0ed3, 0xa61: 0x0edf, 0xa62: 0x0ef3, 0xa63: 0x1728,
+ 0xa64: 0x0f07, 0xa65: 0x0f0b, 0xa66: 0x172d, 0xa67: 0x1732, 0xa68: 0x0f27, 0xa69: 0x0f37,
+ 0xa6a: 0x061b, 0xa6b: 0x0f3b, 0xa6c: 0x061f, 0xa6d: 0x061f, 0xa6e: 0x0f53, 0xa6f: 0x0f57,
+ 0xa70: 0x0f5f, 0xa71: 0x0f63, 0xa72: 0x0f6f, 0xa73: 0x0623, 0xa74: 0x0f87, 0xa75: 0x1737,
+ 0xa76: 0x0fa3, 0xa77: 0x173c, 0xa78: 0x0faf, 0xa79: 0x16a1, 0xa7a: 0x0fbf, 0xa7b: 0x1741,
+ 0xa7c: 0x1746, 0xa7d: 0x174b, 0xa7e: 0x0627, 0xa7f: 0x062b,
+ // Block 0x2a, offset 0xa80
+ 0xa80: 0x0ff7, 0xa81: 0x1755, 0xa82: 0x1750, 0xa83: 0x175a, 0xa84: 0x175f, 0xa85: 0x0fff,
+ 0xa86: 0x1003, 0xa87: 0x1003, 0xa88: 0x100b, 0xa89: 0x0633, 0xa8a: 0x100f, 0xa8b: 0x0637,
+ 0xa8c: 0x063b, 0xa8d: 0x1769, 0xa8e: 0x1023, 0xa8f: 0x102b, 0xa90: 0x1037, 0xa91: 0x063f,
+ 0xa92: 0x176e, 0xa93: 0x105b, 0xa94: 0x1773, 0xa95: 0x1778, 0xa96: 0x107b, 0xa97: 0x1093,
+ 0xa98: 0x0643, 0xa99: 0x109b, 0xa9a: 0x109f, 0xa9b: 0x10a3, 0xa9c: 0x177d, 0xa9d: 0x1782,
+ 0xa9e: 0x1782, 0xa9f: 0x10bb, 0xaa0: 0x0647, 0xaa1: 0x1787, 0xaa2: 0x10cf, 0xaa3: 0x10d3,
+ 0xaa4: 0x064b, 0xaa5: 0x178c, 0xaa6: 0x10ef, 0xaa7: 0x064f, 0xaa8: 0x10ff, 0xaa9: 0x10f7,
+ 0xaaa: 0x1107, 0xaab: 0x1796, 0xaac: 0x111f, 0xaad: 0x0653, 0xaae: 0x112b, 0xaaf: 0x1133,
+ 0xab0: 0x1143, 0xab1: 0x0657, 0xab2: 0x17a0, 0xab3: 0x17a5, 0xab4: 0x065b, 0xab5: 0x17aa,
+ 0xab6: 0x115b, 0xab7: 0x17af, 0xab8: 0x1167, 0xab9: 0x1173, 0xaba: 0x117b, 0xabb: 0x17b4,
+ 0xabc: 0x17b9, 0xabd: 0x118f, 0xabe: 0x17be, 0xabf: 0x1197,
+ // Block 0x2b, offset 0xac0
+ 0xac0: 0x16ce, 0xac1: 0x065f, 0xac2: 0x11af, 0xac3: 0x11b3, 0xac4: 0x0667, 0xac5: 0x11b7,
+ 0xac6: 0x0a33, 0xac7: 0x17c3, 0xac8: 0x17c8, 0xac9: 0x16d3, 0xaca: 0x16d8, 0xacb: 0x11d7,
+ 0xacc: 0x11db, 0xacd: 0x13f3, 0xace: 0x066b, 0xacf: 0x1207, 0xad0: 0x1203, 0xad1: 0x120b,
+ 0xad2: 0x083f, 0xad3: 0x120f, 0xad4: 0x1213, 0xad5: 0x1217, 0xad6: 0x121f, 0xad7: 0x17cd,
+ 0xad8: 0x121b, 0xad9: 0x1223, 0xada: 0x1237, 0xadb: 0x123b, 0xadc: 0x1227, 0xadd: 0x123f,
+ 0xade: 0x1253, 0xadf: 0x1267, 0xae0: 0x1233, 0xae1: 0x1247, 0xae2: 0x124b, 0xae3: 0x124f,
+ 0xae4: 0x17d2, 0xae5: 0x17dc, 0xae6: 0x17d7, 0xae7: 0x066f, 0xae8: 0x126f, 0xae9: 0x1273,
+ 0xaea: 0x127b, 0xaeb: 0x17f0, 0xaec: 0x127f, 0xaed: 0x17e1, 0xaee: 0x0673, 0xaef: 0x0677,
+ 0xaf0: 0x17e6, 0xaf1: 0x17eb, 0xaf2: 0x067b, 0xaf3: 0x129f, 0xaf4: 0x12a3, 0xaf5: 0x12a7,
+ 0xaf6: 0x12ab, 0xaf7: 0x12b7, 0xaf8: 0x12b3, 0xaf9: 0x12bf, 0xafa: 0x12bb, 0xafb: 0x12cb,
+ 0xafc: 0x12c3, 0xafd: 0x12c7, 0xafe: 0x12cf, 0xaff: 0x067f,
+ // Block 0x2c, offset 0xb00
+ 0xb00: 0x12d7, 0xb01: 0x12db, 0xb02: 0x0683, 0xb03: 0x12eb, 0xb04: 0x12ef, 0xb05: 0x17f5,
+ 0xb06: 0x12fb, 0xb07: 0x12ff, 0xb08: 0x0687, 0xb09: 0x130b, 0xb0a: 0x05bb, 0xb0b: 0x17fa,
+ 0xb0c: 0x17ff, 0xb0d: 0x068b, 0xb0e: 0x068f, 0xb0f: 0x1337, 0xb10: 0x134f, 0xb11: 0x136b,
+ 0xb12: 0x137b, 0xb13: 0x1804, 0xb14: 0x138f, 0xb15: 0x1393, 0xb16: 0x13ab, 0xb17: 0x13b7,
+ 0xb18: 0x180e, 0xb19: 0x1660, 0xb1a: 0x13c3, 0xb1b: 0x13bf, 0xb1c: 0x13cb, 0xb1d: 0x1665,
+ 0xb1e: 0x13d7, 0xb1f: 0x13e3, 0xb20: 0x1813, 0xb21: 0x1818, 0xb22: 0x1423, 0xb23: 0x142f,
+ 0xb24: 0x1437, 0xb25: 0x181d, 0xb26: 0x143b, 0xb27: 0x1467, 0xb28: 0x1473, 0xb29: 0x1477,
+ 0xb2a: 0x146f, 0xb2b: 0x1483, 0xb2c: 0x1487, 0xb2d: 0x1822, 0xb2e: 0x1493, 0xb2f: 0x0693,
+ 0xb30: 0x149b, 0xb31: 0x1827, 0xb32: 0x0697, 0xb33: 0x14d3, 0xb34: 0x0ac3, 0xb35: 0x14eb,
+ 0xb36: 0x182c, 0xb37: 0x1836, 0xb38: 0x069b, 0xb39: 0x069f, 0xb3a: 0x1513, 0xb3b: 0x183b,
+ 0xb3c: 0x06a3, 0xb3d: 0x1840, 0xb3e: 0x152b, 0xb3f: 0x152b,
+ // Block 0x2d, offset 0xb40
+ 0xb40: 0x1533, 0xb41: 0x1845, 0xb42: 0x154b, 0xb43: 0x06a7, 0xb44: 0x155b, 0xb45: 0x1567,
+ 0xb46: 0x156f, 0xb47: 0x1577, 0xb48: 0x06ab, 0xb49: 0x184a, 0xb4a: 0x158b, 0xb4b: 0x15a7,
+ 0xb4c: 0x15b3, 0xb4d: 0x06af, 0xb4e: 0x06b3, 0xb4f: 0x15b7, 0xb50: 0x184f, 0xb51: 0x06b7,
+ 0xb52: 0x1854, 0xb53: 0x1859, 0xb54: 0x185e, 0xb55: 0x15db, 0xb56: 0x06bb, 0xb57: 0x15ef,
+ 0xb58: 0x15f7, 0xb59: 0x15fb, 0xb5a: 0x1603, 0xb5b: 0x160b, 0xb5c: 0x1613, 0xb5d: 0x1868,
+}
+
+// nfcIndex: 22 blocks, 1408 entries, 1408 bytes
+// Block 0 is the zero block.
+var nfcIndex = [1408]uint8{
+ // Block 0x0, offset 0x0
+ // Block 0x1, offset 0x40
+ // Block 0x2, offset 0x80
+ // Block 0x3, offset 0xc0
+ 0xc2: 0x2c, 0xc3: 0x01, 0xc4: 0x02, 0xc5: 0x03, 0xc6: 0x2d, 0xc7: 0x04,
+ 0xc8: 0x05, 0xca: 0x2e, 0xcb: 0x2f, 0xcc: 0x06, 0xcd: 0x07, 0xce: 0x08, 0xcf: 0x30,
+ 0xd0: 0x09, 0xd1: 0x31, 0xd2: 0x32, 0xd3: 0x0a, 0xd6: 0x0b, 0xd7: 0x33,
+ 0xd8: 0x34, 0xd9: 0x0c, 0xdb: 0x35, 0xdc: 0x36, 0xdd: 0x37, 0xdf: 0x38,
+ 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05,
+ 0xea: 0x06, 0xeb: 0x07, 0xec: 0x08, 0xed: 0x09, 0xef: 0x0a,
+ 0xf0: 0x13,
+ // Block 0x4, offset 0x100
+ 0x120: 0x39, 0x121: 0x3a, 0x123: 0x3b, 0x124: 0x3c, 0x125: 0x3d, 0x126: 0x3e, 0x127: 0x3f,
+ 0x128: 0x40, 0x129: 0x41, 0x12a: 0x42, 0x12b: 0x43, 0x12c: 0x3e, 0x12d: 0x44, 0x12e: 0x45, 0x12f: 0x46,
+ 0x131: 0x47, 0x132: 0x48, 0x133: 0x49, 0x134: 0x4a, 0x135: 0x4b, 0x137: 0x4c,
+ 0x138: 0x4d, 0x139: 0x4e, 0x13a: 0x4f, 0x13b: 0x50, 0x13c: 0x51, 0x13d: 0x52, 0x13e: 0x53, 0x13f: 0x54,
+ // Block 0x5, offset 0x140
+ 0x140: 0x55, 0x142: 0x56, 0x144: 0x57, 0x145: 0x58, 0x146: 0x59, 0x147: 0x5a,
+ 0x14d: 0x5b,
+ 0x15c: 0x5c, 0x15f: 0x5d,
+ 0x162: 0x5e, 0x164: 0x5f,
+ 0x168: 0x60, 0x169: 0x61, 0x16a: 0x62, 0x16c: 0x0d, 0x16d: 0x63, 0x16e: 0x64, 0x16f: 0x65,
+ 0x170: 0x66, 0x173: 0x67, 0x177: 0x68,
+ 0x178: 0x0e, 0x179: 0x0f, 0x17a: 0x10, 0x17b: 0x11, 0x17c: 0x12, 0x17d: 0x13, 0x17e: 0x14, 0x17f: 0x15,
+ // Block 0x6, offset 0x180
+ 0x180: 0x69, 0x183: 0x6a, 0x184: 0x6b, 0x186: 0x6c, 0x187: 0x6d,
+ 0x188: 0x6e, 0x189: 0x16, 0x18a: 0x17, 0x18b: 0x6f, 0x18c: 0x70,
+ 0x1ab: 0x71,
+ 0x1b3: 0x72, 0x1b5: 0x73, 0x1b7: 0x74,
+ // Block 0x7, offset 0x1c0
+ 0x1c0: 0x75, 0x1c1: 0x18, 0x1c2: 0x19, 0x1c3: 0x1a, 0x1c4: 0x76, 0x1c5: 0x77,
+ 0x1c9: 0x78, 0x1cc: 0x79, 0x1cd: 0x7a,
+ // Block 0x8, offset 0x200
+ 0x219: 0x7b, 0x21a: 0x7c, 0x21b: 0x7d,
+ 0x220: 0x7e, 0x223: 0x7f, 0x224: 0x80, 0x225: 0x81, 0x226: 0x82, 0x227: 0x83,
+ 0x22a: 0x84, 0x22b: 0x85, 0x22f: 0x86,
+ 0x230: 0x87, 0x231: 0x88, 0x232: 0x89, 0x233: 0x8a, 0x234: 0x8b, 0x235: 0x8c, 0x236: 0x8d, 0x237: 0x87,
+ 0x238: 0x88, 0x239: 0x89, 0x23a: 0x8a, 0x23b: 0x8b, 0x23c: 0x8c, 0x23d: 0x8d, 0x23e: 0x87, 0x23f: 0x88,
+ // Block 0x9, offset 0x240
+ 0x240: 0x89, 0x241: 0x8a, 0x242: 0x8b, 0x243: 0x8c, 0x244: 0x8d, 0x245: 0x87, 0x246: 0x88, 0x247: 0x89,
+ 0x248: 0x8a, 0x249: 0x8b, 0x24a: 0x8c, 0x24b: 0x8d, 0x24c: 0x87, 0x24d: 0x88, 0x24e: 0x89, 0x24f: 0x8a,
+ 0x250: 0x8b, 0x251: 0x8c, 0x252: 0x8d, 0x253: 0x87, 0x254: 0x88, 0x255: 0x89, 0x256: 0x8a, 0x257: 0x8b,
+ 0x258: 0x8c, 0x259: 0x8d, 0x25a: 0x87, 0x25b: 0x88, 0x25c: 0x89, 0x25d: 0x8a, 0x25e: 0x8b, 0x25f: 0x8c,
+ 0x260: 0x8d, 0x261: 0x87, 0x262: 0x88, 0x263: 0x89, 0x264: 0x8a, 0x265: 0x8b, 0x266: 0x8c, 0x267: 0x8d,
+ 0x268: 0x87, 0x269: 0x88, 0x26a: 0x89, 0x26b: 0x8a, 0x26c: 0x8b, 0x26d: 0x8c, 0x26e: 0x8d, 0x26f: 0x87,
+ 0x270: 0x88, 0x271: 0x89, 0x272: 0x8a, 0x273: 0x8b, 0x274: 0x8c, 0x275: 0x8d, 0x276: 0x87, 0x277: 0x88,
+ 0x278: 0x89, 0x279: 0x8a, 0x27a: 0x8b, 0x27b: 0x8c, 0x27c: 0x8d, 0x27d: 0x87, 0x27e: 0x88, 0x27f: 0x89,
+ // Block 0xa, offset 0x280
+ 0x280: 0x8a, 0x281: 0x8b, 0x282: 0x8c, 0x283: 0x8d, 0x284: 0x87, 0x285: 0x88, 0x286: 0x89, 0x287: 0x8a,
+ 0x288: 0x8b, 0x289: 0x8c, 0x28a: 0x8d, 0x28b: 0x87, 0x28c: 0x88, 0x28d: 0x89, 0x28e: 0x8a, 0x28f: 0x8b,
+ 0x290: 0x8c, 0x291: 0x8d, 0x292: 0x87, 0x293: 0x88, 0x294: 0x89, 0x295: 0x8a, 0x296: 0x8b, 0x297: 0x8c,
+ 0x298: 0x8d, 0x299: 0x87, 0x29a: 0x88, 0x29b: 0x89, 0x29c: 0x8a, 0x29d: 0x8b, 0x29e: 0x8c, 0x29f: 0x8d,
+ 0x2a0: 0x87, 0x2a1: 0x88, 0x2a2: 0x89, 0x2a3: 0x8a, 0x2a4: 0x8b, 0x2a5: 0x8c, 0x2a6: 0x8d, 0x2a7: 0x87,
+ 0x2a8: 0x88, 0x2a9: 0x89, 0x2aa: 0x8a, 0x2ab: 0x8b, 0x2ac: 0x8c, 0x2ad: 0x8d, 0x2ae: 0x87, 0x2af: 0x88,
+ 0x2b0: 0x89, 0x2b1: 0x8a, 0x2b2: 0x8b, 0x2b3: 0x8c, 0x2b4: 0x8d, 0x2b5: 0x87, 0x2b6: 0x88, 0x2b7: 0x89,
+ 0x2b8: 0x8a, 0x2b9: 0x8b, 0x2ba: 0x8c, 0x2bb: 0x8d, 0x2bc: 0x87, 0x2bd: 0x88, 0x2be: 0x89, 0x2bf: 0x8a,
+ // Block 0xb, offset 0x2c0
+ 0x2c0: 0x8b, 0x2c1: 0x8c, 0x2c2: 0x8d, 0x2c3: 0x87, 0x2c4: 0x88, 0x2c5: 0x89, 0x2c6: 0x8a, 0x2c7: 0x8b,
+ 0x2c8: 0x8c, 0x2c9: 0x8d, 0x2ca: 0x87, 0x2cb: 0x88, 0x2cc: 0x89, 0x2cd: 0x8a, 0x2ce: 0x8b, 0x2cf: 0x8c,
+ 0x2d0: 0x8d, 0x2d1: 0x87, 0x2d2: 0x88, 0x2d3: 0x89, 0x2d4: 0x8a, 0x2d5: 0x8b, 0x2d6: 0x8c, 0x2d7: 0x8d,
+ 0x2d8: 0x87, 0x2d9: 0x88, 0x2da: 0x89, 0x2db: 0x8a, 0x2dc: 0x8b, 0x2dd: 0x8c, 0x2de: 0x8e,
+ // Block 0xc, offset 0x300
+ 0x324: 0x1b, 0x325: 0x1c, 0x326: 0x1d, 0x327: 0x1e,
+ 0x328: 0x1f, 0x329: 0x20, 0x32a: 0x21, 0x32b: 0x22, 0x32c: 0x8f, 0x32d: 0x90, 0x32e: 0x91,
+ 0x331: 0x92, 0x332: 0x93, 0x333: 0x94, 0x334: 0x95,
+ 0x338: 0x96, 0x339: 0x97, 0x33a: 0x98, 0x33b: 0x99, 0x33e: 0x9a, 0x33f: 0x9b,
+ // Block 0xd, offset 0x340
+ 0x347: 0x9c,
+ 0x34b: 0x9d, 0x34d: 0x9e,
+ 0x368: 0x9f, 0x36b: 0xa0,
+ // Block 0xe, offset 0x380
+ 0x381: 0xa1, 0x382: 0xa2, 0x384: 0xa3, 0x385: 0x82, 0x387: 0xa4,
+ 0x388: 0xa5, 0x38b: 0xa6, 0x38c: 0x3e, 0x38d: 0xa7,
+ 0x391: 0xa8, 0x392: 0xa9, 0x393: 0xaa, 0x396: 0xab, 0x397: 0xac,
+ 0x398: 0x73, 0x39a: 0xad, 0x39c: 0xae,
+ 0x3b0: 0x73,
+ // Block 0xf, offset 0x3c0
+ 0x3eb: 0xaf, 0x3ec: 0xb0,
+ // Block 0x10, offset 0x400
+ 0x432: 0xb1,
+ // Block 0x11, offset 0x440
+ 0x445: 0xb2, 0x446: 0xb3, 0x447: 0xb4,
+ 0x449: 0xb5,
+ // Block 0x12, offset 0x480
+ 0x480: 0xb6,
+ 0x4a3: 0xb7, 0x4a5: 0xb8,
+ // Block 0x13, offset 0x4c0
+ 0x4c8: 0xb9,
+ // Block 0x14, offset 0x500
+ 0x520: 0x23, 0x521: 0x24, 0x522: 0x25, 0x523: 0x26, 0x524: 0x27, 0x525: 0x28, 0x526: 0x29, 0x527: 0x2a,
+ 0x528: 0x2b,
+ // Block 0x15, offset 0x540
+ 0x550: 0x0b, 0x551: 0x0c, 0x556: 0x0d,
+ 0x55b: 0x0e, 0x55d: 0x0f, 0x55e: 0x10, 0x55f: 0x11,
+ 0x56f: 0x12,
+}
+
+// nfcSparseOffset: 142 entries, 284 bytes
+var nfcSparseOffset = []uint16{0x0, 0x5, 0x9, 0xb, 0xd, 0x18, 0x28, 0x2a, 0x2f, 0x3a, 0x49, 0x56, 0x5e, 0x62, 0x67, 0x69, 0x7a, 0x82, 0x89, 0x8c, 0x93, 0x97, 0x9b, 0x9d, 0x9f, 0xa8, 0xac, 0xb3, 0xb8, 0xbb, 0xc5, 0xc7, 0xce, 0xd6, 0xd9, 0xdb, 0xdd, 0xdf, 0xe4, 0xf5, 0x101, 0x103, 0x109, 0x10b, 0x10d, 0x10f, 0x111, 0x113, 0x115, 0x118, 0x11b, 0x11d, 0x120, 0x123, 0x127, 0x12c, 0x135, 0x137, 0x13a, 0x13c, 0x147, 0x157, 0x15b, 0x169, 0x16c, 0x172, 0x178, 0x183, 0x187, 0x189, 0x18b, 0x18d, 0x18f, 0x191, 0x197, 0x19b, 0x19d, 0x19f, 0x1a7, 0x1ab, 0x1ae, 0x1b0, 0x1b2, 0x1b4, 0x1b7, 0x1b9, 0x1bb, 0x1bd, 0x1bf, 0x1c5, 0x1c8, 0x1ca, 0x1d1, 0x1d7, 0x1dd, 0x1e5, 0x1eb, 0x1f1, 0x1f7, 0x1fb, 0x209, 0x212, 0x215, 0x218, 0x21a, 0x21d, 0x21f, 0x223, 0x228, 0x22a, 0x22c, 0x231, 0x237, 0x239, 0x23b, 0x23d, 0x243, 0x246, 0x249, 0x251, 0x258, 0x25b, 0x25e, 0x260, 0x268, 0x26b, 0x272, 0x275, 0x27b, 0x27d, 0x280, 0x282, 0x284, 0x286, 0x288, 0x295, 0x29f, 0x2a1, 0x2a3, 0x2a9, 0x2ab, 0x2ae}
+
+// nfcSparseValues: 688 entries, 2752 bytes
+var nfcSparseValues = [688]valueRange{
+ // Block 0x0, offset 0x0
+ {value: 0x0000, lo: 0x04},
+ {value: 0xa100, lo: 0xa8, hi: 0xa8},
+ {value: 0x8100, lo: 0xaf, hi: 0xaf},
+ {value: 0x8100, lo: 0xb4, hi: 0xb4},
+ {value: 0x8100, lo: 0xb8, hi: 0xb8},
+ // Block 0x1, offset 0x5
+ {value: 0x0091, lo: 0x03},
+ {value: 0x4778, lo: 0xa0, hi: 0xa1},
+ {value: 0x47aa, lo: 0xaf, hi: 0xb0},
+ {value: 0xa000, lo: 0xb7, hi: 0xb7},
+ // Block 0x2, offset 0x9
+ {value: 0x0000, lo: 0x01},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ // Block 0x3, offset 0xb
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8100, lo: 0x98, hi: 0x9d},
+ // Block 0x4, offset 0xd
+ {value: 0x0006, lo: 0x0a},
+ {value: 0xa000, lo: 0x81, hi: 0x81},
+ {value: 0xa000, lo: 0x85, hi: 0x85},
+ {value: 0xa000, lo: 0x89, hi: 0x89},
+ {value: 0x48d6, lo: 0x8a, hi: 0x8a},
+ {value: 0x48f4, lo: 0x8b, hi: 0x8b},
+ {value: 0x36c7, lo: 0x8c, hi: 0x8c},
+ {value: 0x36df, lo: 0x8d, hi: 0x8d},
+ {value: 0x490c, lo: 0x8e, hi: 0x8e},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ {value: 0x36fd, lo: 0x93, hi: 0x94},
+ // Block 0x5, offset 0x18
+ {value: 0x0000, lo: 0x0f},
+ {value: 0xa000, lo: 0x83, hi: 0x83},
+ {value: 0xa000, lo: 0x87, hi: 0x87},
+ {value: 0xa000, lo: 0x8b, hi: 0x8b},
+ {value: 0xa000, lo: 0x8d, hi: 0x8d},
+ {value: 0x37a5, lo: 0x90, hi: 0x90},
+ {value: 0x37b1, lo: 0x91, hi: 0x91},
+ {value: 0x379f, lo: 0x93, hi: 0x93},
+ {value: 0xa000, lo: 0x96, hi: 0x96},
+ {value: 0x3817, lo: 0x97, hi: 0x97},
+ {value: 0x37e1, lo: 0x9c, hi: 0x9c},
+ {value: 0x37c9, lo: 0x9d, hi: 0x9d},
+ {value: 0x37f3, lo: 0x9e, hi: 0x9e},
+ {value: 0xa000, lo: 0xb4, hi: 0xb5},
+ {value: 0x381d, lo: 0xb6, hi: 0xb6},
+ {value: 0x3823, lo: 0xb7, hi: 0xb7},
+ // Block 0x6, offset 0x28
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0x83, hi: 0x87},
+ // Block 0x7, offset 0x2a
+ {value: 0x0001, lo: 0x04},
+ {value: 0x8113, lo: 0x81, hi: 0x82},
+ {value: 0x8132, lo: 0x84, hi: 0x84},
+ {value: 0x812d, lo: 0x85, hi: 0x85},
+ {value: 0x810d, lo: 0x87, hi: 0x87},
+ // Block 0x8, offset 0x2f
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x8132, lo: 0x90, hi: 0x97},
+ {value: 0x8119, lo: 0x98, hi: 0x98},
+ {value: 0x811a, lo: 0x99, hi: 0x99},
+ {value: 0x811b, lo: 0x9a, hi: 0x9a},
+ {value: 0x3841, lo: 0xa2, hi: 0xa2},
+ {value: 0x3847, lo: 0xa3, hi: 0xa3},
+ {value: 0x3853, lo: 0xa4, hi: 0xa4},
+ {value: 0x384d, lo: 0xa5, hi: 0xa5},
+ {value: 0x3859, lo: 0xa6, hi: 0xa6},
+ {value: 0xa000, lo: 0xa7, hi: 0xa7},
+ // Block 0x9, offset 0x3a
+ {value: 0x0000, lo: 0x0e},
+ {value: 0x386b, lo: 0x80, hi: 0x80},
+ {value: 0xa000, lo: 0x81, hi: 0x81},
+ {value: 0x385f, lo: 0x82, hi: 0x82},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ {value: 0x3865, lo: 0x93, hi: 0x93},
+ {value: 0xa000, lo: 0x95, hi: 0x95},
+ {value: 0x8132, lo: 0x96, hi: 0x9c},
+ {value: 0x8132, lo: 0x9f, hi: 0xa2},
+ {value: 0x812d, lo: 0xa3, hi: 0xa3},
+ {value: 0x8132, lo: 0xa4, hi: 0xa4},
+ {value: 0x8132, lo: 0xa7, hi: 0xa8},
+ {value: 0x812d, lo: 0xaa, hi: 0xaa},
+ {value: 0x8132, lo: 0xab, hi: 0xac},
+ {value: 0x812d, lo: 0xad, hi: 0xad},
+ // Block 0xa, offset 0x49
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x811f, lo: 0x91, hi: 0x91},
+ {value: 0x8132, lo: 0xb0, hi: 0xb0},
+ {value: 0x812d, lo: 0xb1, hi: 0xb1},
+ {value: 0x8132, lo: 0xb2, hi: 0xb3},
+ {value: 0x812d, lo: 0xb4, hi: 0xb4},
+ {value: 0x8132, lo: 0xb5, hi: 0xb6},
+ {value: 0x812d, lo: 0xb7, hi: 0xb9},
+ {value: 0x8132, lo: 0xba, hi: 0xba},
+ {value: 0x812d, lo: 0xbb, hi: 0xbc},
+ {value: 0x8132, lo: 0xbd, hi: 0xbd},
+ {value: 0x812d, lo: 0xbe, hi: 0xbe},
+ {value: 0x8132, lo: 0xbf, hi: 0xbf},
+ // Block 0xb, offset 0x56
+ {value: 0x0005, lo: 0x07},
+ {value: 0x8132, lo: 0x80, hi: 0x80},
+ {value: 0x8132, lo: 0x81, hi: 0x81},
+ {value: 0x812d, lo: 0x82, hi: 0x83},
+ {value: 0x812d, lo: 0x84, hi: 0x85},
+ {value: 0x812d, lo: 0x86, hi: 0x87},
+ {value: 0x812d, lo: 0x88, hi: 0x89},
+ {value: 0x8132, lo: 0x8a, hi: 0x8a},
+ // Block 0xc, offset 0x5e
+ {value: 0x0000, lo: 0x03},
+ {value: 0x8132, lo: 0xab, hi: 0xb1},
+ {value: 0x812d, lo: 0xb2, hi: 0xb2},
+ {value: 0x8132, lo: 0xb3, hi: 0xb3},
+ // Block 0xd, offset 0x62
+ {value: 0x0000, lo: 0x04},
+ {value: 0x8132, lo: 0x96, hi: 0x99},
+ {value: 0x8132, lo: 0x9b, hi: 0xa3},
+ {value: 0x8132, lo: 0xa5, hi: 0xa7},
+ {value: 0x8132, lo: 0xa9, hi: 0xad},
+ // Block 0xe, offset 0x67
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0x99, hi: 0x9b},
+ // Block 0xf, offset 0x69
+ {value: 0x0000, lo: 0x10},
+ {value: 0x8132, lo: 0x94, hi: 0xa1},
+ {value: 0x812d, lo: 0xa3, hi: 0xa3},
+ {value: 0x8132, lo: 0xa4, hi: 0xa5},
+ {value: 0x812d, lo: 0xa6, hi: 0xa6},
+ {value: 0x8132, lo: 0xa7, hi: 0xa8},
+ {value: 0x812d, lo: 0xa9, hi: 0xa9},
+ {value: 0x8132, lo: 0xaa, hi: 0xac},
+ {value: 0x812d, lo: 0xad, hi: 0xaf},
+ {value: 0x8116, lo: 0xb0, hi: 0xb0},
+ {value: 0x8117, lo: 0xb1, hi: 0xb1},
+ {value: 0x8118, lo: 0xb2, hi: 0xb2},
+ {value: 0x8132, lo: 0xb3, hi: 0xb5},
+ {value: 0x812d, lo: 0xb6, hi: 0xb6},
+ {value: 0x8132, lo: 0xb7, hi: 0xb8},
+ {value: 0x812d, lo: 0xb9, hi: 0xba},
+ {value: 0x8132, lo: 0xbb, hi: 0xbf},
+ // Block 0x10, offset 0x7a
+ {value: 0x0000, lo: 0x07},
+ {value: 0xa000, lo: 0xa8, hi: 0xa8},
+ {value: 0x3ed8, lo: 0xa9, hi: 0xa9},
+ {value: 0xa000, lo: 0xb0, hi: 0xb0},
+ {value: 0x3ee0, lo: 0xb1, hi: 0xb1},
+ {value: 0xa000, lo: 0xb3, hi: 0xb3},
+ {value: 0x3ee8, lo: 0xb4, hi: 0xb4},
+ {value: 0x9902, lo: 0xbc, hi: 0xbc},
+ // Block 0x11, offset 0x82
+ {value: 0x0008, lo: 0x06},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x8132, lo: 0x91, hi: 0x91},
+ {value: 0x812d, lo: 0x92, hi: 0x92},
+ {value: 0x8132, lo: 0x93, hi: 0x93},
+ {value: 0x8132, lo: 0x94, hi: 0x94},
+ {value: 0x45b2, lo: 0x98, hi: 0x9f},
+ // Block 0x12, offset 0x89
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8102, lo: 0xbc, hi: 0xbc},
+ {value: 0x9900, lo: 0xbe, hi: 0xbe},
+ // Block 0x13, offset 0x8c
+ {value: 0x0008, lo: 0x06},
+ {value: 0xa000, lo: 0x87, hi: 0x87},
+ {value: 0x2c9e, lo: 0x8b, hi: 0x8c},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x97, hi: 0x97},
+ {value: 0x45f2, lo: 0x9c, hi: 0x9d},
+ {value: 0x4602, lo: 0x9f, hi: 0x9f},
+ // Block 0x14, offset 0x93
+ {value: 0x0000, lo: 0x03},
+ {value: 0x462a, lo: 0xb3, hi: 0xb3},
+ {value: 0x4632, lo: 0xb6, hi: 0xb6},
+ {value: 0x8102, lo: 0xbc, hi: 0xbc},
+ // Block 0x15, offset 0x97
+ {value: 0x0008, lo: 0x03},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x460a, lo: 0x99, hi: 0x9b},
+ {value: 0x4622, lo: 0x9e, hi: 0x9e},
+ // Block 0x16, offset 0x9b
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8102, lo: 0xbc, hi: 0xbc},
+ // Block 0x17, offset 0x9d
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ // Block 0x18, offset 0x9f
+ {value: 0x0000, lo: 0x08},
+ {value: 0xa000, lo: 0x87, hi: 0x87},
+ {value: 0x2cb6, lo: 0x88, hi: 0x88},
+ {value: 0x2cae, lo: 0x8b, hi: 0x8b},
+ {value: 0x2cbe, lo: 0x8c, hi: 0x8c},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x96, hi: 0x97},
+ {value: 0x463a, lo: 0x9c, hi: 0x9c},
+ {value: 0x4642, lo: 0x9d, hi: 0x9d},
+ // Block 0x19, offset 0xa8
+ {value: 0x0000, lo: 0x03},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ {value: 0x2cc6, lo: 0x94, hi: 0x94},
+ {value: 0x9900, lo: 0xbe, hi: 0xbe},
+ // Block 0x1a, offset 0xac
+ {value: 0x0000, lo: 0x06},
+ {value: 0xa000, lo: 0x86, hi: 0x87},
+ {value: 0x2cce, lo: 0x8a, hi: 0x8a},
+ {value: 0x2cde, lo: 0x8b, hi: 0x8b},
+ {value: 0x2cd6, lo: 0x8c, hi: 0x8c},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x97, hi: 0x97},
+ // Block 0x1b, offset 0xb3
+ {value: 0x1801, lo: 0x04},
+ {value: 0xa000, lo: 0x86, hi: 0x86},
+ {value: 0x3ef0, lo: 0x88, hi: 0x88},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x8120, lo: 0x95, hi: 0x96},
+ // Block 0x1c, offset 0xb8
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8102, lo: 0xbc, hi: 0xbc},
+ {value: 0xa000, lo: 0xbf, hi: 0xbf},
+ // Block 0x1d, offset 0xbb
+ {value: 0x0000, lo: 0x09},
+ {value: 0x2ce6, lo: 0x80, hi: 0x80},
+ {value: 0x9900, lo: 0x82, hi: 0x82},
+ {value: 0xa000, lo: 0x86, hi: 0x86},
+ {value: 0x2cee, lo: 0x87, hi: 0x87},
+ {value: 0x2cf6, lo: 0x88, hi: 0x88},
+ {value: 0x2f50, lo: 0x8a, hi: 0x8a},
+ {value: 0x2dd8, lo: 0x8b, hi: 0x8b},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x95, hi: 0x96},
+ // Block 0x1e, offset 0xc5
+ {value: 0x0000, lo: 0x01},
+ {value: 0x9900, lo: 0xbe, hi: 0xbe},
+ // Block 0x1f, offset 0xc7
+ {value: 0x0000, lo: 0x06},
+ {value: 0xa000, lo: 0x86, hi: 0x87},
+ {value: 0x2cfe, lo: 0x8a, hi: 0x8a},
+ {value: 0x2d0e, lo: 0x8b, hi: 0x8b},
+ {value: 0x2d06, lo: 0x8c, hi: 0x8c},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x97, hi: 0x97},
+ // Block 0x20, offset 0xce
+ {value: 0x6bea, lo: 0x07},
+ {value: 0x9904, lo: 0x8a, hi: 0x8a},
+ {value: 0x9900, lo: 0x8f, hi: 0x8f},
+ {value: 0xa000, lo: 0x99, hi: 0x99},
+ {value: 0x3ef8, lo: 0x9a, hi: 0x9a},
+ {value: 0x2f58, lo: 0x9c, hi: 0x9c},
+ {value: 0x2de3, lo: 0x9d, hi: 0x9d},
+ {value: 0x2d16, lo: 0x9e, hi: 0x9f},
+ // Block 0x21, offset 0xd6
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8122, lo: 0xb8, hi: 0xb9},
+ {value: 0x8104, lo: 0xba, hi: 0xba},
+ // Block 0x22, offset 0xd9
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8123, lo: 0x88, hi: 0x8b},
+ // Block 0x23, offset 0xdb
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8124, lo: 0xb8, hi: 0xb9},
+ // Block 0x24, offset 0xdd
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8125, lo: 0x88, hi: 0x8b},
+ // Block 0x25, offset 0xdf
+ {value: 0x0000, lo: 0x04},
+ {value: 0x812d, lo: 0x98, hi: 0x99},
+ {value: 0x812d, lo: 0xb5, hi: 0xb5},
+ {value: 0x812d, lo: 0xb7, hi: 0xb7},
+ {value: 0x812b, lo: 0xb9, hi: 0xb9},
+ // Block 0x26, offset 0xe4
+ {value: 0x0000, lo: 0x10},
+ {value: 0x2644, lo: 0x83, hi: 0x83},
+ {value: 0x264b, lo: 0x8d, hi: 0x8d},
+ {value: 0x2652, lo: 0x92, hi: 0x92},
+ {value: 0x2659, lo: 0x97, hi: 0x97},
+ {value: 0x2660, lo: 0x9c, hi: 0x9c},
+ {value: 0x263d, lo: 0xa9, hi: 0xa9},
+ {value: 0x8126, lo: 0xb1, hi: 0xb1},
+ {value: 0x8127, lo: 0xb2, hi: 0xb2},
+ {value: 0x4a66, lo: 0xb3, hi: 0xb3},
+ {value: 0x8128, lo: 0xb4, hi: 0xb4},
+ {value: 0x4a6f, lo: 0xb5, hi: 0xb5},
+ {value: 0x464a, lo: 0xb6, hi: 0xb6},
+ {value: 0x8200, lo: 0xb7, hi: 0xb7},
+ {value: 0x4652, lo: 0xb8, hi: 0xb8},
+ {value: 0x8200, lo: 0xb9, hi: 0xb9},
+ {value: 0x8127, lo: 0xba, hi: 0xbd},
+ // Block 0x27, offset 0xf5
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x8127, lo: 0x80, hi: 0x80},
+ {value: 0x4a78, lo: 0x81, hi: 0x81},
+ {value: 0x8132, lo: 0x82, hi: 0x83},
+ {value: 0x8104, lo: 0x84, hi: 0x84},
+ {value: 0x8132, lo: 0x86, hi: 0x87},
+ {value: 0x266e, lo: 0x93, hi: 0x93},
+ {value: 0x2675, lo: 0x9d, hi: 0x9d},
+ {value: 0x267c, lo: 0xa2, hi: 0xa2},
+ {value: 0x2683, lo: 0xa7, hi: 0xa7},
+ {value: 0x268a, lo: 0xac, hi: 0xac},
+ {value: 0x2667, lo: 0xb9, hi: 0xb9},
+ // Block 0x28, offset 0x101
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0x86, hi: 0x86},
+ // Block 0x29, offset 0x103
+ {value: 0x0000, lo: 0x05},
+ {value: 0xa000, lo: 0xa5, hi: 0xa5},
+ {value: 0x2d1e, lo: 0xa6, hi: 0xa6},
+ {value: 0x9900, lo: 0xae, hi: 0xae},
+ {value: 0x8102, lo: 0xb7, hi: 0xb7},
+ {value: 0x8104, lo: 0xb9, hi: 0xba},
+ // Block 0x2a, offset 0x109
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0x8d, hi: 0x8d},
+ // Block 0x2b, offset 0x10b
+ {value: 0x0000, lo: 0x01},
+ {value: 0xa000, lo: 0x80, hi: 0x92},
+ // Block 0x2c, offset 0x10d
+ {value: 0x0000, lo: 0x01},
+ {value: 0xb900, lo: 0xa1, hi: 0xb5},
+ // Block 0x2d, offset 0x10f
+ {value: 0x0000, lo: 0x01},
+ {value: 0x9900, lo: 0xa8, hi: 0xbf},
+ // Block 0x2e, offset 0x111
+ {value: 0x0000, lo: 0x01},
+ {value: 0x9900, lo: 0x80, hi: 0x82},
+ // Block 0x2f, offset 0x113
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0x9d, hi: 0x9f},
+ // Block 0x30, offset 0x115
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x94, hi: 0x94},
+ {value: 0x8104, lo: 0xb4, hi: 0xb4},
+ // Block 0x31, offset 0x118
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x92, hi: 0x92},
+ {value: 0x8132, lo: 0x9d, hi: 0x9d},
+ // Block 0x32, offset 0x11b
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8131, lo: 0xa9, hi: 0xa9},
+ // Block 0x33, offset 0x11d
+ {value: 0x0004, lo: 0x02},
+ {value: 0x812e, lo: 0xb9, hi: 0xba},
+ {value: 0x812d, lo: 0xbb, hi: 0xbb},
+ // Block 0x34, offset 0x120
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8132, lo: 0x97, hi: 0x97},
+ {value: 0x812d, lo: 0x98, hi: 0x98},
+ // Block 0x35, offset 0x123
+ {value: 0x0000, lo: 0x03},
+ {value: 0x8104, lo: 0xa0, hi: 0xa0},
+ {value: 0x8132, lo: 0xb5, hi: 0xbc},
+ {value: 0x812d, lo: 0xbf, hi: 0xbf},
+ // Block 0x36, offset 0x127
+ {value: 0x0000, lo: 0x04},
+ {value: 0x8132, lo: 0xb0, hi: 0xb4},
+ {value: 0x812d, lo: 0xb5, hi: 0xba},
+ {value: 0x8132, lo: 0xbb, hi: 0xbc},
+ {value: 0x812d, lo: 0xbd, hi: 0xbd},
+ // Block 0x37, offset 0x12c
+ {value: 0x0000, lo: 0x08},
+ {value: 0x2d66, lo: 0x80, hi: 0x80},
+ {value: 0x2d6e, lo: 0x81, hi: 0x81},
+ {value: 0xa000, lo: 0x82, hi: 0x82},
+ {value: 0x2d76, lo: 0x83, hi: 0x83},
+ {value: 0x8104, lo: 0x84, hi: 0x84},
+ {value: 0x8132, lo: 0xab, hi: 0xab},
+ {value: 0x812d, lo: 0xac, hi: 0xac},
+ {value: 0x8132, lo: 0xad, hi: 0xb3},
+ // Block 0x38, offset 0x135
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0xaa, hi: 0xab},
+ // Block 0x39, offset 0x137
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8102, lo: 0xa6, hi: 0xa6},
+ {value: 0x8104, lo: 0xb2, hi: 0xb3},
+ // Block 0x3a, offset 0x13a
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8102, lo: 0xb7, hi: 0xb7},
+ // Block 0x3b, offset 0x13c
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x8132, lo: 0x90, hi: 0x92},
+ {value: 0x8101, lo: 0x94, hi: 0x94},
+ {value: 0x812d, lo: 0x95, hi: 0x99},
+ {value: 0x8132, lo: 0x9a, hi: 0x9b},
+ {value: 0x812d, lo: 0x9c, hi: 0x9f},
+ {value: 0x8132, lo: 0xa0, hi: 0xa0},
+ {value: 0x8101, lo: 0xa2, hi: 0xa8},
+ {value: 0x812d, lo: 0xad, hi: 0xad},
+ {value: 0x8132, lo: 0xb4, hi: 0xb4},
+ {value: 0x8132, lo: 0xb8, hi: 0xb9},
+ // Block 0x3c, offset 0x147
+ {value: 0x0000, lo: 0x0f},
+ {value: 0x8132, lo: 0x80, hi: 0x81},
+ {value: 0x812d, lo: 0x82, hi: 0x82},
+ {value: 0x8132, lo: 0x83, hi: 0x89},
+ {value: 0x812d, lo: 0x8a, hi: 0x8a},
+ {value: 0x8132, lo: 0x8b, hi: 0x8c},
+ {value: 0x8135, lo: 0x8d, hi: 0x8d},
+ {value: 0x812a, lo: 0x8e, hi: 0x8e},
+ {value: 0x812d, lo: 0x8f, hi: 0x8f},
+ {value: 0x8129, lo: 0x90, hi: 0x90},
+ {value: 0x8132, lo: 0x91, hi: 0xb5},
+ {value: 0x8132, lo: 0xbb, hi: 0xbb},
+ {value: 0x8134, lo: 0xbc, hi: 0xbc},
+ {value: 0x812d, lo: 0xbd, hi: 0xbd},
+ {value: 0x8132, lo: 0xbe, hi: 0xbe},
+ {value: 0x812d, lo: 0xbf, hi: 0xbf},
+ // Block 0x3d, offset 0x157
+ {value: 0x0004, lo: 0x03},
+ {value: 0x0433, lo: 0x80, hi: 0x81},
+ {value: 0x8100, lo: 0x97, hi: 0x97},
+ {value: 0x8100, lo: 0xbe, hi: 0xbe},
+ // Block 0x3e, offset 0x15b
+ {value: 0x0000, lo: 0x0d},
+ {value: 0x8132, lo: 0x90, hi: 0x91},
+ {value: 0x8101, lo: 0x92, hi: 0x93},
+ {value: 0x8132, lo: 0x94, hi: 0x97},
+ {value: 0x8101, lo: 0x98, hi: 0x9a},
+ {value: 0x8132, lo: 0x9b, hi: 0x9c},
+ {value: 0x8132, lo: 0xa1, hi: 0xa1},
+ {value: 0x8101, lo: 0xa5, hi: 0xa6},
+ {value: 0x8132, lo: 0xa7, hi: 0xa7},
+ {value: 0x812d, lo: 0xa8, hi: 0xa8},
+ {value: 0x8132, lo: 0xa9, hi: 0xa9},
+ {value: 0x8101, lo: 0xaa, hi: 0xab},
+ {value: 0x812d, lo: 0xac, hi: 0xaf},
+ {value: 0x8132, lo: 0xb0, hi: 0xb0},
+ // Block 0x3f, offset 0x169
+ {value: 0x427b, lo: 0x02},
+ {value: 0x01b8, lo: 0xa6, hi: 0xa6},
+ {value: 0x0057, lo: 0xaa, hi: 0xab},
+ // Block 0x40, offset 0x16c
+ {value: 0x0007, lo: 0x05},
+ {value: 0xa000, lo: 0x90, hi: 0x90},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ {value: 0xa000, lo: 0x94, hi: 0x94},
+ {value: 0x3bb9, lo: 0x9a, hi: 0x9b},
+ {value: 0x3bc7, lo: 0xae, hi: 0xae},
+ // Block 0x41, offset 0x172
+ {value: 0x000e, lo: 0x05},
+ {value: 0x3bce, lo: 0x8d, hi: 0x8e},
+ {value: 0x3bd5, lo: 0x8f, hi: 0x8f},
+ {value: 0xa000, lo: 0x90, hi: 0x90},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ {value: 0xa000, lo: 0x94, hi: 0x94},
+ // Block 0x42, offset 0x178
+ {value: 0x6408, lo: 0x0a},
+ {value: 0xa000, lo: 0x83, hi: 0x83},
+ {value: 0x3be3, lo: 0x84, hi: 0x84},
+ {value: 0xa000, lo: 0x88, hi: 0x88},
+ {value: 0x3bea, lo: 0x89, hi: 0x89},
+ {value: 0xa000, lo: 0x8b, hi: 0x8b},
+ {value: 0x3bf1, lo: 0x8c, hi: 0x8c},
+ {value: 0xa000, lo: 0xa3, hi: 0xa3},
+ {value: 0x3bf8, lo: 0xa4, hi: 0xa5},
+ {value: 0x3bff, lo: 0xa6, hi: 0xa6},
+ {value: 0xa000, lo: 0xbc, hi: 0xbc},
+ // Block 0x43, offset 0x183
+ {value: 0x0007, lo: 0x03},
+ {value: 0x3c68, lo: 0xa0, hi: 0xa1},
+ {value: 0x3c92, lo: 0xa2, hi: 0xa3},
+ {value: 0x3cbc, lo: 0xaa, hi: 0xad},
+ // Block 0x44, offset 0x187
+ {value: 0x0004, lo: 0x01},
+ {value: 0x048b, lo: 0xa9, hi: 0xaa},
+ // Block 0x45, offset 0x189
+ {value: 0x0000, lo: 0x01},
+ {value: 0x4573, lo: 0x9c, hi: 0x9c},
+ // Block 0x46, offset 0x18b
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0xaf, hi: 0xb1},
+ // Block 0x47, offset 0x18d
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0xbf, hi: 0xbf},
+ // Block 0x48, offset 0x18f
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0xa0, hi: 0xbf},
+ // Block 0x49, offset 0x191
+ {value: 0x0000, lo: 0x05},
+ {value: 0x812c, lo: 0xaa, hi: 0xaa},
+ {value: 0x8131, lo: 0xab, hi: 0xab},
+ {value: 0x8133, lo: 0xac, hi: 0xac},
+ {value: 0x812e, lo: 0xad, hi: 0xad},
+ {value: 0x812f, lo: 0xae, hi: 0xaf},
+ // Block 0x4a, offset 0x197
+ {value: 0x0000, lo: 0x03},
+ {value: 0x4a81, lo: 0xb3, hi: 0xb3},
+ {value: 0x4a81, lo: 0xb5, hi: 0xb6},
+ {value: 0x4a81, lo: 0xba, hi: 0xbf},
+ // Block 0x4b, offset 0x19b
+ {value: 0x0000, lo: 0x01},
+ {value: 0x4a81, lo: 0x8f, hi: 0xa3},
+ // Block 0x4c, offset 0x19d
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8100, lo: 0xae, hi: 0xbe},
+ // Block 0x4d, offset 0x19f
+ {value: 0x0000, lo: 0x07},
+ {value: 0x8100, lo: 0x84, hi: 0x84},
+ {value: 0x8100, lo: 0x87, hi: 0x87},
+ {value: 0x8100, lo: 0x90, hi: 0x90},
+ {value: 0x8100, lo: 0x9e, hi: 0x9e},
+ {value: 0x8100, lo: 0xa1, hi: 0xa1},
+ {value: 0x8100, lo: 0xb2, hi: 0xb2},
+ {value: 0x8100, lo: 0xbb, hi: 0xbb},
+ // Block 0x4e, offset 0x1a7
+ {value: 0x0000, lo: 0x03},
+ {value: 0x8100, lo: 0x80, hi: 0x80},
+ {value: 0x8100, lo: 0x8b, hi: 0x8b},
+ {value: 0x8100, lo: 0x8e, hi: 0x8e},
+ // Block 0x4f, offset 0x1ab
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8132, lo: 0xaf, hi: 0xaf},
+ {value: 0x8132, lo: 0xb4, hi: 0xbd},
+ // Block 0x50, offset 0x1ae
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0x9e, hi: 0x9f},
+ // Block 0x51, offset 0x1b0
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0xb0, hi: 0xb1},
+ // Block 0x52, offset 0x1b2
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0x86, hi: 0x86},
+ // Block 0x53, offset 0x1b4
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x84, hi: 0x84},
+ {value: 0x8132, lo: 0xa0, hi: 0xb1},
+ // Block 0x54, offset 0x1b7
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0xab, hi: 0xad},
+ // Block 0x55, offset 0x1b9
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0x93, hi: 0x93},
+ // Block 0x56, offset 0x1bb
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8102, lo: 0xb3, hi: 0xb3},
+ // Block 0x57, offset 0x1bd
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0x80, hi: 0x80},
+ // Block 0x58, offset 0x1bf
+ {value: 0x0000, lo: 0x05},
+ {value: 0x8132, lo: 0xb0, hi: 0xb0},
+ {value: 0x8132, lo: 0xb2, hi: 0xb3},
+ {value: 0x812d, lo: 0xb4, hi: 0xb4},
+ {value: 0x8132, lo: 0xb7, hi: 0xb8},
+ {value: 0x8132, lo: 0xbe, hi: 0xbf},
+ // Block 0x59, offset 0x1c5
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8132, lo: 0x81, hi: 0x81},
+ {value: 0x8104, lo: 0xb6, hi: 0xb6},
+ // Block 0x5a, offset 0x1c8
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0xad, hi: 0xad},
+ // Block 0x5b, offset 0x1ca
+ {value: 0x0000, lo: 0x06},
+ {value: 0xe500, lo: 0x80, hi: 0x80},
+ {value: 0xc600, lo: 0x81, hi: 0x9b},
+ {value: 0xe500, lo: 0x9c, hi: 0x9c},
+ {value: 0xc600, lo: 0x9d, hi: 0xb7},
+ {value: 0xe500, lo: 0xb8, hi: 0xb8},
+ {value: 0xc600, lo: 0xb9, hi: 0xbf},
+ // Block 0x5c, offset 0x1d1
+ {value: 0x0000, lo: 0x05},
+ {value: 0xc600, lo: 0x80, hi: 0x93},
+ {value: 0xe500, lo: 0x94, hi: 0x94},
+ {value: 0xc600, lo: 0x95, hi: 0xaf},
+ {value: 0xe500, lo: 0xb0, hi: 0xb0},
+ {value: 0xc600, lo: 0xb1, hi: 0xbf},
+ // Block 0x5d, offset 0x1d7
+ {value: 0x0000, lo: 0x05},
+ {value: 0xc600, lo: 0x80, hi: 0x8b},
+ {value: 0xe500, lo: 0x8c, hi: 0x8c},
+ {value: 0xc600, lo: 0x8d, hi: 0xa7},
+ {value: 0xe500, lo: 0xa8, hi: 0xa8},
+ {value: 0xc600, lo: 0xa9, hi: 0xbf},
+ // Block 0x5e, offset 0x1dd
+ {value: 0x0000, lo: 0x07},
+ {value: 0xc600, lo: 0x80, hi: 0x83},
+ {value: 0xe500, lo: 0x84, hi: 0x84},
+ {value: 0xc600, lo: 0x85, hi: 0x9f},
+ {value: 0xe500, lo: 0xa0, hi: 0xa0},
+ {value: 0xc600, lo: 0xa1, hi: 0xbb},
+ {value: 0xe500, lo: 0xbc, hi: 0xbc},
+ {value: 0xc600, lo: 0xbd, hi: 0xbf},
+ // Block 0x5f, offset 0x1e5
+ {value: 0x0000, lo: 0x05},
+ {value: 0xc600, lo: 0x80, hi: 0x97},
+ {value: 0xe500, lo: 0x98, hi: 0x98},
+ {value: 0xc600, lo: 0x99, hi: 0xb3},
+ {value: 0xe500, lo: 0xb4, hi: 0xb4},
+ {value: 0xc600, lo: 0xb5, hi: 0xbf},
+ // Block 0x60, offset 0x1eb
+ {value: 0x0000, lo: 0x05},
+ {value: 0xc600, lo: 0x80, hi: 0x8f},
+ {value: 0xe500, lo: 0x90, hi: 0x90},
+ {value: 0xc600, lo: 0x91, hi: 0xab},
+ {value: 0xe500, lo: 0xac, hi: 0xac},
+ {value: 0xc600, lo: 0xad, hi: 0xbf},
+ // Block 0x61, offset 0x1f1
+ {value: 0x0000, lo: 0x05},
+ {value: 0xc600, lo: 0x80, hi: 0x87},
+ {value: 0xe500, lo: 0x88, hi: 0x88},
+ {value: 0xc600, lo: 0x89, hi: 0xa3},
+ {value: 0xe500, lo: 0xa4, hi: 0xa4},
+ {value: 0xc600, lo: 0xa5, hi: 0xbf},
+ // Block 0x62, offset 0x1f7
+ {value: 0x0000, lo: 0x03},
+ {value: 0xc600, lo: 0x80, hi: 0x87},
+ {value: 0xe500, lo: 0x88, hi: 0x88},
+ {value: 0xc600, lo: 0x89, hi: 0xa3},
+ // Block 0x63, offset 0x1fb
+ {value: 0x0006, lo: 0x0d},
+ {value: 0x4426, lo: 0x9d, hi: 0x9d},
+ {value: 0x8115, lo: 0x9e, hi: 0x9e},
+ {value: 0x4498, lo: 0x9f, hi: 0x9f},
+ {value: 0x4486, lo: 0xaa, hi: 0xab},
+ {value: 0x458a, lo: 0xac, hi: 0xac},
+ {value: 0x4592, lo: 0xad, hi: 0xad},
+ {value: 0x43de, lo: 0xae, hi: 0xb1},
+ {value: 0x43fc, lo: 0xb2, hi: 0xb4},
+ {value: 0x4414, lo: 0xb5, hi: 0xb6},
+ {value: 0x4420, lo: 0xb8, hi: 0xb8},
+ {value: 0x442c, lo: 0xb9, hi: 0xbb},
+ {value: 0x4444, lo: 0xbc, hi: 0xbc},
+ {value: 0x444a, lo: 0xbe, hi: 0xbe},
+ // Block 0x64, offset 0x209
+ {value: 0x0006, lo: 0x08},
+ {value: 0x4450, lo: 0x80, hi: 0x81},
+ {value: 0x445c, lo: 0x83, hi: 0x84},
+ {value: 0x446e, lo: 0x86, hi: 0x89},
+ {value: 0x4492, lo: 0x8a, hi: 0x8a},
+ {value: 0x440e, lo: 0x8b, hi: 0x8b},
+ {value: 0x43f6, lo: 0x8c, hi: 0x8c},
+ {value: 0x443e, lo: 0x8d, hi: 0x8d},
+ {value: 0x4468, lo: 0x8e, hi: 0x8e},
+ // Block 0x65, offset 0x212
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8100, lo: 0xa4, hi: 0xa5},
+ {value: 0x8100, lo: 0xb0, hi: 0xb1},
+ // Block 0x66, offset 0x215
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8100, lo: 0x9b, hi: 0x9d},
+ {value: 0x8200, lo: 0x9e, hi: 0xa3},
+ // Block 0x67, offset 0x218
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8100, lo: 0x90, hi: 0x90},
+ // Block 0x68, offset 0x21a
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8100, lo: 0x99, hi: 0x99},
+ {value: 0x8200, lo: 0xb2, hi: 0xb4},
+ // Block 0x69, offset 0x21d
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8100, lo: 0xbc, hi: 0xbd},
+ // Block 0x6a, offset 0x21f
+ {value: 0x0000, lo: 0x03},
+ {value: 0x8132, lo: 0xa0, hi: 0xa6},
+ {value: 0x812d, lo: 0xa7, hi: 0xad},
+ {value: 0x8132, lo: 0xae, hi: 0xaf},
+ // Block 0x6b, offset 0x223
+ {value: 0x0000, lo: 0x04},
+ {value: 0x8100, lo: 0x89, hi: 0x8c},
+ {value: 0x8100, lo: 0xb0, hi: 0xb2},
+ {value: 0x8100, lo: 0xb4, hi: 0xb4},
+ {value: 0x8100, lo: 0xb6, hi: 0xbf},
+ // Block 0x6c, offset 0x228
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8100, lo: 0x81, hi: 0x8c},
+ // Block 0x6d, offset 0x22a
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8100, lo: 0xb5, hi: 0xba},
+ // Block 0x6e, offset 0x22c
+ {value: 0x0000, lo: 0x04},
+ {value: 0x4a81, lo: 0x9e, hi: 0x9f},
+ {value: 0x4a81, lo: 0xa3, hi: 0xa3},
+ {value: 0x4a81, lo: 0xa5, hi: 0xa6},
+ {value: 0x4a81, lo: 0xaa, hi: 0xaf},
+ // Block 0x6f, offset 0x231
+ {value: 0x0000, lo: 0x05},
+ {value: 0x4a81, lo: 0x82, hi: 0x87},
+ {value: 0x4a81, lo: 0x8a, hi: 0x8f},
+ {value: 0x4a81, lo: 0x92, hi: 0x97},
+ {value: 0x4a81, lo: 0x9a, hi: 0x9c},
+ {value: 0x8100, lo: 0xa3, hi: 0xa3},
+ // Block 0x70, offset 0x237
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0xbd, hi: 0xbd},
+ // Block 0x71, offset 0x239
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0xa0, hi: 0xa0},
+ // Block 0x72, offset 0x23b
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0xb6, hi: 0xba},
+ // Block 0x73, offset 0x23d
+ {value: 0x002c, lo: 0x05},
+ {value: 0x812d, lo: 0x8d, hi: 0x8d},
+ {value: 0x8132, lo: 0x8f, hi: 0x8f},
+ {value: 0x8132, lo: 0xb8, hi: 0xb8},
+ {value: 0x8101, lo: 0xb9, hi: 0xba},
+ {value: 0x8104, lo: 0xbf, hi: 0xbf},
+ // Block 0x74, offset 0x243
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8132, lo: 0xa5, hi: 0xa5},
+ {value: 0x812d, lo: 0xa6, hi: 0xa6},
+ // Block 0x75, offset 0x246
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x86, hi: 0x86},
+ {value: 0x8104, lo: 0xbf, hi: 0xbf},
+ // Block 0x76, offset 0x249
+ {value: 0x17fe, lo: 0x07},
+ {value: 0xa000, lo: 0x99, hi: 0x99},
+ {value: 0x4238, lo: 0x9a, hi: 0x9a},
+ {value: 0xa000, lo: 0x9b, hi: 0x9b},
+ {value: 0x4242, lo: 0x9c, hi: 0x9c},
+ {value: 0xa000, lo: 0xa5, hi: 0xa5},
+ {value: 0x424c, lo: 0xab, hi: 0xab},
+ {value: 0x8104, lo: 0xb9, hi: 0xba},
+ // Block 0x77, offset 0x251
+ {value: 0x0000, lo: 0x06},
+ {value: 0x8132, lo: 0x80, hi: 0x82},
+ {value: 0x9900, lo: 0xa7, hi: 0xa7},
+ {value: 0x2d7e, lo: 0xae, hi: 0xae},
+ {value: 0x2d88, lo: 0xaf, hi: 0xaf},
+ {value: 0xa000, lo: 0xb1, hi: 0xb2},
+ {value: 0x8104, lo: 0xb3, hi: 0xb4},
+ // Block 0x78, offset 0x258
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x80, hi: 0x80},
+ {value: 0x8102, lo: 0x8a, hi: 0x8a},
+ // Block 0x79, offset 0x25b
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0xb5, hi: 0xb5},
+ {value: 0x8102, lo: 0xb6, hi: 0xb6},
+ // Block 0x7a, offset 0x25e
+ {value: 0x0002, lo: 0x01},
+ {value: 0x8102, lo: 0xa9, hi: 0xaa},
+ // Block 0x7b, offset 0x260
+ {value: 0x0000, lo: 0x07},
+ {value: 0xa000, lo: 0x87, hi: 0x87},
+ {value: 0x2d92, lo: 0x8b, hi: 0x8b},
+ {value: 0x2d9c, lo: 0x8c, hi: 0x8c},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x97, hi: 0x97},
+ {value: 0x8132, lo: 0xa6, hi: 0xac},
+ {value: 0x8132, lo: 0xb0, hi: 0xb4},
+ // Block 0x7c, offset 0x268
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x82, hi: 0x82},
+ {value: 0x8102, lo: 0x86, hi: 0x86},
+ // Block 0x7d, offset 0x26b
+ {value: 0x6b5a, lo: 0x06},
+ {value: 0x9900, lo: 0xb0, hi: 0xb0},
+ {value: 0xa000, lo: 0xb9, hi: 0xb9},
+ {value: 0x9900, lo: 0xba, hi: 0xba},
+ {value: 0x2db0, lo: 0xbb, hi: 0xbb},
+ {value: 0x2da6, lo: 0xbc, hi: 0xbd},
+ {value: 0x2dba, lo: 0xbe, hi: 0xbe},
+ // Block 0x7e, offset 0x272
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x82, hi: 0x82},
+ {value: 0x8102, lo: 0x83, hi: 0x83},
+ // Block 0x7f, offset 0x275
+ {value: 0x0000, lo: 0x05},
+ {value: 0x9900, lo: 0xaf, hi: 0xaf},
+ {value: 0xa000, lo: 0xb8, hi: 0xb9},
+ {value: 0x2dc4, lo: 0xba, hi: 0xba},
+ {value: 0x2dce, lo: 0xbb, hi: 0xbb},
+ {value: 0x8104, lo: 0xbf, hi: 0xbf},
+ // Block 0x80, offset 0x27b
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8102, lo: 0x80, hi: 0x80},
+ // Block 0x81, offset 0x27d
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0xb6, hi: 0xb6},
+ {value: 0x8102, lo: 0xb7, hi: 0xb7},
+ // Block 0x82, offset 0x280
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0xab, hi: 0xab},
+ // Block 0x83, offset 0x282
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8101, lo: 0xb0, hi: 0xb4},
+ // Block 0x84, offset 0x284
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0xb0, hi: 0xb6},
+ // Block 0x85, offset 0x286
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8101, lo: 0x9e, hi: 0x9e},
+ // Block 0x86, offset 0x288
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x4662, lo: 0x9e, hi: 0x9e},
+ {value: 0x466c, lo: 0x9f, hi: 0x9f},
+ {value: 0x46a0, lo: 0xa0, hi: 0xa0},
+ {value: 0x46ae, lo: 0xa1, hi: 0xa1},
+ {value: 0x46bc, lo: 0xa2, hi: 0xa2},
+ {value: 0x46ca, lo: 0xa3, hi: 0xa3},
+ {value: 0x46d8, lo: 0xa4, hi: 0xa4},
+ {value: 0x812b, lo: 0xa5, hi: 0xa6},
+ {value: 0x8101, lo: 0xa7, hi: 0xa9},
+ {value: 0x8130, lo: 0xad, hi: 0xad},
+ {value: 0x812b, lo: 0xae, hi: 0xb2},
+ {value: 0x812d, lo: 0xbb, hi: 0xbf},
+ // Block 0x87, offset 0x295
+ {value: 0x0000, lo: 0x09},
+ {value: 0x812d, lo: 0x80, hi: 0x82},
+ {value: 0x8132, lo: 0x85, hi: 0x89},
+ {value: 0x812d, lo: 0x8a, hi: 0x8b},
+ {value: 0x8132, lo: 0xaa, hi: 0xad},
+ {value: 0x4676, lo: 0xbb, hi: 0xbb},
+ {value: 0x4680, lo: 0xbc, hi: 0xbc},
+ {value: 0x46e6, lo: 0xbd, hi: 0xbd},
+ {value: 0x4702, lo: 0xbe, hi: 0xbe},
+ {value: 0x46f4, lo: 0xbf, hi: 0xbf},
+ // Block 0x88, offset 0x29f
+ {value: 0x0000, lo: 0x01},
+ {value: 0x4710, lo: 0x80, hi: 0x80},
+ // Block 0x89, offset 0x2a1
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0x82, hi: 0x84},
+ // Block 0x8a, offset 0x2a3
+ {value: 0x0000, lo: 0x05},
+ {value: 0x8132, lo: 0x80, hi: 0x86},
+ {value: 0x8132, lo: 0x88, hi: 0x98},
+ {value: 0x8132, lo: 0x9b, hi: 0xa1},
+ {value: 0x8132, lo: 0xa3, hi: 0xa4},
+ {value: 0x8132, lo: 0xa6, hi: 0xaa},
+ // Block 0x8b, offset 0x2a9
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0x90, hi: 0x96},
+ // Block 0x8c, offset 0x2ab
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8132, lo: 0x84, hi: 0x89},
+ {value: 0x8102, lo: 0x8a, hi: 0x8a},
+ // Block 0x8d, offset 0x2ae
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8100, lo: 0x93, hi: 0x93},
+}
+
+// lookup returns the trie value for the first UTF-8 encoding in s and
+// the width in bytes of this encoding. The size will be 0 if s does not
+// hold enough bytes to complete the encoding. len(s) must be greater than 0.
+func (t *nfkcTrie) lookup(s []byte) (v uint16, sz int) {
+ c0 := s[0]
+ switch {
+ case c0 < 0x80: // is ASCII
+ return nfkcValues[c0], 1
+ case c0 < 0xC2:
+ return 0, 1 // Illegal UTF-8: not a starter, not ASCII.
+ case c0 < 0xE0: // 2-byte UTF-8
+ if len(s) < 2 {
+ return 0, 0
+ }
+ i := nfkcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c1), 2
+ case c0 < 0xF0: // 3-byte UTF-8
+ if len(s) < 3 {
+ return 0, 0
+ }
+ i := nfkcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = nfkcIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c2), 3
+ case c0 < 0xF8: // 4-byte UTF-8
+ if len(s) < 4 {
+ return 0, 0
+ }
+ i := nfkcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = nfkcIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ o = uint32(i)<<6 + uint32(c2)
+ i = nfkcIndex[o]
+ c3 := s[3]
+ if c3 < 0x80 || 0xC0 <= c3 {
+ return 0, 3 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c3), 4
+ }
+ // Illegal rune
+ return 0, 1
+}
+
+// lookupUnsafe returns the trie value for the first UTF-8 encoding in s.
+// s must start with a full and valid UTF-8 encoded rune.
+func (t *nfkcTrie) lookupUnsafe(s []byte) uint16 {
+ c0 := s[0]
+ if c0 < 0x80 { // is ASCII
+ return nfkcValues[c0]
+ }
+ i := nfkcIndex[c0]
+ if c0 < 0xE0 { // 2-byte UTF-8
+ return t.lookupValue(uint32(i), s[1])
+ }
+ i = nfkcIndex[uint32(i)<<6+uint32(s[1])]
+ if c0 < 0xF0 { // 3-byte UTF-8
+ return t.lookupValue(uint32(i), s[2])
+ }
+ i = nfkcIndex[uint32(i)<<6+uint32(s[2])]
+ if c0 < 0xF8 { // 4-byte UTF-8
+ return t.lookupValue(uint32(i), s[3])
+ }
+ return 0
+}
+
+// lookupString returns the trie value for the first UTF-8 encoding in s and
+// the width in bytes of this encoding. The size will be 0 if s does not
+// hold enough bytes to complete the encoding. len(s) must be greater than 0.
+func (t *nfkcTrie) lookupString(s string) (v uint16, sz int) {
+ c0 := s[0]
+ switch {
+ case c0 < 0x80: // is ASCII
+ return nfkcValues[c0], 1
+ case c0 < 0xC2:
+ return 0, 1 // Illegal UTF-8: not a starter, not ASCII.
+ case c0 < 0xE0: // 2-byte UTF-8
+ if len(s) < 2 {
+ return 0, 0
+ }
+ i := nfkcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c1), 2
+ case c0 < 0xF0: // 3-byte UTF-8
+ if len(s) < 3 {
+ return 0, 0
+ }
+ i := nfkcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = nfkcIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c2), 3
+ case c0 < 0xF8: // 4-byte UTF-8
+ if len(s) < 4 {
+ return 0, 0
+ }
+ i := nfkcIndex[c0]
+ c1 := s[1]
+ if c1 < 0x80 || 0xC0 <= c1 {
+ return 0, 1 // Illegal UTF-8: not a continuation byte.
+ }
+ o := uint32(i)<<6 + uint32(c1)
+ i = nfkcIndex[o]
+ c2 := s[2]
+ if c2 < 0x80 || 0xC0 <= c2 {
+ return 0, 2 // Illegal UTF-8: not a continuation byte.
+ }
+ o = uint32(i)<<6 + uint32(c2)
+ i = nfkcIndex[o]
+ c3 := s[3]
+ if c3 < 0x80 || 0xC0 <= c3 {
+ return 0, 3 // Illegal UTF-8: not a continuation byte.
+ }
+ return t.lookupValue(uint32(i), c3), 4
+ }
+ // Illegal rune
+ return 0, 1
+}
+
+// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s.
+// s must start with a full and valid UTF-8 encoded rune.
+func (t *nfkcTrie) lookupStringUnsafe(s string) uint16 {
+ c0 := s[0]
+ if c0 < 0x80 { // is ASCII
+ return nfkcValues[c0]
+ }
+ i := nfkcIndex[c0]
+ if c0 < 0xE0 { // 2-byte UTF-8
+ return t.lookupValue(uint32(i), s[1])
+ }
+ i = nfkcIndex[uint32(i)<<6+uint32(s[1])]
+ if c0 < 0xF0 { // 3-byte UTF-8
+ return t.lookupValue(uint32(i), s[2])
+ }
+ i = nfkcIndex[uint32(i)<<6+uint32(s[2])]
+ if c0 < 0xF8 { // 4-byte UTF-8
+ return t.lookupValue(uint32(i), s[3])
+ }
+ return 0
+}
+
+// nfkcTrie. Total size: 16994 bytes (16.60 KiB). Checksum: 146925fc21092b17.
+type nfkcTrie struct{}
+
+func newNfkcTrie(i int) *nfkcTrie {
+ return &nfkcTrie{}
+}
+
+// lookupValue determines the type of block n and looks up the value for b.
+func (t *nfkcTrie) lookupValue(n uint32, b byte) uint16 {
+ switch {
+ case n < 90:
+ return uint16(nfkcValues[n<<6+uint32(b)])
+ default:
+ n -= 90
+ return uint16(nfkcSparse.lookup(n, b))
+ }
+}
+
+// nfkcValues: 92 blocks, 5888 entries, 11776 bytes
+// The third block is the zero block.
+var nfkcValues = [5888]uint16{
+ // Block 0x0, offset 0x0
+ 0x3c: 0xa000, 0x3d: 0xa000, 0x3e: 0xa000,
+ // Block 0x1, offset 0x40
+ 0x41: 0xa000, 0x42: 0xa000, 0x43: 0xa000, 0x44: 0xa000, 0x45: 0xa000,
+ 0x46: 0xa000, 0x47: 0xa000, 0x48: 0xa000, 0x49: 0xa000, 0x4a: 0xa000, 0x4b: 0xa000,
+ 0x4c: 0xa000, 0x4d: 0xa000, 0x4e: 0xa000, 0x4f: 0xa000, 0x50: 0xa000,
+ 0x52: 0xa000, 0x53: 0xa000, 0x54: 0xa000, 0x55: 0xa000, 0x56: 0xa000, 0x57: 0xa000,
+ 0x58: 0xa000, 0x59: 0xa000, 0x5a: 0xa000,
+ 0x61: 0xa000, 0x62: 0xa000, 0x63: 0xa000,
+ 0x64: 0xa000, 0x65: 0xa000, 0x66: 0xa000, 0x67: 0xa000, 0x68: 0xa000, 0x69: 0xa000,
+ 0x6a: 0xa000, 0x6b: 0xa000, 0x6c: 0xa000, 0x6d: 0xa000, 0x6e: 0xa000, 0x6f: 0xa000,
+ 0x70: 0xa000, 0x72: 0xa000, 0x73: 0xa000, 0x74: 0xa000, 0x75: 0xa000,
+ 0x76: 0xa000, 0x77: 0xa000, 0x78: 0xa000, 0x79: 0xa000, 0x7a: 0xa000,
+ // Block 0x2, offset 0x80
+ // Block 0x3, offset 0xc0
+ 0xc0: 0x2f6f, 0xc1: 0x2f74, 0xc2: 0x471e, 0xc3: 0x2f79, 0xc4: 0x472d, 0xc5: 0x4732,
+ 0xc6: 0xa000, 0xc7: 0x473c, 0xc8: 0x2fe2, 0xc9: 0x2fe7, 0xca: 0x4741, 0xcb: 0x2ffb,
+ 0xcc: 0x306e, 0xcd: 0x3073, 0xce: 0x3078, 0xcf: 0x4755, 0xd1: 0x3104,
+ 0xd2: 0x3127, 0xd3: 0x312c, 0xd4: 0x475f, 0xd5: 0x4764, 0xd6: 0x4773,
+ 0xd8: 0xa000, 0xd9: 0x31b3, 0xda: 0x31b8, 0xdb: 0x31bd, 0xdc: 0x47a5, 0xdd: 0x3235,
+ 0xe0: 0x327b, 0xe1: 0x3280, 0xe2: 0x47af, 0xe3: 0x3285,
+ 0xe4: 0x47be, 0xe5: 0x47c3, 0xe6: 0xa000, 0xe7: 0x47cd, 0xe8: 0x32ee, 0xe9: 0x32f3,
+ 0xea: 0x47d2, 0xeb: 0x3307, 0xec: 0x337f, 0xed: 0x3384, 0xee: 0x3389, 0xef: 0x47e6,
+ 0xf1: 0x3415, 0xf2: 0x3438, 0xf3: 0x343d, 0xf4: 0x47f0, 0xf5: 0x47f5,
+ 0xf6: 0x4804, 0xf8: 0xa000, 0xf9: 0x34c9, 0xfa: 0x34ce, 0xfb: 0x34d3,
+ 0xfc: 0x4836, 0xfd: 0x3550, 0xff: 0x3569,
+ // Block 0x4, offset 0x100
+ 0x100: 0x2f7e, 0x101: 0x328a, 0x102: 0x4723, 0x103: 0x47b4, 0x104: 0x2f9c, 0x105: 0x32a8,
+ 0x106: 0x2fb0, 0x107: 0x32bc, 0x108: 0x2fb5, 0x109: 0x32c1, 0x10a: 0x2fba, 0x10b: 0x32c6,
+ 0x10c: 0x2fbf, 0x10d: 0x32cb, 0x10e: 0x2fc9, 0x10f: 0x32d5,
+ 0x112: 0x4746, 0x113: 0x47d7, 0x114: 0x2ff1, 0x115: 0x32fd, 0x116: 0x2ff6, 0x117: 0x3302,
+ 0x118: 0x3014, 0x119: 0x3320, 0x11a: 0x3005, 0x11b: 0x3311, 0x11c: 0x302d, 0x11d: 0x3339,
+ 0x11e: 0x3037, 0x11f: 0x3343, 0x120: 0x303c, 0x121: 0x3348, 0x122: 0x3046, 0x123: 0x3352,
+ 0x124: 0x304b, 0x125: 0x3357, 0x128: 0x307d, 0x129: 0x338e,
+ 0x12a: 0x3082, 0x12b: 0x3393, 0x12c: 0x3087, 0x12d: 0x3398, 0x12e: 0x30aa, 0x12f: 0x33b6,
+ 0x130: 0x308c, 0x132: 0x195d, 0x133: 0x19e7, 0x134: 0x30b4, 0x135: 0x33c0,
+ 0x136: 0x30c8, 0x137: 0x33d9, 0x139: 0x30d2, 0x13a: 0x33e3, 0x13b: 0x30dc,
+ 0x13c: 0x33ed, 0x13d: 0x30d7, 0x13e: 0x33e8, 0x13f: 0x1bac,
+ // Block 0x5, offset 0x140
+ 0x140: 0x1c34, 0x143: 0x30ff, 0x144: 0x3410, 0x145: 0x3118,
+ 0x146: 0x3429, 0x147: 0x310e, 0x148: 0x341f, 0x149: 0x1c5c,
+ 0x14c: 0x4769, 0x14d: 0x47fa, 0x14e: 0x3131, 0x14f: 0x3442, 0x150: 0x313b, 0x151: 0x344c,
+ 0x154: 0x3159, 0x155: 0x346a, 0x156: 0x3172, 0x157: 0x3483,
+ 0x158: 0x3163, 0x159: 0x3474, 0x15a: 0x478c, 0x15b: 0x481d, 0x15c: 0x317c, 0x15d: 0x348d,
+ 0x15e: 0x318b, 0x15f: 0x349c, 0x160: 0x4791, 0x161: 0x4822, 0x162: 0x31a4, 0x163: 0x34ba,
+ 0x164: 0x3195, 0x165: 0x34ab, 0x168: 0x479b, 0x169: 0x482c,
+ 0x16a: 0x47a0, 0x16b: 0x4831, 0x16c: 0x31c2, 0x16d: 0x34d8, 0x16e: 0x31cc, 0x16f: 0x34e2,
+ 0x170: 0x31d1, 0x171: 0x34e7, 0x172: 0x31ef, 0x173: 0x3505, 0x174: 0x3212, 0x175: 0x3528,
+ 0x176: 0x323a, 0x177: 0x3555, 0x178: 0x324e, 0x179: 0x325d, 0x17a: 0x357d, 0x17b: 0x3267,
+ 0x17c: 0x3587, 0x17d: 0x326c, 0x17e: 0x358c, 0x17f: 0x00a7,
+ // Block 0x6, offset 0x180
+ 0x184: 0x2dee, 0x185: 0x2df4,
+ 0x186: 0x2dfa, 0x187: 0x1972, 0x188: 0x1975, 0x189: 0x1a08, 0x18a: 0x1987, 0x18b: 0x198a,
+ 0x18c: 0x1a3e, 0x18d: 0x2f88, 0x18e: 0x3294, 0x18f: 0x3096, 0x190: 0x33a2, 0x191: 0x3140,
+ 0x192: 0x3451, 0x193: 0x31d6, 0x194: 0x34ec, 0x195: 0x39cf, 0x196: 0x3b5e, 0x197: 0x39c8,
+ 0x198: 0x3b57, 0x199: 0x39d6, 0x19a: 0x3b65, 0x19b: 0x39c1, 0x19c: 0x3b50,
+ 0x19e: 0x38b0, 0x19f: 0x3a3f, 0x1a0: 0x38a9, 0x1a1: 0x3a38, 0x1a2: 0x35b3, 0x1a3: 0x35c5,
+ 0x1a6: 0x3041, 0x1a7: 0x334d, 0x1a8: 0x30be, 0x1a9: 0x33cf,
+ 0x1aa: 0x4782, 0x1ab: 0x4813, 0x1ac: 0x3990, 0x1ad: 0x3b1f, 0x1ae: 0x35d7, 0x1af: 0x35dd,
+ 0x1b0: 0x33c5, 0x1b1: 0x1942, 0x1b2: 0x1945, 0x1b3: 0x19cf, 0x1b4: 0x3028, 0x1b5: 0x3334,
+ 0x1b8: 0x30fa, 0x1b9: 0x340b, 0x1ba: 0x38b7, 0x1bb: 0x3a46,
+ 0x1bc: 0x35ad, 0x1bd: 0x35bf, 0x1be: 0x35b9, 0x1bf: 0x35cb,
+ // Block 0x7, offset 0x1c0
+ 0x1c0: 0x2f8d, 0x1c1: 0x3299, 0x1c2: 0x2f92, 0x1c3: 0x329e, 0x1c4: 0x300a, 0x1c5: 0x3316,
+ 0x1c6: 0x300f, 0x1c7: 0x331b, 0x1c8: 0x309b, 0x1c9: 0x33a7, 0x1ca: 0x30a0, 0x1cb: 0x33ac,
+ 0x1cc: 0x3145, 0x1cd: 0x3456, 0x1ce: 0x314a, 0x1cf: 0x345b, 0x1d0: 0x3168, 0x1d1: 0x3479,
+ 0x1d2: 0x316d, 0x1d3: 0x347e, 0x1d4: 0x31db, 0x1d5: 0x34f1, 0x1d6: 0x31e0, 0x1d7: 0x34f6,
+ 0x1d8: 0x3186, 0x1d9: 0x3497, 0x1da: 0x319f, 0x1db: 0x34b5,
+ 0x1de: 0x305a, 0x1df: 0x3366,
+ 0x1e6: 0x4728, 0x1e7: 0x47b9, 0x1e8: 0x4750, 0x1e9: 0x47e1,
+ 0x1ea: 0x395f, 0x1eb: 0x3aee, 0x1ec: 0x393c, 0x1ed: 0x3acb, 0x1ee: 0x476e, 0x1ef: 0x47ff,
+ 0x1f0: 0x3958, 0x1f1: 0x3ae7, 0x1f2: 0x3244, 0x1f3: 0x355f,
+ // Block 0x8, offset 0x200
+ 0x200: 0x9932, 0x201: 0x9932, 0x202: 0x9932, 0x203: 0x9932, 0x204: 0x9932, 0x205: 0x8132,
+ 0x206: 0x9932, 0x207: 0x9932, 0x208: 0x9932, 0x209: 0x9932, 0x20a: 0x9932, 0x20b: 0x9932,
+ 0x20c: 0x9932, 0x20d: 0x8132, 0x20e: 0x8132, 0x20f: 0x9932, 0x210: 0x8132, 0x211: 0x9932,
+ 0x212: 0x8132, 0x213: 0x9932, 0x214: 0x9932, 0x215: 0x8133, 0x216: 0x812d, 0x217: 0x812d,
+ 0x218: 0x812d, 0x219: 0x812d, 0x21a: 0x8133, 0x21b: 0x992b, 0x21c: 0x812d, 0x21d: 0x812d,
+ 0x21e: 0x812d, 0x21f: 0x812d, 0x220: 0x812d, 0x221: 0x8129, 0x222: 0x8129, 0x223: 0x992d,
+ 0x224: 0x992d, 0x225: 0x992d, 0x226: 0x992d, 0x227: 0x9929, 0x228: 0x9929, 0x229: 0x812d,
+ 0x22a: 0x812d, 0x22b: 0x812d, 0x22c: 0x812d, 0x22d: 0x992d, 0x22e: 0x992d, 0x22f: 0x812d,
+ 0x230: 0x992d, 0x231: 0x992d, 0x232: 0x812d, 0x233: 0x812d, 0x234: 0x8101, 0x235: 0x8101,
+ 0x236: 0x8101, 0x237: 0x8101, 0x238: 0x9901, 0x239: 0x812d, 0x23a: 0x812d, 0x23b: 0x812d,
+ 0x23c: 0x812d, 0x23d: 0x8132, 0x23e: 0x8132, 0x23f: 0x8132,
+ // Block 0x9, offset 0x240
+ 0x240: 0x4a44, 0x241: 0x4a49, 0x242: 0x9932, 0x243: 0x4a4e, 0x244: 0x4a53, 0x245: 0x9936,
+ 0x246: 0x8132, 0x247: 0x812d, 0x248: 0x812d, 0x249: 0x812d, 0x24a: 0x8132, 0x24b: 0x8132,
+ 0x24c: 0x8132, 0x24d: 0x812d, 0x24e: 0x812d, 0x250: 0x8132, 0x251: 0x8132,
+ 0x252: 0x8132, 0x253: 0x812d, 0x254: 0x812d, 0x255: 0x812d, 0x256: 0x812d, 0x257: 0x8132,
+ 0x258: 0x8133, 0x259: 0x812d, 0x25a: 0x812d, 0x25b: 0x8132, 0x25c: 0x8134, 0x25d: 0x8135,
+ 0x25e: 0x8135, 0x25f: 0x8134, 0x260: 0x8135, 0x261: 0x8135, 0x262: 0x8134, 0x263: 0x8132,
+ 0x264: 0x8132, 0x265: 0x8132, 0x266: 0x8132, 0x267: 0x8132, 0x268: 0x8132, 0x269: 0x8132,
+ 0x26a: 0x8132, 0x26b: 0x8132, 0x26c: 0x8132, 0x26d: 0x8132, 0x26e: 0x8132, 0x26f: 0x8132,
+ 0x274: 0x0170,
+ 0x27a: 0x42a5,
+ 0x27e: 0x0037,
+ // Block 0xa, offset 0x280
+ 0x284: 0x425a, 0x285: 0x4511,
+ 0x286: 0x35e9, 0x287: 0x00ce, 0x288: 0x3607, 0x289: 0x3613, 0x28a: 0x3625,
+ 0x28c: 0x3643, 0x28e: 0x3655, 0x28f: 0x3673, 0x290: 0x3e08, 0x291: 0xa000,
+ 0x295: 0xa000, 0x297: 0xa000,
+ 0x299: 0xa000,
+ 0x29f: 0xa000, 0x2a1: 0xa000,
+ 0x2a5: 0xa000, 0x2a9: 0xa000,
+ 0x2aa: 0x3637, 0x2ab: 0x3667, 0x2ac: 0x4894, 0x2ad: 0x3697, 0x2ae: 0x48be, 0x2af: 0x36a9,
+ 0x2b0: 0x3e70, 0x2b1: 0xa000, 0x2b5: 0xa000,
+ 0x2b7: 0xa000, 0x2b9: 0xa000,
+ 0x2bf: 0xa000,
+ // Block 0xb, offset 0x2c0
+ 0x2c1: 0xa000, 0x2c5: 0xa000,
+ 0x2c9: 0xa000, 0x2ca: 0x48d6, 0x2cb: 0x48f4,
+ 0x2cc: 0x36c7, 0x2cd: 0x36df, 0x2ce: 0x490c, 0x2d0: 0x01be, 0x2d1: 0x01d0,
+ 0x2d2: 0x01ac, 0x2d3: 0x43a2, 0x2d4: 0x43a8, 0x2d5: 0x01fa, 0x2d6: 0x01e8,
+ 0x2f0: 0x01d6, 0x2f1: 0x01eb, 0x2f2: 0x01ee, 0x2f4: 0x0188, 0x2f5: 0x01c7,
+ 0x2f9: 0x01a6,
+ // Block 0xc, offset 0x300
+ 0x300: 0x3721, 0x301: 0x372d, 0x303: 0x371b,
+ 0x306: 0xa000, 0x307: 0x3709,
+ 0x30c: 0x375d, 0x30d: 0x3745, 0x30e: 0x376f, 0x310: 0xa000,
+ 0x313: 0xa000, 0x315: 0xa000, 0x316: 0xa000, 0x317: 0xa000,
+ 0x318: 0xa000, 0x319: 0x3751, 0x31a: 0xa000,
+ 0x31e: 0xa000, 0x323: 0xa000,
+ 0x327: 0xa000,
+ 0x32b: 0xa000, 0x32d: 0xa000,
+ 0x330: 0xa000, 0x333: 0xa000, 0x335: 0xa000,
+ 0x336: 0xa000, 0x337: 0xa000, 0x338: 0xa000, 0x339: 0x37d5, 0x33a: 0xa000,
+ 0x33e: 0xa000,
+ // Block 0xd, offset 0x340
+ 0x341: 0x3733, 0x342: 0x37b7,
+ 0x350: 0x370f, 0x351: 0x3793,
+ 0x352: 0x3715, 0x353: 0x3799, 0x356: 0x3727, 0x357: 0x37ab,
+ 0x358: 0xa000, 0x359: 0xa000, 0x35a: 0x3829, 0x35b: 0x382f, 0x35c: 0x3739, 0x35d: 0x37bd,
+ 0x35e: 0x373f, 0x35f: 0x37c3, 0x362: 0x374b, 0x363: 0x37cf,
+ 0x364: 0x3757, 0x365: 0x37db, 0x366: 0x3763, 0x367: 0x37e7, 0x368: 0xa000, 0x369: 0xa000,
+ 0x36a: 0x3835, 0x36b: 0x383b, 0x36c: 0x378d, 0x36d: 0x3811, 0x36e: 0x3769, 0x36f: 0x37ed,
+ 0x370: 0x3775, 0x371: 0x37f9, 0x372: 0x377b, 0x373: 0x37ff, 0x374: 0x3781, 0x375: 0x3805,
+ 0x378: 0x3787, 0x379: 0x380b,
+ // Block 0xe, offset 0x380
+ 0x387: 0x1d61,
+ 0x391: 0x812d,
+ 0x392: 0x8132, 0x393: 0x8132, 0x394: 0x8132, 0x395: 0x8132, 0x396: 0x812d, 0x397: 0x8132,
+ 0x398: 0x8132, 0x399: 0x8132, 0x39a: 0x812e, 0x39b: 0x812d, 0x39c: 0x8132, 0x39d: 0x8132,
+ 0x39e: 0x8132, 0x39f: 0x8132, 0x3a0: 0x8132, 0x3a1: 0x8132, 0x3a2: 0x812d, 0x3a3: 0x812d,
+ 0x3a4: 0x812d, 0x3a5: 0x812d, 0x3a6: 0x812d, 0x3a7: 0x812d, 0x3a8: 0x8132, 0x3a9: 0x8132,
+ 0x3aa: 0x812d, 0x3ab: 0x8132, 0x3ac: 0x8132, 0x3ad: 0x812e, 0x3ae: 0x8131, 0x3af: 0x8132,
+ 0x3b0: 0x8105, 0x3b1: 0x8106, 0x3b2: 0x8107, 0x3b3: 0x8108, 0x3b4: 0x8109, 0x3b5: 0x810a,
+ 0x3b6: 0x810b, 0x3b7: 0x810c, 0x3b8: 0x810d, 0x3b9: 0x810e, 0x3ba: 0x810e, 0x3bb: 0x810f,
+ 0x3bc: 0x8110, 0x3bd: 0x8111, 0x3bf: 0x8112,
+ // Block 0xf, offset 0x3c0
+ 0x3c8: 0xa000, 0x3ca: 0xa000, 0x3cb: 0x8116,
+ 0x3cc: 0x8117, 0x3cd: 0x8118, 0x3ce: 0x8119, 0x3cf: 0x811a, 0x3d0: 0x811b, 0x3d1: 0x811c,
+ 0x3d2: 0x811d, 0x3d3: 0x9932, 0x3d4: 0x9932, 0x3d5: 0x992d, 0x3d6: 0x812d, 0x3d7: 0x8132,
+ 0x3d8: 0x8132, 0x3d9: 0x8132, 0x3da: 0x8132, 0x3db: 0x8132, 0x3dc: 0x812d, 0x3dd: 0x8132,
+ 0x3de: 0x8132, 0x3df: 0x812d,
+ 0x3f0: 0x811e, 0x3f5: 0x1d84,
+ 0x3f6: 0x2013, 0x3f7: 0x204f, 0x3f8: 0x204a,
+ // Block 0x10, offset 0x400
+ 0x405: 0xa000,
+ 0x406: 0x2d26, 0x407: 0xa000, 0x408: 0x2d2e, 0x409: 0xa000, 0x40a: 0x2d36, 0x40b: 0xa000,
+ 0x40c: 0x2d3e, 0x40d: 0xa000, 0x40e: 0x2d46, 0x411: 0xa000,
+ 0x412: 0x2d4e,
+ 0x434: 0x8102, 0x435: 0x9900,
+ 0x43a: 0xa000, 0x43b: 0x2d56,
+ 0x43c: 0xa000, 0x43d: 0x2d5e, 0x43e: 0xa000, 0x43f: 0xa000,
+ // Block 0x11, offset 0x440
+ 0x440: 0x0069, 0x441: 0x006b, 0x442: 0x006f, 0x443: 0x0083, 0x444: 0x00f5, 0x445: 0x00f8,
+ 0x446: 0x0413, 0x447: 0x0085, 0x448: 0x0089, 0x449: 0x008b, 0x44a: 0x0104, 0x44b: 0x0107,
+ 0x44c: 0x010a, 0x44d: 0x008f, 0x44f: 0x0097, 0x450: 0x009b, 0x451: 0x00e0,
+ 0x452: 0x009f, 0x453: 0x00fe, 0x454: 0x0417, 0x455: 0x041b, 0x456: 0x00a1, 0x457: 0x00a9,
+ 0x458: 0x00ab, 0x459: 0x0423, 0x45a: 0x012b, 0x45b: 0x00ad, 0x45c: 0x0427, 0x45d: 0x01be,
+ 0x45e: 0x01c1, 0x45f: 0x01c4, 0x460: 0x01fa, 0x461: 0x01fd, 0x462: 0x0093, 0x463: 0x00a5,
+ 0x464: 0x00ab, 0x465: 0x00ad, 0x466: 0x01be, 0x467: 0x01c1, 0x468: 0x01eb, 0x469: 0x01fa,
+ 0x46a: 0x01fd,
+ 0x478: 0x020c,
+ // Block 0x12, offset 0x480
+ 0x49b: 0x00fb, 0x49c: 0x0087, 0x49d: 0x0101,
+ 0x49e: 0x00d4, 0x49f: 0x010a, 0x4a0: 0x008d, 0x4a1: 0x010d, 0x4a2: 0x0110, 0x4a3: 0x0116,
+ 0x4a4: 0x011c, 0x4a5: 0x011f, 0x4a6: 0x0122, 0x4a7: 0x042b, 0x4a8: 0x016a, 0x4a9: 0x0128,
+ 0x4aa: 0x042f, 0x4ab: 0x016d, 0x4ac: 0x0131, 0x4ad: 0x012e, 0x4ae: 0x0134, 0x4af: 0x0137,
+ 0x4b0: 0x013a, 0x4b1: 0x013d, 0x4b2: 0x0140, 0x4b3: 0x014c, 0x4b4: 0x014f, 0x4b5: 0x00ec,
+ 0x4b6: 0x0152, 0x4b7: 0x0155, 0x4b8: 0x041f, 0x4b9: 0x0158, 0x4ba: 0x015b, 0x4bb: 0x00b5,
+ 0x4bc: 0x015e, 0x4bd: 0x0161, 0x4be: 0x0164, 0x4bf: 0x01d0,
+ // Block 0x13, offset 0x4c0
+ 0x4c0: 0x2f97, 0x4c1: 0x32a3, 0x4c2: 0x2fa1, 0x4c3: 0x32ad, 0x4c4: 0x2fa6, 0x4c5: 0x32b2,
+ 0x4c6: 0x2fab, 0x4c7: 0x32b7, 0x4c8: 0x38cc, 0x4c9: 0x3a5b, 0x4ca: 0x2fc4, 0x4cb: 0x32d0,
+ 0x4cc: 0x2fce, 0x4cd: 0x32da, 0x4ce: 0x2fdd, 0x4cf: 0x32e9, 0x4d0: 0x2fd3, 0x4d1: 0x32df,
+ 0x4d2: 0x2fd8, 0x4d3: 0x32e4, 0x4d4: 0x38ef, 0x4d5: 0x3a7e, 0x4d6: 0x38f6, 0x4d7: 0x3a85,
+ 0x4d8: 0x3019, 0x4d9: 0x3325, 0x4da: 0x301e, 0x4db: 0x332a, 0x4dc: 0x3904, 0x4dd: 0x3a93,
+ 0x4de: 0x3023, 0x4df: 0x332f, 0x4e0: 0x3032, 0x4e1: 0x333e, 0x4e2: 0x3050, 0x4e3: 0x335c,
+ 0x4e4: 0x305f, 0x4e5: 0x336b, 0x4e6: 0x3055, 0x4e7: 0x3361, 0x4e8: 0x3064, 0x4e9: 0x3370,
+ 0x4ea: 0x3069, 0x4eb: 0x3375, 0x4ec: 0x30af, 0x4ed: 0x33bb, 0x4ee: 0x390b, 0x4ef: 0x3a9a,
+ 0x4f0: 0x30b9, 0x4f1: 0x33ca, 0x4f2: 0x30c3, 0x4f3: 0x33d4, 0x4f4: 0x30cd, 0x4f5: 0x33de,
+ 0x4f6: 0x475a, 0x4f7: 0x47eb, 0x4f8: 0x3912, 0x4f9: 0x3aa1, 0x4fa: 0x30e6, 0x4fb: 0x33f7,
+ 0x4fc: 0x30e1, 0x4fd: 0x33f2, 0x4fe: 0x30eb, 0x4ff: 0x33fc,
+ // Block 0x14, offset 0x500
+ 0x500: 0x30f0, 0x501: 0x3401, 0x502: 0x30f5, 0x503: 0x3406, 0x504: 0x3109, 0x505: 0x341a,
+ 0x506: 0x3113, 0x507: 0x3424, 0x508: 0x3122, 0x509: 0x3433, 0x50a: 0x311d, 0x50b: 0x342e,
+ 0x50c: 0x3935, 0x50d: 0x3ac4, 0x50e: 0x3943, 0x50f: 0x3ad2, 0x510: 0x394a, 0x511: 0x3ad9,
+ 0x512: 0x3951, 0x513: 0x3ae0, 0x514: 0x314f, 0x515: 0x3460, 0x516: 0x3154, 0x517: 0x3465,
+ 0x518: 0x315e, 0x519: 0x346f, 0x51a: 0x4787, 0x51b: 0x4818, 0x51c: 0x3997, 0x51d: 0x3b26,
+ 0x51e: 0x3177, 0x51f: 0x3488, 0x520: 0x3181, 0x521: 0x3492, 0x522: 0x4796, 0x523: 0x4827,
+ 0x524: 0x399e, 0x525: 0x3b2d, 0x526: 0x39a5, 0x527: 0x3b34, 0x528: 0x39ac, 0x529: 0x3b3b,
+ 0x52a: 0x3190, 0x52b: 0x34a1, 0x52c: 0x319a, 0x52d: 0x34b0, 0x52e: 0x31ae, 0x52f: 0x34c4,
+ 0x530: 0x31a9, 0x531: 0x34bf, 0x532: 0x31ea, 0x533: 0x3500, 0x534: 0x31f9, 0x535: 0x350f,
+ 0x536: 0x31f4, 0x537: 0x350a, 0x538: 0x39b3, 0x539: 0x3b42, 0x53a: 0x39ba, 0x53b: 0x3b49,
+ 0x53c: 0x31fe, 0x53d: 0x3514, 0x53e: 0x3203, 0x53f: 0x3519,
+ // Block 0x15, offset 0x540
+ 0x540: 0x3208, 0x541: 0x351e, 0x542: 0x320d, 0x543: 0x3523, 0x544: 0x321c, 0x545: 0x3532,
+ 0x546: 0x3217, 0x547: 0x352d, 0x548: 0x3221, 0x549: 0x353c, 0x54a: 0x3226, 0x54b: 0x3541,
+ 0x54c: 0x322b, 0x54d: 0x3546, 0x54e: 0x3249, 0x54f: 0x3564, 0x550: 0x3262, 0x551: 0x3582,
+ 0x552: 0x3271, 0x553: 0x3591, 0x554: 0x3276, 0x555: 0x3596, 0x556: 0x337a, 0x557: 0x34a6,
+ 0x558: 0x3537, 0x559: 0x3573, 0x55a: 0x1be0, 0x55b: 0x42d7,
+ 0x560: 0x4737, 0x561: 0x47c8, 0x562: 0x2f83, 0x563: 0x328f,
+ 0x564: 0x3878, 0x565: 0x3a07, 0x566: 0x3871, 0x567: 0x3a00, 0x568: 0x3886, 0x569: 0x3a15,
+ 0x56a: 0x387f, 0x56b: 0x3a0e, 0x56c: 0x38be, 0x56d: 0x3a4d, 0x56e: 0x3894, 0x56f: 0x3a23,
+ 0x570: 0x388d, 0x571: 0x3a1c, 0x572: 0x38a2, 0x573: 0x3a31, 0x574: 0x389b, 0x575: 0x3a2a,
+ 0x576: 0x38c5, 0x577: 0x3a54, 0x578: 0x474b, 0x579: 0x47dc, 0x57a: 0x3000, 0x57b: 0x330c,
+ 0x57c: 0x2fec, 0x57d: 0x32f8, 0x57e: 0x38da, 0x57f: 0x3a69,
+ // Block 0x16, offset 0x580
+ 0x580: 0x38d3, 0x581: 0x3a62, 0x582: 0x38e8, 0x583: 0x3a77, 0x584: 0x38e1, 0x585: 0x3a70,
+ 0x586: 0x38fd, 0x587: 0x3a8c, 0x588: 0x3091, 0x589: 0x339d, 0x58a: 0x30a5, 0x58b: 0x33b1,
+ 0x58c: 0x477d, 0x58d: 0x480e, 0x58e: 0x3136, 0x58f: 0x3447, 0x590: 0x3920, 0x591: 0x3aaf,
+ 0x592: 0x3919, 0x593: 0x3aa8, 0x594: 0x392e, 0x595: 0x3abd, 0x596: 0x3927, 0x597: 0x3ab6,
+ 0x598: 0x3989, 0x599: 0x3b18, 0x59a: 0x396d, 0x59b: 0x3afc, 0x59c: 0x3966, 0x59d: 0x3af5,
+ 0x59e: 0x397b, 0x59f: 0x3b0a, 0x5a0: 0x3974, 0x5a1: 0x3b03, 0x5a2: 0x3982, 0x5a3: 0x3b11,
+ 0x5a4: 0x31e5, 0x5a5: 0x34fb, 0x5a6: 0x31c7, 0x5a7: 0x34dd, 0x5a8: 0x39e4, 0x5a9: 0x3b73,
+ 0x5aa: 0x39dd, 0x5ab: 0x3b6c, 0x5ac: 0x39f2, 0x5ad: 0x3b81, 0x5ae: 0x39eb, 0x5af: 0x3b7a,
+ 0x5b0: 0x39f9, 0x5b1: 0x3b88, 0x5b2: 0x3230, 0x5b3: 0x354b, 0x5b4: 0x3258, 0x5b5: 0x3578,
+ 0x5b6: 0x3253, 0x5b7: 0x356e, 0x5b8: 0x323f, 0x5b9: 0x355a,
+ // Block 0x17, offset 0x5c0
+ 0x5c0: 0x489a, 0x5c1: 0x48a0, 0x5c2: 0x49b4, 0x5c3: 0x49cc, 0x5c4: 0x49bc, 0x5c5: 0x49d4,
+ 0x5c6: 0x49c4, 0x5c7: 0x49dc, 0x5c8: 0x4840, 0x5c9: 0x4846, 0x5ca: 0x4924, 0x5cb: 0x493c,
+ 0x5cc: 0x492c, 0x5cd: 0x4944, 0x5ce: 0x4934, 0x5cf: 0x494c, 0x5d0: 0x48ac, 0x5d1: 0x48b2,
+ 0x5d2: 0x3db8, 0x5d3: 0x3dc8, 0x5d4: 0x3dc0, 0x5d5: 0x3dd0,
+ 0x5d8: 0x484c, 0x5d9: 0x4852, 0x5da: 0x3ce8, 0x5db: 0x3cf8, 0x5dc: 0x3cf0, 0x5dd: 0x3d00,
+ 0x5e0: 0x48c4, 0x5e1: 0x48ca, 0x5e2: 0x49e4, 0x5e3: 0x49fc,
+ 0x5e4: 0x49ec, 0x5e5: 0x4a04, 0x5e6: 0x49f4, 0x5e7: 0x4a0c, 0x5e8: 0x4858, 0x5e9: 0x485e,
+ 0x5ea: 0x4954, 0x5eb: 0x496c, 0x5ec: 0x495c, 0x5ed: 0x4974, 0x5ee: 0x4964, 0x5ef: 0x497c,
+ 0x5f0: 0x48dc, 0x5f1: 0x48e2, 0x5f2: 0x3e18, 0x5f3: 0x3e30, 0x5f4: 0x3e20, 0x5f5: 0x3e38,
+ 0x5f6: 0x3e28, 0x5f7: 0x3e40, 0x5f8: 0x4864, 0x5f9: 0x486a, 0x5fa: 0x3d18, 0x5fb: 0x3d30,
+ 0x5fc: 0x3d20, 0x5fd: 0x3d38, 0x5fe: 0x3d28, 0x5ff: 0x3d40,
+ // Block 0x18, offset 0x600
+ 0x600: 0x48e8, 0x601: 0x48ee, 0x602: 0x3e48, 0x603: 0x3e58, 0x604: 0x3e50, 0x605: 0x3e60,
+ 0x608: 0x4870, 0x609: 0x4876, 0x60a: 0x3d48, 0x60b: 0x3d58,
+ 0x60c: 0x3d50, 0x60d: 0x3d60, 0x610: 0x48fa, 0x611: 0x4900,
+ 0x612: 0x3e80, 0x613: 0x3e98, 0x614: 0x3e88, 0x615: 0x3ea0, 0x616: 0x3e90, 0x617: 0x3ea8,
+ 0x619: 0x487c, 0x61b: 0x3d68, 0x61d: 0x3d70,
+ 0x61f: 0x3d78, 0x620: 0x4912, 0x621: 0x4918, 0x622: 0x4a14, 0x623: 0x4a2c,
+ 0x624: 0x4a1c, 0x625: 0x4a34, 0x626: 0x4a24, 0x627: 0x4a3c, 0x628: 0x4882, 0x629: 0x4888,
+ 0x62a: 0x4984, 0x62b: 0x499c, 0x62c: 0x498c, 0x62d: 0x49a4, 0x62e: 0x4994, 0x62f: 0x49ac,
+ 0x630: 0x488e, 0x631: 0x43b4, 0x632: 0x3691, 0x633: 0x43ba, 0x634: 0x48b8, 0x635: 0x43c0,
+ 0x636: 0x36a3, 0x637: 0x43c6, 0x638: 0x36c1, 0x639: 0x43cc, 0x63a: 0x36d9, 0x63b: 0x43d2,
+ 0x63c: 0x4906, 0x63d: 0x43d8,
+ // Block 0x19, offset 0x640
+ 0x640: 0x3da0, 0x641: 0x3da8, 0x642: 0x4184, 0x643: 0x41a2, 0x644: 0x418e, 0x645: 0x41ac,
+ 0x646: 0x4198, 0x647: 0x41b6, 0x648: 0x3cd8, 0x649: 0x3ce0, 0x64a: 0x40d0, 0x64b: 0x40ee,
+ 0x64c: 0x40da, 0x64d: 0x40f8, 0x64e: 0x40e4, 0x64f: 0x4102, 0x650: 0x3de8, 0x651: 0x3df0,
+ 0x652: 0x41c0, 0x653: 0x41de, 0x654: 0x41ca, 0x655: 0x41e8, 0x656: 0x41d4, 0x657: 0x41f2,
+ 0x658: 0x3d08, 0x659: 0x3d10, 0x65a: 0x410c, 0x65b: 0x412a, 0x65c: 0x4116, 0x65d: 0x4134,
+ 0x65e: 0x4120, 0x65f: 0x413e, 0x660: 0x3ec0, 0x661: 0x3ec8, 0x662: 0x41fc, 0x663: 0x421a,
+ 0x664: 0x4206, 0x665: 0x4224, 0x666: 0x4210, 0x667: 0x422e, 0x668: 0x3d80, 0x669: 0x3d88,
+ 0x66a: 0x4148, 0x66b: 0x4166, 0x66c: 0x4152, 0x66d: 0x4170, 0x66e: 0x415c, 0x66f: 0x417a,
+ 0x670: 0x3685, 0x671: 0x367f, 0x672: 0x3d90, 0x673: 0x368b, 0x674: 0x3d98,
+ 0x676: 0x48a6, 0x677: 0x3db0, 0x678: 0x35f5, 0x679: 0x35ef, 0x67a: 0x35e3, 0x67b: 0x4384,
+ 0x67c: 0x35fb, 0x67d: 0x4287, 0x67e: 0x01d3, 0x67f: 0x4287,
+ // Block 0x1a, offset 0x680
+ 0x680: 0x42a0, 0x681: 0x4518, 0x682: 0x3dd8, 0x683: 0x369d, 0x684: 0x3de0,
+ 0x686: 0x48d0, 0x687: 0x3df8, 0x688: 0x3601, 0x689: 0x438a, 0x68a: 0x360d, 0x68b: 0x4390,
+ 0x68c: 0x3619, 0x68d: 0x451f, 0x68e: 0x4526, 0x68f: 0x452d, 0x690: 0x36b5, 0x691: 0x36af,
+ 0x692: 0x3e00, 0x693: 0x457a, 0x696: 0x36bb, 0x697: 0x3e10,
+ 0x698: 0x3631, 0x699: 0x362b, 0x69a: 0x361f, 0x69b: 0x4396, 0x69d: 0x4534,
+ 0x69e: 0x453b, 0x69f: 0x4542, 0x6a0: 0x36eb, 0x6a1: 0x36e5, 0x6a2: 0x3e68, 0x6a3: 0x4582,
+ 0x6a4: 0x36cd, 0x6a5: 0x36d3, 0x6a6: 0x36f1, 0x6a7: 0x3e78, 0x6a8: 0x3661, 0x6a9: 0x365b,
+ 0x6aa: 0x364f, 0x6ab: 0x43a2, 0x6ac: 0x3649, 0x6ad: 0x450a, 0x6ae: 0x4511, 0x6af: 0x0081,
+ 0x6b2: 0x3eb0, 0x6b3: 0x36f7, 0x6b4: 0x3eb8,
+ 0x6b6: 0x491e, 0x6b7: 0x3ed0, 0x6b8: 0x363d, 0x6b9: 0x439c, 0x6ba: 0x366d, 0x6bb: 0x43ae,
+ 0x6bc: 0x3679, 0x6bd: 0x425a, 0x6be: 0x428c,
+ // Block 0x1b, offset 0x6c0
+ 0x6c0: 0x1bd8, 0x6c1: 0x1bdc, 0x6c2: 0x0047, 0x6c3: 0x1c54, 0x6c5: 0x1be8,
+ 0x6c6: 0x1bec, 0x6c7: 0x00e9, 0x6c9: 0x1c58, 0x6ca: 0x008f, 0x6cb: 0x0051,
+ 0x6cc: 0x0051, 0x6cd: 0x0051, 0x6ce: 0x0091, 0x6cf: 0x00da, 0x6d0: 0x0053, 0x6d1: 0x0053,
+ 0x6d2: 0x0059, 0x6d3: 0x0099, 0x6d5: 0x005d, 0x6d6: 0x198d,
+ 0x6d9: 0x0061, 0x6da: 0x0063, 0x6db: 0x0065, 0x6dc: 0x0065, 0x6dd: 0x0065,
+ 0x6e0: 0x199f, 0x6e1: 0x1bc8, 0x6e2: 0x19a8,
+ 0x6e4: 0x0075, 0x6e6: 0x01b8, 0x6e8: 0x0075,
+ 0x6ea: 0x0057, 0x6eb: 0x42d2, 0x6ec: 0x0045, 0x6ed: 0x0047, 0x6ef: 0x008b,
+ 0x6f0: 0x004b, 0x6f1: 0x004d, 0x6f3: 0x005b, 0x6f4: 0x009f, 0x6f5: 0x0215,
+ 0x6f6: 0x0218, 0x6f7: 0x021b, 0x6f8: 0x021e, 0x6f9: 0x0093, 0x6fb: 0x1b98,
+ 0x6fc: 0x01e8, 0x6fd: 0x01c1, 0x6fe: 0x0179, 0x6ff: 0x01a0,
+ // Block 0x1c, offset 0x700
+ 0x700: 0x0463, 0x705: 0x0049,
+ 0x706: 0x0089, 0x707: 0x008b, 0x708: 0x0093, 0x709: 0x0095,
+ 0x710: 0x222e, 0x711: 0x223a,
+ 0x712: 0x22ee, 0x713: 0x2216, 0x714: 0x229a, 0x715: 0x2222, 0x716: 0x22a0, 0x717: 0x22b8,
+ 0x718: 0x22c4, 0x719: 0x2228, 0x71a: 0x22ca, 0x71b: 0x2234, 0x71c: 0x22be, 0x71d: 0x22d0,
+ 0x71e: 0x22d6, 0x71f: 0x1cbc, 0x720: 0x0053, 0x721: 0x195a, 0x722: 0x1ba4, 0x723: 0x1963,
+ 0x724: 0x006d, 0x725: 0x19ab, 0x726: 0x1bd0, 0x727: 0x1d48, 0x728: 0x1966, 0x729: 0x0071,
+ 0x72a: 0x19b7, 0x72b: 0x1bd4, 0x72c: 0x0059, 0x72d: 0x0047, 0x72e: 0x0049, 0x72f: 0x005b,
+ 0x730: 0x0093, 0x731: 0x19e4, 0x732: 0x1c18, 0x733: 0x19ed, 0x734: 0x00ad, 0x735: 0x1a62,
+ 0x736: 0x1c4c, 0x737: 0x1d5c, 0x738: 0x19f0, 0x739: 0x00b1, 0x73a: 0x1a65, 0x73b: 0x1c50,
+ 0x73c: 0x0099, 0x73d: 0x0087, 0x73e: 0x0089, 0x73f: 0x009b,
+ // Block 0x1d, offset 0x740
+ 0x741: 0x3c06, 0x743: 0xa000, 0x744: 0x3c0d, 0x745: 0xa000,
+ 0x747: 0x3c14, 0x748: 0xa000, 0x749: 0x3c1b,
+ 0x74d: 0xa000,
+ 0x760: 0x2f65, 0x761: 0xa000, 0x762: 0x3c29,
+ 0x764: 0xa000, 0x765: 0xa000,
+ 0x76d: 0x3c22, 0x76e: 0x2f60, 0x76f: 0x2f6a,
+ 0x770: 0x3c30, 0x771: 0x3c37, 0x772: 0xa000, 0x773: 0xa000, 0x774: 0x3c3e, 0x775: 0x3c45,
+ 0x776: 0xa000, 0x777: 0xa000, 0x778: 0x3c4c, 0x779: 0x3c53, 0x77a: 0xa000, 0x77b: 0xa000,
+ 0x77c: 0xa000, 0x77d: 0xa000,
+ // Block 0x1e, offset 0x780
+ 0x780: 0x3c5a, 0x781: 0x3c61, 0x782: 0xa000, 0x783: 0xa000, 0x784: 0x3c76, 0x785: 0x3c7d,
+ 0x786: 0xa000, 0x787: 0xa000, 0x788: 0x3c84, 0x789: 0x3c8b,
+ 0x791: 0xa000,
+ 0x792: 0xa000,
+ 0x7a2: 0xa000,
+ 0x7a8: 0xa000, 0x7a9: 0xa000,
+ 0x7ab: 0xa000, 0x7ac: 0x3ca0, 0x7ad: 0x3ca7, 0x7ae: 0x3cae, 0x7af: 0x3cb5,
+ 0x7b2: 0xa000, 0x7b3: 0xa000, 0x7b4: 0xa000, 0x7b5: 0xa000,
+ // Block 0x1f, offset 0x7c0
+ 0x7e0: 0x0023, 0x7e1: 0x0025, 0x7e2: 0x0027, 0x7e3: 0x0029,
+ 0x7e4: 0x002b, 0x7e5: 0x002d, 0x7e6: 0x002f, 0x7e7: 0x0031, 0x7e8: 0x0033, 0x7e9: 0x1882,
+ 0x7ea: 0x1885, 0x7eb: 0x1888, 0x7ec: 0x188b, 0x7ed: 0x188e, 0x7ee: 0x1891, 0x7ef: 0x1894,
+ 0x7f0: 0x1897, 0x7f1: 0x189a, 0x7f2: 0x189d, 0x7f3: 0x18a6, 0x7f4: 0x1a68, 0x7f5: 0x1a6c,
+ 0x7f6: 0x1a70, 0x7f7: 0x1a74, 0x7f8: 0x1a78, 0x7f9: 0x1a7c, 0x7fa: 0x1a80, 0x7fb: 0x1a84,
+ 0x7fc: 0x1a88, 0x7fd: 0x1c80, 0x7fe: 0x1c85, 0x7ff: 0x1c8a,
+ // Block 0x20, offset 0x800
+ 0x800: 0x1c8f, 0x801: 0x1c94, 0x802: 0x1c99, 0x803: 0x1c9e, 0x804: 0x1ca3, 0x805: 0x1ca8,
+ 0x806: 0x1cad, 0x807: 0x1cb2, 0x808: 0x187f, 0x809: 0x18a3, 0x80a: 0x18c7, 0x80b: 0x18eb,
+ 0x80c: 0x190f, 0x80d: 0x1918, 0x80e: 0x191e, 0x80f: 0x1924, 0x810: 0x192a, 0x811: 0x1b60,
+ 0x812: 0x1b64, 0x813: 0x1b68, 0x814: 0x1b6c, 0x815: 0x1b70, 0x816: 0x1b74, 0x817: 0x1b78,
+ 0x818: 0x1b7c, 0x819: 0x1b80, 0x81a: 0x1b84, 0x81b: 0x1b88, 0x81c: 0x1af4, 0x81d: 0x1af8,
+ 0x81e: 0x1afc, 0x81f: 0x1b00, 0x820: 0x1b04, 0x821: 0x1b08, 0x822: 0x1b0c, 0x823: 0x1b10,
+ 0x824: 0x1b14, 0x825: 0x1b18, 0x826: 0x1b1c, 0x827: 0x1b20, 0x828: 0x1b24, 0x829: 0x1b28,
+ 0x82a: 0x1b2c, 0x82b: 0x1b30, 0x82c: 0x1b34, 0x82d: 0x1b38, 0x82e: 0x1b3c, 0x82f: 0x1b40,
+ 0x830: 0x1b44, 0x831: 0x1b48, 0x832: 0x1b4c, 0x833: 0x1b50, 0x834: 0x1b54, 0x835: 0x1b58,
+ 0x836: 0x0043, 0x837: 0x0045, 0x838: 0x0047, 0x839: 0x0049, 0x83a: 0x004b, 0x83b: 0x004d,
+ 0x83c: 0x004f, 0x83d: 0x0051, 0x83e: 0x0053, 0x83f: 0x0055,
+ // Block 0x21, offset 0x840
+ 0x840: 0x06bf, 0x841: 0x06e3, 0x842: 0x06ef, 0x843: 0x06ff, 0x844: 0x0707, 0x845: 0x0713,
+ 0x846: 0x071b, 0x847: 0x0723, 0x848: 0x072f, 0x849: 0x0783, 0x84a: 0x079b, 0x84b: 0x07ab,
+ 0x84c: 0x07bb, 0x84d: 0x07cb, 0x84e: 0x07db, 0x84f: 0x07fb, 0x850: 0x07ff, 0x851: 0x0803,
+ 0x852: 0x0837, 0x853: 0x085f, 0x854: 0x086f, 0x855: 0x0877, 0x856: 0x087b, 0x857: 0x0887,
+ 0x858: 0x08a3, 0x859: 0x08a7, 0x85a: 0x08bf, 0x85b: 0x08c3, 0x85c: 0x08cb, 0x85d: 0x08db,
+ 0x85e: 0x0977, 0x85f: 0x098b, 0x860: 0x09cb, 0x861: 0x09df, 0x862: 0x09e7, 0x863: 0x09eb,
+ 0x864: 0x09fb, 0x865: 0x0a17, 0x866: 0x0a43, 0x867: 0x0a4f, 0x868: 0x0a6f, 0x869: 0x0a7b,
+ 0x86a: 0x0a7f, 0x86b: 0x0a83, 0x86c: 0x0a9b, 0x86d: 0x0a9f, 0x86e: 0x0acb, 0x86f: 0x0ad7,
+ 0x870: 0x0adf, 0x871: 0x0ae7, 0x872: 0x0af7, 0x873: 0x0aff, 0x874: 0x0b07, 0x875: 0x0b33,
+ 0x876: 0x0b37, 0x877: 0x0b3f, 0x878: 0x0b43, 0x879: 0x0b4b, 0x87a: 0x0b53, 0x87b: 0x0b63,
+ 0x87c: 0x0b7f, 0x87d: 0x0bf7, 0x87e: 0x0c0b, 0x87f: 0x0c0f,
+ // Block 0x22, offset 0x880
+ 0x880: 0x0c8f, 0x881: 0x0c93, 0x882: 0x0ca7, 0x883: 0x0cab, 0x884: 0x0cb3, 0x885: 0x0cbb,
+ 0x886: 0x0cc3, 0x887: 0x0ccf, 0x888: 0x0cf7, 0x889: 0x0d07, 0x88a: 0x0d1b, 0x88b: 0x0d8b,
+ 0x88c: 0x0d97, 0x88d: 0x0da7, 0x88e: 0x0db3, 0x88f: 0x0dbf, 0x890: 0x0dc7, 0x891: 0x0dcb,
+ 0x892: 0x0dcf, 0x893: 0x0dd3, 0x894: 0x0dd7, 0x895: 0x0e8f, 0x896: 0x0ed7, 0x897: 0x0ee3,
+ 0x898: 0x0ee7, 0x899: 0x0eeb, 0x89a: 0x0eef, 0x89b: 0x0ef7, 0x89c: 0x0efb, 0x89d: 0x0f0f,
+ 0x89e: 0x0f2b, 0x89f: 0x0f33, 0x8a0: 0x0f73, 0x8a1: 0x0f77, 0x8a2: 0x0f7f, 0x8a3: 0x0f83,
+ 0x8a4: 0x0f8b, 0x8a5: 0x0f8f, 0x8a6: 0x0fb3, 0x8a7: 0x0fb7, 0x8a8: 0x0fd3, 0x8a9: 0x0fd7,
+ 0x8aa: 0x0fdb, 0x8ab: 0x0fdf, 0x8ac: 0x0ff3, 0x8ad: 0x1017, 0x8ae: 0x101b, 0x8af: 0x101f,
+ 0x8b0: 0x1043, 0x8b1: 0x1083, 0x8b2: 0x1087, 0x8b3: 0x10a7, 0x8b4: 0x10b7, 0x8b5: 0x10bf,
+ 0x8b6: 0x10df, 0x8b7: 0x1103, 0x8b8: 0x1147, 0x8b9: 0x114f, 0x8ba: 0x1163, 0x8bb: 0x116f,
+ 0x8bc: 0x1177, 0x8bd: 0x117f, 0x8be: 0x1183, 0x8bf: 0x1187,
+ // Block 0x23, offset 0x8c0
+ 0x8c0: 0x119f, 0x8c1: 0x11a3, 0x8c2: 0x11bf, 0x8c3: 0x11c7, 0x8c4: 0x11cf, 0x8c5: 0x11d3,
+ 0x8c6: 0x11df, 0x8c7: 0x11e7, 0x8c8: 0x11eb, 0x8c9: 0x11ef, 0x8ca: 0x11f7, 0x8cb: 0x11fb,
+ 0x8cc: 0x129b, 0x8cd: 0x12af, 0x8ce: 0x12e3, 0x8cf: 0x12e7, 0x8d0: 0x12ef, 0x8d1: 0x131b,
+ 0x8d2: 0x1323, 0x8d3: 0x132b, 0x8d4: 0x1333, 0x8d5: 0x136f, 0x8d6: 0x1373, 0x8d7: 0x137b,
+ 0x8d8: 0x137f, 0x8d9: 0x1383, 0x8da: 0x13af, 0x8db: 0x13b3, 0x8dc: 0x13bb, 0x8dd: 0x13cf,
+ 0x8de: 0x13d3, 0x8df: 0x13ef, 0x8e0: 0x13f7, 0x8e1: 0x13fb, 0x8e2: 0x141f, 0x8e3: 0x143f,
+ 0x8e4: 0x1453, 0x8e5: 0x1457, 0x8e6: 0x145f, 0x8e7: 0x148b, 0x8e8: 0x148f, 0x8e9: 0x149f,
+ 0x8ea: 0x14c3, 0x8eb: 0x14cf, 0x8ec: 0x14df, 0x8ed: 0x14f7, 0x8ee: 0x14ff, 0x8ef: 0x1503,
+ 0x8f0: 0x1507, 0x8f1: 0x150b, 0x8f2: 0x1517, 0x8f3: 0x151b, 0x8f4: 0x1523, 0x8f5: 0x153f,
+ 0x8f6: 0x1543, 0x8f7: 0x1547, 0x8f8: 0x155f, 0x8f9: 0x1563, 0x8fa: 0x156b, 0x8fb: 0x157f,
+ 0x8fc: 0x1583, 0x8fd: 0x1587, 0x8fe: 0x158f, 0x8ff: 0x1593,
+ // Block 0x24, offset 0x900
+ 0x906: 0xa000, 0x90b: 0xa000,
+ 0x90c: 0x3f08, 0x90d: 0xa000, 0x90e: 0x3f10, 0x90f: 0xa000, 0x910: 0x3f18, 0x911: 0xa000,
+ 0x912: 0x3f20, 0x913: 0xa000, 0x914: 0x3f28, 0x915: 0xa000, 0x916: 0x3f30, 0x917: 0xa000,
+ 0x918: 0x3f38, 0x919: 0xa000, 0x91a: 0x3f40, 0x91b: 0xa000, 0x91c: 0x3f48, 0x91d: 0xa000,
+ 0x91e: 0x3f50, 0x91f: 0xa000, 0x920: 0x3f58, 0x921: 0xa000, 0x922: 0x3f60,
+ 0x924: 0xa000, 0x925: 0x3f68, 0x926: 0xa000, 0x927: 0x3f70, 0x928: 0xa000, 0x929: 0x3f78,
+ 0x92f: 0xa000,
+ 0x930: 0x3f80, 0x931: 0x3f88, 0x932: 0xa000, 0x933: 0x3f90, 0x934: 0x3f98, 0x935: 0xa000,
+ 0x936: 0x3fa0, 0x937: 0x3fa8, 0x938: 0xa000, 0x939: 0x3fb0, 0x93a: 0x3fb8, 0x93b: 0xa000,
+ 0x93c: 0x3fc0, 0x93d: 0x3fc8,
+ // Block 0x25, offset 0x940
+ 0x954: 0x3f00,
+ 0x959: 0x9903, 0x95a: 0x9903, 0x95b: 0x4372, 0x95c: 0x4378, 0x95d: 0xa000,
+ 0x95e: 0x3fd0, 0x95f: 0x26b4,
+ 0x966: 0xa000,
+ 0x96b: 0xa000, 0x96c: 0x3fe0, 0x96d: 0xa000, 0x96e: 0x3fe8, 0x96f: 0xa000,
+ 0x970: 0x3ff0, 0x971: 0xa000, 0x972: 0x3ff8, 0x973: 0xa000, 0x974: 0x4000, 0x975: 0xa000,
+ 0x976: 0x4008, 0x977: 0xa000, 0x978: 0x4010, 0x979: 0xa000, 0x97a: 0x4018, 0x97b: 0xa000,
+ 0x97c: 0x4020, 0x97d: 0xa000, 0x97e: 0x4028, 0x97f: 0xa000,
+ // Block 0x26, offset 0x980
+ 0x980: 0x4030, 0x981: 0xa000, 0x982: 0x4038, 0x984: 0xa000, 0x985: 0x4040,
+ 0x986: 0xa000, 0x987: 0x4048, 0x988: 0xa000, 0x989: 0x4050,
+ 0x98f: 0xa000, 0x990: 0x4058, 0x991: 0x4060,
+ 0x992: 0xa000, 0x993: 0x4068, 0x994: 0x4070, 0x995: 0xa000, 0x996: 0x4078, 0x997: 0x4080,
+ 0x998: 0xa000, 0x999: 0x4088, 0x99a: 0x4090, 0x99b: 0xa000, 0x99c: 0x4098, 0x99d: 0x40a0,
+ 0x9af: 0xa000,
+ 0x9b0: 0xa000, 0x9b1: 0xa000, 0x9b2: 0xa000, 0x9b4: 0x3fd8,
+ 0x9b7: 0x40a8, 0x9b8: 0x40b0, 0x9b9: 0x40b8, 0x9ba: 0x40c0,
+ 0x9bd: 0xa000, 0x9be: 0x40c8, 0x9bf: 0x26c9,
+ // Block 0x27, offset 0x9c0
+ 0x9c0: 0x0367, 0x9c1: 0x032b, 0x9c2: 0x032f, 0x9c3: 0x0333, 0x9c4: 0x037b, 0x9c5: 0x0337,
+ 0x9c6: 0x033b, 0x9c7: 0x033f, 0x9c8: 0x0343, 0x9c9: 0x0347, 0x9ca: 0x034b, 0x9cb: 0x034f,
+ 0x9cc: 0x0353, 0x9cd: 0x0357, 0x9ce: 0x035b, 0x9cf: 0x42dc, 0x9d0: 0x42e1, 0x9d1: 0x42e6,
+ 0x9d2: 0x42eb, 0x9d3: 0x42f0, 0x9d4: 0x42f5, 0x9d5: 0x42fa, 0x9d6: 0x42ff, 0x9d7: 0x4304,
+ 0x9d8: 0x4309, 0x9d9: 0x430e, 0x9da: 0x4313, 0x9db: 0x4318, 0x9dc: 0x431d, 0x9dd: 0x4322,
+ 0x9de: 0x4327, 0x9df: 0x432c, 0x9e0: 0x4331, 0x9e1: 0x4336, 0x9e2: 0x433b, 0x9e3: 0x4340,
+ 0x9e4: 0x03c3, 0x9e5: 0x035f, 0x9e6: 0x0363, 0x9e7: 0x03e7, 0x9e8: 0x03eb, 0x9e9: 0x03ef,
+ 0x9ea: 0x03f3, 0x9eb: 0x03f7, 0x9ec: 0x03fb, 0x9ed: 0x03ff, 0x9ee: 0x036b, 0x9ef: 0x0403,
+ 0x9f0: 0x0407, 0x9f1: 0x036f, 0x9f2: 0x0373, 0x9f3: 0x0377, 0x9f4: 0x037f, 0x9f5: 0x0383,
+ 0x9f6: 0x0387, 0x9f7: 0x038b, 0x9f8: 0x038f, 0x9f9: 0x0393, 0x9fa: 0x0397, 0x9fb: 0x039b,
+ 0x9fc: 0x039f, 0x9fd: 0x03a3, 0x9fe: 0x03a7, 0x9ff: 0x03ab,
+ // Block 0x28, offset 0xa00
+ 0xa00: 0x03af, 0xa01: 0x03b3, 0xa02: 0x040b, 0xa03: 0x040f, 0xa04: 0x03b7, 0xa05: 0x03bb,
+ 0xa06: 0x03bf, 0xa07: 0x03c7, 0xa08: 0x03cb, 0xa09: 0x03cf, 0xa0a: 0x03d3, 0xa0b: 0x03d7,
+ 0xa0c: 0x03db, 0xa0d: 0x03df, 0xa0e: 0x03e3,
+ 0xa12: 0x06bf, 0xa13: 0x071b, 0xa14: 0x06cb, 0xa15: 0x097b, 0xa16: 0x06cf, 0xa17: 0x06e7,
+ 0xa18: 0x06d3, 0xa19: 0x0f93, 0xa1a: 0x0707, 0xa1b: 0x06db, 0xa1c: 0x06c3, 0xa1d: 0x09ff,
+ 0xa1e: 0x098f, 0xa1f: 0x072f,
+ // Block 0x29, offset 0xa40
+ 0xa40: 0x2054, 0xa41: 0x205a, 0xa42: 0x2060, 0xa43: 0x2066, 0xa44: 0x206c, 0xa45: 0x2072,
+ 0xa46: 0x2078, 0xa47: 0x207e, 0xa48: 0x2084, 0xa49: 0x208a, 0xa4a: 0x2090, 0xa4b: 0x2096,
+ 0xa4c: 0x209c, 0xa4d: 0x20a2, 0xa4e: 0x2726, 0xa4f: 0x272f, 0xa50: 0x2738, 0xa51: 0x2741,
+ 0xa52: 0x274a, 0xa53: 0x2753, 0xa54: 0x275c, 0xa55: 0x2765, 0xa56: 0x276e, 0xa57: 0x2780,
+ 0xa58: 0x2789, 0xa59: 0x2792, 0xa5a: 0x279b, 0xa5b: 0x27a4, 0xa5c: 0x2777, 0xa5d: 0x2bac,
+ 0xa5e: 0x2aed, 0xa60: 0x20a8, 0xa61: 0x20c0, 0xa62: 0x20b4, 0xa63: 0x2108,
+ 0xa64: 0x20c6, 0xa65: 0x20e4, 0xa66: 0x20ae, 0xa67: 0x20de, 0xa68: 0x20ba, 0xa69: 0x20f0,
+ 0xa6a: 0x2120, 0xa6b: 0x213e, 0xa6c: 0x2138, 0xa6d: 0x212c, 0xa6e: 0x217a, 0xa6f: 0x210e,
+ 0xa70: 0x211a, 0xa71: 0x2132, 0xa72: 0x2126, 0xa73: 0x2150, 0xa74: 0x20fc, 0xa75: 0x2144,
+ 0xa76: 0x216e, 0xa77: 0x2156, 0xa78: 0x20ea, 0xa79: 0x20cc, 0xa7a: 0x2102, 0xa7b: 0x2114,
+ 0xa7c: 0x214a, 0xa7d: 0x20d2, 0xa7e: 0x2174, 0xa7f: 0x20f6,
+ // Block 0x2a, offset 0xa80
+ 0xa80: 0x215c, 0xa81: 0x20d8, 0xa82: 0x2162, 0xa83: 0x2168, 0xa84: 0x092f, 0xa85: 0x0b03,
+ 0xa86: 0x0ca7, 0xa87: 0x10c7,
+ 0xa90: 0x1bc4, 0xa91: 0x18a9,
+ 0xa92: 0x18ac, 0xa93: 0x18af, 0xa94: 0x18b2, 0xa95: 0x18b5, 0xa96: 0x18b8, 0xa97: 0x18bb,
+ 0xa98: 0x18be, 0xa99: 0x18c1, 0xa9a: 0x18ca, 0xa9b: 0x18cd, 0xa9c: 0x18d0, 0xa9d: 0x18d3,
+ 0xa9e: 0x18d6, 0xa9f: 0x18d9, 0xaa0: 0x0313, 0xaa1: 0x031b, 0xaa2: 0x031f, 0xaa3: 0x0327,
+ 0xaa4: 0x032b, 0xaa5: 0x032f, 0xaa6: 0x0337, 0xaa7: 0x033f, 0xaa8: 0x0343, 0xaa9: 0x034b,
+ 0xaaa: 0x034f, 0xaab: 0x0353, 0xaac: 0x0357, 0xaad: 0x035b, 0xaae: 0x2e18, 0xaaf: 0x2e20,
+ 0xab0: 0x2e28, 0xab1: 0x2e30, 0xab2: 0x2e38, 0xab3: 0x2e40, 0xab4: 0x2e48, 0xab5: 0x2e50,
+ 0xab6: 0x2e60, 0xab7: 0x2e68, 0xab8: 0x2e70, 0xab9: 0x2e78, 0xaba: 0x2e80, 0xabb: 0x2e88,
+ 0xabc: 0x2ed3, 0xabd: 0x2e9b, 0xabe: 0x2e58,
+ // Block 0x2b, offset 0xac0
+ 0xac0: 0x06bf, 0xac1: 0x071b, 0xac2: 0x06cb, 0xac3: 0x097b, 0xac4: 0x071f, 0xac5: 0x07af,
+ 0xac6: 0x06c7, 0xac7: 0x07ab, 0xac8: 0x070b, 0xac9: 0x0887, 0xaca: 0x0d07, 0xacb: 0x0e8f,
+ 0xacc: 0x0dd7, 0xacd: 0x0d1b, 0xace: 0x145f, 0xacf: 0x098b, 0xad0: 0x0ccf, 0xad1: 0x0d4b,
+ 0xad2: 0x0d0b, 0xad3: 0x104b, 0xad4: 0x08fb, 0xad5: 0x0f03, 0xad6: 0x1387, 0xad7: 0x105f,
+ 0xad8: 0x0843, 0xad9: 0x108f, 0xada: 0x0f9b, 0xadb: 0x0a17, 0xadc: 0x140f, 0xadd: 0x077f,
+ 0xade: 0x08ab, 0xadf: 0x0df7, 0xae0: 0x1527, 0xae1: 0x0743, 0xae2: 0x07d3, 0xae3: 0x0d9b,
+ 0xae4: 0x06cf, 0xae5: 0x06e7, 0xae6: 0x06d3, 0xae7: 0x0adb, 0xae8: 0x08ef, 0xae9: 0x087f,
+ 0xaea: 0x0a57, 0xaeb: 0x0a4b, 0xaec: 0x0feb, 0xaed: 0x073f, 0xaee: 0x139b, 0xaef: 0x089b,
+ 0xaf0: 0x09f3, 0xaf1: 0x18dc, 0xaf2: 0x18df, 0xaf3: 0x18e2, 0xaf4: 0x18e5, 0xaf5: 0x18ee,
+ 0xaf6: 0x18f1, 0xaf7: 0x18f4, 0xaf8: 0x18f7, 0xaf9: 0x18fa, 0xafa: 0x18fd, 0xafb: 0x1900,
+ 0xafc: 0x1903, 0xafd: 0x1906, 0xafe: 0x1909, 0xaff: 0x1912,
+ // Block 0x2c, offset 0xb00
+ 0xb00: 0x1cc6, 0xb01: 0x1cd5, 0xb02: 0x1ce4, 0xb03: 0x1cf3, 0xb04: 0x1d02, 0xb05: 0x1d11,
+ 0xb06: 0x1d20, 0xb07: 0x1d2f, 0xb08: 0x1d3e, 0xb09: 0x218c, 0xb0a: 0x219e, 0xb0b: 0x21b0,
+ 0xb0c: 0x1954, 0xb0d: 0x1c04, 0xb0e: 0x19d2, 0xb0f: 0x1ba8, 0xb10: 0x04cb, 0xb11: 0x04d3,
+ 0xb12: 0x04db, 0xb13: 0x04e3, 0xb14: 0x04eb, 0xb15: 0x04ef, 0xb16: 0x04f3, 0xb17: 0x04f7,
+ 0xb18: 0x04fb, 0xb19: 0x04ff, 0xb1a: 0x0503, 0xb1b: 0x0507, 0xb1c: 0x050b, 0xb1d: 0x050f,
+ 0xb1e: 0x0513, 0xb1f: 0x0517, 0xb20: 0x051b, 0xb21: 0x0523, 0xb22: 0x0527, 0xb23: 0x052b,
+ 0xb24: 0x052f, 0xb25: 0x0533, 0xb26: 0x0537, 0xb27: 0x053b, 0xb28: 0x053f, 0xb29: 0x0543,
+ 0xb2a: 0x0547, 0xb2b: 0x054b, 0xb2c: 0x054f, 0xb2d: 0x0553, 0xb2e: 0x0557, 0xb2f: 0x055b,
+ 0xb30: 0x055f, 0xb31: 0x0563, 0xb32: 0x0567, 0xb33: 0x056f, 0xb34: 0x0577, 0xb35: 0x057f,
+ 0xb36: 0x0583, 0xb37: 0x0587, 0xb38: 0x058b, 0xb39: 0x058f, 0xb3a: 0x0593, 0xb3b: 0x0597,
+ 0xb3c: 0x059b, 0xb3d: 0x059f, 0xb3e: 0x05a3,
+ // Block 0x2d, offset 0xb40
+ 0xb40: 0x2b0c, 0xb41: 0x29a8, 0xb42: 0x2b1c, 0xb43: 0x2880, 0xb44: 0x2ee4, 0xb45: 0x288a,
+ 0xb46: 0x2894, 0xb47: 0x2f28, 0xb48: 0x29b5, 0xb49: 0x289e, 0xb4a: 0x28a8, 0xb4b: 0x28b2,
+ 0xb4c: 0x29dc, 0xb4d: 0x29e9, 0xb4e: 0x29c2, 0xb4f: 0x29cf, 0xb50: 0x2ea9, 0xb51: 0x29f6,
+ 0xb52: 0x2a03, 0xb53: 0x2bbe, 0xb54: 0x26bb, 0xb55: 0x2bd1, 0xb56: 0x2be4, 0xb57: 0x2b2c,
+ 0xb58: 0x2a10, 0xb59: 0x2bf7, 0xb5a: 0x2c0a, 0xb5b: 0x2a1d, 0xb5c: 0x28bc, 0xb5d: 0x28c6,
+ 0xb5e: 0x2eb7, 0xb5f: 0x2a2a, 0xb60: 0x2b3c, 0xb61: 0x2ef5, 0xb62: 0x28d0, 0xb63: 0x28da,
+ 0xb64: 0x2a37, 0xb65: 0x28e4, 0xb66: 0x28ee, 0xb67: 0x26d0, 0xb68: 0x26d7, 0xb69: 0x28f8,
+ 0xb6a: 0x2902, 0xb6b: 0x2c1d, 0xb6c: 0x2a44, 0xb6d: 0x2b4c, 0xb6e: 0x2c30, 0xb6f: 0x2a51,
+ 0xb70: 0x2916, 0xb71: 0x290c, 0xb72: 0x2f3c, 0xb73: 0x2a5e, 0xb74: 0x2c43, 0xb75: 0x2920,
+ 0xb76: 0x2b5c, 0xb77: 0x292a, 0xb78: 0x2a78, 0xb79: 0x2934, 0xb7a: 0x2a85, 0xb7b: 0x2f06,
+ 0xb7c: 0x2a6b, 0xb7d: 0x2b6c, 0xb7e: 0x2a92, 0xb7f: 0x26de,
+ // Block 0x2e, offset 0xb80
+ 0xb80: 0x2f17, 0xb81: 0x293e, 0xb82: 0x2948, 0xb83: 0x2a9f, 0xb84: 0x2952, 0xb85: 0x295c,
+ 0xb86: 0x2966, 0xb87: 0x2b7c, 0xb88: 0x2aac, 0xb89: 0x26e5, 0xb8a: 0x2c56, 0xb8b: 0x2e90,
+ 0xb8c: 0x2b8c, 0xb8d: 0x2ab9, 0xb8e: 0x2ec5, 0xb8f: 0x2970, 0xb90: 0x297a, 0xb91: 0x2ac6,
+ 0xb92: 0x26ec, 0xb93: 0x2ad3, 0xb94: 0x2b9c, 0xb95: 0x26f3, 0xb96: 0x2c69, 0xb97: 0x2984,
+ 0xb98: 0x1cb7, 0xb99: 0x1ccb, 0xb9a: 0x1cda, 0xb9b: 0x1ce9, 0xb9c: 0x1cf8, 0xb9d: 0x1d07,
+ 0xb9e: 0x1d16, 0xb9f: 0x1d25, 0xba0: 0x1d34, 0xba1: 0x1d43, 0xba2: 0x2192, 0xba3: 0x21a4,
+ 0xba4: 0x21b6, 0xba5: 0x21c2, 0xba6: 0x21ce, 0xba7: 0x21da, 0xba8: 0x21e6, 0xba9: 0x21f2,
+ 0xbaa: 0x21fe, 0xbab: 0x220a, 0xbac: 0x2246, 0xbad: 0x2252, 0xbae: 0x225e, 0xbaf: 0x226a,
+ 0xbb0: 0x2276, 0xbb1: 0x1c14, 0xbb2: 0x19c6, 0xbb3: 0x1936, 0xbb4: 0x1be4, 0xbb5: 0x1a47,
+ 0xbb6: 0x1a56, 0xbb7: 0x19cc, 0xbb8: 0x1bfc, 0xbb9: 0x1c00, 0xbba: 0x1960, 0xbbb: 0x2701,
+ 0xbbc: 0x270f, 0xbbd: 0x26fa, 0xbbe: 0x2708, 0xbbf: 0x2ae0,
+ // Block 0x2f, offset 0xbc0
+ 0xbc0: 0x1a4a, 0xbc1: 0x1a32, 0xbc2: 0x1c60, 0xbc3: 0x1a1a, 0xbc4: 0x19f3, 0xbc5: 0x1969,
+ 0xbc6: 0x1978, 0xbc7: 0x1948, 0xbc8: 0x1bf0, 0xbc9: 0x1d52, 0xbca: 0x1a4d, 0xbcb: 0x1a35,
+ 0xbcc: 0x1c64, 0xbcd: 0x1c70, 0xbce: 0x1a26, 0xbcf: 0x19fc, 0xbd0: 0x1957, 0xbd1: 0x1c1c,
+ 0xbd2: 0x1bb0, 0xbd3: 0x1b9c, 0xbd4: 0x1bcc, 0xbd5: 0x1c74, 0xbd6: 0x1a29, 0xbd7: 0x19c9,
+ 0xbd8: 0x19ff, 0xbd9: 0x19de, 0xbda: 0x1a41, 0xbdb: 0x1c78, 0xbdc: 0x1a2c, 0xbdd: 0x19c0,
+ 0xbde: 0x1a02, 0xbdf: 0x1c3c, 0xbe0: 0x1bf4, 0xbe1: 0x1a14, 0xbe2: 0x1c24, 0xbe3: 0x1c40,
+ 0xbe4: 0x1bf8, 0xbe5: 0x1a17, 0xbe6: 0x1c28, 0xbe7: 0x22e8, 0xbe8: 0x22fc, 0xbe9: 0x1996,
+ 0xbea: 0x1c20, 0xbeb: 0x1bb4, 0xbec: 0x1ba0, 0xbed: 0x1c48, 0xbee: 0x2716, 0xbef: 0x27ad,
+ 0xbf0: 0x1a59, 0xbf1: 0x1a44, 0xbf2: 0x1c7c, 0xbf3: 0x1a2f, 0xbf4: 0x1a50, 0xbf5: 0x1a38,
+ 0xbf6: 0x1c68, 0xbf7: 0x1a1d, 0xbf8: 0x19f6, 0xbf9: 0x1981, 0xbfa: 0x1a53, 0xbfb: 0x1a3b,
+ 0xbfc: 0x1c6c, 0xbfd: 0x1a20, 0xbfe: 0x19f9, 0xbff: 0x1984,
+ // Block 0x30, offset 0xc00
+ 0xc00: 0x1c2c, 0xc01: 0x1bb8, 0xc02: 0x1d4d, 0xc03: 0x1939, 0xc04: 0x19ba, 0xc05: 0x19bd,
+ 0xc06: 0x22f5, 0xc07: 0x1b94, 0xc08: 0x19c3, 0xc09: 0x194b, 0xc0a: 0x19e1, 0xc0b: 0x194e,
+ 0xc0c: 0x19ea, 0xc0d: 0x196c, 0xc0e: 0x196f, 0xc0f: 0x1a05, 0xc10: 0x1a0b, 0xc11: 0x1a0e,
+ 0xc12: 0x1c30, 0xc13: 0x1a11, 0xc14: 0x1a23, 0xc15: 0x1c38, 0xc16: 0x1c44, 0xc17: 0x1990,
+ 0xc18: 0x1d57, 0xc19: 0x1bbc, 0xc1a: 0x1993, 0xc1b: 0x1a5c, 0xc1c: 0x19a5, 0xc1d: 0x19b4,
+ 0xc1e: 0x22e2, 0xc1f: 0x22dc, 0xc20: 0x1cc1, 0xc21: 0x1cd0, 0xc22: 0x1cdf, 0xc23: 0x1cee,
+ 0xc24: 0x1cfd, 0xc25: 0x1d0c, 0xc26: 0x1d1b, 0xc27: 0x1d2a, 0xc28: 0x1d39, 0xc29: 0x2186,
+ 0xc2a: 0x2198, 0xc2b: 0x21aa, 0xc2c: 0x21bc, 0xc2d: 0x21c8, 0xc2e: 0x21d4, 0xc2f: 0x21e0,
+ 0xc30: 0x21ec, 0xc31: 0x21f8, 0xc32: 0x2204, 0xc33: 0x2240, 0xc34: 0x224c, 0xc35: 0x2258,
+ 0xc36: 0x2264, 0xc37: 0x2270, 0xc38: 0x227c, 0xc39: 0x2282, 0xc3a: 0x2288, 0xc3b: 0x228e,
+ 0xc3c: 0x2294, 0xc3d: 0x22a6, 0xc3e: 0x22ac, 0xc3f: 0x1c10,
+ // Block 0x31, offset 0xc40
+ 0xc40: 0x1377, 0xc41: 0x0cfb, 0xc42: 0x13d3, 0xc43: 0x139f, 0xc44: 0x0e57, 0xc45: 0x06eb,
+ 0xc46: 0x08df, 0xc47: 0x162b, 0xc48: 0x162b, 0xc49: 0x0a0b, 0xc4a: 0x145f, 0xc4b: 0x0943,
+ 0xc4c: 0x0a07, 0xc4d: 0x0bef, 0xc4e: 0x0fcf, 0xc4f: 0x115f, 0xc50: 0x1297, 0xc51: 0x12d3,
+ 0xc52: 0x1307, 0xc53: 0x141b, 0xc54: 0x0d73, 0xc55: 0x0dff, 0xc56: 0x0eab, 0xc57: 0x0f43,
+ 0xc58: 0x125f, 0xc59: 0x1447, 0xc5a: 0x1573, 0xc5b: 0x070f, 0xc5c: 0x08b3, 0xc5d: 0x0d87,
+ 0xc5e: 0x0ecf, 0xc5f: 0x1293, 0xc60: 0x15c3, 0xc61: 0x0ab3, 0xc62: 0x0e77, 0xc63: 0x1283,
+ 0xc64: 0x1317, 0xc65: 0x0c23, 0xc66: 0x11bb, 0xc67: 0x12df, 0xc68: 0x0b1f, 0xc69: 0x0d0f,
+ 0xc6a: 0x0e17, 0xc6b: 0x0f1b, 0xc6c: 0x1427, 0xc6d: 0x074f, 0xc6e: 0x07e7, 0xc6f: 0x0853,
+ 0xc70: 0x0c8b, 0xc71: 0x0d7f, 0xc72: 0x0ecb, 0xc73: 0x0fef, 0xc74: 0x1177, 0xc75: 0x128b,
+ 0xc76: 0x12a3, 0xc77: 0x13c7, 0xc78: 0x14ef, 0xc79: 0x15a3, 0xc7a: 0x15bf, 0xc7b: 0x102b,
+ 0xc7c: 0x106b, 0xc7d: 0x1123, 0xc7e: 0x1243, 0xc7f: 0x147b,
+ // Block 0x32, offset 0xc80
+ 0xc80: 0x15cb, 0xc81: 0x134b, 0xc82: 0x09c7, 0xc83: 0x0b3b, 0xc84: 0x10db, 0xc85: 0x119b,
+ 0xc86: 0x0eff, 0xc87: 0x1033, 0xc88: 0x1397, 0xc89: 0x14e7, 0xc8a: 0x09c3, 0xc8b: 0x0a8f,
+ 0xc8c: 0x0d77, 0xc8d: 0x0e2b, 0xc8e: 0x0e5f, 0xc8f: 0x1113, 0xc90: 0x113b, 0xc91: 0x14a7,
+ 0xc92: 0x084f, 0xc93: 0x11a7, 0xc94: 0x07f3, 0xc95: 0x07ef, 0xc96: 0x1097, 0xc97: 0x1127,
+ 0xc98: 0x125b, 0xc99: 0x14af, 0xc9a: 0x1367, 0xc9b: 0x0c27, 0xc9c: 0x0d73, 0xc9d: 0x1357,
+ 0xc9e: 0x06f7, 0xc9f: 0x0a63, 0xca0: 0x0b93, 0xca1: 0x0f2f, 0xca2: 0x0faf, 0xca3: 0x0873,
+ 0xca4: 0x103b, 0xca5: 0x075f, 0xca6: 0x0b77, 0xca7: 0x06d7, 0xca8: 0x0deb, 0xca9: 0x0ca3,
+ 0xcaa: 0x110f, 0xcab: 0x08c7, 0xcac: 0x09b3, 0xcad: 0x0ffb, 0xcae: 0x1263, 0xcaf: 0x133b,
+ 0xcb0: 0x0db7, 0xcb1: 0x13f7, 0xcb2: 0x0de3, 0xcb3: 0x0c37, 0xcb4: 0x121b, 0xcb5: 0x0c57,
+ 0xcb6: 0x0fab, 0xcb7: 0x072b, 0xcb8: 0x07a7, 0xcb9: 0x07eb, 0xcba: 0x0d53, 0xcbb: 0x10fb,
+ 0xcbc: 0x11f3, 0xcbd: 0x1347, 0xcbe: 0x145b, 0xcbf: 0x085b,
+ // Block 0x33, offset 0xcc0
+ 0xcc0: 0x090f, 0xcc1: 0x0a17, 0xcc2: 0x0b2f, 0xcc3: 0x0cbf, 0xcc4: 0x0e7b, 0xcc5: 0x103f,
+ 0xcc6: 0x1497, 0xcc7: 0x157b, 0xcc8: 0x15cf, 0xcc9: 0x15e7, 0xcca: 0x0837, 0xccb: 0x0cf3,
+ 0xccc: 0x0da3, 0xccd: 0x13eb, 0xcce: 0x0afb, 0xccf: 0x0bd7, 0xcd0: 0x0bf3, 0xcd1: 0x0c83,
+ 0xcd2: 0x0e6b, 0xcd3: 0x0eb7, 0xcd4: 0x0f67, 0xcd5: 0x108b, 0xcd6: 0x112f, 0xcd7: 0x1193,
+ 0xcd8: 0x13db, 0xcd9: 0x126b, 0xcda: 0x1403, 0xcdb: 0x147f, 0xcdc: 0x080f, 0xcdd: 0x083b,
+ 0xcde: 0x0923, 0xcdf: 0x0ea7, 0xce0: 0x12f3, 0xce1: 0x133b, 0xce2: 0x0b1b, 0xce3: 0x0b8b,
+ 0xce4: 0x0c4f, 0xce5: 0x0daf, 0xce6: 0x10d7, 0xce7: 0x0f23, 0xce8: 0x073b, 0xce9: 0x097f,
+ 0xcea: 0x0a63, 0xceb: 0x0ac7, 0xcec: 0x0b97, 0xced: 0x0f3f, 0xcee: 0x0f5b, 0xcef: 0x116b,
+ 0xcf0: 0x118b, 0xcf1: 0x1463, 0xcf2: 0x14e3, 0xcf3: 0x14f3, 0xcf4: 0x152f, 0xcf5: 0x0753,
+ 0xcf6: 0x107f, 0xcf7: 0x144f, 0xcf8: 0x14cb, 0xcf9: 0x0baf, 0xcfa: 0x0717, 0xcfb: 0x0777,
+ 0xcfc: 0x0a67, 0xcfd: 0x0a87, 0xcfe: 0x0caf, 0xcff: 0x0d73,
+ // Block 0x34, offset 0xd00
+ 0xd00: 0x0ec3, 0xd01: 0x0fcb, 0xd02: 0x1277, 0xd03: 0x1417, 0xd04: 0x1623, 0xd05: 0x0ce3,
+ 0xd06: 0x14a3, 0xd07: 0x0833, 0xd08: 0x0d2f, 0xd09: 0x0d3b, 0xd0a: 0x0e0f, 0xd0b: 0x0e47,
+ 0xd0c: 0x0f4b, 0xd0d: 0x0fa7, 0xd0e: 0x1027, 0xd0f: 0x110b, 0xd10: 0x153b, 0xd11: 0x07af,
+ 0xd12: 0x0c03, 0xd13: 0x14b3, 0xd14: 0x0767, 0xd15: 0x0aab, 0xd16: 0x0e2f, 0xd17: 0x13df,
+ 0xd18: 0x0b67, 0xd19: 0x0bb7, 0xd1a: 0x0d43, 0xd1b: 0x0f2f, 0xd1c: 0x14bb, 0xd1d: 0x0817,
+ 0xd1e: 0x08ff, 0xd1f: 0x0a97, 0xd20: 0x0cd3, 0xd21: 0x0d1f, 0xd22: 0x0d5f, 0xd23: 0x0df3,
+ 0xd24: 0x0f47, 0xd25: 0x0fbb, 0xd26: 0x1157, 0xd27: 0x12f7, 0xd28: 0x1303, 0xd29: 0x1457,
+ 0xd2a: 0x14d7, 0xd2b: 0x0883, 0xd2c: 0x0e4b, 0xd2d: 0x0903, 0xd2e: 0x0ec7, 0xd2f: 0x0f6b,
+ 0xd30: 0x1287, 0xd31: 0x14bf, 0xd32: 0x15ab, 0xd33: 0x15d3, 0xd34: 0x0d37, 0xd35: 0x0e27,
+ 0xd36: 0x11c3, 0xd37: 0x10b7, 0xd38: 0x10c3, 0xd39: 0x10e7, 0xd3a: 0x0f17, 0xd3b: 0x0e9f,
+ 0xd3c: 0x1363, 0xd3d: 0x0733, 0xd3e: 0x122b, 0xd3f: 0x081b,
+ // Block 0x35, offset 0xd40
+ 0xd40: 0x080b, 0xd41: 0x0b0b, 0xd42: 0x0c2b, 0xd43: 0x10f3, 0xd44: 0x0a53, 0xd45: 0x0e03,
+ 0xd46: 0x0cef, 0xd47: 0x13e7, 0xd48: 0x12e7, 0xd49: 0x14ab, 0xd4a: 0x1323, 0xd4b: 0x0b27,
+ 0xd4c: 0x0787, 0xd4d: 0x095b, 0xd50: 0x09af,
+ 0xd52: 0x0cdf, 0xd55: 0x07f7, 0xd56: 0x0f1f, 0xd57: 0x0fe3,
+ 0xd58: 0x1047, 0xd59: 0x1063, 0xd5a: 0x1067, 0xd5b: 0x107b, 0xd5c: 0x14fb, 0xd5d: 0x10eb,
+ 0xd5e: 0x116f, 0xd60: 0x128f, 0xd62: 0x1353,
+ 0xd65: 0x1407, 0xd66: 0x1433,
+ 0xd6a: 0x154f, 0xd6b: 0x1553, 0xd6c: 0x1557, 0xd6d: 0x15bb, 0xd6e: 0x142b, 0xd6f: 0x14c7,
+ 0xd70: 0x0757, 0xd71: 0x077b, 0xd72: 0x078f, 0xd73: 0x084b, 0xd74: 0x0857, 0xd75: 0x0897,
+ 0xd76: 0x094b, 0xd77: 0x0967, 0xd78: 0x096f, 0xd79: 0x09ab, 0xd7a: 0x09b7, 0xd7b: 0x0a93,
+ 0xd7c: 0x0a9b, 0xd7d: 0x0ba3, 0xd7e: 0x0bcb, 0xd7f: 0x0bd3,
+ // Block 0x36, offset 0xd80
+ 0xd80: 0x0beb, 0xd81: 0x0c97, 0xd82: 0x0cc7, 0xd83: 0x0ce7, 0xd84: 0x0d57, 0xd85: 0x0e1b,
+ 0xd86: 0x0e37, 0xd87: 0x0e67, 0xd88: 0x0ebb, 0xd89: 0x0edb, 0xd8a: 0x0f4f, 0xd8b: 0x102f,
+ 0xd8c: 0x104b, 0xd8d: 0x1053, 0xd8e: 0x104f, 0xd8f: 0x1057, 0xd90: 0x105b, 0xd91: 0x105f,
+ 0xd92: 0x1073, 0xd93: 0x1077, 0xd94: 0x109b, 0xd95: 0x10af, 0xd96: 0x10cb, 0xd97: 0x112f,
+ 0xd98: 0x1137, 0xd99: 0x113f, 0xd9a: 0x1153, 0xd9b: 0x117b, 0xd9c: 0x11cb, 0xd9d: 0x11ff,
+ 0xd9e: 0x11ff, 0xd9f: 0x1267, 0xda0: 0x130f, 0xda1: 0x1327, 0xda2: 0x135b, 0xda3: 0x135f,
+ 0xda4: 0x13a3, 0xda5: 0x13a7, 0xda6: 0x13ff, 0xda7: 0x1407, 0xda8: 0x14db, 0xda9: 0x151f,
+ 0xdaa: 0x1537, 0xdab: 0x0b9b, 0xdac: 0x171e, 0xdad: 0x11e3,
+ 0xdb0: 0x06df, 0xdb1: 0x07e3, 0xdb2: 0x07a3, 0xdb3: 0x074b, 0xdb4: 0x078b, 0xdb5: 0x07b7,
+ 0xdb6: 0x0847, 0xdb7: 0x0863, 0xdb8: 0x094b, 0xdb9: 0x0937, 0xdba: 0x0947, 0xdbb: 0x0963,
+ 0xdbc: 0x09af, 0xdbd: 0x09bf, 0xdbe: 0x0a03, 0xdbf: 0x0a0f,
+ // Block 0x37, offset 0xdc0
+ 0xdc0: 0x0a2b, 0xdc1: 0x0a3b, 0xdc2: 0x0b23, 0xdc3: 0x0b2b, 0xdc4: 0x0b5b, 0xdc5: 0x0b7b,
+ 0xdc6: 0x0bab, 0xdc7: 0x0bc3, 0xdc8: 0x0bb3, 0xdc9: 0x0bd3, 0xdca: 0x0bc7, 0xdcb: 0x0beb,
+ 0xdcc: 0x0c07, 0xdcd: 0x0c5f, 0xdce: 0x0c6b, 0xdcf: 0x0c73, 0xdd0: 0x0c9b, 0xdd1: 0x0cdf,
+ 0xdd2: 0x0d0f, 0xdd3: 0x0d13, 0xdd4: 0x0d27, 0xdd5: 0x0da7, 0xdd6: 0x0db7, 0xdd7: 0x0e0f,
+ 0xdd8: 0x0e5b, 0xdd9: 0x0e53, 0xdda: 0x0e67, 0xddb: 0x0e83, 0xddc: 0x0ebb, 0xddd: 0x1013,
+ 0xdde: 0x0edf, 0xddf: 0x0f13, 0xde0: 0x0f1f, 0xde1: 0x0f5f, 0xde2: 0x0f7b, 0xde3: 0x0f9f,
+ 0xde4: 0x0fc3, 0xde5: 0x0fc7, 0xde6: 0x0fe3, 0xde7: 0x0fe7, 0xde8: 0x0ff7, 0xde9: 0x100b,
+ 0xdea: 0x1007, 0xdeb: 0x1037, 0xdec: 0x10b3, 0xded: 0x10cb, 0xdee: 0x10e3, 0xdef: 0x111b,
+ 0xdf0: 0x112f, 0xdf1: 0x114b, 0xdf2: 0x117b, 0xdf3: 0x122f, 0xdf4: 0x1257, 0xdf5: 0x12cb,
+ 0xdf6: 0x1313, 0xdf7: 0x131f, 0xdf8: 0x1327, 0xdf9: 0x133f, 0xdfa: 0x1353, 0xdfb: 0x1343,
+ 0xdfc: 0x135b, 0xdfd: 0x1357, 0xdfe: 0x134f, 0xdff: 0x135f,
+ // Block 0x38, offset 0xe00
+ 0xe00: 0x136b, 0xe01: 0x13a7, 0xe02: 0x13e3, 0xe03: 0x1413, 0xe04: 0x144b, 0xe05: 0x146b,
+ 0xe06: 0x14b7, 0xe07: 0x14db, 0xe08: 0x14fb, 0xe09: 0x150f, 0xe0a: 0x151f, 0xe0b: 0x152b,
+ 0xe0c: 0x1537, 0xe0d: 0x158b, 0xe0e: 0x162b, 0xe0f: 0x16b5, 0xe10: 0x16b0, 0xe11: 0x16e2,
+ 0xe12: 0x0607, 0xe13: 0x062f, 0xe14: 0x0633, 0xe15: 0x1764, 0xe16: 0x1791, 0xe17: 0x1809,
+ 0xe18: 0x1617, 0xe19: 0x1627,
+ // Block 0x39, offset 0xe40
+ 0xe40: 0x19d5, 0xe41: 0x19d8, 0xe42: 0x19db, 0xe43: 0x1c08, 0xe44: 0x1c0c, 0xe45: 0x1a5f,
+ 0xe46: 0x1a5f,
+ 0xe53: 0x1d75, 0xe54: 0x1d66, 0xe55: 0x1d6b, 0xe56: 0x1d7a, 0xe57: 0x1d70,
+ 0xe5d: 0x4426,
+ 0xe5e: 0x8115, 0xe5f: 0x4498, 0xe60: 0x022d, 0xe61: 0x0215, 0xe62: 0x021e, 0xe63: 0x0221,
+ 0xe64: 0x0224, 0xe65: 0x0227, 0xe66: 0x022a, 0xe67: 0x0230, 0xe68: 0x0233, 0xe69: 0x0017,
+ 0xe6a: 0x4486, 0xe6b: 0x448c, 0xe6c: 0x458a, 0xe6d: 0x4592, 0xe6e: 0x43de, 0xe6f: 0x43e4,
+ 0xe70: 0x43ea, 0xe71: 0x43f0, 0xe72: 0x43fc, 0xe73: 0x4402, 0xe74: 0x4408, 0xe75: 0x4414,
+ 0xe76: 0x441a, 0xe78: 0x4420, 0xe79: 0x442c, 0xe7a: 0x4432, 0xe7b: 0x4438,
+ 0xe7c: 0x4444, 0xe7e: 0x444a,
+ // Block 0x3a, offset 0xe80
+ 0xe80: 0x4450, 0xe81: 0x4456, 0xe83: 0x445c, 0xe84: 0x4462,
+ 0xe86: 0x446e, 0xe87: 0x4474, 0xe88: 0x447a, 0xe89: 0x4480, 0xe8a: 0x4492, 0xe8b: 0x440e,
+ 0xe8c: 0x43f6, 0xe8d: 0x443e, 0xe8e: 0x4468, 0xe8f: 0x1d7f, 0xe90: 0x0299, 0xe91: 0x0299,
+ 0xe92: 0x02a2, 0xe93: 0x02a2, 0xe94: 0x02a2, 0xe95: 0x02a2, 0xe96: 0x02a5, 0xe97: 0x02a5,
+ 0xe98: 0x02a5, 0xe99: 0x02a5, 0xe9a: 0x02ab, 0xe9b: 0x02ab, 0xe9c: 0x02ab, 0xe9d: 0x02ab,
+ 0xe9e: 0x029f, 0xe9f: 0x029f, 0xea0: 0x029f, 0xea1: 0x029f, 0xea2: 0x02a8, 0xea3: 0x02a8,
+ 0xea4: 0x02a8, 0xea5: 0x02a8, 0xea6: 0x029c, 0xea7: 0x029c, 0xea8: 0x029c, 0xea9: 0x029c,
+ 0xeaa: 0x02cf, 0xeab: 0x02cf, 0xeac: 0x02cf, 0xead: 0x02cf, 0xeae: 0x02d2, 0xeaf: 0x02d2,
+ 0xeb0: 0x02d2, 0xeb1: 0x02d2, 0xeb2: 0x02b1, 0xeb3: 0x02b1, 0xeb4: 0x02b1, 0xeb5: 0x02b1,
+ 0xeb6: 0x02ae, 0xeb7: 0x02ae, 0xeb8: 0x02ae, 0xeb9: 0x02ae, 0xeba: 0x02b4, 0xebb: 0x02b4,
+ 0xebc: 0x02b4, 0xebd: 0x02b4, 0xebe: 0x02b7, 0xebf: 0x02b7,
+ // Block 0x3b, offset 0xec0
+ 0xec0: 0x02b7, 0xec1: 0x02b7, 0xec2: 0x02c0, 0xec3: 0x02c0, 0xec4: 0x02bd, 0xec5: 0x02bd,
+ 0xec6: 0x02c3, 0xec7: 0x02c3, 0xec8: 0x02ba, 0xec9: 0x02ba, 0xeca: 0x02c9, 0xecb: 0x02c9,
+ 0xecc: 0x02c6, 0xecd: 0x02c6, 0xece: 0x02d5, 0xecf: 0x02d5, 0xed0: 0x02d5, 0xed1: 0x02d5,
+ 0xed2: 0x02db, 0xed3: 0x02db, 0xed4: 0x02db, 0xed5: 0x02db, 0xed6: 0x02e1, 0xed7: 0x02e1,
+ 0xed8: 0x02e1, 0xed9: 0x02e1, 0xeda: 0x02de, 0xedb: 0x02de, 0xedc: 0x02de, 0xedd: 0x02de,
+ 0xede: 0x02e4, 0xedf: 0x02e4, 0xee0: 0x02e7, 0xee1: 0x02e7, 0xee2: 0x02e7, 0xee3: 0x02e7,
+ 0xee4: 0x4504, 0xee5: 0x4504, 0xee6: 0x02ed, 0xee7: 0x02ed, 0xee8: 0x02ed, 0xee9: 0x02ed,
+ 0xeea: 0x02ea, 0xeeb: 0x02ea, 0xeec: 0x02ea, 0xeed: 0x02ea, 0xeee: 0x0308, 0xeef: 0x0308,
+ 0xef0: 0x44fe, 0xef1: 0x44fe,
+ // Block 0x3c, offset 0xf00
+ 0xf13: 0x02d8, 0xf14: 0x02d8, 0xf15: 0x02d8, 0xf16: 0x02d8, 0xf17: 0x02f6,
+ 0xf18: 0x02f6, 0xf19: 0x02f3, 0xf1a: 0x02f3, 0xf1b: 0x02f9, 0xf1c: 0x02f9, 0xf1d: 0x204f,
+ 0xf1e: 0x02ff, 0xf1f: 0x02ff, 0xf20: 0x02f0, 0xf21: 0x02f0, 0xf22: 0x02fc, 0xf23: 0x02fc,
+ 0xf24: 0x0305, 0xf25: 0x0305, 0xf26: 0x0305, 0xf27: 0x0305, 0xf28: 0x028d, 0xf29: 0x028d,
+ 0xf2a: 0x25aa, 0xf2b: 0x25aa, 0xf2c: 0x261a, 0xf2d: 0x261a, 0xf2e: 0x25e9, 0xf2f: 0x25e9,
+ 0xf30: 0x2605, 0xf31: 0x2605, 0xf32: 0x25fe, 0xf33: 0x25fe, 0xf34: 0x260c, 0xf35: 0x260c,
+ 0xf36: 0x2613, 0xf37: 0x2613, 0xf38: 0x2613, 0xf39: 0x25f0, 0xf3a: 0x25f0, 0xf3b: 0x25f0,
+ 0xf3c: 0x0302, 0xf3d: 0x0302, 0xf3e: 0x0302, 0xf3f: 0x0302,
+ // Block 0x3d, offset 0xf40
+ 0xf40: 0x25b1, 0xf41: 0x25b8, 0xf42: 0x25d4, 0xf43: 0x25f0, 0xf44: 0x25f7, 0xf45: 0x1d89,
+ 0xf46: 0x1d8e, 0xf47: 0x1d93, 0xf48: 0x1da2, 0xf49: 0x1db1, 0xf4a: 0x1db6, 0xf4b: 0x1dbb,
+ 0xf4c: 0x1dc0, 0xf4d: 0x1dc5, 0xf4e: 0x1dd4, 0xf4f: 0x1de3, 0xf50: 0x1de8, 0xf51: 0x1ded,
+ 0xf52: 0x1dfc, 0xf53: 0x1e0b, 0xf54: 0x1e10, 0xf55: 0x1e15, 0xf56: 0x1e1a, 0xf57: 0x1e29,
+ 0xf58: 0x1e2e, 0xf59: 0x1e3d, 0xf5a: 0x1e42, 0xf5b: 0x1e47, 0xf5c: 0x1e56, 0xf5d: 0x1e5b,
+ 0xf5e: 0x1e60, 0xf5f: 0x1e6a, 0xf60: 0x1ea6, 0xf61: 0x1eb5, 0xf62: 0x1ec4, 0xf63: 0x1ec9,
+ 0xf64: 0x1ece, 0xf65: 0x1ed8, 0xf66: 0x1ee7, 0xf67: 0x1eec, 0xf68: 0x1efb, 0xf69: 0x1f00,
+ 0xf6a: 0x1f05, 0xf6b: 0x1f14, 0xf6c: 0x1f19, 0xf6d: 0x1f28, 0xf6e: 0x1f2d, 0xf6f: 0x1f32,
+ 0xf70: 0x1f37, 0xf71: 0x1f3c, 0xf72: 0x1f41, 0xf73: 0x1f46, 0xf74: 0x1f4b, 0xf75: 0x1f50,
+ 0xf76: 0x1f55, 0xf77: 0x1f5a, 0xf78: 0x1f5f, 0xf79: 0x1f64, 0xf7a: 0x1f69, 0xf7b: 0x1f6e,
+ 0xf7c: 0x1f73, 0xf7d: 0x1f78, 0xf7e: 0x1f7d, 0xf7f: 0x1f87,
+ // Block 0x3e, offset 0xf80
+ 0xf80: 0x1f8c, 0xf81: 0x1f91, 0xf82: 0x1f96, 0xf83: 0x1fa0, 0xf84: 0x1fa5, 0xf85: 0x1faf,
+ 0xf86: 0x1fb4, 0xf87: 0x1fb9, 0xf88: 0x1fbe, 0xf89: 0x1fc3, 0xf8a: 0x1fc8, 0xf8b: 0x1fcd,
+ 0xf8c: 0x1fd2, 0xf8d: 0x1fd7, 0xf8e: 0x1fe6, 0xf8f: 0x1ff5, 0xf90: 0x1ffa, 0xf91: 0x1fff,
+ 0xf92: 0x2004, 0xf93: 0x2009, 0xf94: 0x200e, 0xf95: 0x2018, 0xf96: 0x201d, 0xf97: 0x2022,
+ 0xf98: 0x2031, 0xf99: 0x2040, 0xf9a: 0x2045, 0xf9b: 0x44b6, 0xf9c: 0x44bc, 0xf9d: 0x44f2,
+ 0xf9e: 0x4549, 0xf9f: 0x4550, 0xfa0: 0x4557, 0xfa1: 0x455e, 0xfa2: 0x4565, 0xfa3: 0x456c,
+ 0xfa4: 0x25c6, 0xfa5: 0x25cd, 0xfa6: 0x25d4, 0xfa7: 0x25db, 0xfa8: 0x25f0, 0xfa9: 0x25f7,
+ 0xfaa: 0x1d98, 0xfab: 0x1d9d, 0xfac: 0x1da2, 0xfad: 0x1da7, 0xfae: 0x1db1, 0xfaf: 0x1db6,
+ 0xfb0: 0x1dca, 0xfb1: 0x1dcf, 0xfb2: 0x1dd4, 0xfb3: 0x1dd9, 0xfb4: 0x1de3, 0xfb5: 0x1de8,
+ 0xfb6: 0x1df2, 0xfb7: 0x1df7, 0xfb8: 0x1dfc, 0xfb9: 0x1e01, 0xfba: 0x1e0b, 0xfbb: 0x1e10,
+ 0xfbc: 0x1f3c, 0xfbd: 0x1f41, 0xfbe: 0x1f50, 0xfbf: 0x1f55,
+ // Block 0x3f, offset 0xfc0
+ 0xfc0: 0x1f5a, 0xfc1: 0x1f6e, 0xfc2: 0x1f73, 0xfc3: 0x1f78, 0xfc4: 0x1f7d, 0xfc5: 0x1f96,
+ 0xfc6: 0x1fa0, 0xfc7: 0x1fa5, 0xfc8: 0x1faa, 0xfc9: 0x1fbe, 0xfca: 0x1fdc, 0xfcb: 0x1fe1,
+ 0xfcc: 0x1fe6, 0xfcd: 0x1feb, 0xfce: 0x1ff5, 0xfcf: 0x1ffa, 0xfd0: 0x44f2, 0xfd1: 0x2027,
+ 0xfd2: 0x202c, 0xfd3: 0x2031, 0xfd4: 0x2036, 0xfd5: 0x2040, 0xfd6: 0x2045, 0xfd7: 0x25b1,
+ 0xfd8: 0x25b8, 0xfd9: 0x25bf, 0xfda: 0x25d4, 0xfdb: 0x25e2, 0xfdc: 0x1d89, 0xfdd: 0x1d8e,
+ 0xfde: 0x1d93, 0xfdf: 0x1da2, 0xfe0: 0x1dac, 0xfe1: 0x1dbb, 0xfe2: 0x1dc0, 0xfe3: 0x1dc5,
+ 0xfe4: 0x1dd4, 0xfe5: 0x1dde, 0xfe6: 0x1dfc, 0xfe7: 0x1e15, 0xfe8: 0x1e1a, 0xfe9: 0x1e29,
+ 0xfea: 0x1e2e, 0xfeb: 0x1e3d, 0xfec: 0x1e47, 0xfed: 0x1e56, 0xfee: 0x1e5b, 0xfef: 0x1e60,
+ 0xff0: 0x1e6a, 0xff1: 0x1ea6, 0xff2: 0x1eab, 0xff3: 0x1eb5, 0xff4: 0x1ec4, 0xff5: 0x1ec9,
+ 0xff6: 0x1ece, 0xff7: 0x1ed8, 0xff8: 0x1ee7, 0xff9: 0x1efb, 0xffa: 0x1f00, 0xffb: 0x1f05,
+ 0xffc: 0x1f14, 0xffd: 0x1f19, 0xffe: 0x1f28, 0xfff: 0x1f2d,
+ // Block 0x40, offset 0x1000
+ 0x1000: 0x1f32, 0x1001: 0x1f37, 0x1002: 0x1f46, 0x1003: 0x1f4b, 0x1004: 0x1f5f, 0x1005: 0x1f64,
+ 0x1006: 0x1f69, 0x1007: 0x1f6e, 0x1008: 0x1f73, 0x1009: 0x1f87, 0x100a: 0x1f8c, 0x100b: 0x1f91,
+ 0x100c: 0x1f96, 0x100d: 0x1f9b, 0x100e: 0x1faf, 0x100f: 0x1fb4, 0x1010: 0x1fb9, 0x1011: 0x1fbe,
+ 0x1012: 0x1fcd, 0x1013: 0x1fd2, 0x1014: 0x1fd7, 0x1015: 0x1fe6, 0x1016: 0x1ff0, 0x1017: 0x1fff,
+ 0x1018: 0x2004, 0x1019: 0x44e6, 0x101a: 0x2018, 0x101b: 0x201d, 0x101c: 0x2022, 0x101d: 0x2031,
+ 0x101e: 0x203b, 0x101f: 0x25d4, 0x1020: 0x25e2, 0x1021: 0x1da2, 0x1022: 0x1dac, 0x1023: 0x1dd4,
+ 0x1024: 0x1dde, 0x1025: 0x1dfc, 0x1026: 0x1e06, 0x1027: 0x1e6a, 0x1028: 0x1e6f, 0x1029: 0x1e92,
+ 0x102a: 0x1e97, 0x102b: 0x1f6e, 0x102c: 0x1f73, 0x102d: 0x1f96, 0x102e: 0x1fe6, 0x102f: 0x1ff0,
+ 0x1030: 0x2031, 0x1031: 0x203b, 0x1032: 0x459a, 0x1033: 0x45a2, 0x1034: 0x45aa, 0x1035: 0x1ef1,
+ 0x1036: 0x1ef6, 0x1037: 0x1f0a, 0x1038: 0x1f0f, 0x1039: 0x1f1e, 0x103a: 0x1f23, 0x103b: 0x1e74,
+ 0x103c: 0x1e79, 0x103d: 0x1e9c, 0x103e: 0x1ea1, 0x103f: 0x1e33,
+ // Block 0x41, offset 0x1040
+ 0x1040: 0x1e38, 0x1041: 0x1e1f, 0x1042: 0x1e24, 0x1043: 0x1e4c, 0x1044: 0x1e51, 0x1045: 0x1eba,
+ 0x1046: 0x1ebf, 0x1047: 0x1edd, 0x1048: 0x1ee2, 0x1049: 0x1e7e, 0x104a: 0x1e83, 0x104b: 0x1e88,
+ 0x104c: 0x1e92, 0x104d: 0x1e8d, 0x104e: 0x1e65, 0x104f: 0x1eb0, 0x1050: 0x1ed3, 0x1051: 0x1ef1,
+ 0x1052: 0x1ef6, 0x1053: 0x1f0a, 0x1054: 0x1f0f, 0x1055: 0x1f1e, 0x1056: 0x1f23, 0x1057: 0x1e74,
+ 0x1058: 0x1e79, 0x1059: 0x1e9c, 0x105a: 0x1ea1, 0x105b: 0x1e33, 0x105c: 0x1e38, 0x105d: 0x1e1f,
+ 0x105e: 0x1e24, 0x105f: 0x1e4c, 0x1060: 0x1e51, 0x1061: 0x1eba, 0x1062: 0x1ebf, 0x1063: 0x1edd,
+ 0x1064: 0x1ee2, 0x1065: 0x1e7e, 0x1066: 0x1e83, 0x1067: 0x1e88, 0x1068: 0x1e92, 0x1069: 0x1e8d,
+ 0x106a: 0x1e65, 0x106b: 0x1eb0, 0x106c: 0x1ed3, 0x106d: 0x1e7e, 0x106e: 0x1e83, 0x106f: 0x1e88,
+ 0x1070: 0x1e92, 0x1071: 0x1e6f, 0x1072: 0x1e97, 0x1073: 0x1eec, 0x1074: 0x1e56, 0x1075: 0x1e5b,
+ 0x1076: 0x1e60, 0x1077: 0x1e7e, 0x1078: 0x1e83, 0x1079: 0x1e88, 0x107a: 0x1eec, 0x107b: 0x1efb,
+ 0x107c: 0x449e, 0x107d: 0x449e,
+ // Block 0x42, offset 0x1080
+ 0x1090: 0x2311, 0x1091: 0x2326,
+ 0x1092: 0x2326, 0x1093: 0x232d, 0x1094: 0x2334, 0x1095: 0x2349, 0x1096: 0x2350, 0x1097: 0x2357,
+ 0x1098: 0x237a, 0x1099: 0x237a, 0x109a: 0x239d, 0x109b: 0x2396, 0x109c: 0x23b2, 0x109d: 0x23a4,
+ 0x109e: 0x23ab, 0x109f: 0x23ce, 0x10a0: 0x23ce, 0x10a1: 0x23c7, 0x10a2: 0x23d5, 0x10a3: 0x23d5,
+ 0x10a4: 0x23ff, 0x10a5: 0x23ff, 0x10a6: 0x241b, 0x10a7: 0x23e3, 0x10a8: 0x23e3, 0x10a9: 0x23dc,
+ 0x10aa: 0x23f1, 0x10ab: 0x23f1, 0x10ac: 0x23f8, 0x10ad: 0x23f8, 0x10ae: 0x2422, 0x10af: 0x2430,
+ 0x10b0: 0x2430, 0x10b1: 0x2437, 0x10b2: 0x2437, 0x10b3: 0x243e, 0x10b4: 0x2445, 0x10b5: 0x244c,
+ 0x10b6: 0x2453, 0x10b7: 0x2453, 0x10b8: 0x245a, 0x10b9: 0x2468, 0x10ba: 0x2476, 0x10bb: 0x246f,
+ 0x10bc: 0x247d, 0x10bd: 0x247d, 0x10be: 0x2492, 0x10bf: 0x2499,
+ // Block 0x43, offset 0x10c0
+ 0x10c0: 0x24ca, 0x10c1: 0x24d8, 0x10c2: 0x24d1, 0x10c3: 0x24b5, 0x10c4: 0x24b5, 0x10c5: 0x24df,
+ 0x10c6: 0x24df, 0x10c7: 0x24e6, 0x10c8: 0x24e6, 0x10c9: 0x2510, 0x10ca: 0x2517, 0x10cb: 0x251e,
+ 0x10cc: 0x24f4, 0x10cd: 0x2502, 0x10ce: 0x2525, 0x10cf: 0x252c,
+ 0x10d2: 0x24fb, 0x10d3: 0x2580, 0x10d4: 0x2587, 0x10d5: 0x255d, 0x10d6: 0x2564, 0x10d7: 0x2548,
+ 0x10d8: 0x2548, 0x10d9: 0x254f, 0x10da: 0x2579, 0x10db: 0x2572, 0x10dc: 0x259c, 0x10dd: 0x259c,
+ 0x10de: 0x230a, 0x10df: 0x231f, 0x10e0: 0x2318, 0x10e1: 0x2342, 0x10e2: 0x233b, 0x10e3: 0x2365,
+ 0x10e4: 0x235e, 0x10e5: 0x2388, 0x10e6: 0x236c, 0x10e7: 0x2381, 0x10e8: 0x23b9, 0x10e9: 0x2406,
+ 0x10ea: 0x23ea, 0x10eb: 0x2429, 0x10ec: 0x24c3, 0x10ed: 0x24ed, 0x10ee: 0x2595, 0x10ef: 0x258e,
+ 0x10f0: 0x25a3, 0x10f1: 0x253a, 0x10f2: 0x24a0, 0x10f3: 0x256b, 0x10f4: 0x2492, 0x10f5: 0x24ca,
+ 0x10f6: 0x2461, 0x10f7: 0x24ae, 0x10f8: 0x2541, 0x10f9: 0x2533, 0x10fa: 0x24bc, 0x10fb: 0x24a7,
+ 0x10fc: 0x24bc, 0x10fd: 0x2541, 0x10fe: 0x2373, 0x10ff: 0x238f,
+ // Block 0x44, offset 0x1100
+ 0x1100: 0x2509, 0x1101: 0x2484, 0x1102: 0x2303, 0x1103: 0x24a7, 0x1104: 0x244c, 0x1105: 0x241b,
+ 0x1106: 0x23c0, 0x1107: 0x2556,
+ 0x1130: 0x2414, 0x1131: 0x248b, 0x1132: 0x27bf, 0x1133: 0x27b6, 0x1134: 0x27ec, 0x1135: 0x27da,
+ 0x1136: 0x27c8, 0x1137: 0x27e3, 0x1138: 0x27f5, 0x1139: 0x240d, 0x113a: 0x2c7c, 0x113b: 0x2afc,
+ 0x113c: 0x27d1,
+ // Block 0x45, offset 0x1140
+ 0x1150: 0x0019, 0x1151: 0x0483,
+ 0x1152: 0x0487, 0x1153: 0x0035, 0x1154: 0x0037, 0x1155: 0x0003, 0x1156: 0x003f, 0x1157: 0x04bf,
+ 0x1158: 0x04c3, 0x1159: 0x1b5c,
+ 0x1160: 0x8132, 0x1161: 0x8132, 0x1162: 0x8132, 0x1163: 0x8132,
+ 0x1164: 0x8132, 0x1165: 0x8132, 0x1166: 0x8132, 0x1167: 0x812d, 0x1168: 0x812d, 0x1169: 0x812d,
+ 0x116a: 0x812d, 0x116b: 0x812d, 0x116c: 0x812d, 0x116d: 0x812d, 0x116e: 0x8132, 0x116f: 0x8132,
+ 0x1170: 0x1873, 0x1171: 0x0443, 0x1172: 0x043f, 0x1173: 0x007f, 0x1174: 0x007f, 0x1175: 0x0011,
+ 0x1176: 0x0013, 0x1177: 0x00b7, 0x1178: 0x00bb, 0x1179: 0x04b7, 0x117a: 0x04bb, 0x117b: 0x04ab,
+ 0x117c: 0x04af, 0x117d: 0x0493, 0x117e: 0x0497, 0x117f: 0x048b,
+ // Block 0x46, offset 0x1180
+ 0x1180: 0x048f, 0x1181: 0x049b, 0x1182: 0x049f, 0x1183: 0x04a3, 0x1184: 0x04a7,
+ 0x1187: 0x0077, 0x1188: 0x007b, 0x1189: 0x4269, 0x118a: 0x4269, 0x118b: 0x4269,
+ 0x118c: 0x4269, 0x118d: 0x007f, 0x118e: 0x007f, 0x118f: 0x007f, 0x1190: 0x0019, 0x1191: 0x0483,
+ 0x1192: 0x001d, 0x1194: 0x0037, 0x1195: 0x0035, 0x1196: 0x003f, 0x1197: 0x0003,
+ 0x1198: 0x0443, 0x1199: 0x0011, 0x119a: 0x0013, 0x119b: 0x00b7, 0x119c: 0x00bb, 0x119d: 0x04b7,
+ 0x119e: 0x04bb, 0x119f: 0x0007, 0x11a0: 0x000d, 0x11a1: 0x0015, 0x11a2: 0x0017, 0x11a3: 0x001b,
+ 0x11a4: 0x0039, 0x11a5: 0x003d, 0x11a6: 0x003b, 0x11a8: 0x0079, 0x11a9: 0x0009,
+ 0x11aa: 0x000b, 0x11ab: 0x0041,
+ 0x11b0: 0x42aa, 0x11b1: 0x44c2, 0x11b2: 0x42af, 0x11b4: 0x42b4,
+ 0x11b6: 0x42b9, 0x11b7: 0x44c8, 0x11b8: 0x42be, 0x11b9: 0x44ce, 0x11ba: 0x42c3, 0x11bb: 0x44d4,
+ 0x11bc: 0x42c8, 0x11bd: 0x44da, 0x11be: 0x42cd, 0x11bf: 0x44e0,
+ // Block 0x47, offset 0x11c0
+ 0x11c0: 0x0236, 0x11c1: 0x44a4, 0x11c2: 0x44a4, 0x11c3: 0x44aa, 0x11c4: 0x44aa, 0x11c5: 0x44ec,
+ 0x11c6: 0x44ec, 0x11c7: 0x44b0, 0x11c8: 0x44b0, 0x11c9: 0x44f8, 0x11ca: 0x44f8, 0x11cb: 0x44f8,
+ 0x11cc: 0x44f8, 0x11cd: 0x0239, 0x11ce: 0x0239, 0x11cf: 0x023c, 0x11d0: 0x023c, 0x11d1: 0x023c,
+ 0x11d2: 0x023c, 0x11d3: 0x023f, 0x11d4: 0x023f, 0x11d5: 0x0242, 0x11d6: 0x0242, 0x11d7: 0x0242,
+ 0x11d8: 0x0242, 0x11d9: 0x0245, 0x11da: 0x0245, 0x11db: 0x0245, 0x11dc: 0x0245, 0x11dd: 0x0248,
+ 0x11de: 0x0248, 0x11df: 0x0248, 0x11e0: 0x0248, 0x11e1: 0x024b, 0x11e2: 0x024b, 0x11e3: 0x024b,
+ 0x11e4: 0x024b, 0x11e5: 0x024e, 0x11e6: 0x024e, 0x11e7: 0x024e, 0x11e8: 0x024e, 0x11e9: 0x0251,
+ 0x11ea: 0x0251, 0x11eb: 0x0254, 0x11ec: 0x0254, 0x11ed: 0x0257, 0x11ee: 0x0257, 0x11ef: 0x025a,
+ 0x11f0: 0x025a, 0x11f1: 0x025d, 0x11f2: 0x025d, 0x11f3: 0x025d, 0x11f4: 0x025d, 0x11f5: 0x0260,
+ 0x11f6: 0x0260, 0x11f7: 0x0260, 0x11f8: 0x0260, 0x11f9: 0x0263, 0x11fa: 0x0263, 0x11fb: 0x0263,
+ 0x11fc: 0x0263, 0x11fd: 0x0266, 0x11fe: 0x0266, 0x11ff: 0x0266,
+ // Block 0x48, offset 0x1200
+ 0x1200: 0x0266, 0x1201: 0x0269, 0x1202: 0x0269, 0x1203: 0x0269, 0x1204: 0x0269, 0x1205: 0x026c,
+ 0x1206: 0x026c, 0x1207: 0x026c, 0x1208: 0x026c, 0x1209: 0x026f, 0x120a: 0x026f, 0x120b: 0x026f,
+ 0x120c: 0x026f, 0x120d: 0x0272, 0x120e: 0x0272, 0x120f: 0x0272, 0x1210: 0x0272, 0x1211: 0x0275,
+ 0x1212: 0x0275, 0x1213: 0x0275, 0x1214: 0x0275, 0x1215: 0x0278, 0x1216: 0x0278, 0x1217: 0x0278,
+ 0x1218: 0x0278, 0x1219: 0x027b, 0x121a: 0x027b, 0x121b: 0x027b, 0x121c: 0x027b, 0x121d: 0x027e,
+ 0x121e: 0x027e, 0x121f: 0x027e, 0x1220: 0x027e, 0x1221: 0x0281, 0x1222: 0x0281, 0x1223: 0x0281,
+ 0x1224: 0x0281, 0x1225: 0x0284, 0x1226: 0x0284, 0x1227: 0x0284, 0x1228: 0x0284, 0x1229: 0x0287,
+ 0x122a: 0x0287, 0x122b: 0x0287, 0x122c: 0x0287, 0x122d: 0x028a, 0x122e: 0x028a, 0x122f: 0x028d,
+ 0x1230: 0x028d, 0x1231: 0x0290, 0x1232: 0x0290, 0x1233: 0x0290, 0x1234: 0x0290, 0x1235: 0x2e00,
+ 0x1236: 0x2e00, 0x1237: 0x2e08, 0x1238: 0x2e08, 0x1239: 0x2e10, 0x123a: 0x2e10, 0x123b: 0x1f82,
+ 0x123c: 0x1f82,
+ // Block 0x49, offset 0x1240
+ 0x1240: 0x0081, 0x1241: 0x0083, 0x1242: 0x0085, 0x1243: 0x0087, 0x1244: 0x0089, 0x1245: 0x008b,
+ 0x1246: 0x008d, 0x1247: 0x008f, 0x1248: 0x0091, 0x1249: 0x0093, 0x124a: 0x0095, 0x124b: 0x0097,
+ 0x124c: 0x0099, 0x124d: 0x009b, 0x124e: 0x009d, 0x124f: 0x009f, 0x1250: 0x00a1, 0x1251: 0x00a3,
+ 0x1252: 0x00a5, 0x1253: 0x00a7, 0x1254: 0x00a9, 0x1255: 0x00ab, 0x1256: 0x00ad, 0x1257: 0x00af,
+ 0x1258: 0x00b1, 0x1259: 0x00b3, 0x125a: 0x00b5, 0x125b: 0x00b7, 0x125c: 0x00b9, 0x125d: 0x00bb,
+ 0x125e: 0x00bd, 0x125f: 0x0477, 0x1260: 0x047b, 0x1261: 0x0487, 0x1262: 0x049b, 0x1263: 0x049f,
+ 0x1264: 0x0483, 0x1265: 0x05ab, 0x1266: 0x05a3, 0x1267: 0x04c7, 0x1268: 0x04cf, 0x1269: 0x04d7,
+ 0x126a: 0x04df, 0x126b: 0x04e7, 0x126c: 0x056b, 0x126d: 0x0573, 0x126e: 0x057b, 0x126f: 0x051f,
+ 0x1270: 0x05af, 0x1271: 0x04cb, 0x1272: 0x04d3, 0x1273: 0x04db, 0x1274: 0x04e3, 0x1275: 0x04eb,
+ 0x1276: 0x04ef, 0x1277: 0x04f3, 0x1278: 0x04f7, 0x1279: 0x04fb, 0x127a: 0x04ff, 0x127b: 0x0503,
+ 0x127c: 0x0507, 0x127d: 0x050b, 0x127e: 0x050f, 0x127f: 0x0513,
+ // Block 0x4a, offset 0x1280
+ 0x1280: 0x0517, 0x1281: 0x051b, 0x1282: 0x0523, 0x1283: 0x0527, 0x1284: 0x052b, 0x1285: 0x052f,
+ 0x1286: 0x0533, 0x1287: 0x0537, 0x1288: 0x053b, 0x1289: 0x053f, 0x128a: 0x0543, 0x128b: 0x0547,
+ 0x128c: 0x054b, 0x128d: 0x054f, 0x128e: 0x0553, 0x128f: 0x0557, 0x1290: 0x055b, 0x1291: 0x055f,
+ 0x1292: 0x0563, 0x1293: 0x0567, 0x1294: 0x056f, 0x1295: 0x0577, 0x1296: 0x057f, 0x1297: 0x0583,
+ 0x1298: 0x0587, 0x1299: 0x058b, 0x129a: 0x058f, 0x129b: 0x0593, 0x129c: 0x0597, 0x129d: 0x05a7,
+ 0x129e: 0x4a5a, 0x129f: 0x4a60, 0x12a0: 0x03c3, 0x12a1: 0x0313, 0x12a2: 0x0317, 0x12a3: 0x4345,
+ 0x12a4: 0x031b, 0x12a5: 0x434a, 0x12a6: 0x434f, 0x12a7: 0x031f, 0x12a8: 0x0323, 0x12a9: 0x0327,
+ 0x12aa: 0x4354, 0x12ab: 0x4359, 0x12ac: 0x435e, 0x12ad: 0x4363, 0x12ae: 0x4368, 0x12af: 0x436d,
+ 0x12b0: 0x0367, 0x12b1: 0x032b, 0x12b2: 0x032f, 0x12b3: 0x0333, 0x12b4: 0x037b, 0x12b5: 0x0337,
+ 0x12b6: 0x033b, 0x12b7: 0x033f, 0x12b8: 0x0343, 0x12b9: 0x0347, 0x12ba: 0x034b, 0x12bb: 0x034f,
+ 0x12bc: 0x0353, 0x12bd: 0x0357, 0x12be: 0x035b,
+ // Block 0x4b, offset 0x12c0
+ 0x12c2: 0x42dc, 0x12c3: 0x42e1, 0x12c4: 0x42e6, 0x12c5: 0x42eb,
+ 0x12c6: 0x42f0, 0x12c7: 0x42f5, 0x12ca: 0x42fa, 0x12cb: 0x42ff,
+ 0x12cc: 0x4304, 0x12cd: 0x4309, 0x12ce: 0x430e, 0x12cf: 0x4313,
+ 0x12d2: 0x4318, 0x12d3: 0x431d, 0x12d4: 0x4322, 0x12d5: 0x4327, 0x12d6: 0x432c, 0x12d7: 0x4331,
+ 0x12da: 0x4336, 0x12db: 0x433b, 0x12dc: 0x4340,
+ 0x12e0: 0x00bf, 0x12e1: 0x00c2, 0x12e2: 0x00cb, 0x12e3: 0x4264,
+ 0x12e4: 0x00c8, 0x12e5: 0x00c5, 0x12e6: 0x0447, 0x12e8: 0x046b, 0x12e9: 0x044b,
+ 0x12ea: 0x044f, 0x12eb: 0x0453, 0x12ec: 0x0457, 0x12ed: 0x046f, 0x12ee: 0x0473,
+ // Block 0x4c, offset 0x1300
+ 0x1300: 0x0063, 0x1301: 0x0065, 0x1302: 0x0067, 0x1303: 0x0069, 0x1304: 0x006b, 0x1305: 0x006d,
+ 0x1306: 0x006f, 0x1307: 0x0071, 0x1308: 0x0073, 0x1309: 0x0075, 0x130a: 0x0083, 0x130b: 0x0085,
+ 0x130c: 0x0087, 0x130d: 0x0089, 0x130e: 0x008b, 0x130f: 0x008d, 0x1310: 0x008f, 0x1311: 0x0091,
+ 0x1312: 0x0093, 0x1313: 0x0095, 0x1314: 0x0097, 0x1315: 0x0099, 0x1316: 0x009b, 0x1317: 0x009d,
+ 0x1318: 0x009f, 0x1319: 0x00a1, 0x131a: 0x00a3, 0x131b: 0x00a5, 0x131c: 0x00a7, 0x131d: 0x00a9,
+ 0x131e: 0x00ab, 0x131f: 0x00ad, 0x1320: 0x00af, 0x1321: 0x00b1, 0x1322: 0x00b3, 0x1323: 0x00b5,
+ 0x1324: 0x00dd, 0x1325: 0x00f2, 0x1328: 0x0173, 0x1329: 0x0176,
+ 0x132a: 0x0179, 0x132b: 0x017c, 0x132c: 0x017f, 0x132d: 0x0182, 0x132e: 0x0185, 0x132f: 0x0188,
+ 0x1330: 0x018b, 0x1331: 0x018e, 0x1332: 0x0191, 0x1333: 0x0194, 0x1334: 0x0197, 0x1335: 0x019a,
+ 0x1336: 0x019d, 0x1337: 0x01a0, 0x1338: 0x01a3, 0x1339: 0x0188, 0x133a: 0x01a6, 0x133b: 0x01a9,
+ 0x133c: 0x01ac, 0x133d: 0x01af, 0x133e: 0x01b2, 0x133f: 0x01b5,
+ // Block 0x4d, offset 0x1340
+ 0x1340: 0x01fd, 0x1341: 0x0200, 0x1342: 0x0203, 0x1343: 0x045b, 0x1344: 0x01c7, 0x1345: 0x01d0,
+ 0x1346: 0x01d6, 0x1347: 0x01fa, 0x1348: 0x01eb, 0x1349: 0x01e8, 0x134a: 0x0206, 0x134b: 0x0209,
+ 0x134e: 0x0021, 0x134f: 0x0023, 0x1350: 0x0025, 0x1351: 0x0027,
+ 0x1352: 0x0029, 0x1353: 0x002b, 0x1354: 0x002d, 0x1355: 0x002f, 0x1356: 0x0031, 0x1357: 0x0033,
+ 0x1358: 0x0021, 0x1359: 0x0023, 0x135a: 0x0025, 0x135b: 0x0027, 0x135c: 0x0029, 0x135d: 0x002b,
+ 0x135e: 0x002d, 0x135f: 0x002f, 0x1360: 0x0031, 0x1361: 0x0033, 0x1362: 0x0021, 0x1363: 0x0023,
+ 0x1364: 0x0025, 0x1365: 0x0027, 0x1366: 0x0029, 0x1367: 0x002b, 0x1368: 0x002d, 0x1369: 0x002f,
+ 0x136a: 0x0031, 0x136b: 0x0033, 0x136c: 0x0021, 0x136d: 0x0023, 0x136e: 0x0025, 0x136f: 0x0027,
+ 0x1370: 0x0029, 0x1371: 0x002b, 0x1372: 0x002d, 0x1373: 0x002f, 0x1374: 0x0031, 0x1375: 0x0033,
+ 0x1376: 0x0021, 0x1377: 0x0023, 0x1378: 0x0025, 0x1379: 0x0027, 0x137a: 0x0029, 0x137b: 0x002b,
+ 0x137c: 0x002d, 0x137d: 0x002f, 0x137e: 0x0031, 0x137f: 0x0033,
+ // Block 0x4e, offset 0x1380
+ 0x1380: 0x0239, 0x1381: 0x023c, 0x1382: 0x0248, 0x1383: 0x0251, 0x1385: 0x028a,
+ 0x1386: 0x025a, 0x1387: 0x024b, 0x1388: 0x0269, 0x1389: 0x0290, 0x138a: 0x027b, 0x138b: 0x027e,
+ 0x138c: 0x0281, 0x138d: 0x0284, 0x138e: 0x025d, 0x138f: 0x026f, 0x1390: 0x0275, 0x1391: 0x0263,
+ 0x1392: 0x0278, 0x1393: 0x0257, 0x1394: 0x0260, 0x1395: 0x0242, 0x1396: 0x0245, 0x1397: 0x024e,
+ 0x1398: 0x0254, 0x1399: 0x0266, 0x139a: 0x026c, 0x139b: 0x0272, 0x139c: 0x0293, 0x139d: 0x02e4,
+ 0x139e: 0x02cc, 0x139f: 0x0296, 0x13a1: 0x023c, 0x13a2: 0x0248,
+ 0x13a4: 0x0287, 0x13a7: 0x024b, 0x13a9: 0x0290,
+ 0x13aa: 0x027b, 0x13ab: 0x027e, 0x13ac: 0x0281, 0x13ad: 0x0284, 0x13ae: 0x025d, 0x13af: 0x026f,
+ 0x13b0: 0x0275, 0x13b1: 0x0263, 0x13b2: 0x0278, 0x13b4: 0x0260, 0x13b5: 0x0242,
+ 0x13b6: 0x0245, 0x13b7: 0x024e, 0x13b9: 0x0266, 0x13bb: 0x0272,
+ // Block 0x4f, offset 0x13c0
+ 0x13c2: 0x0248,
+ 0x13c7: 0x024b, 0x13c9: 0x0290, 0x13cb: 0x027e,
+ 0x13cd: 0x0284, 0x13ce: 0x025d, 0x13cf: 0x026f, 0x13d1: 0x0263,
+ 0x13d2: 0x0278, 0x13d4: 0x0260, 0x13d7: 0x024e,
+ 0x13d9: 0x0266, 0x13db: 0x0272, 0x13dd: 0x02e4,
+ 0x13df: 0x0296, 0x13e1: 0x023c, 0x13e2: 0x0248,
+ 0x13e4: 0x0287, 0x13e7: 0x024b, 0x13e8: 0x0269, 0x13e9: 0x0290,
+ 0x13ea: 0x027b, 0x13ec: 0x0281, 0x13ed: 0x0284, 0x13ee: 0x025d, 0x13ef: 0x026f,
+ 0x13f0: 0x0275, 0x13f1: 0x0263, 0x13f2: 0x0278, 0x13f4: 0x0260, 0x13f5: 0x0242,
+ 0x13f6: 0x0245, 0x13f7: 0x024e, 0x13f9: 0x0266, 0x13fa: 0x026c, 0x13fb: 0x0272,
+ 0x13fc: 0x0293, 0x13fe: 0x02cc,
+ // Block 0x50, offset 0x1400
+ 0x1400: 0x0239, 0x1401: 0x023c, 0x1402: 0x0248, 0x1403: 0x0251, 0x1404: 0x0287, 0x1405: 0x028a,
+ 0x1406: 0x025a, 0x1407: 0x024b, 0x1408: 0x0269, 0x1409: 0x0290, 0x140b: 0x027e,
+ 0x140c: 0x0281, 0x140d: 0x0284, 0x140e: 0x025d, 0x140f: 0x026f, 0x1410: 0x0275, 0x1411: 0x0263,
+ 0x1412: 0x0278, 0x1413: 0x0257, 0x1414: 0x0260, 0x1415: 0x0242, 0x1416: 0x0245, 0x1417: 0x024e,
+ 0x1418: 0x0254, 0x1419: 0x0266, 0x141a: 0x026c, 0x141b: 0x0272,
+ 0x1421: 0x023c, 0x1422: 0x0248, 0x1423: 0x0251,
+ 0x1425: 0x028a, 0x1426: 0x025a, 0x1427: 0x024b, 0x1428: 0x0269, 0x1429: 0x0290,
+ 0x142b: 0x027e, 0x142c: 0x0281, 0x142d: 0x0284, 0x142e: 0x025d, 0x142f: 0x026f,
+ 0x1430: 0x0275, 0x1431: 0x0263, 0x1432: 0x0278, 0x1433: 0x0257, 0x1434: 0x0260, 0x1435: 0x0242,
+ 0x1436: 0x0245, 0x1437: 0x024e, 0x1438: 0x0254, 0x1439: 0x0266, 0x143a: 0x026c, 0x143b: 0x0272,
+ // Block 0x51, offset 0x1440
+ 0x1440: 0x1879, 0x1441: 0x1876, 0x1442: 0x187c, 0x1443: 0x18a0, 0x1444: 0x18c4, 0x1445: 0x18e8,
+ 0x1446: 0x190c, 0x1447: 0x1915, 0x1448: 0x191b, 0x1449: 0x1921, 0x144a: 0x1927,
+ 0x1450: 0x1a8c, 0x1451: 0x1a90,
+ 0x1452: 0x1a94, 0x1453: 0x1a98, 0x1454: 0x1a9c, 0x1455: 0x1aa0, 0x1456: 0x1aa4, 0x1457: 0x1aa8,
+ 0x1458: 0x1aac, 0x1459: 0x1ab0, 0x145a: 0x1ab4, 0x145b: 0x1ab8, 0x145c: 0x1abc, 0x145d: 0x1ac0,
+ 0x145e: 0x1ac4, 0x145f: 0x1ac8, 0x1460: 0x1acc, 0x1461: 0x1ad0, 0x1462: 0x1ad4, 0x1463: 0x1ad8,
+ 0x1464: 0x1adc, 0x1465: 0x1ae0, 0x1466: 0x1ae4, 0x1467: 0x1ae8, 0x1468: 0x1aec, 0x1469: 0x1af0,
+ 0x146a: 0x271e, 0x146b: 0x0047, 0x146c: 0x0065, 0x146d: 0x193c, 0x146e: 0x19b1,
+ 0x1470: 0x0043, 0x1471: 0x0045, 0x1472: 0x0047, 0x1473: 0x0049, 0x1474: 0x004b, 0x1475: 0x004d,
+ 0x1476: 0x004f, 0x1477: 0x0051, 0x1478: 0x0053, 0x1479: 0x0055, 0x147a: 0x0057, 0x147b: 0x0059,
+ 0x147c: 0x005b, 0x147d: 0x005d, 0x147e: 0x005f, 0x147f: 0x0061,
+ // Block 0x52, offset 0x1480
+ 0x1480: 0x26ad, 0x1481: 0x26c2, 0x1482: 0x0503,
+ 0x1490: 0x0c0f, 0x1491: 0x0a47,
+ 0x1492: 0x08d3, 0x1493: 0x465a, 0x1494: 0x071b, 0x1495: 0x09ef, 0x1496: 0x132f, 0x1497: 0x09ff,
+ 0x1498: 0x0727, 0x1499: 0x0cd7, 0x149a: 0x0eaf, 0x149b: 0x0caf, 0x149c: 0x0827, 0x149d: 0x0b6b,
+ 0x149e: 0x07bf, 0x149f: 0x0cb7, 0x14a0: 0x0813, 0x14a1: 0x1117, 0x14a2: 0x0f83, 0x14a3: 0x138b,
+ 0x14a4: 0x09d3, 0x14a5: 0x090b, 0x14a6: 0x0e63, 0x14a7: 0x0c1b, 0x14a8: 0x0c47, 0x14a9: 0x06bf,
+ 0x14aa: 0x06cb, 0x14ab: 0x140b, 0x14ac: 0x0adb, 0x14ad: 0x06e7, 0x14ae: 0x08ef, 0x14af: 0x0c3b,
+ 0x14b0: 0x13b3, 0x14b1: 0x0c13, 0x14b2: 0x106f, 0x14b3: 0x10ab, 0x14b4: 0x08f7, 0x14b5: 0x0e43,
+ 0x14b6: 0x0d0b, 0x14b7: 0x0d07, 0x14b8: 0x0f97, 0x14b9: 0x082b, 0x14ba: 0x0957, 0x14bb: 0x1443,
+ // Block 0x53, offset 0x14c0
+ 0x14c0: 0x06fb, 0x14c1: 0x06f3, 0x14c2: 0x0703, 0x14c3: 0x1647, 0x14c4: 0x0747, 0x14c5: 0x0757,
+ 0x14c6: 0x075b, 0x14c7: 0x0763, 0x14c8: 0x076b, 0x14c9: 0x076f, 0x14ca: 0x077b, 0x14cb: 0x0773,
+ 0x14cc: 0x05b3, 0x14cd: 0x165b, 0x14ce: 0x078f, 0x14cf: 0x0793, 0x14d0: 0x0797, 0x14d1: 0x07b3,
+ 0x14d2: 0x164c, 0x14d3: 0x05b7, 0x14d4: 0x079f, 0x14d5: 0x07bf, 0x14d6: 0x1656, 0x14d7: 0x07cf,
+ 0x14d8: 0x07d7, 0x14d9: 0x0737, 0x14da: 0x07df, 0x14db: 0x07e3, 0x14dc: 0x1831, 0x14dd: 0x07ff,
+ 0x14de: 0x0807, 0x14df: 0x05bf, 0x14e0: 0x081f, 0x14e1: 0x0823, 0x14e2: 0x082b, 0x14e3: 0x082f,
+ 0x14e4: 0x05c3, 0x14e5: 0x0847, 0x14e6: 0x084b, 0x14e7: 0x0857, 0x14e8: 0x0863, 0x14e9: 0x0867,
+ 0x14ea: 0x086b, 0x14eb: 0x0873, 0x14ec: 0x0893, 0x14ed: 0x0897, 0x14ee: 0x089f, 0x14ef: 0x08af,
+ 0x14f0: 0x08b7, 0x14f1: 0x08bb, 0x14f2: 0x08bb, 0x14f3: 0x08bb, 0x14f4: 0x166a, 0x14f5: 0x0e93,
+ 0x14f6: 0x08cf, 0x14f7: 0x08d7, 0x14f8: 0x166f, 0x14f9: 0x08e3, 0x14fa: 0x08eb, 0x14fb: 0x08f3,
+ 0x14fc: 0x091b, 0x14fd: 0x0907, 0x14fe: 0x0913, 0x14ff: 0x0917,
+ // Block 0x54, offset 0x1500
+ 0x1500: 0x091f, 0x1501: 0x0927, 0x1502: 0x092b, 0x1503: 0x0933, 0x1504: 0x093b, 0x1505: 0x093f,
+ 0x1506: 0x093f, 0x1507: 0x0947, 0x1508: 0x094f, 0x1509: 0x0953, 0x150a: 0x095f, 0x150b: 0x0983,
+ 0x150c: 0x0967, 0x150d: 0x0987, 0x150e: 0x096b, 0x150f: 0x0973, 0x1510: 0x080b, 0x1511: 0x09cf,
+ 0x1512: 0x0997, 0x1513: 0x099b, 0x1514: 0x099f, 0x1515: 0x0993, 0x1516: 0x09a7, 0x1517: 0x09a3,
+ 0x1518: 0x09bb, 0x1519: 0x1674, 0x151a: 0x09d7, 0x151b: 0x09db, 0x151c: 0x09e3, 0x151d: 0x09ef,
+ 0x151e: 0x09f7, 0x151f: 0x0a13, 0x1520: 0x1679, 0x1521: 0x167e, 0x1522: 0x0a1f, 0x1523: 0x0a23,
+ 0x1524: 0x0a27, 0x1525: 0x0a1b, 0x1526: 0x0a2f, 0x1527: 0x05c7, 0x1528: 0x05cb, 0x1529: 0x0a37,
+ 0x152a: 0x0a3f, 0x152b: 0x0a3f, 0x152c: 0x1683, 0x152d: 0x0a5b, 0x152e: 0x0a5f, 0x152f: 0x0a63,
+ 0x1530: 0x0a6b, 0x1531: 0x1688, 0x1532: 0x0a73, 0x1533: 0x0a77, 0x1534: 0x0b4f, 0x1535: 0x0a7f,
+ 0x1536: 0x05cf, 0x1537: 0x0a8b, 0x1538: 0x0a9b, 0x1539: 0x0aa7, 0x153a: 0x0aa3, 0x153b: 0x1692,
+ 0x153c: 0x0aaf, 0x153d: 0x1697, 0x153e: 0x0abb, 0x153f: 0x0ab7,
+ // Block 0x55, offset 0x1540
+ 0x1540: 0x0abf, 0x1541: 0x0acf, 0x1542: 0x0ad3, 0x1543: 0x05d3, 0x1544: 0x0ae3, 0x1545: 0x0aeb,
+ 0x1546: 0x0aef, 0x1547: 0x0af3, 0x1548: 0x05d7, 0x1549: 0x169c, 0x154a: 0x05db, 0x154b: 0x0b0f,
+ 0x154c: 0x0b13, 0x154d: 0x0b17, 0x154e: 0x0b1f, 0x154f: 0x1863, 0x1550: 0x0b37, 0x1551: 0x16a6,
+ 0x1552: 0x16a6, 0x1553: 0x11d7, 0x1554: 0x0b47, 0x1555: 0x0b47, 0x1556: 0x05df, 0x1557: 0x16c9,
+ 0x1558: 0x179b, 0x1559: 0x0b57, 0x155a: 0x0b5f, 0x155b: 0x05e3, 0x155c: 0x0b73, 0x155d: 0x0b83,
+ 0x155e: 0x0b87, 0x155f: 0x0b8f, 0x1560: 0x0b9f, 0x1561: 0x05eb, 0x1562: 0x05e7, 0x1563: 0x0ba3,
+ 0x1564: 0x16ab, 0x1565: 0x0ba7, 0x1566: 0x0bbb, 0x1567: 0x0bbf, 0x1568: 0x0bc3, 0x1569: 0x0bbf,
+ 0x156a: 0x0bcf, 0x156b: 0x0bd3, 0x156c: 0x0be3, 0x156d: 0x0bdb, 0x156e: 0x0bdf, 0x156f: 0x0be7,
+ 0x1570: 0x0beb, 0x1571: 0x0bef, 0x1572: 0x0bfb, 0x1573: 0x0bff, 0x1574: 0x0c17, 0x1575: 0x0c1f,
+ 0x1576: 0x0c2f, 0x1577: 0x0c43, 0x1578: 0x16ba, 0x1579: 0x0c3f, 0x157a: 0x0c33, 0x157b: 0x0c4b,
+ 0x157c: 0x0c53, 0x157d: 0x0c67, 0x157e: 0x16bf, 0x157f: 0x0c6f,
+ // Block 0x56, offset 0x1580
+ 0x1580: 0x0c63, 0x1581: 0x0c5b, 0x1582: 0x05ef, 0x1583: 0x0c77, 0x1584: 0x0c7f, 0x1585: 0x0c87,
+ 0x1586: 0x0c7b, 0x1587: 0x05f3, 0x1588: 0x0c97, 0x1589: 0x0c9f, 0x158a: 0x16c4, 0x158b: 0x0ccb,
+ 0x158c: 0x0cff, 0x158d: 0x0cdb, 0x158e: 0x05ff, 0x158f: 0x0ce7, 0x1590: 0x05fb, 0x1591: 0x05f7,
+ 0x1592: 0x07c3, 0x1593: 0x07c7, 0x1594: 0x0d03, 0x1595: 0x0ceb, 0x1596: 0x11ab, 0x1597: 0x0663,
+ 0x1598: 0x0d0f, 0x1599: 0x0d13, 0x159a: 0x0d17, 0x159b: 0x0d2b, 0x159c: 0x0d23, 0x159d: 0x16dd,
+ 0x159e: 0x0603, 0x159f: 0x0d3f, 0x15a0: 0x0d33, 0x15a1: 0x0d4f, 0x15a2: 0x0d57, 0x15a3: 0x16e7,
+ 0x15a4: 0x0d5b, 0x15a5: 0x0d47, 0x15a6: 0x0d63, 0x15a7: 0x0607, 0x15a8: 0x0d67, 0x15a9: 0x0d6b,
+ 0x15aa: 0x0d6f, 0x15ab: 0x0d7b, 0x15ac: 0x16ec, 0x15ad: 0x0d83, 0x15ae: 0x060b, 0x15af: 0x0d8f,
+ 0x15b0: 0x16f1, 0x15b1: 0x0d93, 0x15b2: 0x060f, 0x15b3: 0x0d9f, 0x15b4: 0x0dab, 0x15b5: 0x0db7,
+ 0x15b6: 0x0dbb, 0x15b7: 0x16f6, 0x15b8: 0x168d, 0x15b9: 0x16fb, 0x15ba: 0x0ddb, 0x15bb: 0x1700,
+ 0x15bc: 0x0de7, 0x15bd: 0x0def, 0x15be: 0x0ddf, 0x15bf: 0x0dfb,
+ // Block 0x57, offset 0x15c0
+ 0x15c0: 0x0e0b, 0x15c1: 0x0e1b, 0x15c2: 0x0e0f, 0x15c3: 0x0e13, 0x15c4: 0x0e1f, 0x15c5: 0x0e23,
+ 0x15c6: 0x1705, 0x15c7: 0x0e07, 0x15c8: 0x0e3b, 0x15c9: 0x0e3f, 0x15ca: 0x0613, 0x15cb: 0x0e53,
+ 0x15cc: 0x0e4f, 0x15cd: 0x170a, 0x15ce: 0x0e33, 0x15cf: 0x0e6f, 0x15d0: 0x170f, 0x15d1: 0x1714,
+ 0x15d2: 0x0e73, 0x15d3: 0x0e87, 0x15d4: 0x0e83, 0x15d5: 0x0e7f, 0x15d6: 0x0617, 0x15d7: 0x0e8b,
+ 0x15d8: 0x0e9b, 0x15d9: 0x0e97, 0x15da: 0x0ea3, 0x15db: 0x1651, 0x15dc: 0x0eb3, 0x15dd: 0x1719,
+ 0x15de: 0x0ebf, 0x15df: 0x1723, 0x15e0: 0x0ed3, 0x15e1: 0x0edf, 0x15e2: 0x0ef3, 0x15e3: 0x1728,
+ 0x15e4: 0x0f07, 0x15e5: 0x0f0b, 0x15e6: 0x172d, 0x15e7: 0x1732, 0x15e8: 0x0f27, 0x15e9: 0x0f37,
+ 0x15ea: 0x061b, 0x15eb: 0x0f3b, 0x15ec: 0x061f, 0x15ed: 0x061f, 0x15ee: 0x0f53, 0x15ef: 0x0f57,
+ 0x15f0: 0x0f5f, 0x15f1: 0x0f63, 0x15f2: 0x0f6f, 0x15f3: 0x0623, 0x15f4: 0x0f87, 0x15f5: 0x1737,
+ 0x15f6: 0x0fa3, 0x15f7: 0x173c, 0x15f8: 0x0faf, 0x15f9: 0x16a1, 0x15fa: 0x0fbf, 0x15fb: 0x1741,
+ 0x15fc: 0x1746, 0x15fd: 0x174b, 0x15fe: 0x0627, 0x15ff: 0x062b,
+ // Block 0x58, offset 0x1600
+ 0x1600: 0x0ff7, 0x1601: 0x1755, 0x1602: 0x1750, 0x1603: 0x175a, 0x1604: 0x175f, 0x1605: 0x0fff,
+ 0x1606: 0x1003, 0x1607: 0x1003, 0x1608: 0x100b, 0x1609: 0x0633, 0x160a: 0x100f, 0x160b: 0x0637,
+ 0x160c: 0x063b, 0x160d: 0x1769, 0x160e: 0x1023, 0x160f: 0x102b, 0x1610: 0x1037, 0x1611: 0x063f,
+ 0x1612: 0x176e, 0x1613: 0x105b, 0x1614: 0x1773, 0x1615: 0x1778, 0x1616: 0x107b, 0x1617: 0x1093,
+ 0x1618: 0x0643, 0x1619: 0x109b, 0x161a: 0x109f, 0x161b: 0x10a3, 0x161c: 0x177d, 0x161d: 0x1782,
+ 0x161e: 0x1782, 0x161f: 0x10bb, 0x1620: 0x0647, 0x1621: 0x1787, 0x1622: 0x10cf, 0x1623: 0x10d3,
+ 0x1624: 0x064b, 0x1625: 0x178c, 0x1626: 0x10ef, 0x1627: 0x064f, 0x1628: 0x10ff, 0x1629: 0x10f7,
+ 0x162a: 0x1107, 0x162b: 0x1796, 0x162c: 0x111f, 0x162d: 0x0653, 0x162e: 0x112b, 0x162f: 0x1133,
+ 0x1630: 0x1143, 0x1631: 0x0657, 0x1632: 0x17a0, 0x1633: 0x17a5, 0x1634: 0x065b, 0x1635: 0x17aa,
+ 0x1636: 0x115b, 0x1637: 0x17af, 0x1638: 0x1167, 0x1639: 0x1173, 0x163a: 0x117b, 0x163b: 0x17b4,
+ 0x163c: 0x17b9, 0x163d: 0x118f, 0x163e: 0x17be, 0x163f: 0x1197,
+ // Block 0x59, offset 0x1640
+ 0x1640: 0x16ce, 0x1641: 0x065f, 0x1642: 0x11af, 0x1643: 0x11b3, 0x1644: 0x0667, 0x1645: 0x11b7,
+ 0x1646: 0x0a33, 0x1647: 0x17c3, 0x1648: 0x17c8, 0x1649: 0x16d3, 0x164a: 0x16d8, 0x164b: 0x11d7,
+ 0x164c: 0x11db, 0x164d: 0x13f3, 0x164e: 0x066b, 0x164f: 0x1207, 0x1650: 0x1203, 0x1651: 0x120b,
+ 0x1652: 0x083f, 0x1653: 0x120f, 0x1654: 0x1213, 0x1655: 0x1217, 0x1656: 0x121f, 0x1657: 0x17cd,
+ 0x1658: 0x121b, 0x1659: 0x1223, 0x165a: 0x1237, 0x165b: 0x123b, 0x165c: 0x1227, 0x165d: 0x123f,
+ 0x165e: 0x1253, 0x165f: 0x1267, 0x1660: 0x1233, 0x1661: 0x1247, 0x1662: 0x124b, 0x1663: 0x124f,
+ 0x1664: 0x17d2, 0x1665: 0x17dc, 0x1666: 0x17d7, 0x1667: 0x066f, 0x1668: 0x126f, 0x1669: 0x1273,
+ 0x166a: 0x127b, 0x166b: 0x17f0, 0x166c: 0x127f, 0x166d: 0x17e1, 0x166e: 0x0673, 0x166f: 0x0677,
+ 0x1670: 0x17e6, 0x1671: 0x17eb, 0x1672: 0x067b, 0x1673: 0x129f, 0x1674: 0x12a3, 0x1675: 0x12a7,
+ 0x1676: 0x12ab, 0x1677: 0x12b7, 0x1678: 0x12b3, 0x1679: 0x12bf, 0x167a: 0x12bb, 0x167b: 0x12cb,
+ 0x167c: 0x12c3, 0x167d: 0x12c7, 0x167e: 0x12cf, 0x167f: 0x067f,
+ // Block 0x5a, offset 0x1680
+ 0x1680: 0x12d7, 0x1681: 0x12db, 0x1682: 0x0683, 0x1683: 0x12eb, 0x1684: 0x12ef, 0x1685: 0x17f5,
+ 0x1686: 0x12fb, 0x1687: 0x12ff, 0x1688: 0x0687, 0x1689: 0x130b, 0x168a: 0x05bb, 0x168b: 0x17fa,
+ 0x168c: 0x17ff, 0x168d: 0x068b, 0x168e: 0x068f, 0x168f: 0x1337, 0x1690: 0x134f, 0x1691: 0x136b,
+ 0x1692: 0x137b, 0x1693: 0x1804, 0x1694: 0x138f, 0x1695: 0x1393, 0x1696: 0x13ab, 0x1697: 0x13b7,
+ 0x1698: 0x180e, 0x1699: 0x1660, 0x169a: 0x13c3, 0x169b: 0x13bf, 0x169c: 0x13cb, 0x169d: 0x1665,
+ 0x169e: 0x13d7, 0x169f: 0x13e3, 0x16a0: 0x1813, 0x16a1: 0x1818, 0x16a2: 0x1423, 0x16a3: 0x142f,
+ 0x16a4: 0x1437, 0x16a5: 0x181d, 0x16a6: 0x143b, 0x16a7: 0x1467, 0x16a8: 0x1473, 0x16a9: 0x1477,
+ 0x16aa: 0x146f, 0x16ab: 0x1483, 0x16ac: 0x1487, 0x16ad: 0x1822, 0x16ae: 0x1493, 0x16af: 0x0693,
+ 0x16b0: 0x149b, 0x16b1: 0x1827, 0x16b2: 0x0697, 0x16b3: 0x14d3, 0x16b4: 0x0ac3, 0x16b5: 0x14eb,
+ 0x16b6: 0x182c, 0x16b7: 0x1836, 0x16b8: 0x069b, 0x16b9: 0x069f, 0x16ba: 0x1513, 0x16bb: 0x183b,
+ 0x16bc: 0x06a3, 0x16bd: 0x1840, 0x16be: 0x152b, 0x16bf: 0x152b,
+ // Block 0x5b, offset 0x16c0
+ 0x16c0: 0x1533, 0x16c1: 0x1845, 0x16c2: 0x154b, 0x16c3: 0x06a7, 0x16c4: 0x155b, 0x16c5: 0x1567,
+ 0x16c6: 0x156f, 0x16c7: 0x1577, 0x16c8: 0x06ab, 0x16c9: 0x184a, 0x16ca: 0x158b, 0x16cb: 0x15a7,
+ 0x16cc: 0x15b3, 0x16cd: 0x06af, 0x16ce: 0x06b3, 0x16cf: 0x15b7, 0x16d0: 0x184f, 0x16d1: 0x06b7,
+ 0x16d2: 0x1854, 0x16d3: 0x1859, 0x16d4: 0x185e, 0x16d5: 0x15db, 0x16d6: 0x06bb, 0x16d7: 0x15ef,
+ 0x16d8: 0x15f7, 0x16d9: 0x15fb, 0x16da: 0x1603, 0x16db: 0x160b, 0x16dc: 0x1613, 0x16dd: 0x1868,
+}
+
+// nfkcIndex: 22 blocks, 1408 entries, 1408 bytes
+// Block 0 is the zero block.
+var nfkcIndex = [1408]uint8{
+ // Block 0x0, offset 0x0
+ // Block 0x1, offset 0x40
+ // Block 0x2, offset 0x80
+ // Block 0x3, offset 0xc0
+ 0xc2: 0x5a, 0xc3: 0x01, 0xc4: 0x02, 0xc5: 0x03, 0xc6: 0x5b, 0xc7: 0x04,
+ 0xc8: 0x05, 0xca: 0x5c, 0xcb: 0x5d, 0xcc: 0x06, 0xcd: 0x07, 0xce: 0x08, 0xcf: 0x09,
+ 0xd0: 0x0a, 0xd1: 0x5e, 0xd2: 0x5f, 0xd3: 0x0b, 0xd6: 0x0c, 0xd7: 0x60,
+ 0xd8: 0x61, 0xd9: 0x0d, 0xdb: 0x62, 0xdc: 0x63, 0xdd: 0x64, 0xdf: 0x65,
+ 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05,
+ 0xea: 0x06, 0xeb: 0x07, 0xec: 0x08, 0xed: 0x09, 0xef: 0x0a,
+ 0xf0: 0x13,
+ // Block 0x4, offset 0x100
+ 0x120: 0x66, 0x121: 0x67, 0x123: 0x68, 0x124: 0x69, 0x125: 0x6a, 0x126: 0x6b, 0x127: 0x6c,
+ 0x128: 0x6d, 0x129: 0x6e, 0x12a: 0x6f, 0x12b: 0x70, 0x12c: 0x6b, 0x12d: 0x71, 0x12e: 0x72, 0x12f: 0x73,
+ 0x131: 0x74, 0x132: 0x75, 0x133: 0x76, 0x134: 0x77, 0x135: 0x78, 0x137: 0x79,
+ 0x138: 0x7a, 0x139: 0x7b, 0x13a: 0x7c, 0x13b: 0x7d, 0x13c: 0x7e, 0x13d: 0x7f, 0x13e: 0x80, 0x13f: 0x81,
+ // Block 0x5, offset 0x140
+ 0x140: 0x82, 0x142: 0x83, 0x143: 0x84, 0x144: 0x85, 0x145: 0x86, 0x146: 0x87, 0x147: 0x88,
+ 0x14d: 0x89,
+ 0x15c: 0x8a, 0x15f: 0x8b,
+ 0x162: 0x8c, 0x164: 0x8d,
+ 0x168: 0x8e, 0x169: 0x8f, 0x16a: 0x90, 0x16c: 0x0e, 0x16d: 0x91, 0x16e: 0x92, 0x16f: 0x93,
+ 0x170: 0x94, 0x173: 0x95, 0x174: 0x96, 0x175: 0x0f, 0x176: 0x10, 0x177: 0x97,
+ 0x178: 0x11, 0x179: 0x12, 0x17a: 0x13, 0x17b: 0x14, 0x17c: 0x15, 0x17d: 0x16, 0x17e: 0x17, 0x17f: 0x18,
+ // Block 0x6, offset 0x180
+ 0x180: 0x98, 0x181: 0x99, 0x182: 0x9a, 0x183: 0x9b, 0x184: 0x19, 0x185: 0x1a, 0x186: 0x9c, 0x187: 0x9d,
+ 0x188: 0x9e, 0x189: 0x1b, 0x18a: 0x1c, 0x18b: 0x9f, 0x18c: 0xa0,
+ 0x191: 0x1d, 0x192: 0x1e, 0x193: 0xa1,
+ 0x1a8: 0xa2, 0x1a9: 0xa3, 0x1ab: 0xa4,
+ 0x1b1: 0xa5, 0x1b3: 0xa6, 0x1b5: 0xa7, 0x1b7: 0xa8,
+ 0x1ba: 0xa9, 0x1bb: 0xaa, 0x1bc: 0x1f, 0x1bd: 0x20, 0x1be: 0x21, 0x1bf: 0xab,
+ // Block 0x7, offset 0x1c0
+ 0x1c0: 0xac, 0x1c1: 0x22, 0x1c2: 0x23, 0x1c3: 0x24, 0x1c4: 0xad, 0x1c5: 0x25, 0x1c6: 0x26,
+ 0x1c8: 0x27, 0x1c9: 0x28, 0x1ca: 0x29, 0x1cb: 0x2a, 0x1cc: 0x2b, 0x1cd: 0x2c, 0x1ce: 0x2d, 0x1cf: 0x2e,
+ // Block 0x8, offset 0x200
+ 0x219: 0xae, 0x21a: 0xaf, 0x21b: 0xb0, 0x21d: 0xb1, 0x21f: 0xb2,
+ 0x220: 0xb3, 0x223: 0xb4, 0x224: 0xb5, 0x225: 0xb6, 0x226: 0xb7, 0x227: 0xb8,
+ 0x22a: 0xb9, 0x22b: 0xba, 0x22d: 0xbb, 0x22f: 0xbc,
+ 0x230: 0xbd, 0x231: 0xbe, 0x232: 0xbf, 0x233: 0xc0, 0x234: 0xc1, 0x235: 0xc2, 0x236: 0xc3, 0x237: 0xbd,
+ 0x238: 0xbe, 0x239: 0xbf, 0x23a: 0xc0, 0x23b: 0xc1, 0x23c: 0xc2, 0x23d: 0xc3, 0x23e: 0xbd, 0x23f: 0xbe,
+ // Block 0x9, offset 0x240
+ 0x240: 0xbf, 0x241: 0xc0, 0x242: 0xc1, 0x243: 0xc2, 0x244: 0xc3, 0x245: 0xbd, 0x246: 0xbe, 0x247: 0xbf,
+ 0x248: 0xc0, 0x249: 0xc1, 0x24a: 0xc2, 0x24b: 0xc3, 0x24c: 0xbd, 0x24d: 0xbe, 0x24e: 0xbf, 0x24f: 0xc0,
+ 0x250: 0xc1, 0x251: 0xc2, 0x252: 0xc3, 0x253: 0xbd, 0x254: 0xbe, 0x255: 0xbf, 0x256: 0xc0, 0x257: 0xc1,
+ 0x258: 0xc2, 0x259: 0xc3, 0x25a: 0xbd, 0x25b: 0xbe, 0x25c: 0xbf, 0x25d: 0xc0, 0x25e: 0xc1, 0x25f: 0xc2,
+ 0x260: 0xc3, 0x261: 0xbd, 0x262: 0xbe, 0x263: 0xbf, 0x264: 0xc0, 0x265: 0xc1, 0x266: 0xc2, 0x267: 0xc3,
+ 0x268: 0xbd, 0x269: 0xbe, 0x26a: 0xbf, 0x26b: 0xc0, 0x26c: 0xc1, 0x26d: 0xc2, 0x26e: 0xc3, 0x26f: 0xbd,
+ 0x270: 0xbe, 0x271: 0xbf, 0x272: 0xc0, 0x273: 0xc1, 0x274: 0xc2, 0x275: 0xc3, 0x276: 0xbd, 0x277: 0xbe,
+ 0x278: 0xbf, 0x279: 0xc0, 0x27a: 0xc1, 0x27b: 0xc2, 0x27c: 0xc3, 0x27d: 0xbd, 0x27e: 0xbe, 0x27f: 0xbf,
+ // Block 0xa, offset 0x280
+ 0x280: 0xc0, 0x281: 0xc1, 0x282: 0xc2, 0x283: 0xc3, 0x284: 0xbd, 0x285: 0xbe, 0x286: 0xbf, 0x287: 0xc0,
+ 0x288: 0xc1, 0x289: 0xc2, 0x28a: 0xc3, 0x28b: 0xbd, 0x28c: 0xbe, 0x28d: 0xbf, 0x28e: 0xc0, 0x28f: 0xc1,
+ 0x290: 0xc2, 0x291: 0xc3, 0x292: 0xbd, 0x293: 0xbe, 0x294: 0xbf, 0x295: 0xc0, 0x296: 0xc1, 0x297: 0xc2,
+ 0x298: 0xc3, 0x299: 0xbd, 0x29a: 0xbe, 0x29b: 0xbf, 0x29c: 0xc0, 0x29d: 0xc1, 0x29e: 0xc2, 0x29f: 0xc3,
+ 0x2a0: 0xbd, 0x2a1: 0xbe, 0x2a2: 0xbf, 0x2a3: 0xc0, 0x2a4: 0xc1, 0x2a5: 0xc2, 0x2a6: 0xc3, 0x2a7: 0xbd,
+ 0x2a8: 0xbe, 0x2a9: 0xbf, 0x2aa: 0xc0, 0x2ab: 0xc1, 0x2ac: 0xc2, 0x2ad: 0xc3, 0x2ae: 0xbd, 0x2af: 0xbe,
+ 0x2b0: 0xbf, 0x2b1: 0xc0, 0x2b2: 0xc1, 0x2b3: 0xc2, 0x2b4: 0xc3, 0x2b5: 0xbd, 0x2b6: 0xbe, 0x2b7: 0xbf,
+ 0x2b8: 0xc0, 0x2b9: 0xc1, 0x2ba: 0xc2, 0x2bb: 0xc3, 0x2bc: 0xbd, 0x2bd: 0xbe, 0x2be: 0xbf, 0x2bf: 0xc0,
+ // Block 0xb, offset 0x2c0
+ 0x2c0: 0xc1, 0x2c1: 0xc2, 0x2c2: 0xc3, 0x2c3: 0xbd, 0x2c4: 0xbe, 0x2c5: 0xbf, 0x2c6: 0xc0, 0x2c7: 0xc1,
+ 0x2c8: 0xc2, 0x2c9: 0xc3, 0x2ca: 0xbd, 0x2cb: 0xbe, 0x2cc: 0xbf, 0x2cd: 0xc0, 0x2ce: 0xc1, 0x2cf: 0xc2,
+ 0x2d0: 0xc3, 0x2d1: 0xbd, 0x2d2: 0xbe, 0x2d3: 0xbf, 0x2d4: 0xc0, 0x2d5: 0xc1, 0x2d6: 0xc2, 0x2d7: 0xc3,
+ 0x2d8: 0xbd, 0x2d9: 0xbe, 0x2da: 0xbf, 0x2db: 0xc0, 0x2dc: 0xc1, 0x2dd: 0xc2, 0x2de: 0xc4,
+ // Block 0xc, offset 0x300
+ 0x324: 0x2f, 0x325: 0x30, 0x326: 0x31, 0x327: 0x32,
+ 0x328: 0x33, 0x329: 0x34, 0x32a: 0x35, 0x32b: 0x36, 0x32c: 0x37, 0x32d: 0x38, 0x32e: 0x39, 0x32f: 0x3a,
+ 0x330: 0x3b, 0x331: 0x3c, 0x332: 0x3d, 0x333: 0x3e, 0x334: 0x3f, 0x335: 0x40, 0x336: 0x41, 0x337: 0x42,
+ 0x338: 0x43, 0x339: 0x44, 0x33a: 0x45, 0x33b: 0x46, 0x33c: 0xc5, 0x33d: 0x47, 0x33e: 0x48, 0x33f: 0x49,
+ // Block 0xd, offset 0x340
+ 0x347: 0xc6,
+ 0x34b: 0xc7, 0x34d: 0xc8,
+ 0x368: 0xc9, 0x36b: 0xca,
+ // Block 0xe, offset 0x380
+ 0x381: 0xcb, 0x382: 0xcc, 0x384: 0xcd, 0x385: 0xb7, 0x387: 0xce,
+ 0x388: 0xcf, 0x38b: 0xd0, 0x38c: 0x6b, 0x38d: 0xd1,
+ 0x391: 0xd2, 0x392: 0xd3, 0x393: 0xd4, 0x396: 0xd5, 0x397: 0xd6,
+ 0x398: 0xd7, 0x39a: 0xd8, 0x39c: 0xd9,
+ 0x3b0: 0xd7,
+ // Block 0xf, offset 0x3c0
+ 0x3eb: 0xda, 0x3ec: 0xdb,
+ // Block 0x10, offset 0x400
+ 0x432: 0xdc,
+ // Block 0x11, offset 0x440
+ 0x445: 0xdd, 0x446: 0xde, 0x447: 0xdf,
+ 0x449: 0xe0,
+ 0x450: 0xe1, 0x451: 0xe2, 0x452: 0xe3, 0x453: 0xe4, 0x454: 0xe5, 0x455: 0xe6, 0x456: 0xe7, 0x457: 0xe8,
+ 0x458: 0xe9, 0x459: 0xea, 0x45a: 0x4a, 0x45b: 0xeb, 0x45c: 0xec, 0x45d: 0xed, 0x45e: 0xee, 0x45f: 0x4b,
+ // Block 0x12, offset 0x480
+ 0x480: 0xef,
+ 0x4a3: 0xf0, 0x4a5: 0xf1,
+ 0x4b8: 0x4c, 0x4b9: 0x4d, 0x4ba: 0x4e,
+ // Block 0x13, offset 0x4c0
+ 0x4c4: 0x4f, 0x4c5: 0xf2, 0x4c6: 0xf3,
+ 0x4c8: 0x50, 0x4c9: 0xf4,
+ // Block 0x14, offset 0x500
+ 0x520: 0x51, 0x521: 0x52, 0x522: 0x53, 0x523: 0x54, 0x524: 0x55, 0x525: 0x56, 0x526: 0x57, 0x527: 0x58,
+ 0x528: 0x59,
+ // Block 0x15, offset 0x540
+ 0x550: 0x0b, 0x551: 0x0c, 0x556: 0x0d,
+ 0x55b: 0x0e, 0x55d: 0x0f, 0x55e: 0x10, 0x55f: 0x11,
+ 0x56f: 0x12,
+}
+
+// nfkcSparseOffset: 155 entries, 310 bytes
+var nfkcSparseOffset = []uint16{0x0, 0xe, 0x12, 0x1b, 0x25, 0x35, 0x37, 0x3c, 0x47, 0x56, 0x63, 0x6b, 0x6f, 0x74, 0x76, 0x87, 0x8f, 0x96, 0x99, 0xa0, 0xa4, 0xa8, 0xaa, 0xac, 0xb5, 0xb9, 0xc0, 0xc5, 0xc8, 0xd2, 0xd4, 0xdb, 0xe3, 0xe7, 0xe9, 0xec, 0xf0, 0xf6, 0x107, 0x113, 0x115, 0x11b, 0x11d, 0x11f, 0x121, 0x123, 0x125, 0x127, 0x129, 0x12c, 0x12f, 0x131, 0x134, 0x137, 0x13b, 0x140, 0x149, 0x14b, 0x14e, 0x150, 0x15b, 0x166, 0x176, 0x184, 0x192, 0x1a2, 0x1b0, 0x1b7, 0x1bd, 0x1cc, 0x1d0, 0x1d2, 0x1d6, 0x1d8, 0x1db, 0x1dd, 0x1e0, 0x1e2, 0x1e5, 0x1e7, 0x1e9, 0x1eb, 0x1f7, 0x201, 0x20b, 0x20e, 0x212, 0x214, 0x216, 0x218, 0x21a, 0x21d, 0x21f, 0x221, 0x223, 0x225, 0x22b, 0x22e, 0x232, 0x234, 0x23b, 0x241, 0x247, 0x24f, 0x255, 0x25b, 0x261, 0x265, 0x267, 0x269, 0x26b, 0x26d, 0x273, 0x276, 0x279, 0x281, 0x288, 0x28b, 0x28e, 0x290, 0x298, 0x29b, 0x2a2, 0x2a5, 0x2ab, 0x2ad, 0x2af, 0x2b2, 0x2b4, 0x2b6, 0x2b8, 0x2ba, 0x2c7, 0x2d1, 0x2d3, 0x2d5, 0x2d9, 0x2de, 0x2ea, 0x2ef, 0x2f8, 0x2fe, 0x303, 0x307, 0x30c, 0x310, 0x320, 0x32e, 0x33c, 0x34a, 0x350, 0x352, 0x355, 0x35f, 0x361}
+
+// nfkcSparseValues: 875 entries, 3500 bytes
+var nfkcSparseValues = [875]valueRange{
+ // Block 0x0, offset 0x0
+ {value: 0x0002, lo: 0x0d},
+ {value: 0x0001, lo: 0xa0, hi: 0xa0},
+ {value: 0x4278, lo: 0xa8, hi: 0xa8},
+ {value: 0x0083, lo: 0xaa, hi: 0xaa},
+ {value: 0x4264, lo: 0xaf, hi: 0xaf},
+ {value: 0x0025, lo: 0xb2, hi: 0xb3},
+ {value: 0x425a, lo: 0xb4, hi: 0xb4},
+ {value: 0x01dc, lo: 0xb5, hi: 0xb5},
+ {value: 0x4291, lo: 0xb8, hi: 0xb8},
+ {value: 0x0023, lo: 0xb9, hi: 0xb9},
+ {value: 0x009f, lo: 0xba, hi: 0xba},
+ {value: 0x221c, lo: 0xbc, hi: 0xbc},
+ {value: 0x2210, lo: 0xbd, hi: 0xbd},
+ {value: 0x22b2, lo: 0xbe, hi: 0xbe},
+ // Block 0x1, offset 0xe
+ {value: 0x0091, lo: 0x03},
+ {value: 0x4778, lo: 0xa0, hi: 0xa1},
+ {value: 0x47aa, lo: 0xaf, hi: 0xb0},
+ {value: 0xa000, lo: 0xb7, hi: 0xb7},
+ // Block 0x2, offset 0x12
+ {value: 0x0003, lo: 0x08},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ {value: 0x0091, lo: 0xb0, hi: 0xb0},
+ {value: 0x0119, lo: 0xb1, hi: 0xb1},
+ {value: 0x0095, lo: 0xb2, hi: 0xb2},
+ {value: 0x00a5, lo: 0xb3, hi: 0xb3},
+ {value: 0x0143, lo: 0xb4, hi: 0xb6},
+ {value: 0x00af, lo: 0xb7, hi: 0xb7},
+ {value: 0x00b3, lo: 0xb8, hi: 0xb8},
+ // Block 0x3, offset 0x1b
+ {value: 0x000a, lo: 0x09},
+ {value: 0x426e, lo: 0x98, hi: 0x98},
+ {value: 0x4273, lo: 0x99, hi: 0x9a},
+ {value: 0x4296, lo: 0x9b, hi: 0x9b},
+ {value: 0x425f, lo: 0x9c, hi: 0x9c},
+ {value: 0x4282, lo: 0x9d, hi: 0x9d},
+ {value: 0x0113, lo: 0xa0, hi: 0xa0},
+ {value: 0x0099, lo: 0xa1, hi: 0xa1},
+ {value: 0x00a7, lo: 0xa2, hi: 0xa3},
+ {value: 0x0167, lo: 0xa4, hi: 0xa4},
+ // Block 0x4, offset 0x25
+ {value: 0x0000, lo: 0x0f},
+ {value: 0xa000, lo: 0x83, hi: 0x83},
+ {value: 0xa000, lo: 0x87, hi: 0x87},
+ {value: 0xa000, lo: 0x8b, hi: 0x8b},
+ {value: 0xa000, lo: 0x8d, hi: 0x8d},
+ {value: 0x37a5, lo: 0x90, hi: 0x90},
+ {value: 0x37b1, lo: 0x91, hi: 0x91},
+ {value: 0x379f, lo: 0x93, hi: 0x93},
+ {value: 0xa000, lo: 0x96, hi: 0x96},
+ {value: 0x3817, lo: 0x97, hi: 0x97},
+ {value: 0x37e1, lo: 0x9c, hi: 0x9c},
+ {value: 0x37c9, lo: 0x9d, hi: 0x9d},
+ {value: 0x37f3, lo: 0x9e, hi: 0x9e},
+ {value: 0xa000, lo: 0xb4, hi: 0xb5},
+ {value: 0x381d, lo: 0xb6, hi: 0xb6},
+ {value: 0x3823, lo: 0xb7, hi: 0xb7},
+ // Block 0x5, offset 0x35
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0x83, hi: 0x87},
+ // Block 0x6, offset 0x37
+ {value: 0x0001, lo: 0x04},
+ {value: 0x8113, lo: 0x81, hi: 0x82},
+ {value: 0x8132, lo: 0x84, hi: 0x84},
+ {value: 0x812d, lo: 0x85, hi: 0x85},
+ {value: 0x810d, lo: 0x87, hi: 0x87},
+ // Block 0x7, offset 0x3c
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x8132, lo: 0x90, hi: 0x97},
+ {value: 0x8119, lo: 0x98, hi: 0x98},
+ {value: 0x811a, lo: 0x99, hi: 0x99},
+ {value: 0x811b, lo: 0x9a, hi: 0x9a},
+ {value: 0x3841, lo: 0xa2, hi: 0xa2},
+ {value: 0x3847, lo: 0xa3, hi: 0xa3},
+ {value: 0x3853, lo: 0xa4, hi: 0xa4},
+ {value: 0x384d, lo: 0xa5, hi: 0xa5},
+ {value: 0x3859, lo: 0xa6, hi: 0xa6},
+ {value: 0xa000, lo: 0xa7, hi: 0xa7},
+ // Block 0x8, offset 0x47
+ {value: 0x0000, lo: 0x0e},
+ {value: 0x386b, lo: 0x80, hi: 0x80},
+ {value: 0xa000, lo: 0x81, hi: 0x81},
+ {value: 0x385f, lo: 0x82, hi: 0x82},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ {value: 0x3865, lo: 0x93, hi: 0x93},
+ {value: 0xa000, lo: 0x95, hi: 0x95},
+ {value: 0x8132, lo: 0x96, hi: 0x9c},
+ {value: 0x8132, lo: 0x9f, hi: 0xa2},
+ {value: 0x812d, lo: 0xa3, hi: 0xa3},
+ {value: 0x8132, lo: 0xa4, hi: 0xa4},
+ {value: 0x8132, lo: 0xa7, hi: 0xa8},
+ {value: 0x812d, lo: 0xaa, hi: 0xaa},
+ {value: 0x8132, lo: 0xab, hi: 0xac},
+ {value: 0x812d, lo: 0xad, hi: 0xad},
+ // Block 0x9, offset 0x56
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x811f, lo: 0x91, hi: 0x91},
+ {value: 0x8132, lo: 0xb0, hi: 0xb0},
+ {value: 0x812d, lo: 0xb1, hi: 0xb1},
+ {value: 0x8132, lo: 0xb2, hi: 0xb3},
+ {value: 0x812d, lo: 0xb4, hi: 0xb4},
+ {value: 0x8132, lo: 0xb5, hi: 0xb6},
+ {value: 0x812d, lo: 0xb7, hi: 0xb9},
+ {value: 0x8132, lo: 0xba, hi: 0xba},
+ {value: 0x812d, lo: 0xbb, hi: 0xbc},
+ {value: 0x8132, lo: 0xbd, hi: 0xbd},
+ {value: 0x812d, lo: 0xbe, hi: 0xbe},
+ {value: 0x8132, lo: 0xbf, hi: 0xbf},
+ // Block 0xa, offset 0x63
+ {value: 0x0005, lo: 0x07},
+ {value: 0x8132, lo: 0x80, hi: 0x80},
+ {value: 0x8132, lo: 0x81, hi: 0x81},
+ {value: 0x812d, lo: 0x82, hi: 0x83},
+ {value: 0x812d, lo: 0x84, hi: 0x85},
+ {value: 0x812d, lo: 0x86, hi: 0x87},
+ {value: 0x812d, lo: 0x88, hi: 0x89},
+ {value: 0x8132, lo: 0x8a, hi: 0x8a},
+ // Block 0xb, offset 0x6b
+ {value: 0x0000, lo: 0x03},
+ {value: 0x8132, lo: 0xab, hi: 0xb1},
+ {value: 0x812d, lo: 0xb2, hi: 0xb2},
+ {value: 0x8132, lo: 0xb3, hi: 0xb3},
+ // Block 0xc, offset 0x6f
+ {value: 0x0000, lo: 0x04},
+ {value: 0x8132, lo: 0x96, hi: 0x99},
+ {value: 0x8132, lo: 0x9b, hi: 0xa3},
+ {value: 0x8132, lo: 0xa5, hi: 0xa7},
+ {value: 0x8132, lo: 0xa9, hi: 0xad},
+ // Block 0xd, offset 0x74
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0x99, hi: 0x9b},
+ // Block 0xe, offset 0x76
+ {value: 0x0000, lo: 0x10},
+ {value: 0x8132, lo: 0x94, hi: 0xa1},
+ {value: 0x812d, lo: 0xa3, hi: 0xa3},
+ {value: 0x8132, lo: 0xa4, hi: 0xa5},
+ {value: 0x812d, lo: 0xa6, hi: 0xa6},
+ {value: 0x8132, lo: 0xa7, hi: 0xa8},
+ {value: 0x812d, lo: 0xa9, hi: 0xa9},
+ {value: 0x8132, lo: 0xaa, hi: 0xac},
+ {value: 0x812d, lo: 0xad, hi: 0xaf},
+ {value: 0x8116, lo: 0xb0, hi: 0xb0},
+ {value: 0x8117, lo: 0xb1, hi: 0xb1},
+ {value: 0x8118, lo: 0xb2, hi: 0xb2},
+ {value: 0x8132, lo: 0xb3, hi: 0xb5},
+ {value: 0x812d, lo: 0xb6, hi: 0xb6},
+ {value: 0x8132, lo: 0xb7, hi: 0xb8},
+ {value: 0x812d, lo: 0xb9, hi: 0xba},
+ {value: 0x8132, lo: 0xbb, hi: 0xbf},
+ // Block 0xf, offset 0x87
+ {value: 0x0000, lo: 0x07},
+ {value: 0xa000, lo: 0xa8, hi: 0xa8},
+ {value: 0x3ed8, lo: 0xa9, hi: 0xa9},
+ {value: 0xa000, lo: 0xb0, hi: 0xb0},
+ {value: 0x3ee0, lo: 0xb1, hi: 0xb1},
+ {value: 0xa000, lo: 0xb3, hi: 0xb3},
+ {value: 0x3ee8, lo: 0xb4, hi: 0xb4},
+ {value: 0x9902, lo: 0xbc, hi: 0xbc},
+ // Block 0x10, offset 0x8f
+ {value: 0x0008, lo: 0x06},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x8132, lo: 0x91, hi: 0x91},
+ {value: 0x812d, lo: 0x92, hi: 0x92},
+ {value: 0x8132, lo: 0x93, hi: 0x93},
+ {value: 0x8132, lo: 0x94, hi: 0x94},
+ {value: 0x45b2, lo: 0x98, hi: 0x9f},
+ // Block 0x11, offset 0x96
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8102, lo: 0xbc, hi: 0xbc},
+ {value: 0x9900, lo: 0xbe, hi: 0xbe},
+ // Block 0x12, offset 0x99
+ {value: 0x0008, lo: 0x06},
+ {value: 0xa000, lo: 0x87, hi: 0x87},
+ {value: 0x2c9e, lo: 0x8b, hi: 0x8c},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x97, hi: 0x97},
+ {value: 0x45f2, lo: 0x9c, hi: 0x9d},
+ {value: 0x4602, lo: 0x9f, hi: 0x9f},
+ // Block 0x13, offset 0xa0
+ {value: 0x0000, lo: 0x03},
+ {value: 0x462a, lo: 0xb3, hi: 0xb3},
+ {value: 0x4632, lo: 0xb6, hi: 0xb6},
+ {value: 0x8102, lo: 0xbc, hi: 0xbc},
+ // Block 0x14, offset 0xa4
+ {value: 0x0008, lo: 0x03},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x460a, lo: 0x99, hi: 0x9b},
+ {value: 0x4622, lo: 0x9e, hi: 0x9e},
+ // Block 0x15, offset 0xa8
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8102, lo: 0xbc, hi: 0xbc},
+ // Block 0x16, offset 0xaa
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ // Block 0x17, offset 0xac
+ {value: 0x0000, lo: 0x08},
+ {value: 0xa000, lo: 0x87, hi: 0x87},
+ {value: 0x2cb6, lo: 0x88, hi: 0x88},
+ {value: 0x2cae, lo: 0x8b, hi: 0x8b},
+ {value: 0x2cbe, lo: 0x8c, hi: 0x8c},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x96, hi: 0x97},
+ {value: 0x463a, lo: 0x9c, hi: 0x9c},
+ {value: 0x4642, lo: 0x9d, hi: 0x9d},
+ // Block 0x18, offset 0xb5
+ {value: 0x0000, lo: 0x03},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ {value: 0x2cc6, lo: 0x94, hi: 0x94},
+ {value: 0x9900, lo: 0xbe, hi: 0xbe},
+ // Block 0x19, offset 0xb9
+ {value: 0x0000, lo: 0x06},
+ {value: 0xa000, lo: 0x86, hi: 0x87},
+ {value: 0x2cce, lo: 0x8a, hi: 0x8a},
+ {value: 0x2cde, lo: 0x8b, hi: 0x8b},
+ {value: 0x2cd6, lo: 0x8c, hi: 0x8c},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x97, hi: 0x97},
+ // Block 0x1a, offset 0xc0
+ {value: 0x1801, lo: 0x04},
+ {value: 0xa000, lo: 0x86, hi: 0x86},
+ {value: 0x3ef0, lo: 0x88, hi: 0x88},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x8120, lo: 0x95, hi: 0x96},
+ // Block 0x1b, offset 0xc5
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8102, lo: 0xbc, hi: 0xbc},
+ {value: 0xa000, lo: 0xbf, hi: 0xbf},
+ // Block 0x1c, offset 0xc8
+ {value: 0x0000, lo: 0x09},
+ {value: 0x2ce6, lo: 0x80, hi: 0x80},
+ {value: 0x9900, lo: 0x82, hi: 0x82},
+ {value: 0xa000, lo: 0x86, hi: 0x86},
+ {value: 0x2cee, lo: 0x87, hi: 0x87},
+ {value: 0x2cf6, lo: 0x88, hi: 0x88},
+ {value: 0x2f50, lo: 0x8a, hi: 0x8a},
+ {value: 0x2dd8, lo: 0x8b, hi: 0x8b},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x95, hi: 0x96},
+ // Block 0x1d, offset 0xd2
+ {value: 0x0000, lo: 0x01},
+ {value: 0x9900, lo: 0xbe, hi: 0xbe},
+ // Block 0x1e, offset 0xd4
+ {value: 0x0000, lo: 0x06},
+ {value: 0xa000, lo: 0x86, hi: 0x87},
+ {value: 0x2cfe, lo: 0x8a, hi: 0x8a},
+ {value: 0x2d0e, lo: 0x8b, hi: 0x8b},
+ {value: 0x2d06, lo: 0x8c, hi: 0x8c},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x97, hi: 0x97},
+ // Block 0x1f, offset 0xdb
+ {value: 0x6bea, lo: 0x07},
+ {value: 0x9904, lo: 0x8a, hi: 0x8a},
+ {value: 0x9900, lo: 0x8f, hi: 0x8f},
+ {value: 0xa000, lo: 0x99, hi: 0x99},
+ {value: 0x3ef8, lo: 0x9a, hi: 0x9a},
+ {value: 0x2f58, lo: 0x9c, hi: 0x9c},
+ {value: 0x2de3, lo: 0x9d, hi: 0x9d},
+ {value: 0x2d16, lo: 0x9e, hi: 0x9f},
+ // Block 0x20, offset 0xe3
+ {value: 0x0000, lo: 0x03},
+ {value: 0x2621, lo: 0xb3, hi: 0xb3},
+ {value: 0x8122, lo: 0xb8, hi: 0xb9},
+ {value: 0x8104, lo: 0xba, hi: 0xba},
+ // Block 0x21, offset 0xe7
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8123, lo: 0x88, hi: 0x8b},
+ // Block 0x22, offset 0xe9
+ {value: 0x0000, lo: 0x02},
+ {value: 0x2636, lo: 0xb3, hi: 0xb3},
+ {value: 0x8124, lo: 0xb8, hi: 0xb9},
+ // Block 0x23, offset 0xec
+ {value: 0x0000, lo: 0x03},
+ {value: 0x8125, lo: 0x88, hi: 0x8b},
+ {value: 0x2628, lo: 0x9c, hi: 0x9c},
+ {value: 0x262f, lo: 0x9d, hi: 0x9d},
+ // Block 0x24, offset 0xf0
+ {value: 0x0000, lo: 0x05},
+ {value: 0x030b, lo: 0x8c, hi: 0x8c},
+ {value: 0x812d, lo: 0x98, hi: 0x99},
+ {value: 0x812d, lo: 0xb5, hi: 0xb5},
+ {value: 0x812d, lo: 0xb7, hi: 0xb7},
+ {value: 0x812b, lo: 0xb9, hi: 0xb9},
+ // Block 0x25, offset 0xf6
+ {value: 0x0000, lo: 0x10},
+ {value: 0x2644, lo: 0x83, hi: 0x83},
+ {value: 0x264b, lo: 0x8d, hi: 0x8d},
+ {value: 0x2652, lo: 0x92, hi: 0x92},
+ {value: 0x2659, lo: 0x97, hi: 0x97},
+ {value: 0x2660, lo: 0x9c, hi: 0x9c},
+ {value: 0x263d, lo: 0xa9, hi: 0xa9},
+ {value: 0x8126, lo: 0xb1, hi: 0xb1},
+ {value: 0x8127, lo: 0xb2, hi: 0xb2},
+ {value: 0x4a66, lo: 0xb3, hi: 0xb3},
+ {value: 0x8128, lo: 0xb4, hi: 0xb4},
+ {value: 0x4a6f, lo: 0xb5, hi: 0xb5},
+ {value: 0x464a, lo: 0xb6, hi: 0xb6},
+ {value: 0x468a, lo: 0xb7, hi: 0xb7},
+ {value: 0x4652, lo: 0xb8, hi: 0xb8},
+ {value: 0x4695, lo: 0xb9, hi: 0xb9},
+ {value: 0x8127, lo: 0xba, hi: 0xbd},
+ // Block 0x26, offset 0x107
+ {value: 0x0000, lo: 0x0b},
+ {value: 0x8127, lo: 0x80, hi: 0x80},
+ {value: 0x4a78, lo: 0x81, hi: 0x81},
+ {value: 0x8132, lo: 0x82, hi: 0x83},
+ {value: 0x8104, lo: 0x84, hi: 0x84},
+ {value: 0x8132, lo: 0x86, hi: 0x87},
+ {value: 0x266e, lo: 0x93, hi: 0x93},
+ {value: 0x2675, lo: 0x9d, hi: 0x9d},
+ {value: 0x267c, lo: 0xa2, hi: 0xa2},
+ {value: 0x2683, lo: 0xa7, hi: 0xa7},
+ {value: 0x268a, lo: 0xac, hi: 0xac},
+ {value: 0x2667, lo: 0xb9, hi: 0xb9},
+ // Block 0x27, offset 0x113
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0x86, hi: 0x86},
+ // Block 0x28, offset 0x115
+ {value: 0x0000, lo: 0x05},
+ {value: 0xa000, lo: 0xa5, hi: 0xa5},
+ {value: 0x2d1e, lo: 0xa6, hi: 0xa6},
+ {value: 0x9900, lo: 0xae, hi: 0xae},
+ {value: 0x8102, lo: 0xb7, hi: 0xb7},
+ {value: 0x8104, lo: 0xb9, hi: 0xba},
+ // Block 0x29, offset 0x11b
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0x8d, hi: 0x8d},
+ // Block 0x2a, offset 0x11d
+ {value: 0x0000, lo: 0x01},
+ {value: 0x030f, lo: 0xbc, hi: 0xbc},
+ // Block 0x2b, offset 0x11f
+ {value: 0x0000, lo: 0x01},
+ {value: 0xa000, lo: 0x80, hi: 0x92},
+ // Block 0x2c, offset 0x121
+ {value: 0x0000, lo: 0x01},
+ {value: 0xb900, lo: 0xa1, hi: 0xb5},
+ // Block 0x2d, offset 0x123
+ {value: 0x0000, lo: 0x01},
+ {value: 0x9900, lo: 0xa8, hi: 0xbf},
+ // Block 0x2e, offset 0x125
+ {value: 0x0000, lo: 0x01},
+ {value: 0x9900, lo: 0x80, hi: 0x82},
+ // Block 0x2f, offset 0x127
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0x9d, hi: 0x9f},
+ // Block 0x30, offset 0x129
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x94, hi: 0x94},
+ {value: 0x8104, lo: 0xb4, hi: 0xb4},
+ // Block 0x31, offset 0x12c
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x92, hi: 0x92},
+ {value: 0x8132, lo: 0x9d, hi: 0x9d},
+ // Block 0x32, offset 0x12f
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8131, lo: 0xa9, hi: 0xa9},
+ // Block 0x33, offset 0x131
+ {value: 0x0004, lo: 0x02},
+ {value: 0x812e, lo: 0xb9, hi: 0xba},
+ {value: 0x812d, lo: 0xbb, hi: 0xbb},
+ // Block 0x34, offset 0x134
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8132, lo: 0x97, hi: 0x97},
+ {value: 0x812d, lo: 0x98, hi: 0x98},
+ // Block 0x35, offset 0x137
+ {value: 0x0000, lo: 0x03},
+ {value: 0x8104, lo: 0xa0, hi: 0xa0},
+ {value: 0x8132, lo: 0xb5, hi: 0xbc},
+ {value: 0x812d, lo: 0xbf, hi: 0xbf},
+ // Block 0x36, offset 0x13b
+ {value: 0x0000, lo: 0x04},
+ {value: 0x8132, lo: 0xb0, hi: 0xb4},
+ {value: 0x812d, lo: 0xb5, hi: 0xba},
+ {value: 0x8132, lo: 0xbb, hi: 0xbc},
+ {value: 0x812d, lo: 0xbd, hi: 0xbd},
+ // Block 0x37, offset 0x140
+ {value: 0x0000, lo: 0x08},
+ {value: 0x2d66, lo: 0x80, hi: 0x80},
+ {value: 0x2d6e, lo: 0x81, hi: 0x81},
+ {value: 0xa000, lo: 0x82, hi: 0x82},
+ {value: 0x2d76, lo: 0x83, hi: 0x83},
+ {value: 0x8104, lo: 0x84, hi: 0x84},
+ {value: 0x8132, lo: 0xab, hi: 0xab},
+ {value: 0x812d, lo: 0xac, hi: 0xac},
+ {value: 0x8132, lo: 0xad, hi: 0xb3},
+ // Block 0x38, offset 0x149
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0xaa, hi: 0xab},
+ // Block 0x39, offset 0x14b
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8102, lo: 0xa6, hi: 0xa6},
+ {value: 0x8104, lo: 0xb2, hi: 0xb3},
+ // Block 0x3a, offset 0x14e
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8102, lo: 0xb7, hi: 0xb7},
+ // Block 0x3b, offset 0x150
+ {value: 0x0000, lo: 0x0a},
+ {value: 0x8132, lo: 0x90, hi: 0x92},
+ {value: 0x8101, lo: 0x94, hi: 0x94},
+ {value: 0x812d, lo: 0x95, hi: 0x99},
+ {value: 0x8132, lo: 0x9a, hi: 0x9b},
+ {value: 0x812d, lo: 0x9c, hi: 0x9f},
+ {value: 0x8132, lo: 0xa0, hi: 0xa0},
+ {value: 0x8101, lo: 0xa2, hi: 0xa8},
+ {value: 0x812d, lo: 0xad, hi: 0xad},
+ {value: 0x8132, lo: 0xb4, hi: 0xb4},
+ {value: 0x8132, lo: 0xb8, hi: 0xb9},
+ // Block 0x3c, offset 0x15b
+ {value: 0x0002, lo: 0x0a},
+ {value: 0x0043, lo: 0xac, hi: 0xac},
+ {value: 0x00d1, lo: 0xad, hi: 0xad},
+ {value: 0x0045, lo: 0xae, hi: 0xae},
+ {value: 0x0049, lo: 0xb0, hi: 0xb1},
+ {value: 0x00e6, lo: 0xb2, hi: 0xb2},
+ {value: 0x004f, lo: 0xb3, hi: 0xba},
+ {value: 0x005f, lo: 0xbc, hi: 0xbc},
+ {value: 0x00ef, lo: 0xbd, hi: 0xbd},
+ {value: 0x0061, lo: 0xbe, hi: 0xbe},
+ {value: 0x0065, lo: 0xbf, hi: 0xbf},
+ // Block 0x3d, offset 0x166
+ {value: 0x0000, lo: 0x0f},
+ {value: 0x8132, lo: 0x80, hi: 0x81},
+ {value: 0x812d, lo: 0x82, hi: 0x82},
+ {value: 0x8132, lo: 0x83, hi: 0x89},
+ {value: 0x812d, lo: 0x8a, hi: 0x8a},
+ {value: 0x8132, lo: 0x8b, hi: 0x8c},
+ {value: 0x8135, lo: 0x8d, hi: 0x8d},
+ {value: 0x812a, lo: 0x8e, hi: 0x8e},
+ {value: 0x812d, lo: 0x8f, hi: 0x8f},
+ {value: 0x8129, lo: 0x90, hi: 0x90},
+ {value: 0x8132, lo: 0x91, hi: 0xb5},
+ {value: 0x8132, lo: 0xbb, hi: 0xbb},
+ {value: 0x8134, lo: 0xbc, hi: 0xbc},
+ {value: 0x812d, lo: 0xbd, hi: 0xbd},
+ {value: 0x8132, lo: 0xbe, hi: 0xbe},
+ {value: 0x812d, lo: 0xbf, hi: 0xbf},
+ // Block 0x3e, offset 0x176
+ {value: 0x0000, lo: 0x0d},
+ {value: 0x0001, lo: 0x80, hi: 0x8a},
+ {value: 0x043b, lo: 0x91, hi: 0x91},
+ {value: 0x429b, lo: 0x97, hi: 0x97},
+ {value: 0x001d, lo: 0xa4, hi: 0xa4},
+ {value: 0x1873, lo: 0xa5, hi: 0xa5},
+ {value: 0x1b5c, lo: 0xa6, hi: 0xa6},
+ {value: 0x0001, lo: 0xaf, hi: 0xaf},
+ {value: 0x2691, lo: 0xb3, hi: 0xb3},
+ {value: 0x27fe, lo: 0xb4, hi: 0xb4},
+ {value: 0x2698, lo: 0xb6, hi: 0xb6},
+ {value: 0x2808, lo: 0xb7, hi: 0xb7},
+ {value: 0x186d, lo: 0xbc, hi: 0xbc},
+ {value: 0x4269, lo: 0xbe, hi: 0xbe},
+ // Block 0x3f, offset 0x184
+ {value: 0x0002, lo: 0x0d},
+ {value: 0x1933, lo: 0x87, hi: 0x87},
+ {value: 0x1930, lo: 0x88, hi: 0x88},
+ {value: 0x1870, lo: 0x89, hi: 0x89},
+ {value: 0x298e, lo: 0x97, hi: 0x97},
+ {value: 0x0001, lo: 0x9f, hi: 0x9f},
+ {value: 0x0021, lo: 0xb0, hi: 0xb0},
+ {value: 0x0093, lo: 0xb1, hi: 0xb1},
+ {value: 0x0029, lo: 0xb4, hi: 0xb9},
+ {value: 0x0017, lo: 0xba, hi: 0xba},
+ {value: 0x0467, lo: 0xbb, hi: 0xbb},
+ {value: 0x003b, lo: 0xbc, hi: 0xbc},
+ {value: 0x0011, lo: 0xbd, hi: 0xbe},
+ {value: 0x009d, lo: 0xbf, hi: 0xbf},
+ // Block 0x40, offset 0x192
+ {value: 0x0002, lo: 0x0f},
+ {value: 0x0021, lo: 0x80, hi: 0x89},
+ {value: 0x0017, lo: 0x8a, hi: 0x8a},
+ {value: 0x0467, lo: 0x8b, hi: 0x8b},
+ {value: 0x003b, lo: 0x8c, hi: 0x8c},
+ {value: 0x0011, lo: 0x8d, hi: 0x8e},
+ {value: 0x0083, lo: 0x90, hi: 0x90},
+ {value: 0x008b, lo: 0x91, hi: 0x91},
+ {value: 0x009f, lo: 0x92, hi: 0x92},
+ {value: 0x00b1, lo: 0x93, hi: 0x93},
+ {value: 0x0104, lo: 0x94, hi: 0x94},
+ {value: 0x0091, lo: 0x95, hi: 0x95},
+ {value: 0x0097, lo: 0x96, hi: 0x99},
+ {value: 0x00a1, lo: 0x9a, hi: 0x9a},
+ {value: 0x00a7, lo: 0x9b, hi: 0x9c},
+ {value: 0x1999, lo: 0xa8, hi: 0xa8},
+ // Block 0x41, offset 0x1a2
+ {value: 0x0000, lo: 0x0d},
+ {value: 0x8132, lo: 0x90, hi: 0x91},
+ {value: 0x8101, lo: 0x92, hi: 0x93},
+ {value: 0x8132, lo: 0x94, hi: 0x97},
+ {value: 0x8101, lo: 0x98, hi: 0x9a},
+ {value: 0x8132, lo: 0x9b, hi: 0x9c},
+ {value: 0x8132, lo: 0xa1, hi: 0xa1},
+ {value: 0x8101, lo: 0xa5, hi: 0xa6},
+ {value: 0x8132, lo: 0xa7, hi: 0xa7},
+ {value: 0x812d, lo: 0xa8, hi: 0xa8},
+ {value: 0x8132, lo: 0xa9, hi: 0xa9},
+ {value: 0x8101, lo: 0xaa, hi: 0xab},
+ {value: 0x812d, lo: 0xac, hi: 0xaf},
+ {value: 0x8132, lo: 0xb0, hi: 0xb0},
+ // Block 0x42, offset 0x1b0
+ {value: 0x0007, lo: 0x06},
+ {value: 0x2180, lo: 0x89, hi: 0x89},
+ {value: 0xa000, lo: 0x90, hi: 0x90},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ {value: 0xa000, lo: 0x94, hi: 0x94},
+ {value: 0x3bb9, lo: 0x9a, hi: 0x9b},
+ {value: 0x3bc7, lo: 0xae, hi: 0xae},
+ // Block 0x43, offset 0x1b7
+ {value: 0x000e, lo: 0x05},
+ {value: 0x3bce, lo: 0x8d, hi: 0x8e},
+ {value: 0x3bd5, lo: 0x8f, hi: 0x8f},
+ {value: 0xa000, lo: 0x90, hi: 0x90},
+ {value: 0xa000, lo: 0x92, hi: 0x92},
+ {value: 0xa000, lo: 0x94, hi: 0x94},
+ // Block 0x44, offset 0x1bd
+ {value: 0x0173, lo: 0x0e},
+ {value: 0xa000, lo: 0x83, hi: 0x83},
+ {value: 0x3be3, lo: 0x84, hi: 0x84},
+ {value: 0xa000, lo: 0x88, hi: 0x88},
+ {value: 0x3bea, lo: 0x89, hi: 0x89},
+ {value: 0xa000, lo: 0x8b, hi: 0x8b},
+ {value: 0x3bf1, lo: 0x8c, hi: 0x8c},
+ {value: 0xa000, lo: 0xa3, hi: 0xa3},
+ {value: 0x3bf8, lo: 0xa4, hi: 0xa4},
+ {value: 0xa000, lo: 0xa5, hi: 0xa5},
+ {value: 0x3bff, lo: 0xa6, hi: 0xa6},
+ {value: 0x269f, lo: 0xac, hi: 0xad},
+ {value: 0x26a6, lo: 0xaf, hi: 0xaf},
+ {value: 0x281c, lo: 0xb0, hi: 0xb0},
+ {value: 0xa000, lo: 0xbc, hi: 0xbc},
+ // Block 0x45, offset 0x1cc
+ {value: 0x0007, lo: 0x03},
+ {value: 0x3c68, lo: 0xa0, hi: 0xa1},
+ {value: 0x3c92, lo: 0xa2, hi: 0xa3},
+ {value: 0x3cbc, lo: 0xaa, hi: 0xad},
+ // Block 0x46, offset 0x1d0
+ {value: 0x0004, lo: 0x01},
+ {value: 0x048b, lo: 0xa9, hi: 0xaa},
+ // Block 0x47, offset 0x1d2
+ {value: 0x0002, lo: 0x03},
+ {value: 0x0057, lo: 0x80, hi: 0x8f},
+ {value: 0x0083, lo: 0x90, hi: 0xa9},
+ {value: 0x0021, lo: 0xaa, hi: 0xaa},
+ // Block 0x48, offset 0x1d6
+ {value: 0x0000, lo: 0x01},
+ {value: 0x299b, lo: 0x8c, hi: 0x8c},
+ // Block 0x49, offset 0x1d8
+ {value: 0x0263, lo: 0x02},
+ {value: 0x1b8c, lo: 0xb4, hi: 0xb4},
+ {value: 0x192d, lo: 0xb5, hi: 0xb6},
+ // Block 0x4a, offset 0x1db
+ {value: 0x0000, lo: 0x01},
+ {value: 0x4573, lo: 0x9c, hi: 0x9c},
+ // Block 0x4b, offset 0x1dd
+ {value: 0x0000, lo: 0x02},
+ {value: 0x0095, lo: 0xbc, hi: 0xbc},
+ {value: 0x006d, lo: 0xbd, hi: 0xbd},
+ // Block 0x4c, offset 0x1e0
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0xaf, hi: 0xb1},
+ // Block 0x4d, offset 0x1e2
+ {value: 0x0000, lo: 0x02},
+ {value: 0x047f, lo: 0xaf, hi: 0xaf},
+ {value: 0x8104, lo: 0xbf, hi: 0xbf},
+ // Block 0x4e, offset 0x1e5
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0xa0, hi: 0xbf},
+ // Block 0x4f, offset 0x1e7
+ {value: 0x0000, lo: 0x01},
+ {value: 0x0dc3, lo: 0x9f, hi: 0x9f},
+ // Block 0x50, offset 0x1e9
+ {value: 0x0000, lo: 0x01},
+ {value: 0x162f, lo: 0xb3, hi: 0xb3},
+ // Block 0x51, offset 0x1eb
+ {value: 0x0004, lo: 0x0b},
+ {value: 0x1597, lo: 0x80, hi: 0x82},
+ {value: 0x15af, lo: 0x83, hi: 0x83},
+ {value: 0x15c7, lo: 0x84, hi: 0x85},
+ {value: 0x15d7, lo: 0x86, hi: 0x89},
+ {value: 0x15eb, lo: 0x8a, hi: 0x8c},
+ {value: 0x15ff, lo: 0x8d, hi: 0x8d},
+ {value: 0x1607, lo: 0x8e, hi: 0x8e},
+ {value: 0x160f, lo: 0x8f, hi: 0x90},
+ {value: 0x161b, lo: 0x91, hi: 0x93},
+ {value: 0x162b, lo: 0x94, hi: 0x94},
+ {value: 0x1633, lo: 0x95, hi: 0x95},
+ // Block 0x52, offset 0x1f7
+ {value: 0x0004, lo: 0x09},
+ {value: 0x0001, lo: 0x80, hi: 0x80},
+ {value: 0x812c, lo: 0xaa, hi: 0xaa},
+ {value: 0x8131, lo: 0xab, hi: 0xab},
+ {value: 0x8133, lo: 0xac, hi: 0xac},
+ {value: 0x812e, lo: 0xad, hi: 0xad},
+ {value: 0x812f, lo: 0xae, hi: 0xae},
+ {value: 0x812f, lo: 0xaf, hi: 0xaf},
+ {value: 0x04b3, lo: 0xb6, hi: 0xb6},
+ {value: 0x0887, lo: 0xb8, hi: 0xba},
+ // Block 0x53, offset 0x201
+ {value: 0x0005, lo: 0x09},
+ {value: 0x0313, lo: 0xb1, hi: 0xb1},
+ {value: 0x0317, lo: 0xb2, hi: 0xb2},
+ {value: 0x4345, lo: 0xb3, hi: 0xb3},
+ {value: 0x031b, lo: 0xb4, hi: 0xb4},
+ {value: 0x434a, lo: 0xb5, hi: 0xb6},
+ {value: 0x031f, lo: 0xb7, hi: 0xb7},
+ {value: 0x0323, lo: 0xb8, hi: 0xb8},
+ {value: 0x0327, lo: 0xb9, hi: 0xb9},
+ {value: 0x4354, lo: 0xba, hi: 0xbf},
+ // Block 0x54, offset 0x20b
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8132, lo: 0xaf, hi: 0xaf},
+ {value: 0x8132, lo: 0xb4, hi: 0xbd},
+ // Block 0x55, offset 0x20e
+ {value: 0x0000, lo: 0x03},
+ {value: 0x020f, lo: 0x9c, hi: 0x9c},
+ {value: 0x0212, lo: 0x9d, hi: 0x9d},
+ {value: 0x8132, lo: 0x9e, hi: 0x9f},
+ // Block 0x56, offset 0x212
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0xb0, hi: 0xb1},
+ // Block 0x57, offset 0x214
+ {value: 0x0000, lo: 0x01},
+ {value: 0x163b, lo: 0xb0, hi: 0xb0},
+ // Block 0x58, offset 0x216
+ {value: 0x000c, lo: 0x01},
+ {value: 0x00d7, lo: 0xb8, hi: 0xb9},
+ // Block 0x59, offset 0x218
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0x86, hi: 0x86},
+ // Block 0x5a, offset 0x21a
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x84, hi: 0x84},
+ {value: 0x8132, lo: 0xa0, hi: 0xb1},
+ // Block 0x5b, offset 0x21d
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0xab, hi: 0xad},
+ // Block 0x5c, offset 0x21f
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0x93, hi: 0x93},
+ // Block 0x5d, offset 0x221
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8102, lo: 0xb3, hi: 0xb3},
+ // Block 0x5e, offset 0x223
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0x80, hi: 0x80},
+ // Block 0x5f, offset 0x225
+ {value: 0x0000, lo: 0x05},
+ {value: 0x8132, lo: 0xb0, hi: 0xb0},
+ {value: 0x8132, lo: 0xb2, hi: 0xb3},
+ {value: 0x812d, lo: 0xb4, hi: 0xb4},
+ {value: 0x8132, lo: 0xb7, hi: 0xb8},
+ {value: 0x8132, lo: 0xbe, hi: 0xbf},
+ // Block 0x60, offset 0x22b
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8132, lo: 0x81, hi: 0x81},
+ {value: 0x8104, lo: 0xb6, hi: 0xb6},
+ // Block 0x61, offset 0x22e
+ {value: 0x0008, lo: 0x03},
+ {value: 0x1637, lo: 0x9c, hi: 0x9d},
+ {value: 0x0125, lo: 0x9e, hi: 0x9e},
+ {value: 0x1643, lo: 0x9f, hi: 0x9f},
+ // Block 0x62, offset 0x232
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0xad, hi: 0xad},
+ // Block 0x63, offset 0x234
+ {value: 0x0000, lo: 0x06},
+ {value: 0xe500, lo: 0x80, hi: 0x80},
+ {value: 0xc600, lo: 0x81, hi: 0x9b},
+ {value: 0xe500, lo: 0x9c, hi: 0x9c},
+ {value: 0xc600, lo: 0x9d, hi: 0xb7},
+ {value: 0xe500, lo: 0xb8, hi: 0xb8},
+ {value: 0xc600, lo: 0xb9, hi: 0xbf},
+ // Block 0x64, offset 0x23b
+ {value: 0x0000, lo: 0x05},
+ {value: 0xc600, lo: 0x80, hi: 0x93},
+ {value: 0xe500, lo: 0x94, hi: 0x94},
+ {value: 0xc600, lo: 0x95, hi: 0xaf},
+ {value: 0xe500, lo: 0xb0, hi: 0xb0},
+ {value: 0xc600, lo: 0xb1, hi: 0xbf},
+ // Block 0x65, offset 0x241
+ {value: 0x0000, lo: 0x05},
+ {value: 0xc600, lo: 0x80, hi: 0x8b},
+ {value: 0xe500, lo: 0x8c, hi: 0x8c},
+ {value: 0xc600, lo: 0x8d, hi: 0xa7},
+ {value: 0xe500, lo: 0xa8, hi: 0xa8},
+ {value: 0xc600, lo: 0xa9, hi: 0xbf},
+ // Block 0x66, offset 0x247
+ {value: 0x0000, lo: 0x07},
+ {value: 0xc600, lo: 0x80, hi: 0x83},
+ {value: 0xe500, lo: 0x84, hi: 0x84},
+ {value: 0xc600, lo: 0x85, hi: 0x9f},
+ {value: 0xe500, lo: 0xa0, hi: 0xa0},
+ {value: 0xc600, lo: 0xa1, hi: 0xbb},
+ {value: 0xe500, lo: 0xbc, hi: 0xbc},
+ {value: 0xc600, lo: 0xbd, hi: 0xbf},
+ // Block 0x67, offset 0x24f
+ {value: 0x0000, lo: 0x05},
+ {value: 0xc600, lo: 0x80, hi: 0x97},
+ {value: 0xe500, lo: 0x98, hi: 0x98},
+ {value: 0xc600, lo: 0x99, hi: 0xb3},
+ {value: 0xe500, lo: 0xb4, hi: 0xb4},
+ {value: 0xc600, lo: 0xb5, hi: 0xbf},
+ // Block 0x68, offset 0x255
+ {value: 0x0000, lo: 0x05},
+ {value: 0xc600, lo: 0x80, hi: 0x8f},
+ {value: 0xe500, lo: 0x90, hi: 0x90},
+ {value: 0xc600, lo: 0x91, hi: 0xab},
+ {value: 0xe500, lo: 0xac, hi: 0xac},
+ {value: 0xc600, lo: 0xad, hi: 0xbf},
+ // Block 0x69, offset 0x25b
+ {value: 0x0000, lo: 0x05},
+ {value: 0xc600, lo: 0x80, hi: 0x87},
+ {value: 0xe500, lo: 0x88, hi: 0x88},
+ {value: 0xc600, lo: 0x89, hi: 0xa3},
+ {value: 0xe500, lo: 0xa4, hi: 0xa4},
+ {value: 0xc600, lo: 0xa5, hi: 0xbf},
+ // Block 0x6a, offset 0x261
+ {value: 0x0000, lo: 0x03},
+ {value: 0xc600, lo: 0x80, hi: 0x87},
+ {value: 0xe500, lo: 0x88, hi: 0x88},
+ {value: 0xc600, lo: 0x89, hi: 0xa3},
+ // Block 0x6b, offset 0x265
+ {value: 0x0002, lo: 0x01},
+ {value: 0x0003, lo: 0x81, hi: 0xbf},
+ // Block 0x6c, offset 0x267
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0xbd, hi: 0xbd},
+ // Block 0x6d, offset 0x269
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0xa0, hi: 0xa0},
+ // Block 0x6e, offset 0x26b
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0xb6, hi: 0xba},
+ // Block 0x6f, offset 0x26d
+ {value: 0x002c, lo: 0x05},
+ {value: 0x812d, lo: 0x8d, hi: 0x8d},
+ {value: 0x8132, lo: 0x8f, hi: 0x8f},
+ {value: 0x8132, lo: 0xb8, hi: 0xb8},
+ {value: 0x8101, lo: 0xb9, hi: 0xba},
+ {value: 0x8104, lo: 0xbf, hi: 0xbf},
+ // Block 0x70, offset 0x273
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8132, lo: 0xa5, hi: 0xa5},
+ {value: 0x812d, lo: 0xa6, hi: 0xa6},
+ // Block 0x71, offset 0x276
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x86, hi: 0x86},
+ {value: 0x8104, lo: 0xbf, hi: 0xbf},
+ // Block 0x72, offset 0x279
+ {value: 0x17fe, lo: 0x07},
+ {value: 0xa000, lo: 0x99, hi: 0x99},
+ {value: 0x4238, lo: 0x9a, hi: 0x9a},
+ {value: 0xa000, lo: 0x9b, hi: 0x9b},
+ {value: 0x4242, lo: 0x9c, hi: 0x9c},
+ {value: 0xa000, lo: 0xa5, hi: 0xa5},
+ {value: 0x424c, lo: 0xab, hi: 0xab},
+ {value: 0x8104, lo: 0xb9, hi: 0xba},
+ // Block 0x73, offset 0x281
+ {value: 0x0000, lo: 0x06},
+ {value: 0x8132, lo: 0x80, hi: 0x82},
+ {value: 0x9900, lo: 0xa7, hi: 0xa7},
+ {value: 0x2d7e, lo: 0xae, hi: 0xae},
+ {value: 0x2d88, lo: 0xaf, hi: 0xaf},
+ {value: 0xa000, lo: 0xb1, hi: 0xb2},
+ {value: 0x8104, lo: 0xb3, hi: 0xb4},
+ // Block 0x74, offset 0x288
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x80, hi: 0x80},
+ {value: 0x8102, lo: 0x8a, hi: 0x8a},
+ // Block 0x75, offset 0x28b
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0xb5, hi: 0xb5},
+ {value: 0x8102, lo: 0xb6, hi: 0xb6},
+ // Block 0x76, offset 0x28e
+ {value: 0x0002, lo: 0x01},
+ {value: 0x8102, lo: 0xa9, hi: 0xaa},
+ // Block 0x77, offset 0x290
+ {value: 0x0000, lo: 0x07},
+ {value: 0xa000, lo: 0x87, hi: 0x87},
+ {value: 0x2d92, lo: 0x8b, hi: 0x8b},
+ {value: 0x2d9c, lo: 0x8c, hi: 0x8c},
+ {value: 0x8104, lo: 0x8d, hi: 0x8d},
+ {value: 0x9900, lo: 0x97, hi: 0x97},
+ {value: 0x8132, lo: 0xa6, hi: 0xac},
+ {value: 0x8132, lo: 0xb0, hi: 0xb4},
+ // Block 0x78, offset 0x298
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x82, hi: 0x82},
+ {value: 0x8102, lo: 0x86, hi: 0x86},
+ // Block 0x79, offset 0x29b
+ {value: 0x6b5a, lo: 0x06},
+ {value: 0x9900, lo: 0xb0, hi: 0xb0},
+ {value: 0xa000, lo: 0xb9, hi: 0xb9},
+ {value: 0x9900, lo: 0xba, hi: 0xba},
+ {value: 0x2db0, lo: 0xbb, hi: 0xbb},
+ {value: 0x2da6, lo: 0xbc, hi: 0xbd},
+ {value: 0x2dba, lo: 0xbe, hi: 0xbe},
+ // Block 0x7a, offset 0x2a2
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0x82, hi: 0x82},
+ {value: 0x8102, lo: 0x83, hi: 0x83},
+ // Block 0x7b, offset 0x2a5
+ {value: 0x0000, lo: 0x05},
+ {value: 0x9900, lo: 0xaf, hi: 0xaf},
+ {value: 0xa000, lo: 0xb8, hi: 0xb9},
+ {value: 0x2dc4, lo: 0xba, hi: 0xba},
+ {value: 0x2dce, lo: 0xbb, hi: 0xbb},
+ {value: 0x8104, lo: 0xbf, hi: 0xbf},
+ // Block 0x7c, offset 0x2ab
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8102, lo: 0x80, hi: 0x80},
+ // Block 0x7d, offset 0x2ad
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0xbf, hi: 0xbf},
+ // Block 0x7e, offset 0x2af
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8104, lo: 0xb6, hi: 0xb6},
+ {value: 0x8102, lo: 0xb7, hi: 0xb7},
+ // Block 0x7f, offset 0x2b2
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8104, lo: 0xab, hi: 0xab},
+ // Block 0x80, offset 0x2b4
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8101, lo: 0xb0, hi: 0xb4},
+ // Block 0x81, offset 0x2b6
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0xb0, hi: 0xb6},
+ // Block 0x82, offset 0x2b8
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8101, lo: 0x9e, hi: 0x9e},
+ // Block 0x83, offset 0x2ba
+ {value: 0x0000, lo: 0x0c},
+ {value: 0x4662, lo: 0x9e, hi: 0x9e},
+ {value: 0x466c, lo: 0x9f, hi: 0x9f},
+ {value: 0x46a0, lo: 0xa0, hi: 0xa0},
+ {value: 0x46ae, lo: 0xa1, hi: 0xa1},
+ {value: 0x46bc, lo: 0xa2, hi: 0xa2},
+ {value: 0x46ca, lo: 0xa3, hi: 0xa3},
+ {value: 0x46d8, lo: 0xa4, hi: 0xa4},
+ {value: 0x812b, lo: 0xa5, hi: 0xa6},
+ {value: 0x8101, lo: 0xa7, hi: 0xa9},
+ {value: 0x8130, lo: 0xad, hi: 0xad},
+ {value: 0x812b, lo: 0xae, hi: 0xb2},
+ {value: 0x812d, lo: 0xbb, hi: 0xbf},
+ // Block 0x84, offset 0x2c7
+ {value: 0x0000, lo: 0x09},
+ {value: 0x812d, lo: 0x80, hi: 0x82},
+ {value: 0x8132, lo: 0x85, hi: 0x89},
+ {value: 0x812d, lo: 0x8a, hi: 0x8b},
+ {value: 0x8132, lo: 0xaa, hi: 0xad},
+ {value: 0x4676, lo: 0xbb, hi: 0xbb},
+ {value: 0x4680, lo: 0xbc, hi: 0xbc},
+ {value: 0x46e6, lo: 0xbd, hi: 0xbd},
+ {value: 0x4702, lo: 0xbe, hi: 0xbe},
+ {value: 0x46f4, lo: 0xbf, hi: 0xbf},
+ // Block 0x85, offset 0x2d1
+ {value: 0x0000, lo: 0x01},
+ {value: 0x4710, lo: 0x80, hi: 0x80},
+ // Block 0x86, offset 0x2d3
+ {value: 0x0000, lo: 0x01},
+ {value: 0x8132, lo: 0x82, hi: 0x84},
+ // Block 0x87, offset 0x2d5
+ {value: 0x0002, lo: 0x03},
+ {value: 0x0043, lo: 0x80, hi: 0x99},
+ {value: 0x0083, lo: 0x9a, hi: 0xb3},
+ {value: 0x0043, lo: 0xb4, hi: 0xbf},
+ // Block 0x88, offset 0x2d9
+ {value: 0x0002, lo: 0x04},
+ {value: 0x005b, lo: 0x80, hi: 0x8d},
+ {value: 0x0083, lo: 0x8e, hi: 0x94},
+ {value: 0x0093, lo: 0x96, hi: 0xa7},
+ {value: 0x0043, lo: 0xa8, hi: 0xbf},
+ // Block 0x89, offset 0x2de
+ {value: 0x0002, lo: 0x0b},
+ {value: 0x0073, lo: 0x80, hi: 0x81},
+ {value: 0x0083, lo: 0x82, hi: 0x9b},
+ {value: 0x0043, lo: 0x9c, hi: 0x9c},
+ {value: 0x0047, lo: 0x9e, hi: 0x9f},
+ {value: 0x004f, lo: 0xa2, hi: 0xa2},
+ {value: 0x0055, lo: 0xa5, hi: 0xa6},
+ {value: 0x005d, lo: 0xa9, hi: 0xac},
+ {value: 0x0067, lo: 0xae, hi: 0xb5},
+ {value: 0x0083, lo: 0xb6, hi: 0xb9},
+ {value: 0x008d, lo: 0xbb, hi: 0xbb},
+ {value: 0x0091, lo: 0xbd, hi: 0xbf},
+ // Block 0x8a, offset 0x2ea
+ {value: 0x0002, lo: 0x04},
+ {value: 0x0097, lo: 0x80, hi: 0x83},
+ {value: 0x00a1, lo: 0x85, hi: 0x8f},
+ {value: 0x0043, lo: 0x90, hi: 0xa9},
+ {value: 0x0083, lo: 0xaa, hi: 0xbf},
+ // Block 0x8b, offset 0x2ef
+ {value: 0x0002, lo: 0x08},
+ {value: 0x00af, lo: 0x80, hi: 0x83},
+ {value: 0x0043, lo: 0x84, hi: 0x85},
+ {value: 0x0049, lo: 0x87, hi: 0x8a},
+ {value: 0x0055, lo: 0x8d, hi: 0x94},
+ {value: 0x0067, lo: 0x96, hi: 0x9c},
+ {value: 0x0083, lo: 0x9e, hi: 0xb7},
+ {value: 0x0043, lo: 0xb8, hi: 0xb9},
+ {value: 0x0049, lo: 0xbb, hi: 0xbe},
+ // Block 0x8c, offset 0x2f8
+ {value: 0x0002, lo: 0x05},
+ {value: 0x0053, lo: 0x80, hi: 0x84},
+ {value: 0x005f, lo: 0x86, hi: 0x86},
+ {value: 0x0067, lo: 0x8a, hi: 0x90},
+ {value: 0x0083, lo: 0x92, hi: 0xab},
+ {value: 0x0043, lo: 0xac, hi: 0xbf},
+ // Block 0x8d, offset 0x2fe
+ {value: 0x0002, lo: 0x04},
+ {value: 0x006b, lo: 0x80, hi: 0x85},
+ {value: 0x0083, lo: 0x86, hi: 0x9f},
+ {value: 0x0043, lo: 0xa0, hi: 0xb9},
+ {value: 0x0083, lo: 0xba, hi: 0xbf},
+ // Block 0x8e, offset 0x303
+ {value: 0x0002, lo: 0x03},
+ {value: 0x008f, lo: 0x80, hi: 0x93},
+ {value: 0x0043, lo: 0x94, hi: 0xad},
+ {value: 0x0083, lo: 0xae, hi: 0xbf},
+ // Block 0x8f, offset 0x307
+ {value: 0x0002, lo: 0x04},
+ {value: 0x00a7, lo: 0x80, hi: 0x87},
+ {value: 0x0043, lo: 0x88, hi: 0xa1},
+ {value: 0x0083, lo: 0xa2, hi: 0xbb},
+ {value: 0x0043, lo: 0xbc, hi: 0xbf},
+ // Block 0x90, offset 0x30c
+ {value: 0x0002, lo: 0x03},
+ {value: 0x004b, lo: 0x80, hi: 0x95},
+ {value: 0x0083, lo: 0x96, hi: 0xaf},
+ {value: 0x0043, lo: 0xb0, hi: 0xbf},
+ // Block 0x91, offset 0x310
+ {value: 0x0003, lo: 0x0f},
+ {value: 0x01b8, lo: 0x80, hi: 0x80},
+ {value: 0x045f, lo: 0x81, hi: 0x81},
+ {value: 0x01bb, lo: 0x82, hi: 0x9a},
+ {value: 0x045b, lo: 0x9b, hi: 0x9b},
+ {value: 0x01c7, lo: 0x9c, hi: 0x9c},
+ {value: 0x01d0, lo: 0x9d, hi: 0x9d},
+ {value: 0x01d6, lo: 0x9e, hi: 0x9e},
+ {value: 0x01fa, lo: 0x9f, hi: 0x9f},
+ {value: 0x01eb, lo: 0xa0, hi: 0xa0},
+ {value: 0x01e8, lo: 0xa1, hi: 0xa1},
+ {value: 0x0173, lo: 0xa2, hi: 0xb2},
+ {value: 0x0188, lo: 0xb3, hi: 0xb3},
+ {value: 0x01a6, lo: 0xb4, hi: 0xba},
+ {value: 0x045f, lo: 0xbb, hi: 0xbb},
+ {value: 0x01bb, lo: 0xbc, hi: 0xbf},
+ // Block 0x92, offset 0x320
+ {value: 0x0003, lo: 0x0d},
+ {value: 0x01c7, lo: 0x80, hi: 0x94},
+ {value: 0x045b, lo: 0x95, hi: 0x95},
+ {value: 0x01c7, lo: 0x96, hi: 0x96},
+ {value: 0x01d0, lo: 0x97, hi: 0x97},
+ {value: 0x01d6, lo: 0x98, hi: 0x98},
+ {value: 0x01fa, lo: 0x99, hi: 0x99},
+ {value: 0x01eb, lo: 0x9a, hi: 0x9a},
+ {value: 0x01e8, lo: 0x9b, hi: 0x9b},
+ {value: 0x0173, lo: 0x9c, hi: 0xac},
+ {value: 0x0188, lo: 0xad, hi: 0xad},
+ {value: 0x01a6, lo: 0xae, hi: 0xb4},
+ {value: 0x045f, lo: 0xb5, hi: 0xb5},
+ {value: 0x01bb, lo: 0xb6, hi: 0xbf},
+ // Block 0x93, offset 0x32e
+ {value: 0x0003, lo: 0x0d},
+ {value: 0x01d9, lo: 0x80, hi: 0x8e},
+ {value: 0x045b, lo: 0x8f, hi: 0x8f},
+ {value: 0x01c7, lo: 0x90, hi: 0x90},
+ {value: 0x01d0, lo: 0x91, hi: 0x91},
+ {value: 0x01d6, lo: 0x92, hi: 0x92},
+ {value: 0x01fa, lo: 0x93, hi: 0x93},
+ {value: 0x01eb, lo: 0x94, hi: 0x94},
+ {value: 0x01e8, lo: 0x95, hi: 0x95},
+ {value: 0x0173, lo: 0x96, hi: 0xa6},
+ {value: 0x0188, lo: 0xa7, hi: 0xa7},
+ {value: 0x01a6, lo: 0xa8, hi: 0xae},
+ {value: 0x045f, lo: 0xaf, hi: 0xaf},
+ {value: 0x01bb, lo: 0xb0, hi: 0xbf},
+ // Block 0x94, offset 0x33c
+ {value: 0x0003, lo: 0x0d},
+ {value: 0x01eb, lo: 0x80, hi: 0x88},
+ {value: 0x045b, lo: 0x89, hi: 0x89},
+ {value: 0x01c7, lo: 0x8a, hi: 0x8a},
+ {value: 0x01d0, lo: 0x8b, hi: 0x8b},
+ {value: 0x01d6, lo: 0x8c, hi: 0x8c},
+ {value: 0x01fa, lo: 0x8d, hi: 0x8d},
+ {value: 0x01eb, lo: 0x8e, hi: 0x8e},
+ {value: 0x01e8, lo: 0x8f, hi: 0x8f},
+ {value: 0x0173, lo: 0x90, hi: 0xa0},
+ {value: 0x0188, lo: 0xa1, hi: 0xa1},
+ {value: 0x01a6, lo: 0xa2, hi: 0xa8},
+ {value: 0x045f, lo: 0xa9, hi: 0xa9},
+ {value: 0x01bb, lo: 0xaa, hi: 0xbf},
+ // Block 0x95, offset 0x34a
+ {value: 0x0000, lo: 0x05},
+ {value: 0x8132, lo: 0x80, hi: 0x86},
+ {value: 0x8132, lo: 0x88, hi: 0x98},
+ {value: 0x8132, lo: 0x9b, hi: 0xa1},
+ {value: 0x8132, lo: 0xa3, hi: 0xa4},
+ {value: 0x8132, lo: 0xa6, hi: 0xaa},
+ // Block 0x96, offset 0x350
+ {value: 0x0000, lo: 0x01},
+ {value: 0x812d, lo: 0x90, hi: 0x96},
+ // Block 0x97, offset 0x352
+ {value: 0x0000, lo: 0x02},
+ {value: 0x8132, lo: 0x84, hi: 0x89},
+ {value: 0x8102, lo: 0x8a, hi: 0x8a},
+ // Block 0x98, offset 0x355
+ {value: 0x0002, lo: 0x09},
+ {value: 0x0063, lo: 0x80, hi: 0x89},
+ {value: 0x1951, lo: 0x8a, hi: 0x8a},
+ {value: 0x1981, lo: 0x8b, hi: 0x8b},
+ {value: 0x199c, lo: 0x8c, hi: 0x8c},
+ {value: 0x19a2, lo: 0x8d, hi: 0x8d},
+ {value: 0x1bc0, lo: 0x8e, hi: 0x8e},
+ {value: 0x19ae, lo: 0x8f, hi: 0x8f},
+ {value: 0x197b, lo: 0xaa, hi: 0xaa},
+ {value: 0x197e, lo: 0xab, hi: 0xab},
+ // Block 0x99, offset 0x35f
+ {value: 0x0000, lo: 0x01},
+ {value: 0x193f, lo: 0x90, hi: 0x90},
+ // Block 0x9a, offset 0x361
+ {value: 0x0028, lo: 0x09},
+ {value: 0x2862, lo: 0x80, hi: 0x80},
+ {value: 0x2826, lo: 0x81, hi: 0x81},
+ {value: 0x2830, lo: 0x82, hi: 0x82},
+ {value: 0x2844, lo: 0x83, hi: 0x84},
+ {value: 0x284e, lo: 0x85, hi: 0x86},
+ {value: 0x283a, lo: 0x87, hi: 0x87},
+ {value: 0x2858, lo: 0x88, hi: 0x88},
+ {value: 0x0b6f, lo: 0x90, hi: 0x90},
+ {value: 0x08e7, lo: 0x91, hi: 0x91},
+}
+
+// recompMap: 7520 bytes (entries only)
+var recompMap = map[uint32]rune{
+ 0x00410300: 0x00C0,
+ 0x00410301: 0x00C1,
+ 0x00410302: 0x00C2,
+ 0x00410303: 0x00C3,
+ 0x00410308: 0x00C4,
+ 0x0041030A: 0x00C5,
+ 0x00430327: 0x00C7,
+ 0x00450300: 0x00C8,
+ 0x00450301: 0x00C9,
+ 0x00450302: 0x00CA,
+ 0x00450308: 0x00CB,
+ 0x00490300: 0x00CC,
+ 0x00490301: 0x00CD,
+ 0x00490302: 0x00CE,
+ 0x00490308: 0x00CF,
+ 0x004E0303: 0x00D1,
+ 0x004F0300: 0x00D2,
+ 0x004F0301: 0x00D3,
+ 0x004F0302: 0x00D4,
+ 0x004F0303: 0x00D5,
+ 0x004F0308: 0x00D6,
+ 0x00550300: 0x00D9,
+ 0x00550301: 0x00DA,
+ 0x00550302: 0x00DB,
+ 0x00550308: 0x00DC,
+ 0x00590301: 0x00DD,
+ 0x00610300: 0x00E0,
+ 0x00610301: 0x00E1,
+ 0x00610302: 0x00E2,
+ 0x00610303: 0x00E3,
+ 0x00610308: 0x00E4,
+ 0x0061030A: 0x00E5,
+ 0x00630327: 0x00E7,
+ 0x00650300: 0x00E8,
+ 0x00650301: 0x00E9,
+ 0x00650302: 0x00EA,
+ 0x00650308: 0x00EB,
+ 0x00690300: 0x00EC,
+ 0x00690301: 0x00ED,
+ 0x00690302: 0x00EE,
+ 0x00690308: 0x00EF,
+ 0x006E0303: 0x00F1,
+ 0x006F0300: 0x00F2,
+ 0x006F0301: 0x00F3,
+ 0x006F0302: 0x00F4,
+ 0x006F0303: 0x00F5,
+ 0x006F0308: 0x00F6,
+ 0x00750300: 0x00F9,
+ 0x00750301: 0x00FA,
+ 0x00750302: 0x00FB,
+ 0x00750308: 0x00FC,
+ 0x00790301: 0x00FD,
+ 0x00790308: 0x00FF,
+ 0x00410304: 0x0100,
+ 0x00610304: 0x0101,
+ 0x00410306: 0x0102,
+ 0x00610306: 0x0103,
+ 0x00410328: 0x0104,
+ 0x00610328: 0x0105,
+ 0x00430301: 0x0106,
+ 0x00630301: 0x0107,
+ 0x00430302: 0x0108,
+ 0x00630302: 0x0109,
+ 0x00430307: 0x010A,
+ 0x00630307: 0x010B,
+ 0x0043030C: 0x010C,
+ 0x0063030C: 0x010D,
+ 0x0044030C: 0x010E,
+ 0x0064030C: 0x010F,
+ 0x00450304: 0x0112,
+ 0x00650304: 0x0113,
+ 0x00450306: 0x0114,
+ 0x00650306: 0x0115,
+ 0x00450307: 0x0116,
+ 0x00650307: 0x0117,
+ 0x00450328: 0x0118,
+ 0x00650328: 0x0119,
+ 0x0045030C: 0x011A,
+ 0x0065030C: 0x011B,
+ 0x00470302: 0x011C,
+ 0x00670302: 0x011D,
+ 0x00470306: 0x011E,
+ 0x00670306: 0x011F,
+ 0x00470307: 0x0120,
+ 0x00670307: 0x0121,
+ 0x00470327: 0x0122,
+ 0x00670327: 0x0123,
+ 0x00480302: 0x0124,
+ 0x00680302: 0x0125,
+ 0x00490303: 0x0128,
+ 0x00690303: 0x0129,
+ 0x00490304: 0x012A,
+ 0x00690304: 0x012B,
+ 0x00490306: 0x012C,
+ 0x00690306: 0x012D,
+ 0x00490328: 0x012E,
+ 0x00690328: 0x012F,
+ 0x00490307: 0x0130,
+ 0x004A0302: 0x0134,
+ 0x006A0302: 0x0135,
+ 0x004B0327: 0x0136,
+ 0x006B0327: 0x0137,
+ 0x004C0301: 0x0139,
+ 0x006C0301: 0x013A,
+ 0x004C0327: 0x013B,
+ 0x006C0327: 0x013C,
+ 0x004C030C: 0x013D,
+ 0x006C030C: 0x013E,
+ 0x004E0301: 0x0143,
+ 0x006E0301: 0x0144,
+ 0x004E0327: 0x0145,
+ 0x006E0327: 0x0146,
+ 0x004E030C: 0x0147,
+ 0x006E030C: 0x0148,
+ 0x004F0304: 0x014C,
+ 0x006F0304: 0x014D,
+ 0x004F0306: 0x014E,
+ 0x006F0306: 0x014F,
+ 0x004F030B: 0x0150,
+ 0x006F030B: 0x0151,
+ 0x00520301: 0x0154,
+ 0x00720301: 0x0155,
+ 0x00520327: 0x0156,
+ 0x00720327: 0x0157,
+ 0x0052030C: 0x0158,
+ 0x0072030C: 0x0159,
+ 0x00530301: 0x015A,
+ 0x00730301: 0x015B,
+ 0x00530302: 0x015C,
+ 0x00730302: 0x015D,
+ 0x00530327: 0x015E,
+ 0x00730327: 0x015F,
+ 0x0053030C: 0x0160,
+ 0x0073030C: 0x0161,
+ 0x00540327: 0x0162,
+ 0x00740327: 0x0163,
+ 0x0054030C: 0x0164,
+ 0x0074030C: 0x0165,
+ 0x00550303: 0x0168,
+ 0x00750303: 0x0169,
+ 0x00550304: 0x016A,
+ 0x00750304: 0x016B,
+ 0x00550306: 0x016C,
+ 0x00750306: 0x016D,
+ 0x0055030A: 0x016E,
+ 0x0075030A: 0x016F,
+ 0x0055030B: 0x0170,
+ 0x0075030B: 0x0171,
+ 0x00550328: 0x0172,
+ 0x00750328: 0x0173,
+ 0x00570302: 0x0174,
+ 0x00770302: 0x0175,
+ 0x00590302: 0x0176,
+ 0x00790302: 0x0177,
+ 0x00590308: 0x0178,
+ 0x005A0301: 0x0179,
+ 0x007A0301: 0x017A,
+ 0x005A0307: 0x017B,
+ 0x007A0307: 0x017C,
+ 0x005A030C: 0x017D,
+ 0x007A030C: 0x017E,
+ 0x004F031B: 0x01A0,
+ 0x006F031B: 0x01A1,
+ 0x0055031B: 0x01AF,
+ 0x0075031B: 0x01B0,
+ 0x0041030C: 0x01CD,
+ 0x0061030C: 0x01CE,
+ 0x0049030C: 0x01CF,
+ 0x0069030C: 0x01D0,
+ 0x004F030C: 0x01D1,
+ 0x006F030C: 0x01D2,
+ 0x0055030C: 0x01D3,
+ 0x0075030C: 0x01D4,
+ 0x00DC0304: 0x01D5,
+ 0x00FC0304: 0x01D6,
+ 0x00DC0301: 0x01D7,
+ 0x00FC0301: 0x01D8,
+ 0x00DC030C: 0x01D9,
+ 0x00FC030C: 0x01DA,
+ 0x00DC0300: 0x01DB,
+ 0x00FC0300: 0x01DC,
+ 0x00C40304: 0x01DE,
+ 0x00E40304: 0x01DF,
+ 0x02260304: 0x01E0,
+ 0x02270304: 0x01E1,
+ 0x00C60304: 0x01E2,
+ 0x00E60304: 0x01E3,
+ 0x0047030C: 0x01E6,
+ 0x0067030C: 0x01E7,
+ 0x004B030C: 0x01E8,
+ 0x006B030C: 0x01E9,
+ 0x004F0328: 0x01EA,
+ 0x006F0328: 0x01EB,
+ 0x01EA0304: 0x01EC,
+ 0x01EB0304: 0x01ED,
+ 0x01B7030C: 0x01EE,
+ 0x0292030C: 0x01EF,
+ 0x006A030C: 0x01F0,
+ 0x00470301: 0x01F4,
+ 0x00670301: 0x01F5,
+ 0x004E0300: 0x01F8,
+ 0x006E0300: 0x01F9,
+ 0x00C50301: 0x01FA,
+ 0x00E50301: 0x01FB,
+ 0x00C60301: 0x01FC,
+ 0x00E60301: 0x01FD,
+ 0x00D80301: 0x01FE,
+ 0x00F80301: 0x01FF,
+ 0x0041030F: 0x0200,
+ 0x0061030F: 0x0201,
+ 0x00410311: 0x0202,
+ 0x00610311: 0x0203,
+ 0x0045030F: 0x0204,
+ 0x0065030F: 0x0205,
+ 0x00450311: 0x0206,
+ 0x00650311: 0x0207,
+ 0x0049030F: 0x0208,
+ 0x0069030F: 0x0209,
+ 0x00490311: 0x020A,
+ 0x00690311: 0x020B,
+ 0x004F030F: 0x020C,
+ 0x006F030F: 0x020D,
+ 0x004F0311: 0x020E,
+ 0x006F0311: 0x020F,
+ 0x0052030F: 0x0210,
+ 0x0072030F: 0x0211,
+ 0x00520311: 0x0212,
+ 0x00720311: 0x0213,
+ 0x0055030F: 0x0214,
+ 0x0075030F: 0x0215,
+ 0x00550311: 0x0216,
+ 0x00750311: 0x0217,
+ 0x00530326: 0x0218,
+ 0x00730326: 0x0219,
+ 0x00540326: 0x021A,
+ 0x00740326: 0x021B,
+ 0x0048030C: 0x021E,
+ 0x0068030C: 0x021F,
+ 0x00410307: 0x0226,
+ 0x00610307: 0x0227,
+ 0x00450327: 0x0228,
+ 0x00650327: 0x0229,
+ 0x00D60304: 0x022A,
+ 0x00F60304: 0x022B,
+ 0x00D50304: 0x022C,
+ 0x00F50304: 0x022D,
+ 0x004F0307: 0x022E,
+ 0x006F0307: 0x022F,
+ 0x022E0304: 0x0230,
+ 0x022F0304: 0x0231,
+ 0x00590304: 0x0232,
+ 0x00790304: 0x0233,
+ 0x00A80301: 0x0385,
+ 0x03910301: 0x0386,
+ 0x03950301: 0x0388,
+ 0x03970301: 0x0389,
+ 0x03990301: 0x038A,
+ 0x039F0301: 0x038C,
+ 0x03A50301: 0x038E,
+ 0x03A90301: 0x038F,
+ 0x03CA0301: 0x0390,
+ 0x03990308: 0x03AA,
+ 0x03A50308: 0x03AB,
+ 0x03B10301: 0x03AC,
+ 0x03B50301: 0x03AD,
+ 0x03B70301: 0x03AE,
+ 0x03B90301: 0x03AF,
+ 0x03CB0301: 0x03B0,
+ 0x03B90308: 0x03CA,
+ 0x03C50308: 0x03CB,
+ 0x03BF0301: 0x03CC,
+ 0x03C50301: 0x03CD,
+ 0x03C90301: 0x03CE,
+ 0x03D20301: 0x03D3,
+ 0x03D20308: 0x03D4,
+ 0x04150300: 0x0400,
+ 0x04150308: 0x0401,
+ 0x04130301: 0x0403,
+ 0x04060308: 0x0407,
+ 0x041A0301: 0x040C,
+ 0x04180300: 0x040D,
+ 0x04230306: 0x040E,
+ 0x04180306: 0x0419,
+ 0x04380306: 0x0439,
+ 0x04350300: 0x0450,
+ 0x04350308: 0x0451,
+ 0x04330301: 0x0453,
+ 0x04560308: 0x0457,
+ 0x043A0301: 0x045C,
+ 0x04380300: 0x045D,
+ 0x04430306: 0x045E,
+ 0x0474030F: 0x0476,
+ 0x0475030F: 0x0477,
+ 0x04160306: 0x04C1,
+ 0x04360306: 0x04C2,
+ 0x04100306: 0x04D0,
+ 0x04300306: 0x04D1,
+ 0x04100308: 0x04D2,
+ 0x04300308: 0x04D3,
+ 0x04150306: 0x04D6,
+ 0x04350306: 0x04D7,
+ 0x04D80308: 0x04DA,
+ 0x04D90308: 0x04DB,
+ 0x04160308: 0x04DC,
+ 0x04360308: 0x04DD,
+ 0x04170308: 0x04DE,
+ 0x04370308: 0x04DF,
+ 0x04180304: 0x04E2,
+ 0x04380304: 0x04E3,
+ 0x04180308: 0x04E4,
+ 0x04380308: 0x04E5,
+ 0x041E0308: 0x04E6,
+ 0x043E0308: 0x04E7,
+ 0x04E80308: 0x04EA,
+ 0x04E90308: 0x04EB,
+ 0x042D0308: 0x04EC,
+ 0x044D0308: 0x04ED,
+ 0x04230304: 0x04EE,
+ 0x04430304: 0x04EF,
+ 0x04230308: 0x04F0,
+ 0x04430308: 0x04F1,
+ 0x0423030B: 0x04F2,
+ 0x0443030B: 0x04F3,
+ 0x04270308: 0x04F4,
+ 0x04470308: 0x04F5,
+ 0x042B0308: 0x04F8,
+ 0x044B0308: 0x04F9,
+ 0x06270653: 0x0622,
+ 0x06270654: 0x0623,
+ 0x06480654: 0x0624,
+ 0x06270655: 0x0625,
+ 0x064A0654: 0x0626,
+ 0x06D50654: 0x06C0,
+ 0x06C10654: 0x06C2,
+ 0x06D20654: 0x06D3,
+ 0x0928093C: 0x0929,
+ 0x0930093C: 0x0931,
+ 0x0933093C: 0x0934,
+ 0x09C709BE: 0x09CB,
+ 0x09C709D7: 0x09CC,
+ 0x0B470B56: 0x0B48,
+ 0x0B470B3E: 0x0B4B,
+ 0x0B470B57: 0x0B4C,
+ 0x0B920BD7: 0x0B94,
+ 0x0BC60BBE: 0x0BCA,
+ 0x0BC70BBE: 0x0BCB,
+ 0x0BC60BD7: 0x0BCC,
+ 0x0C460C56: 0x0C48,
+ 0x0CBF0CD5: 0x0CC0,
+ 0x0CC60CD5: 0x0CC7,
+ 0x0CC60CD6: 0x0CC8,
+ 0x0CC60CC2: 0x0CCA,
+ 0x0CCA0CD5: 0x0CCB,
+ 0x0D460D3E: 0x0D4A,
+ 0x0D470D3E: 0x0D4B,
+ 0x0D460D57: 0x0D4C,
+ 0x0DD90DCA: 0x0DDA,
+ 0x0DD90DCF: 0x0DDC,
+ 0x0DDC0DCA: 0x0DDD,
+ 0x0DD90DDF: 0x0DDE,
+ 0x1025102E: 0x1026,
+ 0x1B051B35: 0x1B06,
+ 0x1B071B35: 0x1B08,
+ 0x1B091B35: 0x1B0A,
+ 0x1B0B1B35: 0x1B0C,
+ 0x1B0D1B35: 0x1B0E,
+ 0x1B111B35: 0x1B12,
+ 0x1B3A1B35: 0x1B3B,
+ 0x1B3C1B35: 0x1B3D,
+ 0x1B3E1B35: 0x1B40,
+ 0x1B3F1B35: 0x1B41,
+ 0x1B421B35: 0x1B43,
+ 0x00410325: 0x1E00,
+ 0x00610325: 0x1E01,
+ 0x00420307: 0x1E02,
+ 0x00620307: 0x1E03,
+ 0x00420323: 0x1E04,
+ 0x00620323: 0x1E05,
+ 0x00420331: 0x1E06,
+ 0x00620331: 0x1E07,
+ 0x00C70301: 0x1E08,
+ 0x00E70301: 0x1E09,
+ 0x00440307: 0x1E0A,
+ 0x00640307: 0x1E0B,
+ 0x00440323: 0x1E0C,
+ 0x00640323: 0x1E0D,
+ 0x00440331: 0x1E0E,
+ 0x00640331: 0x1E0F,
+ 0x00440327: 0x1E10,
+ 0x00640327: 0x1E11,
+ 0x0044032D: 0x1E12,
+ 0x0064032D: 0x1E13,
+ 0x01120300: 0x1E14,
+ 0x01130300: 0x1E15,
+ 0x01120301: 0x1E16,
+ 0x01130301: 0x1E17,
+ 0x0045032D: 0x1E18,
+ 0x0065032D: 0x1E19,
+ 0x00450330: 0x1E1A,
+ 0x00650330: 0x1E1B,
+ 0x02280306: 0x1E1C,
+ 0x02290306: 0x1E1D,
+ 0x00460307: 0x1E1E,
+ 0x00660307: 0x1E1F,
+ 0x00470304: 0x1E20,
+ 0x00670304: 0x1E21,
+ 0x00480307: 0x1E22,
+ 0x00680307: 0x1E23,
+ 0x00480323: 0x1E24,
+ 0x00680323: 0x1E25,
+ 0x00480308: 0x1E26,
+ 0x00680308: 0x1E27,
+ 0x00480327: 0x1E28,
+ 0x00680327: 0x1E29,
+ 0x0048032E: 0x1E2A,
+ 0x0068032E: 0x1E2B,
+ 0x00490330: 0x1E2C,
+ 0x00690330: 0x1E2D,
+ 0x00CF0301: 0x1E2E,
+ 0x00EF0301: 0x1E2F,
+ 0x004B0301: 0x1E30,
+ 0x006B0301: 0x1E31,
+ 0x004B0323: 0x1E32,
+ 0x006B0323: 0x1E33,
+ 0x004B0331: 0x1E34,
+ 0x006B0331: 0x1E35,
+ 0x004C0323: 0x1E36,
+ 0x006C0323: 0x1E37,
+ 0x1E360304: 0x1E38,
+ 0x1E370304: 0x1E39,
+ 0x004C0331: 0x1E3A,
+ 0x006C0331: 0x1E3B,
+ 0x004C032D: 0x1E3C,
+ 0x006C032D: 0x1E3D,
+ 0x004D0301: 0x1E3E,
+ 0x006D0301: 0x1E3F,
+ 0x004D0307: 0x1E40,
+ 0x006D0307: 0x1E41,
+ 0x004D0323: 0x1E42,
+ 0x006D0323: 0x1E43,
+ 0x004E0307: 0x1E44,
+ 0x006E0307: 0x1E45,
+ 0x004E0323: 0x1E46,
+ 0x006E0323: 0x1E47,
+ 0x004E0331: 0x1E48,
+ 0x006E0331: 0x1E49,
+ 0x004E032D: 0x1E4A,
+ 0x006E032D: 0x1E4B,
+ 0x00D50301: 0x1E4C,
+ 0x00F50301: 0x1E4D,
+ 0x00D50308: 0x1E4E,
+ 0x00F50308: 0x1E4F,
+ 0x014C0300: 0x1E50,
+ 0x014D0300: 0x1E51,
+ 0x014C0301: 0x1E52,
+ 0x014D0301: 0x1E53,
+ 0x00500301: 0x1E54,
+ 0x00700301: 0x1E55,
+ 0x00500307: 0x1E56,
+ 0x00700307: 0x1E57,
+ 0x00520307: 0x1E58,
+ 0x00720307: 0x1E59,
+ 0x00520323: 0x1E5A,
+ 0x00720323: 0x1E5B,
+ 0x1E5A0304: 0x1E5C,
+ 0x1E5B0304: 0x1E5D,
+ 0x00520331: 0x1E5E,
+ 0x00720331: 0x1E5F,
+ 0x00530307: 0x1E60,
+ 0x00730307: 0x1E61,
+ 0x00530323: 0x1E62,
+ 0x00730323: 0x1E63,
+ 0x015A0307: 0x1E64,
+ 0x015B0307: 0x1E65,
+ 0x01600307: 0x1E66,
+ 0x01610307: 0x1E67,
+ 0x1E620307: 0x1E68,
+ 0x1E630307: 0x1E69,
+ 0x00540307: 0x1E6A,
+ 0x00740307: 0x1E6B,
+ 0x00540323: 0x1E6C,
+ 0x00740323: 0x1E6D,
+ 0x00540331: 0x1E6E,
+ 0x00740331: 0x1E6F,
+ 0x0054032D: 0x1E70,
+ 0x0074032D: 0x1E71,
+ 0x00550324: 0x1E72,
+ 0x00750324: 0x1E73,
+ 0x00550330: 0x1E74,
+ 0x00750330: 0x1E75,
+ 0x0055032D: 0x1E76,
+ 0x0075032D: 0x1E77,
+ 0x01680301: 0x1E78,
+ 0x01690301: 0x1E79,
+ 0x016A0308: 0x1E7A,
+ 0x016B0308: 0x1E7B,
+ 0x00560303: 0x1E7C,
+ 0x00760303: 0x1E7D,
+ 0x00560323: 0x1E7E,
+ 0x00760323: 0x1E7F,
+ 0x00570300: 0x1E80,
+ 0x00770300: 0x1E81,
+ 0x00570301: 0x1E82,
+ 0x00770301: 0x1E83,
+ 0x00570308: 0x1E84,
+ 0x00770308: 0x1E85,
+ 0x00570307: 0x1E86,
+ 0x00770307: 0x1E87,
+ 0x00570323: 0x1E88,
+ 0x00770323: 0x1E89,
+ 0x00580307: 0x1E8A,
+ 0x00780307: 0x1E8B,
+ 0x00580308: 0x1E8C,
+ 0x00780308: 0x1E8D,
+ 0x00590307: 0x1E8E,
+ 0x00790307: 0x1E8F,
+ 0x005A0302: 0x1E90,
+ 0x007A0302: 0x1E91,
+ 0x005A0323: 0x1E92,
+ 0x007A0323: 0x1E93,
+ 0x005A0331: 0x1E94,
+ 0x007A0331: 0x1E95,
+ 0x00680331: 0x1E96,
+ 0x00740308: 0x1E97,
+ 0x0077030A: 0x1E98,
+ 0x0079030A: 0x1E99,
+ 0x017F0307: 0x1E9B,
+ 0x00410323: 0x1EA0,
+ 0x00610323: 0x1EA1,
+ 0x00410309: 0x1EA2,
+ 0x00610309: 0x1EA3,
+ 0x00C20301: 0x1EA4,
+ 0x00E20301: 0x1EA5,
+ 0x00C20300: 0x1EA6,
+ 0x00E20300: 0x1EA7,
+ 0x00C20309: 0x1EA8,
+ 0x00E20309: 0x1EA9,
+ 0x00C20303: 0x1EAA,
+ 0x00E20303: 0x1EAB,
+ 0x1EA00302: 0x1EAC,
+ 0x1EA10302: 0x1EAD,
+ 0x01020301: 0x1EAE,
+ 0x01030301: 0x1EAF,
+ 0x01020300: 0x1EB0,
+ 0x01030300: 0x1EB1,
+ 0x01020309: 0x1EB2,
+ 0x01030309: 0x1EB3,
+ 0x01020303: 0x1EB4,
+ 0x01030303: 0x1EB5,
+ 0x1EA00306: 0x1EB6,
+ 0x1EA10306: 0x1EB7,
+ 0x00450323: 0x1EB8,
+ 0x00650323: 0x1EB9,
+ 0x00450309: 0x1EBA,
+ 0x00650309: 0x1EBB,
+ 0x00450303: 0x1EBC,
+ 0x00650303: 0x1EBD,
+ 0x00CA0301: 0x1EBE,
+ 0x00EA0301: 0x1EBF,
+ 0x00CA0300: 0x1EC0,
+ 0x00EA0300: 0x1EC1,
+ 0x00CA0309: 0x1EC2,
+ 0x00EA0309: 0x1EC3,
+ 0x00CA0303: 0x1EC4,
+ 0x00EA0303: 0x1EC5,
+ 0x1EB80302: 0x1EC6,
+ 0x1EB90302: 0x1EC7,
+ 0x00490309: 0x1EC8,
+ 0x00690309: 0x1EC9,
+ 0x00490323: 0x1ECA,
+ 0x00690323: 0x1ECB,
+ 0x004F0323: 0x1ECC,
+ 0x006F0323: 0x1ECD,
+ 0x004F0309: 0x1ECE,
+ 0x006F0309: 0x1ECF,
+ 0x00D40301: 0x1ED0,
+ 0x00F40301: 0x1ED1,
+ 0x00D40300: 0x1ED2,
+ 0x00F40300: 0x1ED3,
+ 0x00D40309: 0x1ED4,
+ 0x00F40309: 0x1ED5,
+ 0x00D40303: 0x1ED6,
+ 0x00F40303: 0x1ED7,
+ 0x1ECC0302: 0x1ED8,
+ 0x1ECD0302: 0x1ED9,
+ 0x01A00301: 0x1EDA,
+ 0x01A10301: 0x1EDB,
+ 0x01A00300: 0x1EDC,
+ 0x01A10300: 0x1EDD,
+ 0x01A00309: 0x1EDE,
+ 0x01A10309: 0x1EDF,
+ 0x01A00303: 0x1EE0,
+ 0x01A10303: 0x1EE1,
+ 0x01A00323: 0x1EE2,
+ 0x01A10323: 0x1EE3,
+ 0x00550323: 0x1EE4,
+ 0x00750323: 0x1EE5,
+ 0x00550309: 0x1EE6,
+ 0x00750309: 0x1EE7,
+ 0x01AF0301: 0x1EE8,
+ 0x01B00301: 0x1EE9,
+ 0x01AF0300: 0x1EEA,
+ 0x01B00300: 0x1EEB,
+ 0x01AF0309: 0x1EEC,
+ 0x01B00309: 0x1EED,
+ 0x01AF0303: 0x1EEE,
+ 0x01B00303: 0x1EEF,
+ 0x01AF0323: 0x1EF0,
+ 0x01B00323: 0x1EF1,
+ 0x00590300: 0x1EF2,
+ 0x00790300: 0x1EF3,
+ 0x00590323: 0x1EF4,
+ 0x00790323: 0x1EF5,
+ 0x00590309: 0x1EF6,
+ 0x00790309: 0x1EF7,
+ 0x00590303: 0x1EF8,
+ 0x00790303: 0x1EF9,
+ 0x03B10313: 0x1F00,
+ 0x03B10314: 0x1F01,
+ 0x1F000300: 0x1F02,
+ 0x1F010300: 0x1F03,
+ 0x1F000301: 0x1F04,
+ 0x1F010301: 0x1F05,
+ 0x1F000342: 0x1F06,
+ 0x1F010342: 0x1F07,
+ 0x03910313: 0x1F08,
+ 0x03910314: 0x1F09,
+ 0x1F080300: 0x1F0A,
+ 0x1F090300: 0x1F0B,
+ 0x1F080301: 0x1F0C,
+ 0x1F090301: 0x1F0D,
+ 0x1F080342: 0x1F0E,
+ 0x1F090342: 0x1F0F,
+ 0x03B50313: 0x1F10,
+ 0x03B50314: 0x1F11,
+ 0x1F100300: 0x1F12,
+ 0x1F110300: 0x1F13,
+ 0x1F100301: 0x1F14,
+ 0x1F110301: 0x1F15,
+ 0x03950313: 0x1F18,
+ 0x03950314: 0x1F19,
+ 0x1F180300: 0x1F1A,
+ 0x1F190300: 0x1F1B,
+ 0x1F180301: 0x1F1C,
+ 0x1F190301: 0x1F1D,
+ 0x03B70313: 0x1F20,
+ 0x03B70314: 0x1F21,
+ 0x1F200300: 0x1F22,
+ 0x1F210300: 0x1F23,
+ 0x1F200301: 0x1F24,
+ 0x1F210301: 0x1F25,
+ 0x1F200342: 0x1F26,
+ 0x1F210342: 0x1F27,
+ 0x03970313: 0x1F28,
+ 0x03970314: 0x1F29,
+ 0x1F280300: 0x1F2A,
+ 0x1F290300: 0x1F2B,
+ 0x1F280301: 0x1F2C,
+ 0x1F290301: 0x1F2D,
+ 0x1F280342: 0x1F2E,
+ 0x1F290342: 0x1F2F,
+ 0x03B90313: 0x1F30,
+ 0x03B90314: 0x1F31,
+ 0x1F300300: 0x1F32,
+ 0x1F310300: 0x1F33,
+ 0x1F300301: 0x1F34,
+ 0x1F310301: 0x1F35,
+ 0x1F300342: 0x1F36,
+ 0x1F310342: 0x1F37,
+ 0x03990313: 0x1F38,
+ 0x03990314: 0x1F39,
+ 0x1F380300: 0x1F3A,
+ 0x1F390300: 0x1F3B,
+ 0x1F380301: 0x1F3C,
+ 0x1F390301: 0x1F3D,
+ 0x1F380342: 0x1F3E,
+ 0x1F390342: 0x1F3F,
+ 0x03BF0313: 0x1F40,
+ 0x03BF0314: 0x1F41,
+ 0x1F400300: 0x1F42,
+ 0x1F410300: 0x1F43,
+ 0x1F400301: 0x1F44,
+ 0x1F410301: 0x1F45,
+ 0x039F0313: 0x1F48,
+ 0x039F0314: 0x1F49,
+ 0x1F480300: 0x1F4A,
+ 0x1F490300: 0x1F4B,
+ 0x1F480301: 0x1F4C,
+ 0x1F490301: 0x1F4D,
+ 0x03C50313: 0x1F50,
+ 0x03C50314: 0x1F51,
+ 0x1F500300: 0x1F52,
+ 0x1F510300: 0x1F53,
+ 0x1F500301: 0x1F54,
+ 0x1F510301: 0x1F55,
+ 0x1F500342: 0x1F56,
+ 0x1F510342: 0x1F57,
+ 0x03A50314: 0x1F59,
+ 0x1F590300: 0x1F5B,
+ 0x1F590301: 0x1F5D,
+ 0x1F590342: 0x1F5F,
+ 0x03C90313: 0x1F60,
+ 0x03C90314: 0x1F61,
+ 0x1F600300: 0x1F62,
+ 0x1F610300: 0x1F63,
+ 0x1F600301: 0x1F64,
+ 0x1F610301: 0x1F65,
+ 0x1F600342: 0x1F66,
+ 0x1F610342: 0x1F67,
+ 0x03A90313: 0x1F68,
+ 0x03A90314: 0x1F69,
+ 0x1F680300: 0x1F6A,
+ 0x1F690300: 0x1F6B,
+ 0x1F680301: 0x1F6C,
+ 0x1F690301: 0x1F6D,
+ 0x1F680342: 0x1F6E,
+ 0x1F690342: 0x1F6F,
+ 0x03B10300: 0x1F70,
+ 0x03B50300: 0x1F72,
+ 0x03B70300: 0x1F74,
+ 0x03B90300: 0x1F76,
+ 0x03BF0300: 0x1F78,
+ 0x03C50300: 0x1F7A,
+ 0x03C90300: 0x1F7C,
+ 0x1F000345: 0x1F80,
+ 0x1F010345: 0x1F81,
+ 0x1F020345: 0x1F82,
+ 0x1F030345: 0x1F83,
+ 0x1F040345: 0x1F84,
+ 0x1F050345: 0x1F85,
+ 0x1F060345: 0x1F86,
+ 0x1F070345: 0x1F87,
+ 0x1F080345: 0x1F88,
+ 0x1F090345: 0x1F89,
+ 0x1F0A0345: 0x1F8A,
+ 0x1F0B0345: 0x1F8B,
+ 0x1F0C0345: 0x1F8C,
+ 0x1F0D0345: 0x1F8D,
+ 0x1F0E0345: 0x1F8E,
+ 0x1F0F0345: 0x1F8F,
+ 0x1F200345: 0x1F90,
+ 0x1F210345: 0x1F91,
+ 0x1F220345: 0x1F92,
+ 0x1F230345: 0x1F93,
+ 0x1F240345: 0x1F94,
+ 0x1F250345: 0x1F95,
+ 0x1F260345: 0x1F96,
+ 0x1F270345: 0x1F97,
+ 0x1F280345: 0x1F98,
+ 0x1F290345: 0x1F99,
+ 0x1F2A0345: 0x1F9A,
+ 0x1F2B0345: 0x1F9B,
+ 0x1F2C0345: 0x1F9C,
+ 0x1F2D0345: 0x1F9D,
+ 0x1F2E0345: 0x1F9E,
+ 0x1F2F0345: 0x1F9F,
+ 0x1F600345: 0x1FA0,
+ 0x1F610345: 0x1FA1,
+ 0x1F620345: 0x1FA2,
+ 0x1F630345: 0x1FA3,
+ 0x1F640345: 0x1FA4,
+ 0x1F650345: 0x1FA5,
+ 0x1F660345: 0x1FA6,
+ 0x1F670345: 0x1FA7,
+ 0x1F680345: 0x1FA8,
+ 0x1F690345: 0x1FA9,
+ 0x1F6A0345: 0x1FAA,
+ 0x1F6B0345: 0x1FAB,
+ 0x1F6C0345: 0x1FAC,
+ 0x1F6D0345: 0x1FAD,
+ 0x1F6E0345: 0x1FAE,
+ 0x1F6F0345: 0x1FAF,
+ 0x03B10306: 0x1FB0,
+ 0x03B10304: 0x1FB1,
+ 0x1F700345: 0x1FB2,
+ 0x03B10345: 0x1FB3,
+ 0x03AC0345: 0x1FB4,
+ 0x03B10342: 0x1FB6,
+ 0x1FB60345: 0x1FB7,
+ 0x03910306: 0x1FB8,
+ 0x03910304: 0x1FB9,
+ 0x03910300: 0x1FBA,
+ 0x03910345: 0x1FBC,
+ 0x00A80342: 0x1FC1,
+ 0x1F740345: 0x1FC2,
+ 0x03B70345: 0x1FC3,
+ 0x03AE0345: 0x1FC4,
+ 0x03B70342: 0x1FC6,
+ 0x1FC60345: 0x1FC7,
+ 0x03950300: 0x1FC8,
+ 0x03970300: 0x1FCA,
+ 0x03970345: 0x1FCC,
+ 0x1FBF0300: 0x1FCD,
+ 0x1FBF0301: 0x1FCE,
+ 0x1FBF0342: 0x1FCF,
+ 0x03B90306: 0x1FD0,
+ 0x03B90304: 0x1FD1,
+ 0x03CA0300: 0x1FD2,
+ 0x03B90342: 0x1FD6,
+ 0x03CA0342: 0x1FD7,
+ 0x03990306: 0x1FD8,
+ 0x03990304: 0x1FD9,
+ 0x03990300: 0x1FDA,
+ 0x1FFE0300: 0x1FDD,
+ 0x1FFE0301: 0x1FDE,
+ 0x1FFE0342: 0x1FDF,
+ 0x03C50306: 0x1FE0,
+ 0x03C50304: 0x1FE1,
+ 0x03CB0300: 0x1FE2,
+ 0x03C10313: 0x1FE4,
+ 0x03C10314: 0x1FE5,
+ 0x03C50342: 0x1FE6,
+ 0x03CB0342: 0x1FE7,
+ 0x03A50306: 0x1FE8,
+ 0x03A50304: 0x1FE9,
+ 0x03A50300: 0x1FEA,
+ 0x03A10314: 0x1FEC,
+ 0x00A80300: 0x1FED,
+ 0x1F7C0345: 0x1FF2,
+ 0x03C90345: 0x1FF3,
+ 0x03CE0345: 0x1FF4,
+ 0x03C90342: 0x1FF6,
+ 0x1FF60345: 0x1FF7,
+ 0x039F0300: 0x1FF8,
+ 0x03A90300: 0x1FFA,
+ 0x03A90345: 0x1FFC,
+ 0x21900338: 0x219A,
+ 0x21920338: 0x219B,
+ 0x21940338: 0x21AE,
+ 0x21D00338: 0x21CD,
+ 0x21D40338: 0x21CE,
+ 0x21D20338: 0x21CF,
+ 0x22030338: 0x2204,
+ 0x22080338: 0x2209,
+ 0x220B0338: 0x220C,
+ 0x22230338: 0x2224,
+ 0x22250338: 0x2226,
+ 0x223C0338: 0x2241,
+ 0x22430338: 0x2244,
+ 0x22450338: 0x2247,
+ 0x22480338: 0x2249,
+ 0x003D0338: 0x2260,
+ 0x22610338: 0x2262,
+ 0x224D0338: 0x226D,
+ 0x003C0338: 0x226E,
+ 0x003E0338: 0x226F,
+ 0x22640338: 0x2270,
+ 0x22650338: 0x2271,
+ 0x22720338: 0x2274,
+ 0x22730338: 0x2275,
+ 0x22760338: 0x2278,
+ 0x22770338: 0x2279,
+ 0x227A0338: 0x2280,
+ 0x227B0338: 0x2281,
+ 0x22820338: 0x2284,
+ 0x22830338: 0x2285,
+ 0x22860338: 0x2288,
+ 0x22870338: 0x2289,
+ 0x22A20338: 0x22AC,
+ 0x22A80338: 0x22AD,
+ 0x22A90338: 0x22AE,
+ 0x22AB0338: 0x22AF,
+ 0x227C0338: 0x22E0,
+ 0x227D0338: 0x22E1,
+ 0x22910338: 0x22E2,
+ 0x22920338: 0x22E3,
+ 0x22B20338: 0x22EA,
+ 0x22B30338: 0x22EB,
+ 0x22B40338: 0x22EC,
+ 0x22B50338: 0x22ED,
+ 0x304B3099: 0x304C,
+ 0x304D3099: 0x304E,
+ 0x304F3099: 0x3050,
+ 0x30513099: 0x3052,
+ 0x30533099: 0x3054,
+ 0x30553099: 0x3056,
+ 0x30573099: 0x3058,
+ 0x30593099: 0x305A,
+ 0x305B3099: 0x305C,
+ 0x305D3099: 0x305E,
+ 0x305F3099: 0x3060,
+ 0x30613099: 0x3062,
+ 0x30643099: 0x3065,
+ 0x30663099: 0x3067,
+ 0x30683099: 0x3069,
+ 0x306F3099: 0x3070,
+ 0x306F309A: 0x3071,
+ 0x30723099: 0x3073,
+ 0x3072309A: 0x3074,
+ 0x30753099: 0x3076,
+ 0x3075309A: 0x3077,
+ 0x30783099: 0x3079,
+ 0x3078309A: 0x307A,
+ 0x307B3099: 0x307C,
+ 0x307B309A: 0x307D,
+ 0x30463099: 0x3094,
+ 0x309D3099: 0x309E,
+ 0x30AB3099: 0x30AC,
+ 0x30AD3099: 0x30AE,
+ 0x30AF3099: 0x30B0,
+ 0x30B13099: 0x30B2,
+ 0x30B33099: 0x30B4,
+ 0x30B53099: 0x30B6,
+ 0x30B73099: 0x30B8,
+ 0x30B93099: 0x30BA,
+ 0x30BB3099: 0x30BC,
+ 0x30BD3099: 0x30BE,
+ 0x30BF3099: 0x30C0,
+ 0x30C13099: 0x30C2,
+ 0x30C43099: 0x30C5,
+ 0x30C63099: 0x30C7,
+ 0x30C83099: 0x30C9,
+ 0x30CF3099: 0x30D0,
+ 0x30CF309A: 0x30D1,
+ 0x30D23099: 0x30D3,
+ 0x30D2309A: 0x30D4,
+ 0x30D53099: 0x30D6,
+ 0x30D5309A: 0x30D7,
+ 0x30D83099: 0x30D9,
+ 0x30D8309A: 0x30DA,
+ 0x30DB3099: 0x30DC,
+ 0x30DB309A: 0x30DD,
+ 0x30A63099: 0x30F4,
+ 0x30EF3099: 0x30F7,
+ 0x30F03099: 0x30F8,
+ 0x30F13099: 0x30F9,
+ 0x30F23099: 0x30FA,
+ 0x30FD3099: 0x30FE,
+ 0x109910BA: 0x1109A,
+ 0x109B10BA: 0x1109C,
+ 0x10A510BA: 0x110AB,
+ 0x11311127: 0x1112E,
+ 0x11321127: 0x1112F,
+ 0x1347133E: 0x1134B,
+ 0x13471357: 0x1134C,
+ 0x14B914BA: 0x114BB,
+ 0x14B914B0: 0x114BC,
+ 0x14B914BD: 0x114BE,
+ 0x15B815AF: 0x115BA,
+ 0x15B915AF: 0x115BB,
+}
+
+// Total size of tables: 53KB (53976 bytes)
diff --git a/vendor/golang.org/x/text/unicode/norm/transform.go b/vendor/golang.org/x/text/unicode/norm/transform.go
new file mode 100644
index 0000000..8589067
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/norm/transform.go
@@ -0,0 +1,88 @@
+// 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 norm
+
+import (
+ "unicode/utf8"
+
+ "golang.org/x/text/transform"
+)
+
+// Reset implements the Reset method of the transform.Transformer interface.
+func (Form) Reset() {}
+
+// Transform implements the Transform method of the transform.Transformer
+// interface. It may need to write segments of up to MaxSegmentSize at once.
+// Users should either catch ErrShortDst and allow dst to grow or have dst be at
+// least of size MaxTransformChunkSize to be guaranteed of progress.
+func (f Form) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
+ n := 0
+ // Cap the maximum number of src bytes to check.
+ b := src
+ eof := atEOF
+ if ns := len(dst); ns < len(b) {
+ err = transform.ErrShortDst
+ eof = false
+ b = b[:ns]
+ }
+ i, ok := formTable[f].quickSpan(inputBytes(b), n, len(b), eof)
+ n += copy(dst[n:], b[n:i])
+ if !ok {
+ nDst, nSrc, err = f.transform(dst[n:], src[n:], atEOF)
+ return nDst + n, nSrc + n, err
+ }
+ if n < len(src) && !atEOF {
+ err = transform.ErrShortSrc
+ }
+ return n, n, err
+}
+
+func flushTransform(rb *reorderBuffer) bool {
+ // Write out (must fully fit in dst, or else it is a ErrShortDst).
+ if len(rb.out) < rb.nrune*utf8.UTFMax {
+ return false
+ }
+ rb.out = rb.out[rb.flushCopy(rb.out):]
+ return true
+}
+
+var errs = []error{nil, transform.ErrShortDst, transform.ErrShortSrc}
+
+// transform implements the transform.Transformer interface. It is only called
+// when quickSpan does not pass for a given string.
+func (f Form) transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
+ // TODO: get rid of reorderBuffer. See CL 23460044.
+ rb := reorderBuffer{}
+ rb.init(f, src)
+ for {
+ // Load segment into reorder buffer.
+ rb.setFlusher(dst[nDst:], flushTransform)
+ end := decomposeSegment(&rb, nSrc, atEOF)
+ if end < 0 {
+ return nDst, nSrc, errs[-end]
+ }
+ nDst = len(dst) - len(rb.out)
+ nSrc = end
+
+ // Next quickSpan.
+ end = rb.nsrc
+ eof := atEOF
+ if n := nSrc + len(dst) - nDst; n < end {
+ err = transform.ErrShortDst
+ end = n
+ eof = false
+ }
+ end, ok := rb.f.quickSpan(rb.src, nSrc, end, eof)
+ n := copy(dst[nDst:], rb.src.bytes[nSrc:end])
+ nSrc += n
+ nDst += n
+ if ok {
+ if n < rb.nsrc && !atEOF {
+ err = transform.ErrShortSrc
+ }
+ return nDst, nSrc, err
+ }
+ }
+}
diff --git a/vendor/golang.org/x/text/unicode/norm/trie.go b/vendor/golang.org/x/text/unicode/norm/trie.go
new file mode 100644
index 0000000..423386b
--- /dev/null
+++ b/vendor/golang.org/x/text/unicode/norm/trie.go
@@ -0,0 +1,54 @@
+// 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 norm
+
+type valueRange struct {
+ value uint16 // header: value:stride
+ lo, hi byte // header: lo:n
+}
+
+type sparseBlocks struct {
+ values []valueRange
+ offset []uint16
+}
+
+var nfcSparse = sparseBlocks{
+ values: nfcSparseValues[:],
+ offset: nfcSparseOffset[:],
+}
+
+var nfkcSparse = sparseBlocks{
+ values: nfkcSparseValues[:],
+ offset: nfkcSparseOffset[:],
+}
+
+var (
+ nfcData = newNfcTrie(0)
+ nfkcData = newNfkcTrie(0)
+)
+
+// lookupValue determines the type of block n and looks up the value for b.
+// For n < t.cutoff, the block is a simple lookup table. Otherwise, the block
+// is a list of ranges with an accompanying value. Given a matching range r,
+// the value for b is by r.value + (b - r.lo) * stride.
+func (t *sparseBlocks) lookup(n uint32, b byte) uint16 {
+ offset := t.offset[n]
+ header := t.values[offset]
+ lo := offset + 1
+ hi := lo + uint16(header.lo)
+ for lo < hi {
+ m := lo + (hi-lo)/2
+ r := t.values[m]
+ if r.lo <= b && b <= r.hi {
+ return r.value + uint16(b-r.lo)*header.value
+ }
+ if b < r.lo {
+ hi = m
+ } else {
+ lo = m + 1
+ }
+ }
+ return 0
+}
diff --git a/vendor/golang.org/x/time/LICENSE b/vendor/golang.org/x/time/LICENSE
new file mode 100644
index 0000000..6a66aea
--- /dev/null
+++ b/vendor/golang.org/x/time/LICENSE
@@ -0,0 +1,27 @@
+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/time/PATENTS b/vendor/golang.org/x/time/PATENTS
new file mode 100644
index 0000000..7330990
--- /dev/null
+++ b/vendor/golang.org/x/time/PATENTS
@@ -0,0 +1,22 @@
+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/time/README b/vendor/golang.org/x/time/README
new file mode 100644
index 0000000..144e347
--- /dev/null
+++ b/vendor/golang.org/x/time/README
@@ -0,0 +1 @@
+This repository provides supplementary Go time packages.
diff --git a/vendor/golang.org/x/time/rate/rate.go b/vendor/golang.org/x/time/rate/rate.go
new file mode 100644
index 0000000..2131b92
--- /dev/null
+++ b/vendor/golang.org/x/time/rate/rate.go
@@ -0,0 +1,368 @@
+// Copyright 2015 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 rate provides a rate limiter.
+package rate
+
+import (
+ "fmt"
+ "math"
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+)
+
+// Limit defines the maximum frequency of some events.
+// Limit is represented as number of events per second.
+// A zero Limit allows no events.
+type Limit float64
+
+// Inf is the infinite rate limit; it allows all events (even if burst is zero).
+const Inf = Limit(math.MaxFloat64)
+
+// Every converts a minimum time interval between events to a Limit.
+func Every(interval time.Duration) Limit {
+ if interval <= 0 {
+ return Inf
+ }
+ return 1 / Limit(interval.Seconds())
+}
+
+// A Limiter controls how frequently events are allowed to happen.
+// It implements a "token bucket" of size b, initially full and refilled
+// at rate r tokens per second.
+// Informally, in any large enough time interval, the Limiter limits the
+// rate to r tokens per second, with a maximum burst size of b events.
+// As a special case, if r == Inf (the infinite rate), b is ignored.
+// See https://en.wikipedia.org/wiki/Token_bucket for more about token buckets.
+//
+// The zero value is a valid Limiter, but it will reject all events.
+// Use NewLimiter to create non-zero Limiters.
+//
+// Limiter has three main methods, Allow, Reserve, and Wait.
+// Most callers should use Wait.
+//
+// Each of the three methods consumes a single token.
+// They differ in their behavior when no token is available.
+// If no token is available, Allow returns false.
+// If no token is available, Reserve returns a reservation for a future token
+// and the amount of time the caller must wait before using it.
+// If no token is available, Wait blocks until one can be obtained
+// or its associated context.Context is canceled.
+//
+// The methods AllowN, ReserveN, and WaitN consume n tokens.
+type Limiter struct {
+ limit Limit
+ burst int
+
+ mu sync.Mutex
+ tokens float64
+ // last is the last time the limiter's tokens field was updated
+ last time.Time
+ // lastEvent is the latest time of a rate-limited event (past or future)
+ lastEvent time.Time
+}
+
+// Limit returns the maximum overall event rate.
+func (lim *Limiter) Limit() Limit {
+ lim.mu.Lock()
+ defer lim.mu.Unlock()
+ return lim.limit
+}
+
+// Burst returns the maximum burst size. Burst is the maximum number of tokens
+// that can be consumed in a single call to Allow, Reserve, or Wait, so higher
+// Burst values allow more events to happen at once.
+// A zero Burst allows no events, unless limit == Inf.
+func (lim *Limiter) Burst() int {
+ return lim.burst
+}
+
+// NewLimiter returns a new Limiter that allows events up to rate r and permits
+// bursts of at most b tokens.
+func NewLimiter(r Limit, b int) *Limiter {
+ return &Limiter{
+ limit: r,
+ burst: b,
+ }
+}
+
+// Allow is shorthand for AllowN(time.Now(), 1).
+func (lim *Limiter) Allow() bool {
+ return lim.AllowN(time.Now(), 1)
+}
+
+// AllowN reports whether n events may happen at time now.
+// Use this method if you intend to drop / skip events that exceed the rate limit.
+// Otherwise use Reserve or Wait.
+func (lim *Limiter) AllowN(now time.Time, n int) bool {
+ return lim.reserveN(now, n, 0).ok
+}
+
+// A Reservation holds information about events that are permitted by a Limiter to happen after a delay.
+// A Reservation may be canceled, which may enable the Limiter to permit additional events.
+type Reservation struct {
+ ok bool
+ lim *Limiter
+ tokens int
+ timeToAct time.Time
+ // This is the Limit at reservation time, it can change later.
+ limit Limit
+}
+
+// OK returns whether the limiter can provide the requested number of tokens
+// within the maximum wait time. If OK is false, Delay returns InfDuration, and
+// Cancel does nothing.
+func (r *Reservation) OK() bool {
+ return r.ok
+}
+
+// Delay is shorthand for DelayFrom(time.Now()).
+func (r *Reservation) Delay() time.Duration {
+ return r.DelayFrom(time.Now())
+}
+
+// InfDuration is the duration returned by Delay when a Reservation is not OK.
+const InfDuration = time.Duration(1<<63 - 1)
+
+// DelayFrom returns the duration for which the reservation holder must wait
+// before taking the reserved action. Zero duration means act immediately.
+// InfDuration means the limiter cannot grant the tokens requested in this
+// Reservation within the maximum wait time.
+func (r *Reservation) DelayFrom(now time.Time) time.Duration {
+ if !r.ok {
+ return InfDuration
+ }
+ delay := r.timeToAct.Sub(now)
+ if delay < 0 {
+ return 0
+ }
+ return delay
+}
+
+// Cancel is shorthand for CancelAt(time.Now()).
+func (r *Reservation) Cancel() {
+ r.CancelAt(time.Now())
+ return
+}
+
+// CancelAt indicates that the reservation holder will not perform the reserved action
+// and reverses the effects of this Reservation on the rate limit as much as possible,
+// considering that other reservations may have already been made.
+func (r *Reservation) CancelAt(now time.Time) {
+ if !r.ok {
+ return
+ }
+
+ r.lim.mu.Lock()
+ defer r.lim.mu.Unlock()
+
+ if r.lim.limit == Inf || r.tokens == 0 || r.timeToAct.Before(now) {
+ return
+ }
+
+ // calculate tokens to restore
+ // The duration between lim.lastEvent and r.timeToAct tells us how many tokens were reserved
+ // after r was obtained. These tokens should not be restored.
+ restoreTokens := float64(r.tokens) - r.limit.tokensFromDuration(r.lim.lastEvent.Sub(r.timeToAct))
+ if restoreTokens <= 0 {
+ return
+ }
+ // advance time to now
+ now, _, tokens := r.lim.advance(now)
+ // calculate new number of tokens
+ tokens += restoreTokens
+ if burst := float64(r.lim.burst); tokens > burst {
+ tokens = burst
+ }
+ // update state
+ r.lim.last = now
+ r.lim.tokens = tokens
+ if r.timeToAct == r.lim.lastEvent {
+ prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens)))
+ if !prevEvent.Before(now) {
+ r.lim.lastEvent = prevEvent
+ }
+ }
+
+ return
+}
+
+// Reserve is shorthand for ReserveN(time.Now(), 1).
+func (lim *Limiter) Reserve() *Reservation {
+ return lim.ReserveN(time.Now(), 1)
+}
+
+// ReserveN returns a Reservation that indicates how long the caller must wait before n events happen.
+// The Limiter takes this Reservation into account when allowing future events.
+// ReserveN returns false if n exceeds the Limiter's burst size.
+// Usage example:
+// r, ok := lim.ReserveN(time.Now(), 1)
+// if !ok {
+// // Not allowed to act! Did you remember to set lim.burst to be > 0 ?
+// }
+// time.Sleep(r.Delay())
+// Act()
+// Use this method if you wish to wait and slow down in accordance with the rate limit without dropping events.
+// If you need to respect a deadline or cancel the delay, use Wait instead.
+// To drop or skip events exceeding rate limit, use Allow instead.
+func (lim *Limiter) ReserveN(now time.Time, n int) *Reservation {
+ r := lim.reserveN(now, n, InfDuration)
+ return &r
+}
+
+// Wait is shorthand for WaitN(ctx, 1).
+func (lim *Limiter) Wait(ctx context.Context) (err error) {
+ return lim.WaitN(ctx, 1)
+}
+
+// WaitN blocks until lim permits n events to happen.
+// It returns an error if n exceeds the Limiter's burst size, the Context is
+// canceled, or the expected wait time exceeds the Context's Deadline.
+func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) {
+ if n > lim.burst {
+ return fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, lim.burst)
+ }
+ // Check if ctx is already cancelled
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+ // Determine wait limit
+ now := time.Now()
+ waitLimit := InfDuration
+ if deadline, ok := ctx.Deadline(); ok {
+ waitLimit = deadline.Sub(now)
+ }
+ // Reserve
+ r := lim.reserveN(now, n, waitLimit)
+ if !r.ok {
+ return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n)
+ }
+ // Wait
+ t := time.NewTimer(r.DelayFrom(now))
+ defer t.Stop()
+ select {
+ case <-t.C:
+ // We can proceed.
+ return nil
+ case <-ctx.Done():
+ // Context was canceled before we could proceed. Cancel the
+ // reservation, which may permit other events to proceed sooner.
+ r.Cancel()
+ return ctx.Err()
+ }
+}
+
+// SetLimit is shorthand for SetLimitAt(time.Now(), newLimit).
+func (lim *Limiter) SetLimit(newLimit Limit) {
+ lim.SetLimitAt(time.Now(), newLimit)
+}
+
+// SetLimitAt sets a new Limit for the limiter. The new Limit, and Burst, may be violated
+// or underutilized by those which reserved (using Reserve or Wait) but did not yet act
+// before SetLimitAt was called.
+func (lim *Limiter) SetLimitAt(now time.Time, newLimit Limit) {
+ lim.mu.Lock()
+ defer lim.mu.Unlock()
+
+ now, _, tokens := lim.advance(now)
+
+ lim.last = now
+ lim.tokens = tokens
+ lim.limit = newLimit
+}
+
+// reserveN is a helper method for AllowN, ReserveN, and WaitN.
+// maxFutureReserve specifies the maximum reservation wait duration allowed.
+// reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN.
+func (lim *Limiter) reserveN(now time.Time, n int, maxFutureReserve time.Duration) Reservation {
+ lim.mu.Lock()
+ defer lim.mu.Unlock()
+
+ if lim.limit == Inf {
+ return Reservation{
+ ok: true,
+ lim: lim,
+ tokens: n,
+ timeToAct: now,
+ }
+ }
+
+ now, last, tokens := lim.advance(now)
+
+ // Calculate the remaining number of tokens resulting from the request.
+ tokens -= float64(n)
+
+ // Calculate the wait duration
+ var waitDuration time.Duration
+ if tokens < 0 {
+ waitDuration = lim.limit.durationFromTokens(-tokens)
+ }
+
+ // Decide result
+ ok := n <= lim.burst && waitDuration <= maxFutureReserve
+
+ // Prepare reservation
+ r := Reservation{
+ ok: ok,
+ lim: lim,
+ limit: lim.limit,
+ }
+ if ok {
+ r.tokens = n
+ r.timeToAct = now.Add(waitDuration)
+ }
+
+ // Update state
+ if ok {
+ lim.last = now
+ lim.tokens = tokens
+ lim.lastEvent = r.timeToAct
+ } else {
+ lim.last = last
+ }
+
+ return r
+}
+
+// advance calculates and returns an updated state for lim resulting from the passage of time.
+// lim is not changed.
+func (lim *Limiter) advance(now time.Time) (newNow time.Time, newLast time.Time, newTokens float64) {
+ last := lim.last
+ if now.Before(last) {
+ last = now
+ }
+
+ // Avoid making delta overflow below when last is very old.
+ maxElapsed := lim.limit.durationFromTokens(float64(lim.burst) - lim.tokens)
+ elapsed := now.Sub(last)
+ if elapsed > maxElapsed {
+ elapsed = maxElapsed
+ }
+
+ // Calculate the new number of tokens, due to time that passed.
+ delta := lim.limit.tokensFromDuration(elapsed)
+ tokens := lim.tokens + delta
+ if burst := float64(lim.burst); tokens > burst {
+ tokens = burst
+ }
+
+ return now, last, tokens
+}
+
+// durationFromTokens is a unit conversion function from the number of tokens to the duration
+// of time it takes to accumulate them at a rate of limit tokens per second.
+func (limit Limit) durationFromTokens(tokens float64) time.Duration {
+ seconds := tokens / float64(limit)
+ return time.Nanosecond * time.Duration(1e9*seconds)
+}
+
+// tokensFromDuration is a unit conversion function from a time duration to the number of tokens
+// which could be accumulated during that duration at a rate of limit tokens per second.
+func (limit Limit) tokensFromDuration(d time.Duration) float64 {
+ return d.Seconds() * float64(limit)
+}
diff --git a/vendor/google.golang.org/api/LICENSE b/vendor/google.golang.org/api/LICENSE
new file mode 100644
index 0000000..263aa7a
--- /dev/null
+++ b/vendor/google.golang.org/api/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2011 Google Inc. 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/google.golang.org/api/README.md b/vendor/google.golang.org/api/README.md
new file mode 100644
index 0000000..b562c2f
--- /dev/null
+++ b/vendor/google.golang.org/api/README.md
@@ -0,0 +1,92 @@
+# Google APIs Client Library for Go
+
+## Status
+[![Build Status](https://travis-ci.org/google/google-api-go-client.png)](https://travis-ci.org/google/google-api-go-client)
+
+These are auto-generated Go libraries from the Google Discovery Service's JSON description files of the available "new style" Google APIs.
+
+Due to the auto-generated nature of this collection of libraries, complete APIs or specific versions can appear or go away without notice.
+As a result, you should always locally vendor any API(s) that your code relies upon.
+
+Announcement email:
+
+* http://groups.google.com/group/golang-nuts/browse_thread/thread/6c7281450be9a21e
+
+Getting started documentation:
+
+* https://github.com/google/google-api-go-client/blob/master/GettingStarted.md
+
+In summary:
+
+```
+$ go get google.golang.org/api/storage/v1
+$ go get google.golang.org/api/tasks/v1
+$ go get google.golang.org/api/moderator/v1
+... etc ...
+```
+
+For docs, see e.g.:
+
+* https://godoc.org/google.golang.org/api/storage/v1
+
+The package of a given import is the second-to-last component, before the version number.
+
+For examples, see:
+
+* https://github.com/google/google-api-go-client/tree/master/examples
+
+For support, use the golang-nuts@ mailing list:
+
+* https://groups.google.com/group/golang-nuts
+
+## Application Default Credentials Example
+
+Application Default Credentials provide a simplified way to obtain credentials
+for authenticating with Google APIs.
+
+The Application Default Credentials authenticate as the application itself,
+which make them great for working with Google Cloud APIs like Storage or
+Datastore. They are the recommended form of authentication when building
+applications that run on Google Compute Engine or Google App Engine.
+
+Default credentials are provided by the `golang.org/x/oauth2/google` package. To use them, add the following import:
+
+```
+import "golang.org/x/oauth2/google"
+```
+
+Some credentials types require you to specify scopes, and service entry points may not inject them. If you encounter this situation you may need to specify scopes as follows:
+
+```
+import (
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2/google"
+ "google.golang.org/api/compute/v1"
+)
+
+func main() {
+ // Use oauth2.NoContext if there isn't a good context to pass in.
+ ctx := context.Background()
+
+ client, err := google.DefaultClient(ctx, compute.ComputeScope)
+ if err != nil {
+ //...
+ }
+ computeService, err := compute.New(client)
+ if err != nil {
+ //...
+ }
+}
+```
+
+If you need a `oauth2.TokenSource`, use the `DefaultTokenSource` function:
+
+```
+ts, err := google.DefaultTokenSource(ctx, scope1, scope2, ...)
+if err != nil {
+ //...
+}
+client := oauth2.NewClient(ctx, ts)
+```
+
+See also: [golang.org/x/oauth2/google](https://godoc.org/golang.org/x/oauth2/google) package documentation.
diff --git a/vendor/google.golang.org/api/googleapi/transport/apikey.go b/vendor/google.golang.org/api/googleapi/transport/apikey.go
new file mode 100644
index 0000000..eca1ea2
--- /dev/null
+++ b/vendor/google.golang.org/api/googleapi/transport/apikey.go
@@ -0,0 +1,38 @@
+// Copyright 2012 Google Inc. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package transport contains HTTP transports used to make
+// authenticated API requests.
+package transport
+
+import (
+ "errors"
+ "net/http"
+)
+
+// APIKey is an HTTP Transport which wraps an underlying transport and
+// appends an API Key "key" parameter to the URL of outgoing requests.
+type APIKey struct {
+ // Key is the API Key to set on requests.
+ Key string
+
+ // Transport is the underlying HTTP transport.
+ // If nil, http.DefaultTransport is used.
+ Transport http.RoundTripper
+}
+
+func (t *APIKey) RoundTrip(req *http.Request) (*http.Response, error) {
+ rt := t.Transport
+ if rt == nil {
+ rt = http.DefaultTransport
+ if rt == nil {
+ return nil, errors.New("googleapi/transport: no Transport specified or available")
+ }
+ }
+ newReq := *req
+ args := newReq.URL.Query()
+ args.Set("key", t.Key)
+ newReq.URL.RawQuery = args.Encode()
+ return rt.RoundTrip(&newReq)
+}
diff --git a/vendor/google.golang.org/api/internal/pool.go b/vendor/google.golang.org/api/internal/pool.go
new file mode 100644
index 0000000..4150feb
--- /dev/null
+++ b/vendor/google.golang.org/api/internal/pool.go
@@ -0,0 +1,59 @@
+// Copyright 2016 Google Inc. All Rights Reserved.
+//
+// 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 internal
+
+import (
+ "errors"
+ "google.golang.org/grpc/naming"
+)
+
+// PoolResolver provides a fixed list of addresses to load balance between
+// and does not provide further updates.
+type PoolResolver struct {
+ poolSize int
+ dialOpt *DialSettings
+ ch chan []*naming.Update
+}
+
+// NewPoolResolver returns a PoolResolver
+// This is an EXPERIMENTAL API and may be changed or removed in the future.
+func NewPoolResolver(size int, o *DialSettings) *PoolResolver {
+ return &PoolResolver{poolSize: size, dialOpt: o}
+}
+
+// Resolve returns a Watcher for the endpoint defined by the DialSettings
+// provided to NewPoolResolver.
+func (r *PoolResolver) Resolve(target string) (naming.Watcher, error) {
+ if r.dialOpt.Endpoint == "" {
+ return nil, errors.New("No endpoint configured")
+ }
+ addrs := make([]*naming.Update, 0, r.poolSize)
+ for i := 0; i < r.poolSize; i++ {
+ addrs = append(addrs, &naming.Update{Op: naming.Add, Addr: r.dialOpt.Endpoint, Metadata: i})
+ }
+ r.ch = make(chan []*naming.Update, 1)
+ r.ch <- addrs
+ return r, nil
+}
+
+// Next returns a static list of updates on the first call,
+// and blocks indefinitely until Close is called on subsequent calls.
+func (r *PoolResolver) Next() ([]*naming.Update, error) {
+ return <-r.ch, nil
+}
+
+func (r *PoolResolver) Close() {
+ close(r.ch)
+}
diff --git a/vendor/google.golang.org/api/internal/settings.go b/vendor/google.golang.org/api/internal/settings.go
new file mode 100644
index 0000000..6e60e48
--- /dev/null
+++ b/vendor/google.golang.org/api/internal/settings.go
@@ -0,0 +1,23 @@
+// Package internal supports the options and transport packages.
+package internal
+
+import (
+ "net/http"
+
+ "golang.org/x/oauth2"
+ "google.golang.org/grpc"
+)
+
+// DialSettings holds information needed to establish a connection with a
+// Google API service.
+type DialSettings struct {
+ Endpoint string
+ Scopes []string
+ ServiceAccountJSONFilename string // if set, TokenSource is ignored.
+ TokenSource oauth2.TokenSource
+ UserAgent string
+ APIKey string
+ HTTPClient *http.Client
+ GRPCDialOpts []grpc.DialOption
+ GRPCConn *grpc.ClientConn
+}
diff --git a/vendor/google.golang.org/api/iterator/iterator.go b/vendor/google.golang.org/api/iterator/iterator.go
new file mode 100644
index 0000000..0640c82
--- /dev/null
+++ b/vendor/google.golang.org/api/iterator/iterator.go
@@ -0,0 +1,231 @@
+// Copyright 2016 Google Inc. All Rights Reserved.
+//
+// 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 iterator provides support for standard Google API iterators.
+// See https://github.com/GoogleCloudPlatform/gcloud-golang/wiki/Iterator-Guidelines.
+package iterator
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+)
+
+// Done is returned by an iterator's Next method when the iteration is
+// complete; when there are no more items to return.
+var Done = errors.New("no more items in iterator")
+
+// We don't support mixed calls to Next and NextPage because they play
+// with the paging state in incompatible ways.
+var errMixed = errors.New("iterator: Next and NextPage called on same iterator")
+
+// PageInfo contains information about an iterator's paging state.
+type PageInfo struct {
+ // Token is the token used to retrieve the next page of items from the
+ // API. You may set Token immediately after creating an iterator to
+ // begin iteration at a particular point. If Token is the empty string,
+ // the iterator will begin with the first eligible item.
+ //
+ // The result of setting Token after the first call to Next is undefined.
+ //
+ // After the underlying API method is called to retrieve a page of items,
+ // Token is set to the next-page token in the response.
+ Token string
+
+ // MaxSize is the maximum number of items returned by a call to the API.
+ // Set MaxSize as a hint to optimize the buffering behavior of the iterator.
+ // If zero, the page size is determined by the underlying service.
+ //
+ // Use Pager to retrieve a page of a specific, exact size.
+ MaxSize int
+
+ // The error state of the iterator. Manipulated by PageInfo.next and Pager.
+ // This is a latch: it starts as nil, and once set should never change.
+ err error
+
+ // If true, no more calls to fetch should be made. Set to true when fetch
+ // returns an empty page token. The iterator is Done when this is true AND
+ // the buffer is empty.
+ atEnd bool
+
+ // Function that fetches a page from the underlying service. It should pass
+ // the pageSize and pageToken arguments to the service, fill the buffer
+ // with the results from the call, and return the next-page token returned
+ // by the service. The function must not remove any existing items from the
+ // buffer. If the underlying RPC takes an int32 page size, pageSize should
+ // be silently truncated.
+ fetch func(pageSize int, pageToken string) (nextPageToken string, err error)
+
+ // Function that clears the iterator's buffer, returning any currently buffered items.
+ bufLen func() int
+
+ // Function that returns the buffer, after setting the buffer variable to nil.
+ takeBuf func() interface{}
+
+ // Set to true on first call to PageInfo.next or Pager.NextPage. Used to check
+ // for calls to both Next and NextPage with the same iterator.
+ nextCalled, nextPageCalled bool
+}
+
+// NewPageInfo exposes internals for iterator implementations.
+// It is not a stable interface.
+var NewPageInfo = newPageInfo
+
+// If an iterator can support paging, its iterator-creating method should call
+// this (via the NewPageInfo variable above).
+//
+// The fetch, bufLen and takeBuf arguments provide access to the
+// iterator's internal slice of buffered items. They behave as described in
+// PageInfo, above.
+//
+// The return value is the PageInfo.next method bound to the returned PageInfo value.
+// (Returning it avoids exporting PageInfo.next.)
+func newPageInfo(fetch func(int, string) (string, error), bufLen func() int, takeBuf func() interface{}) (*PageInfo, func() error) {
+ pi := &PageInfo{
+ fetch: fetch,
+ bufLen: bufLen,
+ takeBuf: takeBuf,
+ }
+ return pi, pi.next
+}
+
+// Remaining returns the number of items available before the iterator makes another API call.
+func (pi *PageInfo) Remaining() int { return pi.bufLen() }
+
+// next provides support for an iterator's Next function. An iterator's Next
+// should return the error returned by next if non-nil; else it can assume
+// there is at least one item in its buffer, and it should return that item and
+// remove it from the buffer.
+func (pi *PageInfo) next() error {
+ pi.nextCalled = true
+ if pi.err != nil { // Once we get an error, always return it.
+ // TODO(jba): fix so users can retry on transient errors? Probably not worth it.
+ return pi.err
+ }
+ if pi.nextPageCalled {
+ pi.err = errMixed
+ return pi.err
+ }
+ // Loop until we get some items or reach the end.
+ for pi.bufLen() == 0 && !pi.atEnd {
+ if err := pi.fill(pi.MaxSize); err != nil {
+ pi.err = err
+ return pi.err
+ }
+ if pi.Token == "" {
+ pi.atEnd = true
+ }
+ }
+ // Either the buffer is non-empty or pi.atEnd is true (or both).
+ if pi.bufLen() == 0 {
+ // The buffer is empty and pi.atEnd is true, i.e. the service has no
+ // more items.
+ pi.err = Done
+ }
+ return pi.err
+}
+
+// Call the service to fill the buffer, using size and pi.Token. Set pi.Token to the
+// next-page token returned by the call.
+// If fill returns a non-nil error, the buffer will be empty.
+func (pi *PageInfo) fill(size int) error {
+ tok, err := pi.fetch(size, pi.Token)
+ if err != nil {
+ pi.takeBuf() // clear the buffer
+ return err
+ }
+ pi.Token = tok
+ return nil
+}
+
+// Pageable is implemented by iterators that support paging.
+type Pageable interface {
+ // PageInfo returns paging information associated with the iterator.
+ PageInfo() *PageInfo
+}
+
+// Pager supports retrieving iterator items a page at a time.
+type Pager struct {
+ pageInfo *PageInfo
+ pageSize int
+}
+
+// NewPager returns a pager that uses iter. Calls to its NextPage method will
+// obtain exactly pageSize items, unless fewer remain. The pageToken argument
+// indicates where to start the iteration. Pass the empty string to start at
+// the beginning, or pass a token retrieved from a call to Pager.NextPage.
+//
+// If you use an iterator with a Pager, you must not call Next on the iterator.
+func NewPager(iter Pageable, pageSize int, pageToken string) *Pager {
+ p := &Pager{
+ pageInfo: iter.PageInfo(),
+ pageSize: pageSize,
+ }
+ p.pageInfo.Token = pageToken
+ if pageSize <= 0 {
+ p.pageInfo.err = errors.New("iterator: page size must be positive")
+ }
+ return p
+}
+
+// NextPage retrieves a sequence of items from the iterator and appends them
+// to slicep, which must be a pointer to a slice of the iterator's item type.
+// Exactly p.pageSize items will be appended, unless fewer remain.
+//
+// The first return value is the page token to use for the next page of items.
+// If empty, there are no more pages. Aside from checking for the end of the
+// iteration, the returned page token is only needed if the iteration is to be
+// resumed a later time, in another context (possibly another process).
+//
+// The second return value is non-nil if an error occurred. It will never be
+// the special iterator sentinel value Done. To recognize the end of the
+// iteration, compare nextPageToken to the empty string.
+//
+// It is possible for NextPage to return a single zero-length page along with
+// an empty page token when there are no more items in the iteration.
+func (p *Pager) NextPage(slicep interface{}) (nextPageToken string, err error) {
+ p.pageInfo.nextPageCalled = true
+ if p.pageInfo.err != nil {
+ return "", p.pageInfo.err
+ }
+ if p.pageInfo.nextCalled {
+ p.pageInfo.err = errMixed
+ return "", p.pageInfo.err
+ }
+ if p.pageInfo.bufLen() > 0 {
+ return "", errors.New("must call NextPage with an empty buffer")
+ }
+ // The buffer must be empty here, so takeBuf is a no-op. We call it just to get
+ // the buffer's type.
+ wantSliceType := reflect.PtrTo(reflect.ValueOf(p.pageInfo.takeBuf()).Type())
+ if slicep == nil {
+ return "", errors.New("nil passed to Pager.NextPage")
+ }
+ vslicep := reflect.ValueOf(slicep)
+ if vslicep.Type() != wantSliceType {
+ return "", fmt.Errorf("slicep should be of type %s, got %T", wantSliceType, slicep)
+ }
+ for p.pageInfo.bufLen() < p.pageSize {
+ if err := p.pageInfo.fill(p.pageSize - p.pageInfo.bufLen()); err != nil {
+ p.pageInfo.err = err
+ return "", p.pageInfo.err
+ }
+ if p.pageInfo.Token == "" {
+ break
+ }
+ }
+ e := vslicep.Elem()
+ e.Set(reflect.AppendSlice(e, reflect.ValueOf(p.pageInfo.takeBuf())))
+ return p.pageInfo.Token, nil
+}
diff --git a/vendor/google.golang.org/api/option/option.go b/vendor/google.golang.org/api/option/option.go
new file mode 100644
index 0000000..f266919
--- /dev/null
+++ b/vendor/google.golang.org/api/option/option.go
@@ -0,0 +1,142 @@
+// Package option contains options for Google API clients.
+package option
+
+import (
+ "net/http"
+
+ "golang.org/x/oauth2"
+ "google.golang.org/api/internal"
+ "google.golang.org/grpc"
+)
+
+// A ClientOption is an option for a Google API client.
+type ClientOption interface {
+ Apply(*internal.DialSettings)
+}
+
+// WithTokenSource returns a ClientOption that specifies an OAuth2 token
+// source to be used as the basis for authentication.
+func WithTokenSource(s oauth2.TokenSource) ClientOption {
+ return withTokenSource{s}
+}
+
+type withTokenSource struct{ ts oauth2.TokenSource }
+
+func (w withTokenSource) Apply(o *internal.DialSettings) {
+ o.TokenSource = w.ts
+}
+
+// WithServiceAccountFile returns a ClientOption that uses a Google service
+// account credentials file to authenticate.
+// Use WithTokenSource with a token source created from
+// golang.org/x/oauth2/google.JWTConfigFromJSON
+// if reading the file from disk is not an option.
+func WithServiceAccountFile(filename string) ClientOption {
+ return withServiceAccountFile(filename)
+}
+
+type withServiceAccountFile string
+
+func (w withServiceAccountFile) Apply(o *internal.DialSettings) {
+ o.ServiceAccountJSONFilename = string(w)
+}
+
+// WithEndpoint returns a ClientOption that overrides the default endpoint
+// to be used for a service.
+func WithEndpoint(url string) ClientOption {
+ return withEndpoint(url)
+}
+
+type withEndpoint string
+
+func (w withEndpoint) Apply(o *internal.DialSettings) {
+ o.Endpoint = string(w)
+}
+
+// WithScopes returns a ClientOption that overrides the default OAuth2 scopes
+// to be used for a service.
+func WithScopes(scope ...string) ClientOption {
+ return withScopes(scope)
+}
+
+type withScopes []string
+
+func (w withScopes) Apply(o *internal.DialSettings) {
+ s := make([]string, len(w))
+ copy(s, w)
+ o.Scopes = s
+}
+
+// WithUserAgent returns a ClientOption that sets the User-Agent.
+func WithUserAgent(ua string) ClientOption {
+ return withUA(ua)
+}
+
+type withUA string
+
+func (w withUA) Apply(o *internal.DialSettings) { o.UserAgent = string(w) }
+
+// WithHTTPClient returns a ClientOption that specifies the HTTP client to use
+// as the basis of communications. This option may only be used with services
+// that support HTTP as their communication transport. When used, the
+// WithHTTPClient option takes precedent over all other supplied options.
+func WithHTTPClient(client *http.Client) ClientOption {
+ return withHTTPClient{client}
+}
+
+type withHTTPClient struct{ client *http.Client }
+
+func (w withHTTPClient) Apply(o *internal.DialSettings) {
+ o.HTTPClient = w.client
+}
+
+// WithGRPCConn returns a ClientOption that specifies the gRPC client
+// connection to use as the basis of communications. This option many only be
+// used with services that support gRPC as their communication transport. When
+// used, the WithGRPCConn option takes precedent over all other supplied
+// options.
+func WithGRPCConn(conn *grpc.ClientConn) ClientOption {
+ return withGRPCConn{conn}
+}
+
+type withGRPCConn struct{ conn *grpc.ClientConn }
+
+func (w withGRPCConn) Apply(o *internal.DialSettings) {
+ o.GRPCConn = w.conn
+}
+
+// WithGRPCDialOption returns a ClientOption that appends a new grpc.DialOption
+// to an underlying gRPC dial. It does not work with WithGRPCConn.
+func WithGRPCDialOption(opt grpc.DialOption) ClientOption {
+ return withGRPCDialOption{opt}
+}
+
+type withGRPCDialOption struct{ opt grpc.DialOption }
+
+func (w withGRPCDialOption) Apply(o *internal.DialSettings) {
+ o.GRPCDialOpts = append(o.GRPCDialOpts, w.opt)
+}
+
+// WithGRPCConnectionPool returns a ClientOption that creates a pool of gRPC
+// connections that requests will be balanced between.
+// This is an EXPERIMENTAL API and may be changed or removed in the future.
+func WithGRPCConnectionPool(size int) ClientOption {
+ return withGRPCConnectionPool(size)
+}
+
+type withGRPCConnectionPool int
+
+func (w withGRPCConnectionPool) Apply(o *internal.DialSettings) {
+ balancer := grpc.RoundRobin(internal.NewPoolResolver(int(w), o))
+ o.GRPCDialOpts = append(o.GRPCDialOpts, grpc.WithBalancer(balancer))
+}
+
+// WithAPIKey returns a ClientOption that specifies an API key to be used
+// as the basis for authentication.
+func WithAPIKey(apiKey string) ClientOption {
+ return withAPIKey(apiKey)
+}
+
+type withAPIKey string
+
+func (w withAPIKey) Apply(o *internal.DialSettings) { o.APIKey = string(w) }
diff --git a/vendor/google.golang.org/api/support/bundler/bundler.go b/vendor/google.golang.org/api/support/bundler/bundler.go
new file mode 100644
index 0000000..4faf13e
--- /dev/null
+++ b/vendor/google.golang.org/api/support/bundler/bundler.go
@@ -0,0 +1,261 @@
+// Copyright 2016 Google Inc. All Rights Reserved.
+//
+// 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 bundler supports bundling (batching) of items. Bundling amortizes an
+// action with fixed costs over multiple items. For example, if an API provides
+// an RPC that accepts a list of items as input, but clients would prefer
+// adding items one at a time, then a Bundler can accept individual items from
+// the client and bundle many of them into a single RPC.
+//
+// This package is experimental and subject to change without notice.
+package bundler
+
+import (
+ "errors"
+ "reflect"
+ "sync"
+ "time"
+)
+
+const (
+ DefaultDelayThreshold = time.Second
+ DefaultBundleCountThreshold = 10
+ DefaultBundleByteThreshold = 1e6 // 1M
+ DefaultBufferedByteLimit = 1e9 // 1G
+)
+
+var (
+ // ErrOverflow indicates that Bundler's stored bytes exceeds its BufferedByteLimit.
+ ErrOverflow = errors.New("bundler reached buffered byte limit")
+
+ // ErrOversizedItem indicates that an item's size exceeds the maximum bundle size.
+ ErrOversizedItem = errors.New("item size exceeds bundle byte limit")
+)
+
+// A Bundler collects items added to it into a bundle until the bundle
+// exceeds a given size, then calls a user-provided function to handle the bundle.
+type Bundler struct {
+ // Starting from the time that the first message is added to a bundle, once
+ // this delay has passed, handle the bundle. The default is DefaultDelayThreshold.
+ DelayThreshold time.Duration
+
+ // Once a bundle has this many items, handle the bundle. Since only one
+ // item at a time is added to a bundle, no bundle will exceed this
+ // threshold, so it also serves as a limit. The default is
+ // DefaultBundleCountThreshold.
+ BundleCountThreshold int
+
+ // Once the number of bytes in current bundle reaches this threshold, handle
+ // the bundle. The default is DefaultBundleByteThreshold. This triggers handling,
+ // but does not cap the total size of a bundle.
+ BundleByteThreshold int
+
+ // The maximum size of a bundle, in bytes. Zero means unlimited.
+ BundleByteLimit int
+
+ // The maximum number of bytes that the Bundler will keep in memory before
+ // returning ErrOverflow. The default is DefaultBufferedByteLimit.
+ BufferedByteLimit int
+
+ handler func(interface{}) // called to handle a bundle
+ itemSliceZero reflect.Value // nil (zero value) for slice of items
+ donec chan struct{} // closed when the Bundler is closed
+ handlec chan int // sent to when a bundle is ready for handling
+ timer *time.Timer // implements DelayThreshold
+
+ mu sync.Mutex
+ bufferedSize int // total bytes buffered
+ closedBundles []bundle // bundles waiting to be handled
+ curBundle bundle // incoming items added to this bundle
+ calledc chan struct{} // closed and re-created after handler is called
+}
+
+type bundle struct {
+ items reflect.Value // slice of item type
+ size int // size in bytes of all items
+}
+
+// NewBundler creates a new Bundler. When you are finished with a Bundler, call
+// its Close method.
+//
+// itemExample is a value of the type that will be bundled. For example, if you
+// want to create bundles of *Entry, you could pass &Entry{} for itemExample.
+//
+// handler is a function that will be called on each bundle. If itemExample is
+// of type T, the argument to handler is of type []T. handler is always called
+// sequentially for each bundle, and never in parallel.
+func NewBundler(itemExample interface{}, handler func(interface{})) *Bundler {
+ b := &Bundler{
+ DelayThreshold: DefaultDelayThreshold,
+ BundleCountThreshold: DefaultBundleCountThreshold,
+ BundleByteThreshold: DefaultBundleByteThreshold,
+ BufferedByteLimit: DefaultBufferedByteLimit,
+
+ handler: handler,
+ itemSliceZero: reflect.Zero(reflect.SliceOf(reflect.TypeOf(itemExample))),
+ donec: make(chan struct{}),
+ handlec: make(chan int, 1),
+ calledc: make(chan struct{}),
+ timer: time.NewTimer(1000 * time.Hour), // harmless initial timeout
+ }
+ b.curBundle.items = b.itemSliceZero
+ go b.background()
+ return b
+}
+
+// Add adds item to the current bundle. It marks the bundle for handling and
+// starts a new one if any of the thresholds or limits are exceeded.
+//
+// If the item's size exceeds the maximum bundle size (Bundler.BundleByteLimit), then
+// the item can never be handled. Add returns ErrOversizedItem in this case.
+//
+// If adding the item would exceed the maximum memory allowed (Bundler.BufferedByteLimit),
+// Add returns ErrOverflow.
+//
+// Add never blocks.
+func (b *Bundler) Add(item interface{}, size int) error {
+ // If this item exceeds the maximum size of a bundle,
+ // we can never send it.
+ if b.BundleByteLimit > 0 && size > b.BundleByteLimit {
+ return ErrOversizedItem
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ // If adding this item would exceed our allotted memory
+ // footprint, we can't accept it.
+ if b.bufferedSize+size > b.BufferedByteLimit {
+ return ErrOverflow
+ }
+ // If adding this item to the current bundle would cause it to exceed the
+ // maximum bundle size, close the current bundle and start a new one.
+ if b.BundleByteLimit > 0 && b.curBundle.size+size > b.BundleByteLimit {
+ b.closeAndHandleBundle()
+ }
+ // Add the item.
+ b.curBundle.items = reflect.Append(b.curBundle.items, reflect.ValueOf(item))
+ b.curBundle.size += size
+ b.bufferedSize += size
+ // If this is the first item in the bundle, restart the timer.
+ if b.curBundle.items.Len() == 1 {
+ b.timer.Reset(b.DelayThreshold)
+ }
+ // If the current bundle equals the count threshold, close it.
+ if b.curBundle.items.Len() == b.BundleCountThreshold {
+ b.closeAndHandleBundle()
+ }
+ // If the current bundle equals or exceeds the byte threshold, close it.
+ if b.curBundle.size >= b.BundleByteThreshold {
+ b.closeAndHandleBundle()
+ }
+ return nil
+}
+
+// Flush waits until all items in the Bundler have been handled (that is,
+// until the last invocation of handler has returned).
+func (b *Bundler) Flush() {
+ b.mu.Lock()
+ b.closeBundle()
+ // Unconditionally trigger the handling goroutine, to ensure calledc is closed
+ // even if there are no outstanding bundles.
+ select {
+ case b.handlec <- 1:
+ default:
+ }
+ calledc := b.calledc // remember locally, because it may change
+ b.mu.Unlock()
+ <-calledc
+}
+
+// Close calls Flush, then shuts down the Bundler. Close should always be
+// called on a Bundler when it is no longer needed. You must wait for all calls
+// to Add to complete before calling Close. Calling Add concurrently with Close
+// may result in the added items being ignored.
+func (b *Bundler) Close() {
+ b.Flush()
+ b.mu.Lock()
+ b.timer.Stop()
+ b.mu.Unlock()
+ close(b.donec)
+}
+
+func (b *Bundler) closeAndHandleBundle() {
+ if b.closeBundle() {
+ // We have created a closed bundle.
+ // Send to handlec without blocking.
+ select {
+ case b.handlec <- 1:
+ default:
+ }
+ }
+}
+
+// closeBundle finishes the current bundle, adds it to the list of closed
+// bundles and informs the background goroutine that there are bundles ready
+// for processing.
+//
+// This should always be called with b.mu held.
+func (b *Bundler) closeBundle() bool {
+ if b.curBundle.items.Len() == 0 {
+ return false
+ }
+ b.closedBundles = append(b.closedBundles, b.curBundle)
+ b.curBundle.items = b.itemSliceZero
+ b.curBundle.size = 0
+ return true
+}
+
+// background runs in a separate goroutine, waiting for events and handling
+// bundles.
+func (b *Bundler) background() {
+ done := false
+ for {
+ timedOut := false
+ // Wait for something to happen.
+ select {
+ case <-b.handlec:
+ case <-b.donec:
+ done = true
+ case <-b.timer.C:
+ timedOut = true
+ }
+ // Handle closed bundles.
+ b.mu.Lock()
+ if timedOut {
+ b.closeBundle()
+ }
+ buns := b.closedBundles
+ b.closedBundles = nil
+ // Closing calledc means we've sent all bundles. We need
+ // a new channel for the next set of bundles, which may start
+ // accumulating as soon as we release the lock.
+ calledc := b.calledc
+ b.calledc = make(chan struct{})
+ b.mu.Unlock()
+ for i, bun := range buns {
+ b.handler(bun.items.Interface())
+ // Drop the bundle's items, reducing our memory footprint.
+ buns[i].items = reflect.Value{} // buns[i] because bun is a copy
+ // Note immediately that we have more space, so Adds that occur
+ // during this loop will have a chance of succeeding.
+ b.mu.Lock()
+ b.bufferedSize -= bun.size
+ b.mu.Unlock()
+ }
+ // Signal that we've sent all outstanding bundles.
+ close(calledc)
+ if done {
+ break
+ }
+ }
+}
diff --git a/vendor/google.golang.org/api/transport/dial.go b/vendor/google.golang.org/api/transport/dial.go
new file mode 100644
index 0000000..9971eb8
--- /dev/null
+++ b/vendor/google.golang.org/api/transport/dial.go
@@ -0,0 +1,134 @@
+// Copyright 2015 Google Inc. All Rights Reserved.
+//
+// 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 transport supports network connections to HTTP and GRPC servers.
+// This package is not intended for use by end developers. Use the
+// google.golang.org/api/option package to configure API clients.
+package transport
+
+import (
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "net/http"
+
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/google"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/credentials/oauth"
+
+ gtransport "google.golang.org/api/googleapi/transport"
+ "google.golang.org/api/internal"
+ "google.golang.org/api/option"
+)
+
+// NewHTTPClient returns an HTTP client for use communicating with a Google cloud
+// service, configured with the given ClientOptions. It also returns the endpoint
+// for the service as specified in the options.
+func NewHTTPClient(ctx context.Context, opts ...option.ClientOption) (*http.Client, string, error) {
+ var o internal.DialSettings
+ for _, opt := range opts {
+ opt.Apply(&o)
+ }
+ if o.GRPCConn != nil {
+ return nil, "", errors.New("unsupported gRPC connection specified")
+ }
+ // TODO(djd): Set UserAgent on all outgoing requests.
+ if o.HTTPClient != nil {
+ return o.HTTPClient, o.Endpoint, nil
+ }
+ if o.APIKey != "" {
+ hc := &http.Client{
+ Transport: &gtransport.APIKey{
+ Key: o.APIKey,
+ Transport: http.DefaultTransport,
+ },
+ }
+ return hc, o.Endpoint, nil
+ }
+ if o.ServiceAccountJSONFilename != "" {
+ ts, err := serviceAcctTokenSource(ctx, o.ServiceAccountJSONFilename, o.Scopes...)
+ if err != nil {
+ return nil, "", err
+ }
+ o.TokenSource = ts
+ }
+ if o.TokenSource == nil {
+ var err error
+ o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
+ if err != nil {
+ return nil, "", fmt.Errorf("google.DefaultTokenSource: %v", err)
+ }
+ }
+ return oauth2.NewClient(ctx, o.TokenSource), o.Endpoint, nil
+}
+
+// Set at init time by dial_appengine.go. If nil, we're not on App Engine.
+var appengineDialerHook func(context.Context) grpc.DialOption
+
+// DialGRPC returns a GRPC connection for use communicating with a Google cloud
+// service, configured with the given ClientOptions.
+func DialGRPC(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {
+ var o internal.DialSettings
+ for _, opt := range opts {
+ opt.Apply(&o)
+ }
+ if o.HTTPClient != nil {
+ return nil, errors.New("unsupported HTTP client specified")
+ }
+ if o.GRPCConn != nil {
+ return o.GRPCConn, nil
+ }
+ if o.ServiceAccountJSONFilename != "" {
+ ts, err := serviceAcctTokenSource(ctx, o.ServiceAccountJSONFilename, o.Scopes...)
+ if err != nil {
+ return nil, err
+ }
+ o.TokenSource = ts
+ }
+ if o.TokenSource == nil {
+ var err error
+ o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
+ if err != nil {
+ return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
+ }
+ }
+ grpcOpts := []grpc.DialOption{
+ grpc.WithPerRPCCredentials(oauth.TokenSource{o.TokenSource}),
+ grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
+ }
+ if appengineDialerHook != nil {
+ // Use the Socket API on App Engine.
+ grpcOpts = append(grpcOpts, appengineDialerHook(ctx))
+ }
+ grpcOpts = append(grpcOpts, o.GRPCDialOpts...)
+ if o.UserAgent != "" {
+ grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
+ }
+ return grpc.DialContext(ctx, o.Endpoint, grpcOpts...)
+}
+
+func serviceAcctTokenSource(ctx context.Context, filename string, scope ...string) (oauth2.TokenSource, error) {
+ data, err := ioutil.ReadFile(filename)
+ if err != nil {
+ return nil, fmt.Errorf("cannot read service account file: %v", err)
+ }
+ cfg, err := google.JWTConfigFromJSON(data, scope...)
+ if err != nil {
+ return nil, fmt.Errorf("google.JWTConfigFromJSON: %v", err)
+ }
+ return cfg.TokenSource(ctx), nil
+}
diff --git a/vendor/google.golang.org/api/transport/dial_appengine.go b/vendor/google.golang.org/api/transport/dial_appengine.go
new file mode 100644
index 0000000..201244d
--- /dev/null
+++ b/vendor/google.golang.org/api/transport/dial_appengine.go
@@ -0,0 +1,34 @@
+// Copyright 2016 Google Inc. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build appengine
+
+package transport
+
+import (
+ "net"
+ "time"
+
+ "golang.org/x/net/context"
+ "google.golang.org/appengine/socket"
+ "google.golang.org/grpc"
+)
+
+func init() {
+ appengineDialerHook = func(ctx context.Context) grpc.DialOption {
+ return grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
+ return socket.DialTimeout(ctx, "tcp", addr, timeout)
+ })
+ }
+}
diff --git a/vendor/google.golang.org/genproto/LICENSE b/vendor/google.golang.org/genproto/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/vendor/google.golang.org/genproto/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/google.golang.org/genproto/README.md b/vendor/google.golang.org/genproto/README.md
new file mode 100644
index 0000000..51d0bae
--- /dev/null
+++ b/vendor/google.golang.org/genproto/README.md
@@ -0,0 +1,28 @@
+Go generated proto packages
+===========================
+
+[![Build Status](https://travis-ci.org/google/go-genproto.svg?branch=master)](https://travis-ci.org/google/go-genproto)
+[![GoDoc](https://godoc.org/google.golang.org/genproto?status.svg)](https://godoc.org/google.golang.org/genproto)
+
+> **IMPORTANT** This repository is currently experimental. The structure
+> of the contained packages is subject to change. Please see the original
+> source repositories (listed below) to find out the status of the each
+> protocol buffer's associated service.
+
+This repository contains the generated Go packages for common protocol buffer
+types, and the generated [gRPC][1] code necessary for interacting with Google's gRPC
+APIs.
+
+There are two sources for the proto files used in this repository:
+
+1. [google/protobuf][2]: the code in the `protobuf` and `ptypes` subdirectories
+ is derived from this repo. The messages in `protobuf` are used to describe
+ protocol buffer messages themselves. The messages under `ptypes` define the
+ common well-known types.
+2. [googleapis/googleapis][3]: the code in the `googleapis` is derived from this
+ repo. The packages here contain types specifically for interacting with Google
+ APIs.
+
+[1]: http://grpc.io
+[2]: https://github.com/google/protobuf/
+[3]: https://github.com/googleapis/googleapis/
diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go
new file mode 100644
index 0000000..b37ccee
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go
@@ -0,0 +1,65 @@
+// Code generated by protoc-gen-go.
+// source: google/api/annotations.proto
+// DO NOT EDIT!
+
+/*
+Package annotations is a generated protocol buffer package.
+
+It is generated from these files:
+ google/api/annotations.proto
+ google/api/http.proto
+
+It has these top-level messages:
+ Http
+ HttpRule
+ CustomHttpPattern
+*/
+package annotations
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+var E_Http = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.MethodOptions)(nil),
+ ExtensionType: (*HttpRule)(nil),
+ Field: 72295728,
+ Name: "google.api.http",
+ Tag: "bytes,72295728,opt,name=http",
+ Filename: "google/api/annotations.proto",
+}
+
+func init() {
+ proto.RegisterExtension(E_Http)
+}
+
+func init() { proto.RegisterFile("google/api/annotations.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 208 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x49, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0xd5, 0x4f, 0x2c, 0xc8, 0xd4, 0x4f, 0xcc, 0xcb, 0xcb, 0x2f, 0x49, 0x2c, 0xc9, 0xcc,
+ 0xcf, 0x2b, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x82, 0xc8, 0xea, 0x25, 0x16, 0x64,
+ 0x4a, 0x89, 0x22, 0xa9, 0xcc, 0x28, 0x29, 0x29, 0x80, 0x28, 0x91, 0x52, 0x80, 0x0a, 0x83, 0x79,
+ 0x49, 0xa5, 0x69, 0xfa, 0x29, 0xa9, 0xc5, 0xc9, 0x45, 0x99, 0x05, 0x25, 0xf9, 0x45, 0x10, 0x15,
+ 0x56, 0xde, 0x5c, 0x2c, 0x20, 0xf5, 0x42, 0x72, 0x7a, 0x50, 0xd3, 0x60, 0x4a, 0xf5, 0x7c, 0x53,
+ 0x4b, 0x32, 0xf2, 0x53, 0xfc, 0x0b, 0xc0, 0x56, 0x4a, 0x6c, 0x38, 0xb5, 0x47, 0x49, 0x81, 0x51,
+ 0x83, 0xdb, 0x48, 0x44, 0x0f, 0x61, 0xad, 0x9e, 0x47, 0x49, 0x49, 0x41, 0x50, 0x69, 0x4e, 0x6a,
+ 0x10, 0xd8, 0x10, 0xa7, 0x3c, 0x2e, 0xbe, 0xe4, 0xfc, 0x5c, 0x24, 0x05, 0x4e, 0x02, 0x8e, 0x08,
+ 0x67, 0x07, 0x80, 0x4c, 0x0e, 0x60, 0x8c, 0x72, 0x84, 0xca, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5,
+ 0xeb, 0xe5, 0x17, 0xa5, 0xeb, 0xa7, 0xa7, 0xe6, 0x81, 0xed, 0xd5, 0x87, 0x48, 0x25, 0x16, 0x64,
+ 0x16, 0xa3, 0x7b, 0xda, 0x1a, 0x89, 0xbd, 0x88, 0x89, 0xc5, 0xdd, 0x31, 0xc0, 0x33, 0x89, 0x0d,
+ 0xac, 0xc9, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xe3, 0x29, 0x19, 0x62, 0x28, 0x01, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go
new file mode 100644
index 0000000..583ecf6
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go
@@ -0,0 +1,567 @@
+// Code generated by protoc-gen-go.
+// source: google/api/http.proto
+// DO NOT EDIT!
+
+package annotations
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// Defines the HTTP configuration for a service. It contains a list of
+// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
+// to one or more HTTP REST API methods.
+type Http struct {
+ // A list of HTTP configuration rules that apply to individual API methods.
+ //
+ // **NOTE:** All service configuration rules follow "last one wins" order.
+ Rules []*HttpRule `protobuf:"bytes,1,rep,name=rules" json:"rules,omitempty"`
+}
+
+func (m *Http) Reset() { *m = Http{} }
+func (m *Http) String() string { return proto.CompactTextString(m) }
+func (*Http) ProtoMessage() {}
+func (*Http) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} }
+
+func (m *Http) GetRules() []*HttpRule {
+ if m != nil {
+ return m.Rules
+ }
+ return nil
+}
+
+// `HttpRule` defines the mapping of an RPC method to one or more HTTP
+// REST APIs. The mapping determines what portions of the request
+// message are populated from the path, query parameters, or body of
+// the HTTP request. The mapping is typically specified as an
+// `google.api.http` annotation, see "google/api/annotations.proto"
+// for details.
+//
+// The mapping consists of a field specifying the path template and
+// method kind. The path template can refer to fields in the request
+// message, as in the example below which describes a REST GET
+// operation on a resource collection of messages:
+//
+//
+// service Messaging {
+// rpc GetMessage(GetMessageRequest) returns (Message) {
+// option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}";
+// }
+// }
+// message GetMessageRequest {
+// message SubMessage {
+// string subfield = 1;
+// }
+// string message_id = 1; // mapped to the URL
+// SubMessage sub = 2; // `sub.subfield` is url-mapped
+// }
+// message Message {
+// string text = 1; // content of the resource
+// }
+//
+// The same http annotation can alternatively be expressed inside the
+// `GRPC API Configuration` YAML file.
+//
+// http:
+// rules:
+// - selector: <proto_package_name>.Messaging.GetMessage
+// get: /v1/messages/{message_id}/{sub.subfield}
+//
+// This definition enables an automatic, bidrectional mapping of HTTP
+// JSON to RPC. Example:
+//
+// HTTP | RPC
+// -----|-----
+// `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))`
+//
+// In general, not only fields but also field paths can be referenced
+// from a path pattern. Fields mapped to the path pattern cannot be
+// repeated and must have a primitive (non-message) type.
+//
+// Any fields in the request message which are not bound by the path
+// pattern automatically become (optional) HTTP query
+// parameters. Assume the following definition of the request message:
+//
+//
+// message GetMessageRequest {
+// message SubMessage {
+// string subfield = 1;
+// }
+// string message_id = 1; // mapped to the URL
+// int64 revision = 2; // becomes a parameter
+// SubMessage sub = 3; // `sub.subfield` becomes a parameter
+// }
+//
+//
+// This enables a HTTP JSON to RPC mapping as below:
+//
+// HTTP | RPC
+// -----|-----
+// `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))`
+//
+// Note that fields which are mapped to HTTP parameters must have a
+// primitive type or a repeated primitive type. Message types are not
+// allowed. In the case of a repeated type, the parameter can be
+// repeated in the URL, as in `...?param=A&param=B`.
+//
+// For HTTP method kinds which allow a request body, the `body` field
+// specifies the mapping. Consider a REST update method on the
+// message resource collection:
+//
+//
+// service Messaging {
+// rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
+// option (google.api.http) = {
+// put: "/v1/messages/{message_id}"
+// body: "message"
+// };
+// }
+// }
+// message UpdateMessageRequest {
+// string message_id = 1; // mapped to the URL
+// Message message = 2; // mapped to the body
+// }
+//
+//
+// The following HTTP JSON to RPC mapping is enabled, where the
+// representation of the JSON in the request body is determined by
+// protos JSON encoding:
+//
+// HTTP | RPC
+// -----|-----
+// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })`
+//
+// The special name `*` can be used in the body mapping to define that
+// every field not bound by the path template should be mapped to the
+// request body. This enables the following alternative definition of
+// the update method:
+//
+// service Messaging {
+// rpc UpdateMessage(Message) returns (Message) {
+// option (google.api.http) = {
+// put: "/v1/messages/{message_id}"
+// body: "*"
+// };
+// }
+// }
+// message Message {
+// string message_id = 1;
+// string text = 2;
+// }
+//
+//
+// The following HTTP JSON to RPC mapping is enabled:
+//
+// HTTP | RPC
+// -----|-----
+// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")`
+//
+// Note that when using `*` in the body mapping, it is not possible to
+// have HTTP parameters, as all fields not bound by the path end in
+// the body. This makes this option more rarely used in practice of
+// defining REST APIs. The common usage of `*` is in custom methods
+// which don't use the URL at all for transferring data.
+//
+// It is possible to define multiple HTTP methods for one RPC by using
+// the `additional_bindings` option. Example:
+//
+// service Messaging {
+// rpc GetMessage(GetMessageRequest) returns (Message) {
+// option (google.api.http) = {
+// get: "/v1/messages/{message_id}"
+// additional_bindings {
+// get: "/v1/users/{user_id}/messages/{message_id}"
+// }
+// };
+// }
+// }
+// message GetMessageRequest {
+// string message_id = 1;
+// string user_id = 2;
+// }
+//
+//
+// This enables the following two alternative HTTP JSON to RPC
+// mappings:
+//
+// HTTP | RPC
+// -----|-----
+// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")`
+// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")`
+//
+// # Rules for HTTP mapping
+//
+// The rules for mapping HTTP path, query parameters, and body fields
+// to the request message are as follows:
+//
+// 1. The `body` field specifies either `*` or a field path, or is
+// omitted. If omitted, it assumes there is no HTTP body.
+// 2. Leaf fields (recursive expansion of nested messages in the
+// request) can be classified into three types:
+// (a) Matched in the URL template.
+// (b) Covered by body (if body is `*`, everything except (a) fields;
+// else everything under the body field)
+// (c) All other fields.
+// 3. URL query parameters found in the HTTP request are mapped to (c) fields.
+// 4. Any body sent with an HTTP request can contain only (b) fields.
+//
+// The syntax of the path template is as follows:
+//
+// Template = "/" Segments [ Verb ] ;
+// Segments = Segment { "/" Segment } ;
+// Segment = "*" | "**" | LITERAL | Variable ;
+// Variable = "{" FieldPath [ "=" Segments ] "}" ;
+// FieldPath = IDENT { "." IDENT } ;
+// Verb = ":" LITERAL ;
+//
+// The syntax `*` matches a single path segment. It follows the semantics of
+// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String
+// Expansion.
+//
+// The syntax `**` matches zero or more path segments. It follows the semantics
+// of [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.3 Reserved
+// Expansion. NOTE: it must be the last segment in the path except the Verb.
+//
+// The syntax `LITERAL` matches literal text in the URL path.
+//
+// The syntax `Variable` matches the entire path as specified by its template;
+// this nested template must not contain further variables. If a variable
+// matches a single path segment, its template may be omitted, e.g. `{var}`
+// is equivalent to `{var=*}`.
+//
+// NOTE: the field paths in variables and in the `body` must not refer to
+// repeated fields or map fields.
+//
+// Use CustomHttpPattern to specify any HTTP method that is not included in the
+// `pattern` field, such as HEAD, or "*" to leave the HTTP method unspecified for
+// a given URL path rule. The wild-card rule is useful for services that provide
+// content to Web (HTML) clients.
+type HttpRule struct {
+ // Selects methods to which this rule applies.
+ //
+ // Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
+ Selector string `protobuf:"bytes,1,opt,name=selector" json:"selector,omitempty"`
+ // Determines the URL pattern is matched by this rules. This pattern can be
+ // used with any of the {get|put|post|delete|patch} methods. A custom method
+ // can be defined using the 'custom' field.
+ //
+ // Types that are valid to be assigned to Pattern:
+ // *HttpRule_Get
+ // *HttpRule_Put
+ // *HttpRule_Post
+ // *HttpRule_Delete
+ // *HttpRule_Patch
+ // *HttpRule_Custom
+ Pattern isHttpRule_Pattern `protobuf_oneof:"pattern"`
+ // The name of the request field whose value is mapped to the HTTP body, or
+ // `*` for mapping all fields not captured by the path pattern to the HTTP
+ // body. NOTE: the referred field must not be a repeated field and must be
+ // present at the top-level of request message type.
+ Body string `protobuf:"bytes,7,opt,name=body" json:"body,omitempty"`
+ // Additional HTTP bindings for the selector. Nested bindings must
+ // not contain an `additional_bindings` field themselves (that is,
+ // the nesting may only be one level deep).
+ AdditionalBindings []*HttpRule `protobuf:"bytes,11,rep,name=additional_bindings,json=additionalBindings" json:"additional_bindings,omitempty"`
+}
+
+func (m *HttpRule) Reset() { *m = HttpRule{} }
+func (m *HttpRule) String() string { return proto.CompactTextString(m) }
+func (*HttpRule) ProtoMessage() {}
+func (*HttpRule) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} }
+
+type isHttpRule_Pattern interface {
+ isHttpRule_Pattern()
+}
+
+type HttpRule_Get struct {
+ Get string `protobuf:"bytes,2,opt,name=get,oneof"`
+}
+type HttpRule_Put struct {
+ Put string `protobuf:"bytes,3,opt,name=put,oneof"`
+}
+type HttpRule_Post struct {
+ Post string `protobuf:"bytes,4,opt,name=post,oneof"`
+}
+type HttpRule_Delete struct {
+ Delete string `protobuf:"bytes,5,opt,name=delete,oneof"`
+}
+type HttpRule_Patch struct {
+ Patch string `protobuf:"bytes,6,opt,name=patch,oneof"`
+}
+type HttpRule_Custom struct {
+ Custom *CustomHttpPattern `protobuf:"bytes,8,opt,name=custom,oneof"`
+}
+
+func (*HttpRule_Get) isHttpRule_Pattern() {}
+func (*HttpRule_Put) isHttpRule_Pattern() {}
+func (*HttpRule_Post) isHttpRule_Pattern() {}
+func (*HttpRule_Delete) isHttpRule_Pattern() {}
+func (*HttpRule_Patch) isHttpRule_Pattern() {}
+func (*HttpRule_Custom) isHttpRule_Pattern() {}
+
+func (m *HttpRule) GetPattern() isHttpRule_Pattern {
+ if m != nil {
+ return m.Pattern
+ }
+ return nil
+}
+
+func (m *HttpRule) GetSelector() string {
+ if m != nil {
+ return m.Selector
+ }
+ return ""
+}
+
+func (m *HttpRule) GetGet() string {
+ if x, ok := m.GetPattern().(*HttpRule_Get); ok {
+ return x.Get
+ }
+ return ""
+}
+
+func (m *HttpRule) GetPut() string {
+ if x, ok := m.GetPattern().(*HttpRule_Put); ok {
+ return x.Put
+ }
+ return ""
+}
+
+func (m *HttpRule) GetPost() string {
+ if x, ok := m.GetPattern().(*HttpRule_Post); ok {
+ return x.Post
+ }
+ return ""
+}
+
+func (m *HttpRule) GetDelete() string {
+ if x, ok := m.GetPattern().(*HttpRule_Delete); ok {
+ return x.Delete
+ }
+ return ""
+}
+
+func (m *HttpRule) GetPatch() string {
+ if x, ok := m.GetPattern().(*HttpRule_Patch); ok {
+ return x.Patch
+ }
+ return ""
+}
+
+func (m *HttpRule) GetCustom() *CustomHttpPattern {
+ if x, ok := m.GetPattern().(*HttpRule_Custom); ok {
+ return x.Custom
+ }
+ return nil
+}
+
+func (m *HttpRule) GetBody() string {
+ if m != nil {
+ return m.Body
+ }
+ return ""
+}
+
+func (m *HttpRule) GetAdditionalBindings() []*HttpRule {
+ if m != nil {
+ return m.AdditionalBindings
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*HttpRule) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _HttpRule_OneofMarshaler, _HttpRule_OneofUnmarshaler, _HttpRule_OneofSizer, []interface{}{
+ (*HttpRule_Get)(nil),
+ (*HttpRule_Put)(nil),
+ (*HttpRule_Post)(nil),
+ (*HttpRule_Delete)(nil),
+ (*HttpRule_Patch)(nil),
+ (*HttpRule_Custom)(nil),
+ }
+}
+
+func _HttpRule_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*HttpRule)
+ // pattern
+ switch x := m.Pattern.(type) {
+ case *HttpRule_Get:
+ b.EncodeVarint(2<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Get)
+ case *HttpRule_Put:
+ b.EncodeVarint(3<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Put)
+ case *HttpRule_Post:
+ b.EncodeVarint(4<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Post)
+ case *HttpRule_Delete:
+ b.EncodeVarint(5<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Delete)
+ case *HttpRule_Patch:
+ b.EncodeVarint(6<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Patch)
+ case *HttpRule_Custom:
+ b.EncodeVarint(8<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Custom); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("HttpRule.Pattern has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _HttpRule_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*HttpRule)
+ switch tag {
+ case 2: // pattern.get
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Pattern = &HttpRule_Get{x}
+ return true, err
+ case 3: // pattern.put
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Pattern = &HttpRule_Put{x}
+ return true, err
+ case 4: // pattern.post
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Pattern = &HttpRule_Post{x}
+ return true, err
+ case 5: // pattern.delete
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Pattern = &HttpRule_Delete{x}
+ return true, err
+ case 6: // pattern.patch
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Pattern = &HttpRule_Patch{x}
+ return true, err
+ case 8: // pattern.custom
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(CustomHttpPattern)
+ err := b.DecodeMessage(msg)
+ m.Pattern = &HttpRule_Custom{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _HttpRule_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*HttpRule)
+ // pattern
+ switch x := m.Pattern.(type) {
+ case *HttpRule_Get:
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Get)))
+ n += len(x.Get)
+ case *HttpRule_Put:
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Put)))
+ n += len(x.Put)
+ case *HttpRule_Post:
+ n += proto.SizeVarint(4<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Post)))
+ n += len(x.Post)
+ case *HttpRule_Delete:
+ n += proto.SizeVarint(5<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Delete)))
+ n += len(x.Delete)
+ case *HttpRule_Patch:
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Patch)))
+ n += len(x.Patch)
+ case *HttpRule_Custom:
+ s := proto.Size(x.Custom)
+ n += proto.SizeVarint(8<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// A custom pattern is used for defining custom HTTP verb.
+type CustomHttpPattern struct {
+ // The name of this custom HTTP verb.
+ Kind string `protobuf:"bytes,1,opt,name=kind" json:"kind,omitempty"`
+ // The path matched by this custom verb.
+ Path string `protobuf:"bytes,2,opt,name=path" json:"path,omitempty"`
+}
+
+func (m *CustomHttpPattern) Reset() { *m = CustomHttpPattern{} }
+func (m *CustomHttpPattern) String() string { return proto.CompactTextString(m) }
+func (*CustomHttpPattern) ProtoMessage() {}
+func (*CustomHttpPattern) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} }
+
+func (m *CustomHttpPattern) GetKind() string {
+ if m != nil {
+ return m.Kind
+ }
+ return ""
+}
+
+func (m *CustomHttpPattern) GetPath() string {
+ if m != nil {
+ return m.Path
+ }
+ return ""
+}
+
+func init() {
+ proto.RegisterType((*Http)(nil), "google.api.Http")
+ proto.RegisterType((*HttpRule)(nil), "google.api.HttpRule")
+ proto.RegisterType((*CustomHttpPattern)(nil), "google.api.CustomHttpPattern")
+}
+
+func init() { proto.RegisterFile("google/api/http.proto", fileDescriptor1) }
+
+var fileDescriptor1 = []byte{
+ // 359 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0xcf, 0x6a, 0xe3, 0x30,
+ 0x10, 0xc6, 0xd7, 0x89, 0xe3, 0x24, 0x13, 0x58, 0x58, 0x6d, 0x76, 0x11, 0x85, 0x42, 0xc8, 0x29,
+ 0xf4, 0x60, 0x43, 0x7a, 0xe8, 0x21, 0xa7, 0xb8, 0x94, 0xa6, 0xb7, 0xe0, 0x63, 0x2f, 0x45, 0xb1,
+ 0x85, 0xa2, 0xd6, 0x91, 0x84, 0x3d, 0x3e, 0xf4, 0x75, 0xfa, 0x0e, 0x7d, 0xb7, 0x1e, 0x8b, 0xfe,
+ 0xa4, 0x09, 0x14, 0x7a, 0x9b, 0xef, 0x37, 0x9f, 0x34, 0xa3, 0x19, 0xc1, 0x3f, 0xa1, 0xb5, 0xa8,
+ 0x79, 0xc6, 0x8c, 0xcc, 0xf6, 0x88, 0x26, 0x35, 0x8d, 0x46, 0x4d, 0xc0, 0xe3, 0x94, 0x19, 0x39,
+ 0x5f, 0x42, 0xbc, 0x41, 0x34, 0xe4, 0x0a, 0x06, 0x4d, 0x57, 0xf3, 0x96, 0x46, 0xb3, 0xfe, 0x62,
+ 0xb2, 0x9c, 0xa6, 0x27, 0x4f, 0x6a, 0x0d, 0x45, 0x57, 0xf3, 0xc2, 0x5b, 0xe6, 0xef, 0x3d, 0x18,
+ 0x1d, 0x19, 0xb9, 0x80, 0x51, 0xcb, 0x6b, 0x5e, 0xa2, 0x6e, 0x68, 0x34, 0x8b, 0x16, 0xe3, 0xe2,
+ 0x4b, 0x13, 0x02, 0x7d, 0xc1, 0x91, 0xf6, 0x2c, 0xde, 0xfc, 0x2a, 0xac, 0xb0, 0xcc, 0x74, 0x48,
+ 0xfb, 0x47, 0x66, 0x3a, 0x24, 0x53, 0x88, 0x8d, 0x6e, 0x91, 0xc6, 0x01, 0x3a, 0x45, 0x28, 0x24,
+ 0x15, 0xaf, 0x39, 0x72, 0x3a, 0x08, 0x3c, 0x68, 0xf2, 0x1f, 0x06, 0x86, 0x61, 0xb9, 0xa7, 0x49,
+ 0x48, 0x78, 0x49, 0x6e, 0x20, 0x29, 0xbb, 0x16, 0xf5, 0x81, 0x8e, 0x66, 0xd1, 0x62, 0xb2, 0xbc,
+ 0x3c, 0x7f, 0xc5, 0xad, 0xcb, 0xd8, 0xbe, 0xb7, 0x0c, 0x91, 0x37, 0xca, 0x5e, 0xe8, 0xed, 0x84,
+ 0x40, 0xbc, 0xd3, 0xd5, 0x2b, 0x1d, 0xba, 0x07, 0xb8, 0x98, 0xdc, 0xc1, 0x5f, 0x56, 0x55, 0x12,
+ 0xa5, 0x56, 0xac, 0x7e, 0xda, 0x49, 0x55, 0x49, 0x25, 0x5a, 0x3a, 0xf9, 0x61, 0x3e, 0xe4, 0x74,
+ 0x20, 0x0f, 0xfe, 0x7c, 0x0c, 0x43, 0xe3, 0xeb, 0xcd, 0x57, 0xf0, 0xe7, 0x5b, 0x13, 0xb6, 0xf4,
+ 0x8b, 0x54, 0x55, 0x98, 0x9d, 0x8b, 0x2d, 0x33, 0x0c, 0xf7, 0x7e, 0x70, 0x85, 0x8b, 0xf3, 0x67,
+ 0xf8, 0x5d, 0xea, 0xc3, 0x59, 0xd9, 0x7c, 0xec, 0xae, 0xb1, 0x1b, 0xdd, 0x46, 0x8f, 0xeb, 0x90,
+ 0x10, 0xba, 0x66, 0x4a, 0xa4, 0xba, 0x11, 0x99, 0xe0, 0xca, 0xed, 0x3b, 0xf3, 0x29, 0x66, 0x64,
+ 0xeb, 0x7e, 0x02, 0x53, 0x4a, 0x23, 0xb3, 0x6d, 0xb6, 0xab, 0xb3, 0xf8, 0x23, 0x8a, 0xde, 0x7a,
+ 0xf1, 0xfd, 0x7a, 0xfb, 0xb0, 0x4b, 0xdc, 0xb9, 0xeb, 0xcf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x68,
+ 0x15, 0x60, 0x5b, 0x40, 0x02, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/api/distribution/distribution.pb.go b/vendor/google.golang.org/genproto/googleapis/api/distribution/distribution.pb.go
new file mode 100644
index 0000000..1ff5823
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/api/distribution/distribution.pb.go
@@ -0,0 +1,507 @@
+// Code generated by protoc-gen-go.
+// source: google/api/distribution.proto
+// DO NOT EDIT!
+
+/*
+Package distribution is a generated protocol buffer package.
+
+It is generated from these files:
+ google/api/distribution.proto
+
+It has these top-level messages:
+ Distribution
+*/
+package distribution
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "google.golang.org/genproto/googleapis/api/annotations"
+import _ "github.com/golang/protobuf/ptypes/any"
+import _ "github.com/golang/protobuf/ptypes/timestamp"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// Distribution contains summary statistics for a population of values and,
+// optionally, a histogram representing the distribution of those values across
+// a specified set of histogram buckets.
+//
+// The summary statistics are the count, mean, sum of the squared deviation from
+// the mean, the minimum, and the maximum of the set of population of values.
+//
+// The histogram is based on a sequence of buckets and gives a count of values
+// that fall into each bucket. The boundaries of the buckets are given either
+// explicitly or by specifying parameters for a method of computing them
+// (buckets of fixed width or buckets of exponentially increasing width).
+//
+// Although it is not forbidden, it is generally a bad idea to include
+// non-finite values (infinities or NaNs) in the population of values, as this
+// will render the `mean` and `sum_of_squared_deviation` fields meaningless.
+type Distribution struct {
+ // The number of values in the population. Must be non-negative.
+ Count int64 `protobuf:"varint,1,opt,name=count" json:"count,omitempty"`
+ // The arithmetic mean of the values in the population. If `count` is zero
+ // then this field must be zero.
+ Mean float64 `protobuf:"fixed64,2,opt,name=mean" json:"mean,omitempty"`
+ // The sum of squared deviations from the mean of the values in the
+ // population. For values x_i this is:
+ //
+ // Sum[i=1..n]((x_i - mean)^2)
+ //
+ // Knuth, "The Art of Computer Programming", Vol. 2, page 323, 3rd edition
+ // describes Welford's method for accumulating this sum in one pass.
+ //
+ // If `count` is zero then this field must be zero.
+ SumOfSquaredDeviation float64 `protobuf:"fixed64,3,opt,name=sum_of_squared_deviation,json=sumOfSquaredDeviation" json:"sum_of_squared_deviation,omitempty"`
+ // If specified, contains the range of the population values. The field
+ // must not be present if the `count` is zero.
+ Range *Distribution_Range `protobuf:"bytes,4,opt,name=range" json:"range,omitempty"`
+ // Defines the histogram bucket boundaries.
+ BucketOptions *Distribution_BucketOptions `protobuf:"bytes,6,opt,name=bucket_options,json=bucketOptions" json:"bucket_options,omitempty"`
+ // If `bucket_options` is given, then the sum of the values in `bucket_counts`
+ // must equal the value in `count`. If `bucket_options` is not given, no
+ // `bucket_counts` fields may be given.
+ //
+ // Bucket counts are given in order under the numbering scheme described
+ // above (the underflow bucket has number 0; the finite buckets, if any,
+ // have numbers 1 through N-2; the overflow bucket has number N-1).
+ //
+ // The size of `bucket_counts` must be no greater than N as defined in
+ // `bucket_options`.
+ //
+ // Any suffix of trailing zero bucket_count fields may be omitted.
+ BucketCounts []int64 `protobuf:"varint,7,rep,packed,name=bucket_counts,json=bucketCounts" json:"bucket_counts,omitempty"`
+}
+
+func (m *Distribution) Reset() { *m = Distribution{} }
+func (m *Distribution) String() string { return proto.CompactTextString(m) }
+func (*Distribution) ProtoMessage() {}
+func (*Distribution) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *Distribution) GetCount() int64 {
+ if m != nil {
+ return m.Count
+ }
+ return 0
+}
+
+func (m *Distribution) GetMean() float64 {
+ if m != nil {
+ return m.Mean
+ }
+ return 0
+}
+
+func (m *Distribution) GetSumOfSquaredDeviation() float64 {
+ if m != nil {
+ return m.SumOfSquaredDeviation
+ }
+ return 0
+}
+
+func (m *Distribution) GetRange() *Distribution_Range {
+ if m != nil {
+ return m.Range
+ }
+ return nil
+}
+
+func (m *Distribution) GetBucketOptions() *Distribution_BucketOptions {
+ if m != nil {
+ return m.BucketOptions
+ }
+ return nil
+}
+
+func (m *Distribution) GetBucketCounts() []int64 {
+ if m != nil {
+ return m.BucketCounts
+ }
+ return nil
+}
+
+// The range of the population values.
+type Distribution_Range struct {
+ // The minimum of the population values.
+ Min float64 `protobuf:"fixed64,1,opt,name=min" json:"min,omitempty"`
+ // The maximum of the population values.
+ Max float64 `protobuf:"fixed64,2,opt,name=max" json:"max,omitempty"`
+}
+
+func (m *Distribution_Range) Reset() { *m = Distribution_Range{} }
+func (m *Distribution_Range) String() string { return proto.CompactTextString(m) }
+func (*Distribution_Range) ProtoMessage() {}
+func (*Distribution_Range) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} }
+
+func (m *Distribution_Range) GetMin() float64 {
+ if m != nil {
+ return m.Min
+ }
+ return 0
+}
+
+func (m *Distribution_Range) GetMax() float64 {
+ if m != nil {
+ return m.Max
+ }
+ return 0
+}
+
+// A Distribution may optionally contain a histogram of the values in the
+// population. The histogram is given in `bucket_counts` as counts of values
+// that fall into one of a sequence of non-overlapping buckets. The sequence
+// of buckets is described by `bucket_options`.
+//
+// A bucket specifies an inclusive lower bound and exclusive upper bound for
+// the values that are counted for that bucket. The upper bound of a bucket
+// is strictly greater than the lower bound.
+//
+// The sequence of N buckets for a Distribution consists of an underflow
+// bucket (number 0), zero or more finite buckets (number 1 through N - 2) and
+// an overflow bucket (number N - 1). The buckets are contiguous: the lower
+// bound of bucket i (i > 0) is the same as the upper bound of bucket i - 1.
+// The buckets span the whole range of finite values: lower bound of the
+// underflow bucket is -infinity and the upper bound of the overflow bucket is
+// +infinity. The finite buckets are so-called because both bounds are
+// finite.
+//
+// `BucketOptions` describes bucket boundaries in one of three ways. Two
+// describe the boundaries by giving parameters for a formula to generate
+// boundaries and one gives the bucket boundaries explicitly.
+//
+// If `bucket_boundaries` is not given, then no `bucket_counts` may be given.
+type Distribution_BucketOptions struct {
+ // Exactly one of these three fields must be set.
+ //
+ // Types that are valid to be assigned to Options:
+ // *Distribution_BucketOptions_LinearBuckets
+ // *Distribution_BucketOptions_ExponentialBuckets
+ // *Distribution_BucketOptions_ExplicitBuckets
+ Options isDistribution_BucketOptions_Options `protobuf_oneof:"options"`
+}
+
+func (m *Distribution_BucketOptions) Reset() { *m = Distribution_BucketOptions{} }
+func (m *Distribution_BucketOptions) String() string { return proto.CompactTextString(m) }
+func (*Distribution_BucketOptions) ProtoMessage() {}
+func (*Distribution_BucketOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 1} }
+
+type isDistribution_BucketOptions_Options interface {
+ isDistribution_BucketOptions_Options()
+}
+
+type Distribution_BucketOptions_LinearBuckets struct {
+ LinearBuckets *Distribution_BucketOptions_Linear `protobuf:"bytes,1,opt,name=linear_buckets,json=linearBuckets,oneof"`
+}
+type Distribution_BucketOptions_ExponentialBuckets struct {
+ ExponentialBuckets *Distribution_BucketOptions_Exponential `protobuf:"bytes,2,opt,name=exponential_buckets,json=exponentialBuckets,oneof"`
+}
+type Distribution_BucketOptions_ExplicitBuckets struct {
+ ExplicitBuckets *Distribution_BucketOptions_Explicit `protobuf:"bytes,3,opt,name=explicit_buckets,json=explicitBuckets,oneof"`
+}
+
+func (*Distribution_BucketOptions_LinearBuckets) isDistribution_BucketOptions_Options() {}
+func (*Distribution_BucketOptions_ExponentialBuckets) isDistribution_BucketOptions_Options() {}
+func (*Distribution_BucketOptions_ExplicitBuckets) isDistribution_BucketOptions_Options() {}
+
+func (m *Distribution_BucketOptions) GetOptions() isDistribution_BucketOptions_Options {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *Distribution_BucketOptions) GetLinearBuckets() *Distribution_BucketOptions_Linear {
+ if x, ok := m.GetOptions().(*Distribution_BucketOptions_LinearBuckets); ok {
+ return x.LinearBuckets
+ }
+ return nil
+}
+
+func (m *Distribution_BucketOptions) GetExponentialBuckets() *Distribution_BucketOptions_Exponential {
+ if x, ok := m.GetOptions().(*Distribution_BucketOptions_ExponentialBuckets); ok {
+ return x.ExponentialBuckets
+ }
+ return nil
+}
+
+func (m *Distribution_BucketOptions) GetExplicitBuckets() *Distribution_BucketOptions_Explicit {
+ if x, ok := m.GetOptions().(*Distribution_BucketOptions_ExplicitBuckets); ok {
+ return x.ExplicitBuckets
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Distribution_BucketOptions) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Distribution_BucketOptions_OneofMarshaler, _Distribution_BucketOptions_OneofUnmarshaler, _Distribution_BucketOptions_OneofSizer, []interface{}{
+ (*Distribution_BucketOptions_LinearBuckets)(nil),
+ (*Distribution_BucketOptions_ExponentialBuckets)(nil),
+ (*Distribution_BucketOptions_ExplicitBuckets)(nil),
+ }
+}
+
+func _Distribution_BucketOptions_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Distribution_BucketOptions)
+ // options
+ switch x := m.Options.(type) {
+ case *Distribution_BucketOptions_LinearBuckets:
+ b.EncodeVarint(1<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.LinearBuckets); err != nil {
+ return err
+ }
+ case *Distribution_BucketOptions_ExponentialBuckets:
+ b.EncodeVarint(2<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.ExponentialBuckets); err != nil {
+ return err
+ }
+ case *Distribution_BucketOptions_ExplicitBuckets:
+ b.EncodeVarint(3<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.ExplicitBuckets); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("Distribution_BucketOptions.Options has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Distribution_BucketOptions_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Distribution_BucketOptions)
+ switch tag {
+ case 1: // options.linear_buckets
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Distribution_BucketOptions_Linear)
+ err := b.DecodeMessage(msg)
+ m.Options = &Distribution_BucketOptions_LinearBuckets{msg}
+ return true, err
+ case 2: // options.exponential_buckets
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Distribution_BucketOptions_Exponential)
+ err := b.DecodeMessage(msg)
+ m.Options = &Distribution_BucketOptions_ExponentialBuckets{msg}
+ return true, err
+ case 3: // options.explicit_buckets
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Distribution_BucketOptions_Explicit)
+ err := b.DecodeMessage(msg)
+ m.Options = &Distribution_BucketOptions_ExplicitBuckets{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Distribution_BucketOptions_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Distribution_BucketOptions)
+ // options
+ switch x := m.Options.(type) {
+ case *Distribution_BucketOptions_LinearBuckets:
+ s := proto.Size(x.LinearBuckets)
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Distribution_BucketOptions_ExponentialBuckets:
+ s := proto.Size(x.ExponentialBuckets)
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Distribution_BucketOptions_ExplicitBuckets:
+ s := proto.Size(x.ExplicitBuckets)
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// Specify a sequence of buckets that all have the same width (except
+// overflow and underflow). Each bucket represents a constant absolute
+// uncertainty on the specific value in the bucket.
+//
+// Defines `num_finite_buckets + 2` (= N) buckets with these boundaries for
+// bucket `i`:
+//
+// Upper bound (0 <= i < N-1): offset + (width * i).
+// Lower bound (1 <= i < N): offset + (width * (i - 1)).
+type Distribution_BucketOptions_Linear struct {
+ // Must be greater than 0.
+ NumFiniteBuckets int32 `protobuf:"varint,1,opt,name=num_finite_buckets,json=numFiniteBuckets" json:"num_finite_buckets,omitempty"`
+ // Must be greater than 0.
+ Width float64 `protobuf:"fixed64,2,opt,name=width" json:"width,omitempty"`
+ // Lower bound of the first bucket.
+ Offset float64 `protobuf:"fixed64,3,opt,name=offset" json:"offset,omitempty"`
+}
+
+func (m *Distribution_BucketOptions_Linear) Reset() { *m = Distribution_BucketOptions_Linear{} }
+func (m *Distribution_BucketOptions_Linear) String() string { return proto.CompactTextString(m) }
+func (*Distribution_BucketOptions_Linear) ProtoMessage() {}
+func (*Distribution_BucketOptions_Linear) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{0, 1, 0}
+}
+
+func (m *Distribution_BucketOptions_Linear) GetNumFiniteBuckets() int32 {
+ if m != nil {
+ return m.NumFiniteBuckets
+ }
+ return 0
+}
+
+func (m *Distribution_BucketOptions_Linear) GetWidth() float64 {
+ if m != nil {
+ return m.Width
+ }
+ return 0
+}
+
+func (m *Distribution_BucketOptions_Linear) GetOffset() float64 {
+ if m != nil {
+ return m.Offset
+ }
+ return 0
+}
+
+// Specify a sequence of buckets that have a width that is proportional to
+// the value of the lower bound. Each bucket represents a constant relative
+// uncertainty on a specific value in the bucket.
+//
+// Defines `num_finite_buckets + 2` (= N) buckets with these boundaries for
+// bucket i:
+//
+// Upper bound (0 <= i < N-1): scale * (growth_factor ^ i).
+// Lower bound (1 <= i < N): scale * (growth_factor ^ (i - 1)).
+type Distribution_BucketOptions_Exponential struct {
+ // Must be greater than 0.
+ NumFiniteBuckets int32 `protobuf:"varint,1,opt,name=num_finite_buckets,json=numFiniteBuckets" json:"num_finite_buckets,omitempty"`
+ // Must be greater than 1.
+ GrowthFactor float64 `protobuf:"fixed64,2,opt,name=growth_factor,json=growthFactor" json:"growth_factor,omitempty"`
+ // Must be greater than 0.
+ Scale float64 `protobuf:"fixed64,3,opt,name=scale" json:"scale,omitempty"`
+}
+
+func (m *Distribution_BucketOptions_Exponential) Reset() {
+ *m = Distribution_BucketOptions_Exponential{}
+}
+func (m *Distribution_BucketOptions_Exponential) String() string { return proto.CompactTextString(m) }
+func (*Distribution_BucketOptions_Exponential) ProtoMessage() {}
+func (*Distribution_BucketOptions_Exponential) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{0, 1, 1}
+}
+
+func (m *Distribution_BucketOptions_Exponential) GetNumFiniteBuckets() int32 {
+ if m != nil {
+ return m.NumFiniteBuckets
+ }
+ return 0
+}
+
+func (m *Distribution_BucketOptions_Exponential) GetGrowthFactor() float64 {
+ if m != nil {
+ return m.GrowthFactor
+ }
+ return 0
+}
+
+func (m *Distribution_BucketOptions_Exponential) GetScale() float64 {
+ if m != nil {
+ return m.Scale
+ }
+ return 0
+}
+
+// A set of buckets with arbitrary widths.
+//
+// Defines `size(bounds) + 1` (= N) buckets with these boundaries for
+// bucket i:
+//
+// Upper bound (0 <= i < N-1): bounds[i]
+// Lower bound (1 <= i < N); bounds[i - 1]
+//
+// There must be at least one element in `bounds`. If `bounds` has only one
+// element, there are no finite buckets, and that single element is the
+// common boundary of the overflow and underflow buckets.
+type Distribution_BucketOptions_Explicit struct {
+ // The values must be monotonically increasing.
+ Bounds []float64 `protobuf:"fixed64,1,rep,packed,name=bounds" json:"bounds,omitempty"`
+}
+
+func (m *Distribution_BucketOptions_Explicit) Reset() { *m = Distribution_BucketOptions_Explicit{} }
+func (m *Distribution_BucketOptions_Explicit) String() string { return proto.CompactTextString(m) }
+func (*Distribution_BucketOptions_Explicit) ProtoMessage() {}
+func (*Distribution_BucketOptions_Explicit) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{0, 1, 2}
+}
+
+func (m *Distribution_BucketOptions_Explicit) GetBounds() []float64 {
+ if m != nil {
+ return m.Bounds
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Distribution)(nil), "google.api.Distribution")
+ proto.RegisterType((*Distribution_Range)(nil), "google.api.Distribution.Range")
+ proto.RegisterType((*Distribution_BucketOptions)(nil), "google.api.Distribution.BucketOptions")
+ proto.RegisterType((*Distribution_BucketOptions_Linear)(nil), "google.api.Distribution.BucketOptions.Linear")
+ proto.RegisterType((*Distribution_BucketOptions_Exponential)(nil), "google.api.Distribution.BucketOptions.Exponential")
+ proto.RegisterType((*Distribution_BucketOptions_Explicit)(nil), "google.api.Distribution.BucketOptions.Explicit")
+}
+
+func init() { proto.RegisterFile("google/api/distribution.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 544 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x5d, 0x6f, 0xd3, 0x30,
+ 0x14, 0x5d, 0x96, 0xb5, 0x85, 0xdb, 0x0f, 0x8a, 0x19, 0x28, 0x44, 0x7c, 0x54, 0x9b, 0x84, 0x2a,
+ 0x01, 0x89, 0x54, 0x90, 0x78, 0xe0, 0xad, 0x1b, 0x53, 0x1f, 0x40, 0x9b, 0x8c, 0xc4, 0x03, 0x42,
+ 0x8a, 0x9c, 0xc4, 0xc9, 0x0c, 0x89, 0x1d, 0x62, 0x67, 0x2b, 0xef, 0xfc, 0x29, 0xfe, 0x1d, 0x8a,
+ 0xed, 0x6e, 0x19, 0x08, 0xa9, 0xbc, 0xf9, 0xde, 0x73, 0x7c, 0xce, 0xb9, 0x57, 0x71, 0xe0, 0x71,
+ 0x2e, 0x44, 0x5e, 0xd0, 0x90, 0x54, 0x2c, 0x4c, 0x99, 0x54, 0x35, 0x8b, 0x1b, 0xc5, 0x04, 0x0f,
+ 0xaa, 0x5a, 0x28, 0x81, 0xc0, 0xc0, 0x01, 0xa9, 0x98, 0xff, 0xa8, 0x43, 0x25, 0x9c, 0x0b, 0x45,
+ 0x5a, 0xa2, 0x34, 0x4c, 0xff, 0xa1, 0x45, 0x75, 0x15, 0x37, 0x59, 0x48, 0xf8, 0x0f, 0x0b, 0x3d,
+ 0xfd, 0x13, 0x52, 0xac, 0xa4, 0x52, 0x91, 0xb2, 0x32, 0x84, 0x83, 0x9f, 0x03, 0x18, 0x1d, 0x77,
+ 0xcc, 0xd1, 0x3e, 0xf4, 0x12, 0xd1, 0x70, 0xe5, 0x39, 0x33, 0x67, 0xee, 0x62, 0x53, 0x20, 0x04,
+ 0x7b, 0x25, 0x25, 0xdc, 0xdb, 0x9d, 0x39, 0x73, 0x07, 0xeb, 0x33, 0x7a, 0x03, 0x9e, 0x6c, 0xca,
+ 0x48, 0x64, 0x91, 0xfc, 0xde, 0x90, 0x9a, 0xa6, 0x51, 0x4a, 0x2f, 0x98, 0x4e, 0xe6, 0xb9, 0x9a,
+ 0x77, 0x5f, 0x36, 0xe5, 0x69, 0xf6, 0xd1, 0xa0, 0xc7, 0x1b, 0x10, 0xbd, 0x86, 0x5e, 0x4d, 0x78,
+ 0x4e, 0xbd, 0xbd, 0x99, 0x33, 0x1f, 0x2e, 0x9e, 0x04, 0xd7, 0x93, 0x06, 0xdd, 0x2c, 0x01, 0x6e,
+ 0x59, 0xd8, 0x90, 0xd1, 0x07, 0x98, 0xc4, 0x4d, 0xf2, 0x8d, 0xaa, 0x48, 0x54, 0x7a, 0x7a, 0xaf,
+ 0xaf, 0xaf, 0x3f, 0xfb, 0xe7, 0xf5, 0xa5, 0xa6, 0x9f, 0x1a, 0x36, 0x1e, 0xc7, 0xdd, 0x12, 0x1d,
+ 0x82, 0x6d, 0x44, 0x7a, 0x42, 0xe9, 0x0d, 0x66, 0xee, 0xdc, 0xc5, 0x23, 0xd3, 0x3c, 0xd2, 0x3d,
+ 0xff, 0x39, 0xf4, 0x74, 0x06, 0x34, 0x05, 0xb7, 0x64, 0x5c, 0xef, 0xc4, 0xc1, 0xed, 0x51, 0x77,
+ 0xc8, 0xda, 0x2e, 0xa4, 0x3d, 0xfa, 0xbf, 0xf6, 0x60, 0x7c, 0xc3, 0x12, 0x7d, 0x82, 0x49, 0xc1,
+ 0x38, 0x25, 0x75, 0x64, 0x54, 0xa5, 0x16, 0x18, 0x2e, 0x5e, 0x6e, 0x17, 0x39, 0x78, 0xaf, 0x2f,
+ 0xaf, 0x76, 0xf0, 0xd8, 0xc8, 0x18, 0x54, 0x22, 0x0a, 0xf7, 0xe8, 0xba, 0x12, 0x9c, 0x72, 0xc5,
+ 0x48, 0x71, 0x25, 0xbe, 0xab, 0xc5, 0x17, 0x5b, 0x8a, 0xbf, 0xbb, 0x56, 0x58, 0xed, 0x60, 0xd4,
+ 0x11, 0xdc, 0xd8, 0x7c, 0x81, 0x29, 0x5d, 0x57, 0x05, 0x4b, 0x98, 0xba, 0xf2, 0x70, 0xb5, 0x47,
+ 0xb8, 0xbd, 0x87, 0xbe, 0xbe, 0xda, 0xc1, 0x77, 0x36, 0x52, 0x56, 0xdd, 0x4f, 0xa1, 0x6f, 0xe6,
+ 0x43, 0x2f, 0x00, 0xf1, 0xa6, 0x8c, 0x32, 0xc6, 0x99, 0xa2, 0x37, 0x56, 0xd5, 0xc3, 0x53, 0xde,
+ 0x94, 0x27, 0x1a, 0xd8, 0xa4, 0xda, 0x87, 0xde, 0x25, 0x4b, 0xd5, 0xb9, 0x5d, 0xbd, 0x29, 0xd0,
+ 0x03, 0xe8, 0x8b, 0x2c, 0x93, 0x54, 0xd9, 0x4f, 0xcf, 0x56, 0xfe, 0x05, 0x0c, 0x3b, 0x83, 0xfe,
+ 0xa7, 0xd5, 0x21, 0x8c, 0xf3, 0x5a, 0x5c, 0xaa, 0xf3, 0x28, 0x23, 0x89, 0x12, 0xb5, 0xb5, 0x1c,
+ 0x99, 0xe6, 0x89, 0xee, 0xb5, 0x79, 0x64, 0x42, 0x0a, 0x6a, 0x8d, 0x4d, 0xe1, 0x1f, 0xc0, 0xad,
+ 0xcd, 0xf0, 0x6d, 0xb6, 0x58, 0x34, 0x3c, 0x6d, 0x8d, 0xdc, 0x36, 0x9b, 0xa9, 0x96, 0xb7, 0x61,
+ 0x60, 0x3f, 0xe5, 0xe5, 0x57, 0x98, 0x24, 0xa2, 0xec, 0x6c, 0x75, 0x79, 0xb7, 0xbb, 0xd6, 0xb3,
+ 0xf6, 0xad, 0x9e, 0x39, 0x9f, 0x8f, 0x2c, 0x21, 0x17, 0x05, 0xe1, 0x79, 0x20, 0xea, 0x3c, 0xcc,
+ 0x29, 0xd7, 0x2f, 0x39, 0x34, 0x10, 0xa9, 0x98, 0xfc, 0xeb, 0x8f, 0xf2, 0xb6, 0x5b, 0xc4, 0x7d,
+ 0xcd, 0x7f, 0xf5, 0x3b, 0x00, 0x00, 0xff, 0xff, 0x88, 0x8e, 0xc5, 0x4b, 0x80, 0x04, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/api/label/label.pb.go b/vendor/google.golang.org/genproto/googleapis/api/label/label.pb.go
new file mode 100644
index 0000000..d0327ab
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/api/label/label.pb.go
@@ -0,0 +1,120 @@
+// Code generated by protoc-gen-go.
+// source: google/api/label.proto
+// DO NOT EDIT!
+
+/*
+Package label is a generated protocol buffer package.
+
+It is generated from these files:
+ google/api/label.proto
+
+It has these top-level messages:
+ LabelDescriptor
+*/
+package label
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// Value types that can be used as label values.
+type LabelDescriptor_ValueType int32
+
+const (
+ // A variable-length string. This is the default.
+ LabelDescriptor_STRING LabelDescriptor_ValueType = 0
+ // Boolean; true or false.
+ LabelDescriptor_BOOL LabelDescriptor_ValueType = 1
+ // A 64-bit signed integer.
+ LabelDescriptor_INT64 LabelDescriptor_ValueType = 2
+)
+
+var LabelDescriptor_ValueType_name = map[int32]string{
+ 0: "STRING",
+ 1: "BOOL",
+ 2: "INT64",
+}
+var LabelDescriptor_ValueType_value = map[string]int32{
+ "STRING": 0,
+ "BOOL": 1,
+ "INT64": 2,
+}
+
+func (x LabelDescriptor_ValueType) String() string {
+ return proto.EnumName(LabelDescriptor_ValueType_name, int32(x))
+}
+func (LabelDescriptor_ValueType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} }
+
+// A description of a label.
+type LabelDescriptor struct {
+ // The label key.
+ Key string `protobuf:"bytes,1,opt,name=key" json:"key,omitempty"`
+ // The type of data that can be assigned to the label.
+ ValueType LabelDescriptor_ValueType `protobuf:"varint,2,opt,name=value_type,json=valueType,enum=google.api.LabelDescriptor_ValueType" json:"value_type,omitempty"`
+ // A human-readable description for the label.
+ Description string `protobuf:"bytes,3,opt,name=description" json:"description,omitempty"`
+}
+
+func (m *LabelDescriptor) Reset() { *m = LabelDescriptor{} }
+func (m *LabelDescriptor) String() string { return proto.CompactTextString(m) }
+func (*LabelDescriptor) ProtoMessage() {}
+func (*LabelDescriptor) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *LabelDescriptor) GetKey() string {
+ if m != nil {
+ return m.Key
+ }
+ return ""
+}
+
+func (m *LabelDescriptor) GetValueType() LabelDescriptor_ValueType {
+ if m != nil {
+ return m.ValueType
+ }
+ return LabelDescriptor_STRING
+}
+
+func (m *LabelDescriptor) GetDescription() string {
+ if m != nil {
+ return m.Description
+ }
+ return ""
+}
+
+func init() {
+ proto.RegisterType((*LabelDescriptor)(nil), "google.api.LabelDescriptor")
+ proto.RegisterEnum("google.api.LabelDescriptor_ValueType", LabelDescriptor_ValueType_name, LabelDescriptor_ValueType_value)
+}
+
+func init() { proto.RegisterFile("google/api/label.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 252 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4b, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0xd5, 0x4f, 0x2c, 0xc8, 0xd4, 0xcf, 0x49, 0x4c, 0x4a, 0xcd, 0xd1, 0x2b, 0x28, 0xca,
+ 0x2f, 0xc9, 0x17, 0xe2, 0x82, 0x88, 0xeb, 0x25, 0x16, 0x64, 0x2a, 0xed, 0x64, 0xe4, 0xe2, 0xf7,
+ 0x01, 0xc9, 0xb9, 0xa4, 0x16, 0x27, 0x17, 0x65, 0x16, 0x94, 0xe4, 0x17, 0x09, 0x09, 0x70, 0x31,
+ 0x67, 0xa7, 0x56, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x06, 0x81, 0x98, 0x42, 0x2e, 0x5c, 0x5c,
+ 0x65, 0x89, 0x39, 0xa5, 0xa9, 0xf1, 0x25, 0x95, 0x05, 0xa9, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0x7c,
+ 0x46, 0xaa, 0x7a, 0x08, 0x63, 0xf4, 0xd0, 0x8c, 0xd0, 0x0b, 0x03, 0xa9, 0x0e, 0xa9, 0x2c, 0x48,
+ 0x0d, 0xe2, 0x2c, 0x83, 0x31, 0x85, 0x14, 0xb8, 0xb8, 0x53, 0xa0, 0x4a, 0x32, 0xf3, 0xf3, 0x24,
+ 0x98, 0xc1, 0xe6, 0x23, 0x0b, 0x29, 0xe9, 0x70, 0x71, 0xc2, 0x75, 0x0a, 0x71, 0x71, 0xb1, 0x05,
+ 0x87, 0x04, 0x79, 0xfa, 0xb9, 0x0b, 0x30, 0x08, 0x71, 0x70, 0xb1, 0x38, 0xf9, 0xfb, 0xfb, 0x08,
+ 0x30, 0x0a, 0x71, 0x72, 0xb1, 0x7a, 0xfa, 0x85, 0x98, 0x99, 0x08, 0x30, 0x39, 0xc5, 0x73, 0xf1,
+ 0x25, 0xe7, 0xe7, 0x22, 0x39, 0xc3, 0x89, 0x0b, 0xec, 0x8e, 0x00, 0x90, 0x2f, 0x03, 0x18, 0xa3,
+ 0x4c, 0xa1, 0x32, 0xe9, 0xf9, 0x39, 0x89, 0x79, 0xe9, 0x7a, 0xf9, 0x45, 0xe9, 0xfa, 0xe9, 0xa9,
+ 0x79, 0xe0, 0x30, 0xd0, 0x87, 0x48, 0x25, 0x16, 0x64, 0x16, 0x23, 0x82, 0xc7, 0x1a, 0x4c, 0xfe,
+ 0x60, 0x64, 0x5c, 0xc4, 0xc4, 0xe2, 0xee, 0x18, 0xe0, 0x99, 0xc4, 0x06, 0x56, 0x6b, 0x0c, 0x08,
+ 0x00, 0x00, 0xff, 0xff, 0x57, 0x04, 0xaa, 0x1f, 0x49, 0x01, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/api/metric/metric.pb.go b/vendor/google.golang.org/genproto/googleapis/api/metric/metric.pb.go
new file mode 100644
index 0000000..738ff43
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/api/metric/metric.pb.go
@@ -0,0 +1,359 @@
+// Code generated by protoc-gen-go.
+// source: google/api/metric.proto
+// DO NOT EDIT!
+
+/*
+Package metric is a generated protocol buffer package.
+
+It is generated from these files:
+ google/api/metric.proto
+
+It has these top-level messages:
+ MetricDescriptor
+ Metric
+*/
+package metric
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_api "google.golang.org/genproto/googleapis/api/label"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// The kind of measurement. It describes how the data is reported.
+type MetricDescriptor_MetricKind int32
+
+const (
+ // Do not use this default value.
+ MetricDescriptor_METRIC_KIND_UNSPECIFIED MetricDescriptor_MetricKind = 0
+ // An instantaneous measurement of a value.
+ MetricDescriptor_GAUGE MetricDescriptor_MetricKind = 1
+ // The change in a value during a time interval.
+ MetricDescriptor_DELTA MetricDescriptor_MetricKind = 2
+ // A value accumulated over a time interval. Cumulative
+ // measurements in a time series should have the same start time
+ // and increasing end times, until an event resets the cumulative
+ // value to zero and sets a new start time for the following
+ // points.
+ MetricDescriptor_CUMULATIVE MetricDescriptor_MetricKind = 3
+)
+
+var MetricDescriptor_MetricKind_name = map[int32]string{
+ 0: "METRIC_KIND_UNSPECIFIED",
+ 1: "GAUGE",
+ 2: "DELTA",
+ 3: "CUMULATIVE",
+}
+var MetricDescriptor_MetricKind_value = map[string]int32{
+ "METRIC_KIND_UNSPECIFIED": 0,
+ "GAUGE": 1,
+ "DELTA": 2,
+ "CUMULATIVE": 3,
+}
+
+func (x MetricDescriptor_MetricKind) String() string {
+ return proto.EnumName(MetricDescriptor_MetricKind_name, int32(x))
+}
+func (MetricDescriptor_MetricKind) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{0, 0}
+}
+
+// The value type of a metric.
+type MetricDescriptor_ValueType int32
+
+const (
+ // Do not use this default value.
+ MetricDescriptor_VALUE_TYPE_UNSPECIFIED MetricDescriptor_ValueType = 0
+ // The value is a boolean.
+ // This value type can be used only if the metric kind is `GAUGE`.
+ MetricDescriptor_BOOL MetricDescriptor_ValueType = 1
+ // The value is a signed 64-bit integer.
+ MetricDescriptor_INT64 MetricDescriptor_ValueType = 2
+ // The value is a double precision floating point number.
+ MetricDescriptor_DOUBLE MetricDescriptor_ValueType = 3
+ // The value is a text string.
+ // This value type can be used only if the metric kind is `GAUGE`.
+ MetricDescriptor_STRING MetricDescriptor_ValueType = 4
+ // The value is a [`Distribution`][google.api.Distribution].
+ MetricDescriptor_DISTRIBUTION MetricDescriptor_ValueType = 5
+ // The value is money.
+ MetricDescriptor_MONEY MetricDescriptor_ValueType = 6
+)
+
+var MetricDescriptor_ValueType_name = map[int32]string{
+ 0: "VALUE_TYPE_UNSPECIFIED",
+ 1: "BOOL",
+ 2: "INT64",
+ 3: "DOUBLE",
+ 4: "STRING",
+ 5: "DISTRIBUTION",
+ 6: "MONEY",
+}
+var MetricDescriptor_ValueType_value = map[string]int32{
+ "VALUE_TYPE_UNSPECIFIED": 0,
+ "BOOL": 1,
+ "INT64": 2,
+ "DOUBLE": 3,
+ "STRING": 4,
+ "DISTRIBUTION": 5,
+ "MONEY": 6,
+}
+
+func (x MetricDescriptor_ValueType) String() string {
+ return proto.EnumName(MetricDescriptor_ValueType_name, int32(x))
+}
+func (MetricDescriptor_ValueType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{0, 1}
+}
+
+// Defines a metric type and its schema. Once a metric descriptor is created,
+// deleting or altering it stops data collection and makes the metric type's
+// existing data unusable.
+type MetricDescriptor struct {
+ // The resource name of the metric descriptor. Depending on the
+ // implementation, the name typically includes: (1) the parent resource name
+ // that defines the scope of the metric type or of its data; and (2) the
+ // metric's URL-encoded type, which also appears in the `type` field of this
+ // descriptor. For example, following is the resource name of a custom
+ // metric within the GCP project `my-project-id`:
+ //
+ // "projects/my-project-id/metricDescriptors/custom.googleapis.com%2Finvoice%2Fpaid%2Famount"
+ Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ // The metric type, including its DNS name prefix. The type is not
+ // URL-encoded. All user-defined custom metric types have the DNS name
+ // `custom.googleapis.com`. Metric types should use a natural hierarchical
+ // grouping. For example:
+ //
+ // "custom.googleapis.com/invoice/paid/amount"
+ // "appengine.googleapis.com/http/server/response_latencies"
+ Type string `protobuf:"bytes,8,opt,name=type" json:"type,omitempty"`
+ // The set of labels that can be used to describe a specific
+ // instance of this metric type. For example, the
+ // `appengine.googleapis.com/http/server/response_latencies` metric
+ // type has a label for the HTTP response code, `response_code`, so
+ // you can look at latencies for successful responses or just
+ // for responses that failed.
+ Labels []*google_api.LabelDescriptor `protobuf:"bytes,2,rep,name=labels" json:"labels,omitempty"`
+ // Whether the metric records instantaneous values, changes to a value, etc.
+ // Some combinations of `metric_kind` and `value_type` might not be supported.
+ MetricKind MetricDescriptor_MetricKind `protobuf:"varint,3,opt,name=metric_kind,json=metricKind,enum=google.api.MetricDescriptor_MetricKind" json:"metric_kind,omitempty"`
+ // Whether the measurement is an integer, a floating-point number, etc.
+ // Some combinations of `metric_kind` and `value_type` might not be supported.
+ ValueType MetricDescriptor_ValueType `protobuf:"varint,4,opt,name=value_type,json=valueType,enum=google.api.MetricDescriptor_ValueType" json:"value_type,omitempty"`
+ // The unit in which the metric value is reported. It is only applicable
+ // if the `value_type` is `INT64`, `DOUBLE`, or `DISTRIBUTION`. The
+ // supported units are a subset of [The Unified Code for Units of
+ // Measure](http://unitsofmeasure.org/ucum.html) standard:
+ //
+ // **Basic units (UNIT)**
+ //
+ // * `bit` bit
+ // * `By` byte
+ // * `s` second
+ // * `min` minute
+ // * `h` hour
+ // * `d` day
+ //
+ // **Prefixes (PREFIX)**
+ //
+ // * `k` kilo (10**3)
+ // * `M` mega (10**6)
+ // * `G` giga (10**9)
+ // * `T` tera (10**12)
+ // * `P` peta (10**15)
+ // * `E` exa (10**18)
+ // * `Z` zetta (10**21)
+ // * `Y` yotta (10**24)
+ // * `m` milli (10**-3)
+ // * `u` micro (10**-6)
+ // * `n` nano (10**-9)
+ // * `p` pico (10**-12)
+ // * `f` femto (10**-15)
+ // * `a` atto (10**-18)
+ // * `z` zepto (10**-21)
+ // * `y` yocto (10**-24)
+ // * `Ki` kibi (2**10)
+ // * `Mi` mebi (2**20)
+ // * `Gi` gibi (2**30)
+ // * `Ti` tebi (2**40)
+ //
+ // **Grammar**
+ //
+ // The grammar includes the dimensionless unit `1`, such as `1/s`.
+ //
+ // The grammar also includes these connectors:
+ //
+ // * `/` division (as an infix operator, e.g. `1/s`).
+ // * `.` multiplication (as an infix operator, e.g. `GBy.d`)
+ //
+ // The grammar for a unit is as follows:
+ //
+ // Expression = Component { "." Component } { "/" Component } ;
+ //
+ // Component = [ PREFIX ] UNIT [ Annotation ]
+ // | Annotation
+ // | "1"
+ // ;
+ //
+ // Annotation = "{" NAME "}" ;
+ //
+ // Notes:
+ //
+ // * `Annotation` is just a comment if it follows a `UNIT` and is
+ // equivalent to `1` if it is used alone. For examples,
+ // `{requests}/s == 1/s`, `By{transmitted}/s == By/s`.
+ // * `NAME` is a sequence of non-blank printable ASCII characters not
+ // containing '{' or '}'.
+ Unit string `protobuf:"bytes,5,opt,name=unit" json:"unit,omitempty"`
+ // A detailed description of the metric, which can be used in documentation.
+ Description string `protobuf:"bytes,6,opt,name=description" json:"description,omitempty"`
+ // A concise name for the metric, which can be displayed in user interfaces.
+ // Use sentence case without an ending period, for example "Request count".
+ DisplayName string `protobuf:"bytes,7,opt,name=display_name,json=displayName" json:"display_name,omitempty"`
+}
+
+func (m *MetricDescriptor) Reset() { *m = MetricDescriptor{} }
+func (m *MetricDescriptor) String() string { return proto.CompactTextString(m) }
+func (*MetricDescriptor) ProtoMessage() {}
+func (*MetricDescriptor) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *MetricDescriptor) GetName() string {
+ if m != nil {
+ return m.Name
+ }
+ return ""
+}
+
+func (m *MetricDescriptor) GetType() string {
+ if m != nil {
+ return m.Type
+ }
+ return ""
+}
+
+func (m *MetricDescriptor) GetLabels() []*google_api.LabelDescriptor {
+ if m != nil {
+ return m.Labels
+ }
+ return nil
+}
+
+func (m *MetricDescriptor) GetMetricKind() MetricDescriptor_MetricKind {
+ if m != nil {
+ return m.MetricKind
+ }
+ return MetricDescriptor_METRIC_KIND_UNSPECIFIED
+}
+
+func (m *MetricDescriptor) GetValueType() MetricDescriptor_ValueType {
+ if m != nil {
+ return m.ValueType
+ }
+ return MetricDescriptor_VALUE_TYPE_UNSPECIFIED
+}
+
+func (m *MetricDescriptor) GetUnit() string {
+ if m != nil {
+ return m.Unit
+ }
+ return ""
+}
+
+func (m *MetricDescriptor) GetDescription() string {
+ if m != nil {
+ return m.Description
+ }
+ return ""
+}
+
+func (m *MetricDescriptor) GetDisplayName() string {
+ if m != nil {
+ return m.DisplayName
+ }
+ return ""
+}
+
+// A specific metric, identified by specifying values for all of the
+// labels of a [`MetricDescriptor`][google.api.MetricDescriptor].
+type Metric struct {
+ // An existing metric type, see [google.api.MetricDescriptor][google.api.MetricDescriptor].
+ // For example, `custom.googleapis.com/invoice/paid/amount`.
+ Type string `protobuf:"bytes,3,opt,name=type" json:"type,omitempty"`
+ // The set of label values that uniquely identify this metric. All
+ // labels listed in the `MetricDescriptor` must be assigned values.
+ Labels map[string]string `protobuf:"bytes,2,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+}
+
+func (m *Metric) Reset() { *m = Metric{} }
+func (m *Metric) String() string { return proto.CompactTextString(m) }
+func (*Metric) ProtoMessage() {}
+func (*Metric) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *Metric) GetType() string {
+ if m != nil {
+ return m.Type
+ }
+ return ""
+}
+
+func (m *Metric) GetLabels() map[string]string {
+ if m != nil {
+ return m.Labels
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*MetricDescriptor)(nil), "google.api.MetricDescriptor")
+ proto.RegisterType((*Metric)(nil), "google.api.Metric")
+ proto.RegisterEnum("google.api.MetricDescriptor_MetricKind", MetricDescriptor_MetricKind_name, MetricDescriptor_MetricKind_value)
+ proto.RegisterEnum("google.api.MetricDescriptor_ValueType", MetricDescriptor_ValueType_name, MetricDescriptor_ValueType_value)
+}
+
+func init() { proto.RegisterFile("google/api/metric.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 506 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x53, 0x4d, 0x6f, 0xda, 0x40,
+ 0x10, 0xad, 0x3f, 0x70, 0xc3, 0x10, 0xa1, 0xd5, 0xaa, 0x4a, 0x2c, 0x22, 0x55, 0x94, 0x43, 0xcb,
+ 0x09, 0xa4, 0xa4, 0x4a, 0xbf, 0x4e, 0x80, 0xb7, 0xd4, 0x8a, 0xb1, 0x91, 0x63, 0x23, 0xa5, 0x17,
+ 0xcb, 0x81, 0x95, 0x65, 0xc5, 0xd8, 0xae, 0x71, 0x22, 0xf9, 0x57, 0xf4, 0x17, 0xf4, 0xd2, 0x5f,
+ 0x5a, 0xed, 0xae, 0x03, 0x16, 0x95, 0x72, 0xe2, 0xed, 0x9b, 0x37, 0x6f, 0x67, 0x96, 0x67, 0x38,
+ 0x8f, 0xb2, 0x2c, 0x4a, 0xe8, 0x38, 0xcc, 0xe3, 0xf1, 0x96, 0x96, 0x45, 0xbc, 0x1e, 0xe5, 0x45,
+ 0x56, 0x66, 0x18, 0x44, 0x61, 0x14, 0xe6, 0x71, 0xef, 0xac, 0x21, 0x4a, 0xc2, 0x7b, 0x9a, 0x08,
+ 0xcd, 0xe0, 0x8f, 0x0a, 0x68, 0xc1, 0x9b, 0x0c, 0xba, 0x5b, 0x17, 0x71, 0x5e, 0x66, 0x05, 0xc6,
+ 0xa0, 0xa6, 0xe1, 0x96, 0xea, 0x52, 0x5f, 0x1a, 0xb6, 0x5d, 0x8e, 0x19, 0x57, 0x56, 0x39, 0xd5,
+ 0x4f, 0x04, 0xc7, 0x30, 0xbe, 0x02, 0x8d, 0x7b, 0xed, 0x74, 0xb9, 0xaf, 0x0c, 0x3b, 0x97, 0x17,
+ 0xa3, 0xc3, 0x8d, 0x23, 0x8b, 0x55, 0x0e, 0xa6, 0x6e, 0x2d, 0xc5, 0x3f, 0xa0, 0x23, 0xa6, 0x0c,
+ 0x1e, 0xe2, 0x74, 0xa3, 0x2b, 0x7d, 0x69, 0xd8, 0xbd, 0xfc, 0xd0, 0xec, 0x3c, 0x9e, 0xa7, 0x26,
+ 0x6e, 0xe2, 0x74, 0xe3, 0xc2, 0x76, 0x8f, 0x31, 0x01, 0x78, 0x0a, 0x93, 0x47, 0x1a, 0xf0, 0xc1,
+ 0x54, 0x6e, 0xf4, 0xfe, 0x45, 0xa3, 0x15, 0x93, 0x7b, 0x55, 0x4e, 0xdd, 0xf6, 0xd3, 0x33, 0x64,
+ 0x9b, 0x3d, 0xa6, 0x71, 0xa9, 0xb7, 0xc4, 0x66, 0x0c, 0xe3, 0x3e, 0x74, 0x36, 0x75, 0x5b, 0x9c,
+ 0xa5, 0xba, 0xc6, 0x4b, 0x4d, 0x0a, 0xbf, 0x83, 0xd3, 0x4d, 0xbc, 0xcb, 0x93, 0xb0, 0x0a, 0xf8,
+ 0x5b, 0xbd, 0xae, 0x25, 0x82, 0xb3, 0xc3, 0x2d, 0x1d, 0x38, 0x00, 0x87, 0xc9, 0xf1, 0x05, 0x9c,
+ 0x2f, 0x88, 0xe7, 0x9a, 0xb3, 0xe0, 0xc6, 0xb4, 0x8d, 0xc0, 0xb7, 0x6f, 0x97, 0x64, 0x66, 0x7e,
+ 0x37, 0x89, 0x81, 0x5e, 0xe1, 0x36, 0xb4, 0xe6, 0x13, 0x7f, 0x4e, 0x90, 0xc4, 0xa0, 0x41, 0x2c,
+ 0x6f, 0x82, 0x64, 0xdc, 0x05, 0x98, 0xf9, 0x0b, 0xdf, 0x9a, 0x78, 0xe6, 0x8a, 0x20, 0x65, 0xf0,
+ 0x0b, 0xda, 0xfb, 0x0d, 0x70, 0x0f, 0xce, 0x56, 0x13, 0xcb, 0x27, 0x81, 0x77, 0xb7, 0x24, 0x47,
+ 0x76, 0x27, 0xa0, 0x4e, 0x1d, 0xc7, 0x12, 0x6e, 0xa6, 0xed, 0x5d, 0x7f, 0x44, 0x32, 0x06, 0xd0,
+ 0x0c, 0xc7, 0x9f, 0x5a, 0x04, 0x29, 0x0c, 0xdf, 0x7a, 0xae, 0x69, 0xcf, 0x91, 0x8a, 0x11, 0x9c,
+ 0x1a, 0x26, 0x3b, 0x4d, 0x7d, 0xcf, 0x74, 0x6c, 0xd4, 0x62, 0x4d, 0x0b, 0xc7, 0x26, 0x77, 0x48,
+ 0x1b, 0xfc, 0x96, 0x40, 0x13, 0x4b, 0xec, 0x13, 0xa0, 0x34, 0x12, 0x70, 0x7d, 0x94, 0x80, 0xb7,
+ 0xff, 0x3f, 0xbf, 0x08, 0xc2, 0x8e, 0xa4, 0x65, 0x51, 0x3d, 0x87, 0xa0, 0xf7, 0x05, 0x3a, 0x0d,
+ 0x1a, 0x23, 0x50, 0x1e, 0x68, 0x55, 0xe7, 0x8d, 0x41, 0xfc, 0x06, 0x5a, 0xfc, 0x1f, 0xd2, 0x65,
+ 0xce, 0x89, 0xc3, 0x57, 0xf9, 0xb3, 0x34, 0x0d, 0xa0, 0xbb, 0xce, 0xb6, 0x8d, 0x7b, 0xa6, 0x1d,
+ 0x71, 0xd1, 0x92, 0x05, 0x7a, 0x29, 0xfd, 0xfc, 0x54, 0x97, 0xa2, 0x2c, 0x09, 0xd3, 0x68, 0x94,
+ 0x15, 0xd1, 0x38, 0xa2, 0x29, 0x8f, 0xfb, 0x58, 0x94, 0xc2, 0x3c, 0xde, 0x35, 0x3e, 0x97, 0x6f,
+ 0xe2, 0xe7, 0xaf, 0xac, 0xce, 0x27, 0x4b, 0xf3, 0x5e, 0xe3, 0xd2, 0xab, 0x7f, 0x01, 0x00, 0x00,
+ 0xff, 0xff, 0x18, 0x04, 0x05, 0x82, 0x58, 0x03, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/api/monitoredres/monitored_resource.pb.go b/vendor/google.golang.org/genproto/googleapis/api/monitoredres/monitored_resource.pb.go
new file mode 100644
index 0000000..9ceb24b
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/api/monitoredres/monitored_resource.pb.go
@@ -0,0 +1,181 @@
+// Code generated by protoc-gen-go.
+// source: google/api/monitored_resource.proto
+// DO NOT EDIT!
+
+/*
+Package monitoredres is a generated protocol buffer package.
+
+It is generated from these files:
+ google/api/monitored_resource.proto
+
+It has these top-level messages:
+ MonitoredResourceDescriptor
+ MonitoredResource
+*/
+package monitoredres
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_api "google.golang.org/genproto/googleapis/api/label"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// An object that describes the schema of a [MonitoredResource][google.api.MonitoredResource] object using a
+// type name and a set of labels. For example, the monitored resource
+// descriptor for Google Compute Engine VM instances has a type of
+// `"gce_instance"` and specifies the use of the labels `"instance_id"` and
+// `"zone"` to identify particular VM instances.
+//
+// Different APIs can support different monitored resource types. APIs generally
+// provide a `list` method that returns the monitored resource descriptors used
+// by the API.
+type MonitoredResourceDescriptor struct {
+ // Optional. The resource name of the monitored resource descriptor:
+ // `"projects/{project_id}/monitoredResourceDescriptors/{type}"` where
+ // {type} is the value of the `type` field in this object and
+ // {project_id} is a project ID that provides API-specific context for
+ // accessing the type. APIs that do not use project information can use the
+ // resource name format `"monitoredResourceDescriptors/{type}"`.
+ Name string `protobuf:"bytes,5,opt,name=name" json:"name,omitempty"`
+ // Required. The monitored resource type. For example, the type
+ // `"cloudsql_database"` represents databases in Google Cloud SQL.
+ // The maximum length of this value is 256 characters.
+ Type string `protobuf:"bytes,1,opt,name=type" json:"type,omitempty"`
+ // Optional. A concise name for the monitored resource type that might be
+ // displayed in user interfaces. It should be a Title Cased Noun Phrase,
+ // without any article or other determiners. For example,
+ // `"Google Cloud SQL Database"`.
+ DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName" json:"display_name,omitempty"`
+ // Optional. A detailed description of the monitored resource type that might
+ // be used in documentation.
+ Description string `protobuf:"bytes,3,opt,name=description" json:"description,omitempty"`
+ // Required. A set of labels used to describe instances of this monitored
+ // resource type. For example, an individual Google Cloud SQL database is
+ // identified by values for the labels `"database_id"` and `"zone"`.
+ Labels []*google_api.LabelDescriptor `protobuf:"bytes,4,rep,name=labels" json:"labels,omitempty"`
+}
+
+func (m *MonitoredResourceDescriptor) Reset() { *m = MonitoredResourceDescriptor{} }
+func (m *MonitoredResourceDescriptor) String() string { return proto.CompactTextString(m) }
+func (*MonitoredResourceDescriptor) ProtoMessage() {}
+func (*MonitoredResourceDescriptor) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *MonitoredResourceDescriptor) GetName() string {
+ if m != nil {
+ return m.Name
+ }
+ return ""
+}
+
+func (m *MonitoredResourceDescriptor) GetType() string {
+ if m != nil {
+ return m.Type
+ }
+ return ""
+}
+
+func (m *MonitoredResourceDescriptor) GetDisplayName() string {
+ if m != nil {
+ return m.DisplayName
+ }
+ return ""
+}
+
+func (m *MonitoredResourceDescriptor) GetDescription() string {
+ if m != nil {
+ return m.Description
+ }
+ return ""
+}
+
+func (m *MonitoredResourceDescriptor) GetLabels() []*google_api.LabelDescriptor {
+ if m != nil {
+ return m.Labels
+ }
+ return nil
+}
+
+// An object representing a resource that can be used for monitoring, logging,
+// billing, or other purposes. Examples include virtual machine instances,
+// databases, and storage devices such as disks. The `type` field identifies a
+// [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor] object that describes the resource's
+// schema. Information in the `labels` field identifies the actual resource and
+// its attributes according to the schema. For example, a particular Compute
+// Engine VM instance could be represented by the following object, because the
+// [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor] for `"gce_instance"` has labels
+// `"instance_id"` and `"zone"`:
+//
+// { "type": "gce_instance",
+// "labels": { "instance_id": "12345678901234",
+// "zone": "us-central1-a" }}
+type MonitoredResource struct {
+ // Required. The monitored resource type. This field must match
+ // the `type` field of a [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor] object. For
+ // example, the type of a Cloud SQL database is `"cloudsql_database"`.
+ Type string `protobuf:"bytes,1,opt,name=type" json:"type,omitempty"`
+ // Required. Values for all of the labels listed in the associated monitored
+ // resource descriptor. For example, Cloud SQL databases use the labels
+ // `"database_id"` and `"zone"`.
+ Labels map[string]string `protobuf:"bytes,2,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+}
+
+func (m *MonitoredResource) Reset() { *m = MonitoredResource{} }
+func (m *MonitoredResource) String() string { return proto.CompactTextString(m) }
+func (*MonitoredResource) ProtoMessage() {}
+func (*MonitoredResource) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *MonitoredResource) GetType() string {
+ if m != nil {
+ return m.Type
+ }
+ return ""
+}
+
+func (m *MonitoredResource) GetLabels() map[string]string {
+ if m != nil {
+ return m.Labels
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*MonitoredResourceDescriptor)(nil), "google.api.MonitoredResourceDescriptor")
+ proto.RegisterType((*MonitoredResource)(nil), "google.api.MonitoredResource")
+}
+
+func init() { proto.RegisterFile("google/api/monitored_resource.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 321 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x51, 0x4b, 0x4b, 0x3b, 0x31,
+ 0x10, 0x27, 0xdb, 0x07, 0xfc, 0x67, 0xff, 0x88, 0x06, 0x29, 0x4b, 0x7b, 0xa9, 0xf5, 0x52, 0x2f,
+ 0xbb, 0x60, 0x2f, 0x3e, 0x4e, 0xad, 0x8a, 0x08, 0x2a, 0xa5, 0x47, 0x2f, 0x25, 0x6d, 0xc3, 0x12,
+ 0xdc, 0x66, 0x42, 0xb2, 0x15, 0xf6, 0xeb, 0x08, 0x7e, 0x0e, 0xbf, 0x96, 0x47, 0xc9, 0xa3, 0x76,
+ 0xa5, 0xde, 0x26, 0xbf, 0xf9, 0x3d, 0x66, 0x32, 0x70, 0x9a, 0x23, 0xe6, 0x05, 0xcf, 0x98, 0x12,
+ 0xd9, 0x1a, 0xa5, 0x28, 0x51, 0xf3, 0xd5, 0x5c, 0x73, 0x83, 0x1b, 0xbd, 0xe4, 0xa9, 0xd2, 0x58,
+ 0x22, 0x05, 0x4f, 0x4a, 0x99, 0x12, 0xdd, 0x4e, 0x4d, 0x50, 0xb0, 0x05, 0x2f, 0x3c, 0x67, 0xf0,
+ 0x49, 0xa0, 0xf7, 0xb4, 0x35, 0x98, 0x05, 0xfd, 0x2d, 0x37, 0x4b, 0x2d, 0x54, 0x89, 0x9a, 0x52,
+ 0x68, 0x4a, 0xb6, 0xe6, 0x49, 0xab, 0x4f, 0x86, 0xff, 0x66, 0xae, 0xb6, 0x58, 0x59, 0x29, 0x9e,
+ 0x10, 0x8f, 0xd9, 0x9a, 0x9e, 0xc0, 0xff, 0x95, 0x30, 0xaa, 0x60, 0xd5, 0xdc, 0xf1, 0x23, 0xd7,
+ 0x8b, 0x03, 0xf6, 0x6c, 0x65, 0x7d, 0x88, 0x57, 0xc1, 0x58, 0xa0, 0x4c, 0x1a, 0x81, 0xb1, 0x83,
+ 0xe8, 0x08, 0xda, 0x6e, 0x36, 0x93, 0x34, 0xfb, 0x8d, 0x61, 0x7c, 0xde, 0x4b, 0x77, 0x1b, 0xa4,
+ 0x8f, 0xb6, 0xb3, 0x9b, 0x6c, 0x16, 0xa8, 0x83, 0x0f, 0x02, 0x47, 0x7b, 0x1b, 0xfc, 0x39, 0xe3,
+ 0xf8, 0xc7, 0x3e, 0x72, 0xf6, 0x67, 0x75, 0xfb, 0x3d, 0x0b, 0x1f, 0x68, 0xee, 0x64, 0xa9, 0xab,
+ 0x6d, 0x58, 0xf7, 0x12, 0xe2, 0x1a, 0x4c, 0x0f, 0xa1, 0xf1, 0xca, 0xab, 0x10, 0x62, 0x4b, 0x7a,
+ 0x0c, 0xad, 0x37, 0x56, 0x6c, 0xb6, 0x1f, 0xe0, 0x1f, 0x57, 0xd1, 0x05, 0x99, 0x54, 0x70, 0xb0,
+ 0xc4, 0x75, 0x2d, 0x72, 0xd2, 0xd9, 0xcb, 0x9c, 0xda, 0x9b, 0x4c, 0xc9, 0xcb, 0x4d, 0x60, 0xe5,
+ 0x58, 0x30, 0x99, 0xa7, 0xa8, 0xf3, 0x2c, 0xe7, 0xd2, 0x5d, 0x2c, 0xf3, 0x2d, 0xa6, 0x84, 0xf9,
+ 0x7d, 0x7d, 0xcd, 0xcd, 0x75, 0xfd, 0xf1, 0x45, 0xc8, 0x7b, 0xd4, 0xbc, 0x1f, 0x4f, 0x1f, 0x16,
+ 0x6d, 0xa7, 0x1c, 0x7d, 0x07, 0x00, 0x00, 0xff, 0xff, 0xf8, 0xfb, 0xfb, 0x11, 0x36, 0x02, 0x00,
+ 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/logging/type/http_request.pb.go b/vendor/google.golang.org/genproto/googleapis/logging/type/http_request.pb.go
new file mode 100644
index 0000000..f0aa78d
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/logging/type/http_request.pb.go
@@ -0,0 +1,224 @@
+// Code generated by protoc-gen-go.
+// source: google/logging/type/http_request.proto
+// DO NOT EDIT!
+
+/*
+Package ltype is a generated protocol buffer package.
+
+It is generated from these files:
+ google/logging/type/http_request.proto
+ google/logging/type/log_severity.proto
+
+It has these top-level messages:
+ HttpRequest
+*/
+package ltype
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "google.golang.org/genproto/googleapis/api/annotations"
+import google_protobuf1 "github.com/golang/protobuf/ptypes/duration"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// A common proto for logging HTTP requests. Only contains semantics
+// defined by the HTTP specification. Product-specific logging
+// information MUST be defined in a separate message.
+type HttpRequest struct {
+ // The request method. Examples: `"GET"`, `"HEAD"`, `"PUT"`, `"POST"`.
+ RequestMethod string `protobuf:"bytes,1,opt,name=request_method,json=requestMethod" json:"request_method,omitempty"`
+ // The scheme (http, https), the host name, the path and the query
+ // portion of the URL that was requested.
+ // Example: `"http://example.com/some/info?color=red"`.
+ RequestUrl string `protobuf:"bytes,2,opt,name=request_url,json=requestUrl" json:"request_url,omitempty"`
+ // The size of the HTTP request message in bytes, including the request
+ // headers and the request body.
+ RequestSize int64 `protobuf:"varint,3,opt,name=request_size,json=requestSize" json:"request_size,omitempty"`
+ // The response code indicating the status of response.
+ // Examples: 200, 404.
+ Status int32 `protobuf:"varint,4,opt,name=status" json:"status,omitempty"`
+ // The size of the HTTP response message sent back to the client, in bytes,
+ // including the response headers and the response body.
+ ResponseSize int64 `protobuf:"varint,5,opt,name=response_size,json=responseSize" json:"response_size,omitempty"`
+ // The user agent sent by the client. Example:
+ // `"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)"`.
+ UserAgent string `protobuf:"bytes,6,opt,name=user_agent,json=userAgent" json:"user_agent,omitempty"`
+ // The IP address (IPv4 or IPv6) of the client that issued the HTTP
+ // request. Examples: `"192.168.1.1"`, `"FE80::0202:B3FF:FE1E:8329"`.
+ RemoteIp string `protobuf:"bytes,7,opt,name=remote_ip,json=remoteIp" json:"remote_ip,omitempty"`
+ // The IP address (IPv4 or IPv6) of the origin server that the request was
+ // sent to.
+ ServerIp string `protobuf:"bytes,13,opt,name=server_ip,json=serverIp" json:"server_ip,omitempty"`
+ // The referer URL of the request, as defined in
+ // [HTTP/1.1 Header Field Definitions](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
+ Referer string `protobuf:"bytes,8,opt,name=referer" json:"referer,omitempty"`
+ // The request processing latency on the server, from the time the request was
+ // received until the response was sent.
+ Latency *google_protobuf1.Duration `protobuf:"bytes,14,opt,name=latency" json:"latency,omitempty"`
+ // Whether or not a cache lookup was attempted.
+ CacheLookup bool `protobuf:"varint,11,opt,name=cache_lookup,json=cacheLookup" json:"cache_lookup,omitempty"`
+ // Whether or not an entity was served from cache
+ // (with or without validation).
+ CacheHit bool `protobuf:"varint,9,opt,name=cache_hit,json=cacheHit" json:"cache_hit,omitempty"`
+ // Whether or not the response was validated with the origin server before
+ // being served from cache. This field is only meaningful if `cache_hit` is
+ // True.
+ CacheValidatedWithOriginServer bool `protobuf:"varint,10,opt,name=cache_validated_with_origin_server,json=cacheValidatedWithOriginServer" json:"cache_validated_with_origin_server,omitempty"`
+ // The number of HTTP response bytes inserted into cache. Set only when a
+ // cache fill was attempted.
+ CacheFillBytes int64 `protobuf:"varint,12,opt,name=cache_fill_bytes,json=cacheFillBytes" json:"cache_fill_bytes,omitempty"`
+}
+
+func (m *HttpRequest) Reset() { *m = HttpRequest{} }
+func (m *HttpRequest) String() string { return proto.CompactTextString(m) }
+func (*HttpRequest) ProtoMessage() {}
+func (*HttpRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *HttpRequest) GetRequestMethod() string {
+ if m != nil {
+ return m.RequestMethod
+ }
+ return ""
+}
+
+func (m *HttpRequest) GetRequestUrl() string {
+ if m != nil {
+ return m.RequestUrl
+ }
+ return ""
+}
+
+func (m *HttpRequest) GetRequestSize() int64 {
+ if m != nil {
+ return m.RequestSize
+ }
+ return 0
+}
+
+func (m *HttpRequest) GetStatus() int32 {
+ if m != nil {
+ return m.Status
+ }
+ return 0
+}
+
+func (m *HttpRequest) GetResponseSize() int64 {
+ if m != nil {
+ return m.ResponseSize
+ }
+ return 0
+}
+
+func (m *HttpRequest) GetUserAgent() string {
+ if m != nil {
+ return m.UserAgent
+ }
+ return ""
+}
+
+func (m *HttpRequest) GetRemoteIp() string {
+ if m != nil {
+ return m.RemoteIp
+ }
+ return ""
+}
+
+func (m *HttpRequest) GetServerIp() string {
+ if m != nil {
+ return m.ServerIp
+ }
+ return ""
+}
+
+func (m *HttpRequest) GetReferer() string {
+ if m != nil {
+ return m.Referer
+ }
+ return ""
+}
+
+func (m *HttpRequest) GetLatency() *google_protobuf1.Duration {
+ if m != nil {
+ return m.Latency
+ }
+ return nil
+}
+
+func (m *HttpRequest) GetCacheLookup() bool {
+ if m != nil {
+ return m.CacheLookup
+ }
+ return false
+}
+
+func (m *HttpRequest) GetCacheHit() bool {
+ if m != nil {
+ return m.CacheHit
+ }
+ return false
+}
+
+func (m *HttpRequest) GetCacheValidatedWithOriginServer() bool {
+ if m != nil {
+ return m.CacheValidatedWithOriginServer
+ }
+ return false
+}
+
+func (m *HttpRequest) GetCacheFillBytes() int64 {
+ if m != nil {
+ return m.CacheFillBytes
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*HttpRequest)(nil), "google.logging.type.HttpRequest")
+}
+
+func init() { proto.RegisterFile("google/logging/type/http_request.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 488 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x92, 0x5b, 0x6b, 0x14, 0x31,
+ 0x14, 0xc7, 0x99, 0x5e, 0xf6, 0x92, 0xbd, 0x50, 0x22, 0x68, 0x5a, 0xb5, 0xae, 0x15, 0x65, 0x9e,
+ 0x66, 0xc0, 0xbe, 0x08, 0x3e, 0xb9, 0x8a, 0xb6, 0x52, 0xb1, 0x4c, 0xbd, 0x80, 0x2f, 0x43, 0x76,
+ 0xf7, 0x6c, 0x26, 0x98, 0x9d, 0xc4, 0x24, 0x53, 0xd9, 0xbe, 0xfa, 0x11, 0xfc, 0x16, 0x7e, 0x4a,
+ 0x99, 0x93, 0x0c, 0x28, 0xf4, 0x65, 0x21, 0xbf, 0xff, 0xef, 0x3f, 0x67, 0xf6, 0x4c, 0xc8, 0x33,
+ 0xa1, 0xb5, 0x50, 0x90, 0x2b, 0x2d, 0x84, 0xac, 0x45, 0xee, 0xb7, 0x06, 0xf2, 0xca, 0x7b, 0x53,
+ 0x5a, 0xf8, 0xd1, 0x80, 0xf3, 0x99, 0xb1, 0xda, 0x6b, 0x7a, 0x27, 0x78, 0x59, 0xf4, 0xb2, 0xd6,
+ 0x3b, 0x7a, 0x10, 0xcb, 0xdc, 0xc8, 0x9c, 0xd7, 0xb5, 0xf6, 0xdc, 0x4b, 0x5d, 0xbb, 0x50, 0x39,
+ 0x3a, 0x8e, 0x29, 0x9e, 0x16, 0xcd, 0x3a, 0x5f, 0x35, 0x16, 0x85, 0x90, 0x9f, 0xfc, 0xde, 0x23,
+ 0xa3, 0x33, 0xef, 0x4d, 0x11, 0x06, 0xd1, 0xa7, 0x64, 0x1a, 0x67, 0x96, 0x1b, 0xf0, 0x95, 0x5e,
+ 0xb1, 0x64, 0x96, 0xa4, 0xc3, 0x62, 0x12, 0xe9, 0x07, 0x84, 0xf4, 0x11, 0x19, 0x75, 0x5a, 0x63,
+ 0x15, 0xdb, 0x41, 0x87, 0x44, 0xf4, 0xd9, 0x2a, 0xfa, 0x98, 0x8c, 0x3b, 0xc1, 0xc9, 0x1b, 0x60,
+ 0xbb, 0xb3, 0x24, 0xdd, 0x2d, 0xba, 0xd2, 0x95, 0xbc, 0x01, 0x7a, 0x97, 0xf4, 0x9c, 0xe7, 0xbe,
+ 0x71, 0x6c, 0x6f, 0x96, 0xa4, 0xfb, 0x45, 0x3c, 0xd1, 0x27, 0x64, 0x62, 0xc1, 0x19, 0x5d, 0x3b,
+ 0x08, 0xdd, 0x7d, 0xec, 0x8e, 0x3b, 0x88, 0xe5, 0x87, 0x84, 0x34, 0x0e, 0x6c, 0xc9, 0x05, 0xd4,
+ 0x9e, 0xf5, 0x70, 0xfe, 0xb0, 0x25, 0xaf, 0x5a, 0x40, 0xef, 0x93, 0xa1, 0x85, 0x8d, 0xf6, 0x50,
+ 0x4a, 0xc3, 0xfa, 0x98, 0x0e, 0x02, 0x38, 0x37, 0x6d, 0xe8, 0xc0, 0x5e, 0x83, 0x6d, 0xc3, 0x49,
+ 0x08, 0x03, 0x38, 0x37, 0x94, 0x91, 0xbe, 0x85, 0x35, 0x58, 0xb0, 0x6c, 0x80, 0x51, 0x77, 0xa4,
+ 0xa7, 0xa4, 0xaf, 0xb8, 0x87, 0x7a, 0xb9, 0x65, 0xd3, 0x59, 0x92, 0x8e, 0x9e, 0x1f, 0x66, 0xf1,
+ 0x7b, 0x74, 0xcb, 0xcd, 0xde, 0xc4, 0xe5, 0x16, 0x9d, 0xd9, 0xee, 0x61, 0xc9, 0x97, 0x15, 0x94,
+ 0x4a, 0xeb, 0xef, 0x8d, 0x61, 0xa3, 0x59, 0x92, 0x0e, 0x8a, 0x11, 0xb2, 0x0b, 0x44, 0xed, 0xeb,
+ 0x04, 0xa5, 0x92, 0x9e, 0x0d, 0x31, 0x1f, 0x20, 0x38, 0x93, 0x9e, 0xbe, 0x27, 0x27, 0x21, 0xbc,
+ 0xe6, 0x4a, 0xae, 0xb8, 0x87, 0x55, 0xf9, 0x53, 0xfa, 0xaa, 0xd4, 0x56, 0x0a, 0x59, 0x97, 0xe1,
+ 0xb5, 0x19, 0xc1, 0xd6, 0x31, 0x9a, 0x5f, 0x3a, 0xf1, 0xab, 0xf4, 0xd5, 0x47, 0xd4, 0xae, 0xd0,
+ 0xa2, 0x29, 0x39, 0x08, 0xcf, 0x5a, 0x4b, 0xa5, 0xca, 0xc5, 0xd6, 0x83, 0x63, 0x63, 0xdc, 0xed,
+ 0x14, 0xf9, 0x5b, 0xa9, 0xd4, 0xbc, 0xa5, 0xf3, 0x5f, 0x09, 0xb9, 0xb7, 0xd4, 0x9b, 0xec, 0x96,
+ 0xfb, 0x36, 0x3f, 0xf8, 0xe7, 0xba, 0x5c, 0xb6, 0x7f, 0xfc, 0x32, 0xf9, 0xf6, 0x22, 0x8a, 0x42,
+ 0x2b, 0x5e, 0x8b, 0x4c, 0x5b, 0x91, 0x0b, 0xa8, 0x71, 0x2d, 0x79, 0x88, 0xb8, 0x91, 0xee, 0xbf,
+ 0xfb, 0xfd, 0x52, 0xb5, 0xbf, 0x7f, 0x76, 0x0e, 0xdf, 0x85, 0xea, 0x6b, 0xa5, 0x9b, 0x55, 0x76,
+ 0x11, 0x27, 0x7d, 0xda, 0x1a, 0x58, 0xf4, 0xf0, 0x01, 0xa7, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff,
+ 0x6f, 0xb5, 0x28, 0xee, 0x1f, 0x03, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/logging/type/log_severity.pb.go b/vendor/google.golang.org/genproto/googleapis/logging/type/log_severity.pb.go
new file mode 100644
index 0000000..36cbe95
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/logging/type/log_severity.pb.go
@@ -0,0 +1,111 @@
+// Code generated by protoc-gen-go.
+// source: google/logging/type/log_severity.proto
+// DO NOT EDIT!
+
+package ltype
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "google.golang.org/genproto/googleapis/api/annotations"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// The severity of the event described in a log entry, expressed as one of the
+// standard severity levels listed below. For your reference, the levels are
+// assigned the listed numeric values. The effect of using numeric values other
+// than those listed is undefined.
+//
+// You can filter for log entries by severity. For example, the following
+// filter expression will match log entries with severities `INFO`, `NOTICE`,
+// and `WARNING`:
+//
+// severity > DEBUG AND severity <= WARNING
+//
+// If you are writing log entries, you should map other severity encodings to
+// one of these standard levels. For example, you might map all of Java's FINE,
+// FINER, and FINEST levels to `LogSeverity.DEBUG`. You can preserve the
+// original severity level in the log entry payload if you wish.
+type LogSeverity int32
+
+const (
+ // (0) The log entry has no assigned severity level.
+ LogSeverity_DEFAULT LogSeverity = 0
+ // (100) Debug or trace information.
+ LogSeverity_DEBUG LogSeverity = 100
+ // (200) Routine information, such as ongoing status or performance.
+ LogSeverity_INFO LogSeverity = 200
+ // (300) Normal but significant events, such as start up, shut down, or
+ // a configuration change.
+ LogSeverity_NOTICE LogSeverity = 300
+ // (400) Warning events might cause problems.
+ LogSeverity_WARNING LogSeverity = 400
+ // (500) Error events are likely to cause problems.
+ LogSeverity_ERROR LogSeverity = 500
+ // (600) Critical events cause more severe problems or outages.
+ LogSeverity_CRITICAL LogSeverity = 600
+ // (700) A person must take an action immediately.
+ LogSeverity_ALERT LogSeverity = 700
+ // (800) One or more systems are unusable.
+ LogSeverity_EMERGENCY LogSeverity = 800
+)
+
+var LogSeverity_name = map[int32]string{
+ 0: "DEFAULT",
+ 100: "DEBUG",
+ 200: "INFO",
+ 300: "NOTICE",
+ 400: "WARNING",
+ 500: "ERROR",
+ 600: "CRITICAL",
+ 700: "ALERT",
+ 800: "EMERGENCY",
+}
+var LogSeverity_value = map[string]int32{
+ "DEFAULT": 0,
+ "DEBUG": 100,
+ "INFO": 200,
+ "NOTICE": 300,
+ "WARNING": 400,
+ "ERROR": 500,
+ "CRITICAL": 600,
+ "ALERT": 700,
+ "EMERGENCY": 800,
+}
+
+func (x LogSeverity) String() string {
+ return proto.EnumName(LogSeverity_name, int32(x))
+}
+func (LogSeverity) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{0} }
+
+func init() {
+ proto.RegisterEnum("google.logging.type.LogSeverity", LogSeverity_name, LogSeverity_value)
+}
+
+func init() { proto.RegisterFile("google/logging/type/log_severity.proto", fileDescriptor1) }
+
+var fileDescriptor1 = []byte{
+ // 297 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4b, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0xd5, 0xcf, 0xc9, 0x4f, 0x4f, 0xcf, 0xcc, 0x4b, 0xd7, 0x2f, 0xa9, 0x2c, 0x00, 0x73,
+ 0xe2, 0x8b, 0x53, 0xcb, 0x52, 0x8b, 0x32, 0x4b, 0x2a, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85,
+ 0x84, 0x21, 0xea, 0xf4, 0xa0, 0xea, 0xf4, 0x40, 0xea, 0xa4, 0x64, 0xa0, 0x9a, 0x13, 0x0b, 0x32,
+ 0xf5, 0x13, 0xf3, 0xf2, 0xf2, 0x4b, 0x12, 0x4b, 0x32, 0xf3, 0xf3, 0x8a, 0x21, 0x5a, 0xb4, 0x9a,
+ 0x18, 0xb9, 0xb8, 0x7d, 0xf2, 0xd3, 0x83, 0xa1, 0x06, 0x09, 0x71, 0x73, 0xb1, 0xbb, 0xb8, 0xba,
+ 0x39, 0x86, 0xfa, 0x84, 0x08, 0x30, 0x08, 0x71, 0x72, 0xb1, 0xba, 0xb8, 0x3a, 0x85, 0xba, 0x0b,
+ 0xa4, 0x08, 0x71, 0x72, 0xb1, 0x78, 0xfa, 0xb9, 0xf9, 0x0b, 0x9c, 0x60, 0x14, 0xe2, 0xe6, 0x62,
+ 0xf3, 0xf3, 0x0f, 0xf1, 0x74, 0x76, 0x15, 0x58, 0xc3, 0x24, 0xc4, 0xc3, 0xc5, 0x1e, 0xee, 0x18,
+ 0xe4, 0xe7, 0xe9, 0xe7, 0x2e, 0x30, 0x81, 0x59, 0x88, 0x8b, 0x8b, 0xd5, 0x35, 0x28, 0xc8, 0x3f,
+ 0x48, 0xe0, 0x0b, 0xb3, 0x10, 0x2f, 0x17, 0x87, 0x73, 0x90, 0x67, 0x88, 0xa7, 0xb3, 0xa3, 0x8f,
+ 0xc0, 0x0d, 0x16, 0x90, 0x94, 0xa3, 0x8f, 0x6b, 0x50, 0x88, 0xc0, 0x1e, 0x56, 0x21, 0x3e, 0x2e,
+ 0x4e, 0x57, 0x5f, 0xd7, 0x20, 0x77, 0x57, 0x3f, 0xe7, 0x48, 0x81, 0x05, 0x6c, 0x4e, 0xcd, 0x8c,
+ 0x5c, 0xe2, 0xc9, 0xf9, 0xb9, 0x7a, 0x58, 0x9c, 0xef, 0x24, 0x80, 0xe4, 0xba, 0x00, 0x90, 0x93,
+ 0x03, 0x18, 0xa3, 0x2c, 0xa0, 0x0a, 0xd3, 0xf3, 0x73, 0x12, 0xf3, 0xd2, 0xf5, 0xf2, 0x8b, 0xd2,
+ 0xf5, 0xd3, 0x53, 0xf3, 0xc0, 0x1e, 0xd2, 0x87, 0x48, 0x25, 0x16, 0x64, 0x16, 0xa3, 0x04, 0x97,
+ 0x75, 0x0e, 0x88, 0x5c, 0xc5, 0x24, 0xe9, 0x0e, 0xd1, 0xea, 0x9c, 0x93, 0x5f, 0x9a, 0xa2, 0xe7,
+ 0x03, 0xb5, 0x29, 0xa4, 0xb2, 0x20, 0x35, 0x89, 0x0d, 0x6c, 0x80, 0x31, 0x20, 0x00, 0x00, 0xff,
+ 0xff, 0x1b, 0x91, 0x99, 0x37, 0x6e, 0x01, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/logging/v2/log_entry.pb.go b/vendor/google.golang.org/genproto/googleapis/logging/v2/log_entry.pb.go
new file mode 100644
index 0000000..d81b52c
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/logging/v2/log_entry.pb.go
@@ -0,0 +1,501 @@
+// Code generated by protoc-gen-go.
+// source: google/logging/v2/log_entry.proto
+// DO NOT EDIT!
+
+/*
+Package logging is a generated protocol buffer package.
+
+It is generated from these files:
+ google/logging/v2/log_entry.proto
+ google/logging/v2/logging.proto
+ google/logging/v2/logging_config.proto
+ google/logging/v2/logging_metrics.proto
+
+It has these top-level messages:
+ LogEntry
+ LogEntryOperation
+ LogEntrySourceLocation
+ DeleteLogRequest
+ WriteLogEntriesRequest
+ WriteLogEntriesResponse
+ WriteLogEntriesPartialErrors
+ ListLogEntriesRequest
+ ListLogEntriesResponse
+ ListMonitoredResourceDescriptorsRequest
+ ListMonitoredResourceDescriptorsResponse
+ ListLogsRequest
+ ListLogsResponse
+ LogSink
+ ListSinksRequest
+ ListSinksResponse
+ GetSinkRequest
+ CreateSinkRequest
+ UpdateSinkRequest
+ DeleteSinkRequest
+ LogMetric
+ ListLogMetricsRequest
+ ListLogMetricsResponse
+ GetLogMetricRequest
+ CreateLogMetricRequest
+ UpdateLogMetricRequest
+ DeleteLogMetricRequest
+*/
+package logging
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "google.golang.org/genproto/googleapis/api/annotations"
+import google_api3 "google.golang.org/genproto/googleapis/api/monitoredres"
+import google_logging_type "google.golang.org/genproto/googleapis/logging/type"
+import google_logging_type1 "google.golang.org/genproto/googleapis/logging/type"
+import google_protobuf2 "github.com/golang/protobuf/ptypes/any"
+import google_protobuf3 "github.com/golang/protobuf/ptypes/struct"
+import google_protobuf4 "github.com/golang/protobuf/ptypes/timestamp"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// An individual entry in a log.
+type LogEntry struct {
+ // Required. The resource name of the log to which this log entry belongs:
+ //
+ // "projects/[PROJECT_ID]/logs/[LOG_ID]"
+ // "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
+ // "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]"
+ // "folders/[FOLDER_ID]/logs/[LOG_ID]"
+ //
+ // `[LOG_ID]` must be URL-encoded within `log_name`. Example:
+ // `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`.
+ // `[LOG_ID]` must be less than 512 characters long and can only include the
+ // following characters: upper and lower case alphanumeric characters,
+ // forward-slash, underscore, hyphen, and period.
+ //
+ // For backward compatibility, if `log_name` begins with a forward-slash, such
+ // as `/projects/...`, then the log entry is ingested as usual but the
+ // forward-slash is removed. Listing the log entry will not show the leading
+ // slash and filtering for a log name with a leading slash will never return
+ // any results.
+ LogName string `protobuf:"bytes,12,opt,name=log_name,json=logName" json:"log_name,omitempty"`
+ // Required. The monitored resource associated with this log entry.
+ // Example: a log entry that reports a database error would be
+ // associated with the monitored resource designating the particular
+ // database that reported the error.
+ Resource *google_api3.MonitoredResource `protobuf:"bytes,8,opt,name=resource" json:"resource,omitempty"`
+ // Optional. The log entry payload, which can be one of multiple types.
+ //
+ // Types that are valid to be assigned to Payload:
+ // *LogEntry_ProtoPayload
+ // *LogEntry_TextPayload
+ // *LogEntry_JsonPayload
+ Payload isLogEntry_Payload `protobuf_oneof:"payload"`
+ // Optional. The time the event described by the log entry occurred. If
+ // omitted in a new log entry, Stackdriver Logging will insert the time the
+ // log entry is received. Stackdriver Logging might reject log entries whose
+ // time stamps are more than a couple of hours in the future. Log entries
+ // with time stamps in the past are accepted.
+ Timestamp *google_protobuf4.Timestamp `protobuf:"bytes,9,opt,name=timestamp" json:"timestamp,omitempty"`
+ // Output only. The time the log entry was received by Stackdriver Logging.
+ ReceiveTimestamp *google_protobuf4.Timestamp `protobuf:"bytes,24,opt,name=receive_timestamp,json=receiveTimestamp" json:"receive_timestamp,omitempty"`
+ // Optional. The severity of the log entry. The default value is
+ // `LogSeverity.DEFAULT`.
+ Severity google_logging_type1.LogSeverity `protobuf:"varint,10,opt,name=severity,enum=google.logging.type.LogSeverity" json:"severity,omitempty"`
+ // Optional. A unique identifier for the log entry. If you provide a value,
+ // then Stackdriver Logging considers other log entries in the same project,
+ // with the same `timestamp`, and with the same `insert_id` to be duplicates
+ // which can be removed. If omitted in new log entries, then Stackdriver
+ // Logging will insert its own unique identifier. The `insert_id` is used
+ // to order log entries that have the same `timestamp` value.
+ InsertId string `protobuf:"bytes,4,opt,name=insert_id,json=insertId" json:"insert_id,omitempty"`
+ // Optional. Information about the HTTP request associated with this
+ // log entry, if applicable.
+ HttpRequest *google_logging_type.HttpRequest `protobuf:"bytes,7,opt,name=http_request,json=httpRequest" json:"http_request,omitempty"`
+ // Optional. A set of user-defined (key, value) data that provides additional
+ // information about the log entry.
+ Labels map[string]string `protobuf:"bytes,11,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ // Optional. Information about an operation associated with the log entry, if
+ // applicable.
+ Operation *LogEntryOperation `protobuf:"bytes,15,opt,name=operation" json:"operation,omitempty"`
+ // Optional. Resource name of the trace associated with the log entry, if any.
+ // If it contains a relative resource name, the name is assumed to be relative
+ // to `//tracing.googleapis.com`. Example:
+ // `projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824`
+ Trace string `protobuf:"bytes,22,opt,name=trace" json:"trace,omitempty"`
+ // Optional. Source code location information associated with the log entry,
+ // if any.
+ SourceLocation *LogEntrySourceLocation `protobuf:"bytes,23,opt,name=source_location,json=sourceLocation" json:"source_location,omitempty"`
+}
+
+func (m *LogEntry) Reset() { *m = LogEntry{} }
+func (m *LogEntry) String() string { return proto.CompactTextString(m) }
+func (*LogEntry) ProtoMessage() {}
+func (*LogEntry) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+type isLogEntry_Payload interface {
+ isLogEntry_Payload()
+}
+
+type LogEntry_ProtoPayload struct {
+ ProtoPayload *google_protobuf2.Any `protobuf:"bytes,2,opt,name=proto_payload,json=protoPayload,oneof"`
+}
+type LogEntry_TextPayload struct {
+ TextPayload string `protobuf:"bytes,3,opt,name=text_payload,json=textPayload,oneof"`
+}
+type LogEntry_JsonPayload struct {
+ JsonPayload *google_protobuf3.Struct `protobuf:"bytes,6,opt,name=json_payload,json=jsonPayload,oneof"`
+}
+
+func (*LogEntry_ProtoPayload) isLogEntry_Payload() {}
+func (*LogEntry_TextPayload) isLogEntry_Payload() {}
+func (*LogEntry_JsonPayload) isLogEntry_Payload() {}
+
+func (m *LogEntry) GetPayload() isLogEntry_Payload {
+ if m != nil {
+ return m.Payload
+ }
+ return nil
+}
+
+func (m *LogEntry) GetLogName() string {
+ if m != nil {
+ return m.LogName
+ }
+ return ""
+}
+
+func (m *LogEntry) GetResource() *google_api3.MonitoredResource {
+ if m != nil {
+ return m.Resource
+ }
+ return nil
+}
+
+func (m *LogEntry) GetProtoPayload() *google_protobuf2.Any {
+ if x, ok := m.GetPayload().(*LogEntry_ProtoPayload); ok {
+ return x.ProtoPayload
+ }
+ return nil
+}
+
+func (m *LogEntry) GetTextPayload() string {
+ if x, ok := m.GetPayload().(*LogEntry_TextPayload); ok {
+ return x.TextPayload
+ }
+ return ""
+}
+
+func (m *LogEntry) GetJsonPayload() *google_protobuf3.Struct {
+ if x, ok := m.GetPayload().(*LogEntry_JsonPayload); ok {
+ return x.JsonPayload
+ }
+ return nil
+}
+
+func (m *LogEntry) GetTimestamp() *google_protobuf4.Timestamp {
+ if m != nil {
+ return m.Timestamp
+ }
+ return nil
+}
+
+func (m *LogEntry) GetReceiveTimestamp() *google_protobuf4.Timestamp {
+ if m != nil {
+ return m.ReceiveTimestamp
+ }
+ return nil
+}
+
+func (m *LogEntry) GetSeverity() google_logging_type1.LogSeverity {
+ if m != nil {
+ return m.Severity
+ }
+ return google_logging_type1.LogSeverity_DEFAULT
+}
+
+func (m *LogEntry) GetInsertId() string {
+ if m != nil {
+ return m.InsertId
+ }
+ return ""
+}
+
+func (m *LogEntry) GetHttpRequest() *google_logging_type.HttpRequest {
+ if m != nil {
+ return m.HttpRequest
+ }
+ return nil
+}
+
+func (m *LogEntry) GetLabels() map[string]string {
+ if m != nil {
+ return m.Labels
+ }
+ return nil
+}
+
+func (m *LogEntry) GetOperation() *LogEntryOperation {
+ if m != nil {
+ return m.Operation
+ }
+ return nil
+}
+
+func (m *LogEntry) GetTrace() string {
+ if m != nil {
+ return m.Trace
+ }
+ return ""
+}
+
+func (m *LogEntry) GetSourceLocation() *LogEntrySourceLocation {
+ if m != nil {
+ return m.SourceLocation
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*LogEntry) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _LogEntry_OneofMarshaler, _LogEntry_OneofUnmarshaler, _LogEntry_OneofSizer, []interface{}{
+ (*LogEntry_ProtoPayload)(nil),
+ (*LogEntry_TextPayload)(nil),
+ (*LogEntry_JsonPayload)(nil),
+ }
+}
+
+func _LogEntry_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*LogEntry)
+ // payload
+ switch x := m.Payload.(type) {
+ case *LogEntry_ProtoPayload:
+ b.EncodeVarint(2<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.ProtoPayload); err != nil {
+ return err
+ }
+ case *LogEntry_TextPayload:
+ b.EncodeVarint(3<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.TextPayload)
+ case *LogEntry_JsonPayload:
+ b.EncodeVarint(6<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.JsonPayload); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("LogEntry.Payload has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _LogEntry_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*LogEntry)
+ switch tag {
+ case 2: // payload.proto_payload
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(google_protobuf2.Any)
+ err := b.DecodeMessage(msg)
+ m.Payload = &LogEntry_ProtoPayload{msg}
+ return true, err
+ case 3: // payload.text_payload
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Payload = &LogEntry_TextPayload{x}
+ return true, err
+ case 6: // payload.json_payload
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(google_protobuf3.Struct)
+ err := b.DecodeMessage(msg)
+ m.Payload = &LogEntry_JsonPayload{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _LogEntry_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*LogEntry)
+ // payload
+ switch x := m.Payload.(type) {
+ case *LogEntry_ProtoPayload:
+ s := proto.Size(x.ProtoPayload)
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *LogEntry_TextPayload:
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.TextPayload)))
+ n += len(x.TextPayload)
+ case *LogEntry_JsonPayload:
+ s := proto.Size(x.JsonPayload)
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// Additional information about a potentially long-running operation with which
+// a log entry is associated.
+type LogEntryOperation struct {
+ // Optional. An arbitrary operation identifier. Log entries with the
+ // same identifier are assumed to be part of the same operation.
+ Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
+ // Optional. An arbitrary producer identifier. The combination of
+ // `id` and `producer` must be globally unique. Examples for `producer`:
+ // `"MyDivision.MyBigCompany.com"`, `"github.com/MyProject/MyApplication"`.
+ Producer string `protobuf:"bytes,2,opt,name=producer" json:"producer,omitempty"`
+ // Optional. Set this to True if this is the first log entry in the operation.
+ First bool `protobuf:"varint,3,opt,name=first" json:"first,omitempty"`
+ // Optional. Set this to True if this is the last log entry in the operation.
+ Last bool `protobuf:"varint,4,opt,name=last" json:"last,omitempty"`
+}
+
+func (m *LogEntryOperation) Reset() { *m = LogEntryOperation{} }
+func (m *LogEntryOperation) String() string { return proto.CompactTextString(m) }
+func (*LogEntryOperation) ProtoMessage() {}
+func (*LogEntryOperation) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *LogEntryOperation) GetId() string {
+ if m != nil {
+ return m.Id
+ }
+ return ""
+}
+
+func (m *LogEntryOperation) GetProducer() string {
+ if m != nil {
+ return m.Producer
+ }
+ return ""
+}
+
+func (m *LogEntryOperation) GetFirst() bool {
+ if m != nil {
+ return m.First
+ }
+ return false
+}
+
+func (m *LogEntryOperation) GetLast() bool {
+ if m != nil {
+ return m.Last
+ }
+ return false
+}
+
+// Additional information about the source code location that produced the log
+// entry.
+type LogEntrySourceLocation struct {
+ // Optional. Source file name. Depending on the runtime environment, this
+ // might be a simple name or a fully-qualified name.
+ File string `protobuf:"bytes,1,opt,name=file" json:"file,omitempty"`
+ // Optional. Line within the source file. 1-based; 0 indicates no line number
+ // available.
+ Line int64 `protobuf:"varint,2,opt,name=line" json:"line,omitempty"`
+ // Optional. Human-readable name of the function or method being invoked, with
+ // optional context such as the class or package name. This information may be
+ // used in contexts such as the logs viewer, where a file and line number are
+ // less meaningful. The format can vary by language. For example:
+ // `qual.if.ied.Class.method` (Java), `dir/package.func` (Go), `function`
+ // (Python).
+ Function string `protobuf:"bytes,3,opt,name=function" json:"function,omitempty"`
+}
+
+func (m *LogEntrySourceLocation) Reset() { *m = LogEntrySourceLocation{} }
+func (m *LogEntrySourceLocation) String() string { return proto.CompactTextString(m) }
+func (*LogEntrySourceLocation) ProtoMessage() {}
+func (*LogEntrySourceLocation) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+
+func (m *LogEntrySourceLocation) GetFile() string {
+ if m != nil {
+ return m.File
+ }
+ return ""
+}
+
+func (m *LogEntrySourceLocation) GetLine() int64 {
+ if m != nil {
+ return m.Line
+ }
+ return 0
+}
+
+func (m *LogEntrySourceLocation) GetFunction() string {
+ if m != nil {
+ return m.Function
+ }
+ return ""
+}
+
+func init() {
+ proto.RegisterType((*LogEntry)(nil), "google.logging.v2.LogEntry")
+ proto.RegisterType((*LogEntryOperation)(nil), "google.logging.v2.LogEntryOperation")
+ proto.RegisterType((*LogEntrySourceLocation)(nil), "google.logging.v2.LogEntrySourceLocation")
+}
+
+func init() { proto.RegisterFile("google/logging/v2/log_entry.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 699 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x54, 0x5f, 0x6f, 0xdb, 0x36,
+ 0x10, 0x8f, 0xec, 0xcc, 0x91, 0x69, 0xe7, 0x1f, 0x91, 0x25, 0x8a, 0x97, 0x61, 0x5e, 0x32, 0x6c,
+ 0xde, 0x8b, 0x0c, 0x78, 0x2f, 0xc9, 0x12, 0xa0, 0xa8, 0x83, 0x22, 0x29, 0xe0, 0xb6, 0x01, 0x53,
+ 0xf4, 0xa1, 0x28, 0x60, 0x30, 0x12, 0xad, 0xb0, 0x95, 0x49, 0x95, 0xa2, 0x8c, 0xfa, 0xa9, 0xdf,
+ 0xa7, 0x9f, 0xa8, 0x1f, 0xa5, 0x8f, 0x05, 0x8f, 0x94, 0xed, 0xda, 0x41, 0xfa, 0x76, 0x27, 0xfe,
+ 0xfe, 0xdc, 0x1d, 0x8f, 0x42, 0x7f, 0x26, 0x52, 0x26, 0x29, 0xeb, 0xa6, 0x32, 0x49, 0xb8, 0x48,
+ 0xba, 0x93, 0x9e, 0x09, 0x87, 0x4c, 0x68, 0x35, 0x0d, 0x33, 0x25, 0xb5, 0xc4, 0xbb, 0x16, 0x12,
+ 0x3a, 0x48, 0x38, 0xe9, 0xb5, 0x8e, 0x1c, 0x8b, 0x66, 0xbc, 0x4b, 0x85, 0x90, 0x9a, 0x6a, 0x2e,
+ 0x45, 0x6e, 0x09, 0xad, 0x93, 0x85, 0xd3, 0xb1, 0x14, 0x5c, 0x4b, 0xc5, 0xe2, 0xa1, 0x62, 0xb9,
+ 0x2c, 0x54, 0xc4, 0x1c, 0xe8, 0xef, 0x25, 0x63, 0x3d, 0xcd, 0x58, 0xf7, 0x5e, 0xeb, 0x6c, 0xa8,
+ 0xd8, 0xc7, 0x82, 0xe5, 0xfa, 0x31, 0x9c, 0x29, 0x31, 0x67, 0x13, 0xa6, 0xb8, 0x76, 0x55, 0xb6,
+ 0x0e, 0x1d, 0x0e, 0xb2, 0xbb, 0x62, 0xd4, 0xa5, 0xa2, 0x3c, 0x3a, 0x5a, 0x3e, 0xca, 0xb5, 0x2a,
+ 0xa2, 0xd2, 0xe0, 0x8f, 0xe5, 0x53, 0xcd, 0xc7, 0x2c, 0xd7, 0x74, 0x9c, 0x59, 0xc0, 0xf1, 0xd7,
+ 0x1a, 0xf2, 0x07, 0x32, 0x79, 0x66, 0x46, 0x82, 0x0f, 0x91, 0x6f, 0xcc, 0x05, 0x1d, 0xb3, 0xa0,
+ 0xd9, 0xf6, 0x3a, 0x75, 0xb2, 0x91, 0xca, 0xe4, 0x25, 0x1d, 0x33, 0x7c, 0x86, 0xfc, 0xb2, 0xc7,
+ 0xc0, 0x6f, 0x7b, 0x9d, 0x46, 0xef, 0xf7, 0xd0, 0x8d, 0x8e, 0x66, 0x3c, 0x7c, 0x51, 0x4e, 0x82,
+ 0x38, 0x10, 0x99, 0xc1, 0xf1, 0x39, 0xda, 0x04, 0xaf, 0x61, 0x46, 0xa7, 0xa9, 0xa4, 0x71, 0x50,
+ 0x01, 0xfe, 0x5e, 0xc9, 0x2f, 0x6b, 0x0b, 0x9f, 0x8a, 0xe9, 0xf5, 0x1a, 0x69, 0x42, 0x7e, 0x63,
+ 0xb1, 0xf8, 0x04, 0x35, 0x35, 0xfb, 0xa4, 0x67, 0xdc, 0xaa, 0x29, 0xeb, 0x7a, 0x8d, 0x34, 0xcc,
+ 0xd7, 0x12, 0x74, 0x81, 0x9a, 0xef, 0x73, 0x29, 0x66, 0xa0, 0x1a, 0x18, 0x1c, 0xac, 0x18, 0xdc,
+ 0xc2, 0x68, 0x0c, 0xdb, 0xc0, 0x4b, 0xf6, 0x29, 0xaa, 0xcf, 0xa6, 0x12, 0xd4, 0x81, 0xda, 0x5a,
+ 0xa1, 0xbe, 0x2e, 0x11, 0x64, 0x0e, 0xc6, 0x57, 0x68, 0x57, 0xb1, 0x88, 0xf1, 0x09, 0x1b, 0xce,
+ 0x15, 0x82, 0x9f, 0x2a, 0xec, 0x38, 0xd2, 0xec, 0x0b, 0xbe, 0x40, 0x7e, 0x79, 0xe3, 0x01, 0x6a,
+ 0x7b, 0x9d, 0xad, 0x5e, 0x3b, 0x5c, 0x5a, 0x4c, 0xb3, 0x1a, 0xe1, 0x40, 0x26, 0xb7, 0x0e, 0x47,
+ 0x66, 0x0c, 0xfc, 0x1b, 0xaa, 0x73, 0x91, 0x33, 0xa5, 0x87, 0x3c, 0x0e, 0xd6, 0xe1, 0xde, 0x7c,
+ 0xfb, 0xe1, 0x79, 0x8c, 0x2f, 0x51, 0x73, 0x71, 0xf1, 0x82, 0x0d, 0x28, 0xef, 0x61, 0xf9, 0x6b,
+ 0xad, 0x33, 0x62, 0x71, 0xa4, 0x71, 0x3f, 0x4f, 0xf0, 0x13, 0x54, 0x4b, 0xe9, 0x1d, 0x4b, 0xf3,
+ 0xa0, 0xd1, 0xae, 0x76, 0x1a, 0xbd, 0x7f, 0xc2, 0x95, 0x67, 0x13, 0x96, 0x5b, 0x14, 0x0e, 0x00,
+ 0x09, 0x31, 0x71, 0x34, 0xdc, 0x47, 0x75, 0x99, 0x31, 0x05, 0x2f, 0x29, 0xd8, 0x86, 0x12, 0xfe,
+ 0x7a, 0x44, 0xe3, 0x55, 0x89, 0x25, 0x73, 0x1a, 0xde, 0x43, 0xbf, 0x68, 0x45, 0x23, 0x16, 0xec,
+ 0x43, 0x8b, 0x36, 0xc1, 0x04, 0x6d, 0xdb, 0x3d, 0x1b, 0xa6, 0x32, 0xb2, 0xfa, 0x07, 0xa0, 0xff,
+ 0xef, 0x23, 0xfa, 0xb7, 0xc0, 0x18, 0x38, 0x02, 0xd9, 0xca, 0x7f, 0xc8, 0x5b, 0x67, 0xa8, 0xb1,
+ 0xd0, 0x04, 0xde, 0x41, 0xd5, 0x0f, 0x6c, 0x1a, 0x78, 0x60, 0x6b, 0x42, 0x53, 0xca, 0x84, 0xa6,
+ 0x05, 0x83, 0x55, 0xae, 0x13, 0x9b, 0xfc, 0x5f, 0x39, 0xf5, 0xfa, 0x75, 0xb4, 0xe1, 0xb6, 0xf0,
+ 0x98, 0xa3, 0xdd, 0x95, 0x7e, 0xf0, 0x16, 0xaa, 0xf0, 0xd8, 0x49, 0x55, 0x78, 0x8c, 0x5b, 0xc8,
+ 0xcf, 0x94, 0x8c, 0x8b, 0x88, 0x29, 0x27, 0x36, 0xcb, 0x8d, 0xcb, 0x88, 0xab, 0x5c, 0xc3, 0xd2,
+ 0xfb, 0xc4, 0x26, 0x18, 0xa3, 0xf5, 0x94, 0xe6, 0x1a, 0x2e, 0xda, 0x27, 0x10, 0x1f, 0xbf, 0x43,
+ 0xfb, 0x0f, 0xb7, 0x66, 0xd0, 0x23, 0x9e, 0x32, 0xe7, 0x08, 0x31, 0x28, 0x70, 0x61, 0x8b, 0xaf,
+ 0x12, 0x88, 0x4d, 0x1d, 0xa3, 0x42, 0x44, 0x30, 0xbf, 0xaa, 0xad, 0xa3, 0xcc, 0xfb, 0x9f, 0xd1,
+ 0xaf, 0x91, 0x1c, 0xaf, 0x8e, 0xb3, 0xbf, 0x59, 0x9a, 0xde, 0xc0, 0x93, 0xf5, 0xde, 0x9e, 0x3a,
+ 0x4c, 0x22, 0x53, 0x2a, 0x92, 0x50, 0xaa, 0xa4, 0x9b, 0x30, 0x01, 0x4f, 0xa0, 0x6b, 0x8f, 0x68,
+ 0xc6, 0xf3, 0x85, 0xff, 0xf1, 0xb9, 0x0b, 0xbf, 0x79, 0xde, 0x97, 0xca, 0xc1, 0x95, 0x65, 0x5f,
+ 0xa6, 0xb2, 0x88, 0xcd, 0x5d, 0x81, 0xcf, 0x9b, 0xde, 0x5d, 0x0d, 0x14, 0xfe, 0xfb, 0x1e, 0x00,
+ 0x00, 0xff, 0xff, 0xa9, 0x61, 0x44, 0xa8, 0xd0, 0x05, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/logging/v2/logging.pb.go b/vendor/google.golang.org/genproto/googleapis/logging/v2/logging.pb.go
new file mode 100644
index 0000000..06eeb23
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/logging/v2/logging.pb.go
@@ -0,0 +1,762 @@
+// Code generated by protoc-gen-go.
+// source: google/logging/v2/logging.proto
+// DO NOT EDIT!
+
+package logging
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "google.golang.org/genproto/googleapis/api/annotations"
+import google_api3 "google.golang.org/genproto/googleapis/api/monitoredres"
+import _ "github.com/golang/protobuf/ptypes/duration"
+import google_protobuf5 "github.com/golang/protobuf/ptypes/empty"
+import _ "github.com/golang/protobuf/ptypes/timestamp"
+import google_rpc "google.golang.org/genproto/googleapis/rpc/status"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// The parameters to DeleteLog.
+type DeleteLogRequest struct {
+ // Required. The resource name of the log to delete:
+ //
+ // "projects/[PROJECT_ID]/logs/[LOG_ID]"
+ // "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
+ // "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]"
+ // "folders/[FOLDER_ID]/logs/[LOG_ID]"
+ //
+ // `[LOG_ID]` must be URL-encoded. For example,
+ // `"projects/my-project-id/logs/syslog"`,
+ // `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`.
+ // For more information about log names, see
+ // [LogEntry][google.logging.v2.LogEntry].
+ LogName string `protobuf:"bytes,1,opt,name=log_name,json=logName" json:"log_name,omitempty"`
+}
+
+func (m *DeleteLogRequest) Reset() { *m = DeleteLogRequest{} }
+func (m *DeleteLogRequest) String() string { return proto.CompactTextString(m) }
+func (*DeleteLogRequest) ProtoMessage() {}
+func (*DeleteLogRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} }
+
+func (m *DeleteLogRequest) GetLogName() string {
+ if m != nil {
+ return m.LogName
+ }
+ return ""
+}
+
+// The parameters to WriteLogEntries.
+type WriteLogEntriesRequest struct {
+ // Optional. A default log resource name that is assigned to all log entries
+ // in `entries` that do not specify a value for `log_name`:
+ //
+ // "projects/[PROJECT_ID]/logs/[LOG_ID]"
+ // "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]"
+ // "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]"
+ // "folders/[FOLDER_ID]/logs/[LOG_ID]"
+ //
+ // `[LOG_ID]` must be URL-encoded. For example,
+ // `"projects/my-project-id/logs/syslog"` or
+ // `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`.
+ // For more information about log names, see
+ // [LogEntry][google.logging.v2.LogEntry].
+ LogName string `protobuf:"bytes,1,opt,name=log_name,json=logName" json:"log_name,omitempty"`
+ // Optional. A default monitored resource object that is assigned to all log
+ // entries in `entries` that do not specify a value for `resource`. Example:
+ //
+ // { "type": "gce_instance",
+ // "labels": {
+ // "zone": "us-central1-a", "instance_id": "00000000000000000000" }}
+ //
+ // See [LogEntry][google.logging.v2.LogEntry].
+ Resource *google_api3.MonitoredResource `protobuf:"bytes,2,opt,name=resource" json:"resource,omitempty"`
+ // Optional. Default labels that are added to the `labels` field of all log
+ // entries in `entries`. If a log entry already has a label with the same key
+ // as a label in this parameter, then the log entry's label is not changed.
+ // See [LogEntry][google.logging.v2.LogEntry].
+ Labels map[string]string `protobuf:"bytes,3,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ // Required. The log entries to write. Values supplied for the fields
+ // `log_name`, `resource`, and `labels` in this `entries.write` request are
+ // inserted into those log entries in this list that do not provide their own
+ // values.
+ //
+ // Stackdriver Logging also creates and inserts values for `timestamp` and
+ // `insert_id` if the entries do not provide them. The created `insert_id` for
+ // the N'th entry in this list will be greater than earlier entries and less
+ // than later entries. Otherwise, the order of log entries in this list does
+ // not matter.
+ //
+ // To improve throughput and to avoid exceeding the
+ // [quota limit](/logging/quota-policy) for calls to `entries.write`,
+ // you should write multiple log entries at once rather than
+ // calling this method for each individual log entry.
+ Entries []*LogEntry `protobuf:"bytes,4,rep,name=entries" json:"entries,omitempty"`
+ // Optional. Whether valid entries should be written even if some other
+ // entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any
+ // entry is not written, then the response status is the error associated
+ // with one of the failed entries and the response includes error details
+ // keyed by the entries' zero-based index in the `entries.write` method.
+ PartialSuccess bool `protobuf:"varint,5,opt,name=partial_success,json=partialSuccess" json:"partial_success,omitempty"`
+}
+
+func (m *WriteLogEntriesRequest) Reset() { *m = WriteLogEntriesRequest{} }
+func (m *WriteLogEntriesRequest) String() string { return proto.CompactTextString(m) }
+func (*WriteLogEntriesRequest) ProtoMessage() {}
+func (*WriteLogEntriesRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} }
+
+func (m *WriteLogEntriesRequest) GetLogName() string {
+ if m != nil {
+ return m.LogName
+ }
+ return ""
+}
+
+func (m *WriteLogEntriesRequest) GetResource() *google_api3.MonitoredResource {
+ if m != nil {
+ return m.Resource
+ }
+ return nil
+}
+
+func (m *WriteLogEntriesRequest) GetLabels() map[string]string {
+ if m != nil {
+ return m.Labels
+ }
+ return nil
+}
+
+func (m *WriteLogEntriesRequest) GetEntries() []*LogEntry {
+ if m != nil {
+ return m.Entries
+ }
+ return nil
+}
+
+func (m *WriteLogEntriesRequest) GetPartialSuccess() bool {
+ if m != nil {
+ return m.PartialSuccess
+ }
+ return false
+}
+
+// Result returned from WriteLogEntries.
+// empty
+type WriteLogEntriesResponse struct {
+}
+
+func (m *WriteLogEntriesResponse) Reset() { *m = WriteLogEntriesResponse{} }
+func (m *WriteLogEntriesResponse) String() string { return proto.CompactTextString(m) }
+func (*WriteLogEntriesResponse) ProtoMessage() {}
+func (*WriteLogEntriesResponse) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} }
+
+// Error details for WriteLogEntries with partial success.
+type WriteLogEntriesPartialErrors struct {
+ // When `WriteLogEntriesRequest.partial_success` is true, records the error
+ // status for entries that were not written due to a permanent error, keyed
+ // by the entry's zero-based index in `WriteLogEntriesRequest.entries`.
+ //
+ // Failed requests for which no entries are written will not include
+ // per-entry errors.
+ LogEntryErrors map[int32]*google_rpc.Status `protobuf:"bytes,1,rep,name=log_entry_errors,json=logEntryErrors" json:"log_entry_errors,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+}
+
+func (m *WriteLogEntriesPartialErrors) Reset() { *m = WriteLogEntriesPartialErrors{} }
+func (m *WriteLogEntriesPartialErrors) String() string { return proto.CompactTextString(m) }
+func (*WriteLogEntriesPartialErrors) ProtoMessage() {}
+func (*WriteLogEntriesPartialErrors) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{3} }
+
+func (m *WriteLogEntriesPartialErrors) GetLogEntryErrors() map[int32]*google_rpc.Status {
+ if m != nil {
+ return m.LogEntryErrors
+ }
+ return nil
+}
+
+// The parameters to `ListLogEntries`.
+type ListLogEntriesRequest struct {
+ // Deprecated. Use `resource_names` instead. One or more project identifiers
+ // or project numbers from which to retrieve log entries. Example:
+ // `"my-project-1A"`. If present, these project identifiers are converted to
+ // resource name format and added to the list of resources in
+ // `resource_names`.
+ ProjectIds []string `protobuf:"bytes,1,rep,name=project_ids,json=projectIds" json:"project_ids,omitempty"`
+ // Required. Names of one or more parent resources from which to
+ // retrieve log entries:
+ //
+ // "projects/[PROJECT_ID]"
+ // "organizations/[ORGANIZATION_ID]"
+ // "billingAccounts/[BILLING_ACCOUNT_ID]"
+ // "folders/[FOLDER_ID]"
+ //
+ // Projects listed in the `project_ids` field are added to this list.
+ ResourceNames []string `protobuf:"bytes,8,rep,name=resource_names,json=resourceNames" json:"resource_names,omitempty"`
+ // Optional. A filter that chooses which log entries to return. See [Advanced
+ // Logs Filters](/logging/docs/view/advanced_filters). Only log entries that
+ // match the filter are returned. An empty filter matches all log entries in
+ // the resources listed in `resource_names`. Referencing a parent resource
+ // that is not listed in `resource_names` will cause the filter to return no
+ // results.
+ // The maximum length of the filter is 20000 characters.
+ Filter string `protobuf:"bytes,2,opt,name=filter" json:"filter,omitempty"`
+ // Optional. How the results should be sorted. Presently, the only permitted
+ // values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
+ // option returns entries in order of increasing values of
+ // `LogEntry.timestamp` (oldest first), and the second option returns entries
+ // in order of decreasing timestamps (newest first). Entries with equal
+ // timestamps are returned in order of their `insert_id` values.
+ OrderBy string `protobuf:"bytes,3,opt,name=order_by,json=orderBy" json:"order_by,omitempty"`
+ // Optional. The maximum number of results to return from this request.
+ // Non-positive values are ignored. The presence of `next_page_token` in the
+ // response indicates that more results might be available.
+ PageSize int32 `protobuf:"varint,4,opt,name=page_size,json=pageSize" json:"page_size,omitempty"`
+ // Optional. If present, then retrieve the next batch of results from the
+ // preceding call to this method. `page_token` must be the value of
+ // `next_page_token` from the previous response. The values of other method
+ // parameters should be identical to those in the previous call.
+ PageToken string `protobuf:"bytes,5,opt,name=page_token,json=pageToken" json:"page_token,omitempty"`
+}
+
+func (m *ListLogEntriesRequest) Reset() { *m = ListLogEntriesRequest{} }
+func (m *ListLogEntriesRequest) String() string { return proto.CompactTextString(m) }
+func (*ListLogEntriesRequest) ProtoMessage() {}
+func (*ListLogEntriesRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{4} }
+
+func (m *ListLogEntriesRequest) GetProjectIds() []string {
+ if m != nil {
+ return m.ProjectIds
+ }
+ return nil
+}
+
+func (m *ListLogEntriesRequest) GetResourceNames() []string {
+ if m != nil {
+ return m.ResourceNames
+ }
+ return nil
+}
+
+func (m *ListLogEntriesRequest) GetFilter() string {
+ if m != nil {
+ return m.Filter
+ }
+ return ""
+}
+
+func (m *ListLogEntriesRequest) GetOrderBy() string {
+ if m != nil {
+ return m.OrderBy
+ }
+ return ""
+}
+
+func (m *ListLogEntriesRequest) GetPageSize() int32 {
+ if m != nil {
+ return m.PageSize
+ }
+ return 0
+}
+
+func (m *ListLogEntriesRequest) GetPageToken() string {
+ if m != nil {
+ return m.PageToken
+ }
+ return ""
+}
+
+// Result returned from `ListLogEntries`.
+type ListLogEntriesResponse struct {
+ // A list of log entries.
+ Entries []*LogEntry `protobuf:"bytes,1,rep,name=entries" json:"entries,omitempty"`
+ // If there might be more results than those appearing in this response, then
+ // `nextPageToken` is included. To get the next set of results, call this
+ // method again using the value of `nextPageToken` as `pageToken`.
+ //
+ // If a value for `next_page_token` appears and the `entries` field is empty,
+ // it means that the search found no log entries so far but it did not have
+ // time to search all the possible log entries. Retry the method with this
+ // value for `page_token` to continue the search. Alternatively, consider
+ // speeding up the search by changing your filter to specify a single log name
+ // or resource type, or to narrow the time range of the search.
+ NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"`
+}
+
+func (m *ListLogEntriesResponse) Reset() { *m = ListLogEntriesResponse{} }
+func (m *ListLogEntriesResponse) String() string { return proto.CompactTextString(m) }
+func (*ListLogEntriesResponse) ProtoMessage() {}
+func (*ListLogEntriesResponse) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{5} }
+
+func (m *ListLogEntriesResponse) GetEntries() []*LogEntry {
+ if m != nil {
+ return m.Entries
+ }
+ return nil
+}
+
+func (m *ListLogEntriesResponse) GetNextPageToken() string {
+ if m != nil {
+ return m.NextPageToken
+ }
+ return ""
+}
+
+// The parameters to ListMonitoredResourceDescriptors
+type ListMonitoredResourceDescriptorsRequest struct {
+ // Optional. The maximum number of results to return from this request.
+ // Non-positive values are ignored. The presence of `nextPageToken` in the
+ // response indicates that more results might be available.
+ PageSize int32 `protobuf:"varint,1,opt,name=page_size,json=pageSize" json:"page_size,omitempty"`
+ // Optional. If present, then retrieve the next batch of results from the
+ // preceding call to this method. `pageToken` must be the value of
+ // `nextPageToken` from the previous response. The values of other method
+ // parameters should be identical to those in the previous call.
+ PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken" json:"page_token,omitempty"`
+}
+
+func (m *ListMonitoredResourceDescriptorsRequest) Reset() {
+ *m = ListMonitoredResourceDescriptorsRequest{}
+}
+func (m *ListMonitoredResourceDescriptorsRequest) String() string { return proto.CompactTextString(m) }
+func (*ListMonitoredResourceDescriptorsRequest) ProtoMessage() {}
+func (*ListMonitoredResourceDescriptorsRequest) Descriptor() ([]byte, []int) {
+ return fileDescriptor1, []int{6}
+}
+
+func (m *ListMonitoredResourceDescriptorsRequest) GetPageSize() int32 {
+ if m != nil {
+ return m.PageSize
+ }
+ return 0
+}
+
+func (m *ListMonitoredResourceDescriptorsRequest) GetPageToken() string {
+ if m != nil {
+ return m.PageToken
+ }
+ return ""
+}
+
+// Result returned from ListMonitoredResourceDescriptors.
+type ListMonitoredResourceDescriptorsResponse struct {
+ // A list of resource descriptors.
+ ResourceDescriptors []*google_api3.MonitoredResourceDescriptor `protobuf:"bytes,1,rep,name=resource_descriptors,json=resourceDescriptors" json:"resource_descriptors,omitempty"`
+ // If there might be more results than those appearing in this response, then
+ // `nextPageToken` is included. To get the next set of results, call this
+ // method again using the value of `nextPageToken` as `pageToken`.
+ NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"`
+}
+
+func (m *ListMonitoredResourceDescriptorsResponse) Reset() {
+ *m = ListMonitoredResourceDescriptorsResponse{}
+}
+func (m *ListMonitoredResourceDescriptorsResponse) String() string { return proto.CompactTextString(m) }
+func (*ListMonitoredResourceDescriptorsResponse) ProtoMessage() {}
+func (*ListMonitoredResourceDescriptorsResponse) Descriptor() ([]byte, []int) {
+ return fileDescriptor1, []int{7}
+}
+
+func (m *ListMonitoredResourceDescriptorsResponse) GetResourceDescriptors() []*google_api3.MonitoredResourceDescriptor {
+ if m != nil {
+ return m.ResourceDescriptors
+ }
+ return nil
+}
+
+func (m *ListMonitoredResourceDescriptorsResponse) GetNextPageToken() string {
+ if m != nil {
+ return m.NextPageToken
+ }
+ return ""
+}
+
+// The parameters to ListLogs.
+type ListLogsRequest struct {
+ // Required. The resource name that owns the logs:
+ //
+ // "projects/[PROJECT_ID]"
+ // "organizations/[ORGANIZATION_ID]"
+ // "billingAccounts/[BILLING_ACCOUNT_ID]"
+ // "folders/[FOLDER_ID]"
+ Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
+ // Optional. The maximum number of results to return from this request.
+ // Non-positive values are ignored. The presence of `nextPageToken` in the
+ // response indicates that more results might be available.
+ PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize" json:"page_size,omitempty"`
+ // Optional. If present, then retrieve the next batch of results from the
+ // preceding call to this method. `pageToken` must be the value of
+ // `nextPageToken` from the previous response. The values of other method
+ // parameters should be identical to those in the previous call.
+ PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken" json:"page_token,omitempty"`
+}
+
+func (m *ListLogsRequest) Reset() { *m = ListLogsRequest{} }
+func (m *ListLogsRequest) String() string { return proto.CompactTextString(m) }
+func (*ListLogsRequest) ProtoMessage() {}
+func (*ListLogsRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{8} }
+
+func (m *ListLogsRequest) GetParent() string {
+ if m != nil {
+ return m.Parent
+ }
+ return ""
+}
+
+func (m *ListLogsRequest) GetPageSize() int32 {
+ if m != nil {
+ return m.PageSize
+ }
+ return 0
+}
+
+func (m *ListLogsRequest) GetPageToken() string {
+ if m != nil {
+ return m.PageToken
+ }
+ return ""
+}
+
+// Result returned from ListLogs.
+type ListLogsResponse struct {
+ // A list of log names. For example,
+ // `"projects/my-project/syslog"` or
+ // `"organizations/123/cloudresourcemanager.googleapis.com%2Factivity"`.
+ LogNames []string `protobuf:"bytes,3,rep,name=log_names,json=logNames" json:"log_names,omitempty"`
+ // If there might be more results than those appearing in this response, then
+ // `nextPageToken` is included. To get the next set of results, call this
+ // method again using the value of `nextPageToken` as `pageToken`.
+ NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"`
+}
+
+func (m *ListLogsResponse) Reset() { *m = ListLogsResponse{} }
+func (m *ListLogsResponse) String() string { return proto.CompactTextString(m) }
+func (*ListLogsResponse) ProtoMessage() {}
+func (*ListLogsResponse) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{9} }
+
+func (m *ListLogsResponse) GetLogNames() []string {
+ if m != nil {
+ return m.LogNames
+ }
+ return nil
+}
+
+func (m *ListLogsResponse) GetNextPageToken() string {
+ if m != nil {
+ return m.NextPageToken
+ }
+ return ""
+}
+
+func init() {
+ proto.RegisterType((*DeleteLogRequest)(nil), "google.logging.v2.DeleteLogRequest")
+ proto.RegisterType((*WriteLogEntriesRequest)(nil), "google.logging.v2.WriteLogEntriesRequest")
+ proto.RegisterType((*WriteLogEntriesResponse)(nil), "google.logging.v2.WriteLogEntriesResponse")
+ proto.RegisterType((*WriteLogEntriesPartialErrors)(nil), "google.logging.v2.WriteLogEntriesPartialErrors")
+ proto.RegisterType((*ListLogEntriesRequest)(nil), "google.logging.v2.ListLogEntriesRequest")
+ proto.RegisterType((*ListLogEntriesResponse)(nil), "google.logging.v2.ListLogEntriesResponse")
+ proto.RegisterType((*ListMonitoredResourceDescriptorsRequest)(nil), "google.logging.v2.ListMonitoredResourceDescriptorsRequest")
+ proto.RegisterType((*ListMonitoredResourceDescriptorsResponse)(nil), "google.logging.v2.ListMonitoredResourceDescriptorsResponse")
+ proto.RegisterType((*ListLogsRequest)(nil), "google.logging.v2.ListLogsRequest")
+ proto.RegisterType((*ListLogsResponse)(nil), "google.logging.v2.ListLogsResponse")
+}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for LoggingServiceV2 service
+
+type LoggingServiceV2Client interface {
+ // Deletes all the log entries in a log.
+ // The log reappears if it receives new entries.
+ // Log entries written shortly before the delete operation might not be
+ // deleted.
+ DeleteLog(ctx context.Context, in *DeleteLogRequest, opts ...grpc.CallOption) (*google_protobuf5.Empty, error)
+ // Writes log entries to Stackdriver Logging.
+ WriteLogEntries(ctx context.Context, in *WriteLogEntriesRequest, opts ...grpc.CallOption) (*WriteLogEntriesResponse, error)
+ // Lists log entries. Use this method to retrieve log entries from
+ // Stackdriver Logging. For ways to export log entries, see
+ // [Exporting Logs](/logging/docs/export).
+ ListLogEntries(ctx context.Context, in *ListLogEntriesRequest, opts ...grpc.CallOption) (*ListLogEntriesResponse, error)
+ // Lists the descriptors for monitored resource types used by Stackdriver
+ // Logging.
+ ListMonitoredResourceDescriptors(ctx context.Context, in *ListMonitoredResourceDescriptorsRequest, opts ...grpc.CallOption) (*ListMonitoredResourceDescriptorsResponse, error)
+ // Lists the logs in projects, organizations, folders, or billing accounts.
+ // Only logs that have entries are listed.
+ ListLogs(ctx context.Context, in *ListLogsRequest, opts ...grpc.CallOption) (*ListLogsResponse, error)
+}
+
+type loggingServiceV2Client struct {
+ cc *grpc.ClientConn
+}
+
+func NewLoggingServiceV2Client(cc *grpc.ClientConn) LoggingServiceV2Client {
+ return &loggingServiceV2Client{cc}
+}
+
+func (c *loggingServiceV2Client) DeleteLog(ctx context.Context, in *DeleteLogRequest, opts ...grpc.CallOption) (*google_protobuf5.Empty, error) {
+ out := new(google_protobuf5.Empty)
+ err := grpc.Invoke(ctx, "/google.logging.v2.LoggingServiceV2/DeleteLog", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *loggingServiceV2Client) WriteLogEntries(ctx context.Context, in *WriteLogEntriesRequest, opts ...grpc.CallOption) (*WriteLogEntriesResponse, error) {
+ out := new(WriteLogEntriesResponse)
+ err := grpc.Invoke(ctx, "/google.logging.v2.LoggingServiceV2/WriteLogEntries", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *loggingServiceV2Client) ListLogEntries(ctx context.Context, in *ListLogEntriesRequest, opts ...grpc.CallOption) (*ListLogEntriesResponse, error) {
+ out := new(ListLogEntriesResponse)
+ err := grpc.Invoke(ctx, "/google.logging.v2.LoggingServiceV2/ListLogEntries", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *loggingServiceV2Client) ListMonitoredResourceDescriptors(ctx context.Context, in *ListMonitoredResourceDescriptorsRequest, opts ...grpc.CallOption) (*ListMonitoredResourceDescriptorsResponse, error) {
+ out := new(ListMonitoredResourceDescriptorsResponse)
+ err := grpc.Invoke(ctx, "/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *loggingServiceV2Client) ListLogs(ctx context.Context, in *ListLogsRequest, opts ...grpc.CallOption) (*ListLogsResponse, error) {
+ out := new(ListLogsResponse)
+ err := grpc.Invoke(ctx, "/google.logging.v2.LoggingServiceV2/ListLogs", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for LoggingServiceV2 service
+
+type LoggingServiceV2Server interface {
+ // Deletes all the log entries in a log.
+ // The log reappears if it receives new entries.
+ // Log entries written shortly before the delete operation might not be
+ // deleted.
+ DeleteLog(context.Context, *DeleteLogRequest) (*google_protobuf5.Empty, error)
+ // Writes log entries to Stackdriver Logging.
+ WriteLogEntries(context.Context, *WriteLogEntriesRequest) (*WriteLogEntriesResponse, error)
+ // Lists log entries. Use this method to retrieve log entries from
+ // Stackdriver Logging. For ways to export log entries, see
+ // [Exporting Logs](/logging/docs/export).
+ ListLogEntries(context.Context, *ListLogEntriesRequest) (*ListLogEntriesResponse, error)
+ // Lists the descriptors for monitored resource types used by Stackdriver
+ // Logging.
+ ListMonitoredResourceDescriptors(context.Context, *ListMonitoredResourceDescriptorsRequest) (*ListMonitoredResourceDescriptorsResponse, error)
+ // Lists the logs in projects, organizations, folders, or billing accounts.
+ // Only logs that have entries are listed.
+ ListLogs(context.Context, *ListLogsRequest) (*ListLogsResponse, error)
+}
+
+func RegisterLoggingServiceV2Server(s *grpc.Server, srv LoggingServiceV2Server) {
+ s.RegisterService(&_LoggingServiceV2_serviceDesc, srv)
+}
+
+func _LoggingServiceV2_DeleteLog_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(DeleteLogRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(LoggingServiceV2Server).DeleteLog(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.LoggingServiceV2/DeleteLog",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(LoggingServiceV2Server).DeleteLog(ctx, req.(*DeleteLogRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _LoggingServiceV2_WriteLogEntries_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(WriteLogEntriesRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(LoggingServiceV2Server).WriteLogEntries(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.LoggingServiceV2/WriteLogEntries",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(LoggingServiceV2Server).WriteLogEntries(ctx, req.(*WriteLogEntriesRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _LoggingServiceV2_ListLogEntries_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListLogEntriesRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(LoggingServiceV2Server).ListLogEntries(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.LoggingServiceV2/ListLogEntries",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(LoggingServiceV2Server).ListLogEntries(ctx, req.(*ListLogEntriesRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _LoggingServiceV2_ListMonitoredResourceDescriptors_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListMonitoredResourceDescriptorsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(LoggingServiceV2Server).ListMonitoredResourceDescriptors(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(LoggingServiceV2Server).ListMonitoredResourceDescriptors(ctx, req.(*ListMonitoredResourceDescriptorsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _LoggingServiceV2_ListLogs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListLogsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(LoggingServiceV2Server).ListLogs(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.LoggingServiceV2/ListLogs",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(LoggingServiceV2Server).ListLogs(ctx, req.(*ListLogsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _LoggingServiceV2_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "google.logging.v2.LoggingServiceV2",
+ HandlerType: (*LoggingServiceV2Server)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "DeleteLog",
+ Handler: _LoggingServiceV2_DeleteLog_Handler,
+ },
+ {
+ MethodName: "WriteLogEntries",
+ Handler: _LoggingServiceV2_WriteLogEntries_Handler,
+ },
+ {
+ MethodName: "ListLogEntries",
+ Handler: _LoggingServiceV2_ListLogEntries_Handler,
+ },
+ {
+ MethodName: "ListMonitoredResourceDescriptors",
+ Handler: _LoggingServiceV2_ListMonitoredResourceDescriptors_Handler,
+ },
+ {
+ MethodName: "ListLogs",
+ Handler: _LoggingServiceV2_ListLogs_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "google/logging/v2/logging.proto",
+}
+
+func init() { proto.RegisterFile("google/logging/v2/logging.proto", fileDescriptor1) }
+
+var fileDescriptor1 = []byte{
+ // 975 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x56, 0xcd, 0x6e, 0xdb, 0x46,
+ 0x10, 0x06, 0xa5, 0xd8, 0x91, 0x46, 0x8d, 0xad, 0x6c, 0x62, 0x59, 0x91, 0x9c, 0x58, 0xa5, 0x9b,
+ 0x5a, 0x11, 0x10, 0x12, 0x55, 0x11, 0x20, 0x71, 0xd0, 0x8b, 0x13, 0xa3, 0x28, 0xe0, 0x14, 0x06,
+ 0xdd, 0x26, 0x40, 0x2e, 0x02, 0x25, 0x4d, 0x88, 0x6d, 0x28, 0x2e, 0xbb, 0xbb, 0x92, 0xab, 0x04,
+ 0xe9, 0x21, 0x87, 0xbe, 0x40, 0xdf, 0xa2, 0x87, 0xbe, 0x45, 0xaf, 0xbd, 0xf4, 0xd2, 0x43, 0x8f,
+ 0x79, 0x88, 0x1e, 0x0b, 0xee, 0x2e, 0x65, 0xea, 0x27, 0xb2, 0xdc, 0x9b, 0x76, 0xe6, 0xdb, 0x99,
+ 0xf9, 0x86, 0xdf, 0xcc, 0x0a, 0x76, 0x03, 0xc6, 0x82, 0x10, 0xdd, 0x90, 0x05, 0x01, 0x8d, 0x02,
+ 0x77, 0xd4, 0x4e, 0x7f, 0x3a, 0x31, 0x67, 0x92, 0x91, 0xeb, 0x1a, 0xe0, 0xa4, 0xd6, 0x51, 0xbb,
+ 0xb6, 0x63, 0xee, 0xf8, 0x31, 0x75, 0xfd, 0x28, 0x62, 0xd2, 0x97, 0x94, 0x45, 0x42, 0x5f, 0xa8,
+ 0xed, 0x65, 0xbc, 0x03, 0x16, 0x51, 0xc9, 0x38, 0xf6, 0x3b, 0x1c, 0x05, 0x1b, 0xf2, 0x1e, 0x1a,
+ 0xd0, 0xa7, 0x0b, 0xd3, 0x76, 0x30, 0x92, 0x7c, 0x6c, 0x20, 0x77, 0x0c, 0x44, 0x9d, 0xba, 0xc3,
+ 0x57, 0x6e, 0x7f, 0xc8, 0x55, 0x22, 0xe3, 0xaf, 0xcf, 0xfa, 0x71, 0x10, 0xcb, 0xf4, 0xf2, 0xee,
+ 0xac, 0x53, 0xd2, 0x01, 0x0a, 0xe9, 0x0f, 0x62, 0x03, 0xd8, 0x36, 0x00, 0x1e, 0xf7, 0x5c, 0x21,
+ 0x7d, 0x39, 0x34, 0xe5, 0xdb, 0xf7, 0xa1, 0xfc, 0x14, 0x43, 0x94, 0x78, 0xcc, 0x02, 0x0f, 0x7f,
+ 0x1c, 0xa2, 0x90, 0xe4, 0x16, 0x14, 0x92, 0xea, 0x22, 0x7f, 0x80, 0x55, 0xab, 0x61, 0x35, 0x8b,
+ 0xde, 0xd5, 0x90, 0x05, 0xdf, 0xfa, 0x03, 0xb4, 0xff, 0xce, 0x41, 0xe5, 0x05, 0xa7, 0x0a, 0x7e,
+ 0x14, 0x49, 0x4e, 0x51, 0x5c, 0x7c, 0x8b, 0x3c, 0x82, 0x42, 0xda, 0x90, 0x6a, 0xae, 0x61, 0x35,
+ 0x4b, 0xed, 0xdb, 0x8e, 0xe9, 0xb3, 0x1f, 0x53, 0xe7, 0x59, 0xda, 0x36, 0xcf, 0x80, 0xbc, 0x09,
+ 0x9c, 0x3c, 0x83, 0xf5, 0xd0, 0xef, 0x62, 0x28, 0xaa, 0xf9, 0x46, 0xbe, 0x59, 0x6a, 0x3f, 0x70,
+ 0xe6, 0x3e, 0x90, 0xb3, 0xb8, 0x20, 0xe7, 0x58, 0xdd, 0x4b, 0x8c, 0x63, 0xcf, 0x04, 0x21, 0x0f,
+ 0xe0, 0x2a, 0x6a, 0x54, 0xf5, 0x8a, 0x8a, 0x57, 0x5f, 0x10, 0xcf, 0x84, 0x1a, 0x7b, 0x29, 0x96,
+ 0xec, 0xc3, 0x66, 0xec, 0x73, 0x49, 0xfd, 0xb0, 0x23, 0x86, 0xbd, 0x1e, 0x0a, 0x51, 0x5d, 0x6b,
+ 0x58, 0xcd, 0x82, 0xb7, 0x61, 0xcc, 0xa7, 0xda, 0x5a, 0x7b, 0x04, 0xa5, 0x4c, 0x5a, 0x52, 0x86,
+ 0xfc, 0x6b, 0x1c, 0x9b, 0x76, 0x24, 0x3f, 0xc9, 0x4d, 0x58, 0x1b, 0xf9, 0xe1, 0x50, 0xf7, 0xa1,
+ 0xe8, 0xe9, 0xc3, 0x41, 0xee, 0xa1, 0x65, 0xdf, 0x82, 0xed, 0x39, 0x22, 0x22, 0x66, 0x91, 0x40,
+ 0xfb, 0x83, 0x05, 0x3b, 0x33, 0xbe, 0x13, 0x9d, 0xf7, 0x88, 0x73, 0xc6, 0x05, 0x19, 0x40, 0x79,
+ 0xa2, 0xa7, 0x0e, 0x2a, 0x5b, 0xd5, 0x52, 0xfc, 0x9e, 0x5c, 0xdc, 0xaf, 0xa9, 0x50, 0x13, 0xf2,
+ 0xfa, 0xa8, 0xfb, 0xb0, 0x11, 0x4e, 0x19, 0x6b, 0xdf, 0xc3, 0x8d, 0x05, 0xb0, 0x2c, 0xdb, 0x35,
+ 0xcd, 0xb6, 0x99, 0x65, 0x5b, 0x6a, 0x93, 0xb4, 0x18, 0x1e, 0xf7, 0x9c, 0x53, 0x25, 0xc3, 0x6c,
+ 0x07, 0xfe, 0xb4, 0x60, 0xeb, 0x98, 0x0a, 0x39, 0xaf, 0xad, 0x5d, 0x28, 0xc5, 0x9c, 0xfd, 0x80,
+ 0x3d, 0xd9, 0xa1, 0x7d, 0x4d, 0xad, 0xe8, 0x81, 0x31, 0x7d, 0xd3, 0x17, 0xe4, 0x2e, 0x6c, 0xa4,
+ 0x92, 0x51, 0x0a, 0x14, 0xd5, 0x82, 0xc2, 0x5c, 0x4b, 0xad, 0x89, 0x0e, 0x05, 0xa9, 0xc0, 0xfa,
+ 0x2b, 0x1a, 0x4a, 0xe4, 0xa6, 0xfd, 0xe6, 0x94, 0x68, 0x97, 0xf1, 0x3e, 0xf2, 0x4e, 0x77, 0x5c,
+ 0xcd, 0x6b, 0xed, 0xaa, 0xf3, 0xe1, 0x98, 0xd4, 0xa1, 0x18, 0xfb, 0x01, 0x76, 0x04, 0x7d, 0x83,
+ 0xd5, 0x2b, 0x8a, 0x5a, 0x21, 0x31, 0x9c, 0xd2, 0x37, 0x48, 0x6e, 0x03, 0x28, 0xa7, 0x64, 0xaf,
+ 0x31, 0x52, 0x92, 0x28, 0x7a, 0x0a, 0xfe, 0x5d, 0x62, 0xb0, 0xcf, 0xa0, 0x32, 0xcb, 0x47, 0x7f,
+ 0xd1, 0xac, 0x0e, 0xad, 0x4b, 0xe8, 0xf0, 0x73, 0xd8, 0x8c, 0xf0, 0x27, 0xd9, 0xc9, 0x24, 0xd5,
+ 0x44, 0xae, 0x25, 0xe6, 0x93, 0x49, 0x62, 0x84, 0xfd, 0x24, 0xf1, 0xdc, 0x60, 0x3d, 0x45, 0xd1,
+ 0xe3, 0x34, 0x96, 0x8c, 0x4f, 0x5a, 0x3b, 0xc5, 0xcf, 0x5a, 0xca, 0x2f, 0x37, 0xcb, 0xef, 0x77,
+ 0x0b, 0x9a, 0x17, 0xe7, 0x31, 0x94, 0x5f, 0xc2, 0xcd, 0xc9, 0x27, 0xea, 0x9f, 0xfb, 0x0d, 0xff,
+ 0xfd, 0xa5, 0x0b, 0xe1, 0x3c, 0x9e, 0x77, 0x83, 0xcf, 0xe7, 0xb8, 0x44, 0x5f, 0x36, 0xcd, 0x07,
+ 0x99, 0xf0, 0xaf, 0xc0, 0x7a, 0xec, 0x73, 0x8c, 0xa4, 0x99, 0x52, 0x73, 0x9a, 0xee, 0x4b, 0x6e,
+ 0x69, 0x5f, 0xf2, 0xb3, 0x7d, 0x79, 0x01, 0xe5, 0xf3, 0x34, 0x86, 0x7e, 0x1d, 0x8a, 0xe9, 0x7a,
+ 0xd4, 0xbb, 0xac, 0xe8, 0x15, 0xcc, 0x7e, 0x5c, 0xb9, 0xfe, 0xf6, 0x3f, 0x6b, 0x50, 0x3e, 0xd6,
+ 0x02, 0x39, 0x45, 0x3e, 0xa2, 0x3d, 0x7c, 0xde, 0x26, 0x67, 0x50, 0x9c, 0xac, 0x70, 0xb2, 0xb7,
+ 0x40, 0x47, 0xb3, 0x0b, 0xbe, 0x56, 0x49, 0x41, 0xe9, 0x7b, 0xe1, 0x1c, 0x25, 0x8f, 0x89, 0x7d,
+ 0xff, 0xfd, 0x5f, 0x1f, 0x7e, 0xcd, 0xed, 0xb7, 0xee, 0xba, 0xa3, 0x76, 0x17, 0xa5, 0xff, 0x85,
+ 0xfb, 0x36, 0xad, 0xf9, 0x2b, 0x33, 0x6c, 0xc2, 0x6d, 0x25, 0x4f, 0x97, 0x70, 0x5b, 0xef, 0xc8,
+ 0x2f, 0x16, 0x6c, 0xce, 0xec, 0x12, 0x72, 0x6f, 0xe5, 0xfd, 0x5c, 0x6b, 0xad, 0x02, 0x35, 0x1b,
+ 0x70, 0x47, 0x55, 0x56, 0xb1, 0xaf, 0x27, 0x4f, 0xa7, 0x99, 0x86, 0x83, 0xb3, 0x04, 0x7c, 0x60,
+ 0xb5, 0xc8, 0x7b, 0x0b, 0x36, 0xa6, 0x07, 0x8d, 0x34, 0x17, 0xcd, 0xd3, 0xa2, 0xdd, 0x52, 0xbb,
+ 0xb7, 0x02, 0xd2, 0x54, 0x51, 0x57, 0x55, 0x6c, 0xd9, 0xe5, 0x6c, 0x15, 0x21, 0x15, 0x32, 0x29,
+ 0xe2, 0x0f, 0x0b, 0x1a, 0x17, 0x0d, 0x03, 0x39, 0xf8, 0x48, 0xb2, 0x15, 0x26, 0xb5, 0xf6, 0xf8,
+ 0x7f, 0xdd, 0x35, 0xa5, 0x37, 0x55, 0xe9, 0x36, 0x69, 0x24, 0xa5, 0x0f, 0x96, 0x95, 0x38, 0x86,
+ 0x42, 0x2a, 0x5e, 0x62, 0x7f, 0xbc, 0x37, 0x93, 0xb2, 0xf6, 0x96, 0x62, 0x4c, 0xfa, 0xcf, 0x54,
+ 0xfa, 0x3b, 0x64, 0x27, 0x49, 0xff, 0x56, 0x8f, 0x58, 0x46, 0x52, 0xef, 0x94, 0xa6, 0x0e, 0x7f,
+ 0x86, 0xad, 0x1e, 0x1b, 0xcc, 0xc7, 0x3b, 0xfc, 0xc4, 0x88, 0xfe, 0x24, 0xd1, 0xeb, 0x89, 0xf5,
+ 0xf2, 0xa1, 0x81, 0x04, 0x2c, 0xf4, 0xa3, 0xc0, 0x61, 0x3c, 0x70, 0x03, 0x8c, 0x94, 0x9a, 0x5d,
+ 0xed, 0xf2, 0x63, 0x2a, 0x32, 0x7f, 0xb7, 0x1e, 0x9b, 0x9f, 0xff, 0x5a, 0xd6, 0x6f, 0xb9, 0xed,
+ 0xaf, 0xf5, 0xed, 0x27, 0x21, 0x1b, 0xf6, 0x1d, 0x13, 0xda, 0x79, 0xde, 0xee, 0xae, 0xab, 0x08,
+ 0x5f, 0xfe, 0x17, 0x00, 0x00, 0xff, 0xff, 0xe2, 0xc4, 0xaa, 0x91, 0x26, 0x0a, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/logging/v2/logging_config.pb.go b/vendor/google.golang.org/genproto/googleapis/logging/v2/logging_config.pb.go
new file mode 100644
index 0000000..f96a1a5
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/logging/v2/logging_config.pb.go
@@ -0,0 +1,735 @@
+// Code generated by protoc-gen-go.
+// source: google/logging/v2/logging_config.proto
+// DO NOT EDIT!
+
+package logging
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "google.golang.org/genproto/googleapis/api/annotations"
+import google_protobuf5 "github.com/golang/protobuf/ptypes/empty"
+import google_protobuf4 "github.com/golang/protobuf/ptypes/timestamp"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// Available log entry formats. Log entries can be written to Stackdriver
+// Logging in either format and can be exported in either format.
+// Version 2 is the preferred format.
+type LogSink_VersionFormat int32
+
+const (
+ // An unspecified format version that will default to V2.
+ LogSink_VERSION_FORMAT_UNSPECIFIED LogSink_VersionFormat = 0
+ // `LogEntry` version 2 format.
+ LogSink_V2 LogSink_VersionFormat = 1
+ // `LogEntry` version 1 format.
+ LogSink_V1 LogSink_VersionFormat = 2
+)
+
+var LogSink_VersionFormat_name = map[int32]string{
+ 0: "VERSION_FORMAT_UNSPECIFIED",
+ 1: "V2",
+ 2: "V1",
+}
+var LogSink_VersionFormat_value = map[string]int32{
+ "VERSION_FORMAT_UNSPECIFIED": 0,
+ "V2": 1,
+ "V1": 2,
+}
+
+func (x LogSink_VersionFormat) String() string {
+ return proto.EnumName(LogSink_VersionFormat_name, int32(x))
+}
+func (LogSink_VersionFormat) EnumDescriptor() ([]byte, []int) { return fileDescriptor2, []int{0, 0} }
+
+// Describes a sink used to export log entries to one of the following
+// destinations in any project: a Cloud Storage bucket, a BigQuery dataset, or a
+// Cloud Pub/Sub topic. A logs filter controls which log entries are
+// exported. The sink must be created within a project, organization, billing
+// account, or folder.
+type LogSink struct {
+ // Required. The client-assigned sink identifier, unique within the
+ // project. Example: `"my-syslog-errors-to-pubsub"`. Sink identifiers are
+ // limited to 100 characters and can include only the following characters:
+ // upper and lower-case alphanumeric characters, underscores, hyphens, and
+ // periods.
+ Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ // Required. The export destination:
+ //
+ // "storage.googleapis.com/[GCS_BUCKET]"
+ // "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET]"
+ // "pubsub.googleapis.com/projects/[PROJECT_ID]/topics/[TOPIC_ID]"
+ //
+ // The sink's `writer_identity`, set when the sink is created, must
+ // have permission to write to the destination or else the log
+ // entries are not exported. For more information, see
+ // [Exporting Logs With Sinks](/logging/docs/api/tasks/exporting-logs).
+ Destination string `protobuf:"bytes,3,opt,name=destination" json:"destination,omitempty"`
+ // Optional.
+ // An [advanced logs filter](/logging/docs/view/advanced_filters). The only
+ // exported log entries are those that are in the resource owning the sink and
+ // that match the filter. The filter must use the log entry format specified
+ // by the `output_version_format` parameter. For example, in the v2 format:
+ //
+ // logName="projects/[PROJECT_ID]/logs/[LOG_ID]" AND severity>=ERROR
+ Filter string `protobuf:"bytes,5,opt,name=filter" json:"filter,omitempty"`
+ // Optional. The log entry format to use for this sink's exported log
+ // entries. The v2 format is used by default.
+ // **The v1 format is deprecated** and should be used only as part of a
+ // migration effort to v2.
+ // See [Migration to the v2 API](/logging/docs/api/v2/migration-to-v2).
+ OutputVersionFormat LogSink_VersionFormat `protobuf:"varint,6,opt,name=output_version_format,json=outputVersionFormat,enum=google.logging.v2.LogSink_VersionFormat" json:"output_version_format,omitempty"`
+ // Output only. An IAM identity&mdash;a service account or group&mdash;under
+ // which Stackdriver Logging writes the exported log entries to the sink's
+ // destination. This field is set by
+ // [sinks.create](/logging/docs/api/reference/rest/v2/projects.sinks/create)
+ // and
+ // [sinks.update](/logging/docs/api/reference/rest/v2/projects.sinks/update),
+ // based on the setting of `unique_writer_identity` in those methods.
+ //
+ // Until you grant this identity write-access to the destination, log entry
+ // exports from this sink will fail. For more information,
+ // see [Granting access for a
+ // resource](/iam/docs/granting-roles-to-service-accounts#granting_access_to_a_service_account_for_a_resource).
+ // Consult the destination service's documentation to determine the
+ // appropriate IAM roles to assign to the identity.
+ WriterIdentity string `protobuf:"bytes,8,opt,name=writer_identity,json=writerIdentity" json:"writer_identity,omitempty"`
+ // Optional. This field applies only to sinks owned by organizations and
+ // folders. If the field is false, the default, only the logs owned by the
+ // sink's parent resource are available for export. If the field is true, then
+ // logs from all the projects, folders, and billing accounts contained in the
+ // sink's parent resource are also available for export. Whether a particular
+ // log entry from the children is exported depends on the sink's filter
+ // expression. For example, if this field is true, then the filter
+ // `resource.type=gce_instance` would export all Compute Engine VM instance
+ // log entries from all projects in the sink's parent. To only export entries
+ // from certain child projects, filter on the project part of the log name:
+ //
+ // logName:("projects/test-project1/" OR "projects/test-project2/") AND
+ // resource.type=gce_instance
+ IncludeChildren bool `protobuf:"varint,9,opt,name=include_children,json=includeChildren" json:"include_children,omitempty"`
+ // Optional. The time at which this sink will begin exporting log entries.
+ // Log entries are exported only if their timestamp is not earlier than the
+ // start time. The default value of this field is the time the sink is
+ // created or updated.
+ StartTime *google_protobuf4.Timestamp `protobuf:"bytes,10,opt,name=start_time,json=startTime" json:"start_time,omitempty"`
+ // Optional. The time at which this sink will stop exporting log entries. Log
+ // entries are exported only if their timestamp is earlier than the end time.
+ // If this field is not supplied, there is no end time. If both a start time
+ // and an end time are provided, then the end time must be later than the
+ // start time.
+ EndTime *google_protobuf4.Timestamp `protobuf:"bytes,11,opt,name=end_time,json=endTime" json:"end_time,omitempty"`
+}
+
+func (m *LogSink) Reset() { *m = LogSink{} }
+func (m *LogSink) String() string { return proto.CompactTextString(m) }
+func (*LogSink) ProtoMessage() {}
+func (*LogSink) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{0} }
+
+func (m *LogSink) GetName() string {
+ if m != nil {
+ return m.Name
+ }
+ return ""
+}
+
+func (m *LogSink) GetDestination() string {
+ if m != nil {
+ return m.Destination
+ }
+ return ""
+}
+
+func (m *LogSink) GetFilter() string {
+ if m != nil {
+ return m.Filter
+ }
+ return ""
+}
+
+func (m *LogSink) GetOutputVersionFormat() LogSink_VersionFormat {
+ if m != nil {
+ return m.OutputVersionFormat
+ }
+ return LogSink_VERSION_FORMAT_UNSPECIFIED
+}
+
+func (m *LogSink) GetWriterIdentity() string {
+ if m != nil {
+ return m.WriterIdentity
+ }
+ return ""
+}
+
+func (m *LogSink) GetIncludeChildren() bool {
+ if m != nil {
+ return m.IncludeChildren
+ }
+ return false
+}
+
+func (m *LogSink) GetStartTime() *google_protobuf4.Timestamp {
+ if m != nil {
+ return m.StartTime
+ }
+ return nil
+}
+
+func (m *LogSink) GetEndTime() *google_protobuf4.Timestamp {
+ if m != nil {
+ return m.EndTime
+ }
+ return nil
+}
+
+// The parameters to `ListSinks`.
+type ListSinksRequest struct {
+ // Required. The parent resource whose sinks are to be listed:
+ //
+ // "projects/[PROJECT_ID]"
+ // "organizations/[ORGANIZATION_ID]"
+ // "billingAccounts/[BILLING_ACCOUNT_ID]"
+ // "folders/[FOLDER_ID]"
+ Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
+ // Optional. If present, then retrieve the next batch of results from the
+ // preceding call to this method. `pageToken` must be the value of
+ // `nextPageToken` from the previous response. The values of other method
+ // parameters should be identical to those in the previous call.
+ PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken" json:"page_token,omitempty"`
+ // Optional. The maximum number of results to return from this request.
+ // Non-positive values are ignored. The presence of `nextPageToken` in the
+ // response indicates that more results might be available.
+ PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize" json:"page_size,omitempty"`
+}
+
+func (m *ListSinksRequest) Reset() { *m = ListSinksRequest{} }
+func (m *ListSinksRequest) String() string { return proto.CompactTextString(m) }
+func (*ListSinksRequest) ProtoMessage() {}
+func (*ListSinksRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{1} }
+
+func (m *ListSinksRequest) GetParent() string {
+ if m != nil {
+ return m.Parent
+ }
+ return ""
+}
+
+func (m *ListSinksRequest) GetPageToken() string {
+ if m != nil {
+ return m.PageToken
+ }
+ return ""
+}
+
+func (m *ListSinksRequest) GetPageSize() int32 {
+ if m != nil {
+ return m.PageSize
+ }
+ return 0
+}
+
+// Result returned from `ListSinks`.
+type ListSinksResponse struct {
+ // A list of sinks.
+ Sinks []*LogSink `protobuf:"bytes,1,rep,name=sinks" json:"sinks,omitempty"`
+ // If there might be more results than appear in this response, then
+ // `nextPageToken` is included. To get the next set of results, call the same
+ // method again using the value of `nextPageToken` as `pageToken`.
+ NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"`
+}
+
+func (m *ListSinksResponse) Reset() { *m = ListSinksResponse{} }
+func (m *ListSinksResponse) String() string { return proto.CompactTextString(m) }
+func (*ListSinksResponse) ProtoMessage() {}
+func (*ListSinksResponse) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{2} }
+
+func (m *ListSinksResponse) GetSinks() []*LogSink {
+ if m != nil {
+ return m.Sinks
+ }
+ return nil
+}
+
+func (m *ListSinksResponse) GetNextPageToken() string {
+ if m != nil {
+ return m.NextPageToken
+ }
+ return ""
+}
+
+// The parameters to `GetSink`.
+type GetSinkRequest struct {
+ // Required. The resource name of the sink:
+ //
+ // "projects/[PROJECT_ID]/sinks/[SINK_ID]"
+ // "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
+ // "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
+ // "folders/[FOLDER_ID]/sinks/[SINK_ID]"
+ //
+ // Example: `"projects/my-project-id/sinks/my-sink-id"`.
+ SinkName string `protobuf:"bytes,1,opt,name=sink_name,json=sinkName" json:"sink_name,omitempty"`
+}
+
+func (m *GetSinkRequest) Reset() { *m = GetSinkRequest{} }
+func (m *GetSinkRequest) String() string { return proto.CompactTextString(m) }
+func (*GetSinkRequest) ProtoMessage() {}
+func (*GetSinkRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{3} }
+
+func (m *GetSinkRequest) GetSinkName() string {
+ if m != nil {
+ return m.SinkName
+ }
+ return ""
+}
+
+// The parameters to `CreateSink`.
+type CreateSinkRequest struct {
+ // Required. The resource in which to create the sink:
+ //
+ // "projects/[PROJECT_ID]"
+ // "organizations/[ORGANIZATION_ID]"
+ // "billingAccounts/[BILLING_ACCOUNT_ID]"
+ // "folders/[FOLDER_ID]"
+ //
+ // Examples: `"projects/my-logging-project"`, `"organizations/123456789"`.
+ Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
+ // Required. The new sink, whose `name` parameter is a sink identifier that
+ // is not already in use.
+ Sink *LogSink `protobuf:"bytes,2,opt,name=sink" json:"sink,omitempty"`
+ // Optional. Determines the kind of IAM identity returned as `writer_identity`
+ // in the new sink. If this value is omitted or set to false, and if the
+ // sink's parent is a project, then the value returned as `writer_identity` is
+ // the same group or service account used by Stackdriver Logging before the
+ // addition of writer identities to this API. The sink's destination must be
+ // in the same project as the sink itself.
+ //
+ // If this field is set to true, or if the sink is owned by a non-project
+ // resource such as an organization, then the value of `writer_identity` will
+ // be a unique service account used only for exports from the new sink. For
+ // more information, see `writer_identity` in [LogSink][google.logging.v2.LogSink].
+ UniqueWriterIdentity bool `protobuf:"varint,3,opt,name=unique_writer_identity,json=uniqueWriterIdentity" json:"unique_writer_identity,omitempty"`
+}
+
+func (m *CreateSinkRequest) Reset() { *m = CreateSinkRequest{} }
+func (m *CreateSinkRequest) String() string { return proto.CompactTextString(m) }
+func (*CreateSinkRequest) ProtoMessage() {}
+func (*CreateSinkRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{4} }
+
+func (m *CreateSinkRequest) GetParent() string {
+ if m != nil {
+ return m.Parent
+ }
+ return ""
+}
+
+func (m *CreateSinkRequest) GetSink() *LogSink {
+ if m != nil {
+ return m.Sink
+ }
+ return nil
+}
+
+func (m *CreateSinkRequest) GetUniqueWriterIdentity() bool {
+ if m != nil {
+ return m.UniqueWriterIdentity
+ }
+ return false
+}
+
+// The parameters to `UpdateSink`.
+type UpdateSinkRequest struct {
+ // Required. The full resource name of the sink to update, including the
+ // parent resource and the sink identifier:
+ //
+ // "projects/[PROJECT_ID]/sinks/[SINK_ID]"
+ // "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
+ // "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
+ // "folders/[FOLDER_ID]/sinks/[SINK_ID]"
+ //
+ // Example: `"projects/my-project-id/sinks/my-sink-id"`.
+ SinkName string `protobuf:"bytes,1,opt,name=sink_name,json=sinkName" json:"sink_name,omitempty"`
+ // Required. The updated sink, whose name is the same identifier that appears
+ // as part of `sink_name`. If `sink_name` does not exist, then
+ // this method creates a new sink.
+ Sink *LogSink `protobuf:"bytes,2,opt,name=sink" json:"sink,omitempty"`
+ // Optional. See
+ // [sinks.create](/logging/docs/api/reference/rest/v2/projects.sinks/create)
+ // for a description of this field. When updating a sink, the effect of this
+ // field on the value of `writer_identity` in the updated sink depends on both
+ // the old and new values of this field:
+ //
+ // + If the old and new values of this field are both false or both true,
+ // then there is no change to the sink's `writer_identity`.
+ // + If the old value is false and the new value is true, then
+ // `writer_identity` is changed to a unique service account.
+ // + It is an error if the old value is true and the new value is false.
+ UniqueWriterIdentity bool `protobuf:"varint,3,opt,name=unique_writer_identity,json=uniqueWriterIdentity" json:"unique_writer_identity,omitempty"`
+}
+
+func (m *UpdateSinkRequest) Reset() { *m = UpdateSinkRequest{} }
+func (m *UpdateSinkRequest) String() string { return proto.CompactTextString(m) }
+func (*UpdateSinkRequest) ProtoMessage() {}
+func (*UpdateSinkRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{5} }
+
+func (m *UpdateSinkRequest) GetSinkName() string {
+ if m != nil {
+ return m.SinkName
+ }
+ return ""
+}
+
+func (m *UpdateSinkRequest) GetSink() *LogSink {
+ if m != nil {
+ return m.Sink
+ }
+ return nil
+}
+
+func (m *UpdateSinkRequest) GetUniqueWriterIdentity() bool {
+ if m != nil {
+ return m.UniqueWriterIdentity
+ }
+ return false
+}
+
+// The parameters to `DeleteSink`.
+type DeleteSinkRequest struct {
+ // Required. The full resource name of the sink to delete, including the
+ // parent resource and the sink identifier:
+ //
+ // "projects/[PROJECT_ID]/sinks/[SINK_ID]"
+ // "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
+ // "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
+ // "folders/[FOLDER_ID]/sinks/[SINK_ID]"
+ //
+ // Example: `"projects/my-project-id/sinks/my-sink-id"`.
+ SinkName string `protobuf:"bytes,1,opt,name=sink_name,json=sinkName" json:"sink_name,omitempty"`
+}
+
+func (m *DeleteSinkRequest) Reset() { *m = DeleteSinkRequest{} }
+func (m *DeleteSinkRequest) String() string { return proto.CompactTextString(m) }
+func (*DeleteSinkRequest) ProtoMessage() {}
+func (*DeleteSinkRequest) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{6} }
+
+func (m *DeleteSinkRequest) GetSinkName() string {
+ if m != nil {
+ return m.SinkName
+ }
+ return ""
+}
+
+func init() {
+ proto.RegisterType((*LogSink)(nil), "google.logging.v2.LogSink")
+ proto.RegisterType((*ListSinksRequest)(nil), "google.logging.v2.ListSinksRequest")
+ proto.RegisterType((*ListSinksResponse)(nil), "google.logging.v2.ListSinksResponse")
+ proto.RegisterType((*GetSinkRequest)(nil), "google.logging.v2.GetSinkRequest")
+ proto.RegisterType((*CreateSinkRequest)(nil), "google.logging.v2.CreateSinkRequest")
+ proto.RegisterType((*UpdateSinkRequest)(nil), "google.logging.v2.UpdateSinkRequest")
+ proto.RegisterType((*DeleteSinkRequest)(nil), "google.logging.v2.DeleteSinkRequest")
+ proto.RegisterEnum("google.logging.v2.LogSink_VersionFormat", LogSink_VersionFormat_name, LogSink_VersionFormat_value)
+}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for ConfigServiceV2 service
+
+type ConfigServiceV2Client interface {
+ // Lists sinks.
+ ListSinks(ctx context.Context, in *ListSinksRequest, opts ...grpc.CallOption) (*ListSinksResponse, error)
+ // Gets a sink.
+ GetSink(ctx context.Context, in *GetSinkRequest, opts ...grpc.CallOption) (*LogSink, error)
+ // Creates a sink that exports specified log entries to a destination. The
+ // export of newly-ingested log entries begins immediately, unless the current
+ // time is outside the sink's start and end times or the sink's
+ // `writer_identity` is not permitted to write to the destination. A sink can
+ // export log entries only from the resource owning the sink.
+ CreateSink(ctx context.Context, in *CreateSinkRequest, opts ...grpc.CallOption) (*LogSink, error)
+ // Updates a sink. If the named sink doesn't exist, then this method is
+ // identical to
+ // [sinks.create](/logging/docs/api/reference/rest/v2/projects.sinks/create).
+ // If the named sink does exist, then this method replaces the following
+ // fields in the existing sink with values from the new sink: `destination`,
+ // `filter`, `output_version_format`, `start_time`, and `end_time`.
+ // The updated filter might also have a new `writer_identity`; see the
+ // `unique_writer_identity` field.
+ UpdateSink(ctx context.Context, in *UpdateSinkRequest, opts ...grpc.CallOption) (*LogSink, error)
+ // Deletes a sink. If the sink has a unique `writer_identity`, then that
+ // service account is also deleted.
+ DeleteSink(ctx context.Context, in *DeleteSinkRequest, opts ...grpc.CallOption) (*google_protobuf5.Empty, error)
+}
+
+type configServiceV2Client struct {
+ cc *grpc.ClientConn
+}
+
+func NewConfigServiceV2Client(cc *grpc.ClientConn) ConfigServiceV2Client {
+ return &configServiceV2Client{cc}
+}
+
+func (c *configServiceV2Client) ListSinks(ctx context.Context, in *ListSinksRequest, opts ...grpc.CallOption) (*ListSinksResponse, error) {
+ out := new(ListSinksResponse)
+ err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/ListSinks", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *configServiceV2Client) GetSink(ctx context.Context, in *GetSinkRequest, opts ...grpc.CallOption) (*LogSink, error) {
+ out := new(LogSink)
+ err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/GetSink", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *configServiceV2Client) CreateSink(ctx context.Context, in *CreateSinkRequest, opts ...grpc.CallOption) (*LogSink, error) {
+ out := new(LogSink)
+ err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/CreateSink", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *configServiceV2Client) UpdateSink(ctx context.Context, in *UpdateSinkRequest, opts ...grpc.CallOption) (*LogSink, error) {
+ out := new(LogSink)
+ err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/UpdateSink", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *configServiceV2Client) DeleteSink(ctx context.Context, in *DeleteSinkRequest, opts ...grpc.CallOption) (*google_protobuf5.Empty, error) {
+ out := new(google_protobuf5.Empty)
+ err := grpc.Invoke(ctx, "/google.logging.v2.ConfigServiceV2/DeleteSink", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for ConfigServiceV2 service
+
+type ConfigServiceV2Server interface {
+ // Lists sinks.
+ ListSinks(context.Context, *ListSinksRequest) (*ListSinksResponse, error)
+ // Gets a sink.
+ GetSink(context.Context, *GetSinkRequest) (*LogSink, error)
+ // Creates a sink that exports specified log entries to a destination. The
+ // export of newly-ingested log entries begins immediately, unless the current
+ // time is outside the sink's start and end times or the sink's
+ // `writer_identity` is not permitted to write to the destination. A sink can
+ // export log entries only from the resource owning the sink.
+ CreateSink(context.Context, *CreateSinkRequest) (*LogSink, error)
+ // Updates a sink. If the named sink doesn't exist, then this method is
+ // identical to
+ // [sinks.create](/logging/docs/api/reference/rest/v2/projects.sinks/create).
+ // If the named sink does exist, then this method replaces the following
+ // fields in the existing sink with values from the new sink: `destination`,
+ // `filter`, `output_version_format`, `start_time`, and `end_time`.
+ // The updated filter might also have a new `writer_identity`; see the
+ // `unique_writer_identity` field.
+ UpdateSink(context.Context, *UpdateSinkRequest) (*LogSink, error)
+ // Deletes a sink. If the sink has a unique `writer_identity`, then that
+ // service account is also deleted.
+ DeleteSink(context.Context, *DeleteSinkRequest) (*google_protobuf5.Empty, error)
+}
+
+func RegisterConfigServiceV2Server(s *grpc.Server, srv ConfigServiceV2Server) {
+ s.RegisterService(&_ConfigServiceV2_serviceDesc, srv)
+}
+
+func _ConfigServiceV2_ListSinks_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListSinksRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ConfigServiceV2Server).ListSinks(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.ConfigServiceV2/ListSinks",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ConfigServiceV2Server).ListSinks(ctx, req.(*ListSinksRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _ConfigServiceV2_GetSink_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetSinkRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ConfigServiceV2Server).GetSink(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.ConfigServiceV2/GetSink",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ConfigServiceV2Server).GetSink(ctx, req.(*GetSinkRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _ConfigServiceV2_CreateSink_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreateSinkRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ConfigServiceV2Server).CreateSink(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.ConfigServiceV2/CreateSink",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ConfigServiceV2Server).CreateSink(ctx, req.(*CreateSinkRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _ConfigServiceV2_UpdateSink_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateSinkRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ConfigServiceV2Server).UpdateSink(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.ConfigServiceV2/UpdateSink",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ConfigServiceV2Server).UpdateSink(ctx, req.(*UpdateSinkRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _ConfigServiceV2_DeleteSink_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(DeleteSinkRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ConfigServiceV2Server).DeleteSink(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.ConfigServiceV2/DeleteSink",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ConfigServiceV2Server).DeleteSink(ctx, req.(*DeleteSinkRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _ConfigServiceV2_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "google.logging.v2.ConfigServiceV2",
+ HandlerType: (*ConfigServiceV2Server)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "ListSinks",
+ Handler: _ConfigServiceV2_ListSinks_Handler,
+ },
+ {
+ MethodName: "GetSink",
+ Handler: _ConfigServiceV2_GetSink_Handler,
+ },
+ {
+ MethodName: "CreateSink",
+ Handler: _ConfigServiceV2_CreateSink_Handler,
+ },
+ {
+ MethodName: "UpdateSink",
+ Handler: _ConfigServiceV2_UpdateSink_Handler,
+ },
+ {
+ MethodName: "DeleteSink",
+ Handler: _ConfigServiceV2_DeleteSink_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "google/logging/v2/logging_config.proto",
+}
+
+func init() { proto.RegisterFile("google/logging/v2/logging_config.proto", fileDescriptor2) }
+
+var fileDescriptor2 = []byte{
+ // 818 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x55, 0xff, 0x6e, 0xdb, 0x54,
+ 0x14, 0xc6, 0xe9, 0xaf, 0xe4, 0x54, 0x6b, 0x93, 0x0b, 0x2b, 0x56, 0xca, 0x58, 0x30, 0xdb, 0x08,
+ 0x41, 0xd8, 0x25, 0x80, 0xc4, 0x0f, 0x21, 0xc4, 0xb2, 0x76, 0xaa, 0x54, 0xba, 0xca, 0xe9, 0x82,
+ 0x84, 0x90, 0x2c, 0x2f, 0x3e, 0x31, 0x97, 0xd9, 0xf7, 0x7a, 0xf6, 0x75, 0x60, 0x9b, 0x2a, 0x01,
+ 0x6f, 0x80, 0x90, 0x78, 0x08, 0x9e, 0x81, 0xb7, 0xe0, 0x15, 0x78, 0x0e, 0x84, 0xee, 0x8f, 0xac,
+ 0x69, 0x1d, 0x42, 0xff, 0xe2, 0xaf, 0xdc, 0xfb, 0x9d, 0x73, 0xee, 0xf7, 0x9d, 0x73, 0x3e, 0x39,
+ 0x70, 0x27, 0xe6, 0x3c, 0x4e, 0xd0, 0x4b, 0x78, 0x1c, 0x53, 0x16, 0x7b, 0xd3, 0xfe, 0xec, 0x18,
+ 0x8c, 0x39, 0x9b, 0xd0, 0xd8, 0xcd, 0x72, 0x2e, 0x38, 0x69, 0xe9, 0x3c, 0xd7, 0x04, 0xdd, 0x69,
+ 0xbf, 0xfd, 0x9a, 0x29, 0x0d, 0x33, 0xea, 0x85, 0x8c, 0x71, 0x11, 0x0a, 0xca, 0x59, 0xa1, 0x0b,
+ 0xda, 0xbb, 0x26, 0xaa, 0x6e, 0x8f, 0xca, 0x89, 0x87, 0x69, 0x26, 0x9e, 0x9a, 0xe0, 0xcd, 0xcb,
+ 0x41, 0x41, 0x53, 0x2c, 0x44, 0x98, 0x66, 0x3a, 0xc1, 0xf9, 0x63, 0x05, 0x36, 0x8e, 0x78, 0x3c,
+ 0xa4, 0xec, 0x31, 0x21, 0xb0, 0xca, 0xc2, 0x14, 0x6d, 0xab, 0x63, 0x75, 0x1b, 0xbe, 0x3a, 0x93,
+ 0x0e, 0x6c, 0x46, 0x58, 0x08, 0xca, 0x14, 0xa7, 0xbd, 0xa2, 0x42, 0xf3, 0x10, 0xd9, 0x81, 0xf5,
+ 0x09, 0x4d, 0x04, 0xe6, 0xf6, 0x9a, 0x0a, 0x9a, 0x1b, 0xf9, 0x06, 0xae, 0xf3, 0x52, 0x64, 0xa5,
+ 0x08, 0xa6, 0x98, 0x17, 0x94, 0xb3, 0x60, 0xc2, 0xf3, 0x34, 0x14, 0xf6, 0x7a, 0xc7, 0xea, 0x6e,
+ 0xf5, 0xbb, 0x6e, 0xa5, 0x51, 0xd7, 0x08, 0x71, 0x47, 0xba, 0xe0, 0x40, 0xe5, 0xfb, 0x2f, 0xeb,
+ 0x67, 0x2e, 0x80, 0xe4, 0x2d, 0xd8, 0xfe, 0x3e, 0xa7, 0x02, 0xf3, 0x80, 0x46, 0xc8, 0x04, 0x15,
+ 0x4f, 0xed, 0xba, 0xa2, 0xdf, 0xd2, 0xf0, 0xa1, 0x41, 0xc9, 0xdb, 0xd0, 0xa4, 0x6c, 0x9c, 0x94,
+ 0x11, 0x06, 0xe3, 0x6f, 0x69, 0x12, 0xe5, 0xc8, 0xec, 0x46, 0xc7, 0xea, 0xd6, 0xfd, 0x6d, 0x83,
+ 0x0f, 0x0c, 0x4c, 0x3e, 0x06, 0x28, 0x44, 0x98, 0x8b, 0x40, 0x0e, 0xc9, 0x86, 0x8e, 0xd5, 0xdd,
+ 0xec, 0xb7, 0x67, 0x32, 0x67, 0x13, 0x74, 0x4f, 0x67, 0x13, 0xf4, 0x1b, 0x2a, 0x5b, 0xde, 0xc9,
+ 0x87, 0x50, 0x47, 0x16, 0xe9, 0xc2, 0xcd, 0xff, 0x2c, 0xdc, 0x40, 0x16, 0xc9, 0x9b, 0xf3, 0x39,
+ 0x5c, 0xbb, 0xd8, 0xd6, 0xeb, 0xd0, 0x1e, 0xed, 0xfb, 0xc3, 0xc3, 0x07, 0xc7, 0xc1, 0xc1, 0x03,
+ 0xff, 0xcb, 0x2f, 0x4e, 0x83, 0x87, 0xc7, 0xc3, 0x93, 0xfd, 0xc1, 0xe1, 0xc1, 0xe1, 0xfe, 0xbd,
+ 0xe6, 0x4b, 0x64, 0x1d, 0x6a, 0xa3, 0x7e, 0xd3, 0x52, 0xbf, 0xef, 0x35, 0x6b, 0xce, 0x04, 0x9a,
+ 0x47, 0xb4, 0x10, 0x72, 0x6a, 0x85, 0x8f, 0x4f, 0x4a, 0x2c, 0x84, 0x5c, 0x48, 0x16, 0xe6, 0xc8,
+ 0x84, 0x59, 0xa4, 0xb9, 0x91, 0x1b, 0x00, 0x59, 0x18, 0x63, 0x20, 0xf8, 0x63, 0x64, 0x76, 0x4d,
+ 0xc5, 0x1a, 0x12, 0x39, 0x95, 0x00, 0xd9, 0x05, 0x75, 0x09, 0x0a, 0xfa, 0x0c, 0xd5, 0x9e, 0xd7,
+ 0xfc, 0xba, 0x04, 0x86, 0xf4, 0x19, 0x3a, 0x29, 0xb4, 0xe6, 0x78, 0x8a, 0x8c, 0xb3, 0x02, 0xc9,
+ 0x1e, 0xac, 0x15, 0x12, 0xb0, 0xad, 0xce, 0xca, 0x7c, 0xc7, 0xd5, 0x8d, 0xfa, 0x3a, 0x91, 0xdc,
+ 0x81, 0x6d, 0x86, 0x3f, 0x88, 0xa0, 0xa2, 0xe3, 0x9a, 0x84, 0x4f, 0x66, 0x5a, 0x9c, 0x77, 0x61,
+ 0xeb, 0x3e, 0x2a, 0xb6, 0x59, 0x53, 0xbb, 0xd0, 0x90, 0x4f, 0x04, 0x73, 0x06, 0xad, 0x4b, 0xe0,
+ 0x38, 0x4c, 0xd1, 0xf9, 0xc5, 0x82, 0xd6, 0x20, 0xc7, 0x50, 0xe0, 0x7c, 0xc9, 0xbf, 0xcd, 0xc1,
+ 0x85, 0x55, 0x59, 0xa9, 0x98, 0x97, 0xab, 0x56, 0x79, 0xe4, 0x03, 0xd8, 0x29, 0x19, 0x7d, 0x52,
+ 0x62, 0x70, 0xd9, 0x71, 0x2b, 0xca, 0x47, 0xaf, 0xe8, 0xe8, 0x57, 0x17, 0x7c, 0xe7, 0xfc, 0x66,
+ 0x41, 0xeb, 0x61, 0x16, 0x5d, 0xd2, 0xb4, 0xac, 0x8d, 0xff, 0x49, 0xd8, 0x1e, 0xb4, 0xee, 0x61,
+ 0x82, 0x57, 0xd7, 0xd5, 0xff, 0x7b, 0x15, 0xb6, 0x07, 0xea, 0x1b, 0x35, 0xc4, 0x7c, 0x4a, 0xc7,
+ 0x38, 0xea, 0x93, 0x33, 0x68, 0xbc, 0x30, 0x04, 0x79, 0x73, 0x91, 0xd4, 0x4b, 0xb6, 0x6c, 0xdf,
+ 0x5a, 0x9e, 0xa4, 0x3d, 0xe5, 0xdc, 0xfe, 0xf9, 0xcf, 0xbf, 0x7e, 0xad, 0xdd, 0x24, 0x37, 0xe4,
+ 0x07, 0xf2, 0xb9, 0xde, 0xd8, 0x67, 0x59, 0xce, 0xbf, 0xc3, 0xb1, 0x28, 0xbc, 0xde, 0x99, 0xa7,
+ 0x8d, 0x24, 0x60, 0xc3, 0x18, 0x84, 0xbc, 0xb1, 0xe0, 0xdd, 0x8b, 0xe6, 0x69, 0x2f, 0x19, 0xa5,
+ 0xd3, 0x53, 0x84, 0xb7, 0x88, 0xa3, 0x08, 0x5f, 0x0c, 0x61, 0x8e, 0x53, 0x53, 0x7a, 0xbd, 0x33,
+ 0xf2, 0x1c, 0xe0, 0xdc, 0x66, 0x64, 0x51, 0x43, 0x15, 0x17, 0x2e, 0xe5, 0x7e, 0x47, 0x71, 0xdf,
+ 0x76, 0x96, 0x37, 0xfb, 0x89, 0xde, 0xf6, 0x8f, 0x16, 0xc0, 0xb9, 0xa1, 0x16, 0xb2, 0x57, 0xfc,
+ 0xb6, 0x94, 0x7d, 0x4f, 0xb1, 0xf7, 0xda, 0x57, 0xe8, 0xdc, 0x48, 0x98, 0x02, 0x9c, 0x5b, 0x67,
+ 0xa1, 0x82, 0x8a, 0xb3, 0xda, 0x3b, 0x95, 0xef, 0xe0, 0xbe, 0xfc, 0x7f, 0x9a, 0xcd, 0xbd, 0x77,
+ 0x05, 0xf6, 0xbb, 0x3f, 0x59, 0x70, 0x7d, 0xcc, 0xd3, 0x2a, 0xdf, 0x5d, 0x72, 0xa4, 0xcf, 0xda,
+ 0x9e, 0x27, 0x92, 0xe2, 0xc4, 0xfa, 0xfa, 0x23, 0x93, 0x18, 0xf3, 0x24, 0x64, 0xb1, 0xcb, 0xf3,
+ 0xd8, 0x8b, 0x91, 0x29, 0x01, 0x9e, 0x0e, 0x85, 0x19, 0x2d, 0xe6, 0xfe, 0x8a, 0x3f, 0x35, 0xc7,
+ 0xdf, 0x6b, 0xaf, 0xde, 0xd7, 0xa5, 0x83, 0x84, 0x97, 0x91, 0x6b, 0x5e, 0x77, 0x47, 0xfd, 0x47,
+ 0xeb, 0xaa, 0xfc, 0xfd, 0x7f, 0x02, 0x00, 0x00, 0xff, 0xff, 0xda, 0xa4, 0xe3, 0x1e, 0xc8, 0x07,
+ 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/logging/v2/logging_metrics.pb.go b/vendor/google.golang.org/genproto/googleapis/logging/v2/logging_metrics.pb.go
new file mode 100644
index 0000000..2478264
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/logging/v2/logging_metrics.pb.go
@@ -0,0 +1,565 @@
+// Code generated by protoc-gen-go.
+// source: google/logging/v2/logging_metrics.proto
+// DO NOT EDIT!
+
+package logging
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "google.golang.org/genproto/googleapis/api/annotations"
+import _ "google.golang.org/genproto/googleapis/api/distribution"
+import _ "google.golang.org/genproto/googleapis/api/metric"
+import google_protobuf5 "github.com/golang/protobuf/ptypes/empty"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// Stackdriver Logging API version.
+type LogMetric_ApiVersion int32
+
+const (
+ // Stackdriver Logging API v2.
+ LogMetric_V2 LogMetric_ApiVersion = 0
+ // Stackdriver Logging API v1.
+ LogMetric_V1 LogMetric_ApiVersion = 1
+)
+
+var LogMetric_ApiVersion_name = map[int32]string{
+ 0: "V2",
+ 1: "V1",
+}
+var LogMetric_ApiVersion_value = map[string]int32{
+ "V2": 0,
+ "V1": 1,
+}
+
+func (x LogMetric_ApiVersion) String() string {
+ return proto.EnumName(LogMetric_ApiVersion_name, int32(x))
+}
+func (LogMetric_ApiVersion) EnumDescriptor() ([]byte, []int) { return fileDescriptor3, []int{0, 0} }
+
+// Describes a logs-based metric. The value of the metric is the
+// number of log entries that match a logs filter in a given time interval.
+type LogMetric struct {
+ // Required. The client-assigned metric identifier.
+ // Examples: `"error_count"`, `"nginx/requests"`.
+ //
+ // Metric identifiers are limited to 100 characters and can include
+ // only the following characters: `A-Z`, `a-z`, `0-9`, and the
+ // special characters `_-.,+!*',()%/`. The forward-slash character
+ // (`/`) denotes a hierarchy of name pieces, and it cannot be the
+ // first character of the name.
+ //
+ // The metric identifier in this field must not be
+ // [URL-encoded](https://en.wikipedia.org/wiki/Percent-encoding).
+ // However, when the metric identifier appears as the `[METRIC_ID]`
+ // part of a `metric_name` API parameter, then the metric identifier
+ // must be URL-encoded. Example:
+ // `"projects/my-project/metrics/nginx%2Frequests"`.
+ Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ // Optional. A description of this metric, which is used in documentation.
+ Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"`
+ // Required. An [advanced logs filter](/logging/docs/view/advanced_filters)
+ // which is used to match log entries.
+ // Example:
+ //
+ // "resource.type=gae_app AND severity>=ERROR"
+ //
+ // The maximum length of the filter is 20000 characters.
+ Filter string `protobuf:"bytes,3,opt,name=filter" json:"filter,omitempty"`
+ // Output only. The API version that created or updated this metric.
+ // The version also dictates the syntax of the filter expression. When a value
+ // for this field is missing, the default value of V2 should be assumed.
+ Version LogMetric_ApiVersion `protobuf:"varint,4,opt,name=version,enum=google.logging.v2.LogMetric_ApiVersion" json:"version,omitempty"`
+}
+
+func (m *LogMetric) Reset() { *m = LogMetric{} }
+func (m *LogMetric) String() string { return proto.CompactTextString(m) }
+func (*LogMetric) ProtoMessage() {}
+func (*LogMetric) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{0} }
+
+func (m *LogMetric) GetName() string {
+ if m != nil {
+ return m.Name
+ }
+ return ""
+}
+
+func (m *LogMetric) GetDescription() string {
+ if m != nil {
+ return m.Description
+ }
+ return ""
+}
+
+func (m *LogMetric) GetFilter() string {
+ if m != nil {
+ return m.Filter
+ }
+ return ""
+}
+
+func (m *LogMetric) GetVersion() LogMetric_ApiVersion {
+ if m != nil {
+ return m.Version
+ }
+ return LogMetric_V2
+}
+
+// The parameters to ListLogMetrics.
+type ListLogMetricsRequest struct {
+ // Required. The name of the project containing the metrics:
+ //
+ // "projects/[PROJECT_ID]"
+ Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
+ // Optional. If present, then retrieve the next batch of results from the
+ // preceding call to this method. `pageToken` must be the value of
+ // `nextPageToken` from the previous response. The values of other method
+ // parameters should be identical to those in the previous call.
+ PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken" json:"page_token,omitempty"`
+ // Optional. The maximum number of results to return from this request.
+ // Non-positive values are ignored. The presence of `nextPageToken` in the
+ // response indicates that more results might be available.
+ PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize" json:"page_size,omitempty"`
+}
+
+func (m *ListLogMetricsRequest) Reset() { *m = ListLogMetricsRequest{} }
+func (m *ListLogMetricsRequest) String() string { return proto.CompactTextString(m) }
+func (*ListLogMetricsRequest) ProtoMessage() {}
+func (*ListLogMetricsRequest) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{1} }
+
+func (m *ListLogMetricsRequest) GetParent() string {
+ if m != nil {
+ return m.Parent
+ }
+ return ""
+}
+
+func (m *ListLogMetricsRequest) GetPageToken() string {
+ if m != nil {
+ return m.PageToken
+ }
+ return ""
+}
+
+func (m *ListLogMetricsRequest) GetPageSize() int32 {
+ if m != nil {
+ return m.PageSize
+ }
+ return 0
+}
+
+// Result returned from ListLogMetrics.
+type ListLogMetricsResponse struct {
+ // A list of logs-based metrics.
+ Metrics []*LogMetric `protobuf:"bytes,1,rep,name=metrics" json:"metrics,omitempty"`
+ // If there might be more results than appear in this response, then
+ // `nextPageToken` is included. To get the next set of results, call this
+ // method again using the value of `nextPageToken` as `pageToken`.
+ NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"`
+}
+
+func (m *ListLogMetricsResponse) Reset() { *m = ListLogMetricsResponse{} }
+func (m *ListLogMetricsResponse) String() string { return proto.CompactTextString(m) }
+func (*ListLogMetricsResponse) ProtoMessage() {}
+func (*ListLogMetricsResponse) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{2} }
+
+func (m *ListLogMetricsResponse) GetMetrics() []*LogMetric {
+ if m != nil {
+ return m.Metrics
+ }
+ return nil
+}
+
+func (m *ListLogMetricsResponse) GetNextPageToken() string {
+ if m != nil {
+ return m.NextPageToken
+ }
+ return ""
+}
+
+// The parameters to GetLogMetric.
+type GetLogMetricRequest struct {
+ // The resource name of the desired metric:
+ //
+ // "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
+ MetricName string `protobuf:"bytes,1,opt,name=metric_name,json=metricName" json:"metric_name,omitempty"`
+}
+
+func (m *GetLogMetricRequest) Reset() { *m = GetLogMetricRequest{} }
+func (m *GetLogMetricRequest) String() string { return proto.CompactTextString(m) }
+func (*GetLogMetricRequest) ProtoMessage() {}
+func (*GetLogMetricRequest) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{3} }
+
+func (m *GetLogMetricRequest) GetMetricName() string {
+ if m != nil {
+ return m.MetricName
+ }
+ return ""
+}
+
+// The parameters to CreateLogMetric.
+type CreateLogMetricRequest struct {
+ // The resource name of the project in which to create the metric:
+ //
+ // "projects/[PROJECT_ID]"
+ //
+ // The new metric must be provided in the request.
+ Parent string `protobuf:"bytes,1,opt,name=parent" json:"parent,omitempty"`
+ // The new logs-based metric, which must not have an identifier that
+ // already exists.
+ Metric *LogMetric `protobuf:"bytes,2,opt,name=metric" json:"metric,omitempty"`
+}
+
+func (m *CreateLogMetricRequest) Reset() { *m = CreateLogMetricRequest{} }
+func (m *CreateLogMetricRequest) String() string { return proto.CompactTextString(m) }
+func (*CreateLogMetricRequest) ProtoMessage() {}
+func (*CreateLogMetricRequest) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{4} }
+
+func (m *CreateLogMetricRequest) GetParent() string {
+ if m != nil {
+ return m.Parent
+ }
+ return ""
+}
+
+func (m *CreateLogMetricRequest) GetMetric() *LogMetric {
+ if m != nil {
+ return m.Metric
+ }
+ return nil
+}
+
+// The parameters to UpdateLogMetric.
+type UpdateLogMetricRequest struct {
+ // The resource name of the metric to update:
+ //
+ // "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
+ //
+ // The updated metric must be provided in the request and it's
+ // `name` field must be the same as `[METRIC_ID]` If the metric
+ // does not exist in `[PROJECT_ID]`, then a new metric is created.
+ MetricName string `protobuf:"bytes,1,opt,name=metric_name,json=metricName" json:"metric_name,omitempty"`
+ // The updated metric.
+ Metric *LogMetric `protobuf:"bytes,2,opt,name=metric" json:"metric,omitempty"`
+}
+
+func (m *UpdateLogMetricRequest) Reset() { *m = UpdateLogMetricRequest{} }
+func (m *UpdateLogMetricRequest) String() string { return proto.CompactTextString(m) }
+func (*UpdateLogMetricRequest) ProtoMessage() {}
+func (*UpdateLogMetricRequest) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{5} }
+
+func (m *UpdateLogMetricRequest) GetMetricName() string {
+ if m != nil {
+ return m.MetricName
+ }
+ return ""
+}
+
+func (m *UpdateLogMetricRequest) GetMetric() *LogMetric {
+ if m != nil {
+ return m.Metric
+ }
+ return nil
+}
+
+// The parameters to DeleteLogMetric.
+type DeleteLogMetricRequest struct {
+ // The resource name of the metric to delete:
+ //
+ // "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
+ MetricName string `protobuf:"bytes,1,opt,name=metric_name,json=metricName" json:"metric_name,omitempty"`
+}
+
+func (m *DeleteLogMetricRequest) Reset() { *m = DeleteLogMetricRequest{} }
+func (m *DeleteLogMetricRequest) String() string { return proto.CompactTextString(m) }
+func (*DeleteLogMetricRequest) ProtoMessage() {}
+func (*DeleteLogMetricRequest) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{6} }
+
+func (m *DeleteLogMetricRequest) GetMetricName() string {
+ if m != nil {
+ return m.MetricName
+ }
+ return ""
+}
+
+func init() {
+ proto.RegisterType((*LogMetric)(nil), "google.logging.v2.LogMetric")
+ proto.RegisterType((*ListLogMetricsRequest)(nil), "google.logging.v2.ListLogMetricsRequest")
+ proto.RegisterType((*ListLogMetricsResponse)(nil), "google.logging.v2.ListLogMetricsResponse")
+ proto.RegisterType((*GetLogMetricRequest)(nil), "google.logging.v2.GetLogMetricRequest")
+ proto.RegisterType((*CreateLogMetricRequest)(nil), "google.logging.v2.CreateLogMetricRequest")
+ proto.RegisterType((*UpdateLogMetricRequest)(nil), "google.logging.v2.UpdateLogMetricRequest")
+ proto.RegisterType((*DeleteLogMetricRequest)(nil), "google.logging.v2.DeleteLogMetricRequest")
+ proto.RegisterEnum("google.logging.v2.LogMetric_ApiVersion", LogMetric_ApiVersion_name, LogMetric_ApiVersion_value)
+}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for MetricsServiceV2 service
+
+type MetricsServiceV2Client interface {
+ // Lists logs-based metrics.
+ ListLogMetrics(ctx context.Context, in *ListLogMetricsRequest, opts ...grpc.CallOption) (*ListLogMetricsResponse, error)
+ // Gets a logs-based metric.
+ GetLogMetric(ctx context.Context, in *GetLogMetricRequest, opts ...grpc.CallOption) (*LogMetric, error)
+ // Creates a logs-based metric.
+ CreateLogMetric(ctx context.Context, in *CreateLogMetricRequest, opts ...grpc.CallOption) (*LogMetric, error)
+ // Creates or updates a logs-based metric.
+ UpdateLogMetric(ctx context.Context, in *UpdateLogMetricRequest, opts ...grpc.CallOption) (*LogMetric, error)
+ // Deletes a logs-based metric.
+ DeleteLogMetric(ctx context.Context, in *DeleteLogMetricRequest, opts ...grpc.CallOption) (*google_protobuf5.Empty, error)
+}
+
+type metricsServiceV2Client struct {
+ cc *grpc.ClientConn
+}
+
+func NewMetricsServiceV2Client(cc *grpc.ClientConn) MetricsServiceV2Client {
+ return &metricsServiceV2Client{cc}
+}
+
+func (c *metricsServiceV2Client) ListLogMetrics(ctx context.Context, in *ListLogMetricsRequest, opts ...grpc.CallOption) (*ListLogMetricsResponse, error) {
+ out := new(ListLogMetricsResponse)
+ err := grpc.Invoke(ctx, "/google.logging.v2.MetricsServiceV2/ListLogMetrics", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *metricsServiceV2Client) GetLogMetric(ctx context.Context, in *GetLogMetricRequest, opts ...grpc.CallOption) (*LogMetric, error) {
+ out := new(LogMetric)
+ err := grpc.Invoke(ctx, "/google.logging.v2.MetricsServiceV2/GetLogMetric", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *metricsServiceV2Client) CreateLogMetric(ctx context.Context, in *CreateLogMetricRequest, opts ...grpc.CallOption) (*LogMetric, error) {
+ out := new(LogMetric)
+ err := grpc.Invoke(ctx, "/google.logging.v2.MetricsServiceV2/CreateLogMetric", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *metricsServiceV2Client) UpdateLogMetric(ctx context.Context, in *UpdateLogMetricRequest, opts ...grpc.CallOption) (*LogMetric, error) {
+ out := new(LogMetric)
+ err := grpc.Invoke(ctx, "/google.logging.v2.MetricsServiceV2/UpdateLogMetric", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *metricsServiceV2Client) DeleteLogMetric(ctx context.Context, in *DeleteLogMetricRequest, opts ...grpc.CallOption) (*google_protobuf5.Empty, error) {
+ out := new(google_protobuf5.Empty)
+ err := grpc.Invoke(ctx, "/google.logging.v2.MetricsServiceV2/DeleteLogMetric", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for MetricsServiceV2 service
+
+type MetricsServiceV2Server interface {
+ // Lists logs-based metrics.
+ ListLogMetrics(context.Context, *ListLogMetricsRequest) (*ListLogMetricsResponse, error)
+ // Gets a logs-based metric.
+ GetLogMetric(context.Context, *GetLogMetricRequest) (*LogMetric, error)
+ // Creates a logs-based metric.
+ CreateLogMetric(context.Context, *CreateLogMetricRequest) (*LogMetric, error)
+ // Creates or updates a logs-based metric.
+ UpdateLogMetric(context.Context, *UpdateLogMetricRequest) (*LogMetric, error)
+ // Deletes a logs-based metric.
+ DeleteLogMetric(context.Context, *DeleteLogMetricRequest) (*google_protobuf5.Empty, error)
+}
+
+func RegisterMetricsServiceV2Server(s *grpc.Server, srv MetricsServiceV2Server) {
+ s.RegisterService(&_MetricsServiceV2_serviceDesc, srv)
+}
+
+func _MetricsServiceV2_ListLogMetrics_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListLogMetricsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(MetricsServiceV2Server).ListLogMetrics(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.MetricsServiceV2/ListLogMetrics",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(MetricsServiceV2Server).ListLogMetrics(ctx, req.(*ListLogMetricsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _MetricsServiceV2_GetLogMetric_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetLogMetricRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(MetricsServiceV2Server).GetLogMetric(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.MetricsServiceV2/GetLogMetric",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(MetricsServiceV2Server).GetLogMetric(ctx, req.(*GetLogMetricRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _MetricsServiceV2_CreateLogMetric_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(CreateLogMetricRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(MetricsServiceV2Server).CreateLogMetric(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.MetricsServiceV2/CreateLogMetric",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(MetricsServiceV2Server).CreateLogMetric(ctx, req.(*CreateLogMetricRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _MetricsServiceV2_UpdateLogMetric_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateLogMetricRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(MetricsServiceV2Server).UpdateLogMetric(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.MetricsServiceV2/UpdateLogMetric",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(MetricsServiceV2Server).UpdateLogMetric(ctx, req.(*UpdateLogMetricRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _MetricsServiceV2_DeleteLogMetric_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(DeleteLogMetricRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(MetricsServiceV2Server).DeleteLogMetric(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/google.logging.v2.MetricsServiceV2/DeleteLogMetric",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(MetricsServiceV2Server).DeleteLogMetric(ctx, req.(*DeleteLogMetricRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _MetricsServiceV2_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "google.logging.v2.MetricsServiceV2",
+ HandlerType: (*MetricsServiceV2Server)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "ListLogMetrics",
+ Handler: _MetricsServiceV2_ListLogMetrics_Handler,
+ },
+ {
+ MethodName: "GetLogMetric",
+ Handler: _MetricsServiceV2_GetLogMetric_Handler,
+ },
+ {
+ MethodName: "CreateLogMetric",
+ Handler: _MetricsServiceV2_CreateLogMetric_Handler,
+ },
+ {
+ MethodName: "UpdateLogMetric",
+ Handler: _MetricsServiceV2_UpdateLogMetric_Handler,
+ },
+ {
+ MethodName: "DeleteLogMetric",
+ Handler: _MetricsServiceV2_DeleteLogMetric_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "google/logging/v2/logging_metrics.proto",
+}
+
+func init() { proto.RegisterFile("google/logging/v2/logging_metrics.proto", fileDescriptor3) }
+
+var fileDescriptor3 = []byte{
+ // 665 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0x4f, 0x4f, 0x13, 0x41,
+ 0x14, 0x77, 0x0a, 0x14, 0x79, 0x28, 0xc5, 0x21, 0x94, 0xa6, 0x40, 0xa8, 0x7b, 0x80, 0xc2, 0x61,
+ 0x57, 0x57, 0x43, 0xfc, 0x13, 0x0f, 0x80, 0x86, 0x0b, 0x1a, 0x52, 0xb4, 0x07, 0x2f, 0xcd, 0xd2,
+ 0x3e, 0x36, 0x23, 0xed, 0xce, 0xba, 0x33, 0x6d, 0x10, 0xc3, 0x85, 0x70, 0x33, 0xf1, 0xa0, 0xdf,
+ 0xc2, 0x8f, 0xe0, 0xd7, 0xd0, 0x8f, 0xe0, 0x07, 0x31, 0x3b, 0x33, 0x0b, 0x6b, 0xbb, 0xd2, 0x86,
+ 0x53, 0x67, 0xde, 0xef, 0xbd, 0xfd, 0xfd, 0xde, 0x7b, 0xbf, 0x4c, 0x61, 0xcd, 0xe7, 0xdc, 0x6f,
+ 0xa3, 0xd3, 0xe6, 0xbe, 0xcf, 0x02, 0xdf, 0xe9, 0xb9, 0xc9, 0xb1, 0xd1, 0x41, 0x19, 0xb1, 0xa6,
+ 0xb0, 0xc3, 0x88, 0x4b, 0x4e, 0xef, 0xe9, 0x44, 0xdb, 0xa0, 0x76, 0xcf, 0x2d, 0x2f, 0x99, 0x5a,
+ 0x2f, 0x64, 0x8e, 0x17, 0x04, 0x5c, 0x7a, 0x92, 0xf1, 0xc0, 0x14, 0x94, 0x97, 0x53, 0x68, 0x8b,
+ 0x09, 0x19, 0xb1, 0xc3, 0x6e, 0x8c, 0x1b, 0x78, 0x21, 0x05, 0x6b, 0x26, 0x03, 0x2c, 0x1a, 0x40,
+ 0xdd, 0x0e, 0xbb, 0x47, 0x0e, 0x76, 0x42, 0xf9, 0x49, 0x83, 0xd6, 0x4f, 0x02, 0x53, 0x7b, 0xdc,
+ 0x7f, 0xad, 0x0a, 0x28, 0x85, 0xf1, 0xc0, 0xeb, 0x60, 0x89, 0x54, 0x48, 0x75, 0xaa, 0xa6, 0xce,
+ 0xb4, 0x02, 0xd3, 0x2d, 0x14, 0xcd, 0x88, 0x85, 0x31, 0x59, 0x29, 0xa7, 0xa0, 0x74, 0x88, 0x16,
+ 0x21, 0x7f, 0xc4, 0xda, 0x12, 0xa3, 0xd2, 0x98, 0x02, 0xcd, 0x8d, 0x6e, 0xc1, 0x64, 0x0f, 0x23,
+ 0x11, 0x57, 0x8d, 0x57, 0x48, 0x75, 0xc6, 0x5d, 0xb3, 0x07, 0x7a, 0xb6, 0x2f, 0xc9, 0xed, 0xad,
+ 0x90, 0xd5, 0x75, 0x7a, 0x2d, 0xa9, 0xb3, 0x96, 0x00, 0xae, 0xc2, 0x34, 0x0f, 0xb9, 0xba, 0x3b,
+ 0x7b, 0x4b, 0xfd, 0x3e, 0x9c, 0x25, 0xd6, 0x31, 0xcc, 0xef, 0x31, 0x21, 0x2f, 0x3f, 0x21, 0x6a,
+ 0xf8, 0xb1, 0x8b, 0x42, 0xc6, 0x8a, 0x42, 0x2f, 0xc2, 0x40, 0x9a, 0x4e, 0xcc, 0x8d, 0x2e, 0x03,
+ 0x84, 0x9e, 0x8f, 0x0d, 0xc9, 0x8f, 0x31, 0x69, 0x65, 0x2a, 0x8e, 0xbc, 0x8d, 0x03, 0x74, 0x11,
+ 0xd4, 0xa5, 0x21, 0xd8, 0x29, 0xaa, 0x5e, 0x26, 0x6a, 0xb7, 0xe3, 0xc0, 0x01, 0x3b, 0x45, 0xeb,
+ 0x04, 0x8a, 0xfd, 0x64, 0x22, 0xe4, 0x81, 0x40, 0xba, 0x09, 0x93, 0x66, 0xb5, 0x25, 0x52, 0x19,
+ 0xab, 0x4e, 0xbb, 0x4b, 0xd7, 0xf5, 0x59, 0x4b, 0x92, 0xe9, 0x2a, 0x14, 0x02, 0x3c, 0x91, 0x8d,
+ 0x01, 0x49, 0x77, 0xe3, 0xf0, 0x7e, 0x22, 0xcb, 0xda, 0x84, 0xb9, 0x5d, 0xbc, 0x22, 0x4e, 0x9a,
+ 0x5c, 0x81, 0x69, 0xfd, 0xa5, 0x46, 0x6a, 0x67, 0xa0, 0x43, 0x6f, 0xbc, 0x0e, 0x5a, 0x47, 0x50,
+ 0xdc, 0x89, 0xd0, 0x93, 0x38, 0x50, 0xfa, 0xbf, 0xf9, 0x3c, 0x86, 0xbc, 0xae, 0x57, 0x42, 0x86,
+ 0x35, 0x62, 0x72, 0x2d, 0x0e, 0xc5, 0x77, 0x61, 0x2b, 0x8b, 0x67, 0x98, 0xc4, 0x1b, 0x12, 0x3e,
+ 0x85, 0xe2, 0x4b, 0x6c, 0xe3, 0x0d, 0x08, 0xdd, 0xdf, 0x13, 0x30, 0x6b, 0xf6, 0x77, 0x80, 0x51,
+ 0x8f, 0x35, 0xb1, 0xee, 0xd2, 0xaf, 0x04, 0x66, 0xfe, 0xdd, 0x2d, 0xad, 0x66, 0x09, 0xc9, 0xf2,
+ 0x5a, 0x79, 0x7d, 0x84, 0x4c, 0x6d, 0x14, 0x6b, 0xed, 0xfc, 0xd7, 0x9f, 0xef, 0xb9, 0xfb, 0x74,
+ 0x25, 0x7e, 0x15, 0x3e, 0xeb, 0x99, 0xbf, 0x08, 0x23, 0xfe, 0x01, 0x9b, 0x52, 0x38, 0x1b, 0x67,
+ 0x4e, 0xe2, 0x8c, 0x0b, 0x02, 0x77, 0xd2, 0x2b, 0xa7, 0xab, 0x19, 0x24, 0x19, 0x9e, 0x28, 0x5f,
+ 0x3b, 0x3f, 0xcb, 0x56, 0xfc, 0x55, 0xba, 0xaa, 0xf8, 0x53, 0x83, 0x4a, 0x89, 0x48, 0x34, 0x38,
+ 0x1b, 0x67, 0xf4, 0x0b, 0x81, 0x42, 0x9f, 0x83, 0x68, 0x56, 0xbb, 0xd9, 0x2e, 0x1b, 0x22, 0xc6,
+ 0x51, 0x62, 0xd6, 0xad, 0x61, 0xc3, 0x78, 0x66, 0xb6, 0x4e, 0xbf, 0x11, 0x28, 0xf4, 0xf9, 0x2c,
+ 0x53, 0x4d, 0xb6, 0x17, 0x87, 0xa8, 0xd9, 0x54, 0x6a, 0x1e, 0x94, 0x47, 0x1c, 0xcd, 0xa5, 0xa8,
+ 0x0b, 0x02, 0x85, 0x3e, 0x2f, 0x66, 0x8a, 0xca, 0xf6, 0x6b, 0xb9, 0x98, 0xa4, 0x26, 0x8f, 0xb3,
+ 0xfd, 0x2a, 0x7e, 0x9c, 0x93, 0x4d, 0x6d, 0x8c, 0x28, 0x67, 0xfb, 0x9c, 0xc0, 0x7c, 0x93, 0x77,
+ 0x06, 0x89, 0xb7, 0xe7, 0xf6, 0xf4, 0xd9, 0x78, 0x71, 0x3f, 0xe6, 0xd9, 0x27, 0xef, 0x9f, 0x98,
+ 0x4c, 0x9f, 0xb7, 0xbd, 0xc0, 0xb7, 0x79, 0xe4, 0x3b, 0x3e, 0x06, 0x4a, 0x85, 0xa3, 0x21, 0x2f,
+ 0x64, 0x22, 0xf5, 0x2f, 0xf6, 0xdc, 0x1c, 0x7f, 0xe4, 0x16, 0x76, 0x75, 0xe9, 0x4e, 0x9b, 0x77,
+ 0x5b, 0xb6, 0xf9, 0xbc, 0x5d, 0x77, 0x0f, 0xf3, 0xaa, 0xfc, 0xd1, 0xdf, 0x00, 0x00, 0x00, 0xff,
+ 0xff, 0x22, 0xd3, 0x7f, 0x20, 0x03, 0x07, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go b/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go
new file mode 100644
index 0000000..ec26060
--- /dev/null
+++ b/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go
@@ -0,0 +1,144 @@
+// Code generated by protoc-gen-go.
+// source: google/rpc/status.proto
+// DO NOT EDIT!
+
+/*
+Package status is a generated protocol buffer package.
+
+It is generated from these files:
+ google/rpc/status.proto
+
+It has these top-level messages:
+ Status
+*/
+package status
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_protobuf "github.com/golang/protobuf/ptypes/any"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// The `Status` type defines a logical error model that is suitable for different
+// programming environments, including REST APIs and RPC APIs. It is used by
+// [gRPC](https://github.com/grpc). The error model is designed to be:
+//
+// - Simple to use and understand for most users
+// - Flexible enough to meet unexpected needs
+//
+// # Overview
+//
+// The `Status` message contains three pieces of data: error code, error message,
+// and error details. The error code should be an enum value of
+// [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The
+// error message should be a developer-facing English message that helps
+// developers *understand* and *resolve* the error. If a localized user-facing
+// error message is needed, put the localized message in the error details or
+// localize it in the client. The optional error details may contain arbitrary
+// information about the error. There is a predefined set of error detail types
+// in the package `google.rpc` which can be used for common error conditions.
+//
+// # Language mapping
+//
+// The `Status` message is the logical representation of the error model, but it
+// is not necessarily the actual wire format. When the `Status` message is
+// exposed in different client libraries and different wire protocols, it can be
+// mapped differently. For example, it will likely be mapped to some exceptions
+// in Java, but more likely mapped to some error codes in C.
+//
+// # Other uses
+//
+// The error model and the `Status` message can be used in a variety of
+// environments, either with or without APIs, to provide a
+// consistent developer experience across different environments.
+//
+// Example uses of this error model include:
+//
+// - Partial errors. If a service needs to return partial errors to the client,
+// it may embed the `Status` in the normal response to indicate the partial
+// errors.
+//
+// - Workflow errors. A typical workflow has multiple steps. Each step may
+// have a `Status` message for error reporting purpose.
+//
+// - Batch operations. If a client uses batch request and batch response, the
+// `Status` message should be used directly inside batch response, one for
+// each error sub-response.
+//
+// - Asynchronous operations. If an API call embeds asynchronous operation
+// results in its response, the status of those operations should be
+// represented directly using the `Status` message.
+//
+// - Logging. If some API errors are stored in logs, the message `Status` could
+// be used directly after any stripping needed for security/privacy reasons.
+type Status struct {
+ // The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code].
+ Code int32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"`
+ // A developer-facing error message, which should be in English. Any
+ // user-facing error message should be localized and sent in the
+ // [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client.
+ Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
+ // A list of messages that carry the error details. There will be a
+ // common set of message types for APIs to use.
+ Details []*google_protobuf.Any `protobuf:"bytes,3,rep,name=details" json:"details,omitempty"`
+}
+
+func (m *Status) Reset() { *m = Status{} }
+func (m *Status) String() string { return proto.CompactTextString(m) }
+func (*Status) ProtoMessage() {}
+func (*Status) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *Status) GetCode() int32 {
+ if m != nil {
+ return m.Code
+ }
+ return 0
+}
+
+func (m *Status) GetMessage() string {
+ if m != nil {
+ return m.Message
+ }
+ return ""
+}
+
+func (m *Status) GetDetails() []*google_protobuf.Any {
+ if m != nil {
+ return m.Details
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Status)(nil), "google.rpc.Status")
+}
+
+func init() { proto.RegisterFile("google/rpc/status.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 209 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4f, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0xd5, 0x2f, 0x2a, 0x48, 0xd6, 0x2f, 0x2e, 0x49, 0x2c, 0x29, 0x2d, 0xd6, 0x2b, 0x28,
+ 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x82, 0x48, 0xe8, 0x15, 0x15, 0x24, 0x4b, 0x49, 0x42, 0x15, 0x81,
+ 0x65, 0x92, 0x4a, 0xd3, 0xf4, 0x13, 0xf3, 0x2a, 0x21, 0xca, 0x94, 0xd2, 0xb8, 0xd8, 0x82, 0xc1,
+ 0xda, 0x84, 0x84, 0xb8, 0x58, 0x92, 0xf3, 0x53, 0x52, 0x25, 0x18, 0x15, 0x18, 0x35, 0x58, 0x83,
+ 0xc0, 0x6c, 0x21, 0x09, 0x2e, 0xf6, 0xdc, 0xd4, 0xe2, 0xe2, 0xc4, 0xf4, 0x54, 0x09, 0x26, 0x05,
+ 0x46, 0x0d, 0xce, 0x20, 0x18, 0x57, 0x48, 0x8f, 0x8b, 0x3d, 0x25, 0xb5, 0x24, 0x31, 0x33, 0xa7,
+ 0x58, 0x82, 0x59, 0x81, 0x59, 0x83, 0xdb, 0x48, 0x44, 0x0f, 0x6a, 0x21, 0xcc, 0x12, 0x3d, 0xc7,
+ 0xbc, 0xca, 0x20, 0x98, 0x22, 0xa7, 0x38, 0x2e, 0xbe, 0xe4, 0xfc, 0x5c, 0x3d, 0x84, 0xa3, 0x9c,
+ 0xb8, 0x21, 0xf6, 0x06, 0x80, 0x94, 0x07, 0x30, 0x46, 0x99, 0x43, 0xa5, 0xd2, 0xf3, 0x73, 0x12,
+ 0xf3, 0xd2, 0xf5, 0xf2, 0x8b, 0xd2, 0xf5, 0xd3, 0x53, 0xf3, 0xc0, 0x86, 0xe9, 0x43, 0xa4, 0x12,
+ 0x0b, 0x32, 0x8b, 0x91, 0xfc, 0x69, 0x0d, 0xa1, 0x16, 0x31, 0x31, 0x07, 0x05, 0x38, 0x27, 0xb1,
+ 0x81, 0x55, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xa4, 0x53, 0xf0, 0x7c, 0x10, 0x01, 0x00,
+ 0x00,
+}
diff --git a/vendor/google.golang.org/grpc/LICENSE b/vendor/google.golang.org/grpc/LICENSE
new file mode 100644
index 0000000..f4988b4
--- /dev/null
+++ b/vendor/google.golang.org/grpc/LICENSE
@@ -0,0 +1,28 @@
+Copyright 2014, Google Inc.
+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/google.golang.org/grpc/PATENTS b/vendor/google.golang.org/grpc/PATENTS
new file mode 100644
index 0000000..69b4795
--- /dev/null
+++ b/vendor/google.golang.org/grpc/PATENTS
@@ -0,0 +1,22 @@
+Additional IP Rights Grant (Patents)
+
+"This implementation" means the copyrightable works distributed by
+Google as part of the gRPC 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 gRPC, 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 gRPC. 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 gRPC or any code incorporated within this
+implementation of gRPC 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 gRPC
+shall terminate as of the date such litigation is filed.
diff --git a/vendor/google.golang.org/grpc/README.md b/vendor/google.golang.org/grpc/README.md
new file mode 100644
index 0000000..ae0236f
--- /dev/null
+++ b/vendor/google.golang.org/grpc/README.md
@@ -0,0 +1,41 @@
+# gRPC-Go
+
+[![Build Status](https://travis-ci.org/grpc/grpc-go.svg)](https://travis-ci.org/grpc/grpc-go) [![GoDoc](https://godoc.org/google.golang.org/grpc?status.svg)](https://godoc.org/google.golang.org/grpc)
+
+The Go implementation of [gRPC](http://www.grpc.io/): A high performance, open source, general RPC framework that puts mobile and HTTP/2 first. For more information see the [gRPC Quick Start](http://www.grpc.io/docs/) guide.
+
+Installation
+------------
+
+To install this package, you need to install Go and setup your Go workspace on your computer. The simplest way to install the library is to run:
+
+```
+$ go get google.golang.org/grpc
+```
+
+Prerequisites
+-------------
+
+This requires Go 1.6 or later.
+
+Constraints
+-----------
+The grpc package should only depend on standard Go packages and a small number of exceptions. If your contribution introduces new dependencies which are NOT in the [list](http://godoc.org/google.golang.org/grpc?imports), you need a discussion with gRPC-Go authors and consultants.
+
+Documentation
+-------------
+See [API documentation](https://godoc.org/google.golang.org/grpc) for package and API descriptions and find examples in the [examples directory](examples/).
+
+Status
+------
+GA
+
+FAQ
+---
+
+#### Compiling error, undefined: grpc.SupportPackageIsVersion
+
+Please update proto package, gRPC package and rebuild the proto files:
+ - `go get -u github.com/golang/protobuf/{proto,protoc-gen-go}`
+ - `go get -u google.golang.org/grpc`
+ - `protoc --go_out=plugins=grpc:. *.proto`
diff --git a/vendor/google.golang.org/grpc/backoff.go b/vendor/google.golang.org/grpc/backoff.go
new file mode 100644
index 0000000..c99024e
--- /dev/null
+++ b/vendor/google.golang.org/grpc/backoff.go
@@ -0,0 +1,80 @@
+package grpc
+
+import (
+ "math/rand"
+ "time"
+)
+
+// DefaultBackoffConfig uses values specified for backoff in
+// https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md.
+var (
+ DefaultBackoffConfig = BackoffConfig{
+ MaxDelay: 120 * time.Second,
+ baseDelay: 1.0 * time.Second,
+ factor: 1.6,
+ jitter: 0.2,
+ }
+)
+
+// backoffStrategy defines the methodology for backing off after a grpc
+// connection failure.
+//
+// This is unexported until the gRPC project decides whether or not to allow
+// alternative backoff strategies. Once a decision is made, this type and its
+// method may be exported.
+type backoffStrategy interface {
+ // backoff returns the amount of time to wait before the next retry given
+ // the number of consecutive failures.
+ backoff(retries int) time.Duration
+}
+
+// BackoffConfig defines the parameters for the default gRPC backoff strategy.
+type BackoffConfig struct {
+ // MaxDelay is the upper bound of backoff delay.
+ MaxDelay time.Duration
+
+ // TODO(stevvooe): The following fields are not exported, as allowing
+ // changes would violate the current gRPC specification for backoff. If
+ // gRPC decides to allow more interesting backoff strategies, these fields
+ // may be opened up in the future.
+
+ // baseDelay is the amount of time to wait before retrying after the first
+ // failure.
+ baseDelay time.Duration
+
+ // factor is applied to the backoff after each retry.
+ factor float64
+
+ // jitter provides a range to randomize backoff delays.
+ jitter float64
+}
+
+func setDefaults(bc *BackoffConfig) {
+ md := bc.MaxDelay
+ *bc = DefaultBackoffConfig
+
+ if md > 0 {
+ bc.MaxDelay = md
+ }
+}
+
+func (bc BackoffConfig) backoff(retries int) time.Duration {
+ if retries == 0 {
+ return bc.baseDelay
+ }
+ backoff, max := float64(bc.baseDelay), float64(bc.MaxDelay)
+ for backoff < max && retries > 0 {
+ backoff *= bc.factor
+ retries--
+ }
+ if backoff > max {
+ backoff = max
+ }
+ // Randomize backoff delays so that if a cluster of requests start at
+ // the same time, they won't operate in lockstep.
+ backoff *= 1 + bc.jitter*(rand.Float64()*2-1)
+ if backoff < 0 {
+ return 0
+ }
+ return time.Duration(backoff)
+}
diff --git a/vendor/google.golang.org/grpc/balancer.go b/vendor/google.golang.org/grpc/balancer.go
new file mode 100644
index 0000000..9d943fb
--- /dev/null
+++ b/vendor/google.golang.org/grpc/balancer.go
@@ -0,0 +1,400 @@
+/*
+ *
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "fmt"
+ "sync"
+
+ "golang.org/x/net/context"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/grpclog"
+ "google.golang.org/grpc/naming"
+)
+
+// Address represents a server the client connects to.
+// This is the EXPERIMENTAL API and may be changed or extended in the future.
+type Address struct {
+ // Addr is the server address on which a connection will be established.
+ Addr string
+ // Metadata is the information associated with Addr, which may be used
+ // to make load balancing decision.
+ Metadata interface{}
+}
+
+// BalancerConfig specifies the configurations for Balancer.
+type BalancerConfig struct {
+ // DialCreds is the transport credential the Balancer implementation can
+ // use to dial to a remote load balancer server. The Balancer implementations
+ // can ignore this if it does not need to talk to another party securely.
+ DialCreds credentials.TransportCredentials
+}
+
+// BalancerGetOptions configures a Get call.
+// This is the EXPERIMENTAL API and may be changed or extended in the future.
+type BalancerGetOptions struct {
+ // BlockingWait specifies whether Get should block when there is no
+ // connected address.
+ BlockingWait bool
+}
+
+// Balancer chooses network addresses for RPCs.
+// This is the EXPERIMENTAL API and may be changed or extended in the future.
+type Balancer interface {
+ // Start does the initialization work to bootstrap a Balancer. For example,
+ // this function may start the name resolution and watch the updates. It will
+ // be called when dialing.
+ Start(target string, config BalancerConfig) error
+ // Up informs the Balancer that gRPC has a connection to the server at
+ // addr. It returns down which is called once the connection to addr gets
+ // lost or closed.
+ // TODO: It is not clear how to construct and take advantage of the meaningful error
+ // parameter for down. Need realistic demands to guide.
+ Up(addr Address) (down func(error))
+ // Get gets the address of a server for the RPC corresponding to ctx.
+ // i) If it returns a connected address, gRPC internals issues the RPC on the
+ // connection to this address;
+ // ii) If it returns an address on which the connection is under construction
+ // (initiated by Notify(...)) but not connected, gRPC internals
+ // * fails RPC if the RPC is fail-fast and connection is in the TransientFailure or
+ // Shutdown state;
+ // or
+ // * issues RPC on the connection otherwise.
+ // iii) If it returns an address on which the connection does not exist, gRPC
+ // internals treats it as an error and will fail the corresponding RPC.
+ //
+ // Therefore, the following is the recommended rule when writing a custom Balancer.
+ // If opts.BlockingWait is true, it should return a connected address or
+ // block if there is no connected address. It should respect the timeout or
+ // cancellation of ctx when blocking. If opts.BlockingWait is false (for fail-fast
+ // RPCs), it should return an address it has notified via Notify(...) immediately
+ // instead of blocking.
+ //
+ // The function returns put which is called once the rpc has completed or failed.
+ // put can collect and report RPC stats to a remote load balancer.
+ //
+ // This function should only return the errors Balancer cannot recover by itself.
+ // gRPC internals will fail the RPC if an error is returned.
+ Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error)
+ // Notify returns a channel that is used by gRPC internals to watch the addresses
+ // gRPC needs to connect. The addresses might be from a name resolver or remote
+ // load balancer. gRPC internals will compare it with the existing connected
+ // addresses. If the address Balancer notified is not in the existing connected
+ // addresses, gRPC starts to connect the address. If an address in the existing
+ // connected addresses is not in the notification list, the corresponding connection
+ // is shutdown gracefully. Otherwise, there are no operations to take. Note that
+ // the Address slice must be the full list of the Addresses which should be connected.
+ // It is NOT delta.
+ Notify() <-chan []Address
+ // Close shuts down the balancer.
+ Close() error
+}
+
+// downErr implements net.Error. It is constructed by gRPC internals and passed to the down
+// call of Balancer.
+type downErr struct {
+ timeout bool
+ temporary bool
+ desc string
+}
+
+func (e downErr) Error() string { return e.desc }
+func (e downErr) Timeout() bool { return e.timeout }
+func (e downErr) Temporary() bool { return e.temporary }
+
+func downErrorf(timeout, temporary bool, format string, a ...interface{}) downErr {
+ return downErr{
+ timeout: timeout,
+ temporary: temporary,
+ desc: fmt.Sprintf(format, a...),
+ }
+}
+
+// RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch
+// the name resolution updates and updates the addresses available correspondingly.
+func RoundRobin(r naming.Resolver) Balancer {
+ return &roundRobin{r: r}
+}
+
+type addrInfo struct {
+ addr Address
+ connected bool
+}
+
+type roundRobin struct {
+ r naming.Resolver
+ w naming.Watcher
+ addrs []*addrInfo // all the addresses the client should potentially connect
+ mu sync.Mutex
+ addrCh chan []Address // the channel to notify gRPC internals the list of addresses the client should connect to.
+ next int // index of the next address to return for Get()
+ waitCh chan struct{} // the channel to block when there is no connected address available
+ done bool // The Balancer is closed.
+}
+
+func (rr *roundRobin) watchAddrUpdates() error {
+ updates, err := rr.w.Next()
+ if err != nil {
+ grpclog.Printf("grpc: the naming watcher stops working due to %v.\n", err)
+ return err
+ }
+ rr.mu.Lock()
+ defer rr.mu.Unlock()
+ for _, update := range updates {
+ addr := Address{
+ Addr: update.Addr,
+ Metadata: update.Metadata,
+ }
+ switch update.Op {
+ case naming.Add:
+ var exist bool
+ for _, v := range rr.addrs {
+ if addr == v.addr {
+ exist = true
+ grpclog.Println("grpc: The name resolver wanted to add an existing address: ", addr)
+ break
+ }
+ }
+ if exist {
+ continue
+ }
+ rr.addrs = append(rr.addrs, &addrInfo{addr: addr})
+ case naming.Delete:
+ for i, v := range rr.addrs {
+ if addr == v.addr {
+ copy(rr.addrs[i:], rr.addrs[i+1:])
+ rr.addrs = rr.addrs[:len(rr.addrs)-1]
+ break
+ }
+ }
+ default:
+ grpclog.Println("Unknown update.Op ", update.Op)
+ }
+ }
+ // Make a copy of rr.addrs and write it onto rr.addrCh so that gRPC internals gets notified.
+ open := make([]Address, len(rr.addrs))
+ for i, v := range rr.addrs {
+ open[i] = v.addr
+ }
+ if rr.done {
+ return ErrClientConnClosing
+ }
+ rr.addrCh <- open
+ return nil
+}
+
+func (rr *roundRobin) Start(target string, config BalancerConfig) error {
+ rr.mu.Lock()
+ defer rr.mu.Unlock()
+ if rr.done {
+ return ErrClientConnClosing
+ }
+ if rr.r == nil {
+ // If there is no name resolver installed, it is not needed to
+ // do name resolution. In this case, target is added into rr.addrs
+ // as the only address available and rr.addrCh stays nil.
+ rr.addrs = append(rr.addrs, &addrInfo{addr: Address{Addr: target}})
+ return nil
+ }
+ w, err := rr.r.Resolve(target)
+ if err != nil {
+ return err
+ }
+ rr.w = w
+ rr.addrCh = make(chan []Address)
+ go func() {
+ for {
+ if err := rr.watchAddrUpdates(); err != nil {
+ return
+ }
+ }
+ }()
+ return nil
+}
+
+// Up sets the connected state of addr and sends notification if there are pending
+// Get() calls.
+func (rr *roundRobin) Up(addr Address) func(error) {
+ rr.mu.Lock()
+ defer rr.mu.Unlock()
+ var cnt int
+ for _, a := range rr.addrs {
+ if a.addr == addr {
+ if a.connected {
+ return nil
+ }
+ a.connected = true
+ }
+ if a.connected {
+ cnt++
+ }
+ }
+ // addr is only one which is connected. Notify the Get() callers who are blocking.
+ if cnt == 1 && rr.waitCh != nil {
+ close(rr.waitCh)
+ rr.waitCh = nil
+ }
+ return func(err error) {
+ rr.down(addr, err)
+ }
+}
+
+// down unsets the connected state of addr.
+func (rr *roundRobin) down(addr Address, err error) {
+ rr.mu.Lock()
+ defer rr.mu.Unlock()
+ for _, a := range rr.addrs {
+ if addr == a.addr {
+ a.connected = false
+ break
+ }
+ }
+}
+
+// Get returns the next addr in the rotation.
+func (rr *roundRobin) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) {
+ var ch chan struct{}
+ rr.mu.Lock()
+ if rr.done {
+ rr.mu.Unlock()
+ err = ErrClientConnClosing
+ return
+ }
+
+ if len(rr.addrs) > 0 {
+ if rr.next >= len(rr.addrs) {
+ rr.next = 0
+ }
+ next := rr.next
+ for {
+ a := rr.addrs[next]
+ next = (next + 1) % len(rr.addrs)
+ if a.connected {
+ addr = a.addr
+ rr.next = next
+ rr.mu.Unlock()
+ return
+ }
+ if next == rr.next {
+ // Has iterated all the possible address but none is connected.
+ break
+ }
+ }
+ }
+ if !opts.BlockingWait {
+ if len(rr.addrs) == 0 {
+ rr.mu.Unlock()
+ err = Errorf(codes.Unavailable, "there is no address available")
+ return
+ }
+ // Returns the next addr on rr.addrs for failfast RPCs.
+ addr = rr.addrs[rr.next].addr
+ rr.next++
+ rr.mu.Unlock()
+ return
+ }
+ // Wait on rr.waitCh for non-failfast RPCs.
+ if rr.waitCh == nil {
+ ch = make(chan struct{})
+ rr.waitCh = ch
+ } else {
+ ch = rr.waitCh
+ }
+ rr.mu.Unlock()
+ for {
+ select {
+ case <-ctx.Done():
+ err = ctx.Err()
+ return
+ case <-ch:
+ rr.mu.Lock()
+ if rr.done {
+ rr.mu.Unlock()
+ err = ErrClientConnClosing
+ return
+ }
+
+ if len(rr.addrs) > 0 {
+ if rr.next >= len(rr.addrs) {
+ rr.next = 0
+ }
+ next := rr.next
+ for {
+ a := rr.addrs[next]
+ next = (next + 1) % len(rr.addrs)
+ if a.connected {
+ addr = a.addr
+ rr.next = next
+ rr.mu.Unlock()
+ return
+ }
+ if next == rr.next {
+ // Has iterated all the possible address but none is connected.
+ break
+ }
+ }
+ }
+ // The newly added addr got removed by Down() again.
+ if rr.waitCh == nil {
+ ch = make(chan struct{})
+ rr.waitCh = ch
+ } else {
+ ch = rr.waitCh
+ }
+ rr.mu.Unlock()
+ }
+ }
+}
+
+func (rr *roundRobin) Notify() <-chan []Address {
+ return rr.addrCh
+}
+
+func (rr *roundRobin) Close() error {
+ rr.mu.Lock()
+ defer rr.mu.Unlock()
+ rr.done = true
+ if rr.w != nil {
+ rr.w.Close()
+ }
+ if rr.waitCh != nil {
+ close(rr.waitCh)
+ rr.waitCh = nil
+ }
+ if rr.addrCh != nil {
+ close(rr.addrCh)
+ }
+ return nil
+}
diff --git a/vendor/google.golang.org/grpc/call.go b/vendor/google.golang.org/grpc/call.go
new file mode 100644
index 0000000..af34a71
--- /dev/null
+++ b/vendor/google.golang.org/grpc/call.go
@@ -0,0 +1,306 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "bytes"
+ "io"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/net/trace"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/peer"
+ "google.golang.org/grpc/stats"
+ "google.golang.org/grpc/status"
+ "google.golang.org/grpc/transport"
+)
+
+// recvResponse receives and parses an RPC response.
+// On error, it returns the error and indicates whether the call should be retried.
+//
+// TODO(zhaoq): Check whether the received message sequence is valid.
+// TODO ctx is used for stats collection and processing. It is the context passed from the application.
+func recvResponse(ctx context.Context, dopts dialOptions, t transport.ClientTransport, c *callInfo, stream *transport.Stream, reply interface{}) (err error) {
+ // Try to acquire header metadata from the server if there is any.
+ defer func() {
+ if err != nil {
+ if _, ok := err.(transport.ConnectionError); !ok {
+ t.CloseStream(stream, err)
+ }
+ }
+ }()
+ c.headerMD, err = stream.Header()
+ if err != nil {
+ return
+ }
+ p := &parser{r: stream}
+ var inPayload *stats.InPayload
+ if dopts.copts.StatsHandler != nil {
+ inPayload = &stats.InPayload{
+ Client: true,
+ }
+ }
+ for {
+ if err = recv(p, dopts.codec, stream, dopts.dc, reply, dopts.maxMsgSize, inPayload); err != nil {
+ if err == io.EOF {
+ break
+ }
+ return
+ }
+ }
+ if inPayload != nil && err == io.EOF && stream.Status().Code() == codes.OK {
+ // TODO in the current implementation, inTrailer may be handled before inPayload in some cases.
+ // Fix the order if necessary.
+ dopts.copts.StatsHandler.HandleRPC(ctx, inPayload)
+ }
+ c.trailerMD = stream.Trailer()
+ if peer, ok := peer.FromContext(stream.Context()); ok {
+ c.peer = peer
+ }
+ return nil
+}
+
+// sendRequest writes out various information of an RPC such as Context and Message.
+func sendRequest(ctx context.Context, dopts dialOptions, compressor Compressor, callHdr *transport.CallHdr, stream *transport.Stream, t transport.ClientTransport, args interface{}, opts *transport.Options) (err error) {
+ defer func() {
+ if err != nil {
+ // If err is connection error, t will be closed, no need to close stream here.
+ if _, ok := err.(transport.ConnectionError); !ok {
+ t.CloseStream(stream, err)
+ }
+ }
+ }()
+ var (
+ cbuf *bytes.Buffer
+ outPayload *stats.OutPayload
+ )
+ if compressor != nil {
+ cbuf = new(bytes.Buffer)
+ }
+ if dopts.copts.StatsHandler != nil {
+ outPayload = &stats.OutPayload{
+ Client: true,
+ }
+ }
+ outBuf, err := encode(dopts.codec, args, compressor, cbuf, outPayload)
+ if err != nil {
+ return Errorf(codes.Internal, "grpc: %v", err)
+ }
+ err = t.Write(stream, outBuf, opts)
+ if err == nil && outPayload != nil {
+ outPayload.SentTime = time.Now()
+ dopts.copts.StatsHandler.HandleRPC(ctx, outPayload)
+ }
+ // t.NewStream(...) could lead to an early rejection of the RPC (e.g., the service/method
+ // does not exist.) so that t.Write could get io.EOF from wait(...). Leave the following
+ // recvResponse to get the final status.
+ if err != nil && err != io.EOF {
+ return err
+ }
+ // Sent successfully.
+ return nil
+}
+
+// Invoke sends the RPC request on the wire and returns after response is received.
+// Invoke is called by generated code. Also users can call Invoke directly when it
+// is really needed in their use cases.
+func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error {
+ if cc.dopts.unaryInt != nil {
+ return cc.dopts.unaryInt(ctx, method, args, reply, cc, invoke, opts...)
+ }
+ return invoke(ctx, method, args, reply, cc, opts...)
+}
+
+func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (e error) {
+ c := defaultCallInfo
+ if mc, ok := cc.getMethodConfig(method); ok {
+ c.failFast = !mc.WaitForReady
+ if mc.Timeout > 0 {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithTimeout(ctx, mc.Timeout)
+ defer cancel()
+ }
+ }
+ for _, o := range opts {
+ if err := o.before(&c); err != nil {
+ return toRPCErr(err)
+ }
+ }
+ defer func() {
+ for _, o := range opts {
+ o.after(&c)
+ }
+ }()
+ if EnableTracing {
+ c.traceInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
+ defer c.traceInfo.tr.Finish()
+ c.traceInfo.firstLine.client = true
+ if deadline, ok := ctx.Deadline(); ok {
+ c.traceInfo.firstLine.deadline = deadline.Sub(time.Now())
+ }
+ c.traceInfo.tr.LazyLog(&c.traceInfo.firstLine, false)
+ // TODO(dsymonds): Arrange for c.traceInfo.firstLine.remoteAddr to be set.
+ defer func() {
+ if e != nil {
+ c.traceInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{e}}, true)
+ c.traceInfo.tr.SetError()
+ }
+ }()
+ }
+ ctx = newContextWithRPCInfo(ctx)
+ sh := cc.dopts.copts.StatsHandler
+ if sh != nil {
+ ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method})
+ begin := &stats.Begin{
+ Client: true,
+ BeginTime: time.Now(),
+ FailFast: c.failFast,
+ }
+ sh.HandleRPC(ctx, begin)
+ }
+ defer func() {
+ if sh != nil {
+ end := &stats.End{
+ Client: true,
+ EndTime: time.Now(),
+ Error: e,
+ }
+ sh.HandleRPC(ctx, end)
+ }
+ }()
+ topts := &transport.Options{
+ Last: true,
+ Delay: false,
+ }
+ for {
+ var (
+ err error
+ t transport.ClientTransport
+ stream *transport.Stream
+ // Record the put handler from Balancer.Get(...). It is called once the
+ // RPC has completed or failed.
+ put func()
+ )
+ // TODO(zhaoq): Need a formal spec of fail-fast.
+ callHdr := &transport.CallHdr{
+ Host: cc.authority,
+ Method: method,
+ }
+ if cc.dopts.cp != nil {
+ callHdr.SendCompress = cc.dopts.cp.Type()
+ }
+
+ gopts := BalancerGetOptions{
+ BlockingWait: !c.failFast,
+ }
+ t, put, err = cc.getTransport(ctx, gopts)
+ if err != nil {
+ // TODO(zhaoq): Probably revisit the error handling.
+ if _, ok := status.FromError(err); ok {
+ return err
+ }
+ if err == errConnClosing || err == errConnUnavailable {
+ if c.failFast {
+ return Errorf(codes.Unavailable, "%v", err)
+ }
+ continue
+ }
+ // All the other errors are treated as Internal errors.
+ return Errorf(codes.Internal, "%v", err)
+ }
+ if c.traceInfo.tr != nil {
+ c.traceInfo.tr.LazyLog(&payload{sent: true, msg: args}, true)
+ }
+ stream, err = t.NewStream(ctx, callHdr)
+ if err != nil {
+ if put != nil {
+ if _, ok := err.(transport.ConnectionError); ok {
+ // If error is connection error, transport was sending data on wire,
+ // and we are not sure if anything has been sent on wire.
+ // If error is not connection error, we are sure nothing has been sent.
+ updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false})
+ }
+ put()
+ }
+ if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
+ continue
+ }
+ return toRPCErr(err)
+ }
+ err = sendRequest(ctx, cc.dopts, cc.dopts.cp, callHdr, stream, t, args, topts)
+ if err != nil {
+ if put != nil {
+ updateRPCInfoInContext(ctx, rpcInfo{
+ bytesSent: stream.BytesSent(),
+ bytesReceived: stream.BytesReceived(),
+ })
+ put()
+ }
+ // Retry a non-failfast RPC when
+ // i) there is a connection error; or
+ // ii) the server started to drain before this RPC was initiated.
+ if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
+ continue
+ }
+ return toRPCErr(err)
+ }
+ err = recvResponse(ctx, cc.dopts, t, &c, stream, reply)
+ if err != nil {
+ if put != nil {
+ updateRPCInfoInContext(ctx, rpcInfo{
+ bytesSent: stream.BytesSent(),
+ bytesReceived: stream.BytesReceived(),
+ })
+ put()
+ }
+ if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
+ continue
+ }
+ return toRPCErr(err)
+ }
+ if c.traceInfo.tr != nil {
+ c.traceInfo.tr.LazyLog(&payload{sent: false, msg: reply}, true)
+ }
+ t.CloseStream(stream, nil)
+ if put != nil {
+ updateRPCInfoInContext(ctx, rpcInfo{
+ bytesSent: stream.BytesSent(),
+ bytesReceived: stream.BytesReceived(),
+ })
+ put()
+ }
+ return stream.Status().Err()
+ }
+}
diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go
new file mode 100644
index 0000000..f542d8b
--- /dev/null
+++ b/vendor/google.golang.org/grpc/clientconn.go
@@ -0,0 +1,1030 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "net"
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/net/trace"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/grpclog"
+ "google.golang.org/grpc/keepalive"
+ "google.golang.org/grpc/stats"
+ "google.golang.org/grpc/transport"
+)
+
+var (
+ // ErrClientConnClosing indicates that the operation is illegal because
+ // the ClientConn is closing.
+ ErrClientConnClosing = errors.New("grpc: the client connection is closing")
+ // ErrClientConnTimeout indicates that the ClientConn cannot establish the
+ // underlying connections within the specified timeout.
+ // DEPRECATED: Please use context.DeadlineExceeded instead. This error will be
+ // removed in Q1 2017.
+ ErrClientConnTimeout = errors.New("grpc: timed out when dialing")
+
+ // errNoTransportSecurity indicates that there is no transport security
+ // being set for ClientConn. Users should either set one or explicitly
+ // call WithInsecure DialOption to disable security.
+ errNoTransportSecurity = errors.New("grpc: no transport security set (use grpc.WithInsecure() explicitly or set credentials)")
+ // errTransportCredentialsMissing indicates that users want to transmit security
+ // information (e.g., oauth2 token) which requires secure connection on an insecure
+ // connection.
+ errTransportCredentialsMissing = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)")
+ // errCredentialsConflict indicates that grpc.WithTransportCredentials()
+ // and grpc.WithInsecure() are both called for a connection.
+ errCredentialsConflict = errors.New("grpc: transport credentials are set for an insecure connection (grpc.WithTransportCredentials() and grpc.WithInsecure() are both called)")
+ // errNetworkIO indicates that the connection is down due to some network I/O error.
+ errNetworkIO = errors.New("grpc: failed with network I/O error")
+ // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs.
+ errConnDrain = errors.New("grpc: the connection is drained")
+ // errConnClosing indicates that the connection is closing.
+ errConnClosing = errors.New("grpc: the connection is closing")
+ // errConnUnavailable indicates that the connection is unavailable.
+ errConnUnavailable = errors.New("grpc: the connection is unavailable")
+ // minimum time to give a connection to complete
+ minConnectTimeout = 20 * time.Second
+)
+
+// dialOptions configure a Dial call. dialOptions are set by the DialOption
+// values passed to Dial.
+type dialOptions struct {
+ unaryInt UnaryClientInterceptor
+ streamInt StreamClientInterceptor
+ codec Codec
+ cp Compressor
+ dc Decompressor
+ bs backoffStrategy
+ balancer Balancer
+ block bool
+ insecure bool
+ timeout time.Duration
+ scChan <-chan ServiceConfig
+ copts transport.ConnectOptions
+ maxMsgSize int
+}
+
+const defaultClientMaxMsgSize = math.MaxInt32
+
+// DialOption configures how we set up the connection.
+type DialOption func(*dialOptions)
+
+// WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive.
+func WithMaxMsgSize(s int) DialOption {
+ return func(o *dialOptions) {
+ o.maxMsgSize = s
+ }
+}
+
+// WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.
+func WithCodec(c Codec) DialOption {
+ return func(o *dialOptions) {
+ o.codec = c
+ }
+}
+
+// WithCompressor returns a DialOption which sets a CompressorGenerator for generating message
+// compressor.
+func WithCompressor(cp Compressor) DialOption {
+ return func(o *dialOptions) {
+ o.cp = cp
+ }
+}
+
+// WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating
+// message decompressor.
+func WithDecompressor(dc Decompressor) DialOption {
+ return func(o *dialOptions) {
+ o.dc = dc
+ }
+}
+
+// WithBalancer returns a DialOption which sets a load balancer.
+func WithBalancer(b Balancer) DialOption {
+ return func(o *dialOptions) {
+ o.balancer = b
+ }
+}
+
+// WithServiceConfig returns a DialOption which has a channel to read the service configuration.
+func WithServiceConfig(c <-chan ServiceConfig) DialOption {
+ return func(o *dialOptions) {
+ o.scChan = c
+ }
+}
+
+// WithBackoffMaxDelay configures the dialer to use the provided maximum delay
+// when backing off after failed connection attempts.
+func WithBackoffMaxDelay(md time.Duration) DialOption {
+ return WithBackoffConfig(BackoffConfig{MaxDelay: md})
+}
+
+// WithBackoffConfig configures the dialer to use the provided backoff
+// parameters after connection failures.
+//
+// Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up
+// for use.
+func WithBackoffConfig(b BackoffConfig) DialOption {
+ // Set defaults to ensure that provided BackoffConfig is valid and
+ // unexported fields get default values.
+ setDefaults(&b)
+ return withBackoff(b)
+}
+
+// withBackoff sets the backoff strategy used for retries after a
+// failed connection attempt.
+//
+// This can be exported if arbitrary backoff strategies are allowed by gRPC.
+func withBackoff(bs backoffStrategy) DialOption {
+ return func(o *dialOptions) {
+ o.bs = bs
+ }
+}
+
+// WithBlock returns a DialOption which makes caller of Dial blocks until the underlying
+// connection is up. Without this, Dial returns immediately and connecting the server
+// happens in background.
+func WithBlock() DialOption {
+ return func(o *dialOptions) {
+ o.block = true
+ }
+}
+
+// WithInsecure returns a DialOption which disables transport security for this ClientConn.
+// Note that transport security is required unless WithInsecure is set.
+func WithInsecure() DialOption {
+ return func(o *dialOptions) {
+ o.insecure = true
+ }
+}
+
+// WithTransportCredentials returns a DialOption which configures a
+// connection level security credentials (e.g., TLS/SSL).
+func WithTransportCredentials(creds credentials.TransportCredentials) DialOption {
+ return func(o *dialOptions) {
+ o.copts.TransportCredentials = creds
+ }
+}
+
+// WithPerRPCCredentials returns a DialOption which sets
+// credentials which will place auth state on each outbound RPC.
+func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption {
+ return func(o *dialOptions) {
+ o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds)
+ }
+}
+
+// WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn
+// initially. This is valid if and only if WithBlock() is present.
+func WithTimeout(d time.Duration) DialOption {
+ return func(o *dialOptions) {
+ o.timeout = d
+ }
+}
+
+// WithDialer returns a DialOption that specifies a function to use for dialing network addresses.
+// If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error's
+// Temporary() method to decide if it should try to reconnect to the network address.
+func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption {
+ return func(o *dialOptions) {
+ o.copts.Dialer = func(ctx context.Context, addr string) (net.Conn, error) {
+ if deadline, ok := ctx.Deadline(); ok {
+ return f(addr, deadline.Sub(time.Now()))
+ }
+ return f(addr, 0)
+ }
+ }
+}
+
+// WithStatsHandler returns a DialOption that specifies the stats handler
+// for all the RPCs and underlying network connections in this ClientConn.
+func WithStatsHandler(h stats.Handler) DialOption {
+ return func(o *dialOptions) {
+ o.copts.StatsHandler = h
+ }
+}
+
+// FailOnNonTempDialError returns a DialOption that specified if gRPC fails on non-temporary dial errors.
+// If f is true, and dialer returns a non-temporary error, gRPC will fail the connection to the network
+// address and won't try to reconnect.
+// The default value of FailOnNonTempDialError is false.
+// This is an EXPERIMENTAL API.
+func FailOnNonTempDialError(f bool) DialOption {
+ return func(o *dialOptions) {
+ o.copts.FailOnNonTempDialError = f
+ }
+}
+
+// WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.
+func WithUserAgent(s string) DialOption {
+ return func(o *dialOptions) {
+ o.copts.UserAgent = s
+ }
+}
+
+// WithKeepaliveParams returns a DialOption that specifies keepalive paramaters for the client transport.
+func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption {
+ return func(o *dialOptions) {
+ o.copts.KeepaliveParams = kp
+ }
+}
+
+// WithUnaryInterceptor returns a DialOption that specifies the interceptor for unary RPCs.
+func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption {
+ return func(o *dialOptions) {
+ o.unaryInt = f
+ }
+}
+
+// WithStreamInterceptor returns a DialOption that specifies the interceptor for streaming RPCs.
+func WithStreamInterceptor(f StreamClientInterceptor) DialOption {
+ return func(o *dialOptions) {
+ o.streamInt = f
+ }
+}
+
+// WithAuthority returns a DialOption that specifies the value to be used as
+// the :authority pseudo-header. This value only works with WithInsecure and
+// has no effect if TransportCredentials are present.
+func WithAuthority(a string) DialOption {
+ return func(o *dialOptions) {
+ o.copts.Authority = a
+ }
+}
+
+// Dial creates a client connection to the given target.
+func Dial(target string, opts ...DialOption) (*ClientConn, error) {
+ return DialContext(context.Background(), target, opts...)
+}
+
+// DialContext creates a client connection to the given target. ctx can be used to
+// cancel or expire the pending connecting. Once this function returns, the
+// cancellation and expiration of ctx will be noop. Users should call ClientConn.Close
+// to terminate all the pending operations after this function returns.
+// This is the EXPERIMENTAL API.
+func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error) {
+ cc := &ClientConn{
+ target: target,
+ conns: make(map[Address]*addrConn),
+ }
+ cc.ctx, cc.cancel = context.WithCancel(context.Background())
+ cc.dopts.maxMsgSize = defaultClientMaxMsgSize
+ for _, opt := range opts {
+ opt(&cc.dopts)
+ }
+ cc.mkp = cc.dopts.copts.KeepaliveParams
+
+ if cc.dopts.copts.Dialer == nil {
+ cc.dopts.copts.Dialer = newProxyDialer(
+ func(ctx context.Context, addr string) (net.Conn, error) {
+ return dialContext(ctx, "tcp", addr)
+ },
+ )
+ }
+
+ if cc.dopts.copts.UserAgent != "" {
+ cc.dopts.copts.UserAgent += " " + grpcUA
+ } else {
+ cc.dopts.copts.UserAgent = grpcUA
+ }
+
+ if cc.dopts.timeout > 0 {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithTimeout(ctx, cc.dopts.timeout)
+ defer cancel()
+ }
+
+ defer func() {
+ select {
+ case <-ctx.Done():
+ conn, err = nil, ctx.Err()
+ default:
+ }
+
+ if err != nil {
+ cc.Close()
+ }
+ }()
+
+ if cc.dopts.scChan != nil {
+ // Wait for the initial service config.
+ select {
+ case sc, ok := <-cc.dopts.scChan:
+ if ok {
+ cc.sc = sc
+ }
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+ // Set defaults.
+ if cc.dopts.codec == nil {
+ cc.dopts.codec = protoCodec{}
+ }
+ if cc.dopts.bs == nil {
+ cc.dopts.bs = DefaultBackoffConfig
+ }
+ creds := cc.dopts.copts.TransportCredentials
+ if creds != nil && creds.Info().ServerName != "" {
+ cc.authority = creds.Info().ServerName
+ } else if cc.dopts.insecure && cc.dopts.copts.Authority != "" {
+ cc.authority = cc.dopts.copts.Authority
+ } else {
+ cc.authority = target
+ }
+ waitC := make(chan error, 1)
+ go func() {
+ defer close(waitC)
+ if cc.dopts.balancer == nil && cc.sc.LB != nil {
+ cc.dopts.balancer = cc.sc.LB
+ }
+ if cc.dopts.balancer != nil {
+ var credsClone credentials.TransportCredentials
+ if creds != nil {
+ credsClone = creds.Clone()
+ }
+ config := BalancerConfig{
+ DialCreds: credsClone,
+ }
+ if err := cc.dopts.balancer.Start(target, config); err != nil {
+ waitC <- err
+ return
+ }
+ ch := cc.dopts.balancer.Notify()
+ if ch != nil {
+ if cc.dopts.block {
+ doneChan := make(chan struct{})
+ go cc.lbWatcher(doneChan)
+ <-doneChan
+ } else {
+ go cc.lbWatcher(nil)
+ }
+ return
+ }
+ }
+ // No balancer, or no resolver within the balancer. Connect directly.
+ if err := cc.resetAddrConn(Address{Addr: target}, cc.dopts.block, nil); err != nil {
+ waitC <- err
+ return
+ }
+ }()
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case err := <-waitC:
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ if cc.dopts.scChan != nil {
+ go cc.scWatcher()
+ }
+
+ return cc, nil
+}
+
+// ConnectivityState indicates the state of a client connection.
+type ConnectivityState int
+
+const (
+ // Idle indicates the ClientConn is idle.
+ Idle ConnectivityState = iota
+ // Connecting indicates the ClienConn is connecting.
+ Connecting
+ // Ready indicates the ClientConn is ready for work.
+ Ready
+ // TransientFailure indicates the ClientConn has seen a failure but expects to recover.
+ TransientFailure
+ // Shutdown indicates the ClientConn has started shutting down.
+ Shutdown
+)
+
+func (s ConnectivityState) String() string {
+ switch s {
+ case Idle:
+ return "IDLE"
+ case Connecting:
+ return "CONNECTING"
+ case Ready:
+ return "READY"
+ case TransientFailure:
+ return "TRANSIENT_FAILURE"
+ case Shutdown:
+ return "SHUTDOWN"
+ default:
+ panic(fmt.Sprintf("unknown connectivity state: %d", s))
+ }
+}
+
+// ClientConn represents a client connection to an RPC server.
+type ClientConn struct {
+ ctx context.Context
+ cancel context.CancelFunc
+
+ target string
+ authority string
+ dopts dialOptions
+
+ mu sync.RWMutex
+ sc ServiceConfig
+ conns map[Address]*addrConn
+ // Keepalive parameter can be udated if a GoAway is received.
+ mkp keepalive.ClientParameters
+}
+
+// lbWatcher watches the Notify channel of the balancer in cc and manages
+// connections accordingly. If doneChan is not nil, it is closed after the
+// first successfull connection is made.
+func (cc *ClientConn) lbWatcher(doneChan chan struct{}) {
+ for addrs := range cc.dopts.balancer.Notify() {
+ var (
+ add []Address // Addresses need to setup connections.
+ del []*addrConn // Connections need to tear down.
+ )
+ cc.mu.Lock()
+ for _, a := range addrs {
+ if _, ok := cc.conns[a]; !ok {
+ add = append(add, a)
+ }
+ }
+ for k, c := range cc.conns {
+ var keep bool
+ for _, a := range addrs {
+ if k == a {
+ keep = true
+ break
+ }
+ }
+ if !keep {
+ del = append(del, c)
+ delete(cc.conns, c.addr)
+ }
+ }
+ cc.mu.Unlock()
+ for _, a := range add {
+ if doneChan != nil {
+ err := cc.resetAddrConn(a, true, nil)
+ if err == nil {
+ close(doneChan)
+ doneChan = nil
+ }
+ } else {
+ cc.resetAddrConn(a, false, nil)
+ }
+ }
+ for _, c := range del {
+ c.tearDown(errConnDrain)
+ }
+ }
+}
+
+func (cc *ClientConn) scWatcher() {
+ for {
+ select {
+ case sc, ok := <-cc.dopts.scChan:
+ if !ok {
+ return
+ }
+ cc.mu.Lock()
+ // TODO: load balance policy runtime change is ignored.
+ // We may revist this decision in the future.
+ cc.sc = sc
+ cc.mu.Unlock()
+ case <-cc.ctx.Done():
+ return
+ }
+ }
+}
+
+// resetAddrConn creates an addrConn for addr and adds it to cc.conns.
+// If there is an old addrConn for addr, it will be torn down, using tearDownErr as the reason.
+// If tearDownErr is nil, errConnDrain will be used instead.
+func (cc *ClientConn) resetAddrConn(addr Address, block bool, tearDownErr error) error {
+ ac := &addrConn{
+ cc: cc,
+ addr: addr,
+ dopts: cc.dopts,
+ }
+ cc.mu.RLock()
+ ac.dopts.copts.KeepaliveParams = cc.mkp
+ cc.mu.RUnlock()
+ ac.ctx, ac.cancel = context.WithCancel(cc.ctx)
+ ac.stateCV = sync.NewCond(&ac.mu)
+ if EnableTracing {
+ ac.events = trace.NewEventLog("grpc.ClientConn", ac.addr.Addr)
+ }
+ if !ac.dopts.insecure {
+ if ac.dopts.copts.TransportCredentials == nil {
+ return errNoTransportSecurity
+ }
+ } else {
+ if ac.dopts.copts.TransportCredentials != nil {
+ return errCredentialsConflict
+ }
+ for _, cd := range ac.dopts.copts.PerRPCCredentials {
+ if cd.RequireTransportSecurity() {
+ return errTransportCredentialsMissing
+ }
+ }
+ }
+ // Track ac in cc. This needs to be done before any getTransport(...) is called.
+ cc.mu.Lock()
+ if cc.conns == nil {
+ cc.mu.Unlock()
+ return ErrClientConnClosing
+ }
+ stale := cc.conns[ac.addr]
+ cc.conns[ac.addr] = ac
+ cc.mu.Unlock()
+ if stale != nil {
+ // There is an addrConn alive on ac.addr already. This could be due to
+ // 1) a buggy Balancer notifies duplicated Addresses;
+ // 2) goaway was received, a new ac will replace the old ac.
+ // The old ac should be deleted from cc.conns, but the
+ // underlying transport should drain rather than close.
+ if tearDownErr == nil {
+ // tearDownErr is nil if resetAddrConn is called by
+ // 1) Dial
+ // 2) lbWatcher
+ // In both cases, the stale ac should drain, not close.
+ stale.tearDown(errConnDrain)
+ } else {
+ stale.tearDown(tearDownErr)
+ }
+ }
+ if block {
+ if err := ac.resetTransport(false); err != nil {
+ if err != errConnClosing {
+ // Tear down ac and delete it from cc.conns.
+ cc.mu.Lock()
+ delete(cc.conns, ac.addr)
+ cc.mu.Unlock()
+ ac.tearDown(err)
+ }
+ if e, ok := err.(transport.ConnectionError); ok && !e.Temporary() {
+ return e.Origin()
+ }
+ return err
+ }
+ // Start to monitor the error status of transport.
+ go ac.transportMonitor()
+ } else {
+ // Start a goroutine connecting to the server asynchronously.
+ go func() {
+ if err := ac.resetTransport(false); err != nil {
+ grpclog.Printf("Failed to dial %s: %v; please retry.", ac.addr.Addr, err)
+ if err != errConnClosing {
+ // Keep this ac in cc.conns, to get the reason it's torn down.
+ ac.tearDown(err)
+ }
+ return
+ }
+ ac.transportMonitor()
+ }()
+ }
+ return nil
+}
+
+// TODO: Avoid the locking here.
+func (cc *ClientConn) getMethodConfig(method string) (m MethodConfig, ok bool) {
+ cc.mu.RLock()
+ defer cc.mu.RUnlock()
+ m, ok = cc.sc.Methods[method]
+ return
+}
+
+func (cc *ClientConn) getTransport(ctx context.Context, opts BalancerGetOptions) (transport.ClientTransport, func(), error) {
+ var (
+ ac *addrConn
+ ok bool
+ put func()
+ )
+ if cc.dopts.balancer == nil {
+ // If balancer is nil, there should be only one addrConn available.
+ cc.mu.RLock()
+ if cc.conns == nil {
+ cc.mu.RUnlock()
+ return nil, nil, toRPCErr(ErrClientConnClosing)
+ }
+ for _, ac = range cc.conns {
+ // Break after the first iteration to get the first addrConn.
+ ok = true
+ break
+ }
+ cc.mu.RUnlock()
+ } else {
+ var (
+ addr Address
+ err error
+ )
+ addr, put, err = cc.dopts.balancer.Get(ctx, opts)
+ if err != nil {
+ return nil, nil, toRPCErr(err)
+ }
+ cc.mu.RLock()
+ if cc.conns == nil {
+ cc.mu.RUnlock()
+ return nil, nil, toRPCErr(ErrClientConnClosing)
+ }
+ ac, ok = cc.conns[addr]
+ cc.mu.RUnlock()
+ }
+ if !ok {
+ if put != nil {
+ updateRPCInfoInContext(ctx, rpcInfo{bytesSent: false, bytesReceived: false})
+ put()
+ }
+ return nil, nil, errConnClosing
+ }
+ t, err := ac.wait(ctx, cc.dopts.balancer != nil, !opts.BlockingWait)
+ if err != nil {
+ if put != nil {
+ updateRPCInfoInContext(ctx, rpcInfo{bytesSent: false, bytesReceived: false})
+ put()
+ }
+ return nil, nil, err
+ }
+ return t, put, nil
+}
+
+// Close tears down the ClientConn and all underlying connections.
+func (cc *ClientConn) Close() error {
+ cc.cancel()
+
+ cc.mu.Lock()
+ if cc.conns == nil {
+ cc.mu.Unlock()
+ return ErrClientConnClosing
+ }
+ conns := cc.conns
+ cc.conns = nil
+ cc.mu.Unlock()
+ if cc.dopts.balancer != nil {
+ cc.dopts.balancer.Close()
+ }
+ for _, ac := range conns {
+ ac.tearDown(ErrClientConnClosing)
+ }
+ return nil
+}
+
+// addrConn is a network connection to a given address.
+type addrConn struct {
+ ctx context.Context
+ cancel context.CancelFunc
+
+ cc *ClientConn
+ addr Address
+ dopts dialOptions
+ events trace.EventLog
+
+ mu sync.Mutex
+ state ConnectivityState
+ stateCV *sync.Cond
+ down func(error) // the handler called when a connection is down.
+ // ready is closed and becomes nil when a new transport is up or failed
+ // due to timeout.
+ ready chan struct{}
+ transport transport.ClientTransport
+
+ // The reason this addrConn is torn down.
+ tearDownErr error
+}
+
+// adjustParams updates parameters used to create transports upon
+// receiving a GoAway.
+func (ac *addrConn) adjustParams(r transport.GoAwayReason) {
+ switch r {
+ case transport.TooManyPings:
+ v := 2 * ac.dopts.copts.KeepaliveParams.Time
+ ac.cc.mu.Lock()
+ if v > ac.cc.mkp.Time {
+ ac.cc.mkp.Time = v
+ }
+ ac.cc.mu.Unlock()
+ }
+}
+
+// printf records an event in ac's event log, unless ac has been closed.
+// REQUIRES ac.mu is held.
+func (ac *addrConn) printf(format string, a ...interface{}) {
+ if ac.events != nil {
+ ac.events.Printf(format, a...)
+ }
+}
+
+// errorf records an error in ac's event log, unless ac has been closed.
+// REQUIRES ac.mu is held.
+func (ac *addrConn) errorf(format string, a ...interface{}) {
+ if ac.events != nil {
+ ac.events.Errorf(format, a...)
+ }
+}
+
+// getState returns the connectivity state of the Conn
+func (ac *addrConn) getState() ConnectivityState {
+ ac.mu.Lock()
+ defer ac.mu.Unlock()
+ return ac.state
+}
+
+// waitForStateChange blocks until the state changes to something other than the sourceState.
+func (ac *addrConn) waitForStateChange(ctx context.Context, sourceState ConnectivityState) (ConnectivityState, error) {
+ ac.mu.Lock()
+ defer ac.mu.Unlock()
+ if sourceState != ac.state {
+ return ac.state, nil
+ }
+ done := make(chan struct{})
+ var err error
+ go func() {
+ select {
+ case <-ctx.Done():
+ ac.mu.Lock()
+ err = ctx.Err()
+ ac.stateCV.Broadcast()
+ ac.mu.Unlock()
+ case <-done:
+ }
+ }()
+ defer close(done)
+ for sourceState == ac.state {
+ ac.stateCV.Wait()
+ if err != nil {
+ return ac.state, err
+ }
+ }
+ return ac.state, nil
+}
+
+func (ac *addrConn) resetTransport(closeTransport bool) error {
+ for retries := 0; ; retries++ {
+ ac.mu.Lock()
+ ac.printf("connecting")
+ if ac.state == Shutdown {
+ // ac.tearDown(...) has been invoked.
+ ac.mu.Unlock()
+ return errConnClosing
+ }
+ if ac.down != nil {
+ ac.down(downErrorf(false, true, "%v", errNetworkIO))
+ ac.down = nil
+ }
+ ac.state = Connecting
+ ac.stateCV.Broadcast()
+ t := ac.transport
+ ac.mu.Unlock()
+ if closeTransport && t != nil {
+ t.Close()
+ }
+ sleepTime := ac.dopts.bs.backoff(retries)
+ timeout := minConnectTimeout
+ if timeout < sleepTime {
+ timeout = sleepTime
+ }
+ ctx, cancel := context.WithTimeout(ac.ctx, timeout)
+ connectTime := time.Now()
+ sinfo := transport.TargetInfo{
+ Addr: ac.addr.Addr,
+ Metadata: ac.addr.Metadata,
+ }
+ newTransport, err := transport.NewClientTransport(ctx, sinfo, ac.dopts.copts)
+ // Don't call cancel in success path due to a race in Go 1.6:
+ // https://github.com/golang/go/issues/15078.
+ if err != nil {
+ cancel()
+
+ if e, ok := err.(transport.ConnectionError); ok && !e.Temporary() {
+ return err
+ }
+ grpclog.Printf("grpc: addrConn.resetTransport failed to create client transport: %v; Reconnecting to %v", err, ac.addr)
+ ac.mu.Lock()
+ if ac.state == Shutdown {
+ // ac.tearDown(...) has been invoked.
+ ac.mu.Unlock()
+ return errConnClosing
+ }
+ ac.errorf("transient failure: %v", err)
+ ac.state = TransientFailure
+ ac.stateCV.Broadcast()
+ if ac.ready != nil {
+ close(ac.ready)
+ ac.ready = nil
+ }
+ ac.mu.Unlock()
+ closeTransport = false
+ select {
+ case <-time.After(sleepTime - time.Since(connectTime)):
+ case <-ac.ctx.Done():
+ return ac.ctx.Err()
+ }
+ continue
+ }
+ ac.mu.Lock()
+ ac.printf("ready")
+ if ac.state == Shutdown {
+ // ac.tearDown(...) has been invoked.
+ ac.mu.Unlock()
+ newTransport.Close()
+ return errConnClosing
+ }
+ ac.state = Ready
+ ac.stateCV.Broadcast()
+ ac.transport = newTransport
+ if ac.ready != nil {
+ close(ac.ready)
+ ac.ready = nil
+ }
+ if ac.cc.dopts.balancer != nil {
+ ac.down = ac.cc.dopts.balancer.Up(ac.addr)
+ }
+ ac.mu.Unlock()
+ return nil
+ }
+}
+
+// Run in a goroutine to track the error in transport and create the
+// new transport if an error happens. It returns when the channel is closing.
+func (ac *addrConn) transportMonitor() {
+ for {
+ ac.mu.Lock()
+ t := ac.transport
+ ac.mu.Unlock()
+ select {
+ // This is needed to detect the teardown when
+ // the addrConn is idle (i.e., no RPC in flight).
+ case <-ac.ctx.Done():
+ select {
+ case <-t.Error():
+ t.Close()
+ default:
+ }
+ return
+ case <-t.GoAway():
+ ac.adjustParams(t.GetGoAwayReason())
+ // If GoAway happens without any network I/O error, ac is closed without shutting down the
+ // underlying transport (the transport will be closed when all the pending RPCs finished or
+ // failed.).
+ // If GoAway and some network I/O error happen concurrently, ac and its underlying transport
+ // are closed.
+ // In both cases, a new ac is created.
+ select {
+ case <-t.Error():
+ ac.cc.resetAddrConn(ac.addr, false, errNetworkIO)
+ default:
+ ac.cc.resetAddrConn(ac.addr, false, errConnDrain)
+ }
+ return
+ case <-t.Error():
+ select {
+ case <-ac.ctx.Done():
+ t.Close()
+ return
+ case <-t.GoAway():
+ ac.adjustParams(t.GetGoAwayReason())
+ ac.cc.resetAddrConn(ac.addr, false, errNetworkIO)
+ return
+ default:
+ }
+ ac.mu.Lock()
+ if ac.state == Shutdown {
+ // ac has been shutdown.
+ ac.mu.Unlock()
+ return
+ }
+ ac.state = TransientFailure
+ ac.stateCV.Broadcast()
+ ac.mu.Unlock()
+ if err := ac.resetTransport(true); err != nil {
+ ac.mu.Lock()
+ ac.printf("transport exiting: %v", err)
+ ac.mu.Unlock()
+ grpclog.Printf("grpc: addrConn.transportMonitor exits due to: %v", err)
+ if err != errConnClosing {
+ // Keep this ac in cc.conns, to get the reason it's torn down.
+ ac.tearDown(err)
+ }
+ return
+ }
+ }
+ }
+}
+
+// wait blocks until i) the new transport is up or ii) ctx is done or iii) ac is closed or
+// iv) transport is in TransientFailure and there is a balancer/failfast is true.
+func (ac *addrConn) wait(ctx context.Context, hasBalancer, failfast bool) (transport.ClientTransport, error) {
+ for {
+ ac.mu.Lock()
+ switch {
+ case ac.state == Shutdown:
+ if failfast || !hasBalancer {
+ // RPC is failfast or balancer is nil. This RPC should fail with ac.tearDownErr.
+ err := ac.tearDownErr
+ ac.mu.Unlock()
+ return nil, err
+ }
+ ac.mu.Unlock()
+ return nil, errConnClosing
+ case ac.state == Ready:
+ ct := ac.transport
+ ac.mu.Unlock()
+ return ct, nil
+ case ac.state == TransientFailure:
+ if failfast || hasBalancer {
+ ac.mu.Unlock()
+ return nil, errConnUnavailable
+ }
+ }
+ ready := ac.ready
+ if ready == nil {
+ ready = make(chan struct{})
+ ac.ready = ready
+ }
+ ac.mu.Unlock()
+ select {
+ case <-ctx.Done():
+ return nil, toRPCErr(ctx.Err())
+ // Wait until the new transport is ready or failed.
+ case <-ready:
+ }
+ }
+}
+
+// tearDown starts to tear down the addrConn.
+// TODO(zhaoq): Make this synchronous to avoid unbounded memory consumption in
+// some edge cases (e.g., the caller opens and closes many addrConn's in a
+// tight loop.
+// tearDown doesn't remove ac from ac.cc.conns.
+func (ac *addrConn) tearDown(err error) {
+ ac.cancel()
+
+ ac.mu.Lock()
+ defer ac.mu.Unlock()
+ if ac.down != nil {
+ ac.down(downErrorf(false, false, "%v", err))
+ ac.down = nil
+ }
+ if err == errConnDrain && ac.transport != nil {
+ // GracefulClose(...) may be executed multiple times when
+ // i) receiving multiple GoAway frames from the server; or
+ // ii) there are concurrent name resolver/Balancer triggered
+ // address removal and GoAway.
+ ac.transport.GracefulClose()
+ }
+ if ac.state == Shutdown {
+ return
+ }
+ ac.state = Shutdown
+ ac.tearDownErr = err
+ ac.stateCV.Broadcast()
+ if ac.events != nil {
+ ac.events.Finish()
+ ac.events = nil
+ }
+ if ac.ready != nil {
+ close(ac.ready)
+ ac.ready = nil
+ }
+ if ac.transport != nil && err != errConnDrain {
+ ac.transport.Close()
+ }
+ return
+}
diff --git a/vendor/google.golang.org/grpc/codec.go b/vendor/google.golang.org/grpc/codec.go
new file mode 100644
index 0000000..bd76ebb
--- /dev/null
+++ b/vendor/google.golang.org/grpc/codec.go
@@ -0,0 +1,118 @@
+/*
+*
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+*/
+
+package grpc
+
+import (
+ "math"
+ "sync"
+
+ "github.com/golang/protobuf/proto"
+)
+
+// Codec defines the interface gRPC uses to encode and decode messages.
+// Note that implementations of this interface must be thread safe;
+// a Codec's methods can be called from concurrent goroutines.
+type Codec interface {
+ // Marshal returns the wire format of v.
+ Marshal(v interface{}) ([]byte, error)
+ // Unmarshal parses the wire format into v.
+ Unmarshal(data []byte, v interface{}) error
+ // String returns the name of the Codec implementation. The returned
+ // string will be used as part of content type in transmission.
+ String() string
+}
+
+// protoCodec is a Codec implementation with protobuf. It is the default codec for gRPC.
+type protoCodec struct {
+}
+
+type cachedProtoBuffer struct {
+ lastMarshaledSize uint32
+ proto.Buffer
+}
+
+func capToMaxInt32(val int) uint32 {
+ if val > math.MaxInt32 {
+ return uint32(math.MaxInt32)
+ }
+ return uint32(val)
+}
+
+func (p protoCodec) marshal(v interface{}, cb *cachedProtoBuffer) ([]byte, error) {
+ protoMsg := v.(proto.Message)
+ newSlice := make([]byte, 0, cb.lastMarshaledSize)
+
+ cb.SetBuf(newSlice)
+ cb.Reset()
+ if err := cb.Marshal(protoMsg); err != nil {
+ return nil, err
+ }
+ out := cb.Bytes()
+ cb.lastMarshaledSize = capToMaxInt32(len(out))
+ return out, nil
+}
+
+func (p protoCodec) Marshal(v interface{}) ([]byte, error) {
+ cb := protoBufferPool.Get().(*cachedProtoBuffer)
+ out, err := p.marshal(v, cb)
+
+ // put back buffer and lose the ref to the slice
+ cb.SetBuf(nil)
+ protoBufferPool.Put(cb)
+ return out, err
+}
+
+func (p protoCodec) Unmarshal(data []byte, v interface{}) error {
+ cb := protoBufferPool.Get().(*cachedProtoBuffer)
+ cb.SetBuf(data)
+ err := cb.Unmarshal(v.(proto.Message))
+ cb.SetBuf(nil)
+ protoBufferPool.Put(cb)
+ return err
+}
+
+func (protoCodec) String() string {
+ return "proto"
+}
+
+var (
+ protoBufferPool = &sync.Pool{
+ New: func() interface{} {
+ return &cachedProtoBuffer{
+ Buffer: proto.Buffer{},
+ lastMarshaledSize: 16,
+ }
+ },
+ }
+)
diff --git a/vendor/google.golang.org/grpc/codes/code_string.go b/vendor/google.golang.org/grpc/codes/code_string.go
new file mode 100644
index 0000000..e6762d0
--- /dev/null
+++ b/vendor/google.golang.org/grpc/codes/code_string.go
@@ -0,0 +1,16 @@
+// generated by stringer -type=Code; DO NOT EDIT
+
+package codes
+
+import "fmt"
+
+const _Code_name = "OKCanceledUnknownInvalidArgumentDeadlineExceededNotFoundAlreadyExistsPermissionDeniedResourceExhaustedFailedPreconditionAbortedOutOfRangeUnimplementedInternalUnavailableDataLossUnauthenticated"
+
+var _Code_index = [...]uint8{0, 2, 10, 17, 32, 48, 56, 69, 85, 102, 120, 127, 137, 150, 158, 169, 177, 192}
+
+func (i Code) String() string {
+ if i+1 >= Code(len(_Code_index)) {
+ return fmt.Sprintf("Code(%d)", i)
+ }
+ return _Code_name[_Code_index[i]:_Code_index[i+1]]
+}
diff --git a/vendor/google.golang.org/grpc/codes/codes.go b/vendor/google.golang.org/grpc/codes/codes.go
new file mode 100644
index 0000000..e14b464
--- /dev/null
+++ b/vendor/google.golang.org/grpc/codes/codes.go
@@ -0,0 +1,159 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+// Package codes defines the canonical error codes used by gRPC. It is
+// consistent across various languages.
+package codes // import "google.golang.org/grpc/codes"
+
+// A Code is an unsigned 32-bit error code as defined in the gRPC spec.
+type Code uint32
+
+//go:generate stringer -type=Code
+
+const (
+ // OK is returned on success.
+ OK Code = 0
+
+ // Canceled indicates the operation was cancelled (typically by the caller).
+ Canceled Code = 1
+
+ // Unknown error. An example of where this error may be returned is
+ // if a Status value received from another address space belongs to
+ // an error-space that is not known in this address space. Also
+ // errors raised by APIs that do not return enough error information
+ // may be converted to this error.
+ Unknown Code = 2
+
+ // InvalidArgument indicates client specified an invalid argument.
+ // Note that this differs from FailedPrecondition. It indicates arguments
+ // that are problematic regardless of the state of the system
+ // (e.g., a malformed file name).
+ InvalidArgument Code = 3
+
+ // DeadlineExceeded means operation expired before completion.
+ // For operations that change the state of the system, this error may be
+ // returned even if the operation has completed successfully. For
+ // example, a successful response from a server could have been delayed
+ // long enough for the deadline to expire.
+ DeadlineExceeded Code = 4
+
+ // NotFound means some requested entity (e.g., file or directory) was
+ // not found.
+ NotFound Code = 5
+
+ // AlreadyExists means an attempt to create an entity failed because one
+ // already exists.
+ AlreadyExists Code = 6
+
+ // PermissionDenied indicates the caller does not have permission to
+ // execute the specified operation. It must not be used for rejections
+ // caused by exhausting some resource (use ResourceExhausted
+ // instead for those errors). It must not be
+ // used if the caller cannot be identified (use Unauthenticated
+ // instead for those errors).
+ PermissionDenied Code = 7
+
+ // Unauthenticated indicates the request does not have valid
+ // authentication credentials for the operation.
+ Unauthenticated Code = 16
+
+ // ResourceExhausted indicates some resource has been exhausted, perhaps
+ // a per-user quota, or perhaps the entire file system is out of space.
+ ResourceExhausted Code = 8
+
+ // FailedPrecondition indicates operation was rejected because the
+ // system is not in a state required for the operation's execution.
+ // For example, directory to be deleted may be non-empty, an rmdir
+ // operation is applied to a non-directory, etc.
+ //
+ // A litmus test that may help a service implementor in deciding
+ // between FailedPrecondition, Aborted, and Unavailable:
+ // (a) Use Unavailable if the client can retry just the failing call.
+ // (b) Use Aborted if the client should retry at a higher-level
+ // (e.g., restarting a read-modify-write sequence).
+ // (c) Use FailedPrecondition if the client should not retry until
+ // the system state has been explicitly fixed. E.g., if an "rmdir"
+ // fails because the directory is non-empty, FailedPrecondition
+ // should be returned since the client should not retry unless
+ // they have first fixed up the directory by deleting files from it.
+ // (d) Use FailedPrecondition if the client performs conditional
+ // REST Get/Update/Delete on a resource and the resource on the
+ // server does not match the condition. E.g., conflicting
+ // read-modify-write on the same resource.
+ FailedPrecondition Code = 9
+
+ // Aborted indicates the operation was aborted, typically due to a
+ // concurrency issue like sequencer check failures, transaction aborts,
+ // etc.
+ //
+ // See litmus test above for deciding between FailedPrecondition,
+ // Aborted, and Unavailable.
+ Aborted Code = 10
+
+ // OutOfRange means operation was attempted past the valid range.
+ // E.g., seeking or reading past end of file.
+ //
+ // Unlike InvalidArgument, this error indicates a problem that may
+ // be fixed if the system state changes. For example, a 32-bit file
+ // system will generate InvalidArgument if asked to read at an
+ // offset that is not in the range [0,2^32-1], but it will generate
+ // OutOfRange if asked to read from an offset past the current
+ // file size.
+ //
+ // There is a fair bit of overlap between FailedPrecondition and
+ // OutOfRange. We recommend using OutOfRange (the more specific
+ // error) when it applies so that callers who are iterating through
+ // a space can easily look for an OutOfRange error to detect when
+ // they are done.
+ OutOfRange Code = 11
+
+ // Unimplemented indicates operation is not implemented or not
+ // supported/enabled in this service.
+ Unimplemented Code = 12
+
+ // Internal errors. Means some invariants expected by underlying
+ // system has been broken. If you see one of these errors,
+ // something is very broken.
+ Internal Code = 13
+
+ // Unavailable indicates the service is currently unavailable.
+ // This is a most likely a transient condition and may be corrected
+ // by retrying with a backoff.
+ //
+ // See litmus test above for deciding between FailedPrecondition,
+ // Aborted, and Unavailable.
+ Unavailable Code = 14
+
+ // DataLoss indicates unrecoverable data loss or corruption.
+ DataLoss Code = 15
+)
diff --git a/vendor/google.golang.org/grpc/credentials/credentials.go b/vendor/google.golang.org/grpc/credentials/credentials.go
new file mode 100644
index 0000000..a8114d6
--- /dev/null
+++ b/vendor/google.golang.org/grpc/credentials/credentials.go
@@ -0,0 +1,234 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+// Package credentials implements various credentials supported by gRPC library,
+// which encapsulate all the state needed by a client to authenticate with a
+// server and make various assertions, e.g., about the client's identity, role,
+// or whether it is authorized to make a particular call.
+package credentials // import "google.golang.org/grpc/credentials"
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "net"
+ "strings"
+
+ "golang.org/x/net/context"
+)
+
+var (
+ // alpnProtoStr are the specified application level protocols for gRPC.
+ alpnProtoStr = []string{"h2"}
+)
+
+// PerRPCCredentials defines the common interface for the credentials which need to
+// attach security information to every RPC (e.g., oauth2).
+type PerRPCCredentials interface {
+ // GetRequestMetadata gets the current request metadata, refreshing
+ // tokens if required. This should be called by the transport layer on
+ // each request, and the data should be populated in headers or other
+ // context. uri is the URI of the entry point for the request. When
+ // supported by the underlying implementation, ctx can be used for
+ // timeout and cancellation.
+ // TODO(zhaoq): Define the set of the qualified keys instead of leaving
+ // it as an arbitrary string.
+ GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
+ // RequireTransportSecurity indicates whether the credentials requires
+ // transport security.
+ RequireTransportSecurity() bool
+}
+
+// ProtocolInfo provides information regarding the gRPC wire protocol version,
+// security protocol, security protocol version in use, server name, etc.
+type ProtocolInfo struct {
+ // ProtocolVersion is the gRPC wire protocol version.
+ ProtocolVersion string
+ // SecurityProtocol is the security protocol in use.
+ SecurityProtocol string
+ // SecurityVersion is the security protocol version.
+ SecurityVersion string
+ // ServerName is the user-configured server name.
+ ServerName string
+}
+
+// AuthInfo defines the common interface for the auth information the users are interested in.
+type AuthInfo interface {
+ AuthType() string
+}
+
+var (
+ // ErrConnDispatched indicates that rawConn has been dispatched out of gRPC
+ // and the caller should not close rawConn.
+ ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC")
+)
+
+// TransportCredentials defines the common interface for all the live gRPC wire
+// protocols and supported transport security protocols (e.g., TLS, SSL).
+type TransportCredentials interface {
+ // ClientHandshake does the authentication handshake specified by the corresponding
+ // authentication protocol on rawConn for clients. It returns the authenticated
+ // connection and the corresponding auth information about the connection.
+ // Implementations must use the provided context to implement timely cancellation.
+ // gRPC will try to reconnect if the error returned is a temporary error
+ // (io.EOF, context.DeadlineExceeded or err.Temporary() == true).
+ // If the returned error is a wrapper error, implementations should make sure that
+ // the error implements Temporary() to have the correct retry behaviors.
+ ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error)
+ // ServerHandshake does the authentication handshake for servers. It returns
+ // the authenticated connection and the corresponding auth information about
+ // the connection.
+ ServerHandshake(net.Conn) (net.Conn, AuthInfo, error)
+ // Info provides the ProtocolInfo of this TransportCredentials.
+ Info() ProtocolInfo
+ // Clone makes a copy of this TransportCredentials.
+ Clone() TransportCredentials
+ // OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server.
+ // gRPC internals also use it to override the virtual hosting name if it is set.
+ // It must be called before dialing. Currently, this is only used by grpclb.
+ OverrideServerName(string) error
+}
+
+// TLSInfo contains the auth information for a TLS authenticated connection.
+// It implements the AuthInfo interface.
+type TLSInfo struct {
+ State tls.ConnectionState
+}
+
+// AuthType returns the type of TLSInfo as a string.
+func (t TLSInfo) AuthType() string {
+ return "tls"
+}
+
+// tlsCreds is the credentials required for authenticating a connection using TLS.
+type tlsCreds struct {
+ // TLS configuration
+ config *tls.Config
+}
+
+func (c tlsCreds) Info() ProtocolInfo {
+ return ProtocolInfo{
+ SecurityProtocol: "tls",
+ SecurityVersion: "1.2",
+ ServerName: c.config.ServerName,
+ }
+}
+
+func (c *tlsCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) {
+ // use local cfg to avoid clobbering ServerName if using multiple endpoints
+ cfg := cloneTLSConfig(c.config)
+ if cfg.ServerName == "" {
+ colonPos := strings.LastIndex(addr, ":")
+ if colonPos == -1 {
+ colonPos = len(addr)
+ }
+ cfg.ServerName = addr[:colonPos]
+ }
+ conn := tls.Client(rawConn, cfg)
+ errChannel := make(chan error, 1)
+ go func() {
+ errChannel <- conn.Handshake()
+ }()
+ select {
+ case err := <-errChannel:
+ if err != nil {
+ return nil, nil, err
+ }
+ case <-ctx.Done():
+ return nil, nil, ctx.Err()
+ }
+ return conn, TLSInfo{conn.ConnectionState()}, nil
+}
+
+func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {
+ conn := tls.Server(rawConn, c.config)
+ if err := conn.Handshake(); err != nil {
+ return nil, nil, err
+ }
+ return conn, TLSInfo{conn.ConnectionState()}, nil
+}
+
+func (c *tlsCreds) Clone() TransportCredentials {
+ return NewTLS(c.config)
+}
+
+func (c *tlsCreds) OverrideServerName(serverNameOverride string) error {
+ c.config.ServerName = serverNameOverride
+ return nil
+}
+
+// NewTLS uses c to construct a TransportCredentials based on TLS.
+func NewTLS(c *tls.Config) TransportCredentials {
+ tc := &tlsCreds{cloneTLSConfig(c)}
+ tc.config.NextProtos = alpnProtoStr
+ return tc
+}
+
+// NewClientTLSFromCert constructs a TLS from the input certificate for client.
+// serverNameOverride is for testing only. If set to a non empty string,
+// it will override the virtual host name of authority (e.g. :authority header field) in requests.
+func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {
+ return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})
+}
+
+// NewClientTLSFromFile constructs a TLS from the input certificate file for client.
+// serverNameOverride is for testing only. If set to a non empty string,
+// it will override the virtual host name of authority (e.g. :authority header field) in requests.
+func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) {
+ b, err := ioutil.ReadFile(certFile)
+ if err != nil {
+ return nil, err
+ }
+ cp := x509.NewCertPool()
+ if !cp.AppendCertsFromPEM(b) {
+ return nil, fmt.Errorf("credentials: failed to append certificates")
+ }
+ return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil
+}
+
+// NewServerTLSFromCert constructs a TLS from the input certificate for server.
+func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {
+ return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})
+}
+
+// NewServerTLSFromFile constructs a TLS from the input certificate file and key
+// file for server.
+func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {
+ cert, err := tls.LoadX509KeyPair(certFile, keyFile)
+ if err != nil {
+ return nil, err
+ }
+ return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil
+}
diff --git a/vendor/google.golang.org/grpc/credentials/credentials_util_go17.go b/vendor/google.golang.org/grpc/credentials/credentials_util_go17.go
new file mode 100644
index 0000000..7597b09
--- /dev/null
+++ b/vendor/google.golang.org/grpc/credentials/credentials_util_go17.go
@@ -0,0 +1,75 @@
+// +build go1.7
+// +build !go1.8
+
+/*
+ *
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+package credentials
+
+import (
+ "crypto/tls"
+)
+
+// cloneTLSConfig returns a shallow clone of the exported
+// fields of cfg, ignoring the unexported sync.Once, which
+// contains a mutex and must not be copied.
+//
+// If cfg is nil, a new zero tls.Config is returned.
+func cloneTLSConfig(cfg *tls.Config) *tls.Config {
+ if cfg == nil {
+ return &tls.Config{}
+ }
+ return &tls.Config{
+ Rand: cfg.Rand,
+ Time: cfg.Time,
+ Certificates: cfg.Certificates,
+ NameToCertificate: cfg.NameToCertificate,
+ GetCertificate: cfg.GetCertificate,
+ RootCAs: cfg.RootCAs,
+ NextProtos: cfg.NextProtos,
+ ServerName: cfg.ServerName,
+ ClientAuth: cfg.ClientAuth,
+ ClientCAs: cfg.ClientCAs,
+ InsecureSkipVerify: cfg.InsecureSkipVerify,
+ CipherSuites: cfg.CipherSuites,
+ PreferServerCipherSuites: cfg.PreferServerCipherSuites,
+ SessionTicketsDisabled: cfg.SessionTicketsDisabled,
+ SessionTicketKey: cfg.SessionTicketKey,
+ ClientSessionCache: cfg.ClientSessionCache,
+ MinVersion: cfg.MinVersion,
+ MaxVersion: cfg.MaxVersion,
+ CurvePreferences: cfg.CurvePreferences,
+ DynamicRecordSizingDisabled: cfg.DynamicRecordSizingDisabled,
+ Renegotiation: cfg.Renegotiation,
+ }
+}
diff --git a/vendor/google.golang.org/grpc/credentials/credentials_util_go18.go b/vendor/google.golang.org/grpc/credentials/credentials_util_go18.go
new file mode 100644
index 0000000..0ecf342
--- /dev/null
+++ b/vendor/google.golang.org/grpc/credentials/credentials_util_go18.go
@@ -0,0 +1,53 @@
+// +build go1.8
+
+/*
+ *
+ * Copyright 2017, Google Inc.
+ * 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.
+ *
+ */
+
+package credentials
+
+import (
+ "crypto/tls"
+)
+
+// cloneTLSConfig returns a shallow clone of the exported
+// fields of cfg, ignoring the unexported sync.Once, which
+// contains a mutex and must not be copied.
+//
+// If cfg is nil, a new zero tls.Config is returned.
+func cloneTLSConfig(cfg *tls.Config) *tls.Config {
+ if cfg == nil {
+ return &tls.Config{}
+ }
+
+ return cfg.Clone()
+}
diff --git a/vendor/google.golang.org/grpc/credentials/credentials_util_pre_go17.go b/vendor/google.golang.org/grpc/credentials/credentials_util_pre_go17.go
new file mode 100644
index 0000000..cfd40df
--- /dev/null
+++ b/vendor/google.golang.org/grpc/credentials/credentials_util_pre_go17.go
@@ -0,0 +1,72 @@
+// +build !go1.7
+
+/*
+ *
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+package credentials
+
+import (
+ "crypto/tls"
+)
+
+// cloneTLSConfig returns a shallow clone of the exported
+// fields of cfg, ignoring the unexported sync.Once, which
+// contains a mutex and must not be copied.
+//
+// If cfg is nil, a new zero tls.Config is returned.
+func cloneTLSConfig(cfg *tls.Config) *tls.Config {
+ if cfg == nil {
+ return &tls.Config{}
+ }
+ return &tls.Config{
+ Rand: cfg.Rand,
+ Time: cfg.Time,
+ Certificates: cfg.Certificates,
+ NameToCertificate: cfg.NameToCertificate,
+ GetCertificate: cfg.GetCertificate,
+ RootCAs: cfg.RootCAs,
+ NextProtos: cfg.NextProtos,
+ ServerName: cfg.ServerName,
+ ClientAuth: cfg.ClientAuth,
+ ClientCAs: cfg.ClientCAs,
+ InsecureSkipVerify: cfg.InsecureSkipVerify,
+ CipherSuites: cfg.CipherSuites,
+ PreferServerCipherSuites: cfg.PreferServerCipherSuites,
+ SessionTicketsDisabled: cfg.SessionTicketsDisabled,
+ SessionTicketKey: cfg.SessionTicketKey,
+ ClientSessionCache: cfg.ClientSessionCache,
+ MinVersion: cfg.MinVersion,
+ MaxVersion: cfg.MaxVersion,
+ CurvePreferences: cfg.CurvePreferences,
+ }
+}
diff --git a/vendor/google.golang.org/grpc/credentials/oauth/oauth.go b/vendor/google.golang.org/grpc/credentials/oauth/oauth.go
new file mode 100644
index 0000000..25393cc
--- /dev/null
+++ b/vendor/google.golang.org/grpc/credentials/oauth/oauth.go
@@ -0,0 +1,180 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * 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.
+ *
+ */
+
+// Package oauth implements gRPC credentials using OAuth.
+package oauth
+
+import (
+ "fmt"
+ "io/ioutil"
+
+ "golang.org/x/net/context"
+ "golang.org/x/oauth2"
+ "golang.org/x/oauth2/google"
+ "golang.org/x/oauth2/jwt"
+ "google.golang.org/grpc/credentials"
+)
+
+// TokenSource supplies PerRPCCredentials from an oauth2.TokenSource.
+type TokenSource struct {
+ oauth2.TokenSource
+}
+
+// GetRequestMetadata gets the request metadata as a map from a TokenSource.
+func (ts TokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
+ token, err := ts.Token()
+ if err != nil {
+ return nil, err
+ }
+ return map[string]string{
+ "authorization": token.Type() + " " + token.AccessToken,
+ }, nil
+}
+
+// RequireTransportSecurity indicates whether the credentials requires transport security.
+func (ts TokenSource) RequireTransportSecurity() bool {
+ return true
+}
+
+type jwtAccess struct {
+ jsonKey []byte
+}
+
+// NewJWTAccessFromFile creates PerRPCCredentials from the given keyFile.
+func NewJWTAccessFromFile(keyFile string) (credentials.PerRPCCredentials, error) {
+ jsonKey, err := ioutil.ReadFile(keyFile)
+ if err != nil {
+ return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err)
+ }
+ return NewJWTAccessFromKey(jsonKey)
+}
+
+// NewJWTAccessFromKey creates PerRPCCredentials from the given jsonKey.
+func NewJWTAccessFromKey(jsonKey []byte) (credentials.PerRPCCredentials, error) {
+ return jwtAccess{jsonKey}, nil
+}
+
+func (j jwtAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
+ ts, err := google.JWTAccessTokenSourceFromJSON(j.jsonKey, uri[0])
+ if err != nil {
+ return nil, err
+ }
+ token, err := ts.Token()
+ if err != nil {
+ return nil, err
+ }
+ return map[string]string{
+ "authorization": token.TokenType + " " + token.AccessToken,
+ }, nil
+}
+
+func (j jwtAccess) RequireTransportSecurity() bool {
+ return true
+}
+
+// oauthAccess supplies PerRPCCredentials from a given token.
+type oauthAccess struct {
+ token oauth2.Token
+}
+
+// NewOauthAccess constructs the PerRPCCredentials using a given token.
+func NewOauthAccess(token *oauth2.Token) credentials.PerRPCCredentials {
+ return oauthAccess{token: *token}
+}
+
+func (oa oauthAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
+ return map[string]string{
+ "authorization": oa.token.TokenType + " " + oa.token.AccessToken,
+ }, nil
+}
+
+func (oa oauthAccess) RequireTransportSecurity() bool {
+ return true
+}
+
+// NewComputeEngine constructs the PerRPCCredentials that fetches access tokens from
+// Google Compute Engine (GCE)'s metadata server. It is only valid to use this
+// if your program is running on a GCE instance.
+// TODO(dsymonds): Deprecate and remove this.
+func NewComputeEngine() credentials.PerRPCCredentials {
+ return TokenSource{google.ComputeTokenSource("")}
+}
+
+// serviceAccount represents PerRPCCredentials via JWT signing key.
+type serviceAccount struct {
+ config *jwt.Config
+}
+
+func (s serviceAccount) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
+ token, err := s.config.TokenSource(ctx).Token()
+ if err != nil {
+ return nil, err
+ }
+ return map[string]string{
+ "authorization": token.TokenType + " " + token.AccessToken,
+ }, nil
+}
+
+func (s serviceAccount) RequireTransportSecurity() bool {
+ return true
+}
+
+// NewServiceAccountFromKey constructs the PerRPCCredentials using the JSON key slice
+// from a Google Developers service account.
+func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerRPCCredentials, error) {
+ config, err := google.JWTConfigFromJSON(jsonKey, scope...)
+ if err != nil {
+ return nil, err
+ }
+ return serviceAccount{config: config}, nil
+}
+
+// NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file
+// of a Google Developers service account.
+func NewServiceAccountFromFile(keyFile string, scope ...string) (credentials.PerRPCCredentials, error) {
+ jsonKey, err := ioutil.ReadFile(keyFile)
+ if err != nil {
+ return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err)
+ }
+ return NewServiceAccountFromKey(jsonKey, scope...)
+}
+
+// NewApplicationDefault returns "Application Default Credentials". For more
+// detail, see https://developers.google.com/accounts/docs/application-default-credentials.
+func NewApplicationDefault(ctx context.Context, scope ...string) (credentials.PerRPCCredentials, error) {
+ t, err := google.DefaultTokenSource(ctx, scope...)
+ if err != nil {
+ return nil, err
+ }
+ return TokenSource{t}, nil
+}
diff --git a/vendor/google.golang.org/grpc/doc.go b/vendor/google.golang.org/grpc/doc.go
new file mode 100644
index 0000000..a35f218
--- /dev/null
+++ b/vendor/google.golang.org/grpc/doc.go
@@ -0,0 +1,6 @@
+/*
+Package grpc implements an RPC system called gRPC.
+
+See www.grpc.io for more information about gRPC.
+*/
+package grpc // import "google.golang.org/grpc"
diff --git a/vendor/google.golang.org/grpc/go16.go b/vendor/google.golang.org/grpc/go16.go
new file mode 100644
index 0000000..b61c57e
--- /dev/null
+++ b/vendor/google.golang.org/grpc/go16.go
@@ -0,0 +1,56 @@
+// +build go1.6,!go1.7
+
+/*
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "fmt"
+ "net"
+ "net/http"
+
+ "golang.org/x/net/context"
+)
+
+// dialContext connects to the address on the named network.
+func dialContext(ctx context.Context, network, address string) (net.Conn, error) {
+ return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address)
+}
+
+func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error {
+ req.Cancel = ctx.Done()
+ if err := req.Write(conn); err != nil {
+ return fmt.Errorf("failed to write the HTTP request: %v", err)
+ }
+ return nil
+}
diff --git a/vendor/google.golang.org/grpc/go17.go b/vendor/google.golang.org/grpc/go17.go
new file mode 100644
index 0000000..844f0e1
--- /dev/null
+++ b/vendor/google.golang.org/grpc/go17.go
@@ -0,0 +1,55 @@
+// +build go1.7
+
+/*
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "net"
+ "net/http"
+
+ "golang.org/x/net/context"
+)
+
+// dialContext connects to the address on the named network.
+func dialContext(ctx context.Context, network, address string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, address)
+}
+
+func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error {
+ req = req.WithContext(ctx)
+ if err := req.Write(conn); err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/vendor/google.golang.org/grpc/grpclb.go b/vendor/google.golang.org/grpc/grpclb.go
new file mode 100644
index 0000000..524e429
--- /dev/null
+++ b/vendor/google.golang.org/grpc/grpclb.go
@@ -0,0 +1,749 @@
+/*
+ *
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "errors"
+ "fmt"
+ "math/rand"
+ "net"
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+ "google.golang.org/grpc/codes"
+ lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1"
+ "google.golang.org/grpc/grpclog"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/naming"
+)
+
+// Client API for LoadBalancer service.
+// Mostly copied from generated pb.go file.
+// To avoid circular dependency.
+type loadBalancerClient struct {
+ cc *ClientConn
+}
+
+func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...CallOption) (*balanceLoadClientStream, error) {
+ desc := &StreamDesc{
+ StreamName: "BalanceLoad",
+ ServerStreams: true,
+ ClientStreams: true,
+ }
+ stream, err := NewClientStream(ctx, desc, c.cc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &balanceLoadClientStream{stream}
+ return x, nil
+}
+
+type balanceLoadClientStream struct {
+ ClientStream
+}
+
+func (x *balanceLoadClientStream) Send(m *lbpb.LoadBalanceRequest) error {
+ return x.ClientStream.SendMsg(m)
+}
+
+func (x *balanceLoadClientStream) Recv() (*lbpb.LoadBalanceResponse, error) {
+ m := new(lbpb.LoadBalanceResponse)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// AddressType indicates the address type returned by name resolution.
+type AddressType uint8
+
+const (
+ // Backend indicates the server is a backend server.
+ Backend AddressType = iota
+ // GRPCLB indicates the server is a grpclb load balancer.
+ GRPCLB
+)
+
+// AddrMetadataGRPCLB contains the information the name resolution for grpclb should provide. The
+// name resolver used by grpclb balancer is required to provide this type of metadata in
+// its address updates.
+type AddrMetadataGRPCLB struct {
+ // AddrType is the type of server (grpc load balancer or backend).
+ AddrType AddressType
+ // ServerName is the name of the grpc load balancer. Used for authentication.
+ ServerName string
+}
+
+// NewGRPCLBBalancer creates a grpclb load balancer.
+func NewGRPCLBBalancer(r naming.Resolver) Balancer {
+ return &balancer{
+ r: r,
+ }
+}
+
+type remoteBalancerInfo struct {
+ addr string
+ // the server name used for authentication with the remote LB server.
+ name string
+}
+
+// grpclbAddrInfo consists of the information of a backend server.
+type grpclbAddrInfo struct {
+ addr Address
+ connected bool
+ // dropForRateLimiting indicates whether this particular request should be
+ // dropped by the client for rate limiting.
+ dropForRateLimiting bool
+ // dropForLoadBalancing indicates whether this particular request should be
+ // dropped by the client for load balancing.
+ dropForLoadBalancing bool
+}
+
+type balancer struct {
+ r naming.Resolver
+ target string
+ mu sync.Mutex
+ seq int // a sequence number to make sure addrCh does not get stale addresses.
+ w naming.Watcher
+ addrCh chan []Address
+ rbs []remoteBalancerInfo
+ addrs []*grpclbAddrInfo
+ next int
+ waitCh chan struct{}
+ done bool
+ expTimer *time.Timer
+ rand *rand.Rand
+
+ clientStats lbpb.ClientStats
+}
+
+func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerInfo) error {
+ updates, err := w.Next()
+ if err != nil {
+ return err
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.done {
+ return ErrClientConnClosing
+ }
+ for _, update := range updates {
+ switch update.Op {
+ case naming.Add:
+ var exist bool
+ for _, v := range b.rbs {
+ // TODO: Is the same addr with different server name a different balancer?
+ if update.Addr == v.addr {
+ exist = true
+ break
+ }
+ }
+ if exist {
+ continue
+ }
+ md, ok := update.Metadata.(*AddrMetadataGRPCLB)
+ if !ok {
+ // TODO: Revisit the handling here and may introduce some fallback mechanism.
+ grpclog.Printf("The name resolution contains unexpected metadata %v", update.Metadata)
+ continue
+ }
+ switch md.AddrType {
+ case Backend:
+ // TODO: Revisit the handling here and may introduce some fallback mechanism.
+ grpclog.Printf("The name resolution does not give grpclb addresses")
+ continue
+ case GRPCLB:
+ b.rbs = append(b.rbs, remoteBalancerInfo{
+ addr: update.Addr,
+ name: md.ServerName,
+ })
+ default:
+ grpclog.Printf("Received unknow address type %d", md.AddrType)
+ continue
+ }
+ case naming.Delete:
+ for i, v := range b.rbs {
+ if update.Addr == v.addr {
+ copy(b.rbs[i:], b.rbs[i+1:])
+ b.rbs = b.rbs[:len(b.rbs)-1]
+ break
+ }
+ }
+ default:
+ grpclog.Println("Unknown update.Op ", update.Op)
+ }
+ }
+ // TODO: Fall back to the basic round-robin load balancing if the resulting address is
+ // not a load balancer.
+ select {
+ case <-ch:
+ default:
+ }
+ ch <- b.rbs
+ return nil
+}
+
+func (b *balancer) serverListExpire(seq int) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ // TODO: gRPC interanls do not clear the connections when the server list is stale.
+ // This means RPCs will keep using the existing server list until b receives new
+ // server list even though the list is expired. Revisit this behavior later.
+ if b.done || seq < b.seq {
+ return
+ }
+ b.next = 0
+ b.addrs = nil
+ // Ask grpc internals to close all the corresponding connections.
+ b.addrCh <- nil
+}
+
+func convertDuration(d *lbpb.Duration) time.Duration {
+ if d == nil {
+ return 0
+ }
+ return time.Duration(d.Seconds)*time.Second + time.Duration(d.Nanos)*time.Nanosecond
+}
+
+func (b *balancer) processServerList(l *lbpb.ServerList, seq int) {
+ if l == nil {
+ return
+ }
+ servers := l.GetServers()
+ expiration := convertDuration(l.GetExpirationInterval())
+ var (
+ sl []*grpclbAddrInfo
+ addrs []Address
+ )
+ for _, s := range servers {
+ md := metadata.Pairs("lb-token", s.LoadBalanceToken)
+ addr := Address{
+ Addr: fmt.Sprintf("%s:%d", net.IP(s.IpAddress), s.Port),
+ Metadata: &md,
+ }
+ sl = append(sl, &grpclbAddrInfo{
+ addr: addr,
+ dropForRateLimiting: s.DropForRateLimiting,
+ dropForLoadBalancing: s.DropForLoadBalancing,
+ })
+ addrs = append(addrs, addr)
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.done || seq < b.seq {
+ return
+ }
+ if len(sl) > 0 {
+ // reset b.next to 0 when replacing the server list.
+ b.next = 0
+ b.addrs = sl
+ b.addrCh <- addrs
+ if b.expTimer != nil {
+ b.expTimer.Stop()
+ b.expTimer = nil
+ }
+ if expiration > 0 {
+ b.expTimer = time.AfterFunc(expiration, func() {
+ b.serverListExpire(seq)
+ })
+ }
+ }
+ return
+}
+
+func (b *balancer) sendLoadReport(s *balanceLoadClientStream, interval time.Duration, done <-chan struct{}) {
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ case <-done:
+ return
+ }
+ b.mu.Lock()
+ stats := b.clientStats
+ b.clientStats = lbpb.ClientStats{} // Clear the stats.
+ b.mu.Unlock()
+ t := time.Now()
+ stats.Timestamp = &lbpb.Timestamp{
+ Seconds: t.Unix(),
+ Nanos: int32(t.Nanosecond()),
+ }
+ if err := s.Send(&lbpb.LoadBalanceRequest{
+ LoadBalanceRequestType: &lbpb.LoadBalanceRequest_ClientStats{
+ ClientStats: &stats,
+ },
+ }); err != nil {
+ return
+ }
+ }
+}
+
+func (b *balancer) callRemoteBalancer(lbc *loadBalancerClient, seq int) (retry bool) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ stream, err := lbc.BalanceLoad(ctx)
+ if err != nil {
+ grpclog.Printf("Failed to perform RPC to the remote balancer %v", err)
+ return
+ }
+ b.mu.Lock()
+ if b.done {
+ b.mu.Unlock()
+ return
+ }
+ b.mu.Unlock()
+ initReq := &lbpb.LoadBalanceRequest{
+ LoadBalanceRequestType: &lbpb.LoadBalanceRequest_InitialRequest{
+ InitialRequest: &lbpb.InitialLoadBalanceRequest{
+ Name: b.target,
+ },
+ },
+ }
+ if err := stream.Send(initReq); err != nil {
+ // TODO: backoff on retry?
+ return true
+ }
+ reply, err := stream.Recv()
+ if err != nil {
+ // TODO: backoff on retry?
+ return true
+ }
+ initResp := reply.GetInitialResponse()
+ if initResp == nil {
+ grpclog.Println("Failed to receive the initial response from the remote balancer.")
+ return
+ }
+ // TODO: Support delegation.
+ if initResp.LoadBalancerDelegate != "" {
+ // delegation
+ grpclog.Println("TODO: Delegation is not supported yet.")
+ return
+ }
+ streamDone := make(chan struct{})
+ defer close(streamDone)
+ b.mu.Lock()
+ b.clientStats = lbpb.ClientStats{} // Clear client stats.
+ b.mu.Unlock()
+ if d := convertDuration(initResp.ClientStatsReportInterval); d > 0 {
+ go b.sendLoadReport(stream, d, streamDone)
+ }
+ // Retrieve the server list.
+ for {
+ reply, err := stream.Recv()
+ if err != nil {
+ break
+ }
+ b.mu.Lock()
+ if b.done || seq < b.seq {
+ b.mu.Unlock()
+ return
+ }
+ b.seq++ // tick when receiving a new list of servers.
+ seq = b.seq
+ b.mu.Unlock()
+ if serverList := reply.GetServerList(); serverList != nil {
+ b.processServerList(serverList, seq)
+ }
+ }
+ return true
+}
+
+func (b *balancer) Start(target string, config BalancerConfig) error {
+ b.rand = rand.New(rand.NewSource(time.Now().Unix()))
+ // TODO: Fall back to the basic direct connection if there is no name resolver.
+ if b.r == nil {
+ return errors.New("there is no name resolver installed")
+ }
+ b.target = target
+ b.mu.Lock()
+ if b.done {
+ b.mu.Unlock()
+ return ErrClientConnClosing
+ }
+ b.addrCh = make(chan []Address)
+ w, err := b.r.Resolve(target)
+ if err != nil {
+ b.mu.Unlock()
+ return err
+ }
+ b.w = w
+ b.mu.Unlock()
+ balancerAddrsCh := make(chan []remoteBalancerInfo, 1)
+ // Spawn a goroutine to monitor the name resolution of remote load balancer.
+ go func() {
+ for {
+ if err := b.watchAddrUpdates(w, balancerAddrsCh); err != nil {
+ grpclog.Printf("grpc: the naming watcher stops working due to %v.\n", err)
+ close(balancerAddrsCh)
+ return
+ }
+ }
+ }()
+ // Spawn a goroutine to talk to the remote load balancer.
+ go func() {
+ var (
+ cc *ClientConn
+ // ccError is closed when there is an error in the current cc.
+ // A new rb should be picked from rbs and connected.
+ ccError chan struct{}
+ rb *remoteBalancerInfo
+ rbs []remoteBalancerInfo
+ rbIdx int
+ )
+
+ defer func() {
+ if ccError != nil {
+ select {
+ case <-ccError:
+ default:
+ close(ccError)
+ }
+ }
+ if cc != nil {
+ cc.Close()
+ }
+ }()
+
+ for {
+ var ok bool
+ select {
+ case rbs, ok = <-balancerAddrsCh:
+ if !ok {
+ return
+ }
+ foundIdx := -1
+ if rb != nil {
+ for i, trb := range rbs {
+ if trb == *rb {
+ foundIdx = i
+ break
+ }
+ }
+ }
+ if foundIdx >= 0 {
+ if foundIdx >= 1 {
+ // Move the address in use to the beginning of the list.
+ b.rbs[0], b.rbs[foundIdx] = b.rbs[foundIdx], b.rbs[0]
+ rbIdx = 0
+ }
+ continue // If found, don't dial new cc.
+ } else if len(rbs) > 0 {
+ // Pick a random one from the list, instead of always using the first one.
+ if l := len(rbs); l > 1 && rb != nil {
+ tmpIdx := b.rand.Intn(l - 1)
+ b.rbs[0], b.rbs[tmpIdx] = b.rbs[tmpIdx], b.rbs[0]
+ }
+ rbIdx = 0
+ rb = &rbs[0]
+ } else {
+ // foundIdx < 0 && len(rbs) <= 0.
+ rb = nil
+ }
+ case <-ccError:
+ ccError = nil
+ if rbIdx < len(rbs)-1 {
+ rbIdx++
+ rb = &rbs[rbIdx]
+ } else {
+ rb = nil
+ }
+ }
+
+ if rb == nil {
+ continue
+ }
+
+ if cc != nil {
+ cc.Close()
+ }
+ // Talk to the remote load balancer to get the server list.
+ var err error
+ creds := config.DialCreds
+ ccError = make(chan struct{})
+ if creds == nil {
+ cc, err = Dial(rb.addr, WithInsecure())
+ } else {
+ if rb.name != "" {
+ if err := creds.OverrideServerName(rb.name); err != nil {
+ grpclog.Printf("Failed to override the server name in the credentials: %v", err)
+ continue
+ }
+ }
+ cc, err = Dial(rb.addr, WithTransportCredentials(creds))
+ }
+ if err != nil {
+ grpclog.Printf("Failed to setup a connection to the remote balancer %v: %v", rb.addr, err)
+ close(ccError)
+ continue
+ }
+ b.mu.Lock()
+ b.seq++ // tick when getting a new balancer address
+ seq := b.seq
+ b.next = 0
+ b.mu.Unlock()
+ go func(cc *ClientConn, ccError chan struct{}) {
+ lbc := &loadBalancerClient{cc}
+ b.callRemoteBalancer(lbc, seq)
+ cc.Close()
+ select {
+ case <-ccError:
+ default:
+ close(ccError)
+ }
+ }(cc, ccError)
+ }
+ }()
+ return nil
+}
+
+func (b *balancer) down(addr Address, err error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ for _, a := range b.addrs {
+ if addr == a.addr {
+ a.connected = false
+ break
+ }
+ }
+}
+
+func (b *balancer) Up(addr Address) func(error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.done {
+ return nil
+ }
+ var cnt int
+ for _, a := range b.addrs {
+ if a.addr == addr {
+ if a.connected {
+ return nil
+ }
+ a.connected = true
+ }
+ if a.connected && !a.dropForRateLimiting && !a.dropForLoadBalancing {
+ cnt++
+ }
+ }
+ // addr is the only one which is connected. Notify the Get() callers who are blocking.
+ if cnt == 1 && b.waitCh != nil {
+ close(b.waitCh)
+ b.waitCh = nil
+ }
+ return func(err error) {
+ b.down(addr, err)
+ }
+}
+
+func (b *balancer) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) {
+ var ch chan struct{}
+ b.mu.Lock()
+ if b.done {
+ b.mu.Unlock()
+ err = ErrClientConnClosing
+ return
+ }
+ seq := b.seq
+
+ defer func() {
+ if err != nil {
+ return
+ }
+ put = func() {
+ s, ok := rpcInfoFromContext(ctx)
+ if !ok {
+ return
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.done || seq < b.seq {
+ return
+ }
+ b.clientStats.NumCallsFinished++
+ if !s.bytesSent {
+ b.clientStats.NumCallsFinishedWithClientFailedToSend++
+ } else if s.bytesReceived {
+ b.clientStats.NumCallsFinishedKnownReceived++
+ }
+ }
+ }()
+
+ b.clientStats.NumCallsStarted++
+ if len(b.addrs) > 0 {
+ if b.next >= len(b.addrs) {
+ b.next = 0
+ }
+ next := b.next
+ for {
+ a := b.addrs[next]
+ next = (next + 1) % len(b.addrs)
+ if a.connected {
+ if !a.dropForRateLimiting && !a.dropForLoadBalancing {
+ addr = a.addr
+ b.next = next
+ b.mu.Unlock()
+ return
+ }
+ if !opts.BlockingWait {
+ b.next = next
+ if a.dropForLoadBalancing {
+ b.clientStats.NumCallsFinished++
+ b.clientStats.NumCallsFinishedWithDropForLoadBalancing++
+ } else if a.dropForRateLimiting {
+ b.clientStats.NumCallsFinished++
+ b.clientStats.NumCallsFinishedWithDropForRateLimiting++
+ }
+ b.mu.Unlock()
+ err = Errorf(codes.Unavailable, "%s drops requests", a.addr.Addr)
+ return
+ }
+ }
+ if next == b.next {
+ // Has iterated all the possible address but none is connected.
+ break
+ }
+ }
+ }
+ if !opts.BlockingWait {
+ if len(b.addrs) == 0 {
+ b.clientStats.NumCallsFinished++
+ b.clientStats.NumCallsFinishedWithClientFailedToSend++
+ b.mu.Unlock()
+ err = Errorf(codes.Unavailable, "there is no address available")
+ return
+ }
+ // Returns the next addr on b.addrs for a failfast RPC.
+ addr = b.addrs[b.next].addr
+ b.next++
+ b.mu.Unlock()
+ return
+ }
+ // Wait on b.waitCh for non-failfast RPCs.
+ if b.waitCh == nil {
+ ch = make(chan struct{})
+ b.waitCh = ch
+ } else {
+ ch = b.waitCh
+ }
+ b.mu.Unlock()
+ for {
+ select {
+ case <-ctx.Done():
+ b.mu.Lock()
+ b.clientStats.NumCallsFinished++
+ b.clientStats.NumCallsFinishedWithClientFailedToSend++
+ b.mu.Unlock()
+ err = ctx.Err()
+ return
+ case <-ch:
+ b.mu.Lock()
+ if b.done {
+ b.clientStats.NumCallsFinished++
+ b.clientStats.NumCallsFinishedWithClientFailedToSend++
+ b.mu.Unlock()
+ err = ErrClientConnClosing
+ return
+ }
+
+ if len(b.addrs) > 0 {
+ if b.next >= len(b.addrs) {
+ b.next = 0
+ }
+ next := b.next
+ for {
+ a := b.addrs[next]
+ next = (next + 1) % len(b.addrs)
+ if a.connected {
+ if !a.dropForRateLimiting && !a.dropForLoadBalancing {
+ addr = a.addr
+ b.next = next
+ b.mu.Unlock()
+ return
+ }
+ if !opts.BlockingWait {
+ b.next = next
+ if a.dropForLoadBalancing {
+ b.clientStats.NumCallsFinished++
+ b.clientStats.NumCallsFinishedWithDropForLoadBalancing++
+ } else if a.dropForRateLimiting {
+ b.clientStats.NumCallsFinished++
+ b.clientStats.NumCallsFinishedWithDropForRateLimiting++
+ }
+ b.mu.Unlock()
+ err = Errorf(codes.Unavailable, "drop requests for the addreess %s", a.addr.Addr)
+ return
+ }
+ }
+ if next == b.next {
+ // Has iterated all the possible address but none is connected.
+ break
+ }
+ }
+ }
+ // The newly added addr got removed by Down() again.
+ if b.waitCh == nil {
+ ch = make(chan struct{})
+ b.waitCh = ch
+ } else {
+ ch = b.waitCh
+ }
+ b.mu.Unlock()
+ }
+ }
+}
+
+func (b *balancer) Notify() <-chan []Address {
+ return b.addrCh
+}
+
+func (b *balancer) Close() error {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ b.done = true
+ if b.expTimer != nil {
+ b.expTimer.Stop()
+ }
+ if b.waitCh != nil {
+ close(b.waitCh)
+ }
+ if b.addrCh != nil {
+ close(b.addrCh)
+ }
+ if b.w != nil {
+ b.w.Close()
+ }
+ return nil
+}
diff --git a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/grpclb.pb.go b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/grpclb.pb.go
new file mode 100644
index 0000000..f63941b
--- /dev/null
+++ b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/grpclb.pb.go
@@ -0,0 +1,629 @@
+// Code generated by protoc-gen-go.
+// source: grpclb.proto
+// DO NOT EDIT!
+
+/*
+Package grpc_lb_v1 is a generated protocol buffer package.
+
+It is generated from these files:
+ grpclb.proto
+
+It has these top-level messages:
+ Duration
+ Timestamp
+ LoadBalanceRequest
+ InitialLoadBalanceRequest
+ ClientStats
+ LoadBalanceResponse
+ InitialLoadBalanceResponse
+ ServerList
+ Server
+*/
+package grpc_lb_v1
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+type Duration struct {
+ // Signed seconds of the span of time. Must be from -315,576,000,000
+ // to +315,576,000,000 inclusive.
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"`
+ // Signed fractions of a second at nanosecond resolution of the span
+ // of time. Durations less than one second are represented with a 0
+ // `seconds` field and a positive or negative `nanos` field. For durations
+ // of one second or more, a non-zero value for the `nanos` field must be
+ // of the same sign as the `seconds` field. Must be from -999,999,999
+ // to +999,999,999 inclusive.
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"`
+}
+
+func (m *Duration) Reset() { *m = Duration{} }
+func (m *Duration) String() string { return proto.CompactTextString(m) }
+func (*Duration) ProtoMessage() {}
+func (*Duration) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *Duration) GetSeconds() int64 {
+ if m != nil {
+ return m.Seconds
+ }
+ return 0
+}
+
+func (m *Duration) GetNanos() int32 {
+ if m != nil {
+ return m.Nanos
+ }
+ return 0
+}
+
+type Timestamp struct {
+ // Represents seconds of UTC time since Unix epoch
+ // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ // 9999-12-31T23:59:59Z inclusive.
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"`
+ // Non-negative fractions of a second at nanosecond resolution. Negative
+ // second values with fractions must still have non-negative nanos values
+ // that count forward in time. Must be from 0 to 999,999,999
+ // inclusive.
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"`
+}
+
+func (m *Timestamp) Reset() { *m = Timestamp{} }
+func (m *Timestamp) String() string { return proto.CompactTextString(m) }
+func (*Timestamp) ProtoMessage() {}
+func (*Timestamp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *Timestamp) GetSeconds() int64 {
+ if m != nil {
+ return m.Seconds
+ }
+ return 0
+}
+
+func (m *Timestamp) GetNanos() int32 {
+ if m != nil {
+ return m.Nanos
+ }
+ return 0
+}
+
+type LoadBalanceRequest struct {
+ // Types that are valid to be assigned to LoadBalanceRequestType:
+ // *LoadBalanceRequest_InitialRequest
+ // *LoadBalanceRequest_ClientStats
+ LoadBalanceRequestType isLoadBalanceRequest_LoadBalanceRequestType `protobuf_oneof:"load_balance_request_type"`
+}
+
+func (m *LoadBalanceRequest) Reset() { *m = LoadBalanceRequest{} }
+func (m *LoadBalanceRequest) String() string { return proto.CompactTextString(m) }
+func (*LoadBalanceRequest) ProtoMessage() {}
+func (*LoadBalanceRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+
+type isLoadBalanceRequest_LoadBalanceRequestType interface {
+ isLoadBalanceRequest_LoadBalanceRequestType()
+}
+
+type LoadBalanceRequest_InitialRequest struct {
+ InitialRequest *InitialLoadBalanceRequest `protobuf:"bytes,1,opt,name=initial_request,json=initialRequest,oneof"`
+}
+type LoadBalanceRequest_ClientStats struct {
+ ClientStats *ClientStats `protobuf:"bytes,2,opt,name=client_stats,json=clientStats,oneof"`
+}
+
+func (*LoadBalanceRequest_InitialRequest) isLoadBalanceRequest_LoadBalanceRequestType() {}
+func (*LoadBalanceRequest_ClientStats) isLoadBalanceRequest_LoadBalanceRequestType() {}
+
+func (m *LoadBalanceRequest) GetLoadBalanceRequestType() isLoadBalanceRequest_LoadBalanceRequestType {
+ if m != nil {
+ return m.LoadBalanceRequestType
+ }
+ return nil
+}
+
+func (m *LoadBalanceRequest) GetInitialRequest() *InitialLoadBalanceRequest {
+ if x, ok := m.GetLoadBalanceRequestType().(*LoadBalanceRequest_InitialRequest); ok {
+ return x.InitialRequest
+ }
+ return nil
+}
+
+func (m *LoadBalanceRequest) GetClientStats() *ClientStats {
+ if x, ok := m.GetLoadBalanceRequestType().(*LoadBalanceRequest_ClientStats); ok {
+ return x.ClientStats
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*LoadBalanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _LoadBalanceRequest_OneofMarshaler, _LoadBalanceRequest_OneofUnmarshaler, _LoadBalanceRequest_OneofSizer, []interface{}{
+ (*LoadBalanceRequest_InitialRequest)(nil),
+ (*LoadBalanceRequest_ClientStats)(nil),
+ }
+}
+
+func _LoadBalanceRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*LoadBalanceRequest)
+ // load_balance_request_type
+ switch x := m.LoadBalanceRequestType.(type) {
+ case *LoadBalanceRequest_InitialRequest:
+ b.EncodeVarint(1<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.InitialRequest); err != nil {
+ return err
+ }
+ case *LoadBalanceRequest_ClientStats:
+ b.EncodeVarint(2<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.ClientStats); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("LoadBalanceRequest.LoadBalanceRequestType has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _LoadBalanceRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*LoadBalanceRequest)
+ switch tag {
+ case 1: // load_balance_request_type.initial_request
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(InitialLoadBalanceRequest)
+ err := b.DecodeMessage(msg)
+ m.LoadBalanceRequestType = &LoadBalanceRequest_InitialRequest{msg}
+ return true, err
+ case 2: // load_balance_request_type.client_stats
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(ClientStats)
+ err := b.DecodeMessage(msg)
+ m.LoadBalanceRequestType = &LoadBalanceRequest_ClientStats{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _LoadBalanceRequest_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*LoadBalanceRequest)
+ // load_balance_request_type
+ switch x := m.LoadBalanceRequestType.(type) {
+ case *LoadBalanceRequest_InitialRequest:
+ s := proto.Size(x.InitialRequest)
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *LoadBalanceRequest_ClientStats:
+ s := proto.Size(x.ClientStats)
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type InitialLoadBalanceRequest struct {
+ // Name of load balanced service (IE, balancer.service.com)
+ // length should be less than 256 bytes.
+ Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+}
+
+func (m *InitialLoadBalanceRequest) Reset() { *m = InitialLoadBalanceRequest{} }
+func (m *InitialLoadBalanceRequest) String() string { return proto.CompactTextString(m) }
+func (*InitialLoadBalanceRequest) ProtoMessage() {}
+func (*InitialLoadBalanceRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
+
+func (m *InitialLoadBalanceRequest) GetName() string {
+ if m != nil {
+ return m.Name
+ }
+ return ""
+}
+
+// Contains client level statistics that are useful to load balancing. Each
+// count except the timestamp should be reset to zero after reporting the stats.
+type ClientStats struct {
+ // The timestamp of generating the report.
+ Timestamp *Timestamp `protobuf:"bytes,1,opt,name=timestamp" json:"timestamp,omitempty"`
+ // The total number of RPCs that started.
+ NumCallsStarted int64 `protobuf:"varint,2,opt,name=num_calls_started,json=numCallsStarted" json:"num_calls_started,omitempty"`
+ // The total number of RPCs that finished.
+ NumCallsFinished int64 `protobuf:"varint,3,opt,name=num_calls_finished,json=numCallsFinished" json:"num_calls_finished,omitempty"`
+ // The total number of RPCs that were dropped by the client because of rate
+ // limiting.
+ NumCallsFinishedWithDropForRateLimiting int64 `protobuf:"varint,4,opt,name=num_calls_finished_with_drop_for_rate_limiting,json=numCallsFinishedWithDropForRateLimiting" json:"num_calls_finished_with_drop_for_rate_limiting,omitempty"`
+ // The total number of RPCs that were dropped by the client because of load
+ // balancing.
+ NumCallsFinishedWithDropForLoadBalancing int64 `protobuf:"varint,5,opt,name=num_calls_finished_with_drop_for_load_balancing,json=numCallsFinishedWithDropForLoadBalancing" json:"num_calls_finished_with_drop_for_load_balancing,omitempty"`
+ // The total number of RPCs that failed to reach a server except dropped RPCs.
+ NumCallsFinishedWithClientFailedToSend int64 `protobuf:"varint,6,opt,name=num_calls_finished_with_client_failed_to_send,json=numCallsFinishedWithClientFailedToSend" json:"num_calls_finished_with_client_failed_to_send,omitempty"`
+ // The total number of RPCs that finished and are known to have been received
+ // by a server.
+ NumCallsFinishedKnownReceived int64 `protobuf:"varint,7,opt,name=num_calls_finished_known_received,json=numCallsFinishedKnownReceived" json:"num_calls_finished_known_received,omitempty"`
+}
+
+func (m *ClientStats) Reset() { *m = ClientStats{} }
+func (m *ClientStats) String() string { return proto.CompactTextString(m) }
+func (*ClientStats) ProtoMessage() {}
+func (*ClientStats) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
+
+func (m *ClientStats) GetTimestamp() *Timestamp {
+ if m != nil {
+ return m.Timestamp
+ }
+ return nil
+}
+
+func (m *ClientStats) GetNumCallsStarted() int64 {
+ if m != nil {
+ return m.NumCallsStarted
+ }
+ return 0
+}
+
+func (m *ClientStats) GetNumCallsFinished() int64 {
+ if m != nil {
+ return m.NumCallsFinished
+ }
+ return 0
+}
+
+func (m *ClientStats) GetNumCallsFinishedWithDropForRateLimiting() int64 {
+ if m != nil {
+ return m.NumCallsFinishedWithDropForRateLimiting
+ }
+ return 0
+}
+
+func (m *ClientStats) GetNumCallsFinishedWithDropForLoadBalancing() int64 {
+ if m != nil {
+ return m.NumCallsFinishedWithDropForLoadBalancing
+ }
+ return 0
+}
+
+func (m *ClientStats) GetNumCallsFinishedWithClientFailedToSend() int64 {
+ if m != nil {
+ return m.NumCallsFinishedWithClientFailedToSend
+ }
+ return 0
+}
+
+func (m *ClientStats) GetNumCallsFinishedKnownReceived() int64 {
+ if m != nil {
+ return m.NumCallsFinishedKnownReceived
+ }
+ return 0
+}
+
+type LoadBalanceResponse struct {
+ // Types that are valid to be assigned to LoadBalanceResponseType:
+ // *LoadBalanceResponse_InitialResponse
+ // *LoadBalanceResponse_ServerList
+ LoadBalanceResponseType isLoadBalanceResponse_LoadBalanceResponseType `protobuf_oneof:"load_balance_response_type"`
+}
+
+func (m *LoadBalanceResponse) Reset() { *m = LoadBalanceResponse{} }
+func (m *LoadBalanceResponse) String() string { return proto.CompactTextString(m) }
+func (*LoadBalanceResponse) ProtoMessage() {}
+func (*LoadBalanceResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
+
+type isLoadBalanceResponse_LoadBalanceResponseType interface {
+ isLoadBalanceResponse_LoadBalanceResponseType()
+}
+
+type LoadBalanceResponse_InitialResponse struct {
+ InitialResponse *InitialLoadBalanceResponse `protobuf:"bytes,1,opt,name=initial_response,json=initialResponse,oneof"`
+}
+type LoadBalanceResponse_ServerList struct {
+ ServerList *ServerList `protobuf:"bytes,2,opt,name=server_list,json=serverList,oneof"`
+}
+
+func (*LoadBalanceResponse_InitialResponse) isLoadBalanceResponse_LoadBalanceResponseType() {}
+func (*LoadBalanceResponse_ServerList) isLoadBalanceResponse_LoadBalanceResponseType() {}
+
+func (m *LoadBalanceResponse) GetLoadBalanceResponseType() isLoadBalanceResponse_LoadBalanceResponseType {
+ if m != nil {
+ return m.LoadBalanceResponseType
+ }
+ return nil
+}
+
+func (m *LoadBalanceResponse) GetInitialResponse() *InitialLoadBalanceResponse {
+ if x, ok := m.GetLoadBalanceResponseType().(*LoadBalanceResponse_InitialResponse); ok {
+ return x.InitialResponse
+ }
+ return nil
+}
+
+func (m *LoadBalanceResponse) GetServerList() *ServerList {
+ if x, ok := m.GetLoadBalanceResponseType().(*LoadBalanceResponse_ServerList); ok {
+ return x.ServerList
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*LoadBalanceResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _LoadBalanceResponse_OneofMarshaler, _LoadBalanceResponse_OneofUnmarshaler, _LoadBalanceResponse_OneofSizer, []interface{}{
+ (*LoadBalanceResponse_InitialResponse)(nil),
+ (*LoadBalanceResponse_ServerList)(nil),
+ }
+}
+
+func _LoadBalanceResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*LoadBalanceResponse)
+ // load_balance_response_type
+ switch x := m.LoadBalanceResponseType.(type) {
+ case *LoadBalanceResponse_InitialResponse:
+ b.EncodeVarint(1<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.InitialResponse); err != nil {
+ return err
+ }
+ case *LoadBalanceResponse_ServerList:
+ b.EncodeVarint(2<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.ServerList); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("LoadBalanceResponse.LoadBalanceResponseType has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _LoadBalanceResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*LoadBalanceResponse)
+ switch tag {
+ case 1: // load_balance_response_type.initial_response
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(InitialLoadBalanceResponse)
+ err := b.DecodeMessage(msg)
+ m.LoadBalanceResponseType = &LoadBalanceResponse_InitialResponse{msg}
+ return true, err
+ case 2: // load_balance_response_type.server_list
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(ServerList)
+ err := b.DecodeMessage(msg)
+ m.LoadBalanceResponseType = &LoadBalanceResponse_ServerList{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _LoadBalanceResponse_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*LoadBalanceResponse)
+ // load_balance_response_type
+ switch x := m.LoadBalanceResponseType.(type) {
+ case *LoadBalanceResponse_InitialResponse:
+ s := proto.Size(x.InitialResponse)
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *LoadBalanceResponse_ServerList:
+ s := proto.Size(x.ServerList)
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type InitialLoadBalanceResponse struct {
+ // This is an application layer redirect that indicates the client should use
+ // the specified server for load balancing. When this field is non-empty in
+ // the response, the client should open a separate connection to the
+ // load_balancer_delegate and call the BalanceLoad method. Its length should
+ // be less than 64 bytes.
+ LoadBalancerDelegate string `protobuf:"bytes,1,opt,name=load_balancer_delegate,json=loadBalancerDelegate" json:"load_balancer_delegate,omitempty"`
+ // This interval defines how often the client should send the client stats
+ // to the load balancer. Stats should only be reported when the duration is
+ // positive.
+ ClientStatsReportInterval *Duration `protobuf:"bytes,2,opt,name=client_stats_report_interval,json=clientStatsReportInterval" json:"client_stats_report_interval,omitempty"`
+}
+
+func (m *InitialLoadBalanceResponse) Reset() { *m = InitialLoadBalanceResponse{} }
+func (m *InitialLoadBalanceResponse) String() string { return proto.CompactTextString(m) }
+func (*InitialLoadBalanceResponse) ProtoMessage() {}
+func (*InitialLoadBalanceResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
+
+func (m *InitialLoadBalanceResponse) GetLoadBalancerDelegate() string {
+ if m != nil {
+ return m.LoadBalancerDelegate
+ }
+ return ""
+}
+
+func (m *InitialLoadBalanceResponse) GetClientStatsReportInterval() *Duration {
+ if m != nil {
+ return m.ClientStatsReportInterval
+ }
+ return nil
+}
+
+type ServerList struct {
+ // Contains a list of servers selected by the load balancer. The list will
+ // be updated when server resolutions change or as needed to balance load
+ // across more servers. The client should consume the server list in order
+ // unless instructed otherwise via the client_config.
+ Servers []*Server `protobuf:"bytes,1,rep,name=servers" json:"servers,omitempty"`
+ // Indicates the amount of time that the client should consider this server
+ // list as valid. It may be considered stale after waiting this interval of
+ // time after receiving the list. If the interval is not positive, the
+ // client can assume the list is valid until the next list is received.
+ ExpirationInterval *Duration `protobuf:"bytes,3,opt,name=expiration_interval,json=expirationInterval" json:"expiration_interval,omitempty"`
+}
+
+func (m *ServerList) Reset() { *m = ServerList{} }
+func (m *ServerList) String() string { return proto.CompactTextString(m) }
+func (*ServerList) ProtoMessage() {}
+func (*ServerList) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
+
+func (m *ServerList) GetServers() []*Server {
+ if m != nil {
+ return m.Servers
+ }
+ return nil
+}
+
+func (m *ServerList) GetExpirationInterval() *Duration {
+ if m != nil {
+ return m.ExpirationInterval
+ }
+ return nil
+}
+
+// Contains server information. When none of the [drop_for_*] fields are true,
+// use the other fields. When drop_for_rate_limiting is true, ignore all other
+// fields. Use drop_for_load_balancing only when it is true and
+// drop_for_rate_limiting is false.
+type Server struct {
+ // A resolved address for the server, serialized in network-byte-order. It may
+ // either be an IPv4 or IPv6 address.
+ IpAddress []byte `protobuf:"bytes,1,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"`
+ // A resolved port number for the server.
+ Port int32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"`
+ // An opaque but printable token given to the frontend for each pick. All
+ // frontend requests for that pick must include the token in its initial
+ // metadata. The token is used by the backend to verify the request and to
+ // allow the backend to report load to the gRPC LB system.
+ //
+ // Its length is variable but less than 50 bytes.
+ LoadBalanceToken string `protobuf:"bytes,3,opt,name=load_balance_token,json=loadBalanceToken" json:"load_balance_token,omitempty"`
+ // Indicates whether this particular request should be dropped by the client
+ // for rate limiting.
+ DropForRateLimiting bool `protobuf:"varint,4,opt,name=drop_for_rate_limiting,json=dropForRateLimiting" json:"drop_for_rate_limiting,omitempty"`
+ // Indicates whether this particular request should be dropped by the client
+ // for load balancing.
+ DropForLoadBalancing bool `protobuf:"varint,5,opt,name=drop_for_load_balancing,json=dropForLoadBalancing" json:"drop_for_load_balancing,omitempty"`
+}
+
+func (m *Server) Reset() { *m = Server{} }
+func (m *Server) String() string { return proto.CompactTextString(m) }
+func (*Server) ProtoMessage() {}
+func (*Server) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
+
+func (m *Server) GetIpAddress() []byte {
+ if m != nil {
+ return m.IpAddress
+ }
+ return nil
+}
+
+func (m *Server) GetPort() int32 {
+ if m != nil {
+ return m.Port
+ }
+ return 0
+}
+
+func (m *Server) GetLoadBalanceToken() string {
+ if m != nil {
+ return m.LoadBalanceToken
+ }
+ return ""
+}
+
+func (m *Server) GetDropForRateLimiting() bool {
+ if m != nil {
+ return m.DropForRateLimiting
+ }
+ return false
+}
+
+func (m *Server) GetDropForLoadBalancing() bool {
+ if m != nil {
+ return m.DropForLoadBalancing
+ }
+ return false
+}
+
+func init() {
+ proto.RegisterType((*Duration)(nil), "grpc.lb.v1.Duration")
+ proto.RegisterType((*Timestamp)(nil), "grpc.lb.v1.Timestamp")
+ proto.RegisterType((*LoadBalanceRequest)(nil), "grpc.lb.v1.LoadBalanceRequest")
+ proto.RegisterType((*InitialLoadBalanceRequest)(nil), "grpc.lb.v1.InitialLoadBalanceRequest")
+ proto.RegisterType((*ClientStats)(nil), "grpc.lb.v1.ClientStats")
+ proto.RegisterType((*LoadBalanceResponse)(nil), "grpc.lb.v1.LoadBalanceResponse")
+ proto.RegisterType((*InitialLoadBalanceResponse)(nil), "grpc.lb.v1.InitialLoadBalanceResponse")
+ proto.RegisterType((*ServerList)(nil), "grpc.lb.v1.ServerList")
+ proto.RegisterType((*Server)(nil), "grpc.lb.v1.Server")
+}
+
+func init() { proto.RegisterFile("grpclb.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 733 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0xdd, 0x4e, 0x1b, 0x39,
+ 0x14, 0x66, 0x36, 0xfc, 0xe5, 0x24, 0x5a, 0x58, 0x93, 0x85, 0xc0, 0xc2, 0x2e, 0x1b, 0xa9, 0x34,
+ 0xaa, 0x68, 0x68, 0x43, 0x7b, 0xd1, 0x9f, 0x9b, 0x02, 0x45, 0x41, 0xe5, 0xa2, 0x72, 0xa8, 0x7a,
+ 0x55, 0x59, 0x4e, 0xc6, 0x80, 0xc5, 0xc4, 0x9e, 0xda, 0x4e, 0x68, 0x2f, 0x7b, 0xd9, 0x47, 0xe9,
+ 0x63, 0x54, 0x7d, 0x86, 0xbe, 0x4f, 0x65, 0x7b, 0x26, 0x33, 0x90, 0x1f, 0xd4, 0xbb, 0xf1, 0xf1,
+ 0x77, 0xbe, 0xf3, 0xf9, 0xd8, 0xdf, 0x19, 0x28, 0x5f, 0xa8, 0xb8, 0x1b, 0x75, 0x1a, 0xb1, 0x92,
+ 0x46, 0x22, 0xb0, 0xab, 0x46, 0xd4, 0x69, 0x0c, 0x1e, 0xd7, 0x9e, 0xc3, 0xe2, 0x51, 0x5f, 0x51,
+ 0xc3, 0xa5, 0x40, 0x55, 0x58, 0xd0, 0xac, 0x2b, 0x45, 0xa8, 0xab, 0xc1, 0x76, 0x50, 0x2f, 0xe0,
+ 0x74, 0x89, 0x2a, 0x30, 0x27, 0xa8, 0x90, 0xba, 0xfa, 0xc7, 0x76, 0x50, 0x9f, 0xc3, 0x7e, 0x51,
+ 0x7b, 0x01, 0xc5, 0x33, 0xde, 0x63, 0xda, 0xd0, 0x5e, 0xfc, 0xdb, 0xc9, 0xdf, 0x03, 0x40, 0xa7,
+ 0x92, 0x86, 0x07, 0x34, 0xa2, 0xa2, 0xcb, 0x30, 0xfb, 0xd8, 0x67, 0xda, 0xa0, 0xb7, 0xb0, 0xc4,
+ 0x05, 0x37, 0x9c, 0x46, 0x44, 0xf9, 0x90, 0xa3, 0x2b, 0x35, 0xef, 0x35, 0x32, 0xd5, 0x8d, 0x13,
+ 0x0f, 0x19, 0xcd, 0x6f, 0xcd, 0xe0, 0x3f, 0x93, 0xfc, 0x94, 0xf1, 0x25, 0x94, 0xbb, 0x11, 0x67,
+ 0xc2, 0x10, 0x6d, 0xa8, 0xf1, 0x2a, 0x4a, 0xcd, 0xb5, 0x3c, 0xdd, 0xa1, 0xdb, 0x6f, 0xdb, 0xed,
+ 0xd6, 0x0c, 0x2e, 0x75, 0xb3, 0xe5, 0xc1, 0x3f, 0xb0, 0x1e, 0x49, 0x1a, 0x92, 0x8e, 0x2f, 0x93,
+ 0x8a, 0x22, 0xe6, 0x73, 0xcc, 0x6a, 0x7b, 0xb0, 0x3e, 0x51, 0x09, 0x42, 0x30, 0x2b, 0x68, 0x8f,
+ 0x39, 0xf9, 0x45, 0xec, 0xbe, 0x6b, 0x5f, 0x67, 0xa1, 0x94, 0x2b, 0x86, 0xf6, 0xa1, 0x68, 0xd2,
+ 0x0e, 0x26, 0xe7, 0xfc, 0x3b, 0x2f, 0x6c, 0xd8, 0x5e, 0x9c, 0xe1, 0xd0, 0x03, 0xf8, 0x4b, 0xf4,
+ 0x7b, 0xa4, 0x4b, 0xa3, 0x48, 0xdb, 0x33, 0x29, 0xc3, 0x42, 0x77, 0xaa, 0x02, 0x5e, 0x12, 0xfd,
+ 0xde, 0xa1, 0x8d, 0xb7, 0x7d, 0x18, 0xed, 0x02, 0xca, 0xb0, 0xe7, 0x5c, 0x70, 0x7d, 0xc9, 0xc2,
+ 0x6a, 0xc1, 0x81, 0x97, 0x53, 0xf0, 0x71, 0x12, 0x47, 0x04, 0x1a, 0xa3, 0x68, 0x72, 0xcd, 0xcd,
+ 0x25, 0x09, 0x95, 0x8c, 0xc9, 0xb9, 0x54, 0x44, 0x51, 0xc3, 0x48, 0xc4, 0x7b, 0xdc, 0x70, 0x71,
+ 0x51, 0x9d, 0x75, 0x4c, 0xf7, 0x6f, 0x33, 0xbd, 0xe7, 0xe6, 0xf2, 0x48, 0xc9, 0xf8, 0x58, 0x2a,
+ 0x4c, 0x0d, 0x3b, 0x4d, 0xe0, 0x88, 0xc2, 0xde, 0x9d, 0x05, 0x72, 0xed, 0xb6, 0x15, 0xe6, 0x5c,
+ 0x85, 0xfa, 0x94, 0x0a, 0x59, 0xef, 0x6d, 0x89, 0x0f, 0xf0, 0x70, 0x52, 0x89, 0xe4, 0x19, 0x9c,
+ 0x53, 0x1e, 0xb1, 0x90, 0x18, 0x49, 0x34, 0x13, 0x61, 0x75, 0xde, 0x15, 0xd8, 0x19, 0x57, 0xc0,
+ 0x5f, 0xd5, 0xb1, 0xc3, 0x9f, 0xc9, 0x36, 0x13, 0x21, 0x6a, 0xc1, 0xff, 0x63, 0xe8, 0xaf, 0x84,
+ 0xbc, 0x16, 0x44, 0xb1, 0x2e, 0xe3, 0x03, 0x16, 0x56, 0x17, 0x1c, 0xe5, 0xd6, 0x6d, 0xca, 0x37,
+ 0x16, 0x85, 0x13, 0x50, 0xed, 0x47, 0x00, 0x2b, 0x37, 0x9e, 0x8d, 0x8e, 0xa5, 0xd0, 0x0c, 0xb5,
+ 0x61, 0x39, 0x73, 0x80, 0x8f, 0x25, 0x4f, 0x63, 0xe7, 0x2e, 0x0b, 0x78, 0x74, 0x6b, 0x06, 0x2f,
+ 0x0d, 0x3d, 0x90, 0x90, 0x3e, 0x83, 0x92, 0x66, 0x6a, 0xc0, 0x14, 0x89, 0xb8, 0x36, 0x89, 0x07,
+ 0x56, 0xf3, 0x7c, 0x6d, 0xb7, 0x7d, 0xca, 0x9d, 0x87, 0x40, 0x0f, 0x57, 0x07, 0x9b, 0xb0, 0x71,
+ 0xcb, 0x01, 0x9e, 0xd3, 0x5b, 0xe0, 0x5b, 0x00, 0x1b, 0x93, 0xa5, 0xa0, 0x27, 0xb0, 0x9a, 0x4f,
+ 0x56, 0x24, 0x64, 0x11, 0xbb, 0xa0, 0x26, 0xb5, 0x45, 0x25, 0xca, 0x92, 0xd4, 0x51, 0xb2, 0x87,
+ 0xde, 0xc1, 0x66, 0xde, 0xb2, 0x44, 0xb1, 0x58, 0x2a, 0x43, 0xb8, 0x30, 0x4c, 0x0d, 0x68, 0x94,
+ 0xc8, 0xaf, 0xe4, 0xe5, 0xa7, 0x43, 0x0c, 0xaf, 0xe7, 0xdc, 0x8b, 0x5d, 0xde, 0x49, 0x92, 0x56,
+ 0xfb, 0x12, 0x00, 0x64, 0xc7, 0x44, 0xbb, 0x76, 0x62, 0xd9, 0x95, 0x9d, 0x58, 0x85, 0x7a, 0xa9,
+ 0x89, 0x46, 0xfb, 0x81, 0x53, 0x08, 0x7a, 0x0d, 0x2b, 0xec, 0x53, 0xcc, 0x7d, 0x95, 0x4c, 0x4a,
+ 0x61, 0x8a, 0x14, 0x94, 0x25, 0x0c, 0x35, 0xfc, 0x0c, 0x60, 0xde, 0x53, 0xa3, 0x2d, 0x00, 0x1e,
+ 0x13, 0x1a, 0x86, 0x8a, 0x69, 0x3f, 0x34, 0xcb, 0xb8, 0xc8, 0xe3, 0x57, 0x3e, 0x60, 0xe7, 0x87,
+ 0x55, 0x9f, 0x4c, 0x4d, 0xf7, 0x6d, 0xed, 0x7c, 0xe3, 0x2e, 0x8c, 0xbc, 0x62, 0xc2, 0x69, 0x28,
+ 0xe2, 0xe5, 0x5c, 0x2b, 0xcf, 0x6c, 0x1c, 0xed, 0xc3, 0xea, 0x14, 0xdb, 0x2e, 0xe2, 0x95, 0x70,
+ 0x8c, 0x45, 0x9f, 0xc2, 0xda, 0x34, 0x2b, 0x2e, 0xe2, 0x4a, 0x38, 0xc6, 0x76, 0xcd, 0x0e, 0x94,
+ 0x73, 0xf7, 0xaf, 0x10, 0x86, 0x52, 0xf2, 0x6d, 0xc3, 0xe8, 0xdf, 0x7c, 0x83, 0x46, 0x87, 0xe5,
+ 0xc6, 0x7f, 0x13, 0xf7, 0xfd, 0x43, 0xaa, 0x07, 0x8f, 0x82, 0xce, 0xbc, 0xfb, 0x7d, 0xed, 0xff,
+ 0x0a, 0x00, 0x00, 0xff, 0xff, 0x64, 0xbf, 0xda, 0x5e, 0xce, 0x06, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/grpclb.proto b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/grpclb.proto
new file mode 100644
index 0000000..a2502fb
--- /dev/null
+++ b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/grpclb.proto
@@ -0,0 +1,179 @@
+// Copyright 2016, Google Inc.
+// 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.
+
+syntax = "proto3";
+
+package grpc.lb.v1;
+
+message Duration {
+ // Signed seconds of the span of time. Must be from -315,576,000,000
+ // to +315,576,000,000 inclusive.
+ int64 seconds = 1;
+
+ // Signed fractions of a second at nanosecond resolution of the span
+ // of time. Durations less than one second are represented with a 0
+ // `seconds` field and a positive or negative `nanos` field. For durations
+ // of one second or more, a non-zero value for the `nanos` field must be
+ // of the same sign as the `seconds` field. Must be from -999,999,999
+ // to +999,999,999 inclusive.
+ int32 nanos = 2;
+}
+
+message Timestamp {
+
+ // Represents seconds of UTC time since Unix epoch
+ // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ // 9999-12-31T23:59:59Z inclusive.
+ int64 seconds = 1;
+
+ // Non-negative fractions of a second at nanosecond resolution. Negative
+ // second values with fractions must still have non-negative nanos values
+ // that count forward in time. Must be from 0 to 999,999,999
+ // inclusive.
+ int32 nanos = 2;
+}
+
+service LoadBalancer {
+ // Bidirectional rpc to get a list of servers.
+ rpc BalanceLoad(stream LoadBalanceRequest)
+ returns (stream LoadBalanceResponse);
+}
+
+message LoadBalanceRequest {
+ oneof load_balance_request_type {
+ // This message should be sent on the first request to the load balancer.
+ InitialLoadBalanceRequest initial_request = 1;
+
+ // The client stats should be periodically reported to the load balancer
+ // based on the duration defined in the InitialLoadBalanceResponse.
+ ClientStats client_stats = 2;
+ }
+}
+
+message InitialLoadBalanceRequest {
+ // Name of load balanced service (IE, balancer.service.com)
+ // length should be less than 256 bytes.
+ string name = 1;
+}
+
+// Contains client level statistics that are useful to load balancing. Each
+// count except the timestamp should be reset to zero after reporting the stats.
+message ClientStats {
+ // The timestamp of generating the report.
+ Timestamp timestamp = 1;
+
+ // The total number of RPCs that started.
+ int64 num_calls_started = 2;
+
+ // The total number of RPCs that finished.
+ int64 num_calls_finished = 3;
+
+ // The total number of RPCs that were dropped by the client because of rate
+ // limiting.
+ int64 num_calls_finished_with_drop_for_rate_limiting = 4;
+
+ // The total number of RPCs that were dropped by the client because of load
+ // balancing.
+ int64 num_calls_finished_with_drop_for_load_balancing = 5;
+
+ // The total number of RPCs that failed to reach a server except dropped RPCs.
+ int64 num_calls_finished_with_client_failed_to_send = 6;
+
+ // The total number of RPCs that finished and are known to have been received
+ // by a server.
+ int64 num_calls_finished_known_received = 7;
+}
+
+message LoadBalanceResponse {
+ oneof load_balance_response_type {
+ // This message should be sent on the first response to the client.
+ InitialLoadBalanceResponse initial_response = 1;
+
+ // Contains the list of servers selected by the load balancer. The client
+ // should send requests to these servers in the specified order.
+ ServerList server_list = 2;
+ }
+}
+
+message InitialLoadBalanceResponse {
+ // This is an application layer redirect that indicates the client should use
+ // the specified server for load balancing. When this field is non-empty in
+ // the response, the client should open a separate connection to the
+ // load_balancer_delegate and call the BalanceLoad method. Its length should
+ // be less than 64 bytes.
+ string load_balancer_delegate = 1;
+
+ // This interval defines how often the client should send the client stats
+ // to the load balancer. Stats should only be reported when the duration is
+ // positive.
+ Duration client_stats_report_interval = 2;
+}
+
+message ServerList {
+ // Contains a list of servers selected by the load balancer. The list will
+ // be updated when server resolutions change or as needed to balance load
+ // across more servers. The client should consume the server list in order
+ // unless instructed otherwise via the client_config.
+ repeated Server servers = 1;
+
+ // Indicates the amount of time that the client should consider this server
+ // list as valid. It may be considered stale after waiting this interval of
+ // time after receiving the list. If the interval is not positive, the
+ // client can assume the list is valid until the next list is received.
+ Duration expiration_interval = 3;
+}
+
+// Contains server information. When none of the [drop_for_*] fields are true,
+// use the other fields. When drop_for_rate_limiting is true, ignore all other
+// fields. Use drop_for_load_balancing only when it is true and
+// drop_for_rate_limiting is false.
+message Server {
+ // A resolved address for the server, serialized in network-byte-order. It may
+ // either be an IPv4 or IPv6 address.
+ bytes ip_address = 1;
+
+ // A resolved port number for the server.
+ int32 port = 2;
+
+ // An opaque but printable token given to the frontend for each pick. All
+ // frontend requests for that pick must include the token in its initial
+ // metadata. The token is used by the backend to verify the request and to
+ // allow the backend to report load to the gRPC LB system.
+ //
+ // Its length is variable but less than 50 bytes.
+ string load_balance_token = 3;
+
+ // Indicates whether this particular request should be dropped by the client
+ // for rate limiting.
+ bool drop_for_rate_limiting = 4;
+
+ // Indicates whether this particular request should be dropped by the client
+ // for load balancing.
+ bool drop_for_load_balancing = 5;
+}
diff --git a/vendor/google.golang.org/grpc/grpclog/logger.go b/vendor/google.golang.org/grpc/grpclog/logger.go
new file mode 100644
index 0000000..3b29330
--- /dev/null
+++ b/vendor/google.golang.org/grpc/grpclog/logger.go
@@ -0,0 +1,93 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * 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.
+ *
+ */
+
+/*
+Package grpclog defines logging for grpc.
+*/
+package grpclog // import "google.golang.org/grpc/grpclog"
+
+import (
+ "log"
+ "os"
+)
+
+// Use golang's standard logger by default.
+// Access is not mutex-protected: do not modify except in init()
+// functions.
+var logger Logger = log.New(os.Stderr, "", log.LstdFlags)
+
+// Logger mimics golang's standard Logger as an interface.
+type Logger interface {
+ Fatal(args ...interface{})
+ Fatalf(format string, args ...interface{})
+ Fatalln(args ...interface{})
+ Print(args ...interface{})
+ Printf(format string, args ...interface{})
+ Println(args ...interface{})
+}
+
+// SetLogger sets the logger that is used in grpc. Call only from
+// init() functions.
+func SetLogger(l Logger) {
+ logger = l
+}
+
+// Fatal is equivalent to Print() followed by a call to os.Exit() with a non-zero exit code.
+func Fatal(args ...interface{}) {
+ logger.Fatal(args...)
+}
+
+// Fatalf is equivalent to Printf() followed by a call to os.Exit() with a non-zero exit code.
+func Fatalf(format string, args ...interface{}) {
+ logger.Fatalf(format, args...)
+}
+
+// Fatalln is equivalent to Println() followed by a call to os.Exit()) with a non-zero exit code.
+func Fatalln(args ...interface{}) {
+ logger.Fatalln(args...)
+}
+
+// Print prints to the logger. Arguments are handled in the manner of fmt.Print.
+func Print(args ...interface{}) {
+ logger.Print(args...)
+}
+
+// Printf prints to the logger. Arguments are handled in the manner of fmt.Printf.
+func Printf(format string, args ...interface{}) {
+ logger.Printf(format, args...)
+}
+
+// Println prints to the logger. Arguments are handled in the manner of fmt.Println.
+func Println(args ...interface{}) {
+ logger.Println(args...)
+}
diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go
new file mode 100644
index 0000000..89c4d45
--- /dev/null
+++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go
@@ -0,0 +1,176 @@
+// Code generated by protoc-gen-go.
+// source: health.proto
+// DO NOT EDIT!
+
+/*
+Package grpc_health_v1 is a generated protocol buffer package.
+
+It is generated from these files:
+ health.proto
+
+It has these top-level messages:
+ HealthCheckRequest
+ HealthCheckResponse
+*/
+package grpc_health_v1
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+import (
+ context "golang.org/x/net/context"
+ grpc "google.golang.org/grpc"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+type HealthCheckResponse_ServingStatus int32
+
+const (
+ HealthCheckResponse_UNKNOWN HealthCheckResponse_ServingStatus = 0
+ HealthCheckResponse_SERVING HealthCheckResponse_ServingStatus = 1
+ HealthCheckResponse_NOT_SERVING HealthCheckResponse_ServingStatus = 2
+)
+
+var HealthCheckResponse_ServingStatus_name = map[int32]string{
+ 0: "UNKNOWN",
+ 1: "SERVING",
+ 2: "NOT_SERVING",
+}
+var HealthCheckResponse_ServingStatus_value = map[string]int32{
+ "UNKNOWN": 0,
+ "SERVING": 1,
+ "NOT_SERVING": 2,
+}
+
+func (x HealthCheckResponse_ServingStatus) String() string {
+ return proto.EnumName(HealthCheckResponse_ServingStatus_name, int32(x))
+}
+func (HealthCheckResponse_ServingStatus) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{1, 0}
+}
+
+type HealthCheckRequest struct {
+ Service string `protobuf:"bytes,1,opt,name=service" json:"service,omitempty"`
+}
+
+func (m *HealthCheckRequest) Reset() { *m = HealthCheckRequest{} }
+func (m *HealthCheckRequest) String() string { return proto.CompactTextString(m) }
+func (*HealthCheckRequest) ProtoMessage() {}
+func (*HealthCheckRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+type HealthCheckResponse struct {
+ Status HealthCheckResponse_ServingStatus `protobuf:"varint,1,opt,name=status,enum=grpc.health.v1.HealthCheckResponse_ServingStatus" json:"status,omitempty"`
+}
+
+func (m *HealthCheckResponse) Reset() { *m = HealthCheckResponse{} }
+func (m *HealthCheckResponse) String() string { return proto.CompactTextString(m) }
+func (*HealthCheckResponse) ProtoMessage() {}
+func (*HealthCheckResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func init() {
+ proto.RegisterType((*HealthCheckRequest)(nil), "grpc.health.v1.HealthCheckRequest")
+ proto.RegisterType((*HealthCheckResponse)(nil), "grpc.health.v1.HealthCheckResponse")
+ proto.RegisterEnum("grpc.health.v1.HealthCheckResponse_ServingStatus", HealthCheckResponse_ServingStatus_name, HealthCheckResponse_ServingStatus_value)
+}
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ context.Context
+var _ grpc.ClientConn
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+const _ = grpc.SupportPackageIsVersion4
+
+// Client API for Health service
+
+type HealthClient interface {
+ Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error)
+}
+
+type healthClient struct {
+ cc *grpc.ClientConn
+}
+
+func NewHealthClient(cc *grpc.ClientConn) HealthClient {
+ return &healthClient{cc}
+}
+
+func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) {
+ out := new(HealthCheckResponse)
+ err := grpc.Invoke(ctx, "/grpc.health.v1.Health/Check", in, out, c.cc, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// Server API for Health service
+
+type HealthServer interface {
+ Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error)
+}
+
+func RegisterHealthServer(s *grpc.Server, srv HealthServer) {
+ s.RegisterService(&_Health_serviceDesc, srv)
+}
+
+func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(HealthCheckRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(HealthServer).Check(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/grpc.health.v1.Health/Check",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(HealthServer).Check(ctx, req.(*HealthCheckRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+var _Health_serviceDesc = grpc.ServiceDesc{
+ ServiceName: "grpc.health.v1.Health",
+ HandlerType: (*HealthServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "Check",
+ Handler: _Health_Check_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{},
+ Metadata: "health.proto",
+}
+
+func init() { proto.RegisterFile("health.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 204 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0xc9, 0x48, 0x4d, 0xcc,
+ 0x29, 0xc9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x4b, 0x2f, 0x2a, 0x48, 0xd6, 0x83,
+ 0x0a, 0x95, 0x19, 0x2a, 0xe9, 0x71, 0x09, 0x79, 0x80, 0x39, 0xce, 0x19, 0xa9, 0xc9, 0xd9, 0x41,
+ 0xa9, 0x85, 0xa5, 0xa9, 0xc5, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0x45, 0x65, 0x99, 0xc9,
+ 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x30, 0xae, 0xd2, 0x1c, 0x46, 0x2e, 0x61, 0x14,
+ 0x0d, 0xc5, 0x05, 0xf9, 0x79, 0xc5, 0xa9, 0x42, 0x9e, 0x5c, 0x6c, 0xc5, 0x25, 0x89, 0x25, 0xa5,
+ 0xc5, 0x60, 0x0d, 0x7c, 0x46, 0x86, 0x7a, 0xa8, 0x16, 0xe9, 0x61, 0xd1, 0xa4, 0x17, 0x0c, 0x32,
+ 0x34, 0x2f, 0x3d, 0x18, 0xac, 0x31, 0x08, 0x6a, 0x80, 0x92, 0x15, 0x17, 0x2f, 0x8a, 0x84, 0x10,
+ 0x37, 0x17, 0x7b, 0xa8, 0x9f, 0xb7, 0x9f, 0x7f, 0xb8, 0x9f, 0x00, 0x03, 0x88, 0x13, 0xec, 0x1a,
+ 0x14, 0xe6, 0xe9, 0xe7, 0x2e, 0xc0, 0x28, 0xc4, 0xcf, 0xc5, 0xed, 0xe7, 0x1f, 0x12, 0x0f, 0x13,
+ 0x60, 0x32, 0x8a, 0xe2, 0x62, 0x83, 0x58, 0x24, 0x14, 0xc0, 0xc5, 0x0a, 0xb6, 0x4c, 0x48, 0x09,
+ 0xaf, 0x4b, 0xc0, 0xfe, 0x95, 0x52, 0x26, 0xc2, 0xb5, 0x49, 0x6c, 0xe0, 0x10, 0x34, 0x06, 0x04,
+ 0x00, 0x00, 0xff, 0xff, 0xac, 0x56, 0x2a, 0xcb, 0x51, 0x01, 0x00, 0x00,
+}
diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.proto b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.proto
new file mode 100644
index 0000000..e2dc088
--- /dev/null
+++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.proto
@@ -0,0 +1,20 @@
+syntax = "proto3";
+
+package grpc.health.v1;
+
+message HealthCheckRequest {
+ string service = 1;
+}
+
+message HealthCheckResponse {
+ enum ServingStatus {
+ UNKNOWN = 0;
+ SERVING = 1;
+ NOT_SERVING = 2;
+ }
+ ServingStatus status = 1;
+}
+
+service Health{
+ rpc Check(HealthCheckRequest) returns (HealthCheckResponse);
+}
diff --git a/vendor/google.golang.org/grpc/health/health.go b/vendor/google.golang.org/grpc/health/health.go
new file mode 100644
index 0000000..3425529
--- /dev/null
+++ b/vendor/google.golang.org/grpc/health/health.go
@@ -0,0 +1,52 @@
+// Package health provides some utility functions to health-check a server. The implementation
+// is based on protobuf. Users need to write their own implementations if other IDLs are used.
+package health
+
+import (
+ "sync"
+
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
+)
+
+// Server implements `service Health`.
+type Server struct {
+ mu sync.Mutex
+ // statusMap stores the serving status of the services this Server monitors.
+ statusMap map[string]healthpb.HealthCheckResponse_ServingStatus
+}
+
+// NewServer returns a new Server.
+func NewServer() *Server {
+ return &Server{
+ statusMap: make(map[string]healthpb.HealthCheckResponse_ServingStatus),
+ }
+}
+
+// Check implements `service Health`.
+func (s *Server) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if in.Service == "" {
+ // check the server overall health status.
+ return &healthpb.HealthCheckResponse{
+ Status: healthpb.HealthCheckResponse_SERVING,
+ }, nil
+ }
+ if status, ok := s.statusMap[in.Service]; ok {
+ return &healthpb.HealthCheckResponse{
+ Status: status,
+ }, nil
+ }
+ return nil, grpc.Errorf(codes.NotFound, "unknown service")
+}
+
+// SetServingStatus is called when need to reset the serving status of a service
+// or insert a new service entry into the statusMap.
+func (s *Server) SetServingStatus(service string, status healthpb.HealthCheckResponse_ServingStatus) {
+ s.mu.Lock()
+ s.statusMap[service] = status
+ s.mu.Unlock()
+}
diff --git a/vendor/google.golang.org/grpc/interceptor.go b/vendor/google.golang.org/grpc/interceptor.go
new file mode 100644
index 0000000..a692161
--- /dev/null
+++ b/vendor/google.golang.org/grpc/interceptor.go
@@ -0,0 +1,90 @@
+/*
+ *
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "golang.org/x/net/context"
+)
+
+// UnaryInvoker is called by UnaryClientInterceptor to complete RPCs.
+type UnaryInvoker func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error
+
+// UnaryClientInterceptor intercepts the execution of a unary RPC on the client. invoker is the handler to complete the RPC
+// and it is the responsibility of the interceptor to call it.
+// This is the EXPERIMENTAL API.
+type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error
+
+// Streamer is called by StreamClientInterceptor to create a ClientStream.
+type Streamer func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error)
+
+// StreamClientInterceptor intercepts the creation of ClientStream. It may return a custom ClientStream to intercept all I/O
+// operations. streamer is the handlder to create a ClientStream and it is the responsibility of the interceptor to call it.
+// This is the EXPERIMENTAL API.
+type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error)
+
+// UnaryServerInfo consists of various information about a unary RPC on
+// server side. All per-rpc information may be mutated by the interceptor.
+type UnaryServerInfo struct {
+ // Server is the service implementation the user provides. This is read-only.
+ Server interface{}
+ // FullMethod is the full RPC method string, i.e., /package.service/method.
+ FullMethod string
+}
+
+// UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal
+// execution of a unary RPC.
+type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error)
+
+// UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info
+// contains all the information of this RPC the interceptor can operate on. And handler is the wrapper
+// of the service method implementation. It is the responsibility of the interceptor to invoke handler
+// to complete the RPC.
+type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error)
+
+// StreamServerInfo consists of various information about a streaming RPC on
+// server side. All per-rpc information may be mutated by the interceptor.
+type StreamServerInfo struct {
+ // FullMethod is the full RPC method string, i.e., /package.service/method.
+ FullMethod string
+ // IsClientStream indicates whether the RPC is a client streaming RPC.
+ IsClientStream bool
+ // IsServerStream indicates whether the RPC is a server streaming RPC.
+ IsServerStream bool
+}
+
+// StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server.
+// info contains all the information of this RPC the interceptor can operate on. And handler is the
+// service method implementation. It is the responsibility of the interceptor to invoke handler to
+// complete the RPC.
+type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error
diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go
new file mode 100644
index 0000000..5489143
--- /dev/null
+++ b/vendor/google.golang.org/grpc/internal/internal.go
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+// Package internal contains gRPC-internal code for testing, to avoid polluting
+// the godoc of the top-level grpc package.
+package internal
+
+// TestingCloseConns closes all existing transports but keeps
+// grpcServer.lis accepting new connections.
+//
+// The provided grpcServer must be of type *grpc.Server. It is untyped
+// for circular dependency reasons.
+var TestingCloseConns func(grpcServer interface{})
+
+// TestingUseHandlerImpl enables the http.Handler-based server implementation.
+// It must be called before Serve and requires TLS credentials.
+//
+// The provided grpcServer must be of type *grpc.Server. It is untyped
+// for circular dependency reasons.
+var TestingUseHandlerImpl func(grpcServer interface{})
diff --git a/vendor/google.golang.org/grpc/keepalive/keepalive.go b/vendor/google.golang.org/grpc/keepalive/keepalive.go
new file mode 100644
index 0000000..d492589
--- /dev/null
+++ b/vendor/google.golang.org/grpc/keepalive/keepalive.go
@@ -0,0 +1,80 @@
+/*
+ *
+ * Copyright 2017, Google Inc.
+ * 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.
+ *
+ */
+
+// Package keepalive defines configurable parameters for point-to-point healthcheck.
+package keepalive
+
+import (
+ "time"
+)
+
+// ClientParameters is used to set keepalive parameters on the client-side.
+// These configure how the client will actively probe to notice when a connection broken
+// and to cause activity so intermediaries are aware the connection is still in use.
+// Make sure these parameters are set in coordination with the keepalive policy on the server,
+// as incompatible settings can result in closing of connection.
+type ClientParameters struct {
+ // After a duration of this time if the client doesn't see any activity it pings the server to see if the transport is still alive.
+ Time time.Duration // The current default value is infinity.
+ // After having pinged for keepalive check, the client waits for a duration of Timeout and if no activity is seen even after that
+ // the connection is closed.
+ Timeout time.Duration // The current default value is 20 seconds.
+ // If true, client runs keepalive checks even with no active RPCs.
+ PermitWithoutStream bool // false by default.
+}
+
+// ServerParameters is used to set keepalive and max-age parameters on the server-side.
+type ServerParameters struct {
+ // MaxConnectionIdle is a duration for the amount of time after which an idle connection would be closed by sending a GoAway.
+ // Idleness duration is defined since the most recent time the number of outstanding RPCs became zero or the connection establishment.
+ MaxConnectionIdle time.Duration // The current default value is infinity.
+ // MaxConnectionAge is a duration for the maximum amount of time a connection may exist before it will be closed by sending a GoAway.
+ // A random jitter of +/-10% will be added to MaxConnectionAge to spread out connection storms.
+ MaxConnectionAge time.Duration // The current default value is infinity.
+ // MaxConnectinoAgeGrace is an additive period after MaxConnectionAge after which the connection will be forcibly closed.
+ MaxConnectionAgeGrace time.Duration // The current default value is infinity.
+ // After a duration of this time if the server doesn't see any activity it pings the client to see if the transport is still alive.
+ Time time.Duration // The current default value is 2 hours.
+ // After having pinged for keepalive check, the server waits for a duration of Timeout and if no activity is seen even after that
+ // the connection is closed.
+ Timeout time.Duration // The current default value is 20 seconds.
+}
+
+// EnforcementPolicy is used to set keepalive enforcement policy on the server-side.
+// Server will close connection with a client that violates this policy.
+type EnforcementPolicy struct {
+ // MinTime is the minimum amount of time a client should wait before sending a keepalive ping.
+ MinTime time.Duration // The current default value is 5 minutes.
+ // If true, server expects keepalive pings even when there are no active streams(RPCs).
+ PermitWithoutStream bool // false by default.
+}
diff --git a/vendor/google.golang.org/grpc/metadata/metadata.go b/vendor/google.golang.org/grpc/metadata/metadata.go
new file mode 100644
index 0000000..5395ca8
--- /dev/null
+++ b/vendor/google.golang.org/grpc/metadata/metadata.go
@@ -0,0 +1,144 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+// Package metadata define the structure of the metadata supported by gRPC library.
+// Please refer to http://www.grpc.io/docs/guides/wire.html for more information about custom-metadata.
+package metadata // import "google.golang.org/grpc/metadata"
+
+import (
+ "fmt"
+ "strings"
+
+ "golang.org/x/net/context"
+)
+
+// DecodeKeyValue returns k, v, nil. It is deprecated and should not be used.
+func DecodeKeyValue(k, v string) (string, string, error) {
+ return k, v, nil
+}
+
+// MD is a mapping from metadata keys to values. Users should use the following
+// two convenience functions New and Pairs to generate MD.
+type MD map[string][]string
+
+// New creates a MD from given key-value map.
+// Keys are automatically converted to lowercase.
+func New(m map[string]string) MD {
+ md := MD{}
+ for k, val := range m {
+ key := strings.ToLower(k)
+ md[key] = append(md[key], val)
+ }
+ return md
+}
+
+// Pairs returns an MD formed by the mapping of key, value ...
+// Pairs panics if len(kv) is odd.
+// Keys are automatically converted to lowercase.
+func Pairs(kv ...string) MD {
+ if len(kv)%2 == 1 {
+ panic(fmt.Sprintf("metadata: Pairs got the odd number of input pairs for metadata: %d", len(kv)))
+ }
+ md := MD{}
+ var key string
+ for i, s := range kv {
+ if i%2 == 0 {
+ key = strings.ToLower(s)
+ continue
+ }
+ md[key] = append(md[key], s)
+ }
+ return md
+}
+
+// Len returns the number of items in md.
+func (md MD) Len() int {
+ return len(md)
+}
+
+// Copy returns a copy of md.
+func (md MD) Copy() MD {
+ return Join(md)
+}
+
+// Join joins any number of MDs into a single MD.
+// The order of values for each key is determined by the order in which
+// the MDs containing those values are presented to Join.
+func Join(mds ...MD) MD {
+ out := MD{}
+ for _, md := range mds {
+ for k, v := range md {
+ out[k] = append(out[k], v...)
+ }
+ }
+ return out
+}
+
+type mdIncomingKey struct{}
+type mdOutgoingKey struct{}
+
+// NewContext is a wrapper for NewOutgoingContext(ctx, md). Deprecated.
+func NewContext(ctx context.Context, md MD) context.Context {
+ return NewOutgoingContext(ctx, md)
+}
+
+// NewIncomingContext creates a new context with incoming md attached.
+func NewIncomingContext(ctx context.Context, md MD) context.Context {
+ return context.WithValue(ctx, mdIncomingKey{}, md)
+}
+
+// NewOutgoingContext creates a new context with outgoing md attached.
+func NewOutgoingContext(ctx context.Context, md MD) context.Context {
+ return context.WithValue(ctx, mdOutgoingKey{}, md)
+}
+
+// FromContext is a wrapper for FromIncomingContext(ctx). Deprecated.
+func FromContext(ctx context.Context) (md MD, ok bool) {
+ return FromIncomingContext(ctx)
+}
+
+// FromIncomingContext returns the incoming MD in ctx if it exists. The
+// returned md should be immutable, writing to it may cause races.
+// Modification should be made to the copies of the returned md.
+func FromIncomingContext(ctx context.Context) (md MD, ok bool) {
+ md, ok = ctx.Value(mdIncomingKey{}).(MD)
+ return
+}
+
+// FromOutgoingContext returns the outgoing MD in ctx if it exists. The
+// returned md should be immutable, writing to it may cause races.
+// Modification should be made to the copies of the returned md.
+func FromOutgoingContext(ctx context.Context) (md MD, ok bool) {
+ md, ok = ctx.Value(mdOutgoingKey{}).(MD)
+ return
+}
diff --git a/vendor/google.golang.org/grpc/naming/naming.go b/vendor/google.golang.org/grpc/naming/naming.go
new file mode 100644
index 0000000..c2e0871
--- /dev/null
+++ b/vendor/google.golang.org/grpc/naming/naming.go
@@ -0,0 +1,74 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+// Package naming defines the naming API and related data structures for gRPC.
+// The interface is EXPERIMENTAL and may be suject to change.
+package naming
+
+// Operation defines the corresponding operations for a name resolution change.
+type Operation uint8
+
+const (
+ // Add indicates a new address is added.
+ Add Operation = iota
+ // Delete indicates an exisiting address is deleted.
+ Delete
+)
+
+// Update defines a name resolution update. Notice that it is not valid having both
+// empty string Addr and nil Metadata in an Update.
+type Update struct {
+ // Op indicates the operation of the update.
+ Op Operation
+ // Addr is the updated address. It is empty string if there is no address update.
+ Addr string
+ // Metadata is the updated metadata. It is nil if there is no metadata update.
+ // Metadata is not required for a custom naming implementation.
+ Metadata interface{}
+}
+
+// Resolver creates a Watcher for a target to track its resolution changes.
+type Resolver interface {
+ // Resolve creates a Watcher for target.
+ Resolve(target string) (Watcher, error)
+}
+
+// Watcher watches for the updates on the specified target.
+type Watcher interface {
+ // Next blocks until an update or error happens. It may return one or more
+ // updates. The first call should get the full set of the results. It should
+ // return an error if and only if Watcher cannot recover.
+ Next() ([]*Update, error)
+ // Close closes the Watcher.
+ Close()
+}
diff --git a/vendor/google.golang.org/grpc/peer/peer.go b/vendor/google.golang.org/grpc/peer/peer.go
new file mode 100644
index 0000000..bfa6205
--- /dev/null
+++ b/vendor/google.golang.org/grpc/peer/peer.go
@@ -0,0 +1,65 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+// Package peer defines various peer information associated with RPCs and
+// corresponding utils.
+package peer
+
+import (
+ "net"
+
+ "golang.org/x/net/context"
+ "google.golang.org/grpc/credentials"
+)
+
+// Peer contains the information of the peer for an RPC.
+type Peer struct {
+ // Addr is the peer address.
+ Addr net.Addr
+ // AuthInfo is the authentication information of the transport.
+ // It is nil if there is no transport security being used.
+ AuthInfo credentials.AuthInfo
+}
+
+type peerKey struct{}
+
+// NewContext creates a new context with peer information attached.
+func NewContext(ctx context.Context, p *Peer) context.Context {
+ return context.WithValue(ctx, peerKey{}, p)
+}
+
+// FromContext returns the peer information in ctx if it exists.
+func FromContext(ctx context.Context) (p *Peer, ok bool) {
+ p, ok = ctx.Value(peerKey{}).(*Peer)
+ return
+}
diff --git a/vendor/google.golang.org/grpc/proxy.go b/vendor/google.golang.org/grpc/proxy.go
new file mode 100644
index 0000000..10188dc
--- /dev/null
+++ b/vendor/google.golang.org/grpc/proxy.go
@@ -0,0 +1,145 @@
+/*
+ *
+ * Copyright 2017, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+
+ "golang.org/x/net/context"
+)
+
+var (
+ // errDisabled indicates that proxy is disabled for the address.
+ errDisabled = errors.New("proxy is disabled for the address")
+ // The following variable will be overwritten in the tests.
+ httpProxyFromEnvironment = http.ProxyFromEnvironment
+)
+
+func mapAddress(ctx context.Context, address string) (string, error) {
+ req := &http.Request{
+ URL: &url.URL{
+ Scheme: "https",
+ Host: address,
+ },
+ }
+ url, err := httpProxyFromEnvironment(req)
+ if err != nil {
+ return "", err
+ }
+ if url == nil {
+ return "", errDisabled
+ }
+ return url.Host, nil
+}
+
+// To read a response from a net.Conn, http.ReadResponse() takes a bufio.Reader.
+// It's possible that this reader reads more than what's need for the response and stores
+// those bytes in the buffer.
+// bufConn wraps the original net.Conn and the bufio.Reader to make sure we don't lose the
+// bytes in the buffer.
+type bufConn struct {
+ net.Conn
+ r io.Reader
+}
+
+func (c *bufConn) Read(b []byte) (int, error) {
+ return c.r.Read(b)
+}
+
+func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, addr string) (_ net.Conn, err error) {
+ defer func() {
+ if err != nil {
+ conn.Close()
+ }
+ }()
+
+ req := (&http.Request{
+ Method: http.MethodConnect,
+ URL: &url.URL{Host: addr},
+ Header: map[string][]string{"User-Agent": {grpcUA}},
+ })
+
+ if err := sendHTTPRequest(ctx, req, conn); err != nil {
+ return nil, fmt.Errorf("failed to write the HTTP request: %v", err)
+ }
+
+ r := bufio.NewReader(conn)
+ resp, err := http.ReadResponse(r, req)
+ if err != nil {
+ return nil, fmt.Errorf("reading server HTTP response: %v", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ dump, err := httputil.DumpResponse(resp, true)
+ if err != nil {
+ return nil, fmt.Errorf("failed to do connect handshake, status code: %s", resp.Status)
+ }
+ return nil, fmt.Errorf("failed to do connect handshake, response: %q", dump)
+ }
+
+ return &bufConn{Conn: conn, r: r}, nil
+}
+
+// newProxyDialer returns a dialer that connects to proxy first if necessary.
+// The returned dialer checks if a proxy is necessary, dial to the proxy with the
+// provided dialer, does HTTP CONNECT handshake and returns the connection.
+func newProxyDialer(dialer func(context.Context, string) (net.Conn, error)) func(context.Context, string) (net.Conn, error) {
+ return func(ctx context.Context, addr string) (conn net.Conn, err error) {
+ var skipHandshake bool
+ newAddr, err := mapAddress(ctx, addr)
+ if err != nil {
+ if err != errDisabled {
+ return nil, err
+ }
+ skipHandshake = true
+ newAddr = addr
+ }
+
+ conn, err = dialer(ctx, newAddr)
+ if err != nil {
+ return
+ }
+ if !skipHandshake {
+ conn, err = doHTTPConnectHandshake(ctx, conn, addr)
+ }
+ return
+ }
+}
diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go
new file mode 100644
index 0000000..34e1ad0
--- /dev/null
+++ b/vendor/google.golang.org/grpc/rpc_util.go
@@ -0,0 +1,501 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "bytes"
+ "compress/gzip"
+ "encoding/binary"
+ "io"
+ "io/ioutil"
+ "math"
+ "os"
+ "time"
+
+ "golang.org/x/net/context"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/peer"
+ "google.golang.org/grpc/stats"
+ "google.golang.org/grpc/status"
+ "google.golang.org/grpc/transport"
+)
+
+// Compressor defines the interface gRPC uses to compress a message.
+type Compressor interface {
+ // Do compresses p into w.
+ Do(w io.Writer, p []byte) error
+ // Type returns the compression algorithm the Compressor uses.
+ Type() string
+}
+
+// NewGZIPCompressor creates a Compressor based on GZIP.
+func NewGZIPCompressor() Compressor {
+ return &gzipCompressor{}
+}
+
+type gzipCompressor struct {
+}
+
+func (c *gzipCompressor) Do(w io.Writer, p []byte) error {
+ z := gzip.NewWriter(w)
+ if _, err := z.Write(p); err != nil {
+ return err
+ }
+ return z.Close()
+}
+
+func (c *gzipCompressor) Type() string {
+ return "gzip"
+}
+
+// Decompressor defines the interface gRPC uses to decompress a message.
+type Decompressor interface {
+ // Do reads the data from r and uncompress them.
+ Do(r io.Reader) ([]byte, error)
+ // Type returns the compression algorithm the Decompressor uses.
+ Type() string
+}
+
+type gzipDecompressor struct {
+}
+
+// NewGZIPDecompressor creates a Decompressor based on GZIP.
+func NewGZIPDecompressor() Decompressor {
+ return &gzipDecompressor{}
+}
+
+func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) {
+ z, err := gzip.NewReader(r)
+ if err != nil {
+ return nil, err
+ }
+ defer z.Close()
+ return ioutil.ReadAll(z)
+}
+
+func (d *gzipDecompressor) Type() string {
+ return "gzip"
+}
+
+// callInfo contains all related configuration and information about an RPC.
+type callInfo struct {
+ failFast bool
+ headerMD metadata.MD
+ trailerMD metadata.MD
+ peer *peer.Peer
+ traceInfo traceInfo // in trace.go
+}
+
+var defaultCallInfo = callInfo{failFast: true}
+
+// CallOption configures a Call before it starts or extracts information from
+// a Call after it completes.
+type CallOption interface {
+ // before is called before the call is sent to any server. If before
+ // returns a non-nil error, the RPC fails with that error.
+ before(*callInfo) error
+
+ // after is called after the call has completed. after cannot return an
+ // error, so any failures should be reported via output parameters.
+ after(*callInfo)
+}
+
+type beforeCall func(c *callInfo) error
+
+func (o beforeCall) before(c *callInfo) error { return o(c) }
+func (o beforeCall) after(c *callInfo) {}
+
+type afterCall func(c *callInfo)
+
+func (o afterCall) before(c *callInfo) error { return nil }
+func (o afterCall) after(c *callInfo) { o(c) }
+
+// Header returns a CallOptions that retrieves the header metadata
+// for a unary RPC.
+func Header(md *metadata.MD) CallOption {
+ return afterCall(func(c *callInfo) {
+ *md = c.headerMD
+ })
+}
+
+// Trailer returns a CallOptions that retrieves the trailer metadata
+// for a unary RPC.
+func Trailer(md *metadata.MD) CallOption {
+ return afterCall(func(c *callInfo) {
+ *md = c.trailerMD
+ })
+}
+
+// Peer returns a CallOption that retrieves peer information for a
+// unary RPC.
+func Peer(peer *peer.Peer) CallOption {
+ return afterCall(func(c *callInfo) {
+ if c.peer != nil {
+ *peer = *c.peer
+ }
+ })
+}
+
+// FailFast configures the action to take when an RPC is attempted on broken
+// connections or unreachable servers. If failfast is true, the RPC will fail
+// immediately. Otherwise, the RPC client will block the call until a
+// connection is available (or the call is canceled or times out) and will retry
+// the call if it fails due to a transient error. Please refer to
+// https://github.com/grpc/grpc/blob/master/doc/fail_fast.md. Note: failFast is default to true.
+func FailFast(failFast bool) CallOption {
+ return beforeCall(func(c *callInfo) error {
+ c.failFast = failFast
+ return nil
+ })
+}
+
+// The format of the payload: compressed or not?
+type payloadFormat uint8
+
+const (
+ compressionNone payloadFormat = iota // no compression
+ compressionMade
+)
+
+// parser reads complete gRPC messages from the underlying reader.
+type parser struct {
+ // r is the underlying reader.
+ // See the comment on recvMsg for the permissible
+ // error types.
+ r io.Reader
+
+ // The header of a gRPC message. Find more detail
+ // at http://www.grpc.io/docs/guides/wire.html.
+ header [5]byte
+}
+
+// recvMsg reads a complete gRPC message from the stream.
+//
+// It returns the message and its payload (compression/encoding)
+// format. The caller owns the returned msg memory.
+//
+// If there is an error, possible values are:
+// * io.EOF, when no messages remain
+// * io.ErrUnexpectedEOF
+// * of type transport.ConnectionError
+// * of type transport.StreamError
+// No other error values or types must be returned, which also means
+// that the underlying io.Reader must not return an incompatible
+// error.
+func (p *parser) recvMsg(maxMsgSize int) (pf payloadFormat, msg []byte, err error) {
+ if _, err := io.ReadFull(p.r, p.header[:]); err != nil {
+ return 0, nil, err
+ }
+
+ pf = payloadFormat(p.header[0])
+ length := binary.BigEndian.Uint32(p.header[1:])
+
+ if length == 0 {
+ return pf, nil, nil
+ }
+ if length > uint32(maxMsgSize) {
+ return 0, nil, Errorf(codes.Internal, "grpc: received message length %d exceeding the max size %d", length, maxMsgSize)
+ }
+ // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead
+ // of making it for each message:
+ msg = make([]byte, int(length))
+ if _, err := io.ReadFull(p.r, msg); err != nil {
+ if err == io.EOF {
+ err = io.ErrUnexpectedEOF
+ }
+ return 0, nil, err
+ }
+ return pf, msg, nil
+}
+
+// encode serializes msg and prepends the message header. If msg is nil, it
+// generates the message header of 0 message length.
+func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer, outPayload *stats.OutPayload) ([]byte, error) {
+ var (
+ b []byte
+ length uint
+ )
+ if msg != nil {
+ var err error
+ // TODO(zhaoq): optimize to reduce memory alloc and copying.
+ b, err = c.Marshal(msg)
+ if err != nil {
+ return nil, err
+ }
+ if outPayload != nil {
+ outPayload.Payload = msg
+ // TODO truncate large payload.
+ outPayload.Data = b
+ outPayload.Length = len(b)
+ }
+ if cp != nil {
+ if err := cp.Do(cbuf, b); err != nil {
+ return nil, err
+ }
+ b = cbuf.Bytes()
+ }
+ length = uint(len(b))
+ }
+ if length > math.MaxUint32 {
+ return nil, Errorf(codes.InvalidArgument, "grpc: message too large (%d bytes)", length)
+ }
+
+ const (
+ payloadLen = 1
+ sizeLen = 4
+ )
+
+ var buf = make([]byte, payloadLen+sizeLen+len(b))
+
+ // Write payload format
+ if cp == nil {
+ buf[0] = byte(compressionNone)
+ } else {
+ buf[0] = byte(compressionMade)
+ }
+ // Write length of b into buf
+ binary.BigEndian.PutUint32(buf[1:], uint32(length))
+ // Copy encoded msg to buf
+ copy(buf[5:], b)
+
+ if outPayload != nil {
+ outPayload.WireLength = len(buf)
+ }
+
+ return buf, nil
+}
+
+func checkRecvPayload(pf payloadFormat, recvCompress string, dc Decompressor) error {
+ switch pf {
+ case compressionNone:
+ case compressionMade:
+ if dc == nil || recvCompress != dc.Type() {
+ return Errorf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress)
+ }
+ default:
+ return Errorf(codes.Internal, "grpc: received unexpected payload format %d", pf)
+ }
+ return nil
+}
+
+func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{}, maxMsgSize int, inPayload *stats.InPayload) error {
+ pf, d, err := p.recvMsg(maxMsgSize)
+ if err != nil {
+ return err
+ }
+ if inPayload != nil {
+ inPayload.WireLength = len(d)
+ }
+ if err := checkRecvPayload(pf, s.RecvCompress(), dc); err != nil {
+ return err
+ }
+ if pf == compressionMade {
+ d, err = dc.Do(bytes.NewReader(d))
+ if err != nil {
+ return Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err)
+ }
+ }
+ if len(d) > maxMsgSize {
+ // TODO: Revisit the error code. Currently keep it consistent with java
+ // implementation.
+ return Errorf(codes.Internal, "grpc: received a message of %d bytes exceeding %d limit", len(d), maxMsgSize)
+ }
+ if err := c.Unmarshal(d, m); err != nil {
+ return Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err)
+ }
+ if inPayload != nil {
+ inPayload.RecvTime = time.Now()
+ inPayload.Payload = m
+ // TODO truncate large payload.
+ inPayload.Data = d
+ inPayload.Length = len(d)
+ }
+ return nil
+}
+
+type rpcInfo struct {
+ bytesSent bool
+ bytesReceived bool
+}
+
+type rpcInfoContextKey struct{}
+
+func newContextWithRPCInfo(ctx context.Context) context.Context {
+ return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{})
+}
+
+func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) {
+ s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo)
+ return
+}
+
+func updateRPCInfoInContext(ctx context.Context, s rpcInfo) {
+ if ss, ok := rpcInfoFromContext(ctx); ok {
+ *ss = s
+ }
+ return
+}
+
+// Code returns the error code for err if it was produced by the rpc system.
+// Otherwise, it returns codes.Unknown.
+//
+// Deprecated; use status.FromError and Code method instead.
+func Code(err error) codes.Code {
+ if s, ok := status.FromError(err); ok {
+ return s.Code()
+ }
+ return codes.Unknown
+}
+
+// ErrorDesc returns the error description of err if it was produced by the rpc system.
+// Otherwise, it returns err.Error() or empty string when err is nil.
+//
+// Deprecated; use status.FromError and Message method instead.
+func ErrorDesc(err error) string {
+ if s, ok := status.FromError(err); ok {
+ return s.Message()
+ }
+ return err.Error()
+}
+
+// Errorf returns an error containing an error code and a description;
+// Errorf returns nil if c is OK.
+//
+// Deprecated; use status.Errorf instead.
+func Errorf(c codes.Code, format string, a ...interface{}) error {
+ return status.Errorf(c, format, a...)
+}
+
+// toRPCErr converts an error into an error from the status package.
+func toRPCErr(err error) error {
+ if _, ok := status.FromError(err); ok {
+ return err
+ }
+ switch e := err.(type) {
+ case transport.StreamError:
+ return status.Error(e.Code, e.Desc)
+ case transport.ConnectionError:
+ return status.Error(codes.Internal, e.Desc)
+ default:
+ switch err {
+ case context.DeadlineExceeded:
+ return status.Error(codes.DeadlineExceeded, err.Error())
+ case context.Canceled:
+ return status.Error(codes.Canceled, err.Error())
+ case ErrClientConnClosing:
+ return status.Error(codes.FailedPrecondition, err.Error())
+ }
+ }
+ return status.Error(codes.Unknown, err.Error())
+}
+
+// convertCode converts a standard Go error into its canonical code. Note that
+// this is only used to translate the error returned by the server applications.
+func convertCode(err error) codes.Code {
+ switch err {
+ case nil:
+ return codes.OK
+ case io.EOF:
+ return codes.OutOfRange
+ case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF:
+ return codes.FailedPrecondition
+ case os.ErrInvalid:
+ return codes.InvalidArgument
+ case context.Canceled:
+ return codes.Canceled
+ case context.DeadlineExceeded:
+ return codes.DeadlineExceeded
+ }
+ switch {
+ case os.IsExist(err):
+ return codes.AlreadyExists
+ case os.IsNotExist(err):
+ return codes.NotFound
+ case os.IsPermission(err):
+ return codes.PermissionDenied
+ }
+ return codes.Unknown
+}
+
+// MethodConfig defines the configuration recommended by the service providers for a
+// particular method.
+// This is EXPERIMENTAL and subject to change.
+type MethodConfig struct {
+ // WaitForReady indicates whether RPCs sent to this method should wait until
+ // the connection is ready by default (!failfast). The value specified via the
+ // gRPC client API will override the value set here.
+ WaitForReady bool
+ // Timeout is the default timeout for RPCs sent to this method. The actual
+ // deadline used will be the minimum of the value specified here and the value
+ // set by the application via the gRPC client API. If either one is not set,
+ // then the other will be used. If neither is set, then the RPC has no deadline.
+ Timeout time.Duration
+ // MaxReqSize is the maximum allowed payload size for an individual request in a
+ // stream (client->server) in bytes. The size which is measured is the serialized
+ // payload after per-message compression (but before stream compression) in bytes.
+ // The actual value used is the minumum of the value specified here and the value set
+ // by the application via the gRPC client API. If either one is not set, then the other
+ // will be used. If neither is set, then the built-in default is used.
+ // TODO: support this.
+ MaxReqSize uint32
+ // MaxRespSize is the maximum allowed payload size for an individual response in a
+ // stream (server->client) in bytes.
+ // TODO: support this.
+ MaxRespSize uint32
+}
+
+// ServiceConfig is provided by the service provider and contains parameters for how
+// clients that connect to the service should behave.
+// This is EXPERIMENTAL and subject to change.
+type ServiceConfig struct {
+ // LB is the load balancer the service providers recommends. The balancer specified
+ // via grpc.WithBalancer will override this.
+ LB Balancer
+ // Methods contains a map for the methods in this service.
+ Methods map[string]MethodConfig
+}
+
+// SupportPackageIsVersion4 is referenced from generated protocol buffer files
+// to assert that that code is compatible with this version of the grpc package.
+//
+// This constant may be renamed in the future if a change in the generated code
+// requires a synchronised update of grpc-go and protoc-gen-go. This constant
+// should not be referenced from any other code.
+const SupportPackageIsVersion4 = true
+
+// Version is the current grpc version.
+const Version = "1.3.0"
+
+const grpcUA = "grpc-go/" + Version
diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go
new file mode 100644
index 0000000..b15f71c
--- /dev/null
+++ b/vendor/google.golang.org/grpc/server.go
@@ -0,0 +1,1108 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "reflect"
+ "runtime"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/net/http2"
+ "golang.org/x/net/trace"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/grpclog"
+ "google.golang.org/grpc/internal"
+ "google.golang.org/grpc/keepalive"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/stats"
+ "google.golang.org/grpc/status"
+ "google.golang.org/grpc/tap"
+ "google.golang.org/grpc/transport"
+)
+
+type methodHandler func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error)
+
+// MethodDesc represents an RPC service's method specification.
+type MethodDesc struct {
+ MethodName string
+ Handler methodHandler
+}
+
+// ServiceDesc represents an RPC service's specification.
+type ServiceDesc struct {
+ ServiceName string
+ // The pointer to the service interface. Used to check whether the user
+ // provided implementation satisfies the interface requirements.
+ HandlerType interface{}
+ Methods []MethodDesc
+ Streams []StreamDesc
+ Metadata interface{}
+}
+
+// service consists of the information of the server serving this service and
+// the methods in this service.
+type service struct {
+ server interface{} // the server for service methods
+ md map[string]*MethodDesc
+ sd map[string]*StreamDesc
+ mdata interface{}
+}
+
+// Server is a gRPC server to serve RPC requests.
+type Server struct {
+ opts options
+
+ mu sync.Mutex // guards following
+ lis map[net.Listener]bool
+ conns map[io.Closer]bool
+ drain bool
+ ctx context.Context
+ cancel context.CancelFunc
+ // A CondVar to let GracefulStop() blocks until all the pending RPCs are finished
+ // and all the transport goes away.
+ cv *sync.Cond
+ m map[string]*service // service name -> service info
+ events trace.EventLog
+}
+
+type options struct {
+ creds credentials.TransportCredentials
+ codec Codec
+ cp Compressor
+ dc Decompressor
+ maxMsgSize int
+ unaryInt UnaryServerInterceptor
+ streamInt StreamServerInterceptor
+ inTapHandle tap.ServerInHandle
+ statsHandler stats.Handler
+ maxConcurrentStreams uint32
+ useHandlerImpl bool // use http.Handler-based server
+ unknownStreamDesc *StreamDesc
+ keepaliveParams keepalive.ServerParameters
+ keepalivePolicy keepalive.EnforcementPolicy
+}
+
+var defaultMaxMsgSize = 1024 * 1024 * 4 // use 4MB as the default message size limit
+
+// A ServerOption sets options.
+type ServerOption func(*options)
+
+// KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server.
+func KeepaliveParams(kp keepalive.ServerParameters) ServerOption {
+ return func(o *options) {
+ o.keepaliveParams = kp
+ }
+}
+
+// KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server.
+func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption {
+ return func(o *options) {
+ o.keepalivePolicy = kep
+ }
+}
+
+// CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
+func CustomCodec(codec Codec) ServerOption {
+ return func(o *options) {
+ o.codec = codec
+ }
+}
+
+// RPCCompressor returns a ServerOption that sets a compressor for outbound messages.
+func RPCCompressor(cp Compressor) ServerOption {
+ return func(o *options) {
+ o.cp = cp
+ }
+}
+
+// RPCDecompressor returns a ServerOption that sets a decompressor for inbound messages.
+func RPCDecompressor(dc Decompressor) ServerOption {
+ return func(o *options) {
+ o.dc = dc
+ }
+}
+
+// MaxMsgSize returns a ServerOption to set the max message size in bytes for inbound mesages.
+// If this is not set, gRPC uses the default 4MB.
+func MaxMsgSize(m int) ServerOption {
+ return func(o *options) {
+ o.maxMsgSize = m
+ }
+}
+
+// MaxConcurrentStreams returns a ServerOption that will apply a limit on the number
+// of concurrent streams to each ServerTransport.
+func MaxConcurrentStreams(n uint32) ServerOption {
+ return func(o *options) {
+ o.maxConcurrentStreams = n
+ }
+}
+
+// Creds returns a ServerOption that sets credentials for server connections.
+func Creds(c credentials.TransportCredentials) ServerOption {
+ return func(o *options) {
+ o.creds = c
+ }
+}
+
+// UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the
+// server. Only one unary interceptor can be installed. The construction of multiple
+// interceptors (e.g., chaining) can be implemented at the caller.
+func UnaryInterceptor(i UnaryServerInterceptor) ServerOption {
+ return func(o *options) {
+ if o.unaryInt != nil {
+ panic("The unary server interceptor has been set.")
+ }
+ o.unaryInt = i
+ }
+}
+
+// StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the
+// server. Only one stream interceptor can be installed.
+func StreamInterceptor(i StreamServerInterceptor) ServerOption {
+ return func(o *options) {
+ if o.streamInt != nil {
+ panic("The stream server interceptor has been set.")
+ }
+ o.streamInt = i
+ }
+}
+
+// InTapHandle returns a ServerOption that sets the tap handle for all the server
+// transport to be created. Only one can be installed.
+func InTapHandle(h tap.ServerInHandle) ServerOption {
+ return func(o *options) {
+ if o.inTapHandle != nil {
+ panic("The tap handle has been set.")
+ }
+ o.inTapHandle = h
+ }
+}
+
+// StatsHandler returns a ServerOption that sets the stats handler for the server.
+func StatsHandler(h stats.Handler) ServerOption {
+ return func(o *options) {
+ o.statsHandler = h
+ }
+}
+
+// UnknownServiceHandler returns a ServerOption that allows for adding a custom
+// unknown service handler. The provided method is a bidi-streaming RPC service
+// handler that will be invoked instead of returning the the "unimplemented" gRPC
+// error whenever a request is received for an unregistered service or method.
+// The handling function has full access to the Context of the request and the
+// stream, and the invocation passes through interceptors.
+func UnknownServiceHandler(streamHandler StreamHandler) ServerOption {
+ return func(o *options) {
+ o.unknownStreamDesc = &StreamDesc{
+ StreamName: "unknown_service_handler",
+ Handler: streamHandler,
+ // We need to assume that the users of the streamHandler will want to use both.
+ ClientStreams: true,
+ ServerStreams: true,
+ }
+ }
+}
+
+// NewServer creates a gRPC server which has no service registered and has not
+// started to accept requests yet.
+func NewServer(opt ...ServerOption) *Server {
+ var opts options
+ opts.maxMsgSize = defaultMaxMsgSize
+ for _, o := range opt {
+ o(&opts)
+ }
+ if opts.codec == nil {
+ // Set the default codec.
+ opts.codec = protoCodec{}
+ }
+ s := &Server{
+ lis: make(map[net.Listener]bool),
+ opts: opts,
+ conns: make(map[io.Closer]bool),
+ m: make(map[string]*service),
+ }
+ s.cv = sync.NewCond(&s.mu)
+ s.ctx, s.cancel = context.WithCancel(context.Background())
+ if EnableTracing {
+ _, file, line, _ := runtime.Caller(1)
+ s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line))
+ }
+ return s
+}
+
+// printf records an event in s's event log, unless s has been stopped.
+// REQUIRES s.mu is held.
+func (s *Server) printf(format string, a ...interface{}) {
+ if s.events != nil {
+ s.events.Printf(format, a...)
+ }
+}
+
+// errorf records an error in s's event log, unless s has been stopped.
+// REQUIRES s.mu is held.
+func (s *Server) errorf(format string, a ...interface{}) {
+ if s.events != nil {
+ s.events.Errorf(format, a...)
+ }
+}
+
+// RegisterService register a service and its implementation to the gRPC
+// server. Called from the IDL generated code. This must be called before
+// invoking Serve.
+func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) {
+ ht := reflect.TypeOf(sd.HandlerType).Elem()
+ st := reflect.TypeOf(ss)
+ if !st.Implements(ht) {
+ grpclog.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht)
+ }
+ s.register(sd, ss)
+}
+
+func (s *Server) register(sd *ServiceDesc, ss interface{}) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.printf("RegisterService(%q)", sd.ServiceName)
+ if _, ok := s.m[sd.ServiceName]; ok {
+ grpclog.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName)
+ }
+ srv := &service{
+ server: ss,
+ md: make(map[string]*MethodDesc),
+ sd: make(map[string]*StreamDesc),
+ mdata: sd.Metadata,
+ }
+ for i := range sd.Methods {
+ d := &sd.Methods[i]
+ srv.md[d.MethodName] = d
+ }
+ for i := range sd.Streams {
+ d := &sd.Streams[i]
+ srv.sd[d.StreamName] = d
+ }
+ s.m[sd.ServiceName] = srv
+}
+
+// MethodInfo contains the information of an RPC including its method name and type.
+type MethodInfo struct {
+ // Name is the method name only, without the service name or package name.
+ Name string
+ // IsClientStream indicates whether the RPC is a client streaming RPC.
+ IsClientStream bool
+ // IsServerStream indicates whether the RPC is a server streaming RPC.
+ IsServerStream bool
+}
+
+// ServiceInfo contains unary RPC method info, streaming RPC methid info and metadata for a service.
+type ServiceInfo struct {
+ Methods []MethodInfo
+ // Metadata is the metadata specified in ServiceDesc when registering service.
+ Metadata interface{}
+}
+
+// GetServiceInfo returns a map from service names to ServiceInfo.
+// Service names include the package names, in the form of <package>.<service>.
+func (s *Server) GetServiceInfo() map[string]ServiceInfo {
+ ret := make(map[string]ServiceInfo)
+ for n, srv := range s.m {
+ methods := make([]MethodInfo, 0, len(srv.md)+len(srv.sd))
+ for m := range srv.md {
+ methods = append(methods, MethodInfo{
+ Name: m,
+ IsClientStream: false,
+ IsServerStream: false,
+ })
+ }
+ for m, d := range srv.sd {
+ methods = append(methods, MethodInfo{
+ Name: m,
+ IsClientStream: d.ClientStreams,
+ IsServerStream: d.ServerStreams,
+ })
+ }
+
+ ret[n] = ServiceInfo{
+ Methods: methods,
+ Metadata: srv.mdata,
+ }
+ }
+ return ret
+}
+
+var (
+ // ErrServerStopped indicates that the operation is now illegal because of
+ // the server being stopped.
+ ErrServerStopped = errors.New("grpc: the server has been stopped")
+)
+
+func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
+ if s.opts.creds == nil {
+ return rawConn, nil, nil
+ }
+ return s.opts.creds.ServerHandshake(rawConn)
+}
+
+// Serve accepts incoming connections on the listener lis, creating a new
+// ServerTransport and service goroutine for each. The service goroutines
+// read gRPC requests and then call the registered handlers to reply to them.
+// Serve returns when lis.Accept fails with fatal errors. lis will be closed when
+// this method returns.
+// Serve always returns non-nil error.
+func (s *Server) Serve(lis net.Listener) error {
+ s.mu.Lock()
+ s.printf("serving")
+ if s.lis == nil {
+ s.mu.Unlock()
+ lis.Close()
+ return ErrServerStopped
+ }
+ s.lis[lis] = true
+ s.mu.Unlock()
+ defer func() {
+ s.mu.Lock()
+ if s.lis != nil && s.lis[lis] {
+ lis.Close()
+ delete(s.lis, lis)
+ }
+ s.mu.Unlock()
+ }()
+
+ var tempDelay time.Duration // how long to sleep on accept failure
+
+ for {
+ rawConn, err := lis.Accept()
+ if err != nil {
+ if ne, ok := err.(interface {
+ Temporary() bool
+ }); ok && ne.Temporary() {
+ if tempDelay == 0 {
+ tempDelay = 5 * time.Millisecond
+ } else {
+ tempDelay *= 2
+ }
+ if max := 1 * time.Second; tempDelay > max {
+ tempDelay = max
+ }
+ s.mu.Lock()
+ s.printf("Accept error: %v; retrying in %v", err, tempDelay)
+ s.mu.Unlock()
+ select {
+ case <-time.After(tempDelay):
+ case <-s.ctx.Done():
+ }
+ continue
+ }
+ s.mu.Lock()
+ s.printf("done serving; Accept = %v", err)
+ s.mu.Unlock()
+ return err
+ }
+ tempDelay = 0
+ // Start a new goroutine to deal with rawConn
+ // so we don't stall this Accept loop goroutine.
+ go s.handleRawConn(rawConn)
+ }
+}
+
+// handleRawConn is run in its own goroutine and handles a just-accepted
+// connection that has not had any I/O performed on it yet.
+func (s *Server) handleRawConn(rawConn net.Conn) {
+ conn, authInfo, err := s.useTransportAuthenticator(rawConn)
+ if err != nil {
+ s.mu.Lock()
+ s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
+ s.mu.Unlock()
+ grpclog.Printf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
+ // If serverHandShake returns ErrConnDispatched, keep rawConn open.
+ if err != credentials.ErrConnDispatched {
+ rawConn.Close()
+ }
+ return
+ }
+
+ s.mu.Lock()
+ if s.conns == nil {
+ s.mu.Unlock()
+ conn.Close()
+ return
+ }
+ s.mu.Unlock()
+
+ if s.opts.useHandlerImpl {
+ s.serveUsingHandler(conn)
+ } else {
+ s.serveHTTP2Transport(conn, authInfo)
+ }
+}
+
+// serveHTTP2Transport sets up a http/2 transport (using the
+// gRPC http2 server transport in transport/http2_server.go) and
+// serves streams on it.
+// This is run in its own goroutine (it does network I/O in
+// transport.NewServerTransport).
+func (s *Server) serveHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) {
+ config := &transport.ServerConfig{
+ MaxStreams: s.opts.maxConcurrentStreams,
+ AuthInfo: authInfo,
+ InTapHandle: s.opts.inTapHandle,
+ StatsHandler: s.opts.statsHandler,
+ KeepaliveParams: s.opts.keepaliveParams,
+ KeepalivePolicy: s.opts.keepalivePolicy,
+ }
+ st, err := transport.NewServerTransport("http2", c, config)
+ if err != nil {
+ s.mu.Lock()
+ s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err)
+ s.mu.Unlock()
+ c.Close()
+ grpclog.Println("grpc: Server.Serve failed to create ServerTransport: ", err)
+ return
+ }
+ if !s.addConn(st) {
+ st.Close()
+ return
+ }
+ s.serveStreams(st)
+}
+
+func (s *Server) serveStreams(st transport.ServerTransport) {
+ defer s.removeConn(st)
+ defer st.Close()
+ var wg sync.WaitGroup
+ st.HandleStreams(func(stream *transport.Stream) {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ s.handleStream(st, stream, s.traceInfo(st, stream))
+ }()
+ }, func(ctx context.Context, method string) context.Context {
+ if !EnableTracing {
+ return ctx
+ }
+ tr := trace.New("grpc.Recv."+methodFamily(method), method)
+ return trace.NewContext(ctx, tr)
+ })
+ wg.Wait()
+}
+
+var _ http.Handler = (*Server)(nil)
+
+// serveUsingHandler is called from handleRawConn when s is configured
+// to handle requests via the http.Handler interface. It sets up a
+// net/http.Server to handle the just-accepted conn. The http.Server
+// is configured to route all incoming requests (all HTTP/2 streams)
+// to ServeHTTP, which creates a new ServerTransport for each stream.
+// serveUsingHandler blocks until conn closes.
+//
+// This codepath is only used when Server.TestingUseHandlerImpl has
+// been configured. This lets the end2end tests exercise the ServeHTTP
+// method as one of the environment types.
+//
+// conn is the *tls.Conn that's already been authenticated.
+func (s *Server) serveUsingHandler(conn net.Conn) {
+ if !s.addConn(conn) {
+ conn.Close()
+ return
+ }
+ defer s.removeConn(conn)
+ h2s := &http2.Server{
+ MaxConcurrentStreams: s.opts.maxConcurrentStreams,
+ }
+ h2s.ServeConn(conn, &http2.ServeConnOpts{
+ Handler: s,
+ })
+}
+
+func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ st, err := transport.NewServerHandlerTransport(w, r)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ if !s.addConn(st) {
+ st.Close()
+ return
+ }
+ defer s.removeConn(st)
+ s.serveStreams(st)
+}
+
+// traceInfo returns a traceInfo and associates it with stream, if tracing is enabled.
+// If tracing is not enabled, it returns nil.
+func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) {
+ tr, ok := trace.FromContext(stream.Context())
+ if !ok {
+ return nil
+ }
+
+ trInfo = &traceInfo{
+ tr: tr,
+ }
+ trInfo.firstLine.client = false
+ trInfo.firstLine.remoteAddr = st.RemoteAddr()
+
+ if dl, ok := stream.Context().Deadline(); ok {
+ trInfo.firstLine.deadline = dl.Sub(time.Now())
+ }
+ return trInfo
+}
+
+func (s *Server) addConn(c io.Closer) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.conns == nil || s.drain {
+ return false
+ }
+ s.conns[c] = true
+ return true
+}
+
+func (s *Server) removeConn(c io.Closer) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.conns != nil {
+ delete(s.conns, c)
+ s.cv.Broadcast()
+ }
+}
+
+func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options) error {
+ var (
+ cbuf *bytes.Buffer
+ outPayload *stats.OutPayload
+ )
+ if cp != nil {
+ cbuf = new(bytes.Buffer)
+ }
+ if s.opts.statsHandler != nil {
+ outPayload = &stats.OutPayload{}
+ }
+ p, err := encode(s.opts.codec, msg, cp, cbuf, outPayload)
+ if err != nil {
+ // This typically indicates a fatal issue (e.g., memory
+ // corruption or hardware faults) the application program
+ // cannot handle.
+ //
+ // TODO(zhaoq): There exist other options also such as only closing the
+ // faulty stream locally and remotely (Other streams can keep going). Find
+ // the optimal option.
+ grpclog.Fatalf("grpc: Server failed to encode response %v", err)
+ }
+ err = t.Write(stream, p, opts)
+ if err == nil && outPayload != nil {
+ outPayload.SentTime = time.Now()
+ s.opts.statsHandler.HandleRPC(stream.Context(), outPayload)
+ }
+ return err
+}
+
+func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) {
+ sh := s.opts.statsHandler
+ if sh != nil {
+ begin := &stats.Begin{
+ BeginTime: time.Now(),
+ }
+ sh.HandleRPC(stream.Context(), begin)
+ }
+ defer func() {
+ if sh != nil {
+ end := &stats.End{
+ EndTime: time.Now(),
+ }
+ if err != nil && err != io.EOF {
+ end.Error = toRPCErr(err)
+ }
+ sh.HandleRPC(stream.Context(), end)
+ }
+ }()
+ if trInfo != nil {
+ defer trInfo.tr.Finish()
+ trInfo.firstLine.client = false
+ trInfo.tr.LazyLog(&trInfo.firstLine, false)
+ defer func() {
+ if err != nil && err != io.EOF {
+ trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
+ trInfo.tr.SetError()
+ }
+ }()
+ }
+ if s.opts.cp != nil {
+ // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
+ stream.SetSendCompress(s.opts.cp.Type())
+ }
+ p := &parser{r: stream}
+ for { // TODO: delete
+ pf, req, err := p.recvMsg(s.opts.maxMsgSize)
+ if err == io.EOF {
+ // The entire stream is done (for unary RPC only).
+ return err
+ }
+ if err == io.ErrUnexpectedEOF {
+ err = Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
+ }
+ if err != nil {
+ if st, ok := status.FromError(err); ok {
+ if e := t.WriteStatus(stream, st); e != nil {
+ grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", e)
+ }
+ } else {
+ switch st := err.(type) {
+ case transport.ConnectionError:
+ // Nothing to do here.
+ case transport.StreamError:
+ if e := t.WriteStatus(stream, status.New(st.Code, st.Desc)); e != nil {
+ grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", e)
+ }
+ default:
+ panic(fmt.Sprintf("grpc: Unexpected error (%T) from recvMsg: %v", st, st))
+ }
+ }
+ return err
+ }
+
+ if err := checkRecvPayload(pf, stream.RecvCompress(), s.opts.dc); err != nil {
+ if st, ok := status.FromError(err); ok {
+ if e := t.WriteStatus(stream, st); e != nil {
+ grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", e)
+ }
+ return err
+ }
+ if e := t.WriteStatus(stream, status.New(codes.Internal, err.Error())); e != nil {
+ grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", e)
+ }
+
+ // TODO checkRecvPayload always return RPC error. Add a return here if necessary.
+ }
+ var inPayload *stats.InPayload
+ if sh != nil {
+ inPayload = &stats.InPayload{
+ RecvTime: time.Now(),
+ }
+ }
+ df := func(v interface{}) error {
+ if inPayload != nil {
+ inPayload.WireLength = len(req)
+ }
+ if pf == compressionMade {
+ var err error
+ req, err = s.opts.dc.Do(bytes.NewReader(req))
+ if err != nil {
+ return Errorf(codes.Internal, err.Error())
+ }
+ }
+ if len(req) > s.opts.maxMsgSize {
+ // TODO: Revisit the error code. Currently keep it consistent with
+ // java implementation.
+ return status.Errorf(codes.Internal, "grpc: server received a message of %d bytes exceeding %d limit", len(req), s.opts.maxMsgSize)
+ }
+ if err := s.opts.codec.Unmarshal(req, v); err != nil {
+ return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err)
+ }
+ if inPayload != nil {
+ inPayload.Payload = v
+ inPayload.Data = req
+ inPayload.Length = len(req)
+ sh.HandleRPC(stream.Context(), inPayload)
+ }
+ if trInfo != nil {
+ trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true)
+ }
+ return nil
+ }
+ reply, appErr := md.Handler(srv.server, stream.Context(), df, s.opts.unaryInt)
+ if appErr != nil {
+ appStatus, ok := status.FromError(appErr)
+ if !ok {
+ // Convert appErr if it is not a grpc status error.
+ appErr = status.Error(convertCode(appErr), appErr.Error())
+ appStatus, _ = status.FromError(appErr)
+ }
+ if trInfo != nil {
+ trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
+ trInfo.tr.SetError()
+ }
+ if e := t.WriteStatus(stream, appStatus); e != nil {
+ grpclog.Printf("grpc: Server.processUnaryRPC failed to write status: %v", e)
+ }
+ return appErr
+ }
+ if trInfo != nil {
+ trInfo.tr.LazyLog(stringer("OK"), false)
+ }
+ opts := &transport.Options{
+ Last: true,
+ Delay: false,
+ }
+ if err := s.sendResponse(t, stream, reply, s.opts.cp, opts); err != nil {
+ if err == io.EOF {
+ // The entire stream is done (for unary RPC only).
+ return err
+ }
+ if s, ok := status.FromError(err); ok {
+ if e := t.WriteStatus(stream, s); e != nil {
+ grpclog.Printf("grpc: Server.processUnaryRPC failed to write status: %v", e)
+ }
+ } else {
+ switch st := err.(type) {
+ case transport.ConnectionError:
+ // Nothing to do here.
+ case transport.StreamError:
+ if e := t.WriteStatus(stream, status.New(st.Code, st.Desc)); e != nil {
+ grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", e)
+ }
+ default:
+ panic(fmt.Sprintf("grpc: Unexpected error (%T) from sendResponse: %v", st, st))
+ }
+ }
+ return err
+ }
+ if trInfo != nil {
+ trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true)
+ }
+ // TODO: Should we be logging if writing status failed here, like above?
+ // Should the logging be in WriteStatus? Should we ignore the WriteStatus
+ // error or allow the stats handler to see it?
+ return t.WriteStatus(stream, status.New(codes.OK, ""))
+ }
+}
+
+func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) {
+ sh := s.opts.statsHandler
+ if sh != nil {
+ begin := &stats.Begin{
+ BeginTime: time.Now(),
+ }
+ sh.HandleRPC(stream.Context(), begin)
+ }
+ defer func() {
+ if sh != nil {
+ end := &stats.End{
+ EndTime: time.Now(),
+ }
+ if err != nil && err != io.EOF {
+ end.Error = toRPCErr(err)
+ }
+ sh.HandleRPC(stream.Context(), end)
+ }
+ }()
+ if s.opts.cp != nil {
+ stream.SetSendCompress(s.opts.cp.Type())
+ }
+ ss := &serverStream{
+ t: t,
+ s: stream,
+ p: &parser{r: stream},
+ codec: s.opts.codec,
+ cp: s.opts.cp,
+ dc: s.opts.dc,
+ maxMsgSize: s.opts.maxMsgSize,
+ trInfo: trInfo,
+ statsHandler: sh,
+ }
+ if ss.cp != nil {
+ ss.cbuf = new(bytes.Buffer)
+ }
+ if trInfo != nil {
+ trInfo.tr.LazyLog(&trInfo.firstLine, false)
+ defer func() {
+ ss.mu.Lock()
+ if err != nil && err != io.EOF {
+ ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
+ ss.trInfo.tr.SetError()
+ }
+ ss.trInfo.tr.Finish()
+ ss.trInfo.tr = nil
+ ss.mu.Unlock()
+ }()
+ }
+ var appErr error
+ var server interface{}
+ if srv != nil {
+ server = srv.server
+ }
+ if s.opts.streamInt == nil {
+ appErr = sd.Handler(server, ss)
+ } else {
+ info := &StreamServerInfo{
+ FullMethod: stream.Method(),
+ IsClientStream: sd.ClientStreams,
+ IsServerStream: sd.ServerStreams,
+ }
+ appErr = s.opts.streamInt(server, ss, info, sd.Handler)
+ }
+ if appErr != nil {
+ appStatus, ok := status.FromError(appErr)
+ if !ok {
+ switch err := appErr.(type) {
+ case transport.StreamError:
+ appStatus = status.New(err.Code, err.Desc)
+ default:
+ appStatus = status.New(convertCode(appErr), appErr.Error())
+ }
+ appErr = appStatus.Err()
+ }
+ if trInfo != nil {
+ ss.mu.Lock()
+ ss.trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
+ ss.trInfo.tr.SetError()
+ ss.mu.Unlock()
+ }
+ t.WriteStatus(ss.s, appStatus)
+ // TODO: Should we log an error from WriteStatus here and below?
+ return appErr
+ }
+ if trInfo != nil {
+ ss.mu.Lock()
+ ss.trInfo.tr.LazyLog(stringer("OK"), false)
+ ss.mu.Unlock()
+ }
+ return t.WriteStatus(ss.s, status.New(codes.OK, ""))
+
+}
+
+func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) {
+ sm := stream.Method()
+ if sm != "" && sm[0] == '/' {
+ sm = sm[1:]
+ }
+ pos := strings.LastIndex(sm, "/")
+ if pos == -1 {
+ if trInfo != nil {
+ trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true)
+ trInfo.tr.SetError()
+ }
+ errDesc := fmt.Sprintf("malformed method name: %q", stream.Method())
+ if err := t.WriteStatus(stream, status.New(codes.InvalidArgument, errDesc)); err != nil {
+ if trInfo != nil {
+ trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
+ trInfo.tr.SetError()
+ }
+ grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
+ }
+ if trInfo != nil {
+ trInfo.tr.Finish()
+ }
+ return
+ }
+ service := sm[:pos]
+ method := sm[pos+1:]
+ srv, ok := s.m[service]
+ if !ok {
+ if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil {
+ s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo)
+ return
+ }
+ if trInfo != nil {
+ trInfo.tr.LazyLog(&fmtStringer{"Unknown service %v", []interface{}{service}}, true)
+ trInfo.tr.SetError()
+ }
+ errDesc := fmt.Sprintf("unknown service %v", service)
+ if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
+ if trInfo != nil {
+ trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
+ trInfo.tr.SetError()
+ }
+ grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
+ }
+ if trInfo != nil {
+ trInfo.tr.Finish()
+ }
+ return
+ }
+ // Unary RPC or Streaming RPC?
+ if md, ok := srv.md[method]; ok {
+ s.processUnaryRPC(t, stream, srv, md, trInfo)
+ return
+ }
+ if sd, ok := srv.sd[method]; ok {
+ s.processStreamingRPC(t, stream, srv, sd, trInfo)
+ return
+ }
+ if trInfo != nil {
+ trInfo.tr.LazyLog(&fmtStringer{"Unknown method %v", []interface{}{method}}, true)
+ trInfo.tr.SetError()
+ }
+ if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil {
+ s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo)
+ return
+ }
+ errDesc := fmt.Sprintf("unknown method %v", method)
+ if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
+ if trInfo != nil {
+ trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
+ trInfo.tr.SetError()
+ }
+ grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
+ }
+ if trInfo != nil {
+ trInfo.tr.Finish()
+ }
+}
+
+// Stop stops the gRPC server. It immediately closes all open
+// connections and listeners.
+// It cancels all active RPCs on the server side and the corresponding
+// pending RPCs on the client side will get notified by connection
+// errors.
+func (s *Server) Stop() {
+ s.mu.Lock()
+ listeners := s.lis
+ s.lis = nil
+ st := s.conns
+ s.conns = nil
+ // interrupt GracefulStop if Stop and GracefulStop are called concurrently.
+ s.cv.Broadcast()
+ s.mu.Unlock()
+
+ for lis := range listeners {
+ lis.Close()
+ }
+ for c := range st {
+ c.Close()
+ }
+
+ s.mu.Lock()
+ s.cancel()
+ if s.events != nil {
+ s.events.Finish()
+ s.events = nil
+ }
+ s.mu.Unlock()
+}
+
+// GracefulStop stops the gRPC server gracefully. It stops the server to accept new
+// connections and RPCs and blocks until all the pending RPCs are finished.
+func (s *Server) GracefulStop() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.conns == nil {
+ return
+ }
+ for lis := range s.lis {
+ lis.Close()
+ }
+ s.lis = nil
+ s.cancel()
+ if !s.drain {
+ for c := range s.conns {
+ c.(transport.ServerTransport).Drain()
+ }
+ s.drain = true
+ }
+ for len(s.conns) != 0 {
+ s.cv.Wait()
+ }
+ s.conns = nil
+ if s.events != nil {
+ s.events.Finish()
+ s.events = nil
+ }
+}
+
+func init() {
+ internal.TestingCloseConns = func(arg interface{}) {
+ arg.(*Server).testingCloseConns()
+ }
+ internal.TestingUseHandlerImpl = func(arg interface{}) {
+ arg.(*Server).opts.useHandlerImpl = true
+ }
+}
+
+// testingCloseConns closes all existing transports but keeps s.lis
+// accepting new connections.
+func (s *Server) testingCloseConns() {
+ s.mu.Lock()
+ for c := range s.conns {
+ c.Close()
+ delete(s.conns, c)
+ }
+ s.mu.Unlock()
+}
+
+// SetHeader sets the header metadata.
+// When called multiple times, all the provided metadata will be merged.
+// All the metadata will be sent out when one of the following happens:
+// - grpc.SendHeader() is called;
+// - The first response is sent out;
+// - An RPC status is sent out (error or success).
+func SetHeader(ctx context.Context, md metadata.MD) error {
+ if md.Len() == 0 {
+ return nil
+ }
+ stream, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
+ }
+ return stream.SetHeader(md)
+}
+
+// SendHeader sends header metadata. It may be called at most once.
+// The provided md and headers set by SetHeader() will be sent.
+func SendHeader(ctx context.Context, md metadata.MD) error {
+ stream, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
+ }
+ t := stream.ServerTransport()
+ if t == nil {
+ grpclog.Fatalf("grpc: SendHeader: %v has no ServerTransport to send header metadata.", stream)
+ }
+ if err := t.WriteHeader(stream, md); err != nil {
+ return toRPCErr(err)
+ }
+ return nil
+}
+
+// SetTrailer sets the trailer metadata that will be sent when an RPC returns.
+// When called more than once, all the provided metadata will be merged.
+func SetTrailer(ctx context.Context, md metadata.MD) error {
+ if md.Len() == 0 {
+ return nil
+ }
+ stream, ok := transport.StreamFromContext(ctx)
+ if !ok {
+ return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
+ }
+ return stream.SetTrailer(md)
+}
diff --git a/vendor/google.golang.org/grpc/stats/handlers.go b/vendor/google.golang.org/grpc/stats/handlers.go
new file mode 100644
index 0000000..26e1a8e
--- /dev/null
+++ b/vendor/google.golang.org/grpc/stats/handlers.go
@@ -0,0 +1,76 @@
+/*
+ *
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+package stats
+
+import (
+ "net"
+
+ "golang.org/x/net/context"
+)
+
+// ConnTagInfo defines the relevant information needed by connection context tagger.
+type ConnTagInfo struct {
+ // RemoteAddr is the remote address of the corresponding connection.
+ RemoteAddr net.Addr
+ // LocalAddr is the local address of the corresponding connection.
+ LocalAddr net.Addr
+ // TODO add QOS related fields.
+}
+
+// RPCTagInfo defines the relevant information needed by RPC context tagger.
+type RPCTagInfo struct {
+ // FullMethodName is the RPC method in the format of /package.service/method.
+ FullMethodName string
+}
+
+// Handler defines the interface for the related stats handling (e.g., RPCs, connections).
+type Handler interface {
+ // TagRPC can attach some information to the given context.
+ // The returned context is used in the rest lifetime of the RPC.
+ TagRPC(context.Context, *RPCTagInfo) context.Context
+ // HandleRPC processes the RPC stats.
+ HandleRPC(context.Context, RPCStats)
+
+ // TagConn can attach some information to the given context.
+ // The returned context will be used for stats handling.
+ // For conn stats handling, the context used in HandleConn for this
+ // connection will be derived from the context returned.
+ // For RPC stats handling,
+ // - On server side, the context used in HandleRPC for all RPCs on this
+ // connection will be derived from the context returned.
+ // - On client side, the context is not derived from the context returned.
+ TagConn(context.Context, *ConnTagInfo) context.Context
+ // HandleConn processes the Conn stats.
+ HandleConn(context.Context, ConnStats)
+}
diff --git a/vendor/google.golang.org/grpc/stats/stats.go b/vendor/google.golang.org/grpc/stats/stats.go
new file mode 100644
index 0000000..43d6f00
--- /dev/null
+++ b/vendor/google.golang.org/grpc/stats/stats.go
@@ -0,0 +1,223 @@
+/*
+ *
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+// Package stats is for collecting and reporting various network and RPC stats.
+// This package is for monitoring purpose only. All fields are read-only.
+// All APIs are experimental.
+package stats // import "google.golang.org/grpc/stats"
+
+import (
+ "net"
+ "time"
+)
+
+// RPCStats contains stats information about RPCs.
+type RPCStats interface {
+ isRPCStats()
+ // IsClient returns true if this RPCStats is from client side.
+ IsClient() bool
+}
+
+// Begin contains stats when an RPC begins.
+// FailFast are only valid if Client is true.
+type Begin struct {
+ // Client is true if this Begin is from client side.
+ Client bool
+ // BeginTime is the time when the RPC begins.
+ BeginTime time.Time
+ // FailFast indicates if this RPC is failfast.
+ FailFast bool
+}
+
+// IsClient indicates if this is from client side.
+func (s *Begin) IsClient() bool { return s.Client }
+
+func (s *Begin) isRPCStats() {}
+
+// InPayload contains the information for an incoming payload.
+type InPayload struct {
+ // Client is true if this InPayload is from client side.
+ Client bool
+ // Payload is the payload with original type.
+ Payload interface{}
+ // Data is the serialized message payload.
+ Data []byte
+ // Length is the length of uncompressed data.
+ Length int
+ // WireLength is the length of data on wire (compressed, signed, encrypted).
+ WireLength int
+ // RecvTime is the time when the payload is received.
+ RecvTime time.Time
+}
+
+// IsClient indicates if this is from client side.
+func (s *InPayload) IsClient() bool { return s.Client }
+
+func (s *InPayload) isRPCStats() {}
+
+// InHeader contains stats when a header is received.
+// FullMethod, addresses and Compression are only valid if Client is false.
+type InHeader struct {
+ // Client is true if this InHeader is from client side.
+ Client bool
+ // WireLength is the wire length of header.
+ WireLength int
+
+ // FullMethod is the full RPC method string, i.e., /package.service/method.
+ FullMethod string
+ // RemoteAddr is the remote address of the corresponding connection.
+ RemoteAddr net.Addr
+ // LocalAddr is the local address of the corresponding connection.
+ LocalAddr net.Addr
+ // Compression is the compression algorithm used for the RPC.
+ Compression string
+}
+
+// IsClient indicates if this is from client side.
+func (s *InHeader) IsClient() bool { return s.Client }
+
+func (s *InHeader) isRPCStats() {}
+
+// InTrailer contains stats when a trailer is received.
+type InTrailer struct {
+ // Client is true if this InTrailer is from client side.
+ Client bool
+ // WireLength is the wire length of trailer.
+ WireLength int
+}
+
+// IsClient indicates if this is from client side.
+func (s *InTrailer) IsClient() bool { return s.Client }
+
+func (s *InTrailer) isRPCStats() {}
+
+// OutPayload contains the information for an outgoing payload.
+type OutPayload struct {
+ // Client is true if this OutPayload is from client side.
+ Client bool
+ // Payload is the payload with original type.
+ Payload interface{}
+ // Data is the serialized message payload.
+ Data []byte
+ // Length is the length of uncompressed data.
+ Length int
+ // WireLength is the length of data on wire (compressed, signed, encrypted).
+ WireLength int
+ // SentTime is the time when the payload is sent.
+ SentTime time.Time
+}
+
+// IsClient indicates if this is from client side.
+func (s *OutPayload) IsClient() bool { return s.Client }
+
+func (s *OutPayload) isRPCStats() {}
+
+// OutHeader contains stats when a header is sent.
+// FullMethod, addresses and Compression are only valid if Client is true.
+type OutHeader struct {
+ // Client is true if this OutHeader is from client side.
+ Client bool
+ // WireLength is the wire length of header.
+ WireLength int
+
+ // FullMethod is the full RPC method string, i.e., /package.service/method.
+ FullMethod string
+ // RemoteAddr is the remote address of the corresponding connection.
+ RemoteAddr net.Addr
+ // LocalAddr is the local address of the corresponding connection.
+ LocalAddr net.Addr
+ // Compression is the compression algorithm used for the RPC.
+ Compression string
+}
+
+// IsClient indicates if this is from client side.
+func (s *OutHeader) IsClient() bool { return s.Client }
+
+func (s *OutHeader) isRPCStats() {}
+
+// OutTrailer contains stats when a trailer is sent.
+type OutTrailer struct {
+ // Client is true if this OutTrailer is from client side.
+ Client bool
+ // WireLength is the wire length of trailer.
+ WireLength int
+}
+
+// IsClient indicates if this is from client side.
+func (s *OutTrailer) IsClient() bool { return s.Client }
+
+func (s *OutTrailer) isRPCStats() {}
+
+// End contains stats when an RPC ends.
+type End struct {
+ // Client is true if this End is from client side.
+ Client bool
+ // EndTime is the time when the RPC ends.
+ EndTime time.Time
+ // Error is the error just happened. It implements status.Status if non-nil.
+ Error error
+}
+
+// IsClient indicates if this is from client side.
+func (s *End) IsClient() bool { return s.Client }
+
+func (s *End) isRPCStats() {}
+
+// ConnStats contains stats information about connections.
+type ConnStats interface {
+ isConnStats()
+ // IsClient returns true if this ConnStats is from client side.
+ IsClient() bool
+}
+
+// ConnBegin contains the stats of a connection when it is established.
+type ConnBegin struct {
+ // Client is true if this ConnBegin is from client side.
+ Client bool
+}
+
+// IsClient indicates if this is from client side.
+func (s *ConnBegin) IsClient() bool { return s.Client }
+
+func (s *ConnBegin) isConnStats() {}
+
+// ConnEnd contains the stats of a connection when it ends.
+type ConnEnd struct {
+ // Client is true if this ConnEnd is from client side.
+ Client bool
+}
+
+// IsClient indicates if this is from client side.
+func (s *ConnEnd) IsClient() bool { return s.Client }
+
+func (s *ConnEnd) isConnStats() {}
diff --git a/vendor/google.golang.org/grpc/status/status.go b/vendor/google.golang.org/grpc/status/status.go
new file mode 100644
index 0000000..99a4cbe
--- /dev/null
+++ b/vendor/google.golang.org/grpc/status/status.go
@@ -0,0 +1,145 @@
+/*
+ *
+ * Copyright 2017, Google Inc.
+ * 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.
+ *
+ */
+
+// Package status implements errors returned by gRPC. These errors are
+// serialized and transmitted on the wire between server and client, and allow
+// for additional data to be transmitted via the Details field in the status
+// proto. gRPC service handlers should return an error created by this
+// package, and gRPC clients should expect a corresponding error to be
+// returned from the RPC call.
+//
+// This package upholds the invariants that a non-nil error may not
+// contain an OK code, and an OK code must result in a nil error.
+package status
+
+import (
+ "fmt"
+
+ "github.com/golang/protobuf/proto"
+ spb "google.golang.org/genproto/googleapis/rpc/status"
+ "google.golang.org/grpc/codes"
+)
+
+// statusError is an alias of a status proto. It implements error and Status,
+// and a nil statusError should never be returned by this package.
+type statusError spb.Status
+
+func (se *statusError) Error() string {
+ p := (*spb.Status)(se)
+ return fmt.Sprintf("rpc error: code = %s desc = %s", codes.Code(p.GetCode()), p.GetMessage())
+}
+
+func (se *statusError) status() *Status {
+ return &Status{s: (*spb.Status)(se)}
+}
+
+// Status represents an RPC status code, message, and details. It is immutable
+// and should be created with New, Newf, or FromProto.
+type Status struct {
+ s *spb.Status
+}
+
+// Code returns the status code contained in s.
+func (s *Status) Code() codes.Code {
+ if s == nil || s.s == nil {
+ return codes.OK
+ }
+ return codes.Code(s.s.Code)
+}
+
+// Message returns the message contained in s.
+func (s *Status) Message() string {
+ if s == nil || s.s == nil {
+ return ""
+ }
+ return s.s.Message
+}
+
+// Proto returns s's status as an spb.Status proto message.
+func (s *Status) Proto() *spb.Status {
+ if s == nil {
+ return nil
+ }
+ return proto.Clone(s.s).(*spb.Status)
+}
+
+// Err returns an immutable error representing s; returns nil if s.Code() is
+// OK.
+func (s *Status) Err() error {
+ if s.Code() == codes.OK {
+ return nil
+ }
+ return (*statusError)(s.s)
+}
+
+// New returns a Status representing c and msg.
+func New(c codes.Code, msg string) *Status {
+ return &Status{s: &spb.Status{Code: int32(c), Message: msg}}
+}
+
+// Newf returns New(c, fmt.Sprintf(format, a...)).
+func Newf(c codes.Code, format string, a ...interface{}) *Status {
+ return New(c, fmt.Sprintf(format, a...))
+}
+
+// Error returns an error representing c and msg. If c is OK, returns nil.
+func Error(c codes.Code, msg string) error {
+ return New(c, msg).Err()
+}
+
+// Errorf returns Error(c, fmt.Sprintf(format, a...)).
+func Errorf(c codes.Code, format string, a ...interface{}) error {
+ return Error(c, fmt.Sprintf(format, a...))
+}
+
+// ErrorProto returns an error representing s. If s.Code is OK, returns nil.
+func ErrorProto(s *spb.Status) error {
+ return FromProto(s).Err()
+}
+
+// FromProto returns a Status representing s.
+func FromProto(s *spb.Status) *Status {
+ return &Status{s: proto.Clone(s).(*spb.Status)}
+}
+
+// FromError returns a Status representing err if it was produced from this
+// package, otherwise it returns nil, false.
+func FromError(err error) (s *Status, ok bool) {
+ if err == nil {
+ return &Status{s: &spb.Status{Code: int32(codes.OK)}}, true
+ }
+ if s, ok := err.(*statusError); ok {
+ return s.status(), true
+ }
+ return nil, false
+}
diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go
new file mode 100644
index 0000000..33f1c78
--- /dev/null
+++ b/vendor/google.golang.org/grpc/stream.go
@@ -0,0 +1,633 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/net/trace"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/stats"
+ "google.golang.org/grpc/status"
+ "google.golang.org/grpc/transport"
+)
+
+// StreamHandler defines the handler called by gRPC server to complete the
+// execution of a streaming RPC.
+type StreamHandler func(srv interface{}, stream ServerStream) error
+
+// StreamDesc represents a streaming RPC service's method specification.
+type StreamDesc struct {
+ StreamName string
+ Handler StreamHandler
+
+ // At least one of these is true.
+ ServerStreams bool
+ ClientStreams bool
+}
+
+// Stream defines the common interface a client or server stream has to satisfy.
+type Stream interface {
+ // Context returns the context for this stream.
+ Context() context.Context
+ // SendMsg blocks until it sends m, the stream is done or the stream
+ // breaks.
+ // On error, it aborts the stream and returns an RPC status on client
+ // side. On server side, it simply returns the error to the caller.
+ // SendMsg is called by generated code. Also Users can call SendMsg
+ // directly when it is really needed in their use cases.
+ SendMsg(m interface{}) error
+ // RecvMsg blocks until it receives a message or the stream is
+ // done. On client side, it returns io.EOF when the stream is done. On
+ // any other error, it aborts the stream and returns an RPC status. On
+ // server side, it simply returns the error to the caller.
+ RecvMsg(m interface{}) error
+}
+
+// ClientStream defines the interface a client stream has to satisfy.
+type ClientStream interface {
+ // Header returns the header metadata received from the server if there
+ // is any. It blocks if the metadata is not ready to read.
+ Header() (metadata.MD, error)
+ // Trailer returns the trailer metadata from the server, if there is any.
+ // It must only be called after stream.CloseAndRecv has returned, or
+ // stream.Recv has returned a non-nil error (including io.EOF).
+ Trailer() metadata.MD
+ // CloseSend closes the send direction of the stream. It closes the stream
+ // when non-nil error is met.
+ CloseSend() error
+ Stream
+}
+
+// NewClientStream creates a new Stream for the client side. This is called
+// by generated code.
+func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
+ if cc.dopts.streamInt != nil {
+ return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...)
+ }
+ return newClientStream(ctx, desc, cc, method, opts...)
+}
+
+func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
+ var (
+ t transport.ClientTransport
+ s *transport.Stream
+ put func()
+ cancel context.CancelFunc
+ )
+ c := defaultCallInfo
+ if mc, ok := cc.getMethodConfig(method); ok {
+ c.failFast = !mc.WaitForReady
+ if mc.Timeout > 0 {
+ ctx, cancel = context.WithTimeout(ctx, mc.Timeout)
+ }
+ }
+ for _, o := range opts {
+ if err := o.before(&c); err != nil {
+ return nil, toRPCErr(err)
+ }
+ }
+ callHdr := &transport.CallHdr{
+ Host: cc.authority,
+ Method: method,
+ Flush: desc.ServerStreams && desc.ClientStreams,
+ }
+ if cc.dopts.cp != nil {
+ callHdr.SendCompress = cc.dopts.cp.Type()
+ }
+ var trInfo traceInfo
+ if EnableTracing {
+ trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
+ trInfo.firstLine.client = true
+ if deadline, ok := ctx.Deadline(); ok {
+ trInfo.firstLine.deadline = deadline.Sub(time.Now())
+ }
+ trInfo.tr.LazyLog(&trInfo.firstLine, false)
+ ctx = trace.NewContext(ctx, trInfo.tr)
+ defer func() {
+ if err != nil {
+ // Need to call tr.finish() if error is returned.
+ // Because tr will not be returned to caller.
+ trInfo.tr.LazyPrintf("RPC: [%v]", err)
+ trInfo.tr.SetError()
+ trInfo.tr.Finish()
+ }
+ }()
+ }
+ ctx = newContextWithRPCInfo(ctx)
+ sh := cc.dopts.copts.StatsHandler
+ if sh != nil {
+ ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method})
+ begin := &stats.Begin{
+ Client: true,
+ BeginTime: time.Now(),
+ FailFast: c.failFast,
+ }
+ sh.HandleRPC(ctx, begin)
+ }
+ defer func() {
+ if err != nil && sh != nil {
+ // Only handle end stats if err != nil.
+ end := &stats.End{
+ Client: true,
+ Error: err,
+ }
+ sh.HandleRPC(ctx, end)
+ }
+ }()
+ gopts := BalancerGetOptions{
+ BlockingWait: !c.failFast,
+ }
+ for {
+ t, put, err = cc.getTransport(ctx, gopts)
+ if err != nil {
+ // TODO(zhaoq): Probably revisit the error handling.
+ if _, ok := status.FromError(err); ok {
+ return nil, err
+ }
+ if err == errConnClosing || err == errConnUnavailable {
+ if c.failFast {
+ return nil, Errorf(codes.Unavailable, "%v", err)
+ }
+ continue
+ }
+ // All the other errors are treated as Internal errors.
+ return nil, Errorf(codes.Internal, "%v", err)
+ }
+
+ s, err = t.NewStream(ctx, callHdr)
+ if err != nil {
+ if _, ok := err.(transport.ConnectionError); ok && put != nil {
+ // If error is connection error, transport was sending data on wire,
+ // and we are not sure if anything has been sent on wire.
+ // If error is not connection error, we are sure nothing has been sent.
+ updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false})
+ }
+ if put != nil {
+ put()
+ put = nil
+ }
+ if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast {
+ continue
+ }
+ return nil, toRPCErr(err)
+ }
+ break
+ }
+ cs := &clientStream{
+ opts: opts,
+ c: c,
+ desc: desc,
+ codec: cc.dopts.codec,
+ cp: cc.dopts.cp,
+ dc: cc.dopts.dc,
+ maxMsgSize: cc.dopts.maxMsgSize,
+ cancel: cancel,
+
+ put: put,
+ t: t,
+ s: s,
+ p: &parser{r: s},
+
+ tracing: EnableTracing,
+ trInfo: trInfo,
+
+ statsCtx: ctx,
+ statsHandler: cc.dopts.copts.StatsHandler,
+ }
+ if cc.dopts.cp != nil {
+ cs.cbuf = new(bytes.Buffer)
+ }
+ // Listen on ctx.Done() to detect cancellation and s.Done() to detect normal termination
+ // when there is no pending I/O operations on this stream.
+ go func() {
+ select {
+ case <-t.Error():
+ // Incur transport error, simply exit.
+ case <-cc.ctx.Done():
+ cs.finish(ErrClientConnClosing)
+ cs.closeTransportStream(ErrClientConnClosing)
+ case <-s.Done():
+ // TODO: The trace of the RPC is terminated here when there is no pending
+ // I/O, which is probably not the optimal solution.
+ cs.finish(s.Status().Err())
+ cs.closeTransportStream(nil)
+ case <-s.GoAway():
+ cs.finish(errConnDrain)
+ cs.closeTransportStream(errConnDrain)
+ case <-s.Context().Done():
+ err := s.Context().Err()
+ cs.finish(err)
+ cs.closeTransportStream(transport.ContextErr(err))
+ }
+ }()
+ return cs, nil
+}
+
+// clientStream implements a client side Stream.
+type clientStream struct {
+ opts []CallOption
+ c callInfo
+ t transport.ClientTransport
+ s *transport.Stream
+ p *parser
+ desc *StreamDesc
+ codec Codec
+ cp Compressor
+ cbuf *bytes.Buffer
+ dc Decompressor
+ maxMsgSize int
+ cancel context.CancelFunc
+
+ tracing bool // set to EnableTracing when the clientStream is created.
+
+ mu sync.Mutex
+ put func()
+ closed bool
+ finished bool
+ // trInfo.tr is set when the clientStream is created (if EnableTracing is true),
+ // and is set to nil when the clientStream's finish method is called.
+ trInfo traceInfo
+
+ // statsCtx keeps the user context for stats handling.
+ // All stats collection should use the statsCtx (instead of the stream context)
+ // so that all the generated stats for a particular RPC can be associated in the processing phase.
+ statsCtx context.Context
+ statsHandler stats.Handler
+}
+
+func (cs *clientStream) Context() context.Context {
+ return cs.s.Context()
+}
+
+func (cs *clientStream) Header() (metadata.MD, error) {
+ m, err := cs.s.Header()
+ if err != nil {
+ if _, ok := err.(transport.ConnectionError); !ok {
+ cs.closeTransportStream(err)
+ }
+ }
+ return m, err
+}
+
+func (cs *clientStream) Trailer() metadata.MD {
+ return cs.s.Trailer()
+}
+
+func (cs *clientStream) SendMsg(m interface{}) (err error) {
+ if cs.tracing {
+ cs.mu.Lock()
+ if cs.trInfo.tr != nil {
+ cs.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
+ }
+ cs.mu.Unlock()
+ }
+ // TODO Investigate how to signal the stats handling party.
+ // generate error stats if err != nil && err != io.EOF?
+ defer func() {
+ if err != nil {
+ cs.finish(err)
+ }
+ if err == nil {
+ return
+ }
+ if err == io.EOF {
+ // Specialize the process for server streaming. SendMesg is only called
+ // once when creating the stream object. io.EOF needs to be skipped when
+ // the rpc is early finished (before the stream object is created.).
+ // TODO: It is probably better to move this into the generated code.
+ if !cs.desc.ClientStreams && cs.desc.ServerStreams {
+ err = nil
+ }
+ return
+ }
+ if _, ok := err.(transport.ConnectionError); !ok {
+ cs.closeTransportStream(err)
+ }
+ err = toRPCErr(err)
+ }()
+ var outPayload *stats.OutPayload
+ if cs.statsHandler != nil {
+ outPayload = &stats.OutPayload{
+ Client: true,
+ }
+ }
+ out, err := encode(cs.codec, m, cs.cp, cs.cbuf, outPayload)
+ defer func() {
+ if cs.cbuf != nil {
+ cs.cbuf.Reset()
+ }
+ }()
+ if err != nil {
+ return Errorf(codes.Internal, "grpc: %v", err)
+ }
+ err = cs.t.Write(cs.s, out, &transport.Options{Last: false})
+ if err == nil && outPayload != nil {
+ outPayload.SentTime = time.Now()
+ cs.statsHandler.HandleRPC(cs.statsCtx, outPayload)
+ }
+ return err
+}
+
+func (cs *clientStream) RecvMsg(m interface{}) (err error) {
+ var inPayload *stats.InPayload
+ if cs.statsHandler != nil {
+ inPayload = &stats.InPayload{
+ Client: true,
+ }
+ }
+ err = recv(cs.p, cs.codec, cs.s, cs.dc, m, cs.maxMsgSize, inPayload)
+ defer func() {
+ // err != nil indicates the termination of the stream.
+ if err != nil {
+ cs.finish(err)
+ }
+ }()
+ if err == nil {
+ if cs.tracing {
+ cs.mu.Lock()
+ if cs.trInfo.tr != nil {
+ cs.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
+ }
+ cs.mu.Unlock()
+ }
+ if inPayload != nil {
+ cs.statsHandler.HandleRPC(cs.statsCtx, inPayload)
+ }
+ if !cs.desc.ClientStreams || cs.desc.ServerStreams {
+ return
+ }
+ // Special handling for client streaming rpc.
+ // This recv expects EOF or errors, so we don't collect inPayload.
+ err = recv(cs.p, cs.codec, cs.s, cs.dc, m, cs.maxMsgSize, nil)
+ cs.closeTransportStream(err)
+ if err == nil {
+ return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
+ }
+ if err == io.EOF {
+ if se := cs.s.Status().Err(); se != nil {
+ return se
+ }
+ cs.finish(err)
+ return nil
+ }
+ return toRPCErr(err)
+ }
+ if _, ok := err.(transport.ConnectionError); !ok {
+ cs.closeTransportStream(err)
+ }
+ if err == io.EOF {
+ if statusErr := cs.s.Status().Err(); statusErr != nil {
+ return statusErr
+ }
+ // Returns io.EOF to indicate the end of the stream.
+ return
+ }
+ return toRPCErr(err)
+}
+
+func (cs *clientStream) CloseSend() (err error) {
+ err = cs.t.Write(cs.s, nil, &transport.Options{Last: true})
+ defer func() {
+ if err != nil {
+ cs.finish(err)
+ }
+ }()
+ if err == nil || err == io.EOF {
+ return nil
+ }
+ if _, ok := err.(transport.ConnectionError); !ok {
+ cs.closeTransportStream(err)
+ }
+ err = toRPCErr(err)
+ return
+}
+
+func (cs *clientStream) closeTransportStream(err error) {
+ cs.mu.Lock()
+ if cs.closed {
+ cs.mu.Unlock()
+ return
+ }
+ cs.closed = true
+ cs.mu.Unlock()
+ cs.t.CloseStream(cs.s, err)
+}
+
+func (cs *clientStream) finish(err error) {
+ cs.mu.Lock()
+ defer cs.mu.Unlock()
+ if cs.finished {
+ return
+ }
+ cs.finished = true
+ defer func() {
+ if cs.cancel != nil {
+ cs.cancel()
+ }
+ }()
+ for _, o := range cs.opts {
+ o.after(&cs.c)
+ }
+ if cs.put != nil {
+ updateRPCInfoInContext(cs.s.Context(), rpcInfo{
+ bytesSent: cs.s.BytesSent(),
+ bytesReceived: cs.s.BytesReceived(),
+ })
+ cs.put()
+ cs.put = nil
+ }
+ if cs.statsHandler != nil {
+ end := &stats.End{
+ Client: true,
+ EndTime: time.Now(),
+ }
+ if err != io.EOF {
+ // end.Error is nil if the RPC finished successfully.
+ end.Error = toRPCErr(err)
+ }
+ cs.statsHandler.HandleRPC(cs.statsCtx, end)
+ }
+ if !cs.tracing {
+ return
+ }
+ if cs.trInfo.tr != nil {
+ if err == nil || err == io.EOF {
+ cs.trInfo.tr.LazyPrintf("RPC: [OK]")
+ } else {
+ cs.trInfo.tr.LazyPrintf("RPC: [%v]", err)
+ cs.trInfo.tr.SetError()
+ }
+ cs.trInfo.tr.Finish()
+ cs.trInfo.tr = nil
+ }
+}
+
+// ServerStream defines the interface a server stream has to satisfy.
+type ServerStream interface {
+ // SetHeader sets the header metadata. It may be called multiple times.
+ // When call multiple times, all the provided metadata will be merged.
+ // All the metadata will be sent out when one of the following happens:
+ // - ServerStream.SendHeader() is called;
+ // - The first response is sent out;
+ // - An RPC status is sent out (error or success).
+ SetHeader(metadata.MD) error
+ // SendHeader sends the header metadata.
+ // The provided md and headers set by SetHeader() will be sent.
+ // It fails if called multiple times.
+ SendHeader(metadata.MD) error
+ // SetTrailer sets the trailer metadata which will be sent with the RPC status.
+ // When called more than once, all the provided metadata will be merged.
+ SetTrailer(metadata.MD)
+ Stream
+}
+
+// serverStream implements a server side Stream.
+type serverStream struct {
+ t transport.ServerTransport
+ s *transport.Stream
+ p *parser
+ codec Codec
+ cp Compressor
+ dc Decompressor
+ cbuf *bytes.Buffer
+ maxMsgSize int
+ trInfo *traceInfo
+
+ statsHandler stats.Handler
+
+ mu sync.Mutex // protects trInfo.tr after the service handler runs.
+}
+
+func (ss *serverStream) Context() context.Context {
+ return ss.s.Context()
+}
+
+func (ss *serverStream) SetHeader(md metadata.MD) error {
+ if md.Len() == 0 {
+ return nil
+ }
+ return ss.s.SetHeader(md)
+}
+
+func (ss *serverStream) SendHeader(md metadata.MD) error {
+ return ss.t.WriteHeader(ss.s, md)
+}
+
+func (ss *serverStream) SetTrailer(md metadata.MD) {
+ if md.Len() == 0 {
+ return
+ }
+ ss.s.SetTrailer(md)
+ return
+}
+
+func (ss *serverStream) SendMsg(m interface{}) (err error) {
+ defer func() {
+ if ss.trInfo != nil {
+ ss.mu.Lock()
+ if ss.trInfo.tr != nil {
+ if err == nil {
+ ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
+ } else {
+ ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
+ ss.trInfo.tr.SetError()
+ }
+ }
+ ss.mu.Unlock()
+ }
+ }()
+ var outPayload *stats.OutPayload
+ if ss.statsHandler != nil {
+ outPayload = &stats.OutPayload{}
+ }
+ out, err := encode(ss.codec, m, ss.cp, ss.cbuf, outPayload)
+ defer func() {
+ if ss.cbuf != nil {
+ ss.cbuf.Reset()
+ }
+ }()
+ if err != nil {
+ err = Errorf(codes.Internal, "grpc: %v", err)
+ return err
+ }
+ if err := ss.t.Write(ss.s, out, &transport.Options{Last: false}); err != nil {
+ return toRPCErr(err)
+ }
+ if outPayload != nil {
+ outPayload.SentTime = time.Now()
+ ss.statsHandler.HandleRPC(ss.s.Context(), outPayload)
+ }
+ return nil
+}
+
+func (ss *serverStream) RecvMsg(m interface{}) (err error) {
+ defer func() {
+ if ss.trInfo != nil {
+ ss.mu.Lock()
+ if ss.trInfo.tr != nil {
+ if err == nil {
+ ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
+ } else if err != io.EOF {
+ ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
+ ss.trInfo.tr.SetError()
+ }
+ }
+ ss.mu.Unlock()
+ }
+ }()
+ var inPayload *stats.InPayload
+ if ss.statsHandler != nil {
+ inPayload = &stats.InPayload{}
+ }
+ if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxMsgSize, inPayload); err != nil {
+ if err == io.EOF {
+ return err
+ }
+ if err == io.ErrUnexpectedEOF {
+ err = Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
+ }
+ return toRPCErr(err)
+ }
+ if inPayload != nil {
+ ss.statsHandler.HandleRPC(ss.s.Context(), inPayload)
+ }
+ return nil
+}
diff --git a/vendor/google.golang.org/grpc/tap/tap.go b/vendor/google.golang.org/grpc/tap/tap.go
new file mode 100644
index 0000000..0f36647
--- /dev/null
+++ b/vendor/google.golang.org/grpc/tap/tap.go
@@ -0,0 +1,54 @@
+/*
+ *
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+// Package tap defines the function handles which are executed on the transport
+// layer of gRPC-Go and related information. Everything here is EXPERIMENTAL.
+package tap
+
+import (
+ "golang.org/x/net/context"
+)
+
+// Info defines the relevant information needed by the handles.
+type Info struct {
+ // FullMethodName is the string of grpc method (in the format of
+ // /package.service/method).
+ FullMethodName string
+ // TODO: More to be added.
+}
+
+// ServerInHandle defines the function which runs when a new stream is created
+// on the server side. Note that it is executed in the per-connection I/O goroutine(s) instead
+// of per-RPC goroutine. Therefore, users should NOT have any blocking/time-consuming
+// work in this handle. Otherwise all the RPCs would slow down.
+type ServerInHandle func(ctx context.Context, info *Info) (context.Context, error)
diff --git a/vendor/google.golang.org/grpc/trace.go b/vendor/google.golang.org/grpc/trace.go
new file mode 100644
index 0000000..f6747e1
--- /dev/null
+++ b/vendor/google.golang.org/grpc/trace.go
@@ -0,0 +1,119 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * 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.
+ *
+ */
+
+package grpc
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "net"
+ "strings"
+ "time"
+
+ "golang.org/x/net/trace"
+)
+
+// EnableTracing controls whether to trace RPCs using the golang.org/x/net/trace package.
+// This should only be set before any RPCs are sent or received by this program.
+var EnableTracing = true
+
+// methodFamily returns the trace family for the given method.
+// It turns "/pkg.Service/GetFoo" into "pkg.Service".
+func methodFamily(m string) string {
+ m = strings.TrimPrefix(m, "/") // remove leading slash
+ if i := strings.Index(m, "/"); i >= 0 {
+ m = m[:i] // remove everything from second slash
+ }
+ if i := strings.LastIndex(m, "."); i >= 0 {
+ m = m[i+1:] // cut down to last dotted component
+ }
+ return m
+}
+
+// traceInfo contains tracing information for an RPC.
+type traceInfo struct {
+ tr trace.Trace
+ firstLine firstLine
+}
+
+// firstLine is the first line of an RPC trace.
+type firstLine struct {
+ client bool // whether this is a client (outgoing) RPC
+ remoteAddr net.Addr
+ deadline time.Duration // may be zero
+}
+
+func (f *firstLine) String() string {
+ var line bytes.Buffer
+ io.WriteString(&line, "RPC: ")
+ if f.client {
+ io.WriteString(&line, "to")
+ } else {
+ io.WriteString(&line, "from")
+ }
+ fmt.Fprintf(&line, " %v deadline:", f.remoteAddr)
+ if f.deadline != 0 {
+ fmt.Fprint(&line, f.deadline)
+ } else {
+ io.WriteString(&line, "none")
+ }
+ return line.String()
+}
+
+// payload represents an RPC request or response payload.
+type payload struct {
+ sent bool // whether this is an outgoing payload
+ msg interface{} // e.g. a proto.Message
+ // TODO(dsymonds): add stringifying info to codec, and limit how much we hold here?
+}
+
+func (p payload) String() string {
+ if p.sent {
+ return fmt.Sprintf("sent: %v", p.msg)
+ }
+ return fmt.Sprintf("recv: %v", p.msg)
+}
+
+type fmtStringer struct {
+ format string
+ a []interface{}
+}
+
+func (f *fmtStringer) String() string {
+ return fmt.Sprintf(f.format, f.a...)
+}
+
+type stringer string
+
+func (s stringer) String() string { return string(s) }
diff --git a/vendor/google.golang.org/grpc/transport/control.go b/vendor/google.golang.org/grpc/transport/control.go
new file mode 100644
index 0000000..8d29aee
--- /dev/null
+++ b/vendor/google.golang.org/grpc/transport/control.go
@@ -0,0 +1,207 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+package transport
+
+import (
+ "fmt"
+ "math"
+ "sync"
+ "time"
+
+ "golang.org/x/net/http2"
+)
+
+const (
+ // The default value of flow control window size in HTTP2 spec.
+ defaultWindowSize = 65535
+ // The initial window size for flow control.
+ initialWindowSize = defaultWindowSize // for an RPC
+ initialConnWindowSize = defaultWindowSize * 16 // for a connection
+ infinity = time.Duration(math.MaxInt64)
+ defaultClientKeepaliveTime = infinity
+ defaultClientKeepaliveTimeout = time.Duration(20 * time.Second)
+ defaultMaxStreamsClient = 100
+ defaultMaxConnectionIdle = infinity
+ defaultMaxConnectionAge = infinity
+ defaultMaxConnectionAgeGrace = infinity
+ defaultServerKeepaliveTime = time.Duration(2 * time.Hour)
+ defaultServerKeepaliveTimeout = time.Duration(20 * time.Second)
+ defaultKeepalivePolicyMinTime = time.Duration(5 * time.Minute)
+)
+
+// The following defines various control items which could flow through
+// the control buffer of transport. They represent different aspects of
+// control tasks, e.g., flow control, settings, streaming resetting, etc.
+type windowUpdate struct {
+ streamID uint32
+ increment uint32
+}
+
+func (*windowUpdate) item() {}
+
+type settings struct {
+ ack bool
+ ss []http2.Setting
+}
+
+func (*settings) item() {}
+
+type resetStream struct {
+ streamID uint32
+ code http2.ErrCode
+}
+
+func (*resetStream) item() {}
+
+type goAway struct {
+ code http2.ErrCode
+ debugData []byte
+}
+
+func (*goAway) item() {}
+
+type flushIO struct {
+}
+
+func (*flushIO) item() {}
+
+type ping struct {
+ ack bool
+ data [8]byte
+}
+
+func (*ping) item() {}
+
+// quotaPool is a pool which accumulates the quota and sends it to acquire()
+// when it is available.
+type quotaPool struct {
+ c chan int
+
+ mu sync.Mutex
+ quota int
+}
+
+// newQuotaPool creates a quotaPool which has quota q available to consume.
+func newQuotaPool(q int) *quotaPool {
+ qb := &quotaPool{
+ c: make(chan int, 1),
+ }
+ if q > 0 {
+ qb.c <- q
+ } else {
+ qb.quota = q
+ }
+ return qb
+}
+
+// add cancels the pending quota sent on acquired, incremented by v and sends
+// it back on acquire.
+func (qb *quotaPool) add(v int) {
+ qb.mu.Lock()
+ defer qb.mu.Unlock()
+ select {
+ case n := <-qb.c:
+ qb.quota += n
+ default:
+ }
+ qb.quota += v
+ if qb.quota <= 0 {
+ return
+ }
+ // After the pool has been created, this is the only place that sends on
+ // the channel. Since mu is held at this point and any quota that was sent
+ // on the channel has been retrieved, we know that this code will always
+ // place any positive quota value on the channel.
+ select {
+ case qb.c <- qb.quota:
+ qb.quota = 0
+ default:
+ }
+}
+
+// acquire returns the channel on which available quota amounts are sent.
+func (qb *quotaPool) acquire() <-chan int {
+ return qb.c
+}
+
+// inFlow deals with inbound flow control
+type inFlow struct {
+ // The inbound flow control limit for pending data.
+ limit uint32
+
+ mu sync.Mutex
+ // pendingData is the overall data which have been received but not been
+ // consumed by applications.
+ pendingData uint32
+ // The amount of data the application has consumed but grpc has not sent
+ // window update for them. Used to reduce window update frequency.
+ pendingUpdate uint32
+}
+
+// onData is invoked when some data frame is received. It updates pendingData.
+func (f *inFlow) onData(n uint32) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.pendingData += n
+ if f.pendingData+f.pendingUpdate > f.limit {
+ return fmt.Errorf("received %d-bytes data exceeding the limit %d bytes", f.pendingData+f.pendingUpdate, f.limit)
+ }
+ return nil
+}
+
+// onRead is invoked when the application reads the data. It returns the window size
+// to be sent to the peer.
+func (f *inFlow) onRead(n uint32) uint32 {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.pendingData == 0 {
+ return 0
+ }
+ f.pendingData -= n
+ f.pendingUpdate += n
+ if f.pendingUpdate >= f.limit/4 {
+ wu := f.pendingUpdate
+ f.pendingUpdate = 0
+ return wu
+ }
+ return 0
+}
+
+func (f *inFlow) resetPendingData() uint32 {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ n := f.pendingData
+ f.pendingData = 0
+ return n
+}
diff --git a/vendor/google.golang.org/grpc/transport/go16.go b/vendor/google.golang.org/grpc/transport/go16.go
new file mode 100644
index 0000000..ee1c46b
--- /dev/null
+++ b/vendor/google.golang.org/grpc/transport/go16.go
@@ -0,0 +1,46 @@
+// +build go1.6,!go1.7
+
+/*
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+package transport
+
+import (
+ "net"
+
+ "golang.org/x/net/context"
+)
+
+// dialContext connects to the address on the named network.
+func dialContext(ctx context.Context, network, address string) (net.Conn, error) {
+ return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address)
+}
diff --git a/vendor/google.golang.org/grpc/transport/go17.go b/vendor/google.golang.org/grpc/transport/go17.go
new file mode 100644
index 0000000..356f13f
--- /dev/null
+++ b/vendor/google.golang.org/grpc/transport/go17.go
@@ -0,0 +1,46 @@
+// +build go1.7
+
+/*
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+package transport
+
+import (
+ "net"
+
+ "golang.org/x/net/context"
+)
+
+// dialContext connects to the address on the named network.
+func dialContext(ctx context.Context, network, address string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, address)
+}
diff --git a/vendor/google.golang.org/grpc/transport/handler_server.go b/vendor/google.golang.org/grpc/transport/handler_server.go
new file mode 100644
index 0000000..24f306b
--- /dev/null
+++ b/vendor/google.golang.org/grpc/transport/handler_server.go
@@ -0,0 +1,406 @@
+/*
+ * Copyright 2016, Google Inc.
+ * 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.
+ *
+ */
+
+// This file is the implementation of a gRPC server using HTTP/2 which
+// uses the standard Go http2 Server implementation (via the
+// http.Handler interface), rather than speaking low-level HTTP/2
+// frames itself. It is the implementation of *grpc.Server.ServeHTTP.
+
+package transport
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/net/http2"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/peer"
+ "google.golang.org/grpc/status"
+)
+
+// NewServerHandlerTransport returns a ServerTransport handling gRPC
+// from inside an http.Handler. It requires that the http Server
+// supports HTTP/2.
+func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request) (ServerTransport, error) {
+ if r.ProtoMajor != 2 {
+ return nil, errors.New("gRPC requires HTTP/2")
+ }
+ if r.Method != "POST" {
+ return nil, errors.New("invalid gRPC request method")
+ }
+ if !validContentType(r.Header.Get("Content-Type")) {
+ return nil, errors.New("invalid gRPC request content-type")
+ }
+ if _, ok := w.(http.Flusher); !ok {
+ return nil, errors.New("gRPC requires a ResponseWriter supporting http.Flusher")
+ }
+ if _, ok := w.(http.CloseNotifier); !ok {
+ return nil, errors.New("gRPC requires a ResponseWriter supporting http.CloseNotifier")
+ }
+
+ st := &serverHandlerTransport{
+ rw: w,
+ req: r,
+ closedCh: make(chan struct{}),
+ writes: make(chan func()),
+ }
+
+ if v := r.Header.Get("grpc-timeout"); v != "" {
+ to, err := decodeTimeout(v)
+ if err != nil {
+ return nil, streamErrorf(codes.Internal, "malformed time-out: %v", err)
+ }
+ st.timeoutSet = true
+ st.timeout = to
+ }
+
+ var metakv []string
+ if r.Host != "" {
+ metakv = append(metakv, ":authority", r.Host)
+ }
+ for k, vv := range r.Header {
+ k = strings.ToLower(k)
+ if isReservedHeader(k) && !isWhitelistedPseudoHeader(k) {
+ continue
+ }
+ for _, v := range vv {
+ if k == "user-agent" {
+ // user-agent is special. Copying logic of http_util.go.
+ if i := strings.LastIndex(v, " "); i == -1 {
+ // There is no application user agent string being set
+ continue
+ } else {
+ v = v[:i]
+ }
+ }
+ v, err := decodeMetadataHeader(k, v)
+ if err != nil {
+ return nil, streamErrorf(codes.InvalidArgument, "malformed binary metadata: %v", err)
+ }
+ metakv = append(metakv, k, v)
+ }
+ }
+ st.headerMD = metadata.Pairs(metakv...)
+
+ return st, nil
+}
+
+// serverHandlerTransport is an implementation of ServerTransport
+// which replies to exactly one gRPC request (exactly one HTTP request),
+// using the net/http.Handler interface. This http.Handler is guaranteed
+// at this point to be speaking over HTTP/2, so it's able to speak valid
+// gRPC.
+type serverHandlerTransport struct {
+ rw http.ResponseWriter
+ req *http.Request
+ timeoutSet bool
+ timeout time.Duration
+ didCommonHeaders bool
+
+ headerMD metadata.MD
+
+ closeOnce sync.Once
+ closedCh chan struct{} // closed on Close
+
+ // writes is a channel of code to run serialized in the
+ // ServeHTTP (HandleStreams) goroutine. The channel is closed
+ // when WriteStatus is called.
+ writes chan func()
+}
+
+func (ht *serverHandlerTransport) Close() error {
+ ht.closeOnce.Do(ht.closeCloseChanOnce)
+ return nil
+}
+
+func (ht *serverHandlerTransport) closeCloseChanOnce() { close(ht.closedCh) }
+
+func (ht *serverHandlerTransport) RemoteAddr() net.Addr { return strAddr(ht.req.RemoteAddr) }
+
+// strAddr is a net.Addr backed by either a TCP "ip:port" string, or
+// the empty string if unknown.
+type strAddr string
+
+func (a strAddr) Network() string {
+ if a != "" {
+ // Per the documentation on net/http.Request.RemoteAddr, if this is
+ // set, it's set to the IP:port of the peer (hence, TCP):
+ // https://golang.org/pkg/net/http/#Request
+ //
+ // If we want to support Unix sockets later, we can
+ // add our own grpc-specific convention within the
+ // grpc codebase to set RemoteAddr to a different
+ // format, or probably better: we can attach it to the
+ // context and use that from serverHandlerTransport.RemoteAddr.
+ return "tcp"
+ }
+ return ""
+}
+
+func (a strAddr) String() string { return string(a) }
+
+// do runs fn in the ServeHTTP goroutine.
+func (ht *serverHandlerTransport) do(fn func()) error {
+ select {
+ case ht.writes <- fn:
+ return nil
+ case <-ht.closedCh:
+ return ErrConnClosing
+ }
+}
+
+func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) error {
+ err := ht.do(func() {
+ ht.writeCommonHeaders(s)
+
+ // And flush, in case no header or body has been sent yet.
+ // This forces a separation of headers and trailers if this is the
+ // first call (for example, in end2end tests's TestNoService).
+ ht.rw.(http.Flusher).Flush()
+
+ h := ht.rw.Header()
+ h.Set("Grpc-Status", fmt.Sprintf("%d", st.Code()))
+ if m := st.Message(); m != "" {
+ h.Set("Grpc-Message", encodeGrpcMessage(m))
+ }
+
+ // TODO: Support Grpc-Status-Details-Bin
+
+ if md := s.Trailer(); len(md) > 0 {
+ for k, vv := range md {
+ // Clients don't tolerate reading restricted headers after some non restricted ones were sent.
+ if isReservedHeader(k) {
+ continue
+ }
+ for _, v := range vv {
+ // http2 ResponseWriter mechanism to send undeclared Trailers after
+ // the headers have possibly been written.
+ h.Add(http2.TrailerPrefix+k, encodeMetadataHeader(k, v))
+ }
+ }
+ }
+ })
+ close(ht.writes)
+ return err
+}
+
+// writeCommonHeaders sets common headers on the first write
+// call (Write, WriteHeader, or WriteStatus).
+func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) {
+ if ht.didCommonHeaders {
+ return
+ }
+ ht.didCommonHeaders = true
+
+ h := ht.rw.Header()
+ h["Date"] = nil // suppress Date to make tests happy; TODO: restore
+ h.Set("Content-Type", "application/grpc")
+
+ // Predeclare trailers we'll set later in WriteStatus (after the body).
+ // This is a SHOULD in the HTTP RFC, and the way you add (known)
+ // Trailers per the net/http.ResponseWriter contract.
+ // See https://golang.org/pkg/net/http/#ResponseWriter
+ // and https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
+ h.Add("Trailer", "Grpc-Status")
+ h.Add("Trailer", "Grpc-Message")
+ // TODO: Support Grpc-Status-Details-Bin
+
+ if s.sendCompress != "" {
+ h.Set("Grpc-Encoding", s.sendCompress)
+ }
+}
+
+func (ht *serverHandlerTransport) Write(s *Stream, data []byte, opts *Options) error {
+ return ht.do(func() {
+ ht.writeCommonHeaders(s)
+ ht.rw.Write(data)
+ if !opts.Delay {
+ ht.rw.(http.Flusher).Flush()
+ }
+ })
+}
+
+func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error {
+ return ht.do(func() {
+ ht.writeCommonHeaders(s)
+ h := ht.rw.Header()
+ for k, vv := range md {
+ // Clients don't tolerate reading restricted headers after some non restricted ones were sent.
+ if isReservedHeader(k) {
+ continue
+ }
+ for _, v := range vv {
+ v = encodeMetadataHeader(k, v)
+ h.Add(k, v)
+ }
+ }
+ ht.rw.WriteHeader(200)
+ ht.rw.(http.Flusher).Flush()
+ })
+}
+
+func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), traceCtx func(context.Context, string) context.Context) {
+ // With this transport type there will be exactly 1 stream: this HTTP request.
+
+ var ctx context.Context
+ var cancel context.CancelFunc
+ if ht.timeoutSet {
+ ctx, cancel = context.WithTimeout(context.Background(), ht.timeout)
+ } else {
+ ctx, cancel = context.WithCancel(context.Background())
+ }
+
+ // requestOver is closed when either the request's context is done
+ // or the status has been written via WriteStatus.
+ requestOver := make(chan struct{})
+
+ // clientGone receives a single value if peer is gone, either
+ // because the underlying connection is dead or because the
+ // peer sends an http2 RST_STREAM.
+ clientGone := ht.rw.(http.CloseNotifier).CloseNotify()
+ go func() {
+ select {
+ case <-requestOver:
+ return
+ case <-ht.closedCh:
+ case <-clientGone:
+ }
+ cancel()
+ }()
+
+ req := ht.req
+
+ s := &Stream{
+ id: 0, // irrelevant
+ windowHandler: func(int) {}, // nothing
+ cancel: cancel,
+ buf: newRecvBuffer(),
+ st: ht,
+ method: req.URL.Path,
+ recvCompress: req.Header.Get("grpc-encoding"),
+ }
+ pr := &peer.Peer{
+ Addr: ht.RemoteAddr(),
+ }
+ if req.TLS != nil {
+ pr.AuthInfo = credentials.TLSInfo{State: *req.TLS}
+ }
+ ctx = metadata.NewIncomingContext(ctx, ht.headerMD)
+ ctx = peer.NewContext(ctx, pr)
+ s.ctx = newContextWithStream(ctx, s)
+ s.dec = &recvBufferReader{ctx: s.ctx, recv: s.buf}
+
+ // readerDone is closed when the Body.Read-ing goroutine exits.
+ readerDone := make(chan struct{})
+ go func() {
+ defer close(readerDone)
+
+ // TODO: minimize garbage, optimize recvBuffer code/ownership
+ const readSize = 8196
+ for buf := make([]byte, readSize); ; {
+ n, err := req.Body.Read(buf)
+ if n > 0 {
+ s.buf.put(&recvMsg{data: buf[:n:n]})
+ buf = buf[n:]
+ }
+ if err != nil {
+ s.buf.put(&recvMsg{err: mapRecvMsgError(err)})
+ return
+ }
+ if len(buf) == 0 {
+ buf = make([]byte, readSize)
+ }
+ }
+ }()
+
+ // startStream is provided by the *grpc.Server's serveStreams.
+ // It starts a goroutine serving s and exits immediately.
+ // The goroutine that is started is the one that then calls
+ // into ht, calling WriteHeader, Write, WriteStatus, Close, etc.
+ startStream(s)
+
+ ht.runStream()
+ close(requestOver)
+
+ // Wait for reading goroutine to finish.
+ req.Body.Close()
+ <-readerDone
+}
+
+func (ht *serverHandlerTransport) runStream() {
+ for {
+ select {
+ case fn, ok := <-ht.writes:
+ if !ok {
+ return
+ }
+ fn()
+ case <-ht.closedCh:
+ return
+ }
+ }
+}
+
+func (ht *serverHandlerTransport) Drain() {
+ panic("Drain() is not implemented")
+}
+
+// mapRecvMsgError returns the non-nil err into the appropriate
+// error value as expected by callers of *grpc.parser.recvMsg.
+// In particular, in can only be:
+// * io.EOF
+// * io.ErrUnexpectedEOF
+// * of type transport.ConnectionError
+// * of type transport.StreamError
+func mapRecvMsgError(err error) error {
+ if err == io.EOF || err == io.ErrUnexpectedEOF {
+ return err
+ }
+ if se, ok := err.(http2.StreamError); ok {
+ if code, ok := http2ErrConvTab[se.Code]; ok {
+ return StreamError{
+ Code: code,
+ Desc: se.Error(),
+ }
+ }
+ }
+ return connectionErrorf(true, err, err.Error())
+}
diff --git a/vendor/google.golang.org/grpc/transport/http2_client.go b/vendor/google.golang.org/grpc/transport/http2_client.go
new file mode 100644
index 0000000..380fff6
--- /dev/null
+++ b/vendor/google.golang.org/grpc/transport/http2_client.go
@@ -0,0 +1,1248 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+package transport
+
+import (
+ "bytes"
+ "io"
+ "math"
+ "net"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "golang.org/x/net/context"
+ "golang.org/x/net/http2"
+ "golang.org/x/net/http2/hpack"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/grpclog"
+ "google.golang.org/grpc/keepalive"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/peer"
+ "google.golang.org/grpc/stats"
+ "google.golang.org/grpc/status"
+)
+
+// http2Client implements the ClientTransport interface with HTTP2.
+type http2Client struct {
+ ctx context.Context
+ target string // server name/addr
+ userAgent string
+ md interface{}
+ conn net.Conn // underlying communication channel
+ remoteAddr net.Addr
+ localAddr net.Addr
+ authInfo credentials.AuthInfo // auth info about the connection
+ nextID uint32 // the next stream ID to be used
+
+ // writableChan synchronizes write access to the transport.
+ // A writer acquires the write lock by sending a value on writableChan
+ // and releases it by receiving from writableChan.
+ writableChan chan int
+ // shutdownChan is closed when Close is called.
+ // Blocking operations should select on shutdownChan to avoid
+ // blocking forever after Close.
+ // TODO(zhaoq): Maybe have a channel context?
+ shutdownChan chan struct{}
+ // errorChan is closed to notify the I/O error to the caller.
+ errorChan chan struct{}
+ // goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor)
+ // that the server sent GoAway on this transport.
+ goAway chan struct{}
+ // awakenKeepalive is used to wake up keepalive when after it has gone dormant.
+ awakenKeepalive chan struct{}
+
+ framer *framer
+ hBuf *bytes.Buffer // the buffer for HPACK encoding
+ hEnc *hpack.Encoder // HPACK encoder
+
+ // controlBuf delivers all the control related tasks (e.g., window
+ // updates, reset streams, and various settings) to the controller.
+ controlBuf *recvBuffer
+ fc *inFlow
+ // sendQuotaPool provides flow control to outbound message.
+ sendQuotaPool *quotaPool
+ // streamsQuota limits the max number of concurrent streams.
+ streamsQuota *quotaPool
+
+ // The scheme used: https if TLS is on, http otherwise.
+ scheme string
+
+ creds []credentials.PerRPCCredentials
+
+ // Boolean to keep track of reading activity on transport.
+ // 1 is true and 0 is false.
+ activity uint32 // Accessed atomically.
+ kp keepalive.ClientParameters
+
+ statsHandler stats.Handler
+
+ mu sync.Mutex // guard the following variables
+ state transportState // the state of underlying connection
+ activeStreams map[uint32]*Stream
+ // The max number of concurrent streams
+ maxStreams int
+ // the per-stream outbound flow control window size set by the peer.
+ streamSendQuota uint32
+ // goAwayID records the Last-Stream-ID in the GoAway frame from the server.
+ goAwayID uint32
+ // prevGoAway ID records the Last-Stream-ID in the previous GOAway frame.
+ prevGoAwayID uint32
+ // goAwayReason records the http2.ErrCode and debug data received with the
+ // GoAway frame.
+ goAwayReason GoAwayReason
+}
+
+func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr string) (net.Conn, error) {
+ if fn != nil {
+ return fn(ctx, addr)
+ }
+ return dialContext(ctx, "tcp", addr)
+}
+
+func isTemporary(err error) bool {
+ switch err {
+ case io.EOF:
+ // Connection closures may be resolved upon retry, and are thus
+ // treated as temporary.
+ return true
+ case context.DeadlineExceeded:
+ // In Go 1.7, context.DeadlineExceeded implements Timeout(), and this
+ // special case is not needed. Until then, we need to keep this
+ // clause.
+ return true
+ }
+
+ switch err := err.(type) {
+ case interface {
+ Temporary() bool
+ }:
+ return err.Temporary()
+ case interface {
+ Timeout() bool
+ }:
+ // Timeouts may be resolved upon retry, and are thus treated as
+ // temporary.
+ return err.Timeout()
+ }
+ return false
+}
+
+// newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2
+// and starts to receive messages on it. Non-nil error returns if construction
+// fails.
+func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions) (_ ClientTransport, err error) {
+ scheme := "http"
+ conn, err := dial(ctx, opts.Dialer, addr.Addr)
+ if err != nil {
+ if opts.FailOnNonTempDialError {
+ return nil, connectionErrorf(isTemporary(err), err, "transport: %v", err)
+ }
+ return nil, connectionErrorf(true, err, "transport: %v", err)
+ }
+ // Any further errors will close the underlying connection
+ defer func(conn net.Conn) {
+ if err != nil {
+ conn.Close()
+ }
+ }(conn)
+ var authInfo credentials.AuthInfo
+ if creds := opts.TransportCredentials; creds != nil {
+ scheme = "https"
+ conn, authInfo, err = creds.ClientHandshake(ctx, addr.Addr, conn)
+ if err != nil {
+ // Credentials handshake errors are typically considered permanent
+ // to avoid retrying on e.g. bad certificates.
+ temp := isTemporary(err)
+ return nil, connectionErrorf(temp, err, "transport: %v", err)
+ }
+ }
+ kp := opts.KeepaliveParams
+ // Validate keepalive parameters.
+ if kp.Time == 0 {
+ kp.Time = defaultClientKeepaliveTime
+ }
+ if kp.Timeout == 0 {
+ kp.Timeout = defaultClientKeepaliveTimeout
+ }
+ var buf bytes.Buffer
+ t := &http2Client{
+ ctx: ctx,
+ target: addr.Addr,
+ userAgent: opts.UserAgent,
+ md: addr.Metadata,
+ conn: conn,
+ remoteAddr: conn.RemoteAddr(),
+ localAddr: conn.LocalAddr(),
+ authInfo: authInfo,
+ // The client initiated stream id is odd starting from 1.
+ nextID: 1,
+ writableChan: make(chan int, 1),
+ shutdownChan: make(chan struct{}),
+ errorChan: make(chan struct{}),
+ goAway: make(chan struct{}),
+ awakenKeepalive: make(chan struct{}, 1),
+ framer: newFramer(conn),
+ hBuf: &buf,
+ hEnc: hpack.NewEncoder(&buf),
+ controlBuf: newRecvBuffer(),
+ fc: &inFlow{limit: initialConnWindowSize},
+ sendQuotaPool: newQuotaPool(defaultWindowSize),
+ scheme: scheme,
+ state: reachable,
+ activeStreams: make(map[uint32]*Stream),
+ creds: opts.PerRPCCredentials,
+ maxStreams: defaultMaxStreamsClient,
+ streamsQuota: newQuotaPool(defaultMaxStreamsClient),
+ streamSendQuota: defaultWindowSize,
+ kp: kp,
+ statsHandler: opts.StatsHandler,
+ }
+ // Make sure awakenKeepalive can't be written upon.
+ // keepalive routine will make it writable, if need be.
+ t.awakenKeepalive <- struct{}{}
+ if t.statsHandler != nil {
+ t.ctx = t.statsHandler.TagConn(t.ctx, &stats.ConnTagInfo{
+ RemoteAddr: t.remoteAddr,
+ LocalAddr: t.localAddr,
+ })
+ connBegin := &stats.ConnBegin{
+ Client: true,
+ }
+ t.statsHandler.HandleConn(t.ctx, connBegin)
+ }
+ // Start the reader goroutine for incoming message. Each transport has
+ // a dedicated goroutine which reads HTTP2 frame from network. Then it
+ // dispatches the frame to the corresponding stream entity.
+ go t.reader()
+ // Send connection preface to server.
+ n, err := t.conn.Write(clientPreface)
+ if err != nil {
+ t.Close()
+ return nil, connectionErrorf(true, err, "transport: %v", err)
+ }
+ if n != len(clientPreface) {
+ t.Close()
+ return nil, connectionErrorf(true, err, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface))
+ }
+ if initialWindowSize != defaultWindowSize {
+ err = t.framer.writeSettings(true, http2.Setting{
+ ID: http2.SettingInitialWindowSize,
+ Val: uint32(initialWindowSize),
+ })
+ } else {
+ err = t.framer.writeSettings(true)
+ }
+ if err != nil {
+ t.Close()
+ return nil, connectionErrorf(true, err, "transport: %v", err)
+ }
+ // Adjust the connection flow control window if needed.
+ if delta := uint32(initialConnWindowSize - defaultWindowSize); delta > 0 {
+ if err := t.framer.writeWindowUpdate(true, 0, delta); err != nil {
+ t.Close()
+ return nil, connectionErrorf(true, err, "transport: %v", err)
+ }
+ }
+ go t.controller()
+ if t.kp.Time != infinity {
+ go t.keepalive()
+ }
+ t.writableChan <- 0
+ return t, nil
+}
+
+func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream {
+ // TODO(zhaoq): Handle uint32 overflow of Stream.id.
+ s := &Stream{
+ id: t.nextID,
+ done: make(chan struct{}),
+ goAway: make(chan struct{}),
+ method: callHdr.Method,
+ sendCompress: callHdr.SendCompress,
+ buf: newRecvBuffer(),
+ fc: &inFlow{limit: initialWindowSize},
+ sendQuotaPool: newQuotaPool(int(t.streamSendQuota)),
+ headerChan: make(chan struct{}),
+ }
+ t.nextID += 2
+ s.windowHandler = func(n int) {
+ t.updateWindow(s, uint32(n))
+ }
+ // The client side stream context should have exactly the same life cycle with the user provided context.
+ // That means, s.ctx should be read-only. And s.ctx is done iff ctx is done.
+ // So we use the original context here instead of creating a copy.
+ s.ctx = ctx
+ s.dec = &recvBufferReader{
+ ctx: s.ctx,
+ goAway: s.goAway,
+ recv: s.buf,
+ }
+ return s
+}
+
+// NewStream creates a stream and registers it into the transport as "active"
+// streams.
+func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) {
+ pr := &peer.Peer{
+ Addr: t.remoteAddr,
+ }
+ // Attach Auth info if there is any.
+ if t.authInfo != nil {
+ pr.AuthInfo = t.authInfo
+ }
+ userCtx := ctx
+ ctx = peer.NewContext(ctx, pr)
+ authData := make(map[string]string)
+ for _, c := range t.creds {
+ // Construct URI required to get auth request metadata.
+ var port string
+ if pos := strings.LastIndex(t.target, ":"); pos != -1 {
+ // Omit port if it is the default one.
+ if t.target[pos+1:] != "443" {
+ port = ":" + t.target[pos+1:]
+ }
+ }
+ pos := strings.LastIndex(callHdr.Method, "/")
+ if pos == -1 {
+ return nil, streamErrorf(codes.InvalidArgument, "transport: malformed method name: %q", callHdr.Method)
+ }
+ audience := "https://" + callHdr.Host + port + callHdr.Method[:pos]
+ data, err := c.GetRequestMetadata(ctx, audience)
+ if err != nil {
+ return nil, streamErrorf(codes.InvalidArgument, "transport: %v", err)
+ }
+ for k, v := range data {
+ authData[k] = v
+ }
+ }
+ t.mu.Lock()
+ if t.activeStreams == nil {
+ t.mu.Unlock()
+ return nil, ErrConnClosing
+ }
+ if t.state == draining {
+ t.mu.Unlock()
+ return nil, ErrStreamDrain
+ }
+ if t.state != reachable {
+ t.mu.Unlock()
+ return nil, ErrConnClosing
+ }
+ t.mu.Unlock()
+ sq, err := wait(ctx, nil, nil, t.shutdownChan, t.streamsQuota.acquire())
+ if err != nil {
+ return nil, err
+ }
+ // Returns the quota balance back.
+ if sq > 1 {
+ t.streamsQuota.add(sq - 1)
+ }
+ if _, err := wait(ctx, nil, nil, t.shutdownChan, t.writableChan); err != nil {
+ // Return the quota back now because there is no stream returned to the caller.
+ if _, ok := err.(StreamError); ok {
+ t.streamsQuota.add(1)
+ }
+ return nil, err
+ }
+ t.mu.Lock()
+ if t.state == draining {
+ t.mu.Unlock()
+ t.streamsQuota.add(1)
+ // Need to make t writable again so that the rpc in flight can still proceed.
+ t.writableChan <- 0
+ return nil, ErrStreamDrain
+ }
+ if t.state != reachable {
+ t.mu.Unlock()
+ return nil, ErrConnClosing
+ }
+ s := t.newStream(ctx, callHdr)
+ s.clientStatsCtx = userCtx
+ t.activeStreams[s.id] = s
+ // If the number of active streams change from 0 to 1, then check if keepalive
+ // has gone dormant. If so, wake it up.
+ if len(t.activeStreams) == 1 {
+ select {
+ case t.awakenKeepalive <- struct{}{}:
+ t.framer.writePing(false, false, [8]byte{})
+ default:
+ }
+ }
+
+ t.mu.Unlock()
+
+ // HPACK encodes various headers. Note that once WriteField(...) is
+ // called, the corresponding headers/continuation frame has to be sent
+ // because hpack.Encoder is stateful.
+ t.hBuf.Reset()
+ t.hEnc.WriteField(hpack.HeaderField{Name: ":method", Value: "POST"})
+ t.hEnc.WriteField(hpack.HeaderField{Name: ":scheme", Value: t.scheme})
+ t.hEnc.WriteField(hpack.HeaderField{Name: ":path", Value: callHdr.Method})
+ t.hEnc.WriteField(hpack.HeaderField{Name: ":authority", Value: callHdr.Host})
+ t.hEnc.WriteField(hpack.HeaderField{Name: "content-type", Value: "application/grpc"})
+ t.hEnc.WriteField(hpack.HeaderField{Name: "user-agent", Value: t.userAgent})
+ t.hEnc.WriteField(hpack.HeaderField{Name: "te", Value: "trailers"})
+
+ if callHdr.SendCompress != "" {
+ t.hEnc.WriteField(hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress})
+ }
+ if dl, ok := ctx.Deadline(); ok {
+ // Send out timeout regardless its value. The server can detect timeout context by itself.
+ timeout := dl.Sub(time.Now())
+ t.hEnc.WriteField(hpack.HeaderField{Name: "grpc-timeout", Value: encodeTimeout(timeout)})
+ }
+
+ for k, v := range authData {
+ // Capital header names are illegal in HTTP/2.
+ k = strings.ToLower(k)
+ t.hEnc.WriteField(hpack.HeaderField{Name: k, Value: v})
+ }
+ var (
+ hasMD bool
+ endHeaders bool
+ )
+ if md, ok := metadata.FromOutgoingContext(ctx); ok {
+ hasMD = true
+ for k, vv := range md {
+ // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set.
+ if isReservedHeader(k) {
+ continue
+ }
+ for _, v := range vv {
+ t.hEnc.WriteField(hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
+ }
+ }
+ }
+ if md, ok := t.md.(*metadata.MD); ok {
+ for k, vv := range *md {
+ if isReservedHeader(k) {
+ continue
+ }
+ for _, v := range vv {
+ t.hEnc.WriteField(hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
+ }
+ }
+ }
+ first := true
+ bufLen := t.hBuf.Len()
+ // Sends the headers in a single batch even when they span multiple frames.
+ for !endHeaders {
+ size := t.hBuf.Len()
+ if size > http2MaxFrameLen {
+ size = http2MaxFrameLen
+ } else {
+ endHeaders = true
+ }
+ var flush bool
+ if endHeaders && (hasMD || callHdr.Flush) {
+ flush = true
+ }
+ if first {
+ // Sends a HeadersFrame to server to start a new stream.
+ p := http2.HeadersFrameParam{
+ StreamID: s.id,
+ BlockFragment: t.hBuf.Next(size),
+ EndStream: false,
+ EndHeaders: endHeaders,
+ }
+ // Do a force flush for the buffered frames iff it is the last headers frame
+ // and there is header metadata to be sent. Otherwise, there is flushing until
+ // the corresponding data frame is written.
+ err = t.framer.writeHeaders(flush, p)
+ first = false
+ } else {
+ // Sends Continuation frames for the leftover headers.
+ err = t.framer.writeContinuation(flush, s.id, endHeaders, t.hBuf.Next(size))
+ }
+ if err != nil {
+ t.notifyError(err)
+ return nil, connectionErrorf(true, err, "transport: %v", err)
+ }
+ }
+ s.bytesSent = true
+
+ if t.statsHandler != nil {
+ outHeader := &stats.OutHeader{
+ Client: true,
+ WireLength: bufLen,
+ FullMethod: callHdr.Method,
+ RemoteAddr: t.remoteAddr,
+ LocalAddr: t.localAddr,
+ Compression: callHdr.SendCompress,
+ }
+ t.statsHandler.HandleRPC(s.clientStatsCtx, outHeader)
+ }
+ t.writableChan <- 0
+ return s, nil
+}
+
+// CloseStream clears the footprint of a stream when the stream is not needed any more.
+// This must not be executed in reader's goroutine.
+func (t *http2Client) CloseStream(s *Stream, err error) {
+ t.mu.Lock()
+ if t.activeStreams == nil {
+ t.mu.Unlock()
+ return
+ }
+ delete(t.activeStreams, s.id)
+ if t.state == draining && len(t.activeStreams) == 0 {
+ // The transport is draining and s is the last live stream on t.
+ t.mu.Unlock()
+ t.Close()
+ return
+ }
+ t.mu.Unlock()
+ // rstStream is true in case the stream is being closed at the client-side
+ // and the server needs to be intimated about it by sending a RST_STREAM
+ // frame.
+ // To make sure this frame is written to the wire before the headers of the
+ // next stream waiting for streamsQuota, we add to streamsQuota pool only
+ // after having acquired the writableChan to send RST_STREAM out (look at
+ // the controller() routine).
+ var rstStream bool
+ var rstError http2.ErrCode
+ defer func() {
+ // In case, the client doesn't have to send RST_STREAM to server
+ // we can safely add back to streamsQuota pool now.
+ if !rstStream {
+ t.streamsQuota.add(1)
+ return
+ }
+ t.controlBuf.put(&resetStream{s.id, rstError})
+ }()
+ s.mu.Lock()
+ rstStream = s.rstStream
+ rstError = s.rstError
+ if q := s.fc.resetPendingData(); q > 0 {
+ if n := t.fc.onRead(q); n > 0 {
+ t.controlBuf.put(&windowUpdate{0, n})
+ }
+ }
+ if s.state == streamDone {
+ s.mu.Unlock()
+ return
+ }
+ if !s.headerDone {
+ close(s.headerChan)
+ s.headerDone = true
+ }
+ s.state = streamDone
+ s.mu.Unlock()
+ if _, ok := err.(StreamError); ok {
+ rstStream = true
+ rstError = http2.ErrCodeCancel
+ }
+}
+
+// Close kicks off the shutdown process of the transport. This should be called
+// only once on a transport. Once it is called, the transport should not be
+// accessed any more.
+func (t *http2Client) Close() (err error) {
+ t.mu.Lock()
+ if t.state == closing {
+ t.mu.Unlock()
+ return
+ }
+ if t.state == reachable || t.state == draining {
+ close(t.errorChan)
+ }
+ t.state = closing
+ t.mu.Unlock()
+ close(t.shutdownChan)
+ err = t.conn.Close()
+ t.mu.Lock()
+ streams := t.activeStreams
+ t.activeStreams = nil
+ t.mu.Unlock()
+ // Notify all active streams.
+ for _, s := range streams {
+ s.mu.Lock()
+ if !s.headerDone {
+ close(s.headerChan)
+ s.headerDone = true
+ }
+ s.mu.Unlock()
+ s.write(recvMsg{err: ErrConnClosing})
+ }
+ if t.statsHandler != nil {
+ connEnd := &stats.ConnEnd{
+ Client: true,
+ }
+ t.statsHandler.HandleConn(t.ctx, connEnd)
+ }
+ return
+}
+
+func (t *http2Client) GracefulClose() error {
+ t.mu.Lock()
+ switch t.state {
+ case unreachable:
+ // The server may close the connection concurrently. t is not available for
+ // any streams. Close it now.
+ t.mu.Unlock()
+ t.Close()
+ return nil
+ case closing:
+ t.mu.Unlock()
+ return nil
+ }
+ // Notify the streams which were initiated after the server sent GOAWAY.
+ select {
+ case <-t.goAway:
+ n := t.prevGoAwayID
+ if n == 0 && t.nextID > 1 {
+ n = t.nextID - 2
+ }
+ m := t.goAwayID + 2
+ if m == 2 {
+ m = 1
+ }
+ for i := m; i <= n; i += 2 {
+ if s, ok := t.activeStreams[i]; ok {
+ close(s.goAway)
+ }
+ }
+ default:
+ }
+ if t.state == draining {
+ t.mu.Unlock()
+ return nil
+ }
+ t.state = draining
+ active := len(t.activeStreams)
+ t.mu.Unlock()
+ if active == 0 {
+ return t.Close()
+ }
+ return nil
+}
+
+// Write formats the data into HTTP2 data frame(s) and sends it out. The caller
+// should proceed only if Write returns nil.
+// TODO(zhaoq): opts.Delay is ignored in this implementation. Support it later
+// if it improves the performance.
+func (t *http2Client) Write(s *Stream, data []byte, opts *Options) error {
+ r := bytes.NewBuffer(data)
+ for {
+ var p []byte
+ if r.Len() > 0 {
+ size := http2MaxFrameLen
+ // Wait until the stream has some quota to send the data.
+ sq, err := wait(s.ctx, s.done, s.goAway, t.shutdownChan, s.sendQuotaPool.acquire())
+ if err != nil {
+ return err
+ }
+ // Wait until the transport has some quota to send the data.
+ tq, err := wait(s.ctx, s.done, s.goAway, t.shutdownChan, t.sendQuotaPool.acquire())
+ if err != nil {
+ return err
+ }
+ if sq < size {
+ size = sq
+ }
+ if tq < size {
+ size = tq
+ }
+ p = r.Next(size)
+ ps := len(p)
+ if ps < sq {
+ // Overbooked stream quota. Return it back.
+ s.sendQuotaPool.add(sq - ps)
+ }
+ if ps < tq {
+ // Overbooked transport quota. Return it back.
+ t.sendQuotaPool.add(tq - ps)
+ }
+ }
+ var (
+ endStream bool
+ forceFlush bool
+ )
+ if opts.Last && r.Len() == 0 {
+ endStream = true
+ }
+ // Indicate there is a writer who is about to write a data frame.
+ t.framer.adjustNumWriters(1)
+ // Got some quota. Try to acquire writing privilege on the transport.
+ if _, err := wait(s.ctx, s.done, s.goAway, t.shutdownChan, t.writableChan); err != nil {
+ if _, ok := err.(StreamError); ok || err == io.EOF {
+ // Return the connection quota back.
+ t.sendQuotaPool.add(len(p))
+ }
+ if t.framer.adjustNumWriters(-1) == 0 {
+ // This writer is the last one in this batch and has the
+ // responsibility to flush the buffered frames. It queues
+ // a flush request to controlBuf instead of flushing directly
+ // in order to avoid the race with other writing or flushing.
+ t.controlBuf.put(&flushIO{})
+ }
+ return err
+ }
+ select {
+ case <-s.ctx.Done():
+ t.sendQuotaPool.add(len(p))
+ if t.framer.adjustNumWriters(-1) == 0 {
+ t.controlBuf.put(&flushIO{})
+ }
+ t.writableChan <- 0
+ return ContextErr(s.ctx.Err())
+ default:
+ }
+ if r.Len() == 0 && t.framer.adjustNumWriters(0) == 1 {
+ // Do a force flush iff this is last frame for the entire gRPC message
+ // and the caller is the only writer at this moment.
+ forceFlush = true
+ }
+ // If WriteData fails, all the pending streams will be handled
+ // by http2Client.Close(). No explicit CloseStream() needs to be
+ // invoked.
+ if err := t.framer.writeData(forceFlush, s.id, endStream, p); err != nil {
+ t.notifyError(err)
+ return connectionErrorf(true, err, "transport: %v", err)
+ }
+ if t.framer.adjustNumWriters(-1) == 0 {
+ t.framer.flushWrite()
+ }
+ t.writableChan <- 0
+ if r.Len() == 0 {
+ break
+ }
+ }
+ if !opts.Last {
+ return nil
+ }
+ s.mu.Lock()
+ if s.state != streamDone {
+ s.state = streamWriteDone
+ }
+ s.mu.Unlock()
+ return nil
+}
+
+func (t *http2Client) getStream(f http2.Frame) (*Stream, bool) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ s, ok := t.activeStreams[f.Header().StreamID]
+ return s, ok
+}
+
+// updateWindow adjusts the inbound quota for the stream and the transport.
+// Window updates will deliver to the controller for sending when
+// the cumulative quota exceeds the corresponding threshold.
+func (t *http2Client) updateWindow(s *Stream, n uint32) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.state == streamDone {
+ return
+ }
+ if w := t.fc.onRead(n); w > 0 {
+ t.controlBuf.put(&windowUpdate{0, w})
+ }
+ if w := s.fc.onRead(n); w > 0 {
+ t.controlBuf.put(&windowUpdate{s.id, w})
+ }
+}
+
+func (t *http2Client) handleData(f *http2.DataFrame) {
+ size := f.Header().Length
+ if err := t.fc.onData(uint32(size)); err != nil {
+ t.notifyError(connectionErrorf(true, err, "%v", err))
+ return
+ }
+ // Select the right stream to dispatch.
+ s, ok := t.getStream(f)
+ if !ok {
+ if w := t.fc.onRead(uint32(size)); w > 0 {
+ t.controlBuf.put(&windowUpdate{0, w})
+ }
+ return
+ }
+ if size > 0 {
+ if f.Header().Flags.Has(http2.FlagDataPadded) {
+ if w := t.fc.onRead(uint32(size) - uint32(len(f.Data()))); w > 0 {
+ t.controlBuf.put(&windowUpdate{0, w})
+ }
+ }
+ s.mu.Lock()
+ if s.state == streamDone {
+ s.mu.Unlock()
+ // The stream has been closed. Release the corresponding quota.
+ if w := t.fc.onRead(uint32(size)); w > 0 {
+ t.controlBuf.put(&windowUpdate{0, w})
+ }
+ return
+ }
+ if err := s.fc.onData(uint32(size)); err != nil {
+ s.rstStream = true
+ s.rstError = http2.ErrCodeFlowControl
+ s.finish(status.New(codes.Internal, err.Error()))
+ s.mu.Unlock()
+ s.write(recvMsg{err: io.EOF})
+ return
+ }
+ if f.Header().Flags.Has(http2.FlagDataPadded) {
+ if w := s.fc.onRead(uint32(size) - uint32(len(f.Data()))); w > 0 {
+ t.controlBuf.put(&windowUpdate{s.id, w})
+ }
+ }
+ s.mu.Unlock()
+ // TODO(bradfitz, zhaoq): A copy is required here because there is no
+ // guarantee f.Data() is consumed before the arrival of next frame.
+ // Can this copy be eliminated?
+ if len(f.Data()) > 0 {
+ data := make([]byte, len(f.Data()))
+ copy(data, f.Data())
+ s.write(recvMsg{data: data})
+ }
+ }
+ // The server has closed the stream without sending trailers. Record that
+ // the read direction is closed, and set the status appropriately.
+ if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) {
+ s.mu.Lock()
+ if s.state == streamDone {
+ s.mu.Unlock()
+ return
+ }
+ s.finish(status.New(codes.Internal, "server closed the stream without sending trailers"))
+ s.mu.Unlock()
+ s.write(recvMsg{err: io.EOF})
+ }
+}
+
+func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) {
+ s, ok := t.getStream(f)
+ if !ok {
+ return
+ }
+ s.mu.Lock()
+ if s.state == streamDone {
+ s.mu.Unlock()
+ return
+ }
+ if !s.headerDone {
+ close(s.headerChan)
+ s.headerDone = true
+ }
+ statusCode, ok := http2ErrConvTab[http2.ErrCode(f.ErrCode)]
+ if !ok {
+ grpclog.Println("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error ", f.ErrCode)
+ statusCode = codes.Unknown
+ }
+ s.finish(status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %d", f.ErrCode))
+ s.mu.Unlock()
+ s.write(recvMsg{err: io.EOF})
+}
+
+func (t *http2Client) handleSettings(f *http2.SettingsFrame) {
+ if f.IsAck() {
+ return
+ }
+ var ss []http2.Setting
+ f.ForeachSetting(func(s http2.Setting) error {
+ ss = append(ss, s)
+ return nil
+ })
+ // The settings will be applied once the ack is sent.
+ t.controlBuf.put(&settings{ack: true, ss: ss})
+}
+
+func (t *http2Client) handlePing(f *http2.PingFrame) {
+ if f.IsAck() { // Do nothing.
+ return
+ }
+ pingAck := &ping{ack: true}
+ copy(pingAck.data[:], f.Data[:])
+ t.controlBuf.put(pingAck)
+}
+
+func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) {
+ if f.ErrCode == http2.ErrCodeEnhanceYourCalm {
+ grpclog.Printf("Client received GoAway with http2.ErrCodeEnhanceYourCalm.")
+ }
+ t.mu.Lock()
+ if t.state == reachable || t.state == draining {
+ if f.LastStreamID > 0 && f.LastStreamID%2 != 1 {
+ t.mu.Unlock()
+ t.notifyError(connectionErrorf(true, nil, "received illegal http2 GOAWAY frame: stream ID %d is even", f.LastStreamID))
+ return
+ }
+ select {
+ case <-t.goAway:
+ id := t.goAwayID
+ // t.goAway has been closed (i.e.,multiple GoAways).
+ if id < f.LastStreamID {
+ t.mu.Unlock()
+ t.notifyError(connectionErrorf(true, nil, "received illegal http2 GOAWAY frame: previously recv GOAWAY frame with LastStramID %d, currently recv %d", id, f.LastStreamID))
+ return
+ }
+ t.prevGoAwayID = id
+ t.goAwayID = f.LastStreamID
+ t.mu.Unlock()
+ return
+ default:
+ t.setGoAwayReason(f)
+ }
+ t.goAwayID = f.LastStreamID
+ close(t.goAway)
+ }
+ t.mu.Unlock()
+}
+
+// setGoAwayReason sets the value of t.goAwayReason based
+// on the GoAway frame received.
+// It expects a lock on transport's mutext to be held by
+// the caller.
+func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) {
+ t.goAwayReason = NoReason
+ switch f.ErrCode {
+ case http2.ErrCodeEnhanceYourCalm:
+ if string(f.DebugData()) == "too_many_pings" {
+ t.goAwayReason = TooManyPings
+ }
+ }
+}
+
+func (t *http2Client) GetGoAwayReason() GoAwayReason {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ return t.goAwayReason
+}
+
+func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) {
+ id := f.Header().StreamID
+ incr := f.Increment
+ if id == 0 {
+ t.sendQuotaPool.add(int(incr))
+ return
+ }
+ if s, ok := t.getStream(f); ok {
+ s.sendQuotaPool.add(int(incr))
+ }
+}
+
+// operateHeaders takes action on the decoded headers.
+func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) {
+ s, ok := t.getStream(frame)
+ if !ok {
+ return
+ }
+ s.bytesReceived = true
+ var state decodeState
+ for _, hf := range frame.Fields {
+ if err := state.processHeaderField(hf); err != nil {
+ s.mu.Lock()
+ if !s.headerDone {
+ close(s.headerChan)
+ s.headerDone = true
+ }
+ s.mu.Unlock()
+ s.write(recvMsg{err: err})
+ // Something wrong. Stops reading even when there is remaining.
+ return
+ }
+ }
+
+ endStream := frame.StreamEnded()
+ var isHeader bool
+ defer func() {
+ if t.statsHandler != nil {
+ if isHeader {
+ inHeader := &stats.InHeader{
+ Client: true,
+ WireLength: int(frame.Header().Length),
+ }
+ t.statsHandler.HandleRPC(s.clientStatsCtx, inHeader)
+ } else {
+ inTrailer := &stats.InTrailer{
+ Client: true,
+ WireLength: int(frame.Header().Length),
+ }
+ t.statsHandler.HandleRPC(s.clientStatsCtx, inTrailer)
+ }
+ }
+ }()
+
+ s.mu.Lock()
+ if !endStream {
+ s.recvCompress = state.encoding
+ }
+ if !s.headerDone {
+ if !endStream && len(state.mdata) > 0 {
+ s.header = state.mdata
+ }
+ close(s.headerChan)
+ s.headerDone = true
+ isHeader = true
+ }
+ if !endStream || s.state == streamDone {
+ s.mu.Unlock()
+ return
+ }
+
+ if len(state.mdata) > 0 {
+ s.trailer = state.mdata
+ }
+ s.finish(state.status())
+ s.mu.Unlock()
+ s.write(recvMsg{err: io.EOF})
+}
+
+func handleMalformedHTTP2(s *Stream, err error) {
+ s.mu.Lock()
+ if !s.headerDone {
+ close(s.headerChan)
+ s.headerDone = true
+ }
+ s.mu.Unlock()
+ s.write(recvMsg{err: err})
+}
+
+// reader runs as a separate goroutine in charge of reading data from network
+// connection.
+//
+// TODO(zhaoq): currently one reader per transport. Investigate whether this is
+// optimal.
+// TODO(zhaoq): Check the validity of the incoming frame sequence.
+func (t *http2Client) reader() {
+ // Check the validity of server preface.
+ frame, err := t.framer.readFrame()
+ if err != nil {
+ t.notifyError(err)
+ return
+ }
+ atomic.CompareAndSwapUint32(&t.activity, 0, 1)
+ sf, ok := frame.(*http2.SettingsFrame)
+ if !ok {
+ t.notifyError(err)
+ return
+ }
+ t.handleSettings(sf)
+
+ // loop to keep reading incoming messages on this transport.
+ for {
+ frame, err := t.framer.readFrame()
+ atomic.CompareAndSwapUint32(&t.activity, 0, 1)
+ if err != nil {
+ // Abort an active stream if the http2.Framer returns a
+ // http2.StreamError. This can happen only if the server's response
+ // is malformed http2.
+ if se, ok := err.(http2.StreamError); ok {
+ t.mu.Lock()
+ s := t.activeStreams[se.StreamID]
+ t.mu.Unlock()
+ if s != nil {
+ // use error detail to provide better err message
+ handleMalformedHTTP2(s, streamErrorf(http2ErrConvTab[se.Code], "%v", t.framer.errorDetail()))
+ }
+ continue
+ } else {
+ // Transport error.
+ t.notifyError(err)
+ return
+ }
+ }
+ switch frame := frame.(type) {
+ case *http2.MetaHeadersFrame:
+ t.operateHeaders(frame)
+ case *http2.DataFrame:
+ t.handleData(frame)
+ case *http2.RSTStreamFrame:
+ t.handleRSTStream(frame)
+ case *http2.SettingsFrame:
+ t.handleSettings(frame)
+ case *http2.PingFrame:
+ t.handlePing(frame)
+ case *http2.GoAwayFrame:
+ t.handleGoAway(frame)
+ case *http2.WindowUpdateFrame:
+ t.handleWindowUpdate(frame)
+ default:
+ grpclog.Printf("transport: http2Client.reader got unhandled frame type %v.", frame)
+ }
+ }
+}
+
+func (t *http2Client) applySettings(ss []http2.Setting) {
+ for _, s := range ss {
+ switch s.ID {
+ case http2.SettingMaxConcurrentStreams:
+ // TODO(zhaoq): This is a hack to avoid significant refactoring of the
+ // code to deal with the unrealistic int32 overflow. Probably will try
+ // to find a better way to handle this later.
+ if s.Val > math.MaxInt32 {
+ s.Val = math.MaxInt32
+ }
+ t.mu.Lock()
+ ms := t.maxStreams
+ t.maxStreams = int(s.Val)
+ t.mu.Unlock()
+ t.streamsQuota.add(int(s.Val) - ms)
+ case http2.SettingInitialWindowSize:
+ t.mu.Lock()
+ for _, stream := range t.activeStreams {
+ // Adjust the sending quota for each stream.
+ stream.sendQuotaPool.add(int(s.Val - t.streamSendQuota))
+ }
+ t.streamSendQuota = s.Val
+ t.mu.Unlock()
+ }
+ }
+}
+
+// controller running in a separate goroutine takes charge of sending control
+// frames (e.g., window update, reset stream, setting, etc.) to the server.
+func (t *http2Client) controller() {
+ for {
+ select {
+ case i := <-t.controlBuf.get():
+ t.controlBuf.load()
+ select {
+ case <-t.writableChan:
+ switch i := i.(type) {
+ case *windowUpdate:
+ t.framer.writeWindowUpdate(true, i.streamID, i.increment)
+ case *settings:
+ if i.ack {
+ t.framer.writeSettingsAck(true)
+ t.applySettings(i.ss)
+ } else {
+ t.framer.writeSettings(true, i.ss...)
+ }
+ case *resetStream:
+ // If the server needs to be to intimated about stream closing,
+ // then we need to make sure the RST_STREAM frame is written to
+ // the wire before the headers of the next stream waiting on
+ // streamQuota. We ensure this by adding to the streamsQuota pool
+ // only after having acquired the writableChan to send RST_STREAM.
+ t.streamsQuota.add(1)
+ t.framer.writeRSTStream(true, i.streamID, i.code)
+ case *flushIO:
+ t.framer.flushWrite()
+ case *ping:
+ t.framer.writePing(true, i.ack, i.data)
+ default:
+ grpclog.Printf("transport: http2Client.controller got unexpected item type %v\n", i)
+ }
+ t.writableChan <- 0
+ continue
+ case <-t.shutdownChan:
+ return
+ }
+ case <-t.shutdownChan:
+ return
+ }
+ }
+}
+
+// keepalive running in a separate goroutune makes sure the connection is alive by sending pings.
+func (t *http2Client) keepalive() {
+ p := &ping{data: [8]byte{}}
+ timer := time.NewTimer(t.kp.Time)
+ for {
+ select {
+ case <-timer.C:
+ if atomic.CompareAndSwapUint32(&t.activity, 1, 0) {
+ timer.Reset(t.kp.Time)
+ continue
+ }
+ // Check if keepalive should go dormant.
+ t.mu.Lock()
+ if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream {
+ // Make awakenKeepalive writable.
+ <-t.awakenKeepalive
+ t.mu.Unlock()
+ select {
+ case <-t.awakenKeepalive:
+ // If the control gets here a ping has been sent
+ // need to reset the timer with keepalive.Timeout.
+ case <-t.shutdownChan:
+ return
+ }
+ } else {
+ t.mu.Unlock()
+ // Send ping.
+ t.controlBuf.put(p)
+ }
+
+ // By the time control gets here a ping has been sent one way or the other.
+ timer.Reset(t.kp.Timeout)
+ select {
+ case <-timer.C:
+ if atomic.CompareAndSwapUint32(&t.activity, 1, 0) {
+ timer.Reset(t.kp.Time)
+ continue
+ }
+ t.Close()
+ return
+ case <-t.shutdownChan:
+ if !timer.Stop() {
+ <-timer.C
+ }
+ return
+ }
+ case <-t.shutdownChan:
+ if !timer.Stop() {
+ <-timer.C
+ }
+ return
+ }
+ }
+}
+
+func (t *http2Client) Error() <-chan struct{} {
+ return t.errorChan
+}
+
+func (t *http2Client) GoAway() <-chan struct{} {
+ return t.goAway
+}
+
+func (t *http2Client) notifyError(err error) {
+ t.mu.Lock()
+ // make sure t.errorChan is closed only once.
+ if t.state == draining {
+ t.mu.Unlock()
+ t.Close()
+ return
+ }
+ if t.state == reachable {
+ t.state = unreachable
+ close(t.errorChan)
+ grpclog.Printf("transport: http2Client.notifyError got notified that the client transport was broken %v.", err)
+ }
+ t.mu.Unlock()
+}
diff --git a/vendor/google.golang.org/grpc/transport/http2_server.go b/vendor/google.golang.org/grpc/transport/http2_server.go
new file mode 100644
index 0000000..14cd19c
--- /dev/null
+++ b/vendor/google.golang.org/grpc/transport/http2_server.go
@@ -0,0 +1,1070 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+package transport
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "math"
+ "math/rand"
+ "net"
+ "strconv"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/golang/protobuf/proto"
+ "golang.org/x/net/context"
+ "golang.org/x/net/http2"
+ "golang.org/x/net/http2/hpack"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/grpclog"
+ "google.golang.org/grpc/keepalive"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/peer"
+ "google.golang.org/grpc/stats"
+ "google.golang.org/grpc/status"
+ "google.golang.org/grpc/tap"
+)
+
+// ErrIllegalHeaderWrite indicates that setting header is illegal because of
+// the stream's state.
+var ErrIllegalHeaderWrite = errors.New("transport: the stream is done or WriteHeader was already called")
+
+// http2Server implements the ServerTransport interface with HTTP2.
+type http2Server struct {
+ ctx context.Context
+ conn net.Conn
+ remoteAddr net.Addr
+ localAddr net.Addr
+ maxStreamID uint32 // max stream ID ever seen
+ authInfo credentials.AuthInfo // auth info about the connection
+ inTapHandle tap.ServerInHandle
+ // writableChan synchronizes write access to the transport.
+ // A writer acquires the write lock by receiving a value on writableChan
+ // and releases it by sending on writableChan.
+ writableChan chan int
+ // shutdownChan is closed when Close is called.
+ // Blocking operations should select on shutdownChan to avoid
+ // blocking forever after Close.
+ shutdownChan chan struct{}
+ framer *framer
+ hBuf *bytes.Buffer // the buffer for HPACK encoding
+ hEnc *hpack.Encoder // HPACK encoder
+
+ // The max number of concurrent streams.
+ maxStreams uint32
+ // controlBuf delivers all the control related tasks (e.g., window
+ // updates, reset streams, and various settings) to the controller.
+ controlBuf *recvBuffer
+ fc *inFlow
+ // sendQuotaPool provides flow control to outbound message.
+ sendQuotaPool *quotaPool
+
+ stats stats.Handler
+
+ // Flag to keep track of reading activity on transport.
+ // 1 is true and 0 is false.
+ activity uint32 // Accessed atomically.
+ // Keepalive and max-age parameters for the server.
+ kp keepalive.ServerParameters
+
+ // Keepalive enforcement policy.
+ kep keepalive.EnforcementPolicy
+ // The time instance last ping was received.
+ lastPingAt time.Time
+ // Number of times the client has violated keepalive ping policy so far.
+ pingStrikes uint8
+ // Flag to signify that number of ping strikes should be reset to 0.
+ // This is set whenever data or header frames are sent.
+ // 1 means yes.
+ resetPingStrikes uint32 // Accessed atomically.
+
+ mu sync.Mutex // guard the following
+ state transportState
+ activeStreams map[uint32]*Stream
+ // the per-stream outbound flow control window size set by the peer.
+ streamSendQuota uint32
+ // idle is the time instant when the connection went idle.
+ // This is either the begining of the connection or when the number of
+ // RPCs go down to 0.
+ // When the connection is busy, this value is set to 0.
+ idle time.Time
+}
+
+// newHTTP2Server constructs a ServerTransport based on HTTP2. ConnectionError is
+// returned if something goes wrong.
+func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err error) {
+ framer := newFramer(conn)
+ // Send initial settings as connection preface to client.
+ var settings []http2.Setting
+ // TODO(zhaoq): Have a better way to signal "no limit" because 0 is
+ // permitted in the HTTP2 spec.
+ maxStreams := config.MaxStreams
+ if maxStreams == 0 {
+ maxStreams = math.MaxUint32
+ } else {
+ settings = append(settings, http2.Setting{
+ ID: http2.SettingMaxConcurrentStreams,
+ Val: maxStreams,
+ })
+ }
+ if initialWindowSize != defaultWindowSize {
+ settings = append(settings, http2.Setting{
+ ID: http2.SettingInitialWindowSize,
+ Val: uint32(initialWindowSize)})
+ }
+ if err := framer.writeSettings(true, settings...); err != nil {
+ return nil, connectionErrorf(true, err, "transport: %v", err)
+ }
+ // Adjust the connection flow control window if needed.
+ if delta := uint32(initialConnWindowSize - defaultWindowSize); delta > 0 {
+ if err := framer.writeWindowUpdate(true, 0, delta); err != nil {
+ return nil, connectionErrorf(true, err, "transport: %v", err)
+ }
+ }
+ kp := config.KeepaliveParams
+ if kp.MaxConnectionIdle == 0 {
+ kp.MaxConnectionIdle = defaultMaxConnectionIdle
+ }
+ if kp.MaxConnectionAge == 0 {
+ kp.MaxConnectionAge = defaultMaxConnectionAge
+ }
+ // Add a jitter to MaxConnectionAge.
+ kp.MaxConnectionAge += getJitter(kp.MaxConnectionAge)
+ if kp.MaxConnectionAgeGrace == 0 {
+ kp.MaxConnectionAgeGrace = defaultMaxConnectionAgeGrace
+ }
+ if kp.Time == 0 {
+ kp.Time = defaultServerKeepaliveTime
+ }
+ if kp.Timeout == 0 {
+ kp.Timeout = defaultServerKeepaliveTimeout
+ }
+ kep := config.KeepalivePolicy
+ if kep.MinTime == 0 {
+ kep.MinTime = defaultKeepalivePolicyMinTime
+ }
+ var buf bytes.Buffer
+ t := &http2Server{
+ ctx: context.Background(),
+ conn: conn,
+ remoteAddr: conn.RemoteAddr(),
+ localAddr: conn.LocalAddr(),
+ authInfo: config.AuthInfo,
+ framer: framer,
+ hBuf: &buf,
+ hEnc: hpack.NewEncoder(&buf),
+ maxStreams: maxStreams,
+ inTapHandle: config.InTapHandle,
+ controlBuf: newRecvBuffer(),
+ fc: &inFlow{limit: initialConnWindowSize},
+ sendQuotaPool: newQuotaPool(defaultWindowSize),
+ state: reachable,
+ writableChan: make(chan int, 1),
+ shutdownChan: make(chan struct{}),
+ activeStreams: make(map[uint32]*Stream),
+ streamSendQuota: defaultWindowSize,
+ stats: config.StatsHandler,
+ kp: kp,
+ idle: time.Now(),
+ kep: kep,
+ }
+ if t.stats != nil {
+ t.ctx = t.stats.TagConn(t.ctx, &stats.ConnTagInfo{
+ RemoteAddr: t.remoteAddr,
+ LocalAddr: t.localAddr,
+ })
+ connBegin := &stats.ConnBegin{}
+ t.stats.HandleConn(t.ctx, connBegin)
+ }
+ go t.controller()
+ go t.keepalive()
+ t.writableChan <- 0
+ return t, nil
+}
+
+// operateHeader takes action on the decoded headers.
+func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func(*Stream), traceCtx func(context.Context, string) context.Context) (close bool) {
+ buf := newRecvBuffer()
+ s := &Stream{
+ id: frame.Header().StreamID,
+ st: t,
+ buf: buf,
+ fc: &inFlow{limit: initialWindowSize},
+ }
+
+ var state decodeState
+ for _, hf := range frame.Fields {
+ if err := state.processHeaderField(hf); err != nil {
+ if se, ok := err.(StreamError); ok {
+ t.controlBuf.put(&resetStream{s.id, statusCodeConvTab[se.Code]})
+ }
+ return
+ }
+ }
+
+ if frame.StreamEnded() {
+ // s is just created by the caller. No lock needed.
+ s.state = streamReadDone
+ }
+ s.recvCompress = state.encoding
+ if state.timeoutSet {
+ s.ctx, s.cancel = context.WithTimeout(t.ctx, state.timeout)
+ } else {
+ s.ctx, s.cancel = context.WithCancel(t.ctx)
+ }
+ pr := &peer.Peer{
+ Addr: t.remoteAddr,
+ }
+ // Attach Auth info if there is any.
+ if t.authInfo != nil {
+ pr.AuthInfo = t.authInfo
+ }
+ s.ctx = peer.NewContext(s.ctx, pr)
+ // Cache the current stream to the context so that the server application
+ // can find out. Required when the server wants to send some metadata
+ // back to the client (unary call only).
+ s.ctx = newContextWithStream(s.ctx, s)
+ // Attach the received metadata to the context.
+ if len(state.mdata) > 0 {
+ s.ctx = metadata.NewIncomingContext(s.ctx, state.mdata)
+ }
+
+ s.dec = &recvBufferReader{
+ ctx: s.ctx,
+ recv: s.buf,
+ }
+ s.recvCompress = state.encoding
+ s.method = state.method
+ if t.inTapHandle != nil {
+ var err error
+ info := &tap.Info{
+ FullMethodName: state.method,
+ }
+ s.ctx, err = t.inTapHandle(s.ctx, info)
+ if err != nil {
+ // TODO: Log the real error.
+ t.controlBuf.put(&resetStream{s.id, http2.ErrCodeRefusedStream})
+ return
+ }
+ }
+ t.mu.Lock()
+ if t.state != reachable {
+ t.mu.Unlock()
+ return
+ }
+ if uint32(len(t.activeStreams)) >= t.maxStreams {
+ t.mu.Unlock()
+ t.controlBuf.put(&resetStream{s.id, http2.ErrCodeRefusedStream})
+ return
+ }
+ if s.id%2 != 1 || s.id <= t.maxStreamID {
+ t.mu.Unlock()
+ // illegal gRPC stream id.
+ grpclog.Println("transport: http2Server.HandleStreams received an illegal stream id: ", s.id)
+ return true
+ }
+ t.maxStreamID = s.id
+ s.sendQuotaPool = newQuotaPool(int(t.streamSendQuota))
+ t.activeStreams[s.id] = s
+ if len(t.activeStreams) == 1 {
+ t.idle = time.Time{}
+ }
+ t.mu.Unlock()
+ s.windowHandler = func(n int) {
+ t.updateWindow(s, uint32(n))
+ }
+ s.ctx = traceCtx(s.ctx, s.method)
+ if t.stats != nil {
+ s.ctx = t.stats.TagRPC(s.ctx, &stats.RPCTagInfo{FullMethodName: s.method})
+ inHeader := &stats.InHeader{
+ FullMethod: s.method,
+ RemoteAddr: t.remoteAddr,
+ LocalAddr: t.localAddr,
+ Compression: s.recvCompress,
+ WireLength: int(frame.Header().Length),
+ }
+ t.stats.HandleRPC(s.ctx, inHeader)
+ }
+ handle(s)
+ return
+}
+
+// HandleStreams receives incoming streams using the given handler. This is
+// typically run in a separate goroutine.
+// traceCtx attaches trace to ctx and returns the new context.
+func (t *http2Server) HandleStreams(handle func(*Stream), traceCtx func(context.Context, string) context.Context) {
+ // Check the validity of client preface.
+ preface := make([]byte, len(clientPreface))
+ if _, err := io.ReadFull(t.conn, preface); err != nil {
+ grpclog.Printf("transport: http2Server.HandleStreams failed to receive the preface from client: %v", err)
+ t.Close()
+ return
+ }
+ if !bytes.Equal(preface, clientPreface) {
+ grpclog.Printf("transport: http2Server.HandleStreams received bogus greeting from client: %q", preface)
+ t.Close()
+ return
+ }
+
+ frame, err := t.framer.readFrame()
+ if err == io.EOF || err == io.ErrUnexpectedEOF {
+ t.Close()
+ return
+ }
+ if err != nil {
+ grpclog.Printf("transport: http2Server.HandleStreams failed to read frame: %v", err)
+ t.Close()
+ return
+ }
+ atomic.StoreUint32(&t.activity, 1)
+ sf, ok := frame.(*http2.SettingsFrame)
+ if !ok {
+ grpclog.Printf("transport: http2Server.HandleStreams saw invalid preface type %T from client", frame)
+ t.Close()
+ return
+ }
+ t.handleSettings(sf)
+
+ for {
+ frame, err := t.framer.readFrame()
+ atomic.StoreUint32(&t.activity, 1)
+ if err != nil {
+ if se, ok := err.(http2.StreamError); ok {
+ t.mu.Lock()
+ s := t.activeStreams[se.StreamID]
+ t.mu.Unlock()
+ if s != nil {
+ t.closeStream(s)
+ }
+ t.controlBuf.put(&resetStream{se.StreamID, se.Code})
+ continue
+ }
+ if err == io.EOF || err == io.ErrUnexpectedEOF {
+ t.Close()
+ return
+ }
+ grpclog.Printf("transport: http2Server.HandleStreams failed to read frame: %v", err)
+ t.Close()
+ return
+ }
+ switch frame := frame.(type) {
+ case *http2.MetaHeadersFrame:
+ if t.operateHeaders(frame, handle, traceCtx) {
+ t.Close()
+ break
+ }
+ case *http2.DataFrame:
+ t.handleData(frame)
+ case *http2.RSTStreamFrame:
+ t.handleRSTStream(frame)
+ case *http2.SettingsFrame:
+ t.handleSettings(frame)
+ case *http2.PingFrame:
+ t.handlePing(frame)
+ case *http2.WindowUpdateFrame:
+ t.handleWindowUpdate(frame)
+ case *http2.GoAwayFrame:
+ // TODO: Handle GoAway from the client appropriately.
+ default:
+ grpclog.Printf("transport: http2Server.HandleStreams found unhandled frame type %v.", frame)
+ }
+ }
+}
+
+func (t *http2Server) getStream(f http2.Frame) (*Stream, bool) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.activeStreams == nil {
+ // The transport is closing.
+ return nil, false
+ }
+ s, ok := t.activeStreams[f.Header().StreamID]
+ if !ok {
+ // The stream is already done.
+ return nil, false
+ }
+ return s, true
+}
+
+// updateWindow adjusts the inbound quota for the stream and the transport.
+// Window updates will deliver to the controller for sending when
+// the cumulative quota exceeds the corresponding threshold.
+func (t *http2Server) updateWindow(s *Stream, n uint32) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.state == streamDone {
+ return
+ }
+ if w := t.fc.onRead(n); w > 0 {
+ t.controlBuf.put(&windowUpdate{0, w})
+ }
+ if w := s.fc.onRead(n); w > 0 {
+ t.controlBuf.put(&windowUpdate{s.id, w})
+ }
+}
+
+func (t *http2Server) handleData(f *http2.DataFrame) {
+ size := f.Header().Length
+ if err := t.fc.onData(uint32(size)); err != nil {
+ grpclog.Printf("transport: http2Server %v", err)
+ t.Close()
+ return
+ }
+ // Select the right stream to dispatch.
+ s, ok := t.getStream(f)
+ if !ok {
+ if w := t.fc.onRead(uint32(size)); w > 0 {
+ t.controlBuf.put(&windowUpdate{0, w})
+ }
+ return
+ }
+ if size > 0 {
+ if f.Header().Flags.Has(http2.FlagDataPadded) {
+ if w := t.fc.onRead(uint32(size) - uint32(len(f.Data()))); w > 0 {
+ t.controlBuf.put(&windowUpdate{0, w})
+ }
+ }
+ s.mu.Lock()
+ if s.state == streamDone {
+ s.mu.Unlock()
+ // The stream has been closed. Release the corresponding quota.
+ if w := t.fc.onRead(uint32(size)); w > 0 {
+ t.controlBuf.put(&windowUpdate{0, w})
+ }
+ return
+ }
+ if err := s.fc.onData(uint32(size)); err != nil {
+ s.mu.Unlock()
+ t.closeStream(s)
+ t.controlBuf.put(&resetStream{s.id, http2.ErrCodeFlowControl})
+ return
+ }
+ if f.Header().Flags.Has(http2.FlagDataPadded) {
+ if w := s.fc.onRead(uint32(size) - uint32(len(f.Data()))); w > 0 {
+ t.controlBuf.put(&windowUpdate{s.id, w})
+ }
+ }
+ s.mu.Unlock()
+ // TODO(bradfitz, zhaoq): A copy is required here because there is no
+ // guarantee f.Data() is consumed before the arrival of next frame.
+ // Can this copy be eliminated?
+ if len(f.Data()) > 0 {
+ data := make([]byte, len(f.Data()))
+ copy(data, f.Data())
+ s.write(recvMsg{data: data})
+ }
+ }
+ if f.Header().Flags.Has(http2.FlagDataEndStream) {
+ // Received the end of stream from the client.
+ s.mu.Lock()
+ if s.state != streamDone {
+ s.state = streamReadDone
+ }
+ s.mu.Unlock()
+ s.write(recvMsg{err: io.EOF})
+ }
+}
+
+func (t *http2Server) handleRSTStream(f *http2.RSTStreamFrame) {
+ s, ok := t.getStream(f)
+ if !ok {
+ return
+ }
+ t.closeStream(s)
+}
+
+func (t *http2Server) handleSettings(f *http2.SettingsFrame) {
+ if f.IsAck() {
+ return
+ }
+ var ss []http2.Setting
+ f.ForeachSetting(func(s http2.Setting) error {
+ ss = append(ss, s)
+ return nil
+ })
+ // The settings will be applied once the ack is sent.
+ t.controlBuf.put(&settings{ack: true, ss: ss})
+}
+
+const (
+ maxPingStrikes = 2
+ defaultPingTimeout = 2 * time.Hour
+)
+
+func (t *http2Server) handlePing(f *http2.PingFrame) {
+ if f.IsAck() { // Do nothing.
+ return
+ }
+ pingAck := &ping{ack: true}
+ copy(pingAck.data[:], f.Data[:])
+ t.controlBuf.put(pingAck)
+
+ now := time.Now()
+ defer func() {
+ t.lastPingAt = now
+ }()
+ // A reset ping strikes means that we don't need to check for policy
+ // violation for this ping and the pingStrikes counter should be set
+ // to 0.
+ if atomic.CompareAndSwapUint32(&t.resetPingStrikes, 1, 0) {
+ t.pingStrikes = 0
+ return
+ }
+ t.mu.Lock()
+ ns := len(t.activeStreams)
+ t.mu.Unlock()
+ if ns < 1 && !t.kep.PermitWithoutStream {
+ // Keepalive shouldn't be active thus, this new ping should
+ // have come after atleast defaultPingTimeout.
+ if t.lastPingAt.Add(defaultPingTimeout).After(now) {
+ t.pingStrikes++
+ }
+ } else {
+ // Check if keepalive policy is respected.
+ if t.lastPingAt.Add(t.kep.MinTime).After(now) {
+ t.pingStrikes++
+ }
+ }
+
+ if t.pingStrikes > maxPingStrikes {
+ // Send goaway and close the connection.
+ t.controlBuf.put(&goAway{code: http2.ErrCodeEnhanceYourCalm, debugData: []byte("too_many_pings")})
+ }
+}
+
+func (t *http2Server) handleWindowUpdate(f *http2.WindowUpdateFrame) {
+ id := f.Header().StreamID
+ incr := f.Increment
+ if id == 0 {
+ t.sendQuotaPool.add(int(incr))
+ return
+ }
+ if s, ok := t.getStream(f); ok {
+ s.sendQuotaPool.add(int(incr))
+ }
+}
+
+func (t *http2Server) writeHeaders(s *Stream, b *bytes.Buffer, endStream bool) error {
+ first := true
+ endHeaders := false
+ var err error
+ defer func() {
+ if err == nil {
+ // Reset ping strikes when seding headers since that might cause the
+ // peer to send ping.
+ atomic.StoreUint32(&t.resetPingStrikes, 1)
+ }
+ }()
+ // Sends the headers in a single batch.
+ for !endHeaders {
+ size := t.hBuf.Len()
+ if size > http2MaxFrameLen {
+ size = http2MaxFrameLen
+ } else {
+ endHeaders = true
+ }
+ if first {
+ p := http2.HeadersFrameParam{
+ StreamID: s.id,
+ BlockFragment: b.Next(size),
+ EndStream: endStream,
+ EndHeaders: endHeaders,
+ }
+ err = t.framer.writeHeaders(endHeaders, p)
+ first = false
+ } else {
+ err = t.framer.writeContinuation(endHeaders, s.id, endHeaders, b.Next(size))
+ }
+ if err != nil {
+ t.Close()
+ return connectionErrorf(true, err, "transport: %v", err)
+ }
+ }
+ return nil
+}
+
+// WriteHeader sends the header metedata md back to the client.
+func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error {
+ s.mu.Lock()
+ if s.headerOk || s.state == streamDone {
+ s.mu.Unlock()
+ return ErrIllegalHeaderWrite
+ }
+ s.headerOk = true
+ if md.Len() > 0 {
+ if s.header.Len() > 0 {
+ s.header = metadata.Join(s.header, md)
+ } else {
+ s.header = md
+ }
+ }
+ md = s.header
+ s.mu.Unlock()
+ if _, err := wait(s.ctx, nil, nil, t.shutdownChan, t.writableChan); err != nil {
+ return err
+ }
+ t.hBuf.Reset()
+ t.hEnc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
+ t.hEnc.WriteField(hpack.HeaderField{Name: "content-type", Value: "application/grpc"})
+ if s.sendCompress != "" {
+ t.hEnc.WriteField(hpack.HeaderField{Name: "grpc-encoding", Value: s.sendCompress})
+ }
+ for k, vv := range md {
+ if isReservedHeader(k) {
+ // Clients don't tolerate reading restricted headers after some non restricted ones were sent.
+ continue
+ }
+ for _, v := range vv {
+ t.hEnc.WriteField(hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
+ }
+ }
+ bufLen := t.hBuf.Len()
+ if err := t.writeHeaders(s, t.hBuf, false); err != nil {
+ return err
+ }
+ if t.stats != nil {
+ outHeader := &stats.OutHeader{
+ WireLength: bufLen,
+ }
+ t.stats.HandleRPC(s.Context(), outHeader)
+ }
+ t.writableChan <- 0
+ return nil
+}
+
+// WriteStatus sends stream status to the client and terminates the stream.
+// There is no further I/O operations being able to perform on this stream.
+// TODO(zhaoq): Now it indicates the end of entire stream. Revisit if early
+// OK is adopted.
+func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error {
+ var headersSent, hasHeader bool
+ s.mu.Lock()
+ if s.state == streamDone {
+ s.mu.Unlock()
+ return nil
+ }
+ if s.headerOk {
+ headersSent = true
+ }
+ if s.header.Len() > 0 {
+ hasHeader = true
+ }
+ s.mu.Unlock()
+
+ if !headersSent && hasHeader {
+ t.WriteHeader(s, nil)
+ headersSent = true
+ }
+
+ if _, err := wait(s.ctx, nil, nil, t.shutdownChan, t.writableChan); err != nil {
+ return err
+ }
+ t.hBuf.Reset()
+ if !headersSent {
+ t.hEnc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"})
+ t.hEnc.WriteField(hpack.HeaderField{Name: "content-type", Value: "application/grpc"})
+ }
+ t.hEnc.WriteField(
+ hpack.HeaderField{
+ Name: "grpc-status",
+ Value: strconv.Itoa(int(st.Code())),
+ })
+ t.hEnc.WriteField(hpack.HeaderField{Name: "grpc-message", Value: encodeGrpcMessage(st.Message())})
+
+ if p := st.Proto(); p != nil && len(p.Details) > 0 {
+ stBytes, err := proto.Marshal(p)
+ if err != nil {
+ // TODO: return error instead, when callers are able to handle it.
+ panic(err)
+ }
+
+ t.hEnc.WriteField(hpack.HeaderField{Name: "grpc-status-details-bin", Value: encodeBinHeader(stBytes)})
+ }
+
+ // Attach the trailer metadata.
+ for k, vv := range s.trailer {
+ // Clients don't tolerate reading restricted headers after some non restricted ones were sent.
+ if isReservedHeader(k) {
+ continue
+ }
+ for _, v := range vv {
+ t.hEnc.WriteField(hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)})
+ }
+ }
+ bufLen := t.hBuf.Len()
+ if err := t.writeHeaders(s, t.hBuf, true); err != nil {
+ t.Close()
+ return err
+ }
+ if t.stats != nil {
+ outTrailer := &stats.OutTrailer{
+ WireLength: bufLen,
+ }
+ t.stats.HandleRPC(s.Context(), outTrailer)
+ }
+ t.closeStream(s)
+ t.writableChan <- 0
+ return nil
+}
+
+// Write converts the data into HTTP2 data frame and sends it out. Non-nil error
+// is returns if it fails (e.g., framing error, transport error).
+func (t *http2Server) Write(s *Stream, data []byte, opts *Options) (err error) {
+ // TODO(zhaoq): Support multi-writers for a single stream.
+ var writeHeaderFrame bool
+ s.mu.Lock()
+ if s.state == streamDone {
+ s.mu.Unlock()
+ return streamErrorf(codes.Unknown, "the stream has been done")
+ }
+ if !s.headerOk {
+ writeHeaderFrame = true
+ }
+ s.mu.Unlock()
+ if writeHeaderFrame {
+ t.WriteHeader(s, nil)
+ }
+ defer func() {
+ if err == nil {
+ // Reset ping strikes when sending data since this might cause
+ // the peer to send ping.
+ atomic.StoreUint32(&t.resetPingStrikes, 1)
+ }
+ }()
+ r := bytes.NewBuffer(data)
+ for {
+ if r.Len() == 0 {
+ return nil
+ }
+ size := http2MaxFrameLen
+ // Wait until the stream has some quota to send the data.
+ sq, err := wait(s.ctx, nil, nil, t.shutdownChan, s.sendQuotaPool.acquire())
+ if err != nil {
+ return err
+ }
+ // Wait until the transport has some quota to send the data.
+ tq, err := wait(s.ctx, nil, nil, t.shutdownChan, t.sendQuotaPool.acquire())
+ if err != nil {
+ return err
+ }
+ if sq < size {
+ size = sq
+ }
+ if tq < size {
+ size = tq
+ }
+ p := r.Next(size)
+ ps := len(p)
+ if ps < sq {
+ // Overbooked stream quota. Return it back.
+ s.sendQuotaPool.add(sq - ps)
+ }
+ if ps < tq {
+ // Overbooked transport quota. Return it back.
+ t.sendQuotaPool.add(tq - ps)
+ }
+ t.framer.adjustNumWriters(1)
+ // Got some quota. Try to acquire writing privilege on the
+ // transport.
+ if _, err := wait(s.ctx, nil, nil, t.shutdownChan, t.writableChan); err != nil {
+ if _, ok := err.(StreamError); ok {
+ // Return the connection quota back.
+ t.sendQuotaPool.add(ps)
+ }
+ if t.framer.adjustNumWriters(-1) == 0 {
+ // This writer is the last one in this batch and has the
+ // responsibility to flush the buffered frames. It queues
+ // a flush request to controlBuf instead of flushing directly
+ // in order to avoid the race with other writing or flushing.
+ t.controlBuf.put(&flushIO{})
+ }
+ return err
+ }
+ select {
+ case <-s.ctx.Done():
+ t.sendQuotaPool.add(ps)
+ if t.framer.adjustNumWriters(-1) == 0 {
+ t.controlBuf.put(&flushIO{})
+ }
+ t.writableChan <- 0
+ return ContextErr(s.ctx.Err())
+ default:
+ }
+ var forceFlush bool
+ if r.Len() == 0 && t.framer.adjustNumWriters(0) == 1 && !opts.Last {
+ forceFlush = true
+ }
+ if err := t.framer.writeData(forceFlush, s.id, false, p); err != nil {
+ t.Close()
+ return connectionErrorf(true, err, "transport: %v", err)
+ }
+ if t.framer.adjustNumWriters(-1) == 0 {
+ t.framer.flushWrite()
+ }
+ t.writableChan <- 0
+ }
+
+}
+
+func (t *http2Server) applySettings(ss []http2.Setting) {
+ for _, s := range ss {
+ if s.ID == http2.SettingInitialWindowSize {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ for _, stream := range t.activeStreams {
+ stream.sendQuotaPool.add(int(s.Val - t.streamSendQuota))
+ }
+ t.streamSendQuota = s.Val
+ }
+
+ }
+}
+
+// keepalive running in a separate goroutine does the following:
+// 1. Gracefully closes an idle connection after a duration of keepalive.MaxConnectionIdle.
+// 2. Gracefully closes any connection after a duration of keepalive.MaxConnectionAge.
+// 3. Forcibly closes a connection after an additive period of keepalive.MaxConnectionAgeGrace over keepalive.MaxConnectionAge.
+// 4. Makes sure a connection is alive by sending pings with a frequency of keepalive.Time and closes a non-resposive connection
+// after an additional duration of keepalive.Timeout.
+func (t *http2Server) keepalive() {
+ p := &ping{}
+ var pingSent bool
+ maxIdle := time.NewTimer(t.kp.MaxConnectionIdle)
+ maxAge := time.NewTimer(t.kp.MaxConnectionAge)
+ keepalive := time.NewTimer(t.kp.Time)
+ // NOTE: All exit paths of this function should reset their
+ // respecitve timers. A failure to do so will cause the
+ // following clean-up to deadlock and eventually leak.
+ defer func() {
+ if !maxIdle.Stop() {
+ <-maxIdle.C
+ }
+ if !maxAge.Stop() {
+ <-maxAge.C
+ }
+ if !keepalive.Stop() {
+ <-keepalive.C
+ }
+ }()
+ for {
+ select {
+ case <-maxIdle.C:
+ t.mu.Lock()
+ idle := t.idle
+ if idle.IsZero() { // The connection is non-idle.
+ t.mu.Unlock()
+ maxIdle.Reset(t.kp.MaxConnectionIdle)
+ continue
+ }
+ val := t.kp.MaxConnectionIdle - time.Since(idle)
+ if val <= 0 {
+ // The connection has been idle for a duration of keepalive.MaxConnectionIdle or more.
+ // Gracefully close the connection.
+ t.state = draining
+ t.mu.Unlock()
+ t.Drain()
+ // Reseting the timer so that the clean-up doesn't deadlock.
+ maxIdle.Reset(infinity)
+ return
+ }
+ t.mu.Unlock()
+ maxIdle.Reset(val)
+ case <-maxAge.C:
+ t.mu.Lock()
+ t.state = draining
+ t.mu.Unlock()
+ t.Drain()
+ maxAge.Reset(t.kp.MaxConnectionAgeGrace)
+ select {
+ case <-maxAge.C:
+ // Close the connection after grace period.
+ t.Close()
+ // Reseting the timer so that the clean-up doesn't deadlock.
+ maxAge.Reset(infinity)
+ case <-t.shutdownChan:
+ }
+ return
+ case <-keepalive.C:
+ if atomic.CompareAndSwapUint32(&t.activity, 1, 0) {
+ pingSent = false
+ keepalive.Reset(t.kp.Time)
+ continue
+ }
+ if pingSent {
+ t.Close()
+ // Reseting the timer so that the clean-up doesn't deadlock.
+ keepalive.Reset(infinity)
+ return
+ }
+ pingSent = true
+ t.controlBuf.put(p)
+ keepalive.Reset(t.kp.Timeout)
+ case <-t.shutdownChan:
+ return
+ }
+ }
+}
+
+// controller running in a separate goroutine takes charge of sending control
+// frames (e.g., window update, reset stream, setting, etc.) to the server.
+func (t *http2Server) controller() {
+ for {
+ select {
+ case i := <-t.controlBuf.get():
+ t.controlBuf.load()
+ select {
+ case <-t.writableChan:
+ switch i := i.(type) {
+ case *windowUpdate:
+ t.framer.writeWindowUpdate(true, i.streamID, i.increment)
+ case *settings:
+ if i.ack {
+ t.framer.writeSettingsAck(true)
+ t.applySettings(i.ss)
+ } else {
+ t.framer.writeSettings(true, i.ss...)
+ }
+ case *resetStream:
+ t.framer.writeRSTStream(true, i.streamID, i.code)
+ case *goAway:
+ t.mu.Lock()
+ if t.state == closing {
+ t.mu.Unlock()
+ // The transport is closing.
+ return
+ }
+ sid := t.maxStreamID
+ t.state = draining
+ t.mu.Unlock()
+ t.framer.writeGoAway(true, sid, i.code, i.debugData)
+ if i.code == http2.ErrCodeEnhanceYourCalm {
+ t.Close()
+ }
+ case *flushIO:
+ t.framer.flushWrite()
+ case *ping:
+ t.framer.writePing(true, i.ack, i.data)
+ default:
+ grpclog.Printf("transport: http2Server.controller got unexpected item type %v\n", i)
+ }
+ t.writableChan <- 0
+ continue
+ case <-t.shutdownChan:
+ return
+ }
+ case <-t.shutdownChan:
+ return
+ }
+ }
+}
+
+// Close starts shutting down the http2Server transport.
+// TODO(zhaoq): Now the destruction is not blocked on any pending streams. This
+// could cause some resource issue. Revisit this later.
+func (t *http2Server) Close() (err error) {
+ t.mu.Lock()
+ if t.state == closing {
+ t.mu.Unlock()
+ return errors.New("transport: Close() was already called")
+ }
+ t.state = closing
+ streams := t.activeStreams
+ t.activeStreams = nil
+ t.mu.Unlock()
+ close(t.shutdownChan)
+ err = t.conn.Close()
+ // Cancel all active streams.
+ for _, s := range streams {
+ s.cancel()
+ }
+ if t.stats != nil {
+ connEnd := &stats.ConnEnd{}
+ t.stats.HandleConn(t.ctx, connEnd)
+ }
+ return
+}
+
+// closeStream clears the footprint of a stream when the stream is not needed
+// any more.
+func (t *http2Server) closeStream(s *Stream) {
+ t.mu.Lock()
+ delete(t.activeStreams, s.id)
+ if len(t.activeStreams) == 0 {
+ t.idle = time.Now()
+ }
+ if t.state == draining && len(t.activeStreams) == 0 {
+ defer t.Close()
+ }
+ t.mu.Unlock()
+ // In case stream sending and receiving are invoked in separate
+ // goroutines (e.g., bi-directional streaming), cancel needs to be
+ // called to interrupt the potential blocking on other goroutines.
+ s.cancel()
+ s.mu.Lock()
+ if q := s.fc.resetPendingData(); q > 0 {
+ if w := t.fc.onRead(q); w > 0 {
+ t.controlBuf.put(&windowUpdate{0, w})
+ }
+ }
+ if s.state == streamDone {
+ s.mu.Unlock()
+ return
+ }
+ s.state = streamDone
+ s.mu.Unlock()
+}
+
+func (t *http2Server) RemoteAddr() net.Addr {
+ return t.remoteAddr
+}
+
+func (t *http2Server) Drain() {
+ t.controlBuf.put(&goAway{code: http2.ErrCodeNo})
+}
+
+var rgen = rand.New(rand.NewSource(time.Now().UnixNano()))
+
+func getJitter(v time.Duration) time.Duration {
+ if v == infinity {
+ return 0
+ }
+ // Generate a jitter between +/- 10% of the value.
+ r := int64(v / 10)
+ j := rgen.Int63n(2*r) - r
+ return time.Duration(j)
+}
diff --git a/vendor/google.golang.org/grpc/transport/http_util.go b/vendor/google.golang.org/grpc/transport/http_util.go
new file mode 100644
index 0000000..795d5d1
--- /dev/null
+++ b/vendor/google.golang.org/grpc/transport/http_util.go
@@ -0,0 +1,549 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+package transport
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/base64"
+ "fmt"
+ "io"
+ "net"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "time"
+
+ "github.com/golang/protobuf/proto"
+ "golang.org/x/net/http2"
+ "golang.org/x/net/http2/hpack"
+ spb "google.golang.org/genproto/googleapis/rpc/status"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/grpclog"
+ "google.golang.org/grpc/status"
+)
+
+const (
+ // http2MaxFrameLen specifies the max length of a HTTP2 frame.
+ http2MaxFrameLen = 16384 // 16KB frame
+ // http://http2.github.io/http2-spec/#SettingValues
+ http2InitHeaderTableSize = 4096
+ // http2IOBufSize specifies the buffer size for sending frames.
+ http2IOBufSize = 32 * 1024
+)
+
+var (
+ clientPreface = []byte(http2.ClientPreface)
+ http2ErrConvTab = map[http2.ErrCode]codes.Code{
+ http2.ErrCodeNo: codes.Internal,
+ http2.ErrCodeProtocol: codes.Internal,
+ http2.ErrCodeInternal: codes.Internal,
+ http2.ErrCodeFlowControl: codes.ResourceExhausted,
+ http2.ErrCodeSettingsTimeout: codes.Internal,
+ http2.ErrCodeStreamClosed: codes.Internal,
+ http2.ErrCodeFrameSize: codes.Internal,
+ http2.ErrCodeRefusedStream: codes.Unavailable,
+ http2.ErrCodeCancel: codes.Canceled,
+ http2.ErrCodeCompression: codes.Internal,
+ http2.ErrCodeConnect: codes.Internal,
+ http2.ErrCodeEnhanceYourCalm: codes.ResourceExhausted,
+ http2.ErrCodeInadequateSecurity: codes.PermissionDenied,
+ http2.ErrCodeHTTP11Required: codes.FailedPrecondition,
+ }
+ statusCodeConvTab = map[codes.Code]http2.ErrCode{
+ codes.Internal: http2.ErrCodeInternal,
+ codes.Canceled: http2.ErrCodeCancel,
+ codes.Unavailable: http2.ErrCodeRefusedStream,
+ codes.ResourceExhausted: http2.ErrCodeEnhanceYourCalm,
+ codes.PermissionDenied: http2.ErrCodeInadequateSecurity,
+ }
+)
+
+// Records the states during HPACK decoding. Must be reset once the
+// decoding of the entire headers are finished.
+type decodeState struct {
+ encoding string
+ // statusGen caches the stream status received from the trailer the server
+ // sent. Client side only. Do not access directly. After all trailers are
+ // parsed, use the status method to retrieve the status.
+ statusGen *status.Status
+ // rawStatusCode and rawStatusMsg are set from the raw trailer fields and are not
+ // intended for direct access outside of parsing.
+ rawStatusCode int32
+ rawStatusMsg string
+ // Server side only fields.
+ timeoutSet bool
+ timeout time.Duration
+ method string
+ // key-value metadata map from the peer.
+ mdata map[string][]string
+}
+
+// isReservedHeader checks whether hdr belongs to HTTP2 headers
+// reserved by gRPC protocol. Any other headers are classified as the
+// user-specified metadata.
+func isReservedHeader(hdr string) bool {
+ if hdr != "" && hdr[0] == ':' {
+ return true
+ }
+ switch hdr {
+ case "content-type",
+ "grpc-message-type",
+ "grpc-encoding",
+ "grpc-message",
+ "grpc-status",
+ "grpc-timeout",
+ "grpc-status-details-bin",
+ "te":
+ return true
+ default:
+ return false
+ }
+}
+
+// isWhitelistedPseudoHeader checks whether hdr belongs to HTTP2 pseudoheaders
+// that should be propagated into metadata visible to users.
+func isWhitelistedPseudoHeader(hdr string) bool {
+ switch hdr {
+ case ":authority":
+ return true
+ default:
+ return false
+ }
+}
+
+func validContentType(t string) bool {
+ e := "application/grpc"
+ if !strings.HasPrefix(t, e) {
+ return false
+ }
+ // Support variations on the content-type
+ // (e.g. "application/grpc+blah", "application/grpc;blah").
+ if len(t) > len(e) && t[len(e)] != '+' && t[len(e)] != ';' {
+ return false
+ }
+ return true
+}
+
+func (d *decodeState) status() *status.Status {
+ if d.statusGen == nil {
+ // No status-details were provided; generate status using code/msg.
+ d.statusGen = status.New(codes.Code(d.rawStatusCode), d.rawStatusMsg)
+ }
+ return d.statusGen
+}
+
+const binHdrSuffix = "-bin"
+
+func encodeBinHeader(v []byte) string {
+ return base64.RawStdEncoding.EncodeToString(v)
+}
+
+func decodeBinHeader(v string) ([]byte, error) {
+ if len(v)%4 == 0 {
+ // Input was padded, or padding was not necessary.
+ return base64.StdEncoding.DecodeString(v)
+ }
+ return base64.RawStdEncoding.DecodeString(v)
+}
+
+func encodeMetadataHeader(k, v string) string {
+ if strings.HasSuffix(k, binHdrSuffix) {
+ return encodeBinHeader(([]byte)(v))
+ }
+ return v
+}
+
+func decodeMetadataHeader(k, v string) (string, error) {
+ if strings.HasSuffix(k, binHdrSuffix) {
+ b, err := decodeBinHeader(v)
+ return string(b), err
+ }
+ return v, nil
+}
+
+func (d *decodeState) processHeaderField(f hpack.HeaderField) error {
+ switch f.Name {
+ case "content-type":
+ if !validContentType(f.Value) {
+ return streamErrorf(codes.FailedPrecondition, "transport: received the unexpected content-type %q", f.Value)
+ }
+ case "grpc-encoding":
+ d.encoding = f.Value
+ case "grpc-status":
+ code, err := strconv.Atoi(f.Value)
+ if err != nil {
+ return streamErrorf(codes.Internal, "transport: malformed grpc-status: %v", err)
+ }
+ d.rawStatusCode = int32(code)
+ case "grpc-message":
+ d.rawStatusMsg = decodeGrpcMessage(f.Value)
+ case "grpc-status-details-bin":
+ v, err := decodeBinHeader(f.Value)
+ if err != nil {
+ return streamErrorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err)
+ }
+ s := &spb.Status{}
+ if err := proto.Unmarshal(v, s); err != nil {
+ return streamErrorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err)
+ }
+ d.statusGen = status.FromProto(s)
+ case "grpc-timeout":
+ d.timeoutSet = true
+ var err error
+ if d.timeout, err = decodeTimeout(f.Value); err != nil {
+ return streamErrorf(codes.Internal, "transport: malformed time-out: %v", err)
+ }
+ case ":path":
+ d.method = f.Value
+ default:
+ if !isReservedHeader(f.Name) || isWhitelistedPseudoHeader(f.Name) {
+ if d.mdata == nil {
+ d.mdata = make(map[string][]string)
+ }
+ v, err := decodeMetadataHeader(f.Name, f.Value)
+ if err != nil {
+ grpclog.Printf("Failed to decode (%q, %q): %v", f.Name, f.Value, err)
+ return nil
+ }
+ d.mdata[f.Name] = append(d.mdata[f.Name], v)
+ }
+ }
+ return nil
+}
+
+type timeoutUnit uint8
+
+const (
+ hour timeoutUnit = 'H'
+ minute timeoutUnit = 'M'
+ second timeoutUnit = 'S'
+ millisecond timeoutUnit = 'm'
+ microsecond timeoutUnit = 'u'
+ nanosecond timeoutUnit = 'n'
+)
+
+func timeoutUnitToDuration(u timeoutUnit) (d time.Duration, ok bool) {
+ switch u {
+ case hour:
+ return time.Hour, true
+ case minute:
+ return time.Minute, true
+ case second:
+ return time.Second, true
+ case millisecond:
+ return time.Millisecond, true
+ case microsecond:
+ return time.Microsecond, true
+ case nanosecond:
+ return time.Nanosecond, true
+ default:
+ }
+ return
+}
+
+const maxTimeoutValue int64 = 100000000 - 1
+
+// div does integer division and round-up the result. Note that this is
+// equivalent to (d+r-1)/r but has less chance to overflow.
+func div(d, r time.Duration) int64 {
+ if m := d % r; m > 0 {
+ return int64(d/r + 1)
+ }
+ return int64(d / r)
+}
+
+// TODO(zhaoq): It is the simplistic and not bandwidth efficient. Improve it.
+func encodeTimeout(t time.Duration) string {
+ if t <= 0 {
+ return "0n"
+ }
+ if d := div(t, time.Nanosecond); d <= maxTimeoutValue {
+ return strconv.FormatInt(d, 10) + "n"
+ }
+ if d := div(t, time.Microsecond); d <= maxTimeoutValue {
+ return strconv.FormatInt(d, 10) + "u"
+ }
+ if d := div(t, time.Millisecond); d <= maxTimeoutValue {
+ return strconv.FormatInt(d, 10) + "m"
+ }
+ if d := div(t, time.Second); d <= maxTimeoutValue {
+ return strconv.FormatInt(d, 10) + "S"
+ }
+ if d := div(t, time.Minute); d <= maxTimeoutValue {
+ return strconv.FormatInt(d, 10) + "M"
+ }
+ // Note that maxTimeoutValue * time.Hour > MaxInt64.
+ return strconv.FormatInt(div(t, time.Hour), 10) + "H"
+}
+
+func decodeTimeout(s string) (time.Duration, error) {
+ size := len(s)
+ if size < 2 {
+ return 0, fmt.Errorf("transport: timeout string is too short: %q", s)
+ }
+ unit := timeoutUnit(s[size-1])
+ d, ok := timeoutUnitToDuration(unit)
+ if !ok {
+ return 0, fmt.Errorf("transport: timeout unit is not recognized: %q", s)
+ }
+ t, err := strconv.ParseInt(s[:size-1], 10, 64)
+ if err != nil {
+ return 0, err
+ }
+ return d * time.Duration(t), nil
+}
+
+const (
+ spaceByte = ' '
+ tildaByte = '~'
+ percentByte = '%'
+)
+
+// encodeGrpcMessage is used to encode status code in header field
+// "grpc-message".
+// It checks to see if each individual byte in msg is an
+// allowable byte, and then either percent encoding or passing it through.
+// When percent encoding, the byte is converted into hexadecimal notation
+// with a '%' prepended.
+func encodeGrpcMessage(msg string) string {
+ if msg == "" {
+ return ""
+ }
+ lenMsg := len(msg)
+ for i := 0; i < lenMsg; i++ {
+ c := msg[i]
+ if !(c >= spaceByte && c < tildaByte && c != percentByte) {
+ return encodeGrpcMessageUnchecked(msg)
+ }
+ }
+ return msg
+}
+
+func encodeGrpcMessageUnchecked(msg string) string {
+ var buf bytes.Buffer
+ lenMsg := len(msg)
+ for i := 0; i < lenMsg; i++ {
+ c := msg[i]
+ if c >= spaceByte && c < tildaByte && c != percentByte {
+ buf.WriteByte(c)
+ } else {
+ buf.WriteString(fmt.Sprintf("%%%02X", c))
+ }
+ }
+ return buf.String()
+}
+
+// decodeGrpcMessage decodes the msg encoded by encodeGrpcMessage.
+func decodeGrpcMessage(msg string) string {
+ if msg == "" {
+ return ""
+ }
+ lenMsg := len(msg)
+ for i := 0; i < lenMsg; i++ {
+ if msg[i] == percentByte && i+2 < lenMsg {
+ return decodeGrpcMessageUnchecked(msg)
+ }
+ }
+ return msg
+}
+
+func decodeGrpcMessageUnchecked(msg string) string {
+ var buf bytes.Buffer
+ lenMsg := len(msg)
+ for i := 0; i < lenMsg; i++ {
+ c := msg[i]
+ if c == percentByte && i+2 < lenMsg {
+ parsed, err := strconv.ParseUint(msg[i+1:i+3], 16, 8)
+ if err != nil {
+ buf.WriteByte(c)
+ } else {
+ buf.WriteByte(byte(parsed))
+ i += 2
+ }
+ } else {
+ buf.WriteByte(c)
+ }
+ }
+ return buf.String()
+}
+
+type framer struct {
+ numWriters int32
+ reader io.Reader
+ writer *bufio.Writer
+ fr *http2.Framer
+}
+
+func newFramer(conn net.Conn) *framer {
+ f := &framer{
+ reader: bufio.NewReaderSize(conn, http2IOBufSize),
+ writer: bufio.NewWriterSize(conn, http2IOBufSize),
+ }
+ f.fr = http2.NewFramer(f.writer, f.reader)
+ // Opt-in to Frame reuse API on framer to reduce garbage.
+ // Frames aren't safe to read from after a subsequent call to ReadFrame.
+ f.fr.SetReuseFrames()
+ f.fr.ReadMetaHeaders = hpack.NewDecoder(http2InitHeaderTableSize, nil)
+ return f
+}
+
+func (f *framer) adjustNumWriters(i int32) int32 {
+ return atomic.AddInt32(&f.numWriters, i)
+}
+
+// The following writeXXX functions can only be called when the caller gets
+// unblocked from writableChan channel (i.e., owns the privilege to write).
+
+func (f *framer) writeContinuation(forceFlush bool, streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
+ if err := f.fr.WriteContinuation(streamID, endHeaders, headerBlockFragment); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) writeData(forceFlush bool, streamID uint32, endStream bool, data []byte) error {
+ if err := f.fr.WriteData(streamID, endStream, data); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) writeGoAway(forceFlush bool, maxStreamID uint32, code http2.ErrCode, debugData []byte) error {
+ if err := f.fr.WriteGoAway(maxStreamID, code, debugData); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) writeHeaders(forceFlush bool, p http2.HeadersFrameParam) error {
+ if err := f.fr.WriteHeaders(p); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) writePing(forceFlush, ack bool, data [8]byte) error {
+ if err := f.fr.WritePing(ack, data); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) writePriority(forceFlush bool, streamID uint32, p http2.PriorityParam) error {
+ if err := f.fr.WritePriority(streamID, p); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) writePushPromise(forceFlush bool, p http2.PushPromiseParam) error {
+ if err := f.fr.WritePushPromise(p); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) writeRSTStream(forceFlush bool, streamID uint32, code http2.ErrCode) error {
+ if err := f.fr.WriteRSTStream(streamID, code); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) writeSettings(forceFlush bool, settings ...http2.Setting) error {
+ if err := f.fr.WriteSettings(settings...); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) writeSettingsAck(forceFlush bool) error {
+ if err := f.fr.WriteSettingsAck(); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) writeWindowUpdate(forceFlush bool, streamID, incr uint32) error {
+ if err := f.fr.WriteWindowUpdate(streamID, incr); err != nil {
+ return err
+ }
+ if forceFlush {
+ return f.writer.Flush()
+ }
+ return nil
+}
+
+func (f *framer) flushWrite() error {
+ return f.writer.Flush()
+}
+
+func (f *framer) readFrame() (http2.Frame, error) {
+ return f.fr.ReadFrame()
+}
+
+func (f *framer) errorDetail() error {
+ return f.fr.ErrorDetail()
+}
diff --git a/vendor/google.golang.org/grpc/transport/transport.go b/vendor/google.golang.org/grpc/transport/transport.go
new file mode 100644
index 0000000..88c2c98
--- /dev/null
+++ b/vendor/google.golang.org/grpc/transport/transport.go
@@ -0,0 +1,666 @@
+/*
+ *
+ * Copyright 2014, Google Inc.
+ * 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.
+ *
+ */
+
+/*
+Package transport defines and implements message oriented communication channel
+to complete various transactions (e.g., an RPC).
+*/
+package transport // import "google.golang.org/grpc/transport"
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "net"
+ "sync"
+
+ "golang.org/x/net/context"
+ "golang.org/x/net/http2"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/keepalive"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/stats"
+ "google.golang.org/grpc/status"
+ "google.golang.org/grpc/tap"
+)
+
+// recvMsg represents the received msg from the transport. All transport
+// protocol specific info has been removed.
+type recvMsg struct {
+ data []byte
+ // nil: received some data
+ // io.EOF: stream is completed. data is nil.
+ // other non-nil error: transport failure. data is nil.
+ err error
+}
+
+func (*recvMsg) item() {}
+
+// All items in an out of a recvBuffer should be the same type.
+type item interface {
+ item()
+}
+
+// recvBuffer is an unbounded channel of item.
+type recvBuffer struct {
+ c chan item
+ mu sync.Mutex
+ backlog []item
+}
+
+func newRecvBuffer() *recvBuffer {
+ b := &recvBuffer{
+ c: make(chan item, 1),
+ }
+ return b
+}
+
+func (b *recvBuffer) put(r item) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if len(b.backlog) == 0 {
+ select {
+ case b.c <- r:
+ return
+ default:
+ }
+ }
+ b.backlog = append(b.backlog, r)
+}
+
+func (b *recvBuffer) load() {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if len(b.backlog) > 0 {
+ select {
+ case b.c <- b.backlog[0]:
+ b.backlog = b.backlog[1:]
+ default:
+ }
+ }
+}
+
+// get returns the channel that receives an item in the buffer.
+//
+// Upon receipt of an item, the caller should call load to send another
+// item onto the channel if there is any.
+func (b *recvBuffer) get() <-chan item {
+ return b.c
+}
+
+// recvBufferReader implements io.Reader interface to read the data from
+// recvBuffer.
+type recvBufferReader struct {
+ ctx context.Context
+ goAway chan struct{}
+ recv *recvBuffer
+ last *bytes.Reader // Stores the remaining data in the previous calls.
+ err error
+}
+
+// Read reads the next len(p) bytes from last. If last is drained, it tries to
+// read additional data from recv. It blocks if there no additional data available
+// in recv. If Read returns any non-nil error, it will continue to return that error.
+func (r *recvBufferReader) Read(p []byte) (n int, err error) {
+ if r.err != nil {
+ return 0, r.err
+ }
+ defer func() { r.err = err }()
+ if r.last != nil && r.last.Len() > 0 {
+ // Read remaining data left in last call.
+ return r.last.Read(p)
+ }
+ select {
+ case <-r.ctx.Done():
+ return 0, ContextErr(r.ctx.Err())
+ case <-r.goAway:
+ return 0, ErrStreamDrain
+ case i := <-r.recv.get():
+ r.recv.load()
+ m := i.(*recvMsg)
+ if m.err != nil {
+ return 0, m.err
+ }
+ r.last = bytes.NewReader(m.data)
+ return r.last.Read(p)
+ }
+}
+
+type streamState uint8
+
+const (
+ streamActive streamState = iota
+ streamWriteDone // EndStream sent
+ streamReadDone // EndStream received
+ streamDone // the entire stream is finished.
+)
+
+// Stream represents an RPC in the transport layer.
+type Stream struct {
+ id uint32
+ // nil for client side Stream.
+ st ServerTransport
+ // clientStatsCtx keeps the user context for stats handling.
+ // It's only valid on client side. Server side stats context is same as s.ctx.
+ // All client side stats collection should use the clientStatsCtx (instead of the stream context)
+ // so that all the generated stats for a particular RPC can be associated in the processing phase.
+ clientStatsCtx context.Context
+ // ctx is the associated context of the stream.
+ ctx context.Context
+ // cancel is always nil for client side Stream.
+ cancel context.CancelFunc
+ // done is closed when the final status arrives.
+ done chan struct{}
+ // goAway is closed when the server sent GoAways signal before this stream was initiated.
+ goAway chan struct{}
+ // method records the associated RPC method of the stream.
+ method string
+ recvCompress string
+ sendCompress string
+ buf *recvBuffer
+ dec io.Reader
+ fc *inFlow
+ recvQuota uint32
+ // The accumulated inbound quota pending for window update.
+ updateQuota uint32
+ // The handler to control the window update procedure for both this
+ // particular stream and the associated transport.
+ windowHandler func(int)
+
+ sendQuotaPool *quotaPool
+ // Close headerChan to indicate the end of reception of header metadata.
+ headerChan chan struct{}
+ // header caches the received header metadata.
+ header metadata.MD
+ // The key-value map of trailer metadata.
+ trailer metadata.MD
+
+ mu sync.RWMutex // guard the following
+ // headerOK becomes true from the first header is about to send.
+ headerOk bool
+ state streamState
+ // true iff headerChan is closed. Used to avoid closing headerChan
+ // multiple times.
+ headerDone bool
+ // the status error received from the server.
+ status *status.Status
+ // rstStream indicates whether a RST_STREAM frame needs to be sent
+ // to the server to signify that this stream is closing.
+ rstStream bool
+ // rstError is the error that needs to be sent along with the RST_STREAM frame.
+ rstError http2.ErrCode
+ // bytesSent and bytesReceived indicates whether any bytes have been sent or
+ // received on this stream.
+ bytesSent bool
+ bytesReceived bool
+}
+
+// RecvCompress returns the compression algorithm applied to the inbound
+// message. It is empty string if there is no compression applied.
+func (s *Stream) RecvCompress() string {
+ return s.recvCompress
+}
+
+// SetSendCompress sets the compression algorithm to the stream.
+func (s *Stream) SetSendCompress(str string) {
+ s.sendCompress = str
+}
+
+// Done returns a chanel which is closed when it receives the final status
+// from the server.
+func (s *Stream) Done() <-chan struct{} {
+ return s.done
+}
+
+// GoAway returns a channel which is closed when the server sent GoAways signal
+// before this stream was initiated.
+func (s *Stream) GoAway() <-chan struct{} {
+ return s.goAway
+}
+
+// Header acquires the key-value pairs of header metadata once it
+// is available. It blocks until i) the metadata is ready or ii) there is no
+// header metadata or iii) the stream is cancelled/expired.
+func (s *Stream) Header() (metadata.MD, error) {
+ select {
+ case <-s.ctx.Done():
+ return nil, ContextErr(s.ctx.Err())
+ case <-s.goAway:
+ return nil, ErrStreamDrain
+ case <-s.headerChan:
+ return s.header.Copy(), nil
+ }
+}
+
+// Trailer returns the cached trailer metedata. Note that if it is not called
+// after the entire stream is done, it could return an empty MD. Client
+// side only.
+func (s *Stream) Trailer() metadata.MD {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.trailer.Copy()
+}
+
+// ServerTransport returns the underlying ServerTransport for the stream.
+// The client side stream always returns nil.
+func (s *Stream) ServerTransport() ServerTransport {
+ return s.st
+}
+
+// Context returns the context of the stream.
+func (s *Stream) Context() context.Context {
+ return s.ctx
+}
+
+// Method returns the method for the stream.
+func (s *Stream) Method() string {
+ return s.method
+}
+
+// Status returns the status received from the server.
+func (s *Stream) Status() *status.Status {
+ return s.status
+}
+
+// SetHeader sets the header metadata. This can be called multiple times.
+// Server side only.
+func (s *Stream) SetHeader(md metadata.MD) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.headerOk || s.state == streamDone {
+ return ErrIllegalHeaderWrite
+ }
+ if md.Len() == 0 {
+ return nil
+ }
+ s.header = metadata.Join(s.header, md)
+ return nil
+}
+
+// SetTrailer sets the trailer metadata which will be sent with the RPC status
+// by the server. This can be called multiple times. Server side only.
+func (s *Stream) SetTrailer(md metadata.MD) error {
+ if md.Len() == 0 {
+ return nil
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.trailer = metadata.Join(s.trailer, md)
+ return nil
+}
+
+func (s *Stream) write(m recvMsg) {
+ s.buf.put(&m)
+}
+
+// Read reads all the data available for this Stream from the transport and
+// passes them into the decoder, which converts them into a gRPC message stream.
+// The error is io.EOF when the stream is done or another non-nil error if
+// the stream broke.
+func (s *Stream) Read(p []byte) (n int, err error) {
+ n, err = s.dec.Read(p)
+ if err != nil {
+ return
+ }
+ s.windowHandler(n)
+ return
+}
+
+// finish sets the stream's state and status, and closes the done channel.
+// s.mu must be held by the caller. st must always be non-nil.
+func (s *Stream) finish(st *status.Status) {
+ s.status = st
+ s.state = streamDone
+ close(s.done)
+}
+
+// BytesSent indicates whether any bytes have been sent on this stream.
+func (s *Stream) BytesSent() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.bytesSent
+}
+
+// BytesReceived indicates whether any bytes have been received on this stream.
+func (s *Stream) BytesReceived() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.bytesReceived
+}
+
+// GoString is implemented by Stream so context.String() won't
+// race when printing %#v.
+func (s *Stream) GoString() string {
+ return fmt.Sprintf("<stream: %p, %v>", s, s.method)
+}
+
+// The key to save transport.Stream in the context.
+type streamKey struct{}
+
+// newContextWithStream creates a new context from ctx and attaches stream
+// to it.
+func newContextWithStream(ctx context.Context, stream *Stream) context.Context {
+ return context.WithValue(ctx, streamKey{}, stream)
+}
+
+// StreamFromContext returns the stream saved in ctx.
+func StreamFromContext(ctx context.Context) (s *Stream, ok bool) {
+ s, ok = ctx.Value(streamKey{}).(*Stream)
+ return
+}
+
+// state of transport
+type transportState int
+
+const (
+ reachable transportState = iota
+ unreachable
+ closing
+ draining
+)
+
+// ServerConfig consists of all the configurations to establish a server transport.
+type ServerConfig struct {
+ MaxStreams uint32
+ AuthInfo credentials.AuthInfo
+ InTapHandle tap.ServerInHandle
+ StatsHandler stats.Handler
+ KeepaliveParams keepalive.ServerParameters
+ KeepalivePolicy keepalive.EnforcementPolicy
+}
+
+// NewServerTransport creates a ServerTransport with conn or non-nil error
+// if it fails.
+func NewServerTransport(protocol string, conn net.Conn, config *ServerConfig) (ServerTransport, error) {
+ return newHTTP2Server(conn, config)
+}
+
+// ConnectOptions covers all relevant options for communicating with the server.
+type ConnectOptions struct {
+ // UserAgent is the application user agent.
+ UserAgent string
+ // Authority is the :authority pseudo-header to use. This field has no effect if
+ // TransportCredentials is set.
+ Authority string
+ // Dialer specifies how to dial a network address.
+ Dialer func(context.Context, string) (net.Conn, error)
+ // FailOnNonTempDialError specifies if gRPC fails on non-temporary dial errors.
+ FailOnNonTempDialError bool
+ // PerRPCCredentials stores the PerRPCCredentials required to issue RPCs.
+ PerRPCCredentials []credentials.PerRPCCredentials
+ // TransportCredentials stores the Authenticator required to setup a client connection.
+ TransportCredentials credentials.TransportCredentials
+ // KeepaliveParams stores the keepalive parameters.
+ KeepaliveParams keepalive.ClientParameters
+ // StatsHandler stores the handler for stats.
+ StatsHandler stats.Handler
+}
+
+// TargetInfo contains the information of the target such as network address and metadata.
+type TargetInfo struct {
+ Addr string
+ Metadata interface{}
+}
+
+// NewClientTransport establishes the transport with the required ConnectOptions
+// and returns it to the caller.
+func NewClientTransport(ctx context.Context, target TargetInfo, opts ConnectOptions) (ClientTransport, error) {
+ return newHTTP2Client(ctx, target, opts)
+}
+
+// Options provides additional hints and information for message
+// transmission.
+type Options struct {
+ // Last indicates whether this write is the last piece for
+ // this stream.
+ Last bool
+
+ // Delay is a hint to the transport implementation for whether
+ // the data could be buffered for a batching write. The
+ // Transport implementation may ignore the hint.
+ Delay bool
+}
+
+// CallHdr carries the information of a particular RPC.
+type CallHdr struct {
+ // Host specifies the peer's host.
+ Host string
+
+ // Method specifies the operation to perform.
+ Method string
+
+ // RecvCompress specifies the compression algorithm applied on
+ // inbound messages.
+ RecvCompress string
+
+ // SendCompress specifies the compression algorithm applied on
+ // outbound message.
+ SendCompress string
+
+ // Flush indicates whether a new stream command should be sent
+ // to the peer without waiting for the first data. This is
+ // only a hint. The transport may modify the flush decision
+ // for performance purposes.
+ Flush bool
+}
+
+// ClientTransport is the common interface for all gRPC client-side transport
+// implementations.
+type ClientTransport interface {
+ // Close tears down this transport. Once it returns, the transport
+ // should not be accessed any more. The caller must make sure this
+ // is called only once.
+ Close() error
+
+ // GracefulClose starts to tear down the transport. It stops accepting
+ // new RPCs and wait the completion of the pending RPCs.
+ GracefulClose() error
+
+ // Write sends the data for the given stream. A nil stream indicates
+ // the write is to be performed on the transport as a whole.
+ Write(s *Stream, data []byte, opts *Options) error
+
+ // NewStream creates a Stream for an RPC.
+ NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error)
+
+ // CloseStream clears the footprint of a stream when the stream is
+ // not needed any more. The err indicates the error incurred when
+ // CloseStream is called. Must be called when a stream is finished
+ // unless the associated transport is closing.
+ CloseStream(stream *Stream, err error)
+
+ // Error returns a channel that is closed when some I/O error
+ // happens. Typically the caller should have a goroutine to monitor
+ // this in order to take action (e.g., close the current transport
+ // and create a new one) in error case. It should not return nil
+ // once the transport is initiated.
+ Error() <-chan struct{}
+
+ // GoAway returns a channel that is closed when ClientTranspor
+ // receives the draining signal from the server (e.g., GOAWAY frame in
+ // HTTP/2).
+ GoAway() <-chan struct{}
+
+ // GetGoAwayReason returns the reason why GoAway frame was received.
+ GetGoAwayReason() GoAwayReason
+}
+
+// ServerTransport is the common interface for all gRPC server-side transport
+// implementations.
+//
+// Methods may be called concurrently from multiple goroutines, but
+// Write methods for a given Stream will be called serially.
+type ServerTransport interface {
+ // HandleStreams receives incoming streams using the given handler.
+ HandleStreams(func(*Stream), func(context.Context, string) context.Context)
+
+ // WriteHeader sends the header metadata for the given stream.
+ // WriteHeader may not be called on all streams.
+ WriteHeader(s *Stream, md metadata.MD) error
+
+ // Write sends the data for the given stream.
+ // Write may not be called on all streams.
+ Write(s *Stream, data []byte, opts *Options) error
+
+ // WriteStatus sends the status of a stream to the client. WriteStatus is
+ // the final call made on a stream and always occurs.
+ WriteStatus(s *Stream, st *status.Status) error
+
+ // Close tears down the transport. Once it is called, the transport
+ // should not be accessed any more. All the pending streams and their
+ // handlers will be terminated asynchronously.
+ Close() error
+
+ // RemoteAddr returns the remote network address.
+ RemoteAddr() net.Addr
+
+ // Drain notifies the client this ServerTransport stops accepting new RPCs.
+ Drain()
+}
+
+// streamErrorf creates an StreamError with the specified error code and description.
+func streamErrorf(c codes.Code, format string, a ...interface{}) StreamError {
+ return StreamError{
+ Code: c,
+ Desc: fmt.Sprintf(format, a...),
+ }
+}
+
+// connectionErrorf creates an ConnectionError with the specified error description.
+func connectionErrorf(temp bool, e error, format string, a ...interface{}) ConnectionError {
+ return ConnectionError{
+ Desc: fmt.Sprintf(format, a...),
+ temp: temp,
+ err: e,
+ }
+}
+
+// ConnectionError is an error that results in the termination of the
+// entire connection and the retry of all the active streams.
+type ConnectionError struct {
+ Desc string
+ temp bool
+ err error
+}
+
+func (e ConnectionError) Error() string {
+ return fmt.Sprintf("connection error: desc = %q", e.Desc)
+}
+
+// Temporary indicates if this connection error is temporary or fatal.
+func (e ConnectionError) Temporary() bool {
+ return e.temp
+}
+
+// Origin returns the original error of this connection error.
+func (e ConnectionError) Origin() error {
+ // Never return nil error here.
+ // If the original error is nil, return itself.
+ if e.err == nil {
+ return e
+ }
+ return e.err
+}
+
+var (
+ // ErrConnClosing indicates that the transport is closing.
+ ErrConnClosing = connectionErrorf(true, nil, "transport is closing")
+ // ErrStreamDrain indicates that the stream is rejected by the server because
+ // the server stops accepting new RPCs.
+ ErrStreamDrain = streamErrorf(codes.Unavailable, "the server stops accepting new RPCs")
+)
+
+// TODO: See if we can replace StreamError with status package errors.
+
+// StreamError is an error that only affects one stream within a connection.
+type StreamError struct {
+ Code codes.Code
+ Desc string
+}
+
+func (e StreamError) Error() string {
+ return fmt.Sprintf("stream error: code = %s desc = %q", e.Code, e.Desc)
+}
+
+// ContextErr converts the error from context package into a StreamError.
+func ContextErr(err error) StreamError {
+ switch err {
+ case context.DeadlineExceeded:
+ return streamErrorf(codes.DeadlineExceeded, "%v", err)
+ case context.Canceled:
+ return streamErrorf(codes.Canceled, "%v", err)
+ }
+ panic(fmt.Sprintf("Unexpected error from context packet: %v", err))
+}
+
+// wait blocks until it can receive from ctx.Done, closing, or proceed.
+// If it receives from ctx.Done, it returns 0, the StreamError for ctx.Err.
+// If it receives from done, it returns 0, io.EOF if ctx is not done; otherwise
+// it return the StreamError for ctx.Err.
+// If it receives from goAway, it returns 0, ErrStreamDrain.
+// If it receives from closing, it returns 0, ErrConnClosing.
+// If it receives from proceed, it returns the received integer, nil.
+func wait(ctx context.Context, done, goAway, closing <-chan struct{}, proceed <-chan int) (int, error) {
+ select {
+ case <-ctx.Done():
+ return 0, ContextErr(ctx.Err())
+ case <-done:
+ // User cancellation has precedence.
+ select {
+ case <-ctx.Done():
+ return 0, ContextErr(ctx.Err())
+ default:
+ }
+ return 0, io.EOF
+ case <-goAway:
+ return 0, ErrStreamDrain
+ case <-closing:
+ return 0, ErrConnClosing
+ case i := <-proceed:
+ return i, nil
+ }
+}
+
+// GoAwayReason contains the reason for the GoAway frame received.
+type GoAwayReason uint8
+
+const (
+ // Invalid indicates that no GoAway frame is received.
+ Invalid GoAwayReason = 0
+ // NoReason is the default value when GoAway frame is received.
+ NoReason GoAwayReason = 1
+ // TooManyPings indicates that a GoAway frame with ErrCodeEnhanceYourCalm
+ // was recieved and that the debug data said "too_many_pings".
+ TooManyPings GoAwayReason = 2
+)
diff --git a/vendor/gopkg.in/yaml.v2/LICENSE b/vendor/gopkg.in/yaml.v2/LICENSE
new file mode 100644
index 0000000..866d74a
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/LICENSE
@@ -0,0 +1,13 @@
+Copyright 2011-2016 Canonical Ltd.
+
+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/gopkg.in/yaml.v2/LICENSE.libyaml b/vendor/gopkg.in/yaml.v2/LICENSE.libyaml
new file mode 100644
index 0000000..8da58fb
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/LICENSE.libyaml
@@ -0,0 +1,31 @@
+The following files were ported to Go from C files of libyaml, and thus
+are still covered by their original copyright and license:
+
+ apic.go
+ emitterc.go
+ parserc.go
+ readerc.go
+ scannerc.go
+ writerc.go
+ yamlh.go
+ yamlprivateh.go
+
+Copyright (c) 2006 Kirill Simonov
+
+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/yaml.v2/README.md b/vendor/gopkg.in/yaml.v2/README.md
new file mode 100644
index 0000000..1884de6
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/README.md
@@ -0,0 +1,131 @@
+# YAML support for the Go language
+
+Introduction
+------------
+
+The yaml package enables Go programs to comfortably encode and decode YAML
+values. It was developed within [Canonical](https://www.canonical.com) as
+part of the [juju](https://juju.ubuntu.com) project, and is based on a
+pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML)
+C library to parse and generate YAML data quickly and reliably.
+
+Compatibility
+-------------
+
+The yaml package supports most of YAML 1.1 and 1.2, including support for
+anchors, tags, map merging, etc. Multi-document unmarshalling is not yet
+implemented, and base-60 floats from YAML 1.1 are purposefully not
+supported since they're a poor design and are gone in YAML 1.2.
+
+Installation and usage
+----------------------
+
+The import path for the package is *gopkg.in/yaml.v2*.
+
+To install it, run:
+
+ go get gopkg.in/yaml.v2
+
+API documentation
+-----------------
+
+If opened in a browser, the import path itself leads to the API documentation:
+
+ * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2)
+
+API stability
+-------------
+
+The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in).
+
+
+License
+-------
+
+The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details.
+
+
+Example
+-------
+
+```Go
+package main
+
+import (
+ "fmt"
+ "log"
+
+ "gopkg.in/yaml.v2"
+)
+
+var data = `
+a: Easy!
+b:
+ c: 2
+ d: [3, 4]
+`
+
+type T struct {
+ A string
+ B struct {
+ RenamedC int `yaml:"c"`
+ D []int `yaml:",flow"`
+ }
+}
+
+func main() {
+ t := T{}
+
+ err := yaml.Unmarshal([]byte(data), &t)
+ if err != nil {
+ log.Fatalf("error: %v", err)
+ }
+ fmt.Printf("--- t:\n%v\n\n", t)
+
+ d, err := yaml.Marshal(&t)
+ if err != nil {
+ log.Fatalf("error: %v", err)
+ }
+ fmt.Printf("--- t dump:\n%s\n\n", string(d))
+
+ m := make(map[interface{}]interface{})
+
+ err = yaml.Unmarshal([]byte(data), &m)
+ if err != nil {
+ log.Fatalf("error: %v", err)
+ }
+ fmt.Printf("--- m:\n%v\n\n", m)
+
+ d, err = yaml.Marshal(&m)
+ if err != nil {
+ log.Fatalf("error: %v", err)
+ }
+ fmt.Printf("--- m dump:\n%s\n\n", string(d))
+}
+```
+
+This example will generate the following output:
+
+```
+--- t:
+{Easy! {2 [3 4]}}
+
+--- t dump:
+a: Easy!
+b:
+ c: 2
+ d: [3, 4]
+
+
+--- m:
+map[a:Easy! b:map[c:2 d:[3 4]]]
+
+--- m dump:
+a: Easy!
+b:
+ c: 2
+ d:
+ - 3
+ - 4
+```
+
diff --git a/vendor/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go
new file mode 100644
index 0000000..95ec014
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/apic.go
@@ -0,0 +1,742 @@
+package yaml
+
+import (
+ "io"
+ "os"
+)
+
+func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) {
+ //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens))
+
+ // Check if we can move the queue at the beginning of the buffer.
+ if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) {
+ if parser.tokens_head != len(parser.tokens) {
+ copy(parser.tokens, parser.tokens[parser.tokens_head:])
+ }
+ parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head]
+ parser.tokens_head = 0
+ }
+ parser.tokens = append(parser.tokens, *token)
+ if pos < 0 {
+ return
+ }
+ copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:])
+ parser.tokens[parser.tokens_head+pos] = *token
+}
+
+// Create a new parser object.
+func yaml_parser_initialize(parser *yaml_parser_t) bool {
+ *parser = yaml_parser_t{
+ raw_buffer: make([]byte, 0, input_raw_buffer_size),
+ buffer: make([]byte, 0, input_buffer_size),
+ }
+ return true
+}
+
+// Destroy a parser object.
+func yaml_parser_delete(parser *yaml_parser_t) {
+ *parser = yaml_parser_t{}
+}
+
+// String read handler.
+func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) {
+ if parser.input_pos == len(parser.input) {
+ return 0, io.EOF
+ }
+ n = copy(buffer, parser.input[parser.input_pos:])
+ parser.input_pos += n
+ return n, nil
+}
+
+// File read handler.
+func yaml_file_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) {
+ return parser.input_file.Read(buffer)
+}
+
+// Set a string input.
+func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) {
+ if parser.read_handler != nil {
+ panic("must set the input source only once")
+ }
+ parser.read_handler = yaml_string_read_handler
+ parser.input = input
+ parser.input_pos = 0
+}
+
+// Set a file input.
+func yaml_parser_set_input_file(parser *yaml_parser_t, file *os.File) {
+ if parser.read_handler != nil {
+ panic("must set the input source only once")
+ }
+ parser.read_handler = yaml_file_read_handler
+ parser.input_file = file
+}
+
+// Set the source encoding.
+func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) {
+ if parser.encoding != yaml_ANY_ENCODING {
+ panic("must set the encoding only once")
+ }
+ parser.encoding = encoding
+}
+
+// Create a new emitter object.
+func yaml_emitter_initialize(emitter *yaml_emitter_t) bool {
+ *emitter = yaml_emitter_t{
+ buffer: make([]byte, output_buffer_size),
+ raw_buffer: make([]byte, 0, output_raw_buffer_size),
+ states: make([]yaml_emitter_state_t, 0, initial_stack_size),
+ events: make([]yaml_event_t, 0, initial_queue_size),
+ }
+ return true
+}
+
+// Destroy an emitter object.
+func yaml_emitter_delete(emitter *yaml_emitter_t) {
+ *emitter = yaml_emitter_t{}
+}
+
+// String write handler.
+func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error {
+ *emitter.output_buffer = append(*emitter.output_buffer, buffer...)
+ return nil
+}
+
+// File write handler.
+func yaml_file_write_handler(emitter *yaml_emitter_t, buffer []byte) error {
+ _, err := emitter.output_file.Write(buffer)
+ return err
+}
+
+// Set a string output.
+func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) {
+ if emitter.write_handler != nil {
+ panic("must set the output target only once")
+ }
+ emitter.write_handler = yaml_string_write_handler
+ emitter.output_buffer = output_buffer
+}
+
+// Set a file output.
+func yaml_emitter_set_output_file(emitter *yaml_emitter_t, file io.Writer) {
+ if emitter.write_handler != nil {
+ panic("must set the output target only once")
+ }
+ emitter.write_handler = yaml_file_write_handler
+ emitter.output_file = file
+}
+
+// Set the output encoding.
+func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) {
+ if emitter.encoding != yaml_ANY_ENCODING {
+ panic("must set the output encoding only once")
+ }
+ emitter.encoding = encoding
+}
+
+// Set the canonical output style.
+func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) {
+ emitter.canonical = canonical
+}
+
+//// Set the indentation increment.
+func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) {
+ if indent < 2 || indent > 9 {
+ indent = 2
+ }
+ emitter.best_indent = indent
+}
+
+// Set the preferred line width.
+func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) {
+ if width < 0 {
+ width = -1
+ }
+ emitter.best_width = width
+}
+
+// Set if unescaped non-ASCII characters are allowed.
+func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) {
+ emitter.unicode = unicode
+}
+
+// Set the preferred line break character.
+func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) {
+ emitter.line_break = line_break
+}
+
+///*
+// * Destroy a token object.
+// */
+//
+//YAML_DECLARE(void)
+//yaml_token_delete(yaml_token_t *token)
+//{
+// assert(token); // Non-NULL token object expected.
+//
+// switch (token.type)
+// {
+// case YAML_TAG_DIRECTIVE_TOKEN:
+// yaml_free(token.data.tag_directive.handle);
+// yaml_free(token.data.tag_directive.prefix);
+// break;
+//
+// case YAML_ALIAS_TOKEN:
+// yaml_free(token.data.alias.value);
+// break;
+//
+// case YAML_ANCHOR_TOKEN:
+// yaml_free(token.data.anchor.value);
+// break;
+//
+// case YAML_TAG_TOKEN:
+// yaml_free(token.data.tag.handle);
+// yaml_free(token.data.tag.suffix);
+// break;
+//
+// case YAML_SCALAR_TOKEN:
+// yaml_free(token.data.scalar.value);
+// break;
+//
+// default:
+// break;
+// }
+//
+// memset(token, 0, sizeof(yaml_token_t));
+//}
+//
+///*
+// * Check if a string is a valid UTF-8 sequence.
+// *
+// * Check 'reader.c' for more details on UTF-8 encoding.
+// */
+//
+//static int
+//yaml_check_utf8(yaml_char_t *start, size_t length)
+//{
+// yaml_char_t *end = start+length;
+// yaml_char_t *pointer = start;
+//
+// while (pointer < end) {
+// unsigned char octet;
+// unsigned int width;
+// unsigned int value;
+// size_t k;
+//
+// octet = pointer[0];
+// width = (octet & 0x80) == 0x00 ? 1 :
+// (octet & 0xE0) == 0xC0 ? 2 :
+// (octet & 0xF0) == 0xE0 ? 3 :
+// (octet & 0xF8) == 0xF0 ? 4 : 0;
+// value = (octet & 0x80) == 0x00 ? octet & 0x7F :
+// (octet & 0xE0) == 0xC0 ? octet & 0x1F :
+// (octet & 0xF0) == 0xE0 ? octet & 0x0F :
+// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0;
+// if (!width) return 0;
+// if (pointer+width > end) return 0;
+// for (k = 1; k < width; k ++) {
+// octet = pointer[k];
+// if ((octet & 0xC0) != 0x80) return 0;
+// value = (value << 6) + (octet & 0x3F);
+// }
+// if (!((width == 1) ||
+// (width == 2 && value >= 0x80) ||
+// (width == 3 && value >= 0x800) ||
+// (width == 4 && value >= 0x10000))) return 0;
+//
+// pointer += width;
+// }
+//
+// return 1;
+//}
+//
+
+// Create STREAM-START.
+func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) bool {
+ *event = yaml_event_t{
+ typ: yaml_STREAM_START_EVENT,
+ encoding: encoding,
+ }
+ return true
+}
+
+// Create STREAM-END.
+func yaml_stream_end_event_initialize(event *yaml_event_t) bool {
+ *event = yaml_event_t{
+ typ: yaml_STREAM_END_EVENT,
+ }
+ return true
+}
+
+// Create DOCUMENT-START.
+func yaml_document_start_event_initialize(event *yaml_event_t, version_directive *yaml_version_directive_t,
+ tag_directives []yaml_tag_directive_t, implicit bool) bool {
+ *event = yaml_event_t{
+ typ: yaml_DOCUMENT_START_EVENT,
+ version_directive: version_directive,
+ tag_directives: tag_directives,
+ implicit: implicit,
+ }
+ return true
+}
+
+// Create DOCUMENT-END.
+func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) bool {
+ *event = yaml_event_t{
+ typ: yaml_DOCUMENT_END_EVENT,
+ implicit: implicit,
+ }
+ return true
+}
+
+///*
+// * Create ALIAS.
+// */
+//
+//YAML_DECLARE(int)
+//yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t)
+//{
+// mark yaml_mark_t = { 0, 0, 0 }
+// anchor_copy *yaml_char_t = NULL
+//
+// assert(event) // Non-NULL event object is expected.
+// assert(anchor) // Non-NULL anchor is expected.
+//
+// if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0
+//
+// anchor_copy = yaml_strdup(anchor)
+// if (!anchor_copy)
+// return 0
+//
+// ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark)
+//
+// return 1
+//}
+
+// Create SCALAR.
+func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool {
+ *event = yaml_event_t{
+ typ: yaml_SCALAR_EVENT,
+ anchor: anchor,
+ tag: tag,
+ value: value,
+ implicit: plain_implicit,
+ quoted_implicit: quoted_implicit,
+ style: yaml_style_t(style),
+ }
+ return true
+}
+
+// Create SEQUENCE-START.
+func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool {
+ *event = yaml_event_t{
+ typ: yaml_SEQUENCE_START_EVENT,
+ anchor: anchor,
+ tag: tag,
+ implicit: implicit,
+ style: yaml_style_t(style),
+ }
+ return true
+}
+
+// Create SEQUENCE-END.
+func yaml_sequence_end_event_initialize(event *yaml_event_t) bool {
+ *event = yaml_event_t{
+ typ: yaml_SEQUENCE_END_EVENT,
+ }
+ return true
+}
+
+// Create MAPPING-START.
+func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) bool {
+ *event = yaml_event_t{
+ typ: yaml_MAPPING_START_EVENT,
+ anchor: anchor,
+ tag: tag,
+ implicit: implicit,
+ style: yaml_style_t(style),
+ }
+ return true
+}
+
+// Create MAPPING-END.
+func yaml_mapping_end_event_initialize(event *yaml_event_t) bool {
+ *event = yaml_event_t{
+ typ: yaml_MAPPING_END_EVENT,
+ }
+ return true
+}
+
+// Destroy an event object.
+func yaml_event_delete(event *yaml_event_t) {
+ *event = yaml_event_t{}
+}
+
+///*
+// * Create a document object.
+// */
+//
+//YAML_DECLARE(int)
+//yaml_document_initialize(document *yaml_document_t,
+// version_directive *yaml_version_directive_t,
+// tag_directives_start *yaml_tag_directive_t,
+// tag_directives_end *yaml_tag_directive_t,
+// start_implicit int, end_implicit int)
+//{
+// struct {
+// error yaml_error_type_t
+// } context
+// struct {
+// start *yaml_node_t
+// end *yaml_node_t
+// top *yaml_node_t
+// } nodes = { NULL, NULL, NULL }
+// version_directive_copy *yaml_version_directive_t = NULL
+// struct {
+// start *yaml_tag_directive_t
+// end *yaml_tag_directive_t
+// top *yaml_tag_directive_t
+// } tag_directives_copy = { NULL, NULL, NULL }
+// value yaml_tag_directive_t = { NULL, NULL }
+// mark yaml_mark_t = { 0, 0, 0 }
+//
+// assert(document) // Non-NULL document object is expected.
+// assert((tag_directives_start && tag_directives_end) ||
+// (tag_directives_start == tag_directives_end))
+// // Valid tag directives are expected.
+//
+// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error
+//
+// if (version_directive) {
+// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t))
+// if (!version_directive_copy) goto error
+// version_directive_copy.major = version_directive.major
+// version_directive_copy.minor = version_directive.minor
+// }
+//
+// if (tag_directives_start != tag_directives_end) {
+// tag_directive *yaml_tag_directive_t
+// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE))
+// goto error
+// for (tag_directive = tag_directives_start
+// tag_directive != tag_directives_end; tag_directive ++) {
+// assert(tag_directive.handle)
+// assert(tag_directive.prefix)
+// if (!yaml_check_utf8(tag_directive.handle,
+// strlen((char *)tag_directive.handle)))
+// goto error
+// if (!yaml_check_utf8(tag_directive.prefix,
+// strlen((char *)tag_directive.prefix)))
+// goto error
+// value.handle = yaml_strdup(tag_directive.handle)
+// value.prefix = yaml_strdup(tag_directive.prefix)
+// if (!value.handle || !value.prefix) goto error
+// if (!PUSH(&context, tag_directives_copy, value))
+// goto error
+// value.handle = NULL
+// value.prefix = NULL
+// }
+// }
+//
+// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy,
+// tag_directives_copy.start, tag_directives_copy.top,
+// start_implicit, end_implicit, mark, mark)
+//
+// return 1
+//
+//error:
+// STACK_DEL(&context, nodes)
+// yaml_free(version_directive_copy)
+// while (!STACK_EMPTY(&context, tag_directives_copy)) {
+// value yaml_tag_directive_t = POP(&context, tag_directives_copy)
+// yaml_free(value.handle)
+// yaml_free(value.prefix)
+// }
+// STACK_DEL(&context, tag_directives_copy)
+// yaml_free(value.handle)
+// yaml_free(value.prefix)
+//
+// return 0
+//}
+//
+///*
+// * Destroy a document object.
+// */
+//
+//YAML_DECLARE(void)
+//yaml_document_delete(document *yaml_document_t)
+//{
+// struct {
+// error yaml_error_type_t
+// } context
+// tag_directive *yaml_tag_directive_t
+//
+// context.error = YAML_NO_ERROR // Eliminate a compliler warning.
+//
+// assert(document) // Non-NULL document object is expected.
+//
+// while (!STACK_EMPTY(&context, document.nodes)) {
+// node yaml_node_t = POP(&context, document.nodes)
+// yaml_free(node.tag)
+// switch (node.type) {
+// case YAML_SCALAR_NODE:
+// yaml_free(node.data.scalar.value)
+// break
+// case YAML_SEQUENCE_NODE:
+// STACK_DEL(&context, node.data.sequence.items)
+// break
+// case YAML_MAPPING_NODE:
+// STACK_DEL(&context, node.data.mapping.pairs)
+// break
+// default:
+// assert(0) // Should not happen.
+// }
+// }
+// STACK_DEL(&context, document.nodes)
+//
+// yaml_free(document.version_directive)
+// for (tag_directive = document.tag_directives.start
+// tag_directive != document.tag_directives.end
+// tag_directive++) {
+// yaml_free(tag_directive.handle)
+// yaml_free(tag_directive.prefix)
+// }
+// yaml_free(document.tag_directives.start)
+//
+// memset(document, 0, sizeof(yaml_document_t))
+//}
+//
+///**
+// * Get a document node.
+// */
+//
+//YAML_DECLARE(yaml_node_t *)
+//yaml_document_get_node(document *yaml_document_t, index int)
+//{
+// assert(document) // Non-NULL document object is expected.
+//
+// if (index > 0 && document.nodes.start + index <= document.nodes.top) {
+// return document.nodes.start + index - 1
+// }
+// return NULL
+//}
+//
+///**
+// * Get the root object.
+// */
+//
+//YAML_DECLARE(yaml_node_t *)
+//yaml_document_get_root_node(document *yaml_document_t)
+//{
+// assert(document) // Non-NULL document object is expected.
+//
+// if (document.nodes.top != document.nodes.start) {
+// return document.nodes.start
+// }
+// return NULL
+//}
+//
+///*
+// * Add a scalar node to a document.
+// */
+//
+//YAML_DECLARE(int)
+//yaml_document_add_scalar(document *yaml_document_t,
+// tag *yaml_char_t, value *yaml_char_t, length int,
+// style yaml_scalar_style_t)
+//{
+// struct {
+// error yaml_error_type_t
+// } context
+// mark yaml_mark_t = { 0, 0, 0 }
+// tag_copy *yaml_char_t = NULL
+// value_copy *yaml_char_t = NULL
+// node yaml_node_t
+//
+// assert(document) // Non-NULL document object is expected.
+// assert(value) // Non-NULL value is expected.
+//
+// if (!tag) {
+// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG
+// }
+//
+// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error
+// tag_copy = yaml_strdup(tag)
+// if (!tag_copy) goto error
+//
+// if (length < 0) {
+// length = strlen((char *)value)
+// }
+//
+// if (!yaml_check_utf8(value, length)) goto error
+// value_copy = yaml_malloc(length+1)
+// if (!value_copy) goto error
+// memcpy(value_copy, value, length)
+// value_copy[length] = '\0'
+//
+// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark)
+// if (!PUSH(&context, document.nodes, node)) goto error
+//
+// return document.nodes.top - document.nodes.start
+//
+//error:
+// yaml_free(tag_copy)
+// yaml_free(value_copy)
+//
+// return 0
+//}
+//
+///*
+// * Add a sequence node to a document.
+// */
+//
+//YAML_DECLARE(int)
+//yaml_document_add_sequence(document *yaml_document_t,
+// tag *yaml_char_t, style yaml_sequence_style_t)
+//{
+// struct {
+// error yaml_error_type_t
+// } context
+// mark yaml_mark_t = { 0, 0, 0 }
+// tag_copy *yaml_char_t = NULL
+// struct {
+// start *yaml_node_item_t
+// end *yaml_node_item_t
+// top *yaml_node_item_t
+// } items = { NULL, NULL, NULL }
+// node yaml_node_t
+//
+// assert(document) // Non-NULL document object is expected.
+//
+// if (!tag) {
+// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG
+// }
+//
+// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error
+// tag_copy = yaml_strdup(tag)
+// if (!tag_copy) goto error
+//
+// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error
+//
+// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end,
+// style, mark, mark)
+// if (!PUSH(&context, document.nodes, node)) goto error
+//
+// return document.nodes.top - document.nodes.start
+//
+//error:
+// STACK_DEL(&context, items)
+// yaml_free(tag_copy)
+//
+// return 0
+//}
+//
+///*
+// * Add a mapping node to a document.
+// */
+//
+//YAML_DECLARE(int)
+//yaml_document_add_mapping(document *yaml_document_t,
+// tag *yaml_char_t, style yaml_mapping_style_t)
+//{
+// struct {
+// error yaml_error_type_t
+// } context
+// mark yaml_mark_t = { 0, 0, 0 }
+// tag_copy *yaml_char_t = NULL
+// struct {
+// start *yaml_node_pair_t
+// end *yaml_node_pair_t
+// top *yaml_node_pair_t
+// } pairs = { NULL, NULL, NULL }
+// node yaml_node_t
+//
+// assert(document) // Non-NULL document object is expected.
+//
+// if (!tag) {
+// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG
+// }
+//
+// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error
+// tag_copy = yaml_strdup(tag)
+// if (!tag_copy) goto error
+//
+// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error
+//
+// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end,
+// style, mark, mark)
+// if (!PUSH(&context, document.nodes, node)) goto error
+//
+// return document.nodes.top - document.nodes.start
+//
+//error:
+// STACK_DEL(&context, pairs)
+// yaml_free(tag_copy)
+//
+// return 0
+//}
+//
+///*
+// * Append an item to a sequence node.
+// */
+//
+//YAML_DECLARE(int)
+//yaml_document_append_sequence_item(document *yaml_document_t,
+// sequence int, item int)
+//{
+// struct {
+// error yaml_error_type_t
+// } context
+//
+// assert(document) // Non-NULL document is required.
+// assert(sequence > 0
+// && document.nodes.start + sequence <= document.nodes.top)
+// // Valid sequence id is required.
+// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE)
+// // A sequence node is required.
+// assert(item > 0 && document.nodes.start + item <= document.nodes.top)
+// // Valid item id is required.
+//
+// if (!PUSH(&context,
+// document.nodes.start[sequence-1].data.sequence.items, item))
+// return 0
+//
+// return 1
+//}
+//
+///*
+// * Append a pair of a key and a value to a mapping node.
+// */
+//
+//YAML_DECLARE(int)
+//yaml_document_append_mapping_pair(document *yaml_document_t,
+// mapping int, key int, value int)
+//{
+// struct {
+// error yaml_error_type_t
+// } context
+//
+// pair yaml_node_pair_t
+//
+// assert(document) // Non-NULL document is required.
+// assert(mapping > 0
+// && document.nodes.start + mapping <= document.nodes.top)
+// // Valid mapping id is required.
+// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE)
+// // A mapping node is required.
+// assert(key > 0 && document.nodes.start + key <= document.nodes.top)
+// // Valid key id is required.
+// assert(value > 0 && document.nodes.start + value <= document.nodes.top)
+// // Valid value id is required.
+//
+// pair.key = key
+// pair.value = value
+//
+// if (!PUSH(&context,
+// document.nodes.start[mapping-1].data.mapping.pairs, pair))
+// return 0
+//
+// return 1
+//}
+//
+//
diff --git a/vendor/gopkg.in/yaml.v2/decode.go b/vendor/gopkg.in/yaml.v2/decode.go
new file mode 100644
index 0000000..b13ab9f
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/decode.go
@@ -0,0 +1,683 @@
+package yaml
+
+import (
+ "encoding"
+ "encoding/base64"
+ "fmt"
+ "math"
+ "reflect"
+ "strconv"
+ "time"
+)
+
+const (
+ documentNode = 1 << iota
+ mappingNode
+ sequenceNode
+ scalarNode
+ aliasNode
+)
+
+type node struct {
+ kind int
+ line, column int
+ tag string
+ value string
+ implicit bool
+ children []*node
+ anchors map[string]*node
+}
+
+// ----------------------------------------------------------------------------
+// Parser, produces a node tree out of a libyaml event stream.
+
+type parser struct {
+ parser yaml_parser_t
+ event yaml_event_t
+ doc *node
+}
+
+func newParser(b []byte) *parser {
+ p := parser{}
+ if !yaml_parser_initialize(&p.parser) {
+ panic("failed to initialize YAML emitter")
+ }
+
+ if len(b) == 0 {
+ b = []byte{'\n'}
+ }
+
+ yaml_parser_set_input_string(&p.parser, b)
+
+ p.skip()
+ if p.event.typ != yaml_STREAM_START_EVENT {
+ panic("expected stream start event, got " + strconv.Itoa(int(p.event.typ)))
+ }
+ p.skip()
+ return &p
+}
+
+func (p *parser) destroy() {
+ if p.event.typ != yaml_NO_EVENT {
+ yaml_event_delete(&p.event)
+ }
+ yaml_parser_delete(&p.parser)
+}
+
+func (p *parser) skip() {
+ if p.event.typ != yaml_NO_EVENT {
+ if p.event.typ == yaml_STREAM_END_EVENT {
+ failf("attempted to go past the end of stream; corrupted value?")
+ }
+ yaml_event_delete(&p.event)
+ }
+ if !yaml_parser_parse(&p.parser, &p.event) {
+ p.fail()
+ }
+}
+
+func (p *parser) fail() {
+ var where string
+ var line int
+ if p.parser.problem_mark.line != 0 {
+ line = p.parser.problem_mark.line
+ } else if p.parser.context_mark.line != 0 {
+ line = p.parser.context_mark.line
+ }
+ if line != 0 {
+ where = "line " + strconv.Itoa(line) + ": "
+ }
+ var msg string
+ if len(p.parser.problem) > 0 {
+ msg = p.parser.problem
+ } else {
+ msg = "unknown problem parsing YAML content"
+ }
+ failf("%s%s", where, msg)
+}
+
+func (p *parser) anchor(n *node, anchor []byte) {
+ if anchor != nil {
+ p.doc.anchors[string(anchor)] = n
+ }
+}
+
+func (p *parser) parse() *node {
+ switch p.event.typ {
+ case yaml_SCALAR_EVENT:
+ return p.scalar()
+ case yaml_ALIAS_EVENT:
+ return p.alias()
+ case yaml_MAPPING_START_EVENT:
+ return p.mapping()
+ case yaml_SEQUENCE_START_EVENT:
+ return p.sequence()
+ case yaml_DOCUMENT_START_EVENT:
+ return p.document()
+ case yaml_STREAM_END_EVENT:
+ // Happens when attempting to decode an empty buffer.
+ return nil
+ default:
+ panic("attempted to parse unknown event: " + strconv.Itoa(int(p.event.typ)))
+ }
+ panic("unreachable")
+}
+
+func (p *parser) node(kind int) *node {
+ return &node{
+ kind: kind,
+ line: p.event.start_mark.line,
+ column: p.event.start_mark.column,
+ }
+}
+
+func (p *parser) document() *node {
+ n := p.node(documentNode)
+ n.anchors = make(map[string]*node)
+ p.doc = n
+ p.skip()
+ n.children = append(n.children, p.parse())
+ if p.event.typ != yaml_DOCUMENT_END_EVENT {
+ panic("expected end of document event but got " + strconv.Itoa(int(p.event.typ)))
+ }
+ p.skip()
+ return n
+}
+
+func (p *parser) alias() *node {
+ n := p.node(aliasNode)
+ n.value = string(p.event.anchor)
+ p.skip()
+ return n
+}
+
+func (p *parser) scalar() *node {
+ n := p.node(scalarNode)
+ n.value = string(p.event.value)
+ n.tag = string(p.event.tag)
+ n.implicit = p.event.implicit
+ p.anchor(n, p.event.anchor)
+ p.skip()
+ return n
+}
+
+func (p *parser) sequence() *node {
+ n := p.node(sequenceNode)
+ p.anchor(n, p.event.anchor)
+ p.skip()
+ for p.event.typ != yaml_SEQUENCE_END_EVENT {
+ n.children = append(n.children, p.parse())
+ }
+ p.skip()
+ return n
+}
+
+func (p *parser) mapping() *node {
+ n := p.node(mappingNode)
+ p.anchor(n, p.event.anchor)
+ p.skip()
+ for p.event.typ != yaml_MAPPING_END_EVENT {
+ n.children = append(n.children, p.parse(), p.parse())
+ }
+ p.skip()
+ return n
+}
+
+// ----------------------------------------------------------------------------
+// Decoder, unmarshals a node into a provided value.
+
+type decoder struct {
+ doc *node
+ aliases map[string]bool
+ mapType reflect.Type
+ terrors []string
+}
+
+var (
+ mapItemType = reflect.TypeOf(MapItem{})
+ durationType = reflect.TypeOf(time.Duration(0))
+ defaultMapType = reflect.TypeOf(map[interface{}]interface{}{})
+ ifaceType = defaultMapType.Elem()
+)
+
+func newDecoder() *decoder {
+ d := &decoder{mapType: defaultMapType}
+ d.aliases = make(map[string]bool)
+ return d
+}
+
+func (d *decoder) terror(n *node, tag string, out reflect.Value) {
+ if n.tag != "" {
+ tag = n.tag
+ }
+ value := n.value
+ if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG {
+ if len(value) > 10 {
+ value = " `" + value[:7] + "...`"
+ } else {
+ value = " `" + value + "`"
+ }
+ }
+ d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type()))
+}
+
+func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) {
+ terrlen := len(d.terrors)
+ err := u.UnmarshalYAML(func(v interface{}) (err error) {
+ defer handleErr(&err)
+ d.unmarshal(n, reflect.ValueOf(v))
+ if len(d.terrors) > terrlen {
+ issues := d.terrors[terrlen:]
+ d.terrors = d.terrors[:terrlen]
+ return &TypeError{issues}
+ }
+ return nil
+ })
+ if e, ok := err.(*TypeError); ok {
+ d.terrors = append(d.terrors, e.Errors...)
+ return false
+ }
+ if err != nil {
+ fail(err)
+ }
+ return true
+}
+
+// d.prepare initializes and dereferences pointers and calls UnmarshalYAML
+// if a value is found to implement it.
+// It returns the initialized and dereferenced out value, whether
+// unmarshalling was already done by UnmarshalYAML, and if so whether
+// its types unmarshalled appropriately.
+//
+// If n holds a null value, prepare returns before doing anything.
+func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) {
+ if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "" && n.implicit) {
+ return out, false, false
+ }
+ again := true
+ for again {
+ again = false
+ if out.Kind() == reflect.Ptr {
+ if out.IsNil() {
+ out.Set(reflect.New(out.Type().Elem()))
+ }
+ out = out.Elem()
+ again = true
+ }
+ if out.CanAddr() {
+ if u, ok := out.Addr().Interface().(Unmarshaler); ok {
+ good = d.callUnmarshaler(n, u)
+ return out, true, good
+ }
+ }
+ }
+ return out, false, false
+}
+
+func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) {
+ switch n.kind {
+ case documentNode:
+ return d.document(n, out)
+ case aliasNode:
+ return d.alias(n, out)
+ }
+ out, unmarshaled, good := d.prepare(n, out)
+ if unmarshaled {
+ return good
+ }
+ switch n.kind {
+ case scalarNode:
+ good = d.scalar(n, out)
+ case mappingNode:
+ good = d.mapping(n, out)
+ case sequenceNode:
+ good = d.sequence(n, out)
+ default:
+ panic("internal error: unknown node kind: " + strconv.Itoa(n.kind))
+ }
+ return good
+}
+
+func (d *decoder) document(n *node, out reflect.Value) (good bool) {
+ if len(n.children) == 1 {
+ d.doc = n
+ d.unmarshal(n.children[0], out)
+ return true
+ }
+ return false
+}
+
+func (d *decoder) alias(n *node, out reflect.Value) (good bool) {
+ an, ok := d.doc.anchors[n.value]
+ if !ok {
+ failf("unknown anchor '%s' referenced", n.value)
+ }
+ if d.aliases[n.value] {
+ failf("anchor '%s' value contains itself", n.value)
+ }
+ d.aliases[n.value] = true
+ good = d.unmarshal(an, out)
+ delete(d.aliases, n.value)
+ return good
+}
+
+var zeroValue reflect.Value
+
+func resetMap(out reflect.Value) {
+ for _, k := range out.MapKeys() {
+ out.SetMapIndex(k, zeroValue)
+ }
+}
+
+func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
+ var tag string
+ var resolved interface{}
+ if n.tag == "" && !n.implicit {
+ tag = yaml_STR_TAG
+ resolved = n.value
+ } else {
+ tag, resolved = resolve(n.tag, n.value)
+ if tag == yaml_BINARY_TAG {
+ data, err := base64.StdEncoding.DecodeString(resolved.(string))
+ if err != nil {
+ failf("!!binary value contains invalid base64 data")
+ }
+ resolved = string(data)
+ }
+ }
+ if resolved == nil {
+ if out.Kind() == reflect.Map && !out.CanAddr() {
+ resetMap(out)
+ } else {
+ out.Set(reflect.Zero(out.Type()))
+ }
+ return true
+ }
+ if s, ok := resolved.(string); ok && out.CanAddr() {
+ if u, ok := out.Addr().Interface().(encoding.TextUnmarshaler); ok {
+ err := u.UnmarshalText([]byte(s))
+ if err != nil {
+ fail(err)
+ }
+ return true
+ }
+ }
+ switch out.Kind() {
+ case reflect.String:
+ if tag == yaml_BINARY_TAG {
+ out.SetString(resolved.(string))
+ good = true
+ } else if resolved != nil {
+ out.SetString(n.value)
+ good = true
+ }
+ case reflect.Interface:
+ if resolved == nil {
+ out.Set(reflect.Zero(out.Type()))
+ } else {
+ out.Set(reflect.ValueOf(resolved))
+ }
+ good = true
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ switch resolved := resolved.(type) {
+ case int:
+ if !out.OverflowInt(int64(resolved)) {
+ out.SetInt(int64(resolved))
+ good = true
+ }
+ case int64:
+ if !out.OverflowInt(resolved) {
+ out.SetInt(resolved)
+ good = true
+ }
+ case uint64:
+ if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
+ out.SetInt(int64(resolved))
+ good = true
+ }
+ case float64:
+ if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
+ out.SetInt(int64(resolved))
+ good = true
+ }
+ case string:
+ if out.Type() == durationType {
+ d, err := time.ParseDuration(resolved)
+ if err == nil {
+ out.SetInt(int64(d))
+ good = true
+ }
+ }
+ }
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ switch resolved := resolved.(type) {
+ case int:
+ if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
+ out.SetUint(uint64(resolved))
+ good = true
+ }
+ case int64:
+ if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
+ out.SetUint(uint64(resolved))
+ good = true
+ }
+ case uint64:
+ if !out.OverflowUint(uint64(resolved)) {
+ out.SetUint(uint64(resolved))
+ good = true
+ }
+ case float64:
+ if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) {
+ out.SetUint(uint64(resolved))
+ good = true
+ }
+ }
+ case reflect.Bool:
+ switch resolved := resolved.(type) {
+ case bool:
+ out.SetBool(resolved)
+ good = true
+ }
+ case reflect.Float32, reflect.Float64:
+ switch resolved := resolved.(type) {
+ case int:
+ out.SetFloat(float64(resolved))
+ good = true
+ case int64:
+ out.SetFloat(float64(resolved))
+ good = true
+ case uint64:
+ out.SetFloat(float64(resolved))
+ good = true
+ case float64:
+ out.SetFloat(resolved)
+ good = true
+ }
+ case reflect.Ptr:
+ if out.Type().Elem() == reflect.TypeOf(resolved) {
+ // TODO DOes this make sense? When is out a Ptr except when decoding a nil value?
+ elem := reflect.New(out.Type().Elem())
+ elem.Elem().Set(reflect.ValueOf(resolved))
+ out.Set(elem)
+ good = true
+ }
+ }
+ if !good {
+ d.terror(n, tag, out)
+ }
+ return good
+}
+
+func settableValueOf(i interface{}) reflect.Value {
+ v := reflect.ValueOf(i)
+ sv := reflect.New(v.Type()).Elem()
+ sv.Set(v)
+ return sv
+}
+
+func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
+ l := len(n.children)
+
+ var iface reflect.Value
+ switch out.Kind() {
+ case reflect.Slice:
+ out.Set(reflect.MakeSlice(out.Type(), l, l))
+ case reflect.Interface:
+ // No type hints. Will have to use a generic sequence.
+ iface = out
+ out = settableValueOf(make([]interface{}, l))
+ default:
+ d.terror(n, yaml_SEQ_TAG, out)
+ return false
+ }
+ et := out.Type().Elem()
+
+ j := 0
+ for i := 0; i < l; i++ {
+ e := reflect.New(et).Elem()
+ if ok := d.unmarshal(n.children[i], e); ok {
+ out.Index(j).Set(e)
+ j++
+ }
+ }
+ out.Set(out.Slice(0, j))
+ if iface.IsValid() {
+ iface.Set(out)
+ }
+ return true
+}
+
+func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
+ switch out.Kind() {
+ case reflect.Struct:
+ return d.mappingStruct(n, out)
+ case reflect.Slice:
+ return d.mappingSlice(n, out)
+ case reflect.Map:
+ // okay
+ case reflect.Interface:
+ if d.mapType.Kind() == reflect.Map {
+ iface := out
+ out = reflect.MakeMap(d.mapType)
+ iface.Set(out)
+ } else {
+ slicev := reflect.New(d.mapType).Elem()
+ if !d.mappingSlice(n, slicev) {
+ return false
+ }
+ out.Set(slicev)
+ return true
+ }
+ default:
+ d.terror(n, yaml_MAP_TAG, out)
+ return false
+ }
+ outt := out.Type()
+ kt := outt.Key()
+ et := outt.Elem()
+
+ mapType := d.mapType
+ if outt.Key() == ifaceType && outt.Elem() == ifaceType {
+ d.mapType = outt
+ }
+
+ if out.IsNil() {
+ out.Set(reflect.MakeMap(outt))
+ }
+ l := len(n.children)
+ for i := 0; i < l; i += 2 {
+ if isMerge(n.children[i]) {
+ d.merge(n.children[i+1], out)
+ continue
+ }
+ k := reflect.New(kt).Elem()
+ if d.unmarshal(n.children[i], k) {
+ kkind := k.Kind()
+ if kkind == reflect.Interface {
+ kkind = k.Elem().Kind()
+ }
+ if kkind == reflect.Map || kkind == reflect.Slice {
+ failf("invalid map key: %#v", k.Interface())
+ }
+ e := reflect.New(et).Elem()
+ if d.unmarshal(n.children[i+1], e) {
+ out.SetMapIndex(k, e)
+ }
+ }
+ }
+ d.mapType = mapType
+ return true
+}
+
+func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) {
+ outt := out.Type()
+ if outt.Elem() != mapItemType {
+ d.terror(n, yaml_MAP_TAG, out)
+ return false
+ }
+
+ mapType := d.mapType
+ d.mapType = outt
+
+ var slice []MapItem
+ var l = len(n.children)
+ for i := 0; i < l; i += 2 {
+ if isMerge(n.children[i]) {
+ d.merge(n.children[i+1], out)
+ continue
+ }
+ item := MapItem{}
+ k := reflect.ValueOf(&item.Key).Elem()
+ if d.unmarshal(n.children[i], k) {
+ v := reflect.ValueOf(&item.Value).Elem()
+ if d.unmarshal(n.children[i+1], v) {
+ slice = append(slice, item)
+ }
+ }
+ }
+ out.Set(reflect.ValueOf(slice))
+ d.mapType = mapType
+ return true
+}
+
+func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) {
+ sinfo, err := getStructInfo(out.Type())
+ if err != nil {
+ panic(err)
+ }
+ name := settableValueOf("")
+ l := len(n.children)
+
+ var inlineMap reflect.Value
+ var elemType reflect.Type
+ if sinfo.InlineMap != -1 {
+ inlineMap = out.Field(sinfo.InlineMap)
+ inlineMap.Set(reflect.New(inlineMap.Type()).Elem())
+ elemType = inlineMap.Type().Elem()
+ }
+
+ for i := 0; i < l; i += 2 {
+ ni := n.children[i]
+ if isMerge(ni) {
+ d.merge(n.children[i+1], out)
+ continue
+ }
+ if !d.unmarshal(ni, name) {
+ continue
+ }
+ if info, ok := sinfo.FieldsMap[name.String()]; ok {
+ var field reflect.Value
+ if info.Inline == nil {
+ field = out.Field(info.Num)
+ } else {
+ field = out.FieldByIndex(info.Inline)
+ }
+ d.unmarshal(n.children[i+1], field)
+ } else if sinfo.InlineMap != -1 {
+ if inlineMap.IsNil() {
+ inlineMap.Set(reflect.MakeMap(inlineMap.Type()))
+ }
+ value := reflect.New(elemType).Elem()
+ d.unmarshal(n.children[i+1], value)
+ inlineMap.SetMapIndex(name, value)
+ }
+ }
+ return true
+}
+
+func failWantMap() {
+ failf("map merge requires map or sequence of maps as the value")
+}
+
+func (d *decoder) merge(n *node, out reflect.Value) {
+ switch n.kind {
+ case mappingNode:
+ d.unmarshal(n, out)
+ case aliasNode:
+ an, ok := d.doc.anchors[n.value]
+ if ok && an.kind != mappingNode {
+ failWantMap()
+ }
+ d.unmarshal(n, out)
+ case sequenceNode:
+ // Step backwards as earlier nodes take precedence.
+ for i := len(n.children) - 1; i >= 0; i-- {
+ ni := n.children[i]
+ if ni.kind == aliasNode {
+ an, ok := d.doc.anchors[ni.value]
+ if ok && an.kind != mappingNode {
+ failWantMap()
+ }
+ } else if ni.kind != mappingNode {
+ failWantMap()
+ }
+ d.unmarshal(ni, out)
+ }
+ default:
+ failWantMap()
+ }
+}
+
+func isMerge(n *node) bool {
+ return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG)
+}
diff --git a/vendor/gopkg.in/yaml.v2/emitterc.go b/vendor/gopkg.in/yaml.v2/emitterc.go
new file mode 100644
index 0000000..2befd55
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/emitterc.go
@@ -0,0 +1,1685 @@
+package yaml
+
+import (
+ "bytes"
+)
+
+// Flush the buffer if needed.
+func flush(emitter *yaml_emitter_t) bool {
+ if emitter.buffer_pos+5 >= len(emitter.buffer) {
+ return yaml_emitter_flush(emitter)
+ }
+ return true
+}
+
+// Put a character to the output buffer.
+func put(emitter *yaml_emitter_t, value byte) bool {
+ if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) {
+ return false
+ }
+ emitter.buffer[emitter.buffer_pos] = value
+ emitter.buffer_pos++
+ emitter.column++
+ return true
+}
+
+// Put a line break to the output buffer.
+func put_break(emitter *yaml_emitter_t) bool {
+ if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) {
+ return false
+ }
+ switch emitter.line_break {
+ case yaml_CR_BREAK:
+ emitter.buffer[emitter.buffer_pos] = '\r'
+ emitter.buffer_pos += 1
+ case yaml_LN_BREAK:
+ emitter.buffer[emitter.buffer_pos] = '\n'
+ emitter.buffer_pos += 1
+ case yaml_CRLN_BREAK:
+ emitter.buffer[emitter.buffer_pos+0] = '\r'
+ emitter.buffer[emitter.buffer_pos+1] = '\n'
+ emitter.buffer_pos += 2
+ default:
+ panic("unknown line break setting")
+ }
+ emitter.column = 0
+ emitter.line++
+ return true
+}
+
+// Copy a character from a string into buffer.
+func write(emitter *yaml_emitter_t, s []byte, i *int) bool {
+ if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) {
+ return false
+ }
+ p := emitter.buffer_pos
+ w := width(s[*i])
+ switch w {
+ case 4:
+ emitter.buffer[p+3] = s[*i+3]
+ fallthrough
+ case 3:
+ emitter.buffer[p+2] = s[*i+2]
+ fallthrough
+ case 2:
+ emitter.buffer[p+1] = s[*i+1]
+ fallthrough
+ case 1:
+ emitter.buffer[p+0] = s[*i+0]
+ default:
+ panic("unknown character width")
+ }
+ emitter.column++
+ emitter.buffer_pos += w
+ *i += w
+ return true
+}
+
+// Write a whole string into buffer.
+func write_all(emitter *yaml_emitter_t, s []byte) bool {
+ for i := 0; i < len(s); {
+ if !write(emitter, s, &i) {
+ return false
+ }
+ }
+ return true
+}
+
+// Copy a line break character from a string into buffer.
+func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool {
+ if s[*i] == '\n' {
+ if !put_break(emitter) {
+ return false
+ }
+ *i++
+ } else {
+ if !write(emitter, s, i) {
+ return false
+ }
+ emitter.column = 0
+ emitter.line++
+ }
+ return true
+}
+
+// Set an emitter error and return false.
+func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool {
+ emitter.error = yaml_EMITTER_ERROR
+ emitter.problem = problem
+ return false
+}
+
+// Emit an event.
+func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+ emitter.events = append(emitter.events, *event)
+ for !yaml_emitter_need_more_events(emitter) {
+ event := &emitter.events[emitter.events_head]
+ if !yaml_emitter_analyze_event(emitter, event) {
+ return false
+ }
+ if !yaml_emitter_state_machine(emitter, event) {
+ return false
+ }
+ yaml_event_delete(event)
+ emitter.events_head++
+ }
+ return true
+}
+
+// Check if we need to accumulate more events before emitting.
+//
+// We accumulate extra
+// - 1 event for DOCUMENT-START
+// - 2 events for SEQUENCE-START
+// - 3 events for MAPPING-START
+//
+func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool {
+ if emitter.events_head == len(emitter.events) {
+ return true
+ }
+ var accumulate int
+ switch emitter.events[emitter.events_head].typ {
+ case yaml_DOCUMENT_START_EVENT:
+ accumulate = 1
+ break
+ case yaml_SEQUENCE_START_EVENT:
+ accumulate = 2
+ break
+ case yaml_MAPPING_START_EVENT:
+ accumulate = 3
+ break
+ default:
+ return false
+ }
+ if len(emitter.events)-emitter.events_head > accumulate {
+ return false
+ }
+ var level int
+ for i := emitter.events_head; i < len(emitter.events); i++ {
+ switch emitter.events[i].typ {
+ case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT:
+ level++
+ case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT:
+ level--
+ }
+ if level == 0 {
+ return false
+ }
+ }
+ return true
+}
+
+// Append a directive to the directives stack.
+func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool {
+ for i := 0; i < len(emitter.tag_directives); i++ {
+ if bytes.Equal(value.handle, emitter.tag_directives[i].handle) {
+ if allow_duplicates {
+ return true
+ }
+ return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive")
+ }
+ }
+
+ // [Go] Do we actually need to copy this given garbage collection
+ // and the lack of deallocating destructors?
+ tag_copy := yaml_tag_directive_t{
+ handle: make([]byte, len(value.handle)),
+ prefix: make([]byte, len(value.prefix)),
+ }
+ copy(tag_copy.handle, value.handle)
+ copy(tag_copy.prefix, value.prefix)
+ emitter.tag_directives = append(emitter.tag_directives, tag_copy)
+ return true
+}
+
+// Increase the indentation level.
+func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool {
+ emitter.indents = append(emitter.indents, emitter.indent)
+ if emitter.indent < 0 {
+ if flow {
+ emitter.indent = emitter.best_indent
+ } else {
+ emitter.indent = 0
+ }
+ } else if !indentless {
+ emitter.indent += emitter.best_indent
+ }
+ return true
+}
+
+// State dispatcher.
+func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+ switch emitter.state {
+ default:
+ case yaml_EMIT_STREAM_START_STATE:
+ return yaml_emitter_emit_stream_start(emitter, event)
+
+ case yaml_EMIT_FIRST_DOCUMENT_START_STATE:
+ return yaml_emitter_emit_document_start(emitter, event, true)
+
+ case yaml_EMIT_DOCUMENT_START_STATE:
+ return yaml_emitter_emit_document_start(emitter, event, false)
+
+ case yaml_EMIT_DOCUMENT_CONTENT_STATE:
+ return yaml_emitter_emit_document_content(emitter, event)
+
+ case yaml_EMIT_DOCUMENT_END_STATE:
+ return yaml_emitter_emit_document_end(emitter, event)
+
+ case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE:
+ return yaml_emitter_emit_flow_sequence_item(emitter, event, true)
+
+ case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE:
+ return yaml_emitter_emit_flow_sequence_item(emitter, event, false)
+
+ case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE:
+ return yaml_emitter_emit_flow_mapping_key(emitter, event, true)
+
+ case yaml_EMIT_FLOW_MAPPING_KEY_STATE:
+ return yaml_emitter_emit_flow_mapping_key(emitter, event, false)
+
+ case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE:
+ return yaml_emitter_emit_flow_mapping_value(emitter, event, true)
+
+ case yaml_EMIT_FLOW_MAPPING_VALUE_STATE:
+ return yaml_emitter_emit_flow_mapping_value(emitter, event, false)
+
+ case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE:
+ return yaml_emitter_emit_block_sequence_item(emitter, event, true)
+
+ case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE:
+ return yaml_emitter_emit_block_sequence_item(emitter, event, false)
+
+ case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE:
+ return yaml_emitter_emit_block_mapping_key(emitter, event, true)
+
+ case yaml_EMIT_BLOCK_MAPPING_KEY_STATE:
+ return yaml_emitter_emit_block_mapping_key(emitter, event, false)
+
+ case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE:
+ return yaml_emitter_emit_block_mapping_value(emitter, event, true)
+
+ case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE:
+ return yaml_emitter_emit_block_mapping_value(emitter, event, false)
+
+ case yaml_EMIT_END_STATE:
+ return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END")
+ }
+ panic("invalid emitter state")
+}
+
+// Expect STREAM-START.
+func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+ if event.typ != yaml_STREAM_START_EVENT {
+ return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START")
+ }
+ if emitter.encoding == yaml_ANY_ENCODING {
+ emitter.encoding = event.encoding
+ if emitter.encoding == yaml_ANY_ENCODING {
+ emitter.encoding = yaml_UTF8_ENCODING
+ }
+ }
+ if emitter.best_indent < 2 || emitter.best_indent > 9 {
+ emitter.best_indent = 2
+ }
+ if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 {
+ emitter.best_width = 80
+ }
+ if emitter.best_width < 0 {
+ emitter.best_width = 1<<31 - 1
+ }
+ if emitter.line_break == yaml_ANY_BREAK {
+ emitter.line_break = yaml_LN_BREAK
+ }
+
+ emitter.indent = -1
+ emitter.line = 0
+ emitter.column = 0
+ emitter.whitespace = true
+ emitter.indention = true
+
+ if emitter.encoding != yaml_UTF8_ENCODING {
+ if !yaml_emitter_write_bom(emitter) {
+ return false
+ }
+ }
+ emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE
+ return true
+}
+
+// Expect DOCUMENT-START or STREAM-END.
+func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool {
+
+ if event.typ == yaml_DOCUMENT_START_EVENT {
+
+ if event.version_directive != nil {
+ if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) {
+ return false
+ }
+ }
+
+ for i := 0; i < len(event.tag_directives); i++ {
+ tag_directive := &event.tag_directives[i]
+ if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) {
+ return false
+ }
+ if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) {
+ return false
+ }
+ }
+
+ for i := 0; i < len(default_tag_directives); i++ {
+ tag_directive := &default_tag_directives[i]
+ if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) {
+ return false
+ }
+ }
+
+ implicit := event.implicit
+ if !first || emitter.canonical {
+ implicit = false
+ }
+
+ if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) {
+ if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+
+ if event.version_directive != nil {
+ implicit = false
+ if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+
+ if len(event.tag_directives) > 0 {
+ implicit = false
+ for i := 0; i < len(event.tag_directives); i++ {
+ tag_directive := &event.tag_directives[i]
+ if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) {
+ return false
+ }
+ if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) {
+ return false
+ }
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ }
+
+ if yaml_emitter_check_empty_document(emitter) {
+ implicit = false
+ }
+ if !implicit {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) {
+ return false
+ }
+ if emitter.canonical {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ }
+
+ emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE
+ return true
+ }
+
+ if event.typ == yaml_STREAM_END_EVENT {
+ if emitter.open_ended {
+ if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ if !yaml_emitter_flush(emitter) {
+ return false
+ }
+ emitter.state = yaml_EMIT_END_STATE
+ return true
+ }
+
+ return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END")
+}
+
+// Expect the root node.
+func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+ emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE)
+ return yaml_emitter_emit_node(emitter, event, true, false, false, false)
+}
+
+// Expect DOCUMENT-END.
+func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+ if event.typ != yaml_DOCUMENT_END_EVENT {
+ return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END")
+ }
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ if !event.implicit {
+ // [Go] Allocate the slice elsewhere.
+ if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ if !yaml_emitter_flush(emitter) {
+ return false
+ }
+ emitter.state = yaml_EMIT_DOCUMENT_START_STATE
+ emitter.tag_directives = emitter.tag_directives[:0]
+ return true
+}
+
+// Expect a flow item node.
+func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool {
+ if first {
+ if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) {
+ return false
+ }
+ if !yaml_emitter_increase_indent(emitter, true, false) {
+ return false
+ }
+ emitter.flow_level++
+ }
+
+ if event.typ == yaml_SEQUENCE_END_EVENT {
+ emitter.flow_level--
+ emitter.indent = emitter.indents[len(emitter.indents)-1]
+ emitter.indents = emitter.indents[:len(emitter.indents)-1]
+ if emitter.canonical && !first {
+ if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) {
+ return false
+ }
+ emitter.state = emitter.states[len(emitter.states)-1]
+ emitter.states = emitter.states[:len(emitter.states)-1]
+
+ return true
+ }
+
+ if !first {
+ if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) {
+ return false
+ }
+ }
+
+ if emitter.canonical || emitter.column > emitter.best_width {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE)
+ return yaml_emitter_emit_node(emitter, event, false, true, false, false)
+}
+
+// Expect a flow key node.
+func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool {
+ if first {
+ if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) {
+ return false
+ }
+ if !yaml_emitter_increase_indent(emitter, true, false) {
+ return false
+ }
+ emitter.flow_level++
+ }
+
+ if event.typ == yaml_MAPPING_END_EVENT {
+ emitter.flow_level--
+ emitter.indent = emitter.indents[len(emitter.indents)-1]
+ emitter.indents = emitter.indents[:len(emitter.indents)-1]
+ if emitter.canonical && !first {
+ if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) {
+ return false
+ }
+ emitter.state = emitter.states[len(emitter.states)-1]
+ emitter.states = emitter.states[:len(emitter.states)-1]
+ return true
+ }
+
+ if !first {
+ if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) {
+ return false
+ }
+ }
+ if emitter.canonical || emitter.column > emitter.best_width {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+
+ if !emitter.canonical && yaml_emitter_check_simple_key(emitter) {
+ emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE)
+ return yaml_emitter_emit_node(emitter, event, false, false, true, true)
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) {
+ return false
+ }
+ emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE)
+ return yaml_emitter_emit_node(emitter, event, false, false, true, false)
+}
+
+// Expect a flow value node.
+func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool {
+ if simple {
+ if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) {
+ return false
+ }
+ } else {
+ if emitter.canonical || emitter.column > emitter.best_width {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) {
+ return false
+ }
+ }
+ emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE)
+ return yaml_emitter_emit_node(emitter, event, false, false, true, false)
+}
+
+// Expect a block item node.
+func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool {
+ if first {
+ if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) {
+ return false
+ }
+ }
+ if event.typ == yaml_SEQUENCE_END_EVENT {
+ emitter.indent = emitter.indents[len(emitter.indents)-1]
+ emitter.indents = emitter.indents[:len(emitter.indents)-1]
+ emitter.state = emitter.states[len(emitter.states)-1]
+ emitter.states = emitter.states[:len(emitter.states)-1]
+ return true
+ }
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) {
+ return false
+ }
+ emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE)
+ return yaml_emitter_emit_node(emitter, event, false, true, false, false)
+}
+
+// Expect a block key node.
+func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool {
+ if first {
+ if !yaml_emitter_increase_indent(emitter, false, false) {
+ return false
+ }
+ }
+ if event.typ == yaml_MAPPING_END_EVENT {
+ emitter.indent = emitter.indents[len(emitter.indents)-1]
+ emitter.indents = emitter.indents[:len(emitter.indents)-1]
+ emitter.state = emitter.states[len(emitter.states)-1]
+ emitter.states = emitter.states[:len(emitter.states)-1]
+ return true
+ }
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ if yaml_emitter_check_simple_key(emitter) {
+ emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE)
+ return yaml_emitter_emit_node(emitter, event, false, false, true, true)
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) {
+ return false
+ }
+ emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE)
+ return yaml_emitter_emit_node(emitter, event, false, false, true, false)
+}
+
+// Expect a block value node.
+func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool {
+ if simple {
+ if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) {
+ return false
+ }
+ } else {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) {
+ return false
+ }
+ }
+ emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE)
+ return yaml_emitter_emit_node(emitter, event, false, false, true, false)
+}
+
+// Expect a node.
+func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t,
+ root bool, sequence bool, mapping bool, simple_key bool) bool {
+
+ emitter.root_context = root
+ emitter.sequence_context = sequence
+ emitter.mapping_context = mapping
+ emitter.simple_key_context = simple_key
+
+ switch event.typ {
+ case yaml_ALIAS_EVENT:
+ return yaml_emitter_emit_alias(emitter, event)
+ case yaml_SCALAR_EVENT:
+ return yaml_emitter_emit_scalar(emitter, event)
+ case yaml_SEQUENCE_START_EVENT:
+ return yaml_emitter_emit_sequence_start(emitter, event)
+ case yaml_MAPPING_START_EVENT:
+ return yaml_emitter_emit_mapping_start(emitter, event)
+ default:
+ return yaml_emitter_set_emitter_error(emitter,
+ "expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS")
+ }
+ return false
+}
+
+// Expect ALIAS.
+func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+ if !yaml_emitter_process_anchor(emitter) {
+ return false
+ }
+ emitter.state = emitter.states[len(emitter.states)-1]
+ emitter.states = emitter.states[:len(emitter.states)-1]
+ return true
+}
+
+// Expect SCALAR.
+func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+ if !yaml_emitter_select_scalar_style(emitter, event) {
+ return false
+ }
+ if !yaml_emitter_process_anchor(emitter) {
+ return false
+ }
+ if !yaml_emitter_process_tag(emitter) {
+ return false
+ }
+ if !yaml_emitter_increase_indent(emitter, true, false) {
+ return false
+ }
+ if !yaml_emitter_process_scalar(emitter) {
+ return false
+ }
+ emitter.indent = emitter.indents[len(emitter.indents)-1]
+ emitter.indents = emitter.indents[:len(emitter.indents)-1]
+ emitter.state = emitter.states[len(emitter.states)-1]
+ emitter.states = emitter.states[:len(emitter.states)-1]
+ return true
+}
+
+// Expect SEQUENCE-START.
+func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+ if !yaml_emitter_process_anchor(emitter) {
+ return false
+ }
+ if !yaml_emitter_process_tag(emitter) {
+ return false
+ }
+ if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE ||
+ yaml_emitter_check_empty_sequence(emitter) {
+ emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE
+ } else {
+ emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE
+ }
+ return true
+}
+
+// Expect MAPPING-START.
+func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+ if !yaml_emitter_process_anchor(emitter) {
+ return false
+ }
+ if !yaml_emitter_process_tag(emitter) {
+ return false
+ }
+ if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE ||
+ yaml_emitter_check_empty_mapping(emitter) {
+ emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE
+ } else {
+ emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE
+ }
+ return true
+}
+
+// Check if the document content is an empty scalar.
+func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool {
+ return false // [Go] Huh?
+}
+
+// Check if the next events represent an empty sequence.
+func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool {
+ if len(emitter.events)-emitter.events_head < 2 {
+ return false
+ }
+ return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT &&
+ emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT
+}
+
+// Check if the next events represent an empty mapping.
+func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool {
+ if len(emitter.events)-emitter.events_head < 2 {
+ return false
+ }
+ return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT &&
+ emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT
+}
+
+// Check if the next node can be expressed as a simple key.
+func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool {
+ length := 0
+ switch emitter.events[emitter.events_head].typ {
+ case yaml_ALIAS_EVENT:
+ length += len(emitter.anchor_data.anchor)
+ case yaml_SCALAR_EVENT:
+ if emitter.scalar_data.multiline {
+ return false
+ }
+ length += len(emitter.anchor_data.anchor) +
+ len(emitter.tag_data.handle) +
+ len(emitter.tag_data.suffix) +
+ len(emitter.scalar_data.value)
+ case yaml_SEQUENCE_START_EVENT:
+ if !yaml_emitter_check_empty_sequence(emitter) {
+ return false
+ }
+ length += len(emitter.anchor_data.anchor) +
+ len(emitter.tag_data.handle) +
+ len(emitter.tag_data.suffix)
+ case yaml_MAPPING_START_EVENT:
+ if !yaml_emitter_check_empty_mapping(emitter) {
+ return false
+ }
+ length += len(emitter.anchor_data.anchor) +
+ len(emitter.tag_data.handle) +
+ len(emitter.tag_data.suffix)
+ default:
+ return false
+ }
+ return length <= 128
+}
+
+// Determine an acceptable scalar style.
+func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+
+ no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0
+ if no_tag && !event.implicit && !event.quoted_implicit {
+ return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified")
+ }
+
+ style := event.scalar_style()
+ if style == yaml_ANY_SCALAR_STYLE {
+ style = yaml_PLAIN_SCALAR_STYLE
+ }
+ if emitter.canonical {
+ style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
+ }
+ if emitter.simple_key_context && emitter.scalar_data.multiline {
+ style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
+ }
+
+ if style == yaml_PLAIN_SCALAR_STYLE {
+ if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed ||
+ emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed {
+ style = yaml_SINGLE_QUOTED_SCALAR_STYLE
+ }
+ if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) {
+ style = yaml_SINGLE_QUOTED_SCALAR_STYLE
+ }
+ if no_tag && !event.implicit {
+ style = yaml_SINGLE_QUOTED_SCALAR_STYLE
+ }
+ }
+ if style == yaml_SINGLE_QUOTED_SCALAR_STYLE {
+ if !emitter.scalar_data.single_quoted_allowed {
+ style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
+ }
+ }
+ if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE {
+ if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context {
+ style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
+ }
+ }
+
+ if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE {
+ emitter.tag_data.handle = []byte{'!'}
+ }
+ emitter.scalar_data.style = style
+ return true
+}
+
+// Write an achor.
+func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool {
+ if emitter.anchor_data.anchor == nil {
+ return true
+ }
+ c := []byte{'&'}
+ if emitter.anchor_data.alias {
+ c[0] = '*'
+ }
+ if !yaml_emitter_write_indicator(emitter, c, true, false, false) {
+ return false
+ }
+ return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor)
+}
+
+// Write a tag.
+func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool {
+ if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 {
+ return true
+ }
+ if len(emitter.tag_data.handle) > 0 {
+ if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) {
+ return false
+ }
+ if len(emitter.tag_data.suffix) > 0 {
+ if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) {
+ return false
+ }
+ }
+ } else {
+ // [Go] Allocate these slices elsewhere.
+ if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) {
+ return false
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) {
+ return false
+ }
+ }
+ return true
+}
+
+// Write a scalar.
+func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool {
+ switch emitter.scalar_data.style {
+ case yaml_PLAIN_SCALAR_STYLE:
+ return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context)
+
+ case yaml_SINGLE_QUOTED_SCALAR_STYLE:
+ return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context)
+
+ case yaml_DOUBLE_QUOTED_SCALAR_STYLE:
+ return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context)
+
+ case yaml_LITERAL_SCALAR_STYLE:
+ return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value)
+
+ case yaml_FOLDED_SCALAR_STYLE:
+ return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value)
+ }
+ panic("unknown scalar style")
+}
+
+// Check if a %YAML directive is valid.
+func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool {
+ if version_directive.major != 1 || version_directive.minor != 1 {
+ return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive")
+ }
+ return true
+}
+
+// Check if a %TAG directive is valid.
+func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool {
+ handle := tag_directive.handle
+ prefix := tag_directive.prefix
+ if len(handle) == 0 {
+ return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty")
+ }
+ if handle[0] != '!' {
+ return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'")
+ }
+ if handle[len(handle)-1] != '!' {
+ return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'")
+ }
+ for i := 1; i < len(handle)-1; i += width(handle[i]) {
+ if !is_alpha(handle, i) {
+ return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only")
+ }
+ }
+ if len(prefix) == 0 {
+ return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty")
+ }
+ return true
+}
+
+// Check if an anchor is valid.
+func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool {
+ if len(anchor) == 0 {
+ problem := "anchor value must not be empty"
+ if alias {
+ problem = "alias value must not be empty"
+ }
+ return yaml_emitter_set_emitter_error(emitter, problem)
+ }
+ for i := 0; i < len(anchor); i += width(anchor[i]) {
+ if !is_alpha(anchor, i) {
+ problem := "anchor value must contain alphanumerical characters only"
+ if alias {
+ problem = "alias value must contain alphanumerical characters only"
+ }
+ return yaml_emitter_set_emitter_error(emitter, problem)
+ }
+ }
+ emitter.anchor_data.anchor = anchor
+ emitter.anchor_data.alias = alias
+ return true
+}
+
+// Check if a tag is valid.
+func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool {
+ if len(tag) == 0 {
+ return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty")
+ }
+ for i := 0; i < len(emitter.tag_directives); i++ {
+ tag_directive := &emitter.tag_directives[i]
+ if bytes.HasPrefix(tag, tag_directive.prefix) {
+ emitter.tag_data.handle = tag_directive.handle
+ emitter.tag_data.suffix = tag[len(tag_directive.prefix):]
+ return true
+ }
+ }
+ emitter.tag_data.suffix = tag
+ return true
+}
+
+// Check if a scalar is valid.
+func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool {
+ var (
+ block_indicators = false
+ flow_indicators = false
+ line_breaks = false
+ special_characters = false
+
+ leading_space = false
+ leading_break = false
+ trailing_space = false
+ trailing_break = false
+ break_space = false
+ space_break = false
+
+ preceeded_by_whitespace = false
+ followed_by_whitespace = false
+ previous_space = false
+ previous_break = false
+ )
+
+ emitter.scalar_data.value = value
+
+ if len(value) == 0 {
+ emitter.scalar_data.multiline = false
+ emitter.scalar_data.flow_plain_allowed = false
+ emitter.scalar_data.block_plain_allowed = true
+ emitter.scalar_data.single_quoted_allowed = true
+ emitter.scalar_data.block_allowed = false
+ return true
+ }
+
+ if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) {
+ block_indicators = true
+ flow_indicators = true
+ }
+
+ preceeded_by_whitespace = true
+ for i, w := 0, 0; i < len(value); i += w {
+ w = width(value[i])
+ followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w)
+
+ if i == 0 {
+ switch value[i] {
+ case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`':
+ flow_indicators = true
+ block_indicators = true
+ case '?', ':':
+ flow_indicators = true
+ if followed_by_whitespace {
+ block_indicators = true
+ }
+ case '-':
+ if followed_by_whitespace {
+ flow_indicators = true
+ block_indicators = true
+ }
+ }
+ } else {
+ switch value[i] {
+ case ',', '?', '[', ']', '{', '}':
+ flow_indicators = true
+ case ':':
+ flow_indicators = true
+ if followed_by_whitespace {
+ block_indicators = true
+ }
+ case '#':
+ if preceeded_by_whitespace {
+ flow_indicators = true
+ block_indicators = true
+ }
+ }
+ }
+
+ if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode {
+ special_characters = true
+ }
+ if is_space(value, i) {
+ if i == 0 {
+ leading_space = true
+ }
+ if i+width(value[i]) == len(value) {
+ trailing_space = true
+ }
+ if previous_break {
+ break_space = true
+ }
+ previous_space = true
+ previous_break = false
+ } else if is_break(value, i) {
+ line_breaks = true
+ if i == 0 {
+ leading_break = true
+ }
+ if i+width(value[i]) == len(value) {
+ trailing_break = true
+ }
+ if previous_space {
+ space_break = true
+ }
+ previous_space = false
+ previous_break = true
+ } else {
+ previous_space = false
+ previous_break = false
+ }
+
+ // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition.
+ preceeded_by_whitespace = is_blankz(value, i)
+ }
+
+ emitter.scalar_data.multiline = line_breaks
+ emitter.scalar_data.flow_plain_allowed = true
+ emitter.scalar_data.block_plain_allowed = true
+ emitter.scalar_data.single_quoted_allowed = true
+ emitter.scalar_data.block_allowed = true
+
+ if leading_space || leading_break || trailing_space || trailing_break {
+ emitter.scalar_data.flow_plain_allowed = false
+ emitter.scalar_data.block_plain_allowed = false
+ }
+ if trailing_space {
+ emitter.scalar_data.block_allowed = false
+ }
+ if break_space {
+ emitter.scalar_data.flow_plain_allowed = false
+ emitter.scalar_data.block_plain_allowed = false
+ emitter.scalar_data.single_quoted_allowed = false
+ }
+ if space_break || special_characters {
+ emitter.scalar_data.flow_plain_allowed = false
+ emitter.scalar_data.block_plain_allowed = false
+ emitter.scalar_data.single_quoted_allowed = false
+ emitter.scalar_data.block_allowed = false
+ }
+ if line_breaks {
+ emitter.scalar_data.flow_plain_allowed = false
+ emitter.scalar_data.block_plain_allowed = false
+ }
+ if flow_indicators {
+ emitter.scalar_data.flow_plain_allowed = false
+ }
+ if block_indicators {
+ emitter.scalar_data.block_plain_allowed = false
+ }
+ return true
+}
+
+// Check if the event data is valid.
+func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool {
+
+ emitter.anchor_data.anchor = nil
+ emitter.tag_data.handle = nil
+ emitter.tag_data.suffix = nil
+ emitter.scalar_data.value = nil
+
+ switch event.typ {
+ case yaml_ALIAS_EVENT:
+ if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) {
+ return false
+ }
+
+ case yaml_SCALAR_EVENT:
+ if len(event.anchor) > 0 {
+ if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) {
+ return false
+ }
+ }
+ if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) {
+ if !yaml_emitter_analyze_tag(emitter, event.tag) {
+ return false
+ }
+ }
+ if !yaml_emitter_analyze_scalar(emitter, event.value) {
+ return false
+ }
+
+ case yaml_SEQUENCE_START_EVENT:
+ if len(event.anchor) > 0 {
+ if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) {
+ return false
+ }
+ }
+ if len(event.tag) > 0 && (emitter.canonical || !event.implicit) {
+ if !yaml_emitter_analyze_tag(emitter, event.tag) {
+ return false
+ }
+ }
+
+ case yaml_MAPPING_START_EVENT:
+ if len(event.anchor) > 0 {
+ if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) {
+ return false
+ }
+ }
+ if len(event.tag) > 0 && (emitter.canonical || !event.implicit) {
+ if !yaml_emitter_analyze_tag(emitter, event.tag) {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// Write the BOM character.
+func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool {
+ if !flush(emitter) {
+ return false
+ }
+ pos := emitter.buffer_pos
+ emitter.buffer[pos+0] = '\xEF'
+ emitter.buffer[pos+1] = '\xBB'
+ emitter.buffer[pos+2] = '\xBF'
+ emitter.buffer_pos += 3
+ return true
+}
+
+func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool {
+ indent := emitter.indent
+ if indent < 0 {
+ indent = 0
+ }
+ if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) {
+ if !put_break(emitter) {
+ return false
+ }
+ }
+ for emitter.column < indent {
+ if !put(emitter, ' ') {
+ return false
+ }
+ }
+ emitter.whitespace = true
+ emitter.indention = true
+ return true
+}
+
+func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool {
+ if need_whitespace && !emitter.whitespace {
+ if !put(emitter, ' ') {
+ return false
+ }
+ }
+ if !write_all(emitter, indicator) {
+ return false
+ }
+ emitter.whitespace = is_whitespace
+ emitter.indention = (emitter.indention && is_indention)
+ emitter.open_ended = false
+ return true
+}
+
+func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool {
+ if !write_all(emitter, value) {
+ return false
+ }
+ emitter.whitespace = false
+ emitter.indention = false
+ return true
+}
+
+func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool {
+ if !emitter.whitespace {
+ if !put(emitter, ' ') {
+ return false
+ }
+ }
+ if !write_all(emitter, value) {
+ return false
+ }
+ emitter.whitespace = false
+ emitter.indention = false
+ return true
+}
+
+func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool {
+ if need_whitespace && !emitter.whitespace {
+ if !put(emitter, ' ') {
+ return false
+ }
+ }
+ for i := 0; i < len(value); {
+ var must_write bool
+ switch value[i] {
+ case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']':
+ must_write = true
+ default:
+ must_write = is_alpha(value, i)
+ }
+ if must_write {
+ if !write(emitter, value, &i) {
+ return false
+ }
+ } else {
+ w := width(value[i])
+ for k := 0; k < w; k++ {
+ octet := value[i]
+ i++
+ if !put(emitter, '%') {
+ return false
+ }
+
+ c := octet >> 4
+ if c < 10 {
+ c += '0'
+ } else {
+ c += 'A' - 10
+ }
+ if !put(emitter, c) {
+ return false
+ }
+
+ c = octet & 0x0f
+ if c < 10 {
+ c += '0'
+ } else {
+ c += 'A' - 10
+ }
+ if !put(emitter, c) {
+ return false
+ }
+ }
+ }
+ }
+ emitter.whitespace = false
+ emitter.indention = false
+ return true
+}
+
+func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool {
+ if !emitter.whitespace {
+ if !put(emitter, ' ') {
+ return false
+ }
+ }
+
+ spaces := false
+ breaks := false
+ for i := 0; i < len(value); {
+ if is_space(value, i) {
+ if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ i += width(value[i])
+ } else {
+ if !write(emitter, value, &i) {
+ return false
+ }
+ }
+ spaces = true
+ } else if is_break(value, i) {
+ if !breaks && value[i] == '\n' {
+ if !put_break(emitter) {
+ return false
+ }
+ }
+ if !write_break(emitter, value, &i) {
+ return false
+ }
+ emitter.indention = true
+ breaks = true
+ } else {
+ if breaks {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ if !write(emitter, value, &i) {
+ return false
+ }
+ emitter.indention = false
+ spaces = false
+ breaks = false
+ }
+ }
+
+ emitter.whitespace = false
+ emitter.indention = false
+ if emitter.root_context {
+ emitter.open_ended = true
+ }
+
+ return true
+}
+
+func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool {
+
+ if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) {
+ return false
+ }
+
+ spaces := false
+ breaks := false
+ for i := 0; i < len(value); {
+ if is_space(value, i) {
+ if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ i += width(value[i])
+ } else {
+ if !write(emitter, value, &i) {
+ return false
+ }
+ }
+ spaces = true
+ } else if is_break(value, i) {
+ if !breaks && value[i] == '\n' {
+ if !put_break(emitter) {
+ return false
+ }
+ }
+ if !write_break(emitter, value, &i) {
+ return false
+ }
+ emitter.indention = true
+ breaks = true
+ } else {
+ if breaks {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ if value[i] == '\'' {
+ if !put(emitter, '\'') {
+ return false
+ }
+ }
+ if !write(emitter, value, &i) {
+ return false
+ }
+ emitter.indention = false
+ spaces = false
+ breaks = false
+ }
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) {
+ return false
+ }
+ emitter.whitespace = false
+ emitter.indention = false
+ return true
+}
+
+func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool {
+ spaces := false
+ if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) {
+ return false
+ }
+
+ for i := 0; i < len(value); {
+ if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) ||
+ is_bom(value, i) || is_break(value, i) ||
+ value[i] == '"' || value[i] == '\\' {
+
+ octet := value[i]
+
+ var w int
+ var v rune
+ switch {
+ case octet&0x80 == 0x00:
+ w, v = 1, rune(octet&0x7F)
+ case octet&0xE0 == 0xC0:
+ w, v = 2, rune(octet&0x1F)
+ case octet&0xF0 == 0xE0:
+ w, v = 3, rune(octet&0x0F)
+ case octet&0xF8 == 0xF0:
+ w, v = 4, rune(octet&0x07)
+ }
+ for k := 1; k < w; k++ {
+ octet = value[i+k]
+ v = (v << 6) + (rune(octet) & 0x3F)
+ }
+ i += w
+
+ if !put(emitter, '\\') {
+ return false
+ }
+
+ var ok bool
+ switch v {
+ case 0x00:
+ ok = put(emitter, '0')
+ case 0x07:
+ ok = put(emitter, 'a')
+ case 0x08:
+ ok = put(emitter, 'b')
+ case 0x09:
+ ok = put(emitter, 't')
+ case 0x0A:
+ ok = put(emitter, 'n')
+ case 0x0b:
+ ok = put(emitter, 'v')
+ case 0x0c:
+ ok = put(emitter, 'f')
+ case 0x0d:
+ ok = put(emitter, 'r')
+ case 0x1b:
+ ok = put(emitter, 'e')
+ case 0x22:
+ ok = put(emitter, '"')
+ case 0x5c:
+ ok = put(emitter, '\\')
+ case 0x85:
+ ok = put(emitter, 'N')
+ case 0xA0:
+ ok = put(emitter, '_')
+ case 0x2028:
+ ok = put(emitter, 'L')
+ case 0x2029:
+ ok = put(emitter, 'P')
+ default:
+ if v <= 0xFF {
+ ok = put(emitter, 'x')
+ w = 2
+ } else if v <= 0xFFFF {
+ ok = put(emitter, 'u')
+ w = 4
+ } else {
+ ok = put(emitter, 'U')
+ w = 8
+ }
+ for k := (w - 1) * 4; ok && k >= 0; k -= 4 {
+ digit := byte((v >> uint(k)) & 0x0F)
+ if digit < 10 {
+ ok = put(emitter, digit+'0')
+ } else {
+ ok = put(emitter, digit+'A'-10)
+ }
+ }
+ }
+ if !ok {
+ return false
+ }
+ spaces = false
+ } else if is_space(value, i) {
+ if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ if is_space(value, i+1) {
+ if !put(emitter, '\\') {
+ return false
+ }
+ }
+ i += width(value[i])
+ } else if !write(emitter, value, &i) {
+ return false
+ }
+ spaces = true
+ } else {
+ if !write(emitter, value, &i) {
+ return false
+ }
+ spaces = false
+ }
+ }
+ if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) {
+ return false
+ }
+ emitter.whitespace = false
+ emitter.indention = false
+ return true
+}
+
+func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool {
+ if is_space(value, 0) || is_break(value, 0) {
+ indent_hint := []byte{'0' + byte(emitter.best_indent)}
+ if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) {
+ return false
+ }
+ }
+
+ emitter.open_ended = false
+
+ var chomp_hint [1]byte
+ if len(value) == 0 {
+ chomp_hint[0] = '-'
+ } else {
+ i := len(value) - 1
+ for value[i]&0xC0 == 0x80 {
+ i--
+ }
+ if !is_break(value, i) {
+ chomp_hint[0] = '-'
+ } else if i == 0 {
+ chomp_hint[0] = '+'
+ emitter.open_ended = true
+ } else {
+ i--
+ for value[i]&0xC0 == 0x80 {
+ i--
+ }
+ if is_break(value, i) {
+ chomp_hint[0] = '+'
+ emitter.open_ended = true
+ }
+ }
+ }
+ if chomp_hint[0] != 0 {
+ if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) {
+ return false
+ }
+ }
+ return true
+}
+
+func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool {
+ if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_block_scalar_hints(emitter, value) {
+ return false
+ }
+ if !put_break(emitter) {
+ return false
+ }
+ emitter.indention = true
+ emitter.whitespace = true
+ breaks := true
+ for i := 0; i < len(value); {
+ if is_break(value, i) {
+ if !write_break(emitter, value, &i) {
+ return false
+ }
+ emitter.indention = true
+ breaks = true
+ } else {
+ if breaks {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ }
+ if !write(emitter, value, &i) {
+ return false
+ }
+ emitter.indention = false
+ breaks = false
+ }
+ }
+
+ return true
+}
+
+func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool {
+ if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) {
+ return false
+ }
+ if !yaml_emitter_write_block_scalar_hints(emitter, value) {
+ return false
+ }
+
+ if !put_break(emitter) {
+ return false
+ }
+ emitter.indention = true
+ emitter.whitespace = true
+
+ breaks := true
+ leading_spaces := true
+ for i := 0; i < len(value); {
+ if is_break(value, i) {
+ if !breaks && !leading_spaces && value[i] == '\n' {
+ k := 0
+ for is_break(value, k) {
+ k += width(value[k])
+ }
+ if !is_blankz(value, k) {
+ if !put_break(emitter) {
+ return false
+ }
+ }
+ }
+ if !write_break(emitter, value, &i) {
+ return false
+ }
+ emitter.indention = true
+ breaks = true
+ } else {
+ if breaks {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ leading_spaces = is_blank(value, i)
+ }
+ if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width {
+ if !yaml_emitter_write_indent(emitter) {
+ return false
+ }
+ i += width(value[i])
+ } else {
+ if !write(emitter, value, &i) {
+ return false
+ }
+ }
+ emitter.indention = false
+ breaks = false
+ }
+ }
+ return true
+}
diff --git a/vendor/gopkg.in/yaml.v2/encode.go b/vendor/gopkg.in/yaml.v2/encode.go
new file mode 100644
index 0000000..84f8499
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/encode.go
@@ -0,0 +1,306 @@
+package yaml
+
+import (
+ "encoding"
+ "fmt"
+ "reflect"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+type encoder struct {
+ emitter yaml_emitter_t
+ event yaml_event_t
+ out []byte
+ flow bool
+}
+
+func newEncoder() (e *encoder) {
+ e = &encoder{}
+ e.must(yaml_emitter_initialize(&e.emitter))
+ yaml_emitter_set_output_string(&e.emitter, &e.out)
+ yaml_emitter_set_unicode(&e.emitter, true)
+ e.must(yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING))
+ e.emit()
+ e.must(yaml_document_start_event_initialize(&e.event, nil, nil, true))
+ e.emit()
+ return e
+}
+
+func (e *encoder) finish() {
+ e.must(yaml_document_end_event_initialize(&e.event, true))
+ e.emit()
+ e.emitter.open_ended = false
+ e.must(yaml_stream_end_event_initialize(&e.event))
+ e.emit()
+}
+
+func (e *encoder) destroy() {
+ yaml_emitter_delete(&e.emitter)
+}
+
+func (e *encoder) emit() {
+ // This will internally delete the e.event value.
+ if !yaml_emitter_emit(&e.emitter, &e.event) && e.event.typ != yaml_DOCUMENT_END_EVENT && e.event.typ != yaml_STREAM_END_EVENT {
+ e.must(false)
+ }
+}
+
+func (e *encoder) must(ok bool) {
+ if !ok {
+ msg := e.emitter.problem
+ if msg == "" {
+ msg = "unknown problem generating YAML content"
+ }
+ failf("%s", msg)
+ }
+}
+
+func (e *encoder) marshal(tag string, in reflect.Value) {
+ if !in.IsValid() {
+ e.nilv()
+ return
+ }
+ iface := in.Interface()
+ if m, ok := iface.(Marshaler); ok {
+ v, err := m.MarshalYAML()
+ if err != nil {
+ fail(err)
+ }
+ if v == nil {
+ e.nilv()
+ return
+ }
+ in = reflect.ValueOf(v)
+ } else if m, ok := iface.(encoding.TextMarshaler); ok {
+ text, err := m.MarshalText()
+ if err != nil {
+ fail(err)
+ }
+ in = reflect.ValueOf(string(text))
+ }
+ switch in.Kind() {
+ case reflect.Interface:
+ if in.IsNil() {
+ e.nilv()
+ } else {
+ e.marshal(tag, in.Elem())
+ }
+ case reflect.Map:
+ e.mapv(tag, in)
+ case reflect.Ptr:
+ if in.IsNil() {
+ e.nilv()
+ } else {
+ e.marshal(tag, in.Elem())
+ }
+ case reflect.Struct:
+ e.structv(tag, in)
+ case reflect.Slice:
+ if in.Type().Elem() == mapItemType {
+ e.itemsv(tag, in)
+ } else {
+ e.slicev(tag, in)
+ }
+ case reflect.String:
+ e.stringv(tag, in)
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ if in.Type() == durationType {
+ e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String()))
+ } else {
+ e.intv(tag, in)
+ }
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ e.uintv(tag, in)
+ case reflect.Float32, reflect.Float64:
+ e.floatv(tag, in)
+ case reflect.Bool:
+ e.boolv(tag, in)
+ default:
+ panic("cannot marshal type: " + in.Type().String())
+ }
+}
+
+func (e *encoder) mapv(tag string, in reflect.Value) {
+ e.mappingv(tag, func() {
+ keys := keyList(in.MapKeys())
+ sort.Sort(keys)
+ for _, k := range keys {
+ e.marshal("", k)
+ e.marshal("", in.MapIndex(k))
+ }
+ })
+}
+
+func (e *encoder) itemsv(tag string, in reflect.Value) {
+ e.mappingv(tag, func() {
+ slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem)
+ for _, item := range slice {
+ e.marshal("", reflect.ValueOf(item.Key))
+ e.marshal("", reflect.ValueOf(item.Value))
+ }
+ })
+}
+
+func (e *encoder) structv(tag string, in reflect.Value) {
+ sinfo, err := getStructInfo(in.Type())
+ if err != nil {
+ panic(err)
+ }
+ e.mappingv(tag, func() {
+ for _, info := range sinfo.FieldsList {
+ var value reflect.Value
+ if info.Inline == nil {
+ value = in.Field(info.Num)
+ } else {
+ value = in.FieldByIndex(info.Inline)
+ }
+ if info.OmitEmpty && isZero(value) {
+ continue
+ }
+ e.marshal("", reflect.ValueOf(info.Key))
+ e.flow = info.Flow
+ e.marshal("", value)
+ }
+ if sinfo.InlineMap >= 0 {
+ m := in.Field(sinfo.InlineMap)
+ if m.Len() > 0 {
+ e.flow = false
+ keys := keyList(m.MapKeys())
+ sort.Sort(keys)
+ for _, k := range keys {
+ if _, found := sinfo.FieldsMap[k.String()]; found {
+ panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String()))
+ }
+ e.marshal("", k)
+ e.flow = false
+ e.marshal("", m.MapIndex(k))
+ }
+ }
+ }
+ })
+}
+
+func (e *encoder) mappingv(tag string, f func()) {
+ implicit := tag == ""
+ style := yaml_BLOCK_MAPPING_STYLE
+ if e.flow {
+ e.flow = false
+ style = yaml_FLOW_MAPPING_STYLE
+ }
+ e.must(yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style))
+ e.emit()
+ f()
+ e.must(yaml_mapping_end_event_initialize(&e.event))
+ e.emit()
+}
+
+func (e *encoder) slicev(tag string, in reflect.Value) {
+ implicit := tag == ""
+ style := yaml_BLOCK_SEQUENCE_STYLE
+ if e.flow {
+ e.flow = false
+ style = yaml_FLOW_SEQUENCE_STYLE
+ }
+ e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style))
+ e.emit()
+ n := in.Len()
+ for i := 0; i < n; i++ {
+ e.marshal("", in.Index(i))
+ }
+ e.must(yaml_sequence_end_event_initialize(&e.event))
+ e.emit()
+}
+
+// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1.
+//
+// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported
+// in YAML 1.2 and by this package, but these should be marshalled quoted for
+// the time being for compatibility with other parsers.
+func isBase60Float(s string) (result bool) {
+ // Fast path.
+ if s == "" {
+ return false
+ }
+ c := s[0]
+ if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 {
+ return false
+ }
+ // Do the full match.
+ return base60float.MatchString(s)
+}
+
+// From http://yaml.org/type/float.html, except the regular expression there
+// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix.
+var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`)
+
+func (e *encoder) stringv(tag string, in reflect.Value) {
+ var style yaml_scalar_style_t
+ s := in.String()
+ rtag, rs := resolve("", s)
+ if rtag == yaml_BINARY_TAG {
+ if tag == "" || tag == yaml_STR_TAG {
+ tag = rtag
+ s = rs.(string)
+ } else if tag == yaml_BINARY_TAG {
+ failf("explicitly tagged !!binary data must be base64-encoded")
+ } else {
+ failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag))
+ }
+ }
+ if tag == "" && (rtag != yaml_STR_TAG || isBase60Float(s)) {
+ style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
+ } else if strings.Contains(s, "\n") {
+ style = yaml_LITERAL_SCALAR_STYLE
+ } else {
+ style = yaml_PLAIN_SCALAR_STYLE
+ }
+ e.emitScalar(s, "", tag, style)
+}
+
+func (e *encoder) boolv(tag string, in reflect.Value) {
+ var s string
+ if in.Bool() {
+ s = "true"
+ } else {
+ s = "false"
+ }
+ e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
+}
+
+func (e *encoder) intv(tag string, in reflect.Value) {
+ s := strconv.FormatInt(in.Int(), 10)
+ e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
+}
+
+func (e *encoder) uintv(tag string, in reflect.Value) {
+ s := strconv.FormatUint(in.Uint(), 10)
+ e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
+}
+
+func (e *encoder) floatv(tag string, in reflect.Value) {
+ // FIXME: Handle 64 bits here.
+ s := strconv.FormatFloat(float64(in.Float()), 'g', -1, 32)
+ switch s {
+ case "+Inf":
+ s = ".inf"
+ case "-Inf":
+ s = "-.inf"
+ case "NaN":
+ s = ".nan"
+ }
+ e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
+}
+
+func (e *encoder) nilv() {
+ e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE)
+}
+
+func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) {
+ implicit := tag == ""
+ e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style))
+ e.emit()
+}
diff --git a/vendor/gopkg.in/yaml.v2/parserc.go b/vendor/gopkg.in/yaml.v2/parserc.go
new file mode 100644
index 0000000..0a7037a
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/parserc.go
@@ -0,0 +1,1096 @@
+package yaml
+
+import (
+ "bytes"
+)
+
+// The parser implements the following grammar:
+//
+// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
+// implicit_document ::= block_node DOCUMENT-END*
+// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
+// block_node_or_indentless_sequence ::=
+// ALIAS
+// | properties (block_content | indentless_block_sequence)?
+// | block_content
+// | indentless_block_sequence
+// block_node ::= ALIAS
+// | properties block_content?
+// | block_content
+// flow_node ::= ALIAS
+// | properties flow_content?
+// | flow_content
+// properties ::= TAG ANCHOR? | ANCHOR TAG?
+// block_content ::= block_collection | flow_collection | SCALAR
+// flow_content ::= flow_collection | SCALAR
+// block_collection ::= block_sequence | block_mapping
+// flow_collection ::= flow_sequence | flow_mapping
+// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
+// indentless_sequence ::= (BLOCK-ENTRY block_node?)+
+// block_mapping ::= BLOCK-MAPPING_START
+// ((KEY block_node_or_indentless_sequence?)?
+// (VALUE block_node_or_indentless_sequence?)?)*
+// BLOCK-END
+// flow_sequence ::= FLOW-SEQUENCE-START
+// (flow_sequence_entry FLOW-ENTRY)*
+// flow_sequence_entry?
+// FLOW-SEQUENCE-END
+// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+// flow_mapping ::= FLOW-MAPPING-START
+// (flow_mapping_entry FLOW-ENTRY)*
+// flow_mapping_entry?
+// FLOW-MAPPING-END
+// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+
+// Peek the next token in the token queue.
+func peek_token(parser *yaml_parser_t) *yaml_token_t {
+ if parser.token_available || yaml_parser_fetch_more_tokens(parser) {
+ return &parser.tokens[parser.tokens_head]
+ }
+ return nil
+}
+
+// Remove the next token from the queue (must be called after peek_token).
+func skip_token(parser *yaml_parser_t) {
+ parser.token_available = false
+ parser.tokens_parsed++
+ parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN
+ parser.tokens_head++
+}
+
+// Get the next event.
+func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool {
+ // Erase the event object.
+ *event = yaml_event_t{}
+
+ // No events after the end of the stream or error.
+ if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE {
+ return true
+ }
+
+ // Generate the next event.
+ return yaml_parser_state_machine(parser, event)
+}
+
+// Set parser error.
+func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool {
+ parser.error = yaml_PARSER_ERROR
+ parser.problem = problem
+ parser.problem_mark = problem_mark
+ return false
+}
+
+func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool {
+ parser.error = yaml_PARSER_ERROR
+ parser.context = context
+ parser.context_mark = context_mark
+ parser.problem = problem
+ parser.problem_mark = problem_mark
+ return false
+}
+
+// State dispatcher.
+func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool {
+ //trace("yaml_parser_state_machine", "state:", parser.state.String())
+
+ switch parser.state {
+ case yaml_PARSE_STREAM_START_STATE:
+ return yaml_parser_parse_stream_start(parser, event)
+
+ case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE:
+ return yaml_parser_parse_document_start(parser, event, true)
+
+ case yaml_PARSE_DOCUMENT_START_STATE:
+ return yaml_parser_parse_document_start(parser, event, false)
+
+ case yaml_PARSE_DOCUMENT_CONTENT_STATE:
+ return yaml_parser_parse_document_content(parser, event)
+
+ case yaml_PARSE_DOCUMENT_END_STATE:
+ return yaml_parser_parse_document_end(parser, event)
+
+ case yaml_PARSE_BLOCK_NODE_STATE:
+ return yaml_parser_parse_node(parser, event, true, false)
+
+ case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE:
+ return yaml_parser_parse_node(parser, event, true, true)
+
+ case yaml_PARSE_FLOW_NODE_STATE:
+ return yaml_parser_parse_node(parser, event, false, false)
+
+ case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE:
+ return yaml_parser_parse_block_sequence_entry(parser, event, true)
+
+ case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE:
+ return yaml_parser_parse_block_sequence_entry(parser, event, false)
+
+ case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE:
+ return yaml_parser_parse_indentless_sequence_entry(parser, event)
+
+ case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE:
+ return yaml_parser_parse_block_mapping_key(parser, event, true)
+
+ case yaml_PARSE_BLOCK_MAPPING_KEY_STATE:
+ return yaml_parser_parse_block_mapping_key(parser, event, false)
+
+ case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE:
+ return yaml_parser_parse_block_mapping_value(parser, event)
+
+ case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE:
+ return yaml_parser_parse_flow_sequence_entry(parser, event, true)
+
+ case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE:
+ return yaml_parser_parse_flow_sequence_entry(parser, event, false)
+
+ case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE:
+ return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event)
+
+ case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE:
+ return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event)
+
+ case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE:
+ return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event)
+
+ case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE:
+ return yaml_parser_parse_flow_mapping_key(parser, event, true)
+
+ case yaml_PARSE_FLOW_MAPPING_KEY_STATE:
+ return yaml_parser_parse_flow_mapping_key(parser, event, false)
+
+ case yaml_PARSE_FLOW_MAPPING_VALUE_STATE:
+ return yaml_parser_parse_flow_mapping_value(parser, event, false)
+
+ case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE:
+ return yaml_parser_parse_flow_mapping_value(parser, event, true)
+
+ default:
+ panic("invalid parser state")
+ }
+ return false
+}
+
+// Parse the production:
+// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
+// ************
+func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool {
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_STREAM_START_TOKEN {
+ return yaml_parser_set_parser_error(parser, "did not find expected <stream-start>", token.start_mark)
+ }
+ parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE
+ *event = yaml_event_t{
+ typ: yaml_STREAM_START_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.end_mark,
+ encoding: token.encoding,
+ }
+ skip_token(parser)
+ return true
+}
+
+// Parse the productions:
+// implicit_document ::= block_node DOCUMENT-END*
+// *
+// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
+// *************************
+func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool {
+
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+
+ // Parse extra document end indicators.
+ if !implicit {
+ for token.typ == yaml_DOCUMENT_END_TOKEN {
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ }
+ }
+
+ if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN &&
+ token.typ != yaml_TAG_DIRECTIVE_TOKEN &&
+ token.typ != yaml_DOCUMENT_START_TOKEN &&
+ token.typ != yaml_STREAM_END_TOKEN {
+ // Parse an implicit document.
+ if !yaml_parser_process_directives(parser, nil, nil) {
+ return false
+ }
+ parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE)
+ parser.state = yaml_PARSE_BLOCK_NODE_STATE
+
+ *event = yaml_event_t{
+ typ: yaml_DOCUMENT_START_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.end_mark,
+ }
+
+ } else if token.typ != yaml_STREAM_END_TOKEN {
+ // Parse an explicit document.
+ var version_directive *yaml_version_directive_t
+ var tag_directives []yaml_tag_directive_t
+ start_mark := token.start_mark
+ if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) {
+ return false
+ }
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_DOCUMENT_START_TOKEN {
+ yaml_parser_set_parser_error(parser,
+ "did not find expected <document start>", token.start_mark)
+ return false
+ }
+ parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE)
+ parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE
+ end_mark := token.end_mark
+
+ *event = yaml_event_t{
+ typ: yaml_DOCUMENT_START_EVENT,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ version_directive: version_directive,
+ tag_directives: tag_directives,
+ implicit: false,
+ }
+ skip_token(parser)
+
+ } else {
+ // Parse the stream end.
+ parser.state = yaml_PARSE_END_STATE
+ *event = yaml_event_t{
+ typ: yaml_STREAM_END_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.end_mark,
+ }
+ skip_token(parser)
+ }
+
+ return true
+}
+
+// Parse the productions:
+// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
+// ***********
+//
+func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool {
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ == yaml_VERSION_DIRECTIVE_TOKEN ||
+ token.typ == yaml_TAG_DIRECTIVE_TOKEN ||
+ token.typ == yaml_DOCUMENT_START_TOKEN ||
+ token.typ == yaml_DOCUMENT_END_TOKEN ||
+ token.typ == yaml_STREAM_END_TOKEN {
+ parser.state = parser.states[len(parser.states)-1]
+ parser.states = parser.states[:len(parser.states)-1]
+ return yaml_parser_process_empty_scalar(parser, event,
+ token.start_mark)
+ }
+ return yaml_parser_parse_node(parser, event, true, false)
+}
+
+// Parse the productions:
+// implicit_document ::= block_node DOCUMENT-END*
+// *************
+// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
+//
+func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool {
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+
+ start_mark := token.start_mark
+ end_mark := token.start_mark
+
+ implicit := true
+ if token.typ == yaml_DOCUMENT_END_TOKEN {
+ end_mark = token.end_mark
+ skip_token(parser)
+ implicit = false
+ }
+
+ parser.tag_directives = parser.tag_directives[:0]
+
+ parser.state = yaml_PARSE_DOCUMENT_START_STATE
+ *event = yaml_event_t{
+ typ: yaml_DOCUMENT_END_EVENT,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ implicit: implicit,
+ }
+ return true
+}
+
+// Parse the productions:
+// block_node_or_indentless_sequence ::=
+// ALIAS
+// *****
+// | properties (block_content | indentless_block_sequence)?
+// ********** *
+// | block_content | indentless_block_sequence
+// *
+// block_node ::= ALIAS
+// *****
+// | properties block_content?
+// ********** *
+// | block_content
+// *
+// flow_node ::= ALIAS
+// *****
+// | properties flow_content?
+// ********** *
+// | flow_content
+// *
+// properties ::= TAG ANCHOR? | ANCHOR TAG?
+// *************************
+// block_content ::= block_collection | flow_collection | SCALAR
+// ******
+// flow_content ::= flow_collection | SCALAR
+// ******
+func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool {
+ //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)()
+
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+
+ if token.typ == yaml_ALIAS_TOKEN {
+ parser.state = parser.states[len(parser.states)-1]
+ parser.states = parser.states[:len(parser.states)-1]
+ *event = yaml_event_t{
+ typ: yaml_ALIAS_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.end_mark,
+ anchor: token.value,
+ }
+ skip_token(parser)
+ return true
+ }
+
+ start_mark := token.start_mark
+ end_mark := token.start_mark
+
+ var tag_token bool
+ var tag_handle, tag_suffix, anchor []byte
+ var tag_mark yaml_mark_t
+ if token.typ == yaml_ANCHOR_TOKEN {
+ anchor = token.value
+ start_mark = token.start_mark
+ end_mark = token.end_mark
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ == yaml_TAG_TOKEN {
+ tag_token = true
+ tag_handle = token.value
+ tag_suffix = token.suffix
+ tag_mark = token.start_mark
+ end_mark = token.end_mark
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ }
+ } else if token.typ == yaml_TAG_TOKEN {
+ tag_token = true
+ tag_handle = token.value
+ tag_suffix = token.suffix
+ start_mark = token.start_mark
+ tag_mark = token.start_mark
+ end_mark = token.end_mark
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ == yaml_ANCHOR_TOKEN {
+ anchor = token.value
+ end_mark = token.end_mark
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ }
+ }
+
+ var tag []byte
+ if tag_token {
+ if len(tag_handle) == 0 {
+ tag = tag_suffix
+ tag_suffix = nil
+ } else {
+ for i := range parser.tag_directives {
+ if bytes.Equal(parser.tag_directives[i].handle, tag_handle) {
+ tag = append([]byte(nil), parser.tag_directives[i].prefix...)
+ tag = append(tag, tag_suffix...)
+ break
+ }
+ }
+ if len(tag) == 0 {
+ yaml_parser_set_parser_error_context(parser,
+ "while parsing a node", start_mark,
+ "found undefined tag handle", tag_mark)
+ return false
+ }
+ }
+ }
+
+ implicit := len(tag) == 0
+ if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN {
+ end_mark = token.end_mark
+ parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE
+ *event = yaml_event_t{
+ typ: yaml_SEQUENCE_START_EVENT,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ anchor: anchor,
+ tag: tag,
+ implicit: implicit,
+ style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE),
+ }
+ return true
+ }
+ if token.typ == yaml_SCALAR_TOKEN {
+ var plain_implicit, quoted_implicit bool
+ end_mark = token.end_mark
+ if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') {
+ plain_implicit = true
+ } else if len(tag) == 0 {
+ quoted_implicit = true
+ }
+ parser.state = parser.states[len(parser.states)-1]
+ parser.states = parser.states[:len(parser.states)-1]
+
+ *event = yaml_event_t{
+ typ: yaml_SCALAR_EVENT,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ anchor: anchor,
+ tag: tag,
+ value: token.value,
+ implicit: plain_implicit,
+ quoted_implicit: quoted_implicit,
+ style: yaml_style_t(token.style),
+ }
+ skip_token(parser)
+ return true
+ }
+ if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN {
+ // [Go] Some of the events below can be merged as they differ only on style.
+ end_mark = token.end_mark
+ parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE
+ *event = yaml_event_t{
+ typ: yaml_SEQUENCE_START_EVENT,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ anchor: anchor,
+ tag: tag,
+ implicit: implicit,
+ style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE),
+ }
+ return true
+ }
+ if token.typ == yaml_FLOW_MAPPING_START_TOKEN {
+ end_mark = token.end_mark
+ parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE
+ *event = yaml_event_t{
+ typ: yaml_MAPPING_START_EVENT,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ anchor: anchor,
+ tag: tag,
+ implicit: implicit,
+ style: yaml_style_t(yaml_FLOW_MAPPING_STYLE),
+ }
+ return true
+ }
+ if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN {
+ end_mark = token.end_mark
+ parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE
+ *event = yaml_event_t{
+ typ: yaml_SEQUENCE_START_EVENT,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ anchor: anchor,
+ tag: tag,
+ implicit: implicit,
+ style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE),
+ }
+ return true
+ }
+ if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN {
+ end_mark = token.end_mark
+ parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE
+ *event = yaml_event_t{
+ typ: yaml_MAPPING_START_EVENT,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ anchor: anchor,
+ tag: tag,
+ implicit: implicit,
+ style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE),
+ }
+ return true
+ }
+ if len(anchor) > 0 || len(tag) > 0 {
+ parser.state = parser.states[len(parser.states)-1]
+ parser.states = parser.states[:len(parser.states)-1]
+
+ *event = yaml_event_t{
+ typ: yaml_SCALAR_EVENT,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ anchor: anchor,
+ tag: tag,
+ implicit: implicit,
+ quoted_implicit: false,
+ style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE),
+ }
+ return true
+ }
+
+ context := "while parsing a flow node"
+ if block {
+ context = "while parsing a block node"
+ }
+ yaml_parser_set_parser_error_context(parser, context, start_mark,
+ "did not find expected node content", token.start_mark)
+ return false
+}
+
+// Parse the productions:
+// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END
+// ******************** *********** * *********
+//
+func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool {
+ if first {
+ token := peek_token(parser)
+ parser.marks = append(parser.marks, token.start_mark)
+ skip_token(parser)
+ }
+
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+
+ if token.typ == yaml_BLOCK_ENTRY_TOKEN {
+ mark := token.end_mark
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN {
+ parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE)
+ return yaml_parser_parse_node(parser, event, true, false)
+ } else {
+ parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE
+ return yaml_parser_process_empty_scalar(parser, event, mark)
+ }
+ }
+ if token.typ == yaml_BLOCK_END_TOKEN {
+ parser.state = parser.states[len(parser.states)-1]
+ parser.states = parser.states[:len(parser.states)-1]
+ parser.marks = parser.marks[:len(parser.marks)-1]
+
+ *event = yaml_event_t{
+ typ: yaml_SEQUENCE_END_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.end_mark,
+ }
+
+ skip_token(parser)
+ return true
+ }
+
+ context_mark := parser.marks[len(parser.marks)-1]
+ parser.marks = parser.marks[:len(parser.marks)-1]
+ return yaml_parser_set_parser_error_context(parser,
+ "while parsing a block collection", context_mark,
+ "did not find expected '-' indicator", token.start_mark)
+}
+
+// Parse the productions:
+// indentless_sequence ::= (BLOCK-ENTRY block_node?)+
+// *********** *
+func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool {
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+
+ if token.typ == yaml_BLOCK_ENTRY_TOKEN {
+ mark := token.end_mark
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_BLOCK_ENTRY_TOKEN &&
+ token.typ != yaml_KEY_TOKEN &&
+ token.typ != yaml_VALUE_TOKEN &&
+ token.typ != yaml_BLOCK_END_TOKEN {
+ parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE)
+ return yaml_parser_parse_node(parser, event, true, false)
+ }
+ parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE
+ return yaml_parser_process_empty_scalar(parser, event, mark)
+ }
+ parser.state = parser.states[len(parser.states)-1]
+ parser.states = parser.states[:len(parser.states)-1]
+
+ *event = yaml_event_t{
+ typ: yaml_SEQUENCE_END_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark?
+ }
+ return true
+}
+
+// Parse the productions:
+// block_mapping ::= BLOCK-MAPPING_START
+// *******************
+// ((KEY block_node_or_indentless_sequence?)?
+// *** *
+// (VALUE block_node_or_indentless_sequence?)?)*
+//
+// BLOCK-END
+// *********
+//
+func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool {
+ if first {
+ token := peek_token(parser)
+ parser.marks = append(parser.marks, token.start_mark)
+ skip_token(parser)
+ }
+
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+
+ if token.typ == yaml_KEY_TOKEN {
+ mark := token.end_mark
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_KEY_TOKEN &&
+ token.typ != yaml_VALUE_TOKEN &&
+ token.typ != yaml_BLOCK_END_TOKEN {
+ parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE)
+ return yaml_parser_parse_node(parser, event, true, true)
+ } else {
+ parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE
+ return yaml_parser_process_empty_scalar(parser, event, mark)
+ }
+ } else if token.typ == yaml_BLOCK_END_TOKEN {
+ parser.state = parser.states[len(parser.states)-1]
+ parser.states = parser.states[:len(parser.states)-1]
+ parser.marks = parser.marks[:len(parser.marks)-1]
+ *event = yaml_event_t{
+ typ: yaml_MAPPING_END_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.end_mark,
+ }
+ skip_token(parser)
+ return true
+ }
+
+ context_mark := parser.marks[len(parser.marks)-1]
+ parser.marks = parser.marks[:len(parser.marks)-1]
+ return yaml_parser_set_parser_error_context(parser,
+ "while parsing a block mapping", context_mark,
+ "did not find expected key", token.start_mark)
+}
+
+// Parse the productions:
+// block_mapping ::= BLOCK-MAPPING_START
+//
+// ((KEY block_node_or_indentless_sequence?)?
+//
+// (VALUE block_node_or_indentless_sequence?)?)*
+// ***** *
+// BLOCK-END
+//
+//
+func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool {
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ == yaml_VALUE_TOKEN {
+ mark := token.end_mark
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_KEY_TOKEN &&
+ token.typ != yaml_VALUE_TOKEN &&
+ token.typ != yaml_BLOCK_END_TOKEN {
+ parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE)
+ return yaml_parser_parse_node(parser, event, true, true)
+ }
+ parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE
+ return yaml_parser_process_empty_scalar(parser, event, mark)
+ }
+ parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE
+ return yaml_parser_process_empty_scalar(parser, event, token.start_mark)
+}
+
+// Parse the productions:
+// flow_sequence ::= FLOW-SEQUENCE-START
+// *******************
+// (flow_sequence_entry FLOW-ENTRY)*
+// * **********
+// flow_sequence_entry?
+// *
+// FLOW-SEQUENCE-END
+// *****************
+// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+// *
+//
+func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool {
+ if first {
+ token := peek_token(parser)
+ parser.marks = append(parser.marks, token.start_mark)
+ skip_token(parser)
+ }
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN {
+ if !first {
+ if token.typ == yaml_FLOW_ENTRY_TOKEN {
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ } else {
+ context_mark := parser.marks[len(parser.marks)-1]
+ parser.marks = parser.marks[:len(parser.marks)-1]
+ return yaml_parser_set_parser_error_context(parser,
+ "while parsing a flow sequence", context_mark,
+ "did not find expected ',' or ']'", token.start_mark)
+ }
+ }
+
+ if token.typ == yaml_KEY_TOKEN {
+ parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE
+ *event = yaml_event_t{
+ typ: yaml_MAPPING_START_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.end_mark,
+ implicit: true,
+ style: yaml_style_t(yaml_FLOW_MAPPING_STYLE),
+ }
+ skip_token(parser)
+ return true
+ } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN {
+ parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE)
+ return yaml_parser_parse_node(parser, event, false, false)
+ }
+ }
+
+ parser.state = parser.states[len(parser.states)-1]
+ parser.states = parser.states[:len(parser.states)-1]
+ parser.marks = parser.marks[:len(parser.marks)-1]
+
+ *event = yaml_event_t{
+ typ: yaml_SEQUENCE_END_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.end_mark,
+ }
+
+ skip_token(parser)
+ return true
+}
+
+//
+// Parse the productions:
+// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+// *** *
+//
+func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool {
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_VALUE_TOKEN &&
+ token.typ != yaml_FLOW_ENTRY_TOKEN &&
+ token.typ != yaml_FLOW_SEQUENCE_END_TOKEN {
+ parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE)
+ return yaml_parser_parse_node(parser, event, false, false)
+ }
+ mark := token.end_mark
+ skip_token(parser)
+ parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE
+ return yaml_parser_process_empty_scalar(parser, event, mark)
+}
+
+// Parse the productions:
+// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+// ***** *
+//
+func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool {
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ == yaml_VALUE_TOKEN {
+ skip_token(parser)
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN {
+ parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE)
+ return yaml_parser_parse_node(parser, event, false, false)
+ }
+ }
+ parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE
+ return yaml_parser_process_empty_scalar(parser, event, token.start_mark)
+}
+
+// Parse the productions:
+// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+// *
+//
+func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool {
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+ parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE
+ *event = yaml_event_t{
+ typ: yaml_MAPPING_END_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.start_mark, // [Go] Shouldn't this be end_mark?
+ }
+ return true
+}
+
+// Parse the productions:
+// flow_mapping ::= FLOW-MAPPING-START
+// ******************
+// (flow_mapping_entry FLOW-ENTRY)*
+// * **********
+// flow_mapping_entry?
+// ******************
+// FLOW-MAPPING-END
+// ****************
+// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+// * *** *
+//
+func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool {
+ if first {
+ token := peek_token(parser)
+ parser.marks = append(parser.marks, token.start_mark)
+ skip_token(parser)
+ }
+
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+
+ if token.typ != yaml_FLOW_MAPPING_END_TOKEN {
+ if !first {
+ if token.typ == yaml_FLOW_ENTRY_TOKEN {
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ } else {
+ context_mark := parser.marks[len(parser.marks)-1]
+ parser.marks = parser.marks[:len(parser.marks)-1]
+ return yaml_parser_set_parser_error_context(parser,
+ "while parsing a flow mapping", context_mark,
+ "did not find expected ',' or '}'", token.start_mark)
+ }
+ }
+
+ if token.typ == yaml_KEY_TOKEN {
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_VALUE_TOKEN &&
+ token.typ != yaml_FLOW_ENTRY_TOKEN &&
+ token.typ != yaml_FLOW_MAPPING_END_TOKEN {
+ parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE)
+ return yaml_parser_parse_node(parser, event, false, false)
+ } else {
+ parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE
+ return yaml_parser_process_empty_scalar(parser, event, token.start_mark)
+ }
+ } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN {
+ parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE)
+ return yaml_parser_parse_node(parser, event, false, false)
+ }
+ }
+
+ parser.state = parser.states[len(parser.states)-1]
+ parser.states = parser.states[:len(parser.states)-1]
+ parser.marks = parser.marks[:len(parser.marks)-1]
+ *event = yaml_event_t{
+ typ: yaml_MAPPING_END_EVENT,
+ start_mark: token.start_mark,
+ end_mark: token.end_mark,
+ }
+ skip_token(parser)
+ return true
+}
+
+// Parse the productions:
+// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)?
+// * ***** *
+//
+func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool {
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if empty {
+ parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE
+ return yaml_parser_process_empty_scalar(parser, event, token.start_mark)
+ }
+ if token.typ == yaml_VALUE_TOKEN {
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN {
+ parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE)
+ return yaml_parser_parse_node(parser, event, false, false)
+ }
+ }
+ parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE
+ return yaml_parser_process_empty_scalar(parser, event, token.start_mark)
+}
+
+// Generate an empty scalar event.
+func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool {
+ *event = yaml_event_t{
+ typ: yaml_SCALAR_EVENT,
+ start_mark: mark,
+ end_mark: mark,
+ value: nil, // Empty
+ implicit: true,
+ style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE),
+ }
+ return true
+}
+
+var default_tag_directives = []yaml_tag_directive_t{
+ {[]byte("!"), []byte("!")},
+ {[]byte("!!"), []byte("tag:yaml.org,2002:")},
+}
+
+// Parse directives.
+func yaml_parser_process_directives(parser *yaml_parser_t,
+ version_directive_ref **yaml_version_directive_t,
+ tag_directives_ref *[]yaml_tag_directive_t) bool {
+
+ var version_directive *yaml_version_directive_t
+ var tag_directives []yaml_tag_directive_t
+
+ token := peek_token(parser)
+ if token == nil {
+ return false
+ }
+
+ for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN {
+ if token.typ == yaml_VERSION_DIRECTIVE_TOKEN {
+ if version_directive != nil {
+ yaml_parser_set_parser_error(parser,
+ "found duplicate %YAML directive", token.start_mark)
+ return false
+ }
+ if token.major != 1 || token.minor != 1 {
+ yaml_parser_set_parser_error(parser,
+ "found incompatible YAML document", token.start_mark)
+ return false
+ }
+ version_directive = &yaml_version_directive_t{
+ major: token.major,
+ minor: token.minor,
+ }
+ } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN {
+ value := yaml_tag_directive_t{
+ handle: token.value,
+ prefix: token.prefix,
+ }
+ if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) {
+ return false
+ }
+ tag_directives = append(tag_directives, value)
+ }
+
+ skip_token(parser)
+ token = peek_token(parser)
+ if token == nil {
+ return false
+ }
+ }
+
+ for i := range default_tag_directives {
+ if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) {
+ return false
+ }
+ }
+
+ if version_directive_ref != nil {
+ *version_directive_ref = version_directive
+ }
+ if tag_directives_ref != nil {
+ *tag_directives_ref = tag_directives
+ }
+ return true
+}
+
+// Append a tag directive to the directives stack.
+func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool {
+ for i := range parser.tag_directives {
+ if bytes.Equal(value.handle, parser.tag_directives[i].handle) {
+ if allow_duplicates {
+ return true
+ }
+ return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark)
+ }
+ }
+
+ // [Go] I suspect the copy is unnecessary. This was likely done
+ // because there was no way to track ownership of the data.
+ value_copy := yaml_tag_directive_t{
+ handle: make([]byte, len(value.handle)),
+ prefix: make([]byte, len(value.prefix)),
+ }
+ copy(value_copy.handle, value.handle)
+ copy(value_copy.prefix, value.prefix)
+ parser.tag_directives = append(parser.tag_directives, value_copy)
+ return true
+}
diff --git a/vendor/gopkg.in/yaml.v2/readerc.go b/vendor/gopkg.in/yaml.v2/readerc.go
new file mode 100644
index 0000000..f450791
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/readerc.go
@@ -0,0 +1,394 @@
+package yaml
+
+import (
+ "io"
+)
+
+// Set the reader error and return 0.
+func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool {
+ parser.error = yaml_READER_ERROR
+ parser.problem = problem
+ parser.problem_offset = offset
+ parser.problem_value = value
+ return false
+}
+
+// Byte order marks.
+const (
+ bom_UTF8 = "\xef\xbb\xbf"
+ bom_UTF16LE = "\xff\xfe"
+ bom_UTF16BE = "\xfe\xff"
+)
+
+// Determine the input stream encoding by checking the BOM symbol. If no BOM is
+// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure.
+func yaml_parser_determine_encoding(parser *yaml_parser_t) bool {
+ // Ensure that we had enough bytes in the raw buffer.
+ for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 {
+ if !yaml_parser_update_raw_buffer(parser) {
+ return false
+ }
+ }
+
+ // Determine the encoding.
+ buf := parser.raw_buffer
+ pos := parser.raw_buffer_pos
+ avail := len(buf) - pos
+ if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] {
+ parser.encoding = yaml_UTF16LE_ENCODING
+ parser.raw_buffer_pos += 2
+ parser.offset += 2
+ } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] {
+ parser.encoding = yaml_UTF16BE_ENCODING
+ parser.raw_buffer_pos += 2
+ parser.offset += 2
+ } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] {
+ parser.encoding = yaml_UTF8_ENCODING
+ parser.raw_buffer_pos += 3
+ parser.offset += 3
+ } else {
+ parser.encoding = yaml_UTF8_ENCODING
+ }
+ return true
+}
+
+// Update the raw buffer.
+func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool {
+ size_read := 0
+
+ // Return if the raw buffer is full.
+ if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) {
+ return true
+ }
+
+ // Return on EOF.
+ if parser.eof {
+ return true
+ }
+
+ // Move the remaining bytes in the raw buffer to the beginning.
+ if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) {
+ copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:])
+ }
+ parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos]
+ parser.raw_buffer_pos = 0
+
+ // Call the read handler to fill the buffer.
+ size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)])
+ parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read]
+ if err == io.EOF {
+ parser.eof = true
+ } else if err != nil {
+ return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1)
+ }
+ return true
+}
+
+// Ensure that the buffer contains at least `length` characters.
+// Return true on success, false on failure.
+//
+// The length is supposed to be significantly less that the buffer size.
+func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool {
+ if parser.read_handler == nil {
+ panic("read handler must be set")
+ }
+
+ // If the EOF flag is set and the raw buffer is empty, do nothing.
+ if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) {
+ return true
+ }
+
+ // Return if the buffer contains enough characters.
+ if parser.unread >= length {
+ return true
+ }
+
+ // Determine the input encoding if it is not known yet.
+ if parser.encoding == yaml_ANY_ENCODING {
+ if !yaml_parser_determine_encoding(parser) {
+ return false
+ }
+ }
+
+ // Move the unread characters to the beginning of the buffer.
+ buffer_len := len(parser.buffer)
+ if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len {
+ copy(parser.buffer, parser.buffer[parser.buffer_pos:])
+ buffer_len -= parser.buffer_pos
+ parser.buffer_pos = 0
+ } else if parser.buffer_pos == buffer_len {
+ buffer_len = 0
+ parser.buffer_pos = 0
+ }
+
+ // Open the whole buffer for writing, and cut it before returning.
+ parser.buffer = parser.buffer[:cap(parser.buffer)]
+
+ // Fill the buffer until it has enough characters.
+ first := true
+ for parser.unread < length {
+
+ // Fill the raw buffer if necessary.
+ if !first || parser.raw_buffer_pos == len(parser.raw_buffer) {
+ if !yaml_parser_update_raw_buffer(parser) {
+ parser.buffer = parser.buffer[:buffer_len]
+ return false
+ }
+ }
+ first = false
+
+ // Decode the raw buffer.
+ inner:
+ for parser.raw_buffer_pos != len(parser.raw_buffer) {
+ var value rune
+ var width int
+
+ raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos
+
+ // Decode the next character.
+ switch parser.encoding {
+ case yaml_UTF8_ENCODING:
+ // Decode a UTF-8 character. Check RFC 3629
+ // (http://www.ietf.org/rfc/rfc3629.txt) for more details.
+ //
+ // The following table (taken from the RFC) is used for
+ // decoding.
+ //
+ // Char. number range | UTF-8 octet sequence
+ // (hexadecimal) | (binary)
+ // --------------------+------------------------------------
+ // 0000 0000-0000 007F | 0xxxxxxx
+ // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
+ // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
+ // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+ //
+ // Additionally, the characters in the range 0xD800-0xDFFF
+ // are prohibited as they are reserved for use with UTF-16
+ // surrogate pairs.
+
+ // Determine the length of the UTF-8 sequence.
+ octet := parser.raw_buffer[parser.raw_buffer_pos]
+ switch {
+ case octet&0x80 == 0x00:
+ width = 1
+ case octet&0xE0 == 0xC0:
+ width = 2
+ case octet&0xF0 == 0xE0:
+ width = 3
+ case octet&0xF8 == 0xF0:
+ width = 4
+ default:
+ // The leading octet is invalid.
+ return yaml_parser_set_reader_error(parser,
+ "invalid leading UTF-8 octet",
+ parser.offset, int(octet))
+ }
+
+ // Check if the raw buffer contains an incomplete character.
+ if width > raw_unread {
+ if parser.eof {
+ return yaml_parser_set_reader_error(parser,
+ "incomplete UTF-8 octet sequence",
+ parser.offset, -1)
+ }
+ break inner
+ }
+
+ // Decode the leading octet.
+ switch {
+ case octet&0x80 == 0x00:
+ value = rune(octet & 0x7F)
+ case octet&0xE0 == 0xC0:
+ value = rune(octet & 0x1F)
+ case octet&0xF0 == 0xE0:
+ value = rune(octet & 0x0F)
+ case octet&0xF8 == 0xF0:
+ value = rune(octet & 0x07)
+ default:
+ value = 0
+ }
+
+ // Check and decode the trailing octets.
+ for k := 1; k < width; k++ {
+ octet = parser.raw_buffer[parser.raw_buffer_pos+k]
+
+ // Check if the octet is valid.
+ if (octet & 0xC0) != 0x80 {
+ return yaml_parser_set_reader_error(parser,
+ "invalid trailing UTF-8 octet",
+ parser.offset+k, int(octet))
+ }
+
+ // Decode the octet.
+ value = (value << 6) + rune(octet&0x3F)
+ }
+
+ // Check the length of the sequence against the value.
+ switch {
+ case width == 1:
+ case width == 2 && value >= 0x80:
+ case width == 3 && value >= 0x800:
+ case width == 4 && value >= 0x10000:
+ default:
+ return yaml_parser_set_reader_error(parser,
+ "invalid length of a UTF-8 sequence",
+ parser.offset, -1)
+ }
+
+ // Check the range of the value.
+ if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF {
+ return yaml_parser_set_reader_error(parser,
+ "invalid Unicode character",
+ parser.offset, int(value))
+ }
+
+ case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING:
+ var low, high int
+ if parser.encoding == yaml_UTF16LE_ENCODING {
+ low, high = 0, 1
+ } else {
+ low, high = 1, 0
+ }
+
+ // The UTF-16 encoding is not as simple as one might
+ // naively think. Check RFC 2781
+ // (http://www.ietf.org/rfc/rfc2781.txt).
+ //
+ // Normally, two subsequent bytes describe a Unicode
+ // character. However a special technique (called a
+ // surrogate pair) is used for specifying character
+ // values larger than 0xFFFF.
+ //
+ // A surrogate pair consists of two pseudo-characters:
+ // high surrogate area (0xD800-0xDBFF)
+ // low surrogate area (0xDC00-0xDFFF)
+ //
+ // The following formulas are used for decoding
+ // and encoding characters using surrogate pairs:
+ //
+ // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF)
+ // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF)
+ // W1 = 110110yyyyyyyyyy
+ // W2 = 110111xxxxxxxxxx
+ //
+ // where U is the character value, W1 is the high surrogate
+ // area, W2 is the low surrogate area.
+
+ // Check for incomplete UTF-16 character.
+ if raw_unread < 2 {
+ if parser.eof {
+ return yaml_parser_set_reader_error(parser,
+ "incomplete UTF-16 character",
+ parser.offset, -1)
+ }
+ break inner
+ }
+
+ // Get the character.
+ value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) +
+ (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8)
+
+ // Check for unexpected low surrogate area.
+ if value&0xFC00 == 0xDC00 {
+ return yaml_parser_set_reader_error(parser,
+ "unexpected low surrogate area",
+ parser.offset, int(value))
+ }
+
+ // Check for a high surrogate area.
+ if value&0xFC00 == 0xD800 {
+ width = 4
+
+ // Check for incomplete surrogate pair.
+ if raw_unread < 4 {
+ if parser.eof {
+ return yaml_parser_set_reader_error(parser,
+ "incomplete UTF-16 surrogate pair",
+ parser.offset, -1)
+ }
+ break inner
+ }
+
+ // Get the next character.
+ value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) +
+ (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8)
+
+ // Check for a low surrogate area.
+ if value2&0xFC00 != 0xDC00 {
+ return yaml_parser_set_reader_error(parser,
+ "expected low surrogate area",
+ parser.offset+2, int(value2))
+ }
+
+ // Generate the value of the surrogate pair.
+ value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF)
+ } else {
+ width = 2
+ }
+
+ default:
+ panic("impossible")
+ }
+
+ // Check if the character is in the allowed range:
+ // #x9 | #xA | #xD | [#x20-#x7E] (8 bit)
+ // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit)
+ // | [#x10000-#x10FFFF] (32 bit)
+ switch {
+ case value == 0x09:
+ case value == 0x0A:
+ case value == 0x0D:
+ case value >= 0x20 && value <= 0x7E:
+ case value == 0x85:
+ case value >= 0xA0 && value <= 0xD7FF:
+ case value >= 0xE000 && value <= 0xFFFD:
+ case value >= 0x10000 && value <= 0x10FFFF:
+ default:
+ return yaml_parser_set_reader_error(parser,
+ "control characters are not allowed",
+ parser.offset, int(value))
+ }
+
+ // Move the raw pointers.
+ parser.raw_buffer_pos += width
+ parser.offset += width
+
+ // Finally put the character into the buffer.
+ if value <= 0x7F {
+ // 0000 0000-0000 007F . 0xxxxxxx
+ parser.buffer[buffer_len+0] = byte(value)
+ buffer_len += 1
+ } else if value <= 0x7FF {
+ // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx
+ parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6))
+ parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F))
+ buffer_len += 2
+ } else if value <= 0xFFFF {
+ // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx
+ parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12))
+ parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F))
+ parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F))
+ buffer_len += 3
+ } else {
+ // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+ parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18))
+ parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F))
+ parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F))
+ parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F))
+ buffer_len += 4
+ }
+
+ parser.unread++
+ }
+
+ // On EOF, put NUL into the buffer and return.
+ if parser.eof {
+ parser.buffer[buffer_len] = 0
+ buffer_len++
+ parser.unread++
+ break
+ }
+ }
+ parser.buffer = parser.buffer[:buffer_len]
+ return true
+}
diff --git a/vendor/gopkg.in/yaml.v2/resolve.go b/vendor/gopkg.in/yaml.v2/resolve.go
new file mode 100644
index 0000000..232313c
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/resolve.go
@@ -0,0 +1,208 @@
+package yaml
+
+import (
+ "encoding/base64"
+ "math"
+ "regexp"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+)
+
+type resolveMapItem struct {
+ value interface{}
+ tag string
+}
+
+var resolveTable = make([]byte, 256)
+var resolveMap = make(map[string]resolveMapItem)
+
+func init() {
+ t := resolveTable
+ t[int('+')] = 'S' // Sign
+ t[int('-')] = 'S'
+ for _, c := range "0123456789" {
+ t[int(c)] = 'D' // Digit
+ }
+ for _, c := range "yYnNtTfFoO~" {
+ t[int(c)] = 'M' // In map
+ }
+ t[int('.')] = '.' // Float (potentially in map)
+
+ var resolveMapList = []struct {
+ v interface{}
+ tag string
+ l []string
+ }{
+ {true, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}},
+ {true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}},
+ {true, yaml_BOOL_TAG, []string{"on", "On", "ON"}},
+ {false, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}},
+ {false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}},
+ {false, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}},
+ {nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}},
+ {math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}},
+ {math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}},
+ {math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}},
+ {math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}},
+ {"<<", yaml_MERGE_TAG, []string{"<<"}},
+ }
+
+ m := resolveMap
+ for _, item := range resolveMapList {
+ for _, s := range item.l {
+ m[s] = resolveMapItem{item.v, item.tag}
+ }
+ }
+}
+
+const longTagPrefix = "tag:yaml.org,2002:"
+
+func shortTag(tag string) string {
+ // TODO This can easily be made faster and produce less garbage.
+ if strings.HasPrefix(tag, longTagPrefix) {
+ return "!!" + tag[len(longTagPrefix):]
+ }
+ return tag
+}
+
+func longTag(tag string) string {
+ if strings.HasPrefix(tag, "!!") {
+ return longTagPrefix + tag[2:]
+ }
+ return tag
+}
+
+func resolvableTag(tag string) bool {
+ switch tag {
+ case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG:
+ return true
+ }
+ return false
+}
+
+var yamlStyleFloat = regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+][0-9]+)?$`)
+
+func resolve(tag string, in string) (rtag string, out interface{}) {
+ if !resolvableTag(tag) {
+ return tag, in
+ }
+
+ defer func() {
+ switch tag {
+ case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG:
+ return
+ }
+ failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag))
+ }()
+
+ // Any data is accepted as a !!str or !!binary.
+ // Otherwise, the prefix is enough of a hint about what it might be.
+ hint := byte('N')
+ if in != "" {
+ hint = resolveTable[in[0]]
+ }
+ if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG {
+ // Handle things we can lookup in a map.
+ if item, ok := resolveMap[in]; ok {
+ return item.tag, item.value
+ }
+
+ // Base 60 floats are a bad idea, were dropped in YAML 1.2, and
+ // are purposefully unsupported here. They're still quoted on
+ // the way out for compatibility with other parser, though.
+
+ switch hint {
+ case 'M':
+ // We've already checked the map above.
+
+ case '.':
+ // Not in the map, so maybe a normal float.
+ floatv, err := strconv.ParseFloat(in, 64)
+ if err == nil {
+ return yaml_FLOAT_TAG, floatv
+ }
+
+ case 'D', 'S':
+ // Int, float, or timestamp.
+ plain := strings.Replace(in, "_", "", -1)
+ intv, err := strconv.ParseInt(plain, 0, 64)
+ if err == nil {
+ if intv == int64(int(intv)) {
+ return yaml_INT_TAG, int(intv)
+ } else {
+ return yaml_INT_TAG, intv
+ }
+ }
+ uintv, err := strconv.ParseUint(plain, 0, 64)
+ if err == nil {
+ return yaml_INT_TAG, uintv
+ }
+ if yamlStyleFloat.MatchString(plain) {
+ floatv, err := strconv.ParseFloat(plain, 64)
+ if err == nil {
+ return yaml_FLOAT_TAG, floatv
+ }
+ }
+ if strings.HasPrefix(plain, "0b") {
+ intv, err := strconv.ParseInt(plain[2:], 2, 64)
+ if err == nil {
+ if intv == int64(int(intv)) {
+ return yaml_INT_TAG, int(intv)
+ } else {
+ return yaml_INT_TAG, intv
+ }
+ }
+ uintv, err := strconv.ParseUint(plain[2:], 2, 64)
+ if err == nil {
+ return yaml_INT_TAG, uintv
+ }
+ } else if strings.HasPrefix(plain, "-0b") {
+ intv, err := strconv.ParseInt(plain[3:], 2, 64)
+ if err == nil {
+ if intv == int64(int(intv)) {
+ return yaml_INT_TAG, -int(intv)
+ } else {
+ return yaml_INT_TAG, -intv
+ }
+ }
+ }
+ // XXX Handle timestamps here.
+
+ default:
+ panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")")
+ }
+ }
+ if tag == yaml_BINARY_TAG {
+ return yaml_BINARY_TAG, in
+ }
+ if utf8.ValidString(in) {
+ return yaml_STR_TAG, in
+ }
+ return yaml_BINARY_TAG, encodeBase64(in)
+}
+
+// encodeBase64 encodes s as base64 that is broken up into multiple lines
+// as appropriate for the resulting length.
+func encodeBase64(s string) string {
+ const lineLen = 70
+ encLen := base64.StdEncoding.EncodedLen(len(s))
+ lines := encLen/lineLen + 1
+ buf := make([]byte, encLen*2+lines)
+ in := buf[0:encLen]
+ out := buf[encLen:]
+ base64.StdEncoding.Encode(in, []byte(s))
+ k := 0
+ for i := 0; i < len(in); i += lineLen {
+ j := i + lineLen
+ if j > len(in) {
+ j = len(in)
+ }
+ k += copy(out[k:], in[i:j])
+ if lines > 1 {
+ out[k] = '\n'
+ k++
+ }
+ }
+ return string(out[:k])
+}
diff --git a/vendor/gopkg.in/yaml.v2/scannerc.go b/vendor/gopkg.in/yaml.v2/scannerc.go
new file mode 100644
index 0000000..2580800
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/scannerc.go
@@ -0,0 +1,2710 @@
+package yaml
+
+import (
+ "bytes"
+ "fmt"
+)
+
+// Introduction
+// ************
+//
+// The following notes assume that you are familiar with the YAML specification
+// (http://yaml.org/spec/cvs/current.html). We mostly follow it, although in
+// some cases we are less restrictive that it requires.
+//
+// The process of transforming a YAML stream into a sequence of events is
+// divided on two steps: Scanning and Parsing.
+//
+// The Scanner transforms the input stream into a sequence of tokens, while the
+// parser transform the sequence of tokens produced by the Scanner into a
+// sequence of parsing events.
+//
+// The Scanner is rather clever and complicated. The Parser, on the contrary,
+// is a straightforward implementation of a recursive-descendant parser (or,
+// LL(1) parser, as it is usually called).
+//
+// Actually there are two issues of Scanning that might be called "clever", the
+// rest is quite straightforward. The issues are "block collection start" and
+// "simple keys". Both issues are explained below in details.
+//
+// Here the Scanning step is explained and implemented. We start with the list
+// of all the tokens produced by the Scanner together with short descriptions.
+//
+// Now, tokens:
+//
+// STREAM-START(encoding) # The stream start.
+// STREAM-END # The stream end.
+// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive.
+// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive.
+// DOCUMENT-START # '---'
+// DOCUMENT-END # '...'
+// BLOCK-SEQUENCE-START # Indentation increase denoting a block
+// BLOCK-MAPPING-START # sequence or a block mapping.
+// BLOCK-END # Indentation decrease.
+// FLOW-SEQUENCE-START # '['
+// FLOW-SEQUENCE-END # ']'
+// BLOCK-SEQUENCE-START # '{'
+// BLOCK-SEQUENCE-END # '}'
+// BLOCK-ENTRY # '-'
+// FLOW-ENTRY # ','
+// KEY # '?' or nothing (simple keys).
+// VALUE # ':'
+// ALIAS(anchor) # '*anchor'
+// ANCHOR(anchor) # '&anchor'
+// TAG(handle,suffix) # '!handle!suffix'
+// SCALAR(value,style) # A scalar.
+//
+// The following two tokens are "virtual" tokens denoting the beginning and the
+// end of the stream:
+//
+// STREAM-START(encoding)
+// STREAM-END
+//
+// We pass the information about the input stream encoding with the
+// STREAM-START token.
+//
+// The next two tokens are responsible for tags:
+//
+// VERSION-DIRECTIVE(major,minor)
+// TAG-DIRECTIVE(handle,prefix)
+//
+// Example:
+//
+// %YAML 1.1
+// %TAG ! !foo
+// %TAG !yaml! tag:yaml.org,2002:
+// ---
+//
+// The correspoding sequence of tokens:
+//
+// STREAM-START(utf-8)
+// VERSION-DIRECTIVE(1,1)
+// TAG-DIRECTIVE("!","!foo")
+// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:")
+// DOCUMENT-START
+// STREAM-END
+//
+// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole
+// line.
+//
+// The document start and end indicators are represented by:
+//
+// DOCUMENT-START
+// DOCUMENT-END
+//
+// Note that if a YAML stream contains an implicit document (without '---'
+// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be
+// produced.
+//
+// In the following examples, we present whole documents together with the
+// produced tokens.
+//
+// 1. An implicit document:
+//
+// 'a scalar'
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// SCALAR("a scalar",single-quoted)
+// STREAM-END
+//
+// 2. An explicit document:
+//
+// ---
+// 'a scalar'
+// ...
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// DOCUMENT-START
+// SCALAR("a scalar",single-quoted)
+// DOCUMENT-END
+// STREAM-END
+//
+// 3. Several documents in a stream:
+//
+// 'a scalar'
+// ---
+// 'another scalar'
+// ---
+// 'yet another scalar'
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// SCALAR("a scalar",single-quoted)
+// DOCUMENT-START
+// SCALAR("another scalar",single-quoted)
+// DOCUMENT-START
+// SCALAR("yet another scalar",single-quoted)
+// STREAM-END
+//
+// We have already introduced the SCALAR token above. The following tokens are
+// used to describe aliases, anchors, tag, and scalars:
+//
+// ALIAS(anchor)
+// ANCHOR(anchor)
+// TAG(handle,suffix)
+// SCALAR(value,style)
+//
+// The following series of examples illustrate the usage of these tokens:
+//
+// 1. A recursive sequence:
+//
+// &A [ *A ]
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// ANCHOR("A")
+// FLOW-SEQUENCE-START
+// ALIAS("A")
+// FLOW-SEQUENCE-END
+// STREAM-END
+//
+// 2. A tagged scalar:
+//
+// !!float "3.14" # A good approximation.
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// TAG("!!","float")
+// SCALAR("3.14",double-quoted)
+// STREAM-END
+//
+// 3. Various scalar styles:
+//
+// --- # Implicit empty plain scalars do not produce tokens.
+// --- a plain scalar
+// --- 'a single-quoted scalar'
+// --- "a double-quoted scalar"
+// --- |-
+// a literal scalar
+// --- >-
+// a folded
+// scalar
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// DOCUMENT-START
+// DOCUMENT-START
+// SCALAR("a plain scalar",plain)
+// DOCUMENT-START
+// SCALAR("a single-quoted scalar",single-quoted)
+// DOCUMENT-START
+// SCALAR("a double-quoted scalar",double-quoted)
+// DOCUMENT-START
+// SCALAR("a literal scalar",literal)
+// DOCUMENT-START
+// SCALAR("a folded scalar",folded)
+// STREAM-END
+//
+// Now it's time to review collection-related tokens. We will start with
+// flow collections:
+//
+// FLOW-SEQUENCE-START
+// FLOW-SEQUENCE-END
+// FLOW-MAPPING-START
+// FLOW-MAPPING-END
+// FLOW-ENTRY
+// KEY
+// VALUE
+//
+// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and
+// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}'
+// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the
+// indicators '?' and ':', which are used for denoting mapping keys and values,
+// are represented by the KEY and VALUE tokens.
+//
+// The following examples show flow collections:
+//
+// 1. A flow sequence:
+//
+// [item 1, item 2, item 3]
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// FLOW-SEQUENCE-START
+// SCALAR("item 1",plain)
+// FLOW-ENTRY
+// SCALAR("item 2",plain)
+// FLOW-ENTRY
+// SCALAR("item 3",plain)
+// FLOW-SEQUENCE-END
+// STREAM-END
+//
+// 2. A flow mapping:
+//
+// {
+// a simple key: a value, # Note that the KEY token is produced.
+// ? a complex key: another value,
+// }
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// FLOW-MAPPING-START
+// KEY
+// SCALAR("a simple key",plain)
+// VALUE
+// SCALAR("a value",plain)
+// FLOW-ENTRY
+// KEY
+// SCALAR("a complex key",plain)
+// VALUE
+// SCALAR("another value",plain)
+// FLOW-ENTRY
+// FLOW-MAPPING-END
+// STREAM-END
+//
+// A simple key is a key which is not denoted by the '?' indicator. Note that
+// the Scanner still produce the KEY token whenever it encounters a simple key.
+//
+// For scanning block collections, the following tokens are used (note that we
+// repeat KEY and VALUE here):
+//
+// BLOCK-SEQUENCE-START
+// BLOCK-MAPPING-START
+// BLOCK-END
+// BLOCK-ENTRY
+// KEY
+// VALUE
+//
+// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation
+// increase that precedes a block collection (cf. the INDENT token in Python).
+// The token BLOCK-END denote indentation decrease that ends a block collection
+// (cf. the DEDENT token in Python). However YAML has some syntax pecularities
+// that makes detections of these tokens more complex.
+//
+// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators
+// '-', '?', and ':' correspondingly.
+//
+// The following examples show how the tokens BLOCK-SEQUENCE-START,
+// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner:
+//
+// 1. Block sequences:
+//
+// - item 1
+// - item 2
+// -
+// - item 3.1
+// - item 3.2
+// -
+// key 1: value 1
+// key 2: value 2
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// BLOCK-SEQUENCE-START
+// BLOCK-ENTRY
+// SCALAR("item 1",plain)
+// BLOCK-ENTRY
+// SCALAR("item 2",plain)
+// BLOCK-ENTRY
+// BLOCK-SEQUENCE-START
+// BLOCK-ENTRY
+// SCALAR("item 3.1",plain)
+// BLOCK-ENTRY
+// SCALAR("item 3.2",plain)
+// BLOCK-END
+// BLOCK-ENTRY
+// BLOCK-MAPPING-START
+// KEY
+// SCALAR("key 1",plain)
+// VALUE
+// SCALAR("value 1",plain)
+// KEY
+// SCALAR("key 2",plain)
+// VALUE
+// SCALAR("value 2",plain)
+// BLOCK-END
+// BLOCK-END
+// STREAM-END
+//
+// 2. Block mappings:
+//
+// a simple key: a value # The KEY token is produced here.
+// ? a complex key
+// : another value
+// a mapping:
+// key 1: value 1
+// key 2: value 2
+// a sequence:
+// - item 1
+// - item 2
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// BLOCK-MAPPING-START
+// KEY
+// SCALAR("a simple key",plain)
+// VALUE
+// SCALAR("a value",plain)
+// KEY
+// SCALAR("a complex key",plain)
+// VALUE
+// SCALAR("another value",plain)
+// KEY
+// SCALAR("a mapping",plain)
+// BLOCK-MAPPING-START
+// KEY
+// SCALAR("key 1",plain)
+// VALUE
+// SCALAR("value 1",plain)
+// KEY
+// SCALAR("key 2",plain)
+// VALUE
+// SCALAR("value 2",plain)
+// BLOCK-END
+// KEY
+// SCALAR("a sequence",plain)
+// VALUE
+// BLOCK-SEQUENCE-START
+// BLOCK-ENTRY
+// SCALAR("item 1",plain)
+// BLOCK-ENTRY
+// SCALAR("item 2",plain)
+// BLOCK-END
+// BLOCK-END
+// STREAM-END
+//
+// YAML does not always require to start a new block collection from a new
+// line. If the current line contains only '-', '?', and ':' indicators, a new
+// block collection may start at the current line. The following examples
+// illustrate this case:
+//
+// 1. Collections in a sequence:
+//
+// - - item 1
+// - item 2
+// - key 1: value 1
+// key 2: value 2
+// - ? complex key
+// : complex value
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// BLOCK-SEQUENCE-START
+// BLOCK-ENTRY
+// BLOCK-SEQUENCE-START
+// BLOCK-ENTRY
+// SCALAR("item 1",plain)
+// BLOCK-ENTRY
+// SCALAR("item 2",plain)
+// BLOCK-END
+// BLOCK-ENTRY
+// BLOCK-MAPPING-START
+// KEY
+// SCALAR("key 1",plain)
+// VALUE
+// SCALAR("value 1",plain)
+// KEY
+// SCALAR("key 2",plain)
+// VALUE
+// SCALAR("value 2",plain)
+// BLOCK-END
+// BLOCK-ENTRY
+// BLOCK-MAPPING-START
+// KEY
+// SCALAR("complex key")
+// VALUE
+// SCALAR("complex value")
+// BLOCK-END
+// BLOCK-END
+// STREAM-END
+//
+// 2. Collections in a mapping:
+//
+// ? a sequence
+// : - item 1
+// - item 2
+// ? a mapping
+// : key 1: value 1
+// key 2: value 2
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// BLOCK-MAPPING-START
+// KEY
+// SCALAR("a sequence",plain)
+// VALUE
+// BLOCK-SEQUENCE-START
+// BLOCK-ENTRY
+// SCALAR("item 1",plain)
+// BLOCK-ENTRY
+// SCALAR("item 2",plain)
+// BLOCK-END
+// KEY
+// SCALAR("a mapping",plain)
+// VALUE
+// BLOCK-MAPPING-START
+// KEY
+// SCALAR("key 1",plain)
+// VALUE
+// SCALAR("value 1",plain)
+// KEY
+// SCALAR("key 2",plain)
+// VALUE
+// SCALAR("value 2",plain)
+// BLOCK-END
+// BLOCK-END
+// STREAM-END
+//
+// YAML also permits non-indented sequences if they are included into a block
+// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced:
+//
+// key:
+// - item 1 # BLOCK-SEQUENCE-START is NOT produced here.
+// - item 2
+//
+// Tokens:
+//
+// STREAM-START(utf-8)
+// BLOCK-MAPPING-START
+// KEY
+// SCALAR("key",plain)
+// VALUE
+// BLOCK-ENTRY
+// SCALAR("item 1",plain)
+// BLOCK-ENTRY
+// SCALAR("item 2",plain)
+// BLOCK-END
+//
+
+// Ensure that the buffer contains the required number of characters.
+// Return true on success, false on failure (reader error or memory error).
+func cache(parser *yaml_parser_t, length int) bool {
+ // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B)
+ return parser.unread >= length || yaml_parser_update_buffer(parser, length)
+}
+
+// Advance the buffer pointer.
+func skip(parser *yaml_parser_t) {
+ parser.mark.index++
+ parser.mark.column++
+ parser.unread--
+ parser.buffer_pos += width(parser.buffer[parser.buffer_pos])
+}
+
+func skip_line(parser *yaml_parser_t) {
+ if is_crlf(parser.buffer, parser.buffer_pos) {
+ parser.mark.index += 2
+ parser.mark.column = 0
+ parser.mark.line++
+ parser.unread -= 2
+ parser.buffer_pos += 2
+ } else if is_break(parser.buffer, parser.buffer_pos) {
+ parser.mark.index++
+ parser.mark.column = 0
+ parser.mark.line++
+ parser.unread--
+ parser.buffer_pos += width(parser.buffer[parser.buffer_pos])
+ }
+}
+
+// Copy a character to a string buffer and advance pointers.
+func read(parser *yaml_parser_t, s []byte) []byte {
+ w := width(parser.buffer[parser.buffer_pos])
+ if w == 0 {
+ panic("invalid character sequence")
+ }
+ if len(s) == 0 {
+ s = make([]byte, 0, 32)
+ }
+ if w == 1 && len(s)+w <= cap(s) {
+ s = s[:len(s)+1]
+ s[len(s)-1] = parser.buffer[parser.buffer_pos]
+ parser.buffer_pos++
+ } else {
+ s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...)
+ parser.buffer_pos += w
+ }
+ parser.mark.index++
+ parser.mark.column++
+ parser.unread--
+ return s
+}
+
+// Copy a line break character to a string buffer and advance pointers.
+func read_line(parser *yaml_parser_t, s []byte) []byte {
+ buf := parser.buffer
+ pos := parser.buffer_pos
+ switch {
+ case buf[pos] == '\r' && buf[pos+1] == '\n':
+ // CR LF . LF
+ s = append(s, '\n')
+ parser.buffer_pos += 2
+ parser.mark.index++
+ parser.unread--
+ case buf[pos] == '\r' || buf[pos] == '\n':
+ // CR|LF . LF
+ s = append(s, '\n')
+ parser.buffer_pos += 1
+ case buf[pos] == '\xC2' && buf[pos+1] == '\x85':
+ // NEL . LF
+ s = append(s, '\n')
+ parser.buffer_pos += 2
+ case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'):
+ // LS|PS . LS|PS
+ s = append(s, buf[parser.buffer_pos:pos+3]...)
+ parser.buffer_pos += 3
+ default:
+ return s
+ }
+ parser.mark.index++
+ parser.mark.column = 0
+ parser.mark.line++
+ parser.unread--
+ return s
+}
+
+// Get the next token.
+func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool {
+ // Erase the token object.
+ *token = yaml_token_t{} // [Go] Is this necessary?
+
+ // No tokens after STREAM-END or error.
+ if parser.stream_end_produced || parser.error != yaml_NO_ERROR {
+ return true
+ }
+
+ // Ensure that the tokens queue contains enough tokens.
+ if !parser.token_available {
+ if !yaml_parser_fetch_more_tokens(parser) {
+ return false
+ }
+ }
+
+ // Fetch the next token from the queue.
+ *token = parser.tokens[parser.tokens_head]
+ parser.tokens_head++
+ parser.tokens_parsed++
+ parser.token_available = false
+
+ if token.typ == yaml_STREAM_END_TOKEN {
+ parser.stream_end_produced = true
+ }
+ return true
+}
+
+// Set the scanner error and return false.
+func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool {
+ parser.error = yaml_SCANNER_ERROR
+ parser.context = context
+ parser.context_mark = context_mark
+ parser.problem = problem
+ parser.problem_mark = parser.mark
+ return false
+}
+
+func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool {
+ context := "while parsing a tag"
+ if directive {
+ context = "while parsing a %TAG directive"
+ }
+ return yaml_parser_set_scanner_error(parser, context, context_mark, "did not find URI escaped octet")
+}
+
+func trace(args ...interface{}) func() {
+ pargs := append([]interface{}{"+++"}, args...)
+ fmt.Println(pargs...)
+ pargs = append([]interface{}{"---"}, args...)
+ return func() { fmt.Println(pargs...) }
+}
+
+// Ensure that the tokens queue contains at least one token which can be
+// returned to the Parser.
+func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool {
+ // While we need more tokens to fetch, do it.
+ for {
+ // Check if we really need to fetch more tokens.
+ need_more_tokens := false
+
+ if parser.tokens_head == len(parser.tokens) {
+ // Queue is empty.
+ need_more_tokens = true
+ } else {
+ // Check if any potential simple key may occupy the head position.
+ if !yaml_parser_stale_simple_keys(parser) {
+ return false
+ }
+
+ for i := range parser.simple_keys {
+ simple_key := &parser.simple_keys[i]
+ if simple_key.possible && simple_key.token_number == parser.tokens_parsed {
+ need_more_tokens = true
+ break
+ }
+ }
+ }
+
+ // We are finished.
+ if !need_more_tokens {
+ break
+ }
+ // Fetch the next token.
+ if !yaml_parser_fetch_next_token(parser) {
+ return false
+ }
+ }
+
+ parser.token_available = true
+ return true
+}
+
+// The dispatcher for token fetchers.
+func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool {
+ // Ensure that the buffer is initialized.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
+ // Check if we just started scanning. Fetch STREAM-START then.
+ if !parser.stream_start_produced {
+ return yaml_parser_fetch_stream_start(parser)
+ }
+
+ // Eat whitespaces and comments until we reach the next token.
+ if !yaml_parser_scan_to_next_token(parser) {
+ return false
+ }
+
+ // Remove obsolete potential simple keys.
+ if !yaml_parser_stale_simple_keys(parser) {
+ return false
+ }
+
+ // Check the indentation level against the current column.
+ if !yaml_parser_unroll_indent(parser, parser.mark.column) {
+ return false
+ }
+
+ // Ensure that the buffer contains at least 4 characters. 4 is the length
+ // of the longest indicators ('--- ' and '... ').
+ if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) {
+ return false
+ }
+
+ // Is it the end of the stream?
+ if is_z(parser.buffer, parser.buffer_pos) {
+ return yaml_parser_fetch_stream_end(parser)
+ }
+
+ // Is it a directive?
+ if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' {
+ return yaml_parser_fetch_directive(parser)
+ }
+
+ buf := parser.buffer
+ pos := parser.buffer_pos
+
+ // Is it the document start indicator?
+ if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) {
+ return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN)
+ }
+
+ // Is it the document end indicator?
+ if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) {
+ return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN)
+ }
+
+ // Is it the flow sequence start indicator?
+ if buf[pos] == '[' {
+ return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN)
+ }
+
+ // Is it the flow mapping start indicator?
+ if parser.buffer[parser.buffer_pos] == '{' {
+ return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN)
+ }
+
+ // Is it the flow sequence end indicator?
+ if parser.buffer[parser.buffer_pos] == ']' {
+ return yaml_parser_fetch_flow_collection_end(parser,
+ yaml_FLOW_SEQUENCE_END_TOKEN)
+ }
+
+ // Is it the flow mapping end indicator?
+ if parser.buffer[parser.buffer_pos] == '}' {
+ return yaml_parser_fetch_flow_collection_end(parser,
+ yaml_FLOW_MAPPING_END_TOKEN)
+ }
+
+ // Is it the flow entry indicator?
+ if parser.buffer[parser.buffer_pos] == ',' {
+ return yaml_parser_fetch_flow_entry(parser)
+ }
+
+ // Is it the block entry indicator?
+ if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) {
+ return yaml_parser_fetch_block_entry(parser)
+ }
+
+ // Is it the key indicator?
+ if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) {
+ return yaml_parser_fetch_key(parser)
+ }
+
+ // Is it the value indicator?
+ if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) {
+ return yaml_parser_fetch_value(parser)
+ }
+
+ // Is it an alias?
+ if parser.buffer[parser.buffer_pos] == '*' {
+ return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN)
+ }
+
+ // Is it an anchor?
+ if parser.buffer[parser.buffer_pos] == '&' {
+ return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN)
+ }
+
+ // Is it a tag?
+ if parser.buffer[parser.buffer_pos] == '!' {
+ return yaml_parser_fetch_tag(parser)
+ }
+
+ // Is it a literal scalar?
+ if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 {
+ return yaml_parser_fetch_block_scalar(parser, true)
+ }
+
+ // Is it a folded scalar?
+ if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 {
+ return yaml_parser_fetch_block_scalar(parser, false)
+ }
+
+ // Is it a single-quoted scalar?
+ if parser.buffer[parser.buffer_pos] == '\'' {
+ return yaml_parser_fetch_flow_scalar(parser, true)
+ }
+
+ // Is it a double-quoted scalar?
+ if parser.buffer[parser.buffer_pos] == '"' {
+ return yaml_parser_fetch_flow_scalar(parser, false)
+ }
+
+ // Is it a plain scalar?
+ //
+ // A plain scalar may start with any non-blank characters except
+ //
+ // '-', '?', ':', ',', '[', ']', '{', '}',
+ // '#', '&', '*', '!', '|', '>', '\'', '\"',
+ // '%', '@', '`'.
+ //
+ // In the block context (and, for the '-' indicator, in the flow context
+ // too), it may also start with the characters
+ //
+ // '-', '?', ':'
+ //
+ // if it is followed by a non-space character.
+ //
+ // The last rule is more restrictive than the specification requires.
+ // [Go] Make this logic more reasonable.
+ //switch parser.buffer[parser.buffer_pos] {
+ //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`':
+ //}
+ if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' ||
+ parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' ||
+ parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' ||
+ parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' ||
+ parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' ||
+ parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' ||
+ parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' ||
+ parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' ||
+ parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' ||
+ parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') ||
+ (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) ||
+ (parser.flow_level == 0 &&
+ (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') &&
+ !is_blankz(parser.buffer, parser.buffer_pos+1)) {
+ return yaml_parser_fetch_plain_scalar(parser)
+ }
+
+ // If we don't determine the token type so far, it is an error.
+ return yaml_parser_set_scanner_error(parser,
+ "while scanning for the next token", parser.mark,
+ "found character that cannot start any token")
+}
+
+// Check the list of potential simple keys and remove the positions that
+// cannot contain simple keys anymore.
+func yaml_parser_stale_simple_keys(parser *yaml_parser_t) bool {
+ // Check for a potential simple key for each flow level.
+ for i := range parser.simple_keys {
+ simple_key := &parser.simple_keys[i]
+
+ // The specification requires that a simple key
+ //
+ // - is limited to a single line,
+ // - is shorter than 1024 characters.
+ if simple_key.possible && (simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index) {
+
+ // Check if the potential simple key to be removed is required.
+ if simple_key.required {
+ return yaml_parser_set_scanner_error(parser,
+ "while scanning a simple key", simple_key.mark,
+ "could not find expected ':'")
+ }
+ simple_key.possible = false
+ }
+ }
+ return true
+}
+
+// Check if a simple key may start at the current position and add it if
+// needed.
+func yaml_parser_save_simple_key(parser *yaml_parser_t) bool {
+ // A simple key is required at the current position if the scanner is in
+ // the block context and the current column coincides with the indentation
+ // level.
+
+ required := parser.flow_level == 0 && parser.indent == parser.mark.column
+
+ // A simple key is required only when it is the first token in the current
+ // line. Therefore it is always allowed. But we add a check anyway.
+ if required && !parser.simple_key_allowed {
+ panic("should not happen")
+ }
+
+ //
+ // If the current position may start a simple key, save it.
+ //
+ if parser.simple_key_allowed {
+ simple_key := yaml_simple_key_t{
+ possible: true,
+ required: required,
+ token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head),
+ }
+ simple_key.mark = parser.mark
+
+ if !yaml_parser_remove_simple_key(parser) {
+ return false
+ }
+ parser.simple_keys[len(parser.simple_keys)-1] = simple_key
+ }
+ return true
+}
+
+// Remove a potential simple key at the current flow level.
+func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool {
+ i := len(parser.simple_keys) - 1
+ if parser.simple_keys[i].possible {
+ // If the key is required, it is an error.
+ if parser.simple_keys[i].required {
+ return yaml_parser_set_scanner_error(parser,
+ "while scanning a simple key", parser.simple_keys[i].mark,
+ "could not find expected ':'")
+ }
+ }
+ // Remove the key from the stack.
+ parser.simple_keys[i].possible = false
+ return true
+}
+
+// Increase the flow level and resize the simple key list if needed.
+func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool {
+ // Reset the simple key on the next level.
+ parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{})
+
+ // Increase the flow level.
+ parser.flow_level++
+ return true
+}
+
+// Decrease the flow level.
+func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool {
+ if parser.flow_level > 0 {
+ parser.flow_level--
+ parser.simple_keys = parser.simple_keys[:len(parser.simple_keys)-1]
+ }
+ return true
+}
+
+// Push the current indentation level to the stack and set the new level
+// the current column is greater than the indentation level. In this case,
+// append or insert the specified token into the token queue.
+func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool {
+ // In the flow context, do nothing.
+ if parser.flow_level > 0 {
+ return true
+ }
+
+ if parser.indent < column {
+ // Push the current indentation level to the stack and set the new
+ // indentation level.
+ parser.indents = append(parser.indents, parser.indent)
+ parser.indent = column
+
+ // Create a token and insert it into the queue.
+ token := yaml_token_t{
+ typ: typ,
+ start_mark: mark,
+ end_mark: mark,
+ }
+ if number > -1 {
+ number -= parser.tokens_parsed
+ }
+ yaml_insert_token(parser, number, &token)
+ }
+ return true
+}
+
+// Pop indentation levels from the indents stack until the current level
+// becomes less or equal to the column. For each indentation level, append
+// the BLOCK-END token.
+func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool {
+ // In the flow context, do nothing.
+ if parser.flow_level > 0 {
+ return true
+ }
+
+ // Loop through the indentation levels in the stack.
+ for parser.indent > column {
+ // Create a token and append it to the queue.
+ token := yaml_token_t{
+ typ: yaml_BLOCK_END_TOKEN,
+ start_mark: parser.mark,
+ end_mark: parser.mark,
+ }
+ yaml_insert_token(parser, -1, &token)
+
+ // Pop the indentation level.
+ parser.indent = parser.indents[len(parser.indents)-1]
+ parser.indents = parser.indents[:len(parser.indents)-1]
+ }
+ return true
+}
+
+// Initialize the scanner and produce the STREAM-START token.
+func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool {
+
+ // Set the initial indentation.
+ parser.indent = -1
+
+ // Initialize the simple key stack.
+ parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{})
+
+ // A simple key is allowed at the beginning of the stream.
+ parser.simple_key_allowed = true
+
+ // We have started.
+ parser.stream_start_produced = true
+
+ // Create the STREAM-START token and append it to the queue.
+ token := yaml_token_t{
+ typ: yaml_STREAM_START_TOKEN,
+ start_mark: parser.mark,
+ end_mark: parser.mark,
+ encoding: parser.encoding,
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the STREAM-END token and shut down the scanner.
+func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {
+
+ // Force new line.
+ if parser.mark.column != 0 {
+ parser.mark.column = 0
+ parser.mark.line++
+ }
+
+ // Reset the indentation level.
+ if !yaml_parser_unroll_indent(parser, -1) {
+ return false
+ }
+
+ // Reset simple keys.
+ if !yaml_parser_remove_simple_key(parser) {
+ return false
+ }
+
+ parser.simple_key_allowed = false
+
+ // Create the STREAM-END token and append it to the queue.
+ token := yaml_token_t{
+ typ: yaml_STREAM_END_TOKEN,
+ start_mark: parser.mark,
+ end_mark: parser.mark,
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token.
+func yaml_parser_fetch_directive(parser *yaml_parser_t) bool {
+ // Reset the indentation level.
+ if !yaml_parser_unroll_indent(parser, -1) {
+ return false
+ }
+
+ // Reset simple keys.
+ if !yaml_parser_remove_simple_key(parser) {
+ return false
+ }
+
+ parser.simple_key_allowed = false
+
+ // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token.
+ token := yaml_token_t{}
+ if !yaml_parser_scan_directive(parser, &token) {
+ return false
+ }
+ // Append the token to the queue.
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the DOCUMENT-START or DOCUMENT-END token.
+func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool {
+ // Reset the indentation level.
+ if !yaml_parser_unroll_indent(parser, -1) {
+ return false
+ }
+
+ // Reset simple keys.
+ if !yaml_parser_remove_simple_key(parser) {
+ return false
+ }
+
+ parser.simple_key_allowed = false
+
+ // Consume the token.
+ start_mark := parser.mark
+
+ skip(parser)
+ skip(parser)
+ skip(parser)
+
+ end_mark := parser.mark
+
+ // Create the DOCUMENT-START or DOCUMENT-END token.
+ token := yaml_token_t{
+ typ: typ,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ }
+ // Append the token to the queue.
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token.
+func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool {
+ // The indicators '[' and '{' may start a simple key.
+ if !yaml_parser_save_simple_key(parser) {
+ return false
+ }
+
+ // Increase the flow level.
+ if !yaml_parser_increase_flow_level(parser) {
+ return false
+ }
+
+ // A simple key may follow the indicators '[' and '{'.
+ parser.simple_key_allowed = true
+
+ // Consume the token.
+ start_mark := parser.mark
+ skip(parser)
+ end_mark := parser.mark
+
+ // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token.
+ token := yaml_token_t{
+ typ: typ,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ }
+ // Append the token to the queue.
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token.
+func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool {
+ // Reset any potential simple key on the current flow level.
+ if !yaml_parser_remove_simple_key(parser) {
+ return false
+ }
+
+ // Decrease the flow level.
+ if !yaml_parser_decrease_flow_level(parser) {
+ return false
+ }
+
+ // No simple keys after the indicators ']' and '}'.
+ parser.simple_key_allowed = false
+
+ // Consume the token.
+
+ start_mark := parser.mark
+ skip(parser)
+ end_mark := parser.mark
+
+ // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token.
+ token := yaml_token_t{
+ typ: typ,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ }
+ // Append the token to the queue.
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the FLOW-ENTRY token.
+func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool {
+ // Reset any potential simple keys on the current flow level.
+ if !yaml_parser_remove_simple_key(parser) {
+ return false
+ }
+
+ // Simple keys are allowed after ','.
+ parser.simple_key_allowed = true
+
+ // Consume the token.
+ start_mark := parser.mark
+ skip(parser)
+ end_mark := parser.mark
+
+ // Create the FLOW-ENTRY token and append it to the queue.
+ token := yaml_token_t{
+ typ: yaml_FLOW_ENTRY_TOKEN,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the BLOCK-ENTRY token.
+func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool {
+ // Check if the scanner is in the block context.
+ if parser.flow_level == 0 {
+ // Check if we are allowed to start a new entry.
+ if !parser.simple_key_allowed {
+ return yaml_parser_set_scanner_error(parser, "", parser.mark,
+ "block sequence entries are not allowed in this context")
+ }
+ // Add the BLOCK-SEQUENCE-START token if needed.
+ if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) {
+ return false
+ }
+ } else {
+ // It is an error for the '-' indicator to occur in the flow context,
+ // but we let the Parser detect and report about it because the Parser
+ // is able to point to the context.
+ }
+
+ // Reset any potential simple keys on the current flow level.
+ if !yaml_parser_remove_simple_key(parser) {
+ return false
+ }
+
+ // Simple keys are allowed after '-'.
+ parser.simple_key_allowed = true
+
+ // Consume the token.
+ start_mark := parser.mark
+ skip(parser)
+ end_mark := parser.mark
+
+ // Create the BLOCK-ENTRY token and append it to the queue.
+ token := yaml_token_t{
+ typ: yaml_BLOCK_ENTRY_TOKEN,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the KEY token.
+func yaml_parser_fetch_key(parser *yaml_parser_t) bool {
+
+ // In the block context, additional checks are required.
+ if parser.flow_level == 0 {
+ // Check if we are allowed to start a new key (not nessesary simple).
+ if !parser.simple_key_allowed {
+ return yaml_parser_set_scanner_error(parser, "", parser.mark,
+ "mapping keys are not allowed in this context")
+ }
+ // Add the BLOCK-MAPPING-START token if needed.
+ if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) {
+ return false
+ }
+ }
+
+ // Reset any potential simple keys on the current flow level.
+ if !yaml_parser_remove_simple_key(parser) {
+ return false
+ }
+
+ // Simple keys are allowed after '?' in the block context.
+ parser.simple_key_allowed = parser.flow_level == 0
+
+ // Consume the token.
+ start_mark := parser.mark
+ skip(parser)
+ end_mark := parser.mark
+
+ // Create the KEY token and append it to the queue.
+ token := yaml_token_t{
+ typ: yaml_KEY_TOKEN,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the VALUE token.
+func yaml_parser_fetch_value(parser *yaml_parser_t) bool {
+
+ simple_key := &parser.simple_keys[len(parser.simple_keys)-1]
+
+ // Have we found a simple key?
+ if simple_key.possible {
+ // Create the KEY token and insert it into the queue.
+ token := yaml_token_t{
+ typ: yaml_KEY_TOKEN,
+ start_mark: simple_key.mark,
+ end_mark: simple_key.mark,
+ }
+ yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token)
+
+ // In the block context, we may need to add the BLOCK-MAPPING-START token.
+ if !yaml_parser_roll_indent(parser, simple_key.mark.column,
+ simple_key.token_number,
+ yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) {
+ return false
+ }
+
+ // Remove the simple key.
+ simple_key.possible = false
+
+ // A simple key cannot follow another simple key.
+ parser.simple_key_allowed = false
+
+ } else {
+ // The ':' indicator follows a complex key.
+
+ // In the block context, extra checks are required.
+ if parser.flow_level == 0 {
+
+ // Check if we are allowed to start a complex value.
+ if !parser.simple_key_allowed {
+ return yaml_parser_set_scanner_error(parser, "", parser.mark,
+ "mapping values are not allowed in this context")
+ }
+
+ // Add the BLOCK-MAPPING-START token if needed.
+ if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) {
+ return false
+ }
+ }
+
+ // Simple keys after ':' are allowed in the block context.
+ parser.simple_key_allowed = parser.flow_level == 0
+ }
+
+ // Consume the token.
+ start_mark := parser.mark
+ skip(parser)
+ end_mark := parser.mark
+
+ // Create the VALUE token and append it to the queue.
+ token := yaml_token_t{
+ typ: yaml_VALUE_TOKEN,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the ALIAS or ANCHOR token.
+func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool {
+ // An anchor or an alias could be a simple key.
+ if !yaml_parser_save_simple_key(parser) {
+ return false
+ }
+
+ // A simple key cannot follow an anchor or an alias.
+ parser.simple_key_allowed = false
+
+ // Create the ALIAS or ANCHOR token and append it to the queue.
+ var token yaml_token_t
+ if !yaml_parser_scan_anchor(parser, &token, typ) {
+ return false
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the TAG token.
+func yaml_parser_fetch_tag(parser *yaml_parser_t) bool {
+ // A tag could be a simple key.
+ if !yaml_parser_save_simple_key(parser) {
+ return false
+ }
+
+ // A simple key cannot follow a tag.
+ parser.simple_key_allowed = false
+
+ // Create the TAG token and append it to the queue.
+ var token yaml_token_t
+ if !yaml_parser_scan_tag(parser, &token) {
+ return false
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens.
+func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool {
+ // Remove any potential simple keys.
+ if !yaml_parser_remove_simple_key(parser) {
+ return false
+ }
+
+ // A simple key may follow a block scalar.
+ parser.simple_key_allowed = true
+
+ // Create the SCALAR token and append it to the queue.
+ var token yaml_token_t
+ if !yaml_parser_scan_block_scalar(parser, &token, literal) {
+ return false
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens.
+func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool {
+ // A plain scalar could be a simple key.
+ if !yaml_parser_save_simple_key(parser) {
+ return false
+ }
+
+ // A simple key cannot follow a flow scalar.
+ parser.simple_key_allowed = false
+
+ // Create the SCALAR token and append it to the queue.
+ var token yaml_token_t
+ if !yaml_parser_scan_flow_scalar(parser, &token, single) {
+ return false
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Produce the SCALAR(...,plain) token.
+func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool {
+ // A plain scalar could be a simple key.
+ if !yaml_parser_save_simple_key(parser) {
+ return false
+ }
+
+ // A simple key cannot follow a flow scalar.
+ parser.simple_key_allowed = false
+
+ // Create the SCALAR token and append it to the queue.
+ var token yaml_token_t
+ if !yaml_parser_scan_plain_scalar(parser, &token) {
+ return false
+ }
+ yaml_insert_token(parser, -1, &token)
+ return true
+}
+
+// Eat whitespaces and comments until the next token is found.
+func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool {
+
+ // Until the next token is not found.
+ for {
+ // Allow the BOM mark to start a line.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) {
+ skip(parser)
+ }
+
+ // Eat whitespaces.
+ // Tabs are allowed:
+ // - in the flow context
+ // - in the block context, but not at the beginning of the line or
+ // after '-', '?', or ':' (complex value).
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
+ for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') {
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Eat a comment until a line break.
+ if parser.buffer[parser.buffer_pos] == '#' {
+ for !is_breakz(parser.buffer, parser.buffer_pos) {
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+ }
+
+ // If it is a line break, eat it.
+ if is_break(parser.buffer, parser.buffer_pos) {
+ if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
+ return false
+ }
+ skip_line(parser)
+
+ // In the block context, a new line may start a simple key.
+ if parser.flow_level == 0 {
+ parser.simple_key_allowed = true
+ }
+ } else {
+ break // We have found a token.
+ }
+ }
+
+ return true
+}
+
+// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token.
+//
+// Scope:
+// %YAML 1.1 # a comment \n
+// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+// %TAG !yaml! tag:yaml.org,2002: \n
+// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+//
+func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool {
+ // Eat '%'.
+ start_mark := parser.mark
+ skip(parser)
+
+ // Scan the directive name.
+ var name []byte
+ if !yaml_parser_scan_directive_name(parser, start_mark, &name) {
+ return false
+ }
+
+ // Is it a YAML directive?
+ if bytes.Equal(name, []byte("YAML")) {
+ // Scan the VERSION directive value.
+ var major, minor int8
+ if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) {
+ return false
+ }
+ end_mark := parser.mark
+
+ // Create a VERSION-DIRECTIVE token.
+ *token = yaml_token_t{
+ typ: yaml_VERSION_DIRECTIVE_TOKEN,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ major: major,
+ minor: minor,
+ }
+
+ // Is it a TAG directive?
+ } else if bytes.Equal(name, []byte("TAG")) {
+ // Scan the TAG directive value.
+ var handle, prefix []byte
+ if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) {
+ return false
+ }
+ end_mark := parser.mark
+
+ // Create a TAG-DIRECTIVE token.
+ *token = yaml_token_t{
+ typ: yaml_TAG_DIRECTIVE_TOKEN,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ value: handle,
+ prefix: prefix,
+ }
+
+ // Unknown directive.
+ } else {
+ yaml_parser_set_scanner_error(parser, "while scanning a directive",
+ start_mark, "found unknown directive name")
+ return false
+ }
+
+ // Eat the rest of the line including any comments.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
+ for is_blank(parser.buffer, parser.buffer_pos) {
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ if parser.buffer[parser.buffer_pos] == '#' {
+ for !is_breakz(parser.buffer, parser.buffer_pos) {
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+ }
+
+ // Check if we are at the end of the line.
+ if !is_breakz(parser.buffer, parser.buffer_pos) {
+ yaml_parser_set_scanner_error(parser, "while scanning a directive",
+ start_mark, "did not find expected comment or line break")
+ return false
+ }
+
+ // Eat a line break.
+ if is_break(parser.buffer, parser.buffer_pos) {
+ if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
+ return false
+ }
+ skip_line(parser)
+ }
+
+ return true
+}
+
+// Scan the directive name.
+//
+// Scope:
+// %YAML 1.1 # a comment \n
+// ^^^^
+// %TAG !yaml! tag:yaml.org,2002: \n
+// ^^^
+//
+func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool {
+ // Consume the directive name.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
+ var s []byte
+ for is_alpha(parser.buffer, parser.buffer_pos) {
+ s = read(parser, s)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Check if the name is empty.
+ if len(s) == 0 {
+ yaml_parser_set_scanner_error(parser, "while scanning a directive",
+ start_mark, "could not find expected directive name")
+ return false
+ }
+
+ // Check for an blank character after the name.
+ if !is_blankz(parser.buffer, parser.buffer_pos) {
+ yaml_parser_set_scanner_error(parser, "while scanning a directive",
+ start_mark, "found unexpected non-alphabetical character")
+ return false
+ }
+ *name = s
+ return true
+}
+
+// Scan the value of VERSION-DIRECTIVE.
+//
+// Scope:
+// %YAML 1.1 # a comment \n
+// ^^^^^^
+func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool {
+ // Eat whitespaces.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ for is_blank(parser.buffer, parser.buffer_pos) {
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Consume the major version number.
+ if !yaml_parser_scan_version_directive_number(parser, start_mark, major) {
+ return false
+ }
+
+ // Eat '.'.
+ if parser.buffer[parser.buffer_pos] != '.' {
+ return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
+ start_mark, "did not find expected digit or '.' character")
+ }
+
+ skip(parser)
+
+ // Consume the minor version number.
+ if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) {
+ return false
+ }
+ return true
+}
+
+const max_number_length = 2
+
+// Scan the version number of VERSION-DIRECTIVE.
+//
+// Scope:
+// %YAML 1.1 # a comment \n
+// ^
+// %YAML 1.1 # a comment \n
+// ^
+func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool {
+
+ // Repeat while the next character is digit.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ var value, length int8
+ for is_digit(parser.buffer, parser.buffer_pos) {
+ // Check if the number is too long.
+ length++
+ if length > max_number_length {
+ return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
+ start_mark, "found extremely long version number")
+ }
+ value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos))
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Check if the number was present.
+ if length == 0 {
+ return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
+ start_mark, "did not find expected version number")
+ }
+ *number = value
+ return true
+}
+
+// Scan the value of a TAG-DIRECTIVE token.
+//
+// Scope:
+// %TAG !yaml! tag:yaml.org,2002: \n
+// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+//
+func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool {
+ var handle_value, prefix_value []byte
+
+ // Eat whitespaces.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
+ for is_blank(parser.buffer, parser.buffer_pos) {
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Scan a handle.
+ if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) {
+ return false
+ }
+
+ // Expect a whitespace.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ if !is_blank(parser.buffer, parser.buffer_pos) {
+ yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive",
+ start_mark, "did not find expected whitespace")
+ return false
+ }
+
+ // Eat whitespaces.
+ for is_blank(parser.buffer, parser.buffer_pos) {
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Scan a prefix.
+ if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) {
+ return false
+ }
+
+ // Expect a whitespace or line break.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ if !is_blankz(parser.buffer, parser.buffer_pos) {
+ yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive",
+ start_mark, "did not find expected whitespace or line break")
+ return false
+ }
+
+ *handle = handle_value
+ *prefix = prefix_value
+ return true
+}
+
+func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool {
+ var s []byte
+
+ // Eat the indicator character.
+ start_mark := parser.mark
+ skip(parser)
+
+ // Consume the value.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
+ for is_alpha(parser.buffer, parser.buffer_pos) {
+ s = read(parser, s)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ end_mark := parser.mark
+
+ /*
+ * Check if length of the anchor is greater than 0 and it is followed by
+ * a whitespace character or one of the indicators:
+ *
+ * '?', ':', ',', ']', '}', '%', '@', '`'.
+ */
+
+ if len(s) == 0 ||
+ !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' ||
+ parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' ||
+ parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' ||
+ parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' ||
+ parser.buffer[parser.buffer_pos] == '`') {
+ context := "while scanning an alias"
+ if typ == yaml_ANCHOR_TOKEN {
+ context = "while scanning an anchor"
+ }
+ yaml_parser_set_scanner_error(parser, context, start_mark,
+ "did not find expected alphabetic or numeric character")
+ return false
+ }
+
+ // Create a token.
+ *token = yaml_token_t{
+ typ: typ,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ value: s,
+ }
+
+ return true
+}
+
+/*
+ * Scan a TAG token.
+ */
+
+func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool {
+ var handle, suffix []byte
+
+ start_mark := parser.mark
+
+ // Check if the tag is in the canonical form.
+ if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
+ return false
+ }
+
+ if parser.buffer[parser.buffer_pos+1] == '<' {
+ // Keep the handle as ''
+
+ // Eat '!<'
+ skip(parser)
+ skip(parser)
+
+ // Consume the tag value.
+ if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) {
+ return false
+ }
+
+ // Check for '>' and eat it.
+ if parser.buffer[parser.buffer_pos] != '>' {
+ yaml_parser_set_scanner_error(parser, "while scanning a tag",
+ start_mark, "did not find the expected '>'")
+ return false
+ }
+
+ skip(parser)
+ } else {
+ // The tag has either the '!suffix' or the '!handle!suffix' form.
+
+ // First, try to scan a handle.
+ if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) {
+ return false
+ }
+
+ // Check if it is, indeed, handle.
+ if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' {
+ // Scan the suffix now.
+ if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) {
+ return false
+ }
+ } else {
+ // It wasn't a handle after all. Scan the rest of the tag.
+ if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) {
+ return false
+ }
+
+ // Set the handle to '!'.
+ handle = []byte{'!'}
+
+ // A special case: the '!' tag. Set the handle to '' and the
+ // suffix to '!'.
+ if len(suffix) == 0 {
+ handle, suffix = suffix, handle
+ }
+ }
+ }
+
+ // Check the character which ends the tag.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ if !is_blankz(parser.buffer, parser.buffer_pos) {
+ yaml_parser_set_scanner_error(parser, "while scanning a tag",
+ start_mark, "did not find expected whitespace or line break")
+ return false
+ }
+
+ end_mark := parser.mark
+
+ // Create a token.
+ *token = yaml_token_t{
+ typ: yaml_TAG_TOKEN,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ value: handle,
+ suffix: suffix,
+ }
+ return true
+}
+
+// Scan a tag handle.
+func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool {
+ // Check the initial '!' character.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ if parser.buffer[parser.buffer_pos] != '!' {
+ yaml_parser_set_scanner_tag_error(parser, directive,
+ start_mark, "did not find expected '!'")
+ return false
+ }
+
+ var s []byte
+
+ // Copy the '!' character.
+ s = read(parser, s)
+
+ // Copy all subsequent alphabetical and numerical characters.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ for is_alpha(parser.buffer, parser.buffer_pos) {
+ s = read(parser, s)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Check if the trailing character is '!' and copy it.
+ if parser.buffer[parser.buffer_pos] == '!' {
+ s = read(parser, s)
+ } else {
+ // It's either the '!' tag or not really a tag handle. If it's a %TAG
+ // directive, it's an error. If it's a tag token, it must be a part of URI.
+ if directive && !(s[0] == '!' && s[1] == 0) {
+ yaml_parser_set_scanner_tag_error(parser, directive,
+ start_mark, "did not find expected '!'")
+ return false
+ }
+ }
+
+ *handle = s
+ return true
+}
+
+// Scan a tag.
+func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool {
+ //size_t length = head ? strlen((char *)head) : 0
+ var s []byte
+
+ // Copy the head if needed.
+ //
+ // Note that we don't copy the leading '!' character.
+ if len(head) > 1 {
+ s = append(s, head[1:]...)
+ }
+
+ // Scan the tag.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
+ // The set of characters that may appear in URI is as follows:
+ //
+ // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&',
+ // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']',
+ // '%'.
+ // [Go] Convert this into more reasonable logic.
+ for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' ||
+ parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' ||
+ parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' ||
+ parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' ||
+ parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' ||
+ parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' ||
+ parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' ||
+ parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' ||
+ parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' ||
+ parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' ||
+ parser.buffer[parser.buffer_pos] == '%' {
+ // Check if it is a URI-escape sequence.
+ if parser.buffer[parser.buffer_pos] == '%' {
+ if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) {
+ return false
+ }
+ } else {
+ s = read(parser, s)
+ }
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Check if the tag is non-empty.
+ if len(s) == 0 {
+ yaml_parser_set_scanner_tag_error(parser, directive,
+ start_mark, "did not find expected tag URI")
+ return false
+ }
+ *uri = s
+ return true
+}
+
+// Decode an URI-escape sequence corresponding to a single UTF-8 character.
+func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool {
+
+ // Decode the required number of characters.
+ w := 1024
+ for w > 0 {
+ // Check for a URI-escaped octet.
+ if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) {
+ return false
+ }
+
+ if !(parser.buffer[parser.buffer_pos] == '%' &&
+ is_hex(parser.buffer, parser.buffer_pos+1) &&
+ is_hex(parser.buffer, parser.buffer_pos+2)) {
+ return yaml_parser_set_scanner_tag_error(parser, directive,
+ start_mark, "did not find URI escaped octet")
+ }
+
+ // Get the octet.
+ octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2))
+
+ // If it is the leading octet, determine the length of the UTF-8 sequence.
+ if w == 1024 {
+ w = width(octet)
+ if w == 0 {
+ return yaml_parser_set_scanner_tag_error(parser, directive,
+ start_mark, "found an incorrect leading UTF-8 octet")
+ }
+ } else {
+ // Check if the trailing octet is correct.
+ if octet&0xC0 != 0x80 {
+ return yaml_parser_set_scanner_tag_error(parser, directive,
+ start_mark, "found an incorrect trailing UTF-8 octet")
+ }
+ }
+
+ // Copy the octet and move the pointers.
+ *s = append(*s, octet)
+ skip(parser)
+ skip(parser)
+ skip(parser)
+ w--
+ }
+ return true
+}
+
+// Scan a block scalar.
+func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool {
+ // Eat the indicator '|' or '>'.
+ start_mark := parser.mark
+ skip(parser)
+
+ // Scan the additional block scalar indicators.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
+ // Check for a chomping indicator.
+ var chomping, increment int
+ if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' {
+ // Set the chomping method and eat the indicator.
+ if parser.buffer[parser.buffer_pos] == '+' {
+ chomping = +1
+ } else {
+ chomping = -1
+ }
+ skip(parser)
+
+ // Check for an indentation indicator.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ if is_digit(parser.buffer, parser.buffer_pos) {
+ // Check that the indentation is greater than 0.
+ if parser.buffer[parser.buffer_pos] == '0' {
+ yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
+ start_mark, "found an indentation indicator equal to 0")
+ return false
+ }
+
+ // Get the indentation level and eat the indicator.
+ increment = as_digit(parser.buffer, parser.buffer_pos)
+ skip(parser)
+ }
+
+ } else if is_digit(parser.buffer, parser.buffer_pos) {
+ // Do the same as above, but in the opposite order.
+
+ if parser.buffer[parser.buffer_pos] == '0' {
+ yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
+ start_mark, "found an indentation indicator equal to 0")
+ return false
+ }
+ increment = as_digit(parser.buffer, parser.buffer_pos)
+ skip(parser)
+
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' {
+ if parser.buffer[parser.buffer_pos] == '+' {
+ chomping = +1
+ } else {
+ chomping = -1
+ }
+ skip(parser)
+ }
+ }
+
+ // Eat whitespaces and comments to the end of the line.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ for is_blank(parser.buffer, parser.buffer_pos) {
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+ if parser.buffer[parser.buffer_pos] == '#' {
+ for !is_breakz(parser.buffer, parser.buffer_pos) {
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+ }
+
+ // Check if we are at the end of the line.
+ if !is_breakz(parser.buffer, parser.buffer_pos) {
+ yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
+ start_mark, "did not find expected comment or line break")
+ return false
+ }
+
+ // Eat a line break.
+ if is_break(parser.buffer, parser.buffer_pos) {
+ if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
+ return false
+ }
+ skip_line(parser)
+ }
+
+ end_mark := parser.mark
+
+ // Set the indentation level if it was specified.
+ var indent int
+ if increment > 0 {
+ if parser.indent >= 0 {
+ indent = parser.indent + increment
+ } else {
+ indent = increment
+ }
+ }
+
+ // Scan the leading line breaks and determine the indentation level if needed.
+ var s, leading_break, trailing_breaks []byte
+ if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) {
+ return false
+ }
+
+ // Scan the block scalar content.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ var leading_blank, trailing_blank bool
+ for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) {
+ // We are at the beginning of a non-empty line.
+
+ // Is it a trailing whitespace?
+ trailing_blank = is_blank(parser.buffer, parser.buffer_pos)
+
+ // Check if we need to fold the leading line break.
+ if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' {
+ // Do we need to join the lines by space?
+ if len(trailing_breaks) == 0 {
+ s = append(s, ' ')
+ }
+ } else {
+ s = append(s, leading_break...)
+ }
+ leading_break = leading_break[:0]
+
+ // Append the remaining line breaks.
+ s = append(s, trailing_breaks...)
+ trailing_breaks = trailing_breaks[:0]
+
+ // Is it a leading whitespace?
+ leading_blank = is_blank(parser.buffer, parser.buffer_pos)
+
+ // Consume the current line.
+ for !is_breakz(parser.buffer, parser.buffer_pos) {
+ s = read(parser, s)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Consume the line break.
+ if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
+ return false
+ }
+
+ leading_break = read_line(parser, leading_break)
+
+ // Eat the following indentation spaces and line breaks.
+ if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) {
+ return false
+ }
+ }
+
+ // Chomp the tail.
+ if chomping != -1 {
+ s = append(s, leading_break...)
+ }
+ if chomping == 1 {
+ s = append(s, trailing_breaks...)
+ }
+
+ // Create a token.
+ *token = yaml_token_t{
+ typ: yaml_SCALAR_TOKEN,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ value: s,
+ style: yaml_LITERAL_SCALAR_STYLE,
+ }
+ if !literal {
+ token.style = yaml_FOLDED_SCALAR_STYLE
+ }
+ return true
+}
+
+// Scan indentation spaces and line breaks for a block scalar. Determine the
+// indentation level if needed.
+func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool {
+ *end_mark = parser.mark
+
+ // Eat the indentation spaces and line breaks.
+ max_indent := 0
+ for {
+ // Eat the indentation spaces.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) {
+ skip(parser)
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+ if parser.mark.column > max_indent {
+ max_indent = parser.mark.column
+ }
+
+ // Check for a tab character messing the indentation.
+ if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) {
+ return yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
+ start_mark, "found a tab character where an indentation space is expected")
+ }
+
+ // Have we found a non-empty line?
+ if !is_break(parser.buffer, parser.buffer_pos) {
+ break
+ }
+
+ // Consume the line break.
+ if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
+ return false
+ }
+ // [Go] Should really be returning breaks instead.
+ *breaks = read_line(parser, *breaks)
+ *end_mark = parser.mark
+ }
+
+ // Determine the indentation level if needed.
+ if *indent == 0 {
+ *indent = max_indent
+ if *indent < parser.indent+1 {
+ *indent = parser.indent + 1
+ }
+ if *indent < 1 {
+ *indent = 1
+ }
+ }
+ return true
+}
+
+// Scan a quoted scalar.
+func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool {
+ // Eat the left quote.
+ start_mark := parser.mark
+ skip(parser)
+
+ // Consume the content of the quoted scalar.
+ var s, leading_break, trailing_breaks, whitespaces []byte
+ for {
+ // Check that there are no document indicators at the beginning of the line.
+ if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) {
+ return false
+ }
+
+ if parser.mark.column == 0 &&
+ ((parser.buffer[parser.buffer_pos+0] == '-' &&
+ parser.buffer[parser.buffer_pos+1] == '-' &&
+ parser.buffer[parser.buffer_pos+2] == '-') ||
+ (parser.buffer[parser.buffer_pos+0] == '.' &&
+ parser.buffer[parser.buffer_pos+1] == '.' &&
+ parser.buffer[parser.buffer_pos+2] == '.')) &&
+ is_blankz(parser.buffer, parser.buffer_pos+3) {
+ yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar",
+ start_mark, "found unexpected document indicator")
+ return false
+ }
+
+ // Check for EOF.
+ if is_z(parser.buffer, parser.buffer_pos) {
+ yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar",
+ start_mark, "found unexpected end of stream")
+ return false
+ }
+
+ // Consume non-blank characters.
+ leading_blanks := false
+ for !is_blankz(parser.buffer, parser.buffer_pos) {
+ if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' {
+ // Is is an escaped single quote.
+ s = append(s, '\'')
+ skip(parser)
+ skip(parser)
+
+ } else if single && parser.buffer[parser.buffer_pos] == '\'' {
+ // It is a right single quote.
+ break
+ } else if !single && parser.buffer[parser.buffer_pos] == '"' {
+ // It is a right double quote.
+ break
+
+ } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) {
+ // It is an escaped line break.
+ if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) {
+ return false
+ }
+ skip(parser)
+ skip_line(parser)
+ leading_blanks = true
+ break
+
+ } else if !single && parser.buffer[parser.buffer_pos] == '\\' {
+ // It is an escape sequence.
+ code_length := 0
+
+ // Check the escape character.
+ switch parser.buffer[parser.buffer_pos+1] {
+ case '0':
+ s = append(s, 0)
+ case 'a':
+ s = append(s, '\x07')
+ case 'b':
+ s = append(s, '\x08')
+ case 't', '\t':
+ s = append(s, '\x09')
+ case 'n':
+ s = append(s, '\x0A')
+ case 'v':
+ s = append(s, '\x0B')
+ case 'f':
+ s = append(s, '\x0C')
+ case 'r':
+ s = append(s, '\x0D')
+ case 'e':
+ s = append(s, '\x1B')
+ case ' ':
+ s = append(s, '\x20')
+ case '"':
+ s = append(s, '"')
+ case '\'':
+ s = append(s, '\'')
+ case '\\':
+ s = append(s, '\\')
+ case 'N': // NEL (#x85)
+ s = append(s, '\xC2')
+ s = append(s, '\x85')
+ case '_': // #xA0
+ s = append(s, '\xC2')
+ s = append(s, '\xA0')
+ case 'L': // LS (#x2028)
+ s = append(s, '\xE2')
+ s = append(s, '\x80')
+ s = append(s, '\xA8')
+ case 'P': // PS (#x2029)
+ s = append(s, '\xE2')
+ s = append(s, '\x80')
+ s = append(s, '\xA9')
+ case 'x':
+ code_length = 2
+ case 'u':
+ code_length = 4
+ case 'U':
+ code_length = 8
+ default:
+ yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
+ start_mark, "found unknown escape character")
+ return false
+ }
+
+ skip(parser)
+ skip(parser)
+
+ // Consume an arbitrary escape code.
+ if code_length > 0 {
+ var value int
+
+ // Scan the character value.
+ if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) {
+ return false
+ }
+ for k := 0; k < code_length; k++ {
+ if !is_hex(parser.buffer, parser.buffer_pos+k) {
+ yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
+ start_mark, "did not find expected hexdecimal number")
+ return false
+ }
+ value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k)
+ }
+
+ // Check the value and write the character.
+ if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF {
+ yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
+ start_mark, "found invalid Unicode character escape code")
+ return false
+ }
+ if value <= 0x7F {
+ s = append(s, byte(value))
+ } else if value <= 0x7FF {
+ s = append(s, byte(0xC0+(value>>6)))
+ s = append(s, byte(0x80+(value&0x3F)))
+ } else if value <= 0xFFFF {
+ s = append(s, byte(0xE0+(value>>12)))
+ s = append(s, byte(0x80+((value>>6)&0x3F)))
+ s = append(s, byte(0x80+(value&0x3F)))
+ } else {
+ s = append(s, byte(0xF0+(value>>18)))
+ s = append(s, byte(0x80+((value>>12)&0x3F)))
+ s = append(s, byte(0x80+((value>>6)&0x3F)))
+ s = append(s, byte(0x80+(value&0x3F)))
+ }
+
+ // Advance the pointer.
+ for k := 0; k < code_length; k++ {
+ skip(parser)
+ }
+ }
+ } else {
+ // It is a non-escaped non-blank character.
+ s = read(parser, s)
+ }
+ if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
+ return false
+ }
+ }
+
+ // Check if we are at the end of the scalar.
+ if single {
+ if parser.buffer[parser.buffer_pos] == '\'' {
+ break
+ }
+ } else {
+ if parser.buffer[parser.buffer_pos] == '"' {
+ break
+ }
+ }
+
+ // Consume blank characters.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
+ for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) {
+ if is_blank(parser.buffer, parser.buffer_pos) {
+ // Consume a space or a tab character.
+ if !leading_blanks {
+ whitespaces = read(parser, whitespaces)
+ } else {
+ skip(parser)
+ }
+ } else {
+ if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
+ return false
+ }
+
+ // Check if it is a first line break.
+ if !leading_blanks {
+ whitespaces = whitespaces[:0]
+ leading_break = read_line(parser, leading_break)
+ leading_blanks = true
+ } else {
+ trailing_breaks = read_line(parser, trailing_breaks)
+ }
+ }
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Join the whitespaces or fold line breaks.
+ if leading_blanks {
+ // Do we need to fold line breaks?
+ if len(leading_break) > 0 && leading_break[0] == '\n' {
+ if len(trailing_breaks) == 0 {
+ s = append(s, ' ')
+ } else {
+ s = append(s, trailing_breaks...)
+ }
+ } else {
+ s = append(s, leading_break...)
+ s = append(s, trailing_breaks...)
+ }
+ trailing_breaks = trailing_breaks[:0]
+ leading_break = leading_break[:0]
+ } else {
+ s = append(s, whitespaces...)
+ whitespaces = whitespaces[:0]
+ }
+ }
+
+ // Eat the right quote.
+ skip(parser)
+ end_mark := parser.mark
+
+ // Create a token.
+ *token = yaml_token_t{
+ typ: yaml_SCALAR_TOKEN,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ value: s,
+ style: yaml_SINGLE_QUOTED_SCALAR_STYLE,
+ }
+ if !single {
+ token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
+ }
+ return true
+}
+
+// Scan a plain scalar.
+func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool {
+
+ var s, leading_break, trailing_breaks, whitespaces []byte
+ var leading_blanks bool
+ var indent = parser.indent + 1
+
+ start_mark := parser.mark
+ end_mark := parser.mark
+
+ // Consume the content of the plain scalar.
+ for {
+ // Check for a document indicator.
+ if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) {
+ return false
+ }
+ if parser.mark.column == 0 &&
+ ((parser.buffer[parser.buffer_pos+0] == '-' &&
+ parser.buffer[parser.buffer_pos+1] == '-' &&
+ parser.buffer[parser.buffer_pos+2] == '-') ||
+ (parser.buffer[parser.buffer_pos+0] == '.' &&
+ parser.buffer[parser.buffer_pos+1] == '.' &&
+ parser.buffer[parser.buffer_pos+2] == '.')) &&
+ is_blankz(parser.buffer, parser.buffer_pos+3) {
+ break
+ }
+
+ // Check for a comment.
+ if parser.buffer[parser.buffer_pos] == '#' {
+ break
+ }
+
+ // Consume non-blank characters.
+ for !is_blankz(parser.buffer, parser.buffer_pos) {
+
+ // Check for 'x:x' in the flow context. TODO: Fix the test "spec-08-13".
+ if parser.flow_level > 0 &&
+ parser.buffer[parser.buffer_pos] == ':' &&
+ !is_blankz(parser.buffer, parser.buffer_pos+1) {
+ yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
+ start_mark, "found unexpected ':'")
+ return false
+ }
+
+ // Check for indicators that may end a plain scalar.
+ if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) ||
+ (parser.flow_level > 0 &&
+ (parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == ':' ||
+ parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' ||
+ parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' ||
+ parser.buffer[parser.buffer_pos] == '}')) {
+ break
+ }
+
+ // Check if we need to join whitespaces and breaks.
+ if leading_blanks || len(whitespaces) > 0 {
+ if leading_blanks {
+ // Do we need to fold line breaks?
+ if leading_break[0] == '\n' {
+ if len(trailing_breaks) == 0 {
+ s = append(s, ' ')
+ } else {
+ s = append(s, trailing_breaks...)
+ }
+ } else {
+ s = append(s, leading_break...)
+ s = append(s, trailing_breaks...)
+ }
+ trailing_breaks = trailing_breaks[:0]
+ leading_break = leading_break[:0]
+ leading_blanks = false
+ } else {
+ s = append(s, whitespaces...)
+ whitespaces = whitespaces[:0]
+ }
+ }
+
+ // Copy the character.
+ s = read(parser, s)
+
+ end_mark = parser.mark
+ if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
+ return false
+ }
+ }
+
+ // Is it the end?
+ if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) {
+ break
+ }
+
+ // Consume blank characters.
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+
+ for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) {
+ if is_blank(parser.buffer, parser.buffer_pos) {
+
+ // Check for tab character that abuse indentation.
+ if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) {
+ yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
+ start_mark, "found a tab character that violate indentation")
+ return false
+ }
+
+ // Consume a space or a tab character.
+ if !leading_blanks {
+ whitespaces = read(parser, whitespaces)
+ } else {
+ skip(parser)
+ }
+ } else {
+ if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
+ return false
+ }
+
+ // Check if it is a first line break.
+ if !leading_blanks {
+ whitespaces = whitespaces[:0]
+ leading_break = read_line(parser, leading_break)
+ leading_blanks = true
+ } else {
+ trailing_breaks = read_line(parser, trailing_breaks)
+ }
+ }
+ if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
+ return false
+ }
+ }
+
+ // Check indentation level.
+ if parser.flow_level == 0 && parser.mark.column < indent {
+ break
+ }
+ }
+
+ // Create a token.
+ *token = yaml_token_t{
+ typ: yaml_SCALAR_TOKEN,
+ start_mark: start_mark,
+ end_mark: end_mark,
+ value: s,
+ style: yaml_PLAIN_SCALAR_STYLE,
+ }
+
+ // Note that we change the 'simple_key_allowed' flag.
+ if leading_blanks {
+ parser.simple_key_allowed = true
+ }
+ return true
+}
diff --git a/vendor/gopkg.in/yaml.v2/sorter.go b/vendor/gopkg.in/yaml.v2/sorter.go
new file mode 100644
index 0000000..5958822
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/sorter.go
@@ -0,0 +1,104 @@
+package yaml
+
+import (
+ "reflect"
+ "unicode"
+)
+
+type keyList []reflect.Value
+
+func (l keyList) Len() int { return len(l) }
+func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
+func (l keyList) Less(i, j int) bool {
+ a := l[i]
+ b := l[j]
+ ak := a.Kind()
+ bk := b.Kind()
+ for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() {
+ a = a.Elem()
+ ak = a.Kind()
+ }
+ for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() {
+ b = b.Elem()
+ bk = b.Kind()
+ }
+ af, aok := keyFloat(a)
+ bf, bok := keyFloat(b)
+ if aok && bok {
+ if af != bf {
+ return af < bf
+ }
+ if ak != bk {
+ return ak < bk
+ }
+ return numLess(a, b)
+ }
+ if ak != reflect.String || bk != reflect.String {
+ return ak < bk
+ }
+ ar, br := []rune(a.String()), []rune(b.String())
+ for i := 0; i < len(ar) && i < len(br); i++ {
+ if ar[i] == br[i] {
+ continue
+ }
+ al := unicode.IsLetter(ar[i])
+ bl := unicode.IsLetter(br[i])
+ if al && bl {
+ return ar[i] < br[i]
+ }
+ if al || bl {
+ return bl
+ }
+ var ai, bi int
+ var an, bn int64
+ for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ {
+ an = an*10 + int64(ar[ai]-'0')
+ }
+ for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ {
+ bn = bn*10 + int64(br[bi]-'0')
+ }
+ if an != bn {
+ return an < bn
+ }
+ if ai != bi {
+ return ai < bi
+ }
+ return ar[i] < br[i]
+ }
+ return len(ar) < len(br)
+}
+
+// keyFloat returns a float value for v if it is a number/bool
+// and whether it is a number/bool or not.
+func keyFloat(v reflect.Value) (f float64, ok bool) {
+ switch v.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ return float64(v.Int()), true
+ case reflect.Float32, reflect.Float64:
+ return v.Float(), true
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ return float64(v.Uint()), true
+ case reflect.Bool:
+ if v.Bool() {
+ return 1, true
+ }
+ return 0, true
+ }
+ return 0, false
+}
+
+// numLess returns whether a < b.
+// a and b must necessarily have the same kind.
+func numLess(a, b reflect.Value) bool {
+ switch a.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ return a.Int() < b.Int()
+ case reflect.Float32, reflect.Float64:
+ return a.Float() < b.Float()
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ return a.Uint() < b.Uint()
+ case reflect.Bool:
+ return !a.Bool() && b.Bool()
+ }
+ panic("not a number")
+}
diff --git a/vendor/gopkg.in/yaml.v2/writerc.go b/vendor/gopkg.in/yaml.v2/writerc.go
new file mode 100644
index 0000000..190362f
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/writerc.go
@@ -0,0 +1,89 @@
+package yaml
+
+// Set the writer error and return false.
+func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool {
+ emitter.error = yaml_WRITER_ERROR
+ emitter.problem = problem
+ return false
+}
+
+// Flush the output buffer.
+func yaml_emitter_flush(emitter *yaml_emitter_t) bool {
+ if emitter.write_handler == nil {
+ panic("write handler not set")
+ }
+
+ // Check if the buffer is empty.
+ if emitter.buffer_pos == 0 {
+ return true
+ }
+
+ // If the output encoding is UTF-8, we don't need to recode the buffer.
+ if emitter.encoding == yaml_UTF8_ENCODING {
+ if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil {
+ return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
+ }
+ emitter.buffer_pos = 0
+ return true
+ }
+
+ // Recode the buffer into the raw buffer.
+ var low, high int
+ if emitter.encoding == yaml_UTF16LE_ENCODING {
+ low, high = 0, 1
+ } else {
+ high, low = 1, 0
+ }
+
+ pos := 0
+ for pos < emitter.buffer_pos {
+ // See the "reader.c" code for more details on UTF-8 encoding. Note
+ // that we assume that the buffer contains a valid UTF-8 sequence.
+
+ // Read the next UTF-8 character.
+ octet := emitter.buffer[pos]
+
+ var w int
+ var value rune
+ switch {
+ case octet&0x80 == 0x00:
+ w, value = 1, rune(octet&0x7F)
+ case octet&0xE0 == 0xC0:
+ w, value = 2, rune(octet&0x1F)
+ case octet&0xF0 == 0xE0:
+ w, value = 3, rune(octet&0x0F)
+ case octet&0xF8 == 0xF0:
+ w, value = 4, rune(octet&0x07)
+ }
+ for k := 1; k < w; k++ {
+ octet = emitter.buffer[pos+k]
+ value = (value << 6) + (rune(octet) & 0x3F)
+ }
+ pos += w
+
+ // Write the character.
+ if value < 0x10000 {
+ var b [2]byte
+ b[high] = byte(value >> 8)
+ b[low] = byte(value & 0xFF)
+ emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1])
+ } else {
+ // Write the character using a surrogate pair (check "reader.c").
+ var b [4]byte
+ value -= 0x10000
+ b[high] = byte(0xD8 + (value >> 18))
+ b[low] = byte((value >> 10) & 0xFF)
+ b[high+2] = byte(0xDC + ((value >> 8) & 0xFF))
+ b[low+2] = byte(value & 0xFF)
+ emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1], b[2], b[3])
+ }
+ }
+
+ // Write the raw buffer.
+ if err := emitter.write_handler(emitter, emitter.raw_buffer); err != nil {
+ return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
+ }
+ emitter.buffer_pos = 0
+ emitter.raw_buffer = emitter.raw_buffer[:0]
+ return true
+}
diff --git a/vendor/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go
new file mode 100644
index 0000000..36d6b88
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/yaml.go
@@ -0,0 +1,346 @@
+// Package yaml implements YAML support for the Go language.
+//
+// Source code and other details for the project are available at GitHub:
+//
+// https://github.com/go-yaml/yaml
+//
+package yaml
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "strings"
+ "sync"
+)
+
+// MapSlice encodes and decodes as a YAML map.
+// The order of keys is preserved when encoding and decoding.
+type MapSlice []MapItem
+
+// MapItem is an item in a MapSlice.
+type MapItem struct {
+ Key, Value interface{}
+}
+
+// The Unmarshaler interface may be implemented by types to customize their
+// behavior when being unmarshaled from a YAML document. The UnmarshalYAML
+// method receives a function that may be called to unmarshal the original
+// YAML value into a field or variable. It is safe to call the unmarshal
+// function parameter more than once if necessary.
+type Unmarshaler interface {
+ UnmarshalYAML(unmarshal func(interface{}) error) error
+}
+
+// The Marshaler interface may be implemented by types to customize their
+// behavior when being marshaled into a YAML document. The returned value
+// is marshaled in place of the original value implementing Marshaler.
+//
+// If an error is returned by MarshalYAML, the marshaling procedure stops
+// and returns with the provided error.
+type Marshaler interface {
+ MarshalYAML() (interface{}, error)
+}
+
+// Unmarshal decodes the first document found within the in byte slice
+// and assigns decoded values into the out value.
+//
+// Maps and pointers (to a struct, string, int, etc) are accepted as out
+// values. If an internal pointer within a struct is not initialized,
+// the yaml package will initialize it if necessary for unmarshalling
+// the provided data. The out parameter must not be nil.
+//
+// The type of the decoded values should be compatible with the respective
+// values in out. If one or more values cannot be decoded due to a type
+// mismatches, decoding continues partially until the end of the YAML
+// content, and a *yaml.TypeError is returned with details for all
+// missed values.
+//
+// Struct fields are only unmarshalled if they are exported (have an
+// upper case first letter), and are unmarshalled using the field name
+// lowercased as the default key. Custom keys may be defined via the
+// "yaml" name in the field tag: the content preceding the first comma
+// is used as the key, and the following comma-separated options are
+// used to tweak the marshalling process (see Marshal).
+// Conflicting names result in a runtime error.
+//
+// For example:
+//
+// type T struct {
+// F int `yaml:"a,omitempty"`
+// B int
+// }
+// var t T
+// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t)
+//
+// See the documentation of Marshal for the format of tags and a list of
+// supported tag options.
+//
+func Unmarshal(in []byte, out interface{}) (err error) {
+ defer handleErr(&err)
+ d := newDecoder()
+ p := newParser(in)
+ defer p.destroy()
+ node := p.parse()
+ if node != nil {
+ v := reflect.ValueOf(out)
+ if v.Kind() == reflect.Ptr && !v.IsNil() {
+ v = v.Elem()
+ }
+ d.unmarshal(node, v)
+ }
+ if len(d.terrors) > 0 {
+ return &TypeError{d.terrors}
+ }
+ return nil
+}
+
+// Marshal serializes the value provided into a YAML document. The structure
+// of the generated document will reflect the structure of the value itself.
+// Maps and pointers (to struct, string, int, etc) are accepted as the in value.
+//
+// Struct fields are only unmarshalled if they are exported (have an upper case
+// first letter), and are unmarshalled using the field name lowercased as the
+// default key. Custom keys may be defined via the "yaml" name in the field
+// tag: the content preceding the first comma is used as the key, and the
+// following comma-separated options are used to tweak the marshalling process.
+// Conflicting names result in a runtime error.
+//
+// The field tag format accepted is:
+//
+// `(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
+//
+// 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.
+// Does not apply to zero valued structs.
+//
+// flow Marshal using a flow style (useful for structs,
+// sequences and maps).
+//
+// 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 yaml keys of other struct fields.
+//
+// In addition, if the key is "-", the field is ignored.
+//
+// For example:
+//
+// type T struct {
+// F int "a,omitempty"
+// B int
+// }
+// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
+// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n"
+//
+func Marshal(in interface{}) (out []byte, err error) {
+ defer handleErr(&err)
+ e := newEncoder()
+ defer e.destroy()
+ e.marshal("", reflect.ValueOf(in))
+ e.finish()
+ out = e.out
+ return
+}
+
+func handleErr(err *error) {
+ if v := recover(); v != nil {
+ if e, ok := v.(yamlError); ok {
+ *err = e.err
+ } else {
+ panic(v)
+ }
+ }
+}
+
+type yamlError struct {
+ err error
+}
+
+func fail(err error) {
+ panic(yamlError{err})
+}
+
+func failf(format string, args ...interface{}) {
+ panic(yamlError{fmt.Errorf("yaml: "+format, args...)})
+}
+
+// A TypeError is returned by Unmarshal when one or more fields in
+// the YAML document cannot be properly decoded into the requested
+// types. When this error is returned, the value is still
+// unmarshaled partially.
+type TypeError struct {
+ Errors []string
+}
+
+func (e *TypeError) Error() string {
+ return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n "))
+}
+
+// --------------------------------------------------------------------------
+// Maintain a mapping of keys to structure field indexes
+
+// The code in this section was copied from mgo/bson.
+
+// structInfo holds details for the serialization of fields of
+// a given struct.
+type structInfo struct {
+ FieldsMap map[string]fieldInfo
+ FieldsList []fieldInfo
+
+ // InlineMap is the number of the field in the struct that
+ // contains an ,inline map, or -1 if there's none.
+ InlineMap int
+}
+
+type fieldInfo struct {
+ Key string
+ Num int
+ OmitEmpty bool
+ Flow bool
+
+ // Inline holds the field index if the field is part of an inlined struct.
+ Inline []int
+}
+
+var structMap = make(map[reflect.Type]*structInfo)
+var fieldMapMutex sync.RWMutex
+
+func getStructInfo(st reflect.Type) (*structInfo, error) {
+ fieldMapMutex.RLock()
+ sinfo, found := structMap[st]
+ fieldMapMutex.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("yaml")
+ 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 "flow":
+ info.Flow = true
+ case "inline":
+ inline = true
+ default:
+ return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st))
+ }
+ }
+ 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:
+ //return nil, errors.New("Option ,inline needs a struct value or map field")
+ return nil, errors.New("Option ,inline needs a struct value 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}
+
+ fieldMapMutex.Lock()
+ structMap[st] = sinfo
+ fieldMapMutex.Unlock()
+ return sinfo, nil
+}
+
+func isZero(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.String:
+ return len(v.String()) == 0
+ case reflect.Interface, reflect.Ptr:
+ 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.Float32, reflect.Float64:
+ return v.Float() == 0
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ return v.Uint() == 0
+ case reflect.Bool:
+ return !v.Bool()
+ case reflect.Struct:
+ vt := v.Type()
+ for i := v.NumField() - 1; i >= 0; i-- {
+ if vt.Field(i).PkgPath != "" {
+ continue // Private field
+ }
+ if !isZero(v.Field(i)) {
+ return false
+ }
+ }
+ return true
+ }
+ return false
+}
diff --git a/vendor/gopkg.in/yaml.v2/yamlh.go b/vendor/gopkg.in/yaml.v2/yamlh.go
new file mode 100644
index 0000000..d60a6b6
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/yamlh.go
@@ -0,0 +1,716 @@
+package yaml
+
+import (
+ "io"
+)
+
+// The version directive data.
+type yaml_version_directive_t struct {
+ major int8 // The major version number.
+ minor int8 // The minor version number.
+}
+
+// The tag directive data.
+type yaml_tag_directive_t struct {
+ handle []byte // The tag handle.
+ prefix []byte // The tag prefix.
+}
+
+type yaml_encoding_t int
+
+// The stream encoding.
+const (
+ // Let the parser choose the encoding.
+ yaml_ANY_ENCODING yaml_encoding_t = iota
+
+ yaml_UTF8_ENCODING // The default UTF-8 encoding.
+ yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM.
+ yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM.
+)
+
+type yaml_break_t int
+
+// Line break types.
+const (
+ // Let the parser choose the break type.
+ yaml_ANY_BREAK yaml_break_t = iota
+
+ yaml_CR_BREAK // Use CR for line breaks (Mac style).
+ yaml_LN_BREAK // Use LN for line breaks (Unix style).
+ yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style).
+)
+
+type yaml_error_type_t int
+
+// Many bad things could happen with the parser and emitter.
+const (
+ // No error is produced.
+ yaml_NO_ERROR yaml_error_type_t = iota
+
+ yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory.
+ yaml_READER_ERROR // Cannot read or decode the input stream.
+ yaml_SCANNER_ERROR // Cannot scan the input stream.
+ yaml_PARSER_ERROR // Cannot parse the input stream.
+ yaml_COMPOSER_ERROR // Cannot compose a YAML document.
+ yaml_WRITER_ERROR // Cannot write to the output stream.
+ yaml_EMITTER_ERROR // Cannot emit a YAML stream.
+)
+
+// The pointer position.
+type yaml_mark_t struct {
+ index int // The position index.
+ line int // The position line.
+ column int // The position column.
+}
+
+// Node Styles
+
+type yaml_style_t int8
+
+type yaml_scalar_style_t yaml_style_t
+
+// Scalar styles.
+const (
+ // Let the emitter choose the style.
+ yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota
+
+ yaml_PLAIN_SCALAR_STYLE // The plain scalar style.
+ yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style.
+ yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style.
+ yaml_LITERAL_SCALAR_STYLE // The literal scalar style.
+ yaml_FOLDED_SCALAR_STYLE // The folded scalar style.
+)
+
+type yaml_sequence_style_t yaml_style_t
+
+// Sequence styles.
+const (
+ // Let the emitter choose the style.
+ yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota
+
+ yaml_BLOCK_SEQUENCE_STYLE // The block sequence style.
+ yaml_FLOW_SEQUENCE_STYLE // The flow sequence style.
+)
+
+type yaml_mapping_style_t yaml_style_t
+
+// Mapping styles.
+const (
+ // Let the emitter choose the style.
+ yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota
+
+ yaml_BLOCK_MAPPING_STYLE // The block mapping style.
+ yaml_FLOW_MAPPING_STYLE // The flow mapping style.
+)
+
+// Tokens
+
+type yaml_token_type_t int
+
+// Token types.
+const (
+ // An empty token.
+ yaml_NO_TOKEN yaml_token_type_t = iota
+
+ yaml_STREAM_START_TOKEN // A STREAM-START token.
+ yaml_STREAM_END_TOKEN // A STREAM-END token.
+
+ yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token.
+ yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token.
+ yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token.
+ yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token.
+
+ yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token.
+ yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token.
+ yaml_BLOCK_END_TOKEN // A BLOCK-END token.
+
+ yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token.
+ yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token.
+ yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token.
+ yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token.
+
+ yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token.
+ yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token.
+ yaml_KEY_TOKEN // A KEY token.
+ yaml_VALUE_TOKEN // A VALUE token.
+
+ yaml_ALIAS_TOKEN // An ALIAS token.
+ yaml_ANCHOR_TOKEN // An ANCHOR token.
+ yaml_TAG_TOKEN // A TAG token.
+ yaml_SCALAR_TOKEN // A SCALAR token.
+)
+
+func (tt yaml_token_type_t) String() string {
+ switch tt {
+ case yaml_NO_TOKEN:
+ return "yaml_NO_TOKEN"
+ case yaml_STREAM_START_TOKEN:
+ return "yaml_STREAM_START_TOKEN"
+ case yaml_STREAM_END_TOKEN:
+ return "yaml_STREAM_END_TOKEN"
+ case yaml_VERSION_DIRECTIVE_TOKEN:
+ return "yaml_VERSION_DIRECTIVE_TOKEN"
+ case yaml_TAG_DIRECTIVE_TOKEN:
+ return "yaml_TAG_DIRECTIVE_TOKEN"
+ case yaml_DOCUMENT_START_TOKEN:
+ return "yaml_DOCUMENT_START_TOKEN"
+ case yaml_DOCUMENT_END_TOKEN:
+ return "yaml_DOCUMENT_END_TOKEN"
+ case yaml_BLOCK_SEQUENCE_START_TOKEN:
+ return "yaml_BLOCK_SEQUENCE_START_TOKEN"
+ case yaml_BLOCK_MAPPING_START_TOKEN:
+ return "yaml_BLOCK_MAPPING_START_TOKEN"
+ case yaml_BLOCK_END_TOKEN:
+ return "yaml_BLOCK_END_TOKEN"
+ case yaml_FLOW_SEQUENCE_START_TOKEN:
+ return "yaml_FLOW_SEQUENCE_START_TOKEN"
+ case yaml_FLOW_SEQUENCE_END_TOKEN:
+ return "yaml_FLOW_SEQUENCE_END_TOKEN"
+ case yaml_FLOW_MAPPING_START_TOKEN:
+ return "yaml_FLOW_MAPPING_START_TOKEN"
+ case yaml_FLOW_MAPPING_END_TOKEN:
+ return "yaml_FLOW_MAPPING_END_TOKEN"
+ case yaml_BLOCK_ENTRY_TOKEN:
+ return "yaml_BLOCK_ENTRY_TOKEN"
+ case yaml_FLOW_ENTRY_TOKEN:
+ return "yaml_FLOW_ENTRY_TOKEN"
+ case yaml_KEY_TOKEN:
+ return "yaml_KEY_TOKEN"
+ case yaml_VALUE_TOKEN:
+ return "yaml_VALUE_TOKEN"
+ case yaml_ALIAS_TOKEN:
+ return "yaml_ALIAS_TOKEN"
+ case yaml_ANCHOR_TOKEN:
+ return "yaml_ANCHOR_TOKEN"
+ case yaml_TAG_TOKEN:
+ return "yaml_TAG_TOKEN"
+ case yaml_SCALAR_TOKEN:
+ return "yaml_SCALAR_TOKEN"
+ }
+ return "<unknown token>"
+}
+
+// The token structure.
+type yaml_token_t struct {
+ // The token type.
+ typ yaml_token_type_t
+
+ // The start/end of the token.
+ start_mark, end_mark yaml_mark_t
+
+ // The stream encoding (for yaml_STREAM_START_TOKEN).
+ encoding yaml_encoding_t
+
+ // The alias/anchor/scalar value or tag/tag directive handle
+ // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN).
+ value []byte
+
+ // The tag suffix (for yaml_TAG_TOKEN).
+ suffix []byte
+
+ // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN).
+ prefix []byte
+
+ // The scalar style (for yaml_SCALAR_TOKEN).
+ style yaml_scalar_style_t
+
+ // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN).
+ major, minor int8
+}
+
+// Events
+
+type yaml_event_type_t int8
+
+// Event types.
+const (
+ // An empty event.
+ yaml_NO_EVENT yaml_event_type_t = iota
+
+ yaml_STREAM_START_EVENT // A STREAM-START event.
+ yaml_STREAM_END_EVENT // A STREAM-END event.
+ yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event.
+ yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event.
+ yaml_ALIAS_EVENT // An ALIAS event.
+ yaml_SCALAR_EVENT // A SCALAR event.
+ yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event.
+ yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event.
+ yaml_MAPPING_START_EVENT // A MAPPING-START event.
+ yaml_MAPPING_END_EVENT // A MAPPING-END event.
+)
+
+// The event structure.
+type yaml_event_t struct {
+
+ // The event type.
+ typ yaml_event_type_t
+
+ // The start and end of the event.
+ start_mark, end_mark yaml_mark_t
+
+ // The document encoding (for yaml_STREAM_START_EVENT).
+ encoding yaml_encoding_t
+
+ // The version directive (for yaml_DOCUMENT_START_EVENT).
+ version_directive *yaml_version_directive_t
+
+ // The list of tag directives (for yaml_DOCUMENT_START_EVENT).
+ tag_directives []yaml_tag_directive_t
+
+ // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT).
+ anchor []byte
+
+ // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT).
+ tag []byte
+
+ // The scalar value (for yaml_SCALAR_EVENT).
+ value []byte
+
+ // Is the document start/end indicator implicit, or the tag optional?
+ // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT).
+ implicit bool
+
+ // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT).
+ quoted_implicit bool
+
+ // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT).
+ style yaml_style_t
+}
+
+func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) }
+func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) }
+func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) }
+
+// Nodes
+
+const (
+ yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null.
+ yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false.
+ yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values.
+ yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values.
+ yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values.
+ yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values.
+
+ yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences.
+ yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping.
+
+ // Not in original libyaml.
+ yaml_BINARY_TAG = "tag:yaml.org,2002:binary"
+ yaml_MERGE_TAG = "tag:yaml.org,2002:merge"
+
+ yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str.
+ yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq.
+ yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map.
+)
+
+type yaml_node_type_t int
+
+// Node types.
+const (
+ // An empty node.
+ yaml_NO_NODE yaml_node_type_t = iota
+
+ yaml_SCALAR_NODE // A scalar node.
+ yaml_SEQUENCE_NODE // A sequence node.
+ yaml_MAPPING_NODE // A mapping node.
+)
+
+// An element of a sequence node.
+type yaml_node_item_t int
+
+// An element of a mapping node.
+type yaml_node_pair_t struct {
+ key int // The key of the element.
+ value int // The value of the element.
+}
+
+// The node structure.
+type yaml_node_t struct {
+ typ yaml_node_type_t // The node type.
+ tag []byte // The node tag.
+
+ // The node data.
+
+ // The scalar parameters (for yaml_SCALAR_NODE).
+ scalar struct {
+ value []byte // The scalar value.
+ length int // The length of the scalar value.
+ style yaml_scalar_style_t // The scalar style.
+ }
+
+ // The sequence parameters (for YAML_SEQUENCE_NODE).
+ sequence struct {
+ items_data []yaml_node_item_t // The stack of sequence items.
+ style yaml_sequence_style_t // The sequence style.
+ }
+
+ // The mapping parameters (for yaml_MAPPING_NODE).
+ mapping struct {
+ pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value).
+ pairs_start *yaml_node_pair_t // The beginning of the stack.
+ pairs_end *yaml_node_pair_t // The end of the stack.
+ pairs_top *yaml_node_pair_t // The top of the stack.
+ style yaml_mapping_style_t // The mapping style.
+ }
+
+ start_mark yaml_mark_t // The beginning of the node.
+ end_mark yaml_mark_t // The end of the node.
+
+}
+
+// The document structure.
+type yaml_document_t struct {
+
+ // The document nodes.
+ nodes []yaml_node_t
+
+ // The version directive.
+ version_directive *yaml_version_directive_t
+
+ // The list of tag directives.
+ tag_directives_data []yaml_tag_directive_t
+ tag_directives_start int // The beginning of the tag directives list.
+ tag_directives_end int // The end of the tag directives list.
+
+ start_implicit int // Is the document start indicator implicit?
+ end_implicit int // Is the document end indicator implicit?
+
+ // The start/end of the document.
+ start_mark, end_mark yaml_mark_t
+}
+
+// The prototype of a read handler.
+//
+// The read handler is called when the parser needs to read more bytes from the
+// source. The handler should write not more than size bytes to the buffer.
+// The number of written bytes should be set to the size_read variable.
+//
+// [in,out] data A pointer to an application data specified by
+// yaml_parser_set_input().
+// [out] buffer The buffer to write the data from the source.
+// [in] size The size of the buffer.
+// [out] size_read The actual number of bytes read from the source.
+//
+// On success, the handler should return 1. If the handler failed,
+// the returned value should be 0. On EOF, the handler should set the
+// size_read to 0 and return 1.
+type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error)
+
+// This structure holds information about a potential simple key.
+type yaml_simple_key_t struct {
+ possible bool // Is a simple key possible?
+ required bool // Is a simple key required?
+ token_number int // The number of the token.
+ mark yaml_mark_t // The position mark.
+}
+
+// The states of the parser.
+type yaml_parser_state_t int
+
+const (
+ yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota
+
+ yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document.
+ yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START.
+ yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document.
+ yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END.
+ yaml_PARSE_BLOCK_NODE_STATE // Expect a block node.
+ yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence.
+ yaml_PARSE_FLOW_NODE_STATE // Expect a flow node.
+ yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence.
+ yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence.
+ yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence.
+ yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping.
+ yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key.
+ yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value.
+ yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence.
+ yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence.
+ yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping.
+ yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping.
+ yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry.
+ yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping.
+ yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping.
+ yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping.
+ yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping.
+ yaml_PARSE_END_STATE // Expect nothing.
+)
+
+func (ps yaml_parser_state_t) String() string {
+ switch ps {
+ case yaml_PARSE_STREAM_START_STATE:
+ return "yaml_PARSE_STREAM_START_STATE"
+ case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE:
+ return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE"
+ case yaml_PARSE_DOCUMENT_START_STATE:
+ return "yaml_PARSE_DOCUMENT_START_STATE"
+ case yaml_PARSE_DOCUMENT_CONTENT_STATE:
+ return "yaml_PARSE_DOCUMENT_CONTENT_STATE"
+ case yaml_PARSE_DOCUMENT_END_STATE:
+ return "yaml_PARSE_DOCUMENT_END_STATE"
+ case yaml_PARSE_BLOCK_NODE_STATE:
+ return "yaml_PARSE_BLOCK_NODE_STATE"
+ case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE:
+ return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE"
+ case yaml_PARSE_FLOW_NODE_STATE:
+ return "yaml_PARSE_FLOW_NODE_STATE"
+ case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE:
+ return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE"
+ case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE:
+ return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE"
+ case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE:
+ return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE"
+ case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE:
+ return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE"
+ case yaml_PARSE_BLOCK_MAPPING_KEY_STATE:
+ return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE"
+ case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE:
+ return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE"
+ case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE:
+ return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE"
+ case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE:
+ return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE"
+ case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE:
+ return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE"
+ case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE:
+ return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE"
+ case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE:
+ return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE"
+ case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE:
+ return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE"
+ case yaml_PARSE_FLOW_MAPPING_KEY_STATE:
+ return "yaml_PARSE_FLOW_MAPPING_KEY_STATE"
+ case yaml_PARSE_FLOW_MAPPING_VALUE_STATE:
+ return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE"
+ case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE:
+ return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE"
+ case yaml_PARSE_END_STATE:
+ return "yaml_PARSE_END_STATE"
+ }
+ return "<unknown parser state>"
+}
+
+// This structure holds aliases data.
+type yaml_alias_data_t struct {
+ anchor []byte // The anchor.
+ index int // The node id.
+ mark yaml_mark_t // The anchor mark.
+}
+
+// The parser structure.
+//
+// All members are internal. Manage the structure using the
+// yaml_parser_ family of functions.
+type yaml_parser_t struct {
+
+ // Error handling
+
+ error yaml_error_type_t // Error type.
+
+ problem string // Error description.
+
+ // The byte about which the problem occured.
+ problem_offset int
+ problem_value int
+ problem_mark yaml_mark_t
+
+ // The error context.
+ context string
+ context_mark yaml_mark_t
+
+ // Reader stuff
+
+ read_handler yaml_read_handler_t // Read handler.
+
+ input_file io.Reader // File input data.
+ input []byte // String input data.
+ input_pos int
+
+ eof bool // EOF flag
+
+ buffer []byte // The working buffer.
+ buffer_pos int // The current position of the buffer.
+
+ unread int // The number of unread characters in the buffer.
+
+ raw_buffer []byte // The raw buffer.
+ raw_buffer_pos int // The current position of the buffer.
+
+ encoding yaml_encoding_t // The input encoding.
+
+ offset int // The offset of the current position (in bytes).
+ mark yaml_mark_t // The mark of the current position.
+
+ // Scanner stuff
+
+ stream_start_produced bool // Have we started to scan the input stream?
+ stream_end_produced bool // Have we reached the end of the input stream?
+
+ flow_level int // The number of unclosed '[' and '{' indicators.
+
+ tokens []yaml_token_t // The tokens queue.
+ tokens_head int // The head of the tokens queue.
+ tokens_parsed int // The number of tokens fetched from the queue.
+ token_available bool // Does the tokens queue contain a token ready for dequeueing.
+
+ indent int // The current indentation level.
+ indents []int // The indentation levels stack.
+
+ simple_key_allowed bool // May a simple key occur at the current position?
+ simple_keys []yaml_simple_key_t // The stack of simple keys.
+
+ // Parser stuff
+
+ state yaml_parser_state_t // The current parser state.
+ states []yaml_parser_state_t // The parser states stack.
+ marks []yaml_mark_t // The stack of marks.
+ tag_directives []yaml_tag_directive_t // The list of TAG directives.
+
+ // Dumper stuff
+
+ aliases []yaml_alias_data_t // The alias data.
+
+ document *yaml_document_t // The currently parsed document.
+}
+
+// Emitter Definitions
+
+// The prototype of a write handler.
+//
+// The write handler is called when the emitter needs to flush the accumulated
+// characters to the output. The handler should write @a size bytes of the
+// @a buffer to the output.
+//
+// @param[in,out] data A pointer to an application data specified by
+// yaml_emitter_set_output().
+// @param[in] buffer The buffer with bytes to be written.
+// @param[in] size The size of the buffer.
+//
+// @returns On success, the handler should return @c 1. If the handler failed,
+// the returned value should be @c 0.
+//
+type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error
+
+type yaml_emitter_state_t int
+
+// The emitter states.
+const (
+ // Expect STREAM-START.
+ yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota
+
+ yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END.
+ yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END.
+ yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document.
+ yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END.
+ yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence.
+ yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence.
+ yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping.
+ yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping.
+ yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping.
+ yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping.
+ yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence.
+ yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence.
+ yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping.
+ yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping.
+ yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping.
+ yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping.
+ yaml_EMIT_END_STATE // Expect nothing.
+)
+
+// The emitter structure.
+//
+// All members are internal. Manage the structure using the @c yaml_emitter_
+// family of functions.
+type yaml_emitter_t struct {
+
+ // Error handling
+
+ error yaml_error_type_t // Error type.
+ problem string // Error description.
+
+ // Writer stuff
+
+ write_handler yaml_write_handler_t // Write handler.
+
+ output_buffer *[]byte // String output data.
+ output_file io.Writer // File output data.
+
+ buffer []byte // The working buffer.
+ buffer_pos int // The current position of the buffer.
+
+ raw_buffer []byte // The raw buffer.
+ raw_buffer_pos int // The current position of the buffer.
+
+ encoding yaml_encoding_t // The stream encoding.
+
+ // Emitter stuff
+
+ canonical bool // If the output is in the canonical style?
+ best_indent int // The number of indentation spaces.
+ best_width int // The preferred width of the output lines.
+ unicode bool // Allow unescaped non-ASCII characters?
+ line_break yaml_break_t // The preferred line break.
+
+ state yaml_emitter_state_t // The current emitter state.
+ states []yaml_emitter_state_t // The stack of states.
+
+ events []yaml_event_t // The event queue.
+ events_head int // The head of the event queue.
+
+ indents []int // The stack of indentation levels.
+
+ tag_directives []yaml_tag_directive_t // The list of tag directives.
+
+ indent int // The current indentation level.
+
+ flow_level int // The current flow level.
+
+ root_context bool // Is it the document root context?
+ sequence_context bool // Is it a sequence context?
+ mapping_context bool // Is it a mapping context?
+ simple_key_context bool // Is it a simple mapping key context?
+
+ line int // The current line.
+ column int // The current column.
+ whitespace bool // If the last character was a whitespace?
+ indention bool // If the last character was an indentation character (' ', '-', '?', ':')?
+ open_ended bool // If an explicit document end is required?
+
+ // Anchor analysis.
+ anchor_data struct {
+ anchor []byte // The anchor value.
+ alias bool // Is it an alias?
+ }
+
+ // Tag analysis.
+ tag_data struct {
+ handle []byte // The tag handle.
+ suffix []byte // The tag suffix.
+ }
+
+ // Scalar analysis.
+ scalar_data struct {
+ value []byte // The scalar value.
+ multiline bool // Does the scalar contain line breaks?
+ flow_plain_allowed bool // Can the scalar be expessed in the flow plain style?
+ block_plain_allowed bool // Can the scalar be expressed in the block plain style?
+ single_quoted_allowed bool // Can the scalar be expressed in the single quoted style?
+ block_allowed bool // Can the scalar be expressed in the literal or folded styles?
+ style yaml_scalar_style_t // The output style.
+ }
+
+ // Dumper stuff
+
+ opened bool // If the stream was already opened?
+ closed bool // If the stream was already closed?
+
+ // The information associated with the document nodes.
+ anchors *struct {
+ references int // The number of references.
+ anchor int // The anchor id.
+ serialized bool // If the node has been emitted?
+ }
+
+ last_anchor_id int // The last assigned anchor id.
+
+ document *yaml_document_t // The currently emitted document.
+}
diff --git a/vendor/gopkg.in/yaml.v2/yamlprivateh.go b/vendor/gopkg.in/yaml.v2/yamlprivateh.go
new file mode 100644
index 0000000..8110ce3
--- /dev/null
+++ b/vendor/gopkg.in/yaml.v2/yamlprivateh.go
@@ -0,0 +1,173 @@
+package yaml
+
+const (
+ // The size of the input raw buffer.
+ input_raw_buffer_size = 512
+
+ // The size of the input buffer.
+ // It should be possible to decode the whole raw buffer.
+ input_buffer_size = input_raw_buffer_size * 3
+
+ // The size of the output buffer.
+ output_buffer_size = 128
+
+ // The size of the output raw buffer.
+ // It should be possible to encode the whole output buffer.
+ output_raw_buffer_size = (output_buffer_size*2 + 2)
+
+ // The size of other stacks and queues.
+ initial_stack_size = 16
+ initial_queue_size = 16
+ initial_string_size = 16
+)
+
+// Check if the character at the specified position is an alphabetical
+// character, a digit, '_', or '-'.
+func is_alpha(b []byte, i int) bool {
+ return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-'
+}
+
+// Check if the character at the specified position is a digit.
+func is_digit(b []byte, i int) bool {
+ return b[i] >= '0' && b[i] <= '9'
+}
+
+// Get the value of a digit.
+func as_digit(b []byte, i int) int {
+ return int(b[i]) - '0'
+}
+
+// Check if the character at the specified position is a hex-digit.
+func is_hex(b []byte, i int) bool {
+ return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f'
+}
+
+// Get the value of a hex-digit.
+func as_hex(b []byte, i int) int {
+ bi := b[i]
+ if bi >= 'A' && bi <= 'F' {
+ return int(bi) - 'A' + 10
+ }
+ if bi >= 'a' && bi <= 'f' {
+ return int(bi) - 'a' + 10
+ }
+ return int(bi) - '0'
+}
+
+// Check if the character is ASCII.
+func is_ascii(b []byte, i int) bool {
+ return b[i] <= 0x7F
+}
+
+// Check if the character at the start of the buffer can be printed unescaped.
+func is_printable(b []byte, i int) bool {
+ return ((b[i] == 0x0A) || // . == #x0A
+ (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E
+ (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF
+ (b[i] > 0xC2 && b[i] < 0xED) ||
+ (b[i] == 0xED && b[i+1] < 0xA0) ||
+ (b[i] == 0xEE) ||
+ (b[i] == 0xEF && // #xE000 <= . <= #xFFFD
+ !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF
+ !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF))))
+}
+
+// Check if the character at the specified position is NUL.
+func is_z(b []byte, i int) bool {
+ return b[i] == 0x00
+}
+
+// Check if the beginning of the buffer is a BOM.
+func is_bom(b []byte, i int) bool {
+ return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF
+}
+
+// Check if the character at the specified position is space.
+func is_space(b []byte, i int) bool {
+ return b[i] == ' '
+}
+
+// Check if the character at the specified position is tab.
+func is_tab(b []byte, i int) bool {
+ return b[i] == '\t'
+}
+
+// Check if the character at the specified position is blank (space or tab).
+func is_blank(b []byte, i int) bool {
+ //return is_space(b, i) || is_tab(b, i)
+ return b[i] == ' ' || b[i] == '\t'
+}
+
+// Check if the character at the specified position is a line break.
+func is_break(b []byte, i int) bool {
+ return (b[i] == '\r' || // CR (#xD)
+ b[i] == '\n' || // LF (#xA)
+ b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
+ b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
+ b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029)
+}
+
+func is_crlf(b []byte, i int) bool {
+ return b[i] == '\r' && b[i+1] == '\n'
+}
+
+// Check if the character is a line break or NUL.
+func is_breakz(b []byte, i int) bool {
+ //return is_break(b, i) || is_z(b, i)
+ return ( // is_break:
+ b[i] == '\r' || // CR (#xD)
+ b[i] == '\n' || // LF (#xA)
+ b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
+ b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
+ b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
+ // is_z:
+ b[i] == 0)
+}
+
+// Check if the character is a line break, space, or NUL.
+func is_spacez(b []byte, i int) bool {
+ //return is_space(b, i) || is_breakz(b, i)
+ return ( // is_space:
+ b[i] == ' ' ||
+ // is_breakz:
+ b[i] == '\r' || // CR (#xD)
+ b[i] == '\n' || // LF (#xA)
+ b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
+ b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
+ b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
+ b[i] == 0)
+}
+
+// Check if the character is a line break, space, tab, or NUL.
+func is_blankz(b []byte, i int) bool {
+ //return is_blank(b, i) || is_breakz(b, i)
+ return ( // is_blank:
+ b[i] == ' ' || b[i] == '\t' ||
+ // is_breakz:
+ b[i] == '\r' || // CR (#xD)
+ b[i] == '\n' || // LF (#xA)
+ b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
+ b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
+ b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
+ b[i] == 0)
+}
+
+// Determine the width of the character.
+func width(b byte) int {
+ // Don't replace these by a switch without first
+ // confirming that it is being inlined.
+ if b&0x80 == 0x00 {
+ return 1
+ }
+ if b&0xE0 == 0xC0 {
+ return 2
+ }
+ if b&0xF0 == 0xE0 {
+ return 3
+ }
+ if b&0xF8 == 0xF0 {
+ return 4
+ }
+ return 0
+
+}